Your IP : 216.73.216.86


Current Path : /home/emeraadmin/public_html/4d695/
Upload File :
Current File : /home/emeraadmin/public_html/4d695/python2-docs.zip

PK	%�\L�Zs��html/_images/logging_flow.pngnu�[����PNG


IHDR��I�sRGB���gAMA���a cHRMz&�����u0�`:�p��Q<�nIDATx^�M�fG��	��m��i����GmZ��lz!jd��aJ�&e�B�1Nޤ!yk�4N�µH��18���	-�01xD�
�a�.��U4����A����*]U����u>"Ή��!I��y�D��x�s=����g?��@����/��������?��?������_|�ɓ'��3�O��}>����H1s@�@�>���W^yE�}��z��O>�4�	|
���)x��w��ys�ߒX@��B1��!��g���!O���@1�%E9@e��?�裏�1��K�{P4���Z��M@
b޻Uڃ �_%�bfF�M���G�}�z@�j%��_����(�Z���@1��D�V	h���q@��!�c>;�f&�b���*#@se�9hVg��* ��^�i�$sI��}<��c�Y	X|d��� P���,_j߇�yδr�Q�i�s!�T[��2ʱ�����cMKG W��i� sA�T]�+�Jҥ��P��� �lP��PR�^ȕ�i�)I�\�.uO�\Ǐd%�bΊ�� @��i�4si��,☏�O��	���#���P̥	S�P�{P������cO�E���`�ҒP�%�R�^P�{���c����N��������RȕQ�,��Iż'm�ڟ�2�gN�E	�����r�+�O����(O�*1�Q�%�R' �BP̅�Rm9�+������	�Y�Ŝ�)5�D�\5��d �b��*�%q�(f~0�C�0��W_}��?_yk;5,�c}<�8=��_TU!�+L�Bż��Bż�L�� p�b~�7^~����^{��r�����^��}z&c���B(�
��@1o�ǵ�@1�ew&Џb.�����K7M�����w���ܰ���sv�TX�@�� *c�[���K1+�A��ǣG��y{��r!����.��*>f����ҋ��|�avy�ʵ�%�Ǹ�c��<�Q��?�<mB���x���Q�����O���}�_ԉ^���S�re�᥹a	��{��ЗM�+�<�p�ץ���z��~JQ��;w�H5Z���r�h}�4��%Ζ�Ϩ
Gmz�?%dC�ꅕ�Ŭ���ª'��D%��Y�-��5�0! KL �l��pqY;xinX(沟djo��2����s,�h���;[=�xէ��.)ZWx�|����!!ki�w�+��٩G��b��XWŲB����e4qҵݾ/��8�SL��@1�vK���<ڍ��֫��pS1��|��S�<�vp����"�i�E�r6*#�ˎ��8vI�e?�nD��	�\>���ƚ
@1s{���P�5ߤ���.Ŝ�{�^�Zud�C�k�cNc:|]1�-�7�?�B�*���vNT�uŜ�~�d�M�����Cd�c���Ōb>����[�@�ܥ*��SG*f	�X]g�(�h'k�`�th��J_���=�h�5ϖ�ϷE����h�^qx�~W��Ws��:�G]���.�(g�7�M��Ջ5�Q��
�\�-{ @��}n7��?��_i׏?��?_�Q���T�����V��댣�C;:�Wgt>�gw�Ug�O:��Fu�""|a��۝\�3�}�ש4w�iIGK�ۯ� E��X�<�2Ṗ@1���S3ȕ��݉��_>��o���3G1ϯ32�In��k����ѝ�ۛT���|�(	���N�C�}����~F��nF�Єb� vhD��V��{����<w#\!@�T��P�ܟ �ʿ�
�V��s��j#@s
���m@1�vK��t���7��p�
��O��k��͗_���?�eχ��c�u��r�l�����װ6|�����=Y�!c���(8�n�/�UI�cop2@f<z����?��q���SC�(��?��"s
��am��?�_�/?��X��B1/%F��	t�+�b�~�?�}�۟O�����W_��ԅq>�����鵶��'�yb��t��?pC�ݣQ�7?�2�fI
�C�\��	���y�[
=�I��\g���������
8��]I[�T�v=�������-�U�e����>�x�w
�b>kC\+��.q<��l��z�Z��O#��o"��/	�{@1sρ�t�+�b���~�����k�e�T������k���u����r��YU���1lH�YlL�t����m����Y�5��ٛ��P����T&;���P̑��f2;�e��;W�n�iКn��sr;]t�S��;Lj�_�Э^w��5�o���(���0tp���SmM��a�ʵ���]�����7t;���U@�J��Y�|�y�ݜ޵��3[g�0���s,M1;ǜ$�qlԗ��N"�d�}C�ˠ�8�VI�О�L��c�<O��~��X&eµ��I�o�rdX7���o)Rs�z������D���C���l�m�b�m�Q�\ޢ�ÆpHGG������o�'Ѭ��b'j}\�щ
�_���cly�%�W|���#+��Z��b��z����ؗ���׿�#~�ښ܊�D�2��
K��Ҕ�ڴ��)fy
����Z��ס׺m���f�����m]�&;HUg	�-s�_]8�"��N�]b_�U��XR�Q��p@��_���1�A�9��!6���um@�<�����v-G1��9=���L`��؂�J�7F�}{�;�7p�e��&�L�>o�Z�gb-�������95ƫVt'�7B<��t��S����!Ŝ�%�(�k'7�oMg[��Kcg��m��\qs��&�`5��j}�!�>o��'��R��>�N�D�ʜ��͹�5��1�b��e��Sw���"�~I1+$#�,*��]˷�;W����nZ�-=-�uW�b��2�֓���u(f�TU��EI���'7��c��6��zmߊ^8���e�0���������rU�R��]�O��)��F�B��mZ�����Q��ǙhZԺ/�Cw��O�UR�] >�\�㙡�r��S��.�v�M~�u��s����~����@��2��z��r^e*ي9�S�Q�v��n�m.K%�>��|̺���觍�G���e�,�X�;�^o��pۂ���#O���ҳ>f��(O����<�;��p
>>�K�og�p�n�#�6��n����h��Esz��[��>��>t՟�������w]�����:Ψ	߮U��τ����;����q�x�n"����7v�{z&�-ւ_o=��p�n��t�+c���k�|3������1�|�3K���}[�-,�m�L���^ݎ�Lj^5�#\�>�����seL�hV߇��:�ɩ�����N5[+�(��d�b�a̰GY��›���<��D�cs�9��\.��b�,C��V�O���T[w�q�j:b�O�"Ғ֯�t1<&!�m��B���W����z(泽h�vW����1/�
�I�dcm��WH��ˋx^)<�b��Ïa
!�9��<q���bV���s��٨=Qt@�W�,Ṟ�Ej��8'��>���.�YH��X�b>��C�2s|�u2�t��(�L����HMO:%�/9��S�m�k?�0|F���?�_>9cŜ�ܣWZ���݋�nt���b��Y.Q[�s�w̫�@ߊ�K;R�� ������Ż���^��d�E�5�H�<i��i�`M�z����Q�F�s�+���^�/t���E��Y/§�3����Sg���n��%[�q��~Nwz�_�J�k�z�c8NC�^8Bcrfb��\o=��^�yOk�*3�yW(�o�|8���u������7��]�ɾ�����>$(�.[k_7;H���gV���ȋo��e�]��ӈ�c�q�S_��-�O�̈
��vyW��j�1��9=���}��Һߵ;9��8��Ս��ʸyף�!P���;�Ȟ�ΕqȽ�F��M1[O�>h���/�s��SS��i��5�[��q.^�}c���L��S��Nny�ӫB[��Hs�����u�>�V&��3a������Uޛ�zM�{ީFhk�\����K�<�
�>�E`�Dyo������N�_�4@bf%y��F6筟�j @��rv%�b��c�
��;WFC�qLSkS��:\��b>��
i�c���B�c�U/�y�M{�b.�I�ھ	���m�p*�?��N(f�P�u���r(��U����+�?`�>P̻�ő��Ȋ�{��YB�C�� :�^���VZ!�b��y s+7
�,J�\(�]	���ד5��ǻZ�I��~�-��8P/�t��Y��,;�F=�-?�u���ȕ��j��;�b�>�Κ�|���3M}�w�1Ͽy�]�� ЫbΕ�"�d��wł�'W����%��#+�4��$�g����(x�k�jrep=�@ߊY!O�9��dgz�ɛ���L$������%U̮$�ujg�w��}htÉcF1�J`XŬ;��&��{�nܚ����|���1�i�cŬ�ml��G�sd�Š���>����Jz>�؝�.U�ޒp�}��B1�{�G1�����}W��X/��S`�F�E��j�n��,�E����@}+fH#�B�5*`ݖ#@ُ�_��M|��6�Q��O�%�3PϞP�(�]	�����J�N�hՍշfߋ��?��Ż{�h�N(��"Mw���N�n���H׷�T�u��pǬ?�ܹ�bq8�#ڪ�&�U7	D���G��W���������6��?}��uhRޜ����>�^UOy�I�fWt=�aI%ȕ�l=��P�ٱ���b�3É�v��;Y�3�b��^���ʸqH���9��<T�r?��:HNt�n�A`�D*6�>��h��~e���b�M;<к{O��	�JT���;re���=j�N`@����.%@��c%�����|��Z�s�Ք�[�-_F|��×�)�c�#�C;�:�k�s�~.z����"�ż]�QC(fn[� �yp�zl�{U��g ���9�ȣ��P̋>���Ŭ�'��ٟ��:���F���]��KI,�Z|,���8��9�ң�<P��h�N�
c��O�$�g�Z p����V�%�2���X�\�Yqc����~x��6�%�zU�&JGd	�^��V�j���YHn��B�s-w���@1o��syCȕ1����R�F��>�ޣdΡ��p���o�I���,L���c���֯5(�>�S��2���5۳ҊY�%+'��'��S(T����lյ.K9b#!Q���u���]oV�%ժ6����˧��v�.�^Ϲ�Lv]�s	e���+�F;(�f�b����
	��؍is�*f	P+]��6�Nʥ:Ѿ�ͺ*�$���֙8�2�ש�>��W�Ϸ.W"�:�S��Fu���R�7���ېsE/���y	�<­��>���~ީ�N(�v�Q�Z^T1K��GQ*��8=Z6�QRzT�`;}u�R�����-��83�@_)iݟ6�Ȇ�����Y*�b�~�E�P̅>�T[��������|؁�&��ɕ]�S�+�m��4-�S5�jk��#L=��Wz�Z1_�ے�OcE�b�TŜ���zP�]�n;�b^���†�͕�P�0u@3�Ȝǎֻ�ߛ��/��ZQ���TsG���]R�g7�^��/u�6;=�d�!%�zq�&�TM.?[�s��.�+�[��E�P���h}O�se�i
mA`)���Y�Q�PP�O���:]��%}Ѻ��q���!�?��ӆ�'jHXm����봰5�j��~-�v��/U�Ɓ�J^o�:A�&�A������g�����ѡ�QX�ׅm�(�>㴻'���2���� ����Ҫκ�%s[IK�=�E��k��ɕрl�Ds�w�C`n�(��lW�.O�����㨮�hw�F'+j撣��c��?����{[��`���(8��C��|�����Ћw�}wSu\�*	�S�Uv� �s(f�AsP��
�
������ �sc:x�P̃O��O��G
���ݻw��_|�E�@�K�ret��N�A���8�re8�t9��8��TztM����9re�9���Jnf̣
�P�]�+c(Dt������K/���3��ū���b��V:��= �����/��?���������� ����J�h����yz�,s�C��_�sB)2���o�Ǭ;�\q��@P����=�P:��Wd�}?���@�4������y)f?�{��|�������������f���#��H�\;¦�|~�(�M�܉B>�(B>��5A�`��8xh>7Mi̹�R�ȕ�e��B@��G?���0�wɥ
%�%��ݻ��,̩�@^zl�m����VKm(G�\��Rs~��OZ��7ߜS�;C�
՘S�2���2jl[D@�C��%C�s�?�SA֟,H��|y�]F@���_��Enc݈''�,Ʋ�(
���\�h`�J
��C�M��Zy���@�l_(�}y��rV�rE�MVг�K�rK����K��޽(�N��ԝf_���-7��:A;C@1=��w^�\�z(O�<d˯ܱpB�̔h��t�j�Ћ+��D֟�;��[N���z����0��V�]y2��l�vwM�\]o���-��B�I�d�b�n�ѱ�	�+���4I�✙��c<���@6Η��^$Db�I����ȕ��"u�#��r0����b��|=�&�'@���L��/9͗���,�,j���N�8ffH-�N�y�k�=Y�]�@B�8f�C���'�6#{%�b�ud[ꗟt�'qH6{'U��\-Q�֑��G�V�Z(ٮ�E�Э��	�����S��n�Jdql_#���Z?K��Ĩ��i."����gB߶�+���w��J�{�ÆqG W��i�6��S)�[C�{g�:߶��A�\9(R�l5B8DD��	�����&p�v}�q��O&�O� W����n���v���2ı���A�\L����4�G�����4��}Cs��[W�K�Twʤ�C����	k�#@s}c2�E��ږ���p�\h�Ç��N�Q��bu��w���8JO_��ˌ� �
3��^顜568�mVU�c�@1g�H%	�1u�-��4�O�<�%K�7WK������F�ѧN W3� ��X�KjA�6T��}gȟ��.����XC�kr�Bm�˯?b�F���ȕ��L��*��>�:�W3�%/�j�C(K �Rh㽲-e��FV�T�
re02ȾKjf�rT'�_��r���"ȕQ+�^&�򥛛�k��!k�`☛�f�,�Kj��W̉�4���o�:�b�%�137v#����n��h�F	�#׉by�s�}�]Rs���.;��!L�*�g���;�Bm9z�����a���y��.�͝wI-ؓ�U;w�Ǵ�Y��@1G<|
V�i�v:��6���y�+#�ak9d��:i�F��Ǐ�Q�5m�2��ʍ�Bm���l��;����a+�+�������wI���/M����m--?��|?�}WN}a+��N�3�<#ku(k
)S�<4����'�pml�6��@��a�~}ǫ�%u}7�]��yk�Q��bnW��-���j�]Jzʍz��
J�w��ա�����B�reT0�0�B�t���P
����t��\pwճ��!��9M��"kf/J��	?�cw.��`A.�rۡ�\b*[��'��Ypm�)X�q�
h�^�]R�ʂ��:���ɇz`�^��>���^x�({�B��4�1)�U��(�flg�P{2��v����ΦPtGQu_��^��-��c�b�p�����.��G�;*���_�D~뭷�(�,M)��~BT8F�Lҗ�>&r9�0�A1gG:`�,Ծ4�5�6����:�Mwr-�3�O+��2�^|��2z��3뾎ɕ��,=���%5��Jrf�چ����\�駟Ω��R0o���߬*��!z)f�e���?�|����+�^�A�����\�#D
�#��fݑW�:{!�2���6j�q�6t�Z��n��z/�c4��t'o7%��W�g}K@�kre�>������g�(��J��B��9��ZIO	P�����xG��ӳ�;�.w7=z�،��O��-�E?	�
,�v~a��u1��jK��P�j�`��X���Z��H���2�
���nN�>������Nt����X�W��!WƖY��K�i��E�����GNO���(�zjU�0��9FP��-:����?�
Mƫ�#A��CL����3NU6(&�7C�I8�%}�����?8�G3ǿ�}\t+���=|���nC�
�ڐn��l&���X�Wyd��K�%i%'�����O���}�x��t1���gq2��b5�qS�gK���� O���E7b7����65�J�#�L�p�T��յ~���?�v�� -%Ѭ��[D���e���&?q�Z�ou��O�f�5���_�7�Xx�6�zV���H���HMu�����WN����=��	�
�}���ˤ���9;ã�W̢n/�.��w�;���G�%��K/���>�־���Z՟�h��ڒz�fI�St	�*u�}r�i+*o�SX��5Q�*����F�P
���y�&5�o5�3�N�Tktd�ɋ�N��%�~�iF�R�E)��\#�ǻYjF1g�8B%N��uN�Ez�eт�͒v`�XL���95���ޓ9�Ӯ
E��|s(�����?��h�ߒs��,��'��l��b�>57E3���ѩ���>��}�bN5�nC�^��ڲ4 8��Z�Z��Z�<
{�Y2�з��Խ�wF��H��ڷ�0OH��=J��ȅb��gD7���*Q%gd�0߉/ٮ�P�Q��	��3�N=��+c�mU��E�ess[C��g7�|�7�_��c��^
g�_>���^ЍzQ��[��K��&�fX1�/�:��}qh��M�t(k.�_�#WF�#��m^+�6�qS1�#=��9*#��Q,�Q��-�fI_e-�nqS1����u����3�PAT�	)\��/����&^{�]@w[�{�]ⶫ����kwI�
ԧ��V��U�+c;þkp^��'���n��a�c��O��`7����w�g%�f�9mnb��0)�*��l�������t��yr����2yH��v��U� :����T݉p��s[~��?�ۼ�By7��nFl�+c;�&kP|�n����U���6Dj�'vT�ފx	�;�g><��m~�tV1�,��x��9�3\>�~�b�?���])n[g�gN��1��C�)�GϹvhZ�1����6���~6�4�B�Ou�}�qI1{=��c82uƎ��u&~7Q̾�Ww(9�q=��JI�|Ū�V<�6ر
n�*3N���bܖ��|����`�uLRU�-�v���t��_"��cN�}=���O���8ȕ�}��Q�j��>�Z��ߤ|���7n��uI��C�t9�o��ۖ�@M��fz����ۥo�q�?��F+z�[��і�Ѿ���Џ�2�`��Z1�ڥ.��g�|����,����@}�nw�+c��j�	=����П�ɡ�����y�-.n�qN��.IF>��2C�<U�Q_�*�i+*��QRWH|�B
�1a�%G�ͻ��,�4-�Z闈�ڵ��|	g���K��D�+�'����i��x@6y���T�����\:�g|��F�|�����n_)��p5���ΟZ�VTL�L�>*��n�~���ڳ�
a��g	�]�t���=�\QO����� y(ө��G���=��g���#�9�m�}H���P����O���>�r]fr�,W]��G+���6L8u����K�S��Y��*zB;3�q�l��]��a��䎗X|�۳��Lv+��y�Q���}�3���<���̼��>�rXU��a�>�gsԝ���4dYJ1�o&�1Mr�Ӓ�v,�����N���?i4'�m�37�IY��w���o�
ż`O�;6`沇K���4���a�bV
�e"X�>��KZ�޴��T1�9�:Ŝ�D���ݯظ`�F	ײ;5N~�+�}�]�b��Fz�/{&��ũX�I
�(}��XFz��V�$��X7+�G϶J�H���E���lӜ��o�>?۲�@1��KM��'��:��sI1�a����y�oT�
��`��O�Y�͒��U��C�ر��[N��2ibӉ�"�
!~꓾91��R.�V9���p|�~ Ń囜�,��Գ��ɕ��(������~[��Z�5���?���/�:����aݬ��s�T_��d�_���'���ӯ��	���֕��%D��u�{��9Ζf0�4I%c���~D4���uZr���Pχ�jh�	��%]�%����k�J�6ƞ״�+q����'�f�	)	,���ڸޣ\�}���4�������Ů{(ȕ��gK�k�]$Z�˶ʷ$*1���u�.�b��w���G����<P�DH�K��˛��}�,��(��o�ј�p�J�n™%�[�~Z�JfZus�M���Y��;,מx�/献��䀓_z�59Y�ٛ6�2�2����ҖՂu/;�>9'����Ct�(�A�d���#6�e|GN}��/=�}��
�26l��c�jnڱf�"���gn��=�N�.;��Y�\�LŠ�#��n�^�t�LбC�?��c���ix:q���U�i�4���?nf
N7�珁���FWk��W����$�m�Y�����kل�6f^��Xd��8���s�@F�^#rCgǬw-�#��:�\eᜒW���d��\���0����k���4v��N����q<��3������Lj������TOG�@ݴ�^���Ĝ�]�b����2G�-[��b}f
�,�{���=)E�3~�?�e�3�'���K��s��B�-8M��xe��@�>I�U�W�_>�f�lM(�-C�ܵ�{�?esx�1X�[9|�;����X�qt���/����/���M6aHW��b�I}5�9@�h�tw2UP�|v�je��e�޵�	}�N}�i,�4���b�CvV�v����>)j�_fL�31{�&�v�=���Υ=�Z�Ss�<���2��]/�żW녽nA��W��n���~�~���)�eU(f���_����$N��N��!�W|*��R��b>�#c�y�G���8ɕ�r3�휶,}�O��z�sd�k?��Jgk�xjs��� ^e�;UW�q�$���T����^�B����D1���/Z���rS6�R�n��9�/red�	�W��e�4oI[����;b��VC�&��[]��
��[ٮ�V$�ޯ�Fv#���ܬ�7�&<I��W|�H0^G��׫�{�<���]�K�:�E$�)i�J{2�a�|���F:!��uZ�T'�nCѦ�ӏ�W	���Ǯ�zm��[����aӨ�hH��Π�$��E5��,���CO��e����43��JU3kp�Tkڣ1���2�}�ǭ�)'��'���OGٮ�d�����Ƞ�vX�g7���t����s5�>�d��
��N��$φt�+c��k���d�{�ۮ�&��`ߞR�:)vI1�֧����w�"���I���0�^&����e�04�ȲE�l W�Ɓh�rOK�,um�Ի���ڥ�lT����Q�ek���hQ[�.2cK��5t������W��Y�D�T�}zq�KI�Yޞ��u���PB1�����fQ��!Q����Sq��-m�*��!iz�I�D1��'t��Ȥ���dY�vsvU[@BG��,+ip�W;ʻ�9�4mY�6}g���C��⼻�K�_�7�S����ܷ�*��C;wբ�;��/U��k�#��q��8��S��D-�i���9��M@	�6���˜~�5@nij;p���bo���dD��\�}��슈�~�v<Fܣ�<ֿ&#O��;�RI�k����ʵ9X�t�o�}�={�v�t.�z��.d�j�{ �tZg�Wi���.�b���lqQڲ�m��h�C���7�?O�1�5گOo�g�LO��U̗BTm�&��j����χխ�sOj��]�/���K��z�JҞ�*f'�?�=%��׃�,?���S��W͜�V���kG1�F��%���M�����C��f��VG���c��-�裏��Sgw�mP�n�4�N:Y�����ݞ�j:��z��ࢽV�zD���:�b.=^
��eWV&E_��
P�]�/PɈ=��"�A�gs���L�|z�䱞�n��UszWW�ؼ�O'5�> �?�N�djm<f�[��l�|(�]9�ݢeve.j��/�&WF�V�kd��C�}���]Xj���}�UM��+B�&�Lkcwȕ�`�G^�+�O�*fiD?�ӻz!A�b�����R��r�b���s��M����7sک���LnΖ��J���I�\7? #�/{ñ�(5l�U�'(P�X���.#�<l,�n�iH�sT��K�?���L�,��w��ˡM#㧪�j���jʸd�b>�6�ͮ��8f��
��xiY��1'i
�����=��3V�\�]���0�Ϧ"���l��u��A�����&z�|�HD�k9�����v�f�n>܌��w�kfhre��v�Au���"����ELps����m��1ى-.�2;���>��U�QsYq�ڈ�s���8u;��lp
N'��:�S
�N�_K�T1��QI#{=)�y�j������'5X��
��y�{�8�G���؅��zģ߬�])WH�!��ҨnF�g�U�bU�J�X»Ls�a�*�:=�P�����k�0��?���(g;�L僚��-&w���q�.�\�ڬ�U B>N�
�O[�����q&ݩĖ،�y��l�»�]P��̕����4��+��(�$)���%A0'�^"���z�ձF\:�r�(CV�4�hy�%5G1/�ic�Wv0}�ڊ�
v��U=÷�t\��
e�����%���\�&�b��α��*��,�x2�5� �$�������?�?�C9�)f���^����[u��T���@c����ż��`W6w����4M~=#�u������M�Eoks�ا��:{�\�Go��'�H�ӡm�ͳ��J?*��B�Y!��Њ��wg��~�Zr*?��_��H��҄;��\4^w:nl������[[�,V u�M�5�+c��/�'C�7jL�����O�[�����%@�_�y�o}�[��w�֩H+fy_��xkxy�H,�XA���	4}����/g>��	�\+>P\�
~���wI�����L�	����~�w~�@r5M��\$G��D=�F�ǧgq�/���rj�&G��)��� �yѧ���	��%"N����U����k�]��?��[aq�+�qI9��i�›�8�=��o֋F]��Q��'�_��|s�P`�1ˣ,���˅2$�BO��`�b�͌bf�o'0�s�]Ih=����h��,'�n��?ơk�;��d�V��2��g�Q�y��je�2�y��^���$���M�P�ڭ�|�P{8��p3��7�.���7%t�Jve\�4��s������?������^�}W�L�>�	t�1��r�rh�	��f��܇��\���=:�Lr�i!��U�Flg�ª�G�9�	^�ާ#��؇�@�ؓ!Yٙ'C?|�)��&[�l�8��p3��Z$໙���v7�'�,Ԯm��5�������\����ddy r,/�ś���9v�������Н����������5�V�\��H7�h�PO�F�o[U_�V�u���cnk:5i�<
�oד���~��$�`�گ��?�G�1w0��va��>�j'�İp0W�fF1�2���ӿ�K���l�a�O��Pu�sG�IW��8����S'S��`��͌b�4�T3��n[JĦ�MD�ys�^�:�1\=A1�0��aG�� 7ȎsgSSs�nfrelc.^A <�.�է�
�W�l��t��ɕQ���դn�󄰡)��~���Q��ru:�ȕ�м��Ty2�P����JV�D�a�64+��F1��;�@`�����=ݚn��~�Ҷj��:{A��:�e�“���5tXaJ��4��:�k�Ԗ
�(fre�5�V�6�Ah�G~B(��`n�f�L	Ԭ��cf�L@���u���n��h������Q����hV6��[ѠJg��Ʀ׉�(��G��O���|�R�
��d����V6�:��	a���1B���b�e$�GI�d(s�nOӼQ!Su~��=J�(�QF�~�B�N�Ǐ��ڸԿp��p�)P���3�2�?
,"���+6t�m(��"�N	t��ɕ�Į��D�s%��~B�P�u%�X�5+fs#WF��gD����}��'C	:�&in/���>w��7���$�(���Y�캜ʃ'���5S�f�L��f��h��'#��ԭ��=����n3�2�Oj�N@t��S4��g��/U�'�j��d��q赡�3�2z�u��KT�9��d�'#vI�g�4tc�n3�2f�6E �M��HP��wh�'�;@>�	�i�y[<;�Лg�WP�}�'����.	y��WV�=�ٕ���,s��K�v!�N�n�ڻt�F�@1��K�H
{�W�2OG�n5+fre�0���|OF�p�~�
ٓn3�2���MvZ�
�ȵ�zϐ�&qwgtٰ͊ɕ�ݤ�C�=%�v����u��{$���6����B)v7�u�f�L������YOFѴt�o�@7��\��=�Q��K��R�,��	Ԭ�ɕ����_H=�l}��t��ɕ����� ��������O�/?cR�9�R�(�z�K:$ O�o��o�[��m{�!v�%s�K�Z"�'$�q�L�7�vF���Z�5��(�ǟޗ'�������BcP̍
�K@�W_y�e�8
��Bz��/z6�@͊�\���B�@1W>@G�׍b&W�QS�v��F'r$+�ćj��Yk��~�	a^���V�b6Ure�;����P�̃��Q̌/�!*�������n:HG��Y1�+c��rm-P̵�Devt��ɕQ��œ����O��뿾4���V��z5+freT?}0p�H#�F1�+c���u�->��"�[Cż��@`>�|VC�D15�t�!(�kOSQ�{Ҧ�	��G�}F1πD@�|���Y1�+�������o�n3�2���v����n�Y͊�#WƦ���	���:
�F1׉� ���y5��/�Y1�+��7J�P̣���~v��ɕ�p�)^;s�#t�}5+fre4)h6+sV��T֍b&WF?���|M��D8K��Ā@Y�b~��=z�}���/����\�j�����a�(����	���(K U̟~��$�|rn��^KtY;��2(��s ����
��ɕ���$*�7ސ�Y{����‡���֡>#߳����}Ht��ɕ�������՝�}��#�2r�5�C�4�ٱr6��zV��L���E��8`㭷ޒh>�zZ-F��\�C��b�ꫯN��30G�Z�b&W�ѳ��s8U̎�_�ű��]X�ӧO�{�R�‘�ꨈ@7��\�*L�A U̓P:UO4]�M�Q�b&WF�S
�'��ʘ,��8N{��r�+Z��ͫn3�2�����h��t�����}��N��#0G1K"+��6I(��4K4�g1-�Bżf��b�q�~��4�N�u^wo�/%�f��t��W���!��	�Q����F�{�^���;�\˺)���a`�7P���I�T1;6#]�-��Q����r|(�Ν�Vl�9����Y1�+c��raE�*f�+R+����u�
_��U��\Q�0e3�n3�26�*����\��C���r��No�u�
k6�Y1�[���0�\Z���`j4��\#\l��g��Y�D1�]�Ҷ�YO��l�ҊԬ�ɕQ�D���P̫�}a7��\}O�{7G1{��xT�F�ʱ�D>�4!Ҁ��r͊�\�ͷ{�bq�g��L���M���Q��4���x��8�Y�q�-��[Q�3 Q��7��RsϣK�Z&pV1���D�X~�tC���Ls���vs��J�*"�b�h0j2�\�h`�!�.�̆�jV���`�@���(�C7��\fUI�|$��ۮY1�2*�>�6��y��t��G<��5s�û�s5+fre�W��������ʒn3�2��W���y;�.k�Y1�+��)7\�P��
��w��ɕ1o�)�s3C���(�}y��xP�����ga�v'�b�y
���'�l��{�w'9>|�b/��s!�T��P��zy͊�\�κ����/Z3?��3
���t��n3�2n
5�7F��؀�en͊�ȕ��\���͌��ݶ��F1�=X�(f&�Y5+fre0i{  73�2w�Q����=5��0�Zy�O��?y��g�E����+#P�b&WFe��As~�h!��ǿ��������A���y�س��(fre�<M��[��)���ݻ���	������@~�W*8����n�P ����(檆c `�m�̊�����-b�ҡ�d�/��n�c(�
�� `7�o��o*�h���yjV��ʘ7���@Ōb���эb&WF��ۖP,���S���?����?��ɓ�5P�W5+f3'WF�s�x�P�(��lC�(�
����G?���|���2����Hg>�裊Ŕ�Ԭ�ɕqФ�Y3���܍b&WF���fP��<�o���ir=Ey饗�ݻGN��0{-V�b&WF��n�~��Q�;M�U�t��ɕ�j���
��2�Ÿ.������oKR�b7v�Nż;r܋�ż�\[��y
5��@>z<�0������g)5UA�\�0`D	(fs�y��Ns.���V���~���	�X���KjV���hzjo<��|�,�lA7��\5O3l;%�%.��w߽��^	Ԭ�͜\�ν�B1���O�

t��70�R�J o�4�Ʈݠ��Ԭ�ɕqФ�Y3���܍b&WF��ۂ��o�]"���4^���7��&P�b&WF�s�x�P�(��lC�(frel�\�eSVz����O)���PY�O����C�؅�y�4r3���y7�M�\R���ZzT�<ʒ�;lA"�,�,ݬ��k�庪	�����BŌb�2J_�b.M��'�
��_�r����vV���5�l��v P�b&W���&�)��?�����z�7ff񬁲�!5dm
�J�Ѝb&WF�B�K	�^'��
�˅a\7IA�[[ɞ	�X:v5��Y1��2j�?U�VH1?z���_�R�zq������}U���E���ڡp7�yV4���1@���]���� Pk
��n����@͊�\�O���+���>}*�����^��u,$�Q���upU7��\���`�*�rU
��ޅ�3�2�mPB1K.+#��駟�Ϗ?�XoI=�П֯�����[.�?}�*.o�m׵�*�s	�[��F1�+c�4��,"
�0��p���4�4/��P	�y�Q��%�n(��N�[�9�W_}�zm��d�4�/qD�^��Y/"�#}�q�P�af�
Ŝ#�N���vv��q�鑷�(�<��";+��p|�հ�g��/a力���./=mGu�Ŝ���P��R��Z����^v�k��5+fre4:�j1��bV��$�X���\g\,��UF:XjXA�>�T1
nF1�2/iG7��\�M��iz�%�V&��;��0��c͊�4ȕ������9��&Ia�`��Hs�:P����4��������~�3��&��߸4x(�ڦu7��6���7�nv��������w5+fre�4��K	Ŭn8jB�V���:�*f��|�p/�s�����>��]�6\�+m���9#�,Uu��ɕ�e>P�Mz��s���|�p�ّ�y�-	�R��5+freT>yj7��bV�%p�	�/��>�4#ih	��dz&��d�>�3#bsF�Y��F1�+#�|����3NY-��oOiH4k7o�	�5@1�<:ض�@9żɬ�.F1�b�(��F{�$�0ݾ�/I߂RjL�4��w���U"�bftKŜ-�����b�mD��6
ZP�t��c�f[	{�_�쭰�A�[�a�:kV���(:�W�bF1�<˻Q��ʨy��k�}�
�h��,�j��:8�^U�b6re;CnŌb�y�v��k��m-�d$�Wq���_�v�s�6׬�ɕ��r3����x��n3�2j�fm���
K�b��,/a��Rz�
R�Ҟu֬�ɕ��L谭���;]��k�6N�^+��${��'�N'�[tǼ���Q����a�����ώ��O߽{�M�psÄ�k쯘S+�wy�ݷ���~�U�g�ڭ�y7�4T9���9@����=~�� ����@1�cK�ȥ���dlb�ާ�����?��I�{Nw��f%>������:��$*�f(Kᢘ�+]�\�0��O@~S�!VԲb��X�������.��\�z͊�\+�K�!�E1[�j��w�
���^x�l�`���ׇ�ҟV�R���ƶخ�� z7�P����ܹ�JTƛ�7�F1w0ѻQ����`6�����
9��F���4t�E�]h�����+���u��Y��i�ƌ@�ԝ콯���e�"�r�P��V��p�N��:O�u�b�"�|����|7�9���n����=��mc�<So�f@�$H#�Y�Ԭ�ɕ1k)t�@.�,�MXצ�VB6s��
�k���O��g�N�����ss��L��>&�>�����7�7%�#�m���p䛞��y���}5\�Y]O�7�i������
�8�)_yq�,��`y�*9jV��ʨd��jFŬO�B,��1ֻq[L}�Aʑv3���tU��Ȥ�x�uJm�d��U��8l>�V'ebw7��\��� ����Z���s���C����W�G�y����ޖDI��Q�����
�E����J��e*J�1��:KN���wk=֢��,�L`�b�[�^�׭����֩V�ү�0�vv�_|�]�.t
V�^M������2�8Zw�/�
�s�rDu(�#���1E��Ž"�H�X�a���R+}2M�y�X\��Z�y��uc��l�C���U��N�Mڊz��$�-g
����LZq��u���uaG�o�Q.ꑿO��lJ�Ws��3y���b�2MC`�b�=.��V̾����>�֯�g�>S��
����^��Q[>���9���!����	�\3A�Vżj:����r�j�Z8A'�9l�Φ�|����^�>��D���Iל_��'��'Tz߶1~���m�j�$=m+걣Dm�6�u�T�(q���J�W4�۔|a��UX.|�fmx�pol��&]
P'�N��L<Y��sy͊�\sF�2	,U��Q��kQ��#���D1o�W��n3�2JL��lh�@�K�9�V���pD���հ�D8r��5k�	�ppċ(�g[�b>
�=�VT�:S‘���
����F�QW��(�aV�ộ(f���_Mg�Ӹ��j�]�M/��R�[�s͊ٸȕ���.�S�^��{>��ż�^�k�Q�%�Pg�����<���%Ŝ��X�n�o%��cV��s?�Z{�W(�-N�bhζu�����TV�PG�L��}�J�;�}�Z+�0 �d�xG�FS��3�T1��q���x�^��3X�b&WF�̃�/���ت�Q̫����L�������cW�K	�'B��B&��'�,-1}L�X'>;b��T�'�n��϶xV�^j�T1�Q����I���K�
�������k�����mM���9�]/������ǚ3�2��ݶ�bN��\�D�F1�+���u�=
���3y7�oJ�JCG�:!M+�㉼��INم�>FrO��*�Hm�Ҹ��-I-a�ų��R[��Yg"#*�!O���k�X��O�z���
Ґ��Y���S�kC��C��k����\�ܢ�(�E�(�3���b�yt�m)-8S�8->���F��](�w���G�b/�X�&�?u.�r/<u�FƷx�
\��
�-JÝ�b�m˦���ǵ%aU�/�~9��T1�'��XJ�b� J.K4K:K@/��;
��`+��㨌݌D1��&�bF1�=疴�b^B���P�ai�YA��Q�>����ْ���Eg���o�lə��3Ӽ��
�P��B5q�pJ�f�L���&(f�	T��n3�2
ϔz�W���I���7�5wx�<^
�i(H��A�Y1�2��0-�bF1�<_�Q�5Cƶr��Y��[�f��U�F�g�쬰�3�2*�0-��bF1�<_�Q��ʨy���͒�޽{Y�0JXH�7	(�\?x~�( �LڋG�&�C
�+��4�bF1�<��Q��ʨy�����e�_�r�܇�����[��?��L�H1�6	ż���VP�(�'7�������]�����b'�o��I���h�Q̍\-f��Q̵��sv��kl�C�{�)m�"s攟�q*��^J�v��I��'R�-��R��:��ȝw��J.;U��b��0c�T�re���&P�(��w7��\5O�lS�2��{�)�n�׽b��
DV�+깾Uފ�uɢtog
�\H1�^�D���&�"WF�T��(fs���6u��k��m���Y��Ei˼m�����I��q��[���
�m���/�~x>��/�W�U,��$�U�q&5#.w�g�r��3P�e7�Vb��Td��;w�x�3���z�X�a�F�0�}>�B����4��\�<�F1�+��i��mKsh��Y�R2�k�B׆��
KMJ
�Ll�lq�3�֛E�p�|;}�[^O��t%��v�5�}�5��٫\�����~��Q��6u��L}̮$�J�,��91��3���'@�̻jQ��g�=|y�?��8�=6�v�oW�nvg�Q��ʘ=�C���9�^D��o��N
5y��wC1�.z�$�y����LN�JGK���KWY
��ĺ+��U��JO��|��^���A��!>o��$�y��.�Y�z�T�����f�Ǡ�E(S�*(�Uظ�3�Ls�<	�MUr�vl��R�<q٦��g��>�=U�0��z}��[vK[L�Ǥ��&RA�R�i��k�C��Dsn��wk�#Z�ͪ	�����L@K�^y�+{˅��TM�sák�*�P�*�Tk�5˅�EL��*�37�R︚��yR^��!v��G�1��HqS%��GK0ًq��m�re�7fX|J�̬8K��L�f������̋�BNz�.^I���K���UI,<U�Q���$��.�d����Y��r��qt�]����^/h�Iv�_��5Wrz(ٟ2dk	&�0��H�+cء��(�N2w7�Q̹�P_o�e�2i�n�!�,�O34˟�2:�䦗�IpK�Z����Z1�Q2�����[v�p�V:�,x��RM/������;z!�U�da�:b��^�OT���\%��ͽ��3��2�q�T�P�u��a�u��ɕq�j�����˦�m�X��W�(��:��a�h�:j!@s-#�[������n3�2:��ٻ�=�e��b7�2g+��0���Ç���*<���@�4���9ʾ*B1�5��f.ie������^C�_%�G�
��*�@@P�L���{�}@1�J����ݻw_}�UEk4ct�*U�~ohIe�`EȕQ�0`�F(�{���L��^����Z@�h]`7AE�)JZY��(ʹ��ɕ���a��	���g	t��_l! �,��֮5�4U�g���?o2�dy��a�%��ָ䳳�Bre�1����<���n3�2���	���-E���x��:��ގE5�/
¾����{ٱ��bk�g���L���cN�u�1��RXD�c�-]�m���<�һ�3J�,�"��+�V̓�g��[=�D��F7څ(��F������ͽB1oFH}P�a��w�yg{�)�A���w���:��a���x�>��f�V̾�{�ݹsg�ٵ���n�j�ҲHVFf�9B%(�F��>����U=D1���ECP�ƽ{��ob'��Pc��jY�^	��qZ�e���9_ v��
�N{i��ĝ,g�ޝh���N�H\Q�B�\�t��D1w>�k�׍b&W��)�u7h��f�:5D�d	Y���g���<29cM�*�S�}P����+X��Z��/+ p�j��X��� �b�b�3��\Z,��o��z�T1�b7�ã͏=J}�rN�T��^G?v�}]
\52re�<������Xf�I7��\Y���!�9&O�27����%��
y�\�#�(圞Qa�;���Ţ�4��ҋ�sa�N)��;�0V�� ����s�X��(fre�Ty�������^���+o���dMV�NJ���gT,�D�eۤ?���:HڇΤ�Be��2Ge�f���(v�����s�X�(�P��ʡa��zW�����B=�@�]�rP���R�~P��n�%sSÅ�p�t�v��J�+�t���F� W3�(�F�@�Q���(0;��6�F}���+���R	�+c!0�WF�\ـ�bN7����1$�+�Fq�N��({�!��k�+c
5�������Ğn3�2*�QÚ��ѕ�p����;�t�&�o"�@P�
�&v��ɕq���)�3�!�P�-������L�\��`�\(湤+�bl�����XQ•왧0eY޲g��h�(�.�q�N��������(A@A��J7k���ϩSA��WV����)Ol$@�����
(�*��>#�Q��ʨora�Ϸ@�{���4��3�^WN��ۥ9�+�9�6s��W�ns1BT�������ڻ�u͸^1���ʵ�Os3,��(ȕ1�H��Os�㻺w�(fre��\�=�V�9	Y�+ל�����ߥ]�S���,L�H���8K��L�fx�B�f,�G��O�%�b>�?��!�b�ñ�ZP��
)���~�)H#c���Q��ž����cO�����&sW�Ig�!�eeށ+�!��� W�~�i�s9�M�܍b&WF��pL�#��R&/%PC���6S~��d���&��ۡ�ֱn�6\
��H.+e�F��!�0p4\re�7&X���y9�!��F1�+c���o'���B5�w��]��z��q�`Q�Br`H.��C/��6����t�@7��\L��	�W��jQ�� 
�a(��ޕ����b�P̽��(��S�g�y��/��l�xS�D175\�?E�+HC�[����}[het�n�=l���١��_��‚Y�	�@ %�bf>@�B��Z۝H"+C;�h��T@Wh0&A@ȕ�4h�@��q07?��;Ѝb&WF�A}P����<�쳊8:������XB���px\}va��Q�s�y @t~�TY��2
¥������V���
�B��L��V�v�'�b�ϊ�5 ���Q���4�_��x��׵�D���ŕ��F1�-���t�g�j&A[P�m��~C 6��lDJZ��Eh�!)���i�j	���;K���h���)�i6"%��[J��d�0:+sV�T��P�9iRWy��(Ϙ��P׳�ǬMY�q6U~Vs��j�(freT=�0n�*l\t0re<4?��t�M�$�OS��i�2��F1w3"tA��dh��2��q����x�tS(��W�Ƹ��y7��\��n��b�vh;�q̝lG��PJ��zS(�
'l&U~G�bVW�Q�h�Y�M��0��.����IP/+]y��(]E�nT��²P�L
TK@��"�Z�0(f�D�
ES���f]%�bf�@�Z��߻w�Z�0��`JTG�􊽥+��A�	t��ɕ1{�)�s3C��	re0� �gV�9Yꪀ�t��70�RTJ�\�`���`j�B@{���ȕ�Pj�t��ɕ�api�P̕f] @3S�x��Z{�����n����L�Q�d�4#��"(�Sf@1πD�b�C+?�ψ�4�52�b}���Ek̺�B-@1�0J�8(��l�Q��]��kWe��M���|��vkg������,I	�������ڡ���ȕ��8��1K++��!a�;���vTD�B�@C�Y	t��ɕ�u^PYP�UF,$@����(�����j'�ʃd�R��o��q�n�(F?G"�bi�{�+�2z�&��[�!҄�2ҾpiT�o��vv��ɕq�D��P�%�Rg9�1�cK��h:>XA��[3�f�F1�+c�S�!�������O?�ꫯ���J������/�0�7��������k#v��(���Y�,�|�Ν��z+�����o��ƈ��seP̕
HG�D��n���7����_WP���%,$pI1���矻>�B�/E�\��^��0����Ҵ�7���iu��Q���X=��Z��$�G�^{�b~�������_�7re�=���NI0���_���i�v(��+�:��,M-&Ѝb^�s.�@��(f���>f	e�8��׊o����ret5��vF�d��� r0k�>�K.K4k�B}��i�V��F1�+c��S�~��V�:6ÊYZY/�S�4�\�wf!q̝
�a�Q�8����a\g����O��a�i�2�n3�2������_�f�U���G1�7%*����j�<�ah��K2��U�?�_(�,Y���d"�y�Ѧ�������e�ΐ8v$F���k�w�梘���z ��0��G�_��ċ-��+L��	�Q̒�V�v9��,dz|�`���ȕ�3�~�s4��0��R��(:�XF�N�/�(fre��x4���ܩ�%}�&z�倬�;z�n�\C����˛oW��>�
ȥ�g���(�=���!��:�i�V ���2�3��J�U��;˞�;�8��M��F1�+���	���#�¢�c.���ʽsI!
��;�u'�E�*܍b&W�QS�v�@1�cK�%��KP�N'֞rt�ַ���IS]��P�`Q�@1�˛ֶ@1o%����������)�����_5�e��:�z|,�D��������4��'�rm�������2����Mj��F(��|g���xK�)Ca���U%�����[Ԣ�{����KHz=�|��֙�f��,�p���LKԝ�o�����.��LJ��������v&��u��ɕ��l���	��wNsY�+#�~*��P�N���"ݘTJqϼ�j+e:u�`=���I[��r�"����{N?E�����3�����i�T�QgSO�^�gϞ��F1�	�� ��>�i%re�"�I=���O>-u�T��ka$��p<?}�T'��������Y��3�]]�B�I%���a�cvy�qڢ�۫��m|�Vԣ��Vt�]�T�+�I+?��$m��H/���Cz18��!t:��t;.J�рřE���n3�26�.�����A��+�cfz|C@�O%vH}���Y2�^g�x"��rH�l
�޲�C��T�v�VT���������l�V�����<��Y��_(`���Au��=�oX�:Y�uPJ/�n�~�/��%���H6�nfk�1[��u�F1�+�;uO�)Д��_za
*'�b�|�v2Oi$�_;�nWs� 1d����^�g�n�����R�\V(�K-�
�>m�RT�����*��
���W/�w�7��R��'/.�Z[��`�n&~D�b�6��z��u���3,]4��^�z\�B�vS��� ii!�T���9/�jSx�vٸ���T1�)�D�O�C1��RHWH��[L��k���c�s�I��sR�ٶ.����m��›�9.���e�F�޽{J�ע��T1�3?�+����%]A1�wK��1h���s�=�J�1m�^�+c�K��s���b����b��pK�J	���1�?�.O����v�b>��Y�|����9�谏9m�1g�!���wEJ)9.�V�k}�4��z���kJ��B��"8�L��G7��\;��ؓ@���}��'.ڪ��2���,�0��?�O���<?g�ZJ*�����Q�O���Q�Jz	ݤ�|�v;��ų��l[i=$��3�+���ѷq��g��w��],�;8G)zoE���T�܌=�i5t?U�4H'Ҟ	
�Q̛G�
 P9tTgA�re75��z1��~��cR^Q�h��b�#�D���O��[����8���xwҢ���en�l[N|�w�
�%e���3iUv6G8�$oZt-��3��@���*�\�f}���<g��,s��r���L��\Sb�z�PB��ʏ��Q��2���F���I��kiB�d���"3�k�eH�ڡ�<E6+�Y�k�0�B#�Q��ʨpvUe�~S)͑n�>�����{[IB9�З��
��
r������-�bnq��ج�1=�W�8�X��w�5
������Fż�W5D@N*�~N��u�@�;�^A�S��3B�(�GYO�����*l#J7������Y���/������{j6>��D���~Q�
)��l�B-�@��(
�@�\5�BY���v�i��ri�v����������q�J��_�K��_����������`�vA?��
9M���j�D@�_C�S�IB���G�i�x���0G�t/�;r��
=$���4Z���k�+R�B�S��@1s��
)S3re�<:�m��rYҖ�I�,�����:�n=���>*Ճ��M`7��%u;�Oy2x�:ZZ��L��u�˫��t[ �C%����S;Ds%�Q�☋⭮r�BR�2�&ޒ�,�F|��3���hQj��ƇP�A1�ye/�ݠ��P7��8�֧b.���I7p�r.�Y��phP����JP�5�N)�$���t^�ЛqxO;3�3=R��=M��I��%�P'�Q�j����8���^��������*�f��R�uyja�G���Nt�6� �G����o_��;����zpe/�u5x�y�A��
�%��!֠hh*4�2@1g��XU
�X��,��w���$V�g�w��� R��v�ܴ`���е9pBoy�?+r�b��:㝖ӝJ�wړ��t�.Im�J�.O-T��9:.�,������ݱ���J֠H1�q�՜(�9�(�
E�i9J+֎f���U}:�2���sڲ�{˅���5ڐ�L#�X*u�R8�[��E1���k��c��h�u��KW���]a�b����>7s������^ً�V$$n�녻Q����8+�J���z��`�]n�l
�gG[���Zre����%�[N��gދSŜFY��\RŜ�?U��֝im.fwrv	Or���W��+:- �Z�M����9��4L�Ҍ�^��������nsv2T�\����-�+c���U�2��I�jR��.�u���(�zp��w��v	��)���t�ct���H%��b�rUDb�U��V��^�I�I*�Su�*�p���3C�����}��Q���(7I��Y��5��_V>XS���<�7��r�d�n���`KL�p�ī��*Y
R/"��+�J���za��k2�kg*��W9l�6�iZ��ϴ�1Ǝ�P����f�ZYQ�W�s�w�w5��L7��\{M�J�I�9l,=�$�YFw6Ǥ��Cn�Ym8PnVu��%��XW��N}1ׯ=�di�|�͕D177d�
��������M��a�n�q���ƥZ\�U��pܧt��tUqmܛT���͙��ӫ�߂S�r�"#���cJ��,t���Ձ�g@G
��;̡���F�J�4�lN��ob�!J��������>�;{I�pe�@ڍ2�ݢ���)��v
�D4k�4X�,�p+P̭���v*iC�h�X(���4��}�y�|6�9osj{�w֥(�S9e&P�L�>�9������w�Lh;(�v��*����I���I�5�J6D�\

�ަzE�>�%V�9��/�7�#4t�dK�]��_�4��ݛ��r{��Ѝb&W��Νo�_R���雪^�p^y;h�c�=VUMn�ιi������]���:�x�����ǧ9E}��G��>o��v�I�!����oյ�W�[ן:�:�S�%zj2��~�x�`b;����	�5]>q3��5������rX�tJ�!����g��*c�V��[��n�ȃH����g��])�H	B9�:�B=��F�ΉbvX]�i���8W{]1[Ȫ�Ů^xňk�л��"��p��Q��^���k}��޵�g,�CG��EZ[�I�|Z:���
x��`���cK��.�5��ffg�uX֦���A\W	W�#Ѝb&Wƺ	��Uz ��I7�8ӕ~+Bݬ}2D��|)�O����n��b�lD
2��Y�{U�}�g�u�N�hZ�ի�C�����D��\��v�b>�9��J>۴-�`i��{�"%@3�a.��,����3�)C�Ny�%wf^B���Q����;1ڪ�]�b���ɑJ�B�y��
�l�����G<ɤSg�������U�3>�|���OY�z�O��5X�����!�b�C�2��S	��P�F,Ci�Nd����n���:Y�#J�W�}OC��+A1�FDž��t9Ŝf�O㘣E��T&:�!U̱V��Ա�ב����z�S����tZ�O:�Ls�_���/[�~�k�.Q�|v�Z�b��s���!��6�=���w��!�}��f�v�Q�rb�2*�'����&+�t��n�<�Ǭ��nSz��b��n�q͡Y}_u
Q�����X������nf����%�����6]nu>_1;Ѿus,C���_��l����m�$]4+��즊�+����XMKC�Z��./��b~���}��.69����
W��:Ӽuq���=��Y:^m%�(freT;�1L>�X{}i�t3��&���n��[��u>
��L�2��Ҹq[N��p��7���O����x��Z;�<���?*��&v��+#����0}kR���$T:���<�gz�ʞȕ�'����Q�x�=HCw"���~��pE8w�U�����ov��1\vrL�'�G�G%#���pyJ��̰N@Q^E[I�fO��ِك�/�ó��W�d5��I��Y��	�+�����}�>��a�l�D�e�I�3��\/�H��x�g�~��b���S_�R�����׾��_"Ѝb&W��\��&�B��u��E���r��='rYfk��.�s��[E�v���O�<�����9N.��
����Mτ�>�g��^�E.G<�t3�B�(freT8��4I?�����̞�W���0m��h�Kv#�b�
�
E���u&�Y�c(G�r�0�/d����c���0�T1�΍k�bc���(Č�:�b><��'��x�J䯗��i���GMu@1�5}X��K���9���"���F�
SN��Ep��uƫ���'N����K]h��>&@=�@1�3X�������ͼc��54 v�+G��ɕq�tk�ҽ�&~_/��=����Icu�3�z��Hs���{{.�v`�n3�2�E�4���:�KR�� �\����T8�<��ܼ"Hö���X?�@7)9���t}�}[�{K�xڛ&�-'Ѝb^�u�萀\\JL��v�!�j��A�����)b�2�`�Ҕ��c
�PFWI�+Ųt��1�m�F1�+���W�Z�Eu;�w{9�+j�phP��[��a/!�yء߻��R�x��V�(O��V�8�{Ϙ�u��ɕ�c:tR�}�J�S!��{0�s9��<% ?��K���۩6^��>��|3�64��A1�gEɆxu5*��!������>�i�
�\�Z�+�	e�ܺB���蕀#�{j��p>2=
�;�+�&"
!�h%�0ڡ��"��~��(fre�?�@��m��r�䯝/pa|���&��pЏ��5U����vW(?��YЍb�-�B@�f��Q��i4����:���IE9W[9�2��Q�!k���I.�}�ٴ�F1�+�����;��:H�Ν;�_�o����[�`XAf��쳷�
�cne�:��At��5��9�!�׍b&WƐ�we���_Ff[�"ך�0
&Δ�s���P�}�g˽��i���OO��k��_$�bfr@�@(�,�$�Hm����/E#�YY��
[���k� �re46`�����պ�+���CK7�m�#w��L����1}��!@��z�K~A@ZY�V��C���Ѥ�%�	�ȅ��z�Q̕s�<@� WF�C�v=A�Tyc���Q>��Ms<�Q���o��c@�.�1�5Xs���p��I�?���F1�+c��K�!�������F`E�q�xhF�~(��!4A���0a�/��q�O�
�r(��� �B�\��v~C�z��:36��F1�+��9�a��Pȕ1�pw�ٳ{�)XY�5�QS��t����(f��|���|/�1h0�	|
J
�hK�P�#�����ă����J��}O�C�u��l"�bFU���_��_�������][Z��c�ʡ�7}+s�$����[���k	��F�3�\^�|�I�<����(Y's��Us	�7��Ҕ��y����UP��s�=w�Ν�Vm(�A��-B�_7s��s�u(����0r0K.��̼h�����~��3�B�Q�LN �͸��Bż��O�|�Ti���a�����7�X�ioQ̝�0�B13��:�b^Ƌ��M`�`�͜0��Mż7q��KŜ�g7����J:�(%S���C��_|ѯ����`6P�́�	����b֣����b,# ���+�,��������1��%P�Kh
T�<�`�U@�	���3���P�%�6\7����t@�@1�7&X���y	��ʢ�l�Z7�2���K�<���$�b�s\�
�|�`L��L����q�(�q�j�Q�LTB�\�@`�F(���`(����Q̵�v
G�<ܐw�as�;L�P���������4 \%�bf��M�����\-C��y�Q��(�F3c_P�aR� *c=���������5P�k�
p
�y�A��m@1�1NXy���!ޯ��Y��[o���k����O?��+X���9'M�(�
�"(�SV8���x�;w���^���W��%�@17:p��sc:f�P�c�{?�����߿/�~�T1�-1����@ON���� ���9#L�:��%�,M���_�M���!1-�G������P̅S= ������z{E1���ĎͰb��Y/��}��iL������Q�fl$�b���&p]1["K+��_Yn�4���|V(�8��	��׳�ʚ��k
lYN�bV}��8��u�h���۸���8a�P��]D11�w�bVߥ��:ù2"C7q���?��c8#w
�<��������YMżVA�R>��y��	e���Z�'�L��*Ư�(�bh����P�#�zO}fϿ�F3c_P�aR ���m@1�=~ŬG1CK�XF���e�(]+s�#�]����q��y�!�õ@1�:2ص��y/J�F�\ۈTb��������}@1�1���<��_�9����J��+��Hż �L�|���<��֑�.@M@179lP�L��P�L@�HŜ&U@�|��D1�0J�8�2��:�b`���"����]�9�zv\	��P�YqR�aṖ���,P�Y0�W	���1�G�@17:p�=!�bfJ�M�����\-C`�2^�����֑��yP��8
W
�<ܐ�a@%	��Kҥ��P��7����a�h@�@1�:2�5��y��J���r:\+�2j�ZFż��k#�b�mD*��\�@`P�́>����{��;���+�}�śo�9"�|�����J��+��Hż �F�/�x�g���O3���#�b�oL�hP(�A��n���ґ:���C�w��o�z���6#J@��l(�٨(X�p3�`�op��|��< �������z#73��v�Q̷Q� *c�4R���8�^���/_}�U-�;���w�������ڠօB�^Ǻ�~��[5l����a�S(�=O�?���{N�Bx����Ԓ��9E�@(���(�
�M���֭M��[-73�9?�
5��7��R�$�b�I���#�b>�}�-���D1�6�Q̵��@h�����;�x3���w�m�-B�@����hJŌb���b�yt�m(De5�w�������\v�m�ż�WC s6�Tt(�[n<�b�ꫯ>N��?��-6�1�6^(��F{�%�bv�;�8���ݯ;y�o���/���C��>}��3��*�RՕJP̥	/�ż��!P���X�ݙ�yg�4�]1��VrY�9,U�b�B��JP�m��B������׼��YV�z!��k���c�����OUOx�]OZU.���s��U�9I� @13
VȮ�=z�Hf=“����,�
���w�z�-��w��OϤ]
�^ąj+����e(�,3V�b��� ��Q[�qm=P��Ec�dW�i�Dp�&�
ׁ���z!��Χg�*f�p]��{�HŜf��P�Y0R	�@1ogH
5@1�0
Mڐ]1��6�WXJWoI��U&
Ij�)�뽩O���1��Y�Q�MN��F��g�� �@1��K�{@1�E��v�Q�ҵJ<gx�1K+��Vp�^��Ia�b�����3�	>�0�T�b΂�J ���y;Cj�����Qh҆}���t�hO����:tF��I����_9.��,�Q�Y0f�Ŝ&UA���9��@^�,Gr��'�?!���n��k�I6��I+�8���׶�ϗ/C1gG��B�F�\@)3�a%���y��\�b�f(~a�����a	�1��w�qsg�_wP�)k�~3o^K(�y�(��P���.P̻`�3���y�b�yt�m((框��΢�;ܲ]C1���ΰm������jd#�bΆ��%�b>ˍ��Q�5�_sͣ�m��#�bnn�j1x�bV��t'��݈z�E��z�\�Lv�C��Z�KĖ:Q�[�q- L������?��[��c'�Y�].tv��u��+݊�Q�� KU(�,��	���!5�@�\�(4`�s�=��ɓT7�S�ʅ�-���>��]+鲜���7�bz�g�ϟΧ�^{ۿ�V�����m�����kպ�b>�e��qB1�6�Q̵��K�<��w�qsgZ�;w�>RݼB1[���)�k�*y��
�u���U��]�>���P1]����o��U��
�B�ן���Zٵ����خ-m�h/��\j歭ż��A 3sf�Tw�A�[k֊9����������w�v���Н4���NM�"��W��x�c�&�jU�*Ҷ,��]��`]kE�CתX4:�k*�b^�k��(� ��@1ϡD��	���ݻ��>^o$��|�7~�7�O�Pɩb�SY�V�X��sx��u��z|�������p*���|i1Y���}����<��U^_�h0�A`&�<n�B)��	���n��Y|̡bC��))Nk��圪�P̩��^�b��
�p�GpP1Gq������ٵev��s	��	@`X(�a�~Ydz�1�U�ָ�T�g}̎-VЅ�&��K��u��\���b��ٲ�%S��36 �%*c�̨�4��֑�.@M@179l��=WF��9^[
��*=R��3N_{�^����,籃:$�-�'��#*C%'�t��mt>g|��Y�SżgZ� 0� �����1o����Q̵�����@M@17=|G�4�ܑ��o�\��P��xQ��@13AV@1��P�+�Q��P���R1 �	��G�,}F1���L�B�����Z@c@1�9�z�bF1g�FŪ@1CK��F$�bqԳ����G�s�GI��Ω���9��,�bޓ6mA����!.����q$xv'ץR�Ŝc�JP�aR ���+	\W���[^��tߐx�:\&}�?�;�/��X��R8�H��Ŝ�zl��w���mCX���jZ�uf��v(�Ө�e(�bh����P�#�z�>_Q�ޏZrVۂx>���vc7l��km ���
�*��%��Dg�ڻ�y�?)W��#v϶�us��O�����U�JW����@	��7O�q)�ŜeRe�Ŝ&UA���9����,e��yg�K��.[+f��.����7�OJ�:#�
�o�bV���ڐז�zK����۲V��.���B1��F�.C1CK��F$�bqԳ�bgm4tV1�2N�)$d�o�q��	�T��+�9m.dwj�%uZC����W����b�2�2V�b��� @��XI`�bv�"�,9�0�&ޢ�e�Uo����V�z11żr�w��8��@�C(�u�.]Q�ң�+�*1j�*ä�X�����
��
Gk誥�Y�%����zV�Z�W[�ŽQ�h+�U/"*#]xJ�>�n~+(�(	@7	��o"��yW��}8��:8���#�8}��^�爈X�qɡ���/*хi=^ާ#
(�B�}��;��A :���]�ku�+��<��T@1�9A1�6"�@�i(榇�H�o�c��pae�c��
_�-�!Ms�(��XhsZϩ�(曣VOs=c�%�: �b�`���M�|�Y�[��X��L�;ٱ�R�Χ�=VX��y�������r@�@1�6��ۜbVϥ���:��Hv�G��y#�
hE/A1�K��F#�bmij��EŜ��'��˱]W3�y7�� ��P�L��P�)8��iT�2s1�T@`D(�G=K�Q�(�,�P%(�B`����P�c�{�^��Q��Q�*P���R1 �	��G�,}F1���L�B�����Z@c@1�9�z-��s�9�����k�Z��7f��0$T�@13 @ #sF�cU��_���Z�v��[��[��cmP�B��_�5��-����:@�@176`�;!��,�@13% @ #sF�Tu��[h���(a# �f���*=K���8K��Ā ��P�aR�P�@o�Is�����!�bnf�03s`>�|V�� ��P�7Q�j�����C1Ǟ�!tH����%�P�=��(�(	@7	��o"�@�P�U�qơ��cO��:$�b�pP���y���Y�|V�� ��P�7Q�j(檇�8�P�DZ�e@@1w8�Cu	�<�p��,�y>+JB��M(曈(P5s��s�q(����2 �	��;ԡ��bj��w�<�%!@�&�MD������9�8�q�i�@�P��P]B15��;�b�ϊ�� p���&"
TM�\��g��8��@�C(�u�.����E1�gEI@�I�|�&�b�zx�3�|{Z� �!s��:T�P�C
��΢�糢$ �$�b���U@1W=<��b>�=-C����A�KO�<��>��ts�J�� ��P�3AQ�:?��O�{�9k�g�y�/���D:���8��@�C(�u�.���8�>��(晠(@s���P�L��f�\��j��P�4@�7(��Ft���͌�y�A��_�J�� ��P�3AQ�F_~�������1�8<�ڄb>?�C�����?�.?���o���{ァJ3� �q�OO�@13C @ #sF�T���>���_T0�|�nRZY�������NF�L�P�u��Ah�����\E_����/���'�|r���>�{���4~���� ���9#L�*K��7ߔ��w߽��| �~��@�5�ګ$�b�rX0
�@�P̭��PvKK+��
Ҙ)���8TgQ�C
7�� P���4a��D@a�-���+��
��dWO�\�a  ����[��l�b>%�ظ���?�,
㰝E1;�t�@	(�T�s+�adL�Tt�P��Z��@172P�	@�
(�6�i+��B�.t(�E�^+H�ʳ��tyk��
	��+L� �.s�cכ�
���>EP�\�o��͒�lXr
5��kl� �
s7C�vG�3N!�Jp�Ͼ}
�P��B5ڦ���	���� ���9#L�ZC@�,��BI-vv�*[�v
�n��5vsM�P�u��Ah������\kV�a�Y6}�^�i�����q�*@�@17:p͛]U\��1!�^@1�0J�@�(�f��C�\{�Ϻ�n������#,� �sC�ռ���w+�ۮ��k�(��F{!TM�\���d\C{�d�?��ql�/(�VF
;!4A`Ŭ^ڼ��C���?�LJ���;�4132��>չ��Έ��@1/�Ea@�N`�,��|�K����?>܌;w�`^ɼW���)�R�Ub�"3d�ݻw���5]H��	��� ��=ԛ�{�z���/�(f�h���+
�\5\� 
�G��%5؃
s���P� �$�b�	*[��$��*t&1�`���lSߊP��5@�@1�=�}+��>���0i�i�K/��h���s��Ṗ�q@�@1�=��*f/������ۛ��)��<�< Hc_��ZC1/�Ei@�Jż��R1K%K+K1K7�
�g����ڧ�P�L@�HŜ欪:S���C��ǘ��
��,O����:wԭN��b�d � �:����n���I/j���kjO1͊lV|���k�kt[P̣��@ +sV�3*�C1+g��0�>b�0��c�2c
Pd(�=(� �a������\�ڑD���R�L;ݥ����޳��N���� ���9#�YU����>|�0ᕑV`�~Q(��_�>�
�����b@#@1�=�*f%����ɓ'{�j�=%Q&�������[�~�W_}��oT5V(檆c �Nż�6���B+۔�颹	��\���/�������|���s�҅Q̥	S? �������$����2��V�%�S�=��X]I�J1�x���*f	h����|v� �+�J��ډ�����V�駟�a�ҙъbV��0����7�`)�B��8���g�f���fV���v�ZD��N�kzL|�V�
���O��բ�o"� �'P�b���w�u�D��}�(6}1@)e G�|�.Y�by�;-��.�«�.��!�g�3�g�o	ie�Sp��'o����*�͈�I�p<���k�kC1��J���%P�b��9�D:4���-w�����׳�S7�\_*f�e_T�׺D
�L��2=mEgT�fD��
�=Z�f�Y1+Ci��A)�R\1��c�]�,e>��?�P
7m����`�f��gi�:�����NM�93�1��"}}��*�zl���d:9�p�A�sQA�<�5�Y�2��Ŝ#�@��	Ԩ�e��h�5,I���%}O�����Oe������x��.��W�%�U`�>ۊ�6մ;դ}f�L�S1��0�Sh���R�8}�`
�:!�¥Q�����3A�^I�����u1_�qws�V�f��\RF��0Ŝ�́P�!��ԣ	�z���M��Py�/��)TC���^k,�c��:E1�0X�@�	T�����A�����H�9����ޚ<�%gs<>V�x}����TUaO7Qe�0���ؿC�f�8��J�R�_֗&c�O��d����'UƊY��w?"F9j�$�p�6�L:��D��3�I-<ۻ�TG�k����kH'���߁��_��'P�o�Z��|v� �+�Js��O�-��"=R��H��wv�<��O}��Z�xԬ;P��䠽6�gr�,g���ä!B1an��j�	��Pީ';~)y�k㗒���9tm���y���!U�g�@����s�w�n
Ҹw�^��H���ϒ��_5>�
�@1���E� E�FŬ/c�'zW_�i���O}��
��H1��ҟb�l��k��K�K:�"Mq��#ٗ`����'�!!�����׆12 T�Ys����$��"�<��K�����x}3H�[>�҄���PjT�~�+=�uR�ob�Tj#u�4R?�ד�]��}��Vx��>�W���\R̍�1K%+`�tiT��8�e���\�4D�>ݔ��:�B�z��I�i�:��>�;��5��}2�ʞ-��q2��k�S̙����o��b�z7S1��î�y�(�<�
���jT�'"�<JxY��'�Po��+٫;�W���~�pR��-�&������:i�h>v�R4(C��ǘ9��|�1(���1[��X\����
݄�D4�Q[j�"�5DC��#ecB����93�����#�ƕz��c�D��93��ȵP����3��؄��)@	T��3�����R�Rc�ACj�Ħ�gc�o���f1��P��ܸyI���O	���mɷ�#�y=�� �	��S�Ŭ�q
�P��B{�U��p�@�d�p������b:@`O(�=i�����n�+�]��G���>8�g{4�bރ2m@��y��S1+㯶e&(v�1�ڞBϕ~�;��B58���_�5��CAe� 0.��c��b��Yb�D��=̙ڋ$����_>�	��2��@�:F`��L�4�������S1���Ӗ)?]�Wt>+e�Ra��_��h�[�\���F�E>�@�쭘ӝD����N6{[Q��KNm�_1�=�-;��]l6���˝��Y�&;�donE��6�^!����~@U�Y1�K�wxNm8D1�S����pR�鏮sl�#c&[H��W�)�I�$�yM��6s��y��"p�bv�0�2�>og�PJ�xS	�wPGl{׺�J�*�3�P#�љ�=G"yY�nX�bLZ��qt=*�>���q�b��Җ	���4X1@�Zeb���a����
�����S�GJ��
J!�t��׎.�h��6�?�14��*�CO�!� p�bN7C�M�$\�9�}x־�fȒJ+���"{(��F=�;<���i���N%��I[	k-��£��3U���O��eR��㉽Qv�xmU�b��1�g�5F�y2(2�{=��n�/����|:�VƓ�{�\���͏��h�k�MP���糢$ �$p�bN7{�Ҳ�s%_$k&r��%<�* Q�t�t�O\>�Ǖ�hҦU�ճT��΄b�V�E�wSZ���Ԭ��������%���Knk̙+�9}K�聋����N?��M�lT�
��b��G��R`>�|V�� ���W��M厣2n*��C��>_R��%'�Y�:�CJ��Bʺ<<����a�ݖbv�s%dH��k���C¦�����.U̎<N�����c(��b��4&J�M���P�+�q	 \"p�bN5kH��Ol�b��'��\׆�R_;w�+��ډC:=�����̦֦��B�����H�+�������:�
 �n*a��7�u�bN��+T���_5�'�~�;���ag��$Hc5.y��*[>�Օp�(f� d$p�b�����,��X�ԟ:"TT��g|R�Z�!���9���ނ�
�)D����Ր�MZQ��ד�*k�֯S���+�.͞�>���ݻ�����5�Ͱ�������K��氦�Y�
�G��Aџ���n��Ӄ��`1�l�N��Y�iL�RV�MF��%�	�X�nQy�"\� ���V̩�N9
	����.���'S��kC6����|^��e<[ҞlU������O����]��.m7=_�b6%%5�fiJp������
�饻���<reX~̇ɠ����L�j���“��ɀ�Ζ�>f`(s�����T���4a� 0����R3����%�[����f��p�a�+fuDAo���������W�%�+C�W�8�1�d@g~���pjEH>|��H�xk�
�\��` ��T���i�=��9M��u9-~jd���6+x@��<��gQ�_�C�u�G�O�.�3L$�"�:ܥ�m׌b�xp� ��	T����!-���
G��
�3�n��[�l[�T�k��P��@�HŜ欪�R�o%��
mV)�5E�+C��� ٟ�y�@�c(��E�,F��U*42<̙.�:��#:�bNyʔ �b.A�:!Kż��7����Y��M��{�k�=���T�kY����FsϣK� �Nż7��a)9�D!;�M�������e�0��P�k�\�(` �n������)HC����IͶ� -lOI0�ϔ�Br���¥j@�@1�=�}(fS�RT�a��~98�_{�n��b�E��!@`�XY����
D������ad�T���9/Oj� 08���?�,�^��̓�xc������3�
@�Hż���R1��4�ϪF���?0k�C1�%�u� p��y�iѱb6J�����RF���ޟ�
�7��R@�@1�='�W�*�,���������ds{(�����!�b�{6����T	4�pMq��؛r���%Ѿ-�|�I�Z��8sq�4@`${(f�� ��a�>��H�AZ���:�<�0Q2��,�`3s�2�C1g4wKU�w�&�p˵�IOGc7*�T7ע��J:@��(fie�w%�k�>�
��7|��g��9��^���� ���(�Y�A��3ΞUռ���ZVъ�qIUP�U
�@h����f��k���i�J�5)^
#��
(��" ��	��������\�V �xE�D���P�r9 ��W̩�7sm����ڇ�ܻ��/j��(^*� 0��������)��;�("B�{ڦ�qjTI<�ۛpO�ն�b�vh0�@��W�1*|��<A��}��$�~X�N=v�dо$J�Q�-�?������. �.	����V;���Zֺ��_�A��:�؍b�e$� �*����H	(^���/��o����E�|yڅ �%s���|�[�qM��>x�0��g����g��  �&�b�͈Gp�7��I"߻wOrY���^��!Ṗ`�Q@�@1�:����>X����o�B%��=�M�<!@�6�mF�8����Vp�����OZY�����p�1�(�C��( �^	��{���e�V���5.uOe�6Nj�J��Х(f& d$�b���� � 
�����Vz
���jc;h�n(��� 4F��؀a�	HK7�8��V�e�h6�c�����@	��3¤�]	8�w�w����]���,�����q�
@�@1w2��v������a�O�/@137 @ #sF�Tu���q@�4Y7s��u�#�bnl�0wB�̔8K��Ā ��P�aR�P�@o�Is�����!�bnf�0�,33s�J@1�&L�e	����m�v|���C�����Q���P��Y
U�<�p�Y@�	��K���P�e�6[;��١�p@5@1�8*�4��y>��J���n:@�4si��_���,�fkG17;t@�F(�G��@1�g5TI�P�Mg!�&�b.M���@1���l�(�f��!�H�\�`�|(��*�bj��, ��P̥	SY(�|������a8 �	��kl�O�<��P%Q�C
7�� P���4a�/K�\�o�����:� P#s���M�	����$�y�ᦳ�J@1�&L�e	����m�vs�C���j$�b�qT�i>�|VC�D15�t�@i(�҄��,sY��֎bnv�0�@�P�5�
6�'�b��j��(框��B(M�\�0��%�b.˷��Q���C�����Q���P��Y
U�<�p�Y@�	��K���P�e�6[;��١�p@5@1�8*�4�@��_~��G�ŵ���/����ϯ���@1w3�t�@
P�5�6�'�*�O?�T��?tu���Z*�׷��
@178h�@�^(�z����De����4����/|�O	h*�3�=��I�9mQ�!(�S!�O�\�a�5�q̎͐�9t�ճ�4T���-�u�o���D3�;#�b�l@� �c	����O�[	�*f�f�/��XJ�x��}�_�9B8����@1W6 �@�m(�����ʘ,��8N{��r�+Z��M$scJ� H�| |��@`�b�DV��P��9
h�h�`
U�D�\�h` ��	����;0G1+�B�X�z�
As���4b���$;�>����;��%�b>�?�o%pV1K��Wi�����
\�n��*������5@1�4�@�y(��p������R�Q�L@�HŜ&U@�|��D1�0J�@�(�f�
C�@131�@131 @ #sF�Tu��[h���(a# �f���*����O�<�%!@�&�MD��>檇�8�P�DZ�e@@1w8�Cu	�<�p��,�y>+JB��M(曈(P5s��s�q(����2 �	��;ԡ��bj��w�<�%!@�&�MD������9�8�q�i�@�P��P]B15��;�b�ϊ�� p���&"
TM�\��g��8��@�C(�u�.����E1�gEI@�I�|�&�b�zx�3�|{Z� �!s��:T�P�C
��΢�糢$ �$�b���U@1W=<��b>�=-C����A�K(框{~gQ��YQ�n@1�DD��	�����C1Ǟ�!tH����%�P�=��(�(	@7	��o"�@�>��#���}}�Ż�[���u��i�@�P��m���/�y�;�<�{��L�@1�gEI@�I�|�%���C�_|�^+��(�#��& �n	����:nf�#��>���0 \'�bf��M@nf�ma�Q�e�R+ �A	���n��G�G?�я���EŜ�$�@���������^��x���_z�O>��՞`w(�P����P��}�=��O*���>���P�9�f<x���/�l�_X���9#L�� 3s�1Z��Ͽ������~�m����� �b.�*!�K�<��7���'�Aw��U��K���,O����:7�A�HŜ&UA���9��`�a|��s�UL�"��ݻwE[ϩ�2�@1�;vX@�B(�
�~��;�#��0��\V_��!�WH�\�` �v	�����-��*^���0=D13�t��P�{P����#�	�^j!�+'�b�|�0�@[P�m���Jy�$�?>M�1�:�bl��. ��P�e�R�"��*K+K1����G���,L� P?s�c4��Jj���l��*Zc�Cv�<��i@���K����C~_������/Pi���� ��0+��\�` �v	����,W~eie��Cv��V�XWp���M��@13 @ #sF�T����0�{�d�����_����(z���!އ �P�`Q4���*yE�
�Tbo�Ç�vg���P��@�HŜ&U�&��a�a�=��ɓ�#�oS��r(��̸�.@139v"*�b�&W5Y;��nU\TsÀ�z!�b�e$+���r*��YrY��<x ]1ZL�H��� ��P�aR��iO))�ø>f�}PB_�msP��
C������i�6%��jQB��ݴZ���ܬ��m��`֣�p�@�,sY�c�.��0�nT�'�|"�$tM���f#�y�ᦳ�J@1�&<\�ںOZYa��\��k-F��7�{�bm��/ ��P�E�U��Z-w�޽��v�+HCi����z�bnmİ�@�P�UO+�IG*��t� ���ꫯ*D��Ly�̟v��KP�N@�@1;��:��ʆ�����HEJ� �Ǐ�Qሡ�+L� �.s�cw���(˯,��;KK+K1K7W���3�P�&@�����ܳ'�1�b��l�ζ��
�i(Z�N�
�<��e@���˱�f%��WU91��᪎i-��h]��U�J]�b.E�z!I�<䰯��+#
����	�[˘��@1��H-� �53a�a(�@*������J{�(�!+7Y�+�b.ǖ�!H�<�/���o�l,n[��"��6A���*�b�E�z @3s����%�ں���ɓ1S�Õ�*sF�T@��7́�^{��ӧi:�`�M��q��?(����t|��Wo����UR��>���~����EA�m��駟����)�����[7��Pżd�� 0�~���_x�P�=�b�Tc˝��Z�6g#�?�XnZ-ea��g*�u^�zq���m!�ѿs�N:����E1Ϝ�� �9P�s(]+#����~�v�'��G��ԥ�3�8��J�ʊ"P���0�T1��S�i�-��i.9q�N�OQ�__��Z�9mZ'���]_�]��31���L���	ij�^�1Jɧ�"
��:��^�D@GL�T1�O������gN��:&�b�:�X�Or9�:{uRr9��'a!�"{k�Y�W�%�P����b���ZR�&^g!R���*���*�^:�k�u�.�?u^/|�$F��
�]U��z&�zt,�G�����=��nT�^��GAZ(��At�A�#�%��Co���]�b��RŜ#�@��	��3��f����ͯ��U`���W�)
�0�.��O�%��S�v#�Bjr2���@XW�J�kėH����P�piO�z�Z�8ӵ�Tm_�ǿ�t�is�'Ӻ�'��ߧd�x�P̓h��ӱ�m(�}8�
 �A�����A� ݠ3���.��F�i~C-�Pƺ:&>f�r8Uީb��q��d擊QK(pv�{îk]�&�9=��7�9F�=a��l#����rW��Os�?�YrZ3�yOڴ@�{(�<C|����K1�/O��S�ixC-�_c�Z�P�6DZ�w;qS1K�:n8��-���v�~5�7�,�C����b�bOFŬ�,Zg�a��\�wlF�Igx�����*E1� �@Ŝg�'�ف^UQ�*cײ�E��W��|g�_c{��4*#��G�CXw]1;�ۅ�|*��1�:�����|�6��o���H�."~F'��|ݞ���v���j�^4�������i������<UC��9ϘKcMB��t����p��q�o��v�=5R	��)��	�<=���R<�Vզ�x���M��NQ�k],Q��[���7�P_{ݞ�́��4�_�@M�'?6L~��AD1繵Q |M�<�D���.�۷Y"rΦg�߼��όKo���?Zn�Sb�'y.�(�\$��P̣�%��w��<J����ids��x)͟4�Rj4ap�F��+L� �.|���\˕C�0�c��S���|��^��8%�+�L���f�Ŝ)B��X�Y~��#?���\������6����W��/�l�~@(D` Ŭܷ�������_��]��
��݁��~���mj�Ua,���'M@��@�y��t�Ѵe�K�"'F�V�Ԝ1	`{�� 0,�C_ڲ4�[�!�4szq3WF93�Ԝ7	�)@��%(�Q�F�i��
D

��5G�`-<M]�ݥ��p�I�� N�<��6mY(f�v�}Lҭ1�Ͳm>����b�m�b�2���:�w�q��R�������@����y�)Qa�2+f��V�z�-�%v�߲O�&��r\�9�6\�:����ox�FtWf��IG��g@h������jlU͊YWB9z)]�
�#M��W�toj�������:9����N����uqe��Y�.� tM�����\=a���q�j�LC�#�"U��V�:9Y���)��O5�-N�ޯ6H�T��� �&s���j/5{���k-�'rV
X�_v�#T�o��}̓�|:�@�S�,�n
�3�2@�@�P��a�<y�Dۤ)�Y�
��dIai_��TV`�#�%���9.T�BY�|�N���u�:}�'�[4v� tO��/蠷��s�:/�,GQI^'�����i��O�L���*֟�?�v\k��ԣ�3�n×��2�xQ� Ps�P������S�m
v9�-	%�����>k��0~�}���f��j�� @�����	���;�w
�8��,K"KG&
/�ɪ_���{�)�E�I���� ,%�b^Jl��
��r@����5�'?��+��r���J��b�l@���P���o�uk��_ͷh��{�a��Xč�� �
	��+�Mz��w�+�?0�iQ�K(	@�@�P��Mu�y�27�v���|��'U���na @�A(��P���ꫯ*0W��5��Ɲ�O�(���W� �E���x��%P��ǏI�`���_�vځ J�<�oﶴ��t����ڭ�{�˻|�����r@�@P�MS�F*6C��P�F�V��L�C�ϋ���\�j� @�
(�*��u#�P~V��Ϫ<�+'F�c��� �$�b����(H�"Ry�f]�l!�WV7��y��Xa8 @ s��b
T�^'��� 
�N!(���9@��%(f�F~��j��n�4�AW6���9�+�@h����Qj��'O���(m�a�J�͙��� ��P�[	r��M��M=�	Di@t�]�� 02�ȣ�S�%������őm�-�w�%4@�������4P����`e�ʎ���B��!�bއ3����j9�27W����PBœ0f� @�P�̄�	h�<i(	]U�Tj^k��0��'�A��'�b�~�:5P�H�*e[
��ʘ�` @)3��0��U�棌���}
څ @�,3�`
�.z���T}��< @�$�bf.TA��)���.!
%�bx0� 06���_S凌wX{�br�F	[ @#@1�8�5���6{�o@X�a @�o(�Ƿ��)ś2i��+HC;���w�y�U"�
@��qP�DZ����֬�f�8oA�D���9EK���õ� K�<�з�q�R(����SJ���Z퓢D+�]��!@�����k�1�O�imM�z@��AP����������"X��_���R�� @�+(殆���8�⥗^�^}���<�at?�  @`O(�=i�Vʩ,/r��Oa�?�Z�<mP @�%3s�UJ�Lڽ�J1�JE�*� @�s�Ժ-|��i(Zc�i� �	��+������IEND�B`�PK	%�\�����&html/_sources/c-api/exceptions.rst.txtnu�[���.. highlightlang:: c


.. _exceptionhandling:

******************
Exception Handling
******************

The functions described in this chapter will let you handle and raise Python
exceptions.  It is important to understand some of the basics of Python
exception handling.  It works somewhat like the Unix :c:data:`errno` variable:
there is a global indicator (per thread) of the last error that occurred.  Most
functions don't clear this on success, but will set it to indicate the cause of
the error on failure.  Most functions also return an error indicator, usually
*NULL* if they are supposed to return a pointer, or ``-1`` if they return an
integer (exception: the :c:func:`PyArg_\*` functions return ``1`` for success and
``0`` for failure).

When a function must fail because some function it called failed, it generally
doesn't set the error indicator; the function it called already set it.  It is
responsible for either handling the error and clearing the exception or
returning after cleaning up any resources it holds (such as object references or
memory allocations); it should *not* continue normally if it is not prepared to
handle the error.  If returning due to an error, it is important to indicate to
the caller that an error has been set.  If the error is not handled or carefully
propagated, additional calls into the Python/C API may not behave as intended
and may fail in mysterious ways.

.. index::
   single: exc_type (in module sys)
   single: exc_value (in module sys)
   single: exc_traceback (in module sys)

The error indicator consists of three Python objects corresponding to   the
Python variables ``sys.exc_type``, ``sys.exc_value`` and ``sys.exc_traceback``.
API functions exist to interact with the error indicator in various ways.  There
is a separate error indicator for each thread.

.. XXX Order of these should be more thoughtful.
   Either alphabetical or some kind of structure.


.. c:function:: void PyErr_PrintEx(int set_sys_last_vars)

   Print a standard traceback to ``sys.stderr`` and clear the error indicator.
   Call this function only when the error indicator is set.  (Otherwise it will
   cause a fatal error!)

   If *set_sys_last_vars* is nonzero, the variables :data:`sys.last_type`,
   :data:`sys.last_value` and :data:`sys.last_traceback` will be set to the
   type, value and traceback of the printed exception, respectively.


.. c:function:: void PyErr_Print()

   Alias for ``PyErr_PrintEx(1)``.


.. c:function:: PyObject* PyErr_Occurred()

   Test whether the error indicator is set.  If set, return the exception *type*
   (the first argument to the last call to one of the :c:func:`PyErr_Set\*`
   functions or to :c:func:`PyErr_Restore`).  If not set, return *NULL*.  You do not
   own a reference to the return value, so you do not need to :c:func:`Py_DECREF`
   it.

   .. note::

      Do not compare the return value to a specific exception; use
      :c:func:`PyErr_ExceptionMatches` instead, shown below.  (The comparison could
      easily fail since the exception may be an instance instead of a class, in the
      case of a class exception, or it may be a subclass of the expected exception.)


.. c:function:: int PyErr_ExceptionMatches(PyObject *exc)

   Equivalent to ``PyErr_GivenExceptionMatches(PyErr_Occurred(), exc)``.  This
   should only be called when an exception is actually set; a memory access
   violation will occur if no exception has been raised.


.. c:function:: int PyErr_GivenExceptionMatches(PyObject *given, PyObject *exc)

   Return true if the *given* exception matches the exception in *exc*.  If
   *exc* is a class object, this also returns true when *given* is an instance
   of a subclass.  If *exc* is a tuple, all exceptions in the tuple (and
   recursively in subtuples) are searched for a match.


.. c:function:: void PyErr_NormalizeException(PyObject**exc, PyObject**val, PyObject**tb)

   Under certain circumstances, the values returned by :c:func:`PyErr_Fetch` below
   can be "unnormalized", meaning that ``*exc`` is a class object but ``*val`` is
   not an instance of the  same class.  This function can be used to instantiate
   the class in that case.  If the values are already normalized, nothing happens.
   The delayed normalization is implemented to improve performance.


.. c:function:: void PyErr_Clear()

   Clear the error indicator.  If the error indicator is not set, there is no
   effect.


.. c:function:: void PyErr_Fetch(PyObject **ptype, PyObject **pvalue, PyObject **ptraceback)

   Retrieve the error indicator into three variables whose addresses are passed.
   If the error indicator is not set, set all three variables to *NULL*.  If it is
   set, it will be cleared and you own a reference to each object retrieved.  The
   value and traceback object may be *NULL* even when the type object is not.

   .. note::

      This function is normally only used by code that needs to handle exceptions or
      by code that needs to save and restore the error indicator temporarily.


.. c:function:: void PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)

   Set  the error indicator from the three objects.  If the error indicator is
   already set, it is cleared first.  If the objects are *NULL*, the error
   indicator is cleared.  Do not pass a *NULL* type and non-*NULL* value or
   traceback.  The exception type should be a class.  Do not pass an invalid
   exception type or value. (Violating these rules will cause subtle problems
   later.)  This call takes away a reference to each object: you must own a
   reference to each object before the call and after the call you no longer own
   these references.  (If you don't understand this, don't use this function.  I
   warned you.)

   .. note::

      This function is normally only used by code that needs to save and restore the
      error indicator temporarily; use :c:func:`PyErr_Fetch` to save the current
      exception state.


.. c:function:: void PyErr_SetString(PyObject *type, const char *message)

   This is the most common way to set the error indicator.  The first argument
   specifies the exception type; it is normally one of the standard exceptions,
   e.g. :c:data:`PyExc_RuntimeError`.  You need not increment its reference count.
   The second argument is an error message; it is converted to a string object.


.. c:function:: void PyErr_SetObject(PyObject *type, PyObject *value)

   This function is similar to :c:func:`PyErr_SetString` but lets you specify an
   arbitrary Python object for the "value" of the exception.


.. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)

   This function sets the error indicator and returns *NULL*.  *exception*
   should be a Python exception class.  The *format* and subsequent
   parameters help format the error message; they have the same meaning and
   values as in :c:func:`PyString_FromFormat`.


.. c:function:: void PyErr_SetNone(PyObject *type)

   This is a shorthand for ``PyErr_SetObject(type, Py_None)``.


.. c:function:: int PyErr_BadArgument()

   This is a shorthand for ``PyErr_SetString(PyExc_TypeError, message)``, where
   *message* indicates that a built-in operation was invoked with an illegal
   argument.  It is mostly for internal use.


.. c:function:: PyObject* PyErr_NoMemory()

   This is a shorthand for ``PyErr_SetNone(PyExc_MemoryError)``; it returns *NULL*
   so an object allocation function can write ``return PyErr_NoMemory();`` when it
   runs out of memory.


.. c:function:: PyObject* PyErr_SetFromErrno(PyObject *type)

   .. index:: single: strerror()

   This is a convenience function to raise an exception when a C library function
   has returned an error and set the C variable :c:data:`errno`.  It constructs a
   tuple object whose first item is the integer :c:data:`errno` value and whose
   second item is the corresponding error message (gotten from :c:func:`strerror`),
   and then calls ``PyErr_SetObject(type, object)``.  On Unix, when the
   :c:data:`errno` value is :const:`EINTR`, indicating an interrupted system call,
   this calls :c:func:`PyErr_CheckSignals`, and if that set the error indicator,
   leaves it set to that.  The function always returns *NULL*, so a wrapper
   function around a system call can write ``return PyErr_SetFromErrno(type);``
   when the system call returns an error.


.. c:function:: PyObject* PyErr_SetFromErrnoWithFilenameObject(PyObject *type, PyObject *filenameObject)

   Similar to :c:func:`PyErr_SetFromErrno`, with the additional behavior that if
   *filenameObject* is not *NULL*, it is passed to the constructor of *type* as
   a third parameter.  In the case of exceptions such as :exc:`IOError` and
   :exc:`OSError`, this is used to define the :attr:`filename` attribute of the
   exception instance.


.. c:function:: PyObject* PyErr_SetFromErrnoWithFilename(PyObject *type, const char *filename)

   Similar to :c:func:`PyErr_SetFromErrnoWithFilenameObject`, but the filename
   is given as a C string.


.. c:function:: PyObject* PyErr_SetFromWindowsErr(int ierr)

   This is a convenience function to raise :exc:`WindowsError`. If called with
   *ierr* of :c:data:`0`, the error code returned by a call to :c:func:`GetLastError`
   is used instead.  It calls the Win32 function :c:func:`FormatMessage` to retrieve
   the Windows description of error code given by *ierr* or :c:func:`GetLastError`,
   then it constructs a tuple object whose first item is the *ierr* value and whose
   second item is the corresponding error message (gotten from
   :c:func:`FormatMessage`), and then calls ``PyErr_SetObject(PyExc_WindowsError,
   object)``. This function always returns *NULL*. Availability: Windows.


.. c:function:: PyObject* PyErr_SetExcFromWindowsErr(PyObject *type, int ierr)

   Similar to :c:func:`PyErr_SetFromWindowsErr`, with an additional parameter
   specifying the exception type to be raised. Availability: Windows.

   .. versionadded:: 2.3


.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilenameObject(int ierr, PyObject *filenameObject)

   Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior that
   if *filenameObject* is not *NULL*, it is passed to the constructor of
   :exc:`WindowsError` as a third parameter. Availability: Windows.


.. c:function:: PyObject* PyErr_SetFromWindowsErrWithFilename(int ierr, const char *filename)

   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, but the
   filename is given as a C string. Availability: Windows.


.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilenameObject(PyObject *type, int ierr, PyObject *filename)

   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilenameObject`, with an
   additional parameter specifying the exception type to be raised.
   Availability: Windows.

   .. versionadded:: 2.3


.. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, const char *filename)

   Similar to :c:func:`PyErr_SetFromWindowsErrWithFilename`, with an additional
   parameter specifying the exception type to be raised. Availability: Windows.

   .. versionadded:: 2.3


.. c:function:: void PyErr_BadInternalCall()

   This is a shorthand for ``PyErr_SetString(PyExc_SystemError, message)``,
   where *message* indicates that an internal operation (e.g. a Python/C API
   function) was invoked with an illegal argument.  It is mostly for internal
   use.


.. c:function:: int PyErr_WarnEx(PyObject *category, char *message, int stacklevel)

   Issue a warning message.  The *category* argument is a warning category (see
   below) or *NULL*; the *message* argument is a message string.  *stacklevel* is a
   positive number giving a number of stack frames; the warning will be issued from
   the  currently executing line of code in that stack frame.  A *stacklevel* of 1
   is the function calling :c:func:`PyErr_WarnEx`, 2 is  the function above that,
   and so forth.

   This function normally prints a warning message to *sys.stderr*; however, it is
   also possible that the user has specified that warnings are to be turned into
   errors, and in that case this will raise an exception.  It is also possible that
   the function raises an exception because of a problem with the warning machinery
   (the implementation imports the :mod:`warnings` module to do the heavy lifting).
   The return value is ``0`` if no exception is raised, or ``-1`` if an exception
   is raised.  (It is not possible to determine whether a warning message is
   actually printed, nor what the reason is for the exception; this is
   intentional.)  If an exception is raised, the caller should do its normal
   exception handling (for example, :c:func:`Py_DECREF` owned references and return
   an error value).

   Warning categories must be subclasses of :c:data:`PyExc_Warning`;
   :c:data:`PyExc_Warning` is a subclass of :c:data:`PyExc_Exception`;
   the default warning category is :c:data:`PyExc_RuntimeWarning`. The standard
   Python warning categories are available as global variables whose names are
   enumerated at :ref:`standardwarningcategories`.

   For information about warning control, see the documentation for the
   :mod:`warnings` module and the :option:`-W` option in the command line
   documentation.  There is no C API for warning control.


.. c:function:: int PyErr_Warn(PyObject *category, char *message)

   Issue a warning message.  The *category* argument is a warning category (see
   below) or *NULL*; the *message* argument is a message string.  The warning will
   appear to be issued from the function calling :c:func:`PyErr_Warn`, equivalent to
   calling :c:func:`PyErr_WarnEx` with a *stacklevel* of 1.

   Deprecated; use :c:func:`PyErr_WarnEx` instead.


.. c:function:: int PyErr_WarnExplicit(PyObject *category, const char *message, const char *filename, int lineno, const char *module, PyObject *registry)

   Issue a warning message with explicit control over all warning attributes.  This
   is a straightforward wrapper around the Python function
   :func:`warnings.warn_explicit`, see there for more information.  The *module*
   and *registry* arguments may be set to *NULL* to get the default effect
   described there.


.. c:function:: int PyErr_WarnPy3k(char *message, int stacklevel)

   Issue a :exc:`DeprecationWarning` with the given *message* and *stacklevel*
   if the :c:data:`Py_Py3kWarningFlag` flag is enabled.

   .. versionadded:: 2.6


.. c:function:: int PyErr_CheckSignals()

   .. index::
      module: signal
      single: SIGINT
      single: KeyboardInterrupt (built-in exception)

   This function interacts with Python's signal handling.  It checks whether a
   signal has been sent to the processes and if so, invokes the corresponding
   signal handler.  If the :mod:`signal` module is supported, this can invoke a
   signal handler written in Python.  In all cases, the default effect for
   :const:`SIGINT` is to raise the  :exc:`KeyboardInterrupt` exception.  If an
   exception is raised the error indicator is set and the function returns ``-1``;
   otherwise the function returns ``0``.  The error indicator may or may not be
   cleared if it was previously set.


.. c:function:: void PyErr_SetInterrupt()

   .. index::
      single: SIGINT
      single: KeyboardInterrupt (built-in exception)

   This function simulates the effect of a :const:`SIGINT` signal arriving --- the
   next time :c:func:`PyErr_CheckSignals` is called,  :exc:`KeyboardInterrupt` will
   be raised.  It may be called without holding the interpreter lock.

   .. % XXX This was described as obsolete, but is used in
   .. % thread.interrupt_main() (used from IDLE), so it's still needed.


.. c:function:: int PySignal_SetWakeupFd(int fd)

   This utility function specifies a file descriptor to which a ``'\0'`` byte will
   be written whenever a signal is received.  It returns the previous such file
   descriptor.  The value ``-1`` disables the feature; this is the initial state.
   This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any
   error checking.  *fd* should be a valid file descriptor.  The function should
   only be called from the main thread.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyErr_NewException(char *name, PyObject *base, PyObject *dict)

   This utility function creates and returns a new exception class. The *name*
   argument must be the name of the new exception, a C string of the form
   ``module.classname``.  The *base* and *dict* arguments are normally *NULL*.
   This creates a class object derived from :exc:`Exception` (accessible in C as
   :c:data:`PyExc_Exception`).

   The :attr:`__module__` attribute of the new class is set to the first part (up
   to the last dot) of the *name* argument, and the class name is set to the last
   part (after the last dot).  The *base* argument can be used to specify alternate
   base classes; it can either be only one class or a tuple of classes. The *dict*
   argument can be used to specify a dictionary of class variables and methods.


.. c:function:: PyObject* PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)

   Same as :c:func:`PyErr_NewException`, except that the new exception class can
   easily be given a docstring: If *doc* is non-*NULL*, it will be used as the
   docstring for the exception class.

   .. versionadded:: 2.7


.. c:function:: void PyErr_WriteUnraisable(PyObject *obj)

   This utility function prints a warning message to ``sys.stderr`` when an
   exception has been set but it is impossible for the interpreter to actually
   raise the exception.  It is used, for example, when an exception occurs in an
   :meth:`__del__` method.

   The function is called with a single argument *obj* that identifies the context
   in which the unraisable exception occurred. If possible,
   the repr of *obj* will be printed in the warning message.


.. _unicodeexceptions:

Unicode Exception Objects
=========================

The following functions are used to create and modify Unicode exceptions from C.

.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

   Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
   *object*, *length*, *start*, *end* and *reason*.

.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

   Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
   *object*, *length*, *start*, *end* and *reason*.

.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)

   Create a :class:`UnicodeTranslateError` object with the attributes *object*,
   *length*, *start*, *end* and *reason*.

.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
               PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)

   Return the *encoding* attribute of the given exception object.

.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
               PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
               PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)

   Return the *object* attribute of the given exception object.

.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
               int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
               int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)

   Get the *start* attribute of the given exception object and place it into
   *\*start*.  *start* must not be *NULL*.  Return ``0`` on success, ``-1`` on
   failure.

.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
               int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
               int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)

   Set the *start* attribute of the given exception object to *start*.  Return
   ``0`` on success, ``-1`` on failure.

.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
               int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
               int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)

   Get the *end* attribute of the given exception object and place it into
   *\*end*.  *end* must not be *NULL*.  Return ``0`` on success, ``-1`` on
   failure.

.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
               int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
               int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)

   Set the *end* attribute of the given exception object to *end*.  Return ``0``
   on success, ``-1`` on failure.

.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
               PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
               PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)

   Return the *reason* attribute of the given exception object.

.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
               int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
               int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)

   Set the *reason* attribute of the given exception object to *reason*.  Return
   ``0`` on success, ``-1`` on failure.


Recursion Control
=================

These two functions provide a way to perform safe recursive calls at the C
level, both in the core and in extension modules.  They are needed if the
recursive code does not necessarily invoke Python code (which tracks its
recursion depth automatically).

.. c:function:: int Py_EnterRecursiveCall(const char *where)

   Marks a point where a recursive C-level call is about to be performed.

   If :const:`USE_STACKCHECK` is defined, this function checks if the OS
   stack overflowed using :c:func:`PyOS_CheckStack`.  In this is the case, it
   sets a :exc:`MemoryError` and returns a nonzero value.

   The function then checks if the recursion limit is reached.  If this is the
   case, a :exc:`RuntimeError` is set and a nonzero value is returned.
   Otherwise, zero is returned.

   *where* should be a string such as ``" in instance check"`` to be
   concatenated to the :exc:`RuntimeError` message caused by the recursion depth
   limit.

.. c:function:: void Py_LeaveRecursiveCall()

   Ends a :c:func:`Py_EnterRecursiveCall`.  Must be called once for each
   *successful* invocation of :c:func:`Py_EnterRecursiveCall`.


.. _standardexceptions:

Standard Exceptions
===================

All standard Python exceptions are available as global variables whose names are
``PyExc_`` followed by the Python exception name.  These have the type
:c:type:`PyObject\*`; they are all class objects.  For completeness, here are all
the variables:

.. index::
   single: PyExc_BaseException
   single: PyExc_Exception
   single: PyExc_StandardError
   single: PyExc_ArithmeticError
   single: PyExc_AssertionError
   single: PyExc_AttributeError
   single: PyExc_BufferError
   single: PyExc_EnvironmentError
   single: PyExc_EOFError
   single: PyExc_FloatingPointError
   single: PyExc_GeneratorExit
   single: PyExc_ImportError
   single: PyExc_IndentationError
   single: PyExc_IndexError
   single: PyExc_IOError
   single: PyExc_KeyError
   single: PyExc_KeyboardInterrupt
   single: PyExc_LookupError
   single: PyExc_MemoryError
   single: PyExc_NameError
   single: PyExc_NotImplementedError
   single: PyExc_OSError
   single: PyExc_OverflowError
   single: PyExc_ReferenceError
   single: PyExc_RuntimeError
   single: PyExc_StopIteration
   single: PyExc_SyntaxError
   single: PyExc_SystemError
   single: PyExc_SystemExit
   single: PyExc_TabError
   single: PyExc_TypeError
   single: PyExc_UnboundLocalError
   single: PyExc_UnicodeDecodeError
   single: PyExc_UnicodeEncodeError
   single: PyExc_UnicodeError
   single: PyExc_UnicodeTranslateError
   single: PyExc_VMSError
   single: PyExc_ValueError
   single: PyExc_WindowsError
   single: PyExc_ZeroDivisionError

+-----------------------------------------+---------------------------------+----------+
| C Name                                  | Python Name                     | Notes    |
+=========================================+=================================+==========+
| :c:data:`PyExc_BaseException`           | :exc:`BaseException`            | (1), (4) |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_Exception`               | :exc:`Exception`                | \(1)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_StandardError`           | :exc:`StandardError`            | \(1)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ArithmeticError`         | :exc:`ArithmeticError`          | \(1)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_AssertionError`          | :exc:`AssertionError`           |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_AttributeError`          | :exc:`AttributeError`           |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_BufferError`             | :exc:`BufferError`              |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_EnvironmentError`        | :exc:`EnvironmentError`         | \(1)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_EOFError`                | :exc:`EOFError`                 |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_FloatingPointError`      | :exc:`FloatingPointError`       |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_GeneratorExit`           | :exc:`GeneratorExit`            |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ImportError`             | :exc:`ImportError`              |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_IndentationError`        | :exc:`IndentationError`         |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_IndexError`              | :exc:`IndexError`               |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_IOError`                 | :exc:`IOError`                  |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_KeyError`                | :exc:`KeyError`                 |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_KeyboardInterrupt`       | :exc:`KeyboardInterrupt`        |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_LookupError`             | :exc:`LookupError`              | \(1)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_MemoryError`             | :exc:`MemoryError`              |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_NameError`               | :exc:`NameError`                |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_NotImplementedError`     | :exc:`NotImplementedError`      |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_OSError`                 | :exc:`OSError`                  |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_OverflowError`           | :exc:`OverflowError`            |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ReferenceError`          | :exc:`ReferenceError`           | \(2)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_RuntimeError`            | :exc:`RuntimeError`             |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_StopIteration`           | :exc:`StopIteration`            |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_SyntaxError`             | :exc:`SyntaxError`              |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_SystemError`             | :exc:`SystemError`              |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_SystemExit`              | :exc:`SystemExit`               |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_TabError`                | :exc:`TabError`                 |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_TypeError`               | :exc:`TypeError`                |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnboundLocalError`       | :exc:`UnboundLocalError`        |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnicodeDecodeError`      | :exc:`UnicodeDecodeError`       |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnicodeEncodeError`      | :exc:`UnicodeEncodeError`       |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnicodeError`            | :exc:`UnicodeError`             |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnicodeTranslateError`   | :exc:`UnicodeTranslateError`    |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_VMSError`                | :exc:`VMSError`                 | \(5)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ValueError`              | :exc:`ValueError`               |          |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_WindowsError`            | :exc:`WindowsError`             | \(3)     |
+-----------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ZeroDivisionError`       | :exc:`ZeroDivisionError`        |          |
+-----------------------------------------+---------------------------------+----------+

Notes:

(1)
   This is a base class for other standard exceptions.

(2)
   This is the same as :exc:`weakref.ReferenceError`.

(3)
   Only defined on Windows; protect code that uses this by testing that the
   preprocessor macro ``MS_WINDOWS`` is defined.

(4)
   .. versionadded:: 2.5

(5)
   Only defined on VMS; protect code that uses this by testing that the
   preprocessor macro ``__VMS`` is defined.

.. _standardwarningcategories:

Standard Warning Categories
===========================

All standard Python warning categories are available as global variables whose
names are ``PyExc_`` followed by the Python exception name. These have the type
:c:type:`PyObject\*`; they are all class objects. For completeness, here are all
the variables:

.. index::
   single: PyExc_Warning
   single: PyExc_BytesWarning
   single: PyExc_DeprecationWarning
   single: PyExc_FutureWarning
   single: PyExc_ImportWarning
   single: PyExc_PendingDeprecationWarning
   single: PyExc_RuntimeWarning
   single: PyExc_SyntaxWarning
   single: PyExc_UnicodeWarning
   single: PyExc_UserWarning

+------------------------------------------+---------------------------------+----------+
| C Name                                   | Python Name                     | Notes    |
+==========================================+=================================+==========+
| :c:data:`PyExc_Warning`                  | :exc:`Warning`                  | \(1)     |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_BytesWarning`             | :exc:`BytesWarning`             |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_DeprecationWarning`       | :exc:`DeprecationWarning`       |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_FutureWarning`            | :exc:`FutureWarning`            |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_ImportWarning`            | :exc:`ImportWarning`            |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_PendingDeprecationWarning`| :exc:`PendingDeprecationWarning`|          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_RuntimeWarning`           | :exc:`RuntimeWarning`           |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_SyntaxWarning`            | :exc:`SyntaxWarning`            |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UnicodeWarning`           | :exc:`UnicodeWarning`           |          |
+------------------------------------------+---------------------------------+----------+
| :c:data:`PyExc_UserWarning`              | :exc:`UserWarning`              |          |
+------------------------------------------+---------------------------------+----------+

Notes:

(1)
   This is a base class for other standard warning categories.

String Exceptions
=================

.. versionchanged:: 2.6
   All exceptions to be raised or caught must be derived from :exc:`BaseException`.
   Trying to raise a string exception now raises :exc:`TypeError`.
PK	%�\��~/66 html/_sources/c-api/file.rst.txtnu�[���.. highlightlang:: c

.. _fileobjects:

File Objects
------------

.. index:: object: file

Python's built-in file objects are implemented entirely on the :c:type:`FILE\*`
support from the C standard library.  This is an implementation detail and may
change in future releases of Python.


.. c:type:: PyFileObject

   This subtype of :c:type:`PyObject` represents a Python file object.


.. c:var:: PyTypeObject PyFile_Type

   .. index:: single: FileType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python file type.  This is
   exposed to Python programs as ``file`` and ``types.FileType``.


.. c:function:: int PyFile_Check(PyObject *p)

   Return true if its argument is a :c:type:`PyFileObject` or a subtype of
   :c:type:`PyFileObject`.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyFile_CheckExact(PyObject *p)

   Return true if its argument is a :c:type:`PyFileObject`, but not a subtype of
   :c:type:`PyFileObject`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyFile_FromString(char *filename, char *mode)

   .. index:: single: fopen()

   On success, return a new file object that is opened on the file given by
   *filename*, with a file mode given by *mode*, where *mode* has the same
   semantics as the standard C routine :c:func:`fopen`.  On failure, return *NULL*.


.. c:function:: PyObject* PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE*))

   Create a new :c:type:`PyFileObject` from the already-open standard C file
   pointer, *fp*.  The function *close* will be called when the file should be
   closed.  Return *NULL* and close the file using *close* on failure.
   *close* is optional and can be set to *NULL*.


.. c:function:: FILE* PyFile_AsFile(PyObject \*p)

   Return the file object associated with *p* as a :c:type:`FILE\*`.

   If the caller will ever use the returned :c:type:`FILE\*` object while
   the :term:`GIL` is released it must also call the :c:func:`PyFile_IncUseCount` and
   :c:func:`PyFile_DecUseCount` functions described below as appropriate.


.. c:function:: void PyFile_IncUseCount(PyFileObject \*p)

   Increments the PyFileObject's internal use count to indicate
   that the underlying :c:type:`FILE\*` is being used.
   This prevents Python from calling f_close() on it from another thread.
   Callers of this must call :c:func:`PyFile_DecUseCount` when they are
   finished with the :c:type:`FILE\*`.  Otherwise the file object will
   never be closed by Python.

   The :term:`GIL` must be held while calling this function.

   The suggested use is to call this after :c:func:`PyFile_AsFile` and before
   you release the GIL::

      FILE *fp = PyFile_AsFile(p);
      PyFile_IncUseCount(p);
      /* ... */
      Py_BEGIN_ALLOW_THREADS
      do_something(fp);
      Py_END_ALLOW_THREADS
      /* ... */
      PyFile_DecUseCount(p);

   .. versionadded:: 2.6


.. c:function:: void PyFile_DecUseCount(PyFileObject \*p)

   Decrements the PyFileObject's internal unlocked_count member to
   indicate that the caller is done with its own use of the :c:type:`FILE\*`.
   This may only be called to undo a prior call to :c:func:`PyFile_IncUseCount`.

   The :term:`GIL` must be held while calling this function (see the example
   above).

   .. versionadded:: 2.6


.. c:function:: PyObject* PyFile_GetLine(PyObject *p, int n)

   .. index:: single: EOFError (built-in exception)

   Equivalent to ``p.readline([n])``, this function reads one line from the
   object *p*.  *p* may be a file object or any object with a
   :meth:`~io.IOBase.readline`
   method.  If *n* is ``0``, exactly one line is read, regardless of the length of
   the line.  If *n* is greater than ``0``, no more than *n* bytes will be read
   from the file; a partial line can be returned.  In both cases, an empty string
   is returned if the end of the file is reached immediately.  If *n* is less than
   ``0``, however, one line is read regardless of length, but :exc:`EOFError` is
   raised if the end of the file is reached immediately.


.. c:function:: PyObject* PyFile_Name(PyObject *p)

   Return the name of the file specified by *p* as a string object.


.. c:function:: void PyFile_SetBufSize(PyFileObject *p, int n)

   .. index:: single: setvbuf()

   Available on systems with :c:func:`setvbuf` only.  This should only be called
   immediately after file object creation.


.. c:function:: int PyFile_SetEncoding(PyFileObject *p, const char *enc)

   Set the file's encoding for Unicode output to *enc*. Return ``1`` on success and ``0``
   on failure.

   .. versionadded:: 2.3


.. c:function:: int PyFile_SetEncodingAndErrors(PyFileObject *p, const char *enc, *errors)

   Set the file's encoding for Unicode output to *enc*, and its error
   mode to *err*. Return ``1`` on success and ``0`` on failure.

   .. versionadded:: 2.6


.. c:function:: int PyFile_SoftSpace(PyObject *p, int newflag)

   .. index:: single: softspace (file attribute)

   This function exists for internal use by the interpreter.  Set the
   :attr:`softspace` attribute of *p* to *newflag* and return the previous value.
   *p* does not have to be a file object for this function to work properly; any
   object is supported (thought its only interesting if the :attr:`softspace`
   attribute can be set).  This function clears any errors, and will return ``0``
   as the previous value if the attribute either does not exist or if there were
   errors in retrieving it.  There is no way to detect errors from this function,
   but doing so should not be needed.


.. c:function:: int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)

   .. index:: single: Py_PRINT_RAW

   Write object *obj* to file object *p*.  The only supported flag for *flags* is
   :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
   instead of the :func:`repr`.  Return ``0`` on success or ``-1`` on failure; the
   appropriate exception will be set.


.. c:function:: int PyFile_WriteString(const char *s, PyObject *p)

   Write string *s* to file object *p*.  Return ``0`` on success or ``-1`` on
   failure; the appropriate exception will be set.
PK	%�\�J�+
+
!html/_sources/c-api/float.rst.txtnu�[���.. highlightlang:: c

.. _floatobjects:

Floating Point Objects
----------------------

.. index:: object: floating point


.. c:type:: PyFloatObject

   This subtype of :c:type:`PyObject` represents a Python floating point object.


.. c:var:: PyTypeObject PyFloat_Type

   .. index:: single: FloatType (in modules types)

   This instance of :c:type:`PyTypeObject` represents the Python floating point
   type.  This is the same object as ``float`` and ``types.FloatType``.


.. c:function:: int PyFloat_Check(PyObject *p)

   Return true if its argument is a :c:type:`PyFloatObject` or a subtype of
   :c:type:`PyFloatObject`.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyFloat_CheckExact(PyObject *p)

   Return true if its argument is a :c:type:`PyFloatObject`, but not a subtype of
   :c:type:`PyFloatObject`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyFloat_FromString(PyObject *str, char **pend)

   Create a :c:type:`PyFloatObject` object based on the string value in *str*, or
   *NULL* on failure.  The *pend* argument is ignored.  It remains only for
   backward compatibility.


.. c:function:: PyObject* PyFloat_FromDouble(double v)

   Create a :c:type:`PyFloatObject` object from *v*, or *NULL* on failure.


.. c:function:: double PyFloat_AsDouble(PyObject *pyfloat)

   Return a C :c:type:`double` representation of the contents of *pyfloat*.  If
   *pyfloat* is not a Python floating point object but has a :meth:`__float__`
   method, this method will first be called to convert *pyfloat* into a float.
   This method returns ``-1.0`` upon failure, so one should call
   :c:func:`PyErr_Occurred` to check for errors.


.. c:function:: double PyFloat_AS_DOUBLE(PyObject *pyfloat)

   Return a C :c:type:`double` representation of the contents of *pyfloat*, but
   without error checking.


.. c:function:: PyObject* PyFloat_GetInfo(void)

   Return a structseq instance which contains information about the
   precision, minimum and maximum values of a float. It's a thin wrapper
   around the header file :file:`float.h`.

   .. versionadded:: 2.6


.. c:function:: double PyFloat_GetMax()

   Return the maximum representable finite float *DBL_MAX* as C :c:type:`double`.

   .. versionadded:: 2.6


.. c:function:: double PyFloat_GetMin()

   Return the minimum normalized positive float *DBL_MIN* as C :c:type:`double`.

   .. versionadded:: 2.6


.. c:function:: int PyFloat_ClearFreeList()

   Clear the float free list. Return the number of items that could not
   be freed.

   .. versionadded:: 2.6


.. c:function:: void PyFloat_AsString(char *buf, PyFloatObject *v)

   Convert the argument *v* to a string, using the same rules as
   :func:`str`. The length of *buf* should be at least 100.

   This function is unsafe to call because it writes to a buffer whose
   length it does not know.

   .. deprecated:: 2.7
      Use :func:`PyObject_Str` or :func:`PyOS_double_to_string` instead.


.. c:function:: void PyFloat_AsReprString(char *buf, PyFloatObject *v)

   Same as PyFloat_AsString, except uses the same rules as
   :func:`repr`.  The length of *buf* should be at least 100.

   This function is unsafe to call because it writes to a buffer whose
   length it does not know.

   .. deprecated:: 2.7
      Use :func:`PyObject_Repr` or :func:`PyOS_double_to_string` instead.
PK	%�\��g�u	u	$html/_sources/c-api/function.rst.txtnu�[���.. highlightlang:: c

.. _function-objects:

Function Objects
----------------

.. index:: object: function

There are a few functions specific to Python functions.


.. c:type:: PyFunctionObject

   The C structure used for functions.


.. c:var:: PyTypeObject PyFunction_Type

   .. index:: single: MethodType (in module types)

   This is an instance of :c:type:`PyTypeObject` and represents the Python function
   type.  It is exposed to Python programmers as ``types.FunctionType``.


.. c:function:: int PyFunction_Check(PyObject *o)

   Return true if *o* is a function object (has type :c:data:`PyFunction_Type`).
   The parameter must not be *NULL*.


.. c:function:: PyObject* PyFunction_New(PyObject *code, PyObject *globals)

   Return a new function object associated with the code object *code*. *globals*
   must be a dictionary with the global variables accessible to the function.

   The function's docstring, name and *__module__* are retrieved from the code
   object, the argument defaults and closure are set to *NULL*.


.. c:function:: PyObject* PyFunction_GetCode(PyObject *op)

   Return the code object associated with the function object *op*.


.. c:function:: PyObject* PyFunction_GetGlobals(PyObject *op)

   Return the globals dictionary associated with the function object *op*.


.. c:function:: PyObject* PyFunction_GetModule(PyObject *op)

   Return the *__module__* attribute of the function object *op*. This is normally
   a string containing the module name, but can be set to any other object by
   Python code.


.. c:function:: PyObject* PyFunction_GetDefaults(PyObject *op)

   Return the argument default values of the function object *op*. This can be a
   tuple of arguments or *NULL*.


.. c:function:: int PyFunction_SetDefaults(PyObject *op, PyObject *defaults)

   Set the argument default values for the function object *op*. *defaults* must be
   *Py_None* or a tuple.

   Raises :exc:`SystemError` and returns ``-1`` on failure.


.. c:function:: PyObject* PyFunction_GetClosure(PyObject *op)

   Return the closure associated with the function object *op*. This can be *NULL*
   or a tuple of cell objects.


.. c:function:: int PyFunction_SetClosure(PyObject *op, PyObject *closure)

   Set the closure associated with the function object *op*. *closure* must be
   *Py_None* or a tuple of cell objects.

   Raises :exc:`SystemError` and returns ``-1`` on failure.
PK	%�\X?���%html/_sources/c-api/gcsupport.rst.txtnu�[���.. highlightlang:: c

.. _supporting-cycle-detection:

Supporting Cyclic Garbage Collection
====================================

Python's support for detecting and collecting garbage which involves circular
references requires support from object types which are "containers" for other
objects which may also be containers.  Types which do not store references to
other objects, or which only store references to atomic types (such as numbers
or strings), do not need to provide any explicit support for garbage
collection.

.. An example showing the use of these interfaces can be found in "Supporting the
.. Cycle Collector (XXX not found: ../ext/example-cycle-support.html)".

To create a container type, the :c:member:`~PyTypeObject.tp_flags` field of the type object must
include the :const:`Py_TPFLAGS_HAVE_GC` and provide an implementation of the
:c:member:`~PyTypeObject.tp_traverse` handler.  If instances of the type are mutable, a
:c:member:`~PyTypeObject.tp_clear` implementation must also be provided.


.. data:: Py_TPFLAGS_HAVE_GC
   :noindex:

   Objects with a type with this flag set must conform with the rules
   documented here.  For convenience these objects will be referred to as
   container objects.

Constructors for container types must conform to two rules:

#. The memory for the object must be allocated using :c:func:`PyObject_GC_New`
   or :c:func:`PyObject_GC_NewVar`.

#. Once all the fields which may contain references to other containers are
   initialized, it must call :c:func:`PyObject_GC_Track`.


.. c:function:: TYPE* PyObject_GC_New(TYPE, PyTypeObject *type)

   Analogous to :c:func:`PyObject_New` but for container objects with the
   :const:`Py_TPFLAGS_HAVE_GC` flag set.


.. c:function:: TYPE* PyObject_GC_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)

   Analogous to :c:func:`PyObject_NewVar` but for container objects with the
   :const:`Py_TPFLAGS_HAVE_GC` flag set.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: TYPE* PyObject_GC_Resize(TYPE, PyVarObject *op, Py_ssize_t newsize)

   Resize an object allocated by :c:func:`PyObject_NewVar`.  Returns the
   resized object or *NULL* on failure.  *op* must not be tracked by the collector yet.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *newsize*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: void PyObject_GC_Track(PyObject *op)

   Adds the object *op* to the set of container objects tracked by the
   collector.  The collector can run at unexpected times so objects must be
   valid while being tracked.  This should be called once all the fields
   followed by the :c:member:`~PyTypeObject.tp_traverse` handler become valid, usually near the
   end of the constructor.


.. c:function:: void _PyObject_GC_TRACK(PyObject *op)

   A macro version of :c:func:`PyObject_GC_Track`.  It should not be used for
   extension modules.

Similarly, the deallocator for the object must conform to a similar pair of
rules:

#. Before fields which refer to other containers are invalidated,
   :c:func:`PyObject_GC_UnTrack` must be called.

#. The object's memory must be deallocated using :c:func:`PyObject_GC_Del`.


.. c:function:: void PyObject_GC_Del(void *op)

   Releases memory allocated to an object using :c:func:`PyObject_GC_New` or
   :c:func:`PyObject_GC_NewVar`.


.. c:function:: void PyObject_GC_UnTrack(void *op)

   Remove the object *op* from the set of container objects tracked by the
   collector.  Note that :c:func:`PyObject_GC_Track` can be called again on
   this object to add it back to the set of tracked objects.  The deallocator
   (:c:member:`~PyTypeObject.tp_dealloc` handler) should call this for the object before any of
   the fields used by the :c:member:`~PyTypeObject.tp_traverse` handler become invalid.


.. c:function:: void _PyObject_GC_UNTRACK(PyObject *op)

   A macro version of :c:func:`PyObject_GC_UnTrack`.  It should not be used for
   extension modules.

The :c:member:`~PyTypeObject.tp_traverse` handler accepts a function parameter of this type:


.. c:type:: int (*visitproc)(PyObject *object, void *arg)

   Type of the visitor function passed to the :c:member:`~PyTypeObject.tp_traverse` handler.
   The function should be called with an object to traverse as *object* and
   the third parameter to the :c:member:`~PyTypeObject.tp_traverse` handler as *arg*.  The
   Python core uses several visitor functions to implement cyclic garbage
   detection; it's not expected that users will need to write their own
   visitor functions.

The :c:member:`~PyTypeObject.tp_traverse` handler must have the following type:


.. c:type:: int (*traverseproc)(PyObject *self, visitproc visit, void *arg)

   Traversal function for a container object.  Implementations must call the
   *visit* function for each object directly contained by *self*, with the
   parameters to *visit* being the contained object and the *arg* value passed
   to the handler.  The *visit* function must not be called with a *NULL*
   object argument.  If *visit* returns a non-zero value that value should be
   returned immediately.

To simplify writing :c:member:`~PyTypeObject.tp_traverse` handlers, a :c:func:`Py_VISIT` macro is
provided.  In order to use this macro, the :c:member:`~PyTypeObject.tp_traverse` implementation
must name its arguments exactly *visit* and *arg*:


.. c:function:: void Py_VISIT(PyObject *o)

   If *o* is not *NULL*, call the *visit* callback, with arguments *o*
   and *arg*.  If *visit* returns a non-zero value, then return it.
   Using this macro, :c:member:`~PyTypeObject.tp_traverse` handlers
   look like::

      static int
      my_traverse(Noddy *self, visitproc visit, void *arg)
      {
          Py_VISIT(self->foo);
          Py_VISIT(self->bar);
          return 0;
      }

   .. versionadded:: 2.4

The :c:member:`~PyTypeObject.tp_clear` handler must be of the :c:type:`inquiry` type, or *NULL*
if the object is immutable.


.. c:type:: int (*inquiry)(PyObject *self)

   Drop references that may have created reference cycles.  Immutable objects
   do not have to define this method since they can never directly create
   reference cycles.  Note that the object must still be valid after calling
   this method (don't just call :c:func:`Py_DECREF` on a reference).  The
   collector will call this method if it detects that this object is involved
   in a reference cycle.
PK	%�\���E��html/_sources/c-api/gen.rst.txtnu�[���.. highlightlang:: c

.. _gen-objects:

Generator Objects
-----------------

Generator objects are what Python uses to implement generator iterators. They
are normally created by iterating over a function that yields values, rather
than explicitly calling :c:func:`PyGen_New`.


.. c:type:: PyGenObject

   The C structure used for generator objects.


.. c:var:: PyTypeObject PyGen_Type

   The type object corresponding to generator objects.


.. c:function:: int PyGen_Check(ob)

   Return true if *ob* is a generator object; *ob* must not be *NULL*.


.. c:function:: int PyGen_CheckExact(ob)

   Return true if *ob*'s type is *PyGen_Type* is a generator object; *ob* must not
   be *NULL*.


.. c:function:: PyObject* PyGen_New(PyFrameObject *frame)

   Create and return a new generator object based on the *frame* object. A
   reference to *frame* is stolen by this function. The parameter must not be
   *NULL*.
PK	%�\@i1�+�+"html/_sources/c-api/import.rst.txtnu�[���.. highlightlang:: c

.. _importing:

Importing Modules
=================


.. c:function:: PyObject* PyImport_ImportModule(const char *name)

   .. index::
      single: package variable; __all__
      single: __all__ (package variable)
      single: modules (in module sys)

   This is a simplified interface to :c:func:`PyImport_ImportModuleEx` below,
   leaving the *globals* and *locals* arguments set to *NULL* and *level* set
   to 0.  When the *name*
   argument contains a dot (when it specifies a submodule of a package), the
   *fromlist* argument is set to the list ``['*']`` so that the return value is the
   named module rather than the top-level package containing it as would otherwise
   be the case.  (Unfortunately, this has an additional side effect when *name* in
   fact specifies a subpackage instead of a submodule: the submodules specified in
   the package's ``__all__`` variable are  loaded.)  Return a new reference to the
   imported module, or *NULL* with an exception set on failure.  Before Python 2.4,
   the module may still be created in the failure case --- examine ``sys.modules``
   to find out.  Starting with Python 2.4, a failing import of a module no longer
   leaves the module in ``sys.modules``.

   .. versionchanged:: 2.4
      Failing imports remove incomplete module objects.

   .. versionchanged:: 2.6
      Always uses absolute imports.


.. c:function:: PyObject* PyImport_ImportModuleNoBlock(const char *name)

   This version of :c:func:`PyImport_ImportModule` does not block. It's intended
   to be used in C functions that import other modules to execute a function.
   The import may block if another thread holds the import lock. The function
   :c:func:`PyImport_ImportModuleNoBlock` never blocks. It first tries to fetch
   the module from sys.modules and falls back to :c:func:`PyImport_ImportModule`
   unless the lock is held, in which case the function will raise an
   :exc:`ImportError`.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist)

   .. index:: builtin: __import__

   Import a module.  This is best described by referring to the built-in Python
   function :func:`__import__`, as the standard :func:`__import__` function calls
   this function directly.

   The return value is a new reference to the imported module or top-level package,
   or *NULL* with an exception set on failure (before Python 2.4, the module may
   still be created in this case).  Like for :func:`__import__`, the return value
   when a submodule of a package was requested is normally the top-level package,
   unless a non-empty *fromlist* was given.

   .. versionchanged:: 2.4
      Failing imports remove incomplete module objects.

   .. versionchanged:: 2.6
      The function is an alias for :c:func:`PyImport_ImportModuleLevel` with
      ``-1`` as level, meaning relative import.


.. c:function:: PyObject* PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals, PyObject *fromlist, int level)

   Import a module.  This is best described by referring to the built-in Python
   function :func:`__import__`, as the standard :func:`__import__` function calls
   this function directly.

   The return value is a new reference to the imported module or top-level package,
   or *NULL* with an exception set on failure.  Like for :func:`__import__`,
   the return value when a submodule of a package was requested is normally the
   top-level package, unless a non-empty *fromlist* was given.

   .. versionadded:: 2.5


.. c:function:: PyObject* PyImport_Import(PyObject *name)

   .. index::
      module: rexec
      module: ihooks

   This is a higher-level interface that calls the current "import hook function".
   It invokes the :func:`__import__` function from the ``__builtins__`` of the
   current globals.  This means that the import is done using whatever import hooks
   are installed in the current environment, e.g. by :mod:`rexec` or :mod:`ihooks`.

   .. versionchanged:: 2.6
      Always uses absolute imports.


.. c:function:: PyObject* PyImport_ReloadModule(PyObject *m)

   .. index:: builtin: reload

   Reload a module.  This is best described by referring to the built-in Python
   function :func:`reload`, as the standard :func:`reload` function calls this
   function directly.  Return a new reference to the reloaded module, or *NULL*
   with an exception set on failure (the module still exists in this case).


.. c:function:: PyObject* PyImport_AddModule(const char *name)

   Return the module object corresponding to a module name.  The *name* argument
   may be of the form ``package.module``. First check the modules dictionary if
   there's one there, and if not, create a new one and insert it in the modules
   dictionary. Return *NULL* with an exception set on failure.

   .. note::

      This function does not load or import the module; if the module wasn't already
      loaded, you will get an empty module object. Use :c:func:`PyImport_ImportModule`
      or one of its variants to import a module.  Package structures implied by a
      dotted name for *name* are not created if not already present.


.. c:function:: PyObject* PyImport_ExecCodeModule(char *name, PyObject *co)

   .. index:: builtin: compile

   Given a module name (possibly of the form ``package.module``) and a code object
   read from a Python bytecode file or obtained from the built-in function
   :func:`compile`, load the module.  Return a new reference to the module object,
   or *NULL* with an exception set if an error occurred.  Before Python 2.4, the
   module could still be created in error cases.  Starting with Python 2.4, *name*
   is removed from :attr:`sys.modules` in error cases, and even if *name* was already
   in :attr:`sys.modules` on entry to :c:func:`PyImport_ExecCodeModule`.  Leaving
   incompletely initialized modules in :attr:`sys.modules` is dangerous, as imports of
   such modules have no way to know that the module object is an unknown (and
   probably damaged with respect to the module author's intents) state.

   The module's :attr:`__file__` attribute will be set to the code object's
   :c:member:`co_filename`.

   This function will reload the module if it was already imported.  See
   :c:func:`PyImport_ReloadModule` for the intended way to reload a module.

   If *name* points to a dotted name of the form ``package.module``, any package
   structures not already created will still not be created.

   .. versionchanged:: 2.4
      *name* is removed from :attr:`sys.modules` in error cases.


.. c:function:: PyObject* PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)

   Like :c:func:`PyImport_ExecCodeModule`, but the :attr:`__file__` attribute of
   the module object is set to *pathname* if it is non-``NULL``.


.. c:function:: long PyImport_GetMagicNumber()

   Return the magic number for Python bytecode files (a.k.a. :file:`.pyc` and
   :file:`.pyo` files).  The magic number should be present in the first four bytes
   of the bytecode file, in little-endian byte order.


.. c:function:: PyObject* PyImport_GetModuleDict()

   Return the dictionary used for the module administration (a.k.a.
   ``sys.modules``).  Note that this is a per-interpreter variable.


.. c:function:: PyObject* PyImport_GetImporter(PyObject *path)

   Return an importer object for a :data:`sys.path`/:attr:`pkg.__path__` item
   *path*, possibly by fetching it from the :data:`sys.path_importer_cache`
   dict.  If it wasn't yet cached, traverse :data:`sys.path_hooks` until a hook
   is found that can handle the path item.  Return ``None`` if no hook could;
   this tells our caller it should fall back to the built-in import mechanism.
   Cache the result in :data:`sys.path_importer_cache`.  Return a new reference
   to the importer object.

   .. versionadded:: 2.6


.. c:function:: void _PyImport_Init()

   Initialize the import mechanism.  For internal use only.


.. c:function:: void PyImport_Cleanup()

   Empty the module table.  For internal use only.


.. c:function:: void _PyImport_Fini()

   Finalize the import mechanism.  For internal use only.


.. c:function:: PyObject* _PyImport_FindExtension(char *, char *)

   For internal use only.


.. c:function:: PyObject* _PyImport_FixupExtension(char *, char *)

   For internal use only.


.. c:function:: int PyImport_ImportFrozenModule(char *name)

   Load a frozen module named *name*.  Return ``1`` for success, ``0`` if the
   module is not found, and ``-1`` with an exception set if the initialization
   failed.  To access the imported module on a successful load, use
   :c:func:`PyImport_ImportModule`.  (Note the misnomer --- this function would
   reload the module if it was already imported.)


.. c:type:: struct _frozen

   .. index:: single: freeze utility

   This is the structure type definition for frozen module descriptors, as
   generated by the :program:`freeze` utility (see :file:`Tools/freeze/` in the
   Python source distribution).  Its definition, found in :file:`Include/import.h`,
   is::

      struct _frozen {
          char *name;
          unsigned char *code;
          int size;
      };


.. c:var:: struct _frozen* PyImport_FrozenModules

   This pointer is initialized to point to an array of :c:type:`struct _frozen`
   records, terminated by one whose members are all *NULL* or zero.  When a frozen
   module is imported, it is searched in this table.  Third-party code could play
   tricks with this to provide a dynamically created collection of frozen modules.


.. c:function:: int PyImport_AppendInittab(const char *name, void (*initfunc)(void))

   Add a single module to the existing table of built-in modules.  This is a
   convenience wrapper around :c:func:`PyImport_ExtendInittab`, returning ``-1`` if
   the table could not be extended.  The new module can be imported by the name
   *name*, and uses the function *initfunc* as the initialization function called
   on the first attempted import.  This should be called before
   :c:func:`Py_Initialize`.


.. c:type:: struct _inittab

   Structure describing a single entry in the list of built-in modules.  Each of
   these structures gives the name and initialization function for a module built
   into the interpreter.  Programs which embed Python may use an array of these
   structures in conjunction with :c:func:`PyImport_ExtendInittab` to provide
   additional built-in modules.  The structure is defined in
   :file:`Include/import.h` as::

      struct _inittab {
          char *name;
          void (*initfunc)(void);
      };


.. c:function:: int PyImport_ExtendInittab(struct _inittab *newtab)

   Add a collection of modules to the table of built-in modules.  The *newtab*
   array must end with a sentinel entry which contains *NULL* for the :attr:`name`
   field; failure to provide the sentinel value can result in a memory fault.
   Returns ``0`` on success or ``-1`` if insufficient memory could be allocated to
   extend the internal table.  In the event of failure, no modules are added to the
   internal table.  This should be called before :c:func:`Py_Initialize`.
PK	%�\�~V.BB!html/_sources/c-api/index.rst.txtnu�[���.. _c-api-index:

##################################
  Python/C API Reference Manual
##################################

This manual documents the API used by C and C++ programmers who want to write
extension modules or embed Python.  It is a companion to :ref:`extending-index`,
which describes the general principles of extension writing but does not
document the API functions in detail.

.. toctree::
   :maxdepth: 2

   intro.rst
   veryhigh.rst
   refcounting.rst
   exceptions.rst
   utilities.rst
   abstract.rst
   concrete.rst
   init.rst
   memory.rst
   objimpl.rst
PK	%�\�T6��� html/_sources/c-api/init.rst.txtnu�[���.. highlightlang:: c


.. _initialization:

*****************************************
Initialization, Finalization, and Threads
*****************************************


Initializing and finalizing the interpreter
===========================================


.. c:function:: void Py_Initialize()

   .. index::
      single: Py_SetProgramName()
      single: PyEval_InitThreads()
      single: PyEval_ReleaseLock()
      single: PyEval_AcquireLock()
      single: modules (in module sys)
      single: path (in module sys)
      module: __builtin__
      module: __main__
      module: sys
      triple: module; search; path
      single: PySys_SetArgv()
      single: PySys_SetArgvEx()
      single: Py_Finalize()

   Initialize the Python interpreter.  In an application embedding  Python, this
   should be called before using any other Python/C API functions; with the
   exception of :c:func:`Py_SetProgramName`, :c:func:`Py_SetPythonHome`, :c:func:`PyEval_InitThreads`,
   :c:func:`PyEval_ReleaseLock`, and :c:func:`PyEval_AcquireLock`. This initializes
   the table of loaded modules (``sys.modules``), and creates the fundamental
   modules :mod:`__builtin__`, :mod:`__main__` and :mod:`sys`.  It also initializes
   the module search path (``sys.path``). It does not set ``sys.argv``; use
   :c:func:`PySys_SetArgvEx` for that.  This is a no-op when called for a second time
   (without calling :c:func:`Py_Finalize` first).  There is no return value; it is a
   fatal error if the initialization fails.


.. c:function:: void Py_InitializeEx(int initsigs)

   This function works like :c:func:`Py_Initialize` if *initsigs* is ``1``. If
   *initsigs* is ``0``, it skips initialization registration of signal handlers, which
   might be useful when Python is embedded.

   .. versionadded:: 2.4


.. c:function:: int Py_IsInitialized()

   Return true (nonzero) when the Python interpreter has been initialized, false
   (zero) if not.  After :c:func:`Py_Finalize` is called, this returns false until
   :c:func:`Py_Initialize` is called again.


.. c:function:: void Py_Finalize()

   Undo all initializations made by :c:func:`Py_Initialize` and subsequent use of
   Python/C API functions, and destroy all sub-interpreters (see
   :c:func:`Py_NewInterpreter` below) that were created and not yet destroyed since
   the last call to :c:func:`Py_Initialize`.  Ideally, this frees all memory
   allocated by the Python interpreter.  This is a no-op when called for a second
   time (without calling :c:func:`Py_Initialize` again first).  There is no return
   value; errors during finalization are ignored.

   This function is provided for a number of reasons.  An embedding application
   might want to restart Python without having to restart the application itself.
   An application that has loaded the Python interpreter from a dynamically
   loadable library (or DLL) might want to free all memory allocated by Python
   before unloading the DLL. During a hunt for memory leaks in an application a
   developer might want to free all memory allocated by Python before exiting from
   the application.

   **Bugs and caveats:** The destruction of modules and objects in modules is done
   in random order; this may cause destructors (:meth:`__del__` methods) to fail
   when they depend on other objects (even functions) or modules.  Dynamically
   loaded extension modules loaded by Python are not unloaded.  Small amounts of
   memory allocated by the Python interpreter may not be freed (if you find a leak,
   please report it).  Memory tied up in circular references between objects is not
   freed.  Some memory allocated by extension modules may not be freed.  Some
   extensions may not work properly if their initialization routine is called more
   than once; this can happen if an application calls :c:func:`Py_Initialize` and
   :c:func:`Py_Finalize` more than once.


Process-wide parameters
=======================


.. c:function:: void Py_SetProgramName(char *name)

   .. index::
      single: Py_Initialize()
      single: main()
      single: Py_GetPath()

   This function should be called before :c:func:`Py_Initialize` is called for
   the first time, if it is called at all.  It tells the interpreter the value
   of the ``argv[0]`` argument to the :c:func:`main` function of the program.
   This is used by :c:func:`Py_GetPath` and some other functions below to find
   the Python run-time libraries relative to the interpreter executable.  The
   default value is ``'python'``.  The argument should point to a
   zero-terminated character string in static storage whose contents will not
   change for the duration of the program's execution.  No code in the Python
   interpreter will change the contents of this storage.


.. c:function:: char* Py_GetProgramName()

   .. index:: single: Py_SetProgramName()

   Return the program name set with :c:func:`Py_SetProgramName`, or the default.
   The returned string points into static storage; the caller should not modify its
   value.


.. c:function:: char* Py_GetPrefix()

   Return the *prefix* for installed platform-independent files. This is derived
   through a number of complicated rules from the program name set with
   :c:func:`Py_SetProgramName` and some environment variables; for example, if the
   program name is ``'/usr/local/bin/python'``, the prefix is ``'/usr/local'``. The
   returned string points into static storage; the caller should not modify its
   value.  This corresponds to the :makevar:`prefix` variable in the top-level
   :file:`Makefile` and the ``--prefix`` argument to the :program:`configure`
   script at build time.  The value is available to Python code as ``sys.prefix``.
   It is only useful on Unix.  See also the next function.


.. c:function:: char* Py_GetExecPrefix()

   Return the *exec-prefix* for installed platform-*dependent* files.  This is
   derived through a number of complicated rules from the program name set with
   :c:func:`Py_SetProgramName` and some environment variables; for example, if the
   program name is ``'/usr/local/bin/python'``, the exec-prefix is
   ``'/usr/local'``.  The returned string points into static storage; the caller
   should not modify its value.  This corresponds to the :makevar:`exec_prefix`
   variable in the top-level :file:`Makefile` and the ``--exec-prefix``
   argument to the :program:`configure` script at build  time.  The value is
   available to Python code as ``sys.exec_prefix``.  It is only useful on Unix.

   Background: The exec-prefix differs from the prefix when platform dependent
   files (such as executables and shared libraries) are installed in a different
   directory tree.  In a typical installation, platform dependent files may be
   installed in the :file:`/usr/local/plat` subtree while platform independent may
   be installed in :file:`/usr/local`.

   Generally speaking, a platform is a combination of hardware and software
   families, e.g.  Sparc machines running the Solaris 2.x operating system are
   considered the same platform, but Intel machines running Solaris 2.x are another
   platform, and Intel machines running Linux are yet another platform.  Different
   major revisions of the same operating system generally also form different
   platforms.  Non-Unix operating systems are a different story; the installation
   strategies on those systems are so different that the prefix and exec-prefix are
   meaningless, and set to the empty string. Note that compiled Python bytecode
   files are platform independent (but not independent from the Python version by
   which they were compiled!).

   System administrators will know how to configure the :program:`mount` or
   :program:`automount` programs to share :file:`/usr/local` between platforms
   while having :file:`/usr/local/plat` be a different filesystem for each
   platform.


.. c:function:: char* Py_GetProgramFullPath()

   .. index::
      single: Py_SetProgramName()
      single: executable (in module sys)

   Return the full program name of the Python executable; this is  computed as a
   side-effect of deriving the default module search path  from the program name
   (set by :c:func:`Py_SetProgramName` above). The returned string points into
   static storage; the caller should not modify its value.  The value is available
   to Python code as ``sys.executable``.


.. c:function:: char* Py_GetPath()

   .. index::
      triple: module; search; path
      single: path (in module sys)

   Return the default module search path; this is computed from the program name
   (set by :c:func:`Py_SetProgramName` above) and some environment variables.
   The returned string consists of a series of directory names separated by a
   platform dependent delimiter character.  The delimiter character is ``':'``
   on Unix and Mac OS X, ``';'`` on Windows.  The returned string points into
   static storage; the caller should not modify its value.  The list
   :data:`sys.path` is initialized with this value on interpreter startup; it
   can be (and usually is) modified later to change the search path for loading
   modules.

   .. XXX should give the exact rules


.. c:function:: const char* Py_GetVersion()

   Return the version of this Python interpreter.  This is a string that looks
   something like ::

      "1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]"

   .. index:: single: version (in module sys)

   The first word (up to the first space character) is the current Python version;
   the first three characters are the major and minor version separated by a
   period.  The returned string points into static storage; the caller should not
   modify its value.  The value is available to Python code as ``sys.version``.


.. c:function:: const char* Py_GetPlatform()

   .. index:: single: platform (in module sys)

   Return the platform identifier for the current platform.  On Unix, this is
   formed from the "official" name of the operating system, converted to lower
   case, followed by the major revision number; e.g., for Solaris 2.x, which is
   also known as SunOS 5.x, the value is ``'sunos5'``.  On Mac OS X, it is
   ``'darwin'``.  On Windows, it is ``'win'``.  The returned string points into
   static storage; the caller should not modify its value.  The value is available
   to Python code as ``sys.platform``.


.. c:function:: const char* Py_GetCopyright()

   Return the official copyright string for the current Python version, for example

   ``'Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'``

   .. index:: single: copyright (in module sys)

   The returned string points into static storage; the caller should not modify its
   value.  The value is available to Python code as ``sys.copyright``.


.. c:function:: const char* Py_GetCompiler()

   Return an indication of the compiler used to build the current Python version,
   in square brackets, for example::

      "[GCC 2.7.2.2]"

   .. index:: single: version (in module sys)

   The returned string points into static storage; the caller should not modify its
   value.  The value is available to Python code as part of the variable
   ``sys.version``.


.. c:function:: const char* Py_GetBuildInfo()

   Return information about the sequence number and build date and time  of the
   current Python interpreter instance, for example ::

      "#67, Aug  1 1997, 22:34:28"

   .. index:: single: version (in module sys)

   The returned string points into static storage; the caller should not modify its
   value.  The value is available to Python code as part of the variable
   ``sys.version``.


.. c:function:: void PySys_SetArgvEx(int argc, char **argv, int updatepath)

   .. index::
      single: main()
      single: Py_FatalError()
      single: argv (in module sys)

   Set :data:`sys.argv` based on *argc* and *argv*.  These parameters are
   similar to those passed to the program's :c:func:`main` function with the
   difference that the first entry should refer to the script file to be
   executed rather than the executable hosting the Python interpreter.  If there
   isn't a script that will be run, the first entry in *argv* can be an empty
   string.  If this function fails to initialize :data:`sys.argv`, a fatal
   condition is signalled using :c:func:`Py_FatalError`.

   If *updatepath* is zero, this is all the function does.  If *updatepath*
   is non-zero, the function also modifies :data:`sys.path` according to the
   following algorithm:

   - If the name of an existing script is passed in ``argv[0]``, the absolute
     path of the directory where the script is located is prepended to
     :data:`sys.path`.
   - Otherwise (that is, if *argc* is 0 or ``argv[0]`` doesn't point
     to an existing file name), an empty string is prepended to
     :data:`sys.path`, which is the same as prepending the current working
     directory (``"."``).

   .. note::
      It is recommended that applications embedding the Python interpreter
      for purposes other than executing a single script pass ``0`` as *updatepath*,
      and update :data:`sys.path` themselves if desired.
      See `CVE-2008-5983 <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.

      On versions before 2.6.6, you can achieve the same effect by manually
      popping the first :data:`sys.path` element after having called
      :c:func:`PySys_SetArgv`, for example using::

         PyRun_SimpleString("import sys; sys.path.pop(0)\n");

   .. versionadded:: 2.6.6

   .. XXX impl. doesn't seem consistent in allowing ``0``/``NULL`` for the params;
      check w/ Guido.


.. c:function:: void PySys_SetArgv(int argc, char **argv)

   This function works like :c:func:`PySys_SetArgvEx` with *updatepath* set to ``1``.


.. c:function:: void Py_SetPythonHome(char *home)

   Set the default "home" directory, that is, the location of the standard
   Python libraries.  See :envvar:`PYTHONHOME` for the meaning of the
   argument string.

   The argument should point to a zero-terminated character string in static
   storage whose contents will not change for the duration of the program's
   execution.  No code in the Python interpreter will change the contents of
   this storage.


.. c:function:: char* Py_GetPythonHome()

   Return the default "home", that is, the value set by a previous call to
   :c:func:`Py_SetPythonHome`, or the value of the :envvar:`PYTHONHOME`
   environment variable if it is set.


.. _threads:

Thread State and the Global Interpreter Lock
============================================

.. index::
   single: GIL
   single: global interpreter lock
   single: interpreter lock
   single: lock, interpreter

The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there's a global lock, called the :term:`global
interpreter lock` or :term:`GIL`, that must be held by the current thread before
it can safely access Python objects. Without the lock, even the simplest
operations could cause problems in a multi-threaded program: for example, when
two threads simultaneously increment the reference count of the same object, the
reference count could end up being incremented only once instead of twice.

.. index:: single: setcheckinterval() (in module sys)

Therefore, the rule exists that only the thread that has acquired the
:term:`GIL` may operate on Python objects or call Python/C API functions.
In order to emulate concurrency of execution, the interpreter regularly
tries to switch threads (see :func:`sys.setcheckinterval`).  The lock is also
released around potentially blocking I/O operations like reading or writing
a file, so that other Python threads can run in the meantime.

.. index::
   single: PyThreadState
   single: PyThreadState

The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called :c:type:`PyThreadState`.  There's also one
global variable pointing to the current :c:type:`PyThreadState`: it can
be retrieved using :c:func:`PyThreadState_Get`.

Releasing the GIL from extension code
-------------------------------------

Most extension code manipulating the :term:`GIL` has the following simple
structure::

   Save the thread state in a local variable.
   Release the global interpreter lock.
   ... Do some blocking I/O operation ...
   Reacquire the global interpreter lock.
   Restore the thread state from the local variable.

This is so common that a pair of macros exists to simplify it::

   Py_BEGIN_ALLOW_THREADS
   ... Do some blocking I/O operation ...
   Py_END_ALLOW_THREADS

.. index::
   single: Py_BEGIN_ALLOW_THREADS
   single: Py_END_ALLOW_THREADS

The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
block.  These two macros are still available when Python is compiled without
thread support (they simply have an empty expansion).

When thread support is enabled, the block above expands to the following code::

   PyThreadState *_save;

   _save = PyEval_SaveThread();
   ...Do some blocking I/O operation...
   PyEval_RestoreThread(_save);

.. index::
   single: PyEval_RestoreThread()
   single: PyEval_SaveThread()

Here is how these functions work: the global interpreter lock is used to protect the pointer to the
current thread state.  When releasing the lock and saving the thread state,
the current thread state pointer must be retrieved before the lock is released
(since another thread could immediately acquire the lock and store its own thread
state in the global variable). Conversely, when acquiring the lock and restoring
the thread state, the lock must be acquired before storing the thread state
pointer.

.. note::
   Calling system I/O functions is the most common use case for releasing
   the GIL, but it can also be useful before calling long-running computations
   which don't need access to Python objects, such as compression or
   cryptographic functions operating over memory buffers.  For example, the
   standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
   compressing or hashing data.


.. _gilstate:

Non-Python created threads
--------------------------

When threads are created using the dedicated Python APIs (such as the
:mod:`threading` module), a thread state is automatically associated to them
and the code showed above is therefore correct.  However, when threads are
created from C (for example by a third-party library with its own thread
management), they don't hold the GIL, nor is there a thread state structure
for them.

If you need to call Python code from these threads (often this will be part
of a callback API provided by the aforementioned third-party library),
you must first register these threads with the interpreter by
creating a thread state data structure, then acquiring the GIL, and finally
storing their thread state pointer, before you can start using the Python/C
API.  When you are done, you should reset the thread state pointer, release
the GIL, and finally free the thread state data structure.

The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
all of the above automatically.  The typical idiom for calling into Python
from a C thread is::

   PyGILState_STATE gstate;
   gstate = PyGILState_Ensure();

   /* Perform Python actions here. */
   result = CallSomeFunction();
   /* evaluate result or handle exception */

   /* Release the thread. No Python API allowed beyond this point. */
   PyGILState_Release(gstate);

Note that the :c:func:`PyGILState_\*` functions assume there is only one global
interpreter (created automatically by :c:func:`Py_Initialize`).  Python
supports the creation of additional interpreters (using
:c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
:c:func:`PyGILState_\*` API is unsupported.

Another important thing to note about threads is their behaviour in the face
of the C :c:func:`fork` call. On most systems with :c:func:`fork`, after a
process forks only the thread that issued the fork will exist. That also
means any locks held by other threads will never be released. Python solves
this for :func:`os.fork` by acquiring the locks it uses internally before
the fork, and releasing them afterwards. In addition, it resets any
:ref:`lock-objects` in the child. When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as
:c:func:`pthread_atfork` would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling :c:func:`fork`
directly rather than through :func:`os.fork` (and returning to or calling
into Python) may result in a deadlock by one of Python's internal locks
being held by a thread that is defunct after the fork.
:c:func:`PyOS_AfterFork` tries to reset the necessary locks, but is not
always able to.


High-level API
--------------

These are the most commonly used types and functions when writing C extension
code, or when embedding the Python interpreter:

.. c:type:: PyInterpreterState

   This data structure represents the state shared by a number of cooperating
   threads.  Threads belonging to the same interpreter share their module
   administration and a few other internal items. There are no public members in
   this structure.

   Threads belonging to different interpreters initially share nothing, except
   process state like available memory, open file descriptors and such.  The global
   interpreter lock is also shared by all threads, regardless of to which
   interpreter they belong.


.. c:type:: PyThreadState

   This data structure represents the state of a single thread.  The only public
   data member is :c:type:`PyInterpreterState \*`:attr:`interp`, which points to
   this thread's interpreter state.


.. c:function:: void PyEval_InitThreads()

   .. index::
      single: PyEval_ReleaseLock()
      single: PyEval_ReleaseThread()
      single: PyEval_SaveThread()
      single: PyEval_RestoreThread()

   Initialize and acquire the global interpreter lock.  It should be called in the
   main thread before creating a second thread or engaging in any other thread
   operations such as :c:func:`PyEval_ReleaseLock` or
   ``PyEval_ReleaseThread(tstate)``. It is not needed before calling
   :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.

   .. index:: single: Py_Initialize()

   This is a no-op when called for a second time.  It is safe to call this function
   before calling :c:func:`Py_Initialize`.

   .. index:: module: thread

   .. note::

      When only the main thread exists, no GIL operations are needed. This is a
      common situation (most Python programs do not use threads), and the lock
      operations slow the interpreter down a bit. Therefore, the lock is not
      created initially.  This situation is equivalent to having acquired the lock:
      when there is only a single thread, all object accesses are safe.  Therefore,
      when this function initializes the global interpreter lock, it also acquires
      it.  Before the Python :mod:`_thread` module creates a new thread, knowing
      that either it has the lock or the lock hasn't been created yet, it calls
      :c:func:`PyEval_InitThreads`.  When this call returns, it is guaranteed that
      the lock has been created and that the calling thread has acquired it.

      It is **not** safe to call this function when it is unknown which thread (if
      any) currently has the global interpreter lock.

      This function is not available when thread support is disabled at compile time.


.. c:function:: int PyEval_ThreadsInitialized()

   Returns a non-zero value if :c:func:`PyEval_InitThreads` has been called.  This
   function can be called without holding the GIL, and therefore can be used to
   avoid calls to the locking API when running single-threaded.  This function is
   not available when thread support is disabled at compile time.

   .. versionadded:: 2.4


.. c:function:: PyThreadState* PyEval_SaveThread()

   Release the global interpreter lock (if it has been created and thread
   support is enabled) and reset the thread state to *NULL*, returning the
   previous thread state (which is not *NULL*).  If the lock has been created,
   the current thread must have acquired it.  (This function is available even
   when thread support is disabled at compile time.)


.. c:function:: void PyEval_RestoreThread(PyThreadState *tstate)

   Acquire the global interpreter lock (if it has been created and thread
   support is enabled) and set the thread state to *tstate*, which must not be
   *NULL*.  If the lock has been created, the current thread must not have
   acquired it, otherwise deadlock ensues.  (This function is available even
   when thread support is disabled at compile time.)


.. c:function:: PyThreadState* PyThreadState_Get()

   Return the current thread state.  The global interpreter lock must be held.
   When the current thread state is *NULL*, this issues a fatal error (so that
   the caller needn't check for *NULL*).


.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)

   Swap the current thread state with the thread state given by the argument
   *tstate*, which may be *NULL*.  The global interpreter lock must be held
   and is not released.


.. c:function:: void PyEval_ReInitThreads()

   This function is called from :c:func:`PyOS_AfterFork` to ensure that newly
   created child processes don't hold locks referring to threads which
   are not running in the child process.


The following functions use thread-local storage, and are not compatible
with sub-interpreters:

.. c:function:: PyGILState_STATE PyGILState_Ensure()

   Ensure that the current thread is ready to call the Python C API regardless
   of the current state of Python, or of the global interpreter lock. This may
   be called as many times as desired by a thread as long as each call is
   matched with a call to :c:func:`PyGILState_Release`. In general, other
   thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
   :c:func:`PyGILState_Release` calls as long as the thread state is restored to
   its previous state before the Release().  For example, normal usage of the
   :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
   acceptable.

   The return value is an opaque "handle" to the thread state when
   :c:func:`PyGILState_Ensure` was called, and must be passed to
   :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
   though recursive calls are allowed, these handles *cannot* be shared - each
   unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
   to :c:func:`PyGILState_Release`.

   When the function returns, the current thread will hold the GIL and be able
   to call arbitrary Python code.  Failure is a fatal error.

   .. versionadded:: 2.3


.. c:function:: void PyGILState_Release(PyGILState_STATE)

   Release any resources previously acquired.  After this call, Python's state will
   be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
   (but generally this state will be unknown to the caller, hence the use of the
   GILState API).

   Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
   :c:func:`PyGILState_Release` on the same thread.

   .. versionadded:: 2.3


.. c:function:: PyThreadState* PyGILState_GetThisThreadState()

   Get the current thread state for this thread.  May return ``NULL`` if no
   GILState API has been used on the current thread.  Note that the main thread
   always has such a thread-state, even if no auto-thread-state call has been
   made on the main thread.  This is mainly a helper/diagnostic function.

   .. versionadded:: 2.3


The following macros are normally used without a trailing semicolon; look for
example usage in the Python source distribution.


.. c:macro:: Py_BEGIN_ALLOW_THREADS

   This macro expands to ``{ PyThreadState *_save; _save = PyEval_SaveThread();``.
   Note that it contains an opening brace; it must be matched with a following
   :c:macro:`Py_END_ALLOW_THREADS` macro.  See above for further discussion of this
   macro.  It is a no-op when thread support is disabled at compile time.


.. c:macro:: Py_END_ALLOW_THREADS

   This macro expands to ``PyEval_RestoreThread(_save); }``. Note that it contains
   a closing brace; it must be matched with an earlier
   :c:macro:`Py_BEGIN_ALLOW_THREADS` macro.  See above for further discussion of
   this macro.  It is a no-op when thread support is disabled at compile time.


.. c:macro:: Py_BLOCK_THREADS

   This macro expands to ``PyEval_RestoreThread(_save);``: it is equivalent to
   :c:macro:`Py_END_ALLOW_THREADS` without the closing brace.  It is a no-op when
   thread support is disabled at compile time.


.. c:macro:: Py_UNBLOCK_THREADS

   This macro expands to ``_save = PyEval_SaveThread();``: it is equivalent to
   :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
   declaration.  It is a no-op when thread support is disabled at compile time.


Low-level API
-------------

All of the following functions are only available when thread support is enabled
at compile time, and must be called only when the global interpreter lock has
been created.


.. c:function:: PyInterpreterState* PyInterpreterState_New()

   Create a new interpreter state object.  The global interpreter lock need not
   be held, but may be held if it is necessary to serialize calls to this
   function.


.. c:function:: void PyInterpreterState_Clear(PyInterpreterState *interp)

   Reset all information in an interpreter state object.  The global interpreter
   lock must be held.


.. c:function:: void PyInterpreterState_Delete(PyInterpreterState *interp)

   Destroy an interpreter state object.  The global interpreter lock need not be
   held.  The interpreter state must have been reset with a previous call to
   :c:func:`PyInterpreterState_Clear`.


.. c:function:: PyThreadState* PyThreadState_New(PyInterpreterState *interp)

   Create a new thread state object belonging to the given interpreter object.
   The global interpreter lock need not be held, but may be held if it is
   necessary to serialize calls to this function.


.. c:function:: void PyThreadState_Clear(PyThreadState *tstate)

   Reset all information in a thread state object.  The global interpreter lock
   must be held.


.. c:function:: void PyThreadState_Delete(PyThreadState *tstate)

   Destroy a thread state object.  The global interpreter lock need not be held.
   The thread state must have been reset with a previous call to
   :c:func:`PyThreadState_Clear`.


.. c:function:: PyObject* PyThreadState_GetDict()

   Return a dictionary in which extensions can store thread-specific state
   information.  Each extension should use a unique key to use to store state in
   the dictionary.  It is okay to call this function when no current thread state
   is available. If this function returns *NULL*, no exception has been raised and
   the caller should assume no current thread state is available.

   .. versionchanged:: 2.3
      Previously this could only be called when a current thread is active, and *NULL*
      meant that an exception was raised.


.. c:function:: int PyThreadState_SetAsyncExc(long id, PyObject *exc)

   Asynchronously raise an exception in a thread. The *id* argument is the thread
   id of the target thread; *exc* is the exception object to be raised. This
   function does not steal any references to *exc*. To prevent naive misuse, you
   must write your own C extension to call this.  Must be called with the GIL held.
   Returns the number of thread states modified; this is normally one, but will be
   zero if the thread id isn't found.  If *exc* is :const:`NULL`, the pending
   exception (if any) for the thread is cleared. This raises no exceptions.

   .. versionadded:: 2.3


.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)

   Acquire the global interpreter lock and set the current thread state to
   *tstate*, which should not be *NULL*.  The lock must have been created earlier.
   If this thread already has the lock, deadlock ensues.

   :c:func:`PyEval_RestoreThread` is a higher-level function which is always
   available (even when thread support isn't enabled or when threads have
   not been initialized).


.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)

   Reset the current thread state to *NULL* and release the global interpreter
   lock.  The lock must have been created earlier and must be held by the current
   thread.  The *tstate* argument, which must not be *NULL*, is only used to check
   that it represents the current thread state --- if it isn't, a fatal error is
   reported.

   :c:func:`PyEval_SaveThread` is a higher-level function which is always
   available (even when thread support isn't enabled or when threads have
   not been initialized).


.. c:function:: void PyEval_AcquireLock()

   Acquire the global interpreter lock.  The lock must have been created earlier.
   If this thread already has the lock, a deadlock ensues.

   .. warning::
      This function does not change the current thread state.  Please use
      :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
      instead.


.. c:function:: void PyEval_ReleaseLock()

   Release the global interpreter lock.  The lock must have been created earlier.

   .. warning::
      This function does not change the current thread state.  Please use
      :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
      instead.


Sub-interpreter support
=======================

While in most uses, you will only embed a single Python interpreter, there
are cases where you need to create several independent interpreters in the
same process and perhaps even in the same thread.  Sub-interpreters allow
you to do that.  You can switch between sub-interpreters using the
:c:func:`PyThreadState_Swap` function.  You can create and destroy them
using the following functions:


.. c:function:: PyThreadState* Py_NewInterpreter()

   .. index::
      module: builtins
      module: __main__
      module: sys
      single: stdout (in module sys)
      single: stderr (in module sys)
      single: stdin (in module sys)

   Create a new sub-interpreter.  This is an (almost) totally separate environment
   for the execution of Python code.  In particular, the new interpreter has
   separate, independent versions of all imported modules, including the
   fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.  The
   table of loaded modules (``sys.modules``) and the module search path
   (``sys.path``) are also separate.  The new environment has no ``sys.argv``
   variable.  It has new standard I/O stream file objects ``sys.stdin``,
   ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
   file descriptors).

   The return value points to the first thread state created in the new
   sub-interpreter.  This thread state is made in the current thread state.
   Note that no actual thread is created; see the discussion of thread states
   below.  If creation of the new interpreter is unsuccessful, *NULL* is
   returned; no exception is set since the exception state is stored in the
   current thread state and there may not be a current thread state.  (Like all
   other Python/C API functions, the global interpreter lock must be held before
   calling this function and is still held when it returns; however, unlike most
   other Python/C API functions, there needn't be a current thread state on
   entry.)

   .. index::
      single: Py_Finalize()
      single: Py_Initialize()

   Extension modules are shared between (sub-)interpreters as follows: the first
   time a particular extension is imported, it is initialized normally, and a
   (shallow) copy of its module's dictionary is squirreled away.  When the same
   extension is imported by another (sub-)interpreter, a new module is initialized
   and filled with the contents of this copy; the extension's ``init`` function is
   not called.  Note that this is different from what happens when an extension is
   imported after the interpreter has been completely re-initialized by calling
   :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's
   ``initmodule`` function *is* called again.

   .. index:: single: close() (in module os)


.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)

   .. index:: single: Py_Finalize()

   Destroy the (sub-)interpreter represented by the given thread state. The given
   thread state must be the current thread state.  See the discussion of thread
   states below.  When the call returns, the current thread state is *NULL*.  All
   thread states associated with this interpreter are destroyed.  (The global
   interpreter lock must be held before calling this function and is still held
   when it returns.)  :c:func:`Py_Finalize` will destroy all sub-interpreters that
   haven't been explicitly destroyed at that point.


Bugs and caveats
----------------

Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn't perfect --- for example, using
low-level file operations like  :func:`os.close` they can
(accidentally or maliciously) affect each other's open files.  Because of the
way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when the extension makes use of
(static) global variables, or when the extension manipulates its module's
dictionary after its initialization.  It is possible to insert objects created
in one sub-interpreter into a namespace of another sub-interpreter; this should
be done with great care to avoid sharing user-defined functions, methods,
instances or classes between sub-interpreters, since import operations executed
by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
modules.

Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
is delicate, because these APIs assume a bijection between Python thread states
and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don't switch sub-interpreters between a pair
of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using
sub-interpreters.


Asynchronous Notifications
==========================

A mechanism is provided to make asynchronous notifications to the main
interpreter thread.  These notifications take the form of a function
pointer and a void pointer argument.


.. c:function:: int Py_AddPendingCall(int (*func)(void *), void *arg)

   .. index:: single: Py_AddPendingCall()

   Schedule a function to be called from the main interpreter thread.  On
   success, ``0`` is returned and *func* is queued for being called in the
   main thread.  On failure, ``-1`` is returned without setting any exception.

   When successfully queued, *func* will be *eventually* called from the
   main interpreter thread with the argument *arg*.  It will be called
   asynchronously with respect to normally running Python code, but with
   both these conditions met:

   * on a :term:`bytecode` boundary;
   * with the main thread holding the :term:`global interpreter lock`
     (*func* can therefore use the full C API).

   *func* must return ``0`` on success, or ``-1`` on failure with an exception
   set.  *func* won't be interrupted to perform another asynchronous
   notification recursively, but it can still be interrupted to switch
   threads if the global interpreter lock is released.

   This function doesn't need a current thread state to run, and it doesn't
   need the global interpreter lock.

   .. warning::
      This is a low-level function, only useful for very special cases.
      There is no guarantee that *func* will be called as quick as
      possible.  If the main thread is busy executing a system call,
      *func* won't be called before the system call returns.  This
      function is generally **not** suitable for calling Python code from
      arbitrary C threads.  Instead, use the :ref:`PyGILState API<gilstate>`.

   .. versionadded:: 2.7


.. _profiling:

Profiling and Tracing
=====================

.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The Python interpreter provides some low-level support for attaching profiling
and execution tracing facilities.  These are used for profiling, debugging, and
coverage analysis tools.

Starting with Python 2.2, the implementation of this facility was substantially
revised, and an interface from C was added.  This C interface allows the
profiling or tracing code to avoid the overhead of calling through Python-level
callable objects, making a direct C function call instead.  The essential
attributes of the facility have not changed; the interface allows trace
functions to be installed per-thread, and the basic events reported to the trace
function are the same as had been reported to the Python-level trace functions
in previous versions.


.. c:type:: int (*Py_tracefunc)(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)

   The type of the trace function registered using :c:func:`PyEval_SetProfile` and
   :c:func:`PyEval_SetTrace`. The first parameter is the object passed to the
   registration function as *obj*, *frame* is the frame object to which the event
   pertains, *what* is one of the constants :const:`PyTrace_CALL`,
   :const:`PyTrace_EXCEPTION`, :const:`PyTrace_LINE`, :const:`PyTrace_RETURN`,
   :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION`, or
   :const:`PyTrace_C_RETURN`, and *arg* depends on the value of *what*:

   +------------------------------+--------------------------------------+
   | Value of *what*              | Meaning of *arg*                     |
   +==============================+======================================+
   | :const:`PyTrace_CALL`        | Always :c:data:`Py_None`.            |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_EXCEPTION`   | Exception information as returned by |
   |                              | :func:`sys.exc_info`.                |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_LINE`        | Always :c:data:`Py_None`.            |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_RETURN`      | Value being returned to the caller,  |
   |                              | or *NULL* if caused by an exception. |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_C_CALL`      | Function object being called.        |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_C_EXCEPTION` | Function object being called.        |
   +------------------------------+--------------------------------------+
   | :const:`PyTrace_C_RETURN`    | Function object being called.        |
   +------------------------------+--------------------------------------+


.. c:var:: int PyTrace_CALL

   The value of the *what* parameter to a :c:type:`Py_tracefunc` function when a new
   call to a function or method is being reported, or a new entry into a generator.
   Note that the creation of the iterator for a generator function is not reported
   as there is no control transfer to the Python bytecode in the corresponding
   frame.


.. c:var:: int PyTrace_EXCEPTION

   The value of the *what* parameter to a :c:type:`Py_tracefunc` function when an
   exception has been raised.  The callback function is called with this value for
   *what* when after any bytecode is processed after which the exception becomes
   set within the frame being executed.  The effect of this is that as exception
   propagation causes the Python stack to unwind, the callback is called upon
   return to each frame as the exception propagates.  Only trace functions receives
   these events; they are not needed by the profiler.


.. c:var:: int PyTrace_LINE

   The value passed as the *what* parameter to a trace function (but not a
   profiling function) when a line-number event is being reported.


.. c:var:: int PyTrace_RETURN

   The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a
   call is about to return.


.. c:var:: int PyTrace_C_CALL

   The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
   function is about to be called.


.. c:var:: int PyTrace_C_EXCEPTION

   The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
   function has raised an exception.


.. c:var:: int PyTrace_C_RETURN

   The value for the *what* parameter to :c:type:`Py_tracefunc` functions when a C
   function has returned.


.. c:function:: void PyEval_SetProfile(Py_tracefunc func, PyObject *obj)

   Set the profiler function to *func*.  The *obj* parameter is passed to the
   function as its first parameter, and may be any Python object, or *NULL*.  If
   the profile function needs to maintain state, using a different value for *obj*
   for each thread provides a convenient and thread-safe place to store it.  The
   profile function is called for all monitored events except :const:`PyTrace_LINE`
   and :const:`PyTrace_EXCEPTION`.


.. c:function:: void PyEval_SetTrace(Py_tracefunc func, PyObject *obj)

   Set the tracing function to *func*.  This is similar to
   :c:func:`PyEval_SetProfile`, except the tracing function does receive line-number
   events and does not receive any event related to C function objects being called. Any
   trace function registered using :c:func:`PyEval_SetTrace` will not receive
   :const:`PyTrace_C_CALL`, :const:`PyTrace_C_EXCEPTION` or :const:`PyTrace_C_RETURN`
   as a value for the *what* parameter.


.. c:function:: PyObject* PyEval_GetCallStats(PyObject *self)

   Return a tuple of function call counts.  There are constants defined for the
   positions within the tuple:

   +-------------------------------+-------+
   | Name                          | Value |
   +===============================+=======+
   | :const:`PCALL_ALL`            | 0     |
   +-------------------------------+-------+
   | :const:`PCALL_FUNCTION`       | 1     |
   +-------------------------------+-------+
   | :const:`PCALL_FAST_FUNCTION`  | 2     |
   +-------------------------------+-------+
   | :const:`PCALL_FASTER_FUNCTION`| 3     |
   +-------------------------------+-------+
   | :const:`PCALL_METHOD`         | 4     |
   +-------------------------------+-------+
   | :const:`PCALL_BOUND_METHOD`   | 5     |
   +-------------------------------+-------+
   | :const:`PCALL_CFUNCTION`      | 6     |
   +-------------------------------+-------+
   | :const:`PCALL_TYPE`           | 7     |
   +-------------------------------+-------+
   | :const:`PCALL_GENERATOR`      | 8     |
   +-------------------------------+-------+
   | :const:`PCALL_OTHER`          | 9     |
   +-------------------------------+-------+
   | :const:`PCALL_POP`            | 10    |
   +-------------------------------+-------+

   :const:`PCALL_FAST_FUNCTION` means no argument tuple needs to be created.
   :const:`PCALL_FASTER_FUNCTION` means that the fast-path frame setup code is used.

   If there is a method call where the call can be optimized by changing
   the argument tuple and calling the function directly, it gets recorded
   twice.

   This function is only present if Python is compiled with :const:`CALL_PROFILE`
   defined.

.. _advanced-debugging:

Advanced Debugger Support
=========================

.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


These functions are only intended to be used by advanced debugging tools.


.. c:function:: PyInterpreterState* PyInterpreterState_Head()

   Return the interpreter state object at the head of the list of all such objects.

   .. versionadded:: 2.2


.. c:function:: PyInterpreterState* PyInterpreterState_Next(PyInterpreterState *interp)

   Return the next interpreter state object after *interp* from the list of all
   such objects.

   .. versionadded:: 2.2


.. c:function:: PyThreadState * PyInterpreterState_ThreadHead(PyInterpreterState *interp)

   Return the pointer to the first :c:type:`PyThreadState` object in the list of
   threads associated with the interpreter *interp*.

   .. versionadded:: 2.2


.. c:function:: PyThreadState* PyThreadState_Next(PyThreadState *tstate)

   Return the next thread state object after *tstate* from the list of all such
   objects belonging to the same :c:type:`PyInterpreterState` object.

   .. versionadded:: 2.2

PK	%�\�O����html/_sources/c-api/int.rst.txtnu�[���.. highlightlang:: c

.. _intobjects:

Plain Integer Objects
---------------------

.. index:: object: integer


.. c:type:: PyIntObject

   This subtype of :c:type:`PyObject` represents a Python integer object.


.. c:var:: PyTypeObject PyInt_Type

   .. index:: single: IntType (in modules types)

   This instance of :c:type:`PyTypeObject` represents the Python plain integer type.
   This is the same object as ``int`` and ``types.IntType``.


.. c:function:: int PyInt_Check(PyObject *o)

   Return true if *o* is of type :c:data:`PyInt_Type` or a subtype of
   :c:data:`PyInt_Type`.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyInt_CheckExact(PyObject *o)

   Return true if *o* is of type :c:data:`PyInt_Type`, but not a subtype of
   :c:data:`PyInt_Type`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyInt_FromString(char *str, char **pend, int base)

   Return a new :c:type:`PyIntObject` or :c:type:`PyLongObject` based on the string
   value in *str*, which is interpreted according to the radix in *base*.  If
   *pend* is non-*NULL*, ``*pend`` will point to the first character in *str* which
   follows the representation of the number.  If *base* is ``0``, the radix will be
   determined based on the leading characters of *str*: if *str* starts with
   ``'0x'`` or ``'0X'``, radix 16 will be used; if *str* starts with ``'0'``, radix
   8 will be used; otherwise radix 10 will be used.  If *base* is not ``0``, it
   must be between ``2`` and ``36``, inclusive.  Leading spaces are ignored.  If
   there are no digits, :exc:`ValueError` will be raised.  If the string represents
   a number too large to be contained within the machine's :c:type:`long int` type
   and overflow warnings are being suppressed, a :c:type:`PyLongObject` will be
   returned.  If overflow warnings are not being suppressed, *NULL* will be
   returned in this case.


.. c:function:: PyObject* PyInt_FromLong(long ival)

   Create a new integer object with a value of *ival*.

   The current implementation keeps an array of integer objects for all integers
   between ``-5`` and ``256``, when you create an int in that range you actually
   just get back a reference to the existing object. So it should be possible to
   change the value of ``1``.  I suspect the behaviour of Python in this case is
   undefined. :-)


.. c:function:: PyObject* PyInt_FromSsize_t(Py_ssize_t ival)

   Create a new integer object with a value of *ival*. If the value is larger
   than ``LONG_MAX`` or smaller than ``LONG_MIN``, a long integer object is
   returned.

   .. versionadded:: 2.5


.. c:function:: PyObject* PyInt_FromSize_t(size_t ival)

   Create a new integer object with a value of *ival*. If the value exceeds
   ``LONG_MAX``, a long integer object is returned.

   .. versionadded:: 2.5


.. c:function:: long PyInt_AsLong(PyObject *io)

   Will first attempt to cast the object to a :c:type:`PyIntObject`, if it is not
   already one, and then return its value. If there is an error, ``-1`` is
   returned, and the caller should check ``PyErr_Occurred()`` to find out whether
   there was an error, or whether the value just happened to be ``-1``.


.. c:function:: long PyInt_AS_LONG(PyObject *io)

   Return the value of the object *io*.  No error checking is performed.


.. c:function:: unsigned long PyInt_AsUnsignedLongMask(PyObject *io)

   Will first attempt to cast the object to a :c:type:`PyIntObject` or
   :c:type:`PyLongObject`, if it is not already one, and then return its value as
   unsigned long.  This function does not check for overflow.

   .. versionadded:: 2.3


.. c:function:: unsigned PY_LONG_LONG PyInt_AsUnsignedLongLongMask(PyObject *io)

   Will first attempt to cast the object to a :c:type:`PyIntObject` or
   :c:type:`PyLongObject`, if it is not already one, and then return its value as
   unsigned long long, without checking for overflow.

   .. versionadded:: 2.3


.. c:function:: Py_ssize_t PyInt_AsSsize_t(PyObject *io)

   Will first attempt to cast the object to a :c:type:`PyIntObject` or
   :c:type:`PyLongObject`, if it is not already one, and then return its value as
   :c:type:`Py_ssize_t`.

   .. versionadded:: 2.5


.. c:function:: long PyInt_GetMax()

   .. index:: single: LONG_MAX

   Return the system's idea of the largest integer it can handle
   (:const:`LONG_MAX`, as defined in the system header files).


.. c:function:: int PyInt_ClearFreeList()

   Clear the integer free list. Return the number of items that could not
   be freed.

   .. versionadded:: 2.6
PK	%�\�?��9o9o!html/_sources/c-api/intro.rst.txtnu�[���.. highlightlang:: c


.. _api-intro:

************
Introduction
************

The Application Programmer's Interface to Python gives C and C++ programmers
access to the Python interpreter at a variety of levels.  The API is equally
usable from C++, but for brevity it is generally referred to as the Python/C
API.  There are two fundamentally different reasons for using the Python/C API.
The first reason is to write *extension modules* for specific purposes; these
are C modules that extend the Python interpreter.  This is probably the most
common use.  The second reason is to use Python as a component in a larger
application; this technique is generally referred to as :dfn:`embedding` Python
in an application.

Writing an extension module is a relatively well-understood process,  where a
"cookbook" approach works well.  There are several tools  that automate the
process to some extent.  While people have embedded  Python in other
applications since its early existence, the process of  embedding Python is less
straightforward than writing an extension.

Many API functions are useful independent of whether you're embedding  or
extending Python; moreover, most applications that embed Python  will need to
provide a custom extension as well, so it's probably a  good idea to become
familiar with writing an extension before  attempting to embed Python in a real
application.


.. _api-includes:

Include Files
=============

All function, type and macro definitions needed to use the Python/C API are
included in your code by the following line::

   #include "Python.h"

This implies inclusion of the following standard headers: ``<stdio.h>``,
``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
(if available).

.. note::

   Since Python may define some pre-processor definitions which affect the standard
   headers on some systems, you *must* include :file:`Python.h` before any standard
   headers are included.

All user visible names defined by Python.h (except those defined by the included
standard headers) have one of the prefixes ``Py`` or ``_Py``.  Names beginning
with ``_Py`` are for internal use by the Python implementation and should not be
used by extension writers. Structure member names do not have a reserved prefix.

**Important:** user code should never define names that begin with ``Py`` or
``_Py``.  This confuses the reader, and jeopardizes the portability of the user
code to future Python versions, which may define additional names beginning with
one of these prefixes.

The header files are typically installed with Python.  On Unix, these  are
located in the directories :file:`{prefix}/include/pythonversion/` and
:file:`{exec_prefix}/include/pythonversion/`, where :envvar:`prefix` and
:envvar:`exec_prefix` are defined by the corresponding parameters to Python's
:program:`configure` script and *version* is ``sys.version[:3]``.  On Windows,
the headers are installed in :file:`{prefix}/include`, where :envvar:`prefix` is
the installation directory specified to the installer.

To include the headers, place both directories (if different) on your compiler's
search path for includes.  Do *not* place the parent directories on the search
path and then use ``#include <pythonX.Y/Python.h>``; this will break on
multi-platform builds since the platform independent headers under
:envvar:`prefix` include the platform specific headers from
:envvar:`exec_prefix`.

C++ users should note that though the API is defined entirely using C, the
header files do properly declare the entry points to be ``extern "C"``, so there
is no need to do anything special to use the API from C++.


.. _api-objects:

Objects, Types and Reference Counts
===================================

.. index:: object: type

Most Python/C API functions have one or more arguments as well as a return value
of type :c:type:`PyObject\*`.  This type is a pointer to an opaque data type
representing an arbitrary Python object.  Since all Python object types are
treated the same way by the Python language in most situations (e.g.,
assignments, scope rules, and argument passing), it is only fitting that they
should be represented by a single C type.  Almost all Python objects live on the
heap: you never declare an automatic or static variable of type
:c:type:`PyObject`, only pointer variables of type :c:type:`PyObject\*` can  be
declared.  The sole exception are the type objects; since these must never be
deallocated, they are typically static :c:type:`PyTypeObject` objects.

All Python objects (even Python integers) have a :dfn:`type` and a
:dfn:`reference count`.  An object's type determines what kind of object it is
(e.g., an integer, a list, or a user-defined function; there are many more as
explained in :ref:`types`).  For each of the well-known types there is a macro
to check whether an object is of that type; for instance, ``PyList_Check(a)`` is
true if (and only if) the object pointed to by *a* is a Python list.


.. _api-refcounts:

Reference Counts
----------------

The reference count is important because today's computers have a  finite (and
often severely limited) memory size; it counts how many  different places there
are that have a reference to an object.  Such a  place could be another object,
or a global (or static) C variable, or  a local variable in some C function.
When an object's reference count  becomes zero, the object is deallocated.  If
it contains references to  other objects, their reference count is decremented.
Those other  objects may be deallocated in turn, if this decrement makes their
reference count become zero, and so on.  (There's an obvious problem  with
objects that reference each other here; for now, the solution is  "don't do
that.")

.. index::
   single: Py_INCREF()
   single: Py_DECREF()

Reference counts are always manipulated explicitly.  The normal way is  to use
the macro :c:func:`Py_INCREF` to increment an object's reference count by one,
and :c:func:`Py_DECREF` to decrement it by   one.  The :c:func:`Py_DECREF` macro
is considerably more complex than the incref one, since it must check whether
the reference count becomes zero and then cause the object's deallocator to be
called. The deallocator is a function pointer contained in the object's type
structure.  The type-specific deallocator takes care of decrementing the
reference counts for other objects contained in the object if this is a compound
object type, such as a list, as well as performing any additional finalization
that's needed.  There's no chance that the reference count can overflow; at
least as many bits are used to hold the reference count as there are distinct
memory locations in virtual memory (assuming ``sizeof(Py_ssize_t) >= sizeof(void*)``).
Thus, the reference count increment is a simple operation.

It is not necessary to increment an object's reference count for every  local
variable that contains a pointer to an object.  In theory, the  object's
reference count goes up by one when the variable is made to  point to it and it
goes down by one when the variable goes out of  scope.  However, these two
cancel each other out, so at the end the  reference count hasn't changed.  The
only real reason to use the  reference count is to prevent the object from being
deallocated as  long as our variable is pointing to it.  If we know that there
is at  least one other reference to the object that lives at least as long as
our variable, there is no need to increment the reference count  temporarily.
An important situation where this arises is in objects  that are passed as
arguments to C functions in an extension module  that are called from Python;
the call mechanism guarantees to hold a  reference to every argument for the
duration of the call.

However, a common pitfall is to extract an object from a list and hold on to it
for a while without incrementing its reference count. Some other operation might
conceivably remove the object from the list, decrementing its reference count
and possible deallocating it. The real danger is that innocent-looking
operations may invoke arbitrary Python code which could do this; there is a code
path which allows control to flow back to the user from a :c:func:`Py_DECREF`, so
almost any operation is potentially dangerous.

A safe approach is to always use the generic operations (functions  whose name
begins with ``PyObject_``, ``PyNumber_``, ``PySequence_`` or ``PyMapping_``).
These operations always increment the reference count of the object they return.
This leaves the caller with the responsibility to call :c:func:`Py_DECREF` when
they are done with the result; this soon becomes second nature.


.. _api-refcountdetails:

Reference Count Details
^^^^^^^^^^^^^^^^^^^^^^^

The reference count behavior of functions in the Python/C API is best  explained
in terms of *ownership of references*.  Ownership pertains to references, never
to objects (objects are not owned: they are always shared).  "Owning a
reference" means being responsible for calling Py_DECREF on it when the
reference is no longer needed.  Ownership can also be transferred, meaning that
the code that receives ownership of the reference then becomes responsible for
eventually decref'ing it by calling :c:func:`Py_DECREF` or :c:func:`Py_XDECREF`
when it's no longer needed---or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a *new* reference.  When no ownership is transferred,
the caller is said to *borrow* the reference. Nothing needs to be done for a
borrowed reference.

Conversely, when a calling function passes in a reference to an  object, there
are two possibilities: the function *steals* a  reference to the object, or it
does not.  *Stealing a reference* means that when you pass a reference to a
function, that function assumes that it now owns that reference, and you are not
responsible for it any longer.

.. index::
   single: PyList_SetItem()
   single: PyTuple_SetItem()

Few functions steal references; the two notable exceptions are
:c:func:`PyList_SetItem` and :c:func:`PyTuple_SetItem`, which  steal a reference
to the item (but not to the tuple or list into which the item is put!).  These
functions were designed to steal a reference because of a common idiom for
populating a tuple or list with newly created objects; for example, the code to
create the tuple ``(1, 2, "three")`` could look like this (forgetting about
error handling for the moment; a better way to code this is shown below)::

   PyObject *t;

   t = PyTuple_New(3);
   PyTuple_SetItem(t, 0, PyInt_FromLong(1L));
   PyTuple_SetItem(t, 1, PyInt_FromLong(2L));
   PyTuple_SetItem(t, 2, PyString_FromString("three"));

Here, :c:func:`PyInt_FromLong` returns a new reference which is immediately
stolen by :c:func:`PyTuple_SetItem`.  When you want to keep using an object
although the reference to it will be stolen, use :c:func:`Py_INCREF` to grab
another reference before calling the reference-stealing function.

Incidentally, :c:func:`PyTuple_SetItem` is the *only* way to set tuple items;
:c:func:`PySequence_SetItem` and :c:func:`PyObject_SetItem` refuse to do this
since tuples are an immutable data type.  You should only use
:c:func:`PyTuple_SetItem` for tuples that you are creating yourself.

Equivalent code for populating a list can be written using :c:func:`PyList_New`
and :c:func:`PyList_SetItem`.

However, in practice, you will rarely use these ways of creating and populating
a tuple or list.  There's a generic function, :c:func:`Py_BuildValue`, that can
create most common objects from C values, directed by a :dfn:`format string`.
For example, the above two blocks of code could be replaced by the following
(which also takes care of the error checking)::

   PyObject *tuple, *list;

   tuple = Py_BuildValue("(iis)", 1, 2, "three");
   list = Py_BuildValue("[iis]", 1, 2, "three");

It is much more common to use :c:func:`PyObject_SetItem` and friends with items
whose references you are only borrowing, like arguments that were passed in to
the function you are writing.  In that case, their behaviour regarding reference
counts is much saner, since you don't have to increment a reference count so you
can give a reference away ("have it be stolen").  For example, this function
sets all items of a list (actually, any mutable sequence) to a given item::

   int
   set_all(PyObject *target, PyObject *item)
   {
       int i, n;

       n = PyObject_Length(target);
       if (n < 0)
           return -1;
       for (i = 0; i < n; i++) {
           PyObject *index = PyInt_FromLong(i);
           if (!index)
               return -1;
           if (PyObject_SetItem(target, index, item) < 0) {
               Py_DECREF(index);
               return -1;
           }
           Py_DECREF(index);
       }
       return 0;
   }

.. index:: single: set_all()

The situation is slightly different for function return values.   While passing
a reference to most functions does not change your  ownership responsibilities
for that reference, many functions that  return a reference to an object give
you ownership of the reference. The reason is simple: in many cases, the
returned object is created  on the fly, and the reference you get is the only
reference to the  object.  Therefore, the generic functions that return object
references, like :c:func:`PyObject_GetItem` and  :c:func:`PySequence_GetItem`,
always return a new reference (the caller becomes the owner of the reference).

It is important to realize that whether you own a reference returned  by a
function depends on which function you call only --- *the plumage* (the type of
the object passed as an argument to the function) *doesn't enter into it!*
Thus, if you  extract an item from a list using :c:func:`PyList_GetItem`, you
don't own the reference --- but if you obtain the same item from the same list
using :c:func:`PySequence_GetItem` (which happens to take exactly the same
arguments), you do own a reference to the returned object.

.. index::
   single: PyList_GetItem()
   single: PySequence_GetItem()

Here is an example of how you could write a function that computes the sum of
the items in a list of integers; once using  :c:func:`PyList_GetItem`, and once
using :c:func:`PySequence_GetItem`. ::

   long
   sum_list(PyObject *list)
   {
       int i, n;
       long total = 0;
       PyObject *item;

       n = PyList_Size(list);
       if (n < 0)
           return -1; /* Not a list */
       for (i = 0; i < n; i++) {
           item = PyList_GetItem(list, i); /* Can't fail */
           if (!PyInt_Check(item)) continue; /* Skip non-integers */
           total += PyInt_AsLong(item);
       }
       return total;
   }

.. index:: single: sum_list()

::

   long
   sum_sequence(PyObject *sequence)
   {
       int i, n;
       long total = 0;
       PyObject *item;
       n = PySequence_Length(sequence);
       if (n < 0)
           return -1; /* Has no length */
       for (i = 0; i < n; i++) {
           item = PySequence_GetItem(sequence, i);
           if (item == NULL)
               return -1; /* Not a sequence, or other failure */
           if (PyInt_Check(item))
               total += PyInt_AsLong(item);
           Py_DECREF(item); /* Discard reference ownership */
       }
       return total;
   }

.. index:: single: sum_sequence()


.. _api-types:

Types
-----

There are few other data types that play a significant role in  the Python/C
API; most are simple C types such as :c:type:`int`,  :c:type:`long`,
:c:type:`double` and :c:type:`char\*`.  A few structure types  are used to
describe static tables used to list the functions exported  by a module or the
data attributes of a new object type, and another is used to describe the value
of a complex number.  These will  be discussed together with the functions that
use them.


.. _api-exceptions:

Exceptions
==========

The Python programmer only needs to deal with exceptions if specific  error
handling is required; unhandled exceptions are automatically  propagated to the
caller, then to the caller's caller, and so on, until they reach the top-level
interpreter, where they are reported to the  user accompanied by a stack
traceback.

.. index:: single: PyErr_Occurred()

For C programmers, however, error checking always has to be explicit.  All
functions in the Python/C API can raise exceptions, unless an explicit claim is
made otherwise in a function's documentation.  In general, when a function
encounters an error, it sets an exception, discards any object references that
it owns, and returns an error indicator.  If not documented otherwise, this
indicator is either *NULL* or ``-1``, depending on the function's return type.
A few functions return a Boolean true/false result, with false indicating an
error.  Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with
:c:func:`PyErr_Occurred`.  These exceptions are always explicitly documented.

.. index::
   single: PyErr_SetString()
   single: PyErr_Clear()

Exception state is maintained in per-thread storage (this is  equivalent to
using global storage in an unthreaded application).  A  thread can be in one of
two states: an exception has occurred, or not. The function
:c:func:`PyErr_Occurred` can be used to check for this: it returns a borrowed
reference to the exception type object when an exception has occurred, and
*NULL* otherwise.  There are a number of functions to set the exception state:
:c:func:`PyErr_SetString` is the most common (though not the most general)
function to set the exception state, and :c:func:`PyErr_Clear` clears the
exception state.

.. index::
   single: exc_type (in module sys)
   single: exc_value (in module sys)
   single: exc_traceback (in module sys)

The full exception state consists of three objects (all of which can  be
*NULL*): the exception type, the corresponding exception  value, and the
traceback.  These have the same meanings as the Python   objects
``sys.exc_type``, ``sys.exc_value``, and ``sys.exc_traceback``; however, they
are not the same: the Python objects represent the last exception being handled
by a Python  :keyword:`try` ... :keyword:`except` statement, while the C level
exception state only exists while an exception is being passed on between C
functions until it reaches the Python bytecode interpreter's  main loop, which
takes care of transferring it to ``sys.exc_type`` and friends.

.. index:: single: exc_info() (in module sys)

Note that starting with Python 1.5, the preferred, thread-safe way to access the
exception state from Python code is to call the function :func:`sys.exc_info`,
which returns the per-thread exception state for Python code.  Also, the
semantics of both ways to access the exception state have changed so that a
function which catches an exception will save and restore its thread's exception
state so as to preserve the exception state of its caller.  This prevents common
bugs in exception handling code caused by an innocent-looking function
overwriting the exception being handled; it also reduces the often unwanted
lifetime extension for objects that are referenced by the stack frames in the
traceback.

As a general principle, a function that calls another function to  perform some
task should check whether the called function raised an  exception, and if so,
pass the exception state on to its caller.  It  should discard any object
references that it owns, and return an  error indicator, but it should *not* set
another exception --- that would overwrite the exception that was just raised,
and lose important information about the exact cause of the error.

.. index:: single: sum_sequence()

A simple example of detecting exceptions and passing them on is shown in the
:c:func:`sum_sequence` example above.  It so happens that this example doesn't
need to clean up any owned references when it detects an error.  The following
example function shows some error cleanup.  First, to remind you why you like
Python, we show the equivalent Python code::

   def incr_item(dict, key):
       try:
           item = dict[key]
       except KeyError:
           item = 0
       dict[key] = item + 1

.. index:: single: incr_item()

Here is the corresponding C code, in all its glory::

   int
   incr_item(PyObject *dict, PyObject *key)
   {
       /* Objects all initialized to NULL for Py_XDECREF */
       PyObject *item = NULL, *const_one = NULL, *incremented_item = NULL;
       int rv = -1; /* Return value initialized to -1 (failure) */

       item = PyObject_GetItem(dict, key);
       if (item == NULL) {
           /* Handle KeyError only: */
           if (!PyErr_ExceptionMatches(PyExc_KeyError))
               goto error;

           /* Clear the error and use zero: */
           PyErr_Clear();
           item = PyInt_FromLong(0L);
           if (item == NULL)
               goto error;
       }
       const_one = PyInt_FromLong(1L);
       if (const_one == NULL)
           goto error;

       incremented_item = PyNumber_Add(item, const_one);
       if (incremented_item == NULL)
           goto error;

       if (PyObject_SetItem(dict, key, incremented_item) < 0)
           goto error;
       rv = 0; /* Success */
       /* Continue with cleanup code */

    error:
       /* Cleanup code, shared by success and failure path */

       /* Use Py_XDECREF() to ignore NULL references */
       Py_XDECREF(item);
       Py_XDECREF(const_one);
       Py_XDECREF(incremented_item);

       return rv; /* -1 for error, 0 for success */
   }

.. index:: single: incr_item()

.. index::
   single: PyErr_ExceptionMatches()
   single: PyErr_Clear()
   single: Py_XDECREF()

This example represents an endorsed use of the ``goto`` statement  in C!
It illustrates the use of :c:func:`PyErr_ExceptionMatches` and
:c:func:`PyErr_Clear` to handle specific exceptions, and the use of
:c:func:`Py_XDECREF` to dispose of owned references that may be *NULL* (note the
``'X'`` in the name; :c:func:`Py_DECREF` would crash when confronted with a
*NULL* reference).  It is important that the variables used to hold owned
references are initialized to *NULL* for this to work; likewise, the proposed
return value is initialized to ``-1`` (failure) and only set to success after
the final call made is successful.


.. _api-embedding:

Embedding Python
================

The one important task that only embedders (as opposed to extension writers) of
the Python interpreter have to worry about is the initialization, and possibly
the finalization, of the Python interpreter.  Most functionality of the
interpreter can only be used after the interpreter has been initialized.

.. index::
   single: Py_Initialize()
   module: __builtin__
   module: __main__
   module: sys
   module: exceptions
   triple: module; search; path
   single: path (in module sys)

The basic initialization function is :c:func:`Py_Initialize`. This initializes
the table of loaded modules, and creates the fundamental modules
:mod:`__builtin__`, :mod:`__main__`, :mod:`sys`, and :mod:`exceptions`.  It also
initializes the module search path (``sys.path``).

.. index:: single: PySys_SetArgvEx()

:c:func:`Py_Initialize` does not set the "script argument list"  (``sys.argv``).
If this variable is needed by Python code that will be executed later, it must
be set explicitly with a call to  ``PySys_SetArgvEx(argc, argv, updatepath)``
after the call to :c:func:`Py_Initialize`.

On most systems (in particular, on Unix and Windows, although the details are
slightly different), :c:func:`Py_Initialize` calculates the module search path
based upon its best guess for the location of the standard Python interpreter
executable, assuming that the Python library is found in a fixed location
relative to the Python interpreter executable.  In particular, it looks for a
directory named :file:`lib/python{X.Y}` relative to the parent directory
where the executable named :file:`python` is found on the shell command search
path (the environment variable :envvar:`PATH`).

For instance, if the Python executable is found in
:file:`/usr/local/bin/python`, it will assume that the libraries are in
:file:`/usr/local/lib/python{X.Y}`.  (In fact, this particular path is also
the "fallback" location, used when no executable file named :file:`python` is
found along :envvar:`PATH`.)  The user can override this behavior by setting the
environment variable :envvar:`PYTHONHOME`, or insert additional directories in
front of the standard path by setting :envvar:`PYTHONPATH`.

.. index::
   single: Py_SetProgramName()
   single: Py_GetPath()
   single: Py_GetPrefix()
   single: Py_GetExecPrefix()
   single: Py_GetProgramFullPath()

The embedding application can steer the search by calling
``Py_SetProgramName(file)`` *before* calling  :c:func:`Py_Initialize`.  Note that
:envvar:`PYTHONHOME` still overrides this and :envvar:`PYTHONPATH` is still
inserted in front of the standard path.  An application that requires total
control has to provide its own implementation of :c:func:`Py_GetPath`,
:c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`, and
:c:func:`Py_GetProgramFullPath` (all defined in :file:`Modules/getpath.c`).

.. index:: single: Py_IsInitialized()

Sometimes, it is desirable to "uninitialize" Python.  For instance,  the
application may want to start over (make another call to
:c:func:`Py_Initialize`) or the application is simply done with its  use of
Python and wants to free memory allocated by Python.  This can be accomplished
by calling :c:func:`Py_Finalize`.  The function :c:func:`Py_IsInitialized` returns
true if Python is currently in the initialized state.  More information about
these functions is given in a later chapter. Notice that :c:func:`Py_Finalize`
does *not* free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.


.. _api-debugging:

Debugging Builds
================

Python can be built with several macros to enable extra checks of the
interpreter and extension modules.  These checks tend to add a large amount of
overhead to the runtime so they are not enabled by default.

A full list of the various types of debugging builds is in the file
:file:`Misc/SpecialBuilds.txt` in the Python source distribution. Builds are
available that support tracing of reference counts, debugging the memory
allocator, or low-level profiling of the main interpreter loop.  Only the most
frequently-used builds will be described in the remainder of this section.

Compiling the interpreter with the :c:macro:`Py_DEBUG` macro defined produces
what is generally meant by "a debug build" of Python. :c:macro:`Py_DEBUG` is
enabled in the Unix build by adding ``--with-pydebug`` to the
:file:`./configure` command.  It is also implied by the presence of the
not-Python-specific :c:macro:`_DEBUG` macro.  When :c:macro:`Py_DEBUG` is enabled
in the Unix build, compiler optimization is disabled.

In addition to the reference count debugging described below, the following
extra checks are performed:

* Extra checks are added to the object allocator.

* Extra checks are added to the parser and compiler.

* Downcasts from wide types to narrow types are checked for loss of information.

* A number of assertions are added to the dictionary and set implementations.
  In addition, the set object acquires a :meth:`test_c_api` method.

* Sanity checks of the input arguments are added to frame creation.

* The storage for long ints is initialized with a known invalid pattern to catch
  reference to uninitialized digits.

* Low-level tracing and extra exception checking are added to the runtime
  virtual machine.

* Extra checks are added to the memory arena implementation.

* Extra debugging is added to the thread module.

There may be additional checks not mentioned here.

Defining :c:macro:`Py_TRACE_REFS` enables reference tracing.  When defined, a
circular doubly linked list of active objects is maintained by adding two extra
fields to every :c:type:`PyObject`.  Total allocations are tracked as well.  Upon
exit, all existing references are printed.  (In interactive mode this happens
after every statement run by the interpreter.)  Implied by :c:macro:`Py_DEBUG`.

Please refer to :file:`Misc/SpecialBuilds.txt` in the Python source distribution
for more detailed information.

PK	%�\���nn html/_sources/c-api/iter.rst.txtnu�[���.. highlightlang:: c

.. _iterator:

Iterator Protocol
=================

.. versionadded:: 2.2

There are two functions specifically for working with iterators.


.. c:function:: int PyIter_Check(PyObject *o)

   Return true if the object *o* supports the iterator protocol.

   This function can return a false positive in the case of old-style
   classes because those classes always define a :c:member:`tp_iternext`
   slot with logic that either invokes a :meth:`next` method or raises
   a :exc:`TypeError`.

.. c:function:: PyObject* PyIter_Next(PyObject *o)

   Return the next value from the iteration *o*.  The object must be an iterator
   (it is up to the caller to check this).  If there are no remaining values,
   returns *NULL* with no exception set.  If an error occurs while retrieving
   the item, returns *NULL* and passes along the exception.

To write a loop which iterates over an iterator, the C code should look
something like this::

   PyObject *iterator = PyObject_GetIter(obj);
   PyObject *item;

   if (iterator == NULL) {
       /* propagate error */
   }

   while (item = PyIter_Next(iterator)) {
       /* do something with item */
       ...
       /* release reference when done */
       Py_DECREF(item);
   }

   Py_DECREF(iterator);

   if (PyErr_Occurred()) {
       /* propagate error */
   }
   else {
       /* continue doing useful work */
   }
PK	%�\�ѥ$html/_sources/c-api/iterator.rst.txtnu�[���.. highlightlang:: c

.. _iterator-objects:

Iterator Objects
----------------

Python provides two general-purpose iterator objects.  The first, a sequence
iterator, works with an arbitrary sequence supporting the :meth:`__getitem__`
method.  The second works with a callable object and a sentinel value, calling
the callable for each item in the sequence, and ending the iteration when the
sentinel value is returned.


.. c:var:: PyTypeObject PySeqIter_Type

   Type object for iterator objects returned by :c:func:`PySeqIter_New` and the
   one-argument form of the :func:`iter` built-in function for built-in sequence
   types.

   .. versionadded:: 2.2


.. c:function:: int PySeqIter_Check(op)

   Return true if the type of *op* is :c:data:`PySeqIter_Type`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PySeqIter_New(PyObject *seq)

   Return an iterator that works with a general sequence object, *seq*.  The
   iteration ends when the sequence raises :exc:`IndexError` for the subscripting
   operation.

   .. versionadded:: 2.2


.. c:var:: PyTypeObject PyCallIter_Type

   Type object for iterator objects returned by :c:func:`PyCallIter_New` and the
   two-argument form of the :func:`iter` built-in function.

   .. versionadded:: 2.2


.. c:function:: int PyCallIter_Check(op)

   Return true if the type of *op* is :c:data:`PyCallIter_Type`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyCallIter_New(PyObject *callable, PyObject *sentinel)

   Return a new iterator.  The first parameter, *callable*, can be any Python
   callable object that can be called with no parameters; each call to it should
   return the next item in the iteration.  When *callable* returns a value equal to
   *sentinel*, the iteration will be terminated.

   .. versionadded:: 2.2
PK	%�\��`F�� html/_sources/c-api/list.rst.txtnu�[���.. highlightlang:: c

.. _listobjects:

List Objects
------------

.. index:: object: list


.. c:type:: PyListObject

   This subtype of :c:type:`PyObject` represents a Python list object.


.. c:var:: PyTypeObject PyList_Type

   This instance of :c:type:`PyTypeObject` represents the Python list type.  This
   is the same object as ``list`` in the Python layer.


.. c:function:: int PyList_Check(PyObject *p)

   Return true if *p* is a list object or an instance of a subtype of the list
   type.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyList_CheckExact(PyObject *p)

   Return true if *p* is a list object, but not an instance of a subtype of
   the list type.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyList_New(Py_ssize_t len)

   Return a new list of length *len* on success, or *NULL* on failure.

   .. note::

      If *len* is greater than zero, the returned list object's items are
      set to ``NULL``.  Thus you cannot use abstract API functions such as
      :c:func:`PySequence_SetItem`  or expose the object to Python code before
      setting all items to a real object with :c:func:`PyList_SetItem`.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyList_Size(PyObject *list)

   .. index:: builtin: len

   Return the length of the list object in *list*; this is equivalent to
   ``len(list)`` on a list object.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int`. This might require changes in
      your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyList_GET_SIZE(PyObject *list)

   Macro form of :c:func:`PyList_Size` without error checking.

   .. versionchanged:: 2.5
      This macro returned an :c:type:`int`. This might require changes in your
      code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)

   Return the object at position *index* in the list pointed to by *list*.  The
   position must be positive, indexing from the end of the list is not
   supported.  If *index* is out of bounds, return *NULL* and set an
   :exc:`IndexError` exception.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *index*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyList_GET_ITEM(PyObject *list, Py_ssize_t i)

   Macro form of :c:func:`PyList_GetItem` without error checking.

   .. versionchanged:: 2.5
      This macro used an :c:type:`int` for *i*. This might require changes in
      your code for properly supporting 64-bit systems.


.. c:function:: int PyList_SetItem(PyObject *list, Py_ssize_t index, PyObject *item)

   Set the item at index *index* in list to *item*.  Return ``0`` on success
   or ``-1`` on failure.

   .. note::

      This function "steals" a reference to *item* and discards a reference to
      an item already in the list at the affected position.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *index*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: void PyList_SET_ITEM(PyObject *list, Py_ssize_t i, PyObject *o)

   Macro form of :c:func:`PyList_SetItem` without error checking. This is
   normally only used to fill in new lists where there is no previous content.

   .. note::

      This macro "steals" a reference to *item*, and, unlike
      :c:func:`PyList_SetItem`, does *not* discard a reference to any item that
      it being replaced; any reference in *list* at position *i* will be
      leaked.

   .. versionchanged:: 2.5
      This macro used an :c:type:`int` for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyList_Insert(PyObject *list, Py_ssize_t index, PyObject *item)

   Insert the item *item* into list *list* in front of index *index*.  Return
   ``0`` if successful; return ``-1`` and set an exception if unsuccessful.
   Analogous to ``list.insert(index, item)``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *index*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyList_Append(PyObject *list, PyObject *item)

   Append the object *item* at the end of list *list*. Return ``0`` if
   successful; return ``-1`` and set an exception if unsuccessful.  Analogous
   to ``list.append(item)``.


.. c:function:: PyObject* PyList_GetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high)

   Return a list of the objects in *list* containing the objects *between* *low*
   and *high*.  Return *NULL* and set an exception if unsuccessful.  Analogous
   to ``list[low:high]``.  Negative indices, as when slicing from Python, are not
   supported.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *low* and *high*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyList_SetSlice(PyObject *list, Py_ssize_t low, Py_ssize_t high, PyObject *itemlist)

   Set the slice of *list* between *low* and *high* to the contents of
   *itemlist*.  Analogous to ``list[low:high] = itemlist``. The *itemlist* may
   be *NULL*, indicating the assignment of an empty list (slice deletion).
   Return ``0`` on success, ``-1`` on failure.  Negative indices, as when
   slicing from Python, are not supported.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *low* and *high*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyList_Sort(PyObject *list)

   Sort the items of *list* in place.  Return ``0`` on success, ``-1`` on
   failure.  This is equivalent to ``list.sort()``.


.. c:function:: int PyList_Reverse(PyObject *list)

   Reverse the items of *list* in place.  Return ``0`` on success, ``-1`` on
   failure.  This is the equivalent of ``list.reverse()``.


.. c:function:: PyObject* PyList_AsTuple(PyObject *list)

   .. index:: builtin: tuple

   Return a new tuple object containing the contents of *list*; equivalent to
   ``tuple(list)``.
PK	%�\�=9�33 html/_sources/c-api/long.rst.txtnu�[���.. highlightlang:: c

.. _longobjects:

Long Integer Objects
--------------------

.. index:: object: long integer


.. c:type:: PyLongObject

   This subtype of :c:type:`PyObject` represents a Python long integer object.


.. c:var:: PyTypeObject PyLong_Type

   .. index:: single: LongType (in modules types)

   This instance of :c:type:`PyTypeObject` represents the Python long integer type.
   This is the same object as ``long`` and ``types.LongType``.


.. c:function:: int PyLong_Check(PyObject *p)

   Return true if its argument is a :c:type:`PyLongObject` or a subtype of
   :c:type:`PyLongObject`.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyLong_CheckExact(PyObject *p)

   Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of
   :c:type:`PyLongObject`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyLong_FromLong(long v)

   Return a new :c:type:`PyLongObject` object from *v*, or *NULL* on failure.


.. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v)

   Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long`, or
   *NULL* on failure.


.. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v)

   Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or
   *NULL* on failure.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyLong_FromSize_t(size_t v)

   Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or
   *NULL* on failure.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyLong_FromLongLong(PY_LONG_LONG v)

   Return a new :c:type:`PyLongObject` object from a C :c:type:`long long`, or *NULL*
   on failure.


.. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG v)

   Return a new :c:type:`PyLongObject` object from a C :c:type:`unsigned long long`,
   or *NULL* on failure.


.. c:function:: PyObject* PyLong_FromDouble(double v)

   Return a new :c:type:`PyLongObject` object from the integer part of *v*, or
   *NULL* on failure.


.. c:function:: PyObject* PyLong_FromString(char *str, char **pend, int base)

   Return a new :c:type:`PyLongObject` based on the string value in *str*, which is
   interpreted according to the radix in *base*.  If *pend* is non-*NULL*,
   *\*pend* will point to the first character in *str* which follows the
   representation of the number.  If *base* is ``0``, the radix will be determined
   based on the leading characters of *str*: if *str* starts with ``'0x'`` or
   ``'0X'``, radix 16 will be used; if *str* starts with ``'0'``, radix 8 will be
   used; otherwise radix 10 will be used.  If *base* is not ``0``, it must be
   between ``2`` and ``36``, inclusive.  Leading spaces are ignored.  If there are
   no digits, :exc:`ValueError` will be raised.


.. c:function:: PyObject* PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)

   Convert a sequence of Unicode digits to a Python long integer value.  The first
   parameter, *u*, points to the first character of the Unicode string, *length*
   gives the number of characters, and *base* is the radix for the conversion.  The
   radix must be in the range [2, 36]; if it is out of range, :exc:`ValueError`
   will be raised.

   .. versionadded:: 1.6

   .. versionchanged:: 2.5
      This function used an :c:type:`int` for *length*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyLong_FromVoidPtr(void *p)

   Create a Python integer or long integer from the pointer *p*. The pointer value
   can be retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.5
      If the integer is larger than LONG_MAX, a positive long integer is returned.


.. c:function:: long PyLong_AsLong(PyObject *pylong)

   .. index::
      single: LONG_MAX
      single: OverflowError (built-in exception)

   Return a C :c:type:`long` representation of the contents of *pylong*.  If
   *pylong* is greater than :const:`LONG_MAX`, an :exc:`OverflowError` is raised
   and ``-1`` will be returned.


.. c:function:: long PyLong_AsLongAndOverflow(PyObject *pylong, int *overflow)

   Return a C :c:type:`long` representation of the contents of
   *pylong*.  If *pylong* is greater than :const:`LONG_MAX` or less
   than :const:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``,
   respectively, and return ``-1``; otherwise, set *\*overflow* to
   ``0``.  If any other exception occurs (for example a TypeError or
   MemoryError), then ``-1`` will be returned and *\*overflow* will
   be ``0``.

   .. versionadded:: 2.7


.. c:function:: PY_LONG_LONG PyLong_AsLongLongAndOverflow(PyObject *pylong, int *overflow)

   Return a C :c:type:`long long` representation of the contents of
   *pylong*.  If *pylong* is greater than :const:`PY_LLONG_MAX` or less
   than :const:`PY_LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``,
   respectively, and return ``-1``; otherwise, set *\*overflow* to
   ``0``.  If any other exception occurs (for example a TypeError or
   MemoryError), then ``-1`` will be returned and *\*overflow* will
   be ``0``.

   .. versionadded:: 2.7


.. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)

   .. index::
      single: PY_SSIZE_T_MAX
      single: OverflowError (built-in exception)

   Return a C :c:type:`Py_ssize_t` representation of the contents of *pylong*.  If
   *pylong* is greater than :const:`PY_SSIZE_T_MAX`, an :exc:`OverflowError` is raised
   and ``-1`` will be returned.

   .. versionadded:: 2.6


.. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)

   .. index::
      single: ULONG_MAX
      single: OverflowError (built-in exception)

   Return a C :c:type:`unsigned long` representation of the contents of *pylong*.
   If *pylong* is greater than :const:`ULONG_MAX`, an :exc:`OverflowError` is
   raised.


.. c:function:: PY_LONG_LONG PyLong_AsLongLong(PyObject *pylong)

   .. index::
      single: OverflowError (built-in exception)

   Return a C :c:type:`long long` from a Python long integer.  If
   *pylong* cannot be represented as a :c:type:`long long`, an
   :exc:`OverflowError` is raised and ``-1`` is returned.

   .. versionadded:: 2.2


.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLong(PyObject *pylong)

   .. index::
      single: OverflowError (built-in exception)

   Return a C :c:type:`unsigned long long` from a Python long integer. If
   *pylong* cannot be represented as an :c:type:`unsigned long long`, an
   :exc:`OverflowError` is raised and ``(unsigned long long)-1`` is
   returned.

   .. versionadded:: 2.2

   .. versionchanged:: 2.7
      A negative *pylong* now raises :exc:`OverflowError`, not
      :exc:`TypeError`.


.. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *io)

   Return a C :c:type:`unsigned long` from a Python long integer, without checking
   for overflow.

   .. versionadded:: 2.3


.. c:function:: unsigned PY_LONG_LONG PyLong_AsUnsignedLongLongMask(PyObject *io)

   Return a C :c:type:`unsigned long long` from a Python long integer, without
   checking for overflow.

   .. versionadded:: 2.3


.. c:function:: double PyLong_AsDouble(PyObject *pylong)

   Return a C :c:type:`double` representation of the contents of *pylong*.  If
   *pylong* cannot be approximately represented as a :c:type:`double`, an
   :exc:`OverflowError` exception is raised and ``-1.0`` will be returned.


.. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong)

   Convert a Python integer or long integer *pylong* to a C :c:type:`void` pointer.
   If *pylong* cannot be converted, an :exc:`OverflowError` will be raised.  This
   is only assured to produce a usable :c:type:`void` pointer for values created
   with :c:func:`PyLong_FromVoidPtr`.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.5
      For values outside 0..LONG_MAX, both signed and unsigned integers are accepted.


PK	%�\$;��::#html/_sources/c-api/mapping.rst.txtnu�[���.. highlightlang:: c

.. _mapping:

Mapping Protocol
================


.. c:function:: int PyMapping_Check(PyObject *o)

   Return ``1`` if the object provides mapping protocol, and ``0`` otherwise.  This
   function always succeeds.


.. c:function:: Py_ssize_t PyMapping_Size(PyObject *o)
               Py_ssize_t PyMapping_Length(PyObject *o)

   .. index:: builtin: len

   Returns the number of keys in object *o* on success, and ``-1`` on failure.  For
   objects that do not provide mapping protocol, this is equivalent to the Python
   expression ``len(o)``.

   .. versionchanged:: 2.5
      These functions returned an :c:type:`int` type. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyMapping_DelItemString(PyObject *o, char *key)

   Remove the mapping for object *key* from the object *o*. Return ``-1`` on
   failure.  This is equivalent to the Python statement ``del o[key]``.


.. c:function:: int PyMapping_DelItem(PyObject *o, PyObject *key)

   Remove the mapping for object *key* from the object *o*. Return ``-1`` on
   failure.  This is equivalent to the Python statement ``del o[key]``.


.. c:function:: int PyMapping_HasKeyString(PyObject *o, char *key)

   On success, return ``1`` if the mapping object has the key *key* and ``0``
   otherwise.  This is equivalent to ``o[key]``, returning ``True`` on success
   and ``False`` on an exception.  This function always succeeds.


.. c:function:: int PyMapping_HasKey(PyObject *o, PyObject *key)

   Return ``1`` if the mapping object has the key *key* and ``0`` otherwise.
   This is equivalent to ``o[key]``, returning ``True`` on success and ``False``
   on an exception.  This function always succeeds.


.. c:function:: PyObject* PyMapping_Keys(PyObject *o)

   On success, return a list of the keys in object *o*.  On failure, return *NULL*.
   This is equivalent to the Python expression ``o.keys()``.


.. c:function:: PyObject* PyMapping_Values(PyObject *o)

   On success, return a list of the values in object *o*.  On failure, return
   *NULL*. This is equivalent to the Python expression ``o.values()``.


.. c:function:: PyObject* PyMapping_Items(PyObject *o)

   On success, return a list of the items in object *o*, where each item is a tuple
   containing a key-value pair.  On failure, return *NULL*. This is equivalent to
   the Python expression ``o.items()``.


.. c:function:: PyObject* PyMapping_GetItemString(PyObject *o, char *key)

   Return element of *o* corresponding to the object *key* or *NULL* on failure.
   This is the equivalent of the Python expression ``o[key]``.


.. c:function:: int PyMapping_SetItemString(PyObject *o, char *key, PyObject *v)

   Map the object *key* to the value *v* in object *o*. Returns ``-1`` on failure.
   This is the equivalent of the Python statement ``o[key] = v``.
PK	%�\�����#html/_sources/c-api/marshal.rst.txtnu�[���.. highlightlang:: c

.. _marshalling-utils:

Data marshalling support
========================

These routines allow C code to work with serialized objects using the same
data format as the :mod:`marshal` module.  There are functions to write data
into the serialization format, and additional functions that can be used to
read the data back.  Files used to store marshalled data must be opened in
binary mode.

Numeric values are stored with the least significant byte first.

The module supports two versions of the data format: version ``0`` is the
historical version, version ``1`` (new in Python 2.4) shares interned strings in
the file, and upon unmarshalling.  Version 2 (new in Python 2.5) uses a binary
format for floating point numbers.  *Py_MARSHAL_VERSION* indicates the current
file format (currently 2).


.. c:function:: void PyMarshal_WriteLongToFile(long value, FILE *file, int version)

   Marshal a :c:type:`long` integer, *value*, to *file*.  This will only write
   the least-significant 32 bits of *value*; regardless of the size of the
   native :c:type:`long` type.

   .. versionchanged:: 2.4
      *version* indicates the file format.


.. c:function:: void PyMarshal_WriteObjectToFile(PyObject *value, FILE *file, int version)

   Marshal a Python object, *value*, to *file*.

   .. versionchanged:: 2.4
      *version* indicates the file format.


.. c:function:: PyObject* PyMarshal_WriteObjectToString(PyObject *value, int version)

   Return a string object containing the marshalled representation of *value*.

   .. versionchanged:: 2.4
      *version* indicates the file format.


The following functions allow marshalled values to be read back in.

XXX What about error detection?  It appears that reading past the end of the
file will always result in a negative numeric value (where that's relevant),
but it's not clear that negative values won't be handled properly when there's
no error.  What's the right way to tell? Should only non-negative values be
written using these routines?


.. c:function:: long PyMarshal_ReadLongFromFile(FILE *file)

   Return a C :c:type:`long` from the data stream in a :c:type:`FILE\*` opened
   for reading.  Only a 32-bit value can be read in using this function,
   regardless of the native size of :c:type:`long`.


.. c:function:: int PyMarshal_ReadShortFromFile(FILE *file)

   Return a C :c:type:`short` from the data stream in a :c:type:`FILE\*` opened
   for reading.  Only a 16-bit value can be read in using this function,
   regardless of the native size of :c:type:`short`.


.. c:function:: PyObject* PyMarshal_ReadObjectFromFile(FILE *file)

   Return a Python object from the data stream in a :c:type:`FILE\*` opened for
   reading.  On error, sets the appropriate exception (:exc:`EOFError` or
   :exc:`TypeError`) and returns *NULL*.


.. c:function:: PyObject* PyMarshal_ReadLastObjectFromFile(FILE *file)

   Return a Python object from the data stream in a :c:type:`FILE\*` opened for
   reading.  Unlike :c:func:`PyMarshal_ReadObjectFromFile`, this function
   assumes that no further objects will be read from the file, allowing it to
   aggressively load file data into memory so that the de-serialization can
   operate from data in memory rather than reading a byte at a time from the
   file.  Only use these variant if you are certain that you won't be reading
   anything else from the file.  On error, sets the appropriate exception
   (:exc:`EOFError` or :exc:`TypeError`) and returns *NULL*.


.. c:function:: PyObject* PyMarshal_ReadObjectFromString(char *string, Py_ssize_t len)

   Return a Python object from the data stream in a character buffer
   containing *len* bytes pointed to by *string*.  On error, sets the
   appropriate exception (:exc:`EOFError` or :exc:`TypeError`) and returns
   *NULL*.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *len*. This might require
      changes in your code for properly supporting 64-bit systems.
PK	%�\&6y$-$-"html/_sources/c-api/memory.rst.txtnu�[���.. highlightlang:: c


.. _memory:

*****************
Memory Management
*****************

.. sectionauthor:: Vladimir Marangozov <Vladimir.Marangozov@inrialpes.fr>



.. _memoryoverview:

Overview
========

Memory management in Python involves a private heap containing all Python
objects and data structures. The management of this private heap is ensured
internally by the *Python memory manager*.  The Python memory manager has
different components which deal with various dynamic storage management aspects,
like sharing, segmentation, preallocation or caching.

At the lowest level, a raw memory allocator ensures that there is enough room in
the private heap for storing all Python-related data by interacting with the
memory manager of the operating system. On top of the raw memory allocator,
several object-specific allocators operate on the same heap and implement
distinct memory management policies adapted to the peculiarities of every object
type. For example, integer objects are managed differently within the heap than
strings, tuples or dictionaries because integers imply different storage
requirements and speed/space tradeoffs. The Python memory manager thus delegates
some of the work to the object-specific allocators, but ensures that the latter
operate within the bounds of the private heap.

It is important to understand that the management of the Python heap is
performed by the interpreter itself and that the user has no control over it,
even if they regularly manipulate object pointers to memory blocks inside that
heap.  The allocation of heap space for Python objects and other internal
buffers is performed on demand by the Python memory manager through the Python/C
API functions listed in this document.

.. index::
   single: malloc()
   single: calloc()
   single: realloc()
   single: free()

To avoid memory corruption, extension writers should never try to operate on
Python objects with the functions exported by the C library: :c:func:`malloc`,
:c:func:`calloc`, :c:func:`realloc` and :c:func:`free`.  This will result in  mixed
calls between the C allocator and the Python memory manager with fatal
consequences, because they implement different algorithms and operate on
different heaps.  However, one may safely allocate and release memory blocks
with the C library allocator for individual purposes, as shown in the following
example::

   PyObject *res;
   char *buf = (char *) malloc(BUFSIZ); /* for I/O */

   if (buf == NULL)
       return PyErr_NoMemory();
   ...Do some I/O operation involving buf...
   res = PyString_FromString(buf);
   free(buf); /* malloc'ed */
   return res;

In this example, the memory request for the I/O buffer is handled by the C
library allocator. The Python memory manager is involved only in the allocation
of the string object returned as a result.

In most situations, however, it is recommended to allocate memory from the
Python heap specifically because the latter is under control of the Python
memory manager. For example, this is required when the interpreter is extended
with new object types written in C. Another reason for using the Python heap is
the desire to *inform* the Python memory manager about the memory needs of the
extension module. Even when the requested memory is used exclusively for
internal, highly-specific purposes, delegating all memory requests to the Python
memory manager causes the interpreter to have a more accurate image of its
memory footprint as a whole. Consequently, under certain circumstances, the
Python memory manager may or may not trigger appropriate actions, like garbage
collection, memory compaction or other preventive procedures. Note that by using
the C library allocator as shown in the previous example, the allocated memory
for the I/O buffer escapes completely the Python memory manager.


.. _memoryinterface:

Memory Interface
================

The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap:


.. c:function:: void* PyMem_Malloc(size_t n)

   Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the
   allocated memory, or *NULL* if the request fails. Requesting zero bytes returns
   a distinct non-*NULL* pointer if possible, as if ``PyMem_Malloc(1)`` had
   been called instead. The memory will not have been initialized in any way.


.. c:function:: void* PyMem_Realloc(void *p, size_t n)

   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
   unchanged to the minimum of the old and the new sizes. If *p* is *NULL*, the
   call is equivalent to ``PyMem_Malloc(n)``; else if *n* is equal to zero,
   the memory block is resized but is not freed, and the returned pointer is
   non-*NULL*.  Unless *p* is *NULL*, it must have been returned by a previous call
   to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`. If the request fails,
   :c:func:`PyMem_Realloc` returns *NULL* and *p* remains a valid pointer to the
   previous memory area.


.. c:function:: void PyMem_Free(void *p)

   Frees the memory block pointed to by *p*, which must have been returned by a
   previous call to :c:func:`PyMem_Malloc` or :c:func:`PyMem_Realloc`.  Otherwise, or
   if ``PyMem_Free(p)`` has been called before, undefined behavior occurs. If
   *p* is *NULL*, no operation is performed.

The following type-oriented macros are provided for convenience.  Note  that
*TYPE* refers to any C type.


.. c:function:: TYPE* PyMem_New(TYPE, size_t n)

   Same as :c:func:`PyMem_Malloc`, but allocates ``(n * sizeof(TYPE))`` bytes of
   memory.  Returns a pointer cast to :c:type:`TYPE\*`.  The memory will not have
   been initialized in any way.


.. c:function:: TYPE* PyMem_Resize(void *p, TYPE, size_t n)

   Same as :c:func:`PyMem_Realloc`, but the memory block is resized to ``(n *
   sizeof(TYPE))`` bytes.  Returns a pointer cast to :c:type:`TYPE\*`. On return,
   *p* will be a pointer to the new memory area, or *NULL* in the event of
   failure.  This is a C preprocessor macro; p is always reassigned.  Save
   the original value of p to avoid losing memory when handling errors.


.. c:function:: void PyMem_Del(void *p)

   Same as :c:func:`PyMem_Free`.

In addition, the following macro sets are provided for calling the Python memory
allocator directly, without involving the C API functions listed above. However,
note that their use does not preserve binary compatibility across Python
versions and is therefore deprecated in extension modules.

:c:func:`PyMem_MALLOC`, :c:func:`PyMem_REALLOC`, :c:func:`PyMem_FREE`.

:c:func:`PyMem_NEW`, :c:func:`PyMem_RESIZE`, :c:func:`PyMem_DEL`.


Object allocators
=================

The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap.

By default, these functions use :ref:`pymalloc memory allocator <pymalloc>`.

.. warning::

   The :term:`GIL <global interpreter lock>` must be held when using these
   functions.

.. c:function:: void* PyObject_Malloc(size_t n)

   Allocates *n* bytes and returns a pointer of type :c:type:`void\*` to the
   allocated memory, or *NULL* if the request fails.

   Requesting zero bytes returns a distinct non-*NULL* pointer if possible, as
   if ``PyObject_Malloc(1)`` had been called instead. The memory will not have
   been initialized in any way.


.. c:function:: void* PyObject_Realloc(void *p, size_t n)

   Resizes the memory block pointed to by *p* to *n* bytes. The contents will be
   unchanged to the minimum of the old and the new sizes.

   If *p* is *NULL*, the call is equivalent to ``PyObject_Malloc(n)``; else if *n*
   is equal to zero, the memory block is resized but is not freed, and the
   returned pointer is non-*NULL*.

   Unless *p* is *NULL*, it must have been returned by a previous call to
   :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or :c:func:`PyObject_Calloc`.

   If the request fails, :c:func:`PyObject_Realloc` returns *NULL* and *p* remains
   a valid pointer to the previous memory area.


.. c:function:: void PyObject_Free(void *p)

   Frees the memory block pointed to by *p*, which must have been returned by a
   previous call to :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc` or
   :c:func:`PyObject_Calloc`.  Otherwise, or if ``PyObject_Free(p)`` has been called
   before, undefined behavior occurs.

   If *p* is *NULL*, no operation is performed.


In addition, the following macro sets are provided:

* :c:func:`PyObject_MALLOC`: alias to :c:func:`PyObject_Malloc`
* :c:func:`PyObject_REALLOC`: alias to :c:func:`PyObject_Realloc`
* :c:func:`PyObject_FREE`: alias to :c:func:`PyObject_Free`
* :c:func:`PyObject_Del`: alias to :c:func:`PyObject_Free`
* :c:func:`PyObject_DEL`: alias to :c:func:`PyObject_FREE` (so finally an alias
  to :c:func:`PyObject_Free`)


.. _pymalloc:

The pymalloc allocator
======================

Python has a *pymalloc* allocator optimized for small objects (smaller or equal
to 512 bytes) with a short lifetime. It uses memory mappings called "arenas"
with a fixed size of 256 KiB. It falls back to :c:func:`malloc` and
:c:func:`realloc` for allocations larger than 512 bytes.

*pymalloc* is the default allocator of :c:func:`PyObject_Malloc`.

The arena allocator uses the following functions:

* :c:func:`mmap` and :c:func:`munmap` if available,
* :c:func:`malloc` and :c:func:`free` otherwise.

.. versionchanged:: 2.7.7
   The threshold changed from 256 to 512 bytes. The arena allocator now
   uses :c:func:`mmap` if available.


.. _memoryexamples:

Examples
========

Here is the example from section :ref:`memoryoverview`, rewritten so that the
I/O buffer is allocated from the Python heap by using the first function set::

   PyObject *res;
   char *buf = (char *) PyMem_Malloc(BUFSIZ); /* for I/O */

   if (buf == NULL)
       return PyErr_NoMemory();
   /* ...Do some I/O operation involving buf... */
   res = PyString_FromString(buf);
   PyMem_Free(buf); /* allocated with PyMem_Malloc */
   return res;

The same code using the type-oriented function set::

   PyObject *res;
   char *buf = PyMem_New(char, BUFSIZ); /* for I/O */

   if (buf == NULL)
       return PyErr_NoMemory();
   /* ...Do some I/O operation involving buf... */
   res = PyString_FromString(buf);
   PyMem_Del(buf); /* allocated with PyMem_New */
   return res;

Note that in the two examples above, the buffer is always manipulated via
functions belonging to the same set. Indeed, it is required to use the same
memory API family for a given memory block, so that the risk of mixing different
allocators is reduced to a minimum. The following code sequence contains two
errors, one of which is labeled as *fatal* because it mixes two different
allocators operating on different heaps. ::

   char *buf1 = PyMem_New(char, BUFSIZ);
   char *buf2 = (char *) malloc(BUFSIZ);
   char *buf3 = (char *) PyMem_Malloc(BUFSIZ);
   ...
   PyMem_Del(buf3);  /* Wrong -- should be PyMem_Free() */
   free(buf2);       /* Right -- allocated via malloc() */
   free(buf1);       /* Fatal -- should be PyMem_Del()  */

In addition to the functions aimed at handling raw memory blocks from the Python
heap, objects in Python are allocated and released with :c:func:`PyObject_New`,
:c:func:`PyObject_NewVar` and :c:func:`PyObject_Del`.

These will be explained in the next chapter on defining and implementing new
object types in C.

PK	%�\9�	�33"html/_sources/c-api/method.rst.txtnu�[���.. highlightlang:: c

.. _method-objects:

Method Objects
--------------

.. index:: object: method

There are some useful functions that are useful for working with method objects.


.. c:var:: PyTypeObject PyMethod_Type

   .. index:: single: MethodType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python method type.  This
   is exposed to Python programs as ``types.MethodType``.


.. c:function:: int PyMethod_Check(PyObject *o)

   Return true if *o* is a method object (has type :c:data:`PyMethod_Type`).  The
   parameter must not be *NULL*.


.. c:function:: PyObject* PyMethod_New(PyObject *func, PyObject *self, PyObject *class)

   Return a new method object, with *func* being any callable object; this is the
   function that will be called when the method is called.  If this method should
   be bound to an instance, *self* should be the instance and *class* should be the
   class of *self*, otherwise *self* should be *NULL* and *class* should be the
   class which provides the unbound method..


.. c:function:: PyObject* PyMethod_Class(PyObject *meth)

   Return the class object from which the method *meth* was created; if this was
   created from an instance, it will be the class of the instance.


.. c:function:: PyObject* PyMethod_GET_CLASS(PyObject *meth)

   Macro version of :c:func:`PyMethod_Class` which avoids error checking.


.. c:function:: PyObject* PyMethod_Function(PyObject *meth)

   Return the function object associated with the method *meth*.


.. c:function:: PyObject* PyMethod_GET_FUNCTION(PyObject *meth)

   Macro version of :c:func:`PyMethod_Function` which avoids error checking.


.. c:function:: PyObject* PyMethod_Self(PyObject *meth)

   Return the instance associated with the method *meth* if it is bound, otherwise
   return *NULL*.


.. c:function:: PyObject* PyMethod_GET_SELF(PyObject *meth)

   Macro version of :c:func:`PyMethod_Self` which avoids error checking.


.. c:function:: int PyMethod_ClearFreeList()

   Clear the free list. Return the total number of freed items.

   .. versionadded:: 2.6
PK	%�\��J�"html/_sources/c-api/module.rst.txtnu�[���.. highlightlang:: c

.. _moduleobjects:

Module Objects
--------------

.. index:: object: module

There are only a few functions special to module objects.


.. c:var:: PyTypeObject PyModule_Type

   .. index:: single: ModuleType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python module type.  This
   is exposed to Python programs as ``types.ModuleType``.


.. c:function:: int PyModule_Check(PyObject *p)

   Return true if *p* is a module object, or a subtype of a module object.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyModule_CheckExact(PyObject *p)

   Return true if *p* is a module object, but not a subtype of
   :c:data:`PyModule_Type`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyModule_New(const char *name)

   .. index::
      single: __name__ (module attribute)
      single: __doc__ (module attribute)
      single: __file__ (module attribute)

   Return a new module object with the :attr:`__name__` attribute set to *name*.
   Only the module's :attr:`__doc__` and :attr:`__name__` attributes are filled in;
   the caller is responsible for providing a :attr:`__file__` attribute.


.. c:function:: PyObject* PyModule_GetDict(PyObject *module)

   .. index:: single: __dict__ (module attribute)

   Return the dictionary object that implements *module*'s namespace; this object
   is the same as the :attr:`~object.__dict__` attribute of the module object.  This
   function never fails.  It is recommended extensions use other
   :c:func:`PyModule_\*` and :c:func:`PyObject_\*` functions rather than directly
   manipulate a module's :attr:`~object.__dict__`.


.. c:function:: char* PyModule_GetName(PyObject *module)

   .. index::
      single: __name__ (module attribute)
      single: SystemError (built-in exception)

   Return *module*'s :attr:`__name__` value.  If the module does not provide one,
   or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned.


.. c:function:: char* PyModule_GetFilename(PyObject *module)

   .. index::
      single: __file__ (module attribute)
      single: SystemError (built-in exception)

   Return the name of the file from which *module* was loaded using *module*'s
   :attr:`__file__` attribute.  If this is not defined, or if it is not a string,
   raise :exc:`SystemError` and return *NULL*.


.. c:function:: int PyModule_AddObject(PyObject *module, const char *name, PyObject *value)

   Add an object to *module* as *name*.  This is a convenience function which can
   be used from the module's initialization function.  This steals a reference to
   *value*.  Return ``-1`` on error, ``0`` on success.

   .. versionadded:: 2.0


.. c:function:: int PyModule_AddIntConstant(PyObject *module, const char *name, long value)

   Add an integer constant to *module* as *name*.  This convenience function can be
   used from the module's initialization function. Return ``-1`` on error, ``0`` on
   success.

   .. versionadded:: 2.0


.. c:function:: int PyModule_AddStringConstant(PyObject *module, const char *name, const char *value)

   Add a string constant to *module* as *name*.  This convenience function can be
   used from the module's initialization function.  The string *value* must be
   null-terminated.  Return ``-1`` on error, ``0`` on success.

   .. versionadded:: 2.0

.. c:function:: int PyModule_AddIntMacro(PyObject *module, macro)

   Add an int constant to *module*. The name and the value are taken from
   *macro*. For example ``PyModule_AddIntMacro(module, AF_INET)`` adds the int
   constant *AF_INET* with the value of *AF_INET* to *module*.
   Return ``-1`` on error, ``0`` on success.

   .. versionadded:: 2.6

.. c:function:: int PyModule_AddStringMacro(PyObject *module, macro)

   Add a string constant to *module*.

  .. versionadded:: 2.6

PK	%�\�Q9�� html/_sources/c-api/none.rst.txtnu�[���.. highlightlang:: c

.. _noneobject:

The ``None`` Object
-------------------

.. index:: object: None

Note that the :c:type:`PyTypeObject` for ``None`` is not directly exposed in the
Python/C API.  Since ``None`` is a singleton, testing for object identity (using
``==`` in C) is sufficient. There is no :c:func:`PyNone_Check` function for the
same reason.


.. c:var:: PyObject* Py_None

   The Python ``None`` object, denoting lack of value.  This object has no methods.
   It needs to be treated just like any other object with respect to reference
   counts.


.. c:macro:: Py_RETURN_NONE

   Properly handle returning :c:data:`Py_None` from within a C function.

   .. versionadded:: 2.4

PK	%�\fj�ϣ.�."html/_sources/c-api/number.rst.txtnu�[���.. highlightlang:: c

.. _number:

Number Protocol
===============


.. c:function:: int PyNumber_Check(PyObject *o)

   Returns ``1`` if the object *o* provides numeric protocols, and false otherwise.
   This function always succeeds.


.. c:function:: PyObject* PyNumber_Add(PyObject *o1, PyObject *o2)

   Returns the result of adding *o1* and *o2*, or *NULL* on failure.  This is the
   equivalent of the Python expression ``o1 + o2``.


.. c:function:: PyObject* PyNumber_Subtract(PyObject *o1, PyObject *o2)

   Returns the result of subtracting *o2* from *o1*, or *NULL* on failure.  This is
   the equivalent of the Python expression ``o1 - o2``.


.. c:function:: PyObject* PyNumber_Multiply(PyObject *o1, PyObject *o2)

   Returns the result of multiplying *o1* and *o2*, or *NULL* on failure.  This is
   the equivalent of the Python expression ``o1 * o2``.


.. c:function:: PyObject* PyNumber_Divide(PyObject *o1, PyObject *o2)

   Returns the result of dividing *o1* by *o2*, or *NULL* on failure.  This is the
   equivalent of the Python expression ``o1 / o2``.


.. c:function:: PyObject* PyNumber_FloorDivide(PyObject *o1, PyObject *o2)

   Return the floor of *o1* divided by *o2*, or *NULL* on failure.  This is
   equivalent to the "classic" division of integers.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyNumber_TrueDivide(PyObject *o1, PyObject *o2)

   Return a reasonable approximation for the mathematical value of *o1* divided by
   *o2*, or *NULL* on failure.  The return value is "approximate" because binary
   floating point numbers are approximate; it is not possible to represent all real
   numbers in base two.  This function can return a floating point value when
   passed two integers.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyNumber_Remainder(PyObject *o1, PyObject *o2)

   Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure.  This is
   the equivalent of the Python expression ``o1 % o2``.


.. c:function:: PyObject* PyNumber_Divmod(PyObject *o1, PyObject *o2)

   .. index:: builtin: divmod

   See the built-in function :func:`divmod`. Returns *NULL* on failure.  This is
   the equivalent of the Python expression ``divmod(o1, o2)``.


.. c:function:: PyObject* PyNumber_Power(PyObject *o1, PyObject *o2, PyObject *o3)

   .. index:: builtin: pow

   See the built-in function :func:`pow`. Returns *NULL* on failure.  This is the
   equivalent of the Python expression ``pow(o1, o2, o3)``, where *o3* is optional.
   If *o3* is to be ignored, pass :c:data:`Py_None` in its place (passing *NULL* for
   *o3* would cause an illegal memory access).


.. c:function:: PyObject* PyNumber_Negative(PyObject *o)

   Returns the negation of *o* on success, or *NULL* on failure. This is the
   equivalent of the Python expression ``-o``.


.. c:function:: PyObject* PyNumber_Positive(PyObject *o)

   Returns *o* on success, or *NULL* on failure.  This is the equivalent of the
   Python expression ``+o``.


.. c:function:: PyObject* PyNumber_Absolute(PyObject *o)

   .. index:: builtin: abs

   Returns the absolute value of *o*, or *NULL* on failure.  This is the equivalent
   of the Python expression ``abs(o)``.


.. c:function:: PyObject* PyNumber_Invert(PyObject *o)

   Returns the bitwise negation of *o* on success, or *NULL* on failure.  This is
   the equivalent of the Python expression ``~o``.


.. c:function:: PyObject* PyNumber_Lshift(PyObject *o1, PyObject *o2)

   Returns the result of left shifting *o1* by *o2* on success, or *NULL* on
   failure.  This is the equivalent of the Python expression ``o1 << o2``.


.. c:function:: PyObject* PyNumber_Rshift(PyObject *o1, PyObject *o2)

   Returns the result of right shifting *o1* by *o2* on success, or *NULL* on
   failure.  This is the equivalent of the Python expression ``o1 >> o2``.


.. c:function:: PyObject* PyNumber_And(PyObject *o1, PyObject *o2)

   Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure.
   This is the equivalent of the Python expression ``o1 & o2``.


.. c:function:: PyObject* PyNumber_Xor(PyObject *o1, PyObject *o2)

   Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on
   failure.  This is the equivalent of the Python expression ``o1 ^ o2``.


.. c:function:: PyObject* PyNumber_Or(PyObject *o1, PyObject *o2)

   Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure.
   This is the equivalent of the Python expression ``o1 | o2``.


.. c:function:: PyObject* PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2)

   Returns the result of adding *o1* and *o2*, or *NULL* on failure.  The operation
   is done *in-place* when *o1* supports it.  This is the equivalent of the Python
   statement ``o1 += o2``.


.. c:function:: PyObject* PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2)

   Returns the result of subtracting *o2* from *o1*, or *NULL* on failure.  The
   operation is done *in-place* when *o1* supports it.  This is the equivalent of
   the Python statement ``o1 -= o2``.


.. c:function:: PyObject* PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2)

   Returns the result of multiplying *o1* and *o2*, or *NULL* on failure.  The
   operation is done *in-place* when *o1* supports it.  This is the equivalent of
   the Python statement ``o1 *= o2``.


.. c:function:: PyObject* PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2)

   Returns the result of dividing *o1* by *o2*, or *NULL* on failure.  The
   operation is done *in-place* when *o1* supports it. This is the equivalent of
   the Python statement ``o1 /= o2``.


.. c:function:: PyObject* PyNumber_InPlaceFloorDivide(PyObject *o1, PyObject *o2)

   Returns the mathematical floor of dividing *o1* by *o2*, or *NULL* on failure.
   The operation is done *in-place* when *o1* supports it.  This is the equivalent
   of the Python statement ``o1 //= o2``.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyNumber_InPlaceTrueDivide(PyObject *o1, PyObject *o2)

   Return a reasonable approximation for the mathematical value of *o1* divided by
   *o2*, or *NULL* on failure.  The return value is "approximate" because binary
   floating point numbers are approximate; it is not possible to represent all real
   numbers in base two.  This function can return a floating point value when
   passed two integers.  The operation is done *in-place* when *o1* supports it.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2)

   Returns the remainder of dividing *o1* by *o2*, or *NULL* on failure.  The
   operation is done *in-place* when *o1* supports it.  This is the equivalent of
   the Python statement ``o1 %= o2``.


.. c:function:: PyObject* PyNumber_InPlacePower(PyObject *o1, PyObject *o2, PyObject *o3)

   .. index:: builtin: pow

   See the built-in function :func:`pow`. Returns *NULL* on failure.  The operation
   is done *in-place* when *o1* supports it.  This is the equivalent of the Python
   statement ``o1 **= o2`` when o3 is :c:data:`Py_None`, or an in-place variant of
   ``pow(o1, o2, o3)`` otherwise. If *o3* is to be ignored, pass :c:data:`Py_None`
   in its place (passing *NULL* for *o3* would cause an illegal memory access).


.. c:function:: PyObject* PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2)

   Returns the result of left shifting *o1* by *o2* on success, or *NULL* on
   failure.  The operation is done *in-place* when *o1* supports it.  This is the
   equivalent of the Python statement ``o1 <<= o2``.


.. c:function:: PyObject* PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2)

   Returns the result of right shifting *o1* by *o2* on success, or *NULL* on
   failure.  The operation is done *in-place* when *o1* supports it.  This is the
   equivalent of the Python statement ``o1 >>= o2``.


.. c:function:: PyObject* PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2)

   Returns the "bitwise and" of *o1* and *o2* on success and *NULL* on failure. The
   operation is done *in-place* when *o1* supports it.  This is the equivalent of
   the Python statement ``o1 &= o2``.


.. c:function:: PyObject* PyNumber_InPlaceXor(PyObject *o1, PyObject *o2)

   Returns the "bitwise exclusive or" of *o1* by *o2* on success, or *NULL* on
   failure.  The operation is done *in-place* when *o1* supports it.  This is the
   equivalent of the Python statement ``o1 ^= o2``.


.. c:function:: PyObject* PyNumber_InPlaceOr(PyObject *o1, PyObject *o2)

   Returns the "bitwise or" of *o1* and *o2* on success, or *NULL* on failure.  The
   operation is done *in-place* when *o1* supports it.  This is the equivalent of
   the Python statement ``o1 |= o2``.


.. c:function:: int PyNumber_Coerce(PyObject **p1, PyObject **p2)

   .. index:: builtin: coerce

   This function takes the addresses of two variables of type :c:type:`PyObject\*`.
   If the objects pointed to by ``*p1`` and ``*p2`` have the same type, increment
   their reference count and return ``0`` (success). If the objects can be
   converted to a common numeric type, replace ``*p1`` and ``*p2`` by their
   converted value (with 'new' reference counts), and return ``0``. If no
   conversion is possible, or if some other error occurs, return ``-1`` (failure)
   and don't increment the reference counts.  The call ``PyNumber_Coerce(&o1,
   &o2)`` is equivalent to the Python statement ``o1, o2 = coerce(o1, o2)``.


.. c:function:: int PyNumber_CoerceEx(PyObject **p1, PyObject **p2)

   This function is similar to :c:func:`PyNumber_Coerce`, except that it returns
   ``1`` when the conversion is not possible and when no error is raised.
   Reference counts are still not increased in this case.


.. c:function:: PyObject* PyNumber_Int(PyObject *o)

   .. index:: builtin: int

   Returns the *o* converted to an integer object on success, or *NULL* on failure.
   If the argument is outside the integer range a long object will be returned
   instead. This is the equivalent of the Python expression ``int(o)``.


.. c:function:: PyObject* PyNumber_Long(PyObject *o)

   .. index:: builtin: long

   Returns the *o* converted to a long integer object on success, or *NULL* on
   failure.  This is the equivalent of the Python expression ``long(o)``.


.. c:function:: PyObject* PyNumber_Float(PyObject *o)

   .. index:: builtin: float

   Returns the *o* converted to a float object on success, or *NULL* on failure.
   This is the equivalent of the Python expression ``float(o)``.


.. c:function:: PyObject* PyNumber_Index(PyObject *o)

   Returns the *o* converted to a Python int or long on success or *NULL* with a
   :exc:`TypeError` exception raised on failure.

   .. versionadded:: 2.5


.. c:function:: PyObject* PyNumber_ToBase(PyObject *n, int base)

   Returns the integer *n* converted to *base* as a string with a base
   marker of ``'0b'``, ``'0o'``, or ``'0x'`` if applicable.  When
   *base* is not 2, 8, 10, or 16, the format is ``'x#num'`` where x is the
   base. If *n* is not an int object, it is converted with
   :c:func:`PyNumber_Index` first.

   .. versionadded:: 2.6


.. c:function:: Py_ssize_t PyNumber_AsSsize_t(PyObject *o, PyObject *exc)

   Returns *o* converted to a Py_ssize_t value if *o* can be interpreted as an
   integer. If *o* can be converted to a Python int or long but the attempt to
   convert to a Py_ssize_t value would raise an :exc:`OverflowError`, then the
   *exc* argument is the type of exception that will be raised (usually
   :exc:`IndexError` or :exc:`OverflowError`).  If *exc* is *NULL*, then the
   exception is cleared and the value is clipped to *PY_SSIZE_T_MIN* for a negative
   integer or *PY_SSIZE_T_MAX* for a positive integer.

   .. versionadded:: 2.5


.. c:function:: int PyIndex_Check(PyObject *o)

   Returns ``1`` if *o* is an index integer (has the nb_index slot of  the
   tp_as_number structure filled in), and ``0`` otherwise.

   .. versionadded:: 2.5
PK	%�\o����	�	%html/_sources/c-api/objbuffer.rst.txtnu�[���.. highlightlang:: c

.. _abstract-buffer:


Old Buffer Protocol
===================

This section describes the legacy buffer protocol, which has been introduced
in Python 1.6. It is still supported but deprecated in the Python 2.x series.
Python 3 introduces a new buffer protocol which fixes weaknesses and
shortcomings of the protocol, and has been backported to Python 2.6.  See
:ref:`bufferobjects` for more information.


.. c:function:: int PyObject_AsCharBuffer(PyObject *obj, const char **buffer, Py_ssize_t *buffer_len)

   Returns a pointer to a read-only memory location usable as character-based
   input.  The *obj* argument must support the single-segment character buffer
   interface.  On success, returns ``0``, sets *buffer* to the memory location
   and *buffer_len* to the buffer length.  Returns ``-1`` and sets a
   :exc:`TypeError` on error.

   .. versionadded:: 1.6

   .. versionchanged:: 2.5
      This function used an :c:type:`int *` type for *buffer_len*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyObject_AsReadBuffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)

   Returns a pointer to a read-only memory location containing arbitrary data.
   The *obj* argument must support the single-segment readable buffer
   interface.  On success, returns ``0``, sets *buffer* to the memory location
   and *buffer_len* to the buffer length.  Returns ``-1`` and sets a
   :exc:`TypeError` on error.

   .. versionadded:: 1.6

   .. versionchanged:: 2.5
      This function used an :c:type:`int *` type for *buffer_len*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyObject_CheckReadBuffer(PyObject *o)

   Returns ``1`` if *o* supports the single-segment readable buffer interface.
   Otherwise returns ``0``.

   .. versionadded:: 2.2


.. c:function:: int PyObject_AsWriteBuffer(PyObject *obj, void **buffer, Py_ssize_t *buffer_len)

   Returns a pointer to a writeable memory location.  The *obj* argument must
   support the single-segment, character buffer interface.  On success,
   returns ``0``, sets *buffer* to the memory location and *buffer_len* to the
   buffer length.  Returns ``-1`` and sets a :exc:`TypeError` on error.

   .. versionadded:: 1.6

   .. versionchanged:: 2.5
      This function used an :c:type:`int *` type for *buffer_len*. This might
      require changes in your code for properly supporting 64-bit systems.

PK	%�\���SDSD"html/_sources/c-api/object.rst.txtnu�[���.. highlightlang:: c

.. _object:

Object Protocol
===============


.. c:function:: int PyObject_Print(PyObject *o, FILE *fp, int flags)

   Print an object *o*, on file *fp*.  Returns ``-1`` on error.  The flags argument
   is used to enable certain printing options.  The only option currently supported
   is :const:`Py_PRINT_RAW`; if given, the :func:`str` of the object is written
   instead of the :func:`repr`.


.. c:function:: int PyObject_HasAttr(PyObject *o, PyObject *attr_name)

   Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise.  This
   is equivalent to the Python expression ``hasattr(o, attr_name)``.  This function
   always succeeds.


.. c:function:: int PyObject_HasAttrString(PyObject *o, const char *attr_name)

   Returns ``1`` if *o* has the attribute *attr_name*, and ``0`` otherwise.  This
   is equivalent to the Python expression ``hasattr(o, attr_name)``.  This function
   always succeeds.


.. c:function:: PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name)

   Retrieve an attribute named *attr_name* from object *o*. Returns the attribute
   value on success, or *NULL* on failure.  This is the equivalent of the Python
   expression ``o.attr_name``.


.. c:function:: PyObject* PyObject_GetAttrString(PyObject *o, const char *attr_name)

   Retrieve an attribute named *attr_name* from object *o*. Returns the attribute
   value on success, or *NULL* on failure. This is the equivalent of the Python
   expression ``o.attr_name``.


.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name)

   Generic attribute getter function that is meant to be put into a type
   object's ``tp_getattro`` slot.  It looks for a descriptor in the dictionary
   of classes in the object's MRO as well as an attribute in the object's
   :attr:`~object.__dict__` (if present).  As outlined in :ref:`descriptors`,
   data descriptors take preference over instance attributes, while non-data
   descriptors don't.  Otherwise, an :exc:`AttributeError` is raised.


.. c:function:: int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)

   Set the value of the attribute named *attr_name*, for object *o*, to the value
   *v*. Raise an exception and return ``-1`` on failure;
   return ``0`` on success.  This is the equivalent of the Python statement
   ``o.attr_name = v``.

   If *v* is *NULL*, the attribute is deleted, however this feature is
   deprecated in favour of using :c:func:`PyObject_DelAttr`.


.. c:function:: int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)

   Set the value of the attribute named *attr_name*, for object *o*, to the value
   *v*. Raise an exception and return ``-1`` on failure;
   return ``0`` on success.  This is the equivalent of the Python statement
   ``o.attr_name = v``.

   If *v* is *NULL*, the attribute is deleted, however this feature is
   deprecated in favour of using :c:func:`PyObject_DelAttrString`.


.. c:function:: int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)

   Generic attribute setter and deleter function that is meant
   to be put into a type object's :c:member:`~PyTypeObject.tp_setattro`
   slot.  It looks for a data descriptor in the
   dictionary of classes in the object's MRO, and if found it takes preference
   over setting or deleting the attribute in the instance dictionary. Otherwise, the
   attribute is set or deleted in the object's :attr:`~object.__dict__` (if present).
   On success, ``0`` is returned, otherwise an :exc:`AttributeError`
   is raised and ``-1`` is returned.


.. c:function:: int PyObject_DelAttr(PyObject *o, PyObject *attr_name)

   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
   This is the equivalent of the Python statement ``del o.attr_name``.


.. c:function:: int PyObject_DelAttrString(PyObject *o, const char *attr_name)

   Delete attribute named *attr_name*, for object *o*. Returns ``-1`` on failure.
   This is the equivalent of the Python statement ``del o.attr_name``.


.. c:function:: PyObject* PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)

   Compare the values of *o1* and *o2* using the operation specified by *opid*,
   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. This is the equivalent of
   the Python expression ``o1 op o2``, where ``op`` is the operator corresponding
   to *opid*. Returns the value of the comparison on success, or *NULL* on failure.


.. c:function:: int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)

   Compare the values of *o1* and *o2* using the operation specified by *opid*,
   which must be one of :const:`Py_LT`, :const:`Py_LE`, :const:`Py_EQ`,
   :const:`Py_NE`, :const:`Py_GT`, or :const:`Py_GE`, corresponding to ``<``,
   ``<=``, ``==``, ``!=``, ``>``, or ``>=`` respectively. Returns ``-1`` on error,
   ``0`` if the result is false, ``1`` otherwise. This is the equivalent of the
   Python expression ``o1 op o2``, where ``op`` is the operator corresponding to
   *opid*.

.. note::
   If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool`
   will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.

.. c:function:: int PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)

   .. index:: builtin: cmp

   Compare the values of *o1* and *o2* using a routine provided by *o1*, if one
   exists, otherwise with a routine provided by *o2*.  The result of the comparison
   is returned in *result*.  Returns ``-1`` on failure.  This is the equivalent of
   the Python statement ``result = cmp(o1, o2)``.


.. c:function:: int PyObject_Compare(PyObject *o1, PyObject *o2)

   .. index:: builtin: cmp

   Compare the values of *o1* and *o2* using a routine provided by *o1*, if one
   exists, otherwise with a routine provided by *o2*.  Returns the result of the
   comparison on success.  On error, the value returned is undefined; use
   :c:func:`PyErr_Occurred` to detect an error.  This is equivalent to the Python
   expression ``cmp(o1, o2)``.


.. c:function:: PyObject* PyObject_Repr(PyObject *o)

   .. index:: builtin: repr

   Compute a string representation of object *o*.  Returns the string
   representation on success, *NULL* on failure.  This is the equivalent of the
   Python expression ``repr(o)``.  Called by the :func:`repr` built-in function and
   by reverse quotes.


.. c:function:: PyObject* PyObject_Str(PyObject *o)

   .. index:: builtin: str

   Compute a string representation of object *o*.  Returns the string
   representation on success, *NULL* on failure.  This is the equivalent of the
   Python expression ``str(o)``.  Called by the :func:`str` built-in function and
   by the :keyword:`print` statement.


.. c:function:: PyObject* PyObject_Bytes(PyObject *o)

   .. index:: builtin: bytes

   Compute a bytes representation of object *o*.  In 2.x, this is just an alias
   for :c:func:`PyObject_Str`.


.. c:function:: PyObject* PyObject_Unicode(PyObject *o)

   .. index:: builtin: unicode

   Compute a Unicode string representation of object *o*.  Returns the Unicode
   string representation on success, *NULL* on failure. This is the equivalent of
   the Python expression ``unicode(o)``.  Called by the :func:`unicode` built-in
   function.


.. c:function:: int PyObject_IsInstance(PyObject *inst, PyObject *cls)

   Returns ``1`` if *inst* is an instance of the class *cls* or a subclass of
   *cls*, or ``0`` if not.  On error, returns ``-1`` and sets an exception.  If
   *cls* is a type object rather than a class object, :c:func:`PyObject_IsInstance`
   returns ``1`` if *inst* is of type *cls*.  If *cls* is a tuple, the check will
   be done against every entry in *cls*. The result will be ``1`` when at least one
   of the checks returns ``1``, otherwise it will be ``0``. If *inst* is not a
   class instance and *cls* is neither a type object, nor a class object, nor a
   tuple, *inst* must have a :attr:`~instance.__class__` attribute --- the
   class relationship of the value of that attribute with *cls* will be used
   to determine the result of this function.

   .. versionadded:: 2.1

   .. versionchanged:: 2.2
      Support for a tuple as the second argument added.

Subclass determination is done in a fairly straightforward way, but includes a
wrinkle that implementors of extensions to the class system may want to be aware
of.  If :class:`A` and :class:`B` are class objects, :class:`B` is a subclass of
:class:`A` if it inherits from :class:`A` either directly or indirectly.  If
either is not a class object, a more general mechanism is used to determine the
class relationship of the two objects.  When testing if *B* is a subclass of
*A*, if *A* is *B*, :c:func:`PyObject_IsSubclass` returns true.  If *A* and *B*
are different objects, *B*'s :attr:`~class.__bases__` attribute is searched in
a depth-first fashion for *A* --- the presence of the :attr:`~class.__bases__`
attribute is considered sufficient for this determination.


.. c:function:: int PyObject_IsSubclass(PyObject *derived, PyObject *cls)

   Returns ``1`` if the class *derived* is identical to or derived from the class
   *cls*, otherwise returns ``0``.  In case of an error, returns ``-1``. If *cls*
   is a tuple, the check will be done against every entry in *cls*. The result will
   be ``1`` when at least one of the checks returns ``1``, otherwise it will be
   ``0``. If either *derived* or *cls* is not an actual class object (or tuple),
   this function uses the generic algorithm described above.

   .. versionadded:: 2.1

   .. versionchanged:: 2.3
      Older versions of Python did not support a tuple as the second argument.


.. c:function:: int PyCallable_Check(PyObject *o)

   Determine if the object *o* is callable.  Return ``1`` if the object is callable
   and ``0`` otherwise.  This function always succeeds.


.. c:function:: PyObject* PyObject_Call(PyObject *callable_object, PyObject *args, PyObject *kw)

   .. index:: builtin: apply

   Call a callable Python object *callable_object*, with arguments given by the
   tuple *args*, and named arguments given by the dictionary *kw*. If no named
   arguments are needed, *kw* may be *NULL*. *args* must not be *NULL*, use an
   empty tuple if no arguments are needed. Returns the result of the call on
   success, or *NULL* on failure.  This is the equivalent of the Python expression
   ``apply(callable_object, args, kw)`` or ``callable_object(*args, **kw)``.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyObject_CallObject(PyObject *callable_object, PyObject *args)

   .. index:: builtin: apply

   Call a callable Python object *callable_object*, with arguments given by the
   tuple *args*.  If no arguments are needed, then *args* may be *NULL*.  Returns
   the result of the call on success, or *NULL* on failure.  This is the equivalent
   of the Python expression ``apply(callable_object, args)`` or
   ``callable_object(*args)``.


.. c:function:: PyObject* PyObject_CallFunction(PyObject *callable, char *format, ...)

   .. index:: builtin: apply

   Call a callable Python object *callable*, with a variable number of C arguments.
   The C arguments are described using a :c:func:`Py_BuildValue` style format
   string.  The format may be *NULL*, indicating that no arguments are provided.
   Returns the result of the call on success, or *NULL* on failure.  This is the
   equivalent of the Python expression ``apply(callable, args)`` or
   ``callable(*args)``. Note that if you only pass :c:type:`PyObject \*` args,
   :c:func:`PyObject_CallFunctionObjArgs` is a faster alternative.


.. c:function:: PyObject* PyObject_CallMethod(PyObject *o, char *method, char *format, ...)

   Call the method named *method* of object *o* with a variable number of C
   arguments.  The C arguments are described by a :c:func:`Py_BuildValue` format
   string that should  produce a tuple.  The format may be *NULL*, indicating that
   no arguments are provided. Returns the result of the call on success, or *NULL*
   on failure.  This is the equivalent of the Python expression ``o.method(args)``.
   Note that if you only pass :c:type:`PyObject \*` args,
   :c:func:`PyObject_CallMethodObjArgs` is a faster alternative.


.. c:function:: PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)

   Call a callable Python object *callable*, with a variable number of
   :c:type:`PyObject\*` arguments.  The arguments are provided as a variable number
   of parameters followed by *NULL*. Returns the result of the call on success, or
   *NULL* on failure.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyObject_CallMethodObjArgs(PyObject *o, PyObject *name, ..., NULL)

   Calls a method of the object *o*, where the name of the method is given as a
   Python string object in *name*.  It is called with a variable number of
   :c:type:`PyObject\*` arguments.  The arguments are provided as a variable number
   of parameters followed by *NULL*. Returns the result of the call on success, or
   *NULL* on failure.

   .. versionadded:: 2.2


.. c:function:: long PyObject_Hash(PyObject *o)

   .. index:: builtin: hash

   Compute and return the hash value of an object *o*.  On failure, return ``-1``.
   This is the equivalent of the Python expression ``hash(o)``.


.. c:function:: long PyObject_HashNotImplemented(PyObject *o)

   Set a :exc:`TypeError` indicating that ``type(o)`` is not hashable and return ``-1``.
   This function receives special treatment when stored in a ``tp_hash`` slot,
   allowing a type to explicitly indicate to the interpreter that it is not
   hashable.

   .. versionadded:: 2.6


.. c:function:: int PyObject_IsTrue(PyObject *o)

   Returns ``1`` if the object *o* is considered to be true, and ``0`` otherwise.
   This is equivalent to the Python expression ``not not o``.  On failure, return
   ``-1``.


.. c:function:: int PyObject_Not(PyObject *o)

   Returns ``0`` if the object *o* is considered to be true, and ``1`` otherwise.
   This is equivalent to the Python expression ``not o``.  On failure, return
   ``-1``.


.. c:function:: PyObject* PyObject_Type(PyObject *o)

   .. index:: builtin: type

   When *o* is non-*NULL*, returns a type object corresponding to the object type
   of object *o*. On failure, raises :exc:`SystemError` and returns *NULL*.  This
   is equivalent to the Python expression ``type(o)``. This function increments the
   reference count of the return value. There's really no reason to use this
   function instead of the common expression ``o->ob_type``, which returns a
   pointer of type :c:type:`PyTypeObject\*`, except when the incremented reference
   count is needed.


.. c:function:: int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)

   Return true if the object *o* is of type *type* or a subtype of *type*.  Both
   parameters must be non-*NULL*.

   .. versionadded:: 2.2


.. c:function:: Py_ssize_t PyObject_Length(PyObject *o)
               Py_ssize_t PyObject_Size(PyObject *o)

   .. index:: builtin: len

   Return the length of object *o*.  If the object *o* provides either the sequence
   and mapping protocols, the sequence length is returned.  On error, ``-1`` is
   returned.  This is the equivalent to the Python expression ``len(o)``.

   .. versionchanged:: 2.5
      These functions returned an :c:type:`int` type. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyObject_GetItem(PyObject *o, PyObject *key)

   Return element of *o* corresponding to the object *key* or *NULL* on failure.
   This is the equivalent of the Python expression ``o[key]``.


.. c:function:: int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)

   Map the object *key* to the value *v*.  Raise an exception and
   return ``-1`` on failure; return ``0`` on success.  This is the
   equivalent of the Python statement ``o[key] = v``.


.. c:function:: int PyObject_DelItem(PyObject *o, PyObject *key)

   Delete the mapping for *key* from *o*.  Returns ``-1`` on failure. This is the
   equivalent of the Python statement ``del o[key]``.


.. c:function:: int PyObject_AsFileDescriptor(PyObject *o)

   Derives a file descriptor from a Python object.  If the object is an integer or
   long integer, its value is returned.  If not, the object's :meth:`fileno` method
   is called if it exists; the method must return an integer or long integer, which
   is returned as the file descriptor value.  Returns ``-1`` on failure.


.. c:function:: PyObject* PyObject_Dir(PyObject *o)

   This is equivalent to the Python expression ``dir(o)``, returning a (possibly
   empty) list of strings appropriate for the object argument, or *NULL* if there
   was an error.  If the argument is *NULL*, this is like the Python ``dir()``,
   returning the names of the current locals; in this case, if no execution frame
   is active then *NULL* is returned but :c:func:`PyErr_Occurred` will return false.


.. c:function:: PyObject* PyObject_GetIter(PyObject *o)

   This is equivalent to the Python expression ``iter(o)``. It returns a new
   iterator for the object argument, or the object  itself if the object is already
   an iterator.  Raises :exc:`TypeError` and returns *NULL* if the object cannot be
   iterated.
PK	%�\D�<11#html/_sources/c-api/objimpl.rst.txtnu�[���.. highlightlang:: c


.. _newtypes:

*****************************
Object Implementation Support
*****************************

This chapter describes the functions, types, and macros used when defining new
object types.

.. toctree::

   allocation.rst
   structures.rst
   typeobj.rst
   gcsupport.rst
PK	%�\���tvv'html/_sources/c-api/refcounting.rst.txtnu�[���.. highlightlang:: c


.. _countingrefs:

******************
Reference Counting
******************

The macros in this section are used for managing reference counts of Python
objects.


.. c:function:: void Py_INCREF(PyObject *o)

   Increment the reference count for object *o*.  The object must not be *NULL*; if
   you aren't sure that it isn't *NULL*, use :c:func:`Py_XINCREF`.


.. c:function:: void Py_XINCREF(PyObject *o)

   Increment the reference count for object *o*.  The object may be *NULL*, in
   which case the macro has no effect.


.. c:function:: void Py_DECREF(PyObject *o)

   Decrement the reference count for object *o*.  The object must not be *NULL*; if
   you aren't sure that it isn't *NULL*, use :c:func:`Py_XDECREF`.  If the reference
   count reaches zero, the object's type's deallocation function (which must not be
   *NULL*) is invoked.

   .. warning::

      The deallocation function can cause arbitrary Python code to be invoked (e.g.
      when a class instance with a :meth:`__del__` method is deallocated).  While
      exceptions in such code are not propagated, the executed code has free access to
      all Python global variables.  This means that any object that is reachable from
      a global variable should be in a consistent state before :c:func:`Py_DECREF` is
      invoked.  For example, code to delete an object from a list should copy a
      reference to the deleted object in a temporary variable, update the list data
      structure, and then call :c:func:`Py_DECREF` for the temporary variable.


.. c:function:: void Py_XDECREF(PyObject *o)

   Decrement the reference count for object *o*.  The object may be *NULL*, in
   which case the macro has no effect; otherwise the effect is the same as for
   :c:func:`Py_DECREF`, and the same warning applies.


.. c:function:: void Py_CLEAR(PyObject *o)

   Decrement the reference count for object *o*.  The object may be *NULL*, in
   which case the macro has no effect; otherwise the effect is the same as for
   :c:func:`Py_DECREF`, except that the argument is also set to *NULL*.  The warning
   for :c:func:`Py_DECREF` does not apply with respect to the object passed because
   the macro carefully uses a temporary variable and sets the argument to *NULL*
   before decrementing its reference count.

   It is a good idea to use this macro whenever decrementing the value of a
   variable that might be traversed during garbage collection.

   .. versionadded:: 2.4

The following functions are for runtime dynamic embedding of Python:
``Py_IncRef(PyObject *o)``, ``Py_DecRef(PyObject *o)``. They are
simply exported function versions of :c:func:`Py_XINCREF` and
:c:func:`Py_XDECREF`, respectively.

The following functions or macros are only for use within the interpreter core:
:c:func:`_Py_Dealloc`, :c:func:`_Py_ForgetReference`, :c:func:`_Py_NewReference`,
as well as the global variable :c:data:`_Py_RefTotal`.

PK	%�\�'
�&html/_sources/c-api/reflection.rst.txtnu�[���.. highlightlang:: c

.. _reflection:

Reflection
==========

.. c:function:: PyObject* PyEval_GetBuiltins()

   Return a dictionary of the builtins in the current execution frame,
   or the interpreter of the thread state if no frame is currently executing.


.. c:function:: PyObject* PyEval_GetLocals()

   Return a dictionary of the local variables in the current execution frame,
   or *NULL* if no frame is currently executing.


.. c:function:: PyObject* PyEval_GetGlobals()

   Return a dictionary of the global variables in the current execution frame,
   or *NULL* if no frame is currently executing.


.. c:function:: PyFrameObject* PyEval_GetFrame()

   Return the current thread state's frame, which is *NULL* if no frame is
   currently executing.


.. c:function:: int PyFrame_GetLineNumber(PyFrameObject *frame)

   Return the line number that *frame* is currently executing.


.. c:function:: int PyEval_GetRestricted()

   If there is a current frame and it is executing in restricted mode, return true,
   otherwise false.


.. c:function:: const char* PyEval_GetFuncName(PyObject *func)

   Return the name of *func* if it is a function, class or instance object, else the
   name of *func*\s type.


.. c:function:: const char* PyEval_GetFuncDesc(PyObject *func)

   Return a description string, depending on the type of *func*.
   Return values include "()" for functions and methods, " constructor",
   " instance", and " object".  Concatenated with the result of
   :c:func:`PyEval_GetFuncName`, the result will be a description of
   *func*.
PK	%�\��`s""$html/_sources/c-api/sequence.rst.txtnu�[���.. highlightlang:: c

.. _sequence:

Sequence Protocol
=================


.. c:function:: int PySequence_Check(PyObject *o)

   Return ``1`` if the object provides sequence protocol, and ``0`` otherwise.
   This function always succeeds.


.. c:function:: Py_ssize_t PySequence_Size(PyObject *o)
               Py_ssize_t PySequence_Length(PyObject *o)

   .. index:: builtin: len

   Returns the number of objects in sequence *o* on success, and ``-1`` on
   failure.  This is equivalent to the Python expression ``len(o)``.

   .. versionchanged:: 2.5
      These functions returned an :c:type:`int` type. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PySequence_Concat(PyObject *o1, PyObject *o2)

   Return the concatenation of *o1* and *o2* on success, and *NULL* on failure.
   This is the equivalent of the Python expression ``o1 + o2``.


.. c:function:: PyObject* PySequence_Repeat(PyObject *o, Py_ssize_t count)

   Return the result of repeating sequence object *o* *count* times, or *NULL* on
   failure.  This is the equivalent of the Python expression ``o * count``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *count*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PySequence_InPlaceConcat(PyObject *o1, PyObject *o2)

   Return the concatenation of *o1* and *o2* on success, and *NULL* on failure.
   The operation is done *in-place* when *o1* supports it.  This is the equivalent
   of the Python expression ``o1 += o2``.


.. c:function:: PyObject* PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)

   Return the result of repeating sequence object *o* *count* times, or *NULL* on
   failure.  The operation is done *in-place* when *o* supports it.  This is the
   equivalent of the Python expression ``o *= count``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *count*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PySequence_GetItem(PyObject *o, Py_ssize_t i)

   Return the *i*\ th element of *o*, or *NULL* on failure. This is the equivalent of
   the Python expression ``o[i]``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)

   Return the slice of sequence object *o* between *i1* and *i2*, or *NULL* on
   failure. This is the equivalent of the Python expression ``o[i1:i2]``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i1* and *i2*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v)

   Assign object *v* to the *i*\ th element of *o*.  Raise an exception
   and return ``-1`` on failure; return ``0`` on success.  This
   is the equivalent of the Python statement ``o[i] = v``.  This function *does
   not* steal a reference to *v*.

   If *v* is *NULL*, the element is deleted, however this feature is
   deprecated in favour of using :c:func:`PySequence_DelItem`.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PySequence_DelItem(PyObject *o, Py_ssize_t i)

   Delete the *i*\ th element of object *o*.  Returns ``-1`` on failure.  This is the
   equivalent of the Python statement ``del o[i]``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2, PyObject *v)

   Assign the sequence object *v* to the slice in sequence object *o* from *i1* to
   *i2*.  Raise an exception and return ``-1`` on failure; return ``0`` on success.
   This is the equivalent of the Python statement ``o[i1:i2] = v``.

   If *v* is *NULL*, the slice is deleted, however this feature is
   deprecated in favour of using :c:func:`PySequence_DelSlice`.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i1* and *i2*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2)

   Delete the slice in sequence object *o* from *i1* to *i2*.  Returns ``-1`` on
   failure.  This is the equivalent of the Python statement ``del o[i1:i2]``.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i1* and *i2*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PySequence_Count(PyObject *o, PyObject *value)

   Return the number of occurrences of *value* in *o*, that is, return the number
   of keys for which ``o[key] == value``.  On failure, return ``-1``.  This is
   equivalent to the Python expression ``o.count(value)``.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: int PySequence_Contains(PyObject *o, PyObject *value)

   Determine if *o* contains *value*.  If an item in *o* is equal to *value*,
   return ``1``, otherwise return ``0``. On error, return ``-1``.  This is
   equivalent to the Python expression ``value in o``.


.. c:function:: Py_ssize_t PySequence_Index(PyObject *o, PyObject *value)

   Return the first index *i* for which ``o[i] == value``.  On error, return
   ``-1``.    This is equivalent to the Python expression ``o.index(value)``.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PySequence_List(PyObject *o)

   Return a list object with the same contents as the arbitrary sequence *o*.  The
   returned list is guaranteed to be new.


.. c:function:: PyObject* PySequence_Tuple(PyObject *o)

   .. index:: builtin: tuple

   Return a tuple object with the same contents as the arbitrary sequence *o* or
   *NULL* on failure.  If *o* is a tuple, a new reference will be returned,
   otherwise a tuple will be constructed with the appropriate contents.  This is
   equivalent to the Python expression ``tuple(o)``.


.. c:function:: PyObject* PySequence_Fast(PyObject *o, const char *m)

   Return the sequence *o* as a list, unless it is already a tuple or list, in
   which case *o* is returned.  Use :c:func:`PySequence_Fast_GET_ITEM` to access
   the members of the result.  Returns *NULL* on failure.  If the object is not
   a sequence, raises :exc:`TypeError` with *m* as the message text.


.. c:function:: PyObject* PySequence_Fast_GET_ITEM(PyObject *o, Py_ssize_t i)

   Return the *i*\ th element of *o*, assuming that *o* was returned by
   :c:func:`PySequence_Fast`, *o* is not *NULL*, and that *i* is within bounds.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject** PySequence_Fast_ITEMS(PyObject *o)

   Return the underlying array of PyObject pointers.  Assumes that *o* was returned
   by :c:func:`PySequence_Fast` and *o* is not *NULL*.

   Note, if a list gets resized, the reallocation may relocate the items array.
   So, only use the underlying array pointer in contexts where the sequence
   cannot change.

   .. versionadded:: 2.4


.. c:function:: PyObject* PySequence_ITEM(PyObject *o, Py_ssize_t i)

   Return the *i*\ th element of *o* or *NULL* on failure. Macro form of
   :c:func:`PySequence_GetItem` but without checking that
   :c:func:`PySequence_Check` on *o* is true and without adjustment for negative
   indices.

   .. versionadded:: 2.3

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *i*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PySequence_Fast_GET_SIZE(PyObject *o)

   Returns the length of *o*, assuming that *o* was returned by
   :c:func:`PySequence_Fast` and that *o* is not *NULL*.  The size can also be
   gotten by calling :c:func:`PySequence_Size` on *o*, but
   :c:func:`PySequence_Fast_GET_SIZE` is faster because it can assume *o* is a list
   or tuple.
PK	%�\�����html/_sources/c-api/set.rst.txtnu�[���.. highlightlang:: c

.. _setobjects:

Set Objects
-----------

.. sectionauthor:: Raymond D. Hettinger <python@rcn.com>


.. index::
   object: set
   object: frozenset

.. versionadded:: 2.5

This section details the public API for :class:`set` and :class:`frozenset`
objects.  Any functionality not listed below is best accessed using the either
the abstract object protocol (including :c:func:`PyObject_CallMethod`,
:c:func:`PyObject_RichCompareBool`, :c:func:`PyObject_Hash`,
:c:func:`PyObject_Repr`, :c:func:`PyObject_IsTrue`, :c:func:`PyObject_Print`, and
:c:func:`PyObject_GetIter`) or the abstract number protocol (including
:c:func:`PyNumber_And`, :c:func:`PyNumber_Subtract`, :c:func:`PyNumber_Or`,
:c:func:`PyNumber_Xor`, :c:func:`PyNumber_InPlaceAnd`,
:c:func:`PyNumber_InPlaceSubtract`, :c:func:`PyNumber_InPlaceOr`, and
:c:func:`PyNumber_InPlaceXor`).


.. c:type:: PySetObject

   This subtype of :c:type:`PyObject` is used to hold the internal data for both
   :class:`set` and :class:`frozenset` objects.  It is like a :c:type:`PyDictObject`
   in that it is a fixed size for small sets (much like tuple storage) and will
   point to a separate, variable sized block of memory for medium and large sized
   sets (much like list storage). None of the fields of this structure should be
   considered public and are subject to change.  All access should be done through
   the documented API rather than by manipulating the values in the structure.


.. c:var:: PyTypeObject PySet_Type

   This is an instance of :c:type:`PyTypeObject` representing the Python
   :class:`set` type.


.. c:var:: PyTypeObject PyFrozenSet_Type

   This is an instance of :c:type:`PyTypeObject` representing the Python
   :class:`frozenset` type.

The following type check macros work on pointers to any Python object. Likewise,
the constructor functions work with any iterable Python object.


.. c:function:: int PySet_Check(PyObject *p)

   Return true if *p* is a :class:`set` object or an instance of a subtype.

   .. versionadded:: 2.6

.. c:function:: int PyFrozenSet_Check(PyObject *p)

   Return true if *p* is a :class:`frozenset` object or an instance of a
   subtype.

   .. versionadded:: 2.6

.. c:function:: int PyAnySet_Check(PyObject *p)

   Return true if *p* is a :class:`set` object, a :class:`frozenset` object, or an
   instance of a subtype.


.. c:function:: int PyAnySet_CheckExact(PyObject *p)

   Return true if *p* is a :class:`set` object or a :class:`frozenset` object but
   not an instance of a subtype.


.. c:function:: int PyFrozenSet_CheckExact(PyObject *p)

   Return true if *p* is a :class:`frozenset` object but not an instance of a
   subtype.


.. c:function:: PyObject* PySet_New(PyObject *iterable)

   Return a new :class:`set` containing objects returned by the *iterable*.  The
   *iterable* may be *NULL* to create a new empty set.  Return the new set on
   success or *NULL* on failure.  Raise :exc:`TypeError` if *iterable* is not
   actually iterable.  The constructor is also useful for copying a set
   (``c=set(s)``).


.. c:function:: PyObject* PyFrozenSet_New(PyObject *iterable)

   Return a new :class:`frozenset` containing objects returned by the *iterable*.
   The *iterable* may be *NULL* to create a new empty frozenset.  Return the new
   set on success or *NULL* on failure.  Raise :exc:`TypeError` if *iterable* is
   not actually iterable.

   .. versionchanged:: 2.6
      Now guaranteed to return a brand-new :class:`frozenset`.  Formerly,
      frozensets of zero-length were a singleton.  This got in the way of
      building-up new frozensets with :meth:`PySet_Add`.

The following functions and macros are available for instances of :class:`set`
or :class:`frozenset` or instances of their subtypes.


.. c:function:: Py_ssize_t PySet_Size(PyObject *anyset)

   .. index:: builtin: len

   Return the length of a :class:`set` or :class:`frozenset` object. Equivalent to
   ``len(anyset)``.  Raises a :exc:`PyExc_SystemError` if *anyset* is not a
   :class:`set`, :class:`frozenset`, or an instance of a subtype.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int`. This might require changes in
      your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PySet_GET_SIZE(PyObject *anyset)

   Macro form of :c:func:`PySet_Size` without error checking.


.. c:function:: int PySet_Contains(PyObject *anyset, PyObject *key)

   Return ``1`` if found, ``0`` if not found, and ``-1`` if an error is encountered.  Unlike
   the Python :meth:`__contains__` method, this function does not automatically
   convert unhashable sets into temporary frozensets.  Raise a :exc:`TypeError` if
   the *key* is unhashable. Raise :exc:`PyExc_SystemError` if *anyset* is not a
   :class:`set`, :class:`frozenset`, or an instance of a subtype.


.. c:function:: int PySet_Add(PyObject *set, PyObject *key)

   Add *key* to a :class:`set` instance.  Does not apply to :class:`frozenset`
   instances.  Return ``0`` on success or ``-1`` on failure. Raise a :exc:`TypeError` if
   the *key* is unhashable. Raise a :exc:`MemoryError` if there is no room to grow.
   Raise a :exc:`SystemError` if *set* is not an instance of :class:`set` or its
   subtype.

   .. versionchanged:: 2.6
      Now works with instances of :class:`frozenset` or its subtypes.
      Like :c:func:`PyTuple_SetItem` in that it can be used to fill-in the
      values of brand new frozensets before they are exposed to other code.

The following functions are available for instances of :class:`set` or its
subtypes but not for instances of :class:`frozenset` or its subtypes.


.. c:function:: int PySet_Discard(PyObject *set, PyObject *key)

   Return ``1`` if found and removed, ``0`` if not found (no action taken), and ``-1`` if an
   error is encountered.  Does not raise :exc:`KeyError` for missing keys.  Raise a
   :exc:`TypeError` if the *key* is unhashable.  Unlike the Python :meth:`~set.discard`
   method, this function does not automatically convert unhashable sets into
   temporary frozensets. Raise :exc:`PyExc_SystemError` if *set* is not an
   instance of :class:`set` or its subtype.


.. c:function:: PyObject* PySet_Pop(PyObject *set)

   Return a new reference to an arbitrary object in the *set*, and removes the
   object from the *set*.  Return *NULL* on failure.  Raise :exc:`KeyError` if the
   set is empty. Raise a :exc:`SystemError` if *set* is not an instance of
   :class:`set` or its subtype.


.. c:function:: int PySet_Clear(PyObject *set)

   Empty an existing set of all elements.
PK	%�\�3�$��!html/_sources/c-api/slice.rst.txtnu�[���.. highlightlang:: c

.. _slice-objects:

Slice Objects
-------------


.. c:var:: PyTypeObject PySlice_Type

   .. index:: single: SliceType (in module types)

   The type object for slice objects.  This is the same as ``slice`` and
   ``types.SliceType``.


.. c:function:: int PySlice_Check(PyObject *ob)

   Return true if *ob* is a slice object; *ob* must not be *NULL*.


.. c:function:: PyObject* PySlice_New(PyObject *start, PyObject *stop, PyObject *step)

   Return a new slice object with the given values.  The *start*, *stop*, and
   *step* parameters are used as the values of the slice object attributes of
   the same names.  Any of the values may be *NULL*, in which case the
   ``None`` will be used for the corresponding attribute.  Return *NULL* if
   the new object could not be allocated.


.. c:function:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)

   Retrieve the start, stop and step indices from the slice object *slice*,
   assuming a sequence of length *length*. Treats indices greater than
   *length* as errors.

   Returns ``0`` on success and ``-1`` on error with no exception set (unless one of
   the indices was not :const:`None` and failed to be converted to an integer,
   in which case ``-1`` is returned with an exception set).

   You probably do not want to use this function.  If you want to use slice
   objects in versions of Python prior to 2.3, you would probably do well to
   incorporate the source of :c:func:`PySlice_GetIndicesEx`, suitably renamed,
   in the source of your extension.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *length* and an
      :c:type:`int *` type for *start*, *stop*, and *step*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)

   Usable replacement for :c:func:`PySlice_GetIndices`.  Retrieve the start,
   stop, and step indices from the slice object *slice* assuming a sequence of
   length *length*, and store the length of the slice in *slicelength*.  Out
   of bounds indices are clipped in a manner consistent with the handling of
   normal slices.

   Returns ``0`` on success and ``-1`` on error with exception set.

   .. versionadded:: 2.3

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *length* and an
      :c:type:`int *` type for *start*, *stop*, *step*, and *slicelength*. This
      might require changes in your code for properly supporting 64-bit
      systems.


Ellipsis Object
---------------


.. c:var:: PyObject *Py_Ellipsis

   The Python ``Ellipsis`` object.  This object has no methods.  It needs to be
   treated just like any other object with respect to reference counts.  Like
   :c:data:`Py_None` it is a singleton object.
PK	%�\Qē'><><"html/_sources/c-api/string.rst.txtnu�[���.. highlightlang:: c

.. _stringobjects:

String/Bytes Objects
--------------------

These functions raise :exc:`TypeError` when expecting a string parameter and are
called with a non-string parameter.

.. note::

   These functions have been renamed to PyBytes_* in Python 3.x. Unless
   otherwise noted, the PyBytes functions available in 3.x are aliased to their
   PyString_* equivalents to help porting.

.. index:: object: string


.. c:type:: PyStringObject

   This subtype of :c:type:`PyObject` represents a Python string object.


.. c:var:: PyTypeObject PyString_Type

   .. index:: single: StringType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python string type; it is
   the same object as ``str`` and ``types.StringType`` in the Python layer. .


.. c:function:: int PyString_Check(PyObject *o)

   Return true if the object *o* is a string object or an instance of a subtype of
   the string type.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyString_CheckExact(PyObject *o)

   Return true if the object *o* is a string object, but not an instance of a
   subtype of the string type.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyString_FromString(const char *v)

   Return a new string object with a copy of the string *v* as value on success,
   and *NULL* on failure.  The parameter *v* must not be *NULL*; it will not be
   checked.


.. c:function:: PyObject* PyString_FromStringAndSize(const char *v, Py_ssize_t len)

   Return a new string object with a copy of the string *v* as value and length
   *len* on success, and *NULL* on failure.  If *v* is *NULL*, the contents of the
   string are uninitialized.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *len*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyString_FromFormat(const char *format, ...)

   Take a C :c:func:`printf`\ -style *format* string and a variable number of
   arguments, calculate the size of the resulting Python string and return a string
   with the values formatted into it.  The variable arguments must be C types and
   must correspond exactly to the format characters in the *format* string.  The
   following format characters are allowed:

   .. % This should be exactly the same as the table in PyErr_Format.
   .. % One should just refer to the other.
   .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
   .. % because not all compilers support the %z width modifier -- we fake it
   .. % when necessary via interpolating PY_FORMAT_SIZE_T.
   .. % Similar comments apply to the %ll width modifier and
   .. % PY_FORMAT_LONG_LONG.
   .. % %u, %lu, %zu should have "new in Python 2.5" blurbs.

   +-------------------+---------------+--------------------------------+
   | Format Characters | Type          | Comment                        |
   +===================+===============+================================+
   | :attr:`%%`        | *n/a*         | The literal % character.       |
   +-------------------+---------------+--------------------------------+
   | :attr:`%c`        | int           | A single character,            |
   |                   |               | represented as a C int.        |
   +-------------------+---------------+--------------------------------+
   | :attr:`%d`        | int           | Exactly equivalent to          |
   |                   |               | ``printf("%d")``.              |
   +-------------------+---------------+--------------------------------+
   | :attr:`%u`        | unsigned int  | Exactly equivalent to          |
   |                   |               | ``printf("%u")``.              |
   +-------------------+---------------+--------------------------------+
   | :attr:`%ld`       | long          | Exactly equivalent to          |
   |                   |               | ``printf("%ld")``.             |
   +-------------------+---------------+--------------------------------+
   | :attr:`%lu`       | unsigned long | Exactly equivalent to          |
   |                   |               | ``printf("%lu")``.             |
   +-------------------+---------------+--------------------------------+
   | :attr:`%lld`      | long long     | Exactly equivalent to          |
   |                   |               | ``printf("%lld")``.            |
   +-------------------+---------------+--------------------------------+
   | :attr:`%llu`      | unsigned      | Exactly equivalent to          |
   |                   | long long     | ``printf("%llu")``.            |
   +-------------------+---------------+--------------------------------+
   | :attr:`%zd`       | Py_ssize_t    | Exactly equivalent to          |
   |                   |               | ``printf("%zd")``.             |
   +-------------------+---------------+--------------------------------+
   | :attr:`%zu`       | size_t        | Exactly equivalent to          |
   |                   |               | ``printf("%zu")``.             |
   +-------------------+---------------+--------------------------------+
   | :attr:`%i`        | int           | Exactly equivalent to          |
   |                   |               | ``printf("%i")``.              |
   +-------------------+---------------+--------------------------------+
   | :attr:`%x`        | int           | Exactly equivalent to          |
   |                   |               | ``printf("%x")``.              |
   +-------------------+---------------+--------------------------------+
   | :attr:`%s`        | char\*        | A null-terminated C character  |
   |                   |               | array.                         |
   +-------------------+---------------+--------------------------------+
   | :attr:`%p`        | void\*        | The hex representation of a C  |
   |                   |               | pointer. Mostly equivalent to  |
   |                   |               | ``printf("%p")`` except that   |
   |                   |               | it is guaranteed to start with |
   |                   |               | the literal ``0x`` regardless  |
   |                   |               | of what the platform's         |
   |                   |               | ``printf`` yields.             |
   +-------------------+---------------+--------------------------------+

   An unrecognized format character causes all the rest of the format string to be
   copied as-is to the result string, and any extra arguments discarded.

   .. note::

      The `"%lld"` and `"%llu"` format specifiers are only available
      when :const:`HAVE_LONG_LONG` is defined.

   .. versionchanged:: 2.7
      Support for `"%lld"` and `"%llu"` added.


.. c:function:: PyObject* PyString_FromFormatV(const char *format, va_list vargs)

   Identical to :c:func:`PyString_FromFormat` except that it takes exactly two
   arguments.


.. c:function:: Py_ssize_t PyString_Size(PyObject *string)

   Return the length of the string in string object *string*.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyString_GET_SIZE(PyObject *string)

   Macro form of :c:func:`PyString_Size` but without error checking.

   .. versionchanged:: 2.5
      This macro returned an :c:type:`int` type. This might require changes in
      your code for properly supporting 64-bit systems.


.. c:function:: char* PyString_AsString(PyObject *string)

   Return a NUL-terminated representation of the contents of *string*.  The pointer
   refers to the internal buffer of *string*, not a copy.  The data must not be
   modified in any way, unless the string was just created using
   ``PyString_FromStringAndSize(NULL, size)``. It must not be deallocated.  If
   *string* is a Unicode object, this function computes the default encoding of
   *string* and operates on that.  If *string* is not a string object at all,
   :c:func:`PyString_AsString` returns *NULL* and raises :exc:`TypeError`.


.. c:function:: char* PyString_AS_STRING(PyObject *string)

   Macro form of :c:func:`PyString_AsString` but without error checking.  Only
   string objects are supported; no Unicode objects should be passed.


.. c:function:: int PyString_AsStringAndSize(PyObject *obj, char **buffer, Py_ssize_t *length)

   Return a NUL-terminated representation of the contents of the object *obj*
   through the output variables *buffer* and *length*.

   The function accepts both string and Unicode objects as input. For Unicode
   objects it returns the default encoded version of the object.  If *length* is
   *NULL*, the resulting buffer may not contain NUL characters; if it does, the
   function returns ``-1`` and a :exc:`TypeError` is raised.

   The buffer refers to an internal string buffer of *obj*, not a copy. The data
   must not be modified in any way, unless the string was just created using
   ``PyString_FromStringAndSize(NULL, size)``.  It must not be deallocated.  If
   *string* is a Unicode object, this function computes the default encoding of
   *string* and operates on that.  If *string* is not a string object at all,
   :c:func:`PyString_AsStringAndSize` returns ``-1`` and raises :exc:`TypeError`.

   .. versionchanged:: 2.5
      This function used an :c:type:`int *` type for *length*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: void PyString_Concat(PyObject **string, PyObject *newpart)

   Create a new string object in *\*string* containing the contents of *newpart*
   appended to *string*; the caller will own the new reference.  The reference to
   the old value of *string* will be stolen.  If the new string cannot be created,
   the old reference to *string* will still be discarded and the value of
   *\*string* will be set to *NULL*; the appropriate exception will be set.


.. c:function:: void PyString_ConcatAndDel(PyObject **string, PyObject *newpart)

   Create a new string object in *\*string* containing the contents of *newpart*
   appended to *string*.  This version decrements the reference count of *newpart*.


.. c:function:: int _PyString_Resize(PyObject **string, Py_ssize_t newsize)

   A way to resize a string object even though it is "immutable". Only use this to
   build up a brand new string object; don't use this if the string may already be
   known in other parts of the code.  It is an error to call this function if the
   refcount on the input string object is not one. Pass the address of an existing
   string object as an lvalue (it may be written into), and the new size desired.
   On success, *\*string* holds the resized string object and ``0`` is returned;
   the address in *\*string* may differ from its input value.  If the reallocation
   fails, the original string object at *\*string* is deallocated, *\*string* is
   set to *NULL*, a memory exception is set, and ``-1`` is returned.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *newsize*. This might
      require changes in your code for properly supporting 64-bit systems.

.. c:function:: PyObject* PyString_Format(PyObject *format, PyObject *args)

   Return a new string object from *format* and *args*. Analogous to ``format %
   args``.  The *args* argument must be a tuple or dict.


.. c:function:: void PyString_InternInPlace(PyObject **string)

   Intern the argument *\*string* in place.  The argument must be the address of a
   pointer variable pointing to a Python string object.  If there is an existing
   interned string that is the same as *\*string*, it sets *\*string* to it
   (decrementing the reference count of the old string object and incrementing the
   reference count of the interned string object), otherwise it leaves *\*string*
   alone and interns it (incrementing its reference count).  (Clarification: even
   though there is a lot of talk about reference counts, think of this function as
   reference-count-neutral; you own the object after the call if and only if you
   owned it before the call.)

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.


.. c:function:: PyObject* PyString_InternFromString(const char *v)

   A combination of :c:func:`PyString_FromString` and
   :c:func:`PyString_InternInPlace`, returning either a new string object that has
   been interned, or a new ("owned") reference to an earlier interned string object
   with the same value.

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.


.. c:function:: PyObject* PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)

   Create an object by decoding *size* bytes of the encoded buffer *s* using the
   codec registered for *encoding*.  *encoding* and *errors* have the same meaning
   as the parameters of the same name in the :func:`unicode` built-in function.
   The codec to be used is looked up using the Python codec registry.  Return
   *NULL* if an exception was raised by the codec.

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyString_AsDecodedObject(PyObject *str, const char *encoding, const char *errors)

   Decode a string object by passing it to the codec registered for *encoding* and
   return the result as Python object. *encoding* and *errors* have the same
   meaning as the parameters of the same name in the string :meth:`encode` method.
   The codec to be used is looked up using the Python codec registry. Return *NULL*
   if an exception was raised by the codec.

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.


.. c:function:: PyObject* PyString_Encode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)

   Encode the :c:type:`char` buffer of the given size by passing it to the codec
   registered for *encoding* and return a Python object. *encoding* and *errors*
   have the same meaning as the parameters of the same name in the string
   :meth:`encode` method. The codec to be used is looked up using the Python codec
   registry.  Return *NULL* if an exception was raised by the codec.

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyString_AsEncodedObject(PyObject *str, const char *encoding, const char *errors)

   Encode a string object using the codec registered for *encoding* and return the
   result as Python object. *encoding* and *errors* have the same meaning as the
   parameters of the same name in the string :meth:`encode` method. The codec to be
   used is looked up using the Python codec registry. Return *NULL* if an exception
   was raised by the codec.

   .. note::

      This function is not available in 3.x and does not have a PyBytes alias.
PK	%�\����v:v:&html/_sources/c-api/structures.rst.txtnu�[���.. highlightlang:: c

.. _common-structs:

Common Object Structures
========================

There are a large number of structures which are used in the definition of
object types for Python.  This section describes these structures and how they
are used.

All Python objects ultimately share a small number of fields at the beginning
of the object's representation in memory.  These are represented by the
:c:type:`PyObject` and :c:type:`PyVarObject` types, which are defined, in turn,
by the expansions of some macros also used, whether directly or indirectly, in
the definition of all other Python objects.


.. c:type:: PyObject

   All object types are extensions of this type.  This is a type which
   contains the information Python needs to treat a pointer to an object as an
   object.  In a normal "release" build, it contains only the object's
   reference count and a pointer to the corresponding type object.  It
   corresponds to the fields defined by the expansion of the ``PyObject_HEAD``
   macro.


.. c:type:: PyVarObject

   This is an extension of :c:type:`PyObject` that adds the :attr:`ob_size`
   field.  This is only used for objects that have some notion of *length*.
   This type does not often appear in the Python/C API.  It corresponds to the
   fields defined by the expansion of the ``PyObject_VAR_HEAD`` macro.

These macros are used in the definition of :c:type:`PyObject` and
:c:type:`PyVarObject`:


.. c:macro:: PyObject_HEAD

   This is a macro which expands to the declarations of the fields of the
   :c:type:`PyObject` type; it is used when declaring new types which represent
   objects without a varying length.  The specific fields it expands to depend
   on the definition of :c:macro:`Py_TRACE_REFS`.  By default, that macro is
   not defined, and :c:macro:`PyObject_HEAD` expands to::

      Py_ssize_t ob_refcnt;
      PyTypeObject *ob_type;

   When :c:macro:`Py_TRACE_REFS` is defined, it expands to::

      PyObject *_ob_next, *_ob_prev;
      Py_ssize_t ob_refcnt;
      PyTypeObject *ob_type;


.. c:macro:: PyObject_VAR_HEAD

   This is a macro which expands to the declarations of the fields of the
   :c:type:`PyVarObject` type; it is used when declaring new types which
   represent objects with a length that varies from instance to instance.
   This macro always expands to::

      PyObject_HEAD
      Py_ssize_t ob_size;

   Note that :c:macro:`PyObject_HEAD` is part of the expansion, and that its own
   expansion varies depending on the definition of :c:macro:`Py_TRACE_REFS`.


.. c:macro:: Py_TYPE(o)

   This macro is used to access the :attr:`ob_type` member of a Python object.
   It expands to::

      (((PyObject*)(o))->ob_type)

   .. versionadded:: 2.6


.. c:macro:: Py_REFCNT(o)

   This macro is used to access the :attr:`ob_refcnt` member of a Python
   object.
   It expands to::

      (((PyObject*)(o))->ob_refcnt)

   .. versionadded:: 2.6


.. c:macro:: Py_SIZE(o)

   This macro is used to access the :attr:`ob_size` member of a Python object.
   It expands to::

      (((PyVarObject*)(o))->ob_size)

   .. versionadded:: 2.6


.. c:macro:: PyObject_HEAD_INIT(type)

   This is a macro which expands to initialization values for a new
   :c:type:`PyObject` type.  This macro expands to::

      _PyObject_EXTRA_INIT
      1, type,


.. c:macro:: PyVarObject_HEAD_INIT(type, size)

   This is a macro which expands to initialization values for a new
   :c:type:`PyVarObject` type, including the :attr:`ob_size` field.
   This macro expands to::

      _PyObject_EXTRA_INIT
      1, type, size,


.. c:type:: PyCFunction

   Type of the functions used to implement most Python callables in C.
   Functions of this type take two :c:type:`PyObject\*` parameters and return
   one such value.  If the return value is *NULL*, an exception shall have
   been set.  If not *NULL*, the return value is interpreted as the return
   value of the function as exposed in Python.  The function must return a new
   reference.


.. c:type:: PyMethodDef

   Structure used to describe a method of an extension type.  This structure has
   four fields:

   +------------------+-------------+-------------------------------+
   | Field            | C Type      | Meaning                       |
   +==================+=============+===============================+
   | :attr:`ml_name`  | char \*     | name of the method            |
   +------------------+-------------+-------------------------------+
   | :attr:`ml_meth`  | PyCFunction | pointer to the C              |
   |                  |             | implementation                |
   +------------------+-------------+-------------------------------+
   | :attr:`ml_flags` | int         | flag bits indicating how the  |
   |                  |             | call should be constructed    |
   +------------------+-------------+-------------------------------+
   | :attr:`ml_doc`   | char \*     | points to the contents of the |
   |                  |             | docstring                     |
   +------------------+-------------+-------------------------------+

The :attr:`ml_meth` is a C function pointer.  The functions may be of different
types, but they always return :c:type:`PyObject\*`.  If the function is not of
the :c:type:`PyCFunction`, the compiler will require a cast in the method table.
Even though :c:type:`PyCFunction` defines the first parameter as
:c:type:`PyObject\*`, it is common that the method implementation uses the
specific C type of the *self* object.

The :attr:`ml_flags` field is a bitfield which can include the following flags.
The individual flags indicate either a calling convention or a binding
convention.  Of the calling convention flags, only :const:`METH_VARARGS` and
:const:`METH_KEYWORDS` can be combined. Any of the calling convention flags
can be combined with a binding flag.


.. data:: METH_VARARGS

   This is the typical calling convention, where the methods have the type
   :c:type:`PyCFunction`. The function expects two :c:type:`PyObject\*` values.
   The first one is the *self* object for methods; for module functions, it is
   the module object.  The second parameter (often called *args*) is a tuple
   object representing all arguments.  This parameter is typically processed
   using :c:func:`PyArg_ParseTuple` or :c:func:`PyArg_UnpackTuple`.


.. data:: METH_KEYWORDS

   Methods with these flags must be of type :c:type:`PyCFunctionWithKeywords`.
   The function expects three parameters: *self*, *args*, and a dictionary of
   all the keyword arguments.  The flag is typically combined with
   :const:`METH_VARARGS`, and the parameters are typically processed using
   :c:func:`PyArg_ParseTupleAndKeywords`.


.. data:: METH_NOARGS

   Methods without parameters don't need to check whether arguments are given if
   they are listed with the :const:`METH_NOARGS` flag.  They need to be of type
   :c:type:`PyCFunction`.  The first parameter is typically named ``self`` and
   will hold a reference to the module or object instance.  In all cases the
   second parameter will be *NULL*.


.. data:: METH_O

   Methods with a single object argument can be listed with the :const:`METH_O`
   flag, instead of invoking :c:func:`PyArg_ParseTuple` with a ``"O"`` argument.
   They have the type :c:type:`PyCFunction`, with the *self* parameter, and a
   :c:type:`PyObject\*` parameter representing the single argument.


.. data:: METH_OLDARGS

   This calling convention is deprecated.  The method must be of type
   :c:type:`PyCFunction`.  The second argument is *NULL* if no arguments are
   given, a single object if exactly one argument is given, and a tuple of
   objects if more than one argument is given.  There is no way for a function
   using this convention to distinguish between a call with multiple arguments
   and a call with a tuple as the only argument.

These two constants are not used to indicate the calling convention but the
binding when use with methods of classes.  These may not be used for functions
defined for modules.  At most one of these flags may be set for any given
method.


.. data:: METH_CLASS

   .. index:: builtin: classmethod

   The method will be passed the type object as the first parameter rather
   than an instance of the type.  This is used to create *class methods*,
   similar to what is created when using the :func:`classmethod` built-in
   function.

   .. versionadded:: 2.3


.. data:: METH_STATIC

   .. index:: builtin: staticmethod

   The method will be passed *NULL* as the first parameter rather than an
   instance of the type.  This is used to create *static methods*, similar to
   what is created when using the :func:`staticmethod` built-in function.

   .. versionadded:: 2.3

One other constant controls whether a method is loaded in place of another
definition with the same method name.


.. data:: METH_COEXIST

   The method will be loaded in place of existing definitions.  Without
   *METH_COEXIST*, the default is to skip repeated definitions.  Since slot
   wrappers are loaded before the method table, the existence of a
   *sq_contains* slot, for example, would generate a wrapped method named
   :meth:`__contains__` and preclude the loading of a corresponding
   PyCFunction with the same name.  With the flag defined, the PyCFunction
   will be loaded in place of the wrapper object and will co-exist with the
   slot.  This is helpful because calls to PyCFunctions are optimized more
   than wrapper object calls.

   .. versionadded:: 2.4


.. c:type:: PyMemberDef

   Structure which describes an attribute of a type which corresponds to a C
   struct member.  Its fields are:

   +------------------+-------------+-------------------------------+
   | Field            | C Type      | Meaning                       |
   +==================+=============+===============================+
   | :attr:`name`     | char \*     | name of the member            |
   +------------------+-------------+-------------------------------+
   | :attr:`!type`    | int         | the type of the member in the |
   |                  |             | C struct                      |
   +------------------+-------------+-------------------------------+
   | :attr:`offset`   | Py_ssize_t  | the offset in bytes that the  |
   |                  |             | member is located on the      |
   |                  |             | type's object struct          |
   +------------------+-------------+-------------------------------+
   | :attr:`flags`    | int         | flag bits indicating if the   |
   |                  |             | field should be read-only or  |
   |                  |             | writable                      |
   +------------------+-------------+-------------------------------+
   | :attr:`doc`      | char \*     | points to the contents of the |
   |                  |             | docstring                     |
   +------------------+-------------+-------------------------------+

   :attr:`!type` can be one of many ``T_`` macros corresponding to various C
   types.  When the member is accessed in Python, it will be converted to the
   equivalent Python type.

   =============== ==================
   Macro name      C type
   =============== ==================
   T_SHORT         short
   T_INT           int
   T_LONG          long
   T_FLOAT         float
   T_DOUBLE        double
   T_STRING        char \*
   T_OBJECT        PyObject \*
   T_OBJECT_EX     PyObject \*
   T_CHAR          char
   T_BYTE          char
   T_UBYTE         unsigned char
   T_UINT          unsigned int
   T_USHORT        unsigned short
   T_ULONG         unsigned long
   T_BOOL          char
   T_LONGLONG      long long
   T_ULONGLONG     unsigned long long
   T_PYSSIZET      Py_ssize_t
   =============== ==================

   :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX` differ in that
   :c:macro:`T_OBJECT` returns ``None`` if the member is *NULL* and
   :c:macro:`T_OBJECT_EX` raises an :exc:`AttributeError`.  Try to use
   :c:macro:`T_OBJECT_EX` over :c:macro:`T_OBJECT` because :c:macro:`T_OBJECT_EX`
   handles use of the :keyword:`del` statement on that attribute more correctly
   than :c:macro:`T_OBJECT`.

   :attr:`flags` can be ``0`` for write and read access or :c:macro:`READONLY` for
   read-only access.  Using :c:macro:`T_STRING` for :attr:`type` implies
   :c:macro:`READONLY`.  Only :c:macro:`T_OBJECT` and :c:macro:`T_OBJECT_EX`
   members can be deleted.  (They are set to *NULL*).


.. c:type:: PyGetSetDef

   Structure to define property-like access for a type. See also description of
   the :c:member:`PyTypeObject.tp_getset` slot.

   +-------------+------------------+-----------------------------------+
   | Field       | C Type           | Meaning                           |
   +=============+==================+===================================+
   | name        | char \*          | attribute name                    |
   +-------------+------------------+-----------------------------------+
   | get         | getter           | C Function to get the attribute   |
   +-------------+------------------+-----------------------------------+
   | set         | setter           | optional C function to set or     |
   |             |                  | delete the attribute, if omitted  |
   |             |                  | the attribute is readonly         |
   +-------------+------------------+-----------------------------------+
   | doc         | char \*          | optional docstring                |
   +-------------+------------------+-----------------------------------+
   | closure     | void \*          | optional function pointer,        |
   |             |                  | providing additional data for     |
   |             |                  | getter and setter                 |
   +-------------+------------------+-----------------------------------+

   The ``get`` function takes one :c:type:`PyObject\*` parameter (the
   instance) and a function pointer (the associated ``closure``)::

      typedef PyObject *(*getter)(PyObject *, void *);

   It should return a new reference on success or *NULL* with a set exception
   on failure.

   ``set`` functions take two :c:type:`PyObject\*` parameters (the instance and
   the value to be set) and a function pointer (the associated ``closure``)::

      typedef int (*setter)(PyObject *, PyObject *, void *);

   In case the attribute should be deleted the second parameter is *NULL*.
   Should return ``0`` on success or ``-1`` with a set exception on failure.


.. c:function:: PyObject* Py_FindMethod(PyMethodDef table[], PyObject *ob, char *name)

   Return a bound method object for an extension type implemented in C.  This
   can be useful in the implementation of a :c:member:`~PyTypeObject.tp_getattro` or
   :c:member:`~PyTypeObject.tp_getattr` handler that does not use the
   :c:func:`PyObject_GenericGetAttr` function.
PK	%�\$�+�RRhtml/_sources/c-api/sys.rst.txtnu�[���.. highlightlang:: c

.. _os:

Operating System Utilities
==========================


.. c:function:: int Py_FdIsInteractive(FILE *fp, const char *filename)

   Return true (nonzero) if the standard I/O file *fp* with name *filename* is
   deemed interactive.  This is the case for files for which ``isatty(fileno(fp))``
   is true.  If the global flag :c:data:`Py_InteractiveFlag` is true, this function
   also returns true if the *filename* pointer is *NULL* or if the name is equal to
   one of the strings ``'<stdin>'`` or ``'???'``.


.. c:function:: void PyOS_AfterFork()

   Function to update some internal state after a process fork; this should be
   called in the new process if the Python interpreter will continue to be used.
   If a new executable is loaded into the new process, this function does not need
   to be called.


.. c:function:: int PyOS_CheckStack()

   Return true when the interpreter runs out of stack space.  This is a reliable
   check, but is only available when :const:`USE_STACKCHECK` is defined (currently
   on Windows using the Microsoft Visual C++ compiler).  :const:`USE_STACKCHECK`
   will be defined automatically; you should never change the definition in your
   own code.


.. c:function:: PyOS_sighandler_t PyOS_getsig(int i)

   Return the current signal handler for signal *i*.  This is a thin wrapper around
   either :c:func:`sigaction` or :c:func:`signal`.  Do not call those functions
   directly! :c:type:`PyOS_sighandler_t` is a typedef alias for :c:type:`void
   (\*)(int)`.


.. c:function:: PyOS_sighandler_t PyOS_setsig(int i, PyOS_sighandler_t h)

   Set the signal handler for signal *i* to be *h*; return the old signal handler.
   This is a thin wrapper around either :c:func:`sigaction` or :c:func:`signal`.  Do
   not call those functions directly!  :c:type:`PyOS_sighandler_t` is a typedef
   alias for :c:type:`void (\*)(int)`.

.. _systemfunctions:

System Functions
================

These are utility functions that make functionality from the :mod:`sys` module
accessible to C code.  They all work with the current interpreter thread's
:mod:`sys` module's dict, which is contained in the internal thread state structure.

.. c:function:: PyObject *PySys_GetObject(char *name)

   Return the object *name* from the :mod:`sys` module or *NULL* if it does
   not exist, without setting an exception.

.. c:function:: FILE *PySys_GetFile(char *name, FILE *def)

   Return the :c:type:`FILE*` associated with the object *name* in the
   :mod:`sys` module, or *def* if *name* is not in the module or is not associated
   with a :c:type:`FILE*`.

.. c:function:: int PySys_SetObject(char *name, PyObject *v)

   Set *name* in the :mod:`sys` module to *v* unless *v* is *NULL*, in which
   case *name* is deleted from the sys module. Returns ``0`` on success, ``-1``
   on error.

.. c:function:: void PySys_ResetWarnOptions()

   Reset :data:`sys.warnoptions` to an empty list.

.. c:function:: void PySys_AddWarnOption(char *s)

   Append *s* to :data:`sys.warnoptions`.

.. c:function:: void PySys_SetPath(char *path)

   Set :data:`sys.path` to a list object of paths found in *path* which should
   be a list of paths separated with the platform's search path delimiter
   (``:`` on Unix, ``;`` on Windows).

.. c:function:: void PySys_WriteStdout(const char *format, ...)

   Write the output string described by *format* to :data:`sys.stdout`.  No
   exceptions are raised, even if truncation occurs (see below).

   *format* should limit the total size of the formatted output string to
   1000 bytes or less -- after 1000 bytes, the output string is truncated.
   In particular, this means that no unrestricted "%s" formats should occur;
   these should be limited using "%.<N>s" where <N> is a decimal number
   calculated so that <N> plus the maximum size of other formatted text does not
   exceed 1000 bytes.  Also watch out for "%f", which can print hundreds of
   digits for very large numbers.

   If a problem occurs, or :data:`sys.stdout` is unset, the formatted message
   is written to the real (C level) *stdout*.

.. c:function:: void PySys_WriteStderr(const char *format, ...)

   As above, but write to :data:`sys.stderr` or *stderr* instead.


.. _processcontrol:

Process Control
===============


.. c:function:: void Py_FatalError(const char *message)

   .. index:: single: abort()

   Print a fatal error message and kill the process.  No cleanup is performed.
   This function should only be invoked when a condition is detected that would
   make it dangerous to continue using the Python interpreter; e.g., when the
   object administration appears to be corrupted.  On Unix, the standard C library
   function :c:func:`abort` is called which will attempt to produce a :file:`core`
   file.


.. c:function:: void Py_Exit(int status)

   .. index::
      single: Py_Finalize()
      single: exit()

   Exit the current process.  This calls :c:func:`Py_Finalize` and then calls the
   standard C library function ``exit(status)``.


.. c:function:: int Py_AtExit(void (*func) ())

   .. index::
      single: Py_Finalize()
      single: cleanup functions

   Register a cleanup function to be called by :c:func:`Py_Finalize`.  The cleanup
   function will be called with no arguments and should return no value.  At most
   32 cleanup functions can be registered.  When the registration is successful,
   :c:func:`Py_AtExit` returns ``0``; on failure, it returns ``-1``.  The cleanup
   function registered last is called first. Each cleanup function will be called
   at most once.  Since Python's internal finalization will have completed before
   the cleanup function, no Python APIs should be called by *func*.
PK	%�\Fm�hss!html/_sources/c-api/tuple.rst.txtnu�[���.. highlightlang:: c

.. _tupleobjects:

Tuple Objects
-------------

.. index:: object: tuple


.. c:type:: PyTupleObject

   This subtype of :c:type:`PyObject` represents a Python tuple object.


.. c:var:: PyTypeObject PyTuple_Type

   .. index:: single: TupleType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python tuple type; it is
   the same object as ``tuple`` and ``types.TupleType`` in the Python layer..


.. c:function:: int PyTuple_Check(PyObject *p)

   Return true if *p* is a tuple object or an instance of a subtype of the tuple
   type.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyTuple_CheckExact(PyObject *p)

   Return true if *p* is a tuple object, but not an instance of a subtype of the
   tuple type.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyTuple_New(Py_ssize_t len)

   Return a new tuple object of size *len*, or *NULL* on failure.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *len*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyTuple_Pack(Py_ssize_t n, ...)

   Return a new tuple object of size *n*, or *NULL* on failure. The tuple values
   are initialized to the subsequent *n* C arguments pointing to Python objects.
   ``PyTuple_Pack(2, a, b)`` is equivalent to ``Py_BuildValue("(OO)", a, b)``.

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *n*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyTuple_Size(PyObject *p)

   Take a pointer to a tuple object, and return the size of that tuple.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyTuple_GET_SIZE(PyObject *p)

   Return the size of the tuple *p*, which must be non-*NULL* and point to a tuple;
   no error checking is performed.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyTuple_GetItem(PyObject *p, Py_ssize_t pos)

   Return the object at position *pos* in the tuple pointed to by *p*.  If *pos* is
   out of bounds, return *NULL* and sets an :exc:`IndexError` exception.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *pos*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyTuple_GET_ITEM(PyObject *p, Py_ssize_t pos)

   Like :c:func:`PyTuple_GetItem`, but does no checking of its arguments.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *pos*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyTuple_GetSlice(PyObject *p, Py_ssize_t low, Py_ssize_t high)

   Take a slice of the tuple pointed to by *p* from *low* to *high* and return it
   as a new tuple.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *low* and *high*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyTuple_SetItem(PyObject *p, Py_ssize_t pos, PyObject *o)

   Insert a reference to object *o* at position *pos* of the tuple pointed to by
   *p*. Return ``0`` on success.

   .. note::

      This function "steals" a reference to *o*.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *pos*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: void PyTuple_SET_ITEM(PyObject *p, Py_ssize_t pos, PyObject *o)

   Like :c:func:`PyTuple_SetItem`, but does no error checking, and should *only* be
   used to fill in brand new tuples.

   .. note::

      This function "steals" a reference to *o*.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *pos*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int _PyTuple_Resize(PyObject **p, Py_ssize_t newsize)

   Can be used to resize a tuple.  *newsize* will be the new length of the tuple.
   Because tuples are *supposed* to be immutable, this should only be used if there
   is only one reference to the object.  Do *not* use this if the tuple may already
   be known to some other part of the code.  The tuple will always grow or shrink
   at the end.  Think of this as destroying the old tuple and creating a new one,
   only more efficiently.  Returns ``0`` on success. Client code should never
   assume that the resulting value of ``*p`` will be the same as before calling
   this function. If the object referenced by ``*p`` is replaced, the original
   ``*p`` is destroyed.  On failure, returns ``-1`` and sets ``*p`` to *NULL*, and
   raises :exc:`MemoryError` or :exc:`SystemError`.

   .. versionchanged:: 2.2
      Removed unused third parameter, *last_is_sticky*.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *newsize*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyTuple_ClearFreeList()

   Clear the free list. Return the total number of freed items.

   .. versionadded:: 2.6
PK	%�\>d5��
�
 html/_sources/c-api/type.rst.txtnu�[���.. highlightlang:: c

.. _typeobjects:

Type Objects
------------

.. index:: object: type


.. c:type:: PyTypeObject

   The C structure of the objects used to describe built-in types.


.. c:var:: PyObject* PyType_Type

   .. index:: single: TypeType (in module types)

   This is the type object for type objects; it is the same object as ``type`` and
   ``types.TypeType`` in the Python layer.


.. c:function:: int PyType_Check(PyObject *o)

   Return true if the object *o* is a type object, including instances of types
   derived from the standard type object.  Return false in all other cases.


.. c:function:: int PyType_CheckExact(PyObject *o)

   Return true if the object *o* is a type object, but not a subtype of the
   standard type object.  Return false in all other cases.

   .. versionadded:: 2.2


.. c:function:: unsigned int PyType_ClearCache()

   Clear the internal lookup cache. Return the current version tag.

   .. versionadded:: 2.6


.. c:function:: void PyType_Modified(PyTypeObject *type)

   Invalidate the internal lookup cache for the type and all of its
   subtypes.  This function must be called after any manual
   modification of the attributes or base classes of the type.

   .. versionadded:: 2.6


.. c:function:: int PyType_HasFeature(PyObject *o, int feature)

   Return true if the type object *o* sets the feature *feature*.  Type features
   are denoted by single bit flags.


.. c:function:: int PyType_IS_GC(PyObject *o)

   Return true if the type object includes support for the cycle detector; this
   tests the type flag :const:`Py_TPFLAGS_HAVE_GC`.

   .. versionadded:: 2.0


.. c:function:: int PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)

   Return true if *a* is a subtype of *b*.

   .. versionadded:: 2.2

   This function only checks for actual subtypes, which means that
   :meth:`~class.__subclasscheck__` is not called on *b*.  Call
   :c:func:`PyObject_IsSubclass` to do the same check that :func:`issubclass`
   would do.


.. c:function:: PyObject* PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)

   .. versionadded:: 2.2

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *nitems*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)

   .. versionadded:: 2.2


.. c:function:: int PyType_Ready(PyTypeObject *type)

   Finalize a type object.  This should be called on all type objects to finish
   their initialization.  This function is responsible for adding inherited slots
   from a type's base class.  Return ``0`` on success, or return ``-1`` and sets an
   exception on error.

   .. versionadded:: 2.2
PK	%�\�c�(xx#html/_sources/c-api/typeobj.rst.txtnu�[���.. highlightlang:: c

.. _type-structs:

Type Objects
============

Perhaps one of the most important structures of the Python object system is the
structure that defines a new type: the :c:type:`PyTypeObject` structure.  Type
objects can be handled using any of the :c:func:`PyObject_\*` or
:c:func:`PyType_\*` functions, but do not offer much that's interesting to most
Python applications. These objects are fundamental to how objects behave, so
they are very important to the interpreter itself and to any extension module
that implements new types.

Type objects are fairly large compared to most of the standard types. The reason
for the size is that each type object stores a large number of values, mostly C
function pointers, each of which implements a small part of the type's
functionality.  The fields of the type object are examined in detail in this
section.  The fields will be described in the order in which they occur in the
structure.

Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor,
freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc,
cmpfunc, reprfunc, hashfunc

The structure definition for :c:type:`PyTypeObject` can be found in
:file:`Include/object.h`.  For convenience of reference, this repeats the
definition found there:

.. literalinclude:: ../includes/typestruct.h


The type object structure extends the :c:type:`PyVarObject` structure. The
:attr:`ob_size` field is used for dynamic types (created by  :func:`type_new`,
usually called from a class statement). Note that :c:data:`PyType_Type` (the
metatype) initializes :c:member:`~PyTypeObject.tp_itemsize`, which means that its instances (i.e.
type objects) *must* have the :attr:`ob_size` field.


.. c:member:: PyObject* PyObject._ob_next
             PyObject* PyObject._ob_prev

   These fields are only present when the macro ``Py_TRACE_REFS`` is defined.
   Their initialization to *NULL* is taken care of by the ``PyObject_HEAD_INIT``
   macro.  For statically allocated objects, these fields always remain *NULL*.
   For dynamically allocated objects, these two fields are used to link the object
   into a doubly-linked list of *all* live objects on the heap.  This could be used
   for various debugging purposes; currently the only use is to print the objects
   that are still alive at the end of a run when the environment variable
   :envvar:`PYTHONDUMPREFS` is set.

   These fields are not inherited by subtypes.


.. c:member:: Py_ssize_t PyObject.ob_refcnt

   This is the type object's reference count, initialized to ``1`` by the
   ``PyObject_HEAD_INIT`` macro.  Note that for statically allocated type objects,
   the type's instances (objects whose :attr:`ob_type` points back to the type) do
   *not* count as references.  But for dynamically allocated type objects, the
   instances *do* count as references.

   This field is not inherited by subtypes.

   .. versionchanged:: 2.5
      This field used to be an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:member:: PyTypeObject* PyObject.ob_type

   This is the type's type, in other words its metatype.  It is initialized by the
   argument to the ``PyObject_HEAD_INIT`` macro, and its value should normally be
   ``&PyType_Type``.  However, for dynamically loadable extension modules that must
   be usable on Windows (at least), the compiler complains that this is not a valid
   initializer.  Therefore, the convention is to pass *NULL* to the
   ``PyObject_HEAD_INIT`` macro and to initialize this field explicitly at the
   start of the module's initialization function, before doing anything else.  This
   is typically done like this::

      Foo_Type.ob_type = &PyType_Type;

   This should be done before any instances of the type are created.
   :c:func:`PyType_Ready` checks if :attr:`ob_type` is *NULL*, and if so,
   initializes it: in Python 2.2, it is set to ``&PyType_Type``; in Python 2.2.1
   and later it is initialized to the :attr:`ob_type` field of the base class.
   :c:func:`PyType_Ready` will not change this field if it is non-zero.

   In Python 2.2, this field is not inherited by subtypes.  In 2.2.1, and in 2.3
   and beyond, it is inherited by subtypes.


.. c:member:: Py_ssize_t PyVarObject.ob_size

   For statically allocated type objects, this should be initialized to zero.  For
   dynamically allocated type objects, this field has a special internal meaning.

   This field is not inherited by subtypes.


.. c:member:: char* PyTypeObject.tp_name

   Pointer to a NUL-terminated string containing the name of the type. For types
   that are accessible as module globals, the string should be the full module
   name, followed by a dot, followed by the type name; for built-in types, it
   should be just the type name.  If the module is a submodule of a package, the
   full package name is part of the full module name.  For example, a type named
   :class:`T` defined in module :mod:`M` in subpackage :mod:`Q` in package :mod:`P`
   should have the :c:member:`~PyTypeObject.tp_name` initializer ``"P.Q.M.T"``.

   For dynamically allocated type objects, this should just be the type name, and
   the module name explicitly stored in the type dict as the value for key
   ``'__module__'``.

   For statically allocated type objects, the tp_name field should contain a dot.
   Everything before the last dot is made accessible as the :attr:`__module__`
   attribute, and everything after the last dot is made accessible as the
   :attr:`~definition.__name__` attribute.

   If no dot is present, the entire :c:member:`~PyTypeObject.tp_name` field is made accessible as the
   :attr:`~definition.__name__` attribute, and the :attr:`__module__` attribute is undefined
   (unless explicitly set in the dictionary, as explained above).  This means your
   type will be impossible to pickle.  Additionally, it will not be listed in
   module documentations created with pydoc.

   This field is not inherited by subtypes.


.. c:member:: Py_ssize_t PyTypeObject.tp_basicsize
             Py_ssize_t PyTypeObject.tp_itemsize

   These fields allow calculating the size in bytes of instances of the type.

   There are two kinds of types: types with fixed-length instances have a zero
   :c:member:`~PyTypeObject.tp_itemsize` field, types with variable-length instances have a non-zero
   :c:member:`~PyTypeObject.tp_itemsize` field.  For a type with fixed-length instances, all
   instances have the same size, given in :c:member:`~PyTypeObject.tp_basicsize`.

   For a type with variable-length instances, the instances must have an
   :attr:`ob_size` field, and the instance size is :c:member:`~PyTypeObject.tp_basicsize` plus N
   times :c:member:`~PyTypeObject.tp_itemsize`, where N is the "length" of the object.  The value of
   N is typically stored in the instance's :attr:`ob_size` field.  There are
   exceptions:  for example, long ints use a negative :attr:`ob_size` to indicate a
   negative number, and N is ``abs(ob_size)`` there.  Also, the presence of an
   :attr:`ob_size` field in the instance layout doesn't mean that the instance
   structure is variable-length (for example, the structure for the list type has
   fixed-length instances, yet those instances have a meaningful :attr:`ob_size`
   field).

   The basic size includes the fields in the instance declared by the macro
   :c:macro:`PyObject_HEAD` or :c:macro:`PyObject_VAR_HEAD` (whichever is used to
   declare the instance struct) and this in turn includes the :attr:`_ob_prev` and
   :attr:`_ob_next` fields if they are present.  This means that the only correct
   way to get an initializer for the :c:member:`~PyTypeObject.tp_basicsize` is to use the
   ``sizeof`` operator on the struct used to declare the instance layout.
   The basic size does not include the GC header size (this is new in Python 2.2;
   in 2.1 and 2.0, the GC header size was included in :c:member:`~PyTypeObject.tp_basicsize`).

   These fields are inherited separately by subtypes.  If the base type has a
   non-zero :c:member:`~PyTypeObject.tp_itemsize`, it is generally not safe to set
   :c:member:`~PyTypeObject.tp_itemsize` to a different non-zero value in a subtype (though this
   depends on the implementation of the base type).

   A note about alignment: if the variable items require a particular alignment,
   this should be taken care of by the value of :c:member:`~PyTypeObject.tp_basicsize`.  Example:
   suppose a type implements an array of ``double``. :c:member:`~PyTypeObject.tp_itemsize` is
   ``sizeof(double)``. It is the programmer's responsibility that
   :c:member:`~PyTypeObject.tp_basicsize` is a multiple of ``sizeof(double)`` (assuming this is the
   alignment requirement for ``double``).


.. c:member:: destructor PyTypeObject.tp_dealloc

   A pointer to the instance destructor function.  This function must be defined
   unless the type guarantees that its instances will never be deallocated (as is
   the case for the singletons ``None`` and ``Ellipsis``).

   The destructor function is called by the :c:func:`Py_DECREF` and
   :c:func:`Py_XDECREF` macros when the new reference count is zero.  At this point,
   the instance is still in existence, but there are no references to it.  The
   destructor function should free all references which the instance owns, free all
   memory buffers owned by the instance (using the freeing function corresponding
   to the allocation function used to allocate the buffer), and finally (as its
   last action) call the type's :c:member:`~PyTypeObject.tp_free` function.  If the type is not
   subtypable (doesn't have the :const:`Py_TPFLAGS_BASETYPE` flag bit set), it is
   permissible to call the object deallocator directly instead of via
   :c:member:`~PyTypeObject.tp_free`.  The object deallocator should be the one used to allocate the
   instance; this is normally :c:func:`PyObject_Del` if the instance was allocated
   using :c:func:`PyObject_New` or :c:func:`PyObject_VarNew`, or
   :c:func:`PyObject_GC_Del` if the instance was allocated using
   :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar`.

   This field is inherited by subtypes.


.. c:member:: printfunc PyTypeObject.tp_print

   An optional pointer to the instance print function.

   The print function is only called when the instance is printed to a *real* file;
   when it is printed to a pseudo-file (like a :class:`~StringIO.StringIO` instance), the
   instance's :c:member:`~PyTypeObject.tp_repr` or :c:member:`~PyTypeObject.tp_str` function is called to convert it to
   a string.  These are also called when the type's :c:member:`~PyTypeObject.tp_print` field is
   *NULL*.  A type should never implement :c:member:`~PyTypeObject.tp_print` in a way that produces
   different output than :c:member:`~PyTypeObject.tp_repr` or :c:member:`~PyTypeObject.tp_str` would.

   The print function is called with the same signature as :c:func:`PyObject_Print`:
   ``int tp_print(PyObject *self, FILE *file, int flags)``.  The *self* argument is
   the instance to be printed.  The *file* argument is the stdio file to which it
   is to be printed.  The *flags* argument is composed of flag bits. The only flag
   bit currently defined is :const:`Py_PRINT_RAW`. When the :const:`Py_PRINT_RAW`
   flag bit is set, the instance should be printed the same way as :c:member:`~PyTypeObject.tp_str`
   would format it; when the :const:`Py_PRINT_RAW` flag bit is clear, the instance
   should be printed the same was as :c:member:`~PyTypeObject.tp_repr` would format it. It should
   return ``-1`` and set an exception condition when an error occurred during the
   comparison.

   It is possible that the :c:member:`~PyTypeObject.tp_print` field will be deprecated. In any case,
   it is recommended not to define :c:member:`~PyTypeObject.tp_print`, but instead to rely on
   :c:member:`~PyTypeObject.tp_repr` and :c:member:`~PyTypeObject.tp_str` for printing.

   This field is inherited by subtypes.


.. c:member:: getattrfunc PyTypeObject.tp_getattr

   An optional pointer to the get-attribute-string function.

   This field is deprecated.  When it is defined, it should point to a function
   that acts the same as the :c:member:`~PyTypeObject.tp_getattro` function, but taking a C string
   instead of a Python string object to give the attribute name.  The signature is ::

      PyObject * tp_getattr(PyObject *o, char *attr_name);

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattro`: a subtype
   inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
   the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both *NULL*.


.. c:member:: setattrfunc PyTypeObject.tp_setattr

   An optional pointer to the function for setting and deleting attributes.

   This field is deprecated.  When it is defined, it should point to a function
   that acts the same as the :c:member:`~PyTypeObject.tp_setattro` function, but taking a C string
   instead of a Python string object to give the attribute name.  The signature is ::

      PyObject * tp_setattr(PyObject *o, char *attr_name, PyObject *v);

   The *v* argument is set to *NULL* to delete the attribute.
   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattro`: a subtype
   inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
   the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both *NULL*.


.. c:member:: cmpfunc PyTypeObject.tp_compare

   An optional pointer to the three-way comparison function.

   The signature is the same as for :c:func:`PyObject_Compare`. The function should
   return ``1`` if *self* greater than *other*, ``0`` if *self* is equal to
   *other*, and ``-1`` if *self* less than *other*.  It should return ``-1`` and
   set an exception condition when an error occurred during the comparison.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_richcompare` and
   :c:member:`~PyTypeObject.tp_hash`: a subtypes inherits all three of :c:member:`~PyTypeObject.tp_compare`,
   :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` when the subtype's
   :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.


.. c:member:: reprfunc PyTypeObject.tp_repr

   .. index:: builtin: repr

   An optional pointer to a function that implements the built-in function
   :func:`repr`.

   The signature is the same as for :c:func:`PyObject_Repr`; it must return a string
   or a Unicode object.  Ideally, this function should return a string that, when
   passed to :func:`eval`, given a suitable environment, returns an object with the
   same value.  If this is not feasible, it should return a string starting with
   ``'<'`` and ending with ``'>'`` from which both the type and the value of the
   object can be deduced.

   When this field is not set, a string of the form ``<%s object at %p>`` is
   returned, where ``%s`` is replaced by the type name, and ``%p`` by the object's
   memory address.

   This field is inherited by subtypes.

.. c:member:: PyNumberMethods* tp_as_number

   Pointer to an additional structure that contains fields relevant only to
   objects which implement the number protocol.  These fields are documented in
   :ref:`number-structs`.

   The :c:member:`~PyTypeObject.tp_as_number` field is not inherited, but the contained fields are
   inherited individually.


.. c:member:: PySequenceMethods* tp_as_sequence

   Pointer to an additional structure that contains fields relevant only to
   objects which implement the sequence protocol.  These fields are documented
   in :ref:`sequence-structs`.

   The :c:member:`~PyTypeObject.tp_as_sequence` field is not inherited, but the contained fields
   are inherited individually.


.. c:member:: PyMappingMethods* tp_as_mapping

   Pointer to an additional structure that contains fields relevant only to
   objects which implement the mapping protocol.  These fields are documented in
   :ref:`mapping-structs`.

   The :c:member:`~PyTypeObject.tp_as_mapping` field is not inherited, but the contained fields
   are inherited individually.


.. c:member:: hashfunc PyTypeObject.tp_hash

   .. index:: builtin: hash

   An optional pointer to a function that implements the built-in function
   :func:`hash`.

   The signature is the same as for :c:func:`PyObject_Hash`; it must return a C
   long.  The value ``-1`` should not be returned as a normal return value; when an
   error occurs during the computation of the hash value, the function should set
   an exception and return ``-1``.

   This field can be set explicitly to :c:func:`PyObject_HashNotImplemented` to
   block inheritance of the hash method from a parent type. This is interpreted
   as the equivalent of ``__hash__ = None`` at the Python level, causing
   ``isinstance(o, collections.Hashable)`` to correctly return ``False``. Note
   that the converse is also true - setting ``__hash__ = None`` on a class at
   the Python level will result in the ``tp_hash`` slot being set to
   :c:func:`PyObject_HashNotImplemented`.

   When this field is not set, two possibilities exist: if the :c:member:`~PyTypeObject.tp_compare`
   and :c:member:`~PyTypeObject.tp_richcompare` fields are both *NULL*, a default hash value based on
   the object's address is returned; otherwise, a :exc:`TypeError` is raised.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_richcompare` and
   :c:member:`~PyTypeObject.tp_compare`: a subtypes inherits all three of :c:member:`~PyTypeObject.tp_compare`,
   :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
   :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare` and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.


.. c:member:: ternaryfunc PyTypeObject.tp_call

   An optional pointer to a function that implements calling the object.  This
   should be *NULL* if the object is not callable.  The signature is the same as
   for :c:func:`PyObject_Call`.

   This field is inherited by subtypes.


.. c:member:: reprfunc PyTypeObject.tp_str

   An optional pointer to a function that implements the built-in operation
   :func:`str`.  (Note that :class:`str` is a type now, and :func:`str` calls the
   constructor for that type.  This constructor calls :c:func:`PyObject_Str` to do
   the actual work, and :c:func:`PyObject_Str` will call this handler.)

   The signature is the same as for :c:func:`PyObject_Str`; it must return a string
   or a Unicode object.  This function should return a "friendly" string
   representation of the object, as this is the representation that will be used by
   the print statement.

   When this field is not set, :c:func:`PyObject_Repr` is called to return a string
   representation.

   This field is inherited by subtypes.


.. c:member:: getattrofunc PyTypeObject.tp_getattro

   An optional pointer to the get-attribute function.

   The signature is the same as for :c:func:`PyObject_GetAttr`.  It is usually
   convenient to set this field to :c:func:`PyObject_GenericGetAttr`, which
   implements the normal way of looking for object attributes.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_getattr`: a subtype
   inherits both :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` from its base type when
   the subtype's :c:member:`~PyTypeObject.tp_getattr` and :c:member:`~PyTypeObject.tp_getattro` are both *NULL*.


.. c:member:: setattrofunc PyTypeObject.tp_setattro

   An optional pointer to the function for setting and deleting attributes.

   The signature is the same as for :c:func:`PyObject_SetAttr`, but setting
   *v* to *NULL* to delete an attribute must be supported.  It is usually
   convenient to set this field to :c:func:`PyObject_GenericSetAttr`, which
   implements the normal way of setting object attributes.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_setattr`: a subtype
   inherits both :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` from its base type when
   the subtype's :c:member:`~PyTypeObject.tp_setattr` and :c:member:`~PyTypeObject.tp_setattro` are both *NULL*.


.. c:member:: PyBufferProcs* PyTypeObject.tp_as_buffer

   Pointer to an additional structure that contains fields relevant only to objects
   which implement the buffer interface.  These fields are documented in
   :ref:`buffer-structs`.

   The :c:member:`~PyTypeObject.tp_as_buffer` field is not inherited, but the contained fields are
   inherited individually.


.. c:member:: long PyTypeObject.tp_flags

   This field is a bit mask of various flags.  Some flags indicate variant
   semantics for certain situations; others are used to indicate that certain
   fields in the type object (or in the extension structures referenced via
   :c:member:`~PyTypeObject.tp_as_number`, :c:member:`~PyTypeObject.tp_as_sequence`, :c:member:`~PyTypeObject.tp_as_mapping`, and
   :c:member:`~PyTypeObject.tp_as_buffer`) that were historically not always present are valid; if
   such a flag bit is clear, the type fields it guards must not be accessed and
   must be considered to have a zero or *NULL* value instead.

   Inheritance of this field is complicated.  Most flag bits are inherited
   individually, i.e. if the base type has a flag bit set, the subtype inherits
   this flag bit.  The flag bits that pertain to extension structures are strictly
   inherited if the extension structure is inherited, i.e. the base type's value of
   the flag bit is copied into the subtype together with a pointer to the extension
   structure.  The :const:`Py_TPFLAGS_HAVE_GC` flag bit is inherited together with
   the :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields, i.e. if the
   :const:`Py_TPFLAGS_HAVE_GC` flag bit is clear in the subtype and the
   :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` fields in the subtype exist (as
   indicated by the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit) and have *NULL*
   values.

   The following bit masks are currently defined; these can be ORed together using
   the ``|`` operator to form the value of the :c:member:`~PyTypeObject.tp_flags` field.  The macro
   :c:func:`PyType_HasFeature` takes a type and a flags value, *tp* and *f*, and
   checks whether ``tp->tp_flags & f`` is non-zero.


   .. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER

      If this bit is set, the :c:type:`PyBufferProcs` struct referenced by
      :c:member:`~PyTypeObject.tp_as_buffer` has the :attr:`bf_getcharbuffer` field.


   .. data:: Py_TPFLAGS_HAVE_SEQUENCE_IN

      If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
      :c:member:`~PyTypeObject.tp_as_sequence` has the :attr:`sq_contains` field.


   .. data:: Py_TPFLAGS_GC

      This bit is obsolete.  The bit it used to name is no longer in use.  The symbol
      is now defined as zero.


   .. data:: Py_TPFLAGS_HAVE_INPLACEOPS

      If this bit is set, the :c:type:`PySequenceMethods` struct referenced by
      :c:member:`~PyTypeObject.tp_as_sequence` and the :c:type:`PyNumberMethods` structure referenced by
      :c:member:`~PyTypeObject.tp_as_number` contain the fields for in-place operators. In particular,
      this means that the :c:type:`PyNumberMethods` structure has the fields
      :attr:`nb_inplace_add`, :attr:`nb_inplace_subtract`,
      :attr:`nb_inplace_multiply`, :attr:`nb_inplace_divide`,
      :attr:`nb_inplace_remainder`, :attr:`nb_inplace_power`,
      :attr:`nb_inplace_lshift`, :attr:`nb_inplace_rshift`, :attr:`nb_inplace_and`,
      :attr:`nb_inplace_xor`, and :attr:`nb_inplace_or`; and the
      :c:type:`PySequenceMethods` struct has the fields :attr:`sq_inplace_concat` and
      :attr:`sq_inplace_repeat`.


   .. data:: Py_TPFLAGS_CHECKTYPES

      If this bit is set, the binary and ternary operations in the
      :c:type:`PyNumberMethods` structure referenced by :c:member:`~PyTypeObject.tp_as_number` accept
      arguments of arbitrary object types, and do their own type conversions if
      needed.  If this bit is clear, those operations require that all arguments have
      the current type as their type, and the caller is supposed to perform a coercion
      operation first.  This applies to :attr:`nb_add`, :attr:`nb_subtract`,
      :attr:`nb_multiply`, :attr:`nb_divide`, :attr:`nb_remainder`, :attr:`nb_divmod`,
      :attr:`nb_power`, :attr:`nb_lshift`, :attr:`nb_rshift`, :attr:`nb_and`,
      :attr:`nb_xor`, and :attr:`nb_or`.


   .. data:: Py_TPFLAGS_HAVE_RICHCOMPARE

      If this bit is set, the type object has the :c:member:`~PyTypeObject.tp_richcompare` field, as
      well as the :c:member:`~PyTypeObject.tp_traverse` and the :c:member:`~PyTypeObject.tp_clear` fields.


   .. data:: Py_TPFLAGS_HAVE_WEAKREFS

      If this bit is set, the :c:member:`~PyTypeObject.tp_weaklistoffset` field is defined.  Instances
      of a type are weakly referenceable if the type's :c:member:`~PyTypeObject.tp_weaklistoffset` field
      has a value greater than zero.


   .. data:: Py_TPFLAGS_HAVE_ITER

      If this bit is set, the type object has the :c:member:`~PyTypeObject.tp_iter` and
      :c:member:`~PyTypeObject.tp_iternext` fields.


   .. data:: Py_TPFLAGS_HAVE_CLASS

      If this bit is set, the type object has several new fields defined starting in
      Python 2.2: :c:member:`~PyTypeObject.tp_methods`, :c:member:`~PyTypeObject.tp_members`, :c:member:`~PyTypeObject.tp_getset`,
      :c:member:`~PyTypeObject.tp_base`, :c:member:`~PyTypeObject.tp_dict`, :c:member:`~PyTypeObject.tp_descr_get`, :c:member:`~PyTypeObject.tp_descr_set`,
      :c:member:`~PyTypeObject.tp_dictoffset`, :c:member:`~PyTypeObject.tp_init`, :c:member:`~PyTypeObject.tp_alloc`, :c:member:`~PyTypeObject.tp_new`,
      :c:member:`~PyTypeObject.tp_free`, :c:member:`~PyTypeObject.tp_is_gc`, :c:member:`~PyTypeObject.tp_bases`, :c:member:`~PyTypeObject.tp_mro`,
      :c:member:`~PyTypeObject.tp_cache`, :c:member:`~PyTypeObject.tp_subclasses`, and :c:member:`~PyTypeObject.tp_weaklist`.


   .. data:: Py_TPFLAGS_HEAPTYPE

      This bit is set when the type object itself is allocated on the heap.  In this
      case, the :attr:`ob_type` field of its instances is considered a reference to
      the type, and the type object is INCREF'ed when a new instance is created, and
      DECREF'ed when an instance is destroyed (this does not apply to instances of
      subtypes; only the type referenced by the instance's ob_type gets INCREF'ed or
      DECREF'ed).


   .. data:: Py_TPFLAGS_BASETYPE

      This bit is set when the type can be used as the base type of another type.  If
      this bit is clear, the type cannot be subtyped (similar to a "final" class in
      Java).


   .. data:: Py_TPFLAGS_READY

      This bit is set when the type object has been fully initialized by
      :c:func:`PyType_Ready`.


   .. data:: Py_TPFLAGS_READYING

      This bit is set while :c:func:`PyType_Ready` is in the process of initializing
      the type object.


   .. data:: Py_TPFLAGS_HAVE_GC

      This bit is set when the object supports garbage collection.  If this bit
      is set, instances must be created using :c:func:`PyObject_GC_New` and
      destroyed using :c:func:`PyObject_GC_Del`.  More information in section
      :ref:`supporting-cycle-detection`.  This bit also implies that the
      GC-related fields :c:member:`~PyTypeObject.tp_traverse` and :c:member:`~PyTypeObject.tp_clear` are present in
      the type object; but those fields also exist when
      :const:`Py_TPFLAGS_HAVE_GC` is clear but
      :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` is set.


   .. data:: Py_TPFLAGS_DEFAULT

      This is a bitmask of all the bits that pertain to the existence of certain
      fields in the type object and its extension structures. Currently, it includes
      the following bits: :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`,
      :const:`Py_TPFLAGS_HAVE_SEQUENCE_IN`, :const:`Py_TPFLAGS_HAVE_INPLACEOPS`,
      :const:`Py_TPFLAGS_HAVE_RICHCOMPARE`, :const:`Py_TPFLAGS_HAVE_WEAKREFS`,
      :const:`Py_TPFLAGS_HAVE_ITER`, and :const:`Py_TPFLAGS_HAVE_CLASS`.


.. c:member:: char* PyTypeObject.tp_doc

   An optional pointer to a NUL-terminated C string giving the docstring for this
   type object.  This is exposed as the :attr:`__doc__` attribute on the type and
   instances of the type.

   This field is *not* inherited by subtypes.

The following three fields only exist if the
:const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag bit is set.


.. c:member:: traverseproc PyTypeObject.tp_traverse

   An optional pointer to a traversal function for the garbage collector.  This is
   only used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.  More information
   about Python's garbage collection scheme can be found in section
   :ref:`supporting-cycle-detection`.

   The :c:member:`~PyTypeObject.tp_traverse` pointer is used by the garbage collector to detect
   reference cycles. A typical implementation of a :c:member:`~PyTypeObject.tp_traverse` function
   simply calls :c:func:`Py_VISIT` on each of the instance's members that are Python
   objects.  For example, this is function :c:func:`local_traverse` from the
   :mod:`thread` extension module::

      static int
      local_traverse(localobject *self, visitproc visit, void *arg)
      {
          Py_VISIT(self->args);
          Py_VISIT(self->kw);
          Py_VISIT(self->dict);
          return 0;
      }

   Note that :c:func:`Py_VISIT` is called only on those members that can participate
   in reference cycles.  Although there is also a ``self->key`` member, it can only
   be *NULL* or a Python string and therefore cannot be part of a reference cycle.

   On the other hand, even if you know a member can never be part of a cycle, as a
   debugging aid you may want to visit it anyway just so the :mod:`gc` module's
   :func:`~gc.get_referents` function will include it.

   Note that :c:func:`Py_VISIT` requires the *visit* and *arg* parameters to
   :c:func:`local_traverse` to have these specific names; don't name them just
   anything.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_clear` and the
   :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
   :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
   the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
   bit set.


.. c:member:: inquiry PyTypeObject.tp_clear

   An optional pointer to a clear function for the garbage collector. This is only
   used if the :const:`Py_TPFLAGS_HAVE_GC` flag bit is set.

   The :c:member:`~PyTypeObject.tp_clear` member function is used to break reference cycles in cyclic
   garbage detected by the garbage collector.  Taken together, all :c:member:`~PyTypeObject.tp_clear`
   functions in the system must combine to break all reference cycles.  This is
   subtle, and if in any doubt supply a :c:member:`~PyTypeObject.tp_clear` function.  For example,
   the tuple type does not implement a :c:member:`~PyTypeObject.tp_clear` function, because it's
   possible to prove that no reference cycle can be composed entirely of tuples.
   Therefore the :c:member:`~PyTypeObject.tp_clear` functions of other types must be sufficient to
   break any cycle containing a tuple.  This isn't immediately obvious, and there's
   rarely a good reason to avoid implementing :c:member:`~PyTypeObject.tp_clear`.

   Implementations of :c:member:`~PyTypeObject.tp_clear` should drop the instance's references to
   those of its members that may be Python objects, and set its pointers to those
   members to *NULL*, as in the following example::

      static int
      local_clear(localobject *self)
      {
          Py_CLEAR(self->key);
          Py_CLEAR(self->args);
          Py_CLEAR(self->kw);
          Py_CLEAR(self->dict);
          return 0;
      }

   The :c:func:`Py_CLEAR` macro should be used, because clearing references is
   delicate:  the reference to the contained object must not be decremented until
   after the pointer to the contained object is set to *NULL*.  This is because
   decrementing the reference count may cause the contained object to become trash,
   triggering a chain of reclamation activity that may include invoking arbitrary
   Python code (due to finalizers, or weakref callbacks, associated with the
   contained object). If it's possible for such code to reference *self* again,
   it's important that the pointer to the contained object be *NULL* at that time,
   so that *self* knows the contained object can no longer be used.  The
   :c:func:`Py_CLEAR` macro performs the operations in a safe order.

   Because the goal of :c:member:`~PyTypeObject.tp_clear` functions is to break reference cycles,
   it's not necessary to clear contained objects like Python strings or Python
   integers, which can't participate in reference cycles. On the other hand, it may
   be convenient to clear all contained Python objects, and write the type's
   :c:member:`~PyTypeObject.tp_dealloc` function to invoke :c:member:`~PyTypeObject.tp_clear`.

   More information about Python's garbage collection scheme can be found in
   section :ref:`supporting-cycle-detection`.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_traverse` and the
   :const:`Py_TPFLAGS_HAVE_GC` flag bit: the flag bit, :c:member:`~PyTypeObject.tp_traverse`, and
   :c:member:`~PyTypeObject.tp_clear` are all inherited from the base type if they are all zero in
   the subtype *and* the subtype has the :const:`Py_TPFLAGS_HAVE_RICHCOMPARE` flag
   bit set.


.. c:member:: richcmpfunc PyTypeObject.tp_richcompare

   An optional pointer to the rich comparison function, whose signature is
   ``PyObject *tp_richcompare(PyObject *a, PyObject *b, int op)``.

   The function should return the result of the comparison (usually ``Py_True``
   or ``Py_False``).  If the comparison is undefined, it must return
   ``Py_NotImplemented``, if another error occurred it must return ``NULL`` and
   set an exception condition.

   .. note::

      If you want to implement a type for which only a limited set of
      comparisons makes sense (e.g. ``==`` and ``!=``, but not ``<`` and
      friends), directly raise :exc:`TypeError` in the rich comparison function.

   This field is inherited by subtypes together with :c:member:`~PyTypeObject.tp_compare` and
   :c:member:`~PyTypeObject.tp_hash`: a subtype inherits all three of :c:member:`~PyTypeObject.tp_compare`,
   :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash`, when the subtype's
   :c:member:`~PyTypeObject.tp_compare`, :c:member:`~PyTypeObject.tp_richcompare`, and :c:member:`~PyTypeObject.tp_hash` are all *NULL*.

   The following constants are defined to be used as the third argument for
   :c:member:`~PyTypeObject.tp_richcompare` and for :c:func:`PyObject_RichCompare`:

   +----------------+------------+
   | Constant       | Comparison |
   +================+============+
   | :const:`Py_LT` | ``<``      |
   +----------------+------------+
   | :const:`Py_LE` | ``<=``     |
   +----------------+------------+
   | :const:`Py_EQ` | ``==``     |
   +----------------+------------+
   | :const:`Py_NE` | ``!=``     |
   +----------------+------------+
   | :const:`Py_GT` | ``>``      |
   +----------------+------------+
   | :const:`Py_GE` | ``>=``     |
   +----------------+------------+


The next field only exists if the :const:`Py_TPFLAGS_HAVE_WEAKREFS` flag bit is
set.

.. c:member:: long PyTypeObject.tp_weaklistoffset

   If the instances of this type are weakly referenceable, this field is greater
   than zero and contains the offset in the instance structure of the weak
   reference list head (ignoring the GC header, if present); this offset is used by
   :c:func:`PyObject_ClearWeakRefs` and the :c:func:`PyWeakref_\*` functions.  The
   instance structure needs to include a field of type :c:type:`PyObject\*` which is
   initialized to *NULL*.

   Do not confuse this field with :c:member:`~PyTypeObject.tp_weaklist`; that is the list head for
   weak references to the type object itself.

   This field is inherited by subtypes, but see the rules listed below. A subtype
   may override this offset; this means that the subtype uses a different weak
   reference list head than the base type.  Since the list head is always found via
   :c:member:`~PyTypeObject.tp_weaklistoffset`, this should not be a problem.

   When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
   and none of its base types are weakly referenceable, the type is made weakly
   referenceable by adding a weak reference list head slot to the instance layout
   and setting the :c:member:`~PyTypeObject.tp_weaklistoffset` of that slot's offset.

   When a type's :attr:`__slots__` declaration contains a slot named
   :attr:`__weakref__`, that slot becomes the weak reference list head for
   instances of the type, and the slot's offset is stored in the type's
   :c:member:`~PyTypeObject.tp_weaklistoffset`.

   When a type's :attr:`__slots__` declaration does not contain a slot named
   :attr:`__weakref__`, the type inherits its :c:member:`~PyTypeObject.tp_weaklistoffset` from its
   base type.

The next two fields only exist if the :const:`Py_TPFLAGS_HAVE_ITER` flag bit is
set.


.. c:member:: getiterfunc PyTypeObject.tp_iter

   An optional pointer to a function that returns an iterator for the object.  Its
   presence normally signals that the instances of this type are iterable (although
   sequences may be iterable without this function, and classic instances always
   have this function, even if they don't define an :meth:`__iter__` method).

   This function has the same signature as :c:func:`PyObject_GetIter`.

   This field is inherited by subtypes.


.. c:member:: iternextfunc PyTypeObject.tp_iternext

   An optional pointer to a function that returns the next item in an iterator.
   When the iterator is exhausted, it must return *NULL*; a :exc:`StopIteration`
   exception may or may not be set.  When another error occurs, it must return
   *NULL* too.  Its presence normally signals that the instances of this type
   are iterators (although classic instances always have this function, even if
   they don't define a :meth:`~iterator.next` method).

   Iterator types should also define the :c:member:`~PyTypeObject.tp_iter` function, and that
   function should return the iterator instance itself (not a new iterator
   instance).

   This function has the same signature as :c:func:`PyIter_Next`.

   This field is inherited by subtypes.

The next fields, up to and including :c:member:`~PyTypeObject.tp_weaklist`, only exist if the
:const:`Py_TPFLAGS_HAVE_CLASS` flag bit is set.


.. c:member:: struct PyMethodDef* PyTypeObject.tp_methods

   An optional pointer to a static *NULL*-terminated array of :c:type:`PyMethodDef`
   structures, declaring regular methods of this type.

   For each entry in the array, an entry is added to the type's dictionary (see
   :c:member:`~PyTypeObject.tp_dict` below) containing a method descriptor.

   This field is not inherited by subtypes (methods are inherited through a
   different mechanism).


.. c:member:: struct PyMemberDef* PyTypeObject.tp_members

   An optional pointer to a static *NULL*-terminated array of :c:type:`PyMemberDef`
   structures, declaring regular data members (fields or slots) of instances of
   this type.

   For each entry in the array, an entry is added to the type's dictionary (see
   :c:member:`~PyTypeObject.tp_dict` below) containing a member descriptor.

   This field is not inherited by subtypes (members are inherited through a
   different mechanism).


.. c:member:: struct PyGetSetDef* PyTypeObject.tp_getset

   An optional pointer to a static *NULL*-terminated array of :c:type:`PyGetSetDef`
   structures, declaring computed attributes of instances of this type.

   For each entry in the array, an entry is added to the type's dictionary (see
   :c:member:`~PyTypeObject.tp_dict` below) containing a getset descriptor.

   This field is not inherited by subtypes (computed attributes are inherited
   through a different mechanism).


.. c:member:: PyTypeObject* PyTypeObject.tp_base

   An optional pointer to a base type from which type properties are inherited.  At
   this level, only single inheritance is supported; multiple inheritance require
   dynamically creating a type object by calling the metatype.

   This field is not inherited by subtypes (obviously), but it defaults to
   ``&PyBaseObject_Type`` (which to Python programmers is known as the type
   :class:`object`).


.. c:member:: PyObject* PyTypeObject.tp_dict

   The type's dictionary is stored here by :c:func:`PyType_Ready`.

   This field should normally be initialized to *NULL* before PyType_Ready is
   called; it may also be initialized to a dictionary containing initial attributes
   for the type.  Once :c:func:`PyType_Ready` has initialized the type, extra
   attributes for the type may be added to this dictionary only if they don't
   correspond to overloaded operations (like :meth:`__add__`).

   This field is not inherited by subtypes (though the attributes defined in here
   are inherited through a different mechanism).


.. c:member:: descrgetfunc PyTypeObject.tp_descr_get

   An optional pointer to a "descriptor get" function.

   The function signature is ::

      PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);

   .. XXX explain.

   This field is inherited by subtypes.


.. c:member:: descrsetfunc PyTypeObject.tp_descr_set

   An optional pointer to a function for setting and deleting
   a descriptor's value.

   The function signature is ::

      int tp_descr_set(PyObject *self, PyObject *obj, PyObject *value);

   The *value* argument is set to *NULL* to delete the value.
   This field is inherited by subtypes.

   .. XXX explain.


.. c:member:: long PyTypeObject.tp_dictoffset

   If the instances of this type have a dictionary containing instance variables,
   this field is non-zero and contains the offset in the instances of the type of
   the instance variable dictionary; this offset is used by
   :c:func:`PyObject_GenericGetAttr`.

   Do not confuse this field with :c:member:`~PyTypeObject.tp_dict`; that is the dictionary for
   attributes of the type object itself.

   If the value of this field is greater than zero, it specifies the offset from
   the start of the instance structure.  If the value is less than zero, it
   specifies the offset from the *end* of the instance structure.  A negative
   offset is more expensive to use, and should only be used when the instance
   structure contains a variable-length part.  This is used for example to add an
   instance variable dictionary to subtypes of :class:`str` or :class:`tuple`. Note
   that the :c:member:`~PyTypeObject.tp_basicsize` field should account for the dictionary added to
   the end in that case, even though the dictionary is not included in the basic
   object layout.  On a system with a pointer size of 4 bytes,
   :c:member:`~PyTypeObject.tp_dictoffset` should be set to ``-4`` to indicate that the dictionary is
   at the very end of the structure.

   The real dictionary offset in an instance can be computed from a negative
   :c:member:`~PyTypeObject.tp_dictoffset` as follows::

      dictoffset = tp_basicsize + abs(ob_size)*tp_itemsize + tp_dictoffset
      if dictoffset is not aligned on sizeof(void*):
          round up to sizeof(void*)

   where :c:member:`~PyTypeObject.tp_basicsize`, :c:member:`~PyTypeObject.tp_itemsize` and :c:member:`~PyTypeObject.tp_dictoffset` are
   taken from the type object, and :attr:`ob_size` is taken from the instance.  The
   absolute value is taken because long ints use the sign of :attr:`ob_size` to
   store the sign of the number.  (There's never a need to do this calculation
   yourself; it is done for you by :c:func:`_PyObject_GetDictPtr`.)

   This field is inherited by subtypes, but see the rules listed below. A subtype
   may override this offset; this means that the subtype instances store the
   dictionary at a difference offset than the base type.  Since the dictionary is
   always found via :c:member:`~PyTypeObject.tp_dictoffset`, this should not be a problem.

   When a type defined by a class statement has no :attr:`~object.__slots__` declaration,
   and none of its base types has an instance variable dictionary, a dictionary
   slot is added to the instance layout and the :c:member:`~PyTypeObject.tp_dictoffset` is set to
   that slot's offset.

   When a type defined by a class statement has a :attr:`__slots__` declaration,
   the type inherits its :c:member:`~PyTypeObject.tp_dictoffset` from its base type.

   (Adding a slot named :attr:`~object.__dict__` to the :attr:`__slots__` declaration does
   not have the expected effect, it just causes confusion.  Maybe this should be
   added as a feature just like :attr:`__weakref__` though.)


.. c:member:: initproc PyTypeObject.tp_init

   An optional pointer to an instance initialization function.

   This function corresponds to the :meth:`__init__` method of classes.  Like
   :meth:`__init__`, it is possible to create an instance without calling
   :meth:`__init__`, and it is possible to reinitialize an instance by calling its
   :meth:`__init__` method again.

   The function signature is ::

      int tp_init(PyObject *self, PyObject *args, PyObject *kwds)

   The self argument is the instance to be initialized; the *args* and *kwds*
   arguments represent positional and keyword arguments of the call to
   :meth:`__init__`.

   The :c:member:`~PyTypeObject.tp_init` function, if not *NULL*, is called when an instance is
   created normally by calling its type, after the type's :c:member:`~PyTypeObject.tp_new` function
   has returned an instance of the type.  If the :c:member:`~PyTypeObject.tp_new` function returns an
   instance of some other type that is not a subtype of the original type, no
   :c:member:`~PyTypeObject.tp_init` function is called; if :c:member:`~PyTypeObject.tp_new` returns an instance of a
   subtype of the original type, the subtype's :c:member:`~PyTypeObject.tp_init` is called.  (VERSION
   NOTE: described here is what is implemented in Python 2.2.1 and later.  In
   Python 2.2, the :c:member:`~PyTypeObject.tp_init` of the type of the object returned by
   :c:member:`~PyTypeObject.tp_new` was always called, if not *NULL*.)

   This field is inherited by subtypes.


.. c:member:: allocfunc PyTypeObject.tp_alloc

   An optional pointer to an instance allocation function.

   The function signature is ::

      PyObject *tp_alloc(PyTypeObject *self, Py_ssize_t nitems)

   The purpose of this function is to separate memory allocation from memory
   initialization.  It should return a pointer to a block of memory of adequate
   length for the instance, suitably aligned, and initialized to zeros, but with
   :attr:`ob_refcnt` set to ``1`` and :attr:`ob_type` set to the type argument.  If
   the type's :c:member:`~PyTypeObject.tp_itemsize` is non-zero, the object's :attr:`ob_size` field
   should be initialized to *nitems* and the length of the allocated memory block
   should be ``tp_basicsize + nitems*tp_itemsize``, rounded up to a multiple of
   ``sizeof(void*)``; otherwise, *nitems* is not used and the length of the block
   should be :c:member:`~PyTypeObject.tp_basicsize`.

   Do not use this function to do any other instance initialization, not even to
   allocate additional memory; that should be done by :c:member:`~PyTypeObject.tp_new`.

   This field is inherited by static subtypes, but not by dynamic subtypes
   (subtypes created by a class statement); in the latter, this field is always set
   to :c:func:`PyType_GenericAlloc`, to force a standard heap allocation strategy.
   That is also the recommended value for statically defined types.


.. c:member:: newfunc PyTypeObject.tp_new

   An optional pointer to an instance creation function.

   If this function is *NULL* for a particular type, that type cannot be called to
   create new instances; presumably there is some other way to create instances,
   like a factory function.

   The function signature is ::

      PyObject *tp_new(PyTypeObject *subtype, PyObject *args, PyObject *kwds)

   The subtype argument is the type of the object being created; the *args* and
   *kwds* arguments represent positional and keyword arguments of the call to the
   type.  Note that subtype doesn't have to equal the type whose :c:member:`~PyTypeObject.tp_new`
   function is called; it may be a subtype of that type (but not an unrelated
   type).

   The :c:member:`~PyTypeObject.tp_new` function should call ``subtype->tp_alloc(subtype, nitems)``
   to allocate space for the object, and then do only as much further
   initialization as is absolutely necessary.  Initialization that can safely be
   ignored or repeated should be placed in the :c:member:`~PyTypeObject.tp_init` handler.  A good
   rule of thumb is that for immutable types, all initialization should take place
   in :c:member:`~PyTypeObject.tp_new`, while for mutable types, most initialization should be
   deferred to :c:member:`~PyTypeObject.tp_init`.

   This field is inherited by subtypes, except it is not inherited by static types
   whose :c:member:`~PyTypeObject.tp_base` is *NULL* or ``&PyBaseObject_Type``.  The latter exception
   is a precaution so that old extension types don't become callable simply by
   being linked with Python 2.2.


.. c:member:: destructor PyTypeObject.tp_free

   An optional pointer to an instance deallocation function.

   The signature of this function has changed slightly: in Python 2.2 and 2.2.1,
   its signature is :c:type:`destructor`::

      void tp_free(PyObject *)

   In Python 2.3 and beyond, its signature is :c:type:`freefunc`::

      void tp_free(void *)

   The only initializer that is compatible with both versions is ``_PyObject_Del``,
   whose definition has suitably adapted in Python 2.3.

   This field is inherited by static subtypes, but not by dynamic subtypes
   (subtypes created by a class statement); in the latter, this field is set to a
   deallocator suitable to match :c:func:`PyType_GenericAlloc` and the value of the
   :const:`Py_TPFLAGS_HAVE_GC` flag bit.


.. c:member:: inquiry PyTypeObject.tp_is_gc

   An optional pointer to a function called by the garbage collector.

   The garbage collector needs to know whether a particular object is collectible
   or not.  Normally, it is sufficient to look at the object's type's
   :c:member:`~PyTypeObject.tp_flags` field, and check the :const:`Py_TPFLAGS_HAVE_GC` flag bit.  But
   some types have a mixture of statically and dynamically allocated instances, and
   the statically allocated instances are not collectible.  Such types should
   define this function; it should return ``1`` for a collectible instance, and
   ``0`` for a non-collectible instance. The signature is ::

      int tp_is_gc(PyObject *self)

   (The only example of this are types themselves.  The metatype,
   :c:data:`PyType_Type`, defines this function to distinguish between statically
   and dynamically allocated types.)

   This field is inherited by subtypes.  (VERSION NOTE: in Python 2.2, it was not
   inherited.  It is inherited in 2.2.1 and later versions.)


.. c:member:: PyObject* PyTypeObject.tp_bases

   Tuple of base types.

   This is set for types created by a class statement.  It should be *NULL* for
   statically defined types.

   This field is not inherited.


.. c:member:: PyObject* PyTypeObject.tp_mro

   Tuple containing the expanded set of base types, starting with the type itself
   and ending with :class:`object`, in Method Resolution Order.

   This field is not inherited; it is calculated fresh by :c:func:`PyType_Ready`.


.. c:member:: PyObject* PyTypeObject.tp_cache

   Unused.  Not inherited.  Internal use only.


.. c:member:: PyObject* PyTypeObject.tp_subclasses

   List of weak references to subclasses.  Not inherited.  Internal use only.


.. c:member:: PyObject* PyTypeObject.tp_weaklist

   Weak reference list head, for weak references to this type object.  Not
   inherited.  Internal use only.

The remaining fields are only defined if the feature test macro
:const:`COUNT_ALLOCS` is defined, and are for internal use only. They are
documented here for completeness.  None of these fields are inherited by
subtypes. See the :envvar:`PYTHONSHOWALLOCCOUNT` environment variable.


.. c:member:: Py_ssize_t PyTypeObject.tp_allocs

   Number of allocations.


.. c:member:: Py_ssize_t PyTypeObject.tp_frees

   Number of frees.


.. c:member:: Py_ssize_t PyTypeObject.tp_maxalloc

   Maximum simultaneously allocated objects.


.. c:member:: PyTypeObject* PyTypeObject.tp_next

   Pointer to the next type object with a non-zero :c:member:`~PyTypeObject.tp_allocs` field.

Also, note that, in a garbage collected Python, tp_dealloc may be called from
any Python thread, not just the thread which created the object (if the object
becomes part of a refcount cycle, that cycle might be collected by a garbage
collection on any thread).  This is not a problem for Python API calls, since
the thread on which tp_dealloc is called will own the Global Interpreter Lock
(GIL). However, if the object being destroyed in turn destroys objects from some
other C or C++ library, care should be taken to ensure that destroying those
objects on the thread which called tp_dealloc will not violate any assumptions
of the library.


.. _number-structs:

Number Object Structures
========================

.. sectionauthor:: Amaury Forgeot d'Arc


.. c:type:: PyNumberMethods

   This structure holds pointers to the functions which an object uses to
   implement the number protocol.  Almost every function below is used by the
   function of similar name documented in the :ref:`number` section.

   Here is the structure definition::

       typedef struct {
            binaryfunc nb_add;
            binaryfunc nb_subtract;
            binaryfunc nb_multiply;
            binaryfunc nb_divide;
            binaryfunc nb_remainder;
            binaryfunc nb_divmod;
            ternaryfunc nb_power;
            unaryfunc nb_negative;
            unaryfunc nb_positive;
            unaryfunc nb_absolute;
            inquiry nb_nonzero;       /* Used by PyObject_IsTrue */
            unaryfunc nb_invert;
            binaryfunc nb_lshift;
            binaryfunc nb_rshift;
            binaryfunc nb_and;
            binaryfunc nb_xor;
            binaryfunc nb_or;
            coercion nb_coerce;       /* Used by the coerce() function */
            unaryfunc nb_int;
            unaryfunc nb_long;
            unaryfunc nb_float;
            unaryfunc nb_oct;
            unaryfunc nb_hex;

            /* Added in release 2.0 */
            binaryfunc nb_inplace_add;
            binaryfunc nb_inplace_subtract;
            binaryfunc nb_inplace_multiply;
            binaryfunc nb_inplace_divide;
            binaryfunc nb_inplace_remainder;
            ternaryfunc nb_inplace_power;
            binaryfunc nb_inplace_lshift;
            binaryfunc nb_inplace_rshift;
            binaryfunc nb_inplace_and;
            binaryfunc nb_inplace_xor;
            binaryfunc nb_inplace_or;

            /* Added in release 2.2 */
            binaryfunc nb_floor_divide;
            binaryfunc nb_true_divide;
            binaryfunc nb_inplace_floor_divide;
            binaryfunc nb_inplace_true_divide;

            /* Added in release 2.5 */
            unaryfunc nb_index;
       } PyNumberMethods;


Binary and ternary functions may receive different kinds of arguments, depending
on the flag bit :const:`Py_TPFLAGS_CHECKTYPES`:

- If :const:`Py_TPFLAGS_CHECKTYPES` is not set, the function arguments are
  guaranteed to be of the object's type; the caller is responsible for calling
  the coercion method specified by the :attr:`nb_coerce` member to convert the
  arguments:

  .. c:member:: coercion PyNumberMethods.nb_coerce

     This function is used by :c:func:`PyNumber_CoerceEx` and has the same
     signature.  The first argument is always a pointer to an object of the
     defined type.  If the conversion to a common "larger" type is possible, the
     function replaces the pointers with new references to the converted objects
     and returns ``0``.  If the conversion is not possible, the function returns
     ``1``.  If an error condition is set, it will return ``-1``.

- If the :const:`Py_TPFLAGS_CHECKTYPES` flag is set, binary and ternary
  functions must check the type of all their operands, and implement the
  necessary conversions (at least one of the operands is an instance of the
  defined type).  This is the recommended way; with Python 3 coercion will
  disappear completely.

If the operation is not defined for the given operands, binary and ternary
functions must return ``Py_NotImplemented``, if another error occurred they must
return ``NULL`` and set an exception.


.. _mapping-structs:

Mapping Object Structures
=========================

.. sectionauthor:: Amaury Forgeot d'Arc


.. c:type:: PyMappingMethods

   This structure holds pointers to the functions which an object uses to
   implement the mapping protocol.  It has three members:

.. c:member:: lenfunc PyMappingMethods.mp_length

   This function is used by :c:func:`PyMapping_Length` and
   :c:func:`PyObject_Size`, and has the same signature.  This slot may be set to
   *NULL* if the object has no defined length.

.. c:member:: binaryfunc PyMappingMethods.mp_subscript

   This function is used by :c:func:`PyObject_GetItem` and has the same
   signature.  This slot must be filled for the :c:func:`PyMapping_Check`
   function to return ``1``, it can be *NULL* otherwise.

.. c:member:: objobjargproc PyMappingMethods.mp_ass_subscript

   This function is used by :c:func:`PyObject_SetItem` and
   :c:func:`PyObject_DelItem`.  It has the same signature as
   :c:func:`PyObject_SetItem`, but *v* can also be set to *NULL* to delete
   an item.  If this slot is *NULL*, the object does not support item
   assignment and deletion.


.. _sequence-structs:

Sequence Object Structures
==========================

.. sectionauthor:: Amaury Forgeot d'Arc


.. c:type:: PySequenceMethods

   This structure holds pointers to the functions which an object uses to
   implement the sequence protocol.

.. c:member:: lenfunc PySequenceMethods.sq_length

   This function is used by :c:func:`PySequence_Size` and :c:func:`PyObject_Size`,
   and has the same signature.

.. c:member:: binaryfunc PySequenceMethods.sq_concat

   This function is used by :c:func:`PySequence_Concat` and has the same
   signature.  It is also used by the ``+`` operator, after trying the numeric
   addition via the :c:member:`~PyTypeObject.tp_as_number.nb_add` slot.

.. c:member:: ssizeargfunc PySequenceMethods.sq_repeat

   This function is used by :c:func:`PySequence_Repeat` and has the same
   signature.  It is also used by the ``*`` operator, after trying numeric
   multiplication via the :c:member:`~PyTypeObject.tp_as_number.nb_multiply`
   slot.

.. c:member:: ssizeargfunc PySequenceMethods.sq_item

   This function is used by :c:func:`PySequence_GetItem` and has the same
   signature.  This slot must be filled for the :c:func:`PySequence_Check`
   function to return ``1``, it can be *NULL* otherwise.

   Negative indexes are handled as follows: if the :attr:`sq_length` slot is
   filled, it is called and the sequence length is used to compute a positive
   index which is passed to :attr:`sq_item`.  If :attr:`sq_length` is *NULL*,
   the index is passed as is to the function.

.. c:member:: ssizeobjargproc PySequenceMethods.sq_ass_item

   This function is used by :c:func:`PySequence_SetItem` and has the same
   signature.  This slot may be left to *NULL* if the object does not support
   item assignment and deletion.

.. c:member:: objobjproc PySequenceMethods.sq_contains

   This function may be used by :c:func:`PySequence_Contains` and has the same
   signature.  This slot may be left to *NULL*, in this case
   :c:func:`PySequence_Contains` simply traverses the sequence until it finds a
   match.

.. c:member:: binaryfunc PySequenceMethods.sq_inplace_concat

   This function is used by :c:func:`PySequence_InPlaceConcat` and has the same
   signature.  It should modify its first operand, and return it.

.. c:member:: ssizeargfunc PySequenceMethods.sq_inplace_repeat

   This function is used by :c:func:`PySequence_InPlaceRepeat` and has the same
   signature.  It should modify its first operand, and return it.

.. XXX need to explain precedence between mapping and sequence
.. XXX explains when to implement the sq_inplace_* slots


.. _buffer-structs:

Buffer Object Structures
========================

.. sectionauthor:: Greg J. Stein <greg@lyra.org>


The buffer interface exports a model where an object can expose its internal
data as a set of chunks of data, where each chunk is specified as a
pointer/length pair.  These chunks are called :dfn:`segments` and are presumed
to be non-contiguous in memory.

If an object does not export the buffer interface, then its :c:member:`~PyTypeObject.tp_as_buffer`
member in the :c:type:`PyTypeObject` structure should be *NULL*.  Otherwise, the
:c:member:`~PyTypeObject.tp_as_buffer` will point to a :c:type:`PyBufferProcs` structure.

.. note::

   It is very important that your :c:type:`PyTypeObject` structure uses
   :const:`Py_TPFLAGS_DEFAULT` for the value of the :c:member:`~PyTypeObject.tp_flags` member rather
   than ``0``.  This tells the Python runtime that your :c:type:`PyBufferProcs`
   structure contains the :attr:`bf_getcharbuffer` slot. Older versions of Python
   did not have this member, so a new Python interpreter using an old extension
   needs to be able to test for its presence before using it.


.. c:type:: PyBufferProcs

   Structure used to hold the function pointers which define an implementation of
   the buffer protocol.

   The first slot is :attr:`bf_getreadbuffer`, of type :c:type:`readbufferproc`.
   If this slot is *NULL*, then the object does not support reading from the
   internal data.  This is non-sensical, so implementors should fill this in, but
   callers should test that the slot contains a non-*NULL* value.

   The next slot is :attr:`bf_getwritebuffer` having type
   :c:type:`writebufferproc`.  This slot may be *NULL* if the object does not
   allow writing into its returned buffers.

   The third slot is :attr:`bf_getsegcount`, with type :c:type:`segcountproc`.
   This slot must not be *NULL* and is used to inform the caller how many segments
   the object contains.  Simple objects such as :c:type:`PyString_Type` and
   :c:type:`PyBuffer_Type` objects contain a single segment.

   .. index:: single: PyType_HasFeature()

   The last slot is :attr:`bf_getcharbuffer`, of type :c:type:`charbufferproc`.
   This slot will only be present if the :const:`Py_TPFLAGS_HAVE_GETCHARBUFFER`
   flag is present in the :c:member:`~PyTypeObject.tp_flags` field of the object's
   :c:type:`PyTypeObject`. Before using this slot, the caller should test whether it
   is present by using the :c:func:`PyType_HasFeature` function.  If the flag is
   present, :attr:`bf_getcharbuffer` may be *NULL*, indicating that the object's
   contents cannot be used as *8-bit characters*. The slot function may also raise
   an error if the object's contents cannot be interpreted as 8-bit characters.
   For example, if the object is an array which is configured to hold floating
   point values, an exception may be raised if a caller attempts to use
   :attr:`bf_getcharbuffer` to fetch a sequence of 8-bit characters. This notion of
   exporting the internal buffers as "text" is used to distinguish between objects
   that are binary in nature, and those which have character-based content.

   .. note::

      The current policy seems to state that these characters may be multi-byte
      characters. This implies that a buffer size of *N* does not mean there are *N*
      characters present.


.. data:: Py_TPFLAGS_HAVE_GETCHARBUFFER

   Flag bit set in the type structure to indicate that the :attr:`bf_getcharbuffer`
   slot is known.  This being set does not indicate that the object supports the
   buffer interface or that the :attr:`bf_getcharbuffer` slot is non-*NULL*.


.. c:type:: Py_ssize_t (*readbufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)

   Return a pointer to a readable segment of the buffer in ``*ptrptr``.  This
   function is allowed to raise an exception, in which case it must return ``-1``.
   The *segment* which is specified must be zero or positive, and strictly less
   than the number of segments returned by the :attr:`bf_getsegcount` slot
   function.  On success, it returns the length of the segment, and sets
   ``*ptrptr`` to a pointer to that memory.


.. c:type:: Py_ssize_t (*writebufferproc) (PyObject *self, Py_ssize_t segment, void **ptrptr)

   Return a pointer to a writable memory buffer in ``*ptrptr``, and the length of
   that segment as the function return value.  The memory buffer must correspond to
   buffer segment *segment*.  Must return ``-1`` and set an exception on error.
   :exc:`TypeError` should be raised if the object only supports read-only buffers,
   and :exc:`SystemError` should be raised when *segment* specifies a segment that
   doesn't exist.

   .. Why doesn't it raise ValueError for this one?
      GJS: because you shouldn't be calling it with an invalid
      segment. That indicates a blatant programming error in the C code.


.. c:type:: Py_ssize_t (*segcountproc) (PyObject *self, Py_ssize_t *lenp)

   Return the number of memory segments which comprise the buffer.  If *lenp* is
   not *NULL*, the implementation must report the sum of the sizes (in bytes) of
   all segments in ``*lenp``. The function cannot fail.


.. c:type:: Py_ssize_t (*charbufferproc) (PyObject *self, Py_ssize_t segment, char **ptrptr)

   Return the size of the segment *segment* that *ptrptr*  is set to.  ``*ptrptr``
   is set to the memory buffer. Returns ``-1`` on error.
PK	%�\pin6F�F�#html/_sources/c-api/unicode.rst.txtnu�[���.. highlightlang:: c

.. _unicodeobjects:

Unicode Objects and Codecs
--------------------------

.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>

Unicode Objects
^^^^^^^^^^^^^^^


Unicode Type
""""""""""""

These are the basic Unicode object types used for the Unicode implementation in
Python:


.. c:type:: Py_UNICODE

   This type represents the storage type which is used by Python internally as
   basis for holding Unicode ordinals.  Python's default builds use a 16-bit type
   for :c:type:`Py_UNICODE` and store Unicode values internally as UCS2. It is also
   possible to build a UCS4 version of Python (most recent Linux distributions come
   with UCS4 builds of Python). These builds then use a 32-bit type for
   :c:type:`Py_UNICODE` and store Unicode data internally as UCS4. On platforms
   where :c:type:`wchar_t` is available and compatible with the chosen Python
   Unicode build variant, :c:type:`Py_UNICODE` is a typedef alias for
   :c:type:`wchar_t` to enhance native platform compatibility. On all other
   platforms, :c:type:`Py_UNICODE` is a typedef alias for either :c:type:`unsigned
   short` (UCS2) or :c:type:`unsigned long` (UCS4).

Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep
this in mind when writing extensions or interfaces.


.. c:type:: PyUnicodeObject

   This subtype of :c:type:`PyObject` represents a Python Unicode object.


.. c:var:: PyTypeObject PyUnicode_Type

   This instance of :c:type:`PyTypeObject` represents the Python Unicode type.  It
   is exposed to Python code as ``unicode`` and ``types.UnicodeType``.

The following APIs are really C macros and can be used to do fast checks and to
access internal read-only data of Unicode objects:


.. c:function:: int PyUnicode_Check(PyObject *o)

   Return true if the object *o* is a Unicode object or an instance of a Unicode
   subtype.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyUnicode_CheckExact(PyObject *o)

   Return true if the object *o* is a Unicode object, but not an instance of a
   subtype.

   .. versionadded:: 2.2


.. c:function:: Py_ssize_t PyUnicode_GET_SIZE(PyObject *o)

   Return the size of the object.  *o* has to be a :c:type:`PyUnicodeObject` (not
   checked).

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyUnicode_GET_DATA_SIZE(PyObject *o)

   Return the size of the object's internal buffer in bytes.  *o* has to be a
   :c:type:`PyUnicodeObject` (not checked).

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: Py_UNICODE* PyUnicode_AS_UNICODE(PyObject *o)

   Return a pointer to the internal :c:type:`Py_UNICODE` buffer of the object.  *o*
   has to be a :c:type:`PyUnicodeObject` (not checked).


.. c:function:: const char* PyUnicode_AS_DATA(PyObject *o)

   Return a pointer to the internal buffer of the object. *o* has to be a
   :c:type:`PyUnicodeObject` (not checked).


.. c:function:: int PyUnicode_ClearFreeList()

   Clear the free list. Return the total number of freed items.

   .. versionadded:: 2.6


Unicode Character Properties
""""""""""""""""""""""""""""

Unicode provides many different character properties. The most often needed ones
are available through these macros which are mapped to C functions depending on
the Python configuration.


.. c:function:: int Py_UNICODE_ISSPACE(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a whitespace character.


.. c:function:: int Py_UNICODE_ISLOWER(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a lowercase character.


.. c:function:: int Py_UNICODE_ISUPPER(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is an uppercase character.


.. c:function:: int Py_UNICODE_ISTITLE(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a titlecase character.


.. c:function:: int Py_UNICODE_ISLINEBREAK(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a linebreak character.


.. c:function:: int Py_UNICODE_ISDECIMAL(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a decimal character.


.. c:function:: int Py_UNICODE_ISDIGIT(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a digit character.


.. c:function:: int Py_UNICODE_ISNUMERIC(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is a numeric character.


.. c:function:: int Py_UNICODE_ISALPHA(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is an alphabetic character.


.. c:function:: int Py_UNICODE_ISALNUM(Py_UNICODE ch)

   Return ``1`` or ``0`` depending on whether *ch* is an alphanumeric character.

These APIs can be used for fast direct character conversions:


.. c:function:: Py_UNICODE Py_UNICODE_TOLOWER(Py_UNICODE ch)

   Return the character *ch* converted to lower case.


.. c:function:: Py_UNICODE Py_UNICODE_TOUPPER(Py_UNICODE ch)

   Return the character *ch* converted to upper case.


.. c:function:: Py_UNICODE Py_UNICODE_TOTITLE(Py_UNICODE ch)

   Return the character *ch* converted to title case.


.. c:function:: int Py_UNICODE_TODECIMAL(Py_UNICODE ch)

   Return the character *ch* converted to a decimal positive integer.  Return
   ``-1`` if this is not possible.  This macro does not raise exceptions.


.. c:function:: int Py_UNICODE_TODIGIT(Py_UNICODE ch)

   Return the character *ch* converted to a single digit integer. Return ``-1`` if
   this is not possible.  This macro does not raise exceptions.


.. c:function:: double Py_UNICODE_TONUMERIC(Py_UNICODE ch)

   Return the character *ch* converted to a double. Return ``-1.0`` if this is not
   possible.  This macro does not raise exceptions.


Plain Py_UNICODE
""""""""""""""""

To create Unicode objects and access their basic sequence properties, use these
APIs:


.. c:function:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)

   Create a Unicode object from the Py_UNICODE buffer *u* of the given size. *u*
   may be *NULL* which causes the contents to be undefined. It is the user's
   responsibility to fill in the needed data.  The buffer is copied into the new
   object. If the buffer is not *NULL*, the return value might be a shared object.
   Therefore, modification of the resulting Unicode object is only allowed when *u*
   is *NULL*.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)

   Create a Unicode object from the char buffer *u*.  The bytes will be interpreted
   as being UTF-8 encoded.  *u* may also be *NULL* which
   causes the contents to be undefined. It is the user's responsibility to fill in
   the needed data.  The buffer is copied into the new object. If the buffer is not
   *NULL*, the return value might be a shared object. Therefore, modification of
   the resulting Unicode object is only allowed when *u* is *NULL*.

   .. versionadded:: 2.6


.. c:function:: PyObject *PyUnicode_FromString(const char *u)

   Create a Unicode object from a UTF-8 encoded null-terminated char buffer
   *u*.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyUnicode_FromFormat(const char *format, ...)

   Take a C :c:func:`printf`\ -style *format* string and a variable number of
   arguments, calculate the size of the resulting Python unicode string and return
   a string with the values formatted into it.  The variable arguments must be C
   types and must correspond exactly to the format characters in the *format*
   string.  The following format characters are allowed:

   .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
   .. % because not all compilers support the %z width modifier -- we fake it
   .. % when necessary via interpolating PY_FORMAT_SIZE_T.

   .. tabularcolumns:: |l|l|L|

   +-------------------+---------------------+--------------------------------+
   | Format Characters | Type                | Comment                        |
   +===================+=====================+================================+
   | :attr:`%%`        | *n/a*               | The literal % character.       |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%c`        | int                 | A single character,            |
   |                   |                     | represented as a C int.        |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%d`        | int                 | Exactly equivalent to          |
   |                   |                     | ``printf("%d")``.              |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%u`        | unsigned int        | Exactly equivalent to          |
   |                   |                     | ``printf("%u")``.              |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%ld`       | long                | Exactly equivalent to          |
   |                   |                     | ``printf("%ld")``.             |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%lu`       | unsigned long       | Exactly equivalent to          |
   |                   |                     | ``printf("%lu")``.             |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%zd`       | Py_ssize_t          | Exactly equivalent to          |
   |                   |                     | ``printf("%zd")``.             |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%zu`       | size_t              | Exactly equivalent to          |
   |                   |                     | ``printf("%zu")``.             |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%i`        | int                 | Exactly equivalent to          |
   |                   |                     | ``printf("%i")``.              |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%x`        | int                 | Exactly equivalent to          |
   |                   |                     | ``printf("%x")``.              |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%s`        | char\*              | A null-terminated C character  |
   |                   |                     | array.                         |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%p`        | void\*              | The hex representation of a C  |
   |                   |                     | pointer. Mostly equivalent to  |
   |                   |                     | ``printf("%p")`` except that   |
   |                   |                     | it is guaranteed to start with |
   |                   |                     | the literal ``0x`` regardless  |
   |                   |                     | of what the platform's         |
   |                   |                     | ``printf`` yields.             |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%U`        | PyObject\*          | A unicode object.              |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%V`        | PyObject\*, char \* | A unicode object (which may be |
   |                   |                     | *NULL*) and a null-terminated  |
   |                   |                     | C character array as a second  |
   |                   |                     | parameter (which will be used, |
   |                   |                     | if the first parameter is      |
   |                   |                     | *NULL*).                       |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%S`        | PyObject\*          | The result of calling          |
   |                   |                     | :func:`PyObject_Unicode`.      |
   +-------------------+---------------------+--------------------------------+
   | :attr:`%R`        | PyObject\*          | The result of calling          |
   |                   |                     | :func:`PyObject_Repr`.         |
   +-------------------+---------------------+--------------------------------+

   An unrecognized format character causes all the rest of the format string to be
   copied as-is to the result string, and any extra arguments discarded.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyUnicode_FromFormatV(const char *format, va_list vargs)

   Identical to :func:`PyUnicode_FromFormat` except that it takes exactly two
   arguments.

   .. versionadded:: 2.6


.. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)

   Return a read-only pointer to the Unicode object's internal
   :c:type:`Py_UNICODE` buffer, *NULL* if *unicode* is not a Unicode object.
   Note that the resulting :c:type:`Py_UNICODE*` string may contain embedded
   null characters, which would cause the string to be truncated when used in
   most C functions.


.. c:function:: Py_ssize_t PyUnicode_GetSize(PyObject *unicode)

   Return the length of the Unicode object.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type. This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_FromEncodedObject(PyObject *obj, const char *encoding, const char *errors)

   Coerce an encoded object *obj* to a Unicode object and return a reference with
   incremented refcount.

   String and other char buffer compatible objects are decoded according to the
   given encoding and using the error handling defined by errors.  Both can be
   *NULL* to have the interface use the default values (see the next section for
   details).

   All other objects, including Unicode objects, cause a :exc:`TypeError` to be
   set.

   The API returns *NULL* if there was an error.  The caller is responsible for
   decref'ing the returned objects.


.. c:function:: PyObject* PyUnicode_FromObject(PyObject *obj)

   Shortcut for ``PyUnicode_FromEncodedObject(obj, NULL, "strict")`` which is used
   throughout the interpreter whenever coercion to Unicode is needed.

If the platform supports :c:type:`wchar_t` and provides a header file wchar.h,
Python can interface directly to this type using the following functions.
Support is optimized if Python's own :c:type:`Py_UNICODE` type is identical to
the system's :c:type:`wchar_t`.


wchar_t Support
"""""""""""""""

:c:type:`wchar_t` support for platforms which support it:

.. c:function:: PyObject* PyUnicode_FromWideChar(const wchar_t *w, Py_ssize_t size)

   Create a Unicode object from the :c:type:`wchar_t` buffer *w* of the given *size*.
   Return *NULL* on failure.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: Py_ssize_t PyUnicode_AsWideChar(PyUnicodeObject *unicode, wchar_t *w, Py_ssize_t size)

   Copy the Unicode object contents into the :c:type:`wchar_t` buffer *w*.  At most
   *size* :c:type:`wchar_t` characters are copied (excluding a possibly trailing
   0-termination character).  Return the number of :c:type:`wchar_t` characters
   copied or ``-1`` in case of an error.  Note that the resulting :c:type:`wchar_t`
   string may or may not be 0-terminated.  It is the responsibility of the caller
   to make sure that the :c:type:`wchar_t` string is 0-terminated in case this is
   required by the application. Also, note that the :c:type:`wchar_t*` string
   might contain null characters, which would cause the string to be truncated
   when used with most C functions.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type and used an :c:type:`int`
      type for *size*. This might require changes in your code for properly
      supporting 64-bit systems.


.. _builtincodecs:

Built-in Codecs
^^^^^^^^^^^^^^^

Python provides a set of built-in codecs which are written in C for speed. All of
these codecs are directly usable via the following functions.

Many of the following APIs take two arguments encoding and errors, and they
have the same semantics as the ones of the built-in :func:`unicode` Unicode
object constructor.

Setting encoding to *NULL* causes the default encoding to be used which is
ASCII.  The file system calls should use :c:data:`Py_FileSystemDefaultEncoding`
as the encoding for file names. This variable should be treated as read-only: on
some systems, it will be a pointer to a static string, on others, it will change
at run-time (such as when the application invokes setlocale).

Error handling is set by errors which may also be set to *NULL* meaning to use
the default handling defined for the codec.  Default error handling for all
built-in codecs is "strict" (:exc:`ValueError` is raised).

The codecs all use a similar interface.  Only deviation from the following
generic ones are documented for simplicity.


Generic Codecs
""""""""""""""

These are the generic codec APIs:


.. c:function:: PyObject* PyUnicode_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors)

   Create a Unicode object by decoding *size* bytes of the encoded string *s*.
   *encoding* and *errors* have the same meaning as the parameters of the same name
   in the :func:`unicode` built-in function.  The codec to be used is looked up
   using the Python codec registry.  Return *NULL* if an exception was raised by
   the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_Encode(const Py_UNICODE *s, Py_ssize_t size, const char *encoding, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* and return a Python
   string object.  *encoding* and *errors* have the same meaning as the parameters
   of the same name in the Unicode :meth:`~unicode.encode` method.  The codec
   to be used is looked up using the Python codec registry.  Return *NULL* if
   an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsEncodedString(PyObject *unicode, const char *encoding, const char *errors)

   Encode a Unicode object and return the result as Python string object.
   *encoding* and *errors* have the same meaning as the parameters of the same name
   in the Unicode :meth:`encode` method. The codec to be used is looked up using
   the Python codec registry. Return *NULL* if an exception was raised by the
   codec.


UTF-8 Codecs
""""""""""""

These are the UTF-8 codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeUTF8(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the UTF-8 encoded string
   *s*. Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_DecodeUTF8Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)

   If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF8`. If
   *consumed* is not *NULL*, trailing incomplete UTF-8 byte sequences will not be
   treated as an error. Those bytes will not be decoded and the number of bytes
   that have been decoded will be stored in *consumed*.

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeUTF8(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer *s* of the given *size* using UTF-8 and return a
   Python string object.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsUTF8String(PyObject *unicode)

   Encode a Unicode object using UTF-8 and return the result as Python string
   object.  Error handling is "strict".  Return *NULL* if an exception was raised
   by the codec.


UTF-32 Codecs
"""""""""""""

These are the UTF-32 codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeUTF32(const char *s, Py_ssize_t size, const char *errors, int *byteorder)

   Decode *size* bytes from a UTF-32 encoded buffer string and return the
   corresponding Unicode object.  *errors* (if non-*NULL*) defines the error
   handling. It defaults to "strict".

   If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
   order::

      *byteorder == -1: little endian
      *byteorder == 0:  native order
      *byteorder == 1:  big endian

   If ``*byteorder`` is zero, and the first four bytes of the input data are a
   byte order mark (BOM), the decoder switches to this byte order and the BOM is
   not copied into the resulting Unicode string.  If ``*byteorder`` is ``-1`` or
   ``1``, any byte order mark is copied to the output.

   After completion, *\*byteorder* is set to the current byte order at the end
   of input data.

   In a narrow build code points outside the BMP will be decoded as surrogate pairs.

   If *byteorder* is *NULL*, the codec starts in native order mode.

   Return *NULL* if an exception was raised by the codec.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyUnicode_DecodeUTF32Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)

   If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF32`. If
   *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF32Stateful` will not treat
   trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
   by four) as an error. Those bytes will not be decoded and the number of bytes
   that have been decoded will be stored in *consumed*.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyUnicode_EncodeUTF32(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)

   Return a Python bytes object holding the UTF-32 encoded value of the Unicode
   data in *s*.  Output is written according to the following byte order::

      byteorder == -1: little endian
      byteorder == 0:  native byte order (writes a BOM mark)
      byteorder == 1:  big endian

   If byteorder is ``0``, the output string will always start with the Unicode BOM
   mark (U+FEFF). In the other two modes, no BOM mark is prepended.

   If *Py_UNICODE_WIDE* is not defined, surrogate pairs will be output
   as a single code point.

   Return *NULL* if an exception was raised by the codec.

   .. versionadded:: 2.6


.. c:function:: PyObject* PyUnicode_AsUTF32String(PyObject *unicode)

   Return a Python string using the UTF-32 encoding in native byte order. The
   string always starts with a BOM mark.  Error handling is "strict".  Return
   *NULL* if an exception was raised by the codec.

   .. versionadded:: 2.6


UTF-16 Codecs
"""""""""""""

These are the UTF-16 codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeUTF16(const char *s, Py_ssize_t size, const char *errors, int *byteorder)

   Decode *size* bytes from a UTF-16 encoded buffer string and return the
   corresponding Unicode object.  *errors* (if non-*NULL*) defines the error
   handling. It defaults to "strict".

   If *byteorder* is non-*NULL*, the decoder starts decoding using the given byte
   order::

      *byteorder == -1: little endian
      *byteorder == 0:  native order
      *byteorder == 1:  big endian

   If ``*byteorder`` is zero, and the first two bytes of the input data are a
   byte order mark (BOM), the decoder switches to this byte order and the BOM is
   not copied into the resulting Unicode string.  If ``*byteorder`` is ``-1`` or
   ``1``, any byte order mark is copied to the output (where it will result in
   either a ``\ufeff`` or a ``\ufffe`` character).

   After completion, *\*byteorder* is set to the current byte order at the end
   of input data.

   If *byteorder* is *NULL*, the codec starts in native order mode.

   Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_DecodeUTF16Stateful(const char *s, Py_ssize_t size, const char *errors, int *byteorder, Py_ssize_t *consumed)

   If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF16`. If
   *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeUTF16Stateful` will not treat
   trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
   split surrogate pair) as an error. Those bytes will not be decoded and the
   number of bytes that have been decoded will be stored in *consumed*.

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size* and an :c:type:`int *`
      type for *consumed*. This might require changes in your code for
      properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeUTF16(const Py_UNICODE *s, Py_ssize_t size, const char *errors, int byteorder)

   Return a Python string object holding the UTF-16 encoded value of the Unicode
   data in *s*.  Output is written according to the following byte order::

      byteorder == -1: little endian
      byteorder == 0:  native byte order (writes a BOM mark)
      byteorder == 1:  big endian

   If byteorder is ``0``, the output string will always start with the Unicode BOM
   mark (U+FEFF). In the other two modes, no BOM mark is prepended.

   If *Py_UNICODE_WIDE* is defined, a single :c:type:`Py_UNICODE` value may get
   represented as a surrogate pair. If it is not defined, each :c:type:`Py_UNICODE`
   values is interpreted as a UCS-2 character.

   Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsUTF16String(PyObject *unicode)

   Return a Python string using the UTF-16 encoding in native byte order. The
   string always starts with a BOM mark.  Error handling is "strict".  Return
   *NULL* if an exception was raised by the codec.


UTF-7 Codecs
""""""""""""

These are the UTF-7 codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeUTF7(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the UTF-7 encoded string
   *s*.  Return *NULL* if an exception was raised by the codec.


.. c:function:: PyObject* PyUnicode_DecodeUTF7Stateful(const char *s, Py_ssize_t size, const char *errors, Py_ssize_t *consumed)

   If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeUTF7`.  If
   *consumed* is not *NULL*, trailing incomplete UTF-7 base-64 sections will not
   be treated as an error.  Those bytes will not be decoded and the number of
   bytes that have been decoded will be stored in *consumed*.


.. c:function:: PyObject* PyUnicode_EncodeUTF7(const Py_UNICODE *s, Py_ssize_t size, int base64SetO, int base64WhiteSpace, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given size using UTF-7 and
   return a Python bytes object.  Return *NULL* if an exception was raised by
   the codec.

   If *base64SetO* is nonzero, "Set O" (punctuation that has no otherwise
   special meaning) will be encoded in base-64.  If *base64WhiteSpace* is
   nonzero, whitespace will be encoded in base-64.  Both are set to zero for the
   Python "utf-7" codec.


Unicode-Escape Codecs
"""""""""""""""""""""

These are the "Unicode Escape" codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the Unicode-Escape encoded
   string *s*.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Unicode-Escape and
   return a Python string object.  Return *NULL* if an exception was raised by the
   codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsUnicodeEscapeString(PyObject *unicode)

   Encode a Unicode object using Unicode-Escape and return the result as Python
   string object.  Error handling is "strict". Return *NULL* if an exception was
   raised by the codec.


Raw-Unicode-Escape Codecs
"""""""""""""""""""""""""

These are the "Raw Unicode Escape" codec APIs:


.. c:function:: PyObject* PyUnicode_DecodeRawUnicodeEscape(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the Raw-Unicode-Escape
   encoded string *s*.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Raw-Unicode-Escape
   and return a Python string object.  Return *NULL* if an exception was raised by
   the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)

   Encode a Unicode object using Raw-Unicode-Escape and return the result as
   Python string object. Error handling is "strict". Return *NULL* if an exception
   was raised by the codec.


Latin-1 Codecs
""""""""""""""

These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
ordinals and only these are accepted by the codecs during encoding.


.. c:function:: PyObject* PyUnicode_DecodeLatin1(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the Latin-1 encoded string
   *s*.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeLatin1(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using Latin-1 and return
   a Python string object.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsLatin1String(PyObject *unicode)

   Encode a Unicode object using Latin-1 and return the result as Python string
   object.  Error handling is "strict".  Return *NULL* if an exception was raised
   by the codec.


ASCII Codecs
""""""""""""

These are the ASCII codec APIs.  Only 7-bit ASCII data is accepted. All other
codes generate errors.


.. c:function:: PyObject* PyUnicode_DecodeASCII(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the ASCII encoded string
   *s*.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeASCII(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using ASCII and return a
   Python string object.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsASCIIString(PyObject *unicode)

   Encode a Unicode object using ASCII and return the result as Python string
   object.  Error handling is "strict".  Return *NULL* if an exception was raised
   by the codec.


Character Map Codecs
""""""""""""""""""""

This codec is special in that it can be used to implement many different codecs
(and this is in fact what was done to obtain most of the standard codecs
included in the :mod:`encodings` package). The codec uses mapping to encode and
decode characters.

Decoding mappings must map single string characters to single Unicode
characters, integers (which are then interpreted as Unicode ordinals) or ``None``
(meaning "undefined mapping" and causing an error).

Encoding mappings must map single Unicode characters to single string
characters, integers (which are then interpreted as Latin-1 ordinals) or ``None``
(meaning "undefined mapping" and causing an error).

The mapping objects provided must only support the __getitem__ mapping
interface.

If a character lookup fails with a LookupError, the character is copied as-is
meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
resp. Because of this, mappings only need to contain those mappings which map
characters to different code points.

These are the mapping codec APIs:

.. c:function:: PyObject* PyUnicode_DecodeCharmap(const char *s, Py_ssize_t size, PyObject *mapping, const char *errors)

   Create a Unicode object by decoding *size* bytes of the encoded string *s* using
   the given *mapping* object.  Return *NULL* if an exception was raised by the
   codec. If *mapping* is *NULL* latin-1 decoding will be done. Else it can be a
   dictionary mapping byte or a unicode string, which is treated as a lookup table.
   Byte values greater that the length of the string and U+FFFE "characters" are
   treated as "undefined mapping".

   .. versionchanged:: 2.4
      Allowed unicode string as mapping argument.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_EncodeCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *mapping, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using the given
   *mapping* object and return a Python string object. Return *NULL* if an
   exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsCharmapString(PyObject *unicode, PyObject *mapping)

   Encode a Unicode object using the given *mapping* object and return the result
   as Python string object.  Error handling is "strict".  Return *NULL* if an
   exception was raised by the codec.

The following codec API is special in that maps Unicode to Unicode.


.. c:function:: PyObject* PyUnicode_TranslateCharmap(const Py_UNICODE *s, Py_ssize_t size, PyObject *table, const char *errors)

   Translate a :c:type:`Py_UNICODE` buffer of the given *size* by applying a
   character mapping *table* to it and return the resulting Unicode object.  Return
   *NULL* when an exception was raised by the codec.

   The *mapping* table must map Unicode ordinal integers to Unicode ordinal
   integers or ``None`` (causing deletion of the character).

   Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
   and sequences work well.  Unmapped character ordinals (ones which cause a
   :exc:`LookupError`) are left untouched and are copied as-is.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


MBCS codecs for Windows
"""""""""""""""""""""""

These are the MBCS codec APIs. They are currently only available on Windows and
use the Win32 MBCS converters to implement the conversions.  Note that MBCS (or
DBCS) is a class of encodings, not just one.  The target encoding is defined by
the user settings on the machine running the codec.


.. c:function:: PyObject* PyUnicode_DecodeMBCS(const char *s, Py_ssize_t size, const char *errors)

   Create a Unicode object by decoding *size* bytes of the MBCS encoded string *s*.
   Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_DecodeMBCSStateful(const char *s, int size, const char *errors, int *consumed)

   If *consumed* is *NULL*, behave like :c:func:`PyUnicode_DecodeMBCS`. If
   *consumed* is not *NULL*, :c:func:`PyUnicode_DecodeMBCSStateful` will not decode
   trailing lead byte and the number of bytes that have been decoded will be stored
   in *consumed*.

   .. versionadded:: 2.5


.. c:function:: PyObject* PyUnicode_EncodeMBCS(const Py_UNICODE *s, Py_ssize_t size, const char *errors)

   Encode the :c:type:`Py_UNICODE` buffer of the given *size* using MBCS and return a
   Python string object.  Return *NULL* if an exception was raised by the codec.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_AsMBCSString(PyObject *unicode)

   Encode a Unicode object using MBCS and return the result as Python string
   object.  Error handling is "strict".  Return *NULL* if an exception was raised
   by the codec.


Methods & Slots
"""""""""""""""

.. _unicodemethodsandslots:

Methods and Slot Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^

The following APIs are capable of handling Unicode objects and strings on input
(we refer to them as strings in the descriptions) and return Unicode objects or
integers as appropriate.

They all return *NULL* or ``-1`` if an exception occurs.


.. c:function:: PyObject* PyUnicode_Concat(PyObject *left, PyObject *right)

   Concat two strings giving a new Unicode string.


.. c:function:: PyObject* PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)

   Split a string giving a list of Unicode strings.  If *sep* is *NULL*, splitting
   will be done at all whitespace substrings.  Otherwise, splits occur at the given
   separator.  At most *maxsplit* splits will be done.  If negative, no limit is
   set.  Separators are not included in the resulting list.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *maxsplit*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_Splitlines(PyObject *s, int keepend)

   Split a Unicode string at line breaks, returning a list of Unicode strings.
   CRLF is considered to be one line break.  If *keepend* is ``0``, the Line break
   characters are not included in the resulting strings.


.. c:function:: PyObject* PyUnicode_Translate(PyObject *str, PyObject *table, const char *errors)

   Translate a string by applying a character mapping table to it and return the
   resulting Unicode object.

   The mapping table must map Unicode ordinal integers to Unicode ordinal integers
   or ``None`` (causing deletion of the character).

   Mapping tables need only provide the :meth:`__getitem__` interface; dictionaries
   and sequences work well.  Unmapped character ordinals (ones which cause a
   :exc:`LookupError`) are left untouched and are copied as-is.

   *errors* has the usual meaning for codecs. It may be *NULL* which indicates to
   use the default error handling.


.. c:function:: PyObject* PyUnicode_Join(PyObject *separator, PyObject *seq)

   Join a sequence of strings using the given *separator* and return the resulting
   Unicode string.


.. c:function:: Py_ssize_t PyUnicode_Tailmatch(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)

   Return ``1`` if *substr* matches ``str[start:end]`` at the given tail end
   (*direction* == ``-1`` means to do a prefix match, *direction* == ``1`` a suffix match),
   ``0`` otherwise. Return ``-1`` if an error occurred.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *start* and *end*. This
      might require changes in your code for properly supporting 64-bit
      systems.


.. c:function:: Py_ssize_t PyUnicode_Find(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end, int direction)

   Return the first position of *substr* in ``str[start:end]`` using the given
   *direction* (*direction* == ``1`` means to do a forward search, *direction* == ``-1`` a
   backward search).  The return value is the index of the first match; a value of
   ``-1`` indicates that no match was found, and ``-2`` indicates that an error
   occurred and an exception has been set.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *start* and *end*. This
      might require changes in your code for properly supporting 64-bit
      systems.


.. c:function:: Py_ssize_t PyUnicode_Count(PyObject *str, PyObject *substr, Py_ssize_t start, Py_ssize_t end)

   Return the number of non-overlapping occurrences of *substr* in
   ``str[start:end]``.  Return ``-1`` if an error occurred.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type and used an :c:type:`int`
      type for *start* and *end*. This might require changes in your code for
      properly supporting 64-bit systems.


.. c:function:: PyObject* PyUnicode_Replace(PyObject *str, PyObject *substr, PyObject *replstr, Py_ssize_t maxcount)

   Replace at most *maxcount* occurrences of *substr* in *str* with *replstr* and
   return the resulting Unicode object. *maxcount* == ``-1`` means replace all
   occurrences.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *maxcount*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyUnicode_Compare(PyObject *left, PyObject *right)

   Compare two strings and return ``-1``, ``0``, ``1`` for less than, equal, and greater than,
   respectively.


.. c:function:: int PyUnicode_RichCompare(PyObject *left,  PyObject *right,  int op)

   Rich compare two unicode strings and return one of the following:

   * ``NULL`` in case an exception was raised
   * :const:`Py_True` or :const:`Py_False` for successful comparisons
   * :const:`Py_NotImplemented` in case the type combination is unknown

   Note that :const:`Py_EQ` and :const:`Py_NE` comparisons can cause a
   :exc:`UnicodeWarning` in case the conversion of the arguments to Unicode fails
   with a :exc:`UnicodeDecodeError`.

   Possible values for *op* are :const:`Py_GT`, :const:`Py_GE`, :const:`Py_EQ`,
   :const:`Py_NE`, :const:`Py_LT`, and :const:`Py_LE`.


.. c:function:: PyObject* PyUnicode_Format(PyObject *format, PyObject *args)

   Return a new string object from *format* and *args*; this is analogous to
   ``format % args``.


.. c:function:: int PyUnicode_Contains(PyObject *container, PyObject *element)

   Check whether *element* is contained in *container* and return true or false
   accordingly.

   *element* has to coerce to a one element Unicode string. ``-1`` is returned if
   there was an error.
PK	%�\E�����%html/_sources/c-api/utilities.rst.txtnu�[���.. highlightlang:: c


.. _utilities:

*********
Utilities
*********

The functions in this chapter perform various utility tasks, ranging from
helping C code be more portable across platforms, using Python modules from C,
and parsing function arguments and constructing Python values from C values.

.. toctree::

   sys.rst
   import.rst
   marshal.rst
   arg.rst
   conversion.rst
   reflection.rst
   codec.rst
PK	%�\�n\w3434$html/_sources/c-api/veryhigh.rst.txtnu�[���.. highlightlang:: c


.. _veryhigh:

*************************
The Very High Level Layer
*************************

The functions in this chapter will let you execute Python source code given in a
file or a buffer, but they will not let you interact in a more detailed way with
the interpreter.

Several of these functions accept a start symbol from the grammar as a
parameter.  The available start symbols are :const:`Py_eval_input`,
:const:`Py_file_input`, and :const:`Py_single_input`.  These are described
following the functions which accept them as parameters.

Note also that several of these functions take :c:type:`FILE\*` parameters.  One
particular issue which needs to be handled carefully is that the :c:type:`FILE`
structure for different C libraries can be different and incompatible.  Under
Windows (at least), it is possible for dynamically linked extensions to actually
use different libraries, so care should be taken that :c:type:`FILE\*` parameters
are only passed to these functions if it is certain that they were created by
the same library that the Python runtime is using.


.. c:function:: int Py_Main(int argc, char **argv)

   The main program for the standard interpreter.  This is made available for
   programs which embed Python.  The *argc* and *argv* parameters should be
   prepared exactly as those which are passed to a C program's :c:func:`main`
   function.  It is important to note that the argument list may be modified (but
   the contents of the strings pointed to by the argument list are not). The return
   value will be ``0`` if the interpreter exits normally (ie, without an
   exception), ``1`` if the interpreter exits due to an exception, or ``2``
   if the parameter list does not represent a valid Python command line.

   Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
   function will not return ``1``, but exit the process, as long as
   ``Py_InspectFlag`` is not set.


.. c:function:: int PyRun_AnyFile(FILE *fp, const char *filename)

   This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving
   *closeit* set to ``0`` and *flags* set to *NULL*.


.. c:function:: int PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

   This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving
   the *closeit* argument set to ``0``.


.. c:function:: int PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit)

   This is a simplified interface to :c:func:`PyRun_AnyFileExFlags` below, leaving
   the *flags* argument set to *NULL*.


.. c:function:: int PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

   If *fp* refers to a file associated with an interactive device (console or
   terminal input or Unix pseudo-terminal), return the value of
   :c:func:`PyRun_InteractiveLoop`, otherwise return the result of
   :c:func:`PyRun_SimpleFile`.  If *filename* is *NULL*, this function uses
   ``"???"`` as the filename.


.. c:function:: int PyRun_SimpleString(const char *command)

   This is a simplified interface to :c:func:`PyRun_SimpleStringFlags` below,
   leaving the *PyCompilerFlags\** argument set to NULL.


.. c:function:: int PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)

   Executes the Python source code from *command* in the :mod:`__main__` module
   according to the *flags* argument. If :mod:`__main__` does not already exist, it
   is created.  Returns ``0`` on success or ``-1`` if an exception was raised.  If
   there was an error, there is no way to get the exception information. For the
   meaning of *flags*, see below.

   Note that if an otherwise unhandled :exc:`SystemExit` is raised, this
   function will not return ``-1``, but exit the process, as long as
   ``Py_InspectFlag`` is not set.


.. c:function:: int PyRun_SimpleFile(FILE *fp, const char *filename)

   This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below,
   leaving *closeit* set to ``0`` and *flags* set to *NULL*.


.. c:function:: int PyRun_SimpleFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

   This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below,
   leaving *closeit* set to ``0``.


.. c:function:: int PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit)

   This is a simplified interface to :c:func:`PyRun_SimpleFileExFlags` below,
   leaving *flags* set to *NULL*.


.. c:function:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)

   Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is read
   from *fp* instead of an in-memory string. *filename* should be the name of the
   file.  If *closeit* is true, the file is closed before PyRun_SimpleFileExFlags
   returns.


.. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename)

   This is a simplified interface to :c:func:`PyRun_InteractiveOneFlags` below,
   leaving *flags* set to *NULL*.


.. c:function:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

   Read and execute a single statement from a file associated with an
   interactive device according to the *flags* argument.  The user will be
   prompted using ``sys.ps1`` and ``sys.ps2``.  Returns ``0`` when the input was
   executed successfully, ``-1`` if there was an exception, or an error code
   from the :file:`errcode.h` include file distributed as part of Python if
   there was a parse error.  (Note that :file:`errcode.h` is not included by
   :file:`Python.h`, so must be included specifically if needed.)


.. c:function:: int PyRun_InteractiveLoop(FILE *fp, const char *filename)

   This is a simplified interface to :c:func:`PyRun_InteractiveLoopFlags` below,
   leaving *flags* set to *NULL*.


.. c:function:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)

   Read and execute statements from a file associated with an interactive device
   until EOF is reached.  The user will be prompted using ``sys.ps1`` and
   ``sys.ps2``.  Returns ``0`` at EOF.


.. c:function:: struct _node* PyParser_SimpleParseString(const char *str, int start)

   This is a simplified interface to
   :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving  *filename* set
   to *NULL* and *flags* set to ``0``.


.. c:function:: struct _node* PyParser_SimpleParseStringFlags( const char *str, int start, int flags)

   This is a simplified interface to
   :c:func:`PyParser_SimpleParseStringFlagsFilename` below, leaving  *filename* set
   to *NULL*.


.. c:function:: struct _node* PyParser_SimpleParseStringFlagsFilename( const char *str, const char *filename, int start, int flags)

   Parse Python source code from *str* using the start token *start* according to
   the *flags* argument.  The result can be used to create a code object which can
   be evaluated efficiently. This is useful if a code fragment must be evaluated
   many times.


.. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)

   This is a simplified interface to :c:func:`PyParser_SimpleParseFileFlags` below,
   leaving *flags* set to ``0``.


.. c:function:: struct _node* PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)

   Similar to :c:func:`PyParser_SimpleParseStringFlagsFilename`, but the Python
   source code is read from *fp* instead of an in-memory string.


.. c:function:: PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals)

   This is a simplified interface to :c:func:`PyRun_StringFlags` below, leaving
   *flags* set to *NULL*.


.. c:function:: PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)

   Execute Python source code from *str* in the context specified by the
   dictionaries *globals* and *locals* with the compiler flags specified by
   *flags*.  The parameter *start* specifies the start token that should be used to
   parse the source code.

   Returns the result of executing the code as a Python object, or *NULL* if an
   exception was raised.


.. c:function:: PyObject* PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals)

   This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving
   *closeit* set to ``0`` and *flags* set to *NULL*.


.. c:function:: PyObject* PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit)

   This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving
   *flags* set to *NULL*.


.. c:function:: PyObject* PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)

   This is a simplified interface to :c:func:`PyRun_FileExFlags` below, leaving
   *closeit* set to ``0``.


.. c:function:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)

   Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read from
   *fp* instead of an in-memory string. *filename* should be the name of the file.
   If *closeit* is true, the file is closed before :c:func:`PyRun_FileExFlags`
   returns.


.. c:function:: PyObject* Py_CompileString(const char *str, const char *filename, int start)

   This is a simplified interface to :c:func:`Py_CompileStringFlags` below, leaving
   *flags* set to *NULL*.


.. c:function:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)

   Parse and compile the Python source code in *str*, returning the resulting code
   object.  The start token is given by *start*; this can be used to constrain the
   code which can be compiled and should be :const:`Py_eval_input`,
   :const:`Py_file_input`, or :const:`Py_single_input`.  The filename specified by
   *filename* is used to construct the code object and may appear in tracebacks or
   :exc:`SyntaxError` exception messages.  This returns *NULL* if the code cannot
   be parsed or compiled.


.. c:function:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)

   This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just
   the code object, and the dictionaries of global and local variables.
   The other arguments are set to *NULL*.


.. c:function:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure)

   Evaluate a precompiled code object, given a particular environment for its
   evaluation.  This environment consists of dictionaries of global and local
   variables, arrays of arguments, keywords and defaults, and a closure tuple of
   cells.


.. c:function:: PyObject* PyEval_EvalFrame(PyFrameObject *f)

   Evaluate an execution frame.  This is a simplified interface to
   PyEval_EvalFrameEx, for backward compatibility.


.. c:function:: PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)

   This is the main, unvarnished function of Python interpretation.  It is
   literally 2000 lines long.  The code object associated with the execution
   frame *f* is executed, interpreting bytecode and executing calls as needed.
   The additional *throwflag* parameter can mostly be ignored - if true, then
   it causes an exception to immediately be thrown; this is used for the
   :meth:`~generator.throw` methods of generator objects.


.. c:function:: int PyEval_MergeCompilerFlags(PyCompilerFlags *cf)

   This function changes the flags of the current evaluation frame, and returns
   true on success, false on failure.


.. c:var:: int Py_eval_input

   .. index:: single: Py_CompileString()

   The start symbol from the Python grammar for isolated expressions; for use with
   :c:func:`Py_CompileString`.


.. c:var:: int Py_file_input

   .. index:: single: Py_CompileString()

   The start symbol from the Python grammar for sequences of statements as read
   from a file or other source; for use with :c:func:`Py_CompileString`.  This is
   the symbol to use when compiling arbitrarily long Python source code.


.. c:var:: int Py_single_input

   .. index:: single: Py_CompileString()

   The start symbol from the Python grammar for a single statement; for use with
   :c:func:`Py_CompileString`. This is the symbol used for the interactive
   interpreter loop.


.. c:type:: struct PyCompilerFlags

   This is the structure used to hold compiler flags.  In cases where code is only
   being compiled, it is passed as ``int flags``, and in cases where code is being
   executed, it is passed as ``PyCompilerFlags *flags``.  In this case, ``from
   __future__ import`` can modify *flags*.

   Whenever ``PyCompilerFlags *flags`` is *NULL*, :attr:`cf_flags` is treated as
   equal to ``0``, and any modification due to ``from __future__ import`` is
   discarded.  ::

      struct PyCompilerFlags {
          int cf_flags;
      }


.. c:var:: int CO_FUTURE_DIVISION

   This bit can be set in *flags* to cause division operator ``/`` to be
   interpreted as "true division" according to :pep:`238`.

PK	%�\$�q9#html/_sources/c-api/weakref.rst.txtnu�[���.. highlightlang:: c

.. _weakrefobjects:

Weak Reference Objects
----------------------

Python supports *weak references* as first-class objects.  There are two
specific object types which directly implement weak references.  The first is a
simple reference object, and the second acts as a proxy for the original object
as much as it can.


.. c:function:: int PyWeakref_Check(ob)

   Return true if *ob* is either a reference or proxy object.

   .. versionadded:: 2.2


.. c:function:: int PyWeakref_CheckRef(ob)

   Return true if *ob* is a reference object.

   .. versionadded:: 2.2


.. c:function:: int PyWeakref_CheckProxy(ob)

   Return true if *ob* is a proxy object.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyWeakref_NewRef(PyObject *ob, PyObject *callback)

   Return a weak reference object for the object *ob*.  This will always return
   a new reference, but is not guaranteed to create a new object; an existing
   reference object may be returned.  The second parameter, *callback*, can be a
   callable object that receives notification when *ob* is garbage collected; it
   should accept a single parameter, which will be the weak reference object
   itself. *callback* may also be ``None`` or *NULL*.  If *ob* is not a
   weakly-referencable object, or if *callback* is not callable, ``None``, or
   *NULL*, this will return *NULL* and raise :exc:`TypeError`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyWeakref_NewProxy(PyObject *ob, PyObject *callback)

   Return a weak reference proxy object for the object *ob*.  This will always
   return a new reference, but is not guaranteed to create a new object; an
   existing proxy object may be returned.  The second parameter, *callback*, can
   be a callable object that receives notification when *ob* is garbage
   collected; it should accept a single parameter, which will be the weak
   reference object itself. *callback* may also be ``None`` or *NULL*.  If *ob*
   is not a weakly-referencable object, or if *callback* is not callable,
   ``None``, or *NULL*, this will return *NULL* and raise :exc:`TypeError`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyWeakref_GetObject(PyObject *ref)

   Return the referenced object from a weak reference, *ref*.  If the referent is
   no longer live, returns :const:`Py_None`.

   .. versionadded:: 2.2

   .. warning::

      This function returns a **borrowed reference** to the referenced object.
      This means that you should always call :c:func:`Py_INCREF` on the object
      except if you know that it cannot be destroyed while you are still
      using it.


.. c:function:: PyObject* PyWeakref_GET_OBJECT(PyObject *ref)

   Similar to :c:func:`PyWeakref_GetObject`, but implemented as a macro that does no
   error checking.

   .. versionadded:: 2.2
PK	%�\��H���$html/_sources/c-api/abstract.rst.txtnu�[���.. highlightlang:: c


.. _abstract:

**********************
Abstract Objects Layer
**********************

The functions in this chapter interact with Python objects regardless of their
type, or with wide classes of object types (e.g. all numerical types, or all
sequence types).  When used on object types for which they do not apply, they
will raise a Python exception.

It is not possible to use these functions on objects that are not properly
initialized, such as a list object that has been created by :c:func:`PyList_New`,
but whose items have not been set to some non-\ ``NULL`` value yet.

.. toctree::

   object.rst
   number.rst
   sequence.rst
   mapping.rst
   iter.rst
   objbuffer.rst
PK	%�\���A��&html/_sources/c-api/allocation.rst.txtnu�[���.. highlightlang:: c

.. _allocating-objects:

Allocating Objects on the Heap
==============================


.. c:function:: PyObject* _PyObject_New(PyTypeObject *type)


.. c:function:: PyVarObject* _PyObject_NewVar(PyTypeObject *type, Py_ssize_t size)

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: void _PyObject_Del(PyObject *op)


.. c:function:: PyObject* PyObject_Init(PyObject *op, PyTypeObject *type)

   Initialize a newly-allocated object *op* with its type and initial
   reference.  Returns the initialized object.  If *type* indicates that the
   object participates in the cyclic garbage detector, it is added to the
   detector's set of observed objects. Other fields of the object are not
   affected.


.. c:function:: PyVarObject* PyObject_InitVar(PyVarObject *op, PyTypeObject *type, Py_ssize_t size)

   This does everything :c:func:`PyObject_Init` does, and also initializes the
   length information for a variable-size object.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: TYPE* PyObject_New(TYPE, PyTypeObject *type)

   Allocate a new Python object using the C structure type *TYPE* and the
   Python type object *type*.  Fields not defined by the Python object header
   are not initialized; the object's reference count will be one.  The size of
   the memory allocation is determined from the :c:member:`~PyTypeObject.tp_basicsize` field of
   the type object.


.. c:function:: TYPE* PyObject_NewVar(TYPE, PyTypeObject *type, Py_ssize_t size)

   Allocate a new Python object using the C structure type *TYPE* and the
   Python type object *type*.  Fields not defined by the Python object header
   are not initialized.  The allocated memory allows for the *TYPE* structure
   plus *size* fields of the size given by the :c:member:`~PyTypeObject.tp_itemsize` field of
   *type*.  This is useful for implementing objects like tuples, which are
   able to determine their size at construction time.  Embedding the array of
   fields into the same allocation decreases the number of allocations,
   improving the memory management efficiency.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: void PyObject_Del(PyObject *op)

   Releases memory allocated to an object using :c:func:`PyObject_New` or
   :c:func:`PyObject_NewVar`.  This is normally called from the
   :c:member:`~PyTypeObject.tp_dealloc` handler specified in the object's type.  The fields of
   the object should not be accessed after this call as the memory is no
   longer a valid Python object.


.. c:function:: PyObject* Py_InitModule(char *name, PyMethodDef *methods)

   Create a new module object based on a name and table of functions,
   returning the new module object.

   .. versionchanged:: 2.3
      Older versions of Python did not support *NULL* as the value for the
      *methods* argument.


.. c:function:: PyObject* Py_InitModule3(char *name, PyMethodDef *methods, char *doc)

   Create a new module object based on a name and table of functions,
   returning the new module object.  If *doc* is non-*NULL*, it will be used
   to define the docstring for the module.

   .. versionchanged:: 2.3
      Older versions of Python did not support *NULL* as the value for the
      *methods* argument.


.. c:function:: PyObject* Py_InitModule4(char *name, PyMethodDef *methods, char *doc, PyObject *self, int apiver)

   Create a new module object based on a name and table of functions,
   returning the new module object.  If *doc* is non-*NULL*, it will be used
   to define the docstring for the module.  If *self* is non-*NULL*, it will
   be passed to the functions of the module as their (otherwise *NULL*) first
   parameter.  (This was added as an experimental feature, and there are no
   known uses in the current version of Python.)  For *apiver*, the only value
   which should be passed is defined by the constant
   :const:`PYTHON_API_VERSION`.

   .. note::

      Most uses of this function should probably be using the
      :c:func:`Py_InitModule3` instead; only use this if you are sure you need
      it.

   .. versionchanged:: 2.3
      Older versions of Python did not support *NULL* as the value for the
      *methods* argument.


.. c:var:: PyObject _Py_NoneStruct

   Object which is visible in Python as ``None``.  This should only be
   accessed using the ``Py_None`` macro, which evaluates to a pointer to this
   object.
PK	%�\��n�e�ehtml/_sources/c-api/arg.rst.txtnu�[���.. highlightlang:: c

.. _arg-parsing:

Parsing arguments and building values
=====================================

These functions are useful when creating your own extensions functions and
methods.  Additional information and examples are available in
:ref:`extending-index`.

The first three of these functions described, :c:func:`PyArg_ParseTuple`,
:c:func:`PyArg_ParseTupleAndKeywords`, and :c:func:`PyArg_Parse`, all use
*format strings* which are used to tell the function about the expected
arguments.  The format strings use the same syntax for each of these
functions.

A format string consists of zero or more "format units."  A format unit
describes one Python object; it is usually a single character or a
parenthesized sequence of format units.  With a few exceptions, a format unit
that is not a parenthesized sequence normally corresponds to a single address
argument to these functions.  In the following description, the quoted form is
the format unit; the entry in (round) parentheses is the Python object type
that matches the format unit; and the entry in [square] brackets is the type
of the C variable(s) whose address should be passed.

These formats allow accessing an object as a contiguous chunk of memory.
You don't have to provide raw storage for the returned unicode or bytes
area.  Also, you won't have to release any memory yourself, except with the
``es``, ``es#``, ``et`` and ``et#`` formats.

``s`` (string or Unicode) [const char \*]
   Convert a Python string or Unicode object to a C pointer to a character
   string.  You must not provide storage for the string itself; a pointer to
   an existing string is stored into the character pointer variable whose
   address you pass.  The C string is NUL-terminated.  The Python string must
   not contain embedded NUL bytes; if it does, a :exc:`TypeError` exception is
   raised. Unicode objects are converted to C strings using the default
   encoding.  If this conversion fails, a :exc:`UnicodeError` is raised.

``s#`` (string, Unicode or any read buffer compatible object) [const char \*, int (or :c:type:`Py_ssize_t`, see below)]
   This variant on ``s`` stores into two C variables, the first one a pointer
   to a character string, the second one its length.  In this case the Python
   string may contain embedded null bytes.  Unicode objects pass back a
   pointer to the default encoded string version of the object if such a
   conversion is possible.  All other read-buffer compatible objects pass back
   a reference to the raw internal data representation.

   Starting with Python 2.5 the type of the length argument can be controlled
   by defining the macro :c:macro:`PY_SSIZE_T_CLEAN` before including
   :file:`Python.h`.  If the macro is defined, length is a :c:type:`Py_ssize_t`
   rather than an int.

``s*`` (string, Unicode, or any buffer compatible object) [Py_buffer]
   Similar to ``s#``, this code fills a Py_buffer structure provided by the
   caller.  The buffer gets locked, so that the caller can subsequently use
   the buffer even inside a ``Py_BEGIN_ALLOW_THREADS`` block; the caller is
   responsible for calling ``PyBuffer_Release`` with the structure after it
   has processed the data.

   .. versionadded:: 2.6

``z`` (string, Unicode  or ``None``) [const char \*]
   Like ``s``, but the Python object may also be ``None``, in which case the C
   pointer is set to *NULL*.

``z#`` (string, Unicode, ``None`` or any read buffer compatible object) [const char \*, int]
   This is to ``s#`` as ``z`` is to ``s``.

``z*`` (string, Unicode, ``None`` or any buffer compatible object) [Py_buffer]
   This is to ``s*`` as ``z`` is to ``s``.

   .. versionadded:: 2.6

``u`` (Unicode) [Py_UNICODE \*]
   Convert a Python Unicode object to a C pointer to a NUL-terminated buffer
   of 16-bit Unicode (UTF-16) data.  As with ``s``, there is no need to
   provide storage for the Unicode data buffer; a pointer to the existing
   Unicode data is stored into the :c:type:`Py_UNICODE` pointer variable whose
   address you pass.

``u#`` (Unicode) [Py_UNICODE \*, int]
   This variant on ``u`` stores into two C variables, the first one a pointer
   to a Unicode data buffer, the second one its length. Non-Unicode objects
   are handled by interpreting their read-buffer pointer as pointer to a
   :c:type:`Py_UNICODE` array.

``es`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer]
   This variant on ``s`` is used for encoding Unicode and objects convertible
   to Unicode into a character buffer. It only works for encoded data without
   embedded NUL bytes.

   This format requires two arguments.  The first is only used as input, and
   must be a :c:type:`const char\*` which points to the name of an encoding as
   a NUL-terminated string, or *NULL*, in which case the default encoding is
   used.  An exception is raised if the named encoding is not known to Python.
   The second argument must be a :c:type:`char\*\*`; the value of the pointer
   it references will be set to a buffer with the contents of the argument
   text.  The text will be encoded in the encoding specified by the first
   argument.

   :c:func:`PyArg_ParseTuple` will allocate a buffer of the needed size, copy
   the encoded data into this buffer and adjust *\*buffer* to reference the
   newly allocated storage.  The caller is responsible for calling
   :c:func:`PyMem_Free` to free the allocated buffer after use.

``et`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer]
   Same as ``es`` except that 8-bit string objects are passed through without
   recoding them.  Instead, the implementation assumes that the string object
   uses the encoding passed in as parameter.

``es#`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
   This variant on ``s#`` is used for encoding Unicode and objects convertible
   to Unicode into a character buffer.  Unlike the ``es`` format, this variant
   allows input data which contains NUL characters.

   It requires three arguments.  The first is only used as input, and must be
   a :c:type:`const char\*` which points to the name of an encoding as a
   NUL-terminated string, or *NULL*, in which case the default encoding is
   used.  An exception is raised if the named encoding is not known to Python.
   The second argument must be a :c:type:`char\*\*`; the value of the pointer
   it references will be set to a buffer with the contents of the argument
   text.  The text will be encoded in the encoding specified by the first
   argument.  The third argument must be a pointer to an integer; the
   referenced integer will be set to the number of bytes in the output buffer.

   There are two modes of operation:

   If *\*buffer* points a *NULL* pointer, the function will allocate a buffer
   of the needed size, copy the encoded data into this buffer and set
   *\*buffer* to reference the newly allocated storage.  The caller is
   responsible for calling :c:func:`PyMem_Free` to free the allocated buffer
   after usage.

   If *\*buffer* points to a non-*NULL* pointer (an already allocated buffer),
   :c:func:`PyArg_ParseTuple` will use this location as the buffer and
   interpret the initial value of *\*buffer_length* as the buffer size.  It
   will then copy the encoded data into the buffer and NUL-terminate it.  If
   the buffer is not large enough, a :exc:`TypeError` will be set.
   Note: starting from Python 3.6 a :exc:`ValueError` will be set.

   In both cases, *\*buffer_length* is set to the length of the encoded data
   without the trailing NUL byte.

``et#`` (string, Unicode or character buffer compatible object) [const char \*encoding, char \*\*buffer, int \*buffer_length]
   Same as ``es#`` except that string objects are passed through without
   recoding them. Instead, the implementation assumes that the string object
   uses the encoding passed in as parameter.

``b`` (integer) [unsigned char]
   Convert a nonnegative Python integer to an unsigned tiny int, stored in a C
   :c:type:`unsigned char`.

``B`` (integer) [unsigned char]
   Convert a Python integer to a tiny int without overflow checking, stored in
   a C :c:type:`unsigned char`.

   .. versionadded:: 2.3

``h`` (integer) [short int]
   Convert a Python integer to a C :c:type:`short int`.

``H`` (integer) [unsigned short int]
   Convert a Python integer to a C :c:type:`unsigned short int`, without
   overflow checking.

   .. versionadded:: 2.3

``i`` (integer) [int]
   Convert a Python integer to a plain C :c:type:`int`.

``I`` (integer) [unsigned int]
   Convert a Python integer to a C :c:type:`unsigned int`, without overflow
   checking.

   .. versionadded:: 2.3

``l`` (integer) [long int]
   Convert a Python integer to a C :c:type:`long int`.

``k`` (integer) [unsigned long]
   Convert a Python integer or long integer to a C :c:type:`unsigned long`
   without overflow checking.

   .. versionadded:: 2.3

``L`` (integer) [PY_LONG_LONG]
   Convert a Python integer to a C :c:type:`long long`.  This format is only
   available on platforms that support :c:type:`long long` (or :c:type:`_int64`
   on Windows).

``K`` (integer) [unsigned PY_LONG_LONG]
   Convert a Python integer or long integer to a C :c:type:`unsigned long long`
   without overflow checking.  This format is only available on platforms that
   support :c:type:`unsigned long long` (or :c:type:`unsigned _int64` on
   Windows).

   .. versionadded:: 2.3

``n`` (integer) [Py_ssize_t]
   Convert a Python integer or long integer to a C :c:type:`Py_ssize_t`.

   .. versionadded:: 2.5

``c`` (string of length 1) [char]
   Convert a Python character, represented as a string of length 1, to a C
   :c:type:`char`.

``f`` (float) [float]
   Convert a Python floating point number to a C :c:type:`float`.

``d`` (float) [double]
   Convert a Python floating point number to a C :c:type:`double`.

``D`` (complex) [Py_complex]
   Convert a Python complex number to a C :c:type:`Py_complex` structure.

``O`` (object) [PyObject \*]
   Store a Python object (without any conversion) in a C object pointer.  The
   C program thus receives the actual object that was passed.  The object's
   reference count is not increased.  The pointer stored is not *NULL*.

``O!`` (object) [*typeobject*, PyObject \*]
   Store a Python object in a C object pointer.  This is similar to ``O``, but
   takes two C arguments: the first is the address of a Python type object,
   the second is the address of the C variable (of type :c:type:`PyObject\*`)
   into which the object pointer is stored.  If the Python object does not
   have the required type, :exc:`TypeError` is raised.

``O&`` (object) [*converter*, *anything*]
   Convert a Python object to a C variable through a *converter* function.
   This takes two arguments: the first is a function, the second is the
   address of a C variable (of arbitrary type), converted to :c:type:`void \*`.
   The *converter* function in turn is called as follows::

      status = converter(object, address);

   where *object* is the Python object to be converted and *address* is the
   :c:type:`void\*` argument that was passed to the :c:func:`PyArg_Parse\*`
   function.  The returned *status* should be ``1`` for a successful
   conversion and ``0`` if the conversion has failed.  When the conversion
   fails, the *converter* function should raise an exception and leave the
   content of *address* unmodified.

``S`` (string) [PyStringObject \*]
   Like ``O`` but requires that the Python object is a string object.  Raises
   :exc:`TypeError` if the object is not a string object.  The C variable may
   also be declared as :c:type:`PyObject\*`.

``U`` (Unicode string) [PyUnicodeObject \*]
   Like ``O`` but requires that the Python object is a Unicode object.  Raises
   :exc:`TypeError` if the object is not a Unicode object.  The C variable may
   also be declared as :c:type:`PyObject\*`.

``t#`` (read-only character buffer) [char \*, int]
   Like ``s#``, but accepts any object which implements the read-only buffer
   interface.  The :c:type:`char\*` variable is set to point to the first byte
   of the buffer, and the :c:type:`int` is set to the length of the buffer.
   Only single-segment buffer objects are accepted; :exc:`TypeError` is raised
   for all others.

``w`` (read-write character buffer) [char \*]
   Similar to ``s``, but accepts any object which implements the read-write
   buffer interface.  The caller must determine the length of the buffer by
   other means, or use ``w#`` instead.  Only single-segment buffer objects are
   accepted; :exc:`TypeError` is raised for all others.

``w#`` (read-write character buffer) [char \*, Py_ssize_t]
   Like ``s#``, but accepts any object which implements the read-write buffer
   interface.  The :c:type:`char \*` variable is set to point to the first byte
   of the buffer, and the :c:type:`Py_ssize_t` is set to the length of the
   buffer.  Only single-segment buffer objects are accepted; :exc:`TypeError`
   is raised for all others.

``w*`` (read-write byte-oriented buffer) [Py_buffer]
   This is to ``w`` what ``s*`` is to ``s``.

   .. versionadded:: 2.6

``(items)`` (tuple) [*matching-items*]
   The object must be a Python sequence whose length is the number of format
   units in *items*.  The C arguments must correspond to the individual format
   units in *items*.  Format units for sequences may be nested.

   .. note::

      Prior to Python version 1.5.2, this format specifier only accepted a
      tuple containing the individual parameters, not an arbitrary sequence.
      Code which previously caused :exc:`TypeError` to be raised here may now
      proceed without an exception.  This is not expected to be a problem for
      existing code.

It is possible to pass Python long integers where integers are requested;
however no proper range checking is done --- the most significant bits are
silently truncated when the receiving field is too small to receive the value
(actually, the semantics are inherited from downcasts in C --- your mileage
may vary).

A few other characters have a meaning in a format string.  These may not occur
inside nested parentheses.  They are:

``|``
   Indicates that the remaining arguments in the Python argument list are
   optional.  The C variables corresponding to optional arguments should be
   initialized to their default value --- when an optional argument is not
   specified, :c:func:`PyArg_ParseTuple` does not touch the contents of the
   corresponding C variable(s).

``:``
   The list of format units ends here; the string after the colon is used as
   the function name in error messages (the "associated value" of the
   exception that :c:func:`PyArg_ParseTuple` raises).

``;``
   The list of format units ends here; the string after the semicolon is used
   as the error message *instead* of the default error message.  ``:`` and
   ``;`` mutually exclude each other.

Note that any Python object references which are provided to the caller are
*borrowed* references; do not decrement their reference count!

Additional arguments passed to these functions must be addresses of variables
whose type is determined by the format string; these are used to store values
from the input tuple.  There are a few cases, as described in the list of
format units above, where these parameters are used as input values; they
should match what is specified for the corresponding format unit in that case.

For the conversion to succeed, the *arg* object must match the format and the
format must be exhausted.  On success, the :c:func:`PyArg_Parse\*` functions
return true, otherwise they return false and raise an appropriate exception.
When the :c:func:`PyArg_Parse\*` functions fail due to conversion failure in
one of the format units, the variables at the addresses corresponding to that
and the following format units are left untouched.


.. c:function:: int PyArg_ParseTuple(PyObject *args, const char *format, ...)

   Parse the parameters of a function that takes only positional parameters
   into local variables.  Returns true on success; on failure, it returns
   false and raises the appropriate exception.


.. c:function:: int PyArg_VaParse(PyObject *args, const char *format, va_list vargs)

   Identical to :c:func:`PyArg_ParseTuple`, except that it accepts a va_list
   rather than a variable number of arguments.


.. c:function:: int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], ...)

   Parse the parameters of a function that takes both positional and keyword
   parameters into local variables.  Returns true on success; on failure, it
   returns false and raises the appropriate exception.


.. c:function:: int PyArg_VaParseTupleAndKeywords(PyObject *args, PyObject *kw, const char *format, char *keywords[], va_list vargs)

   Identical to :c:func:`PyArg_ParseTupleAndKeywords`, except that it accepts a
   va_list rather than a variable number of arguments.


.. c:function:: int PyArg_Parse(PyObject *args, const char *format, ...)

   Function used to deconstruct the argument lists of "old-style" functions
   --- these are functions which use the :const:`METH_OLDARGS` parameter
   parsing method.  This is not recommended for use in parameter parsing in
   new code, and most code in the standard interpreter has been modified to no
   longer use this for that purpose.  It does remain a convenient way to
   decompose other tuples, however, and may continue to be used for that
   purpose.


.. c:function:: int PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)

   A simpler form of parameter retrieval which does not use a format string to
   specify the types of the arguments.  Functions which use this method to
   retrieve their parameters should be declared as :const:`METH_VARARGS` in
   function or method tables.  The tuple containing the actual parameters
   should be passed as *args*; it must actually be a tuple.  The length of the
   tuple must be at least *min* and no more than *max*; *min* and *max* may be
   equal.  Additional arguments must be passed to the function, each of which
   should be a pointer to a :c:type:`PyObject\*` variable; these will be filled
   in with the values from *args*; they will contain borrowed references.  The
   variables which correspond to optional parameters not given by *args* will
   not be filled in; these should be initialized by the caller. This function
   returns true on success and false if *args* is not a tuple or contains the
   wrong number of elements; an exception will be set if there was a failure.

   This is an example of the use of this function, taken from the sources for
   the :mod:`_weakref` helper module for weak references::

      static PyObject *
      weakref_ref(PyObject *self, PyObject *args)
      {
          PyObject *object;
          PyObject *callback = NULL;
          PyObject *result = NULL;

          if (PyArg_UnpackTuple(args, "ref", 1, 2, &object, &callback)) {
              result = PyWeakref_NewRef(object, callback);
          }
          return result;
      }

   The call to :c:func:`PyArg_UnpackTuple` in this example is entirely
   equivalent to this call to :c:func:`PyArg_ParseTuple`::

      PyArg_ParseTuple(args, "O|O:ref", &object, &callback)

   .. versionadded:: 2.2

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *min* and *max*. This might
      require changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* Py_BuildValue(const char *format, ...)

   Create a new value based on a format string similar to those accepted by
   the :c:func:`PyArg_Parse\*` family of functions and a sequence of values.
   Returns the value or *NULL* in the case of an error; an exception will be
   raised if *NULL* is returned.

   :c:func:`Py_BuildValue` does not always build a tuple.  It builds a tuple
   only if its format string contains two or more format units.  If the format
   string is empty, it returns ``None``; if it contains exactly one format
   unit, it returns whatever object is described by that format unit.  To
   force it to return a tuple of size ``0`` or one, parenthesize the format
   string.

   When memory buffers are passed as parameters to supply data to build
   objects, as for the ``s`` and ``s#`` formats, the required data is copied.
   Buffers provided by the caller are never referenced by the objects created
   by :c:func:`Py_BuildValue`.  In other words, if your code invokes
   :c:func:`malloc` and passes the allocated memory to :c:func:`Py_BuildValue`,
   your code is responsible for calling :c:func:`free` for that memory once
   :c:func:`Py_BuildValue` returns.

   In the following description, the quoted form is the format unit; the entry
   in (round) parentheses is the Python object type that the format unit will
   return; and the entry in [square] brackets is the type of the C value(s) to
   be passed.

   The characters space, tab, colon and comma are ignored in format strings
   (but not within format units such as ``s#``).  This can be used to make
   long format strings a tad more readable.

   ``s`` (string) [char \*]
      Convert a null-terminated C string to a Python object.  If the C string
      pointer is *NULL*, ``None`` is used.

   ``s#`` (string) [char \*, int]
      Convert a C string and its length to a Python object.  If the C string
      pointer is *NULL*, the length is ignored and ``None`` is returned.

   ``z`` (string or ``None``) [char \*]
      Same as ``s``.

   ``z#`` (string or ``None``) [char \*, int]
      Same as ``s#``.

   ``u`` (Unicode string) [Py_UNICODE \*]
      Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a
      Python Unicode object.  If the Unicode buffer pointer is *NULL*,
      ``None`` is returned.

   ``u#`` (Unicode string) [Py_UNICODE \*, int]
      Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a
      Python Unicode object.   If the Unicode buffer pointer is *NULL*, the
      length is ignored and ``None`` is returned.

   ``i`` (integer) [int]
      Convert a plain C :c:type:`int` to a Python integer object.

   ``b`` (integer) [char]
      Convert a plain C :c:type:`char` to a Python integer object.

   ``h`` (integer) [short int]
      Convert a plain C :c:type:`short int` to a Python integer object.

   ``l`` (integer) [long int]
      Convert a C :c:type:`long int` to a Python integer object.

   ``B`` (integer) [unsigned char]
      Convert a C :c:type:`unsigned char` to a Python integer object.

   ``H`` (integer) [unsigned short int]
      Convert a C :c:type:`unsigned short int` to a Python integer object.

   ``I`` (integer/long) [unsigned int]
      Convert a C :c:type:`unsigned int` to a Python integer object or a Python
      long integer object, if it is larger than ``sys.maxint``.

   ``k`` (integer/long) [unsigned long]
      Convert a C :c:type:`unsigned long` to a Python integer object or a
      Python long integer object, if it is larger than ``sys.maxint``.

   ``L`` (long) [PY_LONG_LONG]
      Convert a C :c:type:`long long` to a Python long integer object. Only
      available on platforms that support :c:type:`long long`.

   ``K`` (long) [unsigned PY_LONG_LONG]
      Convert a C :c:type:`unsigned long long` to a Python long integer object.
      Only available on platforms that support :c:type:`unsigned long long`.

   ``n`` (int) [Py_ssize_t]
      Convert a C :c:type:`Py_ssize_t` to a Python integer or long integer.

      .. versionadded:: 2.5

   ``c`` (string of length 1) [char]
      Convert a C :c:type:`int` representing a character to a Python string of
      length 1.

   ``d`` (float) [double]
      Convert a C :c:type:`double` to a Python floating point number.

   ``f`` (float) [float]
      Same as ``d``.

   ``D`` (complex) [Py_complex \*]
      Convert a C :c:type:`Py_complex` structure to a Python complex number.

   ``O`` (object) [PyObject \*]
      Pass a Python object untouched (except for its reference count, which is
      incremented by one).  If the object passed in is a *NULL* pointer, it is
      assumed that this was caused because the call producing the argument
      found an error and set an exception. Therefore, :c:func:`Py_BuildValue`
      will return *NULL* but won't raise an exception.  If no exception has
      been raised yet, :exc:`SystemError` is set.

   ``S`` (object) [PyObject \*]
      Same as ``O``.

   ``N`` (object) [PyObject \*]
      Same as ``O``, except it doesn't increment the reference count on the
      object.  Useful when the object is created by a call to an object
      constructor in the argument list.

   ``O&`` (object) [*converter*, *anything*]
      Convert *anything* to a Python object through a *converter* function.
      The function is called with *anything* (which should be compatible with
      :c:type:`void \*`) as its argument and should return a "new" Python
      object, or *NULL* if an error occurred.

   ``(items)`` (tuple) [*matching-items*]
      Convert a sequence of C values to a Python tuple with the same number of
      items.

   ``[items]`` (list) [*matching-items*]
      Convert a sequence of C values to a Python list with the same number of
      items.

   ``{items}`` (dictionary) [*matching-items*]
      Convert a sequence of C values to a Python dictionary.  Each pair of
      consecutive C values adds one item to the dictionary, serving as key and
      value, respectively.

   If there is an error in the format string, the :exc:`SystemError` exception
   is set and *NULL* returned.

.. c:function:: PyObject* Py_VaBuildValue(const char *format, va_list vargs)

   Identical to :c:func:`Py_BuildValue`, except that it accepts a va_list
   rather than a variable number of arguments.
PK	%�\
��2 html/_sources/c-api/bool.rst.txtnu�[���.. highlightlang:: c

.. _boolobjects:

Boolean Objects
---------------

Booleans in Python are implemented as a subclass of integers.  There are only
two booleans, :const:`Py_False` and :const:`Py_True`.  As such, the normal
creation and deletion functions don't apply to booleans.  The following macros
are available, however.


.. c:function:: int PyBool_Check(PyObject *o)

   Return true if *o* is of type :c:data:`PyBool_Type`.

   .. versionadded:: 2.3


.. c:var:: PyObject* Py_False

   The Python ``False`` object.  This object has no methods.  It needs to be
   treated just like any other object with respect to reference counts.


.. c:var:: PyObject* Py_True

   The Python ``True`` object.  This object has no methods.  It needs to be treated
   just like any other object with respect to reference counts.


.. c:macro:: Py_RETURN_FALSE

   Return :const:`Py_False` from a function, properly incrementing its reference
   count.

   .. versionadded:: 2.4


.. c:macro:: Py_RETURN_TRUE

   Return :const:`Py_True` from a function, properly incrementing its reference
   count.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyBool_FromLong(long v)

   Return a new reference to :const:`Py_True` or :const:`Py_False` depending on the
   truth value of *v*.

   .. versionadded:: 2.3
PK	%�\�Wf�Y�Y"html/_sources/c-api/buffer.rst.txtnu�[���.. highlightlang:: c

.. _bufferobjects:

Buffers and Memoryview Objects
------------------------------

.. sectionauthor:: Greg Stein <gstein@lyra.org>
.. sectionauthor:: Benjamin Peterson


.. index::
   object: buffer
   single: buffer interface

Python objects implemented in C can export a group of functions called the
"buffer interface."  These functions can be used by an object to expose its
data in a raw, byte-oriented format. Clients of the object can use the buffer
interface to access the object data directly, without needing to copy it
first.

Two examples of objects that support the buffer interface are strings and
arrays. The string object exposes the character contents in the buffer
interface's byte-oriented form. An array can only expose its contents via the
old-style buffer interface. This limitation does not apply to Python 3,
where :class:`memoryview` objects can be constructed from arrays, too.
Array elements may be multi-byte values.

An example user of the buffer interface is the file object's :meth:`write`
method. Any object that can export a series of bytes through the buffer
interface can be written to a file. There are a number of format codes to
:c:func:`PyArg_ParseTuple` that operate against an object's buffer interface,
returning data from the target object.

Starting from version 1.6, Python has been providing Python-level buffer
objects and a C-level buffer API so that any built-in or used-defined type can
expose its characteristics. Both, however, have been deprecated because of
various shortcomings, and have been officially removed in Python 3 in favour
of a new C-level buffer API and a new Python-level object named
:class:`memoryview`.

The new buffer API has been backported to Python 2.6, and the
:class:`memoryview` object has been backported to Python 2.7. It is strongly
advised to use them rather than the old APIs, unless you are blocked from
doing so for compatibility reasons.


The new-style Py_buffer struct
==============================


.. c:type:: Py_buffer

   .. c:member:: void *buf

      A pointer to the start of the memory for the object.

   .. c:member:: Py_ssize_t len
      :noindex:

      The total length of the memory in bytes.

   .. c:member:: int readonly

      An indicator of whether the buffer is read only.

   .. c:member:: const char *format
      :noindex:

      A *NULL* terminated string in :mod:`struct` module style syntax giving
      the contents of the elements available through the buffer.  If this is
      *NULL*, ``"B"`` (unsigned bytes) is assumed.

   .. c:member:: int ndim

      The number of dimensions the memory represents as a multi-dimensional
      array.  If it is ``0``, :c:data:`strides` and :c:data:`suboffsets` must be
      *NULL*.

   .. c:member:: Py_ssize_t *shape

      An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the
      shape of the memory as a multi-dimensional array.  Note that
      ``((*shape)[0] * ... * (*shape)[ndims-1])*itemsize`` should be equal to
      :c:data:`len`.

   .. c:member:: Py_ssize_t *strides

      An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim` giving the
      number of bytes to skip to get to a new element in each dimension.

   .. c:member:: Py_ssize_t *suboffsets

      An array of :c:type:`Py_ssize_t`\s the length of :c:data:`ndim`.  If these
      suboffset numbers are greater than or equal to 0, then the value stored
      along the indicated dimension is a pointer and the suboffset value
      dictates how many bytes to add to the pointer after de-referencing. A
      suboffset value that it negative indicates that no de-referencing should
      occur (striding in a contiguous memory block).

      If all suboffsets are negative (i.e. no de-referencing is needed), then
      this field must be NULL (the default value).

      Here is a function that returns a pointer to the element in an N-D array
      pointed to by an N-dimensional index when there are both non-NULL strides
      and suboffsets::

          void *get_item_pointer(int ndim, void *buf, Py_ssize_t *strides,
              Py_ssize_t *suboffsets, Py_ssize_t *indices) {
              char *pointer = (char*)buf;
              int i;
              for (i = 0; i < ndim; i++) {
                  pointer += strides[i] * indices[i];
                  if (suboffsets[i] >=0 ) {
                      pointer = *((char**)pointer) + suboffsets[i];
                  }
              }
              return (void*)pointer;
           }


   .. c:member:: Py_ssize_t itemsize

      This is a storage for the itemsize (in bytes) of each element of the
      shared memory. It is technically un-necessary as it can be obtained
      using :c:func:`PyBuffer_SizeFromFormat`, however an exporter may know
      this information without parsing the format string and it is necessary
      to know the itemsize for proper interpretation of striding. Therefore,
      storing it is more convenient and faster.

   .. c:member:: void *internal

      This is for use internally by the exporting object. For example, this
      might be re-cast as an integer by the exporter and used to store flags
      about whether or not the shape, strides, and suboffsets arrays must be
      freed when the buffer is released. The consumer should never alter this
      value.


Buffer related functions
========================


.. c:function:: int PyObject_CheckBuffer(PyObject *obj)

   Return ``1`` if *obj* supports the buffer interface otherwise ``0``.


.. c:function:: int PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)

      Export *obj* into a :c:type:`Py_buffer`, *view*.  These arguments must
      never be *NULL*.  The *flags* argument is a bit field indicating what
      kind of buffer the caller is prepared to deal with and therefore what
      kind of buffer the exporter is allowed to return.  The buffer interface
      allows for complicated memory sharing possibilities, but some caller may
      not be able to handle all the complexity but may want to see if the
      exporter will let them take a simpler view to its memory.

      Some exporters may not be able to share memory in every possible way and
      may need to raise errors to signal to some consumers that something is
      just not possible. These errors should be a :exc:`BufferError` unless
      there is another error that is actually causing the problem. The
      exporter can use flags information to simplify how much of the
      :c:data:`Py_buffer` structure is filled in with non-default values and/or
      raise an error if the object can't support a simpler view of its memory.

      ``0`` is returned on success and ``-1`` on error.

      The following table gives possible values to the *flags* arguments.

      +-------------------------------+---------------------------------------------------+
      | Flag                          | Description                                       |
      +===============================+===================================================+
      | :c:macro:`PyBUF_SIMPLE`       | This is the default flag state.  The returned     |
      |                               | buffer may or may not have writable memory.  The  |
      |                               | format of the data will be assumed to be unsigned |
      |                               | bytes.  This is a "stand-alone" flag constant. It |
      |                               | never needs to be '|'d to the others. The exporter|
      |                               | will raise an error if it cannot provide such a   |
      |                               | contiguous buffer of bytes.                       |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_WRITABLE`     | The returned buffer must be writable.  If it is   |
      |                               | not writable, then raise an error.                |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_STRIDES`      | This implies :c:macro:`PyBUF_ND`. The returned    |
      |                               | buffer must provide strides information (i.e. the |
      |                               | strides cannot be NULL). This would be used when  |
      |                               | the consumer can handle strided, discontiguous    |
      |                               | arrays.  Handling strides automatically assumes   |
      |                               | you can handle shape.  The exporter can raise an  |
      |                               | error if a strided representation of the data is  |
      |                               | not possible (i.e. without the suboffsets).       |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_ND`           | The returned buffer must provide shape            |
      |                               | information. The memory will be assumed C-style   |
      |                               | contiguous (last dimension varies the             |
      |                               | fastest). The exporter may raise an error if it   |
      |                               | cannot provide this kind of contiguous buffer. If |
      |                               | this is not given then shape will be *NULL*.      |
      |                               |                                                   |
      |                               |                                                   |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      |:c:macro:`PyBUF_C_CONTIGUOUS`  | These flags indicate that the contiguity returned |
      |:c:macro:`PyBUF_F_CONTIGUOUS`  | buffer must be respectively, C-contiguous (last   |
      |:c:macro:`PyBUF_ANY_CONTIGUOUS`| dimension varies the fastest), Fortran contiguous |
      |                               | (first dimension varies the fastest) or either    |
      |                               | one.  All of these flags imply                    |
      |                               | :c:macro:`PyBUF_STRIDES` and guarantee that the   |
      |                               | strides buffer info structure will be filled in   |
      |                               | correctly.                                        |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_INDIRECT`     | This flag indicates the returned buffer must have |
      |                               | suboffsets information (which can be NULL if no   |
      |                               | suboffsets are needed).  This can be used when    |
      |                               | the consumer can handle indirect array            |
      |                               | referencing implied by these suboffsets. This     |
      |                               | implies :c:macro:`PyBUF_STRIDES`.                 |
      |                               |                                                   |
      |                               |                                                   |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_FORMAT`       | The returned buffer must have true format         |
      |                               | information if this flag is provided. This would  |
      |                               | be used when the consumer is going to be checking |
      |                               | for what 'kind' of data is actually stored. An    |
      |                               | exporter should always be able to provide this    |
      |                               | information if requested. If format is not        |
      |                               | explicitly requested then the format must be      |
      |                               | returned as *NULL* (which means ``'B'``, or       |
      |                               | unsigned bytes)                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_STRIDED`      | This is equivalent to ``(PyBUF_STRIDES |          |
      |                               | PyBUF_WRITABLE)``.                                |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_STRIDED_RO`   | This is equivalent to ``(PyBUF_STRIDES)``.        |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_RECORDS`      | This is equivalent to ``(PyBUF_STRIDES |          |
      |                               | PyBUF_FORMAT | PyBUF_WRITABLE)``.                 |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_RECORDS_RO`   | This is equivalent to ``(PyBUF_STRIDES |          |
      |                               | PyBUF_FORMAT)``.                                  |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_FULL`         | This is equivalent to ``(PyBUF_INDIRECT |         |
      |                               | PyBUF_FORMAT | PyBUF_WRITABLE)``.                 |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_FULL_RO`      | This is equivalent to ``(PyBUF_INDIRECT |         |
      |                               | PyBUF_FORMAT)``.                                  |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_CONTIG`       | This is equivalent to ``(PyBUF_ND |               |
      |                               | PyBUF_WRITABLE)``.                                |
      +-------------------------------+---------------------------------------------------+
      | :c:macro:`PyBUF_CONTIG_RO`    | This is equivalent to ``(PyBUF_ND)``.             |
      |                               |                                                   |
      +-------------------------------+---------------------------------------------------+


.. c:function:: void PyBuffer_Release(Py_buffer *view)

   Release the buffer *view*.  This should be called when the buffer
   is no longer being used as it may free memory from it.


.. c:function:: Py_ssize_t PyBuffer_SizeFromFormat(const char *)

   Return the implied :c:data:`~Py_buffer.itemsize` from the struct-stype
   :c:data:`~Py_buffer.format`.


.. c:function:: int PyBuffer_IsContiguous(Py_buffer *view, char fortran)

   Return ``1`` if the memory defined by the *view* is C-style (*fortran* is
   ``'C'``) or Fortran-style (*fortran* is ``'F'``) contiguous or either one
   (*fortran* is ``'A'``).  Return ``0`` otherwise.


.. c:function:: void PyBuffer_FillContiguousStrides(int ndims, Py_ssize_t *shape, Py_ssize_t *strides, int itemsize, char fortran)

   Fill the *strides* array with byte-strides of a contiguous (C-style if
   *fortran* is ``'C'`` or Fortran-style if *fortran* is ``'F'``) array of the
   given shape with the given number of bytes per element.


.. c:function:: int PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len, int readonly, int infoflags)

   Fill in a buffer-info structure, *view*, correctly for an exporter that can
   only share a contiguous chunk of memory of "unsigned bytes" of the given
   length.  Return ``0`` on success and ``-1`` (with raising an error) on error.


MemoryView objects
==================

.. versionadded:: 2.7

A :class:`memoryview` object exposes the new C level buffer interface as a
Python object which can then be passed around like any other object.

.. c:function:: PyObject *PyMemoryView_FromObject(PyObject *obj)

   Create a memoryview object from an object that defines the new buffer
   interface.


.. c:function:: PyObject *PyMemoryView_FromBuffer(Py_buffer *view)

   Create a memoryview object wrapping the given buffer-info structure *view*.
   The memoryview object then owns the buffer, which means you shouldn't
   try to release it yourself: it will be released on deallocation of the
   memoryview object.


.. c:function:: PyObject *PyMemoryView_GetContiguous(PyObject *obj, int buffertype, char order)

   Create a memoryview object to a contiguous chunk of memory (in either
   'C' or 'F'ortran *order*) from an object that defines the buffer
   interface. If memory is contiguous, the memoryview object points to the
   original memory. Otherwise copy is made and the memoryview points to a
   new bytes object.


.. c:function:: int PyMemoryView_Check(PyObject *obj)

   Return true if the object *obj* is a memoryview object.  It is not
   currently allowed to create subclasses of :class:`memoryview`.


.. c:function:: Py_buffer *PyMemoryView_GET_BUFFER(PyObject *obj)

   Return a pointer to the buffer-info structure wrapped by the given
   object.  The object **must** be a memoryview instance; this macro doesn't
   check its type, you must do it yourself or you will risk crashes.


Old-style buffer objects
========================

.. index:: single: PyBufferProcs

More information on the old buffer interface is provided in the section
:ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`.

A "buffer object" is defined in the :file:`bufferobject.h` header (included by
:file:`Python.h`). These objects look very similar to string objects at the
Python programming level: they support slicing, indexing, concatenation, and
some other standard string operations. However, their data can come from one
of two sources: from a block of memory, or from another object which exports
the buffer interface.

Buffer objects are useful as a way to expose the data from another object's
buffer interface to the Python programmer. They can also be used as a
zero-copy slicing mechanism. Using their ability to reference a block of
memory, it is possible to expose any data to the Python programmer quite
easily. The memory could be a large, constant array in a C extension, it could
be a raw block of memory for manipulation before passing to an operating
system library, or it could be used to pass around structured data in its
native, in-memory format.


.. c:type:: PyBufferObject

   This subtype of :c:type:`PyObject` represents a buffer object.


.. c:var:: PyTypeObject PyBuffer_Type

   .. index:: single: BufferType (in module types)

   The instance of :c:type:`PyTypeObject` which represents the Python buffer type;
   it is the same object as ``buffer`` and  ``types.BufferType`` in the Python
   layer. .


.. c:var:: int Py_END_OF_BUFFER

   This constant may be passed as the *size* parameter to
   :c:func:`PyBuffer_FromObject` or :c:func:`PyBuffer_FromReadWriteObject`.  It
   indicates that the new :c:type:`PyBufferObject` should refer to *base*
   object from the specified *offset* to the end of its exported buffer.
   Using this enables the caller to avoid querying the *base* object for its
   length.


.. c:function:: int PyBuffer_Check(PyObject *p)

   Return true if the argument has type :c:data:`PyBuffer_Type`.


.. c:function:: PyObject* PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)

   Return a new read-only buffer object.  This raises :exc:`TypeError` if
   *base* doesn't support the read-only buffer protocol or doesn't provide
   exactly one buffer segment, or it raises :exc:`ValueError` if *offset* is
   less than zero.  The buffer will hold a reference to the *base* object, and
   the buffer's contents will refer to the *base* object's buffer interface,
   starting as position *offset* and extending for *size* bytes. If *size* is
   :const:`Py_END_OF_BUFFER`, then the new buffer's contents extend to the
   length of the *base* object's exported buffer data.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *offset* and *size*. This
      might require changes in your code for properly supporting 64-bit
      systems.


.. c:function:: PyObject* PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)

   Return a new writable buffer object.  Parameters and exceptions are similar
   to those for :c:func:`PyBuffer_FromObject`.  If the *base* object does not
   export the writeable buffer protocol, then :exc:`TypeError` is raised.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *offset* and *size*. This
      might require changes in your code for properly supporting 64-bit
      systems.


.. c:function:: PyObject* PyBuffer_FromMemory(void *ptr, Py_ssize_t size)

   Return a new read-only buffer object that reads from a specified location
   in memory, with a specified size.  The caller is responsible for ensuring
   that the memory buffer, passed in as *ptr*, is not deallocated while the
   returned buffer object exists.  Raises :exc:`ValueError` if *size* is less
   than zero.  Note that :const:`Py_END_OF_BUFFER` may *not* be passed for the
   *size* parameter; :exc:`ValueError` will be raised in that case.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)

   Similar to :c:func:`PyBuffer_FromMemory`, but the returned buffer is
   writable.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: PyObject* PyBuffer_New(Py_ssize_t size)

   Return a new writable buffer object that maintains its own memory buffer of
   *size* bytes.  :exc:`ValueError` is returned if *size* is not zero or
   positive.  Note that the memory buffer (as returned by
   :c:func:`PyObject_AsWriteBuffer`) is not specifically aligned.

   .. versionchanged:: 2.5
      This function used an :c:type:`int` type for *size*. This might require
      changes in your code for properly supporting 64-bit systems.
PK	%�\D��T��%html/_sources/c-api/bytearray.rst.txtnu�[���.. highlightlang:: c

.. _bytearrayobjects:

Byte Array Objects
------------------

.. index:: object: bytearray

.. versionadded:: 2.6


.. c:type:: PyByteArrayObject

   This subtype of :c:type:`PyObject` represents a Python bytearray object.


.. c:var:: PyTypeObject PyByteArray_Type

   This instance of :c:type:`PyTypeObject` represents the Python bytearray type;
   it is the same object as ``bytearray`` in the Python layer.

Type check macros
^^^^^^^^^^^^^^^^^

.. c:function:: int PyByteArray_Check(PyObject *o)

   Return true if the object *o* is a bytearray object or an instance of a
   subtype of the bytearray type.


.. c:function:: int PyByteArray_CheckExact(PyObject *o)

   Return true if the object *o* is a bytearray object, but not an instance of a
   subtype of the bytearray type.


Direct API functions
^^^^^^^^^^^^^^^^^^^^

.. c:function:: PyObject* PyByteArray_FromObject(PyObject *o)

   Return a new bytearray object from any object, *o*, that implements the
   buffer protocol.

   .. XXX expand about the buffer protocol, at least somewhere


.. c:function:: PyObject* PyByteArray_FromStringAndSize(const char *string, Py_ssize_t len)

   Create a new bytearray object from *string* and its length, *len*.  On
   failure, *NULL* is returned.


.. c:function:: PyObject* PyByteArray_Concat(PyObject *a, PyObject *b)

   Concat bytearrays *a* and *b* and return a new bytearray with the result.


.. c:function:: Py_ssize_t PyByteArray_Size(PyObject *bytearray)

   Return the size of *bytearray* after checking for a *NULL* pointer.


.. c:function:: char* PyByteArray_AsString(PyObject *bytearray)

   Return the contents of *bytearray* as a char array after checking for a
   *NULL* pointer.


.. c:function:: int PyByteArray_Resize(PyObject *bytearray, Py_ssize_t len)

   Resize the internal buffer of *bytearray* to *len*.

Macros
^^^^^^

These macros trade safety for speed and they don't check pointers.

.. c:function:: char* PyByteArray_AS_STRING(PyObject *bytearray)

   Macro version of :c:func:`PyByteArray_AsString`.


.. c:function:: Py_ssize_t PyByteArray_GET_SIZE(PyObject *bytearray)

   Macro version of :c:func:`PyByteArray_Size`.
PK	%�\�
�mmm#html/_sources/c-api/capsule.rst.txtnu�[���.. highlightlang:: c

.. _capsules:

Capsules
--------

.. index:: object: Capsule

Refer to :ref:`using-capsules` for more information on using these objects.

.. versionadded:: 2.7


.. c:type:: PyCapsule

   This subtype of :c:type:`PyObject` represents an opaque value, useful for C
   extension modules who need to pass an opaque value (as a :c:type:`void\*`
   pointer) through Python code to other C code.  It is often used to make a C
   function pointer defined in one module available to other modules, so the
   regular import mechanism can be used to access C APIs defined in dynamically
   loaded modules.


.. c:type:: PyCapsule_Destructor

   The type of a destructor callback for a capsule.  Defined as::

      typedef void (*PyCapsule_Destructor)(PyObject *);

   See :c:func:`PyCapsule_New` for the semantics of PyCapsule_Destructor
   callbacks.


.. c:function:: int PyCapsule_CheckExact(PyObject *p)

   Return true if its argument is a :c:type:`PyCapsule`.


.. c:function:: PyObject* PyCapsule_New(void *pointer, const char *name, PyCapsule_Destructor destructor)

   Create a :c:type:`PyCapsule` encapsulating the *pointer*.  The *pointer*
   argument may not be *NULL*.

   On failure, set an exception and return *NULL*.

   The *name* string may either be *NULL* or a pointer to a valid C string.  If
   non-*NULL*, this string must outlive the capsule.  (Though it is permitted to
   free it inside the *destructor*.)

   If the *destructor* argument is not *NULL*, it will be called with the
   capsule as its argument when it is destroyed.

   If this capsule will be stored as an attribute of a module, the *name* should
   be specified as ``modulename.attributename``.  This will enable other modules
   to import the capsule using :c:func:`PyCapsule_Import`.


.. c:function:: void* PyCapsule_GetPointer(PyObject *capsule, const char *name)

   Retrieve the *pointer* stored in the capsule.  On failure, set an exception
   and return *NULL*.

   The *name* parameter must compare exactly to the name stored in the capsule.
   If the name stored in the capsule is *NULL*, the *name* passed in must also
   be *NULL*.  Python uses the C function :c:func:`strcmp` to compare capsule
   names.


.. c:function:: PyCapsule_Destructor PyCapsule_GetDestructor(PyObject *capsule)

   Return the current destructor stored in the capsule.  On failure, set an
   exception and return *NULL*.

   It is legal for a capsule to have a *NULL* destructor.  This makes a *NULL*
   return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or
   :c:func:`PyErr_Occurred` to disambiguate.


.. c:function:: void* PyCapsule_GetContext(PyObject *capsule)

   Return the current context stored in the capsule.  On failure, set an
   exception and return *NULL*.

   It is legal for a capsule to have a *NULL* context.  This makes a *NULL*
   return code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or
   :c:func:`PyErr_Occurred` to disambiguate.


.. c:function:: const char* PyCapsule_GetName(PyObject *capsule)

   Return the current name stored in the capsule.  On failure, set an exception
   and return *NULL*.

   It is legal for a capsule to have a *NULL* name.  This makes a *NULL* return
   code somewhat ambiguous; use :c:func:`PyCapsule_IsValid` or
   :c:func:`PyErr_Occurred` to disambiguate.


.. c:function:: void* PyCapsule_Import(const char *name, int no_block)

   Import a pointer to a C object from a capsule attribute in a module.  The
   *name* parameter should specify the full name to the attribute, as in
   ``module.attribute``.  The *name* stored in the capsule must match this
   string exactly.  If *no_block* is true, import the module without blocking
   (using :c:func:`PyImport_ImportModuleNoBlock`).  If *no_block* is false,
   import the module conventionally (using :c:func:`PyImport_ImportModule`).

   Return the capsule's internal *pointer* on success.  On failure, set an
   exception and return *NULL*.


.. c:function:: int PyCapsule_IsValid(PyObject *capsule, const char *name)

   Determines whether or not *capsule* is a valid capsule.  A valid capsule is
   non-*NULL*, passes :c:func:`PyCapsule_CheckExact`, has a non-*NULL* pointer
   stored in it, and its internal name matches the *name* parameter.  (See
   :c:func:`PyCapsule_GetPointer` for information on how capsule names are
   compared.)

   In other words, if :c:func:`PyCapsule_IsValid` returns a true value, calls to
   any of the accessors (any function starting with :c:func:`PyCapsule_Get`) are
   guaranteed to succeed.

   Return a nonzero value if the object is valid and matches the name passed in.
   Return ``0`` otherwise.  This function will not fail.


.. c:function:: int PyCapsule_SetContext(PyObject *capsule, void *context)

   Set the context pointer inside *capsule* to *context*.

   Return ``0`` on success.  Return nonzero and set an exception on failure.


.. c:function:: int PyCapsule_SetDestructor(PyObject *capsule, PyCapsule_Destructor destructor)

   Set the destructor inside *capsule* to *destructor*.

   Return ``0`` on success.  Return nonzero and set an exception on failure.


.. c:function:: int PyCapsule_SetName(PyObject *capsule, const char *name)

   Set the name inside *capsule* to *name*.  If non-*NULL*, the name must
   outlive the capsule.  If the previous *name* stored in the capsule was not
   *NULL*, no attempt is made to free it.

   Return ``0`` on success.  Return nonzero and set an exception on failure.


.. c:function:: int PyCapsule_SetPointer(PyObject *capsule, void *pointer)

   Set the void pointer inside *capsule* to *pointer*.  The pointer may not be
   *NULL*.

   Return ``0`` on success.  Return nonzero and set an exception on failure.
PK	%�\mʼW�� html/_sources/c-api/cell.rst.txtnu�[���.. highlightlang:: c

.. _cell-objects:

Cell Objects
------------

"Cell" objects are used to implement variables referenced by multiple scopes.
For each such variable, a cell object is created to store the value; the local
variables of each stack frame that references the value contains a reference to
the cells from outer scopes which also use that variable.  When the value is
accessed, the value contained in the cell is used instead of the cell object
itself.  This de-referencing of the cell object requires support from the
generated byte-code; these are not automatically de-referenced when accessed.
Cell objects are not likely to be useful elsewhere.


.. c:type:: PyCellObject

   The C structure used for cell objects.


.. c:var:: PyTypeObject PyCell_Type

   The type object corresponding to cell objects.


.. c:function:: int PyCell_Check(ob)

   Return true if *ob* is a cell object; *ob* must not be *NULL*.


.. c:function:: PyObject* PyCell_New(PyObject *ob)

   Create and return a new cell object containing the value *ob*. The parameter may
   be *NULL*.


.. c:function:: PyObject* PyCell_Get(PyObject *cell)

   Return the contents of the cell *cell*.


.. c:function:: PyObject* PyCell_GET(PyObject *cell)

   Return the contents of the cell *cell*, but without checking that *cell* is
   non-*NULL* and a cell object.


.. c:function:: int PyCell_Set(PyObject *cell, PyObject *value)

   Set the contents of the cell object *cell* to *value*.  This releases the
   reference to any current content of the cell. *value* may be *NULL*.  *cell*
   must be non-*NULL*; if it is not a cell object, ``-1`` will be returned.  On
   success, ``0`` will be returned.


.. c:function:: void PyCell_SET(PyObject *cell, PyObject *value)

   Sets the value of the cell object *cell* to *value*.  No reference counts are
   adjusted, and no checks are made for safety; *cell* must be non-*NULL* and must
   be a cell object.
PK	%�\��?JJ!html/_sources/c-api/class.rst.txtnu�[���.. highlightlang:: c

.. _classobjects:

Class and Instance Objects
--------------------------

.. index:: object: class

Note that the class objects described here represent old-style classes, which
will go away in Python 3. When creating new types for extension modules, you
will want to work with type objects (section :ref:`typeobjects`).


.. c:type:: PyClassObject

   The C structure of the objects used to describe built-in classes.


.. c:var:: PyObject* PyClass_Type

   .. index:: single: ClassType (in module types)

   This is the type object for class objects; it is the same object as
   ``types.ClassType`` in the Python layer.


.. c:function:: int PyClass_Check(PyObject *o)

   Return true if the object *o* is a class object, including instances of types
   derived from the standard class object.  Return false in all other cases.


.. c:function:: int PyClass_IsSubclass(PyObject *klass, PyObject *base)

   Return true if *klass* is a subclass of *base*. Return false in all other cases.


.. index:: object: instance

There are very few functions specific to instance objects.


.. c:var:: PyTypeObject PyInstance_Type

   Type object for class instances.


.. c:function:: int PyInstance_Check(PyObject *obj)

   Return true if *obj* is an instance.


.. c:function:: PyObject* PyInstance_New(PyObject *class, PyObject *arg, PyObject *kw)

   Create a new instance of a specific class.  The parameters *arg* and *kw* are
   used as the positional and keyword parameters to the object's constructor.


.. c:function:: PyObject* PyInstance_NewRaw(PyObject *class, PyObject *dict)

   Create a new instance of a specific class without calling its constructor.
   *class* is the class of new object.  The *dict* parameter will be used as the
   object's :attr:`~object.__dict__`; if *NULL*, a new dictionary will be created for the
   instance.
PK	%�\��NN#html/_sources/c-api/cobject.rst.txtnu�[���.. highlightlang:: c

.. _cobjects:

CObjects
--------

.. index:: object: CObject


.. warning::

   The CObject API is deprecated as of Python 2.7.  Please switch to the new
   :ref:`capsules` API.

.. c:type:: PyCObject

   This subtype of :c:type:`PyObject` represents an opaque value, useful for C
   extension modules who need to pass an opaque value (as a :c:type:`void\*`
   pointer) through Python code to other C code.  It is often used to make a C
   function pointer defined in one module available to other modules, so the
   regular import mechanism can be used to access C APIs defined in dynamically
   loaded modules.


.. c:function:: int PyCObject_Check(PyObject *p)

   Return true if its argument is a :c:type:`PyCObject`.


.. c:function:: PyObject* PyCObject_FromVoidPtr(void* cobj, void (*destr)(void *))

   Create a :c:type:`PyCObject` from the ``void *`` *cobj*.  The *destr* function
   will be called when the object is reclaimed, unless it is *NULL*.


.. c:function:: PyObject* PyCObject_FromVoidPtrAndDesc(void* cobj, void* desc, void (*destr)(void *, void *))

   Create a :c:type:`PyCObject` from the :c:type:`void \*` *cobj*.  The *destr*
   function will be called when the object is reclaimed. The *desc* argument can
   be used to pass extra callback data for the destructor function.


.. c:function:: void* PyCObject_AsVoidPtr(PyObject* self)

   Return the object :c:type:`void \*` that the :c:type:`PyCObject` *self* was
   created with.


.. c:function:: void* PyCObject_GetDesc(PyObject* self)

   Return the description :c:type:`void \*` that the :c:type:`PyCObject` *self* was
   created with.


.. c:function:: int PyCObject_SetVoidPtr(PyObject* self, void* cobj)

   Set the void pointer inside *self* to *cobj*. The :c:type:`PyCObject` must not
   have an associated destructor. Return true on success, false on failure.
PK	%�\��l�cc html/_sources/c-api/code.rst.txtnu�[���.. highlightlang:: c

.. _codeobjects:

.. index:: object; code, code object

Code Objects
------------

.. sectionauthor:: Jeffrey Yasskin <jyasskin@gmail.com>

Code objects are a low-level detail of the CPython implementation.
Each one represents a chunk of executable code that hasn't yet been
bound into a function.

.. c:type:: PyCodeObject

   The C structure of the objects used to describe code objects.  The
   fields of this type are subject to change at any time.


.. c:var:: PyTypeObject PyCode_Type

   This is an instance of :c:type:`PyTypeObject` representing the Python
   :class:`code` type.


.. c:function:: int PyCode_Check(PyObject *co)

   Return true if *co* is a :class:`code` object.

.. c:function:: int PyCode_GetNumFree(PyObject *co)

   Return the number of free variables in *co*.

.. c:function:: PyCodeObject *PyCode_New(int argcount, int nlocals, int stacksize, int flags, PyObject *code, PyObject *consts, PyObject *names, PyObject *varnames, PyObject *freevars, PyObject *cellvars, PyObject *filename, PyObject *name, int firstlineno, PyObject *lnotab)

   Return a new code object.  If you need a dummy code object to
   create a frame, use :c:func:`PyCode_NewEmpty` instead.  Calling
   :c:func:`PyCode_New` directly can bind you to a precise Python
   version since the definition of the bytecode changes often.


.. c:function:: int PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)

   Return a new empty code object with the specified filename,
   function name, and first line number.  It is illegal to
   :keyword:`exec` or :func:`eval` the resulting code object.
PK	%�\|-�##!html/_sources/c-api/codec.rst.txtnu�[���.. _codec-registry:

Codec registry and support functions
====================================

.. c:function:: int PyCodec_Register(PyObject *search_function)

   Register a new codec search function.

   As side effect, this tries to load the :mod:`encodings` package, if not yet
   done, to make sure that it is always first in the list of search functions.

.. c:function:: int PyCodec_KnownEncoding(const char *encoding)

   Return ``1`` or ``0`` depending on whether there is a registered codec for
   the given *encoding*.

.. c:function:: PyObject* PyCodec_Encode(PyObject *object, const char *encoding, const char *errors)

   Generic codec based encoding API.

   *object* is passed through the encoder function found for the given
   *encoding* using the error handling method defined by *errors*.  *errors* may
   be *NULL* to use the default method defined for the codec.  Raises a
   :exc:`LookupError` if no encoder can be found.

.. c:function:: PyObject* PyCodec_Decode(PyObject *object, const char *encoding, const char *errors)

   Generic codec based decoding API.

   *object* is passed through the decoder function found for the given
   *encoding* using the error handling method defined by *errors*.  *errors* may
   be *NULL* to use the default method defined for the codec.  Raises a
   :exc:`LookupError` if no encoder can be found.


Codec lookup API
----------------

In the following functions, the *encoding* string is looked up converted to all
lower-case characters, which makes encodings looked up through this mechanism
effectively case-insensitive.  If no codec is found, a :exc:`KeyError` is set
and *NULL* returned.

.. c:function:: PyObject* PyCodec_Encoder(const char *encoding)

   Get an encoder function for the given *encoding*.

.. c:function:: PyObject* PyCodec_Decoder(const char *encoding)

   Get a decoder function for the given *encoding*.

.. c:function:: PyObject* PyCodec_IncrementalEncoder(const char *encoding, const char *errors)

   Get an :class:`~codecs.IncrementalEncoder` object for the given *encoding*.

.. c:function:: PyObject* PyCodec_IncrementalDecoder(const char *encoding, const char *errors)

   Get an :class:`~codecs.IncrementalDecoder` object for the given *encoding*.

.. c:function:: PyObject* PyCodec_StreamReader(const char *encoding, PyObject *stream, const char *errors)

   Get a :class:`~codecs.StreamReader` factory function for the given *encoding*.

.. c:function:: PyObject* PyCodec_StreamWriter(const char *encoding, PyObject *stream, const char *errors)

   Get a :class:`~codecs.StreamWriter` factory function for the given *encoding*.


Registry API for Unicode encoding error handlers
------------------------------------------------

.. c:function:: int PyCodec_RegisterError(const char *name, PyObject *error)

   Register the error handling callback function *error* under the given *name*.
   This callback function will be called by a codec when it encounters
   unencodable characters/undecodable bytes and *name* is specified as the error
   parameter in the call to the encode/decode function.

   The callback gets a single argument, an instance of
   :exc:`UnicodeEncodeError`, :exc:`UnicodeDecodeError` or
   :exc:`UnicodeTranslateError` that holds information about the problematic
   sequence of characters or bytes and their offset in the original string (see
   :ref:`unicodeexceptions` for functions to extract this information).  The
   callback must either raise the given exception, or return a two-item tuple
   containing the replacement for the problematic sequence, and an integer
   giving the offset in the original string at which encoding/decoding should be
   resumed.

   Return ``0`` on success, ``-1`` on error.

.. c:function:: PyObject* PyCodec_LookupError(const char *name)

   Lookup the error handling callback function registered under *name*.  As a
   special case *NULL* can be passed, in which case the error handling callback
   for "strict" will be returned.

.. c:function:: PyObject* PyCodec_StrictErrors(PyObject *exc)

   Raise *exc* as an exception.

.. c:function:: PyObject* PyCodec_IgnoreErrors(PyObject *exc)

   Ignore the unicode error, skipping the faulty input.

.. c:function:: PyObject* PyCodec_ReplaceErrors(PyObject *exc)

   Replace the unicode encode error with ``?`` or ``U+FFFD``.

.. c:function:: PyObject* PyCodec_XMLCharRefReplaceErrors(PyObject *exc)

   Replace the unicode encode error with XML character references.

.. c:function:: PyObject* PyCodec_BackslashReplaceErrors(PyObject *exc)

   Replace the unicode encode error with backslash escapes (``\x``, ``\u`` and
   ``\U``).

PK	%�\����#html/_sources/c-api/complex.rst.txtnu�[���.. highlightlang:: c

.. _complexobjects:

Complex Number Objects
----------------------

.. index:: object: complex number

Python's complex number objects are implemented as two distinct types when
viewed from the C API:  one is the Python object exposed to Python programs, and
the other is a C structure which represents the actual complex number value.
The API provides functions for working with both.


Complex Numbers as C Structures
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Note that the functions which accept these structures as parameters and return
them as results do so *by value* rather than dereferencing them through
pointers.  This is consistent throughout the API.


.. c:type:: Py_complex

   The C structure which corresponds to the value portion of a Python complex
   number object.  Most of the functions for dealing with complex number objects
   use structures of this type as input or output values, as appropriate.  It is
   defined as::

      typedef struct {
         double real;
         double imag;
      } Py_complex;


.. c:function:: Py_complex _Py_c_sum(Py_complex left, Py_complex right)

   Return the sum of two complex numbers, using the C :c:type:`Py_complex`
   representation.


.. c:function:: Py_complex _Py_c_diff(Py_complex left, Py_complex right)

   Return the difference between two complex numbers, using the C
   :c:type:`Py_complex` representation.


.. c:function:: Py_complex _Py_c_neg(Py_complex complex)

   Return the negation of the complex number *complex*, using the C
   :c:type:`Py_complex` representation.


.. c:function:: Py_complex _Py_c_prod(Py_complex left, Py_complex right)

   Return the product of two complex numbers, using the C :c:type:`Py_complex`
   representation.


.. c:function:: Py_complex _Py_c_quot(Py_complex dividend, Py_complex divisor)

   Return the quotient of two complex numbers, using the C :c:type:`Py_complex`
   representation.

   If *divisor* is null, this method returns zero and sets
   :c:data:`errno` to :c:data:`EDOM`.


.. c:function:: Py_complex _Py_c_pow(Py_complex num, Py_complex exp)

   Return the exponentiation of *num* by *exp*, using the C :c:type:`Py_complex`
   representation.

   If *num* is null and *exp* is not a positive real number,
   this method returns zero and sets :c:data:`errno` to :c:data:`EDOM`.


Complex Numbers as Python Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^


.. c:type:: PyComplexObject

   This subtype of :c:type:`PyObject` represents a Python complex number object.


.. c:var:: PyTypeObject PyComplex_Type

   This instance of :c:type:`PyTypeObject` represents the Python complex number
   type. It is the same object as ``complex`` and ``types.ComplexType``.


.. c:function:: int PyComplex_Check(PyObject *p)

   Return true if its argument is a :c:type:`PyComplexObject` or a subtype of
   :c:type:`PyComplexObject`.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyComplex_CheckExact(PyObject *p)

   Return true if its argument is a :c:type:`PyComplexObject`, but not a subtype of
   :c:type:`PyComplexObject`.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyComplex_FromCComplex(Py_complex v)

   Create a new Python complex number object from a C :c:type:`Py_complex` value.


.. c:function:: PyObject* PyComplex_FromDoubles(double real, double imag)

   Return a new :c:type:`PyComplexObject` object from *real* and *imag*.


.. c:function:: double PyComplex_RealAsDouble(PyObject *op)

   Return the real part of *op* as a C :c:type:`double`.


.. c:function:: double PyComplex_ImagAsDouble(PyObject *op)

   Return the imaginary part of *op* as a C :c:type:`double`.


.. c:function:: Py_complex PyComplex_AsCComplex(PyObject *op)

   Return the :c:type:`Py_complex` value of the complex number *op*.
   Upon failure, this method returns ``-1.0`` as a real value.

   .. versionchanged:: 2.6
      If *op* is not a Python complex number object but has a :meth:`__complex__`
      method, this method will first be called to convert *op* to a Python complex
      number object.
PK	%�\i��
��$html/_sources/c-api/concrete.rst.txtnu�[���.. highlightlang:: c


.. _concrete:

**********************
Concrete Objects Layer
**********************

The functions in this chapter are specific to certain Python object types.
Passing them an object of the wrong type is not a good idea; if you receive an
object from a Python program and you are not sure that it has the right type,
you must perform a type check first; for example, to check that an object is a
dictionary, use :c:func:`PyDict_Check`.  The chapter is structured like the
"family tree" of Python object types.

.. warning::

   While the functions described in this chapter carefully check the type of the
   objects which are passed in, many of them do not check for *NULL* being passed
   instead of a valid object.  Allowing *NULL* to be passed in can cause memory
   access violations and immediate termination of the interpreter.


.. _fundamental:

Fundamental Objects
===================

This section describes Python type objects and the singleton object ``None``.

.. toctree::

   type.rst
   none.rst


.. _numericobjects:

Numeric Objects
===============

.. index:: object: numeric

.. toctree::

   int.rst
   bool.rst
   long.rst
   float.rst
   complex.rst


.. _sequenceobjects:

Sequence Objects
================

.. index:: object: sequence

Generic operations on sequence objects were discussed in the previous chapter;
this section deals with the specific kinds of sequence objects that are
intrinsic to the Python language.

.. toctree::

   bytearray.rst
   string.rst
   unicode.rst
   buffer.rst
   tuple.rst
   list.rst


.. _mapobjects:

Mapping Objects
===============

.. index:: object: mapping

.. toctree::

   dict.rst


.. _otherobjects:

Other Objects
=============

.. toctree::

   class.rst
   function.rst
   method.rst
   file.rst
   module.rst
   iterator.rst
   descriptor.rst
   slice.rst
   weakref.rst
   capsule.rst
   cobject.rst
   cell.rst
   gen.rst
   datetime.rst
   set.rst
   code.rst
PK	%�\�0���&html/_sources/c-api/conversion.rst.txtnu�[���.. highlightlang:: c

.. _string-conversion:

String conversion and formatting
================================

Functions for number conversion and formatted string output.


.. c:function:: int PyOS_snprintf(char *str, size_t size,  const char *format, ...)

   Output not more than *size* bytes to *str* according to the format string
   *format* and the extra arguments. See the Unix man page :manpage:`snprintf(2)`.


.. c:function:: int PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)

   Output not more than *size* bytes to *str* according to the format string
   *format* and the variable argument list *va*. Unix man page
   :manpage:`vsnprintf(2)`.

:c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf` wrap the Standard C library
functions :c:func:`snprintf` and :c:func:`vsnprintf`. Their purpose is to
guarantee consistent behavior in corner cases, which the Standard C functions do
not.

The wrappers ensure that *str*[*size*-1] is always ``'\0'`` upon return. They
never write more than *size* bytes (including the trailing ``'\0'`` into str.
Both functions require that ``str != NULL``, ``size > 0`` and ``format !=
NULL``.

If the platform doesn't have :c:func:`vsnprintf` and the buffer size needed to
avoid truncation exceeds *size* by more than 512 bytes, Python aborts with a
*Py_FatalError*.

The return value (*rv*) for these functions should be interpreted as follows:

* When ``0 <= rv < size``, the output conversion was successful and *rv*
  characters were written to *str* (excluding the trailing ``'\0'`` byte at
  *str*[*rv*]).

* When ``rv >= size``, the output conversion was truncated and a buffer with
  ``rv + 1`` bytes would have been needed to succeed. *str*[*size*-1] is ``'\0'``
  in this case.

* When ``rv < 0``, "something bad happened." *str*[*size*-1] is ``'\0'`` in
  this case too, but the rest of *str* is undefined. The exact cause of the error
  depends on the underlying platform.

The following functions provide locale-independent string to number conversions.


.. c:function:: double PyOS_string_to_double(const char *s, char **endptr, PyObject *overflow_exception)

   Convert a string ``s`` to a :c:type:`double`, raising a Python
   exception on failure.  The set of accepted strings corresponds to
   the set of strings accepted by Python's :func:`float` constructor,
   except that ``s`` must not have leading or trailing whitespace.
   The conversion is independent of the current locale.

   If ``endptr`` is ``NULL``, convert the whole string.  Raise
   ValueError and return ``-1.0`` if the string is not a valid
   representation of a floating-point number.

   If endptr is not ``NULL``, convert as much of the string as
   possible and set ``*endptr`` to point to the first unconverted
   character.  If no initial segment of the string is the valid
   representation of a floating-point number, set ``*endptr`` to point
   to the beginning of the string, raise ValueError, and return
   ``-1.0``.

   If ``s`` represents a value that is too large to store in a float
   (for example, ``"1e500"`` is such a string on many platforms) then
   if ``overflow_exception`` is ``NULL`` return ``Py_HUGE_VAL`` (with
   an appropriate sign) and don't set any exception.  Otherwise,
   ``overflow_exception`` must point to a Python exception object;
   raise that exception and return ``-1.0``.  In both cases, set
   ``*endptr`` to point to the first character after the converted value.

   If any other error occurs during the conversion (for example an
   out-of-memory error), set the appropriate Python exception and
   return ``-1.0``.

   .. versionadded:: 2.7


.. c:function:: double PyOS_ascii_strtod(const char *nptr, char **endptr)

   Convert a string to a :c:type:`double`. This function behaves like the Standard C
   function :c:func:`strtod` does in the C locale. It does this without changing the
   current locale, since that would not be thread-safe.

   :c:func:`PyOS_ascii_strtod` should typically be used for reading configuration
   files or other non-user input that should be locale independent.

   See the Unix man page :manpage:`strtod(2)` for details.

   .. versionadded:: 2.4

   .. deprecated:: 2.7
      Use :c:func:`PyOS_string_to_double` instead.



.. c:function:: char* PyOS_ascii_formatd(char *buffer, size_t buf_len, const char *format, double d)

   Convert a :c:type:`double` to a string using the ``'.'`` as the decimal
   separator. *format* is a :c:func:`printf`\ -style format string specifying the
   number format. Allowed conversion characters are ``'e'``, ``'E'``, ``'f'``,
   ``'F'``, ``'g'`` and ``'G'``.

   The return value is a pointer to *buffer* with the converted string or NULL if
   the conversion failed.

   .. versionadded:: 2.4
   .. deprecated:: 2.7
      This function is removed in Python 2.7 and 3.1.  Use :func:`PyOS_double_to_string`
      instead.


.. c:function:: char* PyOS_double_to_string(double val, char format_code, int precision, int flags, int *ptype)

   Convert a :c:type:`double` *val* to a string using supplied
   *format_code*, *precision*, and *flags*.

   *format_code* must be one of ``'e'``, ``'E'``, ``'f'``, ``'F'``,
   ``'g'``, ``'G'`` or ``'r'``.  For ``'r'``, the supplied *precision*
   must be ``0`` and is ignored.  The ``'r'`` format code specifies the
   standard :func:`repr` format.

   *flags* can be zero or more of the values *Py_DTSF_SIGN*,
   *Py_DTSF_ADD_DOT_0*, or *Py_DTSF_ALT*, or-ed together:

   * *Py_DTSF_SIGN* means to always precede the returned string with a sign
     character, even if *val* is non-negative.

   * *Py_DTSF_ADD_DOT_0* means to ensure that the returned string will not look
     like an integer.

   * *Py_DTSF_ALT* means to apply "alternate" formatting rules.  See the
     documentation for the :c:func:`PyOS_snprintf` ``'#'`` specifier for
     details.

   If *ptype* is non-NULL, then the value it points to will be set to one of
   *Py_DTST_FINITE*, *Py_DTST_INFINITE*, or *Py_DTST_NAN*, signifying that
   *val* is a finite number, an infinite number, or not a number, respectively.

   The return value is a pointer to *buffer* with the converted string or
   *NULL* if the conversion failed. The caller is responsible for freeing the
   returned string by calling :c:func:`PyMem_Free`.

   .. versionadded:: 2.7


.. c:function:: double PyOS_ascii_atof(const char *nptr)

   Convert a string to a :c:type:`double` in a locale-independent way.

   See the Unix man page :manpage:`atof(2)` for details.

   .. versionadded:: 2.4

   .. deprecated:: 3.1
      Use :c:func:`PyOS_string_to_double` instead.


.. c:function:: char* PyOS_stricmp(char *s1, char *s2)

   Case insensitive comparison of strings. The function works almost
   identically to :c:func:`strcmp` except that it ignores the case.

   .. versionadded:: 2.6


.. c:function:: char* PyOS_strnicmp(char *s1, char *s2, Py_ssize_t  size)

   Case insensitive comparison of strings. The function works almost
   identically to :c:func:`strncmp` except that it ignores the case.

   .. versionadded:: 2.6
PK	%�\I�͖

$html/_sources/c-api/datetime.rst.txtnu�[���.. highlightlang:: c

.. _datetimeobjects:

DateTime Objects
----------------

Various date and time objects are supplied by the :mod:`datetime` module.
Before using any of these functions, the header file :file:`datetime.h` must be
included in your source (note that this is not included by :file:`Python.h`),
and the macro :c:macro:`PyDateTime_IMPORT` must be invoked, usually as part of
the module initialisation function.  The macro puts a pointer to a C structure
into a static variable, :c:data:`PyDateTimeAPI`, that is used by the following
macros.

Type-check macros:


.. c:function:: int PyDate_Check(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DateType` or a subtype of
   :c:data:`PyDateTime_DateType`.  *ob* must not be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyDate_CheckExact(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DateType`. *ob* must not be
   *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_Check(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType` or a subtype of
   :c:data:`PyDateTime_DateTimeType`.  *ob* must not be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_CheckExact(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DateTimeType`. *ob* must not
   be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyTime_Check(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_TimeType` or a subtype of
   :c:data:`PyDateTime_TimeType`.  *ob* must not be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyTime_CheckExact(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_TimeType`. *ob* must not be
   *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyDelta_Check(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DeltaType` or a subtype of
   :c:data:`PyDateTime_DeltaType`.  *ob* must not be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyDelta_CheckExact(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_DeltaType`. *ob* must not be
   *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyTZInfo_Check(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType` or a subtype of
   :c:data:`PyDateTime_TZInfoType`.  *ob* must not be *NULL*.

   .. versionadded:: 2.4


.. c:function:: int PyTZInfo_CheckExact(PyObject *ob)

   Return true if *ob* is of type :c:data:`PyDateTime_TZInfoType`. *ob* must not be
   *NULL*.

   .. versionadded:: 2.4

Macros to create objects:


.. c:function:: PyObject* PyDate_FromDate(int year, int month, int day)

   Return a ``datetime.date`` object with the specified year, month and day.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyDateTime_FromDateAndTime(int year, int month, int day, int hour, int minute, int second, int usecond)

   Return a ``datetime.datetime`` object with the specified year, month, day, hour,
   minute, second and microsecond.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyTime_FromTime(int hour, int minute, int second, int usecond)

   Return a ``datetime.time`` object with the specified hour, minute, second and
   microsecond.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyDelta_FromDSU(int days, int seconds, int useconds)

   Return a ``datetime.timedelta`` object representing the given number of days,
   seconds and microseconds.  Normalization is performed so that the resulting
   number of microseconds and seconds lie in the ranges documented for
   ``datetime.timedelta`` objects.

   .. versionadded:: 2.4

Macros to extract fields from date objects.  The argument must be an instance of
:c:data:`PyDateTime_Date`, including subclasses (such as
:c:data:`PyDateTime_DateTime`).  The argument must not be *NULL*, and the type is
not checked:


.. c:function:: int PyDateTime_GET_YEAR(PyDateTime_Date *o)

   Return the year, as a positive int.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_GET_MONTH(PyDateTime_Date *o)

   Return the month, as an int from 1 through 12.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_GET_DAY(PyDateTime_Date *o)

   Return the day, as an int from 1 through 31.

   .. versionadded:: 2.4

Macros to extract fields from datetime objects.  The argument must be an
instance of :c:data:`PyDateTime_DateTime`, including subclasses. The argument
must not be *NULL*, and the type is not checked:


.. c:function:: int PyDateTime_DATE_GET_HOUR(PyDateTime_DateTime *o)

   Return the hour, as an int from 0 through 23.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_DATE_GET_MINUTE(PyDateTime_DateTime *o)

   Return the minute, as an int from 0 through 59.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_DATE_GET_SECOND(PyDateTime_DateTime *o)

   Return the second, as an int from 0 through 59.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_DATE_GET_MICROSECOND(PyDateTime_DateTime *o)

   Return the microsecond, as an int from 0 through 999999.

   .. versionadded:: 2.4

Macros to extract fields from time objects.  The argument must be an instance of
:c:data:`PyDateTime_Time`, including subclasses. The argument must not be *NULL*,
and the type is not checked:


.. c:function:: int PyDateTime_TIME_GET_HOUR(PyDateTime_Time *o)

   Return the hour, as an int from 0 through 23.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_TIME_GET_MINUTE(PyDateTime_Time *o)

   Return the minute, as an int from 0 through 59.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_TIME_GET_SECOND(PyDateTime_Time *o)

   Return the second, as an int from 0 through 59.

   .. versionadded:: 2.4


.. c:function:: int PyDateTime_TIME_GET_MICROSECOND(PyDateTime_Time *o)

   Return the microsecond, as an int from 0 through 999999.

   .. versionadded:: 2.4

Macros for the convenience of modules implementing the DB API:


.. c:function:: PyObject* PyDateTime_FromTimestamp(PyObject *args)

   Create and return a new ``datetime.datetime`` object given an argument tuple
   suitable for passing to ``datetime.datetime.fromtimestamp()``.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyDate_FromTimestamp(PyObject *args)

   Create and return a new ``datetime.date`` object given an argument tuple
   suitable for passing to ``datetime.date.fromtimestamp()``.

   .. versionadded:: 2.4
PK	%�\�
��&html/_sources/c-api/descriptor.rst.txtnu�[���.. highlightlang:: c

.. _descriptor-objects:

Descriptor Objects
------------------

"Descriptors" are objects that describe some attribute of an object. They are
found in the dictionary of type objects.


.. c:var:: PyTypeObject PyProperty_Type

   The type object for the built-in descriptor types.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyDescr_NewGetSet(PyTypeObject *type, struct PyGetSetDef *getset)

   .. versionadded:: 2.2


.. c:function:: PyObject* PyDescr_NewMember(PyTypeObject *type, struct PyMemberDef *meth)

   .. versionadded:: 2.2


.. c:function:: PyObject* PyDescr_NewMethod(PyTypeObject *type, struct PyMethodDef *meth)

   .. versionadded:: 2.2


.. c:function:: PyObject* PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *wrapper, void *wrapped)

   .. versionadded:: 2.2


.. c:function:: PyObject* PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)

   .. versionadded:: 2.3


.. c:function:: int PyDescr_IsData(PyObject *descr)

   Return true if the descriptor objects *descr* describes a data attribute, or
   false if it describes a method.  *descr* must be a descriptor object; there is
   no error checking.

   .. versionadded:: 2.2


.. c:function:: PyObject* PyWrapper_New(PyObject *, PyObject *)

   .. versionadded:: 2.2
PK	%�\���MM html/_sources/c-api/dict.rst.txtnu�[���.. highlightlang:: c

.. _dictobjects:

Dictionary Objects
------------------

.. index:: object: dictionary


.. c:type:: PyDictObject

   This subtype of :c:type:`PyObject` represents a Python dictionary object.


.. c:var:: PyTypeObject PyDict_Type

   .. index::
      single: DictType (in module types)
      single: DictionaryType (in module types)

   This instance of :c:type:`PyTypeObject` represents the Python dictionary
   type.  This is exposed to Python programs as ``dict`` and
   ``types.DictType``.


.. c:function:: int PyDict_Check(PyObject *p)

   Return true if *p* is a dict object or an instance of a subtype of the dict
   type.

   .. versionchanged:: 2.2
      Allowed subtypes to be accepted.


.. c:function:: int PyDict_CheckExact(PyObject *p)

   Return true if *p* is a dict object, but not an instance of a subtype of
   the dict type.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyDict_New()

   Return a new empty dictionary, or *NULL* on failure.


.. c:function:: PyObject* PyDictProxy_New(PyObject *dict)

   Return a proxy object for a mapping which enforces read-only behavior.
   This is normally used to create a proxy to prevent modification of the
   dictionary for non-dynamic class types.

   .. versionadded:: 2.2


.. c:function:: void PyDict_Clear(PyObject *p)

   Empty an existing dictionary of all key-value pairs.


.. c:function:: int PyDict_Contains(PyObject *p, PyObject *key)

   Determine if dictionary *p* contains *key*.  If an item in *p* is matches
   *key*, return ``1``, otherwise return ``0``.  On error, return ``-1``.
   This is equivalent to the Python expression ``key in p``.

   .. versionadded:: 2.4


.. c:function:: PyObject* PyDict_Copy(PyObject *p)

   Return a new dictionary that contains the same key-value pairs as *p*.

   .. versionadded:: 1.6


.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)

   Insert *value* into the dictionary *p* with a key of *key*.  *key* must be
   :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return
   ``0`` on success or ``-1`` on failure.


.. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)

   .. index:: single: PyString_FromString()

   Insert *value* into the dictionary *p* using *key* as a key. *key* should
   be a :c:type:`char\*`.  The key object is created using
   ``PyString_FromString(key)``.  Return ``0`` on success or ``-1`` on
   failure.


.. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key)

   Remove the entry in dictionary *p* with key *key*. *key* must be hashable;
   if it isn't, :exc:`TypeError` is raised.  Return ``0`` on success or ``-1``
   on failure.


.. c:function:: int PyDict_DelItemString(PyObject *p, char *key)

   Remove the entry in dictionary *p* which has a key specified by the string
   *key*.  Return ``0`` on success or ``-1`` on failure.


.. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)

   Return the object from dictionary *p* which has a key *key*.  Return *NULL*
   if the key *key* is not present, but *without* setting an exception.


.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)

   This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a
   :c:type:`char\*`, rather than a :c:type:`PyObject\*`.


.. c:function:: PyObject* PyDict_Items(PyObject *p)

   Return a :c:type:`PyListObject` containing all the items from the
   dictionary, as in the dictionary method :meth:`dict.items`.


.. c:function:: PyObject* PyDict_Keys(PyObject *p)

   Return a :c:type:`PyListObject` containing all the keys from the dictionary,
   as in the dictionary method :meth:`dict.keys`.


.. c:function:: PyObject* PyDict_Values(PyObject *p)

   Return a :c:type:`PyListObject` containing all the values from the
   dictionary *p*, as in the dictionary method :meth:`dict.values`.


.. c:function:: Py_ssize_t PyDict_Size(PyObject *p)

   .. index:: builtin: len

   Return the number of items in the dictionary.  This is equivalent to
   ``len(p)`` on a dictionary.

   .. versionchanged:: 2.5
      This function returned an :c:type:`int` type.  This might require changes
      in your code for properly supporting 64-bit systems.


.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)

   Iterate over all key-value pairs in the dictionary *p*.  The
   :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0``
   prior to the first call to this function to start the iteration; the
   function returns true for each pair in the dictionary, and false once all
   pairs have been reported.  The parameters *pkey* and *pvalue* should either
   point to :c:type:`PyObject\*` variables that will be filled in with each key
   and value, respectively, or may be *NULL*.  Any references returned through
   them are borrowed.  *ppos* should not be altered during iteration. Its
   value represents offsets within the internal dictionary structure, and
   since the structure is sparse, the offsets are not consecutive.

   For example::

      PyObject *key, *value;
      Py_ssize_t pos = 0;

      while (PyDict_Next(self->dict, &pos, &key, &value)) {
          /* do something interesting with the values... */
          ...
      }

   The dictionary *p* should not be mutated during iteration.  It is safe
   (since Python 2.1) to modify the values of the keys as you iterate over the
   dictionary, but only so long as the set of keys does not change.  For
   example::

      PyObject *key, *value;
      Py_ssize_t pos = 0;

      while (PyDict_Next(self->dict, &pos, &key, &value)) {
          int i = PyInt_AS_LONG(value) + 1;
          PyObject *o = PyInt_FromLong(i);
          if (o == NULL)
              return -1;
          if (PyDict_SetItem(self->dict, key, o) < 0) {
              Py_DECREF(o);
              return -1;
          }
          Py_DECREF(o);
      }

   .. versionchanged:: 2.5
      This function used an :c:type:`int *` type for *ppos*. This might require
      changes in your code for properly supporting 64-bit systems.


.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override)

   Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
   *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys`
   and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
   will be replaced if a matching key is found in *b*, otherwise pairs will
   only be added if there is not a matching key in *a*. Return ``0`` on
   success or ``-1`` if an exception was raised.

   .. versionadded:: 2.2


.. c:function:: int PyDict_Update(PyObject *a, PyObject *b)

   This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to
   ``a.update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall
   back to the iterating over a sequence of key value pairs if the second
   argument has no "keys" attribute.  Return ``0`` on success or ``-1`` if an
   exception was raised.

   .. versionadded:: 2.2


.. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)

   Update or merge into dictionary *a*, from the key-value pairs in *seq2*.
   *seq2* must be an iterable object producing iterable objects of length 2,
   viewed as key-value pairs.  In case of duplicate keys, the last wins if
   *override* is true, else the first wins. Return ``0`` on success or ``-1``
   if an exception was raised. Equivalent Python (except for the return
   value)::

      def PyDict_MergeFromSeq2(a, seq2, override):
          for key, value in seq2:
              if override or key not in a:
                  a[key] = value

   .. versionadded:: 2.2
PK	%�\���ROO(html/_sources/distributing/index.rst.txtnu�[���.. _distributing-index:

###############################
  Distributing Python Modules
###############################

:Email: distutils-sig@python.org


As a popular open source development project, Python has an active
supporting community of contributors and users that also make their software
available for other Python developers to use under open source license terms.

This allows Python users to share and collaborate effectively, benefiting
from the solutions others have already created to common (and sometimes
even rare!) problems, as well as potentially contributing their own
solutions to the common pool.

This guide covers the distribution part of the process. For a guide to
installing other Python projects, refer to the
:ref:`installation guide <installing-index>`.

.. note::

   For corporate and other institutional users, be aware that many
   organisations have their own policies around using and contributing to
   open source software. Please take such policies into account when making
   use of the distribution and installation tools provided with Python.


Key terms
=========

* the `Python Packaging Index <https://pypi.org>`__ is a public
  repository of open source licensed packages made available for use by
  other Python users
* the `Python Packaging Authority
  <https://www.pypa.io/>`__ are the group of
  developers and documentation authors responsible for the maintenance and
  evolution of the standard packaging tools and the associated metadata and
  file format standards. They maintain a variety of tools, documentation
  and issue trackers on both `GitHub <https://github.com/pypa>`__ and
  `BitBucket <https://bitbucket.org/pypa/>`__.
* :mod:`distutils` is the original build and distribution system first added
  to the Python standard library in 1998. While direct use of :mod:`distutils`
  is being phased out, it still laid the foundation for the current packaging
  and distribution infrastructure, and it not only remains part of the
  standard library, but its name lives on in other ways (such as the name
  of the mailing list used to coordinate Python packaging standards
  development).
* `setuptools`_ is a (largely) drop-in replacement for :mod:`distutils` first
  published in 2004. Its most notable addition over the unmodified
  :mod:`distutils` tools was the ability to declare dependencies on other
  packages. It is currently recommended as a more regularly updated
  alternative to :mod:`distutils` that offers consistent support for more
  recent packaging standards across a wide range of Python versions.
* `wheel`_ (in this context) is a project that adds the ``bdist_wheel``
  command to :mod:`distutils`/`setuptools`_. This produces a cross platform
  binary packaging format (called "wheels" or "wheel files" and defined in
  :pep:`427`) that allows Python libraries, even those including binary
  extensions, to be installed on a system without needing to be built
  locally.

.. _setuptools: https://setuptools.readthedocs.io/en/latest/
.. _wheel: https://wheel.readthedocs.org

Open source licensing and collaboration
=======================================

In most parts of the world, software is automatically covered by copyright.
This means that other developers require explicit permission to copy, use,
modify and redistribute the software.

Open source licensing is a way of explicitly granting such permission in a
relatively consistent way, allowing developers to share and collaborate
efficiently by making common solutions to various problems freely available.
This leaves many developers free to spend more time focusing on the problems
that are relatively unique to their specific situation.

The distribution tools provided with Python are designed to make it
reasonably straightforward for developers to make their own contributions
back to that common pool of software if they choose to do so.

The same distribution tools can also be used to distribute software within
an organisation, regardless of whether that software is published as open
source software or not.


Installing the tools
====================

The standard library does not include build tools that support modern
Python packaging standards, as the core development team has found that it
is important to have standard tools that work consistently, even on older
versions of Python.

The currently recommended build and distribution tools can be installed
by invoking the ``pip`` module at the command line::

    python -m pip install setuptools wheel twine

.. note::

   For POSIX users (including Mac OS X and Linux users), these instructions
   assume the use of a :term:`virtual environment`.

   For Windows users, these instructions assume that the option to
   adjust the system PATH environment variable was selected when installing
   Python.

The Python Packaging User Guide includes more details on the `currently
recommended tools`_.

.. _currently recommended tools: https://packaging.python.org/en/latest/current/#packaging-tool-recommendations

Reading the guide
=================

The Python Packaging User Guide covers the various key steps and elements
involved in creating a project:

* `Project structure`_
* `Building and packaging the project`_
* `Uploading the project to the Python Packaging Index`_

.. _Project structure: \
   https://packaging.python.org/en/latest/distributing/
.. _Building and packaging the project: \
   https://packaging.python.org/en/latest/distributing/#packaging-your-project
.. _Uploading the project to the Python Packaging Index: \
   https://packaging.python.org/en/latest/distributing/#uploading-your-project-to-pypi


How do I...?
============

These are quick answers or links for some common tasks.

... choose a name for my project?
---------------------------------

This isn't an easy topic, but here are a few tips:

* check the Python Packaging Index to see if the name is already in use
* check popular hosting sites like GitHub, BitBucket, etc to see if there
  is already a project with that name
* check what comes up in a web search for the name you're considering
* avoid particularly common words, especially ones with multiple meanings,
  as they can make it difficult for users to find your software when
  searching for it


... create and distribute binary extensions?
--------------------------------------------

This is actually quite a complex topic, with a variety of alternatives
available depending on exactly what you're aiming to achieve. See the
Python Packaging User Guide for more information and recommendations.

.. seealso::

   `Python Packaging User Guide: Binary Extensions
   <https://packaging.python.org/en/latest/extensions>`__

.. other topics:

   Once the Development & Deployment part of PPUG is fleshed out, some of
   those sections should be linked from new questions here (most notably,
   we should have a question about avoiding depending on PyPI that links to
   https://packaging.python.org/en/latest/mirrors/)
PK	%�\���p�p&html/_sources/distutils/apiref.rst.txtnu�[���.. _api-reference:

*************
API Reference
*************


:mod:`distutils.core` --- Core Distutils functionality
======================================================

.. module:: distutils.core
   :synopsis: The core Distutils functionality


The :mod:`distutils.core` module is the only module that needs to be installed
to use the Distutils. It provides the :func:`setup` (which is called from the
setup script). Indirectly provides the  :class:`distutils.dist.Distribution` and
:class:`distutils.cmd.Command` class.


.. function:: setup(arguments)

   The basic do-everything function that does most everything you could ever ask
   for from a Distutils method.

   The setup function takes a large number of arguments. These are laid out in the
   following table.

   .. tabularcolumns:: |l|L|L|

   +--------------------+--------------------------------+-------------------------------------------------------------+
   | argument name      | value                          | type                                                        |
   +====================+================================+=============================================================+
   | *name*             | The name of the package        | a string                                                    |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *version*          | The version number of the      | a string                                                    |
   |                    | package; see                   |                                                             |
   |                    | :mod:`distutils.version`       |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *description*      | A single line describing the   | a string                                                    |
   |                    | package                        |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *long_description* | Longer description of the      | a string                                                    |
   |                    | package                        |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *author*           | The name of the package author | a string                                                    |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *author_email*     | The email address of the       | a string                                                    |
   |                    | package author                 |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *maintainer*       | The name of the current        | a string                                                    |
   |                    | maintainer, if different from  |                                                             |
   |                    | the author. Note that if       |                                                             |
   |                    | the maintainer is provided,    |                                                             |
   |                    | distutils will use it as the   |                                                             |
   |                    | author in :file:`PKG-INFO`     |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *maintainer_email* | The email address of the       | a string                                                    |
   |                    | current maintainer, if         |                                                             |
   |                    | different from the author      |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *url*              | A URL for the package          | a string                                                    |
   |                    | (homepage)                     |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *download_url*     | A URL to download the package  | a string                                                    |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *packages*         | A list of Python packages that | a list of strings                                           |
   |                    | distutils will manipulate      |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *py_modules*       | A list of Python modules that  | a list of strings                                           |
   |                    | distutils will manipulate      |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *scripts*          | A list of standalone script    | a list of strings                                           |
   |                    | files to be built and          |                                                             |
   |                    | installed                      |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *ext_modules*      | A list of Python extensions to | a list of instances of                                      |
   |                    | be built                       | :class:`distutils.core.Extension`                           |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *classifiers*      | A list of categories for the   | a list of strings; valid classifiers are listed on `PyPI    |
   |                    | package                        | <https://pypi.org/classifiers>`_.                           |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *distclass*        | the :class:`Distribution`      | a subclass of                                               |
   |                    | class to use                   | :class:`distutils.core.Distribution`                        |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *script_name*      | The name of the setup.py       | a string                                                    |
   |                    | script - defaults to           |                                                             |
   |                    | ``sys.argv[0]``                |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *script_args*      | Arguments to supply to the     | a list of strings                                           |
   |                    | setup script                   |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *options*          | default options for the setup  | a dictionary                                                |
   |                    | script                         |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *license*          | The license for the package    | a string                                                    |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *keywords*         | Descriptive meta-data, see     | a list of strings or a comma-separated string               |
   |                    | :pep:`314`                     |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *platforms*        |                                | a list of strings or a comma-separated string               |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *cmdclass*         | A mapping of command names to  | a dictionary                                                |
   |                    | :class:`Command` subclasses    |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *data_files*       | A list of data files to        | a list                                                      |
   |                    | install                        |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+
   | *package_dir*      | A mapping of package to        | a dictionary                                                |
   |                    | directory names                |                                                             |
   +--------------------+--------------------------------+-------------------------------------------------------------+



.. function:: run_setup(script_name[, script_args=None, stop_after='run'])

   Run a setup script in a somewhat controlled environment, and return  the
   :class:`distutils.dist.Distribution` instance that drives things.   This is
   useful if you need to find out the distribution meta-data  (passed as keyword
   args from *script* to :func:`setup`), or  the contents of the config files or
   command-line.

   *script_name* is a file that will be run with :func:`execfile` ``sys.argv[0]``
   will be replaced with *script* for the duration of the call.  *script_args* is a
   list of strings; if supplied, ``sys.argv[1:]`` will be replaced by *script_args*
   for the duration  of the call.

   *stop_after* tells :func:`setup` when to stop processing; possible  values:

   .. tabularcolumns:: |l|L|

   +---------------+---------------------------------------------+
   | value         | description                                 |
   +===============+=============================================+
   | *init*        | Stop after the :class:`Distribution`        |
   |               | instance has been created  and populated    |
   |               | with the keyword arguments to :func:`setup` |
   +---------------+---------------------------------------------+
   | *config*      | Stop after config files have been parsed    |
   |               | (and their data stored in the               |
   |               | :class:`Distribution` instance)             |
   +---------------+---------------------------------------------+
   | *commandline* | Stop after the command-line                 |
   |               | (``sys.argv[1:]`` or  *script_args*) have   |
   |               | been parsed (and the data stored in the     |
   |               | :class:`Distribution` instance.)            |
   +---------------+---------------------------------------------+
   | *run*         | Stop after all commands have been run (the  |
   |               | same as  if :func:`setup` had been called   |
   |               | in the usual way). This is the default      |
   |               | value.                                      |
   +---------------+---------------------------------------------+

In addition, the :mod:`distutils.core` module exposed a number of  classes that
live elsewhere.

* :class:`~distutils.extension.Extension` from :mod:`distutils.extension`

* :class:`~distutils.cmd.Command` from :mod:`distutils.cmd`

* :class:`~distutils.dist.Distribution` from :mod:`distutils.dist`

A short description of each of these follows, but see the relevant module for
the full reference.


.. class:: Extension

   The Extension class describes a single C or C++ extension module in a setup
   script. It accepts the following keyword arguments in its constructor

   .. tabularcolumns:: |l|L|l|

   +------------------------+--------------------------------+---------------------------+
   | argument name          | value                          | type                      |
   +========================+================================+===========================+
   | *name*                 | the full name of the           | a string                  |
   |                        | extension, including any       |                           |
   |                        | packages --- ie. *not* a       |                           |
   |                        | filename or pathname, but      |                           |
   |                        | Python dotted name             |                           |
   +------------------------+--------------------------------+---------------------------+
   | *sources*              | list of source filenames,      | a list of strings         |
   |                        | relative to the distribution   |                           |
   |                        | root (where the setup script   |                           |
   |                        | lives), in Unix form (slash-   |                           |
   |                        | separated) for portability.    |                           |
   |                        | Source files may be C, C++,    |                           |
   |                        | SWIG (.i), platform-specific   |                           |
   |                        | resource files, or whatever    |                           |
   |                        | else is recognized by the      |                           |
   |                        | :command:`build_ext` command   |                           |
   |                        | as source for a Python         |                           |
   |                        | extension.                     |                           |
   +------------------------+--------------------------------+---------------------------+
   | *include_dirs*         | list of directories to search  | a list of strings         |
   |                        | for C/C++ header files (in     |                           |
   |                        | Unix form for portability)     |                           |
   +------------------------+--------------------------------+---------------------------+
   | *define_macros*        | list of macros to define; each | a list of tuples          |
   |                        | macro is defined using a       |                           |
   |                        | 2-tuple ``(name, value)``,     |                           |
   |                        | where *value* is               |                           |
   |                        | either the string to define it |                           |
   |                        | to or ``None`` to define it    |                           |
   |                        | without a particular value     |                           |
   |                        | (equivalent of ``#define FOO`` |                           |
   |                        | in source or :option:`!-DFOO`  |                           |
   |                        | on Unix C compiler command     |                           |
   |                        | line)                          |                           |
   +------------------------+--------------------------------+---------------------------+
   | *undef_macros*         | list of macros to undefine     | a list of strings         |
   |                        | explicitly                     |                           |
   +------------------------+--------------------------------+---------------------------+
   | *library_dirs*         | list of directories to search  | a list of strings         |
   |                        | for C/C++ libraries at link    |                           |
   |                        | time                           |                           |
   +------------------------+--------------------------------+---------------------------+
   | *libraries*            | list of library names (not     | a list of strings         |
   |                        | filenames or paths) to link    |                           |
   |                        | against                        |                           |
   +------------------------+--------------------------------+---------------------------+
   | *runtime_library_dirs* | list of directories to search  | a list of strings         |
   |                        | for C/C++ libraries at run     |                           |
   |                        | time (for shared extensions,   |                           |
   |                        | this is when the extension is  |                           |
   |                        | loaded)                        |                           |
   +------------------------+--------------------------------+---------------------------+
   | *extra_objects*        | list of extra files to link    | a list of strings         |
   |                        | with (eg. object files not     |                           |
   |                        | implied by 'sources', static   |                           |
   |                        | library that must be           |                           |
   |                        | explicitly specified, binary   |                           |
   |                        | resource files, etc.)          |                           |
   +------------------------+--------------------------------+---------------------------+
   | *extra_compile_args*   | any extra platform- and        | a list of strings         |
   |                        | compiler-specific information  |                           |
   |                        | to use when compiling the      |                           |
   |                        | source files in 'sources'. For |                           |
   |                        | platforms and compilers where  |                           |
   |                        | a command line makes sense,    |                           |
   |                        | this is typically a list of    |                           |
   |                        | command-line arguments, but    |                           |
   |                        | for other platforms it could   |                           |
   |                        | be anything.                   |                           |
   +------------------------+--------------------------------+---------------------------+
   | *extra_link_args*      | any extra platform- and        | a list of strings         |
   |                        | compiler-specific information  |                           |
   |                        | to use when linking object     |                           |
   |                        | files together to create the   |                           |
   |                        | extension (or to create a new  |                           |
   |                        | static Python interpreter).    |                           |
   |                        | Similar interpretation as for  |                           |
   |                        | 'extra_compile_args'.          |                           |
   +------------------------+--------------------------------+---------------------------+
   | *export_symbols*       | list of symbols to be exported | a list of strings         |
   |                        | from a shared extension. Not   |                           |
   |                        | used on all platforms, and not |                           |
   |                        | generally necessary for Python |                           |
   |                        | extensions, which typically    |                           |
   |                        | export exactly one symbol:     |                           |
   |                        | ``init`` + extension_name.     |                           |
   +------------------------+--------------------------------+---------------------------+
   | *depends*              | list of files that the         | a list of strings         |
   |                        | extension depends on           |                           |
   +------------------------+--------------------------------+---------------------------+
   | *language*             | extension language (i.e.       | a string                  |
   |                        | ``'c'``, ``'c++'``,            |                           |
   |                        | ``'objc'``). Will be detected  |                           |
   |                        | from the source extensions if  |                           |
   |                        | not provided.                  |                           |
   +------------------------+--------------------------------+---------------------------+


.. class:: Distribution

   A :class:`Distribution` describes how to build, install and package up a Python
   software package.

   See the :func:`setup` function for a list of keyword arguments accepted  by the
   Distribution constructor. :func:`setup` creates a Distribution instance.


.. class:: Command

   A :class:`Command` class (or rather, an instance of one of its subclasses)
   implement a single distutils command.


:mod:`distutils.ccompiler` --- CCompiler base class
===================================================

.. module:: distutils.ccompiler
   :synopsis: Abstract CCompiler class


This module provides the abstract base class for the :class:`CCompiler`
classes.  A :class:`CCompiler` instance can be used for all the compile  and
link steps needed to build a single project. Methods are provided to  set
options for the compiler --- macro definitions, include directories,  link path,
libraries and the like.

This module provides the following functions.


.. function:: gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries)

   Generate linker options for searching library directories and linking with
   specific libraries.  *libraries* and *library_dirs* are, respectively, lists of
   library names (not filenames!) and search directories.  Returns a list of
   command-line options suitable for use with some compiler (depending on the two
   format strings passed in).


.. function:: gen_preprocess_options(macros, include_dirs)

   Generate C pre-processor options (:option:`!-D`, :option:`!-U`, :option:`!-I`) as
   used by at least two types of compilers: the typical Unix compiler and Visual
   C++. *macros* is the usual thing, a list of 1- or 2-tuples, where ``(name,)``
   means undefine (:option:`!-U`) macro *name*, and ``(name, value)`` means define
   (:option:`!-D`) macro *name* to *value*.  *include_dirs* is just a list of
   directory names to be added to the header file search path (:option:`!-I`).
   Returns a list of command-line options suitable for either Unix compilers or
   Visual C++.


.. function:: get_default_compiler(osname, platform)

   Determine the default compiler to use for the given platform.

   *osname* should be one of the standard Python OS names (i.e. the ones returned
   by ``os.name``) and *platform* the common value returned by ``sys.platform`` for
   the platform in question.

   The default values are ``os.name`` and ``sys.platform`` in case the parameters
   are not given.


.. function:: new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0)

   Factory function to generate an instance of some CCompiler subclass for the
   supplied platform/compiler combination. *plat* defaults to ``os.name`` (eg.
   ``'posix'``, ``'nt'``), and *compiler*  defaults to the default compiler for
   that platform. Currently only ``'posix'`` and ``'nt'`` are supported, and the
   default compilers are "traditional Unix interface" (:class:`UnixCCompiler`
   class) and Visual C++ (:class:`MSVCCompiler` class).  Note that it's perfectly
   possible to ask for a Unix compiler object under Windows, and a Microsoft
   compiler object under Unix---if you supply a value for *compiler*, *plat* is
   ignored.

   .. % Is the posix/nt only thing still true? Mac OS X seems to work, and
   .. % returns a UnixCCompiler instance. How to document this... hmm.


.. function:: show_compilers()

   Print list of available compilers (used by the :option:`!--help-compiler` options
   to :command:`build`, :command:`build_ext`, :command:`build_clib`).


.. class:: CCompiler([verbose=0, dry_run=0, force=0])

   The abstract base class :class:`CCompiler` defines the interface that  must be
   implemented by real compiler classes.  The class also has  some utility methods
   used by several compiler classes.

   The basic idea behind a compiler abstraction class is that each instance can be
   used for all the compile/link steps in building a single project.  Thus,
   attributes common to all of those compile and link steps --- include
   directories, macros to define, libraries to link against, etc. --- are
   attributes of the compiler instance.  To allow for variability in how individual
   files are treated, most of those attributes may be varied on a per-compilation
   or per-link basis.

   The constructor for each subclass creates an instance of the Compiler object.
   Flags are *verbose* (show verbose output), *dry_run* (don't actually execute the
   steps) and *force* (rebuild everything, regardless of dependencies). All of
   these flags default to ``0`` (off). Note that you probably don't want to
   instantiate :class:`CCompiler` or one of its subclasses directly - use the
   :func:`distutils.CCompiler.new_compiler` factory function instead.

   The following methods allow you to manually alter compiler options for  the
   instance of the Compiler class.


   .. method:: CCompiler.add_include_dir(dir)

      Add *dir* to the list of directories that will be searched for header files.
      The compiler is instructed to search directories in the order in which they are
      supplied by successive calls to :meth:`add_include_dir`.


   .. method:: CCompiler.set_include_dirs(dirs)

      Set the list of directories that will be searched to *dirs* (a list of strings).
      Overrides any preceding calls to :meth:`add_include_dir`; subsequent calls to
      :meth:`add_include_dir` add to the list passed to :meth:`set_include_dirs`.
      This does not affect any list of standard include directories that the compiler
      may search by default.


   .. method:: CCompiler.add_library(libname)

      Add *libname* to the list of libraries that will be included in all links driven
      by this compiler object.  Note that *libname* should \*not\* be the name of a
      file containing a library, but the name of the library itself: the actual
      filename will be inferred by the linker, the compiler, or the compiler class
      (depending on the platform).

      The linker will be instructed to link against libraries in the order they were
      supplied to :meth:`add_library` and/or :meth:`set_libraries`.  It is perfectly
      valid to duplicate library names; the linker will be instructed to link against
      libraries as many times as they are mentioned.


   .. method:: CCompiler.set_libraries(libnames)

      Set the list of libraries to be included in all links driven by this compiler
      object to *libnames* (a list of strings).  This does not affect any standard
      system libraries that the linker may include by default.


   .. method:: CCompiler.add_library_dir(dir)

      Add *dir* to the list of directories that will be searched for libraries
      specified to :meth:`add_library` and :meth:`set_libraries`.  The linker will be
      instructed to search for libraries in the order they are supplied to
      :meth:`add_library_dir` and/or :meth:`set_library_dirs`.


   .. method:: CCompiler.set_library_dirs(dirs)

      Set the list of library search directories to *dirs* (a list of strings).  This
      does not affect any standard library search path that the linker may search by
      default.


   .. method:: CCompiler.add_runtime_library_dir(dir)

      Add *dir* to the list of directories that will be searched for shared libraries
      at runtime.


   .. method:: CCompiler.set_runtime_library_dirs(dirs)

      Set the list of directories to search for shared libraries at runtime to *dirs*
      (a list of strings).  This does not affect any standard search path that the
      runtime linker may search by default.


   .. method:: CCompiler.define_macro(name[, value=None])

      Define a preprocessor macro for all compilations driven by this compiler object.
      The optional parameter *value* should be a string; if it is not supplied, then
      the macro will be defined without an explicit value and the exact outcome
      depends on the compiler used.

      .. XXX true? does ANSI say anything about this?


   .. method:: CCompiler.undefine_macro(name)

      Undefine a preprocessor macro for all compilations driven by this compiler
      object.  If the same macro is defined by :meth:`define_macro` and
      undefined by :meth:`undefine_macro` the last call takes precedence
      (including multiple redefinitions or undefinitions).  If the macro is
      redefined/undefined on a per-compilation basis (ie. in the call to
      :meth:`compile`), then that takes precedence.


   .. method:: CCompiler.add_link_object(object)

      Add *object* to the list of object files (or analogues, such as explicitly named
      library files or the output of "resource compilers") to be included in every
      link driven by this compiler object.


   .. method:: CCompiler.set_link_objects(objects)

      Set the list of object files (or analogues) to be included in every link to
      *objects*.  This does not affect any standard object files that the linker may
      include by default (such as system libraries).

   The following methods implement methods for autodetection of compiler  options,
   providing some functionality similar to GNU :program:`autoconf`.


   .. method:: CCompiler.detect_language(sources)

      Detect the language of a given file, or list of files. Uses the  instance
      attributes :attr:`language_map` (a dictionary), and  :attr:`language_order` (a
      list) to do the job.


   .. method:: CCompiler.find_library_file(dirs, lib[, debug=0])

      Search the specified list of directories for a static or shared library file
      *lib* and return the full path to that file.  If *debug* is true, look for a
      debugging version (if that makes sense on the current platform).  Return
      ``None`` if *lib* wasn't found in any of the specified directories.


   .. method:: CCompiler.has_function(funcname [, includes=None, include_dirs=None, libraries=None, library_dirs=None])

      Return a boolean indicating whether *funcname* is supported on the current
      platform.  The optional arguments can be used to augment the compilation
      environment by providing additional include files and paths and libraries and
      paths.


   .. method:: CCompiler.library_dir_option(dir)

      Return the compiler option to add *dir* to the list of directories searched for
      libraries.


   .. method:: CCompiler.library_option(lib)

      Return the compiler option to add *lib* to the list of libraries linked into the
      shared library or executable.


   .. method:: CCompiler.runtime_library_dir_option(dir)

      Return the compiler option to add *dir* to the list of directories searched for
      runtime libraries.


   .. method:: CCompiler.set_executables(**args)

      Define the executables (and options for them) that will be run to perform the
      various stages of compilation.  The exact set of executables that may be
      specified here depends on the compiler class (via the 'executables' class
      attribute), but most will have:

      +--------------+------------------------------------------+
      | attribute    | description                              |
      +==============+==========================================+
      | *compiler*   | the C/C++ compiler                       |
      +--------------+------------------------------------------+
      | *linker_so*  | linker used to create shared objects and |
      |              | libraries                                |
      +--------------+------------------------------------------+
      | *linker_exe* | linker used to create binary executables |
      +--------------+------------------------------------------+
      | *archiver*   | static library creator                   |
      +--------------+------------------------------------------+

      On platforms with a command-line (Unix, DOS/Windows), each of these is a string
      that will be split into executable name and (optional) list of arguments.
      (Splitting the string is done similarly to how Unix shells operate: words are
      delimited by spaces, but quotes and backslashes can override this.  See
      :func:`distutils.util.split_quoted`.)

   The following methods invoke stages in the build process.


   .. method:: CCompiler.compile(sources[, output_dir=None, macros=None, include_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, depends=None])

      Compile one or more source files. Generates object files (e.g.  transforms a
      :file:`.c` file to a :file:`.o` file.)

      *sources* must be a list of filenames, most likely C/C++ files, but in reality
      anything that can be handled by a particular compiler and compiler class (eg.
      :class:`MSVCCompiler` can handle resource files in *sources*).  Return a list of
      object filenames, one per source filename in *sources*.  Depending on the
      implementation, not all source files will necessarily be compiled, but all
      corresponding object filenames will be returned.

      If *output_dir* is given, object files will be put under it, while retaining
      their original path component.  That is, :file:`foo/bar.c` normally compiles to
      :file:`foo/bar.o` (for a Unix implementation); if *output_dir* is *build*, then
      it would compile to :file:`build/foo/bar.o`.

      *macros*, if given, must be a list of macro definitions.  A macro definition is
      either a ``(name, value)`` 2-tuple or a ``(name,)`` 1-tuple. The former defines
      a macro; if the value is ``None``, the macro is defined without an explicit
      value.  The 1-tuple case undefines a macro.  Later
      definitions/redefinitions/undefinitions take precedence.

      *include_dirs*, if given, must be a list of strings, the directories to add to
      the default include file search path for this compilation only.

      *debug* is a boolean; if true, the compiler will be instructed to output debug
      symbols in (or alongside) the object file(s).

      *extra_preargs* and *extra_postargs* are implementation-dependent. On platforms
      that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most
      likely lists of strings: extra command-line arguments to prepend/append to the
      compiler command line.  On other platforms, consult the implementation class
      documentation.  In any event, they are intended as an escape hatch for those
      occasions when the abstract compiler framework doesn't cut the mustard.

      *depends*, if given, is a list of filenames that all targets depend on.  If a
      source file is older than any file in depends, then the source file will be
      recompiled.  This supports dependency tracking, but only at a coarse
      granularity.

      Raises :exc:`CompileError` on failure.


   .. method:: CCompiler.create_static_lib(objects, output_libname[, output_dir=None, debug=0, target_lang=None])

      Link a bunch of stuff together to create a static library file. The "bunch of
      stuff" consists of the list of object files supplied as *objects*, the extra
      object files supplied to :meth:`add_link_object` and/or
      :meth:`set_link_objects`, the libraries supplied to :meth:`add_library` and/or
      :meth:`set_libraries`, and the libraries supplied as *libraries* (if any).

      *output_libname* should be a library name, not a filename; the filename will be
      inferred from the library name.  *output_dir* is the directory where the library
      file will be put.

      .. XXX defaults to what?

      *debug* is a boolean; if true, debugging information will be included in the
      library (note that on most platforms, it is the compile step where this matters:
      the *debug* flag is included here just for consistency).

      *target_lang* is the target language for which the given objects are being
      compiled. This allows specific linkage time treatment of certain languages.

      Raises :exc:`LibError` on failure.


   .. method:: CCompiler.link(target_desc, objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

      Link a bunch of stuff together to create an executable or shared library file.

      The "bunch of stuff" consists of the list of object files supplied as *objects*.
      *output_filename* should be a filename.  If *output_dir* is supplied,
      *output_filename* is relative to it (i.e. *output_filename* can provide
      directory components if needed).

      *libraries* is a list of libraries to link against.  These are library names,
      not filenames, since they're translated into filenames in a platform-specific
      way (eg. *foo* becomes :file:`libfoo.a` on Unix and :file:`foo.lib` on
      DOS/Windows).  However, they can include a directory component, which means the
      linker will look in that specific directory rather than searching all the normal
      locations.

      *library_dirs*, if supplied, should be a list of directories to search for
      libraries that were specified as bare library names (ie. no directory
      component).  These are on top of the system default and those supplied to
      :meth:`add_library_dir` and/or :meth:`set_library_dirs`.  *runtime_library_dirs*
      is a list of directories that will be embedded into the shared library and used
      to search for other shared libraries that \*it\* depends on at run-time.  (This
      may only be relevant on Unix.)

      *export_symbols* is a list of symbols that the shared library will export.
      (This appears to be relevant only on Windows.)

      *debug* is as for :meth:`compile` and :meth:`create_static_lib`,  with the
      slight distinction that it actually matters on most platforms (as opposed to
      :meth:`create_static_lib`, which includes a *debug* flag mostly for form's
      sake).

      *extra_preargs* and *extra_postargs* are as for :meth:`compile`  (except of
      course that they supply command-line arguments for the particular linker being
      used).

      *target_lang* is the target language for which the given objects are being
      compiled. This allows specific linkage time treatment of certain languages.

      Raises :exc:`LinkError` on failure.


   .. method:: CCompiler.link_executable(objects, output_progname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, debug=0, extra_preargs=None, extra_postargs=None, target_lang=None])

      Link an executable.  *output_progname* is the name of the file executable, while
      *objects* are a list of object filenames to link in. Other arguments  are as for
      the :meth:`link` method.


   .. method:: CCompiler.link_shared_lib(objects, output_libname[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

      Link a shared library. *output_libname* is the name of the output  library,
      while *objects* is a list of object filenames to link in.  Other arguments are
      as for the :meth:`link` method.


   .. method:: CCompiler.link_shared_object(objects, output_filename[, output_dir=None, libraries=None, library_dirs=None, runtime_library_dirs=None, export_symbols=None, debug=0, extra_preargs=None, extra_postargs=None, build_temp=None, target_lang=None])

      Link a shared object. *output_filename* is the name of the shared object that
      will be created, while *objects* is a list of object filenames  to link in.
      Other arguments are as for the :meth:`link` method.


   .. method:: CCompiler.preprocess(source[, output_file=None, macros=None, include_dirs=None, extra_preargs=None, extra_postargs=None])

      Preprocess a single C/C++ source file, named in *source*. Output will be written
      to file named *output_file*, or *stdout* if *output_file* not supplied.
      *macros* is a list of macro definitions as for :meth:`compile`, which will
      augment the macros set with :meth:`define_macro` and :meth:`undefine_macro`.
      *include_dirs* is a list of directory names that will be added to the  default
      list, in the same way as :meth:`add_include_dir`.

      Raises :exc:`PreprocessError` on failure.

   The following utility methods are defined by the :class:`CCompiler` class, for
   use by the various concrete subclasses.


   .. method:: CCompiler.executable_filename(basename[, strip_dir=0, output_dir=''])

      Returns the filename of the executable for the given *basename*.  Typically for
      non-Windows platforms this is the same as the basename,  while Windows will get
      a :file:`.exe` added.


   .. method:: CCompiler.library_filename(libname[, lib_type='static', strip_dir=0, output_dir=''])

      Returns the filename for the given library name on the current platform. On Unix
      a library with *lib_type* of ``'static'`` will typically  be of the form
      :file:`liblibname.a`, while a *lib_type* of ``'dynamic'``  will be of the form
      :file:`liblibname.so`.


   .. method:: CCompiler.object_filenames(source_filenames[, strip_dir=0, output_dir=''])

      Returns the name of the object files for the given source files.
      *source_filenames* should be a list of filenames.


   .. method:: CCompiler.shared_object_filename(basename[, strip_dir=0, output_dir=''])

      Returns the name of a shared object file for the given file name *basename*.


   .. method:: CCompiler.execute(func, args[, msg=None, level=1])

      Invokes :func:`distutils.util.execute`. This method invokes a  Python function
      *func* with the given arguments *args*, after  logging and taking into account
      the *dry_run* flag.


   .. method:: CCompiler.spawn(cmd)

      Invokes :func:`distutils.util.spawn`. This invokes an external  process to run
      the given command.


   .. method:: CCompiler.mkpath(name[, mode=511])

      Invokes :func:`distutils.dir_util.mkpath`. This creates a directory  and any
      missing ancestor directories.


   .. method:: CCompiler.move_file(src, dst)

      Invokes :meth:`distutils.file_util.move_file`. Renames *src* to  *dst*.


   .. method:: CCompiler.announce(msg[, level=1])

      Write a message using :func:`distutils.log.debug`.


   .. method:: CCompiler.warn(msg)

      Write a warning message *msg* to standard error.


   .. method:: CCompiler.debug_print(msg)

      If the *debug* flag is set on this :class:`CCompiler` instance, print  *msg* to
      standard output, otherwise do nothing.

.. % \subsection{Compiler-specific modules}
.. %
.. % The following modules implement concrete subclasses of the abstract
.. % \class{CCompiler} class. They should not be instantiated directly, but should
.. % be created using \function{distutils.ccompiler.new_compiler()} factory
.. % function.


:mod:`distutils.unixccompiler` --- Unix C Compiler
==================================================

.. module:: distutils.unixccompiler
   :synopsis: UNIX C Compiler


This module provides the :class:`UnixCCompiler` class, a subclass of
:class:`CCompiler` that handles the typical Unix-style command-line  C compiler:

* macros defined with :option:`!-Dname[=value]`

* macros undefined with :option:`!-Uname`

* include search directories specified with :option:`!-Idir`

* libraries specified with :option:`!-llib`

* library search directories specified with :option:`!-Ldir`

* compile handled by :program:`cc` (or similar) executable with :option:`!-c`
  option: compiles :file:`.c` to :file:`.o`

* link static library handled by :program:`ar` command (possibly with
  :program:`ranlib`)

* link shared library handled by :program:`cc` :option:`!-shared`


:mod:`distutils.msvccompiler` --- Microsoft Compiler
====================================================

.. module:: distutils.msvccompiler
   :synopsis: Microsoft Compiler


This module provides :class:`MSVCCompiler`, an implementation of the abstract
:class:`CCompiler` class for Microsoft Visual Studio. Typically, extension
modules need to be compiled with the same compiler that was used to compile
Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python
2.4 and 2.5, the compiler is Visual Studio .NET 2003. The AMD64 and Itanium
binaries are created using the Platform SDK.

:class:`MSVCCompiler` will normally choose the right compiler, linker etc. on
its own. To override this choice, the environment variables *DISTUTILS_USE_SDK*
and *MSSdk* must be both set. *MSSdk* indicates that the current environment has
been setup by the SDK's ``SetEnv.Cmd`` script, or that the environment variables
had been registered when the SDK was installed; *DISTUTILS_USE_SDK* indicates
that the distutils user has made an explicit choice to override the compiler
selection by :class:`MSVCCompiler`.


:mod:`distutils.bcppcompiler` --- Borland Compiler
==================================================

.. module:: distutils.bcppcompiler


This module provides :class:`BorlandCCompiler`, a subclass of the abstract
:class:`CCompiler` class for the Borland C++ compiler.


:mod:`distutils.cygwincompiler` --- Cygwin Compiler
===================================================

.. module:: distutils.cygwinccompiler


This module provides the :class:`CygwinCCompiler` class, a subclass of
:class:`UnixCCompiler` that handles the Cygwin port of the GNU C compiler to
Windows.  It also contains the Mingw32CCompiler class which handles the mingw32
port of GCC (same as cygwin in no-cygwin mode).


:mod:`distutils.emxccompiler` --- OS/2 EMX Compiler
===================================================

.. module:: distutils.emxccompiler
   :synopsis: OS/2 EMX Compiler support


This module provides the EMXCCompiler class, a subclass of
:class:`UnixCCompiler` that handles the EMX port of the GNU C compiler to OS/2.


:mod:`distutils.archive_util` ---  Archiving utilities
======================================================

.. module:: distutils.archive_util
   :synopsis: Utility functions for creating archive files (tarballs, zip files, ...)


This module provides a few functions for creating archive files, such as
tarballs or zipfiles.


.. function:: make_archive(base_name, format[, root_dir=None, base_dir=None, verbose=0, dry_run=0])

   Create an archive file (eg. ``zip`` or ``tar``).  *base_name*  is the name of
   the file to create, minus any format-specific extension;  *format* is the
   archive format: one of ``zip``, ``tar``,  ``ztar``, or ``gztar``. *root_dir* is
   a directory that will be the root directory of the archive; ie. we typically
   ``chdir`` into *root_dir* before  creating the archive.  *base_dir* is the
   directory where we start  archiving from; ie. *base_dir* will be the common
   prefix of all files and directories in the archive.  *root_dir* and *base_dir*
   both default to the current directory.  Returns the name of the archive file.


.. function:: make_tarball(base_name, base_dir[, compress='gzip', verbose=0, dry_run=0])

   'Create an (optional compressed) archive as a tar file from all files in and
   under *base_dir*. *compress* must be ``'gzip'`` (the default),  ``'compress'``,
   ``'bzip2'``, or ``None``.  Both :program:`tar` and the compression utility named
   by *compress* must be on the  default program search path, so this is probably
   Unix-specific.  The  output tar file will be named :file:`base_dir.tar`,
   possibly plus the appropriate compression extension (:file:`.gz`, :file:`.bz2`
   or :file:`.Z`).  Return the output filename.


.. function:: make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])

   Create a zip file from all files in and under *base_dir*.  The output zip file
   will be named *base_name* + :file:`.zip`.  Uses either the  :mod:`zipfile` Python
   module (if available) or the InfoZIP :file:`zip`  utility (if installed and
   found on the default search path).  If neither  tool is available, raises
   :exc:`DistutilsExecError`.   Returns the name of the output zip file.


:mod:`distutils.dep_util` --- Dependency checking
=================================================

.. module:: distutils.dep_util
   :synopsis: Utility functions for simple dependency checking


This module provides functions for performing simple, timestamp-based
dependency of files and groups of files; also, functions based entirely  on such
timestamp dependency analysis.


.. function:: newer(source, target)

   Return true if *source* exists and is more recently modified than *target*, or
   if *source* exists and *target* doesn't. Return false if both exist and *target*
   is the same age or newer  than *source*. Raise :exc:`DistutilsFileError` if
   *source* does not exist.


.. function:: newer_pairwise(sources, targets)

   Walk two filename lists in parallel, testing if each source is newer than its
   corresponding target.  Return a pair of lists (*sources*, *targets*) where
   source is newer than target, according to the semantics of :func:`newer`.

   .. % % equivalent to a listcomp...


.. function:: newer_group(sources, target[, missing='error'])

   Return true if *target* is out-of-date with respect to any file listed in
   *sources*.  In other words, if *target* exists and is newer than every file in
   *sources*, return false; otherwise return true. *missing* controls what we do
   when a source file is missing; the default (``'error'``) is to blow up with an
   :exc:`OSError` from  inside :func:`os.stat`; if it is ``'ignore'``, we silently
   drop any missing source files; if it is ``'newer'``, any missing source files
   make us assume that *target* is out-of-date (this is handy in "dry-run" mode:
   it'll make you pretend to carry out commands that wouldn't work because inputs
   are missing, but that doesn't matter because you're not actually going to run
   the commands).


:mod:`distutils.dir_util` --- Directory tree operations
=======================================================

.. module:: distutils.dir_util
   :synopsis: Utility functions for operating on directories and directory trees


This module provides functions for operating on directories and trees of
directories.


.. function:: mkpath(name[, mode=0777, verbose=0, dry_run=0])

   Create a directory and any missing ancestor directories.  If the directory
   already exists (or if *name* is the empty string, which means the current
   directory, which of course exists), then do nothing.  Raise
   :exc:`DistutilsFileError` if unable to create some directory along the way (eg.
   some sub-path exists, but is a file rather than a directory).  If *verbose* is
   true, print a one-line summary of each mkdir to stdout.  Return the list of
   directories actually created.


.. function:: create_tree(base_dir, files[, mode=0777, verbose=0, dry_run=0])

   Create all the empty directories under *base_dir* needed to put *files* there.
   *base_dir* is just the name of a directory which doesn't necessarily exist
   yet; *files* is a list of filenames to be interpreted relative to *base_dir*.
   *base_dir* + the directory portion of every file in *files* will be created if
   it doesn't already exist.  *mode*, *verbose* and *dry_run* flags  are as for
   :func:`mkpath`.


.. function:: copy_tree(src, dst[, preserve_mode=1, preserve_times=1, preserve_symlinks=0, update=0, verbose=0, dry_run=0])

   Copy an entire directory tree *src* to a new location *dst*.  Both *src* and
   *dst* must be directory names.  If *src* is not a directory, raise
   :exc:`DistutilsFileError`.  If *dst* does  not exist, it is created with
   :func:`mkpath`.  The end result of the copy is that every file in *src* is
   copied to *dst*, and directories under *src* are recursively copied to *dst*.
   Return the list of files that were copied or might have been copied, using their
   output name. The return value is unaffected by *update* or *dry_run*: it is
   simply the list of all files under *src*, with the names changed to be under
   *dst*.

   *preserve_mode* and *preserve_times* are the same as for
   :func:`distutils.file_util.copy_file`; note that they only apply to
   regular files, not to
   directories.  If *preserve_symlinks* is true, symlinks will be copied as
   symlinks (on platforms that support them!); otherwise (the default), the
   destination of the symlink will be copied.  *update* and *verbose* are the same
   as for :func:`copy_file`.

   Files in *src* that begin with :file:`.nfs` are skipped (more information on
   these files is available in answer D2 of the `NFS FAQ page
   <http://nfs.sourceforge.net/#section_d>`_.

   .. versionchanged:: 2.7.4
      NFS files are ignored.


.. function:: remove_tree(directory[, verbose=0, dry_run=0])

   Recursively remove *directory* and all files and directories underneath it. Any
   errors are ignored (apart from being reported to ``sys.stdout`` if *verbose* is
   true).


:mod:`distutils.file_util` --- Single file operations
=====================================================

.. module:: distutils.file_util
   :synopsis: Utility functions for operating on single files


This module contains some utility functions for operating on individual files.


.. function:: copy_file(src, dst[, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=0, dry_run=0])

   Copy file *src* to *dst*. If *dst* is a directory, then *src* is copied there
   with the same name; otherwise, it must be a filename. (If the file exists, it
   will be ruthlessly clobbered.) If *preserve_mode* is true (the default), the
   file's mode (type and permission bits, or whatever is analogous on the
   current platform) is copied. If *preserve_times* is true (the default), the
   last-modified and last-access times are copied as well. If *update* is true,
   *src* will only be copied if *dst* does not exist, or if *dst* does exist but
   is older than *src*.

   *link* allows you to make hard links (using :func:`os.link`) or symbolic links
   (using :func:`os.symlink`) instead of copying: set it to ``'hard'`` or
   ``'sym'``; if it is ``None`` (the default), files are copied. Don't set *link*
   on systems that don't support it: :func:`copy_file` doesn't check if hard or
   symbolic linking is available.  It uses :func:`_copy_file_contents` to copy file
   contents.

   Return a tuple ``(dest_name, copied)``: *dest_name* is the actual  name of the
   output file, and *copied* is true if the file was copied  (or would have been
   copied, if *dry_run* true).

   .. % XXX if the destination file already exists, we clobber it if
   .. % copying, but blow up if linking.  Hmmm.  And I don't know what
   .. % macostools.copyfile() does.  Should definitely be consistent, and
   .. % should probably blow up if destination exists and we would be
   .. % changing it (ie. it's not already a hard/soft link to src OR
   .. % (not update) and (src newer than dst)).


.. function:: move_file(src, dst[, verbose, dry_run])

   Move file *src* to *dst*. If *dst* is a directory, the file will be moved into
   it with the same name; otherwise, *src* is just renamed to *dst*.  Returns the
   new full name of the file.

   .. warning::

      Handles cross-device moves on Unix using :func:`copy_file`.  What about
      other systems?


.. function:: write_file(filename, contents)

   Create a file called *filename* and write *contents* (a sequence of strings
   without line terminators) to it.


:mod:`distutils.util` --- Miscellaneous other utility functions
===============================================================

.. module:: distutils.util
   :synopsis: Miscellaneous other utility functions


This module contains other assorted bits and pieces that don't fit into  any
other utility module.


.. function:: get_platform()

   Return a string that identifies the current platform.  This is used mainly to
   distinguish platform-specific build directories and platform-specific built
   distributions.  Typically includes the OS name and version and the architecture
   (as supplied by 'os.uname()'), although the exact information included depends
   on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only
   runs on SGI hardware), but for Linux the kernel version isn't particularly
   important.

   Examples of returned values:

   * ``linux-i586``
   * ``linux-alpha``
   * ``solaris-2.6-sun4u``
   * ``irix-5.3``
   * ``irix64-6.2``

   For non-POSIX platforms, currently just returns ``sys.platform``.

   For Mac OS X systems the OS version reflects the minimal version on which
   binaries will run (that is, the value of ``MACOSX_DEPLOYMENT_TARGET``
   during the build of Python), not the OS version of the current system.

   For universal binary builds on Mac OS X the architecture value reflects
   the universal binary status instead of the architecture of the current
   processor. For 32-bit universal binaries the architecture is ``fat``,
   for 64-bit universal binaries the architecture is ``fat64``, and
   for 4-way universal binaries the architecture is ``universal``. Starting
   from Python 2.7 and Python 3.2 the architecture ``fat3`` is used for
   a 3-way universal build (ppc, i386, x86_64) and ``intel`` is used for
   a universal build with the i386 and x86_64 architectures

   Examples of returned values on Mac OS X:

   * ``macosx-10.3-ppc``

   * ``macosx-10.3-fat``

   * ``macosx-10.5-universal``

   * ``macosx-10.6-intel``


.. function:: convert_path(pathname)

   Return 'pathname' as a name that will work on the native filesystem, i.e. split
   it on '/' and put it back together again using the current directory separator.
   Needed because filenames in the setup script are always supplied in Unix style,
   and have to be converted to the local convention before we can actually use them
   in the filesystem.  Raises :exc:`ValueError` on non-Unix-ish systems if
   *pathname* either  starts or ends with a slash.


.. function:: change_root(new_root, pathname)

   Return *pathname* with *new_root* prepended.  If *pathname* is relative, this is
   equivalent to ``os.path.join(new_root,pathname)`` Otherwise, it requires making
   *pathname* relative and then joining the two, which is tricky on DOS/Windows.


.. function:: check_environ()

   Ensure that 'os.environ' has all the environment variables we guarantee that
   users can use in config files, command-line options, etc.  Currently this
   includes:

   * :envvar:`HOME` - user's home directory (Unix only)
   * :envvar:`PLAT` - description of the current platform, including hardware and
     OS (see :func:`get_platform`)


.. function:: subst_vars(s, local_vars)

   Perform shell/Perl-style variable substitution on *s*.  Every occurrence of
   ``$`` followed by a name is considered a variable, and variable is substituted
   by the value found in the *local_vars* dictionary, or in ``os.environ`` if it's
   not in *local_vars*. *os.environ* is first checked/augmented to guarantee that
   it contains certain values: see :func:`check_environ`.  Raise :exc:`ValueError`
   for any variables not found in either *local_vars* or ``os.environ``.

   Note that this is not a fully-fledged string interpolation function. A valid
   ``$variable`` can consist only of upper and lower case letters, numbers and an
   underscore. No { } or ( ) style quoting is available.



.. function:: split_quoted(s)

   Split a string up according to Unix shell-like rules for quotes and backslashes.
   In short: words are delimited by spaces, as long as those spaces are not escaped
   by a backslash, or inside a quoted string. Single and double quotes are
   equivalent, and the quote characters can be backslash-escaped.  The backslash is
   stripped from any two-character escape sequence, leaving only the escaped
   character.  The quote characters are stripped from any quoted string.  Returns a
   list of words.

   .. % Should probably be moved into the standard library.


.. function:: execute(func, args[, msg=None, verbose=0, dry_run=0])

   Perform some action that affects the outside world (for instance, writing to the
   filesystem).  Such actions are special because they are disabled by the
   *dry_run* flag.  This method takes  care of all that bureaucracy for you; all
   you have to do is supply the function to call and an argument tuple for it (to
   embody the "external action" being performed), and an optional message to print.


.. function:: strtobool(val)

   Convert a string representation of truth to true (1) or false (0).

   True values are ``y``, ``yes``, ``t``, ``true``, ``on``  and ``1``; false values
   are ``n``, ``no``, ``f``, ``false``,  ``off`` and ``0``.  Raises
   :exc:`ValueError` if *val*  is anything else.


.. function:: byte_compile(py_files[, optimize=0, force=0, prefix=None, base_dir=None, verbose=1, dry_run=0, direct=None])

   Byte-compile a collection of Python source files to either :file:`.pyc` or
   :file:`.pyo` files in the same directory.  *py_files* is a list of files to
   compile; any files that don't end in :file:`.py` are silently skipped.
   *optimize* must be one of the following:

   * ``0`` - don't optimize (generate :file:`.pyc`)
   * ``1`` - normal optimization (like ``python -O``)
   * ``2`` - extra optimization (like ``python -OO``)

   If *force* is true, all files are recompiled regardless of timestamps.

   The source filename encoded in each :term:`bytecode` file defaults to the filenames
   listed in *py_files*; you can modify these with *prefix* and *basedir*.
   *prefix* is a string that will be stripped off of each source filename, and
   *base_dir* is a directory name that will be prepended (after *prefix* is
   stripped).  You can supply either or both (or neither) of *prefix* and
   *base_dir*, as you wish.

   If *dry_run* is true, doesn't actually do anything that would affect the
   filesystem.

   Byte-compilation is either done directly in this interpreter process with the
   standard :mod:`py_compile` module, or indirectly by writing a temporary script
   and executing it.  Normally, you should let :func:`byte_compile` figure out to
   use direct compilation or not (see the source for details).  The *direct* flag
   is used by the script generated in indirect mode; unless you know what you're
   doing, leave it set to ``None``.


.. function:: rfc822_escape(header)

   Return a version of *header* escaped for inclusion in an :rfc:`822` header, by
   ensuring there are 8 spaces space after each newline. Note that it does no other
   modification of the string.

   .. % this _can_ be replaced

.. % \subsection{Distutils objects}


:mod:`distutils.dist` --- The Distribution class
================================================

.. module:: distutils.dist
   :synopsis: Provides the Distribution class, which represents the module distribution being
              built/installed/distributed


This module provides the :class:`~distutils.core.Distribution` class, which
represents the module distribution being built/installed/distributed.


:mod:`distutils.extension` --- The Extension class
==================================================

.. module:: distutils.extension
   :synopsis: Provides the Extension class, used to describe C/C++ extension modules in setup
              scripts


This module provides the :class:`Extension` class, used to describe C/C++
extension modules in setup scripts.

.. % \subsection{Ungrouped modules}
.. % The following haven't been moved into a more appropriate section yet.


:mod:`distutils.debug` --- Distutils debug mode
===============================================

.. module:: distutils.debug
   :synopsis: Provides the debug flag for distutils


This module provides the DEBUG flag.


:mod:`distutils.errors` --- Distutils exceptions
================================================

.. module:: distutils.errors
   :synopsis: Provides standard distutils exceptions


Provides exceptions used by the Distutils modules.  Note that Distutils modules
may raise standard exceptions; in particular, SystemExit is usually raised for
errors that are obviously the end-user's fault (eg. bad command-line arguments).

This module is safe to use in ``from ... import *`` mode; it only exports
symbols whose names start with ``Distutils`` and end with ``Error``.


:mod:`distutils.fancy_getopt` --- Wrapper around the standard getopt module
===========================================================================

.. module:: distutils.fancy_getopt
   :synopsis: Additional getopt functionality


This module provides a wrapper around the standard :mod:`getopt`  module that
provides the following additional features:

* short and long options are tied together

* options have help strings, so :func:`fancy_getopt` could potentially  create a
  complete usage summary

* options set attributes of a passed-in object

* boolean options can have "negative aliases" --- eg. if :option:`!--quiet` is
  the "negative alias" of :option:`!--verbose`, then :option:`!--quiet` on the
  command line sets *verbose* to false.


.. function:: fancy_getopt(options, negative_opt, object, args)

   Wrapper function. *options* is a list of ``(long_option, short_option,
   help_string)`` 3-tuples as described in the constructor for
   :class:`FancyGetopt`. *negative_opt* should be a dictionary mapping option names
   to option names, both the key and value should be in the *options* list.
   *object* is an object which will be used to store values (see the :meth:`getopt`
   method of the :class:`FancyGetopt` class). *args* is the argument list. Will use
   ``sys.argv[1:]`` if you  pass ``None`` as *args*.


.. function:: wrap_text(text, width)

   Wraps *text* to less than *width* wide.



.. class:: FancyGetopt([option_table=None])

   The option_table is a list of 3-tuples: ``(long_option, short_option,
   help_string)``

   If an option takes an argument, its *long_option* should have ``'='`` appended;
   *short_option* should just be a single character, no ``':'`` in any case.
   *short_option* should be ``None`` if a *long_option*  doesn't have a
   corresponding *short_option*. All option tuples must have long options.

The :class:`FancyGetopt` class provides the following methods:


.. method:: FancyGetopt.getopt([args=None, object=None])

   Parse command-line options in args. Store as attributes on *object*.

   If *args* is ``None`` or not supplied, uses ``sys.argv[1:]``.  If *object* is
   ``None`` or not supplied, creates a new :class:`OptionDummy` instance, stores
   option values there, and returns a tuple ``(args, object)``.  If *object* is
   supplied, it is modified in place and :func:`getopt` just returns *args*; in
   both cases, the returned *args* is a modified copy of the passed-in *args* list,
   which is left untouched.

   .. % and args returned are?


.. method:: FancyGetopt.get_option_order()

   Returns the list of ``(option, value)`` tuples processed by the previous run of
   :meth:`getopt`  Raises :exc:`RuntimeError` if :meth:`getopt` hasn't been called
   yet.


.. method:: FancyGetopt.generate_help([header=None])

   Generate help text (a list of strings, one per suggested line of output) from
   the option table for this :class:`FancyGetopt` object.

   If supplied, prints the supplied *header* at the top of the help.


:mod:`distutils.filelist` --- The FileList class
================================================

.. module:: distutils.filelist
   :synopsis: The FileList class, used for poking about the file system and
              building lists of files.


This module provides the :class:`FileList` class, used for poking about the
filesystem and building lists of files.


:mod:`distutils.log` --- Simple PEP 282-style logging
=====================================================

.. module:: distutils.log
   :synopsis: A simple logging mechanism, 282-style


:mod:`distutils.spawn` --- Spawn a sub-process
==============================================

.. module:: distutils.spawn
   :synopsis: Provides the spawn() function


This module provides the :func:`spawn` function, a front-end to  various
platform-specific functions for launching another program in a  sub-process.
Also provides :func:`find_executable` to search the path for a given executable
name.


:mod:`distutils.sysconfig` --- System configuration information
===============================================================

.. module:: distutils.sysconfig
   :synopsis: Low-level access to configuration information of the Python interpreter.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The :mod:`distutils.sysconfig` module provides access to Python's low-level
configuration information.  The specific configuration variables available
depend heavily on the platform and configuration. The specific variables depend
on the build process for the specific version of Python being run; the variables
are those found in the :file:`Makefile` and configuration header that are
installed with Python on Unix systems.  The configuration header is called
:file:`pyconfig.h` for Python versions starting with 2.2, and :file:`config.h`
for earlier versions of Python.

Some additional functions are provided which perform some useful manipulations
for other parts of the :mod:`distutils` package.


.. data:: PREFIX

   The result of ``os.path.normpath(sys.prefix)``.


.. data:: EXEC_PREFIX

   The result of ``os.path.normpath(sys.exec_prefix)``.


.. function:: get_config_var(name)

   Return the value of a single variable.  This is equivalent to
   ``get_config_vars().get(name)``.


.. function:: get_config_vars(...)

   Return a set of variable definitions.  If there are no arguments, this returns a
   dictionary mapping names of configuration variables to values.  If arguments are
   provided, they should be strings, and the return value will be a sequence giving
   the associated values. If a given name does not have a corresponding value,
   ``None`` will be included for that variable.


.. function:: get_config_h_filename()

   Return the full path name of the configuration header.  For Unix, this will be
   the header generated by the :program:`configure` script; for other platforms the
   header will have been supplied directly by the Python source distribution.  The
   file is a platform-specific text file.


.. function:: get_makefile_filename()

   Return the full path name of the :file:`Makefile` used to build Python.  For
   Unix, this will be a file generated by the :program:`configure` script; the
   meaning for other platforms will vary.  The file is a platform-specific text
   file, if it exists. This function is only useful on POSIX platforms.


.. function:: get_python_inc([plat_specific[, prefix]])

   Return the directory for either the general or platform-dependent C include
   files.  If *plat_specific* is true, the platform-dependent include directory is
   returned; if false or omitted, the platform-independent directory is returned.
   If *prefix* is given, it is used as either the prefix instead of
   :const:`PREFIX`, or as the exec-prefix instead of :const:`EXEC_PREFIX` if
   *plat_specific* is true.


.. function:: get_python_lib([plat_specific[, standard_lib[, prefix]]])

   Return the directory for either the general or platform-dependent library
   installation.  If *plat_specific* is true, the platform-dependent include
   directory is returned; if false or omitted, the platform-independent directory
   is returned.  If *prefix* is given, it is used as either the prefix instead of
   :const:`PREFIX`, or as the exec-prefix instead of :const:`EXEC_PREFIX` if
   *plat_specific* is true.  If *standard_lib* is true, the directory for the
   standard library is returned rather than the directory for the installation of
   third-party extensions.

The following function is only intended for use within the :mod:`distutils`
package.


.. function:: customize_compiler(compiler)

   Do any platform-specific customization of a
   :class:`distutils.ccompiler.CCompiler` instance.

   This function is only needed on Unix at this time, but should be called
   consistently to support forward-compatibility.  It inserts the information that
   varies across Unix flavors and is stored in Python's :file:`Makefile`.  This
   information includes the selected compiler, compiler and linker options, and the
   extension used by the linker for shared objects.

This function is even more special-purpose, and should only be used from
Python's own build procedures.


.. function:: set_python_build()

   Inform the :mod:`distutils.sysconfig` module that it is being used as part of
   the build process for Python.  This changes a lot of relative locations for
   files, allowing them to be located in the build area rather than in an installed
   Python.


:mod:`distutils.text_file` --- The TextFile class
=================================================

.. module:: distutils.text_file
   :synopsis: provides the TextFile class, a simple interface to text files


This module provides the :class:`TextFile` class, which gives an interface  to
text files that (optionally) takes care of stripping comments, ignoring  blank
lines, and joining lines with backslashes.


.. class:: TextFile([filename=None, file=None, **options])

   This class provides a file-like object that takes care of all  the things you
   commonly want to do when processing a text file  that has some line-by-line
   syntax: strip comments (as long as ``#``  is your comment character), skip blank
   lines, join adjacent lines by escaping the newline (ie. backslash at end of
   line), strip leading and/or trailing whitespace.  All of these are optional and
   independently controllable.

   The class provides a :meth:`warn` method so you can generate  warning messages
   that report physical line number, even if the  logical line in question spans
   multiple physical lines.  Also  provides :meth:`unreadline` for implementing
   line-at-a-time lookahead.

   :class:`TextFile` instances are create with either *filename*, *file*, or both.
   :exc:`RuntimeError` is raised if both are ``None``. *filename* should be a
   string, and *file* a file object (or something that provides :meth:`readline`
   and :meth:`close`  methods).  It is recommended that you supply at least
   *filename*,  so that :class:`TextFile` can include it in warning messages.  If
   *file* is not supplied, :class:`TextFile` creates its own using the
   :func:`open` built-in function.

   The options are all boolean, and affect the values returned by :meth:`readline`

   .. tabularcolumns:: |l|L|l|

   +------------------+--------------------------------+---------+
   | option name      | description                    | default |
   +==================+================================+=========+
   | *strip_comments* | strip from ``'#'`` to end-of-  | true    |
   |                  | line, as well as any           |         |
   |                  | whitespace leading up to the   |         |
   |                  | ``'#'``\ ---unless it is       |         |
   |                  | escaped by a backslash         |         |
   +------------------+--------------------------------+---------+
   | *lstrip_ws*      | strip leading whitespace from  | false   |
   |                  | each line before returning it  |         |
   +------------------+--------------------------------+---------+
   | *rstrip_ws*      | strip trailing whitespace      | true    |
   |                  | (including line terminator!)   |         |
   |                  | from each line before          |         |
   |                  | returning it.                  |         |
   +------------------+--------------------------------+---------+
   | *skip_blanks*    | skip lines that are empty      | true    |
   |                  | \*after\* stripping comments   |         |
   |                  | and whitespace.  (If both      |         |
   |                  | lstrip_ws and rstrip_ws are    |         |
   |                  | false, then some lines may     |         |
   |                  | consist of solely whitespace:  |         |
   |                  | these will \*not\* be skipped, |         |
   |                  | even if *skip_blanks* is       |         |
   |                  | true.)                         |         |
   +------------------+--------------------------------+---------+
   | *join_lines*     | if a backslash is the last     | false   |
   |                  | non-newline character on a     |         |
   |                  | line after stripping comments  |         |
   |                  | and whitespace, join the       |         |
   |                  | following line to it to form   |         |
   |                  | one logical line; if N         |         |
   |                  | consecutive lines end with a   |         |
   |                  | backslash, then N+1 physical   |         |
   |                  | lines will be joined to form   |         |
   |                  | one logical line.              |         |
   +------------------+--------------------------------+---------+
   | *collapse_join*  | strip leading whitespace from  | false   |
   |                  | lines that are joined to their |         |
   |                  | predecessor; only matters if   |         |
   |                  | ``(join_lines and not          |         |
   |                  | lstrip_ws)``                   |         |
   +------------------+--------------------------------+---------+

   Note that since *rstrip_ws* can strip the trailing newline, the semantics of
   :meth:`readline` must differ from those of the built-in file object's
   :meth:`readline` method!  In particular, :meth:`readline`  returns ``None`` for
   end-of-file: an empty string might just be a  blank line (or an all-whitespace
   line), if *rstrip_ws* is true  but *skip_blanks* is not.


   .. method:: TextFile.open(filename)

      Open a new file *filename*.  This overrides any *file* or *filename*
      constructor arguments.


   .. method:: TextFile.close()

      Close the current file and forget everything we know about it (including the
      filename and the current line number).


   .. method:: TextFile.warn(msg[,line=None])

      Print (to stderr) a warning message tied to the current logical line in the
      current file.  If the current logical line in the file spans multiple physical
      lines, the warning refers to the whole range, such as ``"lines 3-5"``.  If
      *line* is supplied,  it overrides the current line number; it may be a list or
      tuple  to indicate a range of physical lines, or an integer for a  single
      physical line.


   .. method:: TextFile.readline()

      Read and return a single logical line from the current file (or from an internal
      buffer if lines have previously been "unread" with :meth:`unreadline`).  If the
      *join_lines* option  is true, this may involve reading multiple physical lines
      concatenated into a single string.  Updates the current line number,  so calling
      :meth:`warn` after :meth:`readline` emits a warning  about the physical line(s)
      just read.  Returns ``None`` on end-of-file,  since the empty string can occur
      if *rstrip_ws* is true but  *strip_blanks* is not.


   .. method:: TextFile.readlines()

      Read and return the list of all logical lines remaining in the current file.
      This updates the current line number to the last line of the file.


   .. method:: TextFile.unreadline(line)

      Push *line* (a string) onto an internal buffer that will be checked by future
      :meth:`readline` calls.  Handy for implementing a parser with line-at-a-time
      lookahead. Note that lines that are "unread" with :meth:`unreadline` are not
      subsequently re-cleansed (whitespace  stripped, or whatever) when read with
      :meth:`readline`. If multiple calls are made to :meth:`unreadline` before a call
      to :meth:`readline`, the lines will be returned most in most recent first order.


:mod:`distutils.version` --- Version number classes
===================================================

.. module:: distutils.version
   :synopsis: implements classes that represent module version numbers.


.. % todo
.. % \section{Distutils Commands}
.. %
.. % This part of Distutils implements the various Distutils commands, such
.. % as \code{build}, \code{install} \&c. Each command is implemented as a
.. % separate module, with the command name as the name of the module.


:mod:`distutils.cmd` --- Abstract base class for Distutils commands
===================================================================

.. module:: distutils.cmd
   :synopsis: This module provides the abstract base class Command. This class
              is subclassed by the modules in the distutils.command subpackage.


This module supplies the abstract base class :class:`Command`.


.. class:: Command(dist)

   Abstract base class for defining command classes, the "worker bees" of the
   Distutils.  A useful analogy for command classes is to think of them as
   subroutines with local variables called *options*.  The options are declared
   in :meth:`initialize_options` and defined (given their final values) in
   :meth:`finalize_options`, both of which must be defined by every command
   class.  The distinction between the two is necessary because option values
   might come from the outside world (command line, config file, ...), and any
   options dependent on other options must be computed after these outside
   influences have been processed --- hence :meth:`finalize_options`.  The body
   of the subroutine, where it does all its work based on the values of its
   options, is the :meth:`run` method, which must also be implemented by every
   command class.

   The class constructor takes a single argument *dist*, a
   :class:`~distutils.core.Distribution` instance.


Creating a new Distutils command
================================

This section outlines the steps to create a new Distutils command.

A new command lives in a module in the :mod:`distutils.command` package. There
is a sample template in that directory called :file:`command_template`.  Copy
this file to a new module with the same name as the new command you're
implementing.  This module should implement a class with the same name as the
module (and the command).  So, for instance, to create the command
``peel_banana`` (so that users can run ``setup.py peel_banana``), you'd copy
:file:`command_template` to :file:`distutils/command/peel_banana.py`, then edit
it so that it's implementing the class :class:`peel_banana`, a subclass of
:class:`distutils.cmd.Command`.

Subclasses of :class:`Command` must define the following methods.

.. method:: Command.initialize_options()

   Set default values for all the options that this command supports.  Note that
   these defaults may be overridden by other commands, by the setup script, by
   config files, or by the command-line.  Thus, this is not the place to code
   dependencies between options; generally, :meth:`initialize_options`
   implementations are just a bunch of ``self.foo = None`` assignments.


.. method:: Command.finalize_options()

   Set final values for all the options that this command supports. This is
   always called as late as possible, ie.  after any option assignments from the
   command-line or from other commands have been done.  Thus, this is the place
   to code option dependencies: if *foo* depends on *bar*, then it is safe to
   set *foo* from *bar* as long as *foo* still has the same value it was
   assigned in :meth:`initialize_options`.


.. method:: Command.run()

   A command's raison d'etre: carry out the action it exists to perform, controlled
   by the options initialized in :meth:`initialize_options`, customized by other
   commands, the setup script, the command-line, and config files, and finalized in
   :meth:`finalize_options`.  All terminal output and filesystem interaction should
   be done by :meth:`run`.


.. attribute:: Command.sub_commands

   *sub_commands* formalizes the notion of a "family" of commands,
   e.g. ``install`` as the parent with sub-commands ``install_lib``,
   ``install_headers``, etc.  The parent of a family of commands defines
   *sub_commands* as a class attribute; it's a list of 2-tuples ``(command_name,
   predicate)``, with *command_name* a string and *predicate* a function, a
   string or ``None``.  *predicate* is a method of the parent command that
   determines whether the corresponding command is applicable in the current
   situation.  (E.g. ``install_headers`` is only applicable if we have any C
   header files to install.)  If *predicate* is ``None``, that command is always
   applicable.

   *sub_commands* is usually defined at the *end* of a class, because
   predicates can be methods of the class, so they must already have been
   defined.  The canonical example is the :command:`install` command.


:mod:`distutils.command` --- Individual Distutils commands
==========================================================

.. module:: distutils.command
   :synopsis: This subpackage contains one module for each standard Distutils command.


.. % \subsubsection{Individual Distutils commands}
.. % todo


:mod:`distutils.command.bdist` --- Build a binary installer
===========================================================

.. module:: distutils.command.bdist
   :synopsis: Build a binary installer for a package


.. % todo


:mod:`distutils.command.bdist_packager` --- Abstract base class for packagers
=============================================================================

.. module:: distutils.command.bdist_packager
   :synopsis: Abstract base class for packagers


.. % todo


:mod:`distutils.command.bdist_dumb` --- Build a "dumb" installer
================================================================

.. module:: distutils.command.bdist_dumb
   :synopsis: Build a "dumb" installer - a simple archive of files


.. % todo


:mod:`distutils.command.bdist_msi` --- Build a Microsoft Installer binary package
=================================================================================

.. module:: distutils.command.bdist_msi
   :synopsis: Build a binary distribution as a Windows MSI file

.. class:: bdist_msi

   Builds a `Windows Installer`_ (.msi) binary package.

   .. _Windows Installer: https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx

   In most cases, the ``bdist_msi`` installer is a better choice than the
   ``bdist_wininst`` installer, because it provides better support for
   Win64 platforms, allows administrators to perform non-interactive
   installations, and allows installation through group policies.


:mod:`distutils.command.bdist_rpm` --- Build a binary distribution as a Redhat RPM and SRPM
===========================================================================================

.. module:: distutils.command.bdist_rpm
   :synopsis: Build a binary distribution as a Redhat RPM and SRPM


.. % todo


:mod:`distutils.command.bdist_wininst` --- Build a Windows installer
====================================================================

.. module:: distutils.command.bdist_wininst
   :synopsis: Build a Windows installer


.. % todo


:mod:`distutils.command.sdist` --- Build a source distribution
==============================================================

.. module:: distutils.command.sdist
   :synopsis: Build a source distribution


.. % todo


:mod:`distutils.command.build` --- Build all files of a package
===============================================================

.. module:: distutils.command.build
   :synopsis: Build all files of a package


.. % todo


:mod:`distutils.command.build_clib` --- Build any C libraries in a package
==========================================================================

.. module:: distutils.command.build_clib
   :synopsis: Build any C libraries in a package


.. % todo


:mod:`distutils.command.build_ext` --- Build any extensions in a package
========================================================================

.. module:: distutils.command.build_ext
   :synopsis: Build any extensions in a package


.. % todo


:mod:`distutils.command.build_py` --- Build the .py/.pyc files of a package
===========================================================================

.. module:: distutils.command.build_py
   :synopsis: Build the .py/.pyc files of a package


:mod:`distutils.command.build_scripts` --- Build the scripts of a package
=========================================================================

.. module:: distutils.command.build_scripts
   :synopsis: Build the scripts of a package


.. % todo


:mod:`distutils.command.clean` --- Clean a package build area
=============================================================

.. module:: distutils.command.clean
   :synopsis: Clean a package build area

This command removes the temporary files created by :command:`build`
and its subcommands, like intermediary compiled object files.  With
the ``--all`` option, the complete build directory will be removed.

Extension modules built :ref:`in place <distutils-build-ext-inplace>`
will not be cleaned, as they are not in the build directory.


:mod:`distutils.command.config` --- Perform package configuration
=================================================================

.. module:: distutils.command.config
   :synopsis: Perform package configuration


.. % todo


:mod:`distutils.command.install` --- Install a package
======================================================

.. module:: distutils.command.install
   :synopsis: Install a package


.. % todo


:mod:`distutils.command.install_data` --- Install data files from a package
===========================================================================

.. module:: distutils.command.install_data
   :synopsis: Install data files from a package


.. % todo


:mod:`distutils.command.install_headers` --- Install C/C++ header files from a package
======================================================================================

.. module:: distutils.command.install_headers
   :synopsis: Install C/C++ header files from a package


.. % todo


:mod:`distutils.command.install_lib` --- Install library files from a package
=============================================================================

.. module:: distutils.command.install_lib
   :synopsis: Install library files from a package


.. % todo


:mod:`distutils.command.install_scripts` --- Install script files from a package
================================================================================

.. module:: distutils.command.install_scripts
   :synopsis: Install script files from a package


.. % todo


:mod:`distutils.command.register` --- Register a module with the Python Package Index
=====================================================================================

.. module:: distutils.command.register
   :synopsis: Register a module with the Python Package Index


The ``register`` command registers the package with the Python Package  Index.
This is described in more detail in :pep:`301`.

.. % todo


:mod:`distutils.command.check` --- Check the meta-data of a package
===================================================================

.. module:: distutils.command.check
   :synopsis: Check the metadata of a package


The ``check`` command performs some tests on the meta-data of a package.
For example, it verifies that all required meta-data are provided as
the arguments passed to the :func:`setup` function.

.. % todo
PK	%�\'7�IfVfV)html/_sources/distutils/builtdist.rst.txtnu�[���.. _built-dist:

****************************
Creating Built Distributions
****************************

A "built distribution" is what you're probably used to thinking of either as a
"binary package" or an "installer" (depending on your background).  It's not
necessarily binary, though, because it might contain only Python source code
and/or byte-code; and we don't call it a package, because that word is already
spoken for in Python.  (And "installer" is a term specific to the world of
mainstream desktop systems.)

A built distribution is how you make life as easy as possible for installers of
your module distribution: for users of RPM-based Linux systems, it's a binary
RPM; for Windows users, it's an executable installer; for Debian-based Linux
users, it's a Debian package; and so forth.  Obviously, no one person will be
able to create built distributions for every platform under the sun, so the
Distutils are designed to enable module developers to concentrate on their
specialty---writing code and creating source distributions---while an
intermediary species called *packagers* springs up to turn source distributions
into built distributions for as many platforms as there are packagers.

Of course, the module developer could be their own packager; or the packager could
be a volunteer "out there" somewhere who has access to a platform which the
original developer does not; or it could be software periodically grabbing new
source distributions and turning them into built distributions for as many
platforms as the software has access to.  Regardless of who they are, a packager
uses the setup script and the :command:`bdist` command family to generate built
distributions.

As a simple example, if I run the following command in the Distutils source
tree::

   python setup.py bdist

then the Distutils builds my module distribution (the Distutils itself in this
case), does a "fake" installation (also in the :file:`build` directory), and
creates the default type of built distribution for my platform.  The default
format for built distributions is a "dumb" tar file on Unix, and a simple
executable installer on Windows.  (That tar file is considered "dumb" because it
has to be unpacked in a specific location to work.)

Thus, the above command on a Unix system creates
:file:`Distutils-1.0.{plat}.tar.gz`; unpacking this tarball from the right place
installs the Distutils just as though you had downloaded the source distribution
and run ``python setup.py install``.  (The "right place" is either the root of
the filesystem or  Python's :file:`{prefix}` directory, depending on the options
given to the :command:`bdist_dumb` command; the default is to make dumb
distributions relative to :file:`{prefix}`.)

Obviously, for pure Python distributions, this isn't any simpler than just
running ``python setup.py install``\ ---but for non-pure distributions, which
include extensions that would need to be compiled, it can mean the difference
between someone being able to use your extensions or not.  And creating "smart"
built distributions, such as an RPM package or an executable installer for
Windows, is far more convenient for users even if your distribution doesn't
include any extensions.

The :command:`bdist` command has a :option:`!--formats` option, similar to the
:command:`sdist` command, which you can use to select the types of built
distribution to generate: for example, ::

   python setup.py bdist --format=zip

would, when run on a Unix system, create :file:`Distutils-1.0.{plat}.zip`\
---again, this archive would be unpacked from the root directory to install the
Distutils.

The available formats for built distributions are:

+-------------+------------------------------+---------+
| Format      | Description                  | Notes   |
+=============+==============================+=========+
| ``gztar``   | gzipped tar file             | (1),(3) |
|             | (:file:`.tar.gz`)            |         |
+-------------+------------------------------+---------+
| ``ztar``    | compressed tar file          | \(3)    |
|             | (:file:`.tar.Z`)             |         |
+-------------+------------------------------+---------+
| ``tar``     | tar file (:file:`.tar`)      | \(3)    |
+-------------+------------------------------+---------+
| ``zip``     | zip file (:file:`.zip`)      | (2),(4) |
+-------------+------------------------------+---------+
| ``rpm``     | RPM                          | \(5)    |
+-------------+------------------------------+---------+
| ``pkgtool`` | Solaris :program:`pkgtool`   |         |
+-------------+------------------------------+---------+
| ``sdux``    | HP-UX :program:`swinstall`   |         |
+-------------+------------------------------+---------+
| ``wininst`` | self-extracting ZIP file for | \(4)    |
|             | Windows                      |         |
+-------------+------------------------------+---------+
| ``msi``     | Microsoft Installer.         |         |
+-------------+------------------------------+---------+


Notes:

(1)
   default on Unix

(2)
   default on Windows

(3)
   requires external utilities: :program:`tar` and possibly one of :program:`gzip`,
   :program:`bzip2`, or :program:`compress`

(4)
   requires either external :program:`zip` utility or :mod:`zipfile` module (part
   of the standard Python library since Python 1.6)

(5)
   requires external :program:`rpm` utility, version 3.0.4 or better (use ``rpm
   --version`` to find out which version you have)

You don't have to use the :command:`bdist` command with the :option:`!--formats`
option; you can also use the command that directly implements the format you're
interested in.  Some of these :command:`bdist` "sub-commands" actually generate
several similar formats; for instance, the :command:`bdist_dumb` command
generates all the "dumb" archive formats (``tar``, ``ztar``, ``gztar``, and
``zip``), and :command:`bdist_rpm` generates both binary and source RPMs.  The
:command:`bdist` sub-commands, and the formats generated by each, are:

+--------------------------+-----------------------+
| Command                  | Formats               |
+==========================+=======================+
| :command:`bdist_dumb`    | tar, ztar, gztar, zip |
+--------------------------+-----------------------+
| :command:`bdist_rpm`     | rpm, srpm             |
+--------------------------+-----------------------+
| :command:`bdist_wininst` | wininst               |
+--------------------------+-----------------------+
| :command:`bdist_msi`     | msi                   |
+--------------------------+-----------------------+

The following sections give details on the individual :command:`bdist_\*`
commands.


.. _creating-dumb:

Creating dumb built distributions
=================================

.. XXX Need to document absolute vs. prefix-relative packages here, but first
       I have to implement it!


.. _creating-rpms:

Creating RPM packages
=====================

The RPM format is used by many popular Linux distributions, including Red Hat,
SuSE, and Mandrake.  If one of these (or any of the other RPM-based Linux
distributions) is your usual environment, creating RPM packages for other users
of that same distribution is trivial. Depending on the complexity of your module
distribution and differences between Linux distributions, you may also be able
to create RPMs that work on different RPM-based distributions.

The usual way to create an RPM of your module distribution is to run the
:command:`bdist_rpm` command::

   python setup.py bdist_rpm

or the :command:`bdist` command with the :option:`!--format` option::

   python setup.py bdist --formats=rpm

The former allows you to specify RPM-specific options; the latter allows  you to
easily specify multiple formats in one run.  If you need to do both, you can
explicitly specify multiple :command:`bdist_\*` commands and their options::

   python setup.py bdist_rpm --packager="John Doe <jdoe@example.org>" \
                   bdist_wininst --target-version="2.0"

Creating RPM packages is driven by a :file:`.spec` file, much as using the
Distutils is driven by the setup script.  To make your life easier, the
:command:`bdist_rpm` command normally creates a :file:`.spec` file based on the
information you supply in the setup script, on the command line, and in any
Distutils configuration files.  Various options and sections in the
:file:`.spec` file are derived from options in the setup script as follows:

+------------------------------------------+----------------------------------------------+
| RPM :file:`.spec` file option or section | Distutils setup script option                |
+==========================================+==============================================+
| Name                                     | ``name``                                     |
+------------------------------------------+----------------------------------------------+
| Summary (in preamble)                    | ``description``                              |
+------------------------------------------+----------------------------------------------+
| Version                                  | ``version``                                  |
+------------------------------------------+----------------------------------------------+
| Vendor                                   | ``author`` and ``author_email``,             |
|                                          | or  --- & ``maintainer`` and                 |
|                                          | ``maintainer_email``                         |
+------------------------------------------+----------------------------------------------+
| Copyright                                | ``license``                                  |
+------------------------------------------+----------------------------------------------+
| Url                                      | ``url``                                      |
+------------------------------------------+----------------------------------------------+
| %description (section)                   | ``long_description``                         |
+------------------------------------------+----------------------------------------------+

Additionally, there are many options in :file:`.spec` files that don't have
corresponding options in the setup script.  Most of these are handled through
options to the :command:`bdist_rpm` command as follows:

+-------------------------------+-----------------------------+-------------------------+
| RPM :file:`.spec` file option | :command:`bdist_rpm` option | default value           |
| or section                    |                             |                         |
+===============================+=============================+=========================+
| Release                       | ``release``                 | "1"                     |
+-------------------------------+-----------------------------+-------------------------+
| Group                         | ``group``                   | "Development/Libraries" |
+-------------------------------+-----------------------------+-------------------------+
| Vendor                        | ``vendor``                  | (see above)             |
+-------------------------------+-----------------------------+-------------------------+
| Packager                      | ``packager``                | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Provides                      | ``provides``                | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Requires                      | ``requires``                | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Conflicts                     | ``conflicts``               | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Obsoletes                     | ``obsoletes``               | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Distribution                  | ``distribution_name``       | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| BuildRequires                 | ``build_requires``          | (none)                  |
+-------------------------------+-----------------------------+-------------------------+
| Icon                          | ``icon``                    | (none)                  |
+-------------------------------+-----------------------------+-------------------------+

Obviously, supplying even a few of these options on the command-line would be
tedious and error-prone, so it's usually best to put them in the setup
configuration file, :file:`setup.cfg`\ ---see section :ref:`setup-config`.  If
you distribute or package many Python module distributions, you might want to
put options that apply to all of them in your personal Distutils configuration
file (:file:`~/.pydistutils.cfg`).  If you want to temporarily disable
this file, you can pass the --no-user-cfg option to setup.py.

There are three steps to building a binary RPM package, all of which are
handled automatically by the Distutils:

#. create a :file:`.spec` file, which describes the package (analogous  to the
   Distutils setup script; in fact, much of the information in the  setup script
   winds up in the :file:`.spec` file)

#. create the source RPM

#. create the "binary" RPM (which may or may not contain binary code, depending
   on whether your module distribution contains Python extensions)

Normally, RPM bundles the last two steps together; when you use the Distutils,
all three steps are typically bundled together.

If you wish, you can separate these three steps.  You can use the
:option:`!--spec-only` option to make :command:`bdist_rpm` just create the
:file:`.spec` file and exit; in this case, the :file:`.spec` file will be
written to the "distribution directory"---normally :file:`dist/`, but
customizable with the :option:`!--dist-dir` option.  (Normally, the :file:`.spec`
file winds up deep in the "build tree," in a temporary directory created by
:command:`bdist_rpm`.)

.. % \XXX{this isn't implemented yet---is it needed?!}
.. % You can also specify a custom \file{.spec} file with the
.. % \longprogramopt{spec-file} option; used in conjunction with
.. % \longprogramopt{spec-only}, this gives you an opportunity to customize
.. % the \file{.spec} file manually:
.. %
.. % \ begin{verbatim}
.. % > python setup.py bdist_rpm --spec-only
.. % # ...edit dist/FooBar-1.0.spec
.. % > python setup.py bdist_rpm --spec-file=dist/FooBar-1.0.spec
.. % \ end{verbatim}
.. %
.. % (Although a better way to do this is probably to override the standard
.. % \command{bdist\_rpm} command with one that writes whatever else you want
.. % to the \file{.spec} file.)


.. _creating-wininst:

Creating Windows Installers
===========================

Executable installers are the natural format for binary distributions on
Windows.  They display a nice graphical user interface, display some information
about the module distribution to be installed taken from the metadata in the
setup script, let the user select a few options, and start or cancel the
installation.

Since the metadata is taken from the setup script, creating Windows installers
is usually as easy as running::

   python setup.py bdist_wininst

or the :command:`bdist` command with the :option:`!--formats` option::

   python setup.py bdist --formats=wininst

If you have a pure module distribution (only containing pure Python modules and
packages), the resulting installer will be version independent and have a name
like :file:`foo-1.0.win32.exe`.  These installers can even be created on Unix
platforms or Mac OS X.

If you have a non-pure distribution, the extensions can only be created on a
Windows platform, and will be Python version dependent. The installer filename
will reflect this and now has the form :file:`foo-1.0.win32-py2.0.exe`.  You
have to create a separate installer for every Python version you want to
support.

The installer will try to compile pure modules into :term:`bytecode` after installation
on the target system in normal and optimizing mode.  If you don't want this to
happen for some reason, you can run the :command:`bdist_wininst` command with
the :option:`!--no-target-compile` and/or the :option:`!--no-target-optimize`
option.

By default the installer will display the cool "Python Powered" logo when it is
run, but you can also supply your own 152x261 bitmap which must be a Windows
:file:`.bmp` file with the :option:`!--bitmap` option.

The installer will also display a large title on the desktop background window
when it is run, which is constructed from the name of your distribution and the
version number.  This can be changed to another text by using the
:option:`!--title` option.

The installer file will be written to the "distribution directory" --- normally
:file:`dist/`, but customizable with the :option:`!--dist-dir` option.

.. _cross-compile-windows:

Cross-compiling on Windows
==========================

Starting with Python 2.6, distutils is capable of cross-compiling between
Windows platforms.  In practice, this means that with the correct tools
installed, you can use a 32bit version of Windows to create 64bit extensions
and vice-versa.

To build for an alternate platform, specify the :option:`!--plat-name` option
to the build command.  Valid values are currently 'win32', 'win-amd64' and
'win-ia64'.  For example, on a 32bit version of Windows, you could execute::

   python setup.py build --plat-name=win-amd64

to build a 64bit version of your extension.  The Windows Installers also
support this option, so the command::

   python setup.py build --plat-name=win-amd64 bdist_wininst

would create a 64bit installation executable on your 32bit version of Windows.

To cross-compile, you must download the Python source code and cross-compile
Python itself for the platform you are targeting - it is not possible from a
binary installation of Python (as the .lib etc file for other platforms are
not included.)  In practice, this means the user of a 32 bit operating
system will need to use Visual Studio 2008 to open the
:file:`PCBuild/PCbuild.sln` solution in the Python source tree and build the
"x64" configuration of the 'pythoncore' project before cross-compiling
extensions is possible.

Note that by default, Visual Studio 2008 does not install 64bit compilers or
tools.  You may need to reexecute the Visual Studio setup process and select
these tools (using Control Panel->[Add/Remove] Programs is a convenient way to
check or modify your existing install.)

.. _postinstallation-script:

The Postinstallation script
---------------------------

Starting with Python 2.3, a postinstallation script can be specified with the
:option:`!--install-script` option.  The basename of the script must be
specified, and the script filename must also be listed in the scripts argument
to the setup function.

This script will be run at installation time on the target system after all the
files have been copied, with ``argv[1]`` set to :option:`!-install`, and again at
uninstallation time before the files are removed with ``argv[1]`` set to
:option:`!-remove`.

The installation script runs embedded in the windows installer, every output
(``sys.stdout``, ``sys.stderr``) is redirected into a buffer and will be
displayed in the GUI after the script has finished.

Some functions especially useful in this context are available as additional
built-in functions in the installation script.


.. function:: directory_created(path)
              file_created(path)

   These functions should be called when a directory or file is created by the
   postinstall script at installation time.  It will register *path* with the
   uninstaller, so that it will be removed when the distribution is uninstalled.
   To be safe, directories are only removed if they are empty.


.. function:: get_special_folder_path(csidl_string)

   This function can be used to retrieve special folder locations on Windows like
   the Start Menu or the Desktop.  It returns the full path to the folder.
   *csidl_string* must be one of the following strings::

      "CSIDL_APPDATA"

      "CSIDL_COMMON_STARTMENU"
      "CSIDL_STARTMENU"

      "CSIDL_COMMON_DESKTOPDIRECTORY"
      "CSIDL_DESKTOPDIRECTORY"

      "CSIDL_COMMON_STARTUP"
      "CSIDL_STARTUP"

      "CSIDL_COMMON_PROGRAMS"
      "CSIDL_PROGRAMS"

      "CSIDL_FONTS"

   If the folder cannot be retrieved, :exc:`OSError` is raised.

   Which folders are available depends on the exact Windows version, and probably
   also the configuration.  For details refer to Microsoft's documentation of the
   :c:func:`SHGetSpecialFolderPath` function.


.. function:: create_shortcut(target, description, filename[, arguments[, workdir[, iconpath[, iconindex]]]])

   This function creates a shortcut. *target* is the path to the program to be
   started by the shortcut. *description* is the description of the shortcut.
   *filename* is the title of the shortcut that the user will see. *arguments*
   specifies the command line arguments, if any. *workdir* is the working directory
   for the program. *iconpath* is the file containing the icon for the shortcut,
   and *iconindex* is the index of the icon in the file *iconpath*.  Again, for
   details consult the Microsoft documentation for the :class:`IShellLink`
   interface.


Vista User Access Control (UAC)
===============================

Starting with Python 2.6, bdist_wininst supports a :option:`!--user-access-control`
option.  The default is 'none' (meaning no UAC handling is done), and other
valid values are 'auto' (meaning prompt for UAC elevation if Python was
installed for all users) and 'force' (meaning always prompt for elevation).
PK	%�\ �F`*html/_sources/distutils/commandref.rst.txtnu�[���.. _reference:

*****************
Command Reference
*****************

.. % \section{Building modules: the \protect\command{build} command family}
.. % \label{build-cmds}
.. % \subsubsection{\protect\command{build}}
.. % \label{build-cmd}
.. % \subsubsection{\protect\command{build\_py}}
.. % \label{build-py-cmd}
.. % \subsubsection{\protect\command{build\_ext}}
.. % \label{build-ext-cmd}
.. % \subsubsection{\protect\command{build\_clib}}
.. % \label{build-clib-cmd}


.. _install-cmd:

Installing modules: the :command:`install` command family
=========================================================

The install command ensures that the build commands have been run and then runs
the subcommands :command:`install_lib`, :command:`install_data` and
:command:`install_scripts`.

.. % \subsubsection{\protect\command{install\_lib}}
.. % \label{install-lib-cmd}


.. _install-data-cmd:

:command:`install_data`
-----------------------

This command installs all data files provided with the distribution.


.. _install-scripts-cmd:

:command:`install_scripts`
--------------------------

This command installs all (Python) scripts in the distribution.

.. % \subsection{Cleaning up: the \protect\command{clean} command}
.. % \label{clean-cmd}


.. % \section{Creating a built distribution: the
.. % \protect\command{bdist} command family}
.. % \label{bdist-cmds}

.. % \subsection{\protect\command{bdist}}
.. % \subsection{\protect\command{bdist\_dumb}}
.. % \subsection{\protect\command{bdist\_rpm}}
.. % \subsection{\protect\command{bdist\_wininst}}


PK	%�\U'HI*html/_sources/distutils/configfile.rst.txtnu�[���.. _setup-config:

************************************
Writing the Setup Configuration File
************************************

Often, it's not possible to write down everything needed to build a distribution
*a priori*: you may need to get some information from the user, or from the
user's system, in order to proceed.  As long as that information is fairly
simple---a list of directories to search for C header files or libraries, for
example---then providing a configuration file, :file:`setup.cfg`, for users to
edit is a cheap and easy way to solicit it.  Configuration files also let you
provide default values for any command option, which the installer can then
override either on the command-line or by editing the config file.

The setup configuration file is a useful middle-ground between the setup script
---which, ideally, would be opaque to installers [#]_---and the command-line to
the setup script, which is outside of your control and entirely up to the
installer.  In fact, :file:`setup.cfg` (and any other Distutils configuration
files present on the target system) are processed after the contents of the
setup script, but before the command-line.  This has  several useful
consequences:

.. % (If you have more advanced needs, such as determining which extensions
.. % to build based on what capabilities are present on the target system,
.. % then you need the Distutils ``auto-configuration'' facility.  This
.. % started to appear in Distutils 0.9 but, as of this writing, isn't mature
.. % or stable enough yet for real-world use.)

* installers can override some of what you put in :file:`setup.py` by editing
  :file:`setup.cfg`

* you can provide non-standard defaults for options that are not easily set in
  :file:`setup.py`

* installers can override anything in :file:`setup.cfg` using the command-line
  options to :file:`setup.py`

The basic syntax of the configuration file is simple::

   [command]
   option=value
   ...

where *command* is one of the Distutils commands (e.g. :command:`build_py`,
:command:`install`), and *option* is one of the options that command supports.
Any number of options can be supplied for each command, and any number of
command sections can be included in the file.  Blank lines are ignored, as are
comments, which run from a ``'#'`` character until the end of the line.  Long
option values can be split across multiple lines simply by indenting the
continuation lines.

You can find out the list of options supported by a particular command with the
universal :option:`!--help` option, e.g. ::

   > python setup.py --help build_ext
   [...]
   Options for 'build_ext' command:
     --build-lib (-b)     directory for compiled extension modules
     --build-temp (-t)    directory for temporary files (build by-products)
     --inplace (-i)       ignore build-lib and put compiled extensions into the
                          source directory alongside your pure Python modules
     --include-dirs (-I)  list of directories to search for header files
     --define (-D)        C preprocessor macros to define
     --undef (-U)         C preprocessor macros to undefine
     --swig-opts          list of SWIG command line options
   [...]

Note that an option spelled :option:`!--foo-bar` on the command-line  is spelled
``foo_bar`` in configuration files.

.. _distutils-build-ext-inplace:

For example, say you want your extensions to be built "in-place"---that is, you
have an extension :mod:`pkg.ext`, and you want the compiled extension file
(:file:`ext.so` on Unix, say) to be put in the same source directory as your
pure Python modules :mod:`pkg.mod1` and :mod:`pkg.mod2`.  You can always use the
:option:`!--inplace` option on the command-line to ensure this::

   python setup.py build_ext --inplace

But this requires that you always specify the :command:`build_ext` command
explicitly, and remember to provide :option:`!--inplace`. An easier way is to
"set and forget" this option, by encoding it in :file:`setup.cfg`, the
configuration file for this distribution::

   [build_ext]
   inplace=1

This will affect all builds of this module distribution, whether or not you
explicitly specify :command:`build_ext`.  If you include :file:`setup.cfg` in
your source distribution, it will also affect end-user builds---which is
probably a bad idea for this option, since always building extensions in-place
would break installation of the module distribution.  In certain peculiar cases,
though, modules are built right in their installation directory, so this is
conceivably a useful ability.  (Distributing extensions that expect to be built
in their installation directory is almost always a bad idea, though.)

Another example: certain commands take a lot of options that don't change from
run to run; for example, :command:`bdist_rpm` needs to know everything required
to generate a "spec" file for creating an RPM distribution.  Some of this
information comes from the setup script, and some is automatically generated by
the Distutils (such as the list of files installed).  But some of it has to be
supplied as options to :command:`bdist_rpm`, which would be very tedious to do
on the command-line for every run.  Hence, here is a snippet from the Distutils'
own :file:`setup.cfg`::

   [bdist_rpm]
   release = 1
   packager = Greg Ward <gward@python.net>
   doc_files = CHANGES.txt
               README.txt
               USAGE.txt
               doc/
               examples/

Note that the ``doc_files`` option is simply a whitespace-separated string
split across multiple lines for readability.


.. seealso::

   :ref:`inst-config-syntax` in "Installing Python Modules"
      More information on the configuration files is available in the manual for
      system administrators.


.. rubric:: Footnotes

.. [#] This ideal probably won't be achieved until auto-configuration is fully
   supported by the Distutils.

PK	%�\$��ZZ(html/_sources/distutils/examples.rst.txtnu�[���.. _examples:

********
Examples
********

This chapter provides a number of basic examples to help get started with
distutils.  Additional information about using distutils can be found in the
Distutils Cookbook.


.. seealso::

   `Distutils Cookbook <https://wiki.python.org/moin/Distutils/Cookbook>`_
      Collection of recipes showing how to achieve more control over distutils.


.. _pure-mod:

Pure Python distribution (by module)
====================================

If you're just distributing a couple of modules, especially if they don't live
in a particular package, you can specify them individually using the
``py_modules`` option in the setup script.

In the simplest case, you'll have two files to worry about: a setup script and
the single module you're distributing, :file:`foo.py` in this example::

   <root>/
           setup.py
           foo.py

(In all diagrams in this section, *<root>* will refer to the distribution root
directory.)  A minimal setup script to describe this situation would be::

   from distutils.core import setup
   setup(name='foo',
         version='1.0',
         py_modules=['foo'],
         )

Note that the name of the distribution is specified independently with the
``name`` option, and there's no rule that says it has to be the same as
the name of the sole module in the distribution (although that's probably a good
convention to follow).  However, the distribution name is used to generate
filenames, so you should stick to letters, digits, underscores, and hyphens.

Since ``py_modules`` is a list, you can of course specify multiple
modules, eg. if you're distributing modules :mod:`foo` and :mod:`bar`, your
setup might look like this::

   <root>/
           setup.py
           foo.py
           bar.py

and the setup script might be  ::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         py_modules=['foo', 'bar'],
         )

You can put module source files into another directory, but if you have enough
modules to do that, it's probably easier to specify modules by package rather
than listing them individually.


.. _pure-pkg:

Pure Python distribution (by package)
=====================================

If you have more than a couple of modules to distribute, especially if they are
in multiple packages, it's probably easier to specify whole packages rather than
individual modules.  This works even if your modules are not in a package; you
can just tell the Distutils to process modules from the root package, and that
works the same as any other package (except that you don't have to have an
:file:`__init__.py` file).

The setup script from the last example could also be written as  ::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         packages=[''],
         )

(The empty string stands for the root package.)

If those two files are moved into a subdirectory, but remain in the root
package, e.g.::

   <root>/
           setup.py
           src/      foo.py
                     bar.py

then you would still specify the root package, but you have to tell the
Distutils where source files in the root package live::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         package_dir={'': 'src'},
         packages=[''],
         )

More typically, though, you will want to distribute multiple modules in the same
package (or in sub-packages).  For example, if the :mod:`foo`  and :mod:`bar`
modules belong in package :mod:`foobar`, one way to layout your source tree is
::

   <root>/
           setup.py
           foobar/
                    __init__.py
                    foo.py
                    bar.py

This is in fact the default layout expected by the Distutils, and the one that
requires the least work to describe in your setup script::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         packages=['foobar'],
         )

If you want to put modules in directories not named for their package, then you
need to use the ``package_dir`` option again.  For example, if the
:file:`src` directory holds modules in the :mod:`foobar` package::

   <root>/
           setup.py
           src/
                    __init__.py
                    foo.py
                    bar.py

an appropriate setup script would be  ::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         package_dir={'foobar': 'src'},
         packages=['foobar'],
         )

Or, you might put modules from your main package right in the distribution
root::

   <root>/
           setup.py
           __init__.py
           foo.py
           bar.py

in which case your setup script would be  ::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         package_dir={'foobar': ''},
         packages=['foobar'],
         )

(The empty string also stands for the current directory.)

If you have sub-packages, they must be explicitly listed in ``packages``,
but any entries in ``package_dir`` automatically extend to sub-packages.
(In other words, the Distutils does *not* scan your source tree, trying to
figure out which directories correspond to Python packages by looking for
:file:`__init__.py` files.)  Thus, if the default layout grows a sub-package::

   <root>/
           setup.py
           foobar/
                    __init__.py
                    foo.py
                    bar.py
                    subfoo/
                              __init__.py
                              blah.py

then the corresponding setup script would be  ::

   from distutils.core import setup
   setup(name='foobar',
         version='1.0',
         packages=['foobar', 'foobar.subfoo'],
         )


.. _single-ext:

Single extension module
=======================

Extension modules are specified using the ``ext_modules`` option.
``package_dir`` has no effect on where extension source files are found;
it only affects the source for pure Python modules.  The simplest  case, a
single extension module in a single C source file, is::

   <root>/
           setup.py
           foo.c

If the :mod:`foo` extension belongs in the root package, the setup script for
this could be  ::

   from distutils.core import setup
   from distutils.extension import Extension
   setup(name='foobar',
         version='1.0',
         ext_modules=[Extension('foo', ['foo.c'])],
         )

If the extension actually belongs in a package, say :mod:`foopkg`, then

With exactly the same source tree layout, this extension can be put in the
:mod:`foopkg` package simply by changing the name of the extension::

   from distutils.core import setup
   from distutils.extension import Extension
   setup(name='foobar',
         version='1.0',
         ext_modules=[Extension('foopkg.foo', ['foo.c'])],
         )

.. % \section{Multiple extension modules}
.. % \label{multiple-ext}

.. % \section{Putting it all together}


PK	%�\cG���)html/_sources/distutils/extending.rst.txtnu�[���.. _extending-distutils:

*******************
Extending Distutils
*******************

Distutils can be extended in various ways.  Most extensions take the form of new
commands or replacements for existing commands.  New commands may be written to
support new types of platform-specific packaging, for example, while
replacements for existing commands may be made to modify details of how the
command operates on a package.

Most extensions of the distutils are made within :file:`setup.py` scripts that
want to modify existing commands; many simply add a few file extensions that
should be copied into packages in addition to :file:`.py` files as a
convenience.

Most distutils command implementations are subclasses of the
:class:`distutils.cmd.Command` class.  New commands may directly inherit from
:class:`Command`, while replacements often derive from :class:`Command`
indirectly, directly subclassing the command they are replacing.  Commands are
required to derive from :class:`Command`.

.. % \section{Extending existing commands}
.. % \label{extend-existing}

.. % \section{Writing new commands}
.. % \label{new-commands}
.. % \XXX{Would an uninstall command be a good example here?}


Integrating new commands
========================

There are different ways to integrate new command implementations into
distutils.  The most difficult is to lobby for the inclusion of the new features
in distutils itself, and wait for (and require) a version of Python that
provides that support.  This is really hard for many reasons.

The most common, and possibly the most reasonable for most needs, is to include
the new implementations with your :file:`setup.py` script, and cause the
:func:`distutils.core.setup` function use them::

   from distutils.command.build_py import build_py as _build_py
   from distutils.core import setup

   class build_py(_build_py):
       """Specialized Python source builder."""

       # implement whatever needs to be different...

   setup(cmdclass={'build_py': build_py},
         ...)

This approach is most valuable if the new implementations must be used to use a
particular package, as everyone interested in the package will need to have the
new command implementation.

Beginning with Python 2.4, a third option is available, intended to allow new
commands to be added which can support existing :file:`setup.py` scripts without
requiring modifications to the Python installation.  This is expected to allow
third-party extensions to provide support for additional packaging systems, but
the commands can be used for anything distutils commands can be used for.  A new
configuration option, ``command_packages`` (command-line option
:option:`!--command-packages`), can be used to specify additional packages to be
searched for modules implementing commands.  Like all distutils options, this
can be specified on the command line or in a configuration file.  This option
can only be set in the ``[global]`` section of a configuration file, or before
any commands on the command line.  If set in a configuration file, it can be
overridden from the command line; setting it to an empty string on the command
line causes the default to be used.  This should never be set in a configuration
file provided with a package.

This new option can be used to add any number of packages to the list of
packages searched for command implementations; multiple package names should be
separated by commas.  When not specified, the search is only performed in the
:mod:`distutils.command` package.  When :file:`setup.py` is run with the option
``--command-packages distcmds,buildcmds``, however, the packages
:mod:`distutils.command`, :mod:`distcmds`, and :mod:`buildcmds` will be searched
in that order.  New commands are expected to be implemented in modules of the
same name as the command by classes sharing the same name.  Given the example
command line option above, the command :command:`bdist_openpkg` could be
implemented by the class :class:`distcmds.bdist_openpkg.bdist_openpkg` or
:class:`buildcmds.bdist_openpkg.bdist_openpkg`.


Adding new distribution types
=============================

Commands that create distributions (files in the :file:`dist/` directory) need
to add ``(command, filename)`` pairs to ``self.distribution.dist_files`` so that
:command:`upload` can upload it to PyPI.  The *filename* in the pair contains no
path information, only the name of the file itself.  In dry-run mode, pairs
should still be added to represent what would have been created.


PK	%�\�0��%html/_sources/distutils/index.rst.txtnu�[���.. _distutils-index:

##############################################
  Distributing Python Modules (Legacy version)
##############################################

:Authors: Greg Ward, Anthony Baxter
:Email: distutils-sig@python.org

.. seealso::

   :ref:`distributing-index`
      The up to date module distribution documentations

This document describes the Python Distribution Utilities ("Distutils") from
the module developer's point of view, describing how to use the Distutils to
make Python modules and extensions easily available to a wider audience with
very little overhead for build/release/install mechanics.

.. note::

   This guide only covers the basic tools for building and distributing
   extensions that are provided as part of this version of Python. Third party
   tools offer easier to use and more secure alternatives. Refer to the `quick
   recommendations section <https://packaging.python.org/en/latest/current/>`__
   in the Python Packaging User Guide for more information.


.. toctree::
   :maxdepth: 2
   :numbered:

   introduction.rst
   setupscript.rst
   configfile.rst
   sourcedist.rst
   builtdist.rst
   packageindex.rst
   examples.rst
   extending.rst
   commandref.rst
   apiref.rst
PK	%�\ϓ�*r!r!,html/_sources/distutils/introduction.rst.txtnu�[���.. _distutils-intro:

****************************
An Introduction to Distutils
****************************

This document covers using the Distutils to distribute your Python modules,
concentrating on the role of developer/distributor: if you're looking for
information on installing Python modules, you should refer to the
:ref:`install-index` chapter.


.. _distutils-concepts:

Concepts & Terminology
======================

Using the Distutils is quite simple, both for module developers and for
users/administrators installing third-party modules.  As a developer, your
responsibilities (apart from writing solid, well-documented and well-tested
code, of course!) are:

* write a setup script (:file:`setup.py` by convention)

* (optional) write a setup configuration file

* create a source distribution

* (optional) create one or more built (binary) distributions

Each of these tasks is covered in this document.

Not all module developers have access to a multitude of platforms, so it's not
always feasible to expect them to create a multitude of built distributions.  It
is hoped that a class of intermediaries, called *packagers*, will arise to
address this need.  Packagers will take source distributions released by module
developers, build them on one or more platforms, and release the resulting built
distributions.  Thus, users on the most popular platforms will be able to
install most popular Python module distributions in the most natural way for
their platform, without having to run a single setup script or compile a line of
code.


.. _distutils-simple-example:

A Simple Example
================

The setup script is usually quite simple, although since it's written in Python,
there are no arbitrary limits to what you can do with it, though you should be
careful about putting arbitrarily expensive operations in your setup script.
Unlike, say, Autoconf-style configure scripts, the setup script may be run
multiple times in the course of building and installing your module
distribution.

If all you want to do is distribute a module called :mod:`foo`, contained in a
file :file:`foo.py`, then your setup script can be as simple as this::

   from distutils.core import setup
   setup(name='foo',
         version='1.0',
         py_modules=['foo'],
         )

Some observations:

* most information that you supply to the Distutils is supplied as keyword
  arguments to the :func:`setup` function

* those keyword arguments fall into two categories: package metadata (name,
  version number) and information about what's in the package (a list of pure
  Python modules, in this case)

* modules are specified by module name, not filename (the same will hold true
  for packages and extensions)

* it's recommended that you supply a little more metadata, in particular your
  name, email address and a URL for the project (see section :ref:`setup-script`
  for an example)

To create a source distribution for this module, you would create a setup
script, :file:`setup.py`, containing the above code, and run this command from a
terminal::

   python setup.py sdist

For Windows, open a command prompt windows (:menuselection:`Start -->
Accessories`) and change the command to::

   setup.py sdist

:command:`sdist` will create an archive file (e.g., tarball on Unix, ZIP file on Windows)
containing your setup script :file:`setup.py`, and your module :file:`foo.py`.
The archive file will be named :file:`foo-1.0.tar.gz` (or :file:`.zip`), and
will unpack into a directory :file:`foo-1.0`.

If an end-user wishes to install your :mod:`foo` module, all they have to do is
download :file:`foo-1.0.tar.gz` (or :file:`.zip`), unpack it, and---from the
:file:`foo-1.0` directory---run ::

   python setup.py install

which will ultimately copy :file:`foo.py` to the appropriate directory for
third-party modules in their Python installation.

This simple example demonstrates some fundamental concepts of the Distutils.
First, both developers and installers have the same basic user interface, i.e.
the setup script.  The difference is which Distutils *commands* they use: the
:command:`sdist` command is almost exclusively for module developers, while
:command:`install` is more often for installers (although most developers will
want to install their own code occasionally).

If you want to make things really easy for your users, you can create one or
more built distributions for them.  For instance, if you are running on a
Windows machine, and want to make things easy for other Windows users, you can
create an executable installer (the most appropriate type of built distribution
for this platform) with the :command:`bdist_wininst` command.  For example::

   python setup.py bdist_wininst

will create an executable installer, :file:`foo-1.0.win32.exe`, in the current
directory.

Other useful built distribution formats are RPM, implemented by the
:command:`bdist_rpm` command, Solaris :program:`pkgtool`
(:command:`bdist_pkgtool`), and HP-UX :program:`swinstall`
(:command:`bdist_sdux`).  For example, the following command will create an RPM
file called :file:`foo-1.0.noarch.rpm`::

   python setup.py bdist_rpm

(The :command:`bdist_rpm` command uses the :command:`rpm` executable, therefore
this has to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or
Mandrake Linux.)

You can find out what distribution formats are available at any time by running
::

   python setup.py bdist --help-formats


.. _python-terms:

General Python terminology
==========================

If you're reading this document, you probably have a good idea of what modules,
extensions, and so forth are.  Nevertheless, just to be sure that everyone is
operating from a common starting point, we offer the following glossary of
common Python terms:

module
   the basic unit of code reusability in Python: a block of code imported by some
   other code.  Three types of modules concern us here: pure Python modules,
   extension modules, and packages.

pure Python module
   a module written in Python and contained in a single :file:`.py` file (and
   possibly associated :file:`.pyc` and/or :file:`.pyo` files).  Sometimes referred
   to as a "pure module."

extension module
   a module written in the low-level language of the Python implementation: C/C++
   for Python, Java for Jython. Typically contained in a single dynamically
   loadable pre-compiled file, e.g. a shared object (:file:`.so`) file for Python
   extensions on Unix, a DLL (given the :file:`.pyd` extension) for Python
   extensions on Windows, or a Java class file for Jython extensions.  (Note that
   currently, the Distutils only handles C/C++ extensions for Python.)

package
   a module that contains other modules; typically contained in a directory in the
   filesystem and distinguished from other directories by the presence of a file
   :file:`__init__.py`.

root package
   the root of the hierarchy of packages.  (This isn't really a package, since it
   doesn't have an :file:`__init__.py` file.  But we have to call it something.)
   The vast majority of the standard library is in the root package, as are many
   small, standalone third-party modules that don't belong to a larger module
   collection. Unlike regular packages, modules in the root package can be found in
   many directories: in fact, every directory listed in ``sys.path`` contributes
   modules to the root package.


.. _distutils-term:

Distutils-specific terminology
==============================

The following terms apply more specifically to the domain of distributing Python
modules using the Distutils:

module distribution
   a collection of Python modules distributed together as a single downloadable
   resource and meant to be installed *en masse*.  Examples of some well-known
   module distributions are Numeric Python, PyXML, Pillow,
   or mxBase.  (This would be called a *package*, except that term is
   already taken in the Python context: a single module distribution may contain
   zero, one, or many Python packages.)

pure module distribution
   a module distribution that contains only pure Python modules and packages.
   Sometimes referred to as a "pure distribution."

non-pure module distribution
   a module distribution that contains at least one extension module.  Sometimes
   referred to as a "non-pure distribution."

distribution root
   the top-level directory of your source tree (or  source distribution); the
   directory where :file:`setup.py` exists.  Generally  :file:`setup.py` will be
   run from this directory.


PK	%�\ ��!�!,html/_sources/distutils/packageindex.rst.txtnu�[���.. index::
   single: Python Package Index (PyPI)
   single: PyPI; (see Python Package Index (PyPI))

.. _package-index:

*******************************
The Python Package Index (PyPI)
*******************************

The `Python Package Index (PyPI)`_ stores :ref:`meta-data <meta-data>`
describing distributions packaged with distutils, as well as package data like
distribution files if a package author wishes.

Distutils provides the :command:`register` and :command:`upload` commands for
pushing meta-data and distribution files to PyPI, respectively.  See
:ref:`package-commands` for information on these commands.


PyPI overview
=============

PyPI lets you submit any number of versions of your distribution to the index.
If you alter the meta-data for a particular version, you can submit it again
and the index will be updated.

PyPI holds a record for each (name, version) combination submitted.  The first
user to submit information for a given name is designated the Owner of that
name.  Changes can be submitted through the :command:`register` command or
through the web interface.  Owners can designate other users as Owners or
Maintainers.  Maintainers can edit the package information, but not designate
new Owners or Maintainers.

By default PyPI displays only the newest version of a given package.  The web
interface lets one change this default behavior and manually select which
versions to display and hide.

For each version, PyPI displays a home page.  The home page is created from
the ``long_description`` which can be submitted via the :command:`register`
command.  See :ref:`package-display` for more information.


.. _package-commands:

Distutils commands
==================

Distutils exposes two commands for submitting package data to PyPI: the
:ref:`register <package-register>` command for submitting meta-data to PyPI
and the :ref:`upload <package-upload>` command for submitting distribution
files.  Both commands read configuration data from a special file called a
:ref:`.pypirc file <pypirc>`.


.. _package-register:

The ``register`` command
------------------------

The distutils command :command:`register` is used to submit your distribution's
meta-data to an index server. It is invoked as follows::

    python setup.py register

Distutils will respond with the following prompt::

    running register
    We need to know who you are, so please choose either:
        1. use your existing login,
        2. register as a new user,
        3. have the server generate a new password for you (and email it to you), or
        4. quit
    Your selection [default 1]:

Note: if your username and password are saved locally, you will not see this
menu.  Also, refer to :ref:`pypirc` for how to store your credentials in a
:file:`.pypirc` file.

If you have not registered with PyPI, then you will need to do so now. You
should choose option 2, and enter your details as required. Soon after
submitting your details, you will receive an email which will be used to confirm
your registration.

Once you are registered, you may choose option 1 from the menu. You will be
prompted for your PyPI username and password, and :command:`register` will then
submit your meta-data to the index.

See :ref:`package-cmdoptions` for options to the :command:`register` command.


.. _package-upload:

The ``upload`` command
----------------------

.. versionadded:: 2.5

The distutils command :command:`upload` pushes the distribution files to PyPI.

The command is invoked immediately after building one or more distribution
files.  For example, the command ::

    python setup.py sdist bdist_wininst upload

will cause the source distribution and the Windows installer to be uploaded to
PyPI.  Note that these will be uploaded even if they are built using an earlier
invocation of :file:`setup.py`, but that only distributions named on the command
line for the invocation including the :command:`upload` command are uploaded.

If a :command:`register` command was previously called in the same command,
and if the password was entered in the prompt, :command:`upload` will reuse the
entered password.  This is useful if you do not want to store a password in
clear text in a :file:`.pypirc` file.

You can use the ``--sign`` option to tell :command:`upload` to sign each
uploaded file using GPG (GNU Privacy Guard).  The  :program:`gpg` program must
be available for execution on the system :envvar:`PATH`.  You can also specify
which key to use for signing using the ``--identity=name`` option.

See :ref:`package-cmdoptions` for additional options to the :command:`upload`
command.


.. _package-cmdoptions:

Additional command options
--------------------------

This section describes options common to both the :command:`register` and
:command:`upload` commands.

The ``--repository`` or ``-r`` option lets you specify a PyPI server
different from the default.  For example::

    python setup.py sdist bdist_wininst upload -r https://example.com/pypi

For convenience, a name can be used in place of the URL when the
:file:`.pypirc` file is configured to do so.  For example::

    python setup.py register -r other

See :ref:`pypirc` for more information on defining alternate servers.

The ``--show-response`` option displays the full response text from the PyPI
server, which is useful when debugging problems with registering and uploading.


.. index::
   single: .pypirc file
   single: Python Package Index (PyPI); .pypirc file

.. _pypirc:

The ``.pypirc`` file
--------------------

The :command:`register` and :command:`upload` commands both check for the
existence of a :file:`.pypirc` file at the location :file:`$HOME/.pypirc`.
If this file exists, the command uses the username, password, and repository
URL configured in the file.  The format of a :file:`.pypirc` file is as
follows::

    [distutils]
    index-servers =
        pypi

    [pypi]
    repository: <repository-url>
    username: <username>
    password: <password>

The *distutils* section defines an *index-servers* variable that lists the
name of all sections describing a repository.

Each section describing a repository defines three variables:

- *repository*, that defines the url of the PyPI server. Defaults to
    ``https://www.python.org/pypi``.
- *username*, which is the registered username on the PyPI server.
- *password*, that will be used to authenticate. If omitted the user
    will be prompt to type it when needed.

If you want to define another server a new section can be created and
listed in the *index-servers* variable::

    [distutils]
    index-servers =
        pypi
        other

    [pypi]
    repository: <repository-url>
    username: <username>
    password: <password>

    [other]
    repository: https://example.com/pypi
    username: <username>
    password: <password>

This allows the :command:`register` and :command:`upload` commands to be
called with the ``--repository`` option as described in
:ref:`package-cmdoptions`.

Specifically, you might want to add the `PyPI Test Repository
<https://wiki.python.org/moin/TestPyPI>`_ to your ``.pypirc`` to facilitate
testing before doing your first upload to ``PyPI`` itself.


.. _package-display:

PyPI package display
====================

The ``long_description`` field plays a special role at PyPI. It is used by
the server to display a home page for the registered package.

If you use the `reStructuredText <http://docutils.sourceforge.net/rst.html>`_
syntax for this field, PyPI will parse it and display an HTML output for
the package home page.

The ``long_description`` field can be attached to a text file located
in the package::

    from distutils.core import setup

    with open('README.txt') as file:
        long_description = file.read()

    setup(name='Distutils',
          long_description=long_description)

In that case, :file:`README.txt` is a regular reStructuredText text file located
in the root of the package besides :file:`setup.py`.

To prevent registering broken reStructuredText content, you can use the
:program:`rst2html` program that is provided by the :mod:`docutils` package and
check the ``long_description`` from the command line:

.. code-block:: shell-session

    $ python setup.py --long-description | rst2html.py > output.html

:mod:`docutils` will display a warning if there's something wrong with your
syntax.  Because PyPI applies additional checks (e.g. by passing ``--no-raw``
to ``rst2html.py`` in the command above), being able to run the command above
without warnings does not guarantee that PyPI will convert the content
successfully.


.. _Python Package Index (PyPI): https://pypi.org
PK	%�\���y�y+html/_sources/distutils/setupscript.rst.txtnu�[���.. _setup-script:

************************
Writing the Setup Script
************************

The setup script is the centre of all activity in building, distributing, and
installing modules using the Distutils.  The main purpose of the setup script is
to describe your module distribution to the Distutils, so that the various
commands that operate on your modules do the right thing.  As we saw in section
:ref:`distutils-simple-example` above, the setup script consists mainly of a call to
:func:`setup`, and most information supplied to the Distutils by the module
developer is supplied as keyword arguments to :func:`setup`.

Here's a slightly more involved example, which we'll follow for the next couple
of sections: the Distutils' own setup script.  (Keep in mind that although the
Distutils are included with Python 1.6 and later, they also have an independent
existence so that Python 1.5.2 users can use them to install other module
distributions.  The Distutils' own setup script, shown here, is used to install
the package into Python 1.5.2.) ::

    #!/usr/bin/env python

    from distutils.core import setup

    setup(name='Distutils',
          version='1.0',
          description='Python Distribution Utilities',
          author='Greg Ward',
          author_email='gward@python.net',
          url='https://www.python.org/sigs/distutils-sig/',
          packages=['distutils', 'distutils.command'],
         )

There are only two differences between this and the trivial one-file
distribution presented in section :ref:`distutils-simple-example`: more metadata, and the
specification of pure Python modules by package, rather than by module.  This is
important since the Distutils consist of a couple of dozen modules split into
(so far) two packages; an explicit list of every module would be tedious to
generate and difficult to maintain.  For more information on the additional
meta-data, see section :ref:`meta-data`.

Note that any pathnames (files or directories) supplied in the setup script
should be written using the Unix convention, i.e. slash-separated.  The
Distutils will take care of converting this platform-neutral representation into
whatever is appropriate on your current platform before actually using the
pathname.  This makes your setup script portable across operating systems, which
of course is one of the major goals of the Distutils.  In this spirit, all
pathnames in this document are slash-separated.

This, of course, only applies to pathnames given to Distutils functions.  If
you, for example, use standard Python functions such as :func:`glob.glob` or
:func:`os.listdir` to specify files, you should be careful to write portable
code instead of hardcoding path separators::

    glob.glob(os.path.join('mydir', 'subdir', '*.html'))
    os.listdir(os.path.join('mydir', 'subdir'))


.. _listing-packages:

Listing whole packages
======================

The ``packages`` option tells the Distutils to process (build, distribute,
install, etc.) all pure Python modules found in each package mentioned in the
``packages`` list.  In order to do this, of course, there has to be a
correspondence between package names and directories in the filesystem.  The
default correspondence is the most obvious one, i.e. package :mod:`distutils` is
found in the directory :file:`distutils` relative to the distribution root.
Thus, when you say ``packages = ['foo']`` in your setup script, you are
promising that the Distutils will find a file :file:`foo/__init__.py` (which
might be spelled differently on your system, but you get the idea) relative to
the directory where your setup script lives.  If you break this promise, the
Distutils will issue a warning but still process the broken package anyway.

If you use a different convention to lay out your source directory, that's no
problem: you just have to supply the ``package_dir`` option to tell the
Distutils about your convention.  For example, say you keep all Python source
under :file:`lib`, so that modules in the "root package" (i.e., not in any
package at all) are in :file:`lib`, modules in the :mod:`foo` package are in
:file:`lib/foo`, and so forth.  Then you would put ::

    package_dir = {'': 'lib'}

in your setup script.  The keys to this dictionary are package names, and an
empty package name stands for the root package.  The values are directory names
relative to your distribution root.  In this case, when you say ``packages =
['foo']``, you are promising that the file :file:`lib/foo/__init__.py` exists.

Another possible convention is to put the :mod:`foo` package right in
:file:`lib`, the :mod:`foo.bar` package in :file:`lib/bar`, etc.  This would be
written in the setup script as ::

    package_dir = {'foo': 'lib'}

A ``package: dir`` entry in the ``package_dir`` dictionary implicitly
applies to all packages below *package*, so the :mod:`foo.bar` case is
automatically handled here.  In this example, having ``packages = ['foo',
'foo.bar']`` tells the Distutils to look for :file:`lib/__init__.py` and
:file:`lib/bar/__init__.py`.  (Keep in mind that although ``package_dir``
applies recursively, you must explicitly list all packages in
``packages``: the Distutils will *not* recursively scan your source tree
looking for any directory with an :file:`__init__.py` file.)


.. _listing-modules:

Listing individual modules
==========================

For a small module distribution, you might prefer to list all modules rather
than listing packages---especially the case of a single module that goes in the
"root package" (i.e., no package at all).  This simplest case was shown in
section :ref:`distutils-simple-example`; here is a slightly more involved example::

    py_modules = ['mod1', 'pkg.mod2']

This describes two modules, one of them in the "root" package, the other in the
:mod:`pkg` package.  Again, the default package/directory layout implies that
these two modules can be found in :file:`mod1.py` and :file:`pkg/mod2.py`, and
that :file:`pkg/__init__.py` exists as well. And again, you can override the
package/directory correspondence using the ``package_dir`` option.


.. _describing-extensions:

Describing extension modules
============================

Just as writing Python extension modules is a bit more complicated than writing
pure Python modules, describing them to the Distutils is a bit more complicated.
Unlike pure modules, it's not enough just to list modules or packages and expect
the Distutils to go out and find the right files; you have to specify the
extension name, source file(s), and any compile/link requirements (include
directories, libraries to link with, etc.).

.. XXX read over this section

All of this is done through another keyword argument to :func:`setup`, the
``ext_modules`` option.  ``ext_modules`` is just a list of
:class:`~distutils.core.Extension` instances, each of which describes a
single extension module.
Suppose your distribution includes a single extension, called :mod:`foo` and
implemented by :file:`foo.c`.  If no additional instructions to the
compiler/linker are needed, describing this extension is quite simple::

    Extension('foo', ['foo.c'])

The :class:`Extension` class can be imported from :mod:`distutils.core` along
with :func:`setup`.  Thus, the setup script for a module distribution that
contains only this one extension and nothing else might be::

    from distutils.core import setup, Extension
    setup(name='foo',
          version='1.0',
          ext_modules=[Extension('foo', ['foo.c'])],
          )

The :class:`Extension` class (actually, the underlying extension-building
machinery implemented by the :command:`build_ext` command) supports a great deal
of flexibility in describing Python extensions, which is explained in the
following sections.


Extension names and packages
----------------------------

The first argument to the :class:`~distutils.core.Extension` constructor is
always the name of the extension, including any package names.  For example, ::

    Extension('foo', ['src/foo1.c', 'src/foo2.c'])

describes an extension that lives in the root package, while ::

    Extension('pkg.foo', ['src/foo1.c', 'src/foo2.c'])

describes the same extension in the :mod:`pkg` package.  The source files and
resulting object code are identical in both cases; the only difference is where
in the filesystem (and therefore where in Python's namespace hierarchy) the
resulting extension lives.

If you have a number of extensions all in the same package (or all under the
same base package), use the ``ext_package`` keyword argument to
:func:`setup`.  For example, ::

    setup(...,
          ext_package='pkg',
          ext_modules=[Extension('foo', ['foo.c']),
                       Extension('subpkg.bar', ['bar.c'])],
         )

will compile :file:`foo.c` to the extension :mod:`pkg.foo`, and :file:`bar.c` to
:mod:`pkg.subpkg.bar`.


Extension source files
----------------------

The second argument to the :class:`~distutils.core.Extension` constructor is
a list of source
files.  Since the Distutils currently only support C, C++, and Objective-C
extensions, these are normally C/C++/Objective-C source files.  (Be sure to use
appropriate extensions to distinguish C++ source files: :file:`.cc` and
:file:`.cpp` seem to be recognized by both Unix and Windows compilers.)

However, you can also include SWIG interface (:file:`.i`) files in the list; the
:command:`build_ext` command knows how to deal with SWIG extensions: it will run
SWIG on the interface file and compile the resulting C/C++ file into your
extension.

.. XXX SWIG support is rough around the edges and largely untested!

This warning notwithstanding, options to SWIG can be currently passed like
this::

    setup(...,
          ext_modules=[Extension('_foo', ['foo.i'],
                                 swig_opts=['-modern', '-I../include'])],
          py_modules=['foo'],
         )

Or on the commandline like this::

    > python setup.py build_ext --swig-opts="-modern -I../include"

On some platforms, you can include non-source files that are processed by the
compiler and included in your extension.  Currently, this just means Windows
message text (:file:`.mc`) files and resource definition (:file:`.rc`) files for
Visual C++. These will be compiled to binary resource (:file:`.res`) files and
linked into the executable.


Preprocessor options
--------------------

Three optional arguments to :class:`~distutils.core.Extension` will help if
you need to specify include directories to search or preprocessor macros to
define/undefine: ``include_dirs``, ``define_macros``, and ``undef_macros``.

For example, if your extension requires header files in the :file:`include`
directory under your distribution root, use the ``include_dirs`` option::

    Extension('foo', ['foo.c'], include_dirs=['include'])

You can specify absolute directories there; if you know that your extension will
only be built on Unix systems with X11R6 installed to :file:`/usr`, you can get
away with ::

    Extension('foo', ['foo.c'], include_dirs=['/usr/include/X11'])

You should avoid this sort of non-portable usage if you plan to distribute your
code: it's probably better to write C code like  ::

    #include <X11/Xlib.h>

If you need to include header files from some other Python extension, you can
take advantage of the fact that header files are installed in a consistent way
by the Distutils :command:`install_headers` command.  For example, the Numerical
Python header files are installed (on a standard Unix installation) to
:file:`/usr/local/include/python1.5/Numerical`. (The exact location will differ
according to your platform and Python installation.)  Since the Python include
directory---\ :file:`/usr/local/include/python1.5` in this case---is always
included in the search path when building Python extensions, the best approach
is to write C code like  ::

    #include <Numerical/arrayobject.h>

If you must put the :file:`Numerical` include directory right into your header
search path, though, you can find that directory using the Distutils
:mod:`distutils.sysconfig` module::

    from distutils.sysconfig import get_python_inc
    incdir = os.path.join(get_python_inc(plat_specific=1), 'Numerical')
    setup(...,
          Extension(..., include_dirs=[incdir]),
          )

Even though this is quite portable---it will work on any Python installation,
regardless of platform---it's probably easier to just write your C code in the
sensible way.

You can define and undefine pre-processor macros with the ``define_macros`` and
``undef_macros`` options. ``define_macros`` takes a list of ``(name, value)``
tuples, where ``name`` is the name of the macro to define (a string) and
``value`` is its value: either a string or ``None``.  (Defining a macro ``FOO``
to ``None`` is the equivalent of a bare ``#define FOO`` in your C source: with
most compilers, this sets ``FOO`` to the string ``1``.)  ``undef_macros`` is
just a list of macros to undefine.

For example::

    Extension(...,
              define_macros=[('NDEBUG', '1'),
                             ('HAVE_STRFTIME', None)],
              undef_macros=['HAVE_FOO', 'HAVE_BAR'])

is the equivalent of having this at the top of every C source file::

    #define NDEBUG 1
    #define HAVE_STRFTIME
    #undef HAVE_FOO
    #undef HAVE_BAR


Library options
---------------

You can also specify the libraries to link against when building your extension,
and the directories to search for those libraries.  The ``libraries`` option is
a list of libraries to link against, ``library_dirs`` is a list of directories
to search for libraries at  link-time, and ``runtime_library_dirs`` is a list of
directories to  search for shared (dynamically loaded) libraries at run-time.

For example, if you need to link against libraries known to be in the standard
library search path on target systems ::

    Extension(...,
              libraries=['gdbm', 'readline'])

If you need to link with libraries in a non-standard location, you'll have to
include the location in ``library_dirs``::

    Extension(...,
              library_dirs=['/usr/X11R6/lib'],
              libraries=['X11', 'Xt'])

(Again, this sort of non-portable construct should be avoided if you intend to
distribute your code.)

.. XXX Should mention clib libraries here or somewhere else!


Other options
-------------

There are still some other options which can be used to handle special cases.

The ``extra_objects`` option is a list of object files to be passed to the
linker. These files must not have extensions, as the default extension for the
compiler is used.

``extra_compile_args`` and ``extra_link_args`` can be used to
specify additional command line options for the respective compiler and linker
command lines.

``export_symbols`` is only useful on Windows.  It can contain a list of
symbols (functions or variables) to be exported. This option is not needed when
building compiled extensions: Distutils  will automatically add ``initmodule``
to the list of exported symbols.

The ``depends`` option is a list of files that the extension depends on
(for example header files). The build command will call the compiler on the
sources to rebuild extension if any on this files has been modified since the
previous build.

Relationships between Distributions and Packages
================================================

A distribution may relate to packages in three specific ways:

#. It can require packages or modules.

#. It can provide packages or modules.

#. It can obsolete packages or modules.

These relationships can be specified using keyword arguments to the
:func:`distutils.core.setup` function.

Dependencies on other Python modules and packages can be specified by supplying
the *requires* keyword argument to :func:`setup`. The value must be a list of
strings.  Each string specifies a package that is required, and optionally what
versions are sufficient.

To specify that any version of a module or package is required, the string
should consist entirely of the module or package name. Examples include
``'mymodule'`` and ``'xml.parsers.expat'``.

If specific versions are required, a sequence of qualifiers can be supplied in
parentheses.  Each qualifier may consist of a comparison operator and a version
number.  The accepted comparison operators are::

    <    >    ==
    <=   >=   !=

These can be combined by using multiple qualifiers separated by commas (and
optional whitespace).  In this case, all of the qualifiers must be matched; a
logical AND is used to combine the evaluations.

Let's look at a bunch of examples:

+-------------------------+----------------------------------------------+
| Requires Expression     | Explanation                                  |
+=========================+==============================================+
| ``==1.0``               | Only version ``1.0`` is compatible           |
+-------------------------+----------------------------------------------+
| ``>1.0, !=1.5.1, <2.0`` | Any version after ``1.0`` and before ``2.0`` |
|                         | is compatible, except ``1.5.1``              |
+-------------------------+----------------------------------------------+

Now that we can specify dependencies, we also need to be able to specify what we
provide that other distributions can require.  This is done using the *provides*
keyword argument to :func:`setup`. The value for this keyword is a list of
strings, each of which names a Python module or package, and optionally
identifies the version.  If the version is not specified, it is assumed to match
that of the distribution.

Some examples:

+---------------------+----------------------------------------------+
| Provides Expression | Explanation                                  |
+=====================+==============================================+
| ``mypkg``           | Provide ``mypkg``, using the distribution    |
|                     | version                                      |
+---------------------+----------------------------------------------+
| ``mypkg (1.1)``     | Provide ``mypkg`` version 1.1, regardless of |
|                     | the distribution version                     |
+---------------------+----------------------------------------------+

A package can declare that it obsoletes other packages using the *obsoletes*
keyword argument.  The value for this is similar to that of the *requires*
keyword: a list of strings giving module or package specifiers.  Each specifier
consists of a module or package name optionally followed by one or more version
qualifiers.  Version qualifiers are given in parentheses after the module or
package name.

The versions identified by the qualifiers are those that are obsoleted by the
distribution being described.  If no qualifiers are given, all versions of the
named module or package are understood to be obsoleted.

.. _distutils-installing-scripts:

Installing Scripts
==================

So far we have been dealing with pure and non-pure Python modules, which are
usually not run by themselves but imported by scripts.

Scripts are files containing Python source code, intended to be started from the
command line.  Scripts don't require Distutils to do anything very complicated.
The only clever feature is that if the first line of the script starts with
``#!`` and contains the word "python", the Distutils will adjust the first line
to refer to the current interpreter location. By default, it is replaced with
the current interpreter location.  The :option:`!--executable` (or :option:`!-e`)
option will allow the interpreter path to be explicitly overridden.

The ``scripts`` option simply is a list of files to be handled in this
way.  From the PyXML setup script::

    setup(...,
          scripts=['scripts/xmlproc_parse', 'scripts/xmlproc_val']
          )

.. versionchanged:: 2.7
    All the scripts will also be added to the ``MANIFEST``
    file if no template is provided. See :ref:`manifest`.

.. _distutils-installing-package-data:

Installing Package Data
=======================

Often, additional files need to be installed into a package.  These files are
often data that's closely related to the package's implementation, or text files
containing documentation that might be of interest to programmers using the
package.  These files are called :dfn:`package data`.

Package data can be added to packages using the ``package_data`` keyword
argument to the :func:`setup` function.  The value must be a mapping from
package name to a list of relative path names that should be copied into the
package.  The paths are interpreted as relative to the directory containing the
package (information from the ``package_dir`` mapping is used if appropriate);
that is, the files are expected to be part of the package in the source
directories. They may contain glob patterns as well.

The path names may contain directory portions; any necessary directories will be
created in the installation.

For example, if a package should contain a subdirectory with several data files,
the files can be arranged like this in the source tree::

    setup.py
    src/
        mypkg/
            __init__.py
            module.py
            data/
                tables.dat
                spoons.dat
                forks.dat

The corresponding call to :func:`setup` might be::

    setup(...,
          packages=['mypkg'],
          package_dir={'mypkg': 'src/mypkg'},
          package_data={'mypkg': ['data/*.dat']},
          )

.. versionadded:: 2.4

.. versionchanged:: 2.7
    All the files that match ``package_data`` will be added to the ``MANIFEST``
    file if no template is provided. See :ref:`manifest`.


.. _distutils-additional-files:

Installing Additional Files
===========================

The ``data_files`` option can be used to specify additional files needed
by the module distribution: configuration files, message catalogs, data files,
anything which doesn't fit in the previous categories.

``data_files`` specifies a sequence of (*directory*, *files*) pairs in the
following way::

    setup(...,
          data_files=[('bitmaps', ['bm/b1.gif', 'bm/b2.gif']),
                      ('config', ['cfg/data.cfg']),
         )

Each (*directory*, *files*) pair in the sequence specifies the installation
directory and the files to install there.

Each file name in *files* is interpreted relative to the :file:`setup.py`
script at the top of the package source distribution. Note that you can
specify the directory where the data files will be installed, but you cannot
rename the data files themselves.

The *directory* should be a relative path. It is interpreted relative to the
installation prefix (Python's ``sys.prefix`` for system installations;
``site.USER_BASE`` for user installations). Distutils allows *directory* to be
an absolute installation path, but this is discouraged since it is
incompatible with the wheel packaging format. No directory information from
*files* is used to determine the final location of the installed file; only
the name of the file is used.

You can specify the ``data_files`` options as a simple sequence of files
without specifying a target directory, but this is not recommended, and the
:command:`install` command will print a warning in this case. To install data
files directly in the target directory, an empty string should be given as the
directory.

.. versionchanged:: 2.7
    All the files that match ``data_files`` will be added to the ``MANIFEST``
    file if no template is provided. See :ref:`manifest`.



.. _meta-data:

Additional meta-data
====================

The setup script may include additional meta-data beyond the name and version.
This information includes:

+----------------------+---------------------------+-----------------+--------+
| Meta-Data            | Description               | Value           | Notes  |
+======================+===========================+=================+========+
| ``name``             | name of the package       | short string    | \(1)   |
+----------------------+---------------------------+-----------------+--------+
| ``version``          | version of this release   | short string    | (1)(2) |
+----------------------+---------------------------+-----------------+--------+
| ``author``           | package author's name     | short string    | \(3)   |
+----------------------+---------------------------+-----------------+--------+
| ``author_email``     | email address of the      | email address   | \(3)   |
|                      | package author            |                 |        |
+----------------------+---------------------------+-----------------+--------+
| ``maintainer``       | package maintainer's name | short string    | \(3)   |
+----------------------+---------------------------+-----------------+--------+
| ``maintainer_email`` | email address of the      | email address   | \(3)   |
|                      | package maintainer        |                 |        |
+----------------------+---------------------------+-----------------+--------+
| ``url``              | home page for the package | URL             | \(1)   |
+----------------------+---------------------------+-----------------+--------+
| ``description``      | short, summary            | short string    |        |
|                      | description of the        |                 |        |
|                      | package                   |                 |        |
+----------------------+---------------------------+-----------------+--------+
| ``long_description`` | longer description of the | long string     | \(5)   |
|                      | package                   |                 |        |
+----------------------+---------------------------+-----------------+--------+
| ``download_url``     | location where the        | URL             | \(4)   |
|                      | package may be downloaded |                 |        |
+----------------------+---------------------------+-----------------+--------+
| ``classifiers``      | a list of classifiers     | list of strings | \(4)   |
+----------------------+---------------------------+-----------------+--------+
| ``platforms``        | a list of platforms       | list of strings |        |
+----------------------+---------------------------+-----------------+--------+
| ``license``          | license for the package   | short string    | \(6)   |
+----------------------+---------------------------+-----------------+--------+

Notes:

(1)
    These fields are required.

(2)
    It is recommended that versions take the form *major.minor[.patch[.sub]]*.

(3)
    Either the author or the maintainer must be identified. If maintainer is
    provided, distutils lists it as the author in :file:`PKG-INFO`.

(4)
    These fields should not be used if your package is to be compatible with Python
    versions prior to 2.2.3 or 2.3.  The list is available from the `PyPI website
    <https://pypi.org>`_.

(5)
    The ``long_description`` field is used by PyPI when you are
    :ref:`registering <package-register>` a package, to
    :ref:`build its home page <package-display>`.

(6)
    The ``license`` field is a text indicating the license covering the
    package where the license is not a selection from the "License" Trove
    classifiers. See the ``Classifier`` field. Notice that
    there's a ``licence`` distribution option which is deprecated but still
    acts as an alias for ``license``.

'short string'
    A single line of text, not more than 200 characters.

'long string'
    Multiple lines of plain text in reStructuredText format (see
    http://docutils.sourceforge.net/).

'list of strings'
    See below.

None of the string values may be Unicode.

Encoding the version information is an art in itself. Python packages generally
adhere to the version format *major.minor[.patch][sub]*. The major number is 0
for initial, experimental releases of software. It is incremented for releases
that represent major milestones in a package. The minor number is incremented
when important new features are added to the package. The patch number
increments when bug-fix releases are made. Additional trailing version
information is sometimes used to indicate sub-releases.  These are
"a1,a2,...,aN" (for alpha releases, where functionality and API may change),
"b1,b2,...,bN" (for beta releases, which only fix bugs) and "pr1,pr2,...,prN"
(for final pre-release release testing). Some examples:

0.1.0
    the first, experimental release of a package

1.0.1a2
    the second alpha release of the first patch version of 1.0

``classifiers`` are specified in a Python list::

    setup(...,
          classifiers=[
              'Development Status :: 4 - Beta',
              'Environment :: Console',
              'Environment :: Web Environment',
              'Intended Audience :: End Users/Desktop',
              'Intended Audience :: Developers',
              'Intended Audience :: System Administrators',
              'License :: OSI Approved :: Python Software Foundation License',
              'Operating System :: MacOS :: MacOS X',
              'Operating System :: Microsoft :: Windows',
              'Operating System :: POSIX',
              'Programming Language :: Python',
              'Topic :: Communications :: Email',
              'Topic :: Office/Business',
              'Topic :: Software Development :: Bug Tracking',
              ],
          )

If you wish to include classifiers in your :file:`setup.py` file and also wish
to remain backwards-compatible with Python releases prior to 2.2.3, then you can
include the following code fragment in your :file:`setup.py` before the
:func:`setup` call. ::

    # patch distutils if it can't cope with the "classifiers" or
    # "download_url" keywords
    from sys import version
    if version < '2.2.3':
        from distutils.dist import DistributionMetadata
        DistributionMetadata.classifiers = None
        DistributionMetadata.download_url = None


.. _debug-setup-script:

Debugging the setup script
==========================

Sometimes things go wrong, and the setup script doesn't do what the developer
wants.

Distutils catches any exceptions when running the setup script, and print a
simple error message before the script is terminated.  The motivation for this
behaviour is to not confuse administrators who don't know much about Python and
are trying to install a package.  If they get a big long traceback from deep
inside the guts of Distutils, they may think the package or the Python
installation is broken because they don't read all the way down to the bottom
and see that it's a permission problem.

On the other hand, this doesn't help the developer to find the cause of the
failure. For this purpose, the :envvar:`DISTUTILS_DEBUG` environment variable can be set
to anything except an empty string, and distutils will now print detailed
information about what it is doing, dump the full traceback when an exception
occurs, and print the whole command line when an external program (like a C
compiler) fails.
PK	%�\��z�0�0*html/_sources/distutils/sourcedist.rst.txtnu�[���.. _source-dist:

******************************
Creating a Source Distribution
******************************

As shown in section :ref:`distutils-simple-example`, you use the :command:`sdist` command
to create a source distribution.  In the simplest case, ::

   python setup.py sdist

(assuming you haven't specified any :command:`sdist` options in the setup script
or config file), :command:`sdist` creates the archive of the default format for
the current platform.  The default format is a gzip'ed tar file
(:file:`.tar.gz`) on Unix, and ZIP file on Windows.

You can specify as many formats as you like using the :option:`!--formats`
option, for example::

   python setup.py sdist --formats=gztar,zip

to create a gzipped tarball and a zip file.  The available formats are:

+-----------+-------------------------+---------+
| Format    | Description             | Notes   |
+===========+=========================+=========+
| ``zip``   | zip file (:file:`.zip`) | (1),(3) |
+-----------+-------------------------+---------+
| ``gztar`` | gzip'ed tar file        | \(2)    |
|           | (:file:`.tar.gz`)       |         |
+-----------+-------------------------+---------+
| ``bztar`` | bzip2'ed tar file       |         |
|           | (:file:`.tar.bz2`)      |         |
+-----------+-------------------------+---------+
| ``ztar``  | compressed tar file     | \(4)    |
|           | (:file:`.tar.Z`)        |         |
+-----------+-------------------------+---------+
| ``tar``   | tar file (:file:`.tar`) |         |
+-----------+-------------------------+---------+

Notes:

(1)
   default on Windows

(2)
   default on Unix

(3)
   requires either external :program:`zip` utility or :mod:`zipfile` module (part
   of the standard Python library since Python 1.6)

(4)
   requires the :program:`compress` program.

When using any ``tar`` format (``gztar``, ``bztar``, ``ztar`` or
``tar``) under Unix, you can specify the ``owner`` and ``group`` names
that will be set for each member of the archive.

For example, if you want all files of the archive to be owned by root::

    python setup.py sdist --owner=root --group=root


.. _manifest:

Specifying the files to distribute
==================================

If you don't supply an explicit list of files (or instructions on how to
generate one), the :command:`sdist` command puts a minimal default set into the
source distribution:

* all Python source files implied by the ``py_modules`` and
  ``packages`` options

* all C source files mentioned in the ``ext_modules`` or
  ``libraries`` options

  .. XXX Getting C library sources is currently broken -- no
     :meth:`get_source_files` method in :file:`build_clib.py`!

* scripts identified by the ``scripts`` option
  See :ref:`distutils-installing-scripts`.

* anything that looks like a test script: :file:`test/test\*.py` (currently, the
  Distutils don't do anything with test scripts except include them in source
  distributions, but in the future there will be a standard for testing Python
  module distributions)

* :file:`README.txt` (or :file:`README`), :file:`setup.py` (or whatever  you
  called your setup script), and :file:`setup.cfg`

* all files that matches the ``package_data`` metadata.
  See :ref:`distutils-installing-package-data`.

* all files that matches the ``data_files`` metadata.
  See :ref:`distutils-additional-files`.

Sometimes this is enough, but usually you will want to specify additional files
to distribute.  The typical way to do this is to write a *manifest template*,
called :file:`MANIFEST.in` by default.  The manifest template is just a list of
instructions for how to generate your manifest file, :file:`MANIFEST`, which is
the exact list of files to include in your source distribution.  The
:command:`sdist` command processes this template and generates a manifest based
on its instructions and what it finds in the filesystem.

If you prefer to roll your own manifest file, the format is simple: one filename
per line, regular files (or symlinks to them) only.  If you do supply your own
:file:`MANIFEST`, you must specify everything: the default set of files
described above does not apply in this case.

.. versionchanged:: 2.7
   An existing generated :file:`MANIFEST` will be regenerated without
   :command:`sdist` comparing its modification time to the one of
   :file:`MANIFEST.in` or :file:`setup.py`.

.. versionchanged:: 2.7.1
   :file:`MANIFEST` files start with a comment indicating they are generated.
   Files without this comment are not overwritten or removed.

.. versionchanged:: 2.7.3
   :command:`sdist` will read a :file:`MANIFEST` file if no :file:`MANIFEST.in`
   exists, like it did before 2.7.

See :ref:`manifest_template` section for a syntax reference.


.. _manifest-options:

Manifest-related options
========================

The normal course of operations for the :command:`sdist` command is as follows:

* if the manifest file (:file:`MANIFEST` by default) exists and the first line
  does not have a comment indicating it is generated from :file:`MANIFEST.in`,
  then it is used as is, unaltered

* if the manifest file doesn't exist or has been previously automatically
  generated, read :file:`MANIFEST.in` and create the manifest

* if neither :file:`MANIFEST` nor :file:`MANIFEST.in` exist, create a manifest
  with just the default file set

* use the list of files now in :file:`MANIFEST` (either just generated or read
  in) to create the source distribution archive(s)

There are a couple of options that modify this behaviour.  First, use the
:option:`!--no-defaults` and :option:`!--no-prune` to disable the standard
"include" and "exclude" sets.

Second, you might just want to (re)generate the manifest, but not create a
source distribution::

   python setup.py sdist --manifest-only

:option:`!-o` is a shortcut for :option:`!--manifest-only`.

.. _manifest_template:

The MANIFEST.in template
========================

A :file:`MANIFEST.in` file can be added in a project to define the list of
files to include in the distribution built by the :command:`sdist` command.

When :command:`sdist` is run, it will look for the :file:`MANIFEST.in` file
and interpret it to generate the :file:`MANIFEST` file that contains the
list of files that will be included in the package.

This mechanism can be used when the default list of files is not enough.
(See :ref:`manifest`).

Principle
---------

The manifest template has one command per line, where each command specifies a
set of files to include or exclude from the source distribution.  For an
example, let's look at the Distutils' own manifest template::

   include *.txt
   recursive-include examples *.txt *.py
   prune examples/sample?/build

The meanings should be fairly clear: include all files in the distribution root
matching :file:`\*.txt`, all files anywhere under the :file:`examples` directory
matching :file:`\*.txt` or :file:`\*.py`, and exclude all directories matching
:file:`examples/sample?/build`.  All of this is done *after* the standard
include set, so you can exclude files from the standard set with explicit
instructions in the manifest template.  (Or, you can use the
:option:`!--no-defaults` option to disable the standard set entirely.)

The order of commands in the manifest template matters: initially, we have the
list of default files as described above, and each command in the template adds
to or removes from that list of files.  Once we have fully processed the
manifest template, we remove files that should not be included in the source
distribution:

* all files in the Distutils "build" tree (default :file:`build/`)

* all files in directories named :file:`RCS`, :file:`CVS`, :file:`.svn`,
  :file:`.hg`, :file:`.git`, :file:`.bzr` or :file:`_darcs`

Now we have our complete list of files, which is written to the manifest for
future reference, and then used to build the source distribution archive(s).

You can disable the default set of included files with the
:option:`!--no-defaults` option, and you can disable the standard exclude set
with :option:`!--no-prune`.

Following the Distutils' own manifest template, let's trace how the
:command:`sdist` command builds the list of files to include in the Distutils
source distribution:

#. include all Python source files in the :file:`distutils` and
   :file:`distutils/command` subdirectories (because packages corresponding to
   those two directories were mentioned in the ``packages`` option in the
   setup script---see section :ref:`setup-script`)

#. include :file:`README.txt`, :file:`setup.py`, and :file:`setup.cfg` (standard
   files)

#. include :file:`test/test\*.py` (standard files)

#. include :file:`\*.txt` in the distribution root (this will find
   :file:`README.txt` a second time, but such redundancies are weeded out later)

#. include anything matching :file:`\*.txt` or :file:`\*.py` in the sub-tree
   under :file:`examples`,

#. exclude all files in the sub-trees starting at directories matching
   :file:`examples/sample?/build`\ ---this may exclude files included by the
   previous two steps, so it's important that the ``prune`` command in the manifest
   template comes after the ``recursive-include`` command

#. exclude the entire :file:`build` tree, and any :file:`RCS`, :file:`CVS`,
   :file:`.svn`, :file:`.hg`, :file:`.git`, :file:`.bzr` and :file:`_darcs`
   directories

Just like in the setup script, file and directory names in the manifest template
should always be slash-separated; the Distutils will take care of converting
them to the standard representation on your platform. That way, the manifest
template is portable across operating systems.

Commands
--------

The manifest template commands are:

+-------------------------------------------+-----------------------------------------------+
| Command                                   | Description                                   |
+===========================================+===============================================+
| :command:`include pat1 pat2 ...`          | include all files matching any of the listed  |
|                                           | patterns                                      |
+-------------------------------------------+-----------------------------------------------+
| :command:`exclude pat1 pat2 ...`          | exclude all files matching any of the listed  |
|                                           | patterns                                      |
+-------------------------------------------+-----------------------------------------------+
| :command:`recursive-include dir pat1 pat2 | include all files under *dir* matching any of |
| ...`                                      | the listed patterns                           |
+-------------------------------------------+-----------------------------------------------+
| :command:`recursive-exclude dir pat1 pat2 | exclude all files under *dir* matching any of |
| ...`                                      | the listed patterns                           |
+-------------------------------------------+-----------------------------------------------+
| :command:`global-include pat1 pat2 ...`   | include all files anywhere in the source tree |
|                                           | matching --- & any of the listed patterns     |
+-------------------------------------------+-----------------------------------------------+
| :command:`global-exclude pat1 pat2 ...`   | exclude all files anywhere in the source tree |
|                                           | matching --- & any of the listed patterns     |
+-------------------------------------------+-----------------------------------------------+
| :command:`prune dir`                      | exclude all files under *dir*                 |
+-------------------------------------------+-----------------------------------------------+
| :command:`graft dir`                      | include all files under *dir*                 |
+-------------------------------------------+-----------------------------------------------+

The patterns here are Unix-style "glob" patterns: ``*`` matches any sequence of
regular filename characters, ``?`` matches any single regular filename
character, and ``[range]`` matches any of the characters in *range* (e.g.,
``a-z``, ``a-zA-Z``, ``a-f0-9_.``).  The definition of "regular filename
character" is platform-specific: on Unix it is anything except slash; on Windows
anything except backslash or colon.
PK	%�\7Ru���)html/_sources/distutils/uploading.rst.txtnu�[���:orphan:

***************************************
Uploading Packages to the Package Index
***************************************

The contents of this page have moved to the section :ref:`package-index`.
PK	%�\� �V(html/_sources/extending/building.rst.txtnu�[���.. highlightlang:: c


.. _building:

********************************************
Building C and C++ Extensions with distutils
********************************************

.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


Starting in Python 1.4, Python provides, on Unix, a special make file for
building make files for building dynamically-linked extensions and custom
interpreters.  Starting with Python 2.0, this mechanism (known as related to
Makefile.pre.in, and Setup files) is no longer supported. Building custom
interpreters was rarely used, and extension modules can be built using
distutils.

Building an extension module using distutils requires that distutils is
installed on the build machine, which is included in Python 2.x and available
separately for Python 1.5. Since distutils also supports creation of binary
packages, users don't necessarily need a compiler and distutils to install the
extension.

A distutils package contains a driver script, :file:`setup.py`. This is a plain
Python file, which, in the most simple case, could look like this:

.. code-block:: python

   from distutils.core import setup, Extension

   module1 = Extension('demo',
                       sources = ['demo.c'])

   setup (name = 'PackageName',
          version = '1.0',
          description = 'This is a demo package',
          ext_modules = [module1])


With this :file:`setup.py`, and a file :file:`demo.c`, running ::

   python setup.py build

will compile :file:`demo.c`, and produce an extension module named ``demo`` in
the :file:`build` directory. Depending on the system, the module file will end
up in a subdirectory :file:`build/lib.system`, and may have a name like
:file:`demo.so` or :file:`demo.pyd`.

In the :file:`setup.py`, all execution is performed by calling the ``setup``
function. This takes a variable number of keyword arguments, of which the
example above uses only a subset. Specifically, the example specifies
meta-information to build packages, and it specifies the contents of the
package.  Normally, a package will contain of addition modules, like Python
source modules, documentation, subpackages, etc. Please refer to the distutils
documentation in :ref:`distutils-index` to learn more about the features of
distutils; this section explains building extension modules only.

It is common to pre-compute arguments to :func:`setup`, to better structure the
driver script. In the example above, the ``ext_modules`` argument to
:func:`setup` is a list of extension modules, each of which is an instance of
the :class:`~distutils.extension.Extension`. In the example, the instance
defines an extension named ``demo`` which is build by compiling a single source
file, :file:`demo.c`.

In many cases, building an extension is more complex, since additional
preprocessor defines and libraries may be needed. This is demonstrated in the
example below.

.. code-block:: python

   from distutils.core import setup, Extension

   module1 = Extension('demo',
                       define_macros = [('MAJOR_VERSION', '1'),
                                        ('MINOR_VERSION', '0')],
                       include_dirs = ['/usr/local/include'],
                       libraries = ['tcl83'],
                       library_dirs = ['/usr/local/lib'],
                       sources = ['demo.c'])

   setup (name = 'PackageName',
          version = '1.0',
          description = 'This is a demo package',
          author = 'Martin v. Loewis',
          author_email = 'martin@v.loewis.de',
          url = 'https://docs.python.org/extending/building',
          long_description = '''
   This is really just a demo package.
   ''',
          ext_modules = [module1])


In this example, :func:`setup` is called with additional meta-information, which
is recommended when distribution packages have to be built. For the extension
itself, it specifies preprocessor defines, include directories, library
directories, and libraries. Depending on the compiler, distutils passes this
information in different ways to the compiler. For example, on Unix, this may
result in the compilation commands ::

   gcc -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DMAJOR_VERSION=1 -DMINOR_VERSION=0 -I/usr/local/include -I/usr/local/include/python2.2 -c demo.c -o build/temp.linux-i686-2.2/demo.o

   gcc -shared build/temp.linux-i686-2.2/demo.o -L/usr/local/lib -ltcl83 -o build/lib.linux-i686-2.2/demo.so

These lines are for demonstration purposes only; distutils users should trust
that distutils gets the invocations right.


.. _distributing:

Distributing your extension modules
===================================

When an extension has been successfully build, there are three ways to use it.

End-users will typically want to install the module, they do so by running ::

   python setup.py install

Module maintainers should produce source packages; to do so, they run ::

   python setup.py sdist

In some cases, additional files need to be included in a source distribution;
this is done through a :file:`MANIFEST.in` file; see the distutils documentation
for details.

If the source distribution has been build successfully, maintainers can also
create binary distributions. Depending on the platform, one of the following
commands can be used to do so. ::

   python setup.py bdist_wininst
   python setup.py bdist_rpm
   python setup.py bdist_dumb
PK	%�\�w��{/{/)html/_sources/extending/embedding.rst.txtnu�[���.. highlightlang:: c


.. _embedding:

***************************************
Embedding Python in Another Application
***************************************

The previous chapters discussed how to extend Python, that is, how to extend the
functionality of Python by attaching a library of C functions to it.  It is also
possible to do it the other way around: enrich your C/C++ application by
embedding Python in it.  Embedding provides your application with the ability to
implement some of the functionality of your application in Python rather than C
or C++. This can be used for many purposes; one example would be to allow users
to tailor the application to their needs by writing some scripts in Python.  You
can also use it yourself if some of the functionality can be written in Python
more easily.

Embedding Python is similar to extending it, but not quite.  The difference is
that when you extend Python, the main program of the application is still the
Python interpreter, while if you embed Python, the main program may have nothing
to do with Python --- instead, some parts of the application occasionally call
the Python interpreter to run some Python code.

So if you are embedding Python, you are providing your own main program.  One of
the things this main program has to do is initialize the Python interpreter.  At
the very least, you have to call the function :c:func:`Py_Initialize`.  There are
optional calls to pass command line arguments to Python.  Then later you can
call the interpreter from any part of the application.

There are several different ways to call the interpreter: you can pass a string
containing Python statements to :c:func:`PyRun_SimpleString`, or you can pass a
stdio file pointer and a file name (for identification in error messages only)
to :c:func:`PyRun_SimpleFile`.  You can also call the lower-level operations
described in the previous chapters to construct and use Python objects.

A simple demo of embedding Python can be found in the directory
:file:`Demo/embed/` of the source distribution.


.. seealso::

   :ref:`c-api-index`
      The details of Python's C interface are given in this manual. A great deal of
      necessary information can be found here.


.. _high-level-embedding:

Very High Level Embedding
=========================

The simplest form of embedding Python is the use of the very high level
interface. This interface is intended to execute a Python script without needing
to interact with the application directly. This can for example be used to
perform some operation on a file. ::

   #include <Python.h>

   int
   main(int argc, char *argv[])
   {
     Py_SetProgramName(argv[0]);  /* optional but recommended */
     Py_Initialize();
     PyRun_SimpleString("from time import time,ctime\n"
                        "print 'Today is',ctime(time())\n");
     Py_Finalize();
     return 0;
   }

The :c:func:`Py_SetProgramName` function should be called before
:c:func:`Py_Initialize` to inform the interpreter about paths to Python run-time
libraries.  Next, the Python interpreter is initialized with
:c:func:`Py_Initialize`, followed by the execution of a hard-coded Python script
that prints the date and time.  Afterwards, the :c:func:`Py_Finalize` call shuts
the interpreter down, followed by the end of the program.  In a real program,
you may want to get the Python script from another source, perhaps a text-editor
routine, a file, or a database.  Getting the Python code from a file can better
be done by using the :c:func:`PyRun_SimpleFile` function, which saves you the
trouble of allocating memory space and loading the file contents.


.. _lower-level-embedding:

Beyond Very High Level Embedding: An overview
=============================================

The high level interface gives you the ability to execute arbitrary pieces of
Python code from your application, but exchanging data values is quite
cumbersome to say the least. If you want that, you should use lower level calls.
At the cost of having to write more C code, you can achieve almost anything.

It should be noted that extending Python and embedding Python is quite the same
activity, despite the different intent. Most topics discussed in the previous
chapters are still valid. To show this, consider what the extension code from
Python to C really does:

#. Convert data values from Python to C,

#. Perform a function call to a C routine using the converted values, and

#. Convert the data values from the call from C to Python.

When embedding Python, the interface code does:

#. Convert data values from C to Python,

#. Perform a function call to a Python interface routine using the converted
   values, and

#. Convert the data values from the call from Python to C.

As you can see, the data conversion steps are simply swapped to accommodate the
different direction of the cross-language transfer. The only difference is the
routine that you call between both data conversions. When extending, you call a
C routine, when embedding, you call a Python routine.

This chapter will not discuss how to convert data from Python to C and vice
versa.  Also, proper use of references and dealing with errors is assumed to be
understood.  Since these aspects do not differ from extending the interpreter,
you can refer to earlier chapters for the required information.


.. _pure-embedding:

Pure Embedding
==============

The first program aims to execute a function in a Python script. Like in the
section about the very high level interface, the Python interpreter does not
directly interact with the application (but that will change in the next
section).

The code to run a function defined in a Python script is:

.. literalinclude:: ../includes/run-func.c


This code loads a Python script using ``argv[1]``, and calls the function named
in ``argv[2]``.  Its integer arguments are the other values of the ``argv``
array.  If you compile and link this program (let's call the finished executable
:program:`call`), and use it to execute a Python script, such as:

.. code-block:: python

   def multiply(a,b):
       print "Will compute", a, "times", b
       c = 0
       for i in range(0, a):
           c = c + b
       return c

then the result should be:

.. code-block:: shell-session

   $ call multiply multiply 3 2
   Will compute 3 times 2
   Result of call: 6

Although the program is quite large for its functionality, most of the code is
for data conversion between Python and C, and for error reporting.  The
interesting part with respect to embedding Python starts with ::

   Py_Initialize();
   pName = PyString_FromString(argv[1]);
   /* Error checking of pName left out */
   pModule = PyImport_Import(pName);

After initializing the interpreter, the script is loaded using
:c:func:`PyImport_Import`.  This routine needs a Python string as its argument,
which is constructed using the :c:func:`PyString_FromString` data conversion
routine. ::

   pFunc = PyObject_GetAttrString(pModule, argv[2]);
   /* pFunc is a new reference */

   if (pFunc && PyCallable_Check(pFunc)) {
       ...
   }
   Py_XDECREF(pFunc);

Once the script is loaded, the name we're looking for is retrieved using
:c:func:`PyObject_GetAttrString`.  If the name exists, and the object returned is
callable, you can safely assume that it is a function.  The program then
proceeds by constructing a tuple of arguments as normal.  The call to the Python
function is then made with::

   pValue = PyObject_CallObject(pFunc, pArgs);

Upon return of the function, ``pValue`` is either *NULL* or it contains a
reference to the return value of the function.  Be sure to release the reference
after examining the value.


.. _extending-with-embedding:

Extending Embedded Python
=========================

Until now, the embedded Python interpreter had no access to functionality from
the application itself.  The Python API allows this by extending the embedded
interpreter.  That is, the embedded interpreter gets extended with routines
provided by the application. While it sounds complex, it is not so bad.  Simply
forget for a while that the application starts the Python interpreter.  Instead,
consider the application to be a set of subroutines, and write some glue code
that gives Python access to those routines, just like you would write a normal
Python extension.  For example::

   static int numargs=0;

   /* Return the number of arguments of the application command line */
   static PyObject*
   emb_numargs(PyObject *self, PyObject *args)
   {
       if(!PyArg_ParseTuple(args, ":numargs"))
           return NULL;
       return Py_BuildValue("i", numargs);
   }

   static PyMethodDef EmbMethods[] = {
       {"numargs", emb_numargs, METH_VARARGS,
        "Return the number of arguments received by the process."},
       {NULL, NULL, 0, NULL}
   };

Insert the above code just above the :c:func:`main` function. Also, insert the
following two statements directly after :c:func:`Py_Initialize`::

   numargs = argc;
   Py_InitModule("emb", EmbMethods);

These two lines initialize the ``numargs`` variable, and make the
:func:`emb.numargs` function accessible to the embedded Python interpreter.
With these extensions, the Python script can do things like

.. code-block:: python

   import emb
   print "Number of arguments", emb.numargs()

In a real application, the methods will expose an API of the application to
Python.

.. TODO: threads, code examples do not really behave well if errors happen
   (what to watch out for)


.. _embeddingincplusplus:

Embedding Python in C++
=======================

It is also possible to embed Python in a C++ program; precisely how this is done
will depend on the details of the C++ system used; in general you will need to
write the main program in C++, and use the C++ compiler to compile and link your
program.  There is no need to recompile Python itself using C++.


.. _link-reqs:

Compiling and Linking under Unix-like systems
=============================================

It is not necessarily trivial to find the right flags to pass to your
compiler (and linker) in order to embed the Python interpreter into your
application, particularly because Python needs to load library modules
implemented as C dynamic extensions (:file:`.so` files) linked against
it.

To find out the required compiler and linker flags, you can execute the
:file:`python{X.Y}-config` script which is generated as part of the
installation process (a :file:`python-config` script may also be
available).  This script has several options, of which the following will
be directly useful to you:

* ``pythonX.Y-config --cflags`` will give you the recommended flags when
  compiling:

  .. code-block:: shell-session

     $ /opt/bin/python2.7-config --cflags
     -I/opt/include/python2.7 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes

* ``pythonX.Y-config --ldflags`` will give you the recommended flags when
  linking:

  .. code-block:: shell-session

     $ /opt/bin/python2.7-config --ldflags
     -L/opt/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic

.. note::
   To avoid confusion between several Python installations (and especially
   between the system Python and your own compiled Python), it is recommended
   that you use the absolute path to :file:`python{X.Y}-config`, as in the above
   example.

If this procedure doesn't work for you (it is not guaranteed to work for
all Unix-like platforms; however, we welcome :ref:`bug reports <reporting-bugs>`)
you will have to read your system's documentation about dynamic linking and/or
examine Python's :file:`Makefile` (use :func:`sysconfig.get_makefile_filename`
to find its location) and compilation
options.  In this case, the :mod:`sysconfig` module is a useful tool to
programmatically extract the configuration values that you will want to
combine together.  For example:

.. code-block:: python

   >>> import sysconfig
   >>> sysconfig.get_config_var('LIBS')
   '-lpthread -ldl  -lutil'
   >>> sysconfig.get_config_var('LINKFORSHARED')
   '-Xlinker -export-dynamic'


.. XXX similar documentation for Windows missing
PK	%�\��1N����)html/_sources/extending/extending.rst.txtnu�[���.. highlightlang:: c


.. _extending-intro:

******************************
Extending Python with C or C++
******************************

It is quite easy to add new built-in modules to Python, if you know how to
program in C.  Such :dfn:`extension modules` can do two things that can't be
done directly in Python: they can implement new built-in object types, and they
can call C library functions and system calls.

To support extensions, the Python API (Application Programmers Interface)
defines a set of functions, macros and variables that provide access to most
aspects of the Python run-time system.  The Python API is incorporated in a C
source file by including the header ``"Python.h"``.

The compilation of an extension module depends on its intended use as well as on
your system setup; details are given in later chapters.

.. note::

   The C extension interface is specific to CPython, and extension modules do
   not work on other Python implementations.  In many cases, it is possible to
   avoid writing C extensions and preserve portability to other implementations.
   For example, if your use case is calling C library functions or system calls,
   you should consider using the :mod:`ctypes` module or the `cffi
   <https://cffi.readthedocs.org>`_ library rather than writing custom C code.
   These modules let you write Python code to interface with C code and are more
   portable between implementations of Python than writing and compiling a C
   extension module.


.. _extending-simpleexample:

A Simple Example
================

Let's create an extension module called ``spam`` (the favorite food of Monty
Python fans...) and let's say we want to create a Python interface to the C
library function :c:func:`system` [#]_. This function takes a null-terminated
character string as argument and returns an integer.  We want this function to
be callable from Python as follows::

   >>> import spam
   >>> status = spam.system("ls -l")

Begin by creating a file :file:`spammodule.c`.  (Historically, if a module is
called ``spam``, the C file containing its implementation is called
:file:`spammodule.c`; if the module name is very long, like ``spammify``, the
module name can be just :file:`spammify.c`.)

The first line of our file can be::

   #include <Python.h>

which pulls in the Python API (you can add a comment describing the purpose of
the module and a copyright notice if you like).

.. note::

   Since Python may define some pre-processor definitions which affect the standard
   headers on some systems, you *must* include :file:`Python.h` before any standard
   headers are included.

All user-visible symbols defined by :file:`Python.h` have a prefix of ``Py`` or
``PY``, except those defined in standard header files. For convenience, and
since they are used extensively by the Python interpreter, ``"Python.h"``
includes a few standard header files: ``<stdio.h>``, ``<string.h>``,
``<errno.h>``, and ``<stdlib.h>``.  If the latter header file does not exist on
your system, it declares the functions :c:func:`malloc`, :c:func:`free` and
:c:func:`realloc` directly.

The next thing we add to our module file is the C function that will be called
when the Python expression ``spam.system(string)`` is evaluated (we'll see
shortly how it ends up being called)::

   static PyObject *
   spam_system(PyObject *self, PyObject *args)
   {
       const char *command;
       int sts;

       if (!PyArg_ParseTuple(args, "s", &command))
           return NULL;
       sts = system(command);
       return Py_BuildValue("i", sts);
   }

There is a straightforward translation from the argument list in Python (for
example, the single expression ``"ls -l"``) to the arguments passed to the C
function.  The C function always has two arguments, conventionally named *self*
and *args*.

For module functions, the *self* argument is *NULL* or a pointer selected while
initializing the module (see :c:func:`Py_InitModule4`).  For a method, it would
point to the object instance.

The *args* argument will be a pointer to a Python tuple object containing the
arguments.  Each item of the tuple corresponds to an argument in the call's
argument list.  The arguments are Python objects --- in order to do anything
with them in our C function we have to convert them to C values.  The function
:c:func:`PyArg_ParseTuple` in the Python API checks the argument types and
converts them to C values.  It uses a template string to determine the required
types of the arguments as well as the types of the C variables into which to
store the converted values.  More about this later.

:c:func:`PyArg_ParseTuple` returns true (nonzero) if all arguments have the right
type and its components have been stored in the variables whose addresses are
passed.  It returns false (zero) if an invalid argument list was passed.  In the
latter case it also raises an appropriate exception so the calling function can
return *NULL* immediately (as we saw in the example).


.. _extending-errors:

Intermezzo: Errors and Exceptions
=================================

An important convention throughout the Python interpreter is the following: when
a function fails, it should set an exception condition and return an error value
(usually a *NULL* pointer).  Exceptions are stored in a static global variable
inside the interpreter; if this variable is *NULL* no exception has occurred.  A
second global variable stores the "associated value" of the exception (the
second argument to :keyword:`raise`).  A third variable contains the stack
traceback in case the error originated in Python code.  These three variables
are the C equivalents of the Python variables ``sys.exc_type``,
``sys.exc_value`` and ``sys.exc_traceback`` (see the section on module
:mod:`sys` in the Python Library Reference).  It is important to know about them
to understand how errors are passed around.

The Python API defines a number of functions to set various types of exceptions.

The most common one is :c:func:`PyErr_SetString`.  Its arguments are an exception
object and a C string.  The exception object is usually a predefined object like
:c:data:`PyExc_ZeroDivisionError`.  The C string indicates the cause of the error
and is converted to a Python string object and stored as the "associated value"
of the exception.

Another useful function is :c:func:`PyErr_SetFromErrno`, which only takes an
exception argument and constructs the associated value by inspection of the
global variable :c:data:`errno`.  The most general function is
:c:func:`PyErr_SetObject`, which takes two object arguments, the exception and
its associated value.  You don't need to :c:func:`Py_INCREF` the objects passed
to any of these functions.

You can test non-destructively whether an exception has been set with
:c:func:`PyErr_Occurred`.  This returns the current exception object, or *NULL*
if no exception has occurred.  You normally don't need to call
:c:func:`PyErr_Occurred` to see whether an error occurred in a function call,
since you should be able to tell from the return value.

When a function *f* that calls another function *g* detects that the latter
fails, *f* should itself return an error value (usually *NULL* or ``-1``).  It
should *not* call one of the :c:func:`PyErr_\*` functions --- one has already
been called by *g*. *f*'s caller is then supposed to also return an error
indication to *its* caller, again *without* calling :c:func:`PyErr_\*`, and so on
--- the most detailed cause of the error was already reported by the function
that first detected it.  Once the error reaches the Python interpreter's main
loop, this aborts the currently executing Python code and tries to find an
exception handler specified by the Python programmer.

(There are situations where a module can actually give a more detailed error
message by calling another :c:func:`PyErr_\*` function, and in such cases it is
fine to do so.  As a general rule, however, this is not necessary, and can cause
information about the cause of the error to be lost: most operations can fail
for a variety of reasons.)

To ignore an exception set by a function call that failed, the exception
condition must be cleared explicitly by calling :c:func:`PyErr_Clear`.  The only
time C code should call :c:func:`PyErr_Clear` is if it doesn't want to pass the
error on to the interpreter but wants to handle it completely by itself
(possibly by trying something else, or pretending nothing went wrong).

Every failing :c:func:`malloc` call must be turned into an exception --- the
direct caller of :c:func:`malloc` (or :c:func:`realloc`) must call
:c:func:`PyErr_NoMemory` and return a failure indicator itself.  All the
object-creating functions (for example, :c:func:`PyInt_FromLong`) already do
this, so this note is only relevant to those who call :c:func:`malloc` directly.

Also note that, with the important exception of :c:func:`PyArg_ParseTuple` and
friends, functions that return an integer status usually return a positive value
or zero for success and ``-1`` for failure, like Unix system calls.

Finally, be careful to clean up garbage (by making :c:func:`Py_XDECREF` or
:c:func:`Py_DECREF` calls for objects you have already created) when you return
an error indicator!

The choice of which exception to raise is entirely yours.  There are predeclared
C objects corresponding to all built-in Python exceptions, such as
:c:data:`PyExc_ZeroDivisionError`, which you can use directly. Of course, you
should choose exceptions wisely --- don't use :c:data:`PyExc_TypeError` to mean
that a file couldn't be opened (that should probably be :c:data:`PyExc_IOError`).
If something's wrong with the argument list, the :c:func:`PyArg_ParseTuple`
function usually raises :c:data:`PyExc_TypeError`.  If you have an argument whose
value must be in a particular range or must satisfy other conditions,
:c:data:`PyExc_ValueError` is appropriate.

You can also define a new exception that is unique to your module. For this, you
usually declare a static object variable at the beginning of your file::

   static PyObject *SpamError;

and initialize it in your module's initialization function (:c:func:`initspam`)
with an exception object (leaving out the error checking for now)::

   PyMODINIT_FUNC
   initspam(void)
   {
       PyObject *m;

       m = Py_InitModule("spam", SpamMethods);
       if (m == NULL)
           return;

       SpamError = PyErr_NewException("spam.error", NULL, NULL);
       Py_INCREF(SpamError);
       PyModule_AddObject(m, "error", SpamError);
   }

Note that the Python name for the exception object is :exc:`spam.error`.  The
:c:func:`PyErr_NewException` function may create a class with the base class
being :exc:`Exception` (unless another class is passed in instead of *NULL*),
described in :ref:`bltin-exceptions`.

Note also that the :c:data:`SpamError` variable retains a reference to the newly
created exception class; this is intentional!  Since the exception could be
removed from the module by external code, an owned reference to the class is
needed to ensure that it will not be discarded, causing :c:data:`SpamError` to
become a dangling pointer. Should it become a dangling pointer, C code which
raises the exception could cause a core dump or other unintended side effects.

We discuss the use of ``PyMODINIT_FUNC`` as a function return type later in this
sample.

The :exc:`spam.error` exception can be raised in your extension module using a
call to :c:func:`PyErr_SetString` as shown below::

   static PyObject *
   spam_system(PyObject *self, PyObject *args)
   {
       const char *command;
       int sts;

       if (!PyArg_ParseTuple(args, "s", &command))
           return NULL;
       sts = system(command);
       if (sts < 0) {
           PyErr_SetString(SpamError, "System command failed");
           return NULL;
       }
       return PyLong_FromLong(sts);
   }


.. _backtoexample:

Back to the Example
===================

Going back to our example function, you should now be able to understand this
statement::

   if (!PyArg_ParseTuple(args, "s", &command))
       return NULL;

It returns *NULL* (the error indicator for functions returning object pointers)
if an error is detected in the argument list, relying on the exception set by
:c:func:`PyArg_ParseTuple`.  Otherwise the string value of the argument has been
copied to the local variable :c:data:`command`.  This is a pointer assignment and
you are not supposed to modify the string to which it points (so in Standard C,
the variable :c:data:`command` should properly be declared as ``const char
*command``).

The next statement is a call to the Unix function :c:func:`system`, passing it
the string we just got from :c:func:`PyArg_ParseTuple`::

   sts = system(command);

Our :func:`spam.system` function must return the value of :c:data:`sts` as a
Python object.  This is done using the function :c:func:`Py_BuildValue`, which is
something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format
string and an arbitrary number of C values, and returns a new Python object.
More info on :c:func:`Py_BuildValue` is given later. ::

   return Py_BuildValue("i", sts);

In this case, it will return an integer object.  (Yes, even integers are objects
on the heap in Python!)

If you have a C function that returns no useful argument (a function returning
:c:type:`void`), the corresponding Python function must return ``None``.   You
need this idiom to do so (which is implemented by the :c:macro:`Py_RETURN_NONE`
macro)::

   Py_INCREF(Py_None);
   return Py_None;

:c:data:`Py_None` is the C name for the special Python object ``None``.  It is a
genuine Python object rather than a *NULL* pointer, which means "error" in most
contexts, as we have seen.


.. _methodtable:

The Module's Method Table and Initialization Function
=====================================================

I promised to show how :c:func:`spam_system` is called from Python programs.
First, we need to list its name and address in a "method table"::

   static PyMethodDef SpamMethods[] = {
       ...
       {"system",  spam_system, METH_VARARGS,
        "Execute a shell command."},
       ...
       {NULL, NULL, 0, NULL}        /* Sentinel */
   };

Note the third entry (``METH_VARARGS``).  This is a flag telling the interpreter
the calling convention to be used for the C function.  It should normally always
be ``METH_VARARGS`` or ``METH_VARARGS | METH_KEYWORDS``; a value of ``0`` means
that an obsolete variant of :c:func:`PyArg_ParseTuple` is used.

When using only ``METH_VARARGS``, the function should expect the Python-level
parameters to be passed in as a tuple acceptable for parsing via
:c:func:`PyArg_ParseTuple`; more information on this function is provided below.

The :const:`METH_KEYWORDS` bit may be set in the third field if keyword
arguments should be passed to the function.  In this case, the C function should
accept a third ``PyObject *`` parameter which will be a dictionary of keywords.
Use :c:func:`PyArg_ParseTupleAndKeywords` to parse the arguments to such a
function.

The method table must be passed to the interpreter in the module's
initialization function.  The initialization function must be named
:c:func:`initname`, where *name* is the name of the module, and should be the
only non-\ ``static`` item defined in the module file::

   PyMODINIT_FUNC
   initspam(void)
   {
       (void) Py_InitModule("spam", SpamMethods);
   }

Note that PyMODINIT_FUNC declares the function as ``void`` return type,
declares any special linkage declarations required by the platform, and for  C++
declares the function as ``extern "C"``.

When the Python program imports module :mod:`spam` for the first time,
:c:func:`initspam` is called. (See below for comments about embedding Python.)
It calls :c:func:`Py_InitModule`, which creates a "module object" (which is
inserted in the dictionary ``sys.modules`` under the key ``"spam"``), and
inserts built-in function objects into the newly created module based upon the
table (an array of :c:type:`PyMethodDef` structures) that was passed as its
second argument. :c:func:`Py_InitModule` returns a pointer to the module object
that it creates (which is unused here).  It may abort with a fatal error for
certain errors, or return *NULL* if the module could not be initialized
satisfactorily.

When embedding Python, the :c:func:`initspam` function is not called
automatically unless there's an entry in the :c:data:`_PyImport_Inittab` table.
The easiest way to handle this is to statically initialize your
statically-linked modules by directly calling :c:func:`initspam` after the call
to :c:func:`Py_Initialize`::

   int
   main(int argc, char *argv[])
   {
       /* Pass argv[0] to the Python interpreter */
       Py_SetProgramName(argv[0]);

       /* Initialize the Python interpreter.  Required. */
       Py_Initialize();

       /* Add a static module */
       initspam();

       ...

An example may be found in the file :file:`Demo/embed/demo.c` in the Python
source distribution.

.. note::

   Removing entries from ``sys.modules`` or importing compiled modules into
   multiple interpreters within a process (or following a :c:func:`fork` without an
   intervening :c:func:`exec`) can create problems for some extension modules.
   Extension module authors should exercise caution when initializing internal data
   structures. Note also that the :func:`reload` function can be used with
   extension modules, and will call the module initialization function
   (:c:func:`initspam` in the example), but will not load the module again if it was
   loaded from a dynamically loadable object file (:file:`.so` on Unix,
   :file:`.dll` on Windows).

A more substantial example module is included in the Python source distribution
as :file:`Modules/xxmodule.c`.  This file may be used as a  template or simply
read as an example.


.. _compilation:

Compilation and Linkage
=======================

There are two more things to do before you can use your new extension: compiling
and linking it with the Python system.  If you use dynamic loading, the details
may depend on the style of dynamic loading your system uses; see the chapters
about building extension modules (chapter :ref:`building`) and additional
information that pertains only to building on Windows (chapter
:ref:`building-on-windows`) for more information about this.

If you can't use dynamic loading, or if you want to make your module a permanent
part of the Python interpreter, you will have to change the configuration setup
and rebuild the interpreter.  Luckily, this is very simple on Unix: just place
your file (:file:`spammodule.c` for example) in the :file:`Modules/` directory
of an unpacked source distribution, add a line to the file
:file:`Modules/Setup.local` describing your file::

   spam spammodule.o

and rebuild the interpreter by running :program:`make` in the toplevel
directory.  You can also run :program:`make` in the :file:`Modules/`
subdirectory, but then you must first rebuild :file:`Makefile` there by running
':program:`make` Makefile'.  (This is necessary each time you change the
:file:`Setup` file.)

If your module requires additional libraries to link with, these can be listed
on the line in the configuration file as well, for instance::

   spam spammodule.o -lX11


.. _callingpython:

Calling Python Functions from C
===============================

So far we have concentrated on making C functions callable from Python.  The
reverse is also useful: calling Python functions from C. This is especially the
case for libraries that support so-called "callback" functions.  If a C
interface makes use of callbacks, the equivalent Python often needs to provide a
callback mechanism to the Python programmer; the implementation will require
calling the Python callback functions from a C callback.  Other uses are also
imaginable.

Fortunately, the Python interpreter is easily called recursively, and there is a
standard interface to call a Python function.  (I won't dwell on how to call the
Python parser with a particular string as input --- if you're interested, have a
look at the implementation of the :option:`-c` command line option in
:file:`Modules/main.c` from the Python source code.)

Calling a Python function is easy.  First, the Python program must somehow pass
you the Python function object.  You should provide a function (or some other
interface) to do this.  When this function is called, save a pointer to the
Python function object (be careful to :c:func:`Py_INCREF` it!) in a global
variable --- or wherever you see fit. For example, the following function might
be part of a module definition::

   static PyObject *my_callback = NULL;

   static PyObject *
   my_set_callback(PyObject *dummy, PyObject *args)
   {
       PyObject *result = NULL;
       PyObject *temp;

       if (PyArg_ParseTuple(args, "O:set_callback", &temp)) {
           if (!PyCallable_Check(temp)) {
               PyErr_SetString(PyExc_TypeError, "parameter must be callable");
               return NULL;
           }
           Py_XINCREF(temp);         /* Add a reference to new callback */
           Py_XDECREF(my_callback);  /* Dispose of previous callback */
           my_callback = temp;       /* Remember new callback */
           /* Boilerplate to return "None" */
           Py_INCREF(Py_None);
           result = Py_None;
       }
       return result;
   }

This function must be registered with the interpreter using the
:const:`METH_VARARGS` flag; this is described in section :ref:`methodtable`.  The
:c:func:`PyArg_ParseTuple` function and its arguments are documented in section
:ref:`parsetuple`.

The macros :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF` increment/decrement the
reference count of an object and are safe in the presence of *NULL* pointers
(but note that *temp* will not be  *NULL* in this context).  More info on them
in section :ref:`refcounts`.

.. index:: single: PyObject_CallObject()

Later, when it is time to call the function, you call the C function
:c:func:`PyObject_CallObject`.  This function has two arguments, both pointers to
arbitrary Python objects: the Python function, and the argument list.  The
argument list must always be a tuple object, whose length is the number of
arguments.  To call the Python function with no arguments, pass in NULL, or
an empty tuple; to call it with one argument, pass a singleton tuple.
:c:func:`Py_BuildValue` returns a tuple when its format string consists of zero
or more format codes between parentheses.  For example::

   int arg;
   PyObject *arglist;
   PyObject *result;
   ...
   arg = 123;
   ...
   /* Time to call the callback */
   arglist = Py_BuildValue("(i)", arg);
   result = PyObject_CallObject(my_callback, arglist);
   Py_DECREF(arglist);

:c:func:`PyObject_CallObject` returns a Python object pointer: this is the return
value of the Python function.  :c:func:`PyObject_CallObject` is
"reference-count-neutral" with respect to its arguments.  In the example a new
tuple was created to serve as the argument list, which is :c:func:`Py_DECREF`\
-ed immediately after the :c:func:`PyObject_CallObject` call.

The return value of :c:func:`PyObject_CallObject` is "new": either it is a brand
new object, or it is an existing object whose reference count has been
incremented.  So, unless you want to save it in a global variable, you should
somehow :c:func:`Py_DECREF` the result, even (especially!) if you are not
interested in its value.

Before you do this, however, it is important to check that the return value
isn't *NULL*.  If it is, the Python function terminated by raising an exception.
If the C code that called :c:func:`PyObject_CallObject` is called from Python, it
should now return an error indication to its Python caller, so the interpreter
can print a stack trace, or the calling Python code can handle the exception.
If this is not possible or desirable, the exception should be cleared by calling
:c:func:`PyErr_Clear`.  For example::

   if (result == NULL)
       return NULL; /* Pass error back */
   ...use result...
   Py_DECREF(result);

Depending on the desired interface to the Python callback function, you may also
have to provide an argument list to :c:func:`PyObject_CallObject`.  In some cases
the argument list is also provided by the Python program, through the same
interface that specified the callback function.  It can then be saved and used
in the same manner as the function object.  In other cases, you may have to
construct a new tuple to pass as the argument list.  The simplest way to do this
is to call :c:func:`Py_BuildValue`.  For example, if you want to pass an integral
event code, you might use the following code::

   PyObject *arglist;
   ...
   arglist = Py_BuildValue("(l)", eventcode);
   result = PyObject_CallObject(my_callback, arglist);
   Py_DECREF(arglist);
   if (result == NULL)
       return NULL; /* Pass error back */
   /* Here maybe use the result */
   Py_DECREF(result);

Note the placement of ``Py_DECREF(arglist)`` immediately after the call, before
the error check!  Also note that strictly speaking this code is not complete:
:c:func:`Py_BuildValue` may run out of memory, and this should be checked.

You may also call a function with keyword arguments by using
:c:func:`PyObject_Call`, which supports arguments and keyword arguments.  As in
the above example, we use :c:func:`Py_BuildValue` to construct the dictionary. ::

   PyObject *dict;
   ...
   dict = Py_BuildValue("{s:i}", "name", val);
   result = PyObject_Call(my_callback, NULL, dict);
   Py_DECREF(dict);
   if (result == NULL)
       return NULL; /* Pass error back */
   /* Here maybe use the result */
   Py_DECREF(result);


.. _parsetuple:

Extracting Parameters in Extension Functions
============================================

.. index:: single: PyArg_ParseTuple()

The :c:func:`PyArg_ParseTuple` function is declared as follows::

   int PyArg_ParseTuple(PyObject *arg, char *format, ...);

The *arg* argument must be a tuple object containing an argument list passed
from Python to a C function.  The *format* argument must be a format string,
whose syntax is explained in :ref:`arg-parsing` in the Python/C API Reference
Manual.  The remaining arguments must be addresses of variables whose type is
determined by the format string.

Note that while :c:func:`PyArg_ParseTuple` checks that the Python arguments have
the required types, it cannot check the validity of the addresses of C variables
passed to the call: if you make mistakes there, your code will probably crash or
at least overwrite random bits in memory.  So be careful!

Note that any Python object references which are provided to the caller are
*borrowed* references; do not decrement their reference count!

Some example calls::

   int ok;
   int i, j;
   long k, l;
   const char *s;
   int size;

   ok = PyArg_ParseTuple(args, ""); /* No arguments */
       /* Python call: f() */

::

   ok = PyArg_ParseTuple(args, "s", &s); /* A string */
       /* Possible Python call: f('whoops!') */

::

   ok = PyArg_ParseTuple(args, "lls", &k, &l, &s); /* Two longs and a string */
       /* Possible Python call: f(1, 2, 'three') */

::

   ok = PyArg_ParseTuple(args, "(ii)s#", &i, &j, &s, &size);
       /* A pair of ints and a string, whose size is also returned */
       /* Possible Python call: f((1, 2), 'three') */

::

   {
       const char *file;
       const char *mode = "r";
       int bufsize = 0;
       ok = PyArg_ParseTuple(args, "s|si", &file, &mode, &bufsize);
       /* A string, and optionally another string and an integer */
       /* Possible Python calls:
          f('spam')
          f('spam', 'w')
          f('spam', 'wb', 100000) */
   }

::

   {
       int left, top, right, bottom, h, v;
       ok = PyArg_ParseTuple(args, "((ii)(ii))(ii)",
                &left, &top, &right, &bottom, &h, &v);
       /* A rectangle and a point */
       /* Possible Python call:
          f(((0, 0), (400, 300)), (10, 10)) */
   }

::

   {
       Py_complex c;
       ok = PyArg_ParseTuple(args, "D:myfunction", &c);
       /* a complex, also providing a function name for errors */
       /* Possible Python call: myfunction(1+2j) */
   }


.. _parsetupleandkeywords:

Keyword Parameters for Extension Functions
==========================================

.. index:: single: PyArg_ParseTupleAndKeywords()

The :c:func:`PyArg_ParseTupleAndKeywords` function is declared as follows::

   int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                   char *format, char *kwlist[], ...);

The *arg* and *format* parameters are identical to those of the
:c:func:`PyArg_ParseTuple` function.  The *kwdict* parameter is the dictionary of
keywords received as the third parameter from the Python runtime.  The *kwlist*
parameter is a *NULL*-terminated list of strings which identify the parameters;
the names are matched with the type information from *format* from left to
right.  On success, :c:func:`PyArg_ParseTupleAndKeywords` returns true, otherwise
it returns false and raises an appropriate exception.

.. note::

   Nested tuples cannot be parsed when using keyword arguments!  Keyword parameters
   passed in which are not present in the *kwlist* will cause :exc:`TypeError` to
   be raised.

.. index:: single: Philbrick, Geoff

Here is an example module which uses keywords, based on an example by Geoff
Philbrick (philbrick@hks.com)::

   #include "Python.h"

   static PyObject *
   keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
   {
       int voltage;
       char *state = "a stiff";
       char *action = "voom";
       char *type = "Norwegian Blue";

       static char *kwlist[] = {"voltage", "state", "action", "type", NULL};

       if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist,
                                        &voltage, &state, &action, &type))
           return NULL;

       printf("-- This parrot wouldn't %s if you put %i Volts through it.\n",
              action, voltage);
       printf("-- Lovely plumage, the %s -- It's %s!\n", type, state);

       Py_INCREF(Py_None);

       return Py_None;
   }

   static PyMethodDef keywdarg_methods[] = {
       /* The cast of the function is necessary since PyCFunction values
        * only take two PyObject* parameters, and keywdarg_parrot() takes
        * three.
        */
       {"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
        "Print a lovely skit to standard output."},
       {NULL, NULL, 0, NULL}   /* sentinel */
   };

::

   void
   initkeywdarg(void)
   {
     /* Create the module and add the functions */
     Py_InitModule("keywdarg", keywdarg_methods);
   }


.. _buildvalue:

Building Arbitrary Values
=========================

This function is the counterpart to :c:func:`PyArg_ParseTuple`.  It is declared
as follows::

   PyObject *Py_BuildValue(char *format, ...);

It recognizes a set of format units similar to the ones recognized by
:c:func:`PyArg_ParseTuple`, but the arguments (which are input to the function,
not output) must not be pointers, just values.  It returns a new Python object,
suitable for returning from a C function called from Python.

One difference with :c:func:`PyArg_ParseTuple`: while the latter requires its
first argument to be a tuple (since Python argument lists are always represented
as tuples internally), :c:func:`Py_BuildValue` does not always build a tuple.  It
builds a tuple only if its format string contains two or more format units. If
the format string is empty, it returns ``None``; if it contains exactly one
format unit, it returns whatever object is described by that format unit.  To
force it to return a tuple of size 0 or one, parenthesize the format string.

Examples (to the left the call, to the right the resulting Python value):

.. code-block:: none

   Py_BuildValue("")                        None
   Py_BuildValue("i", 123)                  123
   Py_BuildValue("iii", 123, 456, 789)      (123, 456, 789)
   Py_BuildValue("s", "hello")              'hello'
   Py_BuildValue("ss", "hello", "world")    ('hello', 'world')
   Py_BuildValue("s#", "hello", 4)          'hell'
   Py_BuildValue("()")                      ()
   Py_BuildValue("(i)", 123)                (123,)
   Py_BuildValue("(ii)", 123, 456)          (123, 456)
   Py_BuildValue("(i,i)", 123, 456)         (123, 456)
   Py_BuildValue("[i,i]", 123, 456)         [123, 456]
   Py_BuildValue("{s:i,s:i}",
                 "abc", 123, "def", 456)    {'abc': 123, 'def': 456}
   Py_BuildValue("((ii)(ii)) (ii)",
                 1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))


.. _refcounts:

Reference Counts
================

In languages like C or C++, the programmer is responsible for dynamic allocation
and deallocation of memory on the heap.  In C, this is done using the functions
:c:func:`malloc` and :c:func:`free`.  In C++, the operators ``new`` and
``delete`` are used with essentially the same meaning and we'll restrict
the following discussion to the C case.

Every block of memory allocated with :c:func:`malloc` should eventually be
returned to the pool of available memory by exactly one call to :c:func:`free`.
It is important to call :c:func:`free` at the right time.  If a block's address
is forgotten but :c:func:`free` is not called for it, the memory it occupies
cannot be reused until the program terminates.  This is called a :dfn:`memory
leak`.  On the other hand, if a program calls :c:func:`free` for a block and then
continues to use the block, it creates a conflict with re-use of the block
through another :c:func:`malloc` call.  This is called :dfn:`using freed memory`.
It has the same bad consequences as referencing uninitialized data --- core
dumps, wrong results, mysterious crashes.

Common causes of memory leaks are unusual paths through the code.  For instance,
a function may allocate a block of memory, do some calculation, and then free
the block again.  Now a change in the requirements for the function may add a
test to the calculation that detects an error condition and can return
prematurely from the function.  It's easy to forget to free the allocated memory
block when taking this premature exit, especially when it is added later to the
code.  Such leaks, once introduced, often go undetected for a long time: the
error exit is taken only in a small fraction of all calls, and most modern
machines have plenty of virtual memory, so the leak only becomes apparent in a
long-running process that uses the leaking function frequently.  Therefore, it's
important to prevent leaks from happening by having a coding convention or
strategy that minimizes this kind of errors.

Since Python makes heavy use of :c:func:`malloc` and :c:func:`free`, it needs a
strategy to avoid memory leaks as well as the use of freed memory.  The chosen
method is called :dfn:`reference counting`.  The principle is simple: every
object contains a counter, which is incremented when a reference to the object
is stored somewhere, and which is decremented when a reference to it is deleted.
When the counter reaches zero, the last reference to the object has been deleted
and the object is freed.

An alternative strategy is called :dfn:`automatic garbage collection`.
(Sometimes, reference counting is also referred to as a garbage collection
strategy, hence my use of "automatic" to distinguish the two.)  The big
advantage of automatic garbage collection is that the user doesn't need to call
:c:func:`free` explicitly.  (Another claimed advantage is an improvement in speed
or memory usage --- this is no hard fact however.)  The disadvantage is that for
C, there is no truly portable automatic garbage collector, while reference
counting can be implemented portably (as long as the functions :c:func:`malloc`
and :c:func:`free` are available --- which the C Standard guarantees). Maybe some
day a sufficiently portable automatic garbage collector will be available for C.
Until then, we'll have to live with reference counts.

While Python uses the traditional reference counting implementation, it also
offers a cycle detector that works to detect reference cycles.  This allows
applications to not worry about creating direct or indirect circular references;
these are the weakness of garbage collection implemented using only reference
counting.  Reference cycles consist of objects which contain (possibly indirect)
references to themselves, so that each object in the cycle has a reference count
which is non-zero.  Typical reference counting implementations are not able to
reclaim the memory belonging to any objects in a reference cycle, or referenced
from the objects in the cycle, even though there are no further references to
the cycle itself.

The cycle detector is able to detect garbage cycles and can reclaim them so long
as there are no finalizers implemented in Python (:meth:`__del__` methods).
When there are such finalizers, the detector exposes the cycles through the
:mod:`gc` module (specifically, the :attr:`~gc.garbage` variable in that module).
The :mod:`gc` module also exposes a way to run the detector (the
:func:`~gc.collect` function), as well as configuration
interfaces and the ability to disable the detector at runtime.  The cycle
detector is considered an optional component; though it is included by default,
it can be disabled at build time using the :option:`!--without-cycle-gc` option
to the :program:`configure` script on Unix platforms (including Mac OS X) or by
removing the definition of ``WITH_CYCLE_GC`` in the :file:`pyconfig.h` header on
other platforms.  If the cycle detector is disabled in this way, the :mod:`gc`
module will not be available.


.. _refcountsinpython:

Reference Counting in Python
----------------------------

There are two macros, ``Py_INCREF(x)`` and ``Py_DECREF(x)``, which handle the
incrementing and decrementing of the reference count. :c:func:`Py_DECREF` also
frees the object when the count reaches zero. For flexibility, it doesn't call
:c:func:`free` directly --- rather, it makes a call through a function pointer in
the object's :dfn:`type object`.  For this purpose (and others), every object
also contains a pointer to its type object.

The big question now remains: when to use ``Py_INCREF(x)`` and ``Py_DECREF(x)``?
Let's first introduce some terms.  Nobody "owns" an object; however, you can
:dfn:`own a reference` to an object.  An object's reference count is now defined
as the number of owned references to it.  The owner of a reference is
responsible for calling :c:func:`Py_DECREF` when the reference is no longer
needed.  Ownership of a reference can be transferred.  There are three ways to
dispose of an owned reference: pass it on, store it, or call :c:func:`Py_DECREF`.
Forgetting to dispose of an owned reference creates a memory leak.

It is also possible to :dfn:`borrow` [#]_ a reference to an object.  The
borrower of a reference should not call :c:func:`Py_DECREF`.  The borrower must
not hold on to the object longer than the owner from which it was borrowed.
Using a borrowed reference after the owner has disposed of it risks using freed
memory and should be avoided completely [#]_.

The advantage of borrowing over owning a reference is that you don't need to
take care of disposing of the reference on all possible paths through the code
--- in other words, with a borrowed reference you don't run the risk of leaking
when a premature exit is taken.  The disadvantage of borrowing over owning is
that there are some subtle situations where in seemingly correct code a borrowed
reference can be used after the owner from which it was borrowed has in fact
disposed of it.

A borrowed reference can be changed into an owned reference by calling
:c:func:`Py_INCREF`.  This does not affect the status of the owner from which the
reference was borrowed --- it creates a new owned reference, and gives full
owner responsibilities (the new owner must dispose of the reference properly, as
well as the previous owner).


.. _ownershiprules:

Ownership Rules
---------------

Whenever an object reference is passed into or out of a function, it is part of
the function's interface specification whether ownership is transferred with the
reference or not.

Most functions that return a reference to an object pass on ownership with the
reference.  In particular, all functions whose function it is to create a new
object, such as :c:func:`PyInt_FromLong` and :c:func:`Py_BuildValue`, pass
ownership to the receiver.  Even if the object is not actually new, you still
receive ownership of a new reference to that object.  For instance,
:c:func:`PyInt_FromLong` maintains a cache of popular values and can return a
reference to a cached item.

Many functions that extract objects from other objects also transfer ownership
with the reference, for instance :c:func:`PyObject_GetAttrString`.  The picture
is less clear, here, however, since a few common routines are exceptions:
:c:func:`PyTuple_GetItem`, :c:func:`PyList_GetItem`, :c:func:`PyDict_GetItem`, and
:c:func:`PyDict_GetItemString` all return references that you borrow from the
tuple, list or dictionary.

The function :c:func:`PyImport_AddModule` also returns a borrowed reference, even
though it may actually create the object it returns: this is possible because an
owned reference to the object is stored in ``sys.modules``.

When you pass an object reference into another function, in general, the
function borrows the reference from you --- if it needs to store it, it will use
:c:func:`Py_INCREF` to become an independent owner.  There are exactly two
important exceptions to this rule: :c:func:`PyTuple_SetItem` and
:c:func:`PyList_SetItem`.  These functions take over ownership of the item passed
to them --- even if they fail!  (Note that :c:func:`PyDict_SetItem` and friends
don't take over ownership --- they are "normal.")

When a C function is called from Python, it borrows references to its arguments
from the caller.  The caller owns a reference to the object, so the borrowed
reference's lifetime is guaranteed until the function returns.  Only when such a
borrowed reference must be stored or passed on, it must be turned into an owned
reference by calling :c:func:`Py_INCREF`.

The object reference returned from a C function that is called from Python must
be an owned reference --- ownership is transferred from the function to its
caller.


.. _thinice:

Thin Ice
--------

There are a few situations where seemingly harmless use of a borrowed reference
can lead to problems.  These all have to do with implicit invocations of the
interpreter, which can cause the owner of a reference to dispose of it.

The first and most important case to know about is using :c:func:`Py_DECREF` on
an unrelated object while borrowing a reference to a list item.  For instance::

   void
   bug(PyObject *list)
   {
       PyObject *item = PyList_GetItem(list, 0);

       PyList_SetItem(list, 1, PyInt_FromLong(0L));
       PyObject_Print(item, stdout, 0); /* BUG! */
   }

This function first borrows a reference to ``list[0]``, then replaces
``list[1]`` with the value ``0``, and finally prints the borrowed reference.
Looks harmless, right?  But it's not!

Let's follow the control flow into :c:func:`PyList_SetItem`.  The list owns
references to all its items, so when item 1 is replaced, it has to dispose of
the original item 1.  Now let's suppose the original item 1 was an instance of a
user-defined class, and let's further suppose that the class defined a
:meth:`__del__` method.  If this class instance has a reference count of 1,
disposing of it will call its :meth:`__del__` method.

Since it is written in Python, the :meth:`__del__` method can execute arbitrary
Python code.  Could it perhaps do something to invalidate the reference to
``item`` in :c:func:`bug`?  You bet!  Assuming that the list passed into
:c:func:`bug` is accessible to the :meth:`__del__` method, it could execute a
statement to the effect of ``del list[0]``, and assuming this was the last
reference to that object, it would free the memory associated with it, thereby
invalidating ``item``.

The solution, once you know the source of the problem, is easy: temporarily
increment the reference count.  The correct version of the function reads::

   void
   no_bug(PyObject *list)
   {
       PyObject *item = PyList_GetItem(list, 0);

       Py_INCREF(item);
       PyList_SetItem(list, 1, PyInt_FromLong(0L));
       PyObject_Print(item, stdout, 0);
       Py_DECREF(item);
   }

This is a true story.  An older version of Python contained variants of this bug
and someone spent a considerable amount of time in a C debugger to figure out
why his :meth:`__del__` methods would fail...

The second case of problems with a borrowed reference is a variant involving
threads.  Normally, multiple threads in the Python interpreter can't get in each
other's way, because there is a global lock protecting Python's entire object
space.  However, it is possible to temporarily release this lock using the macro
:c:macro:`Py_BEGIN_ALLOW_THREADS`, and to re-acquire it using
:c:macro:`Py_END_ALLOW_THREADS`.  This is common around blocking I/O calls, to
let other threads use the processor while waiting for the I/O to complete.
Obviously, the following function has the same problem as the previous one::

   void
   bug(PyObject *list)
   {
       PyObject *item = PyList_GetItem(list, 0);
       Py_BEGIN_ALLOW_THREADS
       ...some blocking I/O call...
       Py_END_ALLOW_THREADS
       PyObject_Print(item, stdout, 0); /* BUG! */
   }


.. _nullpointers:

NULL Pointers
-------------

In general, functions that take object references as arguments do not expect you
to pass them *NULL* pointers, and will dump core (or cause later core dumps) if
you do so.  Functions that return object references generally return *NULL* only
to indicate that an exception occurred.  The reason for not testing for *NULL*
arguments is that functions often pass the objects they receive on to other
function --- if each function were to test for *NULL*, there would be a lot of
redundant tests and the code would run more slowly.

It is better to test for *NULL* only at the "source:" when a pointer that may be
*NULL* is received, for example, from :c:func:`malloc` or from a function that
may raise an exception.

The macros :c:func:`Py_INCREF` and :c:func:`Py_DECREF` do not check for *NULL*
pointers --- however, their variants :c:func:`Py_XINCREF` and :c:func:`Py_XDECREF`
do.

The macros for checking for a particular object type (``Pytype_Check()``) don't
check for *NULL* pointers --- again, there is much code that calls several of
these in a row to test an object against various different expected types, and
this would generate redundant tests.  There are no variants with *NULL*
checking.

The C function calling mechanism guarantees that the argument list passed to C
functions (``args`` in the examples) is never *NULL* --- in fact it guarantees
that it is always a tuple [#]_.

It is a severe error to ever let a *NULL* pointer "escape" to the Python user.

.. Frank Stajano:
   A pedagogically buggy example, along the lines of the previous listing, would
   be helpful here -- showing in more concrete terms what sort of actions could
   cause the problem. I can't very well imagine it from the description.


.. _cplusplus:

Writing Extensions in C++
=========================

It is possible to write extension modules in C++.  Some restrictions apply.  If
the main program (the Python interpreter) is compiled and linked by the C
compiler, global or static objects with constructors cannot be used.  This is
not a problem if the main program is linked by the C++ compiler.  Functions that
will be called by the Python interpreter (in particular, module initialization
functions) have to be declared using ``extern "C"``. It is unnecessary to
enclose the Python header files in ``extern "C" {...}`` --- they use this form
already if the symbol ``__cplusplus`` is defined (all recent C++ compilers
define this symbol).


.. _using-capsules:

Providing a C API for an Extension Module
=========================================

.. sectionauthor:: Konrad Hinsen <hinsen@cnrs-orleans.fr>


Many extension modules just provide new functions and types to be used from
Python, but sometimes the code in an extension module can be useful for other
extension modules. For example, an extension module could implement a type
"collection" which works like lists without order. Just like the standard Python
list type has a C API which permits extension modules to create and manipulate
lists, this new collection type should have a set of C functions for direct
manipulation from other extension modules.

At first sight this seems easy: just write the functions (without declaring them
``static``, of course), provide an appropriate header file, and document
the C API. And in fact this would work if all extension modules were always
linked statically with the Python interpreter. When modules are used as shared
libraries, however, the symbols defined in one module may not be visible to
another module. The details of visibility depend on the operating system; some
systems use one global namespace for the Python interpreter and all extension
modules (Windows, for example), whereas others require an explicit list of
imported symbols at module link time (AIX is one example), or offer a choice of
different strategies (most Unices). And even if symbols are globally visible,
the module whose functions one wishes to call might not have been loaded yet!

Portability therefore requires not to make any assumptions about symbol
visibility. This means that all symbols in extension modules should be declared
``static``, except for the module's initialization function, in order to
avoid name clashes with other extension modules (as discussed in section
:ref:`methodtable`). And it means that symbols that *should* be accessible from
other extension modules must be exported in a different way.

Python provides a special mechanism to pass C-level information (pointers) from
one extension module to another one: Capsules. A Capsule is a Python data type
which stores a pointer (:c:type:`void \*`).  Capsules can only be created and
accessed via their C API, but they can be passed around like any other Python
object. In particular,  they can be assigned to a name in an extension module's
namespace. Other extension modules can then import this module, retrieve the
value of this name, and then retrieve the pointer from the Capsule.

There are many ways in which Capsules can be used to export the C API of an
extension module. Each function could get its own Capsule, or all C API pointers
could be stored in an array whose address is published in a Capsule. And the
various tasks of storing and retrieving the pointers can be distributed in
different ways between the module providing the code and the client modules.

Whichever method you choose, it's important to name your Capsules properly.
The function :c:func:`PyCapsule_New` takes a name parameter
(:c:type:`const char \*`); you're permitted to pass in a *NULL* name, but
we strongly encourage you to specify a name.  Properly named Capsules provide
a degree of runtime type-safety; there is no feasible way to tell one unnamed
Capsule from another.

In particular, Capsules used to expose C APIs should be given a name following
this convention::

    modulename.attributename

The convenience function :c:func:`PyCapsule_Import` makes it easy to
load a C API provided via a Capsule, but only if the Capsule's name
matches this convention.  This behavior gives C API users a high degree
of certainty that the Capsule they load contains the correct C API.

The following example demonstrates an approach that puts most of the burden on
the writer of the exporting module, which is appropriate for commonly used
library modules. It stores all C API pointers (just one in the example!) in an
array of :c:type:`void` pointers which becomes the value of a Capsule. The header
file corresponding to the module provides a macro that takes care of importing
the module and retrieving its C API pointers; client modules only have to call
this macro before accessing the C API.

The exporting module is a modification of the :mod:`spam` module from section
:ref:`extending-simpleexample`. The function :func:`spam.system` does not call
the C library function :c:func:`system` directly, but a function
:c:func:`PySpam_System`, which would of course do something more complicated in
reality (such as adding "spam" to every command). This function
:c:func:`PySpam_System` is also exported to other extension modules.

The function :c:func:`PySpam_System` is a plain C function, declared
``static`` like everything else::

   static int
   PySpam_System(const char *command)
   {
       return system(command);
   }

The function :c:func:`spam_system` is modified in a trivial way::

   static PyObject *
   spam_system(PyObject *self, PyObject *args)
   {
       const char *command;
       int sts;

       if (!PyArg_ParseTuple(args, "s", &command))
           return NULL;
       sts = PySpam_System(command);
       return Py_BuildValue("i", sts);
   }

In the beginning of the module, right after the line ::

   #include "Python.h"

two more lines must be added::

   #define SPAM_MODULE
   #include "spammodule.h"

The ``#define`` is used to tell the header file that it is being included in the
exporting module, not a client module. Finally, the module's initialization
function must take care of initializing the C API pointer array::

   PyMODINIT_FUNC
   initspam(void)
   {
       PyObject *m;
       static void *PySpam_API[PySpam_API_pointers];
       PyObject *c_api_object;

       m = Py_InitModule("spam", SpamMethods);
       if (m == NULL)
           return;

       /* Initialize the C API pointer array */
       PySpam_API[PySpam_System_NUM] = (void *)PySpam_System;

       /* Create a Capsule containing the API pointer array's address */
       c_api_object = PyCapsule_New((void *)PySpam_API, "spam._C_API", NULL);

       if (c_api_object != NULL)
           PyModule_AddObject(m, "_C_API", c_api_object);
   }

Note that ``PySpam_API`` is declared ``static``; otherwise the pointer
array would disappear when :func:`initspam` terminates!

The bulk of the work is in the header file :file:`spammodule.h`, which looks
like this::

   #ifndef Py_SPAMMODULE_H
   #define Py_SPAMMODULE_H
   #ifdef __cplusplus
   extern "C" {
   #endif

   /* Header file for spammodule */

   /* C API functions */
   #define PySpam_System_NUM 0
   #define PySpam_System_RETURN int
   #define PySpam_System_PROTO (const char *command)

   /* Total number of C API pointers */
   #define PySpam_API_pointers 1


   #ifdef SPAM_MODULE
   /* This section is used when compiling spammodule.c */

   static PySpam_System_RETURN PySpam_System PySpam_System_PROTO;

   #else
   /* This section is used in modules that use spammodule's API */

   static void **PySpam_API;

   #define PySpam_System \
    (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])

   /* Return -1 on error, 0 on success.
    * PyCapsule_Import will set an exception if there's an error.
    */
   static int
   import_spam(void)
   {
       PySpam_API = (void **)PyCapsule_Import("spam._C_API", 0);
       return (PySpam_API != NULL) ? 0 : -1;
   }

   #endif

   #ifdef __cplusplus
   }
   #endif

   #endif /* !defined(Py_SPAMMODULE_H) */

All that a client module must do in order to have access to the function
:c:func:`PySpam_System` is to call the function (or rather macro)
:c:func:`import_spam` in its initialization function::

   PyMODINIT_FUNC
   initclient(void)
   {
       PyObject *m;

       m = Py_InitModule("client", ClientMethods);
       if (m == NULL)
           return;
       if (import_spam() < 0)
           return;
       /* additional initialization can happen here */
   }

The main disadvantage of this approach is that the file :file:`spammodule.h` is
rather complicated. However, the basic structure is the same for each function
that is exported, so it has to be learned only once.

Finally it should be mentioned that Capsules offer additional functionality,
which is especially useful for memory allocation and deallocation of the pointer
stored in a Capsule. The details are described in the Python/C API Reference
Manual in the section :ref:`capsules` and in the implementation of Capsules (files
:file:`Include/pycapsule.h` and :file:`Objects/pycapsule.c` in the Python source
code distribution).

.. rubric:: Footnotes

.. [#] An interface for this function already exists in the standard module :mod:`os`
   --- it was chosen as a simple and straightforward example.

.. [#] The metaphor of "borrowing" a reference is not completely correct: the owner
   still has a copy of the reference.

.. [#] Checking that the reference count is at least 1 **does not work** --- the
   reference count itself could be in freed memory and may thus be reused for
   another object!

.. [#] These guarantees don't hold when you use the "old" style calling convention ---
   this is still found in much existing code.

PK	%�\�Cs4SS%html/_sources/extending/index.rst.txtnu�[���.. _extending-index:

##################################################
  Extending and Embedding the Python Interpreter
##################################################

This document describes how to write modules in C or C++ to extend the Python
interpreter with new modules.  Those modules can not only define new functions
but also new object types and their methods.  The document also describes how
to embed the Python interpreter in another application, for use as an extension
language.  Finally, it shows how to compile and link extension modules so that
they can be loaded dynamically (at run time) into the interpreter, if the
underlying operating system supports this feature.

This document assumes basic knowledge about Python.  For an informal
introduction to the language, see :ref:`tutorial-index`.  :ref:`reference-index`
gives a more formal definition of the language.  :ref:`library-index` documents
the existing object types, functions and modules (both built-in and written in
Python) that give the language its wide application range.

For a detailed description of the whole Python/C API, see the separate
:ref:`c-api-index`.

.. note::

   This guide only covers the basic tools for creating extensions provided
   as part of this version of CPython. Third party tools may offer simpler
   alternatives. Refer to the `binary extensions section
   <https://packaging.python.org/en/latest/extensions/>`__ in the Python
   Packaging User Guide for more information.


.. toctree::
   :maxdepth: 2
   :numbered:

   extending.rst
   newtypes.rst
   building.rst
   windows.rst
   embedding.rst
PK	%�\XO������(html/_sources/extending/newtypes.rst.txtnu�[���.. highlightlang:: c


.. _defining-new-types:

******************
Defining New Types
******************

.. sectionauthor:: Michael Hudson <mwh@python.net>
.. sectionauthor:: Dave Kuhlman <dkuhlman@rexx.com>
.. sectionauthor:: Jim Fulton <jim@zope.com>


As mentioned in the last chapter, Python allows the writer of an extension
module to define new types that can be manipulated from Python code, much like
strings and lists in core Python.

This is not hard; the code for all extension types follows a pattern, but there
are some details that you need to understand before you can get started.

.. note::

   The way new types are defined changed dramatically (and for the better) in
   Python 2.2.  This document documents how to define new types for Python 2.2 and
   later.  If you need to support older versions of Python, you will need to refer
   to `older versions of this documentation
   <https://www.python.org/doc/versions/>`_.


.. _dnt-basics:

The Basics
==========

The Python runtime sees all Python objects as variables of type
:c:type:`PyObject\*`.  A :c:type:`PyObject` is not a very magnificent object - it
just contains the refcount and a pointer to the object's "type object".  This is
where the action is; the type object determines which (C) functions get called
when, for instance, an attribute gets looked up on an object or it is multiplied
by another object.  These C functions are called "type methods".

So, if you want to define a new object type, you need to create a new type
object.

This sort of thing can only be explained by example, so here's a minimal, but
complete, module that defines a new type:

.. literalinclude:: ../includes/noddy.c


Now that's quite a bit to take in at once, but hopefully bits will seem familiar
from the last chapter.

The first bit that will be new is::

   typedef struct {
       PyObject_HEAD
   } noddy_NoddyObject;

This is what a Noddy object will contain---in this case, nothing more than every
Python object contains, namely a refcount and a pointer to a type object.  These
are the fields the ``PyObject_HEAD`` macro brings in.  The reason for the macro
is to standardize the layout and to enable special debugging fields in debug
builds.  Note that there is no semicolon after the ``PyObject_HEAD`` macro; one
is included in the macro definition.  Be wary of adding one by accident; it's
easy to do from habit, and your compiler might not complain, but someone else's
probably will!  (On Windows, MSVC is known to call this an error and refuse to
compile the code.)

For contrast, let's take a look at the corresponding definition for standard
Python integers::

   typedef struct {
       PyObject_HEAD
       long ob_ival;
   } PyIntObject;

Moving on, we come to the crunch --- the type object. ::

   static PyTypeObject noddy_NoddyType = {
       PyVarObject_HEAD_INIT(NULL, 0)
       "noddy.Noddy",             /* tp_name */
       sizeof(noddy_NoddyObject), /* tp_basicsize */
       0,                         /* tp_itemsize */
       0,                         /* tp_dealloc */
       0,                         /* tp_print */
       0,                         /* tp_getattr */
       0,                         /* tp_setattr */
       0,                         /* tp_compare */
       0,                         /* tp_repr */
       0,                         /* tp_as_number */
       0,                         /* tp_as_sequence */
       0,                         /* tp_as_mapping */
       0,                         /* tp_hash */
       0,                         /* tp_call */
       0,                         /* tp_str */
       0,                         /* tp_getattro */
       0,                         /* tp_setattro */
       0,                         /* tp_as_buffer */
       Py_TPFLAGS_DEFAULT,        /* tp_flags */
       "Noddy objects",           /* tp_doc */
   };

Now if you go and look up the definition of :c:type:`PyTypeObject` in
:file:`object.h` you'll see that it has many more fields that the definition
above.  The remaining fields will be filled with zeros by the C compiler, and
it's common practice to not specify them explicitly unless you need them.

This is so important that we're going to pick the top of it apart still
further::

   PyVarObject_HEAD_INIT(NULL, 0)

This line is a bit of a wart; what we'd like to write is::

   PyVarObject_HEAD_INIT(&PyType_Type, 0)

as the type of a type object is "type", but this isn't strictly conforming C and
some compilers complain.  Fortunately, this member will be filled in for us by
:c:func:`PyType_Ready`. ::

   "noddy.Noddy",              /* tp_name */

The name of our type.  This will appear in the default textual representation of
our objects and in some error messages, for example::

   >>> "" + noddy.new_noddy()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: cannot add type "noddy.Noddy" to string

Note that the name is a dotted name that includes both the module name and the
name of the type within the module. The module in this case is :mod:`noddy` and
the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`.
One side effect of using an undotted name is that the pydoc documentation tool
will not list the new type in the module documentation. ::

   sizeof(noddy_NoddyObject),  /* tp_basicsize */

This is so that Python knows how much memory to allocate when you call
:c:func:`PyObject_New`.

.. note::

   If you want your type to be subclassable from Python, and your type has the same
   :c:member:`~PyTypeObject.tp_basicsize` as its base type, you may have problems with multiple
   inheritance.  A Python subclass of your type will have to list your type first
   in its :attr:`~class.__bases__`, or else it will not be able to call your type's
   :meth:`__new__` method without getting an error.  You can avoid this problem by
   ensuring that your type has a larger value for :c:member:`~PyTypeObject.tp_basicsize` than its
   base type does.  Most of the time, this will be true anyway, because either your
   base type will be :class:`object`, or else you will be adding data members to
   your base type, and therefore increasing its size.

::

   0,                          /* tp_itemsize */

This has to do with variable length objects like lists and strings. Ignore this
for now.

Skipping a number of type methods that we don't provide, we set the class flags
to :const:`Py_TPFLAGS_DEFAULT`. ::

   Py_TPFLAGS_DEFAULT,        /* tp_flags */

All types should include this constant in their flags.  It enables all of the
members defined by the current version of Python.

We provide a doc string for the type in :c:member:`~PyTypeObject.tp_doc`. ::

   "Noddy objects",           /* tp_doc */

Now we get into the type methods, the things that make your objects different
from the others.  We aren't going to implement any of these in this version of
the module.  We'll expand this example later to have more interesting behavior.

For now, all we want to be able to do is to create new :class:`Noddy` objects.
To enable object creation, we have to provide a :c:member:`~PyTypeObject.tp_new` implementation.
In this case, we can just use the default implementation provided by the API
function :c:func:`PyType_GenericNew`.  We'd like to just assign this to the
:c:member:`~PyTypeObject.tp_new` slot, but we can't, for portability sake, On some platforms or
compilers, we can't statically initialize a structure member with a function
defined in another C module, so, instead, we'll assign the :c:member:`~PyTypeObject.tp_new` slot
in the module initialization function just before calling
:c:func:`PyType_Ready`::

   noddy_NoddyType.tp_new = PyType_GenericNew;
   if (PyType_Ready(&noddy_NoddyType) < 0)
       return;

All the other type methods are *NULL*, so we'll go over them later --- that's
for a later section!

Everything else in the file should be familiar, except for some code in
:c:func:`initnoddy`::

   if (PyType_Ready(&noddy_NoddyType) < 0)
       return;

This initializes the :class:`Noddy` type, filing in a number of members,
including :attr:`ob_type` that we initially set to *NULL*. ::

   PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);

This adds the type to the module dictionary.  This allows us to create
:class:`Noddy` instances by calling the :class:`Noddy` class::

   >>> import noddy
   >>> mynoddy = noddy.Noddy()

That's it!  All that remains is to build it; put the above code in a file called
:file:`noddy.c` and ::

   from distutils.core import setup, Extension
   setup(name="noddy", version="1.0",
         ext_modules=[Extension("noddy", ["noddy.c"])])

in a file called :file:`setup.py`; then typing

.. code-block:: shell-session

   $ python setup.py build

at a shell should produce a file :file:`noddy.so` in a subdirectory; move to
that directory and fire up Python --- you should be able to ``import noddy`` and
play around with Noddy objects.

That wasn't so hard, was it?

Of course, the current Noddy type is pretty uninteresting. It has no data and
doesn't do anything. It can't even be subclassed.


Adding data and methods to the Basic example
--------------------------------------------

Let's extend the basic example to add some data and methods.  Let's also make
the type usable as a base class. We'll create a new module, :mod:`noddy2` that
adds these capabilities:

.. literalinclude:: ../includes/noddy2.c


This version of the module has a number of changes.

We've added an extra include::

   #include <structmember.h>

This include provides declarations that we use to handle attributes, as
described a bit later.

The name of the :class:`Noddy` object structure has been shortened to
:class:`Noddy`.  The type object name has been shortened to :class:`NoddyType`.

The  :class:`Noddy` type now has three data attributes, *first*, *last*, and
*number*.  The *first* and *last* variables are Python strings containing first
and last names. The *number* attribute is an integer.

The object structure is updated accordingly::

   typedef struct {
       PyObject_HEAD
       PyObject *first;
       PyObject *last;
       int number;
   } Noddy;

Because we now have data to manage, we have to be more careful about object
allocation and deallocation.  At a minimum, we need a deallocation method::

   static void
   Noddy_dealloc(Noddy* self)
   {
       Py_XDECREF(self->first);
       Py_XDECREF(self->last);
       Py_TYPE(self)->tp_free((PyObject*)self);
   }

which is assigned to the :c:member:`~PyTypeObject.tp_dealloc` member::

   (destructor)Noddy_dealloc, /*tp_dealloc*/

This method decrements the reference counts of the two Python attributes. We use
:c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
could be *NULL*.  It then calls the :c:member:`~PyTypeObject.tp_free` member of the object's type
to free the object's memory.  Note that the object's type might not be
:class:`NoddyType`, because the object may be an instance of a subclass.

We want to make sure that the first and last names are initialized to empty
strings, so we provide a new method::

   static PyObject *
   Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
   {
       Noddy *self;

       self = (Noddy *)type->tp_alloc(type, 0);
       if (self != NULL) {
           self->first = PyString_FromString("");
           if (self->first == NULL)
             {
               Py_DECREF(self);
               return NULL;
             }

           self->last = PyString_FromString("");
           if (self->last == NULL)
             {
               Py_DECREF(self);
               return NULL;
             }

           self->number = 0;
       }

       return (PyObject *)self;
   }

and install it in the :c:member:`~PyTypeObject.tp_new` member::

   Noddy_new,                 /* tp_new */

The new member is responsible for creating (as opposed to initializing) objects
of the type.  It is exposed in Python as the :meth:`__new__` method.  See the
paper titled "Unifying types and classes in Python" for a detailed discussion of
the :meth:`__new__` method.  One reason to implement a new method is to assure
the initial values of instance variables.  In this case, we use the new method
to make sure that the initial values of the members :attr:`first` and
:attr:`last` are not *NULL*. If we didn't care whether the initial values were
*NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we
did before.  :c:func:`PyType_GenericNew` initializes all of the instance variable
members to *NULL*.

The new method is a static method that is passed the type being instantiated and
any arguments passed when the type was called, and that returns the new object
created. New methods always accept positional and keyword arguments, but they
often ignore the arguments, leaving the argument handling to initializer
methods. Note that if the type supports subclassing, the type passed may not be
the type being defined.  The new method calls the tp_alloc slot to allocate
memory. We don't fill the :c:member:`~PyTypeObject.tp_alloc` slot ourselves. Rather
:c:func:`PyType_Ready` fills it for us by inheriting it from our base class,
which is :class:`object` by default.  Most types use the default allocation.

.. note::

   If you are creating a co-operative :c:member:`~PyTypeObject.tp_new` (one that calls a base type's
   :c:member:`~PyTypeObject.tp_new` or :meth:`__new__`), you must *not* try to determine what method
   to call using method resolution order at runtime.  Always statically determine
   what type you are going to call, and call its :c:member:`~PyTypeObject.tp_new` directly, or via
   ``type->tp_base->tp_new``.  If you do not do this, Python subclasses of your
   type that also inherit from other Python-defined classes may not work correctly.
   (Specifically, you may not be able to create instances of such subclasses
   without getting a :exc:`TypeError`.)

We provide an initialization function::

   static int
   Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
   {
       PyObject *first=NULL, *last=NULL, *tmp;

       static char *kwlist[] = {"first", "last", "number", NULL};

       if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
                                         &first, &last,
                                         &self->number))
           return -1;

       if (first) {
           tmp = self->first;
           Py_INCREF(first);
           self->first = first;
           Py_XDECREF(tmp);
       }

       if (last) {
           tmp = self->last;
           Py_INCREF(last);
           self->last = last;
           Py_XDECREF(tmp);
       }

       return 0;
   }

by filling the :c:member:`~PyTypeObject.tp_init` slot. ::

   (initproc)Noddy_init,         /* tp_init */

The :c:member:`~PyTypeObject.tp_init` slot is exposed in Python as the :meth:`__init__` method. It
is used to initialize an object after it's created. Unlike the new method, we
can't guarantee that the initializer is called.  The initializer isn't called
when unpickling objects and it can be overridden.  Our initializer accepts
arguments to provide initial values for our instance. Initializers always accept
positional and keyword arguments.

Initializers can be called multiple times.  Anyone can call the :meth:`__init__`
method on our objects.  For this reason, we have to be extra careful when
assigning the new values.  We might be tempted, for example to assign the
:attr:`first` member like this::

   if (first) {
       Py_XDECREF(self->first);
       Py_INCREF(first);
       self->first = first;
   }

But this would be risky.  Our type doesn't restrict the type of the
:attr:`first` member, so it could be any kind of object.  It could have a
destructor that causes code to be executed that tries to access the
:attr:`first` member.  To be paranoid and protect ourselves against this
possibility, we almost always reassign members before decrementing their
reference counts.  When don't we have to do this?

* when we absolutely know that the reference count is greater than 1

* when we know that deallocation of the object [#]_ will not cause any calls
  back into our type's code

* when decrementing a reference count in a :c:member:`~PyTypeObject.tp_dealloc` handler when
  garbage-collections is not supported [#]_

We want to expose our instance variables as attributes. There are a
number of ways to do that. The simplest way is to define member definitions::

   static PyMemberDef Noddy_members[] = {
       {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
        "first name"},
       {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
        "last name"},
       {"number", T_INT, offsetof(Noddy, number), 0,
        "noddy number"},
       {NULL}  /* Sentinel */
   };

and put the definitions in the :c:member:`~PyTypeObject.tp_members` slot::

   Noddy_members,             /* tp_members */

Each member definition has a member name, type, offset, access flags and
documentation string. See the :ref:`Generic-Attribute-Management` section below for
details.

A disadvantage of this approach is that it doesn't provide a way to restrict the
types of objects that can be assigned to the Python attributes.  We expect the
first and last names to be strings, but any Python objects can be assigned.
Further, the attributes can be deleted, setting the C pointers to *NULL*.  Even
though we can make sure the members are initialized to non-*NULL* values, the
members can be set to *NULL* if the attributes are deleted.

We define a single method, :meth:`name`, that outputs the objects name as the
concatenation of the first and last names. ::

   static PyObject *
   Noddy_name(Noddy* self)
   {
       static PyObject *format = NULL;
       PyObject *args, *result;

       if (format == NULL) {
           format = PyString_FromString("%s %s");
           if (format == NULL)
               return NULL;
       }

       if (self->first == NULL) {
           PyErr_SetString(PyExc_AttributeError, "first");
           return NULL;
       }

       if (self->last == NULL) {
           PyErr_SetString(PyExc_AttributeError, "last");
           return NULL;
       }

       args = Py_BuildValue("OO", self->first, self->last);
       if (args == NULL)
           return NULL;

       result = PyString_Format(format, args);
       Py_DECREF(args);

       return result;
   }

The method is implemented as a C function that takes a :class:`Noddy` (or
:class:`Noddy` subclass) instance as the first argument.  Methods always take an
instance as the first argument. Methods often take positional and keyword
arguments as well, but in this case we don't take any and don't need to accept
a positional argument tuple or keyword argument dictionary. This method is
equivalent to the Python method::

   def name(self):
      return "%s %s" % (self.first, self.last)

Note that we have to check for the possibility that our :attr:`first` and
:attr:`last` members are *NULL*.  This is because they can be deleted, in which
case they are set to *NULL*.  It would be better to prevent deletion of these
attributes and to restrict the attribute values to be strings.  We'll see how to
do that in the next section.

Now that we've defined the method, we need to create an array of method
definitions::

   static PyMethodDef Noddy_methods[] = {
       {"name", (PyCFunction)Noddy_name, METH_NOARGS,
        "Return the name, combining the first and last name"
       },
       {NULL}  /* Sentinel */
   };

and assign them to the :c:member:`~PyTypeObject.tp_methods` slot::

   Noddy_methods,             /* tp_methods */

Note that we used the :const:`METH_NOARGS` flag to indicate that the method is
passed no arguments.

Finally, we'll make our type usable as a base class.  We've written our methods
carefully so far so that they don't make any assumptions about the type of the
object being created or used, so all we need to do is to add the
:const:`Py_TPFLAGS_BASETYPE` to our class flag definition::

   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/

We rename :c:func:`initnoddy` to :c:func:`initnoddy2` and update the module name
passed to :c:func:`Py_InitModule3`.

Finally, we update our :file:`setup.py` file to build the new module::

   from distutils.core import setup, Extension
   setup(name="noddy", version="1.0",
         ext_modules=[
            Extension("noddy", ["noddy.c"]),
            Extension("noddy2", ["noddy2.c"]),
            ])


Providing finer control over data attributes
--------------------------------------------

In this section, we'll provide finer control over how the :attr:`first` and
:attr:`last` attributes are set in the :class:`Noddy` example. In the previous
version of our module, the instance variables :attr:`first` and :attr:`last`
could be set to non-string values or even deleted. We want to make sure that
these attributes always contain strings.

.. literalinclude:: ../includes/noddy3.c


To provide greater control, over the :attr:`first` and :attr:`last` attributes,
we'll use custom getter and setter functions.  Here are the functions for
getting and setting the :attr:`first` attribute::

   Noddy_getfirst(Noddy *self, void *closure)
   {
       Py_INCREF(self->first);
       return self->first;
   }

   static int
   Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
   {
     if (value == NULL) {
       PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
       return -1;
     }

     if (! PyString_Check(value)) {
       PyErr_SetString(PyExc_TypeError,
                       "The first attribute value must be a string");
       return -1;
     }

     Py_DECREF(self->first);
     Py_INCREF(value);
     self->first = value;

     return 0;
   }

The getter function is passed a :class:`Noddy` object and a "closure", which is
void pointer. In this case, the closure is ignored. (The closure supports an
advanced usage in which definition data is passed to the getter and setter. This
could, for example, be used to allow a single set of getter and setter functions
that decide the attribute to get or set based on data in the closure.)

The setter function is passed the :class:`Noddy` object, the new value, and the
closure. The new value may be *NULL*, in which case the attribute is being
deleted.  In our setter, we raise an error if the attribute is deleted or if the
attribute value is not a string.

We create an array of :c:type:`PyGetSetDef` structures::

   static PyGetSetDef Noddy_getseters[] = {
       {"first",
        (getter)Noddy_getfirst, (setter)Noddy_setfirst,
        "first name",
        NULL},
       {"last",
        (getter)Noddy_getlast, (setter)Noddy_setlast,
        "last name",
        NULL},
       {NULL}  /* Sentinel */
   };

and register it in the :c:member:`~PyTypeObject.tp_getset` slot::

   Noddy_getseters,           /* tp_getset */

to register our attribute getters and setters.

The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned
above. In this case, we aren't using the closure, so we just pass *NULL*.

We also remove the member definitions for these attributes::

   static PyMemberDef Noddy_members[] = {
       {"number", T_INT, offsetof(Noddy, number), 0,
        "noddy number"},
       {NULL}  /* Sentinel */
   };

We also need to update the :c:member:`~PyTypeObject.tp_init` handler to only allow strings [#]_ to
be passed::

   static int
   Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
   {
       PyObject *first=NULL, *last=NULL, *tmp;

       static char *kwlist[] = {"first", "last", "number", NULL};

       if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSi", kwlist,
                                         &first, &last,
                                         &self->number))
           return -1;

       if (first) {
           tmp = self->first;
           Py_INCREF(first);
           self->first = first;
           Py_DECREF(tmp);
       }

       if (last) {
           tmp = self->last;
           Py_INCREF(last);
           self->last = last;
           Py_DECREF(tmp);
       }

       return 0;
   }

With these changes, we can assure that the :attr:`first` and :attr:`last`
members are never *NULL* so we can remove checks for *NULL* values in almost all
cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to
:c:func:`Py_DECREF` calls. The only place we can't change these calls is in the
deallocator, where there is the possibility that the initialization of these
members failed in the constructor.

We also rename the module initialization function and module name in the
initialization function, as we did before, and we add an extra definition to the
:file:`setup.py` file.


Supporting cyclic garbage collection
------------------------------------

Python has a cyclic-garbage collector that can identify unneeded objects even
when their reference counts are not zero. This can happen when objects are
involved in cycles.  For example, consider::

   >>> l = []
   >>> l.append(l)
   >>> del l

In this example, we create a list that contains itself. When we delete it, it
still has a reference from itself. Its reference count doesn't drop to zero.
Fortunately, Python's cyclic-garbage collector will eventually figure out that
the list is garbage and free it.

In the second version of the :class:`Noddy` example, we allowed any kind of
object to be stored in the :attr:`first` or :attr:`last` attributes [#]_. This
means that :class:`Noddy` objects can participate in cycles::

   >>> import noddy2
   >>> n = noddy2.Noddy()
   >>> l = [n]
   >>> n.first = l

This is pretty silly, but it gives us an excuse to add support for the
cyclic-garbage collector to the :class:`Noddy` example.  To support cyclic
garbage collection, types need to fill two slots and set a class flag that
enables these slots:

.. literalinclude:: ../includes/noddy4.c


The traversal method provides access to subobjects that could participate in
cycles::

   static int
   Noddy_traverse(Noddy *self, visitproc visit, void *arg)
   {
       int vret;

       if (self->first) {
           vret = visit(self->first, arg);
           if (vret != 0)
               return vret;
       }
       if (self->last) {
           vret = visit(self->last, arg);
           if (vret != 0)
               return vret;
       }

       return 0;
   }

For each subobject that can participate in cycles, we need to call the
:c:func:`visit` function, which is passed to the traversal method. The
:c:func:`visit` function takes as arguments the subobject and the extra argument
*arg* passed to the traversal method.  It returns an integer value that must be
returned if it is non-zero.

Python 2.4 and higher provide a :c:func:`Py_VISIT` macro that automates calling
visit functions.  With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be
simplified::

   static int
   Noddy_traverse(Noddy *self, visitproc visit, void *arg)
   {
       Py_VISIT(self->first);
       Py_VISIT(self->last);
       return 0;
   }

.. note::

   Note that the :c:member:`~PyTypeObject.tp_traverse` implementation must name its arguments exactly
   *visit* and *arg* in order to use :c:func:`Py_VISIT`.  This is to encourage
   uniformity across these boring implementations.

We also need to provide a method for clearing any subobjects that can
participate in cycles.

::

   static int
   Noddy_clear(Noddy *self)
   {
       PyObject *tmp;

       tmp = self->first;
       self->first = NULL;
       Py_XDECREF(tmp);

       tmp = self->last;
       self->last = NULL;
       Py_XDECREF(tmp);

       return 0;
   }

Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the
temporary variable so that we can set each member to *NULL* before decrementing
its reference count.  We do this because, as was discussed earlier, if the
reference count drops to zero, we might cause code to run that calls back into
the object.  In addition, because we now support garbage collection, we also
have to worry about code being run that triggers garbage collection.  If garbage
collection is run, our :c:member:`~PyTypeObject.tp_traverse` handler could get called. We can't
take a chance of having :c:func:`Noddy_traverse` called when a member's reference
count has dropped to zero and its value hasn't been set to *NULL*.

Python 2.4 and higher provide a :c:func:`Py_CLEAR` that automates the careful
decrementing of reference counts.  With :c:func:`Py_CLEAR`, the
:c:func:`Noddy_clear` function can be simplified::

   static int
   Noddy_clear(Noddy *self)
   {
       Py_CLEAR(self->first);
       Py_CLEAR(self->last);
       return 0;
   }

Note that :c:func:`Noddy_dealloc` may call arbitrary functions through
``__del__`` method or weakref callback. It means circular GC can be
triggered inside the function.  Since GC assumes reference count is not zero,
we need to untrack the object from GC by calling :c:func:`PyObject_GC_UnTrack`
before clearing members. Here is reimplemented deallocator which uses
:c:func:`PyObject_GC_UnTrack` and :c:func:`Noddy_clear`.

::

   static void
   Noddy_dealloc(Noddy* self)
   {
       PyObject_GC_UnTrack(self);
       Noddy_clear(self);
       Py_TYPE(self)->tp_free((PyObject*)self);
   }

Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags::

   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */

That's pretty much it.  If we had written custom :c:member:`~PyTypeObject.tp_alloc` or
:c:member:`~PyTypeObject.tp_free` slots, we'd need to modify them for cyclic-garbage collection.
Most extensions will use the versions automatically provided.


Subclassing other types
-----------------------

It is possible to create new extension types that are derived from existing
types. It is easiest to inherit from the built in types, since an extension can
easily use the :class:`PyTypeObject` it needs. It can be difficult to share
these :class:`PyTypeObject` structures between extension modules.

In this example we will create a :class:`Shoddy` type that inherits from the
built-in :class:`list` type. The new type will be completely compatible with
regular lists, but will have an additional :meth:`increment` method that
increases an internal counter. ::

   >>> import shoddy
   >>> s = shoddy.Shoddy(range(3))
   >>> s.extend(s)
   >>> print len(s)
   6
   >>> print s.increment()
   1
   >>> print s.increment()
   2

.. literalinclude:: ../includes/shoddy.c


As you can see, the source code closely resembles the :class:`Noddy` examples in
previous sections. We will break down the main differences between them. ::

   typedef struct {
       PyListObject list;
       int state;
   } Shoddy;

The primary difference for derived type objects is that the base type's object
structure must be the first value. The base type will already include the
:c:func:`PyObject_HEAD` at the beginning of its structure.

When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
be safely cast to both *PyListObject\** and *Shoddy\**. ::

   static int
   Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
   {
       if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
          return -1;
       self->state = 0;
       return 0;
   }

In the :attr:`__init__` method for our type, we can see how to call through to
the :attr:`__init__` method of the base type.

This pattern is important when writing a type with custom :attr:`new` and
:attr:`dealloc` methods. The :attr:`new` method should not actually create the
memory for the object with :c:member:`~PyTypeObject.tp_alloc`, that will be handled by the base
class when calling its :c:member:`~PyTypeObject.tp_new`.

When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see
a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't
fill that field directly with the :c:func:`PyList_Type`; it can be done later in
the module's :c:func:`init` function. ::

   PyMODINIT_FUNC
   initshoddy(void)
   {
       PyObject *m;

       ShoddyType.tp_base = &PyList_Type;
       if (PyType_Ready(&ShoddyType) < 0)
           return;

       m = Py_InitModule3("shoddy", NULL, "Shoddy module");
       if (m == NULL)
           return;

       Py_INCREF(&ShoddyType);
       PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
   }

Before calling :c:func:`PyType_Ready`, the type structure must have the
:c:member:`~PyTypeObject.tp_base` slot filled in. When we are deriving a new type, it is not
necessary to fill out the :c:member:`~PyTypeObject.tp_alloc` slot with :c:func:`PyType_GenericNew`
-- the allocate function from the base type will be inherited.

After that, calling :c:func:`PyType_Ready` and adding the type object to the
module is the same as with the basic :class:`Noddy` examples.


.. _dnt-type-methods:

Type Methods
============

This section aims to give a quick fly-by on the various type methods you can
implement and what they do.

Here is the definition of :c:type:`PyTypeObject`, with some fields only used in
debug builds omitted:

.. literalinclude:: ../includes/typestruct.h


Now that's a *lot* of methods.  Don't worry too much though - if you have a type
you want to define, the chances are very good that you will only implement a
handful of these.

As you probably expect by now, we're going to go over this and give more
information about the various handlers.  We won't go in the order they are
defined in the structure, because there is a lot of historical baggage that
impacts the ordering of the fields; be sure your type initialization keeps the
fields in the right order!  It's often easiest to find an example that includes
all the fields you need (even if they're initialized to ``0``) and then change
the values to suit your new type. ::

   char *tp_name; /* For printing */

The name of the type - as mentioned in the last section, this will appear in
various places, almost entirely for diagnostic purposes. Try to choose something
that will be helpful in such a situation! ::

   int tp_basicsize, tp_itemsize; /* For allocation */

These fields tell the runtime how much memory to allocate when new objects of
this type are created.  Python has some built-in support for variable length
structures (think: strings, lists) which is where the :c:member:`~PyTypeObject.tp_itemsize` field
comes in.  This will be dealt with later. ::

   char *tp_doc;

Here you can put a string (or its address) that you want returned when the
Python script references ``obj.__doc__`` to retrieve the doc string.

Now we come to the basic type methods---the ones most extension types will
implement.


Finalization and De-allocation
------------------------------

.. index::
   single: object; deallocation
   single: deallocation, object
   single: object; finalization
   single: finalization, of objects

::

   destructor tp_dealloc;

This function is called when the reference count of the instance of your type is
reduced to zero and the Python interpreter wants to reclaim it.  If your type
has memory to free or other clean-up to perform, you can put it here.  The
object itself needs to be freed here as well.  Here is an example of this
function::

   static void
   newdatatype_dealloc(newdatatypeobject * obj)
   {
       free(obj->obj_UnderlyingDatatypePtr);
       Py_TYPE(obj)->tp_free(obj);
   }

.. index::
   single: PyErr_Fetch()
   single: PyErr_Restore()

One important requirement of the deallocator function is that it leaves any
pending exceptions alone.  This is important since deallocators are frequently
called as the interpreter unwinds the Python stack; when the stack is unwound
due to an exception (rather than normal returns), nothing is done to protect the
deallocators from seeing that an exception has already been set.  Any actions
which a deallocator performs which may cause additional Python code to be
executed may detect that an exception has been set.  This can lead to misleading
errors from the interpreter.  The proper way to protect against this is to save
a pending exception before performing the unsafe action, and restoring it when
done.  This can be done using the :c:func:`PyErr_Fetch` and
:c:func:`PyErr_Restore` functions::

   static void
   my_dealloc(PyObject *obj)
   {
       MyObject *self = (MyObject *) obj;
       PyObject *cbresult;

       if (self->my_callback != NULL) {
           PyObject *err_type, *err_value, *err_traceback;
           int have_error = PyErr_Occurred() ? 1 : 0;

           if (have_error)
               PyErr_Fetch(&err_type, &err_value, &err_traceback);

           cbresult = PyObject_CallObject(self->my_callback, NULL);
           if (cbresult == NULL)
               PyErr_WriteUnraisable(self->my_callback);
           else
               Py_DECREF(cbresult);

           if (have_error)
               PyErr_Restore(err_type, err_value, err_traceback);

           Py_DECREF(self->my_callback);
       }
       Py_TYPE(obj)->tp_free((PyObject*)self);
   }


Object Presentation
-------------------

.. index::
   builtin: repr
   builtin: str

In Python, there are three ways to generate a textual representation of an
object: the :func:`repr` function (or equivalent back-tick syntax), the
:func:`str` function, and the :keyword:`print` statement.  For most objects, the
:keyword:`print` statement is equivalent to the :func:`str` function, but it is
possible to special-case printing to a :c:type:`FILE\*` if necessary; this should
only be done if efficiency is identified as a problem and profiling suggests
that creating a temporary string object to be written to a file is too
expensive.

These handlers are all optional, and most types at most need to implement the
:c:member:`~PyTypeObject.tp_str` and :c:member:`~PyTypeObject.tp_repr` handlers. ::

   reprfunc tp_repr;
   reprfunc tp_str;
   printfunc tp_print;

The :c:member:`~PyTypeObject.tp_repr` handler should return a string object containing a
representation of the instance for which it is called.  Here is a simple
example::

   static PyObject *
   newdatatype_repr(newdatatypeobject * obj)
   {
       return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
                                  obj->obj_UnderlyingDatatypePtr->size);
   }

If no :c:member:`~PyTypeObject.tp_repr` handler is specified, the interpreter will supply a
representation that uses the type's :c:member:`~PyTypeObject.tp_name` and a uniquely-identifying
value for the object.

The :c:member:`~PyTypeObject.tp_str` handler is to :func:`str` what the :c:member:`~PyTypeObject.tp_repr` handler
described above is to :func:`repr`; that is, it is called when Python code calls
:func:`str` on an instance of your object.  Its implementation is very similar
to the :c:member:`~PyTypeObject.tp_repr` function, but the resulting string is intended for human
consumption.  If :c:member:`~PyTypeObject.tp_str` is not specified, the :c:member:`~PyTypeObject.tp_repr` handler is
used instead.

Here is a simple example::

   static PyObject *
   newdatatype_str(newdatatypeobject * obj)
   {
       return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
                                  obj->obj_UnderlyingDatatypePtr->size);
   }

The print function will be called whenever Python needs to "print" an instance
of the type.  For example, if 'node' is an instance of type TreeNode, then the
print function is called when Python code calls::

   print node

There is a flags argument and one flag, :const:`Py_PRINT_RAW`, and it suggests
that you print without string quotes and possibly without interpreting escape
sequences.

The print function receives a file object as an argument. You will likely want
to write to that file object.

Here is a sample print function::

   static int
   newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
   {
       if (flags & Py_PRINT_RAW) {
           fprintf(fp, "<{newdatatype object--size: %d}>",
                   obj->obj_UnderlyingDatatypePtr->size);
       }
       else {
           fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
                   obj->obj_UnderlyingDatatypePtr->size);
       }
       return 0;
   }


Attribute Management
--------------------

For every object which can support attributes, the corresponding type must
provide the functions that control how the attributes are resolved.  There needs
to be a function which can retrieve attributes (if any are defined), and another
to set attributes (if setting attributes is allowed).  Removing an attribute is
a special case, for which the new value passed to the handler is *NULL*.

Python supports two pairs of attribute handlers; a type that supports attributes
only needs to implement the functions for one pair.  The difference is that one
pair takes the name of the attribute as a :c:type:`char\*`, while the other
accepts a :c:type:`PyObject\*`.  Each type can use whichever pair makes more
sense for the implementation's convenience. ::

   getattrfunc  tp_getattr;        /* char * version */
   setattrfunc  tp_setattr;
   /* ... */
   getattrofunc tp_getattrofunc;   /* PyObject * version */
   setattrofunc tp_setattrofunc;

If accessing attributes of an object is always a simple operation (this will be
explained shortly), there are generic implementations which can be used to
provide the :c:type:`PyObject\*` version of the attribute management functions.
The actual need for type-specific attribute handlers almost completely
disappeared starting with Python 2.2, though there are many examples which have
not been updated to use some of the new generic mechanism that is available.


.. _generic-attribute-management:

Generic Attribute Management
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 2.2

Most extension types only use *simple* attributes.  So, what makes the
attributes simple?  There are only a couple of conditions that must be met:

#. The name of the attributes must be known when :c:func:`PyType_Ready` is
   called.

#. No special processing is needed to record that an attribute was looked up or
   set, nor do actions need to be taken based on the value.

Note that this list does not place any restrictions on the values of the
attributes, when the values are computed, or how relevant data is stored.

When :c:func:`PyType_Ready` is called, it uses three tables referenced by the
type object to create :term:`descriptor`\s which are placed in the dictionary of the
type object.  Each descriptor controls access to one attribute of the instance
object.  Each of the tables is optional; if all three are *NULL*, instances of
the type will only have attributes that are inherited from their base type, and
should leave the :c:member:`~PyTypeObject.tp_getattro` and :c:member:`~PyTypeObject.tp_setattro` fields *NULL* as
well, allowing the base type to handle attributes.

The tables are declared as three fields of the type object::

   struct PyMethodDef *tp_methods;
   struct PyMemberDef *tp_members;
   struct PyGetSetDef *tp_getset;

If :c:member:`~PyTypeObject.tp_methods` is not *NULL*, it must refer to an array of
:c:type:`PyMethodDef` structures.  Each entry in the table is an instance of this
structure::

   typedef struct PyMethodDef {
       const char  *ml_name;       /* method name */
       PyCFunction  ml_meth;       /* implementation function */
       int          ml_flags;      /* flags */
       const char  *ml_doc;        /* docstring */
   } PyMethodDef;

One entry should be defined for each method provided by the type; no entries are
needed for methods inherited from a base type.  One additional entry is needed
at the end; it is a sentinel that marks the end of the array.  The
:attr:`ml_name` field of the sentinel must be *NULL*.

XXX Need to refer to some unified discussion of the structure fields, shared
with the next section.

The second table is used to define attributes which map directly to data stored
in the instance.  A variety of primitive C types are supported, and access may
be read-only or read-write.  The structures in the table are defined as::

   typedef struct PyMemberDef {
       char *name;
       int   type;
       int   offset;
       int   flags;
       char *doc;
   } PyMemberDef;

For each entry in the table, a :term:`descriptor` will be constructed and added to the
type which will be able to extract a value from the instance structure.  The
:attr:`type` field should contain one of the type codes defined in the
:file:`structmember.h` header; the value will be used to determine how to
convert Python values to and from C values.  The :attr:`flags` field is used to
store flags which control how the attribute can be accessed.

XXX Need to move some of this to a shared section!

The following flag constants are defined in :file:`structmember.h`; they may be
combined using bitwise-OR.

+---------------------------+----------------------------------------------+
| Constant                  | Meaning                                      |
+===========================+==============================================+
| :const:`READONLY`         | Never writable.                              |
+---------------------------+----------------------------------------------+
| :const:`RO`               | Shorthand for :const:`READONLY`.             |
+---------------------------+----------------------------------------------+
| :const:`READ_RESTRICTED`  | Not readable in restricted mode.             |
+---------------------------+----------------------------------------------+
| :const:`WRITE_RESTRICTED` | Not writable in restricted mode.             |
+---------------------------+----------------------------------------------+
| :const:`RESTRICTED`       | Not readable or writable in restricted mode. |
+---------------------------+----------------------------------------------+

.. index::
   single: READONLY
   single: RO
   single: READ_RESTRICTED
   single: WRITE_RESTRICTED
   single: RESTRICTED

An interesting advantage of using the :c:member:`~PyTypeObject.tp_members` table to build
descriptors that are used at runtime is that any attribute defined this way can
have an associated doc string simply by providing the text in the table.  An
application can use the introspection API to retrieve the descriptor from the
class object, and get the doc string using its :attr:`__doc__` attribute.

As with the :c:member:`~PyTypeObject.tp_methods` table, a sentinel entry with a :attr:`name` value
of *NULL* is required.

.. XXX Descriptors need to be explained in more detail somewhere, but not here.

   Descriptor objects have two handler functions which correspond to the
   \member{tp_getattro} and \member{tp_setattro} handlers.  The
   \method{__get__()} handler is a function which is passed the descriptor,
   instance, and type objects, and returns the value of the attribute, or it
   returns \NULL{} and sets an exception.  The \method{__set__()} handler is
   passed the descriptor, instance, type, and new value;


Type-specific Attribute Management
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For simplicity, only the :c:type:`char\*` version will be demonstrated here; the
type of the name parameter is the only difference between the :c:type:`char\*`
and :c:type:`PyObject\*` flavors of the interface. This example effectively does
the same thing as the generic example above, but does not use the generic
support added in Python 2.2.  The value in showing this is two-fold: it
demonstrates how basic attribute management can be done in a way that is
portable to older versions of Python, and explains how the handler functions are
called, so that if you do need to extend their functionality, you'll understand
what needs to be done.

The :c:member:`~PyTypeObject.tp_getattr` handler is called when the object requires an attribute
look-up.  It is called in the same situations where the :meth:`__getattr__`
method of a class would be called.

A likely way to handle this is (1) to implement a set of functions (such as
:c:func:`newdatatype_getSize` and :c:func:`newdatatype_setSize` in the example
below), (2) provide a method table listing these functions, and (3) provide a
getattr function that returns the result of a lookup in that table.  The method
table uses the same structure as the :c:member:`~PyTypeObject.tp_methods` field of the type
object.

Here is an example::

   static PyMethodDef newdatatype_methods[] = {
       {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
        "Return the current size."},
       {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
        "Set the size."},
       {NULL, NULL, 0, NULL}           /* sentinel */
   };

   static PyObject *
   newdatatype_getattr(newdatatypeobject *obj, char *name)
   {
       return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
   }

The :c:member:`~PyTypeObject.tp_setattr` handler is called when the :meth:`__setattr__` or
:meth:`__delattr__` method of a class instance would be called.  When an
attribute should be deleted, the third parameter will be *NULL*.  Here is an
example that simply raises an exception; if this were really all you wanted, the
:c:member:`~PyTypeObject.tp_setattr` handler should be set to *NULL*. ::

   static int
   newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
   {
       (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
       return -1;
   }


Object Comparison
-----------------

::

   cmpfunc tp_compare;

The :c:member:`~PyTypeObject.tp_compare` handler is called when comparisons are needed and the
object does not implement the specific rich comparison method which matches the
requested comparison.  (It is always used if defined and the
:c:func:`PyObject_Compare` or :c:func:`PyObject_Cmp` functions are used, or if
:func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method.
This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they
are equal, and ``1`` if *obj1* is greater than *obj2*. (It was previously
allowed to return arbitrary negative or positive integers for less than and
greater than, respectively; as of Python 2.2, this is no longer allowed.  In the
future, other return values may be assigned a different meaning.)

A :c:member:`~PyTypeObject.tp_compare` handler may raise an exception.  In this case it should
return a negative value.  The caller has to test for the exception using
:c:func:`PyErr_Occurred`.

Here is a sample implementation::

   static int
   newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
   {
       long result;

       if (obj1->obj_UnderlyingDatatypePtr->size <
           obj2->obj_UnderlyingDatatypePtr->size) {
           result = -1;
       }
       else if (obj1->obj_UnderlyingDatatypePtr->size >
                obj2->obj_UnderlyingDatatypePtr->size) {
           result = 1;
       }
       else {
           result = 0;
       }
       return result;
   }


Abstract Protocol Support
-------------------------

Python supports a variety of *abstract* 'protocols;' the specific interfaces
provided to use these interfaces are documented in :ref:`abstract`.


A number of these abstract interfaces were defined early in the development of
the Python implementation.  In particular, the number, mapping, and sequence
protocols have been part of Python since the beginning.  Other protocols have
been added over time.  For protocols which depend on several handler routines
from the type implementation, the older protocols have been defined as optional
blocks of handlers referenced by the type object.  For newer protocols there are
additional slots in the main type object, with a flag bit being set to indicate
that the slots are present and should be checked by the interpreter.  (The flag
bit does not indicate that the slot values are non-*NULL*. The flag may be set
to indicate the presence of a slot, but a slot may still be unfilled.) ::

   PyNumberMethods   *tp_as_number;
   PySequenceMethods *tp_as_sequence;
   PyMappingMethods  *tp_as_mapping;

If you wish your object to be able to act like a number, a sequence, or a
mapping object, then you place the address of a structure that implements the C
type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or
:c:type:`PyMappingMethods`, respectively. It is up to you to fill in this
structure with appropriate values. You can find examples of the use of each of
these in the :file:`Objects` directory of the Python source distribution. ::

   hashfunc tp_hash;

This function, if you choose to provide it, should return a hash number for an
instance of your data type. Here is a moderately pointless example::

   static long
   newdatatype_hash(newdatatypeobject *obj)
   {
       long result;
       result = obj->obj_UnderlyingDatatypePtr->size;
       result = result * 3;
       return result;
   }

::

   ternaryfunc tp_call;

This function is called when an instance of your data type is "called", for
example, if ``obj1`` is an instance of your data type and the Python script
contains ``obj1('hello')``, the :c:member:`~PyTypeObject.tp_call` handler is invoked.

This function takes three arguments:

#. *arg1* is the instance of the data type which is the subject of the call. If
   the call is ``obj1('hello')``, then *arg1* is ``obj1``.

#. *arg2* is a tuple containing the arguments to the call.  You can use
   :c:func:`PyArg_ParseTuple` to extract the arguments.

#. *arg3* is a dictionary of keyword arguments that were passed. If this is
   non-*NULL* and you support keyword arguments, use
   :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments.  If you do not
   want to support keyword arguments and this is non-*NULL*, raise a
   :exc:`TypeError` with a message saying that keyword arguments are not supported.

Here is a desultory example of the implementation of the call function. ::

   /* Implement the call function.
    *    obj1 is the instance receiving the call.
    *    obj2 is a tuple containing the arguments to the call, in this
    *         case 3 strings.
    */
   static PyObject *
   newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
   {
       PyObject *result;
       char *arg1;
       char *arg2;
       char *arg3;

       if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
           return NULL;
       }
       result = PyString_FromFormat(
           "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
           obj->obj_UnderlyingDatatypePtr->size,
           arg1, arg2, arg3);
       printf("\%s", PyString_AS_STRING(result));
       return result;
   }

XXX some fields need to be added here... ::

   /* Added in release 2.2 */
   /* Iterators */
   getiterfunc tp_iter;
   iternextfunc tp_iternext;

These functions provide support for the iterator protocol.  Any object which
wishes to support iteration over its contents (which may be generated during
iteration) must implement the ``tp_iter`` handler.  Objects which are returned
by a ``tp_iter`` handler must implement both the ``tp_iter`` and ``tp_iternext``
handlers. Both handlers take exactly one parameter, the instance for which they
are being called, and return a new reference.  In the case of an error, they
should set an exception and return *NULL*.

For an object which represents an iterable collection, the ``tp_iter`` handler
must return an iterator object.  The iterator object is responsible for
maintaining the state of the iteration.  For collections which can support
multiple iterators which do not interfere with each other (as lists and tuples
do), a new iterator should be created and returned.  Objects which can only be
iterated over once (usually due to side effects of iteration) should implement
this handler by returning a new reference to themselves, and should also
implement the ``tp_iternext`` handler.  File objects are an example of such an
iterator.

Iterator objects should implement both handlers.  The ``tp_iter`` handler should
return a new reference to the iterator (this is the same as the ``tp_iter``
handler for objects which can only be iterated over destructively).  The
``tp_iternext`` handler should return a new reference to the next object in the
iteration if there is one.  If the iteration has reached the end, it may return
*NULL* without setting an exception or it may set :exc:`StopIteration`; avoiding
the exception can yield slightly better performance.  If an actual error occurs,
it should set an exception and return *NULL*.


.. _weakref-support:

Weak Reference Support
----------------------

One of the goals of Python's weak-reference implementation is to allow any type
to participate in the weak reference mechanism without incurring the overhead on
those objects which do not benefit by weak referencing (such as numbers).

For an object to be weakly referencable, the extension must include a
:c:type:`PyObject\*` field in the instance structure for the use of the weak
reference mechanism; it must be initialized to *NULL* by the object's
constructor.  It must also set the :c:member:`~PyTypeObject.tp_weaklistoffset` field of the
corresponding type object to the offset of the field. For example, the instance
type is defined with the following structure::

   typedef struct {
       PyObject_HEAD
       PyClassObject *in_class;       /* The class object */
       PyObject      *in_dict;        /* A dictionary */
       PyObject      *in_weakreflist; /* List of weak references */
   } PyInstanceObject;

The statically-declared type object for instances is defined this way::

   PyTypeObject PyInstance_Type = {
       PyObject_HEAD_INIT(&PyType_Type)
       0,
       "module.instance",

       /* Lots of stuff omitted for brevity... */

       Py_TPFLAGS_DEFAULT,                         /* tp_flags */
       0,                                          /* tp_doc */
       0,                                          /* tp_traverse */
       0,                                          /* tp_clear */
       0,                                          /* tp_richcompare */
       offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
   };

The type constructor is responsible for initializing the weak reference list to
*NULL*::

   static PyObject *
   instance_new() {
       /* Other initialization stuff omitted for brevity */

       self->in_weakreflist = NULL;

       return (PyObject *) self;
   }

The only further addition is that the destructor needs to call the weak
reference manager to clear any weak references.  This is only required if the
weak reference list is non-*NULL*::

   static void
   instance_dealloc(PyInstanceObject *inst)
   {
       /* Allocate temporaries if needed, but do not begin
          destruction just yet.
        */

       if (inst->in_weakreflist != NULL)
           PyObject_ClearWeakRefs((PyObject *) inst);

       /* Proceed with object destruction normally. */
   }


More Suggestions
----------------

Remember that you can omit most of these functions, in which case you provide
``0`` as a value.  There are type definitions for each of the functions you must
provide.  They are in :file:`object.h` in the Python include directory that
comes with the source distribution of Python.

In order to learn how to implement any specific method for your new data type,
do the following: Download and unpack the Python source distribution.  Go the
:file:`Objects` directory, then search the C source files for ``tp_`` plus the
function you want (for example, ``tp_print`` or ``tp_compare``).  You will find
examples of the function you want to implement.

When you need to verify that an object is an instance of the type you are
implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use
might be something like the following::

   if (! PyObject_TypeCheck(some_object, &MyType)) {
       PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
       return NULL;
   }

.. rubric:: Footnotes

.. [#] This is true when we know that the object is a basic type, like a string or a
   float.

.. [#] We relied on this in the :c:member:`~PyTypeObject.tp_dealloc` handler in this example, because our
   type doesn't support garbage collection. Even if a type supports garbage
   collection, there are calls that can be made to "untrack" the object from
   garbage collection, however, these calls are advanced and not covered here.

.. [#] We now know that the first and last members are strings, so perhaps we could be
   less careful about decrementing their reference counts, however, we accept
   instances of string subclasses. Even though deallocating normal strings won't
   call back into our objects, we can't guarantee that deallocating an instance of
   a string subclass won't call back into our objects.

.. [#] Even in the third version, we aren't guaranteed to avoid cycles.  Instances of
   string subclasses are allowed and string subclasses could allow cycles even if
   normal strings don't.
PK	%�\:n	�  'html/_sources/extending/windows.rst.txtnu�[���.. highlightlang:: c


.. _building-on-windows:

****************************************
Building C and C++ Extensions on Windows
****************************************

This chapter briefly explains how to create a Windows extension module for
Python using Microsoft Visual C++, and follows with more detailed background
information on how it works.  The explanatory material is useful for both the
Windows programmer learning to build Python extensions and the Unix programmer
interested in producing software which can be successfully built on both Unix
and Windows.

Module authors are encouraged to use the distutils approach for building
extension modules, instead of the one described in this section. You will still
need the C compiler that was used to build Python; typically Microsoft Visual
C++.

.. note::

   This chapter mentions a number of filenames that include an encoded Python
   version number.  These filenames are represented with the version number shown
   as ``XY``; in practice, ``'X'`` will be the major version number and ``'Y'``
   will be the minor version number of the Python release you're working with.  For
   example, if you are using Python 2.2.1, ``XY`` will actually be ``22``.


.. _win-cookbook:

A Cookbook Approach
===================

There are two approaches to building extension modules on Windows, just as there
are on Unix: use the :mod:`distutils` package to control the build process, or
do things manually.  The distutils approach works well for most extensions;
documentation on using :mod:`distutils` to build and package extension modules
is available in :ref:`distutils-index`.  If you find you really need to do
things manually, it may be instructive to study the project file for the
:source:`winsound <PCbuild/winsound.vcxproj>` standard library module.


.. _dynamic-linking:

Differences Between Unix and Windows
====================================

.. sectionauthor:: Chris Phoenix <cphoenix@best.com>


Unix and Windows use completely different paradigms for run-time loading of
code.  Before you try to build a module that can be dynamically loaded, be aware
of how your system works.

In Unix, a shared object (:file:`.so`) file contains code to be used by the
program, and also the names of functions and data that it expects to find in the
program.  When the file is joined to the program, all references to those
functions and data in the file's code are changed to point to the actual
locations in the program where the functions and data are placed in memory.
This is basically a link operation.

In Windows, a dynamic-link library (:file:`.dll`) file has no dangling
references.  Instead, an access to functions or data goes through a lookup
table.  So the DLL code does not have to be fixed up at runtime to refer to the
program's memory; instead, the code already uses the DLL's lookup table, and the
lookup table is modified at runtime to point to the functions and data.

In Unix, there is only one type of library file (:file:`.a`) which contains code
from several object files (:file:`.o`).  During the link step to create a shared
object file (:file:`.so`), the linker may find that it doesn't know where an
identifier is defined.  The linker will look for it in the object files in the
libraries; if it finds it, it will include all the code from that object file.

In Windows, there are two types of library, a static library and an import
library (both called :file:`.lib`).  A static library is like a Unix :file:`.a`
file; it contains code to be included as necessary. An import library is
basically used only to reassure the linker that a certain identifier is legal,
and will be present in the program when the DLL is loaded.  So the linker uses
the information from the import library to build the lookup table for using
identifiers that are not included in the DLL.  When an application or a DLL is
linked, an import library may be generated, which will need to be used for all
future DLLs that depend on the symbols in the application or DLL.

Suppose you are building two dynamic-load modules, B and C, which should share
another block of code A.  On Unix, you would *not* pass :file:`A.a` to the
linker for :file:`B.so` and :file:`C.so`; that would cause it to be included
twice, so that B and C would each have their own copy.  In Windows, building
:file:`A.dll` will also build :file:`A.lib`.  You *do* pass :file:`A.lib` to the
linker for B and C.  :file:`A.lib` does not contain code; it just contains
information which will be used at runtime to access A's code.

In Windows, using an import library is sort of like using ``import spam``; it
gives you access to spam's names, but does not create a separate copy.  On Unix,
linking with a library is more like ``from spam import *``; it does create a
separate copy.


.. _win-dlls:

Using DLLs in Practice
======================

.. sectionauthor:: Chris Phoenix <cphoenix@best.com>


Windows Python is built in Microsoft Visual C++; using other compilers may or
may not work (though Borland seems to).  The rest of this section is MSVC++
specific.

When creating DLLs in Windows, you must pass :file:`pythonXY.lib` to the linker.
To build two DLLs, spam and ni (which uses C functions found in spam), you could
use these commands::

   cl /LD /I/python/include spam.c ../libs/pythonXY.lib
   cl /LD /I/python/include ni.c spam.lib ../libs/pythonXY.lib

The first command created three files: :file:`spam.obj`, :file:`spam.dll` and
:file:`spam.lib`.  :file:`Spam.dll` does not contain any Python functions (such
as :c:func:`PyArg_ParseTuple`), but it does know how to find the Python code
thanks to :file:`pythonXY.lib`.

The second command created :file:`ni.dll` (and :file:`.obj` and :file:`.lib`),
which knows how to find the necessary functions from spam, and also from the
Python executable.

Not every identifier is exported to the lookup table.  If you want any other
modules (including Python) to be able to see your identifiers, you have to say
``_declspec(dllexport)``, as in ``void _declspec(dllexport) initspam(void)`` or
``PyObject _declspec(dllexport) *NiGetSpamData(void)``.

Developer Studio will throw in a lot of import libraries that you do not really
need, adding about 100K to your executable.  To get rid of them, use the Project
Settings dialog, Link tab, to specify *ignore default libraries*.  Add the
correct :file:`msvcrtxx.lib` to the list of libraries.

PK	%�\P�9s�� html/_sources/faq/design.rst.txtnu�[���======================
Design and History FAQ
======================

.. only:: html

   .. contents::


Why does Python use indentation for grouping of statements?
-----------------------------------------------------------

Guido van Rossum believes that using indentation for grouping is extremely
elegant and contributes a lot to the clarity of the average Python program.
Most people learn to love this feature after a while.

Since there are no begin/end brackets there cannot be a disagreement between
grouping perceived by the parser and the human reader.  Occasionally C
programmers will encounter a fragment of code like this::

   if (x <= y)
           x++;
           y--;
   z++;

Only the ``x++`` statement is executed if the condition is true, but the
indentation leads you to believe otherwise.  Even experienced C programmers will
sometimes stare at it a long time wondering why ``y`` is being decremented even
for ``x > y``.

Because there are no begin/end brackets, Python is much less prone to
coding-style conflicts.  In C there are many different ways to place the braces.
If you're used to reading and writing code that uses one style, you will feel at
least slightly uneasy when reading (or being required to write) another style.

Many coding styles place begin/end brackets on a line by themselves.  This makes
programs considerably longer and wastes valuable screen space, making it harder
to get a good overview of a program.  Ideally, a function should fit on one
screen (say, 20--30 lines).  20 lines of Python can do a lot more work than 20
lines of C.  This is not solely due to the lack of begin/end brackets -- the
lack of declarations and the high-level data types are also responsible -- but
the indentation-based syntax certainly helps.


Why am I getting strange results with simple arithmetic operations?
-------------------------------------------------------------------

See the next question.


Why are floating point calculations so inaccurate?
--------------------------------------------------

People are often very surprised by results like this::

   >>> 1.2 - 1.0
   0.19999999999999996

and think it is a bug in Python. It's not.  This has nothing to do with Python,
but with how the underlying C platform handles floating point numbers, and
ultimately with the inaccuracies introduced when writing down numbers as a
string of a fixed number of digits.

The internal representation of floating point numbers uses a fixed number of
binary digits to represent a decimal number.  Some decimal numbers can't be
represented exactly in binary, resulting in small roundoff errors.

In decimal math, there are many numbers that can't be represented with a fixed
number of decimal digits, e.g.  1/3 = 0.3333333333.......

In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc.  .2 equals 2/10 equals 1/5,
resulting in the binary fractional number 0.001100110011001...

Floating point numbers only have 32 or 64 bits of precision, so the digits are
cut off at some point, and the resulting number is 0.199999999999999996 in
decimal, not 0.2.

A floating point number's ``repr()`` function prints as many digits are
necessary to make ``eval(repr(f)) == f`` true for any float f.  The ``str()``
function prints fewer digits and this often results in the more sensible number
that was probably intended::

   >>> 1.1 - 0.9
   0.20000000000000007
   >>> print 1.1 - 0.9
   0.2

One of the consequences of this is that it is error-prone to compare the result
of some computation to a float with ``==``. Tiny inaccuracies may mean that
``==`` fails.  Instead, you have to check that the difference between the two
numbers is less than a certain threshold::

   epsilon = 0.0000000000001  # Tiny allowed error
   expected_result = 0.4

   if expected_result-epsilon <= computation() <= expected_result+epsilon:
       ...

Please see the chapter on :ref:`floating point arithmetic <tut-fp-issues>` in
the Python tutorial for more information.


Why are Python strings immutable?
---------------------------------

There are several advantages.

One is performance: knowing that a string is immutable means we can allocate
space for it at creation time, and the storage requirements are fixed and
unchanging.  This is also one of the reasons for the distinction between tuples
and lists.

Another advantage is that strings in Python are considered as "elemental" as
numbers.  No amount of activity will change the value 8 to anything else, and in
Python, no amount of activity will change the string "eight" to anything else.


.. _why-self:

Why must 'self' be used explicitly in method definitions and calls?
-------------------------------------------------------------------

The idea was borrowed from Modula-3.  It turns out to be very useful, for a
variety of reasons.

First, it's more obvious that you are using a method or instance attribute
instead of a local variable.  Reading ``self.x`` or ``self.meth()`` makes it
absolutely clear that an instance variable or method is used even if you don't
know the class definition by heart.  In C++, you can sort of tell by the lack of
a local variable declaration (assuming globals are rare or easily recognizable)
-- but in Python, there are no local variable declarations, so you'd have to
look up the class definition to be sure.  Some C++ and Java coding standards
call for instance attributes to have an ``m_`` prefix, so this explicitness is
still useful in those languages, too.

Second, it means that no special syntax is necessary if you want to explicitly
reference or call the method from a particular class.  In C++, if you want to
use a method from a base class which is overridden in a derived class, you have
to use the ``::`` operator -- in Python you can write
``baseclass.methodname(self, <argument list>)``.  This is particularly useful
for :meth:`__init__` methods, and in general in cases where a derived class
method wants to extend the base class method of the same name and thus has to
call the base class method somehow.

Finally, for instance variables it solves a syntactic problem with assignment:
since local variables in Python are (by definition!) those variables to which a
value is assigned in a function body (and that aren't explicitly declared
global), there has to be some way to tell the interpreter that an assignment was
meant to assign to an instance variable instead of to a local variable, and it
should preferably be syntactic (for efficiency reasons).  C++ does this through
declarations, but Python doesn't have declarations and it would be a pity having
to introduce them just for this purpose.  Using the explicit ``self.var`` solves
this nicely.  Similarly, for using instance variables, having to write
``self.var`` means that references to unqualified names inside a method don't
have to search the instance's directories.  To put it another way, local
variables and instance variables live in two different namespaces, and you need
to tell Python which namespace to use.


Why can't I use an assignment in an expression?
-----------------------------------------------

Many people used to C or Perl complain that they want to use this C idiom:

.. code-block:: c

   while (line = readline(f)) {
       // do something with line
   }

where in Python you're forced to write this::

   while True:
       line = f.readline()
       if not line:
           break
       ...  # do something with line

The reason for not allowing assignment in Python expressions is a common,
hard-to-find bug in those other languages, caused by this construct:

.. code-block:: c

    if (x = 0) {
        // error handling
    }
    else {
        // code that only works for nonzero x
    }

The error is a simple typo: ``x = 0``, which assigns 0 to the variable ``x``,
was written while the comparison ``x == 0`` is certainly what was intended.

Many alternatives have been proposed.  Most are hacks that save some typing but
use arbitrary or cryptic syntax or keywords, and fail the simple criterion for
language change proposals: it should intuitively suggest the proper meaning to a
human reader who has not yet been introduced to the construct.

An interesting phenomenon is that most experienced Python programmers recognize
the ``while True`` idiom and don't seem to be missing the assignment in
expression construct much; it's only newcomers who express a strong desire to
add this to the language.

There's an alternative way of spelling this that seems attractive but is
generally less robust than the "while True" solution::

   line = f.readline()
   while line:
       ...  # do something with line...
       line = f.readline()

The problem with this is that if you change your mind about exactly how you get
the next line (e.g. you want to change it into ``sys.stdin.readline()``) you
have to remember to change two places in your program -- the second occurrence
is hidden at the bottom of the loop.

The best approach is to use iterators, making it possible to loop through
objects using the ``for`` statement.  For example, in the current version of
Python file objects support the iterator protocol, so you can now write simply::

   for line in f:
       ...  # do something with line...



Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?
----------------------------------------------------------------------------------------------------------------

As Guido said:

    (a) For some operations, prefix notation just reads better than
    postfix -- prefix (and infix!) operations have a long tradition in
    mathematics which likes notations where the visuals help the
    mathematician thinking about a problem. Compare the easy with which we
    rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
    doing the same thing using a raw OO notation.

    (b) When I read code that says len(x) I *know* that it is asking for
    the length of something. This tells me two things: the result is an
    integer, and the argument is some kind of container. To the contrary,
    when I read x.len(), I have to already know that x is some kind of
    container implementing an interface or inheriting from a class that
    has a standard len(). Witness the confusion we occasionally have when
    a class that is not implementing a mapping has a get() or keys()
    method, or something that isn't a file has a write() method.

    -- https://mail.python.org/pipermail/python-3000/2006-November/004643.html


Why is join() a string method instead of a list or tuple method?
----------------------------------------------------------------

Strings became much more like other standard types starting in Python 1.6, when
methods were added which give the same functionality that has always been
available using the functions of the string module.  Most of these new methods
have been widely accepted, but the one which appears to make some programmers
feel uncomfortable is::

   ", ".join(['1', '2', '4', '8', '16'])

which gives the result::

   "1, 2, 4, 8, 16"

There are two common arguments against this usage.

The first runs along the lines of: "It looks really ugly using a method of a
string literal (string constant)", to which the answer is that it might, but a
string literal is just a fixed value. If the methods are to be allowed on names
bound to strings there is no logical reason to make them unavailable on
literals.

The second objection is typically cast as: "I am really telling a sequence to
join its members together with a string constant".  Sadly, you aren't.  For some
reason there seems to be much less difficulty with having :meth:`~str.split` as
a string method, since in that case it is easy to see that ::

   "1, 2, 4, 8, 16".split(", ")

is an instruction to a string literal to return the substrings delimited by the
given separator (or, by default, arbitrary runs of white space).  In this case a
Unicode string returns a list of Unicode strings, an ASCII string returns a list
of ASCII strings, and everyone is happy.

:meth:`~str.join` is a string method because in using it you are telling the
separator string to iterate over a sequence of strings and insert itself between
adjacent elements.  This method can be used with any argument which obeys the
rules for sequence objects, including any new classes you might define yourself.

Because this is a string method it can work for Unicode strings as well as plain
ASCII strings.  If ``join()`` were a method of the sequence types then the
sequence types would have to decide which type of string to return depending on
the type of the separator.

.. XXX remove next paragraph eventually

If none of these arguments persuade you, then for the moment you can continue to
use the ``join()`` function from the string module, which allows you to write ::

   string.join(['1', '2', '4', '8', '16'], ", ")


How fast are exceptions?
------------------------

A try/except block is extremely efficient if no exceptions are raised.  Actually
catching an exception is expensive.  In versions of Python prior to 2.0 it was
common to use this idiom::

   try:
       value = mydict[key]
   except KeyError:
       mydict[key] = getvalue(key)
       value = mydict[key]

This only made sense when you expected the dict to have the key almost all the
time.  If that wasn't the case, you coded it like this::

   if key in mydict:
       value = mydict[key]
   else:
       value = mydict[key] = getvalue(key)

.. note::

   In Python 2.0 and higher, you can code this as ``value =
   mydict.setdefault(key, getvalue(key))``.


Why isn't there a switch or case statement in Python?
-----------------------------------------------------

You can do this easily enough with a sequence of ``if... elif... elif... else``.
There have been some proposals for switch statement syntax, but there is no
consensus (yet) on whether and how to do range tests.  See :pep:`275` for
complete details and the current status.

For cases where you need to choose from a very large number of possibilities,
you can create a dictionary mapping case values to functions to call.  For
example::

   def function_1(...):
       ...

   functions = {'a': function_1,
                'b': function_2,
                'c': self.method_1, ...}

   func = functions[value]
   func()

For calling methods on objects, you can simplify yet further by using the
:func:`getattr` built-in to retrieve methods with a particular name::

   def visit_a(self, ...):
       ...
   ...

   def dispatch(self, value):
       method_name = 'visit_' + str(value)
       method = getattr(self, method_name)
       method()

It's suggested that you use a prefix for the method names, such as ``visit_`` in
this example.  Without such a prefix, if values are coming from an untrusted
source, an attacker would be able to call any method on your object.


Can't you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?
--------------------------------------------------------------------------------------------------------

Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for
each Python stack frame.  Also, extensions can call back into Python at almost
random moments.  Therefore, a complete threads implementation requires thread
support for C.

Answer 2: Fortunately, there is `Stackless Python <http://www.stackless.com>`_,
which has a completely redesigned interpreter loop that avoids the C stack.


Why can't lambda expressions contain statements?
------------------------------------------------

Python lambda expressions cannot contain statements because Python's syntactic
framework can't handle statements nested inside expressions.  However, in
Python, this is not a serious problem.  Unlike lambda forms in other languages,
where they add functionality, Python lambdas are only a shorthand notation if
you're too lazy to define a function.

Functions are already first class objects in Python, and can be declared in a
local scope.  Therefore the only advantage of using a lambda instead of a
locally-defined function is that you don't need to invent a name for the
function -- but that's just a local variable to which the function object (which
is exactly the same type of object that a lambda expression yields) is assigned!


Can Python be compiled to machine code, C or some other language?
-----------------------------------------------------------------

`Cython <http://cython.org/>`_ compiles a modified version of Python with
optional annotations into C extensions.  `Nuitka <http://www.nuitka.net/>`_ is
an up-and-coming compiler of Python into C++ code, aiming to support the full
Python language. For compiling to Java you can consider
`VOC <https://voc.readthedocs.io>`_.


How does Python manage memory?
------------------------------

The details of Python memory management depend on the implementation.  The
standard C implementation of Python uses reference counting to detect
inaccessible objects, and another mechanism to collect reference cycles,
periodically executing a cycle detection algorithm which looks for inaccessible
cycles and deletes the objects involved. The :mod:`gc` module provides functions
to perform a garbage collection, obtain debugging statistics, and tune the
collector's parameters.

Jython relies on the Java runtime so the JVM's garbage collector is used.  This
difference can cause some subtle porting problems if your Python code depends on
the behavior of the reference counting implementation.

.. XXX relevant for Python 2.6?

Sometimes objects get stuck in tracebacks temporarily and hence are not
deallocated when you might expect.  Clear the tracebacks with::

   import sys
   sys.exc_clear()
   sys.exc_traceback = sys.last_traceback = None

Tracebacks are used for reporting errors, implementing debuggers and related
things.  They contain a portion of the program state extracted during the
handling of an exception (usually the most recent exception).

In the absence of circularities and tracebacks, Python programs do not need to
manage memory explicitly.

Why doesn't Python use a more traditional garbage collection scheme?  For one
thing, this is not a C standard feature and hence it's not portable.  (Yes, we
know about the Boehm GC library.  It has bits of assembler code for *most*
common platforms, not for all of them, and although it is mostly transparent, it
isn't completely transparent; patches are required to get Python to work with
it.)

Traditional GC also becomes a problem when Python is embedded into other
applications.  While in a standalone Python it's fine to replace the standard
malloc() and free() with versions provided by the GC library, an application
embedding Python may want to have its *own* substitute for malloc() and free(),
and may not want Python's.  Right now, Python works with anything that
implements malloc() and free() properly.

In Jython, the following code (which is fine in CPython) will probably run out
of file descriptors long before it runs out of memory::

   for file in very_long_list_of_files:
       f = open(file)
       c = f.read(1)

Using the current reference counting and destructor scheme, each new assignment
to f closes the previous file.  Using GC, this is not guaranteed.  If you want
to write code that will work with any Python implementation, you should
explicitly close the file or use the :keyword:`with` statement; this will work
regardless of GC::

   for file in very_long_list_of_files:
       with open(file) as f:
           c = f.read(1)


Why isn't all memory freed when Python exits?
---------------------------------------------

Objects referenced from the global namespaces of Python modules are not always
deallocated when Python exits.  This may happen if there are circular
references.  There are also certain bits of memory that are allocated by the C
library that are impossible to free (e.g. a tool like Purify will complain about
these).  Python is, however, aggressive about cleaning up memory on exit and
does try to destroy every single object.

If you want to force Python to delete certain things on deallocation use the
:mod:`atexit` module to run a function that will force those deletions.


Why are there separate tuple and list data types?
-------------------------------------------------

Lists and tuples, while similar in many respects, are generally used in
fundamentally different ways.  Tuples can be thought of as being similar to
Pascal records or C structs; they're small collections of related data which may
be of different types which are operated on as a group.  For example, a
Cartesian coordinate is appropriately represented as a tuple of two or three
numbers.

Lists, on the other hand, are more like arrays in other languages.  They tend to
hold a varying number of objects all of which have the same type and which are
operated on one-by-one.  For example, ``os.listdir('.')`` returns a list of
strings representing the files in the current directory.  Functions which
operate on this output would generally not break if you added another file or
two to the directory.

Tuples are immutable, meaning that once a tuple has been created, you can't
replace any of its elements with a new value.  Lists are mutable, meaning that
you can always change a list's elements.  Only immutable elements can be used as
dictionary keys, and hence only tuples and not lists can be used as keys.


How are lists implemented in CPython?
-------------------------------------

CPython's lists are really variable-length arrays, not Lisp-style linked lists.
The implementation uses a contiguous array of references to other objects, and
keeps a pointer to this array and the array's length in a list head structure.

This makes indexing a list ``a[i]`` an operation whose cost is independent of
the size of the list or the value of the index.

When items are appended or inserted, the array of references is resized.  Some
cleverness is applied to improve the performance of appending items repeatedly;
when the array must be grown, some extra space is allocated so the next few
times don't require an actual resize.


How are dictionaries implemented in CPython?
--------------------------------------------

CPython's dictionaries are implemented as resizable hash tables.  Compared to
B-trees, this gives better performance for lookup (the most common operation by
far) under most circumstances, and the implementation is simpler.

Dictionaries work by computing a hash code for each key stored in the dictionary
using the :func:`hash` built-in function.  The hash code varies widely depending
on the key; for example, "Python" hashes to -539294296 while "python", a string
that differs by a single bit, hashes to 1142331976.  The hash code is then used
to calculate a location in an internal array where the value will be stored.
Assuming that you're storing keys that all have different hash values, this
means that dictionaries take constant time -- O(1), in computer science notation
-- to retrieve a key.  It also means that no sorted order of the keys is
maintained, and traversing the array as the ``.keys()`` and ``.items()`` do will
output the dictionary's content in some arbitrary jumbled order.


Why must dictionary keys be immutable?
--------------------------------------

The hash table implementation of dictionaries uses a hash value calculated from
the key value to find the key.  If the key were a mutable object, its value
could change, and thus its hash could also change.  But since whoever changes
the key object can't tell that it was being used as a dictionary key, it can't
move the entry around in the dictionary.  Then, when you try to look up the same
object in the dictionary it won't be found because its hash value is different.
If you tried to look up the old value it wouldn't be found either, because the
value of the object found in that hash bin would be different.

If you want a dictionary indexed with a list, simply convert the list to a tuple
first; the function ``tuple(L)`` creates a tuple with the same entries as the
list ``L``.  Tuples are immutable and can therefore be used as dictionary keys.

Some unacceptable solutions that have been proposed:

- Hash lists by their address (object ID).  This doesn't work because if you
  construct a new list with the same value it won't be found; e.g.::

     mydict = {[1, 2]: '12'}
     print mydict[[1, 2]]

  would raise a KeyError exception because the id of the ``[1, 2]`` used in the
  second line differs from that in the first line.  In other words, dictionary
  keys should be compared using ``==``, not using :keyword:`is`.

- Make a copy when using a list as a key.  This doesn't work because the list,
  being a mutable object, could contain a reference to itself, and then the
  copying code would run into an infinite loop.

- Allow lists as keys but tell the user not to modify them.  This would allow a
  class of hard-to-track bugs in programs when you forgot or modified a list by
  accident. It also invalidates an important invariant of dictionaries: every
  value in ``d.keys()`` is usable as a key of the dictionary.

- Mark lists as read-only once they are used as a dictionary key.  The problem
  is that it's not just the top-level object that could change its value; you
  could use a tuple containing a list as a key.  Entering anything as a key into
  a dictionary would require marking all objects reachable from there as
  read-only -- and again, self-referential objects could cause an infinite loop.

There is a trick to get around this if you need to, but use it at your own risk:
You can wrap a mutable structure inside a class instance which has both a
:meth:`__eq__` and a :meth:`__hash__` method.  You must then make sure that the
hash value for all such wrapper objects that reside in a dictionary (or other
hash based structure), remain fixed while the object is in the dictionary (or
other structure). ::

   class ListWrapper:
       def __init__(self, the_list):
           self.the_list = the_list

       def __eq__(self, other):
           return self.the_list == other.the_list

       def __hash__(self):
           l = self.the_list
           result = 98767 - len(l)*555
           for i, el in enumerate(l):
               try:
                   result = result + (hash(el) % 9999999) * 1001 + i
               except Exception:
                   result = (result % 7777777) + i * 333
           return result

Note that the hash computation is complicated by the possibility that some
members of the list may be unhashable and also by the possibility of arithmetic
overflow.

Furthermore it must always be the case that if ``o1 == o2`` (ie ``o1.__eq__(o2)
is True``) then ``hash(o1) == hash(o2)`` (ie, ``o1.__hash__() == o2.__hash__()``),
regardless of whether the object is in a dictionary or not.  If you fail to meet
these restrictions dictionaries and other hash based structures will misbehave.

In the case of ListWrapper, whenever the wrapper object is in a dictionary the
wrapped list must not change to avoid anomalies.  Don't do this unless you are
prepared to think hard about the requirements and the consequences of not
meeting them correctly.  Consider yourself warned.


Why doesn't list.sort() return the sorted list?
-----------------------------------------------

In situations where performance matters, making a copy of the list just to sort
it would be wasteful. Therefore, :meth:`list.sort` sorts the list in place. In
order to remind you of that fact, it does not return the sorted list.  This way,
you won't be fooled into accidentally overwriting a list when you need a sorted
copy but also need to keep the unsorted version around.

In Python 2.4 a new built-in function -- :func:`sorted` -- has been added.
This function creates a new list from a provided iterable, sorts it and returns
it.  For example, here's how to iterate over the keys of a dictionary in sorted
order::

   for key in sorted(mydict):
       ...  # do whatever with mydict[key]...


How do you specify and enforce an interface spec in Python?
-----------------------------------------------------------

An interface specification for a module as provided by languages such as C++ and
Java describes the prototypes for the methods and functions of the module.  Many
feel that compile-time enforcement of interface specifications helps in the
construction of large programs.

Python 2.6 adds an :mod:`abc` module that lets you define Abstract Base Classes
(ABCs).  You can then use :func:`isinstance` and :func:`issubclass` to check
whether an instance or a class implements a particular ABC.  The
:mod:`collections` module defines a set of useful ABCs such as
:class:`~collections.Iterable`, :class:`~collections.Container`, and
:class:`~collections.MutableMapping`.

For Python, many of the advantages of interface specifications can be obtained
by an appropriate test discipline for components.  There is also a tool,
PyChecker, which can be used to find problems due to subclassing.

A good test suite for a module can both provide a regression test and serve as a
module interface specification and a set of examples.  Many Python modules can
be run as a script to provide a simple "self test."  Even modules which use
complex external interfaces can often be tested in isolation using trivial
"stub" emulations of the external interface.  The :mod:`doctest` and
:mod:`unittest` modules or third-party test frameworks can be used to construct
exhaustive test suites that exercise every line of code in a module.

An appropriate testing discipline can help build large complex applications in
Python as well as having interface specifications would.  In fact, it can be
better because an interface specification cannot test certain properties of a
program.  For example, the :meth:`append` method is expected to add new elements
to the end of some internal list; an interface specification cannot test that
your :meth:`append` implementation will actually do this correctly, but it's
trivial to check this property in a test suite.

Writing test suites is very helpful, and you might want to design your code with
an eye to making it easily tested.  One increasingly popular technique,
test-directed development, calls for writing parts of the test suite first,
before you write any of the actual code.  Of course Python allows you to be
sloppy and not write test cases at all.


Why is there no goto?
---------------------

You can use exceptions to provide a "structured goto" that even works across
function calls.  Many feel that exceptions can conveniently emulate all
reasonable uses of the "go" or "goto" constructs of C, Fortran, and other
languages.  For example::

   class label: pass  # declare a label

   try:
       ...
       if condition: raise label()  # goto label
       ...
   except label:  # where to goto
       pass
   ...

This doesn't allow you to jump into the middle of a loop, but that's usually
considered an abuse of goto anyway.  Use sparingly.


Why can't raw strings (r-strings) end with a backslash?
-------------------------------------------------------

More precisely, they can't end with an odd number of backslashes: the unpaired
backslash at the end escapes the closing quote character, leaving an
unterminated string.

Raw strings were designed to ease creating input for processors (chiefly regular
expression engines) that want to do their own backslash escape processing. Such
processors consider an unmatched trailing backslash to be an error anyway, so
raw strings disallow that.  In return, they allow you to pass on the string
quote character by escaping it with a backslash.  These rules work well when
r-strings are used for their intended purpose.

If you're trying to build Windows pathnames, note that all Windows system calls
accept forward slashes too::

   f = open("/mydir/file.txt")  # works fine!

If you're trying to build a pathname for a DOS command, try e.g. one of ::

   dir = r"\this\is\my\dos\dir" "\\"
   dir = r"\this\is\my\dos\dir\ "[:-1]
   dir = "\\this\\is\\my\\dos\\dir\\"


Why doesn't Python have a "with" statement for attribute assignments?
---------------------------------------------------------------------

Python has a 'with' statement that wraps the execution of a block, calling code
on the entrance and exit from the block.  Some language have a construct that
looks like this::

   with obj:
       a = 1               # equivalent to obj.a = 1
       total = total + 1   # obj.total = obj.total + 1

In Python, such a construct would be ambiguous.

Other languages, such as Object Pascal, Delphi, and C++, use static types, so
it's possible to know, in an unambiguous way, what member is being assigned
to. This is the main point of static typing -- the compiler *always* knows the
scope of every variable at compile time.

Python uses dynamic types. It is impossible to know in advance which attribute
will be referenced at runtime. Member attributes may be added or removed from
objects on the fly. This makes it impossible to know, from a simple reading,
what attribute is being referenced: a local one, a global one, or a member
attribute?

For instance, take the following incomplete snippet::

   def foo(a):
       with a:
           print x

The snippet assumes that "a" must have a member attribute called "x".  However,
there is nothing in Python that tells the interpreter this. What should happen
if "a" is, let us say, an integer?  If there is a global variable named "x",
will it be used inside the with block?  As you see, the dynamic nature of Python
makes such choices much harder.

The primary benefit of "with" and similar language features (reduction of code
volume) can, however, easily be achieved in Python by assignment.  Instead of::

   function(args).mydict[index][index].a = 21
   function(args).mydict[index][index].b = 42
   function(args).mydict[index][index].c = 63

write this::

   ref = function(args).mydict[index][index]
   ref.a = 21
   ref.b = 42
   ref.c = 63

This also has the side-effect of increasing execution speed because name
bindings are resolved at run-time in Python, and the second version only needs
to perform the resolution once.


Why are colons required for the if/while/def/class statements?
--------------------------------------------------------------

The colon is required primarily to enhance readability (one of the results of
the experimental ABC language).  Consider this::

   if a == b
       print a

versus ::

   if a == b:
       print a

Notice how the second one is slightly easier to read.  Notice further how a
colon sets off the example in this FAQ answer; it's a standard usage in English.

Another minor reason is that the colon makes it easier for editors with syntax
highlighting; they can look for colons to decide when indentation needs to be
increased instead of having to do a more elaborate parsing of the program text.


Why does Python allow commas at the end of lists and tuples?
------------------------------------------------------------

Python lets you add a trailing comma at the end of lists, tuples, and
dictionaries::

   [1, 2, 3,]
   ('a', 'b', 'c',)
   d = {
       "A": [1, 5],
       "B": [6, 7],  # last trailing comma is optional but good style
   }


There are several reasons to allow this.

When you have a literal value for a list, tuple, or dictionary spread across
multiple lines, it's easier to add more elements because you don't have to
remember to add a comma to the previous line.  The lines can also be reordered
without creating a syntax error.

Accidentally omitting the comma can lead to errors that are hard to diagnose.
For example::

       x = [
         "fee",
         "fie"
         "foo",
         "fum"
       ]

This list looks like it has four elements, but it actually contains three:
"fee", "fiefoo" and "fum".  Always adding the comma avoids this source of error.

Allowing the trailing comma may also make programmatic code generation easier.
PK	%�\{ۻ#�F�F#html/_sources/faq/extending.rst.txtnu�[���=======================
Extending/Embedding FAQ
=======================

.. only:: html

   .. contents::

.. highlight:: c


Can I create my own functions in C?
-----------------------------------

Yes, you can create built-in modules containing functions, variables, exceptions
and even new types in C.  This is explained in the document
:ref:`extending-index`.

Most intermediate or advanced Python books will also cover this topic.


Can I create my own functions in C++?
-------------------------------------

Yes, using the C compatibility features found in C++.  Place ``extern "C" {
... }`` around the Python include files and put ``extern "C"`` before each
function that is going to be called by the Python interpreter.  Global or static
C++ objects with constructors are probably not a good idea.


.. _c-wrapper-software:

Writing C is hard; are there any alternatives?
----------------------------------------------

There are a number of alternatives to writing your own C extensions, depending
on what you're trying to do.

.. XXX make sure these all work; mention Cython

If you need more speed, `Psyco <http://psyco.sourceforge.net/>`_ generates x86
assembly code from Python bytecode.  You can use Psyco to compile the most
time-critical functions in your code, and gain a significant improvement with
very little effort, as long as you're running on a machine with an
x86-compatible processor.

`Cython <http://cython.org>`_ and its relative `Pyrex
<https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/>`_ are compilers
that accept a slightly modified form of Python and generate the corresponding
C code.  Pyrex makes it possible to write an extension without having to learn
Python's C API.

If you need to interface to some C or C++ library for which no Python extension
currently exists, you can try wrapping the library's data types and functions
with a tool such as `SWIG <http://www.swig.org>`_.  `SIP
<https://riverbankcomputing.com/software/sip/intro>`__, `CXX
<http://cxx.sourceforge.net/>`_ `Boost
<http://www.boost.org/libs/python/doc/index.html>`_, or `Weave
<https://github.com/scipy/weave>`_ are also
alternatives for wrapping C++ libraries.


How can I execute arbitrary Python statements from C?
-----------------------------------------------------

The highest-level function to do this is :c:func:`PyRun_SimpleString` which takes
a single string argument to be executed in the context of the module
``__main__`` and returns 0 for success and -1 when an exception occurred
(including ``SyntaxError``).  If you want more control, use
:c:func:`PyRun_String`; see the source for :c:func:`PyRun_SimpleString` in
``Python/pythonrun.c``.


How can I evaluate an arbitrary Python expression from C?
---------------------------------------------------------

Call the function :c:func:`PyRun_String` from the previous question with the
start symbol :c:data:`Py_eval_input`; it parses an expression, evaluates it and
returns its value.


How do I extract C values from a Python object?
-----------------------------------------------

That depends on the object's type.  If it's a tuple, :c:func:`PyTuple_Size`
returns its length and :c:func:`PyTuple_GetItem` returns the item at a specified
index.  Lists have similar functions, :c:func:`PyListSize` and
:c:func:`PyList_GetItem`.

For strings, :c:func:`PyString_Size` returns its length and
:c:func:`PyString_AsString` a pointer to its value.  Note that Python strings may
contain null bytes so C's :c:func:`strlen` should not be used.

To test the type of an object, first make sure it isn't *NULL*, and then use
:c:func:`PyString_Check`, :c:func:`PyTuple_Check`, :c:func:`PyList_Check`, etc.

There is also a high-level API to Python objects which is provided by the
so-called 'abstract' interface -- read ``Include/abstract.h`` for further
details.  It allows interfacing with any kind of Python sequence using calls
like :c:func:`PySequence_Length`, :c:func:`PySequence_GetItem`, etc.)  as well as
many other useful protocols.


How do I use Py_BuildValue() to create a tuple of arbitrary length?
-------------------------------------------------------------------

You can't.  Use ``t = PyTuple_New(n)`` instead, and fill it with objects using
``PyTuple_SetItem(t, i, o)`` -- note that this "eats" a reference count of
``o``, so you have to :c:func:`Py_INCREF` it.  Lists have similar functions
``PyList_New(n)`` and ``PyList_SetItem(l, i, o)``.  Note that you *must* set all
the tuple items to some value before you pass the tuple to Python code --
``PyTuple_New(n)`` initializes them to NULL, which isn't a valid Python value.


How do I call an object's method from C?
----------------------------------------

The :c:func:`PyObject_CallMethod` function can be used to call an arbitrary
method of an object.  The parameters are the object, the name of the method to
call, a format string like that used with :c:func:`Py_BuildValue`, and the
argument values::

   PyObject *
   PyObject_CallMethod(PyObject *object, char *method_name,
                       char *arg_format, ...);

This works for any object that has methods -- whether built-in or user-defined.
You are responsible for eventually :c:func:`Py_DECREF`\ 'ing the return value.

To call, e.g., a file object's "seek" method with arguments 10, 0 (assuming the
file object pointer is "f")::

   res = PyObject_CallMethod(f, "seek", "(ii)", 10, 0);
   if (res == NULL) {
           ... an exception occurred ...
   }
   else {
           Py_DECREF(res);
   }

Note that since :c:func:`PyObject_CallObject` *always* wants a tuple for the
argument list, to call a function without arguments, pass "()" for the format,
and to call a function with one argument, surround the argument in parentheses,
e.g. "(i)".


How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?
----------------------------------------------------------------------------------------

In Python code, define an object that supports the ``write()`` method.  Assign
this object to :data:`sys.stdout` and :data:`sys.stderr`.  Call print_error, or
just allow the standard traceback mechanism to work. Then, the output will go
wherever your ``write()`` method sends it.

The easiest way to do this is to use the StringIO class in the standard library.

Sample code and use for catching stdout:

.. code-block:: pycon

   >>> class StdoutCatcher:
   ...     def __init__(self):
   ...         self.data = ''
   ...     def write(self, stuff):
   ...         self.data = self.data + stuff
   ...
   >>> import sys
   >>> sys.stdout = StdoutCatcher()
   >>> print 'foo'
   >>> print 'hello world!'
   >>> sys.stderr.write(sys.stdout.data)
   foo
   hello world!


How do I access a module written in Python from C?
--------------------------------------------------

You can get a pointer to the module object as follows::

   module = PyImport_ImportModule("<modulename>");

If the module hasn't been imported yet (i.e. it is not yet present in
:data:`sys.modules`), this initializes the module; otherwise it simply returns
the value of ``sys.modules["<modulename>"]``.  Note that it doesn't enter the
module into any namespace -- it only ensures it has been initialized and is
stored in :data:`sys.modules`.

You can then access the module's attributes (i.e. any name defined in the
module) as follows::

   attr = PyObject_GetAttrString(module, "<attrname>");

Calling :c:func:`PyObject_SetAttrString` to assign to variables in the module
also works.


How do I interface to C++ objects from Python?
----------------------------------------------

Depending on your requirements, there are many approaches.  To do this manually,
begin by reading :ref:`the "Extending and Embedding" document
<extending-index>`.  Realize that for the Python run-time system, there isn't a
whole lot of difference between C and C++ -- so the strategy of building a new
Python type around a C structure (pointer) type will also work for C++ objects.

For C++ libraries, see :ref:`c-wrapper-software`.


I added a module using the Setup file and the make fails; why?
--------------------------------------------------------------

Setup must end in a newline, if there is no newline there, the build process
fails.  (Fixing this requires some ugly shell script hackery, and this bug is so
minor that it doesn't seem worth the effort.)


How do I debug an extension?
----------------------------

When using GDB with dynamically loaded extensions, you can't set a breakpoint in
your extension until your extension is loaded.

In your ``.gdbinit`` file (or interactively), add the command:

.. code-block:: none

   br _PyImport_LoadDynamicModule

Then, when you run GDB:

.. code-block:: shell-session

   $ gdb /local/bin/python
   gdb) run myscript.py
   gdb) continue # repeat until your extension is loaded
   gdb) finish   # so that your extension is loaded
   gdb) br myfunction.c:50
   gdb) continue

I want to compile a Python module on my Linux system, but some files are missing. Why?
--------------------------------------------------------------------------------------

Most packaged versions of Python don't include the
:file:`/usr/lib/python2.{x}/config/` directory, which contains various files
required for compiling Python extensions.

For Red Hat, install the python-devel RPM to get the necessary files.

For Debian, run ``apt-get install python-dev``.


What does "SystemError: _PyImport_FixupExtension: module yourmodule not loaded" mean?
-------------------------------------------------------------------------------------

This means that you have created an extension module named "yourmodule", but
your module init function does not initialize with that name.

Every module init function will have a line similar to::

   module = Py_InitModule("yourmodule", yourmodule_functions);

If the string passed to this function is not the same name as your extension
module, the :exc:`SystemError` exception will be raised.


How do I tell "incomplete input" from "invalid input"?
------------------------------------------------------

Sometimes you want to emulate the Python interactive interpreter's behavior,
where it gives you a continuation prompt when the input is incomplete (e.g. you
typed the start of an "if" statement or you didn't close your parentheses or
triple string quotes), but it gives you a syntax error message immediately when
the input is invalid.

In Python you can use the :mod:`codeop` module, which approximates the parser's
behavior sufficiently.  IDLE uses this, for example.

The easiest way to do it in C is to call :c:func:`PyRun_InteractiveLoop` (perhaps
in a separate thread) and let the Python interpreter handle the input for
you. You can also set the :c:func:`PyOS_ReadlineFunctionPointer` to point at your
custom input function. See ``Modules/readline.c`` and ``Parser/myreadline.c``
for more hints.

However sometimes you have to run the embedded Python interpreter in the same
thread as your rest application and you can't allow the
:c:func:`PyRun_InteractiveLoop` to stop while waiting for user input.  The one
solution then is to call :c:func:`PyParser_ParseString` and test for ``e.error``
equal to ``E_EOF``, which means the input is incomplete.  Here's a sample code
fragment, untested, inspired by code from Alex Farber::

   #include <Python.h>
   #include <node.h>
   #include <errcode.h>
   #include <grammar.h>
   #include <parsetok.h>
   #include <compile.h>

   int testcomplete(char *code)
     /* code should end in \n */
     /* return -1 for error, 0 for incomplete, 1 for complete */
   {
     node *n;
     perrdetail e;

     n = PyParser_ParseString(code, &_PyParser_Grammar,
                              Py_file_input, &e);
     if (n == NULL) {
       if (e.error == E_EOF)
         return 0;
       return -1;
     }

     PyNode_Free(n);
     return 1;
   }

Another solution is trying to compile the received string with
:c:func:`Py_CompileString`. If it compiles without errors, try to execute the
returned code object by calling :c:func:`PyEval_EvalCode`. Otherwise save the
input for later. If the compilation fails, find out if it's an error or just
more input is required - by extracting the message string from the exception
tuple and comparing it to the string "unexpected EOF while parsing".  Here is a
complete example using the GNU readline library (you may want to ignore
**SIGINT** while calling readline())::

   #include <stdio.h>
   #include <readline.h>

   #include <Python.h>
   #include <object.h>
   #include <compile.h>
   #include <eval.h>

   int main (int argc, char* argv[])
   {
     int i, j, done = 0;                          /* lengths of line, code */
     char ps1[] = ">>> ";
     char ps2[] = "... ";
     char *prompt = ps1;
     char *msg, *line, *code = NULL;
     PyObject *src, *glb, *loc;
     PyObject *exc, *val, *trb, *obj, *dum;

     Py_Initialize ();
     loc = PyDict_New ();
     glb = PyDict_New ();
     PyDict_SetItemString (glb, "__builtins__", PyEval_GetBuiltins ());

     while (!done)
     {
       line = readline (prompt);

       if (NULL == line)                          /* Ctrl-D pressed */
       {
         done = 1;
       }
       else
       {
         i = strlen (line);

         if (i > 0)
           add_history (line);                    /* save non-empty lines */

         if (NULL == code)                        /* nothing in code yet */
           j = 0;
         else
           j = strlen (code);

         code = realloc (code, i + j + 2);
         if (NULL == code)                        /* out of memory */
           exit (1);

         if (0 == j)                              /* code was empty, so */
           code[0] = '\0';                        /* keep strncat happy */

         strncat (code, line, i);                 /* append line to code */
         code[i + j] = '\n';                      /* append '\n' to code */
         code[i + j + 1] = '\0';

         src = Py_CompileString (code, "<stdin>", Py_single_input);

         if (NULL != src)                         /* compiled just fine - */
         {
           if (ps1  == prompt ||                  /* ">>> " or */
               '\n' == code[i + j - 1])           /* "... " and double '\n' */
           {                                               /* so execute it */
             dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
             Py_XDECREF (dum);
             Py_XDECREF (src);
             free (code);
             code = NULL;
             if (PyErr_Occurred ())
               PyErr_Print ();
             prompt = ps1;
           }
         }                                        /* syntax error or E_EOF? */
         else if (PyErr_ExceptionMatches (PyExc_SyntaxError))
         {
           PyErr_Fetch (&exc, &val, &trb);        /* clears exception! */

           if (PyArg_ParseTuple (val, "sO", &msg, &obj) &&
               !strcmp (msg, "unexpected EOF while parsing")) /* E_EOF */
           {
             Py_XDECREF (exc);
             Py_XDECREF (val);
             Py_XDECREF (trb);
             prompt = ps2;
           }
           else                                   /* some other syntax error */
           {
             PyErr_Restore (exc, val, trb);
             PyErr_Print ();
             free (code);
             code = NULL;
             prompt = ps1;
           }
         }
         else                                     /* some non-syntax error */
         {
           PyErr_Print ();
           free (code);
           code = NULL;
           prompt = ps1;
         }

         free (line);
       }
     }

     Py_XDECREF(glb);
     Py_XDECREF(loc);
     Py_Finalize();
     exit(0);
   }


How do I find undefined g++ symbols __builtin_new or __pure_virtual?
--------------------------------------------------------------------

To dynamically load g++ extension modules, you must recompile Python, relink it
using g++ (change LINKCC in the Python Modules Makefile), and link your
extension module using g++ (e.g., ``g++ -shared -o mymodule.so mymodule.o``).


Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?
----------------------------------------------------------------------------------------------------------------

Yes, you can inherit from built-in classes such as :class:`int`, :class:`list`,
:class:`dict`, etc.

The Boost Python Library (BPL, http://www.boost.org/libs/python/doc/index.html)
provides a way of doing this from C++ (i.e. you can inherit from an extension
class written in C++ using the BPL).


When importing module X, why do I get "undefined symbol: PyUnicodeUCS2*"?
-------------------------------------------------------------------------

You are using a version of Python that uses a 4-byte representation for Unicode
characters, but some C extension module you are importing was compiled using a
Python that uses a 2-byte representation for Unicode characters (the default).

If instead the name of the undefined symbol starts with ``PyUnicodeUCS4``, the
problem is the reverse: Python was built using 2-byte Unicode characters, and
the extension module was compiled using a Python with 4-byte Unicode characters.

This can easily occur when using pre-built extension packages.  RedHat Linux
7.x, in particular, provided a "python2" binary that is compiled with 4-byte
Unicode.  This only causes the link failure if the extension uses any of the
``PyUnicode_*()`` functions.  It is also a problem if an extension uses any of
the Unicode-related format specifiers for :c:func:`Py_BuildValue` (or similar) or
parameter specifications for :c:func:`PyArg_ParseTuple`.

You can check the size of the Unicode character a Python interpreter is using by
checking the value of sys.maxunicode:

.. code-block:: pycon

   >>> import sys
   >>> if sys.maxunicode > 65535:
   ...     print 'UCS4 build'
   ... else:
   ...     print 'UCS2 build'

The only way to solve this problem is to use extension modules compiled with a
Python binary built using the same size for Unicode characters.



PK	%�\�T=�GVGV!html/_sources/faq/general.rst.txtnu�[���:tocdepth: 2

==================
General Python FAQ
==================

.. only:: html

   .. contents::


General Information
===================

What is Python?
---------------

Python is an interpreted, interactive, object-oriented programming language.  It
incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.  Python combines remarkable power with very clear syntax.
It has interfaces to many system calls and libraries, as well as to various
window systems, and is extensible in C or C++.  It is also usable as an
extension language for applications that need a programmable interface.
Finally, Python is portable: it runs on many Unix variants, on the Mac, and on
PCs under MS-DOS, Windows, Windows NT, and OS/2.

To find out more, start with :ref:`tutorial-index`.  The `Beginner's Guide to
Python <https://wiki.python.org/moin/BeginnersGuide>`_ links to other
introductory tutorials and resources for learning Python.


What is the Python Software Foundation?
---------------------------------------

The Python Software Foundation is an independent non-profit organization that
holds the copyright on Python versions 2.1 and newer.  The PSF's mission is to
advance open source technology related to the Python programming language and to
publicize the use of Python.  The PSF's home page is at
https://www.python.org/psf/.

Donations to the PSF are tax-exempt in the US.  If you use Python and find it
helpful, please contribute via `the PSF donation page
<https://www.python.org/psf/donations/>`_.


Are there copyright restrictions on the use of Python?
------------------------------------------------------

You can do anything you want with the source, as long as you leave the
copyrights in and display those copyrights in any documentation about Python
that you produce.  If you honor the copyright rules, it's OK to use Python for
commercial use, to sell copies of Python in source or binary form (modified or
unmodified), or to sell products that incorporate Python in some form.  We would
still like to know about all commercial use of Python, of course.

See `the PSF license page <https://www.python.org/psf/license/>`_ to find further
explanations and a link to the full text of the license.

The Python logo is trademarked, and in certain cases permission is required to
use it.  Consult `the Trademark Usage Policy
<https://www.python.org/psf/trademarks/>`__ for more information.


Why was Python created in the first place?
------------------------------------------

Here's a *very* brief summary of what started it all, written by Guido van
Rossum:

   I had extensive experience with implementing an interpreted language in the
   ABC group at CWI, and from working with this group I had learned a lot about
   language design.  This is the origin of many Python features, including the
   use of indentation for statement grouping and the inclusion of
   very-high-level data types (although the details are all different in
   Python).

   I had a number of gripes about the ABC language, but also liked many of its
   features.  It was impossible to extend the ABC language (or its
   implementation) to remedy my complaints -- in fact its lack of extensibility
   was one of its biggest problems.  I had some experience with using Modula-2+
   and talked with the designers of Modula-3 and read the Modula-3 report.
   Modula-3 is the origin of the syntax and semantics used for exceptions, and
   some other Python features.

   I was working in the Amoeba distributed operating system group at CWI.  We
   needed a better way to do system administration than by writing either C
   programs or Bourne shell scripts, since Amoeba had its own system call
   interface which wasn't easily accessible from the Bourne shell.  My
   experience with error handling in Amoeba made me acutely aware of the
   importance of exceptions as a programming language feature.

   It occurred to me that a scripting language with a syntax like ABC but with
   access to the Amoeba system calls would fill the need.  I realized that it
   would be foolish to write an Amoeba-specific language, so I decided that I
   needed a language that was generally extensible.

   During the 1989 Christmas holidays, I had a lot of time on my hand, so I
   decided to give it a try.  During the next year, while still mostly working
   on it in my own time, Python was used in the Amoeba project with increasing
   success, and the feedback from colleagues made me add many early
   improvements.

   In February 1991, after just over a year of development, I decided to post to
   USENET.  The rest is in the ``Misc/HISTORY`` file.


What is Python good for?
------------------------

Python is a high-level general-purpose programming language that can be applied
to many different classes of problems.

The language comes with a large standard library that covers areas such as
string processing (regular expressions, Unicode, calculating differences between
files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI
programming), software engineering (unit testing, logging, profiling, parsing
Python code), and operating system interfaces (system calls, filesystems, TCP/IP
sockets).  Look at the table of contents for :ref:`library-index` to get an idea
of what's available.  A wide variety of third-party extensions are also
available.  Consult `the Python Package Index <https://pypi.org>`_ to
find packages of interest to you.


How does the Python version numbering scheme work?
--------------------------------------------------

Python versions are numbered A.B.C or A.B.  A is the major version number -- it
is only incremented for really major changes in the language.  B is the minor
version number, incremented for less earth-shattering changes.  C is the
micro-level -- it is incremented for each bugfix release.  See :pep:`6` for more
information about bugfix releases.

Not all releases are bugfix releases.  In the run-up to a new major release, a
series of development releases are made, denoted as alpha, beta, or release
candidate.  Alphas are early releases in which interfaces aren't yet finalized;
it's not unexpected to see an interface change between two alpha releases.
Betas are more stable, preserving existing interfaces but possibly adding new
modules, and release candidates are frozen, making no changes except as needed
to fix critical bugs.

Alpha, beta and release candidate versions have an additional suffix.  The
suffix for an alpha version is "aN" for some small number N, the suffix for a
beta version is "bN" for some small number N, and the suffix for a release
candidate version is "cN" for some small number N.  In other words, all versions
labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled
2.0cN, and *those* precede 2.0.

You may also find version numbers with a "+" suffix, e.g. "2.2+".  These are
unreleased versions, built directly from the CPython development repository.  In
practice, after a final minor release is made, the version is incremented to the
next minor version, which becomes the "a0" version, e.g. "2.4a0".

See also the documentation for :data:`sys.version`, :data:`sys.hexversion`, and
:data:`sys.version_info`.


How do I obtain a copy of the Python source?
--------------------------------------------

The latest Python source distribution is always available from python.org, at
https://www.python.org/downloads/.  The latest development sources can be obtained
at https://github.com/python/cpython/.

The source distribution is a gzipped tar file containing the complete C source,
Sphinx-formatted documentation, Python library modules, example programs, and
several useful pieces of freely distributable software.  The source will compile
and run out of the box on most UNIX platforms.

Consult the `Getting Started section of the Python Developer's Guide
<https://docs.python.org/devguide/setup.html>`__ for more
information on getting the source code and compiling it.


How do I get documentation on Python?
-------------------------------------

.. XXX mention py3k

The standard documentation for the current stable version of Python is available
at https://docs.python.org/3/.  PDF, plain text, and downloadable HTML versions are
also available at https://docs.python.org/3/download.html.

The documentation is written in reStructuredText and processed by `the Sphinx
documentation tool <http://sphinx-doc.org/>`__.  The reStructuredText source for
the documentation is part of the Python source distribution.


I've never programmed before. Is there a Python tutorial?
---------------------------------------------------------

There are numerous tutorials and books available.  The standard documentation
includes :ref:`tutorial-index`.

Consult `the Beginner's Guide <https://wiki.python.org/moin/BeginnersGuide>`_ to
find information for beginning Python programmers, including lists of tutorials.


Is there a newsgroup or mailing list devoted to Python?
-------------------------------------------------------

There is a newsgroup, :newsgroup:`comp.lang.python`, and a mailing list,
`python-list <https://mail.python.org/mailman/listinfo/python-list>`_.  The
newsgroup and mailing list are gatewayed into each other -- if you can read news
it's unnecessary to subscribe to the mailing list.
:newsgroup:`comp.lang.python` is high-traffic, receiving hundreds of postings
every day, and Usenet readers are often more able to cope with this volume.

Announcements of new software releases and events can be found in
comp.lang.python.announce, a low-traffic moderated list that receives about five
postings per day.  It's available as `the python-announce mailing list
<https://mail.python.org/mailman/listinfo/python-announce-list>`_.

More info about other mailing lists and newsgroups
can be found at https://www.python.org/community/lists/.


How do I get a beta test version of Python?
-------------------------------------------

Alpha and beta releases are available from https://www.python.org/downloads/.  All
releases are announced on the comp.lang.python and comp.lang.python.announce
newsgroups and on the Python home page at https://www.python.org/; an RSS feed of
news is available.

You can also access the development version of Python through Git.  See
`The Python Developer's Guide <https://docs.python.org/devguide/>`_ for details.


How do I submit bug reports and patches for Python?
---------------------------------------------------

To report a bug or submit a patch, please use the Roundup installation at
https://bugs.python.org/.

You must have a Roundup account to report bugs; this makes it possible for us to
contact you if we have follow-up questions.  It will also enable Roundup to send
you updates as we act on your bug. If you had previously used SourceForge to
report bugs to Python, you can obtain your Roundup password through Roundup's
`password reset procedure <https://bugs.python.org/user?@template=forgotten>`_.

For more information on how Python is developed, consult `the Python Developer's
Guide <https://docs.python.org/devguide/>`_.


Are there any published articles about Python that I can reference?
-------------------------------------------------------------------

It's probably best to cite your favorite book about Python.

The very first article about Python was written in 1991 and is now quite
outdated.

    Guido van Rossum and Jelke de Boer, "Interactively Testing Remote Servers
    Using the Python Programming Language", CWI Quarterly, Volume 4, Issue 4
    (December 1991), Amsterdam, pp 283--303.


Are there any books on Python?
------------------------------

Yes, there are many, and more are being published.  See the python.org wiki at
https://wiki.python.org/moin/PythonBooks for a list.

You can also search online bookstores for "Python" and filter out the Monty
Python references; or perhaps search for "Python" and "language".


Where in the world is www.python.org located?
---------------------------------------------

The Python project's infrastructure is located all over the world.
`www.python.org <https://www.python.org>`_ is graciously hosted by `Rackspace
<https://www.rackspace.com>`_, with CDN caching provided by `Fastly
<https://www.fastly.com>`_.  `Upfront Systems
<http://www.upfrontsystems.co.za/>`_ hosts `bugs.python.org
<https://bugs.python.org>`_.  Many other Python services like `the Wiki
<https://wiki.python.org>`_ are hosted by `Oregon State
University Open Source Lab <https://osuosl.org>`_.


Why is it called Python?
------------------------

When he began implementing Python, Guido van Rossum was also reading the
published scripts from `"Monty Python's Flying Circus"
<https://en.wikipedia.org/wiki/Monty_Python>`__, a BBC comedy series from the 1970s.  Van Rossum
thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python.


Do I have to like "Monty Python's Flying Circus"?
-------------------------------------------------

No, but it helps.  :)


Python in the real world
========================

How stable is Python?
---------------------

Very stable.  New, stable releases have been coming out roughly every 6 to 18
months since 1991, and this seems likely to continue.  Currently there are
usually around 18 months between major releases.

The developers issue "bugfix" releases of older versions, so the stability of
existing releases gradually improves.  Bugfix releases, indicated by a third
component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability;
only fixes for known problems are included in a bugfix release, and it's
guaranteed that interfaces will remain the same throughout a series of bugfix
releases.

The latest stable releases can always be found on the `Python download page
<https://www.python.org/downloads/>`_.  There are two production-ready version
of Python: 2.x and 3.x, but the recommended one at this times is Python 3.x.
Although Python 2.x is still widely used, `it will not be
maintained after January 1, 2020 <https://www.python.org/dev/peps/pep-0373/>`_.
Python 2.x was known for having more third-party libraries available, however,
by the time of this writing, most of the widely used libraries support Python 3.x,
and some are even dropping the Python 2.x support.


How many people are using Python?
---------------------------------

There are probably tens of thousands of users, though it's difficult to obtain
an exact count.

Python is available for free download, so there are no sales figures, and it's
available from many different sites and packaged with many Linux distributions,
so download statistics don't tell the whole story either.

The comp.lang.python newsgroup is very active, but not all Python users post to
the group or even read it.


Have any significant projects been done in Python?
--------------------------------------------------

See https://www.python.org/about/success for a list of projects that use Python.
Consulting the proceedings for `past Python conferences
<https://www.python.org/community/workshops/>`_ will reveal contributions from many
different companies and organizations.

High-profile Python projects include `the Mailman mailing list manager
<http://www.list.org>`_ and `the Zope application server
<http://www.zope.org>`_.  Several Linux distributions, most notably `Red Hat
<https://www.redhat.com>`_, have written part or all of their installer and
system administration software in Python.  Companies that use Python internally
include Google, Yahoo, and Lucasfilm Ltd.


What new developments are expected for Python in the future?
------------------------------------------------------------

See https://www.python.org/dev/peps/ for the Python Enhancement Proposals
(PEPs). PEPs are design documents describing a suggested new feature for Python,
providing a concise technical specification and a rationale.  Look for a PEP
titled "Python X.Y Release Schedule", where X.Y is a version that hasn't been
publicly released yet.

New development is discussed on `the python-dev mailing list
<https://mail.python.org/mailman/listinfo/python-dev/>`_.


Is it reasonable to propose incompatible changes to Python?
-----------------------------------------------------------

In general, no.  There are already millions of lines of Python code around the
world, so any change in the language that invalidates more than a very small
fraction of existing programs has to be frowned upon.  Even if you can provide a
conversion program, there's still the problem of updating all documentation;
many books have been written about Python, and we don't want to invalidate them
all at a single stroke.

Providing a gradual upgrade path is necessary if a feature has to be changed.
:pep:`5` describes the procedure followed for introducing backward-incompatible
changes while minimizing disruption for users.


Is Python a good language for beginning programmers?
----------------------------------------------------

Yes.

It is still common to start students with a procedural and statically typed
language such as Pascal, C, or a subset of C++ or Java.  Students may be better
served by learning Python as their first language.  Python has a very simple and
consistent syntax and a large standard library and, most importantly, using
Python in a beginning programming course lets students concentrate on important
programming skills such as problem decomposition and data type design.  With
Python, students can be quickly introduced to basic concepts such as loops and
procedures.  They can probably even work with user-defined objects in their very
first course.

For a student who has never programmed before, using a statically typed language
seems unnatural.  It presents additional complexity that the student must master
and slows the pace of the course.  The students are trying to learn to think
like a computer, decompose problems, design consistent interfaces, and
encapsulate data.  While learning to use a statically typed language is
important in the long term, it is not necessarily the best topic to address in
the students' first programming course.

Many other aspects of Python make it a good first language.  Like Java, Python
has a large standard library so that students can be assigned programming
projects very early in the course that *do* something.  Assignments aren't
restricted to the standard four-function calculator and check balancing
programs.  By using the standard library, students can gain the satisfaction of
working on realistic applications as they learn the fundamentals of programming.
Using the standard library also teaches students about code reuse.  Third-party
modules such as PyGame are also helpful in extending the students' reach.

Python's interactive interpreter enables students to test language features
while they're programming.  They can keep a window with the interpreter running
while they enter their program's source in another window.  If they can't
remember the methods for a list, they can do something like this::

   >>> L = []
   >>> dir(L) # doctest: +NORMALIZE_WHITESPACE
   ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
   '__delslice__', '__doc__', '__eq__', '__format__', '__ge__',
   '__getattribute__', '__getitem__', '__getslice__', '__gt__',
   '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__',
   '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
   '__reduce_ex__', '__repr__', '__reversed__', '__rmul__',
   '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__',
   '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert',
   'pop', 'remove', 'reverse', 'sort']
   >>> help(L.append)
   Help on built-in function append:
   <BLANKLINE>
   append(...)
       L.append(object) -- append object to end
   <BLANKLINE>
   >>> L.append(1)
   >>> L
   [1]

With the interpreter, documentation is never far from the student as he's
programming.

There are also good IDEs for Python.  IDLE is a cross-platform IDE for Python
that is written in Python using Tkinter.  PythonWin is a Windows-specific IDE.
Emacs users will be happy to know that there is a very good Python mode for
Emacs.  All of these programming environments provide syntax highlighting,
auto-indenting, and access to the interactive interpreter while coding.  Consult
`the Python wiki <https://wiki.python.org/moin/PythonEditors>`_ for a full list
of Python editing environments.

If you want to discuss Python's use in education, you may be interested in
joining `the edu-sig mailing list
<https://www.python.org/community/sigs/current/edu-sig>`_.


Upgrading Python
================

What is this bsddb185 module my application keeps complaining about?
--------------------------------------------------------------------

.. XXX remove this question?

Starting with Python2.3, the distribution includes the `PyBSDDB package
<http://pybsddb.sf.net/>` as a replacement for the old bsddb module.  It
includes functions which provide backward compatibility at the API level, but
requires a newer version of the underlying `Berkeley DB
<http://www.sleepycat.com>`_ library.  Files created with the older bsddb module
can't be opened directly using the new module.

Using your old version of Python and a pair of scripts which are part of Python
2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can
convert your old database files to the new format.  Using your old Python
version, run the db2pickle.py script to convert it to a pickle, e.g.::

   python2.2 <pathto>/db2pickley.py database.db database.pck

Rename your database file::

   mv database.db olddatabase.db

Now convert the pickle file to a new format database::

   python <pathto>/pickle2db.py database.db database.pck

The precise commands you use will vary depending on the particulars of your
installation.  For full details about operation of these two scripts check the
doc string at the start of each one.
PK	%�\�mi��html/_sources/faq/gui.rst.txtnu�[���:tocdepth: 2

==========================
Graphic User Interface FAQ
==========================

.. only:: html

   .. contents::

What platform-independent GUI toolkits exist for Python?
========================================================

Depending on what platform(s) you are aiming at, there are several.

.. XXX check links

Tkinter
-------

Standard builds of Python include an object-oriented interface to the Tcl/Tk
widget set, called Tkinter.  This is probably the easiest to install and use.
For more info about Tk, including pointers to the source, see the Tcl/Tk home
page at https://www.tcl.tk.  Tcl/Tk is fully portable to the Mac OS X, Windows,
and Unix platforms.

wxWidgets
---------

wxWidgets (https://www.wxwidgets.org) is a free, portable GUI class
library written in C++ that provides a native look and feel on a
number of platforms, with Windows, Mac OS X, GTK, X11, all listed as
current stable targets.  Language bindings are available for a number
of languages including Python, Perl, Ruby, etc.

wxPython (http://www.wxpython.org) is the Python binding for
wxwidgets.  While it often lags slightly behind the official wxWidgets
releases, it also offers a number of features via pure Python
extensions that are not available in other language bindings.  There
is an active wxPython user and developer community.

Both wxWidgets and wxPython are free, open source, software with
permissive licences that allow their use in commercial products as
well as in freeware or shareware.


Qt
---

There are bindings available for the Qt toolkit (using either `PyQt
<https://riverbankcomputing.com/software/pyqt/intro>`_ or `PySide
<https://wiki.qt.io/PySide>`_) and for KDE (`PyKDE4 <https://techbase.kde.org/Languages/Python/Using_PyKDE_4>`__).
PyQt is currently more mature than PySide, but you must buy a PyQt license from
`Riverbank Computing <https://www.riverbankcomputing.com/commercial/license-faq>`_
if you want to write proprietary applications.  PySide is free for all applications.

Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses
are available from `The Qt Company <https://www.qt.io/licensing/>`_.

Gtk+
----

PyGtk bindings for the `Gtk+ toolkit <http://www.gtk.org>`_ have been
implemented by James Henstridge; see <http://www.pygtk.org>.

FLTK
----

Python bindings for `the FLTK toolkit <http://www.fltk.org>`_, a simple yet
powerful and mature cross-platform windowing system, are available from `the
PyFLTK project <http://pyfltk.sourceforge.net>`_.

OpenGL
------

For OpenGL bindings, see `PyOpenGL <http://pyopengl.sourceforge.net>`_.


What platform-specific GUI toolkits exist for Python?
========================================================

By installing the `PyObjc Objective-C bridge
<https://pythonhosted.org/pyobjc/>`_, Python programs can use Mac OS X's
Cocoa libraries.

:ref:`Pythonwin <windows-faq>` by Mark Hammond includes an interface to the
Microsoft Foundation Classes and a Python programming environment
that's written mostly in Python using the MFC classes.


Tkinter questions
=================

How do I freeze Tkinter applications?
-------------------------------------

Freeze is a tool to create stand-alone applications.  When freezing Tkinter
applications, the applications will not be truly stand-alone, as the application
will still need the Tcl and Tk libraries.

One solution is to ship the application with the Tcl and Tk libraries, and point
to them at run-time using the :envvar:`TCL_LIBRARY` and :envvar:`TK_LIBRARY`
environment variables.

To get truly stand-alone applications, the Tcl scripts that form the library
have to be integrated into the application as well. One tool supporting that is
SAM (stand-alone modules), which is part of the Tix distribution
(http://tix.sourceforge.net/).

Build Tix with SAM enabled, perform the appropriate call to
:c:func:`Tclsam_init`, etc. inside Python's
:file:`Modules/tkappinit.c`, and link with libtclsam and libtksam (you
might include the Tix libraries as well).


Can I have Tk events handled while waiting for I/O?
---------------------------------------------------

On platforms other than Windows, yes, and you don't even
need threads!  But you'll have to restructure your I/O
code a bit.  Tk has the equivalent of Xt's :c:func:`XtAddInput()` call, which allows you
to register a callback function which will be called from the Tk mainloop when
I/O is possible on a file descriptor.  See :ref:`tkinter-file-handlers`.


I can't get key bindings to work in Tkinter: why?
-------------------------------------------------

An often-heard complaint is that event handlers bound to events with the
:meth:`bind` method don't get handled even when the appropriate key is pressed.

The most common cause is that the widget to which the binding applies doesn't
have "keyboard focus".  Check out the Tk documentation for the focus command.
Usually a widget is given the keyboard focus by clicking in it (but not for
labels; see the takefocus option).



PK	%�\Vv��html/_sources/faq/index.rst.txtnu�[���.. _faq-index:

###################################
  Python Frequently Asked Questions
###################################

.. toctree::
   :maxdepth: 1

   general.rst
   programming.rst
   design.rst
   library.rst
   extending.rst
   windows.rst
   gui.rst
   installed.rst
PK	%�\��}-	-	#html/_sources/faq/installed.rst.txtnu�[���=============================================
"Why is Python Installed on my Computer?" FAQ
=============================================

What is Python?
---------------

Python is a programming language.  It's used for many different applications.
It's used in some high schools and colleges as an introductory programming
language because Python is easy to learn, but it's also used by professional
software developers at places such as Google, NASA, and Lucasfilm Ltd.

If you wish to learn more about Python, start with the `Beginner's Guide to
Python <https://wiki.python.org/moin/BeginnersGuide>`_.


Why is Python installed on my machine?
--------------------------------------

If you find Python installed on your system but don't remember installing it,
there are several possible ways it could have gotten there.

* Perhaps another user on the computer wanted to learn programming and installed
  it; you'll have to figure out who's been using the machine and might have
  installed it.
* A third-party application installed on the machine might have been written in
  Python and included a Python installation.  For a home computer, the most
  common such application is `PySol <http://pysolfc.sourceforge.net/>`_, a
  solitaire game that includes over 1000 different games and variations.
* Some Windows machines also have Python installed.  At this writing we're aware
  of computers from Hewlett-Packard and Compaq that include Python.  Apparently
  some of HP/Compaq's administrative tools are written in Python.
* All Apple computers running Mac OS X have Python installed; it's included in
  the base installation.


Can I delete Python?
--------------------

That depends on where Python came from.

If someone installed it deliberately, you can remove it without hurting
anything.  On Windows, use the Add/Remove Programs icon in the Control Panel.

If Python was installed by a third-party application, you can also remove it,
but that application will no longer work.  You should use that application's
uninstaller rather than removing Python directly.

If Python came with your operating system, removing it is not recommended.  If
you remove it, whatever tools were written in Python will no longer run, and
some of them might be important to you.  Reinstalling the whole system would
then be required to fix things again.

PK	%�\՘S�{�{�!html/_sources/faq/library.rst.txtnu�[���:tocdepth: 2

=========================
Library and Extension FAQ
=========================

.. only:: html

   .. contents::

General Library Questions
=========================

How do I find a module or application to perform task X?
--------------------------------------------------------

Check :ref:`the Library Reference <library-index>` to see if there's a relevant
standard library module.  (Eventually you'll learn what's in the standard
library and will be able to skip this step.)

For third-party packages, search the `Python Package Index
<https://pypi.org>`_ or try `Google <https://www.google.com>`_ or
another Web search engine.  Searching for "Python" plus a keyword or two for
your topic of interest will usually find something helpful.


Where is the math.py (socket.py, regex.py, etc.) source file?
-------------------------------------------------------------

If you can't find a source file for a module it may be a built-in or
dynamically loaded module implemented in C, C++ or other compiled language.
In this case you may not have the source file or it may be something like
:file:`mathmodule.c`, somewhere in a C source directory (not on the Python Path).

There are (at least) three kinds of modules in Python:

1) modules written in Python (.py);
2) modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
3) modules written in C and linked with the interpreter; to get a list of these,
   type::

      import sys
      print sys.builtin_module_names


How do I make a Python script executable on Unix?
-------------------------------------------------

You need to do two things: the script file's mode must be executable and the
first line must begin with ``#!`` followed by the path of the Python
interpreter.

The first is done by executing ``chmod +x scriptfile`` or perhaps ``chmod 755
scriptfile``.

The second can be done in a number of ways.  The most straightforward way is to
write ::

  #!/usr/local/bin/python

as the very first line of your file, using the pathname for where the Python
interpreter is installed on your platform.

If you would like the script to be independent of where the Python interpreter
lives, you can use the :program:`env` program.  Almost all Unix variants support
the following, assuming the Python interpreter is in a directory on the user's
:envvar:`PATH`::

  #!/usr/bin/env python

*Don't* do this for CGI scripts.  The :envvar:`PATH` variable for CGI scripts is
often very minimal, so you need to use the actual absolute pathname of the
interpreter.

Occasionally, a user's environment is so full that the :program:`/usr/bin/env`
program fails; or there's no env program at all.  In that case, you can try the
following hack (due to Alex Rezinsky)::

   #! /bin/sh
   """:"
   exec python $0 ${1+"$@"}
   """

The minor disadvantage is that this defines the script's __doc__ string.
However, you can fix that by adding ::

   __doc__ = """...Whatever..."""



Is there a curses/termcap package for Python?
---------------------------------------------

.. XXX curses *is* built by default, isn't it?

For Unix variants the standard Python source distribution comes with a curses
module in the :source:`Modules` subdirectory, though it's not compiled by default.
(Note that this is not available in the Windows distribution -- there is no
curses module for Windows.)

The :mod:`curses` module supports basic curses features as well as many additional
functions from ncurses and SYSV curses such as colour, alternative character set
support, pads, and mouse support. This means the module isn't compatible with
operating systems that only have BSD curses, but there don't seem to be any
currently maintained OSes that fall into this category.

For Windows: use `the consolelib module
<http://effbot.org/zone/console-index.htm>`_.


Is there an equivalent to C's onexit() in Python?
-------------------------------------------------

The :mod:`atexit` module provides a register function that is similar to C's
:c:func:`onexit`.


Why don't my signal handlers work?
----------------------------------

The most common problem is that the signal handler is declared with the wrong
argument list.  It is called as ::

   handler(signum, frame)

so it should be declared with two arguments::

   def handler(signum, frame):
       ...


Common tasks
============

How do I test a Python program or component?
--------------------------------------------

Python comes with two testing frameworks.  The :mod:`doctest` module finds
examples in the docstrings for a module and runs them, comparing the output with
the expected output given in the docstring.

The :mod:`unittest` module is a fancier testing framework modelled on Java and
Smalltalk testing frameworks.

To make testing easier, you should use good modular design in your program.
Your program should have almost all functionality
encapsulated in either functions or class methods -- and this sometimes has the
surprising and delightful effect of making the program run faster (because local
variable accesses are faster than global accesses).  Furthermore the program
should avoid depending on mutating global variables, since this makes testing
much more difficult to do.

The "global main logic" of your program may be as simple as ::

   if __name__ == "__main__":
       main_logic()

at the bottom of the main module of your program.

Once your program is organized as a tractable collection of functions and class
behaviours you should write test functions that exercise the behaviours.  A test
suite that automates a sequence of tests can be associated with each module.
This sounds like a lot of work, but since Python is so terse and flexible it's
surprisingly easy.  You can make coding much more pleasant and fun by writing
your test functions in parallel with the "production code", since this makes it
easy to find bugs and even design flaws earlier.

"Support modules" that are not intended to be the main module of a program may
include a self-test of the module. ::

   if __name__ == "__main__":
       self_test()

Even programs that interact with complex external interfaces may be tested when
the external interfaces are unavailable by using "fake" interfaces implemented
in Python.


How do I create documentation from doc strings?
-----------------------------------------------

The :mod:`pydoc` module can create HTML from the doc strings in your Python
source code.  An alternative for creating API documentation purely from
docstrings is `epydoc <http://epydoc.sourceforge.net/>`_.  `Sphinx
<http://sphinx-doc.org>`_ can also include docstring content.


How do I get a single keypress at a time?
-----------------------------------------

For Unix variants there are several solutions.  It's straightforward to do this
using curses, but curses is a fairly large module to learn.  Here's a solution
without curses::

   import termios, fcntl, sys, os
   fd = sys.stdin.fileno()

   oldterm = termios.tcgetattr(fd)
   newattr = termios.tcgetattr(fd)
   newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
   termios.tcsetattr(fd, termios.TCSANOW, newattr)

   oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
   fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

   try:
       while 1:
           try:
               c = sys.stdin.read(1)
               print "Got character", repr(c)
           except IOError: pass
   finally:
       termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
       fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

You need the :mod:`termios` and the :mod:`fcntl` module for any of this to work,
and I've only tried it on Linux, though it should work elsewhere.  In this code,
characters are read and printed one at a time.

:func:`termios.tcsetattr` turns off stdin's echoing and disables canonical mode.
:func:`fcntl.fnctl` is used to obtain stdin's file descriptor flags and modify
them for non-blocking mode.  Since reading stdin when it is empty results in an
:exc:`IOError`, this error is caught and ignored.


Threads
=======

How do I program using threads?
-------------------------------

.. XXX it's _thread in py3k

Be sure to use the :mod:`threading` module and not the :mod:`thread` module.
The :mod:`threading` module builds convenient abstractions on top of the
low-level primitives provided by the :mod:`thread` module.

Aahz has a set of slides from his threading tutorial that are helpful; see
http://www.pythoncraft.com/OSCON2001/.


None of my threads seem to run: why?
------------------------------------

As soon as the main thread exits, all threads are killed.  Your main thread is
running too quickly, giving the threads no time to do any work.

A simple fix is to add a sleep to the end of the program that's long enough for
all the threads to finish::

   import threading, time

   def thread_task(name, n):
       for i in range(n): print name, i

   for i in range(10):
       T = threading.Thread(target=thread_task, args=(str(i), i))
       T.start()

   time.sleep(10) # <----------------------------!

But now (on many platforms) the threads don't run in parallel, but appear to run
sequentially, one at a time!  The reason is that the OS thread scheduler doesn't
start a new thread until the previous thread is blocked.

A simple fix is to add a tiny sleep to the start of the run function::

   def thread_task(name, n):
       time.sleep(0.001) # <---------------------!
       for i in range(n): print name, i

   for i in range(10):
       T = threading.Thread(target=thread_task, args=(str(i), i))
       T.start()

   time.sleep(10)

Instead of trying to guess a good delay value for :func:`time.sleep`,
it's better to use some kind of semaphore mechanism.  One idea is to use the
:mod:`Queue` module to create a queue object, let each thread append a token to
the queue when it finishes, and let the main thread read as many tokens from the
queue as there are threads.


How do I parcel out work among a bunch of worker threads?
---------------------------------------------------------

Use the :mod:`Queue` module to create a queue containing a list of jobs.  The
:class:`~Queue.Queue` class maintains a list of objects and has a ``.put(obj)``
method that adds items to the queue and a ``.get()`` method to return them.
The class will take care of the locking necessary to ensure that each job is
handed out exactly once.

Here's a trivial example::

   import threading, Queue, time

   # The worker thread gets jobs off the queue.  When the queue is empty, it
   # assumes there will be no more work and exits.
   # (Realistically workers will run until terminated.)
   def worker():
       print 'Running worker'
       time.sleep(0.1)
       while True:
           try:
               arg = q.get(block=False)
           except Queue.Empty:
               print 'Worker', threading.currentThread(),
               print 'queue empty'
               break
           else:
               print 'Worker', threading.currentThread(),
               print 'running with argument', arg
               time.sleep(0.5)

   # Create queue
   q = Queue.Queue()

   # Start a pool of 5 workers
   for i in range(5):
       t = threading.Thread(target=worker, name='worker %i' % (i+1))
       t.start()

   # Begin adding work to the queue
   for i in range(50):
       q.put(i)

   # Give threads time to run
   print 'Main thread sleeping'
   time.sleep(5)

When run, this will produce the following output:

.. code-block:: none

   Running worker
   Running worker
   Running worker
   Running worker
   Running worker
   Main thread sleeping
   Worker <Thread(worker 1, started)> running with argument 0
   Worker <Thread(worker 2, started)> running with argument 1
   Worker <Thread(worker 3, started)> running with argument 2
   Worker <Thread(worker 4, started)> running with argument 3
   Worker <Thread(worker 5, started)> running with argument 4
   Worker <Thread(worker 1, started)> running with argument 5
   ...

Consult the module's documentation for more details; the :class:`~Queue.Queue`
class provides a featureful interface.


What kinds of global value mutation are thread-safe?
----------------------------------------------------

A :term:`global interpreter lock` (GIL) is used internally to ensure that only
one thread runs in the Python VM at a time.  In general, Python offers to switch
among threads only between bytecode instructions; how frequently it switches can
be set via :func:`sys.setcheckinterval`.  Each bytecode instruction and
therefore all the C implementation code reached from each instruction is
therefore atomic from the point of view of a Python program.

In theory, this means an exact accounting requires an exact understanding of the
PVM bytecode implementation.  In practice, it means that operations on shared
variables of built-in data types (ints, lists, dicts, etc) that "look atomic"
really are.

For example, the following operations are all atomic (L, L1, L2 are lists, D,
D1, D2 are dicts, x, y are objects, i, j are ints)::

   L.append(x)
   L1.extend(L2)
   x = L[i]
   x = L.pop()
   L1[i:j] = L2
   L.sort()
   x = y
   x.field = y
   D[x] = y
   D1.update(D2)
   D.keys()

These aren't::

   i = i+1
   L.append(L[-1])
   L[i] = L[j]
   D[x] = D[x] + 1

Operations that replace other objects may invoke those other objects'
:meth:`__del__` method when their reference count reaches zero, and that can
affect things.  This is especially true for the mass updates to dictionaries and
lists.  When in doubt, use a mutex!


Can't we get rid of the Global Interpreter Lock?
------------------------------------------------

.. XXX mention multiprocessing
.. XXX link to dbeazley's talk about GIL?

The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
deployment on high-end multiprocessor server machines, because a multi-threaded
Python program effectively only uses one CPU, due to the insistence that
(almost) all Python code can only run while the GIL is held.

Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
patch set (the "free threading" patches) that removed the GIL and replaced it
with fine-grained locking.  Unfortunately, even on Windows (where locks are very
efficient) this ran ordinary Python code about twice as slow as the interpreter
using the GIL.  On Linux the performance loss was even worse because pthread
locks aren't as efficient.

Since then, the idea of getting rid of the GIL has occasionally come up but
nobody has found a way to deal with the expected slowdown, and users who don't
use threads would not be happy if their code ran at half the speed.  Greg's
free threading patch set has not been kept up-to-date for later Python versions.

This doesn't mean that you can't make good use of Python on multi-CPU machines!
You just have to be creative with dividing the work up between multiple
*processes* rather than multiple *threads*.  Judicious use of C extensions will
also help; if you use a C extension to perform a time-consuming task, the
extension can release the GIL while the thread of execution is in the C code and
allow other threads to get some work done.

It has been suggested that the GIL should be a per-interpreter-state lock rather
than truly global; interpreters then wouldn't be able to share objects.
Unfortunately, this isn't likely to happen either.  It would be a tremendous
amount of work, because many object implementations currently have global state.
For example, small integers and short strings are cached; these caches would
have to be moved to the interpreter state.  Other object types have their own
free list; these free lists would have to be moved to the interpreter state.
And so on.

And I doubt that it can even be done in finite time, because the same problem
exists for 3rd party extensions.  It is likely that 3rd party extensions are
being written at a faster rate than you can convert them to store all their
global state in the interpreter state.

And finally, once you have multiple interpreters not sharing any state, what
have you gained over running each interpreter in a separate process?


Input and Output
================

How do I delete a file? (And other file questions...)
-----------------------------------------------------

Use ``os.remove(filename)`` or ``os.unlink(filename)``; for documentation, see
the :mod:`os` module.  The two functions are identical; :func:`unlink` is simply
the name of the Unix system call for this function.

To remove a directory, use :func:`os.rmdir`; use :func:`os.mkdir` to create one.
``os.makedirs(path)`` will create any intermediate directories in ``path`` that
don't exist. ``os.removedirs(path)`` will remove intermediate directories as
long as they're empty; if you want to delete an entire directory tree and its
contents, use :func:`shutil.rmtree`.

To rename a file, use ``os.rename(old_path, new_path)``.

To truncate a file, open it using ``f = open(filename, "r+")``, and use
``f.truncate(offset)``; offset defaults to the current seek position.  There's
also ``os.ftruncate(fd, offset)`` for files opened with :func:`os.open`, where
*fd* is the file descriptor (a small integer).

The :mod:`shutil` module also contains a number of functions to work on files
including :func:`~shutil.copyfile`, :func:`~shutil.copytree`, and
:func:`~shutil.rmtree`.


How do I copy a file?
---------------------

The :mod:`shutil` module contains a :func:`~shutil.copyfile` function.  Note
that on MacOS 9 it doesn't copy the resource fork and Finder info.


How do I read (or write) binary data?
-------------------------------------

To read or write complex binary data formats, it's best to use the :mod:`struct`
module.  It allows you to take a string containing binary data (usually numbers)
and convert it to Python objects; and vice versa.

For example, the following code reads two 2-byte integers and one 4-byte integer
in big-endian format from a file::

   import struct

   f = open(filename, "rb")  # Open in binary mode for portability
   s = f.read(8)
   x, y, z = struct.unpack(">hhl", s)

The '>' in the format string forces big-endian data; the letter 'h' reads one
"short integer" (2 bytes), and 'l' reads one "long integer" (4 bytes) from the
string.

For data that is more regular (e.g. a homogeneous list of ints or floats),
you can also use the :mod:`array` module.


I can't seem to use os.read() on a pipe created with os.popen(); why?
---------------------------------------------------------------------

:func:`os.read` is a low-level function which takes a file descriptor, a small
integer representing the opened file.  :func:`os.popen` creates a high-level
file object, the same type returned by the built-in :func:`open` function.
Thus, to read *n* bytes from a pipe *p* created with :func:`os.popen`, you need to
use ``p.read(n)``.


How do I run a subprocess with pipes connected to both input and output?
------------------------------------------------------------------------

.. XXX update to use subprocess

Use the :mod:`popen2` module.  For example::

   import popen2
   fromchild, tochild = popen2.popen2("command")
   tochild.write("input\n")
   tochild.flush()
   output = fromchild.readline()

Warning: in general it is unwise to do this because you can easily cause a
deadlock where your process is blocked waiting for output from the child while
the child is blocked waiting for input from you.  This can be caused by the
parent expecting the child to output more text than it does or by data being
stuck in stdio buffers due to lack of flushing.  The Python parent
can of course explicitly flush the data it sends to the child before it reads
any output, but if the child is a naive C program it may have been written to
never explicitly flush its output, even if it is interactive, since flushing is
normally automatic.

Note that a deadlock is also possible if you use :func:`popen3` to read stdout
and stderr. If one of the two is too large for the internal buffer (increasing
the buffer size does not help) and you ``read()`` the other one first, there is
a deadlock, too.

Note on a bug in popen2: unless your program calls ``wait()`` or ``waitpid()``,
finished child processes are never removed, and eventually calls to popen2 will
fail because of a limit on the number of child processes.  Calling
:func:`os.waitpid` with the :data:`os.WNOHANG` option can prevent this; a good
place to insert such a call would be before calling ``popen2`` again.

In many cases, all you really need is to run some data through a command and get
the result back.  Unless the amount of data is very large, the easiest way to do
this is to write it to a temporary file and run the command with that temporary
file as input.  The standard module :mod:`tempfile` exports a
:func:`~tempfile.mktemp` function to generate unique temporary file names. ::

   import tempfile
   import os

   class Popen3:
       """
       This is a deadlock-safe version of popen that returns
       an object with errorlevel, out (a string) and err (a string).
       (capturestderr may not work under windows.)
       Example: print Popen3('grep spam','\n\nhere spam\n\n').out
       """
       def __init__(self,command,input=None,capturestderr=None):
           outfile=tempfile.mktemp()
           command="( %s ) > %s" % (command,outfile)
           if input:
               infile=tempfile.mktemp()
               open(infile,"w").write(input)
               command=command+" <"+infile
           if capturestderr:
               errfile=tempfile.mktemp()
               command=command+" 2>"+errfile
           self.errorlevel=os.system(command) >> 8
           self.out=open(outfile,"r").read()
           os.remove(outfile)
           if input:
               os.remove(infile)
           if capturestderr:
               self.err=open(errfile,"r").read()
               os.remove(errfile)

Note that many interactive programs (e.g. vi) don't work well with pipes
substituted for standard input and output.  You will have to use pseudo ttys
("ptys") instead of pipes. Or you can use a Python interface to Don Libes'
"expect" library.  A Python extension that interfaces to expect is called "expy"
and available from http://expectpy.sourceforge.net.  A pure Python solution that
works like expect is `pexpect <https://pypi.org/project/pexpect/>`_.


How do I access the serial (RS232) port?
----------------------------------------

For Win32, POSIX (Linux, BSD, etc.), Jython:

   http://pyserial.sourceforge.net

For Unix, see a Usenet post by Mitch Chapman:

   https://groups.google.com/groups?selm=34A04430.CF9@ohioee.com


Why doesn't closing sys.stdout (stdin, stderr) really close it?
---------------------------------------------------------------

Python file objects are a high-level layer of abstraction on top of C streams,
which in turn are a medium-level layer of abstraction on top of (among other
things) low-level C file descriptors.

For most file objects you create in Python via the built-in ``file``
constructor, ``f.close()`` marks the Python file object as being closed from
Python's point of view, and also arranges to close the underlying C stream.
This also happens automatically in ``f``'s destructor, when ``f`` becomes
garbage.

But stdin, stdout and stderr are treated specially by Python, because of the
special status also given to them by C.  Running ``sys.stdout.close()`` marks
the Python-level file object as being closed, but does *not* close the
associated C stream.

To close the underlying C stream for one of these three, you should first be
sure that's what you really want to do (e.g., you may confuse extension modules
trying to do I/O).  If it is, use os.close::

    os.close(0)   # close C's stdin stream
    os.close(1)   # close C's stdout stream
    os.close(2)   # close C's stderr stream


Network/Internet Programming
============================

What WWW tools are there for Python?
------------------------------------

See the chapters titled :ref:`internet` and :ref:`netdata` in the Library
Reference Manual.  Python has many modules that will help you build server-side
and client-side web systems.

.. XXX check if wiki page is still up to date

A summary of available frameworks is maintained by Paul Boddie at
https://wiki.python.org/moin/WebProgramming\ .

Cameron Laird maintains a useful set of pages about Python web technologies at
http://phaseit.net/claird/comp.lang.python/web_python.


How can I mimic CGI form submission (METHOD=POST)?
--------------------------------------------------

I would like to retrieve web pages that are the result of POSTing a form. Is
there existing code that would let me do this easily?

Yes. Here's a simple example that uses httplib::

   #!/usr/local/bin/python

   import httplib, sys, time

   # build the query string
   qs = "First=Josephine&MI=Q&Last=Public"

   # connect and send the server a path
   httpobj = httplib.HTTP('www.some-server.out-there', 80)
   httpobj.putrequest('POST', '/cgi-bin/some-cgi-script')
   # now generate the rest of the HTTP headers...
   httpobj.putheader('Accept', '*/*')
   httpobj.putheader('Connection', 'Keep-Alive')
   httpobj.putheader('Content-type', 'application/x-www-form-urlencoded')
   httpobj.putheader('Content-length', '%d' % len(qs))
   httpobj.endheaders()
   httpobj.send(qs)
   # find out what the server said in response...
   reply, msg, hdrs = httpobj.getreply()
   if reply != 200:
       sys.stdout.write(httpobj.getfile().read())

Note that in general for percent-encoded POST operations, query strings must be
quoted using :func:`urllib.urlencode`.  For example, to send
``name=Guy Steele, Jr.``::

   >>> import urllib
   >>> urllib.urlencode({'name': 'Guy Steele, Jr.'})
   'name=Guy+Steele%2C+Jr.'


What module should I use to help with generating HTML?
------------------------------------------------------

.. XXX add modern template languages

You can find a collection of useful links on the `Web Programming wiki page
<https://wiki.python.org/moin/WebProgramming>`_.


How do I send mail from a Python script?
----------------------------------------

Use the standard library module :mod:`smtplib`.

Here's a very simple interactive mail sender that uses it.  This method will
work on any host that supports an SMTP listener. ::

   import sys, smtplib

   fromaddr = raw_input("From: ")
   toaddrs  = raw_input("To: ").split(',')
   print "Enter message, end with ^D:"
   msg = ''
   while True:
       line = sys.stdin.readline()
       if not line:
           break
       msg += line

   # The actual mail send
   server = smtplib.SMTP('localhost')
   server.sendmail(fromaddr, toaddrs, msg)
   server.quit()

A Unix-only alternative uses sendmail.  The location of the sendmail program
varies between systems; sometimes it is ``/usr/lib/sendmail``, sometimes
``/usr/sbin/sendmail``.  The sendmail manual page will help you out.  Here's
some sample code::

   import os

   SENDMAIL = "/usr/sbin/sendmail"  # sendmail location
   p = os.popen("%s -t -i" % SENDMAIL, "w")
   p.write("To: receiver@example.com\n")
   p.write("Subject: test\n")
   p.write("\n") # blank line separating headers from body
   p.write("Some text\n")
   p.write("some more text\n")
   sts = p.close()
   if sts != 0:
       print "Sendmail exit status", sts


How do I avoid blocking in the connect() method of a socket?
------------------------------------------------------------

The select module is commonly used to help with asynchronous I/O on sockets.

To prevent the TCP connect from blocking, you can set the socket to non-blocking
mode.  Then when you do the ``connect()``, you will either connect immediately
(unlikely) or get an exception that contains the error number as ``.errno``.
``errno.EINPROGRESS`` indicates that the connection is in progress, but hasn't
finished yet.  Different OSes will return different values, so you're going to
have to check what's returned on your system.

You can use the ``connect_ex()`` method to avoid creating an exception.  It will
just return the errno value.  To poll, you can call ``connect_ex()`` again later
-- 0 or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
socket to select to check if it's writable.


Databases
=========

Are there any interfaces to database packages in Python?
--------------------------------------------------------

Yes.

.. XXX remove bsddb in py3k, fix other module names

Python 2.3 includes the :mod:`bsddb` package which provides an interface to the
BerkeleyDB library.  Interfaces to disk-based hashes such as :mod:`DBM <dbm>`
and :mod:`GDBM <gdbm>` are also included with standard Python.

Support for most relational databases is available.  See the
`DatabaseProgramming wiki page
<https://wiki.python.org/moin/DatabaseProgramming>`_ for details.


How do you implement persistent objects in Python?
--------------------------------------------------

The :mod:`pickle` library module solves this in a very general way (though you
still can't store things like open files, sockets or windows), and the
:mod:`shelve` library module uses pickle and (g)dbm to create persistent
mappings containing arbitrary Python objects.  For better performance, you can
use the :mod:`cPickle` module.

A more awkward way of doing things is to use pickle's little sister, marshal.
The :mod:`marshal` module provides very fast ways to store noncircular basic
Python types to files and strings, and back again.  Although marshal does not do
fancy things like store instances or handle shared references properly, it does
run extremely fast.  For example, loading a half megabyte of data may take less
than a third of a second.  This often beats doing something more complex and
general such as using gdbm with pickle/shelve.


Why is cPickle so slow?
-----------------------

.. XXX update this, default protocol is 2/3

By default :mod:`pickle` uses a relatively old and slow format for backward
compatibility.  You can however specify other protocol versions that are
faster::

    largeString = 'z' * (100 * 1024)
    myPickle = cPickle.dumps(largeString, protocol=1)


If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?
------------------------------------------------------------------------------------------

Databases opened for write access with the bsddb module (and often by the anydbm
module, since it will preferentially use bsddb) must explicitly be closed using
the ``.close()`` method of the database.  The underlying library caches database
contents which need to be converted to on-disk form and written.

If you have initialized a new bsddb database but not written anything to it
before the program crashes, you will often wind up with a zero-length file and
encounter an exception the next time the file is opened.


I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, 'Invalid argument'). Help! How can I restore my data?
----------------------------------------------------------------------------------------------------------------------------

Don't panic! Your data is probably intact. The most frequent cause for the error
is that you tried to open an earlier Berkeley DB file with a later version of
the Berkeley DB library.

Many Linux systems now have all three versions of Berkeley DB available.  If you
are migrating from version 1 to a newer version use db_dump185 to dump a plain
text version of the database.  If you are migrating from version 2 to version 3
use db2_dump to create a plain text version of the database.  In either case,
use db_load to create a new native database for the latest version installed on
your computer.  If you have version 3 of Berkeley DB installed, you should be
able to use db2_load to create a native version 2 database.

You should move away from Berkeley DB version 1 files because the hash file code
contains known bugs that can corrupt your data.


Mathematics and Numerics
========================

How do I generate random numbers in Python?
-------------------------------------------

The standard module :mod:`random` implements a random number generator.  Usage
is simple::

   import random
   random.random()

This returns a random floating point number in the range [0, 1).

There are also many other specialized generators in this module, such as:

* ``randrange(a, b)`` chooses an integer in the range [a, b).
* ``uniform(a, b)`` chooses a floating point number in the range [a, b).
* ``normalvariate(mean, sdev)`` samples the normal (Gaussian) distribution.

Some higher-level functions operate on sequences directly, such as:

* ``choice(S)`` chooses random element from a given sequence
* ``shuffle(L)`` shuffles a list in-place, i.e. permutes it randomly

There's also a ``Random`` class you can instantiate to create independent
multiple random number generators.
PK	%�\����""%html/_sources/faq/programming.rst.txtnu�[���:tocdepth: 2

===============
Programming FAQ
===============

.. only:: html

   .. contents::

General Questions
=================

Is there a source code level debugger with breakpoints, single-stepping, etc.?
------------------------------------------------------------------------------

Yes.

The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is :mod:`documented in the Library
Reference Manual <pdb>`. You can also write your own debugger by using the code
for pdb as an example.

The IDLE interactive development environment, which is part of the standard
Python distribution (normally available as Tools/scripts/idle), includes a
graphical debugger.

PythonWin is a Python IDE that includes a GUI debugger based on pdb.  The
Pythonwin debugger colors breakpoints and has quite a few cool features such as
debugging non-Pythonwin programs.  Pythonwin is available as part of the `Python
for Windows Extensions <https://sourceforge.net/projects/pywin32/>`__ project and
as a part of the ActivePython distribution (see
https://www.activestate.com/activepython\ ).

`Boa Constructor <http://boa-constructor.sourceforge.net/>`_ is an IDE and GUI
builder that uses wxWidgets.  It offers visual frame creation and manipulation,
an object inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced debugger,
integrated help, and Zope support.

`Eric <http://eric-ide.python-projects.org/>`_ is an IDE built on PyQt
and the Scintilla editing component.

Pydb is a version of the standard Python debugger pdb, modified for use with DDD
(Data Display Debugger), a popular graphical debugger front end.  Pydb can be
found at http://bashdb.sourceforge.net/pydb/ and DDD can be found at
https://www.gnu.org/software/ddd.

There are a number of commercial Python IDEs that include graphical debuggers.
They include:

* Wing IDE (https://wingware.com/)
* Komodo IDE (https://komodoide.com/)
* PyCharm (https://www.jetbrains.com/pycharm/)


Is there a tool to help find bugs or perform static analysis?
-------------------------------------------------------------

Yes.

PyChecker is a static analysis tool that finds bugs in Python source code and
warns about code complexity and style.  You can get PyChecker from
http://pychecker.sourceforge.net/.

`Pylint <https://www.pylint.org/>`_ is another tool that checks
if a module satisfies a coding standard, and also makes it possible to write
plug-ins to add a custom feature.  In addition to the bug checking that
PyChecker performs, Pylint offers some additional features such as checking line
length, whether variable names are well-formed according to your coding
standard, whether declared interfaces are fully implemented, and more.
https://docs.pylint.org/ provides a full list of Pylint's features.


How can I create a stand-alone binary from a Python script?
-----------------------------------------------------------

You don't need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first.  There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.

One is to use the freeze tool, which is included in the Python source tree as
``Tools/freeze``. It converts Python byte code to C arrays; a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.

It works by scanning your source recursively for import statements (in both
forms) and looking for the modules in the standard Python path as well as in the
source directory (for built-in modules).  It then turns the bytecode for modules
written in Python into C code (array initializers that can be turned into code
objects using the marshal module) and creates a custom-made config file that
only contains those built-in modules which are actually used in the program.  It
then compiles the generated C code and links it with the rest of the Python
interpreter to form a self-contained binary which acts exactly like your script.

Obviously, freeze requires a C compiler.  There are several other utilities
which don't. One is Thomas Heller's py2exe (Windows only) at

    http://www.py2exe.org/

Another tool is Anthony Tuininga's `cx_Freeze <http://cx-freeze.sourceforge.net/>`_.


Are there coding standards or a style guide for Python programs?
----------------------------------------------------------------

Yes.  The coding style required for standard library modules is documented as
:pep:`8`.


My program is too slow. How do I speed it up?
---------------------------------------------

That's a tough one, in general.  There are many tricks to speed up Python code;
consider rewriting parts in C as a last resort.

In some cases it's possible to automatically translate Python to C or x86
assembly language, meaning that you don't have to modify your code to gain
increased speed.

.. XXX seems to have overlap with other questions!

`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ can compile a
slightly modified version of Python code into a C extension, and can be used on
many different platforms.

`Psyco <http://psyco.sourceforge.net>`_ is a just-in-time compiler that
translates Python code into x86 assembly language.  If you can use it, Psyco can
provide dramatic speedups for critical functions.

The rest of this answer will discuss various tricks for squeezing a bit more
speed out of Python code.  *Never* apply any optimization tricks unless you know
you need them, after profiling has indicated that a particular function is the
heavily executed hot spot in the code.  Optimizations almost always make the
code less clear, and you shouldn't pay the costs of reduced clarity (increased
development time, greater likelihood of bugs) unless the resulting performance
benefit is worth it.

There is a page on the wiki devoted to `performance tips
<https://wiki.python.org/moin/PythonSpeed/PerformanceTips>`_.

Guido van Rossum has written up an anecdote related to optimization at
https://www.python.org/doc/essays/list2str.

One thing to notice is that function and (especially) method calls are rather
expensive; if you have designed a purely OO interface with lots of tiny
functions that don't do much more than get or set an instance variable or call
another method, you might consider using a more direct way such as directly
accessing instance variables.  Also see the standard module :mod:`profile` which
makes it possible to find out where your program is spending most of its time
(if you have some patience -- the profiling itself can slow your program down by
an order of magnitude).

Remember that many standard optimization heuristics you may know from other
programming experience may well apply to Python.  For example it may be faster
to send output to output devices using larger writes rather than smaller ones in
order to reduce the overhead of kernel system calls.  Thus CGI scripts that
write all output in "one shot" may be faster than those that write lots of small
pieces of output.

Also, be sure to use Python's core features where appropriate.  For example,
slicing allows programs to chop up lists and other sequence objects in a single
tick of the interpreter's mainloop using highly optimized C implementations.
Thus to get the same effect as::

   L2 = []
   for i in range(3):
       L2.append(L1[i])

it is much shorter and far faster to use ::

   L2 = list(L1[:3])  # "list" is redundant if L1 is a list.

Note that the functionally-oriented built-in functions such as :func:`map`,
:func:`zip`, and friends can be a convenient accelerator for loops that
perform a single task.  For example to pair the elements of two lists
together::

   >>> zip([1, 2, 3], [4, 5, 6])
   [(1, 4), (2, 5), (3, 6)]

or to compute a number of sines::

   >>> map(math.sin, (1, 2, 3, 4))
   [0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]

The operation completes very quickly in such cases.

Other examples include the ``join()`` and ``split()`` :ref:`methods
of string objects <string-methods>`.
For example if s1..s7 are large (10K+) strings then
``"".join([s1,s2,s3,s4,s5,s6,s7])`` may be far faster than the more obvious
``s1+s2+s3+s4+s5+s6+s7``, since the "summation" will compute many
subexpressions, whereas ``join()`` does all the copying in one pass.  For
manipulating strings, use the ``replace()`` and the ``format()`` :ref:`methods
on string objects <string-methods>`.  Use regular expressions only when you're
not dealing with constant string patterns.  You may still use :ref:`the old %
operations <string-formatting>` ``string % tuple`` and ``string % dictionary``.

Be sure to use the :meth:`list.sort` built-in method to do sorting, and see the
`sorting mini-HOWTO <https://wiki.python.org/moin/HowTo/Sorting>`_ for examples
of moderately advanced usage.  :meth:`list.sort` beats other techniques for
sorting in all but the most extreme circumstances.

Another common trick is to "push loops into functions or methods."  For example
suppose you have a program that runs slowly and you use the profiler to
determine that a Python function ``ff()`` is being called lots of times.  If you
notice that ``ff()``::

   def ff(x):
       ... # do something with x computing result...
       return result

tends to be called in loops like::

   list = map(ff, oldlist)

or::

   for x in sequence:
       value = ff(x)
       ... # do something with value...

then you can often eliminate function call overhead by rewriting ``ff()`` to::

   def ffseq(seq):
       resultseq = []
       for x in seq:
           ... # do something with x computing result...
           resultseq.append(result)
       return resultseq

and rewrite the two examples to ``list = ffseq(oldlist)`` and to::

   for value in ffseq(sequence):
       ... # do something with value...

Single calls to ``ff(x)`` translate to ``ffseq([x])[0]`` with little penalty.
Of course this technique is not always appropriate and there are other variants
which you can figure out.

You can gain some performance by explicitly storing the results of a function or
method lookup into a local variable.  A loop like::

   for key in token:
       dict[key] = dict.get(key, 0) + 1

resolves ``dict.get`` every iteration.  If the method isn't going to change, a
slightly faster implementation is::

   dict_get = dict.get  # look up the method once
   for key in token:
       dict[key] = dict_get(key, 0) + 1

Default arguments can be used to determine values once, at compile time instead
of at run time.  This can only be done for functions or objects which will not
be changed during program execution, such as replacing ::

   def degree_sin(deg):
       return math.sin(deg * math.pi / 180.0)

with ::

   def degree_sin(deg, factor=math.pi/180.0, sin=math.sin):
       return sin(deg * factor)

Because this trick uses default arguments for terms which should not be changed,
it should only be used when you are not concerned with presenting a possibly
confusing API to your users.


Core Language
=============

Why am I getting an UnboundLocalError when the variable has a value?
--------------------------------------------------------------------

It can be a surprise to get the UnboundLocalError in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.

This code:

   >>> x = 10
   >>> def bar():
   ...     print x
   >>> bar()
   10

works, but this code:

   >>> x = 10
   >>> def foo():
   ...     print x
   ...     x += 1

results in an UnboundLocalError:

   >>> foo()
   Traceback (most recent call last):
     ...
   UnboundLocalError: local variable 'x' referenced before assignment

This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
in the outer scope.  Since the last statement in foo assigns a new value to
``x``, the compiler recognizes it as a local variable.  Consequently when the
earlier ``print x`` attempts to print the uninitialized local variable and
an error results.

In the example above you can access the outer scope variable by declaring it
global:

   >>> x = 10
   >>> def foobar():
   ...     global x
   ...     print x
   ...     x += 1
   >>> foobar()
   10

This explicit declaration is required in order to remind you that (unlike the
superficially analogous situation with class and instance variables) you are
actually modifying the value of the variable in the outer scope:

   >>> print x
   11


What are the rules for local and global variables in Python?
------------------------------------------------------------

In Python, variables that are only referenced inside a function are implicitly
global.  If a variable is assigned a value anywhere within the function's body,
it's assumed to be a local unless explicitly declared as global.

Though a bit surprising at first, a moment's consideration explains this.  On
one hand, requiring :keyword:`global` for assigned variables provides a bar
against unintended side-effects.  On the other hand, if ``global`` was required
for all global references, you'd be using ``global`` all the time.  You'd have
to declare as global every reference to a built-in function or to a component of
an imported module.  This clutter would defeat the usefulness of the ``global``
declaration for identifying side-effects.


Why do lambdas defined in a loop with different values all return the same result?
----------------------------------------------------------------------------------

Assume you use a for loop to define a few different lambdas (or even plain
functions), e.g.::

   >>> squares = []
   >>> for x in range(5):
   ...     squares.append(lambda: x**2)

This gives you a list that contains 5 lambdas that calculate ``x**2``.  You
might expect that, when called, they would return, respectively, ``0``, ``1``,
``4``, ``9``, and ``16``.  However, when you actually try you will see that
they all return ``16``::

   >>> squares[2]()
   16
   >>> squares[4]()
   16

This happens because ``x`` is not local to the lambdas, but is defined in
the outer scope, and it is accessed when the lambda is called --- not when it
is defined.  At the end of the loop, the value of ``x`` is ``4``, so all the
functions now return ``4**2``, i.e. ``16``.  You can also verify this by
changing the value of ``x`` and see how the results of the lambdas change::

   >>> x = 8
   >>> squares[2]()
   64

In order to avoid this, you need to save the values in variables local to the
lambdas, so that they don't rely on the value of the global ``x``::

   >>> squares = []
   >>> for x in range(5):
   ...     squares.append(lambda n=x: n**2)

Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed
when the lambda is defined so that it has the same value that ``x`` had at
that point in the loop.  This means that the value of ``n`` will be ``0``
in the first lambda, ``1`` in the second, ``2`` in the third, and so on.
Therefore each lambda will now return the correct result::

   >>> squares[2]()
   4
   >>> squares[4]()
   16

Note that this behaviour is not peculiar to lambdas, but applies to regular
functions too.


How do I share global variables across modules?
------------------------------------------------

The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg).  Just import the config
module in all modules of your application; the module then becomes available as
a global name.  Because there is only one instance of each module, any changes
made to the module object get reflected everywhere.  For example:

config.py::

   x = 0   # Default value of the 'x' configuration setting

mod.py::

   import config
   config.x = 1

main.py::

   import config
   import mod
   print config.x

Note that using a module is also the basis for implementing the Singleton design
pattern, for the same reason.


What are the "best practices" for using import in a module?
-----------------------------------------------------------

In general, don't use ``from modulename import *``.  Doing so clutters the
importer's namespace, and makes it much harder for linters to detect undefined
names.

Import modules at the top of a file.  Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.

It's good practice if you import modules in the following order:

1. standard library modules -- e.g. ``sys``, ``os``, ``getopt``, ``re``
2. third-party library modules (anything installed in Python's site-packages
   directory) -- e.g. mx.DateTime, ZODB, PIL.Image, etc.
3. locally-developed modules

Only use explicit relative package imports.  If you're writing code that's in
the ``package.sub.m1`` module and want to import ``package.sub.m2``, do not just
write ``import m2``, even though it's legal.  Write ``from package.sub import
m2`` or ``from . import m2`` instead.

It is sometimes necessary to move imports to a function or class to avoid
problems with circular imports.  Gordon McMillan says:

   Circular imports are fine where both modules use the "import <module>" form
   of import.  They fail when the 2nd module wants to grab a name out of the
   first ("from module import name") and the import is at the top level.  That's
   because names in the 1st are not yet available, because the first module is
   busy importing the 2nd.

In this case, if the second module is only used in one function, then the import
can easily be moved into that function.  By the time the import is called, the
first module will have finished initializing, and the second module can do its
import.

It may also be necessary to move imports out of the top level of code if some of
the modules are platform-specific.  In that case, it may not even be possible to
import all of the modules at the top of the file.  In this case, importing the
correct modules in the corresponding platform-specific code is a good option.

Only move imports into a local scope, such as inside a function definition, if
it's necessary to solve a problem such as avoiding a circular import or are
trying to reduce the initialization time of a module.  This technique is
especially helpful if many of the imports are unnecessary depending on how the
program executes.  You may also want to move imports into a function if the
modules are only ever used in that function.  Note that loading a module the
first time may be expensive because of the one time initialization of the
module, but loading a module multiple times is virtually free, costing only a
couple of dictionary lookups.  Even if the module name has gone out of scope,
the module is probably available in :data:`sys.modules`.


Why are default values shared between objects?
----------------------------------------------

This type of bug commonly bites neophyte programmers.  Consider this function::

   def foo(mydict={}):  # Danger: shared reference to one dict for all calls
       ... compute something ...
       mydict[key] = value
       return mydict

The first time you call this function, ``mydict`` contains a single item.  The
second time, ``mydict`` contains two items because when ``foo()`` begins
executing, ``mydict`` starts out with an item already in it.

It is often expected that a function call creates new objects for default
values. This is not what happens. Default values are created exactly once, when
the function is defined.  If that object is changed, like the dictionary in this
example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and ``None``,
are safe from change. Changes to mutable objects such as dictionaries, lists,
and class instances can lead to confusion.

Because of this feature, it is good programming practice to not use mutable
objects as default values.  Instead, use ``None`` as the default value and
inside the function, check if the parameter is ``None`` and create a new
list/dictionary/whatever if it is.  For example, don't write::

   def foo(mydict={}):
       ...

but::

   def foo(mydict=None):
       if mydict is None:
           mydict = {}  # create a new dict for local namespace

This feature can be useful.  When you have a function that's time-consuming to
compute, a common technique is to cache the parameters and the resulting value
of each call to the function, and return the cached value if the same value is
requested again.  This is called "memoizing", and can be implemented like this::

   # Callers will never provide a third parameter for this function.
   def expensive(arg1, arg2, _cache={}):
       if (arg1, arg2) in _cache:
           return _cache[(arg1, arg2)]

       # Calculate the value
       result = ... expensive computation ...
       _cache[(arg1, arg2)] = result           # Store result in the cache
       return result

You could use a global variable containing a dictionary instead of the default
value; it's a matter of taste.


How can I pass optional or keyword parameters from one function to another?
---------------------------------------------------------------------------

Collect the arguments using the ``*`` and ``**`` specifiers in the function's
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary.  You can then pass these arguments when
calling another function by using ``*`` and ``**``::

   def f(x, *args, **kwargs):
       ...
       kwargs['width'] = '14.3c'
       ...
       g(x, *args, **kwargs)

In the unlikely case that you care about Python versions older than 2.0, use
:func:`apply`::

   def f(x, *args, **kwargs):
       ...
       kwargs['width'] = '14.3c'
       ...
       apply(g, (x,)+args, kwargs)


.. index::
   single: argument; difference from parameter
   single: parameter; difference from argument

.. _faq-argument-vs-parameter:

What is the difference between arguments and parameters?
--------------------------------------------------------

:term:`Parameters <parameter>` are defined by the names that appear in a
function definition, whereas :term:`arguments <argument>` are the values
actually passed to a function when calling it.  Parameters define what types of
arguments a function can accept.  For example, given the function definition::

   def func(foo, bar=None, **kwargs):
       pass

*foo*, *bar* and *kwargs* are parameters of ``func``.  However, when calling
``func``, for example::

   func(42, bar=314, extra=somevar)

the values ``42``, ``314``, and ``somevar`` are arguments.


Why did changing list 'y' also change list 'x'?
------------------------------------------------

If you wrote code like::

   >>> x = []
   >>> y = x
   >>> y.append(10)
   >>> y
   [10]
   >>> x
   [10]

you might be wondering why appending an element to ``y`` changed ``x`` too.

There are two factors that produce this result:

1) Variables are simply names that refer to objects.  Doing ``y = x`` doesn't
   create a copy of the list -- it creates a new variable ``y`` that refers to
   the same object ``x`` refers to.  This means that there is only one object
   (the list), and both ``x`` and ``y`` refer to it.
2) Lists are :term:`mutable`, which means that you can change their content.

After the call to :meth:`~list.append`, the content of the mutable object has
changed from ``[]`` to ``[10]``.  Since both the variables refer to the same
object, using either name accesses the modified value ``[10]``.

If we instead assign an immutable object to ``x``::

   >>> x = 5  # ints are immutable
   >>> y = x
   >>> x = x + 1  # 5 can't be mutated, we are creating a new object here
   >>> x
   6
   >>> y
   5

we can see that in this case ``x`` and ``y`` are not equal anymore.  This is
because integers are :term:`immutable`, and when we do ``x = x + 1`` we are not
mutating the int ``5`` by incrementing its value; instead, we are creating a
new object (the int ``6``) and assigning it to ``x`` (that is, changing which
object ``x`` refers to).  After this assignment we have two objects (the ints
``6`` and ``5``) and two variables that refer to them (``x`` now refers to
``6`` but ``y`` still refers to ``5``).

Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the
object, whereas superficially similar operations (for example ``y = y + [10]``
and ``sorted(y)``) create a new object.  In general in Python (and in all cases
in the standard library) a method that mutates an object will return ``None``
to help avoid getting the two types of operations confused.  So if you
mistakenly write ``y.sort()`` thinking it will give you a sorted copy of ``y``,
you'll instead end up with ``None``, which will likely cause your program to
generate an easily diagnosed error.

However, there is one class of operations where the same operation sometimes
has different behaviors with different types:  the augmented assignment
operators.  For example, ``+=`` mutates lists but not tuples or ints (``a_list
+= [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and mutates
``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += 1`` create
new objects).

In other words:

* If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`,
  etc.), we can use some specific operations to mutate it and all the variables
  that refer to it will see the change.
* If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`,
  etc.), all the variables that refer to it will always see the same value,
  but operations that transform that value into a new value always return a new
  object.

If you want to know if two variables refer to the same object or not, you can
use the :keyword:`is` operator, or the built-in function :func:`id`.


How do I write a function with output parameters (call by reference)?
---------------------------------------------------------------------

Remember that arguments are passed by assignment in Python.  Since assignment
just creates references to objects, there's no alias between an argument name in
the caller and callee, and so no call-by-reference per se.  You can achieve the
desired effect in a number of ways.

1) By returning a tuple of the results::

      def func2(a, b):
          a = 'new-value'        # a and b are local names
          b = b + 1              # assigned to new objects
          return a, b            # return new values

      x, y = 'old-value', 99
      x, y = func2(x, y)
      print x, y                 # output: new-value 100

   This is almost always the clearest solution.

2) By using global variables.  This isn't thread-safe, and is not recommended.

3) By passing a mutable (changeable in-place) object::

      def func1(a):
          a[0] = 'new-value'     # 'a' references a mutable list
          a[1] = a[1] + 1        # changes a shared object

      args = ['old-value', 99]
      func1(args)
      print args[0], args[1]     # output: new-value 100

4) By passing in a dictionary that gets mutated::

      def func3(args):
          args['a'] = 'new-value'     # args is a mutable dictionary
          args['b'] = args['b'] + 1   # change it in-place

      args = {'a': 'old-value', 'b': 99}
      func3(args)
      print args['a'], args['b']

5) Or bundle up values in a class instance::

      class callByRef:
          def __init__(self, **args):
              for (key, value) in args.items():
                  setattr(self, key, value)

      def func4(args):
          args.a = 'new-value'        # args is a mutable callByRef
          args.b = args.b + 1         # change object in-place

      args = callByRef(a='old-value', b=99)
      func4(args)
      print args.a, args.b


   There's almost never a good reason to get this complicated.

Your best choice is to return a tuple containing the multiple results.


How do you make a higher order function in Python?
--------------------------------------------------

You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define ``linear(a,b)`` which returns a
function ``f(x)`` that computes the value ``a*x+b``.  Using nested scopes::

   def linear(a, b):
       def result(x):
           return a * x + b
       return result

Or using a callable object::

   class linear:

       def __init__(self, a, b):
           self.a, self.b = a, b

       def __call__(self, x):
           return self.a * x + self.b

In both cases, ::

   taxes = linear(0.3, 2)

gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``.

The callable object approach has the disadvantage that it is a bit slower and
results in slightly longer code.  However, note that a collection of callables
can share their signature via inheritance::

   class exponential(linear):
       # __init__ inherited
       def __call__(self, x):
           return self.a * (x ** self.b)

Object can encapsulate state for several methods::

   class counter:

       value = 0

       def set(self, x):
           self.value = x

       def up(self):
           self.value = self.value + 1

       def down(self):
           self.value = self.value - 1

   count = counter()
   inc, dec, reset = count.up, count.down, count.set

Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the
same counting variable.


How do I copy an object in Python?
----------------------------------

In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general case.
Not all objects can be copied, but most can.

Some objects can be copied more easily.  Dictionaries have a :meth:`~dict.copy`
method::

   newdict = olddict.copy()

Sequences can be copied by slicing::

   new_l = l[:]


How can I find the methods or attributes of an object?
------------------------------------------------------

For an instance x of a user-defined class, ``dir(x)`` returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.


How can my code discover the name of an object?
-----------------------------------------------

Generally speaking, it can't, because objects don't really have names.
Essentially, assignment always binds a name to a value; The same is true of
``def`` and ``class`` statements, but in that case the value is a
callable. Consider the following code::

   >>> class A:
   ...     pass
   ...
   >>> B = A
   >>> a = B()
   >>> b = a
   >>> print b
   <__main__.A instance at 0x16D07CC>
   >>> print a
   <__main__.A instance at 0x16D07CC>

Arguably the class has a name: even though it is bound to two names and invoked
through the name B the created instance is still reported as an instance of
class A.  However, it is impossible to say whether the instance's name is a or
b, since both names are bound to the same value.

Generally speaking it should not be necessary for your code to "know the names"
of particular values. Unless you are deliberately writing introspective
programs, this is usually an indication that a change of approach might be
beneficial.

In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
this question:

   The same way as you get the name of that cat you found on your porch: the cat
   (object) itself cannot tell you its name, and it doesn't really care -- so
   the only way to find out what it's called is to ask all your neighbours
   (namespaces) if it's their cat (object)...

   ....and don't be surprised if you'll find that it's known by many names, or
   no name at all!


What's up with the comma operator's precedence?
-----------------------------------------------

Comma is not an operator in Python.  Consider this session::

    >>> "a" in "b", "a"
    (False, 'a')

Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered::

    ("a" in "b"), "a"

not::

    "a" in ("b", "a")

The same is true of the various assignment operators (``=``, ``+=`` etc).  They
are not truly operators but syntactic delimiters in assignment statements.


Is there an equivalent of C's "?:" ternary operator?
----------------------------------------------------

Yes, this feature was added in Python 2.5. The syntax would be as follows::

   [on_true] if [expression] else [on_false]

   x, y = 50, 25

   small = x if x < y else y

For versions previous to 2.5 the answer would be 'No'.


Is it possible to write obfuscated one-liners in Python?
--------------------------------------------------------

Yes.  Usually this is done by nesting :keyword:`lambda` within
:keyword:`lambda`.  See the following three examples, due to Ulf Bartelt::

   # Primes < 1000
   print filter(None,map(lambda y:y*reduce(lambda x,y:x*y!=0,
   map(lambda x,y=y:y%x,range(2,int(pow(y,0.5)+1))),1),range(2,1000)))

   # First 10 Fibonacci numbers
   print map(lambda x,f=lambda x,f:(f(x-1,f)+f(x-2,f)) if x>1 else 1: f(x,f),
   range(10))

   # Mandelbrot set
   print (lambda Ru,Ro,Iu,Io,IM,Sx,Sy:reduce(lambda x,y:x+y,map(lambda y,
   Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,Sy=Sy,L=lambda yc,Iu=Iu,Io=Io,Ru=Ru,Ro=Ro,i=IM,
   Sx=Sx,Sy=Sy:reduce(lambda x,y:x+y,map(lambda x,xc=Ru,yc=yc,Ru=Ru,Ro=Ro,
   i=i,Sx=Sx,F=lambda xc,yc,x,y,k,f=lambda xc,yc,x,y,k,f:(k<=0)or (x*x+y*y
   >=4.0) or 1+f(xc,yc,x*x-y*y+xc,2.0*x*y+yc,k-1,f):f(xc,yc,x,y,k,f):chr(
   64+F(Ru+x*(Ro-Ru)/Sx,yc,0,0,i)),range(Sx))):L(Iu+y*(Io-Iu)/Sy),range(Sy
   ))))(-2.1, 0.7, -1.2, 1.2, 30, 80, 24)
   #    \___ ___/  \___ ___/  |   |   |__ lines on screen
   #        V          V      |   |______ columns on screen
   #        |          |      |__________ maximum of "iterations"
   #        |          |_________________ range on y axis
   #        |____________________________ range on x axis

Don't try this at home, kids!


Numbers and strings
===================

How do I specify hexadecimal and octal integers?
------------------------------------------------

To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase "o".  For example, to set the variable "a" to the octal value "10"
(8 in decimal), type::

   >>> a = 0o10
   >>> a
   8

Hexadecimal is just as easy.  Simply precede the hexadecimal number with a zero,
and then a lower or uppercase "x".  Hexadecimal digits can be specified in lower
or uppercase.  For example, in the Python interpreter::

   >>> a = 0xa5
   >>> a
   165
   >>> b = 0XB2
   >>> b
   178


Why does -22 // 10 return -3?
-----------------------------

It's primarily driven by the desire that ``i % j`` have the same sign as ``j``.
If you want that, and also want::

    i == (i // j) * j + (i % j)

then integer division has to return the floor.  C also requires that identity to
hold, and then compilers that truncate ``i // j`` need to make ``i % j`` have
the same sign as ``i``.

There are few real use cases for ``i % j`` when ``j`` is negative.  When ``j``
is positive, there are many, and in virtually all of them it's more useful for
``i % j`` to be ``>= 0``.  If the clock says 10 now, what did it say 200 hours
ago?  ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a bug waiting to
bite.

.. note::

   On Python 2, ``a / b`` returns the same as ``a // b`` if
   ``__future__.division`` is not in effect.  This is also known as "classic"
   division.


How do I convert a string to a number?
--------------------------------------

For integers, use the built-in :func:`int` type constructor, e.g. ``int('144')
== 144``.  Similarly, :func:`float` converts to floating-point,
e.g. ``float('144') == 144.0``.

By default, these interpret the number as decimal, so that ``int('0144') ==
144`` and ``int('0x144')`` raises :exc:`ValueError`. ``int(string, base)`` takes
the base to convert from as a second optional argument, so ``int('0x144', 16) ==
324``.  If the base is specified as 0, the number is interpreted using Python's
rules: a leading '0' indicates octal, and '0x' indicates a hex number.

Do not use the built-in function :func:`eval` if all you need is to convert
strings to numbers.  :func:`eval` will be significantly slower and it presents a
security risk: someone could pass you a Python expression that might have
unwanted side effects.  For example, someone could pass
``__import__('os').system("rm -rf $HOME")`` which would erase your home
directory.

:func:`eval` also has the effect of interpreting numbers as Python expressions,
so that e.g. ``eval('09')`` gives a syntax error because Python regards numbers
starting with '0' as octal (base 8).


How do I convert a number to a string?
--------------------------------------

To convert, e.g., the number 144 to the string '144', use the built-in type
constructor :func:`str`.  If you want a hexadecimal or octal representation, use
the built-in functions :func:`hex` or :func:`oct`.  For fancy formatting, see
the :ref:`formatstrings` section, e.g. ``"{:04d}".format(144)`` yields
``'0144'`` and ``"{:.3f}".format(1/3)`` yields ``'0.333'``.  You may also use
:ref:`the % operator <string-formatting>` on strings.  See the library reference
manual for details.


How do I modify a string in place?
----------------------------------

You can't, because strings are immutable.  If you need an object with this
ability, try converting the string to a list or use the array module::

   >>> import io
   >>> s = "Hello, world"
   >>> a = list(s)
   >>> print a
   ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
   >>> a[7:] = list("there!")
   >>> ''.join(a)
   'Hello, there!'

   >>> import array
   >>> a = array.array('c', s)
   >>> print a
   array('c', 'Hello, world')
   >>> a[0] = 'y'; print a
   array('c', 'yello, world')
   >>> a.tostring()
   'yello, world'


How do I use strings to call functions/methods?
-----------------------------------------------

There are various techniques.

* The best is to use a dictionary that maps strings to functions.  The primary
  advantage of this technique is that the strings do not need to match the names
  of the functions.  This is also the primary technique used to emulate a case
  construct::

     def a():
         pass

     def b():
         pass

     dispatch = {'go': a, 'stop': b}  # Note lack of parens for funcs

     dispatch[get_input()]()  # Note trailing parens to call function

* Use the built-in function :func:`getattr`::

     import foo
     getattr(foo, 'bar')()

  Note that :func:`getattr` works on any object, including classes, class
  instances, modules, and so on.

  This is used in several places in the standard library, like this::

     class Foo:
         def do_foo(self):
             ...

         def do_bar(self):
             ...

     f = getattr(foo_instance, 'do_' + opname)
     f()


* Use :func:`locals` or :func:`eval` to resolve the function name::

     def myFunc():
         print "hello"

     fname = "myFunc"

     f = locals()[fname]
     f()

     f = eval(fname)
     f()

  Note: Using :func:`eval` is slow and dangerous.  If you don't have absolute
  control over the contents of the string, someone could pass a string that
  resulted in an arbitrary function being executed.

Is there an equivalent to Perl's chomp() for removing trailing newlines from strings?
-------------------------------------------------------------------------------------

Starting with Python 2.2, you can use ``S.rstrip("\r\n")`` to remove all
occurrences of any line terminator from the end of the string ``S`` without
removing other trailing whitespace.  If the string ``S`` represents more than
one line, with several empty lines at the end, the line terminators for all the
blank lines will be removed::

   >>> lines = ("line 1 \r\n"
   ...          "\r\n"
   ...          "\r\n")
   >>> lines.rstrip("\n\r")
   'line 1 '

Since this is typically only desired when reading text one line at a time, using
``S.rstrip()`` this way works well.

For older versions of Python, there are two partial substitutes:

- If you want to remove all trailing whitespace, use the ``rstrip()`` method of
  string objects.  This removes all trailing whitespace, not just a single
  newline.

- Otherwise, if there is only one line in the string ``S``, use
  ``S.splitlines()[0]``.


Is there a scanf() or sscanf() equivalent?
------------------------------------------

Not as such.

For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the :meth:`~str.split` method of string objects
and then convert decimal strings to numeric values using :func:`int` or
:func:`float`.  ``split()`` supports an optional "sep" parameter which is useful
if the line uses something other than whitespace as a separator.

For more complicated input parsing, regular expressions are more powerful
than C's :c:func:`sscanf` and better suited for the task.


What does 'UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)' mean?
------------------------------------------------------------------------------------------

This error indicates that your Python installation can handle only 7-bit ASCII
strings.  There are a couple ways to fix or work around the problem.

If your programs must handle data in arbitrary character set encodings, the
environment the application runs in will generally identify the encoding of the
data it is handing you.  You need to convert the input to Unicode data using
that encoding.  For example, a program that handles email or web input will
typically find character set encoding information in Content-Type headers.  This
can then be used to properly convert input data to Unicode. Assuming the string
referred to by ``value`` is encoded as UTF-8::

   value = unicode(value, "utf-8")

will return a Unicode object.  If the data is not correctly encoded as UTF-8,
the above call will raise a :exc:`UnicodeError` exception.

If you only want strings converted to Unicode which have non-ASCII data, you can
try converting them first assuming an ASCII encoding, and then generate Unicode
objects if that fails::

   try:
       x = unicode(value, "ascii")
   except UnicodeError:
       value = unicode(value, "utf-8")
   else:
       # value was valid ASCII data
       pass

It's possible to set a default encoding in a file called ``sitecustomize.py``
that's part of the Python library.  However, this isn't recommended because
changing the Python-wide default encoding may cause third-party extension
modules to fail.

Note that on Windows, there is an encoding known as "mbcs", which uses an
encoding specific to your current locale.  In many cases, and particularly when
working with COM, this may be an appropriate default encoding to use.


Sequences (Tuples/Lists)
========================

How do I convert between tuples and lists?
------------------------------------------

The type constructor ``tuple(seq)`` converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.

For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')``
yields ``('a', 'b', 'c')``.  If the argument is a tuple, it does not make a copy
but returns the same object, so it is cheap to call :func:`tuple` when you
aren't sure that an object is already a tuple.

The type constructor ``list(seq)`` converts any sequence or iterable into a list
with the same items in the same order.  For example, ``list((1, 2, 3))`` yields
``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``.  If the argument
is a list, it makes a copy just like ``seq[:]`` would.


What's a negative index?
------------------------

Python sequences are indexed with positive numbers and negative numbers.  For
positive numbers 0 is the first index 1 is the second index and so forth.  For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth.  Think of ``seq[-n]`` as the same as ``seq[len(seq)-n]``.

Using negative indices can be very convenient.  For example ``S[:-1]`` is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.


How do I iterate over a sequence in reverse order?
--------------------------------------------------

Use the :func:`reversed` built-in function, which is new in Python 2.4::

   for x in reversed(sequence):
       ...  # do something with x ...

This won't touch your original sequence, but build a new copy with reversed
order to iterate over.

With Python 2.3, you can use an extended slice syntax::

   for x in sequence[::-1]:
       ...  # do something with x ...


How do you remove duplicates from a list?
-----------------------------------------

See the Python Cookbook for a long discussion of many ways to do this:

   https://code.activestate.com/recipes/52560/

If you don't mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go::

   if mylist:
       mylist.sort()
       last = mylist[-1]
       for i in range(len(mylist)-2, -1, -1):
           if last == mylist[i]:
               del mylist[i]
           else:
               last = mylist[i]

If all elements of the list may be used as dictionary keys (i.e. they are all
hashable) this is often faster ::

   d = {}
   for x in mylist:
       d[x] = 1
   mylist = list(d.keys())

In Python 2.5 and later, the following is possible instead::

   mylist = list(set(mylist))

This converts the list into a set, thereby removing duplicates, and then back
into a list.


How do you make an array in Python?
-----------------------------------

Use a list::

   ["this", 1, "is", "an", "array"]

Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.

The ``array`` module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists.  Also
note that the Numeric extensions and others define array-like structures with
various characteristics as well.

To get Lisp-style linked lists, you can emulate cons cells using tuples::

   lisp_list = ("like",  ("this",  ("example", None) ) )

If mutability is desired, you could use lists instead of tuples.  Here the
analogue of lisp car is ``lisp_list[0]`` and the analogue of cdr is
``lisp_list[1]``.  Only do this if you're sure you really need to, because it's
usually a lot slower than using Python lists.


.. _faq-multidimensional-list:

How do I create a multidimensional list?
----------------------------------------

You probably tried to make a multidimensional array like this::

   >>> A = [[None] * 2] * 3

This looks correct if you print it::

   >>> A
   [[None, None], [None, None], [None, None]]

But when you assign a value, it shows up in multiple places:

  >>> A[0][0] = 5
  >>> A
  [[5, None], [5, None], [5, None]]

The reason is that replicating a list with ``*`` doesn't create copies, it only
creates references to the existing objects.  The ``*3`` creates a list
containing 3 references to the same list of length two.  Changes to one row will
show in all rows, which is almost certainly not what you want.

The suggested approach is to create a list of the desired length first and then
fill in each element with a newly created list::

   A = [None] * 3
   for i in range(3):
       A[i] = [None] * 2

This generates a list containing 3 different lists of length two.  You can also
use a list comprehension::

   w, h = 2, 3
   A = [[None] * w for i in range(h)]

Or, you can use an extension that provides a matrix datatype; `NumPy
<http://www.numpy.org/>`_ is the best known.


How do I apply a method to a sequence of objects?
-------------------------------------------------

Use a list comprehension::

   result = [obj.method() for obj in mylist]

More generically, you can try the following function::

   def method_map(objects, method, arguments):
       """method_map([a,b], "meth", (1,2)) gives [a.meth(1,2), b.meth(1,2)]"""
       nobjects = len(objects)
       methods = map(getattr, objects, [method]*nobjects)
       return map(apply, methods, [arguments]*nobjects)


Why does a_tuple[i] += ['item'] raise an exception when the addition works?
---------------------------------------------------------------------------

This is because of a combination of the fact that augmented assignment
operators are *assignment* operators, and the difference between mutable and
immutable objects in Python.

This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we'll use
a ``list`` and ``+=`` as our exemplar.

If you wrote::

   >>> a_tuple = (1, 2)
   >>> a_tuple[0] += 1
   Traceback (most recent call last):
      ...
   TypeError: 'tuple' object does not support item assignment

The reason for the exception should be immediately clear: ``1`` is added to the
object ``a_tuple[0]`` points to (``1``), producing the result object, ``2``,
but when we attempt to assign the result of the computation, ``2``, to element
``0`` of the tuple, we get an error because we can't change what an element of
a tuple points to.

Under the covers, what this augmented assignment statement is doing is
approximately this::

   >>> result = a_tuple[0] + 1
   >>> a_tuple[0] = result
   Traceback (most recent call last):
     ...
   TypeError: 'tuple' object does not support item assignment

It is the assignment part of the operation that produces the error, since a
tuple is immutable.

When you write something like::

   >>> a_tuple = (['foo'], 'bar')
   >>> a_tuple[0] += ['item']
   Traceback (most recent call last):
     ...
   TypeError: 'tuple' object does not support item assignment

The exception is a bit more surprising, and even more surprising is the fact
that even though there was an error, the append worked::

    >>> a_tuple[0]
    ['foo', 'item']

To see why this happens, you need to know that (a) if an object implements an
``__iadd__`` magic method, it gets called when the ``+=`` augmented assignment
is executed, and its return value is what gets used in the assignment statement;
and (b) for lists, ``__iadd__`` is equivalent to calling ``extend`` on the list
and returning the list.  That's why we say that for lists, ``+=`` is a
"shorthand" for ``list.extend``::

    >>> a_list = []
    >>> a_list += [1]
    >>> a_list
    [1]

This is equivalent to::

    >>> result = a_list.__iadd__([1])
    >>> a_list = result

The object pointed to by a_list has been mutated, and the pointer to the
mutated object is assigned back to ``a_list``.  The end result of the
assignment is a no-op, since it is a pointer to the same object that ``a_list``
was previously pointing to, but the assignment still happens.

Thus, in our tuple example what is happening is equivalent to::

   >>> result = a_tuple[0].__iadd__(['item'])
   >>> a_tuple[0] = result
   Traceback (most recent call last):
     ...
   TypeError: 'tuple' object does not support item assignment

The ``__iadd__`` succeeds, and thus the list is extended, but even though
``result`` points to the same object that ``a_tuple[0]`` already points to,
that final assignment still results in an error, because tuples are immutable.


Dictionaries
============

How can I get a dictionary to display its keys in a consistent order?
---------------------------------------------------------------------

You can't.  Dictionaries store their keys in an unpredictable order, so the
display order of a dictionary's elements will be similarly unpredictable.

This can be frustrating if you want to save a printable version to a file, make
some changes and then compare it with some other printed dictionary.  In this
case, use the ``pprint`` module to pretty-print the dictionary; the items will
be presented in order sorted by the key.

A more complicated solution is to subclass ``dict`` to create a
``SortedDict`` class that prints itself in a predictable order.  Here's one
simpleminded implementation of such a class::

   class SortedDict(dict):
       def __repr__(self):
           keys = sorted(self.keys())
           result = ("{!r}: {!r}".format(k, self[k]) for k in keys)
           return "{{{}}}".format(", ".join(result))

       __str__ = __repr__

This will work for many common situations you might encounter, though it's far
from a perfect solution. The largest flaw is that if some values in the
dictionary are also dictionaries, their values won't be presented in any
particular order.


I want to do a complicated sort: can you do a Schwartzian Transform in Python?
------------------------------------------------------------------------------

The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its "sort value". In
Python, use the ``key`` argument for the :func:`sort()` function::

   Isorted = L[:]
   Isorted.sort(key=lambda s: int(s[10:15]))


How can I sort one list by values from another list?
----------------------------------------------------

Merge them into a single list of tuples, sort the resulting list, and then pick
out the element you want. ::

   >>> list1 = ["what", "I'm", "sorting", "by"]
   >>> list2 = ["something", "else", "to", "sort"]
   >>> pairs = zip(list1, list2)
   >>> pairs
   [('what', 'something'), ("I'm", 'else'), ('sorting', 'to'), ('by', 'sort')]
   >>> pairs.sort()
   >>> result = [ x[1] for x in pairs ]
   >>> result
   ['else', 'sort', 'to', 'something']

An alternative for the last step is::

   >>> result = []
   >>> for p in pairs: result.append(p[1])

If you find this more legible, you might prefer to use this instead of the final
list comprehension.  However, it is almost twice as slow for long lists.  Why?
First, the ``append()`` operation has to reallocate memory, and while it uses
some tricks to avoid doing that each time, it still has to do it occasionally,
and that costs quite a bit.  Second, the expression "result.append" requires an
extra attribute lookup, and third, there's a speed reduction from having to make
all those function calls.


Objects
=======

What is a class?
----------------

A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.

A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance.  You might have a
generic ``Mailbox`` class that provides basic accessor methods for a mailbox,
and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, ``OutlookMailbox``
that handle various specific mailbox formats.


What is a method?
-----------------

A method is a function on some object ``x`` that you normally call as
``x.name(arguments...)``.  Methods are defined as functions inside the class
definition::

   class C:
       def meth(self, arg):
           return arg * 2 + self.attribute


What is self?
-------------

Self is merely a conventional name for the first argument of a method.  A method
defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, c)`` for
some instance ``x`` of the class in which the definition occurs; the called
method will think it is called as ``meth(x, a, b, c)``.

See also :ref:`why-self`.


How do I check if an object is an instance of a given class or of a subclass of it?
-----------------------------------------------------------------------------------

Use the built-in function ``isinstance(obj, cls)``.  You can check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, e.g. ``isinstance(obj, (class1, class2, ...))``, and can also
check whether an object is one of Python's built-in types, e.g.
``isinstance(obj, str)`` or ``isinstance(obj, (int, long, float, complex))``.

Note that most programs do not use :func:`isinstance` on user-defined classes
very often.  If you are developing the classes yourself, a more proper
object-oriented style is to define methods on the classes that encapsulate a
particular behaviour, instead of checking the object's class and doing a
different thing based on what class it is.  For example, if you have a function
that does something::

   def search(obj):
       if isinstance(obj, Mailbox):
           ...  # code to search a mailbox
       elif isinstance(obj, Document):
           ...  # code to search a document
       elif ...

A better approach is to define a ``search()`` method on all the classes and just
call it::

   class Mailbox:
       def search(self):
           ...  # code to search a mailbox

   class Document:
       def search(self):
           ...  # code to search a document

   obj.search()


What is delegation?
-------------------

Delegation is an object oriented technique (also called a design pattern).
Let's say you have an object ``x`` and want to change the behaviour of just one
of its methods.  You can create a new class that provides a new implementation
of the method you're interested in changing and delegates all other methods to
the corresponding method of ``x``.

Python programmers can easily implement delegation.  For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase::

   class UpperOut:

       def __init__(self, outfile):
           self._outfile = outfile

       def write(self, s):
           self._outfile.write(s.upper())

       def __getattr__(self, name):
           return getattr(self._outfile, name)

Here the ``UpperOut`` class redefines the ``write()`` method to convert the
argument string to uppercase before calling the underlying
``self.__outfile.write()`` method.  All other methods are delegated to the
underlying ``self.__outfile`` object.  The delegation is accomplished via the
``__getattr__`` method; consult :ref:`the language reference <attribute-access>`
for more information about controlling attribute access.

Note that for more general cases delegation can get trickier. When attributes
must be set as well as retrieved, the class must define a :meth:`__setattr__`
method too, and it must do so carefully.  The basic implementation of
:meth:`__setattr__` is roughly equivalent to the following::

   class X:
       ...
       def __setattr__(self, name, value):
           self.__dict__[name] = value
       ...

Most :meth:`__setattr__` implementations must modify ``self.__dict__`` to store
local state for self without causing an infinite recursion.


How do I call a method defined in a base class from a derived class that overrides it?
--------------------------------------------------------------------------------------

If you're using new-style classes, use the built-in :func:`super` function::

   class Derived(Base):
       def meth(self):
           super(Derived, self).meth()

If you're using classic classes: For a class definition such as ``class
Derived(Base): ...`` you can call method ``meth()`` defined in ``Base`` (or one
of ``Base``'s base classes) as ``Base.meth(self, arguments...)``.  Here,
``Base.meth`` is an unbound method, so you need to provide the ``self``
argument.


How can I organize my code to make it easier to change the base class?
----------------------------------------------------------------------

You could define an alias for the base class, assign the real base class to it
before your class definition, and use the alias throughout your class.  Then all
you have to change is the value assigned to the alias.  Incidentally, this trick
is also handy if you want to decide dynamically (e.g. depending on availability
of resources) which base class to use.  Example::

   BaseAlias = <real base class>

   class Derived(BaseAlias):
       def meth(self):
           BaseAlias.meth(self)
           ...


How do I create static class data and static class methods?
-----------------------------------------------------------

Both static data and static methods (in the sense of C++ or Java) are supported
in Python.

For static data, simply define a class attribute.  To assign a new value to the
attribute, you have to explicitly use the class name in the assignment::

   class C:
       count = 0   # number of times C.__init__ called

       def __init__(self):
           C.count = C.count + 1

       def getcount(self):
           return C.count  # or return self.count

``c.count`` also refers to ``C.count`` for any ``c`` such that ``isinstance(c,
C)`` holds, unless overridden by ``c`` itself or by some class on the base-class
search path from ``c.__class__`` back to ``C``.

Caution: within a method of C, an assignment like ``self.count = 42`` creates a
new and unrelated instance named "count" in ``self``'s own dict.  Rebinding of a
class-static data name must always specify the class whether inside a method or
not::

   C.count = 314

Static methods are possible since Python 2.2::

   class C:
       def static(arg1, arg2, arg3):
           # No 'self' parameter!
           ...
       static = staticmethod(static)

With Python 2.4's decorators, this can also be written as ::

   class C:
       @staticmethod
       def static(arg1, arg2, arg3):
           # No 'self' parameter!
           ...

However, a far more straightforward way to get the effect of a static method is
via a simple module-level function::

   def getcount():
       return C.count

If your code is structured so as to define one class (or tightly related class
hierarchy) per module, this supplies the desired encapsulation.


How can I overload constructors (or methods) in Python?
-------------------------------------------------------

This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.

In C++ you'd write

.. code-block:: c

    class C {
        C() { cout << "No arguments\n"; }
        C(int i) { cout << "Argument is " << i << "\n"; }
    }

In Python you have to write a single constructor that catches all cases using
default arguments.  For example::

   class C:
       def __init__(self, i=None):
           if i is None:
               print "No arguments"
           else:
               print "Argument is", i

This is not entirely equivalent, but close enough in practice.

You could also try a variable-length argument list, e.g. ::

   def __init__(self, *args):
       ...

The same approach works for all method definitions.


I try to use __spam and I get an error about _SomeClassName__spam.
------------------------------------------------------------------

Variable names with double leading underscores are "mangled" to provide a simple
but effective way to define class private variables.  Any identifier of the form
``__spam`` (at least two leading underscores, at most one trailing underscore)
is textually replaced with ``_classname__spam``, where ``classname`` is the
current class name with any leading underscores stripped.

This doesn't guarantee privacy: an outside user can still deliberately access
the "_classname__spam" attribute, and private values are visible in the object's
``__dict__``.  Many Python programmers never bother to use private variable
names at all.


My class defines __del__ but it is not called when I delete the object.
-----------------------------------------------------------------------

There are several possible reasons for this.

The del statement does not necessarily call :meth:`__del__` -- it simply
decrements the object's reference count, and if this reaches zero
:meth:`__del__` is called.

If your data structures contain circular links (e.g. a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero.  Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
reference to your data structure vanishes, so your :meth:`__del__` method may be
called at an inconvenient and random time. This is inconvenient if you're trying
to reproduce a problem. Worse, the order in which object's :meth:`__del__`
methods are executed is arbitrary.  You can run :func:`gc.collect` to force a
collection, but there *are* pathological cases where objects will never be
collected.

Despite the cycle collector, it's still a good idea to define an explicit
``close()`` method on objects to be called whenever you're done with them.  The
``close()`` method can then remove attributes that refer to subobjecs.  Don't
call :meth:`__del__` directly -- :meth:`__del__` should call ``close()`` and
``close()`` should make sure that it can be called more than once for the same
object.

Another way to avoid cyclical references is to use the :mod:`weakref` module,
which allows you to point to objects without incrementing their reference count.
Tree data structures, for instance, should use weak references for their parent
and sibling references (if they need them!).

If the object has ever been a local variable in a function that caught an
expression in an except clause, chances are that a reference to the object still
exists in that function's stack frame as contained in the stack trace.
Normally, calling :func:`sys.exc_clear` will take care of this by clearing the
last recorded exception.

Finally, if your :meth:`__del__` method raises an exception, a warning message
is printed to :data:`sys.stderr`.


How do I get a list of all instances of a given class?
------------------------------------------------------

Python does not keep track of all instances of a class (or of a built-in type).
You can program the class's constructor to keep track of all instances by
keeping a list of weak references to each instance.


Why does the result of ``id()`` appear to be not unique?
--------------------------------------------------------

The :func:`id` builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object's memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory.  This
is illustrated by this example:

>>> id(1000)
13901272
>>> id(2000)
13901272

The two ids belong to different integer objects that are created before, and
deleted immediately after execution of the ``id()`` call.  To be sure that
objects whose id you want to examine are still alive, create another reference
to the object:

>>> a = 1000; b = 2000
>>> id(a)
13901272
>>> id(b)
13891296


Modules
=======

How do I create a .pyc file?
----------------------------

When a module is imported for the first time (or when the source is more recent
than the current compiled file) a ``.pyc`` file containing the compiled code
should be created in the same directory as the ``.py`` file.

One reason that a ``.pyc`` file may not be created is permissions problems with
the directory. This can happen, for example, if you develop as one user but run
as another, such as if you are testing with a web server.  Creation of a .pyc
file is automatic if you're importing a module and Python has the ability
(permissions, free space, etc...) to write the compiled module back to the
directory.

Running Python on a top level script is not considered an import and no
``.pyc`` will be created.  For example, if you have a top-level module
``foo.py`` that imports another module ``xyz.py``, when you run ``foo``,
``xyz.pyc`` will be created since ``xyz`` is imported, but no ``foo.pyc`` file
will be created since ``foo.py`` isn't being imported.

If you need to create ``foo.pyc`` -- that is, to create a ``.pyc`` file for a module
that is not imported -- you can, using the :mod:`py_compile` and
:mod:`compileall` modules.

The :mod:`py_compile` module can manually compile any module.  One way is to use
the ``compile()`` function in that module interactively::

   >>> import py_compile
   >>> py_compile.compile('foo.py')                 # doctest: +SKIP

This will write the ``.pyc`` to the same location as ``foo.py`` (or you can
override that with the optional parameter ``cfile``).

You can also automatically compile all files in a directory or directories using
the :mod:`compileall` module.  You can do it from the shell prompt by running
``compileall.py`` and providing the path of a directory containing Python files
to compile::

       python -m compileall .


How do I find the current module name?
--------------------------------------

A module can find out its own module name by looking at the predefined global
variable ``__name__``.  If this has the value ``'__main__'``, the program is
running as a script.  Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking ``__name__``::

   def main():
       print 'Running test...'
       ...

   if __name__ == '__main__':
       main()


How can I have modules that mutually import each other?
-------------------------------------------------------

Suppose you have the following modules:

foo.py::

   from bar import bar_var
   foo_var = 1

bar.py::

   from foo import foo_var
   bar_var = 2

The problem is that the interpreter will perform the following steps:

* main imports foo
* Empty globals for foo are created
* foo is compiled and starts executing
* foo imports bar
* Empty globals for bar are created
* bar is compiled and starts executing
* bar imports foo (which is a no-op since there already is a module named foo)
* bar.foo_var = foo.foo_var

The last step fails, because Python isn't done with interpreting ``foo`` yet and
the global symbol dictionary for ``foo`` is still empty.

The same thing happens when you use ``import foo``, and then try to access
``foo.foo_var`` in global code.

There are (at least) three possible workarounds for this problem.

Guido van Rossum recommends avoiding all uses of ``from <module> import ...``,
and placing all code inside functions.  Initializations of global variables and
class variables should use constants or built-in functions only.  This means
everything from an imported module is referenced as ``<module>.<name>``.

Jim Roskind suggests performing steps in the following order in each module:

* exports (globals, functions, and classes that don't need imported base
  classes)
* ``import`` statements
* active code (including globals that are initialized from imported values).

van Rossum doesn't like this approach much because the imports appear in a
strange place, but it does work.

Matthias Urlichs recommends restructuring your code so that the recursive import
is not necessary in the first place.

These solutions are not mutually exclusive.


__import__('x.y.z') returns <module 'x'>; how do I get z?
---------------------------------------------------------

Consider using the convenience function :func:`~importlib.import_module` from
:mod:`importlib` instead::

   z = importlib.import_module('x.y.z')


When I edit an imported module and reimport it, the changes don't show up.  Why does this happen?
-------------------------------------------------------------------------------------------------

For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported.  If it didn't, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times.  To force rereading of a
changed module, do this::

   import modname
   reload(modname)

Warning: this technique is not 100% fool-proof.  In particular, modules
containing statements like ::

   from modname import some_objects

will continue to work with the old version of the imported objects.  If the
module contains class definitions, existing class instances will *not* be
updated to use the new class definition.  This can result in the following
paradoxical behaviour:

   >>> import cls
   >>> c = cls.C()                # Create an instance of C
   >>> reload(cls)
   <module 'cls' from 'cls.pyc'>
   >>> isinstance(c, cls.C)       # isinstance is false?!?
   False

The nature of the problem is made clear if you print out the class objects:

   >>> c.__class__
   <class cls.C at 0x7352a0>
   >>> cls.C
   <class cls.C at 0x4198d0>

PK	%�\���6�6!html/_sources/faq/windows.rst.txtnu�[���:tocdepth: 2

.. _windows-faq:

=====================
Python on Windows FAQ
=====================

.. only:: html

   .. contents::

How do I run a Python program under Windows?
--------------------------------------------

This is not necessarily a straightforward question. If you are already familiar
with running programs from the Windows command line then everything will seem
obvious; otherwise, you might need a little more guidance.

Unless you use some sort of integrated development environment, you will end up
*typing* Windows commands into what is variously referred to as a "DOS window"
or "Command prompt window".  Usually you can create such a window from your
Start menu; under Windows 7 the menu selection is :menuselection:`Start -->
Programs --> Accessories --> Command Prompt`.  You should be able to recognize
when you have started such a window because you will see a Windows "command
prompt", which usually looks like this::

   C:\>

The letter may be different, and there might be other things after it, so you
might just as easily see something like::

   D:\YourName\Projects\Python>

depending on how your computer has been set up and what else you have recently
done with it.  Once you have started such a window, you are well on the way to
running Python programs.

You need to realize that your Python scripts have to be processed by another
program called the Python *interpreter*.  The interpreter reads your script,
compiles it into bytecodes, and then executes the bytecodes to run your
program. So, how do you arrange for the interpreter to handle your Python?

First, you need to make sure that your command window recognises the word
"python" as an instruction to start the interpreter.  If you have opened a
command window, you should try entering the command ``python`` and hitting
return.::

   C:\Users\YourName> python

You should then see something like::

   Python 2.7.3 (default, Apr 10 2012, 22.71:26) [MSC v.1500 32 bit (Intel)] on win32
   Type "help", "copyright", "credits" or "license" for more information.
   >>>

You have started the interpreter in "interactive mode". That means you can enter
Python statements or expressions interactively and have them executed or
evaluated while you wait.  This is one of Python's strongest features.  Check it
by entering a few expressions of your choice and seeing the results::

    >>> print "Hello"
    Hello
    >>> "Hello" * 3
    'HelloHelloHello'

Many people use the interactive mode as a convenient yet highly programmable
calculator.  When you want to end your interactive Python session, hold the :kbd:`Ctrl`
key down while you enter a :kbd:`Z`, then hit the ":kbd:`Enter`" key to get back to your
Windows command prompt.

You may also find that you have a Start-menu entry such as :menuselection:`Start
--> Programs --> Python 2.7 --> Python (command line)` that results in you
seeing the ``>>>`` prompt in a new window.  If so, the window will disappear
after you enter the :kbd:`Ctrl-Z` character; Windows is running a single "python"
command in the window, and closes it when you terminate the interpreter.

If the ``python`` command, instead of displaying the interpreter prompt ``>>>``,
gives you a message like::

   'python' is not recognized as an internal or external command, operable program or batch file.

or::

   Bad command or filename

then you need to make sure that your computer knows where to find the Python
interpreter.  To do this you will have to modify a setting called PATH, which is
a list of directories where Windows will look for programs.

You should arrange for Python's installation directory to be added to the PATH
of every command window as it starts.  If you installed Python fairly recently
then the command ::

   dir C:\py*

will probably tell you where it is installed; the usual location is something
like ``C:\Python27``.  Otherwise you will be reduced to a search of your whole
disk ... use :menuselection:`Tools --> Find` or hit the :guilabel:`Search`
button and look for "python.exe".  Supposing you discover that Python is
installed in the ``C:\Python27`` directory (the default at the time of writing),
you should make sure that entering the command ::

   c:\Python27\python

starts up the interpreter as above (and don't forget you'll need a ":kbd:`Ctrl-Z`" and
an ":kbd:`Enter`" to get out of it). Once you have verified the directory, you can
add it to the system path to make it easier to start Python by just running
the ``python`` command. This is currently an option in the installer as of
CPython 2.7.

More information about environment variables can be found on the
:ref:`Using Python on Windows <setting-envvars>` page.

How do I make Python scripts executable?
----------------------------------------

On Windows, the standard Python installer already associates the .py
extension with a file type (Python.File) and gives that file type an open
command that runs the interpreter (``D:\Program Files\Python\python.exe "%1"
%*``).  This is enough to make scripts executable from the command prompt as
'foo.py'.  If you'd rather be able to execute the script by simple typing 'foo'
with no extension you need to add .py to the PATHEXT environment variable.

Why does Python sometimes take so long to start?
------------------------------------------------

Usually Python starts very quickly on Windows, but occasionally there are bug
reports that Python suddenly begins to take a long time to start up.  This is
made even more puzzling because Python will work fine on other Windows systems
which appear to be configured identically.

The problem may be caused by a misconfiguration of virus checking software on
the problem machine.  Some virus scanners have been known to introduce startup
overhead of two orders of magnitude when the scanner is configured to monitor
all reads from the filesystem.  Try checking the configuration of virus scanning
software on your systems to ensure that they are indeed configured identically.
McAfee, when configured to scan all file system read activity, is a particular
offender.


How do I make an executable from a Python script?
-------------------------------------------------

See http://www.py2exe.org/ for a distutils extension that allows you
to create console and GUI executables from Python code.

Is a ``*.pyd`` file the same as a DLL?
--------------------------------------

.. XXX update for py3k (PyInit_foo)

Yes, .pyd files are dll's, but there are a few differences.  If you have a DLL
named ``foo.pyd``, then it must have a function ``initfoo()``.  You can then
write Python "import foo", and Python will search for foo.pyd (as well as
foo.py, foo.pyc) and if it finds it, will attempt to call ``initfoo()`` to
initialize it.  You do not link your .exe with foo.lib, as that would cause
Windows to require the DLL to be present.

Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
that Windows uses to search for foo.dll.  Also, foo.pyd need not be present to
run your program, whereas if you linked your program with a dll, the dll is
required.  Of course, foo.pyd is required if you want to say ``import foo``.  In
a DLL, linkage is declared in the source code with ``__declspec(dllexport)``.
In a .pyd, linkage is defined in a list of available functions.


How can I embed Python into a Windows application?
--------------------------------------------------

Embedding the Python interpreter in a Windows app can be summarized as follows:

1. Do _not_ build Python into your .exe file directly.  On Windows, Python must
   be a DLL to handle importing modules that are themselves DLL's.  (This is the
   first key undocumented fact.)  Instead, link to :file:`python{NN}.dll`; it is
   typically installed in ``C:\Windows\System``.  *NN* is the Python version, a
   number such as "27" for Python 2.7.

   You can link to Python in two different ways.  Load-time linking means
   linking against :file:`python{NN}.lib`, while run-time linking means linking
   against :file:`python{NN}.dll`.  (General note: :file:`python{NN}.lib` is the
   so-called "import lib" corresponding to :file:`python{NN}.dll`.  It merely
   defines symbols for the linker.)

   Run-time linking greatly simplifies link options; everything happens at run
   time.  Your code must load :file:`python{NN}.dll` using the Windows
   ``LoadLibraryEx()`` routine.  The code must also use access routines and data
   in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
   by the Windows ``GetProcAddress()`` routine.  Macros can make using these
   pointers transparent to any C code that calls routines in Python's C API.

   Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
   first.

   .. XXX what about static linking?

2. If you use SWIG, it is easy to create a Python "extension module" that will
   make the app's data and methods available to Python.  SWIG will handle just
   about all the grungy details for you.  The result is C code that you link
   *into* your .exe file (!)  You do _not_ have to create a DLL file, and this
   also simplifies linking.

3. SWIG will create an init function (a C function) whose name depends on the
   name of the extension module.  For example, if the name of the module is leo,
   the init function will be called initleo().  If you use SWIG shadow classes,
   as you should, the init function will be called initleoc().  This initializes
   a mostly hidden helper class used by the shadow class.

   The reason you can link the C code in step 2 into your .exe file is that
   calling the initialization function is equivalent to importing the module
   into Python! (This is the second key undocumented fact.)

4. In short, you can use the following code to initialize the Python interpreter
   with your extension module.

   .. code-block:: c

      #include "python.h"
      ...
      Py_Initialize();  // Initialize Python.
      initmyAppc();  // Initialize (import) the helper class.
      PyRun_SimpleString("import myApp");  // Import the shadow class.

5. There are two problems with Python's C API which will become apparent if you
   use a compiler other than MSVC, the compiler used to build pythonNN.dll.

   Problem 1: The so-called "Very High Level" functions that take FILE *
   arguments will not work in a multi-compiler environment because each
   compiler's notion of a struct FILE will be different.  From an implementation
   standpoint these are very _low_ level functions.

   Problem 2: SWIG generates the following code when generating wrappers to void
   functions:

   .. code-block:: c

      Py_INCREF(Py_None);
      _resultobj = Py_None;
      return _resultobj;

   Alas, Py_None is a macro that expands to a reference to a complex data
   structure called _Py_NoneStruct inside pythonNN.dll.  Again, this code will
   fail in a mult-compiler environment.  Replace such code by:

   .. code-block:: c

      return Py_BuildValue("");

   It may be possible to use SWIG's ``%typemap`` command to make the change
   automatically, though I have not been able to get this to work (I'm a
   complete SWIG newbie).

6. Using a Python shell script to put up a Python interpreter window from inside
   your Windows app is not a good idea; the resulting window will be independent
   of your app's windowing system.  Rather, you (or the wxPythonWindow class)
   should create a "native" interpreter window.  It is easy to connect that
   window to the Python interpreter.  You can redirect Python's i/o to _any_
   object that supports read and write, so all you need is a Python object
   (defined in your extension module) that contains read() and write() methods.

How do I keep editors from inserting tabs into my Python source?
----------------------------------------------------------------

The FAQ does not recommend using tabs, and the Python style guide, :pep:`8`,
recommends 4 spaces for distributed Python code; this is also the Emacs
python-mode default.

Under any editor, mixing tabs and spaces is a bad idea.  MSVC is no different in
this respect, and is easily configured to use spaces: Take :menuselection:`Tools
--> Options --> Tabs`, and for file type "Default" set "Tab size" and "Indent
size" to 4, and select the "Insert spaces" radio button.

If you suspect mixed tabs and spaces are causing problems in leading whitespace,
run Python with the :option:`-t` switch or run the :mod:`tabnanny` module to
check a directory tree in batch mode.


How do I check for a keypress without blocking?
-----------------------------------------------

Use the msvcrt module.  This is a standard Windows-specific extension module.
It defines a function ``kbhit()`` which checks whether a keyboard hit is
present, and ``getch()`` which gets one character without echoing it.


How do I emulate os.kill() in Windows?
--------------------------------------

Prior to Python 2.7 and 3.2, to terminate a process, you can use :mod:`ctypes`::

   import ctypes

   def kill(pid):
       """kill function for Win32"""
       kernel32 = ctypes.windll.kernel32
       handle = kernel32.OpenProcess(1, 0, pid)
       return (0 != kernel32.TerminateProcess(handle, 0))

In 2.7 and 3.2, :func:`os.kill` is implemented similar to the above function,
with the additional feature of being able to send :kbd:`Ctrl+C` and :kbd:`Ctrl+Break`
to console subprocesses which are designed to handle those signals. See
:func:`os.kill` for further details.

How do I extract the downloaded documentation on Windows?
---------------------------------------------------------

Sometimes, when you download the documentation package to a Windows machine
using a web browser, the file extension of the saved file ends up being .EXE.
This is a mistake; the extension should be .TGZ.

Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
able to handle it.  (If your copy of WinZip doesn't, get a newer one from
https://www.winzip.com.)

PK	%�\���\�\$html/_sources/howto/argparse.rst.txtnu�[���*****************
Argparse Tutorial
*****************

:author: Tshepang Lekhonkhobe

.. _argparse-tutorial:

This tutorial is intended to be a gentle introduction to :mod:`argparse`, the
recommended command-line parsing module in the Python standard library.
This was written for argparse in Python 3. A few details are different in 2.x,
especially some exception messages, which were improved in 3.x.

.. note::

   There are two other modules that fulfill the same task, namely
   :mod:`getopt` (an equivalent for :c:func:`getopt` from the C
   language) and the deprecated :mod:`optparse`.
   Note also that :mod:`argparse` is based on :mod:`optparse`,
   and therefore very similar in terms of usage.


Concepts
========

Let's show the sort of functionality that we are going to explore in this
introductory tutorial by making use of the :command:`ls` command:

.. code-block:: sh

   $ ls
   cpython  devguide  prog.py  pypy  rm-unused-function.patch
   $ ls pypy
   ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
   $ ls -l
   total 20
   drwxr-xr-x 19 wena wena 4096 Feb 18 18:51 cpython
   drwxr-xr-x  4 wena wena 4096 Feb  8 12:04 devguide
   -rwxr-xr-x  1 wena wena  535 Feb 19 00:05 prog.py
   drwxr-xr-x 14 wena wena 4096 Feb  7 00:59 pypy
   -rw-r--r--  1 wena wena  741 Feb 18 01:01 rm-unused-function.patch
   $ ls --help
   Usage: ls [OPTION]... [FILE]...
   List information about the FILEs (the current directory by default).
   Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
   ...

A few concepts we can learn from the four commands:

* The :command:`ls` command is useful when run without any options at all. It defaults
  to displaying the contents of the current directory.

* If we want beyond what it provides by default, we tell it a bit more. In
  this case, we want it to display a different directory, ``pypy``.
  What we did is specify what is known as a positional argument. It's named so
  because the program should know what to do with the value, solely based on
  where it appears on the command line. This concept is more relevant
  to a command like :command:`cp`, whose most basic usage is ``cp SRC DEST``.
  The first position is *what you want copied,* and the second
  position is *where you want it copied to*.

* Now, say we want to change behaviour of the program. In our example,
  we display more info for each file instead of just showing the file names.
  The ``-l`` in that case is known as an optional argument.

* That's a snippet of the help text. It's very useful in that you can
  come across a program you have never used before, and can figure out
  how it works simply by reading its help text.


The basics
==========

Let us start with a very simple example which does (almost) nothing::

   import argparse
   parser = argparse.ArgumentParser()
   parser.parse_args()

Following is a result of running the code:

.. code-block:: sh

   $ python prog.py
   $ python prog.py --help
   usage: prog.py [-h]

   optional arguments:
     -h, --help  show this help message and exit
   $ python prog.py --verbose
   usage: prog.py [-h]
   prog.py: error: unrecognized arguments: --verbose
   $ python prog.py foo
   usage: prog.py [-h]
   prog.py: error: unrecognized arguments: foo

Here is what is happening:

* Running the script without any options results in nothing displayed to
  stdout. Not so useful.

* The second one starts to display the usefulness of the :mod:`argparse`
  module. We have done almost nothing, but already we get a nice help message.

* The ``--help`` option, which can also be shortened to ``-h``, is the only
  option we get for free (i.e. no need to specify it). Specifying anything
  else results in an error. But even then, we do get a useful usage message,
  also for free.


Introducing Positional arguments
================================

An example::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("echo")
   args = parser.parse_args()
   print args.echo

And running the code:

.. code-block:: sh

   $ python prog.py
   usage: prog.py [-h] echo
   prog.py: error: the following arguments are required: echo
   $ python prog.py --help
   usage: prog.py [-h] echo

   positional arguments:
     echo

   optional arguments:
     -h, --help  show this help message and exit
   $ python prog.py foo
   foo

Here is what's happening:

* We've added the :meth:`add_argument` method, which is what we use to specify
  which command-line options the program is willing to accept. In this case,
  I've named it ``echo`` so that it's in line with its function.

* Calling our program now requires us to specify an option.

* The :meth:`parse_args` method actually returns some data from the
  options specified, in this case, ``echo``.

* The variable is some form of 'magic' that :mod:`argparse` performs for free
  (i.e. no need to specify which variable that value is stored in).
  You will also notice that its name matches the string argument given
  to the method, ``echo``.

Note however that, although the help display looks nice and all, it currently
is not as helpful as it can be. For example we see that we got ``echo`` as a
positional argument, but we don't know what it does, other than by guessing or
by reading the source code. So, let's make it a bit more useful::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("echo", help="echo the string you use here")
   args = parser.parse_args()
   print args.echo

And we get:

.. code-block:: sh

   $ python prog.py -h
   usage: prog.py [-h] echo

   positional arguments:
     echo        echo the string you use here

   optional arguments:
     -h, --help  show this help message and exit

Now, how about doing something even more useful::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", help="display a square of a given number")
   args = parser.parse_args()
   print args.square**2

Following is a result of running the code:

.. code-block:: sh

   $ python prog.py 4
   Traceback (most recent call last):
     File "prog.py", line 5, in <module>
       print args.square**2
   TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

That didn't go so well. That's because :mod:`argparse` treats the options we
give it as strings, unless we tell it otherwise. So, let's tell
:mod:`argparse` to treat that input as an integer::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", help="display a square of a given number",
                       type=int)
   args = parser.parse_args()
   print args.square**2

Following is a result of running the code:

.. code-block:: sh

   $ python prog.py 4
   16
   $ python prog.py four
   usage: prog.py [-h] square
   prog.py: error: argument square: invalid int value: 'four'

That went well. The program now even helpfully quits on bad illegal input
before proceeding.


Introducing Optional arguments
==============================

So far we have been playing with positional arguments. Let us
have a look on how to add optional ones::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("--verbosity", help="increase output verbosity")
   args = parser.parse_args()
   if args.verbosity:
       print "verbosity turned on"

And the output:

.. code-block:: sh

   $ python prog.py --verbosity 1
   verbosity turned on
   $ python prog.py
   $ python prog.py --help
   usage: prog.py [-h] [--verbosity VERBOSITY]

   optional arguments:
     -h, --help            show this help message and exit
     --verbosity VERBOSITY
                           increase output verbosity
   $ python prog.py --verbosity
   usage: prog.py [-h] [--verbosity VERBOSITY]
   prog.py: error: argument --verbosity: expected one argument

Here is what is happening:

* The program is written so as to display something when ``--verbosity`` is
  specified and display nothing when not.

* To show that the option is actually optional, there is no error when running
  the program without it. Note that by default, if an optional argument isn't
  used, the relevant variable, in this case :attr:`args.verbosity`, is
  given ``None`` as a value, which is the reason it fails the truth
  test of the :keyword:`if` statement.

* The help message is a bit different.

* When using the ``--verbosity`` option, one must also specify some value,
  any value.

The above example accepts arbitrary integer values for ``--verbosity``, but for
our simple program, only two values are actually useful, ``True`` or ``False``.
Let's modify the code accordingly::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("--verbose", help="increase output verbosity",
                       action="store_true")
   args = parser.parse_args()
   if args.verbose:
      print "verbosity turned on"

And the output:

.. code-block:: sh

   $ python prog.py --verbose
   verbosity turned on
   $ python prog.py --verbose 1
   usage: prog.py [-h] [--verbose]
   prog.py: error: unrecognized arguments: 1
   $ python prog.py --help
   usage: prog.py [-h] [--verbose]

   optional arguments:
     -h, --help  show this help message and exit
     --verbose   increase output verbosity

Here is what is happening:

* The option is now more of a flag than something that requires a value.
  We even changed the name of the option to match that idea.
  Note that we now specify a new keyword, ``action``, and give it the value
  ``"store_true"``. This means that, if the option is specified,
  assign the value ``True`` to :data:`args.verbose`.
  Not specifying it implies ``False``.

* It complains when you specify a value, in true spirit of what flags
  actually are.

* Notice the different help text.


Short options
-------------

If you are familiar with command line usage,
you will notice that I haven't yet touched on the topic of short
versions of the options. It's quite simple::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("-v", "--verbose", help="increase output verbosity",
                       action="store_true")
   args = parser.parse_args()
   if args.verbose:
       print "verbosity turned on"

And here goes:

.. code-block:: sh

   $ python prog.py -v
   verbosity turned on
   $ python prog.py --help
   usage: prog.py [-h] [-v]

   optional arguments:
     -h, --help     show this help message and exit
     -v, --verbose  increase output verbosity

Note that the new ability is also reflected in the help text.


Combining Positional and Optional arguments
===========================================

Our program keeps growing in complexity::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display a square of a given number")
   parser.add_argument("-v", "--verbose", action="store_true",
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2
   if args.verbose:
       print "the square of {} equals {}".format(args.square, answer)
   else:
       print answer

And now the output:

.. code-block:: sh

   $ python prog.py
   usage: prog.py [-h] [-v] square
   prog.py: error: the following arguments are required: square
   $ python prog.py 4
   16
   $ python prog.py 4 --verbose
   the square of 4 equals 16
   $ python prog.py --verbose 4
   the square of 4 equals 16

* We've brought back a positional argument, hence the complaint.

* Note that the order does not matter.

How about we give this program of ours back the ability to have
multiple verbosity values, and actually get to use them::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display a square of a given number")
   parser.add_argument("-v", "--verbosity", type=int,
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2
   if args.verbosity == 2:
       print "the square of {} equals {}".format(args.square, answer)
   elif args.verbosity == 1:
       print "{}^2 == {}".format(args.square, answer)
   else:
       print answer

And the output:

.. code-block:: sh

   $ python prog.py 4
   16
   $ python prog.py 4 -v
   usage: prog.py [-h] [-v VERBOSITY] square
   prog.py: error: argument -v/--verbosity: expected one argument
   $ python prog.py 4 -v 1
   4^2 == 16
   $ python prog.py 4 -v 2
   the square of 4 equals 16
   $ python prog.py 4 -v 3
   16

These all look good except the last one, which exposes a bug in our program.
Let's fix it by restricting the values the ``--verbosity`` option can accept::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display a square of a given number")
   parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2
   if args.verbosity == 2:
       print "the square of {} equals {}".format(args.square, answer)
   elif args.verbosity == 1:
       print "{}^2 == {}".format(args.square, answer)
   else:
       print answer

And the output:

.. code-block:: sh

   $ python prog.py 4 -v 3
   usage: prog.py [-h] [-v {0,1,2}] square
   prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
   $ python prog.py 4 -h
   usage: prog.py [-h] [-v {0,1,2}] square

   positional arguments:
     square                display a square of a given number

   optional arguments:
     -h, --help            show this help message and exit
     -v {0,1,2}, --verbosity {0,1,2}
                           increase output verbosity

Note that the change also reflects both in the error message as well as the
help string.

Now, let's use a different approach of playing with verbosity, which is pretty
common. It also matches the way the CPython executable handles its own
verbosity argument (check the output of ``python --help``)::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display the square of a given number")
   parser.add_argument("-v", "--verbosity", action="count",
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2
   if args.verbosity == 2:
       print "the square of {} equals {}".format(args.square, answer)
   elif args.verbosity == 1:
       print "{}^2 == {}".format(args.square, answer)
   else:
       print answer

We have introduced another action, "count",
to count the number of occurrences of a specific optional arguments:

.. code-block:: sh

   $ python prog.py 4
   16
   $ python prog.py 4 -v
   4^2 == 16
   $ python prog.py 4 -vv
   the square of 4 equals 16
   $ python prog.py 4 --verbosity --verbosity
   the square of 4 equals 16
   $ python prog.py 4 -v 1
   usage: prog.py [-h] [-v] square
   prog.py: error: unrecognized arguments: 1
   $ python prog.py 4 -h
   usage: prog.py [-h] [-v] square

   positional arguments:
     square           display a square of a given number

   optional arguments:
     -h, --help       show this help message and exit
     -v, --verbosity  increase output verbosity
   $ python prog.py 4 -vvv
   16

* Yes, it's now more of a flag (similar to ``action="store_true"``) in the
  previous version of our script. That should explain the complaint.

* It also behaves similar to "store_true" action.

* Now here's a demonstration of what the "count" action gives. You've probably
  seen this sort of usage before.

* And, just like the "store_true" action, if you don't specify the ``-v`` flag,
  that flag is considered to have ``None`` value.

* As should be expected, specifying the long form of the flag, we should get
  the same output.

* Sadly, our help output isn't very informative on the new ability our script
  has acquired, but that can always be fixed by improving the documentation for
  our script (e.g. via the ``help`` keyword argument).

* That last output exposes a bug in our program.


Let's fix::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display a square of a given number")
   parser.add_argument("-v", "--verbosity", action="count",
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2

   # bugfix: replace == with >=
   if args.verbosity >= 2:
       print "the square of {} equals {}".format(args.square, answer)
   elif args.verbosity >= 1:
       print "{}^2 == {}".format(args.square, answer)
   else:
       print answer

And this is what it gives:

.. code-block:: sh

   $ python prog.py 4 -vvv
   the square of 4 equals 16
   $ python prog.py 4 -vvvv
   the square of 4 equals 16
   $ python prog.py 4
   Traceback (most recent call last):
     File "prog.py", line 11, in <module>
       if args.verbosity >= 2:
   TypeError: unorderable types: NoneType() >= int()

* First output went well, and fixes the bug we had before.
  That is, we want any value >= 2 to be as verbose as possible.

* Third output not so good.

Let's fix that bug::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("square", type=int,
                       help="display a square of a given number")
   parser.add_argument("-v", "--verbosity", action="count", default=0,
                       help="increase output verbosity")
   args = parser.parse_args()
   answer = args.square**2
   if args.verbosity >= 2:
       print "the square of {} equals {}".format(args.square, answer)
   elif args.verbosity >= 1:
       print "{}^2 == {}".format(args.square, answer)
   else:
       print answer

We've just introduced yet another keyword, ``default``.
We've set it to ``0`` in order to make it comparable to the other int values.
Remember that by default,
if an optional argument isn't specified,
it gets the ``None`` value, and that cannot be compared to an int value
(hence the :exc:`TypeError` exception).

And:

.. code-block:: sh

   $ python prog.py 4
   16

You can go quite far just with what we've learned so far,
and we have only scratched the surface.
The :mod:`argparse` module is very powerful,
and we'll explore a bit more of it before we end this tutorial.


Getting a little more advanced
==============================

What if we wanted to expand our tiny program to perform other powers,
not just squares::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("x", type=int, help="the base")
   parser.add_argument("y", type=int, help="the exponent")
   parser.add_argument("-v", "--verbosity", action="count", default=0)
   args = parser.parse_args()
   answer = args.x**args.y
   if args.verbosity >= 2:
       print "{} to the power {} equals {}".format(args.x, args.y, answer)
   elif args.verbosity >= 1:
       print "{}^{} == {}".format(args.x, args.y, answer)
   else:
       print answer

Output:

.. code-block:: sh

   $ python prog.py
   usage: prog.py [-h] [-v] x y
   prog.py: error: the following arguments are required: x, y
   $ python prog.py -h
   usage: prog.py [-h] [-v] x y

   positional arguments:
     x                the base
     y                the exponent

   optional arguments:
     -h, --help       show this help message and exit
     -v, --verbosity
   $ python prog.py 4 2 -v
   4^2 == 16


Notice that so far we've been using verbosity level to *change* the text
that gets displayed. The following example instead uses verbosity level
to display *more* text instead::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument("x", type=int, help="the base")
   parser.add_argument("y", type=int, help="the exponent")
   parser.add_argument("-v", "--verbosity", action="count", default=0)
   args = parser.parse_args()
   answer = args.x**args.y
   if args.verbosity >= 2:
       print "Running '{}'".format(__file__)
   if args.verbosity >= 1:
       print "{}^{} ==".format(args.x, args.y),
   print answer

Output:

.. code-block:: sh

   $ python prog.py 4 2
   16
   $ python prog.py 4 2 -v
   4^2 == 16
   $ python prog.py 4 2 -vv
   Running 'prog.py'
   4^2 == 16


Conflicting options
-------------------

So far, we have been working with two methods of an
:class:`argparse.ArgumentParser` instance. Let's introduce a third one,
:meth:`add_mutually_exclusive_group`. It allows for us to specify options that
conflict with each other. Let's also change the rest of the program so that
the new functionality makes more sense:
we'll introduce the ``--quiet`` option,
which will be the opposite of the ``--verbose`` one::

   import argparse

   parser = argparse.ArgumentParser()
   group = parser.add_mutually_exclusive_group()
   group.add_argument("-v", "--verbose", action="store_true")
   group.add_argument("-q", "--quiet", action="store_true")
   parser.add_argument("x", type=int, help="the base")
   parser.add_argument("y", type=int, help="the exponent")
   args = parser.parse_args()
   answer = args.x**args.y

   if args.quiet:
       print answer
   elif args.verbose:
       print "{} to the power {} equals {}".format(args.x, args.y, answer)
   else:
       print "{}^{} == {}".format(args.x, args.y, answer)

Our program is now simpler, and we've lost some functionality for the sake of
demonstration. Anyways, here's the output:

.. code-block:: sh

   $ python prog.py 4 2
   4^2 == 16
   $ python prog.py 4 2 -q
   16
   $ python prog.py 4 2 -v
   4 to the power 2 equals 16
   $ python prog.py 4 2 -vq
   usage: prog.py [-h] [-v | -q] x y
   prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
   $ python prog.py 4 2 -v --quiet
   usage: prog.py [-h] [-v | -q] x y
   prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose

That should be easy to follow. I've added that last output so you can see the
sort of flexibility you get, i.e. mixing long form options with short form
ones.

Before we conclude, you probably want to tell your users the main purpose of
your program, just in case they don't know::

   import argparse

   parser = argparse.ArgumentParser(description="calculate X to the power of Y")
   group = parser.add_mutually_exclusive_group()
   group.add_argument("-v", "--verbose", action="store_true")
   group.add_argument("-q", "--quiet", action="store_true")
   parser.add_argument("x", type=int, help="the base")
   parser.add_argument("y", type=int, help="the exponent")
   args = parser.parse_args()
   answer = args.x**args.y

   if args.quiet:
       print answer
   elif args.verbose:
       print "{} to the power {} equals {}".format(args.x, args.y, answer)
   else:
       print "{}^{} == {}".format(args.x, args.y, answer)

Note that slight difference in the usage text. Note the ``[-v | -q]``,
which tells us that we can either use ``-v`` or ``-q``,
but not both at the same time:

.. code-block:: sh

   $ python prog.py --help
   usage: prog.py [-h] [-v | -q] x y

   calculate X to the power of Y

   positional arguments:
     x              the base
     y              the exponent

   optional arguments:
     -h, --help     show this help message and exit
     -v, --verbose
     -q, --quiet


Conclusion
==========

The :mod:`argparse` module offers a lot more than shown here.
Its docs are quite detailed and thorough, and full of examples.
Having gone through this tutorial, you should easily digest them
without feeling overwhelmed.
PK	%�\�%`$html/_sources/howto/cporting.rst.txtnu�[���.. highlightlang:: c

.. _cporting-howto:

*************************************
Porting Extension Modules to Python 3
*************************************

:author: Benjamin Peterson


.. topic:: Abstract

   Although changing the C-API was not one of Python 3's objectives,
   the many Python-level changes made leaving Python 2's API intact
   impossible.  In fact, some changes such as :func:`int` and
   :func:`long` unification are more obvious on the C level.  This
   document endeavors to document incompatibilities and how they can
   be worked around.


Conditional compilation
=======================

The easiest way to compile only some code for Python 3 is to check
if :c:macro:`PY_MAJOR_VERSION` is greater than or equal to 3. ::

   #if PY_MAJOR_VERSION >= 3
   #define IS_PY3K
   #endif

API functions that are not present can be aliased to their equivalents within
conditional blocks.


Changes to Object APIs
======================

Python 3 merged together some types with similar functions while cleanly
separating others.


str/unicode Unification
-----------------------

Python 3's :func:`str` type is equivalent to Python 2's :func:`unicode`; the C
functions are called ``PyUnicode_*`` for both.  The old 8-bit string type has become
:func:`bytes`, with C functions called ``PyBytes_*``.  Python 2.6 and later provide a compatibility header,
:file:`bytesobject.h`, mapping ``PyBytes`` names to ``PyString`` ones.  For best
compatibility with Python 3, :c:type:`PyUnicode` should be used for textual data and
:c:type:`PyBytes` for binary data.  It's also important to remember that
:c:type:`PyBytes` and :c:type:`PyUnicode` in Python 3 are not interchangeable like
:c:type:`PyString` and :c:type:`PyUnicode` are in Python 2.  The following example
shows best practices with regards to :c:type:`PyUnicode`, :c:type:`PyString`,
and :c:type:`PyBytes`. ::

   #include "stdlib.h"
   #include "Python.h"
   #include "bytesobject.h"

   /* text example */
   static PyObject *
   say_hello(PyObject *self, PyObject *args) {
       PyObject *name, *result;

       if (!PyArg_ParseTuple(args, "U:say_hello", &name))
           return NULL;

       result = PyUnicode_FromFormat("Hello, %S!", name);
       return result;
   }

   /* just a forward */
   static char * do_encode(PyObject *);

   /* bytes example */
   static PyObject *
   encode_object(PyObject *self, PyObject *args) {
       char *encoded;
       PyObject *result, *myobj;

       if (!PyArg_ParseTuple(args, "O:encode_object", &myobj))
           return NULL;

       encoded = do_encode(myobj);
       if (encoded == NULL)
           return NULL;
       result = PyBytes_FromString(encoded);
       free(encoded);
       return result;
   }


long/int Unification
--------------------

Python 3 has only one integer type, :func:`int`.  But it actually
corresponds to Python 2's :func:`long` type—the :func:`int` type
used in Python 2 was removed.  In the C-API, ``PyInt_*`` functions
are replaced by their ``PyLong_*`` equivalents.


Module initialization and state
===============================

Python 3 has a revamped extension module initialization system.  (See
:pep:`3121`.)  Instead of storing module state in globals, they should
be stored in an interpreter specific structure.  Creating modules that
act correctly in both Python 2 and Python 3 is tricky.  The following
simple example demonstrates how. ::

   #include "Python.h"

   struct module_state {
       PyObject *error;
   };

   #if PY_MAJOR_VERSION >= 3
   #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
   #else
   #define GETSTATE(m) (&_state)
   static struct module_state _state;
   #endif

   static PyObject *
   error_out(PyObject *m) {
       struct module_state *st = GETSTATE(m);
       PyErr_SetString(st->error, "something bad happened");
       return NULL;
   }

   static PyMethodDef myextension_methods[] = {
       {"error_out", (PyCFunction)error_out, METH_NOARGS, NULL},
       {NULL, NULL}
   };

   #if PY_MAJOR_VERSION >= 3

   static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
       Py_VISIT(GETSTATE(m)->error);
       return 0;
   }

   static int myextension_clear(PyObject *m) {
       Py_CLEAR(GETSTATE(m)->error);
       return 0;
   }


   static struct PyModuleDef moduledef = {
           PyModuleDef_HEAD_INIT,
           "myextension",
           NULL,
           sizeof(struct module_state),
           myextension_methods,
           NULL,
           myextension_traverse,
           myextension_clear,
           NULL
   };

   #define INITERROR return NULL

   PyMODINIT_FUNC
   PyInit_myextension(void)

   #else
   #define INITERROR return

   void
   initmyextension(void)
   #endif
   {
   #if PY_MAJOR_VERSION >= 3
       PyObject *module = PyModule_Create(&moduledef);
   #else
       PyObject *module = Py_InitModule("myextension", myextension_methods);
   #endif

       if (module == NULL)
           INITERROR;
       struct module_state *st = GETSTATE(module);

       st->error = PyErr_NewException("myextension.Error", NULL, NULL);
       if (st->error == NULL) {
           Py_DECREF(module);
           INITERROR;
       }

   #if PY_MAJOR_VERSION >= 3
       return module;
   #endif
   }


CObject replaced with Capsule
=============================

The :c:type:`Capsule` object was introduced in Python 3.1 and 2.7 to replace
:c:type:`CObject`.  CObjects were useful,
but the :c:type:`CObject` API was problematic: it didn't permit distinguishing
between valid CObjects, which allowed mismatched CObjects to crash the
interpreter, and some of its APIs relied on undefined behavior in C.
(For further reading on the rationale behind Capsules, please see :issue:`5630`.)

If you're currently using CObjects, and you want to migrate to 3.1 or newer,
you'll need to switch to Capsules.
:c:type:`CObject` was deprecated in 3.1 and 2.7 and completely removed in
Python 3.2.  If you only support 2.7, or 3.1 and above, you
can simply switch to :c:type:`Capsule`.  If you need to support Python 3.0,
or versions of Python earlier than 2.7,
you'll have to support both CObjects and Capsules.
(Note that Python 3.0 is no longer supported, and it is not recommended
for production use.)

The following example header file :file:`capsulethunk.h` may
solve the problem for you.  Simply write your code against the
:c:type:`Capsule` API and include this header file after
:file:`Python.h`.  Your code will automatically use Capsules
in versions of Python with Capsules, and switch to CObjects
when Capsules are unavailable.

:file:`capsulethunk.h` simulates Capsules using CObjects.  However,
:c:type:`CObject` provides no place to store the capsule's "name".  As a
result the simulated :c:type:`Capsule` objects created by :file:`capsulethunk.h`
behave slightly differently from real Capsules.  Specifically:

  * The name parameter passed in to :c:func:`PyCapsule_New` is ignored.

  * The name parameter passed in to :c:func:`PyCapsule_IsValid` and
    :c:func:`PyCapsule_GetPointer` is ignored, and no error checking
    of the name is performed.

  * :c:func:`PyCapsule_GetName` always returns NULL.

  * :c:func:`PyCapsule_SetName` always raises an exception and
    returns failure.  (Since there's no way to store a name
    in a CObject, noisy failure of :c:func:`PyCapsule_SetName`
    was deemed preferable to silent failure here.  If this is
    inconvenient, feel free to modify your local
    copy as you see fit.)

You can find :file:`capsulethunk.h` in the Python source distribution
as :source:`Doc/includes/capsulethunk.h`.  We also include it here for
your convenience:

.. literalinclude:: ../includes/capsulethunk.h



Other options
=============

If you are writing a new extension module, you might consider `Cython
<http://cython.org/>`_.  It translates a Python-like language to C.  The
extension modules it creates are compatible with Python 3 and Python 2.

PK	%�\a0���U�U"html/_sources/howto/curses.rst.txtnu�[���.. _curses-howto:

**********************************
  Curses Programming with Python
**********************************

:Author: A.M. Kuchling, Eric S. Raymond
:Release: 2.03


.. topic:: Abstract

   This document describes how to write text-mode programs with Python 2.x, using
   the :mod:`curses` extension module to control the display.


What is curses?
===============

The curses library supplies a terminal-independent screen-painting and
keyboard-handling facility for text-based terminals; such terminals include
VT100s, the Linux console, and the simulated terminal provided by X11 programs
such as xterm and rxvt.  Display terminals support various control codes to
perform common operations such as moving the cursor, scrolling the screen, and
erasing areas.  Different terminals use widely differing codes, and often have
their own minor quirks.

In a world of X displays, one might ask "why bother"?  It's true that
character-cell display terminals are an obsolete technology, but there are
niches in which being able to do fancy things with them are still valuable.  One
is on small-footprint or embedded Unixes that don't carry an X server.  Another
is for tools like OS installers and kernel configurators that may have to run
before X is available.

The curses library hides all the details of different terminals, and provides
the programmer with an abstraction of a display, containing multiple
non-overlapping windows.  The contents of a window can be changed in various
ways---adding text, erasing it, changing its appearance---and the curses library
will automagically figure out what control codes need to be sent to the terminal
to produce the right output.

The curses library was originally written for BSD Unix; the later System V
versions of Unix from AT&T added many enhancements and new functions. BSD curses
is no longer maintained, having been replaced by ncurses, which is an
open-source implementation of the AT&T interface.  If you're using an
open-source Unix such as Linux or FreeBSD, your system almost certainly uses
ncurses.  Since most current commercial Unix versions are based on System V
code, all the functions described here will probably be available.  The older
versions of curses carried by some proprietary Unixes may not support
everything, though.

No one has made a Windows port of the curses module.  On a Windows platform, try
the Console module written by Fredrik Lundh.  The Console module provides
cursor-addressable text output, plus full support for mouse and keyboard input,
and is available from http://effbot.org/zone/console-index.htm.


The Python curses module
------------------------

Thy Python module is a fairly simple wrapper over the C functions provided by
curses; if you're already familiar with curses programming in C, it's really
easy to transfer that knowledge to Python.  The biggest difference is that the
Python interface makes things simpler, by merging different C functions such as
:func:`addstr`, :func:`mvaddstr`, :func:`mvwaddstr`, into a single
:meth:`addstr` method.  You'll see this covered in more detail later.

This HOWTO is simply an introduction to writing text-mode programs with curses
and Python. It doesn't attempt to be a complete guide to the curses API; for
that, see the Python library guide's section on ncurses, and the C manual pages
for ncurses.  It will, however, give you the basic ideas.


Starting and ending a curses application
========================================

Before doing anything, curses must be initialized.  This is done by calling the
:func:`initscr` function, which will determine the terminal type, send any
required setup codes to the terminal, and create various internal data
structures.  If successful, :func:`initscr` returns a window object representing
the entire screen; this is usually called ``stdscr``, after the name of the
corresponding C variable. ::

   import curses
   stdscr = curses.initscr()

Usually curses applications turn off automatic echoing of keys to the screen, in
order to be able to read keys and only display them under certain circumstances.
This requires calling the :func:`noecho` function. ::

   curses.noecho()

Applications will also commonly need to react to keys instantly, without
requiring the Enter key to be pressed; this is called cbreak mode, as opposed to
the usual buffered input mode. ::

   curses.cbreak()

Terminals usually return special keys, such as the cursor keys or navigation
keys such as Page Up and Home, as a multibyte escape sequence.  While you could
write your application to expect such sequences and process them accordingly,
curses can do it for you, returning a special value such as
:const:`curses.KEY_LEFT`.  To get curses to do the job, you'll have to enable
keypad mode. ::

   stdscr.keypad(1)

Terminating a curses application is much easier than starting one. You'll need
to call  ::

   curses.nocbreak(); stdscr.keypad(0); curses.echo()

to reverse the curses-friendly terminal settings. Then call the :func:`endwin`
function to restore the terminal to its original operating mode. ::

   curses.endwin()

A common problem when debugging a curses application is to get your terminal
messed up when the application dies without restoring the terminal to its
previous state.  In Python this commonly happens when your code is buggy and
raises an uncaught exception.  Keys are no longer echoed to the screen when
you type them, for example, which makes using the shell difficult.

In Python you can avoid these complications and make debugging much easier by
importing the :func:`curses.wrapper` function.  It takes a callable and does
the initializations described above, also initializing colors if color support
is present.  It then runs your provided callable and finally deinitializes
appropriately.  The callable is called inside a try-catch clause which catches
exceptions, performs curses deinitialization, and then passes the exception
upwards.  Thus, your terminal won't be left in a funny state on exception.


Windows and Pads
================

Windows are the basic abstraction in curses.  A window object represents a
rectangular area of the screen, and supports various methods to display text,
erase it, allow the user to input strings, and so forth.

The ``stdscr`` object returned by the :func:`initscr` function is a window
object that covers the entire screen.  Many programs may need only this single
window, but you might wish to divide the screen into smaller windows, in order
to redraw or clear them separately. The :func:`newwin` function creates a new
window of a given size, returning the new window object. ::

   begin_x = 20; begin_y = 7
   height = 5; width = 40
   win = curses.newwin(height, width, begin_y, begin_x)

A word about the coordinate system used in curses: coordinates are always passed
in the order *y,x*, and the top-left corner of a window is coordinate (0,0).
This breaks a common convention for handling coordinates, where the *x*
coordinate usually comes first.  This is an unfortunate difference from most
other computer applications, but it's been part of curses since it was first
written, and it's too late to change things now.

When you call a method to display or erase text, the effect doesn't immediately
show up on the display.  This is because curses was originally written with slow
300-baud terminal connections in mind; with these terminals, minimizing the time
required to redraw the screen is very important.  This lets curses accumulate
changes to the screen, and display them in the most efficient manner.  For
example, if your program displays some characters in a window, and then clears
the window, there's no need to send the original characters because they'd never
be visible.

Accordingly, curses requires that you explicitly tell it to redraw windows,
using the :func:`refresh` method of window objects.  In practice, this doesn't
really complicate programming with curses much. Most programs go into a flurry
of activity, and then pause waiting for a keypress or some other action on the
part of the user.  All you have to do is to be sure that the screen has been
redrawn before pausing to wait for user input, by simply calling
``stdscr.refresh()`` or the :func:`refresh` method of some other relevant
window.

A pad is a special case of a window; it can be larger than the actual display
screen, and only a portion of it displayed at a time. Creating a pad simply
requires the pad's height and width, while refreshing a pad requires giving the
coordinates of the on-screen area where a subsection of the pad will be
displayed.   ::

   pad = curses.newpad(100, 100)
   #  These loops fill the pad with letters; this is
   # explained in the next section
   for y in range(0, 100):
       for x in range(0, 100):
           try:
               pad.addch(y,x, ord('a') + (x*x+y*y) % 26)
           except curses.error:
               pass

   #  Displays a section of the pad in the middle of the screen
   pad.refresh(0,0, 5,5, 20,75)

The :func:`refresh` call displays a section of the pad in the rectangle
extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper
left corner of the displayed section is coordinate (0,0) on the pad.  Beyond
that difference, pads are exactly like ordinary windows and support the same
methods.

If you have multiple windows and pads on screen there is a more efficient way to
go, which will prevent annoying screen flicker at refresh time.  Use the
:meth:`noutrefresh` method of each window to update the data structure
representing the desired state of the screen; then change the physical screen to
match the desired state in one go with the function :func:`doupdate`.  The
normal :meth:`refresh` method calls :func:`doupdate` as its last act.


Displaying Text
===============

From a C programmer's point of view, curses may sometimes look like a twisty
maze of functions, all subtly different.  For example, :func:`addstr` displays a
string at the current cursor location in the ``stdscr`` window, while
:func:`mvaddstr` moves to a given y,x coordinate first before displaying the
string. :func:`waddstr` is just like :func:`addstr`, but allows specifying a
window to use, instead of using ``stdscr`` by default. :func:`mvwaddstr` follows
similarly.

Fortunately the Python interface hides all these details; ``stdscr`` is a window
object like any other, and methods like :func:`addstr` accept multiple argument
forms.  Usually there are four different forms.

+---------------------------------+-----------------------------------------------+
| Form                            | Description                                   |
+=================================+===============================================+
| *str* or *ch*                   | Display the string *str* or character *ch* at |
|                                 | the current position                          |
+---------------------------------+-----------------------------------------------+
| *str* or *ch*, *attr*           | Display the string *str* or character *ch*,   |
|                                 | using attribute *attr* at the current         |
|                                 | position                                      |
+---------------------------------+-----------------------------------------------+
| *y*, *x*, *str* or *ch*         | Move to position *y,x* within the window, and |
|                                 | display *str* or *ch*                         |
+---------------------------------+-----------------------------------------------+
| *y*, *x*, *str* or *ch*, *attr* | Move to position *y,x* within the window, and |
|                                 | display *str* or *ch*, using attribute *attr* |
+---------------------------------+-----------------------------------------------+

Attributes allow displaying text in highlighted forms, such as in boldface,
underline, reverse code, or in color.  They'll be explained in more detail in
the next subsection.

The :func:`addstr` function takes a Python string as the value to be displayed,
while the :func:`addch` functions take a character, which can be either a Python
string of length 1 or an integer.  If it's a string, you're limited to
displaying characters between 0 and 255.  SVr4 curses provides constants for
extension characters; these constants are integers greater than 255.  For
example, :const:`ACS_PLMINUS` is a +/- symbol, and :const:`ACS_ULCORNER` is the
upper left corner of a box (handy for drawing borders).

Windows remember where the cursor was left after the last operation, so if you
leave out the *y,x* coordinates, the string or character will be displayed
wherever the last operation left off.  You can also move the cursor with the
``move(y,x)`` method.  Because some terminals always display a flashing cursor,
you may want to ensure that the cursor is positioned in some location where it
won't be distracting; it can be confusing to have the cursor blinking at some
apparently random location.

If your application doesn't need a blinking cursor at all, you can call
``curs_set(0)`` to make it invisible.  Equivalently, and for compatibility with
older curses versions, there's a ``leaveok(bool)`` function.  When *bool* is
true, the curses library will attempt to suppress the flashing cursor, and you
won't need to worry about leaving it in odd locations.


Attributes and Color
--------------------

Characters can be displayed in different ways.  Status lines in a text-based
application are commonly shown in reverse video; a text viewer may need to
highlight certain words.  curses supports this by allowing you to specify an
attribute for each cell on the screen.

An attribute is an integer, each bit representing a different attribute.  You can
try to display text with multiple attribute bits set, but curses doesn't
guarantee that all the possible combinations are available, or that they're all
visually distinct.  That depends on the ability of the terminal being used, so
it's safest to stick to the most commonly available attributes, listed here.

+----------------------+--------------------------------------+
| Attribute            | Description                          |
+======================+======================================+
| :const:`A_BLINK`     | Blinking text                        |
+----------------------+--------------------------------------+
| :const:`A_BOLD`      | Extra bright or bold text            |
+----------------------+--------------------------------------+
| :const:`A_DIM`       | Half bright text                     |
+----------------------+--------------------------------------+
| :const:`A_REVERSE`   | Reverse-video text                   |
+----------------------+--------------------------------------+
| :const:`A_STANDOUT`  | The best highlighting mode available |
+----------------------+--------------------------------------+
| :const:`A_UNDERLINE` | Underlined text                      |
+----------------------+--------------------------------------+

So, to display a reverse-video status line on the top line of the screen, you
could code::

   stdscr.addstr(0, 0, "Current mode: Typing mode",
                 curses.A_REVERSE)
   stdscr.refresh()

The curses library also supports color on those terminals that provide it. The
most common such terminal is probably the Linux console, followed by color
xterms.

To use color, you must call the :func:`start_color` function soon after calling
:func:`initscr`, to initialize the default color set (the
:func:`curses.wrapper.wrapper` function does this automatically).  Once that's
done, the :func:`has_colors` function returns TRUE if the terminal in use can
actually display color.  (Note: curses uses the American spelling 'color',
instead of the Canadian/British spelling 'colour'.  If you're used to the
British spelling, you'll have to resign yourself to misspelling it for the sake
of these functions.)

The curses library maintains a finite number of color pairs, containing a
foreground (or text) color and a background color.  You can get the attribute
value corresponding to a color pair with the :func:`color_pair` function; this
can be bitwise-OR'ed with other attributes such as :const:`A_REVERSE`, but
again, such combinations are not guaranteed to work on all terminals.

An example, which displays a line of text using color pair 1::

   stdscr.addstr("Pretty text", curses.color_pair(1))
   stdscr.refresh()

As I said before, a color pair consists of a foreground and background color.
:func:`start_color` initializes 8 basic colors when it activates color mode.
They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
7:white.  The curses module defines named constants for each of these colors:
:const:`curses.COLOR_BLACK`, :const:`curses.COLOR_RED`, and so forth.

The ``init_pair(n, f, b)`` function changes the definition of color pair *n*, to
foreground color f and background color b.  Color pair 0 is hard-wired to white
on black, and cannot be changed.

Let's put all this together. To change color 1 to red text on a white
background, you would call::

   curses.init_pair(1, curses.COLOR_RED, curses.COLOR_WHITE)

When you change a color pair, any text already displayed using that color pair
will change to the new colors.  You can also display new text in this color
with::

   stdscr.addstr(0,0, "RED ALERT!", curses.color_pair(1))

Very fancy terminals can change the definitions of the actual colors to a given
RGB value.  This lets you change color 1, which is usually red, to purple or
blue or any other color you like.  Unfortunately, the Linux console doesn't
support this, so I'm unable to try it out, and can't provide any examples.  You
can check if your terminal can do this by calling :func:`can_change_color`,
which returns TRUE if the capability is there.  If you're lucky enough to have
such a talented terminal, consult your system's man pages for more information.


User Input
==========

The curses library itself offers only very simple input mechanisms. Python's
support adds a text-input widget that makes up some of the lack.

The most common way to get input to a window is to use its :meth:`getch` method.
:meth:`getch` pauses and waits for the user to hit a key, displaying it if
:func:`echo` has been called earlier.  You can optionally specify a coordinate
to which the cursor should be moved before pausing.

It's possible to change this behavior with the method :meth:`nodelay`. After
``nodelay(1)``, :meth:`getch` for the window becomes non-blocking and returns
``curses.ERR`` (a value of -1) when no input is ready.  There's also a
:func:`halfdelay` function, which can be used to (in effect) set a timer on each
:meth:`getch`; if no input becomes available within a specified
delay (measured in tenths of a second), curses raises an exception.

The :meth:`getch` method returns an integer; if it's between 0 and 255, it
represents the ASCII code of the key pressed.  Values greater than 255 are
special keys such as Page Up, Home, or the cursor keys. You can compare the
value returned to constants such as :const:`curses.KEY_PPAGE`,
:const:`curses.KEY_HOME`, or :const:`curses.KEY_LEFT`.  Usually the main loop of
your program will look something like this::

   while 1:
       c = stdscr.getch()
       if c == ord('p'):
           PrintDocument()
       elif c == ord('q'):
           break  # Exit the while()
       elif c == curses.KEY_HOME:
           x = y = 0

The :mod:`curses.ascii` module supplies ASCII class membership functions that
take either integer or 1-character-string arguments; these may be useful in
writing more readable tests for your command interpreters.  It also supplies
conversion functions  that take either integer or 1-character-string arguments
and return the same type.  For example, :func:`curses.ascii.ctrl` returns the
control character corresponding to its argument.

There's also a method to retrieve an entire string, :const:`getstr()`.  It isn't
used very often, because its functionality is quite limited; the only editing
keys available are the backspace key and the Enter key, which terminates the
string.  It can optionally be limited to a fixed number of characters. ::

   curses.echo()            # Enable echoing of characters

   # Get a 15-character string, with the cursor on the top line
   s = stdscr.getstr(0,0, 15)

The Python :mod:`curses.textpad` module supplies something better. With it, you
can turn a window into a text box that supports an Emacs-like set of
keybindings.  Various methods of :class:`Textbox` class support editing with
input validation and gathering the edit results either with or without trailing
spaces.   See the library documentation on :mod:`curses.textpad` for the
details.


For More Information
====================

This HOWTO didn't cover some advanced topics, such as screen-scraping or
capturing mouse events from an xterm instance.  But the Python library page for
the curses modules is now pretty complete.  You should browse it next.

If you're in doubt about the detailed behavior of any of the ncurses entry
points, consult the manual pages for your curses implementation, whether it's
ncurses or a proprietary Unix vendor's.  The manual pages will document any
quirks, and provide complete lists of all the functions, attributes, and
:const:`ACS_\*` characters available to you.

Because the curses API is so large, some functions aren't supported in the
Python interface, not because they're difficult to implement, but because no one
has needed them yet.  Feel free to add them and then submit a patch.  Also, we
don't yet have support for the menu library associated with
ncurses; feel free to add that.

If you write an interesting little program, feel free to contribute it as
another demo.  We can always use more of them!

The ncurses FAQ: http://invisible-island.net/ncurses/ncurses.faq.html
PK	%�\�X�KIDID&html/_sources/howto/descriptor.rst.txtnu�[���======================
Descriptor HowTo Guide
======================

:Author: Raymond Hettinger
:Contact: <python at rcn dot com>

.. Contents::

Abstract
--------

Defines descriptors, summarizes the protocol, and shows how descriptors are
called.  Examines a custom descriptor and several built-in python descriptors
including functions, properties, static methods, and class methods.  Shows how
each works by giving a pure Python equivalent and a sample application.

Learning about descriptors not only provides access to a larger toolset, it
creates a deeper understanding of how Python works and an appreciation for the
elegance of its design.


Definition and Introduction
---------------------------

In general, a descriptor is an object attribute with "binding behavior", one
whose attribute access has been overridden by methods in the descriptor
protocol.  Those methods are :meth:`__get__`, :meth:`__set__`, and
:meth:`__delete__`.  If any of those methods are defined for an object, it is
said to be a descriptor.

The default behavior for attribute access is to get, set, or delete the
attribute from an object's dictionary.  For instance, ``a.x`` has a lookup chain
starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
continuing through the base classes of ``type(a)`` excluding metaclasses. If the
looked-up value is an object defining one of the descriptor methods, then Python
may override the default behavior and invoke the descriptor method instead.
Where this occurs in the precedence chain depends on which descriptor methods
were defined.  Note that descriptors are only invoked for new style objects or
classes (a class is new style if it inherits from :class:`object` or
:class:`type`).

Descriptors are a powerful, general purpose protocol.  They are the mechanism
behind properties, methods, static methods, class methods, and :func:`super()`.
They are used throughout Python itself to implement the new style classes
introduced in version 2.2.  Descriptors simplify the underlying C-code and offer
a flexible set of new tools for everyday Python programs.


Descriptor Protocol
-------------------

``descr.__get__(self, obj, type=None) --> value``

``descr.__set__(self, obj, value) --> None``

``descr.__delete__(self, obj) --> None``

That is all there is to it.  Define any of these methods and an object is
considered a descriptor and can override default behavior upon being looked up
as an attribute.

If an object defines both :meth:`__get__` and :meth:`__set__`, it is considered
a data descriptor.  Descriptors that only define :meth:`__get__` are called
non-data descriptors (they are typically used for methods but other uses are
possible).

Data and non-data descriptors differ in how overrides are calculated with
respect to entries in an instance's dictionary.  If an instance's dictionary
has an entry with the same name as a data descriptor, the data descriptor
takes precedence.  If an instance's dictionary has an entry with the same
name as a non-data descriptor, the dictionary entry takes precedence.

To make a read-only data descriptor, define both :meth:`__get__` and
:meth:`__set__` with the :meth:`__set__` raising an :exc:`AttributeError` when
called.  Defining the :meth:`__set__` method with an exception raising
placeholder is enough to make it a data descriptor.


Invoking Descriptors
--------------------

A descriptor can be called directly by its method name.  For example,
``d.__get__(obj)``.

Alternatively, it is more common for a descriptor to be invoked automatically
upon attribute access.  For example, ``obj.d`` looks up ``d`` in the dictionary
of ``obj``.  If ``d`` defines the method :meth:`__get__`, then ``d.__get__(obj)``
is invoked according to the precedence rules listed below.

The details of invocation depend on whether ``obj`` is an object or a class.
Either way, descriptors only work for new style objects and classes.  A class is
new style if it is a subclass of :class:`object`.

For objects, the machinery is in :meth:`object.__getattribute__` which
transforms ``b.x`` into ``type(b).__dict__['x'].__get__(b, type(b))``.  The
implementation works through a precedence chain that gives data descriptors
priority over instance variables, instance variables priority over non-data
descriptors, and assigns lowest priority to :meth:`__getattr__` if provided.
The full C implementation can be found in :c:func:`PyObject_GenericGetAttr()` in
:source:`Objects/object.c`.

For classes, the machinery is in :meth:`type.__getattribute__` which transforms
``B.x`` into ``B.__dict__['x'].__get__(None, B)``.  In pure Python, it looks
like::

    def __getattribute__(self, key):
        "Emulate type_getattro() in Objects/typeobject.c"
        v = object.__getattribute__(self, key)
        if hasattr(v, '__get__'):
            return v.__get__(None, self)
        return v

The important points to remember are:

* descriptors are invoked by the :meth:`__getattribute__` method
* overriding :meth:`__getattribute__` prevents automatic descriptor calls
* :meth:`__getattribute__` is only available with new style classes and objects
* :meth:`object.__getattribute__` and :meth:`type.__getattribute__` make
  different calls to :meth:`__get__`.
* data descriptors always override instance dictionaries.
* non-data descriptors may be overridden by instance dictionaries.

The object returned by ``super()`` also has a custom :meth:`__getattribute__`
method for invoking descriptors.  The call ``super(B, obj).m()`` searches
``obj.__class__.__mro__`` for the base class ``A`` immediately following ``B``
and then returns ``A.__dict__['m'].__get__(obj, B)``.  If not a descriptor,
``m`` is returned unchanged.  If not in the dictionary, ``m`` reverts to a
search using :meth:`object.__getattribute__`.

Note, in Python 2.2, ``super(B, obj).m()`` would only invoke :meth:`__get__` if
``m`` was a data descriptor.  In Python 2.3, non-data descriptors also get
invoked unless an old-style class is involved.  The implementation details are
in :c:func:`super_getattro()` in :source:`Objects/typeobject.c`.

.. _`Guido's Tutorial`: https://www.python.org/download/releases/2.2.3/descrintro/#cooperation

The details above show that the mechanism for descriptors is embedded in the
:meth:`__getattribute__()` methods for :class:`object`, :class:`type`, and
:func:`super`.  Classes inherit this machinery when they derive from
:class:`object` or if they have a meta-class providing similar functionality.
Likewise, classes can turn-off descriptor invocation by overriding
:meth:`__getattribute__()`.


Descriptor Example
------------------

The following code creates a class whose objects are data descriptors which
print a message for each get or set.  Overriding :meth:`__getattribute__` is
alternate approach that could do this for every attribute.  However, this
descriptor is useful for monitoring just a few chosen attributes::

    class RevealAccess(object):
        """A data descriptor that sets and returns values
           normally and prints a message logging their access.
        """

        def __init__(self, initval=None, name='var'):
            self.val = initval
            self.name = name

        def __get__(self, obj, objtype):
            print 'Retrieving', self.name
            return self.val

        def __set__(self, obj, val):
            print 'Updating', self.name
            self.val = val

    >>> class MyClass(object):
    ...     x = RevealAccess(10, 'var "x"')
    ...     y = 5
    ...
    >>> m = MyClass()
    >>> m.x
    Retrieving var "x"
    10
    >>> m.x = 20
    Updating var "x"
    >>> m.x
    Retrieving var "x"
    20
    >>> m.y
    5

The protocol is simple and offers exciting possibilities.  Several use cases are
so common that they have been packaged into individual function calls.
Properties, bound and unbound methods, static methods, and class methods are all
based on the descriptor protocol.


Properties
----------

Calling :func:`property` is a succinct way of building a data descriptor that
triggers function calls upon access to an attribute.  Its signature is::

    property(fget=None, fset=None, fdel=None, doc=None) -> property attribute

The documentation shows a typical use to define a managed attribute ``x``::

    class C(object):
        def getx(self): return self.__x
        def setx(self, value): self.__x = value
        def delx(self): del self.__x
        x = property(getx, setx, delx, "I'm the 'x' property.")

To see how :func:`property` is implemented in terms of the descriptor protocol,
here is a pure Python equivalent::

    class Property(object):
        "Emulate PyProperty_Type() in Objects/descrobject.c"

        def __init__(self, fget=None, fset=None, fdel=None, doc=None):
            self.fget = fget
            self.fset = fset
            self.fdel = fdel
            if doc is None and fget is not None:
                doc = fget.__doc__
            self.__doc__ = doc

        def __get__(self, obj, objtype=None):
            if obj is None:
                return self
            if self.fget is None:
                raise AttributeError("unreadable attribute")
            return self.fget(obj)

        def __set__(self, obj, value):
            if self.fset is None:
                raise AttributeError("can't set attribute")
            self.fset(obj, value)

        def __delete__(self, obj):
            if self.fdel is None:
                raise AttributeError("can't delete attribute")
            self.fdel(obj)

        def getter(self, fget):
            return type(self)(fget, self.fset, self.fdel, self.__doc__)

        def setter(self, fset):
            return type(self)(self.fget, fset, self.fdel, self.__doc__)

        def deleter(self, fdel):
            return type(self)(self.fget, self.fset, fdel, self.__doc__)

The :func:`property` builtin helps whenever a user interface has granted
attribute access and then subsequent changes require the intervention of a
method.

For instance, a spreadsheet class may grant access to a cell value through
``Cell('b10').value``. Subsequent improvements to the program require the cell
to be recalculated on every access; however, the programmer does not want to
affect existing client code accessing the attribute directly.  The solution is
to wrap access to the value attribute in a property data descriptor::

    class Cell(object):
        . . .
        def getvalue(self):
            "Recalculate the cell before returning value"
            self.recalc()
            return self._value
        value = property(getvalue)


Functions and Methods
---------------------

Python's object oriented features are built upon a function based environment.
Using non-data descriptors, the two are merged seamlessly.

Class dictionaries store methods as functions.  In a class definition, methods
are written using :keyword:`def` and :keyword:`lambda`, the usual tools for
creating functions.  The only difference from regular functions is that the
first argument is reserved for the object instance.  By Python convention, the
instance reference is called *self* but may be called *this* or any other
variable name.

To support method calls, functions include the :meth:`__get__` method for
binding methods during attribute access.  This means that all functions are
non-data descriptors which return bound or unbound methods depending whether
they are invoked from an object or a class.  In pure python, it works like
this::

    class Function(object):
        . . .
        def __get__(self, obj, objtype=None):
            "Simulate func_descr_get() in Objects/funcobject.c"
            return types.MethodType(self, obj, objtype)

Running the interpreter shows how the function descriptor works in practice::

    >>> class D(object):
    ...     def f(self, x):
    ...         return x
    ...
    >>> d = D()
    >>> D.__dict__['f']  # Stored internally as a function
    <function f at 0x00C45070>
    >>> D.f              # Get from a class becomes an unbound method
    <unbound method D.f>
    >>> d.f              # Get from an instance becomes a bound method
    <bound method D.f of <__main__.D object at 0x00B18C90>>

The output suggests that bound and unbound methods are two different types.
While they could have been implemented that way, the actual C implementation of
:c:type:`PyMethod_Type` in :source:`Objects/classobject.c` is a single object
with two different representations depending on whether the :attr:`im_self`
field is set or is *NULL* (the C equivalent of ``None``).

Likewise, the effects of calling a method object depend on the :attr:`im_self`
field. If set (meaning bound), the original function (stored in the
:attr:`im_func` field) is called as expected with the first argument set to the
instance.  If unbound, all of the arguments are passed unchanged to the original
function. The actual C implementation of :func:`instancemethod_call()` is only
slightly more complex in that it includes some type checking.


Static Methods and Class Methods
--------------------------------

Non-data descriptors provide a simple mechanism for variations on the usual
patterns of binding functions into methods.

To recap, functions have a :meth:`__get__` method so that they can be converted
to a method when accessed as attributes.  The non-data descriptor transforms an
``obj.f(*args)`` call into ``f(obj, *args)``.  Calling ``klass.f(*args)``
becomes ``f(*args)``.

This chart summarizes the binding and its two most useful variants:

      +-----------------+----------------------+------------------+
      | Transformation  | Called from an       | Called from a    |
      |                 | Object               | Class            |
      +=================+======================+==================+
      | function        | f(obj, \*args)       | f(\*args)        |
      +-----------------+----------------------+------------------+
      | staticmethod    | f(\*args)            | f(\*args)        |
      +-----------------+----------------------+------------------+
      | classmethod     | f(type(obj), \*args) | f(klass, \*args) |
      +-----------------+----------------------+------------------+

Static methods return the underlying function without changes.  Calling either
``c.f`` or ``C.f`` is the equivalent of a direct lookup into
``object.__getattribute__(c, "f")`` or ``object.__getattribute__(C, "f")``. As a
result, the function becomes identically accessible from either an object or a
class.

Good candidates for static methods are methods that do not reference the
``self`` variable.

For instance, a statistics package may include a container class for
experimental data.  The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However,
there may be useful functions which are conceptually related but do not depend
on the data.  For instance, ``erf(x)`` is handy conversion routine that comes up
in statistical work but does not directly depend on a particular dataset.
It can be called either from an object or the class:  ``s.erf(1.5) --> .9332`` or
``Sample.erf(1.5) --> .9332``.

Since staticmethods return the underlying function with no changes, the example
calls are unexciting::

    >>> class E(object):
    ...     def f(x):
    ...         print x
    ...     f = staticmethod(f)
    ...
    >>> print E.f(3)
    3
    >>> print E().f(3)
    3

Using the non-data descriptor protocol, a pure Python version of
:func:`staticmethod` would look like this::

    class StaticMethod(object):
        "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

        def __init__(self, f):
            self.f = f

        def __get__(self, obj, objtype=None):
            return self.f

Unlike static methods, class methods prepend the class reference to the
argument list before calling the function.  This format is the same
for whether the caller is an object or a class::

    >>> class E(object):
    ...     def f(klass, x):
    ...          return klass.__name__, x
    ...     f = classmethod(f)
    ...
    >>> print E.f(3)
    ('E', 3)
    >>> print E().f(3)
    ('E', 3)


This behavior is useful whenever the function only needs to have a class
reference and does not care about any underlying data.  One use for classmethods
is to create alternate class constructors.  In Python 2.3, the classmethod
:func:`dict.fromkeys` creates a new dictionary from a list of keys.  The pure
Python equivalent is::

    class Dict(object):
        . . .
        def fromkeys(klass, iterable, value=None):
            "Emulate dict_fromkeys() in Objects/dictobject.c"
            d = klass()
            for key in iterable:
                d[key] = value
            return d
        fromkeys = classmethod(fromkeys)

Now a new dictionary of unique keys can be constructed like this::

    >>> Dict.fromkeys('abracadabra')
    {'a': None, 'r': None, 'b': None, 'c': None, 'd': None}

Using the non-data descriptor protocol, a pure Python version of
:func:`classmethod` would look like this::

    class ClassMethod(object):
        "Emulate PyClassMethod_Type() in Objects/funcobject.c"

        def __init__(self, f):
            self.f = f

        def __get__(self, obj, klass=None):
            if klass is None:
                klass = type(obj)
            def newfunc(*args):
                return self.f(klass, *args)
            return newfunc

PK	%�\�N�w,w,%html/_sources/howto/doanddont.rst.txtnu�[���************************************
  Idioms and Anti-Idioms in Python
************************************

:Author: Moshe Zadka

This document is placed in the public domain.


.. topic:: Abstract

   This document can be considered a companion to the tutorial. It shows how to use
   Python, and even more importantly, how *not* to use Python.


Language Constructs You Should Not Use
======================================

While Python has relatively few gotchas compared to other languages, it still
has some constructs which are only useful in corner cases, or are plain
dangerous.


from module import \*
---------------------


Inside Function Definitions
^^^^^^^^^^^^^^^^^^^^^^^^^^^

``from module import *`` is *invalid* inside function definitions. While many
versions of Python do not check for the invalidity, it does not make it more
valid, no more than having a smart lawyer makes a man innocent. Do not use it
like that ever. Even in versions where it was accepted, it made the function
execution slower, because the compiler could not be certain which names were
local and which were global. In Python 2.1 this construct causes warnings, and
sometimes even errors.


At Module Level
^^^^^^^^^^^^^^^

While it is valid to use ``from module import *`` at module level it is usually
a bad idea. For one, this loses an important property Python otherwise has ---
you can know where each toplevel name is defined by a simple "search" function
in your favourite editor. You also open yourself to trouble in the future, if
some module grows additional functions or classes.

One of the most awful questions asked on the newsgroup is why this code::

   f = open("www")
   f.read()

does not work. Of course, it works just fine (assuming you have a file called
"www".) But it does not work if somewhere in the module, the statement ``from
os import *`` is present. The :mod:`os` module has a function called
:func:`open` which returns an integer. While it is very useful, shadowing a
builtin is one of its least useful properties.

Remember, you can never know for sure what names a module exports, so either
take what you need --- ``from module import name1, name2``, or keep them in the
module and access on a per-need basis ---  ``import module;print module.name``.


When It Is Just Fine
^^^^^^^^^^^^^^^^^^^^

There are situations in which ``from module import *`` is just fine:

* The interactive prompt. For example, ``from math import *`` makes Python an
  amazing scientific calculator.

* When extending a module in C with a module in Python.

* When the module advertises itself as ``from import *`` safe.


Unadorned :keyword:`exec`, :func:`execfile` and friends
-------------------------------------------------------

The word "unadorned" refers to the use without an explicit dictionary, in which
case those constructs evaluate code in the *current* environment. This is
dangerous for the same reasons ``from import *`` is dangerous --- it might step
over variables you are counting on and mess up things for the rest of your code.
Simply do not do that.

Bad examples::

   >>> for name in sys.argv[1:]:
   >>>     exec "%s=1" % name
   >>> def func(s, **kw):
   >>>     for var, val in kw.items():
   >>>         exec "s.%s=val" % var  # invalid!
   >>> execfile("handler.py")
   >>> handle()

Good examples::

   >>> d = {}
   >>> for name in sys.argv[1:]:
   >>>     d[name] = 1
   >>> def func(s, **kw):
   >>>     for var, val in kw.items():
   >>>         setattr(s, var, val)
   >>> d={}
   >>> execfile("handle.py", d, d)
   >>> handle = d['handle']
   >>> handle()


from module import name1, name2
-------------------------------

This is a "don't" which is much weaker than the previous "don't"s but is still
something you should not do if you don't have good reasons to do that. The
reason it is usually a bad idea is because you suddenly have an object which lives
in two separate namespaces. When the binding in one namespace changes, the
binding in the other will not, so there will be a discrepancy between them. This
happens when, for example, one module is reloaded, or changes the definition of
a function at runtime.

Bad example::

   # foo.py
   a = 1

   # bar.py
   from foo import a
   if something():
       a = 2 # danger: foo.a != a

Good example::

   # foo.py
   a = 1

   # bar.py
   import foo
   if something():
       foo.a = 2


except:
-------

Python has the ``except:`` clause, which catches all exceptions. Since *every*
error in Python raises an exception, using ``except:`` can make many
programming errors look like runtime problems, which hinders the debugging
process.

The following code shows a great example of why this is bad::

   try:
       foo = opne("file") # misspelled "open"
   except:
       sys.exit("could not open file!")

The second line triggers a :exc:`NameError`, which is caught by the except
clause. The program will exit, and the error message the program prints will
make you think the problem is the readability of ``"file"`` when in fact
the real error has nothing to do with ``"file"``.

A better way to write the above is ::

   try:
       foo = opne("file")
   except IOError:
       sys.exit("could not open file")

When this is run, Python will produce a traceback showing the :exc:`NameError`,
and it will be immediately apparent what needs to be fixed.

.. index:: bare except, except; bare

Because ``except:`` catches *all* exceptions, including :exc:`SystemExit`,
:exc:`KeyboardInterrupt`, and :exc:`GeneratorExit` (which is not an error and
should not normally be caught by user code), using a bare ``except:`` is almost
never a good idea.  In situations where you need to catch all "normal" errors,
such as in a framework that runs callbacks, you can catch the base class for
all normal exceptions, :exc:`Exception`.  Unfortunately in Python 2.x it is
possible for third-party code to raise exceptions that do not inherit from
:exc:`Exception`, so in Python 2.x there are some cases where you may have to
use a bare ``except:`` and manually re-raise the exceptions you don't want
to catch.


Exceptions
==========

Exceptions are a useful feature of Python. You should learn to raise them
whenever something unexpected occurs, and catch them only where you can do
something about them.

The following is a very popular anti-idiom ::

   def get_status(file):
       if not os.path.exists(file):
           print "file not found"
           sys.exit(1)
       return open(file).readline()

Consider the case where the file gets deleted between the time the call to
:func:`os.path.exists` is made and the time :func:`open` is called. In that
case the last line will raise an :exc:`IOError`.  The same thing would happen
if *file* exists but has no read permission.  Since testing this on a normal
machine on existent and non-existent files makes it seem bugless, the test
results will seem fine, and the code will get shipped.  Later an unhandled
:exc:`IOError` (or perhaps some other :exc:`EnvironmentError`) escapes to the
user, who gets to watch the ugly traceback.

Here is a somewhat better way to do it. ::

   def get_status(file):
       try:
           return open(file).readline()
       except EnvironmentError as err:
           print "Unable to open file: {}".format(err)
           sys.exit(1)

In this version, *either* the file gets opened and the line is read (so it
works even on flaky NFS or SMB connections), or an error message is printed
that provides all the available information on why the open failed, and the
application is aborted.

However, even this version of :func:`get_status` makes too many assumptions ---
that it will only be used in a short running script, and not, say, in a long
running server. Sure, the caller could do something like ::

   try:
       status = get_status(log)
   except SystemExit:
       status = None

But there is a better way.  You should try to use as few ``except`` clauses in
your code as you can --- the ones you do use will usually be inside calls which
should always succeed, or a catch-all in a main function.

So, an even better version of :func:`get_status()` is probably ::

   def get_status(file):
       return open(file).readline()

The caller can deal with the exception if it wants (for example, if it tries
several files in a loop), or just let the exception filter upwards to *its*
caller.

But the last version still has a serious problem --- due to implementation
details in CPython, the file would not be closed when an exception is raised
until the exception handler finishes; and, worse, in other implementations
(e.g., Jython) it might not be closed at all regardless of whether or not
an exception is raised.

The best version of this function uses the ``open()`` call as a context
manager, which will ensure that the file gets closed as soon as the
function returns::

   def get_status(file):
       with open(file) as fp:
           return fp.readline()


Using the Batteries
===================

Every so often, people seem to be writing stuff in the Python library again,
usually poorly. While the occasional module has a poor interface, it is usually
much better to use the rich standard library and data types that come with
Python than inventing your own.

A useful module very few people know about is :mod:`os.path`. It  always has the
correct path arithmetic for your operating system, and will usually be much
better than whatever you come up with yourself.

Compare::

   # ugh!
   return dir+"/"+file
   # better
   return os.path.join(dir, file)

More useful functions in :mod:`os.path`: :func:`basename`,  :func:`dirname` and
:func:`splitext`.

There are also many useful built-in functions people seem not to be aware of
for some reason: :func:`min` and :func:`max` can find the minimum/maximum of
any sequence with comparable semantics, for example, yet many people write
their own :func:`max`/:func:`min`. Another highly useful function is
:func:`reduce` which can be used to repeatedly apply a binary operation to a
sequence, reducing it to a single value.  For example, compute a factorial
with a series of multiply operations::

   >>> n = 4
   >>> import operator
   >>> reduce(operator.mul, range(1, n+1))
   24

When it comes to parsing numbers, note that :func:`float`, :func:`int` and
:func:`long` all accept string arguments and will reject ill-formed strings
by raising an :exc:`ValueError`.


Using Backslash to Continue Statements
======================================

Since Python treats a newline as a statement terminator, and since statements
are often more than is comfortable to put in one line, many people do::

   if foo.bar()['first'][0] == baz.quux(1, 2)[5:9] and \
      calculate_number(10, 20) != forbulate(500, 360):
         pass

You should realize that this is dangerous: a stray space after the ``\`` would
make this line wrong, and stray spaces are notoriously hard to see in editors.
In this case, at least it would be a syntax error, but if the code was::

   value = foo.bar()['first'][0]*baz.quux(1, 2)[5:9] \
           + calculate_number(10, 20)*forbulate(500, 360)

then it would just be subtly wrong.

It is usually much better to use the implicit continuation inside parenthesis:

This version is bulletproof::

   value = (foo.bar()['first'][0]*baz.quux(1, 2)[5:9]
           + calculate_number(10, 20)*forbulate(500, 360))

PK	%�\<����&html/_sources/howto/functional.rst.txtnu�[���********************************
  Functional Programming HOWTO
********************************

:Author: A. M. Kuchling
:Release: 0.31

In this document, we'll take a tour of Python's features suitable for
implementing programs in a functional style.  After an introduction to the
concepts of functional programming, we'll look at language features such as
:term:`iterator`\s and :term:`generator`\s and relevant library modules such as
:mod:`itertools` and :mod:`functools`.


Introduction
============

This section explains the basic concept of functional programming; if you're
just interested in learning about Python language features, skip to the next
section.

Programming languages support decomposing problems in several different ways:

* Most programming languages are **procedural**: programs are lists of
  instructions that tell the computer what to do with the program's input.  C,
  Pascal, and even Unix shells are procedural languages.

* In **declarative** languages, you write a specification that describes the
  problem to be solved, and the language implementation figures out how to
  perform the computation efficiently.  SQL is the declarative language you're
  most likely to be familiar with; a SQL query describes the data set you want
  to retrieve, and the SQL engine decides whether to scan tables or use indexes,
  which subclauses should be performed first, etc.

* **Object-oriented** programs manipulate collections of objects.  Objects have
  internal state and support methods that query or modify this internal state in
  some way. Smalltalk and Java are object-oriented languages.  C++ and Python
  are languages that support object-oriented programming, but don't force the
  use of object-oriented features.

* **Functional** programming decomposes a problem into a set of functions.
  Ideally, functions only take inputs and produce outputs, and don't have any
  internal state that affects the output produced for a given input.  Well-known
  functional languages include the ML family (Standard ML, OCaml, and other
  variants) and Haskell.

The designers of some computer languages choose to emphasize one particular
approach to programming.  This often makes it difficult to write programs that
use a different approach.  Other languages are multi-paradigm languages that
support several different approaches.  Lisp, C++, and Python are
multi-paradigm; you can write programs or libraries that are largely
procedural, object-oriented, or functional in all of these languages.  In a
large program, different sections might be written using different approaches;
the GUI might be object-oriented while the processing logic is procedural or
functional, for example.

In a functional program, input flows through a set of functions. Each function
operates on its input and produces some output.  Functional style discourages
functions with side effects that modify internal state or make other changes
that aren't visible in the function's return value.  Functions that have no side
effects at all are called **purely functional**.  Avoiding side effects means
not using data structures that get updated as a program runs; every function's
output must only depend on its input.

Some languages are very strict about purity and don't even have assignment
statements such as ``a=3`` or ``c = a + b``, but it's difficult to avoid all
side effects.  Printing to the screen or writing to a disk file are side
effects, for example.  For example, in Python a ``print`` statement or a
``time.sleep(1)`` both return no useful value; they're only called for their
side effects of sending some text to the screen or pausing execution for a
second.

Python programs written in functional style usually won't go to the extreme of
avoiding all I/O or all assignments; instead, they'll provide a
functional-appearing interface but will use non-functional features internally.
For example, the implementation of a function will still use assignments to
local variables, but won't modify global variables or have other side effects.

Functional programming can be considered the opposite of object-oriented
programming.  Objects are little capsules containing some internal state along
with a collection of method calls that let you modify this state, and programs
consist of making the right set of state changes.  Functional programming wants
to avoid state changes as much as possible and works with data flowing between
functions.  In Python you might combine the two approaches by writing functions
that take and return instances representing objects in your application (e-mail
messages, transactions, etc.).

Functional design may seem like an odd constraint to work under.  Why should you
avoid objects and side effects?  There are theoretical and practical advantages
to the functional style:

* Formal provability.
* Modularity.
* Composability.
* Ease of debugging and testing.


Formal provability
------------------

A theoretical benefit is that it's easier to construct a mathematical proof that
a functional program is correct.

For a long time researchers have been interested in finding ways to
mathematically prove programs correct.  This is different from testing a program
on numerous inputs and concluding that its output is usually correct, or reading
a program's source code and concluding that the code looks right; the goal is
instead a rigorous proof that a program produces the right result for all
possible inputs.

The technique used to prove programs correct is to write down **invariants**,
properties of the input data and of the program's variables that are always
true.  For each line of code, you then show that if invariants X and Y are true
**before** the line is executed, the slightly different invariants X' and Y' are
true **after** the line is executed.  This continues until you reach the end of
the program, at which point the invariants should match the desired conditions
on the program's output.

Functional programming's avoidance of assignments arose because assignments are
difficult to handle with this technique; assignments can break invariants that
were true before the assignment without producing any new invariants that can be
propagated onward.

Unfortunately, proving programs correct is largely impractical and not relevant
to Python software. Even trivial programs require proofs that are several pages
long; the proof of correctness for a moderately complicated program would be
enormous, and few or none of the programs you use daily (the Python interpreter,
your XML parser, your web browser) could be proven correct.  Even if you wrote
down or generated a proof, there would then be the question of verifying the
proof; maybe there's an error in it, and you wrongly believe you've proved the
program correct.


Modularity
----------

A more practical benefit of functional programming is that it forces you to
break apart your problem into small pieces.  Programs are more modular as a
result.  It's easier to specify and write a small function that does one thing
than a large function that performs a complicated transformation.  Small
functions are also easier to read and to check for errors.


Ease of debugging and testing
-----------------------------

Testing and debugging a functional-style program is easier.

Debugging is simplified because functions are generally small and clearly
specified.  When a program doesn't work, each function is an interface point
where you can check that the data are correct.  You can look at the intermediate
inputs and outputs to quickly isolate the function that's responsible for a bug.

Testing is easier because each function is a potential subject for a unit test.
Functions don't depend on system state that needs to be replicated before
running a test; instead you only have to synthesize the right input and then
check that the output matches expectations.


Composability
-------------

As you work on a functional-style program, you'll write a number of functions
with varying inputs and outputs.  Some of these functions will be unavoidably
specialized to a particular application, but others will be useful in a wide
variety of programs.  For example, a function that takes a directory path and
returns all the XML files in the directory, or a function that takes a filename
and returns its contents, can be applied to many different situations.

Over time you'll form a personal library of utilities.  Often you'll assemble
new programs by arranging existing functions in a new configuration and writing
a few functions specialized for the current task.


Iterators
=========

I'll start by looking at a Python language feature that's an important
foundation for writing functional-style programs: iterators.

An iterator is an object representing a stream of data; this object returns the
data one element at a time.  A Python iterator must support a method called
``next()`` that takes no arguments and always returns the next element of the
stream.  If there are no more elements in the stream, ``next()`` must raise the
``StopIteration`` exception.  Iterators don't have to be finite, though; it's
perfectly reasonable to write an iterator that produces an infinite stream of
data.

The built-in :func:`iter` function takes an arbitrary object and tries to return
an iterator that will return the object's contents or elements, raising
:exc:`TypeError` if the object doesn't support iteration.  Several of Python's
built-in data types support iteration, the most common being lists and
dictionaries.  An object is called an **iterable** object if you can get an
iterator for it.

You can experiment with the iteration interface manually:

    >>> L = [1,2,3]
    >>> it = iter(L)
    >>> print it
    <...iterator object at ...>
    >>> it.next()
    1
    >>> it.next()
    2
    >>> it.next()
    3
    >>> it.next()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    StopIteration
    >>>

Python expects iterable objects in several different contexts, the most
important being the ``for`` statement.  In the statement ``for X in Y``, Y must
be an iterator or some object for which ``iter()`` can create an iterator.
These two statements are equivalent::

    for i in iter(obj):
        print i

    for i in obj:
        print i

Iterators can be materialized as lists or tuples by using the :func:`list` or
:func:`tuple` constructor functions:

    >>> L = [1,2,3]
    >>> iterator = iter(L)
    >>> t = tuple(iterator)
    >>> t
    (1, 2, 3)

Sequence unpacking also supports iterators: if you know an iterator will return
N elements, you can unpack them into an N-tuple:

    >>> L = [1,2,3]
    >>> iterator = iter(L)
    >>> a,b,c = iterator
    >>> a,b,c
    (1, 2, 3)

Built-in functions such as :func:`max` and :func:`min` can take a single
iterator argument and will return the largest or smallest element.  The ``"in"``
and ``"not in"`` operators also support iterators: ``X in iterator`` is true if
X is found in the stream returned by the iterator.  You'll run into obvious
problems if the iterator is infinite; ``max()``, ``min()``
will never return, and if the element X never appears in the stream, the
``"in"`` and ``"not in"`` operators won't return either.

Note that you can only go forward in an iterator; there's no way to get the
previous element, reset the iterator, or make a copy of it.  Iterator objects
can optionally provide these additional capabilities, but the iterator protocol
only specifies the ``next()`` method.  Functions may therefore consume all of
the iterator's output, and if you need to do something different with the same
stream, you'll have to create a new iterator.



Data Types That Support Iterators
---------------------------------

We've already seen how lists and tuples support iterators.  In fact, any Python
sequence type, such as strings, will automatically support creation of an
iterator.

Calling :func:`iter` on a dictionary returns an iterator that will loop over the
dictionary's keys:

.. not a doctest since dict ordering varies across Pythons

::

    >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
    ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
    >>> for key in m:
    ...     print key, m[key]
    Mar 3
    Feb 2
    Aug 8
    Sep 9
    Apr 4
    Jun 6
    Jul 7
    Jan 1
    May 5
    Nov 11
    Dec 12
    Oct 10

Note that the order is essentially random, because it's based on the hash
ordering of the objects in the dictionary.

Applying ``iter()`` to a dictionary always loops over the keys, but dictionaries
have methods that return other iterators.  If you want to iterate over keys,
values, or key/value pairs, you can explicitly call the ``iterkeys()``,
``itervalues()``, or ``iteritems()`` methods to get an appropriate iterator.

The :func:`dict` constructor can accept an iterator that returns a finite stream
of ``(key, value)`` tuples:

    >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
    >>> dict(iter(L))
    {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}

Files also support iteration by calling the ``readline()`` method until there
are no more lines in the file.  This means you can read each line of a file like
this::

    for line in file:
        # do something for each line
        ...

Sets can take their contents from an iterable and let you iterate over the set's
elements::

    S = set((2, 3, 5, 7, 11, 13))
    for i in S:
        print i



Generator expressions and list comprehensions
=============================================

Two common operations on an iterator's output are 1) performing some operation
for every element, 2) selecting a subset of elements that meet some condition.
For example, given a list of strings, you might want to strip off trailing
whitespace from each line or extract all the strings containing a given
substring.

List comprehensions and generator expressions (short form: "listcomps" and
"genexps") are a concise notation for such operations, borrowed from the
functional programming language Haskell (https://www.haskell.org/).  You can strip
all the whitespace from a stream of strings with the following code::

    line_list = ['  line 1\n', 'line 2  \n', ...]

    # Generator expression -- returns iterator
    stripped_iter = (line.strip() for line in line_list)

    # List comprehension -- returns list
    stripped_list = [line.strip() for line in line_list]

You can select only certain elements by adding an ``"if"`` condition::

    stripped_list = [line.strip() for line in line_list
                     if line != ""]

With a list comprehension, you get back a Python list; ``stripped_list`` is a
list containing the resulting lines, not an iterator.  Generator expressions
return an iterator that computes the values as necessary, not needing to
materialize all the values at once.  This means that list comprehensions aren't
useful if you're working with iterators that return an infinite stream or a very
large amount of data.  Generator expressions are preferable in these situations.

Generator expressions are surrounded by parentheses ("()") and list
comprehensions are surrounded by square brackets ("[]").  Generator expressions
have the form::

    ( expression for expr in sequence1
                 if condition1
                 for expr2 in sequence2
                 if condition2
                 for expr3 in sequence3 ...
                 if condition3
                 for exprN in sequenceN
                 if conditionN )

Again, for a list comprehension only the outside brackets are different (square
brackets instead of parentheses).

The elements of the generated output will be the successive values of
``expression``.  The ``if`` clauses are all optional; if present, ``expression``
is only evaluated and added to the result when ``condition`` is true.

Generator expressions always have to be written inside parentheses, but the
parentheses signalling a function call also count.  If you want to create an
iterator that will be immediately passed to a function you can write::

    obj_total = sum(obj.count for obj in list_all_objects())

The ``for...in`` clauses contain the sequences to be iterated over.  The
sequences do not have to be the same length, because they are iterated over from
left to right, **not** in parallel.  For each element in ``sequence1``,
``sequence2`` is looped over from the beginning.  ``sequence3`` is then looped
over for each resulting pair of elements from ``sequence1`` and ``sequence2``.

To put it another way, a list comprehension or generator expression is
equivalent to the following Python code::

    for expr1 in sequence1:
        if not (condition1):
            continue   # Skip this element
        for expr2 in sequence2:
            if not (condition2):
                continue   # Skip this element
            ...
            for exprN in sequenceN:
                if not (conditionN):
                    continue   # Skip this element

                # Output the value of
                # the expression.

This means that when there are multiple ``for...in`` clauses but no ``if``
clauses, the length of the resulting output will be equal to the product of the
lengths of all the sequences.  If you have two lists of length 3, the output
list is 9 elements long:

.. doctest::
    :options: +NORMALIZE_WHITESPACE

    >>> seq1 = 'abc'
    >>> seq2 = (1,2,3)
    >>> [(x,y) for x in seq1 for y in seq2]
    [('a', 1), ('a', 2), ('a', 3),
     ('b', 1), ('b', 2), ('b', 3),
     ('c', 1), ('c', 2), ('c', 3)]

To avoid introducing an ambiguity into Python's grammar, if ``expression`` is
creating a tuple, it must be surrounded with parentheses.  The first list
comprehension below is a syntax error, while the second one is correct::

    # Syntax error
    [ x,y for x in seq1 for y in seq2]
    # Correct
    [ (x,y) for x in seq1 for y in seq2]


Generators
==========

Generators are a special class of functions that simplify the task of writing
iterators.  Regular functions compute a value and return it, but generators
return an iterator that returns a stream of values.

You're doubtless familiar with how regular function calls work in Python or C.
When you call a function, it gets a private namespace where its local variables
are created.  When the function reaches a ``return`` statement, the local
variables are destroyed and the value is returned to the caller.  A later call
to the same function creates a new private namespace and a fresh set of local
variables. But, what if the local variables weren't thrown away on exiting a
function?  What if you could later resume the function where it left off?  This
is what generators provide; they can be thought of as resumable functions.

Here's the simplest example of a generator function:

.. testcode::

    def generate_ints(N):
        for i in range(N):
            yield i

Any function containing a ``yield`` keyword is a generator function; this is
detected by Python's :term:`bytecode` compiler which compiles the function
specially as a result.

When you call a generator function, it doesn't return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the ``yield`` expression, the generator outputs the value of ``i``, similar to a
``return`` statement.  The big difference between ``yield`` and a ``return``
statement is that on reaching a ``yield`` the generator's state of execution is
suspended and local variables are preserved.  On the next call to the
generator's ``.next()`` method, the function will resume executing.

Here's a sample usage of the ``generate_ints()`` generator:

    >>> gen = generate_ints(3)
    >>> gen
    <generator object generate_ints at ...>
    >>> gen.next()
    0
    >>> gen.next()
    1
    >>> gen.next()
    2
    >>> gen.next()
    Traceback (most recent call last):
      File "stdin", line 1, in <module>
      File "stdin", line 2, in generate_ints
    StopIteration

You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
generate_ints(3)``.

Inside a generator function, the ``return`` statement can only be used without a
value, and signals the end of the procession of values; after executing a
``return`` the generator cannot return any further values.  ``return`` with a
value, such as ``return 5``, is a syntax error inside a generator function.  The
end of the generator's results can also be indicated by raising
``StopIteration`` manually, or by just letting the flow of execution fall off
the bottom of the function.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting ``self.count`` to
0, and having the ``next()`` method increment ``self.count`` and return it.
However, for a moderately complicated generator, writing a corresponding class
can be much messier.

The test suite included with Python's library, ``test_generators.py``, contains
a number of more interesting examples.  Here's one generator that implements an
in-order traversal of a tree using generators recursively. ::

    # A recursive generator that generates Tree leaves in in-order.
    def inorder(t):
        if t:
            for x in inorder(t.left):
                yield x

            yield t.label

            for x in inorder(t.right):
                yield x

Two other examples in ``test_generators.py`` produce solutions for the N-Queens
problem (placing N queens on an NxN chess board so that no queen threatens
another) and the Knight's Tour (finding a route that takes a knight to every
square of an NxN chessboard without visiting any square twice).



Passing values into a generator
-------------------------------

In Python 2.4 and earlier, generators only produced output.  Once a generator's
code was invoked to create an iterator, there was no way to pass any new
information into the function when its execution is resumed.  You could hack
together this ability by making the generator look at a global variable or by
passing in some mutable object that callers then modify, but these approaches
are messy.

In Python 2.5 there's a simple way to pass values into a generator.
:keyword:`yield` became an expression, returning a value that can be assigned to
a variable or otherwise operated on::

    val = (yield i)

I recommend that you **always** put parentheses around a ``yield`` expression
when you're doing something with the returned value, as in the above example.
The parentheses aren't always necessary, but it's easier to always add them
instead of having to remember when they're needed.

(PEP 342 explains the exact rules, which are that a ``yield``-expression must
always be parenthesized except when it occurs at the top-level expression on the
right-hand side of an assignment.  This means you can write ``val = yield i``
but have to use parentheses when there's an operation, as in ``val = (yield i)
+ 12``.)

Values are sent into a generator by calling its ``send(value)`` method.  This
method resumes the generator's code and the ``yield`` expression returns the
specified value.  If the regular ``next()`` method is called, the ``yield``
returns ``None``.

Here's a simple counter that increments by 1 and allows changing the value of
the internal counter.

.. testcode::

    def counter (maximum):
        i = 0
        while i < maximum:
            val = (yield i)
            # If value provided, change counter
            if val is not None:
                i = val
            else:
                i += 1

And here's an example of changing the counter:

    >>> it = counter(10)
    >>> print it.next()
    0
    >>> print it.next()
    1
    >>> print it.send(8)
    8
    >>> print it.next()
    9
    >>> print it.next()
    Traceback (most recent call last):
      File "t.py", line 15, in <module>
        print it.next()
    StopIteration

Because ``yield`` will often be returning ``None``, you should always check for
this case.  Don't just use its value in expressions unless you're sure that the
``send()`` method will be the only method used to resume your generator
function.

In addition to ``send()``, there are two other new methods on generators:

* ``throw(type, value=None, traceback=None)`` is used to raise an exception
  inside the generator; the exception is raised by the ``yield`` expression
  where the generator's execution is paused.

* ``close()`` raises a :exc:`GeneratorExit` exception inside the generator to
  terminate the iteration.  On receiving this exception, the generator's code
  must either raise :exc:`GeneratorExit` or :exc:`StopIteration`; catching the
  exception and doing anything else is illegal and will trigger a
  :exc:`RuntimeError`.  ``close()`` will also be called by Python's garbage
  collector when the generator is garbage-collected.

  If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
  using a ``try: ... finally:`` suite instead of catching :exc:`GeneratorExit`.

The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.

Generators also become **coroutines**, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a ``return`` statement), but coroutines can be entered, exited,
and resumed at many different points (the ``yield`` statements).


Built-in functions
==================

Let's look in more detail at built-in functions often used with iterators.

Two of Python's built-in functions, :func:`map` and :func:`filter`, are somewhat
obsolete; they duplicate the features of list comprehensions but return actual
lists instead of iterators.

``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0], iterB[0]),
f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.

    >>> def upper(s):
    ...     return s.upper()

    >>> map(upper, ['sentence', 'fragment'])
    ['SENTENCE', 'FRAGMENT']

    >>> [upper(s) for s in ['sentence', 'fragment']]
    ['SENTENCE', 'FRAGMENT']

As shown above, you can achieve the same effect with a list comprehension.  The
:func:`itertools.imap` function does the same thing but can handle infinite
iterators; it'll be discussed later, in the section on the :mod:`itertools` module.

``filter(predicate, iter)`` returns a list that contains all the sequence
elements that meet a certain condition, and is similarly duplicated by list
comprehensions.  A **predicate** is a function that returns the truth value of
some condition; for use with :func:`filter`, the predicate must take a single
value.

    >>> def is_even(x):
    ...     return (x % 2) == 0

    >>> filter(is_even, range(10))
    [0, 2, 4, 6, 8]

This can also be written as a list comprehension:

    >>> [x for x in range(10) if is_even(x)]
    [0, 2, 4, 6, 8]

:func:`filter` also has a counterpart in the :mod:`itertools` module,
:func:`itertools.ifilter`, that returns an iterator and can therefore handle
infinite sequences just as :func:`itertools.imap` can.

``reduce(func, iter, [initial_value])`` doesn't have a counterpart in the
:mod:`itertools` module because it cumulatively performs an operation on all the
iterable's elements and therefore can't be applied to infinite iterables.
``func`` must be a function that takes two elements and returns a single value.
:func:`reduce` takes the first two elements A and B returned by the iterator and
calculates ``func(A, B)``.  It then requests the third element, C, calculates
``func(func(A, B), C)``, combines this result with the fourth element returned,
and continues until the iterable is exhausted.  If the iterable returns no
values at all, a :exc:`TypeError` exception is raised.  If the initial value is
supplied, it's used as a starting point and ``func(initial_value, A)`` is the
first calculation.

    >>> import operator
    >>> reduce(operator.concat, ['A', 'BB', 'C'])
    'ABBC'
    >>> reduce(operator.concat, [])
    Traceback (most recent call last):
      ...
    TypeError: reduce() of empty sequence with no initial value
    >>> reduce(operator.mul, [1,2,3], 1)
    6
    >>> reduce(operator.mul, [], 1)
    1

If you use :func:`operator.add` with :func:`reduce`, you'll add up all the
elements of the iterable.  This case is so common that there's a special
built-in called :func:`sum` to compute it:

    >>> reduce(operator.add, [1,2,3,4], 0)
    10
    >>> sum([1,2,3,4])
    10
    >>> sum([])
    0

For many uses of :func:`reduce`, though, it can be clearer to just write the
obvious :keyword:`for` loop::

    # Instead of:
    product = reduce(operator.mul, [1,2,3], 1)

    # You can write:
    product = 1
    for i in [1,2,3]:
        product *= i


``enumerate(iter)`` counts off the elements in the iterable, returning 2-tuples
containing the count and each element.

    >>> for item in enumerate(['subject', 'verb', 'object']):
    ...     print item
    (0, 'subject')
    (1, 'verb')
    (2, 'object')

:func:`enumerate` is often used when looping through a list and recording the
indexes at which certain conditions are met::

    f = open('data.txt', 'r')
    for i, line in enumerate(f):
        if line.strip() == '':
            print 'Blank line at line #%i' % i

``sorted(iterable, [cmp=None], [key=None], [reverse=False])`` collects all the
elements of the iterable into a list, sorts the list, and returns the sorted
result.  The ``cmp``, ``key``, and ``reverse`` arguments are passed through to
the constructed list's ``.sort()`` method. ::

    >>> import random
    >>> # Generate 8 random numbers between [0, 10000)
    >>> rand_list = random.sample(range(10000), 8)
    >>> rand_list
    [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
    >>> sorted(rand_list)
    [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
    >>> sorted(rand_list, reverse=True)
    [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]

(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
Python wiki at https://wiki.python.org/moin/HowTo/Sorting.)

The ``any(iter)`` and ``all(iter)`` built-ins look at the truth values of an
iterable's contents.  :func:`any` returns ``True`` if any element in the iterable is
a true value, and :func:`all` returns ``True`` if all of the elements are true
values:

    >>> any([0,1,0])
    True
    >>> any([0,0,0])
    False
    >>> any([1,1,1])
    True
    >>> all([0,1,0])
    False
    >>> all([0,0,0])
    False
    >>> all([1,1,1])
    True


Small functions and the lambda expression
=========================================

When writing functional-style programs, you'll often need little functions that
act as predicates or that combine elements in some way.

If there's a Python built-in or a module function that's suitable, you don't
need to define a new function at all::

    stripped_lines = [line.strip() for line in lines]
    existing_files = filter(os.path.exists, file_list)

If the function you need doesn't exist, you need to write it.  One way to write
small functions is to use the ``lambda`` statement.  ``lambda`` takes a number
of parameters and an expression combining these parameters, and creates a small
function that returns the value of the expression::

    lowercase = lambda x: x.lower()

    print_assign = lambda name, value: name + '=' + str(value)

    adder = lambda x, y: x+y

An alternative is to just use the ``def`` statement and define a function in the
usual way::

    def lowercase(x):
        return x.lower()

    def print_assign(name, value):
        return name + '=' + str(value)

    def adder(x,y):
        return x + y

Which alternative is preferable?  That's a style question; my usual course is to
avoid using ``lambda``.

One reason for my preference is that ``lambda`` is quite limited in the
functions it can define.  The result has to be computable as a single
expression, which means you can't have multiway ``if... elif... else``
comparisons or ``try... except`` statements.  If you try to do too much in a
``lambda`` statement, you'll end up with an overly complicated expression that's
hard to read.  Quick, what's the following code doing?

::

    total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]

You can figure it out, but it takes time to disentangle the expression to figure
out what's going on.  Using a short nested ``def`` statements makes things a
little bit better::

    def combine (a, b):
        return 0, a[1] + b[1]

    total = reduce(combine, items)[1]

But it would be best of all if I had simply used a ``for`` loop::

     total = 0
     for a, b in items:
         total += b

Or the :func:`sum` built-in and a generator expression::

     total = sum(b for a,b in items)

Many uses of :func:`reduce` are clearer when written as ``for`` loops.

Fredrik Lundh once suggested the following set of rules for refactoring uses of
``lambda``:

1) Write a lambda function.
2) Write a comment explaining what the heck that lambda does.
3) Study the comment for a while, and think of a name that captures the essence
   of the comment.
4) Convert the lambda to a def statement, using that name.
5) Remove the comment.

I really like these rules, but you're free to disagree
about whether this lambda-free style is better.


The itertools module
====================

The :mod:`itertools` module contains a number of commonly-used iterators as well
as functions for combining several iterators.  This section will introduce the
module's contents by showing small examples.

The module's functions fall into a few broad classes:

* Functions that create a new iterator based on an existing iterator.
* Functions for treating an iterator's elements as function arguments.
* Functions for selecting portions of an iterator's output.
* A function for grouping an iterator's output.

Creating new iterators
----------------------

``itertools.count(n)`` returns an infinite stream of integers, increasing by 1
each time.  You can optionally supply the starting number, which defaults to 0::

    itertools.count() =>
      0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
    itertools.count(10) =>
      10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

``itertools.cycle(iter)`` saves a copy of the contents of a provided iterable
and returns a new iterator that returns its elements from first to last.  The
new iterator will repeat these elements infinitely. ::

    itertools.cycle([1,2,3,4,5]) =>
      1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...

``itertools.repeat(elem, [n])`` returns the provided element ``n`` times, or
returns the element endlessly if ``n`` is not provided. ::

    itertools.repeat('abc') =>
      abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
    itertools.repeat('abc', 5) =>
      abc, abc, abc, abc, abc

``itertools.chain(iterA, iterB, ...)`` takes an arbitrary number of iterables as
input, and returns all the elements of the first iterator, then all the elements
of the second, and so on, until all of the iterables have been exhausted. ::

    itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
      a, b, c, 1, 2, 3

``itertools.izip(iterA, iterB, ...)`` takes one element from each iterable and
returns them in a tuple::

    itertools.izip(['a', 'b', 'c'], (1, 2, 3)) =>
      ('a', 1), ('b', 2), ('c', 3)

It's similar to the built-in :func:`zip` function, but doesn't construct an
in-memory list and exhaust all the input iterators before returning; instead
tuples are constructed and returned only if they're requested.  (The technical
term for this behaviour is `lazy evaluation
<http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)

This iterator is intended to be used with iterables that are all of the same
length.  If the iterables are of different lengths, the resulting stream will be
the same length as the shortest iterable. ::

    itertools.izip(['a', 'b'], (1, 2, 3)) =>
      ('a', 1), ('b', 2)

You should avoid doing this, though, because an element may be taken from the
longer iterators and discarded.  This means you can't go on to use the iterators
further because you risk skipping a discarded element.

``itertools.islice(iter, [start], stop, [step])`` returns a stream that's a
slice of the iterator.  With a single ``stop`` argument, it will return the
first ``stop`` elements.  If you supply a starting index, you'll get
``stop-start`` elements, and if you supply a value for ``step``, elements will
be skipped accordingly.  Unlike Python's string and list slicing, you can't use
negative values for ``start``, ``stop``, or ``step``. ::

    itertools.islice(range(10), 8) =>
      0, 1, 2, 3, 4, 5, 6, 7
    itertools.islice(range(10), 2, 8) =>
      2, 3, 4, 5, 6, 7
    itertools.islice(range(10), 2, 8, 2) =>
      2, 4, 6

``itertools.tee(iter, [n])`` replicates an iterator; it returns ``n``
independent iterators that will all return the contents of the source iterator.
If you don't supply a value for ``n``, the default is 2.  Replicating iterators
requires saving some of the contents of the source iterator, so this can consume
significant memory if the iterator is large and one of the new iterators is
consumed more than the others. ::

        itertools.tee( itertools.count() ) =>
           iterA, iterB

        where iterA ->
           0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...

        and   iterB ->
           0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...


Calling functions on elements
-----------------------------

Two functions are used for calling other functions on the contents of an
iterable.

``itertools.imap(f, iterA, iterB, ...)`` returns a stream containing
``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``::

    itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) =>
      6, 8, 8

The ``operator`` module contains a set of functions corresponding to Python's
operators.  Some examples are ``operator.add(a, b)`` (adds two values),
``operator.ne(a, b)`` (same as ``a!=b``), and ``operator.attrgetter('id')``
(returns a callable that fetches the ``"id"`` attribute).

``itertools.starmap(func, iter)`` assumes that the iterable will return a stream
of tuples, and calls ``f()`` using these tuples as the arguments::

    itertools.starmap(os.path.join,
                      [('/usr', 'bin', 'java'), ('/bin', 'python'),
                       ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])
    =>
      /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby


Selecting elements
------------------

Another group of functions chooses a subset of an iterator's elements based on a
predicate.

``itertools.ifilter(predicate, iter)`` returns all the elements for which the
predicate returns true::

    def is_even(x):
        return (x % 2) == 0

    itertools.ifilter(is_even, itertools.count()) =>
      0, 2, 4, 6, 8, 10, 12, 14, ...

``itertools.ifilterfalse(predicate, iter)`` is the opposite, returning all
elements for which the predicate returns false::

    itertools.ifilterfalse(is_even, itertools.count()) =>
      1, 3, 5, 7, 9, 11, 13, 15, ...

``itertools.takewhile(predicate, iter)`` returns elements for as long as the
predicate returns true.  Once the predicate returns false, the iterator will
signal the end of its results.

::

    def less_than_10(x):
        return (x < 10)

    itertools.takewhile(less_than_10, itertools.count()) =>
      0, 1, 2, 3, 4, 5, 6, 7, 8, 9

    itertools.takewhile(is_even, itertools.count()) =>
      0

``itertools.dropwhile(predicate, iter)`` discards elements while the predicate
returns true, and then returns the rest of the iterable's results.

::

    itertools.dropwhile(less_than_10, itertools.count()) =>
      10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...

    itertools.dropwhile(is_even, itertools.count()) =>
      1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...


Grouping elements
-----------------

The last function I'll discuss, ``itertools.groupby(iter, key_func=None)``, is
the most complicated.  ``key_func(elem)`` is a function that can compute a key
value for each element returned by the iterable.  If you don't supply a key
function, the key is simply each element itself.

``groupby()`` collects all the consecutive elements from the underlying iterable
that have the same key value, and returns a stream of 2-tuples containing a key
value and an iterator for the elements with that key.

::

    city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
                 ('Anchorage', 'AK'), ('Nome', 'AK'),
                 ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
                 ...
                ]

    def get_state ((city, state)):
        return state

    itertools.groupby(city_list, get_state) =>
      ('AL', iterator-1),
      ('AK', iterator-2),
      ('AZ', iterator-3), ...

    where
    iterator-1 =>
      ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
    iterator-2 =>
      ('Anchorage', 'AK'), ('Nome', 'AK')
    iterator-3 =>
      ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')

``groupby()`` assumes that the underlying iterable's contents will already be
sorted based on the key.  Note that the returned iterators also use the
underlying iterable, so you have to consume the results of iterator-1 before
requesting iterator-2 and its corresponding key.


The functools module
====================

The :mod:`functools` module in Python 2.5 contains some higher-order functions.
A **higher-order function** takes one or more functions as input and returns a
new function.  The most useful tool in this module is the
:func:`functools.partial` function.

For programs written in a functional style, you'll sometimes want to construct
variants of existing functions that have some of the parameters filled in.
Consider a Python function ``f(a, b, c)``; you may wish to create a new function
``g(b, c)`` that's equivalent to ``f(1, b, c)``; you're filling in a value for
one of ``f()``'s parameters.  This is called "partial function application".

The constructor for ``partial`` takes the arguments ``(function, arg1, arg2,
... kwarg1=value1, kwarg2=value2)``.  The resulting object is callable, so you
can just call it to invoke ``function`` with the filled-in arguments.

Here's a small but realistic example::

    import functools

    def log (message, subsystem):
        "Write the contents of 'message' to the specified subsystem."
        print '%s: %s' % (subsystem, message)
        ...

    server_log = functools.partial(log, subsystem='server')
    server_log('Unable to open socket')


The operator module
-------------------

The :mod:`operator` module was mentioned earlier.  It contains a set of
functions corresponding to Python's operators.  These functions are often useful
in functional-style code because they save you from writing trivial functions
that perform a single operation.

Some of the functions in this module are:

* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``,
  ``abs()``, ...
* Logical operations: ``not_()``, ``truth()``.
* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
* Object identity: ``is_()``, ``is_not()``.

Consult the operator module's documentation for a complete list.


Revision History and Acknowledgements
=====================================

The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Ian Bicking,
Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
Lameiro, Jussi Salmela, Collin Winter, Blake Winton.

Version 0.1: posted June 30 2006.

Version 0.11: posted July 1 2006.  Typo fixes.

Version 0.2: posted July 10 2006.  Merged genexp and listcomp sections into one.
Typo fixes.

Version 0.21: Added more references suggested on the tutor mailing list.

Version 0.30: Adds a section on the ``functional`` module written by Collin
Winter; adds short section on the operator module; a few other edits.


References
==========

General
-------

**Structure and Interpretation of Computer Programs**, by Harold Abelson and
Gerald Jay Sussman with Julie Sussman.  Full text at
https://mitpress.mit.edu/sicp/.  In this classic textbook of computer science,
chapters 2 and 3 discuss the use of sequences and streams to organize the data
flow inside a program.  The book uses Scheme for its examples, but many of the
design approaches described in these chapters are applicable to functional-style
Python code.

http://www.defmacro.org/ramblings/fp.html: A general introduction to functional
programming that uses Java examples and has a lengthy historical introduction.

https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry
describing functional programming.

https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.

https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.

Python-specific
---------------

http://gnosis.cx/TPiP/: The first chapter of David Mertz's book
:title-reference:`Text Processing in Python` discusses functional programming
for text processing, in the section titled "Utilizing Higher-Order Functions in
Text Processing".

Mertz also wrote a 3-part series of articles on functional programming
for IBM's DeveloperWorks site; see

`part 1 <https://www.ibm.com/developerworks/linux/library/l-prog/index.html>`__,
`part 2 <https://www.ibm.com/developerworks/linux/library/l-prog2/index.html>`__, and
`part 3 <https://www.ibm.com/developerworks/linux/library/l-prog3/index.html>`__,


Python documentation
--------------------

Documentation for the :mod:`itertools` module.

Documentation for the :mod:`operator` module.

:pep:`289`: "Generator Expressions"

:pep:`342`: "Coroutines via Enhanced Generators" describes the new generator
features in Python 2.5.

.. comment

    Topics to place
    -----------------------------

    XXX os.walk()

    XXX Need a large example.

    But will an example add much?  I'll post a first draft and see
    what the comments say.

.. comment

    Original outline:
    Introduction
            Idea of FP
                    Programs built out of functions
                    Functions are strictly input-output, no internal state
            Opposed to OO programming, where objects have state

            Why FP?
                    Formal provability
                            Assignment is difficult to reason about
                            Not very relevant to Python
                    Modularity
                            Small functions that do one thing
                    Debuggability:
                            Easy to test due to lack of state
                            Easy to verify output from intermediate steps
                    Composability
                            You assemble a toolbox of functions that can be mixed

    Tackling a problem
            Need a significant example

    Iterators
    Generators
    The itertools module
    List comprehensions
    Small functions and the lambda statement
    Built-in functions
            map
            filter
            reduce

.. comment

    Handy little function for printing part of an iterator -- used
    while writing this document.

    import itertools
    def print_iter(it):
         slice = itertools.islice(it, 10)
         for elem in slice[:-1]:
             sys.stdout.write(str(elem))
             sys.stdout.write(', ')
        print elem[-1]


PK	%�\iO�{{!html/_sources/howto/index.rst.txtnu�[���***************
 Python HOWTOs
***************

Python HOWTOs are documents that cover a single, specific topic,
and attempt to cover it fairly completely. Modelled on the Linux
Documentation Project's HOWTO collection, this collection is an
effort to foster documentation that's more detailed than the
Python Library Reference.

Currently, the HOWTOs are:

.. toctree::
   :maxdepth: 1

   pyporting.rst
   cporting.rst
   curses.rst
   descriptor.rst
   doanddont.rst
   functional.rst
   logging.rst
   logging-cookbook.rst
   regex.rst
   sockets.rst
   sorting.rst
   unicode.rst
   urllib2.rst
   webservers.rst
   argparse.rst

PK	%�\a��`�`�,html/_sources/howto/logging-cookbook.rst.txtnu�[���.. _logging-cookbook:

================
Logging Cookbook
================

:Author: Vinay Sajip <vinay_sajip at red-dove dot com>

This page contains a number of recipes related to logging, which have been found
useful in the past.

.. currentmodule:: logging

Using logging in multiple modules
---------------------------------

Multiple calls to ``logging.getLogger('someLogger')`` return a reference to the
same logger object.  This is true not only within the same module, but also
across modules as long as it is in the same Python interpreter process.  It is
true for references to the same object; additionally, application code can
define and configure a parent logger in one module and create (but not
configure) a child logger in a separate module, and all logger calls to the
child will pass up to the parent.  Here is a main module::

    import logging
    import auxiliary_module

    # create logger with 'spam_application'
    logger = logging.getLogger('spam_application')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler('spam.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)
    # add the handlers to the logger
    logger.addHandler(fh)
    logger.addHandler(ch)

    logger.info('creating an instance of auxiliary_module.Auxiliary')
    a = auxiliary_module.Auxiliary()
    logger.info('created an instance of auxiliary_module.Auxiliary')
    logger.info('calling auxiliary_module.Auxiliary.do_something')
    a.do_something()
    logger.info('finished auxiliary_module.Auxiliary.do_something')
    logger.info('calling auxiliary_module.some_function()')
    auxiliary_module.some_function()
    logger.info('done with auxiliary_module.some_function()')

Here is the auxiliary module::

    import logging

    # create logger
    module_logger = logging.getLogger('spam_application.auxiliary')

    class Auxiliary:
        def __init__(self):
            self.logger = logging.getLogger('spam_application.auxiliary.Auxiliary')
            self.logger.info('creating an instance of Auxiliary')

        def do_something(self):
            self.logger.info('doing something')
            a = 1 + 1
            self.logger.info('done doing something')

    def some_function():
        module_logger.info('received a call to "some_function"')

The output looks like this::

    2005-03-23 23:47:11,663 - spam_application - INFO -
       creating an instance of auxiliary_module.Auxiliary
    2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
       creating an instance of Auxiliary
    2005-03-23 23:47:11,665 - spam_application - INFO -
       created an instance of auxiliary_module.Auxiliary
    2005-03-23 23:47:11,668 - spam_application - INFO -
       calling auxiliary_module.Auxiliary.do_something
    2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
       doing something
    2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
       done doing something
    2005-03-23 23:47:11,670 - spam_application - INFO -
       finished auxiliary_module.Auxiliary.do_something
    2005-03-23 23:47:11,671 - spam_application - INFO -
       calling auxiliary_module.some_function()
    2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
       received a call to 'some_function'
    2005-03-23 23:47:11,673 - spam_application - INFO -
       done with auxiliary_module.some_function()

Logging from multiple threads
-----------------------------

Logging from multiple threads requires no special effort. The following example
shows logging from the main (initIal) thread and another thread::

    import logging
    import threading
    import time

    def worker(arg):
        while not arg['stop']:
            logging.debug('Hi from myfunc')
            time.sleep(0.5)

    def main():
        logging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')
        info = {'stop': False}
        thread = threading.Thread(target=worker, args=(info,))
        thread.start()
        while True:
            try:
                logging.debug('Hello from main')
                time.sleep(0.75)
            except KeyboardInterrupt:
                info['stop'] = True
                break
        thread.join()

    if __name__ == '__main__':
        main()

When run, the script should print something like the following::

     0 Thread-1 Hi from myfunc
     3 MainThread Hello from main
   505 Thread-1 Hi from myfunc
   755 MainThread Hello from main
  1007 Thread-1 Hi from myfunc
  1507 MainThread Hello from main
  1508 Thread-1 Hi from myfunc
  2010 Thread-1 Hi from myfunc
  2258 MainThread Hello from main
  2512 Thread-1 Hi from myfunc
  3009 MainThread Hello from main
  3013 Thread-1 Hi from myfunc
  3515 Thread-1 Hi from myfunc
  3761 MainThread Hello from main
  4017 Thread-1 Hi from myfunc
  4513 MainThread Hello from main
  4518 Thread-1 Hi from myfunc

This shows the logging output interspersed as one might expect. This approach
works for more threads than shown here, of course.

Multiple handlers and formatters
--------------------------------

Loggers are plain Python objects.  The :meth:`~Logger.addHandler` method has no
minimum or maximum quota for the number of handlers you may add.  Sometimes it
will be beneficial for an application to log all messages of all severities to a
text file while simultaneously logging errors or above to the console.  To set
this up, simply configure the appropriate handlers.  The logging calls in the
application code will remain unchanged.  Here is a slight modification to the
previous simple module-based configuration example::

    import logging

    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler('spam.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.ERROR)
    # create formatter and add it to the handlers
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    # add the handlers to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')

Notice that the 'application' code does not care about multiple handlers.  All
that changed was the addition and configuration of a new handler named *fh*.

The ability to create new handlers with higher- or lower-severity filters can be
very helpful when writing and testing an application.  Instead of using many
``print`` statements for debugging, use ``logger.debug``: Unlike the print
statements, which you will have to delete or comment out later, the logger.debug
statements can remain intact in the source code and remain dormant until you
need them again.  At that time, the only change that needs to happen is to
modify the severity level of the logger and/or handler to debug.

.. _multiple-destinations:

Logging to multiple destinations
--------------------------------

Let's say you want to log to console and file with different message formats and
in differing circumstances. Say you want to log messages with levels of DEBUG
and higher to file, and those messages at level INFO and higher to the console.
Let's also assume that the file should contain timestamps, but the console
messages should not. Here's how you can achieve this::

   import logging

   # set up logging to file - see previous section for more details
   logging.basicConfig(level=logging.DEBUG,
                       format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                       datefmt='%m-%d %H:%M',
                       filename='/temp/myapp.log',
                       filemode='w')
   # define a Handler which writes INFO messages or higher to the sys.stderr
   console = logging.StreamHandler()
   console.setLevel(logging.INFO)
   # set a format which is simpler for console use
   formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
   # tell the handler to use this format
   console.setFormatter(formatter)
   # add the handler to the root logger
   logging.getLogger('').addHandler(console)

   # Now, we can log to the root logger, or any other logger. First the root...
   logging.info('Jackdaws love my big sphinx of quartz.')

   # Now, define a couple of other loggers which might represent areas in your
   # application:

   logger1 = logging.getLogger('myapp.area1')
   logger2 = logging.getLogger('myapp.area2')

   logger1.debug('Quick zephyrs blow, vexing daft Jim.')
   logger1.info('How quickly daft jumping zebras vex.')
   logger2.warning('Jail zesty vixen who grabbed pay from quack.')
   logger2.error('The five boxing wizards jump quickly.')

When you run this, on the console you will see ::

   root        : INFO     Jackdaws love my big sphinx of quartz.
   myapp.area1 : INFO     How quickly daft jumping zebras vex.
   myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
   myapp.area2 : ERROR    The five boxing wizards jump quickly.

and in the file you will see something like ::

   10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
   10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
   10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
   10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
   10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.

As you can see, the DEBUG message only shows up in the file. The other messages
are sent to both destinations.

This example uses console and file handlers, but you can use any number and
combination of handlers you choose.


Configuration server example
----------------------------

Here is an example of a module using the logging configuration server::

    import logging
    import logging.config
    import time
    import os

    # read initial config file
    logging.config.fileConfig('logging.conf')

    # create and start listener on port 9999
    t = logging.config.listen(9999)
    t.start()

    logger = logging.getLogger('simpleExample')

    try:
        # loop through logging calls to see the difference
        # new configurations make, until Ctrl+C is pressed
        while True:
            logger.debug('debug message')
            logger.info('info message')
            logger.warn('warn message')
            logger.error('error message')
            logger.critical('critical message')
            time.sleep(5)
    except KeyboardInterrupt:
        # cleanup
        logging.config.stopListening()
        t.join()

And here is a script that takes a filename and sends that file to the server,
properly preceded with the binary-encoded length, as the new logging
configuration::

    #!/usr/bin/env python
    import socket, sys, struct

    with open(sys.argv[1], 'rb') as f:
        data_to_send = f.read()

    HOST = 'localhost'
    PORT = 9999
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('connecting...')
    s.connect((HOST, PORT))
    print('sending config...')
    s.send(struct.pack('>L', len(data_to_send)))
    s.send(data_to_send)
    s.close()
    print('complete')


.. _network-logging:

Sending and receiving logging events across a network
-----------------------------------------------------

Let's say you want to send logging events across a network, and handle them at
the receiving end. A simple way of doing this is attaching a
:class:`SocketHandler` instance to the root logger at the sending end::

   import logging, logging.handlers

   rootLogger = logging.getLogger('')
   rootLogger.setLevel(logging.DEBUG)
   socketHandler = logging.handlers.SocketHandler('localhost',
                       logging.handlers.DEFAULT_TCP_LOGGING_PORT)
   # don't bother with a formatter, since a socket handler sends the event as
   # an unformatted pickle
   rootLogger.addHandler(socketHandler)

   # Now, we can log to the root logger, or any other logger. First the root...
   logging.info('Jackdaws love my big sphinx of quartz.')

   # Now, define a couple of other loggers which might represent areas in your
   # application:

   logger1 = logging.getLogger('myapp.area1')
   logger2 = logging.getLogger('myapp.area2')

   logger1.debug('Quick zephyrs blow, vexing daft Jim.')
   logger1.info('How quickly daft jumping zebras vex.')
   logger2.warning('Jail zesty vixen who grabbed pay from quack.')
   logger2.error('The five boxing wizards jump quickly.')

At the receiving end, you can set up a receiver using the :mod:`SocketServer`
module. Here is a basic working example::

   import pickle
   import logging
   import logging.handlers
   import SocketServer
   import struct


   class LogRecordStreamHandler(SocketServer.StreamRequestHandler):
       """Handler for a streaming logging request.

       This basically logs the record using whatever logging policy is
       configured locally.
       """

       def handle(self):
           """
           Handle multiple requests - each expected to be a 4-byte length,
           followed by the LogRecord in pickle format. Logs the record
           according to whatever policy is configured locally.
           """
           while True:
               chunk = self.connection.recv(4)
               if len(chunk) < 4:
                   break
               slen = struct.unpack('>L', chunk)[0]
               chunk = self.connection.recv(slen)
               while len(chunk) < slen:
                   chunk = chunk + self.connection.recv(slen - len(chunk))
               obj = self.unPickle(chunk)
               record = logging.makeLogRecord(obj)
               self.handleLogRecord(record)

       def unPickle(self, data):
           return pickle.loads(data)

       def handleLogRecord(self, record):
           # if a name is specified, we use the named logger rather than the one
           # implied by the record.
           if self.server.logname is not None:
               name = self.server.logname
           else:
               name = record.name
           logger = logging.getLogger(name)
           # N.B. EVERY record gets logged. This is because Logger.handle
           # is normally called AFTER logger-level filtering. If you want
           # to do filtering, do it at the client end to save wasting
           # cycles and network bandwidth!
           logger.handle(record)

   class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer):
       """
       Simple TCP socket-based logging receiver suitable for testing.
       """

       allow_reuse_address = 1

       def __init__(self, host='localhost',
                    port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                    handler=LogRecordStreamHandler):
           SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
           self.abort = 0
           self.timeout = 1
           self.logname = None

       def serve_until_stopped(self):
           import select
           abort = 0
           while not abort:
               rd, wr, ex = select.select([self.socket.fileno()],
                                          [], [],
                                          self.timeout)
               if rd:
                   self.handle_request()
               abort = self.abort

   def main():
       logging.basicConfig(
           format='%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s')
       tcpserver = LogRecordSocketReceiver()
       print('About to start TCP server...')
       tcpserver.serve_until_stopped()

   if __name__ == '__main__':
       main()

First run the server, and then the client. On the client side, nothing is
printed on the console; on the server side, you should see something like::

   About to start TCP server...
      59 root            INFO     Jackdaws love my big sphinx of quartz.
      59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
      69 myapp.area1     INFO     How quickly daft jumping zebras vex.
      69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
      69 myapp.area2     ERROR    The five boxing wizards jump quickly.

Note that there are some security issues with pickle in some scenarios. If
these affect you, you can use an alternative serialization scheme by overriding
the :meth:`~handlers.SocketHandler.makePickle` method and implementing your
alternative there, as well as adapting the above script to use your alternative
serialization.


.. _context-info:

Adding contextual information to your logging output
----------------------------------------------------

.. currentmodule:: logging

Sometimes you want logging output to contain contextual information in
addition to the parameters passed to the logging call. For example, in a
networked application, it may be desirable to log client-specific information
in the log (e.g. remote client's username, or IP address). Although you could
use the *extra* parameter to achieve this, it's not always convenient to pass
the information in this way. While it might be tempting to create
:class:`Logger` instances on a per-connection basis, this is not a good idea
because these instances are not garbage collected. While this is not a problem
in practice, when the number of :class:`Logger` instances is dependent on the
level of granularity you want to use in logging an application, it could
be hard to manage if the number of :class:`Logger` instances becomes
effectively unbounded.


Using LoggerAdapters to impart contextual information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

An easy way in which you can pass contextual information to be output along
with logging event information is to use the :class:`LoggerAdapter` class.
This class is designed to look like a :class:`Logger`, so that you can call
:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
same signatures as their counterparts in :class:`Logger`, so you can use the
two types of instances interchangeably.

When you create an instance of :class:`LoggerAdapter`, you pass it a
:class:`Logger` instance and a dict-like object which contains your contextual
information. When you call one of the logging methods on an instance of
:class:`LoggerAdapter`, it delegates the call to the underlying instance of
:class:`Logger` passed to its constructor, and arranges to pass the contextual
information in the delegated call. Here's a snippet from the code of
:class:`LoggerAdapter`::

    def debug(self, msg, *args, **kwargs):
        """
        Delegate a debug call to the underlying logger, after adding
        contextual information from this adapter instance.
        """
        msg, kwargs = self.process(msg, kwargs)
        self.logger.debug(msg, *args, **kwargs)

The :meth:`~LoggerAdapter.process` method of :class:`LoggerAdapter` is where the
contextual information is added to the logging output. It's passed the message
and keyword arguments of the logging call, and it passes back (potentially)
modified versions of these to use in the call to the underlying logger. The
default implementation of this method leaves the message alone, but inserts
an 'extra' key in the keyword argument whose value is the dict-like object
passed to the constructor. Of course, if you had passed an 'extra' keyword
argument in the call to the adapter, it will be silently overwritten.

The advantage of using 'extra' is that the values in the dict-like object are
merged into the :class:`LogRecord` instance's __dict__, allowing you to use
customized strings with your :class:`Formatter` instances which know about
the keys of the dict-like object. If you need a different method, e.g. if you
want to prepend or append the contextual information to the message string,
you just need to subclass :class:`LoggerAdapter` and override
:meth:`~LoggerAdapter.process` to do what you need. Here is a simple example::

    class CustomAdapter(logging.LoggerAdapter):
        """
        This example adapter expects the passed in dict-like object to have a
        'connid' key, whose value in brackets is prepended to the log message.
        """
        def process(self, msg, kwargs):
            return '[%s] %s' % (self.extra['connid'], msg), kwargs

which you can use like this::

    logger = logging.getLogger(__name__)
    adapter = CustomAdapter(logger, {'connid': some_conn_id})

Then any events that you log to the adapter will have the value of
``some_conn_id`` prepended to the log messages.

Using objects other than dicts to pass contextual information
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

You don't need to pass an actual dict to a :class:`LoggerAdapter` - you could
pass an instance of a class which implements ``__getitem__`` and ``__iter__`` so
that it looks like a dict to logging. This would be useful if you want to
generate values dynamically (whereas the values in a dict would be constant).


.. _filters-contextual:

Using Filters to impart contextual information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can also add contextual information to log output using a user-defined
:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
passed to them, including adding additional attributes which can then be output
using a suitable format string, or if needed a custom :class:`Formatter`.

For example in a web application, the request being processed (or at least,
the interesting parts of it) can be stored in a threadlocal
(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
add, say, information from the request - say, the remote IP address and remote
user's username - to the ``LogRecord``, using the attribute names 'ip' and
'user' as in the ``LoggerAdapter`` example above. In that case, the same format
string can be used to get similar output to that shown above. Here's an example
script::

    import logging
    from random import choice

    class ContextFilter(logging.Filter):
        """
        This is a filter which injects contextual information into the log.

        Rather than use actual contextual information, we just use random
        data in this demo.
        """

        USERS = ['jim', 'fred', 'sheila']
        IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']

        def filter(self, record):

            record.ip = choice(ContextFilter.IPS)
            record.user = choice(ContextFilter.USERS)
            return True

    if __name__ == '__main__':
        levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s')
        a1 = logging.getLogger('a.b.c')
        a2 = logging.getLogger('d.e.f')

        f = ContextFilter()
        a1.addFilter(f)
        a2.addFilter(f)
        a1.debug('A debug message')
        a1.info('An info message with %s', 'some parameters')
        for x in range(10):
            lvl = choice(levels)
            lvlname = logging.getLevelName(lvl)
            a2.log(lvl, 'A message at %s level with %d %s', lvlname, 2, 'parameters')

which, when run, produces something like::

    2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
    2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
    2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
    2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
    2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
    2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters


.. _multiple-processes:

Logging to a single file from multiple processes
------------------------------------------------

Although logging is thread-safe, and logging to a single file from multiple
threads in a single process *is* supported, logging to a single file from
*multiple processes* is *not* supported, because there is no standard way to
serialize access to a single file across multiple processes in Python. If you
need to log to a single file from multiple processes, one way of doing this is
to have all the processes log to a :class:`~handlers.SocketHandler`, and have a
separate process which implements a socket server which reads from the socket
and logs to file. (If you prefer, you can dedicate one thread in one of the
existing processes to perform this function.)
:ref:`This section <network-logging>` documents this approach in more detail and
includes a working socket receiver which can be used as a starting point for you
to adapt in your own applications.

If you are using a recent version of Python which includes the
:mod:`multiprocessing` module, you could write your own handler which uses the
:class:`~multiprocessing.Lock` class from this module to serialize access to the
file from your processes. The existing :class:`FileHandler` and subclasses do
not make use of :mod:`multiprocessing` at present, though they may do so in the
future. Note that at present, the :mod:`multiprocessing` module does not provide
working lock functionality on all platforms (see
https://bugs.python.org/issue3770).


Using file rotation
-------------------

.. sectionauthor:: Doug Hellmann, Vinay Sajip (changes)
.. (see <https://pymotw.com/3/logging/>)

Sometimes you want to let a log file grow to a certain size, then open a new
file and log to that. You may want to keep a certain number of these files, and
when that many files have been created, rotate the files so that the number of
files and the size of the files both remain bounded. For this usage pattern, the
logging package provides a :class:`~handlers.RotatingFileHandler`::

   import glob
   import logging
   import logging.handlers

   LOG_FILENAME = 'logging_rotatingfile_example.out'

   # Set up a specific logger with our desired output level
   my_logger = logging.getLogger('MyLogger')
   my_logger.setLevel(logging.DEBUG)

   # Add the log message handler to the logger
   handler = logging.handlers.RotatingFileHandler(
                 LOG_FILENAME, maxBytes=20, backupCount=5)

   my_logger.addHandler(handler)

   # Log some messages
   for i in range(20):
       my_logger.debug('i = %d' % i)

   # See what files are created
   logfiles = glob.glob('%s*' % LOG_FILENAME)

   for filename in logfiles:
       print(filename)

The result should be 6 separate files, each with part of the log history for the
application::

   logging_rotatingfile_example.out
   logging_rotatingfile_example.out.1
   logging_rotatingfile_example.out.2
   logging_rotatingfile_example.out.3
   logging_rotatingfile_example.out.4
   logging_rotatingfile_example.out.5

The most current file is always :file:`logging_rotatingfile_example.out`,
and each time it reaches the size limit it is renamed with the suffix
``.1``. Each of the existing backup files is renamed to increment the suffix
(``.1`` becomes ``.2``, etc.)  and the ``.6`` file is erased.

Obviously this example sets the log length much too small as an extreme
example.  You would want to set *maxBytes* to an appropriate value.

An example dictionary-based configuration
-----------------------------------------

Below is an example of a logging configuration dictionary - it's taken from
the `documentation on the Django project <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_.
This dictionary is passed to :func:`~config.dictConfig` to put the configuration into effect::

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': True,
        'formatters': {
            'verbose': {
                'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
            },
            'simple': {
                'format': '%(levelname)s %(message)s'
            },
        },
        'filters': {
            'special': {
                '()': 'project.logging.SpecialFilter',
                'foo': 'bar',
            }
        },
        'handlers': {
            'null': {
                'level':'DEBUG',
                'class':'django.utils.log.NullHandler',
            },
            'console':{
                'level':'DEBUG',
                'class':'logging.StreamHandler',
                'formatter': 'simple'
            },
            'mail_admins': {
                'level': 'ERROR',
                'class': 'django.utils.log.AdminEmailHandler',
                'filters': ['special']
            }
        },
        'loggers': {
            'django': {
                'handlers':['null'],
                'propagate': True,
                'level':'INFO',
            },
            'django.request': {
                'handlers': ['mail_admins'],
                'level': 'ERROR',
                'propagate': False,
            },
            'myproject.custom': {
                'handlers': ['console', 'mail_admins'],
                'level': 'INFO',
                'filters': ['special']
            }
        }
    }

For more information about this configuration, you can see the `relevant
section <https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging>`_
of the Django documentation.

Inserting a BOM into messages sent to a SysLogHandler
-----------------------------------------------------

`RFC 5424 <https://tools.ietf.org/html/rfc5424>`_ requires that a
Unicode message be sent to a syslog daemon as a set of bytes which have the
following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the `relevant
section of the specification <https://tools.ietf.org/html/rfc5424#section-6>`_.)

In Python 2.6 and 2.7, code was added to
:class:`~logging.handlers.SysLogHandler` to insert a BOM into the message, but
unfortunately, it was implemented incorrectly, with the BOM appearing at the
beginning of the message and hence not allowing any pure-ASCII component to
appear before it.

As this behaviour is broken, the incorrect BOM insertion code is being removed
from Python 2.7.4 and later. However, it is not being replaced, and if you
want to produce RFC 5424-compliant messages which include a BOM, an optional
pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
UTF-8, then you need to do the following:

#. Attach a :class:`~logging.Formatter` instance to your
   :class:`~logging.handlers.SysLogHandler` instance, with a format string
   such as::

      u'ASCII section\ufeffUnicode section'

   The Unicode code point ``u'\ufeff'``, when encoded using UTF-8, will be
   encoded as a UTF-8 BOM -- the byte-string ``'\xef\xbb\xbf'``.

#. Replace the ASCII section with whatever placeholders you like, but make sure
   that the data that appears in there after substitution is always ASCII (that
   way, it will remain unchanged after UTF-8 encoding).

#. Replace the Unicode section with whatever placeholders you like; if the data
   which appears there after substitution contains characters outside the ASCII
   range, that's fine -- it will be encoded using UTF-8.

If the formatted message is Unicode, it *will* be encoded using UTF-8 encoding
by ``SysLogHandler``. If you follow the above rules, you should be able to
produce RFC 5424-compliant messages. If you don't, logging may not complain,
but your messages will not be RFC 5424-compliant, and your syslog daemon may
complain.


Implementing structured logging
-------------------------------

Although most logging messages are intended for reading by humans, and thus not
readily machine-parseable, there might be circumstances where you want to output
messages in a structured format which *is* capable of being parsed by a program
(without needing complex regular expressions to parse the log message). This is
straightforward to achieve using the logging package. There are a number of
ways in which this could be achieved, but the following is a simple approach
which uses JSON to serialise the event in a machine-parseable manner::

    import json
    import logging

    class StructuredMessage(object):
        def __init__(self, message, **kwargs):
            self.message = message
            self.kwargs = kwargs

        def __str__(self):
            return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

    _ = StructuredMessage   # optional, to improve readability

    logging.basicConfig(level=logging.INFO, format='%(message)s')
    logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))

If the above script is run, it prints::

    message 1 >>> {"fnum": 123.456, "num": 123, "bar": "baz", "foo": "bar"}

Note that the order of items might be different according to the version of
Python used.

If you need more specialised processing, you can use a custom JSON encoder,
as in the following complete example::

    from __future__ import unicode_literals

    import json
    import logging

    # This next bit is to ensure the script runs unchanged on 2.x and 3.x
    try:
        unicode
    except NameError:
        unicode = str

    class Encoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, set):
                return tuple(o)
            elif isinstance(o, unicode):
                return o.encode('unicode_escape').decode('ascii')
            return super(Encoder, self).default(o)

    class StructuredMessage(object):
        def __init__(self, message, **kwargs):
            self.message = message
            self.kwargs = kwargs

        def __str__(self):
            s = Encoder().encode(self.kwargs)
            return '%s >>> %s' % (self.message, s)

    _ = StructuredMessage   # optional, to improve readability

    def main():
        logging.basicConfig(level=logging.INFO, format='%(message)s')
        logging.info(_('message 1', set_value=set([1, 2, 3]), snowman='\u2603'))

    if __name__ == '__main__':
        main()

When the above script is run, it prints::

    message 1 >>> {"snowman": "\u2603", "set_value": [1, 2, 3]}

Note that the order of items might be different according to the version of
Python used.


.. _custom-handlers:

.. currentmodule:: logging.config

Customizing handlers with :func:`dictConfig`
--------------------------------------------

There are times when you want to customize logging handlers in particular ways,
and if you use :func:`dictConfig` you may be able to do this without
subclassing. As an example, consider that you may want to set the ownership of a
log file. On POSIX, this is easily done using :func:`os.chown`, but the file
handlers in the stdlib don't offer built-in support. You can customize handler
creation using a plain function such as::

    def owned_file_handler(filename, mode='a', encoding=None, owner=None):
        if owner:
            import os, pwd, grp
            # convert user and group names to uid and gid
            uid = pwd.getpwnam(owner[0]).pw_uid
            gid = grp.getgrnam(owner[1]).gr_gid
            owner = (uid, gid)
            if not os.path.exists(filename):
                open(filename, 'a').close()
            os.chown(filename, *owner)
        return logging.FileHandler(filename, mode, encoding)

You can then specify, in a logging configuration passed to :func:`dictConfig`,
that a logging handler be created by calling this function::

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
            },
        },
        'handlers': {
            'file':{
                # The values below are popped from this dictionary and
                # used to create the handler, set the handler's level and
                # its formatter.
                '()': owned_file_handler,
                'level':'DEBUG',
                'formatter': 'default',
                # The values below are passed to the handler creator callable
                # as keyword arguments.
                'owner': ['pulse', 'pulse'],
                'filename': 'chowntest.log',
                'mode': 'w',
                'encoding': 'utf-8',
            },
        },
        'root': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }

In this example I am setting the ownership using the ``pulse`` user and group,
just for the purposes of illustration. Putting it together into a working
script, ``chowntest.py``::

    import logging, logging.config, os, shutil

    def owned_file_handler(filename, mode='a', encoding=None, owner=None):
        if owner:
            if not os.path.exists(filename):
                open(filename, 'a').close()
            shutil.chown(filename, *owner)
        return logging.FileHandler(filename, mode, encoding)

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'default': {
                'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
            },
        },
        'handlers': {
            'file':{
                # The values below are popped from this dictionary and
                # used to create the handler, set the handler's level and
                # its formatter.
                '()': owned_file_handler,
                'level':'DEBUG',
                'formatter': 'default',
                # The values below are passed to the handler creator callable
                # as keyword arguments.
                'owner': ['pulse', 'pulse'],
                'filename': 'chowntest.log',
                'mode': 'w',
                'encoding': 'utf-8',
            },
        },
        'root': {
            'handlers': ['file'],
            'level': 'DEBUG',
        },
    }

    logging.config.dictConfig(LOGGING)
    logger = logging.getLogger('mylogger')
    logger.debug('A debug message')

To run this, you will probably need to run as ``root``:

.. code-block:: shell-session

    $ sudo python3.3 chowntest.py
    $ cat chowntest.log
    2013-11-05 09:34:51,128 DEBUG mylogger A debug message
    $ ls -l chowntest.log
    -rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log

Note that this example uses Python 3.3 because that's where :func:`shutil.chown`
makes an appearance. This approach should work with any Python version that
supports :func:`dictConfig` - namely, Python 2.7, 3.2 or later. With pre-3.3
versions, you would need to implement the actual ownership change using e.g.
:func:`os.chown`.

In practice, the handler-creating function may be in a utility module somewhere
in your project. Instead of the line in the configuration::

    '()': owned_file_handler,

you could use e.g.::

    '()': 'ext://project.util.owned_file_handler',

where ``project.util`` can be replaced with the actual name of the package
where the function resides. In the above working script, using
``'ext://__main__.owned_file_handler'`` should work. Here, the actual callable
is resolved by :func:`dictConfig` from the ``ext://`` specification.

This example hopefully also points the way to how you could implement other
types of file change - e.g. setting specific POSIX permission bits - in the
same way, using :func:`os.chmod`.

Of course, the approach could also be extended to types of handler other than a
:class:`~logging.FileHandler` - for example, one of the rotating file handlers,
or a different type of handler altogether.


.. _filters-dictconfig:

Configuring filters with :func:`dictConfig`
-------------------------------------------

You *can* configure filters using :func:`~logging.config.dictConfig`, though it
might not be obvious at first glance how to do it (hence this recipe). Since
:class:`~logging.Filter` is the only filter class included in the standard
library, and it is unlikely to cater to many requirements (it's only there as a
base class), you will typically need to define your own :class:`~logging.Filter`
subclass with an overridden :meth:`~logging.Filter.filter` method. To do this,
specify the ``()`` key in the configuration dictionary for the filter,
specifying a callable which will be used to create the filter (a class is the
most obvious, but you can provide any callable which returns a
:class:`~logging.Filter` instance). Here is a complete example::

    import logging
    import logging.config
    import sys

    class MyFilter(logging.Filter):
        def __init__(self, param=None):
            self.param = param

        def filter(self, record):
            if self.param is None:
                allow = True
            else:
                allow = self.param not in record.msg
            if allow:
                record.msg = 'changed: ' + record.msg
            return allow

    LOGGING = {
        'version': 1,
        'filters': {
            'myfilter': {
                '()': MyFilter,
                'param': 'noshow',
            }
        },
        'handlers': {
            'console': {
                'class': 'logging.StreamHandler',
                'filters': ['myfilter']
            }
        },
        'root': {
            'level': 'DEBUG',
            'handlers': ['console']
        },
    }

    if __name__ == '__main__':
        logging.config.dictConfig(LOGGING)
        logging.debug('hello')
        logging.debug('hello - noshow')

This example shows how you can pass configuration data to the callable which
constructs the instance, in the form of keyword parameters. When run, the above
script will print::

    changed: hello

which shows that the filter is working as configured.

A couple of extra points to note:

* If you can't refer to the callable directly in the configuration (e.g. if it
  lives in a different module, and you can't import it directly where the
  configuration dictionary is), you can use the form ``ext://...`` as described
  in :ref:`logging-config-dict-externalobj`. For example, you could have used
  the text ``'ext://__main__.MyFilter'`` instead of ``MyFilter`` in the above
  example.

* As well as for filters, this technique can also be used to configure custom
  handlers and formatters. See :ref:`logging-config-dict-userdef` for more
  information on how logging supports using user-defined objects in its
  configuration, and see the other cookbook recipe :ref:`custom-handlers` above.


.. _custom-format-exception:

Customized exception formatting
-------------------------------

There might be times when you want to do customized exception formatting - for
argument's sake, let's say you want exactly one line per logged event, even
when exception information is present. You can do this with a custom formatter
class, as shown in the following example::

    import logging

    class OneLineExceptionFormatter(logging.Formatter):
        def formatException(self, exc_info):
            """
            Format an exception so that it prints on a single line.
            """
            result = super(OneLineExceptionFormatter, self).formatException(exc_info)
            return repr(result) # or format into one line however you want to

        def format(self, record):
            s = super(OneLineExceptionFormatter, self).format(record)
            if record.exc_text:
                s = s.replace('\n', '') + '|'
            return s

    def configure_logging():
        fh = logging.FileHandler('output.txt', 'w')
        f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|',
                                      '%d/%m/%Y %H:%M:%S')
        fh.setFormatter(f)
        root = logging.getLogger()
        root.setLevel(logging.DEBUG)
        root.addHandler(fh)

    def main():
        configure_logging()
        logging.info('Sample message')
        try:
            x = 1 / 0
        except ZeroDivisionError as e:
            logging.exception('ZeroDivisionError: %s', e)

    if __name__ == '__main__':
        main()

When run, this produces a file with exactly two lines::

    28/01/2015 07:21:23|INFO|Sample message|
    28/01/2015 07:21:23|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest7.py", line 30, in main\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|

While the above treatment is simplistic, it points the way to how exception
information can be formatted to your liking. The :mod:`traceback` module may be
helpful for more specialized needs.

.. _spoken-messages:

Speaking logging messages
-------------------------

There might be situations when it is desirable to have logging messages rendered
in an audible rather than a visible format. This is easy to do if you have
text-to-speech (TTS) functionality available in your system, even if it doesn't have
a Python binding. Most TTS systems have a command line program you can run, and
this can be invoked from a handler using :mod:`subprocess`. It's assumed here
that TTS command line programs won't expect to interact with users or take a
long time to complete, and that the frequency of logged messages will be not so
high as to swamp the user with messages, and that it's acceptable to have the
messages spoken one at a time rather than concurrently, The example implementation
below waits for one message to be spoken before the next is processed, and this
might cause other handlers to be kept waiting. Here is a short example showing
the approach, which assumes that the ``espeak`` TTS package is available::

    import logging
    import subprocess
    import sys

    class TTSHandler(logging.Handler):
        def emit(self, record):
            msg = self.format(record)
            # Speak slowly in a female English voice
            cmd = ['espeak', '-s150', '-ven+f3', msg]
            p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
            # wait for the program to finish
            p.communicate()

    def configure_logging():
        h = TTSHandler()
        root = logging.getLogger()
        root.addHandler(h)
        # the default formatter just returns the message
        root.setLevel(logging.DEBUG)

    def main():
        logging.info('Hello')
        logging.debug('Goodbye')

    if __name__ == '__main__':
        configure_logging()
        sys.exit(main())

When run, this script should say "Hello" and then "Goodbye" in a female voice.

The above approach can, of course, be adapted to other TTS systems and even
other systems altogether which can process messages via external programs run
from a command line.

.. _buffered-logging:

Buffering logging messages and outputting them conditionally
------------------------------------------------------------

There might be situations where you want to log messages in a temporary area
and only output them if a certain condition occurs. For example, you may want to
start logging debug events in a function, and if the function completes without
errors, you don't want to clutter the log with the collected debug information,
but if there is an error, you want all the debug information to be output as well
as the error.

Here is an example which shows how you could do this using a decorator for your
functions where you want logging to behave this way. It makes use of the
:class:`logging.handlers.MemoryHandler`, which allows buffering of logged events
until some condition occurs, at which point the buffered events are ``flushed``
- passed to another handler (the ``target`` handler) for processing. By default,
the ``MemoryHandler`` flushed when its buffer gets filled up or an event whose
level is greater than or equal to a specified threshold is seen. You can use this
recipe with a more specialised subclass of ``MemoryHandler`` if you want custom
flushing behavior.

The example script has a simple function, ``foo``, which just cycles through
all the logging levels, writing to ``sys.stderr`` to say what level it's about
to log at, and then actually logging a message at that level. You can pass a
parameter to ``foo`` which, if true, will log at ERROR and CRITICAL levels -
otherwise, it only logs at DEBUG, INFO and WARNING levels.

The script just arranges to decorate ``foo`` with a decorator which will do the
conditional logging that's required. The decorator takes a logger as a parameter
and attaches a memory handler for the duration of the call to the decorated
function. The decorator can be additionally parameterised using a target handler,
a level at which flushing should occur, and a capacity for the buffer. These
default to a :class:`~logging.StreamHandler` which writes to ``sys.stderr``,
``logging.ERROR`` and ``100`` respectively.

Here's the script::

    import logging
    from logging.handlers import MemoryHandler
    import sys

    logger = logging.getLogger(__name__)
    logger.addHandler(logging.NullHandler())

    def log_if_errors(logger, target_handler=None, flush_level=None, capacity=None):
        if target_handler is None:
            target_handler = logging.StreamHandler()
        if flush_level is None:
            flush_level = logging.ERROR
        if capacity is None:
            capacity = 100
        handler = MemoryHandler(capacity, flushLevel=flush_level, target=target_handler)

        def decorator(fn):
            def wrapper(*args, **kwargs):
                logger.addHandler(handler)
                try:
                    return fn(*args, **kwargs)
                except Exception:
                    logger.exception('call failed')
                    raise
                finally:
                    super(MemoryHandler, handler).flush()
                    logger.removeHandler(handler)
            return wrapper

        return decorator

    def write_line(s):
        sys.stderr.write('%s\n' % s)

    def foo(fail=False):
        write_line('about to log at DEBUG ...')
        logger.debug('Actually logged at DEBUG')
        write_line('about to log at INFO ...')
        logger.info('Actually logged at INFO')
        write_line('about to log at WARNING ...')
        logger.warning('Actually logged at WARNING')
        if fail:
            write_line('about to log at ERROR ...')
            logger.error('Actually logged at ERROR')
            write_line('about to log at CRITICAL ...')
            logger.critical('Actually logged at CRITICAL')
        return fail

    decorated_foo = log_if_errors(logger)(foo)

    if __name__ == '__main__':
        logger.setLevel(logging.DEBUG)
        write_line('Calling undecorated foo with False')
        assert not foo(False)
        write_line('Calling undecorated foo with True')
        assert foo(True)
        write_line('Calling decorated foo with False')
        assert not decorated_foo(False)
        write_line('Calling decorated foo with True')
        assert decorated_foo(True)

When this script is run, the following output should be observed::

    Calling undecorated foo with False
    about to log at DEBUG ...
    about to log at INFO ...
    about to log at WARNING ...
    Calling undecorated foo with True
    about to log at DEBUG ...
    about to log at INFO ...
    about to log at WARNING ...
    about to log at ERROR ...
    about to log at CRITICAL ...
    Calling decorated foo with False
    about to log at DEBUG ...
    about to log at INFO ...
    about to log at WARNING ...
    Calling decorated foo with True
    about to log at DEBUG ...
    about to log at INFO ...
    about to log at WARNING ...
    about to log at ERROR ...
    Actually logged at DEBUG
    Actually logged at INFO
    Actually logged at WARNING
    Actually logged at ERROR
    about to log at CRITICAL ...
    Actually logged at CRITICAL

As you can see, actual logging output only occurs when an event is logged whose
severity is ERROR or greater, but in that case, any previous events at lower
severities are also logged.

You can of course use the conventional means of decoration::

    @log_if_errors(logger)
    def foo(fail=False):
        ...


.. _utc-formatting:

Formatting times using UTC (GMT) via configuration
--------------------------------------------------

Sometimes you want to format times using UTC, which can be done using a class
such as `UTCFormatter`, shown below::

    import logging
    import time

    class UTCFormatter(logging.Formatter):
        converter = time.gmtime

and you can then use the ``UTCFormatter`` in your code instead of
:class:`~logging.Formatter`. If you want to do that via configuration, you can
use the :func:`~logging.config.dictConfig` API with an approach illustrated by
the following complete example::

    import logging
    import logging.config
    import time

    class UTCFormatter(logging.Formatter):
        converter = time.gmtime

    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'formatters': {
            'utc': {
                '()': UTCFormatter,
                'format': '%(asctime)s %(message)s',
            },
            'local': {
                'format': '%(asctime)s %(message)s',
            }
        },
        'handlers': {
            'console1': {
                'class': 'logging.StreamHandler',
                'formatter': 'utc',
            },
            'console2': {
                'class': 'logging.StreamHandler',
                'formatter': 'local',
            },
        },
        'root': {
            'handlers': ['console1', 'console2'],
       }
    }

    if __name__ == '__main__':
        logging.config.dictConfig(LOGGING)
        logging.warning('The local time is %s', time.asctime())

When this script is run, it should print something like::

    2015-10-17 12:53:29,501 The local time is Sat Oct 17 13:53:29 2015
    2015-10-17 13:53:29,501 The local time is Sat Oct 17 13:53:29 2015

showing how the time is formatted both as local time and UTC, one for each
handler.


.. _context-manager:

Using a context manager for selective logging
---------------------------------------------

There are times when it would be useful to temporarily change the logging
configuration and revert it back after doing something. For this, a context
manager is the most obvious way of saving and restoring the logging context.
Here is a simple example of such a context manager, which allows you to
optionally change the logging level and add a logging handler purely in the
scope of the context manager::

    import logging
    import sys

    class LoggingContext(object):
        def __init__(self, logger, level=None, handler=None, close=True):
            self.logger = logger
            self.level = level
            self.handler = handler
            self.close = close

        def __enter__(self):
            if self.level is not None:
                self.old_level = self.logger.level
                self.logger.setLevel(self.level)
            if self.handler:
                self.logger.addHandler(self.handler)

        def __exit__(self, et, ev, tb):
            if self.level is not None:
                self.logger.setLevel(self.old_level)
            if self.handler:
                self.logger.removeHandler(self.handler)
            if self.handler and self.close:
                self.handler.close()
            # implicit return of None => don't swallow exceptions

If you specify a level value, the logger's level is set to that value in the
scope of the with block covered by the context manager. If you specify a
handler, it is added to the logger on entry to the block and removed on exit
from the block. You can also ask the manager to close the handler for you on
block exit - you could do this if you don't need the handler any more.

To illustrate how it works, we can add the following block of code to the
above::

    if __name__ == '__main__':
        logger = logging.getLogger('foo')
        logger.addHandler(logging.StreamHandler())
        logger.setLevel(logging.INFO)
        logger.info('1. This should appear just once on stderr.')
        logger.debug('2. This should not appear.')
        with LoggingContext(logger, level=logging.DEBUG):
            logger.debug('3. This should appear once on stderr.')
        logger.debug('4. This should not appear.')
        h = logging.StreamHandler(sys.stdout)
        with LoggingContext(logger, level=logging.DEBUG, handler=h, close=True):
            logger.debug('5. This should appear twice - once on stderr and once on stdout.')
        logger.info('6. This should appear just once on stderr.')
        logger.debug('7. This should not appear.')

We initially set the logger's level to ``INFO``, so message #1 appears and
message #2 doesn't. We then change the level to ``DEBUG`` temporarily in the
following ``with`` block, and so message #3 appears. After the block exits, the
logger's level is restored to ``INFO`` and so message #4 doesn't appear. In the
next ``with`` block, we set the level to ``DEBUG`` again but also add a handler
writing to ``sys.stdout``. Thus, message #5 appears twice on the console (once
via ``stderr`` and once via ``stdout``). After the ``with`` statement's
completion, the status is as it was before so message #6 appears (like message
#1) whereas message #7 doesn't (just like message #2).

If we run the resulting script, the result is as follows:

.. code-block:: shell-session

    $ python logctx.py
    1. This should appear just once on stderr.
    3. This should appear once on stderr.
    5. This should appear twice - once on stderr and once on stdout.
    5. This should appear twice - once on stderr and once on stdout.
    6. This should appear just once on stderr.

If we run it again, but pipe ``stderr`` to ``/dev/null``, we see the following,
which is the only message written to ``stdout``:

.. code-block:: shell-session

    $ python logctx.py 2>/dev/null
    5. This should appear twice - once on stderr and once on stdout.

Once again, but piping ``stdout`` to ``/dev/null``, we get:

.. code-block:: shell-session

    $ python logctx.py >/dev/null
    1. This should appear just once on stderr.
    3. This should appear once on stderr.
    5. This should appear twice - once on stderr and once on stdout.
    6. This should appear just once on stderr.

In this case, the message #5 printed to ``stdout`` doesn't appear, as expected.

Of course, the approach described here can be generalised, for example to attach
logging filters temporarily. Note that the above code works in Python 2 as well
as Python 3.
PK	%�\X������#html/_sources/howto/logging.rst.txtnu�[���=============
Logging HOWTO
=============

:Author: Vinay Sajip <vinay_sajip at red-dove dot com>

.. _logging-basic-tutorial:

.. currentmodule:: logging

Basic Logging Tutorial
----------------------

Logging is a means of tracking events that happen when some software runs. The
software's developer adds logging calls to their code to indicate that certain
events have occurred. An event is described by a descriptive message which can
optionally contain variable data (i.e. data that is potentially different for
each occurrence of the event). Events also have an importance which the
developer ascribes to the event; the importance can also be called the *level*
or *severity*.

When to use logging
^^^^^^^^^^^^^^^^^^^

Logging provides a set of convenience functions for simple logging usage. These
are :func:`debug`, :func:`info`, :func:`warning`, :func:`error` and
:func:`critical`. To determine when to use logging, see the table below, which
states, for each of a set of common tasks, the best tool to use for it.

+-------------------------------------+--------------------------------------+
| Task you want to perform            | The best tool for the task           |
+=====================================+======================================+
| Display console output for ordinary | :func:`print`                        |
| usage of a command line script or   |                                      |
| program                             |                                      |
+-------------------------------------+--------------------------------------+
| Report events that occur during     | :func:`logging.info` (or             |
| normal operation of a program (e.g. | :func:`logging.debug` for very       |
| for status monitoring or fault      | detailed output for diagnostic       |
| investigation)                      | purposes)                            |
+-------------------------------------+--------------------------------------+
| Issue a warning regarding a         | :func:`warnings.warn` in library     |
| particular runtime event            | code if the issue is avoidable and   |
|                                     | the client application should be     |
|                                     | modified to eliminate the warning    |
|                                     |                                      |
|                                     | :func:`logging.warning` if there is  |
|                                     | nothing the client application can do|
|                                     | about the situation, but the event   |
|                                     | should still be noted                |
+-------------------------------------+--------------------------------------+
| Report an error regarding a         | Raise an exception                   |
| particular runtime event            |                                      |
+-------------------------------------+--------------------------------------+
| Report suppression of an error      | :func:`logging.error`,               |
| without raising an exception (e.g.  | :func:`logging.exception` or         |
| error handler in a long-running     | :func:`logging.critical` as          |
| server process)                     | appropriate for the specific error   |
|                                     | and application domain               |
+-------------------------------------+--------------------------------------+

The logging functions are named after the level or severity of the events
they are used to track. The standard levels and their applicability are
described below (in increasing order of severity):

.. tabularcolumns:: |l|L|

+--------------+---------------------------------------------+
| Level        | When it's used                              |
+==============+=============================================+
| ``DEBUG``    | Detailed information, typically of interest |
|              | only when diagnosing problems.              |
+--------------+---------------------------------------------+
| ``INFO``     | Confirmation that things are working as     |
|              | expected.                                   |
+--------------+---------------------------------------------+
| ``WARNING``  | An indication that something unexpected     |
|              | happened, or indicative of some problem in  |
|              | the near future (e.g. 'disk space low').    |
|              | The software is still working as expected.  |
+--------------+---------------------------------------------+
| ``ERROR``    | Due to a more serious problem, the software |
|              | has not been able to perform some function. |
+--------------+---------------------------------------------+
| ``CRITICAL`` | A serious error, indicating that the program|
|              | itself may be unable to continue running.   |
+--------------+---------------------------------------------+

The default level is ``WARNING``, which means that only events of this level
and above will be tracked, unless the logging package is configured to do
otherwise.

Events that are tracked can be handled in different ways. The simplest way of
handling tracked events is to print them to the console. Another common way
is to write them to a disk file.


.. _howto-minimal-example:

A simple example
^^^^^^^^^^^^^^^^

A very simple example is::

   import logging
   logging.warning('Watch out!')  # will print a message to the console
   logging.info('I told you so')  # will not print anything

If you type these lines into a script and run it, you'll see:

.. code-block:: none

   WARNING:root:Watch out!

printed out on the console. The ``INFO`` message doesn't appear because the
default level is ``WARNING``. The printed message includes the indication of
the level and the description of the event provided in the logging call, i.e.
'Watch out!'. Don't worry about the 'root' part for now: it will be explained
later. The actual output can be formatted quite flexibly if you need that;
formatting options will also be explained later.


Logging to a file
^^^^^^^^^^^^^^^^^

A very common situation is that of recording logging events in a file, so let's
look at that next. Be sure to try the following in a newly-started Python
interpreter, and don't just continue from the session described above::

   import logging
   logging.basicConfig(filename='example.log',level=logging.DEBUG)
   logging.debug('This message should go to the log file')
   logging.info('So should this')
   logging.warning('And this, too')

And now if we open the file and look at what we have, we should find the log
messages::

   DEBUG:root:This message should go to the log file
   INFO:root:So should this
   WARNING:root:And this, too

This example also shows how you can set the logging level which acts as the
threshold for tracking. In this case, because we set the threshold to
``DEBUG``, all of the messages were printed.

If you want to set the logging level from a command-line option such as::

   --log=INFO

and you have the value of the parameter passed for ``--log`` in some variable
*loglevel*, you can use::

   getattr(logging, loglevel.upper())

to get the value which you'll pass to :func:`basicConfig` via the *level*
argument. You may want to error check any user input value, perhaps as in the
following example::

   # assuming loglevel is bound to the string value obtained from the
   # command line argument. Convert to upper case to allow the user to
   # specify --log=DEBUG or --log=debug
   numeric_level = getattr(logging, loglevel.upper(), None)
   if not isinstance(numeric_level, int):
       raise ValueError('Invalid log level: %s' % loglevel)
   logging.basicConfig(level=numeric_level, ...)

The call to :func:`basicConfig` should come *before* any calls to :func:`debug`,
:func:`info` etc. As it's intended as a one-off simple configuration facility,
only the first call will actually do anything: subsequent calls are effectively
no-ops.

If you run the above script several times, the messages from successive runs
are appended to the file *example.log*. If you want each run to start afresh,
not remembering the messages from earlier runs, you can specify the *filemode*
argument, by changing the call in the above example to::

   logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)

The output will be the same as before, but the log file is no longer appended
to, so the messages from earlier runs are lost.


Logging from multiple modules
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If your program consists of multiple modules, here's an example of how you
could organize logging in it::

   # myapp.py
   import logging
   import mylib

   def main():
       logging.basicConfig(filename='myapp.log', level=logging.INFO)
       logging.info('Started')
       mylib.do_something()
       logging.info('Finished')

   if __name__ == '__main__':
       main()

::

   # mylib.py
   import logging

   def do_something():
       logging.info('Doing something')

If you run *myapp.py*, you should see this in *myapp.log*::

   INFO:root:Started
   INFO:root:Doing something
   INFO:root:Finished

which is hopefully what you were expecting to see. You can generalize this to
multiple modules, using the pattern in *mylib.py*. Note that for this simple
usage pattern, you won't know, by looking in the log file, *where* in your
application your messages came from, apart from looking at the event
description. If you want to track the location of your messages, you'll need
to refer to the documentation beyond the tutorial level -- see
:ref:`logging-advanced-tutorial`.


Logging variable data
^^^^^^^^^^^^^^^^^^^^^

To log variable data, use a format string for the event description message and
append the variable data as arguments. For example::

   import logging
   logging.warning('%s before you %s', 'Look', 'leap!')

will display:

.. code-block:: none

   WARNING:root:Look before you leap!

As you can see, merging of variable data into the event description message
uses the old, %-style of string formatting. This is for backwards
compatibility: the logging package pre-dates newer formatting options such as
:meth:`str.format` and :class:`string.Template`. These newer formatting
options *are* supported, but exploring them is outside the scope of this
tutorial.


Changing the format of displayed messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To change the format which is used to display messages, you need to
specify the format you want to use::

   import logging
   logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
   logging.debug('This message should appear on the console')
   logging.info('So should this')
   logging.warning('And this, too')

which would print::

   DEBUG:This message should appear on the console
   INFO:So should this
   WARNING:And this, too

Notice that the 'root' which appeared in earlier examples has disappeared. For
a full set of things that can appear in format strings, you can refer to the
documentation for :ref:`logrecord-attributes`, but for simple usage, you just
need the *levelname* (severity), *message* (event description, including
variable data) and perhaps to display when the event occurred. This is
described in the next section.


Displaying the date/time in messages
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To display the date and time of an event, you would place '%(asctime)s' in
your format string::

   import logging
   logging.basicConfig(format='%(asctime)s %(message)s')
   logging.warning('is when this event was logged.')

which should print something like this::

   2010-12-12 11:41:42,612 is when this event was logged.

The default format for date/time display (shown above) is ISO8601. If you need
more control over the formatting of the date/time, provide a *datefmt*
argument to ``basicConfig``, as in this example::

   import logging
   logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
   logging.warning('is when this event was logged.')

which would display something like this::

   12/12/2010 11:46:36 AM is when this event was logged.

The format of the *datefmt* argument is the same as supported by
:func:`time.strftime`.


Next Steps
^^^^^^^^^^

That concludes the basic tutorial. It should be enough to get you up and
running with logging. There's a lot more that the logging package offers, but
to get the best out of it, you'll need to invest a little more of your time in
reading the following sections. If you're ready for that, grab some of your
favourite beverage and carry on.

If your logging needs are simple, then use the above examples to incorporate
logging into your own scripts, and if you run into problems or don't
understand something, please post a question on the comp.lang.python Usenet
group (available at https://groups.google.com/group/comp.lang.python) and you
should receive help before too long.

Still here? You can carry on reading the next few sections, which provide a
slightly more advanced/in-depth tutorial than the basic one above. After that,
you can take a look at the :ref:`logging-cookbook`.

.. _logging-advanced-tutorial:


Advanced Logging Tutorial
-------------------------

The logging library takes a modular approach and offers several categories
of components: loggers, handlers, filters, and formatters.

* Loggers expose the interface that application code directly uses.
* Handlers send the log records (created by loggers) to the appropriate
  destination.
* Filters provide a finer grained facility for determining which log records
  to output.
* Formatters specify the layout of log records in the final output.

Log event information is passed between loggers, handlers, filters and
formatters in a :class:`LogRecord` instance.

Logging is performed by calling methods on instances of the :class:`Logger`
class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
conceptually arranged in a namespace hierarchy using dots (periods) as
separators. For example, a logger named 'scan' is the parent of loggers
'scan.text', 'scan.html' and 'scan.pdf'. Logger names can be anything you want,
and indicate the area of an application in which a logged message originates.

A good convention to use when naming loggers is to use a module-level logger,
in each module which uses logging, named as follows::

   logger = logging.getLogger(__name__)

This means that logger names track the package/module hierarchy, and it's
intuitively obvious where events are logged just from the logger name.

The root of the hierarchy of loggers is called the root logger. That's the
logger used by the functions :func:`debug`, :func:`info`, :func:`warning`,
:func:`error` and :func:`critical`, which just call the same-named method of
the root logger. The functions and the methods have the same signatures. The
root logger's name is printed as 'root' in the logged output.

It is, of course, possible to log messages to different destinations. Support
is included in the package for writing log messages to files, HTTP GET/POST
locations, email via SMTP, generic sockets, or OS-specific logging mechanisms
such as syslog or the Windows NT event log. Destinations are served by
:dfn:`handler` classes. You can create your own log destination class if you
have special requirements not met by any of the built-in handler classes.

By default, no destination is set for any logging messages. You can specify
a destination (such as console or file) by using :func:`basicConfig` as in the
tutorial examples. If you call the functions  :func:`debug`, :func:`info`,
:func:`warning`, :func:`error` and :func:`critical`, they will check to see
if no destination is set; and if one is not set, they will set a destination
of the console (``sys.stderr``) and a default format for the displayed
message before delegating to the root logger to do the actual message output.

The default format set by :func:`basicConfig` for messages is::

   severity:logger name:message

You can change this by passing a format string to :func:`basicConfig` with the
*format* keyword argument. For all options regarding how a format string is
constructed, see :ref:`formatter-objects`.

Logging Flow
^^^^^^^^^^^^

The flow of log event information in loggers and handlers is illustrated in the
following diagram.

.. image:: logging_flow.png

Loggers
^^^^^^^

:class:`Logger` objects have a threefold job.  First, they expose several
methods to application code so that applications can log messages at runtime.
Second, logger objects determine which log messages to act upon based upon
severity (the default filtering facility) or filter objects.  Third, logger
objects pass along relevant log messages to all interested log handlers.

The most widely used methods on logger objects fall into two categories:
configuration and message sending.

These are the most common configuration methods:

* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
  will handle, where debug is the lowest built-in severity level and critical
  is the highest built-in severity.  For example, if the severity level is
  INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
  and will ignore DEBUG messages.

* :meth:`Logger.addHandler` and :meth:`Logger.removeHandler` add and remove
  handler objects from the logger object.  Handlers are covered in more detail
  in :ref:`handler-basic`.

* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
  objects from the logger object.  Filters are covered in more detail in
  :ref:`filter`.

You don't need to always call these methods on every logger you create. See the
last two paragraphs in this section.

With the logger object configured, the following methods create log messages:

* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
  :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
  a message and a level that corresponds to their respective method names. The
  message is actually a format string, which may contain the standard string
  substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on.  The
  rest of their arguments is a list of objects that correspond with the
  substitution fields in the message.  With regard to :const:`**kwargs`, the
  logging methods care only about a keyword of :const:`exc_info` and use it to
  determine whether to log exception information.

* :meth:`Logger.exception` creates a log message similar to
  :meth:`Logger.error`.  The difference is that :meth:`Logger.exception` dumps a
  stack trace along with it.  Call this method only from an exception handler.

* :meth:`Logger.log` takes a log level as an explicit argument.  This is a
  little more verbose for logging messages than using the log level convenience
  methods listed above, but this is how to log at custom log levels.

:func:`getLogger` returns a reference to a logger instance with the specified
name if it is provided, or ``root`` if not.  The names are period-separated
hierarchical structures.  Multiple calls to :func:`getLogger` with the same name
will return a reference to the same logger object.  Loggers that are further
down in the hierarchical list are children of loggers higher up in the list.
For example, given a logger with a name of ``foo``, loggers with names of
``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.

Loggers have a concept of *effective level*. If a level is not explicitly set
on a logger, the level of its parent is used instead as its effective level.
If the parent has no explicit level set, *its* parent is examined, and so on -
all ancestors are searched until an explicitly set level is found. The root
logger always has an explicit level set (``WARNING`` by default). When deciding
whether to process an event, the effective level of the logger is used to
determine whether the event is passed to the logger's handlers.

Child loggers propagate messages up to the handlers associated with their
ancestor loggers. Because of this, it is unnecessary to define and configure
handlers for all the loggers an application uses. It is sufficient to
configure handlers for a top-level logger and create child loggers as needed.
(You can, however, turn off propagation by setting the *propagate*
attribute of a logger to ``False``.)


.. _handler-basic:

Handlers
^^^^^^^^

:class:`~logging.Handler` objects are responsible for dispatching the
appropriate log messages (based on the log messages' severity) to the handler's
specified destination.  :class:`Logger` objects can add zero or more handler
objects to themselves with an :meth:`~Logger.addHandler` method.  As an example
scenario, an application may want to send all log messages to a log file, all
log messages of error or higher to stdout, and all messages of critical to an
email address. This scenario requires three individual handlers where each
handler is responsible for sending messages of a specific severity to a specific
location.

The standard library includes quite a few handler types (see
:ref:`useful-handlers`); the tutorials use mainly :class:`StreamHandler` and
:class:`FileHandler` in its examples.

There are very few methods in a handler for application developers to concern
themselves with.  The only handler methods that seem relevant for application
developers who are using the built-in handler objects (that is, not creating
custom handlers) are the following configuration methods:

* The :meth:`~Handler.setLevel` method, just as in logger objects, specifies the
  lowest severity that will be dispatched to the appropriate destination.  Why
  are there two :func:`setLevel` methods?  The level set in the logger
  determines which severity of messages it will pass to its handlers.  The level
  set in each handler determines which messages that handler will send on.

* :meth:`~Handler.setFormatter` selects a Formatter object for this handler to
  use.

* :meth:`~Handler.addFilter` and :meth:`~Handler.removeFilter` respectively
  configure and deconfigure filter objects on handlers.

Application code should not directly instantiate and use instances of
:class:`Handler`.  Instead, the :class:`Handler` class is a base class that
defines the interface that all handlers should have and establishes some
default behavior that child classes can use (or override).


Formatters
^^^^^^^^^^

Formatter objects configure the final order, structure, and contents of the log
message.  Unlike the base :class:`logging.Handler` class, application code may
instantiate formatter classes, although you could likely subclass the formatter
if your application needs special behavior.  The constructor takes two
optional arguments -- a message format string and a date format string.

.. method:: logging.Formatter.__init__(fmt=None, datefmt=None)

If there is no message format string, the default is to use the
raw message.  If there is no date format string, the default date format is::

    %Y-%m-%d %H:%M:%S

with the milliseconds tacked on at the end.

The message format string uses ``%(<dictionary key>)s`` styled string
substitution; the possible keys are documented in :ref:`logrecord-attributes`.

The following message format string will log the time in a human-readable
format, the severity of the message, and the contents of the message, in that
order::

    '%(asctime)s - %(levelname)s - %(message)s'

Formatters use a user-configurable function to convert the creation time of a
record to a tuple. By default, :func:`time.localtime` is used; to change this
for a particular formatter instance, set the ``converter`` attribute of the
instance to a function with the same signature as :func:`time.localtime` or
:func:`time.gmtime`. To change it for all formatters, for example if you want
all logging times to be shown in GMT, set the ``converter`` attribute in the
Formatter class (to ``time.gmtime`` for GMT display).


Configuring Logging
^^^^^^^^^^^^^^^^^^^

.. currentmodule:: logging.config

Programmers can configure logging in three ways:

1. Creating loggers, handlers, and formatters explicitly using Python
   code that calls the configuration methods listed above.
2. Creating a logging config file and reading it using the :func:`fileConfig`
   function.
3. Creating a dictionary of configuration information and passing it
   to the :func:`dictConfig` function.

For the reference documentation on the last two options, see
:ref:`logging-config-api`.  The following example configures a very simple
logger, a console handler, and a simple formatter using Python code::

    import logging

    # create logger
    logger = logging.getLogger('simple_example')
    logger.setLevel(logging.DEBUG)

    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # add formatter to ch
    ch.setFormatter(formatter)

    # add ch to logger
    logger.addHandler(ch)

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')

Running this module from the command line produces the following output:

.. code-block:: shell-session

    $ python simple_logging_module.py
    2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
    2005-03-19 15:10:26,620 - simple_example - INFO - info message
    2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
    2005-03-19 15:10:26,697 - simple_example - ERROR - error message
    2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message

The following Python module creates a logger, handler, and formatter nearly
identical to those in the example listed above, with the only difference being
the names of the objects::

    import logging
    import logging.config

    logging.config.fileConfig('logging.conf')

    # create logger
    logger = logging.getLogger('simpleExample')

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')

Here is the logging.conf file::

    [loggers]
    keys=root,simpleExample

    [handlers]
    keys=consoleHandler

    [formatters]
    keys=simpleFormatter

    [logger_root]
    level=DEBUG
    handlers=consoleHandler

    [logger_simpleExample]
    level=DEBUG
    handlers=consoleHandler
    qualname=simpleExample
    propagate=0

    [handler_consoleHandler]
    class=StreamHandler
    level=DEBUG
    formatter=simpleFormatter
    args=(sys.stdout,)

    [formatter_simpleFormatter]
    format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
    datefmt=

The output is nearly identical to that of the non-config-file-based example:

.. code-block:: shell-session

    $ python simple_logging_config.py
    2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
    2005-03-19 15:38:55,979 - simpleExample - INFO - info message
    2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
    2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
    2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

You can see that the config file approach has a few advantages over the Python
code approach, mainly separation of configuration and code and the ability of
noncoders to easily modify the logging properties.

.. warning:: The :func:`fileConfig` function takes a default parameter,
   ``disable_existing_loggers``, which defaults to ``True`` for reasons of
   backward compatibility. This may or may not be what you want, since it
   will cause any loggers existing before the :func:`fileConfig` call to
   be disabled unless they (or an ancestor) are explicitly named in the
   configuration.  Please refer to the reference documentation for more
   information, and specify ``False`` for this parameter if you wish.

   The dictionary passed to :func:`dictConfig` can also specify a Boolean
   value with key ``disable_existing_loggers``, which if not specified
   explicitly in the dictionary also defaults to being interpreted as
   ``True``.  This leads to the logger-disabling behaviour described above,
   which may not be what you want - in which case, provide the key
   explicitly with a value of ``False``.

.. currentmodule:: logging

Note that the class names referenced in config files need to be either relative
to the logging module, or absolute values which can be resolved using normal
import mechanisms. Thus, you could use either
:class:`~logging.handlers.WatchedFileHandler` (relative to the logging module) or
``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
and module ``mymodule``, where ``mypackage`` is available on the Python import
path).

In Python 2.7, a new means of configuring logging has been introduced, using
dictionaries to hold configuration information. This provides a superset of the
functionality of the config-file-based approach outlined above, and is the
recommended configuration method for new applications and deployments. Because
a Python dictionary is used to hold configuration information, and since you
can populate that dictionary using different means, you have more options for
configuration. For example, you can use a configuration file in JSON format,
or, if you have access to YAML processing functionality, a file in YAML
format, to populate the configuration dictionary. Or, of course, you can
construct the dictionary in Python code, receive it in pickled form over a
socket, or use whatever approach makes sense for your application.

Here's an example of the same configuration as above, in YAML format for
the new dictionary-based approach::

    version: 1
    formatters:
      simple:
        format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    handlers:
      console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple
        stream: ext://sys.stdout
    loggers:
      simpleExample:
        level: DEBUG
        handlers: [console]
        propagate: no
    root:
      level: DEBUG
      handlers: [console]

For more information about logging using a dictionary, see
:ref:`logging-config-api`.

What happens if no configuration is provided
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If no logging configuration is provided, it is possible to have a situation
where a logging event needs to be output, but no handlers can be found to
output the event. The behaviour of the logging package in these
circumstances is dependent on the Python version.

For Python 2.x, the behaviour is as follows:

* If *logging.raiseExceptions* is ``False`` (production mode), the event is
  silently dropped.

* If *logging.raiseExceptions* is ``True`` (development mode), a message
  'No handlers could be found for logger X.Y.Z' is printed once.

.. _library-config:

Configuring Logging for a Library
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

When developing a library which uses logging, you should take care to
document how the library uses logging - for example, the names of loggers
used. Some consideration also needs to be given to its logging configuration.
If the using application does not configure logging, and library code makes
logging calls, then (as described in the previous section) an error message
will be printed to ``sys.stderr``.

If for some reason you *don't* want this message printed in the absence of
any logging configuration, you can attach a do-nothing handler to the top-level
logger for your library. This avoids the message being printed, since a handler
will be always be found for the library's events: it just doesn't produce any
output. If the library user configures logging for application use, presumably
that configuration will add some handlers, and if levels are suitably
configured then logging calls made in library code will send output to those
handlers, as normal.

A do-nothing handler is included in the logging package:
:class:`~logging.NullHandler` (since Python 2.7). An instance of this handler
could be added to the top-level logger of the logging namespace used by the
library (*if* you want to prevent an error message being output to
``sys.stderr`` in the absence of logging configuration). If all logging by a
library *foo* is done using loggers with names matching 'foo.x', 'foo.x.y',
etc. then the code::

    import logging
    logging.getLogger('foo').addHandler(logging.NullHandler())

should have the desired effect. If an organisation produces a number of
libraries, then the logger name specified can be 'orgname.foo' rather than
just 'foo'.

.. note:: It is strongly advised that you *do not add any handlers other
   than* :class:`~logging.NullHandler` *to your library's loggers*. This is
   because the configuration of handlers is the prerogative of the application
   developer who uses your library. The application developer knows their
   target audience and what handlers are most appropriate for their
   application: if you add handlers 'under the hood', you might well interfere
   with their ability to carry out unit tests and deliver logs which suit their
   requirements.


Logging Levels
--------------

The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.

+--------------+---------------+
| Level        | Numeric value |
+==============+===============+
| ``CRITICAL`` | 50            |
+--------------+---------------+
| ``ERROR``    | 40            |
+--------------+---------------+
| ``WARNING``  | 30            |
+--------------+---------------+
| ``INFO``     | 20            |
+--------------+---------------+
| ``DEBUG``    | 10            |
+--------------+---------------+
| ``NOTSET``   | 0             |
+--------------+---------------+

Levels can also be associated with loggers, being set either by the developer or
through loading a saved logging configuration. When a logging method is called
on a logger, the logger compares its own level with the level associated with
the method call. If the logger's level is higher than the method call's, no
logging message is actually generated. This is the basic mechanism controlling
the verbosity of logging output.

Logging messages are encoded as instances of the :class:`~logging.LogRecord`
class. When a logger decides to actually log an event, a
:class:`~logging.LogRecord` instance is created from the logging message.

Logging messages are subjected to a dispatch mechanism through the use of
:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
class. Handlers are responsible for ensuring that a logged message (in the form
of a :class:`LogRecord`) ends up in a particular location (or set of locations)
which is useful for the target audience for that message (such as end users,
support desk staff, system administrators, developers). Handlers are passed
:class:`LogRecord` instances intended for particular destinations. Each logger
can have zero, one or more handlers associated with it (via the
:meth:`~Logger.addHandler` method of :class:`Logger`). In addition to any
handlers directly associated with a logger, *all handlers associated with all
ancestors of the logger* are called to dispatch the message (unless the
*propagate* flag for a logger is set to a false value, at which point the
passing to ancestor handlers stops).

Just as for loggers, handlers can have levels associated with them. A handler's
level acts as a filter in the same way as a logger's level does. If a handler
decides to actually dispatch an event, the :meth:`~Handler.emit` method is used
to send the message to its destination. Most user-defined subclasses of
:class:`Handler` will need to override this :meth:`~Handler.emit`.

.. _custom-levels:

Custom Levels
^^^^^^^^^^^^^

Defining your own levels is possible, but should not be necessary, as the
existing levels have been chosen on the basis of practical experience.
However, if you are convinced that you need custom levels, great care should
be exercised when doing this, and it is possibly *a very bad idea to define
custom levels if you are developing a library*. That's because if multiple
library authors all define their own custom levels, there is a chance that
the logging output from such multiple libraries used together will be
difficult for the using developer to control and/or interpret, because a
given numeric value might mean different things for different libraries.

.. _useful-handlers:

Useful Handlers
---------------

In addition to the base :class:`Handler` class, many useful subclasses are
provided:

#. :class:`StreamHandler` instances send messages to streams (file-like
   objects).

#. :class:`FileHandler` instances send messages to disk files.

#. :class:`~handlers.BaseRotatingHandler` is the base class for handlers that
   rotate log files at a certain point. It is not meant to be  instantiated
   directly. Instead, use :class:`~handlers.RotatingFileHandler` or
   :class:`~handlers.TimedRotatingFileHandler`.

#. :class:`~handlers.RotatingFileHandler` instances send messages to disk
   files, with support for maximum log file sizes and log file rotation.

#. :class:`~handlers.TimedRotatingFileHandler` instances send messages to
   disk files, rotating the log file at certain timed intervals.

#. :class:`~handlers.SocketHandler` instances send messages to TCP/IP
   sockets.

#. :class:`~handlers.DatagramHandler` instances send messages to UDP
   sockets.

#. :class:`~handlers.SMTPHandler` instances send messages to a designated
   email address.

#. :class:`~handlers.SysLogHandler` instances send messages to a Unix
   syslog daemon, possibly on a remote machine.

#. :class:`~handlers.NTEventLogHandler` instances send messages to a
   Windows NT/2000/XP event log.

#. :class:`~handlers.MemoryHandler` instances send messages to a buffer
   in memory, which is flushed whenever specific criteria are met.

#. :class:`~handlers.HTTPHandler` instances send messages to an HTTP
   server using either ``GET`` or ``POST`` semantics.

#. :class:`~handlers.WatchedFileHandler` instances watch the file they are
   logging to. If the file changes, it is closed and reopened using the file
   name. This handler is only useful on Unix-like systems; Windows does not
   support the underlying mechanism used.

#. :class:`NullHandler` instances do nothing with error messages. They are used
   by library developers who want to use logging, but want to avoid the 'No
   handlers could be found for logger XXX' message which can be displayed if
   the library user has not configured logging. See :ref:`library-config` for
   more information.

.. versionadded:: 2.7
   The :class:`NullHandler` class.

The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
classes are defined in the core logging package. The other handlers are
defined in a sub- module, :mod:`logging.handlers`. (There is also another
sub-module, :mod:`logging.config`, for configuration functionality.)

Logged messages are formatted for presentation through instances of the
:class:`Formatter` class. They are initialized with a format string suitable for
use with the % operator and a dictionary.

For formatting multiple messages in a batch, instances of
:class:`~handlers.BufferingFormatter` can be used. In addition to the format
string (which is applied to each message in the batch), there is provision for
header and trailer format strings.

When filtering based on logger level and/or handler level is not enough,
instances of :class:`Filter` can be added to both :class:`Logger` and
:class:`Handler` instances (through their :meth:`~Handler.addFilter` method).
Before deciding to process a message further, both loggers and handlers consult
all their filters for permission. If any filter returns a false value, the
message is not processed further.

The basic :class:`Filter` functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.


.. _logging-exceptions:

Exceptions raised during logging
--------------------------------

The logging package is designed to swallow exceptions which occur while logging
in production. This is so that errors which occur while handling logging events
- such as logging misconfiguration, network or other similar errors - do not
cause the application using logging to terminate prematurely.

:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
swallowed. Other exceptions which occur during the :meth:`~Handler.emit` method
of a :class:`Handler` subclass are passed to its :meth:`~Handler.handleError`
method.

The default implementation of :meth:`~Handler.handleError` in :class:`Handler`
checks to see if a module-level variable, :data:`raiseExceptions`, is set. If
set, a traceback is printed to :data:`sys.stderr`. If not set, the exception is
swallowed.

.. note:: The default value of :data:`raiseExceptions` is ``True``. This is
   because during development, you typically want to be notified of any
   exceptions that occur. It's advised that you set :data:`raiseExceptions` to
   ``False`` for production usage.


.. _arbitrary-object-messages:

Using arbitrary objects as messages
-----------------------------------

In the preceding sections and examples, it has been assumed that the message
passed when logging the event is a string. However, this is not the only
possibility. You can pass an arbitrary object as a message, and its
:meth:`~object.__str__` method will be called when the logging system needs to
convert it to a string representation. In fact, if you want to, you can avoid
computing a string representation altogether - for example, the
:class:`~handlers.SocketHandler` emits an event by pickling it and sending it
over the wire.


Optimization
------------

Formatting of message arguments is deferred until it cannot be avoided.
However, computing the arguments passed to the logging method can also be
expensive, and you may want to avoid doing it if the logger will just throw
away your event. To decide what to do, you can call the
:meth:`~Logger.isEnabledFor` method which takes a level argument and returns
true if the event would be created by the Logger for that level of call.
You can write code like this::

    if logger.isEnabledFor(logging.DEBUG):
        logger.debug('Message with %s, %s', expensive_func1(),
                                            expensive_func2())

so that if the logger's threshold is set above ``DEBUG``, the calls to
:func:`expensive_func1` and :func:`expensive_func2` are never made.

.. note:: In some cases, :meth:`~Logger.isEnabledFor` can itself be more
   expensive than you'd like (e.g. for deeply nested loggers where an explicit
   level is only set high up in the logger hierarchy). In such cases (or if you
   want to avoid calling a method in tight loops), you can cache the result of a
   call to :meth:`~Logger.isEnabledFor` in a local or instance variable, and use
   that instead of calling the method each time. Such a cached value would only
   need to be recomputed when the logging configuration changes dynamically
   while the application is running (which is not all that common).

There are other optimizations which can be made for specific applications which
need more precise control over what logging information is collected. Here's a
list of things you can do to avoid processing during logging which you don't
need:

+-----------------------------------------------+----------------------------------------+
| What you don't want to collect                | How to avoid collecting it             |
+===============================================+========================================+
| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``.  |
|                                               | This avoids calling                    |
|                                               | :func:`sys._getframe`, which may help  |
|                                               | to speed up your code in environments  |
|                                               | like PyPy (which can't speed up code   |
|                                               | that uses :func:`sys._getframe`).      |
+-----------------------------------------------+----------------------------------------+
| Threading information.                        | Set ``logging.logThreads`` to ``0``.   |
+-----------------------------------------------+----------------------------------------+
| Process information.                          | Set ``logging.logProcesses`` to ``0``. |
+-----------------------------------------------+----------------------------------------+

Also note that the core logging module only includes the basic handlers. If
you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
take up any memory.

.. seealso::

   Module :mod:`logging`
      API reference for the logging module.

   Module :mod:`logging.config`
      Configuration API for the logging module.

   Module :mod:`logging.handlers`
      Useful handlers included with the logging module.

   :ref:`A logging cookbook <logging-cookbook>`
PK	%�\�,x@�W�W%html/_sources/howto/pyporting.rst.txtnu�[���.. _pyporting-howto:

*********************************
Porting Python 2 Code to Python 3
*********************************

:author: Brett Cannon

.. topic:: Abstract

   With Python 3 being the future of Python while Python 2 is still in active
   use, it is good to have your project available for both major releases of
   Python. This guide is meant to help you figure out how best to support both
   Python 2 & 3 simultaneously.

   If you are looking to port an extension module instead of pure Python code,
   please see :ref:`cporting-howto`.

   If you would like to read one core Python developer's take on why Python 3
   came into existence, you can read Nick Coghlan's `Python 3 Q & A`_ or
   Brett Cannon's `Why Python 3 exists`_.

   For help with porting, you can email the python-porting_ mailing list with
   questions.

The Short Explanation
=====================

To make your project be single-source Python 2/3 compatible, the basic steps
are:

#. Only worry about supporting Python 2.7
#. Make sure you have good test coverage (coverage.py_ can help;
   ``pip install coverage``)
#. Learn the differences between Python 2 & 3
#. Use Futurize_ (or Modernize_) to update your code (e.g. ``pip install future``)
#. Use Pylint_ to help make sure you don't regress on your Python 3 support
   (``pip install pylint``)
#. Use caniusepython3_ to find out which of your dependencies are blocking your
   use of Python 3 (``pip install caniusepython3``)
#. Once your dependencies are no longer blocking you, use continuous integration
   to make sure you stay compatible with Python 2 & 3 (tox_ can help test
   against multiple versions of Python; ``pip install tox``)
#. Consider using optional static type checking to make sure your type usage
   works in both Python 2 & 3 (e.g. use mypy_ to check your typing under both
   Python 2 & Python 3).


Details
=======

A key point about supporting Python 2 & 3 simultaneously is that you can start
**today**! Even if your dependencies are not supporting Python 3 yet that does
not mean you can't modernize your code **now** to support Python 3. Most changes
required to support Python 3 lead to cleaner code using newer practices even in
Python 2 code.

Another key point is that modernizing your Python 2 code to also support
Python 3 is largely automated for you. While you might have to make some API
decisions thanks to Python 3 clarifying text data versus binary data, the
lower-level work is now mostly done for you and thus can at least benefit from
the automated changes immediately.

Keep those key points in mind while you read on about the details of porting
your code to support Python 2 & 3 simultaneously.


Drop support for Python 2.6 and older
-------------------------------------

While you can make Python 2.5 work with Python 3, it is **much** easier if you
only have to work with Python 2.7. If dropping Python 2.5 is not an
option then the six_ project can help you support Python 2.5 & 3 simultaneously
(``pip install six``). Do realize, though, that nearly all the projects listed
in this HOWTO will not be available to you.

If you are able to skip Python 2.5 and older, then the required changes
to your code should continue to look and feel like idiomatic Python code. At
worst you will have to use a function instead of a method in some instances or
have to import a function instead of using a built-in one, but otherwise the
overall transformation should not feel foreign to you.

But you should aim for only supporting Python 2.7. Python 2.6 is no longer
freely supported and thus is not receiving bugfixes. This means **you** will have
to work around any issues you come across with Python 2.6. There are also some
tools mentioned in this HOWTO which do not support Python 2.6 (e.g., Pylint_),
and this will become more commonplace as time goes on. It will simply be easier
for you if you only support the versions of Python that you have to support.


Make sure you specify the proper version support in your ``setup.py`` file
--------------------------------------------------------------------------

In your ``setup.py`` file you should have the proper `trove classifier`_
specifying what versions of Python you support. As your project does not support
Python 3 yet you should at least have
``Programming Language :: Python :: 2 :: Only`` specified. Ideally you should
also specify each major/minor version of Python that you do support, e.g.
``Programming Language :: Python :: 2.7``.


Have good test coverage
-----------------------

Once you have your code supporting the oldest version of Python 2 you want it
to, you will want to make sure your test suite has good coverage. A good rule of
thumb is that if you want to be confident enough in your test suite that any
failures that appear after having tools rewrite your code are actual bugs in the
tools and not in your code. If you want a number to aim for, try to get over 80%
coverage (and don't feel bad if you find it hard to get better than 90%
coverage). If you don't already have a tool to measure test coverage then
coverage.py_ is recommended.


Learn the differences between Python 2 & 3
-------------------------------------------

Once you have your code well-tested you are ready to begin porting your code to
Python 3! But to fully understand how your code is going to change and what
you want to look out for while you code, you will want to learn what changes
Python 3 makes in terms of Python 2. Typically the two best ways of doing that
is reading the `"What's New"`_ doc for each release of Python 3 and the
`Porting to Python 3`_ book (which is free online). There is also a handy
`cheat sheet`_ from the Python-Future project.


Update your code
----------------

Once you feel like you know what is different in Python 3 compared to Python 2,
it's time to update your code! You have a choice between two tools in porting
your code automatically: Futurize_ and Modernize_. Which tool you choose will
depend on how much like Python 3 you want your code to be. Futurize_ does its
best to make Python 3 idioms and practices exist in Python 2, e.g. backporting
the ``bytes`` type from Python 3 so that you have semantic parity between the
major versions of Python. Modernize_,
on the other hand, is more conservative and targets a Python 2/3 subset of
Python, directly relying on six_ to help provide compatibility. As Python 3 is
the future, it might be best to consider Futurize to begin adjusting to any new
practices that Python 3 introduces which you are not accustomed to yet.

Regardless of which tool you choose, they will update your code to run under
Python 3 while staying compatible with the version of Python 2 you started with.
Depending on how conservative you want to be, you may want to run the tool over
your test suite first and visually inspect the diff to make sure the
transformation is accurate. After you have transformed your test suite and
verified that all the tests still pass as expected, then you can transform your
application code knowing that any tests which fail is a translation failure.

Unfortunately the tools can't automate everything to make your code work under
Python 3 and so there are a handful of things you will need to update manually
to get full Python 3 support (which of these steps are necessary vary between
the tools). Read the documentation for the tool you choose to use to see what it
fixes by default and what it can do optionally to know what will (not) be fixed
for you and what you may have to fix on your own (e.g. using ``io.open()`` over
the built-in ``open()`` function is off by default in Modernize). Luckily,
though, there are only a couple of things to watch out for which can be
considered large issues that may be hard to debug if not watched for.


Division
++++++++

In Python 3, ``5 / 2 == 2.5`` and not ``2``; all division between ``int`` values
result in a ``float``. This change has actually been planned since Python 2.2
which was released in 2002. Since then users have been encouraged to add
``from __future__ import division`` to any and all files which use the ``/`` and
``//`` operators or to be running the interpreter with the ``-Q`` flag. If you
have not been doing this then you will need to go through your code and do two
things:

#. Add ``from __future__ import division`` to your files
#. Update any division operator as necessary to either use ``//`` to use floor
   division or continue using ``/`` and expect a float

The reason that ``/`` isn't simply translated to ``//`` automatically is that if
an object defines a ``__truediv__`` method but not ``__floordiv__`` then your
code would begin to fail (e.g. a user-defined class that uses ``/`` to
signify some operation but not ``//`` for the same thing or at all).


Text versus binary data
+++++++++++++++++++++++

In Python 2 you could use the ``str`` type for both text and binary data.
Unfortunately this confluence of two different concepts could lead to brittle
code which sometimes worked for either kind of data, sometimes not. It also
could lead to confusing APIs if people didn't explicitly state that something
that accepted ``str`` accepted either text or binary data instead of one
specific type. This complicated the situation especially for anyone supporting
multiple languages as APIs wouldn't bother explicitly supporting ``unicode``
when they claimed text data support.

To make the distinction between text and binary data clearer and more
pronounced, Python 3 did what most languages created in the age of the internet
have done and made text and binary data distinct types that cannot blindly be
mixed together (Python predates widespread access to the internet). For any code
that deals only with text or only binary data, this separation doesn't pose an
issue. But for code that has to deal with both, it does mean you might have to
now care about when you are using text compared to binary data, which is why
this cannot be entirely automated.

To start, you will need to decide which APIs take text and which take binary
(it is **highly** recommended you don't design APIs that can take both due to
the difficulty of keeping the code working; as stated earlier it is difficult to
do well). In Python 2 this means making sure the APIs that take text can work
with ``unicode`` and those that work with binary data work with the
``bytes`` type from Python 3 (which is a subset of ``str`` in Python 2 and acts
as an alias for ``bytes`` type in Python 2). Usually the biggest issue is
realizing which methods exist on which types in Python 2 & 3 simultaneously
(for text that's ``unicode`` in Python 2 and ``str`` in Python 3, for binary
that's ``str``/``bytes`` in Python 2 and ``bytes`` in Python 3). The following
table lists the **unique** methods of each data type across Python 2 & 3
(e.g., the ``decode()`` method is usable on the equivalent binary data type in
either Python 2 or 3, but it can't be used by the textual data type consistently
between Python 2 and 3 because ``str`` in Python 3 doesn't have the method). Do
note that as of Python 3.5 the ``__mod__`` method was added to the bytes type.

======================== =====================
**Text data**            **Binary data**
------------------------ ---------------------
\                        decode
------------------------ ---------------------
encode
------------------------ ---------------------
format
------------------------ ---------------------
isdecimal
------------------------ ---------------------
isnumeric
======================== =====================

Making the distinction easier to handle can be accomplished by encoding and
decoding between binary data and text at the edge of your code. This means that
when you receive text in binary data, you should immediately decode it. And if
your code needs to send text as binary data then encode it as late as possible.
This allows your code to work with only text internally and thus eliminates
having to keep track of what type of data you are working with.

The next issue is making sure you know whether the string literals in your code
represent text or binary data. You should add a ``b`` prefix to any
literal that presents binary data. For text you should add a ``u`` prefix to
the text literal. (there is a :mod:`__future__` import to force all unspecified
literals to be Unicode, but usage has shown it isn't as effective as adding a
``b`` or ``u`` prefix to all literals explicitly)

As part of this dichotomy you also need to be careful about opening files.
Unless you have been working on Windows, there is a chance you have not always
bothered to add the ``b`` mode when opening a binary file (e.g., ``rb`` for
binary reading).  Under Python 3, binary files and text files are clearly
distinct and mutually incompatible; see the :mod:`io` module for details.
Therefore, you **must** make a decision of whether a file will be used for
binary access (allowing binary data to be read and/or written) or textual access
(allowing text data to be read and/or written). You should also use :func:`io.open`
for opening files instead of the built-in :func:`open` function as the :mod:`io`
module is consistent from Python 2 to 3 while the built-in :func:`open` function
is not (in Python 3 it's actually :func:`io.open`). Do not bother with the
outdated practice of using :func:`codecs.open` as that's only necessary for
keeping compatibility with Python 2.5.

The constructors of both ``str`` and ``bytes`` have different semantics for the
same arguments between Python 2 & 3. Passing an integer to ``bytes`` in Python 2
will give you the string representation of the integer: ``bytes(3) == '3'``.
But in Python 3, an integer argument to ``bytes`` will give you a bytes object
as long as the integer specified, filled with null bytes:
``bytes(3) == b'\x00\x00\x00'``. A similar worry is necessary when passing a
bytes object to ``str``. In Python 2 you just get the bytes object back:
``str(b'3') == b'3'``. But in Python 3 you get the string representation of the
bytes object: ``str(b'3') == "b'3'"``.

Finally, the indexing of binary data requires careful handling (slicing does
**not** require any special handling). In Python 2,
``b'123'[1] == b'2'`` while in Python 3 ``b'123'[1] == 50``. Because binary data
is simply a collection of binary numbers, Python 3 returns the integer value for
the byte you index on. But in Python 2 because ``bytes == str``, indexing
returns a one-item slice of bytes. The six_ project has a function
named ``six.indexbytes()`` which will return an integer like in Python 3:
``six.indexbytes(b'123', 1)``.

To summarize:

#. Decide which of your APIs take text and which take binary data
#. Make sure that your code that works with text also works with ``unicode`` and
   code for binary data works with ``bytes`` in Python 2 (see the table above
   for what methods you cannot use for each type)
#. Mark all binary literals with a ``b`` prefix, textual literals with a ``u``
   prefix
#. Decode binary data to text as soon as possible, encode text as binary data as
   late as possible
#. Open files using :func:`io.open` and make sure to specify the ``b`` mode when
   appropriate
#. Be careful when indexing into binary data


Use feature detection instead of version detection
++++++++++++++++++++++++++++++++++++++++++++++++++

Inevitably you will have code that has to choose what to do based on what
version of Python is running. The best way to do this is with feature detection
of whether the version of Python you're running under supports what you need.
If for some reason that doesn't work then you should make the version check be
against Python 2 and not Python 3. To help explain this, let's look at an
example.

Let's pretend that you need access to a feature of importlib_ that
is available in Python's standard library since Python 3.3 and available for
Python 2 through importlib2_ on PyPI. You might be tempted to write code to
access e.g. the ``importlib.abc`` module by doing the following::

  import sys

  if sys.version_info[0] == 3:
      from importlib import abc
  else:
      from importlib2 import abc

The problem with this code is what happens when Python 4 comes out? It would
be better to treat Python 2 as the exceptional case instead of Python 3 and
assume that future Python versions will be more compatible with Python 3 than
Python 2::

  import sys

  if sys.version_info[0] > 2:
      from importlib import abc
  else:
      from importlib2 import abc

The best solution, though, is to do no version detection at all and instead rely
on feature detection. That avoids any potential issues of getting the version
detection wrong and helps keep you future-compatible::

  try:
      from importlib import abc
  except ImportError:
      from importlib2 import abc


Prevent compatibility regressions
---------------------------------

Once you have fully translated your code to be compatible with Python 3, you
will want to make sure your code doesn't regress and stop working under
Python 3. This is especially true if you have a dependency which is blocking you
from actually running under Python 3 at the moment.

To help with staying compatible, any new modules you create should have
at least the following block of code at the top of it::

    from __future__ import absolute_import
    from __future__ import division
    from __future__ import print_function

You can also run Python 2 with the ``-3`` flag to be warned about various
compatibility issues your code triggers during execution. If you turn warnings
into errors with ``-Werror`` then you can make sure that you don't accidentally
miss a warning.

You can also use the Pylint_ project and its ``--py3k`` flag to lint your code
to receive warnings when your code begins to deviate from Python 3
compatibility. This also prevents you from having to run Modernize_ or Futurize_
over your code regularly to catch compatibility regressions. This does require
you only support Python 2.7 and Python 3.4 or newer as that is Pylint's
minimum Python version support.


Check which dependencies block your transition
----------------------------------------------

**After** you have made your code compatible with Python 3 you should begin to
care about whether your dependencies have also been ported. The caniusepython3_
project was created to help you determine which projects
-- directly or indirectly -- are blocking you from supporting Python 3. There
is both a command-line tool as well as a web interface at
https://caniusepython3.com.

The project also provides code which you can integrate into your test suite so
that you will have a failing test when you no longer have dependencies blocking
you from using Python 3. This allows you to avoid having to manually check your
dependencies and to be notified quickly when you can start running on Python 3.


Update your ``setup.py`` file to denote Python 3 compatibility
--------------------------------------------------------------

Once your code works under Python 3, you should update the classifiers in
your ``setup.py`` to contain ``Programming Language :: Python :: 3`` and to not
specify sole Python 2 support. This will tell anyone using your code that you
support Python 2 **and** 3. Ideally you will also want to add classifiers for
each major/minor version of Python you now support.


Use continuous integration to stay compatible
---------------------------------------------

Once you are able to fully run under Python 3 you will want to make sure your
code always works under both Python 2 & 3. Probably the best tool for running
your tests under multiple Python interpreters is tox_. You can then integrate
tox with your continuous integration system so that you never accidentally break
Python 2 or 3 support.

You may also want to use the ``-bb`` flag with the Python 3 interpreter to
trigger an exception when you are comparing bytes to strings or bytes to an int
(the latter is available starting in Python 3.5). By default type-differing
comparisons simply return ``False``, but if you made a mistake in your
separation of text/binary data handling or indexing on bytes you wouldn't easily
find the mistake. This flag will raise an exception when these kinds of
comparisons occur, making the mistake much easier to track down.

And that's mostly it! At this point your code base is compatible with both
Python 2 and 3 simultaneously. Your testing will also be set up so that you
don't accidentally break Python 2 or 3 compatibility regardless of which version
you typically run your tests under while developing.


Consider using optional static type checking
--------------------------------------------

Another way to help port your code is to use a static type checker like
mypy_ or pytype_ on your code. These tools can be used to analyze your code as
if it's being run under Python 2, then you can run the tool a second time as if
your code is running under Python 3. By running a static type checker twice like
this you can discover if you're e.g. misusing binary data type in one version
of Python compared to another. If you add optional type hints to your code you
can also explicitly state whether your APIs use textual or binary data, helping
to make sure everything functions as expected in both versions of Python.


.. _2to3: https://docs.python.org/3/library/2to3.html
.. _caniusepython3: https://pypi.org/project/caniusepython3
.. _cheat sheet: http://python-future.org/compatible_idioms.html
.. _coverage.py: https://pypi.org/project/coverage
.. _Futurize: http://python-future.org/automatic_conversion.html
.. _importlib: https://docs.python.org/3/library/importlib.html#module-importlib
.. _importlib2: https://pypi.org/project/importlib2
.. _Modernize: https://python-modernize.readthedocs.org/en/latest/
.. _mypy: http://mypy-lang.org/
.. _Porting to Python 3: http://python3porting.com/
.. _Pylint: https://pypi.org/project/pylint

.. _Python 3 Q & A: https://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html

.. _pytype: https://github.com/google/pytype
.. _python-future: http://python-future.org/
.. _python-porting: https://mail.python.org/mailman/listinfo/python-porting
.. _six: https://pypi.org/project/six
.. _tox: https://pypi.org/project/tox
.. _trove classifier: https://pypi.org/classifiers

.. _"What's New": https://docs.python.org/3/whatsnew/index.html

.. _Why Python 3 exists: http://www.snarky.ca/why-python-3-exists
PK	%�\?5����!html/_sources/howto/regex.rst.txtnu�[���.. _regex-howto:

****************************
  Regular Expression HOWTO
****************************

:Author: A.M. Kuchling <amk@amk.ca>

.. TODO:
   Document lookbehind assertions
   Better way of displaying a RE, a string, and what it matches
   Mention optional argument to match.groups()
   Unicode (at least a reference)


.. topic:: Abstract

   This document is an introductory tutorial to using regular expressions in Python
   with the :mod:`re` module.  It provides a gentler introduction than the
   corresponding section in the Library Reference.


Introduction
============

The :mod:`re` module was added in Python 1.5, and provides Perl-style regular
expression patterns.  Earlier versions of Python came with the :mod:`regex`
module, which provided Emacs-style patterns.  The :mod:`regex` module was
removed completely in Python 2.5.

Regular expressions (called REs, or regexes, or regex patterns) are essentially
a tiny, highly specialized programming language embedded inside Python and made
available through the :mod:`re` module. Using this little language, you specify
the rules for the set of possible strings that you want to match; this set might
contain English sentences, or e-mail addresses, or TeX commands, or anything you
like.  You can then ask questions such as "Does this string match the pattern?",
or "Is there a match for the pattern anywhere in this string?".  You can also
use REs to modify a string or to split it apart in various ways.

Regular expression patterns are compiled into a series of bytecodes which are
then executed by a matching engine written in C.  For advanced use, it may be
necessary to pay careful attention to how the engine will execute a given RE,
and write the RE in a certain way in order to produce bytecode that runs faster.
Optimization isn't covered in this document, because it requires that you have a
good understanding of the matching engine's internals.

The regular expression language is relatively small and restricted, so not all
possible string processing tasks can be done using regular expressions.  There
are also tasks that *can* be done with regular expressions, but the expressions
turn out to be very complicated.  In these cases, you may be better off writing
Python code to do the processing; while Python code will be slower than an
elaborate regular expression, it will also probably be more understandable.


Simple Patterns
===============

We'll start by learning about the simplest possible regular expressions.  Since
regular expressions are used to operate on strings, we'll begin with the most
common task: matching characters.

For a detailed explanation of the computer science underlying regular
expressions (deterministic and non-deterministic finite automata), you can refer
to almost any textbook on writing compilers.


Matching Characters
-------------------

Most letters and characters will simply match themselves.  For example, the
regular expression ``test`` will match the string ``test`` exactly.  (You can
enable a case-insensitive mode that would let this RE match ``Test`` or ``TEST``
as well; more about this later.)

There are exceptions to this rule; some characters are special
:dfn:`metacharacters`, and don't match themselves.  Instead, they signal that
some out-of-the-ordinary thing should be matched, or they affect other portions
of the RE by repeating them or changing their meaning.  Much of this document is
devoted to discussing various metacharacters and what they do.

Here's a complete list of the metacharacters; their meanings will be discussed
in the rest of this HOWTO.

.. code-block:: none

   . ^ $ * + ? { } [ ] \ | ( )

The first metacharacters we'll look at are ``[`` and ``]``. They're used for
specifying a character class, which is a set of characters that you wish to
match.  Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a ``'-'``.  For
example, ``[abc]`` will match any of the characters ``a``, ``b``, or ``c``; this
is the same as ``[a-c]``, which uses a range to express the same set of
characters.  If you wanted to match only lowercase letters, your RE would be
``[a-z]``.

Metacharacters are not active inside classes.  For example, ``[akm$]`` will
match any of the characters ``'a'``, ``'k'``, ``'m'``, or ``'$'``; ``'$'`` is
usually a metacharacter, but inside a character class it's stripped of its
special nature.

You can match the characters not listed within the class by :dfn:`complementing`
the set.  This is indicated by including a ``'^'`` as the first character of the
class; ``'^'`` outside a character class will simply match the ``'^'``
character.  For example, ``[^5]`` will match any character except ``'5'``.

Perhaps the most important metacharacter is the backslash, ``\``.   As in Python
string literals, the backslash can be followed by various characters to signal
various special sequences.  It's also used to escape all the metacharacters so
you can still match them in patterns; for example, if you need to match a ``[``
or  ``\``, you can precede them with a backslash to remove their special
meaning: ``\[`` or ``\\``.

Some of the special sequences beginning with ``'\'`` represent predefined sets
of characters that are often useful, such as the set of digits, the set of
letters, or the set of anything that isn't whitespace.  The following predefined
special sequences are a subset of those available. The equivalent classes are
for byte string patterns. For a complete list of sequences and expanded class
definitions for Unicode string patterns, see the last part of
:ref:`Regular Expression Syntax <re-syntax>`.

``\d``
   Matches any decimal digit; this is equivalent to the class ``[0-9]``.

``\D``
   Matches any non-digit character; this is equivalent to the class ``[^0-9]``.

``\s``
   Matches any whitespace character; this is equivalent to the class ``[
   \t\n\r\f\v]``.

``\S``
   Matches any non-whitespace character; this is equivalent to the class ``[^
   \t\n\r\f\v]``.

``\w``
   Matches any alphanumeric character; this is equivalent to the class
   ``[a-zA-Z0-9_]``.

``\W``
   Matches any non-alphanumeric character; this is equivalent to the class
   ``[^a-zA-Z0-9_]``.

These sequences can be included inside a character class.  For example,
``[\s,.]`` is a character class that will match any whitespace character, or
``','`` or ``'.'``.

The final metacharacter in this section is ``.``.  It matches anything except a
newline character, and there's an alternate mode (``re.DOTALL``) where it will
match even a newline.  ``'.'`` is often used where you want to match "any
character".


Repeating Things
----------------

Being able to match varying sets of characters is the first thing regular
expressions can do that isn't already possible with the methods available on
strings.  However, if that was the only additional capability of regexes, they
wouldn't be much of an advance. Another capability is that you can specify that
portions of the RE must be repeated a certain number of times.

The first metacharacter for repeating things that we'll look at is ``*``.  ``*``
doesn't match the literal character ``*``; instead, it specifies that the
previous character can be matched zero or more times, instead of exactly once.

For example, ``ca*t`` will match ``ct`` (0 ``a`` characters), ``cat`` (1 ``a``),
``caaat`` (3 ``a`` characters), and so forth.  The RE engine has various
internal limitations stemming from the size of C's ``int`` type that will
prevent it from matching over 2 billion ``a`` characters; you probably don't
have enough memory to construct a string that large, so you shouldn't run into
that limit.

Repetitions such as ``*`` are :dfn:`greedy`; when repeating a RE, the matching
engine will try to repeat it as many times as possible. If later portions of the
pattern don't match, the matching engine will then back up and try again with
fewer repetitions.

A step-by-step example will make this more obvious.  Let's consider the
expression ``a[bcd]*b``.  This matches the letter ``'a'``, zero or more letters
from the class ``[bcd]``, and finally ends with a ``'b'``.  Now imagine matching
this RE against the string ``abcbd``.

+------+-----------+---------------------------------+
| Step | Matched   | Explanation                     |
+======+===========+=================================+
| 1    | ``a``     | The ``a`` in the RE matches.    |
+------+-----------+---------------------------------+
| 2    | ``abcbd`` | The engine matches ``[bcd]*``,  |
|      |           | going as far as it can, which   |
|      |           | is to the end of the string.    |
+------+-----------+---------------------------------+
| 3    | *Failure* | The engine tries to match       |
|      |           | ``b``, but the current position |
|      |           | is at the end of the string, so |
|      |           | it fails.                       |
+------+-----------+---------------------------------+
| 4    | ``abcb``  | Back up, so that  ``[bcd]*``    |
|      |           | matches one less character.     |
+------+-----------+---------------------------------+
| 5    | *Failure* | Try ``b`` again, but the        |
|      |           | current position is at the last |
|      |           | character, which is a ``'d'``.  |
+------+-----------+---------------------------------+
| 6    | ``abc``   | Back up again, so that          |
|      |           | ``[bcd]*`` is only matching     |
|      |           | ``bc``.                         |
+------+-----------+---------------------------------+
| 6    | ``abcb``  | Try ``b`` again.  This time     |
|      |           | the character at the            |
|      |           | current position is ``'b'``, so |
|      |           | it succeeds.                    |
+------+-----------+---------------------------------+

The end of the RE has now been reached, and it has matched ``abcb``.  This
demonstrates how the matching engine goes as far as it can at first, and if no
match is found it will then progressively back up and retry the rest of the RE
again and again.  It will back up until it has tried zero matches for
``[bcd]*``, and if that subsequently fails, the engine will conclude that the
string doesn't match the RE at all.

Another repeating metacharacter is ``+``, which matches one or more times.  Pay
careful attention to the difference between ``*`` and ``+``; ``*`` matches
*zero* or more times, so whatever's being repeated may not be present at all,
while ``+`` requires at least *one* occurrence.  To use a similar example,
``ca+t`` will match ``cat`` (1 ``a``), ``caaat`` (3 ``a``'s), but won't match
``ct``.

There are two more repeating qualifiers.  The question mark character, ``?``,
matches either once or zero times; you can think of it as marking something as
being optional.  For example, ``home-?brew`` matches either ``homebrew`` or
``home-brew``.

The most complicated repeated qualifier is ``{m,n}``, where *m* and *n* are
decimal integers.  This qualifier means there must be at least *m* repetitions,
and at most *n*.  For example, ``a/{1,3}b`` will match ``a/b``, ``a//b``, and
``a///b``.  It won't match ``ab``, which has no slashes, or ``a////b``, which
has four.

You can omit either *m* or *n*; in that case, a reasonable value is assumed for
the missing value.  Omitting *m* is interpreted as a lower limit of 0, while
omitting *n* results in an upper bound of infinity --- actually, the upper bound
is the 2-billion limit mentioned earlier, but that might as well be infinity.

Readers of a reductionist bent may notice that the three other qualifiers can
all be expressed using this notation.  ``{0,}`` is the same as ``*``, ``{1,}``
is equivalent to ``+``, and ``{0,1}`` is the same as ``?``.  It's better to use
``*``, ``+``, or ``?`` when you can, simply because they're shorter and easier
to read.


Using Regular Expressions
=========================

Now that we've looked at some simple regular expressions, how do we actually use
them in Python?  The :mod:`re` module provides an interface to the regular
expression engine, allowing you to compile REs into objects and then perform
matches with them.


Compiling Regular Expressions
-----------------------------

Regular expressions are compiled into pattern objects, which have
methods for various operations such as searching for pattern matches or
performing string substitutions. ::

   >>> import re
   >>> p = re.compile('ab*')
   >>> p  #doctest: +ELLIPSIS
   <_sre.SRE_Pattern object at 0x...>

:func:`re.compile` also accepts an optional *flags* argument, used to enable
various special features and syntax variations.  We'll go over the available
settings later, but for now a single example will do::

   >>> p = re.compile('ab*', re.IGNORECASE)

The RE is passed to :func:`re.compile` as a string.  REs are handled as strings
because regular expressions aren't part of the core Python language, and no
special syntax was created for expressing them.  (There are applications that
don't need REs at all, so there's no need to bloat the language specification by
including them.) Instead, the :mod:`re` module is simply a C extension module
included with Python, just like the :mod:`socket` or :mod:`zlib` modules.

Putting REs in strings keeps the Python language simpler, but has one
disadvantage which is the topic of the next section.


The Backslash Plague
--------------------

As stated earlier, regular expressions use the backslash character (``'\'``) to
indicate special forms or to allow special characters to be used without
invoking their special meaning. This conflicts with Python's usage of the same
character for the same purpose in string literals.

Let's say you want to write a RE that matches the string ``\section``, which
might be found in a LaTeX file.  To figure out what to write in the program
code, start with the desired string to be matched.  Next, you must escape any
backslashes and other metacharacters by preceding them with a backslash,
resulting in the string ``\\section``.  The resulting string that must be passed
to :func:`re.compile` must be ``\\section``.  However, to express this as a
Python string literal, both backslashes must be escaped *again*.

+-------------------+------------------------------------------+
| Characters        | Stage                                    |
+===================+==========================================+
| ``\section``      | Text string to be matched                |
+-------------------+------------------------------------------+
| ``\\section``     | Escaped backslash for :func:`re.compile` |
+-------------------+------------------------------------------+
| ``"\\\\section"`` | Escaped backslashes for a string literal |
+-------------------+------------------------------------------+

In short, to match a literal backslash, one has to write ``'\\\\'`` as the RE
string, because the regular expression must be ``\\``, and each backslash must
be expressed as ``\\`` inside a regular Python string literal.  In REs that
feature backslashes repeatedly, this leads to lots of repeated backslashes and
makes the resulting strings difficult to understand.

The solution is to use Python's raw string notation for regular expressions;
backslashes are not handled in any special way in a string literal prefixed with
``'r'``, so ``r"\n"`` is a two-character string containing ``'\'`` and ``'n'``,
while ``"\n"`` is a one-character string containing a newline. Regular
expressions will often be written in Python code using this raw string notation.

+-------------------+------------------+
| Regular String    | Raw string       |
+===================+==================+
| ``"ab*"``         | ``r"ab*"``       |
+-------------------+------------------+
| ``"\\\\section"`` | ``r"\\section"`` |
+-------------------+------------------+
| ``"\\w+\\s+\\1"`` | ``r"\w+\s+\1"``  |
+-------------------+------------------+


Performing Matches
------------------

Once you have an object representing a compiled regular expression, what do you
do with it?  Pattern objects have several methods and attributes.
Only the most significant ones will be covered here; consult the :mod:`re` docs
for a complete listing.

+------------------+-----------------------------------------------+
| Method/Attribute | Purpose                                       |
+==================+===============================================+
| ``match()``      | Determine if the RE matches at the beginning  |
|                  | of the string.                                |
+------------------+-----------------------------------------------+
| ``search()``     | Scan through a string, looking for any        |
|                  | location where this RE matches.               |
+------------------+-----------------------------------------------+
| ``findall()``    | Find all substrings where the RE matches, and |
|                  | returns them as a list.                       |
+------------------+-----------------------------------------------+
| ``finditer()``   | Find all substrings where the RE matches, and |
|                  | returns them as an :term:`iterator`.          |
+------------------+-----------------------------------------------+

:meth:`match` and :meth:`search` return ``None`` if no match can be found.  If
they're successful, a :ref:`match object <match-objects>` instance is returned,
containing information about the match: where it starts and ends, the substring
it matched, and more.

You can learn about this by interactively experimenting with the :mod:`re`
module.  If you have Tkinter available, you may also want to look at
:source:`Tools/scripts/redemo.py`, a demonstration program included with the
Python distribution.  It allows you to enter REs and strings, and displays
whether the RE matches or fails. :file:`redemo.py` can be quite useful when
trying to debug a complicated RE.  Phil Schwartz's `Kodos
<http://kodos.sourceforge.net/>`_ is also an interactive tool for developing and
testing RE patterns.

This HOWTO uses the standard Python interpreter for its examples. First, run the
Python interpreter, import the :mod:`re` module, and compile a RE::

   Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
   >>> import re
   >>> p = re.compile('[a-z]+')
   >>> p  #doctest: +ELLIPSIS
   <_sre.SRE_Pattern object at 0x...>

Now, you can try matching various strings against the RE ``[a-z]+``.  An empty
string shouldn't match at all, since ``+`` means 'one or more repetitions'.
:meth:`match` should return ``None`` in this case, which will cause the
interpreter to print no output.  You can explicitly print the result of
:meth:`match` to make this clear. ::

   >>> p.match("")
   >>> print p.match("")
   None

Now, let's try it on a string that it should match, such as ``tempo``.  In this
case, :meth:`match` will return a :ref:`match object <match-objects>`, so you
should store the result in a variable for later use. ::

   >>> m = p.match('tempo')
   >>> m  #doctest: +ELLIPSIS
   <_sre.SRE_Match object at 0x...>

Now you can query the :ref:`match object <match-objects>` for information
about the matching string.  :ref:`match object <match-objects>` instances
also have several methods and attributes; the most important ones are:

+------------------+--------------------------------------------+
| Method/Attribute | Purpose                                    |
+==================+============================================+
| ``group()``      | Return the string matched by the RE        |
+------------------+--------------------------------------------+
| ``start()``      | Return the starting position of the match  |
+------------------+--------------------------------------------+
| ``end()``        | Return the ending position of the match    |
+------------------+--------------------------------------------+
| ``span()``       | Return a tuple containing the (start, end) |
|                  | positions  of the match                    |
+------------------+--------------------------------------------+

Trying these methods will soon clarify their meaning::

   >>> m.group()
   'tempo'
   >>> m.start(), m.end()
   (0, 5)
   >>> m.span()
   (0, 5)

:meth:`group` returns the substring that was matched by the RE.  :meth:`start`
and :meth:`end` return the starting and ending index of the match. :meth:`span`
returns both start and end indexes in a single tuple.  Since the :meth:`match`
method only checks if the RE matches at the start of a string, :meth:`start`
will always be zero.  However, the :meth:`search` method of patterns
scans through the string, so  the match may not start at zero in that
case. ::

   >>> print p.match('::: message')
   None
   >>> m = p.search('::: message'); print m  #doctest: +ELLIPSIS
   <_sre.SRE_Match object at 0x...>
   >>> m.group()
   'message'
   >>> m.span()
   (4, 11)

In actual programs, the most common style is to store the
:ref:`match object <match-objects>` in a variable, and then check if it was
``None``.  This usually looks like::

   p = re.compile( ... )
   m = p.match( 'string goes here' )
   if m:
       print 'Match found: ', m.group()
   else:
       print 'No match'

Two pattern methods return all of the matches for a pattern.
:meth:`findall` returns a list of matching strings::

   >>> p = re.compile('\d+')
   >>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
   ['12', '11', '10']

:meth:`findall` has to create the entire list before it can be returned as the
result.  The :meth:`finditer` method returns a sequence of
:ref:`match object <match-objects>` instances as an :term:`iterator`. [#]_ ::

   >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
   >>> iterator  #doctest: +ELLIPSIS
   <callable-iterator object at 0x...>
   >>> for match in iterator:
   ...     print match.span()
   ...
   (0, 2)
   (22, 24)
   (29, 31)


Module-Level Functions
----------------------

You don't have to create a pattern object and call its methods; the
:mod:`re` module also provides top-level functions called :func:`match`,
:func:`search`, :func:`findall`, :func:`sub`, and so forth.  These functions
take the same arguments as the corresponding pattern method, with
the RE string added as the first argument, and still return either ``None`` or a
:ref:`match object <match-objects>` instance. ::

   >>> print re.match(r'From\s+', 'Fromage amk')
   None
   >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')  #doctest: +ELLIPSIS
   <_sre.SRE_Match object at 0x...>

Under the hood, these functions simply create a pattern object for you
and call the appropriate method on it.  They also store the compiled object in a
cache, so future calls using the same RE are faster.

Should you use these module-level functions, or should you get the
pattern and call its methods yourself?  That choice depends on how
frequently the RE will be used, and on your personal coding style.  If the RE is
being used at only one point in the code, then the module functions are probably
more convenient.  If a program contains a lot of regular expressions, or re-uses
the same ones in several locations, then it might be worthwhile to collect all
the definitions in one place, in a section of code that compiles all the REs
ahead of time.  To take an example from the standard library, here's an extract
from the deprecated :mod:`xmllib` module::

   ref = re.compile( ... )
   entityref = re.compile( ... )
   charref = re.compile( ... )
   starttagopen = re.compile( ... )

I generally prefer to work with the compiled object, even for one-time uses, but
few people will be as much of a purist about this as I am.


Compilation Flags
-----------------

Compilation flags let you modify some aspects of how regular expressions work.
Flags are available in the :mod:`re` module under two names, a long name such as
:const:`IGNORECASE` and a short, one-letter form such as :const:`I`.  (If you're
familiar with Perl's pattern modifiers, the one-letter forms use the same
letters; the short form of :const:`re.VERBOSE` is :const:`re.X`, for example.)
Multiple flags can be specified by bitwise OR-ing them; ``re.I | re.M`` sets
both the :const:`I` and :const:`M` flags, for example.

Here's a table of the available flags, followed by a more detailed explanation
of each one.

+---------------------------------+--------------------------------------------+
| Flag                            | Meaning                                    |
+=================================+============================================+
| :const:`DOTALL`, :const:`S`     | Make ``.`` match any character, including  |
|                                 | newlines                                   |
+---------------------------------+--------------------------------------------+
| :const:`IGNORECASE`, :const:`I` | Do case-insensitive matches                |
+---------------------------------+--------------------------------------------+
| :const:`LOCALE`, :const:`L`     | Do a locale-aware match                    |
+---------------------------------+--------------------------------------------+
| :const:`MULTILINE`, :const:`M`  | Multi-line matching, affecting ``^`` and   |
|                                 | ``$``                                      |
+---------------------------------+--------------------------------------------+
| :const:`VERBOSE`, :const:`X`    | Enable verbose REs, which can be organized |
|                                 | more cleanly and understandably.           |
+---------------------------------+--------------------------------------------+
| :const:`UNICODE`, :const:`U`    | Makes several escapes like ``\w``, ``\b``, |
|                                 | ``\s`` and ``\d`` dependent on the Unicode |
|                                 | character database.                        |
+---------------------------------+--------------------------------------------+


.. data:: I
          IGNORECASE
   :noindex:

   Perform case-insensitive matching; character class and literal strings will
   match letters by ignoring case.  For example, ``[A-Z]`` will match lowercase
   letters, too, and ``Spam`` will match ``Spam``, ``spam``, or ``spAM``. This
   lowercasing doesn't take the current locale into account; it will if you also
   set the :const:`LOCALE` flag.


.. data:: L
          LOCALE
   :noindex:

   Make ``\w``, ``\W``, ``\b``, and ``\B``, dependent on the current locale.

   Locales are a feature of the C library intended to help in writing programs that
   take account of language differences.  For example, if you're processing French
   text, you'd want to be able to write ``\w+`` to match words, but ``\w`` only
   matches the character class ``[A-Za-z]``; it won't match ``'é'`` or ``'ç'``.  If
   your system is configured properly and a French locale is selected, certain C
   functions will tell the program that ``'é'`` should also be considered a letter.
   Setting the :const:`LOCALE` flag when compiling a regular expression will cause
   the resulting compiled object to use these C functions for ``\w``; this is
   slower, but also enables ``\w+`` to match French words as you'd expect.


.. data:: M
          MULTILINE
   :noindex:

   (``^`` and ``$`` haven't been explained yet;  they'll be introduced in section
   :ref:`more-metacharacters`.)

   Usually ``^`` matches only at the beginning of the string, and ``$`` matches
   only at the end of the string and immediately before the newline (if any) at the
   end of the string. When this flag is specified, ``^`` matches at the beginning
   of the string and at the beginning of each line within the string, immediately
   following each newline.  Similarly, the ``$`` metacharacter matches either at
   the end of the string and at the end of each line (immediately preceding each
   newline).


.. data:: S
          DOTALL
   :noindex:

   Makes the ``'.'`` special character match any character at all, including a
   newline; without this flag, ``'.'`` will match anything *except* a newline.


.. data:: U
          UNICODE
   :noindex:

   Make ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S``
   dependent on the Unicode character properties database.


.. data:: X
          VERBOSE
   :noindex:

   This flag allows you to write regular expressions that are more readable by
   granting you more flexibility in how you can format them.  When this flag has
   been specified, whitespace within the RE string is ignored, except when the
   whitespace is in a character class or preceded by an unescaped backslash; this
   lets you organize and indent the RE more clearly.  This flag also lets you put
   comments within a RE that will be ignored by the engine; comments are marked by
   a ``'#'`` that's neither in a character class or preceded by an unescaped
   backslash.

   For example, here's a RE that uses :const:`re.VERBOSE`; see how much easier it
   is to read? ::

      charref = re.compile(r"""
       &[#]                # Start of a numeric entity reference
       (
           0[0-7]+         # Octal form
         | [0-9]+          # Decimal form
         | x[0-9a-fA-F]+   # Hexadecimal form
       )
       ;                   # Trailing semicolon
      """, re.VERBOSE)

   Without the verbose setting, the RE would look like this::

      charref = re.compile("&#(0[0-7]+"
                           "|[0-9]+"
                           "|x[0-9a-fA-F]+);")

   In the above example, Python's automatic concatenation of string literals has
   been used to break up the RE into smaller pieces, but it's still more difficult
   to understand than the version using :const:`re.VERBOSE`.


More Pattern Power
==================

So far we've only covered a part of the features of regular expressions.  In
this section, we'll cover some new metacharacters, and how to use groups to
retrieve portions of the text that was matched.


.. _more-metacharacters:

More Metacharacters
-------------------

There are some metacharacters that we haven't covered yet.  Most of them will be
covered in this section.

Some of the remaining metacharacters to be discussed are :dfn:`zero-width
assertions`.  They don't cause the engine to advance through the string;
instead, they consume no characters at all, and simply succeed or fail.  For
example, ``\b`` is an assertion that the current position is located at a word
boundary; the position isn't changed by the ``\b`` at all.  This means that
zero-width assertions should never be repeated, because if they match once at a
given location, they can obviously be matched an infinite number of times.

``|``
   Alternation, or the "or" operator.   If A and B are regular expressions,
   ``A|B`` will match any string that matches either ``A`` or ``B``. ``|`` has very
   low precedence in order to make it work reasonably when you're alternating
   multi-character strings. ``Crow|Servo`` will match either ``Crow`` or ``Servo``,
   not ``Cro``, a ``'w'`` or an ``'S'``, and ``ervo``.

   To match a literal ``'|'``, use ``\|``, or enclose it inside a character class,
   as in ``[|]``.

``^``
   Matches at the beginning of lines.  Unless the :const:`MULTILINE` flag has been
   set, this will only match at the beginning of the string.  In :const:`MULTILINE`
   mode, this also matches immediately after each newline within the string.

   For example, if you wish to match the word ``From`` only at the beginning of a
   line, the RE to use is ``^From``. ::

      >>> print re.search('^From', 'From Here to Eternity')  #doctest: +ELLIPSIS
      <_sre.SRE_Match object at 0x...>
      >>> print re.search('^From', 'Reciting From Memory')
      None

   .. To match a literal \character{\^}, use \regexp{\e\^} or enclose it
   .. inside a character class, as in \regexp{[{\e}\^]}.

``$``
   Matches at the end of a line, which is defined as either the end of the string,
   or any location followed by a newline character.     ::

      >>> print re.search('}$', '{block}')  #doctest: +ELLIPSIS
      <_sre.SRE_Match object at 0x...>
      >>> print re.search('}$', '{block} ')
      None
      >>> print re.search('}$', '{block}\n')  #doctest: +ELLIPSIS
      <_sre.SRE_Match object at 0x...>

   To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
   as in  ``[$]``.

``\A``
   Matches only at the start of the string.  When not in :const:`MULTILINE` mode,
   ``\A`` and ``^`` are effectively the same.  In :const:`MULTILINE` mode, they're
   different: ``\A`` still matches only at the beginning of the string, but ``^``
   may match at any location inside the string that follows a newline character.

``\Z``
   Matches only at the end of the string.

``\b``
   Word boundary.  This is a zero-width assertion that matches only at the
   beginning or end of a word.  A word is defined as a sequence of alphanumeric
   characters, so the end of a word is indicated by whitespace or a
   non-alphanumeric character.

   The following example matches ``class`` only when it's a complete word; it won't
   match when it's contained inside another word. ::

      >>> p = re.compile(r'\bclass\b')
      >>> print p.search('no class at all')  #doctest: +ELLIPSIS
      <_sre.SRE_Match object at 0x...>
      >>> print p.search('the declassified algorithm')
      None
      >>> print p.search('one subclass is')
      None

   There are two subtleties you should remember when using this special sequence.
   First, this is the worst collision between Python's string literals and regular
   expression sequences.  In Python's string literals, ``\b`` is the backspace
   character, ASCII value 8.  If you're not using raw strings, then Python will
   convert the ``\b`` to a backspace, and your RE won't match as you expect it to.
   The following example looks the same as our previous RE, but omits the ``'r'``
   in front of the RE string. ::

      >>> p = re.compile('\bclass\b')
      >>> print p.search('no class at all')
      None
      >>> print p.search('\b' + 'class' + '\b')  #doctest: +ELLIPSIS
      <_sre.SRE_Match object at 0x...>

   Second, inside a character class, where there's no use for this assertion,
   ``\b`` represents the backspace character, for compatibility with Python's
   string literals.

``\B``
   Another zero-width assertion, this is the opposite of ``\b``, only matching when
   the current position is not at a word boundary.


Grouping
--------

Frequently you need to obtain more information than just whether the RE matched
or not.  Regular expressions are often used to dissect strings by writing a RE
divided into several subgroups which match different components of interest.
For example, an RFC-822 header line is divided into a header name and a value,
separated by a ``':'``, like this::

   From: author@example.com
   User-Agent: Thunderbird 1.5.0.9 (X11/20061227)
   MIME-Version: 1.0
   To: editor@example.com

This can be handled by writing a regular expression which matches an entire
header line, and has one group which matches the header name, and another group
which matches the header's value.

Groups are marked by the ``'('``, ``')'`` metacharacters. ``'('`` and ``')'``
have much the same meaning as they do in mathematical expressions; they group
together the expressions contained inside them, and you can repeat the contents
of a group with a repeating qualifier, such as ``*``, ``+``, ``?``, or
``{m,n}``.  For example, ``(ab)*`` will match zero or more repetitions of
``ab``. ::

   >>> p = re.compile('(ab)*')
   >>> print p.match('ababababab').span()
   (0, 10)

Groups indicated with ``'('``, ``')'`` also capture the starting and ending
index of the text that they match; this can be retrieved by passing an argument
to :meth:`group`, :meth:`start`, :meth:`end`, and :meth:`span`.  Groups are
numbered starting with 0.  Group 0 is always present; it's the whole RE, so
:ref:`match object <match-objects>` methods all have group 0 as their default
argument.  Later we'll see how to express groups that don't capture the span
of text that they match. ::

   >>> p = re.compile('(a)b')
   >>> m = p.match('ab')
   >>> m.group()
   'ab'
   >>> m.group(0)
   'ab'

Subgroups are numbered from left to right, from 1 upward.  Groups can be nested;
to determine the number, just count the opening parenthesis characters, going
from left to right. ::

   >>> p = re.compile('(a(b)c)d')
   >>> m = p.match('abcd')
   >>> m.group(0)
   'abcd'
   >>> m.group(1)
   'abc'
   >>> m.group(2)
   'b'

:meth:`group` can be passed multiple group numbers at a time, in which case it
will return a tuple containing the corresponding values for those groups. ::

   >>> m.group(2,1,2)
   ('b', 'abc', 'b')

The :meth:`groups` method returns a tuple containing the strings for all the
subgroups, from 1 up to however many there are. ::

   >>> m.groups()
   ('abc', 'b')

Backreferences in a pattern allow you to specify that the contents of an earlier
capturing group must also be found at the current location in the string.  For
example, ``\1`` will succeed if the exact contents of group 1 can be found at
the current position, and fails otherwise.  Remember that Python's string
literals also use a backslash followed by numbers to allow including arbitrary
characters in a string, so be sure to use a raw string when incorporating
backreferences in a RE.

For example, the following RE detects doubled words in a string. ::

   >>> p = re.compile(r'\b(\w+)\s+\1\b')
   >>> p.search('Paris in the the spring').group()
   'the the'

Backreferences like this aren't often useful for just searching through a string
--- there are few text formats which repeat data in this way --- but you'll soon
find out that they're *very* useful when performing string substitutions.


Non-capturing and Named Groups
------------------------------

Elaborate REs may use many groups, both to capture substrings of interest, and
to group and structure the RE itself.  In complex REs, it becomes difficult to
keep track of the group numbers.  There are two features which help with this
problem.  Both of them use a common syntax for regular expression extensions, so
we'll look at that first.

Perl 5 added several additional features to standard regular expressions, and
the Python :mod:`re` module supports most of them.   It would have been
difficult to choose new single-keystroke metacharacters or new special sequences
beginning with ``\`` to represent the new features without making Perl's regular
expressions confusingly different from standard REs.  If you chose ``&`` as a
new metacharacter, for example, old expressions would be assuming that ``&`` was
a regular character and wouldn't have escaped it by writing ``\&`` or ``[&]``.

The solution chosen by the Perl developers was to use ``(?...)`` as the
extension syntax.  ``?`` immediately after a parenthesis was a syntax error
because the ``?`` would have nothing to repeat, so this didn't introduce any
compatibility problems.  The characters immediately after the ``?``  indicate
what extension is being used, so ``(?=foo)`` is one thing (a positive lookahead
assertion) and ``(?:foo)`` is something else (a non-capturing group containing
the subexpression ``foo``).

Python adds an extension syntax to Perl's extension syntax.  If the first
character after the question mark is a ``P``, you know that it's an extension
that's specific to Python.  Currently there are two such extensions:
``(?P<name>...)`` defines a named group, and ``(?P=name)`` is a backreference to
a named group.  If future versions of Perl 5 add similar features using a
different syntax, the :mod:`re` module will be changed to support the new
syntax, while preserving the Python-specific syntax for compatibility's sake.

Now that we've looked at the general extension syntax, we can return to the
features that simplify working with groups in complex REs. Since groups are
numbered from left to right and a complex expression may use many groups, it can
become difficult to keep track of the correct numbering.  Modifying such a
complex RE is annoying, too: insert a new group near the beginning and you
change the numbers of everything that follows it.

Sometimes you'll want to use a group to collect a part of a regular expression,
but aren't interested in retrieving the group's contents. You can make this fact
explicit by using a non-capturing group: ``(?:...)``, where you can replace the
``...`` with any other regular expression. ::

   >>> m = re.match("([abc])+", "abc")
   >>> m.groups()
   ('c',)
   >>> m = re.match("(?:[abc])+", "abc")
   >>> m.groups()
   ()

Except for the fact that you can't retrieve the contents of what the group
matched, a non-capturing group behaves exactly the same as a capturing group;
you can put anything inside it, repeat it with a repetition metacharacter such
as ``*``, and nest it within other groups (capturing or non-capturing).
``(?:...)`` is particularly useful when modifying an existing pattern, since you
can add new groups without changing how all the other groups are numbered.  It
should be mentioned that there's no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than the other.

A more significant feature is named groups: instead of referring to them by
numbers, groups can be referenced by a name.

The syntax for a named group is one of the Python-specific extensions:
``(?P<name>...)``.  *name* is, obviously, the name of the group.  Named groups
also behave exactly like capturing groups, and additionally associate a name
with a group.  The :ref:`match object <match-objects>` methods that deal with
capturing groups all accept either integers that refer to the group by number
or strings that contain the desired group's name.  Named groups are still
given numbers, so you can retrieve information about a group in two ways::

   >>> p = re.compile(r'(?P<word>\b\w+\b)')
   >>> m = p.search( '(((( Lots of punctuation )))' )
   >>> m.group('word')
   'Lots'
   >>> m.group(1)
   'Lots'

Named groups are handy because they let you use easily-remembered names, instead
of having to remember numbers.  Here's an example RE from the :mod:`imaplib`
module::

   InternalDate = re.compile(r'INTERNALDATE "'
           r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-'
           r'(?P<year>[0-9][0-9][0-9][0-9])'
           r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
           r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
           r'"')

It's obviously much easier to retrieve ``m.group('zonem')``, instead of having
to remember to retrieve group 9.

The syntax for backreferences in an expression such as ``(...)\1`` refers to the
number of the group.  There's naturally a variant that uses the group name
instead of the number. This is another Python extension: ``(?P=name)`` indicates
that the contents of the group called *name* should again be matched at the
current point.  The regular expression for finding doubled words,
``\b(\w+)\s+\1\b`` can also be written as ``\b(?P<word>\w+)\s+(?P=word)\b``::

   >>> p = re.compile(r'\b(?P<word>\w+)\s+(?P=word)\b')
   >>> p.search('Paris in the the spring').group()
   'the the'


Lookahead Assertions
--------------------

Another zero-width assertion is the lookahead assertion.  Lookahead assertions
are available in both positive and negative form, and  look like this:

``(?=...)``
   Positive lookahead assertion.  This succeeds if the contained regular
   expression, represented here by ``...``, successfully matches at the current
   location, and fails otherwise. But, once the contained expression has been
   tried, the matching engine doesn't advance at all; the rest of the pattern is
   tried right where the assertion started.

``(?!...)``
   Negative lookahead assertion.  This is the opposite of the positive assertion;
   it succeeds if the contained expression *doesn't* match at the current position
   in the string.

To make this concrete, let's look at a case where a lookahead is useful.
Consider a simple pattern to match a filename and split it apart into a base
name and an extension, separated by a ``.``.  For example, in ``news.rc``,
``news`` is the base name, and ``rc`` is the filename's extension.

The pattern to match this is quite simple:

``.*[.].*$``

Notice that the ``.`` needs to be treated specially because it's a
metacharacter; I've put it inside a character class.  Also notice the trailing
``$``; this is added to ensure that all the rest of the string must be included
in the extension.  This regular expression matches ``foo.bar`` and
``autoexec.bat`` and ``sendmail.cf`` and ``printers.conf``.

Now, consider complicating the problem a bit; what if you want to match
filenames where the extension is not ``bat``? Some incorrect attempts:

``.*[.][^b].*$``  The first attempt above tries to exclude ``bat`` by requiring
that the first character of the extension is not a ``b``.  This is wrong,
because the pattern also doesn't match ``foo.bar``.

``.*[.]([^b]..|.[^a].|..[^t])$``

The expression gets messier when you try to patch up the first solution by
requiring one of the following cases to match: the first character of the
extension isn't ``b``; the second character isn't ``a``; or the third character
isn't ``t``.  This accepts ``foo.bar`` and rejects ``autoexec.bat``, but it
requires a three-letter extension and won't accept a filename with a two-letter
extension such as ``sendmail.cf``.  We'll complicate the pattern again in an
effort to fix it.

``.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$``

In the third attempt, the second and third letters are all made optional in
order to allow matching extensions shorter than three characters, such as
``sendmail.cf``.

The pattern's getting really complicated now, which makes it hard to read and
understand.  Worse, if the problem changes and you want to exclude both ``bat``
and ``exe`` as extensions, the pattern would get even more complicated and
confusing.

A negative lookahead cuts through all this confusion:

``.*[.](?!bat$)[^.]*$``  The negative lookahead means: if the expression ``bat``
doesn't match at this point, try the rest of the pattern; if ``bat$`` does
match, the whole pattern will fail.  The trailing ``$`` is required to ensure
that something like ``sample.batch``, where the extension only starts with
``bat``, will be allowed.  The ``[^.]*`` makes sure that the pattern works
when there are multiple dots in the filename.

Excluding another filename extension is now easy; simply add it as an
alternative inside the assertion.  The following pattern excludes filenames that
end in either ``bat`` or ``exe``:

``.*[.](?!bat$|exe$)[^.]*$``


Modifying Strings
=================

Up to this point, we've simply performed searches against a static string.
Regular expressions are also commonly used to modify strings in various ways,
using the following pattern methods:

+------------------+-----------------------------------------------+
| Method/Attribute | Purpose                                       |
+==================+===============================================+
| ``split()``      | Split the string into a list, splitting it    |
|                  | wherever the RE matches                       |
+------------------+-----------------------------------------------+
| ``sub()``        | Find all substrings where the RE matches, and |
|                  | replace them with a different string          |
+------------------+-----------------------------------------------+
| ``subn()``       | Does the same thing as :meth:`sub`,  but      |
|                  | returns the new string and the number of      |
|                  | replacements                                  |
+------------------+-----------------------------------------------+


Splitting Strings
-----------------

The :meth:`split` method of a pattern splits a string apart
wherever the RE matches, returning a list of the pieces. It's similar to the
:meth:`split` method of strings but provides much more generality in the
delimiters that you can split by; :meth:`split` only supports splitting by
whitespace or by a fixed string.  As you'd expect, there's a module-level
:func:`re.split` function, too.


.. method:: .split(string [, maxsplit=0])
   :noindex:

   Split *string* by the matches of the regular expression.  If capturing
   parentheses are used in the RE, then their contents will also be returned as
   part of the resulting list.  If *maxsplit* is nonzero, at most *maxsplit* splits
   are performed.

You can limit the number of splits made, by passing a value for *maxsplit*.
When *maxsplit* is nonzero, at most *maxsplit* splits will be made, and the
remainder of the string is returned as the final element of the list.  In the
following example, the delimiter is any sequence of non-alphanumeric characters.
::

   >>> p = re.compile(r'\W+')
   >>> p.split('This is a test, short and sweet, of split().')
   ['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
   >>> p.split('This is a test, short and sweet, of split().', 3)
   ['This', 'is', 'a', 'test, short and sweet, of split().']

Sometimes you're not only interested in what the text between delimiters is, but
also need to know what the delimiter was.  If capturing parentheses are used in
the RE, then their values are also returned as part of the list.  Compare the
following calls::

   >>> p = re.compile(r'\W+')
   >>> p2 = re.compile(r'(\W+)')
   >>> p.split('This... is a test.')
   ['This', 'is', 'a', 'test', '']
   >>> p2.split('This... is a test.')
   ['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

The module-level function :func:`re.split` adds the RE to be used as the first
argument, but is otherwise the same.   ::

   >>> re.split('[\W]+', 'Words, words, words.')
   ['Words', 'words', 'words', '']
   >>> re.split('([\W]+)', 'Words, words, words.')
   ['Words', ', ', 'words', ', ', 'words', '.', '']
   >>> re.split('[\W]+', 'Words, words, words.', 1)
   ['Words', 'words, words.']


Search and Replace
------------------

Another common task is to find all the matches for a pattern, and replace them
with a different string.  The :meth:`sub` method takes a replacement value,
which can be either a string or a function, and the string to be processed.


.. method:: .sub(replacement, string[, count=0])
   :noindex:

   Returns the string obtained by replacing the leftmost non-overlapping
   occurrences of the RE in *string* by the replacement *replacement*.  If the
   pattern isn't found, *string* is returned unchanged.

   The optional argument *count* is the maximum number of pattern occurrences to be
   replaced; *count* must be a non-negative integer.  The default value of 0 means
   to replace all occurrences.

Here's a simple example of using the :meth:`sub` method.  It replaces colour
names with the word ``colour``::

   >>> p = re.compile('(blue|white|red)')
   >>> p.sub('colour', 'blue socks and red shoes')
   'colour socks and colour shoes'
   >>> p.sub('colour', 'blue socks and red shoes', count=1)
   'colour socks and red shoes'

The :meth:`subn` method does the same work, but returns a 2-tuple containing the
new string value and the number of replacements  that were performed::

   >>> p = re.compile('(blue|white|red)')
   >>> p.subn('colour', 'blue socks and red shoes')
   ('colour socks and colour shoes', 2)
   >>> p.subn('colour', 'no colours at all')
   ('no colours at all', 0)

Empty matches are replaced only when they're not adjacent to a previous match.
::

   >>> p = re.compile('x*')
   >>> p.sub('-', 'abxd')
   '-a-b-d-'

If *replacement* is a string, any backslash escapes in it are processed.  That
is, ``\n`` is converted to a single newline character, ``\r`` is converted to a
carriage return, and so forth. Unknown escapes such as ``\j`` are left alone.
Backreferences, such as ``\6``, are replaced with the substring matched by the
corresponding group in the RE.  This lets you incorporate portions of the
original text in the resulting replacement string.

This example matches the word ``section`` followed by a string enclosed in
``{``, ``}``, and changes ``section`` to ``subsection``::

   >>> p = re.compile('section{ ( [^}]* ) }', re.VERBOSE)
   >>> p.sub(r'subsection{\1}','section{First} section{second}')
   'subsection{First} subsection{second}'

There's also a syntax for referring to named groups as defined by the
``(?P<name>...)`` syntax.  ``\g<name>`` will use the substring matched by the
group named ``name``, and  ``\g<number>``  uses the corresponding group number.
``\g<2>`` is therefore equivalent to ``\2``,  but isn't ambiguous in a
replacement string such as ``\g<2>0``.  (``\20`` would be interpreted as a
reference to group 20, not a reference to group 2 followed by the literal
character ``'0'``.)  The following substitutions are all equivalent, but use all
three variations of the replacement string. ::

   >>> p = re.compile('section{ (?P<name> [^}]* ) }', re.VERBOSE)
   >>> p.sub(r'subsection{\1}','section{First}')
   'subsection{First}'
   >>> p.sub(r'subsection{\g<1>}','section{First}')
   'subsection{First}'
   >>> p.sub(r'subsection{\g<name>}','section{First}')
   'subsection{First}'

*replacement* can also be a function, which gives you even more control.  If
*replacement* is a function, the function is called for every non-overlapping
occurrence of *pattern*.  On each call, the function is passed a
:ref:`match object <match-objects>` argument for the match and can use this
information to compute the desired replacement string and return it.

In the following example, the replacement function translates decimals into
hexadecimal::

   >>> def hexrepl(match):
   ...     "Return the hex string for a decimal number"
   ...     value = int(match.group())
   ...     return hex(value)
   ...
   >>> p = re.compile(r'\d+')
   >>> p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
   'Call 0xffd2 for printing, 0xc000 for user code.'

When using the module-level :func:`re.sub` function, the pattern is passed as
the first argument.  The pattern may be provided as an object or as a string; if
you need to specify regular expression flags, you must either use a
pattern object as the first parameter, or use embedded modifiers in the
pattern string, e.g. ``sub("(?i)b+", "x", "bbbb BBBB")`` returns ``'x x'``.


Common Problems
===============

Regular expressions are a powerful tool for some applications, but in some ways
their behaviour isn't intuitive and at times they don't behave the way you may
expect them to.  This section will point out some of the most common pitfalls.


Use String Methods
------------------

Sometimes using the :mod:`re` module is a mistake.  If you're matching a fixed
string, or a single character class, and you're not using any :mod:`re` features
such as the :const:`IGNORECASE` flag, then the full power of regular expressions
may not be required. Strings have several methods for performing operations with
fixed strings and they're usually much faster, because the implementation is a
single small C loop that's been optimized for the purpose, instead of the large,
more generalized regular expression engine.

One example might be replacing a single fixed string with another one; for
example, you might replace ``word`` with ``deed``.  ``re.sub()`` seems like the
function to use for this, but consider the :meth:`replace` method.  Note that
:func:`replace` will also replace ``word`` inside words, turning ``swordfish``
into ``sdeedfish``, but the  naive RE ``word`` would have done that, too.  (To
avoid performing the substitution on parts of words, the pattern would have to
be ``\bword\b``, in order to require that ``word`` have a word boundary on
either side.  This takes the job beyond  :meth:`replace`'s abilities.)

Another common task is deleting every occurrence of a single character from a
string or replacing it with another single character.  You might do this with
something like ``re.sub('\n', ' ', S)``, but :meth:`translate` is capable of
doing both tasks and will be faster than any regular expression operation can
be.

In short, before turning to the :mod:`re` module, consider whether your problem
can be solved with a faster and simpler string method.


match() versus search()
-----------------------

The :func:`match` function only checks if the RE matches at the beginning of the
string while :func:`search` will scan forward through the string for a match.
It's important to keep this distinction in mind.  Remember,  :func:`match` will
only report a successful match which will start at 0; if the match wouldn't
start at zero,  :func:`match` will *not* report it. ::

   >>> print re.match('super', 'superstition').span()
   (0, 5)
   >>> print re.match('super', 'insuperable')
   None

On the other hand, :func:`search` will scan forward through the string,
reporting the first match it finds. ::

   >>> print re.search('super', 'superstition').span()
   (0, 5)
   >>> print re.search('super', 'insuperable').span()
   (2, 7)

Sometimes you'll be tempted to keep using :func:`re.match`, and just add ``.*``
to the front of your RE.  Resist this temptation and use :func:`re.search`
instead.  The regular expression compiler does some analysis of REs in order to
speed up the process of looking for a match.  One such analysis figures out what
the first character of a match must be; for example, a pattern starting with
``Crow`` must match starting with a ``'C'``.  The analysis lets the engine
quickly scan through the string looking for the starting character, only trying
the full match if a ``'C'`` is found.

Adding ``.*`` defeats this optimization, requiring scanning to the end of the
string and then backtracking to find a match for the rest of the RE.  Use
:func:`re.search` instead.


Greedy versus Non-Greedy
------------------------

When repeating a regular expression, as in ``a*``, the resulting action is to
consume as much of the pattern as possible.  This fact often bites you when
you're trying to match a pair of balanced delimiters, such as the angle brackets
surrounding an HTML tag.  The naive pattern for matching a single HTML tag
doesn't work because of the greedy nature of ``.*``. ::

   >>> s = '<html><head><title>Title</title>'
   >>> len(s)
   32
   >>> print re.match('<.*>', s).span()
   (0, 32)
   >>> print re.match('<.*>', s).group()
   <html><head><title>Title</title>

The RE matches the ``'<'`` in ``<html>``, and the ``.*`` consumes the rest of
the string.  There's still more left in the RE, though, and the ``>`` can't
match at the end of the string, so the regular expression engine has to
backtrack character by character until it finds a match for the ``>``.   The
final match extends from the ``'<'`` in ``<html>`` to the ``'>'`` in
``</title>``, which isn't what you want.

In this case, the solution is to use the non-greedy qualifiers ``*?``, ``+?``,
``??``, or ``{m,n}?``, which match as *little* text as possible.  In the above
example, the ``'>'`` is tried immediately after the first ``'<'`` matches, and
when it fails, the engine advances a character at a time, retrying the ``'>'``
at every step.  This produces just the right result::

   >>> print re.match('<.*?>', s).group()
   <html>

(Note that parsing HTML or XML with regular expressions is painful.
Quick-and-dirty patterns will handle common cases, but HTML and XML have special
cases that will break the obvious regular expression; by the time you've written
a regular expression that handles all of the possible cases, the patterns will
be *very* complicated.  Use an HTML or XML parser module for such tasks.)


Using re.VERBOSE
--------------------

By now you've probably noticed that regular expressions are a very compact
notation, but they're not terribly readable.  REs of moderate complexity can
become lengthy collections of backslashes, parentheses, and metacharacters,
making them difficult to read and understand.

For such REs, specifying the ``re.VERBOSE`` flag when compiling the regular
expression can be helpful, because it allows you to format the regular
expression more clearly.

The ``re.VERBOSE`` flag has several effects.  Whitespace in the regular
expression that *isn't* inside a character class is ignored.  This means that an
expression such as ``dog | cat`` is equivalent to the less readable ``dog|cat``,
but ``[a b]`` will still match the characters ``'a'``, ``'b'``, or a space.  In
addition, you can also put comments inside a RE; comments extend from a ``#``
character to the next newline.  When used with triple-quoted strings, this
enables REs to be formatted more neatly::

   pat = re.compile(r"""
    \s*                 # Skip leading whitespace
    (?P<header>[^:]+)   # Header name
    \s* :               # Whitespace, and a colon
    (?P<value>.*?)      # The header's value -- *? used to
                        # lose the following trailing whitespace
    \s*$                # Trailing whitespace to end-of-line
   """, re.VERBOSE)

This is far more readable than::

   pat = re.compile(r"\s*(?P<header>[^:]+)\s*:(?P<value>.*?)\s*$")


Feedback
========

Regular expressions are a complicated topic.  Did this document help you
understand them?  Were there parts that were unclear, or Problems you
encountered that weren't covered here?  If so, please send suggestions for
improvements to the author.

The most complete book on regular expressions is almost certainly Jeffrey
Friedl's Mastering Regular Expressions, published by O'Reilly.  Unfortunately,
it exclusively concentrates on Perl and Java's flavours of regular expressions,
and doesn't contain any Python material at all, so it won't be useful as a
reference for programming in Python.  (The first edition covered Python's
now-removed :mod:`regex` module, which won't help you much.)  Consider checking
it out from your library.


.. rubric:: Footnotes

.. [#] Introduced in Python 2.2.2.

PK	%�\��*��O�O#html/_sources/howto/sockets.rst.txtnu�[���.. _socket-howto:

****************************
  Socket Programming HOWTO
****************************

:Author: Gordon McMillan


.. topic:: Abstract

   Sockets are used nearly everywhere, but are one of the most severely
   misunderstood technologies around. This is a 10,000 foot overview of sockets.
   It's not really a tutorial - you'll still have work to do in getting things
   operational. It doesn't cover the fine points (and there are a lot of them), but
   I hope it will give you enough background to begin using them decently.


Sockets
=======

I'm only going to talk about INET sockets, but they account for at least 99% of
the sockets in use. And I'll only talk about STREAM sockets - unless you really
know what you're doing (in which case this HOWTO isn't for you!), you'll get
better behavior and performance from a STREAM socket than anything else. I will
try to clear up the mystery of what a socket is, as well as some hints on how to
work with blocking and non-blocking sockets. But I'll start by talking about
blocking sockets. You'll need to know how they work before dealing with
non-blocking sockets.

Part of the trouble with understanding these things is that "socket" can mean a
number of subtly different things, depending on context. So first, let's make a
distinction between a "client" socket - an endpoint of a conversation, and a
"server" socket, which is more like a switchboard operator. The client
application (your browser, for example) uses "client" sockets exclusively; the
web server it's talking to uses both "server" sockets and "client" sockets.


History
-------

Of the various forms of :abbr:`IPC (Inter Process Communication)`,
sockets are by far the most popular.  On any given platform, there are
likely to be other forms of IPC that are faster, but for
cross-platform communication, sockets are about the only game in town.

They were invented in Berkeley as part of the BSD flavor of Unix. They spread
like wildfire with the Internet. With good reason --- the combination of sockets
with INET makes talking to arbitrary machines around the world unbelievably easy
(at least compared to other schemes).


Creating a Socket
=================

Roughly speaking, when you clicked on the link that brought you to this page,
your browser did something like the following::

   #create an INET, STREAMing socket
   s = socket.socket(
       socket.AF_INET, socket.SOCK_STREAM)
   #now connect to the web server on port 80
   # - the normal http port
   s.connect(("www.mcmillan-inc.com", 80))

When the ``connect`` completes, the socket ``s`` can be used to send
in a request for the text of the page. The same socket will read the
reply, and then be destroyed. That's right, destroyed. Client sockets
are normally only used for one exchange (or a small set of sequential
exchanges).

What happens in the web server is a bit more complex. First, the web server
creates a "server socket"::

   #create an INET, STREAMing socket
   serversocket = socket.socket(
       socket.AF_INET, socket.SOCK_STREAM)
   #bind the socket to a public host,
   # and a well-known port
   serversocket.bind((socket.gethostname(), 80))
   #become a server socket
   serversocket.listen(5)

A couple things to notice: we used ``socket.gethostname()`` so that the socket
would be visible to the outside world.  If we had used ``s.bind(('localhost',
80))`` or ``s.bind(('127.0.0.1', 80))`` we would still have a "server" socket,
but one that was only visible within the same machine.  ``s.bind(('', 80))``
specifies that the socket is reachable by any address the machine happens to
have.

A second thing to note: low number ports are usually reserved for "well known"
services (HTTP, SNMP etc). If you're playing around, use a nice high number (4
digits).

Finally, the argument to ``listen`` tells the socket library that we want it to
queue up as many as 5 connect requests (the normal max) before refusing outside
connections. If the rest of the code is written properly, that should be plenty.

Now that we have a "server" socket, listening on port 80, we can enter the
mainloop of the web server::

   while 1:
       #accept connections from outside
       (clientsocket, address) = serversocket.accept()
       #now do something with the clientsocket
       #in this case, we'll pretend this is a threaded server
       ct = client_thread(clientsocket)
       ct.run()

There's actually 3 general ways in which this loop could work - dispatching a
thread to handle ``clientsocket``, create a new process to handle
``clientsocket``, or restructure this app to use non-blocking sockets, and
multiplex between our "server" socket and any active ``clientsocket``\ s using
``select``. More about that later. The important thing to understand now is
this: this is *all* a "server" socket does. It doesn't send any data. It doesn't
receive any data. It just produces "client" sockets. Each ``clientsocket`` is
created in response to some *other* "client" socket doing a ``connect()`` to the
host and port we're bound to. As soon as we've created that ``clientsocket``, we
go back to listening for more connections. The two "clients" are free to chat it
up - they are using some dynamically allocated port which will be recycled when
the conversation ends.


IPC
---

If you need fast IPC between two processes on one machine, you should look into
whatever form of shared memory the platform offers. A simple protocol based
around shared memory and locks or semaphores is by far the fastest technique.

If you do decide to use sockets, bind the "server" socket to ``'localhost'``. On
most platforms, this will take a shortcut around a couple of layers of network
code and be quite a bit faster.


Using a Socket
==============

The first thing to note, is that the web browser's "client" socket and the web
server's "client" socket are identical beasts. That is, this is a "peer to peer"
conversation. Or to put it another way, *as the designer, you will have to
decide what the rules of etiquette are for a conversation*. Normally, the
``connect``\ ing socket starts the conversation, by sending in a request, or
perhaps a signon. But that's a design decision - it's not a rule of sockets.

Now there are two sets of verbs to use for communication. You can use ``send``
and ``recv``, or you can transform your client socket into a file-like beast and
use ``read`` and ``write``. The latter is the way Java presents its sockets.
I'm not going to talk about it here, except to warn you that you need to use
``flush`` on sockets. These are buffered "files", and a common mistake is to
``write`` something, and then ``read`` for a reply. Without a ``flush`` in
there, you may wait forever for the reply, because the request may still be in
your output buffer.

Now we come to the major stumbling block of sockets - ``send`` and ``recv`` operate
on the network buffers. They do not necessarily handle all the bytes you hand
them (or expect from them), because their major focus is handling the network
buffers. In general, they return when the associated network buffers have been
filled (``send``) or emptied (``recv``). They then tell you how many bytes they
handled. It is *your* responsibility to call them again until your message has
been completely dealt with.

When a ``recv`` returns 0 bytes, it means the other side has closed (or is in
the process of closing) the connection.  You will not receive any more data on
this connection. Ever.  You may be able to send data successfully; I'll talk
more about this later.

A protocol like HTTP uses a socket for only one transfer. The client sends a
request, then reads a reply.  That's it. The socket is discarded. This means that
a client can detect the end of the reply by receiving 0 bytes.

But if you plan to reuse your socket for further transfers, you need to realize
that *there is no* :abbr:`EOT (End of Transfer)` *on a socket.* I repeat: if a socket
``send`` or ``recv`` returns after handling 0 bytes, the connection has been
broken.  If the connection has *not* been broken, you may wait on a ``recv``
forever, because the socket will *not* tell you that there's nothing more to
read (for now).  Now if you think about that a bit, you'll come to realize a
fundamental truth of sockets: *messages must either be fixed length* (yuck), *or
be delimited* (shrug), *or indicate how long they are* (much better), *or end by
shutting down the connection*. The choice is entirely yours, (but some ways are
righter than others).

Assuming you don't want to end the connection, the simplest solution is a fixed
length message::

   class mysocket:
       '''demonstration class only
         - coded for clarity, not efficiency
       '''

       def __init__(self, sock=None):
           if sock is None:
               self.sock = socket.socket(
                   socket.AF_INET, socket.SOCK_STREAM)
           else:
               self.sock = sock

       def connect(self, host, port):
           self.sock.connect((host, port))

       def mysend(self, msg):
           totalsent = 0
           while totalsent < MSGLEN:
               sent = self.sock.send(msg[totalsent:])
               if sent == 0:
                   raise RuntimeError("socket connection broken")
               totalsent = totalsent + sent

       def myreceive(self):
           chunks = []
           bytes_recd = 0
           while bytes_recd < MSGLEN:
               chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
               if chunk == '':
                   raise RuntimeError("socket connection broken")
               chunks.append(chunk)
               bytes_recd = bytes_recd + len(chunk)
           return ''.join(chunks)

The sending code here is usable for almost any messaging scheme - in Python you
send strings, and you can use ``len()`` to determine its length (even if it has
embedded ``\0`` characters). It's mostly the receiving code that gets more
complex. (And in C, it's not much worse, except you can't use ``strlen`` if the
message has embedded ``\0``\ s.)

The easiest enhancement is to make the first character of the message an
indicator of message type, and have the type determine the length. Now you have
two ``recv``\ s - the first to get (at least) that first character so you can
look up the length, and the second in a loop to get the rest. If you decide to
go the delimited route, you'll be receiving in some arbitrary chunk size, (4096
or 8192 is frequently a good match for network buffer sizes), and scanning what
you've received for a delimiter.

One complication to be aware of: if your conversational protocol allows multiple
messages to be sent back to back (without some kind of reply), and you pass
``recv`` an arbitrary chunk size, you may end up reading the start of a
following message. You'll need to put that aside and hold onto it, until it's
needed.

Prefixing the message with its length (say, as 5 numeric characters) gets more
complex, because (believe it or not), you may not get all 5 characters in one
``recv``. In playing around, you'll get away with it; but in high network loads,
your code will very quickly break unless you use two ``recv`` loops - the first
to determine the length, the second to get the data part of the message. Nasty.
This is also when you'll discover that ``send`` does not always manage to get
rid of everything in one pass. And despite having read this, you will eventually
get bit by it!

In the interests of space, building your character, (and preserving my
competitive position), these enhancements are left as an exercise for the
reader. Lets move on to cleaning up.


Binary Data
-----------

It is perfectly possible to send binary data over a socket. The major problem is
that not all machines use the same formats for binary data. For example, a
Motorola chip will represent a 16 bit integer with the value 1 as the two hex
bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00.
Socket libraries have calls for converting 16 and 32 bit integers - ``ntohl,
htonl, ntohs, htons`` where "n" means *network* and "h" means *host*, "s" means
*short* and "l" means *long*. Where network order is host order, these do
nothing, but where the machine is byte-reversed, these swap the bytes around
appropriately.

In these days of 32 bit machines, the ascii representation of binary data is
frequently smaller than the binary representation. That's because a surprising
amount of the time, all those longs have the value 0, or maybe 1. The string "0"
would be two bytes, while binary is four. Of course, this doesn't fit well with
fixed-length messages. Decisions, decisions.


Disconnecting
=============

Strictly speaking, you're supposed to use ``shutdown`` on a socket before you
``close`` it.  The ``shutdown`` is an advisory to the socket at the other end.
Depending on the argument you pass it, it can mean "I'm not going to send
anymore, but I'll still listen", or "I'm not listening, good riddance!".  Most
socket libraries, however, are so used to programmers neglecting to use this
piece of etiquette that normally a ``close`` is the same as ``shutdown();
close()``.  So in most situations, an explicit ``shutdown`` is not needed.

One way to use ``shutdown`` effectively is in an HTTP-like exchange. The client
sends a request and then does a ``shutdown(1)``. This tells the server "This
client is done sending, but can still receive."  The server can detect "EOF" by
a receive of 0 bytes. It can assume it has the complete request.  The server
sends a reply. If the ``send`` completes successfully then, indeed, the client
was still receiving.

Python takes the automatic shutdown a step further, and says that when a socket
is garbage collected, it will automatically do a ``close`` if it's needed. But
relying on this is a very bad habit. If your socket just disappears without
doing a ``close``, the socket at the other end may hang indefinitely, thinking
you're just being slow. *Please* ``close`` your sockets when you're done.


When Sockets Die
----------------

Probably the worst thing about using blocking sockets is what happens when the
other side comes down hard (without doing a ``close``). Your socket is likely to
hang. SOCKSTREAM is a reliable protocol, and it will wait a long, long time
before giving up on a connection. If you're using threads, the entire thread is
essentially dead. There's not much you can do about it. As long as you aren't
doing something dumb, like holding a lock while doing a blocking read, the
thread isn't really consuming much in the way of resources. Do *not* try to kill
the thread - part of the reason that threads are more efficient than processes
is that they avoid the overhead associated with the automatic recycling of
resources. In other words, if you do manage to kill the thread, your whole
process is likely to be screwed up.


Non-blocking Sockets
====================

If you've understood the preceding, you already know most of what you need to
know about the mechanics of using sockets. You'll still use the same calls, in
much the same ways. It's just that, if you do it right, your app will be almost
inside-out.

In Python, you use ``socket.setblocking(0)`` to make it non-blocking. In C, it's
more complex, (for one thing, you'll need to choose between the BSD flavor
``O_NONBLOCK`` and the almost indistinguishable Posix flavor ``O_NDELAY``, which
is completely different from ``TCP_NODELAY``), but it's the exact same idea. You
do this after creating the socket, but before using it. (Actually, if you're
nuts, you can switch back and forth.)

The major mechanical difference is that ``send``, ``recv``, ``connect`` and
``accept`` can return without having done anything. You have (of course) a
number of choices. You can check return code and error codes and generally drive
yourself crazy. If you don't believe me, try it sometime. Your app will grow
large, buggy and suck CPU. So let's skip the brain-dead solutions and do it
right.

Use ``select``.

In C, coding ``select`` is fairly complex. In Python, it's a piece of cake, but
it's close enough to the C version that if you understand ``select`` in Python,
you'll have little trouble with it in C::

   ready_to_read, ready_to_write, in_error = \
                  select.select(
                     potential_readers,
                     potential_writers,
                     potential_errs,
                     timeout)

You pass ``select`` three lists: the first contains all sockets that you might
want to try reading; the second all the sockets you might want to try writing
to, and the last (normally left empty) those that you want to check for errors.
You should note that a socket can go into more than one list. The ``select``
call is blocking, but you can give it a timeout. This is generally a sensible
thing to do - give it a nice long timeout (say a minute) unless you have good
reason to do otherwise.

In return, you will get three lists. They contain the sockets that are actually
readable, writable and in error. Each of these lists is a subset (possibly
empty) of the corresponding list you passed in.

If a socket is in the output readable list, you can be
as-close-to-certain-as-we-ever-get-in-this-business that a ``recv`` on that
socket will return *something*. Same idea for the writable list. You'll be able
to send *something*. Maybe not all you want to, but *something* is better than
nothing.  (Actually, any reasonably healthy socket will return as writable - it
just means outbound network buffer space is available.)

If you have a "server" socket, put it in the potential_readers list. If it comes
out in the readable list, your ``accept`` will (almost certainly) work. If you
have created a new socket to ``connect`` to someone else, put it in the
potential_writers list. If it shows up in the writable list, you have a decent
chance that it has connected.

One very nasty problem with ``select``: if somewhere in those input lists of
sockets is one which has died a nasty death, the ``select`` will fail. You then
need to loop through every single damn socket in all those lists and do a
``select([sock],[],[],0)`` until you find the bad one. That timeout of 0 means
it won't take long, but it's ugly.

Actually, ``select`` can be handy even with blocking sockets. It's one way of
determining whether you will block - the socket returns as readable when there's
something in the buffers.  However, this still doesn't help with the problem of
determining whether the other end is done, or just busy with something else.

**Portability alert**: On Unix, ``select`` works both with the sockets and
files. Don't try this on Windows. On Windows, ``select`` works with sockets
only. Also note that in C, many of the more advanced socket options are done
differently on Windows. In fact, on Windows I usually use threads (which work
very, very well) with my sockets. Face it, if you want any kind of performance,
your code will look very different on Windows than on Unix.


Performance
-----------

There's no question that the fastest sockets code uses non-blocking sockets and
select to multiplex them. You can put together something that will saturate a
LAN connection without putting any strain on the CPU. The trouble is that an app
written this way can't do much of anything else - it needs to be ready to
shuffle bytes around at all times.

Assuming that your app is actually supposed to do something more than that,
threading is the optimal solution, (and using non-blocking sockets will be
faster than using blocking sockets). Unfortunately, threading support in Unixes
varies both in API and quality. So the normal Unix solution is to fork a
subprocess to deal with each connection. The overhead for this is significant
(and don't do this on Windows - the overhead of process creation is enormous
there). It also means that unless each subprocess is completely independent,
you'll need to use another form of IPC, say a pipe, or shared memory and
semaphores, to communicate between the parent and child processes.

Finally, remember that even though blocking sockets are somewhat slower than
non-blocking, in many cases they are the "right" solution. After all, if your
app is driven by the data it receives over a socket, there's not much sense in
complicating the logic just so your app can wait on ``select`` instead of
``recv``.

PK	%�\�X2020#html/_sources/howto/sorting.rst.txtnu�[���.. _sortinghowto:

Sorting HOW TO
**************

:Author: Andrew Dalke and Raymond Hettinger
:Release: 0.1


Python lists have a built-in :meth:`list.sort` method that modifies the list
in-place.  There is also a :func:`sorted` built-in function that builds a new
sorted list from an iterable.

In this document, we explore the various techniques for sorting data using Python.


Sorting Basics
==============

A simple ascending sort is very easy: just call the :func:`sorted` function. It
returns a new sorted list::

    >>> sorted([5, 2, 3, 1, 4])
    [1, 2, 3, 4, 5]

You can also use the :meth:`list.sort` method of a list. It modifies the list
in-place (and returns ``None`` to avoid confusion). Usually it's less convenient
than :func:`sorted` - but if you don't need the original list, it's slightly
more efficient.

    >>> a = [5, 2, 3, 1, 4]
    >>> a.sort()
    >>> a
    [1, 2, 3, 4, 5]

Another difference is that the :meth:`list.sort` method is only defined for
lists. In contrast, the :func:`sorted` function accepts any iterable.

    >>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
    [1, 2, 3, 4, 5]

Key Functions
=============

Starting with Python 2.4, both :meth:`list.sort` and :func:`sorted` added a
*key* parameter to specify a function to be called on each list element prior to
making comparisons.

For example, here's a case-insensitive string comparison:

    >>> sorted("This is a test string from Andrew".split(), key=str.lower)
    ['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

The value of the *key* parameter should be a function that takes a single argument
and returns a key to use for sorting purposes. This technique is fast because
the key function is called exactly once for each input record.

A common pattern is to sort complex objects using some of the object's indices
as keys. For example:

    >>> student_tuples = [
    ...     ('john', 'A', 15),
    ...     ('jane', 'B', 12),
    ...     ('dave', 'B', 10),
    ... ]
    >>> sorted(student_tuples, key=lambda student: student[2])   # sort by age
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The same technique works for objects with named attributes. For example:

    >>> class Student:
    ...     def __init__(self, name, grade, age):
    ...         self.name = name
    ...         self.grade = grade
    ...         self.age = age
    ...     def __repr__(self):
    ...         return repr((self.name, self.grade, self.age))

    >>> student_objects = [
    ...     Student('john', 'A', 15),
    ...     Student('jane', 'B', 12),
    ...     Student('dave', 'B', 10),
    ... ]
    >>> sorted(student_objects, key=lambda student: student.age)   # sort by age
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

Operator Module Functions
=========================

The key-function patterns shown above are very common, so Python provides
convenience functions to make accessor functions easier and faster. The operator
module has :func:`operator.itemgetter`, :func:`operator.attrgetter`, and
starting in Python 2.5 an :func:`operator.methodcaller` function.

Using those functions, the above examples become simpler and faster:

    >>> from operator import itemgetter, attrgetter

    >>> sorted(student_tuples, key=itemgetter(2))
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

    >>> sorted(student_objects, key=attrgetter('age'))
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The operator module functions allow multiple levels of sorting. For example, to
sort by *grade* then by *age*:

    >>> sorted(student_tuples, key=itemgetter(1,2))
    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

    >>> sorted(student_objects, key=attrgetter('grade', 'age'))
    [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

The :func:`operator.methodcaller` function makes method calls with fixed
parameters for each object being sorted.  For example, the :meth:`str.count`
method could be used to compute message priority by counting the
number of exclamation marks in a message:

    >>> from operator import methodcaller
    >>> messages = ['critical!!!', 'hurry!', 'standby', 'immediate!!']
    >>> sorted(messages, key=methodcaller('count', '!'))
    ['standby', 'hurry!', 'immediate!!', 'critical!!!']

Ascending and Descending
========================

Both :meth:`list.sort` and :func:`sorted` accept a *reverse* parameter with a
boolean value. This is used to flag descending sorts. For example, to get the
student data in reverse *age* order:

    >>> sorted(student_tuples, key=itemgetter(2), reverse=True)
    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

    >>> sorted(student_objects, key=attrgetter('age'), reverse=True)
    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

Sort Stability and Complex Sorts
================================

Starting with Python 2.2, sorts are guaranteed to be `stable
<https://en.wikipedia.org/wiki/Sorting_algorithm#Stability>`_\. That means that
when multiple records have the same key, their original order is preserved.

    >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
    >>> sorted(data, key=itemgetter(0))
    [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]

Notice how the two records for *blue* retain their original order so that
``('blue', 1)`` is guaranteed to precede ``('blue', 2)``.

This wonderful property lets you build complex sorts in a series of sorting
steps. For example, to sort the student data by descending *grade* and then
ascending *age*, do the *age* sort first and then sort again using *grade*:

    >>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary key
    >>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on primary key, descending
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The `Timsort <https://en.wikipedia.org/wiki/Timsort>`_ algorithm used in Python
does multiple sorts efficiently because it can take advantage of any ordering
already present in a dataset.

The Old Way Using Decorate-Sort-Undecorate
==========================================

This idiom is called Decorate-Sort-Undecorate after its three steps:

* First, the initial list is decorated with new values that control the sort order.

* Second, the decorated list is sorted.

* Finally, the decorations are removed, creating a list that contains only the
  initial values in the new order.

For example, to sort the student data by *grade* using the DSU approach:

    >>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
    >>> decorated.sort()
    >>> [student for grade, i, student in decorated]               # undecorate
    [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

This idiom works because tuples are compared lexicographically; the first items
are compared; if they are the same then the second items are compared, and so
on.

It is not strictly necessary in all cases to include the index *i* in the
decorated list, but including it gives two benefits:

* The sort is stable -- if two items have the same key, their order will be
  preserved in the sorted list.

* The original items do not have to be comparable because the ordering of the
  decorated tuples will be determined by at most the first two items. So for
  example the original list could contain complex numbers which cannot be sorted
  directly.

Another name for this idiom is
`Schwartzian transform <https://en.wikipedia.org/wiki/Schwartzian_transform>`_\,
after Randal L. Schwartz, who popularized it among Perl programmers.

For large lists and lists where the comparison information is expensive to
calculate, and Python versions before 2.4, DSU is likely to be the fastest way
to sort the list. For 2.4 and later, key functions provide the same
functionality.

The Old Way Using the *cmp* Parameter
=====================================

Many constructs given in this HOWTO assume Python 2.4 or later. Before that,
there was no :func:`sorted` builtin and :meth:`list.sort` took no keyword
arguments. Instead, all of the Py2.x versions supported a *cmp* parameter to
handle user specified comparison functions.

In Python 3, the *cmp* parameter was removed entirely (as part of a larger effort to
simplify and unify the language, eliminating the conflict between rich
comparisons and the :meth:`__cmp__` magic method).

In Python 2, :meth:`~list.sort` allowed an optional function which can be called for doing the
comparisons. That function should take two arguments to be compared and then
return a negative value for less-than, return zero if they are equal, or return
a positive value for greater-than. For example, we can do:

    >>> def numeric_compare(x, y):
    ...     return x - y
    >>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare) # doctest: +SKIP
    [1, 2, 3, 4, 5]

Or you can reverse the order of comparison with:

    >>> def reverse_numeric(x, y):
    ...     return y - x
    >>> sorted([5, 2, 4, 1, 3], cmp=reverse_numeric) # doctest: +SKIP
    [5, 4, 3, 2, 1]

When porting code from Python 2.x to 3.x, the situation can arise when you have
the user supplying a comparison function and you need to convert that to a key
function. The following wrapper makes that easy to do::

    def cmp_to_key(mycmp):
        'Convert a cmp= function into a key= function'
        class K(object):
            def __init__(self, obj, *args):
                self.obj = obj
            def __lt__(self, other):
                return mycmp(self.obj, other.obj) < 0
            def __gt__(self, other):
                return mycmp(self.obj, other.obj) > 0
            def __eq__(self, other):
                return mycmp(self.obj, other.obj) == 0
            def __le__(self, other):
                return mycmp(self.obj, other.obj) <= 0
            def __ge__(self, other):
                return mycmp(self.obj, other.obj) >= 0
            def __ne__(self, other):
                return mycmp(self.obj, other.obj) != 0
        return K

To convert to a key function, just wrap the old comparison function:

.. testsetup::

    from functools import cmp_to_key

.. doctest::

    >>> sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
    [5, 4, 3, 2, 1]

In Python 2.7, the :func:`functools.cmp_to_key` function was added to the
functools module.

Odd and Ends
============

* For locale aware sorting, use :func:`locale.strxfrm` for a key function or
  :func:`locale.strcoll` for a comparison function.

* The *reverse* parameter still maintains sort stability (so that records with
  equal keys retain their original order). Interestingly, that effect can be
  simulated without the parameter by using the builtin :func:`reversed` function
  twice:

    >>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
    >>> standard_way = sorted(data, key=itemgetter(0), reverse=True)
    >>> double_reversed = list(reversed(sorted(reversed(data), key=itemgetter(0))))
    >>> assert standard_way == double_reversed
    >>> standard_way
    [('red', 1), ('red', 2), ('blue', 1), ('blue', 2)]

* To create a standard sort order for a class, just add the appropriate rich
  comparison methods:

    >>> Student.__eq__ = lambda self, other: self.age == other.age
    >>> Student.__ne__ = lambda self, other: self.age != other.age
    >>> Student.__lt__ = lambda self, other: self.age < other.age
    >>> Student.__le__ = lambda self, other: self.age <= other.age
    >>> Student.__gt__ = lambda self, other: self.age > other.age
    >>> Student.__ge__ = lambda self, other: self.age >= other.age
    >>> sorted(student_objects)
    [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

  For general purpose comparisons, the recommended approach is to define all six
  rich comparison operators.  The :func:`functools.total_ordering` class
  decorator makes this easy to implement.

* Key functions need not depend directly on the objects being sorted. A key
  function can also access external resources. For instance, if the student grades
  are stored in a dictionary, they can be used to sort a separate list of student
  names:

    >>> students = ['dave', 'john', 'jane']
    >>> grades = {'john': 'F', 'jane':'A', 'dave': 'C'}
    >>> sorted(students, key=grades.__getitem__)
    ['jane', 'dave', 'john']
PK	%�\�x'����#html/_sources/howto/unicode.rst.txtnu�[���*****************
  Unicode HOWTO
*****************

:Release: 1.03

This HOWTO discusses Python 2.x's support for Unicode, and explains
various problems that people commonly encounter when trying to work
with Unicode.  For the Python 3 version, see
<https://docs.python.org/3/howto/unicode.html>.

Introduction to Unicode
=======================

History of Character Codes
--------------------------

In 1968, the American Standard Code for Information Interchange, better known by
its acronym ASCII, was standardized.  ASCII defined numeric codes for various
characters, with the numeric values running from 0 to
127.  For example, the lowercase letter 'a' is assigned 97 as its code
value.

ASCII was an American-developed standard, so it only defined unaccented
characters.  There was an 'e', but no 'é' or 'Í'.  This meant that languages
which required accented characters couldn't be faithfully represented in ASCII.
(Actually the missing accents matter for English, too, which contains words such
as 'naïve' and 'café', and some publications have house styles which require
spellings such as 'coöperate'.)

For a while people just wrote programs that didn't display accents.  I remember
looking at Apple ][ BASIC programs, published in French-language publications in
the mid-1980s, that had lines like these::

   PRINT "MISE A JOUR TERMINEE"
   PRINT "PARAMETRES ENREGISTRES"

Those messages should contain accents, and they just look wrong to someone who
can read French.

In the 1980s, almost all personal computers were 8-bit, meaning that bytes could
hold values ranging from 0 to 255.  ASCII codes only went up to 127, so some
machines assigned values between 128 and 255 to accented characters.  Different
machines had different codes, however, which led to problems exchanging files.
Eventually various commonly used sets of values for the 128--255 range emerged.
Some were true standards, defined by the International Organization for
Standardization, and some were *de facto* conventions that were invented by one
company or another and managed to catch on.

255 characters aren't very many.  For example, you can't fit both the accented
characters used in Western Europe and the Cyrillic alphabet used for Russian
into the 128--255 range because there are more than 128 such characters.

You could write files using different codes (all your Russian files in a coding
system called KOI8, all your French files in a different coding system called
Latin1), but what if you wanted to write a French document that quotes some
Russian text?  In the 1980s people began to want to solve this problem, and the
Unicode standardization effort began.

Unicode started out using 16-bit characters instead of 8-bit characters.  16
bits means you have 2^16 = 65,536 distinct values available, making it possible
to represent many different characters from many different alphabets; an initial
goal was to have Unicode contain the alphabets for every single human language.
It turns out that even 16 bits isn't enough to meet that goal, and the modern
Unicode specification uses a wider range of codes, 0--1,114,111 (0x10ffff in
base-16).

There's a related ISO standard, ISO 10646.  Unicode and ISO 10646 were
originally separate efforts, but the specifications were merged with the 1.1
revision of Unicode.

(This discussion of Unicode's history is highly simplified.  I don't think the
average Python programmer needs to worry about the historical details; consult
the Unicode consortium site listed in the References for more information.)


Definitions
-----------

A **character** is the smallest possible component of a text.  'A', 'B', 'C',
etc., are all different characters.  So are 'È' and 'Í'.  Characters are
abstractions, and vary depending on the language or context you're talking
about.  For example, the symbol for ohms (Ω) is usually drawn much like the
capital letter omega (Ω) in the Greek alphabet (they may even be the same in
some fonts), but these are two different characters that have different
meanings.

The Unicode standard describes how characters are represented by **code
points**.  A code point is an integer value, usually denoted in base 16.  In the
standard, a code point is written using the notation U+12ca to mean the
character with value 0x12ca (4810 decimal).  The Unicode standard contains a lot
of tables listing characters and their corresponding code points::

   0061    'a'; LATIN SMALL LETTER A
   0062    'b'; LATIN SMALL LETTER B
   0063    'c'; LATIN SMALL LETTER C
   ...
   007B    '{'; LEFT CURLY BRACKET

Strictly, these definitions imply that it's meaningless to say 'this is
character U+12ca'.  U+12ca is a code point, which represents some particular
character; in this case, it represents the character 'ETHIOPIC SYLLABLE WI'.  In
informal contexts, this distinction between code points and characters will
sometimes be forgotten.

A character is represented on a screen or on paper by a set of graphical
elements that's called a **glyph**.  The glyph for an uppercase A, for example,
is two diagonal strokes and a horizontal stroke, though the exact details will
depend on the font being used.  Most Python code doesn't need to worry about
glyphs; figuring out the correct glyph to display is generally the job of a GUI
toolkit or a terminal's font renderer.


Encodings
---------

To summarize the previous section: a Unicode string is a sequence of code
points, which are numbers from 0 to 0x10ffff.  This sequence needs to be
represented as a set of bytes (meaning, values from 0--255) in memory.  The rules
for translating a Unicode string into a sequence of bytes are called an
**encoding**.

The first encoding you might think of is an array of 32-bit integers.  In this
representation, the string "Python" would look like this::

       P           y           t           h           o           n
    0x50 00 00 00 79 00 00 00 74 00 00 00 68 00 00 00 6f 00 00 00 6e 00 00 00
       0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

This representation is straightforward but using it presents a number of
problems.

1. It's not portable; different processors order the bytes differently.

2. It's very wasteful of space.  In most texts, the majority of the code points
   are less than 127, or less than 255, so a lot of space is occupied by zero
   bytes.  The above string takes 24 bytes compared to the 6 bytes needed for an
   ASCII representation.  Increased RAM usage doesn't matter too much (desktop
   computers have megabytes of RAM, and strings aren't usually that large), but
   expanding our usage of disk and network bandwidth by a factor of 4 is
   intolerable.

3. It's not compatible with existing C functions such as ``strlen()``, so a new
   family of wide string functions would need to be used.

4. Many Internet standards are defined in terms of textual data, and can't
   handle content with embedded zero bytes.

Generally people don't use this encoding, instead choosing other
encodings that are more efficient and convenient.  UTF-8 is probably
the most commonly supported encoding; it will be discussed below.

Encodings don't have to handle every possible Unicode character, and most
encodings don't.  For example, Python's default encoding is the 'ascii'
encoding.  The rules for converting a Unicode string into the ASCII encoding are
simple; for each code point:

1. If the code point is < 128, each byte is the same as the value of the code
   point.

2. If the code point is 128 or greater, the Unicode string can't be represented
   in this encoding.  (Python raises a :exc:`UnicodeEncodeError` exception in this
   case.)

Latin-1, also known as ISO-8859-1, is a similar encoding.  Unicode code points
0--255 are identical to the Latin-1 values, so converting to this encoding simply
requires converting code points to byte values; if a code point larger than 255
is encountered, the string can't be encoded into Latin-1.

Encodings don't have to be simple one-to-one mappings like Latin-1.  Consider
IBM's EBCDIC, which was used on IBM mainframes.  Letter values weren't in one
block: 'a' through 'i' had values from 129 to 137, but 'j' through 'r' were 145
through 153.  If you wanted to use EBCDIC as an encoding, you'd probably use
some sort of lookup table to perform the conversion, but this is largely an
internal detail.

UTF-8 is one of the most commonly used encodings.  UTF stands for "Unicode
Transformation Format", and the '8' means that 8-bit numbers are used in the
encoding.  (There's also a UTF-16 encoding, but it's less frequently used than
UTF-8.)  UTF-8 uses the following rules:

1. If the code point is <128, it's represented by the corresponding byte value.
2. If the code point is between 128 and 0x7ff, it's turned into two byte values
   between 128 and 255.
3. Code points >0x7ff are turned into three- or four-byte sequences, where each
   byte of the sequence is between 128 and 255.

UTF-8 has several convenient properties:

1. It can handle any Unicode code point.
2. A Unicode string is turned into a string of bytes containing no embedded zero
   bytes.  This avoids byte-ordering issues, and means UTF-8 strings can be
   processed by C functions such as ``strcpy()`` and sent through protocols that
   can't handle zero bytes.
3. A string of ASCII text is also valid UTF-8 text.
4. UTF-8 is fairly compact; the majority of code points are turned into two
   bytes, and values less than 128 occupy only a single byte.
5. If bytes are corrupted or lost, it's possible to determine the start of the
   next UTF-8-encoded code point and resynchronize.  It's also unlikely that
   random 8-bit data will look like valid UTF-8.



References
----------

The Unicode Consortium site at <http://www.unicode.org> has character charts, a
glossary, and PDF versions of the Unicode specification.  Be prepared for some
difficult reading.  <http://www.unicode.org/history/> is a chronology of the
origin and development of Unicode.

To help understand the standard, Jukka Korpela has written an introductory guide
to reading the Unicode character tables, available at
<https://www.cs.tut.fi/~jkorpela/unicode/guide.html>.

Another good introductory article was written by Joel Spolsky
<http://www.joelonsoftware.com/articles/Unicode.html>.
If this introduction didn't make things clear to you, you should try reading this
alternate article before continuing.

.. Jason Orendorff XXX http://www.jorendorff.com/articles/unicode/ is broken

Wikipedia entries are often helpful; see the entries for "character encoding"
<http://en.wikipedia.org/wiki/Character_encoding> and UTF-8
<http://en.wikipedia.org/wiki/UTF-8>, for example.


Python 2.x's Unicode Support
============================

Now that you've learned the rudiments of Unicode, we can look at Python's
Unicode features.


The Unicode Type
----------------

Unicode strings are expressed as instances of the :class:`unicode` type, one of
Python's repertoire of built-in types.  It derives from an abstract type called
:class:`basestring`, which is also an ancestor of the :class:`str` type; you can
therefore check if a value is a string type with ``isinstance(value,
basestring)``.  Under the hood, Python represents Unicode strings as either 16-
or 32-bit integers, depending on how the Python interpreter was compiled.

The :func:`unicode` constructor has the signature ``unicode(string[, encoding,
errors])``.  All of its arguments should be 8-bit strings.  The first argument
is converted to Unicode using the specified encoding; if you leave off the
``encoding`` argument, the ASCII encoding is used for the conversion, so
characters greater than 127 will be treated as errors::

    >>> unicode('abcdef')
    u'abcdef'
    >>> s = unicode('abcdef')
    >>> type(s)
    <type 'unicode'>
    >>> unicode('abcdef' + chr(255))    #doctest: +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
    ...
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 6:
    ordinal not in range(128)

The ``errors`` argument specifies the response when the input string can't be
converted according to the encoding's rules.  Legal values for this argument are
'strict' (raise a ``UnicodeDecodeError`` exception), 'replace' (add U+FFFD,
'REPLACEMENT CHARACTER'), or 'ignore' (just leave the character out of the
Unicode result).  The following examples show the differences::

    >>> unicode('\x80abc', errors='strict')     #doctest: +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
        ...
    UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0:
    ordinal not in range(128)
    >>> unicode('\x80abc', errors='replace')
    u'\ufffdabc'
    >>> unicode('\x80abc', errors='ignore')
    u'abc'

Encodings are specified as strings containing the encoding's name.  Python 2.7
comes with roughly 100 different encodings; see the Python Library Reference at
:ref:`standard-encodings` for a list.  Some encodings
have multiple names; for example, 'latin-1', 'iso_8859_1' and '8859' are all
synonyms for the same encoding.

One-character Unicode strings can also be created with the :func:`unichr`
built-in function, which takes integers and returns a Unicode string of length 1
that contains the corresponding code point.  The reverse operation is the
built-in :func:`ord` function that takes a one-character Unicode string and
returns the code point value::

    >>> unichr(40960)
    u'\ua000'
    >>> ord(u'\ua000')
    40960

Instances of the :class:`unicode` type have many of the same methods as the
8-bit string type for operations such as searching and formatting::

    >>> s = u'Was ever feather so lightly blown to and fro as this multitude?'
    >>> s.count('e')
    5
    >>> s.find('feather')
    9
    >>> s.find('bird')
    -1
    >>> s.replace('feather', 'sand')
    u'Was ever sand so lightly blown to and fro as this multitude?'
    >>> s.upper()
    u'WAS EVER FEATHER SO LIGHTLY BLOWN TO AND FRO AS THIS MULTITUDE?'

Note that the arguments to these methods can be Unicode strings or 8-bit
strings.  8-bit strings will be converted to Unicode before carrying out the
operation; Python's default ASCII encoding will be used, so characters greater
than 127 will cause an exception::

    >>> s.find('Was\x9f')                   #doctest: +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
        ...
    UnicodeDecodeError: 'ascii' codec can't decode byte 0x9f in position 3:
    ordinal not in range(128)
    >>> s.find(u'Was\x9f')
    -1

Much Python code that operates on strings will therefore work with Unicode
strings without requiring any changes to the code.  (Input and output code needs
more updating for Unicode; more on this later.)

Another important method is ``.encode([encoding], [errors='strict'])``, which
returns an 8-bit string version of the Unicode string, encoded in the requested
encoding.  The ``errors`` parameter is the same as the parameter of the
``unicode()`` constructor, with one additional possibility; as well as 'strict',
'ignore', and 'replace', you can also pass 'xmlcharrefreplace' which uses XML's
character references.  The following example shows the different results::

    >>> u = unichr(40960) + u'abcd' + unichr(1972)
    >>> u.encode('utf-8')
    '\xea\x80\x80abcd\xde\xb4'
    >>> u.encode('ascii')                       #doctest: +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
        ...
    UnicodeEncodeError: 'ascii' codec can't encode character u'\ua000' in
    position 0: ordinal not in range(128)
    >>> u.encode('ascii', 'ignore')
    'abcd'
    >>> u.encode('ascii', 'replace')
    '?abcd?'
    >>> u.encode('ascii', 'xmlcharrefreplace')
    '&#40960;abcd&#1972;'

Python's 8-bit strings have a ``.decode([encoding], [errors])`` method that
interprets the string using the given encoding::

    >>> u = unichr(40960) + u'abcd' + unichr(1972)   # Assemble a string
    >>> utf8_version = u.encode('utf-8')             # Encode as UTF-8
    >>> type(utf8_version), utf8_version
    (<type 'str'>, '\xea\x80\x80abcd\xde\xb4')
    >>> u2 = utf8_version.decode('utf-8')            # Decode using UTF-8
    >>> u == u2                                      # The two strings match
    True

The low-level routines for registering and accessing the available encodings are
found in the :mod:`codecs` module.  However, the encoding and decoding functions
returned by this module are usually more low-level than is comfortable, so I'm
not going to describe the :mod:`codecs` module here.  If you need to implement a
completely new encoding, you'll need to learn about the :mod:`codecs` module
interfaces, but implementing encodings is a specialized task that also won't be
covered here.  Consult the Python documentation to learn more about this module.

The most commonly used part of the :mod:`codecs` module is the
:func:`codecs.open` function which will be discussed in the section on input and
output.


Unicode Literals in Python Source Code
--------------------------------------

In Python source code, Unicode literals are written as strings prefixed with the
'u' or 'U' character: ``u'abcdefghijk'``.  Specific code points can be written
using the ``\u`` escape sequence, which is followed by four hex digits giving
the code point.  The ``\U`` escape sequence is similar, but expects 8 hex
digits, not 4.

Unicode literals can also use the same escape sequences as 8-bit strings,
including ``\x``, but ``\x`` only takes two hex digits so it can't express an
arbitrary code point.  Octal escapes can go up to U+01ff, which is octal 777.

::

    >>> s = u"a\xac\u1234\u20ac\U00008000"
    ... #      ^^^^ two-digit hex escape
    ... #          ^^^^^^ four-digit Unicode escape
    ... #                      ^^^^^^^^^^ eight-digit Unicode escape
    >>> for c in s:  print ord(c),
    ...
    97 172 4660 8364 32768

Using escape sequences for code points greater than 127 is fine in small doses,
but becomes an annoyance if you're using many accented characters, as you would
in a program with messages in French or some other accent-using language.  You
can also assemble strings using the :func:`unichr` built-in function, but this is
even more tedious.

Ideally, you'd want to be able to write literals in your language's natural
encoding.  You could then edit Python source code with your favorite editor
which would display the accented characters naturally, and have the right
characters used at runtime.

Python supports writing Unicode literals in any encoding, but you have to
declare the encoding being used.  This is done by including a special comment as
either the first or second line of the source file::

    #!/usr/bin/env python
    # -*- coding: latin-1 -*-

    u = u'abcdé'
    print ord(u[-1])

The syntax is inspired by Emacs's notation for specifying variables local to a
file.  Emacs supports many different variables, but Python only supports
'coding'.  The ``-*-`` symbols indicate to Emacs that the comment is special;
they have no significance to Python but are a convention.  Python looks for
``coding: name`` or ``coding=name`` in the comment.

If you don't include such a comment, the default encoding used will be ASCII.
Versions of Python before 2.4 were Euro-centric and assumed Latin-1 as a default
encoding for string literals; in Python 2.4, characters greater than 127 still
work but result in a warning.  For example, the following program has no
encoding declaration::

    #!/usr/bin/env python
    u = u'abcdé'
    print ord(u[-1])

When you run it with Python 2.4, it will output the following warning::

    amk:~$ python2.4 p263.py
    sys:1: DeprecationWarning: Non-ASCII character '\xe9'
         in file p263.py on line 2, but no encoding declared;
         see https://www.python.org/peps/pep-0263.html for details

Python 2.5 and higher are stricter and will produce a syntax error::

    amk:~$ python2.5 p263.py
    File "/tmp/p263.py", line 2
    SyntaxError: Non-ASCII character '\xc3' in file /tmp/p263.py
      on line 2, but no encoding declared; see
      https://www.python.org/peps/pep-0263.html for details


Unicode Properties
------------------

The Unicode specification includes a database of information about code points.
For each code point that's defined, the information includes the character's
name, its category, the numeric value if applicable (Unicode has characters
representing the Roman numerals and fractions such as one-third and
four-fifths).  There are also properties related to the code point's use in
bidirectional text and other display-related properties.

The following program displays some information about several characters, and
prints the numeric value of one particular character::

    import unicodedata

    u = unichr(233) + unichr(0x0bf2) + unichr(3972) + unichr(6000) + unichr(13231)

    for i, c in enumerate(u):
        print i, '%04x' % ord(c), unicodedata.category(c),
        print unicodedata.name(c)

    # Get numeric value of second character
    print unicodedata.numeric(u[1])

When run, this prints::

    0 00e9 Ll LATIN SMALL LETTER E WITH ACUTE
    1 0bf2 No TAMIL NUMBER ONE THOUSAND
    2 0f84 Mn TIBETAN MARK HALANTA
    3 1770 Lo TAGBANWA LETTER SA
    4 33af So SQUARE RAD OVER S SQUARED
    1000.0

The category codes are abbreviations describing the nature of the character.
These are grouped into categories such as "Letter", "Number", "Punctuation", or
"Symbol", which in turn are broken up into subcategories.  To take the codes
from the above output, ``'Ll'`` means 'Letter, lowercase', ``'No'`` means
"Number, other", ``'Mn'`` is "Mark, nonspacing", and ``'So'`` is "Symbol,
other".  See
<http://www.unicode.org/reports/tr44/#General_Category_Values> for a
list of category codes.

References
----------

The Unicode and 8-bit string types are described in the Python library reference
at :ref:`typesseq`.

The documentation for the :mod:`unicodedata` module.

The documentation for the :mod:`codecs` module.

Marc-André Lemburg gave a presentation at EuroPython 2002 titled "Python and
Unicode".  A PDF version of his slides is available at
<https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf>, and is an
excellent overview of the design of Python's Unicode features.


Reading and Writing Unicode Data
================================

Once you've written some code that works with Unicode data, the next problem is
input/output.  How do you get Unicode strings into your program, and how do you
convert Unicode into a form suitable for storage or transmission?

It's possible that you may not need to do anything depending on your input
sources and output destinations; you should check whether the libraries used in
your application support Unicode natively.  XML parsers often return Unicode
data, for example.  Many relational databases also support Unicode-valued
columns and can return Unicode values from an SQL query.

Unicode data is usually converted to a particular encoding before it gets
written to disk or sent over a socket.  It's possible to do all the work
yourself: open a file, read an 8-bit string from it, and convert the string with
``unicode(str, encoding)``.  However, the manual approach is not recommended.

One problem is the multi-byte nature of encodings; one Unicode character can be
represented by several bytes.  If you want to read the file in arbitrary-sized
chunks (say, 1K or 4K), you need to write error-handling code to catch the case
where only part of the bytes encoding a single Unicode character are read at the
end of a chunk.  One solution would be to read the entire file into memory and
then perform the decoding, but that prevents you from working with files that
are extremely large; if you need to read a 2Gb file, you need 2Gb of RAM.
(More, really, since for at least a moment you'd need to have both the encoded
string and its Unicode version in memory.)

The solution would be to use the low-level decoding interface to catch the case
of partial coding sequences.  The work of implementing this has already been
done for you: the :mod:`codecs` module includes a version of the :func:`open`
function that returns a file-like object that assumes the file's contents are in
a specified encoding and accepts Unicode parameters for methods such as
``.read()`` and ``.write()``.

The function's parameters are ``open(filename, mode='rb', encoding=None,
errors='strict', buffering=1)``.  ``mode`` can be ``'r'``, ``'w'``, or ``'a'``,
just like the corresponding parameter to the regular built-in ``open()``
function; add a ``'+'`` to update the file.  ``buffering`` is similarly parallel
to the standard function's parameter.  ``encoding`` is a string giving the
encoding to use; if it's left as ``None``, a regular Python file object that
accepts 8-bit strings is returned.  Otherwise, a wrapper object is returned, and
data written to or read from the wrapper object will be converted as needed.
``errors`` specifies the action for encoding errors and can be one of the usual
values of 'strict', 'ignore', and 'replace'.

Reading Unicode from a file is therefore simple::

    import codecs
    f = codecs.open('unicode.rst', encoding='utf-8')
    for line in f:
        print repr(line)

It's also possible to open files in update mode, allowing both reading and
writing::

    f = codecs.open('test', encoding='utf-8', mode='w+')
    f.write(u'\u4500 blah blah blah\n')
    f.seek(0)
    print repr(f.readline()[:1])
    f.close()

Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
written as the first character of a file in order to assist with autodetection
of the file's byte ordering.  Some encodings, such as UTF-16, expect a BOM to be
present at the start of a file; when such an encoding is used, the BOM will be
automatically written as the first character and will be silently dropped when
the file is read.  There are variants of these encodings, such as 'utf-16-le'
and 'utf-16-be' for little-endian and big-endian encodings, that specify one
particular byte ordering and don't skip the BOM.


Unicode filenames
-----------------

Most of the operating systems in common use today support filenames that contain
arbitrary Unicode characters.  Usually this is implemented by converting the
Unicode string into some encoding that varies depending on the system.  For
example, Mac OS X uses UTF-8 while Windows uses a configurable encoding; on
Windows, Python uses the name "mbcs" to refer to whatever the currently
configured encoding is.  On Unix systems, there will only be a filesystem
encoding if you've set the ``LANG`` or ``LC_CTYPE`` environment variables; if
you haven't, the default encoding is ASCII.

The :func:`sys.getfilesystemencoding` function returns the encoding to use on
your current system, in case you want to do the encoding manually, but there's
not much reason to bother.  When opening a file for reading or writing, you can
usually just provide the Unicode string as the filename, and it will be
automatically converted to the right encoding for you::

    filename = u'filename\u4500abc'
    f = open(filename, 'w')
    f.write('blah\n')
    f.close()

Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode
filenames.

:func:`os.listdir`, which returns filenames, raises an issue: should it return
the Unicode version of filenames, or should it return 8-bit strings containing
the encoded versions?  :func:`os.listdir` will do both, depending on whether you
provided the directory path as an 8-bit string or a Unicode string.  If you pass
a Unicode string as the path, filenames will be decoded using the filesystem's
encoding and a list of Unicode strings will be returned, while passing an 8-bit
path will return the 8-bit versions of the filenames.  For example, assuming the
default filesystem encoding is UTF-8, running the following program::

   fn = u'filename\u4500abc'
   f = open(fn, 'w')
   f.close()

   import os
   print os.listdir('.')
   print os.listdir(u'.')

will produce the following output:

.. code-block:: shell-session

   amk:~$ python t.py
   ['.svn', 'filename\xe4\x94\x80abc', ...]
   [u'.svn', u'filename\u4500abc', ...]

The first list contains UTF-8-encoded filenames, and the second list contains
the Unicode versions.



Tips for Writing Unicode-aware Programs
---------------------------------------

This section provides some suggestions on writing software that deals with
Unicode.

The most important tip is:

    Software should only work with Unicode strings internally, converting to a
    particular encoding on output.

If you attempt to write processing functions that accept both Unicode and 8-bit
strings, you will find your program vulnerable to bugs wherever you combine the
two different kinds of strings.  Python's default encoding is ASCII, so whenever
a character with an ASCII value > 127 is in the input data, you'll get a
:exc:`UnicodeDecodeError` because that character can't be handled by the ASCII
encoding.

It's easy to miss such problems if you only test your software with data that
doesn't contain any accents; everything will seem to work, but there's actually
a bug in your program waiting for the first user who attempts to use characters
> 127.  A second tip, therefore, is:

    Include characters > 127 and, even better, characters > 255 in your test
    data.

When using data coming from a web browser or some other untrusted source, a
common technique is to check for illegal characters in a string before using the
string in a generated command line or storing it in a database.  If you're doing
this, be careful to check the string once it's in the form that will be used or
stored; it's possible for encodings to be used to disguise characters.  This is
especially true if the input data also specifies the encoding; many encodings
leave the commonly checked-for characters alone, but Python includes some
encodings such as ``'base64'`` that modify every single character.

For example, let's say you have a content management system that takes a Unicode
filename, and you want to disallow paths with a '/' character.  You might write
this code::

    def read_file (filename, encoding):
        if '/' in filename:
            raise ValueError("'/' not allowed in filenames")
        unicode_name = filename.decode(encoding)
        f = open(unicode_name, 'r')
        # ... return contents of file ...

However, if an attacker could specify the ``'base64'`` encoding, they could pass
``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
``'/etc/passwd'``, to read a system file.  The above code looks for ``'/'``
characters in the encoded form and misses the dangerous character in the
resulting decoded form.

References
----------

The PDF slides for Marc-André Lemburg's presentation "Writing Unicode-aware
Applications in Python" are available at
<https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf>
and discuss questions of character encodings as well as how to internationalize
and localize an application.


Revision History and Acknowledgements
=====================================

Thanks to the following people who have noted errors or offered suggestions on
this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
Marc-André Lemburg, Martin von Löwis, Chad Whitacre.

Version 1.0: posted August 5 2005.

Version 1.01: posted August 7 2005.  Corrects factual and markup errors; adds
several links.

Version 1.02: posted August 16 2005.  Corrects factual errors.

Version 1.03: posted June 20 2010.  Notes that Python 3.x is not covered,
and that the HOWTO only covers 2.x.


.. comment Describe Python 3.x support (new section? new document?)
.. comment Additional topic: building Python w/ UCS2 or UCS4 support
.. comment Describe obscure -U switch somewhere?
.. comment Describe use of codecs.StreamRecoder and StreamReaderWriter

.. comment
   Original outline:

   - [ ] Unicode introduction
       - [ ] ASCII
       - [ ] Terms
           - [ ] Character
           - [ ] Code point
         - [ ] Encodings
            - [ ] Common encodings: ASCII, Latin-1, UTF-8
       - [ ] Unicode Python type
           - [ ] Writing unicode literals
               - [ ] Obscurity: -U switch
           - [ ] Built-ins
               - [ ] unichr()
               - [ ] ord()
               - [ ] unicode() constructor
           - [ ] Unicode type
               - [ ] encode(), decode() methods
       - [ ] Unicodedata module for character properties
       - [ ] I/O
           - [ ] Reading/writing Unicode data into files
               - [ ] Byte-order marks
           - [ ] Unicode filenames
       - [ ] Writing Unicode programs
           - [ ] Do everything in Unicode
           - [ ] Declaring source code encodings (PEP 263)
       - [ ] Other issues
           - [ ] Building Python (UCS2, UCS4)
PK	%�\0��[�[#html/_sources/howto/urllib2.rst.txtnu�[���.. _urllib-howto:

************************************************
  HOWTO Fetch Internet Resources Using urllib2
************************************************

:Author: `Michael Foord <http://www.voidspace.org.uk/python/index.shtml>`_

.. note::

    There is a French translation of an earlier revision of this
    HOWTO, available at `urllib2 - Le Manuel manquant
    <http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml>`_.



Introduction
============

.. sidebar:: Related Articles

    You may also find useful the following article on fetching web resources
    with Python:

    * `Basic Authentication <http://www.voidspace.org.uk/python/articles/authentication.shtml>`_

        A tutorial on *Basic Authentication*, with examples in Python.

**urllib2** is a Python module for fetching URLs
(Uniform Resource Locators). It offers a very simple interface, in the form of
the *urlopen* function. This is capable of fetching URLs using a variety of
different protocols. It also offers a slightly more complex interface for
handling common situations - like basic authentication, cookies, proxies and so
on. These are provided by objects called handlers and openers.

urllib2 supports fetching URLs for many "URL schemes" (identified by the string
before the ``":"`` in URL - for example ``"ftp"`` is the URL scheme of
``"ftp://python.org/"``) using their associated network protocols (e.g. FTP, HTTP).
This tutorial focuses on the most common case, HTTP.

For straightforward situations *urlopen* is very easy to use. But as soon as you
encounter errors or non-trivial cases when opening HTTP URLs, you will need some
understanding of the HyperText Transfer Protocol. The most comprehensive and
authoritative reference to HTTP is :rfc:`2616`. This is a technical document and
not intended to be easy to read. This HOWTO aims to illustrate using *urllib2*,
with enough detail about HTTP to help you through. It is not intended to replace
the :mod:`urllib2` docs, but is supplementary to them.


Fetching URLs
=============

The simplest way to use urllib2 is as follows::

    import urllib2
    response = urllib2.urlopen('http://python.org/')
    html = response.read()

Many uses of urllib2 will be that simple (note that instead of an 'http:' URL we
could have used a URL starting with 'ftp:', 'file:', etc.).  However, it's the
purpose of this tutorial to explain the more complicated cases, concentrating on
HTTP.

HTTP is based on requests and responses - the client makes requests and servers
send responses. urllib2 mirrors this with a ``Request`` object which represents
the HTTP request you are making. In its simplest form you create a Request
object that specifies the URL you want to fetch. Calling ``urlopen`` with this
Request object returns a response object for the URL requested. This response is
a file-like object, which means you can for example call ``.read()`` on the
response::

    import urllib2

    req = urllib2.Request('http://www.voidspace.org.uk')
    response = urllib2.urlopen(req)
    the_page = response.read()

Note that urllib2 makes use of the same Request interface to handle all URL
schemes.  For example, you can make an FTP request like so::

    req = urllib2.Request('ftp://example.com/')

In the case of HTTP, there are two extra things that Request objects allow you
to do: First, you can pass data to be sent to the server.  Second, you can pass
extra information ("metadata") *about* the data or the about request itself, to
the server - this information is sent as HTTP "headers".  Let's look at each of
these in turn.

Data
----

Sometimes you want to send data to a URL (often the URL will refer to a CGI
(Common Gateway Interface) script [#]_ or other web application). With HTTP,
this is often done using what's known as a **POST** request. This is often what
your browser does when you submit a HTML form that you filled in on the web. Not
all POSTs have to come from forms: you can use a POST to transmit arbitrary data
to your own application. In the common case of HTML forms, the data needs to be
encoded in a standard way, and then passed to the Request object as the ``data``
argument. The encoding is done using a function from the ``urllib`` library
*not* from ``urllib2``. ::

    import urllib
    import urllib2

    url = 'http://www.someserver.com/cgi-bin/register.cgi'
    values = {'name' : 'Michael Foord',
              'location' : 'Northampton',
              'language' : 'Python' }

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    response = urllib2.urlopen(req)
    the_page = response.read()

Note that other encodings are sometimes required (e.g. for file upload from HTML
forms - see `HTML Specification, Form Submission
<https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13>`_ for more
details).

If you do not pass the ``data`` argument, urllib2 uses a **GET** request. One
way in which GET and POST requests differ is that POST requests often have
"side-effects": they change the state of the system in some way (for example by
placing an order with the website for a hundredweight of tinned spam to be
delivered to your door).  Though the HTTP standard makes it clear that POSTs are
intended to *always* cause side-effects, and GET requests *never* to cause
side-effects, nothing prevents a GET request from having side-effects, nor a
POST requests from having no side-effects. Data can also be passed in an HTTP
GET request by encoding it in the URL itself.

This is done as follows::

    >>> import urllib2
    >>> import urllib
    >>> data = {}
    >>> data['name'] = 'Somebody Here'
    >>> data['location'] = 'Northampton'
    >>> data['language'] = 'Python'
    >>> url_values = urllib.urlencode(data)
    >>> print url_values  # The order may differ. #doctest: +SKIP
    name=Somebody+Here&language=Python&location=Northampton
    >>> url = 'http://www.example.com/example.cgi'
    >>> full_url = url + '?' + url_values
    >>> data = urllib2.urlopen(full_url)

Notice that the full URL is created by adding a ``?`` to the URL, followed by
the encoded values.

Headers
-------

We'll discuss here one particular HTTP header, to illustrate how to add headers
to your HTTP request.

Some websites [#]_ dislike being browsed by programs, or send different versions
to different browsers [#]_. By default urllib2 identifies itself as
``Python-urllib/x.y`` (where ``x`` and ``y`` are the major and minor version
numbers of the Python release,
e.g. ``Python-urllib/2.5``), which may confuse the site, or just plain
not work. The way a browser identifies itself is through the
``User-Agent`` header [#]_. When you create a Request object you can
pass a dictionary of headers in. The following example makes the same
request as above, but identifies itself as a version of Internet
Explorer [#]_. ::

    import urllib
    import urllib2

    url = 'http://www.someserver.com/cgi-bin/register.cgi'
    user_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'
    values = {'name': 'Michael Foord',
              'location': 'Northampton',
              'language': 'Python' }
    headers = {'User-Agent': user_agent}

    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()

The response also has two useful methods. See the section on `info and geturl`_
which comes after we have a look at what happens when things go wrong.


Handling Exceptions
===================

*urlopen* raises :exc:`URLError` when it cannot handle a response (though as
usual with Python APIs, built-in exceptions such as :exc:`ValueError`,
:exc:`TypeError` etc. may also be raised).

:exc:`HTTPError` is the subclass of :exc:`URLError` raised in the specific case of
HTTP URLs.

URLError
--------

Often, URLError is raised because there is no network connection (no route to
the specified server), or the specified server doesn't exist.  In this case, the
exception raised will have a 'reason' attribute, which is a tuple containing an
error code and a text error message.

e.g. ::

    >>> req = urllib2.Request('http://www.pretend_server.org')
    >>> try: urllib2.urlopen(req)
    ... except urllib2.URLError as e:
    ...    print e.reason   #doctest: +SKIP
    ...
    (4, 'getaddrinfo failed')


HTTPError
---------

Every HTTP response from the server contains a numeric "status code". Sometimes
the status code indicates that the server is unable to fulfil the request. The
default handlers will handle some of these responses for you (for example, if
the response is a "redirection" that requests the client fetch the document from
a different URL, urllib2 will handle that for you). For those it can't handle,
urlopen will raise an :exc:`HTTPError`. Typical errors include '404' (page not
found), '403' (request forbidden), and '401' (authentication required).

See section 10 of RFC 2616 for a reference on all the HTTP error codes.

The :exc:`HTTPError` instance raised will have an integer 'code' attribute, which
corresponds to the error sent by the server.

Error Codes
~~~~~~~~~~~

Because the default handlers handle redirects (codes in the 300 range), and
codes in the 100--299 range indicate success, you will usually only see error
codes in the 400--599 range.

``BaseHTTPServer.BaseHTTPRequestHandler.responses`` is a useful dictionary of
response codes in that shows all the response codes used by RFC 2616. The
dictionary is reproduced here for convenience ::

    # Table mapping response codes to messages; entries have the
    # form {code: (shortmessage, longmessage)}.
    responses = {
        100: ('Continue', 'Request received, please continue'),
        101: ('Switching Protocols',
              'Switching to new protocol; obey Upgrade header'),

        200: ('OK', 'Request fulfilled, document follows'),
        201: ('Created', 'Document created, URL follows'),
        202: ('Accepted',
              'Request accepted, processing continues off-line'),
        203: ('Non-Authoritative Information', 'Request fulfilled from cache'),
        204: ('No Content', 'Request fulfilled, nothing follows'),
        205: ('Reset Content', 'Clear input form for further input.'),
        206: ('Partial Content', 'Partial content follows.'),

        300: ('Multiple Choices',
              'Object has several resources -- see URI list'),
        301: ('Moved Permanently', 'Object moved permanently -- see URI list'),
        302: ('Found', 'Object moved temporarily -- see URI list'),
        303: ('See Other', 'Object moved -- see Method and URL list'),
        304: ('Not Modified',
              'Document has not changed since given time'),
        305: ('Use Proxy',
              'You must use proxy specified in Location to access this '
              'resource.'),
        307: ('Temporary Redirect',
              'Object moved temporarily -- see URI list'),

        400: ('Bad Request',
              'Bad request syntax or unsupported method'),
        401: ('Unauthorized',
              'No permission -- see authorization schemes'),
        402: ('Payment Required',
              'No payment -- see charging schemes'),
        403: ('Forbidden',
              'Request forbidden -- authorization will not help'),
        404: ('Not Found', 'Nothing matches the given URI'),
        405: ('Method Not Allowed',
              'Specified method is invalid for this server.'),
        406: ('Not Acceptable', 'URI not available in preferred format.'),
        407: ('Proxy Authentication Required', 'You must authenticate with '
              'this proxy before proceeding.'),
        408: ('Request Timeout', 'Request timed out; try again later.'),
        409: ('Conflict', 'Request conflict.'),
        410: ('Gone',
              'URI no longer exists and has been permanently removed.'),
        411: ('Length Required', 'Client must specify Content-Length.'),
        412: ('Precondition Failed', 'Precondition in headers is false.'),
        413: ('Request Entity Too Large', 'Entity is too large.'),
        414: ('Request-URI Too Long', 'URI is too long.'),
        415: ('Unsupported Media Type', 'Entity body in unsupported format.'),
        416: ('Requested Range Not Satisfiable',
              'Cannot satisfy request range.'),
        417: ('Expectation Failed',
              'Expect condition could not be satisfied.'),

        500: ('Internal Server Error', 'Server got itself in trouble'),
        501: ('Not Implemented',
              'Server does not support this operation'),
        502: ('Bad Gateway', 'Invalid responses from another server/proxy.'),
        503: ('Service Unavailable',
              'The server cannot process the request due to a high load'),
        504: ('Gateway Timeout',
              'The gateway server did not receive a timely response'),
        505: ('HTTP Version Not Supported', 'Cannot fulfill request.'),
        }

When an error is raised the server responds by returning an HTTP error code
*and* an error page. You can use the :exc:`HTTPError` instance as a response on the
page returned. This means that as well as the code attribute, it also has read,
geturl, and info, methods. ::

    >>> req = urllib2.Request('http://www.python.org/fish.html')
    >>> try:
    ...     urllib2.urlopen(req)
    ... except urllib2.HTTPError as e:
    ...     print e.code
    ...     print e.read() #doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    ...
    404
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    ...
    <title>Page Not Found</title>
    ...


Wrapping it Up
--------------

So if you want to be prepared for :exc:`HTTPError` *or* :exc:`URLError` there are two
basic approaches. I prefer the second approach.

Number 1
~~~~~~~~

::


    from urllib2 import Request, urlopen, URLError, HTTPError
    req = Request(someurl)
    try:
        response = urlopen(req)
    except HTTPError as e:
        print 'The server couldn\'t fulfill the request.'
        print 'Error code: ', e.code
    except URLError as e:
        print 'We failed to reach a server.'
        print 'Reason: ', e.reason
    else:
        # everything is fine


.. note::

    The ``except HTTPError`` *must* come first, otherwise ``except URLError``
    will *also* catch an :exc:`HTTPError`.

Number 2
~~~~~~~~

::

    from urllib2 import Request, urlopen, URLError
    req = Request(someurl)
    try:
        response = urlopen(req)
    except URLError as e:
        if hasattr(e, 'reason'):
            print 'We failed to reach a server.'
            print 'Reason: ', e.reason
        elif hasattr(e, 'code'):
            print 'The server couldn\'t fulfill the request.'
            print 'Error code: ', e.code
    else:
        # everything is fine


info and geturl
===============

The response returned by urlopen (or the :exc:`HTTPError` instance) has two useful
methods :meth:`info` and :meth:`geturl`.

**geturl** - this returns the real URL of the page fetched. This is useful
because ``urlopen`` (or the opener object used) may have followed a
redirect. The URL of the page fetched may not be the same as the URL requested.

**info** - this returns a dictionary-like object that describes the page
fetched, particularly the headers sent by the server. It is currently an
``httplib.HTTPMessage`` instance.

Typical headers include 'Content-length', 'Content-type', and so on. See the
`Quick Reference to HTTP Headers <https://www.cs.tut.fi/~jkorpela/http.html>`_
for a useful listing of HTTP headers with brief explanations of their meaning
and use.


Openers and Handlers
====================

When you fetch a URL you use an opener (an instance of the perhaps
confusingly-named :class:`urllib2.OpenerDirector`). Normally we have been using
the default opener - via ``urlopen`` - but you can create custom
openers. Openers use handlers. All the "heavy lifting" is done by the
handlers. Each handler knows how to open URLs for a particular URL scheme (http,
ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
redirections or HTTP cookies.

You will want to create openers if you want to fetch URLs with specific handlers
installed, for example to get an opener that handles cookies, or to get an
opener that does not handle redirections.

To create an opener, instantiate an ``OpenerDirector``, and then call
``.add_handler(some_handler_instance)`` repeatedly.

Alternatively, you can use ``build_opener``, which is a convenience function for
creating opener objects with a single function call.  ``build_opener`` adds
several handlers by default, but provides a quick way to add more and/or
override the default handlers.

Other sorts of handlers you might want to can handle proxies, authentication,
and other common but slightly specialised situations.

``install_opener`` can be used to make an ``opener`` object the (global) default
opener. This means that calls to ``urlopen`` will use the opener you have
installed.

Opener objects have an ``open`` method, which can be called directly to fetch
urls in the same way as the ``urlopen`` function: there's no need to call
``install_opener``, except as a convenience.


Basic Authentication
====================

To illustrate creating and installing a handler we will use the
``HTTPBasicAuthHandler``. For a more detailed discussion of this subject --
including an explanation of how Basic Authentication works - see the `Basic
Authentication Tutorial
<http://www.voidspace.org.uk/python/articles/authentication.shtml>`_.

When authentication is required, the server sends a header (as well as the 401
error code) requesting authentication.  This specifies the authentication scheme
and a 'realm'. The header looks like: ``WWW-Authenticate: SCHEME
realm="REALM"``.

e.g. ::

    WWW-Authenticate: Basic realm="cPanel Users"


The client should then retry the request with the appropriate name and password
for the realm included as a header in the request. This is 'basic
authentication'. In order to simplify this process we can create an instance of
``HTTPBasicAuthHandler`` and an opener to use this handler.

The ``HTTPBasicAuthHandler`` uses an object called a password manager to handle
the mapping of URLs and realms to passwords and usernames. If you know what the
realm is (from the authentication header sent by the server), then you can use a
``HTTPPasswordMgr``. Frequently one doesn't care what the realm is. In that
case, it is convenient to use ``HTTPPasswordMgrWithDefaultRealm``. This allows
you to specify a default username and password for a URL. This will be supplied
in the absence of you providing an alternative combination for a specific
realm. We indicate this by providing ``None`` as the realm argument to the
``add_password`` method.

The top-level URL is the first URL that requires authentication. URLs "deeper"
than the URL you pass to .add_password() will also match. ::

    # create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    # Add the username and password.
    # If we knew the realm, we could use it instead of None.
    top_level_url = "http://example.com/foo/"
    password_mgr.add_password(None, top_level_url, username, password)

    handler = urllib2.HTTPBasicAuthHandler(password_mgr)

    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)

    # use the opener to fetch a URL
    opener.open(a_url)

    # Install the opener.
    # Now all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

.. note::

    In the above example we only supplied our ``HTTPBasicAuthHandler`` to
    ``build_opener``. By default openers have the handlers for normal situations
    -- ``ProxyHandler`` (if a proxy setting such as an :envvar:`http_proxy`
    environment variable is set), ``UnknownHandler``, ``HTTPHandler``,
    ``HTTPDefaultErrorHandler``, ``HTTPRedirectHandler``, ``FTPHandler``,
    ``FileHandler``, ``HTTPErrorProcessor``.

``top_level_url`` is in fact *either* a full URL (including the 'http:' scheme
component and the hostname and optionally the port number)
e.g. ``"http://example.com/"`` *or* an "authority" (i.e. the hostname,
optionally including the port number) e.g. ``"example.com"`` or ``"example.com:8080"``
(the latter example includes a port number).  The authority, if present, must
NOT contain the "userinfo" component - for example ``"joe:password@example.com"`` is
not correct.


Proxies
=======

**urllib2** will auto-detect your proxy settings and use those. This is through
the ``ProxyHandler``, which is part of the normal handler chain when a proxy
setting is detected.  Normally that's a good thing, but there are occasions
when it may not be helpful [#]_. One way to do this is to setup our own
``ProxyHandler``, with no proxies defined. This is done using similar steps to
setting up a `Basic Authentication`_ handler: ::

    >>> proxy_support = urllib2.ProxyHandler({})
    >>> opener = urllib2.build_opener(proxy_support)
    >>> urllib2.install_opener(opener)

.. note::

    Currently ``urllib2`` *does not* support fetching of ``https`` locations
    through a proxy.  However, this can be enabled by extending urllib2 as
    shown in the recipe [#]_.

.. note::

    ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set; see
    the documentation on :func:`~urllib.getproxies`.


Sockets and Layers
==================

The Python support for fetching resources from the web is layered. urllib2 uses
the httplib library, which in turn uses the socket library.

As of Python 2.3 you can specify how long a socket should wait for a response
before timing out. This can be useful in applications which have to fetch web
pages. By default the socket module has *no timeout* and can hang. Currently,
the socket timeout is not exposed at the httplib or urllib2 levels.  However,
you can set the default timeout globally for all sockets using ::

    import socket
    import urllib2

    # timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

    # this call to urllib2.urlopen now uses the default timeout
    # we have set in the socket module
    req = urllib2.Request('http://www.voidspace.org.uk')
    response = urllib2.urlopen(req)


-------


Footnotes
=========

This document was reviewed and revised by John Lee.

.. [#] For an introduction to the CGI protocol see
       `Writing Web Applications in Python <http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html>`_.
.. [#] Google for example.
.. [#] Browser sniffing is a very bad practice for website design - building
       sites using web standards is much more sensible. Unfortunately a lot of
       sites still send different versions to different browsers.
.. [#] The user agent for MSIE 6 is
       *'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)'*
.. [#] For details of more HTTP request headers, see
       `Quick Reference to HTTP Headers`_.
.. [#] In my case I have to use a proxy to access the internet at work. If you
       attempt to fetch *localhost* URLs through this proxy it blocks them. IE
       is set to use the proxy, which urllib2 picks up on. In order to test
       scripts with a localhost server, I have to prevent urllib2 from using
       the proxy.
.. [#] urllib2 opener for SSL proxy (CONNECT method): `ASPN Cookbook Recipe
       <https://code.activestate.com/recipes/456195/>`_.

PK	%�\��YjC�C�&html/_sources/howto/webservers.rst.txtnu�[���*******************************
  HOWTO Use Python in the web
*******************************

:Author: Marek Kubica

.. topic:: Abstract

   This document shows how Python fits into the web.  It presents some ways
   to integrate Python with a web server, and general practices useful for
   developing web sites.


Programming for the Web has become a hot topic since the rise of "Web 2.0",
which focuses on user-generated content on web sites.  It has always been
possible to use Python for creating web sites, but it was a rather tedious task.
Therefore, many frameworks and helper tools have been created to assist
developers in creating faster and more robust sites.  This HOWTO describes
some of the methods used to combine Python with a web server to create
dynamic content.  It is not meant as a complete introduction, as this topic is
far too broad to be covered in one single document.  However, a short overview
of the most popular libraries is provided.

.. seealso::

   While this HOWTO tries to give an overview of Python in the web, it cannot
   always be as up to date as desired.  Web development in Python is rapidly
   moving forward, so the wiki page on `Web Programming
   <https://wiki.python.org/moin/WebProgramming>`_ may be more in sync with
   recent development.


The Low-Level View
==================

When a user enters a web site, their browser makes a connection to the site's
web server (this is called the *request*).  The server looks up the file in the
file system and sends it back to the user's browser, which displays it (this is
the *response*).  This is roughly how the underlying protocol, HTTP, works.

Dynamic web sites are not based on files in the file system, but rather on
programs which are run by the web server when a request comes in, and which
*generate* the content that is returned to the user.  They can do all sorts of
useful things, like display the postings of a bulletin board, show your email,
configure software, or just display the current time.  These programs can be
written in any programming language the server supports.  Since most servers
support Python, it is easy to use Python to create dynamic web sites.

Most HTTP servers are written in C or C++, so they cannot execute Python code
directly -- a bridge is needed between the server and the program.  These
bridges, or rather interfaces, define how programs interact with the server.
There have been numerous attempts to create the best possible interface, but
there are only a few worth mentioning.

Not every web server supports every interface.  Many web servers only support
old, now-obsolete interfaces; however, they can often be extended using
third-party modules to support newer ones.


Common Gateway Interface
------------------------

This interface, most commonly referred to as "CGI", is the oldest, and is
supported by nearly every web server out of the box.  Programs using CGI to
communicate with their web server need to be started by the server for every
request.  So, every request starts a new Python interpreter -- which takes some
time to start up -- thus making the whole interface only usable for low load
situations.

The upside of CGI is that it is simple -- writing a Python program which uses
CGI is a matter of about three lines of code.  This simplicity comes at a
price: it does very few things to help the developer.

Writing CGI programs, while still possible, is no longer recommended.  With
:ref:`WSGI <WSGI>`, a topic covered later in this document, it is possible to write
programs that emulate CGI, so they can be run as CGI if no better option is
available.

.. seealso::

   The Python standard library includes some modules that are helpful for
   creating plain CGI programs:

   * :mod:`cgi` -- Handling of user input in CGI scripts
   * :mod:`cgitb` -- Displays nice tracebacks when errors happen in CGI
     applications, instead of presenting a "500 Internal Server Error" message

   The Python wiki features a page on `CGI scripts
   <https://wiki.python.org/moin/CgiScripts>`_ with some additional information
   about CGI in Python.


Simple script for testing CGI
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

To test whether your web server works with CGI, you can use this short and
simple CGI program::

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-

    # enable debugging
    import cgitb
    cgitb.enable()

    print "Content-Type: text/plain;charset=utf-8"
    print

    print "Hello World!"

Depending on your web server configuration, you may need to save this code with
a ``.py`` or ``.cgi`` extension.  Additionally, this file may also need to be
in a ``cgi-bin`` folder, for security reasons.

You might wonder what the ``cgitb`` line is about.  This line makes it possible
to display a nice traceback instead of just crashing and displaying an "Internal
Server Error" in the user's browser.  This is useful for debugging, but it might
risk exposing some confidential data to the user.  You should not use ``cgitb``
in production code for this reason.  You should *always* catch exceptions, and
display proper error pages -- end-users don't like to see nondescript "Internal
Server Errors" in their browsers.


Setting up CGI on your own server
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you don't have your own web server, this does not apply to you.  You can
check whether it works as-is, and if not you will need to talk to the
administrator of your web server. If it is a big host, you can try filing a
ticket asking for Python support.

If you are your own administrator or want to set up CGI for testing purposes on
your own computers, you have to configure it by yourself.  There is no single
way to configure CGI, as there are many web servers with different
configuration options.  Currently the most widely used free web server is
`Apache HTTPd <http://httpd.apache.org/>`_, or Apache for short. Apache can be
easily installed on nearly every system using the system's package management
tool.  `lighttpd <http://www.lighttpd.net>`_ is another alternative and is
said to have better performance.  On many systems this server can also be
installed using the package management tool, so manually compiling the web
server may not be needed.

* On Apache you can take a look at the `Dynamic Content with CGI
  <http://httpd.apache.org/docs/2.2/howto/cgi.html>`_ tutorial, where everything
  is described.  Most of the time it is enough just to set ``+ExecCGI``.  The
  tutorial also describes the most common gotchas that might arise.

* On lighttpd you need to use the `CGI module
  <http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModCGI>`_\ , which can be configured
  in a straightforward way.  It boils down to setting ``cgi.assign`` properly.


Common problems with CGI scripts
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Using CGI sometimes leads to small annoyances while trying to get these
scripts to run.  Sometimes a seemingly correct script does not work as
expected, the cause being some small hidden problem that's difficult to spot.

Some of these potential problems are:

* The Python script is not marked as executable.  When CGI scripts are not
  executable most web servers will let the user download it, instead of
  running it and sending the output to the user.  For CGI scripts to run
  properly on Unix-like operating systems, the ``+x`` bit needs to be set.
  Using ``chmod a+x your_script.py`` may solve this problem.

* On a Unix-like system, The line endings in the program file must be Unix
  style line endings.  This is important because the web server checks the
  first line of the script (called shebang) and tries to run the program
  specified there.  It gets easily confused by Windows line endings (Carriage
  Return & Line Feed, also called CRLF), so you have to convert the file to
  Unix line endings (only Line Feed, LF).  This can be done automatically by
  uploading the file via FTP in text mode instead of binary mode, but the
  preferred way is just telling your editor to save the files with Unix line
  endings.  Most editors support this.

* Your web server must be able to read the file, and you need to make sure the
  permissions are correct.  On unix-like systems, the server often runs as user
  and group ``www-data``, so it might be worth a try to change the file
  ownership, or making the file world readable by using ``chmod a+r
  your_script.py``.

* The web server must know that the file you're trying to access is a CGI script.
  Check the configuration of your web server, as it may be configured
  to expect a specific file extension for CGI scripts.

* On Unix-like systems, the path to the interpreter in the shebang
  (``#!/usr/bin/env python``) must be correct.  This line calls
  ``/usr/bin/env`` to find Python, but it will fail if there is no
  ``/usr/bin/env``, or if Python is not in the web server's path.  If you know
  where your Python is installed, you can also use that full path.  The
  commands ``whereis python`` and ``type -p python`` could help you find
  where it is installed.  Once you know the path, you can change the shebang
  accordingly: ``#!/usr/bin/python``.

* The file must not contain a BOM (Byte Order Mark). The BOM is meant for
  determining the byte order of UTF-16 and UTF-32 encodings, but some editors
  write this also into UTF-8 files.  The BOM interferes with the shebang line,
  so be sure to tell your editor not to write the BOM.

* If the web server is using :ref:`mod-python`, ``mod_python`` may be having
  problems.  ``mod_python`` is able to handle CGI scripts by itself, but it can
  also be a source of issues.


.. _mod-python:

mod_python
----------

People coming from PHP often find it hard to grasp how to use Python in the web.
Their first thought is mostly `mod_python <http://modpython.org/>`_\ ,
because they think that this is the equivalent to ``mod_php``.  Actually, there
are many differences.  What ``mod_python`` does is embed the interpreter into
the Apache process, thus speeding up requests by not having to start a Python
interpreter for each request.  On the other hand, it is not "Python intermixed
with HTML" in the way that PHP is often intermixed with HTML. The Python
equivalent of that is a template engine.  ``mod_python`` itself is much more
powerful and provides more access to Apache internals.  It can emulate CGI,
work in a "Python Server Pages" mode (similar to JSP) which is "HTML
intermingled with Python", and it has a "Publisher" which designates one file
to accept all requests and decide what to do with them.

``mod_python`` does have some problems.  Unlike the PHP interpreter, the Python
interpreter uses caching when executing files, so changes to a file will
require the web server to be restarted.  Another problem is the basic concept
-- Apache starts child processes to handle the requests, and unfortunately
every child process needs to load the whole Python interpreter even if it does
not use it.  This makes the whole web server slower.  Another problem is that,
because ``mod_python`` is linked against a specific version of ``libpython``,
it is not possible to switch from an older version to a newer (e.g. 2.4 to 2.5)
without recompiling ``mod_python``.  ``mod_python`` is also bound to the Apache
web server, so programs written for ``mod_python`` cannot easily run on other
web servers.

These are the reasons why ``mod_python`` should be avoided when writing new
programs.  In some circumstances it still might be a good idea to use
``mod_python`` for deployment, but WSGI makes it possible to run WSGI programs
under ``mod_python`` as well.


FastCGI and SCGI
----------------

FastCGI and SCGI try to solve the performance problem of CGI in another way.
Instead of embedding the interpreter into the web server, they create
long-running background processes. There is still a module in the web server
which makes it possible for the web server to "speak" with the background
process.  As the background process is independent of the server, it can be
written in any language, including Python.  The language just needs to have a
library which handles the communication with the webserver.

The difference between FastCGI and SCGI is very small, as SCGI is essentially
just a "simpler FastCGI".  As the web server support for SCGI is limited,
most people use FastCGI instead, which works the same way.  Almost everything
that applies to SCGI also applies to FastCGI as well, so we'll only cover
the latter.

These days, FastCGI is never used directly.  Just like ``mod_python``, it is only
used for the deployment of WSGI applications.


Setting up FastCGI
^^^^^^^^^^^^^^^^^^

Each web server requires a specific module.

* Apache has both `mod_fastcgi <http://www.fastcgi.com/drupal/>`_ and `mod_fcgid
  <https://httpd.apache.org/mod_fcgid/>`_.  ``mod_fastcgi`` is the original one, but it
  has some licensing issues, which is why it is sometimes considered non-free.
  ``mod_fcgid`` is a smaller, compatible alternative.  One of these modules needs
  to be loaded by Apache.

* lighttpd ships its own `FastCGI module
  <http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI>`_ as well as an
  `SCGI module <http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModSCGI>`_.

* `nginx <http://nginx.org/>`_ also supports `FastCGI
  <https://www.nginx.com/resources/wiki/start/topics/examples/simplepythonfcgi/>`_.

Once you have installed and configured the module, you can test it with the
following WSGI-application::

    #!/usr/bin/env python
    # -*- coding: UTF-8 -*-

    from cgi import escape
    import sys, os
    from flup.server.fcgi import WSGIServer

    def app(environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])

        yield '<h1>FastCGI Environment</h1>'
        yield '<table>'
        for k, v in sorted(environ.items()):
            yield '<tr><th>%s</th><td>%s</td></tr>' % (escape(k), escape(v))
        yield '</table>'

    WSGIServer(app).run()

This is a simple WSGI application, but you need to install `flup
<https://pypi.org/project/flup/1.0>`_ first, as flup handles the low level
FastCGI access.

.. seealso::

   There is some documentation on `setting up Django with WSGI
   <https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/>`_, most of
   which can be reused for other WSGI-compliant frameworks and libraries.
   Only the ``manage.py`` part has to be changed, the example used here can be
   used instead.  Django does more or less the exact same thing.


mod_wsgi
--------

`mod_wsgi <http://code.google.com/p/modwsgi/>`_ is an attempt to get rid of the
low level gateways.  Given that FastCGI, SCGI, and mod_python are mostly used to
deploy WSGI applications, mod_wsgi was started to directly embed WSGI applications
into the Apache web server. mod_wsgi is specifically designed to host WSGI
applications.  It makes the deployment of WSGI applications much easier than
deployment using other low level methods, which need glue code.  The downside
is that mod_wsgi is limited to the Apache web server; other servers would need
their own implementations of mod_wsgi.

mod_wsgi supports two modes: embedded mode, in which it integrates with the
Apache process, and daemon mode, which is more FastCGI-like.  Unlike FastCGI,
mod_wsgi handles the worker-processes by itself, which makes administration
easier.


.. _WSGI:

Step back: WSGI
===============

WSGI has already been mentioned several times, so it has to be something
important.  In fact it really is, and now it is time to explain it.

The *Web Server Gateway Interface*,  or WSGI for short, is defined in
:pep:`333` and is currently the best way to do Python web programming.  While
it is great for programmers writing frameworks, a normal web developer does not
need to get in direct contact with it.  When choosing a framework for web
development it is a good idea to choose one which supports WSGI.

The big benefit of WSGI is the unification of the application programming
interface.  When your program is compatible with WSGI -- which at the outer
level means that the framework you are using has support for WSGI -- your
program can be deployed via any web server interface for which there are WSGI
wrappers.  You do not need to care about whether the application user uses
mod_python or FastCGI or mod_wsgi -- with WSGI your application will work on
any gateway interface.  The Python standard library contains its own WSGI
server, :mod:`wsgiref`, which is a small web server that can be used for
testing.

A really great WSGI feature is middleware.  Middleware is a layer around your
program which can add various functionality to it.  There is quite a bit of
`middleware <https://wsgi.readthedocs.org/en/latest/libraries.html>`_ already
available.  For example, instead of writing your own session management (HTTP
is a stateless protocol, so to associate multiple HTTP requests with a single
user your application must create and manage such state via a session), you can
just download middleware which does that, plug it in, and get on with coding
the unique parts of your application.  The same thing with compression -- there
is existing middleware which handles compressing your HTML using gzip to save
on your server's bandwidth.  Authentication is another problem that is easily
solved using existing middleware.

Although WSGI may seem complex, the initial phase of learning can be very
rewarding because WSGI and the associated middleware already have solutions to
many problems that might arise while developing web sites.


WSGI Servers
------------

The code that is used to connect to various low level gateways like CGI or
mod_python is called a *WSGI server*.  One of these servers is ``flup``, which
supports FastCGI and SCGI, as well as `AJP
<https://en.wikipedia.org/wiki/Apache_JServ_Protocol>`_.  Some of these servers
are written in Python, as ``flup`` is, but there also exist others which are
written in C and can be used as drop-in replacements.

There are many servers already available, so a Python web application
can be deployed nearly anywhere.  This is one big advantage that Python has
compared with other web technologies.

.. seealso::

   A good overview of WSGI-related code can be found in the `WSGI homepage
   <https://wsgi.readthedocs.org/>`_, which contains an extensive list of `WSGI servers
   <https://wsgi.readthedocs.org/en/latest/servers.html>`_ which can be used by *any* application
   supporting WSGI.

   You might be interested in some WSGI-supporting modules already contained in
   the standard library, namely:

   * :mod:`wsgiref` -- some tiny utilities and servers for WSGI


Case study: MoinMoin
--------------------

What does WSGI give the web application developer?  Let's take a look at
an application that's been around for a while, which was written in
Python without using WSGI.

One of the most widely used wiki software packages is `MoinMoin
<https://moinmo.in/>`_.  It was created in 2000, so it predates WSGI by about
three years.  Older versions needed separate code to run on CGI, mod_python,
FastCGI and standalone.

It now includes support for WSGI.  Using WSGI, it is possible to deploy
MoinMoin on any WSGI compliant server, with no additional glue code.
Unlike the pre-WSGI versions, this could include WSGI servers that the
authors of MoinMoin know nothing about.


Model-View-Controller
=====================

The term *MVC* is often encountered in statements such as "framework *foo*
supports MVC".  MVC is more about the overall organization of code, rather than
any particular API.  Many web frameworks use this model to help the developer
bring structure to their program.  Bigger web applications can have lots of
code, so it is a good idea to have an effective structure right from the beginning.
That way, even users of other frameworks (or even other languages, since MVC is
not Python-specific) can easily understand the code, given that they are
already familiar with the MVC structure.

MVC stands for three components:

* The *model*.  This is the data that will be displayed and modified.  In
  Python frameworks, this component is often represented by the classes used by
  an object-relational mapper.

* The *view*.  This component's job is to display the data of the model to the
  user.  Typically this component is implemented via templates.

* The *controller*.  This is the layer between the user and the model.  The
  controller reacts to user actions (like opening some specific URL), tells
  the model to modify the data if necessary, and tells the view code what to
  display,

While one might think that MVC is a complex design pattern, in fact it is not.
It is used in Python because it has turned out to be useful for creating clean,
maintainable web sites.

.. note::

   While not all Python frameworks explicitly support MVC, it is often trivial
   to create a web site which uses the MVC pattern by separating the data logic
   (the model) from the user interaction logic (the controller) and the
   templates (the view).  That's why it is important not to write unnecessary
   Python code in the templates -- it works against the MVC model and creates
   chaos in the code base, making it harder to understand and modify.

.. seealso::

   The English Wikipedia has an article about the `Model-View-Controller pattern
   <https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller>`_.  It includes a long
   list of web frameworks for various programming languages.


Ingredients for Websites
========================

Websites are complex constructs, so tools have been created to help web
developers make their code easier to write and more maintainable.  Tools like
these exist for all web frameworks in all languages.  Developers are not forced
to use these tools, and often there is no "best" tool.  It is worth learning
about the available tools because they can greatly simplify the process of
developing a web site.


.. seealso::

   There are far more components than can be presented here.  The Python wiki
   has a page about these components, called
   `Web Components <https://wiki.python.org/moin/WebComponents>`_.


Templates
---------

Mixing of HTML and Python code is made possible by a few libraries.  While
convenient at first, it leads to horribly unmaintainable code.  That's why
templates exist.  Templates are, in the simplest case, just HTML files with
placeholders.  The HTML is sent to the user's browser after filling in the
placeholders.

Python already includes two ways to build simple templates::

    >>> template = "<html><body><h1>Hello %s!</h1></body></html>"
    >>> print template % "Reader"
    <html><body><h1>Hello Reader!</h1></body></html>

    >>> from string import Template
    >>> template = Template("<html><body><h1>Hello ${name}</h1></body></html>")
    >>> print template.substitute(dict(name='Dinsdale'))
    <html><body><h1>Hello Dinsdale!</h1></body></html>

To generate complex HTML based on non-trivial model data, conditional
and looping constructs like Python's *for* and *if* are generally needed.
*Template engines* support templates of this complexity.

There are a lot of template engines available for Python which can be used with
or without a `framework`_.  Some of these define a plain-text programming
language which is easy to learn, partly because it is limited in scope.
Others use XML, and the template output is guaranteed to be always be valid
XML.  There are many other variations.

Some `frameworks`_ ship their own template engine or recommend one in
particular.  In the absence of a reason to use a different template engine,
using the one provided by or recommended by the framework is a good idea.

Popular template engines include:

   * `Mako <http://www.makotemplates.org/>`_
   * `Genshi <http://genshi.edgewall.org/>`_
   * `Jinja <http://jinja.pocoo.org/>`_

.. seealso::

   There are many template engines competing for attention, because it is
   pretty easy to create them in Python.  The page `Templating
   <https://wiki.python.org/moin/Templating>`_ in the wiki lists a big,
   ever-growing number of these.  The three listed above are considered "second
   generation" template engines and are a good place to start.


Data persistence
----------------

*Data persistence*, while sounding very complicated, is just about storing data.
This data might be the text of blog entries, the postings on a bulletin board or
the text of a wiki page.  There are, of course, a number of different ways to store
information on a web server.

Often, relational database engines like `MySQL <http://www.mysql.com/>`_ or
`PostgreSQL <http://www.postgresql.org/>`_ are used because of their good
performance when handling very large databases consisting of millions of
entries.  There is also a small database engine called `SQLite
<http://www.sqlite.org/>`_, which is bundled with Python in the :mod:`sqlite3`
module, and which uses only one file.  It has no other dependencies.  For
smaller sites SQLite is just enough.

Relational databases are *queried* using a language called `SQL
<https://en.wikipedia.org/wiki/SQL>`_.  Python programmers in general do not
like SQL too much, as they prefer to work with objects.  It is possible to save
Python objects into a database using a technology called `ORM
<https://en.wikipedia.org/wiki/Object-relational_mapping>`_ (Object Relational
Mapping).  ORM translates all object-oriented access into SQL code under the
hood, so the developer does not need to think about it.  Most `frameworks`_ use
ORMs, and it works quite well.

A second possibility is storing data in normal, plain text files (some
times called "flat files").  This is very easy for simple sites,
but can be difficult to get right if the web site is performing many
updates to the stored data.

A third possibility are object oriented databases (also called "object
databases").  These databases store the object data in a form that closely
parallels the way the objects are structured in memory during program
execution.  (By contrast, ORMs store the object data as rows of data in tables
and relations between those rows.)  Storing the objects directly has the
advantage that nearly all objects can be saved in a straightforward way, unlike
in relational databases where some objects are very hard to represent.

`Frameworks`_ often give hints on which data storage method to choose.  It is
usually a good idea to stick to the data store recommended by the framework
unless the application has special requirements better satisfied by an
alternate storage mechanism.

.. seealso::

   * `Persistence Tools <https://wiki.python.org/moin/PersistenceTools>`_ lists
     possibilities on how to save data in the file system.  Some of these
     modules are part of the standard library

   * `Database Programming <https://wiki.python.org/moin/DatabaseProgramming>`_
     helps with choosing a method for saving data

   * `SQLAlchemy <http://www.sqlalchemy.org/>`_, the most powerful OR-Mapper
     for Python, and `Elixir <https://pypi.org/project/Elixir>`_, which makes
     SQLAlchemy easier to use

   * `SQLObject <http://www.sqlobject.org/>`_, another popular OR-Mapper

   * `ZODB <https://launchpad.net/zodb>`_ and `Durus
     <https://www.mems-exchange.org/software/>`_, two object oriented
     databases


.. _framework:

Frameworks
==========

The process of creating code to run web sites involves writing code to provide
various services.  The code to provide a particular service often works the
same way regardless of the complexity or purpose of the web site in question.
Abstracting these common solutions into reusable code produces what are called
"frameworks" for web development.  Perhaps the most well-known framework for
web development is Ruby on Rails, but Python has its own frameworks.  Some of
these were partly inspired by Rails, or borrowed ideas from Rails, but many
existed a long time before Rails.

Originally Python web frameworks tended to incorporate all of the services
needed to develop web sites as a giant, integrated set of tools.  No two web
frameworks were interoperable:  a program developed for one could not be
deployed on a different one without considerable re-engineering work.  This led
to the development of "minimalist" web frameworks that provided just the tools
to communicate between the Python code and the http protocol, with all other
services to be added on top via separate components.  Some ad hoc standards
were developed that allowed for limited interoperability between frameworks,
such as a standard that allowed different template engines to be used
interchangeably.

Since the advent of WSGI, the Python web framework world has been evolving
toward interoperability based on the WSGI standard.  Now many web frameworks,
whether "full stack" (providing all the tools one needs to deploy the most
complex web sites) or minimalist, or anything in between, are built from
collections of reusable components that can be used with more than one
framework.

The majority of users will probably want to select a "full stack" framework
that has an active community.  These frameworks tend to be well documented,
and provide the easiest path to producing a fully functional web site in
minimal time.


Some notable frameworks
-----------------------

There are an incredible number of frameworks, so they cannot all be covered
here.  Instead we will briefly touch on some of the most popular.


Django
^^^^^^

`Django <https://www.djangoproject.com/>`_ is a framework consisting of several
tightly coupled elements which were written from scratch and work together very
well.  It includes an ORM which is quite powerful while being simple to use,
and has a great online administration interface which makes it possible to edit
the data in the database with a browser.  The template engine is text-based and
is designed to be usable for page designers who cannot write Python.  It
supports template inheritance and filters (which work like Unix pipes).  Django
has many handy features bundled, such as creation of RSS feeds or generic views,
which make it possible to create web sites almost without writing any Python code.

It has a big, international community, the members of which have created many
web sites.  There are also a lot of add-on projects which extend Django's normal
functionality.  This is partly due to Django's well written `online
documentation <https://docs.djangoproject.com/>`_ and the `Django book
<http://www.djangobook.com/>`_.


.. note::

   Although Django is an MVC-style framework, it names the elements
   differently, which is described in the `Django FAQ
   <https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names>`_.


TurboGears
^^^^^^^^^^

Another popular web framework for Python is `TurboGears
<http://www.turbogears.org/>`_.  TurboGears takes the approach of using already
existing components and combining them with glue code to create a seamless
experience.  TurboGears gives the user flexibility in choosing components. For
example the ORM and template engine can be changed to use packages different
from those used by default.

The documentation can be found in the `TurboGears documentation
<https://turbogears.readthedocs.org/>`_, where links to screencasts can be found.
TurboGears has also an active user community which can respond to most related
questions.  There is also a `TurboGears book <http://turbogears.org/1.0/docs/TGBooks.html>`_
published, which is a good starting point.

The newest version of TurboGears, version 2.0, moves even further in direction
of WSGI support and a component-based architecture.  TurboGears 2 is based on
the WSGI stack of another popular component-based web framework, `Pylons
<http://www.pylonsproject.org/>`_.


Zope
^^^^

The Zope framework is one of the "old original" frameworks.  Its current
incarnation in Zope2 is a tightly integrated full-stack framework.  One of its
most interesting feature is its tight integration with a powerful object
database called the `ZODB <https://launchpad.net/zodb>`_ (Zope Object Database).
Because of its highly integrated nature, Zope wound up in a somewhat isolated
ecosystem:  code written for Zope wasn't very usable outside of Zope, and
vice-versa.  To solve this problem the Zope 3 effort was started.  Zope 3
re-engineers Zope as a set of more cleanly isolated components.  This effort
was started before the advent of the WSGI standard, but there is WSGI support
for Zope 3 from the `Repoze <http://repoze.org/>`_ project.  Zope components
have many years of production use behind them, and the Zope 3 project gives
access to these components to the wider Python community.  There is even a
separate framework based on the Zope components: `Grok
<http://grok.zope.org/>`_.

Zope is also the infrastructure used by the `Plone <https://plone.org/>`_ content
management system, one of the most powerful and popular content management
systems available.


Other notable frameworks
^^^^^^^^^^^^^^^^^^^^^^^^

Of course these are not the only frameworks that are available.  There are
many other frameworks worth mentioning.

Another framework that's already been mentioned is `Pylons`_.  Pylons is much
like TurboGears, but with an even stronger emphasis on flexibility, which comes
at the cost of being more difficult to use.  Nearly every component can be
exchanged, which makes it necessary to use the documentation of every single
component, of which there are many.  Pylons builds upon `Paste
<http://pythonpaste.org/>`_, an extensive set of tools which are handy for WSGI.

And that's still not everything.  The most up-to-date information can always be
found in the Python wiki.

.. seealso::

   The Python wiki contains an extensive list of `web frameworks
   <https://wiki.python.org/moin/WebFrameworks>`_.

   Most frameworks also have their own mailing lists and IRC channels, look out
   for these on the projects' web sites.
PK	%�\4g9��#html/_sources/install/index.rst.txtnu�[���.. highlightlang:: none

.. _install-index:

********************************************
  Installing Python Modules (Legacy version)
********************************************

:Author: Greg Ward

.. TODO: Fill in XXX comments

.. seealso::

   :ref:`installing-index`
      The up to date module installation documentations

.. The audience for this document includes people who don't know anything
   about Python and aren't about to learn the language just in order to
   install and maintain it for their users, i.e. system administrators.
   Thus, I have to be sure to explain the basics at some point:
   sys.path and PYTHONPATH at least.  Should probably give pointers to
   other docs on "import site", PYTHONSTARTUP, PYTHONHOME, etc.

   Finally, it might be useful to include all the material from my "Care
   and Feeding of a Python Installation" talk in here somewhere.  Yow!

This document describes the Python Distribution Utilities ("Distutils") from the
end-user's point-of-view, describing how to extend the capabilities of a
standard Python installation by building and installing third-party Python
modules and extensions.


.. note::

   This guide only covers the basic tools for building and distributing
   extensions that are provided as part of this version of Python. Third party
   tools offer easier to use and more secure alternatives. Refer to the `quick
   recommendations section <https://packaging.python.org/en/latest/current/>`__
   in the Python Packaging User Guide for more information.


.. _inst-intro:


Introduction
============

Although Python's extensive standard library covers many programming needs,
there often comes a time when you need to add some new functionality to your
Python installation in the form of third-party modules.  This might be necessary
to support your own programming, or to support an application that you want to
use and that happens to be written in Python.

In the past, there has been little support for adding third-party modules to an
existing Python installation.  With the introduction of the Python Distribution
Utilities (Distutils for short) in Python 2.0, this changed.

This document is aimed primarily at the people who need to install third-party
Python modules: end-users and system administrators who just need to get some
Python application running, and existing Python programmers who want to add some
new goodies to their toolbox.  You don't need to know Python to read this
document; there will be some brief forays into using Python's interactive mode
to explore your installation, but that's it.  If you're looking for information
on how to distribute your own Python modules so that others may use them, see
the :ref:`distutils-index` manual.  :ref:`debug-setup-script` may also be of
interest.



.. _inst-trivial-install:

Best case: trivial installation
-------------------------------

In the best case, someone will have prepared a special version of the module
distribution you want to install that is targeted specifically at your platform
and is installed just like any other software on your platform.  For example,
the module developer might make an executable installer available for Windows
users, an RPM package for users of RPM-based Linux systems (Red Hat, SuSE,
Mandrake, and many others), a Debian package for users of Debian-based Linux
systems, and so forth.

In that case, you would download the installer appropriate to your platform and
do the obvious thing with it: run it if it's an executable installer, ``rpm
--install`` it if it's an RPM, etc.  You don't need to run Python or a setup
script, you don't need to compile anything---you might not even need to read any
instructions (although it's always a good idea to do so anyway).

Of course, things will not always be that easy.  You might be interested in a
module distribution that doesn't have an easy-to-use installer for your
platform.  In that case, you'll have to start with the source distribution
released by the module's author/maintainer.  Installing from a source
distribution is not too hard, as long as the modules are packaged in the
standard way.  The bulk of this document is about building and installing
modules from standard source distributions.


.. _inst-new-standard:

The new standard: Distutils
---------------------------

If you download a module source distribution, you can tell pretty quickly if it
was packaged and distributed in the standard way, i.e. using the Distutils.
First, the distribution's name and version number will be featured prominently
in the name of the downloaded archive, e.g. :file:`foo-1.0.tar.gz` or
:file:`widget-0.9.7.zip`.  Next, the archive will unpack into a similarly-named
directory: :file:`foo-1.0` or :file:`widget-0.9.7`.  Additionally, the
distribution will contain a setup script :file:`setup.py`, and a file named
:file:`README.txt` or possibly just :file:`README`, which should explain that
building and installing the module distribution is a simple matter of running
one command from a terminal::

   python setup.py install

For Windows, this command should be run from a command prompt window
(:menuselection:`Start --> Accessories`)::

   setup.py install

If all these things are true, then you already know how to build and install the
modules you've just downloaded:  Run the command above. Unless you need to
install things in a non-standard way or customize the build process, you don't
really need this manual.  Or rather, the above command is everything you need to
get out of this manual.


.. _inst-standard-install:

Standard Build and Install
==========================

As described in section :ref:`inst-new-standard`, building and installing a module
distribution using the Distutils is usually one simple command to run from a
terminal::

   python setup.py install


.. _inst-platform-variations:

Platform variations
-------------------

You should always run the setup command from the distribution root directory,
i.e. the top-level subdirectory that the module source distribution unpacks
into.  For example, if you've just downloaded a module source distribution
:file:`foo-1.0.tar.gz` onto a Unix system, the normal thing to do is::

   gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
   cd foo-1.0
   python setup.py install

On Windows, you'd probably download :file:`foo-1.0.zip`.  If you downloaded the
archive file to :file:`C:\\Temp`, then it would unpack into
:file:`C:\\Temp\\foo-1.0`; you can use either an archive manipulator with a
graphical user interface (such as WinZip) or a command-line tool (such as
:program:`unzip` or :program:`pkunzip`) to unpack the archive.  Then, open a
command prompt window and run::

   cd c:\Temp\foo-1.0
   python setup.py install


.. _inst-splitting-up:

Splitting the job up
--------------------

Running ``setup.py install`` builds and installs all modules in one run.  If you
prefer to work incrementally---especially useful if you want to customize the
build process, or if things are going wrong---you can use the setup script to do
one thing at a time.  This is particularly helpful when the build and install
will be done by different users---for example, you might want to build a module
distribution and hand it off to a system administrator for installation (or do
it yourself, with super-user privileges).

For example, you can build everything in one step, and then install everything
in a second step, by invoking the setup script twice::

   python setup.py build
   python setup.py install

If you do this, you will notice that running the :command:`install` command
first runs the :command:`build` command, which---in this case---quickly notices
that it has nothing to do, since everything in the :file:`build` directory is
up-to-date.

You may not need this ability to break things down often if all you do is
install modules downloaded off the 'net, but it's very handy for more advanced
tasks.  If you get into distributing your own Python modules and extensions,
you'll run lots of individual Distutils commands on their own.


.. _inst-how-build-works:

How building works
------------------

As implied above, the :command:`build` command is responsible for putting the
files to install into a *build directory*.  By default, this is :file:`build`
under the distribution root; if you're excessively concerned with speed, or want
to keep the source tree pristine, you can change the build directory with the
:option:`!--build-base` option. For example::

   python setup.py build --build-base=/path/to/pybuild/foo-1.0

(Or you could do this permanently with a directive in your system or personal
Distutils configuration file; see section :ref:`inst-config-files`.)  Normally, this
isn't necessary.

The default layout for the build tree is as follows::

   --- build/ --- lib/
   or
   --- build/ --- lib.<plat>/
                  temp.<plat>/

where ``<plat>`` expands to a brief description of the current OS/hardware
platform and Python version.  The first form, with just a :file:`lib` directory,
is used for "pure module distributions"---that is, module distributions that
include only pure Python modules.  If a module distribution contains any
extensions (modules written in C/C++), then the second form, with two ``<plat>``
directories, is used.  In that case, the :file:`temp.{plat}` directory holds
temporary files generated by the compile/link process that don't actually get
installed.  In either case, the :file:`lib` (or :file:`lib.{plat}`) directory
contains all Python modules (pure Python and extensions) that will be installed.

In the future, more directories will be added to handle Python scripts,
documentation, binary executables, and whatever else is needed to handle the job
of installing Python modules and applications.


.. _inst-how-install-works:

How installation works
----------------------

After the :command:`build` command runs (whether you run it explicitly, or the
:command:`install` command does it for you), the work of the :command:`install`
command is relatively simple: all it has to do is copy everything under
:file:`build/lib` (or :file:`build/lib.{plat}`) to your chosen installation
directory.

If you don't choose an installation directory---i.e., if you just run ``setup.py
install``\ ---then the :command:`install` command installs to the standard
location for third-party Python modules.  This location varies by platform and
by how you built/installed Python itself.  On Unix (and Mac OS X, which is also
Unix-based), it also depends on whether the module distribution being installed
is pure Python or contains extensions ("non-pure"):

.. tabularcolumns:: |l|l|l|l|

+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
| Platform        | Standard installation location                      | Default value                                    | Notes |
+=================+=====================================================+==================================================+=======+
| Unix (pure)     | :file:`{prefix}/lib/python{X.Y}/site-packages`      | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1)  |
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
| Unix (non-pure) | :file:`{exec-prefix}/lib/python{X.Y}/site-packages` | :file:`/usr/local/lib/python{X.Y}/site-packages` | \(1)  |
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+
| Windows         | :file:`{prefix}\\Lib\\site-packages`                | :file:`C:\\Python{XY}\\Lib\\site-packages`       | \(2)  |
+-----------------+-----------------------------------------------------+--------------------------------------------------+-------+

Notes:

(1)
   Most Linux distributions include Python as a standard part of the system, so
   :file:`{prefix}` and :file:`{exec-prefix}` are usually both :file:`/usr` on
   Linux.  If you build Python yourself on Linux (or any Unix-like system), the
   default :file:`{prefix}` and :file:`{exec-prefix}` are :file:`/usr/local`.

(2)
   The default installation directory on Windows was :file:`C:\\Program
   Files\\Python` under Python 1.6a1, 1.5.2, and earlier.

:file:`{prefix}` and :file:`{exec-prefix}` stand for the directories that Python
is installed to, and where it finds its libraries at run-time.  They are always
the same under Windows, and very often the same under Unix and Mac OS X.  You
can find out what your Python installation uses for :file:`{prefix}` and
:file:`{exec-prefix}` by running Python in interactive mode and typing a few
simple commands. Under Unix, just type ``python`` at the shell prompt.  Under
Windows, choose :menuselection:`Start --> Programs --> Python X.Y -->
Python (command line)`.   Once the interpreter is started, you type Python code
at the prompt.  For example, on my Linux system, I type the three Python
statements shown below, and get the output as shown, to find out my
:file:`{prefix}` and :file:`{exec-prefix}`::

   Python 2.4 (#26, Aug  7 2004, 17:19:02)
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import sys
   >>> sys.prefix
   '/usr'
   >>> sys.exec_prefix
   '/usr'

A few other placeholders are used in this document: :file:`{X.Y}` stands for the
version of Python, for example ``2.7``; :file:`{distname}` will be replaced by
the name of the module distribution being installed.  Dots and capitalization
are important in the paths; for example, a value that uses ``python2.7`` on UNIX
will typically use ``Python27`` on Windows.

If you don't want to install modules to the standard location, or if you don't
have permission to write there, then you need to read about alternate
installations in section :ref:`inst-alt-install`.  If you want to customize your
installation directories more heavily, see section :ref:`inst-custom-install` on
custom installations.


.. _inst-alt-install:

Alternate Installation
======================

Often, it is necessary or desirable to install modules to a location other than
the standard location for third-party Python modules.  For example, on a Unix
system you might not have permission to write to the standard third-party module
directory.  Or you might wish to try out a module before making it a standard
part of your local Python installation.  This is especially true when upgrading
a distribution already present: you want to make sure your existing base of
scripts still works with the new version before actually upgrading.

The Distutils :command:`install` command is designed to make installing module
distributions to an alternate location simple and painless.  The basic idea is
that you supply a base directory for the installation, and the
:command:`install` command picks a set of directories (called an *installation
scheme*) under this base directory in which to install files.  The details
differ across platforms, so read whichever of the following sections applies to
you.

Note that the various alternate installation schemes are mutually exclusive: you
can pass ``--user``, or ``--home``, or ``--prefix`` and ``--exec-prefix``, or
``--install-base`` and ``--install-platbase``, but you can't mix from these
groups.


.. _inst-alt-install-user:

Alternate installation: the user scheme
---------------------------------------

This scheme is designed to be the most convenient solution for users that don't
have write permission to the global site-packages directory or don't want to
install into it.  It is enabled with a simple option::

   python setup.py install --user

Files will be installed into subdirectories of :data:`site.USER_BASE` (written
as :file:`{userbase}` hereafter).  This scheme installs pure Python modules and
extension modules in the same location (also known as :data:`site.USER_SITE`).
Here are the values for UNIX, including Mac OS X:

=============== ===========================================================
Type of file    Installation directory
=============== ===========================================================
modules         :file:`{userbase}/lib/python{X.Y}/site-packages`
scripts         :file:`{userbase}/bin`
data            :file:`{userbase}`
C headers       :file:`{userbase}/include/python{X.Y}/{distname}`
=============== ===========================================================

And here are the values used on Windows:

=============== ===========================================================
Type of file    Installation directory
=============== ===========================================================
modules         :file:`{userbase}\\Python{XY}\\site-packages`
scripts         :file:`{userbase}\\Scripts`
data            :file:`{userbase}`
C headers       :file:`{userbase}\\Python{XY}\\Include\\{distname}`
=============== ===========================================================

The advantage of using this scheme compared to the other ones described below is
that the user site-packages directory is under normal conditions always included
in :data:`sys.path` (see :mod:`site` for more information), which means that
there is no additional step to perform after running the :file:`setup.py` script
to finalize the installation.

The :command:`build_ext` command also has a ``--user`` option to add
:file:`{userbase}/include` to the compiler search path for header files and
:file:`{userbase}/lib` to the compiler search path for libraries as well as to
the runtime search path for shared C libraries (rpath).


.. _inst-alt-install-home:

Alternate installation: the home scheme
---------------------------------------

The idea behind the "home scheme" is that you build and maintain a personal
stash of Python modules.  This scheme's name is derived from the idea of a
"home" directory on Unix, since it's not unusual for a Unix user to make their
home directory have a layout similar to :file:`/usr/` or :file:`/usr/local/`.
This scheme can be used by anyone, regardless of the operating system they
are installing for.

Installing a new module distribution is as simple as ::

   python setup.py install --home=<dir>

where you can supply any directory you like for the :option:`!--home` option.  On
Unix, lazy typists can just type a tilde (``~``); the :command:`install` command
will expand this to your home directory::

   python setup.py install --home=~

To make Python find the distributions installed with this scheme, you may have
to :ref:`modify Python's search path <inst-search-path>` or edit
:mod:`sitecustomize` (see :mod:`site`) to call :func:`site.addsitedir` or edit
:data:`sys.path`.

The :option:`!--home` option defines the installation base directory.  Files are
installed to the following directories under the installation base as follows:

=============== ===========================================================
Type of file    Installation directory
=============== ===========================================================
modules         :file:`{home}/lib/python`
scripts         :file:`{home}/bin`
data            :file:`{home}`
C headers       :file:`{home}/include/python/{distname}`
=============== ===========================================================

(Mentally replace slashes with backslashes if you're on Windows.)

.. versionchanged:: 2.4
   The :option:`!--home` option used to be supported only on Unix.


.. _inst-alt-install-prefix-unix:

Alternate installation: Unix (the prefix scheme)
------------------------------------------------

The "prefix scheme" is useful when you wish to use one Python installation to
perform the build/install (i.e., to run the setup script), but install modules
into the third-party module directory of a different Python installation (or
something that looks like a different Python installation).  If this sounds a
trifle unusual, it is---that's why the user and home schemes come before.  However,
there are at least two known cases where the prefix scheme will be useful.

First, consider that many Linux distributions put Python in :file:`/usr`, rather
than the more traditional :file:`/usr/local`.  This is entirely appropriate,
since in those cases Python is part of "the system" rather than a local add-on.
However, if you are installing Python modules from source, you probably want
them to go in :file:`/usr/local/lib/python2.{X}` rather than
:file:`/usr/lib/python2.{X}`.  This can be done with ::

   /usr/bin/python setup.py install --prefix=/usr/local

Another possibility is a network filesystem where the name used to write to a
remote directory is different from the name used to read it: for example, the
Python interpreter accessed as :file:`/usr/local/bin/python` might search for
modules in :file:`/usr/local/lib/python2.{X}`, but those modules would have to
be installed to, say, :file:`/mnt/{@server}/export/lib/python2.{X}`.  This could
be done with ::

   /usr/local/bin/python setup.py install --prefix=/mnt/@server/export

In either case, the :option:`!--prefix` option defines the installation base, and
the :option:`!--exec-prefix` option defines the platform-specific installation
base, which is used for platform-specific files.  (Currently, this just means
non-pure module distributions, but could be expanded to C libraries, binary
executables, etc.)  If :option:`!--exec-prefix` is not supplied, it defaults to
:option:`!--prefix`.  Files are installed as follows:

================= ==========================================================
Type of file      Installation directory
================= ==========================================================
Python modules    :file:`{prefix}/lib/python{X.Y}/site-packages`
extension modules :file:`{exec-prefix}/lib/python{X.Y}/site-packages`
scripts           :file:`{prefix}/bin`
data              :file:`{prefix}`
C headers         :file:`{prefix}/include/python{X.Y}/{distname}`
================= ==========================================================

There is no requirement that :option:`!--prefix` or :option:`!--exec-prefix`
actually point to an alternate Python installation; if the directories listed
above do not already exist, they are created at installation time.

Incidentally, the real reason the prefix scheme is important is simply that a
standard Unix installation uses the prefix scheme, but with :option:`!--prefix`
and :option:`!--exec-prefix` supplied by Python itself as ``sys.prefix`` and
``sys.exec_prefix``.  Thus, you might think you'll never use the prefix scheme,
but every time you run ``python setup.py install`` without any other options,
you're using it.

Note that installing extensions to an alternate Python installation has no
effect on how those extensions are built: in particular, the Python header files
(:file:`Python.h` and friends) installed with the Python interpreter used to run
the setup script will be used in compiling extensions.  It is your
responsibility to ensure that the interpreter used to run extensions installed
in this way is compatible with the interpreter used to build them.  The best way
to do this is to ensure that the two interpreters are the same version of Python
(possibly different builds, or possibly copies of the same build).  (Of course,
if your :option:`!--prefix` and :option:`!--exec-prefix` don't even point to an
alternate Python installation, this is immaterial.)


.. _inst-alt-install-prefix-windows:

Alternate installation: Windows (the prefix scheme)
---------------------------------------------------

Windows has no concept of a user's home directory, and since the standard Python
installation under Windows is simpler than under Unix, the :option:`!--prefix`
option has traditionally been used to install additional packages in separate
locations on Windows. ::

   python setup.py install --prefix="\Temp\Python"

to install modules to the :file:`\\Temp\\Python` directory on the current drive.

The installation base is defined by the :option:`!--prefix` option; the
:option:`!--exec-prefix` option is not supported under Windows, which means that
pure Python modules and extension modules are installed into the same location.
Files are installed as follows:

=============== ==========================================================
Type of file    Installation directory
=============== ==========================================================
modules         :file:`{prefix}\\Lib\\site-packages`
scripts         :file:`{prefix}\\Scripts`
data            :file:`{prefix}`
C headers       :file:`{prefix}\\Include\\{distname}`
=============== ==========================================================


.. _inst-custom-install:

Custom Installation
===================

Sometimes, the alternate installation schemes described in section
:ref:`inst-alt-install` just don't do what you want.  You might want to tweak just
one or two directories while keeping everything under the same base directory,
or you might want to completely redefine the installation scheme.  In either
case, you're creating a *custom installation scheme*.

To create a custom installation scheme, you start with one of the alternate
schemes and override some of the installation directories used for the various
types of files, using these options:

====================== =======================
Type of file           Override option
====================== =======================
Python modules         ``--install-purelib``
extension modules      ``--install-platlib``
all modules            ``--install-lib``
scripts                ``--install-scripts``
data                   ``--install-data``
C headers              ``--install-headers``
====================== =======================

These override options can be relative, absolute,
or explicitly defined in terms of one of the installation base directories.
(There are two installation base directories, and they are normally the same---
they only differ when you use the Unix "prefix scheme" and supply different
``--prefix`` and ``--exec-prefix`` options; using ``--install-lib`` will
override values computed or given for ``--install-purelib`` and
``--install-platlib``, and is recommended for schemes that don't make a
difference between Python and extension modules.)

For example, say you're installing a module distribution to your home directory
under Unix---but you want scripts to go in :file:`~/scripts` rather than
:file:`~/bin`. As you might expect, you can override this directory with the
:option:`!--install-scripts` option; in this case, it makes most sense to supply
a relative path, which will be interpreted relative to the installation base
directory (your home directory, in this case)::

   python setup.py install --home=~ --install-scripts=scripts

Another Unix example: suppose your Python installation was built and installed
with a prefix of :file:`/usr/local/python`, so under a standard  installation
scripts will wind up in :file:`/usr/local/python/bin`.  If you want them in
:file:`/usr/local/bin` instead, you would supply this absolute directory for the
:option:`!--install-scripts` option::

   python setup.py install --install-scripts=/usr/local/bin

(This performs an installation using the "prefix scheme," where the prefix is
whatever your Python interpreter was installed with--- :file:`/usr/local/python`
in this case.)

If you maintain Python on Windows, you might want third-party modules to live in
a subdirectory of :file:`{prefix}`, rather than right in :file:`{prefix}`
itself.  This is almost as easy as customizing the script installation directory
---you just have to remember that there are two types of modules to worry about,
Python and extension modules, which can conveniently be both controlled by one
option::

   python setup.py install --install-lib=Site

The specified installation directory is relative to :file:`{prefix}`.  Of
course, you also have to ensure that this directory is in Python's module
search path, such as by putting a :file:`.pth` file in a site directory (see
:mod:`site`).  See section :ref:`inst-search-path` to find out how to modify
Python's search path.

If you want to define an entire installation scheme, you just have to supply all
of the installation directory options.  The recommended way to do this is to
supply relative paths; for example, if you want to maintain all Python
module-related files under :file:`python` in your home directory, and you want a
separate directory for each platform that you use your home directory from, you
might define the following installation scheme::

   python setup.py install --home=~ \
                           --install-purelib=python/lib \
                           --install-platlib=python/lib.$PLAT \
                           --install-scripts=python/scripts
                           --install-data=python/data

or, equivalently, ::

   python setup.py install --home=~/python \
                           --install-purelib=lib \
                           --install-platlib='lib.$PLAT' \
                           --install-scripts=scripts
                           --install-data=data

``$PLAT`` is not (necessarily) an environment variable---it will be expanded by
the Distutils as it parses your command line options, just as it does when
parsing your configuration file(s).

Obviously, specifying the entire installation scheme every time you install a
new module distribution would be very tedious.  Thus, you can put these options
into your Distutils config file (see section :ref:`inst-config-files`)::

   [install]
   install-base=$HOME
   install-purelib=python/lib
   install-platlib=python/lib.$PLAT
   install-scripts=python/scripts
   install-data=python/data

or, equivalently, ::

   [install]
   install-base=$HOME/python
   install-purelib=lib
   install-platlib=lib.$PLAT
   install-scripts=scripts
   install-data=data

Note that these two are *not* equivalent if you supply a different installation
base directory when you run the setup script.  For example, ::

   python setup.py install --install-base=/tmp

would install pure modules to :file:`/tmp/python/lib` in the first case, and
to :file:`/tmp/lib` in the second case.  (For the second case, you probably
want to supply an installation base of :file:`/tmp/python`.)

You probably noticed the use of ``$HOME`` and ``$PLAT`` in the sample
configuration file input.  These are Distutils configuration variables, which
bear a strong resemblance to environment variables. In fact, you can use
environment variables in config files on platforms that have such a notion but
the Distutils additionally define a few extra variables that may not be in your
environment, such as ``$PLAT``.  (And of course, on systems that don't have
environment variables, such as Mac OS 9, the configuration variables supplied by
the Distutils are the only ones you can use.) See section :ref:`inst-config-files`
for details.

.. XXX need some Windows examples---when would custom installation schemes be
   needed on those platforms?


.. XXX Move this to Doc/using

.. _inst-search-path:

Modifying Python's Search Path
------------------------------

When the Python interpreter executes an :keyword:`import` statement, it searches
for both Python code and extension modules along a search path.  A default value
for the path is configured into the Python binary when the interpreter is built.
You can determine the path by importing the :mod:`sys` module and printing the
value of ``sys.path``.   ::

   $ python
   Python 2.2 (#11, Oct  3 2002, 13:31:27)
   [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
   Type "help", "copyright", "credits" or "license" for more information.
   >>> import sys
   >>> sys.path
   ['', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2',
    '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload',
    '/usr/local/lib/python2.3/site-packages']
   >>>

The null string in ``sys.path`` represents the current working directory.

The expected convention for locally installed packages is to put them in the
:file:`{...}/site-packages/` directory, but you may want to install Python
modules into some arbitrary directory.  For example, your site may have a
convention of keeping all software related to the web server under :file:`/www`.
Add-on Python modules might then belong in :file:`/www/python`, and in order to
import them, this directory must be added to ``sys.path``.  There are several
different ways to add the directory.

The most convenient way is to add a path configuration file to a directory
that's already on Python's path, usually to the :file:`.../site-packages/`
directory.  Path configuration files have an extension of :file:`.pth`, and each
line must contain a single path that will be appended to ``sys.path``.  (Because
the new paths are appended to ``sys.path``, modules in the added directories
will not override standard modules.  This means you can't use this mechanism for
installing fixed versions of standard modules.)

Paths can be absolute or relative, in which case they're relative to the
directory containing the :file:`.pth` file.  See the documentation of
the :mod:`site` module for more information.

A slightly less convenient way is to edit the :file:`site.py` file in Python's
standard library, and modify ``sys.path``.  :file:`site.py` is automatically
imported when the Python interpreter is executed, unless the :option:`-S` switch
is supplied to suppress this behaviour.  So you could simply edit
:file:`site.py` and add two lines to it::

   import sys
   sys.path.append('/www/python/')

However, if you reinstall the same major version of Python (perhaps when
upgrading from 2.2 to 2.2.2, for example) :file:`site.py` will be overwritten by
the stock version.  You'd have to remember that it was modified and save a copy
before doing the installation.

There are two environment variables that can modify ``sys.path``.
:envvar:`PYTHONHOME` sets an alternate value for the prefix of the Python
installation.  For example, if :envvar:`PYTHONHOME` is set to ``/www/python``,
the search path will be set to ``['', '/www/python/lib/pythonX.Y/',
'/www/python/lib/pythonX.Y/plat-linux2', ...]``.

The :envvar:`PYTHONPATH` variable can be set to a list of paths that will be
added to the beginning of ``sys.path``.  For example, if :envvar:`PYTHONPATH` is
set to ``/www/python:/opt/py``, the search path will begin with
``['/www/python', '/opt/py']``.  (Note that directories must exist in order to
be added to ``sys.path``; the :mod:`site` module removes paths that don't
exist.)

Finally, ``sys.path`` is just a regular Python list, so any Python application
can modify it by adding or removing entries.


.. _inst-config-files:

Distutils Configuration Files
=============================

As mentioned above, you can use Distutils configuration files to record personal
or site preferences for any Distutils options.  That is, any option to any
command can be stored in one of two or three (depending on your platform)
configuration files, which will be consulted before the command-line is parsed.
This means that configuration files will override default values, and the
command-line will in turn override configuration files.  Furthermore, if
multiple configuration files apply, values from "earlier" files are overridden
by "later" files.


.. _inst-config-filenames:

Location and names of config files
----------------------------------

The names and locations of the configuration files vary slightly across
platforms.  On Unix and Mac OS X, the three configuration files (in the order
they are processed) are:

+--------------+----------------------------------------------------------+-------+
| Type of file | Location and filename                                    | Notes |
+==============+==========================================================+=======+
| system       | :file:`{prefix}/lib/python{ver}/distutils/distutils.cfg` | \(1)  |
+--------------+----------------------------------------------------------+-------+
| personal     | :file:`$HOME/.pydistutils.cfg`                           | \(2)  |
+--------------+----------------------------------------------------------+-------+
| local        | :file:`setup.cfg`                                        | \(3)  |
+--------------+----------------------------------------------------------+-------+

And on Windows, the configuration files are:

+--------------+-------------------------------------------------+-------+
| Type of file | Location and filename                           | Notes |
+==============+=================================================+=======+
| system       | :file:`{prefix}\\Lib\\distutils\\distutils.cfg` | \(4)  |
+--------------+-------------------------------------------------+-------+
| personal     | :file:`%HOME%\\pydistutils.cfg`                 | \(5)  |
+--------------+-------------------------------------------------+-------+
| local        | :file:`setup.cfg`                               | \(3)  |
+--------------+-------------------------------------------------+-------+

On all platforms, the "personal" file can be temporarily disabled by
passing the `--no-user-cfg` option.

Notes:

(1)
   Strictly speaking, the system-wide configuration file lives in the directory
   where the Distutils are installed; under Python 1.6 and later on Unix, this is
   as shown. For Python 1.5.2, the Distutils will normally be installed to
   :file:`{prefix}/lib/python1.5/site-packages/distutils`, so the system
   configuration file should be put there under Python 1.5.2.

(2)
   On Unix, if the :envvar:`HOME` environment variable is not defined, the user's
   home directory will be determined with the :func:`getpwuid` function from the
   standard :mod:`pwd` module. This is done by the :func:`os.path.expanduser`
   function used by Distutils.

(3)
   I.e., in the current directory (usually the location of the setup script).

(4)
   (See also note (1).)  Under Python 1.6 and later, Python's default "installation
   prefix" is :file:`C:\\Python`, so the system configuration file is normally
   :file:`C:\\Python\\Lib\\distutils\\distutils.cfg`. Under Python 1.5.2, the
   default prefix was :file:`C:\\Program Files\\Python`, and the Distutils were not
   part of the standard library---so the system configuration file would be
   :file:`C:\\Program Files\\Python\\distutils\\distutils.cfg` in a standard Python
   1.5.2 installation under Windows.

(5)
   On Windows, if the :envvar:`HOME` environment variable is not defined,
   :envvar:`USERPROFILE` then :envvar:`HOMEDRIVE` and :envvar:`HOMEPATH` will
   be tried. This is done by the :func:`os.path.expanduser` function used
   by Distutils.


.. _inst-config-syntax:

Syntax of config files
----------------------

The Distutils configuration files all have the same syntax.  The config files
are grouped into sections.  There is one section for each Distutils command,
plus a ``global`` section for global options that affect every command.  Each
section consists of one option per line, specified as ``option=value``.

For example, the following is a complete config file that just forces all
commands to run quietly by default::

   [global]
   verbose=0

If this is installed as the system config file, it will affect all processing of
any Python module distribution by any user on the current system.  If it is
installed as your personal config file (on systems that support them), it will
affect only module distributions processed by you.  And if it is used as the
:file:`setup.cfg` for a particular module distribution, it affects only that
distribution.

You could override the default "build base" directory and make the
:command:`build\*` commands always forcibly rebuild all files with the
following::

   [build]
   build-base=blib
   force=1

which corresponds to the command-line arguments ::

   python setup.py build --build-base=blib --force

except that including the :command:`build` command on the command-line means
that command will be run.  Including a particular command in config files has no
such implication; it only means that if the command is run, the options in the
config file will apply.  (Or if other commands that derive values from it are
run, they will use the values in the config file.)

You can find out the complete list of options for any command using the
:option:`!--help` option, e.g.::

   python setup.py build --help

and you can find out the complete list of global options by using
:option:`!--help` without a command::

   python setup.py --help

See also the "Reference" section of the "Distributing Python Modules" manual.


.. _inst-building-ext:

Building Extensions: Tips and Tricks
====================================

Whenever possible, the Distutils try to use the configuration information made
available by the Python interpreter used to run the :file:`setup.py` script.
For example, the same compiler and linker flags used to compile Python will also
be used for compiling extensions.  Usually this will work well, but in
complicated situations this might be inappropriate.  This section discusses how
to override the usual Distutils behaviour.


.. _inst-tweak-flags:

Tweaking compiler/linker flags
------------------------------

Compiling a Python extension written in C or C++ will sometimes require
specifying custom flags for the compiler and linker in order to use a particular
library or produce a special kind of object code. This is especially true if the
extension hasn't been tested on your platform, or if you're trying to
cross-compile Python.

In the most general case, the extension author might have foreseen that
compiling the extensions would be complicated, and provided a :file:`Setup` file
for you to edit.  This will likely only be done if the module distribution
contains many separate extension modules, or if they often require elaborate
sets of compiler flags in order to work.

A :file:`Setup` file, if present, is parsed in order to get a list of extensions
to build.  Each line in a :file:`Setup` describes a single module.  Lines have
the following structure::

   module ... [sourcefile ...] [cpparg ...] [library ...]


Let's examine each of the fields in turn.

* *module* is the name of the extension module to be built, and should be a
  valid Python identifier.  You can't just change this in order to rename a module
  (edits to the source code would also be needed), so this should be left alone.

* *sourcefile* is anything that's likely to be a source code file, at least
  judging by the filename.  Filenames ending in :file:`.c` are assumed to be
  written in C, filenames ending in :file:`.C`, :file:`.cc`, and :file:`.c++` are
  assumed to be C++, and filenames ending in :file:`.m` or :file:`.mm` are assumed
  to be in Objective C.

* *cpparg* is an argument for the C preprocessor,  and is anything starting with
  :option:`!-I`, :option:`!-D`, :option:`!-U` or :option:`!-C`.

* *library* is anything ending in :file:`.a` or beginning with :option:`!-l` or
  :option:`!-L`.

If a particular platform requires a special library on your platform, you can
add it by editing the :file:`Setup` file and running ``python setup.py build``.
For example, if the module defined by the line ::

   foo foomodule.c

must be linked with the math library :file:`libm.a` on your platform, simply add
:option:`!-lm` to the line::

   foo foomodule.c -lm

Arbitrary switches intended for the compiler or the linker can be supplied with
the :option:`!-Xcompiler` *arg* and :option:`!-Xlinker` *arg* options::

   foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm

The next option after :option:`!-Xcompiler` and :option:`!-Xlinker` will be
appended to the proper command line, so in the above example the compiler will
be passed the :option:`!-o32` option, and the linker will be passed
:option:`!-shared`.  If a compiler option requires an argument, you'll have to
supply multiple :option:`!-Xcompiler` options; for example, to pass ``-x c++``
the :file:`Setup` file would have to contain ``-Xcompiler -x -Xcompiler c++``.

Compiler flags can also be supplied through setting the :envvar:`CFLAGS`
environment variable.  If set, the contents of :envvar:`CFLAGS` will be added to
the compiler flags specified in the  :file:`Setup` file.


.. _inst-non-ms-compilers:

Using non-Microsoft compilers on Windows
----------------------------------------

.. sectionauthor:: Rene Liebscher <R.Liebscher@gmx.de>



Borland/CodeGear C++
^^^^^^^^^^^^^^^^^^^^

This subsection describes the necessary steps to use Distutils with the Borland
C++ compiler version 5.5.  First you have to know that Borland's object file
format (OMF) is different from the format used by the Python version you can
download from the Python or ActiveState Web site.  (Python is built with
Microsoft Visual C++, which uses COFF as the object file format.) For this
reason you have to convert Python's library :file:`python25.lib` into the
Borland format.  You can do this as follows:

.. Should we mention that users have to create cfg-files for the compiler?
.. see also http://community.borland.com/article/0,1410,21205,00.html

::

   coff2omf python25.lib python25_bcpp.lib

The :file:`coff2omf` program comes with the Borland compiler.  The file
:file:`python25.lib` is in the :file:`Libs` directory of your Python
installation.  If your extension uses other libraries (zlib, ...) you have to
convert them too.

The converted files have to reside in the same directories as the normal
libraries.

How does Distutils manage to use these libraries with their changed names?  If
the extension needs a library (eg. :file:`foo`) Distutils checks first if it
finds a library with suffix :file:`_bcpp` (eg. :file:`foo_bcpp.lib`) and then
uses this library.  In the case it doesn't find such a special library it uses
the default name (:file:`foo.lib`.) [#]_

To let Distutils compile your extension with Borland C++ you now have to type::

   python setup.py build --compiler=bcpp

If you want to use the Borland C++ compiler as the default, you could specify
this in your personal or system-wide configuration file for Distutils (see
section :ref:`inst-config-files`.)


.. seealso::

   `C++Builder Compiler <https://www.embarcadero.com/products>`_
      Information about the free C++ compiler from Borland, including links to the
      download pages.

   `Creating Python Extensions Using Borland's Free Compiler <http://www.cyberus.ca/~g_will/pyExtenDL.shtml>`_
      Document describing how to use Borland's free command-line C++ compiler to build
      Python.


GNU C / Cygwin / MinGW
^^^^^^^^^^^^^^^^^^^^^^

This section describes the necessary steps to use Distutils with the GNU C/C++
compilers in their Cygwin and MinGW distributions. [#]_ For a Python interpreter
that was built with Cygwin, everything should work without any of these
following steps.

Not all extensions can be built with MinGW or Cygwin, but many can.  Extensions
most likely to not work are those that use C++ or depend on Microsoft Visual C
extensions.

To let Distutils compile your extension with Cygwin you have to type::

   python setup.py build --compiler=cygwin

and for Cygwin in no-cygwin mode [#]_ or for MinGW type::

   python setup.py build --compiler=mingw32

If you want to use any of these options/compilers as default, you should
consider writing it in your personal or system-wide configuration file for
Distutils (see section :ref:`inst-config-files`.)

Older Versions of Python and MinGW
""""""""""""""""""""""""""""""""""
The following instructions only apply if you're using a version of Python
inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with
binutils-2.13.90-20030111-1).

These compilers require some special libraries.  This task is more complex than
for Borland's C++, because there is no program to convert the library.  First
you have to create a list of symbols which the Python DLL exports. (You can find
a good program for this task at
https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/).

.. I don't understand what the next line means. --amk
.. (inclusive the references on data structures.)

::

   pexports python25.dll >python25.def

The location of an installed :file:`python25.dll` will depend on the
installation options and the version and language of Windows.  In a "just for
me" installation, it will appear in the root of the installation directory.  In
a shared installation, it will be located in the system directory.

Then you can create from these information an import library for gcc. ::

   /cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a

The resulting library has to be placed in the same directory as
:file:`python25.lib`. (Should be the :file:`libs` directory under your Python
installation directory.)

If your extension uses other libraries (zlib,...) you might  have to convert
them too. The converted files have to reside in the same directories as the
normal libraries do.


.. seealso::

   `Building Python modules on MS Windows platform with MinGW <http://old.zope.org/Members/als/tips/win32_mingw_modules>`_
      Information about building the required libraries for the MinGW environment.


.. rubric:: Footnotes

.. [#] This also means you could replace all existing COFF-libraries with OMF-libraries
   of the same name.

.. [#] Check https://www.sourceware.org/cygwin/ and http://www.mingw.org/ for more
   information

.. [#] Then you have no POSIX emulation available, but you also don't need
   :file:`cygwin1.dll`.
PK	%�\����"�"&html/_sources/installing/index.rst.txtnu�[���.. highlightlang:: none

.. _installing-index:

*****************************
  Installing Python Modules
*****************************

:Email: distutils-sig@python.org

As a popular open source development project, Python has an active
supporting community of contributors and users that also make their software
available for other Python developers to use under open source license terms.

This allows Python users to share and collaborate effectively, benefiting
from the solutions others have already created to common (and sometimes
even rare!) problems, as well as potentially contributing their own
solutions to the common pool.

This guide covers the installation part of the process. For a guide to
creating and sharing your own Python projects, refer to the
:ref:`distribution guide <distributing-index>`.

.. note::

   For corporate and other institutional users, be aware that many
   organisations have their own policies around using and contributing to
   open source software. Please take such policies into account when making
   use of the distribution and installation tools provided with Python.


Key terms
=========

* ``pip`` is the preferred installer program. Starting with Python 2.7.9, it
  is included by default with the Python binary installers.
* a virtual environment is a semi-isolated Python environment that allows
  packages to be installed for use by a particular application, rather than
  being installed system wide
* ``virtualenv`` is a third party tools for creating virtual environments, it
  is defaults to installing ``pip`` into all created virtual environments.
* the `Python Packaging Index <https://pypi.org>`__ is a public repository of
  open source licensed packages made available for use by other Python users
* the `Python Packaging Authority
  <https://www.pypa.io/en/latest/>`__ are the group of
  developers and documentation authors responsible for the maintenance and
  evolution of the standard packaging tools and the associated metadata and
  file format standards. They maintain a variety of tools, documentation
  and issue trackers on both `GitHub <https://github.com/pypa>`__ and
  `BitBucket <https://bitbucket.org/pypa/>`__.
* ``distutils`` is the original build and distribution system first added to
  the Python standard library in 1998. While direct use of ``distutils`` is
  being phased out, it still laid the foundation for the current packaging
  and distribution infrastructure, and it not only remains part of the
  standard library, but its name lives on in other ways (such as the name
  of the mailing list used to coordinate Python packaging standards
  development).


Basic usage
===========

The standard packaging tools are all designed to be used from the command
line.

The following command will install the latest version of a module and its
dependencies from the Python Packaging Index::

    python -m pip install SomePackage

.. note::

   For POSIX users (including Mac OS X and Linux users), the examples in
   this guide assume the use of a :term:`virtual environment`. You may install
   ``virtualenv`` to provide such environments using either pip
   (``pip install virtualenv``) or through your system package manager
   (commonly called ``virtualenv`` or ``python-virtualenv``).

   For Windows users, the examples in this guide assume that the option to
   adjust the system PATH environment variable was selected when installing
   Python.

It's also possible to specify an exact or minimum version directly on the
command line. When using comparator operators such as ``>``, ``<`` or some other
special character which get interpreted by shell, the package name and the
version should be enclosed within double quotes::

    python -m pip install SomePackage==1.0.4    # specific version
    python -m pip install "SomePackage>=1.0.4"  # minimum version

Normally, if a suitable module is already installed, attempting to install
it again will have no effect. Upgrading existing modules must be requested
explicitly::

    python -m pip install --upgrade SomePackage

More information and resources regarding ``pip`` and its capabilities can be
found in the `Python Packaging User Guide <https://packaging.python.org>`__.

.. seealso::

    `Python Packaging User Guide: Installing Python Distribution Packages
    <https://packaging.python.org/en/latest/installing/>`__


How do I ...?
=============

These are quick answers or links for some common tasks.

... install ``pip`` in versions of Python prior to Python 2.7.9?
----------------------------------------------------------------

Python only started bundling ``pip`` with Python 2.7.9. For earlier versions,
``pip`` needs to be "bootstrapped" as described in the Python Packaging
User Guide.

.. seealso::

   `Python Packaging User Guide: Requirements for Installing Packages
   <https://packaging.python.org/en/latest/installing/#requirements-for-installing-packages>`__


.. installing-per-user-installation:

... install packages just for the current user?
-----------------------------------------------

Passing the ``--user`` option to ``python -m pip install`` will install a
package just for the current user, rather than for all users of the system.


... install scientific Python packages?
---------------------------------------

A number of scientific Python packages have complex binary dependencies, and
aren't currently easy to install using ``pip`` directly. At this point in
time, it will often be easier for users to install these packages by
`other means
<https://packaging.python.org/en/latest/science/>`__
rather than attempting to install them with ``pip``.

.. seealso::

   `Python Packaging User Guide: Installing Scientific Packages
   <https://packaging.python.org/en/latest/science/>`__


... work with multiple versions of Python installed in parallel?
----------------------------------------------------------------

On Linux, Mac OS X and other POSIX systems, use the versioned Python commands
in combination with the ``-m`` switch to run the appropriate copy of
``pip``::

   python2   -m pip install SomePackage  # default Python 2
   python2.7 -m pip install SomePackage  # specifically Python 2.7
   python3   -m pip install SomePackage  # default Python 3
   python3.4 -m pip install SomePackage  # specifically Python 3.4

(appropriately versioned ``pip`` commands may also be available)

On Windows, use the ``py`` Python launcher in combination with the ``-m``
switch::

   py -2   -m pip install SomePackage  # default Python 2
   py -2.7 -m pip install SomePackage  # specifically Python 2.7
   py -3   -m pip install SomePackage  # default Python 3
   py -3.4 -m pip install SomePackage  # specifically Python 3.4

.. other questions:

   Once the Development & Deployment part of PPUG is fleshed out, some of
   those sections should be linked from new questions here (most notably,
   we should have a question about avoiding depending on PyPI that links to
   https://packaging.python.org/en/latest/mirrors/)


Common installation issues
==========================

Installing into the system Python on Linux
------------------------------------------

On Linux systems, a Python installation will typically be included as part
of the distribution. Installing into this Python installation requires
root access to the system, and may interfere with the operation of the
system package manager and other components of the system if a component
is unexpectedly upgraded using ``pip``.

On such systems, it is often better to use a virtual environment or a
per-user installation when installing packages with ``pip``.


Pip not installed
-----------------

It is possible that ``pip`` does not get installed by default. One potential fix is::

    python -m ensurepip --default-pip

There are also additional resources for `installing pip.
<https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel>`__


Installing binary extensions
----------------------------

Python has typically relied heavily on source based distribution, with end
users being expected to compile extension modules from source as part of
the installation process.

With the introduction of support for the binary ``wheel`` format, and the
ability to publish wheels for at least Windows and Mac OS X through the
Python Packaging Index, this problem is expected to diminish over time,
as users are more regularly able to install pre-built extensions rather
than needing to build them themselves.

Some of the solutions for installing `scientific software
<https://packaging.python.org/en/latest/science/>`__
that is not yet available as pre-built ``wheel`` files may also help with
obtaining other binary extensions without needing to build them locally.

.. seealso::

   `Python Packaging User Guide: Binary Extensions
   <https://packaging.python.org/en/latest/extensions/>`__
PK	%�\M�J���)html/_sources/library/__builtin__.rst.txtnu�[���
:mod:`__builtin__` --- Built-in objects
=======================================

.. module:: __builtin__
   :synopsis: The module that provides the built-in namespace.


This module provides direct access to all 'built-in' identifiers of Python; for
example, ``__builtin__.open`` is the full name for the built-in function
:func:`open`.  See :ref:`built-in-funcs` and :ref:`built-in-consts` for
documentation.


This module is not normally accessed explicitly by most applications, but can be
useful in modules that provide objects with the same name as a built-in value,
but in which the built-in of that name is also needed.  For example, in a module
that wants to implement an :func:`open` function that wraps the built-in
:func:`open`, this module can be used directly::

   import __builtin__

   def open(path):
       f = __builtin__.open(path, 'r')
       return UpperCaser(f)

   class UpperCaser:
       '''Wrapper around a file that converts output to upper-case.'''

       def __init__(self, f):
           self._f = f

       def read(self, count=-1):
           return self._f.read(count).upper()

       # ...

.. impl-detail::

   Most modules have the name ``__builtins__`` (note the ``'s'``) made available
   as part of their globals.  The value of ``__builtins__`` is normally either
   this module or the value of this modules's :attr:`~object.__dict__` attribute.  Since
   this is an implementation detail, it may not be used by alternate
   implementations of Python.
PK	%�\�I�XX(html/_sources/library/__future__.rst.txtnu�[���:mod:`__future__` --- Future statement definitions
==================================================

.. module:: __future__
   :synopsis: Future statement definitions

**Source code:** :source:`Lib/__future__.py`

--------------

:mod:`__future__` is a real module, and serves three purposes:

* To avoid confusing existing tools that analyze import statements and expect to
  find the modules they're importing.

* To ensure that :ref:`future statements <future>` run under releases prior to
  2.1 at least yield runtime exceptions (the import of :mod:`__future__` will
  fail, because there was no module of that name prior to 2.1).

* To document when incompatible changes were introduced, and when they will be
  --- or were --- made mandatory.  This is a form of executable documentation, and
  can be inspected programmatically via importing :mod:`__future__` and examining
  its contents.

Each statement in :file:`__future__.py` is of the form::

   FeatureName = _Feature(OptionalRelease, MandatoryRelease,
                          CompilerFlag)


where, normally, *OptionalRelease* is less than *MandatoryRelease*, and both are
5-tuples of the same form as ``sys.version_info``::

   (PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
    PY_MINOR_VERSION, # the 1; an int
    PY_MICRO_VERSION, # the 0; an int
    PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
    PY_RELEASE_SERIAL # the 3; an int
   )

*OptionalRelease* records the first release in which the feature was accepted.

In the case of a *MandatoryRelease* that has not yet occurred,
*MandatoryRelease* predicts the release in which the feature will become part of
the language.

Else *MandatoryRelease* records when the feature became part of the language; in
releases at or after that, modules no longer need a future statement to use the
feature in question, but may continue to use such imports.

*MandatoryRelease* may also be ``None``, meaning that a planned feature got
dropped.

Instances of class :class:`_Feature` have two corresponding methods,
:meth:`getOptionalRelease` and :meth:`getMandatoryRelease`.

*CompilerFlag* is the (bitfield) flag that should be passed in the fourth
argument to the built-in function :func:`compile` to enable the feature in
dynamically compiled code.  This flag is stored in the :attr:`compiler_flag`
attribute on :class:`_Feature` instances.

No feature description will ever be deleted from :mod:`__future__`. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:

+------------------+-------------+--------------+---------------------------------------------+
| feature          | optional in | mandatory in | effect                                      |
+==================+=============+==============+=============================================+
| nested_scopes    | 2.1.0b1     | 2.2          | :pep:`227`:                                 |
|                  |             |              | *Statically Nested Scopes*                  |
+------------------+-------------+--------------+---------------------------------------------+
| generators       | 2.2.0a1     | 2.3          | :pep:`255`:                                 |
|                  |             |              | *Simple Generators*                         |
+------------------+-------------+--------------+---------------------------------------------+
| division         | 2.2.0a2     | 3.0          | :pep:`238`:                                 |
|                  |             |              | *Changing the Division Operator*            |
+------------------+-------------+--------------+---------------------------------------------+
| absolute_import  | 2.5.0a1     | 3.0          | :pep:`328`:                                 |
|                  |             |              | *Imports: Multi-Line and Absolute/Relative* |
+------------------+-------------+--------------+---------------------------------------------+
| with_statement   | 2.5.0a1     | 2.6          | :pep:`343`:                                 |
|                  |             |              | *The "with" Statement*                      |
+------------------+-------------+--------------+---------------------------------------------+
| print_function   | 2.6.0a2     | 3.0          | :pep:`3105`:                                |
|                  |             |              | *Make print a function*                     |
+------------------+-------------+--------------+---------------------------------------------+
| unicode_literals | 2.6.0a2     | 3.0          | :pep:`3112`:                                |
|                  |             |              | *Bytes literals in Python 3000*             |
+------------------+-------------+--------------+---------------------------------------------+

.. seealso::

   :ref:`future`
      How the compiler treats future imports.
PK	%�\B���&html/_sources/library/__main__.rst.txtnu�[���
:mod:`__main__` --- Top-level script environment
================================================

.. module:: __main__
   :synopsis: The environment where the top-level script is run.


This module represents the (otherwise anonymous) scope in which the
interpreter's main program executes --- commands read either from standard
input, from a script file, or from an interactive prompt.  It is this
environment in which the idiomatic "conditional script" stanza causes a script
to run::

   if __name__ == "__main__":
       main()

PK	%�\��	[	[%html/_sources/library/_winreg.rst.txtnu�[���:mod:`_winreg` --- Windows registry access
==========================================

.. module:: _winreg
   :platform: Windows
   :synopsis: Routines and objects for manipulating the Windows registry.
.. sectionauthor:: Mark Hammond <MarkH@ActiveState.com>

.. note::
   The :mod:`_winreg` module has been renamed to :mod:`winreg` in Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.


.. versionadded:: 2.0

These functions expose the Windows registry API to Python.  Instead of using an
integer as the registry handle, a :ref:`handle object <handle-object>` is used
to ensure that the handles are closed correctly, even if the programmer neglects
to explicitly close them.

This module offers the following functions:


.. function:: CloseKey(hkey)

   Closes a previously opened registry key.  The *hkey* argument specifies a
   previously opened key.

   .. note::
      If *hkey* is not closed using this method (or via :meth:`hkey.Close() <PyHKEY.Close>`),
      it is closed when the *hkey* object is destroyed by Python.


.. function:: ConnectRegistry(computer_name, key)

   Establishes a connection to a predefined registry handle on another computer,
   and returns a :ref:`handle object <handle-object>`.

   *computer_name* is the name of the remote computer, of the form
   ``r"\\computername"``.  If ``None``, the local computer is used.

   *key* is the predefined handle to connect to.

   The return value is the handle of the opened key. If the function fails, a
   :exc:`WindowsError` exception is raised.


.. function:: CreateKey(key, sub_key)

   Creates or opens the specified key, returning a
   :ref:`handle object <handle-object>`.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that names the key this method opens or creates.

   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
   case, the handle returned is the same key handle passed in to the function.

   If the key already exists, this function opens the existing key.

   The return value is the handle of the opened key. If the function fails, a
   :exc:`WindowsError` exception is raised.


.. function:: CreateKeyEx(key, sub_key[, res[, sam]])

   Creates or opens the specified key, returning a
   :ref:`handle object <handle-object>`.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that names the key this method opens or creates.

   *res* is a reserved integer, and must be zero. The default is zero.

   *sam* is an integer that specifies an access mask that describes the desired
   security access for the key.  Default is :const:`KEY_ALL_ACCESS`.  See
   :ref:`Access Rights <access-rights>` for other allowed values.


   If *key* is one of the predefined keys, *sub_key* may be ``None``. In that
   case, the handle returned is the same key handle passed in to the function.

   If the key already exists, this function opens the existing key.

   The return value is the handle of the opened key. If the function fails, a
   :exc:`WindowsError` exception is raised.

.. versionadded:: 2.7


.. function:: DeleteKey(key, sub_key)

   Deletes the specified key.

   *key* is an already open key, or any one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that must be a subkey of the key identified by the *key*
   parameter.  This value must not be ``None``, and the key may not have subkeys.

   *This method can not delete keys with subkeys.*

   If the method succeeds, the entire key, including all of its values, is removed.
   If the method fails, a :exc:`WindowsError` exception is raised.


.. function:: DeleteKeyEx(key, sub_key[, sam[, res]])

   Deletes the specified key.

   .. note::
      The :func:`DeleteKeyEx` function is implemented with the RegDeleteKeyEx
      Windows API function, which is specific to 64-bit versions of Windows.
      See the `RegDeleteKeyEx documentation
      <http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx>`__.

   *key* is an already open key, or any one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that must be a subkey of the key identified by the
   *key* parameter. This value must not be ``None``, and the key may not have
   subkeys.

   *res* is a reserved integer, and must be zero. The default is zero.

   *sam* is an integer that specifies an access mask that describes the desired
   security access for the key.  Default is :const:`KEY_WOW64_64KEY`.  See
   :ref:`Access Rights <access-rights>` for other allowed values.


   *This method can not delete keys with subkeys.*

   If the method succeeds, the entire key, including all of its values, is
   removed. If the method fails, a :exc:`WindowsError` exception is raised.

   On unsupported Windows versions, :exc:`NotImplementedError` is raised.

.. versionadded:: 2.7


.. function:: DeleteValue(key, value)

   Removes a named value from a registry key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *value* is a string that identifies the value to remove.


.. function:: EnumKey(key, index)

   Enumerates subkeys of an open registry key, returning a string.

   *key* is an already open key, or any one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *index* is an integer that identifies the index of the key to retrieve.

   The function retrieves the name of one subkey each time it is called.  It is
   typically called repeatedly until a :exc:`WindowsError` exception is
   raised, indicating, no more values are available.


.. function:: EnumValue(key, index)

   Enumerates values of an open registry key, returning a tuple.

   *key* is an already open key, or any one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *index* is an integer that identifies the index of the value to retrieve.

   The function retrieves the name of one subkey each time it is called. It is
   typically called repeatedly, until a :exc:`WindowsError` exception is
   raised, indicating no more values.

   The result is a tuple of 3 items:

   +-------+--------------------------------------------+
   | Index | Meaning                                    |
   +=======+============================================+
   | ``0`` | A string that identifies the value name    |
   +-------+--------------------------------------------+
   | ``1`` | An object that holds the value data, and   |
   |       | whose type depends on the underlying       |
   |       | registry type                              |
   +-------+--------------------------------------------+
   | ``2`` | An integer that identifies the type of the |
   |       | value data (see table in docs for          |
   |       | :meth:`SetValueEx`)                        |
   +-------+--------------------------------------------+


.. function:: ExpandEnvironmentStrings(unicode)

   Expands environment variable placeholders ``%NAME%`` in unicode strings like
   :const:`REG_EXPAND_SZ`::

      >>> ExpandEnvironmentStrings(u"%windir%")
      u"C:\\Windows"

   .. versionadded:: 2.6


.. function:: FlushKey(key)

   Writes all the attributes of a key to the registry.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   It is not necessary to call :func:`FlushKey` to change a key. Registry changes are
   flushed to disk by the registry using its lazy flusher.  Registry changes are
   also flushed to disk at system shutdown.  Unlike :func:`CloseKey`, the
   :func:`FlushKey` method returns only when all the data has been written to the
   registry. An application should only call :func:`FlushKey` if it requires
   absolute certainty that registry changes are on disk.

   .. note::

      If you don't know whether a :func:`FlushKey` call is required, it probably
      isn't.


.. function:: LoadKey(key, sub_key, file_name)

   Creates a subkey under the specified key and stores registration information
   from a specified file into that subkey.

   *key* is a handle returned by :func:`ConnectRegistry` or one of the constants
   :const:`HKEY_USERS` or :const:`HKEY_LOCAL_MACHINE`.

   *sub_key* is a string that identifies the subkey to load.

   *file_name* is the name of the file to load registry data from. This file must
   have been created with the :func:`SaveKey` function. Under the file allocation
   table (FAT) file system, the filename may not have an extension.

   A call to :func:`LoadKey` fails if the calling process does not have the
   :const:`SE_RESTORE_PRIVILEGE` privilege.  Note that privileges are different
   from permissions -- see the `RegLoadKey documentation
   <http://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx>`__ for
   more details.

   If *key* is a handle returned by :func:`ConnectRegistry`, then the path
   specified in *file_name* is relative to the remote computer.


.. function:: OpenKey(key, sub_key[, res[, sam]])

   Opens the specified key, returning a :ref:`handle object <handle-object>`.

   *key* is an already open key, or any one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that identifies the sub_key to open.

   *res* is a reserved integer, and must be zero.  The default is zero.

   *sam* is an integer that specifies an access mask that describes the desired
   security access for the key.  Default is :const:`KEY_READ`.  See
   :ref:`Access Rights <access-rights>` for other allowed values.

   The result is a new handle to the specified key.

   If the function fails, :exc:`WindowsError` is raised.


.. function:: OpenKeyEx()

   The functionality of :func:`OpenKeyEx` is provided via :func:`OpenKey`,
   by the use of default arguments.


.. function:: QueryInfoKey(key)

   Returns information about a key, as a tuple.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   The result is a tuple of 3 items:

   +-------+---------------------------------------------+
   | Index | Meaning                                     |
   +=======+=============================================+
   | ``0`` | An integer giving the number of sub keys    |
   |       | this key has.                               |
   +-------+---------------------------------------------+
   | ``1`` | An integer giving the number of values this |
   |       | key has.                                    |
   +-------+---------------------------------------------+
   | ``2`` | A long integer giving when the key was last |
   |       | modified (if available) as 100's of         |
   |       | nanoseconds since Jan 1, 1601.              |
   +-------+---------------------------------------------+


.. function:: QueryValue(key, sub_key)

   Retrieves the unnamed value for a key, as a string.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that holds the name of the subkey with which the value is
   associated.  If this parameter is ``None`` or empty, the function retrieves the
   value set by the :func:`SetValue` method for the key identified by *key*.

   Values in the registry have name, type, and data components. This method
   retrieves the data for a key's first value that has a NULL name. But the
   underlying API call doesn't return the type, so always use
   :func:`QueryValueEx` if possible.


.. function:: QueryValueEx(key, value_name)

   Retrieves the type and data for a specified value name associated with
   an open registry key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *value_name* is a string indicating the value to query.

   The result is a tuple of 2 items:

   +-------+-----------------------------------------+
   | Index | Meaning                                 |
   +=======+=========================================+
   | ``0`` | The value of the registry item.         |
   +-------+-----------------------------------------+
   | ``1`` | An integer giving the registry type for |
   |       | this value (see table in docs for       |
   |       | :meth:`SetValueEx`)                     |
   +-------+-----------------------------------------+


.. function:: SaveKey(key, file_name)

   Saves the specified key, and all its subkeys to the specified file.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *file_name* is the name of the file to save registry data to.  This file
   cannot already exist. If this filename includes an extension, it cannot be
   used on file allocation table (FAT) file systems by the :meth:`LoadKey`
   method.

   If *key* represents a key on a remote computer, the path described by
   *file_name* is relative to the remote computer. The caller of this method must
   possess the :const:`SeBackupPrivilege` security privilege.  Note that
   privileges are different than permissions -- see the
   `Conflicts Between User Rights and Permissions documentation
   <http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__
   for more details.

   This function passes NULL for *security_attributes* to the API.


.. function:: SetValue(key, sub_key, type, value)

   Associates a value with a specified key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *sub_key* is a string that names the subkey with which the value is associated.

   *type* is an integer that specifies the type of the data. Currently this must be
   :const:`REG_SZ`, meaning only strings are supported.  Use the :func:`SetValueEx`
   function for support for other data types.

   *value* is a string that specifies the new value.

   If the key specified by the *sub_key* parameter does not exist, the SetValue
   function creates it.

   Value lengths are limited by available memory. Long values (more than 2048
   bytes) should be stored as files with the filenames stored in the configuration
   registry.  This helps the registry perform efficiently.

   The key identified by the *key* parameter must have been opened with
   :const:`KEY_SET_VALUE` access.


.. function:: SetValueEx(key, value_name, reserved, type, value)

   Stores data in the value field of an open registry key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   *value_name* is a string that names the subkey with which the value is
   associated.

   *type* is an integer that specifies the type of the data. See
   :ref:`Value Types <value-types>` for the available types.

   *reserved* can be anything -- zero is always passed to the API.

   *value* is a string that specifies the new value.

   This method can also set additional value and type information for the specified
   key.  The key identified by the key parameter must have been opened with
   :const:`KEY_SET_VALUE` access.

   To open the key, use the :func:`CreateKey` or :func:`OpenKey` methods.

   Value lengths are limited by available memory. Long values (more than 2048
   bytes) should be stored as files with the filenames stored in the configuration
   registry.  This helps the registry perform efficiently.


.. function:: DisableReflectionKey(key)

   Disables registry reflection for 32-bit processes running on a 64-bit
   operating system.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
   operating system.

   If the key is not on the reflection list, the function succeeds but has no
   effect. Disabling reflection for a key does not affect reflection of any
   subkeys.


.. function:: EnableReflectionKey(key)

   Restores registry reflection for the specified disabled key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
   operating system.

   Restoring reflection for a key does not affect reflection of any subkeys.


.. function:: QueryReflectionKey(key)

   Determines the reflection state for the specified key.

   *key* is an already open key, or one of the predefined
   :ref:`HKEY_* constants <hkey-constants>`.

   Returns ``True`` if reflection is disabled.

   Will generally raise :exc:`NotImplemented` if executed on a 32-bit
   operating system.


.. _constants:

Constants
------------------

The following constants are defined for use in many :mod:`_winreg` functions.

.. _hkey-constants:

HKEY_* Constants
++++++++++++++++

.. data:: HKEY_CLASSES_ROOT

   Registry entries subordinate to this key define types (or classes) of
   documents and the properties associated with those types. Shell and
   COM applications use the information stored under this key.


.. data:: HKEY_CURRENT_USER

   Registry entries subordinate to this key define the preferences of
   the current user. These preferences include the settings of
   environment variables, data about program groups, colors, printers,
   network connections, and application preferences.

.. data:: HKEY_LOCAL_MACHINE

   Registry entries subordinate to this key define the physical state
   of the computer, including data about the bus type, system memory,
   and installed hardware and software.

.. data:: HKEY_USERS

   Registry entries subordinate to this key define the default user
   configuration for new users on the local computer and the user
   configuration for the current user.

.. data:: HKEY_PERFORMANCE_DATA

   Registry entries subordinate to this key allow you to access
   performance data. The data is not actually stored in the registry;
   the registry functions cause the system to collect the data from
   its source.


.. data:: HKEY_CURRENT_CONFIG

   Contains information about the current hardware profile of the
   local computer system.

.. data:: HKEY_DYN_DATA

   This key is not used in versions of Windows after 98.


.. _access-rights:

Access Rights
+++++++++++++

For more information, see `Registry Key Security and Access
<http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx>`__.

.. data:: KEY_ALL_ACCESS

   Combines the STANDARD_RIGHTS_REQUIRED, :const:`KEY_QUERY_VALUE`,
   :const:`KEY_SET_VALUE`, :const:`KEY_CREATE_SUB_KEY`,
   :const:`KEY_ENUMERATE_SUB_KEYS`, :const:`KEY_NOTIFY`,
   and :const:`KEY_CREATE_LINK` access rights.

.. data:: KEY_WRITE

   Combines the STANDARD_RIGHTS_WRITE, :const:`KEY_SET_VALUE`, and
   :const:`KEY_CREATE_SUB_KEY` access rights.

.. data:: KEY_READ

   Combines the STANDARD_RIGHTS_READ, :const:`KEY_QUERY_VALUE`,
   :const:`KEY_ENUMERATE_SUB_KEYS`, and :const:`KEY_NOTIFY` values.

.. data:: KEY_EXECUTE

   Equivalent to :const:`KEY_READ`.

.. data:: KEY_QUERY_VALUE

   Required to query the values of a registry key.

.. data:: KEY_SET_VALUE

   Required to create, delete, or set a registry value.

.. data:: KEY_CREATE_SUB_KEY

   Required to create a subkey of a registry key.

.. data:: KEY_ENUMERATE_SUB_KEYS

   Required to enumerate the subkeys of a registry key.

.. data:: KEY_NOTIFY

   Required to request change notifications for a registry key or for
   subkeys of a registry key.

.. data:: KEY_CREATE_LINK

   Reserved for system use.


.. _64-bit-access-rights:

64-bit Specific
***************

For more information, see `Accessing an Alternate Registry View
<http://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx>`__.

.. data:: KEY_WOW64_64KEY

   Indicates that an application on 64-bit Windows should operate on
   the 64-bit registry view.

.. data:: KEY_WOW64_32KEY

   Indicates that an application on 64-bit Windows should operate on
   the 32-bit registry view.


.. _value-types:

Value Types
+++++++++++

For more information, see `Registry Value Types
<http://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx>`__.

.. data:: REG_BINARY

   Binary data in any form.

.. data:: REG_DWORD

   32-bit number.

.. data:: REG_DWORD_LITTLE_ENDIAN

   A 32-bit number in little-endian format.

.. data:: REG_DWORD_BIG_ENDIAN

   A 32-bit number in big-endian format.

.. data:: REG_EXPAND_SZ

   Null-terminated string containing references to environment
   variables (``%PATH%``).

.. data:: REG_LINK

   A Unicode symbolic link.

.. data:: REG_MULTI_SZ

   A sequence of null-terminated strings, terminated by two null characters.
   (Python handles this termination automatically.)

.. data:: REG_NONE

   No defined value type.

.. data:: REG_RESOURCE_LIST

   A device-driver resource list.

.. data:: REG_FULL_RESOURCE_DESCRIPTOR

   A hardware setting.

.. data:: REG_RESOURCE_REQUIREMENTS_LIST

   A hardware resource list.

.. data:: REG_SZ

   A null-terminated string.


.. _handle-object:

Registry Handle Objects
-----------------------

This object wraps a Windows HKEY object, automatically closing it when the
object is destroyed.  To guarantee cleanup, you can call either the
:meth:`~PyHKEY.Close` method on the object, or the :func:`CloseKey` function.

All registry functions in this module return one of these objects.

All registry functions in this module which accept a handle object also accept
an integer, however, use of the handle object is encouraged.

Handle objects provide semantics for :meth:`__nonzero__` -- thus::

   if handle:
       print "Yes"

will print ``Yes`` if the handle is currently valid (has not been closed or
detached).

The object also support comparison semantics, so handle objects will compare
true if they both reference the same underlying Windows handle value.

Handle objects can be converted to an integer (e.g., using the built-in
:func:`int` function), in which case the underlying Windows handle value is
returned.  You can also use the :meth:`~PyHKEY.Detach` method to return the
integer handle, and also disconnect the Windows handle from the handle object.


.. method:: PyHKEY.Close()

   Closes the underlying Windows handle.

   If the handle is already closed, no error is raised.


.. method:: PyHKEY.Detach()

   Detaches the Windows handle from the handle object.

   The result is an integer (or long on 64 bit Windows) that holds the value of the
   handle before it is detached.  If the handle is already detached or closed, this
   will return zero.

   After calling this function, the handle is effectively invalidated, but the
   handle is not closed.  You would call this function when you need the
   underlying Win32 handle to exist beyond the lifetime of the handle object.

.. method:: PyHKEY.__enter__()
            PyHKEY.__exit__(\*exc_info)

   The HKEY object implements :meth:`~object.__enter__` and
   :meth:`~object.__exit__` and thus supports the context protocol for the
   :keyword:`with` statement::

      with OpenKey(HKEY_LOCAL_MACHINE, "foo") as key:
          ...  # work with key

   will automatically close *key* when control leaves the :keyword:`with` block.

   .. versionadded:: 2.6

PK	%�\��l33!html/_sources/library/abc.rst.txtnu�[���:mod:`abc` --- Abstract Base Classes
====================================

.. module:: abc
   :synopsis: Abstract base classes according to PEP 3119.
.. moduleauthor:: Guido van Rossum
.. sectionauthor:: Georg Brandl
.. much of the content adapted from docstrings

.. versionadded:: 2.6

**Source code:** :source:`Lib/abc.py`

--------------

This module provides the infrastructure for defining :term:`abstract base
classes <abstract base class>` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
regarding a type hierarchy for numbers based on ABCs.)

The :mod:`collections` module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition, the
:mod:`collections` module has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, if it is
hashable or if it is a mapping.


This module provides the following class:

.. class:: ABCMeta

   Metaclass for defining Abstract Base Classes (ABCs).

   Use this metaclass to create an ABC.  An ABC can be subclassed directly, and
   then acts as a mix-in class.  You can also register unrelated concrete
   classes (even built-in classes) and unrelated ABCs as "virtual subclasses" --
   these and their descendants will be considered subclasses of the registering
   ABC by the built-in :func:`issubclass` function, but the registering ABC
   won't show up in their MRO (Method Resolution Order) nor will method
   implementations defined by the registering ABC be callable (not even via
   :func:`super`). [#]_

   Classes created with a metaclass of :class:`ABCMeta` have the following method:

   .. method:: register(subclass)

      Register *subclass* as a "virtual subclass" of this ABC. For
      example::

        from abc import ABCMeta

        class MyABC:
            __metaclass__ = ABCMeta

        MyABC.register(tuple)

        assert issubclass(tuple, MyABC)
        assert isinstance((), MyABC)

   You can also override this method in an abstract base class:

   .. method:: __subclasshook__(subclass)

      (Must be defined as a class method.)

      Check whether *subclass* is considered a subclass of this ABC.  This means
      that you can customize the behavior of ``issubclass`` further without the
      need to call :meth:`register` on every class you want to consider a
      subclass of the ABC.  (This class method is called from the
      :meth:`__subclasscheck__` method of the ABC.)

      This method should return ``True``, ``False`` or ``NotImplemented``.  If
      it returns ``True``, the *subclass* is considered a subclass of this ABC.
      If it returns ``False``, the *subclass* is not considered a subclass of
      this ABC, even if it would normally be one.  If it returns
      ``NotImplemented``, the subclass check is continued with the usual
      mechanism.

      .. XXX explain the "usual mechanism"


   For a demonstration of these concepts, look at this example ABC definition::

      class Foo(object):
          def __getitem__(self, index):
              ...
          def __len__(self):
              ...
          def get_iterator(self):
              return iter(self)

      class MyIterable:
          __metaclass__ = ABCMeta

          @abstractmethod
          def __iter__(self):
              while False:
                  yield None

          def get_iterator(self):
              return self.__iter__()

          @classmethod
          def __subclasshook__(cls, C):
              if cls is MyIterable:
                  if any("__iter__" in B.__dict__ for B in C.__mro__):
                      return True
              return NotImplemented

      MyIterable.register(Foo)

   The ABC ``MyIterable`` defines the standard iterable method,
   :meth:`~iterator.__iter__`, as an abstract method.  The implementation given
   here can still be called from subclasses.  The :meth:`get_iterator` method
   is also part of the ``MyIterable`` abstract base class, but it does not have
   to be overridden in non-abstract derived classes.

   The :meth:`__subclasshook__` class method defined here says that any class
   that has an :meth:`~iterator.__iter__` method in its
   :attr:`~object.__dict__` (or in that of one of its base classes, accessed
   via the :attr:`~class.__mro__` list) is considered a ``MyIterable`` too.

   Finally, the last line makes ``Foo`` a virtual subclass of ``MyIterable``,
   even though it does not define an :meth:`~iterator.__iter__` method (it uses
   the old-style iterable protocol, defined in terms of :meth:`__len__` and
   :meth:`__getitem__`).  Note that this will not make ``get_iterator``
   available as a method of ``Foo``, so it is provided separately.


It also provides the following decorators:

.. function:: abstractmethod(function)

   A decorator indicating abstract methods.

   Using this decorator requires that the class's metaclass is :class:`ABCMeta` or
   is derived from it.
   A class that has a metaclass derived from :class:`ABCMeta`
   cannot be instantiated unless all of its abstract methods and
   properties are overridden.
   The abstract methods can be called using any of the normal 'super' call
   mechanisms.

   Dynamically adding abstract methods to a class, or attempting to modify the
   abstraction status of a method or class once it is created, are not
   supported.  The :func:`abstractmethod` only affects subclasses derived using
   regular inheritance; "virtual subclasses" registered with the ABC's
   :meth:`register` method are not affected.

   Usage::

      class C:
          __metaclass__ = ABCMeta
          @abstractmethod
          def my_abstract_method(self, ...):
              ...

   .. note::

      Unlike Java abstract methods, these abstract
      methods may have an implementation. This implementation can be
      called via the :func:`super` mechanism from the class that
      overrides it.  This could be useful as an end-point for a
      super-call in a framework that uses cooperative
      multiple-inheritance.


.. function:: abstractproperty([fget[, fset[, fdel[, doc]]]])

   A subclass of the built-in :func:`property`, indicating an abstract property.

   Using this function requires that the class's metaclass is :class:`ABCMeta` or
   is derived from it.
   A class that has a metaclass derived from :class:`ABCMeta` cannot be
   instantiated unless all of its abstract methods and properties are overridden.
   The abstract properties can be called using any of the normal
   'super' call mechanisms.

   Usage::

      class C:
          __metaclass__ = ABCMeta
          @abstractproperty
          def my_abstract_property(self):
              ...

   This defines a read-only property; you can also define a read-write abstract
   property using the 'long' form of property declaration::

      class C:
          __metaclass__ = ABCMeta
          def getx(self): ...
          def setx(self, value): ...
          x = abstractproperty(getx, setx)


.. rubric:: Footnotes

.. [#] C++ programmers should note that Python's virtual base class
   concept is not the same as C++'s.
PK	%�\ny�*��$html/_sources/library/aepack.rst.txtnu�[���
:mod:`aepack` --- Conversion between Python variables and AppleEvent data containers
====================================================================================

.. module:: aepack
   :platform: Mac
   :synopsis: Conversion between Python variables and AppleEvent data containers.
   :deprecated:
.. sectionauthor:: Vincent Marchetti <vincem@en.com>
.. moduleauthor:: Jack Jansen

The :mod:`aepack` module defines functions for converting (packing) Python
variables to AppleEvent descriptors and back (unpacking). Within Python the
AppleEvent descriptor is handled by Python objects of built-in type
:class:`AEDesc`, defined in module :mod:`Carbon.AE`.

.. note::

   This module has been removed in Python 3.x.


The :mod:`aepack` module defines the following functions:


.. function:: pack(x[, forcetype])

   Returns an :class:`AEDesc` object  containing a conversion of Python value x. If
   *forcetype* is provided it specifies the descriptor type of the result.
   Otherwise, a default mapping of Python types to Apple Event descriptor types is
   used, as follows:

   +-----------------+-----------------------------------+
   | Python type     | descriptor type                   |
   +=================+===================================+
   | :class:`FSSpec` | typeFSS                           |
   +-----------------+-----------------------------------+
   | :class:`FSRef`  | typeFSRef                         |
   +-----------------+-----------------------------------+
   | :class:`Alias`  | typeAlias                         |
   +-----------------+-----------------------------------+
   | integer         | typeLong (32 bit integer)         |
   +-----------------+-----------------------------------+
   | float           | typeFloat (64 bit floating point) |
   +-----------------+-----------------------------------+
   | string          | typeText                          |
   +-----------------+-----------------------------------+
   | unicode         | typeUnicodeText                   |
   +-----------------+-----------------------------------+
   | list            | typeAEList                        |
   +-----------------+-----------------------------------+
   | dictionary      | typeAERecord                      |
   +-----------------+-----------------------------------+
   | instance        | *see below*                       |
   +-----------------+-----------------------------------+

   If *x* is a Python instance then this function attempts to call an
   :meth:`__aepack__` method.  This method should return an :class:`AEDesc` object.

   If the conversion *x* is not defined above, this function returns the Python
   string representation of a value (the repr() function) encoded as a text
   descriptor.


.. function:: unpack(x[, formodulename])

   *x* must be an object of type :class:`AEDesc`. This function returns a Python
   object representation of the data in the Apple Event descriptor *x*. Simple
   AppleEvent data types (integer, text, float) are returned as their obvious
   Python counterparts. Apple Event lists are returned as Python lists, and the
   list elements are recursively unpacked.  Object references (ex. ``line 3 of
   document 1``) are returned as instances of :class:`aetypes.ObjectSpecifier`,
   unless ``formodulename`` is specified.  AppleEvent descriptors with descriptor
   type typeFSS are returned as :class:`FSSpec` objects.  AppleEvent record
   descriptors are returned as Python dictionaries, with 4-character string keys
   and elements recursively unpacked.

   The optional ``formodulename`` argument is used by the stub packages generated
   by :mod:`gensuitemodule`, and ensures that the OSA classes for object specifiers
   are looked up in the correct module. This ensures that if, say, the Finder
   returns an object specifier for a window you get an instance of
   ``Finder.Window`` and not a generic ``aetypes.Window``. The former knows about
   all the properties and elements a window has in the Finder, while the latter
   knows no such things.


.. seealso::

   Module :mod:`Carbon.AE`
      Built-in access to Apple Event Manager routines.

   Module :mod:`aetypes`
      Python definitions of codes for Apple Event descriptor types.
PK	%�\�#e��
�
%html/_sources/library/aetools.rst.txtnu�[���
:mod:`aetools` --- OSA client support
=====================================

.. module:: aetools
   :platform: Mac
   :synopsis: Basic support for sending Apple Events
   :deprecated:
.. sectionauthor:: Jack Jansen <Jack.Jansen@cwi.nl>
.. moduleauthor:: Jack Jansen

The :mod:`aetools` module contains the basic functionality on which Python
AppleScript client support is built. It also imports and re-exports the core
functionality of the :mod:`aetypes` and :mod:`aepack` modules. The stub packages
generated by :mod:`gensuitemodule` import the relevant portions of
:mod:`aetools`, so usually you do not need to import it yourself. The exception
to this is when you cannot use a generated suite package and need lower-level
access to scripting.

The :mod:`aetools` module itself uses the AppleEvent support provided by the
:mod:`Carbon.AE` module. This has one drawback: you need access to the window
manager, see section :ref:`osx-gui-scripts` for details. This restriction may be
lifted in future releases.

.. note::

   This module has been removed in Python 3.x.


The :mod:`aetools` module defines the following functions:


.. function:: packevent(ae, parameters, attributes)

   Stores parameters and attributes in a pre-created ``Carbon.AE.AEDesc`` object.
   ``parameters`` and ``attributes`` are  dictionaries mapping 4-character OSA
   parameter keys to Python objects. The objects are packed using
   ``aepack.pack()``.


.. function:: unpackevent(ae[, formodulename])

   Recursively unpacks a ``Carbon.AE.AEDesc`` event to Python objects. The function
   returns the parameter dictionary and the attribute dictionary. The
   ``formodulename`` argument is used by generated stub packages to control where
   AppleScript classes are looked up.


.. function:: keysubst(arguments, keydict)

   Converts a Python keyword argument dictionary ``arguments`` to the format
   required by ``packevent`` by replacing the keys, which are Python identifiers,
   by the four-character OSA keys according to the mapping specified in
   ``keydict``. Used by the generated suite packages.


.. function:: enumsubst(arguments, key, edict)

   If the ``arguments`` dictionary contains an entry for ``key`` convert the value
   for that entry according to dictionary ``edict``. This converts human-readable
   Python enumeration names to the OSA 4-character codes. Used by the generated
   suite packages.

The :mod:`aetools` module defines the following class:


.. class:: TalkTo([signature=None, start=0, timeout=0])

   Base class for the proxy used to talk to an application. ``signature`` overrides
   the class attribute ``_signature`` (which is usually set by subclasses) and is
   the 4-char creator code defining the application to talk to. ``start`` can be
   set to true to enable running the application on class instantiation.
   ``timeout`` can be specified to change the default timeout used while waiting
   for an AppleEvent reply.


.. method:: TalkTo._start()

   Test whether the application is running, and attempt to start it if not.


.. method:: TalkTo.send(code, subcode[, parameters, attributes])

   Create the AppleEvent ``Carbon.AE.AEDesc`` for the verb with the OSA designation
   ``code, subcode`` (which are the usual 4-character strings), pack the
   ``parameters`` and ``attributes`` into it, send it to the target application,
   wait for the reply, unpack the reply with ``unpackevent`` and return the reply
   appleevent, the unpacked return values as a dictionary and the return
   attributes.

PK	%�\G`�Q��%html/_sources/library/aetypes.rst.txtnu�[���
:mod:`aetypes` --- AppleEvent objects
=====================================

.. module:: aetypes
   :platform: Mac
   :synopsis: Python representation of the Apple Event Object Model.
   :deprecated:
.. sectionauthor:: Vincent Marchetti <vincem@en.com>
.. moduleauthor:: Jack Jansen

The :mod:`aetypes` defines classes used to represent Apple Event data
descriptors and Apple Event object specifiers.

Apple Event data is contained in descriptors, and these descriptors are typed.
For many descriptors the Python representation is simply the corresponding
Python type: ``typeText`` in OSA is a Python string, ``typeFloat`` is a float,
etc. For OSA types that have no direct Python counterpart this module declares
classes. Packing and unpacking instances of these classes is handled
automatically by :mod:`aepack`.

An object specifier is essentially an address of an object implemented in an
Apple Event server. An Apple Event specifier is used as the direct object for an
Apple Event or as the argument of an optional parameter. The :mod:`aetypes`
module contains the base classes for OSA classes and properties, which are used
by the packages generated by :mod:`gensuitemodule` to populate the classes and
properties in a given suite.

For reasons of backward compatibility, and for cases where you need to script an
application for which you have not generated the stub package this module also
contains object specifiers for a number of common OSA classes such as
``Document``, ``Window``, ``Character``, etc.

.. note::

   This module has been removed in Python 3.x.



The :mod:`AEObjects` module defines the following classes to represent Apple
Event descriptor data:


.. class:: Unknown(type, data)

   The representation of OSA descriptor data for which the :mod:`aepack` and
   :mod:`aetypes` modules have no support, i.e. anything that is not represented by
   the other classes here and that is not equivalent to a simple Python value.


.. class:: Enum(enum)

   An enumeration value with the given 4-character string value.


.. class:: InsertionLoc(of, pos)

   Position ``pos`` in object ``of``.


.. class:: Boolean(bool)

   A boolean.


.. class:: StyledText(style, text)

   Text with style information (font, face, etc) included.


.. class:: AEText(script, style, text)

   Text with script system and style information included.


.. class:: IntlText(script, language, text)

   Text with script system and language information included.


.. class:: IntlWritingCode(script, language)

   Script system and language information.


.. class:: QDPoint(v, h)

   A quickdraw point.


.. class:: QDRectangle(v0, h0, v1, h1)

   A quickdraw rectangle.


.. class:: RGBColor(r, g, b)

   A color.


.. class:: Type(type)

   An OSA type value with the given 4-character name.


.. class:: Keyword(name)

   An OSA keyword with the given 4-character name.


.. class:: Range(start, stop)

   A range.


.. class:: Ordinal(abso)

   Non-numeric absolute positions, such as ``"firs"``, first, or ``"midd"``,
   middle.


.. class:: Logical(logc, term)

   The logical expression of applying operator ``logc`` to ``term``.


.. class:: Comparison(obj1, relo, obj2)

   The comparison ``relo`` of ``obj1`` to ``obj2``.

The following classes are used as base classes by the generated stub packages to
represent AppleScript classes and properties in Python:


.. class:: ComponentItem(which[, fr])

   Abstract baseclass for an OSA class. The subclass should set the class attribute
   ``want`` to the 4-character OSA class code. Instances of subclasses of this
   class are equivalent to AppleScript Object Specifiers. Upon instantiation you
   should pass a selector in ``which``, and optionally a parent object in ``fr``.


.. class:: NProperty(fr)

   Abstract baseclass for an OSA property. The subclass should set the class
   attributes ``want`` and ``which`` to designate which property we are talking
   about. Instances of subclasses of this class are Object Specifiers.


.. class:: ObjectSpecifier(want, form, seld[, fr])

   Base class of ``ComponentItem`` and ``NProperty``, a general OSA Object
   Specifier. See the Apple Open Scripting Architecture documentation for the
   parameters. Note that this class is not abstract.

PK	%�\�

��"html/_sources/library/aifc.rst.txtnu�[���:mod:`aifc` --- Read and write AIFF and AIFC files
==================================================

.. module:: aifc
   :synopsis: Read and write audio files in AIFF or AIFC format.


.. index::
   single: Audio Interchange File Format
   single: AIFF
   single: AIFF-C

**Source code:** :source:`Lib/aifc.py`

--------------

This module provides support for reading and writing AIFF and AIFF-C files.
AIFF is Audio Interchange File Format, a format for storing digital audio
samples in a file.  AIFF-C is a newer version of the format that includes the
ability to compress the audio data.

.. note::

   Some operations may only work under IRIX; these will raise :exc:`ImportError`
   when attempting to import the :mod:`cl` module, which is only available on
   IRIX.

Audio files have a number of parameters that describe the audio data. The
sampling rate or frame rate is the number of times per second the sound is
sampled.  The number of channels indicate if the audio is mono, stereo, or
quadro.  Each frame consists of one sample per channel.  The sample size is the
size in bytes of each sample.  Thus a frame consists of
*nchannels*\*\ *samplesize* bytes, and a second's worth of audio consists of
*nchannels*\*\ *samplesize*\*\ *framerate* bytes.

For example, CD quality audio has a sample size of two bytes (16 bits), uses two
channels (stereo) and has a frame rate of 44,100 frames/second.  This gives a
frame size of 4 bytes (2\*2), and a second's worth occupies 2\*2\*44100 bytes
(176,400 bytes).

Module :mod:`aifc` defines the following function:


.. function:: open(file[, mode])

   Open an AIFF or AIFF-C file and return an object instance with methods that are
   described below.  The argument *file* is either a string naming a file or a file
   object.  *mode* must be ``'r'`` or ``'rb'`` when the file must be opened for
   reading, or ``'w'``  or ``'wb'`` when the file must be opened for writing.  If
   omitted, ``file.mode`` is used if it exists, otherwise ``'rb'`` is used.  When
   used for writing, the file object should be seekable, unless you know ahead of
   time how many samples you are going to write in total and use
   :meth:`writeframesraw` and :meth:`setnframes`.

Objects returned by :func:`.open` when a file is opened for reading have the
following methods:


.. method:: aifc.getnchannels()

   Return the number of audio channels (1 for mono, 2 for stereo).


.. method:: aifc.getsampwidth()

   Return the size in bytes of individual samples.


.. method:: aifc.getframerate()

   Return the sampling rate (number of audio frames per second).


.. method:: aifc.getnframes()

   Return the number of audio frames in the file.


.. method:: aifc.getcomptype()

   Return a four-character string describing the type of compression used in the
   audio file.  For AIFF files, the returned value is ``'NONE'``.


.. method:: aifc.getcompname()

   Return a human-readable description of the type of compression used in the audio
   file.  For AIFF files, the returned value is ``'not compressed'``.


.. method:: aifc.getparams()

   Return a tuple consisting of all of the above values in the above order.


.. method:: aifc.getmarkers()

   Return a list of markers in the audio file.  A marker consists of a tuple of
   three elements.  The first is the mark ID (an integer), the second is the mark
   position in frames from the beginning of the data (an integer), the third is the
   name of the mark (a string).


.. method:: aifc.getmark(id)

   Return the tuple as described in :meth:`getmarkers` for the mark with the given
   *id*.


.. method:: aifc.readframes(nframes)

   Read and return the next *nframes* frames from the audio file.  The returned
   data is a string containing for each frame the uncompressed samples of all
   channels.


.. method:: aifc.rewind()

   Rewind the read pointer.  The next :meth:`readframes` will start from the
   beginning.


.. method:: aifc.setpos(pos)

   Seek to the specified frame number.


.. method:: aifc.tell()

   Return the current frame number.


.. method:: aifc.close()

   Close the AIFF file.  After calling this method, the object can no longer be
   used.

Objects returned by :func:`.open` when a file is opened for writing have all the
above methods, except for :meth:`readframes` and :meth:`setpos`.  In addition
the following methods exist.  The :meth:`get\*` methods can only be called after
the corresponding :meth:`set\*` methods have been called.  Before the first
:meth:`writeframes` or :meth:`writeframesraw`, all parameters except for the
number of frames must be filled in.


.. method:: aifc.aiff()

   Create an AIFF file.  The default is that an AIFF-C file is created, unless the
   name of the file ends in ``'.aiff'`` in which case the default is an AIFF file.


.. method:: aifc.aifc()

   Create an AIFF-C file.  The default is that an AIFF-C file is created, unless
   the name of the file ends in ``'.aiff'`` in which case the default is an AIFF
   file.


.. method:: aifc.setnchannels(nchannels)

   Specify the number of channels in the audio file.


.. method:: aifc.setsampwidth(width)

   Specify the size in bytes of audio samples.


.. method:: aifc.setframerate(rate)

   Specify the sampling frequency in frames per second.


.. method:: aifc.setnframes(nframes)

   Specify the number of frames that are to be written to the audio file. If this
   parameter is not set, or not set correctly, the file needs to support seeking.


.. method:: aifc.setcomptype(type, name)

   .. index::
      single: u-LAW
      single: A-LAW
      single: G.722

   Specify the compression type.  If not specified, the audio data will not be
   compressed.  In AIFF files, compression is not possible.  The name parameter
   should be a human-readable description of the compression type, the type
   parameter should be a four-character string.  Currently the following
   compression types are supported: NONE, ULAW, ALAW, G722.


.. method:: aifc.setparams(nchannels, sampwidth, framerate, comptype, compname)

   Set all the above parameters at once.  The argument is a tuple consisting of the
   various parameters.  This means that it is possible to use the result of a
   :meth:`getparams` call as argument to :meth:`setparams`.


.. method:: aifc.setmark(id, pos, name)

   Add a mark with the given id (larger than 0), and the given name at the given
   position.  This method can be called at any time before :meth:`close`.


.. method:: aifc.tell()

   Return the current write position in the output file.  Useful in combination
   with :meth:`setmark`.


.. method:: aifc.writeframes(data)

   Write data to the output file.  This method can only be called after the audio
   file parameters have been set.


.. method:: aifc.writeframesraw(data)

   Like :meth:`writeframes`, except that the header of the audio file is not
   updated.


.. method:: aifc.close()

   Close the AIFF file.  The header of the file is updated to reflect the actual
   size of the audio data. After calling this method, the object can no longer be
   used.

PK	%�\��T�� html/_sources/library/al.rst.txtnu�[���
:mod:`al` --- Audio functions on the SGI
========================================

.. module:: al
   :platform: IRIX
   :synopsis: Audio functions on the SGI.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`al` module has been removed in Python 3.


This module provides access to the audio facilities of the SGI Indy and Indigo
workstations.  See section 3A of the IRIX man pages for details.  You'll need to
read those man pages to understand what these functions do!  Some of the
functions are not available in IRIX releases before 4.0.5.  Again, see the
manual to check whether a specific function is available on your platform.

All functions and methods defined in this module are equivalent to the C
functions with ``AL`` prefixed to their name.

.. index:: module: AL

Symbolic constants from the C header file ``<audio.h>`` are defined in the
standard module :mod:`AL`, see below.

.. warning::

   The current version of the audio library may dump core when bad argument values
   are passed rather than returning an error status.  Unfortunately, since the
   precise circumstances under which this may happen are undocumented and hard to
   check, the Python interface can provide no protection against this kind of
   problems. (One example is specifying an excessive queue size --- there is no
   documented upper limit.)

The module defines the following functions:


.. function:: openport(name, direction[, config])

   The name and direction arguments are strings.  The optional *config* argument is
   a configuration object as returned by :func:`newconfig`.  The return value is an
   :dfn:`audio port object`; methods of audio port objects are described below.


.. function:: newconfig()

   The return value is a new :dfn:`audio configuration object`; methods of audio
   configuration objects are described below.


.. function:: queryparams(device)

   The device argument is an integer.  The return value is a list of integers
   containing the data returned by :c:func:`ALqueryparams`.


.. function:: getparams(device, list)

   The *device* argument is an integer.  The list argument is a list such as
   returned by :func:`queryparams`; it is modified in place (!).


.. function:: setparams(device, list)

   The *device* argument is an integer.  The *list* argument is a list such as
   returned by :func:`queryparams`.


.. _al-config-objects:

Configuration Objects
---------------------

Configuration objects returned by :func:`newconfig` have the following methods:


.. method:: audio configuration.getqueuesize()

   Return the queue size.


.. method:: audio configuration.setqueuesize(size)

   Set the queue size.


.. method:: audio configuration.getwidth()

   Get the sample width.


.. method:: audio configuration.setwidth(width)

   Set the sample width.


.. method:: audio configuration.getchannels()

   Get the channel count.


.. method:: audio configuration.setchannels(nchannels)

   Set the channel count.


.. method:: audio configuration.getsampfmt()

   Get the sample format.


.. method:: audio configuration.setsampfmt(sampfmt)

   Set the sample format.


.. method:: audio configuration.getfloatmax()

   Get the maximum value for floating sample formats.


.. method:: audio configuration.setfloatmax(floatmax)

   Set the maximum value for floating sample formats.


.. _al-port-objects:

Port Objects
------------

Port objects, as returned by :func:`openport`, have the following methods:


.. method:: audio port.closeport()

   Close the port.


.. method:: audio port.getfd()

   Return the file descriptor as an int.


.. method:: audio port.getfilled()

   Return the number of filled samples.


.. method:: audio port.getfillable()

   Return the number of fillable samples.


.. method:: audio port.readsamps(nsamples)

   Read a number of samples from the queue, blocking if necessary. Return the data
   as a string containing the raw data, (e.g., 2 bytes per sample in big-endian
   byte order (high byte, low byte) if you have set the sample width to 2 bytes).


.. method:: audio port.writesamps(samples)

   Write samples into the queue, blocking if necessary.  The samples are encoded as
   described for the :meth:`readsamps` return value.


.. method:: audio port.getfillpoint()

   Return the 'fill point'.


.. method:: audio port.setfillpoint(fillpoint)

   Set the 'fill point'.


.. method:: audio port.getconfig()

   Return a configuration object containing the current configuration of the port.


.. method:: audio port.setconfig(config)

   Set the configuration from the argument, a configuration object.


.. method:: audio port.getstatus(list)

   Get status information on last error.


:mod:`AL` --- Constants used with the :mod:`al` module
======================================================

.. module:: AL
   :platform: IRIX
   :synopsis: Constants used with the al module.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`AL` module has been removed in Python 3.


This module defines symbolic constants needed to use the built-in module
:mod:`al` (see above); they are equivalent to those defined in the C header file
``<audio.h>`` except that the name prefix ``AL_`` is omitted.  Read the module
source for a complete list of the defined names.  Suggested use::

   import al
   from AL import *

PK	%�\c�#���#html/_sources/library/allos.rst.txtnu�[���
.. _allos:

*********************************
Generic Operating System Services
*********************************

The modules described in this chapter provide interfaces to operating system
features that are available on (almost) all operating systems, such as files and
a clock.  The interfaces are generally modeled after the Unix or C interfaces,
but they are available on most other systems as well.  Here's an overview:


.. toctree::

   os.rst
   io.rst
   time.rst
   argparse.rst
   optparse.rst
   getopt.rst
   logging.rst
   logging.config.rst
   logging.handlers.rst
   getpass.rst
   curses.rst
   curses.ascii.rst
   curses.panel.rst
   platform.rst
   errno.rst
   ctypes.rst
PK	%�\�vy.$html/_sources/library/anydbm.rst.txtnu�[���:mod:`anydbm` --- Generic access to DBM-style databases
=======================================================

.. module:: anydbm
   :synopsis: Generic interface to DBM-style database modules.


.. note::
   The :mod:`anydbm` module has been renamed to :mod:`dbm` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

.. index::
   module: dbhash
   module: bsddb
   module: gdbm
   module: dbm
   module: dumbdbm

:mod:`anydbm` is a generic interface to variants of the DBM database ---
:mod:`dbhash` (requires :mod:`bsddb`), :mod:`gdbm`, or :mod:`dbm`.  If none of
these modules is installed, the slow-but-simple implementation in module
:mod:`dumbdbm` will be used.


.. function:: open(filename[, flag[, mode]])

   Open the database file *filename* and return a corresponding object.

   If the database file already exists, the :mod:`whichdb` module is used to
   determine its type and the appropriate module is used; if it does not exist,
   the first module listed above that can be imported is used.

   The optional *flag* argument must be one of these values:

   +---------+-------------------------------------------+
   | Value   | Meaning                                   |
   +=========+===========================================+
   | ``'r'`` | Open existing database for reading only   |
   |         | (default)                                 |
   +---------+-------------------------------------------+
   | ``'w'`` | Open existing database for reading and    |
   |         | writing                                   |
   +---------+-------------------------------------------+
   | ``'c'`` | Open database for reading and writing,    |
   |         | creating it if it doesn't exist           |
   +---------+-------------------------------------------+
   | ``'n'`` | Always create a new, empty database, open |
   |         | for reading and writing                   |
   +---------+-------------------------------------------+

   If not specified, the default value is ``'r'``.

   The optional *mode* argument is the Unix mode of the file, used only when the
   database has to be created.  It defaults to octal ``0666`` (and will be
   modified by the prevailing umask).


.. exception:: error

   A tuple containing the exceptions that can be raised by each of the supported
   modules, with a unique exception also named :exc:`anydbm.error` as the first
   item --- the latter is used when :exc:`anydbm.error` is raised.

The object returned by :func:`.open` supports most of the same functionality as
dictionaries; keys and their corresponding values can be stored, retrieved, and
deleted, and the :meth:`has_key` and :meth:`keys` methods are available.  Keys
and values must always be strings.

The following example records some hostnames and a corresponding title,  and
then prints out the contents of the database::

   import anydbm

   # Open database, creating it if necessary.
   db = anydbm.open('cache', 'c')

   # Record some values
   db['www.python.org'] = 'Python Website'
   db['www.cnn.com'] = 'Cable News Network'

   # Loop through contents.  Other dictionary methods
   # such as .keys(), .values() also work.
   for k, v in db.iteritems():
       print k, '\t', v

   # Storing a non-string key or value will raise an exception (most
   # likely a TypeError).
   db['www.yahoo.com'] = 4

   # Close when done.
   db.close()


In addition to the dictionary-like methods, ``anydbm`` objects
provide the following method:

.. function:: close()

   Close the ``anydbm`` database.


.. seealso::

   Module :mod:`dbhash`
      BSD ``db`` database interface.

   Module :mod:`dbm`
      Standard Unix database interface.

   Module :mod:`dumbdbm`
      Portable implementation of the ``dbm`` interface.

   Module :mod:`gdbm`
      GNU database interface, based on the ``dbm`` interface.

   Module :mod:`shelve`
      General object persistence built on top of  the Python ``dbm`` interface.

   Module :mod:`whichdb`
      Utility module used to determine the type of an existing database.

PK	%�\To����'html/_sources/library/archiving.rst.txtnu�[���
.. _archiving:

******************************
Data Compression and Archiving
******************************

The modules described in this chapter support data compression with the zlib,
gzip, and bzip2 algorithms, and  the creation of ZIP- and tar-format archives.
See also :ref:`archiving-operations` provided by the :mod:`shutil` module.


.. toctree::

   zlib.rst
   gzip.rst
   bz2.rst
   zipfile.rst
   tarfile.rst
PK	%�\քv��#�#&html/_sources/library/argparse.rst.txtnu�[���:mod:`argparse` --- Parser for command-line options, arguments and sub-commands
===============================================================================

.. module:: argparse
   :synopsis: Command-line option and argument parsing library.
.. moduleauthor:: Steven Bethard <steven.bethard@gmail.com>
.. sectionauthor:: Steven Bethard <steven.bethard@gmail.com>

.. versionadded:: 2.7

**Source code:** :source:`Lib/argparse.py`

--------------

.. sidebar:: Tutorial

   This page contains the API reference information. For a more gentle
   introduction to Python command-line parsing, have a look at the
   :ref:`argparse tutorial <argparse-tutorial>`.

The :mod:`argparse` module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and :mod:`argparse`
will figure out how to parse those out of :data:`sys.argv`.  The :mod:`argparse`
module also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.


Example
-------

The following code is a Python program that takes a list of integers and
produces either the sum or the max::

   import argparse

   parser = argparse.ArgumentParser(description='Process some integers.')
   parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
   parser.add_argument('--sum', dest='accumulate', action='store_const',
                       const=sum, default=max,
                       help='sum the integers (default: find the max)')

   args = parser.parse_args()
   print args.accumulate(args.integers)

Assuming the Python code above is saved into a file called ``prog.py``, it can
be run at the command line and provides useful help messages:

.. code-block:: shell-session

   $ python prog.py -h
   usage: prog.py [-h] [--sum] N [N ...]

   Process some integers.

   positional arguments:
    N           an integer for the accumulator

   optional arguments:
    -h, --help  show this help message and exit
    --sum       sum the integers (default: find the max)

When run with the appropriate arguments, it prints either the sum or the max of
the command-line integers:

.. code-block:: shell-session

   $ python prog.py 1 2 3 4
   4

   $ python prog.py 1 2 3 4 --sum
   10

If invalid arguments are passed in, it will issue an error:

.. code-block:: shell-session

   $ python prog.py a b c
   usage: prog.py [-h] [--sum] N [N ...]
   prog.py: error: argument N: invalid int value: 'a'

The following sections walk you through this example.


Creating a parser
^^^^^^^^^^^^^^^^^

The first step in using the :mod:`argparse` is creating an
:class:`ArgumentParser` object::

   >>> parser = argparse.ArgumentParser(description='Process some integers.')

The :class:`ArgumentParser` object will hold all the information necessary to
parse the command line into Python data types.


Adding arguments
^^^^^^^^^^^^^^^^

Filling an :class:`ArgumentParser` with information about program arguments is
done by making calls to the :meth:`~ArgumentParser.add_argument` method.
Generally, these calls tell the :class:`ArgumentParser` how to take the strings
on the command line and turn them into objects.  This information is stored and
used when :meth:`~ArgumentParser.parse_args` is called. For example::

   >>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
   ...                     help='an integer for the accumulator')
   >>> parser.add_argument('--sum', dest='accumulate', action='store_const',
   ...                     const=sum, default=max,
   ...                     help='sum the integers (default: find the max)')

Later, calling :meth:`~ArgumentParser.parse_args` will return an object with
two attributes, ``integers`` and ``accumulate``.  The ``integers`` attribute
will be a list of one or more ints, and the ``accumulate`` attribute will be
either the :func:`sum` function, if ``--sum`` was specified at the command line,
or the :func:`max` function if it was not.


Parsing arguments
^^^^^^^^^^^^^^^^^

:class:`ArgumentParser` parses arguments through the
:meth:`~ArgumentParser.parse_args` method.  This will inspect the command line,
convert each argument to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple :class:`Namespace` object will be built up from
attributes parsed out of the command line::

   >>> parser.parse_args(['--sum', '7', '-1', '42'])
   Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script, :meth:`~ArgumentParser.parse_args` will typically be called with no
arguments, and the :class:`ArgumentParser` will automatically determine the
command-line arguments from :data:`sys.argv`.


ArgumentParser objects
----------------------

.. class:: ArgumentParser(prog=None, usage=None, description=None, \
                          epilog=None, parents=[], \
                          formatter_class=argparse.HelpFormatter, \
                          prefix_chars='-', fromfile_prefix_chars=None, \
                          argument_default=None, conflict_handler='error', \
                          add_help=True)

   Create a new :class:`ArgumentParser` object. All parameters should be passed
   as keyword arguments. Each parameter has its own more detailed description
   below, but in short they are:

   * prog_ - The name of the program (default: ``sys.argv[0]``)

   * usage_ - The string describing the program usage (default: generated from
     arguments added to parser)

   * description_ - Text to display before the argument help (default: none)

   * epilog_ - Text to display after the argument help (default: none)

   * parents_ - A list of :class:`ArgumentParser` objects whose arguments should
     also be included

   * formatter_class_ - A class for customizing the help output

   * prefix_chars_ - The set of characters that prefix optional arguments
     (default: '-')

   * fromfile_prefix_chars_ - The set of characters that prefix files from
     which additional arguments should be read (default: ``None``)

   * argument_default_ - The global default value for arguments
     (default: ``None``)

   * conflict_handler_ - The strategy for resolving conflicting optionals
     (usually unnecessary)

   * add_help_ - Add a ``-h/--help`` option to the parser (default: ``True``)

The following sections describe how each of these are used.


prog
^^^^

By default, :class:`ArgumentParser` objects use ``sys.argv[0]`` to determine
how to display the name of the program in help messages.  This default is almost
always desirable because it will make the help messages match how the program was
invoked on the command line.  For example, consider a file named
``myprogram.py`` with the following code::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument('--foo', help='foo help')
   args = parser.parse_args()

The help for this program will display ``myprogram.py`` as the program name
(regardless of where the program was invoked from):

.. code-block:: shell-session

   $ python myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO   foo help
   $ cd ..
   $ python subdir/myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO   foo help

To change this default behavior, another value can be supplied using the
``prog=`` argument to :class:`ArgumentParser`::

   >>> parser = argparse.ArgumentParser(prog='myprogram')
   >>> parser.print_help()
   usage: myprogram [-h]

   optional arguments:
    -h, --help  show this help message and exit

Note that the program name, whether determined from ``sys.argv[0]`` or from the
``prog=`` argument, is available to help messages using the ``%(prog)s`` format
specifier.

::

   >>> parser = argparse.ArgumentParser(prog='myprogram')
   >>> parser.add_argument('--foo', help='foo of the %(prog)s program')
   >>> parser.print_help()
   usage: myprogram [-h] [--foo FOO]

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO   foo of the myprogram program


usage
^^^^^

By default, :class:`ArgumentParser` calculates the usage message from the
arguments it contains::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('--foo', nargs='?', help='foo help')
   >>> parser.add_argument('bar', nargs='+', help='bar help')
   >>> parser.print_help()
   usage: PROG [-h] [--foo [FOO]] bar [bar ...]

   positional arguments:
    bar          bar help

   optional arguments:
    -h, --help   show this help message and exit
    --foo [FOO]  foo help

The default message can be overridden with the ``usage=`` keyword argument::

   >>> parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]')
   >>> parser.add_argument('--foo', nargs='?', help='foo help')
   >>> parser.add_argument('bar', nargs='+', help='bar help')
   >>> parser.print_help()
   usage: PROG [options]

   positional arguments:
    bar          bar help

   optional arguments:
    -h, --help   show this help message and exit
    --foo [FOO]  foo help

The ``%(prog)s`` format specifier is available to fill in the program name in
your usage messages.


description
^^^^^^^^^^^

Most calls to the :class:`ArgumentParser` constructor will use the
``description=`` keyword argument.  This argument gives a brief description of
what the program does and how it works.  In help messages, the description is
displayed between the command-line usage string and the help messages for the
various arguments::

   >>> parser = argparse.ArgumentParser(description='A foo that bars')
   >>> parser.print_help()
   usage: argparse.py [-h]

   A foo that bars

   optional arguments:
    -h, --help  show this help message and exit

By default, the description will be line-wrapped so that it fits within the
given space.  To change this behavior, see the formatter_class_ argument.


epilog
^^^^^^

Some programs like to display additional description of the program after the
description of the arguments.  Such text can be specified using the ``epilog=``
argument to :class:`ArgumentParser`::

   >>> parser = argparse.ArgumentParser(
   ...     description='A foo that bars',
   ...     epilog="And that's how you'd foo a bar")
   >>> parser.print_help()
   usage: argparse.py [-h]

   A foo that bars

   optional arguments:
    -h, --help  show this help message and exit

   And that's how you'd foo a bar

As with the description_ argument, the ``epilog=`` text is by default
line-wrapped, but this behavior can be adjusted with the formatter_class_
argument to :class:`ArgumentParser`.


parents
^^^^^^^

Sometimes, several parsers share a common set of arguments. Rather than
repeating the definitions of these arguments, a single parser with all the
shared arguments and passed to ``parents=`` argument to :class:`ArgumentParser`
can be used.  The ``parents=`` argument takes a list of :class:`ArgumentParser`
objects, collects all the positional and optional actions from them, and adds
these actions to the :class:`ArgumentParser` object being constructed::

   >>> parent_parser = argparse.ArgumentParser(add_help=False)
   >>> parent_parser.add_argument('--parent', type=int)

   >>> foo_parser = argparse.ArgumentParser(parents=[parent_parser])
   >>> foo_parser.add_argument('foo')
   >>> foo_parser.parse_args(['--parent', '2', 'XXX'])
   Namespace(foo='XXX', parent=2)

   >>> bar_parser = argparse.ArgumentParser(parents=[parent_parser])
   >>> bar_parser.add_argument('--bar')
   >>> bar_parser.parse_args(['--bar', 'YYY'])
   Namespace(bar='YYY', parent=None)

Note that most parent parsers will specify ``add_help=False``.  Otherwise, the
:class:`ArgumentParser` will see two ``-h/--help`` options (one in the parent
and one in the child) and raise an error.

.. note::
   You must fully initialize the parsers before passing them via ``parents=``.
   If you change the parent parsers after the child parser, those changes will
   not be reflected in the child.


formatter_class
^^^^^^^^^^^^^^^

:class:`ArgumentParser` objects allow the help formatting to be customized by
specifying an alternate formatting class.  Currently, there are three such
classes:

.. class:: RawDescriptionHelpFormatter
           RawTextHelpFormatter
           ArgumentDefaultsHelpFormatter

The first two allow more control over how textual descriptions are displayed,
while the last automatically adds information about argument default values.

By default, :class:`ArgumentParser` objects line-wrap the description_ and
epilog_ texts in command-line help messages::

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     description='''this description
   ...         was indented weird
   ...             but that is okay''',
   ...     epilog='''
   ...             likewise for this epilog whose whitespace will
   ...         be cleaned up and whose words will be wrapped
   ...         across a couple lines''')
   >>> parser.print_help()
   usage: PROG [-h]

   this description was indented weird but that is okay

   optional arguments:
    -h, --help  show this help message and exit

   likewise for this epilog whose whitespace will be cleaned up and whose words
   will be wrapped across a couple lines

Passing :class:`RawDescriptionHelpFormatter` as ``formatter_class=``
indicates that description_ and epilog_ are already correctly formatted and
should not be line-wrapped::

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     formatter_class=argparse.RawDescriptionHelpFormatter,
   ...     description=textwrap.dedent('''\
   ...         Please do not mess up this text!
   ...         --------------------------------
   ...             I have indented it
   ...             exactly the way
   ...             I want it
   ...         '''))
   >>> parser.print_help()
   usage: PROG [-h]

   Please do not mess up this text!
   --------------------------------
      I have indented it
      exactly the way
      I want it

   optional arguments:
    -h, --help  show this help message and exit

:class:`RawTextHelpFormatter` maintains whitespace for all sorts of help text,
including argument descriptions. However, multiple new lines are replaced with
one. If you wish to preserve multiple blank lines, add spaces between the
newlines.

The other formatter class available, :class:`ArgumentDefaultsHelpFormatter`,
will add information about the default value of each of the arguments::

   >>> parser = argparse.ArgumentParser(
   ...     prog='PROG',
   ...     formatter_class=argparse.ArgumentDefaultsHelpFormatter)
   >>> parser.add_argument('--foo', type=int, default=42, help='FOO!')
   >>> parser.add_argument('bar', nargs='*', default=[1, 2, 3], help='BAR!')
   >>> parser.print_help()
   usage: PROG [-h] [--foo FOO] [bar [bar ...]]

   positional arguments:
    bar         BAR! (default: [1, 2, 3])

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO   FOO! (default: 42)


prefix_chars
^^^^^^^^^^^^

Most command-line options will use ``-`` as the prefix, e.g. ``-f/--foo``.
Parsers that need to support different or additional prefix
characters, e.g. for options
like ``+f`` or ``/foo``, may specify them using the ``prefix_chars=`` argument
to the ArgumentParser constructor::

   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='-+')
   >>> parser.add_argument('+f')
   >>> parser.add_argument('++bar')
   >>> parser.parse_args('+f X ++bar Y'.split())
   Namespace(bar='Y', f='X')

The ``prefix_chars=`` argument defaults to ``'-'``. Supplying a set of
characters that does not include ``-`` will cause ``-f/--foo`` options to be
disallowed.


fromfile_prefix_chars
^^^^^^^^^^^^^^^^^^^^^

Sometimes, for example when dealing with a particularly long argument lists, it
may make sense to keep the list of arguments in a file rather than typing it out
at the command line.  If the ``fromfile_prefix_chars=`` argument is given to the
:class:`ArgumentParser` constructor, then arguments that start with any of the
specified characters will be treated as files, and will be replaced by the
arguments they contain.  For example::

   >>> with open('args.txt', 'w') as fp:
   ...     fp.write('-f\nbar')
   >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
   >>> parser.add_argument('-f')
   >>> parser.parse_args(['-f', 'foo', '@args.txt'])
   Namespace(f='bar')

Arguments read from a file must by default be one per line (but see also
:meth:`~ArgumentParser.convert_arg_line_to_args`) and are treated as if they
were in the same place as the original file referencing argument on the command
line.  So in the example above, the expression ``['-f', 'foo', '@args.txt']``
is considered equivalent to the expression ``['-f', 'foo', '-f', 'bar']``.

The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
arguments will never be treated as file references.


argument_default
^^^^^^^^^^^^^^^^

Generally, argument defaults are specified either by passing a default to
:meth:`~ArgumentParser.add_argument` or by calling the
:meth:`~ArgumentParser.set_defaults` methods with a specific set of name-value
pairs.  Sometimes however, it may be useful to specify a single parser-wide
default for arguments.  This can be accomplished by passing the
``argument_default=`` keyword argument to :class:`ArgumentParser`.  For example,
to globally suppress attribute creation on :meth:`~ArgumentParser.parse_args`
calls, we supply ``argument_default=SUPPRESS``::

   >>> parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS)
   >>> parser.add_argument('--foo')
   >>> parser.add_argument('bar', nargs='?')
   >>> parser.parse_args(['--foo', '1', 'BAR'])
   Namespace(bar='BAR', foo='1')
   >>> parser.parse_args([])
   Namespace()


conflict_handler
^^^^^^^^^^^^^^^^

:class:`ArgumentParser` objects do not allow two actions with the same option
string.  By default, :class:`ArgumentParser` objects raise an exception if an
attempt is made to create an argument with an option string that is already in
use::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-f', '--foo', help='old foo help')
   >>> parser.add_argument('--foo', help='new foo help')
   Traceback (most recent call last):
    ..
   ArgumentError: argument --foo: conflicting option string(s): --foo

Sometimes (e.g. when using parents_) it may be useful to simply override any
older arguments with the same option string.  To get this behavior, the value
``'resolve'`` can be supplied to the ``conflict_handler=`` argument of
:class:`ArgumentParser`::

   >>> parser = argparse.ArgumentParser(prog='PROG', conflict_handler='resolve')
   >>> parser.add_argument('-f', '--foo', help='old foo help')
   >>> parser.add_argument('--foo', help='new foo help')
   >>> parser.print_help()
   usage: PROG [-h] [-f FOO] [--foo FOO]

   optional arguments:
    -h, --help  show this help message and exit
    -f FOO      old foo help
    --foo FOO   new foo help

Note that :class:`ArgumentParser` objects only remove an action if all of its
option strings are overridden.  So, in the example above, the old ``-f/--foo``
action is retained as the ``-f`` action, because only the ``--foo`` option
string was overridden.


add_help
^^^^^^^^

By default, ArgumentParser objects add an option which simply displays
the parser's help message. For example, consider a file named
``myprogram.py`` containing the following code::

   import argparse
   parser = argparse.ArgumentParser()
   parser.add_argument('--foo', help='foo help')
   args = parser.parse_args()

If ``-h`` or ``--help`` is supplied at the command line, the ArgumentParser
help will be printed:

.. code-block:: shell-session

   $ python myprogram.py --help
   usage: myprogram.py [-h] [--foo FOO]

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO   foo help

Occasionally, it may be useful to disable the addition of this help option.
This can be achieved by passing ``False`` as the ``add_help=`` argument to
:class:`ArgumentParser`::

   >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
   >>> parser.add_argument('--foo', help='foo help')
   >>> parser.print_help()
   usage: PROG [--foo FOO]

   optional arguments:
    --foo FOO  foo help

The help option is typically ``-h/--help``. The exception to this is
if the ``prefix_chars=`` is specified and does not include ``-``, in
which case ``-h`` and ``--help`` are not valid options.  In
this case, the first character in ``prefix_chars`` is used to prefix
the help options::

   >>> parser = argparse.ArgumentParser(prog='PROG', prefix_chars='+/')
   >>> parser.print_help()
   usage: PROG [+h]

   optional arguments:
     +h, ++help  show this help message and exit


The add_argument() method
-------------------------

.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
                           [const], [default], [type], [choices], [required], \
                           [help], [metavar], [dest])

   Define how a single command-line argument should be parsed.  Each parameter
   has its own more detailed description below, but in short they are:

   * `name or flags`_ - Either a name or a list of option strings, e.g. ``foo``
     or ``-f, --foo``.

   * action_ - The basic type of action to be taken when this argument is
     encountered at the command line.

   * nargs_ - The number of command-line arguments that should be consumed.

   * const_ - A constant value required by some action_ and nargs_ selections.

   * default_ - The value produced if the argument is absent from the
     command line.

   * type_ - The type to which the command-line argument should be converted.

   * choices_ - A container of the allowable values for the argument.

   * required_ - Whether or not the command-line option may be omitted
     (optionals only).

   * help_ - A brief description of what the argument does.

   * metavar_ - A name for the argument in usage messages.

   * dest_ - The name of the attribute to be added to the object returned by
     :meth:`parse_args`.

The following sections describe how each of these are used.


name or flags
^^^^^^^^^^^^^

The :meth:`~ArgumentParser.add_argument` method must know whether an optional
argument, like ``-f`` or ``--foo``, or a positional argument, like a list of
filenames, is expected.  The first arguments passed to
:meth:`~ArgumentParser.add_argument` must therefore be either a series of
flags, or a simple argument name.  For example, an optional argument could
be created like::

   >>> parser.add_argument('-f', '--foo')

while a positional argument could be created like::

   >>> parser.add_argument('bar')

When :meth:`~ArgumentParser.parse_args` is called, optional arguments will be
identified by the ``-`` prefix, and the remaining arguments will be assumed to
be positional::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-f', '--foo')
   >>> parser.add_argument('bar')
   >>> parser.parse_args(['BAR'])
   Namespace(bar='BAR', foo=None)
   >>> parser.parse_args(['BAR', '--foo', 'FOO'])
   Namespace(bar='BAR', foo='FOO')
   >>> parser.parse_args(['--foo', 'FOO'])
   usage: PROG [-h] [-f FOO] bar
   PROG: error: too few arguments


action
^^^^^^

:class:`ArgumentParser` objects associate command-line arguments with actions.  These
actions can do just about anything with the command-line arguments associated with
them, though most actions simply add an attribute to the object returned by
:meth:`~ArgumentParser.parse_args`.  The ``action`` keyword argument specifies
how the command-line arguments should be handled. The supplied actions are:

* ``'store'`` - This just stores the argument's value.  This is the default
  action. For example::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.parse_args('--foo 1'.split())
    Namespace(foo='1')

* ``'store_const'`` - This stores the value specified by the const_ keyword
  argument.  The ``'store_const'`` action is most commonly used with
  optional arguments that specify some sort of flag.  For example::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_const', const=42)
    >>> parser.parse_args(['--foo'])
    Namespace(foo=42)

* ``'store_true'`` and ``'store_false'`` - These are special cases of
  ``'store_const'`` using for storing the values ``True`` and ``False``
  respectively.  In addition, they create default values of ``False`` and ``True``
  respectively.  For example::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='store_true')
    >>> parser.add_argument('--bar', action='store_false')
    >>> parser.add_argument('--baz', action='store_false')
    >>> parser.parse_args('--foo --bar'.split())
    Namespace(bar=False, baz=True, foo=True)

* ``'append'`` - This stores a list, and appends each argument value to the
  list.  This is useful to allow an option to be specified multiple times.
  Example usage::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='append')
    >>> parser.parse_args('--foo 1 --foo 2'.split())
    Namespace(foo=['1', '2'])

* ``'append_const'`` - This stores a list, and appends the value specified by
  the const_ keyword argument to the list.  (Note that the const_ keyword
  argument defaults to ``None``.)  The ``'append_const'`` action is typically
  useful when multiple arguments need to store constants to the same list. For
  example::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
    >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
    >>> parser.parse_args('--str --int'.split())
    Namespace(types=[<type 'str'>, <type 'int'>])

* ``'count'`` - This counts the number of times a keyword argument occurs. For
  example, this is useful for increasing verbosity levels::

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--verbose', '-v', action='count')
    >>> parser.parse_args(['-vvv'])
    Namespace(verbose=3)

* ``'help'`` - This prints a complete help message for all the options in the
  current parser and then exits. By default a help action is automatically
  added to the parser. See :class:`ArgumentParser` for details of how the
  output is created.

* ``'version'`` - This expects a ``version=`` keyword argument in the
  :meth:`~ArgumentParser.add_argument` call, and prints version information
  and exits when invoked::

    >>> import argparse
    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')
    >>> parser.parse_args(['--version'])
    PROG 2.0

You may also specify an arbitrary action by passing an Action subclass or
other object that implements the same interface.  The recommended way to do
this is to extend :class:`Action`, overriding the ``__call__`` method
and optionally the ``__init__`` method.

An example of a custom action::

   >>> class FooAction(argparse.Action):
   ...     def __init__(self, option_strings, dest, nargs=None, **kwargs):
   ...         if nargs is not None:
   ...             raise ValueError("nargs not allowed")
   ...         super(FooAction, self).__init__(option_strings, dest, **kwargs)
   ...     def __call__(self, parser, namespace, values, option_string=None):
   ...         print '%r %r %r' % (namespace, values, option_string)
   ...         setattr(namespace, self.dest, values)
   ...
   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', action=FooAction)
   >>> parser.add_argument('bar', action=FooAction)
   >>> args = parser.parse_args('1 --foo 2'.split())
   Namespace(bar=None, foo=None) '1' None
   Namespace(bar='1', foo=None) '2' '--foo'
   >>> args
   Namespace(bar='1', foo='2')

For more details, see :class:`Action`.

nargs
^^^^^

ArgumentParser objects usually associate a single command-line argument with a
single action to be taken.  The ``nargs`` keyword argument associates a
different number of command-line arguments with a single action.  The supported
values are:

* ``N`` (an integer).  ``N`` arguments from the command line will be gathered
  together into a list.  For example::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs=2)
     >>> parser.add_argument('bar', nargs=1)
     >>> parser.parse_args('c --foo a b'.split())
     Namespace(bar=['c'], foo=['a', 'b'])

  Note that ``nargs=1`` produces a list of one item.  This is different from
  the default, in which the item is produced by itself.

* ``'?'``. One argument will be consumed from the command line if possible, and
  produced as a single item.  If no command-line argument is present, the value from
  default_ will be produced.  Note that for optional arguments, there is an
  additional case - the option string is present but not followed by a
  command-line argument.  In this case the value from const_ will be produced.  Some
  examples to illustrate this::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs='?', const='c', default='d')
     >>> parser.add_argument('bar', nargs='?', default='d')
     >>> parser.parse_args(['XX', '--foo', 'YY'])
     Namespace(bar='XX', foo='YY')
     >>> parser.parse_args(['XX', '--foo'])
     Namespace(bar='XX', foo='c')
     >>> parser.parse_args([])
     Namespace(bar='d', foo='d')

  One of the more common uses of ``nargs='?'`` is to allow optional input and
  output files::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
     ...                     default=sys.stdin)
     >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
     ...                     default=sys.stdout)
     >>> parser.parse_args(['input.txt', 'output.txt'])
     Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>,
               outfile=<open file 'output.txt', mode 'w' at 0x...>)
     >>> parser.parse_args([])
     Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>,
               outfile=<open file '<stdout>', mode 'w' at 0x...>)

* ``'*'``.  All command-line arguments present are gathered into a list.  Note that
  it generally doesn't make much sense to have more than one positional argument
  with ``nargs='*'``, but multiple optional arguments with ``nargs='*'`` is
  possible.  For example::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', nargs='*')
     >>> parser.add_argument('--bar', nargs='*')
     >>> parser.add_argument('baz', nargs='*')
     >>> parser.parse_args('a b --foo x y --bar 1 2'.split())
     Namespace(bar=['1', '2'], baz=['a', 'b'], foo=['x', 'y'])

* ``'+'``. Just like ``'*'``, all command-line args present are gathered into a
  list.  Additionally, an error message will be generated if there wasn't at
  least one command-line argument present.  For example::

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('foo', nargs='+')
     >>> parser.parse_args(['a', 'b'])
     Namespace(foo=['a', 'b'])
     >>> parser.parse_args([])
     usage: PROG [-h] foo [foo ...]
     PROG: error: too few arguments

.. _`argparse.REMAINDER`:

* ``argparse.REMAINDER``.  All the remaining command-line arguments are gathered
  into a list.  This is commonly useful for command line utilities that dispatch
  to other command line utilities::

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('--foo')
     >>> parser.add_argument('command')
     >>> parser.add_argument('args', nargs=argparse.REMAINDER)
     >>> print parser.parse_args('--foo B cmd --arg1 XX ZZ'.split())
     Namespace(args=['--arg1', 'XX', 'ZZ'], command='cmd', foo='B')

If the ``nargs`` keyword argument is not provided, the number of arguments consumed
is determined by the action_.  Generally this means a single command-line argument
will be consumed and a single item (not a list) will be produced.


const
^^^^^

The ``const`` argument of :meth:`~ArgumentParser.add_argument` is used to hold
constant values that are not read from the command line but are required for
the various :class:`ArgumentParser` actions.  The two most common uses of it are:

* When :meth:`~ArgumentParser.add_argument` is called with
  ``action='store_const'`` or ``action='append_const'``.  These actions add the
  ``const`` value to one of the attributes of the object returned by
  :meth:`~ArgumentParser.parse_args`. See the action_ description for examples.

* When :meth:`~ArgumentParser.add_argument` is called with option strings
  (like ``-f`` or ``--foo``) and ``nargs='?'``.  This creates an optional
  argument that can be followed by zero or one command-line arguments.
  When parsing the command line, if the option string is encountered with no
  command-line argument following it, the value of ``const`` will be assumed instead.
  See the nargs_ description for examples.

With the ``'store_const'`` and ``'append_const'`` actions, the ``const``
keyword argument must be given.  For other actions, it defaults to ``None``.


default
^^^^^^^

All optional arguments and some positional arguments may be omitted at the
command line.  The ``default`` keyword argument of
:meth:`~ArgumentParser.add_argument`, whose value defaults to ``None``,
specifies what value should be used if the command-line argument is not present.
For optional arguments, the ``default`` value is used when the option string
was not present at the command line::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', default=42)
   >>> parser.parse_args(['--foo', '2'])
   Namespace(foo='2')
   >>> parser.parse_args([])
   Namespace(foo=42)

If the ``default`` value is a string, the parser parses the value as if it
were a command-line argument.  In particular, the parser applies any type_
conversion argument, if provided, before setting the attribute on the
:class:`Namespace` return value.  Otherwise, the parser uses the value as is::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--length', default='10', type=int)
   >>> parser.add_argument('--width', default=10.5, type=int)
   >>> parser.parse_args()
   Namespace(length=10, width=10.5)

For positional arguments with nargs_ equal to ``?`` or ``*``, the ``default`` value
is used when no command-line argument was present::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('foo', nargs='?', default=42)
   >>> parser.parse_args(['a'])
   Namespace(foo='a')
   >>> parser.parse_args([])
   Namespace(foo=42)


Providing ``default=argparse.SUPPRESS`` causes no attribute to be added if the
command-line argument was not present.::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', default=argparse.SUPPRESS)
   >>> parser.parse_args([])
   Namespace()
   >>> parser.parse_args(['--foo', '1'])
   Namespace(foo='1')


type
^^^^

By default, :class:`ArgumentParser` objects read command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, like a :class:`float` or :class:`int`.  The
``type`` keyword argument of :meth:`~ArgumentParser.add_argument` allows any
necessary type-checking and type conversions to be performed.  Common built-in
types and functions can be used directly as the value of the ``type`` argument::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('foo', type=int)
   >>> parser.add_argument('bar', type=file)
   >>> parser.parse_args('2 temp.txt'.split())
   Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)

See the section on the default_ keyword argument for information on when the
``type`` argument is applied to default arguments.

To ease the use of various types of files, the argparse module provides the
factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
``file`` object.  For example, ``FileType('w')`` can be used to create a
writable file::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('bar', type=argparse.FileType('w'))
   >>> parser.parse_args(['out.txt'])
   Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)

``type=`` can take any callable that takes a single string argument and returns
the converted value::

   >>> def perfect_square(string):
   ...     value = int(string)
   ...     sqrt = math.sqrt(value)
   ...     if sqrt != int(sqrt):
   ...         msg = "%r is not a perfect square" % string
   ...         raise argparse.ArgumentTypeError(msg)
   ...     return value
   ...
   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('foo', type=perfect_square)
   >>> parser.parse_args(['9'])
   Namespace(foo=9)
   >>> parser.parse_args(['7'])
   usage: PROG [-h] foo
   PROG: error: argument foo: '7' is not a perfect square

The choices_ keyword argument may be more convenient for type checkers that
simply check against a range of values::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('foo', type=int, choices=xrange(5, 10))
   >>> parser.parse_args(['7'])
   Namespace(foo=7)
   >>> parser.parse_args(['11'])
   usage: PROG [-h] {5,6,7,8,9}
   PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)

See the choices_ section for more details.


choices
^^^^^^^

Some command-line arguments should be selected from a restricted set of values.
These can be handled by passing a container object as the *choices* keyword
argument to :meth:`~ArgumentParser.add_argument`.  When the command line is
parsed, argument values will be checked, and an error message will be displayed
if the argument was not one of the acceptable values::

   >>> parser = argparse.ArgumentParser(prog='game.py')
   >>> parser.add_argument('move', choices=['rock', 'paper', 'scissors'])
   >>> parser.parse_args(['rock'])
   Namespace(move='rock')
   >>> parser.parse_args(['fire'])
   usage: game.py [-h] {rock,paper,scissors}
   game.py: error: argument move: invalid choice: 'fire' (choose from 'rock',
   'paper', 'scissors')

Note that inclusion in the *choices* container is checked after any type_
conversions have been performed, so the type of the objects in the *choices*
container should match the type_ specified::

   >>> parser = argparse.ArgumentParser(prog='doors.py')
   >>> parser.add_argument('door', type=int, choices=range(1, 4))
   >>> print(parser.parse_args(['3']))
   Namespace(door=3)
   >>> parser.parse_args(['4'])
   usage: doors.py [-h] {1,2,3}
   doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)

Any object that supports the ``in`` operator can be passed as the *choices*
value, so :class:`dict` objects, :class:`set` objects, custom containers,
etc. are all supported.


required
^^^^^^^^

In general, the :mod:`argparse` module assumes that flags like ``-f`` and ``--bar``
indicate *optional* arguments, which can always be omitted at the command line.
To make an option *required*, ``True`` can be specified for the ``required=``
keyword argument to :meth:`~ArgumentParser.add_argument`::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', required=True)
   >>> parser.parse_args(['--foo', 'BAR'])
   Namespace(foo='BAR')
   >>> parser.parse_args([])
   usage: argparse.py [-h] [--foo FOO]
   argparse.py: error: option --foo is required

As the example shows, if an option is marked as ``required``,
:meth:`~ArgumentParser.parse_args` will report an error if that option is not
present at the command line.

.. note::

    Required options are generally considered bad form because users expect
    *options* to be *optional*, and thus they should be avoided when possible.


help
^^^^

The ``help`` value is a string containing a brief description of the argument.
When a user requests help (usually by using ``-h`` or ``--help`` at the
command line), these ``help`` descriptions will be displayed with each
argument::

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('--foo', action='store_true',
   ...                     help='foo the bars before frobbling')
   >>> parser.add_argument('bar', nargs='+',
   ...                     help='one of the bars to be frobbled')
   >>> parser.parse_args(['-h'])
   usage: frobble [-h] [--foo] bar [bar ...]

   positional arguments:
    bar     one of the bars to be frobbled

   optional arguments:
    -h, --help  show this help message and exit
    --foo   foo the bars before frobbling

The ``help`` strings can include various format specifiers to avoid repetition
of things like the program name or the argument default_.  The available
specifiers include the program name, ``%(prog)s`` and most keyword arguments to
:meth:`~ArgumentParser.add_argument`, e.g. ``%(default)s``, ``%(type)s``, etc.::

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('bar', nargs='?', type=int, default=42,
   ...                     help='the bar to %(prog)s (default: %(default)s)')
   >>> parser.print_help()
   usage: frobble [-h] [bar]

   positional arguments:
    bar     the bar to frobble (default: 42)

   optional arguments:
    -h, --help  show this help message and exit

:mod:`argparse` supports silencing the help entry for certain options, by
setting the ``help`` value to ``argparse.SUPPRESS``::

   >>> parser = argparse.ArgumentParser(prog='frobble')
   >>> parser.add_argument('--foo', help=argparse.SUPPRESS)
   >>> parser.print_help()
   usage: frobble [-h]

   optional arguments:
     -h, --help  show this help message and exit


metavar
^^^^^^^

When :class:`ArgumentParser` generates help messages, it needs some way to refer
to each expected argument.  By default, ArgumentParser objects use the dest_
value as the "name" of each object.  By default, for positional argument
actions, the dest_ value is used directly, and for optional argument actions,
the dest_ value is uppercased.  So, a single positional argument with
``dest='bar'`` will be referred to as ``bar``. A single
optional argument ``--foo`` that should be followed by a single command-line argument
will be referred to as ``FOO``.  An example::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> parser.add_argument('bar')
   >>> parser.parse_args('X --foo Y'.split())
   Namespace(bar='X', foo='Y')
   >>> parser.print_help()
   usage:  [-h] [--foo FOO] bar

   positional arguments:
    bar

   optional arguments:
    -h, --help  show this help message and exit
    --foo FOO

An alternative name can be specified with ``metavar``::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', metavar='YYY')
   >>> parser.add_argument('bar', metavar='XXX')
   >>> parser.parse_args('X --foo Y'.split())
   Namespace(bar='X', foo='Y')
   >>> parser.print_help()
   usage:  [-h] [--foo YYY] XXX

   positional arguments:
    XXX

   optional arguments:
    -h, --help  show this help message and exit
    --foo YYY

Note that ``metavar`` only changes the *displayed* name - the name of the
attribute on the :meth:`~ArgumentParser.parse_args` object is still determined
by the dest_ value.

Different values of ``nargs`` may cause the metavar to be used multiple times.
Providing a tuple to ``metavar`` specifies a different display for each of the
arguments::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x', nargs=2)
   >>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
   >>> parser.print_help()
   usage: PROG [-h] [-x X X] [--foo bar baz]

   optional arguments:
    -h, --help     show this help message and exit
    -x X X
    --foo bar baz


dest
^^^^

Most :class:`ArgumentParser` actions add some value as an attribute of the
object returned by :meth:`~ArgumentParser.parse_args`.  The name of this
attribute is determined by the ``dest`` keyword argument of
:meth:`~ArgumentParser.add_argument`.  For positional argument actions,
``dest`` is normally supplied as the first argument to
:meth:`~ArgumentParser.add_argument`::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('bar')
   >>> parser.parse_args(['XXX'])
   Namespace(bar='XXX')

For optional argument actions, the value of ``dest`` is normally inferred from
the option strings.  :class:`ArgumentParser` generates the value of ``dest`` by
taking the first long option string and stripping away the initial ``--``
string.  If no long option strings were supplied, ``dest`` will be derived from
the first short option string by stripping the initial ``-`` character.  Any
internal ``-`` characters will be converted to ``_`` characters to make sure
the string is a valid attribute name.  The examples below illustrate this
behavior::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('-f', '--foo-bar', '--foo')
   >>> parser.add_argument('-x', '-y')
   >>> parser.parse_args('-f 1 -x 2'.split())
   Namespace(foo_bar='1', x='2')
   >>> parser.parse_args('--foo 1 -y 2'.split())
   Namespace(foo_bar='1', x='2')

``dest`` allows a custom attribute name to be provided::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', dest='bar')
   >>> parser.parse_args('--foo XXX'.split())
   Namespace(bar='XXX')

Action classes
^^^^^^^^^^^^^^

Action classes implement the Action API, a callable which returns a callable
which processes arguments from the command-line. Any object which follows this
API may be passed as the ``action`` parameter to :meth:`add_argument`.

.. class:: Action(option_strings, dest, nargs=None, const=None, default=None, \
                  type=None, choices=None, required=False, help=None, \
                  metavar=None)

Action objects are used by an ArgumentParser to represent the information needed
to parse a single argument from one or more strings from the command line. The
Action class must accept the two positional arguments plus any keyword arguments
passed to :meth:`ArgumentParser.add_argument` except for the ``action`` itself.

Instances of Action (or return value of any callable to the ``action``
parameter) should have attributes "dest", "option_strings", "default", "type",
"required", "help", etc. defined. The easiest way to ensure these attributes
are defined is to call ``Action.__init__``.

Action instances should be callable, so subclasses must override the
``__call__`` method, which should accept four parameters:

* ``parser`` - The ArgumentParser object which contains this action.

* ``namespace`` - The :class:`Namespace` object that will be returned by
  :meth:`~ArgumentParser.parse_args`.  Most actions add an attribute to this
  object using :func:`setattr`.

* ``values`` - The associated command-line arguments, with any type conversions
  applied.  Type conversions are specified with the type_ keyword argument to
  :meth:`~ArgumentParser.add_argument`.

* ``option_string`` - The option string that was used to invoke this action.
  The ``option_string`` argument is optional, and will be absent if the action
  is associated with a positional argument.

The ``__call__`` method may perform arbitrary actions, but will typically set
attributes on the ``namespace`` based on ``dest`` and ``values``.


The parse_args() method
-----------------------

.. method:: ArgumentParser.parse_args(args=None, namespace=None)

   Convert argument strings to objects and assign them as attributes of the
   namespace.  Return the populated namespace.

   Previous calls to :meth:`add_argument` determine exactly what objects are
   created and how they are assigned. See the documentation for
   :meth:`add_argument` for details.

   * args_ - List of strings to parse.  The default is taken from
     :data:`sys.argv`.

   * namespace_ - An object to take the attributes.  The default is a new empty
     :class:`Namespace` object.


Option value syntax
^^^^^^^^^^^^^^^^^^^

The :meth:`~ArgumentParser.parse_args` method supports several ways of
specifying the value of an option (if it takes one).  In the simplest case, the
option and its value are passed as two separate arguments::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x')
   >>> parser.add_argument('--foo')
   >>> parser.parse_args(['-x', 'X'])
   Namespace(foo=None, x='X')
   >>> parser.parse_args(['--foo', 'FOO'])
   Namespace(foo='FOO', x=None)

For long options (options with names longer than a single character), the option
and value can also be passed as a single command-line argument, using ``=`` to
separate them::

   >>> parser.parse_args(['--foo=FOO'])
   Namespace(foo='FOO', x=None)

For short options (options only one character long), the option and its value
can be concatenated::

   >>> parser.parse_args(['-xX'])
   Namespace(foo=None, x='X')

Several short options can be joined together, using only a single ``-`` prefix,
as long as only the last option (or none of them) requires a value::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x', action='store_true')
   >>> parser.add_argument('-y', action='store_true')
   >>> parser.add_argument('-z')
   >>> parser.parse_args(['-xyzZ'])
   Namespace(x=True, y=True, z='Z')


Invalid arguments
^^^^^^^^^^^^^^^^^

While parsing the command line, :meth:`~ArgumentParser.parse_args` checks for a
variety of errors, including ambiguous options, invalid types, invalid options,
wrong number of positional arguments, etc.  When it encounters such an error,
it exits and prints the error along with a usage message::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('--foo', type=int)
   >>> parser.add_argument('bar', nargs='?')

   >>> # invalid type
   >>> parser.parse_args(['--foo', 'spam'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: argument --foo: invalid int value: 'spam'

   >>> # invalid option
   >>> parser.parse_args(['--bar'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: no such option: --bar

   >>> # wrong number of arguments
   >>> parser.parse_args(['spam', 'badger'])
   usage: PROG [-h] [--foo FOO] [bar]
   PROG: error: extra arguments found: badger


Arguments containing ``-``
^^^^^^^^^^^^^^^^^^^^^^^^^^

The :meth:`~ArgumentParser.parse_args` method attempts to give errors whenever
the user has clearly made a mistake, but some situations are inherently
ambiguous.  For example, the command-line argument ``-1`` could either be an
attempt to specify an option or an attempt to provide a positional argument.
The :meth:`~ArgumentParser.parse_args` method is cautious here: positional
arguments may only begin with ``-`` if they look like negative numbers and
there are no options in the parser that look like negative numbers::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-x')
   >>> parser.add_argument('foo', nargs='?')

   >>> # no negative number options, so -1 is a positional argument
   >>> parser.parse_args(['-x', '-1'])
   Namespace(foo=None, x='-1')

   >>> # no negative number options, so -1 and -5 are positional arguments
   >>> parser.parse_args(['-x', '-1', '-5'])
   Namespace(foo='-5', x='-1')

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-1', dest='one')
   >>> parser.add_argument('foo', nargs='?')

   >>> # negative number options present, so -1 is an option
   >>> parser.parse_args(['-1', 'X'])
   Namespace(foo=None, one='X')

   >>> # negative number options present, so -2 is an option
   >>> parser.parse_args(['-2'])
   usage: PROG [-h] [-1 ONE] [foo]
   PROG: error: no such option: -2

   >>> # negative number options present, so both -1s are options
   >>> parser.parse_args(['-1', '-1'])
   usage: PROG [-h] [-1 ONE] [foo]
   PROG: error: argument -1: expected one argument

If you have positional arguments that must begin with ``-`` and don't look
like negative numbers, you can insert the pseudo-argument ``'--'`` which tells
:meth:`~ArgumentParser.parse_args` that everything after that is a positional
argument::

   >>> parser.parse_args(['--', '-f'])
   Namespace(foo='-f', one=None)

.. _prefix-matching:

Argument abbreviations (prefix matching)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The :meth:`~ArgumentParser.parse_args` method allows long options to be
abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
a unique option)::

   >>> parser = argparse.ArgumentParser(prog='PROG')
   >>> parser.add_argument('-bacon')
   >>> parser.add_argument('-badger')
   >>> parser.parse_args('-bac MMM'.split())
   Namespace(bacon='MMM', badger=None)
   >>> parser.parse_args('-bad WOOD'.split())
   Namespace(bacon=None, badger='WOOD')
   >>> parser.parse_args('-ba BA'.split())
   usage: PROG [-h] [-bacon BACON] [-badger BADGER]
   PROG: error: ambiguous option: -ba could match -badger, -bacon

An error is produced for arguments that could produce more than one options.

.. _args:

Beyond ``sys.argv``
^^^^^^^^^^^^^^^^^^^

Sometimes it may be useful to have an ArgumentParser parse arguments other than those
of :data:`sys.argv`.  This can be accomplished by passing a list of strings to
:meth:`~ArgumentParser.parse_args`.  This is useful for testing at the
interactive prompt::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument(
   ...     'integers', metavar='int', type=int, choices=xrange(10),
   ...     nargs='+', help='an integer in the range 0..9')
   >>> parser.add_argument(
   ...     '--sum', dest='accumulate', action='store_const', const=sum,
   ...     default=max, help='sum the integers (default: find the max)')
   >>> parser.parse_args(['1', '2', '3', '4'])
   Namespace(accumulate=<built-in function max>, integers=[1, 2, 3, 4])
   >>> parser.parse_args(['1', '2', '3', '4', '--sum'])
   Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 4])

.. _namespace:

The Namespace object
^^^^^^^^^^^^^^^^^^^^

.. class:: Namespace

   Simple class used by default by :meth:`~ArgumentParser.parse_args` to create
   an object holding attributes and return it.

This class is deliberately simple, just an :class:`object` subclass with a
readable string representation. If you prefer to have dict-like view of the
attributes, you can use the standard Python idiom, :func:`vars`::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> args = parser.parse_args(['--foo', 'BAR'])
   >>> vars(args)
   {'foo': 'BAR'}

It may also be useful to have an :class:`ArgumentParser` assign attributes to an
already existing object, rather than a new :class:`Namespace` object.  This can
be achieved by specifying the ``namespace=`` keyword argument::

   >>> class C(object):
   ...     pass
   ...
   >>> c = C()
   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo')
   >>> parser.parse_args(args=['--foo', 'BAR'], namespace=c)
   >>> c.foo
   'BAR'


Other utilities
---------------

Sub-commands
^^^^^^^^^^^^

.. method:: ArgumentParser.add_subparsers([title], [description], [prog], \
                                          [parser_class], [action], \
                                          [option_string], [dest], [help], \
                                          [metavar])

   Many programs split up their functionality into a number of sub-commands,
   for example, the ``svn`` program can invoke sub-commands like ``svn
   checkout``, ``svn update``, and ``svn commit``.  Splitting up functionality
   this way can be a particularly good idea when a program performs several
   different functions which require different kinds of command-line arguments.
   :class:`ArgumentParser` supports the creation of such sub-commands with the
   :meth:`add_subparsers` method.  The :meth:`add_subparsers` method is normally
   called with no arguments and returns a special action object.  This object
   has a single method, :meth:`~ArgumentParser.add_parser`, which takes a
   command name and any :class:`ArgumentParser` constructor arguments, and
   returns an :class:`ArgumentParser` object that can be modified as usual.

   Description of parameters:

   * title - title for the sub-parser group in help output; by default
     "subcommands" if description is provided, otherwise uses title for
     positional arguments

   * description - description for the sub-parser group in help output, by
     default ``None``

   * prog - usage information that will be displayed with sub-command help,
     by default the name of the program and any positional arguments before the
     subparser argument

   * parser_class - class which will be used to create sub-parser instances, by
     default the class of the current parser (e.g. ArgumentParser)

   * action_ - the basic type of action to be taken when this argument is
     encountered at the command line

   * dest_ - name of the attribute under which sub-command name will be
     stored; by default ``None`` and no value is stored

   * help_ - help for sub-parser group in help output, by default ``None``

   * metavar_ - string presenting available sub-commands in help; by default it
     is ``None`` and presents sub-commands in form {cmd1, cmd2, ..}

   Some example usage::

     >>> # create the top-level parser
     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> parser.add_argument('--foo', action='store_true', help='foo help')
     >>> subparsers = parser.add_subparsers(help='sub-command help')
     >>>
     >>> # create the parser for the "a" command
     >>> parser_a = subparsers.add_parser('a', help='a help')
     >>> parser_a.add_argument('bar', type=int, help='bar help')
     >>>
     >>> # create the parser for the "b" command
     >>> parser_b = subparsers.add_parser('b', help='b help')
     >>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
     >>>
     >>> # parse some argument lists
     >>> parser.parse_args(['a', '12'])
     Namespace(bar=12, foo=False)
     >>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
     Namespace(baz='Z', foo=True)

   Note that the object returned by :meth:`parse_args` will only contain
   attributes for the main parser and the subparser that was selected by the
   command line (and not any other subparsers).  So in the example above, when
   the ``a`` command is specified, only the ``foo`` and ``bar`` attributes are
   present, and when the ``b`` command is specified, only the ``foo`` and
   ``baz`` attributes are present.

   Similarly, when a help message is requested from a subparser, only the help
   for that particular parser will be printed.  The help message will not
   include parent parser or sibling parser messages.  (A help message for each
   subparser command, however, can be given by supplying the ``help=`` argument
   to :meth:`add_parser` as above.)

   ::

     >>> parser.parse_args(['--help'])
     usage: PROG [-h] [--foo] {a,b} ...

     positional arguments:
       {a,b}   sub-command help
         a     a help
         b     b help

     optional arguments:
       -h, --help  show this help message and exit
       --foo   foo help

     >>> parser.parse_args(['a', '--help'])
     usage: PROG a [-h] bar

     positional arguments:
       bar     bar help

     optional arguments:
       -h, --help  show this help message and exit

     >>> parser.parse_args(['b', '--help'])
     usage: PROG b [-h] [--baz {X,Y,Z}]

     optional arguments:
       -h, --help     show this help message and exit
       --baz {X,Y,Z}  baz help

   The :meth:`add_subparsers` method also supports ``title`` and ``description``
   keyword arguments.  When either is present, the subparser's commands will
   appear in their own group in the help output.  For example::

     >>> parser = argparse.ArgumentParser()
     >>> subparsers = parser.add_subparsers(title='subcommands',
     ...                                    description='valid subcommands',
     ...                                    help='additional help')
     >>> subparsers.add_parser('foo')
     >>> subparsers.add_parser('bar')
     >>> parser.parse_args(['-h'])
     usage:  [-h] {foo,bar} ...

     optional arguments:
       -h, --help  show this help message and exit

     subcommands:
       valid subcommands

       {foo,bar}   additional help


   One particularly effective way of handling sub-commands is to combine the use
   of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
   that each subparser knows which Python function it should execute.  For
   example::

     >>> # sub-command functions
     >>> def foo(args):
     ...     print args.x * args.y
     ...
     >>> def bar(args):
     ...     print '((%s))' % args.z
     ...
     >>> # create the top-level parser
     >>> parser = argparse.ArgumentParser()
     >>> subparsers = parser.add_subparsers()
     >>>
     >>> # create the parser for the "foo" command
     >>> parser_foo = subparsers.add_parser('foo')
     >>> parser_foo.add_argument('-x', type=int, default=1)
     >>> parser_foo.add_argument('y', type=float)
     >>> parser_foo.set_defaults(func=foo)
     >>>
     >>> # create the parser for the "bar" command
     >>> parser_bar = subparsers.add_parser('bar')
     >>> parser_bar.add_argument('z')
     >>> parser_bar.set_defaults(func=bar)
     >>>
     >>> # parse the args and call whatever function was selected
     >>> args = parser.parse_args('foo 1 -x 2'.split())
     >>> args.func(args)
     2.0
     >>>
     >>> # parse the args and call whatever function was selected
     >>> args = parser.parse_args('bar XYZYX'.split())
     >>> args.func(args)
     ((XYZYX))

   This way, you can let :meth:`parse_args` do the job of calling the
   appropriate function after argument parsing is complete.  Associating
   functions with actions like this is typically the easiest way to handle the
   different actions for each of your subparsers.  However, if it is necessary
   to check the name of the subparser that was invoked, the ``dest`` keyword
   argument to the :meth:`add_subparsers` call will work::

     >>> parser = argparse.ArgumentParser()
     >>> subparsers = parser.add_subparsers(dest='subparser_name')
     >>> subparser1 = subparsers.add_parser('1')
     >>> subparser1.add_argument('-x')
     >>> subparser2 = subparsers.add_parser('2')
     >>> subparser2.add_argument('y')
     >>> parser.parse_args(['2', 'frobble'])
     Namespace(subparser_name='2', y='frobble')


FileType objects
^^^^^^^^^^^^^^^^

.. class:: FileType(mode='r', bufsize=None)

   The :class:`FileType` factory creates objects that can be passed to the type
   argument of :meth:`ArgumentParser.add_argument`.  Arguments that have
   :class:`FileType` objects as their type will open command-line arguments as files
   with the requested modes and buffer sizes::

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
      >>> parser.parse_args(['--output', 'out'])
      Namespace(output=<open file 'out', mode 'wb' at 0x...>)

   FileType objects understand the pseudo-argument ``'-'`` and automatically
   convert this into ``sys.stdin`` for readable :class:`FileType` objects and
   ``sys.stdout`` for writable :class:`FileType` objects::

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('infile', type=argparse.FileType('r'))
      >>> parser.parse_args(['-'])
      Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)


Argument groups
^^^^^^^^^^^^^^^

.. method:: ArgumentParser.add_argument_group(title=None, description=None)

   By default, :class:`ArgumentParser` groups command-line arguments into
   "positional arguments" and "optional arguments" when displaying help
   messages. When there is a better conceptual grouping of arguments than this
   default one, appropriate groups can be created using the
   :meth:`add_argument_group` method::

     >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
     >>> group = parser.add_argument_group('group')
     >>> group.add_argument('--foo', help='foo help')
     >>> group.add_argument('bar', help='bar help')
     >>> parser.print_help()
     usage: PROG [--foo FOO] bar

     group:
       bar    bar help
       --foo FOO  foo help

   The :meth:`add_argument_group` method returns an argument group object which
   has an :meth:`~ArgumentParser.add_argument` method just like a regular
   :class:`ArgumentParser`.  When an argument is added to the group, the parser
   treats it just like a normal argument, but displays the argument in a
   separate group for help messages.  The :meth:`add_argument_group` method
   accepts *title* and *description* arguments which can be used to
   customize this display::

     >>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
     >>> group1 = parser.add_argument_group('group1', 'group1 description')
     >>> group1.add_argument('foo', help='foo help')
     >>> group2 = parser.add_argument_group('group2', 'group2 description')
     >>> group2.add_argument('--bar', help='bar help')
     >>> parser.print_help()
     usage: PROG [--bar BAR] foo

     group1:
       group1 description

       foo    foo help

     group2:
       group2 description

       --bar BAR  bar help

   Note that any arguments not in your user-defined groups will end up back
   in the usual "positional arguments" and "optional arguments" sections.


Mutual exclusion
^^^^^^^^^^^^^^^^

.. method:: ArgumentParser.add_mutually_exclusive_group(required=False)

   Create a mutually exclusive group. :mod:`argparse` will make sure that only
   one of the arguments in the mutually exclusive group was present on the
   command line::

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> group = parser.add_mutually_exclusive_group()
     >>> group.add_argument('--foo', action='store_true')
     >>> group.add_argument('--bar', action='store_false')
     >>> parser.parse_args(['--foo'])
     Namespace(bar=True, foo=True)
     >>> parser.parse_args(['--bar'])
     Namespace(bar=False, foo=False)
     >>> parser.parse_args(['--foo', '--bar'])
     usage: PROG [-h] [--foo | --bar]
     PROG: error: argument --bar: not allowed with argument --foo

   The :meth:`add_mutually_exclusive_group` method also accepts a *required*
   argument, to indicate that at least one of the mutually exclusive arguments
   is required::

     >>> parser = argparse.ArgumentParser(prog='PROG')
     >>> group = parser.add_mutually_exclusive_group(required=True)
     >>> group.add_argument('--foo', action='store_true')
     >>> group.add_argument('--bar', action='store_false')
     >>> parser.parse_args([])
     usage: PROG [-h] (--foo | --bar)
     PROG: error: one of the arguments --foo --bar is required

   Note that currently mutually exclusive argument groups do not support the
   *title* and *description* arguments of
   :meth:`~ArgumentParser.add_argument_group`.


Parser defaults
^^^^^^^^^^^^^^^

.. method:: ArgumentParser.set_defaults(**kwargs)

   Most of the time, the attributes of the object returned by :meth:`parse_args`
   will be fully determined by inspecting the command-line arguments and the argument
   actions.  :meth:`set_defaults` allows some additional
   attributes that are determined without any inspection of the command line to
   be added::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('foo', type=int)
     >>> parser.set_defaults(bar=42, baz='badger')
     >>> parser.parse_args(['736'])
     Namespace(bar=42, baz='badger', foo=736)

   Note that parser-level defaults always override argument-level defaults::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default='bar')
     >>> parser.set_defaults(foo='spam')
     >>> parser.parse_args([])
     Namespace(foo='spam')

   Parser-level defaults can be particularly useful when working with multiple
   parsers.  See the :meth:`~ArgumentParser.add_subparsers` method for an
   example of this type.

.. method:: ArgumentParser.get_default(dest)

   Get the default value for a namespace attribute, as set by either
   :meth:`~ArgumentParser.add_argument` or by
   :meth:`~ArgumentParser.set_defaults`::

     >>> parser = argparse.ArgumentParser()
     >>> parser.add_argument('--foo', default='badger')
     >>> parser.get_default('foo')
     'badger'


Printing help
^^^^^^^^^^^^^

In most typical applications, :meth:`~ArgumentParser.parse_args` will take
care of formatting and printing any usage or error messages.  However, several
formatting methods are available:

.. method:: ArgumentParser.print_usage(file=None)

   Print a brief description of how the :class:`ArgumentParser` should be
   invoked on the command line.  If *file* is ``None``, :data:`sys.stdout` is
   assumed.

.. method:: ArgumentParser.print_help(file=None)

   Print a help message, including the program usage and information about the
   arguments registered with the :class:`ArgumentParser`.  If *file* is
   ``None``, :data:`sys.stdout` is assumed.

There are also variants of these methods that simply return a string instead of
printing it:

.. method:: ArgumentParser.format_usage()

   Return a string containing a brief description of how the
   :class:`ArgumentParser` should be invoked on the command line.

.. method:: ArgumentParser.format_help()

   Return a string containing a help message, including the program usage and
   information about the arguments registered with the :class:`ArgumentParser`.


Partial parsing
^^^^^^^^^^^^^^^

.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)

Sometimes a script may only parse a few of the command-line arguments, passing
the remaining arguments on to another script or program. In these cases, the
:meth:`~ArgumentParser.parse_known_args` method can be useful.  It works much like
:meth:`~ArgumentParser.parse_args` except that it does not produce an error when
extra arguments are present.  Instead, it returns a two item tuple containing
the populated namespace and the list of remaining argument strings.

::

   >>> parser = argparse.ArgumentParser()
   >>> parser.add_argument('--foo', action='store_true')
   >>> parser.add_argument('bar')
   >>> parser.parse_known_args(['--foo', '--badger', 'BAR', 'spam'])
   (Namespace(bar='BAR', foo=True), ['--badger', 'spam'])

.. warning::
   :ref:`Prefix matching <prefix-matching>` rules apply to
   :meth:`parse_known_args`. The parser may consume an option even if it's just
   a prefix of one of its known options, instead of leaving it in the remaining
   arguments list.


Customizing file parsing
^^^^^^^^^^^^^^^^^^^^^^^^

.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)

   Arguments that are read from a file (see the *fromfile_prefix_chars*
   keyword argument to the :class:`ArgumentParser` constructor) are read one
   argument per line. :meth:`convert_arg_line_to_args` can be overridden for
   fancier reading.

   This method takes a single argument *arg_line* which is a string read from
   the argument file.  It returns a list of arguments parsed from this string.
   The method is called once per line read from the argument file, in order.

   A useful override of this method is one that treats each space-separated word
   as an argument::

    def convert_arg_line_to_args(self, arg_line):
        return arg_line.split()


Exiting methods
^^^^^^^^^^^^^^^

.. method:: ArgumentParser.exit(status=0, message=None)

   This method terminates the program, exiting with the specified *status*
   and, if given, it prints a *message* before that.

.. method:: ArgumentParser.error(message)

   This method prints a usage message including the *message* to the
   standard error and terminates the program with a status code of 2.


.. _argparse-from-optparse:

Upgrading optparse code
-----------------------

Originally, the :mod:`argparse` module had attempted to maintain compatibility
with :mod:`optparse`.  However, :mod:`optparse` was difficult to extend
transparently, particularly with the changes required to support the new
``nargs=`` specifiers and better usage messages.  When most everything in
:mod:`optparse` had either been copy-pasted over or monkey-patched, it no
longer seemed practical to try to maintain the backwards compatibility.

The :mod:`argparse` module improves on the standard library :mod:`optparse`
module in a number of ways including:

* Handling positional arguments.
* Supporting sub-commands.
* Allowing alternative option prefixes like ``+`` and ``/``.
* Handling zero-or-more and one-or-more style arguments.
* Producing more informative usage messages.
* Providing a much simpler interface for custom ``type`` and ``action``.

A partial upgrade path from :mod:`optparse` to :mod:`argparse`:

* Replace all :meth:`optparse.OptionParser.add_option` calls with
  :meth:`ArgumentParser.add_argument` calls.

* Replace ``(options, args) = parser.parse_args()`` with ``args =
  parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
  calls for the positional arguments. Keep in mind that what was previously
  called ``options``, now in the :mod:`argparse` context is called ``args``.

* Replace :meth:`optparse.OptionParser.disable_interspersed_args`
  by setting ``nargs`` of a positional argument to `argparse.REMAINDER`_, or
  use :meth:`~ArgumentParser.parse_known_args` to collect unparsed argument
  strings in a separate list.

* Replace callback actions and the ``callback_*`` keyword arguments with
  ``type`` or ``action`` arguments.

* Replace string names for ``type`` keyword arguments with the corresponding
  type objects (e.g. int, float, complex, etc).

* Replace :class:`optparse.Values` with :class:`Namespace` and
  :exc:`optparse.OptionError` and :exc:`optparse.OptionValueError` with
  :exc:`ArgumentError`.

* Replace strings with implicit arguments such as ``%default`` or ``%prog`` with
  the standard Python syntax to use dictionaries to format strings, that is,
  ``%(default)s`` and ``%(prog)s``.

* Replace the OptionParser constructor ``version`` argument with a call to
  ``parser.add_argument('--version', action='version', version='<the version>')``.
PK	%�\�k))#html/_sources/library/array.rst.txtnu�[���
:mod:`array` --- Efficient arrays of numeric values
===================================================

.. module:: array
   :synopsis: Space efficient arrays of uniformly typed numeric values.


.. index:: single: arrays

This module defines an object type which can compactly represent an array of
basic values: characters, integers, floating point numbers.  Arrays are sequence
types and behave very much like lists, except that the type of objects stored in
them is constrained.  The type is specified at object creation time by using a
:dfn:`type code`, which is a single character.  The following type codes are
defined:

+-----------+----------------+-------------------+-----------------------+
| Type code | C Type         | Python Type       | Minimum size in bytes |
+===========+================+===================+=======================+
| ``'c'``   | char           | character         | 1                     |
+-----------+----------------+-------------------+-----------------------+
| ``'b'``   | signed char    | int               | 1                     |
+-----------+----------------+-------------------+-----------------------+
| ``'B'``   | unsigned char  | int               | 1                     |
+-----------+----------------+-------------------+-----------------------+
| ``'u'``   | Py_UNICODE     | Unicode character | 2 (see note)          |
+-----------+----------------+-------------------+-----------------------+
| ``'h'``   | signed short   | int               | 2                     |
+-----------+----------------+-------------------+-----------------------+
| ``'H'``   | unsigned short | int               | 2                     |
+-----------+----------------+-------------------+-----------------------+
| ``'i'``   | signed int     | int               | 2                     |
+-----------+----------------+-------------------+-----------------------+
| ``'I'``   | unsigned int   | long              | 2                     |
+-----------+----------------+-------------------+-----------------------+
| ``'l'``   | signed long    | int               | 4                     |
+-----------+----------------+-------------------+-----------------------+
| ``'L'``   | unsigned long  | long              | 4                     |
+-----------+----------------+-------------------+-----------------------+
| ``'f'``   | float          | float             | 4                     |
+-----------+----------------+-------------------+-----------------------+
| ``'d'``   | double         | float             | 8                     |
+-----------+----------------+-------------------+-----------------------+

.. note::

   The ``'u'`` typecode corresponds to Python's unicode character.  On narrow
   Unicode builds this is 2-bytes, on wide builds this is 4-bytes.

The actual representation of values is determined by the machine architecture
(strictly speaking, by the C implementation).  The actual size can be accessed
through the :attr:`itemsize` attribute.  The values stored  for ``'L'`` and
``'I'`` items will be represented as Python long integers when retrieved,
because Python's plain integer type cannot represent the full range of C's
unsigned (long) integers.

The module defines the following type:


.. class:: array(typecode[, initializer])

   A new array whose items are restricted by *typecode*, and initialized
   from the optional *initializer* value, which must be a list, string, or iterable
   over elements of the appropriate type.

   .. versionchanged:: 2.4
      Formerly, only lists or strings were accepted.

   If given a list or string, the initializer is passed to the new array's
   :meth:`fromlist`, :meth:`fromstring`, or :meth:`fromunicode` method (see below)
   to add initial items to the array.  Otherwise, the iterable initializer is
   passed to the :meth:`extend` method.


.. data:: ArrayType

   Obsolete alias for :class:`~array.array`.

Array objects support the ordinary sequence operations of indexing, slicing,
concatenation, and multiplication.  When using slice assignment, the assigned
value must be an array object with the same type code; in all other cases,
:exc:`TypeError` is raised. Array objects also implement the buffer interface,
and may be used wherever buffer objects are supported.

The following data items and methods are also supported:

.. attribute:: array.typecode

   The typecode character used to create the array.


.. attribute:: array.itemsize

   The length in bytes of one array item in the internal representation.


.. method:: array.append(x)

   Append a new item with value *x* to the end of the array.


.. method:: array.buffer_info()

   Return a tuple ``(address, length)`` giving the current memory address and the
   length in elements of the buffer used to hold array's contents.  The size of the
   memory buffer in bytes can be computed as ``array.buffer_info()[1] *
   array.itemsize``.  This is occasionally useful when working with low-level (and
   inherently unsafe) I/O interfaces that require memory addresses, such as certain
   :c:func:`ioctl` operations.  The returned numbers are valid as long as the array
   exists and no length-changing operations are applied to it.

   .. note::

      When using array objects from code written in C or C++ (the only way to
      effectively make use of this information), it makes more sense to use the buffer
      interface supported by array objects.  This method is maintained for backward
      compatibility and should be avoided in new code.  The buffer interface is
      documented in :ref:`bufferobjects`.


.. method:: array.byteswap()

   "Byteswap" all items of the array.  This is only supported for values which are
   1, 2, 4, or 8 bytes in size; for other types of values, :exc:`RuntimeError` is
   raised.  It is useful when reading data from a file written on a machine with a
   different byte order.


.. method:: array.count(x)

   Return the number of occurrences of *x* in the array.


.. method:: array.extend(iterable)

   Append items from *iterable* to the end of the array.  If *iterable* is another
   array, it must have *exactly* the same type code; if not, :exc:`TypeError` will
   be raised.  If *iterable* is not an array, it must be iterable and its elements
   must be the right type to be appended to the array.

   .. versionchanged:: 2.4
      Formerly, the argument could only be another array.


.. method:: array.fromfile(f, n)

   Read *n* items (as machine values) from the file object *f* and append them to
   the end of the array.  If less than *n* items are available, :exc:`EOFError` is
   raised, but the items that were available are still inserted into the array.
   *f* must be a real built-in file object; something else with a :meth:`read`
   method won't do.


.. method:: array.fromlist(list)

   Append items from the list.  This is equivalent to ``for x in list:
   a.append(x)`` except that if there is a type error, the array is unchanged.


.. method:: array.fromstring(s)

   Appends items from the string, interpreting the string as an array of machine
   values (as if it had been read from a file using the :meth:`fromfile` method).


.. method:: array.fromunicode(s)

   Extends this array with data from the given unicode string.  The array must
   be a type ``'u'`` array; otherwise a :exc:`ValueError` is raised.  Use
   ``array.fromstring(unicodestring.encode(enc))`` to append Unicode data to an
   array of some other type.


.. method:: array.index(x)

   Return the smallest *i* such that *i* is the index of the first occurrence of
   *x* in the array.


.. method:: array.insert(i, x)

   Insert a new item with value *x* in the array before position *i*. Negative
   values are treated as being relative to the end of the array.


.. method:: array.pop([i])

   Removes the item with the index *i* from the array and returns it. The optional
   argument defaults to ``-1``, so that by default the last item is removed and
   returned.


.. method:: array.read(f, n)

   .. deprecated:: 1.5.1
      Use the :meth:`fromfile` method.

   Read *n* items (as machine values) from the file object *f* and append them to
   the end of the array.  If less than *n* items are available, :exc:`EOFError` is
   raised, but the items that were available are still inserted into the array.
   *f* must be a real built-in file object; something else with a :meth:`read`
   method won't do.


.. method:: array.remove(x)

   Remove the first occurrence of *x* from the array.


.. method:: array.reverse()

   Reverse the order of the items in the array.


.. method:: array.tofile(f)

   Write all items (as machine values) to the file object *f*.


.. method:: array.tolist()

   Convert the array to an ordinary list with the same items.


.. method:: array.tostring()

   Convert the array to an array of machine values and return the string
   representation (the same sequence of bytes that would be written to a file by
   the :meth:`tofile` method.)


.. method:: array.tounicode()

   Convert the array to a unicode string.  The array must be a type ``'u'`` array;
   otherwise a :exc:`ValueError` is raised. Use ``array.tostring().decode(enc)`` to
   obtain a unicode string from an array of some other type.


.. method:: array.write(f)

   .. deprecated:: 1.5.1
      Use the :meth:`tofile` method.

   Write all items (as machine values) to the file object *f*.

When an array object is printed or converted to a string, it is represented as
``array(typecode, initializer)``.  The *initializer* is omitted if the array is
empty, otherwise it is a string if the *typecode* is ``'c'``, otherwise it is a
list of numbers.  The string is guaranteed to be able to be converted back to an
array with the same type and value using :func:`eval`, so long as the
:class:`~array.array` class has been imported using ``from array import array``.
Examples::

   array('l')
   array('c', 'hello world')
   array('u', u'hello \u2641')
   array('l', [1, 2, 3, 4, 5])
   array('d', [1.0, 2.0, 3.14])


.. seealso::

   Module :mod:`struct`
      Packing and unpacking of heterogeneous binary data.

   Module :mod:`xdrlib`
      Packing and unpacking of External Data Representation (XDR) data as used in some
      remote procedure call systems.

   `The Numerical Python Documentation <https://docs.scipy.org/doc/>`_
      The Numeric Python extension (NumPy) defines another array type; see
      http://www.numpy.org/ for further information about Numerical Python.

PK	%�\?��''!html/_sources/library/ast.rst.txtnu�[���:mod:`ast` --- Abstract Syntax Trees
====================================

.. module:: ast
   :synopsis: Abstract Syntax Tree classes and manipulation.

.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>
.. sectionauthor:: Georg Brandl <georg@python.org>

.. versionadded:: 2.5
   The low-level ``_ast`` module containing only the node classes.

.. versionadded:: 2.6
   The high-level ``ast`` module containing all helpers.

**Source code:** :source:`Lib/ast.py`

--------------

The :mod:`ast` module helps Python applications to process trees of the Python
abstract syntax grammar.  The abstract syntax itself might change with each
Python release; this module helps to find out programmatically what the current
grammar looks like.

An abstract syntax tree can be generated by passing :data:`ast.PyCF_ONLY_AST` as
a flag to the :func:`compile` built-in function, or using the :func:`parse`
helper provided in this module.  The result will be a tree of objects whose
classes all inherit from :class:`ast.AST`.  An abstract syntax tree can be
compiled into a Python code object using the built-in :func:`compile` function.


Node classes
------------

.. class:: AST

   This is the base of all AST node classes.  The actual node classes are
   derived from the :file:`Parser/Python.asdl` file, which is reproduced
   :ref:`below <abstract-grammar>`.  They are defined in the :mod:`_ast` C
   module and re-exported in :mod:`ast`.

   There is one class defined for each left-hand side symbol in the abstract
   grammar (for example, :class:`ast.stmt` or :class:`ast.expr`).  In addition,
   there is one class defined for each constructor on the right-hand side; these
   classes inherit from the classes for the left-hand side trees.  For example,
   :class:`ast.BinOp` inherits from :class:`ast.expr`.  For production rules
   with alternatives (aka "sums"), the left-hand side class is abstract: only
   instances of specific constructor nodes are ever created.

   .. attribute:: _fields

      Each concrete class has an attribute :attr:`_fields` which gives the names
      of all child nodes.

      Each instance of a concrete class has one attribute for each child node,
      of the type as defined in the grammar.  For example, :class:`ast.BinOp`
      instances have an attribute :attr:`left` of type :class:`ast.expr`.

      If these attributes are marked as optional in the grammar (using a
      question mark), the value might be ``None``.  If the attributes can have
      zero-or-more values (marked with an asterisk), the values are represented
      as Python lists.  All possible attributes must be present and have valid
      values when compiling an AST with :func:`compile`.

   .. attribute:: lineno
                  col_offset

      Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
      :attr:`lineno` and :attr:`col_offset` attributes.  The :attr:`lineno` is
      the line number of source text (1-indexed so the first line is line 1) and
      the :attr:`col_offset` is the UTF-8 byte offset of the first token that
      generated the node.  The UTF-8 offset is recorded because the parser uses
      UTF-8 internally.

   The constructor of a class :class:`ast.T` parses its arguments as follows:

   * If there are positional arguments, there must be as many as there are items
     in :attr:`T._fields`; they will be assigned as attributes of these names.
   * If there are keyword arguments, they will set the attributes of the same
     names to the given values.

   For example, to create and populate an :class:`ast.UnaryOp` node, you could
   use ::

      node = ast.UnaryOp()
      node.op = ast.USub()
      node.operand = ast.Num()
      node.operand.n = 5
      node.operand.lineno = 0
      node.operand.col_offset = 0
      node.lineno = 0
      node.col_offset = 0

   or the more compact ::

      node = ast.UnaryOp(ast.USub(), ast.Num(5, lineno=0, col_offset=0),
                         lineno=0, col_offset=0)

   .. versionadded:: 2.6
      The constructor as explained above was added.  In Python 2.5 nodes had
      to be created by calling the class constructor without arguments and
      setting the attributes afterwards.


.. _abstract-grammar:

Abstract Grammar
----------------

The module defines a string constant ``__version__`` which is the decimal
Subversion revision number of the file shown below.

The abstract grammar is currently defined as follows:

.. literalinclude:: ../../Parser/Python.asdl
   :language: none


:mod:`ast` Helpers
------------------

.. versionadded:: 2.6

Apart from the node classes, :mod:`ast` module defines these utility functions
and classes for traversing abstract syntax trees:

.. function:: parse(source, filename='<unknown>', mode='exec')

   Parse the source into an AST node.  Equivalent to ``compile(source,
   filename, mode, ast.PyCF_ONLY_AST)``.


.. function:: literal_eval(node_or_string)

   Safely evaluate an expression node or a Unicode or *Latin-1* encoded string
   containing a Python literal or container display.  The string or node
   provided may only consist of the following Python literal structures:
   strings, numbers, tuples, lists, dicts, booleans, and ``None``.

   This can be used for safely evaluating strings containing Python values from
   untrusted sources without the need to parse the values oneself.  It is not
   capable of evaluating arbitrarily complex expressions, for example involving
   operators or indexing.


.. function:: get_docstring(node, clean=True)

   Return the docstring of the given *node* (which must be a
   :class:`FunctionDef`, :class:`ClassDef` or :class:`Module` node), or ``None``
   if it has no docstring.  If *clean* is true, clean up the docstring's
   indentation with :func:`inspect.cleandoc`.


.. function:: fix_missing_locations(node)

   When you compile a node tree with :func:`compile`, the compiler expects
   :attr:`lineno` and :attr:`col_offset` attributes for every node that supports
   them.  This is rather tedious to fill in for generated nodes, so this helper
   adds these attributes recursively where not already set, by setting them to
   the values of the parent node.  It works recursively starting at *node*.


.. function:: increment_lineno(node, n=1)

   Increment the line number of each node in the tree starting at *node* by *n*.
   This is useful to "move code" to a different location in a file.


.. function:: copy_location(new_node, old_node)

   Copy source location (:attr:`lineno` and :attr:`col_offset`) from *old_node*
   to *new_node* if possible, and return *new_node*.


.. function:: iter_fields(node)

   Yield a tuple of ``(fieldname, value)`` for each field in ``node._fields``
   that is present on *node*.


.. function:: iter_child_nodes(node)

   Yield all direct child nodes of *node*, that is, all fields that are nodes
   and all items of fields that are lists of nodes.


.. function:: walk(node)

   Recursively yield all descendant nodes in the tree starting at *node*
   (including *node* itself), in no specified order.  This is useful if you only
   want to modify nodes in place and don't care about the context.


.. class:: NodeVisitor()

   A node visitor base class that walks the abstract syntax tree and calls a
   visitor function for every node found.  This function may return a value
   which is forwarded by the :meth:`visit` method.

   This class is meant to be subclassed, with the subclass adding visitor
   methods.

   .. method:: visit(node)

      Visit a node.  The default implementation calls the method called
      :samp:`self.visit_{classname}` where *classname* is the name of the node
      class, or :meth:`generic_visit` if that method doesn't exist.

   .. method:: generic_visit(node)

      This visitor calls :meth:`visit` on all children of the node.

      Note that child nodes of nodes that have a custom visitor method won't be
      visited unless the visitor calls :meth:`generic_visit` or visits them
      itself.

   Don't use the :class:`NodeVisitor` if you want to apply changes to nodes
   during traversal.  For this a special visitor exists
   (:class:`NodeTransformer`) that allows modifications.


.. class:: NodeTransformer()

   A :class:`NodeVisitor` subclass that walks the abstract syntax tree and
   allows modification of nodes.

   The :class:`NodeTransformer` will walk the AST and use the return value of
   the visitor methods to replace or remove the old node.  If the return value
   of the visitor method is ``None``, the node will be removed from its
   location, otherwise it is replaced with the return value.  The return value
   may be the original node in which case no replacement takes place.

   Here is an example transformer that rewrites all occurrences of name lookups
   (``foo``) to ``data['foo']``::

      class RewriteName(NodeTransformer):

          def visit_Name(self, node):
              return copy_location(Subscript(
                  value=Name(id='data', ctx=Load()),
                  slice=Index(value=Str(s=node.id)),
                  ctx=node.ctx
              ), node)

   Keep in mind that if the node you're operating on has child nodes you must
   either transform the child nodes yourself or call the :meth:`generic_visit`
   method for the node first.

   For nodes that were part of a collection of statements (that applies to all
   statement nodes), the visitor may also return a list of nodes rather than
   just a single node.

   Usually you use the transformer like this::

      node = YourTransformer().visit(node)


.. function:: dump(node, annotate_fields=True, include_attributes=False)

   Return a formatted dump of the tree in *node*.  This is mainly useful for
   debugging purposes.  The returned string will show the names and the values
   for fields.  This makes the code impossible to evaluate, so if evaluation is
   wanted *annotate_fields* must be set to ``False``.  Attributes such as line
   numbers and column offsets are not dumped by default.  If this is wanted,
   *include_attributes* can be set to ``True``.
PK	%�\S�`h�#�#&html/_sources/library/asynchat.rst.txtnu�[���:mod:`asynchat` --- Asynchronous socket command/response handler
================================================================

.. module:: asynchat
   :synopsis: Support for asynchronous command/response protocols.
.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>

**Source code:** :source:`Lib/asynchat.py`

--------------

This module builds on the :mod:`asyncore` infrastructure, simplifying
asynchronous clients and servers and making it easier to handle protocols
whose elements are terminated by arbitrary strings, or are of variable length.
:mod:`asynchat` defines the abstract class :class:`async_chat` that you
subclass, providing implementations of the :meth:`collect_incoming_data` and
:meth:`found_terminator` methods. It uses the same asynchronous loop as
:mod:`asyncore`, and the two types of channel, :class:`asyncore.dispatcher`
and :class:`asynchat.async_chat`, can freely be mixed in the channel map.
Typically an :class:`asyncore.dispatcher` server channel generates new
:class:`asynchat.async_chat` channel objects as it receives incoming
connection requests.


.. class:: async_chat()

   This class is an abstract subclass of :class:`asyncore.dispatcher`. To make
   practical use of the code you must subclass :class:`async_chat`, providing
   meaningful :meth:`collect_incoming_data` and :meth:`found_terminator`
   methods.
   The :class:`asyncore.dispatcher` methods can be used, although not all make
   sense in a message/response context.

   Like :class:`asyncore.dispatcher`, :class:`async_chat` defines a set of
   events that are generated by an analysis of socket conditions after a
   :c:func:`select` call. Once the polling loop has been started the
   :class:`async_chat` object's methods are called by the event-processing
   framework with no action on the part of the programmer.

   Two class attributes can be modified, to improve performance, or possibly
   even to conserve memory.


   .. data:: ac_in_buffer_size

      The asynchronous input buffer size (default ``4096``).


   .. data:: ac_out_buffer_size

      The asynchronous output buffer size (default ``4096``).

   Unlike :class:`asyncore.dispatcher`, :class:`async_chat` allows you to
   define a first-in-first-out queue (fifo) of *producers*. A producer need
   have only one method, :meth:`more`, which should return data to be
   transmitted on the channel.
   The producer indicates exhaustion (*i.e.* that it contains no more data) by
   having its :meth:`more` method return the empty string. At this point the
   :class:`async_chat` object removes the producer from the fifo and starts
   using the next producer, if any. When the producer fifo is empty the
   :meth:`handle_write` method does nothing. You use the channel object's
   :meth:`set_terminator` method to describe how to recognize the end of, or
   an important breakpoint in, an incoming transmission from the remote
   endpoint.

   To build a functioning :class:`async_chat` subclass your  input methods
   :meth:`collect_incoming_data` and :meth:`found_terminator` must handle the
   data that the channel receives asynchronously. The methods are described
   below.


.. method:: async_chat.close_when_done()

   Pushes a ``None`` on to the producer fifo. When this producer is popped off
   the fifo it causes the channel to be closed.


.. method:: async_chat.collect_incoming_data(data)

   Called with *data* holding an arbitrary amount of received data.  The
   default method, which must be overridden, raises a
   :exc:`NotImplementedError` exception.


.. method:: async_chat.discard_buffers()

   In emergencies this method will discard any data held in the input and/or
   output buffers and the producer fifo.


.. method:: async_chat.found_terminator()

   Called when the incoming data stream  matches the termination condition set
   by :meth:`set_terminator`. The default method, which must be overridden,
   raises a :exc:`NotImplementedError` exception. The buffered input data
   should be available via an instance attribute.


.. method:: async_chat.get_terminator()

   Returns the current terminator for the channel.


.. method:: async_chat.push(data)

   Pushes data on to the channel's fifo to ensure its transmission.
   This is all you need to do to have the channel write the data out to the
   network, although it is possible to use your own producers in more complex
   schemes to implement encryption and chunking, for example.


.. method:: async_chat.push_with_producer(producer)

   Takes a producer object and adds it to the producer fifo associated with
   the channel.  When all currently-pushed producers have been exhausted the
   channel will consume this producer's data by calling its :meth:`more`
   method and send the data to the remote endpoint.


.. method:: async_chat.set_terminator(term)

   Sets the terminating condition to be recognized on the channel.  ``term``
   may be any of three types of value, corresponding to three different ways
   to handle incoming protocol data.

   +-----------+---------------------------------------------+
   | term      | Description                                 |
   +===========+=============================================+
   | *string*  | Will call :meth:`found_terminator` when the |
   |           | string is found in the input stream         |
   +-----------+---------------------------------------------+
   | *integer* | Will call :meth:`found_terminator` when the |
   |           | indicated number of characters have been    |
   |           | received                                    |
   +-----------+---------------------------------------------+
   | ``None``  | The channel continues to collect data       |
   |           | forever                                     |
   +-----------+---------------------------------------------+

   Note that any data following the terminator will be available for reading
   by the channel after :meth:`found_terminator` is called.


asynchat - Auxiliary Classes
------------------------------------------

.. class:: fifo([list=None])

   A :class:`fifo` holding data which has been pushed by the application but
   not yet popped for writing to the channel.  A :class:`fifo` is a list used
   to hold data and/or producers until they are required.  If the *list*
   argument is provided then it should contain producers or data items to be
   written to the channel.


   .. method:: is_empty()

      Returns ``True`` if and only if the fifo is empty.


   .. method:: first()

      Returns the least-recently :meth:`push`\ ed item from the fifo.


   .. method:: push(data)

      Adds the given data (which may be a string or a producer object) to the
      producer fifo.


   .. method:: pop()

      If the fifo is not empty, returns ``True, first()``, deleting the popped
      item.  Returns ``False, None`` for an empty fifo.


.. _asynchat-example:

asynchat Example
----------------

The following partial example shows how HTTP requests can be read with
:class:`async_chat`.  A web server might create an
:class:`http_request_handler` object for each incoming client connection.
Notice that initially the channel terminator is set to match the blank line at
the end of the HTTP headers, and a flag indicates that the headers are being
read.

Once the headers have been read, if the request is of type POST (indicating
that further data are present in the input stream) then the
``Content-Length:`` header is used to set a numeric terminator to read the
right amount of data from the channel.

The :meth:`handle_request` method is called once all relevant input has been
marshalled, after setting the channel terminator to ``None`` to ensure that
any extraneous data sent by the web client are ignored. ::

   class http_request_handler(asynchat.async_chat):

       def __init__(self, sock, addr, sessions, log):
           asynchat.async_chat.__init__(self, sock=sock)
           self.addr = addr
           self.sessions = sessions
           self.ibuffer = []
           self.obuffer = ""
           self.set_terminator("\r\n\r\n")
           self.reading_headers = True
           self.handling = False
           self.cgi_data = None
           self.log = log

       def collect_incoming_data(self, data):
           """Buffer the data"""
           self.ibuffer.append(data)

       def found_terminator(self):
           if self.reading_headers:
               self.reading_headers = False
               self.parse_headers("".join(self.ibuffer))
               self.ibuffer = []
               if self.op.upper() == "POST":
                   clen = self.headers.getheader("content-length")
                   self.set_terminator(int(clen))
               else:
                   self.handling = True
                   self.set_terminator(None)
                   self.handle_request()
           elif not self.handling:
               self.set_terminator(None)  # browsers sometimes over-send
               self.cgi_data = parse(self.headers, "".join(self.ibuffer))
               self.handling = True
               self.ibuffer = []
               self.handle_request()
PK	%�\�j{�2�2&html/_sources/library/asyncore.rst.txtnu�[���:mod:`asyncore` --- Asynchronous socket handler
===============================================

.. module:: asyncore
   :synopsis: A base class for developing asynchronous socket handling
              services.
.. moduleauthor:: Sam Rushing <rushing@nightmare.com>
.. sectionauthor:: Christopher Petrilli <petrilli@amber.org>
.. sectionauthor:: Steve Holden <sholden@holdenweb.com>
.. heavily adapted from original documentation by Sam Rushing

**Source code:** :source:`Lib/asyncore.py`

--------------

This module provides the basic infrastructure for writing asynchronous  socket
service clients and servers.

There are only two ways to have a program on a single processor do  "more than
one thing at a time." Multi-threaded programming is the  simplest and most
popular way to do it, but there is another very different technique, that lets
you have nearly all the advantages of  multi-threading, without actually using
multiple threads.  It's really  only practical if your program is largely I/O
bound.  If your program is processor bound, then pre-emptive scheduled threads
are probably what you really need.  Network servers are rarely processor
bound, however.

If your operating system supports the :c:func:`select` system call in its I/O
library (and nearly all do), then you can use it to juggle multiple
communication channels at once; doing other work while your I/O is taking
place in the "background."  Although this strategy can seem strange and
complex, especially at first, it is in many ways easier to understand and
control than multi-threaded programming.  The :mod:`asyncore` module solves
many of the difficult problems for you, making the task of building
sophisticated high-performance network servers and clients a snap.  For
"conversational" applications and protocols the companion :mod:`asynchat`
module is invaluable.

The basic idea behind both modules is to create one or more network
*channels*, instances of class :class:`asyncore.dispatcher` and
:class:`asynchat.async_chat`.  Creating the channels adds them to a global
map, used by the :func:`loop` function if you do not provide it with your own
*map*.

Once the initial channel(s) is(are) created, calling the :func:`loop` function
activates channel service, which continues until the last channel (including
any that have been added to the map during asynchronous service) is closed.


.. function:: loop([timeout[, use_poll[, map[,count]]]])

   Enter a polling loop that terminates after count passes or all open
   channels have been closed.  All arguments are optional.  The *count*
   parameter defaults to ``None``, resulting in the loop terminating only when all
   channels have been closed.  The *timeout* argument sets the timeout
   parameter for the appropriate :func:`~select.select` or :func:`~select.poll`
   call, measured in seconds; the default is 30 seconds.  The *use_poll*
   parameter, if true, indicates that :func:`~select.poll` should be used in
   preference to :func:`~select.select` (the default is ``False``).

   The *map* parameter is a dictionary whose items are the channels to watch.
   As channels are closed they are deleted from their map.  If *map* is
   omitted, a global map is used. Channels (instances of
   :class:`asyncore.dispatcher`, :class:`asynchat.async_chat` and subclasses
   thereof) can freely be mixed in the map.


.. class:: dispatcher()

   The :class:`dispatcher` class is a thin wrapper around a low-level socket
   object. To make it more useful, it has a few methods for event-handling
   which are called from the asynchronous loop.   Otherwise, it can be treated
   as a normal non-blocking socket object.

   The firing of low-level events at certain times or in certain connection
   states tells the asynchronous loop that certain higher-level events have
   taken place.  For example, if we have asked for a socket to connect to
   another host, we know that the connection has been made when the socket
   becomes writable for the first time (at this point you know that you may
   write to it with the expectation of success).  The implied higher-level
   events are:

   +----------------------+----------------------------------------+
   | Event                | Description                            |
   +======================+========================================+
   | ``handle_connect()`` | Implied by the first read or write     |
   |                      | event                                  |
   +----------------------+----------------------------------------+
   | ``handle_close()``   | Implied by a read event with no data   |
   |                      | available                              |
   +----------------------+----------------------------------------+
   | ``handle_accept()``  | Implied by a read event on a listening |
   |                      | socket                                 |
   +----------------------+----------------------------------------+

   During asynchronous processing, each mapped channel's :meth:`readable` and
   :meth:`writable` methods are used to determine whether the channel's socket
   should be added to the list of channels :c:func:`select`\ ed or
   :c:func:`poll`\ ed for read and write events.

   Thus, the set of channel events is larger than the basic socket events.  The
   full set of methods that can be overridden in your subclass follows:


   .. method:: handle_read()

      Called when the asynchronous loop detects that a :meth:`read` call on the
      channel's socket will succeed.


   .. method:: handle_write()

      Called when the asynchronous loop detects that a writable socket can be
      written.  Often this method will implement the necessary buffering for
      performance.  For example::

         def handle_write(self):
             sent = self.send(self.buffer)
             self.buffer = self.buffer[sent:]


   .. method:: handle_expt()

      Called when there is out of band (OOB) data for a socket connection.  This
      will almost never happen, as OOB is tenuously supported and rarely used.


   .. method:: handle_connect()

      Called when the active opener's socket actually makes a connection.  Might
      send a "welcome" banner, or initiate a protocol negotiation with the
      remote endpoint, for example.


   .. method:: handle_close()

      Called when the socket is closed.


   .. method:: handle_error()

      Called when an exception is raised and not otherwise handled.  The default
      version prints a condensed traceback.


   .. method:: handle_accept()

      Called on listening channels (passive openers) when a connection can be
      established with a new remote endpoint that has issued a :meth:`connect`
      call for the local endpoint.


   .. method:: readable()

      Called each time around the asynchronous loop to determine whether a
      channel's socket should be added to the list on which read events can
      occur.  The default method simply returns ``True``, indicating that by
      default, all channels will be interested in read events.


   .. method:: writable()

      Called each time around the asynchronous loop to determine whether a
      channel's socket should be added to the list on which write events can
      occur.  The default method simply returns ``True``, indicating that by
      default, all channels will be interested in write events.


   In addition, each channel delegates or extends many of the socket methods.
   Most of these are nearly identical to their socket partners.


   .. method:: create_socket(family, type)

      This is identical to the creation of a normal socket, and will use the
      same options for creation.  Refer to the :mod:`socket` documentation for
      information on creating sockets.


   .. method:: connect(address)

      As with the normal socket object, *address* is a tuple with the first
      element the host to connect to, and the second the port number.


   .. method:: send(data)

      Send *data* to the remote end-point of the socket.


   .. method:: recv(buffer_size)

      Read at most *buffer_size* bytes from the socket's remote end-point.  An
      empty string implies that the channel has been closed from the other end.

      Note that :meth:`recv` may raise :exc:`socket.error` with
      :data:`~errno.EAGAIN` or :data:`~errno.EWOULDBLOCK`, even though
      :func:`select.select` or :func:`select.poll` has reported the socket
      ready for reading.


   .. method:: listen(backlog)

      Listen for connections made to the socket.  The *backlog* argument
      specifies the maximum number of queued connections and should be at least
      1; the maximum value is system-dependent (usually 5).


   .. method:: bind(address)

      Bind the socket to *address*.  The socket must not already be bound.  (The
      format of *address* depends on the address family --- refer to the
      :mod:`socket` documentation for more information.)  To mark
      the socket as re-usable (setting the :const:`SO_REUSEADDR` option), call
      the :class:`dispatcher` object's :meth:`set_reuse_addr` method.


   .. method:: accept()

      Accept a connection.  The socket must be bound to an address and listening
      for connections.  The return value can be either ``None`` or a pair
      ``(conn, address)`` where *conn* is a *new* socket object usable to send
      and receive data on the connection, and *address* is the address bound to
      the socket on the other end of the connection.
      When ``None`` is returned it means the connection didn't take place, in
      which case the server should just ignore this event and keep listening
      for further incoming connections.


   .. method:: close()

      Close the socket.  All future operations on the socket object will fail.
      The remote end-point will receive no more data (after queued data is
      flushed).  Sockets are automatically closed when they are
      garbage-collected.

.. class:: dispatcher_with_send()

   A :class:`dispatcher` subclass which adds simple buffered output capability,
   useful for simple clients. For more sophisticated usage use
   :class:`asynchat.async_chat`.

.. class:: file_dispatcher()

   A file_dispatcher takes a file descriptor or file object along with an
   optional map argument and wraps it for use with the :c:func:`poll` or
   :c:func:`loop` functions.  If provided a file object or anything with a
   :c:func:`fileno` method, that method will be called and passed to the
   :class:`file_wrapper` constructor.  Availability: UNIX.

.. class:: file_wrapper()

   A file_wrapper takes an integer file descriptor and calls :func:`os.dup` to
   duplicate the handle so that the original handle may be closed independently
   of the file_wrapper.  This class implements sufficient methods to emulate a
   socket for use by the :class:`file_dispatcher` class.  Availability: UNIX.


.. _asyncore-example-1:

asyncore Example basic HTTP client
----------------------------------

Here is a very basic HTTP client that uses the :class:`dispatcher` class to
implement its socket handling::

   import asyncore, socket

   class HTTPClient(asyncore.dispatcher):

       def __init__(self, host, path):
           asyncore.dispatcher.__init__(self)
           self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
           self.connect( (host, 80) )
           self.buffer = 'GET %s HTTP/1.0\r\n\r\n' % path

       def handle_connect(self):
           pass

       def handle_close(self):
           self.close()

       def handle_read(self):
           print self.recv(8192)

       def writable(self):
           return (len(self.buffer) > 0)

       def handle_write(self):
           sent = self.send(self.buffer)
           self.buffer = self.buffer[sent:]


   client = HTTPClient('www.python.org', '/')
   asyncore.loop()

.. _asyncore-example-2:

asyncore Example basic echo server
----------------------------------

Here is a basic echo server that uses the :class:`dispatcher` class to accept
connections and dispatches the incoming connections to a handler::

    import asyncore
    import socket

    class EchoHandler(asyncore.dispatcher_with_send):

        def handle_read(self):
            data = self.recv(8192)
            if data:
                self.send(data)

    class EchoServer(asyncore.dispatcher):

        def __init__(self, host, port):
            asyncore.dispatcher.__init__(self)
            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
            self.set_reuse_addr()
            self.bind((host, port))
            self.listen(5)

        def handle_accept(self):
            pair = self.accept()
            if pair is not None:
                sock, addr = pair
                print 'Incoming connection from %s' % repr(addr)
                handler = EchoHandler(sock)

    server = EchoServer('localhost', 8080)
    asyncore.loop()
PK	%�\|��FF$html/_sources/library/atexit.rst.txtnu�[���:mod:`atexit` --- Exit handlers
===============================

.. module:: atexit
   :synopsis: Register and execute cleanup functions.
.. moduleauthor:: Skip Montanaro <skip@pobox.com>
.. sectionauthor:: Skip Montanaro <skip@pobox.com>


.. versionadded:: 2.0

**Source code:** :source:`Lib/atexit.py`

--------------

The :mod:`atexit` module defines a single function to register cleanup
functions.  Functions thus registered are automatically executed upon normal
interpreter termination.  :mod:`atexit` runs these functions in the *reverse*
order in which they were registered; if you register ``A``, ``B``, and ``C``,
at interpreter termination time they will be run in the order ``C``, ``B``,
``A``.

**Note:** The functions registered via this module are not called when the
program is killed by a signal not handled by Python, when a Python fatal
internal error is detected, or when :func:`os._exit` is called.

.. index:: single: exitfunc (in sys)

This is an alternate interface to the functionality provided by the
:func:`sys.exitfunc` variable.

Note: This module is unlikely to work correctly when used with other code that
sets ``sys.exitfunc``.  In particular, other core Python modules are free to use
:mod:`atexit` without the programmer's knowledge.  Authors who use
``sys.exitfunc`` should convert their code to use :mod:`atexit` instead.  The
simplest way to convert code that sets ``sys.exitfunc`` is to import
:mod:`atexit` and register the function that had been bound to ``sys.exitfunc``.


.. function:: register(func[, *args[, **kwargs]])

   Register *func* as a function to be executed at termination.  Any optional
   arguments that are to be passed to *func* must be passed as arguments to
   :func:`register`.  It is possible to register the same function and arguments
   more than once.

   At normal program termination (for instance, if :func:`sys.exit` is called or
   the main module's execution completes), all functions registered are called in
   last in, first out order.  The assumption is that lower level modules will
   normally be imported before higher level modules and thus must be cleaned up
   later.

   If an exception is raised during execution of the exit handlers, a traceback is
   printed (unless :exc:`SystemExit` is raised) and the exception information is
   saved.  After all exit handlers have had a chance to run the last exception to
   be raised is re-raised.

   .. versionchanged:: 2.6
      This function now returns *func*, which makes it possible to use it as a
      decorator.


.. seealso::

   Module :mod:`readline`
      Useful example of :mod:`atexit` to read and write :mod:`readline` history files.


.. _atexit-example:

:mod:`atexit` Example
---------------------

The following simple example demonstrates how a module can initialize a counter
from a file when it is imported and save the counter's updated value
automatically when the program terminates without relying on the application
making an explicit call into this module at termination. ::

   try:
       _count = int(open("counter").read())
   except IOError:
       _count = 0

   def incrcounter(n):
       global _count
       _count = _count + n

   def savecounter():
       open("counter", "w").write("%d" % _count)

   import atexit
   atexit.register(savecounter)

Positional and keyword arguments may also be passed to :func:`register` to be
passed along to the registered function when it is called::

   def goodbye(name, adjective):
       print 'Goodbye, %s, it was %s to meet you.' % (name, adjective)

   import atexit
   atexit.register(goodbye, 'Donny', 'nice')

   # or:
   atexit.register(goodbye, adjective='nice', name='Donny')

Usage as a :term:`decorator`::

   import atexit

   @atexit.register
   def goodbye():
       print "You are now leaving the Python sector."

This only works with functions that can be called without arguments.
PK	%�\��~�(�(%html/_sources/library/audioop.rst.txtnu�[���
:mod:`audioop` --- Manipulate raw audio data
============================================

.. module:: audioop
   :synopsis: Manipulate raw audio data.


The :mod:`audioop` module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples 8, 16 or 32
bits wide, stored in Python strings.  This is the same format as used by the
:mod:`al` and :mod:`sunaudiodev` modules.  All scalar items are integers, unless
specified otherwise.

.. index::
   single: Intel/DVI ADPCM
   single: ADPCM, Intel/DVI
   single: a-LAW
   single: u-LAW

This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.

.. This para is mostly here to provide an excuse for the index entries...

A few of the more complicated operations only take 16-bit samples, otherwise the
sample size (in bytes) is always a parameter of the operation.

The module defines the following variables and functions:


.. exception:: error

   This exception is raised on all errors, such as unknown number of bytes per
   sample, etc.


.. function:: add(fragment1, fragment2, width)

   Return a fragment which is the addition of the two samples passed as parameters.
   *width* is the sample width in bytes, either ``1``, ``2`` or ``4``.  Both
   fragments should have the same length.  Samples are truncated in case of overflow.


.. function:: adpcm2lin(adpcmfragment, width, state)

   Decode an Intel/DVI ADPCM coded fragment to a linear fragment.  See the
   description of :func:`lin2adpcm` for details on ADPCM coding. Return a tuple
   ``(sample, newstate)`` where the sample has the width specified in *width*.


.. function:: alaw2lin(fragment, width)

   Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
   a-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
   width of the output fragment here.

   .. versionadded:: 2.5


.. function:: avg(fragment, width)

   Return the average over all samples in the fragment.


.. function:: avgpp(fragment, width)

   Return the average peak-peak value over all samples in the fragment. No
   filtering is done, so the usefulness of this routine is questionable.


.. function:: bias(fragment, width, bias)

   Return a fragment that is the original fragment with a bias added to each
   sample.  Samples wrap around in case of overflow.


.. function:: cross(fragment, width)

   Return the number of zero crossings in the fragment passed as an argument.


.. function:: findfactor(fragment, reference)

   Return a factor *F* such that ``rms(add(fragment, mul(reference, -F)))`` is
   minimal, i.e., return the factor with which you should multiply *reference* to
   make it match as well as possible to *fragment*.  The fragments should both
   contain 2-byte samples.

   The time taken by this routine is proportional to ``len(fragment)``.


.. function:: findfit(fragment, reference)

   Try to match *reference* as well as possible to a portion of *fragment* (which
   should be the longer fragment).  This is (conceptually) done by taking slices
   out of *fragment*, using :func:`findfactor` to compute the best match, and
   minimizing the result.  The fragments should both contain 2-byte samples.
   Return a tuple ``(offset, factor)`` where *offset* is the (integer) offset into
   *fragment* where the optimal match started and *factor* is the (floating-point)
   factor as per :func:`findfactor`.


.. function:: findmax(fragment, length)

   Search *fragment* for a slice of length *length* samples (not bytes!) with
   maximum energy, i.e., return *i* for which ``rms(fragment[i*2:(i+length)*2])``
   is maximal.  The fragments should both contain 2-byte samples.

   The routine takes time proportional to ``len(fragment)``.


.. function:: getsample(fragment, width, index)

   Return the value of sample *index* from the fragment.


.. function:: lin2adpcm(fragment, width, state)

   Convert samples to 4 bit Intel/DVI ADPCM encoding.  ADPCM coding is an adaptive
   coding scheme, whereby each 4 bit number is the difference between one sample
   and the next, divided by a (varying) step.  The Intel/DVI ADPCM algorithm has
   been selected for use by the IMA, so it may well become a standard.

   *state* is a tuple containing the state of the coder.  The coder returns a tuple
   ``(adpcmfrag, newstate)``, and the *newstate* should be passed to the next call
   of :func:`lin2adpcm`.  In the initial call, ``None`` can be passed as the state.
   *adpcmfrag* is the ADPCM coded fragment packed 2 4-bit values per byte.


.. function:: lin2alaw(fragment, width)

   Convert samples in the audio fragment to a-LAW encoding and return this as a
   Python string.  a-LAW is an audio encoding format whereby you get a dynamic
   range of about 13 bits using only 8 bit samples.  It is used by the Sun audio
   hardware, among others.

   .. versionadded:: 2.5


.. function:: lin2lin(fragment, width, newwidth)

   Convert samples between 1-, 2- and 4-byte formats.

   .. note::

      In some audio formats, such as .WAV files, 16 and 32 bit samples are
      signed, but 8 bit samples are unsigned.  So when converting to 8 bit wide
      samples for these formats, you need to also add 128 to the result::

         new_frames = audioop.lin2lin(frames, old_width, 1)
         new_frames = audioop.bias(new_frames, 1, 128)

      The same, in reverse, has to be applied when converting from 8 to 16 or 32
      bit width samples.


.. function:: lin2ulaw(fragment, width)

   Convert samples in the audio fragment to u-LAW encoding and return this as a
   Python string.  u-LAW is an audio encoding format whereby you get a dynamic
   range of about 14 bits using only 8 bit samples.  It is used by the Sun audio
   hardware, among others.


.. function:: max(fragment, width)

   Return the maximum of the *absolute value* of all samples in a fragment.


.. function:: maxpp(fragment, width)

   Return the maximum peak-peak value in the sound fragment.


.. function:: minmax(fragment, width)

   Return a tuple consisting of the minimum and maximum values of all samples in
   the sound fragment.


.. function:: mul(fragment, width, factor)

   Return a fragment that has all samples in the original fragment multiplied by
   the floating-point value *factor*.  Samples are truncated in case of overflow.


.. function:: ratecv(fragment, width, nchannels, inrate, outrate, state[, weightA[, weightB]])

   Convert the frame rate of the input fragment.

   *state* is a tuple containing the state of the converter.  The converter returns
   a tuple ``(newfragment, newstate)``, and *newstate* should be passed to the next
   call of :func:`ratecv`.  The initial call should pass ``None`` as the state.

   The *weightA* and *weightB* arguments are parameters for a simple digital filter
   and default to ``1`` and ``0`` respectively.


.. function:: reverse(fragment, width)

   Reverse the samples in a fragment and returns the modified fragment.


.. function:: rms(fragment, width)

   Return the root-mean-square of the fragment, i.e. ``sqrt(sum(S_i^2)/n)``.

   This is a measure of the power in an audio signal.


.. function:: tomono(fragment, width, lfactor, rfactor)

   Convert a stereo fragment to a mono fragment.  The left channel is multiplied by
   *lfactor* and the right channel by *rfactor* before adding the two channels to
   give a mono signal.


.. function:: tostereo(fragment, width, lfactor, rfactor)

   Generate a stereo fragment from a mono fragment.  Each pair of samples in the
   stereo fragment are computed from the mono sample, whereby left channel samples
   are multiplied by *lfactor* and right channel samples by *rfactor*.


.. function:: ulaw2lin(fragment, width)

   Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
   u-LAW encoding always uses 8 bits samples, so *width* refers only to the sample
   width of the output fragment here.

Note that operations such as :func:`.mul` or :func:`.max` make no distinction
between mono and stereo fragments, i.e. all samples are treated equal.  If this
is a problem the stereo fragment should be split into two mono fragments first
and recombined later.  Here is an example of how to do that::

   def mul_stereo(sample, width, lfactor, rfactor):
       lsample = audioop.tomono(sample, width, 1, 0)
       rsample = audioop.tomono(sample, width, 0, 1)
       lsample = audioop.mul(lsample, width, lfactor)
       rsample = audioop.mul(rsample, width, rfactor)
       lsample = audioop.tostereo(lsample, width, 1, 0)
       rsample = audioop.tostereo(rsample, width, 0, 1)
       return audioop.add(lsample, rsample, width)

If you use the ADPCM coder to build network packets and you want your protocol
to be stateless (i.e. to be able to tolerate packet loss) you should not only
transmit the data but also the state.  Note that you should send the *initial*
state (the one you passed to :func:`lin2adpcm`) along to the decoder, not the
final state (as returned by the coder).  If you want to use
:class:`struct.Struct` to store the state in binary you can code the first
element (the predicted value) in 16 bits and the second (the delta index) in 8.

The ADPCM coders have never been tried against other ADPCM coders, only against
themselves.  It could well be that I misinterpreted the standards in which case
they will not be interoperable with the respective standards.

The :func:`find\*` routines might look a bit funny at first sight. They are
primarily meant to do echo cancellation.  A reasonably fast way to do this is to
pick the most energetic piece of the output sample, locate that in the input
sample and subtract the whole output sample from the input sample::

   def echocancel(outputdata, inputdata):
       pos = audioop.findmax(outputdata, 800)    # one tenth second
       out_test = outputdata[pos*2:]
       in_test = inputdata[pos*2:]
       ipos, factor = audioop.findfit(in_test, out_test)
       # Optional (for better cancellation):
       # factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],
       #              out_test)
       prefill = '\0'*(pos+ipos)*2
       postfill = '\0'*(len(inputdata)-len(prefill)-len(outputdata))
       outputdata = prefill + audioop.mul(outputdata, 2, -factor) + postfill
       return audioop.add(inputdata, outputdata, 2)

PK	%�\��V��%html/_sources/library/autogil.rst.txtnu�[���
:mod:`autoGIL` --- Global Interpreter Lock handling in event loops
==================================================================

.. module:: autoGIL
   :platform: Mac
   :synopsis: Global Interpreter Lock handling in event loops.
   :deprecated:
.. moduleauthor:: Just van Rossum <just@letterror.com>


The :mod:`autoGIL` module provides a function :func:`installAutoGIL` that
automatically locks and unlocks Python's :term:`Global Interpreter Lock` when
running an event loop.

.. note::

   This module has been removed in Python 3.x.


.. exception:: AutoGILError

   Raised if the observer callback cannot be installed, for example because the
   current thread does not have a run loop.


.. function:: installAutoGIL()

   Install an observer callback in the event loop (CFRunLoop) for the current
   thread, that will lock and unlock the Global Interpreter Lock (GIL) at
   appropriate times, allowing other Python threads to run while the event loop is
   idle.

   Availability: OSX 10.1 or later.

PK	%�\Q�{ll$html/_sources/library/base64.rst.txtnu�[���:mod:`base64` --- RFC 3548: Base16, Base32, Base64 Data Encodings
=================================================================

.. module:: base64
   :synopsis: RFC 3548: Base16, Base32, Base64 Data Encodings


.. index::
   pair: base64; encoding
   single: MIME; base64 encoding

This module provides data encoding and decoding as specified in :rfc:`3548`.
This standard defines the Base16, Base32, and Base64 algorithms for encoding and
decoding arbitrary binary strings into text strings that can be safely sent by
email, used as parts of URLs, or included as part of an HTTP POST request.  The
encoding algorithm is not the same as the :program:`uuencode` program.

There are two interfaces provided by this module.  The modern interface supports
encoding and decoding string objects using both base-64 alphabets defined
in :rfc:`3548` (normal, and URL- and filesystem-safe).  The legacy
interface provides for encoding and decoding to and from file-like objects as
well as strings, but only using the Base64 standard alphabet.

The modern interface, which was introduced in Python 2.4, provides:


.. function:: b64encode(s[, altchars])

   Encode a string using Base64.

   *s* is the string to encode.  Optional *altchars* must be a string of at least
   length 2 (additional characters are ignored) which specifies an alternative
   alphabet for the ``+`` and ``/`` characters.  This allows an application to e.g.
   generate URL or filesystem safe Base64 strings.  The default is ``None``, for
   which the standard Base64 alphabet is used.

   The encoded string is returned.


.. function:: b64decode(s[, altchars])

   Decode a Base64 encoded string.

   *s* is the string to decode.  Optional *altchars* must be a string of at least
   length 2 (additional characters are ignored) which specifies the alternative
   alphabet used instead of the ``+`` and ``/`` characters.

   The decoded string is returned.  A :exc:`TypeError` is raised if *s* is
   incorrectly padded.  Characters that are neither
   in the normal base-64 alphabet nor the alternative alphabet are
   discarded prior to the padding check.


.. function:: standard_b64encode(s)

   Encode string *s* using the standard Base64 alphabet.


.. function:: standard_b64decode(s)

   Decode string *s* using the standard Base64 alphabet.


.. function:: urlsafe_b64encode(s)

   Encode string *s* using the URL- and filesystem-safe
   alphabet, which substitutes ``-`` instead of
   ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet.  The result
   can still contain ``=``.


.. function:: urlsafe_b64decode(s)

   Decode string *s* using the URL- and filesystem-safe
   alphabet, which substitutes ``-`` instead of
   ``+`` and ``_`` instead of ``/`` in the standard Base64 alphabet.


.. function:: b32encode(s)

   Encode a string using Base32.  *s* is the string to encode.  The encoded string
   is returned.


.. function:: b32decode(s[, casefold[, map01]])

   Decode a Base32 encoded string.

   *s* is the string to decode.  Optional *casefold* is a flag specifying whether a
   lowercase alphabet is acceptable as input.  For security purposes, the default
   is ``False``.

   :rfc:`3548` allows for optional mapping of the digit 0 (zero) to the letter O
   (oh), and for optional mapping of the digit 1 (one) to either the letter I (eye)
   or letter L (el).  The optional argument *map01* when not ``None``, specifies
   which letter the digit 1 should be mapped to (when *map01* is not ``None``, the
   digit 0 is always mapped to the letter O).  For security purposes the default is
   ``None``, so that 0 and 1 are not allowed in the input.

   The decoded string is returned.  A :exc:`TypeError` is raised if *s* is
   incorrectly padded or if there are non-alphabet characters present in the
   string.


.. function:: b16encode(s)

   Encode a string using Base16.

   *s* is the string to encode.  The encoded string is returned.


.. function:: b16decode(s[, casefold])

   Decode a Base16 encoded string.

   *s* is the string to decode.  Optional *casefold* is a flag specifying whether a
   lowercase alphabet is acceptable as input.  For security purposes, the default
   is ``False``.

   The decoded string is returned.  A :exc:`TypeError` is raised if *s* were
   incorrectly padded or if there are non-alphabet characters present in the
   string.

The legacy interface:


.. function:: decode(input, output)

   Decode the contents of the *input* file and write the resulting binary data to
   the *output* file. *input* and *output* must either be file objects or objects
   that mimic the file object interface. *input* will be read until
   ``input.read()`` returns an empty string.


.. function:: decodestring(s)

   Decode the string *s*, which must contain one or more lines of base64 encoded
   data, and return a string containing the resulting binary data.


.. function:: encode(input, output)

   Encode the contents of the *input* file and write the resulting base64 encoded
   data to the *output* file. *input* and *output* must either be file objects or
   objects that mimic the file object interface. *input* will be read until
   ``input.read()`` returns an empty string.  :func:`encode` returns the encoded
   data plus a trailing newline character (``'\n'``).


.. function:: encodestring(s)

   Encode the string *s*, which can contain arbitrary binary data, and return a
   string containing one or more lines of base64-encoded data.
   :func:`encodestring` returns a string containing one or more lines of
   base64-encoded data always including an extra trailing newline (``'\n'``).

An example usage of the module:

   >>> import base64
   >>> encoded = base64.b64encode('data to be encoded')
   >>> encoded
   'ZGF0YSB0byBiZSBlbmNvZGVk'
   >>> data = base64.b64decode(encoded)
   >>> data
   'data to be encoded'


.. seealso::

   Module :mod:`binascii`
      Support module containing ASCII-to-binary and binary-to-ASCII conversions.

   :rfc:`1521` - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies
      Section 5.2, "Base64 Content-Transfer-Encoding," provides the definition of the
      base64 encoding.

PK	%�\�Q�^�(�(,html/_sources/library/basehttpserver.rst.txtnu�[���:mod:`BaseHTTPServer` --- Basic HTTP server
===========================================

.. module:: BaseHTTPServer
   :synopsis: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer).

.. note::
   The :mod:`BaseHTTPServer` module has been merged into :mod:`http.server` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.


.. index::
   pair: WWW; server
   pair: HTTP; protocol
   single: URL
   single: httpd
   module: SimpleHTTPServer
   module: CGIHTTPServer

**Source code:** :source:`Lib/BaseHTTPServer.py`

--------------

This module defines two classes for implementing HTTP servers (Web servers).
Usually, this module isn't used directly, but is used as a basis for building
functioning Web servers. See the :mod:`SimpleHTTPServer` and
:mod:`CGIHTTPServer` modules.

The first class, :class:`HTTPServer`, is a :class:`SocketServer.TCPServer`
subclass, and therefore implements the :class:`SocketServer.BaseServer`
interface.  It creates and listens at the HTTP socket, dispatching the requests
to a handler.  Code to create and run the server looks like this::

   def run(server_class=BaseHTTPServer.HTTPServer,
           handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
       server_address = ('', 8000)
       httpd = server_class(server_address, handler_class)
       httpd.serve_forever()


.. class:: HTTPServer(server_address, RequestHandlerClass)

   This class builds on the :class:`TCPServer` class by storing the server
   address as instance variables named :attr:`server_name` and
   :attr:`server_port`. The server is accessible by the handler, typically
   through the handler's :attr:`server` instance variable.


.. class:: BaseHTTPRequestHandler(request, client_address, server)

   This class is used to handle the HTTP requests that arrive at the server. By
   itself, it cannot respond to any actual HTTP requests; it must be subclassed
   to handle each request method (e.g. GET or
   POST). :class:`BaseHTTPRequestHandler` provides a number of class and
   instance variables, and methods for use by subclasses.

   The handler will parse the request and the headers, then call a method
   specific to the request type. The method name is constructed from the
   request. For example, for the request method ``SPAM``, the :meth:`do_SPAM`
   method will be called with no arguments. All of the relevant information is
   stored in instance variables of the handler.  Subclasses should not need to
   override or extend the :meth:`__init__` method.

   :class:`BaseHTTPRequestHandler` has the following instance variables:


   .. attribute:: client_address

      Contains a tuple of the form ``(host, port)`` referring to the client's
      address.


   .. attribute:: server

      Contains the server instance.


   .. attribute:: command

      Contains the command (request type). For example, ``'GET'``.


   .. attribute:: path

      Contains the request path.


   .. attribute:: request_version

      Contains the version string from the request. For example, ``'HTTP/1.0'``.


   .. attribute:: headers

      Holds an instance of the class specified by the :attr:`MessageClass` class
      variable. This instance parses and manages the headers in the HTTP
      request.


   .. attribute:: rfile

      Contains an input stream, positioned at the start of the optional input
      data.


   .. attribute:: wfile

      Contains the output stream for writing a response back to the
      client. Proper adherence to the HTTP protocol must be used when writing to
      this stream.


   :class:`BaseHTTPRequestHandler` has the following class variables:


   .. attribute:: server_version

      Specifies the server software version.  You may want to override this. The
      format is multiple whitespace-separated strings, where each string is of
      the form name[/version]. For example, ``'BaseHTTP/0.2'``.


   .. attribute:: sys_version

      Contains the Python system version, in a form usable by the
      :attr:`version_string` method and the :attr:`server_version` class
      variable. For example, ``'Python/1.4'``.


   .. attribute:: error_message_format

      Specifies a format string for building an error response to the client. It
      uses parenthesized, keyed format specifiers, so the format operand must be
      a dictionary. The *code* key should be an integer, specifying the numeric
      HTTP error code value. *message* should be a string containing a
      (detailed) error message of what occurred, and *explain* should be an
      explanation of the error code number. Default *message* and *explain*
      values can found in the *responses* class variable.


   .. attribute:: error_content_type

      Specifies the Content-Type HTTP header of error responses sent to the
      client.  The default value is ``'text/html'``.

      .. versionadded:: 2.6
         Previously, the content type was always ``'text/html'``.


   .. attribute:: protocol_version

      This specifies the HTTP protocol version used in responses.  If set to
      ``'HTTP/1.1'``, the server will permit HTTP persistent connections;
      however, your server *must* then include an accurate ``Content-Length``
      header (using :meth:`send_header`) in all of its responses to clients.
      For backwards compatibility, the setting defaults to ``'HTTP/1.0'``.


   .. attribute:: MessageClass

      .. index:: single: Message (in module mimetools)

      Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers.
      Typically, this is not overridden, and it defaults to
      :class:`mimetools.Message`.


   .. attribute:: responses

      This variable contains a mapping of error code integers to two-element tuples
      containing a short and long message. For example, ``{code: (shortmessage,
      longmessage)}``. The *shortmessage* is usually used as the *message* key in an
      error response, and *longmessage* as the *explain* key (see the
      :attr:`error_message_format` class variable).


   A :class:`BaseHTTPRequestHandler` instance has the following methods:


   .. method:: handle()

      Calls :meth:`handle_one_request` once (or, if persistent connections are
      enabled, multiple times) to handle incoming HTTP requests. You should
      never need to override it; instead, implement appropriate :meth:`do_\*`
      methods.


   .. method:: handle_one_request()

      This method will parse and dispatch the request to the appropriate
      :meth:`do_\*` method.  You should never need to override it.


   .. method:: send_error(code[, message])

      Sends and logs a complete error reply to the client. The numeric *code*
      specifies the HTTP error code, with *message* as optional, more specific text. A
      complete set of headers is sent, followed by text composed using the
      :attr:`error_message_format` class variable. The body will be empty
      if the method is HEAD or the response code is one of the following:
      ``1xx``, ``204 No Content``, ``205 Reset Content``,
      ``304 Not Modified``.


   .. method:: send_response(code[, message])

      Sends a response header and logs the accepted request. The HTTP response
      line is sent, followed by *Server* and *Date* headers. The values for
      these two headers are picked up from the :meth:`version_string` and
      :meth:`date_time_string` methods, respectively.


   .. method:: send_header(keyword, value)

      Writes a specific HTTP header to the output stream. *keyword* should
      specify the header keyword, with *value* specifying its value.


   .. method:: end_headers()

      Sends a blank line, indicating the end of the HTTP headers in the
      response.


   .. method:: log_request([code[, size]])

      Logs an accepted (successful) request. *code* should specify the numeric
      HTTP code associated with the response. If a size of the response is
      available, then it should be passed as the *size* parameter.


   .. method:: log_error(...)

      Logs an error when a request cannot be fulfilled. By default, it passes
      the message to :meth:`log_message`, so it takes the same arguments
      (*format* and additional values).


   .. method:: log_message(format, ...)

      Logs an arbitrary message to ``sys.stderr``. This is typically overridden
      to create custom error logging mechanisms. The *format* argument is a
      standard printf-style format string, where the additional arguments to
      :meth:`log_message` are applied as inputs to the formatting. The client
      ip address and current date and time are prefixed to every message logged.


   .. method:: version_string()

      Returns the server software's version string. This is a combination of the
      :attr:`server_version` and :attr:`sys_version` class variables.


   .. method:: date_time_string([timestamp])

      Returns the date and time given by *timestamp* (which must be in the
      format returned by :func:`time.time`), formatted for a message header. If
      *timestamp* is omitted, it uses the current date and time.

      The result looks like ``'Sun, 06 Nov 1994 08:49:37 GMT'``.

      .. versionadded:: 2.5
         The *timestamp* parameter.


   .. method:: log_date_time_string()

      Returns the current date and time, formatted for logging.


   .. method:: address_string()

      Returns the client address, formatted for logging. A name lookup is
      performed on the client's IP address.


More examples
-------------

To create a server that doesn't run forever, but until some condition is
fulfilled::

   def run_while_true(server_class=BaseHTTPServer.HTTPServer,
                      handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
       """
       This assumes that keep_running() is a function of no arguments which
       is tested initially and after each request.  If its return value
       is true, the server continues.
       """
       server_address = ('', 8000)
       httpd = server_class(server_address, handler_class)
       while keep_running():
           httpd.handle_request()


.. seealso::

   Module :mod:`CGIHTTPServer`
      Extended request handler that supports CGI scripts.

   Module :mod:`SimpleHTTPServer`
      Basic request handler that limits response to files actually under the
      document root.

PK	%�\a�3
3
%html/_sources/library/bastion.rst.txtnu�[���
:mod:`Bastion` --- Restricting access to objects
================================================

.. module:: Bastion
   :synopsis: Providing restricted access to objects.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`Bastion` module has been removed in Python 3.

.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>


.. versionchanged:: 2.3
   Disabled module.

.. note::

   The documentation has been left in place to help in reading old code that uses
   the module.

According to the dictionary, a bastion is "a fortified area or position", or
"something that is considered a stronghold."  It's a suitable name for this
module, which provides a way to forbid access to certain attributes of an
object.  It must always be used with the :mod:`rexec` module, in order to allow
restricted-mode programs access to certain safe attributes of an object, while
denying access to other, unsafe attributes.

.. I'm concerned that the word 'bastion' won't be understood by people
.. for whom English is a second language, making the module name
.. somewhat mysterious.  Thus, the brief definition... --amk

.. I've punted on the issue of documenting keyword arguments for now.


.. function:: Bastion(object[, filter[, name[, class]]])

   Protect the object *object*, returning a bastion for the object.  Any attempt to
   access one of the object's attributes will have to be approved by the *filter*
   function; if the access is denied an :exc:`AttributeError` exception will be
   raised.

   If present, *filter* must be a function that accepts a string containing an
   attribute name, and returns true if access to that attribute will be permitted;
   if *filter* returns false, the access is denied.  The default filter denies
   access to any function beginning with an underscore (``'_'``).  The bastion's
   string representation will be ``<Bastion for name>`` if a value for *name* is
   provided; otherwise, ``repr(object)`` will be used.

   *class*, if present, should be a subclass of :class:`BastionClass`;  see the
   code in :file:`bastion.py` for the details.  Overriding the default
   :class:`BastionClass` will rarely be required.


.. class:: BastionClass(getfunc, name)

   Class which actually implements bastion objects.  This is the default class used
   by :func:`Bastion`.  The *getfunc* parameter is a function which returns the
   value of an attribute which should be exposed to the restricted execution
   environment when called with the name of the attribute as the only parameter.
   *name* is used to construct the :func:`repr` of the :class:`BastionClass`
   instance.

PK	%�\��N�0�0!html/_sources/library/bdb.rst.txtnu�[���:mod:`bdb` --- Debugger framework
=================================

.. module:: bdb
   :synopsis: Debugger framework.

**Source code:** :source:`Lib/bdb.py`

--------------

The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.

The following exception is defined:

.. exception:: BdbQuit

   Exception raised by the :class:`Bdb` class for quitting the debugger.


The :mod:`bdb` module also defines two classes:

.. class:: Breakpoint(self, file, line, temporary=0, cond=None, funcname=None)

   This class implements temporary breakpoints, ignore counts, disabling and
   (re-)enabling, and conditionals.

   Breakpoints are indexed by number through a list called :attr:`bpbynumber`
   and by ``(file, line)`` pairs through :attr:`bplist`.  The former points to a
   single instance of class :class:`Breakpoint`.  The latter points to a list of
   such instances since there may be more than one breakpoint per line.

   When creating a breakpoint, its associated filename should be in canonical
   form.  If a *funcname* is defined, a breakpoint hit will be counted when the
   first line of that function is executed.  A conditional breakpoint always
   counts a hit.

   :class:`Breakpoint` instances have the following methods:

   .. method:: deleteMe()

      Delete the breakpoint from the list associated to a file/line.  If it is
      the last breakpoint in that position, it also deletes the entry for the
      file/line.


   .. method:: enable()

      Mark the breakpoint as enabled.


   .. method:: disable()

      Mark the breakpoint as disabled.


   .. method:: pprint([out])

      Print all the information about the breakpoint:

      * The breakpoint number.
      * If it is temporary or not.
      * Its file,line position.
      * The condition that causes a break.
      * If it must be ignored the next N times.
      * The breakpoint hit count.


.. class:: Bdb(skip=None)

   The :class:`Bdb` class acts as a generic Python debugger base class.

   This class takes care of the details of the trace facility; a derived class
   should implement user interaction.  The standard debugger class
   (:class:`pdb.Pdb`) is an example.

   The *skip* argument, if given, must be an iterable of glob-style
   module name patterns.  The debugger will not step into frames that
   originate in a module that matches one of these patterns. Whether a
   frame is considered to originate in a certain module is determined
   by the ``__name__`` in the frame globals.

   .. versionadded:: 2.7
      The *skip* argument.

   The following methods of :class:`Bdb` normally don't need to be overridden.

   .. method:: canonic(filename)

      Auxiliary method for getting a filename in a canonical form, that is, as a
      case-normalized (on case-insensitive filesystems) absolute path, stripped
      of surrounding angle brackets.

   .. method:: reset()

      Set the :attr:`botframe`, :attr:`stopframe`, :attr:`returnframe` and
      :attr:`quitting` attributes with values ready to start debugging.

   .. method:: trace_dispatch(frame, event, arg)

      This function is installed as the trace function of debugged frames.  Its
      return value is the new trace function (in most cases, that is, itself).

      The default implementation decides how to dispatch a frame, depending on
      the type of event (passed as a string) that is about to be executed.
      *event* can be one of the following:

      * ``"line"``: A new line of code is going to be executed.
      * ``"call"``: A function is about to be called, or another code block
        entered.
      * ``"return"``: A function or other code block is about to return.
      * ``"exception"``: An exception has occurred.
      * ``"c_call"``: A C function is about to be called.
      * ``"c_return"``: A C function has returned.
      * ``"c_exception"``: A C function has raised an exception.

      For the Python events, specialized functions (see below) are called.  For
      the C events, no action is taken.

      The *arg* parameter depends on the previous event.

      See the documentation for :func:`sys.settrace` for more information on the
      trace function.  For more information on code and frame objects, refer to
      :ref:`types`.

   .. method:: dispatch_line(frame)

      If the debugger should stop on the current line, invoke the
      :meth:`user_line` method (which should be overridden in subclasses).
      Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
      (which can be set from :meth:`user_line`).  Return a reference to the
      :meth:`trace_dispatch` method for further tracing in that scope.

   .. method:: dispatch_call(frame, arg)

      If the debugger should stop on this function call, invoke the
      :meth:`user_call` method (which should be overridden in subclasses).
      Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
      (which can be set from :meth:`user_call`).  Return a reference to the
      :meth:`trace_dispatch` method for further tracing in that scope.

   .. method:: dispatch_return(frame, arg)

      If the debugger should stop on this function return, invoke the
      :meth:`user_return` method (which should be overridden in subclasses).
      Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
      (which can be set from :meth:`user_return`).  Return a reference to the
      :meth:`trace_dispatch` method for further tracing in that scope.

   .. method:: dispatch_exception(frame, arg)

      If the debugger should stop at this exception, invokes the
      :meth:`user_exception` method (which should be overridden in subclasses).
      Raise a :exc:`BdbQuit` exception if the :attr:`Bdb.quitting` flag is set
      (which can be set from :meth:`user_exception`).  Return a reference to the
      :meth:`trace_dispatch` method for further tracing in that scope.

   Normally derived classes don't override the following methods, but they may
   if they want to redefine the definition of stopping and breakpoints.

   .. method:: stop_here(frame)

      This method checks if the *frame* is somewhere below :attr:`botframe` in
      the call stack.  :attr:`botframe` is the frame in which debugging started.

   .. method:: break_here(frame)

      This method checks if there is a breakpoint in the filename and line
      belonging to *frame* or, at least, in the current function.  If the
      breakpoint is a temporary one, this method deletes it.

   .. method:: break_anywhere(frame)

      This method checks if there is a breakpoint in the filename of the current
      frame.

   Derived classes should override these methods to gain control over debugger
   operation.

   .. method:: user_call(frame, argument_list)

      This method is called from :meth:`dispatch_call` when there is the
      possibility that a break might be necessary anywhere inside the called
      function.

   .. method:: user_line(frame)

      This method is called from :meth:`dispatch_line` when either
      :meth:`stop_here` or :meth:`break_here` yields ``True``.

   .. method:: user_return(frame, return_value)

      This method is called from :meth:`dispatch_return` when :meth:`stop_here`
      yields ``True``.

   .. method:: user_exception(frame, exc_info)

      This method is called from :meth:`dispatch_exception` when
      :meth:`stop_here` yields ``True``.

   .. method:: do_clear(arg)

      Handle how a breakpoint must be removed when it is a temporary one.

      This method must be implemented by derived classes.


   Derived classes and clients can call the following methods to affect the
   stepping state.

   .. method:: set_step()

      Stop after one line of code.

   .. method:: set_next(frame)

      Stop on the next line in or below the given frame.

   .. method:: set_return(frame)

      Stop when returning from the given frame.

   .. method:: set_until(frame)

      Stop when the line with the line no greater than the current one is
      reached or when returning from current frame.

   .. method:: set_trace([frame])

      Start debugging from *frame*.  If *frame* is not specified, debugging
      starts from caller's frame.

   .. method:: set_continue()

      Stop only at breakpoints or when finished.  If there are no breakpoints,
      set the system trace function to ``None``.

   .. method:: set_quit()

      Set the :attr:`quitting` attribute to ``True``.  This raises :exc:`BdbQuit` in
      the next call to one of the :meth:`dispatch_\*` methods.


   Derived classes and clients can call the following methods to manipulate
   breakpoints.  These methods return a string containing an error message if
   something went wrong, or ``None`` if all is well.

   .. method:: set_break(filename, lineno, temporary=0, cond=None, funcname=None)

      Set a new breakpoint.  If the *lineno* line doesn't exist for the
      *filename* passed as argument, return an error message.  The *filename*
      should be in canonical form, as described in the :meth:`canonic` method.

   .. method:: clear_break(filename, lineno)

      Delete the breakpoints in *filename* and *lineno*.  If none were set, an
      error message is returned.

   .. method:: clear_bpbynumber(arg)

      Delete the breakpoint which has the index *arg* in the
      :attr:`Breakpoint.bpbynumber`.  If *arg* is not numeric or out of range,
      return an error message.

   .. method:: clear_all_file_breaks(filename)

      Delete all breakpoints in *filename*.  If none were set, an error message
      is returned.

   .. method:: clear_all_breaks()

      Delete all existing breakpoints.

   .. method:: get_break(filename, lineno)

      Check if there is a breakpoint for *lineno* of *filename*.

   .. method:: get_breaks(filename, lineno)

      Return all breakpoints for *lineno* in *filename*, or an empty list if
      none are set.

   .. method:: get_file_breaks(filename)

      Return all breakpoints in *filename*, or an empty list if none are set.

   .. method:: get_all_breaks()

      Return all breakpoints that are set.


   Derived classes and clients can call the following methods to get a data
   structure representing a stack trace.

   .. method:: get_stack(f, t)

      Get a list of records for a frame and all higher (calling) and lower
      frames, and the size of the higher part.

   .. method:: format_stack_entry(frame_lineno, [lprefix=': '])

      Return a string with information about a stack entry, identified by a
      ``(frame, lineno)`` tuple:

      * The canonical form of the filename which contains the frame.
      * The function name, or ``"<lambda>"``.
      * The input arguments.
      * The return value.
      * The line of code (if it exists).


   The following two methods can be called by clients to use a debugger to debug
   a :term:`statement`, given as a string.

   .. method:: run(cmd, [globals, [locals]])

      Debug a statement executed via the :keyword:`exec` statement.  *globals*
      defaults to :attr:`__main__.__dict__`, *locals* defaults to *globals*.

   .. method:: runeval(expr, [globals, [locals]])

      Debug an expression executed via the :func:`eval` function.  *globals* and
      *locals* have the same meaning as in :meth:`run`.

   .. method:: runctx(cmd, globals, locals)

      For backwards compatibility.  Calls the :meth:`run` method.

   .. method:: runcall(func, *args, **kwds)

      Debug a single function call, and return its result.


Finally, the module defines the following functions:

.. function:: checkfuncname(b, frame)

   Check whether we should break here, depending on the way the breakpoint *b*
   was set.

   If it was set via line number, it checks if ``b.line`` is the same as the one
   in the frame also passed as argument.  If the breakpoint was set via function
   name, we have to check we are in the right frame (the right function) and if
   we are in its first executable line.

.. function:: effective(file, line, frame)

   Determine if there is an effective (active) breakpoint at this line of code.
   Return a tuple of the breakpoint and a boolean that indicates if it is ok
   to delete a temporary breakpoint.  Return ``(None, None)`` if there is no
   matching breakpoint.

.. function:: set_trace()

   Start debugging with a :class:`Bdb` instance from caller's frame.
PK	%�\����ll&html/_sources/library/binascii.rst.txtnu�[���
:mod:`binascii` --- Convert between binary and ASCII
====================================================

.. module:: binascii
   :synopsis: Tools for converting between binary and various ASCII-encoded binary
              representations.


.. index::
   module: uu
   module: base64
   module: binhex

The :mod:`binascii` module contains a number of methods to convert between
binary and various ASCII-encoded binary representations. Normally, you will not
use these functions directly but use wrapper modules like :mod:`uu`,
:mod:`base64`, or :mod:`binhex` instead. The :mod:`binascii` module contains
low-level functions written in C for greater speed that are used by the
higher-level modules.

The :mod:`binascii` module defines the following functions:


.. function:: a2b_uu(string)

   Convert a single line of uuencoded data back to binary and return the binary
   data. Lines normally contain 45 (binary) bytes, except for the last line. Line
   data may be followed by whitespace.


.. function:: b2a_uu(data)

   Convert binary data to a line of ASCII characters, the return value is the
   converted line, including a newline char. The length of *data* should be at most
   45.


.. function:: a2b_base64(string)

   Convert a block of base64 data back to binary and return the binary data. More
   than one line may be passed at a time.


.. function:: b2a_base64(data)

   Convert binary data to a line of ASCII characters in base64 coding. The return
   value is the converted line, including a newline char.  The newline is
   added because the original use case for this function was to feed it a
   series of 57 byte input lines to get output lines that conform to the
   MIME-base64 standard.  Otherwise the output conforms to :rfc:`3548`.


.. function:: a2b_qp(string[, header])

   Convert a block of quoted-printable data back to binary and return the binary
   data. More than one line may be passed at a time. If the optional argument
   *header* is present and true, underscores will be decoded as spaces.


.. function:: b2a_qp(data[, quotetabs, istext, header])

   Convert binary data to a line(s) of ASCII characters in quoted-printable
   encoding.  The return value is the converted line(s). If the optional argument
   *quotetabs* is present and true, all tabs and spaces will be encoded.   If the
   optional argument *istext* is present and true, newlines are not encoded but
   trailing whitespace will be encoded. If the optional argument *header* is
   present and true, spaces will be encoded as underscores per RFC1522. If the
   optional argument *header* is present and false, newline characters will be
   encoded as well; otherwise linefeed conversion might corrupt the binary data
   stream.


.. function:: a2b_hqx(string)

   Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression.
   The string should contain a complete number of binary bytes, or (in case of the
   last portion of the binhex4 data) have the remaining bits zero.


.. function:: rledecode_hqx(data)

   Perform RLE-decompression on the data, as per the binhex4 standard. The
   algorithm uses ``0x90`` after a byte as a repeat indicator, followed by a count.
   A count of ``0`` specifies a byte value of ``0x90``. The routine returns the
   decompressed data, unless data input data ends in an orphaned repeat indicator,
   in which case the :exc:`Incomplete` exception is raised.


.. function:: rlecode_hqx(data)

   Perform binhex4 style RLE-compression on *data* and return the result.


.. function:: b2a_hqx(data)

   Perform hexbin4 binary-to-ASCII translation and return the resulting string. The
   argument should already be RLE-coded, and have a length divisible by 3 (except
   possibly the last fragment).


.. function:: crc_hqx(data, crc)

   Compute a 16-bit CRC value of *data*, starting with an initial *crc* and
   returning the result.  This uses the CRC-CCITT polynomial
   *x*:sup:`16` + *x*:sup:`12` + *x*:sup:`5` + 1, often represented as
   0x1021.  This CRC is used in the binhex4 format.


.. function:: crc32(data[, crc])

   Compute CRC-32, the 32-bit checksum of data, starting with an initial crc.  This
   is consistent with the ZIP file checksum.  Since the algorithm is designed for
   use as a checksum algorithm, it is not suitable for use as a general hash
   algorithm.  Use as follows::

      print binascii.crc32("hello world")
      # Or, in two pieces:
      crc = binascii.crc32("hello")
      crc = binascii.crc32(" world", crc) & 0xffffffff
      print 'crc32 = 0x%08x' % crc

.. note::
   To generate the same numeric value across all Python versions and
   platforms use crc32(data) & 0xffffffff.  If you are only using
   the checksum in packed binary format this is not necessary as the
   return value is the correct 32bit binary representation
   regardless of sign.

.. versionchanged:: 2.6
   The return value is in the range [-2**31, 2**31-1]
   regardless of platform.  In the past the value would be signed on
   some platforms and unsigned on others.  Use & 0xffffffff on the
   value if you want it to match Python 3 behavior.

.. versionchanged:: 3.0
   The return value is unsigned and in the range [0, 2**32-1]
   regardless of platform.


.. function:: b2a_hex(data)
              hexlify(data)

   Return the hexadecimal representation of the binary *data*.  Every byte of
   *data* is converted into the corresponding 2-digit hex representation.  The
   resulting string is therefore twice as long as the length of *data*.


.. function:: a2b_hex(hexstr)
              unhexlify(hexstr)

   Return the binary data represented by the hexadecimal string *hexstr*.  This
   function is the inverse of :func:`b2a_hex`. *hexstr* must contain an even number
   of hexadecimal digits (which can be upper or lower case), otherwise a
   :exc:`TypeError` is raised.


.. exception:: Error

   Exception raised on errors. These are usually programming errors.


.. exception:: Incomplete

   Exception raised on incomplete data. These are usually not programming errors,
   but may be handled by reading a little more data and trying again.


.. seealso::

   Module :mod:`base64`
      Support for RFC compliant base64-style encoding in base 16, 32, and 64.

   Module :mod:`binhex`
      Support for the binhex format used on the Macintosh.

   Module :mod:`uu`
      Support for UU encoding used on Unix.

   Module :mod:`quopri`
      Support for quoted-printable encoding used in MIME email messages.

PK	%�\�ؗvv$html/_sources/library/binhex.rst.txtnu�[���:mod:`binhex` --- Encode and decode binhex4 files
=================================================

.. module:: binhex
   :synopsis: Encode and decode files in binhex4 format.


This module encodes and decodes files in binhex4 format, a format allowing
representation of Macintosh files in ASCII.  On the Macintosh, both forks of a
file and the finder information are encoded (or decoded), on other platforms
only the data fork is handled.

.. note::

   In Python 3.x, special Macintosh support has been removed.


The :mod:`binhex` module defines the following functions:


.. function:: binhex(input, output)

   Convert a binary file with filename *input* to binhex file *output*. The
   *output* parameter can either be a filename or a file-like object (any object
   supporting a :meth:`write` and :meth:`close` method).


.. function:: hexbin(input[, output])

   Decode a binhex file *input*. *input* may be a filename or a file-like object
   supporting :meth:`read` and :meth:`close` methods. The resulting file is written
   to a file named *output*, unless the argument is omitted in which case the
   output filename is read from the binhex file.

The following exception is also defined:


.. exception:: Error

   Exception raised when something can't be encoded using the binhex format (for
   example, a filename is too long to fit in the filename field), or when input is
   not properly encoded binhex data.


.. seealso::

   Module :mod:`binascii`
      Support module containing ASCII-to-binary and binary-to-ASCII conversions.


.. _binhex-notes:

Notes
-----

There is an alternative, more powerful interface to the coder and decoder, see
the source for details.

If you code or decode textfiles on non-Macintosh platforms they will still use
the old Macintosh newline convention (carriage-return as end of line).

As of this writing, :func:`hexbin` appears to not work in all cases.

PK	%�\�U,�''$html/_sources/library/bisect.rst.txtnu�[���:mod:`bisect` --- Array bisection algorithm
===========================================

.. module:: bisect
   :synopsis: Array bisection algorithms for binary searching.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Raymond Hettinger <python at rcn.com>
.. example based on the PyModules FAQ entry by Aaron Watters <arw@pythonpros.com>

.. versionadded:: 2.1

**Source code:** :source:`Lib/bisect.py`

--------------

This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion.  For long lists of items with
expensive comparison operations, this can be an improvement over the more common
approach.  The module is called :mod:`bisect` because it uses a basic bisection
algorithm to do its work.  The source code may be most useful as a working
example of the algorithm (the boundary conditions are already right!).

The following functions are provided:


.. function:: bisect_left(a, x, lo=0, hi=len(a))

   Locate the insertion point for *x* in *a* to maintain sorted order.
   The parameters *lo* and *hi* may be used to specify a subset of the list
   which should be considered; by default the entire list is used.  If *x* is
   already present in *a*, the insertion point will be before (to the left of)
   any existing entries.  The return value is suitable for use as the first
   parameter to ``list.insert()`` assuming that *a* is already sorted.

   The returned insertion point *i* partitions the array *a* into two halves so
   that ``all(val < x for val in a[lo:i])`` for the left side and
   ``all(val >= x for val in a[i:hi])`` for the right side.

.. function:: bisect_right(a, x, lo=0, hi=len(a))
              bisect(a, x, lo=0, hi=len(a))

   Similar to :func:`bisect_left`, but returns an insertion point which comes
   after (to the right of) any existing entries of *x* in *a*.

   The returned insertion point *i* partitions the array *a* into two halves so
   that ``all(val <= x for val in a[lo:i])`` for the left side and
   ``all(val > x for val in a[i:hi])`` for the right side.

.. function:: insort_left(a, x, lo=0, hi=len(a))

   Insert *x* in *a* in sorted order.  This is equivalent to
   ``a.insert(bisect.bisect_left(a, x, lo, hi), x)`` assuming that *a* is
   already sorted.  Keep in mind that the O(log n) search is dominated by
   the slow O(n) insertion step.

.. function:: insort_right(a, x, lo=0, hi=len(a))
              insort(a, x, lo=0, hi=len(a))

   Similar to :func:`insort_left`, but inserting *x* in *a* after any existing
   entries of *x*.

.. seealso::

   `SortedCollection recipe
   <https://code.activestate.com/recipes/577197-sortedcollection/>`_ that uses
   bisect to build a full-featured collection class with straight-forward search
   methods and support for a key-function.  The keys are precomputed to save
   unnecessary calls to the key function during searches.


Searching Sorted Lists
----------------------

The above :func:`bisect` functions are useful for finding insertion points but
can be tricky or awkward to use for common searching tasks. The following five
functions show how to transform them into the standard lookups for sorted
lists::

    def index(a, x):
        'Locate the leftmost value exactly equal to x'
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return i
        raise ValueError

    def find_lt(a, x):
        'Find rightmost value less than x'
        i = bisect_left(a, x)
        if i:
            return a[i-1]
        raise ValueError

    def find_le(a, x):
        'Find rightmost value less than or equal to x'
        i = bisect_right(a, x)
        if i:
            return a[i-1]
        raise ValueError

    def find_gt(a, x):
        'Find leftmost value greater than x'
        i = bisect_right(a, x)
        if i != len(a):
            return a[i]
        raise ValueError

    def find_ge(a, x):
        'Find leftmost item greater than or equal to x'
        i = bisect_left(a, x)
        if i != len(a):
            return a[i]
        raise ValueError


Other Examples
--------------

.. _bisect-example:

The :func:`bisect` function can be useful for numeric table lookups. This
example uses :func:`bisect` to look up a letter grade for an exam score (say)
based on a set of ordered numeric breakpoints: 90 and up is an 'A', 80 to 89 is
a 'B', and so on::

   >>> def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
           i = bisect(breakpoints, score)
           return grades[i]

   >>> [grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
   ['F', 'A', 'C', 'C', 'B', 'A', 'A']

Unlike the :func:`sorted` function, it does not make sense for the :func:`bisect`
functions to have *key* or *reversed* arguments because that would lead to an
inefficient design (successive calls to bisect functions would not "remember"
all of the previous key lookups).

Instead, it is better to search a list of precomputed keys to find the index
of the record in question::

    >>> data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
    >>> data.sort(key=lambda r: r[1])
    >>> keys = [r[1] for r in data]         # precomputed list of keys
    >>> data[bisect_left(keys, 0)]
    ('black', 0)
    >>> data[bisect_left(keys, 1)]
    ('blue', 1)
    >>> data[bisect_left(keys, 5)]
    ('red', 5)
    >>> data[bisect_left(keys, 8)]
    ('yellow', 8)

PK	%�\Je���#html/_sources/library/bsddb.rst.txtnu�[���
:mod:`bsddb` --- Interface to Berkeley DB library
=================================================

.. module:: bsddb
   :synopsis: Interface to Berkeley DB database library
.. sectionauthor:: Skip Montanaro <skip@pobox.com>

.. deprecated:: 2.6
    The :mod:`bsddb` module has been removed in Python 3.


The :mod:`bsddb` module provides an interface to the Berkeley DB library.  Users
can create hash, btree or record based library files using the appropriate open
call. Bsddb objects behave generally like dictionaries.  Keys and values must be
strings, however, so to use other objects as keys or to store other kinds of
objects the user must serialize them somehow, typically using
:func:`marshal.dumps` or  :func:`pickle.dumps`.

The :mod:`bsddb` module requires a Berkeley DB library version from 4.0 thru
4.7.


.. seealso::

   http://www.jcea.es/programacion/pybsddb.htm
      The website with documentation for the :mod:`bsddb.db` Python Berkeley DB
      interface that closely mirrors the object oriented interface provided in
      Berkeley DB 4.x itself.

   http://www.oracle.com/database/berkeley-db/
      The Berkeley DB library.

A more modern DB, DBEnv and DBSequence object interface is available in the
:mod:`bsddb.db` module which closely matches the Berkeley DB C API documented at
the above URLs.  Additional features provided by the :mod:`bsddb.db` API include
fine tuning, transactions, logging, and multiprocess concurrent database access.

The following is a description of the legacy :mod:`bsddb` interface compatible
with the old Python bsddb module.  Starting in Python 2.5 this interface should
be safe for multithreaded access.  The :mod:`bsddb.db` API is recommended for
threading users as it provides better control.

The :mod:`bsddb` module defines the following functions that create objects that
access the appropriate type of Berkeley DB file.  The first two arguments of
each function are the same.  For ease of portability, only the first two
arguments should be used in most instances.


.. function:: hashopen(filename[, flag[, mode[, pgsize[, ffactor[, nelem[, cachesize[, lorder[, hflags]]]]]]]])

   Open the hash format file named *filename*.  Files never intended to be
   preserved on disk may be created by passing ``None`` as the  *filename*.  The
   optional *flag* identifies the mode used to open the file.  It may be ``'r'``
   (read only), ``'w'`` (read-write), ``'c'`` (read-write - create if necessary;
   the default) or ``'n'`` (read-write - truncate to zero length).  The other
   arguments are rarely used and are just passed to the low-level :c:func:`dbopen`
   function.  Consult the Berkeley DB documentation for their use and
   interpretation.


.. function:: btopen(filename[, flag[, mode[, btflags[, cachesize[, maxkeypage[, minkeypage[, pgsize[, lorder]]]]]]]])

   Open the btree format file named *filename*.  Files never intended  to be
   preserved on disk may be created by passing ``None`` as the  *filename*.  The
   optional *flag* identifies the mode used to open the file.  It may be ``'r'``
   (read only), ``'w'`` (read-write), ``'c'`` (read-write - create if necessary;
   the default) or ``'n'`` (read-write - truncate to zero length).  The other
   arguments are rarely used and are just passed to the low-level dbopen function.
   Consult the Berkeley DB documentation for their use and interpretation.


.. function:: rnopen(filename[, flag[, mode[, rnflags[, cachesize[, pgsize[, lorder[, rlen[, delim[, source[, pad]]]]]]]]]])

   Open a DB record format file named *filename*.  Files never intended  to be
   preserved on disk may be created by passing ``None`` as the  *filename*.  The
   optional *flag* identifies the mode used to open the file.  It may be ``'r'``
   (read only), ``'w'`` (read-write), ``'c'`` (read-write - create if necessary;
   the default) or ``'n'`` (read-write - truncate to zero length).  The other
   arguments are rarely used and are just passed to the low-level dbopen function.
   Consult the Berkeley DB documentation for their use and interpretation.

.. note::

   Beginning in 2.3 some Unix versions of Python may have a :mod:`bsddb185` module.
   This is present *only* to allow backwards compatibility with systems which ship
   with the old Berkeley DB 1.85 database library.  The :mod:`bsddb185` module
   should never be used directly in new code. The module has been removed in
   Python 3.  If you find you still need it look in PyPI.


.. seealso::

   Module :mod:`dbhash`
      DBM-style interface to the :mod:`bsddb`


.. _bsddb-objects:

Hash, BTree and Record Objects
------------------------------

Once instantiated, hash, btree and record objects support the same methods as
dictionaries.  In addition, they support the methods listed below.

.. versionchanged:: 2.3.1
   Added dictionary methods.


.. method:: bsddbobject.close()

   Close the underlying file.  The object can no longer be accessed.  Since there
   is no open :meth:`open` method for these objects, to open the file again a new
   :mod:`bsddb` module open function must be called.


.. method:: bsddbobject.keys()

   Return the list of keys contained in the DB file.  The order of the list is
   unspecified and should not be relied on.  In particular, the order of the list
   returned is different for different file formats.


.. method:: bsddbobject.has_key(key)

   Return ``1`` if the DB file contains the argument as a key.


.. method:: bsddbobject.set_location(key)

   Set the cursor to the item indicated by *key* and return a tuple containing the
   key and its value.  For binary tree databases (opened using :func:`btopen`), if
   *key* does not actually exist in the database, the cursor will point to the next
   item in sorted order and return that key and value.  For other databases,
   :exc:`KeyError` will be raised if *key* is not found in the database.


.. method:: bsddbobject.first()

   Set the cursor to the first item in the DB file and return it.  The order of
   keys in the file is unspecified, except in the case of B-Tree databases. This
   method raises :exc:`bsddb.error` if the database is empty.


.. method:: bsddbobject.next()

   Set the cursor to the next item in the DB file and return it.  The order of
   keys in the file is unspecified, except in the case of B-Tree databases.


.. method:: bsddbobject.previous()

   Set the cursor to the previous item in the DB file and return it.  The order of
   keys in the file is unspecified, except in the case of B-Tree databases.  This
   is not supported on hashtable databases (those opened with :func:`hashopen`).


.. method:: bsddbobject.last()

   Set the cursor to the last item in the DB file and return it.  The order of keys
   in the file is unspecified.  This is not supported on hashtable databases (those
   opened with :func:`hashopen`). This method raises :exc:`bsddb.error` if the
   database is empty.


.. method:: bsddbobject.sync()

   Synchronize the database on disk.

Example::

   >>> import bsddb
   >>> db = bsddb.btopen('spam.db', 'c')
   >>> for i in range(10): db['%d'%i] = '%d'% (i*i)
   ...
   >>> db['3']
   '9'
   >>> db.keys()
   ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
   >>> db.first()
   ('0', '0')
   >>> db.next()
   ('1', '1')
   >>> db.last()
   ('9', '81')
   >>> db.set_location('2')
   ('2', '4')
   >>> db.previous()
   ('1', '1')
   >>> for k, v in db.iteritems():
   ...     print k, v
   0 0
   1 1
   2 4
   3 9
   4 16
   5 25
   6 36
   7 49
   8 64
   9 81
   >>> '8' in db
   True
   >>> db.sync()
   0

PK	%�\�v����!html/_sources/library/bz2.rst.txtnu�[���
:mod:`bz2` --- Compression compatible with :program:`bzip2`
===========================================================

.. module:: bz2
   :synopsis: Interface to compression and decompression routines compatible with bzip2.
.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>


.. versionadded:: 2.3

This module provides a comprehensive interface for the bz2 compression library.
It implements a complete file interface, one-shot (de)compression functions, and
types for sequential (de)compression.

Here is a summary of the features offered by the bz2 module:

* :class:`BZ2File` class implements a complete file interface, including
  :meth:`~BZ2File.readline`, :meth:`~BZ2File.readlines`,
  :meth:`~BZ2File.writelines`, :meth:`~BZ2File.seek`, etc;

* :class:`BZ2File` class implements emulated :meth:`~BZ2File.seek` support;

* :class:`BZ2File` class implements universal newline support;

* :class:`BZ2File` class offers an optimized line iteration using the readahead
  algorithm borrowed from file objects;

* Sequential (de)compression supported by :class:`BZ2Compressor` and
  :class:`BZ2Decompressor` classes;

* One-shot (de)compression supported by :func:`compress` and :func:`decompress`
  functions;

* Thread safety uses individual locking mechanism.

.. note::
   Handling of multi-stream bzip2 files is not supported.  Modules such as
   `bz2file <https://github.com/nvawda/bz2file>`_ let you overcome this.


(De)compression of files
------------------------

Handling of compressed files is offered by the :class:`BZ2File` class.


.. index::
   single: universal newlines; bz2.BZ2File class

.. class:: BZ2File(filename[, mode[, buffering[, compresslevel]]])

   Open a bz2 file. Mode can be either ``'r'`` or ``'w'``, for reading (default)
   or writing. When opened for writing, the file will be created if it doesn't
   exist, and truncated otherwise. If *buffering* is given, ``0`` means
   unbuffered, and larger numbers specify the buffer size; the default is
   ``0``. If *compresslevel* is given, it must be a number between ``1`` and
   ``9``; the default is ``9``. Add a ``'U'`` to mode to open the file for input
   in :term:`universal newlines` mode. Any line ending in the input file will be
   seen as a ``'\n'`` in Python.  Also, a file so opened gains the attribute
   :attr:`newlines`; the value for this attribute is one of ``None`` (no newline
   read yet), ``'\r'``, ``'\n'``, ``'\r\n'`` or a tuple containing all the
   newline types seen. Universal newlines are available only when
   reading. Instances support iteration in the same way as normal :class:`file`
   instances.

   :class:`BZ2File` supports the :keyword:`with` statement.

   .. versionchanged:: 2.7
      Support for the :keyword:`with` statement was added.


   .. note::

      This class does not support input files containing multiple streams (such
      as those produced by the :program:`pbzip2` tool). When reading such an
      input file, only the first stream will be accessible. If you require
      support for multi-stream files, consider using the third-party
      :mod:`bz2file` module (available from
      `PyPI <https://pypi.org/project/bz2file>`_). This module provides a
      backport of Python 3.3's :class:`BZ2File` class, which does support
      multi-stream files.


   .. method:: close()

      Close the file. Sets data attribute :attr:`closed` to true. A closed file
      cannot be used for further I/O operations. :meth:`close` may be called
      more than once without error.


   .. method:: read([size])

      Read at most *size* uncompressed bytes, returned as a string. If the
      *size* argument is negative or omitted, read until EOF is reached.


   .. method:: readline([size])

      Return the next line from the file, as a string, retaining newline. A
      non-negative *size* argument limits the maximum number of bytes to return
      (an incomplete line may be returned then). Return an empty string at EOF.


   .. method:: readlines([size])

      Return a list of lines read. The optional *size* argument, if given, is an
      approximate bound on the total number of bytes in the lines returned.


   .. method:: xreadlines()

      For backward compatibility. :class:`BZ2File` objects now include the
      performance optimizations previously implemented in the :mod:`xreadlines`
      module.

      .. deprecated:: 2.3
         This exists only for compatibility with the method by this name on
         :class:`file` objects, which is deprecated.  Use ``for line in file``
         instead.


   .. method:: seek(offset[, whence])

      Move to new file position. Argument *offset* is a byte count. Optional
      argument *whence* defaults to ``os.SEEK_SET`` or ``0`` (offset from start
      of file; offset should be ``>= 0``); other values are ``os.SEEK_CUR`` or
      ``1`` (move relative to current position; offset can be positive or
      negative), and ``os.SEEK_END`` or ``2`` (move relative to end of file;
      offset is usually negative, although many platforms allow seeking beyond
      the end of a file).

      Note that seeking of bz2 files is emulated, and depending on the
      parameters the operation may be extremely slow.


   .. method:: tell()

      Return the current file position, an integer (may be a long integer).


   .. method:: write(data)

      Write string *data* to file. Note that due to buffering, :meth:`close` may
      be needed before the file on disk reflects the data written.


   .. method:: writelines(sequence_of_strings)

      Write the sequence of strings to the file. Note that newlines are not
      added. The sequence can be any iterable object producing strings. This is
      equivalent to calling write() for each string.


Sequential (de)compression
--------------------------

Sequential compression and decompression is done using the classes
:class:`BZ2Compressor` and :class:`BZ2Decompressor`.


.. class:: BZ2Compressor([compresslevel])

   Create a new compressor object. This object may be used to compress data
   sequentially. If you want to compress data in one shot, use the
   :func:`compress` function instead. The *compresslevel* parameter, if given,
   must be a number between ``1`` and ``9``; the default is ``9``.


   .. method:: compress(data)

      Provide more data to the compressor object. It will return chunks of
      compressed data whenever possible. When you've finished providing data to
      compress, call the :meth:`flush` method to finish the compression process,
      and return what is left in internal buffers.


   .. method:: flush()

      Finish the compression process and return what is left in internal
      buffers. You must not use the compressor object after calling this method.


.. class:: BZ2Decompressor()

   Create a new decompressor object. This object may be used to decompress data
   sequentially. If you want to decompress data in one shot, use the
   :func:`decompress` function instead.


   .. method:: decompress(data)

      Provide more data to the decompressor object. It will return chunks of
      decompressed data whenever possible. If you try to decompress data after
      the end of stream is found, :exc:`EOFError` will be raised. If any data
      was found after the end of stream, it'll be ignored and saved in
      :attr:`unused_data` attribute.


One-shot (de)compression
------------------------

One-shot compression and decompression is provided through the :func:`compress`
and :func:`decompress` functions.


.. function:: compress(data[, compresslevel])

   Compress *data* in one shot. If you want to compress data sequentially, use
   an instance of :class:`BZ2Compressor` instead. The *compresslevel* parameter,
   if given, must be a number between ``1`` and ``9``; the default is ``9``.


.. function:: decompress(data)

   Decompress *data* in one shot. If you want to decompress data sequentially,
   use an instance of :class:`BZ2Decompressor` instead.

PK	%�\_z��,,&html/_sources/library/calendar.rst.txtnu�[���:mod:`calendar` --- General calendar-related functions
======================================================

.. module:: calendar
   :synopsis: Functions for working with calendars, including some emulation of the Unix cal
              program.
.. sectionauthor:: Drew Csillag <drew_csillag@geocities.com>

**Source code:** :source:`Lib/calendar.py`

--------------

This module allows you to output calendars like the Unix :program:`cal` program,
and provides additional useful functions related to the calendar. By default,
these calendars have Monday as the first day of the week, and Sunday as the last
(the European convention). Use :func:`setfirstweekday` to set the first day of
the week to Sunday (6) or to any other weekday.  Parameters that specify dates
are given as integers. For related
functionality, see also the :mod:`datetime` and :mod:`time` modules.

Most of these functions and classes rely on the :mod:`datetime` module which
uses an idealized calendar, the current Gregorian calendar indefinitely extended
in both directions.  This matches the definition of the "proleptic Gregorian"
calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
it's the base calendar for all computations.


.. class:: Calendar([firstweekday])

   Creates a :class:`Calendar` object. *firstweekday* is an integer specifying the
   first day of the week. ``0`` is Monday (the default), ``6`` is Sunday.

   A :class:`Calendar` object provides several methods that can be used for
   preparing the calendar data for formatting. This class doesn't do any formatting
   itself. This is the job of subclasses.

   .. versionadded:: 2.5

   :class:`Calendar` instances have the following methods:


   .. method:: iterweekdays()

      Return an iterator for the week day numbers that will be used for one
      week.  The first value from the iterator will be the same as the value of
      the :attr:`firstweekday` property.


   .. method:: itermonthdates(year, month)

      Return an iterator for the month *month* (1--12) in the year *year*. This
      iterator will return all days (as :class:`datetime.date` objects) for the
      month and all days before the start of the month or after the end of the
      month that are required to get a complete week.


   .. method:: itermonthdays2(year, month)

      Return an iterator for the month *month* in the year *year* similar to
      :meth:`itermonthdates`. Days returned will be tuples consisting of a day
      number and a week day number.


   .. method:: itermonthdays(year, month)

      Return an iterator for the month *month* in the year *year* similar to
      :meth:`itermonthdates`. Days returned will simply be day numbers.


   .. method:: monthdatescalendar(year, month)

      Return a list of the weeks in the month *month* of the *year* as full
      weeks.  Weeks are lists of seven :class:`datetime.date` objects.


   .. method:: monthdays2calendar(year, month)

      Return a list of the weeks in the month *month* of the *year* as full
      weeks.  Weeks are lists of seven tuples of day numbers and weekday
      numbers.


   .. method:: monthdayscalendar(year, month)

      Return a list of the weeks in the month *month* of the *year* as full
      weeks.  Weeks are lists of seven day numbers.


   .. method:: yeardatescalendar(year[, width])

      Return the data for the specified year ready for formatting. The return
      value is a list of month rows. Each month row contains up to *width*
      months (defaulting to 3). Each month contains between 4 and 6 weeks and
      each week contains 1--7 days. Days are :class:`datetime.date` objects.


   .. method:: yeardays2calendar(year[, width])

      Return the data for the specified year ready for formatting (similar to
      :meth:`yeardatescalendar`). Entries in the week lists are tuples of day
      numbers and weekday numbers. Day numbers outside this month are zero.


   .. method:: yeardayscalendar(year[, width])

      Return the data for the specified year ready for formatting (similar to
      :meth:`yeardatescalendar`). Entries in the week lists are day numbers. Day
      numbers outside this month are zero.


.. class:: TextCalendar([firstweekday])

   This class can be used to generate plain text calendars.

   .. versionadded:: 2.5

   :class:`TextCalendar` instances have the following methods:


   .. method:: formatmonth(theyear, themonth[, w[, l]])

      Return a month's calendar in a multi-line string. If *w* is provided, it
      specifies the width of the date columns, which are centered. If *l* is
      given, it specifies the number of lines that each week will use. Depends
      on the first weekday as specified in the constructor or set by the
      :meth:`setfirstweekday` method.


   .. method:: prmonth(theyear, themonth[, w[, l]])

      Print a month's calendar as returned by :meth:`formatmonth`.


   .. method:: formatyear(theyear[, w[, l[, c[, m]]]])

      Return a *m*-column calendar for an entire year as a multi-line string.
      Optional parameters *w*, *l*, and *c* are for date column width, lines per
      week, and number of spaces between month columns, respectively. Depends on
      the first weekday as specified in the constructor or set by the
      :meth:`setfirstweekday` method.  The earliest year for which a calendar
      can be generated is platform-dependent.


   .. method:: pryear(theyear[, w[, l[, c[, m]]]])

      Print the calendar for an entire year as returned by :meth:`formatyear`.


.. class:: HTMLCalendar([firstweekday])

   This class can be used to generate HTML calendars.

   .. versionadded:: 2.5

   :class:`HTMLCalendar` instances have the following methods:


   .. method:: formatmonth(theyear, themonth[, withyear])

      Return a month's calendar as an HTML table. If *withyear* is true the year
      will be included in the header, otherwise just the month name will be
      used.


   .. method:: formatyear(theyear[, width])

      Return a year's calendar as an HTML table. *width* (defaulting to 3)
      specifies the number of months per row.


   .. method:: formatyearpage(theyear[, width[, css[, encoding]]])

      Return a year's calendar as a complete HTML page. *width* (defaulting to
      3) specifies the number of months per row. *css* is the name for the
      cascading style sheet to be used. :const:`None` can be passed if no style
      sheet should be used. *encoding* specifies the encoding to be used for the
      output (defaulting to the system default encoding).


.. class:: LocaleTextCalendar([firstweekday[, locale]])

   This subclass of :class:`TextCalendar` can be passed a locale name in the
   constructor and will return month and weekday names in the specified locale.
   If this locale includes an encoding all strings containing month and weekday
   names will be returned as unicode.

   .. versionadded:: 2.5


.. class:: LocaleHTMLCalendar([firstweekday[, locale]])

   This subclass of :class:`HTMLCalendar` can be passed a locale name in the
   constructor and will return month and weekday names in the specified
   locale. If this locale includes an encoding all strings containing month and
   weekday names will be returned as unicode.

   .. versionadded:: 2.5

.. note::

   The :meth:`formatweekday` and :meth:`formatmonthname` methods of these two
   classes temporarily change the current locale to the given *locale*.  Because
   the current locale is a process-wide setting, they are not thread-safe.


For simple text calendars this module provides the following functions.


.. function:: setfirstweekday(weekday)

   Sets the weekday (``0`` is Monday, ``6`` is Sunday) to start each week. The
   values :const:`MONDAY`, :const:`TUESDAY`, :const:`WEDNESDAY`, :const:`THURSDAY`,
   :const:`FRIDAY`, :const:`SATURDAY`, and :const:`SUNDAY` are provided for
   convenience. For example, to set the first weekday to Sunday::

      import calendar
      calendar.setfirstweekday(calendar.SUNDAY)

   .. versionadded:: 2.0


.. function:: firstweekday()

   Returns the current setting for the weekday to start each week.

   .. versionadded:: 2.0


.. function:: isleap(year)

   Returns :const:`True` if *year* is a leap year, otherwise :const:`False`.


.. function:: leapdays(y1, y2)

   Returns the number of leap years in the range from *y1* to *y2* (exclusive),
   where *y1* and *y2* are years.

   .. versionchanged:: 2.0
      This function didn't work for ranges spanning a century change in Python
      1.5.2.


.. function:: weekday(year, month, day)

   Returns the day of the week (``0`` is Monday) for *year* (``1970``--...),
   *month* (``1``--``12``), *day* (``1``--``31``).


.. function:: weekheader(n)

   Return a header containing abbreviated weekday names. *n* specifies the width in
   characters for one weekday.


.. function:: monthrange(year, month)

   Returns weekday of first day of the month and number of days in month,  for the
   specified *year* and *month*.


.. function:: monthcalendar(year, month)

   Returns a matrix representing a month's calendar.  Each row represents a week;
   days outside of the month a represented by zeros. Each week begins with Monday
   unless set by :func:`setfirstweekday`.


.. function:: prmonth(theyear, themonth[, w[, l]])

   Prints a month's calendar as returned by :func:`month`.


.. function:: month(theyear, themonth[, w[, l]])

   Returns a month's calendar in a multi-line string using the :meth:`formatmonth`
   of the :class:`TextCalendar` class.

   .. versionadded:: 2.0


.. function:: prcal(year[, w[, l[c]]])

   Prints the calendar for an entire year as returned by  :func:`calendar`.


.. function:: calendar(year[, w[, l[c]]])

   Returns a 3-column calendar for an entire year as a multi-line string using the
   :meth:`formatyear` of the :class:`TextCalendar` class.

   .. versionadded:: 2.0


.. function:: timegm(tuple)

   An unrelated but handy function that takes a time tuple such as returned by
   the :func:`~time.gmtime` function in the :mod:`time` module, and returns the
   corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX
   encoding.  In fact, :func:`time.gmtime` and :func:`timegm` are each others'
   inverse.

   .. versionadded:: 2.0

The :mod:`calendar` module exports the following data attributes:


.. data:: day_name

   An array that represents the days of the week in the current locale.


.. data:: day_abbr

   An array that represents the abbreviated days of the week in the current locale.


.. data:: month_name

   An array that represents the months of the year in the current locale.  This
   follows normal convention of January being month number 1, so it has a length of
   13 and  ``month_name[0]`` is the empty string.


.. data:: month_abbr

   An array that represents the abbreviated months of the year in the current
   locale.  This follows normal convention of January being month number 1, so it
   has a length of 13 and  ``month_abbr[0]`` is the empty string.


.. seealso::

   Module :mod:`datetime`
      Object-oriented interface to dates and times with similar functionality to the
      :mod:`time` module.

   Module :mod:`time`
      Low-level time related functions.

PK	%�\�n�T>T>$html/_sources/library/carbon.rst.txtnu�[���
.. _toolbox:

**********************
Mac OS Toolbox Modules
**********************

These are a set of modules that provide interfaces to various legacy Mac OS toolboxes.
If applicable the module will define a number of Python objects for the various
structures declared by the toolbox, and operations will be implemented as
methods of the object.  Other operations will be implemented as functions in the
module.  Not all operations possible in C will also be possible in Python
(callbacks are often a problem), and parameters will occasionally be different
in Python (input and output buffers, especially).  All methods and functions
have a :attr:`__doc__` string describing their arguments and return values, and
for additional description you are referred to `Inside Macintosh
<http://developer.apple.com/legacy/mac/library/#documentation/macos8/mac8.html>`_ or similar works.

These modules all live in a package called :mod:`Carbon`. Despite that name they
are not all part of the Carbon framework: CF is really in the CoreFoundation
framework and Qt is in the QuickTime framework. The normal use pattern is ::

   from Carbon import AE

.. note::

   Most of the OS X APIs that these modules use are deprecated or removed
   in recent versions of OS X.  Many are not available when Python is
   executing in 64-bit mode.  The Carbon modules have been removed in
   Python 3.  You should avoid using them in Python 2.


:mod:`Carbon.AE` --- Apple Events
=================================

.. module:: Carbon.AE
   :platform: Mac
   :synopsis: Interface to the Apple Events toolbox.
   :deprecated:



:mod:`Carbon.AH` --- Apple Help
===============================

.. module:: Carbon.AH
   :platform: Mac
   :synopsis: Interface to the Apple Help manager.
   :deprecated:



:mod:`Carbon.App` --- Appearance Manager
========================================

.. module:: Carbon.App
   :platform: Mac
   :synopsis: Interface to the Appearance Manager.
   :deprecated:

:mod:`Carbon.Appearance` --- Appearance Manager constants
=========================================================

.. module:: Carbon.Appearance
   :platform: Mac
   :synopsis: Constant definitions for the interface to the Appearance Manager.
   :deprecated:



:mod:`Carbon.CF` --- Core Foundation
====================================

.. module:: Carbon.CF
   :platform: Mac
   :synopsis: Interface to the Core Foundation.
   :deprecated:


The ``CFBase``, ``CFArray``, ``CFData``, ``CFDictionary``, ``CFString`` and
``CFURL`` objects are supported, some only partially.


:mod:`Carbon.CG` --- Core Graphics
==================================

.. module:: Carbon.CG
   :platform: Mac
   :synopsis: Interface to Core Graphics.
   :deprecated:



:mod:`Carbon.CarbonEvt` --- Carbon Event Manager
================================================

.. module:: Carbon.CarbonEvt
   :platform: Mac
   :synopsis: Interface to the Carbon Event Manager.
   :deprecated:

:mod:`Carbon.CarbonEvents` --- Carbon Event Manager constants
=============================================================

.. module:: Carbon.CarbonEvents
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon Event Manager.
   :deprecated:



:mod:`Carbon.Cm` --- Component Manager
======================================

.. module:: Carbon.Cm
   :platform: Mac
   :synopsis: Interface to the Component Manager.
   :deprecated:

:mod:`Carbon.Components` --- Component Manager constants
========================================================

.. module:: Carbon.Components
   :platform: Mac
   :synopsis: Constants for the interface to the Component Manager.
   :deprecated:


:mod:`Carbon.ControlAccessor` --- Control Manager accssors
===========================================================

.. module:: Carbon.ControlAccessor
   :platform: Mac
   :synopsis: Accessor functions for the interface to the Control Manager.
   :deprecated:

:mod:`Carbon.Controls` --- Control Manager constants
====================================================

.. module:: Carbon.Controls
   :platform: Mac
   :synopsis: Constants for the interface to the Control Manager.
   :deprecated:

:mod:`Carbon.CoreFounation` --- CoreFounation constants
=======================================================

.. module:: Carbon.CoreFounation
   :platform: Mac
   :synopsis: Constants for the interface to CoreFoundation.
   :deprecated:

:mod:`Carbon.CoreGraphics` --- CoreGraphics constants
=======================================================

.. module:: Carbon.CoreGraphics
   :platform: Mac
   :synopsis: Constants for the interface to CoreGraphics.
   :deprecated:

:mod:`Carbon.Ctl` --- Control Manager
=====================================

.. module:: Carbon.Ctl
   :platform: Mac
   :synopsis: Interface to the Control Manager.
   :deprecated:

:mod:`Carbon.Dialogs` --- Dialog Manager constants
==================================================

.. module:: Carbon.Dialogs
   :platform: Mac
   :synopsis: Constants for the interface to the Dialog Manager.
   :deprecated:

:mod:`Carbon.Dlg` --- Dialog Manager
====================================

.. module:: Carbon.Dlg
   :platform: Mac
   :synopsis: Interface to the Dialog Manager.
   :deprecated:

:mod:`Carbon.Drag` --- Drag and Drop Manager
=============================================

.. module:: Carbon.Drag
   :platform: Mac
   :synopsis: Interface to the Drag and Drop Manager.
   :deprecated:

:mod:`Carbon.Dragconst` --- Drag and Drop Manager constants
===========================================================

.. module:: Carbon.Dragconst
   :platform: Mac
   :synopsis: Constants for the interface to the Drag and Drop Manager.
   :deprecated:

:mod:`Carbon.Events` --- Event Manager constants
================================================

.. module:: Carbon.Events
   :platform: Mac
   :synopsis: Constants for the interface to the classic Event Manager.
   :deprecated:

:mod:`Carbon.Evt` --- Event Manager
===================================

.. module:: Carbon.Evt
   :platform: Mac
   :synopsis: Interface to the classic Event Manager.
   :deprecated:

:mod:`Carbon.File` --- File Manager
===================================

.. module:: Carbon.File
   :platform: Mac
   :synopsis: Interface to the File Manager.
   :deprecated:

:mod:`Carbon.Files` --- File Manager constants
==============================================

.. module:: Carbon.Files
   :platform: Mac
   :synopsis: Constants for the interface to the File Manager.
   :deprecated:


:mod:`Carbon.Fm` --- Font Manager
=================================

.. module:: Carbon.Fm
   :platform: Mac
   :synopsis: Interface to the Font Manager.
   :deprecated:



:mod:`Carbon.Folder` --- Folder Manager
=======================================

.. module:: Carbon.Folder
   :platform: Mac
   :synopsis: Interface to the Folder Manager.
   :deprecated:

:mod:`Carbon.Folders` --- Folder Manager constants
==================================================

.. module:: Carbon.Folders
   :platform: Mac
   :synopsis: Constants for the interface to the Folder Manager.
   :deprecated:


:mod:`Carbon.Fonts` --- Font Manager constants
==================================================

.. module:: Carbon.Fonts
   :platform: Mac
   :synopsis: Constants for the interface to the Font Manager.
   :deprecated:



:mod:`Carbon.Help` --- Help Manager
===================================

.. module:: Carbon.Help
   :platform: Mac
   :synopsis: Interface to the Carbon Help Manager.
   :deprecated:

:mod:`Carbon.IBCarbon` --- Carbon InterfaceBuilder
==================================================

.. module:: Carbon.IBCarbon
   :platform: Mac
   :synopsis: Interface to the Carbon InterfaceBuilder support libraries.
   :deprecated:

:mod:`Carbon.IBCarbonRuntime` --- Carbon InterfaceBuilder constants
===================================================================

.. module:: Carbon.IBCarbonRuntime
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon InterfaceBuilder support libraries.
   :deprecated:

:mod:`Carbon.Icn` --- Carbon Icon Manager
=========================================

.. module:: Carbon.Icns
   :platform: Mac
   :synopsis: Interface to the Carbon Icon Manager
   :deprecated:

:mod:`Carbon.Icons` --- Carbon Icon Manager constants
=====================================================

.. module:: Carbon.Icons
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon Icon Manager
   :deprecated:

:mod:`Carbon.Launch` --- Carbon Launch Services
===============================================

.. module:: Carbon.Launch
   :platform: Mac
   :synopsis: Interface to the Carbon Launch Services.
   :deprecated:

:mod:`Carbon.LaunchServices` --- Carbon Launch Services constants
=================================================================

.. module:: Carbon.LaunchServices
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon Launch Services.
   :deprecated:


:mod:`Carbon.List` --- List Manager
===================================

.. module:: Carbon.List
   :platform: Mac
   :synopsis: Interface to the List Manager.
   :deprecated:



:mod:`Carbon.Lists` --- List Manager constants
==============================================

.. module:: Carbon.Lists
   :platform: Mac
   :synopsis: Constants for the interface to the List Manager.
   :deprecated:

:mod:`Carbon.MacHelp` --- Help Manager constants
================================================

.. module:: Carbon.MacHelp
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon Help Manager.
   :deprecated:

:mod:`Carbon.MediaDescr` --- Parsers and generators for Quicktime Media descriptors
===================================================================================

.. module:: Carbon.MediaDescr
   :platform: Mac
   :synopsis: Parsers and generators for Quicktime Media descriptors
   :deprecated:


:mod:`Carbon.Menu` --- Menu Manager
===================================

.. module:: Carbon.Menu
   :platform: Mac
   :synopsis: Interface to the Menu Manager.
   :deprecated:

:mod:`Carbon.Menus` --- Menu Manager constants
==============================================

.. module:: Carbon.Menus
   :platform: Mac
   :synopsis: Constants for the interface to the Menu Manager.
   :deprecated:


:mod:`Carbon.Mlte` --- MultiLingual Text Editor
===============================================

.. module:: Carbon.Mlte
   :platform: Mac
   :synopsis: Interface to the MultiLingual Text Editor.
   :deprecated:

:mod:`Carbon.OSA` --- Carbon OSA Interface
==========================================

.. module:: Carbon.OSA
   :platform: Mac
   :synopsis: Interface to the Carbon OSA Library.
   :deprecated:

:mod:`Carbon.OSAconst` --- Carbon OSA Interface constants
=========================================================

.. module:: Carbon.OSAconst
   :platform: Mac
   :synopsis: Constants for the interface to the Carbon OSA Library.
   :deprecated:

:mod:`Carbon.QDOffscreen` --- QuickDraw Offscreen constants
===========================================================

.. module:: Carbon.QDOffscreen
   :platform: Mac
   :synopsis: Constants for the interface to the QuickDraw Offscreen APIs.
   :deprecated:


:mod:`Carbon.Qd` --- QuickDraw
==============================

.. module:: Carbon.Qd
   :platform: Mac
   :synopsis: Interface to the QuickDraw toolbox.
   :deprecated:



:mod:`Carbon.Qdoffs` --- QuickDraw Offscreen
============================================

.. module:: Carbon.Qdoffs
   :platform: Mac
   :synopsis: Interface to the QuickDraw Offscreen APIs.
   :deprecated:



:mod:`Carbon.Qt` --- QuickTime
==============================

.. module:: Carbon.Qt
   :platform: Mac
   :synopsis: Interface to the QuickTime toolbox.
   :deprecated:

:mod:`Carbon.QuickDraw` --- QuickDraw constants
===============================================

.. module:: Carbon.QuickDraw
   :platform: Mac
   :synopsis: Constants for the interface to the QuickDraw toolbox.
   :deprecated:

:mod:`Carbon.QuickTime` --- QuickTime constants
===============================================

.. module:: Carbon.QuickTime
   :platform: Mac
   :synopsis: Constants for the interface to the QuickTime toolbox.
   :deprecated:


:mod:`Carbon.Res` --- Resource Manager and Handles
==================================================

.. module:: Carbon.Res
   :platform: Mac
   :synopsis: Interface to the Resource Manager and Handles.
   :deprecated:

:mod:`Carbon.Resources` --- Resource Manager and Handles constants
==================================================================

.. module:: Carbon.Resources
   :platform: Mac
   :synopsis: Constants for the interface to the Resource Manager and Handles.
   :deprecated:


:mod:`Carbon.Scrap` --- Scrap Manager
=====================================

.. module:: Carbon.Scrap
   :platform: Mac
   :synopsis: The Scrap Manager provides basic services for implementing cut & paste and
              clipboard operations.
   :deprecated:


This module is only fully available on Mac OS 9 and earlier under classic PPC
MacPython.  Very limited functionality is available under Carbon MacPython.

.. index:: single: Scrap Manager

The Scrap Manager supports the simplest form of cut & paste operations on the
Macintosh.  It can be use for both inter- and intra-application clipboard
operations.

The :mod:`Scrap` module provides low-level access to the functions of the Scrap
Manager.  It contains the following functions:


.. function:: InfoScrap()

   Return current information about the scrap.  The information is encoded as a
   tuple containing the fields ``(size, handle, count, state, path)``.

   +----------+---------------------------------------------+
   | Field    | Meaning                                     |
   +==========+=============================================+
   | *size*   | Size of the scrap in bytes.                 |
   +----------+---------------------------------------------+
   | *handle* | Resource object representing the scrap.     |
   +----------+---------------------------------------------+
   | *count*  | Serial number of the scrap contents.        |
   +----------+---------------------------------------------+
   | *state*  | Integer; positive if in memory, ``0`` if on |
   |          | disk, negative if uninitialized.            |
   +----------+---------------------------------------------+
   | *path*   | Filename of the scrap when stored on disk.  |
   +----------+---------------------------------------------+


.. seealso::

   `Scrap Manager <http://developer.apple.com/legacy/mac/library/documentation/mac/MoreToolbox/MoreToolbox-109.html>`_
      Apple's documentation for the Scrap Manager gives a lot of useful information
      about using the Scrap Manager in applications.



:mod:`Carbon.Snd` --- Sound Manager
===================================

.. module:: Carbon.Snd
   :platform: Mac
   :synopsis: Interface to the Sound Manager.
   :deprecated:

:mod:`Carbon.Sound` --- Sound Manager constants
===============================================

.. module:: Carbon.Sound
   :platform: Mac
   :synopsis: Constants for the interface to the Sound Manager.
   :deprecated:


:mod:`Carbon.TE` --- TextEdit
=============================

.. module:: Carbon.TE
   :platform: Mac
   :synopsis: Interface to TextEdit.
   :deprecated:

:mod:`Carbon.TextEdit` --- TextEdit constants
=============================================

.. module:: Carbon.TextEdit
   :platform: Mac
   :synopsis: Constants for the interface to TextEdit.
   :deprecated:



:mod:`Carbon.Win` --- Window Manager
====================================

.. module:: Carbon.Win
   :platform: Mac
   :synopsis: Interface to the Window Manager.
   :deprecated:

:mod:`Carbon.Windows` --- Window Manager constants
==================================================

.. module:: Carbon.Windows
   :platform: Mac
   :synopsis: Constants for the interface to the Window Manager.
   :deprecated:
PK	%�\?Ҿ��.�. html/_sources/library/cd.rst.txtnu�[���
:mod:`cd` --- CD-ROM access on SGI systems
==========================================

.. module:: cd
   :platform: IRIX
   :synopsis: Interface to the CD-ROM on Silicon Graphics systems.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`cd` module has been removed in Python 3.


This module provides an interface to the Silicon Graphics CD library. It is
available only on Silicon Graphics systems.

The way the library works is as follows.  A program opens the CD-ROM device with
:func:`.open` and creates a parser to parse the data from the CD with
:func:`createparser`.  The object returned by :func:`.open` can be used to read
data from the CD, but also to get status information for the CD-ROM device, and
to get information about the CD, such as the table of contents.  Data from the
CD is passed to the parser, which parses the frames, and calls any callback
functions that have previously been added.

An audio CD is divided into :dfn:`tracks` or :dfn:`programs` (the terms are used
interchangeably).  Tracks can be subdivided into :dfn:`indices`.  An audio CD
contains a :dfn:`table of contents` which gives the starts of the tracks on the
CD.  Index 0 is usually the pause before the start of a track.  The start of the
track as given by the table of contents is normally the start of index 1.

Positions on a CD can be represented in two ways.  Either a frame number or a
tuple of three values, minutes, seconds and frames.  Most functions use the
latter representation.  Positions can be both relative to the beginning of the
CD, and to the beginning of the track.

Module :mod:`cd` defines the following functions and constants:


.. function:: createparser()

   Create and return an opaque parser object.  The methods of the parser object are
   described below.


.. function:: msftoframe(minutes, seconds, frames)

   Converts a ``(minutes, seconds, frames)`` triple representing time in absolute
   time code into the corresponding CD frame number.


.. function:: open([device[, mode]])

   Open the CD-ROM device.  The return value is an opaque player object; methods of
   the player object are described below.  The device is the name of the SCSI
   device file, e.g. ``'/dev/scsi/sc0d4l0'``, or ``None``.  If omitted or ``None``,
   the hardware inventory is consulted to locate a CD-ROM drive.  The *mode*, if
   not omitted, should be the string ``'r'``.

The module defines the following variables:


.. exception:: error

   Exception raised on various errors.


.. data:: DATASIZE

   The size of one frame's worth of audio data.  This is the size of the audio data
   as passed to the callback of type ``audio``.


.. data:: BLOCKSIZE

   The size of one uninterpreted frame of audio data.

The following variables are states as returned by :func:`getstatus`:


.. data:: READY

   The drive is ready for operation loaded with an audio CD.


.. data:: NODISC

   The drive does not have a CD loaded.


.. data:: CDROM

   The drive is loaded with a CD-ROM.  Subsequent play or read operations will
   return I/O errors.


.. data:: ERROR

   An error occurred while trying to read the disc or its table of contents.


.. data:: PLAYING

   The drive is in CD player mode playing an audio CD through its audio jacks.


.. data:: PAUSED

   The drive is in CD layer mode with play paused.


.. data:: STILL

   The equivalent of :const:`PAUSED` on older (non 3301) model Toshiba CD-ROM
   drives.  Such drives have never been shipped by SGI.


.. data:: audio
          pnum
          index
          ptime
          atime
          catalog
          ident
          control

   Integer constants describing the various types of parser callbacks that can be
   set by the :meth:`addcallback` method of CD parser objects (see below).


.. _player-objects:

Player Objects
--------------

Player objects (returned by :func:`.open`) have the following methods:


.. method:: CD player.allowremoval()

   Unlocks the eject button on the CD-ROM drive permitting the user to eject the
   caddy if desired.


.. method:: CD player.bestreadsize()

   Returns the best value to use for the *num_frames* parameter of the
   :meth:`readda` method.  Best is defined as the value that permits a continuous
   flow of data from the CD-ROM drive.


.. method:: CD player.close()

   Frees the resources associated with the player object.  After calling
   :meth:`close`, the methods of the object should no longer be used.


.. method:: CD player.eject()

   Ejects the caddy from the CD-ROM drive.


.. method:: CD player.getstatus()

   Returns information pertaining to the current state of the CD-ROM drive.  The
   returned information is a tuple with the following values: *state*, *track*,
   *rtime*, *atime*, *ttime*, *first*, *last*, *scsi_audio*, *cur_block*. *rtime*
   is the time relative to the start of the current track; *atime* is the time
   relative to the beginning of the disc; *ttime* is the total time on the disc.
   For more information on the meaning of the values, see the man page
   :manpage:`CDgetstatus(3dm)`. The value of *state* is one of the following:
   :const:`ERROR`, :const:`NODISC`, :const:`READY`, :const:`PLAYING`,
   :const:`PAUSED`, :const:`STILL`, or :const:`CDROM`.


.. method:: CD player.gettrackinfo(track)

   Returns information about the specified track.  The returned information is a
   tuple consisting of two elements, the start time of the track and the duration
   of the track.


.. method:: CD player.msftoblock(min, sec, frame)

   Converts a minutes, seconds, frames triple representing a time in absolute time
   code into the corresponding logical block number for the given CD-ROM drive.
   You should use :func:`msftoframe` rather than :meth:`msftoblock` for comparing
   times.  The logical block number differs from the frame number by an offset
   required by certain CD-ROM drives.


.. method:: CD player.play(start, play)

   Starts playback of an audio CD in the CD-ROM drive at the specified track.  The
   audio output appears on the CD-ROM drive's headphone and audio jacks (if
   fitted).  Play stops at the end of the disc. *start* is the number of the track
   at which to start playing the CD; if *play* is 0, the CD will be set to an
   initial paused state.  The method :meth:`togglepause` can then be used to
   commence play.


.. method:: CD player.playabs(minutes, seconds, frames, play)

   Like :meth:`play`, except that the start is given in minutes, seconds, and
   frames instead of a track number.


.. method:: CD player.playtrack(start, play)

   Like :meth:`play`, except that playing stops at the end of the track.


.. method:: CD player.playtrackabs(track, minutes, seconds, frames, play)

   Like :meth:`play`, except that playing begins at the specified absolute time and
   ends at the end of the specified track.


.. method:: CD player.preventremoval()

   Locks the eject button on the CD-ROM drive thus preventing the user from
   arbitrarily ejecting the caddy.


.. method:: CD player.readda(num_frames)

   Reads the specified number of frames from an audio CD mounted in the CD-ROM
   drive.  The return value is a string representing the audio frames.  This string
   can be passed unaltered to the :meth:`parseframe` method of the parser object.


.. method:: CD player.seek(minutes, seconds, frames)

   Sets the pointer that indicates the starting point of the next read of digital
   audio data from a CD-ROM.  The pointer is set to an absolute time code location
   specified in *minutes*, *seconds*, and *frames*.  The return value is the
   logical block number to which the pointer has been set.


.. method:: CD player.seekblock(block)

   Sets the pointer that indicates the starting point of the next read of digital
   audio data from a CD-ROM.  The pointer is set to the specified logical block
   number.  The return value is the logical block number to which the pointer has
   been set.


.. method:: CD player.seektrack(track)

   Sets the pointer that indicates the starting point of the next read of digital
   audio data from a CD-ROM.  The pointer is set to the specified track.  The
   return value is the logical block number to which the pointer has been set.


.. method:: CD player.stop()

   Stops the current playing operation.


.. method:: CD player.togglepause()

   Pauses the CD if it is playing, and makes it play if it is paused.


.. _cd-parser-objects:

Parser Objects
--------------

Parser objects (returned by :func:`createparser`) have the following methods:


.. method:: CD parser.addcallback(type, func, arg)

   Adds a callback for the parser.  The parser has callbacks for eight different
   types of data in the digital audio data stream.  Constants for these types are
   defined at the :mod:`cd` module level (see above). The callback is called as
   follows: ``func(arg, type, data)``, where *arg* is the user supplied argument,
   *type* is the particular type of callback, and *data* is the data returned for
   this *type* of callback.  The type of the data depends on the *type* of callback
   as follows:

   +-------------+---------------------------------------------+
   | Type        | Value                                       |
   +=============+=============================================+
   | ``audio``   | String which can be passed unmodified to    |
   |             | :func:`al.writesamps`.                      |
   +-------------+---------------------------------------------+
   | ``pnum``    | Integer giving the program (track) number.  |
   +-------------+---------------------------------------------+
   | ``index``   | Integer giving the index number.            |
   +-------------+---------------------------------------------+
   | ``ptime``   | Tuple consisting of the program time in     |
   |             | minutes, seconds, and frames.               |
   +-------------+---------------------------------------------+
   | ``atime``   | Tuple consisting of the absolute time in    |
   |             | minutes, seconds, and frames.               |
   +-------------+---------------------------------------------+
   | ``catalog`` | String of 13 characters, giving the catalog |
   |             | number of the CD.                           |
   +-------------+---------------------------------------------+
   | ``ident``   | String of 12 characters, giving the ISRC    |
   |             | identification number of the recording.     |
   |             | The string consists of two characters       |
   |             | country code, three characters owner code,  |
   |             | two characters giving the year, and five    |
   |             | characters giving a serial number.          |
   +-------------+---------------------------------------------+
   | ``control`` | Integer giving the control bits from the CD |
   |             | subcode data                                |
   +-------------+---------------------------------------------+


.. method:: CD parser.deleteparser()

   Deletes the parser and frees the memory it was using.  The object should not be
   used after this call.  This call is done automatically when the last reference
   to the object is removed.


.. method:: CD parser.parseframe(frame)

   Parses one or more frames of digital audio data from a CD such as returned by
   :meth:`readda`.  It determines which subcodes are present in the data.  If these
   subcodes have changed since the last frame, then :meth:`parseframe` executes a
   callback of the appropriate type passing to it the subcode data found in the
   frame. Unlike the C function, more than one frame of digital audio data can be
   passed to this method.


.. method:: CD parser.removecallback(type)

   Removes the callback for the given *type*.


.. method:: CD parser.resetparser()

   Resets the fields of the parser used for tracking subcodes to an initial state.
   :meth:`resetparser` should be called after the disc has been changed.

PK	%�\=��EYEY!html/_sources/library/cgi.rst.txtnu�[���:mod:`cgi` --- Common Gateway Interface support
===============================================

.. module:: cgi
   :synopsis: Helpers for running Python scripts via the Common Gateway Interface.


.. index::
   pair: WWW; server
   pair: CGI; protocol
   pair: HTTP; protocol
   pair: MIME; headers
   single: URL
   single: Common Gateway Interface

**Source code:** :source:`Lib/cgi.py`

--------------

Support module for Common Gateway Interface (CGI) scripts.

This module defines a number of utilities for use by CGI scripts written in
Python.


Introduction
------------

.. _cgi-intro:

A CGI script is invoked by an HTTP server, usually to process user input
submitted through an HTML ``<FORM>`` or ``<ISINDEX>`` element.

Most often, CGI scripts live in the server's special :file:`cgi-bin` directory.
The HTTP server places all sorts of information about the request (such as the
client's hostname, the requested URL, the query string, and lots of other
goodies) in the script's shell environment, executes the script, and sends the
script's output back to the client.

The script's input is connected to the client too, and sometimes the form data
is read this way; at other times the form data is passed via the "query string"
part of the URL.  This module is intended to take care of the different cases
and provide a simpler interface to the Python script.  It also provides a number
of utilities that help in debugging scripts, and the latest addition is support
for file uploads from a form (if your browser supports it).

The output of a CGI script should consist of two sections, separated by a blank
line.  The first section contains a number of headers, telling the client what
kind of data is following.  Python code to generate a minimal header section
looks like this::

   print "Content-Type: text/html"     # HTML is following
   print                               # blank line, end of headers

The second section is usually HTML, which allows the client software to display
nicely formatted text with header, in-line images, etc. Here's Python code that
prints a simple piece of HTML::

   print "<TITLE>CGI script output</TITLE>"
   print "<H1>This is my first CGI script</H1>"
   print "Hello, world!"


.. _using-the-cgi-module:

Using the cgi module
--------------------

Begin by writing ``import cgi``.  Do not use ``from cgi import *`` --- the
module defines all sorts of names for its own use or for backward compatibility
that you don't want in your namespace.

When you write a new script, consider adding these lines::

   import cgitb
   cgitb.enable()

This activates a special exception handler that will display detailed reports in
the Web browser if any errors occur.  If you'd rather not show the guts of your
program to users of your script, you can have the reports saved to files
instead, with code like this::

   import cgitb
   cgitb.enable(display=0, logdir="/path/to/logdir")

It's very helpful to use this feature during script development. The reports
produced by :mod:`cgitb` provide information that can save you a lot of time in
tracking down bugs.  You can always remove the ``cgitb`` line later when you
have tested your script and are confident that it works correctly.

To get at submitted form data, it's best to use the :class:`FieldStorage` class.
The other classes defined in this module are provided mostly for backward
compatibility. Instantiate it exactly once, without arguments.  This reads the
form contents from standard input or the environment (depending on the value of
various environment variables set according to the CGI standard).  Since it may
consume standard input, it should be instantiated only once.

The :class:`FieldStorage` instance can be indexed like a Python dictionary.
It allows membership testing with the :keyword:`in` operator, and also supports
the standard dictionary method :meth:`~dict.keys` and the built-in function
:func:`len`.  Form fields containing empty strings are ignored and do not appear
in the dictionary; to keep such values, provide a true value for the optional
*keep_blank_values* keyword parameter when creating the :class:`FieldStorage`
instance.

For instance, the following code (which assumes that the
:mailheader:`Content-Type` header and blank line have already been printed)
checks that the fields ``name`` and ``addr`` are both set to a non-empty
string::

   form = cgi.FieldStorage()
   if "name" not in form or "addr" not in form:
       print "<H1>Error</H1>"
       print "Please fill in the name and addr fields."
       return
   print "<p>name:", form["name"].value
   print "<p>addr:", form["addr"].value
   ...further form processing here...

Here the fields, accessed through ``form[key]``, are themselves instances of
:class:`FieldStorage` (or :class:`MiniFieldStorage`, depending on the form
encoding). The :attr:`~FieldStorage.value` attribute of the instance yields
the string value of the field.  The :meth:`~FieldStorage.getvalue` method
returns this string value directly; it also accepts an optional second argument
as a default to return if the requested key is not present.

If the submitted form data contains more than one field with the same name, the
object retrieved by ``form[key]`` is not a :class:`FieldStorage` or
:class:`MiniFieldStorage` instance but a list of such instances.  Similarly, in
this situation, ``form.getvalue(key)`` would return a list of strings. If you
expect this possibility (when your HTML form contains multiple fields with the
same name), use the :meth:`~FieldStorage.getlist` method, which always returns
a list of values (so that you do not need to special-case the single item
case).  For example, this code concatenates any number of username fields,
separated by commas::

   value = form.getlist("username")
   usernames = ",".join(value)

If a field represents an uploaded file, accessing the value via the
:attr:`~FieldStorage.value` attribute or the :func:`~FieldStorage.getvalue`
method reads the entire file in memory as a string.  This may not be what you
want. You can test for an uploaded file by testing either the
:attr:`~FieldStorage.filename` attribute or the :attr:`~FieldStorage.file`
attribute.  You can then read the data at leisure from the :attr:`!file`
attribute::

   fileitem = form["userfile"]
   if fileitem.file:
       # It's an uploaded file; count lines
       linecount = 0
       while 1:
           line = fileitem.file.readline()
           if not line: break
           linecount = linecount + 1

If an error is encountered when obtaining the contents of an uploaded file
(for example, when the user interrupts the form submission by clicking on
a Back or Cancel button) the :attr:`~FieldStorage.done` attribute of the
object for the field will be set to the value -1.

The file upload draft standard entertains the possibility of uploading multiple
files from one field (using a recursive :mimetype:`multipart/\*` encoding).
When this occurs, the item will be a dictionary-like :class:`FieldStorage` item.
This can be determined by testing its :attr:`!type` attribute, which should be
:mimetype:`multipart/form-data` (or perhaps another MIME type matching
:mimetype:`multipart/\*`).  In this case, it can be iterated over recursively
just like the top-level form object.

When a form is submitted in the "old" format (as the query string or as a single
data part of type :mimetype:`application/x-www-form-urlencoded`), the items will
actually be instances of the class :class:`MiniFieldStorage`.  In this case, the
:attr:`!list`, :attr:`!file`, and :attr:`filename` attributes are always ``None``.

A form submitted via POST that also has a query string will contain both
:class:`FieldStorage` and :class:`MiniFieldStorage` items.

Higher Level Interface
----------------------

.. versionadded:: 2.2

The previous section explains how to read CGI form data using the
:class:`FieldStorage` class.  This section describes a higher level interface
which was added to this class to allow one to do it in a more readable and
intuitive way.  The interface doesn't make the techniques described in previous
sections obsolete --- they are still useful to process file uploads efficiently,
for example.

.. XXX: Is this true ?

The interface consists of two simple methods. Using the methods you can process
form data in a generic way, without the need to worry whether only one or more
values were posted under one name.

In the previous section, you learned to write following code anytime you
expected a user to post more than one value under one name::

   item = form.getvalue("item")
   if isinstance(item, list):
       # The user is requesting more than one item.
   else:
       # The user is requesting only one item.

This situation is common for example when a form contains a group of multiple
checkboxes with the same name::

   <input type="checkbox" name="item" value="1" />
   <input type="checkbox" name="item" value="2" />

In most situations, however, there's only one form control with a particular
name in a form and then you expect and need only one value associated with this
name.  So you write a script containing for example this code::

   user = form.getvalue("user").upper()

The problem with the code is that you should never expect that a client will
provide valid input to your scripts.  For example, if a curious user appends
another ``user=foo`` pair to the query string, then the script would crash,
because in this situation the ``getvalue("user")`` method call returns a list
instead of a string.  Calling the :meth:`~str.upper` method on a list is not valid
(since lists do not have a method of this name) and results in an
:exc:`AttributeError` exception.

Therefore, the appropriate way to read form data values was to always use the
code which checks whether the obtained value is a single value or a list of
values.  That's annoying and leads to less readable scripts.

A more convenient approach is to use the methods :meth:`~FieldStorage.getfirst`
and :meth:`~FieldStorage.getlist` provided by this higher level interface.


.. method:: FieldStorage.getfirst(name[, default])

   This method always returns only one value associated with form field *name*.
   The method returns only the first value in case that more values were posted
   under such name.  Please note that the order in which the values are received
   may vary from browser to browser and should not be counted on. [#]_  If no such
   form field or value exists then the method returns the value specified by the
   optional parameter *default*.  This parameter defaults to ``None`` if not
   specified.


.. method:: FieldStorage.getlist(name)

   This method always returns a list of values associated with form field *name*.
   The method returns an empty list if no such form field or value exists for
   *name*.  It returns a list consisting of one item if only one such value exists.

Using these methods you can write nice compact code::

   import cgi
   form = cgi.FieldStorage()
   user = form.getfirst("user", "").upper()    # This way it's safe.
   for item in form.getlist("item"):
       do_something(item)


Old classes
-----------

.. deprecated:: 2.6

   These classes, present in earlier versions of the :mod:`cgi` module, are
   still supported for backward compatibility.  New applications should use the
   :class:`FieldStorage` class.

:class:`SvFormContentDict` stores single value form content as dictionary; it
assumes each field name occurs in the form only once.

:class:`FormContentDict` stores multiple value form content as a dictionary (the
form items are lists of values).  Useful if your form contains multiple fields
with the same name.

Other classes (:class:`FormContent`, :class:`InterpFormContentDict`) are present
for backwards compatibility with really old applications only.


.. _functions-in-cgi-module:

Functions
---------

These are useful if you want more control, or if you want to employ some of the
algorithms implemented in this module in other circumstances.


.. function:: parse(fp[, environ[, keep_blank_values[, strict_parsing]]])

   Parse a query in the environment or from a file (the file defaults to
   ``sys.stdin`` and environment defaults to ``os.environ``).  The *keep_blank_values* and *strict_parsing* parameters are
   passed to :func:`urlparse.parse_qs` unchanged.


.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]])

   This function is deprecated in this module. Use :func:`urlparse.parse_qs`
   instead. It is maintained here only for backward compatibility.

.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]])

   This function is deprecated in this module. Use :func:`urlparse.parse_qsl`
   instead. It is maintained here only for backward compatibility.

.. function:: parse_multipart(fp, pdict)

   Parse input of type :mimetype:`multipart/form-data` (for  file uploads).
   Arguments are *fp* for the input file and *pdict* for a dictionary containing
   other parameters in the :mailheader:`Content-Type` header.

   Returns a dictionary just like :func:`urlparse.parse_qs` keys are the field names, each
   value is a list of values for that field.  This is easy to use but not much good
   if you are expecting megabytes to be uploaded --- in that case, use the
   :class:`FieldStorage` class instead which is much more flexible.

   Note that this does not parse nested multipart parts --- use
   :class:`FieldStorage` for that.


.. function:: parse_header(string)

   Parse a MIME header (such as :mailheader:`Content-Type`) into a main value and a
   dictionary of parameters.


.. function:: test()

   Robust test CGI script, usable as main program. Writes minimal HTTP headers and
   formats all information provided to the script in HTML form.


.. function:: print_environ()

   Format the shell environment in HTML.


.. function:: print_form(form)

   Format a form in HTML.


.. function:: print_directory()

   Format the current directory in HTML.


.. function:: print_environ_usage()

   Print a list of useful (used by CGI) environment variables in HTML.


.. function:: escape(s[, quote])

   Convert the characters ``'&'``, ``'<'`` and ``'>'`` in string *s* to HTML-safe
   sequences.  Use this if you need to display text that might contain such
   characters in HTML.  If the optional flag *quote* is true, the quotation mark
   character (``"``) is also translated; this helps for inclusion in an HTML
   attribute value delimited by double quotes, as in ``<a href="...">``.  Note
   that single quotes are never translated.

   If the value to be quoted might include single- or double-quote characters,
   or both, consider using the :func:`~xml.sax.saxutils.quoteattr` function in the
   :mod:`xml.sax.saxutils` module instead.


.. _cgi-security:

Caring about security
---------------------

.. index:: pair: CGI; security

There's one important rule: if you invoke an external program (via the
:func:`os.system` or :func:`os.popen` functions. or others with similar
functionality), make very sure you don't pass arbitrary strings received from
the client to the shell.  This is a well-known security hole whereby clever
hackers anywhere on the Web can exploit a gullible CGI script to invoke
arbitrary shell commands.  Even parts of the URL or field names cannot be
trusted, since the request doesn't have to come from your form!

To be on the safe side, if you must pass a string gotten from a form to a shell
command, you should make sure the string contains only alphanumeric characters,
dashes, underscores, and periods.


Installing your CGI script on a Unix system
-------------------------------------------

Read the documentation for your HTTP server and check with your local system
administrator to find the directory where CGI scripts should be installed;
usually this is in a directory :file:`cgi-bin` in the server tree.

Make sure that your script is readable and executable by "others"; the Unix file
mode should be ``0755`` octal (use ``chmod 0755 filename``).  Make sure that the
first line of the script contains ``#!`` starting in column 1 followed by the
pathname of the Python interpreter, for instance::

   #!/usr/local/bin/python

Make sure the Python interpreter exists and is executable by "others".

Make sure that any files your script needs to read or write are readable or
writable, respectively, by "others" --- their mode should be ``0644`` for
readable and ``0666`` for writable.  This is because, for security reasons, the
HTTP server executes your script as user "nobody", without any special
privileges.  It can only read (write, execute) files that everybody can read
(write, execute).  The current directory at execution time is also different (it
is usually the server's cgi-bin directory) and the set of environment variables
is also different from what you get when you log in.  In particular, don't count
on the shell's search path for executables (:envvar:`PATH`) or the Python module
search path (:envvar:`PYTHONPATH`) to be set to anything interesting.

If you need to load modules from a directory which is not on Python's default
module search path, you can change the path in your script, before importing
other modules.  For example::

   import sys
   sys.path.insert(0, "/usr/home/joe/lib/python")
   sys.path.insert(0, "/usr/local/lib/python")

(This way, the directory inserted last will be searched first!)

Instructions for non-Unix systems will vary; check your HTTP server's
documentation (it will usually have a section on CGI scripts).


Testing your CGI script
-----------------------

Unfortunately, a CGI script will generally not run when you try it from the
command line, and a script that works perfectly from the command line may fail
mysteriously when run from the server.  There's one reason why you should still
test your script from the command line: if it contains a syntax error, the
Python interpreter won't execute it at all, and the HTTP server will most likely
send a cryptic error to the client.

Assuming your script has no syntax errors, yet it does not work, you have no
choice but to read the next section.


Debugging CGI scripts
---------------------

.. index:: pair: CGI; debugging

First of all, check for trivial installation errors --- reading the section
above on installing your CGI script carefully can save you a lot of time.  If
you wonder whether you have understood the installation procedure correctly, try
installing a copy of this module file (:file:`cgi.py`) as a CGI script.  When
invoked as a script, the file will dump its environment and the contents of the
form in HTML form. Give it the right mode etc, and send it a request.  If it's
installed in the standard :file:`cgi-bin` directory, it should be possible to
send it a request by entering a URL into your browser of the form:

.. code-block:: none

   http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&addr=At+Home

If this gives an error of type 404, the server cannot find the script -- perhaps
you need to install it in a different directory.  If it gives another error,
there's an installation problem that you should fix before trying to go any
further.  If you get a nicely formatted listing of the environment and form
content (in this example, the fields should be listed as "addr" with value "At
Home" and "name" with value "Joe Blow"), the :file:`cgi.py` script has been
installed correctly.  If you follow the same procedure for your own script, you
should now be able to debug it.

The next step could be to call the :mod:`cgi` module's :func:`test` function
from your script: replace its main code with the single statement ::

   cgi.test()

This should produce the same results as those gotten from installing the
:file:`cgi.py` file itself.

When an ordinary Python script raises an unhandled exception (for whatever
reason: of a typo in a module name, a file that can't be opened, etc.), the
Python interpreter prints a nice traceback and exits.  While the Python
interpreter will still do this when your CGI script raises an exception, most
likely the traceback will end up in one of the HTTP server's log files, or be
discarded altogether.

Fortunately, once you have managed to get your script to execute *some* code,
you can easily send tracebacks to the Web browser using the :mod:`cgitb` module.
If you haven't done so already, just add the lines::

   import cgitb
   cgitb.enable()

to the top of your script.  Then try running it again; when a problem occurs,
you should see a detailed report that will likely make apparent the cause of the
crash.

If you suspect that there may be a problem in importing the :mod:`cgitb` module,
you can use an even more robust approach (which only uses built-in modules)::

   import sys
   sys.stderr = sys.stdout
   print "Content-Type: text/plain"
   print
   ...your code here...

This relies on the Python interpreter to print the traceback.  The content type
of the output is set to plain text, which disables all HTML processing.  If your
script works, the raw HTML will be displayed by your client.  If it raises an
exception, most likely after the first two lines have been printed, a traceback
will be displayed. Because no HTML interpretation is going on, the traceback
will be readable.


Common problems and solutions
-----------------------------

* Most HTTP servers buffer the output from CGI scripts until the script is
  completed.  This means that it is not possible to display a progress report on
  the client's display while the script is running.

* Check the installation instructions above.

* Check the HTTP server's log files.  (``tail -f logfile`` in a separate window
  may be useful!)

* Always check a script for syntax errors first, by doing something like
  ``python script.py``.

* If your script does not have any syntax errors, try adding ``import cgitb;
  cgitb.enable()`` to the top of the script.

* When invoking external programs, make sure they can be found. Usually, this
  means using absolute path names --- :envvar:`PATH` is usually not set to a very
  useful value in a CGI script.

* When reading or writing external files, make sure they can be read or written
  by the userid under which your CGI script will be running: this is typically the
  userid under which the web server is running, or some explicitly specified
  userid for a web server's ``suexec`` feature.

* Don't try to give a CGI script a set-uid mode.  This doesn't work on most
  systems, and is a security liability as well.

.. rubric:: Footnotes

.. [#] Note that some recent versions of the HTML specification do state what order the
   field values should be supplied in, but knowing whether a request was
   received from a conforming browser, or even from a browser at all, is tedious
   and error-prone.
PK	%�\�6gE�
�
+html/_sources/library/cgihttpserver.rst.txtnu�[���:mod:`CGIHTTPServer` --- CGI-capable HTTP request handler
=========================================================

.. module:: CGIHTTPServer
   :synopsis: This module provides a request handler for HTTP servers which can run CGI
              scripts.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

.. note::
   The :mod:`CGIHTTPServer` module has been merged into :mod:`http.server` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.


The :mod:`CGIHTTPServer` module defines a request-handler class, interface
compatible with :class:`BaseHTTPServer.BaseHTTPRequestHandler` and inherits
behavior from :class:`SimpleHTTPServer.SimpleHTTPRequestHandler` but can also
run CGI scripts.

.. note::

   This module can run CGI scripts on Unix and Windows systems.

.. note::

   CGI scripts run by the :class:`CGIHTTPRequestHandler` class cannot execute
   redirects (HTTP code 302), because code 200 (script output follows) is sent
   prior to execution of the CGI script.  This pre-empts the status code.

The :mod:`CGIHTTPServer` module defines the following class:


.. class:: CGIHTTPRequestHandler(request, client_address, server)

   This class is used to serve either files or output of CGI scripts from  the
   current directory and below. Note that mapping HTTP hierarchic structure to
   local directory structure is exactly as in
   :class:`SimpleHTTPServer.SimpleHTTPRequestHandler`.

   The class will however, run the CGI script, instead of serving it as a file, if
   it guesses it to be a CGI script. Only directory-based CGI are used --- the
   other common server configuration is to treat special extensions as denoting CGI
   scripts.

   The :func:`do_GET` and :func:`do_HEAD` functions are modified to run CGI scripts
   and serve the output, instead of serving files, if the request leads to
   somewhere below the ``cgi_directories`` path.

   The :class:`CGIHTTPRequestHandler` defines the following data member:


   .. attribute:: cgi_directories

      This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to
      treat as containing CGI scripts.

   The :class:`CGIHTTPRequestHandler` defines the following methods:


   .. method:: do_POST()

      This method serves the ``'POST'`` request type, only allowed for CGI
      scripts.  Error 501, "Can only POST to CGI scripts", is output when trying
      to POST to a non-CGI url.

Note that CGI scripts will be run with UID of user nobody, for security reasons.
Problems with the CGI script will be translated to error 403.

For example usage, see the implementation of the :func:`test` function.


.. seealso::

   Module :mod:`BaseHTTPServer`
      Base class implementation for Web server and request handler.

PK	%�\{��::#html/_sources/library/cgitb.rst.txtnu�[���
:mod:`cgitb` --- Traceback manager for CGI scripts
==================================================

.. module:: cgitb
   :synopsis: Configurable traceback handler for CGI scripts.
.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. versionadded:: 2.2

.. index::
   single: CGI; exceptions
   single: CGI; tracebacks
   single: exceptions; in CGI scripts
   single: tracebacks; in CGI scripts

The :mod:`cgitb` module provides a special exception handler for Python scripts.
(Its name is a bit misleading.  It was originally designed to display extensive
traceback information in HTML for CGI scripts.  It was later generalized to also
display this information in plain text.)  After this module is activated, if an
uncaught exception occurs, a detailed, formatted report will be displayed.  The
report includes a traceback showing excerpts of the source code for each level,
as well as the values of the arguments and local variables to currently running
functions, to help you debug the problem.  Optionally, you can save this
information to a file instead of sending it to the browser.

To enable this feature, simply add this to the top of your CGI script::

   import cgitb
   cgitb.enable()

The options to the :func:`enable` function control whether the report is
displayed in the browser and whether the report is logged to a file for later
analysis.


.. function:: enable([display[, logdir[, context[, format]]]])

   .. index:: single: excepthook() (in module sys)

   This function causes the :mod:`cgitb` module to take over the interpreter's
   default handling for exceptions by setting the value of :attr:`sys.excepthook`.

   The optional argument *display* defaults to ``1`` and can be set to ``0`` to
   suppress sending the traceback to the browser. If the argument *logdir* is
   present, the traceback reports are written to files.  The value of *logdir*
   should be a directory where these files will be placed. The optional argument
   *context* is the number of lines of context to display around the current line
   of source code in the traceback; this defaults to ``5``. If the optional
   argument *format* is ``"html"``, the output is formatted as HTML.  Any other
   value forces plain text output.  The default value is ``"html"``.


.. function:: handler([info])

   This function handles an exception using the default settings (that is, show a
   report in the browser, but don't log to a file). This can be used when you've
   caught an exception and want to report it using :mod:`cgitb`.  The optional
   *info* argument should be a 3-tuple containing an exception type, exception
   value, and traceback object, exactly like the tuple returned by
   :func:`sys.exc_info`.  If the *info* argument is not supplied, the current
   exception is obtained from :func:`sys.exc_info`.

PK	%�\�;N[[#html/_sources/library/chunk.rst.txtnu�[���
:mod:`chunk` --- Read IFF chunked data
======================================

.. module:: chunk
   :synopsis: Module to read IFF chunks.
.. moduleauthor:: Sjoerd Mullender <sjoerd@acm.org>
.. sectionauthor:: Sjoerd Mullender <sjoerd@acm.org>


.. index::
   single: Audio Interchange File Format
   single: AIFF
   single: AIFF-C
   single: Real Media File Format
   single: RMFF

This module provides an interface for reading files that use EA IFF 85 chunks.
[#]_  This format is used in at least the Audio Interchange File Format
(AIFF/AIFF-C) and the Real Media File Format (RMFF).  The WAVE audio file format
is closely related and can also be read using this module.

A chunk has the following structure:

+---------+--------+-------------------------------+
| Offset  | Length | Contents                      |
+=========+========+===============================+
| 0       | 4      | Chunk ID                      |
+---------+--------+-------------------------------+
| 4       | 4      | Size of chunk in big-endian   |
|         |        | byte order, not including the |
|         |        | header                        |
+---------+--------+-------------------------------+
| 8       | *n*    | Data bytes, where *n* is the  |
|         |        | size given in the preceding   |
|         |        | field                         |
+---------+--------+-------------------------------+
| 8 + *n* | 0 or 1 | Pad byte needed if *n* is odd |
|         |        | and chunk alignment is used   |
+---------+--------+-------------------------------+

The ID is a 4-byte string which identifies the type of chunk.

The size field (a 32-bit value, encoded using big-endian byte order) gives the
size of the chunk data, not including the 8-byte header.

Usually an IFF-type file consists of one or more chunks.  The proposed usage of
the :class:`Chunk` class defined here is to instantiate an instance at the start
of each chunk and read from the instance until it reaches the end, after which a
new instance can be instantiated. At the end of the file, creating a new
instance will fail with an :exc:`EOFError` exception.


.. class:: Chunk(file[, align, bigendian, inclheader])

   Class which represents a chunk.  The *file* argument is expected to be a
   file-like object.  An instance of this class is specifically allowed.  The
   only method that is needed is :meth:`~file.read`.  If the methods
   :meth:`~file.seek` and :meth:`~file.tell` are present and don't
   raise an exception, they are also used.
   If these methods are present and raise an exception, they are expected to not
   have altered the object.  If the optional argument *align* is true, chunks
   are assumed to be aligned on 2-byte boundaries.  If *align* is false, no
   alignment is assumed.  The default value is true.  If the optional argument
   *bigendian* is false, the chunk size is assumed to be in little-endian order.
   This is needed for WAVE audio files. The default value is true.  If the
   optional argument *inclheader* is true, the size given in the chunk header
   includes the size of the header.  The default value is false.

   A :class:`Chunk` object supports the following methods:


   .. method:: getname()

      Returns the name (ID) of the chunk.  This is the first 4 bytes of the
      chunk.


   .. method:: getsize()

      Returns the size of the chunk.


   .. method:: close()

      Close and skip to the end of the chunk.  This does not close the
      underlying file.

   The remaining methods will raise :exc:`IOError` if called after the
   :meth:`close` method has been called.


   .. method:: isatty()

      Returns ``False``.


   .. method:: seek(pos[, whence])

      Set the chunk's current position.  The *whence* argument is optional and
      defaults to ``0`` (absolute file positioning); other values are ``1``
      (seek relative to the current position) and ``2`` (seek relative to the
      file's end).  There is no return value. If the underlying file does not
      allow seek, only forward seeks are allowed.


   .. method:: tell()

      Return the current position into the chunk.


   .. method:: read([size])

      Read at most *size* bytes from the chunk (less if the read hits the end of
      the chunk before obtaining *size* bytes).  If the *size* argument is
      negative or omitted, read all data until the end of the chunk.  The bytes
      are returned as a string object.  An empty string is returned when the end
      of the chunk is encountered immediately.


   .. method:: skip()

      Skip to the end of the chunk.  All further calls to :meth:`read` for the
      chunk will return ``''``.  If you are not interested in the contents of
      the chunk, this method should be called so that the file points to the
      start of the next chunk.


.. rubric:: Footnotes

.. [#] "EA IFF 85" Standard for Interchange Format Files, Jerry Morrison, Electronic
   Arts, January 1985.

PK	%�\ʼQ.��#html/_sources/library/cmath.rst.txtnu�[���:mod:`cmath` --- Mathematical functions for complex numbers
===========================================================

.. module:: cmath
   :synopsis: Mathematical functions for complex numbers.


This module is always available.  It provides access to mathematical functions
for complex numbers.  The functions in this module accept integers,
floating-point numbers or complex numbers as arguments. They will also accept
any Python object that has either a :meth:`__complex__` or a :meth:`__float__`
method: these methods are used to convert the object to a complex or
floating-point number, respectively, and the function is then applied to the
result of the conversion.

.. note::

   On platforms with hardware and system-level support for signed
   zeros, functions involving branch cuts are continuous on *both*
   sides of the branch cut: the sign of the zero distinguishes one
   side of the branch cut from the other.  On platforms that do not
   support signed zeros the continuity is as specified below.


Conversions to and from polar coordinates
-----------------------------------------

A Python complex number ``z`` is stored internally using *rectangular*
or *Cartesian* coordinates.  It is completely determined by its *real
part* ``z.real`` and its *imaginary part* ``z.imag``.  In other
words::

   z == z.real + z.imag*1j

*Polar coordinates* give an alternative way to represent a complex
number.  In polar coordinates, a complex number *z* is defined by the
modulus *r* and the phase angle *phi*. The modulus *r* is the distance
from *z* to the origin, while the phase *phi* is the counterclockwise
angle, measured in radians, from the positive x-axis to the line
segment that joins the origin to *z*.

The following functions can be used to convert from the native
rectangular coordinates to polar coordinates and back.

.. function:: phase(x)

   Return the phase of *x* (also known as the *argument* of *x*), as a
   float.  ``phase(x)`` is equivalent to ``math.atan2(x.imag,
   x.real)``.  The result lies in the range [-π, π], and the branch
   cut for this operation lies along the negative real axis,
   continuous from above.  On systems with support for signed zeros
   (which includes most systems in current use), this means that the
   sign of the result is the same as the sign of ``x.imag``, even when
   ``x.imag`` is zero::

      >>> phase(complex(-1.0, 0.0))
      3.1415926535897931
      >>> phase(complex(-1.0, -0.0))
      -3.1415926535897931

   .. versionadded:: 2.6


.. note::

   The modulus (absolute value) of a complex number *x* can be
   computed using the built-in :func:`abs` function.  There is no
   separate :mod:`cmath` module function for this operation.


.. function:: polar(x)

   Return the representation of *x* in polar coordinates.  Returns a
   pair ``(r, phi)`` where *r* is the modulus of *x* and phi is the
   phase of *x*.  ``polar(x)`` is equivalent to ``(abs(x),
   phase(x))``.

   .. versionadded:: 2.6


.. function:: rect(r, phi)

   Return the complex number *x* with polar coordinates *r* and *phi*.
   Equivalent to ``r * (math.cos(phi) + math.sin(phi)*1j)``.

   .. versionadded:: 2.6


Power and logarithmic functions
-------------------------------

.. function:: exp(x)

   Return the exponential value ``e**x``.


.. function:: log(x[, base])

   Returns the logarithm of *x* to the given *base*. If the *base* is not
   specified, returns the natural logarithm of *x*. There is one branch cut, from 0
   along the negative real axis to -∞, continuous from above.

   .. versionchanged:: 2.4
      *base* argument added.


.. function:: log10(x)

   Return the base-10 logarithm of *x*. This has the same branch cut as
   :func:`log`.


.. function:: sqrt(x)

   Return the square root of *x*. This has the same branch cut as :func:`log`.


Trigonometric functions
-----------------------

.. function:: acos(x)

   Return the arc cosine of *x*. There are two branch cuts: One extends right from
   1 along the real axis to ∞, continuous from below. The other extends left from
   -1 along the real axis to -∞, continuous from above.


.. function:: asin(x)

   Return the arc sine of *x*. This has the same branch cuts as :func:`acos`.


.. function:: atan(x)

   Return the arc tangent of *x*. There are two branch cuts: One extends from
   ``1j`` along the imaginary axis to ``∞j``, continuous from the right. The
   other extends from ``-1j`` along the imaginary axis to ``-∞j``, continuous
   from the left.

   .. versionchanged:: 2.6
      direction of continuity of upper cut reversed


.. function:: cos(x)

   Return the cosine of *x*.


.. function:: sin(x)

   Return the sine of *x*.


.. function:: tan(x)

   Return the tangent of *x*.


Hyperbolic functions
--------------------

.. function:: acosh(x)

   Return the inverse hyperbolic cosine of *x*. There is one branch cut,
   extending left from 1 along the real axis to -∞, continuous from above.


.. function:: asinh(x)

   Return the inverse hyperbolic sine of *x*. There are two branch cuts:
   One extends from ``1j`` along the imaginary axis to ``∞j``,
   continuous from the right.  The other extends from ``-1j`` along
   the imaginary axis to ``-∞j``, continuous from the left.

   .. versionchanged:: 2.6
      branch cuts moved to match those recommended by the C99 standard


.. function:: atanh(x)

   Return the inverse hyperbolic tangent of *x*. There are two branch cuts: One
   extends from ``1`` along the real axis to ``∞``, continuous from below. The
   other extends from ``-1`` along the real axis to ``-∞``, continuous from
   above.

   .. versionchanged:: 2.6
      direction of continuity of right cut reversed


.. function:: cosh(x)

   Return the hyperbolic cosine of *x*.


.. function:: sinh(x)

   Return the hyperbolic sine of *x*.


.. function:: tanh(x)

   Return the hyperbolic tangent of *x*.


Classification functions
------------------------

.. function:: isinf(x)

   Return ``True`` if the real or the imaginary part of x is positive
   or negative infinity.

   .. versionadded:: 2.6


.. function:: isnan(x)

   Return ``True`` if the real or imaginary part of x is not a number (NaN).

   .. versionadded:: 2.6


Constants
---------


.. data:: pi

   The mathematical constant *π*, as a float.


.. data:: e

   The mathematical constant *e*, as a float.

.. index:: module: math

Note that the selection of functions is similar, but not identical, to that in
module :mod:`math`.  The reason for having two modules is that some users aren't
interested in complex numbers, and perhaps don't even know what they are.  They
would rather have ``math.sqrt(-1)`` raise an exception than return a complex
number. Also note that the functions defined in :mod:`cmath` always return a
complex number, even if the answer can be expressed as a real number (in which
case the complex number has an imaginary part of zero).

A note on branch cuts: They are curves along which the given function fails to
be continuous.  They are a necessary feature of many complex functions.  It is
assumed that if you need to compute with complex functions, you will understand
about branch cuts.  Consult almost any (not too elementary) book on complex
variables for enlightenment.  For information of the proper choice of branch
cuts for numerical purposes, a good reference should be the following:


.. seealso::

   Kahan, W:  Branch cuts for complex elementary functions; or, Much ado about
   nothing's sign bit.  In Iserles, A., and Powell, M. (eds.), The state of the art
   in numerical analysis. Clarendon Press (1987) pp165--211.


PK	%�\��u!u!!html/_sources/library/cmd.rst.txtnu�[���:mod:`cmd` --- Support for line-oriented command interpreters
=============================================================

.. module:: cmd
   :synopsis: Build line-oriented command interpreters.
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>

**Source code:** :source:`Lib/cmd.py`

--------------

The :class:`Cmd` class provides a simple framework for writing line-oriented
command interpreters.  These are often useful for test harnesses, administrative
tools, and prototypes that will later be wrapped in a more sophisticated
interface.

.. class:: Cmd([completekey[, stdin[, stdout]]])

   A :class:`Cmd` instance or subclass instance is a line-oriented interpreter
   framework.  There is no good reason to instantiate :class:`Cmd` itself; rather,
   it's useful as a superclass of an interpreter class you define yourself in order
   to inherit :class:`Cmd`'s methods and encapsulate action methods.

   The optional argument *completekey* is the :mod:`readline` name of a completion
   key; it defaults to :kbd:`Tab`. If *completekey* is not :const:`None` and
   :mod:`readline` is available, command completion is done automatically.

   The optional arguments *stdin* and *stdout* specify the  input and output file
   objects that the Cmd instance or subclass  instance will use for input and
   output. If not specified, they will default to :data:`sys.stdin` and
   :data:`sys.stdout`.

   If you want a given *stdin* to be used, make sure to set the instance's
   :attr:`use_rawinput` attribute to ``False``, otherwise *stdin* will be
   ignored.

   .. versionchanged:: 2.3
      The *stdin* and *stdout* parameters were added.


.. _cmd-objects:

Cmd Objects
-----------

A :class:`Cmd` instance has the following methods:


.. method:: Cmd.cmdloop([intro])

   Repeatedly issue a prompt, accept input, parse an initial prefix off the
   received input, and dispatch to action methods, passing them the remainder of
   the line as argument.

   The optional argument is a banner or intro string to be issued before the first
   prompt (this overrides the :attr:`intro` class attribute).

   If the :mod:`readline` module is loaded, input will automatically inherit
   :program:`bash`\ -like history-list editing (e.g. :kbd:`Control-P` scrolls back
   to the last command, :kbd:`Control-N` forward to the next one, :kbd:`Control-F`
   moves the cursor to the right non-destructively, :kbd:`Control-B` moves the
   cursor to the left non-destructively, etc.).

   An end-of-file on input is passed back as the string ``'EOF'``.

   An interpreter instance will recognize a command name ``foo`` if and only if it
   has a method :meth:`do_foo`.  As a special case, a line beginning with the
   character ``'?'`` is dispatched to the method :meth:`do_help`.  As another
   special case, a line beginning with the character ``'!'`` is dispatched to the
   method :meth:`do_shell` (if such a method is defined).

   This method will return when the :meth:`postcmd` method returns a true value.
   The *stop* argument to :meth:`postcmd` is the return value from the command's
   corresponding :meth:`do_\*` method.

   If completion is enabled, completing commands will be done automatically, and
   completing of commands args is done by calling :meth:`complete_foo` with
   arguments *text*, *line*, *begidx*, and *endidx*.  *text* is the string prefix
   we are attempting to match: all returned matches must begin with it. *line* is
   the current input line with leading whitespace removed, *begidx* and *endidx*
   are the beginning and ending indexes of the prefix text, which could be used to
   provide different completion depending upon which position the argument is in.

   All subclasses of :class:`Cmd` inherit a predefined :meth:`do_help`.  This
   method, called with an argument ``'bar'``, invokes the corresponding method
   :meth:`help_bar`, and if that is not present, prints the docstring of
   :meth:`do_bar`, if available.  With no argument, :meth:`do_help` lists all
   available help topics (that is, all commands with corresponding
   :meth:`help_\*` methods or commands that have docstrings), and also lists any
   undocumented commands.


.. method:: Cmd.onecmd(str)

   Interpret the argument as though it had been typed in response to the prompt.
   This may be overridden, but should not normally need to be; see the
   :meth:`precmd` and :meth:`postcmd` methods for useful execution hooks.  The
   return value is a flag indicating whether interpretation of commands by the
   interpreter should stop.  If there is a :meth:`do_\*` method for the command
   *str*, the return value of that method is returned, otherwise the return value
   from the :meth:`default` method is returned.


.. method:: Cmd.emptyline()

   Method called when an empty line is entered in response to the prompt. If this
   method is not overridden, it repeats the last nonempty command entered.


.. method:: Cmd.default(line)

   Method called on an input line when the command prefix is not recognized. If
   this method is not overridden, it prints an error message and returns.


.. method:: Cmd.completedefault(text, line, begidx, endidx)

   Method called to complete an input line when no command-specific
   :meth:`complete_\*` method is available.  By default, it returns an empty list.


.. method:: Cmd.precmd(line)

   Hook method executed just before the command line *line* is interpreted, but
   after the input prompt is generated and issued.  This method is a stub in
   :class:`Cmd`; it exists to be overridden by subclasses.  The return value is
   used as the command which will be executed by the :meth:`onecmd` method; the
   :meth:`precmd` implementation may re-write the command or simply return *line*
   unchanged.


.. method:: Cmd.postcmd(stop, line)

   Hook method executed just after a command dispatch is finished.  This method is
   a stub in :class:`Cmd`; it exists to be overridden by subclasses.  *line* is the
   command line which was executed, and *stop* is a flag which indicates whether
   execution will be terminated after the call to :meth:`postcmd`; this will be the
   return value of the :meth:`onecmd` method.  The return value of this method will
   be used as the new value for the internal flag which corresponds to *stop*;
   returning false will cause interpretation to continue.


.. method:: Cmd.preloop()

   Hook method executed once when :meth:`cmdloop` is called.  This method is a stub
   in :class:`Cmd`; it exists to be overridden by subclasses.


.. method:: Cmd.postloop()

   Hook method executed once when :meth:`cmdloop` is about to return. This method
   is a stub in :class:`Cmd`; it exists to be overridden by subclasses.


Instances of :class:`Cmd` subclasses have some public instance variables:

.. attribute:: Cmd.prompt

   The prompt issued to solicit input.


.. attribute:: Cmd.identchars

   The string of characters accepted for the command prefix.


.. attribute:: Cmd.lastcmd

   The last nonempty command prefix seen.


.. attribute:: Cmd.cmdqueue

   A list of queued input lines.  The cmdqueue list is checked in
   :meth:`cmdloop` when new input is needed; if it is nonempty, its elements
   will be processed in order, as if entered at the prompt.


.. attribute:: Cmd.intro

   A string to issue as an intro or banner.  May be overridden by giving the
   :meth:`cmdloop` method an argument.


.. attribute:: Cmd.doc_header

   The header to issue if the help output has a section for documented commands.


.. attribute:: Cmd.misc_header

   The header to issue if the help output has a section for miscellaneous  help
   topics (that is, there are :meth:`help_\*` methods without corresponding
   :meth:`do_\*` methods).


.. attribute:: Cmd.undoc_header

   The header to issue if the help output has a section for undocumented  commands
   (that is, there are :meth:`do_\*` methods without corresponding :meth:`help_\*`
   methods).


.. attribute:: Cmd.ruler

   The character used to draw separator lines under the help-message headers.  If
   empty, no ruler line is drawn.  It defaults to ``'='``.


.. attribute:: Cmd.use_rawinput

   A flag, defaulting to true.  If true, :meth:`cmdloop` uses :func:`raw_input` to
   display a prompt and read the next command; if false, :meth:`sys.stdout.write`
   and :meth:`sys.stdin.readline` are used. (This means that by importing
   :mod:`readline`, on systems that support it, the interpreter will automatically
   support :program:`Emacs`\ -like line editing  and command-history keystrokes.)

PK	%�\�r.b��"html/_sources/library/code.rst.txtnu�[���
:mod:`code` --- Interpreter base classes
========================================

.. module:: code
   :synopsis: Facilities to implement read-eval-print loops.



The ``code`` module provides facilities to implement read-eval-print loops in
Python.  Two classes and convenience functions are included which can be used to
build applications which provide an interactive interpreter prompt.


.. class:: InteractiveInterpreter([locals])

   This class deals with parsing and interpreter state (the user's namespace); it
   does not deal with input buffering or prompting or input file naming (the
   filename is always passed in explicitly). The optional *locals* argument
   specifies the dictionary in which code will be executed; it defaults to a newly
   created dictionary with key ``'__name__'`` set to ``'__console__'`` and key
   ``'__doc__'`` set to ``None``.


.. class:: InteractiveConsole([locals[, filename]])

   Closely emulate the behavior of the interactive Python interpreter. This class
   builds on :class:`InteractiveInterpreter` and adds prompting using the familiar
   ``sys.ps1`` and ``sys.ps2``, and input buffering.


.. function:: interact([banner[, readfunc[, local]]])

   Convenience function to run a read-eval-print loop.  This creates a new instance
   of :class:`InteractiveConsole` and sets *readfunc* to be used as the
   :meth:`InteractiveConsole.raw_input` method, if provided.  If *local* is
   provided, it is passed to the :class:`InteractiveConsole` constructor for
   use as the default namespace for the interpreter loop.  The :meth:`interact`
   method of the instance is then run with *banner* passed as the banner to
   use, if provided.  The console object is discarded after use.


.. function:: compile_command(source[, filename[, symbol]])

   This function is useful for programs that want to emulate Python's interpreter
   main loop (a.k.a. the read-eval-print loop).  The tricky part is to determine
   when the user has entered an incomplete command that can be completed by
   entering more text (as opposed to a complete command or a syntax error).  This
   function *almost* always makes the same decision as the real interpreter main
   loop.

   *source* is the source string; *filename* is the optional filename from which
   source was read, defaulting to ``'<input>'``; and *symbol* is the optional
   grammar start symbol, which should be either ``'single'`` (the default) or
   ``'eval'``.

   Returns a code object (the same as ``compile(source, filename, symbol)``) if the
   command is complete and valid; ``None`` if the command is incomplete; raises
   :exc:`SyntaxError` if the command is complete and contains a syntax error, or
   raises :exc:`OverflowError` or :exc:`ValueError` if the command contains an
   invalid literal.


.. _interpreter-objects:

Interactive Interpreter Objects
-------------------------------


.. method:: InteractiveInterpreter.runsource(source[, filename[, symbol]])

   Compile and run some source in the interpreter. Arguments are the same as for
   :func:`compile_command`; the default for *filename* is ``'<input>'``, and for
   *symbol* is ``'single'``.  One several things can happen:

   * The input is incorrect; :func:`compile_command` raised an exception
     (:exc:`SyntaxError` or :exc:`OverflowError`).  A syntax traceback will be
     printed by calling the :meth:`showsyntaxerror` method.  :meth:`runsource`
     returns ``False``.

   * The input is incomplete, and more input is required; :func:`compile_command`
     returned ``None``. :meth:`runsource` returns ``True``.

   * The input is complete; :func:`compile_command` returned a code object.  The
     code is executed by calling the :meth:`runcode` (which also handles run-time
     exceptions, except for :exc:`SystemExit`). :meth:`runsource` returns ``False``.

   The return value can be used to decide whether to use ``sys.ps1`` or ``sys.ps2``
   to prompt the next line.


.. method:: InteractiveInterpreter.runcode(code)

   Execute a code object. When an exception occurs, :meth:`showtraceback` is called
   to display a traceback.  All exceptions are caught except :exc:`SystemExit`,
   which is allowed to propagate.

   A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in
   this code, and may not always be caught.  The caller should be prepared to deal
   with it.


.. method:: InteractiveInterpreter.showsyntaxerror([filename])

   Display the syntax error that just occurred.  This does not display a stack
   trace because there isn't one for syntax errors. If *filename* is given, it is
   stuffed into the exception instead of the default filename provided by Python's
   parser, because it always uses ``'<string>'`` when reading from a string. The
   output is written by the :meth:`write` method.


.. method:: InteractiveInterpreter.showtraceback()

   Display the exception that just occurred.  We remove the first stack item
   because it is within the interpreter object implementation. The output is
   written by the :meth:`write` method.


.. method:: InteractiveInterpreter.write(data)

   Write a string to the standard error stream (``sys.stderr``). Derived classes
   should override this to provide the appropriate output handling as needed.


.. _console-objects:

Interactive Console Objects
---------------------------

The :class:`InteractiveConsole` class is a subclass of
:class:`InteractiveInterpreter`, and so offers all the methods of the
interpreter objects as well as the following additions.


.. method:: InteractiveConsole.interact([banner])

   Closely emulate the interactive Python console. The optional banner argument
   specify the banner to print before the first interaction; by default it prints a
   banner similar to the one printed by the standard Python interpreter, followed
   by the class name of the console object in parentheses (so as not to confuse
   this with the real interpreter -- since it's so close!).


.. method:: InteractiveConsole.push(line)

   Push a line of source text to the interpreter. The line should not have a
   trailing newline; it may have internal newlines.  The line is appended to a
   buffer and the interpreter's :meth:`runsource` method is called with the
   concatenated contents of the buffer as source.  If this indicates that the
   command was executed or invalid, the buffer is reset; otherwise, the command is
   incomplete, and the buffer is left as it was after the line was appended.  The
   return value is ``True`` if more input is required, ``False`` if the line was
   dealt with in some way (this is the same as :meth:`runsource`).


.. method:: InteractiveConsole.resetbuffer()

   Remove any unhandled source text from the input buffer.


.. method:: InteractiveConsole.raw_input([prompt])

   Write a prompt and read a line.  The returned line does not include the trailing
   newline.  When the user enters the EOF key sequence, :exc:`EOFError` is raised.
   The base implementation uses the built-in function :func:`raw_input`; a subclass
   may replace this with a different implementation.

PK	%�\_�Zl��$html/_sources/library/codecs.rst.txtnu�[���
:mod:`codecs` --- Codec registry and base classes
=================================================

.. module:: codecs
   :synopsis: Encode and decode data and streams.
.. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. index::
   single: Unicode
   single: Codecs
   pair: Codecs; encode
   pair: Codecs; decode
   single: streams
   pair: stackable; streams

This module defines base classes for standard Python codecs (encoders and
decoders) and provides access to the internal Python codec registry which
manages the codec and error handling lookup process.

It defines the following functions:

.. function:: encode(obj, [encoding[, errors]])

   Encodes *obj* using the codec registered for *encoding*. The default
   encoding is ``'ascii'``.

   *Errors* may be given to set the desired error handling scheme. The
   default error handler is ``'strict'`` meaning that encoding errors raise
   :exc:`ValueError` (or a more codec specific subclass, such as
   :exc:`UnicodeEncodeError`). Refer to :ref:`codec-base-classes` for more
   information on codec error handling.

   .. versionadded:: 2.4

.. function:: decode(obj, [encoding[, errors]])

   Decodes *obj* using the codec registered for *encoding*. The default
   encoding is ``'ascii'``.

   *Errors* may be given to set the desired error handling scheme. The
   default error handler is ``'strict'`` meaning that decoding errors raise
   :exc:`ValueError` (or a more codec specific subclass, such as
   :exc:`UnicodeDecodeError`). Refer to :ref:`codec-base-classes` for more
   information on codec error handling.

   .. versionadded:: 2.4

.. function:: register(search_function)

   Register a codec search function. Search functions are expected to take one
   argument, the encoding name in all lower case letters, and return a
   :class:`CodecInfo` object having the following attributes:

   * ``name`` The name of the encoding;

   * ``encode`` The stateless encoding function;

   * ``decode`` The stateless decoding function;

   * ``incrementalencoder`` An incremental encoder class or factory function;

   * ``incrementaldecoder`` An incremental decoder class or factory function;

   * ``streamwriter`` A stream writer class or factory function;

   * ``streamreader`` A stream reader class or factory function.

   The various functions or classes take the following arguments:

   *encode* and *decode*: These must be functions or methods which have the same
   interface as the :meth:`~Codec.encode`/:meth:`~Codec.decode` methods of Codec
   instances (see :ref:`Codec Interface <codec-objects>`). The functions/methods
   are expected to work in a stateless mode.

   *incrementalencoder* and *incrementaldecoder*: These have to be factory
   functions providing the following interface:

      ``factory(errors='strict')``

   The factory functions must return objects providing the interfaces defined by
   the base classes :class:`IncrementalEncoder` and :class:`IncrementalDecoder`,
   respectively. Incremental codecs can maintain state.

   *streamreader* and *streamwriter*: These have to be factory functions providing
   the following interface:

      ``factory(stream, errors='strict')``

   The factory functions must return objects providing the interfaces defined by
   the base classes :class:`StreamReader` and :class:`StreamWriter`, respectively.
   Stream codecs can maintain state.

   Possible values for errors are

   * ``'strict'``: raise an exception in case of an encoding error
   * ``'replace'``: replace malformed data with a suitable replacement marker,
     such as ``'?'`` or ``'\ufffd'``
   * ``'ignore'``: ignore malformed data and continue without further notice
   * ``'xmlcharrefreplace'``: replace with the appropriate XML character
     reference (for encoding only)
   * ``'backslashreplace'``: replace with backslashed escape sequences (for
     encoding only)

   as well as any other error handling name defined via :func:`register_error`.

   In case a search function cannot find a given encoding, it should return
   ``None``.


.. function:: lookup(encoding)

   Looks up the codec info in the Python codec registry and returns a
   :class:`CodecInfo` object as defined above.

   Encodings are first looked up in the registry's cache. If not found, the list of
   registered search functions is scanned. If no :class:`CodecInfo` object is
   found, a :exc:`LookupError` is raised. Otherwise, the :class:`CodecInfo` object
   is stored in the cache and returned to the caller.

To simplify access to the various codecs, the module provides these additional
functions which use :func:`lookup` for the codec lookup:


.. function:: getencoder(encoding)

   Look up the codec for the given encoding and return its encoder function.

   Raises a :exc:`LookupError` in case the encoding cannot be found.


.. function:: getdecoder(encoding)

   Look up the codec for the given encoding and return its decoder function.

   Raises a :exc:`LookupError` in case the encoding cannot be found.


.. function:: getincrementalencoder(encoding)

   Look up the codec for the given encoding and return its incremental encoder
   class or factory function.

   Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
   doesn't support an incremental encoder.

   .. versionadded:: 2.5


.. function:: getincrementaldecoder(encoding)

   Look up the codec for the given encoding and return its incremental decoder
   class or factory function.

   Raises a :exc:`LookupError` in case the encoding cannot be found or the codec
   doesn't support an incremental decoder.

   .. versionadded:: 2.5


.. function:: getreader(encoding)

   Look up the codec for the given encoding and return its StreamReader class or
   factory function.

   Raises a :exc:`LookupError` in case the encoding cannot be found.


.. function:: getwriter(encoding)

   Look up the codec for the given encoding and return its StreamWriter class or
   factory function.

   Raises a :exc:`LookupError` in case the encoding cannot be found.


.. function:: register_error(name, error_handler)

   Register the error handling function *error_handler* under the name *name*.
   *error_handler* will be called during encoding and decoding in case of an error,
   when *name* is specified as the errors parameter.

   For encoding *error_handler* will be called with a :exc:`UnicodeEncodeError`
   instance, which contains information about the location of the error. The error
   handler must either raise this or a different exception or return a tuple with a
   replacement for the unencodable part of the input and a position where encoding
   should continue. The encoder will encode the replacement and continue encoding
   the original input at the specified position. Negative position values will be
   treated as being relative to the end of the input string. If the resulting
   position is out of bound an :exc:`IndexError` will be raised.

   Decoding and translating works similar, except :exc:`UnicodeDecodeError` or
   :exc:`UnicodeTranslateError` will be passed to the handler and that the
   replacement from the error handler will be put into the output directly.


.. function:: lookup_error(name)

   Return the error handler previously registered under the name *name*.

   Raises a :exc:`LookupError` in case the handler cannot be found.


.. function:: strict_errors(exception)

   Implements the ``strict`` error handling: each encoding or decoding error
   raises a :exc:`UnicodeError`.


.. function:: replace_errors(exception)

   Implements the ``replace`` error handling: malformed data is replaced with a
   suitable replacement character such as ``'?'`` in bytestrings and
   ``'\ufffd'`` in Unicode strings.


.. function:: ignore_errors(exception)

   Implements the ``ignore`` error handling: malformed data is ignored and
   encoding or decoding is continued without further notice.


.. function:: xmlcharrefreplace_errors(exception)

   Implements the ``xmlcharrefreplace`` error handling (for encoding only): the
   unencodable character is replaced by an appropriate XML character reference.


.. function:: backslashreplace_errors(exception)

   Implements the ``backslashreplace`` error handling (for encoding only): the
   unencodable character is replaced by a backslashed escape sequence.

To simplify working with encoded files or stream, the module also defines these
utility functions:


.. function:: open(filename, mode[, encoding[, errors[, buffering]]])

   Open an encoded file using the given *mode* and return a wrapped version
   providing transparent encoding/decoding.  The default file mode is ``'r'``
   meaning to open the file in read mode.

   .. note::

      The wrapped version will only accept the object format defined by the codecs,
      i.e. Unicode objects for most built-in codecs.  Output is also codec-dependent
      and will usually be Unicode as well.

   .. note::

      Files are always opened in binary mode, even if no binary mode was
      specified.  This is done to avoid data loss due to encodings using 8-bit
      values.  This means that no automatic conversion of ``'\n'`` is done
      on reading and writing.

   *encoding* specifies the encoding which is to be used for the file.

   *errors* may be given to define the error handling. It defaults to ``'strict'``
   which causes a :exc:`ValueError` to be raised in case an encoding error occurs.

   *buffering* has the same meaning as for the built-in :func:`open` function.  It
   defaults to line buffered.


.. function:: EncodedFile(file, input[, output[, errors]])

   Return a wrapped version of file which provides transparent encoding
   translation.

   Strings written to the wrapped file are interpreted according to the given
   *input* encoding and then written to the original file as strings using the
   *output* encoding. The intermediate encoding will usually be Unicode but depends
   on the specified codecs.

   If *output* is not given, it defaults to *input*.

   *errors* may be given to define the error handling. It defaults to ``'strict'``,
   which causes :exc:`ValueError` to be raised in case an encoding error occurs.


.. function:: iterencode(iterable, encoding[, errors])

   Uses an incremental encoder to iteratively encode the input provided by
   *iterable*. This function is a :term:`generator`.  *errors* (as well as any
   other keyword argument) is passed through to the incremental encoder.

   .. versionadded:: 2.5


.. function:: iterdecode(iterable, encoding[, errors])

   Uses an incremental decoder to iteratively decode the input provided by
   *iterable*. This function is a :term:`generator`.  *errors* (as well as any
   other keyword argument) is passed through to the incremental decoder.

   .. versionadded:: 2.5

The module also provides the following constants which are useful for reading
and writing to platform dependent files:


.. data:: BOM
          BOM_BE
          BOM_LE
          BOM_UTF8
          BOM_UTF16
          BOM_UTF16_BE
          BOM_UTF16_LE
          BOM_UTF32
          BOM_UTF32_BE
          BOM_UTF32_LE

   These constants define various encodings of the Unicode byte order mark (BOM)
   used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
   stream or file and in UTF-8 as a Unicode signature. :const:`BOM_UTF16` is either
   :const:`BOM_UTF16_BE` or :const:`BOM_UTF16_LE` depending on the platform's
   native byte order, :const:`BOM` is an alias for :const:`BOM_UTF16`,
   :const:`BOM_LE` for :const:`BOM_UTF16_LE` and :const:`BOM_BE` for
   :const:`BOM_UTF16_BE`. The others represent the BOM in UTF-8 and UTF-32
   encodings.


.. _codec-base-classes:

Codec Base Classes
------------------

The :mod:`codecs` module defines a set of base classes which define the
interface and can also be used to easily write your own codecs for use in
Python.

Each codec has to define four interfaces to make it usable as codec in Python:
stateless encoder, stateless decoder, stream reader and stream writer. The
stream reader and writers typically reuse the stateless encoder/decoder to
implement the file protocols.

The :class:`Codec` class defines the interface for stateless encoders/decoders.

To simplify and standardize error handling, the :meth:`~Codec.encode` and
:meth:`~Codec.decode` methods may implement different error handling schemes by
providing the *errors* string argument.  The following string values are defined
and implemented by all standard Python codecs:

.. tabularcolumns:: |l|L|

+-------------------------+-----------------------------------------------+
| Value                   | Meaning                                       |
+=========================+===============================================+
| ``'strict'``            | Raise :exc:`UnicodeError` (or a subclass);    |
|                         | this is the default.                          |
+-------------------------+-----------------------------------------------+
| ``'ignore'``            | Ignore the character and continue with the    |
|                         | next.                                         |
+-------------------------+-----------------------------------------------+
| ``'replace'``           | Replace with a suitable replacement           |
|                         | character; Python will use the official       |
|                         | U+FFFD REPLACEMENT CHARACTER for the built-in |
|                         | Unicode codecs on decoding and '?' on         |
|                         | encoding.                                     |
+-------------------------+-----------------------------------------------+
| ``'xmlcharrefreplace'`` | Replace with the appropriate XML character    |
|                         | reference (only for encoding).                |
+-------------------------+-----------------------------------------------+
| ``'backslashreplace'``  | Replace with backslashed escape sequences     |
|                         | (only for encoding).                          |
+-------------------------+-----------------------------------------------+

The set of allowed values can be extended via :meth:`register_error`.


.. _codec-objects:

Codec Objects
^^^^^^^^^^^^^

The :class:`Codec` class defines these methods which also define the function
interfaces of the stateless encoder and decoder:


.. method:: Codec.encode(input[, errors])

   Encodes the object *input* and returns a tuple (output object, length consumed).
   While codecs are not restricted to use with Unicode, in a Unicode context,
   encoding converts a Unicode object to a plain string using a particular
   character set encoding (e.g., ``cp1252`` or ``iso-8859-1``).

   *errors* defines the error handling to apply. It defaults to ``'strict'``
   handling.

   The method may not store state in the :class:`Codec` instance. Use
   :class:`StreamWriter` for codecs which have to keep state in order to make
   encoding efficient.

   The encoder must be able to handle zero length input and return an empty object
   of the output object type in this situation.


.. method:: Codec.decode(input[, errors])

   Decodes the object *input* and returns a tuple (output object, length consumed).
   In a Unicode context, decoding converts a plain string encoded using a
   particular character set encoding to a Unicode object.

   *input* must be an object which provides the ``bf_getreadbuf`` buffer slot.
   Python strings, buffer objects and memory mapped files are examples of objects
   providing this slot.

   *errors* defines the error handling to apply. It defaults to ``'strict'``
   handling.

   The method may not store state in the :class:`Codec` instance. Use
   :class:`StreamReader` for codecs which have to keep state in order to make
   decoding efficient.

   The decoder must be able to handle zero length input and return an empty object
   of the output object type in this situation.

The :class:`IncrementalEncoder` and :class:`IncrementalDecoder` classes provide
the basic interface for incremental encoding and decoding. Encoding/decoding the
input isn't done with one call to the stateless encoder/decoder function, but
with multiple calls to the
:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method of
the incremental encoder/decoder. The incremental encoder/decoder keeps track of
the encoding/decoding process during method calls.

The joined output of calls to the
:meth:`~IncrementalEncoder.encode`/:meth:`~IncrementalDecoder.decode` method is
the same as if all the single inputs were joined into one, and this input was
encoded/decoded with the stateless encoder/decoder.


.. _incremental-encoder-objects:

IncrementalEncoder Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 2.5

The :class:`IncrementalEncoder` class is used for encoding an input in multiple
steps. It defines the following methods which every incremental encoder must
define in order to be compatible with the Python codec registry.


.. class:: IncrementalEncoder([errors])

   Constructor for an :class:`IncrementalEncoder` instance.

   All incremental encoders must provide this constructor interface. They are free
   to add additional keyword arguments, but only the ones defined here are used by
   the Python codec registry.

   The :class:`IncrementalEncoder` may implement different error handling schemes
   by providing the *errors* keyword argument. These parameters are predefined:

   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.

   * ``'ignore'`` Ignore the character and continue with the next.

   * ``'replace'`` Replace with a suitable replacement character

   * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference

   * ``'backslashreplace'`` Replace with backslashed escape sequences.

   The *errors* argument will be assigned to an attribute of the same name.
   Assigning to this attribute makes it possible to switch between different error
   handling strategies during the lifetime of the :class:`IncrementalEncoder`
   object.

   The set of allowed values for the *errors* argument can be extended with
   :func:`register_error`.


   .. method:: encode(object[, final])

      Encodes *object* (taking the current state of the encoder into account)
      and returns the resulting encoded object. If this is the last call to
      :meth:`encode` *final* must be true (the default is false).


   .. method:: reset()

      Reset the encoder to the initial state.


.. _incremental-decoder-objects:

IncrementalDecoder Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^

The :class:`IncrementalDecoder` class is used for decoding an input in multiple
steps. It defines the following methods which every incremental decoder must
define in order to be compatible with the Python codec registry.


.. class:: IncrementalDecoder([errors])

   Constructor for an :class:`IncrementalDecoder` instance.

   All incremental decoders must provide this constructor interface. They are free
   to add additional keyword arguments, but only the ones defined here are used by
   the Python codec registry.

   The :class:`IncrementalDecoder` may implement different error handling schemes
   by providing the *errors* keyword argument. These parameters are predefined:

   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.

   * ``'ignore'`` Ignore the character and continue with the next.

   * ``'replace'`` Replace with a suitable replacement character.

   The *errors* argument will be assigned to an attribute of the same name.
   Assigning to this attribute makes it possible to switch between different error
   handling strategies during the lifetime of the :class:`IncrementalDecoder`
   object.

   The set of allowed values for the *errors* argument can be extended with
   :func:`register_error`.


   .. method:: decode(object[, final])

      Decodes *object* (taking the current state of the decoder into account)
      and returns the resulting decoded object. If this is the last call to
      :meth:`decode` *final* must be true (the default is false). If *final* is
      true the decoder must decode the input completely and must flush all
      buffers. If this isn't possible (e.g. because of incomplete byte sequences
      at the end of the input) it must initiate error handling just like in the
      stateless case (which might raise an exception).


   .. method:: reset()

      Reset the decoder to the initial state.


The :class:`StreamWriter` and :class:`StreamReader` classes provide generic
working interfaces which can be used to implement new encoding submodules very
easily. See :mod:`encodings.utf_8` for an example of how this is done.


.. _stream-writer-objects:

StreamWriter Objects
^^^^^^^^^^^^^^^^^^^^

The :class:`StreamWriter` class is a subclass of :class:`Codec` and defines the
following methods which every stream writer must define in order to be
compatible with the Python codec registry.


.. class:: StreamWriter(stream[, errors])

   Constructor for a :class:`StreamWriter` instance.

   All stream writers must provide this constructor interface. They are free to add
   additional keyword arguments, but only the ones defined here are used by the
   Python codec registry.

   *stream* must be a file-like object open for writing binary data.

   The :class:`StreamWriter` may implement different error handling schemes by
   providing the *errors* keyword argument. These parameters are predefined:

   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.

   * ``'ignore'`` Ignore the character and continue with the next.

   * ``'replace'`` Replace with a suitable replacement character

   * ``'xmlcharrefreplace'`` Replace with the appropriate XML character reference

   * ``'backslashreplace'`` Replace with backslashed escape sequences.

   The *errors* argument will be assigned to an attribute of the same name.
   Assigning to this attribute makes it possible to switch between different error
   handling strategies during the lifetime of the :class:`StreamWriter` object.

   The set of allowed values for the *errors* argument can be extended with
   :func:`register_error`.


   .. method:: write(object)

      Writes the object's contents encoded to the stream.


   .. method:: writelines(list)

      Writes the concatenated list of strings to the stream (possibly by reusing
      the :meth:`write` method).


   .. method:: reset()

      Flushes and resets the codec buffers used for keeping state.

      Calling this method should ensure that the data on the output is put into
      a clean state that allows appending of new fresh data without having to
      rescan the whole stream to recover state.


In addition to the above methods, the :class:`StreamWriter` must also inherit
all other methods and attributes from the underlying stream.


.. _stream-reader-objects:

StreamReader Objects
^^^^^^^^^^^^^^^^^^^^

The :class:`StreamReader` class is a subclass of :class:`Codec` and defines the
following methods which every stream reader must define in order to be
compatible with the Python codec registry.


.. class:: StreamReader(stream[, errors])

   Constructor for a :class:`StreamReader` instance.

   All stream readers must provide this constructor interface. They are free to add
   additional keyword arguments, but only the ones defined here are used by the
   Python codec registry.

   *stream* must be a file-like object open for reading (binary) data.

   The :class:`StreamReader` may implement different error handling schemes by
   providing the *errors* keyword argument. These parameters are defined:

   * ``'strict'`` Raise :exc:`ValueError` (or a subclass); this is the default.

   * ``'ignore'`` Ignore the character and continue with the next.

   * ``'replace'`` Replace with a suitable replacement character.

   The *errors* argument will be assigned to an attribute of the same name.
   Assigning to this attribute makes it possible to switch between different error
   handling strategies during the lifetime of the :class:`StreamReader` object.

   The set of allowed values for the *errors* argument can be extended with
   :func:`register_error`.


   .. method:: read([size[, chars, [firstline]]])

      Decodes data from the stream and returns the resulting object.

      *chars* indicates the number of characters to read from the
      stream. :func:`read` will never return more than *chars* characters, but
      it might return less, if there are not enough characters available.

      *size* indicates the approximate maximum number of bytes to read from the
      stream for decoding purposes. The decoder can modify this setting as
      appropriate. The default value -1 indicates to read and decode as much as
      possible.  *size* is intended to prevent having to decode huge files in
      one step.

      *firstline* indicates that it would be sufficient to only return the first
      line, if there are decoding errors on later lines.

      The method should use a greedy read strategy meaning that it should read
      as much data as is allowed within the definition of the encoding and the
      given size, e.g.  if optional encoding endings or state markers are
      available on the stream, these should be read too.

      .. versionchanged:: 2.4
         *chars* argument added.

      .. versionchanged:: 2.4.2
         *firstline* argument added.


   .. method:: readline([size[, keepends]])

      Read one line from the input stream and return the decoded data.

      *size*, if given, is passed as size argument to the stream's
      :meth:`read` method.

      If *keepends* is false line-endings will be stripped from the lines
      returned.

      .. versionchanged:: 2.4
         *keepends* argument added.


   .. method:: readlines([sizehint[, keepends]])

      Read all lines available on the input stream and return them as a list of
      lines.

      Line-endings are implemented using the codec's decoder method and are
      included in the list entries if *keepends* is true.

      *sizehint*, if given, is passed as the *size* argument to the stream's
      :meth:`read` method.


   .. method:: reset()

      Resets the codec buffers used for keeping state.

      Note that no stream repositioning should take place.  This method is
      primarily intended to be able to recover from decoding errors.


In addition to the above methods, the :class:`StreamReader` must also inherit
all other methods and attributes from the underlying stream.

The next two base classes are included for convenience. They are not needed by
the codec registry, but may provide useful in practice.


.. _stream-reader-writer:

StreamReaderWriter Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^

The :class:`StreamReaderWriter` allows wrapping streams which work in both read
and write modes.

The design is such that one can use the factory functions returned by the
:func:`lookup` function to construct the instance.


.. class:: StreamReaderWriter(stream, Reader, Writer, errors)

   Creates a :class:`StreamReaderWriter` instance. *stream* must be a file-like
   object. *Reader* and *Writer* must be factory functions or classes providing the
   :class:`StreamReader` and :class:`StreamWriter` interface resp. Error handling
   is done in the same way as defined for the stream readers and writers.

:class:`StreamReaderWriter` instances define the combined interfaces of
:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
methods and attributes from the underlying stream.


.. _stream-recoder-objects:

StreamRecoder Objects
^^^^^^^^^^^^^^^^^^^^^

The :class:`StreamRecoder` provide a frontend - backend view of encoding data
which is sometimes useful when dealing with different encoding environments.

The design is such that one can use the factory functions returned by the
:func:`lookup` function to construct the instance.


.. class:: StreamRecoder(stream, encode, decode, Reader, Writer, errors)

   Creates a :class:`StreamRecoder` instance which implements a two-way conversion:
   *encode* and *decode* work on the frontend (the input to :meth:`read` and output
   of :meth:`write`) while *Reader* and *Writer* work on the backend (reading and
   writing to the stream).

   You can use these objects to do transparent direct recodings from e.g. Latin-1
   to UTF-8 and back.

   *stream* must be a file-like object.

   *encode*, *decode* must adhere to the :class:`Codec` interface. *Reader*,
   *Writer* must be factory functions or classes providing objects of the
   :class:`StreamReader` and :class:`StreamWriter` interface respectively.

   *encode* and *decode* are needed for the frontend translation, *Reader* and
   *Writer* for the backend translation.  The intermediate format used is
   determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
   as the intermediate encoding.

   Error handling is done in the same way as defined for the stream readers and
   writers.


:class:`StreamRecoder` instances define the combined interfaces of
:class:`StreamReader` and :class:`StreamWriter` classes. They inherit all other
methods and attributes from the underlying stream.


.. _encodings-overview:

Encodings and Unicode
---------------------

Unicode strings are stored internally as sequences of code points (to be precise
as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
via ``--enable-unicode=ucs2`` or ``--enable-unicode=ucs4``, with the
former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data
type. Once a Unicode object is used outside of CPU and memory, CPU endianness
and how these arrays are stored as bytes become an issue.  Transforming a
unicode object into a sequence of bytes is called encoding and recreating the
unicode object from the sequence of bytes is known as decoding.  There are many
different methods for how this transformation can be done (these methods are
also called encodings). The simplest method is to map the code points 0--255 to
the bytes ``0x0``--``0xff``. This means that a unicode object that contains
code points above ``U+00FF`` can't be encoded with this method (which is called
``'latin-1'`` or ``'iso-8859-1'``). :func:`unicode.encode` will raise a
:exc:`UnicodeEncodeError` that looks like this: ``UnicodeEncodeError: 'latin-1'
codec can't encode character u'\u1234' in position 3: ordinal not in
range(256)``.

There's another group of encodings (the so called charmap encodings) that choose
a different subset of all unicode code points and how these code points are
mapped to the bytes ``0x0``--``0xff``. To see how this is done simply open
e.g. :file:`encodings/cp1252.py` (which is an encoding that is used primarily on
Windows). There's a string constant with 256 characters that shows you which
character is mapped to which byte value.

All of these encodings can only encode 256 of the 1114112 code points
defined in unicode. A simple and straightforward way that can store each Unicode
code point, is to store each code point as four consecutive bytes. There are two
possibilities: store the bytes in big endian or in little endian order. These
two encodings are called ``UTF-32-BE`` and ``UTF-32-LE`` respectively. Their
disadvantage is that if e.g. you use ``UTF-32-BE`` on a little endian machine you
will always have to swap bytes on encoding and decoding. ``UTF-32`` avoids this
problem: bytes will always be in natural endianness. When these bytes are read
by a CPU with a different endianness, then bytes have to be swapped though. To
be able to detect the endianness of a ``UTF-16`` or ``UTF-32`` byte sequence,
there's the so called BOM ("Byte Order Mark"). This is the Unicode character
``U+FEFF``. This character can be prepended to every ``UTF-16`` or ``UTF-32``
byte sequence. The byte swapped version of this character (``0xFFFE``) is an
illegal character that may not appear in a Unicode text. So when the
first character in an ``UTF-16`` or ``UTF-32`` byte sequence
appears to be a ``U+FFFE`` the bytes have to be swapped on decoding.
Unfortunately the character ``U+FEFF`` had a second purpose as
a ``ZERO WIDTH NO-BREAK SPACE``: a character that has no width and doesn't allow
a word to be split. It can e.g. be used to give hints to a ligature algorithm.
With Unicode 4.0 using ``U+FEFF`` as a ``ZERO WIDTH NO-BREAK SPACE`` has been
deprecated (with ``U+2060`` (``WORD JOINER``) assuming this role). Nevertheless
Unicode software still must be able to handle ``U+FEFF`` in both roles: as a BOM
it's a device to determine the storage layout of the encoded bytes, and vanishes
once the byte sequence has been decoded into a Unicode string; as a ``ZERO WIDTH
NO-BREAK SPACE`` it's a normal character that will be decoded like any other.

There's another encoding that is able to encoding the full range of Unicode
characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
parts: marker bits (the most significant bits) and payload bits. The marker bits
are a sequence of zero to four ``1`` bits followed by a ``0`` bit. Unicode characters are
encoded like this (with x being payload bits, which when concatenated give the
Unicode character):

+-----------------------------------+----------------------------------------------+
| Range                             | Encoding                                     |
+===================================+==============================================+
| ``U-00000000`` ... ``U-0000007F`` | 0xxxxxxx                                     |
+-----------------------------------+----------------------------------------------+
| ``U-00000080`` ... ``U-000007FF`` | 110xxxxx 10xxxxxx                            |
+-----------------------------------+----------------------------------------------+
| ``U-00000800`` ... ``U-0000FFFF`` | 1110xxxx 10xxxxxx 10xxxxxx                   |
+-----------------------------------+----------------------------------------------+
| ``U-00010000`` ... ``U-0010FFFF`` | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx          |
+-----------------------------------+----------------------------------------------+

The least significant bit of the Unicode character is the rightmost x bit.

As UTF-8 is an 8-bit encoding no BOM is required and any ``U+FEFF`` character in
the decoded Unicode string (even if it's the first character) is treated as a
``ZERO WIDTH NO-BREAK SPACE``.

Without external information it's impossible to reliably determine which
encoding was used for encoding a Unicode string. Each charmap encoding can
decode any random byte sequence. However that's not possible with UTF-8, as
UTF-8 byte sequences have a structure that doesn't allow arbitrary byte
sequences. To increase the reliability with which a UTF-8 encoding can be
detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
``"utf-8-sig"``) for its Notepad program: Before any of the Unicode characters
is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
sequence: ``0xef``, ``0xbb``, ``0xbf``) is written. As it's rather improbable
that any charmap encoded file starts with these byte values (which would e.g.
map to

   | LATIN SMALL LETTER I WITH DIAERESIS
   | RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
   | INVERTED QUESTION MARK

in iso-8859-1), this increases the probability that a ``utf-8-sig`` encoding can be
correctly guessed from the byte sequence. So here the BOM is not used to be able
to determine the byte order used for generating the byte sequence, but as a
signature that helps in guessing the encoding. On encoding the utf-8-sig codec
will write ``0xef``, ``0xbb``, ``0xbf`` as the first three bytes to the file. On
decoding ``utf-8-sig`` will skip those three bytes if they appear as the first
three bytes in the file.  In UTF-8, the use of the BOM is discouraged and
should generally be avoided.


.. _standard-encodings:

Standard Encodings
------------------

Python comes with a number of codecs built-in, either implemented as C functions
or with dictionaries as mapping tables. The following table lists the codecs by
name, together with a few common aliases, and the languages for which the
encoding is likely used. Neither the list of aliases nor the list of languages
is meant to be exhaustive. Notice that spelling alternatives that only differ in
case or use a hyphen instead of an underscore are also valid aliases; therefore,
e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.

Many of the character sets support the same languages. They vary in individual
characters (e.g. whether the EURO SIGN is supported or not), and in the
assignment of characters to code positions. For the European languages in
particular, the following variants typically exist:

* an ISO 8859 codeset

* a Microsoft Windows code page, which is typically derived from an 8859 codeset,
  but replaces control characters with additional graphic characters

* an IBM EBCDIC code page

* an IBM PC code page, which is ASCII compatible

.. tabularcolumns:: |l|p{0.3\linewidth}|p{0.3\linewidth}|

+-----------------+--------------------------------+--------------------------------+
| Codec           | Aliases                        | Languages                      |
+=================+================================+================================+
| ascii           | 646, us-ascii                  | English                        |
+-----------------+--------------------------------+--------------------------------+
| big5            | big5-tw, csbig5                | Traditional Chinese            |
+-----------------+--------------------------------+--------------------------------+
| big5hkscs       | big5-hkscs, hkscs              | Traditional Chinese            |
+-----------------+--------------------------------+--------------------------------+
| cp037           | IBM037, IBM039                 | English                        |
+-----------------+--------------------------------+--------------------------------+
| cp424           | EBCDIC-CP-HE, IBM424           | Hebrew                         |
+-----------------+--------------------------------+--------------------------------+
| cp437           | 437, IBM437                    | English                        |
+-----------------+--------------------------------+--------------------------------+
| cp500           | EBCDIC-CP-BE, EBCDIC-CP-CH,    | Western Europe                 |
|                 | IBM500                         |                                |
+-----------------+--------------------------------+--------------------------------+
| cp720           |                                | Arabic                         |
+-----------------+--------------------------------+--------------------------------+
| cp737           |                                | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| cp775           | IBM775                         | Baltic languages               |
+-----------------+--------------------------------+--------------------------------+
| cp850           | 850, IBM850                    | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| cp852           | 852, IBM852                    | Central and Eastern Europe     |
+-----------------+--------------------------------+--------------------------------+
| cp855           | 855, IBM855                    | Bulgarian, Byelorussian,       |
|                 |                                | Macedonian, Russian, Serbian   |
+-----------------+--------------------------------+--------------------------------+
| cp856           |                                | Hebrew                         |
+-----------------+--------------------------------+--------------------------------+
| cp857           | 857, IBM857                    | Turkish                        |
+-----------------+--------------------------------+--------------------------------+
| cp858           | 858, IBM858                    | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| cp860           | 860, IBM860                    | Portuguese                     |
+-----------------+--------------------------------+--------------------------------+
| cp861           | 861, CP-IS, IBM861             | Icelandic                      |
+-----------------+--------------------------------+--------------------------------+
| cp862           | 862, IBM862                    | Hebrew                         |
+-----------------+--------------------------------+--------------------------------+
| cp863           | 863, IBM863                    | Canadian                       |
+-----------------+--------------------------------+--------------------------------+
| cp864           | IBM864                         | Arabic                         |
+-----------------+--------------------------------+--------------------------------+
| cp865           | 865, IBM865                    | Danish, Norwegian              |
+-----------------+--------------------------------+--------------------------------+
| cp866           | 866, IBM866                    | Russian                        |
+-----------------+--------------------------------+--------------------------------+
| cp869           | 869, CP-GR, IBM869             | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| cp874           |                                | Thai                           |
+-----------------+--------------------------------+--------------------------------+
| cp875           |                                | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| cp932           | 932, ms932, mskanji, ms-kanji  | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| cp949           | 949, ms949, uhc                | Korean                         |
+-----------------+--------------------------------+--------------------------------+
| cp950           | 950, ms950                     | Traditional Chinese            |
+-----------------+--------------------------------+--------------------------------+
| cp1006          |                                | Urdu                           |
+-----------------+--------------------------------+--------------------------------+
| cp1026          | ibm1026                        | Turkish                        |
+-----------------+--------------------------------+--------------------------------+
| cp1140          | ibm1140                        | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| cp1250          | windows-1250                   | Central and Eastern Europe     |
+-----------------+--------------------------------+--------------------------------+
| cp1251          | windows-1251                   | Bulgarian, Byelorussian,       |
|                 |                                | Macedonian, Russian, Serbian   |
+-----------------+--------------------------------+--------------------------------+
| cp1252          | windows-1252                   | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| cp1253          | windows-1253                   | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| cp1254          | windows-1254                   | Turkish                        |
+-----------------+--------------------------------+--------------------------------+
| cp1255          | windows-1255                   | Hebrew                         |
+-----------------+--------------------------------+--------------------------------+
| cp1256          | windows-1256                   | Arabic                         |
+-----------------+--------------------------------+--------------------------------+
| cp1257          | windows-1257                   | Baltic languages               |
+-----------------+--------------------------------+--------------------------------+
| cp1258          | windows-1258                   | Vietnamese                     |
+-----------------+--------------------------------+--------------------------------+
| euc_jp          | eucjp, ujis, u-jis             | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| euc_jis_2004    | jisx0213, eucjis2004           | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| euc_jisx0213    | eucjisx0213                    | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| euc_kr          | euckr, korean, ksc5601,        | Korean                         |
|                 | ks_c-5601, ks_c-5601-1987,     |                                |
|                 | ksx1001, ks_x-1001             |                                |
+-----------------+--------------------------------+--------------------------------+
| gb2312          | chinese, csiso58gb231280, euc- | Simplified Chinese             |
|                 | cn, euccn, eucgb2312-cn,       |                                |
|                 | gb2312-1980, gb2312-80, iso-   |                                |
|                 | ir-58                          |                                |
+-----------------+--------------------------------+--------------------------------+
| gbk             | 936, cp936, ms936              | Unified Chinese                |
+-----------------+--------------------------------+--------------------------------+
| gb18030         | gb18030-2000                   | Unified Chinese                |
+-----------------+--------------------------------+--------------------------------+
| hz              | hzgb, hz-gb, hz-gb-2312        | Simplified Chinese             |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp      | csiso2022jp, iso2022jp,        | Japanese                       |
|                 | iso-2022-jp                    |                                |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp_1    | iso2022jp-1, iso-2022-jp-1     | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp_2    | iso2022jp-2, iso-2022-jp-2     | Japanese, Korean, Simplified   |
|                 |                                | Chinese, Western Europe, Greek |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp_2004 | iso2022jp-2004,                | Japanese                       |
|                 | iso-2022-jp-2004               |                                |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp_3    | iso2022jp-3, iso-2022-jp-3     | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| iso2022_jp_ext  | iso2022jp-ext, iso-2022-jp-ext | Japanese                       |
+-----------------+--------------------------------+--------------------------------+
| iso2022_kr      | csiso2022kr, iso2022kr,        | Korean                         |
|                 | iso-2022-kr                    |                                |
+-----------------+--------------------------------+--------------------------------+
| latin_1         | iso-8859-1, iso8859-1, 8859,   | West Europe                    |
|                 | cp819, latin, latin1, L1       |                                |
+-----------------+--------------------------------+--------------------------------+
| iso8859_2       | iso-8859-2, latin2, L2         | Central and Eastern Europe     |
+-----------------+--------------------------------+--------------------------------+
| iso8859_3       | iso-8859-3, latin3, L3         | Esperanto, Maltese             |
+-----------------+--------------------------------+--------------------------------+
| iso8859_4       | iso-8859-4, latin4, L4         | Baltic languages               |
+-----------------+--------------------------------+--------------------------------+
| iso8859_5       | iso-8859-5, cyrillic           | Bulgarian, Byelorussian,       |
|                 |                                | Macedonian, Russian, Serbian   |
+-----------------+--------------------------------+--------------------------------+
| iso8859_6       | iso-8859-6, arabic             | Arabic                         |
+-----------------+--------------------------------+--------------------------------+
| iso8859_7       | iso-8859-7, greek, greek8      | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| iso8859_8       | iso-8859-8, hebrew             | Hebrew                         |
+-----------------+--------------------------------+--------------------------------+
| iso8859_9       | iso-8859-9, latin5, L5         | Turkish                        |
+-----------------+--------------------------------+--------------------------------+
| iso8859_10      | iso-8859-10, latin6, L6        | Nordic languages               |
+-----------------+--------------------------------+--------------------------------+
| iso8859_11      | iso-8859-11, thai              | Thai languages                 |
+-----------------+--------------------------------+--------------------------------+
| iso8859_13      | iso-8859-13, latin7, L7        | Baltic languages               |
+-----------------+--------------------------------+--------------------------------+
| iso8859_14      | iso-8859-14, latin8, L8        | Celtic languages               |
+-----------------+--------------------------------+--------------------------------+
| iso8859_15      | iso-8859-15, latin9, L9        | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| iso8859_16      | iso-8859-16, latin10, L10      | South-Eastern Europe           |
+-----------------+--------------------------------+--------------------------------+
| johab           | cp1361, ms1361                 | Korean                         |
+-----------------+--------------------------------+--------------------------------+
| koi8_r          |                                | Russian                        |
+-----------------+--------------------------------+--------------------------------+
| koi8_u          |                                | Ukrainian                      |
+-----------------+--------------------------------+--------------------------------+
| mac_cyrillic    | maccyrillic                    | Bulgarian, Byelorussian,       |
|                 |                                | Macedonian, Russian, Serbian   |
+-----------------+--------------------------------+--------------------------------+
| mac_greek       | macgreek                       | Greek                          |
+-----------------+--------------------------------+--------------------------------+
| mac_iceland     | maciceland                     | Icelandic                      |
+-----------------+--------------------------------+--------------------------------+
| mac_latin2      | maclatin2, maccentraleurope    | Central and Eastern Europe     |
+-----------------+--------------------------------+--------------------------------+
| mac_roman       | macroman                       | Western Europe                 |
+-----------------+--------------------------------+--------------------------------+
| mac_turkish     | macturkish                     | Turkish                        |
+-----------------+--------------------------------+--------------------------------+
| ptcp154         | csptcp154, pt154, cp154,       | Kazakh                         |
|                 | cyrillic-asian                 |                                |
+-----------------+--------------------------------+--------------------------------+
| shift_jis       | csshiftjis, shiftjis, sjis,    | Japanese                       |
|                 | s_jis                          |                                |
+-----------------+--------------------------------+--------------------------------+
| shift_jis_2004  | shiftjis2004, sjis_2004,       | Japanese                       |
|                 | sjis2004                       |                                |
+-----------------+--------------------------------+--------------------------------+
| shift_jisx0213  | shiftjisx0213, sjisx0213,      | Japanese                       |
|                 | s_jisx0213                     |                                |
+-----------------+--------------------------------+--------------------------------+
| utf_32          | U32, utf32                     | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_32_be       | UTF-32BE                       | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_32_le       | UTF-32LE                       | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_16          | U16, utf16                     | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_16_be       | UTF-16BE                       | all languages (BMP only)       |
+-----------------+--------------------------------+--------------------------------+
| utf_16_le       | UTF-16LE                       | all languages (BMP only)       |
+-----------------+--------------------------------+--------------------------------+
| utf_7           | U7, unicode-1-1-utf-7          | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_8           | U8, UTF, utf8                  | all languages                  |
+-----------------+--------------------------------+--------------------------------+
| utf_8_sig       |                                | all languages                  |
+-----------------+--------------------------------+--------------------------------+

Python Specific Encodings
-------------------------

A number of predefined codecs are specific to Python, so their codec names have
no meaning outside Python.  These are listed in the tables below based on the
expected input and output types (note that while text encodings are the most
common use case for codecs, the underlying codec infrastructure supports
arbitrary data transforms rather than just text encodings).  For asymmetric
codecs, the stated purpose describes the encoding direction.

The following codecs provide unicode-to-str encoding [#encoding-note]_ and
str-to-unicode decoding [#decoding-note]_, similar to the Unicode text
encodings.

.. tabularcolumns:: |l|L|L|

+--------------------+---------------------------+---------------------------+
| Codec              | Aliases                   | Purpose                   |
+====================+===========================+===========================+
| idna               |                           | Implements :rfc:`3490`,   |
|                    |                           | see also                  |
|                    |                           | :mod:`encodings.idna`     |
+--------------------+---------------------------+---------------------------+
| mbcs               | dbcs                      | Windows only: Encode      |
|                    |                           | operand according to the  |
|                    |                           | ANSI codepage (CP_ACP)    |
+--------------------+---------------------------+---------------------------+
| palmos             |                           | Encoding of PalmOS 3.5    |
+--------------------+---------------------------+---------------------------+
| punycode           |                           | Implements :rfc:`3492`    |
+--------------------+---------------------------+---------------------------+
| raw_unicode_escape |                           | Produce a string that is  |
|                    |                           | suitable as raw Unicode   |
|                    |                           | literal in Python source  |
|                    |                           | code                      |
+--------------------+---------------------------+---------------------------+
| rot_13             | rot13                     | Returns the Caesar-cypher |
|                    |                           | encryption of the operand |
+--------------------+---------------------------+---------------------------+
| undefined          |                           | Raise an exception for    |
|                    |                           | all conversions. Can be   |
|                    |                           | used as the system        |
|                    |                           | encoding if no automatic  |
|                    |                           | :term:`coercion` between  |
|                    |                           | byte and Unicode strings  |
|                    |                           | is desired.               |
+--------------------+---------------------------+---------------------------+
| unicode_escape     |                           | Produce a string that is  |
|                    |                           | suitable as Unicode       |
|                    |                           | literal in Python source  |
|                    |                           | code                      |
+--------------------+---------------------------+---------------------------+
| unicode_internal   |                           | Return the internal       |
|                    |                           | representation of the     |
|                    |                           | operand                   |
+--------------------+---------------------------+---------------------------+

.. versionadded:: 2.3
   The ``idna`` and ``punycode`` encodings.

The following codecs provide str-to-str encoding and decoding
[#decoding-note]_.

.. tabularcolumns:: |l|L|L|L|

+--------------------+---------------------------+---------------------------+------------------------------+
| Codec              | Aliases                   | Purpose                   | Encoder/decoder              |
+====================+===========================+===========================+==============================+
| base64_codec       | base64, base-64           | Convert operand to        | :meth:`base64.encodestring`, |
|                    |                           | multiline MIME base64 (the| :meth:`base64.decodestring`  |
|                    |                           | result always includes a  |                              |
|                    |                           | trailing ``'\n'``)        |                              |
+--------------------+---------------------------+---------------------------+------------------------------+
| bz2_codec          | bz2                       | Compress the operand      | :meth:`bz2.compress`,        |
|                    |                           | using bz2                 | :meth:`bz2.decompress`       |
+--------------------+---------------------------+---------------------------+------------------------------+
| hex_codec          | hex                       | Convert operand to        | :meth:`binascii.b2a_hex`,    |
|                    |                           | hexadecimal               | :meth:`binascii.a2b_hex`     |
|                    |                           | representation, with two  |                              |
|                    |                           | digits per byte           |                              |
+--------------------+---------------------------+---------------------------+------------------------------+
| quopri_codec       | quopri, quoted-printable, | Convert operand to MIME   | :meth:`quopri.encode` with   |
|                    | quotedprintable           | quoted printable          | ``quotetabs=True``,          |
|                    |                           |                           | :meth:`quopri.decode`        |
+--------------------+---------------------------+---------------------------+------------------------------+
| string_escape      |                           | Produce a string that is  |                              |
|                    |                           | suitable as string        |                              |
|                    |                           | literal in Python source  |                              |
|                    |                           | code                      |                              |
+--------------------+---------------------------+---------------------------+------------------------------+
| uu_codec           | uu                        | Convert the operand using | :meth:`uu.encode`,           |
|                    |                           | uuencode                  | :meth:`uu.decode`            |
+--------------------+---------------------------+---------------------------+------------------------------+
| zlib_codec         | zip, zlib                 | Compress the operand      | :meth:`zlib.compress`,       |
|                    |                           | using gzip                | :meth:`zlib.decompress`      |
+--------------------+---------------------------+---------------------------+------------------------------+

.. [#encoding-note] str objects are also accepted as input in place of unicode
   objects.  They are implicitly converted to unicode by decoding them using
   the default encoding.  If this conversion fails, it may lead to encoding
   operations raising :exc:`UnicodeDecodeError`.

.. [#decoding-note] unicode objects are also accepted as input in place of str
   objects.  They are implicitly converted to str by encoding them using the
   default encoding.  If this conversion fails, it may lead to decoding
   operations raising :exc:`UnicodeEncodeError`.


:mod:`encodings.idna` --- Internationalized Domain Names in Applications
------------------------------------------------------------------------

.. module:: encodings.idna
   :synopsis: Internationalized Domain Names implementation
.. moduleauthor:: Martin v. Löwis

.. versionadded:: 2.3

This module implements :rfc:`3490` (Internationalized Domain Names in
Applications) and :rfc:`3492` (Nameprep: A Stringprep Profile for
Internationalized Domain Names (IDN)). It builds upon the ``punycode`` encoding
and :mod:`stringprep`.

These RFCs together define a protocol to support non-ASCII characters in domain
names. A domain name containing non-ASCII characters (such as
``www.Alliancefrançaise.nu``) is converted into an ASCII-compatible encoding
(ACE, such as ``www.xn--alliancefranaise-npb.nu``). The ACE form of the domain
name is then used in all places where arbitrary characters are not allowed by
the protocol, such as DNS queries, HTTP :mailheader:`Host` fields, and so
on. This conversion is carried out in the application; if possible invisible to
the user: The application should transparently convert Unicode domain labels to
IDNA on the wire, and convert back ACE labels to Unicode before presenting them
to the user.

Python supports this conversion in several ways:  the ``idna`` codec performs
conversion between Unicode and ACE, separating an input string into labels
based on the separator characters defined in `section 3.1`_ (1) of :rfc:`3490`
and converting each label to ACE as required, and conversely separating an input
byte string into labels based on the ``.`` separator and converting any ACE
labels found into unicode.  Furthermore, the :mod:`socket` module
transparently converts Unicode host names to ACE, so that applications need not
be concerned about converting host names themselves when they pass them to the
socket module. On top of that, modules that have host names as function
parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names
(:mod:`httplib` then also transparently sends an IDNA hostname in the
:mailheader:`Host` field if it sends that field at all).

.. _section 3.1: https://tools.ietf.org/html/rfc3490#section-3.1

When receiving host names from the wire (such as in reverse name lookup), no
automatic conversion to Unicode is performed: Applications wishing to present
such host names to the user should decode them to Unicode.

The module :mod:`encodings.idna` also implements the nameprep procedure, which
performs certain normalizations on host names, to achieve case-insensitivity of
international domain names, and to unify similar characters. The nameprep
functions can be used directly if desired.


.. function:: nameprep(label)

   Return the nameprepped version of *label*. The implementation currently assumes
   query strings, so ``AllowUnassigned`` is true.


.. function:: ToASCII(label)

   Convert a label to ASCII, as specified in :rfc:`3490`. ``UseSTD3ASCIIRules`` is
   assumed to be false.


.. function:: ToUnicode(label)

   Convert a label to Unicode, as specified in :rfc:`3490`.


:mod:`encodings.utf_8_sig` --- UTF-8 codec with BOM signature
-------------------------------------------------------------

.. module:: encodings.utf_8_sig
   :synopsis: UTF-8 codec with BOM signature
.. moduleauthor:: Walter Dörwald

.. versionadded:: 2.5

This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
is only done once (on the first write to the byte stream).  For decoding an
optional UTF-8 encoded BOM at the start of the data will be skipped.

PK	%�\��xʾ�$html/_sources/library/codeop.rst.txtnu�[���
:mod:`codeop` --- Compile Python code
=====================================

.. module:: codeop
   :synopsis: Compile (possibly incomplete) Python code.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
.. sectionauthor:: Michael Hudson <mwh@python.net>

The :mod:`codeop` module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the :mod:`code` module.  As
a result, you probably don't want to use the module directly; if you want to
include such a loop in your program you probably want to use the :mod:`code`
module instead.

There are two parts to this job:

#. Being able to tell if a line of input completes a Python  statement: in
   short, telling whether to print '``>>>``' or '``...``' next.

#. Remembering which future statements the user has entered, so  subsequent
   input can be compiled with these in effect.

The :mod:`codeop` module provides a way of doing each of these things, and a way
of doing them both.

To do just the former:

.. function:: compile_command(source[, filename[, symbol]])

   Tries to compile *source*, which should be a string of Python code and return a
   code object if *source* is valid Python code. In that case, the filename
   attribute of the code object will be *filename*, which defaults to
   ``'<input>'``. Returns ``None`` if *source* is *not* valid Python code, but is a
   prefix of valid Python code.

   If there is a problem with *source*, an exception will be raised.
   :exc:`SyntaxError` is raised if there is invalid Python syntax, and
   :exc:`OverflowError` or :exc:`ValueError` if there is an invalid literal.

   The *symbol* argument determines whether *source* is compiled as a statement
   (``'single'``, the default) or as an :term:`expression` (``'eval'``).  Any
   other value will cause :exc:`ValueError` to  be raised.

   .. note::

      It is possible (but not likely) that the parser stops parsing with a
      successful outcome before reaching the end of the source; in this case,
      trailing symbols may be ignored instead of causing an error.  For example,
      a backslash followed by two newlines may be followed by arbitrary garbage.
      This will be fixed once the API for the parser is better.


.. class:: Compile()

   Instances of this class have :meth:`__call__` methods identical in signature to
   the built-in function :func:`compile`, but with the difference that if the
   instance compiles program text containing a :mod:`__future__` statement, the
   instance 'remembers' and compiles all subsequent program texts with the
   statement in force.


.. class:: CommandCompiler()

   Instances of this class have :meth:`__call__` methods identical in signature to
   :func:`compile_command`; the difference is that if the instance compiles program
   text containing a ``__future__`` statement, the instance 'remembers' and
   compiles all subsequent program texts with the statement in force.

A note on version compatibility: the :class:`Compile` and
:class:`CommandCompiler` are new in Python 2.2.  If you want to enable the
future-tracking features of 2.2 but also retain compatibility with 2.1 and
earlier versions of Python you can either write ::

   try:
       from codeop import CommandCompiler
       compile_command = CommandCompiler()
       del CommandCompiler
   except ImportError:
       from codeop import compile_command

which is a low-impact change, but introduces possibly unwanted global state into
your program, or you can write::

   try:
       from codeop import CommandCompiler
   except ImportError:
       def CommandCompiler():
           from codeop import compile_command
           return compile_command

and then call ``CommandCompiler`` every time you need a fresh compiler object.

PK	%�\�@����)html/_sources/library/collections.rst.txtnu�[���:mod:`collections` --- High-performance container datatypes
===========================================================

.. module:: collections
   :synopsis: High-performance datatypes
.. moduleauthor:: Raymond Hettinger <python@rcn.com>
.. sectionauthor:: Raymond Hettinger <python@rcn.com>

.. versionadded:: 2.4

.. testsetup:: *

   from collections import *
   import itertools
   __name__ = '<doctest>'

**Source code:** :source:`Lib/collections.py` and :source:`Lib/_abcoll.py`

--------------

This module implements specialized container datatypes providing alternatives to
Python's general purpose built-in containers, :class:`dict`, :class:`list`,
:class:`set`, and :class:`tuple`.

=====================   ====================================================================  ===========================
:func:`namedtuple`      factory function for creating tuple subclasses with named fields      .. versionadded:: 2.6
:class:`deque`          list-like container with fast appends and pops on either end          .. versionadded:: 2.4
:class:`Counter`        dict subclass for counting hashable objects                           .. versionadded:: 2.7
:class:`OrderedDict`    dict subclass that remembers the order entries were added             .. versionadded:: 2.7
:class:`defaultdict`    dict subclass that calls a factory function to supply missing values  .. versionadded:: 2.5
=====================   ====================================================================  ===========================

In addition to the concrete container classes, the collections module provides
:ref:`abstract base classes <collections-abstract-base-classes>` that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.


:class:`Counter` objects
------------------------

A counter tool is provided to support convenient and rapid tallies.
For example::

    >>> # Tally occurrences of words in a list
    >>> cnt = Counter()
    >>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    ...     cnt[word] += 1
    >>> cnt
    Counter({'blue': 3, 'red': 2, 'green': 1})

    >>> # Find the ten most common words in Hamlet
    >>> import re
    >>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
    >>> Counter(words).most_common(10)
    [('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
     ('you', 554),  ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]

.. class:: Counter([iterable-or-mapping])

   A :class:`Counter` is a :class:`dict` subclass for counting hashable objects.
   It is an unordered collection where elements are stored as dictionary keys
   and their counts are stored as dictionary values.  Counts are allowed to be
   any integer value including zero or negative counts.  The :class:`Counter`
   class is similar to bags or multisets in other languages.

   Elements are counted from an *iterable* or initialized from another
   *mapping* (or counter):

        >>> c = Counter()                           # a new, empty counter
        >>> c = Counter('gallahad')                 # a new counter from an iterable
        >>> c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
        >>> c = Counter(cats=4, dogs=8)             # a new counter from keyword args

   Counter objects have a dictionary interface except that they return a zero
   count for missing items instead of raising a :exc:`KeyError`:

        >>> c = Counter(['eggs', 'ham'])
        >>> c['bacon']                              # count of a missing element is zero
        0

   Setting a count to zero does not remove an element from a counter.
   Use ``del`` to remove it entirely:

        >>> c['sausage'] = 0                        # counter entry with a zero count
        >>> del c['sausage']                        # del actually removes the entry

   .. versionadded:: 2.7


   Counter objects support three methods beyond those available for all
   dictionaries:

   .. method:: elements()

      Return an iterator over elements repeating each as many times as its
      count.  Elements are returned in arbitrary order.  If an element's count
      is less than one, :meth:`elements` will ignore it.

            >>> c = Counter(a=4, b=2, c=0, d=-2)
            >>> list(c.elements())
            ['a', 'a', 'a', 'a', 'b', 'b']

   .. method:: most_common([n])

      Return a list of the *n* most common elements and their counts from the
      most common to the least.  If *n* is omitted or ``None``,
      :func:`most_common` returns *all* elements in the counter.
      Elements with equal counts are ordered arbitrarily:

            >>> Counter('abracadabra').most_common(3)
            [('a', 5), ('r', 2), ('b', 2)]

   .. method:: subtract([iterable-or-mapping])

      Elements are subtracted from an *iterable* or from another *mapping*
      (or counter).  Like :meth:`dict.update` but subtracts counts instead
      of replacing them.  Both inputs and outputs may be zero or negative.

            >>> c = Counter(a=4, b=2, c=0, d=-2)
            >>> d = Counter(a=1, b=2, c=3, d=4)
            >>> c.subtract(d)
            >>> c
            Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})

   The usual dictionary methods are available for :class:`Counter` objects
   except for two which work differently for counters.

   .. method:: fromkeys(iterable)

      This class method is not implemented for :class:`Counter` objects.

   .. method:: update([iterable-or-mapping])

      Elements are counted from an *iterable* or added-in from another
      *mapping* (or counter).  Like :meth:`dict.update` but adds counts
      instead of replacing them.  Also, the *iterable* is expected to be a
      sequence of elements, not a sequence of ``(key, value)`` pairs.

Common patterns for working with :class:`Counter` objects::

    sum(c.values())                 # total of all counts
    c.clear()                       # reset all counts
    list(c)                         # list unique elements
    set(c)                          # convert to a set
    dict(c)                         # convert to a regular dictionary
    c.items()                       # convert to a list of (elem, cnt) pairs
    Counter(dict(list_of_pairs))    # convert from a list of (elem, cnt) pairs
    c.most_common()[:-n-1:-1]       # n least common elements
    c += Counter()                  # remove zero and negative counts

Several mathematical operations are provided for combining :class:`Counter`
objects to produce multisets (counters that have counts greater than zero).
Addition and subtraction combine counters by adding or subtracting the counts
of corresponding elements.  Intersection and union return the minimum and
maximum of corresponding counts.  Each operation can accept inputs with signed
counts, but the output will exclude results with counts of zero or less.

    >>> c = Counter(a=3, b=1)
    >>> d = Counter(a=1, b=2)
    >>> c + d                       # add two counters together:  c[x] + d[x]
    Counter({'a': 4, 'b': 3})
    >>> c - d                       # subtract (keeping only positive counts)
    Counter({'a': 2})
    >>> c & d                       # intersection:  min(c[x], d[x])
    Counter({'a': 1, 'b': 1})
    >>> c | d                       # union:  max(c[x], d[x])
    Counter({'a': 3, 'b': 2})

.. note::

   Counters were primarily designed to work with positive integers to represent
   running counts; however, care was taken to not unnecessarily preclude use
   cases needing other types or negative values.  To help with those use cases,
   this section documents the minimum range and type restrictions.

   * The :class:`Counter` class itself is a dictionary subclass with no
     restrictions on its keys and values.  The values are intended to be numbers
     representing counts, but you *could* store anything in the value field.

   * The :meth:`most_common` method requires only that the values be orderable.

   * For in-place operations such as ``c[key] += 1``, the value type need only
     support addition and subtraction.  So fractions, floats, and decimals would
     work and negative values are supported.  The same is also true for
     :meth:`update` and :meth:`subtract` which allow negative and zero values
     for both inputs and outputs.

   * The multiset methods are designed only for use cases with positive values.
     The inputs may be negative or zero, but only outputs with positive values
     are created.  There are no type restrictions, but the value type needs to
     support addition, subtraction, and comparison.

   * The :meth:`elements` method requires integer counts.  It ignores zero and
     negative counts.

.. seealso::

    * `Counter class <https://code.activestate.com/recipes/576611/>`_
      adapted for Python 2.5 and an early `Bag recipe
      <https://code.activestate.com/recipes/259174/>`_ for Python 2.4.

    * `Bag class <https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html>`_
      in Smalltalk.

    * Wikipedia entry for `Multisets <https://en.wikipedia.org/wiki/Multiset>`_.

    * `C++ multisets <http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm>`_
      tutorial with examples.

    * For mathematical operations on multisets and their use cases, see
      *Knuth, Donald. The Art of Computer Programming Volume II,
      Section 4.6.3, Exercise 19*.

    * To enumerate all distinct multisets of a given size over a given set of
      elements, see :func:`itertools.combinations_with_replacement`.

          map(Counter, combinations_with_replacement('ABC', 2)) --> AA AB AC BB BC CC


:class:`deque` objects
----------------------

.. class:: deque([iterable[, maxlen]])

   Returns a new deque object initialized left-to-right (using :meth:`append`) with
   data from *iterable*.  If *iterable* is not specified, the new deque is empty.

   Deques are a generalization of stacks and queues (the name is pronounced "deck"
   and is short for "double-ended queue").  Deques support thread-safe, memory
   efficient appends and pops from either side of the deque with approximately the
   same O(1) performance in either direction.

   Though :class:`list` objects support similar operations, they are optimized for
   fast fixed-length operations and incur O(n) memory movement costs for
   ``pop(0)`` and ``insert(0, v)`` operations which change both the size and
   position of the underlying data representation.

   .. versionadded:: 2.4

   If *maxlen* is not specified or is ``None``, deques may grow to an
   arbitrary length.  Otherwise, the deque is bounded to the specified maximum
   length.  Once a bounded length deque is full, when new items are added, a
   corresponding number of items are discarded from the opposite end.  Bounded
   length deques provide functionality similar to the ``tail`` filter in
   Unix. They are also useful for tracking transactions and other pools of data
   where only the most recent activity is of interest.

   .. versionchanged:: 2.6
      Added *maxlen* parameter.

   Deque objects support the following methods:


   .. method:: append(x)

      Add *x* to the right side of the deque.


   .. method:: appendleft(x)

      Add *x* to the left side of the deque.


   .. method:: clear()

      Remove all elements from the deque leaving it with length 0.


   .. method:: count(x)

      Count the number of deque elements equal to *x*.

      .. versionadded:: 2.7

   .. method:: extend(iterable)

      Extend the right side of the deque by appending elements from the iterable
      argument.


   .. method:: extendleft(iterable)

      Extend the left side of the deque by appending elements from *iterable*.
      Note, the series of left appends results in reversing the order of
      elements in the iterable argument.


   .. method:: pop()

      Remove and return an element from the right side of the deque. If no
      elements are present, raises an :exc:`IndexError`.


   .. method:: popleft()

      Remove and return an element from the left side of the deque. If no
      elements are present, raises an :exc:`IndexError`.


   .. method:: remove(value)

      Remove the first occurrence of *value*.  If not found, raises a
      :exc:`ValueError`.

      .. versionadded:: 2.5

   .. method:: reverse()

      Reverse the elements of the deque in-place and then return ``None``.

      .. versionadded:: 2.7

   .. method:: rotate(n=1)

      Rotate the deque *n* steps to the right.  If *n* is negative, rotate to
      the left.

      When the deque is not empty, rotating one step to the right is equivalent to
      ``d.appendleft(d.pop())``, and rotating one step to the left is
      equivalent to ``d.append(d.popleft())``.


   Deque objects also provide one read-only attribute:

   .. attribute:: maxlen

      Maximum size of a deque or ``None`` if unbounded.

      .. versionadded:: 2.7


In addition to the above, deques support iteration, pickling, ``len(d)``,
``reversed(d)``, ``copy.copy(d)``, ``copy.deepcopy(d)``, membership testing with
the :keyword:`in` operator, and subscript references such as ``d[-1]``.  Indexed
access is O(1) at both ends but slows to O(n) in the middle.  For fast random
access, use lists instead.

Example:

.. doctest::

   >>> from collections import deque
   >>> d = deque('ghi')                 # make a new deque with three items
   >>> for elem in d:                   # iterate over the deque's elements
   ...     print elem.upper()
   G
   H
   I

   >>> d.append('j')                    # add a new entry to the right side
   >>> d.appendleft('f')                # add a new entry to the left side
   >>> d                                # show the representation of the deque
   deque(['f', 'g', 'h', 'i', 'j'])

   >>> d.pop()                          # return and remove the rightmost item
   'j'
   >>> d.popleft()                      # return and remove the leftmost item
   'f'
   >>> list(d)                          # list the contents of the deque
   ['g', 'h', 'i']
   >>> d[0]                             # peek at leftmost item
   'g'
   >>> d[-1]                            # peek at rightmost item
   'i'

   >>> list(reversed(d))                # list the contents of a deque in reverse
   ['i', 'h', 'g']
   >>> 'h' in d                         # search the deque
   True
   >>> d.extend('jkl')                  # add multiple elements at once
   >>> d
   deque(['g', 'h', 'i', 'j', 'k', 'l'])
   >>> d.rotate(1)                      # right rotation
   >>> d
   deque(['l', 'g', 'h', 'i', 'j', 'k'])
   >>> d.rotate(-1)                     # left rotation
   >>> d
   deque(['g', 'h', 'i', 'j', 'k', 'l'])

   >>> deque(reversed(d))               # make a new deque in reverse order
   deque(['l', 'k', 'j', 'i', 'h', 'g'])
   >>> d.clear()                        # empty the deque
   >>> d.pop()                          # cannot pop from an empty deque
   Traceback (most recent call last):
     File "<pyshell#6>", line 1, in -toplevel-
       d.pop()
   IndexError: pop from an empty deque

   >>> d.extendleft('abc')              # extendleft() reverses the input order
   >>> d
   deque(['c', 'b', 'a'])


:class:`deque` Recipes
^^^^^^^^^^^^^^^^^^^^^^

This section shows various approaches to working with deques.

Bounded length deques provide functionality similar to the ``tail`` filter
in Unix::

   def tail(filename, n=10):
       'Return the last n lines of a file'
       return deque(open(filename), n)

Another approach to using deques is to maintain a sequence of recently
added elements by appending to the right and popping to the left::

    def moving_average(iterable, n=3):
        # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0
        # http://en.wikipedia.org/wiki/Moving_average
        it = iter(iterable)
        d = deque(itertools.islice(it, n-1))
        d.appendleft(0)
        s = sum(d)
        for elem in it:
            s += elem - d.popleft()
            d.append(elem)
            yield s / float(n)

The :meth:`rotate` method provides a way to implement :class:`deque` slicing and
deletion.  For example, a pure Python implementation of ``del d[n]`` relies on
the :meth:`rotate` method to position elements to be popped::

   def delete_nth(d, n):
       d.rotate(-n)
       d.popleft()
       d.rotate(n)

To implement :class:`deque` slicing, use a similar approach applying
:meth:`rotate` to bring a target element to the left side of the deque. Remove
old entries with :meth:`popleft`, add new entries with :meth:`extend`, and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as ``dup``, ``drop``, ``swap``, ``over``, ``pick``,
``rot``, and ``roll``.


:class:`defaultdict` objects
----------------------------

.. class:: defaultdict([default_factory[, ...]])

   Returns a new dictionary-like object.  :class:`defaultdict` is a subclass of the
   built-in :class:`dict` class.  It overrides one method and adds one writable
   instance variable.  The remaining functionality is the same as for the
   :class:`dict` class and is not documented here.

   The first argument provides the initial value for the :attr:`default_factory`
   attribute; it defaults to ``None``. All remaining arguments are treated the same
   as if they were passed to the :class:`dict` constructor, including keyword
   arguments.

   .. versionadded:: 2.5

   :class:`defaultdict` objects support the following method in addition to the
   standard :class:`dict` operations:

   .. method:: __missing__(key)

      If the :attr:`default_factory` attribute is ``None``, this raises a
      :exc:`KeyError` exception with the *key* as argument.

      If :attr:`default_factory` is not ``None``, it is called without arguments
      to provide a default value for the given *key*, this value is inserted in
      the dictionary for the *key*, and returned.

      If calling :attr:`default_factory` raises an exception this exception is
      propagated unchanged.

      This method is called by the :meth:`__getitem__` method of the
      :class:`dict` class when the requested key is not found; whatever it
      returns or raises is then returned or raised by :meth:`__getitem__`.

      Note that :meth:`__missing__` is *not* called for any operations besides
      :meth:`__getitem__`. This means that :meth:`get` will, like normal
      dictionaries, return ``None`` as a default rather than using
      :attr:`default_factory`.


   :class:`defaultdict` objects support the following instance variable:


   .. attribute:: default_factory

      This attribute is used by the :meth:`__missing__` method; it is
      initialized from the first argument to the constructor, if present, or to
      ``None``, if absent.


:class:`defaultdict` Examples
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Using :class:`list` as the :attr:`default_factory`, it is easy to group a
sequence of key-value pairs into a dictionary of lists:

   >>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
   >>> d = defaultdict(list)
   >>> for k, v in s:
   ...     d[k].append(v)
   ...
   >>> d.items()
   [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the :attr:`default_factory`
function which returns an empty :class:`list`.  The :meth:`list.append`
operation then attaches the value to the new list.  When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
:meth:`list.append` operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using :meth:`dict.setdefault`:

   >>> d = {}
   >>> for k, v in s:
   ...     d.setdefault(k, []).append(v)
   ...
   >>> d.items()
   [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

Setting the :attr:`default_factory` to :class:`int` makes the
:class:`defaultdict` useful for counting (like a bag or multiset in other
languages):

   >>> s = 'mississippi'
   >>> d = defaultdict(int)
   >>> for k in s:
   ...     d[k] += 1
   ...
   >>> d.items()
   [('i', 4), ('p', 2), ('s', 4), ('m', 1)]

When a letter is first encountered, it is missing from the mapping, so the
:attr:`default_factory` function calls :func:`int` to supply a default count of
zero.  The increment operation then builds up the count for each letter.

The function :func:`int` which always returns zero is just a special case of
constant functions.  A faster and more flexible way to create constant functions
is to use :func:`itertools.repeat` which can supply any constant value (not just
zero):

   >>> def constant_factory(value):
   ...     return itertools.repeat(value).next
   >>> d = defaultdict(constant_factory('<missing>'))
   >>> d.update(name='John', action='ran')
   >>> '%(name)s %(action)s to %(object)s' % d
   'John ran to <missing>'

Setting the :attr:`default_factory` to :class:`set` makes the
:class:`defaultdict` useful for building a dictionary of sets:

   >>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
   >>> d = defaultdict(set)
   >>> for k, v in s:
   ...     d[k].add(v)
   ...
   >>> d.items()
   [('blue', set([2, 4])), ('red', set([1, 3]))]


:func:`namedtuple` Factory Function for Tuples with Named Fields
----------------------------------------------------------------

Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code.  They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.

.. function:: namedtuple(typename, field_names, [verbose=False], [rename=False])

   Returns a new tuple subclass named *typename*.  The new subclass is used to
   create tuple-like objects that have fields accessible by attribute lookup as
   well as being indexable and iterable.  Instances of the subclass also have a
   helpful docstring (with typename and field_names) and a helpful :meth:`__repr__`
   method which lists the tuple contents in a ``name=value`` format.

   The *field_names* are a sequence of strings such as ``['x', 'y']``.
   Alternatively, *field_names* can be a single string with each fieldname
   separated by whitespace and/or commas, for example ``'x y'`` or ``'x, y'``.

   Any valid Python identifier may be used for a fieldname except for names
   starting with an underscore.  Valid identifiers consist of letters, digits,
   and underscores but do not start with a digit or underscore and cannot be
   a :mod:`keyword` such as *class*, *for*, *return*, *global*, *pass*, *print*,
   or *raise*.

   If *rename* is true, invalid fieldnames are automatically replaced
   with positional names.  For example, ``['abc', 'def', 'ghi', 'abc']`` is
   converted to ``['abc', '_1', 'ghi', '_3']``, eliminating the keyword
   ``def`` and the duplicate fieldname ``abc``.

   If *verbose* is true, the class definition is printed just before being built.

   Named tuple instances do not have per-instance dictionaries, so they are
   lightweight and require no more memory than regular tuples.

   .. versionadded:: 2.6

   .. versionchanged:: 2.7
      added support for *rename*.

Example:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
   class Point(tuple):
       'Point(x, y)'
   <BLANKLINE>
       __slots__ = ()
   <BLANKLINE>
       _fields = ('x', 'y')
   <BLANKLINE>
       def __new__(_cls, x, y):
           'Create new instance of Point(x, y)'
           return _tuple.__new__(_cls, (x, y))
   <BLANKLINE>
       @classmethod
       def _make(cls, iterable, new=tuple.__new__, len=len):
           'Make a new Point object from a sequence or iterable'
           result = new(cls, iterable)
           if len(result) != 2:
               raise TypeError('Expected 2 arguments, got %d' % len(result))
           return result
   <BLANKLINE>
       def __repr__(self):
           'Return a nicely formatted representation string'
           return 'Point(x=%r, y=%r)' % self
   <BLANKLINE>
       def _asdict(self):
           'Return a new OrderedDict which maps field names to their values'
           return OrderedDict(zip(self._fields, self))
   <BLANKLINE>
       def _replace(_self, **kwds):
           'Return a new Point object replacing specified fields with new values'
           result = _self._make(map(kwds.pop, ('x', 'y'), _self))
           if kwds:
               raise ValueError('Got unexpected field names: %r' % kwds.keys())
           return result
   <BLANKLINE>
       def __getnewargs__(self):
           'Return self as a plain tuple.  Used by copy and pickle.'
           return tuple(self)
   <BLANKLINE>
       __dict__ = _property(_asdict)
   <BLANKLINE>
       def __getstate__(self):
           'Exclude the OrderedDict from pickling'
           pass
   <BLANKLINE>
       x = _property(_itemgetter(0), doc='Alias for field number 0')
   <BLANKLINE>
       y = _property(_itemgetter(1), doc='Alias for field number 1')
   <BLANKLINE>
   <BLANKLINE>

   >>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
   >>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
   33
   >>> x, y = p                # unpack like a regular tuple
   >>> x, y
   (11, 22)
   >>> p.x + p.y               # fields also accessible by name
   33
   >>> p                       # readable __repr__ with a name=value style
   Point(x=11, y=22)

Named tuples are especially useful for assigning field names to result tuples returned
by the :mod:`csv` or :mod:`sqlite3` modules::

   EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

   import csv
   for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
       print emp.name, emp.title

   import sqlite3
   conn = sqlite3.connect('/companydata')
   cursor = conn.cursor()
   cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
   for emp in map(EmployeeRecord._make, cursor.fetchall()):
       print emp.name, emp.title

In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute.  To prevent conflicts with
field names, the method and attribute names start with an underscore.

.. classmethod:: somenamedtuple._make(iterable)

   Class method that makes a new instance from an existing sequence or iterable.

   .. doctest::

      >>> t = [11, 22]
      >>> Point._make(t)
      Point(x=11, y=22)

.. method:: somenamedtuple._asdict()

   Return a new :class:`OrderedDict` which maps field names to their corresponding
   values::

      >>> p = Point(x=11, y=22)
      >>> p._asdict()
      OrderedDict([('x', 11), ('y', 22)])

   .. versionchanged:: 2.7
      Returns an :class:`OrderedDict` instead of a regular :class:`dict`.

.. method:: somenamedtuple._replace(**kwargs)

   Return a new instance of the named tuple replacing specified fields with new
   values::

      >>> p = Point(x=11, y=22)
      >>> p._replace(x=33)
      Point(x=33, y=22)

      >>> for partnum, record in inventory.items():
      ...     inventory[partnum] = record._replace(price=newprices[partnum], timestamp=time.now())

.. attribute:: somenamedtuple._fields

   Tuple of strings listing the field names.  Useful for introspection
   and for creating new named tuple types from existing named tuples.

   .. doctest::

      >>> p._fields            # view the field names
      ('x', 'y')

      >>> Color = namedtuple('Color', 'red green blue')
      >>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
      >>> Pixel(11, 22, 128, 255, 0)
      Pixel(x=11, y=22, red=128, green=255, blue=0)

To retrieve a field whose name is stored in a string, use the :func:`getattr`
function:

    >>> getattr(p, 'x')
    11

To convert a dictionary to a named tuple, use the double-star-operator
(as described in :ref:`tut-unpacking-arguments`):

   >>> d = {'x': 11, 'y': 22}
   >>> Point(**d)
   Point(x=11, y=22)

Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass.  Here is how to add a calculated field and
a fixed-width print format:

    >>> class Point(namedtuple('Point', 'x y')):
    ...     __slots__ = ()
    ...     @property
    ...     def hypot(self):
    ...         return (self.x ** 2 + self.y ** 2) ** 0.5
    ...     def __str__(self):
    ...         return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
    ...
    >>> for p in Point(3, 4), Point(14, 5/7.):
    ...     print p
    Point: x= 3.000  y= 4.000  hypot= 5.000
    Point: x=14.000  y= 0.714  hypot=14.018

The subclass shown above sets ``__slots__`` to an empty tuple.  This helps
keep memory requirements low by preventing the creation of instance dictionaries.

Subclassing is not useful for adding new, stored fields.  Instead, simply
create a new named tuple type from the :attr:`_fields` attribute:

    >>> Point3D = namedtuple('Point3D', Point._fields + ('z',))

Default values can be implemented by using :meth:`_replace` to
customize a prototype instance:

    >>> Account = namedtuple('Account', 'owner balance transaction_count')
    >>> default_account = Account('<owner name>', 0.0, 0)
    >>> johns_account = default_account._replace(owner='John')

Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration:

    >>> Status = namedtuple('Status', 'open pending closed')._make(range(3))
    >>> Status.open, Status.pending, Status.closed
    (0, 1, 2)
    >>> class Status:
    ...     open, pending, closed = range(3)

.. seealso::

   `Named tuple recipe <https://code.activestate.com/recipes/500261/>`_
   adapted for Python 2.4.


:class:`OrderedDict` objects
----------------------------

Ordered dictionaries are just like regular dictionaries but they remember the
order that items were inserted.  When iterating over an ordered dictionary,
the items are returned in the order their keys were first added.

.. class:: OrderedDict([items])

   Return an instance of a dict subclass, supporting the usual :class:`dict`
   methods.  An *OrderedDict* is a dict that remembers the order that keys
   were first inserted. If a new entry overwrites an existing entry, the
   original insertion position is left unchanged.  Deleting an entry and
   reinserting it will move it to the end.

   .. versionadded:: 2.7

.. method:: OrderedDict.popitem(last=True)

   The :meth:`popitem` method for ordered dictionaries returns and removes
   a (key, value) pair.  The pairs are returned in LIFO order if *last* is
   true or FIFO order if false.

In addition to the usual mapping methods, ordered dictionaries also support
reverse iteration using :func:`reversed`.

Equality tests between :class:`OrderedDict` objects are order-sensitive
and are implemented as ``list(od1.items())==list(od2.items())``.
Equality tests between :class:`OrderedDict` objects and other
:class:`Mapping` objects are order-insensitive like regular
dictionaries.  This allows :class:`OrderedDict` objects to be substituted
anywhere a regular dictionary is used.

The :class:`OrderedDict` constructor and :meth:`update` method both accept
keyword arguments, but their order is lost because Python's function call
semantics pass-in keyword arguments using a regular unordered dictionary.

.. seealso::

   `Equivalent OrderedDict recipe <https://code.activestate.com/recipes/576693/>`_
   that runs on Python 2.4 or later.

:class:`OrderedDict` Examples and Recipes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Since an ordered dictionary remembers its insertion order, it can be used
in conjunction with sorting to make a sorted dictionary::

    >>> # regular unsorted dictionary
    >>> d = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}

    >>> # dictionary sorted by key
    >>> OrderedDict(sorted(d.items(), key=lambda t: t[0]))
    OrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])

    >>> # dictionary sorted by value
    >>> OrderedDict(sorted(d.items(), key=lambda t: t[1]))
    OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

    >>> # dictionary sorted by length of the key string
    >>> OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
    OrderedDict([('pear', 1), ('apple', 4), ('orange', 2), ('banana', 3)])

The new sorted dictionaries maintain their sort order when entries
are deleted.  But when new keys are added, the keys are appended
to the end and the sort is not maintained.

It is also straight-forward to create an ordered dictionary variant
that remembers the order the keys were *last* inserted.
If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end::

    class LastUpdatedOrderedDict(OrderedDict):
        'Store items in the order the keys were last added'

        def __setitem__(self, key, value):
            if key in self:
                del self[key]
            OrderedDict.__setitem__(self, key, value)

An ordered dictionary can be combined with the :class:`Counter` class
so that the counter remembers the order elements are first encountered::

   class OrderedCounter(Counter, OrderedDict):
        'Counter that remembers the order elements are first encountered'

        def __repr__(self):
            return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))

        def __reduce__(self):
            return self.__class__, (OrderedDict(self),)


.. _collections-abstract-base-classes:

Collections Abstract Base Classes
---------------------------------

The collections module offers the following :term:`ABCs <abstract base class>`:

=========================  =====================  ======================  ====================================================
ABC                        Inherits from          Abstract Methods        Mixin Methods
=========================  =====================  ======================  ====================================================
:class:`Container`                                ``__contains__``
:class:`Hashable`                                 ``__hash__``
:class:`Iterable`                                 ``__iter__``
:class:`Iterator`          :class:`Iterable`      ``next``                ``__iter__``
:class:`Sized`                                    ``__len__``
:class:`Callable`                                 ``__call__``

:class:`Sequence`          :class:`Sized`,        ``__getitem__``,        ``__contains__``, ``__iter__``, ``__reversed__``,
                           :class:`Iterable`,     ``__len__``             ``index``, and ``count``
                           :class:`Container`

:class:`MutableSequence`   :class:`Sequence`      ``__getitem__``,        Inherited :class:`Sequence` methods and
                                                  ``__setitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
                                                  ``__delitem__``,        ``remove``, and ``__iadd__``
                                                  ``__len__``,
                                                  ``insert``

:class:`Set`               :class:`Sized`,        ``__contains__``,       ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
                           :class:`Iterable`,     ``__iter__``,           ``__gt__``, ``__ge__``, ``__and__``, ``__or__``,
                           :class:`Container`     ``__len__``             ``__sub__``, ``__xor__``, and ``isdisjoint``

:class:`MutableSet`        :class:`Set`           ``__contains__``,       Inherited :class:`Set` methods and
                                                  ``__iter__``,           ``clear``, ``pop``, ``remove``, ``__ior__``,
                                                  ``__len__``,            ``__iand__``, ``__ixor__``, and ``__isub__``
                                                  ``add``,
                                                  ``discard``

:class:`Mapping`           :class:`Sized`,        ``__getitem__``,        ``__contains__``, ``keys``, ``items``, ``values``,
                           :class:`Iterable`,     ``__iter__``,           ``get``, ``__eq__``, and ``__ne__``
                           :class:`Container`     ``__len__``

:class:`MutableMapping`    :class:`Mapping`       ``__getitem__``,        Inherited :class:`Mapping` methods and
                                                  ``__setitem__``,        ``pop``, ``popitem``, ``clear``, ``update``,
                                                  ``__delitem__``,        and ``setdefault``
                                                  ``__iter__``,
                                                  ``__len__``


:class:`MappingView`       :class:`Sized`                                 ``__len__``
:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
                           :class:`Set`                                   ``__iter__``
:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
                           :class:`Set`                                   ``__iter__``
:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
=========================  =====================  ======================  ====================================================


.. class:: Container
           Hashable
           Sized
           Callable

   ABCs for classes that provide respectively the methods :meth:`__contains__`,
   :meth:`__hash__`, :meth:`__len__`, and :meth:`__call__`.

.. class:: Iterable

   ABC for classes that provide the :meth:`__iter__` method.
   See also the definition of :term:`iterable`.

.. class:: Iterator

   ABC for classes that provide the :meth:`~iterator.__iter__` and
   :meth:`~iterator.next` methods.  See also the definition of :term:`iterator`.

.. class:: Sequence
           MutableSequence

   ABCs for read-only and mutable :term:`sequences <sequence>`.

.. class:: Set
           MutableSet

   ABCs for read-only and mutable sets.

.. class:: Mapping
           MutableMapping

   ABCs for read-only and mutable :term:`mappings <mapping>`.

.. class:: MappingView
           ItemsView
           KeysView
           ValuesView

   ABCs for mapping, items, keys, and values :term:`views <dictionary view>`.


These ABCs allow us to ask classes or instances if they provide
particular functionality, for example::

    size = None
    if isinstance(myvar, collections.Sized):
        size = len(myvar)

Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs.  For example, to write a class supporting
the full :class:`Set` API, it only necessary to supply the three underlying
abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
The ABC supplies the remaining methods such as :meth:`__and__` and
:meth:`isdisjoint` ::

    class ListBasedSet(collections.Set):
         ''' Alternate set implementation favoring space over speed
             and not requiring the set elements to be hashable. '''
         def __init__(self, iterable):
             self.elements = lst = []
             for value in iterable:
                 if value not in lst:
                     lst.append(value)

         def __iter__(self):
             return iter(self.elements)

         def __contains__(self, value):
             return value in self.elements

         def __len__(self):
             return len(self.elements)

    s1 = ListBasedSet('abcdef')
    s2 = ListBasedSet('defghi')
    overlap = s1 & s2            # The __and__() method is supported automatically

Notes on using :class:`Set` and :class:`MutableSet` as a mixin:

(1)
   Since some set operations create new sets, the default mixin methods need
   a way to create new instances from an iterable. The class constructor is
   assumed to have a signature in the form ``ClassName(iterable)``.
   That assumption is factored-out to an internal classmethod called
   :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
   If the :class:`Set` mixin is being used in a class with a different
   constructor signature, you will need to override :meth:`_from_iterable`
   with a classmethod that can construct new instances from
   an iterable argument.

(2)
   To override the comparisons (presumably for speed, as the
   semantics are fixed), redefine :meth:`__le__` and :meth:`__ge__`,
   then the other operations will automatically follow suit.

(3)
   The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
   for the set; however, :meth:`__hash__` is not defined because not all sets
   are hashable or immutable.  To add set hashability using mixins,
   inherit from both :meth:`Set` and :meth:`Hashable`, then define
   ``__hash__ = Set._hash``.

.. seealso::

   * `OrderedSet recipe <https://code.activestate.com/recipes/576694/>`_ for an
     example built on :class:`MutableSet`.

   * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.
PK	%�\�����)html/_sources/library/colorpicker.rst.txtnu�[���
:mod:`ColorPicker` --- Color selection dialog
=============================================

.. module:: ColorPicker
   :platform: Mac
   :synopsis: Interface to the standard color selection dialog.
   :deprecated:
.. moduleauthor:: Just van Rossum <just@letterror.com>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The :mod:`ColorPicker` module provides access to the standard color picker
dialog.

.. note::

   This module has been removed in Python 3.x.


.. function:: GetColor(prompt, rgb)

   Show a standard color selection dialog and allow the user to select a color.
   The user is given instruction by the *prompt* string, and the default color is
   set to *rgb*.  *rgb* must be a tuple giving the red, green, and blue components
   of the color. :func:`GetColor` returns a tuple giving the user's selected color
   and a flag indicating whether they accepted the selection of cancelled.

PK	%�\9�B<&html/_sources/library/colorsys.rst.txtnu�[���:mod:`colorsys` --- Conversions between color systems
=====================================================

.. module:: colorsys
   :synopsis: Conversion functions between RGB and other color systems.
.. sectionauthor:: David Ascher <da@python.net>

**Source code:** :source:`Lib/colorsys.py`

--------------

The :mod:`colorsys` module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in
computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness
Saturation) and HSV (Hue Saturation Value).  Coordinates in all of these color
spaces are floating point values.  In the YIQ space, the Y coordinate is between
0 and 1, but the I and Q coordinates can be positive or negative.  In all other
spaces, the coordinates are all between 0 and 1.

.. seealso::

   More information about color spaces can be found at
   http://www.poynton.com/ColorFAQ.html and
   https://www.cambridgeincolour.com/tutorials/color-spaces.htm.

The :mod:`colorsys` module defines the following functions:


.. function:: rgb_to_yiq(r, g, b)

   Convert the color from RGB coordinates to YIQ coordinates.


.. function:: yiq_to_rgb(y, i, q)

   Convert the color from YIQ coordinates to RGB coordinates.


.. function:: rgb_to_hls(r, g, b)

   Convert the color from RGB coordinates to HLS coordinates.


.. function:: hls_to_rgb(h, l, s)

   Convert the color from HLS coordinates to RGB coordinates.


.. function:: rgb_to_hsv(r, g, b)

   Convert the color from RGB coordinates to HSV coordinates.


.. function:: hsv_to_rgb(h, s, v)

   Convert the color from HSV coordinates to RGB coordinates.

Example::

   >>> import colorsys
   >>> colorsys.rgb_to_hsv(0.2, 0.4, 0.4)
   (0.5, 0.5, 0.4)
   >>> colorsys.hsv_to_rgb(0.5, 0.5, 0.4)
   (0.2, 0.4, 0.4)
PK	%�\K�@w#
#
&html/_sources/library/commands.rst.txtnu�[���
:mod:`commands` --- Utilities for running commands
==================================================

.. module:: commands
   :platform: Unix
   :synopsis: Utility functions for running external commands.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`commands` module has been removed in Python 3.  Use the
   :mod:`subprocess` module instead.

.. sectionauthor:: Sue Williams <sbw@provis.com>


The :mod:`commands` module contains wrapper functions for :func:`os.popen` which
take a system command as a string and return any output generated by the command
and, optionally, the exit status.

The :mod:`subprocess` module provides more powerful facilities for spawning new
processes and retrieving their results.  Using the :mod:`subprocess` module is
preferable to using the :mod:`commands` module.

.. note::

   In Python 3.x, :func:`getstatus` and two undocumented functions
   (:func:`mk2arg` and :func:`mkarg`) have been removed.  Also,
   :func:`getstatusoutput` and :func:`getoutput` have been moved to the
   :mod:`subprocess` module.

The :mod:`commands` module defines the following functions:


.. function:: getstatusoutput(cmd)

   Execute the string *cmd* in a shell with :func:`os.popen` and return a 2-tuple
   ``(status, output)``.  *cmd* is actually run as ``{ cmd ; } 2>&1``, so that the
   returned output will contain output or error messages. A trailing newline is
   stripped from the output. The exit status for the command can be interpreted
   according to the rules for the C function :c:func:`wait`.


.. function:: getoutput(cmd)

   Like :func:`getstatusoutput`, except the exit status is ignored and the return
   value is a string containing the command's output.


.. function:: getstatus(file)

   Return the output of ``ls -ld file`` as a string.  This function uses the
   :func:`getoutput` function, and properly escapes backslashes and dollar signs in
   the argument.

   .. deprecated:: 2.6
      This function is nonobvious and useless.  The name is also misleading in the
      presence of :func:`getstatusoutput`.


Example::

   >>> import commands
   >>> commands.getstatusoutput('ls /bin/ls')
   (0, '/bin/ls')
   >>> commands.getstatusoutput('cat /bin/junk')
   (256, 'cat: /bin/junk: No such file or directory')
   >>> commands.getstatusoutput('/bin/junk')
   (256, 'sh: /bin/junk: not found')
   >>> commands.getoutput('ls /bin/ls')
   '/bin/ls'
   >>> commands.getstatus('/bin/ls')
   '-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls'


.. seealso::

   Module :mod:`subprocess`
      Module for spawning and managing subprocesses.

PK	%�\���>FF(html/_sources/library/compileall.rst.txtnu�[���:mod:`compileall` --- Byte-compile Python libraries
===================================================

.. module:: compileall
   :synopsis: Tools for byte-compiling all Python source files in a directory tree.

**Source code:** :source:`Lib/compileall.py`

--------------


This module provides some utility functions to support installing Python
libraries.  These functions compile Python source files in a directory tree.
This module can be used to create the cached byte-code files at library
installation time, which makes them available for use even by users who don't
have write permission to the library directories.


Command-line use
----------------

This module can work as a script (using :program:`python -m compileall`) to
compile Python sources.

.. program:: compileall

.. cmdoption:: directory ...
               file ...

   Positional arguments are files to compile or directories that contain
   source files, traversed recursively.  If no argument is given, behave as if
   the command line was ``-l <directories from sys.path>``.

.. cmdoption:: -l

   Do not recurse into subdirectories, only compile source code files directly
   contained in the named or implied directories.

.. cmdoption:: -f

   Force rebuild even if timestamps are up-to-date.

.. cmdoption:: -q

   Do not print the list of files compiled, print only error messages.

.. cmdoption:: -d destdir

   Directory prepended to the path to each file being compiled.  This will
   appear in compilation time tracebacks, and is also compiled in to the
   byte-code file, where it will be used in tracebacks and other messages in
   cases where the source file does not exist at the time the byte-code file is
   executed.

.. cmdoption:: -x regex

   regex is used to search the full path to each file considered for
   compilation, and if the regex produces a match, the file is skipped.

.. cmdoption:: -i list

   Read the file ``list`` and add each line that it contains to the list of
   files and directories to compile.  If ``list`` is ``-``, read lines from
   ``stdin``.

.. versionchanged:: 2.7
   Added the ``-i``  option.


Public functions
----------------

.. function:: compile_dir(dir[, maxlevels[, ddir[, force[, rx[, quiet]]]]])

   Recursively descend the directory tree named by *dir*, compiling all :file:`.py`
   files along the way.

   The *maxlevels* parameter is used to limit the depth of the recursion; it
   defaults to ``10``.

   If *ddir* is given, it is prepended to the path to each file being compiled
   for use in compilation time tracebacks, and is also compiled in to the
   byte-code file, where it will be used in tracebacks and other messages in
   cases where the source file does not exist at the time the byte-code file is
   executed.

   If *force* is true, modules are re-compiled even if the timestamps are up to
   date.

   If *rx* is given, its search method is called on the complete path to each
   file considered for compilation, and if it returns a true value, the file
   is skipped.

   If *quiet* is true, nothing is printed to the standard output unless errors
   occur.


.. function:: compile_file(fullname[, ddir[, force[, rx[, quiet]]]])

   Compile the file with path *fullname*.

   If *ddir* is given, it is prepended to the path to the file being compiled
   for use in compilation time tracebacks, and is also compiled in to the
   byte-code file, where it will be used in tracebacks and other messages in
   cases where the source file does not exist at the time the byte-code file is
   executed.

   If *rx* is given, its search method is passed the full path name to the
   file being compiled, and if it returns a true value, the file is not
   compiled and ``True`` is returned.

   If *quiet* is true, nothing is printed to the standard output unless errors
   occur.

   .. versionadded:: 2.7


.. function:: compile_path([skip_curdir[, maxlevels[, force]]])

   Byte-compile all the :file:`.py` files found along ``sys.path``. If
   *skip_curdir* is true (the default), the current directory is not included
   in the search.  All other parameters are passed to the :func:`compile_dir`
   function.  Note that unlike the other compile functions, ``maxlevels``
   defaults to ``0``.

To force a recompile of all the :file:`.py` files in the :file:`Lib/`
subdirectory and all its subdirectories::

   import compileall

   compileall.compile_dir('Lib/', force=True)

   # Perform same compilation, excluding files in .svn directories.
   import re
   compileall.compile_dir('Lib/', rx=re.compile(r'[/\\][.]svn'), force=True)


.. seealso::

   Module :mod:`py_compile`
      Byte-compile a single source file.
PK	%�\u��X�X�&html/_sources/library/compiler.rst.txtnu�[���
.. _compiler:

***********************
Python compiler package
***********************

.. deprecated:: 2.6
   The :mod:`compiler` package has been removed in Python 3.

.. sectionauthor:: Jeremy Hylton <jeremy@zope.com>


The Python compiler package is a tool for analyzing Python source code and
generating Python bytecode.  The compiler contains libraries to generate an
abstract syntax tree from Python source code and to generate Python
:term:`bytecode` from the tree.

The :mod:`compiler` package is a Python source to bytecode translator written in
Python.  It uses the built-in parser and standard :mod:`parser` module to
generate a concrete syntax tree.  This tree is used to generate an abstract
syntax tree (AST) and then Python bytecode.

The full functionality of the package duplicates the built-in compiler provided
with the Python interpreter.  It is intended to match its behavior almost
exactly.  Why implement another compiler that does the same thing?  The package
is useful for a variety of purposes.  It can be modified more easily than the
built-in compiler.  The AST it generates is useful for analyzing Python source
code.

This chapter explains how the various components of the :mod:`compiler` package
work.  It blends reference material with a tutorial.


The basic interface
===================

.. module:: compiler
   :synopsis: Python code compiler written in Python.
   :deprecated:


The top-level of the package defines four functions.  If you import
:mod:`compiler`, you will get these functions and a collection of modules
contained in the package.


.. function:: parse(buf)

   Returns an abstract syntax tree for the Python source code in *buf*. The
   function raises :exc:`SyntaxError` if there is an error in the source code.  The
   return value is a :class:`compiler.ast.Module` instance that contains the tree.


.. function:: parseFile(path)

   Return an abstract syntax tree for the Python source code in the file specified
   by *path*.  It is equivalent to ``parse(open(path).read())``.


.. function:: walk(ast, visitor[, verbose])

   Do a pre-order walk over the abstract syntax tree *ast*.  Call the appropriate
   method on the *visitor* instance for each node encountered.


.. function:: compile(source, filename, mode, flags=None,  dont_inherit=None)

   Compile the string *source*, a Python module, statement or expression, into a
   code object that can be executed by the exec statement or :func:`eval`. This
   function is a replacement for the built-in :func:`compile` function.

   The *filename* will be used for run-time error messages.

   The *mode* must be 'exec' to compile a module, 'single' to compile a single
   (interactive) statement, or 'eval' to compile an expression.

   The *flags* and *dont_inherit* arguments affect future-related statements, but
   are not supported yet.


.. function:: compileFile(source)

   Compiles the file *source* and generates a .pyc file.

The :mod:`compiler` package contains the following modules: :mod:`ast`,
:mod:`consts`, :mod:`future`, :mod:`misc`, :mod:`pyassem`, :mod:`pycodegen`,
:mod:`symbols`, :mod:`transformer`, and :mod:`visitor`.


Limitations
===========

There are some problems with the error checking of the compiler package.  The
interpreter detects syntax errors in two distinct phases.  One set of errors is
detected by the interpreter's parser, the other set by the compiler.  The
compiler package relies on the interpreter's parser, so it get the first phases
of error checking for free.  It implements the second phase itself, and that
implementation is incomplete.  For example, the compiler package does not raise
an error if a name appears more than once in an argument list:  ``def f(x, x):
...``

A future version of the compiler should fix these problems.


Python Abstract Syntax
======================

The :mod:`compiler.ast` module defines an abstract syntax for Python.  In the
abstract syntax tree, each node represents a syntactic construct.  The root of
the tree is :class:`Module` object.

The abstract syntax offers a higher level interface to parsed Python source
code.  The :mod:`parser` module and the compiler written in C for the Python
interpreter use a concrete syntax tree.  The concrete syntax is tied closely to
the grammar description used for the Python parser.  Instead of a single node
for a construct, there are often several levels of nested nodes that are
introduced by Python's precedence rules.

The abstract syntax tree is created by the :mod:`compiler.transformer` module.
The transformer relies on the built-in Python parser to generate a concrete
syntax tree.  It generates an abstract syntax tree from the concrete tree.

.. index::
   single: Stein, Greg
   single: Tutt, Bill

The :mod:`transformer` module was created by Greg Stein and Bill Tutt for an
experimental Python-to-C compiler.  The current version contains a number of
modifications and improvements, but the basic form of the abstract syntax and of
the transformer are due to Stein and Tutt.


AST Nodes
---------

.. module:: compiler.ast


The :mod:`compiler.ast` module is generated from a text file that describes each
node type and its elements.  Each node type is represented as a class that
inherits from the abstract base class :class:`compiler.ast.Node` and defines a
set of named attributes for child nodes.


.. class:: Node()

   The :class:`Node` instances are created automatically by the parser generator.
   The recommended interface for specific :class:`Node` instances is to use the
   public attributes to access child nodes.  A public attribute may be bound to a
   single node or to a sequence of nodes, depending on the :class:`Node` type.  For
   example, the :attr:`bases` attribute of the :class:`Class` node, is bound to a
   list of base class nodes, and the :attr:`doc` attribute is bound to a single
   node.

   Each :class:`Node` instance has a :attr:`lineno` attribute which may be
   ``None``.  XXX Not sure what the rules are for which nodes will have a useful
   lineno.

   All :class:`Node` objects offer the following methods:


   .. method:: getChildren()

      Returns a flattened list of the child nodes and objects in the order they
      occur.  Specifically, the order of the nodes is the order in which they
      appear in the Python grammar.  Not all of the children are :class:`Node`
      instances.  The names of functions and classes, for example, are plain
      strings.


   .. method:: getChildNodes()

      Returns a flattened list of the child nodes in the order they occur.  This
      method is like :meth:`getChildren`, except that it only returns those
      children that are :class:`Node` instances.


Two examples illustrate the general structure of :class:`Node` classes.  The
:keyword:`while` statement is defined by the following grammar production::

   while_stmt:     "while" expression ":" suite
                  ["else" ":" suite]

The :class:`While` node has three attributes: :attr:`test`, :attr:`body`, and
:attr:`else_`.  (If the natural name for an attribute is also a Python reserved
word, it can't be used as an attribute name.  An underscore is appended to the
word to make it a legal identifier, hence :attr:`else_` instead of
:keyword:`else`.)

The :keyword:`if` statement is more complicated because it can include several
tests.   ::

   if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]

The :class:`If` node only defines two attributes: :attr:`tests` and
:attr:`else_`.  The :attr:`tests` attribute is a sequence of test expression,
consequent body pairs.  There is one pair for each :keyword:`if`/:keyword:`elif`
clause.  The first element of the pair is the test expression.  The second
elements is a :class:`Stmt` node that contains the code to execute if the test
is true.

The :meth:`getChildren` method of :class:`If` returns a flat list of child
nodes.  If there are three :keyword:`if`/:keyword:`elif` clauses and no
:keyword:`else` clause, then :meth:`getChildren` will return a list of six
elements: the first test expression, the first :class:`Stmt`, the second text
expression, etc.

The following table lists each of the :class:`Node` subclasses defined in
:mod:`compiler.ast` and each of the public attributes available on their
instances.  The values of most of the attributes are themselves :class:`Node`
instances or sequences of instances.  When the value is something other than an
instance, the type is noted in the comment.  The attributes are listed in the
order in which they are returned by :meth:`getChildren` and
:meth:`getChildNodes`.

+-----------------------+--------------------+---------------------------------+
| Node type             | Attribute          | Value                           |
+=======================+====================+=================================+
| :class:`Add`          | :attr:`left`       | left operand                    |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      | right operand                   |
+-----------------------+--------------------+---------------------------------+
| :class:`And`          | :attr:`nodes`      | list of operands                |
+-----------------------+--------------------+---------------------------------+
| :class:`AssAttr`      |                    | *attribute as target of         |
|                       |                    | assignment*                     |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr`       | expression on the left-hand     |
|                       |                    | side of the dot                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`attrname`   | the attribute name, a string    |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      | XXX                             |
+-----------------------+--------------------+---------------------------------+
| :class:`AssList`      | :attr:`nodes`      | list of list elements being     |
|                       |                    | assigned to                     |
+-----------------------+--------------------+---------------------------------+
| :class:`AssName`      | :attr:`name`       | name being assigned to          |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      | XXX                             |
+-----------------------+--------------------+---------------------------------+
| :class:`AssTuple`     | :attr:`nodes`      | list of tuple elements being    |
|                       |                    | assigned to                     |
+-----------------------+--------------------+---------------------------------+
| :class:`Assert`       | :attr:`test`       | the expression to be tested     |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`fail`       | the value of the                |
|                       |                    | :exc:`AssertionError`           |
+-----------------------+--------------------+---------------------------------+
| :class:`Assign`       | :attr:`nodes`      | a list of assignment targets,   |
|                       |                    | one per equal sign              |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr`       | the value being assigned        |
+-----------------------+--------------------+---------------------------------+
| :class:`AugAssign`    | :attr:`node`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`op`         |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Backquote`    | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Bitand`       | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Bitor`        | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Bitxor`       | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Break`        |                    |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`CallFunc`     | :attr:`node`       | expression for the callee       |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`args`       | a list of arguments             |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`star_args`  | the extended \*-arg value       |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`dstar_args` | the extended \*\*-arg value     |
+-----------------------+--------------------+---------------------------------+
| :class:`Class`        | :attr:`name`       | the name of the class, a string |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`bases`      | a list of base classes          |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`doc`        | doc string, a string or         |
|                       |                    | ``None``                        |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`code`       | the body of the class statement |
+-----------------------+--------------------+---------------------------------+
| :class:`Compare`      | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`ops`        |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Const`        | :attr:`value`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Continue`     |                    |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Decorators`   | :attr:`nodes`      | List of function decorator      |
|                       |                    | expressions                     |
+-----------------------+--------------------+---------------------------------+
| :class:`Dict`         | :attr:`items`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Discard`      | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Div`          | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Ellipsis`     |                    |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Expression`   | :attr:`node`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Exec`         | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`locals`     |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`globals`    |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`FloorDiv`     | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`For`          | :attr:`assign`     |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`list`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`body`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`else_`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`From`         | :attr:`modname`    |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`names`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Function`     | :attr:`decorators` | :class:`Decorators` or ``None`` |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`name`       | name used in def, a string      |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`argnames`   | list of argument names, as      |
|                       |                    | strings                         |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`defaults`   | list of default values          |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      | xxx                             |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`doc`        | doc string, a string or         |
|                       |                    | ``None``                        |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`code`       | the body of the function        |
+-----------------------+--------------------+---------------------------------+
| :class:`GenExpr`      | :attr:`code`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`GenExprFor`   | :attr:`assign`     |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`iter`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`ifs`        |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`GenExprIf`    | :attr:`test`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`GenExprInner` | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`quals`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Getattr`      | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`attrname`   |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Global`       | :attr:`names`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`If`           | :attr:`tests`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`else_`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Import`       | :attr:`names`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Invert`       | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Keyword`      | :attr:`name`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Lambda`       | :attr:`argnames`   |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`defaults`   |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`code`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`LeftShift`    | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`List`         | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`ListComp`     | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`quals`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`ListCompFor`  | :attr:`assign`     |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`list`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`ifs`        |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`ListCompIf`   | :attr:`test`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Mod`          | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Module`       | :attr:`doc`        | doc string, a string or         |
|                       |                    | ``None``                        |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`node`       | body of the module, a           |
|                       |                    | :class:`Stmt`                   |
+-----------------------+--------------------+---------------------------------+
| :class:`Mul`          | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Name`         | :attr:`name`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Not`          | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Or`           | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Pass`         |                    |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Power`        | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Print`        | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`dest`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Printnl`      | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`dest`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Raise`        | :attr:`expr1`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr2`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`expr3`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Return`       | :attr:`value`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`RightShift`   | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Slice`        | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`lower`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`upper`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Sliceobj`     | :attr:`nodes`      | list of statements              |
+-----------------------+--------------------+---------------------------------+
| :class:`Stmt`         | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Sub`          | :attr:`left`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`right`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Subscript`    | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`flags`      |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`subs`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`TryExcept`    | :attr:`body`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`handlers`   |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`else_`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`TryFinally`   | :attr:`body`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`final`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Tuple`        | :attr:`nodes`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`UnaryAdd`     | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`UnarySub`     | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`While`        | :attr:`test`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`body`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`else_`      |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`With`         | :attr:`expr`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`vars`       |                                 |
+-----------------------+--------------------+---------------------------------+
|                       | :attr:`body`       |                                 |
+-----------------------+--------------------+---------------------------------+
| :class:`Yield`        | :attr:`value`      |                                 |
+-----------------------+--------------------+---------------------------------+


Assignment nodes
----------------

There is a collection of nodes used to represent assignments.  Each assignment
statement in the source code becomes a single :class:`Assign` node in the AST.
The :attr:`nodes` attribute is a list that contains a node for each assignment
target.  This is necessary because assignment can be chained, e.g. ``a = b =
2``. Each :class:`Node` in the list will be one of the following classes:
:class:`AssAttr`, :class:`AssList`, :class:`AssName`, or :class:`AssTuple`.

Each target assignment node will describe the kind of object being assigned to:
:class:`AssName` for a simple name, e.g. ``a = 1``. :class:`AssAttr` for an
attribute assigned, e.g. ``a.x = 1``. :class:`AssList` and :class:`AssTuple` for
list and tuple expansion respectively, e.g. ``a, b, c = a_tuple``.

The target assignment nodes also have a :attr:`flags` attribute that indicates
whether the node is being used for assignment or in a delete statement.  The
:class:`AssName` is also used to represent a delete statement, e.g. :class:`del
x`.

When an expression contains several attribute references, an assignment or
delete statement will contain only one :class:`AssAttr` node -- for the final
attribute reference.  The other attribute references will be represented as
:class:`Getattr` nodes in the :attr:`expr` attribute of the :class:`AssAttr`
instance.


Examples
--------

This section shows several simple examples of ASTs for Python source code.  The
examples demonstrate how to use the :func:`parse` function, what the repr of an
AST looks like, and how to access attributes of an AST node.

The first module defines a single function.  Assume it is stored in
:file:`doublelib.py`.  ::

   """This is an example module.

   This is the docstring.
   """

   def double(x):
       "Return twice the argument"
       return x * 2

In the interactive interpreter session below, I have reformatted the long AST
reprs for readability.  The AST reprs use unqualified class names.  If you want
to create an instance from a repr, you must import the class names from the
:mod:`compiler.ast` module. ::

   >>> import compiler
   >>> mod = compiler.parseFile("doublelib.py")
   >>> mod
   Module('This is an example module.\n\nThis is the docstring.\n',
          Stmt([Function(None, 'double', ['x'], [], 0,
                         'Return twice the argument',
                         Stmt([Return(Mul((Name('x'), Const(2))))]))]))
   >>> from compiler.ast import *
   >>> Module('This is an example module.\n\nThis is the docstring.\n',
   ...    Stmt([Function(None, 'double', ['x'], [], 0,
   ...                   'Return twice the argument',
   ...                   Stmt([Return(Mul((Name('x'), Const(2))))]))]))
   Module('This is an example module.\n\nThis is the docstring.\n',
          Stmt([Function(None, 'double', ['x'], [], 0,
                         'Return twice the argument',
                         Stmt([Return(Mul((Name('x'), Const(2))))]))]))
   >>> mod.doc
   'This is an example module.\n\nThis is the docstring.\n'
   >>> for node in mod.node.nodes:
   ...     print node
   ...
   Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
            Stmt([Return(Mul((Name('x'), Const(2))))]))
   >>> func = mod.node.nodes[0]
   >>> func.code
   Stmt([Return(Mul((Name('x'), Const(2))))])


Using Visitors to Walk ASTs
===========================

.. module:: compiler.visitor


The visitor pattern is ...  The :mod:`compiler` package uses a variant on the
visitor pattern that takes advantage of Python's introspection features to
eliminate the need for much of the visitor's infrastructure.

The classes being visited do not need to be programmed to accept visitors.  The
visitor need only define visit methods for classes it is specifically interested
in; a default visit method can handle the rest.

XXX The magic :meth:`visit` method for visitors.


.. function:: walk(tree, visitor[, verbose])


.. class:: ASTVisitor()

   The :class:`ASTVisitor` is responsible for walking over the tree in the correct
   order.  A walk begins with a call to :meth:`preorder`.  For each node, it checks
   the *visitor* argument to :meth:`preorder` for a method named 'visitNodeType,'
   where NodeType is the name of the node's class, e.g. for a :class:`While` node a
   :meth:`visitWhile` would be called.  If the method exists, it is called with the
   node as its first argument.

   The visitor method for a particular node type can control how child nodes are
   visited during the walk.  The :class:`ASTVisitor` modifies the visitor argument
   by adding a visit method to the visitor; this method can be used to visit a
   particular child node.  If no visitor is found for a particular node type, the
   :meth:`default` method is called.

   :class:`ASTVisitor` objects have the following methods:

   XXX describe extra arguments


   .. method:: default(node[, ...])


   .. method:: dispatch(node[, ...])


   .. method:: preorder(tree, visitor)


Bytecode Generation
===================

The code generator is a visitor that emits bytecodes.  Each visit method can
call the :meth:`emit` method to emit a new bytecode.  The basic code generator
is specialized for modules, classes, and functions.  An assembler converts that
emitted instructions to the low-level bytecode format.  It handles things like
generation of constant lists of code objects and calculation of jump offsets.

PK	%�\$s�r�L�L*html/_sources/library/configparser.rst.txtnu�[���:mod:`ConfigParser` --- Configuration file parser
=================================================

.. module:: ConfigParser
   :synopsis: Configuration file parser.

.. moduleauthor:: Ken Manheimer <klm@zope.com>
.. moduleauthor:: Barry Warsaw <bwarsaw@python.org>
.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>

.. note::

   The :mod:`ConfigParser` module has been renamed to :mod:`configparser` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.

.. index::
   pair: .ini; file
   pair: configuration; file
   single: ini file
   single: Windows ini file

This module defines the class :class:`~ConfigParser.ConfigParser`.   The :class:`~ConfigParser.ConfigParser`
class implements a basic configuration file parser language which provides a
structure similar to what you would find on Microsoft Windows INI files.  You
can use this to write Python programs which can be customized by end users
easily.

.. note::

   This library does *not* interpret or write the value-type prefixes used in
   the Windows Registry extended version of INI syntax.

.. seealso::

   Module :mod:`shlex`
      Support for creating Unix shell-like mini-languages which can be used as
      an alternate format for application configuration files.

   Module :mod:`json`
      The json module implements a subset of JavaScript syntax which can also
      be used for this purpose.

The configuration file consists of sections, led by a ``[section]`` header and
followed by ``name: value`` entries, with continuations in the style of
:rfc:`822` (see section 3.1.1, "LONG HEADER FIELDS"); ``name=value`` is also
accepted.  Note that leading whitespace is removed from values. The optional
values can contain format strings which refer to other values in the same
section, or values in a special ``DEFAULT`` section.  Additional defaults can be
provided on initialization and retrieval.  Lines beginning with ``'#'`` or
``';'`` are ignored and may be used to provide comments.

Configuration files may include comments, prefixed by specific characters (``#``
and ``;``).  Comments may appear on their own in an otherwise empty line, or may
be entered in lines holding values or section names.  In the latter case, they
need to be preceded by a whitespace character to be recognized as a comment.
(For backwards compatibility, only ``;`` starts an inline comment, while ``#``
does not.)

On top of the core functionality, :class:`SafeConfigParser` supports
interpolation.  This means values can contain format strings which refer to
other values in the same section, or values in a special ``DEFAULT`` section.
Additional defaults can be provided on initialization.

For example::

   [My Section]
   foodir: %(dir)s/whatever
   dir=frob
   long: this value continues
      in the next line

would resolve the ``%(dir)s`` to the value of ``dir`` (``frob`` in this case).
All reference expansions are done on demand.

Default values can be specified by passing them into the :class:`~ConfigParser.ConfigParser`
constructor as a dictionary.  Additional defaults  may be passed into the
:meth:`get` method which will override all others.

Sections are normally stored in a built-in dictionary. An alternative dictionary
type can be passed to the :class:`~ConfigParser.ConfigParser` constructor. For example, if a
dictionary type is passed that sorts its keys, the sections will be sorted on
write-back, as will be the keys within each section.


.. class:: RawConfigParser([defaults[, dict_type[, allow_no_value]]])

   The basic configuration object.  When *defaults* is given, it is initialized
   into the dictionary of intrinsic defaults.  When *dict_type* is given, it will
   be used to create the dictionary objects for the list of sections, for the
   options within a section, and for the default values.  When *allow_no_value*
   is true (default: ``False``), options without values are accepted; the value
   presented for these is ``None``.

   This class does not
   support the magical interpolation behavior.

   All option names are passed through the :meth:`optionxform` method.  Its
   default implementation converts option names to lower case.

   .. versionadded:: 2.3

   .. versionchanged:: 2.6
      *dict_type* was added.

   .. versionchanged:: 2.7
      The default *dict_type* is :class:`collections.OrderedDict`.
      *allow_no_value* was added.


.. class:: ConfigParser([defaults[, dict_type[, allow_no_value]]])

   Derived class of :class:`RawConfigParser` that implements the magical
   interpolation feature and adds optional arguments to the :meth:`get` and
   :meth:`items` methods.  The values in *defaults* must be appropriate for the
   ``%()s`` string interpolation.  Note that *__name__* is an intrinsic default;
   its value is the section name, and will override any value provided in
   *defaults*.

   All option names used in interpolation will be passed through the
   :meth:`optionxform` method just like any other option name reference.  Using
   the default implementation of :meth:`optionxform`, the values ``foo %(bar)s``
   and ``foo %(BAR)s`` are equivalent.

   .. versionadded:: 2.3

   .. versionchanged:: 2.6
      *dict_type* was added.

   .. versionchanged:: 2.7
      The default *dict_type* is :class:`collections.OrderedDict`.
      *allow_no_value* was added.


.. class:: SafeConfigParser([defaults[, dict_type[, allow_no_value]]])

   Derived class of :class:`~ConfigParser.ConfigParser` that implements a more-sane variant of
   the magical interpolation feature.  This implementation is more predictable as
   well. New applications should prefer this version if they don't need to be
   compatible with older versions of Python.

   .. XXX Need to explain what's safer/more predictable about it.

   .. versionadded:: 2.3

   .. versionchanged:: 2.6
      *dict_type* was added.

   .. versionchanged:: 2.7
      The default *dict_type* is :class:`collections.OrderedDict`.
      *allow_no_value* was added.


.. exception:: Error

   Base class for all other configparser exceptions.


.. exception:: NoSectionError

   Exception raised when a specified section is not found.


.. exception:: DuplicateSectionError

   Exception raised if :meth:`add_section` is called with the name of a section
   that is already present.


.. exception:: NoOptionError

   Exception raised when a specified option is not found in the specified  section.


.. exception:: InterpolationError

   Base class for exceptions raised when problems occur performing string
   interpolation.


.. exception:: InterpolationDepthError

   Exception raised when string interpolation cannot be completed because the
   number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
   :exc:`InterpolationError`.


.. exception:: InterpolationMissingOptionError

   Exception raised when an option referenced from a value does not exist. Subclass
   of :exc:`InterpolationError`.

   .. versionadded:: 2.3


.. exception:: InterpolationSyntaxError

   Exception raised when the source text into which substitutions are made does not
   conform to the required syntax. Subclass of :exc:`InterpolationError`.

   .. versionadded:: 2.3


.. exception:: MissingSectionHeaderError

   Exception raised when attempting to parse a file which has no section headers.


.. exception:: ParsingError

   Exception raised when errors occur attempting to parse a file.


.. data:: MAX_INTERPOLATION_DEPTH

   The maximum depth for recursive interpolation for :meth:`get` when the *raw*
   parameter is false.  This is relevant only for the :class:`~ConfigParser.ConfigParser` class.


.. seealso::

   Module :mod:`shlex`
      Support for a creating Unix shell-like mini-languages which can be used as an
      alternate format for application configuration files.


.. _rawconfigparser-objects:

RawConfigParser Objects
-----------------------

:class:`RawConfigParser` instances have the following methods:


.. method:: RawConfigParser.defaults()

   Return a dictionary containing the instance-wide defaults.


.. method:: RawConfigParser.sections()

   Return a list of the sections available; ``DEFAULT`` is not included in the
   list.


.. method:: RawConfigParser.add_section(section)

   Add a section named *section* to the instance.  If a section by the given name
   already exists, :exc:`DuplicateSectionError` is raised. If the name
   ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
   :exc:`ValueError` is raised.

.. method:: RawConfigParser.has_section(section)

   Indicates whether the named section is present in the configuration. The
   ``DEFAULT`` section is not acknowledged.


.. method:: RawConfigParser.options(section)

   Returns a list of options available in the specified *section*.


.. method:: RawConfigParser.has_option(section, option)

   If the given section exists, and contains the given option, return
   :const:`True`; otherwise return :const:`False`.

   .. versionadded:: 1.6


.. method:: RawConfigParser.read(filenames)

   Attempt to read and parse a list of filenames, returning a list of filenames
   which were successfully parsed.  If *filenames* is a string or Unicode string,
   it is treated as a single filename. If a file named in *filenames* cannot be
   opened, that file will be ignored.  This is designed so that you can specify a
   list of potential configuration file locations (for example, the current
   directory, the user's home directory, and some system-wide directory), and all
   existing configuration files in the list will be read.  If none of the named
   files exist, the :class:`~ConfigParser.ConfigParser` instance will contain an empty dataset.
   An application which requires initial values to be loaded from a file should
   load the required file or files using :meth:`readfp` before calling :meth:`read`
   for any optional files::

      import ConfigParser, os

      config = ConfigParser.ConfigParser()
      config.readfp(open('defaults.cfg'))
      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])

   .. versionchanged:: 2.4
      Returns list of successfully parsed filenames.


.. method:: RawConfigParser.readfp(fp[, filename])

   Read and parse configuration data from the file or file-like object in *fp*
   (only the :meth:`readline` method is used).  If *filename* is omitted and *fp*
   has a :attr:`name` attribute, that is used for *filename*; the default is
   ``<???>``.


.. method:: RawConfigParser.get(section, option)

   Get an *option* value for the named *section*.


.. method:: RawConfigParser.getint(section, option)

   A convenience method which coerces the *option* in the specified *section* to an
   integer.


.. method:: RawConfigParser.getfloat(section, option)

   A convenience method which coerces the *option* in the specified *section* to a
   floating point number.


.. method:: RawConfigParser.getboolean(section, option)

   A convenience method which coerces the *option* in the specified *section* to a
   Boolean value.  Note that the accepted values for the option are ``"1"``,
   ``"yes"``, ``"true"``, and ``"on"``, which cause this method to return ``True``,
   and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which cause it to return
   ``False``.  These string values are checked in a case-insensitive manner.  Any
   other value will cause it to raise :exc:`ValueError`.


.. method:: RawConfigParser.items(section)

   Return a list of ``(name, value)`` pairs for each option in the given *section*.


.. method:: RawConfigParser.set(section, option, value)

   If the given section exists, set the given option to the specified value;
   otherwise raise :exc:`NoSectionError`.  While it is possible to use
   :class:`RawConfigParser` (or :class:`~ConfigParser.ConfigParser` with *raw* parameters set to
   true) for *internal* storage of non-string values, full functionality (including
   interpolation and output to files) can only be achieved using string values.

   .. versionadded:: 1.6


.. method:: RawConfigParser.write(fileobject)

   Write a representation of the configuration to the specified file object.  This
   representation can be parsed by a future :meth:`read` call.

   .. versionadded:: 1.6


.. method:: RawConfigParser.remove_option(section, option)

   Remove the specified *option* from the specified *section*. If the section does
   not exist, raise :exc:`NoSectionError`.  If the option existed to be removed,
   return :const:`True`; otherwise return :const:`False`.

   .. versionadded:: 1.6


.. method:: RawConfigParser.remove_section(section)

   Remove the specified *section* from the configuration. If the section in fact
   existed, return ``True``. Otherwise return ``False``.


.. method:: RawConfigParser.optionxform(option)

   Transforms the option name *option* as found in an input file or as passed in
   by client code to the form that should be used in the internal structures.
   The default implementation returns a lower-case version of *option*;
   subclasses may override this or client code can set an attribute of this name
   on instances to affect this behavior.

   You don't necessarily need to subclass a ConfigParser to use this method, you
   can also re-set it on an instance, to a function that takes a string
   argument.  Setting it to ``str``, for example, would make option names case
   sensitive::

      cfgparser = ConfigParser()
      ...
      cfgparser.optionxform = str

   Note that when reading configuration files, whitespace around the
   option names are stripped before :meth:`optionxform` is called.


.. _configparser-objects:

ConfigParser Objects
--------------------

The :class:`~ConfigParser.ConfigParser` class extends some methods of the
:class:`RawConfigParser` interface, adding some optional arguments.


.. method:: ConfigParser.get(section, option[, raw[, vars]])

   Get an *option* value for the named *section*.  If *vars* is provided, it
   must be a dictionary.  The *option* is looked up in *vars* (if provided),
   *section*, and in *defaults* in that order.

   All the ``'%'`` interpolations are expanded in the return values, unless the
   *raw* argument is true.  Values for interpolation keys are looked up in the
   same manner as the option.

.. method:: ConfigParser.items(section[, raw[, vars]])

   Return a list of ``(name, value)`` pairs for each option in the given *section*.
   Optional arguments have the same meaning as for the :meth:`get` method.

   .. versionadded:: 2.3


.. _safeconfigparser-objects:

SafeConfigParser Objects
------------------------

The :class:`SafeConfigParser` class implements the same extended interface as
:class:`~ConfigParser.ConfigParser`, with the following addition:


.. method:: SafeConfigParser.set(section, option, value)

   If the given section exists, set the given option to the specified value;
   otherwise raise :exc:`NoSectionError`.  *value* must be a string (:class:`str`
   or :class:`unicode`); if not, :exc:`TypeError` is raised.

   .. versionadded:: 2.4


Examples
--------

An example of writing to a configuration file::

   import ConfigParser

   config = ConfigParser.RawConfigParser()

   # When adding sections or items, add them in the reverse order of
   # how you want them to be displayed in the actual file.
   # In addition, please note that using RawConfigParser's and the raw
   # mode of ConfigParser's respective set functions, you can assign
   # non-string values to keys internally, but will receive an error
   # when attempting to write to a file or when you get it in non-raw
   # mode. SafeConfigParser does not allow such assignments to take place.
   config.add_section('Section1')
   config.set('Section1', 'an_int', '15')
   config.set('Section1', 'a_bool', 'true')
   config.set('Section1', 'a_float', '3.1415')
   config.set('Section1', 'baz', 'fun')
   config.set('Section1', 'bar', 'Python')
   config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

   # Writing our configuration file to 'example.cfg'
   with open('example.cfg', 'wb') as configfile:
       config.write(configfile)

An example of reading the configuration file again::

   import ConfigParser

   config = ConfigParser.RawConfigParser()
   config.read('example.cfg')

   # getfloat() raises an exception if the value is not a float
   # getint() and getboolean() also do this for their respective types
   a_float = config.getfloat('Section1', 'a_float')
   an_int = config.getint('Section1', 'an_int')
   print a_float + an_int

   # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
   # This is because we are using a RawConfigParser().
   if config.getboolean('Section1', 'a_bool'):
       print config.get('Section1', 'foo')

To get interpolation, you will need to use a :class:`~ConfigParser.ConfigParser` or
:class:`SafeConfigParser`::

   import ConfigParser

   config = ConfigParser.ConfigParser()
   config.read('example.cfg')

   # Set the third, optional argument of get to 1 if you wish to use raw mode.
   print config.get('Section1', 'foo', 0)  # -> "Python is fun!"
   print config.get('Section1', 'foo', 1)  # -> "%(bar)s is %(baz)s!"

   # The optional fourth argument is a dict with members that will take
   # precedence in interpolation.
   print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
                                           'baz': 'evil'})

Defaults are available in all three types of ConfigParsers. They are used in
interpolation if an option used is not defined elsewhere. ::

   import ConfigParser

   # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
   config = ConfigParser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
   config.read('example.cfg')

   print config.get('Section1', 'foo')  # -> "Python is fun!"
   config.remove_option('Section1', 'bar')
   config.remove_option('Section1', 'baz')
   print config.get('Section1', 'foo')  # -> "Life is hard!"

The function ``opt_move`` below can be used to move options between sections::

   def opt_move(config, section1, section2, option):
       try:
           config.set(section2, option, config.get(section1, option, 1))
       except ConfigParser.NoSectionError:
           # Create non-existent section
           config.add_section(section2)
           opt_move(config, section1, section2, option)
       else:
           config.remove_option(section1, option)

Some configuration files are known to include settings without values, but which
otherwise conform to the syntax supported by :mod:`ConfigParser`.  The
*allow_no_value* parameter to the constructor can be used to indicate that such
values should be accepted:

.. doctest::

   >>> import ConfigParser
   >>> import io

   >>> sample_config = """
   ... [mysqld]
   ... user = mysql
   ... pid-file = /var/run/mysqld/mysqld.pid
   ... skip-external-locking
   ... old_passwords = 1
   ... skip-bdb
   ... skip-innodb
   ... """
   >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
   >>> config.readfp(io.BytesIO(sample_config))

   >>> # Settings with values are treated as before:
   >>> config.get("mysqld", "user")
   'mysql'

   >>> # Settings without values provide None:
   >>> config.get("mysqld", "skip-bdb")

   >>> # Settings which aren't specified still raise an error:
   >>> config.get("mysqld", "does-not-exist")
   Traceback (most recent call last):
     ...
   ConfigParser.NoOptionError: No option 'does-not-exist' in section: 'mysqld'
PK	%�\"G�3		'html/_sources/library/constants.rst.txtnu�[���.. _built-in-consts:

Built-in Constants
==================

A small number of constants live in the built-in namespace.  They are:

.. data:: False

   The false value of the :class:`bool` type.

   .. versionadded:: 2.3


.. data:: True

   The true value of the :class:`bool` type.

   .. versionadded:: 2.3


.. data:: None

   The sole value of :attr:`types.NoneType`.  ``None`` is frequently used to
   represent the absence of a value, as when default arguments are not passed to a
   function.

   .. versionchanged:: 2.4
      Assignments to ``None`` are illegal and raise a :exc:`SyntaxError`.


.. data:: NotImplemented

   Special value which can be returned by the "rich comparison" special methods
   (:meth:`__eq__`, :meth:`__lt__`, and friends), to indicate that the comparison
   is not implemented with respect to the other type.


.. data:: Ellipsis

   Special value used in conjunction with extended slicing syntax.


.. data:: __debug__

   This constant is true if Python was not started with an :option:`-O` option.
   See also the :keyword:`assert` statement.


.. note::

   The names :data:`None` and :data:`__debug__` cannot be reassigned
   (assignments to them, even as an attribute name, raise :exc:`SyntaxError`),
   so they can be considered "true" constants.

   .. versionchanged:: 2.7
      Assignments to ``__debug__`` as an attribute became illegal.


Constants added by the :mod:`site` module
-----------------------------------------

The :mod:`site` module (which is imported automatically during startup, except
if the :option:`-S` command-line option is given) adds several constants to the
built-in namespace.  They are useful for the interactive interpreter shell and
should not be used in programs.

.. data:: quit([code=None])
          exit([code=None])

   Objects that when printed, print a message like "Use quit() or Ctrl-D
   (i.e. EOF) to exit", and when called, raise :exc:`SystemExit` with the
   specified exit code.

.. data:: copyright
          credits

   Objects that when printed or called, print the text of copyright or
   credits, respectively.

.. data:: license

   Object that when printed, prints the message "Type license() to see the
   full license text", and when called, displays the full license text in a
   pager-like fashion (one screen at a time).
PK	%�\;?L||(html/_sources/library/contextlib.rst.txtnu�[���:mod:`contextlib` --- Utilities for :keyword:`with`\ -statement contexts
========================================================================

.. module:: contextlib
   :synopsis: Utilities for with-statement contexts.


.. versionadded:: 2.5

**Source code:** :source:`Lib/contextlib.py`

--------------

This module provides utilities for common tasks involving the :keyword:`with`
statement. For more information see also :ref:`typecontextmanager` and
:ref:`context-managers`.

Functions provided:


.. function:: contextmanager(func)

   This function is a :term:`decorator` that can be used to define a factory
   function for :keyword:`with` statement context managers, without needing to
   create a class or separate :meth:`__enter__` and :meth:`__exit__` methods.

   While many objects natively support use in with statements, sometimes a
   resource needs to be managed that isn't a context manager in its own right,
   and doesn't implement a ``close()`` method for use with ``contextlib.closing``

   An abstract example would be the following to ensure correct resource
   management::

      from contextlib import contextmanager

      @contextmanager
      def managed_resource(*args, **kwds):
          # Code to acquire resource, e.g.:
          resource = acquire_resource(*args, **kwds)
          try:
              yield resource
          finally:
              # Code to release resource, e.g.:
              release_resource(resource)

      >>> with managed_resource(timeout=3600) as resource:
      ...     # Resource is released at the end of this block,
      ...     # even if code in the block raises an exception

   The function being decorated must return a :term:`generator`-iterator when
   called. This iterator must yield exactly one value, which will be bound to
   the targets in the :keyword:`with` statement's :keyword:`as` clause, if any.

   At the point where the generator yields, the block nested in the :keyword:`with`
   statement is executed.  The generator is then resumed after the block is exited.
   If an unhandled exception occurs in the block, it is reraised inside the
   generator at the point where the yield occurred.  Thus, you can use a
   :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` statement to trap
   the error (if any), or ensure that some cleanup takes place. If an exception is
   trapped merely in order to log it or to perform some action (rather than to
   suppress it entirely), the generator must reraise that exception. Otherwise the
   generator context manager will indicate to the :keyword:`with` statement that
   the exception has been handled, and execution will resume with the statement
   immediately following the :keyword:`with` statement.


.. function:: nested(mgr1[, mgr2[, ...]])

   Combine multiple context managers into a single nested context manager.

   This function has been deprecated in favour of the multiple manager form
   of the :keyword:`with` statement.

   The one advantage of this function over the multiple manager form of the
   :keyword:`with` statement is that argument unpacking allows it to be
   used with a variable number of context managers as follows::

      from contextlib import nested

      with nested(*managers):
          do_something()

   Note that if the :meth:`__exit__` method of one of the nested context managers
   indicates an exception should be suppressed, no exception information will be
   passed to any remaining outer context managers. Similarly, if the
   :meth:`__exit__` method of one of the nested managers raises an exception, any
   previous exception state will be lost; the new exception will be passed to the
   :meth:`__exit__` methods of any remaining outer context managers. In general,
   :meth:`__exit__` methods should avoid raising exceptions, and in particular they
   should not re-raise a passed-in exception.

   This function has two major quirks that have led to it being deprecated. Firstly,
   as the context managers are all constructed before the function is invoked, the
   :meth:`__new__` and :meth:`__init__` methods of the inner context managers are
   not actually covered by the scope of the outer context managers. That means, for
   example, that using :func:`nested` to open two files is a programming error as the
   first file will not be closed promptly if an exception is thrown when opening
   the second file.

   Secondly, if the :meth:`__enter__` method of one of the inner context managers
   raises an exception that is caught and suppressed by the :meth:`__exit__` method
   of one of the outer context managers, this construct will raise
   :exc:`RuntimeError` rather than skipping the body of the :keyword:`with`
   statement.

   Developers that need to support nesting of a variable number of context managers
   can either use the :mod:`warnings` module to suppress the DeprecationWarning
   raised by this function or else use this function as a model for an application
   specific implementation.

   .. deprecated:: 2.7
      The with-statement now supports this functionality directly (without the
      confusing error prone quirks).

.. function:: closing(thing)

   Return a context manager that closes *thing* upon completion of the block.  This
   is basically equivalent to::

      from contextlib import contextmanager

      @contextmanager
      def closing(thing):
          try:
              yield thing
          finally:
              thing.close()

   And lets you write code like this::

      from contextlib import closing
      import urllib

      with closing(urllib.urlopen('http://www.python.org')) as page:
          for line in page:
              print line

   without needing to explicitly close ``page``.  Even if an error occurs,
   ``page.close()`` will be called when the :keyword:`with` block is exited.


.. seealso::

   :pep:`343` - The "with" statement
      The specification, background, and examples for the Python :keyword:`with`
      statement.

PK	%�\�e4�G%G%$html/_sources/library/cookie.rst.txtnu�[���:mod:`Cookie` --- HTTP state management
=======================================

.. module:: Cookie
   :synopsis: Support for HTTP state management (cookies).
.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

.. note::
   The :mod:`Cookie` module has been renamed to :mod:`http.cookies` in Python
   3.  The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.

**Source code:** :source:`Lib/Cookie.py`

--------------

The :mod:`Cookie` module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.

The module formerly strictly applied the parsing rules described in the
:rfc:`2109` and :rfc:`2068` specifications.  It has since been discovered that
MSIE 3.0x doesn't follow the character rules outlined in those specs and also
many current day browsers and servers have relaxed parsing rules when comes to
Cookie handling.  As a result, the parsing rules used are a bit less strict.

The character set, :data:`string.ascii_letters`, :data:`string.digits` and
``!#$%&'*+-.^_`|~`` denote the set of valid characters allowed by this module
in Cookie name (as :attr:`~Morsel.key`).


.. note::

   On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
   cookie data comes from a browser you should always prepare for invalid data
   and catch :exc:`CookieError` on parsing.


.. exception:: CookieError

   Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
   incorrect :mailheader:`Set-Cookie` header, etc.


.. class:: BaseCookie([input])

   This class is a dictionary-like object whose keys are strings and whose values
   are :class:`Morsel` instances. Note that upon setting a key to a value, the
   value is first converted to a :class:`Morsel` containing the key and the value.

   If *input* is given, it is passed to the :meth:`load` method.


.. class:: SimpleCookie([input])

   This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
   and :meth:`value_encode` to be the identity and :func:`str` respectively.


.. class:: SerialCookie([input])

   This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
   and :meth:`value_encode` to be the :func:`pickle.loads` and
   :func:`pickle.dumps`.

   .. deprecated:: 2.3
      Reading pickled values from untrusted cookie data is a huge security hole, as
      pickle strings can be crafted to cause arbitrary code to execute on your server.
      It is supported for backwards compatibility only, and may eventually go away.


.. class:: SmartCookie([input])

   This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode`
   to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value
   itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it
   is a string, in which case it returns the value itself.

   .. deprecated:: 2.3
      The same security warning from :class:`SerialCookie` applies here.

A further security note is warranted.  For backwards compatibility, the
:mod:`Cookie` module exports a class named :class:`~Cookie.Cookie` which is
just an alias for :class:`SmartCookie`.  This is probably a mistake and will
likely be removed in a future version.  You should not use the
:class:`~Cookie.Cookie` class in your applications, for the same reason why
you should not use the :class:`SerialCookie` class.


.. seealso::

   Module :mod:`cookielib`
      HTTP cookie handling for web *clients*.  The :mod:`cookielib` and :mod:`Cookie`
      modules do not depend on each other.

   :rfc:`2109` - HTTP State Management Mechanism
      This is the state management specification implemented by this module.


.. _cookie-objects:

Cookie Objects
--------------


.. method:: BaseCookie.value_decode(val)

   Return a decoded value from a string representation. Return value can be any
   type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
   overridden.


.. method:: BaseCookie.value_encode(val)

   Return an encoded value. *val* can be any type, but return value must be a
   string. This method does nothing in :class:`BaseCookie` --- it exists so it can
   be overridden.

   In general, it should be the case that :meth:`value_encode` and
   :meth:`value_decode` are inverses on the range of *value_decode*.


.. method:: BaseCookie.output([attrs[, header[, sep]]])

   Return a string representation suitable to be sent as HTTP headers. *attrs* and
   *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
   to join the headers together, and is by default the combination ``'\r\n'``
   (CRLF).

   .. versionchanged:: 2.5
      The default separator has been changed from ``'\n'`` to match the cookie
      specification.


.. method:: BaseCookie.js_output([attrs])

   Return an embeddable JavaScript snippet, which, if run on a browser which
   supports JavaScript, will act the same as if the HTTP headers was sent.

   The meaning for *attrs* is the same as in :meth:`output`.


.. method:: BaseCookie.load(rawdata)

   If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
   found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::

      for k, v in rawdata.items():
          cookie[k] = v


.. _morsel-objects:

Morsel Objects
--------------


.. class:: Morsel

   Abstract a key/value pair, which has some :rfc:`2109` attributes.

   Morsels are dictionary-like objects, whose set of keys is constant --- the valid
   :rfc:`2109` attributes, which are

   * ``expires``
   * ``path``
   * ``comment``
   * ``domain``
   * ``max-age``
   * ``secure``
   * ``version``
   * ``httponly``

   The attribute :attr:`httponly` specifies that the cookie is only transferred
   in HTTP requests, and is not accessible through JavaScript. This is intended
   to mitigate some forms of cross-site scripting.

   The keys are case-insensitive.

   .. versionadded:: 2.6
      The :attr:`httponly` attribute was added.


.. attribute:: Morsel.value

   The value of the cookie.


.. attribute:: Morsel.coded_value

   The encoded value of the cookie --- this is what should be sent.


.. attribute:: Morsel.key

   The name of the cookie.


.. method:: Morsel.set(key, value, coded_value)

   Set the *key*, *value* and *coded_value* attributes.


.. method:: Morsel.isReservedKey(K)

   Whether *K* is a member of the set of keys of a :class:`Morsel`.


.. method:: Morsel.output([attrs[, header]])

   Return a string representation of the Morsel, suitable to be sent as an HTTP
   header. By default, all the attributes are included, unless *attrs* is given, in
   which case it should be a list of attributes to use. *header* is by default
   ``"Set-Cookie:"``.


.. method:: Morsel.js_output([attrs])

   Return an embeddable JavaScript snippet, which, if run on a browser which
   supports JavaScript, will act the same as if the HTTP header was sent.

   The meaning for *attrs* is the same as in :meth:`output`.


.. method:: Morsel.OutputString([attrs])

   Return a string representing the Morsel, without any surrounding HTTP or
   JavaScript.

   The meaning for *attrs* is the same as in :meth:`output`.


.. _cookie-example:

Example
-------

The following example demonstrates how to use the :mod:`Cookie` module.

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> import Cookie
   >>> C = Cookie.SimpleCookie()
   >>> C["fig"] = "newton"
   >>> C["sugar"] = "wafer"
   >>> print C # generate HTTP headers
   Set-Cookie: fig=newton
   Set-Cookie: sugar=wafer
   >>> print C.output() # same thing
   Set-Cookie: fig=newton
   Set-Cookie: sugar=wafer
   >>> C = Cookie.SimpleCookie()
   >>> C["rocky"] = "road"
   >>> C["rocky"]["path"] = "/cookie"
   >>> print C.output(header="Cookie:")
   Cookie: rocky=road; Path=/cookie
   >>> print C.output(attrs=[], header="Cookie:")
   Cookie: rocky=road
   >>> C = Cookie.SimpleCookie()
   >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
   >>> print C
   Set-Cookie: chips=ahoy
   Set-Cookie: vienna=finger
   >>> C = Cookie.SimpleCookie()
   >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
   >>> print C
   Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
   >>> C = Cookie.SimpleCookie()
   >>> C["oreo"] = "doublestuff"
   >>> C["oreo"]["path"] = "/"
   >>> print C
   Set-Cookie: oreo=doublestuff; Path=/
   >>> C["twix"] = "none for you"
   >>> C["twix"].value
   'none for you'
   >>> C = Cookie.SimpleCookie()
   >>> C["number"] = 7 # equivalent to C["number"] = str(7)
   >>> C["string"] = "seven"
   >>> C["number"].value
   '7'
   >>> C["string"].value
   'seven'
   >>> print C
   Set-Cookie: number=7
   Set-Cookie: string=seven
   >>> # SerialCookie and SmartCookie are deprecated
   >>> # using it can cause security loopholes in your code.
   >>> C = Cookie.SerialCookie()
   >>> C["number"] = 7
   >>> C["string"] = "seven"
   >>> C["number"].value
   7
   >>> C["string"].value
   'seven'
   >>> print C
   Set-Cookie: number="I7\012."
   Set-Cookie: string="S'seven'\012p1\012."
   >>> C = Cookie.SmartCookie()
   >>> C["number"] = 7
   >>> C["string"] = "seven"
   >>> C["number"].value
   7
   >>> C["string"].value
   'seven'
   >>> print C
   Set-Cookie: number="I7\012."
   Set-Cookie: string=seven

PK	%�\�r��l�l'html/_sources/library/cookielib.rst.txtnu�[���:mod:`cookielib` --- Cookie handling for HTTP clients
=====================================================

.. module:: cookielib
   :synopsis: Classes for automatic handling of HTTP cookies.
.. moduleauthor:: John J. Lee <jjl@pobox.com>
.. sectionauthor:: John J. Lee <jjl@pobox.com>

.. note::
   The :mod:`cookielib` module has been renamed to :mod:`http.cookiejar` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.

.. versionadded:: 2.4

**Source code:** :source:`Lib/cookielib.py`

--------------

The :mod:`cookielib` module defines classes for automatic handling of HTTP
cookies.  It is useful for accessing web sites that require small pieces of data
-- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.

Both the regular Netscape cookie protocol and the protocol defined by
:rfc:`2965` are handled.  RFC 2965 handling is switched off by default.
:rfc:`2109` cookies are parsed as Netscape cookies and subsequently treated
either as Netscape or RFC 2965 cookies according to the 'policy' in effect.
Note that the great majority of cookies on the Internet are Netscape cookies.
:mod:`cookielib` attempts to follow the de-facto Netscape cookie protocol (which
differs substantially from that set out in the original Netscape specification),
including taking note of the ``max-age`` and ``port`` cookie-attributes
introduced with RFC 2965.

.. note::

   The various named parameters found in :mailheader:`Set-Cookie` and
   :mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
   conventionally referred to as :dfn:`attributes`.  To distinguish them from
   Python attributes, the documentation for this module uses the term
   :dfn:`cookie-attribute` instead.


The module defines the following exception:


.. exception:: LoadError

   Instances of :class:`FileCookieJar` raise this exception on failure to load
   cookies from a file.

   .. note::

      For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`),
      :exc:`LoadError` is a subclass of :exc:`IOError`.


The following classes are provided:


.. class:: CookieJar(policy=None)

   *policy* is an object implementing the :class:`CookiePolicy` interface.

   The :class:`CookieJar` class stores HTTP cookies.  It extracts cookies from HTTP
   requests, and returns them in HTTP responses. :class:`CookieJar` instances
   automatically expire contained cookies when necessary.  Subclasses are also
   responsible for storing and retrieving cookies from a file or database.


.. class:: FileCookieJar(filename, delayload=None, policy=None)

   *policy* is an object implementing the :class:`CookiePolicy` interface.  For the
   other arguments, see the documentation for the corresponding attributes.

   A :class:`CookieJar` which can load cookies from, and perhaps save cookies to, a
   file on disk.  Cookies are **NOT** loaded from the named file until either the
   :meth:`load` or :meth:`revert` method is called.  Subclasses of this class are
   documented in section :ref:`file-cookie-jar-classes`.


.. class:: CookiePolicy()

   This class is responsible for deciding whether each cookie should be accepted
   from / returned to the server.


.. class:: DefaultCookiePolicy( blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False )

   Constructor arguments should be passed as keyword arguments only.
   *blocked_domains* is a sequence of domain names that we never accept cookies
   from, nor return cookies to. *allowed_domains* if not :const:`None`, this is a
   sequence of the only domains for which we accept and return cookies.  For all
   other arguments, see the documentation for :class:`CookiePolicy` and
   :class:`DefaultCookiePolicy` objects.

   :class:`DefaultCookiePolicy` implements the standard accept / reject rules for
   Netscape and RFC 2965 cookies.  By default, RFC 2109 cookies (ie. cookies
   received in a :mailheader:`Set-Cookie` header with a version cookie-attribute of
   1) are treated according to the RFC 2965 rules.  However, if RFC 2965 handling
   is turned off or :attr:`rfc2109_as_netscape` is ``True``, RFC 2109 cookies are
   'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by
   setting the :attr:`version` attribute of the :class:`~cookielib.Cookie` instance to 0.
   :class:`DefaultCookiePolicy` also provides some parameters to allow some
   fine-tuning of policy.


.. class:: Cookie()

   This class represents Netscape, RFC 2109 and RFC 2965 cookies.  It is not
   expected that users of :mod:`cookielib` construct their own :class:`~cookielib.Cookie`
   instances.  Instead, if necessary, call :meth:`make_cookies` on a
   :class:`CookieJar` instance.


.. seealso::

   Module :mod:`urllib2`
      URL opening with automatic cookie handling.

   Module :mod:`Cookie`
      HTTP cookie classes, principally useful for server-side code.  The
      :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other.

   https://curl.haxx.se/rfc/cookie_spec.html
      The specification of the original Netscape cookie protocol.  Though this is
      still the dominant protocol, the 'Netscape cookie protocol' implemented by all
      the major browsers (and :mod:`cookielib`) only bears a passing resemblance to
      the one sketched out in ``cookie_spec.html``.

   :rfc:`2109` - HTTP State Management Mechanism
      Obsoleted by RFC 2965. Uses :mailheader:`Set-Cookie` with version=1.

   :rfc:`2965` - HTTP State Management Mechanism
      The Netscape protocol with the bugs fixed.  Uses :mailheader:`Set-Cookie2` in
      place of :mailheader:`Set-Cookie`.  Not widely used.

   http://kristol.org/cookie/errata.html
      Unfinished errata to RFC 2965.

   :rfc:`2964` - Use of HTTP State Management

.. _cookie-jar-objects:

CookieJar and FileCookieJar Objects
-----------------------------------

:class:`CookieJar` objects support the :term:`iterator` protocol for iterating over
contained :class:`~cookielib.Cookie` objects.

:class:`CookieJar` has the following methods:


.. method:: CookieJar.add_cookie_header(request)

   Add correct :mailheader:`Cookie` header to *request*.

   If policy allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of
   the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false
   respectively), the :mailheader:`Cookie2` header is also added when appropriate.

   The *request* object (usually a :class:`urllib2.Request` instance) must support
   the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`get_type`,
   :meth:`unverifiable`, :meth:`get_origin_req_host`, :meth:`has_header`,
   :meth:`get_header`, :meth:`header_items`, and :meth:`add_unredirected_header`,as
   documented by :mod:`urllib2`.


.. method:: CookieJar.extract_cookies(response, request)

   Extract cookies from HTTP *response* and store them in the :class:`CookieJar`,
   where allowed by policy.

   The :class:`CookieJar` will look for allowable :mailheader:`Set-Cookie` and
   :mailheader:`Set-Cookie2` headers in the *response* argument, and store cookies
   as appropriate (subject to the :meth:`CookiePolicy.set_ok` method's approval).

   The *response* object (usually the result of a call to :meth:`urllib2.urlopen`,
   or similar) should support an :meth:`info` method, which returns an object with
   a :meth:`getallmatchingheaders` method (usually a :class:`mimetools.Message`
   instance).

   The *request* object (usually a :class:`urllib2.Request` instance) must support
   the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`unverifiable`, and
   :meth:`get_origin_req_host`, as documented by :mod:`urllib2`.  The request is
   used to set default values for cookie-attributes as well as for checking that
   the cookie is allowed to be set.


.. method:: CookieJar.set_policy(policy)

   Set the :class:`CookiePolicy` instance to be used.


.. method:: CookieJar.make_cookies(response, request)

   Return sequence of :class:`~cookielib.Cookie` objects extracted from *response* object.

   See the documentation for :meth:`extract_cookies` for the interfaces required of
   the *response* and *request* arguments.


.. method:: CookieJar.set_cookie_if_ok(cookie, request)

   Set a :class:`~cookielib.Cookie` if policy says it's OK to do so.


.. method:: CookieJar.set_cookie(cookie)

   Set a :class:`~cookielib.Cookie`, without checking with policy to see whether or not it
   should be set.


.. method:: CookieJar.clear([domain[, path[, name]]])

   Clear some cookies.

   If invoked without arguments, clear all cookies.  If given a single argument,
   only cookies belonging to that *domain* will be removed. If given two arguments,
   cookies belonging to the specified *domain* and URL *path* are removed.  If
   given three arguments, then the cookie with the specified *domain*, *path* and
   *name* is removed.

   Raises :exc:`KeyError` if no matching cookie exists.


.. method:: CookieJar.clear_session_cookies()

   Discard all session cookies.

   Discards all contained cookies that have a true :attr:`discard` attribute
   (usually because they had either no ``max-age`` or ``expires`` cookie-attribute,
   or an explicit ``discard`` cookie-attribute).  For interactive browsers, the end
   of a session usually corresponds to closing the browser window.

   Note that the :meth:`save` method won't save session cookies anyway, unless you
   ask otherwise by passing a true *ignore_discard* argument.

:class:`FileCookieJar` implements the following additional methods:


.. method:: FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)

   Save cookies to a file.

   This base class raises :exc:`NotImplementedError`.  Subclasses may leave this
   method unimplemented.

   *filename* is the name of file in which to save cookies.  If *filename* is not
   specified, :attr:`self.filename` is used (whose default is the value passed to
   the constructor, if any); if :attr:`self.filename` is :const:`None`,
   :exc:`ValueError` is raised.

   *ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save
   even cookies that have expired

   The file is overwritten if it already exists, thus wiping all the cookies it
   contains.  Saved cookies can be restored later using the :meth:`load` or
   :meth:`revert` methods.


.. method:: FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)

   Load cookies from a file.

   Old cookies are kept unless overwritten by newly loaded ones.

   Arguments are as for :meth:`save`.

   The named file must be in the format understood by the class, or
   :exc:`LoadError` will be raised.  Also, :exc:`IOError` may be raised, for
   example if the file does not exist.

   .. note::

      For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`),
      :exc:`LoadError` is a subclass of :exc:`IOError`.


.. method:: FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)

   Clear all cookies and reload cookies from a saved file.

   :meth:`revert` can raise the same exceptions as :meth:`load`. If there is a
   failure, the object's state will not be altered.

:class:`FileCookieJar` instances have the following public attributes:


.. attribute:: FileCookieJar.filename

   Filename of default file in which to keep cookies.  This attribute may be
   assigned to.


.. attribute:: FileCookieJar.delayload

   If true, load cookies lazily from disk.  This attribute should not be assigned
   to.  This is only a hint, since this only affects performance, not behaviour
   (unless the cookies on disk are changing). A :class:`CookieJar` object may
   ignore it.  None of the :class:`FileCookieJar` classes included in the standard
   library lazily loads cookies.


.. _file-cookie-jar-classes:

FileCookieJar subclasses and co-operation with web browsers
-----------------------------------------------------------

The following :class:`CookieJar` subclasses are provided for reading and
writing.

.. class:: MozillaCookieJar(filename, delayload=None, policy=None)

   A :class:`FileCookieJar` that can load from and save cookies to disk in the
   Mozilla ``cookies.txt`` file format (which is also used by the Lynx and Netscape
   browsers).

   .. note::

      Version 3 of the Firefox web browser no longer writes cookies in the
      ``cookies.txt`` file format.

   .. note::

      This loses information about RFC 2965 cookies, and also about newer or
      non-standard cookie-attributes such as ``port``.

   .. warning::

      Back up your cookies before saving if you have cookies whose loss / corruption
      would be inconvenient (there are some subtleties which may lead to slight
      changes in the file over a load / save round-trip).

   Also note that cookies saved while Mozilla is running will get clobbered by
   Mozilla.


.. class:: LWPCookieJar(filename, delayload=None, policy=None)

   A :class:`FileCookieJar` that can load from and save cookies to disk in format
   compatible with the libwww-perl library's ``Set-Cookie3`` file format.  This is
   convenient if you want to store cookies in a human-readable file.


.. _cookie-policy-objects:

CookiePolicy Objects
--------------------

Objects implementing the :class:`CookiePolicy` interface have the following
methods:


.. method:: CookiePolicy.set_ok(cookie, request)

   Return boolean value indicating whether cookie should be accepted from server.

   *cookie* is a :class:`cookielib.Cookie` instance.  *request* is an object
   implementing the interface defined by the documentation for
   :meth:`CookieJar.extract_cookies`.


.. method:: CookiePolicy.return_ok(cookie, request)

   Return boolean value indicating whether cookie should be returned to server.

   *cookie* is a :class:`cookielib.Cookie` instance.  *request* is an object
   implementing the interface defined by the documentation for
   :meth:`CookieJar.add_cookie_header`.


.. method:: CookiePolicy.domain_return_ok(domain, request)

   Return false if cookies should not be returned, given cookie domain.

   This method is an optimization.  It removes the need for checking every cookie
   with a particular domain (which might involve reading many files).  Returning
   true from :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the
   work to :meth:`return_ok`.

   If :meth:`domain_return_ok` returns true for the cookie domain,
   :meth:`path_return_ok` is called for the cookie path.  Otherwise,
   :meth:`path_return_ok` and :meth:`return_ok` are never called for that cookie
   domain.  If :meth:`path_return_ok` returns true, :meth:`return_ok` is called
   with the :class:`~cookielib.Cookie` object itself for a full check.  Otherwise,
   :meth:`return_ok` is never called for that cookie path.

   Note that :meth:`domain_return_ok` is called for every *cookie* domain, not just
   for the *request* domain.  For example, the function might be called with both
   ``".example.com"`` and ``"www.example.com"`` if the request domain is
   ``"www.example.com"``.  The same goes for :meth:`path_return_ok`.

   The *request* argument is as documented for :meth:`return_ok`.


.. method:: CookiePolicy.path_return_ok(path, request)

   Return false if cookies should not be returned, given cookie path.

   See the documentation for :meth:`domain_return_ok`.

In addition to implementing the methods above, implementations of the
:class:`CookiePolicy` interface must also supply the following attributes,
indicating which protocols should be used, and how.  All of these attributes may
be assigned to.


.. attribute:: CookiePolicy.netscape

   Implement Netscape protocol.


.. attribute:: CookiePolicy.rfc2965

   Implement RFC 2965 protocol.


.. attribute:: CookiePolicy.hide_cookie2

   Don't add :mailheader:`Cookie2` header to requests (the presence of this header
   indicates to the server that we understand RFC 2965 cookies).

The most useful way to define a :class:`CookiePolicy` class is by subclassing
from :class:`DefaultCookiePolicy` and overriding some or all of the methods
above.  :class:`CookiePolicy` itself may be used as a 'null policy' to allow
setting and receiving any and all cookies (this is unlikely to be useful).


.. _default-cookie-policy-objects:

DefaultCookiePolicy Objects
---------------------------

Implements the standard rules for accepting and returning cookies.

Both RFC 2965 and Netscape cookies are covered.  RFC 2965 handling is switched
off by default.

The easiest way to provide your own policy is to override this class and call
its methods in your overridden implementations before adding your own additional
checks::

   import cookielib
   class MyCookiePolicy(cookielib.DefaultCookiePolicy):
       def set_ok(self, cookie, request):
           if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request):
               return False
           if i_dont_want_to_store_this_cookie(cookie):
               return False
           return True

In addition to the features required to implement the :class:`CookiePolicy`
interface, this class allows you to block and allow domains from setting and
receiving cookies.  There are also some strictness switches that allow you to
tighten up the rather loose Netscape protocol rules a little bit (at the cost of
blocking some benign cookies).

A domain blacklist and whitelist is provided (both off by default). Only domains
not in the blacklist and present in the whitelist (if the whitelist is active)
participate in cookie setting and returning.  Use the *blocked_domains*
constructor argument, and :meth:`blocked_domains` and
:meth:`set_blocked_domains` methods (and the corresponding argument and methods
for *allowed_domains*).  If you set a whitelist, you can turn it off again by
setting it to :const:`None`.

Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched.  For example, ``"example.com"`` matches a blacklist
entry of ``"example.com"``, but ``"www.example.com"`` does not.  Domains that do
start with a dot are matched by more specific domains too. For example, both
``"www.example.com"`` and ``"www.coyote.example.com"`` match ``".example.com"``
(but ``"example.com"`` itself does not).  IP addresses are an exception, and
must match exactly.  For example, if blocked_domains contains ``"192.168.1.2"``
and ``".168.1.2"``, 192.168.1.2 is blocked, but 193.168.1.2 is not.

:class:`DefaultCookiePolicy` implements the following additional methods:


.. method:: DefaultCookiePolicy.blocked_domains()

   Return the sequence of blocked domains (as a tuple).


.. method:: DefaultCookiePolicy.set_blocked_domains(blocked_domains)

   Set the sequence of blocked domains.


.. method:: DefaultCookiePolicy.is_blocked(domain)

   Return whether *domain* is on the blacklist for setting or receiving cookies.


.. method:: DefaultCookiePolicy.allowed_domains()

   Return :const:`None`, or the sequence of allowed domains (as a tuple).


.. method:: DefaultCookiePolicy.set_allowed_domains(allowed_domains)

   Set the sequence of allowed domains, or :const:`None`.


.. method:: DefaultCookiePolicy.is_not_allowed(domain)

   Return whether *domain* is not on the whitelist for setting or receiving
   cookies.

:class:`DefaultCookiePolicy` instances have the following attributes, which are
all initialised from the constructor arguments of the same name, and which may
all be assigned to.


.. attribute:: DefaultCookiePolicy.rfc2109_as_netscape

   If true, request that the :class:`CookieJar` instance downgrade RFC 2109 cookies
   (ie. cookies received in a :mailheader:`Set-Cookie` header with a version
   cookie-attribute of 1) to Netscape cookies by setting the version attribute of
   the :class:`~cookielib.Cookie` instance to 0.  The default value is :const:`None`, in which
   case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned
   off.  Therefore, RFC 2109 cookies are downgraded by default.

   .. versionadded:: 2.5

General strictness switches:


.. attribute:: DefaultCookiePolicy.strict_domain

   Don't allow sites to set two-component domains with country-code top-level
   domains like ``.co.uk``, ``.gov.uk``, ``.co.nz``.etc.  This is far from perfect
   and isn't guaranteed to work!

RFC 2965 protocol strictness switches:


.. attribute:: DefaultCookiePolicy.strict_rfc2965_unverifiable

   Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable
   transaction is one resulting from a redirect or a request for an image hosted on
   another site).  If this is false, cookies are *never* blocked on the basis of
   verifiability

Netscape protocol strictness switches:


.. attribute:: DefaultCookiePolicy.strict_ns_unverifiable

   Apply RFC 2965 rules on unverifiable transactions even to Netscape cookies.


.. attribute:: DefaultCookiePolicy.strict_ns_domain

   Flags indicating how strict to be with domain-matching rules for Netscape
   cookies.  See below for acceptable values.


.. attribute:: DefaultCookiePolicy.strict_ns_set_initial_dollar

   Ignore cookies in Set-Cookie: headers that have names starting with ``'$'``.


.. attribute:: DefaultCookiePolicy.strict_ns_set_path

   Don't allow setting cookies whose path doesn't path-match request URI.

:attr:`strict_ns_domain` is a collection of flags.  Its value is constructed by
or-ing together (for example, ``DomainStrictNoDots|DomainStrictNonDomain`` means
both flags are set).


.. attribute:: DefaultCookiePolicy.DomainStrictNoDots

   When setting cookies, the 'host prefix' must not contain a dot (eg.
   ``www.foo.bar.com`` can't set a cookie for ``.bar.com``, because ``www.foo``
   contains a dot).


.. attribute:: DefaultCookiePolicy.DomainStrictNonDomain

   Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
   be returned to a domain equal to the domain that set the cookie (eg.
   ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
   ``domain`` cookie-attribute).


.. attribute:: DefaultCookiePolicy.DomainRFC2965Match

   When setting cookies, require a full RFC 2965 domain-match.

The following attributes are provided for convenience, and are the most useful
combinations of the above flags:


.. attribute:: DefaultCookiePolicy.DomainLiberal

   Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched
   off).


.. attribute:: DefaultCookiePolicy.DomainStrict

   Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``.


.. _cookielib-cookie-objects:

Cookie Objects
--------------

:class:`~cookielib.Cookie` instances have Python attributes roughly corresponding to the
standard cookie-attributes specified in the various cookie standards.  The
correspondence is not one-to-one, because there are complicated rules for
assigning default values, because the ``max-age`` and ``expires``
cookie-attributes contain equivalent information, and because RFC 2109 cookies
may be 'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape)
cookies.

Assignment to these attributes should not be necessary other than in rare
circumstances in a :class:`CookiePolicy` method.  The class does not enforce
internal consistency, so you should know what you're doing if you do that.


.. attribute:: Cookie.version

   Integer or :const:`None`.  Netscape cookies have :attr:`version` 0. RFC 2965 and
   RFC 2109 cookies have a ``version`` cookie-attribute of 1.  However, note that
   :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
   case :attr:`version` is 0.


.. attribute:: Cookie.name

   Cookie name (a string).


.. attribute:: Cookie.value

   Cookie value (a string), or :const:`None`.


.. attribute:: Cookie.port

   String representing a port or a set of ports (eg. '80', or '80,8080'), or
   :const:`None`.


.. attribute:: Cookie.path

   Cookie path (a string, eg. ``'/acme/rocket_launchers'``).


.. attribute:: Cookie.secure

   ``True`` if cookie should only be returned over a secure connection.


.. attribute:: Cookie.expires

   Integer expiry date in seconds since epoch, or :const:`None`.  See also the
   :meth:`is_expired` method.


.. attribute:: Cookie.discard

   ``True`` if this is a session cookie.


.. attribute:: Cookie.comment

   String comment from the server explaining the function of this cookie, or
   :const:`None`.


.. attribute:: Cookie.comment_url

   URL linking to a comment from the server explaining the function of this cookie,
   or :const:`None`.


.. attribute:: Cookie.rfc2109

   ``True`` if this cookie was received as an RFC 2109 cookie (ie. the cookie
   arrived in a :mailheader:`Set-Cookie` header, and the value of the Version
   cookie-attribute in that header was 1).  This attribute is provided because
   :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in
   which case :attr:`version` is 0.

   .. versionadded:: 2.5


.. attribute:: Cookie.port_specified

   ``True`` if a port or set of ports was explicitly specified by the server (in the
   :mailheader:`Set-Cookie` / :mailheader:`Set-Cookie2` header).


.. attribute:: Cookie.domain_specified

   ``True`` if a domain was explicitly specified by the server.


.. attribute:: Cookie.domain_initial_dot

   ``True`` if the domain explicitly specified by the server began with a dot
   (``'.'``).

Cookies may have additional non-standard cookie-attributes.  These may be
accessed using the following methods:


.. method:: Cookie.has_nonstandard_attr(name)

   Return true if cookie has the named cookie-attribute.


.. method:: Cookie.get_nonstandard_attr(name, default=None)

   If cookie has the named cookie-attribute, return its value. Otherwise, return
   *default*.


.. method:: Cookie.set_nonstandard_attr(name, value)

   Set the value of the named cookie-attribute.

The :class:`~cookielib.Cookie` class also defines the following method:


.. method:: Cookie.is_expired([now=None])

   ``True`` if cookie has passed the time at which the server requested it should
   expire.  If *now* is given (in seconds since the epoch), return whether the
   cookie has expired at the specified time.


.. _cookielib-examples:

Examples
--------

The first example shows the most common usage of :mod:`cookielib`::

   import cookielib, urllib2
   cj = cookielib.CookieJar()
   opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
   r = opener.open("http://example.com/")

This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
cookies (assumes Unix/Netscape convention for location of the cookies file)::

   import os, cookielib, urllib2
   cj = cookielib.MozillaCookieJar()
   cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
   opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
   r = opener.open("http://example.com/")

The next example illustrates the use of :class:`DefaultCookiePolicy`. Turn on
RFC 2965 cookies, be more strict about domains when setting and returning
Netscape cookies, and block some domains from setting cookies or having them
returned::

   import urllib2
   from cookielib import CookieJar, DefaultCookiePolicy
   policy = DefaultCookiePolicy(
       rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict,
       blocked_domains=["ads.net", ".ads.net"])
   cj = CookieJar(policy)
   opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
   r = opener.open("http://example.com/")

PK	%�\�`R�

"html/_sources/library/copy.rst.txtnu�[���:mod:`copy` --- Shallow and deep copy operations
================================================

.. module:: copy
   :synopsis: Shallow and deep copy operations.

Assignment statements in Python do not copy objects, they create bindings
between a target and an object. For collections that are mutable or contain
mutable items, a copy is sometimes needed so one can change one copy without
changing the other. This module provides generic shallow and deep copy
operations (explained below).


Interface summary:

.. function:: copy(x)

   Return a shallow copy of *x*.


.. function:: deepcopy(x)

   Return a deep copy of *x*.


.. exception:: error

   Raised for module specific errors.


The difference between shallow and deep copying is only relevant for compound
objects (objects that contain other objects, like lists or class instances):

* A *shallow copy* constructs a new compound object and then (to the extent
  possible) inserts *references* into it to the objects found in the original.

* A *deep copy* constructs a new compound object and then, recursively, inserts
  *copies* into it of the objects found in the original.

Two problems often exist with deep copy operations that don't exist with shallow
copy operations:

* Recursive objects (compound objects that, directly or indirectly, contain a
  reference to themselves) may cause a recursive loop.

* Because deep copy copies everything it may copy too much, such as data
  which is intended to be shared between copies.

The :func:`deepcopy` function avoids these problems by:

* keeping a "memo" dictionary of objects already copied during the current
  copying pass; and

* letting user-defined classes override the copying operation or the set of
  components copied.

This module does not copy types like module, method, stack trace, stack frame,
file, socket, window, array, or any similar types.  It does "copy" functions and
classes (shallow and deeply), by returning the original object unchanged; this
is compatible with the way these are treated by the :mod:`pickle` module.

Shallow copies of dictionaries can be made using :meth:`dict.copy`, and
of lists by assigning a slice of the entire list, for example,
``copied_list = original_list[:]``.

.. versionchanged:: 2.5
   Added copying functions.

.. index:: module: pickle

Classes can use the same interfaces to control copying that they use to control
pickling.  See the description of module :mod:`pickle` for information on these
methods.  The :mod:`copy` module does not use the :mod:`copy_reg` registration
module.

.. index::
   single: __copy__() (copy protocol)
   single: __deepcopy__() (copy protocol)

In order for a class to define its own copy implementation, it can define
special methods :meth:`__copy__` and :meth:`__deepcopy__`.  The former is called
to implement the shallow copy operation; no additional arguments are passed.
The latter is called to implement the deep copy operation; it is passed one
argument, the memo dictionary.  If the :meth:`__deepcopy__` implementation needs
to make a deep copy of a component, it should call the :func:`deepcopy` function
with the component as first argument and the memo dictionary as second argument.


.. seealso::

   Module :mod:`pickle`
      Discussion of the special methods used to support object state retrieval and
      restoration.

PK	%�\��		&html/_sources/library/copy_reg.rst.txtnu�[���:mod:`copy_reg` --- Register :mod:`pickle` support functions
============================================================

.. module:: copy_reg
   :synopsis: Register pickle support functions.

.. note::
   The :mod:`copy_reg` module has been renamed to :mod:`copyreg` in Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

.. index::
   module: pickle
   module: cPickle
   module: copy

The :mod:`copy_reg` module offers a way to define functions used while pickling
specific objects.  The :mod:`pickle`, :mod:`cPickle`, and :mod:`copy` modules
use those functions when pickling/copying those objects.  The module provides
configuration information about object constructors which are not classes.
Such constructors may be factory functions or class instances.


.. function:: constructor(object)

   Declares *object* to be a valid constructor.  If *object* is not callable (and
   hence not valid as a constructor), raises :exc:`TypeError`.


.. function:: pickle(type, function[, constructor])

   Declares that *function* should be used as a "reduction" function for objects of
   type *type*; *type* must not be a "classic" class object.  (Classic classes are
   handled differently; see the documentation for the :mod:`pickle` module for
   details.)  *function* should return either a string or a tuple containing two or
   three elements.

   The optional *constructor* parameter, if provided, is a callable object which
   can be used to reconstruct the object when called with the tuple of arguments
   returned by *function* at pickling time.  :exc:`TypeError` will be raised if
   *object* is a class or *constructor* is not callable.

   See the :mod:`pickle` module for more details on the interface expected of
   *function* and *constructor*.

Example
-------

The example below would like to show how to register a pickle function and how
it will be used:

   >>> import copy_reg, copy, pickle
   >>> class C(object):
   ...     def __init__(self, a):
   ...         self.a = a
   ...
   >>> def pickle_c(c):
   ...     print("pickling a C instance...")
   ...     return C, (c.a,)
   ...
   >>> copy_reg.pickle(C, pickle_c)
   >>> c = C(1)
   >>> d = copy.copy(c)
   pickling a C instance...
   >>> p = pickle.dumps(c)
   pickling a C instance...
PK	%�\�w���#html/_sources/library/crypt.rst.txtnu�[���
:mod:`crypt` --- Function to check Unix passwords
=================================================

.. module:: crypt
   :platform: Unix
   :synopsis: The crypt() function used to check Unix passwords.
.. moduleauthor:: Steven D. Majewski <sdm7g@virginia.edu>
.. sectionauthor:: Steven D. Majewski <sdm7g@virginia.edu>
.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>


.. index::
   single: crypt(3)
   pair: cipher; DES

This module implements an interface to the :manpage:`crypt(3)` routine, which is
a one-way hash function based upon a modified DES algorithm; see the Unix man
page for further details.  Possible uses include allowing Python scripts to
accept typed passwords from the user, or attempting to crack Unix passwords with
a dictionary.

.. index:: single: crypt(3)

Notice that the behavior of this module depends on the actual implementation  of
the :manpage:`crypt(3)` routine in the running system.  Therefore, any
extensions available on the current implementation will also  be available on
this module.


.. function:: crypt(word, salt)

   *word* will usually be a user's password as typed at a prompt or  in a graphical
   interface.  *salt* is usually a random two-character string which will be used
   to perturb the DES algorithm in one of 4096 ways.  The characters in *salt* must
   be in the set ``[./a-zA-Z0-9]``.  Returns the hashed password as a string, which
   will be composed of characters from the same alphabet as the salt (the first two
   characters represent the salt itself).

   .. index:: single: crypt(3)

   Since a few :manpage:`crypt(3)` extensions allow different values, with
   different sizes in the *salt*, it is recommended to use  the full crypted
   password as salt when checking for a password.

A simple example illustrating typical use::

   import crypt, getpass, pwd

   def login():
       username = raw_input('Python login:')
       cryptedpasswd = pwd.getpwnam(username)[1]
       if cryptedpasswd:
           if cryptedpasswd == 'x' or cryptedpasswd == '*':
               raise NotImplementedError(
                   "Sorry, currently no support for shadow passwords")
           cleartext = getpass.getpass()
           return crypt.crypt(cleartext, cryptedpasswd) == cryptedpasswd
       else:
           return 1

PK	%�\ñ�&cc$html/_sources/library/crypto.rst.txtnu�[���
.. _crypto:

**********************
Cryptographic Services
**********************

.. index:: single: cryptography

The modules described in this chapter implement various algorithms of a
cryptographic nature.  They are available at the discretion of the installation.
Here's an overview:


.. toctree::

   hashlib.rst
   hmac.rst
   md5.rst
   sha.rst
PK	%�\�V�~�X�X!html/_sources/library/csv.rst.txtnu�[���
:mod:`csv` --- CSV File Reading and Writing
===========================================

.. module:: csv
   :synopsis: Write and read tabular data to and from delimited files.
.. sectionauthor:: Skip Montanaro <skip@pobox.com>


.. versionadded:: 2.3

.. index::
   single: csv
   pair: data; tabular

The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.  There is no "CSV standard", so
the format is operationally defined by the many applications which read and
write it.  The lack of a standard means that subtle differences often exist in
the data produced and consumed by different applications.  These differences can
make it annoying to process CSV files from multiple sources.  Still, while the
delimiters and quoting characters vary, the overall format is similar enough
that it is possible to write a single module which can efficiently manipulate
such data, hiding the details of reading and writing the data from the
programmer.

The :mod:`csv` module implements classes to read and write tabular data in CSV
format.  It allows programmers to say, "write this data in the format preferred
by Excel," or "read data from this file which was generated by Excel," without
knowing the precise details of the CSV format used by Excel.  Programmers can
also describe the CSV formats understood by other applications or define their
own special-purpose CSV formats.

The :mod:`csv` module's :class:`reader` and :class:`writer` objects read and
write sequences.  Programmers can also read and write data in dictionary form
using the :class:`DictReader` and :class:`DictWriter` classes.

.. note::

   This version of the :mod:`csv` module doesn't support Unicode input.  Also,
   there are currently some issues regarding ASCII NUL characters.  Accordingly,
   all input should be UTF-8 or printable ASCII to be safe; see the examples in
   section :ref:`csv-examples`.


.. seealso::

   :pep:`305` - CSV File API
      The Python Enhancement Proposal which proposed this addition to Python.


.. _csv-contents:

Module Contents
---------------

The :mod:`csv` module defines the following functions:


.. function:: reader(csvfile, dialect='excel', **fmtparams)

   Return a reader object which will iterate over lines in the given *csvfile*.
   *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
   string each time its :meth:`!next` method is called --- file objects and list
   objects are both suitable.   If *csvfile* is a file object, it must be opened
   with the 'b' flag on platforms where that makes a difference.  An optional
   *dialect* parameter can be given which is used to define a set of parameters
   specific to a particular CSV dialect.  It may be an instance of a subclass of
   the :class:`Dialect` class or one of the strings returned by the
   :func:`list_dialects` function.  The other optional *fmtparams* keyword arguments
   can be given to override individual formatting parameters in the current
   dialect.  For full details about the dialect and formatting parameters, see
   section :ref:`csv-fmt-params`.

   Each row read from the csv file is returned as a list of strings.  No
   automatic data type conversion is performed.

   A short usage example::

      >>> import csv
      >>> with open('eggs.csv', 'rb') as csvfile:
      ...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
      ...     for row in spamreader:
      ...         print ', '.join(row)
      Spam, Spam, Spam, Spam, Spam, Baked Beans
      Spam, Lovely Spam, Wonderful Spam

   .. versionchanged:: 2.5
      The parser is now stricter with respect to multi-line quoted fields. Previously,
      if a line ended within a quoted field without a terminating newline character, a
      newline would be inserted into the returned field. This behavior caused problems
      when reading files which contained carriage return characters within fields.
      The behavior was changed to return the field without inserting newlines. As a
      consequence, if newlines embedded within fields are important, the input should
      be split into lines in a manner which preserves the newline characters.


.. function:: writer(csvfile, dialect='excel', **fmtparams)

   Return a writer object responsible for converting the user's data into delimited
   strings on the given file-like object.  *csvfile* can be any object with a
   :func:`write` method.  If *csvfile* is a file object, it must be opened with the
   'b' flag on platforms where that makes a difference.  An optional *dialect*
   parameter can be given which is used to define a set of parameters specific to a
   particular CSV dialect.  It may be an instance of a subclass of the
   :class:`Dialect` class or one of the strings returned by the
   :func:`list_dialects` function.  The other optional *fmtparams* keyword arguments
   can be given to override individual formatting parameters in the current
   dialect.  For full details about the dialect and formatting parameters, see
   section :ref:`csv-fmt-params`. To make it
   as easy as possible to interface with modules which implement the DB API, the
   value :const:`None` is written as the empty string.  While this isn't a
   reversible transformation, it makes it easier to dump SQL NULL data values to
   CSV files without preprocessing the data returned from a ``cursor.fetch*`` call.
   Floats are stringified with :func:`repr` before being written.
   All other non-string data are stringified with :func:`str` before being written.

   A short usage example::

      import csv
      with open('eggs.csv', 'wb') as csvfile:
          spamwriter = csv.writer(csvfile, delimiter=' ',
                                  quotechar='|', quoting=csv.QUOTE_MINIMAL)
          spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
          spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])


.. function:: register_dialect(name[, dialect], **fmtparams)

   Associate *dialect* with *name*.  *name* must be a string or Unicode object. The
   dialect can be specified either by passing a sub-class of :class:`Dialect`, or
   by *fmtparams* keyword arguments, or both, with keyword arguments overriding
   parameters of the dialect. For full details about the dialect and formatting
   parameters, see section :ref:`csv-fmt-params`.


.. function:: unregister_dialect(name)

   Delete the dialect associated with *name* from the dialect registry.  An
   :exc:`Error` is raised if *name* is not a registered dialect name.


.. function:: get_dialect(name)

   Return the dialect associated with *name*.  An :exc:`Error` is raised if *name*
   is not a registered dialect name.

   .. versionchanged:: 2.5
      This function now returns an immutable :class:`Dialect`.  Previously an
      instance of the requested dialect was returned.  Users could modify the
      underlying class, changing the behavior of active readers and writers.

.. function:: list_dialects()

   Return the names of all registered dialects.


.. function:: field_size_limit([new_limit])

   Returns the current maximum field size allowed by the parser. If *new_limit* is
   given, this becomes the new limit.

   .. versionadded:: 2.5

The :mod:`csv` module defines the following classes:


.. class:: DictReader(f, fieldnames=None, restkey=None, restval=None, \
                      dialect='excel', *args, **kwds)

   Create an object which operates like a regular reader but maps the
   information read into a dict whose keys are given by the optional
   *fieldnames* parameter.  The *fieldnames* parameter is a :ref:`sequence
   <collections-abstract-base-classes>` whose elements are associated with the
   fields of the input data in order. These elements become the keys of the
   resulting dictionary.  If the *fieldnames* parameter is omitted, the values
   in the first row of the file *f* will be used as the fieldnames.  If the
   row read has more fields than the fieldnames sequence, the remaining data is
   added as a sequence keyed by the value of *restkey*.  If the row read has
   fewer fields than the fieldnames sequence, the remaining keys take the value
   of the optional *restval* parameter.  Any other optional or keyword
   arguments are passed to the underlying :class:`reader` instance.

   A short usage example::

       >>> import csv
       >>> with open('names.csv') as csvfile:
       ...     reader = csv.DictReader(csvfile)
       ...     for row in reader:
       ...         print(row['first_name'], row['last_name'])
       ...
       Baked Beans
       Lovely Spam
       Wonderful Spam


.. class:: DictWriter(f, fieldnames, restval='', extrasaction='raise', \
                      dialect='excel', *args, **kwds)

   Create an object which operates like a regular writer but maps dictionaries
   onto output rows.  The *fieldnames* parameter is a :ref:`sequence
   <collections-abstract-base-classes>` of keys that identify the order in
   which values in the dictionary passed to the :meth:`writerow` method are
   written to the file *f*.  The optional *restval* parameter specifies the
   value to be written if the dictionary is missing a key in *fieldnames*.  If
   the dictionary passed to the :meth:`writerow` method contains a key not
   found in *fieldnames*, the optional *extrasaction* parameter indicates what
   action to take.  If it is set to ``'raise'`` a :exc:`ValueError` is raised.
   If it is set to ``'ignore'``, extra values in the dictionary are ignored.
   Any other optional or keyword arguments are passed to the underlying
   :class:`writer` instance.

   Note that unlike the :class:`DictReader` class, the *fieldnames* parameter
   of the :class:`DictWriter` is not optional.  Since Python's :class:`dict`
   objects are not ordered, there is not enough information available to deduce
   the order in which the row should be written to the file *f*.

   A short usage example::

       import csv

       with open('names.csv', 'w') as csvfile:
           fieldnames = ['first_name', 'last_name']
           writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

           writer.writeheader()
           writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
           writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'})
           writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'})


.. class:: Dialect

   The :class:`Dialect` class is a container class relied on primarily for its
   attributes, which are used to define the parameters for a specific
   :class:`reader` or :class:`writer` instance.


.. class:: excel()

   The :class:`excel` class defines the usual properties of an Excel-generated CSV
   file.  It is registered with the dialect name ``'excel'``.


.. class:: excel_tab()

   The :class:`excel_tab` class defines the usual properties of an Excel-generated
   TAB-delimited file.  It is registered with the dialect name ``'excel-tab'``.


.. class:: Sniffer()

   The :class:`Sniffer` class is used to deduce the format of a CSV file.

   The :class:`Sniffer` class provides two methods:

   .. method:: sniff(sample, delimiters=None)

      Analyze the given *sample* and return a :class:`Dialect` subclass
      reflecting the parameters found.  If the optional *delimiters* parameter
      is given, it is interpreted as a string containing possible valid
      delimiter characters.


   .. method:: has_header(sample)

      Analyze the sample text (presumed to be in CSV format) and return
      :const:`True` if the first row appears to be a series of column headers.

An example for :class:`Sniffer` use::

   with open('example.csv', 'rb') as csvfile:
       dialect = csv.Sniffer().sniff(csvfile.read(1024))
       csvfile.seek(0)
       reader = csv.reader(csvfile, dialect)
       # ... process CSV file contents here ...


The :mod:`csv` module defines the following constants:

.. data:: QUOTE_ALL

   Instructs :class:`writer` objects to quote all fields.


.. data:: QUOTE_MINIMAL

   Instructs :class:`writer` objects to only quote those fields which contain
   special characters such as *delimiter*, *quotechar* or any of the characters in
   *lineterminator*.


.. data:: QUOTE_NONNUMERIC

   Instructs :class:`writer` objects to quote all non-numeric fields.

   Instructs the reader to convert all non-quoted fields to type *float*.


.. data:: QUOTE_NONE

   Instructs :class:`writer` objects to never quote fields.  When the current
   *delimiter* occurs in output data it is preceded by the current *escapechar*
   character.  If *escapechar* is not set, the writer will raise :exc:`Error` if
   any characters that require escaping are encountered.

   Instructs :class:`reader` to perform no special processing of quote characters.

The :mod:`csv` module defines the following exception:


.. exception:: Error

   Raised by any of the functions when an error is detected.


.. _csv-fmt-params:

Dialects and Formatting Parameters
----------------------------------

To make it easier to specify the format of input and output records, specific
formatting parameters are grouped together into dialects.  A dialect is a
subclass of the :class:`Dialect` class having a set of specific methods and a
single :meth:`validate` method.  When creating :class:`reader` or
:class:`writer` objects, the programmer can specify a string or a subclass of
the :class:`Dialect` class as the dialect parameter.  In addition to, or instead
of, the *dialect* parameter, the programmer can also specify individual
formatting parameters, which have the same names as the attributes defined below
for the :class:`Dialect` class.

Dialects support the following attributes:


.. attribute:: Dialect.delimiter

   A one-character string used to separate fields.  It defaults to ``','``.


.. attribute:: Dialect.doublequote

   Controls how instances of *quotechar* appearing inside a field should
   themselves be quoted.  When :const:`True`, the character is doubled. When
   :const:`False`, the *escapechar* is used as a prefix to the *quotechar*.  It
   defaults to :const:`True`.

   On output, if *doublequote* is :const:`False` and no *escapechar* is set,
   :exc:`Error` is raised if a *quotechar* is found in a field.


.. attribute:: Dialect.escapechar

   A one-character string used by the writer to escape the *delimiter* if *quoting*
   is set to :const:`QUOTE_NONE` and the *quotechar* if *doublequote* is
   :const:`False`. On reading, the *escapechar* removes any special meaning from
   the following character. It defaults to :const:`None`, which disables escaping.


.. attribute:: Dialect.lineterminator

   The string used to terminate lines produced by the :class:`writer`. It defaults
   to ``'\r\n'``.

   .. note::

      The :class:`reader` is hard-coded to recognise either ``'\r'`` or ``'\n'`` as
      end-of-line, and ignores *lineterminator*. This behavior may change in the
      future.


.. attribute:: Dialect.quotechar

   A one-character string used to quote fields containing special characters, such
   as the *delimiter* or *quotechar*, or which contain new-line characters.  It
   defaults to ``'"'``.


.. attribute:: Dialect.quoting

   Controls when quotes should be generated by the writer and recognised by the
   reader.  It can take on any of the :const:`QUOTE_\*` constants (see section
   :ref:`csv-contents`) and defaults to :const:`QUOTE_MINIMAL`.


.. attribute:: Dialect.skipinitialspace

   When :const:`True`, whitespace immediately following the *delimiter* is ignored.
   The default is :const:`False`.


.. attribute:: Dialect.strict

   When ``True``, raise exception :exc:`Error` on bad CSV input.
   The default is ``False``.

Reader Objects
--------------

Reader objects (:class:`DictReader` instances and objects returned by the
:func:`reader` function) have the following public methods:


.. method:: csvreader.next()

   Return the next row of the reader's iterable object as a list, parsed according
   to the current dialect.

Reader objects have the following public attributes:


.. attribute:: csvreader.dialect

   A read-only description of the dialect in use by the parser.


.. attribute:: csvreader.line_num

   The number of lines read from the source iterator. This is not the same as the
   number of records returned, as records can span multiple lines.

   .. versionadded:: 2.5


DictReader objects have the following public attribute:


.. attribute:: csvreader.fieldnames

   If not passed as a parameter when creating the object, this attribute is
   initialized upon first access or when the first record is read from the
   file.

   .. versionchanged:: 2.6


Writer Objects
--------------

:class:`Writer` objects (:class:`DictWriter` instances and objects returned by
the :func:`writer` function) have the following public methods.  A *row* must be
a sequence of strings or numbers for :class:`Writer` objects and a dictionary
mapping fieldnames to strings or numbers (by passing them through :func:`str`
first) for :class:`DictWriter` objects.  Note that complex numbers are written
out surrounded by parens. This may cause some problems for other programs which
read CSV files (assuming they support complex numbers at all).


.. method:: csvwriter.writerow(row)

   Write the *row* parameter to the writer's file object, formatted according to
   the current dialect.


.. method:: csvwriter.writerows(rows)

   Write all elements in *rows* (an iterable of *row* objects as described
   above) to the writer's file object, formatted according to the current
   dialect.

Writer objects have the following public attribute:


.. attribute:: csvwriter.dialect

   A read-only description of the dialect in use by the writer.


DictWriter objects have the following public method:


.. method:: DictWriter.writeheader()

   Write a row with the field names (as specified in the constructor).

   .. versionadded:: 2.7


.. _csv-examples:

Examples
--------

The simplest example of reading a CSV file::

   import csv
   with open('some.csv', 'rb') as f:
       reader = csv.reader(f)
       for row in reader:
           print row

Reading a file with an alternate format::

   import csv
   with open('passwd', 'rb') as f:
       reader = csv.reader(f, delimiter=':', quoting=csv.QUOTE_NONE)
       for row in reader:
           print row

The corresponding simplest possible writing example is::

   import csv
   with open('some.csv', 'wb') as f:
       writer = csv.writer(f)
       writer.writerows(someiterable)

Registering a new dialect::

   import csv
   csv.register_dialect('unixpwd', delimiter=':', quoting=csv.QUOTE_NONE)
   with open('passwd', 'rb') as f:
       reader = csv.reader(f, 'unixpwd')

A slightly more advanced use of the reader --- catching and reporting errors::

   import csv, sys
   filename = 'some.csv'
   with open(filename, 'rb') as f:
       reader = csv.reader(f)
       try:
           for row in reader:
               print row
       except csv.Error as e:
           sys.exit('file %s, line %d: %s' % (filename, reader.line_num, e))

And while the module doesn't directly support parsing strings, it can easily be
done::

   import csv
   for row in csv.reader(['one,two,three']):
       print row

The :mod:`csv` module doesn't directly support reading and writing Unicode, but
it is 8-bit-clean save for some problems with ASCII NUL characters.  So you can
write functions or classes that handle the encoding and decoding for you as long
as you avoid encodings like UTF-16 that use NULs.  UTF-8 is recommended.

:func:`unicode_csv_reader` below is a :term:`generator` that wraps :class:`csv.reader`
to handle Unicode CSV data (a list of Unicode strings).  :func:`utf_8_encoder`
is a :term:`generator` that encodes the Unicode strings as UTF-8, one string (or row) at
a time.  The encoded strings are parsed by the CSV reader, and
:func:`unicode_csv_reader` decodes the UTF-8-encoded cells back into Unicode::

   import csv

   def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
       # csv.py doesn't do Unicode; encode temporarily as UTF-8:
       csv_reader = csv.reader(utf_8_encoder(unicode_csv_data),
                               dialect=dialect, **kwargs)
       for row in csv_reader:
           # decode UTF-8 back to Unicode, cell by cell:
           yield [unicode(cell, 'utf-8') for cell in row]

   def utf_8_encoder(unicode_csv_data):
       for line in unicode_csv_data:
           yield line.encode('utf-8')

For all other encodings the following :class:`UnicodeReader` and
:class:`UnicodeWriter` classes can be used. They take an additional *encoding*
parameter in their constructor and make sure that the data passes the real
reader or writer encoded as UTF-8::

   import csv, codecs, cStringIO

   class UTF8Recoder:
       """
       Iterator that reads an encoded stream and reencodes the input to UTF-8
       """
       def __init__(self, f, encoding):
           self.reader = codecs.getreader(encoding)(f)

       def __iter__(self):
           return self

       def next(self):
           return self.reader.next().encode("utf-8")

   class UnicodeReader:
       """
       A CSV reader which will iterate over lines in the CSV file "f",
       which is encoded in the given encoding.
       """

       def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
           f = UTF8Recoder(f, encoding)
           self.reader = csv.reader(f, dialect=dialect, **kwds)

       def next(self):
           row = self.reader.next()
           return [unicode(s, "utf-8") for s in row]

       def __iter__(self):
           return self

   class UnicodeWriter:
       """
       A CSV writer which will write rows to CSV file "f",
       which is encoded in the given encoding.
       """

       def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
           # Redirect output to a queue
           self.queue = cStringIO.StringIO()
           self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
           self.stream = f
           self.encoder = codecs.getincrementalencoder(encoding)()

       def writerow(self, row):
           self.writer.writerow([s.encode("utf-8") for s in row])
           # Fetch UTF-8 output from the queue ...
           data = self.queue.getvalue()
           data = data.decode("utf-8")
           # ... and reencode it into the target encoding
           data = self.encoder.encode(data)
           # write to the target stream
           self.stream.write(data)
           # empty queue
           self.queue.truncate(0)

       def writerows(self, rows):
           for row in rows:
               self.writerow(row)

PK	%�\����a�a$html/_sources/library/ctypes.rst.txtnu�[���:mod:`ctypes` --- A foreign function library for Python
=======================================================

.. module:: ctypes
   :synopsis: A foreign function library for Python.
.. moduleauthor:: Thomas Heller <theller@python.net>


.. versionadded:: 2.5

:mod:`ctypes` is a foreign function library for Python.  It provides C compatible
data types, and allows calling functions in DLLs or shared libraries.  It can be
used to wrap these libraries in pure Python.


.. _ctypes-ctypes-tutorial:

ctypes tutorial
---------------

Note: The code samples in this tutorial use :mod:`doctest` to make sure that
they actually work.  Since some code samples behave differently under Linux,
Windows, or Mac OS X, they contain doctest directives in comments.

Note: Some code samples reference the ctypes :class:`c_int` type. This type is
an alias for the :class:`c_long` type on 32-bit systems.  So, you should not be
confused if :class:`c_long` is printed if you would expect :class:`c_int` ---
they are actually the same type.


.. _ctypes-loading-dynamic-link-libraries:

Loading dynamic link libraries
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:mod:`ctypes` exports the *cdll*, and on Windows *windll* and *oledll*
objects, for loading dynamic link libraries.

You load libraries by accessing them as attributes of these objects. *cdll*
loads libraries which export functions using the standard ``cdecl`` calling
convention, while *windll* libraries call functions using the ``stdcall``
calling convention. *oledll* also uses the ``stdcall`` calling convention, and
assumes the functions return a Windows :c:type:`HRESULT` error code. The error
code is used to automatically raise a :class:`WindowsError` exception when the
function call fails.

Here are some examples for Windows. Note that ``msvcrt`` is the MS standard C
library containing most standard C functions, and uses the cdecl calling
convention::

   >>> from ctypes import *
   >>> print windll.kernel32  # doctest: +WINDOWS
   <WinDLL 'kernel32', handle ... at ...>
   >>> print cdll.msvcrt      # doctest: +WINDOWS
   <CDLL 'msvcrt', handle ... at ...>
   >>> libc = cdll.msvcrt     # doctest: +WINDOWS
   >>>

Windows appends the usual ``.dll`` file suffix automatically.

On Linux, it is required to specify the filename *including* the extension to
load a library, so attribute access can not be used to load libraries. Either the
:meth:`LoadLibrary` method of the dll loaders should be used, or you should load
the library by creating an instance of CDLL by calling the constructor::

   >>> cdll.LoadLibrary("libc.so.6")  # doctest: +LINUX
   <CDLL 'libc.so.6', handle ... at ...>
   >>> libc = CDLL("libc.so.6")       # doctest: +LINUX
   >>> libc                           # doctest: +LINUX
   <CDLL 'libc.so.6', handle ... at ...>
   >>>

.. XXX Add section for Mac OS X.


.. _ctypes-accessing-functions-from-loaded-dlls:

Accessing functions from loaded dlls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Functions are accessed as attributes of dll objects::

   >>> from ctypes import *
   >>> libc.printf
   <_FuncPtr object at 0x...>
   >>> print windll.kernel32.GetModuleHandleA  # doctest: +WINDOWS
   <_FuncPtr object at 0x...>
   >>> print windll.kernel32.MyOwnFunction     # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "ctypes.py", line 239, in __getattr__
       func = _StdcallFuncPtr(name, self)
   AttributeError: function 'MyOwnFunction' not found
   >>>

Note that win32 system dlls like ``kernel32`` and ``user32`` often export ANSI
as well as UNICODE versions of a function. The UNICODE version is exported with
an ``W`` appended to the name, while the ANSI version is exported with an ``A``
appended to the name. The win32 ``GetModuleHandle`` function, which returns a
*module handle* for a given module name, has the following C prototype, and a
macro is used to expose one of them as ``GetModuleHandle`` depending on whether
UNICODE is defined or not::

   /* ANSI version */
   HMODULE GetModuleHandleA(LPCSTR lpModuleName);
   /* UNICODE version */
   HMODULE GetModuleHandleW(LPCWSTR lpModuleName);

*windll* does not try to select one of them by magic, you must access the
version you need by specifying ``GetModuleHandleA`` or ``GetModuleHandleW``
explicitly, and then call it with strings or unicode strings
respectively.

Sometimes, dlls export functions with names which aren't valid Python
identifiers, like ``"??2@YAPAXI@Z"``. In this case you have to use
:func:`getattr` to retrieve the function::

   >>> getattr(cdll.msvcrt, "??2@YAPAXI@Z")  # doctest: +WINDOWS
   <_FuncPtr object at 0x...>
   >>>

On Windows, some dlls export functions not by name but by ordinal. These
functions can be accessed by indexing the dll object with the ordinal number::

   >>> cdll.kernel32[1]  # doctest: +WINDOWS
   <_FuncPtr object at 0x...>
   >>> cdll.kernel32[0]  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "ctypes.py", line 310, in __getitem__
       func = _StdcallFuncPtr(name, self)
   AttributeError: function ordinal 0 not found
   >>>


.. _ctypes-calling-functions:

Calling functions
^^^^^^^^^^^^^^^^^

You can call these functions like any other Python callable. This example uses
the ``time()`` function, which returns system time in seconds since the Unix
epoch, and the ``GetModuleHandleA()`` function, which returns a win32 module
handle.

This example calls both functions with a NULL pointer (``None`` should be used
as the NULL pointer)::

   >>> print libc.time(None)  # doctest: +SKIP
   1150640792
   >>> print hex(windll.kernel32.GetModuleHandleA(None))  # doctest: +WINDOWS
   0x1d000000
   >>>

:mod:`ctypes` tries to protect you from calling functions with the wrong number
of arguments or the wrong calling convention.  Unfortunately this only works on
Windows.  It does this by examining the stack after the function returns, so
although an error is raised the function *has* been called::

   >>> windll.kernel32.GetModuleHandleA()      # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: Procedure probably called with not enough arguments (4 bytes missing)
   >>> windll.kernel32.GetModuleHandleA(0, 0)  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: Procedure probably called with too many arguments (4 bytes in excess)
   >>>

The same exception is raised when you call an ``stdcall`` function with the
``cdecl`` calling convention, or vice versa::

   >>> cdll.kernel32.GetModuleHandleA(None)  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: Procedure probably called with not enough arguments (4 bytes missing)
   >>>

   >>> windll.msvcrt.printf("spam")  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: Procedure probably called with too many arguments (4 bytes in excess)
   >>>

To find out the correct calling convention you have to look into the C header
file or the documentation for the function you want to call.

On Windows, :mod:`ctypes` uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
argument values::

   >>> windll.kernel32.GetModuleHandleA(32)  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   WindowsError: exception: access violation reading 0x00000020
   >>>

There are, however, enough ways to crash Python with :mod:`ctypes`, so you
should be careful anyway.

``None``, integers, longs, byte strings and unicode strings are the only native
Python objects that can directly be used as parameters in these function calls.
``None`` is passed as a C ``NULL`` pointer, byte strings and unicode strings are
passed as pointer to the memory block that contains their data (:c:type:`char *`
or :c:type:`wchar_t *`).  Python integers and Python longs are passed as the
platforms default C :c:type:`int` type, their value is masked to fit into the C
type.

Before we move on calling functions with other parameter types, we have to learn
more about :mod:`ctypes` data types.


.. _ctypes-fundamental-data-types:

Fundamental data types
^^^^^^^^^^^^^^^^^^^^^^

:mod:`ctypes` defines a number of primitive C compatible data types:

+----------------------+------------------------------------------+----------------------------+
| ctypes type          | C type                                   | Python type                |
+======================+==========================================+============================+
| :class:`c_bool`      | :c:type:`_Bool`                          | bool (1)                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_char`      | :c:type:`char`                           | 1-character string         |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_wchar`     | :c:type:`wchar_t`                        | 1-character unicode string |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_byte`      | :c:type:`char`                           | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ubyte`     | :c:type:`unsigned char`                  | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_short`     | :c:type:`short`                          | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ushort`    | :c:type:`unsigned short`                 | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_int`       | :c:type:`int`                            | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_uint`      | :c:type:`unsigned int`                   | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_long`      | :c:type:`long`                           | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ulong`     | :c:type:`unsigned long`                  | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_longlong`  | :c:type:`__int64` or :c:type:`long long` | int/long                   |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_ulonglong` | :c:type:`unsigned __int64` or            | int/long                   |
|                      | :c:type:`unsigned long long`             |                            |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_float`     | :c:type:`float`                          | float                      |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_double`    | :c:type:`double`                         | float                      |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_longdouble`| :c:type:`long double`                    | float                      |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_char_p`    | :c:type:`char *` (NUL terminated)        | string or ``None``         |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_wchar_p`   | :c:type:`wchar_t *` (NUL terminated)     | unicode or ``None``        |
+----------------------+------------------------------------------+----------------------------+
| :class:`c_void_p`    | :c:type:`void *`                         | int/long or ``None``       |
+----------------------+------------------------------------------+----------------------------+

(1)
   The constructor accepts any object with a truth value.

All these types can be created by calling them with an optional initializer of
the correct type and value::

   >>> c_int()
   c_long(0)
   >>> c_char_p("Hello, World")
   c_char_p('Hello, World')
   >>> c_ushort(-3)
   c_ushort(65533)
   >>>

Since these types are mutable, their value can also be changed afterwards::

   >>> i = c_int(42)
   >>> print i
   c_long(42)
   >>> print i.value
   42
   >>> i.value = -99
   >>> print i.value
   -99
   >>>

Assigning a new value to instances of the pointer types :class:`c_char_p`,
:class:`c_wchar_p`, and :class:`c_void_p` changes the *memory location* they
point to, *not the contents* of the memory block (of course not, because Python
strings are immutable)::

   >>> s = "Hello, World"
   >>> c_s = c_char_p(s)
   >>> print c_s
   c_char_p('Hello, World')
   >>> c_s.value = "Hi, there"
   >>> print c_s
   c_char_p('Hi, there')
   >>> print s                 # first string is unchanged
   Hello, World
   >>>

You should be careful, however, not to pass them to functions expecting pointers
to mutable memory. If you need mutable memory blocks, ctypes has a
:func:`create_string_buffer` function which creates these in various ways.  The
current memory block contents can be accessed (or changed) with the ``raw``
property; if you want to access it as NUL terminated string, use the ``value``
property::

   >>> from ctypes import *
   >>> p = create_string_buffer(3)      # create a 3 byte buffer, initialized to NUL bytes
   >>> print sizeof(p), repr(p.raw)
   3 '\x00\x00\x00'
   >>> p = create_string_buffer("Hello")      # create a buffer containing a NUL terminated string
   >>> print sizeof(p), repr(p.raw)
   6 'Hello\x00'
   >>> print repr(p.value)
   'Hello'
   >>> p = create_string_buffer("Hello", 10)  # create a 10 byte buffer
   >>> print sizeof(p), repr(p.raw)
   10 'Hello\x00\x00\x00\x00\x00'
   >>> p.value = "Hi"
   >>> print sizeof(p), repr(p.raw)
   10 'Hi\x00lo\x00\x00\x00\x00\x00'
   >>>

The :func:`create_string_buffer` function replaces the :func:`c_buffer` function
(which is still available as an alias), as well as the :func:`c_string` function
from earlier ctypes releases.  To create a mutable memory block containing
unicode characters of the C type :c:type:`wchar_t` use the
:func:`create_unicode_buffer` function.


.. _ctypes-calling-functions-continued:

Calling functions, continued
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Note that printf prints to the real standard output channel, *not* to
:data:`sys.stdout`, so these examples will only work at the console prompt, not
from within *IDLE* or *PythonWin*::

   >>> printf = libc.printf
   >>> printf("Hello, %s\n", "World!")
   Hello, World!
   14
   >>> printf("Hello, %S\n", u"World!")
   Hello, World!
   14
   >>> printf("%d bottles of beer\n", 42)
   42 bottles of beer
   19
   >>> printf("%f bottles of beer\n", 42.5)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ArgumentError: argument 2: exceptions.TypeError: Don't know how to convert parameter 2
   >>>

As has been mentioned before, all Python types except integers, strings, and
unicode strings have to be wrapped in their corresponding :mod:`ctypes` type, so
that they can be converted to the required C data type::

   >>> printf("An int %d, a double %f\n", 1234, c_double(3.14))
   An int 1234, a double 3.140000
   31
   >>>


.. _ctypes-calling-functions-with-own-custom-data-types:

Calling functions with your own custom data types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You can also customize :mod:`ctypes` argument conversion to allow instances of
your own classes be used as function arguments.  :mod:`ctypes` looks for an
:attr:`_as_parameter_` attribute and uses this as the function argument.  Of
course, it must be one of integer, string, or unicode::

   >>> class Bottles(object):
   ...     def __init__(self, number):
   ...         self._as_parameter_ = number
   ...
   >>> bottles = Bottles(42)
   >>> printf("%d bottles of beer\n", bottles)
   42 bottles of beer
   19
   >>>

If you don't want to store the instance's data in the :attr:`_as_parameter_`
instance variable, you could define a :func:`property` which makes the data
available.


.. _ctypes-specifying-required-argument-types:

Specifying the required argument types (function prototypes)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It is possible to specify the required argument types of functions exported from
DLLs by setting the :attr:`argtypes` attribute.

:attr:`argtypes` must be a sequence of C data types (the ``printf`` function is
probably not a good example here, because it takes a variable number and
different types of parameters depending on the format string, on the other hand
this is quite handy to experiment with this feature)::

   >>> printf.argtypes = [c_char_p, c_char_p, c_int, c_double]
   >>> printf("String '%s', Int %d, Double %f\n", "Hi", 10, 2.2)
   String 'Hi', Int 10, Double 2.200000
   37
   >>>

Specifying a format protects against incompatible argument types (just as a
prototype for a C function), and tries to convert the arguments to valid types::

   >>> printf("%d %d %d", 1, 2, 3)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ArgumentError: argument 2: exceptions.TypeError: wrong type
   >>> printf("%s %d %f\n", "X", 2, 3)
   X 2 3.000000
   13
   >>>

If you have defined your own classes which you pass to function calls, you have
to implement a :meth:`from_param` class method for them to be able to use them
in the :attr:`argtypes` sequence. The :meth:`from_param` class method receives
the Python object passed to the function call, it should do a typecheck or
whatever is needed to make sure this object is acceptable, and then return the
object itself, its :attr:`_as_parameter_` attribute, or whatever you want to
pass as the C function argument in this case. Again, the result should be an
integer, string, unicode, a :mod:`ctypes` instance, or an object with an
:attr:`_as_parameter_` attribute.


.. _ctypes-return-types:

Return types
^^^^^^^^^^^^

By default functions are assumed to return the C :c:type:`int` type.  Other
return types can be specified by setting the :attr:`restype` attribute of the
function object.

Here is a more advanced example, it uses the ``strchr`` function, which expects
a string pointer and a char, and returns a pointer to a string::

   >>> strchr = libc.strchr
   >>> strchr("abcdef", ord("d"))  # doctest: +SKIP
   8059983
   >>> strchr.restype = c_char_p   # c_char_p is a pointer to a string
   >>> strchr("abcdef", ord("d"))
   'def'
   >>> print strchr("abcdef", ord("x"))
   None
   >>>

If you want to avoid the ``ord("x")`` calls above, you can set the
:attr:`argtypes` attribute, and the second argument will be converted from a
single character Python string into a C char::

   >>> strchr.restype = c_char_p
   >>> strchr.argtypes = [c_char_p, c_char]
   >>> strchr("abcdef", "d")
   'def'
   >>> strchr("abcdef", "def")
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ArgumentError: argument 2: exceptions.TypeError: one character string expected
   >>> print strchr("abcdef", "x")
   None
   >>> strchr("abcdef", "d")
   'def'
   >>>

You can also use a callable Python object (a function or a class for example) as
the :attr:`restype` attribute, if the foreign function returns an integer.  The
callable will be called with the *integer* the C function returns, and the
result of this call will be used as the result of your function call. This is
useful to check for error return values and automatically raise an exception::

   >>> GetModuleHandle = windll.kernel32.GetModuleHandleA  # doctest: +WINDOWS
   >>> def ValidHandle(value):
   ...     if value == 0:
   ...         raise WinError()
   ...     return value
   ...
   >>>
   >>> GetModuleHandle.restype = ValidHandle  # doctest: +WINDOWS
   >>> GetModuleHandle(None)  # doctest: +WINDOWS
   486539264
   >>> GetModuleHandle("something silly")  # doctest: +WINDOWS
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "<stdin>", line 3, in ValidHandle
   WindowsError: [Errno 126] The specified module could not be found.
   >>>

``WinError`` is a function which will call Windows ``FormatMessage()`` api to
get the string representation of an error code, and *returns* an exception.
``WinError`` takes an optional error code parameter, if no one is used, it calls
:func:`GetLastError` to retrieve it.

Please note that a much more powerful error checking mechanism is available
through the :attr:`errcheck` attribute; see the reference manual for details.


.. _ctypes-passing-pointers:

Passing pointers (or: passing parameters by reference)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Sometimes a C api function expects a *pointer* to a data type as parameter,
probably to write into the corresponding location, or if the data is too large
to be passed by value. This is also known as *passing parameters by reference*.

:mod:`ctypes` exports the :func:`byref` function which is used to pass
parameters by reference.  The same effect can be achieved with the
:func:`pointer` function, although :func:`pointer` does a lot more work since it
constructs a real pointer object, so it is faster to use :func:`byref` if you
don't need the pointer object in Python itself::

   >>> i = c_int()
   >>> f = c_float()
   >>> s = create_string_buffer('\000' * 32)
   >>> print i.value, f.value, repr(s.value)
   0 0.0 ''
   >>> libc.sscanf("1 3.14 Hello", "%d %f %s",
   ...             byref(i), byref(f), s)
   3
   >>> print i.value, f.value, repr(s.value)
   1 3.1400001049 'Hello'
   >>>


.. _ctypes-structures-unions:

Structures and unions
^^^^^^^^^^^^^^^^^^^^^

Structures and unions must derive from the :class:`Structure` and :class:`Union`
base classes which are defined in the :mod:`ctypes` module. Each subclass must
define a :attr:`_fields_` attribute.  :attr:`_fields_` must be a list of
*2-tuples*, containing a *field name* and a *field type*.

The field type must be a :mod:`ctypes` type like :class:`c_int`, or any other
derived :mod:`ctypes` type: structure, union, array, pointer.

Here is a simple example of a POINT structure, which contains two integers named
*x* and *y*, and also shows how to initialize a structure in the constructor::

   >>> from ctypes import *
   >>> class POINT(Structure):
   ...     _fields_ = [("x", c_int),
   ...                 ("y", c_int)]
   ...
   >>> point = POINT(10, 20)
   >>> print point.x, point.y
   10 20
   >>> point = POINT(y=5)
   >>> print point.x, point.y
   0 5
   >>> POINT(1, 2, 3)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: too many initializers
   >>>

You can, however, build much more complicated structures.  A structure can
itself contain other structures by using a structure as a field type.

Here is a RECT structure which contains two POINTs named *upperleft* and
*lowerright*::

   >>> class RECT(Structure):
   ...     _fields_ = [("upperleft", POINT),
   ...                 ("lowerright", POINT)]
   ...
   >>> rc = RECT(point)
   >>> print rc.upperleft.x, rc.upperleft.y
   0 5
   >>> print rc.lowerright.x, rc.lowerright.y
   0 0
   >>>

Nested structures can also be initialized in the constructor in several ways::

   >>> r = RECT(POINT(1, 2), POINT(3, 4))
   >>> r = RECT((1, 2), (3, 4))

Field :term:`descriptor`\s can be retrieved from the *class*, they are useful
for debugging because they can provide useful information::

   >>> print POINT.x
   <Field type=c_long, ofs=0, size=4>
   >>> print POINT.y
   <Field type=c_long, ofs=4, size=4>
   >>>


.. _ctypes-structureunion-alignment-byte-order:

.. warning::

   :mod:`ctypes` does not support passing unions or structures with bit-fields
   to functions by value.  While this may work on 32-bit x86, it's not
   guaranteed by the library to work in the general case.  Unions and
   structures with bit-fields should always be passed to functions by pointer.

Structure/union alignment and byte order
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, Structure and Union fields are aligned in the same way the C
compiler does it. It is possible to override this behavior be specifying a
:attr:`_pack_` class attribute in the subclass definition. This must be set to a
positive integer and specifies the maximum alignment for the fields. This is
what ``#pragma pack(n)`` also does in MSVC.

:mod:`ctypes` uses the native byte order for Structures and Unions.  To build
structures with non-native byte order, you can use one of the
:class:`BigEndianStructure`, :class:`LittleEndianStructure`,
:class:`BigEndianUnion`, and :class:`LittleEndianUnion` base classes.  These
classes cannot contain pointer fields.


.. _ctypes-bit-fields-in-structures-unions:

Bit fields in structures and unions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

It is possible to create structures and unions containing bit fields. Bit fields
are only possible for integer fields, the bit width is specified as the third
item in the :attr:`_fields_` tuples::

   >>> class Int(Structure):
   ...     _fields_ = [("first_16", c_int, 16),
   ...                 ("second_16", c_int, 16)]
   ...
   >>> print Int.first_16
   <Field type=c_long, ofs=0:0, bits=16>
   >>> print Int.second_16
   <Field type=c_long, ofs=0:16, bits=16>
   >>>


.. _ctypes-arrays:

Arrays
^^^^^^

Arrays are sequences, containing a fixed number of instances of the same type.

The recommended way to create array types is by multiplying a data type with a
positive integer::

   TenPointsArrayType = POINT * 10

Here is an example of a somewhat artificial data type, a structure containing 4
POINTs among other stuff::

   >>> from ctypes import *
   >>> class POINT(Structure):
   ...     _fields_ = ("x", c_int), ("y", c_int)
   ...
   >>> class MyStruct(Structure):
   ...     _fields_ = [("a", c_int),
   ...                 ("b", c_float),
   ...                 ("point_array", POINT * 4)]
   >>>
   >>> print len(MyStruct().point_array)
   4
   >>>

Instances are created in the usual way, by calling the class::

   arr = TenPointsArrayType()
   for pt in arr:
       print pt.x, pt.y

The above code print a series of ``0 0`` lines, because the array contents is
initialized to zeros.

Initializers of the correct type can also be specified::

   >>> from ctypes import *
   >>> TenIntegers = c_int * 10
   >>> ii = TenIntegers(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
   >>> print ii
   <c_long_Array_10 object at 0x...>
   >>> for i in ii: print i,
   ...
   1 2 3 4 5 6 7 8 9 10
   >>>


.. _ctypes-pointers:

Pointers
^^^^^^^^

Pointer instances are created by calling the :func:`pointer` function on a
:mod:`ctypes` type::

   >>> from ctypes import *
   >>> i = c_int(42)
   >>> pi = pointer(i)
   >>>

Pointer instances have a :attr:`~_Pointer.contents` attribute which
returns the object to which the pointer points, the ``i`` object above::

   >>> pi.contents
   c_long(42)
   >>>

Note that :mod:`ctypes` does not have OOR (original object return), it constructs a
new, equivalent object each time you retrieve an attribute::

   >>> pi.contents is i
   False
   >>> pi.contents is pi.contents
   False
   >>>

Assigning another :class:`c_int` instance to the pointer's contents attribute
would cause the pointer to point to the memory location where this is stored::

   >>> i = c_int(99)
   >>> pi.contents = i
   >>> pi.contents
   c_long(99)
   >>>

.. XXX Document dereferencing pointers, and that it is preferred over the
   .contents attribute.

Pointer instances can also be indexed with integers::

   >>> pi[0]
   99
   >>>

Assigning to an integer index changes the pointed to value::

   >>> print i
   c_long(99)
   >>> pi[0] = 22
   >>> print i
   c_long(22)
   >>>

It is also possible to use indexes different from 0, but you must know what
you're doing, just as in C: You can access or change arbitrary memory locations.
Generally you only use this feature if you receive a pointer from a C function,
and you *know* that the pointer actually points to an array instead of a single
item.

Behind the scenes, the :func:`pointer` function does more than simply create
pointer instances, it has to create pointer *types* first.  This is done with
the :func:`POINTER` function, which accepts any :mod:`ctypes` type, and returns
a new type::

   >>> PI = POINTER(c_int)
   >>> PI
   <class 'ctypes.LP_c_long'>
   >>> PI(42)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: expected c_long instead of int
   >>> PI(c_int(42))
   <ctypes.LP_c_long object at 0x...>
   >>>

Calling the pointer type without an argument creates a ``NULL`` pointer.
``NULL`` pointers have a ``False`` boolean value::

   >>> null_ptr = POINTER(c_int)()
   >>> print bool(null_ptr)
   False
   >>>

:mod:`ctypes` checks for ``NULL`` when dereferencing pointers (but dereferencing
invalid non-\ ``NULL`` pointers would crash Python)::

   >>> null_ptr[0]
   Traceback (most recent call last):
       ....
   ValueError: NULL pointer access
   >>>

   >>> null_ptr[0] = 1234
   Traceback (most recent call last):
       ....
   ValueError: NULL pointer access
   >>>


.. _ctypes-type-conversions:

Type conversions
^^^^^^^^^^^^^^^^

Usually, ctypes does strict type checking.  This means, if you have
``POINTER(c_int)`` in the :attr:`argtypes` list of a function or as the type of
a member field in a structure definition, only instances of exactly the same
type are accepted.  There are some exceptions to this rule, where ctypes accepts
other objects.  For example, you can pass compatible array instances instead of
pointer types.  So, for ``POINTER(c_int)``, ctypes accepts an array of c_int::

   >>> class Bar(Structure):
   ...     _fields_ = [("count", c_int), ("values", POINTER(c_int))]
   ...
   >>> bar = Bar()
   >>> bar.values = (c_int * 3)(1, 2, 3)
   >>> bar.count = 3
   >>> for i in range(bar.count):
   ...     print bar.values[i]
   ...
   1
   2
   3
   >>>

In addition, if a function argument is explicitly declared to be a pointer type
(such as ``POINTER(c_int)``) in :attr:`argtypes`, an object of the pointed
type (``c_int`` in this case) can be passed to the function.  ctypes will apply
the required :func:`byref` conversion in this case automatically.

To set a POINTER type field to ``NULL``, you can assign ``None``::

   >>> bar.values = None
   >>>

.. XXX list other conversions...

Sometimes you have instances of incompatible types.  In C, you can cast one type
into another type.  :mod:`ctypes` provides a :func:`cast` function which can be
used in the same way.  The ``Bar`` structure defined above accepts
``POINTER(c_int)`` pointers or :class:`c_int` arrays for its ``values`` field,
but not instances of other types::

   >>> bar.values = (c_byte * 4)()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: incompatible types, c_byte_Array_4 instance instead of LP_c_long instance
   >>>

For these cases, the :func:`cast` function is handy.

The :func:`cast` function can be used to cast a ctypes instance into a pointer
to a different ctypes data type.  :func:`cast` takes two parameters, a ctypes
object that is or can be converted to a pointer of some kind, and a ctypes
pointer type.  It returns an instance of the second argument, which references
the same memory block as the first argument::

   >>> a = (c_byte * 4)()
   >>> cast(a, POINTER(c_int))
   <ctypes.LP_c_long object at ...>
   >>>

So, :func:`cast` can be used to assign to the ``values`` field of ``Bar`` the
structure::

   >>> bar = Bar()
   >>> bar.values = cast((c_byte * 4)(), POINTER(c_int))
   >>> print bar.values[0]
   0
   >>>


.. _ctypes-incomplete-types:

Incomplete Types
^^^^^^^^^^^^^^^^

*Incomplete Types* are structures, unions or arrays whose members are not yet
specified. In C, they are specified by forward declarations, which are defined
later::

   struct cell; /* forward declaration */

   struct cell {
       char *name;
       struct cell *next;
   };

The straightforward translation into ctypes code would be this, but it does not
work::

   >>> class cell(Structure):
   ...     _fields_ = [("name", c_char_p),
   ...                 ("next", POINTER(cell))]
   ...
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "<stdin>", line 2, in cell
   NameError: name 'cell' is not defined
   >>>

because the new ``class cell`` is not available in the class statement itself.
In :mod:`ctypes`, we can define the ``cell`` class and set the :attr:`_fields_`
attribute later, after the class statement::

   >>> from ctypes import *
   >>> class cell(Structure):
   ...     pass
   ...
   >>> cell._fields_ = [("name", c_char_p),
   ...                  ("next", POINTER(cell))]
   >>>

Lets try it. We create two instances of ``cell``, and let them point to each
other, and finally follow the pointer chain a few times::

   >>> c1 = cell()
   >>> c1.name = "foo"
   >>> c2 = cell()
   >>> c2.name = "bar"
   >>> c1.next = pointer(c2)
   >>> c2.next = pointer(c1)
   >>> p = c1
   >>> for i in range(8):
   ...     print p.name,
   ...     p = p.next[0]
   ...
   foo bar foo bar foo bar foo bar
   >>>


.. _ctypes-callback-functions:

Callback functions
^^^^^^^^^^^^^^^^^^

:mod:`ctypes` allows creating C callable function pointers from Python callables.
These are sometimes called *callback functions*.

First, you must create a class for the callback function, the class knows the
calling convention, the return type, and the number and types of arguments this
function will receive.

The CFUNCTYPE factory function creates types for callback functions using the
normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
function creates types for callback functions using the stdcall calling
convention.

Both of these factory functions are called with the result type as first
argument, and the callback functions expected argument types as the remaining
arguments.

I will present an example here which uses the standard C library's :func:`qsort`
function, this is used to sort items with the help of a callback function.
:func:`qsort` will be used to sort an array of integers::

   >>> IntArray5 = c_int * 5
   >>> ia = IntArray5(5, 1, 7, 33, 99)
   >>> qsort = libc.qsort
   >>> qsort.restype = None
   >>>

:func:`qsort` must be called with a pointer to the data to sort, the number of
items in the data array, the size of one item, and a pointer to the comparison
function, the callback. The callback will then be called with two pointers to
items, and it must return a negative integer if the first item is smaller than
the second, a zero if they are equal, and a positive integer else.

So our callback function receives pointers to integers, and must return an
integer. First we create the ``type`` for the callback function::

   >>> CMPFUNC = CFUNCTYPE(c_int, POINTER(c_int), POINTER(c_int))
   >>>

For the first implementation of the callback function, we simply print the
arguments we get, and return 0 (incremental development ;-)::

   >>> def py_cmp_func(a, b):
   ...     print "py_cmp_func", a, b
   ...     return 0
   ...
   >>>

Create the C callable callback::

   >>> cmp_func = CMPFUNC(py_cmp_func)
   >>>

And we're ready to go::

   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   py_cmp_func <ctypes.LP_c_long object at 0x00...> <ctypes.LP_c_long object at 0x00...>
   >>>

We know how to access the contents of a pointer, so lets redefine our callback::

   >>> def py_cmp_func(a, b):
   ...     print "py_cmp_func", a[0], b[0]
   ...     return 0
   ...
   >>> cmp_func = CMPFUNC(py_cmp_func)
   >>>

Here is what we get on Windows::

   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func) # doctest: +WINDOWS
   py_cmp_func 7 1
   py_cmp_func 33 1
   py_cmp_func 99 1
   py_cmp_func 5 1
   py_cmp_func 7 5
   py_cmp_func 33 5
   py_cmp_func 99 5
   py_cmp_func 7 99
   py_cmp_func 33 99
   py_cmp_func 7 33
   >>>

It is funny to see that on linux the sort function seems to work much more
efficiently, it is doing less comparisons::

   >>> qsort(ia, len(ia), sizeof(c_int), cmp_func)  # doctest: +LINUX
   py_cmp_func 5 1
   py_cmp_func 33 99
   py_cmp_func 7 33
   py_cmp_func 5 7
   py_cmp_func 1 7
   >>>

Ah, we're nearly done! The last step is to actually compare the two items and
return a useful result::

   >>> def py_cmp_func(a, b):
   ...     print "py_cmp_func", a[0], b[0]
   ...     return a[0] - b[0]
   ...
   >>>

Final run on Windows::

   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +WINDOWS
   py_cmp_func 33 7
   py_cmp_func 99 33
   py_cmp_func 5 99
   py_cmp_func 1 99
   py_cmp_func 33 7
   py_cmp_func 1 33
   py_cmp_func 5 33
   py_cmp_func 5 7
   py_cmp_func 1 7
   py_cmp_func 5 1
   >>>

and on Linux::

   >>> qsort(ia, len(ia), sizeof(c_int), CMPFUNC(py_cmp_func)) # doctest: +LINUX
   py_cmp_func 5 1
   py_cmp_func 33 99
   py_cmp_func 7 33
   py_cmp_func 1 7
   py_cmp_func 5 7
   >>>

It is quite interesting to see that the Windows :func:`qsort` function needs
more comparisons than the linux version!

As we can easily check, our array is sorted now::

   >>> for i in ia: print i,
   ...
   1 5 7 33 99
   >>>

.. note::

   Make sure you keep references to :func:`CFUNCTYPE` objects as long as they
   are used from C code. :mod:`ctypes` doesn't, and if you don't, they may be
   garbage collected, crashing your program when a callback is made.

   Also, note that if the callback function is called in a thread created
   outside of Python's control (e.g. by the foreign code that calls the
   callback), ctypes creates a new dummy Python thread on every invocation. This
   behavior is correct for most purposes, but it means that values stored with
   :class:`threading.local` will *not* survive across different callbacks, even when
   those calls are made from the same C thread.

.. _ctypes-accessing-values-exported-from-dlls:

Accessing values exported from dlls
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Some shared libraries not only export functions, they also export variables. An
example in the Python library itself is the ``Py_OptimizeFlag``, an integer set
to 0, 1, or 2, depending on the :option:`-O` or :option:`-OO` flag given on
startup.

:mod:`ctypes` can access values like this with the :meth:`in_dll` class methods of
the type.  *pythonapi* is a predefined symbol giving access to the Python C
api::

   >>> opt_flag = c_int.in_dll(pythonapi, "Py_OptimizeFlag")
   >>> print opt_flag
   c_long(0)
   >>>

If the interpreter would have been started with :option:`-O`, the sample would
have printed ``c_long(1)``, or ``c_long(2)`` if :option:`-OO` would have been
specified.

An extended example which also demonstrates the use of pointers accesses the
``PyImport_FrozenModules`` pointer exported by Python.

Quoting the Python docs: *This pointer is initialized to point to an array of
"struct _frozen" records, terminated by one whose members are all NULL or zero.
When a frozen module is imported, it is searched in this table. Third-party code
could play tricks with this to provide a dynamically created collection of
frozen modules.*

So manipulating this pointer could even prove useful. To restrict the example
size, we show only how this table can be read with :mod:`ctypes`::

   >>> from ctypes import *
   >>>
   >>> class struct_frozen(Structure):
   ...     _fields_ = [("name", c_char_p),
   ...                 ("code", POINTER(c_ubyte)),
   ...                 ("size", c_int)]
   ...
   >>>

We have defined the ``struct _frozen`` data type, so we can get the pointer to
the table::

   >>> FrozenTable = POINTER(struct_frozen)
   >>> table = FrozenTable.in_dll(pythonapi, "PyImport_FrozenModules")
   >>>

Since ``table`` is a ``pointer`` to the array of ``struct_frozen`` records, we
can iterate over it, but we just have to make sure that our loop terminates,
because pointers have no size. Sooner or later it would probably crash with an
access violation or whatever, so it's better to break out of the loop when we
hit the NULL entry::

   >>> for item in table:
   ...     print item.name, item.size
   ...     if item.name is None:
   ...         break
   ...
   __hello__ 104
   __phello__ -104
   __phello__.spam 104
   None 0
   >>>

The fact that standard Python has a frozen module and a frozen package
(indicated by the negative size member) is not well known, it is only used for
testing. Try it out with ``import __hello__`` for example.


.. _ctypes-surprises:

Surprises
^^^^^^^^^

There are some edge cases in :mod:`ctypes` where you might expect something
other than what actually happens.

Consider the following example::

   >>> from ctypes import *
   >>> class POINT(Structure):
   ...     _fields_ = ("x", c_int), ("y", c_int)
   ...
   >>> class RECT(Structure):
   ...     _fields_ = ("a", POINT), ("b", POINT)
   ...
   >>> p1 = POINT(1, 2)
   >>> p2 = POINT(3, 4)
   >>> rc = RECT(p1, p2)
   >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
   1 2 3 4
   >>> # now swap the two points
   >>> rc.a, rc.b = rc.b, rc.a
   >>> print rc.a.x, rc.a.y, rc.b.x, rc.b.y
   3 4 3 4
   >>>

Hm. We certainly expected the last statement to print ``3 4 1 2``. What
happened? Here are the steps of the ``rc.a, rc.b = rc.b, rc.a`` line above::

   >>> temp0, temp1 = rc.b, rc.a
   >>> rc.a = temp0
   >>> rc.b = temp1
   >>>

Note that ``temp0`` and ``temp1`` are objects still using the internal buffer of
the ``rc`` object above. So executing ``rc.a = temp0`` copies the buffer
contents of ``temp0`` into ``rc`` 's buffer.  This, in turn, changes the
contents of ``temp1``. So, the last assignment ``rc.b = temp1``, doesn't have
the expected effect.

Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
doesn't *copy* the sub-object, instead it retrieves a wrapper object accessing
the root-object's underlying buffer.

Another example that may behave different from what one would expect is this::

   >>> s = c_char_p()
   >>> s.value = "abc def ghi"
   >>> s.value
   'abc def ghi'
   >>> s.value is s.value
   False
   >>>

Why is it printing ``False``?  ctypes instances are objects containing a memory
block plus some :term:`descriptor`\s accessing the contents of the memory.
Storing a Python object in the memory block does not store the object itself,
instead the ``contents`` of the object is stored.  Accessing the contents again
constructs a new Python object each time!


.. _ctypes-variable-sized-data-types:

Variable-sized data types
^^^^^^^^^^^^^^^^^^^^^^^^^

:mod:`ctypes` provides some support for variable-sized arrays and structures.

The :func:`resize` function can be used to resize the memory buffer of an
existing ctypes object.  The function takes the object as first argument, and
the requested size in bytes as the second argument.  The memory block cannot be
made smaller than the natural memory block specified by the objects type, a
:exc:`ValueError` is raised if this is tried::

   >>> short_array = (c_short * 4)()
   >>> print sizeof(short_array)
   8
   >>> resize(short_array, 4)
   Traceback (most recent call last):
       ...
   ValueError: minimum size is 8
   >>> resize(short_array, 32)
   >>> sizeof(short_array)
   32
   >>> sizeof(type(short_array))
   8
   >>>

This is nice and fine, but how would one access the additional elements
contained in this array?  Since the type still only knows about 4 elements, we
get errors accessing other elements::

   >>> short_array[:]
   [0, 0, 0, 0]
   >>> short_array[7]
   Traceback (most recent call last):
       ...
   IndexError: invalid index
   >>>

Another way to use variable-sized data types with :mod:`ctypes` is to use the
dynamic nature of Python, and (re-)define the data type after the required size
is already known, on a case by case basis.


.. _ctypes-ctypes-reference:

ctypes reference
----------------


.. _ctypes-finding-shared-libraries:

Finding shared libraries
^^^^^^^^^^^^^^^^^^^^^^^^

When programming in a compiled language, shared libraries are accessed when
compiling/linking a program, and when the program is run.

The purpose of the :func:`find_library` function is to locate a library in a way
similar to what the compiler does (on platforms with several versions of a
shared library the most recent should be loaded), while the ctypes library
loaders act like when a program is run, and call the runtime loader directly.

The :mod:`ctypes.util` module provides a function which can help to determine the
library to load.


.. data:: find_library(name)
   :module: ctypes.util
   :noindex:

   Try to find a library and return a pathname.  *name* is the library name without
   any prefix like *lib*, suffix like ``.so``, ``.dylib`` or version number (this
   is the form used for the posix linker option :option:`!-l`).  If no library can
   be found, returns ``None``.

The exact functionality is system dependent.

On Linux, :func:`find_library` tries to run external programs
(``/sbin/ldconfig``, ``gcc``, and ``objdump``) to find the library file.  It
returns the filename of the library file.  Here are some examples::

   >>> from ctypes.util import find_library
   >>> find_library("m")
   'libm.so.6'
   >>> find_library("c")
   'libc.so.6'
   >>> find_library("bz2")
   'libbz2.so.1.0'
   >>>

On OS X, :func:`find_library` tries several predefined naming schemes and paths
to locate the library, and returns a full pathname if successful::

   >>> from ctypes.util import find_library
   >>> find_library("c")
   '/usr/lib/libc.dylib'
   >>> find_library("m")
   '/usr/lib/libm.dylib'
   >>> find_library("bz2")
   '/usr/lib/libbz2.dylib'
   >>> find_library("AGL")
   '/System/Library/Frameworks/AGL.framework/AGL'
   >>>

On Windows, :func:`find_library` searches along the system search path, and
returns the full pathname, but since there is no predefined naming scheme a call
like ``find_library("c")`` will fail and return ``None``.

If wrapping a shared library with :mod:`ctypes`, it *may* be better to determine
the shared library name at development time, and hardcode that into the wrapper
module instead of using :func:`find_library` to locate the library at runtime.


.. _ctypes-loading-shared-libraries:

Loading shared libraries
^^^^^^^^^^^^^^^^^^^^^^^^

There are several ways to load shared libraries into the Python process.  One
way is to instantiate one of the following classes:


.. class:: CDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

   Instances of this class represent loaded shared libraries. Functions in these
   libraries use the standard C calling convention, and are assumed to return
   :c:type:`int`.


.. class:: OleDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

   Windows only: Instances of this class represent loaded shared libraries,
   functions in these libraries use the ``stdcall`` calling convention, and are
   assumed to return the windows specific :class:`HRESULT` code.  :class:`HRESULT`
   values contain information specifying whether the function call failed or
   succeeded, together with additional error code.  If the return value signals a
   failure, an :class:`WindowsError` is automatically raised.


.. class:: WinDLL(name, mode=DEFAULT_MODE, handle=None, use_errno=False, use_last_error=False)

   Windows only: Instances of this class represent loaded shared libraries,
   functions in these libraries use the ``stdcall`` calling convention, and are
   assumed to return :c:type:`int` by default.

   On Windows CE only the standard calling convention is used, for convenience the
   :class:`WinDLL` and :class:`OleDLL` use the standard calling convention on this
   platform.

The Python :term:`global interpreter lock` is released before calling any
function exported by these libraries, and reacquired afterwards.


.. class:: PyDLL(name, mode=DEFAULT_MODE, handle=None)

   Instances of this class behave like :class:`CDLL` instances, except that the
   Python GIL is *not* released during the function call, and after the function
   execution the Python error flag is checked. If the error flag is set, a Python
   exception is raised.

   Thus, this is only useful to call Python C api functions directly.

All these classes can be instantiated by calling them with at least one
argument, the pathname of the shared library.  If you have an existing handle to
an already loaded shared library, it can be passed as the ``handle`` named
parameter, otherwise the underlying platforms ``dlopen`` or ``LoadLibrary``
function is used to load the library into the process, and to get a handle to
it.

The *mode* parameter can be used to specify how the library is loaded.  For
details, consult the :manpage:`dlopen(3)` manpage.  On Windows, *mode* is
ignored.  On posix systems, RTLD_NOW is always added, and is not
configurable.

The *use_errno* parameter, when set to true, enables a ctypes mechanism that
allows accessing the system :data:`errno` error number in a safe way.
:mod:`ctypes` maintains a thread-local copy of the systems :data:`errno`
variable; if you call foreign functions created with ``use_errno=True`` then the
:data:`errno` value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.

The function :func:`ctypes.get_errno` returns the value of the ctypes private
copy, and the function :func:`ctypes.set_errno` changes the ctypes private copy
to a new value and returns the former value.

The *use_last_error* parameter, when set to true, enables the same mechanism for
the Windows error code which is managed by the :func:`GetLastError` and
:func:`SetLastError` Windows API functions; :func:`ctypes.get_last_error` and
:func:`ctypes.set_last_error` are used to request and change the ctypes private
copy of the windows error code.

.. versionadded:: 2.6
   The *use_last_error* and *use_errno* optional parameters were added.

.. data:: RTLD_GLOBAL
   :noindex:

   Flag to use as *mode* parameter.  On platforms where this flag is not available,
   it is defined as the integer zero.


.. data:: RTLD_LOCAL
   :noindex:

   Flag to use as *mode* parameter.  On platforms where this is not available, it
   is the same as *RTLD_GLOBAL*.


.. data:: DEFAULT_MODE
   :noindex:

   The default mode which is used to load shared libraries.  On OSX 10.3, this is
   *RTLD_GLOBAL*, otherwise it is the same as *RTLD_LOCAL*.

Instances of these classes have no public methods.  Functions exported by the
shared library can be accessed as attributes or by index.  Please note that
accessing the function through an attribute caches the result and therefore
accessing it repeatedly returns the same object each time.  On the other hand,
accessing it through an index returns a new object each time:

   >>> libc.time == libc.time
   True
   >>> libc['time'] == libc['time']
   False

The following public attributes are available, their name starts with an
underscore to not clash with exported function names:


.. attribute:: PyDLL._handle

   The system handle used to access the library.


.. attribute:: PyDLL._name

   The name of the library passed in the constructor.

Shared libraries can also be loaded by using one of the prefabricated objects,
which are instances of the :class:`LibraryLoader` class, either by calling the
:meth:`LoadLibrary` method, or by retrieving the library as attribute of the
loader instance.


.. class:: LibraryLoader(dlltype)

   Class which loads shared libraries.  *dlltype* should be one of the
   :class:`CDLL`, :class:`PyDLL`, :class:`WinDLL`, or :class:`OleDLL` types.

   :meth:`__getattr__` has special behavior: It allows loading a shared library by
   accessing it as attribute of a library loader instance.  The result is cached,
   so repeated attribute accesses return the same library each time.


   .. method:: LoadLibrary(name)

      Load a shared library into the process and return it.  This method always
      returns a new instance of the library.

These prefabricated library loaders are available:


.. data:: cdll
   :noindex:

   Creates :class:`CDLL` instances.


.. data:: windll
   :noindex:

   Windows only: Creates :class:`WinDLL` instances.


.. data:: oledll
   :noindex:

   Windows only: Creates :class:`OleDLL` instances.


.. data:: pydll
   :noindex:

   Creates :class:`PyDLL` instances.

For accessing the C Python api directly, a ready-to-use Python shared library
object is available:


.. data:: pythonapi
   :noindex:

   An instance of :class:`PyDLL` that exposes Python C API functions as
   attributes.  Note that all these functions are assumed to return C
   :c:type:`int`, which is of course not always the truth, so you have to assign
   the correct :attr:`restype` attribute to use these functions.


.. _ctypes-foreign-functions:

Foreign functions
^^^^^^^^^^^^^^^^^

As explained in the previous section, foreign functions can be accessed as
attributes of loaded shared libraries.  The function objects created in this way
by default accept any number of arguments, accept any ctypes data instances as
arguments, and return the default result type specified by the library loader.
They are instances of a private class:


.. class:: _FuncPtr

   Base class for C callable foreign functions.

   Instances of foreign functions are also C compatible data types; they
   represent C function pointers.

   This behavior can be customized by assigning to special attributes of the
   foreign function object.


   .. attribute:: restype

      Assign a ctypes type to specify the result type of the foreign function.
      Use ``None`` for :c:type:`void`, a function not returning anything.

      It is possible to assign a callable Python object that is not a ctypes
      type, in this case the function is assumed to return a C :c:type:`int`, and
      the callable will be called with this integer, allowing further
      processing or error checking.  Using this is deprecated, for more flexible
      post processing or error checking use a ctypes data type as
      :attr:`restype` and assign a callable to the :attr:`errcheck` attribute.


   .. attribute:: argtypes

      Assign a tuple of ctypes types to specify the argument types that the
      function accepts.  Functions using the ``stdcall`` calling convention can
      only be called with the same number of arguments as the length of this
      tuple; functions using the C calling convention accept additional,
      unspecified arguments as well.

      When a foreign function is called, each actual argument is passed to the
      :meth:`from_param` class method of the items in the :attr:`argtypes`
      tuple, this method allows adapting the actual argument to an object that
      the foreign function accepts.  For example, a :class:`c_char_p` item in
      the :attr:`argtypes` tuple will convert a unicode string passed as
      argument into a byte string using ctypes conversion rules.

      New: It is now possible to put items in argtypes which are not ctypes
      types, but each item must have a :meth:`from_param` method which returns a
      value usable as argument (integer, string, ctypes instance).  This allows
      defining adapters that can adapt custom objects as function parameters.


   .. attribute:: errcheck

      Assign a Python function or another callable to this attribute. The
      callable will be called with three or more arguments:

      .. function:: callable(result, func, arguments)
         :noindex:

         *result* is what the foreign function returns, as specified by the
         :attr:`restype` attribute.

         *func* is the foreign function object itself, this allows reusing the
         same callable object to check or post process the results of several
         functions.

         *arguments* is a tuple containing the parameters originally passed to
         the function call, this allows specializing the behavior on the
         arguments used.

      The object that this function returns will be returned from the
      foreign function call, but it can also check the result value
      and raise an exception if the foreign function call failed.


.. exception:: ArgumentError()

   This exception is raised when a foreign function call cannot convert one of the
   passed arguments.


.. _ctypes-function-prototypes:

Function prototypes
^^^^^^^^^^^^^^^^^^^

Foreign functions can also be created by instantiating function prototypes.
Function prototypes are similar to function prototypes in C; they describe a
function (return type, argument types, calling convention) without defining an
implementation.  The factory functions must be called with the desired result
type and the argument types of the function.


.. function:: CFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)

   The returned function prototype creates functions that use the standard C
   calling convention.  The function will release the GIL during the call.  If
   *use_errno* is set to true, the ctypes private copy of the system
   :data:`errno` variable is exchanged with the real :data:`errno` value before
   and after the call; *use_last_error* does the same for the Windows error
   code.

   .. versionchanged:: 2.6
      The optional *use_errno* and *use_last_error* parameters were added.


.. function:: WINFUNCTYPE(restype, *argtypes, use_errno=False, use_last_error=False)

   Windows only: The returned function prototype creates functions that use the
   ``stdcall`` calling convention, except on Windows CE where
   :func:`WINFUNCTYPE` is the same as :func:`CFUNCTYPE`.  The function will
   release the GIL during the call.  *use_errno* and *use_last_error* have the
   same meaning as above.


.. function:: PYFUNCTYPE(restype, *argtypes)

   The returned function prototype creates functions that use the Python calling
   convention.  The function will *not* release the GIL during the call.

Function prototypes created by these factory functions can be instantiated in
different ways, depending on the type and number of the parameters in the call:


   .. function:: prototype(address)
      :noindex:
      :module:

      Returns a foreign function at the specified address which must be an integer.


   .. function:: prototype(callable)
      :noindex:
      :module:

      Create a C callable function (a callback function) from a Python *callable*.


   .. function:: prototype(func_spec[, paramflags])
      :noindex:
      :module:

      Returns a foreign function exported by a shared library. *func_spec* must be a
      2-tuple ``(name_or_ordinal, library)``. The first item is the name of the
      exported function as string, or the ordinal of the exported function as small
      integer.  The second item is the shared library instance.


   .. function:: prototype(vtbl_index, name[, paramflags[, iid]])
      :noindex:
      :module:

      Returns a foreign function that will call a COM method. *vtbl_index* is the
      index into the virtual function table, a small non-negative integer. *name* is
      name of the COM method. *iid* is an optional pointer to the interface identifier
      which is used in extended error reporting.

      COM methods use a special calling convention: They require a pointer to the COM
      interface as first argument, in addition to those parameters that are specified
      in the :attr:`argtypes` tuple.

   The optional *paramflags* parameter creates foreign function wrappers with much
   more functionality than the features described above.

   *paramflags* must be a tuple of the same length as :attr:`argtypes`.

   Each item in this tuple contains further information about a parameter, it must
   be a tuple containing one, two, or three items.

   The first item is an integer containing a combination of direction
   flags for the parameter:

      1
         Specifies an input parameter to the function.

      2
         Output parameter.  The foreign function fills in a value.

      4
         Input parameter which defaults to the integer zero.

   The optional second item is the parameter name as string.  If this is specified,
   the foreign function can be called with named parameters.

   The optional third item is the default value for this parameter.

This example demonstrates how to wrap the Windows ``MessageBoxA`` function so
that it supports default parameters and named arguments. The C declaration from
the windows header file is this::

   WINUSERAPI int WINAPI
   MessageBoxA(
       HWND hWnd,
       LPCSTR lpText,
       LPCSTR lpCaption,
       UINT uType);

Here is the wrapping with :mod:`ctypes`::

   >>> from ctypes import c_int, WINFUNCTYPE, windll
   >>> from ctypes.wintypes import HWND, LPCSTR, UINT
   >>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
   >>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
   >>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
   >>>

The MessageBox foreign function can now be called in these ways::

   >>> MessageBox()
   >>> MessageBox(text="Spam, spam, spam")
   >>> MessageBox(flags=2, text="foo bar")
   >>>

A second example demonstrates output parameters.  The win32 ``GetWindowRect``
function retrieves the dimensions of a specified window by copying them into
``RECT`` structure that the caller has to supply.  Here is the C declaration::

   WINUSERAPI BOOL WINAPI
   GetWindowRect(
        HWND hWnd,
        LPRECT lpRect);

Here is the wrapping with :mod:`ctypes`::

   >>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
   >>> from ctypes.wintypes import BOOL, HWND, RECT
   >>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
   >>> paramflags = (1, "hwnd"), (2, "lprect")
   >>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
   >>>

Functions with output parameters will automatically return the output parameter
value if there is a single one, or a tuple containing the output parameter
values when there are more than one, so the GetWindowRect function now returns a
RECT instance, when called.

Output parameters can be combined with the :attr:`errcheck` protocol to do
further output processing and error checking.  The win32 ``GetWindowRect`` api
function returns a ``BOOL`` to signal success or failure, so this function could
do the error checking, and raises an exception when the api call failed::

   >>> def errcheck(result, func, args):
   ...     if not result:
   ...         raise WinError()
   ...     return args
   ...
   >>> GetWindowRect.errcheck = errcheck
   >>>

If the :attr:`errcheck` function returns the argument tuple it receives
unchanged, :mod:`ctypes` continues the normal processing it does on the output
parameters.  If you want to return a tuple of window coordinates instead of a
``RECT`` instance, you can retrieve the fields in the function and return them
instead, the normal processing will no longer take place::

   >>> def errcheck(result, func, args):
   ...     if not result:
   ...         raise WinError()
   ...     rc = args[1]
   ...     return rc.left, rc.top, rc.bottom, rc.right
   ...
   >>> GetWindowRect.errcheck = errcheck
   >>>


.. _ctypes-utility-functions:

Utility functions
^^^^^^^^^^^^^^^^^


.. function:: addressof(obj)

   Returns the address of the memory buffer as integer.  *obj* must be an
   instance of a ctypes type.


.. function:: alignment(obj_or_type)

   Returns the alignment requirements of a ctypes type. *obj_or_type* must be a
   ctypes type or instance.


.. function:: byref(obj[, offset])

   Returns a light-weight pointer to *obj*, which must be an instance of a
   ctypes type.  *offset* defaults to zero, and must be an integer that will be
   added to the internal pointer value.

   ``byref(obj, offset)`` corresponds to this C code::

      (((char *)&obj) + offset)

   The returned object can only be used as a foreign function call
   parameter.  It behaves similar to ``pointer(obj)``, but the
   construction is a lot faster.

   .. versionadded:: 2.6
      The *offset* optional argument was added.


.. function:: cast(obj, type)

   This function is similar to the cast operator in C.  It returns a new
   instance of *type* which points to the same memory block as *obj*.  *type*
   must be a pointer type, and *obj* must be an object that can be interpreted
   as a pointer.


.. function:: create_string_buffer(init_or_size[, size])

   This function creates a mutable character buffer. The returned object is a
   ctypes array of :class:`c_char`.

   *init_or_size* must be an integer which specifies the size of the array, or a
   string which will be used to initialize the array items.

   If a string is specified as first argument, the buffer is made one item larger
   than the length of the string so that the last element in the array is a NUL
   termination character. An integer can be passed as second argument which allows
   specifying the size of the array if the length of the string should not be used.

   If the first parameter is a unicode string, it is converted into an 8-bit string
   according to ctypes conversion rules.


.. function:: create_unicode_buffer(init_or_size[, size])

   This function creates a mutable unicode character buffer. The returned object is
   a ctypes array of :class:`c_wchar`.

   *init_or_size* must be an integer which specifies the size of the array, or a
   unicode string which will be used to initialize the array items.

   If a unicode string is specified as first argument, the buffer is made one item
   larger than the length of the string so that the last element in the array is a
   NUL termination character. An integer can be passed as second argument which
   allows specifying the size of the array if the length of the string should not
   be used.

   If the first parameter is an 8-bit string, it is converted into a unicode string
   according to ctypes conversion rules.


.. function:: DllCanUnloadNow()

   Windows only: This function is a hook which allows implementing in-process
   COM servers with ctypes.  It is called from the DllCanUnloadNow function that
   the _ctypes extension dll exports.


.. function:: DllGetClassObject()

   Windows only: This function is a hook which allows implementing in-process
   COM servers with ctypes.  It is called from the DllGetClassObject function
   that the ``_ctypes`` extension dll exports.


.. function:: find_library(name)
   :module: ctypes.util

   Try to find a library and return a pathname.  *name* is the library name
   without any prefix like ``lib``, suffix like ``.so``, ``.dylib`` or version
   number (this is the form used for the posix linker option :option:`!-l`).  If
   no library can be found, returns ``None``.

   The exact functionality is system dependent.

   .. versionchanged:: 2.6
      Windows only: ``find_library("m")`` or ``find_library("c")`` return the
      result of a call to ``find_msvcrt()``.


.. function:: find_msvcrt()
   :module: ctypes.util

   Windows only: return the filename of the VC runtime library used by Python,
   and by the extension modules.  If the name of the library cannot be
   determined, ``None`` is returned.

   If you need to free memory, for example, allocated by an extension module
   with a call to the ``free(void *)``, it is important that you use the
   function in the same library that allocated the memory.

   .. versionadded:: 2.6


.. function:: FormatError([code])

   Windows only: Returns a textual description of the error code *code*.  If no
   error code is specified, the last error code is used by calling the Windows
   api function GetLastError.


.. function:: GetLastError()

   Windows only: Returns the last error code set by Windows in the calling thread.
   This function calls the Windows `GetLastError()` function directly,
   it does not return the ctypes-private copy of the error code.

.. function:: get_errno()

   Returns the current value of the ctypes-private copy of the system
   :data:`errno` variable in the calling thread.

   .. versionadded:: 2.6

.. function:: get_last_error()

   Windows only: returns the current value of the ctypes-private copy of the system
   :data:`LastError` variable in the calling thread.

   .. versionadded:: 2.6

.. function:: memmove(dst, src, count)

   Same as the standard C memmove library function: copies *count* bytes from
   *src* to *dst*. *dst* and *src* must be integers or ctypes instances that can
   be converted to pointers.


.. function:: memset(dst, c, count)

   Same as the standard C memset library function: fills the memory block at
   address *dst* with *count* bytes of value *c*. *dst* must be an integer
   specifying an address, or a ctypes instance.


.. function:: POINTER(type)

   This factory function creates and returns a new ctypes pointer type. Pointer
   types are cached and reused internally, so calling this function repeatedly is
   cheap. *type* must be a ctypes type.


.. function:: pointer(obj)

   This function creates a new pointer instance, pointing to *obj*. The returned
   object is of the type ``POINTER(type(obj))``.

   Note: If you just want to pass a pointer to an object to a foreign function
   call, you should use ``byref(obj)`` which is much faster.


.. function:: resize(obj, size)

   This function resizes the internal memory buffer of *obj*, which must be an
   instance of a ctypes type.  It is not possible to make the buffer smaller
   than the native size of the objects type, as given by ``sizeof(type(obj))``,
   but it is possible to enlarge the buffer.


.. function:: set_conversion_mode(encoding, errors)

   This function sets the rules that ctypes objects use when converting between
   8-bit strings and unicode strings.  *encoding* must be a string specifying an
   encoding, like ``'utf-8'`` or ``'mbcs'``, *errors* must be a string
   specifying the error handling on encoding/decoding errors.  Examples of
   possible values are ``"strict"``, ``"replace"``, or ``"ignore"``.

   :func:`set_conversion_mode` returns a 2-tuple containing the previous
   conversion rules.  On windows, the initial conversion rules are ``('mbcs',
   'ignore')``, on other systems ``('ascii', 'strict')``.


.. function:: set_errno(value)

   Set the current value of the ctypes-private copy of the system :data:`errno`
   variable in the calling thread to *value* and return the previous value.

   .. versionadded:: 2.6


.. function:: set_last_error(value)

   Windows only: set the current value of the ctypes-private copy of the system
   :data:`LastError` variable in the calling thread to *value* and return the
   previous value.

   .. versionadded:: 2.6


.. function:: sizeof(obj_or_type)

   Returns the size in bytes of a ctypes type or instance memory buffer.
   Does the same as the C ``sizeof`` operator.


.. function:: string_at(address[, size])

   This function returns the string starting at memory address *address*. If size
   is specified, it is used as size, otherwise the string is assumed to be
   zero-terminated.


.. function:: WinError(code=None, descr=None)

   Windows only: this function is probably the worst-named thing in ctypes.  It
   creates an instance of WindowsError.  If *code* is not specified,
   ``GetLastError`` is called to determine the error code.  If ``descr`` is not
   specified, :func:`FormatError` is called to get a textual description of the
   error.


.. function:: wstring_at(address[, size])

   This function returns the wide character string starting at memory address
   *address* as unicode string.  If *size* is specified, it is used as the
   number of characters of the string, otherwise the string is assumed to be
   zero-terminated.


.. _ctypes-data-types:

Data types
^^^^^^^^^^


.. class:: _CData

   This non-public class is the common base class of all ctypes data types.
   Among other things, all ctypes type instances contain a memory block that
   hold C compatible data; the address of the memory block is returned by the
   :func:`addressof` helper function.  Another instance variable is exposed as
   :attr:`_objects`; this contains other Python objects that need to be kept
   alive in case the memory block contains pointers.

   Common methods of ctypes data types, these are all class methods (to be
   exact, they are methods of the :term:`metaclass`):


   .. method:: _CData.from_buffer(source[, offset])

      This method returns a ctypes instance that shares the buffer of the
      *source* object.  The *source* object must support the writeable buffer
      interface.  The optional *offset* parameter specifies an offset into the
      source buffer in bytes; the default is zero.  If the source buffer is not
      large enough a :exc:`ValueError` is raised.

      .. versionadded:: 2.6


   .. method:: _CData.from_buffer_copy(source[, offset])

      This method creates a ctypes instance, copying the buffer from the
      *source* object buffer which must be readable.  The optional *offset*
      parameter specifies an offset into the source buffer in bytes; the default
      is zero.  If the source buffer is not large enough a :exc:`ValueError` is
      raised.

      .. versionadded:: 2.6


   .. method:: from_address(address)

      This method returns a ctypes type instance using the memory specified by
      *address* which must be an integer.


   .. method:: from_param(obj)

      This method adapts *obj* to a ctypes type.  It is called with the actual
      object used in a foreign function call when the type is present in the
      foreign function's :attr:`argtypes` tuple; it must return an object that
      can be used as a function call parameter.

      All ctypes data types have a default implementation of this classmethod
      that normally returns *obj* if that is an instance of the type.  Some
      types accept other objects as well.


   .. method:: in_dll(library, name)

      This method returns a ctypes type instance exported by a shared
      library. *name* is the name of the symbol that exports the data, *library*
      is the loaded shared library.


   Common instance variables of ctypes data types:

   .. attribute:: _b_base_

      Sometimes ctypes data instances do not own the memory block they contain,
      instead they share part of the memory block of a base object.  The
      :attr:`_b_base_` read-only member is the root ctypes object that owns the
      memory block.


   .. attribute:: _b_needsfree_

      This read-only variable is true when the ctypes data instance has
      allocated the memory block itself, false otherwise.


   .. attribute:: _objects

      This member is either ``None`` or a dictionary containing Python objects
      that need to be kept alive so that the memory block contents is kept
      valid.  This object is only exposed for debugging; never modify the
      contents of this dictionary.


.. _ctypes-fundamental-data-types-2:

Fundamental data types
^^^^^^^^^^^^^^^^^^^^^^


.. class:: _SimpleCData

   This non-public class is the base class of all fundamental ctypes data
   types. It is mentioned here because it contains the common attributes of the
   fundamental ctypes data types.  :class:`_SimpleCData` is a subclass of
   :class:`_CData`, so it inherits their methods and attributes.

   .. versionchanged:: 2.6
      ctypes data types that are not and do not contain pointers can now be
      pickled.

   Instances have a single attribute:

   .. attribute:: value

      This attribute contains the actual value of the instance. For integer and
      pointer types, it is an integer, for character types, it is a single
      character string, for character pointer types it is a Python string or
      unicode string.

      When the ``value`` attribute is retrieved from a ctypes instance, usually
      a new object is returned each time.  :mod:`ctypes` does *not* implement
      original object return, always a new object is constructed.  The same is
      true for all other ctypes object instances.


Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently
converted to native Python types.  In other words, if a foreign function has a
:attr:`restype` of :class:`c_char_p`, you will always receive a Python string,
*not* a :class:`c_char_p` instance.

Subclasses of fundamental data types do *not* inherit this behavior. So, if a
foreign functions :attr:`restype` is a subclass of :class:`c_void_p`, you will
receive an instance of this subclass from the function call. Of course, you can
get the value of the pointer by accessing the ``value`` attribute.

These are the fundamental ctypes data types:

.. class:: c_byte

   Represents the C :c:type:`signed char` datatype, and interprets the value as
   small integer.  The constructor accepts an optional integer initializer; no
   overflow checking is done.


.. class:: c_char

   Represents the C :c:type:`char` datatype, and interprets the value as a single
   character.  The constructor accepts an optional string initializer, the
   length of the string must be exactly one character.


.. class:: c_char_p

   Represents the C :c:type:`char *` datatype when it points to a zero-terminated
   string.  For a general character pointer that may also point to binary data,
   ``POINTER(c_char)`` must be used.  The constructor accepts an integer
   address, or a string.


.. class:: c_double

   Represents the C :c:type:`double` datatype.  The constructor accepts an
   optional float initializer.


.. class:: c_longdouble

   Represents the C :c:type:`long double` datatype.  The constructor accepts an
   optional float initializer.  On platforms where ``sizeof(long double) ==
   sizeof(double)`` it is an alias to :class:`c_double`.

   .. versionadded:: 2.6

.. class:: c_float

   Represents the C :c:type:`float` datatype.  The constructor accepts an
   optional float initializer.


.. class:: c_int

   Represents the C :c:type:`signed int` datatype.  The constructor accepts an
   optional integer initializer; no overflow checking is done.  On platforms
   where ``sizeof(int) == sizeof(long)`` it is an alias to :class:`c_long`.


.. class:: c_int8

   Represents the C 8-bit :c:type:`signed int` datatype.  Usually an alias for
   :class:`c_byte`.


.. class:: c_int16

   Represents the C 16-bit :c:type:`signed int` datatype.  Usually an alias for
   :class:`c_short`.


.. class:: c_int32

   Represents the C 32-bit :c:type:`signed int` datatype.  Usually an alias for
   :class:`c_int`.


.. class:: c_int64

   Represents the C 64-bit :c:type:`signed int` datatype.  Usually an alias for
   :class:`c_longlong`.


.. class:: c_long

   Represents the C :c:type:`signed long` datatype.  The constructor accepts an
   optional integer initializer; no overflow checking is done.


.. class:: c_longlong

   Represents the C :c:type:`signed long long` datatype.  The constructor accepts
   an optional integer initializer; no overflow checking is done.


.. class:: c_short

   Represents the C :c:type:`signed short` datatype.  The constructor accepts an
   optional integer initializer; no overflow checking is done.


.. class:: c_size_t

   Represents the C :c:type:`size_t` datatype.


.. class:: c_ssize_t

   Represents the C :c:type:`ssize_t` datatype.

   .. versionadded:: 2.7


.. class:: c_ubyte

   Represents the C :c:type:`unsigned char` datatype, it interprets the value as
   small integer.  The constructor accepts an optional integer initializer; no
   overflow checking is done.


.. class:: c_uint

   Represents the C :c:type:`unsigned int` datatype.  The constructor accepts an
   optional integer initializer; no overflow checking is done.  On platforms
   where ``sizeof(int) == sizeof(long)`` it is an alias for :class:`c_ulong`.


.. class:: c_uint8

   Represents the C 8-bit :c:type:`unsigned int` datatype.  Usually an alias for
   :class:`c_ubyte`.


.. class:: c_uint16

   Represents the C 16-bit :c:type:`unsigned int` datatype.  Usually an alias for
   :class:`c_ushort`.


.. class:: c_uint32

   Represents the C 32-bit :c:type:`unsigned int` datatype.  Usually an alias for
   :class:`c_uint`.


.. class:: c_uint64

   Represents the C 64-bit :c:type:`unsigned int` datatype.  Usually an alias for
   :class:`c_ulonglong`.


.. class:: c_ulong

   Represents the C :c:type:`unsigned long` datatype.  The constructor accepts an
   optional integer initializer; no overflow checking is done.


.. class:: c_ulonglong

   Represents the C :c:type:`unsigned long long` datatype.  The constructor
   accepts an optional integer initializer; no overflow checking is done.


.. class:: c_ushort

   Represents the C :c:type:`unsigned short` datatype.  The constructor accepts
   an optional integer initializer; no overflow checking is done.


.. class:: c_void_p

   Represents the C :c:type:`void *` type.  The value is represented as integer.
   The constructor accepts an optional integer initializer.


.. class:: c_wchar

   Represents the C :c:type:`wchar_t` datatype, and interprets the value as a
   single character unicode string.  The constructor accepts an optional string
   initializer, the length of the string must be exactly one character.


.. class:: c_wchar_p

   Represents the C :c:type:`wchar_t *` datatype, which must be a pointer to a
   zero-terminated wide character string.  The constructor accepts an integer
   address, or a string.


.. class:: c_bool

   Represent the C :c:type:`bool` datatype (more accurately, :c:type:`_Bool` from
   C99).  Its value can be ``True`` or ``False``, and the constructor accepts any object
   that has a truth value.

   .. versionadded:: 2.6


.. class:: HRESULT

   Windows only: Represents a :c:type:`HRESULT` value, which contains success or
   error information for a function or method call.


.. class:: py_object

   Represents the C :c:type:`PyObject *` datatype.  Calling this without an
   argument creates a ``NULL`` :c:type:`PyObject *` pointer.

The :mod:`ctypes.wintypes` module provides quite some other Windows specific
data types, for example :c:type:`HWND`, :c:type:`WPARAM`, or :c:type:`DWORD`.  Some
useful structures like :c:type:`MSG` or :c:type:`RECT` are also defined.


.. _ctypes-structured-data-types:

Structured data types
^^^^^^^^^^^^^^^^^^^^^


.. class:: Union(*args, **kw)

   Abstract base class for unions in native byte order.


.. class:: BigEndianStructure(*args, **kw)

   Abstract base class for structures in *big endian* byte order.


.. class:: LittleEndianStructure(*args, **kw)

   Abstract base class for structures in *little endian* byte order.

Structures with non-native byte order cannot contain pointer type fields, or any
other data types containing pointer type fields.


.. class:: Structure(*args, **kw)

   Abstract base class for structures in *native* byte order.

   Concrete structure and union types must be created by subclassing one of these
   types, and at least define a :attr:`_fields_` class variable. :mod:`ctypes` will
   create :term:`descriptor`\s which allow reading and writing the fields by direct
   attribute accesses.  These are the


   .. attribute:: _fields_

      A sequence defining the structure fields.  The items must be 2-tuples or
      3-tuples.  The first item is the name of the field, the second item
      specifies the type of the field; it can be any ctypes data type.

      For integer type fields like :class:`c_int`, a third optional item can be
      given.  It must be a small positive integer defining the bit width of the
      field.

      Field names must be unique within one structure or union.  This is not
      checked, only one field can be accessed when names are repeated.

      It is possible to define the :attr:`_fields_` class variable *after* the
      class statement that defines the Structure subclass, this allows creating
      data types that directly or indirectly reference themselves::

         class List(Structure):
             pass
         List._fields_ = [("pnext", POINTER(List)),
                          ...
                         ]

      The :attr:`_fields_` class variable must, however, be defined before the
      type is first used (an instance is created, ``sizeof()`` is called on it,
      and so on).  Later assignments to the :attr:`_fields_` class variable will
      raise an AttributeError.

      It is possible to defined sub-subclasses of structure types, they inherit
      the fields of the base class plus the :attr:`_fields_` defined in the
      sub-subclass, if any.


   .. attribute:: _pack_

      An optional small integer that allows overriding the alignment of
      structure fields in the instance.  :attr:`_pack_` must already be defined
      when :attr:`_fields_` is assigned, otherwise it will have no effect.


   .. attribute:: _anonymous_

      An optional sequence that lists the names of unnamed (anonymous) fields.
      :attr:`_anonymous_` must be already defined when :attr:`_fields_` is
      assigned, otherwise it will have no effect.

      The fields listed in this variable must be structure or union type fields.
      :mod:`ctypes` will create descriptors in the structure type that allow
      accessing the nested fields directly, without the need to create the
      structure or union field.

      Here is an example type (Windows)::

         class _U(Union):
             _fields_ = [("lptdesc", POINTER(TYPEDESC)),
                         ("lpadesc", POINTER(ARRAYDESC)),
                         ("hreftype", HREFTYPE)]

         class TYPEDESC(Structure):
             _anonymous_ = ("u",)
             _fields_ = [("u", _U),
                         ("vt", VARTYPE)]


      The ``TYPEDESC`` structure describes a COM data type, the ``vt`` field
      specifies which one of the union fields is valid.  Since the ``u`` field
      is defined as anonymous field, it is now possible to access the members
      directly off the TYPEDESC instance. ``td.lptdesc`` and ``td.u.lptdesc``
      are equivalent, but the former is faster since it does not need to create
      a temporary union instance::

         td = TYPEDESC()
         td.vt = VT_PTR
         td.lptdesc = POINTER(some_type)
         td.u.lptdesc = POINTER(some_type)

   It is possible to defined sub-subclasses of structures, they inherit the
   fields of the base class.  If the subclass definition has a separate
   :attr:`_fields_` variable, the fields specified in this are appended to the
   fields of the base class.

   Structure and union constructors accept both positional and keyword
   arguments.  Positional arguments are used to initialize member fields in the
   same order as they are appear in :attr:`_fields_`.  Keyword arguments in the
   constructor are interpreted as attribute assignments, so they will initialize
   :attr:`_fields_` with the same name, or create new attributes for names not
   present in :attr:`_fields_`.


.. _ctypes-arrays-pointers:

Arrays and pointers
^^^^^^^^^^^^^^^^^^^

.. class:: Array(\*args)

   Abstract base class for arrays.

   The recommended way to create concrete array types is by multiplying any
   :mod:`ctypes` data type with a positive integer.  Alternatively, you can subclass
   this type and define :attr:`_length_` and :attr:`_type_` class variables.
   Array elements can be read and written using standard
   subscript and slice accesses; for slice reads, the resulting object is
   *not* itself an :class:`Array`.


   .. attribute:: _length_

        A positive integer specifying the number of elements in the array.
        Out-of-range subscripts result in an :exc:`IndexError`. Will be
        returned by :func:`len`.


   .. attribute:: _type_

        Specifies the type of each element in the array.


   Array subclass constructors accept positional arguments, used to
   initialize the elements in order.


.. class:: _Pointer

   Private, abstract base class for pointers.

   Concrete pointer types are created by calling :func:`POINTER` with the
   type that will be pointed to; this is done automatically by
   :func:`pointer`.

   If a pointer points to an array, its elements can be read and
   written using standard subscript and slice accesses.  Pointer objects
   have no size, so :func:`len` will raise :exc:`TypeError`.  Negative
   subscripts will read from the memory *before* the pointer (as in C), and
   out-of-range subscripts will probably crash with an access violation (if
   you're lucky).


   .. attribute:: _type_

        Specifies the type pointed to.

   .. attribute:: contents

        Returns the object to which to pointer points.  Assigning to this
        attribute changes the pointer to point to the assigned object.

PK	%�\��zV#V#*html/_sources/library/curses.ascii.rst.txtnu�[���
:mod:`curses.ascii` --- Utilities for ASCII characters
======================================================

.. module:: curses.ascii
   :synopsis: Constants and set-membership functions for ASCII characters.
.. moduleauthor:: Eric S. Raymond <esr@thyrsus.com>
.. sectionauthor:: Eric S. Raymond <esr@thyrsus.com>


.. versionadded:: 1.6

The :mod:`curses.ascii` module supplies name constants for ASCII characters and
functions to test membership in various ASCII character classes.  The constants
supplied are names for control characters as follows:

+--------------+----------------------------------------------+
| Name         | Meaning                                      |
+==============+==============================================+
| :const:`NUL` |                                              |
+--------------+----------------------------------------------+
| :const:`SOH` | Start of heading, console interrupt          |
+--------------+----------------------------------------------+
| :const:`STX` | Start of text                                |
+--------------+----------------------------------------------+
| :const:`ETX` | End of text                                  |
+--------------+----------------------------------------------+
| :const:`EOT` | End of transmission                          |
+--------------+----------------------------------------------+
| :const:`ENQ` | Enquiry, goes with :const:`ACK` flow control |
+--------------+----------------------------------------------+
| :const:`ACK` | Acknowledgement                              |
+--------------+----------------------------------------------+
| :const:`BEL` | Bell                                         |
+--------------+----------------------------------------------+
| :const:`BS`  | Backspace                                    |
+--------------+----------------------------------------------+
| :const:`TAB` | Tab                                          |
+--------------+----------------------------------------------+
| :const:`HT`  | Alias for :const:`TAB`: "Horizontal tab"     |
+--------------+----------------------------------------------+
| :const:`LF`  | Line feed                                    |
+--------------+----------------------------------------------+
| :const:`NL`  | Alias for :const:`LF`: "New line"            |
+--------------+----------------------------------------------+
| :const:`VT`  | Vertical tab                                 |
+--------------+----------------------------------------------+
| :const:`FF`  | Form feed                                    |
+--------------+----------------------------------------------+
| :const:`CR`  | Carriage return                              |
+--------------+----------------------------------------------+
| :const:`SO`  | Shift-out, begin alternate character set     |
+--------------+----------------------------------------------+
| :const:`SI`  | Shift-in, resume default character set       |
+--------------+----------------------------------------------+
| :const:`DLE` | Data-link escape                             |
+--------------+----------------------------------------------+
| :const:`DC1` | XON, for flow control                        |
+--------------+----------------------------------------------+
| :const:`DC2` | Device control 2, block-mode flow control    |
+--------------+----------------------------------------------+
| :const:`DC3` | XOFF, for flow control                       |
+--------------+----------------------------------------------+
| :const:`DC4` | Device control 4                             |
+--------------+----------------------------------------------+
| :const:`NAK` | Negative acknowledgement                     |
+--------------+----------------------------------------------+
| :const:`SYN` | Synchronous idle                             |
+--------------+----------------------------------------------+
| :const:`ETB` | End transmission block                       |
+--------------+----------------------------------------------+
| :const:`CAN` | Cancel                                       |
+--------------+----------------------------------------------+
| :const:`EM`  | End of medium                                |
+--------------+----------------------------------------------+
| :const:`SUB` | Substitute                                   |
+--------------+----------------------------------------------+
| :const:`ESC` | Escape                                       |
+--------------+----------------------------------------------+
| :const:`FS`  | File separator                               |
+--------------+----------------------------------------------+
| :const:`GS`  | Group separator                              |
+--------------+----------------------------------------------+
| :const:`RS`  | Record separator, block-mode terminator      |
+--------------+----------------------------------------------+
| :const:`US`  | Unit separator                               |
+--------------+----------------------------------------------+
| :const:`SP`  | Space                                        |
+--------------+----------------------------------------------+
| :const:`DEL` | Delete                                       |
+--------------+----------------------------------------------+

Note that many of these have little practical significance in modern usage.  The
mnemonics derive from teleprinter conventions that predate digital computers.

The module supplies the following functions, patterned on those in the standard
C library:


.. function:: isalnum(c)

   Checks for an ASCII alphanumeric character; it is equivalent to ``isalpha(c) or
   isdigit(c)``.


.. function:: isalpha(c)

   Checks for an ASCII alphabetic character; it is equivalent to ``isupper(c) or
   islower(c)``.


.. function:: isascii(c)

   Checks for a character value that fits in the 7-bit ASCII set.


.. function:: isblank(c)

   Checks for an ASCII whitespace character; space or horizontal tab.


.. function:: iscntrl(c)

   Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f).


.. function:: isdigit(c)

   Checks for an ASCII decimal digit, ``'0'`` through ``'9'``.  This is equivalent
   to ``c in string.digits``.


.. function:: isgraph(c)

   Checks for ASCII any printable character except space.


.. function:: islower(c)

   Checks for an ASCII lower-case character.


.. function:: isprint(c)

   Checks for any ASCII printable character including space.


.. function:: ispunct(c)

   Checks for any printable ASCII character which is not a space or an alphanumeric
   character.


.. function:: isspace(c)

   Checks for ASCII white-space characters; space, line feed, carriage return, form
   feed, horizontal tab, vertical tab.


.. function:: isupper(c)

   Checks for an ASCII uppercase letter.


.. function:: isxdigit(c)

   Checks for an ASCII hexadecimal digit.  This is equivalent to ``c in
   string.hexdigits``.


.. function:: isctrl(c)

   Checks for an ASCII control character (ordinal values 0 to 31).


.. function:: ismeta(c)

   Checks for a non-ASCII character (ordinal values 0x80 and above).

These functions accept either integers or strings; when the argument is a
string, it is first converted using the built-in function :func:`ord`.

Note that all these functions check ordinal bit values derived from the  first
character of the string you pass in; they do not actually know anything about
the host machine's character encoding.  For functions  that know about the
character encoding (and handle internationalization properly) see the
:mod:`string` module.

The following two functions take either a single-character string or integer
byte value; they return a value of the same type.


.. function:: ascii(c)

   Return the ASCII value corresponding to the low 7 bits of *c*.


.. function:: ctrl(c)

   Return the control character corresponding to the given character (the character
   bit value is bitwise-anded with 0x1f).


.. function:: alt(c)

   Return the 8-bit character corresponding to the given ASCII character (the
   character bit value is bitwise-ored with 0x80).

The following function takes either a single-character string or integer value;
it returns a string.


.. function:: unctrl(c)

   Return a string representation of the ASCII character *c*.  If *c* is printable,
   this string is the character itself.  If the character is a control character
   (0x00--0x1f) the string consists of a caret (``'^'``) followed by the
   corresponding uppercase letter. If the character is an ASCII delete (0x7f) the
   string is ``'^?'``.  If the character has its meta bit (0x80) set, the meta bit
   is stripped, the preceding rules applied, and ``'!'`` prepended to the result.


.. data:: controlnames

   A 33-element string array that contains the ASCII mnemonics for the thirty-two
   ASCII control characters from 0 (NUL) to 0x1f (US), in order, plus the mnemonic
   ``SP`` for the space character.

PK	%�\��XR�
�
*html/_sources/library/curses.panel.rst.txtnu�[���:mod:`curses.panel` --- A panel stack extension for curses
==========================================================

.. module:: curses.panel
   :synopsis: A panel stack extension that adds depth to  curses windows.
.. sectionauthor:: A.M. Kuchling <amk@amk.ca>


Panels are windows with the added feature of depth, so they can be stacked on
top of each other, and only the visible portions of each window will be
displayed.  Panels can be added, moved up or down in the stack, and removed.


.. _cursespanel-functions:

Functions
---------

The module :mod:`curses.panel` defines the following functions:


.. function:: bottom_panel()

   Returns the bottom panel in the panel stack.


.. function:: new_panel(win)

   Returns a panel object, associating it with the given window *win*. Be aware
   that you need to keep the returned panel object referenced explicitly.  If you
   don't, the panel object is garbage collected and removed from the panel stack.


.. function:: top_panel()

   Returns the top panel in the panel stack.


.. function:: update_panels()

   Updates the virtual screen after changes in the panel stack. This does not call
   :func:`curses.doupdate`, so you'll have to do this yourself.


.. _curses-panel-objects:

Panel Objects
-------------

Panel objects, as returned by :func:`new_panel` above, are windows with a
stacking order. There's always a window associated with a panel which determines
the content, while the panel methods are responsible for the window's depth in
the panel stack.

Panel objects have the following methods:


.. method:: Panel.above()

   Returns the panel above the current panel.


.. method:: Panel.below()

   Returns the panel below the current panel.


.. method:: Panel.bottom()

   Push the panel to the bottom of the stack.


.. method:: Panel.hidden()

   Returns true if the panel is hidden (not visible), false otherwise.


.. method:: Panel.hide()

   Hide the panel. This does not delete the object, it just makes the window on
   screen invisible.


.. method:: Panel.move(y, x)

   Move the panel to the screen coordinates ``(y, x)``.


.. method:: Panel.replace(win)

   Change the window associated with the panel to the window *win*.


.. method:: Panel.set_userptr(obj)

   Set the panel's user pointer to *obj*. This is used to associate an arbitrary
   piece of data with the panel, and can be any Python object.


.. method:: Panel.show()

   Display the panel (which might have been hidden).


.. method:: Panel.top()

   Push panel to the top of the stack.


.. method:: Panel.userptr()

   Returns the user pointer for the panel.  This might be any Python object.


.. method:: Panel.window()

   Returns the window object associated with the panel.

PK	%�\�00�}$}$$html/_sources/library/curses.rst.txtnu�[���:mod:`curses` --- Terminal handling for character-cell displays
===============================================================

.. module:: curses
   :synopsis: An interface to the curses library, providing portable terminal
              handling.
   :platform: Unix
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
.. sectionauthor:: Eric Raymond <esr@thyrsus.com>

.. versionchanged:: 1.6
   Added support for the ``ncurses`` library and converted to a package.

The :mod:`curses` module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.

While curses is most widely used in the Unix environment, versions are available
for DOS, OS/2, and possibly other systems as well.  This extension module is
designed to match the API of ncurses, an open-source curses library hosted on
Linux and the BSD variants of Unix.

.. note::

   Since version 5.4, the ncurses library decides how to interpret non-ASCII data
   using the ``nl_langinfo`` function.  That means that you have to call
   :func:`locale.setlocale` in the application and encode Unicode strings
   using one of the system's available encodings.  This example uses the
   system's default encoding::

      import locale
      locale.setlocale(locale.LC_ALL, '')
      code = locale.getpreferredencoding()

   Then use *code* as the encoding for :meth:`str.encode` calls.

.. seealso::

   Module :mod:`curses.ascii`
      Utilities for working with ASCII characters, regardless of your locale settings.

   Module :mod:`curses.panel`
      A panel stack extension that adds depth to  curses windows.

   Module :mod:`curses.textpad`
      Editable text widget for curses supporting  :program:`Emacs`\ -like bindings.

   :ref:`curses-howto`
      Tutorial material on using curses with Python, by Andrew Kuchling and Eric
      Raymond.

   The :source:`Demo/curses/` directory in the Python source distribution contains
   some example programs using the curses bindings provided by this module.


.. _curses-functions:

Functions
---------

The module :mod:`curses` defines the following exception:


.. exception:: error

   Exception raised when a curses library function returns an error.

.. note::

   Whenever *x* or *y* arguments to a function or a method are optional, they
   default to the current cursor location. Whenever *attr* is optional, it defaults
   to :const:`A_NORMAL`.

The module :mod:`curses` defines the following functions:


.. function:: baudrate()

   Return the output speed of the terminal in bits per second.  On software
   terminal emulators it will have a fixed high value. Included for historical
   reasons; in former times, it was used to  write output loops for time delays and
   occasionally to change interfaces depending on the line speed.


.. function:: beep()

   Emit a short attention sound.


.. function:: can_change_color()

   Return ``True`` or ``False``, depending on whether the programmer can change the colors
   displayed by the terminal.


.. function:: cbreak()

   Enter cbreak mode.  In cbreak mode (sometimes called "rare" mode) normal tty
   line buffering is turned off and characters are available to be read one by one.
   However, unlike raw mode, special characters (interrupt, quit, suspend, and flow
   control) retain their effects on the tty driver and calling program.  Calling
   first :func:`raw` then :func:`cbreak` leaves the terminal in cbreak mode.


.. function:: color_content(color_number)

   Return the intensity of the red, green, and blue (RGB) components in the color
   *color_number*, which must be between ``0`` and :const:`COLORS`.  A 3-tuple is
   returned, containing the R,G,B values for the given color, which will be between
   ``0`` (no component) and ``1000`` (maximum amount of component).


.. function:: color_pair(color_number)

   Return the attribute value for displaying text in the specified color.  This
   attribute value can be combined with :const:`A_STANDOUT`, :const:`A_REVERSE`,
   and the other :const:`A_\*` attributes.  :func:`pair_number` is the counterpart
   to this function.


.. function:: curs_set(visibility)

   Set the cursor state.  *visibility* can be set to 0, 1, or 2, for invisible,
   normal, or very visible.  If the terminal supports the visibility requested, the
   previous cursor state is returned; otherwise, an exception is raised.  On many
   terminals, the "visible" mode is an underline cursor and the "very visible" mode
   is a block cursor.


.. function:: def_prog_mode()

   Save the current terminal mode as the "program" mode, the mode when the running
   program is using curses.  (Its counterpart is the "shell" mode, for when the
   program is not in curses.)  Subsequent calls to :func:`reset_prog_mode` will
   restore this mode.


.. function:: def_shell_mode()

   Save the current terminal mode as the "shell" mode, the mode when the running
   program is not using curses.  (Its counterpart is the "program" mode, when the
   program is using curses capabilities.) Subsequent calls to
   :func:`reset_shell_mode` will restore this mode.


.. function:: delay_output(ms)

   Insert an *ms* millisecond pause in output.


.. function:: doupdate()

   Update the physical screen.  The curses library keeps two data structures, one
   representing the current physical screen contents and a virtual screen
   representing the desired next state.  The :func:`doupdate` ground updates the
   physical screen to match the virtual screen.

   The virtual screen may be updated by a :meth:`noutrefresh` call after write
   operations such as :meth:`addstr` have been performed on a window.  The normal
   :meth:`refresh` call is simply :meth:`noutrefresh` followed by :func:`doupdate`;
   if you have to update multiple windows, you can speed performance and perhaps
   reduce screen flicker by issuing :meth:`noutrefresh` calls on all windows,
   followed by a single :func:`doupdate`.


.. function:: echo()

   Enter echo mode.  In echo mode, each character input is echoed to the screen as
   it is entered.


.. function:: endwin()

   De-initialize the library, and return terminal to normal status.


.. function:: erasechar()

   Return the user's current erase character.  Under Unix operating systems this
   is a property of the controlling tty of the curses program, and is not set by
   the curses library itself.


.. function:: filter()

   The :func:`.filter` routine, if used, must be called before :func:`initscr` is
   called.  The effect is that, during those calls, :envvar:`LINES` is set to 1; the
   capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home
   string is set to the value of cr. The effect is that the cursor is confined to
   the current line, and so are screen updates.  This may be used for enabling
   character-at-a-time  line editing without touching the rest of the screen.


.. function:: flash()

   Flash the screen.  That is, change it to reverse-video and then change it back
   in a short interval.  Some people prefer such as 'visible bell' to the audible
   attention signal produced by :func:`beep`.


.. function:: flushinp()

   Flush all input buffers.  This throws away any  typeahead  that  has been typed
   by the user and has not yet been processed by the program.


.. function:: getmouse()

   After :meth:`getch` returns :const:`KEY_MOUSE` to signal a mouse event, this
   method should be call to retrieve the queued mouse event, represented as a
   5-tuple ``(id, x, y, z, bstate)``. *id* is an ID value used to distinguish
   multiple devices, and *x*, *y*, *z* are the event's coordinates.  (*z* is
   currently unused.)  *bstate* is an integer value whose bits will be set to
   indicate the type of event, and will be the bitwise OR of one or more of the
   following constants, where *n* is the button number from 1 to 4:
   :const:`BUTTONn_PRESSED`, :const:`BUTTONn_RELEASED`, :const:`BUTTONn_CLICKED`,
   :const:`BUTTONn_DOUBLE_CLICKED`, :const:`BUTTONn_TRIPLE_CLICKED`,
   :const:`BUTTON_SHIFT`, :const:`BUTTON_CTRL`, :const:`BUTTON_ALT`.


.. function:: getsyx()

   Return the current coordinates of the virtual screen cursor in y and x.  If
   leaveok is currently true, then -1,-1 is returned.


.. function:: getwin(file)

   Read window related data stored in the file by an earlier :func:`putwin` call.
   The routine then creates and initializes a new window using that data, returning
   the new window object.


.. function:: has_colors()

   Return ``True`` if the terminal can display colors; otherwise, return ``False``.


.. function:: has_ic()

   Return ``True`` if the terminal has insert- and delete-character capabilities.
   This function is included for historical reasons only, as all modern software
   terminal emulators have such capabilities.


.. function:: has_il()

   Return ``True`` if the terminal has insert- and delete-line capabilities, or can
   simulate  them  using scrolling regions. This function is included for
   historical reasons only, as all modern software terminal emulators have such
   capabilities.


.. function:: has_key(ch)

   Take a key value *ch*, and return ``True`` if the current terminal type recognizes
   a key with that value.


.. function:: halfdelay(tenths)

   Used for half-delay mode, which is similar to cbreak mode in that characters
   typed by the user are immediately available to the program. However, after
   blocking for *tenths* tenths of seconds, an exception is raised if nothing has
   been typed.  The value of *tenths* must be a number between ``1`` and ``255``.  Use
   :func:`nocbreak` to leave half-delay mode.


.. function:: init_color(color_number, r, g, b)

   Change the definition of a color, taking the number of the color to be changed
   followed by three RGB values (for the amounts of red, green, and blue
   components).  The value of *color_number* must be between ``0`` and
   :const:`COLORS`.  Each of *r*, *g*, *b*, must be a value between ``0`` and
   ``1000``.  When :func:`init_color` is used, all occurrences of that color on the
   screen immediately change to the new definition.  This function is a no-op on
   most terminals; it is active only if :func:`can_change_color` returns ``1``.


.. function:: init_pair(pair_number, fg, bg)

   Change the definition of a color-pair.  It takes three arguments: the number of
   the color-pair to be changed, the foreground color number, and the background
   color number.  The value of *pair_number* must be between ``1`` and
   ``COLOR_PAIRS - 1`` (the ``0`` color pair is wired to white on black and cannot
   be changed).  The value of *fg* and *bg* arguments must be between ``0`` and
   :const:`COLORS`.  If the color-pair was previously initialized, the screen is
   refreshed and all occurrences of that color-pair are changed to the new
   definition.


.. function:: initscr()

   Initialize the library. Return a :class:`WindowObject` which represents the
   whole screen.

   .. note::

      If there is an error opening the terminal, the underlying curses library may
      cause the interpreter to exit.


.. function:: is_term_resized(nlines, ncols)

   Return ``True`` if :func:`resize_term` would modify the window structure,
   ``False`` otherwise.


.. function:: isendwin()

   Return ``True`` if :func:`endwin` has been called (that is, the  curses library has
   been deinitialized).


.. function:: keyname(k)

   Return the name of the key numbered *k*.  The name of a key generating printable
   ASCII character is the key's character.  The name of a control-key combination
   is a two-character string consisting of a caret followed by the corresponding
   printable ASCII character.  The name of an alt-key combination (128--255) is a
   string consisting of the prefix 'M-' followed by the name of the corresponding
   ASCII character.


.. function:: killchar()

   Return the user's current line kill character. Under Unix operating systems
   this is a property of the controlling tty of the curses program, and is not set
   by the curses library itself.


.. function:: longname()

   Return a string containing the terminfo long name field describing the current
   terminal.  The maximum length of a verbose description is 128 characters.  It is
   defined only after the call to :func:`initscr`.


.. function:: meta(yes)

   If *yes* is 1, allow 8-bit characters to be input. If *yes* is 0,  allow only
   7-bit chars.


.. function:: mouseinterval(interval)

   Set the maximum time in milliseconds that can elapse between press and release
   events in order for them to be recognized as a click, and return the previous
   interval value.  The default value is 200 msec, or one fifth of a second.


.. function:: mousemask(mousemask)

   Set the mouse events to be reported, and return a tuple ``(availmask,
   oldmask)``.   *availmask* indicates which of the specified mouse events can be
   reported; on complete failure it returns 0.  *oldmask* is the previous value of
   the given window's mouse event mask.  If this function is never called, no mouse
   events are ever reported.


.. function:: napms(ms)

   Sleep for *ms* milliseconds.


.. function:: newpad(nlines, ncols)

   Create and return a pointer to a new pad data structure with the given number
   of lines and columns.  A pad is returned as a window object.

   A pad is like a window, except that it is not restricted by the screen size, and
   is not necessarily associated with a particular part of the screen.  Pads can be
   used when a large window is needed, and only a part of the window will be on the
   screen at one time.  Automatic refreshes of pads (such as from scrolling or
   echoing of input) do not occur.  The :meth:`refresh` and :meth:`noutrefresh`
   methods of a pad require 6 arguments to specify the part of the pad to be
   displayed and the location on the screen to be used for the display. The
   arguments are *pminrow*, *pmincol*, *sminrow*, *smincol*, *smaxrow*, *smaxcol*; the *p*
   arguments refer to the upper left corner of the pad region to be displayed and
   the *s* arguments define a clipping box on the screen within which the pad region
   is to be displayed.


.. function:: newwin(nlines, ncols)
              newwin(nlines, ncols, begin_y, begin_x)

   Return a new window, whose left-upper corner is at  ``(begin_y, begin_x)``, and
   whose height/width is  *nlines*/*ncols*.

   By default, the window will extend from the  specified position to the lower
   right corner of the screen.


.. function:: nl()

   Enter newline mode.  This mode translates the return key into newline on input,
   and translates newline into return and line-feed on output. Newline mode is
   initially on.


.. function:: nocbreak()

   Leave cbreak mode.  Return to normal "cooked" mode with line buffering.


.. function:: noecho()

   Leave echo mode.  Echoing of input characters is turned off.


.. function:: nonl()

   Leave newline mode.  Disable translation of return into newline on input, and
   disable low-level translation of newline into newline/return on output (but this
   does not change the behavior of ``addch('\n')``, which always does the
   equivalent of return and line feed on the virtual screen).  With translation
   off, curses can sometimes speed up vertical motion a little; also, it will be
   able to detect the return key on input.


.. function:: noqiflush()

   When the :func:`noqiflush` routine is used, normal flush of input and output queues
   associated with the INTR, QUIT and SUSP characters will not be done.  You may
   want to call :func:`noqiflush` in a signal handler if you want output to
   continue as though the interrupt had not occurred, after the handler exits.


.. function:: noraw()

   Leave raw mode. Return to normal "cooked" mode with line buffering.


.. function:: pair_content(pair_number)

   Return a tuple ``(fg, bg)`` containing the colors for the requested color pair.
   The value of *pair_number* must be between ``1`` and ``COLOR_PAIRS - 1``.


.. function:: pair_number(attr)

   Return the number of the color-pair set by the attribute value *attr*.
   :func:`color_pair` is the counterpart to this function.


.. function:: putp(string)

   Equivalent to ``tputs(str, 1, putchar)``; emit the value of a specified
   terminfo capability for the current terminal.  Note that the output of :func:`putp`
   always goes to standard output.


.. function:: qiflush( [flag] )

   If *flag* is ``False``, the effect is the same as calling :func:`noqiflush`. If
   *flag* is ``True``, or no argument is provided, the queues will be flushed when
   these control characters are read.


.. function:: raw()

   Enter raw mode.  In raw mode, normal line buffering and  processing of
   interrupt, quit, suspend, and flow control keys are turned off; characters are
   presented to curses input functions one by one.


.. function:: reset_prog_mode()

   Restore the  terminal  to "program" mode, as previously saved  by
   :func:`def_prog_mode`.


.. function:: reset_shell_mode()

   Restore the  terminal  to "shell" mode, as previously saved  by
   :func:`def_shell_mode`.


.. function:: resetty()

   Restore the state of the terminal modes to what it was at the last call to
   :func:`savetty`.


.. function:: resize_term(nlines, ncols)

   Backend function used by :func:`resizeterm`, performing most of the work;
   when resizing the windows, :func:`resize_term` blank-fills the areas that are
   extended.  The calling application should fill in these areas with
   appropriate data.  The :func:`resize_term` function attempts to resize all
   windows.  However, due to the calling convention of pads, it is not possible
   to resize these without additional interaction with the application.


.. function:: resizeterm(nlines, ncols)

   Resize the standard and current windows to the specified dimensions, and
   adjusts other bookkeeping data used by the curses library that record the
   window dimensions (in particular the SIGWINCH handler).


.. function:: savetty()

   Save the current state of the terminal modes in a buffer, usable by
   :func:`resetty`.


.. function:: setsyx(y, x)

   Set the virtual screen cursor to *y*, *x*. If *y* and *x* are both -1, then
   leaveok is set.


.. function:: setupterm([termstr, fd])

   Initialize the terminal.  *termstr* is a string giving the terminal name; if
   omitted, the value of the :envvar:`TERM` environment variable will be used.  *fd* is the
   file descriptor to which any initialization sequences will be sent; if not
   supplied, the file descriptor for ``sys.stdout`` will be used.


.. function:: start_color()

   Must be called if the programmer wants to use colors, and before any other color
   manipulation routine is called.  It is good practice to call this routine right
   after :func:`initscr`.

   :func:`start_color` initializes eight basic colors (black, red,  green, yellow,
   blue, magenta, cyan, and white), and two global variables in the :mod:`curses`
   module, :const:`COLORS` and :const:`COLOR_PAIRS`, containing the maximum number
   of colors and color-pairs the terminal can support.  It also restores the colors
   on the terminal to the values they had when the terminal was just turned on.


.. function:: termattrs()

   Return a logical OR of all video attributes supported by the terminal.  This
   information is useful when a curses program needs complete control over the
   appearance of the screen.


.. function:: termname()

   Return the value of the environment variable :envvar:`TERM`, truncated to 14 characters.


.. function:: tigetflag(capname)

   Return the value of the Boolean capability corresponding to the terminfo
   capability name *capname*.  The value ``-1`` is returned if *capname* is not a
   Boolean capability, or ``0`` if it is canceled or absent from the terminal
   description.


.. function:: tigetnum(capname)

   Return the value of the numeric capability corresponding to the terminfo
   capability name *capname*.  The value ``-2`` is returned if *capname* is not a
   numeric capability, or ``-1`` if it is canceled or absent from the terminal
   description.


.. function:: tigetstr(capname)

   Return the value of the string capability corresponding to the terminfo
   capability name *capname*.  ``None`` is returned if *capname* is not a string
   capability, or is canceled or absent from the terminal description.


.. function:: tparm(str[,...])

   Instantiate the string *str* with the supplied parameters, where *str* should
   be a parameterized string obtained from the terminfo database.  E.g.
   ``tparm(tigetstr("cup"), 5, 3)`` could result in ``'\033[6;4H'``, the exact
   result depending on terminal type.


.. function:: typeahead(fd)

   Specify that the file descriptor *fd* be used for typeahead checking.  If *fd*
   is ``-1``, then no typeahead checking is done.

   The curses library does "line-breakout optimization" by looking for typeahead
   periodically while updating the screen.  If input is found, and it is coming
   from a tty, the current update is postponed until refresh or doupdate is called
   again, allowing faster response to commands typed in advance. This function
   allows specifying a different file descriptor for typeahead checking.


.. function:: unctrl(ch)

   Return a string which is a printable representation of the character *ch*.
   Control characters are displayed as a caret followed by the character, for
   example as ``^C``. Printing characters are left as they are.


.. function:: ungetch(ch)

   Push *ch* so the next :meth:`getch` will return it.

   .. note::

      Only one *ch* can be pushed before :meth:`getch` is called.


.. function:: ungetmouse(id, x, y, z, bstate)

   Push a :const:`KEY_MOUSE` event onto the input queue, associating the given
   state data with it.


.. function:: use_env(flag)

   If used, this function should be called before :func:`initscr` or newterm are
   called.  When *flag* is ``False``, the values of lines and columns specified in the
   terminfo database will be used, even if environment variables :envvar:`LINES`
   and :envvar:`COLUMNS` (used by default) are set, or if curses is running in a
   window (in which case default behavior would be to use the window size if
   :envvar:`LINES` and :envvar:`COLUMNS` are not set).


.. function:: use_default_colors()

   Allow use of default values for colors on terminals supporting this feature. Use
   this to support transparency in your application.  The default color is assigned
   to the color number -1. After calling this function,  ``init_pair(x,
   curses.COLOR_RED, -1)`` initializes, for instance, color pair *x* to a red
   foreground color on the default background.


.. function:: wrapper(func, ...)

   Initialize curses and call another callable object, *func*, which should be the
   rest of your curses-using application.  If the application raises an exception,
   this function will restore the terminal to a sane state before re-raising the
   exception and generating a traceback.  The callable object *func* is then passed
   the main window 'stdscr' as its first argument, followed by any other arguments
   passed to :func:`wrapper`.  Before calling *func*, :func:`wrapper` turns on
   cbreak mode, turns off echo, enables the terminal keypad, and initializes colors
   if the terminal has color support.  On exit (whether normally or by exception)
   it restores cooked mode, turns on echo, and disables the terminal keypad.


.. _curses-window-objects:

Window Objects
--------------

Window objects, as returned by :func:`initscr` and :func:`newwin` above, have
the following methods:


.. method:: window.addch(ch[, attr])
            window.addch(y, x, ch[, attr])

   .. note::

      A *character* means a C character (an ASCII code), rather than a Python
      character (a string of length 1). (This note is true whenever the
      documentation mentions a character.) The built-in :func:`ord` is handy for
      conveying strings to codes.

   Paint character *ch* at ``(y, x)`` with attributes *attr*, overwriting any
   character previously painter at that location.  By default, the character
   position and attributes are the current settings for the window object.

   .. note::

      Writing outside the window, subwindow, or pad raises a :exc:`curses.error`.
      Attempting to write to the lower right corner of a window, subwindow,
      or pad will cause an exception to be raised after the character is printed.


.. method:: window.addnstr(str, n[, attr])
            window.addnstr(y, x, str, n[, attr])

   Paint at most *n* characters of the  string *str* at ``(y, x)`` with attributes
   *attr*, overwriting anything previously on the display.


.. method:: window.addstr(str[, attr])
            window.addstr(y, x, str[, attr])

   Paint the string *str* at ``(y, x)`` with attributes *attr*, overwriting
   anything previously on the display.

   .. note::

      Writing outside the window, subwindow, or pad raises :exc:`curses.error`.
      Attempting to write to the lower right corner of a window, subwindow,
      or pad will cause an exception to be raised after the string is printed.


.. method:: window.attroff(attr)

   Remove attribute *attr* from the "background" set applied to all writes to the
   current window.


.. method:: window.attron(attr)

   Add attribute *attr* from the "background" set applied to all writes to the
   current window.


.. method:: window.attrset(attr)

   Set the "background" set of attributes to *attr*.  This set is initially 0 (no
   attributes).


.. method:: window.bkgd(ch[, attr])

   Set the background property of the window to the character *ch*, with
   attributes *attr*.  The change is then applied to every character position in
   that window:

   * The attribute of every character in the window  is changed to the new
     background attribute.

   * Wherever  the  former background character appears, it is changed to the new
     background character.


.. method:: window.bkgdset(ch[, attr])

   Set the window's background.  A window's background consists of a character and
   any combination of attributes.  The attribute part of the background is combined
   (OR'ed) with all non-blank characters that are written into the window.  Both
   the character and attribute parts of the background are combined with the blank
   characters.  The background becomes a property of the character and moves with
   the character through any scrolling and insert/delete line/character operations.


.. method:: window.border([ls[, rs[, ts[, bs[, tl[, tr[, bl[, br]]]]]]]])

   Draw a border around the edges of the window. Each parameter specifies  the
   character to use for a specific part of the border; see the table below for more
   details.  The characters can be specified as integers or as one-character
   strings.

   .. note::

      A ``0`` value for any parameter will cause the default character to be used for
      that parameter.  Keyword parameters can *not* be used.  The defaults are listed
      in this table:

   +-----------+---------------------+-----------------------+
   | Parameter | Description         | Default value         |
   +===========+=====================+=======================+
   | *ls*      | Left side           | :const:`ACS_VLINE`    |
   +-----------+---------------------+-----------------------+
   | *rs*      | Right side          | :const:`ACS_VLINE`    |
   +-----------+---------------------+-----------------------+
   | *ts*      | Top                 | :const:`ACS_HLINE`    |
   +-----------+---------------------+-----------------------+
   | *bs*      | Bottom              | :const:`ACS_HLINE`    |
   +-----------+---------------------+-----------------------+
   | *tl*      | Upper-left corner   | :const:`ACS_ULCORNER` |
   +-----------+---------------------+-----------------------+
   | *tr*      | Upper-right corner  | :const:`ACS_URCORNER` |
   +-----------+---------------------+-----------------------+
   | *bl*      | Bottom-left corner  | :const:`ACS_LLCORNER` |
   +-----------+---------------------+-----------------------+
   | *br*      | Bottom-right corner | :const:`ACS_LRCORNER` |
   +-----------+---------------------+-----------------------+


.. method:: window.box([vertch, horch])

   Similar to :meth:`border`, but both *ls* and *rs* are *vertch* and both *ts* and
   *bs* are *horch*.  The default corner characters are always used by this function.


.. method:: window.chgat(attr)
            window.chgat(num, attr)
            window.chgat(y, x, attr)
            window.chgat(y, x, num, attr)

   Set the attributes of *num* characters at the current cursor position, or at
   position ``(y, x)`` if supplied. If *num* is not given or is ``-1``,
   the attribute will be set on all the characters to the end of the line.  This
   function moves cursor to position ``(y, x)`` if supplied. The changed line
   will be touched using the :meth:`touchline` method so that the contents will
   be redisplayed by the next window refresh.


.. method:: window.clear()

   Like :meth:`erase`, but also cause the whole window to be repainted upon next
   call to :meth:`refresh`.


.. method:: window.clearok(yes)

   If *yes* is 1, the next call to :meth:`refresh` will clear the window
   completely.


.. method:: window.clrtobot()

   Erase from cursor to the end of the window: all lines below the cursor are
   deleted, and then the equivalent of :meth:`clrtoeol` is performed.


.. method:: window.clrtoeol()

   Erase from cursor to the end of the line.


.. method:: window.cursyncup()

   Update the current cursor position of all the ancestors of the window to
   reflect the current cursor position of the window.


.. method:: window.delch([y, x])

   Delete any character at ``(y, x)``.


.. method:: window.deleteln()

   Delete the line under the cursor. All following lines are moved up by one line.


.. method:: window.derwin(begin_y, begin_x)
            window.derwin(nlines, ncols, begin_y, begin_x)

   An abbreviation for "derive window", :meth:`derwin` is the same as calling
   :meth:`subwin`, except that *begin_y* and *begin_x* are relative to the origin
   of the window, rather than relative to the entire screen.  Return a window
   object for the derived window.


.. method:: window.echochar(ch[, attr])

   Add character *ch* with attribute *attr*, and immediately  call :meth:`refresh`
   on the window.


.. method:: window.enclose(y, x)

   Test whether the given pair of screen-relative character-cell coordinates are
   enclosed by the given window, returning ``True`` or ``False``.  It is useful for
   determining what subset of the screen windows enclose the location of a mouse
   event.


.. method:: window.erase()

   Clear the window.


.. method:: window.getbegyx()

   Return a tuple ``(y, x)`` of co-ordinates of upper-left corner.


.. method:: window.getbkgd()

   Return the given window's current background character/attribute pair.


.. method:: window.getch([y, x])

   Get a character. Note that the integer returned does *not* have to be in ASCII
   range: function keys, keypad keys and so on return numbers higher than 256. In
   no-delay mode, -1 is returned if there is no input, else :func:`getch` waits
   until a key is pressed.


.. method:: window.getkey([y, x])

   Get a character, returning a string instead of an integer, as :meth:`getch`
   does. Function keys, keypad keys and so on return a multibyte string containing
   the key name.  In no-delay mode, an exception is raised if there is no input.


.. method:: window.getmaxyx()

   Return a tuple ``(y, x)`` of the height and width of the window.


.. method:: window.getparyx()

   Return the beginning coordinates of this window relative to its parent window
   into two integer variables y and x.  Return ``-1, -1`` if this window has no
   parent.


.. method:: window.getstr([y, x])

   Read a string from the user, with primitive line editing capacity.


.. method:: window.getyx()

   Return a tuple ``(y, x)`` of current cursor position  relative to the window's
   upper-left corner.


.. method:: window.hline(ch, n)
            window.hline(y, x, ch, n)

   Display a horizontal line starting at ``(y, x)`` with length *n* consisting of
   the character *ch*.


.. method:: window.idcok(flag)

   If *flag* is ``False``, curses no longer considers using the hardware insert/delete
   character feature of the terminal; if *flag* is ``True``, use of character insertion
   and deletion is enabled.  When curses is first initialized, use of character
   insert/delete is enabled by default.


.. method:: window.idlok(yes)

   If called with *yes* equal to 1, :mod:`curses` will try and use hardware line
   editing facilities. Otherwise, line insertion/deletion are disabled.


.. method:: window.immedok(flag)

   If *flag* is ``True``, any change in the window image automatically causes the
   window to be refreshed; you no longer have to call :meth:`refresh` yourself.
   However, it may degrade performance considerably, due to repeated calls to
   wrefresh.  This option is disabled by default.


.. method:: window.inch([y, x])

   Return the character at the given position in the window. The bottom 8 bits are
   the character proper, and upper bits are the attributes.


.. method:: window.insch(ch[, attr])
            window.insch(y, x, ch[, attr])

   Paint character *ch* at ``(y, x)`` with attributes *attr*, moving the line from
   position *x* right by one character.


.. method:: window.insdelln(nlines)

   Insert *nlines* lines into the specified window above the current line.  The
   *nlines* bottom lines are lost.  For negative *nlines*, delete *nlines* lines
   starting with the one under the cursor, and move the remaining lines up.  The
   bottom *nlines* lines are cleared.  The current cursor position remains the
   same.


.. method:: window.insertln()

   Insert a blank line under the cursor. All following lines are moved down by one
   line.


.. method:: window.insnstr(str, n[, attr])
            window.insnstr(y, x, str, n[, attr])

   Insert a character string (as many characters as will fit on the line) before
   the character under the cursor, up to *n* characters.   If *n* is zero or
   negative, the entire string is inserted. All characters to the right of the
   cursor are shifted right, with the rightmost characters on the line being lost.
   The cursor position does not change (after moving to *y*, *x*, if specified).


.. method:: window.insstr(str[, attr])
            window.insstr(y, x, str[, attr])

   Insert a character string (as many characters as will fit on the line) before
   the character under the cursor.  All characters to the right of the cursor are
   shifted right, with the rightmost characters on the line being lost.  The cursor
   position does not change (after moving to *y*, *x*, if specified).


.. method:: window.instr([n])
            window.instr(y, x[, n])

   Return a string of characters, extracted from the window starting at the
   current cursor position, or at *y*, *x* if specified. Attributes are stripped
   from the characters.  If *n* is specified, :meth:`instr` returns a string
   at most *n* characters long (exclusive of the trailing NUL).


.. method:: window.is_linetouched(line)

   Return ``True`` if the specified line was modified since the last call to
   :meth:`refresh`; otherwise return ``False``.  Raise a :exc:`curses.error`
   exception if *line* is not valid for the given window.


.. method:: window.is_wintouched()

   Return ``True`` if the specified window was modified since the last call to
   :meth:`refresh`; otherwise return ``False``.


.. method:: window.keypad(yes)

   If *yes* is 1, escape sequences generated by some keys (keypad,  function keys)
   will be interpreted by :mod:`curses`. If *yes* is 0, escape sequences will be
   left as is in the input stream.


.. method:: window.leaveok(yes)

   If *yes* is 1, cursor is left where it is on update, instead of being at "cursor
   position."  This reduces cursor movement where possible. If possible the cursor
   will be made invisible.

   If *yes* is 0, cursor will always be at "cursor position" after an update.


.. method:: window.move(new_y, new_x)

   Move cursor to ``(new_y, new_x)``.


.. method:: window.mvderwin(y, x)

   Move the window inside its parent window.  The screen-relative parameters of
   the window are not changed.  This routine is used to display different parts of
   the parent window at the same physical position on the screen.


.. method:: window.mvwin(new_y, new_x)

   Move the window so its upper-left corner is at ``(new_y, new_x)``.


.. method:: window.nodelay(yes)

   If *yes* is ``1``, :meth:`getch` will be non-blocking.


.. method:: window.notimeout(yes)

   If *yes* is ``1``, escape sequences will not be timed out.

   If *yes* is ``0``, after a few milliseconds, an escape sequence will not be
   interpreted, and will be left in the input stream as is.


.. method:: window.noutrefresh()

   Mark for refresh but wait.  This function updates the data structure
   representing the desired state of the window, but does not force an update of
   the physical screen.  To accomplish that, call  :func:`doupdate`.


.. method:: window.overlay(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

   Overlay the window on top of *destwin*. The windows need not be the same size,
   only the overlapping region is copied. This copy is non-destructive, which means
   that the current background character does not overwrite the old contents of
   *destwin*.

   To get fine-grained control over the copied region, the second form of
   :meth:`overlay` can be used. *sminrow* and *smincol* are the upper-left
   coordinates of the source window, and the other variables mark a rectangle in
   the destination window.


.. method:: window.overwrite(destwin[, sminrow, smincol, dminrow, dmincol, dmaxrow, dmaxcol])

   Overwrite the window on top of *destwin*. The windows need not be the same size,
   in which case only the overlapping region is copied. This copy is destructive,
   which means that the current background character overwrites the old contents of
   *destwin*.

   To get fine-grained control over the copied region, the second form of
   :meth:`overwrite` can be used. *sminrow* and *smincol* are the upper-left
   coordinates of the source window, the other variables mark a rectangle in the
   destination window.


.. method:: window.putwin(file)

   Write all data associated with the window into the provided file object.  This
   information can be later retrieved using the :func:`getwin` function.


.. method:: window.redrawln(beg, num)

   Indicate that the *num* screen lines, starting at line *beg*, are corrupted and
   should be completely redrawn on the next :meth:`refresh` call.


.. method:: window.redrawwin()

   Touch the entire window, causing it to be completely redrawn on the next
   :meth:`refresh` call.


.. method:: window.refresh([pminrow, pmincol, sminrow, smincol, smaxrow, smaxcol])

   Update the display immediately (sync actual screen with previous
   drawing/deleting methods).

   The 6 optional arguments can only be specified when the window is a pad created
   with :func:`newpad`.  The additional parameters are needed to indicate what part
   of the pad and screen are involved. *pminrow* and *pmincol* specify the upper
   left-hand corner of the rectangle to be displayed in the pad.  *sminrow*,
   *smincol*, *smaxrow*, and *smaxcol* specify the edges of the rectangle to be
   displayed on the screen.  The lower right-hand corner of the rectangle to be
   displayed in the pad is calculated from the screen coordinates, since the
   rectangles must be the same size.  Both rectangles must be entirely contained
   within their respective structures.  Negative values of *pminrow*, *pmincol*,
   *sminrow*, or *smincol* are treated as if they were zero.


.. method:: window.resize(nlines, ncols)

   Reallocate storage for a curses window to adjust its dimensions to the
   specified values.  If either dimension is larger than the current values, the
   window's data is filled with blanks that have the current background
   rendition (as set by :meth:`bkgdset`) merged into them.


.. method:: window.scroll([lines=1])

   Scroll the screen or scrolling region upward by *lines* lines.


.. method:: window.scrollok(flag)

   Control what happens when the cursor of a window is moved off the edge of the
   window or scrolling region, either as a result of a newline action on the bottom
   line, or typing the last character of the last line.  If *flag* is false, the
   cursor is left on the bottom line.  If *flag* is true, the window is scrolled up
   one line.  Note that in order to get the physical scrolling effect on the
   terminal, it is also necessary to call :meth:`idlok`.


.. method:: window.setscrreg(top, bottom)

   Set the scrolling region from line *top* to line *bottom*. All scrolling actions
   will take place in this region.


.. method:: window.standend()

   Turn off the standout attribute.  On some terminals this has the side effect of
   turning off all attributes.


.. method:: window.standout()

   Turn on attribute *A_STANDOUT*.


.. method:: window.subpad(begin_y, begin_x)
            window.subpad(nlines, ncols, begin_y, begin_x)

   Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
   whose width/height is *ncols*/*nlines*.


.. method:: window.subwin(begin_y, begin_x)
            window.subwin(nlines, ncols, begin_y, begin_x)

   Return a sub-window, whose upper-left corner is at ``(begin_y, begin_x)``, and
   whose width/height is *ncols*/*nlines*.

   By default, the sub-window will extend from the specified position to the lower
   right corner of the window.


.. method:: window.syncdown()

   Touch each location in the window that has been touched in any of its ancestor
   windows.  This routine is called by :meth:`refresh`, so it should almost never
   be necessary to call it manually.


.. method:: window.syncok(flag)

   If called with *flag* set to ``True``, then :meth:`syncup` is called automatically
   whenever there is a change in the window.


.. method:: window.syncup()

   Touch all locations in ancestors of the window that have been changed in  the
   window.


.. method:: window.timeout(delay)

   Set blocking or non-blocking read behavior for the window.  If *delay* is
   negative, blocking read is used (which will wait indefinitely for input).  If
   *delay* is zero, then non-blocking read is used, and -1 will be returned by
   :meth:`getch` if no input is waiting.  If *delay* is positive, then
   :meth:`getch` will block for *delay* milliseconds, and return -1 if there is
   still no input at the end of that time.


.. method:: window.touchline(start, count[, changed])

   Pretend *count* lines have been changed, starting with line *start*.  If
   *changed* is supplied, it specifies whether the affected lines are marked as
   having been changed (*changed*\ =1) or unchanged (*changed*\ =0).


.. method:: window.touchwin()

   Pretend the whole window has been changed, for purposes of drawing
   optimizations.


.. method:: window.untouchwin()

   Mark all lines in  the  window  as unchanged since the last call to
   :meth:`refresh`.


.. method:: window.vline(ch, n)
            window.vline(y, x, ch, n)

   Display a vertical line starting at ``(y, x)`` with length *n* consisting of the
   character *ch*.


Constants
---------

The :mod:`curses` module defines the following data members:


.. data:: ERR

   Some curses routines  that  return  an integer, such as  :func:`getch`, return
   :const:`ERR` upon failure.


.. data:: OK

   Some curses routines  that  return  an integer, such as  :func:`napms`, return
   :const:`OK` upon success.


.. data:: version

   A string representing the current version of the module.  Also available as
   :const:`__version__`.

Some constants are available to specify character cell attributes.
The exact constants available are system dependent.

+------------------+-------------------------------+
| Attribute        | Meaning                       |
+==================+===============================+
| ``A_ALTCHARSET`` | Alternate character set mode  |
+------------------+-------------------------------+
| ``A_BLINK``      | Blink mode                    |
+------------------+-------------------------------+
| ``A_BOLD``       | Bold mode                     |
+------------------+-------------------------------+
| ``A_DIM``        | Dim mode                      |
+------------------+-------------------------------+
| ``A_INVIS``      | Invisible or blank mode       |
+------------------+-------------------------------+
| ``A_NORMAL``     | Normal attribute              |
+------------------+-------------------------------+
| ``A_PROTECT``    | Protected mode                |
+------------------+-------------------------------+
| ``A_REVERSE``    | Reverse background and        |
|                  | foreground colors             |
+------------------+-------------------------------+
| ``A_STANDOUT``   | Standout mode                 |
+------------------+-------------------------------+
| ``A_UNDERLINE``  | Underline mode                |
+------------------+-------------------------------+
| ``A_HORIZONTAL`` | Horizontal highlight          |
+------------------+-------------------------------+
| ``A_LEFT``       | Left highlight                |
+------------------+-------------------------------+
| ``A_LOW``        | Low highlight                 |
+------------------+-------------------------------+
| ``A_RIGHT``      | Right highlight               |
+------------------+-------------------------------+
| ``A_TOP``        | Top highlight                 |
+------------------+-------------------------------+
| ``A_VERTICAL``   | Vertical highlight            |
+------------------+-------------------------------+
| ``A_CHARTEXT``   | Bit-mask to extract a         |
|                  | character                     |
+------------------+-------------------------------+

Several constants are available to extract corresponding attributes returned
by some methods.

+------------------+-------------------------------+
| Bit-mask         | Meaning                       |
+==================+===============================+
| ``A_ATTRIBUTES`` | Bit-mask to extract           |
|                  | attributes                    |
+------------------+-------------------------------+
| ``A_CHARTEXT``   | Bit-mask to extract a         |
|                  | character                     |
+------------------+-------------------------------+
| ``A_COLOR``      | Bit-mask to extract           |
|                  | color-pair field information  |
+------------------+-------------------------------+

Keys are referred to by integer constants with names starting with  ``KEY_``.
The exact keycaps available are system dependent.

.. XXX this table is far too large! should it be alphabetized?

+-------------------+--------------------------------------------+
| Key constant      | Key                                        |
+===================+============================================+
| ``KEY_MIN``       | Minimum key value                          |
+-------------------+--------------------------------------------+
| ``KEY_BREAK``     | Break key (unreliable)                     |
+-------------------+--------------------------------------------+
| ``KEY_DOWN``      | Down-arrow                                 |
+-------------------+--------------------------------------------+
| ``KEY_UP``        | Up-arrow                                   |
+-------------------+--------------------------------------------+
| ``KEY_LEFT``      | Left-arrow                                 |
+-------------------+--------------------------------------------+
| ``KEY_RIGHT``     | Right-arrow                                |
+-------------------+--------------------------------------------+
| ``KEY_HOME``      | Home key (upward+left arrow)               |
+-------------------+--------------------------------------------+
| ``KEY_BACKSPACE`` | Backspace (unreliable)                     |
+-------------------+--------------------------------------------+
| ``KEY_F0``        | Function keys.  Up to 64 function keys are |
|                   | supported.                                 |
+-------------------+--------------------------------------------+
| ``KEY_Fn``        | Value of function key *n*                  |
+-------------------+--------------------------------------------+
| ``KEY_DL``        | Delete line                                |
+-------------------+--------------------------------------------+
| ``KEY_IL``        | Insert line                                |
+-------------------+--------------------------------------------+
| ``KEY_DC``        | Delete character                           |
+-------------------+--------------------------------------------+
| ``KEY_IC``        | Insert char or enter insert mode           |
+-------------------+--------------------------------------------+
| ``KEY_EIC``       | Exit insert char mode                      |
+-------------------+--------------------------------------------+
| ``KEY_CLEAR``     | Clear screen                               |
+-------------------+--------------------------------------------+
| ``KEY_EOS``       | Clear to end of screen                     |
+-------------------+--------------------------------------------+
| ``KEY_EOL``       | Clear to end of line                       |
+-------------------+--------------------------------------------+
| ``KEY_SF``        | Scroll 1 line forward                      |
+-------------------+--------------------------------------------+
| ``KEY_SR``        | Scroll 1 line backward (reverse)           |
+-------------------+--------------------------------------------+
| ``KEY_NPAGE``     | Next page                                  |
+-------------------+--------------------------------------------+
| ``KEY_PPAGE``     | Previous page                              |
+-------------------+--------------------------------------------+
| ``KEY_STAB``      | Set tab                                    |
+-------------------+--------------------------------------------+
| ``KEY_CTAB``      | Clear tab                                  |
+-------------------+--------------------------------------------+
| ``KEY_CATAB``     | Clear all tabs                             |
+-------------------+--------------------------------------------+
| ``KEY_ENTER``     | Enter or send (unreliable)                 |
+-------------------+--------------------------------------------+
| ``KEY_SRESET``    | Soft (partial) reset (unreliable)          |
+-------------------+--------------------------------------------+
| ``KEY_RESET``     | Reset or hard reset (unreliable)           |
+-------------------+--------------------------------------------+
| ``KEY_PRINT``     | Print                                      |
+-------------------+--------------------------------------------+
| ``KEY_LL``        | Home down or bottom (lower left)           |
+-------------------+--------------------------------------------+
| ``KEY_A1``        | Upper left of keypad                       |
+-------------------+--------------------------------------------+
| ``KEY_A3``        | Upper right of keypad                      |
+-------------------+--------------------------------------------+
| ``KEY_B2``        | Center of keypad                           |
+-------------------+--------------------------------------------+
| ``KEY_C1``        | Lower left of keypad                       |
+-------------------+--------------------------------------------+
| ``KEY_C3``        | Lower right of keypad                      |
+-------------------+--------------------------------------------+
| ``KEY_BTAB``      | Back tab                                   |
+-------------------+--------------------------------------------+
| ``KEY_BEG``       | Beg (beginning)                            |
+-------------------+--------------------------------------------+
| ``KEY_CANCEL``    | Cancel                                     |
+-------------------+--------------------------------------------+
| ``KEY_CLOSE``     | Close                                      |
+-------------------+--------------------------------------------+
| ``KEY_COMMAND``   | Cmd (command)                              |
+-------------------+--------------------------------------------+
| ``KEY_COPY``      | Copy                                       |
+-------------------+--------------------------------------------+
| ``KEY_CREATE``    | Create                                     |
+-------------------+--------------------------------------------+
| ``KEY_END``       | End                                        |
+-------------------+--------------------------------------------+
| ``KEY_EXIT``      | Exit                                       |
+-------------------+--------------------------------------------+
| ``KEY_FIND``      | Find                                       |
+-------------------+--------------------------------------------+
| ``KEY_HELP``      | Help                                       |
+-------------------+--------------------------------------------+
| ``KEY_MARK``      | Mark                                       |
+-------------------+--------------------------------------------+
| ``KEY_MESSAGE``   | Message                                    |
+-------------------+--------------------------------------------+
| ``KEY_MOVE``      | Move                                       |
+-------------------+--------------------------------------------+
| ``KEY_NEXT``      | Next                                       |
+-------------------+--------------------------------------------+
| ``KEY_OPEN``      | Open                                       |
+-------------------+--------------------------------------------+
| ``KEY_OPTIONS``   | Options                                    |
+-------------------+--------------------------------------------+
| ``KEY_PREVIOUS``  | Prev (previous)                            |
+-------------------+--------------------------------------------+
| ``KEY_REDO``      | Redo                                       |
+-------------------+--------------------------------------------+
| ``KEY_REFERENCE`` | Ref (reference)                            |
+-------------------+--------------------------------------------+
| ``KEY_REFRESH``   | Refresh                                    |
+-------------------+--------------------------------------------+
| ``KEY_REPLACE``   | Replace                                    |
+-------------------+--------------------------------------------+
| ``KEY_RESTART``   | Restart                                    |
+-------------------+--------------------------------------------+
| ``KEY_RESUME``    | Resume                                     |
+-------------------+--------------------------------------------+
| ``KEY_SAVE``      | Save                                       |
+-------------------+--------------------------------------------+
| ``KEY_SBEG``      | Shifted Beg (beginning)                    |
+-------------------+--------------------------------------------+
| ``KEY_SCANCEL``   | Shifted Cancel                             |
+-------------------+--------------------------------------------+
| ``KEY_SCOMMAND``  | Shifted Command                            |
+-------------------+--------------------------------------------+
| ``KEY_SCOPY``     | Shifted Copy                               |
+-------------------+--------------------------------------------+
| ``KEY_SCREATE``   | Shifted Create                             |
+-------------------+--------------------------------------------+
| ``KEY_SDC``       | Shifted Delete char                        |
+-------------------+--------------------------------------------+
| ``KEY_SDL``       | Shifted Delete line                        |
+-------------------+--------------------------------------------+
| ``KEY_SELECT``    | Select                                     |
+-------------------+--------------------------------------------+
| ``KEY_SEND``      | Shifted End                                |
+-------------------+--------------------------------------------+
| ``KEY_SEOL``      | Shifted Clear line                         |
+-------------------+--------------------------------------------+
| ``KEY_SEXIT``     | Shifted Exit                               |
+-------------------+--------------------------------------------+
| ``KEY_SFIND``     | Shifted Find                               |
+-------------------+--------------------------------------------+
| ``KEY_SHELP``     | Shifted Help                               |
+-------------------+--------------------------------------------+
| ``KEY_SHOME``     | Shifted Home                               |
+-------------------+--------------------------------------------+
| ``KEY_SIC``       | Shifted Input                              |
+-------------------+--------------------------------------------+
| ``KEY_SLEFT``     | Shifted Left arrow                         |
+-------------------+--------------------------------------------+
| ``KEY_SMESSAGE``  | Shifted Message                            |
+-------------------+--------------------------------------------+
| ``KEY_SMOVE``     | Shifted Move                               |
+-------------------+--------------------------------------------+
| ``KEY_SNEXT``     | Shifted Next                               |
+-------------------+--------------------------------------------+
| ``KEY_SOPTIONS``  | Shifted Options                            |
+-------------------+--------------------------------------------+
| ``KEY_SPREVIOUS`` | Shifted Prev                               |
+-------------------+--------------------------------------------+
| ``KEY_SPRINT``    | Shifted Print                              |
+-------------------+--------------------------------------------+
| ``KEY_SREDO``     | Shifted Redo                               |
+-------------------+--------------------------------------------+
| ``KEY_SREPLACE``  | Shifted Replace                            |
+-------------------+--------------------------------------------+
| ``KEY_SRIGHT``    | Shifted Right arrow                        |
+-------------------+--------------------------------------------+
| ``KEY_SRSUME``    | Shifted Resume                             |
+-------------------+--------------------------------------------+
| ``KEY_SSAVE``     | Shifted Save                               |
+-------------------+--------------------------------------------+
| ``KEY_SSUSPEND``  | Shifted Suspend                            |
+-------------------+--------------------------------------------+
| ``KEY_SUNDO``     | Shifted Undo                               |
+-------------------+--------------------------------------------+
| ``KEY_SUSPEND``   | Suspend                                    |
+-------------------+--------------------------------------------+
| ``KEY_UNDO``      | Undo                                       |
+-------------------+--------------------------------------------+
| ``KEY_MOUSE``     | Mouse event has occurred                   |
+-------------------+--------------------------------------------+
| ``KEY_RESIZE``    | Terminal resize event                      |
+-------------------+--------------------------------------------+
| ``KEY_MAX``       | Maximum key value                          |
+-------------------+--------------------------------------------+

On VT100s and their software emulations, such as X terminal emulators, there are
normally at least four function keys (:const:`KEY_F1`, :const:`KEY_F2`,
:const:`KEY_F3`, :const:`KEY_F4`) available, and the arrow keys mapped to
:const:`KEY_UP`, :const:`KEY_DOWN`, :const:`KEY_LEFT` and :const:`KEY_RIGHT` in
the obvious way.  If your machine has a PC keyboard, it is safe to expect arrow
keys and twelve function keys (older PC keyboards may have only ten function
keys); also, the following keypad mappings are standard:

+------------------+-----------+
| Keycap           | Constant  |
+==================+===========+
| :kbd:`Insert`    | KEY_IC    |
+------------------+-----------+
| :kbd:`Delete`    | KEY_DC    |
+------------------+-----------+
| :kbd:`Home`      | KEY_HOME  |
+------------------+-----------+
| :kbd:`End`       | KEY_END   |
+------------------+-----------+
| :kbd:`Page Up`   | KEY_PPAGE |
+------------------+-----------+
| :kbd:`Page Down` | KEY_NPAGE |
+------------------+-----------+

The following table lists characters from the alternate character set. These are
inherited from the VT100 terminal, and will generally be  available on software
emulations such as X terminals.  When there is no graphic available, curses
falls back on a crude printable ASCII approximation.

.. note::

   These are available only after :func:`initscr` has  been called.

+------------------+------------------------------------------+
| ACS code         | Meaning                                  |
+==================+==========================================+
| ``ACS_BBSS``     | alternate name for upper right corner    |
+------------------+------------------------------------------+
| ``ACS_BLOCK``    | solid square block                       |
+------------------+------------------------------------------+
| ``ACS_BOARD``    | board of squares                         |
+------------------+------------------------------------------+
| ``ACS_BSBS``     | alternate name for horizontal line       |
+------------------+------------------------------------------+
| ``ACS_BSSB``     | alternate name for upper left corner     |
+------------------+------------------------------------------+
| ``ACS_BSSS``     | alternate name for top tee               |
+------------------+------------------------------------------+
| ``ACS_BTEE``     | bottom tee                               |
+------------------+------------------------------------------+
| ``ACS_BULLET``   | bullet                                   |
+------------------+------------------------------------------+
| ``ACS_CKBOARD``  | checker board (stipple)                  |
+------------------+------------------------------------------+
| ``ACS_DARROW``   | arrow pointing down                      |
+------------------+------------------------------------------+
| ``ACS_DEGREE``   | degree symbol                            |
+------------------+------------------------------------------+
| ``ACS_DIAMOND``  | diamond                                  |
+------------------+------------------------------------------+
| ``ACS_GEQUAL``   | greater-than-or-equal-to                 |
+------------------+------------------------------------------+
| ``ACS_HLINE``    | horizontal line                          |
+------------------+------------------------------------------+
| ``ACS_LANTERN``  | lantern symbol                           |
+------------------+------------------------------------------+
| ``ACS_LARROW``   | left arrow                               |
+------------------+------------------------------------------+
| ``ACS_LEQUAL``   | less-than-or-equal-to                    |
+------------------+------------------------------------------+
| ``ACS_LLCORNER`` | lower left-hand corner                   |
+------------------+------------------------------------------+
| ``ACS_LRCORNER`` | lower right-hand corner                  |
+------------------+------------------------------------------+
| ``ACS_LTEE``     | left tee                                 |
+------------------+------------------------------------------+
| ``ACS_NEQUAL``   | not-equal sign                           |
+------------------+------------------------------------------+
| ``ACS_PI``       | letter pi                                |
+------------------+------------------------------------------+
| ``ACS_PLMINUS``  | plus-or-minus sign                       |
+------------------+------------------------------------------+
| ``ACS_PLUS``     | big plus sign                            |
+------------------+------------------------------------------+
| ``ACS_RARROW``   | right arrow                              |
+------------------+------------------------------------------+
| ``ACS_RTEE``     | right tee                                |
+------------------+------------------------------------------+
| ``ACS_S1``       | scan line 1                              |
+------------------+------------------------------------------+
| ``ACS_S3``       | scan line 3                              |
+------------------+------------------------------------------+
| ``ACS_S7``       | scan line 7                              |
+------------------+------------------------------------------+
| ``ACS_S9``       | scan line 9                              |
+------------------+------------------------------------------+
| ``ACS_SBBS``     | alternate name for lower right corner    |
+------------------+------------------------------------------+
| ``ACS_SBSB``     | alternate name for vertical line         |
+------------------+------------------------------------------+
| ``ACS_SBSS``     | alternate name for right tee             |
+------------------+------------------------------------------+
| ``ACS_SSBB``     | alternate name for lower left corner     |
+------------------+------------------------------------------+
| ``ACS_SSBS``     | alternate name for bottom tee            |
+------------------+------------------------------------------+
| ``ACS_SSSB``     | alternate name for left tee              |
+------------------+------------------------------------------+
| ``ACS_SSSS``     | alternate name for crossover or big plus |
+------------------+------------------------------------------+
| ``ACS_STERLING`` | pound sterling                           |
+------------------+------------------------------------------+
| ``ACS_TTEE``     | top tee                                  |
+------------------+------------------------------------------+
| ``ACS_UARROW``   | up arrow                                 |
+------------------+------------------------------------------+
| ``ACS_ULCORNER`` | upper left corner                        |
+------------------+------------------------------------------+
| ``ACS_URCORNER`` | upper right corner                       |
+------------------+------------------------------------------+
| ``ACS_VLINE``    | vertical line                            |
+------------------+------------------------------------------+

The following table lists the predefined colors:

+-------------------+----------------------------+
| Constant          | Color                      |
+===================+============================+
| ``COLOR_BLACK``   | Black                      |
+-------------------+----------------------------+
| ``COLOR_BLUE``    | Blue                       |
+-------------------+----------------------------+
| ``COLOR_CYAN``    | Cyan (light greenish blue) |
+-------------------+----------------------------+
| ``COLOR_GREEN``   | Green                      |
+-------------------+----------------------------+
| ``COLOR_MAGENTA`` | Magenta (purplish red)     |
+-------------------+----------------------------+
| ``COLOR_RED``     | Red                        |
+-------------------+----------------------------+
| ``COLOR_WHITE``   | White                      |
+-------------------+----------------------------+
| ``COLOR_YELLOW``  | Yellow                     |
+-------------------+----------------------------+


:mod:`curses.textpad` --- Text input widget for curses programs
===============================================================

.. module:: curses.textpad
   :synopsis: Emacs-like input editing in a curses window.
.. moduleauthor:: Eric Raymond <esr@thyrsus.com>
.. sectionauthor:: Eric Raymond <esr@thyrsus.com>


.. versionadded:: 1.6

The :mod:`curses.textpad` module provides a :class:`Textbox` class that handles
elementary text editing in a curses window, supporting a set of keybindings
resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x,
FrameMaker, and many other programs).  The module also provides a
rectangle-drawing function useful for framing text boxes or for other purposes.

The module :mod:`curses.textpad` defines the following function:


.. function:: rectangle(win, uly, ulx, lry, lrx)

   Draw a rectangle.  The first argument must be a window object; the remaining
   arguments are coordinates relative to that window.  The second and third
   arguments are the y and x coordinates of the upper left hand corner of the
   rectangle to be drawn; the fourth and fifth arguments are the y and x
   coordinates of the lower right hand corner. The rectangle will be drawn using
   VT100/IBM PC forms characters on terminals that make this possible (including
   xterm and most other software terminal emulators).  Otherwise it will be drawn
   with ASCII  dashes, vertical bars, and plus signs.


.. _curses-textpad-objects:

Textbox objects
---------------

You can instantiate a :class:`Textbox` object as follows:


.. class:: Textbox(win)

   Return a textbox widget object.  The *win* argument should be a curses
   :class:`WindowObject` in which the textbox is to be contained. The edit cursor
   of the textbox is initially located at the upper left hand corner of the
   containing window, with coordinates ``(0, 0)``. The instance's
   :attr:`stripspaces` flag is initially on.

   :class:`Textbox` objects have the following methods:


   .. method:: edit([validator])

      This is the entry point you will normally use.  It accepts editing
      keystrokes until one of the termination keystrokes is entered.  If
      *validator* is supplied, it must be a function.  It will be called for
      each keystroke entered with the keystroke as a parameter; command dispatch
      is done on the result. This method returns the window contents as a
      string; whether blanks in the window are included is affected by the
      :attr:`stripspaces` attribute.


   .. method:: do_command(ch)

      Process a single command keystroke.  Here are the supported special
      keystrokes:

      +------------------+-------------------------------------------+
      | Keystroke        | Action                                    |
      +==================+===========================================+
      | :kbd:`Control-A` | Go to left edge of window.                |
      +------------------+-------------------------------------------+
      | :kbd:`Control-B` | Cursor left, wrapping to previous line if |
      |                  | appropriate.                              |
      +------------------+-------------------------------------------+
      | :kbd:`Control-D` | Delete character under cursor.            |
      +------------------+-------------------------------------------+
      | :kbd:`Control-E` | Go to right edge (stripspaces off) or end |
      |                  | of line (stripspaces on).                 |
      +------------------+-------------------------------------------+
      | :kbd:`Control-F` | Cursor right, wrapping to next line when  |
      |                  | appropriate.                              |
      +------------------+-------------------------------------------+
      | :kbd:`Control-G` | Terminate, returning the window contents. |
      +------------------+-------------------------------------------+
      | :kbd:`Control-H` | Delete character backward.                |
      +------------------+-------------------------------------------+
      | :kbd:`Control-J` | Terminate if the window is 1 line,        |
      |                  | otherwise insert newline.                 |
      +------------------+-------------------------------------------+
      | :kbd:`Control-K` | If line is blank, delete it, otherwise    |
      |                  | clear to end of line.                     |
      +------------------+-------------------------------------------+
      | :kbd:`Control-L` | Refresh screen.                           |
      +------------------+-------------------------------------------+
      | :kbd:`Control-N` | Cursor down; move down one line.          |
      +------------------+-------------------------------------------+
      | :kbd:`Control-O` | Insert a blank line at cursor location.   |
      +------------------+-------------------------------------------+
      | :kbd:`Control-P` | Cursor up; move up one line.              |
      +------------------+-------------------------------------------+

      Move operations do nothing if the cursor is at an edge where the movement
      is not possible.  The following synonyms are supported where possible:

      +------------------------+------------------+
      | Constant               | Keystroke        |
      +========================+==================+
      | :const:`KEY_LEFT`      | :kbd:`Control-B` |
      +------------------------+------------------+
      | :const:`KEY_RIGHT`     | :kbd:`Control-F` |
      +------------------------+------------------+
      | :const:`KEY_UP`        | :kbd:`Control-P` |
      +------------------------+------------------+
      | :const:`KEY_DOWN`      | :kbd:`Control-N` |
      +------------------------+------------------+
      | :const:`KEY_BACKSPACE` | :kbd:`Control-h` |
      +------------------------+------------------+

      All other keystrokes are treated as a command to insert the given
      character and move right (with line wrapping).


   .. method:: gather()

      Return the window contents as a string; whether blanks in the
      window are included is affected by the :attr:`stripspaces` member.


   .. attribute:: stripspaces

      This attribute is a flag which controls the interpretation of blanks in
      the window.  When it is on, trailing blanks on each line are ignored; any
      cursor motion that would land the cursor on a trailing blank goes to the
      end of that line instead, and trailing blanks are stripped when the window
      contents are gathered.

PK	%�\�`�::*html/_sources/library/custominterp.rst.txtnu�[���
.. _custominterp:

**************************
Custom Python Interpreters
**************************

The modules described in this chapter allow writing interfaces similar to
Python's interactive interpreter.  If you want a Python interpreter that
supports some special feature in addition to the Python language, you should
look at the :mod:`code` module.  (The :mod:`codeop` module is lower-level, used
to support compiling a possibly-incomplete chunk of Python code.)

The full list of modules described in this chapter is:


.. toctree::

   code.rst
   codeop.rst
PK	%�\���g``'html/_sources/library/datatypes.rst.txtnu�[���
.. _datatypes:

**********
Data Types
**********

The modules described in this chapter provide a variety of specialized data
types such as dates and times, fixed-type arrays, heap queues, synchronized
queues, and sets.

Python also provides some built-in data types, in particular,
:class:`dict`, :class:`list`, :class:`set` (which along with
:class:`frozenset`, replaces the deprecated :mod:`sets` module), and
:class:`tuple`. The :class:`str` class can be used to handle binary data
and 8-bit text, and the :class:`unicode` class to handle Unicode text.

The following modules are documented in this chapter:


.. toctree::

   datetime.rst
   calendar.rst
   collections.rst
   heapq.rst
   bisect.rst
   array.rst
   sets.rst
   sched.rst
   mutex.rst
   queue.rst
   weakref.rst
   userdict.rst
   types.rst
   new.rst
   copy.rst
   pprint.rst
   repr.rst
PK	%�\
�v��#�#&html/_sources/library/datetime.rst.txtnu�[���:mod:`datetime` --- Basic date and time types
=============================================

.. module:: datetime
   :synopsis: Basic date and time types.
.. moduleauthor:: Tim Peters <tim@zope.com>
.. sectionauthor:: Tim Peters <tim@zope.com>
.. sectionauthor:: A.M. Kuchling <amk@amk.ca>

.. XXX what order should the types be discussed in?

.. versionadded:: 2.3

The :mod:`datetime` module supplies classes for manipulating dates and times in
both simple and complex ways.  While date and time arithmetic is supported, the
focus of the implementation is on efficient attribute extraction for output
formatting and manipulation. For related functionality, see also the
:mod:`time` and :mod:`calendar` modules.

There are two kinds of date and time objects: "naive" and "aware".

An aware object has sufficient knowledge of applicable algorithmic and
political time adjustments, such as time zone and daylight saving time
information, to locate itself relative to other aware objects.  An aware object
is used to represent a specific moment in time that is not open to
interpretation [#]_.

A naive object does not contain enough information to unambiguously locate
itself relative to other date/time objects.  Whether a naive object represents
Coordinated Universal Time (UTC), local time, or time in some other timezone is
purely up to the program, just like it's up to the program whether a particular
number represents metres, miles, or mass.  Naive objects are easy to understand
and to work with, at the cost of ignoring some aspects of reality.

For applications requiring aware objects, :class:`.datetime` and :class:`.time`
objects have an optional time zone information attribute, :attr:`!tzinfo`, that
can be set to an instance of a subclass of the abstract :class:`tzinfo` class.
These :class:`tzinfo` objects capture information about the offset from UTC
time, the time zone name, and whether Daylight Saving Time is in effect.  Note
that no concrete :class:`tzinfo` classes are supplied by the :mod:`datetime`
module.  Supporting timezones at whatever level of detail is required is up to
the application.  The rules for time adjustment across the world are more
political than rational, and there is no standard suitable for every
application.

The :mod:`datetime` module exports the following constants:

.. data:: MINYEAR

   The smallest year number allowed in a :class:`date` or :class:`.datetime` object.
   :const:`MINYEAR` is ``1``.


.. data:: MAXYEAR

   The largest year number allowed in a :class:`date` or :class:`.datetime` object.
   :const:`MAXYEAR` is ``9999``.


.. seealso::

   Module :mod:`calendar`
      General calendar related functions.

   Module :mod:`time`
      Time access and conversions.


Available Types
---------------

.. class:: date
   :noindex:

   An idealized naive date, assuming the current Gregorian calendar always was, and
   always will be, in effect. Attributes: :attr:`year`, :attr:`month`, and
   :attr:`day`.


.. class:: time
   :noindex:

   An idealized time, independent of any particular day, assuming that every day
   has exactly 24\*60\*60 seconds (there is no notion of "leap seconds" here).
   Attributes: :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
   and :attr:`.tzinfo`.


.. class:: datetime
   :noindex:

   A combination of a date and a time. Attributes: :attr:`year`, :attr:`month`,
   :attr:`day`, :attr:`hour`, :attr:`minute`, :attr:`second`, :attr:`microsecond`,
   and :attr:`.tzinfo`.


.. class:: timedelta
   :noindex:

   A duration expressing the difference between two :class:`date`, :class:`.time`,
   or :class:`.datetime` instances to microsecond resolution.


.. class:: tzinfo
   :noindex:

   An abstract base class for time zone information objects.  These are used by the
   :class:`.datetime` and :class:`.time` classes to provide a customizable notion of
   time adjustment (for example, to account for time zone and/or daylight saving
   time).

Objects of these types are immutable.

Objects of the :class:`date` type are always naive.

An object of type :class:`.time` or :class:`.datetime` may be naive or aware.
A :class:`.datetime` object *d* is aware if ``d.tzinfo`` is not ``None`` and
``d.tzinfo.utcoffset(d)`` does not return ``None``.  If ``d.tzinfo`` is
``None``, or if ``d.tzinfo`` is not ``None`` but ``d.tzinfo.utcoffset(d)``
returns ``None``, *d* is naive.  A :class:`.time` object *t* is aware
if ``t.tzinfo`` is not ``None`` and ``t.tzinfo.utcoffset(None)`` does not return
``None``.  Otherwise, *t* is naive.

The distinction between naive and aware doesn't apply to :class:`timedelta`
objects.

Subclass relationships::

   object
       timedelta
       tzinfo
       time
       date
           datetime


.. _datetime-timedelta:

:class:`timedelta` Objects
--------------------------

A :class:`timedelta` object represents a duration, the difference between two
dates or times.

.. class:: timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

   All arguments are optional and default to ``0``.  Arguments may be ints, longs,
   or floats, and may be positive or negative.

   Only *days*, *seconds* and *microseconds* are stored internally.  Arguments are
   converted to those units:

   * A millisecond is converted to 1000 microseconds.
   * A minute is converted to 60 seconds.
   * An hour is converted to 3600 seconds.
   * A week is converted to 7 days.

   and days, seconds and microseconds are then normalized so that the
   representation is unique, with

   * ``0 <= microseconds < 1000000``
   * ``0 <= seconds < 3600*24`` (the number of seconds in one day)
   * ``-999999999 <= days <= 999999999``

   If any argument is a float and there are fractional microseconds, the fractional
   microseconds left over from all arguments are combined and their sum is rounded
   to the nearest microsecond.  If no argument is a float, the conversion and
   normalization processes are exact (no information is lost).

   If the normalized value of days lies outside the indicated range,
   :exc:`OverflowError` is raised.

   Note that normalization of negative values may be surprising at first. For
   example,

      >>> from datetime import timedelta
      >>> d = timedelta(microseconds=-1)
      >>> (d.days, d.seconds, d.microseconds)
      (-1, 86399, 999999)


Class attributes are:

.. attribute:: timedelta.min

   The most negative :class:`timedelta` object, ``timedelta(-999999999)``.


.. attribute:: timedelta.max

   The most positive :class:`timedelta` object, ``timedelta(days=999999999,
   hours=23, minutes=59, seconds=59, microseconds=999999)``.


.. attribute:: timedelta.resolution

   The smallest possible difference between non-equal :class:`timedelta` objects,
   ``timedelta(microseconds=1)``.

Note that, because of normalization, ``timedelta.max`` > ``-timedelta.min``.
``-timedelta.max`` is not representable as a :class:`timedelta` object.

Instance attributes (read-only):

+------------------+--------------------------------------------+
| Attribute        | Value                                      |
+==================+============================================+
| ``days``         | Between -999999999 and 999999999 inclusive |
+------------------+--------------------------------------------+
| ``seconds``      | Between 0 and 86399 inclusive              |
+------------------+--------------------------------------------+
| ``microseconds`` | Between 0 and 999999 inclusive             |
+------------------+--------------------------------------------+

Supported operations:

.. XXX this table is too wide!

+--------------------------------+-----------------------------------------------+
| Operation                      | Result                                        |
+================================+===============================================+
| ``t1 = t2 + t3``               | Sum of *t2* and *t3*. Afterwards *t1*-*t2* == |
|                                | *t3* and *t1*-*t3* == *t2* are true. (1)      |
+--------------------------------+-----------------------------------------------+
| ``t1 = t2 - t3``               | Difference of *t2* and *t3*. Afterwards *t1*  |
|                                | == *t2* - *t3* and *t2* == *t1* + *t3* are    |
|                                | true. (1)                                     |
+--------------------------------+-----------------------------------------------+
| ``t1 = t2 * i or t1 = i * t2`` | Delta multiplied by an integer or long.       |
|                                | Afterwards *t1* // i == *t2* is true,         |
|                                | provided ``i != 0``.                          |
+--------------------------------+-----------------------------------------------+
|                                | In general, *t1* \* i == *t1* \* (i-1) + *t1* |
|                                | is true. (1)                                  |
+--------------------------------+-----------------------------------------------+
| ``t1 = t2 // i``               | The floor is computed and the remainder (if   |
|                                | any) is thrown away. (3)                      |
+--------------------------------+-----------------------------------------------+
| ``+t1``                        | Returns a :class:`timedelta` object with the  |
|                                | same value. (2)                               |
+--------------------------------+-----------------------------------------------+
| ``-t1``                        | equivalent to :class:`timedelta`\             |
|                                | (-*t1.days*, -*t1.seconds*,                   |
|                                | -*t1.microseconds*), and to *t1*\* -1. (1)(4) |
+--------------------------------+-----------------------------------------------+
| ``abs(t)``                     | equivalent to +\ *t* when ``t.days >= 0``, and|
|                                | to -*t* when ``t.days < 0``. (2)              |
+--------------------------------+-----------------------------------------------+
| ``str(t)``                     | Returns a string in the form                  |
|                                | ``[D day[s], ][H]H:MM:SS[.UUUUUU]``, where D  |
|                                | is negative for negative ``t``. (5)           |
+--------------------------------+-----------------------------------------------+
| ``repr(t)``                    | Returns a string in the form                  |
|                                | ``datetime.timedelta(D[, S[, U]])``, where D  |
|                                | is negative for negative ``t``. (5)           |
+--------------------------------+-----------------------------------------------+

Notes:

(1)
   This is exact, but may overflow.

(2)
   This is exact, and cannot overflow.

(3)
   Division by 0 raises :exc:`ZeroDivisionError`.

(4)
   -*timedelta.max* is not representable as a :class:`timedelta` object.

(5)
  String representations of :class:`timedelta` objects are normalized
  similarly to their internal representation.  This leads to somewhat
  unusual results for negative timedeltas.  For example:

  >>> timedelta(hours=-5)
  datetime.timedelta(-1, 68400)
  >>> print(_)
  -1 day, 19:00:00

In addition to the operations listed above :class:`timedelta` objects support
certain additions and subtractions with :class:`date` and :class:`.datetime`
objects (see below).

Comparisons of :class:`timedelta` objects are supported with the
:class:`timedelta` object representing the smaller duration considered to be the
smaller timedelta. In order to stop mixed-type comparisons from falling back to
the default comparison by object address, when a :class:`timedelta` object is
compared to an object of a different type, :exc:`TypeError` is raised unless the
comparison is ``==`` or ``!=``.  The latter cases return :const:`False` or
:const:`True`, respectively.

:class:`timedelta` objects are :term:`hashable` (usable as dictionary keys), support
efficient pickling, and in Boolean contexts, a :class:`timedelta` object is
considered to be true if and only if it isn't equal to ``timedelta(0)``.

Instance methods:

.. method:: timedelta.total_seconds()

   Return the total number of seconds contained in the duration.
   Equivalent to ``(td.microseconds + (td.seconds + td.days * 24 *
   3600) * 10**6) / 10**6`` computed with true division enabled.

   Note that for very large time intervals (greater than 270 years on
   most platforms) this method will lose microsecond accuracy.

   .. versionadded:: 2.7


Example usage:

    >>> from datetime import timedelta
    >>> year = timedelta(days=365)
    >>> another_year = timedelta(weeks=40, days=84, hours=23,
    ...                          minutes=50, seconds=600)  # adds up to 365 days
    >>> year.total_seconds()
    31536000.0
    >>> year == another_year
    True
    >>> ten_years = 10 * year
    >>> ten_years, ten_years.days // 365
    (datetime.timedelta(3650), 10)
    >>> nine_years = ten_years - year
    >>> nine_years, nine_years.days // 365
    (datetime.timedelta(3285), 9)
    >>> three_years = nine_years // 3;
    >>> three_years, three_years.days // 365
    (datetime.timedelta(1095), 3)
    >>> abs(three_years - ten_years) == 2 * three_years + year
    True


.. _datetime-date:

:class:`date` Objects
---------------------

A :class:`date` object represents a date (year, month and day) in an idealized
calendar, the current Gregorian calendar indefinitely extended in both
directions.  January 1 of year 1 is called day number 1, January 2 of year 1 is
called day number 2, and so on.  This matches the definition of the "proleptic
Gregorian" calendar in Dershowitz and Reingold's book Calendrical Calculations,
where it's the base calendar for all computations.  See the book for algorithms
for converting between proleptic Gregorian ordinals and many other calendar
systems.


.. class:: date(year, month, day)

   All arguments are required.  Arguments may be ints or longs, in the following
   ranges:

   * ``MINYEAR <= year <= MAXYEAR``
   * ``1 <= month <= 12``
   * ``1 <= day <= number of days in the given month and year``

   If an argument outside those ranges is given, :exc:`ValueError` is raised.


Other constructors, all class methods:

.. classmethod:: date.today()

   Return the current local date.  This is equivalent to
   ``date.fromtimestamp(time.time())``.


.. classmethod:: date.fromtimestamp(timestamp)

   Return the local date corresponding to the POSIX timestamp, such as is returned
   by :func:`time.time`.  This may raise :exc:`ValueError`, if the timestamp is out
   of the range of values supported by the platform C :c:func:`localtime` function.
   It's common for this to be restricted to years from 1970 through 2038.  Note
   that on non-POSIX systems that include leap seconds in their notion of a
   timestamp, leap seconds are ignored by :meth:`fromtimestamp`.


.. classmethod:: date.fromordinal(ordinal)

   Return the date corresponding to the proleptic Gregorian ordinal, where January
   1 of year 1 has ordinal 1.  :exc:`ValueError` is raised unless ``1 <= ordinal <=
   date.max.toordinal()``. For any date *d*, ``date.fromordinal(d.toordinal()) ==
   d``.


Class attributes:

.. attribute:: date.min

   The earliest representable date, ``date(MINYEAR, 1, 1)``.


.. attribute:: date.max

   The latest representable date, ``date(MAXYEAR, 12, 31)``.


.. attribute:: date.resolution

   The smallest possible difference between non-equal date objects,
   ``timedelta(days=1)``.


Instance attributes (read-only):

.. attribute:: date.year

   Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.


.. attribute:: date.month

   Between 1 and 12 inclusive.


.. attribute:: date.day

   Between 1 and the number of days in the given month of the given year.


Supported operations:

+-------------------------------+----------------------------------------------+
| Operation                     | Result                                       |
+===============================+==============================================+
| ``date2 = date1 + timedelta`` | *date2* is ``timedelta.days`` days removed   |
|                               | from *date1*.  (1)                           |
+-------------------------------+----------------------------------------------+
| ``date2 = date1 - timedelta`` | Computes *date2* such that ``date2 +         |
|                               | timedelta == date1``. (2)                    |
+-------------------------------+----------------------------------------------+
| ``timedelta = date1 - date2`` | \(3)                                         |
+-------------------------------+----------------------------------------------+
| ``date1 < date2``             | *date1* is considered less than *date2* when |
|                               | *date1* precedes *date2* in time. (4)        |
+-------------------------------+----------------------------------------------+

Notes:

(1)
   *date2* is moved forward in time if ``timedelta.days > 0``, or backward if
   ``timedelta.days < 0``.  Afterward ``date2 - date1 == timedelta.days``.
   ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.
   :exc:`OverflowError` is raised if ``date2.year`` would be smaller than
   :const:`MINYEAR` or larger than :const:`MAXYEAR`.

(2)
   This isn't quite equivalent to date1 + (-timedelta), because -timedelta in
   isolation can overflow in cases where date1 - timedelta does not.
   ``timedelta.seconds`` and ``timedelta.microseconds`` are ignored.

(3)
   This is exact, and cannot overflow.  timedelta.seconds and
   timedelta.microseconds are 0, and date2 + timedelta == date1 after.

(4)
   In other words, ``date1 < date2`` if and only if ``date1.toordinal() <
   date2.toordinal()``. In order to stop comparison from falling back to the
   default scheme of comparing object addresses, date comparison normally raises
   :exc:`TypeError` if the other comparand isn't also a :class:`date` object.
   However, ``NotImplemented`` is returned instead if the other comparand has a
   :meth:`timetuple` attribute.  This hook gives other kinds of date objects a
   chance at implementing mixed-type comparison. If not, when a :class:`date`
   object is compared to an object of a different type, :exc:`TypeError` is raised
   unless the comparison is ``==`` or ``!=``.  The latter cases return
   :const:`False` or :const:`True`, respectively.

Dates can be used as dictionary keys. In Boolean contexts, all :class:`date`
objects are considered to be true.

Instance methods:

.. method:: date.replace(year, month, day)

   Return a date with the same value, except for those parameters given new
   values by whichever keyword arguments are specified.  For example, if ``d ==
   date(2002, 12, 31)``, then ``d.replace(day=26) == date(2002, 12, 26)``.


.. method:: date.timetuple()

   Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
   The hours, minutes and seconds are 0, and the DST flag is -1. ``d.timetuple()``
   is equivalent to ``time.struct_time((d.year, d.month, d.day, 0, 0, 0,
   d.weekday(), yday, -1))``, where ``yday = d.toordinal() - date(d.year, 1,
   1).toordinal() + 1`` is the day number within the current year starting with
   ``1`` for January 1st.


.. method:: date.toordinal()

   Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
   has ordinal 1.  For any :class:`date` object *d*,
   ``date.fromordinal(d.toordinal()) == d``.


.. method:: date.weekday()

   Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
   For example, ``date(2002, 12, 4).weekday() == 2``, a Wednesday. See also
   :meth:`isoweekday`.


.. method:: date.isoweekday()

   Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
   For example, ``date(2002, 12, 4).isoweekday() == 3``, a Wednesday. See also
   :meth:`weekday`, :meth:`isocalendar`.


.. method:: date.isocalendar()

   Return a 3-tuple, (ISO year, ISO week number, ISO weekday).

   The ISO calendar is a widely used variant of the Gregorian calendar. See
   https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm for a good
   explanation.

   The ISO year consists of 52 or 53 full weeks, and where a week starts on a
   Monday and ends on a Sunday.  The first week of an ISO year is the first
   (Gregorian) calendar week of a year containing a Thursday. This is called week
   number 1, and the ISO year of that Thursday is the same as its Gregorian year.

   For example, 2004 begins on a Thursday, so the first week of ISO year 2004
   begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
   ``date(2003, 12, 29).isocalendar() == (2004, 1, 1)`` and ``date(2004, 1,
   4).isocalendar() == (2004, 1, 7)``.


.. method:: date.isoformat()

   Return a string representing the date in ISO 8601 format, 'YYYY-MM-DD'.  For
   example, ``date(2002, 12, 4).isoformat() == '2002-12-04'``.


.. method:: date.__str__()

   For a date *d*, ``str(d)`` is equivalent to ``d.isoformat()``.


.. method:: date.ctime()

   Return a string representing the date, for example ``date(2002, 12,
   4).ctime() == 'Wed Dec 4 00:00:00 2002'``. ``d.ctime()`` is equivalent to
   ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the native C
   :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
   :meth:`date.ctime` does not invoke) conforms to the C standard.


.. method:: date.strftime(format)

   Return a string representing the date, controlled by an explicit format string.
   Format codes referring to hours, minutes or seconds will see 0 values. For a
   complete list of formatting directives, see section
   :ref:`strftime-strptime-behavior`.


.. method:: date.__format__(format)

   Same as :meth:`.date.strftime`. This makes it possible to specify a format
   string for a :class:`.date` object when using :meth:`str.format`.
   See section :ref:`strftime-strptime-behavior`.


Example of counting days to an event::

    >>> import time
    >>> from datetime import date
    >>> today = date.today()
    >>> today
    datetime.date(2007, 12, 5)
    >>> today == date.fromtimestamp(time.time())
    True
    >>> my_birthday = date(today.year, 6, 24)
    >>> if my_birthday < today:
    ...     my_birthday = my_birthday.replace(year=today.year + 1)
    >>> my_birthday
    datetime.date(2008, 6, 24)
    >>> time_to_birthday = abs(my_birthday - today)
    >>> time_to_birthday.days
    202

Example of working with :class:`date`:

.. doctest::

    >>> from datetime import date
    >>> d = date.fromordinal(730920) # 730920th day after 1. 1. 0001
    >>> d
    datetime.date(2002, 3, 11)
    >>> t = d.timetuple()
    >>> for i in t:     # doctest: +SKIP
    ...     print i
    2002                # year
    3                   # month
    11                  # day
    0
    0
    0
    0                   # weekday (0 = Monday)
    70                  # 70th day in the year
    -1
    >>> ic = d.isocalendar()
    >>> for i in ic:    # doctest: +SKIP
    ...     print i
    2002                # ISO year
    11                  # ISO week number
    1                   # ISO day number ( 1 = Monday )
    >>> d.isoformat()
    '2002-03-11'
    >>> d.strftime("%d/%m/%y")
    '11/03/02'
    >>> d.strftime("%A %d. %B %Y")
    'Monday 11. March 2002'
    >>> 'The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")
    'The day is 11, the month is March.'


.. _datetime-datetime:

:class:`.datetime` Objects
--------------------------

A :class:`.datetime` object is a single object containing all the information
from a :class:`date` object and a :class:`.time` object.  Like a :class:`date`
object, :class:`.datetime` assumes the current Gregorian calendar extended in
both directions; like a time object, :class:`.datetime` assumes there are exactly
3600\*24 seconds in every day.

Constructor:

.. class:: datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

   The year, month and day arguments are required.  *tzinfo* may be ``None``, or an
   instance of a :class:`tzinfo` subclass.  The remaining arguments may be ints or
   longs, in the following ranges:

   * ``MINYEAR <= year <= MAXYEAR``
   * ``1 <= month <= 12``
   * ``1 <= day <= number of days in the given month and year``
   * ``0 <= hour < 24``
   * ``0 <= minute < 60``
   * ``0 <= second < 60``
   * ``0 <= microsecond < 1000000``

   If an argument outside those ranges is given, :exc:`ValueError` is raised.

Other constructors, all class methods:

.. classmethod:: datetime.today()

   Return the current local datetime, with :attr:`.tzinfo` ``None``. This is
   equivalent to ``datetime.fromtimestamp(time.time())``. See also :meth:`now`,
   :meth:`fromtimestamp`.


.. classmethod:: datetime.now([tz])

   Return the current local date and time.  If optional argument *tz* is ``None``
   or not specified, this is like :meth:`today`, but, if possible, supplies more
   precision than can be gotten from going through a :func:`time.time` timestamp
   (for example, this may be possible on platforms supplying the C
   :c:func:`gettimeofday` function).

   If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
   current date and time are converted to *tz*’s time zone.  In this case the
   result is equivalent to ``tz.fromutc(datetime.utcnow().replace(tzinfo=tz))``.
   See also :meth:`today`, :meth:`utcnow`.


.. classmethod:: datetime.utcnow()

   Return the current UTC date and time, with :attr:`.tzinfo` ``None``. This is like
   :meth:`now`, but returns the current UTC date and time, as a naive
   :class:`.datetime` object. See also :meth:`now`.


.. classmethod:: datetime.fromtimestamp(timestamp[, tz])

   Return the local date and time corresponding to the POSIX timestamp, such as is
   returned by :func:`time.time`. If optional argument *tz* is ``None`` or not
   specified, the timestamp is converted to the platform's local date and time, and
   the returned :class:`.datetime` object is naive.

   If *tz* is not ``None``, it must be an instance of a :class:`tzinfo` subclass, and the
   timestamp is converted to *tz*’s time zone.  In this case the result is
   equivalent to
   ``tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))``.

   :meth:`fromtimestamp` may raise :exc:`ValueError`, if the timestamp is out of
   the range of values supported by the platform C :c:func:`localtime` or
   :c:func:`gmtime` functions.  It's common for this to be restricted to years in
   1970 through 2038. Note that on non-POSIX systems that include leap seconds in
   their notion of a timestamp, leap seconds are ignored by :meth:`fromtimestamp`,
   and then it's possible to have two timestamps differing by a second that yield
   identical :class:`.datetime` objects. See also :meth:`utcfromtimestamp`.


.. classmethod:: datetime.utcfromtimestamp(timestamp)

   Return the UTC :class:`.datetime` corresponding to the POSIX timestamp, with
   :attr:`.tzinfo` ``None``. This may raise :exc:`ValueError`, if the timestamp is
   out of the range of values supported by the platform C :c:func:`gmtime` function.
   It's common for this to be restricted to years in 1970 through 2038. See also
   :meth:`fromtimestamp`.


.. classmethod:: datetime.fromordinal(ordinal)

   Return the :class:`.datetime` corresponding to the proleptic Gregorian ordinal,
   where January 1 of year 1 has ordinal 1. :exc:`ValueError` is raised unless ``1
   <= ordinal <= datetime.max.toordinal()``.  The hour, minute, second and
   microsecond of the result are all 0, and :attr:`.tzinfo` is ``None``.


.. classmethod:: datetime.combine(date, time)

   Return a new :class:`.datetime` object whose date components are equal to the
   given :class:`date` object's, and whose time components and :attr:`.tzinfo`
   attributes are equal to the given :class:`.time` object's. For any
   :class:`.datetime` object *d*,
   ``d == datetime.combine(d.date(), d.timetz())``.  If date is a
   :class:`.datetime` object, its time components and :attr:`.tzinfo` attributes
   are ignored.


.. classmethod:: datetime.strptime(date_string, format)

   Return a :class:`.datetime` corresponding to *date_string*, parsed according to
   *format*.  This is equivalent to ``datetime(*(time.strptime(date_string,
   format)[0:6]))``. :exc:`ValueError` is raised if the date_string and format
   can't be parsed by :func:`time.strptime` or if it returns a value which isn't a
   time tuple. For a complete list of formatting directives, see section
   :ref:`strftime-strptime-behavior`.

   .. versionadded:: 2.5


Class attributes:

.. attribute:: datetime.min

   The earliest representable :class:`.datetime`, ``datetime(MINYEAR, 1, 1,
   tzinfo=None)``.


.. attribute:: datetime.max

   The latest representable :class:`.datetime`, ``datetime(MAXYEAR, 12, 31, 23, 59,
   59, 999999, tzinfo=None)``.


.. attribute:: datetime.resolution

   The smallest possible difference between non-equal :class:`.datetime` objects,
   ``timedelta(microseconds=1)``.


Instance attributes (read-only):

.. attribute:: datetime.year

   Between :const:`MINYEAR` and :const:`MAXYEAR` inclusive.


.. attribute:: datetime.month

   Between 1 and 12 inclusive.


.. attribute:: datetime.day

   Between 1 and the number of days in the given month of the given year.


.. attribute:: datetime.hour

   In ``range(24)``.


.. attribute:: datetime.minute

   In ``range(60)``.


.. attribute:: datetime.second

   In ``range(60)``.


.. attribute:: datetime.microsecond

   In ``range(1000000)``.


.. attribute:: datetime.tzinfo

   The object passed as the *tzinfo* argument to the :class:`.datetime` constructor,
   or ``None`` if none was passed.


Supported operations:

+---------------------------------------+--------------------------------+
| Operation                             | Result                         |
+=======================================+================================+
| ``datetime2 = datetime1 + timedelta`` | \(1)                           |
+---------------------------------------+--------------------------------+
| ``datetime2 = datetime1 - timedelta`` | \(2)                           |
+---------------------------------------+--------------------------------+
| ``timedelta = datetime1 - datetime2`` | \(3)                           |
+---------------------------------------+--------------------------------+
| ``datetime1 < datetime2``             | Compares :class:`.datetime` to |
|                                       | :class:`.datetime`. (4)        |
+---------------------------------------+--------------------------------+

(1)
   datetime2 is a duration of timedelta removed from datetime1, moving forward in
   time if ``timedelta.days`` > 0, or backward if ``timedelta.days`` < 0.  The
   result has the same :attr:`~.datetime.tzinfo` attribute as the input datetime, and
   datetime2 - datetime1 == timedelta after. :exc:`OverflowError` is raised if
   datetime2.year would be smaller than :const:`MINYEAR` or larger than
   :const:`MAXYEAR`. Note that no time zone adjustments are done even if the
   input is an aware object.

(2)
   Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
   addition, the result has the same :attr:`~.datetime.tzinfo` attribute as the input
   datetime, and no time zone adjustments are done even if the input is aware.
   This isn't quite equivalent to datetime1 + (-timedelta), because -timedelta
   in isolation can overflow in cases where datetime1 - timedelta does not.

(3)
   Subtraction of a :class:`.datetime` from a :class:`.datetime` is defined only if
   both operands are naive, or if both are aware.  If one is aware and the other is
   naive, :exc:`TypeError` is raised.

   If both are naive, or both are aware and have the same :attr:`~.datetime.tzinfo` attribute,
   the :attr:`~.datetime.tzinfo` attributes are ignored, and the result is a :class:`timedelta`
   object *t* such that ``datetime2 + t == datetime1``.  No time zone adjustments
   are done in this case.

   If both are aware and have different :attr:`~.datetime.tzinfo` attributes, ``a-b`` acts
   as if *a* and *b* were first converted to naive UTC datetimes first.  The
   result is ``(a.replace(tzinfo=None) - a.utcoffset()) - (b.replace(tzinfo=None)
   - b.utcoffset())`` except that the implementation never overflows.

(4)
   *datetime1* is considered less than *datetime2* when *datetime1* precedes
   *datetime2* in time.

   If one comparand is naive and the other is aware, :exc:`TypeError` is raised.
   If both comparands are aware, and have the same :attr:`~.datetime.tzinfo` attribute, the
   common :attr:`~.datetime.tzinfo` attribute is ignored and the base datetimes are
   compared.  If both comparands are aware and have different :attr:`~.datetime.tzinfo`
   attributes, the comparands are first adjusted by subtracting their UTC
   offsets (obtained from ``self.utcoffset()``).

   .. note::

      In order to stop comparison from falling back to the default scheme of comparing
      object addresses, datetime comparison normally raises :exc:`TypeError` if the
      other comparand isn't also a :class:`.datetime` object.  However,
      ``NotImplemented`` is returned instead if the other comparand has a
      :meth:`timetuple` attribute.  This hook gives other kinds of date objects a
      chance at implementing mixed-type comparison.  If not, when a :class:`.datetime`
      object is compared to an object of a different type, :exc:`TypeError` is raised
      unless the comparison is ``==`` or ``!=``.  The latter cases return
      :const:`False` or :const:`True`, respectively.

:class:`.datetime` objects can be used as dictionary keys. In Boolean contexts,
all :class:`.datetime` objects are considered to be true.

Instance methods:

.. method:: datetime.date()

   Return :class:`date` object with same year, month and day.


.. method:: datetime.time()

   Return :class:`.time` object with same hour, minute, second and microsecond.
   :attr:`.tzinfo` is ``None``.  See also method :meth:`timetz`.


.. method:: datetime.timetz()

   Return :class:`.time` object with same hour, minute, second, microsecond, and
   tzinfo attributes.  See also method :meth:`time`.


.. method:: datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])

   Return a datetime with the same attributes, except for those attributes given
   new values by whichever keyword arguments are specified.  Note that
   ``tzinfo=None`` can be specified to create a naive datetime from an aware
   datetime with no conversion of date and time data.


.. method:: datetime.astimezone(tz)

   Return a :class:`.datetime` object with new :attr:`.tzinfo` attribute *tz*,
   adjusting the date and time data so the result is the same UTC time as
   *self*, but in *tz*'s local time.

   *tz* must be an instance of a :class:`tzinfo` subclass, and its
   :meth:`utcoffset` and :meth:`dst` methods must not return ``None``.  *self* must
   be aware (``self.tzinfo`` must not be ``None``, and ``self.utcoffset()`` must
   not return ``None``).

   If ``self.tzinfo`` is *tz*, ``self.astimezone(tz)`` is equal to *self*:  no
   adjustment of date or time data is performed. Else the result is local
   time in time zone *tz*, representing the same UTC time as *self*:  after
   ``astz = dt.astimezone(tz)``, ``astz - astz.utcoffset()`` will usually have
   the same date and time data as ``dt - dt.utcoffset()``. The discussion
   of class :class:`tzinfo` explains the cases at Daylight Saving Time transition
   boundaries where this cannot be achieved (an issue only if *tz* models both
   standard and daylight time).

   If you merely want to attach a time zone object *tz* to a datetime *dt* without
   adjustment of date and time data, use ``dt.replace(tzinfo=tz)``.  If you
   merely want to remove the time zone object from an aware datetime *dt* without
   conversion of date and time data, use ``dt.replace(tzinfo=None)``.

   Note that the default :meth:`tzinfo.fromutc` method can be overridden in a
   :class:`tzinfo` subclass to affect the result returned by :meth:`astimezone`.
   Ignoring error cases, :meth:`astimezone` acts like::

      def astimezone(self, tz):
          if self.tzinfo is tz:
              return self
          # Convert self to UTC, and attach the new time zone object.
          utc = (self - self.utcoffset()).replace(tzinfo=tz)
          # Convert from UTC to tz's local time.
          return tz.fromutc(utc)


.. method:: datetime.utcoffset()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.utcoffset(self)``, and raises an exception if the latter doesn't
   return ``None``, or a :class:`timedelta` object representing a whole number of
   minutes with magnitude less than one day.


.. method:: datetime.dst()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.dst(self)``, and raises an exception if the latter doesn't return
   ``None``, or a :class:`timedelta` object representing a whole number of minutes
   with magnitude less than one day.


.. method:: datetime.tzname()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.tzname(self)``, raises an exception if the latter doesn't return
   ``None`` or a string object,


.. method:: datetime.timetuple()

   Return a :class:`time.struct_time` such as returned by :func:`time.localtime`.
   ``d.timetuple()`` is equivalent to ``time.struct_time((d.year, d.month, d.day,
   d.hour, d.minute, d.second, d.weekday(), yday, dst))``, where ``yday =
   d.toordinal() - date(d.year, 1, 1).toordinal() + 1`` is the day number within
   the current year starting with ``1`` for January 1st. The :attr:`tm_isdst` flag
   of the result is set according to the :meth:`dst` method: :attr:`.tzinfo` is
   ``None`` or :meth:`dst` returns ``None``, :attr:`tm_isdst` is set to ``-1``;
   else if :meth:`dst` returns a non-zero value, :attr:`tm_isdst` is set to ``1``;
   else :attr:`tm_isdst` is set to ``0``.


.. method:: datetime.utctimetuple()

   If :class:`.datetime` instance *d* is naive, this is the same as
   ``d.timetuple()`` except that :attr:`tm_isdst` is forced to 0 regardless of what
   ``d.dst()`` returns.  DST is never in effect for a UTC time.

   If *d* is aware, *d* is normalized to UTC time, by subtracting
   ``d.utcoffset()``, and a :class:`time.struct_time` for the normalized time is
   returned.  :attr:`tm_isdst` is forced to 0. Note that the result's
   :attr:`tm_year` member may be :const:`MINYEAR`\ -1 or :const:`MAXYEAR`\ +1, if
   *d*.year was ``MINYEAR`` or ``MAXYEAR`` and UTC adjustment spills over a year
   boundary.


.. method:: datetime.toordinal()

   Return the proleptic Gregorian ordinal of the date.  The same as
   ``self.date().toordinal()``.


.. method:: datetime.weekday()

   Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
   The same as ``self.date().weekday()``. See also :meth:`isoweekday`.


.. method:: datetime.isoweekday()

   Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
   The same as ``self.date().isoweekday()``. See also :meth:`weekday`,
   :meth:`isocalendar`.


.. method:: datetime.isocalendar()

   Return a 3-tuple, (ISO year, ISO week number, ISO weekday).  The same as
   ``self.date().isocalendar()``.


.. method:: datetime.isoformat([sep])

   Return a string representing the date and time in ISO 8601 format,
   YYYY-MM-DDTHH:MM:SS.mmmmmm or, if :attr:`microsecond` is 0,
   YYYY-MM-DDTHH:MM:SS

   If :meth:`utcoffset` does not return ``None``, a 6-character string is
   appended, giving the UTC offset in (signed) hours and minutes:
   YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if :attr:`microsecond` is 0
   YYYY-MM-DDTHH:MM:SS+HH:MM

   The optional argument *sep* (default ``'T'``) is a one-character separator,
   placed between the date and time portions of the result.  For example,

      >>> from datetime import tzinfo, timedelta, datetime
      >>> class TZ(tzinfo):
      ...     def utcoffset(self, dt): return timedelta(minutes=-399)
      ...
      >>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
      '2002-12-25 00:00:00-06:39'


.. method:: datetime.__str__()

   For a :class:`.datetime` instance *d*, ``str(d)`` is equivalent to
   ``d.isoformat(' ')``.


.. method:: datetime.ctime()

   Return a string representing the date and time, for example ``datetime(2002, 12,
   4, 20, 30, 40).ctime() == 'Wed Dec  4 20:30:40 2002'``. ``d.ctime()`` is
   equivalent to ``time.ctime(time.mktime(d.timetuple()))`` on platforms where the
   native C :c:func:`ctime` function (which :func:`time.ctime` invokes, but which
   :meth:`datetime.ctime` does not invoke) conforms to the C standard.


.. method:: datetime.strftime(format)

   Return a string representing the date and time, controlled by an explicit format
   string.  For a complete list of formatting directives, see section
   :ref:`strftime-strptime-behavior`.


.. method:: datetime.__format__(format)

   Same as :meth:`.datetime.strftime`.  This makes it possible to specify a format
   string for a :class:`.datetime` object when using :meth:`str.format`.
   See section :ref:`strftime-strptime-behavior`.


Examples of working with datetime objects:

.. doctest::

    >>> from datetime import datetime, date, time
    >>> # Using datetime.combine()
    >>> d = date(2005, 7, 14)
    >>> t = time(12, 30)
    >>> datetime.combine(d, t)
    datetime.datetime(2005, 7, 14, 12, 30)
    >>> # Using datetime.now() or datetime.utcnow()
    >>> datetime.now()   # doctest: +SKIP
    datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1
    >>> datetime.utcnow()   # doctest: +SKIP
    datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)
    >>> # Using datetime.strptime()
    >>> dt = datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
    >>> dt
    datetime.datetime(2006, 11, 21, 16, 30)
    >>> # Using datetime.timetuple() to get tuple of all attributes
    >>> tt = dt.timetuple()
    >>> for it in tt:   # doctest: +SKIP
    ...     print it
    ...
    2006    # year
    11      # month
    21      # day
    16      # hour
    30      # minute
    0       # second
    1       # weekday (0 = Monday)
    325     # number of days since 1st January
    -1      # dst - method tzinfo.dst() returned None
    >>> # Date in ISO format
    >>> ic = dt.isocalendar()
    >>> for it in ic:   # doctest: +SKIP
    ...     print it
    ...
    2006    # ISO year
    47      # ISO week
    2       # ISO weekday
    >>> # Formatting datetime
    >>> dt.strftime("%A, %d. %B %Y %I:%M%p")
    'Tuesday, 21. November 2006 04:30PM'
    >>> 'The {1} is {0:%d}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.'.format(dt, "day", "month", "time")
    'The day is 21, the month is November, the time is 04:30PM.'

Using datetime with tzinfo:

    >>> from datetime import timedelta, datetime, tzinfo
    >>> class GMT1(tzinfo):
    ...     def utcoffset(self, dt):
    ...         return timedelta(hours=1) + self.dst(dt)
    ...     def dst(self, dt):
    ...         # DST starts last Sunday in March
    ...         d = datetime(dt.year, 4, 1)   # ends last Sunday in October
    ...         self.dston = d - timedelta(days=d.weekday() + 1)
    ...         d = datetime(dt.year, 11, 1)
    ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
    ...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
    ...             return timedelta(hours=1)
    ...         else:
    ...             return timedelta(0)
    ...     def tzname(self,dt):
    ...          return "GMT +1"
    ...
    >>> class GMT2(tzinfo):
    ...     def utcoffset(self, dt):
    ...         return timedelta(hours=2) + self.dst(dt)
    ...     def dst(self, dt):
    ...         d = datetime(dt.year, 4, 1)
    ...         self.dston = d - timedelta(days=d.weekday() + 1)
    ...         d = datetime(dt.year, 11, 1)
    ...         self.dstoff = d - timedelta(days=d.weekday() + 1)
    ...         if self.dston <=  dt.replace(tzinfo=None) < self.dstoff:
    ...             return timedelta(hours=1)
    ...         else:
    ...             return timedelta(0)
    ...     def tzname(self,dt):
    ...         return "GMT +2"
    ...
    >>> gmt1 = GMT1()
    >>> # Daylight Saving Time
    >>> dt1 = datetime(2006, 11, 21, 16, 30, tzinfo=gmt1)
    >>> dt1.dst()
    datetime.timedelta(0)
    >>> dt1.utcoffset()
    datetime.timedelta(0, 3600)
    >>> dt2 = datetime(2006, 6, 14, 13, 0, tzinfo=gmt1)
    >>> dt2.dst()
    datetime.timedelta(0, 3600)
    >>> dt2.utcoffset()
    datetime.timedelta(0, 7200)
    >>> # Convert datetime to another time zone
    >>> dt3 = dt2.astimezone(GMT2())
    >>> dt3     # doctest: +ELLIPSIS
    datetime.datetime(2006, 6, 14, 14, 0, tzinfo=<GMT2 object at 0x...>)
    >>> dt2     # doctest: +ELLIPSIS
    datetime.datetime(2006, 6, 14, 13, 0, tzinfo=<GMT1 object at 0x...>)
    >>> dt2.utctimetuple() == dt3.utctimetuple()
    True



.. _datetime-time:

:class:`.time` Objects
----------------------

A time object represents a (local) time of day, independent of any particular
day, and subject to adjustment via a :class:`tzinfo` object.

.. class:: time([hour[, minute[, second[, microsecond[, tzinfo]]]]])

   All arguments are optional.  *tzinfo* may be ``None``, or an instance of a
   :class:`tzinfo` subclass.  The remaining arguments may be ints or longs, in the
   following ranges:

   * ``0 <= hour < 24``
   * ``0 <= minute < 60``
   * ``0 <= second < 60``
   * ``0 <= microsecond < 1000000``.

   If an argument outside those ranges is given, :exc:`ValueError` is raised.  All
   default to ``0`` except *tzinfo*, which defaults to :const:`None`.

Class attributes:


.. attribute:: time.min

   The earliest representable :class:`.time`, ``time(0, 0, 0, 0)``.


.. attribute:: time.max

   The latest representable :class:`.time`, ``time(23, 59, 59, 999999)``.


.. attribute:: time.resolution

   The smallest possible difference between non-equal :class:`.time` objects,
   ``timedelta(microseconds=1)``, although note that arithmetic on
   :class:`.time` objects is not supported.


Instance attributes (read-only):

.. attribute:: time.hour

   In ``range(24)``.


.. attribute:: time.minute

   In ``range(60)``.


.. attribute:: time.second

   In ``range(60)``.


.. attribute:: time.microsecond

   In ``range(1000000)``.


.. attribute:: time.tzinfo

   The object passed as the tzinfo argument to the :class:`.time` constructor, or
   ``None`` if none was passed.


Supported operations:

* comparison of :class:`.time` to :class:`.time`, where *a* is considered less
  than *b* when *a* precedes *b* in time.  If one comparand is naive and the other
  is aware, :exc:`TypeError` is raised.  If both comparands are aware, and have
  the same :attr:`~time.tzinfo` attribute, the common :attr:`~time.tzinfo` attribute is
  ignored and the base times are compared.  If both comparands are aware and
  have different :attr:`~time.tzinfo` attributes, the comparands are first adjusted by
  subtracting their UTC offsets (obtained from ``self.utcoffset()``). In order
  to stop mixed-type comparisons from falling back to the default comparison by
  object address, when a :class:`.time` object is compared to an object of a
  different type, :exc:`TypeError` is raised unless the comparison is ``==`` or
  ``!=``.  The latter cases return :const:`False` or :const:`True`, respectively.

* hash, use as dict key

* efficient pickling

* in Boolean contexts, a :class:`.time` object is considered to be true if and
  only if, after converting it to minutes and subtracting :meth:`utcoffset` (or
  ``0`` if that's ``None``), the result is non-zero.


Instance methods:

.. method:: time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]])

   Return a :class:`.time` with the same value, except for those attributes given
   new values by whichever keyword arguments are specified.  Note that
   ``tzinfo=None`` can be specified to create a naive :class:`.time` from an
   aware :class:`.time`, without conversion of the time data.


.. method:: time.isoformat()

   Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
   self.microsecond is 0, HH:MM:SS If :meth:`utcoffset` does not return ``None``, a
   6-character string is appended, giving the UTC offset in (signed) hours and
   minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM


.. method:: time.__str__()

   For a time *t*, ``str(t)`` is equivalent to ``t.isoformat()``.


.. method:: time.strftime(format)

   Return a string representing the time, controlled by an explicit format string.
   For a complete list of formatting directives, see section
   :ref:`strftime-strptime-behavior`.


.. method:: time.__format__(format)

   Same as :meth:`.time.strftime`. This makes it possible to specify a format string
   for a :class:`.time` object when using :meth:`str.format`.
   See section :ref:`strftime-strptime-behavior`.


.. method:: time.utcoffset()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.utcoffset(None)``, and raises an exception if the latter doesn't
   return ``None`` or a :class:`timedelta` object representing a whole number of
   minutes with magnitude less than one day.


.. method:: time.dst()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.dst(None)``, and raises an exception if the latter doesn't return
   ``None``, or a :class:`timedelta` object representing a whole number of minutes
   with magnitude less than one day.


.. method:: time.tzname()

   If :attr:`.tzinfo` is ``None``, returns ``None``, else returns
   ``self.tzinfo.tzname(None)``, or raises an exception if the latter doesn't
   return ``None`` or a string object.


Example:

    >>> from datetime import time, tzinfo, timedelta
    >>> class GMT1(tzinfo):
    ...     def utcoffset(self, dt):
    ...         return timedelta(hours=1)
    ...     def dst(self, dt):
    ...         return timedelta(0)
    ...     def tzname(self,dt):
    ...         return "Europe/Prague"
    ...
    >>> t = time(12, 10, 30, tzinfo=GMT1())
    >>> t                               # doctest: +ELLIPSIS
    datetime.time(12, 10, 30, tzinfo=<GMT1 object at 0x...>)
    >>> gmt = GMT1()
    >>> t.isoformat()
    '12:10:30+01:00'
    >>> t.dst()
    datetime.timedelta(0)
    >>> t.tzname()
    'Europe/Prague'
    >>> t.strftime("%H:%M:%S %Z")
    '12:10:30 Europe/Prague'
    >>> 'The {} is {:%H:%M}.'.format("time", t)
    'The time is 12:10.'


.. _datetime-tzinfo:

:class:`tzinfo` Objects
-----------------------

.. class:: tzinfo()

   This is an abstract base class, meaning that this class should not be
   instantiated directly.  You need to derive a concrete subclass, and (at least)
   supply implementations of the standard :class:`tzinfo` methods needed by the
   :class:`.datetime` methods you use.  The :mod:`datetime` module does not supply
   any concrete subclasses of :class:`tzinfo`.

   An instance of (a concrete subclass of) :class:`tzinfo` can be passed to the
   constructors for :class:`.datetime` and :class:`.time` objects. The latter objects
   view their attributes as being in local time, and the :class:`tzinfo` object
   supports methods revealing offset of local time from UTC, the name of the time
   zone, and DST offset, all relative to a date or time object passed to them.

   Special requirement for pickling:  A :class:`tzinfo` subclass must have an
   :meth:`__init__` method that can be called with no arguments, else it can be
   pickled but possibly not unpickled again.  This is a technical requirement that
   may be relaxed in the future.

   A concrete subclass of :class:`tzinfo` may need to implement the following
   methods.  Exactly which methods are needed depends on the uses made of aware
   :mod:`datetime` objects.  If in doubt, simply implement all of them.


.. method:: tzinfo.utcoffset(self, dt)

   Return offset of local time from UTC, in minutes east of UTC.  If local time is
   west of UTC, this should be negative.  Note that this is intended to be the
   total offset from UTC; for example, if a :class:`tzinfo` object represents both
   time zone and DST adjustments, :meth:`utcoffset` should return their sum.  If
   the UTC offset isn't known, return ``None``.  Else the value returned must be a
   :class:`timedelta` object specifying a whole number of minutes in the range
   -1439 to 1439 inclusive (1440 = 24\*60; the magnitude of the offset must be less
   than one day).  Most implementations of :meth:`utcoffset` will probably look
   like one of these two::

      return CONSTANT                 # fixed-offset class
      return CONSTANT + self.dst(dt)  # daylight-aware class

   If :meth:`utcoffset` does not return ``None``, :meth:`dst` should not return
   ``None`` either.

   The default implementation of :meth:`utcoffset` raises
   :exc:`NotImplementedError`.


.. method:: tzinfo.dst(self, dt)

   Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
   ``None`` if DST information isn't known.  Return ``timedelta(0)`` if DST is not
   in effect. If DST is in effect, return the offset as a :class:`timedelta` object
   (see :meth:`utcoffset` for details). Note that DST offset, if applicable, has
   already been added to the UTC offset returned by :meth:`utcoffset`, so there's
   no need to consult :meth:`dst` unless you're interested in obtaining DST info
   separately.  For example, :meth:`datetime.timetuple` calls its :attr:`~.datetime.tzinfo`
   attribute's :meth:`dst` method to determine how the :attr:`tm_isdst` flag
   should be set, and :meth:`tzinfo.fromutc` calls :meth:`dst` to account for
   DST changes when crossing time zones.

   An instance *tz* of a :class:`tzinfo` subclass that models both standard and
   daylight times must be consistent in this sense:

   ``tz.utcoffset(dt) - tz.dst(dt)``

   must return the same result for every :class:`.datetime` *dt* with ``dt.tzinfo ==
   tz``  For sane :class:`tzinfo` subclasses, this expression yields the time
   zone's "standard offset", which should not depend on the date or the time, but
   only on geographic location.  The implementation of :meth:`datetime.astimezone`
   relies on this, but cannot detect violations; it's the programmer's
   responsibility to ensure it.  If a :class:`tzinfo` subclass cannot guarantee
   this, it may be able to override the default implementation of
   :meth:`tzinfo.fromutc` to work correctly with :meth:`astimezone` regardless.

   Most implementations of :meth:`dst` will probably look like one of these two::

      def dst(self, dt):
          # a fixed-offset class:  doesn't account for DST
          return timedelta(0)

   or ::

      def dst(self, dt):
          # Code to set dston and dstoff to the time zone's DST
          # transition times based on the input dt.year, and expressed
          # in standard local time.  Then

          if dston <= dt.replace(tzinfo=None) < dstoff:
              return timedelta(hours=1)
          else:
              return timedelta(0)

   The default implementation of :meth:`dst` raises :exc:`NotImplementedError`.


.. method:: tzinfo.tzname(self, dt)

   Return the time zone name corresponding to the :class:`.datetime` object *dt*, as
   a string. Nothing about string names is defined by the :mod:`datetime` module,
   and there's no requirement that it mean anything in particular.  For example,
   "GMT", "UTC", "-500", "-5:00", "EDT", "US/Eastern", "America/New York" are all
   valid replies.  Return ``None`` if a string name isn't known.  Note that this is
   a method rather than a fixed string primarily because some :class:`tzinfo`
   subclasses will wish to return different names depending on the specific value
   of *dt* passed, especially if the :class:`tzinfo` class is accounting for
   daylight time.

   The default implementation of :meth:`tzname` raises :exc:`NotImplementedError`.


These methods are called by a :class:`.datetime` or :class:`.time` object, in
response to their methods of the same names.  A :class:`.datetime` object passes
itself as the argument, and a :class:`.time` object passes ``None`` as the
argument.  A :class:`tzinfo` subclass's methods should therefore be prepared to
accept a *dt* argument of ``None``, or of class :class:`.datetime`.

When ``None`` is passed, it's up to the class designer to decide the best
response.  For example, returning ``None`` is appropriate if the class wishes to
say that time objects don't participate in the :class:`tzinfo` protocols.  It
may be more useful for ``utcoffset(None)`` to return the standard UTC offset, as
there is no other convention for discovering the standard offset.

When a :class:`.datetime` object is passed in response to a :class:`.datetime`
method, ``dt.tzinfo`` is the same object as *self*.  :class:`tzinfo` methods can
rely on this, unless user code calls :class:`tzinfo` methods directly.  The
intent is that the :class:`tzinfo` methods interpret *dt* as being in local
time, and not need worry about objects in other timezones.

There is one more :class:`tzinfo` method that a subclass may wish to override:


.. method:: tzinfo.fromutc(self, dt)

   This is called from the default :class:`datetime.astimezone()`
   implementation.  When called from that, ``dt.tzinfo`` is *self*, and *dt*'s
   date and time data are to be viewed as expressing a UTC time.  The purpose
   of :meth:`fromutc` is to adjust the date and time data, returning an
   equivalent datetime in *self*'s local time.

   Most :class:`tzinfo` subclasses should be able to inherit the default
   :meth:`fromutc` implementation without problems.  It's strong enough to handle
   fixed-offset time zones, and time zones accounting for both standard and
   daylight time, and the latter even if the DST transition times differ in
   different years.  An example of a time zone the default :meth:`fromutc`
   implementation may not handle correctly in all cases is one where the standard
   offset (from UTC) depends on the specific date and time passed, which can happen
   for political reasons. The default implementations of :meth:`astimezone` and
   :meth:`fromutc` may not produce the result you want if the result is one of the
   hours straddling the moment the standard offset changes.

   Skipping code for error cases, the default :meth:`fromutc` implementation acts
   like::

      def fromutc(self, dt):
          # raise ValueError error if dt.tzinfo is not self
          dtoff = dt.utcoffset()
          dtdst = dt.dst()
          # raise ValueError if dtoff is None or dtdst is None
          delta = dtoff - dtdst  # this is self's standard offset
          if delta:
              dt += delta   # convert to standard local time
              dtdst = dt.dst()
              # raise ValueError if dtdst is None
          if dtdst:
              return dt + dtdst
          else:
              return dt

Example :class:`tzinfo` classes:

.. literalinclude:: ../includes/tzinfo-examples.py


Note that there are unavoidable subtleties twice per year in a :class:`tzinfo`
subclass accounting for both standard and daylight time, at the DST transition
points.  For concreteness, consider US Eastern (UTC -0500), where EDT begins the
minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
1:59 (EDT) on the first Sunday in November::

     UTC   3:MM  4:MM  5:MM  6:MM  7:MM  8:MM
     EST  22:MM 23:MM  0:MM  1:MM  2:MM  3:MM
     EDT  23:MM  0:MM  1:MM  2:MM  3:MM  4:MM

   start  22:MM 23:MM  0:MM  1:MM  3:MM  4:MM

     end  23:MM  0:MM  1:MM  1:MM  2:MM  3:MM

When DST starts (the "start" line), the local wall clock leaps from 1:59 to
3:00.  A wall time of the form 2:MM doesn't really make sense on that day, so
``astimezone(Eastern)`` won't deliver a result with ``hour == 2`` on the day DST
begins.  In order for :meth:`astimezone` to make this guarantee, the
:meth:`rzinfo.dst` method must consider times in the "missing hour" (2:MM for
Eastern) to be in daylight time.

When DST ends (the "end" line), there's a potentially worse problem: there's an
hour that can't be spelled unambiguously in local wall time: the last hour of
daylight time.  In Eastern, that's times of the form 5:MM UTC on the day
daylight time ends.  The local wall clock leaps from 1:59 (daylight time) back
to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
:meth:`astimezone` mimics the local clock's behavior by mapping two adjacent UTC
hours into the same local hour then.  In the Eastern example, UTC times of the
form 5:MM and 6:MM both map to 1:MM when converted to Eastern.  In order for
:meth:`astimezone` to make this guarantee, the :meth:`tzinfo.dst` method must
consider times in the "repeated hour" to be in standard time.  This is easily
arranged, as in the example, by expressing DST switch times in the time zone's
standard local time.

Applications that can't bear such ambiguities should avoid using hybrid
:class:`tzinfo` subclasses; there are no ambiguities when using UTC, or any
other fixed-offset :class:`tzinfo` subclass (such as a class representing only
EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).

.. seealso::

   `pytz <https://pypi.org/project/pytz/>`_
      The standard library has no :class:`tzinfo` instances, but
      there exists a third-party library which brings the *IANA timezone
      database* (also known as the Olson database) to Python: *pytz*.

      *pytz* contains up-to-date information and its usage is recommended.

   `IANA timezone database <https://www.iana.org/time-zones>`_
      The Time Zone Database (often called tz or zoneinfo) contains code and
      data that represent the history of local time for many representative
      locations around the globe. It is updated periodically to reflect changes
      made by political bodies to time zone boundaries, UTC offsets, and
      daylight-saving rules.

.. _strftime-strptime-behavior:

:meth:`strftime` and :meth:`strptime` Behavior
----------------------------------------------

:class:`date`, :class:`.datetime`, and :class:`.time` objects all support a
``strftime(format)`` method, to create a string representing the time under the
control of an explicit format string.  Broadly speaking, ``d.strftime(fmt)``
acts like the :mod:`time` module's ``time.strftime(fmt, d.timetuple())``
although not all objects support a :meth:`timetuple` method.

Conversely, the :meth:`datetime.strptime` class method creates a
:class:`.datetime` object from a string representing a date and time and a
corresponding format string. ``datetime.strptime(date_string, format)`` is
equivalent to ``datetime(*(time.strptime(date_string, format)[0:6]))``, except
when the format includes sub-second components or timezone offset information,
which are supported in ``datetime.strptime`` but are discarded by ``time.strptime``.

For :class:`.time` objects, the format codes for year, month, and day should not
be used, as time objects have no such values.  If they're used anyway, ``1900``
is substituted for the year, and ``1`` for the month and day.

For :class:`date` objects, the format codes for hours, minutes, seconds, and
microseconds should not be used, as :class:`date` objects have no such
values.  If they're used anyway, ``0`` is substituted for them.

The full set of format codes supported varies across platforms, because Python
calls the platform C library's :func:`strftime` function, and platform
variations are common.  To see the full set of format codes supported on your
platform, consult the :manpage:`strftime(3)` documentation.

For the same reason, handling of format strings containing Unicode code points
that can't be represented in the charset of the current locale is also
platform-dependent. On some platforms such code points are preserved intact in
the output, while on others ``strftime`` may raise :exc:`UnicodeError` or return
an empty string instead.

The following is a list of all the format codes that the C standard (1989
version) requires, and these work on all platforms with a standard C
implementation.  Note that the 1999 version of the C standard added additional
format codes.

The exact range of years for which :meth:`strftime` works also varies across
platforms.  Regardless of platform, years before 1900 cannot be used.

+-----------+--------------------------------+------------------------+-------+
| Directive | Meaning                        | Example                | Notes |
+===========+================================+========================+=======+
| ``%a``    | Weekday as locale's            || Sun, Mon, ..., Sat    | \(1)  |
|           | abbreviated name.              |  (en_US);              |       |
|           |                                || So, Mo, ..., Sa       |       |
|           |                                |  (de_DE)               |       |
+-----------+--------------------------------+------------------------+-------+
| ``%A``    | Weekday as locale's full name. || Sunday, Monday, ...,  | \(1)  |
|           |                                |  Saturday (en_US);     |       |
|           |                                || Sonntag, Montag, ..., |       |
|           |                                |  Samstag (de_DE)       |       |
+-----------+--------------------------------+------------------------+-------+
| ``%w``    | Weekday as a decimal number,   | 0, 1, ..., 6           |       |
|           | where 0 is Sunday and 6 is     |                        |       |
|           | Saturday.                      |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%d``    | Day of the month as a          | 01, 02, ..., 31        |       |
|           | zero-padded decimal number.    |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%b``    | Month as locale's abbreviated  || Jan, Feb, ..., Dec    | \(1)  |
|           | name.                          |  (en_US);              |       |
|           |                                || Jan, Feb, ..., Dez    |       |
|           |                                |  (de_DE)               |       |
+-----------+--------------------------------+------------------------+-------+
| ``%B``    | Month as locale's full name.   || January, February,    | \(1)  |
|           |                                |  ..., December (en_US);|       |
|           |                                || Januar, Februar, ..., |       |
|           |                                |  Dezember (de_DE)      |       |
+-----------+--------------------------------+------------------------+-------+
| ``%m``    | Month as a zero-padded         | 01, 02, ..., 12        |       |
|           | decimal number.                |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%y``    | Year without century as a      | 00, 01, ..., 99        |       |
|           | zero-padded decimal number.    |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%Y``    | Year with century as a decimal | 1970, 1988, 2001, 2013 |       |
|           | number.                        |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%H``    | Hour (24-hour clock) as a      | 00, 01, ..., 23        |       |
|           | zero-padded decimal number.    |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%I``    | Hour (12-hour clock) as a      | 01, 02, ..., 12        |       |
|           | zero-padded decimal number.    |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%p``    | Locale's equivalent of either  || AM, PM (en_US);       | \(1), |
|           | AM or PM.                      || am, pm (de_DE)        | \(2)  |
+-----------+--------------------------------+------------------------+-------+
| ``%M``    | Minute as a zero-padded        | 00, 01, ..., 59        |       |
|           | decimal number.                |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%S``    | Second as a zero-padded        | 00, 01, ..., 59        | \(3)  |
|           | decimal number.                |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%f``    | Microsecond as a decimal       | 000000, 000001, ...,   | \(4)  |
|           | number, zero-padded on the     | 999999                 |       |
|           | left.                          |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%z``    | UTC offset in the form +HHMM   | (empty), +0000, -0400, | \(5)  |
|           | or -HHMM (empty string if the  | +1030                  |       |
|           | the object is naive).          |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%Z``    | Time zone name (empty string   | (empty), UTC, EST, CST |       |
|           | if the object is naive).       |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%j``    | Day of the year as a           | 001, 002, ..., 366     |       |
|           | zero-padded decimal number.    |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%U``    | Week number of the year        | 00, 01, ..., 53        | \(6)  |
|           | (Sunday as the first day of    |                        |       |
|           | the week) as a zero padded     |                        |       |
|           | decimal number. All days in a  |                        |       |
|           | new year preceding the first   |                        |       |
|           | Sunday are considered to be in |                        |       |
|           | week 0.                        |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%W``    | Week number of the year        | 00, 01, ..., 53        | \(6)  |
|           | (Monday as the first day of    |                        |       |
|           | the week) as a decimal number. |                        |       |
|           | All days in a new year         |                        |       |
|           | preceding the first Monday     |                        |       |
|           | are considered to be in        |                        |       |
|           | week 0.                        |                        |       |
+-----------+--------------------------------+------------------------+-------+
| ``%c``    | Locale's appropriate date and  || Tue Aug 16 21:30:00   | \(1)  |
|           | time representation.           |  1988 (en_US);         |       |
|           |                                || Di 16 Aug 21:30:00    |       |
|           |                                |  1988 (de_DE)          |       |
+-----------+--------------------------------+------------------------+-------+
| ``%x``    | Locale's appropriate date      || 08/16/88 (None);      | \(1)  |
|           | representation.                || 08/16/1988 (en_US);   |       |
|           |                                || 16.08.1988 (de_DE)    |       |
+-----------+--------------------------------+------------------------+-------+
| ``%X``    | Locale's appropriate time      || 21:30:00 (en_US);     | \(1)  |
|           | representation.                || 21:30:00 (de_DE)      |       |
+-----------+--------------------------------+------------------------+-------+
| ``%%``    | A literal ``'%'`` character.   | %                      |       |
+-----------+--------------------------------+------------------------+-------+

Notes:

(1)
   Because the format depends on the current locale, care should be taken when
   making assumptions about the output value. Field orderings will vary (for
   example, "month/day/year" versus "day/month/year"), and the output may
   contain Unicode characters encoded using the locale's default encoding (for
   example, if the current locale is ``ja_JP``, the default encoding could be
   any one of ``eucJP``, ``SJIS``, or ``utf-8``; use :meth:`locale.getlocale`
   to determine the current locale's encoding).

(2)
   When used with the :meth:`strptime` method, the ``%p`` directive only affects
   the output hour field if the ``%I`` directive is used to parse the hour.

(3)
   Unlike the :mod:`time` module, the :mod:`datetime` module does not support
   leap seconds.

(4)
   ``%f`` is an extension to the set of format characters in the C standard
   (but implemented separately in datetime objects, and therefore always
   available).  When used with the :meth:`strptime` method, the ``%f``
   directive accepts from one to six digits and zero pads on the right.

   .. versionadded:: 2.6

(5)
   For a naive object, the ``%z`` and ``%Z`` format codes are replaced by empty
   strings.

   For an aware object:

   ``%z``
      :meth:`utcoffset` is transformed into a 5-character string of the form
      +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
      offset hours, and MM is a 2-digit string giving the number of UTC offset
      minutes.  For example, if :meth:`utcoffset` returns
      ``timedelta(hours=-3, minutes=-30)``, ``%z`` is replaced with the string
      ``'-0330'``.

   ``%Z``
      If :meth:`tzname` returns ``None``, ``%Z`` is replaced by an empty
      string.  Otherwise ``%Z`` is replaced by the returned value, which must
      be a string.

(6)
   When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used
   in calculations when the day of the week and the year are specified.


.. rubric:: Footnotes

.. [#] If, that is, we ignore the effects of Relativity
PK	%�\�/�Y$html/_sources/library/dbhash.rst.txtnu�[���:mod:`dbhash` --- DBM-style interface to the BSD database library
=================================================================

.. module:: dbhash
   :synopsis: DBM-style interface to the BSD database library.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

.. deprecated:: 2.6
   The :mod:`dbhash` module has been removed in Python 3.

.. index:: module: bsddb

The :mod:`dbhash` module provides a function to open databases using the BSD
``db`` library.  This module mirrors the interface of the other Python database
modules that provide access to DBM-style databases.  The :mod:`bsddb` module is
required  to use :mod:`dbhash`.

This module provides an exception and a function:


.. exception:: error

   Exception raised on database errors other than :exc:`KeyError`.  It is a synonym
   for :exc:`bsddb.error`.


.. function:: open(path[, flag[, mode]])

   Open a ``db`` database and return the database object.  The *path* argument is
   the name of the database file.

   The *flag* argument can be:

   +---------+-------------------------------------------+
   | Value   | Meaning                                   |
   +=========+===========================================+
   | ``'r'`` | Open existing database for reading only   |
   |         | (default)                                 |
   +---------+-------------------------------------------+
   | ``'w'`` | Open existing database for reading and    |
   |         | writing                                   |
   +---------+-------------------------------------------+
   | ``'c'`` | Open database for reading and writing,    |
   |         | creating it if it doesn't exist           |
   +---------+-------------------------------------------+
   | ``'n'`` | Always create a new, empty database, open |
   |         | for reading and writing                   |
   +---------+-------------------------------------------+

   For platforms on which the BSD ``db`` library supports locking, an ``'l'``
   can be appended to indicate that locking should be used.

   The optional *mode* parameter is used to indicate the Unix permission bits that
   should be set if a new database must be created; this will be masked by the
   current umask value for the process.


.. seealso::

   Module :mod:`anydbm`
      Generic interface to ``dbm``\ -style databases.

   Module :mod:`bsddb`
      Lower-level interface to the BSD ``db`` library.

   Module :mod:`whichdb`
      Utility module used to determine the type of an existing database.


.. _dbhash-objects:

Database Objects
----------------

The database objects returned by :func:`.open` provide the methods  common to all
the DBM-style databases and mapping objects.  The following methods are
available in addition to the standard methods.


.. method:: dbhash.first()

   It's possible to loop over every key/value pair in the database using this
   method and the :meth:`!next` method.  The traversal is ordered by the databases
   internal hash values, and won't be sorted by the key values.  This method
   returns the starting key.


.. method:: dbhash.last()

   Return the last key/value pair in a database traversal.  This may be used to
   begin a reverse-order traversal; see :meth:`previous`.


.. method:: dbhash.next()

   Returns the key next key/value pair in a database traversal.  The following code
   prints every key in the database ``db``, without having to create a list in
   memory that contains them all::

      print db.first()
      for i in xrange(1, len(db)):
          print db.next()


.. method:: dbhash.previous()

   Returns the previous key/value pair in a forward-traversal of the database. In
   conjunction with :meth:`last`, this may be used to implement a reverse-order
   traversal.


.. method:: dbhash.sync()

   This method forces any unwritten data to be written to the disk.

PK	%�\�J��--!html/_sources/library/dbm.rst.txtnu�[���:mod:`dbm` --- Simple "database" interface
==========================================

.. module:: dbm
   :platform: Unix
   :synopsis: The standard "database" interface, based on ndbm.

.. note::
   The :mod:`dbm` module has been renamed to :mod:`dbm.ndbm` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.


The :mod:`dbm` module provides an interface to the Unix "(n)dbm" library.  Dbm
objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a dbm object doesn't print the keys and values, and the
:meth:`items` and :meth:`values` methods are not supported.

This module can be used with the "classic" ndbm interface, the BSD DB
compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
:program:`configure` script will attempt to locate the appropriate header file
to simplify building this module.

The module defines the following:


.. exception:: error

   Raised on dbm-specific errors, such as I/O errors. :exc:`KeyError` is raised for
   general mapping errors like specifying an incorrect key.


.. data:: library

   Name of the ``ndbm`` implementation library used.


.. function:: open(filename[, flag[, mode]])

   Open a dbm database and return a dbm object.  The *filename* argument is the
   name of the database file (without the :file:`.dir` or :file:`.pag` extensions;
   note that the BSD DB implementation of the interface will append the extension
   :file:`.db` and only create one file).

   The optional *flag* argument must be one of these values:

   +---------+-------------------------------------------+
   | Value   | Meaning                                   |
   +=========+===========================================+
   | ``'r'`` | Open existing database for reading only   |
   |         | (default)                                 |
   +---------+-------------------------------------------+
   | ``'w'`` | Open existing database for reading and    |
   |         | writing                                   |
   +---------+-------------------------------------------+
   | ``'c'`` | Open database for reading and writing,    |
   |         | creating it if it doesn't exist           |
   +---------+-------------------------------------------+
   | ``'n'`` | Always create a new, empty database, open |
   |         | for reading and writing                   |
   +---------+-------------------------------------------+

   The optional *mode* argument is the Unix mode of the file, used only when the
   database has to be created.  It defaults to octal ``0666`` (and will be
   modified by the prevailing umask).

   In addition to the dictionary-like methods, ``dbm`` objects
   provide the following method:


   .. function:: close()

      Close the ``dbm`` database.


.. seealso::

   Module :mod:`anydbm`
      Generic interface to ``dbm``\ -style databases.

   Module :mod:`gdbm`
      Similar interface to the GNU GDBM library.

   Module :mod:`whichdb`
      Utility module used to determine the type of an existing database.

PK	%�\�J����#html/_sources/library/debug.rst.txtnu�[���***********************
Debugging and Profiling
***********************

These libraries help you with Python development: the debugger enables you to
step through code, analyze stack frames and set breakpoints etc., and the
profilers run code and give you a detailed breakdown of execution times,
allowing you to identify bottlenecks in your programs.

.. toctree::

   bdb.rst
   pdb.rst
   profile.rst
   hotshot.rst
   timeit.rst
   trace.rstPK	%�\��%html/_sources/library/decimal.rst.txtnu�[���
:mod:`decimal` --- Decimal fixed point and floating point arithmetic
====================================================================

.. module:: decimal
   :synopsis: Implementation of the General Decimal Arithmetic  Specification.


.. moduleauthor:: Eric Price <eprice at tjhsst.edu>
.. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
.. moduleauthor:: Raymond Hettinger <python at rcn.com>
.. moduleauthor:: Aahz <aahz at pobox.com>
.. moduleauthor:: Tim Peters <tim.one at comcast.net>


.. sectionauthor:: Raymond D. Hettinger <python at rcn.com>

.. versionadded:: 2.4

.. import modules for testing inline doctests with the Sphinx doctest builder
.. testsetup:: *

   import decimal
   import math
   from decimal import *
   # make sure each group gets a fresh context
   setcontext(Context())

The :mod:`decimal` module provides support for decimal floating point
arithmetic.  It offers several advantages over the :class:`float` datatype:

* Decimal "is based on a floating-point model which was designed with people
  in mind, and necessarily has a paramount guiding principle -- computers must
  provide an arithmetic that works in the same way as the arithmetic that
  people learn at school." -- excerpt from the decimal arithmetic specification.

* Decimal numbers can be represented exactly.  In contrast, numbers like
  :const:`1.1` and :const:`2.2` do not have exact representations in binary
  floating point.  End users typically would not expect ``1.1 + 2.2`` to display
  as :const:`3.3000000000000003` as it does with binary floating point.

* The exactness carries over into arithmetic.  In decimal floating point, ``0.1
  + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, the result
  is :const:`5.5511151231257827e-017`.  While near to zero, the differences
  prevent reliable equality testing and differences can accumulate. For this
  reason, decimal is preferred in accounting applications which have strict
  equality invariants.

* The decimal module incorporates a notion of significant places so that ``1.30
  + 1.20`` is :const:`2.50`.  The trailing zero is kept to indicate significance.
  This is the customary presentation for monetary applications. For
  multiplication, the "schoolbook" approach uses all the figures in the
  multiplicands.  For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
  1.20`` gives :const:`1.5600`.

* Unlike hardware based binary floating point, the decimal module has a user
  alterable precision (defaulting to 28 places) which can be as large as needed for
  a given problem:

     >>> from decimal import *
     >>> getcontext().prec = 6
     >>> Decimal(1) / Decimal(7)
     Decimal('0.142857')
     >>> getcontext().prec = 28
     >>> Decimal(1) / Decimal(7)
     Decimal('0.1428571428571428571428571429')

* Both binary and decimal floating point are implemented in terms of published
  standards.  While the built-in float type exposes only a modest portion of its
  capabilities, the decimal module exposes all required parts of the standard.
  When needed, the programmer has full control over rounding and signal handling.
  This includes an option to enforce exact arithmetic by using exceptions
  to block any inexact operations.

* The decimal module was designed to support "without prejudice, both exact
  unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
  and rounded floating-point arithmetic."  -- excerpt from the decimal
  arithmetic specification.

The module design is centered around three concepts:  the decimal number, the
context for arithmetic, and signals.

A decimal number is immutable.  It has a sign, coefficient digits, and an
exponent.  To preserve significance, the coefficient digits do not truncate
trailing zeros.  Decimals also include special values such as
:const:`Infinity`, :const:`-Infinity`, and :const:`NaN`.  The standard also
differentiates :const:`-0` from :const:`+0`.

The context for arithmetic is an environment specifying precision, rounding
rules, limits on exponents, flags indicating the results of operations, and trap
enablers which determine whether signals are treated as exceptions.  Rounding
options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
:const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
:const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.

Signals are groups of exceptional conditions arising during the course of
computation.  Depending on the needs of the application, signals may be ignored,
considered as informational, or treated as exceptions. The signals in the
decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
:const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
:const:`Overflow`, and :const:`Underflow`.

For each signal there is a flag and a trap enabler.  When a signal is
encountered, its flag is set to one, then, if the trap enabler is
set to one, an exception is raised.  Flags are sticky, so the user needs to
reset them before monitoring a calculation.


.. seealso::

   * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
     Specification <http://speleotrove.com/decimal/>`_.

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-tutorial:

Quick-start Tutorial
--------------------

The usual start to using decimals is importing the module, viewing the current
context with :func:`getcontext` and, if necessary, setting new values for
precision, rounding, or enabled traps::

   >>> from decimal import *
   >>> getcontext()
   Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
           capitals=1, flags=[], traps=[Overflow, DivisionByZero,
           InvalidOperation])

   >>> getcontext().prec = 7       # Set a new precision

Decimal instances can be constructed from integers, strings, floats, or tuples.
Construction from an integer or a float performs an exact conversion of the
value of that integer or float.  Decimal numbers include special values such as
:const:`NaN` which stands for "Not a number", positive and negative
:const:`Infinity`, and :const:`-0`.

   >>> getcontext().prec = 28
   >>> Decimal(10)
   Decimal('10')
   >>> Decimal('3.14')
   Decimal('3.14')
   >>> Decimal(3.14)
   Decimal('3.140000000000000124344978758017532527446746826171875')
   >>> Decimal((0, (3, 1, 4), -2))
   Decimal('3.14')
   >>> Decimal(str(2.0 ** 0.5))
   Decimal('1.41421356237')
   >>> Decimal(2) ** Decimal('0.5')
   Decimal('1.414213562373095048801688724')
   >>> Decimal('NaN')
   Decimal('NaN')
   >>> Decimal('-Infinity')
   Decimal('-Infinity')

The significance of a new Decimal is determined solely by the number of digits
input.  Context precision and rounding only come into play during arithmetic
operations.

.. doctest:: newcontext

   >>> getcontext().prec = 6
   >>> Decimal('3.0')
   Decimal('3.0')
   >>> Decimal('3.1415926535')
   Decimal('3.1415926535')
   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
   Decimal('5.85987')
   >>> getcontext().rounding = ROUND_UP
   >>> Decimal('3.1415926535') + Decimal('2.7182818285')
   Decimal('5.85988')

Decimals interact well with much of the rest of Python.  Here is a small decimal
floating point flying circus:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
   >>> max(data)
   Decimal('9.25')
   >>> min(data)
   Decimal('0.03')
   >>> sorted(data)
   [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
    Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
   >>> sum(data)
   Decimal('19.29')
   >>> a,b,c = data[:3]
   >>> str(a)
   '1.34'
   >>> float(a)
   1.34
   >>> round(a, 1)     # round() first converts to binary floating point
   1.3
   >>> int(a)
   1
   >>> a * 5
   Decimal('6.70')
   >>> a * b
   Decimal('2.5058')
   >>> c % a
   Decimal('0.77')

And some mathematical functions are also available to Decimal:

   >>> getcontext().prec = 28
   >>> Decimal(2).sqrt()
   Decimal('1.414213562373095048801688724')
   >>> Decimal(1).exp()
   Decimal('2.718281828459045235360287471')
   >>> Decimal('10').ln()
   Decimal('2.302585092994045684017991455')
   >>> Decimal('10').log10()
   Decimal('1')

The :meth:`quantize` method rounds a number to a fixed exponent.  This method is
useful for monetary applications that often round results to a fixed number of
places:

   >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
   Decimal('7.32')
   >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
   Decimal('8')

As shown above, the :func:`getcontext` function accesses the current context and
allows the settings to be changed.  This approach meets the needs of most
applications.

For more advanced work, it may be useful to create alternate contexts using the
Context() constructor.  To make an alternate active, use the :func:`setcontext`
function.

In accordance with the standard, the :mod:`decimal` module provides two ready to
use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
former is especially useful for debugging because many of the traps are
enabled:

.. doctest:: newcontext
   :options: +NORMALIZE_WHITESPACE

   >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
   >>> setcontext(myothercontext)
   >>> Decimal(1) / Decimal(7)
   Decimal('0.142857142857142857142857142857142857142857142857142857142857')

   >>> ExtendedContext
   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
           capitals=1, flags=[], traps=[])
   >>> setcontext(ExtendedContext)
   >>> Decimal(1) / Decimal(7)
   Decimal('0.142857143')
   >>> Decimal(42) / Decimal(0)
   Decimal('Infinity')

   >>> setcontext(BasicContext)
   >>> Decimal(42) / Decimal(0)
   Traceback (most recent call last):
     File "<pyshell#143>", line 1, in -toplevel-
       Decimal(42) / Decimal(0)
   DivisionByZero: x / 0

Contexts also have signal flags for monitoring exceptional conditions
encountered during computations.  The flags remain set until explicitly cleared,
so it is best to clear the flags before each set of monitored computations by
using the :meth:`clear_flags` method. ::

   >>> setcontext(ExtendedContext)
   >>> getcontext().clear_flags()
   >>> Decimal(355) / Decimal(113)
   Decimal('3.14159292')
   >>> getcontext()
   Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
           capitals=1, flags=[Rounded, Inexact], traps=[])

The *flags* entry shows that the rational approximation to :const:`Pi` was
rounded (digits beyond the context precision were thrown away) and that the
result is inexact (some of the discarded digits were non-zero).

Individual traps are set using the dictionary in the :attr:`traps` field of a
context:

.. doctest:: newcontext

   >>> setcontext(ExtendedContext)
   >>> Decimal(1) / Decimal(0)
   Decimal('Infinity')
   >>> getcontext().traps[DivisionByZero] = 1
   >>> Decimal(1) / Decimal(0)
   Traceback (most recent call last):
     File "<pyshell#112>", line 1, in -toplevel-
       Decimal(1) / Decimal(0)
   DivisionByZero: x / 0

Most programs adjust the current context only once, at the beginning of the
program.  And, in many applications, data is converted to :class:`Decimal` with
a single cast inside a loop.  With context set and decimals created, the bulk of
the program manipulates the data no differently than with other Python numeric
types.

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-decimal:

Decimal objects
---------------


.. class:: Decimal([value [, context]])

   Construct a new :class:`Decimal` object based from *value*.

   *value* can be an integer, string, tuple, :class:`float`, or another :class:`Decimal`
   object. If no *value* is given, returns ``Decimal('0')``.  If *value* is a
   string, it should conform to the decimal numeric string syntax after leading
   and trailing whitespace characters are removed::

      sign           ::=  '+' | '-'
      digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
      indicator      ::=  'e' | 'E'
      digits         ::=  digit [digit]...
      decimal-part   ::=  digits '.' [digits] | ['.'] digits
      exponent-part  ::=  indicator [sign] digits
      infinity       ::=  'Infinity' | 'Inf'
      nan            ::=  'NaN' [digits] | 'sNaN' [digits]
      numeric-value  ::=  decimal-part [exponent-part] | infinity
      numeric-string ::=  [sign] numeric-value | [sign] nan

   If *value* is a unicode string then other Unicode decimal digits
   are also permitted where ``digit`` appears above.  These include
   decimal digits from various other alphabets (for example,
   Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
   ``u'\uff10'`` through ``u'\uff19'``.

   If *value* is a :class:`tuple`, it should have three components, a sign
   (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
   digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
   returns ``Decimal('1.414')``.

   If *value* is a :class:`float`, the binary floating point value is losslessly
   converted to its exact decimal equivalent.  This conversion can often require
   53 or more digits of precision.  For example, ``Decimal(float('1.1'))``
   converts to
   ``Decimal('1.100000000000000088817841970012523233890533447265625')``.

   The *context* precision does not affect how many digits are stored. That is
   determined exclusively by the number of digits in *value*. For example,
   ``Decimal('3.00000')`` records all five zeros even if the context precision is
   only three.

   The purpose of the *context* argument is determining what to do if *value* is a
   malformed string.  If the context traps :const:`InvalidOperation`, an exception
   is raised; otherwise, the constructor returns a new Decimal with the value of
   :const:`NaN`.

   Once constructed, :class:`Decimal` objects are immutable.

   .. versionchanged:: 2.6
      leading and trailing whitespace characters are permitted when
      creating a Decimal instance from a string.

   .. versionchanged:: 2.7
      The argument to the constructor is now permitted to be a :class:`float` instance.

   Decimal floating point objects share many properties with the other built-in
   numeric types such as :class:`float` and :class:`int`.  All of the usual math
   operations and special methods apply.  Likewise, decimal objects can be
   copied, pickled, printed, used as dictionary keys, used as set elements,
   compared, sorted, and coerced to another type (such as :class:`float` or
   :class:`long`).

   There are some small differences between arithmetic on Decimal objects and
   arithmetic on integers and floats.  When the remainder operator ``%`` is
   applied to Decimal objects, the sign of the result is the sign of the
   *dividend* rather than the sign of the divisor::

      >>> (-7) % 4
      1
      >>> Decimal(-7) % Decimal(4)
      Decimal('-3')

   The integer division operator ``//`` behaves analogously, returning the
   integer part of the true quotient (truncating towards zero) rather than its
   floor, so as to preserve the usual identity ``x == (x // y) * y + x % y``::

      >>> -7 // 4
      -2
      >>> Decimal(-7) // Decimal(4)
      Decimal('-1')

   The ``%`` and ``//`` operators implement the ``remainder`` and
   ``divide-integer`` operations (respectively) as described in the
   specification.

   Decimal objects cannot generally be combined with floats in
   arithmetic operations: an attempt to add a :class:`Decimal` to a
   :class:`float`, for example, will raise a :exc:`TypeError`.
   There's one exception to this rule: it's possible to use Python's
   comparison operators to compare a :class:`float` instance ``x``
   with a :class:`Decimal` instance ``y``.  Without this exception,
   comparisons between :class:`Decimal` and :class:`float` instances
   would follow the general rules for comparing objects of different
   types described in the :ref:`expressions` section of the reference
   manual, leading to confusing results.

   .. versionchanged:: 2.7
      A comparison between a :class:`float` instance ``x`` and a
      :class:`Decimal` instance ``y`` now returns a result based on
      the values of ``x`` and ``y``.  In earlier versions ``x < y``
      returned the same (arbitrary) result for any :class:`Decimal`
      instance ``x`` and any :class:`float` instance ``y``.

   In addition to the standard numeric properties, decimal floating point
   objects also have a number of specialized methods:


   .. method:: adjusted()

      Return the adjusted exponent after shifting out the coefficient's
      rightmost digits until only the lead digit remains:
      ``Decimal('321e+5').adjusted()`` returns seven.  Used for determining the
      position of the most significant digit with respect to the decimal point.


   .. method:: as_tuple()

      Return a :term:`named tuple` representation of the number:
      ``DecimalTuple(sign, digits, exponent)``.

      .. versionchanged:: 2.6
         Use a named tuple.


   .. method:: canonical()

      Return the canonical encoding of the argument.  Currently, the encoding of
      a :class:`Decimal` instance is always canonical, so this operation returns
      its argument unchanged.

      .. versionadded:: 2.6

   .. method:: compare(other[, context])

      Compare the values of two Decimal instances.  This operation behaves in
      the same way as the usual comparison method :meth:`__cmp__`, except that
      :meth:`compare` returns a Decimal instance rather than an integer, and if
      either operand is a NaN then the result is a NaN::

         a or b is a NaN ==> Decimal('NaN')
         a < b           ==> Decimal('-1')
         a == b          ==> Decimal('0')
         a > b           ==> Decimal('1')

   .. method:: compare_signal(other[, context])

      This operation is identical to the :meth:`compare` method, except that all
      NaNs signal.  That is, if neither operand is a signaling NaN then any
      quiet NaN operand is treated as though it were a signaling NaN.

      .. versionadded:: 2.6

   .. method:: compare_total(other)

      Compare two operands using their abstract representation rather than their
      numerical value.  Similar to the :meth:`compare` method, but the result
      gives a total ordering on :class:`Decimal` instances.  Two
      :class:`Decimal` instances with the same numeric value but different
      representations compare unequal in this ordering:

         >>> Decimal('12.0').compare_total(Decimal('12'))
         Decimal('-1')

      Quiet and signaling NaNs are also included in the total ordering.  The
      result of this function is ``Decimal('0')`` if both operands have the same
      representation, ``Decimal('-1')`` if the first operand is lower in the
      total order than the second, and ``Decimal('1')`` if the first operand is
      higher in the total order than the second operand.  See the specification
      for details of the total order.

      .. versionadded:: 2.6

   .. method:: compare_total_mag(other)

      Compare two operands using their abstract representation rather than their
      value as in :meth:`compare_total`, but ignoring the sign of each operand.
      ``x.compare_total_mag(y)`` is equivalent to
      ``x.copy_abs().compare_total(y.copy_abs())``.

      .. versionadded:: 2.6

   .. method:: conjugate()

      Just returns self, this method is only to comply with the Decimal
      Specification.

      .. versionadded:: 2.6

   .. method:: copy_abs()

      Return the absolute value of the argument.  This operation is unaffected
      by the context and is quiet: no flags are changed and no rounding is
      performed.

      .. versionadded:: 2.6

   .. method:: copy_negate()

      Return the negation of the argument.  This operation is unaffected by the
      context and is quiet: no flags are changed and no rounding is performed.

      .. versionadded:: 2.6

   .. method:: copy_sign(other)

      Return a copy of the first operand with the sign set to be the same as the
      sign of the second operand.  For example:

         >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
         Decimal('-2.3')

      This operation is unaffected by the context and is quiet: no flags are
      changed and no rounding is performed.

      .. versionadded:: 2.6

   .. method:: exp([context])

      Return the value of the (natural) exponential function ``e**x`` at the
      given number.  The result is correctly rounded using the
      :const:`ROUND_HALF_EVEN` rounding mode.

      >>> Decimal(1).exp()
      Decimal('2.718281828459045235360287471')
      >>> Decimal(321).exp()
      Decimal('2.561702493119680037517373933E+139')

      .. versionadded:: 2.6

   .. method:: from_float(f)

      Classmethod that converts a float to a decimal number, exactly.

      Note `Decimal.from_float(0.1)` is not the same as `Decimal('0.1')`.
      Since 0.1 is not exactly representable in binary floating point, the
      value is stored as the nearest representable value which is
      `0x1.999999999999ap-4`.  That equivalent value in decimal is
      `0.1000000000000000055511151231257827021181583404541015625`.

      .. note:: From Python 2.7 onwards, a :class:`Decimal` instance
         can also be constructed directly from a :class:`float`.

      .. doctest::

          >>> Decimal.from_float(0.1)
          Decimal('0.1000000000000000055511151231257827021181583404541015625')
          >>> Decimal.from_float(float('nan'))
          Decimal('NaN')
          >>> Decimal.from_float(float('inf'))
          Decimal('Infinity')
          >>> Decimal.from_float(float('-inf'))
          Decimal('-Infinity')

      .. versionadded:: 2.7

   .. method:: fma(other, third[, context])

      Fused multiply-add.  Return self*other+third with no rounding of the
      intermediate product self*other.

      >>> Decimal(2).fma(3, 5)
      Decimal('11')

      .. versionadded:: 2.6

   .. method:: is_canonical()

      Return :const:`True` if the argument is canonical and :const:`False`
      otherwise.  Currently, a :class:`Decimal` instance is always canonical, so
      this operation always returns :const:`True`.

      .. versionadded:: 2.6

   .. method:: is_finite()

      Return :const:`True` if the argument is a finite number, and
      :const:`False` if the argument is an infinity or a NaN.

      .. versionadded:: 2.6

   .. method:: is_infinite()

      Return :const:`True` if the argument is either positive or negative
      infinity and :const:`False` otherwise.

      .. versionadded:: 2.6

   .. method:: is_nan()

      Return :const:`True` if the argument is a (quiet or signaling) NaN and
      :const:`False` otherwise.

      .. versionadded:: 2.6

   .. method:: is_normal()

      Return :const:`True` if the argument is a *normal* finite non-zero
      number with an adjusted exponent greater than or equal to *Emin*.
      Return :const:`False` if the argument is zero, subnormal, infinite or a
      NaN.  Note, the term *normal* is used here in a different sense with
      the :meth:`normalize` method which is used to create canonical values.

      .. versionadded:: 2.6

   .. method:: is_qnan()

      Return :const:`True` if the argument is a quiet NaN, and
      :const:`False` otherwise.

      .. versionadded:: 2.6

   .. method:: is_signed()

      Return :const:`True` if the argument has a negative sign and
      :const:`False` otherwise.  Note that zeros and NaNs can both carry signs.

      .. versionadded:: 2.6

   .. method:: is_snan()

      Return :const:`True` if the argument is a signaling NaN and :const:`False`
      otherwise.

      .. versionadded:: 2.6

   .. method:: is_subnormal()

      Return :const:`True` if the argument is subnormal, and :const:`False`
      otherwise. A number is subnormal is if it is nonzero, finite, and has an
      adjusted exponent less than *Emin*.

      .. versionadded:: 2.6

   .. method:: is_zero()

      Return :const:`True` if the argument is a (positive or negative) zero and
      :const:`False` otherwise.

      .. versionadded:: 2.6

   .. method:: ln([context])

      Return the natural (base e) logarithm of the operand.  The result is
      correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.

      .. versionadded:: 2.6

   .. method:: log10([context])

      Return the base ten logarithm of the operand.  The result is correctly
      rounded using the :const:`ROUND_HALF_EVEN` rounding mode.

      .. versionadded:: 2.6

   .. method:: logb([context])

      For a nonzero number, return the adjusted exponent of its operand as a
      :class:`Decimal` instance.  If the operand is a zero then
      ``Decimal('-Infinity')`` is returned and the :const:`DivisionByZero` flag
      is raised.  If the operand is an infinity then ``Decimal('Infinity')`` is
      returned.

      .. versionadded:: 2.6

   .. method:: logical_and(other[, context])

      :meth:`logical_and` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise ``and`` of the two operands.

      .. versionadded:: 2.6

   .. method:: logical_invert([context])

      :meth:`logical_invert` is a logical operation.  The
      result is the digit-wise inversion of the operand.

      .. versionadded:: 2.6

   .. method:: logical_or(other[, context])

      :meth:`logical_or` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise ``or`` of the two operands.

      .. versionadded:: 2.6

   .. method:: logical_xor(other[, context])

      :meth:`logical_xor` is a logical operation which takes two *logical
      operands* (see :ref:`logical_operands_label`).  The result is the
      digit-wise exclusive or of the two operands.

      .. versionadded:: 2.6

   .. method:: max(other[, context])

      Like ``max(self, other)`` except that the context rounding rule is applied
      before returning and that :const:`NaN` values are either signaled or
      ignored (depending on the context and whether they are signaling or
      quiet).

   .. method:: max_mag(other[, context])

      Similar to the :meth:`.max` method, but the comparison is done using the
      absolute values of the operands.

      .. versionadded:: 2.6

   .. method:: min(other[, context])

      Like ``min(self, other)`` except that the context rounding rule is applied
      before returning and that :const:`NaN` values are either signaled or
      ignored (depending on the context and whether they are signaling or
      quiet).

   .. method:: min_mag(other[, context])

      Similar to the :meth:`.min` method, but the comparison is done using the
      absolute values of the operands.

      .. versionadded:: 2.6

   .. method:: next_minus([context])

      Return the largest number representable in the given context (or in the
      current thread's context if no context is given) that is smaller than the
      given operand.

      .. versionadded:: 2.6

   .. method:: next_plus([context])

      Return the smallest number representable in the given context (or in the
      current thread's context if no context is given) that is larger than the
      given operand.

      .. versionadded:: 2.6

   .. method:: next_toward(other[, context])

      If the two operands are unequal, return the number closest to the first
      operand in the direction of the second operand.  If both operands are
      numerically equal, return a copy of the first operand with the sign set to
      be the same as the sign of the second operand.

      .. versionadded:: 2.6

   .. method:: normalize([context])

      Normalize the number by stripping the rightmost trailing zeros and
      converting any result equal to :const:`Decimal('0')` to
      :const:`Decimal('0e0')`. Used for producing canonical values for attributes
      of an equivalence class. For example, ``Decimal('32.100')`` and
      ``Decimal('0.321000e+2')`` both normalize to the equivalent value
      ``Decimal('32.1')``.

   .. method:: number_class([context])

      Return a string describing the *class* of the operand.  The returned value
      is one of the following ten strings.

      * ``"-Infinity"``, indicating that the operand is negative infinity.
      * ``"-Normal"``, indicating that the operand is a negative normal number.
      * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
      * ``"-Zero"``, indicating that the operand is a negative zero.
      * ``"+Zero"``, indicating that the operand is a positive zero.
      * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
      * ``"+Normal"``, indicating that the operand is a positive normal number.
      * ``"+Infinity"``, indicating that the operand is positive infinity.
      * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
      * ``"sNaN"``, indicating that the operand is a signaling NaN.

      .. versionadded:: 2.6

   .. method:: quantize(exp[, rounding[, context[, watchexp]]])

      Return a value equal to the first operand after rounding and having the
      exponent of the second operand.

      >>> Decimal('1.41421356').quantize(Decimal('1.000'))
      Decimal('1.414')

      Unlike other operations, if the length of the coefficient after the
      quantize operation would be greater than precision, then an
      :const:`InvalidOperation` is signaled. This guarantees that, unless there
      is an error condition, the quantized exponent is always equal to that of
      the right-hand operand.

      Also unlike other operations, quantize never signals Underflow, even if
      the result is subnormal and inexact.

      If the exponent of the second operand is larger than that of the first
      then rounding may be necessary.  In this case, the rounding mode is
      determined by the ``rounding`` argument if given, else by the given
      ``context`` argument; if neither argument is given the rounding mode of
      the current thread's context is used.

      If *watchexp* is set (default), then an error is returned whenever the
      resulting exponent is greater than :attr:`Emax` or less than
      :attr:`Etiny`.

   .. method:: radix()

      Return ``Decimal(10)``, the radix (base) in which the :class:`Decimal`
      class does all its arithmetic.  Included for compatibility with the
      specification.

      .. versionadded:: 2.6

   .. method:: remainder_near(other[, context])

      Return the remainder from dividing *self* by *other*.  This differs from
      ``self % other`` in that the sign of the remainder is chosen so as to
      minimize its absolute value.  More precisely, the return value is
      ``self - n * other`` where ``n`` is the integer nearest to the exact
      value of ``self / other``, and if two integers are equally near then the
      even one is chosen.

      If the result is zero then its sign will be the sign of *self*.

      >>> Decimal(18).remainder_near(Decimal(10))
      Decimal('-2')
      >>> Decimal(25).remainder_near(Decimal(10))
      Decimal('5')
      >>> Decimal(35).remainder_near(Decimal(10))
      Decimal('-5')

   .. method:: rotate(other[, context])

      Return the result of rotating the digits of the first operand by an amount
      specified by the second operand.  The second operand must be an integer in
      the range -precision through precision.  The absolute value of the second
      operand gives the number of places to rotate.  If the second operand is
      positive then rotation is to the left; otherwise rotation is to the right.
      The coefficient of the first operand is padded on the left with zeros to
      length precision if necessary.  The sign and exponent of the first operand
      are unchanged.

      .. versionadded:: 2.6

   .. method:: same_quantum(other[, context])

      Test whether self and other have the same exponent or whether both are
      :const:`NaN`.

   .. method:: scaleb(other[, context])

      Return the first operand with exponent adjusted by the second.
      Equivalently, return the first operand multiplied by ``10**other``.  The
      second operand must be an integer.

      .. versionadded:: 2.6

   .. method:: shift(other[, context])

      Return the result of shifting the digits of the first operand by an amount
      specified by the second operand.  The second operand must be an integer in
      the range -precision through precision.  The absolute value of the second
      operand gives the number of places to shift.  If the second operand is
      positive then the shift is to the left; otherwise the shift is to the
      right.  Digits shifted into the coefficient are zeros.  The sign and
      exponent of the first operand are unchanged.

      .. versionadded:: 2.6

   .. method:: sqrt([context])

      Return the square root of the argument to full precision.


   .. method:: to_eng_string([context])

      Convert to a string, using engineering notation if an exponent is needed.

      Engineering notation has an exponent which is a multiple of 3.  This
      can leave up to 3 digits to the left of the decimal place and may
      require the addition of either one or two trailing zeros.

      For example, this converts ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``.

   .. method:: to_integral([rounding[, context]])

      Identical to the :meth:`to_integral_value` method.  The ``to_integral``
      name has been kept for compatibility with older versions.

   .. method:: to_integral_exact([rounding[, context]])

      Round to the nearest integer, signaling :const:`Inexact` or
      :const:`Rounded` as appropriate if rounding occurs.  The rounding mode is
      determined by the ``rounding`` parameter if given, else by the given
      ``context``.  If neither parameter is given then the rounding mode of the
      current context is used.

      .. versionadded:: 2.6

   .. method:: to_integral_value([rounding[, context]])

      Round to the nearest integer without signaling :const:`Inexact` or
      :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the
      rounding method in either the supplied *context* or the current context.

      .. versionchanged:: 2.6
         renamed from ``to_integral`` to ``to_integral_value``.  The old name
         remains valid for compatibility.

.. _logical_operands_label:

Logical operands
^^^^^^^^^^^^^^^^

The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
and :meth:`logical_xor` methods expect their arguments to be *logical
operands*.  A *logical operand* is a :class:`Decimal` instance whose
exponent and sign are both zero, and whose digits are all either
:const:`0` or :const:`1`.

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-context:

Context objects
---------------

Contexts are environments for arithmetic operations.  They govern precision, set
rules for rounding, determine which signals are treated as exceptions, and limit
the range for exponents.

Each thread has its own current context which is accessed or changed using the
:func:`getcontext` and :func:`setcontext` functions:


.. function:: getcontext()

   Return the current context for the active thread.


.. function:: setcontext(c)

   Set the current context for the active thread to *c*.

Beginning with Python 2.5, you can also use the :keyword:`with` statement and
the :func:`localcontext` function to temporarily change the active context.


.. function:: localcontext([c])

   Return a context manager that will set the current context for the active thread
   to a copy of *c* on entry to the with-statement and restore the previous context
   when exiting the with-statement. If no context is specified, a copy of the
   current context is used.

   .. versionadded:: 2.5

   For example, the following code sets the current decimal precision to 42 places,
   performs a calculation, and then automatically restores the previous context::

      from decimal import localcontext

      with localcontext() as ctx:
          ctx.prec = 42   # Perform a high precision calculation
          s = calculate_something()
      s = +s  # Round the final result back to the default precision

      with localcontext(BasicContext):      # temporarily use the BasicContext
          print Decimal(1) / Decimal(7)
          print Decimal(355) / Decimal(113)

New contexts can also be created using the :class:`Context` constructor
described below. In addition, the module provides three pre-made contexts:


.. class:: BasicContext

   This is a standard context defined by the General Decimal Arithmetic
   Specification.  Precision is set to nine.  Rounding is set to
   :const:`ROUND_HALF_UP`.  All flags are cleared.  All traps are enabled (treated
   as exceptions) except :const:`Inexact`, :const:`Rounded`, and
   :const:`Subnormal`.

   Because many of the traps are enabled, this context is useful for debugging.


.. class:: ExtendedContext

   This is a standard context defined by the General Decimal Arithmetic
   Specification.  Precision is set to nine.  Rounding is set to
   :const:`ROUND_HALF_EVEN`.  All flags are cleared.  No traps are enabled (so that
   exceptions are not raised during computations).

   Because the traps are disabled, this context is useful for applications that
   prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
   raising exceptions.  This allows an application to complete a run in the
   presence of conditions that would otherwise halt the program.


.. class:: DefaultContext

   This context is used by the :class:`Context` constructor as a prototype for new
   contexts.  Changing a field (such a precision) has the effect of changing the
   default for new contexts created by the :class:`Context` constructor.

   This context is most useful in multi-threaded environments.  Changing one of the
   fields before threads are started has the effect of setting system-wide
   defaults.  Changing the fields after threads have started is not recommended as
   it would require thread synchronization to prevent race conditions.

   In single threaded environments, it is preferable to not use this context at
   all.  Instead, simply create contexts explicitly as described below.

   The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
   for Overflow, InvalidOperation, and DivisionByZero.

In addition to the three supplied contexts, new contexts can be created with the
:class:`Context` constructor.


.. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)

   Creates a new context.  If a field is not specified or is :const:`None`, the
   default values are copied from the :const:`DefaultContext`.  If the *flags*
   field is not specified or is :const:`None`, all flags are cleared.

   The *prec* field is a positive integer that sets the precision for arithmetic
   operations in the context.

   The *rounding* option is one of:

   * :const:`ROUND_CEILING` (towards :const:`Infinity`),
   * :const:`ROUND_DOWN` (towards zero),
   * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
   * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
   * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
   * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
   * :const:`ROUND_UP` (away from zero).
   * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero
     would have been 0 or 5; otherwise towards zero)

   The *traps* and *flags* fields list any signals to be set. Generally, new
   contexts should only set traps and leave the flags clear.

   The *Emin* and *Emax* fields are integers specifying the outer limits allowable
   for exponents.

   The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
   :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
   lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.

   .. versionchanged:: 2.6
      The :const:`ROUND_05UP` rounding mode was added.

   The :class:`Context` class defines several general purpose methods as well as
   a large number of methods for doing arithmetic directly in a given context.
   In addition, for each of the :class:`Decimal` methods described above (with
   the exception of the :meth:`adjusted` and :meth:`as_tuple` methods) there is
   a corresponding :class:`Context` method.  For example, for a :class:`Context`
   instance ``C`` and :class:`Decimal` instance ``x``, ``C.exp(x)`` is
   equivalent to ``x.exp(context=C)``.  Each :class:`Context` method accepts a
   Python integer (an instance of :class:`int` or :class:`long`) anywhere that a
   Decimal instance is accepted.


   .. method:: clear_flags()

      Resets all of the flags to :const:`0`.

   .. method:: copy()

      Return a duplicate of the context.

   .. method:: copy_decimal(num)

      Return a copy of the Decimal instance num.

   .. method:: create_decimal(num)

      Creates a new Decimal instance from *num* but using *self* as
      context. Unlike the :class:`Decimal` constructor, the context precision,
      rounding method, flags, and traps are applied to the conversion.

      This is useful because constants are often given to a greater precision
      than is needed by the application.  Another benefit is that rounding
      immediately eliminates unintended effects from digits beyond the current
      precision. In the following example, using unrounded inputs means that
      adding zero to a sum can change the result:

      .. doctest:: newcontext

         >>> getcontext().prec = 3
         >>> Decimal('3.4445') + Decimal('1.0023')
         Decimal('4.45')
         >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
         Decimal('4.44')

      This method implements the to-number operation of the IBM specification.
      If the argument is a string, no leading or trailing whitespace is
      permitted.

   .. method:: create_decimal_from_float(f)

      Creates a new Decimal instance from a float *f* but rounding using *self*
      as the context.  Unlike the :meth:`Decimal.from_float` class method,
      the context precision, rounding method, flags, and traps are applied to
      the conversion.

      .. doctest::

         >>> context = Context(prec=5, rounding=ROUND_DOWN)
         >>> context.create_decimal_from_float(math.pi)
         Decimal('3.1415')
         >>> context = Context(prec=5, traps=[Inexact])
         >>> context.create_decimal_from_float(math.pi)
         Traceback (most recent call last):
             ...
         Inexact: None

      .. versionadded:: 2.7

   .. method:: Etiny()

      Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent
      value for subnormal results.  When underflow occurs, the exponent is set
      to :const:`Etiny`.


   .. method:: Etop()

      Returns a value equal to ``Emax - prec + 1``.

   The usual approach to working with decimals is to create :class:`Decimal`
   instances and then apply arithmetic operations which take place within the
   current context for the active thread.  An alternative approach is to use
   context methods for calculating within a specific context.  The methods are
   similar to those for the :class:`Decimal` class and are only briefly
   recounted here.


   .. method:: abs(x)

      Returns the absolute value of *x*.


   .. method:: add(x, y)

      Return the sum of *x* and *y*.


   .. method:: canonical(x)

      Returns the same Decimal object *x*.


   .. method:: compare(x, y)

      Compares *x* and *y* numerically.


   .. method:: compare_signal(x, y)

      Compares the values of the two operands numerically.


   .. method:: compare_total(x, y)

      Compares two operands using their abstract representation.


   .. method:: compare_total_mag(x, y)

      Compares two operands using their abstract representation, ignoring sign.


   .. method:: copy_abs(x)

      Returns a copy of *x* with the sign set to 0.


   .. method:: copy_negate(x)

      Returns a copy of *x* with the sign inverted.


   .. method:: copy_sign(x, y)

      Copies the sign from *y* to *x*.


   .. method:: divide(x, y)

      Return *x* divided by *y*.


   .. method:: divide_int(x, y)

      Return *x* divided by *y*, truncated to an integer.


   .. method:: divmod(x, y)

      Divides two numbers and returns the integer part of the result.


   .. method:: exp(x)

      Returns `e ** x`.


   .. method:: fma(x, y, z)

      Returns *x* multiplied by *y*, plus *z*.


   .. method:: is_canonical(x)

      Returns ``True`` if *x* is canonical; otherwise returns ``False``.


   .. method:: is_finite(x)

      Returns ``True`` if *x* is finite; otherwise returns ``False``.


   .. method:: is_infinite(x)

      Returns ``True`` if *x* is infinite; otherwise returns ``False``.


   .. method:: is_nan(x)

      Returns ``True`` if *x* is a qNaN or sNaN; otherwise returns ``False``.


   .. method:: is_normal(x)

      Returns ``True`` if *x* is a normal number; otherwise returns ``False``.


   .. method:: is_qnan(x)

      Returns ``True`` if *x* is a quiet NaN; otherwise returns ``False``.


   .. method:: is_signed(x)

      Returns ``True`` if *x* is negative; otherwise returns ``False``.


   .. method:: is_snan(x)

      Returns ``True`` if *x* is a signaling NaN; otherwise returns ``False``.


   .. method:: is_subnormal(x)

      Returns ``True`` if *x* is subnormal; otherwise returns ``False``.


   .. method:: is_zero(x)

      Returns ``True`` if *x* is a zero; otherwise returns ``False``.


   .. method:: ln(x)

      Returns the natural (base e) logarithm of *x*.


   .. method:: log10(x)

      Returns the base 10 logarithm of *x*.


   .. method:: logb(x)

       Returns the exponent of the magnitude of the operand's MSD.


   .. method:: logical_and(x, y)

      Applies the logical operation *and* between each operand's digits.


   .. method:: logical_invert(x)

      Invert all the digits in *x*.


   .. method:: logical_or(x, y)

      Applies the logical operation *or* between each operand's digits.


   .. method:: logical_xor(x, y)

      Applies the logical operation *xor* between each operand's digits.


   .. method:: max(x, y)

      Compares two values numerically and returns the maximum.


   .. method:: max_mag(x, y)

      Compares the values numerically with their sign ignored.


   .. method:: min(x, y)

      Compares two values numerically and returns the minimum.


   .. method:: min_mag(x, y)

      Compares the values numerically with their sign ignored.


   .. method:: minus(x)

      Minus corresponds to the unary prefix minus operator in Python.


   .. method:: multiply(x, y)

      Return the product of *x* and *y*.


   .. method:: next_minus(x)

      Returns the largest representable number smaller than *x*.


   .. method:: next_plus(x)

      Returns the smallest representable number larger than *x*.


   .. method:: next_toward(x, y)

      Returns the number closest to *x*, in direction towards *y*.


   .. method:: normalize(x)

      Reduces *x* to its simplest form.


   .. method:: number_class(x)

      Returns an indication of the class of *x*.


   .. method:: plus(x)

      Plus corresponds to the unary prefix plus operator in Python.  This
      operation applies the context precision and rounding, so it is *not* an
      identity operation.


   .. method:: power(x, y[, modulo])

      Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if given.

      With two arguments, compute ``x**y``.  If ``x`` is negative then ``y``
      must be integral.  The result will be inexact unless ``y`` is integral and
      the result is finite and can be expressed exactly in 'precision' digits.
      The result should always be correctly rounded, using the rounding mode of
      the current thread's context.

      With three arguments, compute ``(x**y) % modulo``.  For the three argument
      form, the following restrictions on the arguments hold:

         - all three arguments must be integral
         - ``y`` must be nonnegative
         - at least one of ``x`` or ``y`` must be nonzero
         - ``modulo`` must be nonzero and have at most 'precision' digits

      The value resulting from ``Context.power(x, y, modulo)`` is
      equal to the value that would be obtained by computing ``(x**y)
      % modulo`` with unbounded precision, but is computed more
      efficiently.  The exponent of the result is zero, regardless of
      the exponents of ``x``, ``y`` and ``modulo``.  The result is
      always exact.

      .. versionchanged:: 2.6
         ``y`` may now be nonintegral in ``x**y``.
         Stricter requirements for the three-argument version.


   .. method:: quantize(x, y)

      Returns a value equal to *x* (rounded), having the exponent of *y*.


   .. method:: radix()

      Just returns 10, as this is Decimal, :)


   .. method:: remainder(x, y)

      Returns the remainder from integer division.

      The sign of the result, if non-zero, is the same as that of the original
      dividend.

   .. method:: remainder_near(x, y)

      Returns ``x - y * n``, where *n* is the integer nearest the exact value
      of ``x / y`` (if the result is 0 then its sign will be the sign of *x*).


   .. method:: rotate(x, y)

      Returns a rotated copy of *x*, *y* times.


   .. method:: same_quantum(x, y)

      Returns ``True`` if the two operands have the same exponent.


   .. method:: scaleb (x, y)

      Returns the first operand after adding the second value its exp.


   .. method:: shift(x, y)

      Returns a shifted copy of *x*, *y* times.


   .. method:: sqrt(x)

      Square root of a non-negative number to context precision.


   .. method:: subtract(x, y)

      Return the difference between *x* and *y*.


   .. method:: to_eng_string(x)

      Convert to a string, using engineering notation if an exponent is needed.

      Engineering notation has an exponent which is a multiple of 3.  This
      can leave up to 3 digits to the left of the decimal place and may
      require the addition of either one or two trailing zeros.


   .. method:: to_integral_exact(x)

      Rounds to an integer.


   .. method:: to_sci_string(x)

      Converts a number to a string using scientific notation.

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-signals:

Signals
-------

Signals represent conditions that arise during computation. Each corresponds to
one context flag and one context trap enabler.

The context flag is set whenever the condition is encountered. After the
computation, flags may be checked for informational purposes (for instance, to
determine whether a computation was exact). After checking the flags, be sure to
clear all flags before starting the next computation.

If the context's trap enabler is set for the signal, then the condition causes a
Python exception to be raised.  For example, if the :class:`DivisionByZero` trap
is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
condition.


.. class:: Clamped

   Altered an exponent to fit representation constraints.

   Typically, clamping occurs when an exponent falls outside the context's
   :attr:`Emin` and :attr:`Emax` limits.  If possible, the exponent is reduced to
   fit by adding zeros to the coefficient.


.. class:: DecimalException

   Base class for other signals and a subclass of :exc:`ArithmeticError`.


.. class:: DivisionByZero

   Signals the division of a non-infinite number by zero.

   Can occur with division, modulo division, or when raising a number to a negative
   power.  If this signal is not trapped, returns :const:`Infinity` or
   :const:`-Infinity` with the sign determined by the inputs to the calculation.


.. class:: Inexact

   Indicates that rounding occurred and the result is not exact.

   Signals when non-zero digits were discarded during rounding. The rounded result
   is returned.  The signal flag or trap is used to detect when results are
   inexact.


.. class:: InvalidOperation

   An invalid operation was performed.

   Indicates that an operation was requested that does not make sense. If not
   trapped, returns :const:`NaN`.  Possible causes include::

      Infinity - Infinity
      0 * Infinity
      Infinity / Infinity
      x % 0
      Infinity % x
      x._rescale( non-integer )
      sqrt(-x) and x > 0
      0 ** 0
      x ** (non-integer)
      x ** Infinity


.. class:: Overflow

   Numerical overflow.

   Indicates the exponent is larger than :attr:`Emax` after rounding has
   occurred.  If not trapped, the result depends on the rounding mode, either
   pulling inward to the largest representable finite number or rounding outward
   to :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded`
   are also signaled.


.. class:: Rounded

   Rounding occurred though possibly no information was lost.

   Signaled whenever rounding discards digits; even if those digits are zero
   (such as rounding :const:`5.00` to :const:`5.0`).  If not trapped, returns
   the result unchanged.  This signal is used to detect loss of significant
   digits.


.. class:: Subnormal

   Exponent was lower than :attr:`Emin` prior to rounding.

   Occurs when an operation result is subnormal (the exponent is too small). If
   not trapped, returns the result unchanged.


.. class:: Underflow

   Numerical underflow with result rounded to zero.

   Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
   and :class:`Subnormal` are also signaled.

The following table summarizes the hierarchy of signals::

   exceptions.ArithmeticError(exceptions.StandardError)
       DecimalException
           Clamped
           DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
           Inexact
               Overflow(Inexact, Rounded)
               Underflow(Inexact, Rounded, Subnormal)
           InvalidOperation
           Rounded
           Subnormal

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-notes:

Floating Point Notes
--------------------


Mitigating round-off error with increased precision
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The use of decimal floating point eliminates decimal representation error
(making it possible to represent :const:`0.1` exactly); however, some operations
can still incur round-off error when non-zero digits exceed the fixed precision.

The effects of round-off error can be amplified by the addition or subtraction
of nearly offsetting quantities resulting in loss of significance.  Knuth
provides two instructive examples where rounded floating point arithmetic with
insufficient precision causes the breakdown of the associative and distributive
properties of addition:

.. doctest:: newcontext

   # Examples from Seminumerical Algorithms, Section 4.2.2.
   >>> from decimal import Decimal, getcontext
   >>> getcontext().prec = 8

   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
   >>> (u + v) + w
   Decimal('9.5111111')
   >>> u + (v + w)
   Decimal('10')

   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
   >>> (u*v) + (u*w)
   Decimal('0.01')
   >>> u * (v+w)
   Decimal('0.0060000')

The :mod:`decimal` module makes it possible to restore the identities by
expanding the precision sufficiently to avoid loss of significance:

.. doctest:: newcontext

   >>> getcontext().prec = 20
   >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
   >>> (u + v) + w
   Decimal('9.51111111')
   >>> u + (v + w)
   Decimal('9.51111111')
   >>>
   >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
   >>> (u*v) + (u*w)
   Decimal('0.0060000')
   >>> u * (v+w)
   Decimal('0.0060000')


Special values
^^^^^^^^^^^^^^

The number system for the :mod:`decimal` module provides special values
including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
and two zeros, :const:`+0` and :const:`-0`.

Infinities can be constructed directly with:  ``Decimal('Infinity')``. Also,
they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
not trapped.  Likewise, when the :exc:`Overflow` signal is not trapped, infinity
can result from rounding beyond the limits of the largest representable number.

The infinities are signed (affine) and can be used in arithmetic operations
where they get treated as very large, indeterminate numbers.  For instance,
adding a constant to infinity gives another infinite result.

Some operations are indeterminate and return :const:`NaN`, or if the
:exc:`InvalidOperation` signal is trapped, raise an exception.  For example,
``0/0`` returns :const:`NaN` which means "not a number".  This variety of
:const:`NaN` is quiet and, once created, will flow through other computations
always resulting in another :const:`NaN`.  This behavior can be useful for a
series of computations that occasionally have missing inputs --- it allows the
calculation to proceed while flagging specific results as invalid.

A variant is :const:`sNaN` which signals rather than remaining quiet after every
operation.  This is a useful return value when an invalid result needs to
interrupt a calculation for special handling.

The behavior of Python's comparison operators can be a little surprising where a
:const:`NaN` is involved.  A test for equality where one of the operands is a
quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
:const:`True`.  An attempt to compare two Decimals using any of the ``<``,
``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
if either operand is a :const:`NaN`, and return :const:`False` if this signal is
not trapped.  Note that the General Decimal Arithmetic specification does not
specify the behavior of direct comparisons; these rules for comparisons
involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
section 5.7).  To ensure strict standards-compliance, use the :meth:`compare`
and :meth:`compare-signal` methods instead.

The signed zeros can result from calculations that underflow. They keep the sign
that would have resulted if the calculation had been carried out to greater
precision.  Since their magnitude is zero, both positive and negative zeros are
treated as equal and their sign is informational.

In addition to the two signed zeros which are distinct yet equal, there are
various representations of zero with differing precisions yet equivalent in
value.  This takes a bit of getting used to.  For an eye accustomed to
normalized floating point representations, it is not immediately obvious that
the following calculation returns a value equal to zero:

   >>> 1 / Decimal('Infinity')
   Decimal('0E-1000000026')

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-threads:

Working with threads
--------------------

The :func:`getcontext` function accesses a different :class:`Context` object for
each thread.  Having separate thread contexts means that threads may make
changes (such as ``getcontext.prec=10``) without interfering with other threads.

Likewise, the :func:`setcontext` function automatically assigns its target to
the current thread.

If :func:`setcontext` has not been called before :func:`getcontext`, then
:func:`getcontext` will automatically create a new context for use in the
current thread.

The new context is copied from a prototype context called *DefaultContext*. To
control the defaults so that each thread will use the same values throughout the
application, directly modify the *DefaultContext* object. This should be done
*before* any threads are started so that there won't be a race condition between
threads calling :func:`getcontext`. For example::

   # Set applicationwide defaults for all threads about to be launched
   DefaultContext.prec = 12
   DefaultContext.rounding = ROUND_DOWN
   DefaultContext.traps = ExtendedContext.traps.copy()
   DefaultContext.traps[InvalidOperation] = 1
   setcontext(DefaultContext)

   # Afterwards, the threads can be started
   t1.start()
   t2.start()
   t3.start()
    . . .

.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-recipes:

Recipes
-------

Here are a few recipes that serve as utility functions and that demonstrate ways
to work with the :class:`Decimal` class::

   def moneyfmt(value, places=2, curr='', sep=',', dp='.',
                pos='', neg='-', trailneg=''):
       """Convert Decimal to a money formatted string.

       places:  required number of places after the decimal point
       curr:    optional currency symbol before the sign (may be blank)
       sep:     optional grouping separator (comma, period, space, or blank)
       dp:      decimal point indicator (comma or period)
                only specify as blank when places is zero
       pos:     optional sign for positive numbers: '+', space or blank
       neg:     optional sign for negative numbers: '-', '(', space or blank
       trailneg:optional trailing minus indicator:  '-', ')', space or blank

       >>> d = Decimal('-1234567.8901')
       >>> moneyfmt(d, curr='$')
       '-$1,234,567.89'
       >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
       '1.234.568-'
       >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
       '($1,234,567.89)'
       >>> moneyfmt(Decimal(123456789), sep=' ')
       '123 456 789.00'
       >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
       '<0.02>'

       """
       q = Decimal(10) ** -places      # 2 places --> '0.01'
       sign, digits, exp = value.quantize(q).as_tuple()
       result = []
       digits = map(str, digits)
       build, next = result.append, digits.pop
       if sign:
           build(trailneg)
       for i in range(places):
           build(next() if digits else '0')
       build(dp)
       if not digits:
           build('0')
       i = 0
       while digits:
           build(next())
           i += 1
           if i == 3 and digits:
               i = 0
               build(sep)
       build(curr)
       build(neg if sign else pos)
       return ''.join(reversed(result))

   def pi():
       """Compute Pi to the current precision.

       >>> print pi()
       3.141592653589793238462643383

       """
       getcontext().prec += 2  # extra digits for intermediate steps
       three = Decimal(3)      # substitute "three=3.0" for regular floats
       lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
       while s != lasts:
           lasts = s
           n, na = n+na, na+8
           d, da = d+da, da+32
           t = (t * n) / d
           s += t
       getcontext().prec -= 2
       return +s               # unary plus applies the new precision

   def exp(x):
       """Return e raised to the power of x.  Result type matches input type.

       >>> print exp(Decimal(1))
       2.718281828459045235360287471
       >>> print exp(Decimal(2))
       7.389056098930650227230427461
       >>> print exp(2.0)
       7.38905609893
       >>> print exp(2+0j)
       (7.38905609893+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num = 0, 0, 1, 1, 1
       while s != lasts:
           lasts = s
           i += 1
           fact *= i
           num *= x
           s += num / fact
       getcontext().prec -= 2
       return +s

   def cos(x):
       """Return the cosine of x as measured in radians.

       >>> print cos(Decimal('0.5'))
       0.8775825618903727161162815826
       >>> print cos(0.5)
       0.87758256189
       >>> print cos(0.5+0j)
       (0.87758256189+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
       while s != lasts:
           lasts = s
           i += 2
           fact *= i * (i-1)
           num *= x * x
           sign *= -1
           s += num / fact * sign
       getcontext().prec -= 2
       return +s

   def sin(x):
       """Return the sine of x as measured in radians.

       >>> print sin(Decimal('0.5'))
       0.4794255386042030002732879352
       >>> print sin(0.5)
       0.479425538604
       >>> print sin(0.5+0j)
       (0.479425538604+0j)

       """
       getcontext().prec += 2
       i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
       while s != lasts:
           lasts = s
           i += 2
           fact *= i * (i-1)
           num *= x * x
           sign *= -1
           s += num / fact * sign
       getcontext().prec -= 2
       return +s


.. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


.. _decimal-faq:

Decimal FAQ
-----------

Q. It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to
minimize typing when using the interactive interpreter?

A. Some users abbreviate the constructor to just a single letter:

   >>> D = decimal.Decimal
   >>> D('1.23') + D('3.45')
   Decimal('4.68')

Q. In a fixed-point application with two decimal places, some inputs have many
places and need to be rounded.  Others are not supposed to have excess digits
and need to be validated.  What methods should be used?

A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
the :const:`Inexact` trap is set, it is also useful for validation:

   >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')

   >>> # Round to two places
   >>> Decimal('3.214').quantize(TWOPLACES)
   Decimal('3.21')

   >>> # Validate that a number does not exceed two places
   >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
   Decimal('3.21')

   >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
   Traceback (most recent call last):
      ...
   Inexact: None

Q. Once I have valid two place inputs, how do I maintain that invariant
throughout an application?

A. Some operations like addition, subtraction, and multiplication by an integer
will automatically preserve fixed point.  Others operations, like division and
non-integer multiplication, will change the number of decimal places and need to
be followed-up with a :meth:`quantize` step:

    >>> a = Decimal('102.72')           # Initial fixed-point values
    >>> b = Decimal('3.17')
    >>> a + b                           # Addition preserves fixed-point
    Decimal('105.89')
    >>> a - b
    Decimal('99.55')
    >>> a * 42                          # So does integer multiplication
    Decimal('4314.24')
    >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
    Decimal('325.62')
    >>> (b / a).quantize(TWOPLACES)     # And quantize division
    Decimal('0.03')

In developing fixed-point applications, it is convenient to define functions
to handle the :meth:`quantize` step:

    >>> def mul(x, y, fp=TWOPLACES):
    ...     return (x * y).quantize(fp)
    >>> def div(x, y, fp=TWOPLACES):
    ...     return (x / y).quantize(fp)

    >>> mul(a, b)                       # Automatically preserve fixed-point
    Decimal('325.62')
    >>> div(b, a)
    Decimal('0.03')

Q. There are many ways to express the same value.  The numbers :const:`200`,
:const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
various precisions. Is there a way to transform them to a single recognizable
canonical value?

A. The :meth:`normalize` method maps all equivalent values to a single
representative:

   >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
   >>> [v.normalize() for v in values]
   [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]

Q. Some decimal values always print with exponential notation.  Is there a way
to get a non-exponential representation?

A. For some values, exponential notation is the only way to express the number
of significant places in the coefficient.  For example, expressing
:const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
original's two-place significance.

If an application does not care about tracking significance, it is easy to
remove the exponent and trailing zeros, losing significance, but keeping the
value unchanged::

    def remove_exponent(d):
        '''Remove exponent and trailing zeros.

        >>> remove_exponent(Decimal('5E+3'))
        Decimal('5000')

        '''
        return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()

Q. Is there a way to convert a regular float to a :class:`Decimal`?

A. Yes, any binary floating point number can be exactly expressed as a
Decimal though an exact conversion may take more precision than intuition would
suggest:

.. doctest::

    >>> Decimal(math.pi)
    Decimal('3.141592653589793115997963468544185161590576171875')

Q. Within a complex calculation, how can I make sure that I haven't gotten a
spurious result because of insufficient precision or rounding anomalies.

A. The decimal module makes it easy to test results.  A best practice is to
re-run calculations using greater precision and with various rounding modes.
Widely differing results indicate insufficient precision, rounding mode issues,
ill-conditioned inputs, or a numerically unstable algorithm.

Q. I noticed that context precision is applied to the results of operations but
not to the inputs.  Is there anything to watch out for when mixing values of
different precisions?

A. Yes.  The principle is that all values are considered to be exact and so is
the arithmetic on those values.  Only the results are rounded.  The advantage
for inputs is that "what you type is what you get".  A disadvantage is that the
results can look odd if you forget that the inputs haven't been rounded:

.. doctest:: newcontext

   >>> getcontext().prec = 3
   >>> Decimal('3.104') + Decimal('2.104')
   Decimal('5.21')
   >>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
   Decimal('5.20')

The solution is either to increase precision or to force rounding of inputs
using the unary plus operation:

.. doctest:: newcontext

   >>> getcontext().prec = 3
   >>> +Decimal('1.23456789')      # unary plus triggers rounding
   Decimal('1.23')

Alternatively, inputs can be rounded upon creation using the
:meth:`Context.create_decimal` method:

   >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
   Decimal('1.2345')

PK	%�\A\ER��)html/_sources/library/development.rst.txtnu�[���
.. _development:

*****************
Development Tools
*****************

The modules described in this chapter help you write software.  For example, the
:mod:`pydoc` module takes a module and generates documentation based on the
module's contents.  The :mod:`doctest` and :mod:`unittest` modules contains
frameworks for writing unit tests that automatically exercise code and verify
that the expected output is produced.  :program:`2to3` can translate Python 2.x
source code into valid Python 3.x code.

The list of modules described in this chapter is:


.. toctree::

   pydoc.rst
   doctest.rst
   unittest.rst
   2to3.rst
   test.rst
PK	%�\�}wo�w�w%html/_sources/library/difflib.rst.txtnu�[���:mod:`difflib` --- Helpers for computing deltas
===============================================

.. module:: difflib
   :synopsis: Helpers for computing differences between objects.
.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. Markup by Fred L. Drake, Jr. <fdrake@acm.org>

.. testsetup::

   import sys
   from difflib import *

.. versionadded:: 2.1

This module provides classes and functions for comparing sequences. It
can be used for example, for comparing files, and can produce difference
information in various formats, including HTML and context and unified
diffs. For comparing directories and files, see also, the :mod:`filecmp` module.

.. class:: SequenceMatcher

   This is a flexible class for comparing pairs of sequences of any type, so long
   as the sequence elements are :term:`hashable`.  The basic algorithm predates, and is a
   little fancier than, an algorithm published in the late 1980's by Ratcliff and
   Obershelp under the hyperbolic name "gestalt pattern matching."  The idea is to
   find the longest contiguous matching subsequence that contains no "junk"
   elements (the Ratcliff and Obershelp algorithm doesn't address junk).  The same
   idea is then applied recursively to the pieces of the sequences to the left and
   to the right of the matching subsequence.  This does not yield minimal edit
   sequences, but does tend to yield matches that "look right" to people.

   **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst
   case and quadratic time in the expected case. :class:`SequenceMatcher` is
   quadratic time for the worst case and has expected-case behavior dependent in a
   complicated way on how many elements the sequences have in common; best case
   time is linear.

   **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that
   automatically treats certain sequence items as junk. The heuristic counts how many
   times each individual item appears in the sequence. If an item's duplicates (after
   the first one) account for more than 1% of the sequence and the sequence is at least
   200 items long, this item is marked as "popular" and is treated as junk for
   the purpose of sequence matching. This heuristic can be turned off by setting
   the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`.

   .. versionadded:: 2.7.1
      The *autojunk* parameter.

.. class:: Differ

   This is a class for comparing sequences of lines of text, and producing
   human-readable differences or deltas.  Differ uses :class:`SequenceMatcher`
   both to compare sequences of lines, and to compare sequences of characters
   within similar (near-matching) lines.

   Each line of a :class:`Differ` delta begins with a two-letter code:

   +----------+-------------------------------------------+
   | Code     | Meaning                                   |
   +==========+===========================================+
   | ``'- '`` | line unique to sequence 1                 |
   +----------+-------------------------------------------+
   | ``'+ '`` | line unique to sequence 2                 |
   +----------+-------------------------------------------+
   | ``'  '`` | line common to both sequences             |
   +----------+-------------------------------------------+
   | ``'? '`` | line not present in either input sequence |
   +----------+-------------------------------------------+

   Lines beginning with '``?``' attempt to guide the eye to intraline differences,
   and were not present in either input sequence. These lines can be confusing if
   the sequences contain tab characters.


.. class:: HtmlDiff

   This class can be used to create an HTML table (or a complete HTML file
   containing the table) showing a side by side, line by line comparison of text
   with inter-line and intra-line change highlights.  The table can be generated in
   either full or contextual difference mode.

   The constructor for this class is:


   .. function:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)

      Initializes instance of :class:`HtmlDiff`.

      *tabsize* is an optional keyword argument to specify tab stop spacing and
      defaults to ``8``.

      *wrapcolumn* is an optional keyword to specify column number where lines are
      broken and wrapped, defaults to ``None`` where lines are not wrapped.

      *linejunk* and *charjunk* are optional keyword arguments passed into :func:`ndiff`
      (used by :class:`HtmlDiff` to generate the side by side HTML differences).  See
      :func:`ndiff` documentation for argument default values and descriptions.

   The following methods are public:


   .. function:: make_file(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])

      Compares *fromlines* and *tolines* (lists of strings) and returns a string which
      is a complete HTML file containing a table showing line by line differences with
      inter-line and intra-line changes highlighted.

      *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
      column header strings (both default to an empty string).

      *context* and *numlines* are both optional keyword arguments. Set *context* to
      ``True`` when contextual differences are to be shown, else the default is
      ``False`` to show the full files. *numlines* defaults to ``5``.  When *context*
      is ``True`` *numlines* controls the number of context lines which surround the
      difference highlights.  When *context* is ``False`` *numlines* controls the
      number of lines which are shown before a difference highlight when using the
      "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
      the next difference highlight at the top of the browser without any leading
      context).


   .. function:: make_table(fromlines, tolines [, fromdesc][, todesc][, context][, numlines])

      Compares *fromlines* and *tolines* (lists of strings) and returns a string which
      is a complete HTML table showing line by line differences with inter-line and
      intra-line changes highlighted.

      The arguments for this method are the same as those for the :meth:`make_file`
      method.

   :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
   contains a good example of its use.

   .. versionadded:: 2.4


.. function:: context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])

   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
   generating the delta lines) in context diff format.

   Context diffs are a compact way of showing just the lines that have changed plus
   a few lines of context.  The changes are shown in a before/after style.  The
   number of context lines is set by *n* which defaults to three.

   By default, the diff control lines (those with ``***`` or ``---``) are created
   with a trailing newline.  This is helpful so that inputs created from
   :func:`file.readlines` result in diffs that are suitable for use with
   :func:`file.writelines` since both the inputs and outputs have trailing
   newlines.

   For inputs that do not have trailing newlines, set the *lineterm* argument to
   ``""`` so that the output will be uniformly newline free.

   The context diff format normally has a header for filenames and modification
   times.  Any or all of these may be specified using strings for *fromfile*,
   *tofile*, *fromfiledate*, and *tofiledate*.  The modification times are normally
   expressed in the ISO 8601 format. If not specified, the
   strings default to blanks.

      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
      >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
      ...     sys.stdout.write(line)  # doctest: +NORMALIZE_WHITESPACE
      *** before.py
      --- after.py
      ***************
      *** 1,4 ****
      ! bacon
      ! eggs
      ! ham
        guido
      --- 1,4 ----
      ! python
      ! eggy
      ! hamster
        guido

   See :ref:`difflib-interface` for a more detailed example.

   .. versionadded:: 2.3


.. function:: get_close_matches(word, possibilities[, n][, cutoff])

   Return a list of the best "good enough" matches.  *word* is a sequence for which
   close matches are desired (typically a string), and *possibilities* is a list of
   sequences against which to match *word* (typically a list of strings).

   Optional argument *n* (default ``3``) is the maximum number of close matches to
   return; *n* must be greater than ``0``.

   Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
   Possibilities that don't score at least that similar to *word* are ignored.

   The best (no more than *n*) matches among the possibilities are returned in a
   list, sorted by similarity score, most similar first.

      >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
      ['apple', 'ape']
      >>> import keyword
      >>> get_close_matches('wheel', keyword.kwlist)
      ['while']
      >>> get_close_matches('apple', keyword.kwlist)
      []
      >>> get_close_matches('accept', keyword.kwlist)
      ['except']


.. function:: ndiff(a, b[, linejunk][, charjunk])

   Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
   delta (a :term:`generator` generating the delta lines).

   Optional keyword parameters *linejunk* and *charjunk* are for filter functions
   (or ``None``):

   *linejunk*: A function that accepts a single string argument, and returns true
   if the string is junk, or false if not. The default is (``None``), starting with
   Python 2.3.  Before then, the default was the module-level function
   :func:`IS_LINE_JUNK`, which filters out lines without visible characters, except
   for at most one pound character (``'#'``). As of Python 2.3, the underlying
   :class:`SequenceMatcher` class does a dynamic analysis of which lines are so
   frequent as to constitute noise, and this usually works better than the pre-2.3
   default.

   *charjunk*: A function that accepts a character (a string of length 1), and
   returns if the character is junk, or false if not. The default is module-level
   function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
   blank or tab; note: bad idea to include newline in this!).

   :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.

      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
      ...              'ore\ntree\nemu\n'.splitlines(1))
      >>> print ''.join(diff),
      - one
      ?  ^
      + ore
      ?  ^
      - two
      - three
      ?  -
      + tree
      + emu


.. function:: restore(sequence, which)

   Return one of the two sequences that generated a delta.

   Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
   lines originating from file 1 or 2 (parameter *which*), stripping off line
   prefixes.

   Example:

      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
      ...              'ore\ntree\nemu\n'.splitlines(1))
      >>> diff = list(diff) # materialize the generated delta into a list
      >>> print ''.join(restore(diff, 1)),
      one
      two
      three
      >>> print ''.join(restore(diff, 2)),
      ore
      tree
      emu


.. function:: unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])

   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
   generating the delta lines) in unified diff format.

   Unified diffs are a compact way of showing just the lines that have changed plus
   a few lines of context.  The changes are shown in an inline style (instead of
   separate before/after blocks).  The number of context lines is set by *n* which
   defaults to three.

   By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
   created with a trailing newline.  This is helpful so that inputs created from
   :func:`file.readlines` result in diffs that are suitable for use with
   :func:`file.writelines` since both the inputs and outputs have trailing
   newlines.

   For inputs that do not have trailing newlines, set the *lineterm* argument to
   ``""`` so that the output will be uniformly newline free.

   The context diff format normally has a header for filenames and modification
   times.  Any or all of these may be specified using strings for *fromfile*,
   *tofile*, *fromfiledate*, and *tofiledate*.  The modification times are normally
   expressed in the ISO 8601 format. If not specified, the
   strings default to blanks.

      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
      >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
      ...     sys.stdout.write(line)   # doctest: +NORMALIZE_WHITESPACE
      --- before.py
      +++ after.py
      @@ -1,4 +1,4 @@
      -bacon
      -eggs
      -ham
      +python
      +eggy
      +hamster
       guido

   See :ref:`difflib-interface` for a more detailed example.

   .. versionadded:: 2.3


.. function:: IS_LINE_JUNK(line)

   Return true for ignorable lines.  The line *line* is ignorable if *line* is
   blank or contains a single ``'#'``, otherwise it is not ignorable.  Used as a
   default for parameter *linejunk* in :func:`ndiff` before Python 2.3.


.. function:: IS_CHARACTER_JUNK(ch)

   Return true for ignorable characters.  The character *ch* is ignorable if *ch*
   is a space or tab, otherwise it is not ignorable.  Used as a default for
   parameter *charjunk* in :func:`ndiff`.


.. seealso::

   `Pattern Matching: The Gestalt Approach <http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970>`_
      Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
      was published in `Dr. Dobb's Journal <http://www.drdobbs.com/>`_ in July, 1988.


.. _sequence-matcher:

SequenceMatcher Objects
-----------------------

The :class:`SequenceMatcher` class has this constructor:


.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)

   Optional argument *isjunk* must be ``None`` (the default) or a one-argument
   function that takes a sequence element and returns true if and only if the
   element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
   equivalent to passing ``lambda x: 0``; in other words, no elements are ignored.
   For example, pass::

      lambda x: x in " \t"

   if you're comparing lines as sequences of characters, and don't want to synch up
   on blanks or hard tabs.

   The optional arguments *a* and *b* are sequences to be compared; both default to
   empty strings.  The elements of both sequences must be :term:`hashable`.

   The optional argument *autojunk* can be used to disable the automatic junk
   heuristic.

   .. versionadded:: 2.7.1
      The *autojunk* parameter.

   :class:`SequenceMatcher` objects have the following methods:

   .. method:: set_seqs(a, b)

      Set the two sequences to be compared.

   :class:`SequenceMatcher` computes and caches detailed information about the
   second sequence, so if you want to compare one sequence against many
   sequences, use :meth:`set_seq2` to set the commonly used sequence once and
   call :meth:`set_seq1` repeatedly, once for each of the other sequences.


   .. method:: set_seq1(a)

      Set the first sequence to be compared.  The second sequence to be compared
      is not changed.


   .. method:: set_seq2(b)

      Set the second sequence to be compared.  The first sequence to be compared
      is not changed.


   .. method:: find_longest_match(alo, ahi, blo, bhi)

      Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.

      If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
      ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
      <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
      k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
      <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
      all maximal matching blocks, return one that starts earliest in *a*, and
      of all those maximal matching blocks that start earliest in *a*, return
      the one that starts earliest in *b*.

         >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
         >>> s.find_longest_match(0, 5, 0, 9)
         Match(a=0, b=4, size=5)

      If *isjunk* was provided, first the longest matching block is determined
      as above, but with the additional restriction that no junk element appears
      in the block.  Then that block is extended as far as possible by matching
      (only) junk elements on both sides. So the resulting block never matches
      on junk except as identical junk happens to be adjacent to an interesting
      match.

      Here's the same example as before, but considering blanks to be junk. That
      prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
      second sequence directly.  Instead only the ``'abcd'`` can match, and
      matches the leftmost ``'abcd'`` in the second sequence:

         >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
         >>> s.find_longest_match(0, 5, 0, 9)
         Match(a=1, b=0, size=4)

      If no blocks match, this returns ``(alo, blo, 0)``.

      .. versionchanged:: 2.6
         This method returns a :term:`named tuple` ``Match(a, b, size)``.


   .. method:: get_matching_blocks()

      Return list of triples describing non-overlapping matching subsequences.
      Each triple is of the form ``(i, j, n)``,
      and means that ``a[i:i+n] == b[j:j+n]``.  The
      triples are monotonically increasing in *i* and *j*.

      The last triple is a dummy, and has the value ``(len(a), len(b), 0)``.  It
      is the only triple with ``n == 0``.  If ``(i, j, n)`` and ``(i', j', n')``
      are adjacent triples in the list, and the second is not the last triple in
      the list, then ``i+n < i'`` or ``j+n < j'``; in other words, adjacent
      triples always describe non-adjacent equal blocks.

      .. XXX Explain why a dummy is used!

      .. versionchanged:: 2.5
         The guarantee that adjacent triples always describe non-adjacent blocks
         was implemented.

      .. doctest::

         >>> s = SequenceMatcher(None, "abxcd", "abcd")
         >>> s.get_matching_blocks()
         [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]


   .. method:: get_opcodes()

      Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
      of the form ``(tag, i1, i2, j1, j2)``.  The first tuple has ``i1 == j1 ==
      0``, and remaining tuples have *i1* equal to the *i2* from the preceding
      tuple, and, likewise, *j1* equal to the previous *j2*.

      The *tag* values are strings, with these meanings:

      +---------------+---------------------------------------------+
      | Value         | Meaning                                     |
      +===============+=============================================+
      | ``'replace'`` | ``a[i1:i2]`` should be replaced by          |
      |               | ``b[j1:j2]``.                               |
      +---------------+---------------------------------------------+
      | ``'delete'``  | ``a[i1:i2]`` should be deleted.  Note that  |
      |               | ``j1 == j2`` in this case.                  |
      +---------------+---------------------------------------------+
      | ``'insert'``  | ``b[j1:j2]`` should be inserted at          |
      |               | ``a[i1:i1]``. Note that ``i1 == i2`` in     |
      |               | this case.                                  |
      +---------------+---------------------------------------------+
      | ``'equal'``   | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
      |               | are equal).                                 |
      +---------------+---------------------------------------------+

      For example:

         >>> a = "qabxcd"
         >>> b = "abycdf"
         >>> s = SequenceMatcher(None, a, b)
         >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
         ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
         ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
          delete a[0:1] (q) b[0:0] ()
           equal a[1:3] (ab) b[0:2] (ab)
         replace a[3:4] (x) b[2:3] (y)
           equal a[4:6] (cd) b[3:5] (cd)
          insert a[6:6] () b[5:6] (f)


   .. method:: get_grouped_opcodes([n])

      Return a :term:`generator` of groups with up to *n* lines of context.

      Starting with the groups returned by :meth:`get_opcodes`, this method
      splits out smaller change clusters and eliminates intervening ranges which
      have no changes.

      The groups are returned in the same format as :meth:`get_opcodes`.

      .. versionadded:: 2.3


   .. method:: ratio()

      Return a measure of the sequences' similarity as a float in the range [0,
      1].

      Where T is the total number of elements in both sequences, and M is the
      number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
      sequences are identical, and ``0.0`` if they have nothing in common.

      This is expensive to compute if :meth:`get_matching_blocks` or
      :meth:`get_opcodes` hasn't already been called, in which case you may want
      to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
      upper bound.


   .. method:: quick_ratio()

      Return an upper bound on :meth:`ratio` relatively quickly.


   .. method:: real_quick_ratio()

      Return an upper bound on :meth:`ratio` very quickly.


The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although
:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
:meth:`ratio`:

   >>> s = SequenceMatcher(None, "abcd", "bcde")
   >>> s.ratio()
   0.75
   >>> s.quick_ratio()
   0.75
   >>> s.real_quick_ratio()
   1.0


.. _sequencematcher-examples:

SequenceMatcher Examples
------------------------

This example compares two strings, considering blanks to be "junk:"

   >>> s = SequenceMatcher(lambda x: x == " ",
   ...                     "private Thread currentThread;",
   ...                     "private volatile Thread currentThread;")

:meth:`ratio` returns a float in [0, 1], measuring the similarity of the
sequences.  As a rule of thumb, a :meth:`ratio` value over 0.6 means the
sequences are close matches:

   >>> print round(s.ratio(), 3)
   0.866

If you're only interested in where the sequences match,
:meth:`get_matching_blocks` is handy:

   >>> for block in s.get_matching_blocks():
   ...     print "a[%d] and b[%d] match for %d elements" % block
   a[0] and b[0] match for 8 elements
   a[8] and b[17] match for 21 elements
   a[29] and b[38] match for 0 elements

Note that the last tuple returned by :meth:`get_matching_blocks` is always a
dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
tuple element (number of elements matched) is ``0``.

If you want to know how to change the first sequence into the second, use
:meth:`get_opcodes`:

   >>> for opcode in s.get_opcodes():
   ...     print "%6s a[%d:%d] b[%d:%d]" % opcode
    equal a[0:8] b[0:8]
   insert a[8:8] b[8:17]
    equal a[8:29] b[17:38]

.. seealso::

   * The :func:`get_close_matches` function in this module which shows how
     simple code building on :class:`SequenceMatcher` can be used to do useful
     work.

   * `Simple version control recipe
     <https://code.activestate.com/recipes/576729/>`_ for a small application
     built with :class:`SequenceMatcher`.


.. _differ-objects:

Differ Objects
--------------

Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
diffs. To the contrary, minimal diffs are often counter-intuitive, because they
synch up anywhere possible, sometimes accidental matches 100 pages apart.
Restricting synch points to contiguous matches preserves some notion of
locality, at the occasional cost of producing a longer diff.

The :class:`Differ` class has this constructor:


.. class:: Differ([linejunk[, charjunk]])

   Optional keyword parameters *linejunk* and *charjunk* are for filter functions
   (or ``None``):

   *linejunk*: A function that accepts a single string argument, and returns true
   if the string is junk.  The default is ``None``, meaning that no line is
   considered junk.

   *charjunk*: A function that accepts a single character argument (a string of
   length 1), and returns true if the character is junk. The default is ``None``,
   meaning that no character is considered junk.

   :class:`Differ` objects are used (deltas generated) via a single method:


   .. method:: Differ.compare(a, b)

      Compare two sequences of lines, and generate the delta (a sequence of lines).

      Each sequence must contain individual single-line strings ending with
      newlines.  Such sequences can be obtained from the
      :meth:`~file.readlines` method of file-like objects.  The delta
      generated also consists of newline-terminated strings, ready to be
      printed as-is via the :meth:`~file.writelines` method of a
      file-like object.


.. _differ-examples:

Differ Example
--------------

This example compares two texts. First we set up the texts, sequences of
individual single-line strings ending with newlines (such sequences can also be
obtained from the :meth:`~file.readlines` method of file-like objects):

   >>> text1 = '''  1. Beautiful is better than ugly.
   ...   2. Explicit is better than implicit.
   ...   3. Simple is better than complex.
   ...   4. Complex is better than complicated.
   ... '''.splitlines(1)
   >>> len(text1)
   4
   >>> text1[0][-1]
   '\n'
   >>> text2 = '''  1. Beautiful is better than ugly.
   ...   3.   Simple is better than complex.
   ...   4. Complicated is better than complex.
   ...   5. Flat is better than nested.
   ... '''.splitlines(1)

Next we instantiate a Differ object:

   >>> d = Differ()

Note that when instantiating a :class:`Differ` object we may pass functions to
filter out line and character "junk."  See the :meth:`Differ` constructor for
details.

Finally, we compare the two:

   >>> result = list(d.compare(text1, text2))

``result`` is a list of strings, so let's pretty-print it:

   >>> from pprint import pprint
   >>> pprint(result)
   ['    1. Beautiful is better than ugly.\n',
    '-   2. Explicit is better than implicit.\n',
    '-   3. Simple is better than complex.\n',
    '+   3.   Simple is better than complex.\n',
    '?     ++\n',
    '-   4. Complex is better than complicated.\n',
    '?            ^                     ---- ^\n',
    '+   4. Complicated is better than complex.\n',
    '?           ++++ ^                      ^\n',
    '+   5. Flat is better than nested.\n']

As a single multi-line string it looks like this:

   >>> import sys
   >>> sys.stdout.writelines(result)
       1. Beautiful is better than ugly.
   -   2. Explicit is better than implicit.
   -   3. Simple is better than complex.
   +   3.   Simple is better than complex.
   ?     ++
   -   4. Complex is better than complicated.
   ?            ^                     ---- ^
   +   4. Complicated is better than complex.
   ?           ++++ ^                      ^
   +   5. Flat is better than nested.


.. _difflib-interface:

A command-line interface to difflib
-----------------------------------

This example shows how to use difflib to create a ``diff``-like utility.
It is also contained in the Python source distribution, as
:file:`Tools/scripts/diff.py`.

.. testcode::

   """ Command line interface to difflib.py providing diffs in four formats:

   * ndiff:    lists every line and highlights interline changes.
   * context:  highlights clusters of changes in a before/after format.
   * unified:  highlights clusters of changes in an inline format.
   * html:     generates side by side comparison with change highlights.

   """

   import sys, os, time, difflib, optparse

   def main():
        # Configure the option parser
       usage = "usage: %prog [options] fromfile tofile"
       parser = optparse.OptionParser(usage)
       parser.add_option("-c", action="store_true", default=False,
                         help='Produce a context format diff (default)')
       parser.add_option("-u", action="store_true", default=False,
                         help='Produce a unified format diff')
       hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)'
       parser.add_option("-m", action="store_true", default=False, help=hlp)
       parser.add_option("-n", action="store_true", default=False,
                         help='Produce a ndiff format diff')
       parser.add_option("-l", "--lines", type="int", default=3,
                         help='Set number of context lines (default 3)')
       (options, args) = parser.parse_args()

       if len(args) == 0:
           parser.print_help()
           sys.exit(1)
       if len(args) != 2:
           parser.error("need to specify both a fromfile and tofile")

       n = options.lines
       fromfile, tofile = args # as specified in the usage string

       # we're passing these as arguments to the diff function
       fromdate = time.ctime(os.stat(fromfile).st_mtime)
       todate = time.ctime(os.stat(tofile).st_mtime)
       with open(fromfile, 'U') as f:
           fromlines = f.readlines()
       with open(tofile, 'U') as f:
           tolines = f.readlines()

       if options.u:
           diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
                                       fromdate, todate, n=n)
       elif options.n:
           diff = difflib.ndiff(fromlines, tolines)
       elif options.m:
           diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
                                               tofile, context=options.c,
                                               numlines=n)
       else:
           diff = difflib.context_diff(fromlines, tolines, fromfile, tofile,
                                       fromdate, todate, n=n)

       # we're using writelines because diff is a generator
       sys.stdout.writelines(diff)

   if __name__ == '__main__':
       main()
PK	%�\�$�&html/_sources/library/dircache.rst.txtnu�[���
:mod:`dircache` --- Cached directory listings
=============================================

.. module:: dircache
   :synopsis: Return directory listing, with cache mechanism.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`dircache` module has been removed in Python 3.


.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`dircache` module defines a function for reading directory listing
using a cache, and cache invalidation using the *mtime* of the directory.
Additionally, it defines a function to annotate directories by appending a
slash.

The :mod:`dircache` module defines the following functions:


.. function:: reset()

   Resets the directory cache.


.. function:: listdir(path)

   Return a directory listing of *path*, as gotten from :func:`os.listdir`. Note
   that unless *path* changes, further call to :func:`listdir` will not re-read the
   directory structure.

   Note that the list returned should be regarded as read-only. (Perhaps a future
   version should change it to return a tuple?)


.. function:: opendir(path)

   Same as :func:`listdir`. Defined for backwards compatibility.


.. function:: annotate(head, list)

   Assume *list* is a list of paths relative to *head*, and append, in place, a
   ``'/'`` to each path which points to a directory.

::

   >>> import dircache
   >>> a = dircache.listdir('/')
   >>> a = a[:] # Copy the return value so we can change 'a'
   >>> a
   ['bin', 'boot', 'cdrom', 'dev', 'etc', 'floppy', 'home', 'initrd', 'lib', 'lost+
   found', 'mnt', 'proc', 'root', 'sbin', 'tmp', 'usr', 'var', 'vmlinuz']
   >>> dircache.annotate('/', a)
   >>> a
   ['bin/', 'boot/', 'cdrom/', 'dev/', 'etc/', 'floppy/', 'home/', 'initrd/', 'lib/
   ', 'lost+found/', 'mnt/', 'proc/', 'root/', 'sbin/', 'tmp/', 'usr/', 'var/', 'vm
   linuz']

PK	%�\:4f�Z�Z!html/_sources/library/dis.rst.txtnu�[���:mod:`dis` --- Disassembler for Python bytecode
===============================================

.. module:: dis
   :synopsis: Disassembler for Python bytecode.

**Source code:** :source:`Lib/dis.py`

--------------

The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
disassembling it. The CPython bytecode which this module takes as an input is
defined in the file :file:`Include/opcode.h` and used by the compiler and the
interpreter.

.. impl-detail::

   Bytecode is an implementation detail of the CPython interpreter!  No
   guarantees are made that bytecode will not be added, removed, or changed
   between versions of Python.  Use of this module should not be considered to
   work across Python VMs or Python releases.

Example: Given the function :func:`myfunc`::

   def myfunc(alist):
       return len(alist)

the following command can be used to get the disassembly of :func:`myfunc`::

   >>> dis.dis(myfunc)
     2           0 LOAD_GLOBAL              0 (len)
                 3 LOAD_FAST                0 (alist)
                 6 CALL_FUNCTION            1
                 9 RETURN_VALUE

(The "2" is a line number).

The :mod:`dis` module defines the following functions and constants:


.. function:: dis([bytesource])

   Disassemble the *bytesource* object. *bytesource* can denote either a module,
   a class, a method, a function, or a code object.  For a module, it
   disassembles all functions.  For a class, it disassembles all methods.  For a
   single code sequence, it prints one line per bytecode instruction.  If no
   object is provided, it disassembles the last traceback.


.. function:: distb([tb])

   Disassembles the top-of-stack function of a traceback, using the last
   traceback if none was passed.  The instruction causing the exception is
   indicated.


.. function:: disassemble(code[, lasti])

   Disassembles a code object, indicating the last instruction if *lasti* was
   provided.  The output is divided in the following columns:

   #. the line number, for the first instruction of each line
   #. the current instruction, indicated as ``-->``,
   #. a labelled instruction, indicated with ``>>``,
   #. the address of the instruction,
   #. the operation code name,
   #. operation parameters, and
   #. interpretation of the parameters in parentheses.

   The parameter interpretation recognizes local and global variable names,
   constant values, branch targets, and compare operators.


.. function:: disco(code[, lasti])

   A synonym for :func:`disassemble`.  It is more convenient to type, and kept
   for compatibility with earlier Python releases.


.. function:: findlinestarts(code)

   This generator function uses the ``co_firstlineno`` and ``co_lnotab``
   attributes of the code object *code* to find the offsets which are starts of
   lines in the source code.  They are generated as ``(offset, lineno)`` pairs.


.. function:: findlabels(code)

   Detect all offsets in the code object *code* which are jump targets, and
   return a list of these offsets.


.. data:: opname

   Sequence of operation names, indexable using the bytecode.


.. data:: opmap

   Dictionary mapping operation names to bytecodes.


.. data:: cmp_op

   Sequence of all compare operation names.


.. data:: hasconst

   Sequence of bytecodes that access a constant.


.. data:: hasfree

   Sequence of bytecodes that access a free variable.


.. data:: hasname

   Sequence of bytecodes that access an attribute by name.


.. data:: hasjrel

   Sequence of bytecodes that have a relative jump target.


.. data:: hasjabs

   Sequence of bytecodes that have an absolute jump target.


.. data:: haslocal

   Sequence of bytecodes that access a local variable.


.. data:: hascompare

   Sequence of bytecodes of Boolean operations.


.. _bytecodes:

Python Bytecode Instructions
----------------------------

The Python compiler currently generates the following bytecode instructions.


.. opcode:: STOP_CODE ()

   Indicates end-of-code to the compiler, not used by the interpreter.


.. opcode:: NOP ()

   Do nothing code.  Used as a placeholder by the bytecode optimizer.


.. opcode:: POP_TOP ()

   Removes the top-of-stack (TOS) item.


.. opcode:: ROT_TWO ()

   Swaps the two top-most stack items.


.. opcode:: ROT_THREE ()

   Lifts second and third stack item one position up, moves top down to position
   three.


.. opcode:: ROT_FOUR ()

   Lifts second, third and forth stack item one position up, moves top down to
   position four.


.. opcode:: DUP_TOP ()

   Duplicates the reference on top of the stack.

Unary Operations take the top of the stack, apply the operation, and push the
result back on the stack.


.. opcode:: UNARY_POSITIVE ()

   Implements ``TOS = +TOS``.


.. opcode:: UNARY_NEGATIVE ()

   Implements ``TOS = -TOS``.


.. opcode:: UNARY_NOT ()

   Implements ``TOS = not TOS``.


.. opcode:: UNARY_CONVERT ()

   Implements ``TOS = `TOS```.


.. opcode:: UNARY_INVERT ()

   Implements ``TOS = ~TOS``.


.. opcode:: GET_ITER ()

   Implements ``TOS = iter(TOS)``.

Binary operations remove the top of the stack (TOS) and the second top-most
stack item (TOS1) from the stack.  They perform the operation, and put the
result back on the stack.


.. opcode:: BINARY_POWER ()

   Implements ``TOS = TOS1 ** TOS``.


.. opcode:: BINARY_MULTIPLY ()

   Implements ``TOS = TOS1 * TOS``.


.. opcode:: BINARY_DIVIDE ()

   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is
   not in effect.


.. opcode:: BINARY_FLOOR_DIVIDE ()

   Implements ``TOS = TOS1 // TOS``.


.. opcode:: BINARY_TRUE_DIVIDE ()

   Implements ``TOS = TOS1 / TOS`` when ``from __future__ import division`` is
   in effect.


.. opcode:: BINARY_MODULO ()

   Implements ``TOS = TOS1 % TOS``.


.. opcode:: BINARY_ADD ()

   Implements ``TOS = TOS1 + TOS``.


.. opcode:: BINARY_SUBTRACT ()

   Implements ``TOS = TOS1 - TOS``.


.. opcode:: BINARY_SUBSCR ()

   Implements ``TOS = TOS1[TOS]``.


.. opcode:: BINARY_LSHIFT ()

   Implements ``TOS = TOS1 << TOS``.


.. opcode:: BINARY_RSHIFT ()

   Implements ``TOS = TOS1 >> TOS``.


.. opcode:: BINARY_AND ()

   Implements ``TOS = TOS1 & TOS``.


.. opcode:: BINARY_XOR ()

   Implements ``TOS = TOS1 ^ TOS``.


.. opcode:: BINARY_OR ()

   Implements ``TOS = TOS1 | TOS``.

In-place operations are like binary operations, in that they remove TOS and
TOS1, and push the result back on the stack, but the operation is done in-place
when TOS1 supports it, and the resulting TOS may be (but does not have to be)
the original TOS1.


.. opcode:: INPLACE_POWER ()

   Implements in-place ``TOS = TOS1 ** TOS``.


.. opcode:: INPLACE_MULTIPLY ()

   Implements in-place ``TOS = TOS1 * TOS``.


.. opcode:: INPLACE_DIVIDE ()

   Implements in-place ``TOS = TOS1 / TOS`` when ``from __future__ import
   division`` is not in effect.


.. opcode:: INPLACE_FLOOR_DIVIDE ()

   Implements in-place ``TOS = TOS1 // TOS``.


.. opcode:: INPLACE_TRUE_DIVIDE ()

   Implements in-place ``TOS = TOS1 / TOS`` when ``from __future__ import
   division`` is in effect.


.. opcode:: INPLACE_MODULO ()

   Implements in-place ``TOS = TOS1 % TOS``.


.. opcode:: INPLACE_ADD ()

   Implements in-place ``TOS = TOS1 + TOS``.


.. opcode:: INPLACE_SUBTRACT ()

   Implements in-place ``TOS = TOS1 - TOS``.


.. opcode:: INPLACE_LSHIFT ()

   Implements in-place ``TOS = TOS1 << TOS``.


.. opcode:: INPLACE_RSHIFT ()

   Implements in-place ``TOS = TOS1 >> TOS``.


.. opcode:: INPLACE_AND ()

   Implements in-place ``TOS = TOS1 & TOS``.


.. opcode:: INPLACE_XOR ()

   Implements in-place ``TOS = TOS1 ^ TOS``.


.. opcode:: INPLACE_OR ()

   Implements in-place ``TOS = TOS1 | TOS``.

The slice opcodes take up to three parameters.


.. opcode:: SLICE+0 ()

   Implements ``TOS = TOS[:]``.


.. opcode:: SLICE+1 ()

   Implements ``TOS = TOS1[TOS:]``.


.. opcode:: SLICE+2 ()

   Implements ``TOS = TOS1[:TOS]``.


.. opcode:: SLICE+3 ()

   Implements ``TOS = TOS2[TOS1:TOS]``.

Slice assignment needs even an additional parameter.  As any statement, they put
nothing on the stack.


.. opcode:: STORE_SLICE+0 ()

   Implements ``TOS[:] = TOS1``.


.. opcode:: STORE_SLICE+1 ()

   Implements ``TOS1[TOS:] = TOS2``.


.. opcode:: STORE_SLICE+2 ()

   Implements ``TOS1[:TOS] = TOS2``.


.. opcode:: STORE_SLICE+3 ()

   Implements ``TOS2[TOS1:TOS] = TOS3``.


.. opcode:: DELETE_SLICE+0 ()

   Implements ``del TOS[:]``.


.. opcode:: DELETE_SLICE+1 ()

   Implements ``del TOS1[TOS:]``.


.. opcode:: DELETE_SLICE+2 ()

   Implements ``del TOS1[:TOS]``.


.. opcode:: DELETE_SLICE+3 ()

   Implements ``del TOS2[TOS1:TOS]``.


.. opcode:: STORE_SUBSCR ()

   Implements ``TOS1[TOS] = TOS2``.


.. opcode:: DELETE_SUBSCR ()

   Implements ``del TOS1[TOS]``.

Miscellaneous opcodes.


.. opcode:: PRINT_EXPR ()

   Implements the expression statement for the interactive mode.  TOS is removed
   from the stack and printed.  In non-interactive mode, an expression statement
   is terminated with :opcode:`POP_TOP`.


.. opcode:: PRINT_ITEM ()

   Prints TOS to the file-like object bound to ``sys.stdout``.  There is one
   such instruction for each item in the :keyword:`print` statement.


.. opcode:: PRINT_ITEM_TO ()

   Like ``PRINT_ITEM``, but prints the item second from TOS to the file-like
   object at TOS.  This is used by the extended print statement.


.. opcode:: PRINT_NEWLINE ()

   Prints a new line on ``sys.stdout``.  This is generated as the last operation
   of a :keyword:`print` statement, unless the statement ends with a comma.


.. opcode:: PRINT_NEWLINE_TO ()

   Like ``PRINT_NEWLINE``, but prints the new line on the file-like object on
   the TOS.  This is used by the extended print statement.


.. opcode:: BREAK_LOOP ()

   Terminates a loop due to a :keyword:`break` statement.


.. opcode:: CONTINUE_LOOP (target)

   Continues a loop due to a :keyword:`continue` statement.  *target* is the
   address to jump to (which should be a :opcode:`FOR_ITER` instruction).


.. opcode:: LIST_APPEND (i)

   Calls ``list.append(TOS[-i], TOS)``.  Used to implement list comprehensions.
   While the appended value is popped off, the list object remains on the stack
   so that it is available for further iterations of the loop.


.. opcode:: LOAD_LOCALS ()

   Pushes a reference to the locals of the current scope on the stack. This is
   used in the code for a class definition: After the class body is evaluated,
   the locals are passed to the class definition.


.. opcode:: RETURN_VALUE ()

   Returns with TOS to the caller of the function.


.. opcode:: YIELD_VALUE ()

   Pops ``TOS`` and yields it from a :term:`generator`.


.. opcode:: IMPORT_STAR ()

   Loads all symbols not starting with ``'_'`` directly from the module TOS to
   the local namespace. The module is popped after loading all names. This
   opcode implements ``from module import *``.


.. opcode:: EXEC_STMT ()

   Implements ``exec TOS2,TOS1,TOS``.  The compiler fills missing optional
   parameters with ``None``.


.. opcode:: POP_BLOCK ()

   Removes one block from the block stack.  Per frame, there is a stack of
   blocks, denoting nested loops, try statements, and such.


.. opcode:: END_FINALLY ()

   Terminates a :keyword:`finally` clause.  The interpreter recalls whether the
   exception has to be re-raised, or whether the function returns, and continues
   with the outer-next block.


.. opcode:: BUILD_CLASS ()

   Creates a new class object.  TOS is the methods dictionary, TOS1 the tuple of
   the names of the base classes, and TOS2 the class name.


.. opcode:: SETUP_WITH (delta)

   This opcode performs several operations before a with block starts.  First,
   it loads :meth:`~object.__exit__` from the context manager and pushes it onto
   the stack for later use by :opcode:`WITH_CLEANUP`.  Then,
   :meth:`~object.__enter__` is called, and a finally block pointing to *delta*
   is pushed.  Finally, the result of calling the enter method is pushed onto
   the stack.  The next opcode will either ignore it (:opcode:`POP_TOP`), or
   store it in (a) variable(s) (:opcode:`STORE_FAST`, :opcode:`STORE_NAME`, or
   :opcode:`UNPACK_SEQUENCE`).


.. opcode:: WITH_CLEANUP ()

   Cleans up the stack when a :keyword:`with` statement block exits.  On top of
   the stack are 1--3 values indicating how/why the finally clause was entered:

   * TOP = ``None``
   * (TOP, SECOND) = (``WHY_{RETURN,CONTINUE}``), retval
   * TOP = ``WHY_*``; no retval below it
   * (TOP, SECOND, THIRD) = exc_info()

   Under them is EXIT, the context manager's :meth:`__exit__` bound method.

   In the last case, ``EXIT(TOP, SECOND, THIRD)`` is called, otherwise
   ``EXIT(None, None, None)``.

   EXIT is removed from the stack, leaving the values above it in the same
   order. In addition, if the stack represents an exception, *and* the function
   call returns a 'true' value, this information is "zapped", to prevent
   ``END_FINALLY`` from re-raising the exception.  (But non-local gotos should
   still be resumed.)

   .. XXX explain the WHY stuff!


All of the following opcodes expect arguments.  An argument is two bytes, with
the more significant byte last.

.. opcode:: STORE_NAME (namei)

   Implements ``name = TOS``. *namei* is the index of *name* in the attribute
   :attr:`co_names` of the code object. The compiler tries to use ``STORE_FAST``
   or ``STORE_GLOBAL`` if possible.


.. opcode:: DELETE_NAME (namei)

   Implements ``del name``, where *namei* is the index into :attr:`co_names`
   attribute of the code object.


.. opcode:: UNPACK_SEQUENCE (count)

   Unpacks TOS into *count* individual values, which are put onto the stack
   right-to-left.


.. opcode:: DUP_TOPX (count)

   Duplicate *count* items, keeping them in the same order. Due to
   implementation limits, *count* should be between 1 and 5 inclusive.


.. opcode:: STORE_ATTR (namei)

   Implements ``TOS.name = TOS1``, where *namei* is the index of name in
   :attr:`co_names`.


.. opcode:: DELETE_ATTR (namei)

   Implements ``del TOS.name``, using *namei* as index into :attr:`co_names`.


.. opcode:: STORE_GLOBAL (namei)

   Works as ``STORE_NAME``, but stores the name as a global.


.. opcode:: DELETE_GLOBAL (namei)

   Works as ``DELETE_NAME``, but deletes a global name.


.. opcode:: LOAD_CONST (consti)

   Pushes ``co_consts[consti]`` onto the stack.


.. opcode:: LOAD_NAME (namei)

   Pushes the value associated with ``co_names[namei]`` onto the stack.


.. opcode:: BUILD_TUPLE (count)

   Creates a tuple consuming *count* items from the stack, and pushes the
   resulting tuple onto the stack.


.. opcode:: BUILD_LIST (count)

   Works as ``BUILD_TUPLE``, but creates a list.


.. opcode:: BUILD_SET (count)

   Works as ``BUILD_TUPLE``, but creates a set.

   .. versionadded:: 2.7


.. opcode:: BUILD_MAP (count)

   Pushes a new dictionary object onto the stack.  The dictionary is pre-sized
   to hold *count* entries.


.. opcode:: LOAD_ATTR (namei)

   Replaces TOS with ``getattr(TOS, co_names[namei])``.


.. opcode:: COMPARE_OP (opname)

   Performs a Boolean operation.  The operation name can be found in
   ``cmp_op[opname]``.


.. opcode:: IMPORT_NAME (namei)

   Imports the module ``co_names[namei]``.  TOS and TOS1 are popped and provide
   the *fromlist* and *level* arguments of :func:`__import__`.  The module
   object is pushed onto the stack.  The current namespace is not affected: for
   a proper import statement, a subsequent ``STORE_FAST`` instruction modifies
   the namespace.


.. opcode:: IMPORT_FROM (namei)

   Loads the attribute ``co_names[namei]`` from the module found in TOS. The
   resulting object is pushed onto the stack, to be subsequently stored by a
   ``STORE_FAST`` instruction.


.. opcode:: JUMP_FORWARD (delta)

   Increments bytecode counter by *delta*.


.. opcode:: POP_JUMP_IF_TRUE (target)

   If TOS is true, sets the bytecode counter to *target*.  TOS is popped.


.. opcode:: POP_JUMP_IF_FALSE (target)

   If TOS is false, sets the bytecode counter to *target*.  TOS is popped.


.. opcode:: JUMP_IF_TRUE_OR_POP (target)

   If TOS is true, sets the bytecode counter to *target* and leaves TOS on the
   stack.  Otherwise (TOS is false), TOS is popped.


.. opcode:: JUMP_IF_FALSE_OR_POP (target)

   If TOS is false, sets the bytecode counter to *target* and leaves TOS on the
   stack.  Otherwise (TOS is true), TOS is popped.


.. opcode:: JUMP_ABSOLUTE (target)

   Set bytecode counter to *target*.


.. opcode:: FOR_ITER (delta)

   ``TOS`` is an :term:`iterator`.  Call its :meth:`!next` method.  If this
   yields a new value, push it on the stack (leaving the iterator below it).  If
   the iterator indicates it is exhausted ``TOS`` is popped, and the bytecode
   counter is incremented by *delta*.


.. opcode:: LOAD_GLOBAL (namei)

   Loads the global named ``co_names[namei]`` onto the stack.


.. opcode:: SETUP_LOOP (delta)

   Pushes a block for a loop onto the block stack.  The block spans from the
   current instruction with a size of *delta* bytes.


.. opcode:: SETUP_EXCEPT (delta)

   Pushes a try block from a try-except clause onto the block stack. *delta*
   points to the first except block.


.. opcode:: SETUP_FINALLY (delta)

   Pushes a try block from a try-except clause onto the block stack. *delta*
   points to the finally block.

.. opcode:: STORE_MAP ()

   Store a key and value pair in a dictionary.  Pops the key and value while
   leaving the dictionary on the stack.

.. opcode:: LOAD_FAST (var_num)

   Pushes a reference to the local ``co_varnames[var_num]`` onto the stack.


.. opcode:: STORE_FAST (var_num)

   Stores TOS into the local ``co_varnames[var_num]``.


.. opcode:: DELETE_FAST (var_num)

   Deletes local ``co_varnames[var_num]``.


.. opcode:: LOAD_CLOSURE (i)

   Pushes a reference to the cell contained in slot *i* of the cell and free
   variable storage.  The name of the variable is ``co_cellvars[i]`` if *i* is
   less than the length of *co_cellvars*.  Otherwise it is ``co_freevars[i -
   len(co_cellvars)]``.


.. opcode:: LOAD_DEREF (i)

   Loads the cell contained in slot *i* of the cell and free variable storage.
   Pushes a reference to the object the cell contains on the stack.


.. opcode:: STORE_DEREF (i)

   Stores TOS into the cell contained in slot *i* of the cell and free variable
   storage.


.. opcode:: SET_LINENO (lineno)

   This opcode is obsolete.


.. opcode:: RAISE_VARARGS (argc)

   Raises an exception. *argc* indicates the number of arguments to the raise
   statement, ranging from 0 to 3.  The handler will find the traceback as TOS2,
   the parameter as TOS1, and the exception as TOS.


.. opcode:: CALL_FUNCTION (argc)

   Calls a callable object.  The low byte of *argc* indicates the number of
   positional arguments, the high byte the number of keyword arguments.
   The stack contains keyword arguments on top (if any), then the positional
   arguments below that (if any), then the callable object to call below that.
   Each keyword argument is represented with two values on the stack:
   the argument's name, and its value, with the argument's value above the
   name on the stack.
   The positional arguments are pushed in the order that they are passed in
   to the callable object, with the right-most positional argument on top.
   ``CALL_FUNCTION`` pops all arguments and the callable object off the stack,
   calls the callable object with those arguments, and pushes the return value
   returned by the callable object.


.. opcode:: MAKE_FUNCTION (argc)

   Pushes a new function object on the stack.  TOS is the code associated with
   the function.  The function object is defined to have *argc* default
   parameters, which are found below TOS.


.. opcode:: MAKE_CLOSURE (argc)

   Creates a new function object, sets its *func_closure* slot, and pushes it on
   the stack.  TOS is the code associated with the function, TOS1 the tuple
   containing cells for the closure's free variables.  The function also has
   *argc* default parameters, which are found below the cells.


.. opcode:: BUILD_SLICE (argc)

   .. index:: builtin: slice

   Pushes a slice object on the stack.  *argc* must be 2 or 3.  If it is 2,
   ``slice(TOS1, TOS)`` is pushed; if it is 3, ``slice(TOS2, TOS1, TOS)`` is
   pushed. See the :func:`slice` built-in function for more information.


.. opcode:: EXTENDED_ARG (ext)

   Prefixes any opcode which has an argument too big to fit into the default two
   bytes.  *ext* holds two additional bytes which, taken together with the
   subsequent opcode's argument, comprise a four-byte argument, *ext* being the
   two most-significant bytes.


.. opcode:: CALL_FUNCTION_VAR (argc)

   Calls a callable object, similarly to :opcode:`CALL_FUNCTION`.
   *argc* represents the number of keyword and positional
   arguments, identically to :opcode:`CALL_FUNCTION`.
   The top of the stack contains an iterable object containing
   additional positional arguments.
   Below that are keyword arguments (if any), positional arguments (if any)
   and a callable object, identically to :opcode:`CALL_FUNCTION`.
   Before the callable object is called, the iterable object
   is "unpacked" and its contents are appended to the positional
   arguments passed in.
   The iterable object is ignored when computing
   the value of ``argc``.


.. opcode:: CALL_FUNCTION_KW (argc)

   Calls a callable object, similarly to :opcode:`CALL_FUNCTION`.
   *argc* represents the number of keyword and positional
   arguments, identically to :opcode:`CALL_FUNCTION`.
   The top of the stack contains a mapping object containing additional keyword
   arguments.
   Below that are keyword arguments (if any), positional arguments (if any)
   and a callable object, identically to :opcode:`CALL_FUNCTION`.
   Before the callable is called, the mapping object at the top of the stack is
   "unpacked" and its contents are appended to the keyword arguments passed in.
   The mapping object at the top of the stack is ignored when computing
   the value of ``argc``.


.. opcode:: CALL_FUNCTION_VAR_KW (argc)

   Calls a callable object, similarly to :opcode:`CALL_FUNCTION_VAR` and
   :opcode:`CALL_FUNCTION_KW`.
   *argc* represents the number of keyword and positional
   arguments, identically to :opcode:`CALL_FUNCTION`.
   The top of the stack contains a mapping object, as per
   :opcode:`CALL_FUNCTION_KW`.
   Below that is an iterable object, as per
   :opcode:`CALL_FUNCTION_VAR`.
   Below that are keyword arguments (if any), positional arguments (if any)
   and a callable object, identically to :opcode:`CALL_FUNCTION`.
   Before the callable is called, the mapping object and iterable object
   are each "unpacked" and their contents passed in as keyword and
   positional arguments respectively,
   identically to :opcode:`CALL_FUNCTION_VAR` and :opcode:`CALL_FUNCTION_KW`.
   The mapping object and iterable object are both ignored when computing
   the value of ``argc``.


.. opcode:: HAVE_ARGUMENT ()

   This is not really an opcode.  It identifies the dividing line between
   opcodes which don't take arguments ``< HAVE_ARGUMENT`` and those which do
   ``>= HAVE_ARGUMENT``.
PK	%�\\�fߪ�*html/_sources/library/distribution.rst.txtnu�[���***********************************
Software Packaging and Distribution
***********************************

These libraries help you with publishing and installing Python software.
While these modules are designed to work in conjunction with the
`Python Package Index <https://pypi.org>`__, they can also be used
with a local index server, or without any index server at all.

.. toctree::

   distutils.rst
   ensurepip.rst
PK	%�\�1��'html/_sources/library/distutils.rst.txtnu�[���:mod:`distutils` --- Building and installing Python modules
===========================================================

.. module:: distutils
   :synopsis: Support for building and installing Python modules into an
              existing Python installation.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The :mod:`distutils` package provides support for building and installing
additional modules into a Python installation.  The new modules may be either
100%-pure Python, or may be extension modules written in C, or may be
collections of Python packages which include modules coded in both Python and C.

Most Python users will *not* want to use this module directly, but instead
use the cross-version tools maintained by the Python Packaging Authority. In
particular,
`setuptools <https://setuptools.readthedocs.io/en/latest/>`__ is an
enhanced alternative to :mod:`distutils` that provides:

* support for declaring project dependencies
* additional mechanisms for configuring which files to include in source
  releases (including plugins for integration with version control systems)
* the ability to declare project "entry points", which can be used as the
  basis for application plugin systems
* the ability to automatically generate Windows command line executables at
  installation time rather than needing to prebuild them
* consistent behaviour across all supported Python versions

The recommended `pip <https://pip.pypa.io/>`__ installer runs all
``setup.py`` scripts with ``setuptools``, even if the script itself only
imports ``distutils``. Refer to the
`Python Packaging User Guide <https://packaging.python.org>`_ for more
information.

For the benefits of packaging tool authors and users seeking a deeper
understanding of the details of the current packaging and distribution
system, the legacy :mod:`distutils` based user documentation and API
reference remain available:

* :ref:`install-index`
* :ref:`distutils-index`
PK	%�\�{'e@
@
 html/_sources/library/dl.rst.txtnu�[���
:mod:`dl` --- Call C functions in shared objects
================================================

.. module:: dl
   :platform: Unix
   :synopsis: Call C functions in shared objects.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`dl` module has been removed in Python 3. Use the :mod:`ctypes`
    module instead.

.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

The :mod:`dl` module defines an interface to the :c:func:`dlopen` function, which
is the most common interface on Unix platforms for handling dynamically linked
libraries. It allows the program to call arbitrary functions in such a library.

.. warning::

   The :mod:`dl` module bypasses the Python type system and  error handling. If
   used incorrectly it may cause segmentation faults, crashes or other incorrect
   behaviour.

.. note::

   This module will not work unless ``sizeof(int) == sizeof(long) == sizeof(char
   *)`` If this is not the case, :exc:`SystemError` will be raised on import.

The :mod:`dl` module defines the following function:


.. function:: open(name[, mode=RTLD_LAZY])

   Open a shared object file, and return a handle. Mode signifies late binding
   (:const:`RTLD_LAZY`) or immediate binding (:const:`RTLD_NOW`). Default is
   :const:`RTLD_LAZY`. Note that some systems do not support :const:`RTLD_NOW`.

   Return value is a :class:`dlobject`.

The :mod:`dl` module defines the following constants:


.. data:: RTLD_LAZY

   Useful as an argument to :func:`.open`.


.. data:: RTLD_NOW

   Useful as an argument to :func:`.open`.  Note that on systems which do not
   support immediate binding, this constant will not appear in the module. For
   maximum portability, use :func:`hasattr` to determine if the system supports
   immediate binding.

The :mod:`dl` module defines the following exception:


.. exception:: error

   Exception raised when an error has occurred inside the dynamic loading and
   linking routines.

Example::

   >>> import dl, time
   >>> a=dl.open('/lib/libc.so.6')
   >>> a.call('time'), time.time()
   (929723914, 929723914.498)

This example was tried on a Debian GNU/Linux system, and is a good example of
the fact that using this module is usually a bad alternative.


.. _dl-objects:

Dl Objects
----------

Dl objects, as returned by :func:`.open` above, have the following methods:


.. method:: dl.close()

   Free all resources, except the memory.


.. method:: dl.sym(name)

   Return the pointer for the function named *name*, as a number, if it exists in
   the referenced shared object, otherwise ``None``. This is useful in code like::

      >>> if a.sym('time'):
      ...     a.call('time')
      ... else:
      ...     time.time()

   (Note that this function will return a non-zero number, as zero is the *NULL*
   pointer)


.. method:: dl.call(name[, arg1[, arg2...]])

   Call the function named *name* in the referenced shared object. The arguments
   must be either Python integers, which will be  passed as is, Python strings, to
   which a pointer will be passed,  or ``None``, which will be passed as *NULL*.
   Note that  strings should only be passed to functions as :c:type:`const char\*`,
   as Python will not like its string mutated.

   There must be at most 10 arguments, and arguments not given will be treated as
   ``None``. The function's return value must be a C :c:type:`long`, which is a
   Python integer.

PK	%�\5��8!!%html/_sources/library/doctest.rst.txtnu�[���:keepdoctest:

:mod:`doctest` --- Test interactive Python examples
===================================================

.. module:: doctest
   :synopsis: Test pieces of code within docstrings.
.. moduleauthor:: Tim Peters <tim@python.org>
.. sectionauthor:: Tim Peters <tim@python.org>
.. sectionauthor:: Moshe Zadka <moshez@debian.org>
.. sectionauthor:: Edward Loper <edloper@users.sourceforge.net>


The :mod:`doctest` module searches for pieces of text that look like interactive
Python sessions, and then executes those sessions to verify that they work
exactly as shown.  There are several common ways to use doctest:

* To check that a module's docstrings are up-to-date by verifying that all
  interactive examples still work as documented.

* To perform regression testing by verifying that interactive examples from a
  test file or a test object work as expected.

* To write tutorial documentation for a package, liberally illustrated with
  input-output examples.  Depending on whether the examples or the expository text
  are emphasized, this has the flavor of "literate testing" or "executable
  documentation".

Here's a complete but small example module::

   """
   This is the "example" module.

   The example module supplies one function, factorial().  For example,

   >>> factorial(5)
   120
   """

   def factorial(n):
       """Return the factorial of n, an exact integer >= 0.

       If the result is small enough to fit in an int, return an int.
       Else return a long.

       >>> [factorial(n) for n in range(6)]
       [1, 1, 2, 6, 24, 120]
       >>> [factorial(long(n)) for n in range(6)]
       [1, 1, 2, 6, 24, 120]
       >>> factorial(30)
       265252859812191058636308480000000L
       >>> factorial(30L)
       265252859812191058636308480000000L
       >>> factorial(-1)
       Traceback (most recent call last):
           ...
       ValueError: n must be >= 0

       Factorials of floats are OK, but the float must be an exact integer:
       >>> factorial(30.1)
       Traceback (most recent call last):
           ...
       ValueError: n must be exact integer
       >>> factorial(30.0)
       265252859812191058636308480000000L

       It must also not be ridiculously large:
       >>> factorial(1e100)
       Traceback (most recent call last):
           ...
       OverflowError: n too large
       """

       import math
       if not n >= 0:
           raise ValueError("n must be >= 0")
       if math.floor(n) != n:
           raise ValueError("n must be exact integer")
       if n+1 == n:  # catch a value like 1e300
           raise OverflowError("n too large")
       result = 1
       factor = 2
       while factor <= n:
           result *= factor
           factor += 1
       return result


   if __name__ == "__main__":
       import doctest
       doctest.testmod()

If you run :file:`example.py` directly from the command line, :mod:`doctest`
works its magic:

.. code-block:: shell-session

   $ python example.py
   $

There's no output!  That's normal, and it means all the examples worked.  Pass
``-v`` to the script, and :mod:`doctest` prints a detailed log of what
it's trying, and prints a summary at the end:

.. code-block:: shell-session

   $ python example.py -v
   Trying:
       factorial(5)
   Expecting:
       120
   ok
   Trying:
       [factorial(n) for n in range(6)]
   Expecting:
       [1, 1, 2, 6, 24, 120]
   ok
   Trying:
       [factorial(long(n)) for n in range(6)]
   Expecting:
       [1, 1, 2, 6, 24, 120]
   ok

And so on, eventually ending with:

.. code-block:: none

   Trying:
       factorial(1e100)
   Expecting:
       Traceback (most recent call last):
           ...
       OverflowError: n too large
   ok
   2 items passed all tests:
      1 tests in __main__
      8 tests in __main__.factorial
   9 tests in 2 items.
   9 passed and 0 failed.
   Test passed.
   $

That's all you need to know to start making productive use of :mod:`doctest`!
Jump in.  The following sections provide full details.  Note that there are many
examples of doctests in the standard Python test suite and libraries.
Especially useful examples can be found in the standard test file
:file:`Lib/test/test_doctest.py`.


.. _doctest-simple-testmod:

Simple Usage: Checking Examples in Docstrings
---------------------------------------------

The simplest way to start using doctest (but not necessarily the way you'll
continue to do it) is to end each module :mod:`M` with::

   if __name__ == "__main__":
       import doctest
       doctest.testmod()

:mod:`doctest` then examines docstrings in module :mod:`M`.

Running the module as a script causes the examples in the docstrings to get
executed and verified::

   python M.py

This won't display anything unless an example fails, in which case the failing
example(s) and the cause(s) of the failure(s) are printed to stdout, and the
final line of output is ``***Test Failed*** N failures.``, where *N* is the
number of examples that failed.

Run it with the ``-v`` switch instead::

   python M.py -v

and a detailed report of all examples tried is printed to standard output, along
with assorted summaries at the end.

You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or
prohibit it by passing ``verbose=False``.  In either of those cases,
``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not
has no effect).

Since Python 2.6, there is also a command line shortcut for running
:func:`testmod`.  You can instruct the Python interpreter to run the doctest
module directly from the standard library and pass the module name(s) on the
command line::

   python -m doctest -v example.py

This will import :file:`example.py` as a standalone module and run
:func:`testmod` on it.  Note that this may not work correctly if the file is
part of a package and imports other submodules from that package.

For more information on :func:`testmod`, see section :ref:`doctest-basic-api`.


.. _doctest-simple-testfile:

Simple Usage: Checking Examples in a Text File
----------------------------------------------

Another simple application of doctest is testing interactive examples in a text
file.  This can be done with the :func:`testfile` function::

   import doctest
   doctest.testfile("example.txt")

That short script executes and verifies any interactive Python examples
contained in the file :file:`example.txt`.  The file content is treated as if it
were a single giant docstring; the file doesn't need to contain a Python
program!   For example, perhaps :file:`example.txt` contains this:

.. code-block:: none

   The ``example`` module
   ======================

   Using ``factorial``
   -------------------

   This is an example text file in reStructuredText format.  First import
   ``factorial`` from the ``example`` module:

       >>> from example import factorial

   Now use it:

       >>> factorial(6)
       120

Running ``doctest.testfile("example.txt")`` then finds the error in this
documentation::

   File "./example.txt", line 14, in example.txt
   Failed example:
       factorial(6)
   Expected:
       120
   Got:
       720

As with :func:`testmod`, :func:`testfile` won't display anything unless an
example fails.  If an example does fail, then the failing example(s) and the
cause(s) of the failure(s) are printed to stdout, using the same format as
:func:`testmod`.

By default, :func:`testfile` looks for files in the calling module's directory.
See section :ref:`doctest-basic-api` for a description of the optional arguments
that can be used to tell it to look for files in other locations.

Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the
``-v`` command-line switch or with the optional keyword argument
*verbose*.

Since Python 2.6, there is also a command line shortcut for running
:func:`testfile`.  You can instruct the Python interpreter to run the doctest
module directly from the standard library and pass the file name(s) on the
command line::

   python -m doctest -v example.txt

Because the file name does not end with :file:`.py`, :mod:`doctest` infers that
it must be run with :func:`testfile`, not :func:`testmod`.

For more information on :func:`testfile`, see section :ref:`doctest-basic-api`.


.. _doctest-how-it-works:

How It Works
------------

This section examines in detail how doctest works: which docstrings it looks at,
how it finds interactive examples, what execution context it uses, how it
handles exceptions, and how option flags can be used to control its behavior.
This is the information that you need to know to write doctest examples; for
information about actually running doctest on these examples, see the following
sections.


.. _doctest-which-docstrings:

Which Docstrings Are Examined?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The module docstring, and all function, class and method docstrings are
searched.  Objects imported into the module are not searched.

In addition, if ``M.__test__`` exists and "is true", it must be a dict, and each
entry maps a (string) name to a function object, class object, or string.
Function and class object docstrings found from ``M.__test__`` are searched, and
strings are treated as if they were docstrings.  In output, a key ``K`` in
``M.__test__`` appears with name ::

   <name of M>.__test__.K

Any classes found are recursively searched similarly, to test docstrings in
their contained methods and nested classes.

.. versionchanged:: 2.4
   A "private name" concept is deprecated and no longer documented.


.. _doctest-finding-examples:

How are Docstring Examples Recognized?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In most cases a copy-and-paste of an interactive console session works fine,
but doctest isn't trying to do an exact emulation of any specific Python shell.

::

   >>> # comments are ignored
   >>> x = 12
   >>> x
   12
   >>> if x == 13:
   ...     print "yes"
   ... else:
   ...     print "no"
   ...     print "NO"
   ...     print "NO!!!"
   ...
   no
   NO
   NO!!!
   >>>

Any expected output must immediately follow the final ``'>>> '`` or ``'... '``
line containing the code, and the expected output (if any) extends to the next
``'>>> '`` or all-whitespace line.

The fine print:

* Expected output cannot contain an all-whitespace line, since such a line is
  taken to signal the end of expected output.  If expected output does contain a
  blank line, put ``<BLANKLINE>`` in your doctest example each place a blank line
  is expected.

  .. versionadded:: 2.4
     ``<BLANKLINE>`` was added; there was no way to use expected output containing
     empty lines in previous versions.

* All hard tab characters are expanded to spaces, using 8-column tab stops.
  Tabs in output generated by the tested code are not modified.  Because any
  hard tabs in the sample output *are* expanded, this means that if the code
  output includes hard tabs, the only way the doctest can pass is if the
  :const:`NORMALIZE_WHITESPACE` option or :ref:`directive <doctest-directives>`
  is in effect.
  Alternatively, the test can be rewritten to capture the output and compare it
  to an expected value as part of the test.  This handling of tabs in the
  source was arrived at through trial and error, and has proven to be the least
  error prone way of handling them.  It is possible to use a different
  algorithm for handling tabs by writing a custom :class:`DocTestParser` class.

  .. versionchanged:: 2.4
     Expanding tabs to spaces is new; previous versions tried to preserve hard tabs,
     with confusing results.

* Output to stdout is captured, but not output to stderr (exception tracebacks
  are captured via a different means).

* If you continue a line via backslashing in an interactive session, or for any
  other reason use a backslash, you should use a raw docstring, which will
  preserve your backslashes exactly as you type them::

     >>> def f(x):
     ...     r'''Backslashes in a raw docstring: m\n'''
     >>> print f.__doc__
     Backslashes in a raw docstring: m\n

  Otherwise, the backslash will be interpreted as part of the string. For example,
  the ``\n`` above would be interpreted as a newline character.  Alternatively, you
  can double each backslash in the doctest version (and not use a raw string)::

     >>> def f(x):
     ...     '''Backslashes in a raw docstring: m\\n'''
     >>> print f.__doc__
     Backslashes in a raw docstring: m\n

* The starting column doesn't matter::

     >>> assert "Easy!"
           >>> import math
               >>> math.floor(1.9)
               1.0

  and as many leading whitespace characters are stripped from the expected output
  as appeared in the initial ``'>>> '`` line that started the example.


.. _doctest-execution-context:

What's the Execution Context?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, each time :mod:`doctest` finds a docstring to test, it uses a
*shallow copy* of :mod:`M`'s globals, so that running tests doesn't change the
module's real globals, and so that one test in :mod:`M` can't leave behind
crumbs that accidentally allow another test to work.  This means examples can
freely use any names defined at top-level in :mod:`M`, and names defined earlier
in the docstring being run. Examples cannot see names defined in other
docstrings.

You can force use of your own dict as the execution context by passing
``globs=your_dict`` to :func:`testmod` or :func:`testfile` instead.


.. _doctest-exceptions:

What About Exceptions?
^^^^^^^^^^^^^^^^^^^^^^

No problem, provided that the traceback is the only output produced by the
example:  just paste in the traceback. [#]_ Since tracebacks contain details
that are likely to change rapidly (for example, exact file paths and line
numbers), this is one case where doctest works hard to be flexible in what it
accepts.

Simple example::

   >>> [1, 2, 3].remove(42)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: list.remove(x): x not in list

That doctest succeeds if :exc:`ValueError` is raised, with the ``list.remove(x):
x not in list`` detail as shown.

The expected output for an exception must start with a traceback header, which
may be either of the following two lines, indented the same as the first line of
the example::

   Traceback (most recent call last):
   Traceback (innermost last):

The traceback header is followed by an optional traceback stack, whose contents
are ignored by doctest.  The traceback stack is typically omitted, or copied
verbatim from an interactive session.

The traceback stack is followed by the most interesting part: the line(s)
containing the exception type and detail.  This is usually the last line of a
traceback, but can extend across multiple lines if the exception has a
multi-line detail::

   >>> raise ValueError('multi\n    line\ndetail')
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: multi
       line
   detail

The last three lines (starting with :exc:`ValueError`) are compared against the
exception's type and detail, and the rest are ignored.

.. versionchanged:: 2.4
   Previous versions were unable to handle multi-line exception details.

Best practice is to omit the traceback stack, unless it adds significant
documentation value to the example.  So the last example is probably better as::

   >>> raise ValueError('multi\n    line\ndetail')
   Traceback (most recent call last):
       ...
   ValueError: multi
       line
   detail

Note that tracebacks are treated very specially.  In particular, in the
rewritten example, the use of ``...`` is independent of doctest's
:const:`ELLIPSIS` option.  The ellipsis in that example could be left out, or
could just as well be three (or three hundred) commas or digits, or an indented
transcript of a Monty Python skit.

Some details you should read once, but won't need to remember:

* Doctest can't guess whether your expected output came from an exception
  traceback or from ordinary printing.  So, e.g., an example that expects
  ``ValueError: 42 is prime`` will pass whether :exc:`ValueError` is actually
  raised or if the example merely prints that traceback text.  In practice,
  ordinary output rarely begins with a traceback header line, so this doesn't
  create real problems.

* Each line of the traceback stack (if present) must be indented further than
  the first line of the example, *or* start with a non-alphanumeric character.
  The first line following the traceback header indented the same and starting
  with an alphanumeric is taken to be the start of the exception detail.  Of
  course this does the right thing for genuine tracebacks.

* When the :const:`IGNORE_EXCEPTION_DETAIL` doctest option is specified,
  everything following the leftmost colon and any module information in the
  exception name is ignored.

* The interactive shell omits the traceback header line for some
  :exc:`SyntaxError`\ s.  But doctest uses the traceback header line to
  distinguish exceptions from non-exceptions.  So in the rare case where you need
  to test a :exc:`SyntaxError` that omits the traceback header, you will need to
  manually add the traceback header line to your test example.

* For some :exc:`SyntaxError`\ s, Python displays the character position of the
  syntax error, using a ``^`` marker::

     >>> 1 1
       File "<stdin>", line 1
         1 1
           ^
     SyntaxError: invalid syntax

  Since the lines showing the position of the error come before the exception type
  and detail, they are not checked by doctest.  For example, the following test
  would pass, even though it puts the ``^`` marker in the wrong location::

     >>> 1 1
     Traceback (most recent call last):
       File "<stdin>", line 1
         1 1
         ^
     SyntaxError: invalid syntax


.. _option-flags-and-directives:
.. _doctest-options:

Option Flags
^^^^^^^^^^^^

A number of option flags control various aspects of doctest's behavior.
Symbolic names for the flags are supplied as module constants, which can be
:ref:`bitwise ORed <bitwise>` together and passed to various functions.
The names can also be used in :ref:`doctest directives <doctest-directives>`.

The first group of options define test semantics, controlling aspects of how
doctest decides whether actual output matches an example's expected output:


.. data:: DONT_ACCEPT_TRUE_FOR_1

   By default, if an expected output block contains just ``1``, an actual output
   block containing just ``1`` or just ``True`` is considered to be a match, and
   similarly for ``0`` versus ``False``.  When :const:`DONT_ACCEPT_TRUE_FOR_1` is
   specified, neither substitution is allowed.  The default behavior caters to that
   Python changed the return type of many functions from integer to boolean;
   doctests expecting "little integer" output still work in these cases.  This
   option will probably go away, but not for several years.


.. data:: DONT_ACCEPT_BLANKLINE

   By default, if an expected output block contains a line containing only the
   string ``<BLANKLINE>``, then that line will match a blank line in the actual
   output.  Because a genuinely blank line delimits the expected output, this is
   the only way to communicate that a blank line is expected.  When
   :const:`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed.


.. data:: NORMALIZE_WHITESPACE

   When specified, all sequences of whitespace (blanks and newlines) are treated as
   equal.  Any sequence of whitespace within the expected output will match any
   sequence of whitespace within the actual output. By default, whitespace must
   match exactly. :const:`NORMALIZE_WHITESPACE` is especially useful when a line of
   expected output is very long, and you want to wrap it across multiple lines in
   your source.


.. data:: ELLIPSIS

   When specified, an ellipsis marker (``...``) in the expected output can match
   any substring in the actual output.  This includes substrings that span line
   boundaries, and empty substrings, so it's best to keep usage of this simple.
   Complicated uses can lead to the same kinds of "oops, it matched too much!"
   surprises that ``.*`` is prone to in regular expressions.


.. data:: IGNORE_EXCEPTION_DETAIL

   When specified, an example that expects an exception passes if an exception of
   the expected type is raised, even if the exception detail does not match.  For
   example, an example expecting ``ValueError: 42`` will pass if the actual
   exception raised is ``ValueError: 3*14``, but will fail, e.g., if
   :exc:`TypeError` is raised.

   It will also ignore the module name used in Python 3 doctest reports. Hence
   both of these variations will work with the flag specified, regardless of
   whether the test is run under Python 2.7 or Python 3.2 (or later versions)::

      >>> raise CustomError('message')
      Traceback (most recent call last):
      CustomError: message

      >>> raise CustomError('message')
      Traceback (most recent call last):
      my_module.CustomError: message

   Note that :const:`ELLIPSIS` can also be used to ignore the
   details of the exception message, but such a test may still fail based
   on whether or not the module details are printed as part of the
   exception name. Using :const:`IGNORE_EXCEPTION_DETAIL` and the details
   from Python 2.3 is also the only clear way to write a doctest that doesn't
   care about the exception detail yet continues to pass under Python 2.3 or
   earlier (those releases do not support :ref:`doctest directives
   <doctest-directives>` and ignore them as irrelevant comments). For example::

      >>> (1, 2)[3] = 'moo'
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: object doesn't support item assignment

   passes under Python 2.3 and later Python versions with the flag specified,
   even though the detail
   changed in Python 2.4 to say "does not" instead of "doesn't".

   .. versionchanged:: 2.7
      :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information
      relating to the module containing the exception under test


.. data:: SKIP

   When specified, do not run the example at all.  This can be useful in contexts
   where doctest examples serve as both documentation and test cases, and an
   example should be included for documentation purposes, but should not be
   checked.  E.g., the example's output might be random; or the example might
   depend on resources which would be unavailable to the test driver.

   The SKIP flag can also be used for temporarily "commenting out" examples.

.. versionadded:: 2.5


.. data:: COMPARISON_FLAGS

   A bitmask or'ing together all the comparison flags above.

The second group of options controls how test failures are reported:


.. data:: REPORT_UDIFF

   When specified, failures that involve multi-line expected and actual outputs are
   displayed using a unified diff.


.. data:: REPORT_CDIFF

   When specified, failures that involve multi-line expected and actual outputs
   will be displayed using a context diff.


.. data:: REPORT_NDIFF

   When specified, differences are computed by ``difflib.Differ``, using the same
   algorithm as the popular :file:`ndiff.py` utility. This is the only method that
   marks differences within lines as well as across lines.  For example, if a line
   of expected output contains digit ``1`` where actual output contains letter
   ``l``, a line is inserted with a caret marking the mismatching column positions.


.. data:: REPORT_ONLY_FIRST_FAILURE

   When specified, display the first failing example in each doctest, but suppress
   output for all remaining examples.  This will prevent doctest from reporting
   correct examples that break because of earlier failures; but it might also hide
   incorrect examples that fail independently of the first failure.  When
   :const:`REPORT_ONLY_FIRST_FAILURE` is specified, the remaining examples are
   still run, and still count towards the total number of failures reported; only
   the output is suppressed.


.. data:: REPORTING_FLAGS

   A bitmask or'ing together all the reporting flags above.


.. versionadded:: 2.4
   The constants
   :const:`DONT_ACCEPT_BLANKLINE`, :const:`NORMALIZE_WHITESPACE`,
   :const:`ELLIPSIS`, :const:`IGNORE_EXCEPTION_DETAIL`, :const:`REPORT_UDIFF`,
   :const:`REPORT_CDIFF`, :const:`REPORT_NDIFF`,
   :const:`REPORT_ONLY_FIRST_FAILURE`, :const:`COMPARISON_FLAGS` and
   :const:`REPORTING_FLAGS` were added.

There's also a way to register new option flag names, although this isn't useful
unless you intend to extend :mod:`doctest` internals via subclassing:


.. function:: register_optionflag(name)

   Create a new option flag with a given name, and return the new flag's integer
   value.  :func:`register_optionflag` can be used when subclassing
   :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are
   supported by your subclasses.  :func:`register_optionflag` should always be
   called using the following idiom::

      MY_FLAG = register_optionflag('MY_FLAG')

   .. versionadded:: 2.4


.. _doctest-directives:

Directives
^^^^^^^^^^

Doctest directives may be used to modify the :ref:`option flags
<doctest-options>` for an individual example.  Doctest directives are
special Python comments following an example's source code:

.. productionlist:: doctest
   directive: "#" "doctest:" `directive_options`
   directive_options: `directive_option` ("," `directive_option`)\*
   directive_option: `on_or_off` `directive_option_name`
   on_or_off: "+" \| "-"
   directive_option_name: "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...

Whitespace is not allowed between the ``+`` or ``-`` and the directive option
name.  The directive option name can be any of the option flag names explained
above.

An example's doctest directives modify doctest's behavior for that single
example.  Use ``+`` to enable the named behavior, or ``-`` to disable it.

For example, this test passes::

   >>> print range(20) # doctest: +NORMALIZE_WHITESPACE
   [0,   1,  2,  3,  4,  5,  6,  7,  8,  9,
   10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

Without the directive it would fail, both because the actual output doesn't have
two blanks before the single-digit list elements, and because the actual output
is on a single line.  This test also passes, and also requires a directive to do
so::

   >>> print range(20) # doctest: +ELLIPSIS
   [0, 1, ..., 18, 19]

Multiple directives can be used on a single physical line, separated by
commas::

   >>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
   [0,    1, ...,   18,    19]

If multiple directive comments are used for a single example, then they are
combined::

   >>> print range(20) # doctest: +ELLIPSIS
   ...                 # doctest: +NORMALIZE_WHITESPACE
   [0,    1, ...,   18,    19]

As the previous example shows, you can add ``...`` lines to your example
containing only directives.  This can be useful when an example is too long for
a directive to comfortably fit on the same line::

   >>> print range(5) + range(10,20) + range(30,40) + range(50,60)
   ... # doctest: +ELLIPSIS
   [0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]

Note that since all options are disabled by default, and directives apply only
to the example they appear in, enabling options (via ``+`` in a directive) is
usually the only meaningful choice.  However, option flags can also be passed to
functions that run doctests, establishing different defaults.  In such cases,
disabling an option via ``-`` in a directive can be useful.

.. versionadded:: 2.4
   Support for doctest directives was added.


.. _doctest-warnings:

Warnings
^^^^^^^^

:mod:`doctest` is serious about requiring exact matches in expected output.  If
even a single character doesn't match, the test fails.  This will probably
surprise you a few times, as you learn exactly what Python does and doesn't
guarantee about output.  For example, when printing a dict, Python doesn't
guarantee that the key-value pairs will be printed in any particular order, so a
test like ::

   >>> foo()
   {"Hermione": "hippogryph", "Harry": "broomstick"}

is vulnerable!  One workaround is to do ::

   >>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
   True

instead.  Another is to do ::

   >>> d = foo().items()
   >>> d.sort()
   >>> d
   [('Harry', 'broomstick'), ('Hermione', 'hippogryph')]

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like ::

   >>> id(1.0) # certain to fail some of the time
   7948648
   >>> class C: pass
   >>> C()   # the default repr() for instances embeds an address
   <__main__.C instance at 0x00AC18F0>

The :const:`ELLIPSIS` directive gives a nice approach for the last example::

   >>> C() #doctest: +ELLIPSIS
   <__main__.C instance at 0x...>

Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for float formatting,
and C libraries vary widely in quality here. ::

   >>> 1./7  # risky
   0.14285714285714285
   >>> print 1./7 # safer
   0.142857142857
   >>> print round(1./7, 6) # much safer
   0.142857

Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
contrive doctest examples to produce numbers of that form::

   >>> 3./4  # utterly safe
   0.75

Simple fractions are also easier for people to understand, and that makes for
better documentation.


.. _doctest-basic-api:

Basic API
---------

The functions :func:`testmod` and :func:`testfile` provide a simple interface to
doctest that should be sufficient for most basic uses.  For a less formal
introduction to these two functions, see sections :ref:`doctest-simple-testmod`
and :ref:`doctest-simple-testfile`.


.. function:: testfile(filename[, module_relative][, name][, package][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, parser][, encoding])

   All arguments except *filename* are optional, and should be specified in keyword
   form.

   Test examples in the file named *filename*.  Return ``(failure_count,
   test_count)``.

   Optional argument *module_relative* specifies how the filename should be
   interpreted:

   * If *module_relative* is ``True`` (the default), then *filename* specifies an
     OS-independent module-relative path.  By default, this path is relative to the
     calling module's directory; but if the *package* argument is specified, then it
     is relative to that package.  To ensure OS-independence, *filename* should use
     ``/`` characters to separate path segments, and may not be an absolute path
     (i.e., it may not begin with ``/``).

   * If *module_relative* is ``False``, then *filename* specifies an OS-specific
     path.  The path may be absolute or relative; relative paths are resolved with
     respect to the current working directory.

   Optional argument *name* gives the name of the test; by default, or if ``None``,
   ``os.path.basename(filename)`` is used.

   Optional argument *package* is a Python package or the name of a Python package
   whose directory should be used as the base directory for a module-relative
   filename.  If no package is specified, then the calling module's directory is
   used as the base directory for module-relative filenames.  It is an error to
   specify *package* if *module_relative* is ``False``.

   Optional argument *globs* gives a dict to be used as the globals when executing
   examples.  A new shallow copy of this dict is created for the doctest, so its
   examples start with a clean slate. By default, or if ``None``, a new empty dict
   is used.

   Optional argument *extraglobs* gives a dict merged into the globals used to
   execute examples.  This works like :meth:`dict.update`:  if *globs* and
   *extraglobs* have a common key, the associated value in *extraglobs* appears in
   the combined dict.  By default, or if ``None``, no extra globals are used.  This
   is an advanced feature that allows parameterization of doctests.  For example, a
   doctest can be written for a base class, using a generic name for the class,
   then reused to test any number of subclasses by passing an *extraglobs* dict
   mapping the generic name to the subclass to be tested.

   Optional argument *verbose* prints lots of stuff if true, and prints only
   failures if false; by default, or if ``None``, it's true if and only if ``'-v'``
   is in ``sys.argv``.

   Optional argument *report* prints a summary at the end when true, else prints
   nothing at the end.  In verbose mode, the summary is detailed, else the summary
   is very brief (in fact, empty if all tests passed).

   Optional argument *optionflags* or's together option flags.  See section
   :ref:`doctest-options`.

   Optional argument *raise_on_error* defaults to false.  If true, an exception is
   raised upon the first failure or unexpected exception in an example.  This
   allows failures to be post-mortem debugged. Default behavior is to continue
   running examples.

   Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) that
   should be used to extract tests from the files.  It defaults to a normal parser
   (i.e., ``DocTestParser()``).

   Optional argument *encoding* specifies an encoding that should be used to
   convert the file to unicode.

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      The parameter *encoding* was added.


.. function:: testmod([m][, name][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, exclude_empty])

   All arguments are optional, and all except for *m* should be specified in
   keyword form.

   Test examples in docstrings in functions and classes reachable from module *m*
   (or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with
   ``m.__doc__``.

   Also test examples reachable from dict ``m.__test__``, if it exists and is not
   ``None``.  ``m.__test__`` maps names (strings) to functions, classes and
   strings; function and class docstrings are searched for examples; strings are
   searched directly, as if they were docstrings.

   Only docstrings attached to objects belonging to module *m* are searched.

   Return ``(failure_count, test_count)``.

   Optional argument *name* gives the name of the module; by default, or if
   ``None``, ``m.__name__`` is used.

   Optional argument *exclude_empty* defaults to false.  If true, objects for which
   no doctests are found are excluded from consideration. The default is a backward
   compatibility hack, so that code still using :meth:`doctest.master.summarize` in
   conjunction with :func:`testmod` continues to get output for objects with no
   tests. The *exclude_empty* argument to the newer :class:`DocTestFinder`
   constructor defaults to true.

   Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*,
   *raise_on_error*, and *globs* are the same as for function :func:`testfile`
   above, except that *globs* defaults to ``m.__dict__``.

   .. versionchanged:: 2.3
      The parameter *optionflags* was added.

   .. versionchanged:: 2.4
      The parameters *extraglobs*, *raise_on_error* and *exclude_empty* were added.

   .. versionchanged:: 2.5
      The optional argument *isprivate*, deprecated in 2.4, was removed.


.. function:: run_docstring_examples(f, globs[, verbose][, name][, compileflags][, optionflags])

   Test examples associated with object *f*; for example, *f* may be a string,
   a module, a function, or a class object.

   A shallow copy of dictionary argument *globs* is used for the execution context.

   Optional argument *name* is used in failure messages, and defaults to
   ``"NoName"``.

   If optional argument *verbose* is true, output is generated even if there are no
   failures.  By default, output is generated only in case of an example failure.

   Optional argument *compileflags* gives the set of flags that should be used by
   the Python compiler when running the examples.  By default, or if ``None``,
   flags are deduced corresponding to the set of future features found in *globs*.

   Optional argument *optionflags* works as for function :func:`testfile` above.


.. _doctest-unittest-api:

Unittest API
------------

As your collection of doctest'ed modules grows, you'll want a way to run all
their doctests systematically.  Prior to Python 2.4, :mod:`doctest` had a barely
documented :class:`Tester` class that supplied a rudimentary way to combine
doctests from multiple modules. :class:`Tester` was feeble, and in practice most
serious Python testing frameworks build on the :mod:`unittest` module, which
supplies many flexible ways to combine tests from multiple sources.  So, in
Python 2.4, :mod:`doctest`'s :class:`Tester` class is deprecated, and
:mod:`doctest` provides two functions that can be used to create :mod:`unittest`
test suites from modules and text files containing doctests.  To integrate with
:mod:`unittest` test discovery, include a :func:`load_tests` function in your
test module::

   import unittest
   import doctest
   import my_module_with_doctests

   def load_tests(loader, tests, ignore):
       tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
       return tests

There are two main functions for creating :class:`unittest.TestSuite` instances
from text files and modules with doctests:


.. function:: DocFileSuite(*paths, [module_relative][, package][, setUp][, tearDown][, globs][, optionflags][, parser][, encoding])

   Convert doctest tests from one or more text files to a
   :class:`unittest.TestSuite`.

   The returned :class:`unittest.TestSuite` is to be run by the unittest framework
   and runs the interactive examples in each file.  If an example in any file
   fails, then the synthesized unit test fails, and a :exc:`failureException`
   exception is raised showing the name of the file containing the test and a
   (sometimes approximate) line number.

   Pass one or more paths (as strings) to text files to be examined.

   Options may be provided as keyword arguments:

   Optional argument *module_relative* specifies how the filenames in *paths*
   should be interpreted:

   * If *module_relative* is ``True`` (the default), then each filename in
     *paths* specifies an OS-independent module-relative path.  By default, this
     path is relative to the calling module's directory; but if the *package*
     argument is specified, then it is relative to that package.  To ensure
     OS-independence, each filename should use ``/`` characters to separate path
     segments, and may not be an absolute path (i.e., it may not begin with
     ``/``).

   * If *module_relative* is ``False``, then each filename in *paths* specifies
     an OS-specific path.  The path may be absolute or relative; relative paths
     are resolved with respect to the current working directory.

   Optional argument *package* is a Python package or the name of a Python
   package whose directory should be used as the base directory for
   module-relative filenames in *paths*.  If no package is specified, then the
   calling module's directory is used as the base directory for module-relative
   filenames.  It is an error to specify *package* if *module_relative* is
   ``False``.

   Optional argument *setUp* specifies a set-up function for the test suite.
   This is called before running the tests in each file.  The *setUp* function
   will be passed a :class:`DocTest` object.  The setUp function can access the
   test globals as the *globs* attribute of the test passed.

   Optional argument *tearDown* specifies a tear-down function for the test
   suite.  This is called after running the tests in each file.  The *tearDown*
   function will be passed a :class:`DocTest` object.  The setUp function can
   access the test globals as the *globs* attribute of the test passed.

   Optional argument *globs* is a dictionary containing the initial global
   variables for the tests.  A new copy of this dictionary is created for each
   test.  By default, *globs* is a new empty dictionary.

   Optional argument *optionflags* specifies the default doctest options for the
   tests, created by or-ing together individual option flags.  See section
   :ref:`doctest-options`. See function :func:`set_unittest_reportflags` below
   for a better way to set reporting options.

   Optional argument *parser* specifies a :class:`DocTestParser` (or subclass)
   that should be used to extract tests from the files.  It defaults to a normal
   parser (i.e., ``DocTestParser()``).

   Optional argument *encoding* specifies an encoding that should be used to
   convert the file to unicode.

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      The global ``__file__`` was added to the globals provided to doctests
      loaded from a text file using :func:`DocFileSuite`.

   .. versionchanged:: 2.5
      The parameter *encoding* was added.

   .. note::
      Unlike :func:`testmod` and :class:`DocTestFinder`, this function raises
      a :exc:`ValueError` if *module* contains no docstrings.  You can prevent
      this error by passing a :class:`DocTestFinder` instance as the
      *test_finder* argument with its *exclude_empty* keyword argument set
      to ``False``::

         >>> finder = doctest.DocTestFinder(exclude_empty=False)
         >>> suite = doctest.DocTestSuite(test_finder=finder)


.. function:: DocTestSuite([module][, globs][, extraglobs][, test_finder][, setUp][, tearDown][, checker])

   Convert doctest tests for a module to a :class:`unittest.TestSuite`.

   The returned :class:`unittest.TestSuite` is to be run by the unittest framework
   and runs each doctest in the module.  If any of the doctests fail, then the
   synthesized unit test fails, and a :exc:`failureException` exception is raised
   showing the name of the file containing the test and a (sometimes approximate)
   line number.

   Optional argument *module* provides the module to be tested.  It can be a module
   object or a (possibly dotted) module name.  If not specified, the module calling
   this function is used.

   Optional argument *globs* is a dictionary containing the initial global
   variables for the tests.  A new copy of this dictionary is created for each
   test.  By default, *globs* is a new empty dictionary.

   Optional argument *extraglobs* specifies an extra set of global variables, which
   is merged into *globs*.  By default, no extra globals are used.

   Optional argument *test_finder* is the :class:`DocTestFinder` object (or a
   drop-in replacement) that is used to extract doctests from the module.

   Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for
   function :func:`DocFileSuite` above.

   .. versionadded:: 2.3

   .. versionchanged:: 2.4
      The parameters *globs*, *extraglobs*, *test_finder*, *setUp*, *tearDown*, and
      *optionflags* were added; this function now uses the same search technique as
      :func:`testmod`.

Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented
here (it's an internal detail), but studying its code can answer questions about
the exact details of :mod:`unittest` integration.

Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of
:class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass
of :class:`DocTestCase`.

So both ways of creating a :class:`unittest.TestSuite` run instances of
:class:`DocTestCase`.  This is important for a subtle reason: when you run
:mod:`doctest` functions yourself, you can control the :mod:`doctest` options in
use directly, by passing option flags to :mod:`doctest` functions.  However, if
you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls
when and how tests get run.  The framework author typically wants to control
:mod:`doctest` reporting options (perhaps, e.g., specified by command line
options), but there's no way to pass options through :mod:`unittest` to
:mod:`doctest` test runners.

For this reason, :mod:`doctest` also supports a notion of :mod:`doctest`
reporting flags specific to :mod:`unittest` support, via this function:


.. function:: set_unittest_reportflags(flags)

   Set the :mod:`doctest` reporting flags to use.

   Argument *flags* or's together option flags.  See section
   :ref:`doctest-options`.  Only "reporting flags" can be used.

   This is a module-global setting, and affects all future doctests run by module
   :mod:`unittest`:  the :meth:`runTest` method of :class:`DocTestCase` looks at
   the option flags specified for the test case when the :class:`DocTestCase`
   instance was constructed.  If no reporting flags were specified (which is the
   typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are
   :ref:`bitwise ORed <bitwise>` into the option flags, and the option flags
   so augmented are passed to the :class:`DocTestRunner` instance created to
   run the doctest.  If any reporting flags were specified when the
   :class:`DocTestCase` instance was constructed, :mod:`doctest`'s
   :mod:`unittest` reporting flags are ignored.

   The value of the :mod:`unittest` reporting flags in effect before the function
   was called is returned by the function.

   .. versionadded:: 2.4


.. _doctest-advanced-api:

Advanced API
------------

The basic API is a simple wrapper that's intended to make doctest easy to use.
It is fairly flexible, and should meet most users' needs; however, if you
require more fine-grained control over testing, or wish to extend doctest's
capabilities, then you should use the advanced API.

The advanced API revolves around two container classes, which are used to store
the interactive examples extracted from doctest cases:

* :class:`Example`: A single Python :term:`statement`, paired with its expected
  output.

* :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted
  from a single docstring or text file.

Additional processing classes are defined to find, parse, and run, and check
doctest examples:

* :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a
  :class:`DocTestParser` to create a :class:`DocTest` from every docstring that
  contains interactive examples.

* :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such
  as an object's docstring).

* :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses
  an :class:`OutputChecker` to verify their output.

* :class:`OutputChecker`: Compares the actual output from a doctest example with
  the expected output, and decides whether they match.

The relationships among these processing classes are summarized in the following
diagram::

                               list of:
   +------+                   +---------+
   |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
   +------+    |        ^     +---------+     |       ^    (printed)
               |        |     | Example |     |       |
               v        |     |   ...   |     v       |
              DocTestParser   | Example |   OutputChecker
                              +---------+


.. _doctest-doctest:

DocTest Objects
^^^^^^^^^^^^^^^


.. class:: DocTest(examples, globs, name, filename, lineno, docstring)

   A collection of doctest examples that should be run in a single namespace.  The
   constructor arguments are used to initialize the attributes of the same names.

   .. versionadded:: 2.4

   :class:`DocTest` defines the following attributes.  They are initialized by
   the constructor, and should not be modified directly.


   .. attribute:: examples

      A list of :class:`Example` objects encoding the individual interactive Python
      examples that should be run by this test.


   .. attribute:: globs

      The namespace (aka globals) that the examples should be run in. This is a
      dictionary mapping names to values.  Any changes to the namespace made by the
      examples (such as binding new variables) will be reflected in :attr:`globs`
      after the test is run.


   .. attribute:: name

      A string name identifying the :class:`DocTest`.  Typically, this is the name
      of the object or file that the test was extracted from.


   .. attribute:: filename

      The name of the file that this :class:`DocTest` was extracted from; or
      ``None`` if the filename is unknown, or if the :class:`DocTest` was not
      extracted from a file.


   .. attribute:: lineno

      The line number within :attr:`filename` where this :class:`DocTest` begins, or
      ``None`` if the line number is unavailable.  This line number is zero-based
      with respect to the beginning of the file.


   .. attribute:: docstring

      The string that the test was extracted from, or ``None`` if the string is
      unavailable, or if the test was not extracted from a string.


.. _doctest-example:

Example Objects
^^^^^^^^^^^^^^^


.. class:: Example(source, want[, exc_msg][, lineno][, indent][, options])

   A single interactive example, consisting of a Python statement and its expected
   output.  The constructor arguments are used to initialize the attributes of the
   same names.

   .. versionadded:: 2.4

   :class:`Example` defines the following attributes.  They are initialized by
   the constructor, and should not be modified directly.


   .. attribute:: source

      A string containing the example's source code.  This source code consists of a
      single Python statement, and always ends with a newline; the constructor adds
      a newline when necessary.


   .. attribute:: want

      The expected output from running the example's source code (either from
      stdout, or a traceback in case of exception).  :attr:`want` ends with a
      newline unless no output is expected, in which case it's an empty string.  The
      constructor adds a newline when necessary.


   .. attribute:: exc_msg

      The exception message generated by the example, if the example is expected to
      generate an exception; or ``None`` if it is not expected to generate an
      exception.  This exception message is compared against the return value of
      :func:`traceback.format_exception_only`.  :attr:`exc_msg` ends with a newline
      unless it's ``None``.  The constructor adds a newline if needed.


   .. attribute:: lineno

      The line number within the string containing this example where the example
      begins.  This line number is zero-based with respect to the beginning of the
      containing string.


   .. attribute:: indent

      The example's indentation in the containing string, i.e., the number of space
      characters that precede the example's first prompt.


   .. attribute:: options

      A dictionary mapping from option flags to ``True`` or ``False``, which is used
      to override default options for this example.  Any option flags not contained
      in this dictionary are left at their default value (as specified by the
      :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.


.. _doctest-doctestfinder:

DocTestFinder objects
^^^^^^^^^^^^^^^^^^^^^


.. class:: DocTestFinder([verbose][, parser][, recurse][, exclude_empty])

   A processing class used to extract the :class:`DocTest`\ s that are relevant to
   a given object, from its docstring and the docstrings of its contained objects.
   :class:`DocTest`\ s can currently be extracted from the following object types:
   modules, functions, classes, methods, staticmethods, classmethods, and
   properties.

   The optional argument *verbose* can be used to display the objects searched by
   the finder.  It defaults to ``False`` (no output).

   The optional argument *parser* specifies the :class:`DocTestParser` object (or a
   drop-in replacement) that is used to extract doctests from docstrings.

   If the optional argument *recurse* is false, then :meth:`DocTestFinder.find`
   will only examine the given object, and not any contained objects.

   If the optional argument *exclude_empty* is false, then
   :meth:`DocTestFinder.find` will include tests for objects with empty docstrings.

   .. versionadded:: 2.4

   :class:`DocTestFinder` defines the following method:


   .. method:: find(obj[, name][, module][, globs][, extraglobs])

      Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
      docstring, or by any of its contained objects' docstrings.

      The optional argument *name* specifies the object's name; this name will be
      used to construct names for the returned :class:`DocTest`\ s.  If *name* is
      not specified, then ``obj.__name__`` is used.

      The optional parameter *module* is the module that contains the given object.
      If the module is not specified or is ``None``, then the test finder will attempt
      to automatically determine the correct module.  The object's module is used:

      * As a default namespace, if *globs* is not specified.

      * To prevent the DocTestFinder from extracting DocTests from objects that are
        imported from other modules.  (Contained objects with modules other than
        *module* are ignored.)

      * To find the name of the file containing the object.

      * To help find the line number of the object within its file.

      If *module* is ``False``, no attempt to find the module will be made.  This is
      obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
      is ``None`` but cannot be found automatically, then all objects are considered
      to belong to the (non-existent) module, so all contained objects will
      (recursively) be searched for doctests.

      The globals for each :class:`DocTest` is formed by combining *globs* and
      *extraglobs* (bindings in *extraglobs* override bindings in *globs*).  A new
      shallow copy of the globals dictionary is created for each :class:`DocTest`.
      If *globs* is not specified, then it defaults to the module's *__dict__*, if
      specified, or ``{}`` otherwise.  If *extraglobs* is not specified, then it
      defaults to ``{}``.


.. _doctest-doctestparser:

DocTestParser objects
^^^^^^^^^^^^^^^^^^^^^


.. class:: DocTestParser()

   A processing class used to extract interactive examples from a string, and use
   them to create a :class:`DocTest` object.

   .. versionadded:: 2.4

   :class:`DocTestParser` defines the following methods:


   .. method:: get_doctest(string, globs, name, filename, lineno)

      Extract all doctest examples from the given string, and collect them into a
      :class:`DocTest` object.

      *globs*, *name*, *filename*, and *lineno* are attributes for the new
      :class:`DocTest` object.  See the documentation for :class:`DocTest` for more
      information.


   .. method:: get_examples(string[, name])

      Extract all doctest examples from the given string, and return them as a list
      of :class:`Example` objects.  Line numbers are 0-based.  The optional argument
      *name* is a name identifying this string, and is only used for error messages.


   .. method:: parse(string[, name])

      Divide the given string into examples and intervening text, and return them as
      a list of alternating :class:`Example`\ s and strings. Line numbers for the
      :class:`Example`\ s are 0-based.  The optional argument *name* is a name
      identifying this string, and is only used for error messages.


.. _doctest-doctestrunner:

DocTestRunner objects
^^^^^^^^^^^^^^^^^^^^^


.. class:: DocTestRunner([checker][, verbose][, optionflags])

   A processing class used to execute and verify the interactive examples in a
   :class:`DocTest`.

   The comparison between expected outputs and actual outputs is done by an
   :class:`OutputChecker`.  This comparison may be customized with a number of
   option flags; see section :ref:`doctest-options` for more information.  If the
   option flags are insufficient, then the comparison may also be customized by
   passing a subclass of :class:`OutputChecker` to the constructor.

   The test runner's display output can be controlled in two ways. First, an output
   function can be passed to :meth:`TestRunner.run`; this function will be called
   with strings that should be displayed.  It defaults to ``sys.stdout.write``.  If
   capturing the output is not sufficient, then the display output can be also
   customized by subclassing DocTestRunner, and overriding the methods
   :meth:`report_start`, :meth:`report_success`,
   :meth:`report_unexpected_exception`, and :meth:`report_failure`.

   The optional keyword argument *checker* specifies the :class:`OutputChecker`
   object (or drop-in replacement) that should be used to compare the expected
   outputs to the actual outputs of doctest examples.

   The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s
   verbosity.  If *verbose* is ``True``, then information is printed about each
   example, as it is run.  If *verbose* is ``False``, then only failures are
   printed.  If *verbose* is unspecified, or ``None``, then verbose output is used
   iff the command-line switch ``-v`` is used.

   The optional keyword argument *optionflags* can be used to control how the test
   runner compares expected output to actual output, and how it displays failures.
   For more information, see section :ref:`doctest-options`.

   .. versionadded:: 2.4

   :class:`DocTestParser` defines the following methods:


   .. method:: report_start(out, test, example)

      Report that the test runner is about to process the given example. This method
      is provided to allow subclasses of :class:`DocTestRunner` to customize their
      output; it should not be called directly.

      *example* is the example about to be processed.  *test* is the test
      *containing example*.  *out* is the output function that was passed to
      :meth:`DocTestRunner.run`.


   .. method:: report_success(out, test, example, got)

      Report that the given example ran successfully.  This method is provided to
      allow subclasses of :class:`DocTestRunner` to customize their output; it
      should not be called directly.

      *example* is the example about to be processed.  *got* is the actual output
      from the example.  *test* is the test containing *example*.  *out* is the
      output function that was passed to :meth:`DocTestRunner.run`.


   .. method:: report_failure(out, test, example, got)

      Report that the given example failed.  This method is provided to allow
      subclasses of :class:`DocTestRunner` to customize their output; it should not
      be called directly.

      *example* is the example about to be processed.  *got* is the actual output
      from the example.  *test* is the test containing *example*.  *out* is the
      output function that was passed to :meth:`DocTestRunner.run`.


   .. method:: report_unexpected_exception(out, test, example, exc_info)

      Report that the given example raised an unexpected exception. This method is
      provided to allow subclasses of :class:`DocTestRunner` to customize their
      output; it should not be called directly.

      *example* is the example about to be processed. *exc_info* is a tuple
      containing information about the unexpected exception (as returned by
      :func:`sys.exc_info`). *test* is the test containing *example*.  *out* is the
      output function that was passed to :meth:`DocTestRunner.run`.


   .. method:: run(test[, compileflags][, out][, clear_globs])

      Run the examples in *test* (a :class:`DocTest` object), and display the
      results using the writer function *out*.

      The examples are run in the namespace ``test.globs``.  If *clear_globs* is
      true (the default), then this namespace will be cleared after the test runs,
      to help with garbage collection. If you would like to examine the namespace
      after the test completes, then use *clear_globs=False*.

      *compileflags* gives the set of flags that should be used by the Python
      compiler when running the examples.  If not specified, then it will default to
      the set of future-import flags that apply to *globs*.

      The output of each example is checked using the :class:`DocTestRunner`'s
      output checker, and the results are formatted by the
      :meth:`DocTestRunner.report_\*` methods.


   .. method:: summarize([verbose])

      Print a summary of all the test cases that have been run by this DocTestRunner,
      and return a :term:`named tuple` ``TestResults(failed, attempted)``.

      The optional *verbose* argument controls how detailed the summary is.  If the
      verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
      used.

      .. versionchanged:: 2.6
         Use a named tuple.


.. _doctest-outputchecker:

OutputChecker objects
^^^^^^^^^^^^^^^^^^^^^


.. class:: OutputChecker()

   A class used to check the whether the actual output from a doctest example
   matches the expected output.  :class:`OutputChecker` defines two methods:
   :meth:`check_output`, which compares a given pair of outputs, and returns true
   if they match; and :meth:`output_difference`, which returns a string describing
   the differences between two outputs.

   .. versionadded:: 2.4

   :class:`OutputChecker` defines the following methods:


   .. method:: check_output(want, got, optionflags)

      Return ``True`` iff the actual output from an example (*got*) matches the
      expected output (*want*).  These strings are always considered to match if
      they are identical; but depending on what option flags the test runner is
      using, several non-exact match types are also possible.  See section
      :ref:`doctest-options` for more information about option flags.


   .. method:: output_difference(example, got, optionflags)

      Return a string describing the differences between the expected output for a
      given example (*example*) and the actual output (*got*).  *optionflags* is the
      set of option flags used to compare *want* and *got*.


.. _doctest-debugging:

Debugging
---------

Doctest provides several mechanisms for debugging doctest examples:

* Several functions convert doctests to executable Python programs, which can be
  run under the Python debugger, :mod:`pdb`.

* The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that
  raises an exception for the first failing example, containing information about
  that example. This information can be used to perform post-mortem debugging on
  the example.

* The :mod:`unittest` cases generated by :func:`DocTestSuite` support the
  :meth:`debug` method defined by :class:`unittest.TestCase`.

* You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll
  drop into the Python debugger when that line is executed.  Then you can inspect
  current values of variables, and so on.  For example, suppose :file:`a.py`
  contains just this module docstring::

     """
     >>> def f(x):
     ...     g(x*2)
     >>> def g(x):
     ...     print x+3
     ...     import pdb; pdb.set_trace()
     >>> f(3)
     9
     """

  Then an interactive Python session may look like this::

     >>> import a, doctest
     >>> doctest.testmod(a)
     --Return--
     > <doctest a[1]>(3)g()->None
     -> import pdb; pdb.set_trace()
     (Pdb) list
       1     def g(x):
       2         print x+3
       3  ->     import pdb; pdb.set_trace()
     [EOF]
     (Pdb) print x
     6
     (Pdb) step
     --Return--
     > <doctest a[0]>(2)f()->None
     -> g(x*2)
     (Pdb) list
       1     def f(x):
       2  ->     g(x*2)
     [EOF]
     (Pdb) print x
     3
     (Pdb) step
     --Return--
     > <doctest a[2]>(1)?()->None
     -> f(3)
     (Pdb) cont
     (0, 3)
     >>>

  .. versionchanged:: 2.4
     The ability to use :func:`pdb.set_trace` usefully inside doctests was added.

Functions that convert doctests to Python code, and possibly run the synthesized
code under the debugger:


.. function:: script_from_examples(s)

   Convert text with examples to a script.

   Argument *s* is a string containing doctest examples.  The string is converted
   to a Python script, where doctest examples in *s* are converted to regular code,
   and everything else is converted to Python comments.  The generated script is
   returned as a string. For example, ::

      import doctest
      print doctest.script_from_examples(r"""
          Set x and y to 1 and 2.
          >>> x, y = 1, 2

          Print their sum:
          >>> print x+y
          3
      """)

   displays::

      # Set x and y to 1 and 2.
      x, y = 1, 2
      #
      # Print their sum:
      print x+y
      # Expected:
      ## 3

   This function is used internally by other functions (see below), but can also be
   useful when you want to transform an interactive Python session into a Python
   script.

   .. versionadded:: 2.4


.. function:: testsource(module, name)

   Convert the doctest for an object to a script.

   Argument *module* is a module object, or dotted name of a module, containing the
   object whose doctests are of interest.  Argument *name* is the name (within the
   module) of the object with the doctests of interest.  The result is a string,
   containing the object's docstring converted to a Python script, as described for
   :func:`script_from_examples` above.  For example, if module :file:`a.py`
   contains a top-level function :func:`f`, then ::

      import a, doctest
      print doctest.testsource(a, "a.f")

   prints a script version of function :func:`f`'s docstring, with doctests
   converted to code, and the rest placed in comments.

   .. versionadded:: 2.3


.. function:: debug(module, name[, pm])

   Debug the doctests for an object.

   The *module* and *name* arguments are the same as for function
   :func:`testsource` above.  The synthesized Python script for the named object's
   docstring is written to a temporary file, and then that file is run under the
   control of the Python debugger, :mod:`pdb`.

   A shallow copy of ``module.__dict__`` is used for both local and global
   execution context.

   Optional argument *pm* controls whether post-mortem debugging is used.  If *pm*
   has a true value, the script file is run directly, and the debugger gets
   involved only if the script terminates via raising an unhandled exception.  If
   it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`,
   passing the traceback object from the unhandled exception.  If *pm* is not
   specified, or is false, the script is run under the debugger from the start, via
   passing an appropriate :func:`execfile` call to :func:`pdb.run`.

   .. versionadded:: 2.3

   .. versionchanged:: 2.4
      The *pm* argument was added.


.. function:: debug_src(src[, pm][, globs])

   Debug the doctests in a string.

   This is like function :func:`debug` above, except that a string containing
   doctest examples is specified directly, via the *src* argument.

   Optional argument *pm* has the same meaning as in function :func:`debug` above.

   Optional argument *globs* gives a dictionary to use as both local and global
   execution context.  If not specified, or ``None``, an empty dictionary is used.
   If specified, a shallow copy of the dictionary is used.

   .. versionadded:: 2.4

The :class:`DebugRunner` class, and the special exceptions it may raise, are of
most interest to testing framework authors, and will only be sketched here.  See
the source code, and especially :class:`DebugRunner`'s docstring (which is a
doctest!) for more details:


.. class:: DebugRunner([checker][, verbose][, optionflags])

   A subclass of :class:`DocTestRunner` that raises an exception as soon as a
   failure is encountered.  If an unexpected exception occurs, an
   :exc:`UnexpectedException` exception is raised, containing the test, the
   example, and the original exception.  If the output doesn't match, then a
   :exc:`DocTestFailure` exception is raised, containing the test, the example, and
   the actual output.

   For information about the constructor parameters and methods, see the
   documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`.

There are two exceptions that may be raised by :class:`DebugRunner` instances:


.. exception:: DocTestFailure(test, example, got)

   An exception raised by :class:`DocTestRunner` to signal that a doctest example's
   actual output did not match its expected output. The constructor arguments are
   used to initialize the attributes of the same names.

:exc:`DocTestFailure` defines the following attributes:


.. attribute:: DocTestFailure.test

   The :class:`DocTest` object that was being run when the example failed.


.. attribute:: DocTestFailure.example

   The :class:`Example` that failed.


.. attribute:: DocTestFailure.got

   The example's actual output.


.. exception:: UnexpectedException(test, example, exc_info)

   An exception raised by :class:`DocTestRunner` to signal that a doctest
   example raised an unexpected exception.  The constructor arguments are used
   to initialize the attributes of the same names.

:exc:`UnexpectedException` defines the following attributes:


.. attribute:: UnexpectedException.test

   The :class:`DocTest` object that was being run when the example failed.


.. attribute:: UnexpectedException.example

   The :class:`Example` that failed.


.. attribute:: UnexpectedException.exc_info

   A tuple containing information about the unexpected exception, as returned by
   :func:`sys.exc_info`.


.. _doctest-soapbox:

Soapbox
-------

As mentioned in the introduction, :mod:`doctest` has grown to have three primary
uses:

#. Checking examples in docstrings.

#. Regression testing.

#. Executable documentation / literate testing.

These uses have different requirements, and it is important to distinguish them.
In particular, filling your docstrings with obscure test cases makes for bad
documentation.

When writing a docstring, choose docstring examples with care. There's an art to
this that needs to be learned---it may not be natural at first.  Examples should
add genuine value to the documentation.  A good example can often be worth many
words. If done with care, the examples will be invaluable for your users, and
will pay back the time it takes to collect them many times over as the years go
by and things change.  I'm still amazed at how often one of my :mod:`doctest`
examples stops working after a "harmless" change.

Doctest also makes an excellent tool for regression testing, especially if you
don't skimp on explanatory text.  By interleaving prose and examples, it becomes
much easier to keep track of what's actually being tested, and why.  When a test
fails, good prose can make it much easier to figure out what the problem is, and
how it should be fixed.  It's true that you could write extensive comments in
code-based testing, but few programmers do. Many have found that using doctest
approaches instead leads to much clearer tests.  Perhaps this is simply because
doctest makes writing prose a little easier than writing code, while writing
comments in code is a little harder.  I think it goes deeper than just that:
the natural attitude when writing a doctest-based test is that you want to
explain the fine points of your software, and illustrate them with examples.
This in turn naturally leads to test files that start with the simplest
features, and logically progress to complications and edge cases.  A coherent
narrative is the result, instead of a collection of isolated functions that test
isolated bits of functionality seemingly at random.  It's a different attitude,
and produces different results, blurring the distinction between testing and
explaining.

Regression testing is best confined to dedicated objects or files.  There are
several options for organizing tests:

* Write text files containing test cases as interactive examples, and test the
  files using :func:`testfile` or :func:`DocFileSuite`.  This is recommended,
  although is easiest to do for new projects, designed from the start to use
  doctest.

* Define functions named ``_regrtest_topic`` that consist of single docstrings,
  containing test cases for the named topics.  These functions can be included in
  the same file as the module, or separated out into a separate test file.

* Define a ``__test__`` dictionary mapping from regression test topics to
  docstrings containing test cases.

When you have placed your tests in a module, the module can itself be the test
runner.  When a test fails, you can arrange for your test runner to re-run only
the failing doctest while you debug the problem.  Here is a minimal example of
such a test runner::

    if __name__ == '__main__':
        import doctest
        flags = doctest.REPORT_NDIFF|doctest.REPORT_ONLY_FIRST_FAILURE
        if len(sys.argv) > 1:
            name = sys.argv[1]
            if name in globals():
                obj = globals()[name]
            else:
                obj = __test__[name]
            doctest.run_docstring_examples(obj, globals(), name=name,
                                           optionflags=flags)
        else:
            fail, total = doctest.testmod(optionflags=flags)
            print("{} failures out of {} tests".format(fail, total))


.. rubric:: Footnotes

.. [#] Examples containing both expected output and an exception are not supported.
   Trying to guess where one ends and the other begins is too error-prone, and that
   also makes for a confusing test.
PK	%�\�S�2��-html/_sources/library/docxmlrpcserver.rst.txtnu�[���:mod:`DocXMLRPCServer` --- Self-documenting XML-RPC server
==========================================================

.. module:: DocXMLRPCServer
   :synopsis: Self-documenting XML-RPC server implementation.
.. moduleauthor:: Brian Quinlan <brianq@activestate.com>
.. sectionauthor:: Brian Quinlan <brianq@activestate.com>

.. note::
   The :mod:`DocXMLRPCServer` module has been merged into :mod:`xmlrpc.server`
   in Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.


.. versionadded:: 2.3

The :mod:`DocXMLRPCServer` module extends the classes found in
:mod:`SimpleXMLRPCServer` to serve HTML documentation in response to HTTP GET
requests. Servers can either be free standing, using :class:`~DocXMLRPCServer.DocXMLRPCServer`,
or embedded in a CGI environment, using :class:`DocCGIXMLRPCRequestHandler`.


.. class:: DocXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[,  encoding[, bind_and_activate]]]]])

   Create a new server instance. All parameters have the same meaning as for
   :class:`SimpleXMLRPCServer.SimpleXMLRPCServer`; *requestHandler* defaults to
   :class:`DocXMLRPCRequestHandler`.


.. class:: DocCGIXMLRPCRequestHandler()

   Create a new instance to handle XML-RPC requests in a CGI environment.


.. class:: DocXMLRPCRequestHandler()

   Create a new request handler instance. This request handler supports XML-RPC
   POST requests, documentation GET requests, and modifies logging so that the
   *logRequests* parameter to the :class:`~DocXMLRPCServer.DocXMLRPCServer` constructor parameter is
   honored.


.. _doc-xmlrpc-servers:

DocXMLRPCServer Objects
-----------------------

The :class:`~DocXMLRPCServer.DocXMLRPCServer` class is derived from
:class:`SimpleXMLRPCServer.SimpleXMLRPCServer` and provides a means of creating
self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as
XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style
HTML documentation. This allows a server to provide its own web-based
documentation.


.. method:: DocXMLRPCServer.set_server_title(server_title)

   Set the title used in the generated HTML documentation. This title will be used
   inside the HTML "title" element.


.. method:: DocXMLRPCServer.set_server_name(server_name)

   Set the name used in the generated HTML documentation. This name will appear at
   the top of the generated documentation inside a "h1" element.


.. method:: DocXMLRPCServer.set_server_documentation(server_documentation)

   Set the description used in the generated HTML documentation. This description
   will appear as a paragraph, below the server name, in the documentation.


DocCGIXMLRPCRequestHandler
--------------------------

The :class:`DocCGIXMLRPCRequestHandler` class is derived from
:class:`SimpleXMLRPCServer.CGIXMLRPCRequestHandler` and provides a means of
creating self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled
as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style
HTML documentation. This allows a server to provide its own web-based
documentation.


.. method:: DocCGIXMLRPCRequestHandler.set_server_title(server_title)

   Set the title used in the generated HTML documentation. This title will be used
   inside the HTML "title" element.


.. method:: DocCGIXMLRPCRequestHandler.set_server_name(server_name)

   Set the name used in the generated HTML documentation. This name will appear at
   the top of the generated documentation inside a "h1" element.


.. method:: DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)

   Set the description used in the generated HTML documentation. This description
   will appear as a paragraph, below the server name, in the documentation.

PK	%�\8���%html/_sources/library/dumbdbm.rst.txtnu�[���:mod:`dumbdbm` --- Portable DBM implementation
==============================================

.. module:: dumbdbm
   :synopsis: Portable implementation of the simple DBM interface.

.. note::
   The :mod:`dumbdbm` module has been renamed to :mod:`dbm.dumb` in Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

.. index:: single: databases

.. note::

   The :mod:`dumbdbm` module is intended as a last resort fallback for the
   :mod:`anydbm` module when no more robust module is available. The :mod:`dumbdbm`
   module is not written for speed and is not nearly as heavily used as the other
   database modules.

The :mod:`dumbdbm` module provides a persistent dictionary-like interface which
is written entirely in Python.  Unlike other modules such as :mod:`gdbm` and
:mod:`bsddb`, no external library is required.  As with other persistent
mappings, the keys and values must always be strings.

The module defines the following:


.. exception:: error

   Raised on dumbdbm-specific errors, such as I/O errors.  :exc:`KeyError` is
   raised for general mapping errors like specifying an incorrect key.


.. function:: open(filename[, flag[, mode]])

   Open a dumbdbm database and return a dumbdbm object.  The *filename* argument is
   the basename of the database file (without any specific extensions).  When a
   dumbdbm database is created, files with :file:`.dat` and :file:`.dir` extensions
   are created.

   The optional *flag* argument is currently ignored; the database is always opened
   for update, and will be created if it does not exist.

   The optional *mode* argument is the Unix mode of the file, used only when the
   database has to be created.  It defaults to octal ``0666`` (and will be modified
   by the prevailing umask).

   .. versionchanged:: 2.2
      The *mode* argument was ignored in earlier versions.

In addition to the dictionary-like methods, ``dumbdm`` objects
provide the following method:


.. function:: close()

   Close the ``dumbdm`` database.


.. seealso::

   Module :mod:`anydbm`
      Generic interface to ``dbm``\ -style databases.

   Module :mod:`dbm`
      Similar interface to the DBM/NDBM library.

   Module :mod:`gdbm`
      Similar interface to the GNU GDBM library.

   Module :mod:`shelve`
      Persistence module which stores non-string data.

   Module :mod:`whichdb`
      Utility module used to determine the type of an existing database.


.. _dumbdbm-objects:

Dumbdbm Objects
---------------

In addition to the methods provided by the :class:`UserDict.DictMixin` class,
:class:`~dumbdbm.dumbdbm` objects provide the following methods.


.. method:: dumbdbm.sync()

   Synchronize the on-disk directory and data files.  This method is called by the
   :meth:`sync` method of :class:`Shelve` objects.

PK	%�\�V)v""*html/_sources/library/dummy_thread.rst.txtnu�[���:mod:`dummy_thread` --- Drop-in replacement for the :mod:`thread` module
========================================================================

.. module:: dummy_thread
   :synopsis: Drop-in replacement for the thread module.

.. note::
   The :mod:`dummy_thread` module has been renamed to :mod:`_dummy_thread` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3; however, you should consider using the
   high-lever :mod:`dummy_threading` module instead.

**Source code:** :source:`Lib/dummy_thread.py`

--------------

This module provides a duplicate interface to the :mod:`thread` module.  It is
meant to be imported when the :mod:`thread` module is not provided on a
platform.

Suggested usage is::

   try:
       import thread as _thread
   except ImportError:
       import dummy_thread as _thread

Be careful to not use this module where deadlock might occur from a thread
being created that blocks waiting for another thread to be created.  This  often
occurs with blocking I/O.

PK	%�\ίxe-html/_sources/library/dummy_threading.rst.txtnu�[���:mod:`dummy_threading` --- Drop-in replacement for the :mod:`threading` module
==============================================================================

.. module:: dummy_threading
   :synopsis: Drop-in replacement for the threading module.

**Source code:** :source:`Lib/dummy_threading.py`

--------------

This module provides a duplicate interface to the :mod:`threading` module.  It
is meant to be imported when the :mod:`thread` module is not provided on a
platform.

Suggested usage is::

   try:
       import threading as _threading
   except ImportError:
       import dummy_threading as _threading

Be careful to not use this module where deadlock might occur from a thread
being created that blocks waiting for another thread to be created.  This  often
occurs with blocking I/O.

PK	%�\��/�j(j()html/_sources/library/easydialogs.rst.txtnu�[���
:mod:`EasyDialogs` --- Basic Macintosh dialogs
==============================================

.. module:: EasyDialogs
   :platform: Mac
   :synopsis: Basic Macintosh dialogs.
   :deprecated:


The :mod:`EasyDialogs` module contains some simple dialogs for the Macintosh.
The dialogs get launched in a separate application which appears in the dock and
must be clicked on for the dialogs be displayed.  All routines take an optional
resource ID parameter *id* with which one can override the :const:`DLOG`
resource used for the dialog, provided that the dialog items correspond (both
type and item number) to those in the default :const:`DLOG` resource. See source
code for details.

.. note::

   This module has been removed in Python 3.x.


The :mod:`EasyDialogs` module defines the following functions:


.. function:: Message(str[, id[, ok]])

   Displays a modal dialog with the message text *str*, which should be at most 255
   characters long. The button text defaults to "OK", but is set to the string
   argument *ok* if the latter is supplied. Control is returned when the user
   clicks the "OK" button.


.. function:: AskString(prompt[, default[, id[, ok[, cancel]]]])

   Asks the user to input a string value via a modal dialog. *prompt* is the prompt
   message, and the optional *default* supplies the initial value for the string
   (otherwise ``""`` is used). The text of the "OK" and "Cancel" buttons can be
   changed with the *ok* and *cancel* arguments. All strings can be at most 255
   bytes long. :func:`AskString` returns the string entered or :const:`None` in
   case the user cancelled.


.. function:: AskPassword(prompt[, default[, id[, ok[, cancel]]]])

   Asks the user to input a string value via a modal dialog. Like
   :func:`AskString`, but with the text shown as bullets. The arguments have the
   same meaning as for :func:`AskString`.


.. function:: AskYesNoCancel(question[, default[, yes[, no[, cancel[, id]]]]])

   Presents a dialog with prompt *question* and three buttons labelled "Yes", "No",
   and "Cancel". Returns ``1`` for "Yes", ``0`` for "No" and ``-1`` for "Cancel".
   The value of *default* (or ``0`` if *default* is not supplied) is returned when
   the :kbd:`RETURN` key is pressed. The text of the buttons can be changed with
   the *yes*, *no*, and *cancel* arguments; to prevent a button from appearing,
   supply ``""`` for the corresponding argument.


.. function:: ProgressBar([title[, maxval[, label[, id]]]])

   Displays a modeless progress-bar dialog. This is the constructor for the
   :class:`ProgressBar` class described below. *title* is the text string displayed
   (default "Working..."), *maxval* is the value at which progress is complete
   (default ``0``, indicating that an indeterminate amount of work remains to be
   done), and *label* is the text that is displayed above the progress bar itself.


.. function:: GetArgv([optionlist[ commandlist[, addoldfile[, addnewfile[, addfolder[, id]]]]]])

   Displays a dialog which aids the user in constructing a command-line argument
   list.  Returns the list in ``sys.argv`` format, suitable for passing as an
   argument to :func:`getopt.getopt`.  *addoldfile*, *addnewfile*, and *addfolder*
   are boolean arguments.  When nonzero, they enable the user to insert into the
   command line paths to an existing file, a (possibly) not-yet-existent file, and
   a folder, respectively.  (Note: Option arguments must appear in the command line
   before file and folder arguments in order to be recognized by
   :func:`getopt.getopt`.)  Arguments containing spaces can be specified by
   enclosing them within single or double quotes.  A :exc:`SystemExit` exception is
   raised if the user presses the "Cancel" button.

   *optionlist* is a list that determines a popup menu from which the allowed
   options are selected.  Its items can take one of two forms: *optstr* or
   ``(optstr, descr)``.  When present, *descr* is a short descriptive string that
   is displayed in the dialog while this option is selected in the popup menu.  The
   correspondence between *optstr*\s and command-line arguments is:

   +----------------------+------------------------------------------+
   | *optstr* format      | Command-line format                      |
   +======================+==========================================+
   | ``x``                | :option:`!-x` (short option)             |
   +----------------------+------------------------------------------+
   | ``x:`` or ``x=``     | :option:`!-x` (short option with value)  |
   +----------------------+------------------------------------------+
   | ``xyz``              | :option:`!--xyz` (long option)           |
   +----------------------+------------------------------------------+
   | ``xyz:`` or ``xyz=`` | :option:`!--xyz` (long option with value)|
   +----------------------+------------------------------------------+

   *commandlist* is a list of items of the form *cmdstr* or ``(cmdstr, descr)``,
   where *descr* is as above.  The *cmdstr*\ s will appear in a popup menu.  When
   chosen, the text of *cmdstr* will be appended to the command line as is, except
   that a trailing ``':'`` or ``'='`` (if present) will be trimmed off.

   .. versionadded:: 2.0


.. function:: AskFileForOpen( [message] [, typeList] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, eventProc] [, previewProc] [, filterProc] [, wanted] )

   Post a dialog asking the user for a file to open, and return the file selected
   or :const:`None` if the user cancelled. *message* is a text message to display,
   *typeList* is a list of 4-char filetypes allowable, *defaultLocation* is the
   pathname, :class:`FSSpec` or :class:`FSRef` of the folder to show initially,
   *location* is the ``(x, y)`` position on the screen where the dialog is shown,
   *actionButtonLabel* is a string to show instead of "Open" in the OK button,
   *cancelButtonLabel* is a string to show instead of "Cancel" in the cancel
   button, *wanted* is the type of value wanted as a return: :class:`str`,
   :class:`unicode`, :class:`FSSpec`, :class:`FSRef` and subtypes thereof are
   acceptable.

   .. index:: single: Navigation Services

   For a description of the other arguments please see the Apple Navigation
   Services documentation and the :mod:`EasyDialogs` source code.


.. function:: AskFileForSave( [message] [, savedFileName] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, fileType] [, fileCreator] [, eventProc] [, wanted] )

   Post a dialog asking the user for a file to save to, and return the file
   selected or :const:`None` if the user cancelled. *savedFileName* is the default
   for the file name to save to (the return value). See :func:`AskFileForOpen` for
   a description of the other arguments.


.. function:: AskFolder( [message] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, eventProc] [, filterProc] [, wanted] )

   Post a dialog asking the user to select a folder, and return the folder selected
   or :const:`None` if the user cancelled. See :func:`AskFileForOpen` for a
   description of the arguments.


.. seealso::

   `Navigation Services Reference <http://developer.apple.com/legacy/mac/library/#documentation/Carbon/Conceptual/NavServicesIntro/ns_intro_carb/ns_into_carb.html>`_
      Programmer's reference documentation for the Navigation Services, a part of the
      Carbon framework.


.. _progressbar-objects:

ProgressBar Objects
-------------------

:class:`ProgressBar` objects provide support for modeless progress-bar dialogs.
Both determinate (thermometer style) and indeterminate (barber-pole style)
progress bars are supported.  The bar will be determinate if its maximum value
is greater than zero; otherwise it will be indeterminate.

.. versionchanged:: 2.2
   Support for indeterminate-style progress bars was added.

The dialog is displayed immediately after creation. If the dialog's "Cancel"
button is pressed, or if :kbd:`Cmd-.` or :kbd:`ESC` is typed, the dialog window
is hidden and :exc:`KeyboardInterrupt` is raised (but note that this response
does not occur until the progress bar is next updated, typically via a call to
:meth:`inc` or :meth:`set`).  Otherwise, the bar remains visible until the
:class:`ProgressBar` object is discarded.

:class:`ProgressBar` objects possess the following attributes and methods:


.. attribute:: ProgressBar.curval

   The current value (of type integer or long integer) of the progress bar.  The
   normal access methods coerce :attr:`curval` between ``0`` and :attr:`maxval`.
   This attribute should not be altered directly.


.. attribute:: ProgressBar.maxval

   The maximum value (of type integer or long integer) of the progress bar; the
   progress bar (thermometer style) is full when :attr:`curval` equals
   :attr:`maxval`.  If :attr:`maxval` is ``0``, the bar will be indeterminate
   (barber-pole).  This attribute should not be altered directly.


.. method:: ProgressBar.title([newstr])

   Sets the text in the title bar of the progress dialog to *newstr*.


.. method:: ProgressBar.label([newstr])

   Sets the text in the progress box of the progress dialog to *newstr*.


.. method:: ProgressBar.set(value[, max])

   Sets the progress bar's :attr:`curval` to *value*, and also :attr:`maxval` to
   *max* if the latter is provided.  *value* is first coerced between 0 and
   :attr:`maxval`.  The thermometer bar is updated to reflect the changes,
   including a change from indeterminate to determinate or vice versa.


.. method:: ProgressBar.inc([n])

   Increments the progress bar's :attr:`curval` by *n*, or by ``1`` if *n* is not
   provided.  (Note that *n* may be negative, in which case the effect is a
   decrement.)  The progress bar is updated to reflect the change.  If the bar is
   indeterminate, this causes one "spin" of the barber pole.  The resulting
   :attr:`curval` is coerced between 0 and :attr:`maxval` if incrementing causes it
   to fall outside this range.

PK	%�\�t�v��,html/_sources/library/email-examples.rst.txtnu�[���.. _email-examples:

:mod:`email`: Examples
----------------------

Here are a few examples of how to use the :mod:`email` package to read, write,
and send simple email messages, as well as more complex MIME messages.

First, let's see how to create and send a simple text message:

.. literalinclude:: ../includes/email-simple.py


And parsing RFC822 headers can easily be done by the parse(filename) or
parsestr(message_as_string) methods of the Parser() class:

.. literalinclude:: ../includes/email-headers.py


Here's an example of how to send a MIME message containing a bunch of family
pictures that may be residing in a directory:

.. literalinclude:: ../includes/email-mime.py


Here's an example of how to send the entire contents of a directory as an email
message: [1]_

.. literalinclude:: ../includes/email-dir.py


Here's an example of how to unpack a MIME message like the one
above, into a directory of files:

.. literalinclude:: ../includes/email-unpack.py

Here's an example of how to create an HTML message with an alternative plain
text version: [2]_

.. literalinclude:: ../includes/email-alternative.py


.. rubric:: Footnotes

.. [1] Thanks to Matthew Dixon Cowles for the original inspiration and examples.
.. [2] Contributed by Martin Matejek.
PK	%�\�hWg�%�%+html/_sources/library/email.charset.rst.txtnu�[���:mod:`email.charset`: Representing character sets
-------------------------------------------------

.. module:: email.charset
   :synopsis: Character Sets


This module provides a class :class:`Charset` for representing character sets
and character set conversions in email messages, as well as a character set
registry and several convenience methods for manipulating this registry.
Instances of :class:`Charset` are used in several other modules within the
:mod:`email` package.

Import this class from the :mod:`email.charset` module.

.. versionadded:: 2.2.2


.. class:: Charset([input_charset])

   Map character sets to their email properties.

   This class provides information about the requirements imposed on email for a
   specific character set.  It also provides convenience routines for converting
   between character sets, given the availability of the applicable codecs.  Given
   a character set, it will do its best to provide information on how to use that
   character set in an email message in an RFC-compliant way.

   Certain character sets must be encoded with quoted-printable or base64 when used
   in email headers or bodies.  Certain character sets must be converted outright,
   and are not allowed in email.

   Optional *input_charset* is as described below; it is always coerced to lower
   case.  After being alias normalized it is also used as a lookup into the
   registry of character sets to find out the header encoding, body encoding, and
   output conversion codec to be used for the character set.  For example, if
   *input_charset* is ``iso-8859-1``, then headers and bodies will be encoded using
   quoted-printable and no output conversion codec is necessary.  If
   *input_charset* is ``euc-jp``, then headers will be encoded with base64, bodies
   will not be encoded, but output text will be converted from the ``euc-jp``
   character set to the ``iso-2022-jp`` character set.

   :class:`Charset` instances have the following data attributes:


   .. attribute:: input_charset

      The initial character set specified.  Common aliases are converted to
      their *official* email names (e.g. ``latin_1`` is converted to
      ``iso-8859-1``).  Defaults to 7-bit ``us-ascii``.


   .. attribute:: header_encoding

      If the character set must be encoded before it can be used in an email
      header, this attribute will be set to ``Charset.QP`` (for
      quoted-printable), ``Charset.BASE64`` (for base64 encoding), or
      ``Charset.SHORTEST`` for the shortest of QP or BASE64 encoding. Otherwise,
      it will be ``None``.


   .. attribute:: body_encoding

      Same as *header_encoding*, but describes the encoding for the mail
      message's body, which indeed may be different than the header encoding.
      ``Charset.SHORTEST`` is not allowed for *body_encoding*.


   .. attribute:: output_charset

      Some character sets must be converted before they can be used in email headers
      or bodies.  If the *input_charset* is one of them, this attribute will
      contain the name of the character set output will be converted to.  Otherwise, it will
      be ``None``.


   .. attribute:: input_codec

      The name of the Python codec used to convert the *input_charset* to
      Unicode.  If no conversion codec is necessary, this attribute will be
      ``None``.


   .. attribute:: output_codec

      The name of the Python codec used to convert Unicode to the
      *output_charset*.  If no conversion codec is necessary, this attribute
      will have the same value as the *input_codec*.

   :class:`Charset` instances also have the following methods:


   .. method:: get_body_encoding()

      Return the content transfer encoding used for body encoding.

      This is either the string ``quoted-printable`` or ``base64`` depending on
      the encoding used, or it is a function, in which case you should call the
      function with a single argument, the Message object being encoded.  The
      function should then set the :mailheader:`Content-Transfer-Encoding`
      header itself to whatever is appropriate.

      Returns the string ``quoted-printable`` if *body_encoding* is ``QP``,
      returns the string ``base64`` if *body_encoding* is ``BASE64``, and
      returns the string ``7bit`` otherwise.


   .. method:: convert(s)

      Convert the string *s* from the *input_codec* to the *output_codec*.


   .. method:: to_splittable(s)

      Convert a possibly multibyte string to a safely splittable format. *s* is
      the string to split.

      Uses the *input_codec* to try and convert the string to Unicode, so it can
      be safely split on character boundaries (even for multibyte characters).

      Returns the string as-is if it isn't known how to convert *s* to Unicode
      with the *input_charset*.

      Characters that could not be converted to Unicode will be replaced with
      the Unicode replacement character ``'U+FFFD'``.


   .. method:: from_splittable(ustr[, to_output])

      Convert a splittable string back into an encoded string.  *ustr* is a
      Unicode string to "unsplit".

      This method uses the proper codec to try and convert the string from
      Unicode back into an encoded format.  Return the string as-is if it is not
      Unicode, or if it could not be converted from Unicode.

      Characters that could not be converted from Unicode will be replaced with
      an appropriate character (usually ``'?'``).

      If *to_output* is ``True`` (the default), uses *output_codec* to convert
      to an encoded format.  If *to_output* is ``False``, it uses *input_codec*.


   .. method:: get_output_charset()

      Return the output character set.

      This is the *output_charset* attribute if that is not ``None``, otherwise
      it is *input_charset*.


   .. method:: encoded_header_len()

      Return the length of the encoded header string, properly calculating for
      quoted-printable or base64 encoding.


   .. method:: header_encode(s[, convert])

      Header-encode the string *s*.

      If *convert* is ``True``, the string will be converted from the input
      charset to the output charset automatically.  This is not useful for
      multibyte character sets, which have line length issues (multibyte
      characters must be split on a character, not a byte boundary); use the
      higher-level :class:`~email.header.Header` class to deal with these issues
      (see :mod:`email.header`).  *convert* defaults to ``False``.

      The type of encoding (base64 or quoted-printable) will be based on the
      *header_encoding* attribute.


   .. method:: body_encode(s[, convert])

      Body-encode the string *s*.

      If *convert* is ``True`` (the default), the string will be converted from
      the input charset to output charset automatically. Unlike
      :meth:`header_encode`, there are no issues with byte boundaries and
      multibyte charsets in email bodies, so this is usually pretty safe.

      The type of encoding (base64 or quoted-printable) will be based on the
      *body_encoding* attribute.

   The :class:`Charset` class also provides a number of methods to support
   standard operations and built-in functions.


   .. method:: __str__()

      Returns *input_charset* as a string coerced to lower
      case. :meth:`__repr__` is an alias for :meth:`__str__`.


   .. method:: __eq__(other)

      This method allows you to compare two :class:`Charset` instances for
      equality.


   .. method:: __ne__(other)

      This method allows you to compare two :class:`Charset` instances for
      inequality.

The :mod:`email.charset` module also provides the following functions for adding
new entries to the global character set, alias, and codec registries:


.. function:: add_charset(charset[, header_enc[, body_enc[, output_charset]]])

   Add character properties to the global registry.

   *charset* is the input character set, and must be the canonical name of a
   character set.

   Optional *header_enc* and *body_enc* is either ``Charset.QP`` for
   quoted-printable, ``Charset.BASE64`` for base64 encoding,
   ``Charset.SHORTEST`` for the shortest of quoted-printable or base64 encoding,
   or ``None`` for no encoding.  ``SHORTEST`` is only valid for
   *header_enc*. The default is ``None`` for no encoding.

   Optional *output_charset* is the character set that the output should be in.
   Conversions will proceed from input charset, to Unicode, to the output charset
   when the method :meth:`Charset.convert` is called.  The default is to output in
   the same character set as the input.

   Both *input_charset* and *output_charset* must have Unicode codec entries in the
   module's character set-to-codec mapping; use :func:`add_codec` to add codecs the
   module does not know about.  See the :mod:`codecs` module's documentation for
   more information.

   The global character set registry is kept in the module global dictionary
   ``CHARSETS``.


.. function:: add_alias(alias, canonical)

   Add a character set alias.  *alias* is the alias name, e.g. ``latin-1``.
   *canonical* is the character set's canonical name, e.g. ``iso-8859-1``.

   The global charset alias registry is kept in the module global dictionary
   ``ALIASES``.


.. function:: add_codec(charset, codecname)

   Add a codec that map characters in the given character set to and from Unicode.

   *charset* is the canonical name of a character set. *codecname* is the name of a
   Python codec, as appropriate for the second argument to the :func:`unicode`
   built-in, or to the :meth:`~unicode.encode` method of a Unicode string.

PK	%�\��7+H	H	,html/_sources/library/email.encoders.rst.txtnu�[���:mod:`email.encoders`: Encoders
-------------------------------

.. module:: email.encoders
   :synopsis: Encoders for email message payloads.


When creating :class:`~email.message.Message` objects from scratch, you often
need to encode the payloads for transport through compliant mail servers. This
is especially true for :mimetype:`image/\*` and :mimetype:`text/\*` type messages
containing binary data.

The :mod:`email` package provides some convenient encodings in its
:mod:`encoders` module.  These encoders are actually used by the
:class:`~email.mime.audio.MIMEAudio` and :class:`~email.mime.image.MIMEImage`
class constructors to provide default encodings.  All encoder functions take
exactly one argument, the message object to encode.  They usually extract the
payload, encode it, and reset the payload to this newly encoded value.  They
should also set the :mailheader:`Content-Transfer-Encoding` header as appropriate.

Note that these functions are not meaningful for a multipart message.  They
must be applied to individual subparts instead, and will raise a
:exc:`TypeError` if passed a message whose type is multipart.

Here are the encoding functions provided:


.. function:: encode_quopri(msg)

   Encodes the payload into quoted-printable form and sets the
   :mailheader:`Content-Transfer-Encoding` header to ``quoted-printable`` [#]_.
   This is a good encoding to use when most of your payload is normal printable
   data, but contains a few unprintable characters.


.. function:: encode_base64(msg)

   Encodes the payload into base64 form and sets the
   :mailheader:`Content-Transfer-Encoding` header to ``base64``.  This is a good
   encoding to use when most of your payload is unprintable data since it is a more
   compact form than quoted-printable.  The drawback of base64 encoding is that it
   renders the text non-human readable.


.. function:: encode_7or8bit(msg)

   This doesn't actually modify the message's payload, but it does set the
   :mailheader:`Content-Transfer-Encoding` header to either ``7bit`` or ``8bit`` as
   appropriate, based on the payload data.


.. function:: encode_noop(msg)

   This does nothing; it doesn't even set the
   :mailheader:`Content-Transfer-Encoding` header.

.. rubric:: Footnotes

.. [#] Note that encoding with :meth:`encode_quopri` also encodes all tabs and space
   characters in the data.

PK	%�\�L؈��*html/_sources/library/email.errors.rst.txtnu�[���:mod:`email.errors`: Exception and Defect classes
-------------------------------------------------

.. module:: email.errors
   :synopsis: The exception classes used by the email package.


The following exception classes are defined in the :mod:`email.errors` module:


.. exception:: MessageError()

   This is the base class for all exceptions that the :mod:`email` package can
   raise.  It is derived from the standard :exc:`Exception` class and defines no
   additional methods.


.. exception:: MessageParseError()

   This is the base class for exceptions raised by the :class:`~email.parser.Parser`
   class.  It is derived from :exc:`MessageError`.


.. exception:: HeaderParseError()

   Raised under some error conditions when parsing the :rfc:`2822` headers of a
   message, this class is derived from :exc:`MessageParseError`. It can be raised
   from the :meth:`Parser.parse <email.parser.Parser.parse>` or
   :meth:`Parser.parsestr <email.parser.Parser.parsestr>` methods.

   Situations where it can be raised include finding an envelope header after the
   first :rfc:`2822` header of the message, finding a continuation line before the
   first :rfc:`2822` header is found, or finding a line in the headers which is
   neither a header or a continuation line.


.. exception:: BoundaryError()

   Raised under some error conditions when parsing the :rfc:`2822` headers of a
   message, this class is derived from :exc:`MessageParseError`. It can be raised
   from the :meth:`Parser.parse <email.parser.Parser.parse>` or
   :meth:`Parser.parsestr <email.parser.Parser.parsestr>` methods.

   Situations where it can be raised include not being able to find the starting or
   terminating boundary in a :mimetype:`multipart/\*` message when strict parsing
   is used.


.. exception:: MultipartConversionError()

   Raised when a payload is added to a :class:`~email.message.Message` object
   using :meth:`add_payload`, but the payload is already a scalar and the
   message's :mailheader:`Content-Type` main type is not either
   :mimetype:`multipart` or missing.  :exc:`MultipartConversionError` multiply
   inherits from :exc:`MessageError` and the built-in :exc:`TypeError`.

   Since :meth:`Message.add_payload` is deprecated, this exception is rarely
   raised in practice.  However the exception may also be raised if the
   :meth:`~email.message.Message.attach`
   method is called on an instance of a class derived from
   :class:`~email.mime.nonmultipart.MIMENonMultipart` (e.g.
   :class:`~email.mime.image.MIMEImage`).

Here's the list of the defects that the :class:`~email.parser.FeedParser`
can find while parsing messages.  Note that the defects are added to the message
where the problem was found, so for example, if a message nested inside a
:mimetype:`multipart/alternative` had a malformed header, that nested message
object would have a defect, but the containing messages would not.

All defect classes are subclassed from :class:`email.errors.MessageDefect`, but
this class is *not* an exception!

.. versionadded:: 2.4
   All the defect classes were added.

* :class:`NoBoundaryInMultipartDefect` -- A message claimed to be a multipart,
  but had no :mimetype:`boundary` parameter.

* :class:`StartBoundaryNotFoundDefect` -- The start boundary claimed in the
  :mailheader:`Content-Type` header was never found.

* :class:`FirstHeaderLineIsContinuationDefect` -- The message had a continuation
  line as its first header line.

* :class:`MisplacedEnvelopeHeaderDefect` - A "Unix From" header was found in the
  middle of a header block.

* :class:`MalformedHeaderDefect` -- A header was found that was missing a colon,
  or was otherwise malformed.

* :class:`MultipartInvariantViolationDefect` -- A message claimed to be a
  :mimetype:`multipart`, but no subparts were found.  Note that when a message
  has this defect, its :meth:`~email.message.Message.is_multipart` method may
  return false even though its content type claims to be :mimetype:`multipart`.

PK	%�\4�]���-html/_sources/library/email.generator.rst.txtnu�[���:mod:`email.generator`: Generating MIME documents
-------------------------------------------------

.. module:: email.generator
   :synopsis: Generate flat text email messages from a message structure.


One of the most common tasks is to generate the flat text of the email message
represented by a message object structure.  You will need to do this if you want
to send your message via the :mod:`smtplib` module or the :mod:`nntplib` module,
or print the message on the console.  Taking a message object structure and
producing a flat text document is the job of the :class:`Generator` class.

Again, as with the :mod:`email.parser` module, you aren't limited to the
functionality of the bundled generator; you could write one from scratch
yourself.  However the bundled generator knows how to generate most email in a
standards-compliant way, should handle MIME and non-MIME email messages just
fine, and is designed so that the transformation from flat text, to a message
structure via the :class:`~email.parser.Parser` class, and back to flat text,
is idempotent (the input is identical to the output) [#]_.  On the other hand,
using the Generator on a :class:`~email.message.Message` constructed by program
may result in changes to the :class:`~email.message.Message` object as defaults
are filled in.

Here are the public methods of the :class:`Generator` class, imported from the
:mod:`email.generator` module:


.. class:: Generator(outfp[, mangle_from_[, maxheaderlen]])

   The constructor for the :class:`Generator` class takes a file-like object called
   *outfp* for an argument.  *outfp* must support the :meth:`write` method and be
   usable as the output file in a Python extended print statement.

   Optional *mangle_from_* is a flag that, when ``True``, puts a ``>`` character in
   front of any line in the body that starts exactly as ``From``, i.e. ``From``
   followed by a space at the beginning of the line.  This is the only guaranteed
   portable way to avoid having such lines be mistaken for a Unix mailbox format
   envelope header separator (see `WHY THE CONTENT-LENGTH FORMAT IS BAD
   <https://www.jwz.org/doc/content-length.html>`_ for details).  *mangle_from_*
   defaults to ``True``, but you might want to set this to ``False`` if you are not
   writing Unix mailbox format files.

   Optional *maxheaderlen* specifies the longest length for a non-continued header.
   When a header line is longer than *maxheaderlen* (in characters, with tabs
   expanded to 8 spaces), the header will be split as defined in the
   :class:`~email.header.Header` class.  Set to zero to disable header wrapping.
   The default is 78, as recommended (but not required) by :rfc:`2822`.

   The other public :class:`Generator` methods are:


   .. method:: flatten(msg[, unixfrom])

      Print the textual representation of the message object structure rooted at
      *msg* to the output file specified when the :class:`Generator` instance
      was created.  Subparts are visited depth-first and the resulting text will
      be properly MIME encoded.

      Optional *unixfrom* is a flag that forces the printing of the envelope
      header delimiter before the first :rfc:`2822` header of the root message
      object.  If the root object has no envelope header, a standard one is
      crafted.  By default, this is set to ``False`` to inhibit the printing of
      the envelope delimiter.

      Note that for subparts, no envelope header is ever printed.

      .. versionadded:: 2.2.2


   .. method:: clone(fp)

      Return an independent clone of this :class:`Generator` instance with the
      exact same options.

      .. versionadded:: 2.2.2


   .. method:: write(s)

      Write the string *s* to the underlying file object, i.e. *outfp* passed to
      :class:`Generator`'s constructor.  This provides just enough file-like API
      for :class:`Generator` instances to be used in extended print statements.

As a convenience, see the methods :meth:`Message.as_string` and
``str(aMessage)``, a.k.a. :meth:`Message.__str__`, which simplify the generation
of a formatted string representation of a message object.  For more detail, see
:mod:`email.message`.

The :mod:`email.generator` module also provides a derived class, called
:class:`DecodedGenerator` which is like the :class:`Generator` base class,
except that non-\ :mimetype:`text` parts are substituted with a format string
representing the part.


.. class:: DecodedGenerator(outfp[, mangle_from_[, maxheaderlen[, fmt]]])

   This class, derived from :class:`Generator` walks through all the subparts of a
   message.  If the subpart is of main type :mimetype:`text`, then it prints the
   decoded payload of the subpart. Optional *_mangle_from_* and *maxheaderlen* are
   as with the :class:`Generator` base class.

   If the subpart is not of main type :mimetype:`text`, optional *fmt* is a format
   string that is used instead of the message payload. *fmt* is expanded with the
   following keywords, ``%(keyword)s`` format:

   * ``type`` -- Full MIME type of the non-\ :mimetype:`text` part

   * ``maintype`` -- Main MIME type of the non-\ :mimetype:`text` part

   * ``subtype`` -- Sub-MIME type of the non-\ :mimetype:`text` part

   * ``filename`` -- Filename of the non-\ :mimetype:`text` part

   * ``description`` -- Description associated with the non-\ :mimetype:`text` part

   * ``encoding`` -- Content transfer encoding of the non-\ :mimetype:`text` part

   The default value for *fmt* is ``None``, meaning ::

      [Non-text (%(type)s) part of message omitted, filename %(filename)s]

   .. versionadded:: 2.2.2

.. versionchanged:: 2.5
   The previously deprecated method :meth:`__call__` was removed.


.. rubric:: Footnotes

.. [#] This statement assumes that you use the appropriate setting for the
       ``unixfrom`` argument, and that you set maxheaderlen=0 (which will
       preserve whatever the input line lengths were).  It is also not strictly
       true, since in many cases runs of whitespace in headers are collapsed
       into single blanks.  The latter is a bug that will eventually be fixed.
PK	%�\��~kk*html/_sources/library/email.header.rst.txtnu�[���:mod:`email.header`: Internationalized headers
----------------------------------------------

.. module:: email.header
   :synopsis: Representing non-ASCII headers


:rfc:`2822` is the base standard that describes the format of email messages.
It derives from the older :rfc:`822` standard which came into widespread use at
a time when most email was composed of ASCII characters only.  :rfc:`2822` is a
specification written assuming email contains only 7-bit ASCII characters.

Of course, as email has been deployed worldwide, it has become
internationalized, such that language specific character sets can now be used in
email messages.  The base standard still requires email messages to be
transferred using only 7-bit ASCII characters, so a slew of RFCs have been
written describing how to encode email containing non-ASCII characters into
:rfc:`2822`\ -compliant format. These RFCs include :rfc:`2045`, :rfc:`2046`,
:rfc:`2047`, and :rfc:`2231`. The :mod:`email` package supports these standards
in its :mod:`email.header` and :mod:`email.charset` modules.

If you want to include non-ASCII characters in your email headers, say in the
:mailheader:`Subject` or :mailheader:`To` fields, you should use the
:class:`Header` class and assign the field in the :class:`~email.message.Message`
object to an instance of :class:`Header` instead of using a string for the header
value.  Import the :class:`Header` class from the :mod:`email.header` module.
For example::

   >>> from email.message import Message
   >>> from email.header import Header
   >>> msg = Message()
   >>> h = Header('p\xf6stal', 'iso-8859-1')
   >>> msg['Subject'] = h
   >>> print msg.as_string()
   Subject: =?iso-8859-1?q?p=F6stal?=



Notice here how we wanted the :mailheader:`Subject` field to contain a non-ASCII
character?  We did this by creating a :class:`Header` instance and passing in
the character set that the byte string was encoded in.  When the subsequent
:class:`~email.message.Message` instance was flattened, the :mailheader:`Subject`
field was properly :rfc:`2047` encoded.  MIME-aware mail readers would show this
header using the embedded ISO-8859-1 character.

.. versionadded:: 2.2.2

Here is the :class:`Header` class description:


.. class:: Header([s[, charset[, maxlinelen[, header_name[, continuation_ws[, errors]]]]]])

   Create a MIME-compliant header that can contain strings in different character
   sets.

   Optional *s* is the initial header value.  If ``None`` (the default), the
   initial header value is not set.  You can later append to the header with
   :meth:`append` method calls.  *s* may be a byte string or a Unicode string, but
   see the :meth:`append` documentation for semantics.

   Optional *charset* serves two purposes: it has the same meaning as the *charset*
   argument to the :meth:`append` method.  It also sets the default character set
   for all subsequent :meth:`append` calls that omit the *charset* argument.  If
   *charset* is not provided in the constructor (the default), the ``us-ascii``
   character set is used both as *s*'s initial charset and as the default for
   subsequent :meth:`append` calls.

   The maximum line length can be specified explicitly via *maxlinelen*.  For
   splitting the first line to a shorter value (to account for the field header
   which isn't included in *s*, e.g. :mailheader:`Subject`) pass in the name of the
   field in *header_name*.  The default *maxlinelen* is 76, and the default value
   for *header_name* is ``None``, meaning it is not taken into account for the
   first line of a long, split header.

   Optional *continuation_ws* must be :rfc:`2822`\ -compliant folding whitespace,
   and is usually either a space or a hard tab character. This character will be
   prepended to continuation lines.  *continuation_ws* defaults to a single
   space character (" ").

   Optional *errors* is passed straight through to the :meth:`append` method.


   .. method:: append(s[, charset[, errors]])

      Append the string *s* to the MIME header.

      Optional *charset*, if given, should be a :class:`~email.charset.Charset`
      instance (see :mod:`email.charset`) or the name of a character set, which
      will be converted to a :class:`~email.charset.Charset` instance.  A value
      of ``None`` (the default) means that the *charset* given in the constructor
      is used.

      *s* may be a byte string or a Unicode string.  If it is a byte string
      (i.e.  ``isinstance(s, str)`` is true), then *charset* is the encoding of
      that byte string, and a :exc:`UnicodeError` will be raised if the string
      cannot be decoded with that character set.

      If *s* is a Unicode string, then *charset* is a hint specifying the
      character set of the characters in the string.  In this case, when
      producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the
      Unicode string will be encoded using the following charsets in order:
      ``us-ascii``, the *charset* hint, ``utf-8``.  The first character set to
      not provoke a :exc:`UnicodeError` is used.

      Optional *errors* is passed through to any :func:`unicode` or
      :meth:`unicode.encode` call, and defaults to "strict".


   .. method:: encode([splitchars])

      Encode a message header into an RFC-compliant format, possibly wrapping
      long lines and encapsulating non-ASCII parts in base64 or quoted-printable
      encodings.  Optional *splitchars* is a string containing characters to
      split long ASCII lines on, in rough support of :rfc:`2822`'s *highest
      level syntactic breaks*.  This doesn't affect :rfc:`2047` encoded lines.

   The :class:`Header` class also provides a number of methods to support
   standard operators and built-in functions.


   .. method:: __str__()

      A synonym for :meth:`Header.encode`.  Useful for ``str(aHeader)``.


   .. method:: __unicode__()

      A helper for the built-in :func:`unicode` function.  Returns the header as
      a Unicode string.


   .. method:: __eq__(other)

      This method allows you to compare two :class:`Header` instances for
      equality.


   .. method:: __ne__(other)

      This method allows you to compare two :class:`Header` instances for
      inequality.

The :mod:`email.header` module also provides the following convenient functions.


.. function:: decode_header(header)

   Decode a message header value without converting the character set. The header
   value is in *header*.

   This function returns a list of ``(decoded_string, charset)`` pairs containing
   each of the decoded parts of the header.  *charset* is ``None`` for non-encoded
   parts of the header, otherwise a lower case string containing the name of the
   character set specified in the encoded string.

   Here's an example::

      >>> from email.header import decode_header
      >>> decode_header('=?iso-8859-1?q?p=F6stal?=')
      [('p\xf6stal', 'iso-8859-1')]


.. function:: make_header(decoded_seq[, maxlinelen[, header_name[, continuation_ws]]])

   Create a :class:`Header` instance from a sequence of pairs as returned by
   :func:`decode_header`.

   :func:`decode_header` takes a header value string and returns a sequence of
   pairs of the format ``(decoded_string, charset)`` where *charset* is the name of
   the character set.

   This function takes one of those sequence of pairs and returns a :class:`Header`
   instance.  Optional *maxlinelen*, *header_name*, and *continuation_ws* are as in
   the :class:`Header` constructor.

PK	%�\N�`
u	u	-html/_sources/library/email.iterators.rst.txtnu�[���:mod:`email.iterators`: Iterators
---------------------------------

.. module:: email.iterators
   :synopsis: Iterate over a  message object tree.


Iterating over a message object tree is fairly easy with the
:meth:`Message.walk <email.message.Message.walk>` method.  The
:mod:`email.iterators` module provides some useful higher level iterations over
message object trees.


.. function:: body_line_iterator(msg[, decode])

   This iterates over all the payloads in all the subparts of *msg*, returning the
   string payloads line-by-line.  It skips over all the subpart headers, and it
   skips over any subpart with a payload that isn't a Python string.  This is
   somewhat equivalent to reading the flat text representation of the message from
   a file using :meth:`~io.TextIOBase.readline`, skipping over all the
   intervening headers.

   Optional *decode* is passed through to :meth:`Message.get_payload
   <email.message.Message.get_payload>`.


.. function:: typed_subpart_iterator(msg[, maintype[, subtype]])

   This iterates over all the subparts of *msg*, returning only those subparts that
   match the MIME type specified by *maintype* and *subtype*.

   Note that *subtype* is optional; if omitted, then subpart MIME type matching is
   done only with the main type.  *maintype* is optional too; it defaults to
   :mimetype:`text`.

   Thus, by default :func:`typed_subpart_iterator` returns each subpart that has a
   MIME type of :mimetype:`text/\*`.

The following function has been added as a useful debugging tool.  It should
*not* be considered part of the supported public interface for the package.


.. function:: _structure(msg[, fp[, level]])

   Prints an indented representation of the content types of the message object
   structure.  For example::

      >>> msg = email.message_from_file(somefile)
      >>> _structure(msg)
      multipart/mixed
          text/plain
          text/plain
          multipart/digest
              message/rfc822
                  text/plain
              message/rfc822
                  text/plain
              message/rfc822
                  text/plain
              message/rfc822
                  text/plain
              message/rfc822
                  text/plain
          text/plain

   Optional *fp* is a file-like object to print the output to.  It must be suitable
   for Python's extended print statement.  *level* is used internally.

PK	%�\�1�6�b�b+html/_sources/library/email.message.rst.txtnu�[���:mod:`email.message`: Representing an email message
---------------------------------------------------

.. module:: email.message
   :synopsis: The base class representing email messages.


The central class in the :mod:`email` package is the :class:`Message` class,
imported from the :mod:`email.message` module.  It is the base class for the
:mod:`email` object model.  :class:`Message` provides the core functionality for
setting and querying header fields, and for accessing message bodies.

Conceptually, a :class:`Message` object consists of *headers* and *payloads*.
Headers are :rfc:`2822` style field names and values where the field name and
value are separated by a colon.  The colon is not part of either the field name
or the field value.

Headers are stored and returned in case-preserving form but are matched
case-insensitively.  There may also be a single envelope header, also known as
the *Unix-From* header or the ``From_`` header.  The payload is either a string
in the case of simple message objects or a list of :class:`Message` objects for
MIME container documents (e.g. :mimetype:`multipart/\*` and
:mimetype:`message/rfc822`).

:class:`Message` objects provide a mapping style interface for accessing the
message headers, and an explicit interface for accessing both the headers and
the payload.  It provides convenience methods for generating a flat text
representation of the message object tree, for accessing commonly used header
parameters, and for recursively walking over the object tree.

Here are the methods of the :class:`Message` class:


.. class:: Message()

   The constructor takes no arguments.


   .. method:: as_string([unixfrom])

      Return the entire message flattened as a string.  When optional *unixfrom*
      is ``True``, the envelope header is included in the returned string.
      *unixfrom* defaults to ``False``.  Flattening the message may trigger
      changes to the :class:`Message` if defaults need to be filled in to
      complete the transformation to a string (for example, MIME boundaries may
      be generated or modified).

      Note that this method is provided as a convenience and may not always
      format the message the way you want.  For example, by default it mangles
      lines that begin with ``From``.  For more flexibility, instantiate a
      :class:`~email.generator.Generator` instance and use its
      :meth:`~email.generator.Generator.flatten` method directly.  For example::

         from cStringIO import StringIO
         from email.generator import Generator
         fp = StringIO()
         g = Generator(fp, mangle_from_=False, maxheaderlen=60)
         g.flatten(msg)
         text = fp.getvalue()


   .. method:: __str__()

      Equivalent to ``as_string(unixfrom=True)``.


   .. method:: is_multipart()

      Return ``True`` if the message's payload is a list of sub-\
      :class:`Message` objects, otherwise return ``False``.  When
      :meth:`is_multipart` returns ``False``, the payload should be a string object.


   .. method:: set_unixfrom(unixfrom)

      Set the message's envelope header to *unixfrom*, which should be a string.


   .. method:: get_unixfrom()

      Return the message's envelope header.  Defaults to ``None`` if the
      envelope header was never set.


   .. method:: attach(payload)

      Add the given *payload* to the current payload, which must be ``None`` or
      a list of :class:`Message` objects before the call. After the call, the
      payload will always be a list of :class:`Message` objects.  If you want to
      set the payload to a scalar object (e.g. a string), use
      :meth:`set_payload` instead.


   .. method:: get_payload([i[, decode]])

      Return the current payload, which will be a list of
      :class:`Message` objects when :meth:`is_multipart` is ``True``, or a
      string when :meth:`is_multipart` is ``False``.  If the payload is a list
      and you mutate the list object, you modify the message's payload in place.

      With optional argument *i*, :meth:`get_payload` will return the *i*-th
      element of the payload, counting from zero, if :meth:`is_multipart` is
      ``True``.  An :exc:`IndexError` will be raised if *i* is less than 0 or
      greater than or equal to the number of items in the payload.  If the
      payload is a string (i.e.  :meth:`is_multipart` is ``False``) and *i* is
      given, a :exc:`TypeError` is raised.

      Optional *decode* is a flag indicating whether the payload should be
      decoded or not, according to the :mailheader:`Content-Transfer-Encoding`
      header. When ``True`` and the message is not a multipart, the payload will
      be decoded if this header's value is ``quoted-printable`` or ``base64``.
      If some other encoding is used, or :mailheader:`Content-Transfer-Encoding`
      header is missing, or if the payload has bogus base64 data, the payload is
      returned as-is (undecoded).  If the message is a multipart and the
      *decode* flag is ``True``, then ``None`` is returned.  The default for
      *decode* is ``False``.


   .. method:: set_payload(payload[, charset])

      Set the entire message object's payload to *payload*.  It is the client's
      responsibility to ensure the payload invariants.  Optional *charset* sets
      the message's default character set; see :meth:`set_charset` for details.

      .. versionchanged:: 2.2.2
         *charset* argument added.


   .. method:: set_charset(charset)

      Set the character set of the payload to *charset*, which can either be a
      :class:`~email.charset.Charset` instance (see :mod:`email.charset`), a
      string naming a character set, or ``None``.  If it is a string, it will
      be converted to a :class:`~email.charset.Charset` instance.  If *charset*
      is ``None``, the ``charset`` parameter will be removed from the
      :mailheader:`Content-Type` header (the message will not be otherwise
      modified).  Anything else will generate a :exc:`TypeError`.

      If there is no existing :mailheader:`MIME-Version` header one will be
      added.  If there is no existing :mailheader:`Content-Type` header, one
      will be added with a value of :mimetype:`text/plain`.  Whether the
      :mailheader:`Content-Type` header already exists or not, its ``charset``
      parameter will be set to *charset.output_charset*.   If
      *charset.input_charset* and *charset.output_charset* differ, the payload
      will be re-encoded to the *output_charset*.  If there is no existing
      :mailheader:`Content-Transfer-Encoding` header, then the payload will be
      transfer-encoded, if needed, using the specified
      :class:`~email.charset.Charset`, and a header with the appropriate value
      will be added.  If a :mailheader:`Content-Transfer-Encoding` header
      already exists, the payload is assumed to already be correctly encoded
      using that :mailheader:`Content-Transfer-Encoding` and is not modified.

      The message will be assumed to be of type :mimetype:`text/\*`, with the
      payload either in unicode or encoded with *charset.input_charset*.
      It will be encoded or converted to *charset.output_charset*
      and transfer encoded properly, if needed, when generating the plain text
      representation of the message.  MIME headers (:mailheader:`MIME-Version`,
      :mailheader:`Content-Type`, :mailheader:`Content-Transfer-Encoding`) will
      be added as needed.

      .. versionadded:: 2.2.2


   .. method:: get_charset()

      Return the :class:`~email.charset.Charset` instance associated with the
      message's payload.

      .. versionadded:: 2.2.2

   The following methods implement a mapping-like interface for accessing the
   message's :rfc:`2822` headers.  Note that there are some semantic differences
   between these methods and a normal mapping (i.e. dictionary) interface.  For
   example, in a dictionary there are no duplicate keys, but here there may be
   duplicate message headers.  Also, in dictionaries there is no guaranteed
   order to the keys returned by :meth:`keys`, but in a :class:`Message` object,
   headers are always returned in the order they appeared in the original
   message, or were added to the message later.  Any header deleted and then
   re-added are always appended to the end of the header list.

   These semantic differences are intentional and are biased toward maximal
   convenience.

   Note that in all cases, any envelope header present in the message is not
   included in the mapping interface.


   .. method:: __len__()

      Return the total number of headers, including duplicates.


   .. method:: __contains__(name)

      Return true if the message object has a field named *name*. Matching is
      done case-insensitively and *name* should not include the trailing colon.
      Used for the ``in`` operator, e.g.::

         if 'message-id' in myMessage:
             print 'Message-ID:', myMessage['message-id']


   .. method:: __getitem__(name)

      Return the value of the named header field.  *name* should not include the
      colon field separator.  If the header is missing, ``None`` is returned; a
      :exc:`KeyError` is never raised.

      Note that if the named field appears more than once in the message's
      headers, exactly which of those field values will be returned is
      undefined.  Use the :meth:`get_all` method to get the values of all the
      extant named headers.


   .. method:: __setitem__(name, val)

      Add a header to the message with field name *name* and value *val*.  The
      field is appended to the end of the message's existing fields.

      Note that this does *not* overwrite or delete any existing header with the same
      name.  If you want to ensure that the new header is the only one present in the
      message with field name *name*, delete the field first, e.g.::

         del msg['subject']
         msg['subject'] = 'Python roolz!'


   .. method:: __delitem__(name)

      Delete all occurrences of the field with name *name* from the message's
      headers.  No exception is raised if the named field isn't present in the headers.


   .. method:: has_key(name)

      Return true if the message contains a header field named *name*, otherwise
      return false.


   .. method:: keys()

      Return a list of all the message's header field names.


   .. method:: values()

      Return a list of all the message's field values.


   .. method:: items()

      Return a list of 2-tuples containing all the message's field headers and
      values.


   .. method:: get(name[, failobj])

      Return the value of the named header field.  This is identical to
      :meth:`__getitem__` except that optional *failobj* is returned if the
      named header is missing (defaults to ``None``).

   Here are some additional useful methods:


   .. method:: get_all(name[, failobj])

      Return a list of all the values for the field named *name*. If there are
      no such named headers in the message, *failobj* is returned (defaults to
      ``None``).


   .. method:: add_header(_name, _value, **_params)

      Extended header setting.  This method is similar to :meth:`__setitem__`
      except that additional header parameters can be provided as keyword
      arguments.  *_name* is the header field to add and *_value* is the
      *primary* value for the header.

      For each item in the keyword argument dictionary *_params*, the key is
      taken as the parameter name, with underscores converted to dashes (since
      dashes are illegal in Python identifiers).  Normally, the parameter will
      be added as ``key="value"`` unless the value is ``None``, in which case
      only the key will be added.  If the value contains non-ASCII characters,
      it must be specified as a three tuple in the format
      ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the
      charset to be used to encode the value, ``LANGUAGE`` can usually be set
      to ``None`` or the empty string (see :RFC:`2231` for other possibilities),
      and ``VALUE`` is the string value containing non-ASCII code points.

      Here's an example::

         msg.add_header('Content-Disposition', 'attachment', filename='bud.gif')

      This will add a header that looks like ::

         Content-Disposition: attachment; filename="bud.gif"

      An example with non-ASCII characters::

         msg.add_header('Content-Disposition', 'attachment',
                        filename=('iso-8859-1', '', 'Fußballer.ppt'))

      Which produces ::

         Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"


   .. method:: replace_header(_name, _value)

      Replace a header.  Replace the first header found in the message that
      matches *_name*, retaining header order and field name case.  If no
      matching header was found, a :exc:`KeyError` is raised.

      .. versionadded:: 2.2.2


   .. method:: get_content_type()

      Return the message's content type.  The returned string is coerced to
      lower case of the form :mimetype:`maintype/subtype`.  If there was no
      :mailheader:`Content-Type` header in the message the default type as given
      by :meth:`get_default_type` will be returned.  Since according to
      :rfc:`2045`, messages always have a default type, :meth:`get_content_type`
      will always return a value.

      :rfc:`2045` defines a message's default type to be :mimetype:`text/plain`
      unless it appears inside a :mimetype:`multipart/digest` container, in
      which case it would be :mimetype:`message/rfc822`.  If the
      :mailheader:`Content-Type` header has an invalid type specification,
      :rfc:`2045` mandates that the default type be :mimetype:`text/plain`.

      .. versionadded:: 2.2.2


   .. method:: get_content_maintype()

      Return the message's main content type.  This is the :mimetype:`maintype`
      part of the string returned by :meth:`get_content_type`.

      .. versionadded:: 2.2.2


   .. method:: get_content_subtype()

      Return the message's sub-content type.  This is the :mimetype:`subtype`
      part of the string returned by :meth:`get_content_type`.

      .. versionadded:: 2.2.2


   .. method:: get_default_type()

      Return the default content type.  Most messages have a default content
      type of :mimetype:`text/plain`, except for messages that are subparts of
      :mimetype:`multipart/digest` containers.  Such subparts have a default
      content type of :mimetype:`message/rfc822`.

      .. versionadded:: 2.2.2


   .. method:: set_default_type(ctype)

      Set the default content type.  *ctype* should either be
      :mimetype:`text/plain` or :mimetype:`message/rfc822`, although this is not
      enforced.  The default content type is not stored in the
      :mailheader:`Content-Type` header.

      .. versionadded:: 2.2.2


   .. method:: get_params([failobj[, header[, unquote]]])

      Return the message's :mailheader:`Content-Type` parameters, as a list.
      The elements of the returned list are 2-tuples of key/value pairs, as
      split on the ``'='`` sign.  The left hand side of the ``'='`` is the key,
      while the right hand side is the value.  If there is no ``'='`` sign in
      the parameter the value is the empty string, otherwise the value is as
      described in :meth:`get_param` and is unquoted if optional *unquote* is
      ``True`` (the default).

      Optional *failobj* is the object to return if there is no
      :mailheader:`Content-Type` header.  Optional *header* is the header to
      search instead of :mailheader:`Content-Type`.

      .. versionchanged:: 2.2.2
         *unquote* argument added.


   .. method:: get_param(param[, failobj[, header[, unquote]]])

      Return the value of the :mailheader:`Content-Type` header's parameter
      *param* as a string.  If the message has no :mailheader:`Content-Type`
      header or if there is no such parameter, then *failobj* is returned
      (defaults to ``None``).

      Optional *header* if given, specifies the message header to use instead of
      :mailheader:`Content-Type`.

      Parameter keys are always compared case insensitively.  The return value
      can either be a string, or a 3-tuple if the parameter was :rfc:`2231`
      encoded.  When it's a 3-tuple, the elements of the value are of the form
      ``(CHARSET, LANGUAGE, VALUE)``.  Note that both ``CHARSET`` and
      ``LANGUAGE`` can be ``None``, in which case you should consider ``VALUE``
      to be encoded in the ``us-ascii`` charset.  You can usually ignore
      ``LANGUAGE``.

      If your application doesn't care whether the parameter was encoded as in
      :rfc:`2231`, you can collapse the parameter value by calling
      :func:`email.utils.collapse_rfc2231_value`, passing in the return value
      from :meth:`get_param`.  This will return a suitably decoded Unicode
      string when the value is a tuple, or the original string unquoted if it
      isn't.  For example::

         rawparam = msg.get_param('foo')
         param = email.utils.collapse_rfc2231_value(rawparam)

      In any case, the parameter value (either the returned string, or the
      ``VALUE`` item in the 3-tuple) is always unquoted, unless *unquote* is set
      to ``False``.

      .. versionchanged:: 2.2.2
         *unquote* argument added, and 3-tuple return value possible.


   .. method:: set_param(param, value[, header[, requote[, charset[, language]]]])

      Set a parameter in the :mailheader:`Content-Type` header.  If the
      parameter already exists in the header, its value will be replaced with
      *value*.  If the :mailheader:`Content-Type` header as not yet been defined
      for this message, it will be set to :mimetype:`text/plain` and the new
      parameter value will be appended as per :rfc:`2045`.

      Optional *header* specifies an alternative header to
      :mailheader:`Content-Type`, and all parameters will be quoted as necessary
      unless optional *requote* is ``False`` (the default is ``True``).

      If optional *charset* is specified, the parameter will be encoded
      according to :rfc:`2231`. Optional *language* specifies the RFC 2231
      language, defaulting to the empty string.  Both *charset* and *language*
      should be strings.

      .. versionadded:: 2.2.2


   .. method:: del_param(param[, header[, requote]])

      Remove the given parameter completely from the :mailheader:`Content-Type`
      header.  The header will be re-written in place without the parameter or
      its value.  All values will be quoted as necessary unless *requote* is
      ``False`` (the default is ``True``).  Optional *header* specifies an
      alternative to :mailheader:`Content-Type`.

      .. versionadded:: 2.2.2


   .. method:: set_type(type[, header][, requote])

      Set the main type and subtype for the :mailheader:`Content-Type`
      header. *type* must be a string in the form :mimetype:`maintype/subtype`,
      otherwise a :exc:`ValueError` is raised.

      This method replaces the :mailheader:`Content-Type` header, keeping all
      the parameters in place.  If *requote* is ``False``, this leaves the
      existing header's quoting as is, otherwise the parameters will be quoted
      (the default).

      An alternative header can be specified in the *header* argument. When the
      :mailheader:`Content-Type` header is set a :mailheader:`MIME-Version`
      header is also added.

      .. versionadded:: 2.2.2


   .. method:: get_filename([failobj])

      Return the value of the ``filename`` parameter of the
      :mailheader:`Content-Disposition` header of the message.  If the header
      does not have a ``filename`` parameter, this method falls back to looking
      for the ``name`` parameter on the :mailheader:`Content-Type` header.  If
      neither is found, or the header is missing, then *failobj* is returned.
      The returned string will always be unquoted as per
      :func:`email.utils.unquote`.


   .. method:: get_boundary([failobj])

      Return the value of the ``boundary`` parameter of the
      :mailheader:`Content-Type` header of the message, or *failobj* if either
      the header is missing, or has no ``boundary`` parameter.  The returned
      string will always be unquoted as per :func:`email.utils.unquote`.


   .. method:: set_boundary(boundary)

      Set the ``boundary`` parameter of the :mailheader:`Content-Type` header to
      *boundary*.  :meth:`set_boundary` will always quote *boundary* if
      necessary.  A :exc:`~email.errors.HeaderParseError` is raised if the
      message object has no :mailheader:`Content-Type` header.

      Note that using this method is subtly different than deleting the old
      :mailheader:`Content-Type` header and adding a new one with the new
      boundary via :meth:`add_header`, because :meth:`set_boundary` preserves
      the order of the :mailheader:`Content-Type` header in the list of
      headers. However, it does *not* preserve any continuation lines which may
      have been present in the original :mailheader:`Content-Type` header.


   .. method:: get_content_charset([failobj])

      Return the ``charset`` parameter of the :mailheader:`Content-Type` header,
      coerced to lower case.  If there is no :mailheader:`Content-Type` header, or if
      that header has no ``charset`` parameter, *failobj* is returned.

      Note that this method differs from :meth:`get_charset` which returns the
      :class:`~email.charset.Charset` instance for the default encoding of the message body.

      .. versionadded:: 2.2.2


   .. method:: get_charsets([failobj])

      Return a list containing the character set names in the message.  If the
      message is a :mimetype:`multipart`, then the list will contain one element
      for each subpart in the payload, otherwise, it will be a list of length 1.

      Each item in the list will be a string which is the value of the
      ``charset`` parameter in the :mailheader:`Content-Type` header for the
      represented subpart.  However, if the subpart has no
      :mailheader:`Content-Type` header, no ``charset`` parameter, or is not of
      the :mimetype:`text` main MIME type, then that item in the returned list
      will be *failobj*.


   .. method:: walk()

      The :meth:`walk` method is an all-purpose generator which can be used to
      iterate over all the parts and subparts of a message object tree, in
      depth-first traversal order.  You will typically use :meth:`walk` as the
      iterator in a ``for`` loop; each iteration returns the next subpart.

      Here's an example that prints the MIME type of every part of a multipart
      message structure::

         >>> for part in msg.walk():
         ...     print part.get_content_type()
         multipart/report
         text/plain
         message/delivery-status
         text/plain
         text/plain
         message/rfc822

   .. versionchanged:: 2.5
      The previously deprecated methods :meth:`get_type`, :meth:`get_main_type`, and
      :meth:`get_subtype` were removed.

   :class:`Message` objects can also optionally contain two instance attributes,
   which can be used when generating the plain text of a MIME message.


   .. attribute:: preamble

      The format of a MIME document allows for some text between the blank line
      following the headers, and the first multipart boundary string. Normally,
      this text is never visible in a MIME-aware mail reader because it falls
      outside the standard MIME armor.  However, when viewing the raw text of
      the message, or when viewing the message in a non-MIME aware reader, this
      text can become visible.

      The *preamble* attribute contains this leading extra-armor text for MIME
      documents.  When the :class:`~email.parser.Parser` discovers some text
      after the headers but before the first boundary string, it assigns this
      text to the message's *preamble* attribute.  When the
      :class:`~email.generator.Generator` is writing out the plain text
      representation of a MIME message, and it finds the
      message has a *preamble* attribute, it will write this text in the area
      between the headers and the first boundary.  See :mod:`email.parser` and
      :mod:`email.generator` for details.

      Note that if the message object has no preamble, the *preamble* attribute
      will be ``None``.


   .. attribute:: epilogue

      The *epilogue* attribute acts the same way as the *preamble* attribute,
      except that it contains text that appears between the last boundary and
      the end of the message.

      .. versionchanged:: 2.5
         You do not need to set the epilogue to the empty string in order for the
         :class:`~email.generator.Generator` to print a newline at the end of the
         file.


   .. attribute:: defects

      The *defects* attribute contains a list of all the problems found when
      parsing this message.  See :mod:`email.errors` for a detailed description
      of the possible parsing defects.

      .. versionadded:: 2.4

PK	%�\Yu/v�&�&(html/_sources/library/email.mime.rst.txtnu�[���:mod:`email.mime`: Creating email and MIME objects from scratch
---------------------------------------------------------------

.. module:: email.mime
   :synopsis: Build MIME messages.


Ordinarily, you get a message object structure by passing a file or some text to
a parser, which parses the text and returns the root message object.  However
you can also build a complete message structure from scratch, or even individual
:class:`~email.message.Message` objects by hand.  In fact, you can also take an
existing structure and add new :class:`~email.message.Message` objects, move them
around, etc.  This makes a very convenient interface for slicing-and-dicing MIME
messages.

You can create a new object structure by creating :class:`~email.message.Message`
instances, adding attachments and all the appropriate headers manually.  For MIME
messages though, the :mod:`email` package provides some convenient subclasses to
make things easier.

Here are the classes:

.. currentmodule:: email.mime.base

.. class:: MIMEBase(_maintype, _subtype, **_params)

   Module: :mod:`email.mime.base`

   This is the base class for all the MIME-specific subclasses of
   :class:`~email.message.Message`.  Ordinarily you won't create instances
   specifically of :class:`MIMEBase`, although you could.  :class:`MIMEBase`
   is provided primarily as a convenient base class for more specific
   MIME-aware subclasses.

   *_maintype* is the :mailheader:`Content-Type` major type (e.g. :mimetype:`text`
   or :mimetype:`image`), and *_subtype* is the :mailheader:`Content-Type` minor
   type  (e.g. :mimetype:`plain` or :mimetype:`gif`).  *_params* is a parameter
   key/value dictionary and is passed directly to :meth:`Message.add_header
   <email.message.Message.add_header>`.

   The :class:`MIMEBase` class always adds a :mailheader:`Content-Type` header
   (based on *_maintype*, *_subtype*, and *_params*), and a
   :mailheader:`MIME-Version` header (always set to ``1.0``).


.. currentmodule:: email.mime.nonmultipart

.. class:: MIMENonMultipart()

   Module: :mod:`email.mime.nonmultipart`

   A subclass of :class:`~email.mime.base.MIMEBase`, this is an intermediate base
   class for MIME messages that are not :mimetype:`multipart`.  The primary
   purpose of this class is to prevent the use of the
   :meth:`~email.message.Message.attach` method, which only makes sense for
   :mimetype:`multipart` messages.  If :meth:`~email.message.Message.attach`
   is called, a :exc:`~email.errors.MultipartConversionError` exception is raised.

   .. versionadded:: 2.2.2


.. currentmodule:: email.mime.multipart

.. class:: MIMEMultipart([_subtype[, boundary[, _subparts[, _params]]]])

   Module: :mod:`email.mime.multipart`

   A subclass of :class:`~email.mime.base.MIMEBase`, this is an intermediate base
   class for MIME messages that are :mimetype:`multipart`.  Optional *_subtype*
   defaults to :mimetype:`mixed`, but can be used to specify the subtype of the
   message.  A :mailheader:`Content-Type` header of :mimetype:`multipart/_subtype`
   will be added to the message object.  A :mailheader:`MIME-Version` header will
   also be added.

   Optional *boundary* is the multipart boundary string.  When ``None`` (the
   default), the boundary is calculated when needed (for example, when the
   message is serialized).

   *_subparts* is a sequence of initial subparts for the payload.  It must be
   possible to convert this sequence to a list.  You can always attach new subparts
   to the message by using the :meth:`Message.attach
   <email.message.Message.attach>` method.

   Additional parameters for the :mailheader:`Content-Type` header are taken from
   the keyword arguments, or passed into the *_params* argument, which is a keyword
   dictionary.

   .. versionadded:: 2.2.2


.. currentmodule:: email.mime.application

.. class:: MIMEApplication(_data[, _subtype[, _encoder[, **_params]]])

   Module: :mod:`email.mime.application`

   A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the
   :class:`MIMEApplication` class is used to represent MIME message objects of
   major type :mimetype:`application`.  *_data* is a string containing the raw
   byte data.  Optional *_subtype* specifies the MIME subtype and defaults to
   :mimetype:`octet-stream`.

   Optional *_encoder* is a callable (i.e. function) which will perform the actual
   encoding of the data for transport.  This callable takes one argument, which is
   the :class:`MIMEApplication` instance. It should use
   :meth:`~email.message.Message.get_payload` and
   :meth:`~email.message.Message.set_payload` to change the payload to encoded
   form.  It should also add
   any :mailheader:`Content-Transfer-Encoding` or other headers to the message
   object as necessary.  The default encoding is base64.  See the
   :mod:`email.encoders` module for a list of the built-in encoders.

   *_params* are passed straight through to the base class constructor.

   .. versionadded:: 2.5


.. currentmodule:: email.mime.audio

.. class:: MIMEAudio(_audiodata[, _subtype[, _encoder[, **_params]]])

   Module: :mod:`email.mime.audio`

   A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the
   :class:`MIMEAudio` class is used to create MIME message objects of major type
   :mimetype:`audio`. *_audiodata* is a string containing the raw audio data.  If
   this data can be decoded by the standard Python module :mod:`sndhdr`, then the
   subtype will be automatically included in the :mailheader:`Content-Type` header.
   Otherwise you can explicitly specify the audio subtype via the *_subtype*
   parameter.  If the minor type could not be guessed and *_subtype* was not given,
   then :exc:`TypeError` is raised.

   Optional *_encoder* is a callable (i.e. function) which will perform the actual
   encoding of the audio data for transport.  This callable takes one argument,
   which is the :class:`MIMEAudio` instance. It should use
   :meth:`~email.message.Message.get_payload` and
   :meth:`~email.message.Message.set_payload` to change the payload to encoded
   form.  It should also add
   any :mailheader:`Content-Transfer-Encoding` or other headers to the message
   object as necessary.  The default encoding is base64.  See the
   :mod:`email.encoders` module for a list of the built-in encoders.

   *_params* are passed straight through to the base class constructor.


.. currentmodule:: email.mime.image

.. class:: MIMEImage(_imagedata[, _subtype[, _encoder[, **_params]]])

   Module: :mod:`email.mime.image`

   A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the
   :class:`MIMEImage` class is used to create MIME message objects of major type
   :mimetype:`image`. *_imagedata* is a string containing the raw image data.  If
   this data can be decoded by the standard Python module :mod:`imghdr`, then the
   subtype will be automatically included in the :mailheader:`Content-Type` header.
   Otherwise you can explicitly specify the image subtype via the *_subtype*
   parameter.  If the minor type could not be guessed and *_subtype* was not given,
   then :exc:`TypeError` is raised.

   Optional *_encoder* is a callable (i.e. function) which will perform the actual
   encoding of the image data for transport.  This callable takes one argument,
   which is the :class:`MIMEImage` instance. It should use
   :meth:`~email.message.Message.get_payload` and
   :meth:`~email.message.Message.set_payload` to change the payload to encoded
   form.  It should also add
   any :mailheader:`Content-Transfer-Encoding` or other headers to the message
   object as necessary.  The default encoding is base64.  See the
   :mod:`email.encoders` module for a list of the built-in encoders.

   *_params* are passed straight through to the :class:`~email.mime.base.MIMEBase`
   constructor.


.. currentmodule:: email.mime.message

.. class:: MIMEMessage(_msg[, _subtype])

   Module: :mod:`email.mime.message`

   A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the
   :class:`MIMEMessage` class is used to create MIME objects of main type
   :mimetype:`message`. *_msg* is used as the payload, and must be an instance
   of class :class:`~email.message.Message` (or a subclass thereof), otherwise
   a :exc:`TypeError` is raised.

   Optional *_subtype* sets the subtype of the message; it defaults to
   :mimetype:`rfc822`.


.. currentmodule:: email.mime.text

.. class:: MIMEText(_text[, _subtype[, _charset]])

   Module: :mod:`email.mime.text`

   A subclass of :class:`~email.mime.nonmultipart.MIMENonMultipart`, the
   :class:`MIMEText` class is used to create MIME objects of major type
   :mimetype:`text`. *_text* is the string for the payload.  *_subtype* is the
   minor type and defaults to :mimetype:`plain`.  *_charset* is the character
   set of the text and is passed as a parameter to the
   :class:`~email.mime.nonmultipart.MIMENonMultipart` constructor; it defaults
   to ``us-ascii``.  If *_text* is unicode, it is encoded using the
   *output_charset* of *_charset*, otherwise it is used as-is.

   .. versionchanged:: 2.4
      The previously deprecated *_encoding* argument has been removed.  Content
      Transfer Encoding now happens implicitly based on the *_charset*
      argument.

   Unless the ``_charset`` parameter is explicitly set to ``None``, the
   MIMEText object created will have both a :mailheader:`Content-Type` header
   with a ``charset`` parameter, and a :mailheader:`Content-Transfer-Encoding`
   header.  This means that a subsequent ``set_payload`` call will not result
   in an encoded payload, even if a charset is passed in the ``set_payload``
   command.  You can "reset" this behavior by deleting the
   ``Content-Transfer-Encoding`` header, after which a ``set_payload`` call
   will automatically encode the new payload (and add a new
   :mailheader:`Content-Transfer-Encoding` header).
PK	%�\���W(W(*html/_sources/library/email.parser.rst.txtnu�[���:mod:`email.parser`: Parsing email messages
-------------------------------------------

.. module:: email.parser
   :synopsis: Parse flat text email messages to produce a message object structure.


Message object structures can be created in one of two ways: they can be created
from whole cloth by instantiating :class:`~email.message.Message` objects and
stringing them together via :meth:`~email.message.Message.attach` and
:meth:`~email.message.Message.set_payload` calls, or they
can be created by parsing a flat text representation of the email message.

The :mod:`email` package provides a standard parser that understands most email
document structures, including MIME documents.  You can pass the parser a string
or a file object, and the parser will return to you the root
:class:`~email.message.Message` instance of the object structure.  For simple,
non-MIME messages the payload of this root object will likely be a string
containing the text of the message.  For MIME messages, the root object will
return ``True`` from its :meth:`~email.message.Message.is_multipart` method, and
the subparts can be accessed via the :meth:`~email.message.Message.get_payload`
and :meth:`~email.message.Message.walk` methods.

There are actually two parser interfaces available for use, the classic
:class:`Parser` API and the incremental :class:`FeedParser` API.  The classic
:class:`Parser` API is fine if you have the entire text of the message in memory
as a string, or if the entire message lives in a file on the file system.
:class:`FeedParser` is more appropriate for when you're reading the message from
a stream which might block waiting for more input (e.g. reading an email message
from a socket).  The :class:`FeedParser` can consume and parse the message
incrementally, and only returns the root object when you close the parser [#]_.

Note that the parser can be extended in limited ways, and of course you can
implement your own parser completely from scratch.  There is no magical
connection between the :mod:`email` package's bundled parser and the
:class:`~email.message.Message` class, so your custom parser can create message
object trees any way it finds necessary.


FeedParser API
^^^^^^^^^^^^^^

.. versionadded:: 2.4

The :class:`FeedParser`, imported from the :mod:`email.feedparser` module,
provides an API that is conducive to incremental parsing of email messages, such
as would be necessary when reading the text of an email message from a source
that can block (e.g. a socket).  The :class:`FeedParser` can of course be used
to parse an email message fully contained in a string or a file, but the classic
:class:`Parser` API may be more convenient for such use cases.  The semantics
and results of the two parser APIs are identical.

The :class:`FeedParser`'s API is simple; you create an instance, feed it a bunch
of text until there's no more to feed it, then close the parser to retrieve the
root message object.  The :class:`FeedParser` is extremely accurate when parsing
standards-compliant messages, and it does a very good job of parsing
non-compliant messages, providing information about how a message was deemed
broken.  It will populate a message object's *defects* attribute with a list of
any problems it found in a message.  See the :mod:`email.errors` module for the
list of defects that it can find.

Here is the API for the :class:`FeedParser`:


.. class:: FeedParser([_factory])

   Create a :class:`FeedParser` instance.  Optional *_factory* is a no-argument
   callable that will be called whenever a new message object is needed.  It
   defaults to the :class:`email.message.Message` class.


   .. method:: feed(data)

      Feed the :class:`FeedParser` some more data.  *data* should be a string
      containing one or more lines.  The lines can be partial and the
      :class:`FeedParser` will stitch such partial lines together properly.  The
      lines in the string can have any of the common three line endings,
      carriage return, newline, or carriage return and newline (they can even be
      mixed).


   .. method:: close()

      Closing a :class:`FeedParser` completes the parsing of all previously fed
      data, and returns the root message object.  It is undefined what happens
      if you feed more data to a closed :class:`FeedParser`.


Parser class API
^^^^^^^^^^^^^^^^

The :class:`Parser` class, imported from the :mod:`email.parser` module,
provides an API that can be used to parse a message when the complete contents
of the message are available in a string or file.  The :mod:`email.parser`
module also provides a second class, called :class:`HeaderParser` which can be
used if you're only interested in the headers of the message.
:class:`HeaderParser` can be much faster in these situations, since it does not
attempt to parse the message body, instead setting the payload to the raw body
as a string. :class:`HeaderParser` has the same API as the :class:`Parser`
class.


.. class:: Parser([_class])

   The constructor for the :class:`Parser` class takes an optional argument
   *_class*.  This must be a callable factory (such as a function or a class), and
   it is used whenever a sub-message object needs to be created.  It defaults to
   :class:`~email.message.Message` (see :mod:`email.message`).  The factory will
   be called without arguments.

   The optional *strict* flag is ignored.

   .. deprecated:: 2.4
      Because the :class:`Parser` class is a backward compatible API wrapper
      around the new-in-Python 2.4 :class:`FeedParser`, *all* parsing is
      effectively non-strict.  You should simply stop passing a *strict* flag to
      the :class:`Parser` constructor.

   .. versionchanged:: 2.2.2
      The *strict* flag was added.

   .. versionchanged:: 2.4
      The *strict* flag was deprecated.

   The other public :class:`Parser` methods are:


   .. method:: parse(fp[, headersonly])

      Read all the data from the file-like object *fp*, parse the resulting
      text, and return the root message object.  *fp* must support both the
      :meth:`~io.TextIOBase.readline` and the :meth:`~io.TextIOBase.read`
      methods on file-like objects.

      The text contained in *fp* must be formatted as a block of :rfc:`2822`
      style headers and header continuation lines, optionally preceded by an
      envelope header.  The header block is terminated either by the end of the
      data or by a blank line.  Following the header block is the body of the
      message (which may contain MIME-encoded subparts).

      Optional *headersonly* is a flag specifying whether to stop parsing after
      reading the headers or not.  The default is ``False``, meaning it parses
      the entire contents of the file.

      .. versionchanged:: 2.2.2
         The *headersonly* flag was added.


   .. method:: parsestr(text[, headersonly])

      Similar to the :meth:`parse` method, except it takes a string object
      instead of a file-like object.  Calling this method on a string is exactly
      equivalent to wrapping *text* in a :class:`~StringIO.StringIO` instance first and
      calling :meth:`parse`.

      Optional *headersonly* is as with the :meth:`parse` method.

      .. versionchanged:: 2.2.2
         The *headersonly* flag was added.

Since creating a message object structure from a string or a file object is such
a common task, two functions are provided as a convenience.  They are available
in the top-level :mod:`email` package namespace.

.. currentmodule:: email

.. function:: message_from_string(s[, _class[, strict]])

   Return a message object structure from a string.  This is exactly equivalent to
   ``Parser().parsestr(s)``.  Optional *_class* and *strict* are interpreted as
   with the :class:`~email.parser.Parser` class constructor.

   .. versionchanged:: 2.2.2
      The *strict* flag was added.


.. function:: message_from_file(fp[, _class[, strict]])

   Return a message object structure tree from an open file object.  This is
   exactly equivalent to ``Parser().parse(fp)``.  Optional *_class* and *strict*
   are interpreted as with the :class:`~email.parser.Parser` class constructor.

   .. versionchanged:: 2.2.2
      The *strict* flag was added.

Here's an example of how you might use this at an interactive Python prompt::

   >>> import email
   >>> msg = email.message_from_string(myString)


Additional notes
^^^^^^^^^^^^^^^^

Here are some notes on the parsing semantics:

* Most non-\ :mimetype:`multipart` type messages are parsed as a single message
  object with a string payload.  These objects will return ``False`` for
  :meth:`~email.message.Message.is_multipart`.  Their
  :meth:`~email.message.Message.get_payload` method will return a string object.

* All :mimetype:`multipart` type messages will be parsed as a container message
  object with a list of sub-message objects for their payload.  The outer
  container message will return ``True`` for
  :meth:`~email.message.Message.is_multipart` and their
  :meth:`~email.message.Message.get_payload` method will return the list of
  :class:`~email.message.Message` subparts.

* Most messages with a content type of :mimetype:`message/\*` (e.g.
  :mimetype:`message/delivery-status` and :mimetype:`message/rfc822`) will also be
  parsed as container object containing a list payload of length 1.  Their
  :meth:`~email.message.Message.is_multipart` method will return ``True``.
  The single element in the list payload will be a sub-message object.

* Some non-standards compliant messages may not be internally consistent about
  their :mimetype:`multipart`\ -edness.  Such messages may have a
  :mailheader:`Content-Type` header of type :mimetype:`multipart`, but their
  :meth:`~email.message.Message.is_multipart` method may return ``False``.
  If such messages were parsed with the :class:`~email.parser.FeedParser`,
  they will have an instance of the
  :class:`~email.errors.MultipartInvariantViolationDefect` class in their
  *defects* attribute list.  See :mod:`email.errors` for details.

.. rubric:: Footnotes

.. [#] As of email package version 3.0, introduced in Python 2.4, the classic
   :class:`~email.parser.Parser` was re-implemented in terms of the
   :class:`~email.parser.FeedParser`, so the semantics and results are
   identical between the two parsers.

PK	%�\�4���>�>#html/_sources/library/email.rst.txtnu�[���:mod:`email` --- An email and MIME handling package
===================================================

.. module:: email
   :synopsis: Package supporting the parsing, manipulating, and generating email messages,
              including MIME documents.
.. moduleauthor:: Barry A. Warsaw <barry@python.org>
.. sectionauthor:: Barry A. Warsaw <barry@python.org>
.. Copyright (C) 2001-2007 Python Software Foundation


.. versionadded:: 2.2

The :mod:`email` package is a library for managing email messages, including
MIME and other :rfc:`2822`\ -based message documents.  It subsumes most of the
functionality in several older standard modules such as :mod:`rfc822`,
:mod:`mimetools`, :mod:`multifile`, and other non-standard packages such as
:mod:`mimecntl`.  It is specifically *not* designed to do any sending of email
messages to SMTP (:rfc:`2821`), NNTP, or other servers; those are functions of
modules such as :mod:`smtplib` and :mod:`nntplib`. The :mod:`email` package
attempts to be as RFC-compliant as possible, supporting in addition to
:rfc:`2822`, such MIME-related RFCs as :rfc:`2045`, :rfc:`2046`, :rfc:`2047`,
and :rfc:`2231`.

The primary distinguishing feature of the :mod:`email` package is that it splits
the parsing and generating of email messages from the internal *object model*
representation of email.  Applications using the :mod:`email` package deal
primarily with objects; you can add sub-objects to messages, remove sub-objects
from messages, completely re-arrange the contents, etc.  There is a separate
parser and a separate generator which handles the transformation from flat text
to the object model, and then back to flat text again.  There are also handy
subclasses for some common MIME object types, and a few miscellaneous utilities
that help with such common tasks as extracting and parsing message field values,
creating RFC-compliant dates, etc.

The following sections describe the functionality of the :mod:`email` package.
The ordering follows a progression that should be common in applications: an
email message is read as flat text from a file or other source, the text is
parsed to produce the object structure of the email message, this structure is
manipulated, and finally, the object tree is rendered back into flat text.

It is perfectly feasible to create the object structure out of whole cloth ---
i.e. completely from scratch.  From there, a similar progression can be taken as
above.

Also included are detailed specifications of all the classes and modules that
the :mod:`email` package provides, the exception classes you might encounter
while using the :mod:`email` package, some auxiliary utilities, and a few
examples.  For users of the older :mod:`mimelib` package, or previous versions
of the :mod:`email` package, a section on differences and porting is provided.

Contents of the :mod:`email` package documentation:

.. toctree::

   email.message.rst
   email.parser.rst
   email.generator.rst
   email.mime.rst
   email.header.rst
   email.charset.rst
   email.encoders.rst
   email.errors.rst
   email.utils.rst
   email.iterators.rst
   email-examples.rst


.. seealso::

   Module :mod:`smtplib`
      SMTP protocol client

   Module :mod:`nntplib`
      NNTP protocol client


.. _email-pkg-history:

Package History
---------------

This table describes the release history of the email package, corresponding to
the version of Python that the package was released with.  For purposes of this
document, when you see a note about change or added versions, these refer to the
Python version the change was made in, *not* the email package version.  This
table also describes the Python compatibility of each version of the package.

+---------------+------------------------------+-----------------------+
| email version | distributed with             | compatible with       |
+===============+==============================+=======================+
| :const:`1.x`  | Python 2.2.0 to Python 2.2.1 | *no longer supported* |
+---------------+------------------------------+-----------------------+
| :const:`2.5`  | Python 2.2.2+ and Python 2.3 | Python 2.1 to 2.5     |
+---------------+------------------------------+-----------------------+
| :const:`3.0`  | Python 2.4                   | Python 2.3 to 2.5     |
+---------------+------------------------------+-----------------------+
| :const:`4.0`  | Python 2.5                   | Python 2.3 to 2.5     |
+---------------+------------------------------+-----------------------+

Here are the major differences between :mod:`email` version 4 and version 3:

* All modules have been renamed according to :pep:`8` standards.  For example,
  the version 3 module :mod:`email.Message` was renamed to :mod:`email.message` in
  version 4.

* A new subpackage :mod:`email.mime` was added and all the version 3
  :mod:`email.MIME\*` modules were renamed and situated into the :mod:`email.mime`
  subpackage.  For example, the version 3 module :mod:`email.MIMEText` was renamed
  to :mod:`email.mime.text`.

  *Note that the version 3 names will continue to work until Python 2.6*.

* The :mod:`email.mime.application` module was added, which contains the
  :class:`~email.mime.application.MIMEApplication` class.

* Methods that were deprecated in version 3 have been removed.  These include
  :meth:`Generator.__call__`, :meth:`Message.get_type`,
  :meth:`Message.get_main_type`, :meth:`Message.get_subtype`.

* Fixes have been added for :rfc:`2231` support which can change some of the
  return types for :func:`Message.get_param <email.message.Message.get_param>`
  and friends.  Under some
  circumstances, values which used to return a 3-tuple now return simple strings
  (specifically, if all extended parameter segments were unencoded, there is no
  language and charset designation expected, so the return type is now a simple
  string).  Also, %-decoding used to be done for both encoded and unencoded
  segments; this decoding is now done only for encoded segments.

Here are the major differences between :mod:`email` version 3 and version 2:

* The :class:`~email.parser.FeedParser` class was introduced, and the
  :class:`~email.parser.Parser` class was implemented in terms of the
  :class:`~email.parser.FeedParser`.  All parsing therefore is
  non-strict, and parsing will make a best effort never to raise an exception.
  Problems found while parsing messages are stored in the message's *defect*
  attribute.

* All aspects of the API which raised :exc:`DeprecationWarning`\ s in version 2
  have been removed.  These include the *_encoder* argument to the
  :class:`~email.mime.text.MIMEText` constructor, the
  :meth:`Message.add_payload` method, the :func:`Utils.dump_address_pair`
  function, and the functions :func:`Utils.decode` and :func:`Utils.encode`.

* New :exc:`DeprecationWarning`\ s have been added to:
  :meth:`Generator.__call__`, :meth:`Message.get_type`,
  :meth:`Message.get_main_type`, :meth:`Message.get_subtype`, and the *strict*
  argument to the :class:`~email.parser.Parser` class.  These are expected to
  be removed in future versions.

* Support for Pythons earlier than 2.3 has been removed.

Here are the differences between :mod:`email` version 2 and version 1:

* The :mod:`email.Header` and :mod:`email.Charset` modules have been added.

* The pickle format for :class:`~email.message.Message` instances has changed.
  Since this was never (and still isn't) formally defined, this isn't
  considered a backward incompatibility.  However if your application pickles
  and unpickles :class:`~email.message.Message` instances, be aware that in
  :mod:`email` version 2, :class:`~email.message.Message` instances now have
  private variables *_charset* and *_default_type*.

* Several methods in the :class:`~email.message.Message` class have been
  deprecated, or their signatures changed.  Also, many new methods have been
  added.  See the documentation for the :class:`~email.message.Message` class
  for details.  The changes should be completely backward compatible.

* The object structure has changed in the face of :mimetype:`message/rfc822`
  content types.  In :mod:`email` version 1, such a type would be represented
  by a scalar payload, i.e. the container message's
  :meth:`~email.message.Message.is_multipart` returned false,
  :meth:`~email.message.Message.get_payload` was not a list object, but a
  single :class:`~email.message.Message` instance.

  This structure was inconsistent with the rest of the package, so the object
  representation for :mimetype:`message/rfc822` content types was changed.  In
  :mod:`email` version 2, the container *does* return ``True`` from
  :meth:`~email.message.Message.is_multipart`, and
  :meth:`~email.message.Message.get_payload` returns a list containing a single
  :class:`~email.message.Message` item.

  Note that this is one place that backward compatibility could not be
  completely maintained.  However, if you're already testing the return type of
  :meth:`~email.message.Message.get_payload`, you should be fine.  You just need
  to make sure your code doesn't do a :meth:`~email.message.Message.set_payload`
  with a :class:`~email.message.Message` instance on a container with a content
  type of :mimetype:`message/rfc822`.

* The :class:`~email.parser.Parser` constructor's *strict* argument was added,
  and its :meth:`~email.parser.Parser.parse` and
  :meth:`~email.parser.Parser.parsestr` methods grew a *headersonly* argument.
  The *strict* flag was also added to functions :func:`email.message_from_file`
  and :func:`email.message_from_string`.

* :meth:`Generator.__call__` is deprecated; use :meth:`Generator.flatten
  <email.generator.Generator.flatten>` instead.  The
  :class:`~email.generator.Generator` class has also grown the
  :meth:`~email.generator.Generator.clone` method.

* The :class:`~email.generator.DecodedGenerator` class in the
  :mod:`email.generator` module was added.

* The intermediate base classes
  :class:`~email.mime.nonmultipart.MIMENonMultipart` and
  :class:`~email.mime.multipart.MIMEMultipart` have been added, and interposed
  in the class hierarchy for most of the other MIME-related derived classes.

* The *_encoder* argument to the :class:`~email.mime.text.MIMEText` constructor
  has been deprecated.  Encoding  now happens implicitly based on the
  *_charset* argument.

* The following functions in the :mod:`email.Utils` module have been deprecated:
  :func:`dump_address_pairs`, :func:`decode`, and :func:`encode`.  The following
  functions have been added to the module: :func:`make_msgid`,
  :func:`decode_rfc2231`, :func:`encode_rfc2231`, and :func:`decode_params`.

* The non-public function :func:`email.Iterators._structure` was added.


Differences from :mod:`mimelib`
-------------------------------

The :mod:`email` package was originally prototyped as a separate library called
`mimelib <http://mimelib.sourceforge.net/>`_. Changes have been made so that method names
are more consistent, and some methods or modules have either been added or
removed.  The semantics of some of the methods have also changed.  For the most
part, any functionality available in :mod:`mimelib` is still available in the
:mod:`email` package, albeit often in a different way.  Backward compatibility
between the :mod:`mimelib` package and the :mod:`email` package was not a
priority.

Here is a brief description of the differences between the :mod:`mimelib` and
the :mod:`email` packages, along with hints on how to port your applications.

Of course, the most visible difference between the two packages is that the
package name has been changed to :mod:`email`.  In addition, the top-level
package has the following differences:

* :func:`messageFromString` has been renamed to :func:`message_from_string`.

* :func:`messageFromFile` has been renamed to :func:`message_from_file`.

The :class:`~email.message.Message` class has the following differences:

* The method :meth:`asString` was renamed to
  :meth:`~email.message.Message.as_string`.

* The method :meth:`ismultipart` was renamed to
  :meth:`~email.message.Message.is_multipart`.

* The :meth:`~email.message.Message.get_payload` method has grown a *decode*
  optional argument.

* The method :meth:`getall` was renamed to
  :meth:`~email.message.Message.get_all`.

* The method :meth:`addheader` was renamed to
  :meth:`~email.message.Message.add_header`.

* The method :meth:`gettype` was renamed to :meth:`get_type`.

* The method :meth:`getmaintype` was renamed to :meth:`get_main_type`.

* The method :meth:`getsubtype` was renamed to :meth:`get_subtype`.

* The method :meth:`getparams` was renamed to
  :meth:`~email.message.Message.get_params`. Also, whereas :meth:`getparams`
  returned a list of strings, :meth:`~email.message.Message.get_params` returns
  a list of 2-tuples, effectively the key/value pairs of the parameters, split
  on the ``'='`` sign.

* The method :meth:`getparam` was renamed to
  :meth:`~email.message.Message.get_param`.

* The method :meth:`getcharsets` was renamed to
  :meth:`~email.message.Message.get_charsets`.

* The method :meth:`getfilename` was renamed to
  :meth:`~email.message.Message.get_filename`.

* The method :meth:`getboundary` was renamed to
  :meth:`~email.message.Message.get_boundary`.

* The method :meth:`setboundary` was renamed to
  :meth:`~email.message.Message.set_boundary`.

* The method :meth:`getdecodedpayload` was removed.  To get similar
  functionality, pass the value 1 to the *decode* flag of the
  :meth:`~email.message.Message.get_payload` method.

* The method :meth:`getpayloadastext` was removed.  Similar functionality is
  supported by the :class:`~email.generator.DecodedGenerator` class in the
  :mod:`email.generator` module.

* The method :meth:`getbodyastext` was removed.  You can get similar
  functionality by creating an iterator with
  :func:`~email.iterators.typed_subpart_iterator` in the :mod:`email.iterators`
  module.

The :class:`~email.parser.Parser` class has no differences in its public
interface. It does have some additional smarts to recognize
:mimetype:`message/delivery-status` type messages, which it represents as a
:class:`~email.message.Message` instance containing separate
:class:`~email.message.Message` subparts for each header block in the delivery
status notification [#]_.

The :class:`~email.generator.Generator` class has no differences in its public
interface.  There is a new class in the :mod:`email.generator` module though,
called :class:`~email.generator.DecodedGenerator` which provides most of the
functionality previously available in the :meth:`Message.getpayloadastext`
method.

The following modules and classes have been changed:

* The :class:`~email.mime.base.MIMEBase` class constructor arguments *_major*
  and *_minor* have changed to *_maintype* and *_subtype* respectively.

* The ``Image`` class/module has been renamed to ``MIMEImage``.  The *_minor*
  argument has been renamed to *_subtype*.

* The ``Text`` class/module has been renamed to ``MIMEText``.  The *_minor*
  argument has been renamed to *_subtype*.

* The ``MessageRFC822`` class/module has been renamed to ``MIMEMessage``.  Note
  that an earlier version of :mod:`mimelib` called this class/module ``RFC822``,
  but that clashed with the Python standard library module :mod:`rfc822` on some
  case-insensitive file systems.

  Also, the :class:`~email.mime.message.MIMEMessage` class now represents any
  kind of MIME message
  with main type :mimetype:`message`.  It takes an optional argument *_subtype*
  which is used to set the MIME subtype.  *_subtype* defaults to
  :mimetype:`rfc822`.

:mod:`mimelib` provided some utility functions in its :mod:`address` and
:mod:`date` modules.  All of these functions have been moved to the
:mod:`email.utils` module.

The ``MsgReader`` class/module has been removed.  Its functionality is most
closely supported in the :func:`~email.iterators.body_line_iterator` function
in the :mod:`email.iterators` module.

.. rubric:: Footnotes

.. [#] Delivery Status Notifications (DSN) are defined in :rfc:`1894`.
PK	%�\�iL�KK)html/_sources/library/email.utils.rst.txtnu�[���:mod:`email.utils`: Miscellaneous utilities
-------------------------------------------

.. module:: email.utils
   :synopsis: Miscellaneous email package utilities.


There are several useful utilities provided in the :mod:`email.utils` module:


.. function:: quote(str)

   Return a new string with backslashes in *str* replaced by two backslashes, and
   double quotes replaced by backslash-double quote.


.. function:: unquote(str)

   Return a new string which is an *unquoted* version of *str*. If *str* ends and
   begins with double quotes, they are stripped off.  Likewise if *str* ends and
   begins with angle brackets, they are stripped off.


.. function:: parseaddr(address)

   Parse address -- which should be the value of some address-containing field such
   as :mailheader:`To` or :mailheader:`Cc` -- into its constituent *realname* and
   *email address* parts.  Returns a tuple of that information, unless the parse
   fails, in which case a 2-tuple of ``('', '')`` is returned.


.. function:: formataddr(pair)

   The inverse of :meth:`parseaddr`, this takes a 2-tuple of the form ``(realname,
   email_address)`` and returns the string value suitable for a :mailheader:`To` or
   :mailheader:`Cc` header.  If the first element of *pair* is false, then the
   second element is returned unmodified.


.. function:: getaddresses(fieldvalues)

   This method returns a list of 2-tuples of the form returned by ``parseaddr()``.
   *fieldvalues* is a sequence of header field values as might be returned by
   :meth:`Message.get_all <email.message.Message.get_all>`.  Here's a simple
   example that gets all the recipients of a message::

      from email.utils import getaddresses

      tos = msg.get_all('to', [])
      ccs = msg.get_all('cc', [])
      resent_tos = msg.get_all('resent-to', [])
      resent_ccs = msg.get_all('resent-cc', [])
      all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)


.. function:: parsedate(date)

   Attempts to parse a date according to the rules in :rfc:`2822`. however, some
   mailers don't follow that format as specified, so :func:`parsedate` tries to
   guess correctly in such cases.  *date* is a string containing an :rfc:`2822`
   date, such as  ``"Mon, 20 Nov 1995 19:12:08 -0500"``.  If it succeeds in parsing
   the date, :func:`parsedate` returns a 9-tuple that can be passed directly to
   :func:`time.mktime`; otherwise ``None`` will be returned.  Note that indexes 6,
   7, and 8 of the result tuple are not usable.


.. function:: parsedate_tz(date)

   Performs the same function as :func:`parsedate`, but returns either ``None`` or
   a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
   :func:`time.mktime`, and the tenth is the offset of the date's timezone from UTC
   (which is the official term for Greenwich Mean Time) [#]_.  If the input string
   has no timezone, the last element of the tuple returned is ``None``.  Note that
   indexes 6, 7, and 8 of the result tuple are not usable.


.. function:: mktime_tz(tuple)

   Turn a 10-tuple as returned by :func:`parsedate_tz` into a UTC
   timestamp (seconds since the Epoch).  If the timezone item in the
   tuple is ``None``, assume local time.


.. function:: formatdate([timeval[, localtime][, usegmt]])

   Returns a date string as per :rfc:`2822`, e.g.::

      Fri, 09 Nov 2001 01:08:47 -0000

   Optional *timeval* if given is a floating point time value as accepted by
   :func:`time.gmtime` and :func:`time.localtime`, otherwise the current time is
   used.

   Optional *localtime* is a flag that when ``True``, interprets *timeval*, and
   returns a date relative to the local timezone instead of UTC, properly taking
   daylight savings time into account. The default is ``False`` meaning UTC is
   used.

   Optional *usegmt* is a flag that when ``True``, outputs a  date string with the
   timezone as an ascii string ``GMT``, rather than a numeric ``-0000``. This is
   needed for some protocols (such as HTTP). This only applies when *localtime* is
   ``False``.  The default is ``False``.

   .. versionadded:: 2.4


.. function:: make_msgid([idstring])

   Returns a string suitable for an :rfc:`2822`\ -compliant
   :mailheader:`Message-ID` header.  Optional *idstring* if given, is a string used
   to strengthen the uniqueness of the message id.


.. function:: decode_rfc2231(s)

   Decode the string *s* according to :rfc:`2231`.


.. function:: encode_rfc2231(s[, charset[, language]])

   Encode the string *s* according to :rfc:`2231`.  Optional *charset* and
   *language*, if given is the character set name and language name to use.  If
   neither is given, *s* is returned as-is.  If *charset* is given but *language*
   is not, the string is encoded using the empty string for *language*.


.. function:: collapse_rfc2231_value(value[, errors[, fallback_charset]])

   When a header parameter is encoded in :rfc:`2231` format,
   :meth:`Message.get_param <email.message.Message.get_param>` may return a
   3-tuple containing the character set,
   language, and value.  :func:`collapse_rfc2231_value` turns this into a unicode
   string.  Optional *errors* is passed to the *errors* argument of the built-in
   :func:`unicode` function; it defaults to ``replace``.  Optional
   *fallback_charset* specifies the character set to use if the one in the
   :rfc:`2231` header is not known by Python; it defaults to ``us-ascii``.

   For convenience, if the *value* passed to :func:`collapse_rfc2231_value` is not
   a tuple, it should be a string and it is returned unquoted.


.. function:: decode_params(params)

   Decode parameters list according to :rfc:`2231`.  *params* is a sequence of
   2-tuples containing elements of the form ``(content-type, string-value)``.

.. versionchanged:: 2.4
   The :func:`dump_address_pair` function has been removed; use :func:`formataddr`
   instead.

.. versionchanged:: 2.4
   The :func:`decode` function has been removed; use the
   :meth:`Header.decode_header <email.header.Header.decode_header>` method
   instead.

.. versionchanged:: 2.4
   The :func:`encode` function has been removed; use the :meth:`Header.encode
   <email.header.Header.encode>` method instead.

.. rubric:: Footnotes

.. [#] Note that the sign of the timezone offset is the opposite of the sign of the
   ``time.timezone`` variable for the same timezone; the latter variable follows
   the POSIX standard while this module follows :rfc:`2822`.
PK	%�\IjT��'html/_sources/library/ensurepip.rst.txtnu�[���:mod:`ensurepip` --- Bootstrapping the ``pip`` installer
========================================================

.. module:: ensurepip
   :synopsis: Bootstrapping the ``pip`` installer into an existing Python
              installation or virtual environment.

.. versionadded:: 2.7.9

The :mod:`ensurepip` package provides support for bootstrapping the ``pip``
installer into an existing Python installation or virtual environment. This
bootstrapping approach reflects the fact that ``pip`` is an independent
project with its own release cycle, and the latest available stable version
is bundled with maintenance and feature releases of the CPython reference
interpreter.

In most cases, end users of Python shouldn't need to invoke this module
directly (as ``pip`` should be bootstrapped by default), but it may be
needed if installing ``pip`` was skipped when installing Python (or
when creating a virtual environment) or after explicitly uninstalling ``pip``.

.. note::

   This module *does not* access the internet. All of the components
   needed to bootstrap ``pip`` are included as internal parts of the
   package.

.. seealso::

   :ref:`installing-index`
      The end user guide for installing Python packages

   :pep:`453`: Explicit bootstrapping of pip in Python installations
      The original rationale and specification for this module.

   :pep:`477`: Backport ensurepip (PEP 453) to Python 2.7
      The rationale and specification for backporting PEP 453 to Python 2.7.


Command line interface
----------------------

The command line interface is invoked using the interpreter's ``-m`` switch.

The simplest possible invocation is::

    python -m ensurepip

This invocation will install ``pip`` if it is not already installed,
but otherwise does nothing. To ensure the installed version of ``pip``
is at least as recent as the one bundled with ``ensurepip``, pass the
``--upgrade`` option::

    python -m ensurepip --upgrade

By default, ``pip`` is installed into the current virtual environment
(if one is active) or into the system site packages (if there is no
active virtual environment). The installation location can be controlled
through two additional command line options:

* ``--root <dir>``: Installs ``pip`` relative to the given root directory
  rather than the root of the currently active virtual environment (if any)
  or the default root for the current Python installation.
* ``--user``: Installs ``pip`` into the user site packages directory rather
  than globally for the current Python installation (this option is not
  permitted inside an active virtual environment).

By default, the scripts ``pip``, ``pipX``, and ``pipX.Y`` will be installed
(where X.Y stands for the version of Python used to invoke ``ensurepip``). The
scripts installed can be controlled through two additional command line
options:

* ``--altinstall``: if an alternate installation is requested, the ``pip`` and
  ``pipX`` script will *not* be installed.

* ``--no-default-pip``: if a non-default installation is request, the ``pip``
  script will *not* be installed.

.. versionchanged:: 2.7.15
   The exit status is non-zero if the command fails.


Module API
----------

:mod:`ensurepip` exposes two functions for programmatic use:

.. function:: version()

   Returns a string specifying the bundled version of pip that will be
   installed when bootstrapping an environment.

.. function:: bootstrap(root=None, upgrade=False, user=False, \
                        altinstall=False, default_pip=True, \
                        verbosity=0)

   Bootstraps ``pip`` into the current or designated environment.

   *root* specifies an alternative root directory to install relative to.
   If *root* is ``None``, then installation uses the default install location
   for the current environment.

   *upgrade* indicates whether or not to upgrade an existing installation
   of an earlier version of ``pip`` to the bundled version.

   *user* indicates whether to use the user scheme rather than installing
   globally.

   By default, the scripts ``pip``, ``pipX``, and ``pipX.Y`` will be installed
   (where X.Y stands for the current version of Python).

   If *altinstall* is set, then ``pip`` and ``pipX`` will *not* be installed.

   If *default_pip* is set to ``False``, then ``pip`` will *not* be installed.

   Setting both *altinstall* and *default_pip* will trigger
   :exc:`ValueError`.

   *verbosity* controls the level of output to :data:`sys.stdout` from the
   bootstrapping operation.

   .. note::

      The bootstrapping process has side effects on both ``sys.path`` and
      ``os.environ``. Invoking the command line interface in a subprocess
      instead allows these side effects to be avoided.

   .. note::

      The bootstrapping process may install additional modules required by
      ``pip``, but other software should not assume those dependencies will
      always be present by default (as the dependencies may be removed in a
      future version of ``pip``).
PK	%�\��Y44#html/_sources/library/errno.rst.txtnu�[���
:mod:`errno` --- Standard errno system symbols
==============================================

.. module:: errno
   :synopsis: Standard errno system symbols.


This module makes available standard ``errno`` system symbols. The value of each
symbol is the corresponding integer value. The names and descriptions are
borrowed from :file:`linux/include/errno.h`, which should be pretty
all-inclusive.


.. data:: errorcode

   Dictionary providing a mapping from the errno value to the string name in the
   underlying system.  For instance, ``errno.errorcode[errno.EPERM]`` maps to
   ``'EPERM'``.

To translate a numeric error code to an error message, use :func:`os.strerror`.

Of the following list, symbols that are not used on the current platform are not
defined by the module.  The specific list of defined symbols is available as
``errno.errorcode.keys()``.  Symbols available can include:


.. data:: EPERM

   Operation not permitted


.. data:: ENOENT

   No such file or directory


.. data:: ESRCH

   No such process


.. data:: EINTR

   Interrupted system call


.. data:: EIO

   I/O error


.. data:: ENXIO

   No such device or address


.. data:: E2BIG

   Arg list too long


.. data:: ENOEXEC

   Exec format error


.. data:: EBADF

   Bad file number


.. data:: ECHILD

   No child processes


.. data:: EAGAIN

   Try again


.. data:: ENOMEM

   Out of memory


.. data:: EACCES

   Permission denied


.. data:: EFAULT

   Bad address


.. data:: ENOTBLK

   Block device required


.. data:: EBUSY

   Device or resource busy


.. data:: EEXIST

   File exists


.. data:: EXDEV

   Cross-device link


.. data:: ENODEV

   No such device


.. data:: ENOTDIR

   Not a directory


.. data:: EISDIR

   Is a directory


.. data:: EINVAL

   Invalid argument


.. data:: ENFILE

   File table overflow


.. data:: EMFILE

   Too many open files


.. data:: ENOTTY

   Not a typewriter


.. data:: ETXTBSY

   Text file busy


.. data:: EFBIG

   File too large


.. data:: ENOSPC

   No space left on device


.. data:: ESPIPE

   Illegal seek


.. data:: EROFS

   Read-only file system


.. data:: EMLINK

   Too many links


.. data:: EPIPE

   Broken pipe


.. data:: EDOM

   Math argument out of domain of func


.. data:: ERANGE

   Math result not representable


.. data:: EDEADLK

   Resource deadlock would occur


.. data:: ENAMETOOLONG

   File name too long


.. data:: ENOLCK

   No record locks available


.. data:: ENOSYS

   Function not implemented


.. data:: ENOTEMPTY

   Directory not empty


.. data:: ELOOP

   Too many symbolic links encountered


.. data:: EWOULDBLOCK

   Operation would block


.. data:: ENOMSG

   No message of desired type


.. data:: EIDRM

   Identifier removed


.. data:: ECHRNG

   Channel number out of range


.. data:: EL2NSYNC

   Level 2 not synchronized


.. data:: EL3HLT

   Level 3 halted


.. data:: EL3RST

   Level 3 reset


.. data:: ELNRNG

   Link number out of range


.. data:: EUNATCH

   Protocol driver not attached


.. data:: ENOCSI

   No CSI structure available


.. data:: EL2HLT

   Level 2 halted


.. data:: EBADE

   Invalid exchange


.. data:: EBADR

   Invalid request descriptor


.. data:: EXFULL

   Exchange full


.. data:: ENOANO

   No anode


.. data:: EBADRQC

   Invalid request code


.. data:: EBADSLT

   Invalid slot


.. data:: EDEADLOCK

   File locking deadlock error


.. data:: EBFONT

   Bad font file format


.. data:: ENOSTR

   Device not a stream


.. data:: ENODATA

   No data available


.. data:: ETIME

   Timer expired


.. data:: ENOSR

   Out of streams resources


.. data:: ENONET

   Machine is not on the network


.. data:: ENOPKG

   Package not installed


.. data:: EREMOTE

   Object is remote


.. data:: ENOLINK

   Link has been severed


.. data:: EADV

   Advertise error


.. data:: ESRMNT

   Srmount error


.. data:: ECOMM

   Communication error on send


.. data:: EPROTO

   Protocol error


.. data:: EMULTIHOP

   Multihop attempted


.. data:: EDOTDOT

   RFS specific error


.. data:: EBADMSG

   Not a data message


.. data:: EOVERFLOW

   Value too large for defined data type


.. data:: ENOTUNIQ

   Name not unique on network


.. data:: EBADFD

   File descriptor in bad state


.. data:: EREMCHG

   Remote address changed


.. data:: ELIBACC

   Can not access a needed shared library


.. data:: ELIBBAD

   Accessing a corrupted shared library


.. data:: ELIBSCN

   .lib section in a.out corrupted


.. data:: ELIBMAX

   Attempting to link in too many shared libraries


.. data:: ELIBEXEC

   Cannot exec a shared library directly


.. data:: EILSEQ

   Illegal byte sequence


.. data:: ERESTART

   Interrupted system call should be restarted


.. data:: ESTRPIPE

   Streams pipe error


.. data:: EUSERS

   Too many users


.. data:: ENOTSOCK

   Socket operation on non-socket


.. data:: EDESTADDRREQ

   Destination address required


.. data:: EMSGSIZE

   Message too long


.. data:: EPROTOTYPE

   Protocol wrong type for socket


.. data:: ENOPROTOOPT

   Protocol not available


.. data:: EPROTONOSUPPORT

   Protocol not supported


.. data:: ESOCKTNOSUPPORT

   Socket type not supported


.. data:: EOPNOTSUPP

   Operation not supported on transport endpoint


.. data:: EPFNOSUPPORT

   Protocol family not supported


.. data:: EAFNOSUPPORT

   Address family not supported by protocol


.. data:: EADDRINUSE

   Address already in use


.. data:: EADDRNOTAVAIL

   Cannot assign requested address


.. data:: ENETDOWN

   Network is down


.. data:: ENETUNREACH

   Network is unreachable


.. data:: ENETRESET

   Network dropped connection because of reset


.. data:: ECONNABORTED

   Software caused connection abort


.. data:: ECONNRESET

   Connection reset by peer


.. data:: ENOBUFS

   No buffer space available


.. data:: EISCONN

   Transport endpoint is already connected


.. data:: ENOTCONN

   Transport endpoint is not connected


.. data:: ESHUTDOWN

   Cannot send after transport endpoint shutdown


.. data:: ETOOMANYREFS

   Too many references: cannot splice


.. data:: ETIMEDOUT

   Connection timed out


.. data:: ECONNREFUSED

   Connection refused


.. data:: EHOSTDOWN

   Host is down


.. data:: EHOSTUNREACH

   No route to host


.. data:: EALREADY

   Operation already in progress


.. data:: EINPROGRESS

   Operation now in progress


.. data:: ESTALE

   Stale NFS file handle


.. data:: EUCLEAN

   Structure needs cleaning


.. data:: ENOTNAM

   Not a XENIX named type file


.. data:: ENAVAIL

   No XENIX semaphores available


.. data:: EISNAM

   Is a named type file


.. data:: EREMOTEIO

   Remote I/O error


.. data:: EDQUOT

   Quota exceeded

PK	%�\9!s�G�G(html/_sources/library/exceptions.rst.txtnu�[���.. _bltin-exceptions:

Built-in Exceptions
===================

.. module:: exceptions
   :synopsis: Standard exception classes.


Exceptions should be class objects.   The exceptions are defined in the module
:mod:`exceptions`.  This module never needs to be imported explicitly: the
exceptions are provided in the built-in namespace as well as the
:mod:`exceptions` module.

.. index::
   statement: try
   statement: except

For class exceptions, in a :keyword:`try` statement with an :keyword:`except`
clause that mentions a particular class, that clause also handles any exception
classes derived from that class (but not exception classes from which *it* is
derived).  Two exception classes that are not related via subclassing are never
equivalent, even if they have the same name.

.. index:: statement: raise

The built-in exceptions listed below can be generated by the interpreter or
built-in functions.  Except where mentioned, they have an "associated value"
indicating the detailed cause of the error.  This may be a string or a tuple
containing several items of information (e.g., an error code and a string
explaining the code). The associated value is the second argument to the
:keyword:`raise` statement.  If the exception class is derived from the standard
root class :exc:`BaseException`, the associated value is present as the
exception instance's :attr:`args` attribute.

User code can raise built-in exceptions.  This can be used to test an exception
handler or to report an error condition "just like" the situation in which the
interpreter raises the same exception; but beware that there is nothing to
prevent user code from raising an inappropriate error.

The built-in exception classes can be subclassed to define new exceptions;
programmers are encouraged to derive new exceptions from the :exc:`Exception`
class or one of its subclasses, and not from :exc:`BaseException`.  More
information on defining exceptions is available in the Python Tutorial under
:ref:`tut-userexceptions`.

The following exceptions are only used as base classes for other exceptions.

.. exception:: BaseException

   The base class for all built-in exceptions.  It is not meant to be directly
   inherited by user-defined classes (for that, use :exc:`Exception`).  If
   :func:`str` or :func:`unicode` is called on an instance of this class, the
   representation of the argument(s) to the instance are returned, or the empty
   string when there were no arguments.

   .. versionadded:: 2.5

   .. attribute:: args

      The tuple of arguments given to the exception constructor.  Some built-in
      exceptions (like :exc:`IOError`) expect a certain number of arguments and
      assign a special meaning to the elements of this tuple, while others are
      usually called only with a single string giving an error message.


.. exception:: Exception

   All built-in, non-system-exiting exceptions are derived from this class.  All
   user-defined exceptions should also be derived from this class.

   .. versionchanged:: 2.5
      Changed to inherit from :exc:`BaseException`.


.. exception:: StandardError

   The base class for all built-in exceptions except :exc:`StopIteration`,
   :exc:`GeneratorExit`, :exc:`KeyboardInterrupt` and :exc:`SystemExit`.
   :exc:`StandardError` itself is derived from :exc:`Exception`.


.. exception:: ArithmeticError

   The base class for those built-in exceptions that are raised for various
   arithmetic errors: :exc:`OverflowError`, :exc:`ZeroDivisionError`,
   :exc:`FloatingPointError`.


.. exception:: BufferError

   Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
   performed.


.. exception:: LookupError

   The base class for the exceptions that are raised when a key or index used on
   a mapping or sequence is invalid: :exc:`IndexError`, :exc:`KeyError`.  This
   can be raised directly by :func:`codecs.lookup`.


.. exception:: EnvironmentError

   The base class for exceptions that can occur outside the Python system:
   :exc:`IOError`, :exc:`OSError`.  When exceptions of this type are created with a
   2-tuple, the first item is available on the instance's :attr:`errno` attribute
   (it is assumed to be an error number), and the second item is available on the
   :attr:`strerror` attribute (it is usually the associated error message).  The
   tuple itself is also available on the :attr:`args` attribute.

   .. versionadded:: 1.5.2

   When an :exc:`EnvironmentError` exception is instantiated with a 3-tuple, the
   first two items are available as above, while the third item is available on the
   :attr:`filename` attribute.  However, for backwards compatibility, the
   :attr:`args` attribute contains only a 2-tuple of the first two constructor
   arguments.

   The :attr:`filename` attribute is ``None`` when this exception is created with
   other than 3 arguments.  The :attr:`errno` and :attr:`strerror` attributes are
   also ``None`` when the instance was created with other than 2 or 3 arguments.
   In this last case, :attr:`args` contains the verbatim constructor arguments as a
   tuple.

The following exceptions are the exceptions that are actually raised.


.. exception:: AssertionError

   .. index:: statement: assert

   Raised when an :keyword:`assert` statement fails.


.. exception:: AttributeError

   Raised when an attribute reference (see :ref:`attribute-references`) or
   assignment fails.  (When an object does not support attribute references or
   attribute assignments at all, :exc:`TypeError` is raised.)


.. exception:: EOFError

   Raised when one of the built-in functions (:func:`input` or :func:`raw_input`)
   hits an end-of-file condition (EOF) without reading any data. (N.B.: the
   :meth:`file.read` and :meth:`file.readline` methods return an empty string
   when they hit EOF.)


.. exception:: FloatingPointError

   Raised when a floating point operation fails.  This exception is always defined,
   but can only be raised when Python is configured with the
   ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
   defined in the :file:`pyconfig.h` file.


.. exception:: GeneratorExit

   Raised when a :term:`generator`\'s :meth:`close` method is called.  It
   directly inherits from :exc:`BaseException` instead of :exc:`StandardError`
   since it is technically not an error.

   .. versionadded:: 2.5

   .. versionchanged:: 2.6
      Changed to inherit from :exc:`BaseException`.

.. exception:: IOError

   Raised when an I/O operation (such as a :keyword:`print` statement, the built-in
   :func:`open` function or a method of a file object) fails for an I/O-related
   reason, e.g., "file not found" or "disk full".

   This class is derived from :exc:`EnvironmentError`.  See the discussion above
   for more information on exception instance attributes.

   .. versionchanged:: 2.6
      Changed :exc:`socket.error` to use this as a base class.


.. exception:: ImportError

   Raised when an :keyword:`import` statement fails to find the module definition
   or when a ``from ... import`` fails to find a name that is to be imported.


.. exception:: IndexError

   Raised when a sequence subscript is out of range.  (Slice indices are silently
   truncated to fall in the allowed range; if an index is not a plain integer,
   :exc:`TypeError` is raised.)

   .. XXX xref to sequences


.. exception:: KeyError

   Raised when a mapping (dictionary) key is not found in the set of existing keys.

   .. XXX xref to mapping objects?


.. exception:: KeyboardInterrupt

   Raised when the user hits the interrupt key (normally :kbd:`Control-C` or
   :kbd:`Delete`).  During execution, a check for interrupts is made regularly.
   Interrupts typed when a built-in function :func:`input` or :func:`raw_input` is
   waiting for input also raise this exception. The exception inherits from
   :exc:`BaseException` so as to not be accidentally caught by code that catches
   :exc:`Exception` and thus prevent the interpreter from exiting.

   .. versionchanged:: 2.5
      Changed to inherit from :exc:`BaseException`.


.. exception:: MemoryError

   Raised when an operation runs out of memory but the situation may still be
   rescued (by deleting some objects).  The associated value is a string indicating
   what kind of (internal) operation ran out of memory. Note that because of the
   underlying memory management architecture (C's :c:func:`malloc` function), the
   interpreter may not always be able to completely recover from this situation; it
   nevertheless raises an exception so that a stack traceback can be printed, in
   case a run-away program was the cause.


.. exception:: NameError

   Raised when a local or global name is not found.  This applies only to
   unqualified names.  The associated value is an error message that includes the
   name that could not be found.


.. exception:: NotImplementedError

   This exception is derived from :exc:`RuntimeError`.  In user defined base
   classes, abstract methods should raise this exception when they require derived
   classes to override the method.

   .. versionadded:: 1.5.2


.. exception:: OSError

   .. index:: module: errno

   This exception is derived from :exc:`EnvironmentError`.  It is raised when a
   function returns a system-related error (not for illegal argument types or
   other incidental errors).  The :attr:`errno` attribute is a numeric error
   code from :c:data:`errno`, and the :attr:`strerror` attribute is the
   corresponding string, as would be printed by the C function :c:func:`perror`.
   See the module :mod:`errno`, which contains names for the error codes defined
   by the underlying operating system.

   For exceptions that involve a file system path (such as :func:`chdir` or
   :func:`unlink`), the exception instance will contain a third attribute,
   :attr:`filename`, which is the file name passed to the function.

   .. versionadded:: 1.5.2


.. exception:: OverflowError

   Raised when the result of an arithmetic operation is too large to be
   represented.  This cannot occur for long integers (which would rather raise
   :exc:`MemoryError` than give up) and for most operations with plain integers,
   which return a long integer instead.  Because of the lack of standardization
   of floating point exception handling in C, most floating point operations
   also aren't checked.


.. exception:: ReferenceError

   This exception is raised when a weak reference proxy, created by the
   :func:`weakref.proxy` function, is used to access an attribute of the referent
   after it has been garbage collected. For more information on weak references,
   see the :mod:`weakref` module.

   .. versionadded:: 2.2
      Previously known as the :exc:`weakref.ReferenceError` exception.


.. exception:: RuntimeError

   Raised when an error is detected that doesn't fall in any of the other
   categories.  The associated value is a string indicating what precisely went
   wrong.


.. exception:: StopIteration

   Raised by an :term:`iterator`\'s :meth:`~iterator.next` method to signal that
   there are no further values.  This is derived from :exc:`Exception` rather
   than :exc:`StandardError`, since this is not considered an error in its
   normal application.

   .. versionadded:: 2.2


.. exception:: SyntaxError

   Raised when the parser encounters a syntax error.  This may occur in an
   :keyword:`import` statement, in an :keyword:`exec` statement, in a call to the
   built-in function :func:`eval` or :func:`input`, or when reading the initial
   script or standard input (also interactively).

   Instances of this class have attributes :attr:`filename`, :attr:`lineno`,
   :attr:`offset` and :attr:`text` for easier access to the details.  :func:`str`
   of the exception instance returns only the message.


.. exception:: IndentationError

   Base class for syntax errors related to incorrect indentation.  This is a
   subclass of :exc:`SyntaxError`.


.. exception:: TabError

   Raised when indentation contains an inconsistent use of tabs and spaces.
   This is a subclass of :exc:`IndentationError`.


.. exception:: SystemError

   Raised when the interpreter finds an internal error, but the situation does not
   look so serious to cause it to abandon all hope. The associated value is a
   string indicating what went wrong (in low-level terms).

   You should report this to the author or maintainer of your Python interpreter.
   Be sure to report the version of the Python interpreter (``sys.version``; it is
   also printed at the start of an interactive Python session), the exact error
   message (the exception's associated value) and if possible the source of the
   program that triggered the error.


.. exception:: SystemExit

   This exception is raised by the :func:`sys.exit` function.  When it is not
   handled, the Python interpreter exits; no stack traceback is printed.  If the
   associated value is a plain integer, it specifies the system exit status (passed
   to C's :c:func:`exit` function); if it is ``None``, the exit status is zero; if
   it has another type (such as a string), the object's value is printed and the
   exit status is one.

   Instances have an attribute :attr:`!code` which is set to the proposed exit
   status or error message (defaulting to ``None``). Also, this exception derives
   directly from :exc:`BaseException` and not :exc:`StandardError`, since it is not
   technically an error.

   A call to :func:`sys.exit` is translated into an exception so that clean-up
   handlers (:keyword:`finally` clauses of :keyword:`try` statements) can be
   executed, and so that a debugger can execute a script without running the risk
   of losing control.  The :func:`os._exit` function can be used if it is
   absolutely positively necessary to exit immediately (for example, in the child
   process after a call to :func:`os.fork`).

   The exception inherits from :exc:`BaseException` instead of :exc:`StandardError`
   or :exc:`Exception` so that it is not accidentally caught by code that catches
   :exc:`Exception`.  This allows the exception to properly propagate up and cause
   the interpreter to exit.

   .. versionchanged:: 2.5
      Changed to inherit from :exc:`BaseException`.


.. exception:: TypeError

   Raised when an operation or function is applied to an object of inappropriate
   type.  The associated value is a string giving details about the type mismatch.


.. exception:: UnboundLocalError

   Raised when a reference is made to a local variable in a function or method, but
   no value has been bound to that variable.  This is a subclass of
   :exc:`NameError`.

   .. versionadded:: 2.0


.. exception:: UnicodeError

   Raised when a Unicode-related encoding or decoding error occurs.  It is a
   subclass of :exc:`ValueError`.

   :exc:`UnicodeError` has attributes that describe the encoding or decoding
   error.  For example, ``err.object[err.start:err.end]`` gives the particular
   invalid input that the codec failed on.

   .. attribute:: encoding

       The name of the encoding that raised the error.

   .. attribute:: reason

       A string describing the specific codec error.

   .. attribute:: object

       The object the codec was attempting to encode or decode.

   .. attribute:: start

       The first index of invalid data in :attr:`object`.

   .. attribute:: end

       The index after the last invalid data in :attr:`object`.

   .. versionadded:: 2.0


.. exception:: UnicodeEncodeError

   Raised when a Unicode-related error occurs during encoding.  It is a subclass of
   :exc:`UnicodeError`.

   .. versionadded:: 2.3


.. exception:: UnicodeDecodeError

   Raised when a Unicode-related error occurs during decoding.  It is a subclass of
   :exc:`UnicodeError`.

   .. versionadded:: 2.3


.. exception:: UnicodeTranslateError

   Raised when a Unicode-related error occurs during translating.  It is a subclass
   of :exc:`UnicodeError`.

   .. versionadded:: 2.3


.. exception:: ValueError

   Raised when an operation or function receives an argument that has the
   right type but an inappropriate value, and the situation is not described by a
   more precise exception such as :exc:`IndexError`.


.. exception:: VMSError

   Only available on VMS.  Raised when a VMS-specific error occurs.


.. exception:: WindowsError

   Raised when a Windows-specific error occurs or when the error number does not
   correspond to an :c:data:`errno` value.  The :attr:`winerror` and
   :attr:`strerror` values are created from the return values of the
   :c:func:`GetLastError` and :c:func:`FormatMessage` functions from the Windows
   Platform API. The :attr:`errno` value maps the :attr:`winerror` value to
   corresponding ``errno.h`` values. This is a subclass of :exc:`OSError`.

   .. versionadded:: 2.0

   .. versionchanged:: 2.5
      Previous versions put the :c:func:`GetLastError` codes into :attr:`errno`.


.. exception:: ZeroDivisionError

   Raised when the second argument of a division or modulo operation is zero.  The
   associated value is a string indicating the type of the operands and the
   operation.

The following exceptions are used as warning categories; see the :mod:`warnings`
module for more information.


.. exception:: Warning

   Base class for warning categories.


.. exception:: UserWarning

   Base class for warnings generated by user code.


.. exception:: DeprecationWarning

   Base class for warnings about deprecated features.


.. exception:: PendingDeprecationWarning

   Base class for warnings about features which will be deprecated in the future.


.. exception:: SyntaxWarning

   Base class for warnings about dubious syntax.


.. exception:: RuntimeWarning

   Base class for warnings about dubious runtime behavior.


.. exception:: FutureWarning

   Base class for warnings about constructs that will change semantically in the
   future.


.. exception:: ImportWarning

   Base class for warnings about probable mistakes in module imports.

   .. versionadded:: 2.5


.. exception:: UnicodeWarning

   Base class for warnings related to Unicode.

   .. versionadded:: 2.5


Exception hierarchy
-------------------

The class hierarchy for built-in exceptions is:

.. literalinclude:: ../../Lib/test/exception_hierarchy.txt
PK	%�\iwlX��#html/_sources/library/fcntl.rst.txtnu�[���:mod:`fcntl` --- The ``fcntl`` and ``ioctl`` system calls
=========================================================

.. module:: fcntl
   :platform: Unix
   :synopsis: The fcntl() and ioctl() system calls.
.. sectionauthor:: Jaap Vermeulen


.. index::
   pair: UNIX; file control
   pair: UNIX; I/O control

This module performs file control and I/O control on file descriptors. It is an
interface to the :c:func:`fcntl` and :c:func:`ioctl` Unix routines.  For a
complete description of these calls, see :manpage:`fcntl(2)` and
:manpage:`ioctl(2)` Unix manual pages.

All functions in this module take a file descriptor *fd* as their first
argument.  This can be an integer file descriptor, such as returned by
``sys.stdin.fileno()``, or a file object, such as ``sys.stdin`` itself, which
provides a :meth:`~io.IOBase.fileno` which returns a genuine file descriptor.

The module defines the following functions:


.. function:: fcntl(fd, op[, arg])

   Perform the operation *op* on file descriptor *fd* (file objects providing
   a :meth:`~io.IOBase.fileno` method are accepted as well).  The values used
   for for *op* are operating system dependent, and are available as constants
   in the :mod:`fcntl` module, using the same names as used in the relevant C
   header files.  The argument *arg* is optional, and defaults to the integer
   value ``0``.  When present, it can either be an integer value, or a string.
   With the argument missing or an integer value, the return value of this function
   is the integer return value of the C :c:func:`fcntl` call.  When the argument is
   a string it represents a binary structure, e.g. created by :func:`struct.pack`.
   The binary data is copied to a buffer whose address is passed to the C
   :c:func:`fcntl` call.  The return value after a successful call is the contents
   of the buffer, converted to a string object.  The length of the returned string
   will be the same as the length of the *arg* argument.  This is limited to 1024
   bytes.  If the information returned in the buffer by the operating system is
   larger than 1024 bytes, this is most likely to result in a segmentation
   violation or a more subtle data corruption.

   If the :c:func:`fcntl` fails, an :exc:`IOError` is raised.


.. function:: ioctl(fd, op[, arg[, mutate_flag]])

   This function is identical to the :func:`~fcntl.fcntl` function, except that the
   operations are typically defined in the library module :mod:`termios` and the
   argument handling is even more complicated.

   The op parameter is limited to values that can fit in 32-bits.
   Additional constants of interest for use as the *op* argument can be
   found in the :mod:`termios` module, under the same names as used in
   the relevant C header files.

   The parameter *arg* can be one of an integer, absent (treated identically to the
   integer ``0``), an object supporting the read-only buffer interface (most likely
   a plain Python string) or an object supporting the read-write buffer interface.

   In all but the last case, behaviour is as for the :func:`~fcntl.fcntl`
   function.

   If a mutable buffer is passed, then the behaviour is determined by the value of
   the *mutate_flag* parameter.

   If it is false, the buffer's mutability is ignored and behaviour is as for a
   read-only buffer, except that the 1024 byte limit mentioned above is avoided --
   so long as the buffer you pass is as least as long as what the operating system
   wants to put there, things should work.

   If *mutate_flag* is true, then the buffer is (in effect) passed to the
   underlying :func:`ioctl` system call, the latter's return code is passed back to
   the calling Python, and the buffer's new contents reflect the action of the
   :func:`ioctl`.  This is a slight simplification, because if the supplied buffer
   is less than 1024 bytes long it is first copied into a static buffer 1024 bytes
   long which is then passed to :func:`ioctl` and copied back into the supplied
   buffer.

   If *mutate_flag* is not supplied, then from Python 2.5 it defaults to true,
   which is a change from versions 2.3 and 2.4. Supply the argument explicitly if
   version portability is a priority.

   If the :c:func:`ioctl` fails, an :exc:`IOError` exception is raised.

   An example::

      >>> import array, fcntl, struct, termios, os
      >>> os.getpgrp()
      13341
      >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, "  "))[0]
      13341
      >>> buf = array.array('h', [0])
      >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1)
      0
      >>> buf
      array('h', [13341])


.. function:: flock(fd, op)

   Perform the lock operation *op* on file descriptor *fd* (file objects providing
   a :meth:`~io.IOBase.fileno` method are accepted as well). See the Unix manual
   :manpage:`flock(2)` for details.  (On some systems, this function is emulated
   using :c:func:`fcntl`.)

   If the :c:func:`flock` fails, an :exc:`IOError` exception is raised.


.. function:: lockf(fd, operation, [length, [start, [whence]]])

   This is essentially a wrapper around the :func:`~fcntl.fcntl` locking calls.
   *fd* is the file descriptor of the file to lock or unlock, and *operation*
   is one of the following values:

   * :const:`LOCK_UN` -- unlock
   * :const:`LOCK_SH` -- acquire a shared lock
   * :const:`LOCK_EX` -- acquire an exclusive lock

   When *operation* is :const:`LOCK_SH` or :const:`LOCK_EX`, it can also be
   bitwise ORed with :const:`LOCK_NB` to avoid blocking on lock acquisition.
   If :const:`LOCK_NB` is used and the lock cannot be acquired, an
   :exc:`IOError` will be raised and the exception will have an *errno*
   attribute set to :const:`EACCES` or :const:`EAGAIN` (depending on the
   operating system; for portability, check for both values).  On at least some
   systems, :const:`LOCK_EX` can only be used if the file descriptor refers to a
   file opened for writing.

   *length* is the number of bytes to lock, *start* is the byte offset at
   which the lock starts, relative to *whence*, and *whence* is as with
   :func:`io.IOBase.seek`, specifically:

   * :const:`0` -- relative to the start of the file (:data:`os.SEEK_SET`)
   * :const:`1` -- relative to the current buffer position (:data:`os.SEEK_CUR`)
   * :const:`2` -- relative to the end of the file (:data:`os.SEEK_END`)

   The default for *start* is 0, which means to start at the beginning of the file.
   The default for *length* is 0 which means to lock to the end of the file.  The
   default for *whence* is also 0.

Examples (all on a SVR4 compliant system)::

   import struct, fcntl, os

   f = open(...)
   rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)

   lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
   rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)

Note that in the first example the return value variable *rv* will hold an
integer value; in the second example it will hold a string value.  The structure
lay-out for the *lockdata* variable is system dependent --- therefore using the
:func:`flock` call may be better.


.. seealso::

   Module :mod:`os`
      If the locking flags :data:`~os.O_SHLOCK` and :data:`~os.O_EXLOCK` are
      present in the :mod:`os` module (on BSD only), the :func:`os.open`
      function provides an alternative to the :func:`lockf` and :func:`flock`
      functions.

PK	%�\�^c��%html/_sources/library/filecmp.rst.txtnu�[���:mod:`filecmp` --- File and Directory Comparisons
=================================================

.. module:: filecmp
   :synopsis: Compare files efficiently.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

**Source code:** :source:`Lib/filecmp.py`

--------------

The :mod:`filecmp` module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the :mod:`difflib` module.

The :mod:`filecmp` module defines the following functions:


.. function:: cmp(f1, f2[, shallow])

   Compare the files named *f1* and *f2*, returning ``True`` if they seem equal,
   ``False`` otherwise.

   Unless *shallow* is given and is false, files with identical :func:`os.stat`
   signatures are taken to be equal.

   Files that were compared using this function will not be compared again unless
   their :func:`os.stat` signature changes.

   Note that no external programs are called from this function, giving it
   portability and efficiency.


.. function:: cmpfiles(dir1, dir2, common[, shallow])

   Compare the files in the two directories *dir1* and *dir2* whose names are
   given by *common*.

   Returns three lists of file names: *match*, *mismatch*,
   *errors*.  *match* contains the list of files that match, *mismatch* contains
   the names of those that don't, and *errors* lists the names of files which
   could not be compared.  Files are listed in *errors* if they don't exist in
   one of the directories, the user lacks permission to read them or if the
   comparison could not be done for some other reason.

   The *shallow* parameter has the same meaning and default value as for
   :func:`filecmp.cmp`.

   For example, ``cmpfiles('a', 'b', ['c', 'd/e'])`` will compare ``a/c`` with
   ``b/c`` and ``a/d/e`` with ``b/d/e``.  ``'c'`` and ``'d/e'`` will each be in
   one of the three returned lists.


Example::

   >>> import filecmp
   >>> filecmp.cmp('undoc.rst', 'undoc.rst') # doctest: +SKIP
   True
   >>> filecmp.cmp('undoc.rst', 'index.rst') # doctest: +SKIP
   False


.. _dircmp-objects:

The :class:`dircmp` class
-------------------------

:class:`dircmp` instances are built using this constructor:


.. class:: dircmp(a, b[, ignore[, hide]])

   Construct a new directory comparison object, to compare the directories *a* and
   *b*. *ignore* is a list of names to ignore, and defaults to ``['RCS', 'CVS',
   'tags']``. *hide* is a list of names to hide, and defaults to ``[os.curdir,
   os.pardir]``.

   The :class:`dircmp` class compares files by doing *shallow* comparisons
   as described for :func:`filecmp.cmp`.

   The :class:`dircmp` class provides the following methods:


   .. method:: report()

      Print (to ``sys.stdout``) a comparison between *a* and *b*.


   .. method:: report_partial_closure()

      Print a comparison between *a* and *b* and common immediate
      subdirectories.


   .. method:: report_full_closure()

      Print a comparison between *a* and *b* and common subdirectories
      (recursively).

   The :class:`dircmp` class offers a number of interesting attributes that may be
   used to get various bits of information about the directory trees being
   compared.

   Note that via :meth:`__getattr__` hooks, all attributes are computed lazily,
   so there is no speed penalty if only those attributes which are lightweight
   to compute are used.


   .. attribute:: left

      The directory *a*.


   .. attribute:: right

      The directory *b*.


   .. attribute:: left_list

      Files and subdirectories in *a*, filtered by *hide* and *ignore*.


   .. attribute:: right_list

      Files and subdirectories in *b*, filtered by *hide* and *ignore*.


   .. attribute:: common

      Files and subdirectories in both *a* and *b*.


   .. attribute:: left_only

      Files and subdirectories only in *a*.


   .. attribute:: right_only

      Files and subdirectories only in *b*.


   .. attribute:: common_dirs

      Subdirectories in both *a* and *b*.


   .. attribute:: common_files

      Files in both *a* and *b*


   .. attribute:: common_funny

      Names in both *a* and *b*, such that the type differs between the
      directories, or names for which :func:`os.stat` reports an error.


   .. attribute:: same_files

      Files which are identical in both *a* and *b*, using the class's
      file comparison operator.


   .. attribute:: diff_files

      Files which are in both *a* and *b*, whose contents differ according
      to the class's file comparison operator.


   .. attribute:: funny_files

      Files which are in both *a* and *b*, but could not be compared.


   .. attribute:: subdirs

      A dictionary mapping names in :attr:`common_dirs` to :class:`dircmp` objects.


Here is a simplified example of using the ``subdirs`` attribute to search
recursively through two directories to show common different files::

    >>> from filecmp import dircmp
    >>> def print_diff_files(dcmp):
    ...     for name in dcmp.diff_files:
    ...         print "diff_file %s found in %s and %s" % (name, dcmp.left,
    ...               dcmp.right)
    ...     for sub_dcmp in dcmp.subdirs.values():
    ...         print_diff_files(sub_dcmp)
    ...
    >>> dcmp = dircmp('dir1', 'dir2') # doctest: +SKIP
    >>> print_diff_files(dcmp) # doctest: +SKIP

PK	%�\���#..)html/_sources/library/fileformats.rst.txtnu�[���
.. _fileformats:

************
File Formats
************

The modules described in this chapter parse various miscellaneous file formats
that aren't markup languages or are related to e-mail.


.. toctree::

   csv.rst
   configparser.rst
   robotparser.rst
   netrc.rst
   xdrlib.rst
   plistlib.rst
PK	%�\2��%��'html/_sources/library/fileinput.rst.txtnu�[���:mod:`fileinput` --- Iterate over lines from multiple input streams
===================================================================

.. module:: fileinput
   :synopsis: Loop over standard input or a list of files.
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/fileinput.py`

--------------

This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read or
write one file see :func:`open`.

The typical use is::

   import fileinput
   for line in fileinput.input():
       process(line)

This iterates over the lines of all files listed in ``sys.argv[1:]``, defaulting
to ``sys.stdin`` if the list is empty.  If a filename is ``'-'``, it is also
replaced by ``sys.stdin``.  To specify an alternative list of filenames, pass it
as the first argument to :func:`.input`.  A single file name is also allowed.

All files are opened in text mode by default, but you can override this by
specifying the *mode* parameter in the call to :func:`.input` or
:class:`FileInput()`.  If an I/O error occurs during opening or reading a file,
:exc:`IOError` is raised.

If ``sys.stdin`` is used more than once, the second and further use will return
no lines, except perhaps for interactive use, or if it has been explicitly reset
(e.g. using ``sys.stdin.seek(0)``).

Empty files are opened and immediately closed; the only time their presence in
the list of filenames is noticeable at all is when the last file opened is
empty.

Lines are returned with any newlines intact, which means that the last line in
a file may not have one.

You can control how files are opened by providing an opening hook via the
*openhook* parameter to :func:`fileinput.input` or :class:`FileInput()`. The
hook must be a function that takes two arguments, *filename* and *mode*, and
returns an accordingly opened file-like object. Two useful hooks are already
provided by this module.

The following function is the primary interface of this module:


.. function:: input([files[, inplace[, backup[, bufsize[, mode[, openhook]]]]]])

   Create an instance of the :class:`FileInput` class.  The instance will be used
   as global state for the functions of this module, and is also returned to use
   during iteration.  The parameters to this function will be passed along to the
   constructor of the :class:`FileInput` class.

   .. versionchanged:: 2.5
      Added the *mode* and *openhook* parameters.

   .. versionchanged:: 2.7.12
      The *bufsize* parameter is no longer used.

The following functions use the global state created by :func:`fileinput.input`;
if there is no active state, :exc:`RuntimeError` is raised.


.. function:: filename()

   Return the name of the file currently being read.  Before the first line has
   been read, returns ``None``.


.. function:: fileno()

   Return the integer "file descriptor" for the current file. When no file is
   opened (before the first line and between files), returns ``-1``.

   .. versionadded:: 2.5


.. function:: lineno()

   Return the cumulative line number of the line that has just been read.  Before
   the first line has been read, returns ``0``.  After the last line of the last
   file has been read, returns the line number of that line.


.. function:: filelineno()

   Return the line number in the current file.  Before the first line has been
   read, returns ``0``.  After the last line of the last file has been read,
   returns the line number of that line within the file.


.. function:: isfirstline()

   Returns true if the line just read is the first line of its file, otherwise
   returns false.


.. function:: isstdin()

   Returns true if the last line was read from ``sys.stdin``, otherwise returns
   false.


.. function:: nextfile()

   Close the current file so that the next iteration will read the first line from
   the next file (if any); lines not read from the file will not count towards the
   cumulative line count.  The filename is not changed until after the first line
   of the next file has been read.  Before the first line has been read, this
   function has no effect; it cannot be used to skip the first file.  After the
   last line of the last file has been read, this function has no effect.


.. function:: close()

   Close the sequence.

The class which implements the sequence behavior provided by the module is
available for subclassing as well:


.. class:: FileInput([files[, inplace[, backup[,bufsize[, mode[, openhook]]]]]])

   Class :class:`FileInput` is the implementation; its methods :meth:`filename`,
   :meth:`fileno`, :meth:`lineno`, :meth:`filelineno`, :meth:`isfirstline`,
   :meth:`isstdin`, :meth:`nextfile` and :meth:`close` correspond to the
   functions of the same name in the module. In addition it has a
   :meth:`~file.readline` method which returns the next input line,
   and a :meth:`__getitem__` method which implements the sequence behavior.
   The sequence must be accessed in strictly sequential order; random access
   and :meth:`~file.readline` cannot be mixed.

   With *mode* you can specify which file mode will be passed to :func:`open`. It
   must be one of ``'r'``, ``'rU'``, ``'U'`` and ``'rb'``.

   The *openhook*, when given, must be a function that takes two arguments,
   *filename* and *mode*, and returns an accordingly opened file-like object. You
   cannot use *inplace* and *openhook* together.

   .. versionchanged:: 2.5
      Added the *mode* and *openhook* parameters.

   .. versionchanged:: 2.7.12
      The *bufsize* parameter is no longer used.

**Optional in-place filtering:** if the keyword argument ``inplace=1`` is passed
to :func:`fileinput.input` or to the :class:`FileInput` constructor, the file is
moved to a backup file and standard output is directed to the input file (if a
file of the same name as the backup file already exists, it will be replaced
silently).  This makes it possible to write a filter that rewrites its input
file in place.  If the *backup* parameter is given (typically as
``backup='.<some extension>'``), it specifies the extension for the backup file,
and the backup file remains around; by default, the extension is ``'.bak'`` and
it is deleted when the output file is closed.  In-place filtering is disabled
when standard input is read.

.. note::

   The current implementation does not work for MS-DOS 8+3 filesystems.


The two following opening hooks are provided by this module:

.. function:: hook_compressed(filename, mode)

   Transparently opens files compressed with gzip and bzip2 (recognized by the
   extensions ``'.gz'`` and ``'.bz2'``) using the :mod:`gzip` and :mod:`bz2`
   modules.  If the filename extension is not ``'.gz'`` or ``'.bz2'``, the file is
   opened normally (ie, using :func:`open` without any decompression).

   Usage example:  ``fi = fileinput.FileInput(openhook=fileinput.hook_compressed)``

   .. versionadded:: 2.5


.. function:: hook_encoded(encoding)

   Returns a hook which opens each file with :func:`io.open`, using the given
   *encoding* to read the file.

   Usage example: ``fi =
   fileinput.FileInput(openhook=fileinput.hook_encoded("iso-8859-1"))``

   .. note::

      With this hook, :class:`FileInput` might return Unicode strings depending on the
      specified *encoding*.

   .. versionadded:: 2.5

PK	%�\��&&%html/_sources/library/filesys.rst.txtnu�[���
.. _filesys:

*************************
File and Directory Access
*************************

The modules described in this chapter deal with disk files and directories.  For
example, there are modules for reading the properties of files, manipulating
paths in a portable way, and creating temporary files.  The full list of modules
in this chapter is:


.. toctree::

   os.path.rst
   fileinput.rst
   stat.rst
   statvfs.rst
   filecmp.rst
   tempfile.rst
   glob.rst
   fnmatch.rst
   linecache.rst
   shutil.rst
   dircache.rst
   macpath.rst


.. seealso::

   Section :ref:`bltin-file-objects`
      A description of Python's built-in file objects.

   Module :mod:`os`
      Operating system interfaces, including functions to work with files at a lower
      level than the built-in file object.

PK	%�\����D�D html/_sources/library/fl.rst.txtnu�[���
:mod:`fl` --- FORMS library for graphical user interfaces
=========================================================

.. module:: fl
   :platform: IRIX
   :synopsis: FORMS library for applications with graphical user interfaces.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`fl` module has been removed in Python 3.


.. index::
   single: FORMS Library
   single: Overmars, Mark

This module provides an interface to the FORMS Library by Mark Overmars.  The
source for the library can be retrieved by anonymous FTP from host
``ftp.cs.ruu.nl``, directory :file:`SGI/FORMS`.  It was last tested with version
2.0b.

Most functions are literal translations of their C equivalents, dropping the
initial ``fl_`` from their name.  Constants used by the library are defined in
module :mod:`FL` described below.

The creation of objects is a little different in Python than in C: instead of
the 'current form' maintained by the library to which new FORMS objects are
added, all functions that add a FORMS object to a form are methods of the Python
object representing the form. Consequently, there are no Python equivalents for
the C functions :c:func:`fl_addto_form` and :c:func:`fl_end_form`, and the
equivalent of :c:func:`fl_bgn_form` is called :func:`fl.make_form`.

Watch out for the somewhat confusing terminology: FORMS uses the word
:dfn:`object` for the buttons, sliders etc. that you can place in a form. In
Python, 'object' means any value.  The Python interface to FORMS introduces two
new Python object types: form objects (representing an entire form) and FORMS
objects (representing one button, slider etc.). Hopefully this isn't too
confusing.

There are no 'free objects' in the Python interface to FORMS, nor is there an
easy way to add object classes written in Python.  The FORMS interface to GL
event handling is available, though, so you can mix FORMS with pure GL windows.

**Please note:** importing :mod:`fl` implies a call to the GL function
:c:func:`foreground` and to the FORMS routine :c:func:`fl_init`.


.. _fl-functions:

Functions Defined in Module :mod:`fl`
-------------------------------------

Module :mod:`fl` defines the following functions.  For more information about
what they do, see the description of the equivalent C function in the FORMS
documentation:


.. function:: make_form(type, width, height)

   Create a form with given type, width and height.  This returns a :dfn:`form`
   object, whose methods are described below.


.. function:: do_forms()

   The standard FORMS main loop.  Returns a Python object representing the FORMS
   object needing interaction, or the special value :const:`FL.EVENT`.


.. function:: check_forms()

   Check for FORMS events.  Returns what :func:`do_forms` above returns, or
   ``None`` if there is no event that immediately needs interaction.


.. function:: set_event_call_back(function)

   Set the event callback function.


.. function:: set_graphics_mode(rgbmode, doublebuffering)

   Set the graphics modes.


.. function:: get_rgbmode()

   Return the current rgb mode.  This is the value of the C global variable
   :c:data:`fl_rgbmode`.


.. function:: show_message(str1, str2, str3)

   Show a dialog box with a three-line message and an OK button.


.. function:: show_question(str1, str2, str3)

   Show a dialog box with a three-line message and YES and NO buttons. It returns
   ``1`` if the user pressed YES, ``0`` if NO.


.. function:: show_choice(str1, str2, str3, but1[, but2[, but3]])

   Show a dialog box with a three-line message and up to three buttons. It returns
   the number of the button clicked by the user (``1``, ``2`` or ``3``).


.. function:: show_input(prompt, default)

   Show a dialog box with a one-line prompt message and text field in which the
   user can enter a string.  The second argument is the default input string.  It
   returns the string value as edited by the user.


.. function:: show_file_selector(message, directory, pattern, default)

   Show a dialog box in which the user can select a file.  It returns the absolute
   filename selected by the user, or ``None`` if the user presses Cancel.


.. function:: get_directory()
              get_pattern()
              get_filename()

   These functions return the directory, pattern and filename (the tail part only)
   selected by the user in the last :func:`show_file_selector` call.


.. function:: qdevice(dev)
              unqdevice(dev)
              isqueued(dev)
              qtest()
              qread()
              qreset()
              qenter(dev, val)
              get_mouse()
              tie(button, valuator1, valuator2)

   These functions are the FORMS interfaces to the corresponding GL functions.  Use
   these if you want to handle some GL events yourself when using
   :func:`fl.do_events`.  When a GL event is detected that FORMS cannot handle,
   :func:`fl.do_forms` returns the special value :const:`FL.EVENT` and you should
   call :func:`fl.qread` to read the event from the queue.  Don't use the
   equivalent GL functions!

   .. \funcline{blkqread}{?}


.. function:: color()
              mapcolor()
              getmcolor()

   See the description in the FORMS documentation of :c:func:`fl_color`,
   :c:func:`fl_mapcolor` and :c:func:`fl_getmcolor`.


.. _form-objects:

Form Objects
------------

Form objects (returned by :func:`make_form` above) have the following methods.
Each method corresponds to a C function whose name is prefixed with ``fl_``; and
whose first argument is a form pointer; please refer to the official FORMS
documentation for descriptions.

All the :meth:`add_\*` methods return a Python object representing the FORMS
object.  Methods of FORMS objects are described below.  Most kinds of FORMS
object also have some methods specific to that kind; these methods are listed
here.


.. method:: form.show_form(placement, bordertype, name)

   Show the form.


.. method:: form.hide_form()

   Hide the form.


.. method:: form.redraw_form()

   Redraw the form.


.. method:: form.set_form_position(x, y)

   Set the form's position.


.. method:: form.freeze_form()

   Freeze the form.


.. method:: form.unfreeze_form()

   Unfreeze the form.


.. method:: form.activate_form()

   Activate the form.


.. method:: form.deactivate_form()

   Deactivate the form.


.. method:: form.bgn_group()

   Begin a new group of objects; return a group object.


.. method:: form.end_group()

   End the current group of objects.


.. method:: form.find_first()

   Find the first object in the form.


.. method:: form.find_last()

   Find the last object in the form.


.. method:: form.add_box(type, x, y, w, h, name)

   Add a box object to the form. No extra methods.


.. method:: form.add_text(type, x, y, w, h, name)

   Add a text object to the form. No extra methods.

.. \begin{methoddesc}[form]{add_bitmap}{type, x, y, w, h, name}
.. Add a bitmap object to the form.
.. \end{methoddesc}


.. method:: form.add_clock(type, x, y, w, h, name)

   Add a clock object to the form.  ---  Method: :meth:`get_clock`.


.. method:: form.add_button(type, x, y, w, h,  name)

   Add a button object to the form.  ---  Methods: :meth:`get_button`,
   :meth:`set_button`.


.. method:: form.add_lightbutton(type, x, y, w, h, name)

   Add a lightbutton object to the form.  ---  Methods: :meth:`get_button`,
   :meth:`set_button`.


.. method:: form.add_roundbutton(type, x, y, w, h, name)

   Add a roundbutton object to the form.  ---  Methods: :meth:`get_button`,
   :meth:`set_button`.


.. method:: form.add_slider(type, x, y, w, h, name)

   Add a slider object to the form.  ---  Methods: :meth:`set_slider_value`,
   :meth:`get_slider_value`, :meth:`set_slider_bounds`, :meth:`get_slider_bounds`,
   :meth:`set_slider_return`, :meth:`set_slider_size`,
   :meth:`set_slider_precision`, :meth:`set_slider_step`.


.. method:: form.add_valslider(type, x, y, w, h, name)

   Add a valslider object to the form.  ---  Methods: :meth:`set_slider_value`,
   :meth:`get_slider_value`, :meth:`set_slider_bounds`, :meth:`get_slider_bounds`,
   :meth:`set_slider_return`, :meth:`set_slider_size`,
   :meth:`set_slider_precision`, :meth:`set_slider_step`.


.. method:: form.add_dial(type, x, y, w, h, name)

   Add a dial object to the form.  ---  Methods: :meth:`set_dial_value`,
   :meth:`get_dial_value`, :meth:`set_dial_bounds`, :meth:`get_dial_bounds`.


.. method:: form.add_positioner(type, x, y, w, h, name)

   Add a positioner object to the form.  ---  Methods:
   :meth:`set_positioner_xvalue`, :meth:`set_positioner_yvalue`,
   :meth:`set_positioner_xbounds`, :meth:`set_positioner_ybounds`,
   :meth:`get_positioner_xvalue`, :meth:`get_positioner_yvalue`,
   :meth:`get_positioner_xbounds`, :meth:`get_positioner_ybounds`.


.. method:: form.add_counter(type, x, y, w, h, name)

   Add a counter object to the form.  ---  Methods: :meth:`set_counter_value`,
   :meth:`get_counter_value`, :meth:`set_counter_bounds`, :meth:`set_counter_step`,
   :meth:`set_counter_precision`, :meth:`set_counter_return`.


.. method:: form.add_input(type, x, y, w, h, name)

   Add an input object to the form.  ---  Methods: :meth:`set_input`,
   :meth:`get_input`, :meth:`set_input_color`, :meth:`set_input_return`.


.. method:: form.add_menu(type, x, y, w, h, name)

   Add a menu object to the form.  ---  Methods: :meth:`set_menu`,
   :meth:`get_menu`, :meth:`addto_menu`.


.. method:: form.add_choice(type, x, y, w, h, name)

   Add a choice object to the form.  ---  Methods: :meth:`set_choice`,
   :meth:`get_choice`, :meth:`clear_choice`, :meth:`addto_choice`,
   :meth:`replace_choice`, :meth:`delete_choice`, :meth:`get_choice_text`,
   :meth:`set_choice_fontsize`, :meth:`set_choice_fontstyle`.


.. method:: form.add_browser(type, x, y, w, h, name)

   Add a browser object to the form.  ---  Methods: :meth:`set_browser_topline`,
   :meth:`clear_browser`, :meth:`add_browser_line`, :meth:`addto_browser`,
   :meth:`insert_browser_line`, :meth:`delete_browser_line`,
   :meth:`replace_browser_line`, :meth:`get_browser_line`, :meth:`load_browser`,
   :meth:`get_browser_maxline`, :meth:`select_browser_line`,
   :meth:`deselect_browser_line`, :meth:`deselect_browser`,
   :meth:`isselected_browser_line`, :meth:`get_browser`,
   :meth:`set_browser_fontsize`, :meth:`set_browser_fontstyle`,
   :meth:`set_browser_specialkey`.


.. method:: form.add_timer(type, x, y, w, h, name)

   Add a timer object to the form.  ---  Methods: :meth:`set_timer`,
   :meth:`get_timer`.

Form objects have the following data attributes; see the FORMS documentation:

+---------------------+-----------------+--------------------------------+
| Name                | C Type          | Meaning                        |
+=====================+=================+================================+
| :attr:`window`      | int (read-only) | GL window id                   |
+---------------------+-----------------+--------------------------------+
| :attr:`w`           | float           | form width                     |
+---------------------+-----------------+--------------------------------+
| :attr:`h`           | float           | form height                    |
+---------------------+-----------------+--------------------------------+
| :attr:`x`           | float           | form x origin                  |
+---------------------+-----------------+--------------------------------+
| :attr:`y`           | float           | form y origin                  |
+---------------------+-----------------+--------------------------------+
| :attr:`deactivated` | int             | nonzero if form is deactivated |
+---------------------+-----------------+--------------------------------+
| :attr:`visible`     | int             | nonzero if form is visible     |
+---------------------+-----------------+--------------------------------+
| :attr:`frozen`      | int             | nonzero if form is frozen      |
+---------------------+-----------------+--------------------------------+
| :attr:`doublebuf`   | int             | nonzero if double buffering on |
+---------------------+-----------------+--------------------------------+


.. _forms-objects:

FORMS Objects
-------------

Besides methods specific to particular kinds of FORMS objects, all FORMS objects
also have the following methods:


.. method:: FORMS object.set_call_back(function, argument)

   Set the object's callback function and argument.  When the object needs
   interaction, the callback function will be called with two arguments: the
   object, and the callback argument.  (FORMS objects without a callback function
   are returned by :func:`fl.do_forms` or :func:`fl.check_forms` when they need
   interaction.)  Call this method without arguments to remove the callback
   function.


.. method:: FORMS object.delete_object()

   Delete the object.


.. method:: FORMS object.show_object()

   Show the object.


.. method:: FORMS object.hide_object()

   Hide the object.


.. method:: FORMS object.redraw_object()

   Redraw the object.


.. method:: FORMS object.freeze_object()

   Freeze the object.


.. method:: FORMS object.unfreeze_object()

   Unfreeze the object.

FORMS objects have these data attributes; see the FORMS documentation:

.. \begin{methoddesc}[FORMS object]{handle_object}{} XXX
.. \end{methoddesc}
.. \begin{methoddesc}[FORMS object]{handle_object_direct}{} XXX
.. \end{methoddesc}

+--------------------+-----------------+------------------+
| Name               | C Type          | Meaning          |
+====================+=================+==================+
| :attr:`objclass`   | int (read-only) | object class     |
+--------------------+-----------------+------------------+
| :attr:`type`       | int (read-only) | object type      |
+--------------------+-----------------+------------------+
| :attr:`boxtype`    | int             | box type         |
+--------------------+-----------------+------------------+
| :attr:`x`          | float           | x origin         |
+--------------------+-----------------+------------------+
| :attr:`y`          | float           | y origin         |
+--------------------+-----------------+------------------+
| :attr:`w`          | float           | width            |
+--------------------+-----------------+------------------+
| :attr:`h`          | float           | height           |
+--------------------+-----------------+------------------+
| :attr:`col1`       | int             | primary color    |
+--------------------+-----------------+------------------+
| :attr:`col2`       | int             | secondary color  |
+--------------------+-----------------+------------------+
| :attr:`align`      | int             | alignment        |
+--------------------+-----------------+------------------+
| :attr:`lcol`       | int             | label color      |
+--------------------+-----------------+------------------+
| :attr:`lsize`      | float           | label font size  |
+--------------------+-----------------+------------------+
| :attr:`label`      | string          | label string     |
+--------------------+-----------------+------------------+
| :attr:`lstyle`     | int             | label style      |
+--------------------+-----------------+------------------+
| :attr:`pushed`     | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`focus`      | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`belowmouse` | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`frozen`     | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`active`     | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`input`      | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`visible`    | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`radio`      | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+
| :attr:`automatic`  | int (read-only) | (see FORMS docs) |
+--------------------+-----------------+------------------+


:mod:`FL` --- Constants used with the :mod:`fl` module
======================================================

.. module:: FL
   :platform: IRIX
   :synopsis: Constants used with the fl module.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`FL` module has been removed in Python 3.


This module defines symbolic constants needed to use the built-in module
:mod:`fl` (see above); they are equivalent to those defined in the C header file
``<forms.h>`` except that the name prefix ``FL_`` is omitted.  Read the module
source for a complete list of the defined names.  Suggested use::

   import fl
   from FL import *


:mod:`flp` --- Functions for loading stored FORMS designs
=========================================================

.. module:: flp
   :platform: IRIX
   :synopsis: Functions for loading stored FORMS designs.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`flp` module has been removed in Python 3.


This module defines functions that can read form definitions created by the
'form designer' (:program:`fdesign`) program that comes with the FORMS library
(see module :mod:`fl` above).

For now, see the file :file:`flp.doc` in the Python library source directory for
a description.

XXX A complete description should be inserted here!

PK	%�\5�:�
�
 html/_sources/library/fm.rst.txtnu�[���
:mod:`fm` --- *Font Manager* interface
======================================

.. module:: fm
   :platform: IRIX
   :synopsis: Font Manager interface for SGI workstations.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`fm` module has been removed in Python 3.



.. index::
   single: Font Manager, IRIS
   single: IRIS Font Manager

This module provides access to the IRIS *Font Manager* library.   It is
available only on Silicon Graphics machines. See also: *4Sight User's Guide*,
section 1, chapter 5: "Using the IRIS Font Manager."

This is not yet a full interface to the IRIS Font Manager. Among the unsupported
features are: matrix operations; cache operations; character operations (use
string operations instead); some details of font info; individual glyph metrics;
and printer matching.

It supports the following operations:


.. function:: init()

   Initialization function. Calls :c:func:`fminit`. It is normally not necessary to
   call this function, since it is called automatically the first time the
   :mod:`fm` module is imported.


.. function:: findfont(fontname)

   Return a font handle object. Calls ``fmfindfont(fontname)``.


.. function:: enumerate()

   Returns a list of available font names. This is an interface to
   :c:func:`fmenumerate`.


.. function:: prstr(string)

   Render a string using the current font (see the :func:`setfont` font handle
   method below). Calls ``fmprstr(string)``.


.. function:: setpath(string)

   Sets the font search path. Calls ``fmsetpath(string)``. (XXX Does not work!?!)


.. function:: fontpath()

   Returns the current font search path.

Font handle objects support the following operations:


.. method:: font handle.scalefont(factor)

   Returns a handle for a scaled version of this font. Calls ``fmscalefont(fh,
   factor)``.


.. method:: font handle.setfont()

   Makes this font the current font. Note: the effect is undone silently when the
   font handle object is deleted. Calls ``fmsetfont(fh)``.


.. method:: font handle.getfontname()

   Returns this font's name. Calls ``fmgetfontname(fh)``.


.. method:: font handle.getcomment()

   Returns the comment string associated with this font. Raises an exception if
   there is none. Calls ``fmgetcomment(fh)``.


.. method:: font handle.getfontinfo()

   Returns a tuple giving some pertinent data about this font. This is an interface
   to ``fmgetfontinfo()``. The returned tuple contains the following numbers:
   ``(printermatched, fixed_width, xorig, yorig, xsize, ysize, height, nglyphs)``.


.. method:: font handle.getstrwidth(string)

   Returns the width, in pixels, of *string* when drawn in this font. Calls
   ``fmgetstrwidth(fh, string)``.

PK	%�\�"6j  %html/_sources/library/fnmatch.rst.txtnu�[���:mod:`fnmatch` --- Unix filename pattern matching
=================================================

.. module:: fnmatch
   :synopsis: Unix shell style filename pattern matching.


.. index:: single: filenames; wildcard expansion

.. index:: module: re

**Source code:** :source:`Lib/fnmatch.py`

--------------

This module provides support for Unix shell-style wildcards, which are *not* the
same as regular expressions (which are documented in the :mod:`re` module).  The
special characters used in shell-style wildcards are:

+------------+------------------------------------+
| Pattern    | Meaning                            |
+============+====================================+
| ``*``      | matches everything                 |
+------------+------------------------------------+
| ``?``      | matches any single character       |
+------------+------------------------------------+
| ``[seq]``  | matches any character in *seq*     |
+------------+------------------------------------+
| ``[!seq]`` | matches any character not in *seq* |
+------------+------------------------------------+

For a literal match, wrap the meta-characters in brackets.
For example, ``'[?]'`` matches the character ``'?'``.

.. index:: module: glob

Note that the filename separator (``'/'`` on Unix) is *not* special to this
module.  See module :mod:`glob` for pathname expansion (:mod:`glob` uses
:func:`.filter` to match pathname segments).  Similarly, filenames starting with
a period are not special for this module, and are matched by the ``*`` and ``?``
patterns.


.. function:: fnmatch(filename, pattern)

   Test whether the *filename* string matches the *pattern* string, returning
   :const:`True` or :const:`False`.  Both parameters are case-normalized
   using :func:`os.path.normcase`. :func:`fnmatchcase` can be used to perform a
   case-sensitive comparison, regardless of whether that's standard for the
   operating system.

   This example will print all file names in the current directory with the
   extension ``.txt``::

      import fnmatch
      import os

      for file in os.listdir('.'):
          if fnmatch.fnmatch(file, '*.txt'):
              print file


.. function:: fnmatchcase(filename, pattern)

   Test whether *filename* matches *pattern*, returning :const:`True` or
   :const:`False`; the comparison is case-sensitive and does not apply
   :func:`os.path.normcase`.


.. function:: filter(names, pattern)

   Return the subset of the list of *names* that match *pattern*. It is the same as
   ``[n for n in names if fnmatch(n, pattern)]``, but implemented more efficiently.

   .. versionadded:: 2.2


.. function:: translate(pattern)

   Return the shell-style *pattern* converted to a regular expression for
   using with :func:`re.match`.

   Example:

      >>> import fnmatch, re
      >>>
      >>> regex = fnmatch.translate('*.txt')
      >>> regex
      '.*\\.txt\\Z(?ms)'
      >>> reobj = re.compile(regex)
      >>> reobj.match('foobar.txt')
      <_sre.SRE_Match object at 0x...>


.. seealso::

   Module :mod:`glob`
      Unix shell-style path expansion.
PK	%�\�Y�ս3�3'html/_sources/library/formatter.rst.txtnu�[���
:mod:`formatter` --- Generic output formatting
==============================================

.. module:: formatter
   :synopsis: Generic output formatter and device interface.


.. index:: single: HTMLParser (class in htmllib)

This module supports two interface definitions, each with multiple
implementations.  The *formatter* interface is used by the :class:`~HTMLParser.HTMLParser`
class of the :mod:`htmllib` module, and the *writer* interface is required by
the formatter interface.

Formatter objects transform an abstract flow of formatting events into specific
output events on writer objects.  Formatters manage several stack structures to
allow various properties of a writer object to be changed and restored; writers
need not be able to handle relative changes nor any sort of "change back"
operation.  Specific writer properties which may be controlled via formatter
objects are horizontal alignment, font, and left margin indentations.  A
mechanism is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well.  Additional interfaces facilitate formatting
events which are not reversible, such as paragraph separation.

Writer objects encapsulate device interfaces.  Abstract devices, such as file
formats, are supported as well as physical devices.  The provided
implementations all work with abstract devices.  The interface makes available
mechanisms for setting the properties which formatter objects manage and
inserting data into the output.


.. _formatter-interface:

The Formatter Interface
-----------------------

Interfaces to create formatters are dependent on the specific formatter class
being instantiated.  The interfaces described below are the required interfaces
which all formatters must support once initialized.

One data element is defined at the module level:


.. data:: AS_IS

   Value which can be used in the font specification passed to the ``push_font()``
   method described below, or as the new value to any other ``push_property()``
   method.  Pushing the ``AS_IS`` value allows the corresponding ``pop_property()``
   method to be called without having to track whether the property was changed.

The following attributes are defined for formatter instance objects:


.. attribute:: formatter.writer

   The writer instance with which the formatter interacts.


.. method:: formatter.end_paragraph(blanklines)

   Close any open paragraphs and insert at least *blanklines* before the next
   paragraph.


.. method:: formatter.add_line_break()

   Add a hard line break if one does not already exist.  This does not break the
   logical paragraph.


.. method:: formatter.add_hor_rule(*args, **kw)

   Insert a horizontal rule in the output.  A hard break is inserted if there is
   data in the current paragraph, but the logical paragraph is not broken.  The
   arguments and keywords are passed on to the writer's :meth:`send_line_break`
   method.


.. method:: formatter.add_flowing_data(data)

   Provide data which should be formatted with collapsed whitespace. Whitespace
   from preceding and successive calls to :meth:`add_flowing_data` is considered as
   well when the whitespace collapse is performed.  The data which is passed to
   this method is expected to be word-wrapped by the output device.  Note that any
   word-wrapping still must be performed by the writer object due to the need to
   rely on device and font information.


.. method:: formatter.add_literal_data(data)

   Provide data which should be passed to the writer unchanged. Whitespace,
   including newline and tab characters, are considered legal in the value of
   *data*.


.. method:: formatter.add_label_data(format, counter)

   Insert a label which should be placed to the left of the current left margin.
   This should be used for constructing bulleted or numbered lists.  If the
   *format* value is a string, it is interpreted as a format specification for
   *counter*, which should be an integer. The result of this formatting becomes the
   value of the label; if *format* is not a string it is used as the label value
   directly. The label value is passed as the only argument to the writer's
   :meth:`send_label_data` method.  Interpretation of non-string label values is
   dependent on the associated writer.

   Format specifications are strings which, in combination with a counter value,
   are used to compute label values.  Each character in the format string is copied
   to the label value, with some characters recognized to indicate a transform on
   the counter value.  Specifically, the character ``'1'`` represents the counter
   value formatter as an Arabic number, the characters ``'A'`` and ``'a'``
   represent alphabetic representations of the counter value in upper and lower
   case, respectively, and ``'I'`` and ``'i'`` represent the counter value in Roman
   numerals, in upper and lower case.  Note that the alphabetic and roman
   transforms require that the counter value be greater than zero.


.. method:: formatter.flush_softspace()

   Send any pending whitespace buffered from a previous call to
   :meth:`add_flowing_data` to the associated writer object.  This should be called
   before any direct manipulation of the writer object.


.. method:: formatter.push_alignment(align)

   Push a new alignment setting onto the alignment stack.  This may be
   :const:`AS_IS` if no change is desired.  If the alignment value is changed from
   the previous setting, the writer's :meth:`new_alignment` method is called with
   the *align* value.


.. method:: formatter.pop_alignment()

   Restore the previous alignment.


.. method:: formatter.push_font((size, italic, bold, teletype))

   Change some or all font properties of the writer object.  Properties which are
   not set to :const:`AS_IS` are set to the values passed in while others are
   maintained at their current settings.  The writer's :meth:`new_font` method is
   called with the fully resolved font specification.


.. method:: formatter.pop_font()

   Restore the previous font.


.. method:: formatter.push_margin(margin)

   Increase the number of left margin indentations by one, associating the logical
   tag *margin* with the new indentation.  The initial margin level is ``0``.
   Changed values of the logical tag must be true values; false values other than
   :const:`AS_IS` are not sufficient to change the margin.


.. method:: formatter.pop_margin()

   Restore the previous margin.


.. method:: formatter.push_style(*styles)

   Push any number of arbitrary style specifications.  All styles are pushed onto
   the styles stack in order.  A tuple representing the entire stack, including
   :const:`AS_IS` values, is passed to the writer's :meth:`new_styles` method.


.. method:: formatter.pop_style([n=1])

   Pop the last *n* style specifications passed to :meth:`push_style`.  A tuple
   representing the revised stack, including :const:`AS_IS` values, is passed to
   the writer's :meth:`new_styles` method.


.. method:: formatter.set_spacing(spacing)

   Set the spacing style for the writer.


.. method:: formatter.assert_line_data([flag=1])

   Inform the formatter that data has been added to the current paragraph
   out-of-band.  This should be used when the writer has been manipulated
   directly.  The optional *flag* argument can be set to false if the writer
   manipulations produced a hard line break at the end of the output.


.. _formatter-impls:

Formatter Implementations
-------------------------

Two implementations of formatter objects are provided by this module. Most
applications may use one of these classes without modification or subclassing.


.. class:: NullFormatter([writer])

   A formatter which does nothing.  If *writer* is omitted, a :class:`NullWriter`
   instance is created.  No methods of the writer are called by
   :class:`NullFormatter` instances.  Implementations should inherit from this
   class if implementing a writer interface but don't need to inherit any
   implementation.


.. class:: AbstractFormatter(writer)

   The standard formatter.  This implementation has demonstrated wide applicability
   to many writers, and may be used directly in most circumstances.  It has been
   used to implement a full-featured World Wide Web browser.


.. _writer-interface:

The Writer Interface
--------------------

Interfaces to create writers are dependent on the specific writer class being
instantiated.  The interfaces described below are the required interfaces which
all writers must support once initialized. Note that while most applications can
use the :class:`AbstractFormatter` class as a formatter, the writer must
typically be provided by the application.


.. method:: writer.flush()

   Flush any buffered output or device control events.


.. method:: writer.new_alignment(align)

   Set the alignment style.  The *align* value can be any object, but by convention
   is a string or ``None``, where ``None`` indicates that the writer's "preferred"
   alignment should be used. Conventional *align* values are ``'left'``,
   ``'center'``, ``'right'``, and ``'justify'``.


.. method:: writer.new_font(font)

   Set the font style.  The value of *font* will be ``None``, indicating that the
   device's default font should be used, or a tuple of the form ``(size,
   italic, bold, teletype)``.  Size will be a string indicating the size of
   font that should be used; specific strings and their interpretation must be
   defined by the application.  The *italic*, *bold*, and *teletype* values are
   Boolean values specifying which of those font attributes should be used.


.. method:: writer.new_margin(margin, level)

   Set the margin level to the integer *level* and the logical tag to *margin*.
   Interpretation of the logical tag is at the writer's discretion; the only
   restriction on the value of the logical tag is that it not be a false value for
   non-zero values of *level*.


.. method:: writer.new_spacing(spacing)

   Set the spacing style to *spacing*.


.. method:: writer.new_styles(styles)

   Set additional styles.  The *styles* value is a tuple of arbitrary values; the
   value :const:`AS_IS` should be ignored.  The *styles* tuple may be interpreted
   either as a set or as a stack depending on the requirements of the application
   and writer implementation.


.. method:: writer.send_line_break()

   Break the current line.


.. method:: writer.send_paragraph(blankline)

   Produce a paragraph separation of at least *blankline* blank lines, or the
   equivalent.  The *blankline* value will be an integer.  Note that the
   implementation will receive a call to :meth:`send_line_break` before this call
   if a line break is needed;  this method should not include ending the last line
   of the paragraph. It is only responsible for vertical spacing between
   paragraphs.


.. method:: writer.send_hor_rule(*args, **kw)

   Display a horizontal rule on the output device.  The arguments to this method
   are entirely application- and writer-specific, and should be interpreted with
   care.  The method implementation may assume that a line break has already been
   issued via :meth:`send_line_break`.


.. method:: writer.send_flowing_data(data)

   Output character data which may be word-wrapped and re-flowed as needed.  Within
   any sequence of calls to this method, the writer may assume that spans of
   multiple whitespace characters have been collapsed to single space characters.


.. method:: writer.send_literal_data(data)

   Output character data which has already been formatted for display.  Generally,
   this should be interpreted to mean that line breaks indicated by newline
   characters should be preserved and no new line breaks should be introduced.  The
   data may contain embedded newline and tab characters, unlike data provided to
   the :meth:`send_formatted_data` interface.


.. method:: writer.send_label_data(data)

   Set *data* to the left of the current left margin, if possible. The value of
   *data* is not restricted; treatment of non-string values is entirely
   application- and writer-dependent.  This method will only be called at the
   beginning of a line.


.. _writer-impls:

Writer Implementations
----------------------

Three implementations of the writer object interface are provided as examples by
this module.  Most applications will need to derive new writer classes from the
:class:`NullWriter` class.


.. class:: NullWriter()

   A writer which only provides the interface definition; no actions are taken on
   any methods.  This should be the base class for all writers which do not need to
   inherit any implementation methods.


.. class:: AbstractWriter()

   A writer which can be used in debugging formatters, but not much else.  Each
   method simply announces itself by printing its name and arguments on standard
   output.


.. class:: DumbWriter(file=None, maxcol=72)

   Simple writer class which writes output on the file object passed in as *file*
   or, if *file* is ``None``, on standard output.  The output is simply word-wrapped
   to the number of columns specified by *maxcol*.  This class is suitable for
   reflowing a sequence of paragraphs.

PK	%�\�EKK$html/_sources/library/fpectl.rst.txtnu�[���
:mod:`fpectl` --- Floating point exception control
==================================================

.. module:: fpectl
   :platform: Unix
   :synopsis: Provide control for floating point exception handling.
.. moduleauthor:: Lee Busby <busby1@llnl.gov>
.. sectionauthor:: Lee Busby <busby1@llnl.gov>


.. note::

   The :mod:`fpectl` module is not built by default, and its usage is discouraged
   and may be dangerous except in the hands of experts.  See also the section
   :ref:`fpectl-limitations` on limitations for more details.

.. index:: single: IEEE-754

Most computers carry out floating point operations in conformance with the
so-called IEEE-754 standard. On any real computer, some floating point
operations produce results that cannot be expressed as a normal floating point
value. For example, try ::

   >>> import math
   >>> math.exp(1000)
   inf
   >>> math.exp(1000) / math.exp(1000)
   nan

(The example above will work on many platforms. DEC Alpha may be one exception.)
"Inf" is a special, non-numeric value in IEEE-754 that stands for "infinity",
and "nan" means "not a number." Note that, other than the non-numeric results,
nothing special happened when you asked Python to carry out those calculations.
That is in fact the default behaviour prescribed in the IEEE-754 standard, and
if it works for you, stop reading now.

In some circumstances, it would be better to raise an exception and stop
processing at the point where the faulty operation was attempted. The
:mod:`fpectl` module is for use in that situation. It provides control over
floating point units from several hardware manufacturers, allowing the user to
turn on the generation of :const:`SIGFPE` whenever any of the IEEE-754
exceptions Division by Zero, Overflow, or Invalid Operation occurs. In tandem
with a pair of wrapper macros that are inserted into the C code comprising your
python system, :const:`SIGFPE` is trapped and converted into the Python
:exc:`FloatingPointError` exception.

The :mod:`fpectl` module defines the following functions and may raise the given
exception:


.. function:: turnon_sigfpe()

   Turn on the generation of :const:`SIGFPE`, and set up an appropriate signal
   handler.


.. function:: turnoff_sigfpe()

   Reset default handling of floating point exceptions.


.. exception:: FloatingPointError

   After :func:`turnon_sigfpe` has been executed, a floating point operation that
   raises one of the IEEE-754 exceptions Division by Zero, Overflow, or Invalid
   operation will in turn raise this standard Python exception.


.. _fpectl-example:

Example
-------

The following example demonstrates how to start up and test operation of the
:mod:`fpectl` module. ::

   >>> import fpectl
   >>> import fpetest
   >>> fpectl.turnon_sigfpe()
   >>> fpetest.test()
   overflow        PASS
   FloatingPointError: Overflow

   div by 0        PASS
   FloatingPointError: Division by zero
     [ more output from test elided ]
   >>> import math
   >>> math.exp(1000)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   FloatingPointError: in math_1


.. _fpectl-limitations:

Limitations and other considerations
------------------------------------

Setting up a given processor to trap IEEE-754 floating point errors currently
requires custom code on a per-architecture basis. You may have to modify
:mod:`fpectl` to control your particular hardware.

Conversion of an IEEE-754 exception to a Python exception requires that the
wrapper macros ``PyFPE_START_PROTECT`` and ``PyFPE_END_PROTECT`` be inserted
into your code in an appropriate fashion.  Python itself has been modified to
support the :mod:`fpectl` module, but many other codes of interest to numerical
analysts have not.

The :mod:`fpectl` module is not thread-safe.


.. seealso::

   Some files in the source distribution may be interesting in learning more about
   how this module operates. The include file :source:`Include/pyfpe.h` discusses the
   implementation of this module at some length. :source:`Modules/fpetestmodule.c`
   gives several examples of use. Many additional examples can be found in
   :source:`Objects/floatobject.c`.

PK	%�\@
���&html/_sources/library/fpformat.rst.txtnu�[���
:mod:`fpformat` --- Floating point conversions
==============================================

.. module:: fpformat
   :synopsis: General floating point formatting functions.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`fpformat` module has been removed in Python 3.

.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`fpformat` module defines functions for dealing with floating point
numbers representations in 100% pure Python.

.. note::

   This module is unnecessary: everything here can be done using the ``%`` string
   interpolation operator described in the :ref:`string-formatting` section.

The :mod:`fpformat` module defines the following functions and an exception:


.. function:: fix(x, digs)

   Format *x* as ``[-]ddd.ddd`` with *digs* digits after the point and at least one
   digit before. If ``digs <= 0``, the decimal point is suppressed.

   *x* can be either a number or a string that looks like one. *digs* is an
   integer.

   Return value is a string.


.. function:: sci(x, digs)

   Format *x* as ``[-]d.dddE[+-]ddd`` with *digs* digits after the  point and
   exactly one digit before. If ``digs <= 0``, one digit is kept and the point is
   suppressed.

   *x* can be either a real number, or a string that looks like one. *digs* is an
   integer.

   Return value is a string.


.. exception:: NotANumber

   Exception raised when a string passed to :func:`fix` or :func:`sci` as the *x*
   parameter does not look like a number. This is a subclass of :exc:`ValueError`
   when the standard exceptions are strings.  The exception value is the improperly
   formatted string that caused the exception to be raised.

Example::

   >>> import fpformat
   >>> fpformat.fix(1.23, 1)
   '1.2'

PK	%�\^�ұ�'html/_sources/library/fractions.rst.txtnu�[���:mod:`fractions` --- Rational numbers
=====================================

.. module:: fractions
   :synopsis: Rational numbers.
.. moduleauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
.. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
.. versionadded:: 2.6

**Source code:** :source:`Lib/fractions.py`

--------------

The :mod:`fractions` module provides support for rational number arithmetic.


A Fraction instance can be constructed from a pair of integers, from
another rational number, or from a string.

.. class:: Fraction(numerator=0, denominator=1)
           Fraction(other_fraction)
           Fraction(float)
           Fraction(decimal)
           Fraction(string)

   The first version requires that *numerator* and *denominator* are instances
   of :class:`numbers.Rational` and returns a new :class:`Fraction` instance
   with value ``numerator/denominator``. If *denominator* is :const:`0`, it
   raises a :exc:`ZeroDivisionError`. The second version requires that
   *other_fraction* is an instance of :class:`numbers.Rational` and returns a
   :class:`Fraction` instance with the same value.  The next two versions accept
   either a :class:`float` or a :class:`decimal.Decimal` instance, and return a
   :class:`Fraction` instance with exactly the same value.  Note that due to the
   usual issues with binary floating-point (see :ref:`tut-fp-issues`), the
   argument to ``Fraction(1.1)`` is not exactly equal to 11/10, and so
   ``Fraction(1.1)`` does *not* return ``Fraction(11, 10)`` as one might expect.
   (But see the documentation for the :meth:`limit_denominator` method below.)
   The last version of the constructor expects a string or unicode instance.
   The usual form for this instance is::

      [sign] numerator ['/' denominator]

   where the optional ``sign`` may be either '+' or '-' and
   ``numerator`` and ``denominator`` (if present) are strings of
   decimal digits.  In addition, any string that represents a finite
   value and is accepted by the :class:`float` constructor is also
   accepted by the :class:`Fraction` constructor.  In either form the
   input string may also have leading and/or trailing whitespace.
   Here are some examples::

      >>> from fractions import Fraction
      >>> Fraction(16, -10)
      Fraction(-8, 5)
      >>> Fraction(123)
      Fraction(123, 1)
      >>> Fraction()
      Fraction(0, 1)
      >>> Fraction('3/7')
      Fraction(3, 7)
      >>> Fraction(' -3/7 ')
      Fraction(-3, 7)
      >>> Fraction('1.414213 \t\n')
      Fraction(1414213, 1000000)
      >>> Fraction('-.125')
      Fraction(-1, 8)
      >>> Fraction('7e-6')
      Fraction(7, 1000000)
      >>> Fraction(2.25)
      Fraction(9, 4)
      >>> Fraction(1.1)
      Fraction(2476979795053773, 2251799813685248)
      >>> from decimal import Decimal
      >>> Fraction(Decimal('1.1'))
      Fraction(11, 10)


   The :class:`Fraction` class inherits from the abstract base class
   :class:`numbers.Rational`, and implements all of the methods and
   operations from that class.  :class:`Fraction` instances are hashable,
   and should be treated as immutable.  In addition,
   :class:`Fraction` has the following methods:

   .. versionchanged:: 2.7
      The :class:`Fraction` constructor now accepts :class:`float` and
      :class:`decimal.Decimal` instances.


   .. method:: from_float(flt)

      This class method constructs a :class:`Fraction` representing the exact
      value of *flt*, which must be a :class:`float`. Beware that
      ``Fraction.from_float(0.3)`` is not the same value as ``Fraction(3, 10)``.

      .. note:: From Python 2.7 onwards, you can also construct a
         :class:`Fraction` instance directly from a :class:`float`.


   .. method:: from_decimal(dec)

      This class method constructs a :class:`Fraction` representing the exact
      value of *dec*, which must be a :class:`decimal.Decimal`.

      .. note:: From Python 2.7 onwards, you can also construct a
         :class:`Fraction` instance directly from a :class:`decimal.Decimal`
         instance.


   .. method:: limit_denominator(max_denominator=1000000)

      Finds and returns the closest :class:`Fraction` to ``self`` that has
      denominator at most max_denominator.  This method is useful for finding
      rational approximations to a given floating-point number:

         >>> from fractions import Fraction
         >>> Fraction('3.1415926535897932').limit_denominator(1000)
         Fraction(355, 113)

      or for recovering a rational number that's represented as a float:

         >>> from math import pi, cos
         >>> Fraction(cos(pi/3))
         Fraction(4503599627370497, 9007199254740992)
         >>> Fraction(cos(pi/3)).limit_denominator()
         Fraction(1, 2)
         >>> Fraction(1.1).limit_denominator()
         Fraction(11, 10)


.. function:: gcd(a, b)

   Return the greatest common divisor of the integers *a* and *b*.  If either
   *a* or *b* is nonzero, then the absolute value of ``gcd(a, b)`` is the
   largest integer that divides both *a* and *b*.  ``gcd(a,b)`` has the same
   sign as *b* if *b* is nonzero; otherwise it takes the sign of *a*.  ``gcd(0,
   0)`` returns ``0``.


.. seealso::

   Module :mod:`numbers`
      The abstract base classes making up the numeric tower.
PK	%�\w�O��,�,'html/_sources/library/framework.rst.txtnu�[���
:mod:`FrameWork` --- Interactive application framework
======================================================

.. module:: FrameWork
   :platform: Mac
   :synopsis: Interactive application framework.
   :deprecated:


The :mod:`FrameWork` module contains classes that together provide a framework
for an interactive Macintosh application. The programmer builds an application
by creating subclasses that override various methods of the bases classes,
thereby implementing the functionality wanted. Overriding functionality can
often be done on various different levels, i.e. to handle clicks in a single
dialog window in a non-standard way it is not necessary to override the complete
event handling.

.. note::

   This module has been removed in Python 3.x.

Work on the :mod:`FrameWork` has pretty much stopped, now that :mod:`PyObjC` is
available for full Cocoa access from Python, and the documentation describes
only the most important functionality, and not in the most logical manner at
that. Examine the source or the examples for more details.  The following are
some comments posted on the MacPython newsgroup about the strengths and
limitations of :mod:`FrameWork`:


.. epigraph::

   The strong point of :mod:`FrameWork` is that it allows you to break into the
   control-flow at many different places. :mod:`W`, for instance, uses a different
   way to enable/disable menus and that plugs right in leaving the rest intact.
   The weak points of :mod:`FrameWork` are that it has no abstract command
   interface (but that shouldn't be difficult), that its dialog support is minimal
   and that its control/toolbar support is non-existent.

The :mod:`FrameWork` module defines the following functions:


.. function:: Application()

   An object representing the complete application. See below for a description of
   the methods. The default :meth:`__init__` routine creates an empty window
   dictionary and a menu bar with an apple menu.


.. function:: MenuBar()

   An object representing the menubar. This object is usually not created by the
   user.


.. function:: Menu(bar, title[, after])

   An object representing a menu. Upon creation you pass the ``MenuBar`` the menu
   appears in, the *title* string and a position (1-based) *after* where the menu
   should appear (default: at the end).


.. function:: MenuItem(menu, title[, shortcut, callback])

   Create a menu item object. The arguments are the menu to create, the item title
   string and optionally the keyboard shortcut and a callback routine. The callback
   is called with the arguments menu-id, item number within menu (1-based), current
   front window and the event record.

   Instead of a callable object the callback can also be a string. In this case
   menu selection causes the lookup of a method in the topmost window and the
   application. The method name is the callback string with ``'domenu_'``
   prepended.

   Calling the ``MenuBar`` :meth:`fixmenudimstate` method sets the correct dimming
   for all menu items based on the current front window.


.. function:: Separator(menu)

   Add a separator to the end of a menu.


.. function:: SubMenu(menu, label)

   Create a submenu named *label* under menu *menu*. The menu object is returned.


.. function:: Window(parent)

   Creates a (modeless) window. *Parent* is the application object to which the
   window belongs. The window is not displayed until later.


.. function:: DialogWindow(parent)

   Creates a modeless dialog window.


.. function:: windowbounds(width, height)

   Return a ``(left, top, right, bottom)`` tuple suitable for creation of a window
   of given width and height. The window will be staggered with respect to previous
   windows, and an attempt is made to keep the whole window on-screen. However, the
   window will however always be the exact size given, so parts may be offscreen.


.. function:: setwatchcursor()

   Set the mouse cursor to a watch.


.. function:: setarrowcursor()

   Set the mouse cursor to an arrow.


.. _application-objects:

Application Objects
-------------------

Application objects have the following methods, among others:


.. method:: Application.makeusermenus()

   Override this method if you need menus in your application. Append the menus to
   the attribute :attr:`menubar`.


.. method:: Application.getabouttext()

   Override this method to return a text string describing your application.
   Alternatively, override the :meth:`do_about` method for more elaborate "about"
   messages.


.. method:: Application.mainloop([mask[, wait]])

   This routine is the main event loop, call it to set your application rolling.
   *Mask* is the mask of events you want to handle, *wait* is the number of ticks
   you want to leave to other concurrent application (default 0, which is probably
   not a good idea). While raising *self* to exit the mainloop is still supported
   it is not recommended: call ``self._quit()`` instead.

   The event loop is split into many small parts, each of which can be overridden.
   The default methods take care of dispatching events to windows and dialogs,
   handling drags and resizes, Apple Events, events for non-FrameWork windows, etc.

   In general, all event handlers should return ``1`` if the event is fully handled
   and ``0`` otherwise (because the front window was not a FrameWork window, for
   instance). This is needed so that update events and such can be passed on to
   other windows like the Sioux console window. Calling :func:`MacOS.HandleEvent`
   is not allowed within *our_dispatch* or its callees, since this may result in an
   infinite loop if the code is called through the Python inner-loop event handler.


.. method:: Application.asyncevents(onoff)

   Call this method with a nonzero parameter to enable asynchronous event handling.
   This will tell the inner interpreter loop to call the application event handler
   *async_dispatch* whenever events are available. This will cause FrameWork window
   updates and the user interface to remain working during long computations, but
   will slow the interpreter down and may cause surprising results in non-reentrant
   code (such as FrameWork itself). By default *async_dispatch* will immediately
   call *our_dispatch* but you may override this to handle only certain events
   asynchronously. Events you do not handle will be passed to Sioux and such.

   The old on/off value is returned.


.. method:: Application._quit()

   Terminate the running :meth:`mainloop` call at the next convenient moment.


.. method:: Application.do_char(c, event)

   The user typed character *c*. The complete details of the event can be found in
   the *event* structure. This method can also be provided in a ``Window`` object,
   which overrides the application-wide handler if the window is frontmost.


.. method:: Application.do_dialogevent(event)

   Called early in the event loop to handle modeless dialog events. The default
   method simply dispatches the event to the relevant dialog (not through the
   ``DialogWindow`` object involved). Override if you need special handling of
   dialog events (keyboard shortcuts, etc).


.. method:: Application.idle(event)

   Called by the main event loop when no events are available. The null-event is
   passed (so you can look at mouse position, etc).


.. _window-objects:

Window Objects
--------------

Window objects have the following methods, among others:


.. method:: Window.open()

   Override this method to open a window. Store the Mac OS window-id in
   :attr:`self.wid` and call the :meth:`do_postopen` method to register the window
   with the parent application.


.. method:: Window.close()

   Override this method to do any special processing on window close. Call the
   :meth:`do_postclose` method to cleanup the parent state.


.. method:: Window.do_postresize(width, height, macoswindowid)

   Called after the window is resized. Override if more needs to be done than
   calling ``InvalRect``.


.. method:: Window.do_contentclick(local, modifiers, event)

   The user clicked in the content part of a window. The arguments are the
   coordinates (window-relative), the key modifiers and the raw event.


.. method:: Window.do_update(macoswindowid, event)

   An update event for the window was received. Redraw the window.


.. method:: Window.do_activate(activate, event)

   The window was activated (``activate == 1``) or deactivated (``activate == 0``).
   Handle things like focus highlighting, etc.


.. _controlswindow-object:

ControlsWindow Object
---------------------

ControlsWindow objects have the following methods besides those of ``Window``
objects:


.. method:: ControlsWindow.do_controlhit(window, control, pcode, event)

   Part *pcode* of control *control* was hit by the user. Tracking and such has
   already been taken care of.


.. _scrolledwindow-object:

ScrolledWindow Object
---------------------

ScrolledWindow objects are ControlsWindow objects with the following extra
methods:


.. method:: ScrolledWindow.scrollbars([wantx[, wanty]])

   Create (or destroy) horizontal and vertical scrollbars. The arguments specify
   which you want (default: both). The scrollbars always have minimum ``0`` and
   maximum ``32767``.


.. method:: ScrolledWindow.getscrollbarvalues()

   You must supply this method. It should return a tuple ``(x, y)`` giving the
   current position of the scrollbars (between ``0`` and ``32767``). You can return
   ``None`` for either to indicate the whole document is visible in that direction.


.. method:: ScrolledWindow.updatescrollbars()

   Call this method when the document has changed. It will call
   :meth:`getscrollbarvalues` and update the scrollbars.


.. method:: ScrolledWindow.scrollbar_callback(which, what, value)

   Supplied by you and called after user interaction. *which* will be ``'x'`` or
   ``'y'``, *what* will be ``'-'``, ``'--'``, ``'set'``, ``'++'`` or ``'+'``. For
   ``'set'``, *value* will contain the new scrollbar position.


.. method:: ScrolledWindow.scalebarvalues(absmin, absmax, curmin, curmax)

   Auxiliary method to help you calculate values to return from
   :meth:`getscrollbarvalues`. You pass document minimum and maximum value and
   topmost (leftmost) and bottommost (rightmost) visible values and it returns the
   correct number or ``None``.


.. method:: ScrolledWindow.do_activate(onoff, event)

   Takes care of dimming/highlighting scrollbars when a window becomes frontmost.
   If you override this method, call this one at the end of your method.


.. method:: ScrolledWindow.do_postresize(width, height, window)

   Moves scrollbars to the correct position. Call this method initially if you
   override it.


.. method:: ScrolledWindow.do_controlhit(window, control, pcode, event)

   Handles scrollbar interaction. If you override it call this method first, a
   nonzero return value indicates the hit was in the scrollbars and has been
   handled.


.. _dialogwindow-objects:

DialogWindow Objects
--------------------

DialogWindow objects have the following methods besides those of ``Window``
objects:


.. method:: DialogWindow.open(resid)

   Create the dialog window, from the DLOG resource with id *resid*. The dialog
   object is stored in :attr:`self.wid`.


.. method:: DialogWindow.do_itemhit(item, event)

   Item number *item* was hit. You are responsible for redrawing toggle buttons,
   etc.

PK	%�\n�szz(html/_sources/library/frameworks.rst.txtnu�[���
.. _frameworks:

******************
Program Frameworks
******************

The modules described in this chapter are frameworks that will largely dictate
the structure of your program.  Currently the modules described  here are all
oriented toward writing command-line interfaces.

The full list of modules described in this chapter is:


.. toctree::

   cmd.rst
   shlex.rst
PK	%�\��h=h=$html/_sources/library/ftplib.rst.txtnu�[���:mod:`ftplib` --- FTP protocol client
=====================================

.. module:: ftplib
   :synopsis: FTP protocol client (requires sockets).


.. index::
   pair: FTP; protocol
   single: FTP; ftplib (standard module)

**Source code:** :source:`Lib/ftplib.py`

--------------

This module defines the class :class:`FTP` and a few related items. The
:class:`FTP` class implements the client side of the FTP protocol.  You can use
this to write Python programs that perform a variety of automated FTP jobs, such
as mirroring other FTP servers.  It is also used by the module :mod:`urllib` to
handle URLs that use FTP.  For more information on FTP (File Transfer Protocol),
see Internet :rfc:`959`.

Here's a sample session using the :mod:`ftplib` module::

   >>> from ftplib import FTP
   >>> ftp = FTP('ftp.debian.org')     # connect to host, default port
   >>> ftp.login()                     # user anonymous, passwd anonymous@
   '230 Login successful.'
   >>> ftp.cwd('debian')               # change into "debian" directory
   >>> ftp.retrlines('LIST')           # list directory contents
   -rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README
   ...
   drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool
   drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project
   drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools
   '226 Directory send OK.'
   >>> ftp.retrbinary('RETR README', open('README', 'wb').write)
   '226 Transfer complete.'
   >>> ftp.quit()


The module defines the following items:

.. class:: FTP([host[, user[, passwd[, acct[, timeout]]]]])

   Return a new instance of the :class:`FTP` class.  When *host* is given, the
   method call ``connect(host)`` is made.  When *user* is given, additionally
   the method call ``login(user, passwd, acct)`` is made (where *passwd* and
   *acct* default to the empty string when not given).  The optional *timeout*
   parameter specifies a timeout in seconds for blocking operations like the
   connection attempt (if is not specified, the global default timeout setting
   will be used).

   .. versionchanged:: 2.6
      *timeout* was added.


.. class:: FTP_TLS([host[, user[, passwd[, acct[, keyfile[, certfile[, context[, timeout]]]]]]]])

   A :class:`FTP` subclass which adds TLS support to FTP as described in
   :rfc:`4217`.
   Connect as usual to port 21 implicitly securing the FTP control connection
   before authenticating. Securing the data connection requires the user to
   explicitly ask for it by calling the :meth:`prot_p` method.  *context*
   is a :class:`ssl.SSLContext` object which allows bundling SSL configuration
   options, certificates and private keys into a single (potentially
   long-lived) structure.  Please read :ref:`ssl-security` for best practices.

   *keyfile* and *certfile* are a legacy alternative to *context* -- they
   can point to PEM-formatted private key and certificate chain files
   (respectively) for the SSL connection.

   .. versionadded:: 2.7

   .. versionchanged:: 2.7.10
      The *context* parameter was added.

   Here's a sample session using the :class:`FTP_TLS` class:

   >>> from ftplib import FTP_TLS
   >>> ftps = FTP_TLS('ftp.python.org')
   >>> ftps.login()           # login anonymously before securing control channel
   >>> ftps.prot_p()          # switch to secure data connection
   >>> ftps.retrlines('LIST') # list directory content securely
   total 9
   drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .
   drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..
   drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin
   drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc
   d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming
   drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib
   drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub
   drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr
   -rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg
   '226 Transfer complete.'
   >>> ftps.quit()
   >>>


.. exception:: error_reply

   Exception raised when an unexpected reply is received from the server.


.. exception:: error_temp

   Exception raised when an error code signifying a temporary error (response
   codes in the range 400--499) is received.


.. exception:: error_perm

   Exception raised when an error code signifying a permanent error (response
   codes in the range 500--599) is received.


.. exception:: error_proto

   Exception raised when a reply is received from the server that does not fit
   the response specifications of the File Transfer Protocol, i.e. begin with a
   digit in the range 1--5.


.. data:: all_errors

   The set of all exceptions (as a tuple) that methods of :class:`FTP`
   instances may raise as a result of problems with the FTP connection (as
   opposed to programming errors made by the caller).  This set includes the
   four exceptions listed above as well as :exc:`socket.error` and
   :exc:`IOError`.


.. seealso::

   Module :mod:`netrc`
      Parser for the :file:`.netrc` file format.  The file :file:`.netrc` is
      typically used by FTP clients to load user authentication information
      before prompting the user.

   .. index:: single: ftpmirror.py

   The file :file:`Tools/scripts/ftpmirror.py` in the Python source distribution is
   a script that can mirror FTP sites, or portions thereof, using the :mod:`ftplib`
   module. It can be used as an extended example that applies this module.


.. _ftp-objects:

FTP Objects
-----------

Several methods are available in two flavors: one for handling text files and
another for binary files.  These are named for the command which is used
followed by ``lines`` for the text version or ``binary`` for the binary version.

:class:`FTP` instances have the following methods:


.. method:: FTP.set_debuglevel(level)

   Set the instance's debugging level.  This controls the amount of debugging
   output printed.  The default, ``0``, produces no debugging output.  A value of
   ``1`` produces a moderate amount of debugging output, generally a single line
   per request.  A value of ``2`` or higher produces the maximum amount of
   debugging output, logging each line sent and received on the control connection.


.. method:: FTP.connect(host[, port[, timeout]])

   Connect to the given host and port.  The default port number is ``21``, as
   specified by the FTP protocol specification.  It is rarely needed to specify a
   different port number.  This function should be called only once for each
   instance; it should not be called at all if a host was given when the instance
   was created.  All other methods can only be used after a connection has been
   made.

   The optional *timeout* parameter specifies a timeout in seconds for the
   connection attempt. If no *timeout* is passed, the global default timeout
   setting will be used.

   .. versionchanged:: 2.6
      *timeout* was added.


.. method:: FTP.getwelcome()

   Return the welcome message sent by the server in reply to the initial
   connection.  (This message sometimes contains disclaimers or help information
   that may be relevant to the user.)


.. method:: FTP.login([user[, passwd[, acct]]])

   Log in as the given *user*.  The *passwd* and *acct* parameters are optional and
   default to the empty string.  If no *user* is specified, it defaults to
   ``'anonymous'``.  If *user* is ``'anonymous'``, the default *passwd* is
   ``'anonymous@'``.  This function should be called only once for each instance,
   after a connection has been established; it should not be called at all if a
   host and user were given when the instance was created.  Most FTP commands are
   only allowed after the client has logged in.  The *acct* parameter supplies
   "accounting information"; few systems implement this.


.. method:: FTP.abort()

   Abort a file transfer that is in progress.  Using this does not always work, but
   it's worth a try.


.. method:: FTP.sendcmd(command)

   Send a simple command string to the server and return the response string.


.. method:: FTP.voidcmd(command)

   Send a simple command string to the server and handle the response.  Return
   nothing if a response code corresponding to success (codes in the range
   200--299) is received.  Raise :exc:`error_reply` otherwise.


.. method:: FTP.retrbinary(command, callback[, maxblocksize[, rest]])

   Retrieve a file in binary transfer mode.  *command* should be an appropriate
   ``RETR`` command: ``'RETR filename'``. The *callback* function is called for
   each block of data received, with a single string argument giving the data
   block. The optional *maxblocksize* argument specifies the maximum chunk size to
   read on the low-level socket object created to do the actual transfer (which
   will also be the largest size of the data blocks passed to *callback*).  A
   reasonable default is chosen. *rest* means the same thing as in the
   :meth:`transfercmd` method.


.. method:: FTP.retrlines(command[, callback])

   Retrieve a file or directory listing in ASCII transfer mode.  *command*
   should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or a
   command such as ``LIST``, ``NLST`` or ``MLSD`` (usually just the string
   ``'LIST'``).  ``LIST`` retrieves a list of files and information about those files.
   ``NLST`` retrieves a list of file names.  On some servers, ``MLSD`` retrieves
   a machine readable list of files and information about those files.  The *callback*
   function is called for each line with a string argument containing the line with
   the trailing CRLF stripped.  The default *callback* prints the line to ``sys.stdout``.


.. method:: FTP.set_pasv(val)

   Enable "passive" mode if *val* is true, otherwise disable passive mode.  (In
   Python 2.0 and before, passive mode was off by default; in Python 2.1 and later,
   it is on by default.)


.. method:: FTP.storbinary(command, fp[, blocksize, callback, rest])

   Store a file in binary transfer mode.  *command* should be an appropriate
   ``STOR`` command: ``"STOR filename"``. *fp* is an open file object which is
   read until EOF using its :meth:`read` method in blocks of size *blocksize* to
   provide the data to be stored.  The *blocksize* argument defaults to 8192.
   *callback* is an optional single parameter callable that is called
   on each block of data after it is sent. *rest* means the same thing as in
   the :meth:`transfercmd` method.

   .. versionchanged:: 2.1
      default for *blocksize* added.

   .. versionchanged:: 2.6
      *callback* parameter added.

   .. versionchanged:: 2.7
      *rest* parameter added.

.. method:: FTP.storlines(command, fp[, callback])

   Store a file in ASCII transfer mode.  *command* should be an appropriate
   ``STOR`` command (see :meth:`storbinary`).  Lines are read until EOF from the
   open file object *fp* using its :meth:`~file.readline` method to provide
   the data to be stored.  *callback* is an optional single parameter callable
   that is called on each line after it is sent.

   .. versionchanged:: 2.6
      *callback* parameter added.


.. method:: FTP.transfercmd(cmd[, rest])

   Initiate a transfer over the data connection.  If the transfer is active, send an
   ``EPRT`` or  ``PORT`` command and the transfer command specified by *cmd*, and
   accept the connection.  If the server is passive, send an ``EPSV`` or ``PASV``
   command, connect to it, and start the transfer command.  Either way, return the
   socket for the connection.

   If optional *rest* is given, a ``REST`` command is sent to the server, passing
   *rest* as an argument.  *rest* is usually a byte offset into the requested file,
   telling the server to restart sending the file's bytes at the requested offset,
   skipping over the initial bytes.  Note however that RFC 959 requires only that
   *rest* be a string containing characters in the printable range from ASCII code
   33 to ASCII code 126.  The :meth:`transfercmd` method, therefore, converts
   *rest* to a string, but no check is performed on the string's contents.  If the
   server does not recognize the ``REST`` command, an :exc:`error_reply` exception
   will be raised.  If this happens, simply call :meth:`transfercmd` without a
   *rest* argument.


.. method:: FTP.ntransfercmd(cmd[, rest])

   Like :meth:`transfercmd`, but returns a tuple of the data connection and the
   expected size of the data.  If the expected size could not be computed, ``None``
   will be returned as the expected size.  *cmd* and *rest* means the same thing as
   in :meth:`transfercmd`.


.. method:: FTP.nlst(argument[, ...])

   Return a list of file names as returned by the ``NLST`` command.  The
   optional *argument* is a directory to list (default is the current server
   directory).  Multiple arguments can be used to pass non-standard options to
   the ``NLST`` command.


.. method:: FTP.dir(argument[, ...])

   Produce a directory listing as returned by the ``LIST`` command, printing it to
   standard output.  The optional *argument* is a directory to list (default is the
   current server directory).  Multiple arguments can be used to pass non-standard
   options to the ``LIST`` command.  If the last argument is a function, it is used
   as a *callback* function as for :meth:`retrlines`; the default prints to
   ``sys.stdout``.  This method returns ``None``.


.. method:: FTP.rename(fromname, toname)

   Rename file *fromname* on the server to *toname*.


.. method:: FTP.delete(filename)

   Remove the file named *filename* from the server.  If successful, returns the
   text of the response, otherwise raises :exc:`error_perm` on permission errors or
   :exc:`error_reply` on other errors.


.. method:: FTP.cwd(pathname)

   Set the current directory on the server.


.. method:: FTP.mkd(pathname)

   Create a new directory on the server.


.. method:: FTP.pwd()

   Return the pathname of the current directory on the server.


.. method:: FTP.rmd(dirname)

   Remove the directory named *dirname* on the server.


.. method:: FTP.size(filename)

   Request the size of the file named *filename* on the server.  On success, the
   size of the file is returned as an integer, otherwise ``None`` is returned.
   Note that the ``SIZE`` command is not  standardized, but is supported by many
   common server implementations.


.. method:: FTP.quit()

   Send a ``QUIT`` command to the server and close the connection. This is the
   "polite" way to close a connection, but it may raise an exception if the server
   responds with an error to the ``QUIT`` command.  This implies a call to the
   :meth:`close` method which renders the :class:`FTP` instance useless for
   subsequent calls (see below).


.. method:: FTP.close()

   Close the connection unilaterally.  This should not be applied to an already
   closed connection such as after a successful call to :meth:`~FTP.quit`.
   After this call the :class:`FTP` instance should not be used any more (after
   a call to :meth:`close` or :meth:`~FTP.quit` you cannot reopen the
   connection by issuing another :meth:`login` method).


FTP_TLS Objects
---------------

:class:`FTP_TLS` class inherits from :class:`FTP`, defining these additional objects:

.. attribute:: FTP_TLS.ssl_version

   The SSL version to use (defaults to :attr:`ssl.PROTOCOL_SSLv23`).

.. method:: FTP_TLS.auth()

   Set up secure control connection by using TLS or SSL, depending on what
   specified in :meth:`ssl_version` attribute.

.. method:: FTP_TLS.prot_p()

   Set up secure data connection.

.. method:: FTP_TLS.prot_c()

   Set up clear text data connection.
PK	%�\��"'"''html/_sources/library/functions.rst.txtnu�[���
.. _built-in-funcs:

Built-in Functions
==================

The Python interpreter has a number of functions built into it that are always
available.  They are listed here in alphabetical order.

===================  =================  ==================  =================  ====================
..                   ..                 Built-in Functions  ..                 ..
===================  =================  ==================  =================  ====================
:func:`abs`          :func:`divmod`     :func:`input`       :func:`open`       :func:`staticmethod`
:func:`all`          :func:`enumerate`  :func:`int`         :func:`ord`        :func:`str`
:func:`any`          :func:`eval`       :func:`isinstance`  :func:`pow`        :func:`sum`
:func:`basestring`   :func:`execfile`   :func:`issubclass`  :func:`print`      :func:`super`
:func:`bin`          :func:`file`       :func:`iter`        :func:`property`   :func:`tuple`
:func:`bool`         :func:`filter`     :func:`len`         :func:`range`      :func:`type`
:func:`bytearray`    :func:`float`      |func-list|_        :func:`raw_input`  :func:`unichr`
:func:`callable`     :func:`format`     :func:`locals`      :func:`reduce`     :func:`unicode`
:func:`chr`          |func-frozenset|_  :func:`long`        :func:`reload`     :func:`vars`
:func:`classmethod`  :func:`getattr`    :func:`map`         |func-repr|_       :func:`xrange`
:func:`cmp`          :func:`globals`    :func:`max`         :func:`reversed`   :func:`zip`
:func:`compile`      :func:`hasattr`    |func-memoryview|_  :func:`round`      :func:`__import__`
:func:`complex`      :func:`hash`       :func:`min`         |func-set|_        ..
:func:`delattr`      :func:`help`       :func:`next`        :func:`setattr`    ..
|func-dict|_         :func:`hex`        :func:`object`      :func:`slice`      ..
:func:`dir`          :func:`id`         :func:`oct`         :func:`sorted`     ..
===================  =================  ==================  =================  ====================

In addition, there are other four built-in functions that are no longer
considered essential: :func:`apply`, :func:`buffer`, :func:`coerce`, and
:func:`intern`.  They are documented in the :ref:`non-essential-built-in-funcs`
section.

.. using :func:`dict` would create a link to another page, so local targets are
   used, with replacement texts to make the output in the table consistent

.. |func-dict| replace:: ``dict()``
.. |func-frozenset| replace:: ``frozenset()``
.. |func-list| replace:: ``list()``
.. |func-memoryview| replace:: ``memoryview()``
.. |func-repr| replace:: ``repr()``
.. |func-set| replace:: ``set()``


.. function:: abs(x)

   Return the absolute value of a number.  The argument may be a plain or long
   integer or a floating point number.  If the argument is a complex number, its
   magnitude is returned.


.. function:: all(iterable)

   Return ``True`` if all elements of the *iterable* are true (or if the iterable
   is empty).  Equivalent to::

      def all(iterable):
          for element in iterable:
              if not element:
                  return False
          return True

   .. versionadded:: 2.5


.. function:: any(iterable)

   Return ``True`` if any element of the *iterable* is true.  If the iterable
   is empty, return ``False``.  Equivalent to::

      def any(iterable):
          for element in iterable:
              if element:
                  return True
          return False

   .. versionadded:: 2.5


.. function:: basestring()

   This abstract type is the superclass for :class:`str` and :class:`unicode`. It
   cannot be called or instantiated, but it can be used to test whether an object
   is an instance of :class:`str` or :class:`unicode`. ``isinstance(obj,
   basestring)`` is equivalent to ``isinstance(obj, (str, unicode))``.

   .. versionadded:: 2.3


.. function:: bin(x)

   Convert an integer number to a binary string. The result is a valid Python
   expression.  If *x* is not a Python :class:`int` object, it has to define an
   :meth:`__index__` method that returns an integer.

   .. versionadded:: 2.6


.. class:: bool([x])

   Return a Boolean value, i.e. one of ``True`` or ``False``.  *x* is converted
   using the standard truth testing procedure.  If *x* is false or omitted, this
   returns :const:`False`; otherwise it returns :const:`True`. :class:`bool` is
   also a class, which is a subclass of :class:`int`. Class :class:`bool` cannot
   be subclassed further.  Its only instances are :const:`False` and
   :const:`True`.

   .. index:: pair: Boolean; type

   .. versionadded:: 2.2.1

   .. versionchanged:: 2.3
      If no argument is given, this function returns :const:`False`.


.. class:: bytearray([source[, encoding[, errors]]])

   Return a new array of bytes.  The :class:`bytearray` class is a mutable
   sequence of integers in the range 0 <= x < 256.  It has most of the usual
   methods of mutable sequences, described in :ref:`typesseq-mutable`, as well
   as most methods that the :class:`str` type has, see :ref:`string-methods`.

   The optional *source* parameter can be used to initialize the array in a few
   different ways:

   * If it is *unicode*, you must also give the *encoding* (and optionally,
     *errors*) parameters; :func:`bytearray` then converts the unicode to
     bytes using :meth:`unicode.encode`.

   * If it is an *integer*, the array will have that size and will be
     initialized with null bytes.

   * If it is an object conforming to the *buffer* interface, a read-only buffer
     of the object will be used to initialize the bytes array.

   * If it is an *iterable*, it must be an iterable of integers in the range
     ``0 <= x < 256``, which are used as the initial contents of the array.

   Without an argument, an array of size 0 is created.

   .. versionadded:: 2.6


.. function:: callable(object)

   Return :const:`True` if the *object* argument appears callable,
   :const:`False` if not.  If this
   returns true, it is still possible that a call fails, but if it is false,
   calling *object* will never succeed.  Note that classes are callable (calling a
   class returns a new instance); class instances are callable if they have a
   :meth:`__call__` method.


.. function:: chr(i)

   Return a string of one character whose ASCII code is the integer *i*.  For
   example, ``chr(97)`` returns the string ``'a'``. This is the inverse of
   :func:`ord`.  The argument must be in the range [0..255], inclusive;
   :exc:`ValueError` will be raised if *i* is outside that range. See
   also :func:`unichr`.


.. function:: classmethod(function)

   Return a class method for *function*.

   A class method receives the class as implicit first argument, just like an
   instance method receives the instance. To declare a class method, use this
   idiom::

      class C(object):
          @classmethod
          def f(cls, arg1, arg2, ...):
              ...

   The ``@classmethod`` form is a function :term:`decorator` -- see the description
   of function definitions in :ref:`function` for details.

   It can be called either on the class (such as ``C.f()``) or on an instance (such
   as ``C().f()``).  The instance is ignored except for its class. If a class
   method is called for a derived class, the derived class object is passed as the
   implied first argument.

   Class methods are different than C++ or Java static methods. If you want those,
   see :func:`staticmethod` in this section.

   For more information on class methods, consult the documentation on the standard
   type hierarchy in :ref:`types`.

   .. versionadded:: 2.2

   .. versionchanged:: 2.4
      Function decorator syntax added.


.. function:: cmp(x, y)

   Compare the two objects *x* and *y* and return an integer according to the
   outcome.  The return value is negative if ``x < y``, zero if ``x == y`` and
   strictly positive if ``x > y``.


.. function:: compile(source, filename, mode[, flags[, dont_inherit]])

   Compile the *source* into a code or AST object.  Code objects can be executed
   by an :keyword:`exec` statement or evaluated by a call to :func:`eval`.
   *source* can either be a Unicode string, a *Latin-1* encoded string or an
   AST object.
   Refer to the :mod:`ast` module documentation for information on how to work
   with AST objects.

   The *filename* argument should give the file from which the code was read;
   pass some recognizable value if it wasn't read from a file (``'<string>'`` is
   commonly used).

   The *mode* argument specifies what kind of code must be compiled; it can be
   ``'exec'`` if *source* consists of a sequence of statements, ``'eval'`` if it
   consists of a single expression, or ``'single'`` if it consists of a single
   interactive statement (in the latter case, expression statements that
   evaluate to something other than ``None`` will be printed).

   The optional arguments *flags* and *dont_inherit* control which future
   statements (see :pep:`236`) affect the compilation of *source*.  If neither
   is present (or both are zero) the code is compiled with those future
   statements that are in effect in the code that is calling :func:`compile`.  If the
   *flags* argument is given and *dont_inherit* is not (or is zero) then the
   future statements specified by the *flags* argument are used in addition to
   those that would be used anyway. If *dont_inherit* is a non-zero integer then
   the *flags* argument is it -- the future statements in effect around the call
   to compile are ignored.

   Future statements are specified by bits which can be bitwise ORed together to
   specify multiple statements.  The bitfield required to specify a given feature
   can be found as the :attr:`~__future__._Feature.compiler_flag` attribute on
   the :class:`~__future__._Feature` instance in the :mod:`__future__` module.

   This function raises :exc:`SyntaxError` if the compiled source is invalid,
   and :exc:`TypeError` if the source contains null bytes.

   If you want to parse Python code into its AST representation, see
   :func:`ast.parse`.

   .. note::

      When compiling a string with multi-line code in ``'single'`` or
      ``'eval'`` mode, input must be terminated by at least one newline
      character.  This is to facilitate detection of incomplete and complete
      statements in the :mod:`code` module.

   .. versionchanged:: 2.3
      The *flags* and *dont_inherit* arguments were added.

   .. versionchanged:: 2.6
      Support for compiling AST objects.

   .. versionchanged:: 2.7
      Allowed use of Windows and Mac newlines.  Also input in ``'exec'`` mode
      does not have to end in a newline anymore.


.. class:: complex([real[, imag]])

   Return a complex number with the value *real* + *imag*\*1j or convert a string or
   number to a complex number.  If the first parameter is a string, it will be
   interpreted as a complex number and the function must be called without a second
   parameter.  The second parameter can never be a string. Each argument may be any
   numeric type (including complex). If *imag* is omitted, it defaults to zero and
   the function serves as a numeric conversion function like :func:`int`,
   :func:`long` and :func:`float`.  If both arguments are omitted, returns ``0j``.

   .. note::

      When converting from a string, the string must not contain whitespace
      around the central ``+`` or ``-`` operator.  For example,
      ``complex('1+2j')`` is fine, but ``complex('1 + 2j')`` raises
      :exc:`ValueError`.

   The complex type is described in :ref:`typesnumeric`.


.. function:: delattr(object, name)

   This is a relative of :func:`setattr`.  The arguments are an object and a
   string.  The string must be the name of one of the object's attributes.  The
   function deletes the named attribute, provided the object allows it.  For
   example, ``delattr(x, 'foobar')`` is equivalent to ``del x.foobar``.


.. _func-dict:
.. class:: dict(**kwarg)
           dict(mapping, **kwarg)
           dict(iterable, **kwarg)
   :noindex:

   Create a new dictionary.  The :class:`dict` object is the dictionary class.
   See :class:`dict` and :ref:`typesmapping` for documentation about this class.

   For other containers see the built-in :class:`list`, :class:`set`, and
   :class:`tuple` classes, as well as the :mod:`collections` module.


.. function:: dir([object])

   Without arguments, return the list of names in the current local scope.  With an
   argument, attempt to return a list of valid attributes for that object.

   If the object has a method named :meth:`__dir__`, this method will be called and
   must return the list of attributes. This allows objects that implement a custom
   :func:`__getattr__` or :func:`__getattribute__` function to customize the way
   :func:`dir` reports their attributes.

   If the object does not provide :meth:`__dir__`, the function tries its best to
   gather information from the object's :attr:`~object.__dict__` attribute, if defined, and
   from its type object.  The resulting list is not necessarily complete, and may
   be inaccurate when the object has a custom :func:`__getattr__`.

   The default :func:`dir` mechanism behaves differently with different types of
   objects, as it attempts to produce the most relevant, rather than complete,
   information:

   * If the object is a module object, the list contains the names of the module's
     attributes.

   * If the object is a type or class object, the list contains the names of its
     attributes, and recursively of the attributes of its bases.

   * Otherwise, the list contains the object's attributes' names, the names of its
     class's attributes, and recursively of the attributes of its class's base
     classes.

   The resulting list is sorted alphabetically.  For example:

      >>> import struct
      >>> dir()   # show the names in the module namespace
      ['__builtins__', '__doc__', '__name__', 'struct']
      >>> dir(struct)   # show the names in the struct module
      ['Struct', '__builtins__', '__doc__', '__file__', '__name__',
       '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
       'unpack', 'unpack_from']
      >>> class Shape(object):
              def __dir__(self):
                  return ['area', 'perimeter', 'location']
      >>> s = Shape()
      >>> dir(s)
      ['area', 'perimeter', 'location']

   .. note::

      Because :func:`dir` is supplied primarily as a convenience for use at an
      interactive prompt, it tries to supply an interesting set of names more than it
      tries to supply a rigorously or consistently defined set of names, and its
      detailed behavior may change across releases.  For example, metaclass attributes
      are not in the result list when the argument is a class.


.. function:: divmod(a, b)

   Take two (non complex) numbers as arguments and return a pair of numbers
   consisting of their quotient and remainder when using long division.  With mixed
   operand types, the rules for binary arithmetic operators apply.  For plain and
   long integers, the result is the same as ``(a // b, a % b)``. For floating point
   numbers the result is ``(q, a % b)``, where *q* is usually ``math.floor(a / b)``
   but may be 1 less than that.  In any case ``q * b + a % b`` is very close to
   *a*, if ``a % b`` is non-zero it has the same sign as *b*, and ``0 <= abs(a % b)
   < abs(b)``.

   .. versionchanged:: 2.3
      Using :func:`divmod` with complex numbers is deprecated.


.. function:: enumerate(sequence, start=0)

   Return an enumerate object. *sequence* must be a sequence, an
   :term:`iterator`, or some other object which supports iteration.  The
   :meth:`!next` method of the iterator returned by :func:`enumerate` returns a
   tuple containing a count (from *start* which defaults to 0) and the
   values obtained from iterating over *sequence*::

      >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
      >>> list(enumerate(seasons))
      [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
      >>> list(enumerate(seasons, start=1))
      [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

   Equivalent to::

      def enumerate(sequence, start=0):
          n = start
          for elem in sequence:
              yield n, elem
              n += 1

   .. versionadded:: 2.3
   .. versionchanged:: 2.6
      The *start* parameter was added.


.. function:: eval(expression[, globals[, locals]])

   The arguments are a Unicode or *Latin-1* encoded string and optional
   globals and locals.  If provided, *globals* must be a dictionary.
   If provided, *locals* can be any mapping object.

   .. versionchanged:: 2.4
      formerly *locals* was required to be a dictionary.

   The *expression* argument is parsed and evaluated as a Python expression
   (technically speaking, a condition list) using the *globals* and *locals*
   dictionaries as global and local namespace.  If the *globals* dictionary is
   present and lacks '__builtins__', the current globals are copied into *globals*
   before *expression* is parsed.  This means that *expression* normally has full
   access to the standard :mod:`__builtin__` module and restricted environments are
   propagated.  If the *locals* dictionary is omitted it defaults to the *globals*
   dictionary.  If both dictionaries are omitted, the expression is executed in the
   environment where :func:`eval` is called.  The return value is the result of
   the evaluated expression. Syntax errors are reported as exceptions.  Example:

      >>> x = 1
      >>> print eval('x+1')
      2

   This function can also be used to execute arbitrary code objects (such as
   those created by :func:`compile`).  In this case pass a code object instead
   of a string.  If the code object has been compiled with ``'exec'`` as the
   *mode* argument, :func:`eval`\'s return value will be ``None``.

   Hints: dynamic execution of statements is supported by the :keyword:`exec`
   statement.  Execution of statements from a file is supported by the
   :func:`execfile` function.  The :func:`globals` and :func:`locals` functions
   returns the current global and local dictionary, respectively, which may be
   useful to pass around for use by :func:`eval` or :func:`execfile`.

   See :func:`ast.literal_eval` for a function that can safely evaluate strings
   with expressions containing only literals.


.. function:: execfile(filename[, globals[, locals]])

   This function is similar to the :keyword:`exec` statement, but parses a file
   instead of a string.  It is different from the :keyword:`import` statement in
   that it does not use the module administration --- it reads the file
   unconditionally and does not create a new module. [#]_

   The arguments are a file name and two optional dictionaries.  The file is parsed
   and evaluated as a sequence of Python statements (similarly to a module) using
   the *globals* and *locals* dictionaries as global and local namespace. If
   provided, *locals* can be any mapping object.  Remember that at module level,
   globals and locals are the same dictionary. If two separate objects are
   passed as *globals* and *locals*, the code will be executed as if it were
   embedded in a class definition.

   .. versionchanged:: 2.4
      formerly *locals* was required to be a dictionary.

   If the *locals* dictionary is omitted it defaults to the *globals* dictionary.
   If both dictionaries are omitted, the expression is executed in the environment
   where :func:`execfile` is called.  The return value is ``None``.

   .. note::

      The default *locals* act as described for function :func:`locals` below:
      modifications to the default *locals* dictionary should not be attempted.  Pass
      an explicit *locals* dictionary if you need to see effects of the code on
      *locals* after function :func:`execfile` returns.  :func:`execfile` cannot be
      used reliably to modify a function's locals.


.. function:: file(name[, mode[, buffering]])

   Constructor function for the :class:`file` type, described further in section
   :ref:`bltin-file-objects`.  The constructor's arguments are the same as those
   of the :func:`open` built-in function described below.

   When opening a file, it's preferable to use :func:`open` instead of  invoking
   this constructor directly.  :class:`file` is more suited to type testing (for
   example, writing ``isinstance(f, file)``).

   .. versionadded:: 2.2


.. function:: filter(function, iterable)

   Construct a list from those elements of *iterable* for which *function* returns
   true.  *iterable* may be either a sequence, a container which supports
   iteration, or an iterator.  If *iterable* is a string or a tuple, the result
   also has that type; otherwise it is always a list.  If *function* is ``None``,
   the identity function is assumed, that is, all elements of *iterable* that are
   false are removed.

   Note that ``filter(function, iterable)`` is equivalent to ``[item for item in
   iterable if function(item)]`` if function is not ``None`` and ``[item for item
   in iterable if item]`` if function is ``None``.

   See :func:`itertools.ifilter` and :func:`itertools.ifilterfalse` for iterator
   versions of this function, including a variation that filters for elements
   where the *function* returns false.


.. class:: float([x])

   Return a floating point number constructed from a number or string *x*.

   If the argument is a string, it
   must contain a possibly signed decimal or floating point number, possibly
   embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf.
   Otherwise, the argument may be a plain or long integer
   or a floating point number, and a floating point number with the same value
   (within Python's floating point precision) is returned.  If no argument is
   given, returns ``0.0``.

   .. note::

      .. index::
         single: NaN
         single: Infinity

      When passing in a string, values for NaN and Infinity may be returned, depending
      on the underlying C library.  Float accepts the strings nan, inf and -inf for
      NaN and positive or negative infinity. The case and a leading + are ignored as
      well as a leading - is ignored for NaN. Float always represents NaN and infinity
      as nan, inf or -inf.

   The float type is described in :ref:`typesnumeric`.


.. function:: format(value[, format_spec])

   .. index::
      pair: str; format
      single: __format__

   Convert a *value* to a "formatted" representation, as controlled by
   *format_spec*.  The interpretation of *format_spec* will depend on the type
   of the *value* argument, however there is a standard formatting syntax that
   is used by most built-in types: :ref:`formatspec`.

   .. note::

      ``format(value, format_spec)`` merely calls
      ``value.__format__(format_spec)``.

   .. versionadded:: 2.6


.. _func-frozenset:
.. class:: frozenset([iterable])
   :noindex:

   Return a new :class:`frozenset` object, optionally with elements taken from
   *iterable*.  ``frozenset`` is a built-in class.  See :class:`frozenset` and
   :ref:`types-set` for documentation about this class.

   For other containers see the built-in :class:`set`, :class:`list`,
   :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections`
   module.

   .. versionadded:: 2.4


.. function:: getattr(object, name[, default])

   Return the value of the named attribute of *object*.  *name* must be a string.
   If the string is the name of one of the object's attributes, the result is the
   value of that attribute.  For example, ``getattr(x, 'foobar')`` is equivalent to
   ``x.foobar``.  If the named attribute does not exist, *default* is returned if
   provided, otherwise :exc:`AttributeError` is raised.


.. function:: globals()

   Return a dictionary representing the current global symbol table. This is always
   the dictionary of the current module (inside a function or method, this is the
   module where it is defined, not the module from which it is called).


.. function:: hasattr(object, name)

   The arguments are an object and a string.  The result is ``True`` if the string
   is the name of one of the object's attributes, ``False`` if not. (This is
   implemented by calling ``getattr(object, name)`` and seeing whether it raises an
   exception or not.)


.. function:: hash(object)

   Return the hash value of the object (if it has one).  Hash values are integers.
   They are used to quickly compare dictionary keys during a dictionary lookup.
   Numeric values that compare equal have the same hash value (even if they are of
   different types, as is the case for 1 and 1.0).


.. function:: help([object])

   Invoke the built-in help system.  (This function is intended for interactive
   use.)  If no argument is given, the interactive help system starts on the
   interpreter console.  If the argument is a string, then the string is looked up
   as the name of a module, function, class, method, keyword, or documentation
   topic, and a help page is printed on the console.  If the argument is any other
   kind of object, a help page on the object is generated.

   This function is added to the built-in namespace by the :mod:`site` module.

   .. versionadded:: 2.2


.. function:: hex(x)

   Convert an integer number (of any size) to a lowercase hexadecimal string
   prefixed with "0x", for example:

      >>> hex(255)
      '0xff'
      >>> hex(-42)
      '-0x2a'
      >>> hex(1L)
      '0x1L'

   If x is not a Python :class:`int` or :class:`long` object, it has to
   define a __hex__() method that returns a string.

   See also :func:`int` for converting a hexadecimal string to an
   integer using a base of 16.

   .. note::

      To obtain a hexadecimal string representation for a float, use the
      :meth:`float.hex` method.

   .. versionchanged:: 2.4
      Formerly only returned an unsigned literal.


.. function:: id(object)

   Return the "identity" of an object.  This is an integer (or long integer) which
   is guaranteed to be unique and constant for this object during its lifetime.
   Two objects with non-overlapping lifetimes may have the same :func:`id`
   value.

   .. impl-detail:: This is the address of the object in memory.


.. function:: input([prompt])

   Equivalent to ``eval(raw_input(prompt))``.

   This function does not catch user errors. If the input is not syntactically
   valid, a :exc:`SyntaxError` will be raised. Other exceptions may be raised if
   there is an error during evaluation.

   If the :mod:`readline` module was loaded, then :func:`input` will use it to
   provide elaborate line editing and history features.

   Consider using the :func:`raw_input` function for general input from users.


.. class:: int(x=0)
           int(x, base=10)

   Return an integer object constructed from a number or string *x*, or return ``0`` if no
   arguments are given.  If *x* is a number, it can be a plain integer, a long
   integer, or a floating point number.  If *x* is floating point, the conversion
   truncates towards zero.  If the argument is outside the integer range, the
   function returns a long object instead.

   If *x* is not a number or if *base* is given, then *x* must be a string or
   Unicode object representing an :ref:`integer literal <integers>` in radix
   *base*.  Optionally, the literal can be
   preceded by ``+`` or ``-`` (with no space in between) and surrounded by
   whitespace.  A base-n literal consists of the digits 0 to n-1, with ``a``
   to ``z`` (or ``A`` to ``Z``) having
   values 10 to 35.  The default *base* is 10. The allowed values are 0 and 2--36.
   Base-2, -8, and -16 literals can be optionally prefixed with ``0b``/``0B``,
   ``0o``/``0O``/``0``, or ``0x``/``0X``, as with integer literals in code.
   Base 0 means to interpret the string exactly as an integer literal, so that
   the actual base is 2, 8, 10, or 16.

   The integer type is described in :ref:`typesnumeric`.


.. function:: isinstance(object, classinfo)

   Return true if the *object* argument is an instance of the *classinfo* argument,
   or of a (direct, indirect or :term:`virtual <abstract base class>`) subclass
   thereof.  Also return true if *classinfo*
   is a type object (new-style class) and *object* is an object of that type or of
   a (direct, indirect or :term:`virtual <abstract base class>`) subclass
   thereof.  If *object* is not a class instance or
   an object of the given type, the function always returns false.
   If *classinfo* is a tuple of class or type objects (or recursively, other
   such tuples), return true if *object* is an instance of any of the classes
   or types.  If *classinfo* is not a class, type, or tuple of classes, types,
   and such tuples, a :exc:`TypeError` exception is raised.

   .. versionchanged:: 2.2
      Support for a tuple of type information was added.


.. function:: issubclass(class, classinfo)

   Return true if *class* is a subclass (direct, indirect or :term:`virtual
   <abstract base class>`) of *classinfo*.  A
   class is considered a subclass of itself. *classinfo* may be a tuple of class
   objects, in which case every entry in *classinfo* will be checked. In any other
   case, a :exc:`TypeError` exception is raised.

   .. versionchanged:: 2.3
      Support for a tuple of type information was added.


.. function:: iter(o[, sentinel])

   Return an :term:`iterator` object.  The first argument is interpreted very differently
   depending on the presence of the second argument. Without a second argument, *o*
   must be a collection object which supports the iteration protocol (the
   :meth:`__iter__` method), or it must support the sequence protocol (the
   :meth:`__getitem__` method with integer arguments starting at ``0``).  If it
   does not support either of those protocols, :exc:`TypeError` is raised. If the
   second argument, *sentinel*, is given, then *o* must be a callable object.  The
   iterator created in this case will call *o* with no arguments for each call to
   its :meth:`~iterator.next` method; if the value returned is equal to *sentinel*,
   :exc:`StopIteration` will be raised, otherwise the value will be returned.

   One useful application of the second form of :func:`iter` is to read lines of
   a file until a certain line is reached.  The following example reads a file
   until the :meth:`~io.TextIOBase.readline` method returns an empty string::

      with open('mydata.txt') as fp:
          for line in iter(fp.readline, ''):
              process_line(line)

   .. versionadded:: 2.2


.. function:: len(s)

   Return the length (the number of items) of an object.  The argument may be a
   sequence (such as a string, bytes, tuple, list, or range) or a collection
   (such as a dictionary, set, or frozen set).


.. _func-list:
.. class:: list([iterable])
   :noindex:

   Return a list whose items are the same and in the same order as *iterable*'s
   items.  *iterable* may be either a sequence, a container that supports
   iteration, or an iterator object.  If *iterable* is already a list, a copy is
   made and returned, similar to ``iterable[:]``.  For instance, ``list('abc')``
   returns ``['a', 'b', 'c']`` and ``list( (1, 2, 3) )`` returns ``[1, 2, 3]``.  If
   no argument is given, returns a new empty list, ``[]``.

   :class:`list` is a mutable sequence type, as documented in
   :ref:`typesseq`. For other containers see the built in :class:`dict`,
   :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module.


.. function:: locals()

   Update and return a dictionary representing the current local symbol table.
   Free variables are returned by :func:`locals` when it is called in function
   blocks, but not in class blocks.

   .. note::

      The contents of this dictionary should not be modified; changes may not
      affect the values of local and free variables used by the interpreter.


.. class:: long(x=0)
           long(x, base=10)

   Return a long integer object constructed from a string or number *x*.
   If the argument is a string, it
   must contain a possibly signed number of arbitrary size, possibly embedded in
   whitespace. The *base* argument is interpreted in the same way as for
   :func:`int`, and may only be given when *x* is a string. Otherwise, the argument
   may be a plain or long integer or a floating point number, and a long integer
   with the same value is returned.    Conversion of floating point numbers to
   integers truncates (towards zero).  If no arguments are given, returns ``0L``.

   The long type is described in :ref:`typesnumeric`.


.. function:: map(function, iterable, ...)

   Apply *function* to every item of *iterable* and return a list of the results.
   If additional *iterable* arguments are passed, *function* must take that many
   arguments and is applied to the items from all iterables in parallel.  If one
   iterable is shorter than another it is assumed to be extended with ``None``
   items.  If *function* is ``None``, the identity function is assumed; if there
   are multiple arguments, :func:`map` returns a list consisting of tuples
   containing the corresponding items from all iterables (a kind of transpose
   operation).  The *iterable* arguments may be a sequence  or any iterable object;
   the result is always a list.


.. function:: max(iterable[, key])
              max(arg1, arg2, *args[, key])

   Return the largest item in an iterable or the largest of two or more
   arguments.

   If one positional argument is provided, *iterable* must be a non-empty
   iterable (such as a non-empty string, tuple or list).  The largest item
   in the iterable is returned.  If two or more positional arguments are
   provided, the largest of the positional arguments is returned.

   The optional *key* argument specifies a one-argument ordering function like that
   used for :meth:`list.sort`.  The *key* argument, if supplied, must be in keyword
   form (for example, ``max(a,b,c,key=func)``).

   .. versionchanged:: 2.5
      Added support for the optional *key* argument.

.. _func-memoryview:
.. function:: memoryview(obj)
   :noindex:

   Return a "memory view" object created from the given argument.  See
   :ref:`typememoryview` for more information.


.. function:: min(iterable[, key])
              min(arg1, arg2, *args[, key])

   Return the smallest item in an iterable or the smallest of two or more
   arguments.

   If one positional argument is provided, *iterable* must be a non-empty
   iterable (such as a non-empty string, tuple or list).  The smallest item
   in the iterable is returned.  If two or more positional arguments are
   provided, the smallest of the positional arguments is returned.

   The optional *key* argument specifies a one-argument ordering function like that
   used for :meth:`list.sort`.  The *key* argument, if supplied, must be in keyword
   form (for example, ``min(a,b,c,key=func)``).

   .. versionchanged:: 2.5
      Added support for the optional *key* argument.


.. function:: next(iterator[, default])

   Retrieve the next item from the *iterator* by calling its
   :meth:`~iterator.next` method.  If *default* is given, it is returned if the
   iterator is exhausted, otherwise :exc:`StopIteration` is raised.

   .. versionadded:: 2.6


.. class:: object()

   Return a new featureless object.  :class:`object` is a base for all new style
   classes.  It has the methods that are common to all instances of new style
   classes.

   .. versionadded:: 2.2

   .. versionchanged:: 2.3
      This function does not accept any arguments. Formerly, it accepted arguments but
      ignored them.


.. function:: oct(x)

   Convert an integer number (of any size) to an octal string.  The result is a
   valid Python expression.

   .. versionchanged:: 2.4
      Formerly only returned an unsigned literal.


.. function:: open(name[, mode[, buffering]])

   Open a file, returning an object of the :class:`file` type described in
   section :ref:`bltin-file-objects`.  If the file cannot be opened,
   :exc:`IOError` is raised.  When opening a file, it's preferable to use
   :func:`open` instead of invoking the :class:`file` constructor directly.

   The first two arguments are the same as for ``stdio``'s :c:func:`fopen`:
   *name* is the file name to be opened, and *mode* is a string indicating how
   the file is to be opened.

   The most commonly-used values of *mode* are ``'r'`` for reading, ``'w'`` for
   writing (truncating the file if it already exists), and ``'a'`` for appending
   (which on *some* Unix systems means that *all* writes append to the end of the
   file regardless of the current seek position).  If *mode* is omitted, it
   defaults to ``'r'``.  The default is to use text mode, which may convert
   ``'\n'`` characters to a platform-specific representation on writing and back
   on reading.  Thus, when opening a binary file, you should append ``'b'`` to
   the *mode* value to open the file in binary mode, which will improve
   portability.  (Appending ``'b'`` is useful even on systems that don't treat
   binary and text files differently, where it serves as documentation.)  See below
   for more possible values of *mode*.

   .. index::
      single: line-buffered I/O
      single: unbuffered I/O
      single: buffer size, I/O
      single: I/O control; buffering

   The optional *buffering* argument specifies the file's desired buffer size: 0
   means unbuffered, 1 means line buffered, any other positive value means use a
   buffer of (approximately) that size (in bytes).  A negative *buffering* means
   to use the system default, which is usually line buffered for tty devices and
   fully buffered for other files.  If omitted, the system default is used. [#]_

   Modes ``'r+'``, ``'w+'`` and ``'a+'`` open the file for updating (reading and writing);
   note that ``'w+'`` truncates the file.  Append ``'b'`` to the mode to open the file in
   binary mode, on systems that differentiate between binary and text files; on
   systems that don't have this distinction, adding the ``'b'`` has no effect.

   .. index::
      single: universal newlines; open() built-in function

   In addition to the standard :c:func:`fopen` values *mode* may be ``'U'`` or
   ``'rU'``.  Python is usually built with :term:`universal newlines` support;
   supplying ``'U'`` opens the file as a text file, but lines may be terminated
   by any of the following: the Unix end-of-line convention ``'\n'``,  the
   Macintosh convention ``'\r'``, or the Windows convention ``'\r\n'``. All of
   these external representations are seen as ``'\n'`` by the Python program.
   If Python is built without universal newlines support a *mode* with ``'U'``
   is the same as normal text mode.  Note that file objects so opened also have
   an attribute called :attr:`newlines` which has a value of ``None`` (if no
   newlines have yet been seen), ``'\n'``, ``'\r'``, ``'\r\n'``, or a tuple
   containing all the newline types seen.

   Python enforces that the mode, after stripping ``'U'``, begins with ``'r'``,
   ``'w'`` or ``'a'``.

   Python provides many file handling modules including
   :mod:`fileinput`, :mod:`os`, :mod:`os.path`, :mod:`tempfile`, and
   :mod:`shutil`.

   .. versionchanged:: 2.5
      Restriction on first letter of mode string introduced.


.. function:: ord(c)

   Given a string of length one, return an integer representing the Unicode code
   point of the character when the argument is a unicode object, or the value of
   the byte when the argument is an 8-bit string. For example, ``ord('a')`` returns
   the integer ``97``, ``ord(u'\u2020')`` returns ``8224``.  This is the inverse of
   :func:`chr` for 8-bit strings and of :func:`unichr` for unicode objects.  If a
   unicode argument is given and Python was built with UCS2 Unicode, then the
   character's code point must be in the range [0..65535] inclusive; otherwise the
   string length is two, and a :exc:`TypeError` will be raised.


.. function:: pow(x, y[, z])

   Return *x* to the power *y*; if *z* is present, return *x* to the power *y*,
   modulo *z* (computed more efficiently than ``pow(x, y) % z``). The two-argument
   form ``pow(x, y)`` is equivalent to using the power operator: ``x**y``.

   The arguments must have numeric types.  With mixed operand types, the coercion
   rules for binary arithmetic operators apply.  For int and long int operands, the
   result has the same type as the operands (after coercion) unless the second
   argument is negative; in that case, all arguments are converted to float and a
   float result is delivered.  For example, ``10**2`` returns ``100``, but
   ``10**-2`` returns ``0.01``.  (This last feature was added in Python 2.2.  In
   Python 2.1 and before, if both arguments were of integer types and the second
   argument was negative, an exception was raised.) If the second argument is
   negative, the third argument must be omitted. If *z* is present, *x* and *y*
   must be of integer types, and *y* must be non-negative.  (This restriction was
   added in Python 2.2.  In Python 2.1 and before, floating 3-argument ``pow()``
   returned platform-dependent results depending on floating-point rounding
   accidents.)


.. function:: print(*objects, sep=' ', end='\\n', file=sys.stdout)

   Print *objects* to the stream *file*, separated by *sep* and followed by
   *end*.  *sep*, *end* and *file*, if present, must be given as keyword
   arguments.

   All non-keyword arguments are converted to strings like :func:`str` does and
   written to the stream, separated by *sep* and followed by *end*.  Both *sep*
   and *end* must be strings; they can also be ``None``, which means to use the
   default values.  If no *objects* are given, :func:`print` will just write
   *end*.

   The *file* argument must be an object with a ``write(string)`` method; if it
   is not present or ``None``, :data:`sys.stdout` will be used.  Output buffering
   is determined by *file*.  Use ``file.flush()`` to ensure, for instance,
   immediate appearance on a screen.

   .. note::

      This function is not normally available as a built-in since the name
      ``print`` is recognized as the :keyword:`print` statement.  To disable the
      statement and use the :func:`print` function, use this future statement at
      the top of your module::

         from __future__ import print_function

   .. versionadded:: 2.6


.. class:: property([fget[, fset[, fdel[, doc]]]])

   Return a property attribute for :term:`new-style class`\es (classes that
   derive from :class:`object`).

   *fget* is a function for getting an attribute value.  *fset* is a function
   for setting an attribute value. *fdel* is a function for deleting an attribute
   value.  And *doc* creates a docstring for the attribute.

   A typical use is to define a managed attribute ``x``::

      class C(object):
          def __init__(self):
              self._x = None

          def getx(self):
              return self._x

          def setx(self, value):
              self._x = value

          def delx(self):
              del self._x

          x = property(getx, setx, delx, "I'm the 'x' property.")

   If *c* is an instance of *C*, ``c.x`` will invoke the getter,
   ``c.x = value`` will invoke the setter and ``del c.x`` the deleter.

   If given, *doc* will be the docstring of the property attribute. Otherwise, the
   property will copy *fget*'s docstring (if it exists).  This makes it possible to
   create read-only properties easily using :func:`property` as a :term:`decorator`::

      class Parrot(object):
          def __init__(self):
              self._voltage = 100000

          @property
          def voltage(self):
              """Get the current voltage."""
              return self._voltage

   The ``@property`` decorator turns the :meth:`voltage` method into a "getter"
   for a read-only attribute with the same name, and it sets the docstring for
   *voltage* to "Get the current voltage."

   A property object has :attr:`~property.getter`, :attr:`~property.setter`,
   and :attr:`~property.deleter` methods usable as decorators that create a
   copy of the property with the corresponding accessor function set to the
   decorated function.  This is best explained with an example::

      class C(object):
          def __init__(self):
              self._x = None

          @property
          def x(self):
              """I'm the 'x' property."""
              return self._x

          @x.setter
          def x(self, value):
              self._x = value

          @x.deleter
          def x(self):
              del self._x

   This code is exactly equivalent to the first example.  Be sure to give the
   additional functions the same name as the original property (``x`` in this
   case.)

   The returned property object also has the attributes ``fget``, ``fset``, and
   ``fdel`` corresponding to the constructor arguments.

   .. versionadded:: 2.2

   .. versionchanged:: 2.5
      Use *fget*'s docstring if no *doc* given.

   .. versionchanged:: 2.6
      The ``getter``, ``setter``, and ``deleter`` attributes were added.


.. function:: range(stop)
              range(start, stop[, step])

   This is a versatile function to create lists containing arithmetic progressions.
   It is most often used in :keyword:`for` loops.  The arguments must be plain
   integers.  If the *step* argument is omitted, it defaults to ``1``.  If the
   *start* argument is omitted, it defaults to ``0``.  The full form returns a list
   of plain integers ``[start, start + step, start + 2 * step, ...]``.  If *step*
   is positive, the last element is the largest ``start + i * step`` less than
   *stop*; if *step* is negative, the last element is the smallest ``start + i *
   step`` greater than *stop*.  *step* must not be zero (or else :exc:`ValueError`
   is raised).  Example:

      >>> range(10)
      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      >>> range(1, 11)
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      >>> range(0, 30, 5)
      [0, 5, 10, 15, 20, 25]
      >>> range(0, 10, 3)
      [0, 3, 6, 9]
      >>> range(0, -10, -1)
      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
      >>> range(0)
      []
      >>> range(1, 0)
      []


.. function:: raw_input([prompt])

   If the *prompt* argument is present, it is written to standard output without a
   trailing newline.  The function then reads a line from input, converts it to a
   string (stripping a trailing newline), and returns that. When EOF is read,
   :exc:`EOFError` is raised. Example::

      >>> s = raw_input('--> ')
      --> Monty Python's Flying Circus
      >>> s
      "Monty Python's Flying Circus"

   If the :mod:`readline` module was loaded, then :func:`raw_input` will use it to
   provide elaborate line editing and history features.


.. function:: reduce(function, iterable[, initializer])

   Apply *function* of two arguments cumulatively to the items of *iterable*, from
   left to right, so as to reduce the iterable to a single value.  For example,
   ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
   The left argument, *x*, is the accumulated value and the right argument, *y*, is
   the update value from the *iterable*.  If the optional *initializer* is present,
   it is placed before the items of the iterable in the calculation, and serves as
   a default when the iterable is empty.  If *initializer* is not given and
   *iterable* contains only one item, the first item is returned.
   Roughly equivalent to::

      def reduce(function, iterable, initializer=None):
          it = iter(iterable)
          if initializer is None:
              try:
                  initializer = next(it)
              except StopIteration:
                  raise TypeError('reduce() of empty sequence with no initial value')
          accum_value = initializer
          for x in it:
              accum_value = function(accum_value, x)
          return accum_value

.. function:: reload(module)

   Reload a previously imported *module*.  The argument must be a module object, so
   it must have been successfully imported before.  This is useful if you have
   edited the module source file using an external editor and want to try out the
   new version without leaving the Python interpreter.  The return value is the
   module object (the same as the *module* argument).

   When ``reload(module)`` is executed:

   * Python modules' code is recompiled and the module-level code reexecuted,
     defining a new set of objects which are bound to names in the module's
     dictionary.  The ``init`` function of extension modules is not called a second
     time.

   * As with all other objects in Python the old objects are only reclaimed after
     their reference counts drop to zero.

   * The names in the module namespace are updated to point to any new or changed
     objects.

   * Other references to the old objects (such as names external to the module) are
     not rebound to refer to the new objects and must be updated in each namespace
     where they occur if that is desired.

   There are a number of other caveats:

   When a module is reloaded, its dictionary (containing the module's global
   variables) is retained.  Redefinitions of names will override the old
   definitions, so this is generally not a problem.  If the new version of a module
   does not define a name that was defined by the old version, the old definition
   remains.  This feature can be used to the module's advantage if it maintains a
   global table or cache of objects --- with a :keyword:`try` statement it can test
   for the table's presence and skip its initialization if desired::

      try:
          cache
      except NameError:
          cache = {}

   It is generally not very useful to reload built-in or dynamically loaded
   modules.  Reloading :mod:`sys`, :mod:`__main__`, :mod:`builtins` and other
   key modules is not recommended.  In many cases extension modules are not
   designed to be initialized more than once, and may fail in arbitrary ways
   when reloaded.

   If a module imports objects from another module using :keyword:`from` ...
   :keyword:`import` ..., calling :func:`reload` for the other module does not
   redefine the objects imported from it --- one way around this is to re-execute
   the :keyword:`from` statement, another is to use :keyword:`import` and qualified
   names (*module*.*name*) instead.

   If a module instantiates instances of a class, reloading the module that defines
   the class does not affect the method definitions of the instances --- they
   continue to use the old class definition.  The same is true for derived classes.


.. _func-repr:
.. function:: repr(object)

   Return a string containing a printable representation of an object.  This is
   the same value yielded by conversions (reverse quotes).  It is sometimes
   useful to be able to access this operation as an ordinary function.  For many
   types, this function makes an attempt to return a string that would yield an
   object with the same value when passed to :func:`eval`, otherwise the
   representation is a string enclosed in angle brackets that contains the name
   of the type of the object together with additional information often
   including the name and address of the object.  A class can control what this
   function returns for its instances by defining a :meth:`__repr__` method.


.. function:: reversed(seq)

   Return a reverse :term:`iterator`.  *seq* must be an object which has
   a :meth:`__reversed__` method or supports the sequence protocol (the
   :meth:`__len__` method and the :meth:`__getitem__` method with integer
   arguments starting at ``0``).

   .. versionadded:: 2.4

   .. versionchanged:: 2.6
      Added the possibility to write a custom :meth:`__reversed__` method.


.. function:: round(number[, ndigits])

   Return the floating point value *number* rounded to *ndigits* digits after
   the decimal point.  If *ndigits* is omitted, it defaults to zero. The result
   is a floating point number.  Values are rounded to the closest multiple of
   10 to the power minus *ndigits*; if two multiples are equally close,
   rounding is done away from 0 (so, for example, ``round(0.5)`` is ``1.0`` and
   ``round(-0.5)`` is ``-1.0``).


   .. note::

      The behavior of :func:`round` for floats can be surprising: for example,
      ``round(2.675, 2)`` gives ``2.67`` instead of the expected ``2.68``.
      This is not a bug: it's a result of the fact that most decimal fractions
      can't be represented exactly as a float.  See :ref:`tut-fp-issues` for
      more information.


.. _func-set:
.. class:: set([iterable])
   :noindex:

   Return a new :class:`set` object, optionally with elements taken from
   *iterable*.  ``set`` is a built-in class.  See :class:`set` and
   :ref:`types-set` for documentation about this class.

   For other containers see the built-in :class:`frozenset`, :class:`list`,
   :class:`tuple`, and :class:`dict` classes, as well as the :mod:`collections`
   module.

   .. versionadded:: 2.4


.. function:: setattr(object, name, value)

   This is the counterpart of :func:`getattr`.  The arguments are an object, a
   string and an arbitrary value.  The string may name an existing attribute or a
   new attribute.  The function assigns the value to the attribute, provided the
   object allows it.  For example, ``setattr(x, 'foobar', 123)`` is equivalent to
   ``x.foobar = 123``.


.. class:: slice(stop)
           slice(start, stop[, step])

   .. index:: single: Numerical Python

   Return a :term:`slice` object representing the set of indices specified by
   ``range(start, stop, step)``.  The *start* and *step* arguments default to
   ``None``.  Slice objects have read-only data attributes :attr:`~slice.start`,
   :attr:`~slice.stop` and :attr:`~slice.step` which merely return the argument
   values (or their default).  They have no other explicit functionality;
   however they are used by Numerical Python and other third party extensions.
   Slice objects are also generated when extended indexing syntax is used.  For
   example: ``a[start:stop:step]`` or ``a[start:stop, i]``.  See
   :func:`itertools.islice` for an alternate version that returns an iterator.


.. function:: sorted(iterable[, cmp[, key[, reverse]]])

   Return a new sorted list from the items in *iterable*.

   The optional arguments *cmp*, *key*, and *reverse* have the same meaning as
   those for the :meth:`list.sort` method (described in section
   :ref:`typesseq-mutable`).

   *cmp* specifies a custom comparison function of two arguments (iterable
   elements) which should return a negative, zero or positive number depending on
   whether the first argument is considered smaller than, equal to, or larger than
   the second argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.  The default
   value is ``None``.

   *key* specifies a function of one argument that is used to extract a comparison
   key from each list element: ``key=str.lower``.  The default value is ``None``
   (compare the elements directly).

   *reverse* is a boolean value.  If set to ``True``, then the list elements are
   sorted as if each comparison were reversed.

   In general, the *key* and *reverse* conversion processes are much faster
   than specifying an equivalent *cmp* function.  This is because *cmp* is
   called multiple times for each list element while *key* and *reverse* touch
   each element only once.  Use :func:`functools.cmp_to_key` to convert an
   old-style *cmp* function to a *key* function.

   The built-in :func:`sorted` function is guaranteed to be stable. A sort is
   stable if it guarantees not to change the relative order of elements that
   compare equal --- this is helpful for sorting in multiple passes (for
   example, sort by department, then by salary grade).

   For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.

   .. versionadded:: 2.4


.. function:: staticmethod(function)

   Return a static method for *function*.

   A static method does not receive an implicit first argument. To declare a static
   method, use this idiom::

      class C(object):
          @staticmethod
          def f(arg1, arg2, ...):
              ...

   The ``@staticmethod`` form is a function :term:`decorator` -- see the
   description of function definitions in :ref:`function` for details.

   It can be called either on the class (such as ``C.f()``) or on an instance (such
   as ``C().f()``).  The instance is ignored except for its class.

   Static methods in Python are similar to those found in Java or C++. Also see
   :func:`classmethod` for a variant that is useful for creating alternate
   class constructors.

   For more information on static methods, consult the documentation on the
   standard type hierarchy in :ref:`types`.

   .. versionadded:: 2.2

   .. versionchanged:: 2.4
      Function decorator syntax added.


.. class:: str(object='')

   Return a string containing a nicely printable representation of an object.  For
   strings, this returns the string itself.  The difference with ``repr(object)``
   is that ``str(object)`` does not always attempt to return a string that is
   acceptable to :func:`eval`; its goal is to return a printable string.  If no
   argument is given, returns the empty string, ``''``.

   For more information on strings see :ref:`typesseq` which describes sequence
   functionality (strings are sequences), and also the string-specific methods
   described in the :ref:`string-methods` section. To output formatted strings
   use template strings or the ``%`` operator described in the
   :ref:`string-formatting` section. In addition see the :ref:`stringservices`
   section. See also :func:`unicode`.


.. function:: sum(iterable[, start])

   Sums *start* and the items of an *iterable* from left to right and returns the
   total.  *start* defaults to ``0``. The *iterable*'s items are normally numbers,
   and the start value is not allowed to be a string.

   For some use cases, there are good alternatives to :func:`sum`.
   The preferred, fast way to concatenate a sequence of strings is by calling
   ``''.join(sequence)``.  To add floating point values with extended precision,
   see :func:`math.fsum`\.  To concatenate a series of iterables, consider using
   :func:`itertools.chain`.

   .. versionadded:: 2.3


.. function:: super(type[, object-or-type])

   Return a proxy object that delegates method calls to a parent or sibling
   class of *type*.  This is useful for accessing inherited methods that have
   been overridden in a class. The search order is same as that used by
   :func:`getattr` except that the *type* itself is skipped.

   The :attr:`~class.__mro__` attribute of the *type* lists the method
   resolution search order used by both :func:`getattr` and :func:`super`.  The
   attribute is dynamic and can change whenever the inheritance hierarchy is
   updated.

   If the second argument is omitted, the super object returned is unbound.  If
   the second argument is an object, ``isinstance(obj, type)`` must be true.  If
   the second argument is a type, ``issubclass(type2, type)`` must be true (this
   is useful for classmethods).

   .. note::
      :func:`super` only works for :term:`new-style class`\es.

   There are two typical use cases for *super*.  In a class hierarchy with
   single inheritance, *super* can be used to refer to parent classes without
   naming them explicitly, thus making the code more maintainable.  This use
   closely parallels the use of *super* in other programming languages.

   The second use case is to support cooperative multiple inheritance in a
   dynamic execution environment.  This use case is unique to Python and is
   not found in statically compiled languages or languages that only support
   single inheritance.  This makes it possible to implement "diamond diagrams"
   where multiple base classes implement the same method.  Good design dictates
   that this method have the same calling signature in every case (because the
   order of calls is determined at runtime, because that order adapts
   to changes in the class hierarchy, and because that order can include
   sibling classes that are unknown prior to runtime).

   For both use cases, a typical superclass call looks like this::

      class C(B):
          def method(self, arg):
              super(C, self).method(arg)

   Note that :func:`super` is implemented as part of the binding process for
   explicit dotted attribute lookups such as ``super().__getitem__(name)``.
   It does so by implementing its own :meth:`__getattribute__` method for searching
   classes in a predictable order that supports cooperative multiple inheritance.
   Accordingly, :func:`super` is undefined for implicit lookups using statements or
   operators such as ``super()[name]``.

   Also note that :func:`super` is not limited to use inside methods.  The two
   argument form specifies the arguments exactly and makes the appropriate
   references.

   For practical suggestions on how to design cooperative classes using
   :func:`super`, see `guide to using super()
   <https://rhettinger.wordpress.com/2011/05/26/super-considered-super/>`_.

   .. versionadded:: 2.2


.. function:: tuple([iterable])

   Return a tuple whose items are the same and in the same order as *iterable*'s
   items.  *iterable* may be a sequence, a container that supports iteration, or an
   iterator object. If *iterable* is already a tuple, it is returned unchanged.
   For instance, ``tuple('abc')`` returns ``('a', 'b', 'c')`` and ``tuple([1, 2,
   3])`` returns ``(1, 2, 3)``.  If no argument is given, returns a new empty
   tuple, ``()``.

   :class:`tuple` is an immutable sequence type, as documented in
   :ref:`typesseq`. For other containers see the built in :class:`dict`,
   :class:`list`, and :class:`set` classes, and the :mod:`collections` module.


.. class:: type(object)
           type(name, bases, dict)

   .. index:: object: type

   With one argument, return the type of an *object*.  The return value is a
   type object.  The :func:`isinstance` built-in function is recommended for
   testing the type of an object.

   With three arguments, return a new type object.  This is essentially a
   dynamic form of the :keyword:`class` statement. The *name* string is the
   class name and becomes the :attr:`~definition.__name__` attribute; the *bases* tuple
   itemizes the base classes and becomes the :attr:`~class.__bases__` attribute;
   and the *dict* dictionary is the namespace containing definitions for class
   body and becomes the :attr:`~object.__dict__`  attribute.  For example, the
   following two statements create identical :class:`type` objects:

      >>> class X(object):
      ...     a = 1
      ...
      >>> X = type('X', (object,), dict(a=1))

   .. versionadded:: 2.2


.. function:: unichr(i)

   Return the Unicode string of one character whose Unicode code is the integer
   *i*.  For example, ``unichr(97)`` returns the string ``u'a'``.  This is the
   inverse of :func:`ord` for Unicode strings.  The valid range for the argument
   depends how Python was configured -- it may be either UCS2 [0..0xFFFF] or UCS4
   [0..0x10FFFF]. :exc:`ValueError` is raised otherwise. For ASCII and 8-bit
   strings see :func:`chr`.

   .. versionadded:: 2.0


.. function:: unicode(object='')
              unicode(object[, encoding [, errors]])

   Return the Unicode string version of *object* using one of the following modes:

   If *encoding* and/or *errors* are given, ``unicode()`` will decode the object
   which can either be an 8-bit string or a character buffer using the codec for
   *encoding*. The *encoding* parameter is a string giving the name of an encoding;
   if the encoding is not known, :exc:`LookupError` is raised. Error handling is
   done according to *errors*; this specifies the treatment of characters which are
   invalid in the input encoding.  If *errors* is ``'strict'`` (the default), a
   :exc:`ValueError` is raised on errors, while a value of ``'ignore'`` causes
   errors to be silently ignored, and a value of ``'replace'`` causes the official
   Unicode replacement character, ``U+FFFD``, to be used to replace input
   characters which cannot be decoded.  See also the :mod:`codecs` module.

   If no optional parameters are given, ``unicode()`` will mimic the behaviour of
   ``str()`` except that it returns Unicode strings instead of 8-bit strings. More
   precisely, if *object* is a Unicode string or subclass it will return that
   Unicode string without any additional decoding applied.

   For objects which provide a :meth:`__unicode__` method, it will call this method
   without arguments to create a Unicode string. For all other objects, the 8-bit
   string version or representation is requested and then converted to a Unicode
   string using the codec for the default encoding in ``'strict'`` mode.

   For more information on Unicode strings see :ref:`typesseq` which describes
   sequence functionality (Unicode strings are sequences), and also the
   string-specific methods described in the :ref:`string-methods` section. To
   output formatted strings use template strings or the ``%`` operator described
   in the :ref:`string-formatting` section. In addition see the
   :ref:`stringservices` section. See also :func:`str`.

   .. versionadded:: 2.0

   .. versionchanged:: 2.2
      Support for :meth:`__unicode__` added.


.. function:: vars([object])

   Return the :attr:`~object.__dict__` attribute for a module, class, instance,
   or any other object with a :attr:`~object.__dict__` attribute.

   Objects such as modules and instances have an updateable :attr:`~object.__dict__`
   attribute; however, other objects may have write restrictions on their
   :attr:`~object.__dict__` attributes (for example, new-style classes use a
   dictproxy to prevent direct dictionary updates).

   Without an argument, :func:`vars` acts like :func:`locals`.  Note, the
   locals dictionary is only useful for reads since updates to the locals
   dictionary are ignored.


.. function:: xrange(stop)
              xrange(start, stop[, step])

   This function is very similar to :func:`range`, but returns an :ref:`xrange
   object <typesseq-xrange>`
   instead of a list.  This is an opaque sequence type which yields the same values
   as the corresponding list, without actually storing them all simultaneously.
   The advantage of :func:`xrange` over :func:`range` is minimal (since
   :func:`xrange` still has to create the values when asked for them) except when a
   very large range is used on a memory-starved machine or when all of the range's
   elements are never used (such as when the loop is usually terminated with
   :keyword:`break`).  For more information on xrange objects, see
   :ref:`typesseq-xrange` and :ref:`typesseq`.

   .. impl-detail::

      :func:`xrange` is intended to be simple and fast.  Implementations may
      impose restrictions to achieve this.  The C implementation of Python
      restricts all arguments to native C longs ("short" Python integers), and
      also requires that the number of elements fit in a native C long.  If a
      larger range is needed, an alternate version can be crafted using the
      :mod:`itertools` module: ``islice(count(start, step),
      (stop-start+step-1+2*(step<0))//step)``.


.. function:: zip([iterable, ...])

   This function returns a list of tuples, where the *i*-th tuple contains the
   *i*-th element from each of the argument sequences or iterables. The returned
   list is truncated in length to the length of the shortest argument sequence.
   When there are multiple arguments which are all of the same length, :func:`zip`
   is similar to :func:`map` with an initial argument of ``None``. With a single
   sequence argument, it returns a list of 1-tuples. With no arguments, it returns
   an empty list.

   The left-to-right evaluation order of the iterables is guaranteed. This
   makes possible an idiom for clustering a data series into n-length groups
   using ``zip(*[iter(s)]*n)``.

   :func:`zip` in conjunction with the ``*`` operator can be used to unzip a
   list::

      >>> x = [1, 2, 3]
      >>> y = [4, 5, 6]
      >>> zipped = zip(x, y)
      >>> zipped
      [(1, 4), (2, 5), (3, 6)]
      >>> x2, y2 = zip(*zipped)
      >>> x == list(x2) and y == list(y2)
      True

   .. versionadded:: 2.0

   .. versionchanged:: 2.4
      Formerly, :func:`zip` required at least one argument and ``zip()`` raised a
      :exc:`TypeError` instead of returning an empty list.


.. function:: __import__(name[, globals[, locals[, fromlist[, level]]]])

   .. index::
      statement: import
      module: imp

   .. note::

      This is an advanced function that is not needed in everyday Python
      programming, unlike :func:`importlib.import_module`.

   This function is invoked by the :keyword:`import` statement.  It can be
   replaced (by importing the :mod:`__builtin__` module and assigning to
   ``__builtin__.__import__``) in order to change semantics of the
   :keyword:`import` statement, but nowadays it is usually simpler to use import
   hooks (see :pep:`302`).  Direct use of :func:`__import__` is rare, except in
   cases where you want to import a module whose name is only known at runtime.

   The function imports the module *name*, potentially using the given *globals*
   and *locals* to determine how to interpret the name in a package context.
   The *fromlist* gives the names of objects or submodules that should be
   imported from the module given by *name*.  The standard implementation does
   not use its *locals* argument at all, and uses its *globals* only to
   determine the package context of the :keyword:`import` statement.

   *level* specifies whether to use absolute or relative imports.  The default
   is ``-1`` which indicates both absolute and relative imports will be
   attempted.  ``0`` means only perform absolute imports.  Positive values for
   *level* indicate the number of parent directories to search relative to the
   directory of the module calling :func:`__import__`.

   When the *name* variable is of the form ``package.module``, normally, the
   top-level package (the name up till the first dot) is returned, *not* the
   module named by *name*.  However, when a non-empty *fromlist* argument is
   given, the module named by *name* is returned.

   For example, the statement ``import spam`` results in bytecode resembling the
   following code::

      spam = __import__('spam', globals(), locals(), [], -1)

   The statement ``import spam.ham`` results in this call::

      spam = __import__('spam.ham', globals(), locals(), [], -1)

   Note how :func:`__import__` returns the toplevel module here because this is
   the object that is bound to a name by the :keyword:`import` statement.

   On the other hand, the statement ``from spam.ham import eggs, sausage as
   saus`` results in ::

      _temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
      eggs = _temp.eggs
      saus = _temp.sausage

   Here, the ``spam.ham`` module is returned from :func:`__import__`.  From this
   object, the names to import are retrieved and assigned to their respective
   names.

   If you simply want to import a module (potentially within a package) by name,
   use :func:`importlib.import_module`.


   .. versionchanged:: 2.5
      The level parameter was added.

   .. versionchanged:: 2.5
      Keyword support for parameters was added.

..  ---------------------------------------------------------------------------


.. _non-essential-built-in-funcs:

Non-essential Built-in Functions
================================

There are several built-in functions that are no longer essential to learn, know
or use in modern Python programming.  They have been kept here to maintain
backwards compatibility with programs written for older versions of Python.

Python programmers, trainers, students and book writers should feel free to
bypass these functions without concerns about missing something important.


.. function:: apply(function, args[, keywords])

   The *function* argument must be a callable object (a user-defined or built-in
   function or method, or a class object) and the *args* argument must be a
   sequence.  The *function* is called with *args* as the argument list; the number
   of arguments is the length of the tuple. If the optional *keywords* argument is
   present, it must be a dictionary whose keys are strings.  It specifies keyword
   arguments to be added to the end of the argument list. Calling :func:`apply` is
   different from just calling ``function(args)``, since in that case there is
   always exactly one argument.  The use of :func:`apply` is equivalent to
   ``function(*args, **keywords)``.

   .. deprecated:: 2.3
      Use ``function(*args, **keywords)`` instead of
      ``apply(function, args, keywords)`` (see :ref:`tut-unpacking-arguments`).


.. function:: buffer(object[, offset[, size]])

   The *object* argument must be an object that supports the buffer call interface
   (such as strings, arrays, and buffers).  A new buffer object will be created
   which references the *object* argument. The buffer object will be a slice from
   the beginning of *object* (or from the specified *offset*). The slice will
   extend to the end of *object* (or will have a length given by the *size*
   argument).


.. function:: coerce(x, y)

   Return a tuple consisting of the two numeric arguments converted to a common
   type, using the same rules as used by arithmetic operations. If coercion is not
   possible, raise :exc:`TypeError`.


.. function:: intern(string)

   Enter *string* in the table of "interned" strings and return the interned string
   -- which is *string* itself or a copy. Interning strings is useful to gain a
   little performance on dictionary lookup -- if the keys in a dictionary are
   interned, and the lookup key is interned, the key comparisons (after hashing)
   can be done by a pointer compare instead of a string compare.  Normally, the
   names used in Python programs are automatically interned, and the dictionaries
   used to hold module, class or instance attributes have interned keys.

   .. versionchanged:: 2.3
      Interned strings are not immortal (like they used to be in Python 2.2 and
      before); you must keep a reference to the return value of :func:`intern` around
      to benefit from it.

.. rubric:: Footnotes

.. [#] It is used relatively rarely so does not warrant being made into a statement.

.. [#] Specifying a buffer size currently has no effect on systems that don't have
   :c:func:`setvbuf`.  The interface to specify the buffer size is not done using a
   method that calls :c:func:`setvbuf`, because that may dump core when called after
   any I/O has been performed, and there's no reliable way to determine whether
   this is the case.

.. [#] In the current implementation, local variable bindings cannot normally be
   affected this way, but variables retrieved from other scopes (such as modules)
   can be.  This may change.
PK	%�\�~a'html/_sources/library/functools.rst.txtnu�[���:mod:`functools` --- Higher-order functions and operations on callable objects
==============================================================================

.. module:: functools
   :synopsis: Higher-order functions and operations on callable objects.
.. moduleauthor:: Peter Harris <scav@blueyonder.co.uk>
.. moduleauthor:: Raymond Hettinger <python@rcn.com>
.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>

.. versionadded:: 2.5

**Source code:** :source:`Lib/functools.py`

--------------

The :mod:`functools` module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.

The :mod:`functools` module defines the following functions:

..  function:: cmp_to_key(func)

   Transform an old-style comparison function to a :term:`key function`.  Used
   with tools that accept key functions (such as :func:`sorted`, :func:`min`,
   :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
   :func:`itertools.groupby`).  This function is primarily used as a transition
   tool for programs being converted to Python 3 where comparison functions are
   no longer supported.

   A comparison function is any callable that accept two arguments, compares them,
   and returns a negative number for less-than, zero for equality, or a positive
   number for greater-than.  A key function is a callable that accepts one
   argument and returns another value to be used as the sort key.

   Example::

       sorted(iterable, key=cmp_to_key(locale.strcoll))  # locale-aware sort order

   For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`.


   .. versionadded:: 2.7

.. function:: total_ordering(cls)

   Given a class defining one or more rich comparison ordering methods, this
   class decorator supplies the rest.  This simplifies the effort involved
   in specifying all of the possible rich comparison operations:

   The class must define one of :meth:`__lt__`, :meth:`__le__`,
   :meth:`__gt__`, or :meth:`__ge__`.
   In addition, the class should supply an :meth:`__eq__` method.

   For example::

       @total_ordering
       class Student:
           def __eq__(self, other):
               return ((self.lastname.lower(), self.firstname.lower()) ==
                       (other.lastname.lower(), other.firstname.lower()))
           def __lt__(self, other):
               return ((self.lastname.lower(), self.firstname.lower()) <
                       (other.lastname.lower(), other.firstname.lower()))

   .. versionadded:: 2.7

.. function:: reduce(function, iterable[, initializer])

   This is the same function as :func:`reduce`.  It is made available in this module
   to allow writing code more forward-compatible with Python 3.

   .. versionadded:: 2.6


.. function:: partial(func[,*args][, **keywords])

   Return a new :ref:`partial object<partial-objects>` which when called will behave
   like *func* called with the positional arguments *args* and keyword arguments *keywords*.
   If more arguments are supplied to the call, they are appended to *args*. If
   additional keyword arguments are supplied, they extend and override *keywords*.
   Roughly equivalent to::

      def partial(func, *args, **keywords):
          def newfunc(*fargs, **fkeywords):
              newkeywords = keywords.copy()
              newkeywords.update(fkeywords)
              return func(*(args + fargs), **newkeywords)
          newfunc.func = func
          newfunc.args = args
          newfunc.keywords = keywords
          return newfunc

   The :func:`partial` is used for partial function application which "freezes"
   some portion of a function's arguments and/or keywords resulting in a new object
   with a simplified signature.  For example, :func:`partial` can be used to create
   a callable that behaves like the :func:`int` function where the *base* argument
   defaults to two:

      >>> from functools import partial
      >>> basetwo = partial(int, base=2)
      >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
      >>> basetwo('10010')
      18


.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])

   Update a *wrapper* function to look like the *wrapped* function. The optional
   arguments are tuples to specify which attributes of the original function are
   assigned directly to the matching attributes on the wrapper function and which
   attributes of the wrapper function are updated with the corresponding attributes
   from the original function. The default values for these arguments are the
   module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
   function's *__name__*, *__module__* and *__doc__*, the documentation string) and
   *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
   instance dictionary).

   The main intended use for this function is in :term:`decorator` functions which
   wrap the decorated function and return the wrapper. If the wrapper function is
   not updated, the metadata of the returned function will reflect the wrapper
   definition rather than the original function definition, which is typically less
   than helpful.


.. function:: wraps(wrapped[, assigned][, updated])

   This is a convenience function for invoking :func:`update_wrapper` as a
   function decorator when defining a wrapper function.  It is equivalent to
   ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
   For example::

      >>> from functools import wraps
      >>> def my_decorator(f):
      ...     @wraps(f)
      ...     def wrapper(*args, **kwds):
      ...         print 'Calling decorated function'
      ...         return f(*args, **kwds)
      ...     return wrapper
      ...
      >>> @my_decorator
      ... def example():
      ...     """Docstring"""
      ...     print 'Called example function'
      ...
      >>> example()
      Calling decorated function
      Called example function
      >>> example.__name__
      'example'
      >>> example.__doc__
      'Docstring'

   Without the use of this decorator factory, the name of the example function
   would have been ``'wrapper'``, and the docstring of the original :func:`example`
   would have been lost.


.. _partial-objects:

:class:`partial` Objects
------------------------

:class:`partial` objects are callable objects created by :func:`partial`. They
have three read-only attributes:


.. attribute:: partial.func

   A callable object or function.  Calls to the :class:`partial` object will be
   forwarded to :attr:`func` with new arguments and keywords.


.. attribute:: partial.args

   The leftmost positional arguments that will be prepended to the positional
   arguments provided to a :class:`partial` object call.


.. attribute:: partial.keywords

   The keyword arguments that will be supplied when the :class:`partial` object is
   called.

:class:`partial` objects are like :class:`function` objects in that they are
callable, weak referencable, and can have attributes.  There are some important
differences.  For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes
are not created automatically.  Also, :class:`partial` objects defined in
classes behave like static methods and do not transform into bound methods
during instance attribute look-up.

PK	%�\VW���-html/_sources/library/future_builtins.rst.txtnu�[���:mod:`future_builtins` --- Python 3 builtins
============================================

.. module:: future_builtins
.. sectionauthor:: Georg Brandl
.. versionadded:: 2.6

This module provides functions that exist in 2.x, but have different behavior in
Python 3, so they cannot be put into the 2.x builtins namespace.

Instead, if you want to write code compatible with Python 3 builtins, import
them from this module, like this::

   from future_builtins import map, filter

   ... code using Python 3-style map and filter ...

The :term:`2to3` tool that ports Python 2 code to Python 3 will recognize
this usage and leave the new builtins alone.

.. note::

   The Python 3 :func:`print` function is already in the builtins, but cannot be
   accessed from Python 2 code unless you use the appropriate future statement::

      from __future__ import print_function


Available builtins are:

.. function:: ascii(object)

   Returns the same as :func:`repr`.  In Python 3, :func:`repr` will return
   printable Unicode characters unescaped, while :func:`ascii` will always
   backslash-escape them.  Using :func:`future_builtins.ascii` instead of
   :func:`repr` in 2.6 code makes it clear that you need a pure ASCII return
   value.

.. function:: filter(function, iterable)

   Works like :func:`itertools.ifilter`.

.. function:: hex(object)

   Works like the built-in :func:`hex`, but instead of :meth:`__hex__` it will
   use the :meth:`__index__` method on its argument to get an integer that is
   then converted to hexadecimal.

.. function:: map(function, iterable, ...)

   Works like :func:`itertools.imap`.

   .. note::

      In Python 3, :func:`map` does not accept ``None`` for the
      function argument.

.. function:: oct(object)

   Works like the built-in :func:`oct`, but instead of :meth:`__oct__` it will
   use the :meth:`__index__` method on its argument to get an integer that is
   then converted to octal.

.. function:: zip(*iterables)

   Works like :func:`itertools.izip`.
PK	%�\��6#6# html/_sources/library/gc.rst.txtnu�[���
:mod:`gc` --- Garbage Collector interface
=========================================

.. module:: gc
   :synopsis: Interface to the cycle-detecting garbage collector.
.. moduleauthor:: Neil Schemenauer <nas@arctrix.com>
.. sectionauthor:: Neil Schemenauer <nas@arctrix.com>


This module provides an interface to the optional garbage collector.  It
provides the ability to disable the collector, tune the collection frequency,
and set debugging options.  It also provides access to unreachable objects that
the collector found but cannot free.  Since the collector supplements the
reference counting already used in Python, you can disable the collector if you
are sure your program does not create reference cycles.  Automatic collection
can be disabled by calling ``gc.disable()``.  To debug a leaking program call
``gc.set_debug(gc.DEBUG_LEAK)``. Notice that this includes
``gc.DEBUG_SAVEALL``, causing garbage-collected objects to be saved in
gc.garbage for inspection.

The :mod:`gc` module provides the following functions:


.. function:: enable()

   Enable automatic garbage collection.


.. function:: disable()

   Disable automatic garbage collection.


.. function:: isenabled()

   Returns true if automatic collection is enabled.


.. function:: collect([generation])

   With no arguments, run a full collection.  The optional argument *generation*
   may be an integer specifying which generation to collect (from 0 to 2).  A
   :exc:`ValueError` is raised if the generation number  is invalid. The number of
   unreachable objects found is returned.

   .. versionchanged:: 2.5
      The optional *generation* argument was added.

   .. versionchanged:: 2.6
      The free lists maintained for a number of built-in types are cleared
      whenever a full collection or collection of the highest generation (2)
      is run.  Not all items in some free lists may be freed due to the
      particular implementation, in particular :class:`int` and :class:`float`.


.. function:: set_debug(flags)

   Set the garbage collection debugging flags. Debugging information will be
   written to ``sys.stderr``.  See below for a list of debugging flags which can be
   combined using bit operations to control debugging.


.. function:: get_debug()

   Return the debugging flags currently set.


.. function:: get_objects()

   Returns a list of all objects tracked by the collector, excluding the list
   returned.

   .. versionadded:: 2.2


.. function:: set_threshold(threshold0[, threshold1[, threshold2]])

   Set the garbage collection thresholds (the collection frequency). Setting
   *threshold0* to zero disables collection.

   The GC classifies objects into three generations depending on how many
   collection sweeps they have survived.  New objects are placed in the youngest
   generation (generation ``0``).  If an object survives a collection it is moved
   into the next older generation.  Since generation ``2`` is the oldest
   generation, objects in that generation remain there after a collection.  In
   order to decide when to run, the collector keeps track of the number object
   allocations and deallocations since the last collection.  When the number of
   allocations minus the number of deallocations exceeds *threshold0*, collection
   starts.  Initially only generation ``0`` is examined.  If generation ``0`` has
   been examined more than *threshold1* times since generation ``1`` has been
   examined, then generation ``1`` is examined as well.  Similarly, *threshold2*
   controls the number of collections of generation ``1`` before collecting
   generation ``2``.


.. function:: get_count()

   Return the current collection  counts as a tuple of ``(count0, count1,
   count2)``.

   .. versionadded:: 2.5


.. function:: get_threshold()

   Return the current collection thresholds as a tuple of ``(threshold0,
   threshold1, threshold2)``.


.. function:: get_referrers(*objs)

   Return the list of objects that directly refer to any of objs. This function
   will only locate those containers which support garbage collection; extension
   types which do refer to other objects but do not support garbage collection will
   not be found.

   Note that objects which have already been dereferenced, but which live in cycles
   and have not yet been collected by the garbage collector can be listed among the
   resulting referrers.  To get only currently live objects, call :func:`collect`
   before calling :func:`get_referrers`.

   Care must be taken when using objects returned by :func:`get_referrers` because
   some of them could still be under construction and hence in a temporarily
   invalid state. Avoid using :func:`get_referrers` for any purpose other than
   debugging.

   .. versionadded:: 2.2


.. function:: get_referents(*objs)

   Return a list of objects directly referred to by any of the arguments. The
   referents returned are those objects visited by the arguments' C-level
   :c:member:`~PyTypeObject.tp_traverse` methods (if any), and may not be all objects actually
   directly reachable.  :c:member:`~PyTypeObject.tp_traverse` methods are supported only by objects
   that support garbage collection, and are only required to visit objects that may
   be involved in a cycle.  So, for example, if an integer is directly reachable
   from an argument, that integer object may or may not appear in the result list.

   .. versionadded:: 2.3

.. function:: is_tracked(obj)

   Returns ``True`` if the object is currently tracked by the garbage collector,
   ``False`` otherwise.  As a general rule, instances of atomic types aren't
   tracked and instances of non-atomic types (containers, user-defined
   objects...) are.  However, some type-specific optimizations can be present
   in order to suppress the garbage collector footprint of simple instances
   (e.g. dicts containing only atomic keys and values)::

      >>> gc.is_tracked(0)
      False
      >>> gc.is_tracked("a")
      False
      >>> gc.is_tracked([])
      True
      >>> gc.is_tracked({})
      False
      >>> gc.is_tracked({"a": 1})
      False
      >>> gc.is_tracked({"a": []})
      True

   .. versionadded:: 2.7


The following variable is provided for read-only access (you can mutate its
value but should not rebind it):


.. data:: garbage

   A list of objects which the collector found to be unreachable but could not be
   freed (uncollectable objects).  By default, this list contains only objects with
   :meth:`__del__` methods. [#]_ Objects that have :meth:`__del__` methods and are
   part of a reference cycle cause the entire reference cycle to be uncollectable,
   including objects not necessarily in the cycle but reachable only from it.
   Python doesn't collect such cycles automatically because, in general, it isn't
   possible for Python to guess a safe order in which to run the :meth:`__del__`
   methods.  If you know a safe order, you can force the issue by examining the
   *garbage* list, and explicitly breaking cycles due to your objects within the
   list.  Note that these objects are kept alive even so by virtue of being in the
   *garbage* list, so they should be removed from *garbage* too.  For example,
   after breaking cycles, do ``del gc.garbage[:]`` to empty the list.  It's
   generally better to avoid the issue by not creating cycles containing objects
   with :meth:`__del__` methods, and *garbage* can be examined in that case to
   verify that no such cycles are being created.

   If :const:`DEBUG_SAVEALL` is set, then all unreachable objects will be added to
   this list rather than freed.

The following constants are provided for use with :func:`set_debug`:


.. data:: DEBUG_STATS

   Print statistics during collection.  This information can be useful when tuning
   the collection frequency.


.. data:: DEBUG_COLLECTABLE

   Print information on collectable objects found.


.. data:: DEBUG_UNCOLLECTABLE

   Print information of uncollectable objects found (objects which are not
   reachable but cannot be freed by the collector).  These objects will be added to
   the ``garbage`` list.


.. data:: DEBUG_INSTANCES

   When :const:`DEBUG_COLLECTABLE` or :const:`DEBUG_UNCOLLECTABLE` is set, print
   information about instance objects found.


.. data:: DEBUG_OBJECTS

   When :const:`DEBUG_COLLECTABLE` or :const:`DEBUG_UNCOLLECTABLE` is set, print
   information about objects other than instance objects found.


.. data:: DEBUG_SAVEALL

   When set, all unreachable objects found will be appended to *garbage* rather
   than being freed.  This can be useful for debugging a leaking program.


.. data:: DEBUG_LEAK

   The debugging flags necessary for the collector to print information about a
   leaking program (equal to ``DEBUG_COLLECTABLE | DEBUG_UNCOLLECTABLE |
   DEBUG_INSTANCES | DEBUG_OBJECTS | DEBUG_SAVEALL``).

.. rubric:: Footnotes

.. [#] Prior to Python 2.2, the list contained all instance objects in unreachable
   cycles,  not only those with :meth:`__del__` methods.

PK	%�\��>1"html/_sources/library/gdbm.rst.txtnu�[���:mod:`gdbm` --- GNU's reinterpretation of dbm
=============================================

.. module:: gdbm
   :platform: Unix
   :synopsis: GNU's reinterpretation of dbm.

.. note::
   The :mod:`gdbm` module has been renamed to :mod:`dbm.gnu` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.


.. index:: module: dbm

This module is quite similar to the :mod:`dbm` module, but uses ``gdbm`` instead
to provide some additional functionality.  Please note that the file formats
created by ``gdbm`` and ``dbm`` are incompatible.

The :mod:`gdbm` module provides an interface to the GNU DBM library.  ``gdbm``
objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a ``gdbm`` object doesn't print the keys and values,
and the :meth:`items` and :meth:`values` methods are not supported.

The module defines the following constant and functions:


.. exception:: error

   Raised on ``gdbm``\ -specific errors, such as I/O errors. :exc:`KeyError` is
   raised for general mapping errors like specifying an incorrect key.


.. function:: open(filename, [flag, [mode]])

   Open a ``gdbm`` database and return a ``gdbm`` object.  The *filename* argument
   is the name of the database file.

   The optional *flag* argument can be:

   +---------+-------------------------------------------+
   | Value   | Meaning                                   |
   +=========+===========================================+
   | ``'r'`` | Open existing database for reading only   |
   |         | (default)                                 |
   +---------+-------------------------------------------+
   | ``'w'`` | Open existing database for reading and    |
   |         | writing                                   |
   +---------+-------------------------------------------+
   | ``'c'`` | Open database for reading and writing,    |
   |         | creating it if it doesn't exist           |
   +---------+-------------------------------------------+
   | ``'n'`` | Always create a new, empty database, open |
   |         | for reading and writing                   |
   +---------+-------------------------------------------+

   The following additional characters may be appended to the flag to control
   how the database is opened:

   +---------+--------------------------------------------+
   | Value   | Meaning                                    |
   +=========+============================================+
   | ``'f'`` | Open the database in fast mode.  Writes    |
   |         | to the database will not be synchronized.  |
   +---------+--------------------------------------------+
   | ``'s'`` | Synchronized mode. This will cause changes |
   |         | to the database to be immediately written  |
   |         | to the file.                               |
   +---------+--------------------------------------------+
   | ``'u'`` | Do not lock database.                      |
   +---------+--------------------------------------------+

   Not all flags are valid for all versions of ``gdbm``.  The module constant
   :const:`open_flags` is a string of supported flag characters.  The exception
   :exc:`error` is raised if an invalid flag is specified.

   The optional *mode* argument is the Unix mode of the file, used only when the
   database has to be created.  It defaults to octal ``0666``.

In addition to the dictionary-like methods, ``gdbm`` objects have the following
methods:


.. function:: firstkey()

   It's possible to loop over every key in the database using this method  and the
   :meth:`nextkey` method.  The traversal is ordered by ``gdbm``'s internal hash
   values, and won't be sorted by the key values.  This method returns the starting
   key.


.. function:: nextkey(key)

   Returns the key that follows *key* in the traversal.  The following code prints
   every key in the database ``db``, without having to create a list in memory that
   contains them all::

      k = db.firstkey()
      while k != None:
          print k
          k = db.nextkey(k)


.. function:: reorganize()

   If you have carried out a lot of deletions and would like to shrink the space
   used by the ``gdbm`` file, this routine will reorganize the database.  ``gdbm``
   will not shorten the length of a database file except by using this
   reorganization; otherwise, deleted file space will be kept and reused as new
   (key, value) pairs are added.


.. function:: sync()

   When the database has been opened in fast mode, this method forces any
   unwritten data to be written to the disk.


.. function:: close()

   Close the ``gdbm`` database.


.. seealso::

   Module :mod:`anydbm`
      Generic interface to ``dbm``\ -style databases.

   Module :mod:`whichdb`
      Utility module used to determine the type of an existing database.

PK	%�\���')),html/_sources/library/gensuitemodule.rst.txtnu�[���
:mod:`gensuitemodule` --- Generate OSA stub packages
====================================================

.. module:: gensuitemodule
   :platform: Mac
   :synopsis: Create a stub package from an OSA dictionary
.. sectionauthor:: Jack Jansen <Jack.Jansen@cwi.nl>
.. moduleauthor:: Jack Jansen

The :mod:`gensuitemodule` module creates a Python package implementing stub code
for the AppleScript suites that are implemented by a specific application,
according to its AppleScript dictionary.

It is usually invoked by the user through the :program:`PythonIDE`, but it can
also be run as a script from the command line (pass :option:`--help` for help on
the options) or imported from Python code. For an example of its use see
:file:`Mac/scripts/genallsuites.py` in a source distribution, which generates
the stub packages that are included in the standard library.

It defines the following public functions:


.. function:: is_scriptable(application)

   Returns true if ``application``, which should be passed as a pathname, appears
   to be scriptable. Take the return value with a grain of salt: :program:`Internet
   Explorer` appears not to be scriptable but definitely is.


.. function:: processfile(application[, output, basepkgname,  edit_modnames, creatorsignature, dump, verbose])

   Create a stub package for ``application``, which should be passed as a full
   pathname. For a :file:`.app` bundle this is the pathname to the bundle, not to
   the executable inside the bundle; for an unbundled CFM application you pass the
   filename of the application binary.

   This function asks the application for its OSA terminology resources, decodes
   these resources and uses the resultant data to create the Python code for the
   package implementing the client stubs.

   ``output`` is the pathname where the resulting package is stored, if not
   specified a standard "save file as" dialog is presented to the user.
   ``basepkgname`` is the base package on which this package will build, and
   defaults to :mod:`StdSuites`. Only when generating :mod:`StdSuites` itself do
   you need to specify this. ``edit_modnames`` is a dictionary that can be used to
   change modulenames that are too ugly after name mangling. ``creator_signature``
   can be used to override the 4-char creator code, which is normally obtained from
   the :file:`PkgInfo` file in the package or from the CFM file creator signature.
   When ``dump`` is given it should refer to a file object, and ``processfile``
   will stop after decoding the resources and dump the Python representation of the
   terminology resources to this file. ``verbose`` should also be a file object,
   and specifying it will cause ``processfile`` to tell you what it is doing.


.. function:: processfile_fromresource(application[, output,  basepkgname, edit_modnames, creatorsignature, dump, verbose])

   This function does the same as ``processfile``, except that it uses a different
   method to get the terminology resources. It opens ``application`` as a resource
   file and reads all ``"aete"`` and ``"aeut"`` resources from this file.

PK	%�\��D�$html/_sources/library/getopt.rst.txtnu�[���:mod:`getopt` --- C-style parser for command line options
=========================================================

.. module:: getopt
   :synopsis: Portable parser for command line options; support both short and long option
              names.

**Source code:** :source:`Lib/getopt.py`

--------------

.. note::

   The :mod:`getopt` module is a parser for command line options whose API is
   designed to be familiar to users of the C :c:func:`getopt` function. Users who
   are unfamiliar with the C :c:func:`getopt` function or who would like to write
   less code and get better help and error messages should consider using the
   :mod:`argparse` module instead.

This module helps scripts to parse the command line arguments in ``sys.argv``.
It supports the same conventions as the Unix :c:func:`getopt` function (including
the special meanings of arguments of the form '``-``' and '``--``').  Long
options similar to those supported by GNU software may be used as well via an
optional third argument.

This module provides two functions and an
exception:


.. function:: getopt(args, options[, long_options])

   Parses command line options and parameter list.  *args* is the argument list to
   be parsed, without the leading reference to the running program. Typically, this
   means ``sys.argv[1:]``. *options* is the string of option letters that the
   script wants to recognize, with options that require an argument followed by a
   colon (``':'``; i.e., the same format that Unix :c:func:`getopt` uses).

   .. note::

      Unlike GNU :c:func:`getopt`, after a non-option argument, all further
      arguments are considered also non-options. This is similar to the way
      non-GNU Unix systems work.

   *long_options*, if specified, must be a list of strings with the names of the
   long options which should be supported.  The leading ``'--'``
   characters should not be included in the option name.  Long options which
   require an argument should be followed by an equal sign (``'='``).  Optional
   arguments are not supported.  To accept only long options, *options* should
   be an empty string.  Long options on the command line can be recognized so
   long as they provide a prefix of the option name that matches exactly one of
   the accepted options.  For example, if *long_options* is ``['foo', 'frob']``,
   the option ``--fo`` will match as ``--foo``, but ``--f``
   will not match uniquely, so :exc:`GetoptError` will be raised.

   The return value consists of two elements: the first is a list of ``(option,
   value)`` pairs; the second is the list of program arguments left after the
   option list was stripped (this is a trailing slice of *args*).  Each
   option-and-value pair returned has the option as its first element, prefixed
   with a hyphen for short options (e.g., ``'-x'``) or two hyphens for long
   options (e.g., ``'--long-option'``), and the option argument as its
   second element, or an empty string if the option has no argument.  The
   options occur in the list in the same order in which they were found, thus
   allowing multiple occurrences.  Long and short options may be mixed.


.. function:: gnu_getopt(args, options[, long_options])

   This function works like :func:`getopt`, except that GNU style scanning mode is
   used by default. This means that option and non-option arguments may be
   intermixed. The :func:`getopt` function stops processing options as soon as a
   non-option argument is encountered.

   If the first character of the option string is ``'+'``, or if the environment
   variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
   soon as a non-option argument is encountered.

   .. versionadded:: 2.3


.. exception:: GetoptError

   This is raised when an unrecognized option is found in the argument list or when
   an option requiring an argument is given none. The argument to the exception is
   a string indicating the cause of the error.  For long options, an argument given
   to an option which does not require one will also cause this exception to be
   raised.  The attributes :attr:`msg` and :attr:`opt` give the error message and
   related option; if there is no specific option to which the exception relates,
   :attr:`opt` is an empty string.

   .. versionchanged:: 1.6
      Introduced :exc:`GetoptError` as a synonym for :exc:`error`.


.. exception:: error

   Alias for :exc:`GetoptError`; for backward compatibility.

An example using only Unix style options:

   >>> import getopt
   >>> args = '-a -b -cfoo -d bar a1 a2'.split()
   >>> args
   ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
   >>> optlist, args = getopt.getopt(args, 'abc:d:')
   >>> optlist
   [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
   >>> args
   ['a1', 'a2']

Using long option names is equally easy:

   >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
   >>> args = s.split()
   >>> args
   ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
   >>> optlist, args = getopt.getopt(args, 'x', [
   ...     'condition=', 'output-file=', 'testing'])
   >>> optlist
   [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
   >>> args
   ['a1', 'a2']

In a script, typical usage is something like this::

   import getopt, sys

   def main():
       try:
           opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
       except getopt.GetoptError as err:
           # print help information and exit:
           print str(err)  # will print something like "option -a not recognized"
           usage()
           sys.exit(2)
       output = None
       verbose = False
       for o, a in opts:
           if o == "-v":
               verbose = True
           elif o in ("-h", "--help"):
               usage()
               sys.exit()
           elif o in ("-o", "--output"):
               output = a
           else:
               assert False, "unhandled option"
       # ...

   if __name__ == "__main__":
       main()

Note that an equivalent command line interface could be produced with less code
and more informative help and error messages by using the :mod:`argparse` module::

   import argparse

   if __name__ == '__main__':
       parser = argparse.ArgumentParser()
       parser.add_argument('-o', '--output')
       parser.add_argument('-v', dest='verbose', action='store_true')
       args = parser.parse_args()
       # ... do something with args.output ...
       # ... do something with args.verbose ..

.. seealso::

   Module :mod:`argparse`
      Alternative command line option and argument parsing library.

PK	%�\�~�TT%html/_sources/library/getpass.rst.txtnu�[���:mod:`getpass` --- Portable password input
==========================================

.. module:: getpass
   :synopsis: Portable reading of passwords and retrieval of the userid.
.. moduleauthor:: Piers Lauder <piers@cs.su.oz.au>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. Windows (& Mac?) support by Guido van Rossum.

The :mod:`getpass` module provides two functions:


.. function:: getpass([prompt[, stream]])

   Prompt the user for a password without echoing.  The user is prompted using the
   string *prompt*, which defaults to ``'Password: '``. On Unix, the prompt is
   written to the file-like object *stream*.  *stream* defaults to the
   controlling terminal (/dev/tty) or if that is unavailable to ``sys.stderr``
   (this argument is ignored on Windows).

   If echo free input is unavailable getpass() falls back to printing
   a warning message to *stream* and reading from ``sys.stdin`` and
   issuing a :exc:`GetPassWarning`.

   .. versionchanged:: 2.5
      The *stream* parameter was added.
   .. versionchanged:: 2.6
      On Unix it defaults to using /dev/tty before falling back
      to ``sys.stdin`` and ``sys.stderr``.
   .. note::
      If you call getpass from within IDLE, the input may be done in the
      terminal you launched IDLE from rather than the idle window itself.


.. exception:: GetPassWarning

   A :exc:`UserWarning` subclass issued when password input may be echoed.


.. function:: getuser()

   Return the "login name" of the user.

   This function checks the environment variables :envvar:`LOGNAME`,
   :envvar:`USER`, :envvar:`LNAME` and :envvar:`USERNAME`, in order, and returns
   the value of the first one which is set to a non-empty string.  If none are set,
   the login name from the password database is returned on systems which support
   the :mod:`pwd` module, otherwise, an exception is raised.

PK	%�\���&pqpq%html/_sources/library/gettext.rst.txtnu�[���:mod:`gettext` --- Multilingual internationalization services
=============================================================

.. module:: gettext
   :synopsis: Multilingual internationalization services.
.. moduleauthor:: Barry A. Warsaw <barry@zope.com>
.. sectionauthor:: Barry A. Warsaw <barry@zope.com>

**Source code:** :source:`Lib/gettext.py`

--------------

The :mod:`gettext` module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
GNU ``gettext`` message catalog API and a higher level, class-based API that may
be more appropriate for Python files.  The interface described below allows you
to write your module and application messages in one natural language, and
provide a catalog of translated messages for running under different natural
languages.

Some hints on localizing your Python modules and applications are also given.


GNU :program:`gettext` API
--------------------------

The :mod:`gettext` module defines the following API, which is very similar to
the GNU :program:`gettext` API.  If you use this API you will affect the
translation of your entire application globally.  Often this is what you want if
your application is monolingual, with the choice of language dependent on the
locale of your user.  If you are localizing a Python module, or if your
application needs to switch languages on the fly, you probably want to use the
class-based API instead.


.. function:: bindtextdomain(domain[, localedir])

   Bind the *domain* to the locale directory *localedir*.  More concretely,
   :mod:`gettext` will look for binary :file:`.mo` files for the given domain using
   the path (on Unix): :file:`localedir/language/LC_MESSAGES/domain.mo`, where
   *languages* is searched for in the environment variables :envvar:`LANGUAGE`,
   :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and :envvar:`LANG` respectively.

   If *localedir* is omitted or ``None``, then the current binding for *domain* is
   returned. [#]_


.. function:: bind_textdomain_codeset(domain[, codeset])

   Bind the *domain* to *codeset*, changing the encoding of strings returned by the
   :func:`gettext` family of functions. If *codeset* is omitted, then the current
   binding is returned.

   .. versionadded:: 2.4


.. function:: textdomain([domain])

   Change or query the current global domain.  If *domain* is ``None``, then the
   current global domain is returned, otherwise the global domain is set to
   *domain*, which is returned.


.. function:: gettext(message)

   Return the localized translation of *message*, based on the current global
   domain, language, and locale directory.  This function is usually aliased as
   :func:`_` in the local namespace (see examples below).


.. function:: lgettext(message)

   Equivalent to :func:`gettext`, but the translation is returned in the preferred
   system encoding, if no other encoding was explicitly set with
   :func:`bind_textdomain_codeset`.

   .. versionadded:: 2.4


.. function:: dgettext(domain, message)

   Like :func:`gettext`, but look the message up in the specified *domain*.


.. function:: ldgettext(domain, message)

   Equivalent to :func:`dgettext`, but the translation is returned in the preferred
   system encoding, if no other encoding was explicitly set with
   :func:`bind_textdomain_codeset`.

   .. versionadded:: 2.4


.. function:: ngettext(singular, plural, n)

   Like :func:`gettext`, but consider plural forms. If a translation is found,
   apply the plural formula to *n*, and return the resulting message (some
   languages have more than two plural forms). If no translation is found, return
   *singular* if *n* is 1; return *plural* otherwise.

   The Plural formula is taken from the catalog header. It is a C or Python
   expression that has a free variable *n*; the expression evaluates to the index
   of the plural in the catalog. See the GNU gettext documentation for the precise
   syntax to be used in :file:`.po` files and the formulas for a variety of
   languages.

   .. versionadded:: 2.3


.. function:: lngettext(singular, plural, n)

   Equivalent to :func:`ngettext`, but the translation is returned in the preferred
   system encoding, if no other encoding was explicitly set with
   :func:`bind_textdomain_codeset`.

   .. versionadded:: 2.4


.. function:: dngettext(domain, singular, plural, n)

   Like :func:`ngettext`, but look the message up in the specified *domain*.

   .. versionadded:: 2.3


.. function:: ldngettext(domain, singular, plural, n)

   Equivalent to :func:`dngettext`, but the translation is returned in the
   preferred system encoding, if no other encoding was explicitly set with
   :func:`bind_textdomain_codeset`.

   .. versionadded:: 2.4

Note that GNU :program:`gettext` also defines a :func:`dcgettext` method, but
this was deemed not useful and so it is currently unimplemented.

Here's an example of typical usage for this API::

   import gettext
   gettext.bindtextdomain('myapplication', '/path/to/my/language/directory')
   gettext.textdomain('myapplication')
   _ = gettext.gettext
   # ...
   print _('This is a translatable string.')


Class-based API
---------------

The class-based API of the :mod:`gettext` module gives you more flexibility and
greater convenience than the GNU :program:`gettext` API.  It is the recommended
way of localizing your Python applications and modules.  :mod:`!gettext` defines
a "translations" class which implements the parsing of GNU :file:`.mo` format
files, and has methods for returning either standard 8-bit strings or Unicode
strings. Instances of this "translations" class can also install themselves  in
the built-in namespace as the function :func:`_`.


.. function:: find(domain[, localedir[,  languages[, all]]])

   This function implements the standard :file:`.mo` file search algorithm.  It
   takes a *domain*, identical to what :func:`textdomain` takes.  Optional
   *localedir* is as in :func:`bindtextdomain`  Optional *languages* is a list of
   strings, where each string is a language code.

   If *localedir* is not given, then the default system locale directory is used.
   [#]_  If *languages* is not given, then the following environment variables are
   searched: :envvar:`LANGUAGE`, :envvar:`LC_ALL`, :envvar:`LC_MESSAGES`, and
   :envvar:`LANG`.  The first one returning a non-empty value is used for the
   *languages* variable. The environment variables should contain a colon separated
   list of languages, which will be split on the colon to produce the expected list
   of language code strings.

   :func:`find` then expands and normalizes the languages, and then iterates
   through them, searching for an existing file built of these components:

   :file:`localedir/language/LC_MESSAGES/domain.mo`

   The first such file name that exists is returned by :func:`find`. If no such
   file is found, then ``None`` is returned. If *all* is given, it returns a list
   of all file names, in the order in which they appear in the languages list or
   the environment variables.


.. function:: translation(domain[, localedir[, languages[, class_[, fallback[, codeset]]]]])

   Return a :class:`Translations` instance based on the *domain*, *localedir*, and
   *languages*, which are first passed to :func:`find` to get a list of the
   associated :file:`.mo` file paths.  Instances with identical :file:`.mo` file
   names are cached.  The actual class instantiated is either *class_* if provided,
   otherwise :class:`GNUTranslations`.  The class's constructor must take a single
   file object argument. If provided, *codeset* will change the charset used to
   encode translated strings.

   If multiple files are found, later files are used as fallbacks for earlier ones.
   To allow setting the fallback, :func:`copy.copy` is used to clone each
   translation object from the cache; the actual instance data is still shared with
   the cache.

   If no :file:`.mo` file is found, this function raises :exc:`IOError` if
   *fallback* is false (which is the default), and returns a
   :class:`NullTranslations` instance if *fallback* is true.

   .. versionchanged:: 2.4
      Added the *codeset* parameter.


.. function:: install(domain[, localedir[, unicode [, codeset[, names]]]])

   This installs the function :func:`_` in Python's builtins namespace, based on
   *domain*, *localedir*, and *codeset* which are passed to the function
   :func:`translation`.  The *unicode* flag is passed to the resulting translation
   object's :meth:`~NullTranslations.install` method.

   For the *names* parameter, please see the description of the translation
   object's :meth:`~NullTranslations.install` method.

   As seen below, you usually mark the strings in your application that are
   candidates for translation, by wrapping them in a call to the :func:`_`
   function, like this::

      print _('This string will be translated.')

   For convenience, you want the :func:`_` function to be installed in Python's
   builtins namespace, so it is easily accessible in all modules of your
   application.

   .. versionchanged:: 2.4
      Added the *codeset* parameter.

   .. versionchanged:: 2.5
      Added the *names* parameter.


The :class:`NullTranslations` class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Translation classes are what actually implement the translation of original
source file message strings to translated message strings. The base class used
by all translation classes is :class:`NullTranslations`; this provides the basic
interface you can use to write your own specialized translation classes.  Here
are the methods of :class:`!NullTranslations`:


.. class:: NullTranslations([fp])

   Takes an optional file object *fp*, which is ignored by the base class.
   Initializes "protected" instance variables *_info* and *_charset* which are set
   by derived classes, as well as *_fallback*, which is set through
   :meth:`add_fallback`.  It then calls ``self._parse(fp)`` if *fp* is not
   ``None``.


   .. method:: _parse(fp)

      No-op'd in the base class, this method takes file object *fp*, and reads
      the data from the file, initializing its message catalog.  If you have an
      unsupported message catalog file format, you should override this method
      to parse your format.


   .. method:: add_fallback(fallback)

      Add *fallback* as the fallback object for the current translation
      object. A translation object should consult the fallback if it cannot provide a
      translation for a given message.


   .. method:: gettext(message)

      If a fallback has been set, forward :meth:`!gettext` to the
      fallback. Otherwise, return the translated message.  Overridden in derived
      classes.


   .. method:: lgettext(message)

      If a fallback has been set, forward :meth:`!lgettext` to the
      fallback. Otherwise, return the translated message.  Overridden in derived
      classes.

      .. versionadded:: 2.4


   .. method:: ugettext(message)

      If a fallback has been set, forward :meth:`!ugettext` to the
      fallback. Otherwise, return the translated message as a Unicode
      string. Overridden in derived classes.


   .. method:: ngettext(singular, plural, n)

      If a fallback has been set, forward :meth:`!ngettext` to the
      fallback. Otherwise, return the translated message.  Overridden in derived
      classes.

      .. versionadded:: 2.3


   .. method:: lngettext(singular, plural, n)

      If a fallback has been set, forward :meth:`!lngettext` to the
      fallback. Otherwise, return the translated message.  Overridden in derived
      classes.

      .. versionadded:: 2.4


   .. method:: ungettext(singular, plural, n)

      If a fallback has been set, forward :meth:`!ungettext` to the fallback.
      Otherwise, return the translated message as a Unicode string. Overridden
      in derived classes.

      .. versionadded:: 2.3


   .. method:: info()

      Return the "protected" :attr:`_info` variable.


   .. method:: charset()

      Return the "protected" :attr:`_charset` variable.


   .. method:: output_charset()

      Return the "protected" :attr:`_output_charset` variable, which defines the
      encoding used to return translated messages.

      .. versionadded:: 2.4


   .. method:: set_output_charset(charset)

      Change the "protected" :attr:`_output_charset` variable, which defines the
      encoding used to return translated messages.

      .. versionadded:: 2.4


   .. method:: install([unicode [, names]])

      If the *unicode* flag is false, this method installs :meth:`self.gettext`
      into the built-in namespace, binding it to ``_``.  If *unicode* is true,
      it binds :meth:`self.ugettext` instead.  By default, *unicode* is false.

      If the *names* parameter is given, it must be a sequence containing the
      names of functions you want to install in the builtins namespace in
      addition to :func:`_`.  Supported names are ``'gettext'`` (bound to
      :meth:`self.gettext` or :meth:`self.ugettext` according to the *unicode*
      flag), ``'ngettext'`` (bound to :meth:`self.ngettext` or
      :meth:`self.ungettext` according to the *unicode* flag), ``'lgettext'``
      and ``'lngettext'``.

      Note that this is only one way, albeit the most convenient way, to make
      the :func:`_` function available to your application.  Because it affects
      the entire application globally, and specifically the built-in namespace,
      localized modules should never install :func:`_`. Instead, they should use
      this code to make :func:`_` available to their module::

         import gettext
         t = gettext.translation('mymodule', ...)
         _ = t.gettext

      This puts :func:`_` only in the module's global namespace and so only
      affects calls within this module.

      .. versionchanged:: 2.5
         Added the *names* parameter.


The :class:`GNUTranslations` class
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The :mod:`gettext` module provides one additional class derived from
:class:`NullTranslations`: :class:`GNUTranslations`.  This class overrides
:meth:`_parse` to enable reading GNU :program:`gettext` format :file:`.mo` files
in both big-endian and little-endian format. It also coerces both message ids
and message strings to Unicode.

:class:`GNUTranslations` parses optional meta-data out of the translation
catalog.  It is convention with GNU :program:`gettext` to include meta-data as
the translation for the empty string.  This meta-data is in :rfc:`822`\ -style
``key: value`` pairs, and should contain the ``Project-Id-Version`` key.  If the
key ``Content-Type`` is found, then the ``charset`` property is used to
initialize the "protected" :attr:`_charset` instance variable, defaulting to
``None`` if not found.  If the charset encoding is specified, then all message
ids and message strings read from the catalog are converted to Unicode using
this encoding.  The :meth:`ugettext` method always returns a Unicode, while the
:meth:`gettext` returns an encoded 8-bit string.  For the message id arguments
of both methods, either Unicode strings or 8-bit strings containing only
US-ASCII characters are acceptable.  Note that the Unicode version of the
methods (i.e. :meth:`ugettext` and :meth:`ungettext`) are the recommended
interface to use for internationalized Python programs.

The entire set of key/value pairs are placed into a dictionary and set as the
"protected" :attr:`_info` instance variable.

If the :file:`.mo` file's magic number is invalid, or if other problems occur
while reading the file, instantiating a :class:`GNUTranslations` class can raise
:exc:`IOError`.

The following methods are overridden from the base class implementation:


.. method:: GNUTranslations.gettext(message)

   Look up the *message* id in the catalog and return the corresponding message
   string, as an 8-bit string encoded with the catalog's charset encoding, if
   known.  If there is no entry in the catalog for the *message* id, and a fallback
   has been set, the look up is forwarded to the fallback's :meth:`gettext` method.
   Otherwise, the *message* id is returned.


.. method:: GNUTranslations.lgettext(message)

   Equivalent to :meth:`gettext`, but the translation is returned in the preferred
   system encoding, if no other encoding was explicitly set with
   :meth:`set_output_charset`.

   .. versionadded:: 2.4


.. method:: GNUTranslations.ugettext(message)

   Look up the *message* id in the catalog and return the corresponding message
   string, as a Unicode string.  If there is no entry in the catalog for the
   *message* id, and a fallback has been set, the look up is forwarded to the
   fallback's :meth:`ugettext` method.  Otherwise, the *message* id is returned.


.. method:: GNUTranslations.ngettext(singular, plural, n)

   Do a plural-forms lookup of a message id.  *singular* is used as the message id
   for purposes of lookup in the catalog, while *n* is used to determine which
   plural form to use.  The returned message string is an 8-bit string encoded with
   the catalog's charset encoding, if known.

   If the message id is not found in the catalog, and a fallback is specified, the
   request is forwarded to the fallback's :meth:`ngettext` method.  Otherwise, when
   *n* is 1 *singular* is returned, and *plural* is returned in all other cases.

   .. versionadded:: 2.3


.. method:: GNUTranslations.lngettext(singular, plural, n)

   Equivalent to :meth:`gettext`, but the translation is returned in the preferred
   system encoding, if no other encoding was explicitly set with
   :meth:`set_output_charset`.

   .. versionadded:: 2.4


.. method:: GNUTranslations.ungettext(singular, plural, n)

   Do a plural-forms lookup of a message id.  *singular* is used as the message id
   for purposes of lookup in the catalog, while *n* is used to determine which
   plural form to use.  The returned message string is a Unicode string.

   If the message id is not found in the catalog, and a fallback is specified, the
   request is forwarded to the fallback's :meth:`ungettext` method.  Otherwise,
   when *n* is 1 *singular* is returned, and *plural* is returned in all other
   cases.

   Here is an example::

      n = len(os.listdir('.'))
      cat = GNUTranslations(somefile)
      message = cat.ungettext(
          'There is %(num)d file in this directory',
          'There are %(num)d files in this directory',
          n) % {'num': n}

   .. versionadded:: 2.3


Solaris message catalog support
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The Solaris operating system defines its own binary :file:`.mo` file format, but
since no documentation can be found on this format, it is not supported at this
time.


The Catalog constructor
^^^^^^^^^^^^^^^^^^^^^^^

.. index:: single: GNOME

GNOME uses a version of the :mod:`gettext` module by James Henstridge, but this
version has a slightly different API.  Its documented usage was::

   import gettext
   cat = gettext.Catalog(domain, localedir)
   _ = cat.gettext
   print _('hello world')

For compatibility with this older module, the function :func:`Catalog` is an
alias for the :func:`translation` function described above.

One difference between this module and Henstridge's: his catalog objects
supported access through a mapping API, but this appears to be unused and so is
not currently supported.


Internationalizing your programs and modules
--------------------------------------------

Internationalization (I18N) refers to the operation by which a program is made
aware of multiple languages.  Localization (L10N) refers to the adaptation of
your program, once internationalized, to the local language and cultural habits.
In order to provide multilingual messages for your Python programs, you need to
take the following steps:

#. prepare your program or module by specially marking translatable strings

#. run a suite of tools over your marked files to generate raw messages catalogs

#. create language specific translations of the message catalogs

#. use the :mod:`gettext` module so that message strings are properly translated

In order to prepare your code for I18N, you need to look at all the strings in
your files.  Any string that needs to be translated should be marked by wrapping
it in ``_('...')`` --- that is, a call to the function :func:`_`.  For example::

   filename = 'mylog.txt'
   message = _('writing a log message')
   fp = open(filename, 'w')
   fp.write(message)
   fp.close()

In this example, the string ``'writing a log message'`` is marked as a candidate
for translation, while the strings ``'mylog.txt'`` and ``'w'`` are not.

The Python distribution comes with two tools which help you generate the message
catalogs once you've prepared your source code.  These may or may not be
available from a binary distribution, but they can be found in a source
distribution, in the :file:`Tools/i18n` directory.

The :program:`pygettext` [#]_ program scans all your Python source code looking
for the strings you previously marked as translatable.  It is similar to the GNU
:program:`gettext` program except that it understands all the intricacies of
Python source code, but knows nothing about C or C++ source code.  You don't
need GNU ``gettext`` unless you're also going to be translating C code (such as
C extension modules).

:program:`pygettext` generates textual Uniforum-style human readable message
catalog :file:`.pot` files, essentially structured human readable files which
contain every marked string in the source code, along with a placeholder for the
translation strings. :program:`pygettext` is a command line script that supports
a similar command line interface as :program:`xgettext`; for details on its use,
run::

   pygettext.py --help

Copies of these :file:`.pot` files are then handed over to the individual human
translators who write language-specific versions for every supported natural
language.  They send you back the filled in language-specific versions as a
:file:`.po` file.  Using the :program:`msgfmt.py` [#]_ program (in the
:file:`Tools/i18n` directory), you take the :file:`.po` files from your
translators and generate the machine-readable :file:`.mo` binary catalog files.
The :file:`.mo` files are what the :mod:`gettext` module uses for the actual
translation processing during run-time.

How you use the :mod:`gettext` module in your code depends on whether you are
internationalizing a single module or your entire application. The next two
sections will discuss each case.


Localizing your module
^^^^^^^^^^^^^^^^^^^^^^

If you are localizing your module, you must take care not to make global
changes, e.g. to the built-in namespace.  You should not use the GNU ``gettext``
API but instead the class-based API.

Let's say your module is called "spam" and the module's various natural language
translation :file:`.mo` files reside in :file:`/usr/share/locale` in GNU
:program:`gettext` format.  Here's what you would put at the top of your
module::

   import gettext
   t = gettext.translation('spam', '/usr/share/locale')
   _ = t.lgettext

If your translators were providing you with Unicode strings in their :file:`.po`
files, you'd instead do::

   import gettext
   t = gettext.translation('spam', '/usr/share/locale')
   _ = t.ugettext


Localizing your application
^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you are localizing your application, you can install the :func:`_` function
globally into the built-in namespace, usually in the main driver file of your
application.  This will let all your application-specific files just use
``_('...')`` without having to explicitly install it in each file.

In the simple case then, you need only add the following bit of code to the main
driver file of your application::

   import gettext
   gettext.install('myapplication')

If you need to set the locale directory or the *unicode* flag, you can pass
these into the :func:`install` function::

   import gettext
   gettext.install('myapplication', '/usr/share/locale', unicode=1)


Changing languages on the fly
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If your program needs to support many languages at the same time, you may want
to create multiple translation instances and then switch between them
explicitly, like so::

   import gettext

   lang1 = gettext.translation('myapplication', languages=['en'])
   lang2 = gettext.translation('myapplication', languages=['fr'])
   lang3 = gettext.translation('myapplication', languages=['de'])

   # start by using language1
   lang1.install()

   # ... time goes by, user selects language 2
   lang2.install()

   # ... more time goes by, user selects language 3
   lang3.install()


Deferred translations
^^^^^^^^^^^^^^^^^^^^^

In most coding situations, strings are translated where they are coded.
Occasionally however, you need to mark strings for translation, but defer actual
translation until later.  A classic example is::

   animals = ['mollusk',
              'albatross',
              'rat',
              'penguin',
              'python', ]
   # ...
   for a in animals:
       print a

Here, you want to mark the strings in the ``animals`` list as being
translatable, but you don't actually want to translate them until they are
printed.

Here is one way you can handle this situation::

   def _(message): return message

   animals = [_('mollusk'),
              _('albatross'),
              _('rat'),
              _('penguin'),
              _('python'), ]

   del _

   # ...
   for a in animals:
       print _(a)

This works because the dummy definition of :func:`_` simply returns the string
unchanged.  And this dummy definition will temporarily override any definition
of :func:`_` in the built-in namespace (until the :keyword:`del` command). Take
care, though if you have a previous definition of :func:`_` in the local
namespace.

Note that the second use of :func:`_` will not identify "a" as being
translatable to the :program:`pygettext` program, since it is not a string.

Another way to handle this is with the following example::

   def N_(message): return message

   animals = [N_('mollusk'),
              N_('albatross'),
              N_('rat'),
              N_('penguin'),
              N_('python'), ]

   # ...
   for a in animals:
       print _(a)

In this case, you are marking translatable strings with the function :func:`N_`,
[#]_ which won't conflict with any definition of :func:`_`.  However, you will
need to teach your message extraction program to look for translatable strings
marked with :func:`N_`. :program:`pygettext` and :program:`xpot` both support
this through the use of command line switches.


:func:`gettext` vs. :func:`lgettext`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

In Python 2.4 the :func:`lgettext` family of functions were introduced. The
intention of these functions is to provide an alternative which is more
compliant with the current implementation of GNU gettext. Unlike
:func:`gettext`, which returns strings encoded with the same codeset used in the
translation file, :func:`lgettext` will return strings encoded with the
preferred system encoding, as returned by :func:`locale.getpreferredencoding`.
Also notice that Python 2.4 introduces new functions to explicitly choose the
codeset used in translated strings. If a codeset is explicitly set, even
:func:`lgettext` will return translated strings in the requested codeset, as
would be expected in the GNU gettext implementation.


Acknowledgements
----------------

The following people contributed code, feedback, design suggestions, previous
implementations, and valuable experience to the creation of this module:

* Peter Funk

* James Henstridge

* Juan David Ibáñez Palomar

* Marc-André Lemburg

* Martin von Löwis

* François Pinard

* Barry Warsaw

* Gustavo Niemeyer

.. rubric:: Footnotes

.. [#] The default locale directory is system dependent; for example, on RedHat Linux
   it is :file:`/usr/share/locale`, but on Solaris it is :file:`/usr/lib/locale`.
   The :mod:`gettext` module does not try to support these system dependent
   defaults; instead its default is :file:`sys.prefix/share/locale`. For this
   reason, it is always best to call :func:`bindtextdomain` with an explicit
   absolute path at the start of your application.

.. [#] See the footnote for :func:`bindtextdomain` above.

.. [#] François Pinard has written a program called :program:`xpot` which does a
   similar job.  It is available as part of his
   `po-utils package <https://github.com/pinard/po-utils>`__.

.. [#] :program:`msgfmt.py` is binary compatible with GNU :program:`msgfmt` except that
   it provides a simpler, all-Python implementation.  With this and
   :program:`pygettext.py`, you generally won't need to install the GNU
   :program:`gettext` package to internationalize your Python applications.

.. [#] The choice of :func:`N_` here is totally arbitrary; it could have just as easily
   been :func:`MarkThisStringForTranslation`.

PK	%�\��yy html/_sources/library/gl.rst.txtnu�[���:mod:`gl` --- *Graphics Library* interface
==========================================

.. module:: gl
   :platform: IRIX
   :synopsis: Functions from the Silicon Graphics Graphics Library.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`gl` module has been removed in Python 3.


This module provides access to the Silicon Graphics *Graphics Library*. It is
available only on Silicon Graphics machines.

.. warning::

   Some illegal calls to the GL library cause the Python interpreter to dump
   core.  In particular, the use of most GL calls is unsafe before the first
   window is opened.

The module is too large to document here in its entirety, but the following
should help you to get started. The parameter conventions for the C functions
are translated to Python as follows:

* All (short, long, unsigned) int values are represented by Python integers.

* All float and double values are represented by Python floating point numbers.
  In most cases, Python integers are also allowed.

* All arrays are represented by one-dimensional Python lists. In most cases,
  tuples are also allowed.

* All string and character arguments are represented by Python strings, for
  instance, ``winopen('Hi There!')`` and ``rotate(900, 'z')``.

* All (short, long, unsigned) integer arguments or return values that are only
  used to specify the length of an array argument are omitted. For example, the C
  call ::

     lmdef(deftype, index, np, props)

  is translated to Python as ::

     lmdef(deftype, index, props)

* Output arguments are omitted from the argument list; they are transmitted as
  function return values instead. If more than one value must be returned, the
  return value is a tuple. If the C function has both a regular return value (that
  is not omitted because of the previous rule) and an output argument, the return
  value comes first in the tuple. Examples: the C call ::

     getmcolor(i, &red, &green, &blue)

  is translated to Python as ::

     red, green, blue = getmcolor(i)

The following functions are non-standard or have special argument conventions:


.. function:: varray(argument)

   Equivalent to but faster than a number of ``v3d()`` calls. The *argument* is a
   list (or tuple) of points. Each point must be a tuple of coordinates ``(x, y,
   z)`` or ``(x, y)``. The points may be 2- or 3-dimensional but must all have the
   same dimension. Float and int values may be mixed however. The points are always
   converted to 3D double precision points by assuming ``z = 0.0`` if necessary (as
   indicated in the man page), and for each point ``v3d()`` is called.

   .. XXX the argument-argument added


.. function:: nvarray()

   Equivalent to but faster than a number of ``n3f`` and ``v3f`` calls. The
   argument is an array (list or tuple) of pairs of normals and points. Each pair
   is a tuple of a point and a normal for that point. Each point or normal must be
   a tuple of coordinates ``(x, y, z)``. Three coordinates must be given. Float and
   int values may be mixed. For each pair, ``n3f()`` is called for the normal, and
   then ``v3f()`` is called for the point.


.. function:: vnarray()

   Similar to  ``nvarray()`` but the pairs have the point first and the normal
   second.


.. function:: nurbssurface(s_k, t_k, ctl, s_ord, t_ord, type)

   Defines a nurbs surface. The dimensions of ``ctl[][]`` are computed as follows:
   ``[len(s_k) - s_ord]``, ``[len(t_k) - t_ord]``.

   .. XXX s_k[], t_k[], ctl[][]


.. function:: nurbscurve(knots, ctlpoints, order, type)

   Defines a nurbs curve. The length of ctlpoints is ``len(knots) - order``.


.. function:: pwlcurve(points, type)

   Defines a piecewise-linear curve. *points* is a list of points. *type* must be
   ``N_ST``.


.. function:: pick(n)
              select(n)

   The only argument to these functions specifies the desired size of the pick or
   select buffer.


.. function:: endpick()
              endselect()

   These functions have no arguments. They return a list of integers representing
   the used part of the pick/select buffer. No method is provided to detect buffer
   overrun.

Here is a tiny but complete example GL program in Python::

   import gl, GL, time

   def main():
       gl.foreground()
       gl.prefposition(500, 900, 500, 900)
       w = gl.winopen('CrissCross')
       gl.ortho2(0.0, 400.0, 0.0, 400.0)
       gl.color(GL.WHITE)
       gl.clear()
       gl.color(GL.RED)
       gl.bgnline()
       gl.v2f(0.0, 0.0)
       gl.v2f(400.0, 400.0)
       gl.endline()
       gl.bgnline()
       gl.v2f(400.0, 0.0)
       gl.v2f(0.0, 400.0)
       gl.endline()
       time.sleep(5)

   main()


.. seealso::

   `PyOpenGL: The Python OpenGL Binding <http://pyopengl.sourceforge.net/>`_
      .. index::
         single: OpenGL
         single: PyOpenGL

      An interface to OpenGL is also available; see information about the **PyOpenGL**
      project online at http://pyopengl.sourceforge.net/.  This may be a better option
      if support for SGI hardware from before about 1996 is not required.


:mod:`DEVICE` --- Constants used with the :mod:`gl` module
==========================================================

.. module:: DEVICE
   :platform: IRIX
   :synopsis: Constants used with the gl module.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`DEVICE` module has been removed in Python 3.


This modules defines the constants used by the Silicon Graphics *Graphics
Library* that C programmers find in the header file ``<gl/device.h>``. Read the
module source file for details.


:mod:`GL` --- Constants used with the :mod:`gl` module
======================================================

.. module:: GL
   :platform: IRIX
   :synopsis: Constants used with the gl module.
   :deprecated:


.. deprecated:: 2.6
    The :mod:`GL` module has been removed in Python 3.

This module contains constants used by the Silicon Graphics *Graphics Library*
from the C header file ``<gl/gl.h>``. Read the module source file for details.

PK	%�\Jյn	n	"html/_sources/library/glob.rst.txtnu�[���:mod:`glob` --- Unix style pathname pattern expansion
=====================================================

.. module:: glob
   :synopsis: Unix shell style pathname pattern expansion.


.. index:: single: filenames; pathname expansion

**Source code:** :source:`Lib/glob.py`

--------------

The :mod:`glob` module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell, although results are returned in
arbitrary order.  No tilde expansion is done, but ``*``, ``?``, and character
ranges expressed with ``[]`` will be correctly matched.  This is done by using
the :func:`os.listdir` and :func:`fnmatch.fnmatch` functions in concert, and
not by actually invoking a subshell.  Note that unlike :func:`fnmatch.fnmatch`,
:mod:`glob` treats filenames beginning with a dot (``.``) as special cases.
(For tilde and shell variable expansion, use :func:`os.path.expanduser` and
:func:`os.path.expandvars`.)

For a literal match, wrap the meta-characters in brackets.
For example, ``'[?]'`` matches the character ``'?'``.


.. function:: glob(pathname)

   Return a possibly-empty list of path names that match *pathname*, which must be
   a string containing a path specification. *pathname* can be either absolute
   (like :file:`/usr/src/Python-1.5/Makefile`) or relative (like
   :file:`../../Tools/\*/\*.gif`), and can contain shell-style wildcards. Broken
   symlinks are included in the results (as in the shell).


.. function:: iglob(pathname)

   Return an :term:`iterator` which yields the same values as :func:`glob`
   without actually storing them all simultaneously.

   .. versionadded:: 2.5

For example, consider a directory containing only the following files:
:file:`1.gif`, :file:`2.txt`, and :file:`card.gif`.  :func:`glob` will produce
the following results.  Notice how any leading components of the path are
preserved. ::

   >>> import glob
   >>> glob.glob('./[0-9].*')
   ['./1.gif', './2.txt']
   >>> glob.glob('*.gif')
   ['1.gif', 'card.gif']
   >>> glob.glob('?.gif')
   ['1.gif']

If the directory contains files starting with ``.`` they won't be matched by
default. For example, consider a directory containing :file:`card.gif` and
:file:`.card.gif`::

   >>> import glob
   >>> glob.glob('*.gif')
   ['card.gif']
   >>> glob.glob('.c*')
   ['.card.gif']

.. seealso::

   Module :mod:`fnmatch`
      Shell-style filename (not path) expansion

PK	%�\4)T6��!html/_sources/library/grp.rst.txtnu�[���
:mod:`grp` --- The group database
=================================

.. module:: grp
   :platform: Unix
   :synopsis: The group database (getgrnam() and friends).


This module provides access to the Unix group database. It is available on all
Unix versions.

Group database entries are reported as a tuple-like object, whose attributes
correspond to the members of the ``group`` structure (Attribute field below, see
``<pwd.h>``):

+-------+-----------+---------------------------------+
| Index | Attribute | Meaning                         |
+=======+===========+=================================+
| 0     | gr_name   | the name of the group           |
+-------+-----------+---------------------------------+
| 1     | gr_passwd | the (encrypted) group password; |
|       |           | often empty                     |
+-------+-----------+---------------------------------+
| 2     | gr_gid    | the numerical group ID          |
+-------+-----------+---------------------------------+
| 3     | gr_mem    | all the group member's  user    |
|       |           | names                           |
+-------+-----------+---------------------------------+

The gid is an integer, name and password are strings, and the member list is a
list of strings. (Note that most users are not explicitly listed as members of
the group they are in according to the password database.  Check both databases
to get complete membership information.  Also note that a ``gr_name`` that
starts with a ``+`` or ``-`` is likely to be a YP/NIS reference and may not be
accessible via :func:`getgrnam` or :func:`getgrgid`.)

It defines the following items:


.. function:: getgrgid(gid)

   Return the group database entry for the given numeric group ID. :exc:`KeyError`
   is raised if the entry asked for cannot be found.


.. function:: getgrnam(name)

   Return the group database entry for the given group name. :exc:`KeyError` is
   raised if the entry asked for cannot be found.


.. function:: getgrall()

   Return a list of all available group entries, in arbitrary order.


.. seealso::

   Module :mod:`pwd`
      An interface to the user database, similar to this.

   Module :mod:`spwd`
      An interface to the shadow password database, similar to this.

PK	%�\J�����"html/_sources/library/gzip.rst.txtnu�[���:mod:`gzip` --- Support for :program:`gzip` files
=================================================

.. module:: gzip
   :synopsis: Interfaces for gzip compression and decompression using file objects.

**Source code:** :source:`Lib/gzip.py`

--------------

This module provides a simple interface to compress and decompress files just
like the GNU programs :program:`gzip` and :program:`gunzip` would.

The data compression is provided by the :mod:`zlib` module.

The :mod:`gzip` module provides the :class:`GzipFile` class which is modeled
after Python's File Object. The :class:`GzipFile` class reads and writes
:program:`gzip`\ -format files, automatically compressing or decompressing the
data so that it looks like an ordinary file object.

Note that additional file formats which can be decompressed by the
:program:`gzip` and :program:`gunzip` programs, such  as those produced by
:program:`compress` and :program:`pack`, are not supported by this module.

The module defines the following items:


.. class:: GzipFile([filename[, mode[, compresslevel[, fileobj[, mtime]]]]])

   Constructor for the :class:`GzipFile` class, which simulates most of the methods
   of a file object, with the exception of the :meth:`readinto` and
   :meth:`truncate` methods.  At least one of *fileobj* and *filename* must be
   given a non-trivial value.

   The new class instance is based on *fileobj*, which can be a regular file, a
   :class:`~StringIO.StringIO` object, or any other object which simulates a file.  It
   defaults to ``None``, in which case *filename* is opened to provide a file
   object.

   When *fileobj* is not ``None``, the *filename* argument is only used to be
   included in the :program:`gzip` file header, which may include the original
   filename of the uncompressed file.  It defaults to the filename of *fileobj*, if
   discernible; otherwise, it defaults to the empty string, and in this case the
   original filename is not included in the header.

   The *mode* argument can be any of ``'r'``, ``'rb'``, ``'a'``, ``'ab'``, ``'w'``,
   or ``'wb'``, depending on whether the file will be read or written.  The default
   is the mode of *fileobj* if discernible; otherwise, the default is ``'rb'``. If
   not given, the 'b' flag will be added to the mode to ensure the file is opened
   in binary mode for cross-platform portability.

   The *compresslevel* argument is an integer from ``0`` to ``9`` controlling
   the level of compression; ``1`` is fastest and produces the least
   compression, and ``9`` is slowest and produces the most compression. ``0``
   is no compression. The default is ``9``.

   The *mtime* argument is an optional numeric timestamp to be written to
   the stream when compressing.  All :program:`gzip` compressed streams are
   required to contain a timestamp.  If omitted or ``None``, the current
   time is used.  This module ignores the timestamp when decompressing;
   however, some programs, such as :program:`gunzip`\ , make use of it.
   The format of the timestamp is the same as that of the return value of
   ``time.time()`` and of the ``st_mtime`` attribute of the object returned
   by ``os.stat()``.

   Calling a :class:`GzipFile` object's :meth:`close` method does not close
   *fileobj*, since you might wish to append more material after the compressed
   data.  This also allows you to pass a :class:`~StringIO.StringIO` object opened for
   writing as *fileobj*, and retrieve the resulting memory buffer using the
   :class:`~StringIO.StringIO` object's :meth:`~StringIO.StringIO.getvalue` method.

   :class:`GzipFile` supports iteration and the :keyword:`with` statement.

   .. versionchanged:: 2.7
      Support for the :keyword:`with` statement was added.

   .. versionchanged:: 2.7
      Support for zero-padded files was added.

   .. versionadded:: 2.7
      The *mtime* argument.


.. function:: open(filename[, mode[, compresslevel]])

   This is a shorthand for ``GzipFile(filename,`` ``mode,`` ``compresslevel)``.
   The *filename* argument is required; *mode* defaults to ``'rb'`` and
   *compresslevel* defaults to ``9``.


.. _gzip-usage-examples:

Examples of usage
-----------------

Example of how to read a compressed file::

   import gzip
   with gzip.open('file.txt.gz', 'rb') as f:
       file_content = f.read()

Example of how to create a compressed GZIP file::

   import gzip
   content = "Lots of content here"
   with gzip.open('file.txt.gz', 'wb') as f:
       f.write(content)

Example of how to GZIP compress an existing file::

   import gzip
   import shutil
   with open('file.txt', 'rb') as f_in, gzip.open('file.txt.gz', 'wb') as f_out:
       shutil.copyfileobj(f_in, f_out)


.. seealso::

   Module :mod:`zlib`
      The basic data compression module needed to support the :program:`gzip` file
      format.

PK	%�\&����%html/_sources/library/hashlib.rst.txtnu�[���:mod:`hashlib` --- Secure hashes and message digests
====================================================

.. module:: hashlib
   :synopsis: Secure hash and message digest algorithms.
.. moduleauthor:: Gregory P. Smith <greg@krypto.org>
.. sectionauthor:: Gregory P. Smith <greg@krypto.org>


.. versionadded:: 2.5

.. index::
   single: message digest, MD5
   single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512

**Source code:** :source:`Lib/hashlib.py`

--------------

This module implements a common interface to many different secure hash and
message digest algorithms.  Included are the FIPS secure hash algorithms SHA1,
SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5
algorithm (defined in Internet :rfc:`1321`). The terms secure hash and message
digest are interchangeable.  Older algorithms were called message digests.  The
modern term is secure hash.

.. note::

   If you want the adler32 or crc32 hash functions, they are available in
   the :mod:`zlib` module.

.. warning::

   Some algorithms have known hash collision weaknesses, refer to the "See
   also" section at the end.

There is one constructor method named for each type of :dfn:`hash`.  All return
a hash object with the same simple interface. For example: use :func:`sha1` to
create a SHA1 hash object. You can now feed this object with arbitrary strings
using the :meth:`update` method.  At any point you can ask it for the
:dfn:`digest` of the concatenation of the strings fed to it so far using the
:meth:`digest` or :meth:`hexdigest` methods.

.. index:: single: OpenSSL; (use in module hashlib)

Constructors for hash algorithms that are always present in this module are
:func:`md5`, :func:`sha1`, :func:`sha224`, :func:`sha256`, :func:`sha384`, and
:func:`sha512`.  Additional algorithms may also be available depending upon the
OpenSSL library that Python uses on your platform.

For example, to obtain the digest of the string ``'Nobody inspects the spammish
repetition'``:

   >>> import hashlib
   >>> m = hashlib.md5()
   >>> m.update("Nobody inspects")
   >>> m.update(" the spammish repetition")
   >>> m.digest()
   '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'
   >>> m.digest_size
   16
   >>> m.block_size
   64

More condensed:

   >>> hashlib.sha224("Nobody inspects the spammish repetition").hexdigest()
   'a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2'

A generic :func:`new` constructor that takes the string name of the desired
algorithm as its first parameter also exists to allow access to the above listed
hashes as well as any other algorithms that your OpenSSL library may offer.  The
named constructors are much faster than :func:`new` and should be preferred.

Using :func:`new` with an algorithm provided by OpenSSL:

   >>> h = hashlib.new('ripemd160')
   >>> h.update("Nobody inspects the spammish repetition")
   >>> h.hexdigest()
   'cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc'

This module provides the following constant attribute:

.. data:: hashlib.algorithms

   A tuple providing the names of the hash algorithms guaranteed to be
   supported by this module.

   .. versionadded:: 2.7

.. data:: algorithms_guaranteed

   A set containing the names of the hash algorithms guaranteed to be supported
   by this module on all platforms.

   .. versionadded:: 2.7.9

.. data:: algorithms_available

   A set containing the names of the hash algorithms that are available in the
   running Python interpreter.  These names will be recognized when passed to
   :func:`new`.  :attr:`algorithms_guaranteed` will always be a subset.  The
   same algorithm may appear multiple times in this set under different names
   (thanks to OpenSSL).

   .. versionadded:: 2.7.9


The following values are provided as constant attributes of the hash objects
returned by the constructors:


.. data:: hash.digest_size

   The size of the resulting hash in bytes.

.. data:: hash.block_size

   The internal block size of the hash algorithm in bytes.

A hash object has the following methods:


.. method:: hash.update(arg)

   Update the hash object with the string *arg*.  Repeated calls are equivalent to
   a single call with the concatenation of all the arguments: ``m.update(a);
   m.update(b)`` is equivalent to ``m.update(a+b)``.

   .. versionchanged:: 2.7
      The Python GIL is released to allow other threads to run while
      hash updates on data larger than 2048 bytes is taking place when
      using hash algorithms supplied by OpenSSL.


.. method:: hash.digest()

   Return the digest of the strings passed to the :meth:`update` method so far.
   This is a string of :attr:`digest_size` bytes which may contain non-ASCII
   characters, including null bytes.


.. method:: hash.hexdigest()

   Like :meth:`digest` except the digest is returned as a string of double length,
   containing only hexadecimal digits.  This may  be used to exchange the value
   safely in email or other non-binary environments.


.. method:: hash.copy()

   Return a copy ("clone") of the hash object.  This can be used to efficiently
   compute the digests of strings that share a common initial substring.


Key derivation
--------------

Key derivation and key stretching algorithms are designed for secure password
hashing. Naive algorithms such as ``sha1(password)`` are not resistant against
brute-force attacks. A good password hashing function must be tunable, slow, and
include a `salt <https://en.wikipedia.org/wiki/Salt_%28cryptography%29>`_.


.. function:: pbkdf2_hmac(name, password, salt, rounds, dklen=None)

   The function provides PKCS#5 password-based key derivation function 2. It
   uses HMAC as pseudorandom function.

   The string *name* is the desired name of the hash digest algorithm for
   HMAC, e.g. 'sha1' or 'sha256'. *password* and *salt* are interpreted as
   buffers of bytes. Applications and libraries should limit *password* to
   a sensible value (e.g. 1024). *salt* should be about 16 or more bytes from
   a proper source, e.g. :func:`os.urandom`.

   The number of *rounds* should be chosen based on the hash algorithm and
   computing power. As of 2013, at least 100,000 rounds of SHA-256 is suggested.

   *dklen* is the length of the derived key. If *dklen* is ``None`` then the
   digest size of the hash algorithm *name* is used, e.g. 64 for SHA-512.

   >>> import hashlib, binascii
   >>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)
   >>> binascii.hexlify(dk)
   b'0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5'

   .. versionadded:: 2.7.8

   .. note::

      A fast implementation of *pbkdf2_hmac* is available with OpenSSL.  The
      Python implementation uses an inline version of :mod:`hmac`. It is about
      three times slower and doesn't release the GIL.


.. seealso::

   Module :mod:`hmac`
      A module to generate message authentication codes using hashes.

   Module :mod:`base64`
      Another way to encode binary hashes for non-binary environments.

   http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
      The FIPS 180-2 publication on Secure Hash Algorithms.

   https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms
      Wikipedia article with information on which algorithms have known issues and
      what that means regarding their use.

PK	%�\�a�́3�3#html/_sources/library/heapq.rst.txtnu�[���:mod:`heapq` --- Heap queue algorithm
=====================================

.. module:: heapq
   :synopsis: Heap queue algorithm (a.k.a. priority queue).
.. moduleauthor:: Kevin O'Connor
.. sectionauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: François Pinard
.. sectionauthor:: Raymond Hettinger

.. versionadded:: 2.3

**Source code:** :source:`Lib/heapq.py`

--------------

This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.

Heaps are binary trees for which every parent node has a value less than or
equal to any of its children.  This implementation uses arrays for which
``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
elements from zero.  For the sake of comparison, non-existing elements are
considered to be infinite.  The interesting property of a heap is that its
smallest element is always the root, ``heap[0]``.

The API below differs from textbook heap algorithms in two aspects: (a) We use
zero-based indexing.  This makes the relationship between the index for a node
and the indexes for its children slightly less obvious, but is more suitable
since Python uses zero-based indexing. (b) Our pop method returns the smallest
item, not the largest (called a "min heap" in textbooks; a "max heap" is more
common in texts because of its suitability for in-place sorting).

These two make it possible to view the heap as a regular Python list without
surprises: ``heap[0]`` is the smallest item, and ``heap.sort()`` maintains the
heap invariant!

To create a heap, use a list initialized to ``[]``, or you can transform a
populated list into a heap via function :func:`heapify`.

The following functions are provided:


.. function:: heappush(heap, item)

   Push the value *item* onto the *heap*, maintaining the heap invariant.


.. function:: heappop(heap)

   Pop and return the smallest item from the *heap*, maintaining the heap
   invariant.  If the heap is empty, :exc:`IndexError` is raised.  To access the
   smallest item without popping it, use ``heap[0]``.

.. function:: heappushpop(heap, item)

   Push *item* on the heap, then pop and return the smallest item from the
   *heap*.  The combined action runs more efficiently than :func:`heappush`
   followed by a separate call to :func:`heappop`.

   .. versionadded:: 2.6

.. function:: heapify(x)

   Transform list *x* into a heap, in-place, in linear time.


.. function:: heapreplace(heap, item)

   Pop and return the smallest item from the *heap*, and also push the new *item*.
   The heap size doesn't change. If the heap is empty, :exc:`IndexError` is raised.

   This one step operation is more efficient than a :func:`heappop` followed by
   :func:`heappush` and can be more appropriate when using a fixed-size heap.
   The pop/push combination always returns an element from the heap and replaces
   it with *item*.

   The value returned may be larger than the *item* added.  If that isn't
   desired, consider using :func:`heappushpop` instead.  Its push/pop
   combination returns the smaller of the two values, leaving the larger value
   on the heap.


The module also offers three general purpose functions based on heaps.


.. function:: merge(*iterables)

   Merge multiple sorted inputs into a single sorted output (for example, merge
   timestamped entries from multiple log files).  Returns an :term:`iterator`
   over the sorted values.

   Similar to ``sorted(itertools.chain(*iterables))`` but returns an iterable, does
   not pull the data into memory all at once, and assumes that each of the input
   streams is already sorted (smallest to largest).

   .. versionadded:: 2.6


.. function:: nlargest(n, iterable[, key])

   Return a list with the *n* largest elements from the dataset defined by
   *iterable*.  *key*, if provided, specifies a function of one argument that is
   used to extract a comparison key from each element in the iterable:
   ``key=str.lower`` Equivalent to:  ``sorted(iterable, key=key,
   reverse=True)[:n]``

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      Added the optional *key* argument.


.. function:: nsmallest(n, iterable[, key])

   Return a list with the *n* smallest elements from the dataset defined by
   *iterable*.  *key*, if provided, specifies a function of one argument that is
   used to extract a comparison key from each element in the iterable:
   ``key=str.lower`` Equivalent to:  ``sorted(iterable, key=key)[:n]``

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      Added the optional *key* argument.

The latter two functions perform best for smaller values of *n*.  For larger
values, it is more efficient to use the :func:`sorted` function.  Also, when
``n==1``, it is more efficient to use the built-in :func:`min` and :func:`max`
functions.  If repeated usage of these functions is required, consider turning
the iterable into an actual heap.


Basic Examples
--------------

A `heapsort <https://en.wikipedia.org/wiki/Heapsort>`_ can be implemented by
pushing all values onto a heap and then popping off the smallest values one at a
time::

   >>> def heapsort(iterable):
   ...     h = []
   ...     for value in iterable:
   ...         heappush(h, value)
   ...     return [heappop(h) for i in range(len(h))]
   ...
   >>> heapsort([1, 3, 5, 7, 9, 2, 4, 6, 8, 0])
   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

This is similar to ``sorted(iterable)``, but unlike :func:`sorted`, this
implementation is not stable.

Heap elements can be tuples.  This is useful for assigning comparison values
(such as task priorities) alongside the main record being tracked::

    >>> h = []
    >>> heappush(h, (5, 'write code'))
    >>> heappush(h, (7, 'release product'))
    >>> heappush(h, (1, 'write spec'))
    >>> heappush(h, (3, 'create tests'))
    >>> heappop(h)
    (1, 'write spec')


Priority Queue Implementation Notes
-----------------------------------

A `priority queue <https://en.wikipedia.org/wiki/Priority_queue>`_ is common use
for a heap, and it presents several implementation challenges:

* Sort stability:  how do you get two tasks with equal priorities to be returned
  in the order they were originally added?

* In the future with Python 3, tuple comparison breaks for (priority, task)
  pairs if the priorities are equal and the tasks do not have a default
  comparison order.

* If the priority of a task changes, how do you move it to a new position in
  the heap?

* Or if a pending task needs to be deleted, how do you find it and remove it
  from the queue?

A solution to the first two challenges is to store entries as 3-element list
including the priority, an entry count, and the task.  The entry count serves as
a tie-breaker so that two tasks with the same priority are returned in the order
they were added. And since no two entry counts are the same, the tuple
comparison will never attempt to directly compare two tasks.

The remaining challenges revolve around finding a pending task and making
changes to its priority or removing it entirely.  Finding a task can be done
with a dictionary pointing to an entry in the queue.

Removing the entry or changing its priority is more difficult because it would
break the heap structure invariants.  So, a possible solution is to mark the
existing entry as removed and add a new entry with the revised priority::

    pq = []                         # list of entries arranged in a heap
    entry_finder = {}               # mapping of tasks to entries
    REMOVED = '<removed-task>'      # placeholder for a removed task
    counter = itertools.count()     # unique sequence count

    def add_task(task, priority=0):
        'Add a new task or update the priority of an existing task'
        if task in entry_finder:
            remove_task(task)
        count = next(counter)
        entry = [priority, count, task]
        entry_finder[task] = entry
        heappush(pq, entry)

    def remove_task(task):
        'Mark an existing task as REMOVED.  Raise KeyError if not found.'
        entry = entry_finder.pop(task)
        entry[-1] = REMOVED

    def pop_task():
        'Remove and return the lowest priority task. Raise KeyError if empty.'
        while pq:
            priority, count, task = heappop(pq)
            if task is not REMOVED:
                del entry_finder[task]
                return task
        raise KeyError('pop from an empty priority queue')


Theory
------

Heaps are arrays for which ``a[k] <= a[2*k+1]`` and ``a[k] <= a[2*k+2]`` for all
*k*, counting elements from 0.  For the sake of comparison, non-existing
elements are considered to be infinite.  The interesting property of a heap is
that ``a[0]`` is always its smallest element.

The strange invariant above is meant to be an efficient memory representation
for a tournament.  The numbers below are *k*, not ``a[k]``::

                                  0

                 1                                 2

         3               4                5               6

     7       8       9       10      11      12      13      14

   15 16   17 18   19 20   21 22   23 24   25 26   27 28   29 30

In the tree above, each cell *k* is topping ``2*k+1`` and ``2*k+2``. In a usual
binary tournament we see in sports, each cell is the winner over the two cells
it tops, and we can trace the winner down the tree to see all opponents s/he
had.  However, in many computer applications of such tournaments, we do not need
to trace the history of a winner. To be more memory efficient, when a winner is
promoted, we try to replace it by something else at a lower level, and the rule
becomes that a cell and the two cells it tops contain three different items, but
the top cell "wins" over the two topped cells.

If this heap invariant is protected at all time, index 0 is clearly the overall
winner.  The simplest algorithmic way to remove it and find the "next" winner is
to move some loser (let's say cell 30 in the diagram above) into the 0 position,
and then percolate this new 0 down the tree, exchanging values, until the
invariant is re-established. This is clearly logarithmic on the total number of
items in the tree. By iterating over all items, you get an O(n log n) sort.

A nice feature of this sort is that you can efficiently insert new items while
the sort is going on, provided that the inserted items are not "better" than the
last 0'th element you extracted.  This is especially useful in simulation
contexts, where the tree holds all incoming events, and the "win" condition
means the smallest scheduled time.  When an event schedules other events for
execution, they are scheduled into the future, so they can easily go into the
heap.  So, a heap is a good structure for implementing schedulers (this is what
I used for my MIDI sequencer :-).

Various structures for implementing schedulers have been extensively studied,
and heaps are good for this, as they are reasonably speedy, the speed is almost
constant, and the worst case is not much different than the average case.
However, there are other representations which are more efficient overall, yet
the worst cases might be terrible.

Heaps are also very useful in big disk sorts.  You most probably all know that a
big sort implies producing "runs" (which are pre-sorted sequences, whose size is
usually related to the amount of CPU memory), followed by a merging passes for
these runs, which merging is often very cleverly organised [#]_. It is very
important that the initial sort produces the longest runs possible.  Tournaments
are a good way to achieve that.  If, using all the memory available to hold a
tournament, you replace and percolate items that happen to fit the current run,
you'll produce runs which are twice the size of the memory for random input, and
much better for input fuzzily ordered.

Moreover, if you output the 0'th item on disk and get an input which may not fit
in the current tournament (because the value "wins" over the last output value),
it cannot fit in the heap, so the size of the heap decreases.  The freed memory
could be cleverly reused immediately for progressively building a second heap,
which grows at exactly the same rate the first heap is melting.  When the first
heap completely vanishes, you switch heaps and start a new run.  Clever and
quite effective!

In a word, heaps are useful memory structures to know.  I use them in a few
applications, and I think it is good to keep a 'heap' module around. :-)

.. rubric:: Footnotes

.. [#] The disk balancing algorithms which are current, nowadays, are more annoying
   than clever, and this is a consequence of the seeking capabilities of the disks.
   On devices which cannot seek, like big tape drives, the story was quite
   different, and one had to be very clever to ensure (far in advance) that each
   tape movement will be the most effective possible (that is, will best
   participate at "progressing" the merge).  Some tapes were even able to read
   backwards, and this was also used to avoid the rewinding time. Believe me, real
   good tape sorts were quite spectacular to watch! From all times, sorting has
   always been a Great Art! :-)

PK	%�\
���7979"html/_sources/library/2to3.rst.txtnu�[���.. _2to3-reference:

2to3 - Automated Python 2 to 3 code translation
===============================================

.. sectionauthor:: Benjamin Peterson <benjamin@python.org>

2to3 is a Python program that reads Python 2.x source code and applies a series
of *fixers* to transform it into valid Python 3.x code.  The standard library
contains a rich set of fixers that will handle almost all code.  2to3 supporting
library :mod:`lib2to3` is, however, a flexible and generic library, so it is
possible to write your own fixers for 2to3.  :mod:`lib2to3` could also be
adapted to custom applications in which Python code needs to be edited
automatically.


.. _2to3-using:

Using 2to3
----------

2to3 will usually be installed with the Python interpreter as a script.  It is
also located in the :file:`Tools/scripts` directory of the Python root.

2to3's basic arguments are a list of files or directories to transform.  The
directories are recursively traversed for Python sources.

Here is a sample Python 2.x source file, :file:`example.py`::

   def greet(name):
       print "Hello, {0}!".format(name)
   print "What's your name?"
   name = raw_input()
   greet(name)

It can be converted to Python 3.x code via 2to3 on the command line:

.. code-block:: shell-session

   $ 2to3 example.py

A diff against the original source file is printed.  2to3 can also write the
needed modifications right back to the source file.  (A backup of the original
file is made unless :option:`!-n` is also given.)  Writing the changes back is
enabled with the :option:`!-w` flag:

.. code-block:: shell-session

   $ 2to3 -w example.py

After transformation, :file:`example.py` looks like this::

   def greet(name):
       print("Hello, {0}!".format(name))
   print("What's your name?")
   name = input()
   greet(name)

Comments and exact indentation are preserved throughout the translation process.

By default, 2to3 runs a set of :ref:`predefined fixers <2to3-fixers>`.  The
:option:`!-l` flag lists all available fixers.  An explicit set of fixers to run
can be given with :option:`!-f`.  Likewise the :option:`!-x` explicitly disables a
fixer.  The following example runs only the ``imports`` and ``has_key`` fixers:

.. code-block:: shell-session

   $ 2to3 -f imports -f has_key example.py

This command runs every fixer except the ``apply`` fixer:

.. code-block:: shell-session

   $ 2to3 -x apply example.py

Some fixers are *explicit*, meaning they aren't run by default and must be
listed on the command line to be run.  Here, in addition to the default fixers,
the ``idioms`` fixer is run:

.. code-block:: shell-session

   $ 2to3 -f all -f idioms example.py

Notice how passing ``all`` enables all default fixers.

Sometimes 2to3 will find a place in your source code that needs to be changed,
but 2to3 cannot fix automatically.  In this case, 2to3 will print a warning
beneath the diff for a file.  You should address the warning in order to have
compliant 3.x code.

2to3 can also refactor doctests.  To enable this mode, use the :option:`!-d`
flag.  Note that *only* doctests will be refactored.  This also doesn't require
the module to be valid Python.  For example, doctest like examples in a reST
document could also be refactored with this option.

The :option:`!-v` option enables output of more information on the translation
process.

Since some print statements can be parsed as function calls or statements, 2to3
cannot always read files containing the print function.  When 2to3 detects the
presence of the ``from __future__ import print_function`` compiler directive, it
modifies its internal grammar to interpret :func:`print` as a function.  This
change can also be enabled manually with the :option:`!-p` flag.  Use
:option:`!-p` to run fixers on code that already has had its print statements
converted.

The :option:`!-o` or :option:`!--output-dir` option allows specification of an
alternate directory for processed output files to be written to.  The
:option:`!-n` flag is required when using this as backup files do not make sense
when not overwriting the input files.

.. versionadded:: 2.7.3
   The :option:`!-o` option was added.

The :option:`!-W` or :option:`!--write-unchanged-files` flag tells 2to3 to always
write output files even if no changes were required to the file.  This is most
useful with :option:`!-o` so that an entire Python source tree is copied with
translation from one directory to another.
This option implies the :option:`!-w` flag as it would not make sense otherwise.

.. versionadded:: 2.7.3
   The :option:`!-W` flag was added.

The :option:`!--add-suffix` option specifies a string to append to all output
filenames.  The :option:`!-n` flag is required when specifying this as backups
are not necessary when writing to different filenames.  Example:

.. code-block:: shell-session

   $ 2to3 -n -W --add-suffix=3 example.py

Will cause a converted file named ``example.py3`` to be written.

.. versionadded:: 2.7.3
   The :option:`!--add-suffix` option was added.

To translate an entire project from one directory tree to another use:

.. code-block:: shell-session

   $ 2to3 --output-dir=python3-version/mycode -W -n python2-version/mycode


.. _2to3-fixers:

Fixers
------

Each step of transforming code is encapsulated in a fixer.  The command ``2to3
-l`` lists them.  As :ref:`documented above <2to3-using>`, each can be turned on
and off individually.  They are described here in more detail.


.. 2to3fixer:: apply

   Removes usage of :func:`apply`.  For example ``apply(function, *args,
   **kwargs)`` is converted to ``function(*args, **kwargs)``.

.. 2to3fixer:: asserts

   Replaces deprecated :mod:`unittest` method names with the correct ones.

   ================================  ==========================================
   From                              To
   ================================  ==========================================
   ``failUnlessEqual(a, b)``         :meth:`assertEqual(a, b)
                                     <unittest.TestCase.assertEqual>`
   ``assertEquals(a, b)``            :meth:`assertEqual(a, b)
                                     <unittest.TestCase.assertEqual>`
   ``failIfEqual(a, b)``             :meth:`assertNotEqual(a, b)
                                     <unittest.TestCase.assertNotEqual>`
   ``assertNotEquals(a, b)``         :meth:`assertNotEqual(a, b)
                                     <unittest.TestCase.assertNotEqual>`
   ``failUnless(a)``                 :meth:`assertTrue(a)
                                     <unittest.TestCase.assertTrue>`
   ``assert_(a)``                    :meth:`assertTrue(a)
                                     <unittest.TestCase.assertTrue>`
   ``failIf(a)``                     :meth:`assertFalse(a)
                                     <unittest.TestCase.assertFalse>`
   ``failUnlessRaises(exc, cal)``    :meth:`assertRaises(exc, cal)
                                     <unittest.TestCase.assertRaises>`
   ``failUnlessAlmostEqual(a, b)``   :meth:`assertAlmostEqual(a, b)
                                     <unittest.TestCase.assertAlmostEqual>`
   ``assertAlmostEquals(a, b)``      :meth:`assertAlmostEqual(a, b)
                                     <unittest.TestCase.assertAlmostEqual>`
   ``failIfAlmostEqual(a, b)``       :meth:`assertNotAlmostEqual(a, b)
                                     <unittest.TestCase.assertNotAlmostEqual>`
   ``assertNotAlmostEquals(a, b)``   :meth:`assertNotAlmostEqual(a, b)
                                     <unittest.TestCase.assertNotAlmostEqual>`
   ================================  ==========================================

.. 2to3fixer:: basestring

   Converts :class:`basestring` to :class:`str`.

.. 2to3fixer:: buffer

   Converts :class:`buffer` to :class:`memoryview`.  This fixer is optional
   because the :class:`memoryview` API is similar but not exactly the same as
   that of :class:`buffer`.

.. 2to3fixer:: dict

   Fixes dictionary iteration methods.  :meth:`dict.iteritems` is converted to
   :meth:`dict.items`, :meth:`dict.iterkeys` to :meth:`dict.keys`, and
   :meth:`dict.itervalues` to :meth:`dict.values`.  Similarly,
   :meth:`dict.viewitems`, :meth:`dict.viewkeys` and :meth:`dict.viewvalues` are
   converted respectively to :meth:`dict.items`, :meth:`dict.keys` and
   :meth:`dict.values`.  It also wraps existing usages of :meth:`dict.items`,
   :meth:`dict.keys`, and :meth:`dict.values` in a call to :class:`list`.

.. 2to3fixer:: except

   Converts ``except X, T`` to ``except X as T``.

.. 2to3fixer:: exec

   Converts the :keyword:`exec` statement to the :func:`exec` function.

.. 2to3fixer:: execfile

   Removes usage of :func:`execfile`.  The argument to :func:`execfile` is
   wrapped in calls to :func:`open`, :func:`compile`, and :func:`exec`.

.. 2to3fixer:: exitfunc

   Changes assignment of :attr:`sys.exitfunc` to use of the :mod:`atexit`
   module.

.. 2to3fixer:: filter

   Wraps :func:`filter` usage in a :class:`list` call.

.. 2to3fixer:: funcattrs

   Fixes function attributes that have been renamed.  For example,
   ``my_function.func_closure`` is converted to ``my_function.__closure__``.

.. 2to3fixer:: future

   Removes ``from __future__ import new_feature`` statements.

.. 2to3fixer:: getcwdu

   Renames :func:`os.getcwdu` to :func:`os.getcwd`.

.. 2to3fixer:: has_key

   Changes ``dict.has_key(key)`` to ``key in dict``.

.. 2to3fixer:: idioms

   This optional fixer performs several transformations that make Python code
   more idiomatic.  Type comparisons like ``type(x) is SomeClass`` and
   ``type(x) == SomeClass`` are converted to ``isinstance(x, SomeClass)``.
   ``while 1`` becomes ``while True``.  This fixer also tries to make use of
   :func:`sorted` in appropriate places.  For example, this block ::

       L = list(some_iterable)
       L.sort()

   is changed to ::

      L = sorted(some_iterable)

.. 2to3fixer:: import

   Detects sibling imports and converts them to relative imports.

.. 2to3fixer:: imports

   Handles module renames in the standard library.

.. 2to3fixer:: imports2

   Handles other modules renames in the standard library.  It is separate from
   the :2to3fixer:`imports` fixer only because of technical limitations.

.. 2to3fixer:: input

   Converts ``input(prompt)`` to ``eval(input(prompt))``.

.. 2to3fixer:: intern

   Converts :func:`intern` to :func:`sys.intern`.

.. 2to3fixer:: isinstance

   Fixes duplicate types in the second argument of :func:`isinstance`.  For
   example, ``isinstance(x, (int, int))`` is converted to ``isinstance(x,
   (int))``.

.. 2to3fixer:: itertools_imports

   Removes imports of :func:`itertools.ifilter`, :func:`itertools.izip`, and
   :func:`itertools.imap`.  Imports of :func:`itertools.ifilterfalse` are also
   changed to :func:`itertools.filterfalse`.

.. 2to3fixer:: itertools

   Changes usage of :func:`itertools.ifilter`, :func:`itertools.izip`, and
   :func:`itertools.imap` to their built-in equivalents.
   :func:`itertools.ifilterfalse` is changed to :func:`itertools.filterfalse`.

.. 2to3fixer:: long

   Renames :class:`long` to :class:`int`.

.. 2to3fixer:: map

   Wraps :func:`map` in a :class:`list` call.  It also changes ``map(None, x)``
   to ``list(x)``.  Using ``from future_builtins import map`` disables this
   fixer.

.. 2to3fixer:: metaclass

   Converts the old metaclass syntax (``__metaclass__ = Meta`` in the class
   body) to the new (``class X(metaclass=Meta)``).

.. 2to3fixer:: methodattrs

   Fixes old method attribute names.  For example, ``meth.im_func`` is converted
   to ``meth.__func__``.

.. 2to3fixer:: ne

   Converts the old not-equal syntax, ``<>``, to ``!=``.

.. 2to3fixer:: next

   Converts the use of iterator's :meth:`~iterator.next` methods to the
   :func:`next` function.  It also renames :meth:`~iterator.next` methods to
   :meth:`~iterator.__next__`.

.. 2to3fixer:: nonzero

   Renames :meth:`__nonzero__` to :meth:`~object.__bool__`.

.. 2to3fixer:: numliterals

   Converts octal literals into the new syntax.

.. 2to3fixer:: paren

   Add extra parenthesis where they are required in list comprehensions.  For
   example, ``[x for x in 1, 2]`` becomes ``[x for x in (1, 2)]``.

.. 2to3fixer:: print

   Converts the :keyword:`print` statement to the :func:`print` function.

.. 2to3fixer:: raise

   Converts ``raise E, V`` to ``raise E(V)``, and ``raise E, V, T`` to ``raise
   E(V).with_traceback(T)``.  If ``E`` is a tuple, the translation will be
   incorrect because substituting tuples for exceptions has been removed in Python 3.

.. 2to3fixer:: raw_input

   Converts :func:`raw_input` to :func:`input`.

.. 2to3fixer:: reduce

   Handles the move of :func:`reduce` to :func:`functools.reduce`.

.. 2to3fixer:: renames

   Changes :data:`sys.maxint` to :data:`sys.maxsize`.

.. 2to3fixer:: repr

   Replaces backtick repr with the :func:`repr` function.

.. 2to3fixer:: set_literal

   Replaces use of the :class:`set` constructor with set literals.  This fixer
   is optional.

.. 2to3fixer:: standarderror

   Renames :exc:`StandardError` to :exc:`Exception`.

.. 2to3fixer:: sys_exc

   Changes the deprecated :data:`sys.exc_value`, :data:`sys.exc_type`,
   :data:`sys.exc_traceback` to use :func:`sys.exc_info`.

.. 2to3fixer:: throw

   Fixes the API change in generator's :meth:`throw` method.

.. 2to3fixer:: tuple_params

   Removes implicit tuple parameter unpacking.  This fixer inserts temporary
   variables.

.. 2to3fixer:: types

   Fixes code broken from the removal of some members in the :mod:`types`
   module.

.. 2to3fixer:: unicode

   Renames :class:`unicode` to :class:`str`.

.. 2to3fixer:: urllib

   Handles the rename of :mod:`urllib` and :mod:`urllib2` to the :mod:`urllib`
   package.

.. 2to3fixer:: ws_comma

   Removes excess whitespace from comma separated items.  This fixer is
   optional.

.. 2to3fixer:: xrange

   Renames :func:`xrange` to :func:`range` and wraps existing :func:`range`
   calls with :class:`list`.

.. 2to3fixer:: xreadlines

   Changes ``for x in file.xreadlines()`` to ``for x in file``.

.. 2to3fixer:: zip

   Wraps :func:`zip` usage in a :class:`list` call.  This is disabled when
   ``from future_builtins import zip`` appears.


:mod:`lib2to3` - 2to3's library
-------------------------------

.. module:: lib2to3
   :synopsis: the 2to3 library
.. moduleauthor:: Guido van Rossum
.. moduleauthor:: Collin Winter
.. moduleauthor:: Benjamin Peterson <benjamin@python.org>


.. note::

   The :mod:`lib2to3` API should be considered unstable and may change
   drastically in the future.

.. XXX What is the public interface anyway?
PK	%�\L�6�"html/_sources/library/hmac.rst.txtnu�[���:mod:`hmac` --- Keyed-Hashing for Message Authentication
========================================================

.. module:: hmac
   :synopsis: Keyed-Hashing for Message Authentication (HMAC) implementation
.. moduleauthor:: Gerhard Häring <ghaering@users.sourceforge.net>
.. sectionauthor:: Gerhard Häring <ghaering@users.sourceforge.net>


.. versionadded:: 2.2

**Source code:** :source:`Lib/hmac.py`

--------------

This module implements the HMAC algorithm as described by :rfc:`2104`.


.. function:: new(key[, msg[, digestmod]])

   Return a new hmac object.  If *msg* is present, the method call ``update(msg)``
   is made. *digestmod* is the digest constructor or module for the HMAC object to
   use. It defaults to  the :data:`hashlib.md5` constructor.


An HMAC object has the following methods:

.. method:: HMAC.update(msg)

   Update the hmac object with the string *msg*.  Repeated calls are equivalent to
   a single call with the concatenation of all the arguments: ``m.update(a);
   m.update(b)`` is equivalent to ``m.update(a + b)``.


.. method:: HMAC.digest()

   Return the digest of the strings passed to the :meth:`update` method so far.
   This string will be the same length as the *digest_size* of the digest given to
   the constructor.  It may contain non-ASCII characters, including NUL bytes.

   .. warning::

      When comparing the output of :meth:`digest` to an externally-supplied
      digest during a verification routine, it is recommended to use the
      :func:`compare_digest` function instead of the ``==`` operator
      to reduce the vulnerability to timing attacks.


.. method:: HMAC.hexdigest()

   Like :meth:`digest` except the digest is returned as a string twice the length
   containing only hexadecimal digits.  This may be used to exchange the value
   safely in email or other non-binary environments.

   .. warning::

      When comparing the output of :meth:`hexdigest` to an externally-supplied
      digest during a verification routine, it is recommended to use the
      :func:`compare_digest` function instead of the ``==`` operator
      to reduce the vulnerability to timing attacks.


.. method:: HMAC.copy()

   Return a copy ("clone") of the hmac object.  This can be used to efficiently
   compute the digests of strings that share a common initial substring.


This module also provides the following helper function:

.. function:: compare_digest(a, b)

   Return ``a == b``.  This function uses an approach designed to prevent
   timing analysis by avoiding content-based short circuiting behaviour,
   making it appropriate for cryptography.  *a* and *b* must both be of the
   same type: either :class:`unicode` or a :term:`bytes-like object`.

   .. note::

      If *a* and *b* are of different lengths, or if an error occurs,
      a timing attack could theoretically reveal information about the
      types and lengths of *a* and *b*—but not their values.


   .. versionadded:: 2.7.7


.. seealso::

   Module :mod:`hashlib`
      The Python module providing secure hash functions.

PK	%�\����%html/_sources/library/hotshot.rst.txtnu�[���
:mod:`hotshot` --- High performance logging profiler
====================================================

.. module:: hotshot
   :synopsis: High performance logging profiler, mostly written in C.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Anthony Baxter <anthony@interlink.com.au>


.. versionadded:: 2.2

This module provides a nicer interface to the :mod:`_hotshot` C module. Hotshot
is a replacement for the existing :mod:`profile` module. As it's written mostly
in C, it should result in a much smaller performance impact than the existing
:mod:`profile` module.

.. note::

   The :mod:`hotshot` module focuses on minimizing the overhead while profiling, at
   the expense of long data post-processing times. For common usage it is
   recommended to use :mod:`cProfile` instead. :mod:`hotshot` is not maintained and
   might be removed from the standard library in the future.

.. versionchanged:: 2.5
   The results should be more meaningful than in the past: the timing core
   contained a critical bug.

.. note::

   The :mod:`hotshot` profiler does not yet work well with threads. It is useful to
   use an unthreaded script to run the profiler over the code you're interested in
   measuring if at all possible.


.. class:: Profile(logfile[, lineevents[, linetimings]])

   The profiler object. The argument *logfile* is the name of a log file to use for
   logged profile data. The argument *lineevents* specifies whether to generate
   events for every source line, or just on function call/return. It defaults to
   ``0`` (only log function call/return). The argument *linetimings* specifies
   whether to record timing information. It defaults to ``1`` (store timing
   information).


.. _hotshot-objects:

Profile Objects
---------------

Profile objects have the following methods:


.. method:: Profile.addinfo(key, value)

   Add an arbitrary labelled value to the profile output.


.. method:: Profile.close()

   Close the logfile and terminate the profiler.


.. method:: Profile.fileno()

   Return the file descriptor of the profiler's log file.


.. method:: Profile.run(cmd)

   Profile an :keyword:`exec`\ -compatible string in the script environment. The
   globals from the :mod:`__main__` module are used as both the globals and locals
   for the script.


.. method:: Profile.runcall(func, *args, **keywords)

   Profile a single call of a callable. Additional positional and keyword arguments
   may be passed along; the result of the call is returned, and exceptions are
   allowed to propagate cleanly, while ensuring that profiling is disabled on the
   way out.


.. method:: Profile.runctx(cmd, globals, locals)

   Evaluate an :keyword:`exec`\ -compatible string in a specific environment. The
   string is compiled before profiling begins.


.. method:: Profile.start()

   Start the profiler.


.. method:: Profile.stop()

   Stop the profiler.


Using hotshot data
------------------

.. module:: hotshot.stats
   :synopsis: Statistical analysis for Hotshot


.. versionadded:: 2.2

This module loads hotshot profiling data into the standard :mod:`pstats` Stats
objects.


.. function:: load(filename)

   Load hotshot data from *filename*. Returns an instance of the
   :class:`pstats.Stats` class.


.. seealso::

   Module :mod:`profile`
      The :mod:`profile` module's :class:`Stats` class


.. _hotshot-example:

Example Usage
-------------

Note that this example runs the Python "benchmark" pystones.  It can take some
time to run, and will produce large output files. ::

   >>> import hotshot, hotshot.stats, test.pystone
   >>> prof = hotshot.Profile("stones.prof")
   >>> benchtime, stones = prof.runcall(test.pystone.pystones)
   >>> prof.close()
   >>> stats = hotshot.stats.load("stones.prof")
   >>> stats.strip_dirs()
   >>> stats.sort_stats('time', 'calls')
   >>> stats.print_stats(20)
            850004 function calls in 10.090 CPU seconds

      Ordered by: internal time, call count

      ncalls  tottime  percall  cumtime  percall filename:lineno(function)
           1    3.295    3.295   10.090   10.090 pystone.py:79(Proc0)
      150000    1.315    0.000    1.315    0.000 pystone.py:203(Proc7)
       50000    1.313    0.000    1.463    0.000 pystone.py:229(Func2)
    .
    .
    .

PK	%�\
8���%html/_sources/library/htmllib.rst.txtnu�[���:mod:`htmllib` --- A parser for HTML documents
==============================================

.. module:: htmllib
   :synopsis: A parser for HTML documents.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`htmllib` module has been removed in Python 3.
    Use :mod:`HTMLParser` instead in Python 2, and the equivalent,
    :mod:`html.parser`, in Python 3.


.. index::
   single: HTML
   single: hypertext

.. index::
   module: sgmllib
   module: formatter
   single: SGMLParser (in module sgmllib)

This module defines a class which can serve as a base for parsing text files
formatted in the HyperText Mark-up Language (HTML).  The class is not directly
concerned with I/O --- it must be provided with input in string form via a
method, and makes calls to methods of a "formatter" object in order to produce
output.  The :class:`~HTMLParser.HTMLParser` class is designed to be used as a base class
for other classes in order to add functionality, and allows most of its methods
to be extended or overridden.  In turn, this class is derived from and extends
the :class:`SGMLParser` class defined in module :mod:`sgmllib`.  The
:class:`~HTMLParser.HTMLParser` implementation supports the HTML 2.0 language as described
in :rfc:`1866`.  Two implementations of formatter objects are provided in the
:mod:`formatter` module; refer to the documentation for that module for
information on the formatter interface.

The following is a summary of the interface defined by
:class:`sgmllib.SGMLParser`:

* The interface to feed data to an instance is through the :meth:`feed` method,
  which takes a string argument.  This can be called with as little or as much
  text at a time as desired; ``p.feed(a); p.feed(b)`` has the same effect as
  ``p.feed(a+b)``.  When the data contains complete HTML markup constructs, these
  are processed immediately; incomplete constructs are saved in a buffer.  To
  force processing of all unprocessed data, call the :meth:`close` method.

  For example, to parse the entire contents of a file, use::

     parser.feed(open('myfile.html').read())
     parser.close()

* The interface to define semantics for HTML tags is very simple: derive a class
  and define methods called :meth:`start_tag`, :meth:`end_tag`, or :meth:`do_tag`.
  The parser will call these at appropriate moments: :meth:`start_tag` or
  :meth:`do_tag` is called when an opening tag of the form ``<tag ...>`` is
  encountered; :meth:`end_tag` is called when a closing tag of the form ``<tag>``
  is encountered.  If an opening tag requires a corresponding closing tag, like
  ``<H1>`` ... ``</H1>``, the class should define the :meth:`start_tag` method; if
  a tag requires no closing tag, like ``<P>``, the class should define the
  :meth:`do_tag` method.

The module defines a parser class and an exception:


.. class:: HTMLParser(formatter)

   This is the basic HTML parser class.  It supports all entity names required by
   the XHTML 1.0 Recommendation (https://www.w3.org/TR/xhtml1).   It also defines
   handlers for all HTML 2.0 and many HTML 3.0 and 3.2 elements.


.. exception:: HTMLParseError

   Exception raised by the :class:`~HTMLParser.HTMLParser` class when it encounters an error
   while parsing.

   .. versionadded:: 2.4


.. seealso::

   Module :mod:`formatter`
      Interface definition for transforming an abstract flow of formatting events into
      specific output events on writer objects.

   Module :mod:`HTMLParser`
      Alternate HTML parser that offers a slightly lower-level view of the input, but
      is designed to work with XHTML, and does not implement some of the SGML syntax
      not used in "HTML as deployed" and which isn't legal for XHTML.

   Module :mod:`htmlentitydefs`
      Definition of replacement text for XHTML 1.0  entities.

   Module :mod:`sgmllib`
      Base class for :class:`~HTMLParser.HTMLParser`.


.. _html-parser-objects:

HTMLParser Objects
------------------

In addition to tag methods, the :class:`~HTMLParser.HTMLParser` class provides some
additional methods and instance variables for use within tag methods.


.. attribute:: HTMLParser.formatter

   This is the formatter instance associated with the parser.


.. attribute:: HTMLParser.nofill

   Boolean flag which should be true when whitespace should not be collapsed, or
   false when it should be.  In general, this should only be true when character
   data is to be treated as "preformatted" text, as within a ``<PRE>`` element.
   The default value is false.  This affects the operation of :meth:`handle_data`
   and :meth:`save_end`.


.. method:: HTMLParser.anchor_bgn(href, name, type)

   This method is called at the start of an anchor region.  The arguments
   correspond to the attributes of the ``<A>`` tag with the same names.  The
   default implementation maintains a list of hyperlinks (defined by the ``HREF``
   attribute for ``<A>`` tags) within the document.  The list of hyperlinks is
   available as the data attribute :attr:`anchorlist`.


.. method:: HTMLParser.anchor_end()

   This method is called at the end of an anchor region.  The default
   implementation adds a textual footnote marker using an index into the list of
   hyperlinks created by :meth:`anchor_bgn`.


.. method:: HTMLParser.handle_image(source, alt[, ismap[, align[, width[, height]]]])

   This method is called to handle images.  The default implementation simply
   passes the *alt* value to the :meth:`handle_data` method.


.. method:: HTMLParser.save_bgn()

   Begins saving character data in a buffer instead of sending it to the formatter
   object.  Retrieve the stored data via :meth:`save_end`. Use of the
   :meth:`save_bgn` / :meth:`save_end` pair may not be nested.


.. method:: HTMLParser.save_end()

   Ends buffering character data and returns all data saved since the preceding
   call to :meth:`save_bgn`.  If the :attr:`nofill` flag is false, whitespace is
   collapsed to single spaces.  A call to this method without a preceding call to
   :meth:`save_bgn` will raise a :exc:`TypeError` exception.


:mod:`htmlentitydefs` --- Definitions of HTML general entities
==============================================================

.. module:: htmlentitydefs
   :synopsis: Definitions of HTML general entities.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

.. note::

   The :mod:`htmlentitydefs` module has been renamed to :mod:`html.entities` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.

**Source code:** :source:`Lib/htmlentitydefs.py`

--------------

This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
and ``entitydefs``. ``entitydefs`` is used by the :mod:`htmllib` module to
provide the :attr:`entitydefs` attribute of the :class:`~HTMLParser.HTMLParser` class.  The
definition provided here contains all the entities defined by XHTML 1.0  that
can be handled using simple textual substitution in the Latin-1 character set
(ISO-8859-1).


.. data:: entitydefs

   A dictionary mapping XHTML 1.0 entity definitions to their replacement text in
   ISO Latin-1.


.. data:: name2codepoint

   A dictionary that maps HTML entity names to the Unicode code points.

   .. versionadded:: 2.3


.. data:: codepoint2name

   A dictionary that maps Unicode code points to HTML entity names.

   .. versionadded:: 2.3

PK	%�\�h�x-x-(html/_sources/library/htmlparser.rst.txtnu�[���
:mod:`HTMLParser` --- Simple HTML and XHTML parser
==================================================

.. module:: HTMLParser
   :synopsis: A simple parser that can handle HTML and XHTML.

.. note::

   The :mod:`HTMLParser` module has been renamed to :mod:`html.parser` in Python
   3.  The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.


.. versionadded:: 2.2

.. index::
   single: HTML
   single: XHTML

**Source code:** :source:`Lib/HTMLParser.py`

--------------

This module defines a class :class:`.HTMLParser` which serves as the basis for
parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Unlike the parser in :mod:`htmllib`, this parser is not based on the SGML parser
in :mod:`sgmllib`.


.. class:: HTMLParser()

   An :class:`.HTMLParser` instance is fed HTML data and calls handler methods
   when start tags, end tags, text, comments, and other markup elements are
   encountered.  The user should subclass :class:`.HTMLParser` and override its
   methods to implement the desired behavior.

   The :class:`.HTMLParser` class is instantiated without arguments.

   Unlike the parser in :mod:`htmllib`, this parser does not check that end tags
   match start tags or call the end-tag handler for elements which are closed
   implicitly by closing an outer element.

An exception is defined as well:

.. exception:: HTMLParseError

   :class:`.HTMLParser` is able to handle broken markup, but in some cases it
   might raise this exception when it encounters an error while parsing.
   This exception provides three attributes: :attr:`msg` is a brief
   message explaining the error, :attr:`lineno` is the number of the line on
   which the broken construct was detected, and :attr:`offset` is the number of
   characters into the line at which the construct starts.


Example HTML Parser Application
-------------------------------

As a basic example, below is a simple HTML parser that uses the
:class:`.HTMLParser` class to print out start tags, end tags and data
as they are encountered::

   from HTMLParser import HTMLParser

   # create a subclass and override the handler methods
   class MyHTMLParser(HTMLParser):
       def handle_starttag(self, tag, attrs):
           print "Encountered a start tag:", tag

       def handle_endtag(self, tag):
           print "Encountered an end tag :", tag

       def handle_data(self, data):
           print "Encountered some data  :", data

   # instantiate the parser and fed it some HTML
   parser = MyHTMLParser()
   parser.feed('<html><head><title>Test</title></head>'
               '<body><h1>Parse me!</h1></body></html>')

The output will then be:

.. code-block:: none

   Encountered a start tag: html
   Encountered a start tag: head
   Encountered a start tag: title
   Encountered some data  : Test
   Encountered an end tag : title
   Encountered an end tag : head
   Encountered a start tag: body
   Encountered a start tag: h1
   Encountered some data  : Parse me!
   Encountered an end tag : h1
   Encountered an end tag : body
   Encountered an end tag : html


:class:`.HTMLParser` Methods
----------------------------

:class:`.HTMLParser` instances have the following methods:


.. method:: HTMLParser.feed(data)

   Feed some text to the parser.  It is processed insofar as it consists of
   complete elements; incomplete data is buffered until more data is fed or
   :meth:`close` is called.  *data* can be either :class:`unicode` or
   :class:`str`, but passing :class:`unicode` is advised.


.. method:: HTMLParser.close()

   Force processing of all buffered data as if it were followed by an end-of-file
   mark.  This method may be redefined by a derived class to define additional
   processing at the end of the input, but the redefined version should always call
   the :class:`.HTMLParser` base class method :meth:`close`.


.. method:: HTMLParser.reset()

   Reset the instance.  Loses all unprocessed data.  This is called implicitly at
   instantiation time.


.. method:: HTMLParser.getpos()

   Return current line number and offset.


.. method:: HTMLParser.get_starttag_text()

   Return the text of the most recently opened start tag.  This should not normally
   be needed for structured processing, but may be useful in dealing with HTML "as
   deployed" or for re-generating input with minimal changes (whitespace between
   attributes can be preserved, etc.).


The following methods are called when data or markup elements are encountered
and they are meant to be overridden in a subclass.  The base class
implementations do nothing (except for :meth:`~HTMLParser.handle_startendtag`):


.. method:: HTMLParser.handle_starttag(tag, attrs)

   This method is called to handle the start of a tag (e.g. ``<div id="main">``).

   The *tag* argument is the name of the tag converted to lower case. The *attrs*
   argument is a list of ``(name, value)`` pairs containing the attributes found
   inside the tag's ``<>`` brackets.  The *name* will be translated to lower case,
   and quotes in the *value* have been removed, and character and entity references
   have been replaced.

   For instance, for the tag ``<A HREF="https://www.cwi.nl/">``, this method
   would be called as ``handle_starttag('a', [('href', 'https://www.cwi.nl/')])``.

   .. versionchanged:: 2.6
      All entity references from :mod:`htmlentitydefs` are now replaced in the
      attribute values.


.. method:: HTMLParser.handle_endtag(tag)

   This method is called to handle the end tag of an element (e.g. ``</div>``).

   The *tag* argument is the name of the tag converted to lower case.


.. method:: HTMLParser.handle_startendtag(tag, attrs)

   Similar to :meth:`handle_starttag`, but called when the parser encounters an
   XHTML-style empty tag (``<img ... />``).  This method may be overridden by
   subclasses which require this particular lexical information; the default
   implementation simply calls :meth:`handle_starttag` and :meth:`handle_endtag`.


.. method:: HTMLParser.handle_data(data)

   This method is called to process arbitrary data (e.g. text nodes and the
   content of ``<script>...</script>`` and ``<style>...</style>``).


.. method:: HTMLParser.handle_entityref(name)

   This method is called to process a named character reference of the form
   ``&name;`` (e.g. ``&gt;``), where *name* is a general entity reference
   (e.g. ``'gt'``).


.. method:: HTMLParser.handle_charref(name)

   This method is called to process decimal and hexadecimal numeric character
   references of the form ``&#NNN;`` and ``&#xNNN;``.  For example, the decimal
   equivalent for ``&gt;`` is ``&#62;``, whereas the hexadecimal is ``&#x3E;``;
   in this case the method will receive ``'62'`` or ``'x3E'``.


.. method:: HTMLParser.handle_comment(data)

   This method is called when a comment is encountered (e.g. ``<!--comment-->``).

   For example, the comment ``<!-- comment -->`` will cause this method to be
   called with the argument ``' comment '``.

   The content of Internet Explorer conditional comments (condcoms) will also be
   sent to this method, so, for ``<!--[if IE 9]>IE9-specific content<![endif]-->``,
   this method will receive ``'[if IE 9]>IE9-specific content<![endif]'``.


.. method:: HTMLParser.handle_decl(decl)

   This method is called to handle an HTML doctype declaration (e.g.
   ``<!DOCTYPE html>``).

   The *decl* parameter will be the entire contents of the declaration inside
   the ``<!...>`` markup (e.g. ``'DOCTYPE html'``).


.. method:: HTMLParser.handle_pi(data)

   This method is called when a processing instruction is encountered.  The *data*
   parameter will contain the entire processing instruction.  For example, for the
   processing instruction ``<?proc color='red'>``, this method would be called as
   ``handle_pi("proc color='red'")``.

   .. note::

      The :class:`.HTMLParser` class uses the SGML syntactic rules for processing
      instructions.  An XHTML processing instruction using the trailing ``'?'`` will
      cause the ``'?'`` to be included in *data*.


.. method:: HTMLParser.unknown_decl(data)

   This method is called when an unrecognized declaration is read by the parser.

   The *data* parameter will be the entire contents of the declaration inside
   the ``<![...]>`` markup.  It is sometimes useful to be overridden by a
   derived class.


.. _htmlparser-examples:

Examples
--------

The following class implements a parser that will be used to illustrate more
examples::

   from HTMLParser import HTMLParser
   from htmlentitydefs import name2codepoint

   class MyHTMLParser(HTMLParser):
       def handle_starttag(self, tag, attrs):
           print "Start tag:", tag
           for attr in attrs:
               print "     attr:", attr

       def handle_endtag(self, tag):
           print "End tag  :", tag

       def handle_data(self, data):
           print "Data     :", data

       def handle_comment(self, data):
           print "Comment  :", data

       def handle_entityref(self, name):
           c = unichr(name2codepoint[name])
           print "Named ent:", c

       def handle_charref(self, name):
           if name.startswith('x'):
               c = unichr(int(name[1:], 16))
           else:
               c = unichr(int(name))
           print "Num ent  :", c

       def handle_decl(self, data):
           print "Decl     :", data

   parser = MyHTMLParser()

Parsing a doctype::

   >>> parser.feed('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" '
   ...             '"http://www.w3.org/TR/html4/strict.dtd">')
   Decl     : DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"

Parsing an element with a few attributes and a title::

   >>> parser.feed('<img src="python-logo.png" alt="The Python logo">')
   Start tag: img
        attr: ('src', 'python-logo.png')
        attr: ('alt', 'The Python logo')
   >>>
   >>> parser.feed('<h1>Python</h1>')
   Start tag: h1
   Data     : Python
   End tag  : h1

The content of ``script`` and ``style`` elements is returned as is, without
further parsing::

   >>> parser.feed('<style type="text/css">#python { color: green }</style>')
   Start tag: style
        attr: ('type', 'text/css')
   Data     : #python { color: green }
   End tag  : style

   >>> parser.feed('<script type="text/javascript">'
   ...             'alert("<strong>hello!</strong>");</script>')
   Start tag: script
        attr: ('type', 'text/javascript')
   Data     : alert("<strong>hello!</strong>");
   End tag  : script

Parsing comments::

   >>> parser.feed('<!-- a comment -->'
   ...             '<!--[if IE 9]>IE-specific content<![endif]-->')
   Comment  :  a comment
   Comment  : [if IE 9]>IE-specific content<![endif]

Parsing named and numeric character references and converting them to the
correct char (note: these 3 references are all equivalent to ``'>'``)::

   >>> parser.feed('&gt;&#62;&#x3E;')
   Named ent: >
   Num ent  : >
   Num ent  : >

Feeding incomplete chunks to :meth:`~HTMLParser.feed` works, but
:meth:`~HTMLParser.handle_data` might be called more than once::

   >>> for chunk in ['<sp', 'an>buff', 'ered ', 'text</s', 'pan>']:
   ...     parser.feed(chunk)
   ...
   Start tag: span
   Data     : buff
   Data     : ered
   Data     : text
   End tag  : span

Parsing invalid HTML (e.g. unquoted attributes) also works::

   >>> parser.feed('<p><a class=link href=#main>tag soup</p ></a>')
   Start tag: p
   Start tag: a
        attr: ('class', 'link')
        attr: ('href', '#main')
   Data     : tag soup
   End tag  : p
   End tag  : a
PK	%�\���N�N�%html/_sources/library/httplib.rst.txtnu�[���:mod:`httplib` --- HTTP protocol client
=======================================

.. module:: httplib
   :synopsis: HTTP and HTTPS protocol client (requires sockets).

.. note::
   The :mod:`httplib` module has been renamed to :mod:`http.client` in Python
   3.  The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.


.. index::
   pair: HTTP; protocol
   single: HTTP; httplib (standard module)

.. index:: module: urllib

**Source code:** :source:`Lib/httplib.py`

--------------

This module defines classes which implement the client side of the HTTP and
HTTPS protocols.  It is normally not used directly --- the module :mod:`urllib`
uses it to handle URLs that use HTTP and HTTPS.

.. seealso::

    The `Requests package <http://requests.readthedocs.org/>`_
    is recommended for a higher-level HTTP client interface.

.. note::

   HTTPS support is only available if the :mod:`socket` module was compiled with
   SSL support.

.. note::

   The public interface for this module changed substantially in Python 2.0.  The
   :class:`HTTP` class is retained only for backward compatibility with 1.5.2.  It
   should not be used in new code.  Refer to the online docstrings for usage.

The module provides the following classes:


.. class:: HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])

   An :class:`HTTPConnection` instance represents one transaction with an HTTP
   server.  It should be instantiated passing it a host and optional port
   number.  If no port number is passed, the port is extracted from the host
   string if it has the form ``host:port``, else the default HTTP port (80) is
   used.  When true, the optional parameter *strict* (which defaults to a false
   value) causes ``BadStatusLine`` to
   be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1
   status line.  If the optional *timeout* parameter is given, blocking
   operations (like connection attempts) will timeout after that many seconds
   (if it is not given, the global default timeout setting is used).
   The optional *source_address* parameter may be a tuple of a (host, port)
   to use as the source address the HTTP connection is made from.

   For example, the following calls all create instances that connect to the server
   at the same host and port::

      >>> h1 = httplib.HTTPConnection('www.cwi.nl')
      >>> h2 = httplib.HTTPConnection('www.cwi.nl:80')
      >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80)
      >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10)

   .. versionadded:: 2.0

   .. versionchanged:: 2.6
      *timeout* was added.

   .. versionchanged:: 2.7
      *source_address* was added.


.. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout[, source_address[, context]]]]]]])

   A subclass of :class:`HTTPConnection` that uses SSL for communication with
   secure servers.  Default port is ``443``.  If *context* is specified, it must
   be a :class:`ssl.SSLContext` instance describing the various SSL options.

   *key_file* and *cert_file* are deprecated, please use
   :meth:`ssl.SSLContext.load_cert_chain` instead, or let
   :func:`ssl.create_default_context` select the system's trusted CA
   certificates for you.

   Please read :ref:`ssl-security` for more information on best practices.

   .. versionadded:: 2.0

   .. versionchanged:: 2.6
      *timeout* was added.

   .. versionchanged:: 2.7
      *source_address* was added.

   .. versionchanged:: 2.7.9
      *context* was added.

      This class now performs all the necessary certificate and hostname checks
      by default. To revert to the previous, unverified, behavior
      :func:`ssl._create_unverified_context` can be passed to the *context*
      parameter.


.. class:: HTTPResponse(sock, debuglevel=0, strict=0)

   Class whose instances are returned upon successful connection.  Not instantiated
   directly by user.

   .. versionadded:: 2.0

.. class:: HTTPMessage

   An :class:`HTTPMessage` instance is used to hold the headers from an HTTP
   response. It is implemented using the :class:`mimetools.Message` class and
   provides utility functions to deal with HTTP Headers. It is not directly
   instantiated by the users.


The following exceptions are raised as appropriate:


.. exception:: HTTPException

   The base class of the other exceptions in this module.  It is a subclass of
   :exc:`Exception`.

   .. versionadded:: 2.0


.. exception:: NotConnected

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: InvalidURL

   A subclass of :exc:`HTTPException`, raised if a port is given and is either
   non-numeric or empty.

   .. versionadded:: 2.3


.. exception:: UnknownProtocol

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: UnknownTransferEncoding

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: UnimplementedFileMode

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: IncompleteRead

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: ImproperConnectionState

   A subclass of :exc:`HTTPException`.

   .. versionadded:: 2.0


.. exception:: CannotSendRequest

   A subclass of :exc:`ImproperConnectionState`.

   .. versionadded:: 2.0


.. exception:: CannotSendHeader

   A subclass of :exc:`ImproperConnectionState`.

   .. versionadded:: 2.0


.. exception:: ResponseNotReady

   A subclass of :exc:`ImproperConnectionState`.

   .. versionadded:: 2.0


.. exception:: BadStatusLine

   A subclass of :exc:`HTTPException`.  Raised if a server responds with a HTTP
   status code that we don't understand.

   .. versionadded:: 2.0

The constants defined in this module are:


.. data:: HTTP_PORT

   The default port for the HTTP protocol (always ``80``).


.. data:: HTTPS_PORT

   The default port for the HTTPS protocol (always ``443``).

and also the following constants for integer status codes:

+------------------------------------------+---------+-----------------------------------------------------------------------+
| Constant                                 | Value   | Definition                                                            |
+==========================================+=========+=======================================================================+
| :const:`CONTINUE`                        | ``100`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.1.1                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`SWITCHING_PROTOCOLS`             | ``101`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.1.2                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.2>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`PROCESSING`                      | ``102`` | WEBDAV, `RFC 2518, Section 10.1                                       |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_102>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`OK`                              | ``200`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.1                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`CREATED`                         | ``201`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.2                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`ACCEPTED`                        | ``202`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.3                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NON_AUTHORITATIVE_INFORMATION`   | ``203`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.4                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.4>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NO_CONTENT`                      | ``204`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.5                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`RESET_CONTENT`                   | ``205`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.6                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`PARTIAL_CONTENT`                 | ``206`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.2.7                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`MULTI_STATUS`                    | ``207`` | WEBDAV `RFC 2518, Section 10.2                                        |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_207>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`IM_USED`                         | ``226`` | Delta encoding in HTTP,                                               |
|                                          |         | :rfc:`3229`, Section 10.4.1                                           |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`MULTIPLE_CHOICES`                | ``300`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.1                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`MOVED_PERMANENTLY`               | ``301`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.2                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`FOUND`                           | ``302`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.3                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`SEE_OTHER`                       | ``303`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.4                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NOT_MODIFIED`                    | ``304`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.5                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`USE_PROXY`                       | ``305`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.6                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.6>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`TEMPORARY_REDIRECT`              | ``307`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.3.8                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`BAD_REQUEST`                     | ``400`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.1                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`UNAUTHORIZED`                    | ``401`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.2                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`PAYMENT_REQUIRED`                | ``402`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.3                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.3>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`FORBIDDEN`                       | ``403`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.4                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NOT_FOUND`                       | ``404`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.5                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`METHOD_NOT_ALLOWED`              | ``405`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.6                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NOT_ACCEPTABLE`                  | ``406`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.7                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`PROXY_AUTHENTICATION_REQUIRED`   | ``407`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.8                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`REQUEST_TIMEOUT`                 | ``408`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.9                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`CONFLICT`                        | ``409`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.10                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`GONE`                            | ``410`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.11                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`LENGTH_REQUIRED`                 | ``411`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.12                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.12>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`PRECONDITION_FAILED`             | ``412`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.13                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.13>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`REQUEST_ENTITY_TOO_LARGE`        | ``413`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.14                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.14>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`REQUEST_URI_TOO_LONG`            | ``414`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.15                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`UNSUPPORTED_MEDIA_TYPE`          | ``415`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.16                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`REQUESTED_RANGE_NOT_SATISFIABLE` | ``416`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.17                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`EXPECTATION_FAILED`              | ``417`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.4.18                                                               |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.18>`_ |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`UNPROCESSABLE_ENTITY`            | ``422`` | WEBDAV, `RFC 2518, Section 10.3                                       |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_422>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`LOCKED`                          | ``423`` | WEBDAV `RFC 2518, Section 10.4                                        |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_423>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`FAILED_DEPENDENCY`               | ``424`` | WEBDAV, `RFC 2518, Section 10.5                                       |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_424>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`UPGRADE_REQUIRED`                | ``426`` | HTTP Upgrade to TLS,                                                  |
|                                          |         | :rfc:`2817`, Section 6                                                |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`INTERNAL_SERVER_ERROR`           | ``500`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.5.1                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NOT_IMPLEMENTED`                 | ``501`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.5.2                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`BAD_GATEWAY`                     | ``502`` | HTTP/1.1 `RFC 2616, Section                                           |
|                                          |         | 10.5.3                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`SERVICE_UNAVAILABLE`             | ``503`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.5.4                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`GATEWAY_TIMEOUT`                 | ``504`` | HTTP/1.1 `RFC 2616, Section                                           |
|                                          |         | 10.5.5                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`HTTP_VERSION_NOT_SUPPORTED`      | ``505`` | HTTP/1.1, `RFC 2616, Section                                          |
|                                          |         | 10.5.6                                                                |
|                                          |         | <http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.6>`_  |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`INSUFFICIENT_STORAGE`            | ``507`` | WEBDAV, `RFC 2518, Section 10.6                                       |
|                                          |         | <http://www.webdav.org/specs/rfc2518.html#STATUS_507>`_               |
+------------------------------------------+---------+-----------------------------------------------------------------------+
| :const:`NOT_EXTENDED`                    | ``510`` | An HTTP Extension Framework,                                          |
|                                          |         | :rfc:`2774`, Section 7                                                |
+------------------------------------------+---------+-----------------------------------------------------------------------+


.. data:: responses

   This dictionary maps the HTTP 1.1 status codes to the W3C names.

   Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``.

   .. versionadded:: 2.5


.. _httpconnection-objects:

HTTPConnection Objects
----------------------

:class:`HTTPConnection` instances have the following methods:


.. method:: HTTPConnection.request(method, url[, body[, headers]])

   This will send a request to the server using the HTTP request method *method*
   and the selector *url*.  If the *body* argument is present, it should be a
   string of data to send after the headers are finished. Alternatively, it may
   be an open file object, in which case the contents of the file is sent; this
   file object should support ``fileno()`` and ``read()`` methods. The
   *headers* argument should be a mapping of extra HTTP headers to send with
   the request.

   If one is not provided in *headers*, a ``Content-Length`` header is added
   automatically for all methods if the length of the body can be determined,
   either from the length of the ``str`` representation, or from the reported
   size of the file on disk. If *body* is ``None`` the header is not set except
   for methods that expect a body (``PUT``, ``POST``, and ``PATCH``) in which
   case it is set to ``0``.

   .. versionchanged:: 2.6
      *body* can be a file object.


.. method:: HTTPConnection.getresponse()

   Should be called after a request is sent to get the response from the server.
   Returns an :class:`HTTPResponse` instance.

   .. note::

      Note that you must have read the whole response before you can send a new
      request to the server.


.. method:: HTTPConnection.set_debuglevel(level)

   Set the debugging level (the amount of debugging output printed). The default
   debug level is ``0``, meaning no debugging output is printed.


.. method:: HTTPConnection.set_tunnel(host,port=None, headers=None)

   Set the host and the port for HTTP Connect Tunnelling. Normally used when
   it is required to do HTTPS Connection through a proxy server.

   The headers argument should be a mapping of extra HTTP headers to send
   with the CONNECT request.

   .. versionadded:: 2.7


.. method:: HTTPConnection.connect()

   Connect to the server specified when the object was created.


.. method:: HTTPConnection.close()

   Close the connection to the server.

As an alternative to using the :meth:`request` method described above, you can
also send your request step by step, by using the four functions below.


.. method:: HTTPConnection.putrequest(request, selector[, skip_host[, skip_accept_encoding]])

   This should be the first call after the connection to the server has been made.
   It sends a line to the server consisting of the *request* string, the *selector*
   string, and the HTTP version (``HTTP/1.1``).  To disable automatic sending of
   ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional
   content encodings), specify *skip_host* or *skip_accept_encoding* with non-False
   values.

   .. versionchanged:: 2.4
      *skip_accept_encoding* argument added.


.. method:: HTTPConnection.putheader(header, argument[, ...])

   Send an :rfc:`822`\ -style header to the server.  It sends a line to the server
   consisting of the header, a colon and a space, and the first argument.  If more
   arguments are given, continuation lines are sent, each consisting of a tab and
   an argument.


.. method:: HTTPConnection.endheaders(message_body=None)

   Send a blank line to the server, signalling the end of the headers. The
   optional *message_body* argument can be used to pass a message body
   associated with the request.  The message body will be sent in the same
   packet as the message headers if it is string, otherwise it is sent in a
   separate packet.

   .. versionchanged:: 2.7
      *message_body* was added.


.. method:: HTTPConnection.send(data)

   Send data to the server.  This should be used directly only after the
   :meth:`endheaders` method has been called and before :meth:`getresponse` is
   called.


.. _httpresponse-objects:

HTTPResponse Objects
--------------------

:class:`HTTPResponse` instances have the following methods and attributes:


.. method:: HTTPResponse.read([amt])

   Reads and returns the response body, or up to the next *amt* bytes.


.. method:: HTTPResponse.getheader(name[, default])

   Get the contents of the header *name*, or *default* if there is no matching
   header.


.. method:: HTTPResponse.getheaders()

   Return a list of (header, value) tuples.

   .. versionadded:: 2.4

.. method:: HTTPResponse.fileno()

   Returns the ``fileno`` of the underlying socket.

.. attribute:: HTTPResponse.msg

   A :class:`mimetools.Message` instance containing the response headers.


.. attribute:: HTTPResponse.version

   HTTP protocol version used by server.  10 for HTTP/1.0, 11 for HTTP/1.1.


.. attribute:: HTTPResponse.status

   Status code returned by server.


.. attribute:: HTTPResponse.reason

   Reason phrase returned by server.


.. _httplib-examples:

Examples
--------

Here is an example session that uses the ``GET`` method::

   >>> import httplib
   >>> conn = httplib.HTTPSConnection("www.python.org")
   >>> conn.request("GET", "/")
   >>> r1 = conn.getresponse()
   >>> print r1.status, r1.reason
   200 OK
   >>> data1 = r1.read()
   >>> conn.request("GET", "/")
   >>> r2 = conn.getresponse()
   >>> print r2.status, r2.reason
   404 Not Found
   >>> data2 = r2.read()
   >>> conn.close()

Here is an example session that uses the ``HEAD`` method.  Note that the
``HEAD`` method never returns any data. ::

   >>> import httplib
   >>> conn = httplib.HTTPSConnection("www.python.org")
   >>> conn.request("HEAD","/")
   >>> res = conn.getresponse()
   >>> print res.status, res.reason
   200 OK
   >>> data = res.read()
   >>> print len(data)
   0
   >>> data == ''
   True

Here is an example session that shows how to ``POST`` requests::

   >>> import httplib, urllib
   >>> params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
   >>> headers = {"Content-type": "application/x-www-form-urlencoded",
   ...            "Accept": "text/plain"}
   >>> conn = httplib.HTTPConnection("bugs.python.org")
   >>> conn.request("POST", "", params, headers)
   >>> response = conn.getresponse()
   >>> print response.status, response.reason
   302 Found
   >>> data = response.read()
   >>> data
   'Redirecting to <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>'
   >>> conn.close()

Client side ``HTTP PUT`` requests are very similar to ``POST`` requests. The
difference lies only the server side where HTTP server will allow resources to
be created via ``PUT`` request. Here is an example session that shows how to do
``PUT`` request using httplib::

    >>> # This creates an HTTP message
    >>> # with the content of BODY as the enclosed representation
    >>> # for the resource http://localhost:8080/foobar
    ...
    >>> import httplib
    >>> BODY = "***filecontents***"
    >>> conn = httplib.HTTPConnection("localhost", 8080)
    >>> conn.request("PUT", "/file", BODY)
    >>> response = conn.getresponse()
    >>> print response.status, response.reason
    200, OK

PK	%�\<[���"html/_sources/library/i18n.rst.txtnu�[���
.. _i18n:

********************
Internationalization
********************

The modules described in this chapter help you write software that is
independent of language and locale by providing mechanisms for selecting a
language to be used in  program messages or by tailoring output to match local
conventions.

The list of modules described in this chapter is:


.. toctree::

   gettext.rst
   locale.rst
PK	%�\�\� html/_sources/library/ic.rst.txtnu�[���:mod:`ic` --- Access to the Mac OS X Internet Config
====================================================

.. module:: ic
   :platform: Mac
   :synopsis: Access to the Mac OS X Internet Config.
   :deprecated:


This module provides access to various internet-related preferences set through
:program:`System Preferences` or the :program:`Finder`.

.. note::

   This module has been removed in Python 3.x.


.. index:: module: icglue

There is a low-level companion module :mod:`icglue` which provides the basic
Internet Config access functionality.  This low-level module is not documented,
but the docstrings of the routines document the parameters and the routine names
are the same as for the Pascal or C API to Internet Config, so the standard IC
programmers' documentation can be used if this module is needed.

The :mod:`ic` module defines the :exc:`error` exception and symbolic names for
all error codes Internet Config can produce; see the source for details.


.. exception:: error

   Exception raised on errors in the :mod:`ic` module.

The :mod:`ic` module defines the following class and function:


.. class:: IC([signature[, ic]])

   Create an Internet Config object. The signature is a 4-character creator code of
   the current application (default ``'Pyth'``) which may influence some of ICs
   settings. The optional *ic* argument is a low-level ``icglue.icinstance``
   created beforehand, this may be useful if you want to get preferences from a
   different config file, etc.


.. function:: launchurl(url[, hint])
              parseurl(data[, start[, end[, hint]]])
              mapfile(file)
              maptypecreator(type, creator[, filename])
              settypecreator(file)

   These functions are "shortcuts" to the methods of the same name, described
   below.


IC Objects
----------

:class:`IC` objects have a mapping interface, hence to obtain the mail address
you simply get ``ic['MailAddress']``. Assignment also works, and changes the
option in the configuration file.

The module knows about various datatypes, and converts the internal IC
representation to a "logical" Python data structure. Running the :mod:`ic`
module standalone will run a test program that lists all keys and values in your
IC database, this will have to serve as documentation.

If the module does not know how to represent the data it returns an instance of
the ``ICOpaqueData`` type, with the raw data in its :attr:`data` attribute.
Objects of this type are also acceptable values for assignment.

Besides the dictionary interface, :class:`IC` objects have the following
methods:


.. method:: IC.launchurl(url[, hint])

   Parse the given URL, launch the correct application and pass it the URL. The
   optional *hint* can be a scheme name such as ``'mailto:'``, in which case
   incomplete URLs are completed with this scheme.  If *hint* is not provided,
   incomplete URLs are invalid.


.. method:: IC.parseurl(data[, start[, end[, hint]]])

   Find a URL somewhere in *data* and return start position, end position and the
   URL. The optional *start* and *end* can be used to limit the search, so for
   instance if a user clicks in a long text field you can pass the whole text field
   and the click-position in *start* and this routine will return the whole URL in
   which the user clicked.  As above, *hint* is an optional scheme used to complete
   incomplete URLs.


.. method:: IC.mapfile(file)

   Return the mapping entry for the given *file*, which can be passed as either a
   filename or an :func:`FSSpec` result, and which need not exist.

   The mapping entry is returned as a tuple ``(version, type, creator, postcreator,
   flags, extension, appname, postappname, mimetype, entryname)``, where *version*
   is the entry version number, *type* is the 4-character filetype, *creator* is
   the 4-character creator type, *postcreator* is the 4-character creator code of
   an optional application to post-process the file after downloading, *flags* are
   various bits specifying whether to transfer in binary or ascii and such,
   *extension* is the filename extension for this file type, *appname* is the
   printable name of the application to which this file belongs, *postappname* is
   the name of the postprocessing application, *mimetype* is the MIME type of this
   file and *entryname* is the name of this entry.


.. method:: IC.maptypecreator(type, creator[, filename])

   Return the mapping entry for files with given 4-character *type* and *creator*
   codes. The optional *filename* may be specified to further help finding the
   correct entry (if the creator code is ``'????'``, for instance).

   The mapping entry is returned in the same format as for *mapfile*.


.. method:: IC.settypecreator(file)

   Given an existing *file*, specified either as a filename or as an :func:`FSSpec`
   result, set its creator and type correctly based on its extension.  The finder
   is told about the change, so the finder icon will be updated quickly.
PK	%�\�+��V�V"html/_sources/library/idle.rst.txtnu�[���.. _idle:

IDLE
====

.. index::
   single: IDLE
   single: Python Editor
   single: Integrated Development Environment

.. moduleauthor:: Guido van Rossum <guido@python.org>

IDLE is Python's Integrated Development and Learning Environment.

IDLE has the following features:

* coded in 100% pure Python, using the :mod:`tkinter` GUI toolkit

* cross-platform: works mostly the same on Windows, Unix, and Mac OS X

* Python shell window (interactive interpreter) with colorizing
  of code input, output, and error messages

* multi-window text editor with multiple undo, Python colorizing,
  smart indent, call tips, auto completion, and other features

* search within any window, replace within editor windows, and search
  through multiple files (grep)

* debugger with persistent breakpoints, stepping, and viewing
  of global and local namespaces

* configuration, browsers, and other dialogs

Menus
-----

IDLE has two main window types, the Shell window and the Editor window.  It is
possible to have multiple editor windows simultaneously.  Output windows, such
as used for Edit / Find in Files, are a subtype of edit window.  They currently
have the same top menu as Editor windows but a different default title and
context menu.

IDLE's menus dynamically change based on which window is currently selected.
Each menu documented below indicates which window type it is associated with.

File menu (Shell and Editor)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

New File
   Create a new file editing window.

Open...
   Open an existing file with an Open dialog.

Recent Files
   Open a list of recent files.  Click one to open it.

Open Module...
   Open an existing module (searches sys.path).

.. index::
   single: Class browser
   single: Path browser

Class Browser
   Show functions, classes, and methods in the current Editor file in a
   tree structure.  In the shell, open a module first.

Path Browser
   Show sys.path directories, modules, functions, classes and methods in a
   tree structure.

Save
   Save the current window to the associated file, if there is one.  Windows
   that have been changed since being opened or last saved have a \* before
   and after the window title.  If there is no associated file,
   do Save As instead.

Save As...
   Save the current window with a Save As dialog.  The file saved becomes the
   new associated file for the window.

Save Copy As...
   Save the current window to different file without changing the associated
   file.

Print Window
   Print the current window to the default printer.

Close
   Close the current window (ask to save if unsaved).

Exit
   Close all windows and quit IDLE (ask to save unsaved windows).

Edit menu (Shell and Editor)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Undo
   Undo the last change to the current window.  A maximum of 1000 changes may
   be undone.

Redo
   Redo the last undone change to the current window.

Cut
   Copy selection into the system-wide clipboard; then delete the selection.

Copy
   Copy selection into the system-wide clipboard.

Paste
   Insert contents of the system-wide clipboard into the current window.

The clipboard functions are also available in context menus.

Select All
   Select the entire contents of the current window.

Find...
   Open a search dialog with many options

Find Again
   Repeat the last search, if there is one.

Find Selection
   Search for the currently selected string, if there is one.

Find in Files...
   Open a file search dialog.  Put results in a new output window.

Replace...
   Open a search-and-replace dialog.

Go to Line
   Move cursor to the line number requested and make that line visible.

Show Completions
   Open a scrollable list allowing selection of keywords and attributes. See
   Completions in the Tips sections below.

Expand Word
   Expand a prefix you have typed to match a full word in the same window;
   repeat to get a different expansion.

Show call tip
   After an unclosed parenthesis for a function, open a small window with
   function parameter hints.

Show surrounding parens
   Highlight the surrounding parenthesis.

Format menu (Editor window only)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Indent Region
   Shift selected lines right by the indent width (default 4 spaces).

Dedent Region
   Shift selected lines left by the indent width (default 4 spaces).

Comment Out Region
   Insert ## in front of selected lines.

Uncomment Region
   Remove leading # or ## from selected lines.

Tabify Region
   Turn *leading* stretches of spaces into tabs. (Note: We recommend using
   4 space blocks to indent Python code.)

Untabify Region
   Turn *all* tabs into the correct number of spaces.

Toggle Tabs
   Open a dialog to switch between indenting with spaces and tabs.

New Indent Width
   Open a dialog to change indent width. The accepted default by the Python
   community is 4 spaces.

Format Paragraph
   Reformat the current blank-line-delimited paragraph in comment block or
   multiline string or selected line in a string.  All lines in the
   paragraph will be formatted to less than N columns, where N defaults to 72.

Strip trailing whitespace
   Remove any space characters after the last non-space character of a line.

.. index::
   single: Run script

Run menu (Editor window only)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Python Shell
   Open or wake up the Python Shell window.

Check Module
   Check the syntax of the module currently open in the Editor window. If the
   module has not been saved IDLE will either prompt the user to save or
   autosave, as selected in the General tab of the Idle Settings dialog.  If
   there is a syntax error, the approximate location is indicated in the
   Editor window.

Run Module
   Do Check Module (above).  If no error, restart the shell to clean the
   environment, then execute the module.  Output is displayed in the Shell
   window.  Note that output requires use of ``print`` or ``write``.
   When execution is complete, the Shell retains focus and displays a prompt.
   At this point, one may interactively explore the result of execution.
   This is similar to executing a file with ``python -i file`` at a command
   line.

Shell menu (Shell window only)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

View Last Restart
  Scroll the shell window to the last Shell restart.

Restart Shell
  Restart the shell to clean the environment.

Interrupt Execution
  Stop a running program.

Debug menu (Shell window only)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Go to File/Line
   Look on the current line. with the cursor, and the line above for a filename
   and line number.  If found, open the file if not already open, and show the
   line.  Use this to view source lines referenced in an exception traceback
   and lines found by Find in Files. Also available in the context menu of
   the Shell window and Output windows.

.. index::
   single: debugger
   single: stack viewer

Debugger (toggle)
   When activated, code entered in the Shell or run from an Editor will run
   under the debugger.  In the Editor, breakpoints can be set with the context
   menu.  This feature is still incomplete and somewhat experimental.

Stack Viewer
   Show the stack traceback of the last exception in a tree widget, with
   access to locals and globals.

Auto-open Stack Viewer
   Toggle automatically opening the stack viewer on an unhandled exception.

Options menu (Shell and Editor)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Configure IDLE
   Open a configuration dialog and change preferences for the following:
   fonts, indentation, keybindings, text color themes, startup windows and
   size, additional help sources, and extensions (see below).  On OS X,
   open the configuration dialog by selecting Preferences in the application
   menu.  To use a new built-in color theme (IDLE Dark) with older IDLEs,
   save it as a new custom theme.

   Non-default user settings are saved in a .idlerc directory in the user's
   home directory.  Problems caused by bad user configuration files are solved
   by editing or deleting one or more of the files in .idlerc.

Code Context (toggle)(Editor Window only)
   Open a pane at the top of the edit window which shows the block context
   of the code which has scrolled above the top of the window.

Window menu (Shell and Editor)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Zoom Height
   Toggles the window between normal size and maximum height. The initial size
   defaults to 40 lines by 80 chars unless changed on the General tab of the
   Configure IDLE dialog.

The rest of this menu lists the names of all open windows; select one to bring
it to the foreground (deiconifying it if necessary).

Help menu (Shell and Editor)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

About IDLE
   Display version, copyright, license, credits, and more.

IDLE Help
   Display a help file for IDLE detailing the menu options, basic editing and
   navigation, and other tips.

Python Docs
   Access local Python documentation, if installed, or start a web browser
   and open docs.python.org showing the latest Python documentation.

Turtle Demo
   Run the turtledemo module with example python code and turtle drawings.

Additional help sources may be added here with the Configure IDLE dialog under
the General tab.

.. index::
   single: Cut
   single: Copy
   single: Paste
   single: Set Breakpoint
   single: Clear Breakpoint
   single: breakpoints

Context Menus
^^^^^^^^^^^^^^^^^^^^^^^^^^

Open a context menu by right-clicking in a window (Control-click on OS X).
Context menus have the standard clipboard functions also on the Edit menu.

Cut
   Copy selection into the system-wide clipboard; then delete the selection.

Copy
   Copy selection into the system-wide clipboard.

Paste
   Insert contents of the system-wide clipboard into the current window.

Editor windows also have breakpoint functions.  Lines with a breakpoint set are
specially marked.  Breakpoints only have an effect when running under the
debugger.  Breakpoints for a file are saved in the user's .idlerc directory.

Set Breakpoint
   Set a breakpoint on the current line.

Clear Breakpoint
   Clear the breakpoint on that line.

Shell and Output windows have the following.

Go to file/line
   Same as in Debug menu.


Editing and navigation
----------------------

In this section, 'C' refers to the :kbd:`Control` key on Windows and Unix and
the :kbd:`Command` key on Mac OSX.

* :kbd:`Backspace` deletes to the left; :kbd:`Del` deletes to the right

* :kbd:`C-Backspace` delete word left; :kbd:`C-Del` delete word to the right

* Arrow keys and :kbd:`Page Up`/:kbd:`Page Down` to move around

* :kbd:`C-LeftArrow` and :kbd:`C-RightArrow` moves by words

* :kbd:`Home`/:kbd:`End` go to begin/end of line

* :kbd:`C-Home`/:kbd:`C-End` go to begin/end of file

* Some useful Emacs bindings are inherited from Tcl/Tk:

   * :kbd:`C-a` beginning of line

   * :kbd:`C-e` end of line

   * :kbd:`C-k` kill line (but doesn't put it in clipboard)

   * :kbd:`C-l` center window around the insertion point

   * :kbd:`C-b` go backward one character without deleting (usually you can
     also use the cursor key for this)

   * :kbd:`C-f` go forward one character without deleting (usually you can
     also use the cursor key for this)

   * :kbd:`C-p` go up one line (usually you can also use the cursor key for
     this)

   * :kbd:`C-d` delete next character

Standard keybindings (like :kbd:`C-c` to copy and :kbd:`C-v` to paste)
may work.  Keybindings are selected in the Configure IDLE dialog.


Automatic indentation
^^^^^^^^^^^^^^^^^^^^^

After a block-opening statement, the next line is indented by 4 spaces (in the
Python Shell window by one tab).  After certain keywords (break, return etc.)
the next line is dedented.  In leading indentation, :kbd:`Backspace` deletes up
to 4 spaces if they are there. :kbd:`Tab` inserts spaces (in the Python
Shell window one tab), number depends on Indent width. Currently, tabs
are restricted to four spaces due to Tcl/Tk limitations.

See also the indent/dedent region commands in the edit menu.

Completions
^^^^^^^^^^^

Completions are supplied for functions, classes, and attributes of classes,
both built-in and user-defined. Completions are also provided for
filenames.

The AutoCompleteWindow (ACW) will open after a predefined delay (default is
two seconds) after a '.' or (in a string) an os.sep is typed. If after one
of those characters (plus zero or more other characters) a tab is typed
the ACW will open immediately if a possible continuation is found.

If there is only one possible completion for the characters entered, a
:kbd:`Tab` will supply that completion without opening the ACW.

'Show Completions' will force open a completions window, by default the
:kbd:`C-space` will open a completions window. In an empty
string, this will contain the files in the current directory. On a
blank line, it will contain the built-in and user-defined functions and
classes in the current namespaces, plus any modules imported. If some
characters have been entered, the ACW will attempt to be more specific.

If a string of characters is typed, the ACW selection will jump to the
entry most closely matching those characters.  Entering a :kbd:`tab` will
cause the longest non-ambiguous match to be entered in the Editor window or
Shell.  Two :kbd:`tab` in a row will supply the current ACW selection, as
will return or a double click.  Cursor keys, Page Up/Down, mouse selection,
and the scroll wheel all operate on the ACW.

"Hidden" attributes can be accessed by typing the beginning of hidden
name after a '.', e.g. '_'. This allows access to modules with
``__all__`` set, or to class-private attributes.

Completions and the 'Expand Word' facility can save a lot of typing!

Completions are currently limited to those in the namespaces. Names in
an Editor window which are not via ``__main__`` and :data:`sys.modules` will
not be found.  Run the module once with your imports to correct this situation.
Note that IDLE itself places quite a few modules in sys.modules, so
much can be found by default, e.g. the re module.

If you don't like the ACW popping up unbidden, simply make the delay
longer or disable the extension.

Calltips
^^^^^^^^

A calltip is shown when one types :kbd:`(` after the name of an *accessible*
function.  A name expression may include dots and subscripts.  A calltip
remains until it is clicked, the cursor is moved out of the argument area,
or :kbd:`)` is typed.  When the cursor is in the argument part of a definition,
the menu or shortcut display a calltip.

A calltip consists of the function signature and the first line of the
docstring.  For builtins without an accessible signature, the calltip
consists of all lines up the fifth line or the first blank line.  These
details may change.

The set of *accessible* functions depends on what modules have been imported
into the user process, including those imported by Idle itself,
and what definitions have been run, all since the last restart.

For example, restart the Shell and enter ``itertools.count(``.  A calltip
appears because Idle imports itertools into the user process for its own use.
(This could change.)  Enter ``turtle.write(`` and nothing appears.  Idle does
not import turtle.  The menu or shortcut do nothing either.  Enter
``import turtle`` and then ``turtle.write(`` will work.

In an editor, import statements have no effect until one runs the file.  One
might want to run a file after writing the import statements at the top,
or immediately run an existing file before editing.

Python Shell window
^^^^^^^^^^^^^^^^^^^

* :kbd:`C-c` interrupts executing command

* :kbd:`C-d` sends end-of-file; closes window if typed at a ``>>>`` prompt

* :kbd:`Alt-/` (Expand word) is also useful to reduce typing

  Command history

  * :kbd:`Alt-p` retrieves previous command matching what you have typed. On
    OS X use :kbd:`C-p`.

  * :kbd:`Alt-n` retrieves next. On OS X use :kbd:`C-n`.

  * :kbd:`Return` while on any previous command retrieves that command


Text colors
^^^^^^^^^^^

Idle defaults to black on white text, but colors text with special meanings.
For the shell, these are shell output, shell error, user output, and
user error.  For Python code, at the shell prompt or in an editor, these are
keywords, builtin class and function names, names following ``class`` and
``def``, strings, and comments. For any text window, these are the cursor (when
present), found text (when possible), and selected text.

Text coloring is done in the background, so uncolorized text is occasionally
visible.  To change the color scheme, use the Configure IDLE dialog
Highlighting tab.  The marking of debugger breakpoint lines in the editor and
text in popups and dialogs is not user-configurable.


Startup and code execution
--------------------------

Upon startup with the ``-s`` option, IDLE will execute the file referenced by
the environment variables :envvar:`IDLESTARTUP` or :envvar:`PYTHONSTARTUP`.
IDLE first checks for ``IDLESTARTUP``; if ``IDLESTARTUP`` is present the file
referenced is run.  If ``IDLESTARTUP`` is not present, IDLE checks for
``PYTHONSTARTUP``.  Files referenced by these environment variables are
convenient places to store functions that are used frequently from the IDLE
shell, or for executing import statements to import common modules.

In addition, ``Tk`` also loads a startup file if it is present.  Note that the
Tk file is loaded unconditionally.  This additional file is ``.Idle.py`` and is
looked for in the user's home directory.  Statements in this file will be
executed in the Tk namespace, so this file is not useful for importing
functions to be used from IDLE's Python shell.


Command line usage
^^^^^^^^^^^^^^^^^^

.. code-block:: none

   idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

   -c command  run command in the shell window
   -d          enable debugger and open shell window
   -e          open editor window
   -h          print help message with legal combinations and exit
   -i          open shell window
   -r file     run file in shell window
   -s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
   -t title    set title of shell window
   -           run stdin in shell (- must be last option before args)

If there are arguments:

* If ``-``, ``-c``, or ``r`` is used, all arguments are placed in
  ``sys.argv[1:...]`` and ``sys.argv[0]`` is set to ``''``, ``'-c'``,
  or ``'-r'``.  No editor window is opened, even if that is the default
  set in the Options dialog.

* Otherwise, arguments are files opened for editing and
  ``sys.argv`` reflects the arguments passed to IDLE itself.


IDLE-console differences
^^^^^^^^^^^^^^^^^^^^^^^^

As much as possible, the result of executing Python code with IDLE is the
same as executing the same code in a console window.  However, the different
interface and operation occasionally affect visible results.  For instance,
``sys.modules`` starts with more entries.

IDLE also replaces ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` with
objects that get input from and send output to the Shell window.
When this window has the focus, it controls the keyboard and screen.
This is normally transparent, but functions that directly access the keyboard
and screen will not work.  If ``sys`` is reset with ``reload(sys)``,
IDLE's changes are lost and things like ``input``, ``raw_input``, and
``print`` will not work correctly.

With IDLE's Shell, one enters, edits, and recalls complete statements.
Some consoles only work with a single physical line at a time.  IDLE uses
``exec`` to run each statement.  As a result, ``'__builtins__'`` is always
defined for each statement.

Running without a subprocess
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, IDLE executes user code in a separate subprocess via a socket,
which uses the internal loopback interface.  This connection is not
externally visible and no data is sent to or received from the Internet.
If firewall software complains anyway, you can ignore it.

If the attempt to make the socket connection fails, Idle will notify you.
Such failures are sometimes transient, but if persistent, the problem
may be either a firewall blocking the connection or misconfiguration of
a particular system.  Until the problem is fixed, one can run Idle with
the -n command line switch.

If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.  This can be useful if Python cannot create
the subprocess or the RPC socket interface on your platform.  However,
in this mode user code is not isolated from IDLE itself.  Also, the
environment is not restarted when Run/Run Module (F5) is selected.  If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g. from foo import baz) if the changes
are to take effect.  For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.

.. deprecated:: 3.4


Help and preferences
--------------------

Additional help sources
^^^^^^^^^^^^^^^^^^^^^^^

IDLE includes a help menu entry called "Python Docs" that will open the
extensive sources of help, including tutorials, available at docs.python.org.
Selected URLs can be added or removed from the help menu at any time using the
Configure IDLE dialog. See the IDLE help option in the help menu of IDLE for
more information.


Setting preferences
^^^^^^^^^^^^^^^^^^^

The font preferences, highlighting, keys, and general preferences can be
changed via Configure IDLE on the Option menu.  Keys can be user defined;
IDLE ships with four built-in key sets. In addition, a user can create a
custom key set in the Configure IDLE dialog under the keys tab.


Extensions
^^^^^^^^^^

IDLE contains an extension facility.  Preferences for extensions can be
changed with Configure Extensions. See the beginning of config-extensions.def
in the idlelib directory for further information.  The default extensions
are currently:

* FormatParagraph

* AutoExpand

* ZoomHeight

* ScriptBinding

* CallTips

* ParenMatch

* AutoComplete

* CodeContext

* RstripExtension
PK	%�\ȴ���%html/_sources/library/imageop.rst.txtnu�[���
:mod:`imageop` --- Manipulate raw image data
============================================

.. module:: imageop
   :synopsis: Manipulate raw image data.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`imageop` module has been removed in Python 3.

The :mod:`imageop` module contains some useful operations on images. It operates
on images consisting of 8 or 32 bit pixels stored in Python strings.  This is
the same format as used by :func:`gl.lrectwrite` and the :mod:`imgfile` module.

The module defines the following variables and functions:


.. exception:: error

   This exception is raised on all errors, such as unknown number of bits per
   pixel, etc.


.. function:: crop(image, psize, width, height, x0, y0, x1, y1)

   Return the selected part of *image*, which should be *width* by *height* in size
   and consist of pixels of *psize* bytes. *x0*, *y0*, *x1* and *y1* are like the
   :func:`gl.lrectread` parameters, i.e. the boundary is included in the new image.
   The new boundaries need not be inside the picture.  Pixels that fall outside the
   old image will have their value set to zero.  If *x0* is bigger than *x1* the
   new image is mirrored.  The same holds for the y coordinates.


.. function:: scale(image, psize, width, height, newwidth, newheight)

   Return *image* scaled to size *newwidth* by *newheight*. No interpolation is
   done, scaling is done by simple-minded pixel duplication or removal.  Therefore,
   computer-generated images or dithered images will not look nice after scaling.


.. function:: tovideo(image, psize, width, height)

   Run a vertical low-pass filter over an image.  It does so by computing each
   destination pixel as the average of two vertically-aligned source pixels.  The
   main use of this routine is to forestall excessive flicker if the image is
   displayed on a video device that uses interlacing, hence the name.


.. function:: grey2mono(image, width, height, threshold)

   Convert an 8-bit deep greyscale image to a 1-bit deep image by thresholding all
   the pixels.  The resulting image is tightly packed and is probably only useful
   as an argument to :func:`mono2grey`.


.. function:: dither2mono(image, width, height)

   Convert an 8-bit greyscale image to a 1-bit monochrome image using a
   (simple-minded) dithering algorithm.


.. function:: mono2grey(image, width, height, p0, p1)

   Convert a 1-bit monochrome image to an 8 bit greyscale or color image. All
   pixels that are zero-valued on input get value *p0* on output and all one-value
   input pixels get value *p1* on output.  To convert a monochrome black-and-white
   image to greyscale pass the values ``0`` and ``255`` respectively.


.. function:: grey2grey4(image, width, height)

   Convert an 8-bit greyscale image to a 4-bit greyscale image without dithering.


.. function:: grey2grey2(image, width, height)

   Convert an 8-bit greyscale image to a 2-bit greyscale image without dithering.


.. function:: dither2grey2(image, width, height)

   Convert an 8-bit greyscale image to a 2-bit greyscale image with dithering.  As
   for :func:`dither2mono`, the dithering algorithm is currently very simple.


.. function:: grey42grey(image, width, height)

   Convert a 4-bit greyscale image to an 8-bit greyscale image.


.. function:: grey22grey(image, width, height)

   Convert a 2-bit greyscale image to an 8-bit greyscale image.


.. data:: backward_compatible

   If set to 0, the functions in this module use a non-backward compatible way
   of representing multi-byte pixels on little-endian systems.  The SGI for
   which this module was originally written is a big-endian system, so setting
   this variable will have no effect. However, the code wasn't originally
   intended to run on anything else, so it made assumptions about byte order
   which are not universal.  Setting this variable to 0 will cause the byte
   order to be reversed on little-endian systems, so that it then is the same as
   on big-endian systems.

PK	%�\� �!ECEC%html/_sources/library/imaplib.rst.txtnu�[���:mod:`imaplib` --- IMAP4 protocol client
========================================

.. module:: imaplib
   :synopsis: IMAP4 protocol client (requires sockets).
.. moduleauthor:: Piers Lauder <piers@communitysolutions.com.au>
.. sectionauthor:: Piers Lauder <piers@communitysolutions.com.au>
.. revised by ESR, January 2000
.. changes for IMAP4_SSL by Tino Lange <Tino.Lange@isg.de>, March 2002
.. changes for IMAP4_stream by Piers Lauder <piers@communitysolutions.com.au>,
   November 2002


.. index::
   pair: IMAP4; protocol
   pair: IMAP4_SSL; protocol
   pair: IMAP4_stream; protocol

**Source code:** :source:`Lib/imaplib.py`

--------------

This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
:class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
implement a large subset of the IMAP4rev1 client protocol as defined in
:rfc:`2060`. It is backward compatible with IMAP4 (:rfc:`1730`) servers, but
note that the ``STATUS`` command is not supported in IMAP4.

Three classes are provided by the :mod:`imaplib` module, :class:`IMAP4` is the
base class:


.. class:: IMAP4([host[, port]])

   This class implements the actual IMAP4 protocol.  The connection is created and
   protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
   initialized. If *host* is not specified, ``''`` (the local host) is used. If
   *port* is omitted, the standard IMAP4 port (143) is used.

Three exceptions are defined as attributes of the :class:`IMAP4` class:


.. exception:: IMAP4.error

   Exception raised on any errors.  The reason for the exception is passed to the
   constructor as a string.


.. exception:: IMAP4.abort

   IMAP4 server errors cause this exception to be raised.  This is a sub-class of
   :exc:`IMAP4.error`.  Note that closing the instance and instantiating a new one
   will usually allow recovery from this exception.


.. exception:: IMAP4.readonly

   This exception is raised when a writable mailbox has its status changed by the
   server.  This is a sub-class of :exc:`IMAP4.error`.  Some other client now has
   write permission, and the mailbox will need to be re-opened to re-obtain write
   permission.

There's also a subclass for secure connections:


.. class:: IMAP4_SSL([host[, port[, keyfile[, certfile]]]])

   This is a subclass derived from :class:`IMAP4` that connects over an SSL
   encrypted socket (to use this class you need a socket module that was compiled
   with SSL support).  If *host* is not specified, ``''`` (the local host) is used.
   If *port* is omitted, the standard IMAP4-over-SSL port (993) is used.  *keyfile*
   and *certfile* are also optional - they can contain a PEM formatted private key
   and certificate chain file for the SSL connection.

The second subclass allows for connections created by a child process:


.. class:: IMAP4_stream(command)

   This is a subclass derived from :class:`IMAP4` that connects to the
   ``stdin/stdout`` file descriptors created by passing *command* to
   ``os.popen2()``.

   .. versionadded:: 2.3

The following utility functions are defined:


.. function:: Internaldate2tuple(datestr)

   Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
   time.  The return value is a :class:`time.struct_time` instance or
   ``None`` if the string has wrong format.

.. function:: Int2AP(num)

   Converts an integer into a string representation using characters from the set
   [``A`` .. ``P``].


.. function:: ParseFlags(flagstr)

   Converts an IMAP4 ``FLAGS`` response to a tuple of individual flags.


.. function:: Time2Internaldate(date_time)

   Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.  The
   return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
   +HHMM"`` (including double-quotes).  The *date_time* argument can be a
   number (int or float) representing seconds since epoch (as returned
   by :func:`time.time`), a 9-tuple representing local time (as returned by
   :func:`time.localtime`), or a double-quoted string.  In the last case, it
   is assumed to already be in the correct format.

Note that IMAP4 message numbers change as the mailbox changes; in particular,
after an ``EXPUNGE`` command performs deletions the remaining messages are
renumbered. So it is highly advisable to use UIDs instead, with the UID command.

At the end of the module, there is a test section that contains a more extensive
example of usage.


.. seealso::

   Documents describing the protocol, and sources and binaries  for servers
   implementing it, can all be found at the University of Washington's *IMAP
   Information Center* (https://www.washington.edu/imap/).


.. _imap4-objects:

IMAP4 Objects
-------------

All IMAP4rev1 commands are represented by methods of the same name, either
upper-case or lower-case.

All arguments to commands are converted to strings, except for ``AUTHENTICATE``,
and the last argument to ``APPEND`` which is passed as an IMAP4 literal.  If
necessary (the string contains IMAP4 protocol-sensitive characters and isn't
enclosed with either parentheses or double quotes) each string is quoted.
However, the *password* argument to the ``LOGIN`` command is always quoted. If
you want to avoid having an argument string quoted (eg: the *flags* argument to
``STORE``) then enclose the string in parentheses (eg: ``r'(\Deleted)'``).

Each command returns a tuple: ``(type, [data, ...])`` where *type* is usually
``'OK'`` or ``'NO'``, and *data* is either the text from the command response,
or mandated results from the command. Each *data* is either a string, or a
tuple. If a tuple, then the first part is the header of the response, and the
second part contains the data (ie: 'literal' value).

The *message_set* options to commands below is a string specifying one or more
messages to be acted upon.  It may be a simple message number (``'1'``), a range
of message numbers (``'2:4'``), or a group of non-contiguous ranges separated by
commas (``'1:3,6:9'``).  A range can contain an asterisk to indicate an infinite
upper bound (``'3:*'``).

An :class:`IMAP4` instance has the following methods:


.. method:: IMAP4.append(mailbox, flags, date_time, message)

   Append *message* to named mailbox.


.. method:: IMAP4.authenticate(mechanism, authobject)

   Authenticate command --- requires response processing.

   *mechanism* specifies which authentication mechanism is to be used - it should
   appear in the instance variable ``capabilities`` in the form ``AUTH=mechanism``.

   *authobject* must be a callable object::

      data = authobject(response)

   It will be called to process server continuation responses. It should return
   ``data`` that will be encoded and sent to server. It should return ``None`` if
   the client abort response ``*`` should be sent instead.


.. method:: IMAP4.check()

   Checkpoint mailbox on server.


.. method:: IMAP4.close()

   Close currently selected mailbox. Deleted messages are removed from writable
   mailbox. This is the recommended command before ``LOGOUT``.


.. method:: IMAP4.copy(message_set, new_mailbox)

   Copy *message_set* messages onto end of *new_mailbox*.


.. method:: IMAP4.create(mailbox)

   Create new mailbox named *mailbox*.


.. method:: IMAP4.delete(mailbox)

   Delete old mailbox named *mailbox*.


.. method:: IMAP4.deleteacl(mailbox, who)

   Delete the ACLs (remove any rights) set for who on mailbox.

   .. versionadded:: 2.4


.. method:: IMAP4.expunge()

   Permanently remove deleted items from selected mailbox. Generates an ``EXPUNGE``
   response for each deleted message. Returned data contains a list of ``EXPUNGE``
   message numbers in order received.


.. method:: IMAP4.fetch(message_set, message_parts)

   Fetch (parts of) messages.  *message_parts* should be a string of message part
   names enclosed within parentheses, eg: ``"(UID BODY[TEXT])"``.  Returned data
   are tuples of message part envelope and data.


.. method:: IMAP4.getacl(mailbox)

   Get the ``ACL``\ s for *mailbox*. The method is non-standard, but is supported
   by the ``Cyrus`` server.


.. method:: IMAP4.getannotation(mailbox, entry, attribute)

   Retrieve the specified ``ANNOTATION``\ s for *mailbox*. The method is
   non-standard, but is supported by the ``Cyrus`` server.

   .. versionadded:: 2.5


.. method:: IMAP4.getquota(root)

   Get the ``quota`` *root*'s resource usage and limits. This method is part of the
   IMAP4 QUOTA extension defined in rfc2087.

   .. versionadded:: 2.3


.. method:: IMAP4.getquotaroot(mailbox)

   Get the list of ``quota`` ``roots`` for the named *mailbox*. This method is part
   of the IMAP4 QUOTA extension defined in rfc2087.

   .. versionadded:: 2.3


.. method:: IMAP4.list([directory[, pattern]])

   List mailbox names in *directory* matching *pattern*.  *directory* defaults to
   the top-level mail folder, and *pattern* defaults to match anything.  Returned
   data contains a list of ``LIST`` responses.


.. method:: IMAP4.login(user, password)

   Identify the client using a plaintext password. The *password* will be quoted.


.. method:: IMAP4.login_cram_md5(user, password)

   Force use of ``CRAM-MD5`` authentication when identifying the client to protect
   the password.  Will only work if the server ``CAPABILITY`` response includes the
   phrase ``AUTH=CRAM-MD5``.

   .. versionadded:: 2.3


.. method:: IMAP4.logout()

   Shutdown connection to server. Returns server ``BYE`` response.


.. method:: IMAP4.lsub([directory[, pattern]])

   List subscribed mailbox names in directory matching pattern. *directory*
   defaults to the top level directory and *pattern* defaults to match any mailbox.
   Returned data are tuples of message part envelope and data.


.. method:: IMAP4.myrights(mailbox)

   Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).

   .. versionadded:: 2.4


.. method:: IMAP4.namespace()

   Returns IMAP namespaces as defined in RFC2342.

   .. versionadded:: 2.3


.. method:: IMAP4.noop()

   Send ``NOOP`` to server.


.. method:: IMAP4.open(host, port)

   Opens socket to *port* at *host*.  This method is implicitly called by
   the :class:`IMAP4` constructor.  The connection objects established by this
   method will be used in the :meth:`IMAP4.read`, :meth:`IMAP4.readline`,
   :meth:`IMAP4.send`, and :meth:`IMAP4.shutdown` methods.  You may override
   this method.


.. method:: IMAP4.partial(message_num, message_part, start, length)

   Fetch truncated part of a message. Returned data is a tuple of message part
   envelope and data.


.. method:: IMAP4.proxyauth(user)

   Assume authentication as *user*. Allows an authorised administrator to proxy
   into any user's mailbox.

   .. versionadded:: 2.3


.. method:: IMAP4.read(size)

   Reads *size* bytes from the remote server. You may override this method.


.. method:: IMAP4.readline()

   Reads one line from the remote server. You may override this method.


.. method:: IMAP4.recent()

   Prompt server for an update. Returned data is ``None`` if no new messages, else
   value of ``RECENT`` response.


.. method:: IMAP4.rename(oldmailbox, newmailbox)

   Rename mailbox named *oldmailbox* to *newmailbox*.


.. method:: IMAP4.response(code)

   Return data for response *code* if received, or ``None``. Returns the given
   code, instead of the usual type.


.. method:: IMAP4.search(charset, criterion[, ...])

   Search mailbox for matching messages.  *charset* may be ``None``, in which case
   no ``CHARSET`` will be specified in the request to the server.  The IMAP
   protocol requires that at least one criterion be specified; an exception will be
   raised when the server returns an error.

   Example::

      # M is a connected IMAP4 instance...
      typ, msgnums = M.search(None, 'FROM', '"LDJ"')

      # or:
      typ, msgnums = M.search(None, '(FROM "LDJ")')


.. method:: IMAP4.select([mailbox[, readonly]])

   Select a mailbox. Returned data is the count of messages in *mailbox*
   (``EXISTS`` response).  The default *mailbox* is ``'INBOX'``.  If the *readonly*
   flag is set, modifications to the mailbox are not allowed.


.. method:: IMAP4.send(data)

   Sends ``data`` to the remote server. You may override this method.


.. method:: IMAP4.setacl(mailbox, who, what)

   Set an ``ACL`` for *mailbox*. The method is non-standard, but is supported by
   the ``Cyrus`` server.


.. method:: IMAP4.setannotation(mailbox, entry, attribute[, ...])

   Set ``ANNOTATION``\ s for *mailbox*. The method is non-standard, but is
   supported by the ``Cyrus`` server.

   .. versionadded:: 2.5


.. method:: IMAP4.setquota(root, limits)

   Set the ``quota`` *root*'s resource *limits*. This method is part of the IMAP4
   QUOTA extension defined in rfc2087.

   .. versionadded:: 2.3


.. method:: IMAP4.shutdown()

   Close connection established in ``open``.  This method is implicitly
   called by :meth:`IMAP4.logout`.  You may override this method.


.. method:: IMAP4.socket()

   Returns socket instance used to connect to server.


.. method:: IMAP4.sort(sort_criteria, charset, search_criterion[, ...])

   The ``sort`` command is a variant of ``search`` with sorting semantics for the
   results.  Returned data contains a space separated list of matching message
   numbers.

   Sort has two arguments before the *search_criterion* argument(s); a
   parenthesized list of *sort_criteria*, and the searching *charset*.  Note that
   unlike ``search``, the searching *charset* argument is mandatory.  There is also
   a ``uid sort`` command which corresponds to ``sort`` the way that ``uid search``
   corresponds to ``search``.  The ``sort`` command first searches the mailbox for
   messages that match the given searching criteria using the charset argument for
   the interpretation of strings in the searching criteria.  It then returns the
   numbers of matching messages.

   This is an ``IMAP4rev1`` extension command.


.. method:: IMAP4.status(mailbox, names)

   Request named status conditions for *mailbox*.


.. method:: IMAP4.store(message_set, command, flag_list)

   Alters flag dispositions for messages in mailbox.  *command* is specified by
   section 6.4.6 of :rfc:`2060` as being one of "FLAGS", "+FLAGS", or "-FLAGS",
   optionally with a suffix of ".SILENT".

   For example, to set the delete flag on all messages::

      typ, data = M.search(None, 'ALL')
      for num in data[0].split():
         M.store(num, '+FLAGS', '\\Deleted')
      M.expunge()


.. method:: IMAP4.subscribe(mailbox)

   Subscribe to new mailbox.


.. method:: IMAP4.thread(threading_algorithm, charset, search_criterion[, ...])

   The ``thread`` command is a variant of ``search`` with threading semantics for
   the results.  Returned data contains a space separated list of thread members.

   Thread members consist of zero or more messages numbers, delimited by spaces,
   indicating successive parent and child.

   Thread has two arguments before the *search_criterion* argument(s); a
   *threading_algorithm*, and the searching *charset*.  Note that unlike
   ``search``, the searching *charset* argument is mandatory.  There is also a
   ``uid thread`` command which corresponds to ``thread`` the way that ``uid
   search`` corresponds to ``search``.  The ``thread`` command first searches the
   mailbox for messages that match the given searching criteria using the charset
   argument for the interpretation of strings in the searching criteria. It then
   returns the matching messages threaded according to the specified threading
   algorithm.

   This is an ``IMAP4rev1`` extension command.

   .. versionadded:: 2.4


.. method:: IMAP4.uid(command, arg[, ...])

   Execute command args with messages identified by UID, rather than message
   number.  Returns response appropriate to command.  At least one argument must be
   supplied; if none are provided, the server will return an error and an exception
   will be raised.


.. method:: IMAP4.unsubscribe(mailbox)

   Unsubscribe from old mailbox.


.. method:: IMAP4.xatom(name[, arg[, ...]])

   Allow simple extension commands notified by server in ``CAPABILITY`` response.

Instances of :class:`IMAP4_SSL` have just one additional method:


.. method:: IMAP4_SSL.ssl()

   Returns SSLObject instance used for the secure connection with the server.

The following attributes are defined on instances of :class:`IMAP4`:


.. attribute:: IMAP4.PROTOCOL_VERSION

   The most recent supported protocol in the ``CAPABILITY`` response from the
   server.


.. attribute:: IMAP4.debug

   Integer value to control debugging output.  The initialize value is taken from
   the module variable ``Debug``.  Values greater than three trace each command.


.. _imap4-example:

IMAP4 Example
-------------

Here is a minimal example (without error checking) that opens a mailbox and
retrieves and prints all messages::

   import getpass, imaplib

   M = imaplib.IMAP4()
   M.login(getpass.getuser(), getpass.getpass())
   M.select()
   typ, data = M.search(None, 'ALL')
   for num in data[0].split():
       typ, data = M.fetch(num, '(RFC822)')
       print 'Message %s\n%s\n' % (num, data[0][1])
   M.close()
   M.logout()

PK	%�\����
�
%html/_sources/library/imgfile.rst.txtnu�[���
:mod:`imgfile` --- Support for SGI imglib files
===============================================

.. module:: imgfile
   :platform: IRIX
   :synopsis: Support for SGI imglib files.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`imgfile` module has been removed in Python 3.



The :mod:`imgfile` module allows Python programs to access SGI imglib image
files (also known as :file:`.rgb` files).  The module is far from complete, but
is provided anyway since the functionality that there is enough in some cases.
Currently, colormap files are not supported.

The module defines the following variables and functions:


.. exception:: error

   This exception is raised on all errors, such as unsupported file type, etc.


.. function:: getsizes(file)

   This function returns a tuple ``(x, y, z)`` where *x* and *y* are the size of
   the image in pixels and *z* is the number of bytes per pixel. Only 3 byte RGB
   pixels and 1 byte greyscale pixels are currently supported.


.. function:: read(file)

   This function reads and decodes the image on the specified file, and returns it
   as a Python string. The string has either 1 byte greyscale pixels or 4 byte RGBA
   pixels. The bottom left pixel is the first in the string. This format is
   suitable to pass to :func:`gl.lrectwrite`, for instance.


.. function:: readscaled(file, x, y, filter[, blur])

   This function is identical to read but it returns an image that is scaled to the
   given *x* and *y* sizes. If the *filter* and *blur* parameters are omitted
   scaling is done by simply dropping or duplicating pixels, so the result will be
   less than perfect, especially for computer-generated images.

   Alternatively, you can specify a filter to use to smooth the image after
   scaling. The filter forms supported are ``'impulse'``, ``'box'``,
   ``'triangle'``, ``'quadratic'`` and ``'gaussian'``. If a filter is specified
   *blur* is an optional parameter specifying the blurriness of the filter. It
   defaults to ``1.0``.

   :func:`readscaled` makes no attempt to keep the aspect ratio correct, so that is
   the users' responsibility.


.. function:: ttob(flag)

   This function sets a global flag which defines whether the scan lines of the
   image are read or written from bottom to top (flag is zero, compatible with SGI
   GL) or from top to bottom(flag is one, compatible with X).  The default is zero.


.. function:: write(file, data, x, y, z)

   This function writes the RGB or greyscale data in *data* to image file *file*.
   *x* and *y* give the size of the image, *z* is 1 for 1 byte greyscale images or
   3 for RGB images (which are stored as 4 byte values of which only the lower
   three bytes are used). These are the formats returned by :func:`gl.lrectread`.

PK	%�\z��^K
K
$html/_sources/library/imghdr.rst.txtnu�[���:mod:`imghdr` --- Determine the type of an image
================================================

.. module:: imghdr
   :synopsis: Determine the type of image contained in a file or byte stream.

**Source code:** :source:`Lib/imghdr.py`

--------------

The :mod:`imghdr` module determines the type of image contained in a file or
byte stream.

The :mod:`imghdr` module defines the following function:


.. function:: what(filename[, h])

   Tests the image data contained in the file named by *filename*, and returns a
   string describing the image type.  If optional *h* is provided, the *filename*
   is ignored and *h* is assumed to contain the byte stream to test.

The following image types are recognized, as listed below with the return value
from :func:`what`:

+------------+-----------------------------------+
| Value      | Image format                      |
+============+===================================+
| ``'rgb'``  | SGI ImgLib Files                  |
+------------+-----------------------------------+
| ``'gif'``  | GIF 87a and 89a Files             |
+------------+-----------------------------------+
| ``'pbm'``  | Portable Bitmap Files             |
+------------+-----------------------------------+
| ``'pgm'``  | Portable Graymap Files            |
+------------+-----------------------------------+
| ``'ppm'``  | Portable Pixmap Files             |
+------------+-----------------------------------+
| ``'tiff'`` | TIFF Files                        |
+------------+-----------------------------------+
| ``'rast'`` | Sun Raster Files                  |
+------------+-----------------------------------+
| ``'xbm'``  | X Bitmap Files                    |
+------------+-----------------------------------+
| ``'jpeg'`` | JPEG data in JFIF or Exif formats |
+------------+-----------------------------------+
| ``'bmp'``  | BMP files                         |
+------------+-----------------------------------+
| ``'png'``  | Portable Network Graphics         |
+------------+-----------------------------------+

.. versionadded:: 2.5
   Exif detection.

You can extend the list of file types :mod:`imghdr` can recognize by appending
to this variable:


.. data:: tests

   A list of functions performing the individual tests.  Each function takes two
   arguments: the byte-stream and an open file-like object. When :func:`what` is
   called with a byte-stream, the file-like object will be ``None``.

   The test function should return a string describing the image type if the test
   succeeded, or ``None`` if it failed.

Example::

   >>> import imghdr
   >>> imghdr.what('bass.gif')
   'gif'

PK	%�\B�(�1111!html/_sources/library/imp.rst.txtnu�[���
:mod:`imp` --- Access the :keyword:`import` internals
=====================================================

.. module:: imp
   :synopsis: Access the implementation of the import statement.


.. index:: statement: import

This module provides an interface to the mechanisms used to implement the
:keyword:`import` statement.  It defines the following constants and functions:


.. function:: get_magic()

   .. index:: pair: file; byte-code

   Return the magic string value used to recognize byte-compiled code files
   (:file:`.pyc` files).  (This value may be different for each Python version.)


.. function:: get_suffixes()

   Return a list of 3-element tuples, each describing a particular type of
   module. Each triple has the form ``(suffix, mode, type)``, where *suffix* is
   a string to be appended to the module name to form the filename to search
   for, *mode* is the mode string to pass to the built-in :func:`open` function
   to open the file (this can be ``'r'`` for text files or ``'rb'`` for binary
   files), and *type* is the file type, which has one of the values
   :const:`PY_SOURCE`, :const:`PY_COMPILED`, or :const:`C_EXTENSION`, described
   below.


.. function:: find_module(name[, path])

   Try to find the module *name*.  If *path* is omitted or ``None``, the list of
   directory names given by ``sys.path`` is searched, but first a few special
   places are searched: the function tries to find a built-in module with the
   given name (:const:`C_BUILTIN`), then a frozen module (:const:`PY_FROZEN`),
   and on some systems some other places are looked in as well (on Windows, it
   looks in the registry which may point to a specific file).

   Otherwise, *path* must be a list of directory names; each directory is
   searched for files with any of the suffixes returned by :func:`get_suffixes`
   above.  Invalid names in the list are silently ignored (but all list items
   must be strings).

   If search is successful, the return value is a 3-element tuple ``(file,
   pathname, description)``:

   *file* is an open file object positioned at the beginning, *pathname* is the
   pathname of the file found, and *description* is a 3-element tuple as
   contained in the list returned by :func:`get_suffixes` describing the kind of
   module found.

   If the module does not live in a file, the returned *file* is ``None``,
   *pathname* is the empty string, and the *description* tuple contains empty
   strings for its suffix and mode; the module type is indicated as given in
   parentheses above.  If the search is unsuccessful, :exc:`ImportError` is
   raised.  Other exceptions indicate problems with the arguments or
   environment.

   If the module is a package, *file* is ``None``, *pathname* is the package
   path and the last item in the *description* tuple is :const:`PKG_DIRECTORY`.

   This function does not handle hierarchical module names (names containing
   dots).  In order to find *P.M*, that is, submodule *M* of package *P*, use
   :func:`find_module` and :func:`load_module` to find and load package *P*, and
   then use :func:`find_module` with the *path* argument set to ``P.__path__``.
   When *P* itself has a dotted name, apply this recipe recursively.


.. function:: load_module(name, file, pathname, description)

   .. index:: builtin: reload

   Load a module that was previously found by :func:`find_module` (or by an
   otherwise conducted search yielding compatible results).  This function does
   more than importing the module: if the module was already imported, it is
   equivalent to a :func:`reload`!  The *name* argument indicates the full
   module name (including the package name, if this is a submodule of a
   package).  The *file* argument is an open file, and *pathname* is the
   corresponding file name; these can be ``None`` and ``''``, respectively, when
   the module is a package or not being loaded from a file.  The *description*
   argument is a tuple, as would be returned by :func:`get_suffixes`, describing
   what kind of module must be loaded.

   If the load is successful, the return value is the module object; otherwise,
   an exception (usually :exc:`ImportError`) is raised.

   **Important:** the caller is responsible for closing the *file* argument, if
   it was not ``None``, even when an exception is raised.  This is best done
   using a :keyword:`try` ... :keyword:`finally` statement.


.. function:: new_module(name)

   Return a new empty module object called *name*.  This object is *not* inserted
   in ``sys.modules``.


.. function:: lock_held()

   Return ``True`` if the import lock is currently held, else ``False``. On
   platforms without threads, always return ``False``.

   On platforms with threads, a thread executing an import holds an internal lock
   until the import is complete. This lock blocks other threads from doing an
   import until the original import completes, which in turn prevents other threads
   from seeing incomplete module objects constructed by the original thread while
   in the process of completing its import (and the imports, if any, triggered by
   that).


.. function:: acquire_lock()

   Acquire the interpreter's import lock for the current thread.  This lock should
   be used by import hooks to ensure thread-safety when importing modules.

   Once a thread has acquired the import lock, the same thread may acquire it
   again without blocking; the thread must release it once for each time it has
   acquired it.

   On platforms without threads, this function does nothing.

   .. versionadded:: 2.3


.. function:: release_lock()

   Release the interpreter's import lock. On platforms without threads, this
   function does nothing.

   .. versionadded:: 2.3

The following constants with integer values, defined in this module, are used to
indicate the search result of :func:`find_module`.


.. data:: PY_SOURCE

   The module was found as a source file.


.. data:: PY_COMPILED

   The module was found as a compiled code object file.


.. data:: C_EXTENSION

   The module was found as dynamically loadable shared library.


.. data:: PKG_DIRECTORY

   The module was found as a package directory.


.. data:: C_BUILTIN

   The module was found as a built-in module.


.. data:: PY_FROZEN

   The module was found as a frozen module (see :func:`init_frozen`).

The following constant and functions are obsolete; their functionality is
available through :func:`find_module` or :func:`load_module`. They are kept
around for backward compatibility:


.. data:: SEARCH_ERROR

   Unused.


.. function:: init_builtin(name)

   Initialize the built-in module called *name* and return its module object along
   with storing it in ``sys.modules``.  If the module was already initialized, it
   will be initialized *again*.  Re-initialization involves the copying of the
   built-in module's ``__dict__`` from the cached module over the module's entry in
   ``sys.modules``.  If there is no built-in module called *name*, ``None`` is
   returned.


.. function:: init_frozen(name)

   Initialize the frozen module called *name* and return its module object.  If
   the module was already initialized, it will be initialized *again*.  If there
   is no frozen module called *name*, ``None`` is returned.  (Frozen modules are
   modules written in Python whose compiled byte-code object is incorporated
   into a custom-built Python interpreter by Python's :program:`freeze`
   utility. See :file:`Tools/freeze/` for now.)


.. function:: is_builtin(name)

   Return ``1`` if there is a built-in module called *name* which can be
   initialized again.  Return ``-1`` if there is a built-in module called *name*
   which cannot be initialized again (see :func:`init_builtin`).  Return ``0`` if
   there is no built-in module called *name*.


.. function:: is_frozen(name)

   Return ``True`` if there is a frozen module (see :func:`init_frozen`) called
   *name*, or ``False`` if there is no such module.


.. function:: load_compiled(name, pathname, [file])

   .. index:: pair: file; byte-code

   Load and initialize a module implemented as a byte-compiled code file and return
   its module object.  If the module was already initialized, it will be
   initialized *again*.  The *name* argument is used to create or access a module
   object.  The *pathname* argument points to the byte-compiled code file.  The
   *file* argument is the byte-compiled code file, open for reading in binary mode,
   from the beginning. It must currently be a real file object, not a user-defined
   class emulating a file.


.. function:: load_dynamic(name, pathname[, file])

   Load and initialize a module implemented as a dynamically loadable shared
   library and return its module object.  If the module was already initialized, it
   will be initialized *again*. Re-initialization involves copying the ``__dict__``
   attribute of the cached instance of the module over the value used in the module
   cached in ``sys.modules``.  The *pathname* argument must point to the shared
   library.  The *name* argument is used to construct the name of the
   initialization function: an external C function called ``initname()`` in the
   shared library is called.  The optional *file* argument is ignored.  (Note:
   using shared libraries is highly system dependent, and not all systems support
   it.)

   .. impl-detail::

      The import internals identify extension modules by filename, so doing
      ``foo = load_dynamic("foo", "mod.so")`` and
      ``bar = load_dynamic("bar", "mod.so")`` will result in both foo and bar
      referring to the same module, regardless of whether or not
      ``mod.so`` exports an ``initbar`` function. On systems which
      support them, symlinks can be used to import multiple modules from
      the same shared library, as each reference to the module will use
      a different file name.


.. function:: load_source(name, pathname[, file])

   Load and initialize a module implemented as a Python source file and return its
   module object.  If the module was already initialized, it will be initialized
   *again*.  The *name* argument is used to create or access a module object.  The
   *pathname* argument points to the source file.  The *file* argument is the
   source file, open for reading as text, from the beginning. It must currently be
   a real file object, not a user-defined class emulating a file.  Note that if a
   properly matching byte-compiled file (with suffix :file:`.pyc` or :file:`.pyo`)
   exists, it will be used instead of parsing the given source file.


.. class:: NullImporter(path_string)

   The :class:`NullImporter` type is a :pep:`302` import hook that handles
   non-directory path strings by failing to find any modules.  Calling this type
   with an existing directory or empty string raises :exc:`ImportError`.
   Otherwise, a :class:`NullImporter` instance is returned.

   Python adds instances of this type to ``sys.path_importer_cache`` for any path
   entries that are not directories and are not handled by any other path hooks on
   ``sys.path_hooks``.  Instances have only one method:


   .. method:: NullImporter.find_module(fullname [, path])

      This method always returns ``None``, indicating that the requested module could
      not be found.

   .. versionadded:: 2.5


.. _examples-imp:

Examples
--------

The following function emulates what was the standard import statement up to
Python 1.4 (no hierarchical module names).  (This *implementation* wouldn't work
in that version, since :func:`find_module` has been extended and
:func:`load_module` has been added in 1.4.) ::

   import imp
   import sys

   def __import__(name, globals=None, locals=None, fromlist=None):
       # Fast path: see if the module has already been imported.
       try:
           return sys.modules[name]
       except KeyError:
           pass

       # If any of the following calls raises an exception,
       # there's a problem we can't handle -- let the caller handle it.

       fp, pathname, description = imp.find_module(name)

       try:
           return imp.load_module(name, fp, pathname, description)
       finally:
           # Since we may exit via an exception, close fp explicitly.
           if fp:
               fp.close()

.. index::
   builtin: reload
   module: knee

A more complete example that implements hierarchical module names and includes a
:func:`reload` function can be found in the module :mod:`knee`.  The :mod:`knee`
module can be found in :file:`Demo/imputil/` in the Python source distribution.

PK	%�\rs�ff'html/_sources/library/importlib.rst.txtnu�[���:mod:`importlib` --- Convenience wrappers for :func:`__import__`
================================================================

.. module:: importlib
   :synopsis: Convenience wrappers for __import__

.. moduleauthor:: Brett Cannon <brett@python.org>
.. sectionauthor:: Brett Cannon <brett@python.org>

.. versionadded:: 2.7

This module is a minor subset of what is available in the more full-featured
package of the same name from Python 3.1 that provides a complete
implementation of :keyword:`import`. What is here has been provided to
help ease in transitioning from 2.7 to 3.1.


.. function:: import_module(name, package=None)

    Import a module. The *name* argument specifies what module to
    import in absolute or relative terms
    (e.g. either ``pkg.mod`` or ``..mod``). If the name is
    specified in relative terms, then the *package* argument must be
    specified to the package which is to act as the anchor for resolving the
    package name (e.g. ``import_module('..mod', 'pkg.subpkg')`` will import
    ``pkg.mod``).  The specified module will be inserted into
    :data:`sys.modules` and returned.
PK	%�\&v�oo%html/_sources/library/imputil.rst.txtnu�[���
:mod:`imputil` --- Import utilities
=====================================================

.. module:: imputil
   :synopsis: Manage and augment the import process.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`imputil` module has been removed in Python 3.


.. index:: statement: import

This module provides a very handy and useful mechanism for custom
:keyword:`import` hooks. Compared to the older :mod:`ihooks` module,
:mod:`imputil` takes a dramatically simpler and more straight-forward
approach to custom :keyword:`import` functions.


.. class:: ImportManager([fs_imp])

   Manage the import process.

   .. method:: ImportManager.install([namespace])

      Install this ImportManager into the specified namespace.

   .. method:: ImportManager.uninstall()

      Restore the previous import mechanism.

   .. method:: ImportManager.add_suffix(suffix, importFunc)

      Undocumented.


.. class:: Importer()

   Base class for replacing standard import functions.

   .. method:: Importer.import_top(name)

      Import a top-level module.

   .. method:: Importer.get_code(parent, modname, fqname)

      Find and retrieve the code for the given module.

      *parent* specifies a parent module to define a context for importing.
      It may be ``None``, indicating no particular context for the search.

      *modname* specifies a single module (not dotted) within the parent.

      *fqname* specifies the fully-qualified module name. This is a
      (potentially) dotted name from the "root" of the module namespace
      down to the modname.

      If there is no parent, then modname==fqname.

      This method should return ``None``, or a 3-tuple.

        * If the module was not found, then ``None`` should be returned.

        * The first item of the 2- or 3-tuple should be the integer 0 or 1,
          specifying whether the module that was found is a package or not.

        * The second item is the code object for the module (it will be
          executed within the new module's namespace). This item can also
          be a fully-loaded module object (e.g. loaded from a shared lib).

        * The third item is a dictionary of name/value pairs that will be
          inserted into new module before the code object is executed. This
          is provided in case the module's code expects certain values (such
          as where the module was found). When the second item is a module
          object, then these names/values will be inserted *after* the module
          has been loaded/initialized.


.. class:: BuiltinImporter()

   Emulate the import mechanism for built-in and frozen modules.  This is a
   sub-class of the :class:`Importer` class.

   .. method:: BuiltinImporter.get_code(parent, modname, fqname)

      Undocumented.

.. function:: py_suffix_importer(filename, finfo, fqname)

   Undocumented.

.. class:: DynLoadSuffixImporter([desc])

   Undocumented.

   .. method:: DynLoadSuffixImporter.import_file(filename, finfo, fqname)

      Undocumented.

.. _examples-imputil:

Examples
--------

This is a re-implementation of hierarchical module import.

This code is intended to be read, not executed.  However, it does work
-- all you need to do to enable it is "import knee".

(The name is a pun on the clunkier predecessor of this module, "ni".)

::

   import sys, imp, __builtin__

   # Replacement for __import__()
   def import_hook(name, globals=None, locals=None, fromlist=None):
       parent = determine_parent(globals)
       q, tail = find_head_package(parent, name)
       m = load_tail(q, tail)
       if not fromlist:
           return q
       if hasattr(m, "__path__"):
           ensure_fromlist(m, fromlist)
       return m

   def determine_parent(globals):
       if not globals or  not globals.has_key("__name__"):
           return None
       pname = globals['__name__']
       if globals.has_key("__path__"):
           parent = sys.modules[pname]
           assert globals is parent.__dict__
           return parent
       if '.' in pname:
           i = pname.rfind('.')
           pname = pname[:i]
           parent = sys.modules[pname]
           assert parent.__name__ == pname
           return parent
       return None

   def find_head_package(parent, name):
       if '.' in name:
           i = name.find('.')
           head = name[:i]
           tail = name[i+1:]
       else:
           head = name
           tail = ""
       if parent:
           qname = "%s.%s" % (parent.__name__, head)
       else:
           qname = head
       q = import_module(head, qname, parent)
       if q: return q, tail
       if parent:
           qname = head
           parent = None
           q = import_module(head, qname, parent)
           if q: return q, tail
       raise ImportError("No module named " + qname)

   def load_tail(q, tail):
       m = q
       while tail:
           i = tail.find('.')
           if i < 0: i = len(tail)
           head, tail = tail[:i], tail[i+1:]
           mname = "%s.%s" % (m.__name__, head)
           m = import_module(head, mname, m)
           if not m:
               raise ImportError("No module named " + mname)
       return m

   def ensure_fromlist(m, fromlist, recursive=0):
       for sub in fromlist:
           if sub == "*":
               if not recursive:
                   try:
                       all = m.__all__
                   except AttributeError:
                       pass
                   else:
                       ensure_fromlist(m, all, 1)
               continue
           if sub != "*" and not hasattr(m, sub):
               subname = "%s.%s" % (m.__name__, sub)
               submod = import_module(sub, subname, m)
               if not submod:
                   raise ImportError("No module named " + subname)

   def import_module(partname, fqname, parent):
       try:
           return sys.modules[fqname]
       except KeyError:
           pass
       try:
           fp, pathname, stuff = imp.find_module(partname,
                                                 parent and parent.__path__)
       except ImportError:
           return None
       try:
           m = imp.load_module(fqname, fp, pathname, stuff)
       finally:
           if fp: fp.close()
       if parent:
           setattr(parent, partname, m)
       return m


   # Replacement for reload()
   def reload_hook(module):
       name = module.__name__
       if '.' not in name:
           return import_module(name, name, None)
       i = name.rfind('.')
       pname = name[:i]
       parent = sys.modules[pname]
       return import_module(name[i+1:], name, parent)


   # Save the original hooks
   original_import = __builtin__.__import__
   original_reload = __builtin__.reload

   # Now install our hooks
   __builtin__.__import__ = import_hook
   __builtin__.reload = reload_hook

.. index::
   module: knee

Also see the :mod:`importers` module (which can be found
in :file:`Demo/imputil/` in the Python source distribution) for additional
examples.

PK	%�\g5�s��#html/_sources/library/index.rst.txtnu�[���.. _library-index:

###############################
  The Python Standard Library
###############################

While :ref:`reference-index` describes the exact syntax and
semantics of the Python language, this library reference manual
describes the standard library that is distributed with Python. It also
describes some of the optional components that are commonly included
in Python distributions.

Python's standard library is very extensive, offering a wide range of
facilities as indicated by the long table of contents listed below. The
library contains built-in modules (written in C) that provide access to
system functionality such as file I/O that would otherwise be
inaccessible to Python programmers, as well as modules written in Python
that provide standardized solutions for many problems that occur in
everyday programming. Some of these modules are explicitly designed to
encourage and enhance the portability of Python programs by abstracting
away platform-specifics into platform-neutral APIs.

The Python installers for the Windows platform usually include
the entire standard library and often also include many additional
components. For Unix-like operating systems Python is normally provided
as a collection of packages, so it may be necessary to use the packaging
tools provided with the operating system to obtain some or all of the
optional components.

In addition to the standard library, there is a growing collection of
several thousand components (from individual programs and modules to
packages and entire application development frameworks), available from
the `Python Package Index <https://pypi.org>`_.


.. toctree::
   :maxdepth: 2
   :numbered:

   intro.rst
   functions.rst
   constants.rst
   stdtypes.rst
   exceptions.rst

   strings.rst
   datatypes.rst
   numeric.rst
   filesys.rst
   persistence.rst
   archiving.rst
   fileformats.rst
   crypto.rst
   allos.rst
   someos.rst
   ipc.rst
   netdata.rst
   markup.rst
   internet.rst
   mm.rst
   i18n.rst
   frameworks.rst
   tk.rst
   development.rst
   debug.rst
   distribution.rst
   python.rst
   custominterp.rst
   restricted.rst
   modules.rst
   language.rst
   compiler.rst
   misc.rst
   windows.rst
   unix.rst
   mac.rst
   macosa.rst
   sgi.rst
   sun.rst
   undoc.rst
PK	%�\�B�m�m%html/_sources/library/inspect.rst.txtnu�[���:mod:`inspect` --- Inspect live objects
=======================================

.. module:: inspect
   :synopsis: Extract information and source code from live objects.
.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>


.. versionadded:: 2.1

**Source code:** :source:`Lib/inspect.py`

--------------

The :mod:`inspect` module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects.  For example, it can help you
examine the contents of a class, retrieve the source code of a method, extract
and format the argument list for a function, or get all the information you need
to display a detailed traceback.

There are four main kinds of services provided by this module: type checking,
getting source code, inspecting classes and functions, and examining the
interpreter stack.


.. _inspect-types:

Types and members
-----------------

The :func:`getmembers` function retrieves the members of an object such as a
class or module. The sixteen functions whose names begin with "is" are mainly
provided as convenient choices for the second argument to :func:`getmembers`.
They also help you determine when you can expect to find the following special
attributes:

+-----------+-----------------+---------------------------+-------+
| Type      | Attribute       | Description               | Notes |
+===========+=================+===========================+=======+
| module    | __doc__         | documentation string      |       |
+-----------+-----------------+---------------------------+-------+
|           | __file__        | filename (missing for     |       |
|           |                 | built-in modules)         |       |
+-----------+-----------------+---------------------------+-------+
| class     | __doc__         | documentation string      |       |
+-----------+-----------------+---------------------------+-------+
|           | __module__      | name of module in which   |       |
|           |                 | this class was defined    |       |
+-----------+-----------------+---------------------------+-------+
| method    | __doc__         | documentation string      |       |
+-----------+-----------------+---------------------------+-------+
|           | __name__        | name with which this      |       |
|           |                 | method was defined        |       |
+-----------+-----------------+---------------------------+-------+
|           | im_class        | class object that asked   | \(1)  |
|           |                 | for this method           |       |
+-----------+-----------------+---------------------------+-------+
|           | im_func or      | function object           |       |
|           | __func__        | containing implementation |       |
|           |                 | of method                 |       |
+-----------+-----------------+---------------------------+-------+
|           | im_self or      | instance to which this    |       |
|           | __self__        | method is bound, or       |       |
|           |                 | ``None``                  |       |
+-----------+-----------------+---------------------------+-------+
| function  | __doc__         | documentation string      |       |
+-----------+-----------------+---------------------------+-------+
|           | __name__        | name with which this      |       |
|           |                 | function was defined      |       |
+-----------+-----------------+---------------------------+-------+
|           | func_code       | code object containing    |       |
|           |                 | compiled function         |       |
|           |                 | :term:`bytecode`          |       |
+-----------+-----------------+---------------------------+-------+
|           | func_defaults   | tuple of any default      |       |
|           |                 | values for arguments      |       |
+-----------+-----------------+---------------------------+-------+
|           | func_doc        | (same as __doc__)         |       |
+-----------+-----------------+---------------------------+-------+
|           | func_globals    | global namespace in which |       |
|           |                 | this function was defined |       |
+-----------+-----------------+---------------------------+-------+
|           | func_name       | (same as __name__)        |       |
+-----------+-----------------+---------------------------+-------+
| generator | __iter__        | defined to support        |       |
|           |                 | iteration over container  |       |
+-----------+-----------------+---------------------------+-------+
|           | close           | raises new GeneratorExit  |       |
|           |                 | exception inside the      |       |
|           |                 | generator to terminate    |       |
|           |                 | the iteration             |       |
+-----------+-----------------+---------------------------+-------+
|           | gi_code         | code object               |       |
+-----------+-----------------+---------------------------+-------+
|           | gi_frame        | frame object or possibly  |       |
|           |                 | ``None`` once the         |       |
|           |                 | generator has been        |       |
|           |                 | exhausted                 |       |
+-----------+-----------------+---------------------------+-------+
|           | gi_running      | set to 1 when generator   |       |
|           |                 | is executing, 0 otherwise |       |
+-----------+-----------------+---------------------------+-------+
|           | next            | return the next item from |       |
|           |                 | the container             |       |
+-----------+-----------------+---------------------------+-------+
|           | send            | resumes the generator and |       |
|           |                 | "sends" a value that      |       |
|           |                 | becomes the result of the |       |
|           |                 | current yield-expression  |       |
+-----------+-----------------+---------------------------+-------+
|           | throw           | used to raise an          |       |
|           |                 | exception inside the      |       |
|           |                 | generator                 |       |
+-----------+-----------------+---------------------------+-------+
| traceback | tb_frame        | frame object at this      |       |
|           |                 | level                     |       |
+-----------+-----------------+---------------------------+-------+
|           | tb_lasti        | index of last attempted   |       |
|           |                 | instruction in bytecode   |       |
+-----------+-----------------+---------------------------+-------+
|           | tb_lineno       | current line number in    |       |
|           |                 | Python source code        |       |
+-----------+-----------------+---------------------------+-------+
|           | tb_next         | next inner traceback      |       |
|           |                 | object (called by this    |       |
|           |                 | level)                    |       |
+-----------+-----------------+---------------------------+-------+
| frame     | f_back          | next outer frame object   |       |
|           |                 | (this frame's caller)     |       |
+-----------+-----------------+---------------------------+-------+
|           | f_builtins      | builtins namespace seen   |       |
|           |                 | by this frame             |       |
+-----------+-----------------+---------------------------+-------+
|           | f_code          | code object being         |       |
|           |                 | executed in this frame    |       |
+-----------+-----------------+---------------------------+-------+
|           | f_exc_traceback | traceback if raised in    |       |
|           |                 | this frame, or ``None``   |       |
+-----------+-----------------+---------------------------+-------+
|           | f_exc_type      | exception type if raised  |       |
|           |                 | in this frame, or         |       |
|           |                 | ``None``                  |       |
+-----------+-----------------+---------------------------+-------+
|           | f_exc_value     | exception value if raised |       |
|           |                 | in this frame, or         |       |
|           |                 | ``None``                  |       |
+-----------+-----------------+---------------------------+-------+
|           | f_globals       | global namespace seen by  |       |
|           |                 | this frame                |       |
+-----------+-----------------+---------------------------+-------+
|           | f_lasti         | index of last attempted   |       |
|           |                 | instruction in bytecode   |       |
+-----------+-----------------+---------------------------+-------+
|           | f_lineno        | current line number in    |       |
|           |                 | Python source code        |       |
+-----------+-----------------+---------------------------+-------+
|           | f_locals        | local namespace seen by   |       |
|           |                 | this frame                |       |
+-----------+-----------------+---------------------------+-------+
|           | f_restricted    | 0 or 1 if frame is in     |       |
|           |                 | restricted execution mode |       |
+-----------+-----------------+---------------------------+-------+
|           | f_trace         | tracing function for this |       |
|           |                 | frame, or ``None``        |       |
+-----------+-----------------+---------------------------+-------+
| code      | co_argcount     | number of arguments (not  |       |
|           |                 | including \* or \*\*      |       |
|           |                 | args)                     |       |
+-----------+-----------------+---------------------------+-------+
|           | co_code         | string of raw compiled    |       |
|           |                 | bytecode                  |       |
+-----------+-----------------+---------------------------+-------+
|           | co_consts       | tuple of constants used   |       |
|           |                 | in the bytecode           |       |
+-----------+-----------------+---------------------------+-------+
|           | co_filename     | name of file in which     |       |
|           |                 | this code object was      |       |
|           |                 | created                   |       |
+-----------+-----------------+---------------------------+-------+
|           | co_firstlineno  | number of first line in   |       |
|           |                 | Python source code        |       |
+-----------+-----------------+---------------------------+-------+
|           | co_flags        | bitmap: 1=optimized ``|`` |       |
|           |                 | 2=newlocals ``|`` 4=\*arg |       |
|           |                 | ``|`` 8=\*\*arg           |       |
+-----------+-----------------+---------------------------+-------+
|           | co_lnotab       | encoded mapping of line   |       |
|           |                 | numbers to bytecode       |       |
|           |                 | indices                   |       |
+-----------+-----------------+---------------------------+-------+
|           | co_name         | name with which this code |       |
|           |                 | object was defined        |       |
+-----------+-----------------+---------------------------+-------+
|           | co_names        | tuple of names of local   |       |
|           |                 | variables                 |       |
+-----------+-----------------+---------------------------+-------+
|           | co_nlocals      | number of local variables |       |
+-----------+-----------------+---------------------------+-------+
|           | co_stacksize    | virtual machine stack     |       |
|           |                 | space required            |       |
+-----------+-----------------+---------------------------+-------+
|           | co_varnames     | tuple of names of         |       |
|           |                 | arguments and local       |       |
|           |                 | variables                 |       |
+-----------+-----------------+---------------------------+-------+
| builtin   | __doc__         | documentation string      |       |
+-----------+-----------------+---------------------------+-------+
|           | __name__        | original name of this     |       |
|           |                 | function or method        |       |
+-----------+-----------------+---------------------------+-------+
|           | __self__        | instance to which a       |       |
|           |                 | method is bound, or       |       |
|           |                 | ``None``                  |       |
+-----------+-----------------+---------------------------+-------+

Note:

(1)
   .. versionchanged:: 2.2
      :attr:`im_class` used to refer to the class that defined the method.


.. function:: getmembers(object[, predicate])

   Return all the members of an object in a list of (name, value) pairs sorted by
   name.  If the optional *predicate* argument is supplied, only members for which
   the predicate returns a true value are included.

   .. note::

      :func:`getmembers` does not return metaclass attributes when the argument
      is a class (this behavior is inherited from the :func:`dir` function).


.. function:: getmoduleinfo(path)

   Return a tuple of values that describe how Python will interpret the file
   identified by *path* if it is a module, or ``None`` if it would not be
   identified as a module.  The return tuple is ``(name, suffix, mode,
   module_type)``, where *name* is the name of the module without the name of
   any enclosing package, *suffix* is the trailing part of the file name (which
   may not be a dot-delimited extension), *mode* is the :func:`open` mode that
   would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
   the type of the module.  *module_type* will have a value which can be
   compared to the constants defined in the :mod:`imp` module; see the
   documentation for that module for more information on module types.

   .. versionchanged:: 2.6
      Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
      module_type)``.


.. function:: getmodulename(path)

   Return the name of the module named by the file *path*, without including the
   names of enclosing packages.  This uses the same algorithm as the interpreter
   uses when searching for modules.  If the name cannot be matched according to the
   interpreter's rules, ``None`` is returned.


.. function:: ismodule(object)

   Return true if the object is a module.


.. function:: isclass(object)

   Return true if the object is a class, whether built-in or created in Python
   code.


.. function:: ismethod(object)

   Return true if the object is a bound or unbound method written in Python.



.. function:: isfunction(object)

   Return true if the object is a Python function, which includes functions
   created by a :term:`lambda` expression.


.. function:: isgeneratorfunction(object)

   Return true if the object is a Python generator function.

   .. versionadded:: 2.6


.. function:: isgenerator(object)

   Return true if the object is a generator.

   .. versionadded:: 2.6


.. function:: istraceback(object)

   Return true if the object is a traceback.


.. function:: isframe(object)

   Return true if the object is a frame.


.. function:: iscode(object)

   Return true if the object is a code.


.. function:: isbuiltin(object)

   Return true if the object is a built-in function or a bound built-in method.


.. function:: isroutine(object)

   Return true if the object is a user-defined or built-in function or method.


.. function:: isabstract(object)

   Return true if the object is an abstract base class.

   .. versionadded:: 2.6


.. function:: ismethoddescriptor(object)

   Return true if the object is a method descriptor, but not if
   :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
   are true.

   This is new as of Python 2.2, and, for example, is true of
   ``int.__add__``. An object passing this test
   has a :meth:`~object.__get__` method but not a :meth:`~object.__set__`
   method, but beyond that the set of attributes varies.  A
   :attr:`~definition.__name__` attribute is usually
   sensible, and :attr:`__doc__` often is.

   Methods implemented via descriptors that also pass one of the other tests
   return false from the :func:`ismethoddescriptor` test, simply because the
   other tests promise more -- you can, e.g., count on having the
   :attr:`im_func` attribute (etc) when an object passes :func:`ismethod`.


.. function:: isdatadescriptor(object)

   Return true if the object is a data descriptor.

   Data descriptors have both a :attr:`~object.__get__` and a :attr:`~object.__set__` method.
   Examples are properties (defined in Python), getsets, and members.  The
   latter two are defined in C and there are more specific tests available for
   those types, which is robust across Python implementations.  Typically, data
   descriptors will also have :attr:`~definition.__name__` and :attr:`__doc__` attributes
   (properties, getsets, and members have both of these attributes), but this is
   not guaranteed.

   .. versionadded:: 2.3


.. function:: isgetsetdescriptor(object)

   Return true if the object is a getset descriptor.

   .. impl-detail::

      getsets are attributes defined in extension modules via
      :c:type:`PyGetSetDef` structures.  For Python implementations without such
      types, this method will always return ``False``.

   .. versionadded:: 2.5


.. function:: ismemberdescriptor(object)

   Return true if the object is a member descriptor.

   .. impl-detail::

      Member descriptors are attributes defined in extension modules via
      :c:type:`PyMemberDef` structures.  For Python implementations without such
      types, this method will always return ``False``.

   .. versionadded:: 2.5


.. _inspect-source:

Retrieving source code
----------------------

.. function:: getdoc(object)

   Get the documentation string for an object, cleaned up with :func:`cleandoc`.


.. function:: getcomments(object)

   Return in a single string any lines of comments immediately preceding the
   object's source code (for a class, function, or method), or at the top of the
   Python source file (if the object is a module).


.. function:: getfile(object)

   Return the name of the (text or binary) file in which an object was defined.
   This will fail with a :exc:`TypeError` if the object is a built-in module,
   class, or function.


.. function:: getmodule(object)

   Try to guess which module an object was defined in.


.. function:: getsourcefile(object)

   Return the name of the Python source file in which an object was defined.  This
   will fail with a :exc:`TypeError` if the object is a built-in module, class, or
   function.


.. function:: getsourcelines(object)

   Return a list of source lines and starting line number for an object. The
   argument may be a module, class, method, function, traceback, frame, or code
   object.  The source code is returned as a list of the lines corresponding to the
   object and the line number indicates where in the original source file the first
   line of code was found.  An :exc:`IOError` is raised if the source code cannot
   be retrieved.


.. function:: getsource(object)

   Return the text of the source code for an object. The argument may be a module,
   class, method, function, traceback, frame, or code object.  The source code is
   returned as a single string.  An :exc:`IOError` is raised if the source code
   cannot be retrieved.


.. function:: cleandoc(doc)

   Clean up indentation from docstrings that are indented to line up with blocks
   of code.

   All leading whitespace is removed from the first line.  Any leading whitespace
   that can be uniformly removed from the second line onwards is removed.  Empty
   lines at the beginning and end are subsequently removed.  Also, all tabs are
   expanded to spaces.

   .. versionadded:: 2.6


.. _inspect-classes-functions:

Classes and functions
---------------------


.. function:: getclasstree(classes[, unique])

   Arrange the given list of classes into a hierarchy of nested lists. Where a
   nested list appears, it contains classes derived from the class whose entry
   immediately precedes the list.  Each entry is a 2-tuple containing a class and a
   tuple of its base classes.  If the *unique* argument is true, exactly one entry
   appears in the returned structure for each class in the given list.  Otherwise,
   classes using multiple inheritance and their descendants will appear multiple
   times.


.. function:: getargspec(func)

   Get the names and default values of a Python function's arguments. A tuple of
   four things is returned: ``(args, varargs, keywords, defaults)``. *args* is a
   list of the argument names (it may contain nested lists). *varargs* and
   *keywords* are the names of the ``*`` and ``**`` arguments or
   ``None``. *defaults* is a tuple of default argument values or ``None`` if there
   are no default arguments; if this tuple has *n* elements, they correspond to
   the last *n* elements listed in *args*.

   .. versionchanged:: 2.6
      Returns a :term:`named tuple` ``ArgSpec(args, varargs, keywords,
      defaults)``.


.. function:: getargvalues(frame)

   Get information about arguments passed into a particular frame. A tuple of
   four things is returned: ``(args, varargs, keywords, locals)``. *args* is a
   list of the argument names (it may contain nested lists). *varargs* and
   *keywords* are the names of the ``*`` and ``**`` arguments or ``None``.
   *locals* is the locals dictionary of the given frame.

   .. versionchanged:: 2.6
      Returns a :term:`named tuple` ``ArgInfo(args, varargs, keywords,
      locals)``.


.. function:: formatargspec(args[, varargs, varkw, defaults, formatarg, formatvarargs, formatvarkw, formatvalue, join])

   Format a pretty argument spec from the four values returned by
   :func:`getargspec`.  The format\* arguments are the corresponding optional
   formatting functions that are called to turn names and values into strings.


.. function:: formatargvalues(args[, varargs, varkw, locals, formatarg, formatvarargs, formatvarkw, formatvalue, join])

   Format a pretty argument spec from the four values returned by
   :func:`getargvalues`.  The format\* arguments are the corresponding optional
   formatting functions that are called to turn names and values into strings.


.. function:: getmro(cls)

   Return a tuple of class cls's base classes, including cls, in method resolution
   order.  No class appears more than once in this tuple. Note that the method
   resolution order depends on cls's type.  Unless a very peculiar user-defined
   metatype is in use, cls will be the first element of the tuple.


.. function:: getcallargs(func[, *args][, **kwds])

   Bind the *args* and *kwds* to the argument names of the Python function or
   method *func*, as if it was called with them. For bound methods, bind also the
   first argument (typically named ``self``) to the associated instance. A dict
   is returned, mapping the argument names (including the names of the ``*`` and
   ``**`` arguments, if any) to their values from *args* and *kwds*. In case of
   invoking *func* incorrectly, i.e. whenever ``func(*args, **kwds)`` would raise
   an exception because of incompatible signature, an exception of the same type
   and the same or similar message is raised. For example::

    >>> from inspect import getcallargs
    >>> def f(a, b=1, *pos, **named):
    ...     pass
    >>> getcallargs(f, 1, 2, 3)
    {'a': 1, 'named': {}, 'b': 2, 'pos': (3,)}
    >>> getcallargs(f, a=2, x=4)
    {'a': 2, 'named': {'x': 4}, 'b': 1, 'pos': ()}
    >>> getcallargs(f)
    Traceback (most recent call last):
    ...
    TypeError: f() takes at least 1 argument (0 given)

   .. versionadded:: 2.7


.. _inspect-stack:

The interpreter stack
---------------------

When the following functions return "frame records," each record is a tuple of
six items: the frame object, the filename, the line number of the current line,
the function name, a list of lines of context from the source code, and the
index of the current line within that list.

.. note::

   Keeping references to frame objects, as found in the first element of the frame
   records these functions return, can cause your program to create reference
   cycles.  Once a reference cycle has been created, the lifespan of all objects
   which can be accessed from the objects which form the cycle can become much
   longer even if Python's optional cycle detector is enabled.  If such cycles must
   be created, it is important to ensure they are explicitly broken to avoid the
   delayed destruction of objects and increased memory consumption which occurs.

   Though the cycle detector will catch these, destruction of the frames (and local
   variables) can be made deterministic by removing the cycle in a
   :keyword:`finally` clause.  This is also important if the cycle detector was
   disabled when Python was compiled or using :func:`gc.disable`.  For example::

      def handle_stackframe_without_leak():
          frame = inspect.currentframe()
          try:
              # do something with the frame
          finally:
              del frame

The optional *context* argument supported by most of these functions specifies
the number of lines of context to return, which are centered around the current
line.


.. function:: getframeinfo(frame[, context])

   Get information about a frame or traceback object.  A 5-tuple is returned, the
   last five elements of the frame's frame record.

   .. versionchanged:: 2.6
      Returns a :term:`named tuple` ``Traceback(filename, lineno, function,
      code_context, index)``.


.. function:: getouterframes(frame[, context])

   Get a list of frame records for a frame and all outer frames.  These frames
   represent the calls that lead to the creation of *frame*. The first entry in the
   returned list represents *frame*; the last entry represents the outermost call
   on *frame*'s stack.


.. function:: getinnerframes(traceback[, context])

   Get a list of frame records for a traceback's frame and all inner frames.  These
   frames represent calls made as a consequence of *frame*.  The first entry in the
   list represents *traceback*; the last entry represents where the exception was
   raised.


.. function:: currentframe()

   Return the frame object for the caller's stack frame.

   .. impl-detail::

      This function relies on Python stack frame support in the interpreter,
      which isn't guaranteed to exist in all implementations of Python.  If
      running in an implementation without Python stack frame support this
      function returns ``None``.


.. function:: stack([context])

   Return a list of frame records for the caller's stack.  The first entry in the
   returned list represents the caller; the last entry represents the outermost
   call on the stack.


.. function:: trace([context])

   Return a list of frame records for the stack between the current frame and the
   frame in which an exception currently being handled was raised in.  The first
   entry in the list represents the caller; the last entry represents where the
   exception was raised.

PK	%�\o!����&html/_sources/library/internet.rst.txtnu�[���
.. _internet:

******************************
Internet Protocols and Support
******************************

.. index::
   single: WWW
   single: Internet
   single: World Wide Web

.. index:: module: socket

The modules described in this chapter implement Internet protocols and  support
for related technology.  They are all implemented in Python. Most of these
modules require the presence of the system-dependent module :mod:`socket`, which
is currently supported on most popular platforms.  Here is an overview:


.. toctree::

   webbrowser.rst
   cgi.rst
   cgitb.rst
   wsgiref.rst
   urllib.rst
   urllib2.rst
   httplib.rst
   ftplib.rst
   poplib.rst
   imaplib.rst
   nntplib.rst
   smtplib.rst
   smtpd.rst
   telnetlib.rst
   uuid.rst
   urlparse.rst
   socketserver.rst
   basehttpserver.rst
   simplehttpserver.rst
   cgihttpserver.rst
   cookielib.rst
   cookie.rst
   xmlrpclib.rst
   simplexmlrpcserver.rst
   docxmlrpcserver.rst
PK	%�\V��
�
#html/_sources/library/intro.rst.txtnu�[���
.. _library-intro:

************
Introduction
************

The "Python library" contains several different kinds of components.

It contains data types that would normally be considered part of the "core" of a
language, such as numbers and lists.  For these types, the Python language core
defines the form of literals and places some constraints on their semantics, but
does not fully define the semantics.  (On the other hand, the language core does
define syntactic properties like the spelling and priorities of operators.)

The library also contains built-in functions and exceptions --- objects that can
be used by all Python code without the need of an :keyword:`import` statement.
Some of these are defined by the core language, but many are not essential for
the core semantics and are only described here.

The bulk of the library, however, consists of a collection of modules. There are
many ways to dissect this collection.  Some modules are written in C and built
in to the Python interpreter; others are written in Python and imported in
source form.  Some modules provide interfaces that are highly specific to
Python, like printing a stack trace; some provide interfaces that are specific
to particular operating systems, such as access to specific hardware; others
provide interfaces that are specific to a particular application domain, like
the World Wide Web. Some modules are available in all versions and ports of
Python; others are only available when the underlying system supports or
requires them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.

This manual is organized "from the inside out:" it first describes the built-in
data types, then the built-in functions and exceptions, and finally the modules,
grouped in chapters of related modules.  The ordering of the chapters as well as
the ordering of the modules within each chapter is roughly from most relevant to
least important.

This means that if you start reading this manual from the start, and skip to the
next chapter when you get bored, you will get a reasonable overview of the
available modules and application areas that are supported by the Python
library.  Of course, you don't *have* to read it like a novel --- you can also
browse the table of contents (in front of the manual), or look for a specific
function, module or term in the index (in the back).  And finally, if you enjoy
learning about random subjects, you choose a random page number (see module
:mod:`random`) and read a section or two.  Regardless of the order in which you
read the sections of this manual, it helps to start with chapter
:ref:`built-in-funcs`, as the remainder of the manual assumes familiarity with
this material.

Let the show begin!

PK	%�\���g�g� html/_sources/library/io.rst.txtnu�[���:mod:`io` --- Core tools for working with streams
=================================================

.. module:: io
   :synopsis: Core tools for working with streams.
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. moduleauthor:: Mike Verdone <mike.verdone@gmail.com>
.. moduleauthor:: Mark Russell <mark.russell@zen.co.uk>
.. moduleauthor:: Antoine Pitrou <solipsis@pitrou.net>
.. moduleauthor:: Amaury Forgeot d'Arc <amauryfa@gmail.com>
.. moduleauthor:: Benjamin Peterson <benjamin@python.org>
.. sectionauthor:: Benjamin Peterson <benjamin@python.org>

.. versionadded:: 2.6

The :mod:`io` module provides the Python interfaces to stream handling.
Under Python 2.x, this is proposed as an alternative to the built-in
:class:`file` object, but in Python 3.x it is the default interface to
access files and streams.

.. note::

   Since this module has been designed primarily for Python 3.x, you have to
   be aware that all uses of "bytes" in this document refer to the
   :class:`str` type (of which :class:`bytes` is an alias), and all uses
   of "text" refer to the :class:`unicode` type.  Furthermore, those two
   types are not interchangeable in the :mod:`io` APIs.

At the top of the I/O hierarchy is the abstract base class :class:`IOBase`.  It
defines the basic interface to a stream.  Note, however, that there is no
separation between reading and writing to streams; implementations are allowed
to raise an :exc:`IOError` if they do not support a given operation.

Extending :class:`IOBase` is :class:`RawIOBase` which deals simply with the
reading and writing of raw bytes to a stream.  :class:`FileIO` subclasses
:class:`RawIOBase` to provide an interface to files in the machine's
file system.

:class:`BufferedIOBase` deals with buffering on a raw byte stream
(:class:`RawIOBase`).  Its subclasses, :class:`BufferedWriter`,
:class:`BufferedReader`, and :class:`BufferedRWPair` buffer streams that are
readable, writable, and both readable and writable.
:class:`BufferedRandom` provides a buffered interface to random access
streams.  :class:`BytesIO` is a simple stream of in-memory bytes.

Another :class:`IOBase` subclass, :class:`TextIOBase`, deals with
streams whose bytes represent text, and handles encoding and decoding
from and to :class:`unicode` strings.  :class:`TextIOWrapper`, which extends
it, is a buffered text interface to a buffered raw stream
(:class:`BufferedIOBase`). Finally, :class:`~io.StringIO` is an in-memory
stream for unicode text.

Argument names are not part of the specification, and only the arguments of
:func:`.open` are intended to be used as keyword arguments.


Module Interface
----------------

.. data:: DEFAULT_BUFFER_SIZE

   An int containing the default buffer size used by the module's buffered I/O
   classes.  :func:`.open` uses the file's blksize (as obtained by
   :func:`os.stat`) if possible.

.. function:: open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)

   Open *file* and return a corresponding stream.  If the file cannot be opened,
   an :exc:`IOError` is raised.

   *file* is either a string giving the pathname (absolute or
   relative to the current working directory) of the file to be opened or
   an integer file descriptor of the file to be wrapped.  (If a file descriptor
   is given, it is closed when the returned I/O object is closed, unless
   *closefd* is set to ``False``.)

   *mode* is an optional string that specifies the mode in which the file is
   opened.  It defaults to ``'r'`` which means open for reading in text mode.
   Other common values are ``'w'`` for writing (truncating the file if it
   already exists), and ``'a'`` for appending (which on *some* Unix systems,
   means that *all* writes append to the end of the file regardless of the
   current seek position).  In text mode, if *encoding* is not specified the
   encoding used is platform dependent. (For reading and writing raw bytes use
   binary mode and leave *encoding* unspecified.)  The available modes are:

   ========= ===============================================================
   Character Meaning
   --------- ---------------------------------------------------------------
   ``'r'``   open for reading (default)
   ``'w'``   open for writing, truncating the file first
   ``'a'``   open for writing, appending to the end of the file if it exists
   ``'b'``   binary mode
   ``'t'``   text mode (default)
   ``'+'``   open a disk file for updating (reading and writing)
   ``'U'``   universal newlines mode (for backwards compatibility; should
             not be used in new code)
   ========= ===============================================================

   The default mode is ``'rt'`` (open for reading text).  For binary random
   access, the mode ``'w+b'`` opens and truncates the file to 0 bytes, while
   ``'r+b'`` opens the file without truncation.

   Python distinguishes between files opened in binary and text modes, even when
   the underlying operating system doesn't.  Files opened in binary mode
   (including ``'b'`` in the *mode* argument) return contents as :class:`bytes`
   objects without any decoding.  In text mode (the default, or when ``'t'`` is
   included in the *mode* argument), the contents of the file are returned as
   :class:`unicode` strings, the bytes having been first decoded using a
   platform-dependent encoding or using the specified *encoding* if given.

   *buffering* is an optional integer used to set the buffering policy.
   Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
   line buffering (only usable in text mode), and an integer > 1 to indicate
   the size of a fixed-size chunk buffer.  When no *buffering* argument is
   given, the default buffering policy works as follows:

   * Binary files are buffered in fixed-size chunks; the size of the buffer
     is chosen using a heuristic trying to determine the underlying device's
     "block size" and falling back on :attr:`DEFAULT_BUFFER_SIZE`.
     On many systems, the buffer will typically be 4096 or 8192 bytes long.

   * "Interactive" text files (files for which :meth:`isatty` returns True)
     use line buffering.  Other text files use the policy described above
     for binary files.

   *encoding* is the name of the encoding used to decode or encode the file.
   This should only be used in text mode.  The default encoding is platform
   dependent (whatever :func:`locale.getpreferredencoding` returns), but any
   encoding supported by Python can be used.  See the :mod:`codecs` module for
   the list of supported encodings.

   *errors* is an optional string that specifies how encoding and decoding
   errors are to be handled—this cannot be used in binary mode.  Pass
   ``'strict'`` to raise a :exc:`ValueError` exception if there is an encoding
   error (the default of ``None`` has the same effect), or pass ``'ignore'`` to
   ignore errors.  (Note that ignoring encoding errors can lead to data loss.)
   ``'replace'`` causes a replacement marker (such as ``'?'``) to be inserted
   where there is malformed data.  When writing, ``'xmlcharrefreplace'``
   (replace with the appropriate XML character reference) or
   ``'backslashreplace'`` (replace with backslashed escape sequences) can be
   used.  Any other error handling name that has been registered with
   :func:`codecs.register_error` is also valid.

   .. index::
      single: universal newlines; open() (in module io)

   *newline* controls how :term:`universal newlines` works (it only applies to
   text mode).  It can be ``None``, ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``.
   It works as follows:

   * On input, if *newline* is ``None``, universal newlines mode is enabled.
     Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``, and these
     are translated into ``'\n'`` before being returned to the caller.  If it is
     ``''``, universal newlines mode is enabled, but line endings are returned to
     the caller untranslated.  If it has any of the other legal values, input
     lines are only terminated by the given string, and the line ending is
     returned to the caller untranslated.

   * On output, if *newline* is ``None``, any ``'\n'`` characters written are
     translated to the system default line separator, :data:`os.linesep`.  If
     *newline* is ``''``, no translation takes place.  If *newline* is any of
     the other legal values, any ``'\n'`` characters written are translated to
     the given string.

   If *closefd* is ``False`` and a file descriptor rather than a filename was
   given, the underlying file descriptor will be kept open when the file is
   closed.  If a filename is given *closefd* has no effect and must be ``True``
   (the default).

   The type of file object returned by the :func:`.open` function depends on the
   mode.  When :func:`.open` is used to open a file in a text mode (``'w'``,
   ``'r'``, ``'wt'``, ``'rt'``, etc.), it returns a subclass of
   :class:`TextIOBase` (specifically :class:`TextIOWrapper`).  When used to open
   a file in a binary mode with buffering, the returned class is a subclass of
   :class:`BufferedIOBase`.  The exact class varies: in read binary mode, it
   returns a :class:`BufferedReader`; in write binary and append binary modes,
   it returns a :class:`BufferedWriter`, and in read/write mode, it returns a
   :class:`BufferedRandom`.  When buffering is disabled, the raw stream, a
   subclass of :class:`RawIOBase`, :class:`FileIO`, is returned.

   It is also possible to use an :class:`unicode` or :class:`bytes` string
   as a file for both reading and writing.  For :class:`unicode` strings
   :class:`~io.StringIO` can be used like a file opened in text mode,
   and for :class:`bytes` a :class:`BytesIO` can be used like a
   file opened in a binary mode.


.. exception:: BlockingIOError

   Error raised when blocking would occur on a non-blocking stream.  It inherits
   :exc:`IOError`.

   In addition to those of :exc:`IOError`, :exc:`BlockingIOError` has one
   attribute:

   .. attribute:: characters_written

      An integer containing the number of characters written to the stream
      before it blocked.


.. exception:: UnsupportedOperation

   An exception inheriting :exc:`IOError` and :exc:`ValueError` that is raised
   when an unsupported operation is called on a stream.


I/O Base Classes
----------------

.. class:: IOBase

   The abstract base class for all I/O classes, acting on streams of bytes.
   There is no public constructor.

   This class provides empty abstract implementations for many methods
   that derived classes can override selectively; the default
   implementations represent a file that cannot be read, written or
   seeked.

   Even though :class:`IOBase` does not declare :meth:`read`, :meth:`readinto`,
   or :meth:`write` because their signatures will vary, implementations and
   clients should consider those methods part of the interface.  Also,
   implementations may raise an :exc:`IOError` when operations they do not
   support are called.

   The basic type used for binary data read from or written to a file is
   :class:`bytes` (also known as :class:`str`).  Method arguments may
   also be :class:`bytearray` or :class:`memoryview` of arrays of bytes.
   In some cases, such as :meth:`~RawIOBase.readinto`, a writable object
   such as :class:`bytearray` is required.
   Text I/O classes work with :class:`unicode` data.

   .. versionchanged:: 2.7
      Implementations should support :class:`memoryview` arguments.

   Note that calling any method (even inquiries) on a closed stream is
   undefined.  Implementations may raise :exc:`IOError` in this case.

   IOBase (and its subclasses) support the iterator protocol, meaning that an
   :class:`IOBase` object can be iterated over yielding the lines in a stream.
   Lines are defined slightly differently depending on whether the stream is
   a binary stream (yielding :class:`bytes`), or a text stream (yielding
   :class:`unicode` strings).  See :meth:`~IOBase.readline` below.

   IOBase is also a context manager and therefore supports the
   :keyword:`with` statement.  In this example, *file* is closed after the
   :keyword:`with` statement's suite is finished---even if an exception occurs::

      with io.open('spam.txt', 'w') as file:
          file.write(u'Spam and eggs!')

   :class:`IOBase` provides these data attributes and methods:

   .. method:: close()

      Flush and close this stream. This method has no effect if the file is
      already closed. Once the file is closed, any operation on the file
      (e.g. reading or writing) will raise a :exc:`ValueError`.

      As a convenience, it is allowed to call this method more than once;
      only the first call, however, will have an effect.

   .. attribute:: closed

      True if the stream is closed.

   .. method:: fileno()

      Return the underlying file descriptor (an integer) of the stream if it
      exists.  An :exc:`IOError` is raised if the IO object does not use a file
      descriptor.

   .. method:: flush()

      Flush the write buffers of the stream if applicable.  This does nothing
      for read-only and non-blocking streams.

   .. method:: isatty()

      Return ``True`` if the stream is interactive (i.e., connected to
      a terminal/tty device).

   .. method:: readable()

      Return ``True`` if the stream can be read from.  If ``False``, :meth:`read`
      will raise :exc:`IOError`.

   .. method:: readline(limit=-1)

      Read and return one line from the stream.  If *limit* is specified, at
      most *limit* bytes will be read.

      The line terminator is always ``b'\n'`` for binary files; for text files,
      the *newline* argument to :func:`.open` can be used to select the line
      terminator(s) recognized.

   .. method:: readlines(hint=-1)

      Read and return a list of lines from the stream.  *hint* can be specified
      to control the number of lines read: no more lines will be read if the
      total size (in bytes/characters) of all lines so far exceeds *hint*.

      Note that it's already possible to iterate on file objects using ``for
      line in file: ...`` without calling ``file.readlines()``.

   .. method:: seek(offset[, whence])

      Change the stream position to the given byte *offset*.  *offset* is
      interpreted relative to the position indicated by *whence*.  The default
      value for *whence* is :data:`SEEK_SET`.  Values for *whence* are:

      * :data:`SEEK_SET` or ``0`` -- start of the stream (the default);
        *offset* should be zero or positive
      * :data:`SEEK_CUR` or ``1`` -- current stream position; *offset* may
        be negative
      * :data:`SEEK_END` or ``2`` -- end of the stream; *offset* is usually
        negative

      Return the new absolute position.

      .. versionadded:: 2.7
         The ``SEEK_*`` constants

   .. method:: seekable()

      Return ``True`` if the stream supports random access.  If ``False``,
      :meth:`seek`, :meth:`tell` and :meth:`truncate` will raise :exc:`IOError`.

   .. method:: tell()

      Return the current stream position.

   .. method:: truncate(size=None)

      Resize the stream to the given *size* in bytes (or the current position
      if *size* is not specified).  The current stream position isn't changed.
      This resizing can extend or reduce the current file size.  In case of
      extension, the contents of the new file area depend on the platform
      (on most systems, additional bytes are zero-filled, on Windows they're
      undetermined).  The new file size is returned.

   .. method:: writable()

      Return ``True`` if the stream supports writing.  If ``False``,
      :meth:`write` and :meth:`truncate` will raise :exc:`IOError`.

   .. method:: writelines(lines)

      Write a list of lines to the stream.  Line separators are not added, so it
      is usual for each of the lines provided to have a line separator at the
      end.

   .. method:: __del__()

      Prepare for object destruction. :class:`IOBase` provides a default
      implementation of this method that calls the instance's
      :meth:`~IOBase.close` method.


.. class:: RawIOBase

   Base class for raw binary I/O.  It inherits :class:`IOBase`.  There is no
   public constructor.

   Raw binary I/O typically provides low-level access to an underlying OS
   device or API, and does not try to encapsulate it in high-level primitives
   (this is left to Buffered I/O and Text I/O, described later in this page).

   In addition to the attributes and methods from :class:`IOBase`,
   RawIOBase provides the following methods:

   .. method:: read(n=-1)

      Read up to *n* bytes from the object and return them.  As a convenience,
      if *n* is unspecified or -1, :meth:`readall` is called.  Otherwise,
      only one system call is ever made.  Fewer than *n* bytes may be
      returned if the operating system call returns fewer than *n* bytes.

      If 0 bytes are returned, and *n* was not 0, this indicates end of file.
      If the object is in non-blocking mode and no bytes are available,
      ``None`` is returned.

   .. method:: readall()

      Read and return all the bytes from the stream until EOF, using multiple
      calls to the stream if necessary.

   .. method:: readinto(b)

      Read up to len(b) bytes into *b*, and return the number
      of bytes read.  The object *b* should be a pre-allocated, writable
      array of bytes, either :class:`bytearray` or :class:`memoryview`.
      If the object is in non-blocking mode and no
      bytes are available, ``None`` is returned.

   .. method:: write(b)

      Write *b* to the underlying raw stream, and return the
      number of bytes written.  The object *b* should be an array
      of bytes, either :class:`bytes`, :class:`bytearray`, or
      :class:`memoryview`.  The return value can be less than
      ``len(b)``, depending on specifics of the underlying raw stream, and
      especially if it is in non-blocking mode.  ``None`` is returned if the
      raw stream is set not to block and no single byte could be readily
      written to it.  The caller may release or mutate *b* after
      this method returns, so the implementation should only access *b*
      during the method call.


.. class:: BufferedIOBase

   Base class for binary streams that support some kind of buffering.
   It inherits :class:`IOBase`. There is no public constructor.

   The main difference with :class:`RawIOBase` is that methods :meth:`read`,
   :meth:`readinto` and :meth:`write` will try (respectively) to read as much
   input as requested or to consume all given output, at the expense of
   making perhaps more than one system call.

   In addition, those methods can raise :exc:`BlockingIOError` if the
   underlying raw stream is in non-blocking mode and cannot take or give
   enough data; unlike their :class:`RawIOBase` counterparts, they will
   never return ``None``.

   Besides, the :meth:`read` method does not have a default
   implementation that defers to :meth:`readinto`.

   A typical :class:`BufferedIOBase` implementation should not inherit from a
   :class:`RawIOBase` implementation, but wrap one, like
   :class:`BufferedWriter` and :class:`BufferedReader` do.

   :class:`BufferedIOBase` provides or overrides these methods and attribute in
   addition to those from :class:`IOBase`:

   .. attribute:: raw

      The underlying raw stream (a :class:`RawIOBase` instance) that
      :class:`BufferedIOBase` deals with.  This is not part of the
      :class:`BufferedIOBase` API and may not exist on some implementations.

   .. method:: detach()

      Separate the underlying raw stream from the buffer and return it.

      After the raw stream has been detached, the buffer is in an unusable
      state.

      Some buffers, like :class:`BytesIO`, do not have the concept of a single
      raw stream to return from this method.  They raise
      :exc:`UnsupportedOperation`.

      .. versionadded:: 2.7

   .. method:: read(n=-1)

      Read and return up to *n* bytes.  If the argument is omitted, ``None``, or
      negative, data is read and returned until EOF is reached.  An empty bytes
      object is returned if the stream is already at EOF.

      If the argument is positive, and the underlying raw stream is not
      interactive, multiple raw reads may be issued to satisfy the byte count
      (unless EOF is reached first).  But for interactive raw streams, at most
      one raw read will be issued, and a short result does not imply that EOF is
      imminent.

      A :exc:`BlockingIOError` is raised if the underlying raw stream is in
      non blocking-mode, and has no data available at the moment.

   .. method:: read1(n=-1)

      Read and return up to *n* bytes, with at most one call to the underlying
      raw stream's :meth:`~RawIOBase.read` method.  This can be useful if you
      are implementing your own buffering on top of a :class:`BufferedIOBase`
      object.

   .. method:: readinto(b)

      Read up to len(b) bytes into *b*, and return the number of bytes read.
      The object *b* should be a pre-allocated, writable array of bytes,
      either :class:`bytearray` or :class:`memoryview`.

      Like :meth:`read`, multiple reads may be issued to the underlying raw
      stream, unless the latter is 'interactive'.

      A :exc:`BlockingIOError` is raised if the underlying raw stream is in
      non blocking-mode, and has no data available at the moment.

   .. method:: write(b)

      Write *b*, and return the number of bytes written
      (always equal to ``len(b)``, since if the write fails
      an :exc:`IOError` will be raised).  The object *b* should be
      an array of bytes, either :class:`bytes`, :class:`bytearray`,
      or :class:`memoryview`.  Depending on the actual
      implementation, these bytes may be readily written to the underlying
      stream, or held in a buffer for performance and latency reasons.

      When in non-blocking mode, a :exc:`BlockingIOError` is raised if the
      data needed to be written to the raw stream but it couldn't accept
      all the data without blocking.

      The caller may release or mutate *b* after this method returns,
      so the implementation should only access *b* during the method call.


Raw File I/O
------------

.. class:: FileIO(name, mode='r', closefd=True)

   :class:`FileIO` represents an OS-level file containing bytes data.
   It implements the :class:`RawIOBase` interface (and therefore the
   :class:`IOBase` interface, too).

   The *name* can be one of two things:

   * a string representing the path to the file which will be opened;
   * an integer representing the number of an existing OS-level file descriptor
     to which the resulting :class:`FileIO` object will give access.

   The *mode* can be ``'r'``, ``'w'`` or ``'a'`` for reading (default), writing,
   or appending.  The file will be created if it doesn't exist when opened for
   writing or appending; it will be truncated when opened for writing.  Add a
   ``'+'`` to the mode to allow simultaneous reading and writing.

   The :meth:`read` (when called with a positive argument), :meth:`readinto`
   and :meth:`write` methods on this class will only make one system call.

   In addition to the attributes and methods from :class:`IOBase` and
   :class:`RawIOBase`, :class:`FileIO` provides the following data
   attributes and methods:

   .. attribute:: mode

      The mode as given in the constructor.

   .. attribute:: name

      The file name.  This is the file descriptor of the file when no name is
      given in the constructor.


Buffered Streams
----------------

Buffered I/O streams provide a higher-level interface to an I/O device
than raw I/O does.

.. class:: BytesIO([initial_bytes])

   A stream implementation using an in-memory bytes buffer.  It inherits
   :class:`BufferedIOBase`.

   The optional argument *initial_bytes* is a :class:`bytes` object that
   contains initial data.

   :class:`BytesIO` provides or overrides these methods in addition to those
   from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: getvalue()

      Return ``bytes`` containing the entire contents of the buffer.

   .. method:: read1()

      In :class:`BytesIO`, this is the same as :meth:`read`.


.. class:: BufferedReader(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffer providing higher-level access to a readable, sequential
   :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
   When reading data from this object, a larger amount of data may be
   requested from the underlying raw stream, and kept in an internal buffer.
   The buffered data can then be returned directly on subsequent reads.

   The constructor creates a :class:`BufferedReader` for the given readable
   *raw* stream and *buffer_size*.  If *buffer_size* is omitted,
   :data:`DEFAULT_BUFFER_SIZE` is used.

   :class:`BufferedReader` provides or overrides these methods in addition to
   those from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: peek([n])

      Return bytes from the stream without advancing the position.  At most one
      single read on the raw stream is done to satisfy the call. The number of
      bytes returned may be less or more than requested.

   .. method:: read([n])

      Read and return *n* bytes, or if *n* is not given or negative, until EOF
      or if the read call would block in non-blocking mode.

   .. method:: read1(n)

      Read and return up to *n* bytes with only one call on the raw stream.  If
      at least one byte is buffered, only buffered bytes are returned.
      Otherwise, one raw stream read call is made.


.. class:: BufferedWriter(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffer providing higher-level access to a writeable, sequential
   :class:`RawIOBase` object.  It inherits :class:`BufferedIOBase`.
   When writing to this object, data is normally held into an internal
   buffer.  The buffer will be written out to the underlying :class:`RawIOBase`
   object under various conditions, including:

   * when the buffer gets too small for all pending data;
   * when :meth:`flush()` is called;
   * when a :meth:`seek()` is requested (for :class:`BufferedRandom` objects);
   * when the :class:`BufferedWriter` object is closed or destroyed.

   The constructor creates a :class:`BufferedWriter` for the given writeable
   *raw* stream.  If the *buffer_size* is not given, it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A third argument, *max_buffer_size*, is supported, but unused and deprecated.

   :class:`BufferedWriter` provides or overrides these methods in addition to
   those from :class:`BufferedIOBase` and :class:`IOBase`:

   .. method:: flush()

      Force bytes held in the buffer into the raw stream.  A
      :exc:`BlockingIOError` should be raised if the raw stream blocks.

   .. method:: write(b)

      Write *b*, and return the number of bytes written.
      The object *b* should be an array of bytes, either
      :class:`bytes`, :class:`bytearray`, or :class:`memoryview`.
      When in non-blocking mode, a :exc:`BlockingIOError` is raised
      if the buffer needs to be written out but the raw stream blocks.


.. class:: BufferedRandom(raw, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffered interface to random access streams.  It inherits
   :class:`BufferedReader` and :class:`BufferedWriter`, and further supports
   :meth:`seek` and :meth:`tell` functionality.

   The constructor creates a reader and writer for a seekable raw stream, given
   in the first argument.  If the *buffer_size* is omitted it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A third argument, *max_buffer_size*, is supported, but unused and deprecated.

   :class:`BufferedRandom` is capable of anything :class:`BufferedReader` or
   :class:`BufferedWriter` can do.


.. class:: BufferedRWPair(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE)

   A buffered I/O object combining two unidirectional :class:`RawIOBase`
   objects -- one readable, the other writeable -- into a single bidirectional
   endpoint.  It inherits :class:`BufferedIOBase`.

   *reader* and *writer* are :class:`RawIOBase` objects that are readable and
   writeable respectively.  If the *buffer_size* is omitted it defaults to
   :data:`DEFAULT_BUFFER_SIZE`.

   A fourth argument, *max_buffer_size*, is supported, but unused and
   deprecated.

   :class:`BufferedRWPair` implements all of :class:`BufferedIOBase`\'s methods
   except for :meth:`~BufferedIOBase.detach`, which raises
   :exc:`UnsupportedOperation`.

   .. warning::

      :class:`BufferedRWPair` does not attempt to synchronize accesses to
      its underlying raw streams.  You should not pass it the same object
      as reader and writer; use :class:`BufferedRandom` instead.


Text I/O
--------

.. class:: TextIOBase

   Base class for text streams.  This class provides a unicode character
   and line based interface to stream I/O.  There is no :meth:`readinto`
   method because Python's :class:`unicode` strings are immutable.
   It inherits :class:`IOBase`.  There is no public constructor.

   :class:`TextIOBase` provides or overrides these data attributes and
   methods in addition to those from :class:`IOBase`:

   .. attribute:: encoding

      The name of the encoding used to decode the stream's bytes into
      strings, and to encode strings into bytes.

   .. attribute:: errors

      The error setting of the decoder or encoder.

   .. attribute:: newlines

      A string, a tuple of strings, or ``None``, indicating the newlines
      translated so far.  Depending on the implementation and the initial
      constructor flags, this may not be available.

   .. attribute:: buffer

      The underlying binary buffer (a :class:`BufferedIOBase` instance) that
      :class:`TextIOBase` deals with.  This is not part of the
      :class:`TextIOBase` API and may not exist on some implementations.

   .. method:: detach()

      Separate the underlying binary buffer from the :class:`TextIOBase` and
      return it.

      After the underlying buffer has been detached, the :class:`TextIOBase` is
      in an unusable state.

      Some :class:`TextIOBase` implementations, like :class:`~io.StringIO`, may not
      have the concept of an underlying buffer and calling this method will
      raise :exc:`UnsupportedOperation`.

      .. versionadded:: 2.7

   .. method:: read(n=-1)

      Read and return at most *n* characters from the stream as a single
      :class:`unicode`.  If *n* is negative or ``None``, reads until EOF.

   .. method:: readline(limit=-1)

      Read until newline or EOF and return a single ``unicode``.  If the
      stream is already at EOF, an empty string is returned.

      If *limit* is specified, at most *limit* characters will be read.

   .. method:: seek(offset[, whence])

      Change the stream position to the given *offset*.  Behaviour depends on
      the *whence* parameter.  The default value for *whence* is
      :data:`SEEK_SET`.

      * :data:`SEEK_SET` or ``0``: seek from the start of the stream
        (the default); *offset* must either be a number returned by
        :meth:`TextIOBase.tell`, or zero.  Any other *offset* value
        produces undefined behaviour.
      * :data:`SEEK_CUR` or ``1``: "seek" to the current position;
        *offset* must be zero, which is a no-operation (all other values
        are unsupported).
      * :data:`SEEK_END` or ``2``: seek to the end of the stream;
        *offset* must be zero (all other values are unsupported).

      Return the new absolute position as an opaque number.

      .. versionadded:: 2.7
         The ``SEEK_*`` constants.

   .. method:: tell()

      Return the current stream position as an opaque number.  The number
      does not usually represent a number of bytes in the underlying
      binary storage.

   .. method:: write(s)

      Write the :class:`unicode` string *s* to the stream and return the
      number of characters written.


.. class:: TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False)

   A buffered text stream over a :class:`BufferedIOBase` binary stream.
   It inherits :class:`TextIOBase`.

   *encoding* gives the name of the encoding that the stream will be decoded or
   encoded with.  It defaults to :func:`locale.getpreferredencoding`.

   *errors* is an optional string that specifies how encoding and decoding
   errors are to be handled.  Pass ``'strict'`` to raise a :exc:`ValueError`
   exception if there is an encoding error (the default of ``None`` has the same
   effect), or pass ``'ignore'`` to ignore errors.  (Note that ignoring encoding
   errors can lead to data loss.)  ``'replace'`` causes a replacement marker
   (such as ``'?'``) to be inserted where there is malformed data.  When
   writing, ``'xmlcharrefreplace'`` (replace with the appropriate XML character
   reference) or ``'backslashreplace'`` (replace with backslashed escape
   sequences) can be used.  Any other error handling name that has been
   registered with :func:`codecs.register_error` is also valid.

   .. index::
      single: universal newlines; io.TextIOWrapper class

   *newline* controls how line endings are handled.  It can be ``None``,
   ``''``, ``'\n'``, ``'\r'``, and ``'\r\n'``.  It works as follows:

   * On input, if *newline* is ``None``, :term:`universal newlines` mode is
     enabled.  Lines in the input can end in ``'\n'``, ``'\r'``, or ``'\r\n'``,
     and these are translated into ``'\n'`` before being returned to the
     caller.  If it is ``''``, universal newlines mode is enabled, but line
     endings are returned to the caller untranslated.  If it has any of the
     other legal values, input lines are only terminated by the given string,
     and the line ending is returned to the caller untranslated.

   * On output, if *newline* is ``None``, any ``'\n'`` characters written are
     translated to the system default line separator, :data:`os.linesep`.  If
     *newline* is ``''``, no translation takes place.  If *newline* is any of
     the other legal values, any ``'\n'`` characters written are translated to
     the given string.

   If *line_buffering* is ``True``, :meth:`flush` is implied when a call to
   write contains a newline character or a carriage return.

   :class:`TextIOWrapper` provides one attribute in addition to those of
   :class:`TextIOBase` and its parents:

   .. attribute:: line_buffering

      Whether line buffering is enabled.


.. class:: StringIO(initial_value=u'', newline=u'\\n')

   An in-memory stream for unicode text.  It inherits :class:`TextIOWrapper`.

   The initial value of the buffer can be set by providing *initial_value*.
   If newline translation is enabled, newlines will be encoded as if by
   :meth:`~TextIOBase.write`.  The stream is positioned at the start of
   the buffer.

   The *newline* argument works like that of :class:`TextIOWrapper`.
   The default is to consider only ``\n`` characters as ends of lines and
   to do no newline translation.  If *newline* is set to ``None``,
   newlines are written as ``\n`` on all platforms, but universal
   newline decoding is still performed when reading.

   :class:`~io.StringIO` provides this method in addition to those from
   :class:`TextIOWrapper` and its parents:

   .. method:: getvalue()

      Return a ``unicode`` containing the entire contents of the buffer at any
      time before the :class:`~io.StringIO` object's :meth:`close` method is
      called.  Newlines are decoded as if by :meth:`~TextIOBase.read`,
      although the stream position is not changed.

   Example usage::

      import io

      output = io.StringIO()
      output.write(u'First line.\n')
      output.write(u'Second line.\n')

      # Retrieve file contents -- this will be
      # u'First line.\nSecond line.\n'
      contents = output.getvalue()

      # Close object and discard memory buffer --
      # .getvalue() will now raise an exception.
      output.close()


.. index::
   single: universal newlines; io.IncrementalNewlineDecoder class

.. class:: IncrementalNewlineDecoder

   A helper codec that decodes newlines for :term:`universal newlines` mode.
   It inherits :class:`codecs.IncrementalDecoder`.


Advanced topics
---------------

Here we will discuss several advanced topics pertaining to the concrete
I/O implementations described above.

Performance
^^^^^^^^^^^

Binary I/O
""""""""""

By reading and writing only large chunks of data even when the user asks
for a single byte, buffered I/O is designed to hide any inefficiency in
calling and executing the operating system's unbuffered I/O routines.  The
gain will vary very much depending on the OS and the kind of I/O which is
performed (for example, on some contemporary OSes such as Linux, unbuffered
disk I/O can be as fast as buffered I/O).  The bottom line, however, is
that buffered I/O will offer you predictable performance regardless of the
platform and the backing device.  Therefore, it is most always preferable to
use buffered I/O rather than unbuffered I/O.

Text I/O
""""""""

Text I/O over a binary storage (such as a file) is significantly slower than
binary I/O over the same storage, because it implies conversions from
unicode to binary data using a character codec.  This can become noticeable
if you handle huge amounts of text data (for example very large log files).
Also, :meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both
quite slow due to the reconstruction algorithm used.

:class:`~io.StringIO`, however, is a native in-memory unicode container and will
exhibit similar speed to :class:`BytesIO`.

Multi-threading
^^^^^^^^^^^^^^^

:class:`FileIO` objects are thread-safe to the extent that the operating
system calls (such as ``read(2)`` under Unix) they are wrapping are thread-safe
too.

Binary buffered objects (instances of :class:`BufferedReader`,
:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
protect their internal structures using a lock; it is therefore safe to call
them from multiple threads at once.

:class:`TextIOWrapper` objects are not thread-safe.

Reentrancy
^^^^^^^^^^

Binary buffered objects (instances of :class:`BufferedReader`,
:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
are not reentrant.  While reentrant calls will not happen in normal situations,
they can arise if you are doing I/O in a :mod:`signal` handler.  If it is
attempted to enter a buffered object again while already being accessed
*from the same thread*, then a :exc:`RuntimeError` is raised.

The above implicitly extends to text files, since the :func:`open()`
function will wrap a buffered object inside a :class:`TextIOWrapper`.  This
includes standard streams and therefore affects the built-in function
:func:`print()` as well.

PK	%�\�rL�vv!html/_sources/library/ipc.rst.txtnu�[���
.. _ipc:

*****************************************
Interprocess Communication and Networking
*****************************************

The modules described in this chapter provide mechanisms for different processes
to communicate.

Some modules only work for two processes that are on the same machine, e.g.
:mod:`signal` and :mod:`subprocess`.  Other modules support networking protocols
that two or more processes can use to communicate across machines.

The list of modules described in this chapter is:


.. toctree::

   subprocess.rst
   socket.rst
   ssl.rst
   signal.rst
   popen2.rst
   asyncore.rst
   asynchat.rst
PK	%�\�����'html/_sources/library/itertools.rst.txtnu�[���
:mod:`itertools` --- Functions creating iterators for efficient looping
=======================================================================

.. module:: itertools
   :synopsis: Functions creating iterators for efficient looping.
.. moduleauthor:: Raymond Hettinger <python@rcn.com>
.. sectionauthor:: Raymond Hettinger <python@rcn.com>


.. testsetup::

   from itertools import *

.. versionadded:: 2.3

This module implements a number of :term:`iterator` building blocks inspired
by constructs from APL, Haskell, and SML.  Each has been recast in a form
suitable for Python.

The module standardizes a core set of fast, memory efficient tools that are
useful by themselves or in combination.  Together, they form an "iterator
algebra" making it possible to construct specialized tools succinctly and
efficiently in pure Python.

For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a
sequence ``f(0), f(1), ...``.  The same effect can be achieved in Python
by combining :func:`imap` and :func:`count` to form ``imap(f, count())``.

These tools and their built-in counterparts also work well with the high-speed
functions in the :mod:`operator` module.  For example, the multiplication
operator can be mapped across two vectors to form an efficient dot-product:
``sum(imap(operator.mul, vector1, vector2))``.


**Infinite Iterators:**

==================  =================       =================================================               =========================================
Iterator            Arguments               Results                                                         Example
==================  =================       =================================================               =========================================
:func:`count`       start, [step]           start, start+step, start+2*step, ...                            ``count(10) --> 10 11 12 13 14 ...``
:func:`cycle`       p                       p0, p1, ... plast, p0, p1, ...                                  ``cycle('ABCD') --> A B C D A B C D ...``
:func:`repeat`      elem [,n]               elem, elem, elem, ... endlessly or up to n times                ``repeat(10, 3) --> 10 10 10``
==================  =================       =================================================               =========================================

**Iterators terminating on the shortest input sequence:**

====================    ============================    =================================================   =============================================================
Iterator                Arguments                       Results                                             Example
====================    ============================    =================================================   =============================================================
:func:`chain`           p, q, ...                       p0, p1, ... plast, q0, q1, ...                      ``chain('ABC', 'DEF') --> A B C D E F``
:func:`compress`        data, selectors                 (d[0] if s[0]), (d[1] if s[1]), ...                 ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F``
:func:`dropwhile`       pred, seq                       seq[n], seq[n+1], starting when pred fails          ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1``
:func:`groupby`         iterable[, keyfunc]             sub-iterators grouped by value of keyfunc(v)
:func:`ifilter`         pred, seq                       elements of seq where pred(elem) is true            ``ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9``
:func:`ifilterfalse`    pred, seq                       elements of seq where pred(elem) is false           ``ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8``
:func:`islice`          seq, [start,] stop [, step]     elements from seq[start:stop:step]                  ``islice('ABCDEFG', 2, None) --> C D E F G``
:func:`imap`            func, p, q, ...                 func(p0, q0), func(p1, q1), ...                     ``imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000``
:func:`starmap`         func, seq                       func(\*seq[0]), func(\*seq[1]), ...                 ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000``
:func:`tee`             it, n                           it1, it2, ... itn  splits one iterator into n
:func:`takewhile`       pred, seq                       seq[0], seq[1], until pred fails                    ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4``
:func:`izip`            p, q, ...                       (p[0], q[0]), (p[1], q[1]), ...                     ``izip('ABCD', 'xy') --> Ax By``
:func:`izip_longest`    p, q, ...                       (p[0], q[0]), (p[1], q[1]), ...                     ``izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-``
====================    ============================    =================================================   =============================================================

**Combinatoric generators:**

==============================================   ====================       =============================================================
Iterator                                         Arguments                  Results
==============================================   ====================       =============================================================
:func:`product`                                  p, q, ... [repeat=1]       cartesian product, equivalent to a nested for-loop
:func:`permutations`                             p[, r]                     r-length tuples, all possible orderings, no repeated elements
:func:`combinations`                             p, r                       r-length tuples, in sorted order, no repeated elements
:func:`combinations_with_replacement`            p, r                       r-length tuples, in sorted order, with repeated elements
``product('ABCD', repeat=2)``                                               ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD``
``permutations('ABCD', 2)``                                                 ``AB AC AD BA BC BD CA CB CD DA DB DC``
``combinations('ABCD', 2)``                                                 ``AB AC AD BC BD CD``
``combinations_with_replacement('ABCD', 2)``                                ``AA AB AC AD BB BC BD CC CD DD``
==============================================   ====================       =============================================================


.. _itertools-functions:

Itertool functions
------------------

The following module functions all construct and return iterators. Some provide
streams of infinite length, so they should only be accessed by functions or
loops that truncate the stream.


.. function:: chain(*iterables)

   Make an iterator that returns elements from the first iterable until it is
   exhausted, then proceeds to the next iterable, until all of the iterables are
   exhausted.  Used for treating consecutive sequences as a single sequence.
   Roughly equivalent to::

      def chain(*iterables):
          # chain('ABC', 'DEF') --> A B C D E F
          for it in iterables:
              for element in it:
                  yield element


.. classmethod:: chain.from_iterable(iterable)

   Alternate constructor for :func:`chain`.  Gets chained inputs from a
   single iterable argument that is evaluated lazily.  Roughly equivalent to::

      def from_iterable(iterables):
          # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
          for it in iterables:
              for element in it:
                  yield element

   .. versionadded:: 2.6


.. function:: combinations(iterable, r)

   Return *r* length subsequences of elements from the input *iterable*.

   Combinations are emitted in lexicographic sort order.  So, if the
   input *iterable* is sorted, the combination tuples will be produced
   in sorted order.

   Elements are treated as unique based on their position, not on their
   value.  So if the input elements are unique, there will be no repeat
   values in each combination.

   Roughly equivalent to::

        def combinations(iterable, r):
            # combinations('ABCD', 2) --> AB AC AD BC BD CD
            # combinations(range(4), 3) --> 012 013 023 123
            pool = tuple(iterable)
            n = len(pool)
            if r > n:
                return
            indices = range(r)
            yield tuple(pool[i] for i in indices)
            while True:
                for i in reversed(range(r)):
                    if indices[i] != i + n - r:
                        break
                else:
                    return
                indices[i] += 1
                for j in range(i+1, r):
                    indices[j] = indices[j-1] + 1
                yield tuple(pool[i] for i in indices)

   The code for :func:`combinations` can be also expressed as a subsequence
   of :func:`permutations` after filtering entries where the elements are not
   in sorted order (according to their position in the input pool)::

        def combinations(iterable, r):
            pool = tuple(iterable)
            n = len(pool)
            for indices in permutations(range(n), r):
                if sorted(indices) == list(indices):
                    yield tuple(pool[i] for i in indices)

   The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n``
   or zero when ``r > n``.

   .. versionadded:: 2.6

.. function:: combinations_with_replacement(iterable, r)

   Return *r* length subsequences of elements from the input *iterable*
   allowing individual elements to be repeated more than once.

   Combinations are emitted in lexicographic sort order.  So, if the
   input *iterable* is sorted, the combination tuples will be produced
   in sorted order.

   Elements are treated as unique based on their position, not on their
   value.  So if the input elements are unique, the generated combinations
   will also be unique.

   Roughly equivalent to::

        def combinations_with_replacement(iterable, r):
            # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
            pool = tuple(iterable)
            n = len(pool)
            if not n and r:
                return
            indices = [0] * r
            yield tuple(pool[i] for i in indices)
            while True:
                for i in reversed(range(r)):
                    if indices[i] != n - 1:
                        break
                else:
                    return
                indices[i:] = [indices[i] + 1] * (r - i)
                yield tuple(pool[i] for i in indices)

   The code for :func:`combinations_with_replacement` can be also expressed as
   a subsequence of :func:`product` after filtering entries where the elements
   are not in sorted order (according to their position in the input pool)::

        def combinations_with_replacement(iterable, r):
            pool = tuple(iterable)
            n = len(pool)
            for indices in product(range(n), repeat=r):
                if sorted(indices) == list(indices):
                    yield tuple(pool[i] for i in indices)

   The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``.

   .. versionadded:: 2.7

.. function:: compress(data, selectors)

   Make an iterator that filters elements from *data* returning only those that
   have a corresponding element in *selectors* that evaluates to ``True``.
   Stops when either the *data* or *selectors* iterables has been exhausted.
   Roughly equivalent to::

       def compress(data, selectors):
           # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
           return (d for d, s in izip(data, selectors) if s)

   .. versionadded:: 2.7


.. function:: count(start=0, step=1)

   Make an iterator that returns evenly spaced values starting with *n*. Often
   used as an argument to :func:`imap` to generate consecutive data points.
   Also, used with :func:`izip` to add sequence numbers.  Equivalent to::

      def count(start=0, step=1):
          # count(10) --> 10 11 12 13 14 ...
          # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
          n = start
          while True:
              yield n
              n += step

   When counting with floating point numbers, better accuracy can sometimes be
   achieved by substituting multiplicative code such as: ``(start + step * i
   for i in count())``.

   .. versionchanged:: 2.7
      added *step* argument and allowed non-integer arguments.

.. function:: cycle(iterable)

   Make an iterator returning elements from the iterable and saving a copy of each.
   When the iterable is exhausted, return elements from the saved copy.  Repeats
   indefinitely.  Roughly equivalent to::

      def cycle(iterable):
          # cycle('ABCD') --> A B C D A B C D A B C D ...
          saved = []
          for element in iterable:
              yield element
              saved.append(element)
          while saved:
              for element in saved:
                    yield element

   Note, this member of the toolkit may require significant auxiliary storage
   (depending on the length of the iterable).


.. function:: dropwhile(predicate, iterable)

   Make an iterator that drops elements from the iterable as long as the predicate
   is true; afterwards, returns every element.  Note, the iterator does not produce
   *any* output until the predicate first becomes false, so it may have a lengthy
   start-up time.  Roughly equivalent to::

      def dropwhile(predicate, iterable):
          # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
          iterable = iter(iterable)
          for x in iterable:
              if not predicate(x):
                  yield x
                  break
          for x in iterable:
              yield x


.. function:: groupby(iterable[, key])

   Make an iterator that returns consecutive keys and groups from the *iterable*.
   The *key* is a function computing a key value for each element.  If not
   specified or is ``None``, *key* defaults to an identity function and returns
   the element unchanged.  Generally, the iterable needs to already be sorted on
   the same key function.

   The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix.  It
   generates a break or new group every time the value of the key function changes
   (which is why it is usually necessary to have sorted the data using the same key
   function).  That behavior differs from SQL's GROUP BY which aggregates common
   elements regardless of their input order.

   The returned group is itself an iterator that shares the underlying iterable
   with :func:`groupby`.  Because the source is shared, when the :func:`groupby`
   object is advanced, the previous group is no longer visible.  So, if that data
   is needed later, it should be stored as a list::

      groups = []
      uniquekeys = []
      data = sorted(data, key=keyfunc)
      for k, g in groupby(data, keyfunc):
          groups.append(list(g))      # Store group iterator as a list
          uniquekeys.append(k)

   :func:`groupby` is roughly equivalent to::

      class groupby(object):
          # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
          # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
          def __init__(self, iterable, key=None):
              if key is None:
                  key = lambda x: x
              self.keyfunc = key
              self.it = iter(iterable)
              self.tgtkey = self.currkey = self.currvalue = object()
          def __iter__(self):
              return self
          def next(self):
              while self.currkey == self.tgtkey:
                  self.currvalue = next(self.it)    # Exit on StopIteration
                  self.currkey = self.keyfunc(self.currvalue)
              self.tgtkey = self.currkey
              return (self.currkey, self._grouper(self.tgtkey))
          def _grouper(self, tgtkey):
              while self.currkey == tgtkey:
                  yield self.currvalue
                  self.currvalue = next(self.it)    # Exit on StopIteration
                  self.currkey = self.keyfunc(self.currvalue)

   .. versionadded:: 2.4


.. function:: ifilter(predicate, iterable)

   Make an iterator that filters elements from iterable returning only those for
   which the predicate is ``True``. If *predicate* is ``None``, return the items
   that are true. Roughly equivalent to::

      def ifilter(predicate, iterable):
          # ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
          if predicate is None:
              predicate = bool
          for x in iterable:
              if predicate(x):
                  yield x


.. function:: ifilterfalse(predicate, iterable)

   Make an iterator that filters elements from iterable returning only those for
   which the predicate is ``False``. If *predicate* is ``None``, return the items
   that are false. Roughly equivalent to::

      def ifilterfalse(predicate, iterable):
          # ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
          if predicate is None:
              predicate = bool
          for x in iterable:
              if not predicate(x):
                  yield x


.. function:: imap(function, *iterables)

   Make an iterator that computes the function using arguments from each of the
   iterables.  If *function* is set to ``None``, then :func:`imap` returns the
   arguments as a tuple.  Like :func:`map` but stops when the shortest iterable is
   exhausted instead of filling in ``None`` for shorter iterables.  The reason for
   the difference is that infinite iterator arguments are typically an error for
   :func:`map` (because the output is fully evaluated) but represent a common and
   useful way of supplying arguments to :func:`imap`. Roughly equivalent to::

      def imap(function, *iterables):
          # imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
          iterables = map(iter, iterables)
          while True:
              args = [next(it) for it in iterables]
              if function is None:
                  yield tuple(args)
              else:
                  yield function(*args)


.. function:: islice(iterable, stop)
              islice(iterable, start, stop[, step])

   Make an iterator that returns selected elements from the iterable. If *start* is
   non-zero, then elements from the iterable are skipped until start is reached.
   Afterward, elements are returned consecutively unless *step* is set higher than
   one which results in items being skipped.  If *stop* is ``None``, then iteration
   continues until the iterator is exhausted, if at all; otherwise, it stops at the
   specified position.  Unlike regular slicing, :func:`islice` does not support
   negative values for *start*, *stop*, or *step*.  Can be used to extract related
   fields from data where the internal structure has been flattened (for example, a
   multi-line report may list a name field on every third line).  Roughly equivalent to::

      def islice(iterable, *args):
          # islice('ABCDEFG', 2) --> A B
          # islice('ABCDEFG', 2, 4) --> C D
          # islice('ABCDEFG', 2, None) --> C D E F G
          # islice('ABCDEFG', 0, None, 2) --> A C E G
          s = slice(*args)
          start, stop, step = s.start or 0, s.stop or sys.maxint, s.step or 1
          it = iter(xrange(start, stop, step)))
          try:
              nexti = next(it)
          except StopIteration:
              # Consume *iterable* up to the *start* position.
              for i, element in izip(xrange(start), iterable):
                  pass
              return
          try:
              for i, element in enumerate(iterable):
                  if i == nexti:
                      yield element
                      nexti = next(it)
          except StopIteration:
              # Consume to *stop*.
              for i, element in izip(xrange(i + 1, stop), iterable):
                  pass

   If *start* is ``None``, then iteration starts at zero. If *step* is ``None``,
   then the step defaults to one.

   .. versionchanged:: 2.5
      accept ``None`` values for default *start* and *step*.


.. function:: izip(*iterables)

   Make an iterator that aggregates elements from each of the iterables. Like
   :func:`zip` except that it returns an iterator instead of a list.  Used for
   lock-step iteration over several iterables at a time.  Roughly equivalent to::

      def izip(*iterables):
          # izip('ABCD', 'xy') --> Ax By
          iterators = map(iter, iterables)
          while iterators:
              yield tuple(map(next, iterators))

   .. versionchanged:: 2.4
      When no iterables are specified, returns a zero length iterator instead of
      raising a :exc:`TypeError` exception.

   The left-to-right evaluation order of the iterables is guaranteed. This
   makes possible an idiom for clustering a data series into n-length groups
   using ``izip(*[iter(s)]*n)``.

   :func:`izip` should only be used with unequal length inputs when you don't
   care about trailing, unmatched values from the longer iterables.  If those
   values are important, use :func:`izip_longest` instead.


.. function:: izip_longest(*iterables[, fillvalue])

   Make an iterator that aggregates elements from each of the iterables. If the
   iterables are of uneven length, missing values are filled-in with *fillvalue*.
   Iteration continues until the longest iterable is exhausted.  Roughly equivalent to::

      class ZipExhausted(Exception):
          pass

      def izip_longest(*args, **kwds):
          # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
          fillvalue = kwds.get('fillvalue')
          counter = [len(args) - 1]
          def sentinel():
              if not counter[0]:
                  raise ZipExhausted
              counter[0] -= 1
              yield fillvalue
          fillers = repeat(fillvalue)
          iterators = [chain(it, sentinel(), fillers) for it in args]
          try:
              while iterators:
                  yield tuple(map(next, iterators))
          except ZipExhausted:
              pass

   If one of the iterables is potentially infinite, then the
   :func:`izip_longest` function should be wrapped with something that limits
   the number of calls (for example :func:`islice` or :func:`takewhile`).  If
   not specified, *fillvalue* defaults to ``None``.

   .. versionadded:: 2.6

.. function:: permutations(iterable[, r])

   Return successive *r* length permutations of elements in the *iterable*.

   If *r* is not specified or is ``None``, then *r* defaults to the length
   of the *iterable* and all possible full-length permutations
   are generated.

   Permutations are emitted in lexicographic sort order.  So, if the
   input *iterable* is sorted, the permutation tuples will be produced
   in sorted order.

   Elements are treated as unique based on their position, not on their
   value.  So if the input elements are unique, there will be no repeat
   values in each permutation.

   Roughly equivalent to::

        def permutations(iterable, r=None):
            # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
            # permutations(range(3)) --> 012 021 102 120 201 210
            pool = tuple(iterable)
            n = len(pool)
            r = n if r is None else r
            if r > n:
                return
            indices = range(n)
            cycles = range(n, n-r, -1)
            yield tuple(pool[i] for i in indices[:r])
            while n:
                for i in reversed(range(r)):
                    cycles[i] -= 1
                    if cycles[i] == 0:
                        indices[i:] = indices[i+1:] + indices[i:i+1]
                        cycles[i] = n - i
                    else:
                        j = cycles[i]
                        indices[i], indices[-j] = indices[-j], indices[i]
                        yield tuple(pool[i] for i in indices[:r])
                        break
                else:
                    return

   The code for :func:`permutations` can be also expressed as a subsequence of
   :func:`product`, filtered to exclude entries with repeated elements (those
   from the same position in the input pool)::

        def permutations(iterable, r=None):
            pool = tuple(iterable)
            n = len(pool)
            r = n if r is None else r
            for indices in product(range(n), repeat=r):
                if len(set(indices)) == r:
                    yield tuple(pool[i] for i in indices)

   The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n``
   or zero when ``r > n``.

   .. versionadded:: 2.6

.. function:: product(*iterables[, repeat])

   Cartesian product of input iterables.

   Roughly equivalent to nested for-loops in a generator expression. For example,
   ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.

   The nested loops cycle like an odometer with the rightmost element advancing
   on every iteration.  This pattern creates a lexicographic ordering so that if
   the input's iterables are sorted, the product tuples are emitted in sorted
   order.

   To compute the product of an iterable with itself, specify the number of
   repetitions with the optional *repeat* keyword argument.  For example,
   ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``.

   This function is roughly equivalent to the following code, except that the
   actual implementation does not build up intermediate results in memory::

       def product(*args, **kwds):
           # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
           # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
           pools = map(tuple, args) * kwds.get('repeat', 1)
           result = [[]]
           for pool in pools:
               result = [x+[y] for x in result for y in pool]
           for prod in result:
               yield tuple(prod)

   .. versionadded:: 2.6

.. function:: repeat(object[, times])

   Make an iterator that returns *object* over and over again. Runs indefinitely
   unless the *times* argument is specified. Used as argument to :func:`imap` for
   invariant function parameters.  Also used with :func:`izip` to create constant
   fields in a tuple record.  Roughly equivalent to::

      def repeat(object, times=None):
          # repeat(10, 3) --> 10 10 10
          if times is None:
              while True:
                  yield object
          else:
              for i in xrange(times):
                  yield object

   A common use for *repeat* is to supply a stream of constant values to *imap*
   or *zip*::

      >>> list(imap(pow, xrange(10), repeat(2)))
      [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

.. function:: starmap(function, iterable)

   Make an iterator that computes the function using arguments obtained from
   the iterable.  Used instead of :func:`imap` when argument parameters are already
   grouped in tuples from a single iterable (the data has been "pre-zipped").  The
   difference between :func:`imap` and :func:`starmap` parallels the distinction
   between ``function(a,b)`` and ``function(*c)``. Roughly equivalent to::

      def starmap(function, iterable):
          # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
          for args in iterable:
              yield function(*args)

   .. versionchanged:: 2.6
      Previously, :func:`starmap` required the function arguments to be tuples.
      Now, any iterable is allowed.

.. function:: takewhile(predicate, iterable)

   Make an iterator that returns elements from the iterable as long as the
   predicate is true.  Roughly equivalent to::

      def takewhile(predicate, iterable):
          # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
          for x in iterable:
              if predicate(x):
                  yield x
              else:
                  break


.. function:: tee(iterable[, n=2])

   Return *n* independent iterators from a single iterable.  Roughly equivalent to::

        def tee(iterable, n=2):
            it = iter(iterable)
            deques = [collections.deque() for i in range(n)]
            def gen(mydeque):
                while True:
                    if not mydeque:             # when the local deque is empty
                        newval = next(it)       # fetch a new value and
                        for d in deques:        # load it to all the deques
                            d.append(newval)
                    yield mydeque.popleft()
            return tuple(gen(d) for d in deques)

   Once :func:`tee` has made a split, the original *iterable* should not be
   used anywhere else; otherwise, the *iterable* could get advanced without
   the tee objects being informed.

   This itertool may require significant auxiliary storage (depending on how
   much temporary data needs to be stored). In general, if one iterator uses
   most or all of the data before another iterator starts, it is faster to use
   :func:`list` instead of :func:`tee`.

   .. versionadded:: 2.4


.. _itertools-recipes:

Recipes
-------

This section shows recipes for creating an extended toolset using the existing
itertools as building blocks.

The extended tools offer the same high performance as the underlying toolset.
The superior memory performance is kept by processing elements one at a time
rather than bringing the whole iterable into memory all at once. Code volume is
kept small by linking the tools together in a functional style which helps
eliminate temporary variables.  High speed is retained by preferring
"vectorized" building blocks over the use of for-loops and :term:`generator`\s
which incur interpreter overhead.

.. testcode::

   def take(n, iterable):
       "Return first n items of the iterable as a list"
       return list(islice(iterable, n))

   def tabulate(function, start=0):
       "Return function(0), function(1), ..."
       return imap(function, count(start))

   def consume(iterator, n=None):
       "Advance the iterator n-steps ahead. If n is None, consume entirely."
       # Use functions that consume iterators at C speed.
       if n is None:
           # feed the entire iterator into a zero-length deque
           collections.deque(iterator, maxlen=0)
       else:
           # advance to the empty slice starting at position n
           next(islice(iterator, n, n), None)

   def nth(iterable, n, default=None):
       "Returns the nth item or a default value"
       return next(islice(iterable, n, None), default)

   def all_equal(iterable):
       "Returns True if all the elements are equal to each other"
       g = groupby(iterable)
       return next(g, True) and not next(g, False)

   def quantify(iterable, pred=bool):
       "Count how many times the predicate is true"
       return sum(imap(pred, iterable))

   def padnone(iterable):
       """Returns the sequence elements and then returns None indefinitely.

       Useful for emulating the behavior of the built-in map() function.
       """
       return chain(iterable, repeat(None))

   def ncycles(iterable, n):
       "Returns the sequence elements n times"
       return chain.from_iterable(repeat(tuple(iterable), n))

   def dotproduct(vec1, vec2):
       return sum(imap(operator.mul, vec1, vec2))

   def flatten(listOfLists):
       "Flatten one level of nesting"
       return chain.from_iterable(listOfLists)

   def repeatfunc(func, times=None, *args):
       """Repeat calls to func with specified arguments.

       Example:  repeatfunc(random.random)
       """
       if times is None:
           return starmap(func, repeat(args))
       return starmap(func, repeat(args, times))

   def pairwise(iterable):
       "s -> (s0,s1), (s1,s2), (s2, s3), ..."
       a, b = tee(iterable)
       next(b, None)
       return izip(a, b)

   def grouper(iterable, n, fillvalue=None):
       "Collect data into fixed-length chunks or blocks"
       # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
       args = [iter(iterable)] * n
       return izip_longest(fillvalue=fillvalue, *args)

   def roundrobin(*iterables):
       "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
       # Recipe credited to George Sakkis
       pending = len(iterables)
       nexts = cycle(iter(it).next for it in iterables)
       while pending:
           try:
               for next in nexts:
                   yield next()
           except StopIteration:
               pending -= 1
               nexts = cycle(islice(nexts, pending))

   def powerset(iterable):
       "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
       s = list(iterable)
       return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

   def unique_everseen(iterable, key=None):
       "List unique elements, preserving order. Remember all elements ever seen."
       # unique_everseen('AAAABBBCCDAABBB') --> A B C D
       # unique_everseen('ABBCcAD', str.lower) --> A B C D
       seen = set()
       seen_add = seen.add
       if key is None:
           for element in ifilterfalse(seen.__contains__, iterable):
               seen_add(element)
               yield element
       else:
           for element in iterable:
               k = key(element)
               if k not in seen:
                   seen_add(k)
                   yield element

   def unique_justseen(iterable, key=None):
       "List unique elements, preserving order. Remember only the element just seen."
       # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B
       # unique_justseen('ABBCcAD', str.lower) --> A B C A D
       return imap(next, imap(itemgetter(1), groupby(iterable, key)))

   def iter_except(func, exception, first=None):
       """ Call a function repeatedly until an exception is raised.

       Converts a call-until-exception interface to an iterator interface.
       Like __builtin__.iter(func, sentinel) but uses an exception instead
       of a sentinel to end the loop.

       Examples:
           bsddbiter = iter_except(db.next, bsddb.error, db.first)
           heapiter = iter_except(functools.partial(heappop, h), IndexError)
           dictiter = iter_except(d.popitem, KeyError)
           dequeiter = iter_except(d.popleft, IndexError)
           queueiter = iter_except(q.get_nowait, Queue.Empty)
           setiter = iter_except(s.pop, KeyError)

       """
       try:
           if first is not None:
               yield first()
           while 1:
               yield func()
       except exception:
           pass

   def random_product(*args, **kwds):
       "Random selection from itertools.product(*args, **kwds)"
       pools = map(tuple, args) * kwds.get('repeat', 1)
       return tuple(random.choice(pool) for pool in pools)

   def random_permutation(iterable, r=None):
       "Random selection from itertools.permutations(iterable, r)"
       pool = tuple(iterable)
       r = len(pool) if r is None else r
       return tuple(random.sample(pool, r))

   def random_combination(iterable, r):
       "Random selection from itertools.combinations(iterable, r)"
       pool = tuple(iterable)
       n = len(pool)
       indices = sorted(random.sample(xrange(n), r))
       return tuple(pool[i] for i in indices)

   def random_combination_with_replacement(iterable, r):
       "Random selection from itertools.combinations_with_replacement(iterable, r)"
       pool = tuple(iterable)
       n = len(pool)
       indices = sorted(random.randrange(n) for i in xrange(r))
       return tuple(pool[i] for i in indices)

   def tee_lookahead(t, i):
       """Inspect the i-th upcomping value from a tee object
          while leaving the tee object at its current position.

          Raise an IndexError if the underlying iterator doesn't
          have enough values.

       """
       for value in islice(t.__copy__(), i, None):
           return value
       raise IndexError(i)

Note, many of the above recipes can be optimized by replacing global lookups
with local variables defined as default values.  For example, the
*dotproduct* recipe can be written as::

   def dotproduct(vec1, vec2, sum=sum, imap=imap, mul=operator.mul):
       return sum(imap(mul, vec1, vec2))
PK	%�\gv�"html/_sources/library/jpeg.rst.txtnu�[���
:mod:`jpeg` --- Read and write JPEG files
=========================================

.. module:: jpeg
   :platform: IRIX
   :synopsis: Read and write image files in compressed JPEG format.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`jpeg` module has been removed in Python 3.



.. index:: single: Independent JPEG Group

The module :mod:`jpeg` provides access to the jpeg compressor and decompressor
written by the Independent JPEG Group (IJG). JPEG is a standard for compressing
pictures; it is defined in ISO 10918.  For details on JPEG or the Independent
JPEG Group software refer to the JPEG standard or the documentation provided
with the software.

.. index::
   single: Python Imaging Library
   single: PIL (the Python Imaging Library)
   single: Lundh, Fredrik

A portable interface to JPEG image files is available with the Python Imaging
Library (PIL) by Fredrik Lundh.  Information on PIL is available at
http://www.pythonware.com/products/pil/.

The :mod:`jpeg` module defines an exception and some functions.


.. exception:: error

   Exception raised by :func:`compress` and :func:`decompress` in case of errors.


.. function:: compress(data, w, h, b)

   .. index:: single: JFIF

   Treat data as a pixmap of width *w* and height *h*, with *b* bytes per pixel.
   The data is in SGI GL order, so the first pixel is in the lower-left corner.
   This means that :func:`gl.lrectread` return data can immediately be passed to
   :func:`compress`. Currently only 1 byte and 4 byte pixels are allowed, the
   former being treated as greyscale and the latter as RGB color. :func:`compress`
   returns a string that contains the compressed picture, in JFIF format.


.. function:: decompress(data)

   .. index:: single: JFIF

   Data is a string containing a picture in JFIF format. It returns a tuple
   ``(data, width, height, bytesperpixel)``.  Again, the data is suitable to pass
   to :func:`gl.lrectwrite`.


.. function:: setoption(name, value)

   Set various options.  Subsequent :func:`compress` and :func:`decompress` calls
   will use these options.  The following options are available:

   +-----------------+---------------------------------------------+
   | Option          | Effect                                      |
   +=================+=============================================+
   | ``'forcegray'`` | Force output to be grayscale, even if input |
   |                 | is RGB.                                     |
   +-----------------+---------------------------------------------+
   | ``'quality'``   | Set the quality of the compressed image to  |
   |                 | a value between ``0`` and ``100`` (default  |
   |                 | is ``75``).  This only affects compression. |
   +-----------------+---------------------------------------------+
   | ``'optimize'``  | Perform Huffman table optimization.  Takes  |
   |                 | longer, but results in smaller compressed   |
   |                 | image.  This only affects compression.      |
   +-----------------+---------------------------------------------+
   | ``'smooth'``    | Perform inter-block smoothing on            |
   |                 | uncompressed image.  Only useful for low-   |
   |                 | quality images.  This only affects          |
   |                 | decompression.                              |
   +-----------------+---------------------------------------------+


.. seealso::

   JPEG Still Image Data Compression Standard
      The canonical reference for the JPEG image format, by Pennebaker and Mitchell.

   `Information Technology - Digital Compression and Coding of Continuous-tone Still Images - Requirements and Guidelines <http://www.w3.org/Graphics/JPEG/itu-t81.pdf>`_
      The ISO standard for JPEG is also published as ITU T.81.  This is available
      online in PDF form.

PK	%�\}��;�c�c"html/_sources/library/json.rst.txtnu�[���:mod:`json` --- JSON encoder and decoder
========================================

.. module:: json
   :synopsis: Encode and decode the JSON format.
.. moduleauthor:: Bob Ippolito <bob@redivi.com>
.. sectionauthor:: Bob Ippolito <bob@redivi.com>
.. versionadded:: 2.6

`JSON (JavaScript Object Notation) <http://json.org>`_, specified by
:rfc:`7159` (which obsoletes :rfc:`4627`) and by
`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_,
is a lightweight data interchange format inspired by
`JavaScript <https://en.wikipedia.org/wiki/JavaScript>`_ object literal syntax
(although it is not a strict subset of JavaScript [#rfc-errata]_ ).

:mod:`json` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules.

Encoding basic Python object hierarchies::

    >>> import json
    >>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
    '["foo", {"bar": ["baz", null, 1.0, 2]}]'
    >>> print json.dumps("\"foo\bar")
    "\"foo\bar"
    >>> print json.dumps(u'\u1234')
    "\u1234"
    >>> print json.dumps('\\')
    "\\"
    >>> print json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
    {"a": 0, "b": 0, "c": 0}
    >>> from StringIO import StringIO
    >>> io = StringIO()
    >>> json.dump(['streaming API'], io)
    >>> io.getvalue()
    '["streaming API"]'

Compact encoding::

    >>> import json
    >>> json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))
    '[1,2,3,{"4":5,"6":7}]'

Pretty printing::

    >>> import json
    >>> print json.dumps({'4': 5, '6': 7}, sort_keys=True,
    ...                  indent=4, separators=(',', ': '))
    {
        "4": 5,
        "6": 7
    }

Decoding JSON::

    >>> import json
    >>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
    [u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
    >>> json.loads('"\\"foo\\bar"')
    u'"foo\x08ar'
    >>> from StringIO import StringIO
    >>> io = StringIO('["streaming API"]')
    >>> json.load(io)
    [u'streaming API']

Specializing JSON object decoding::

    >>> import json
    >>> def as_complex(dct):
    ...     if '__complex__' in dct:
    ...         return complex(dct['real'], dct['imag'])
    ...     return dct
    ...
    >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
    ...     object_hook=as_complex)
    (1+2j)
    >>> import decimal
    >>> json.loads('1.1', parse_float=decimal.Decimal)
    Decimal('1.1')

Extending :class:`JSONEncoder`::

    >>> import json
    >>> class ComplexEncoder(json.JSONEncoder):
    ...     def default(self, obj):
    ...         if isinstance(obj, complex):
    ...             return [obj.real, obj.imag]
    ...         # Let the base class default method raise the TypeError
    ...         return json.JSONEncoder.default(self, obj)
    ...
    >>> json.dumps(2 + 1j, cls=ComplexEncoder)
    '[2.0, 1.0]'
    >>> ComplexEncoder().encode(2 + 1j)
    '[2.0, 1.0]'
    >>> list(ComplexEncoder().iterencode(2 + 1j))
    ['[', '2.0', ', ', '1.0', ']']


.. highlight:: none

Using :mod:`json.tool` from the shell to validate and pretty-print::

    $ echo '{"json":"obj"}' | python -m json.tool
    {
        "json": "obj"
    }
    $ echo '{1.2:3.4}' | python -mjson.tool
    Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

.. highlight:: python

.. note::

   JSON is a subset of `YAML <http://yaml.org/>`_ 1.2.  The JSON produced by
   this module's default settings (in particular, the default *separators*
   value) is also a subset of YAML 1.0 and 1.1.  This module can thus also be
   used as a YAML serializer.


Basic Usage
-----------

.. function:: dump(obj, fp, skipkeys=False, ensure_ascii=True, \
                   check_circular=True, allow_nan=True, cls=None, \
                   indent=None, separators=None, encoding="utf-8", \
                   default=None, sort_keys=False, **kw)

   Serialize *obj* as a JSON formatted stream to *fp* (a ``.write()``-supporting
   :term:`file-like object`) using this :ref:`conversion table
   <py-to-json-table>`.

   If *skipkeys* is true (default: ``False``), then dict keys that are not
   of a basic type (:class:`str`, :class:`unicode`, :class:`int`, :class:`long`,
   :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
   :exc:`TypeError`.

   If *ensure_ascii* is true (the default), all non-ASCII characters in the
   output are escaped with ``\uXXXX`` sequences, and the result is a
   :class:`str` instance consisting of ASCII characters only.  If
   *ensure_ascii* is false, some chunks written to *fp* may be
   :class:`unicode` instances.  This usually happens because the input contains
   unicode strings or the *encoding* parameter is used.  Unless ``fp.write()``
   explicitly understands :class:`unicode` (as in :func:`codecs.getwriter`)
   this is likely to cause an error.

   If *check_circular* is false (default: ``True``), then the circular
   reference check for container types will be skipped and a circular reference
   will result in an :exc:`OverflowError` (or worse).

   If *allow_nan* is false (default: ``True``), then it will be a
   :exc:`ValueError` to serialize out of range :class:`float` values (``nan``,
   ``inf``, ``-inf``) in strict compliance of the JSON specification.
   If *allow_nan* is true, their JavaScript equivalents (``NaN``,
   ``Infinity``, ``-Infinity``) will be used.

   If *indent* is a non-negative integer, then JSON array elements and object
   members will be pretty-printed with that indent level.  An indent level of 0,
   or negative, will only insert newlines.  ``None`` (the default) selects the
   most compact representation.

   .. note::

      Since the default item separator is ``', '``,  the output might include
      trailing whitespace when *indent* is specified.  You can use
      ``separators=(',', ': ')`` to avoid this.

   If specified, *separators* should be an ``(item_separator, key_separator)``
   tuple.  By default, ``(', ', ': ')`` are used.  To get the most compact JSON
   representation, you should specify ``(',', ':')`` to eliminate whitespace.

   *encoding* is the character encoding for str instances, default is UTF-8.

   If specified, *default* should be a function that gets called for objects that
   can't otherwise be serialized.  It should return a JSON encodable version of
   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
   is raised.

   If *sort_keys* is true (default: ``False``), then the output of
   dictionaries will be sorted by key.

   To use a custom :class:`JSONEncoder` subclass (e.g. one that overrides the
   :meth:`default` method to serialize additional types), specify it with the
   *cls* kwarg; otherwise :class:`JSONEncoder` is used.

   .. note::

      Unlike :mod:`pickle` and :mod:`marshal`, JSON is not a framed protocol so
      trying to serialize more objects with repeated calls to :func:`dump` and
      the same *fp* will result in an invalid JSON file.

.. function:: dumps(obj, skipkeys=False, ensure_ascii=True, \
                    check_circular=True, allow_nan=True, cls=None, \
                    indent=None, separators=None, encoding="utf-8", \
                    default=None, sort_keys=False, **kw)

   Serialize *obj* to a JSON formatted :class:`str` using this :ref:`conversion
   table <py-to-json-table>`.  If *ensure_ascii* is false, the result may
   contain non-ASCII characters and the return value may be a :class:`unicode`
   instance.

   The arguments have the same meaning as in :func:`dump`.

   .. note::

      Keys in key/value pairs of JSON are always of the type :class:`str`. When
      a dictionary is converted into JSON, all the keys of the dictionary are
      coerced to strings. As a result of this, if a dictionary is converted
      into JSON and then back into a dictionary, the dictionary may not equal
      the original one. That is, ``loads(dumps(x)) != x`` if x has non-string
      keys.

.. function:: load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

   Deserialize *fp* (a ``.read()``-supporting :term:`file-like object`
   containing a JSON document) to a Python object using this :ref:`conversion
   table <json-to-py-table>`.

   If the contents of *fp* are encoded with an ASCII based encoding other than
   UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be specified.
   Encodings that are not ASCII based (such as UCS-2) are not allowed, and
   should be wrapped with ``codecs.getreader(encoding)(fp)``, or simply decoded
   to a :class:`unicode` object and passed to :func:`loads`.

   *object_hook* is an optional function that will be called with the result of
   any object literal decoded (a :class:`dict`).  The return value of
   *object_hook* will be used instead of the :class:`dict`.  This feature can be used
   to implement custom decoders (e.g. `JSON-RPC <http://www.jsonrpc.org>`_
   class hinting).

   *object_pairs_hook* is an optional function that will be called with the
   result of any object literal decoded with an ordered list of pairs.  The
   return value of *object_pairs_hook* will be used instead of the
   :class:`dict`.  This feature can be used to implement custom decoders that
   rely on the order that the key and value pairs are decoded (for example,
   :func:`collections.OrderedDict` will remember the order of insertion). If
   *object_hook* is also defined, the *object_pairs_hook* takes priority.

   .. versionchanged:: 2.7
      Added support for *object_pairs_hook*.

   *parse_float*, if specified, will be called with the string of every JSON
   float to be decoded.  By default, this is equivalent to ``float(num_str)``.
   This can be used to use another datatype or parser for JSON floats
   (e.g. :class:`decimal.Decimal`).

   *parse_int*, if specified, will be called with the string of every JSON int
   to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
   be used to use another datatype or parser for JSON integers
   (e.g. :class:`float`).

   *parse_constant*, if specified, will be called with one of the following
   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
   This can be used to raise an exception if invalid JSON numbers
   are encountered.

   .. versionchanged:: 2.7
      *parse_constant* doesn't get called on 'null', 'true', 'false' anymore.

   To use a custom :class:`JSONDecoder` subclass, specify it with the ``cls``
   kwarg; otherwise :class:`JSONDecoder` is used.  Additional keyword arguments
   will be passed to the constructor of the class.


.. function:: loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

   Deserialize *s* (a :class:`str` or :class:`unicode` instance containing a JSON
   document) to a Python object using this :ref:`conversion table
   <json-to-py-table>`.

   If *s* is a :class:`str` instance and is encoded with an ASCII based encoding
   other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
   specified.  Encodings that are not ASCII based (such as UCS-2) are not
   allowed and should be decoded to :class:`unicode` first.

   The other arguments have the same meaning as in :func:`load`.


Encoders and Decoders
---------------------

.. class:: JSONDecoder([encoding[, object_hook[, parse_float[, parse_int[, parse_constant[, strict[, object_pairs_hook]]]]]]])

   Simple JSON decoder.

   Performs the following translations in decoding by default:

   .. _json-to-py-table:

   +---------------+-------------------+
   | JSON          | Python            |
   +===============+===================+
   | object        | dict              |
   +---------------+-------------------+
   | array         | list              |
   +---------------+-------------------+
   | string        | unicode           |
   +---------------+-------------------+
   | number (int)  | int, long         |
   +---------------+-------------------+
   | number (real) | float             |
   +---------------+-------------------+
   | true          | True              |
   +---------------+-------------------+
   | false         | False             |
   +---------------+-------------------+
   | null          | None              |
   +---------------+-------------------+

   It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their
   corresponding ``float`` values, which is outside the JSON spec.

   *encoding* determines the encoding used to interpret any :class:`str` objects
   decoded by this instance (UTF-8 by default).  It has no effect when decoding
   :class:`unicode` objects.

   Note that currently only encodings that are a superset of ASCII work, strings
   of other encodings should be passed in as :class:`unicode`.

   *object_hook*, if specified, will be called with the result of every JSON
   object decoded and its return value will be used in place of the given
   :class:`dict`.  This can be used to provide custom deserializations (e.g. to
   support JSON-RPC class hinting).

   *object_pairs_hook*, if specified will be called with the result of every
   JSON object decoded with an ordered list of pairs.  The return value of
   *object_pairs_hook* will be used instead of the :class:`dict`.  This
   feature can be used to implement custom decoders that rely on the order
   that the key and value pairs are decoded (for example,
   :func:`collections.OrderedDict` will remember the order of insertion). If
   *object_hook* is also defined, the *object_pairs_hook* takes priority.

   .. versionchanged:: 2.7
      Added support for *object_pairs_hook*.

   *parse_float*, if specified, will be called with the string of every JSON
   float to be decoded.  By default, this is equivalent to ``float(num_str)``.
   This can be used to use another datatype or parser for JSON floats
   (e.g. :class:`decimal.Decimal`).

   *parse_int*, if specified, will be called with the string of every JSON int
   to be decoded.  By default, this is equivalent to ``int(num_str)``.  This can
   be used to use another datatype or parser for JSON integers
   (e.g. :class:`float`).

   *parse_constant*, if specified, will be called with one of the following
   strings: ``'-Infinity'``, ``'Infinity'``, ``'NaN'``.
   This can be used to raise an exception if invalid JSON numbers
   are encountered.

   If *strict* is false (``True`` is the default), then control characters
   will be allowed inside strings.  Control characters in this context are
   those with character codes in the 0--31 range, including ``'\t'`` (tab),
   ``'\n'``, ``'\r'`` and ``'\0'``.

   If the data being deserialized is not a valid JSON document, a
   :exc:`ValueError` will be raised.

   .. method:: decode(s)

      Return the Python representation of *s* (a :class:`str` or
      :class:`unicode` instance containing a JSON document).

   .. method:: raw_decode(s)

      Decode a JSON document from *s* (a :class:`str` or :class:`unicode`
      beginning with a JSON document) and return a 2-tuple of the Python
      representation and the index in *s* where the document ended.

      This can be used to decode a JSON document from a string that may have
      extraneous data at the end.


.. class:: JSONEncoder([skipkeys[, ensure_ascii[, check_circular[, allow_nan[, sort_keys[, indent[, separators[, encoding[, default]]]]]]]]])

   Extensible JSON encoder for Python data structures.

   Supports the following objects and types by default:

   .. _py-to-json-table:

   +-------------------+---------------+
   | Python            | JSON          |
   +===================+===============+
   | dict              | object        |
   +-------------------+---------------+
   | list, tuple       | array         |
   +-------------------+---------------+
   | str, unicode      | string        |
   +-------------------+---------------+
   | int, long, float  | number        |
   +-------------------+---------------+
   | True              | true          |
   +-------------------+---------------+
   | False             | false         |
   +-------------------+---------------+
   | None              | null          |
   +-------------------+---------------+

   To extend this to recognize other objects, subclass and implement a
   :meth:`default` method with another method that returns a serializable object
   for ``o`` if possible, otherwise it should call the superclass implementation
   (to raise :exc:`TypeError`).

   If *skipkeys* is false (the default), then it is a :exc:`TypeError` to
   attempt encoding of keys that are not str, int, long, float or ``None``.  If
   *skipkeys* is true, such items are simply skipped.

   If *ensure_ascii* is true (the default), all non-ASCII characters in the
   output are escaped with ``\uXXXX`` sequences, and the results are
   :class:`str` instances consisting of ASCII characters only. If
   *ensure_ascii* is false, a result may be a :class:`unicode`
   instance. This usually happens if the input contains unicode strings or the
   *encoding* parameter is used.

   If *check_circular* is true (the default), then lists, dicts, and custom
   encoded objects will be checked for circular references during encoding to
   prevent an infinite recursion (which would cause an :exc:`OverflowError`).
   Otherwise, no such check takes place.

   If *allow_nan* is true (the default), then ``NaN``, ``Infinity``, and
   ``-Infinity`` will be encoded as such.  This behavior is not JSON
   specification compliant, but is consistent with most JavaScript based
   encoders and decoders.  Otherwise, it will be a :exc:`ValueError` to encode
   such floats.

   If *sort_keys* is true (default: ``False``), then the output of dictionaries
   will be sorted by key; this is useful for regression tests to ensure that
   JSON serializations can be compared on a day-to-day basis.

   If *indent* is a non-negative integer (it is ``None`` by default), then JSON
   array elements and object members will be pretty-printed with that indent
   level.  An indent level of 0 will only insert newlines.  ``None`` is the most
   compact representation.

   .. note::

      Since the default item separator is ``', '``,  the output might include
      trailing whitespace when *indent* is specified.  You can use
      ``separators=(',', ': ')`` to avoid this.

   If specified, *separators* should be an ``(item_separator, key_separator)``
   tuple.  By default, ``(', ', ': ')`` are used.  To get the most compact JSON
   representation, you should specify ``(',', ':')`` to eliminate whitespace.

   If specified, *default* should be a function that gets called for objects that
   can't otherwise be serialized.  It should return a JSON encodable version of
   the object or raise a :exc:`TypeError`.  If not specified, :exc:`TypeError`
   is raised.

   If *encoding* is not ``None``, then all input strings will be transformed
   into unicode using that encoding prior to JSON-encoding.  The default is
   UTF-8.


   .. method:: default(o)

      Implement this method in a subclass such that it returns a serializable
      object for *o*, or calls the base implementation (to raise a
      :exc:`TypeError`).

      For example, to support arbitrary iterators, you could implement default
      like this::

         def default(self, o):
            try:
                iterable = iter(o)
            except TypeError:
                pass
            else:
                return list(iterable)
            # Let the base class default method raise the TypeError
            return JSONEncoder.default(self, o)


   .. method:: encode(o)

      Return a JSON string representation of a Python data structure, *o*.  For
      example::

        >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
        '{"foo": ["bar", "baz"]}'


   .. method:: iterencode(o)

      Encode the given object, *o*, and yield each string representation as
      available.  For example::

            for chunk in JSONEncoder().iterencode(bigobject):
                mysocket.write(chunk)


Standard Compliance and Interoperability
----------------------------------------

The JSON format is specified by :rfc:`7159` and by
`ECMA-404 <http://www.ecma-international.org/publications/standards/Ecma-404.htm>`_.
This section details this module's level of compliance with the RFC.
For simplicity, :class:`JSONEncoder` and :class:`JSONDecoder` subclasses, and
parameters other than those explicitly mentioned, are not considered.

This module does not comply with the RFC in a strict fashion, implementing some
extensions that are valid JavaScript but not valid JSON.  In particular:

- Infinite and NaN number values are accepted and output;
- Repeated names within an object are accepted, and only the value of the last
  name-value pair is used.

Since the RFC permits RFC-compliant parsers to accept input texts that are not
RFC-compliant, this module's deserializer is technically RFC-compliant under
default settings.

Character Encodings
^^^^^^^^^^^^^^^^^^^

The RFC requires that JSON be represented using either UTF-8, UTF-16, or
UTF-32, with UTF-8 being the recommended default for maximum interoperability.
Accordingly, this module uses UTF-8 as the default for its *encoding* parameter.

This module's deserializer only directly works with ASCII-compatible encodings;
UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
workarounds described in the documentation for the deserializer's *encoding*
parameter.

As permitted, though not required, by the RFC, this module's serializer sets
*ensure_ascii=True* by default, thus escaping the output so that the resulting
strings only contain ASCII characters.

The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
and this module's serializer does not add a BOM to its output.
The RFC permits, but does not require, JSON deserializers to ignore an initial
BOM in their input.  This module's deserializer raises a :exc:`ValueError`
when an initial BOM is present.

The RFC does not explicitly forbid JSON strings which contain byte sequences
that don't correspond to valid Unicode characters (e.g. unpaired UTF-16
surrogates), but it does note that they may cause interoperability problems.
By default, this module accepts and outputs (when present in the original
:class:`str`) code points for such sequences.


Infinite and NaN Number Values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The RFC does not permit the representation of infinite or NaN number values.
Despite that, by default, this module accepts and outputs ``Infinity``,
``-Infinity``, and ``NaN`` as if they were valid JSON number literal values::

   >>> # Neither of these calls raises an exception, but the results are not valid JSON
   >>> json.dumps(float('-inf'))
   '-Infinity'
   >>> json.dumps(float('nan'))
   'NaN'
   >>> # Same when deserializing
   >>> json.loads('-Infinity')
   -inf
   >>> json.loads('NaN')
   nan

In the serializer, the *allow_nan* parameter can be used to alter this
behavior.  In the deserializer, the *parse_constant* parameter can be used to
alter this behavior.


Repeated Names Within an Object
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The RFC specifies that the names within a JSON object should be unique, but
does not mandate how repeated names in JSON objects should be handled.  By
default, this module does not raise an exception; instead, it ignores all but
the last name-value pair for a given name::

   >>> weird_json = '{"x": 1, "x": 2, "x": 3}'
   >>> json.loads(weird_json)
   {u'x': 3}

The *object_pairs_hook* parameter can be used to alter this behavior.


Top-level Non-Object, Non-Array Values
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The old version of JSON specified by the obsolete :rfc:`4627` required that
the top-level value of a JSON text must be either a JSON object or array
(Python :class:`dict` or :class:`list`), and could not be a JSON null,
boolean, number, or string value.  :rfc:`7159` removed that restriction, and
this module does not and has never implemented that restriction in either its
serializer or its deserializer.

Regardless, for maximum interoperability, you may wish to voluntarily adhere
to the restriction yourself.


Implementation Limitations
^^^^^^^^^^^^^^^^^^^^^^^^^^

Some JSON deserializer implementations may set limits on:

* the size of accepted JSON texts
* the maximum level of nesting of JSON objects and arrays
* the range and precision of JSON numbers
* the content and maximum length of JSON strings

This module does not impose any such limits beyond those of the relevant
Python datatypes themselves or the Python interpreter itself.

When serializing to JSON, beware any such limitations in applications that may
consume your JSON.  In particular, it is common for JSON numbers to be
deserialized into IEEE 754 double precision numbers and thus subject to that
representation's range and precision limitations.  This is especially relevant
when serializing Python :class:`int` values of extremely large magnitude, or
when serializing instances of "exotic" numerical types such as
:class:`decimal.Decimal`.


.. rubric:: Footnotes

.. [#rfc-errata] As noted in `the errata for RFC 7159
   <https://www.rfc-editor.org/errata_search.php?rfc=7159>`_,
   JSON permits literal U+2028 (LINE SEPARATOR) and
   U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
   (as of ECMAScript Edition 5.1) does not.
PK	%�\ϖ��ii%html/_sources/library/keyword.rst.txtnu�[���:mod:`keyword` --- Testing for Python keywords
==============================================

.. module:: keyword
   :synopsis: Test whether a string is a keyword in Python.

**Source code:** :source:`Lib/keyword.py`

--------------

This module allows a Python program to determine if a string is a keyword.


.. function:: iskeyword(s)

   Return true if *s* is a Python keyword.


.. data:: kwlist

   Sequence containing all the keywords defined for the interpreter.  If any
   keywords are defined to only be active when particular :mod:`__future__`
   statements are in effect, these will be included as well.
PK	%�\�A�F&html/_sources/library/language.rst.txtnu�[���
.. _language:

************************
Python Language Services
************************

Python provides a number of modules to assist in working with the Python
language.  These modules support tokenizing, parsing, syntax analysis, bytecode
disassembly, and various other facilities.

These modules include:


.. toctree::

   parser.rst
   ast.rst
   symtable.rst
   symbol.rst
   token.rst
   keyword.rst
   tokenize.rst
   tabnanny.rst
   pyclbr.rst
   py_compile.rst
   compileall.rst
   dis.rst
   pickletools.rst
PK	%�\����__'html/_sources/library/linecache.rst.txtnu�[���
:mod:`linecache` --- Random access to text lines
================================================

.. module:: linecache
   :synopsis: This module provides random access to individual lines from text files.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

**Source code:** :source:`Lib/linecache.py`

--------------

The :mod:`linecache` module allows one to get any line from any file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file.  This is used by the :mod:`traceback` module
to retrieve source lines for inclusion in  the formatted traceback.

The :mod:`linecache` module defines the following functions:


.. function:: getline(filename, lineno[, module_globals])

   Get line *lineno* from file named *filename*. This function will never raise an
   exception --- it will return ``''`` on errors (the terminating newline character
   will be included for lines that are found).

   .. index:: triple: module; search; path

   If a file named *filename* is not found, the function will look for it in the
   module search path, ``sys.path``, after first checking for a :pep:`302`
   ``__loader__`` in *module_globals*, in case the module was imported from a
   zipfile or other non-filesystem import source.

   .. versionadded:: 2.5
      The *module_globals* parameter was added.


.. function:: clearcache()

   Clear the cache.  Use this function if you no longer need lines from files
   previously read using :func:`getline`.


.. function:: checkcache([filename])

   Check the cache for validity.  Use this function if files in the cache  may have
   changed on disk, and you require the updated version.  If *filename* is omitted,
   it will check all the entries in the cache.

Example::

   >>> import linecache
   >>> linecache.getline('/etc/passwd', 4)
   'sys:x:3:3:sys:/dev:/bin/sh\n'

PK	%�\����a�a$html/_sources/library/locale.rst.txtnu�[���
:mod:`locale` --- Internationalization services
===============================================

.. module:: locale
   :synopsis: Internationalization services.
.. moduleauthor:: Martin von Löwis <martin@v.loewis.de>
.. sectionauthor:: Martin von Löwis <martin@v.loewis.de>


The :mod:`locale` module opens access to the POSIX locale database and
functionality. The POSIX locale mechanism allows programmers to deal with
certain cultural issues in an application, without requiring the programmer to
know all the specifics of each country where the software is executed.

.. index:: module: _locale

The :mod:`locale` module is implemented on top of the :mod:`_locale` module,
which in turn uses an ANSI C locale implementation if available.

The :mod:`locale` module defines the following exception and functions:


.. exception:: Error

   Exception raised when the locale passed to :func:`setlocale` is not
   recognized.


.. function:: setlocale(category[, locale])

   If *locale* is given and not ``None``, :func:`setlocale` modifies the locale
   setting for the *category*. The available categories are listed in the data
   description below. *locale* may be a string, or an iterable of two strings
   (language code and encoding). If it's an iterable, it's converted to a locale
   name using the locale aliasing engine. An empty string specifies the user's
   default settings. If the modification of the locale fails, the exception
   :exc:`Error` is raised. If successful, the new locale setting is returned.

   If *locale* is omitted or ``None``, the current setting for *category* is
   returned.

   :func:`setlocale` is not thread-safe on most systems. Applications typically
   start with a call of ::

      import locale
      locale.setlocale(locale.LC_ALL, '')

   This sets the locale for all categories to the user's default setting (typically
   specified in the :envvar:`LANG` environment variable).  If the locale is not
   changed thereafter, using multithreading should not cause problems.

   .. versionchanged:: 2.0
      Added support for iterable values of the *locale* parameter.


.. function:: localeconv()

   Returns the database of the local conventions as a dictionary. This dictionary
   has the following strings as keys:

   .. tabularcolumns:: |l|l|L|

   +----------------------+-------------------------------------+--------------------------------+
   | Category             | Key                                 | Meaning                        |
   +======================+=====================================+================================+
   | :const:`LC_NUMERIC`  | ``'decimal_point'``                 | Decimal point character.       |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'grouping'``                      | Sequence of numbers specifying |
   |                      |                                     | which relative positions the   |
   |                      |                                     | ``'thousands_sep'`` is         |
   |                      |                                     | expected.  If the sequence is  |
   |                      |                                     | terminated with                |
   |                      |                                     | :const:`CHAR_MAX`, no further  |
   |                      |                                     | grouping is performed. If the  |
   |                      |                                     | sequence terminates with a     |
   |                      |                                     | ``0``,  the last group size is |
   |                      |                                     | repeatedly used.               |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'thousands_sep'``                 | Character used between groups. |
   +----------------------+-------------------------------------+--------------------------------+
   | :const:`LC_MONETARY` | ``'int_curr_symbol'``               | International currency symbol. |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'currency_symbol'``               | Local currency symbol.         |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'p_cs_precedes/n_cs_precedes'``   | Whether the currency symbol    |
   |                      |                                     | precedes the value (for        |
   |                      |                                     | positive resp. negative        |
   |                      |                                     | values).                       |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'p_sep_by_space/n_sep_by_space'`` | Whether the currency symbol is |
   |                      |                                     | separated from the value  by a |
   |                      |                                     | space (for positive resp.      |
   |                      |                                     | negative values).              |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'mon_decimal_point'``             | Decimal point used for         |
   |                      |                                     | monetary values.               |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'frac_digits'``                   | Number of fractional digits    |
   |                      |                                     | used in local formatting of    |
   |                      |                                     | monetary values.               |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'int_frac_digits'``               | Number of fractional digits    |
   |                      |                                     | used in international          |
   |                      |                                     | formatting of monetary values. |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'mon_thousands_sep'``             | Group separator used for       |
   |                      |                                     | monetary values.               |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'mon_grouping'``                  | Equivalent to ``'grouping'``,  |
   |                      |                                     | used for monetary values.      |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'positive_sign'``                 | Symbol used to annotate a      |
   |                      |                                     | positive monetary value.       |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'negative_sign'``                 | Symbol used to annotate a      |
   |                      |                                     | negative monetary value.       |
   +----------------------+-------------------------------------+--------------------------------+
   |                      | ``'p_sign_posn/n_sign_posn'``       | The position of the sign (for  |
   |                      |                                     | positive resp. negative        |
   |                      |                                     | values), see below.            |
   +----------------------+-------------------------------------+--------------------------------+

   All numeric values can be set to :const:`CHAR_MAX` to indicate that there is no
   value specified in this locale.

   The possible values for ``'p_sign_posn'`` and ``'n_sign_posn'`` are given below.

   +--------------+-----------------------------------------+
   | Value        | Explanation                             |
   +==============+=========================================+
   | ``0``        | Currency and value are surrounded by    |
   |              | parentheses.                            |
   +--------------+-----------------------------------------+
   | ``1``        | The sign should precede the value and   |
   |              | currency symbol.                        |
   +--------------+-----------------------------------------+
   | ``2``        | The sign should follow the value and    |
   |              | currency symbol.                        |
   +--------------+-----------------------------------------+
   | ``3``        | The sign should immediately precede the |
   |              | value.                                  |
   +--------------+-----------------------------------------+
   | ``4``        | The sign should immediately follow the  |
   |              | value.                                  |
   +--------------+-----------------------------------------+
   | ``CHAR_MAX`` | Nothing is specified in this locale.    |
   +--------------+-----------------------------------------+


.. function:: nl_langinfo(option)

   Return some locale-specific information as a string.  This function is not
   available on all systems, and the set of possible options might also vary
   across platforms.  The possible argument values are numbers, for which
   symbolic constants are available in the locale module.

   The :func:`nl_langinfo` function accepts one of the following keys.  Most
   descriptions are taken from the corresponding description in the GNU C
   library.

   .. data:: CODESET

      Get a string with the name of the character encoding used in the
      selected locale.

   .. data:: D_T_FMT

      Get a string that can be used as a format string for :func:`time.strftime` to
      represent date and time in a locale-specific way.

   .. data:: D_FMT

      Get a string that can be used as a format string for :func:`time.strftime` to
      represent a date in a locale-specific way.

   .. data:: T_FMT

      Get a string that can be used as a format string for :func:`time.strftime` to
      represent a time in a locale-specific way.

   .. data:: T_FMT_AMPM

      Get a format string for :func:`time.strftime` to represent time in the am/pm
      format.

   .. data:: DAY_1 ... DAY_7

      Get the name of the n-th day of the week.

      .. note::

         This follows the US convention of :const:`DAY_1` being Sunday, not the
         international convention (ISO 8601) that Monday is the first day of the
         week.

   .. data:: ABDAY_1 ... ABDAY_7

      Get the abbreviated name of the n-th day of the week.

   .. data:: MON_1 ... MON_12

      Get the name of the n-th month.

   .. data:: ABMON_1 ... ABMON_12

      Get the abbreviated name of the n-th month.

   .. data:: RADIXCHAR

      Get the radix character (decimal dot, decimal comma, etc.).

   .. data:: THOUSEP

      Get the separator character for thousands (groups of three digits).

   .. data:: YESEXPR

      Get a regular expression that can be used with the regex function to
      recognize a positive response to a yes/no question.

      .. note::

         The expression is in the syntax suitable for the :c:func:`regex` function
         from the C library, which might differ from the syntax used in :mod:`re`.

   .. data:: NOEXPR

      Get a regular expression that can be used with the regex(3) function to
      recognize a negative response to a yes/no question.

   .. data:: CRNCYSTR

      Get the currency symbol, preceded by "-" if the symbol should appear before
      the value, "+" if the symbol should appear after the value, or "." if the
      symbol should replace the radix character.

   .. data:: ERA

      Get a string that represents the era used in the current locale.

      Most locales do not define this value.  An example of a locale which does
      define this value is the Japanese one.  In Japan, the traditional
      representation of dates includes the name of the era corresponding to the
      then-emperor's reign.

      Normally it should not be necessary to use this value directly. Specifying
      the ``E`` modifier in their format strings causes the :func:`time.strftime`
      function to use this information.  The format of the returned string is not
      specified, and therefore you should not assume knowledge of it on different
      systems.

   .. data:: ERA_D_T_FMT

      Get a format string for :func:`time.strftime` to represent date and time in a
      locale-specific era-based way.

   .. data:: ERA_D_FMT

      Get a format string for :func:`time.strftime` to represent a date in a
      locale-specific era-based way.

   .. data:: ERA_T_FMT

      Get a format string for :func:`time.strftime` to represent a time in a
      locale-specific era-based way.

   .. data:: ALT_DIGITS

      Get a representation of up to 100 values used to represent the values
      0 to 99.


.. function:: getdefaultlocale([envvars])

   Tries to determine the default locale settings and returns them as a tuple of
   the form ``(language code, encoding)``.

   According to POSIX, a program which has not called ``setlocale(LC_ALL, '')``
   runs using the portable ``'C'`` locale.  Calling ``setlocale(LC_ALL, '')`` lets
   it use the default locale as defined by the :envvar:`LANG` variable.  Since we
   do not want to interfere with the current locale setting we thus emulate the
   behavior in the way described above.

   To maintain compatibility with other platforms, not only the :envvar:`LANG`
   variable is tested, but a list of variables given as envvars parameter.  The
   first found to be defined will be used.  *envvars* defaults to the search path
   used in GNU gettext; it must always contain the variable name ``LANG``.  The GNU
   gettext search path contains ``'LANGUAGE'``, ``'LC_ALL'``, ``'LC_CTYPE'``, and
   ``'LANG'``, in that order.

   Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
   *language code* and *encoding* may be ``None`` if their values cannot be
   determined.

   .. versionadded:: 2.0


.. function:: getlocale([category])

   Returns the current setting for the given locale category as sequence containing
   *language code*, *encoding*. *category* may be one of the :const:`LC_\*` values
   except :const:`LC_ALL`.  It defaults to :const:`LC_CTYPE`.

   Except for the code ``'C'``, the language code corresponds to :rfc:`1766`.
   *language code* and *encoding* may be ``None`` if their values cannot be
   determined.

   .. versionadded:: 2.0


.. function:: getpreferredencoding([do_setlocale])

   Return the encoding used for text data, according to user preferences.  User
   preferences are expressed differently on different systems, and might not be
   available programmatically on some systems, so this function only returns a
   guess.

   On some systems, it is necessary to invoke :func:`setlocale` to obtain the user
   preferences, so this function is not thread-safe. If invoking setlocale is not
   necessary or desired, *do_setlocale* should be set to ``False``.

   .. versionadded:: 2.3


.. function:: normalize(localename)

   Returns a normalized locale code for the given locale name.  The returned locale
   code is formatted for use with :func:`setlocale`.  If normalization fails, the
   original name is returned unchanged.

   If the given encoding is not known, the function defaults to the default
   encoding for the locale code just like :func:`setlocale`.

   .. versionadded:: 2.0


.. function:: resetlocale([category])

   Sets the locale for *category* to the default setting.

   The default setting is determined by calling :func:`getdefaultlocale`.
   *category* defaults to :const:`LC_ALL`.

   .. versionadded:: 2.0


.. function:: strcoll(string1, string2)

   Compares two strings according to the current :const:`LC_COLLATE` setting. As
   any other compare function, returns a negative, or a positive value, or ``0``,
   depending on whether *string1* collates before or after *string2* or is equal to
   it.


.. function:: strxfrm(string)

   .. index:: builtin: cmp

   Transforms a string to one that can be used for the built-in function
   :func:`cmp`, and still returns locale-aware results.  This function can be used
   when the same string is compared repeatedly, e.g. when collating a sequence of
   strings.


.. function:: format(format, val[, grouping[, monetary]])

   Formats a number *val* according to the current :const:`LC_NUMERIC` setting.
   The format follows the conventions of the ``%`` operator.  For floating point
   values, the decimal point is modified if appropriate.  If *grouping* is true,
   also takes the grouping into account.

   If *monetary* is true, the conversion uses monetary thousands separator and
   grouping strings.

   Please note that this function will only work for exactly one %char specifier.
   For whole format strings, use :func:`format_string`.

   .. versionchanged:: 2.5
      Added the *monetary* parameter.


.. function:: format_string(format, val[, grouping])

   Processes formatting specifiers as in ``format % val``, but takes the current
   locale settings into account.

   .. versionadded:: 2.5


.. function:: currency(val[, symbol[, grouping[, international]]])

   Formats a number *val* according to the current :const:`LC_MONETARY` settings.

   The returned string includes the currency symbol if *symbol* is true, which is
   the default. If *grouping* is true (which is not the default), grouping is done
   with the value. If *international* is true (which is not the default), the
   international currency symbol is used.

   Note that this function will not work with the 'C' locale, so you have to set a
   locale via :func:`setlocale` first.

   .. versionadded:: 2.5


.. function:: str(float)

   Formats a floating point number using the same format as the built-in function
   ``str(float)``, but takes the decimal point into account.


.. function:: atof(string)

   Converts a string to a floating point number, following the :const:`LC_NUMERIC`
   settings.


.. function:: atoi(string)

   Converts a string to an integer, following the :const:`LC_NUMERIC` conventions.


.. data:: LC_CTYPE

   .. index:: module: string

   Locale category for the character type functions.  Depending on the settings of
   this category, the functions of module :mod:`string` dealing with case change
   their behaviour.


.. data:: LC_COLLATE

   Locale category for sorting strings.  The functions :func:`strcoll` and
   :func:`strxfrm` of the :mod:`locale` module are affected.


.. data:: LC_TIME

   Locale category for the formatting of time.  The function :func:`time.strftime`
   follows these conventions.


.. data:: LC_MONETARY

   Locale category for formatting of monetary values.  The available options are
   available from the :func:`localeconv` function.


.. data:: LC_MESSAGES

   Locale category for message display. Python currently does not support
   application specific locale-aware messages.  Messages displayed by the operating
   system, like those returned by :func:`os.strerror` might be affected by this
   category.


.. data:: LC_NUMERIC

   Locale category for formatting numbers.  The functions :func:`.format`,
   :func:`atoi`, :func:`atof` and :func:`.str` of the :mod:`locale` module are
   affected by that category.  All other numeric formatting operations are not
   affected.


.. data:: LC_ALL

   Combination of all locale settings.  If this flag is used when the locale is
   changed, setting the locale for all categories is attempted. If that fails for
   any category, no category is changed at all.  When the locale is retrieved using
   this flag, a string indicating the setting for all categories is returned. This
   string can be later used to restore the settings.


.. data:: CHAR_MAX

   This is a symbolic constant used for different values returned by
   :func:`localeconv`.


Example::

   >>> import locale
   >>> loc = locale.getlocale()  # get current locale
   # use German locale; name might vary with platform
   >>> locale.setlocale(locale.LC_ALL, 'de_DE')
   >>> locale.strcoll('f\xe4n', 'foo')  # compare a string containing an umlaut
   >>> locale.setlocale(locale.LC_ALL, '')   # use user's preferred locale
   >>> locale.setlocale(locale.LC_ALL, 'C')  # use default (C) locale
   >>> locale.setlocale(locale.LC_ALL, loc)  # restore saved locale


Background, details, hints, tips and caveats
--------------------------------------------

The C standard defines the locale as a program-wide property that may be
relatively expensive to change.  On top of that, some implementation are broken
in such a way that frequent locale changes may cause core dumps.  This makes the
locale somewhat painful to use correctly.

Initially, when a program is started, the locale is the ``C`` locale, no matter
what the user's preferred locale is.  The program must explicitly say that it
wants the user's preferred locale settings by calling ``setlocale(LC_ALL, '')``.

It is generally a bad idea to call :func:`setlocale` in some library routine,
since as a side effect it affects the entire program.  Saving and restoring it
is almost as bad: it is expensive and affects other threads that happen to run
before the settings have been restored.

If, when coding a module for general use, you need a locale independent version
of an operation that is affected by the locale (such as :func:`string.lower`, or
certain formats used with :func:`time.strftime`), you will have to find a way to
do it without using the standard library routine.  Even better is convincing
yourself that using locale settings is okay.  Only as a last resort should you
document that your module is not compatible with non-\ ``C`` locale settings.

.. index:: module: string

The case conversion functions in the :mod:`string` module are affected by the
locale settings.  When a call to the :func:`setlocale` function changes the
:const:`LC_CTYPE` settings, the variables ``string.lowercase``,
``string.uppercase`` and ``string.letters`` are recalculated.  Note that code
that uses these variable through ':keyword:`from` ... :keyword:`import` ...',
e.g. ``from string import letters``, is not affected by subsequent
:func:`setlocale` calls.

The only way to perform numeric operations according to the locale is to use the
special functions defined by this module: :func:`atof`, :func:`atoi`,
:func:`.format`, :func:`.str`.


.. _embedding-locale:

For extension writers and programs that embed Python
----------------------------------------------------

Extension modules should never call :func:`setlocale`, except to find out what
the current locale is.  But since the return value can only be used portably to
restore it, that is not very useful (except perhaps to find out whether or not
the locale is ``C``).

When Python code uses the :mod:`locale` module to change the locale, this also
affects the embedding application.  If the embedding application doesn't want
this to happen, it should remove the :mod:`_locale` extension module (which does
all the work) from the table of built-in modules in the :file:`config.c` file,
and make sure that the :mod:`_locale` module is not accessible as a shared
library.


.. _locale-gettext:

Access to message catalogs
--------------------------

.. function:: gettext(msg)
.. function:: dgettext(domain, msg)
.. function:: dcgettext(domain, msg, category)
.. function:: textdomain(domain)
.. function:: bindtextdomain(domain, dir)

The locale module exposes the C library's gettext interface on systems that
provide this interface.  It consists of the functions :func:`!gettext`,
:func:`!dgettext`, :func:`!dcgettext`, :func:`!textdomain`, :func:`!bindtextdomain`,
and :func:`!bind_textdomain_codeset`.  These are similar to the same functions in
the :mod:`gettext` module, but use the C library's binary format for message
catalogs, and the C library's search algorithms for locating message catalogs.

Python applications should normally find no need to invoke these functions, and
should use :mod:`gettext` instead.  A known exception to this rule are
applications that link with additional C libraries which internally invoke
:c:func:`gettext` or :c:func:`dcgettext`.  For these applications, it may be
necessary to bind the text domain, so that the libraries can properly locate
their message catalogs.

PK	%�\P��H{H{,html/_sources/library/logging.config.rst.txtnu�[���:mod:`logging.config` --- Logging configuration
===============================================

.. module:: logging.config
   :synopsis: Configuration of the logging module.


.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>

.. sidebar:: Important

   This page contains only reference information. For tutorials,
   please see

   * :ref:`Basic Tutorial <logging-basic-tutorial>`
   * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
   * :ref:`Logging Cookbook <logging-cookbook>`

**Source code:** :source:`Lib/logging/config.py`

--------------

This section describes the API for configuring the logging module.

.. _logging-config-api:

Configuration functions
^^^^^^^^^^^^^^^^^^^^^^^

The following functions configure the logging module. They are located in the
:mod:`logging.config` module.  Their use is optional --- you can configure the
logging module using these functions or by making calls to the main API (defined
in :mod:`logging` itself) and defining handlers which are declared either in
:mod:`logging` or :mod:`logging.handlers`.

.. function:: dictConfig(config)

    Takes the logging configuration from a dictionary.  The contents of
    this dictionary are described in :ref:`logging-config-dictschema`
    below.

    If an error is encountered during configuration, this function will
    raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
    or :exc:`ImportError` with a suitably descriptive message.  The
    following is a (possibly incomplete) list of conditions which will
    raise an error:

    * A ``level`` which is not a string or which is a string not
      corresponding to an actual logging level.
    * A ``propagate`` value which is not a boolean.
    * An id which does not have a corresponding destination.
    * A non-existent handler id found during an incremental call.
    * An invalid logger name.
    * Inability to resolve to an internal or external object.

    Parsing is performed by the :class:`DictConfigurator` class, whose
    constructor is passed the dictionary used for configuration, and
    has a :meth:`configure` method.  The :mod:`logging.config` module
    has a callable attribute :attr:`dictConfigClass`
    which is initially set to :class:`DictConfigurator`.
    You can replace the value of :attr:`dictConfigClass` with a
    suitable implementation of your own.

    :func:`dictConfig` calls :attr:`dictConfigClass` passing
    the specified dictionary, and then calls the :meth:`configure` method on
    the returned object to put the configuration into effect::

          def dictConfig(config):
              dictConfigClass(config).configure()

    For example, a subclass of :class:`DictConfigurator` could call
    ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
    set up custom prefixes which would be usable in the subsequent
    :meth:`configure` call. :attr:`dictConfigClass` would be bound to
    this new subclass, and then :func:`dictConfig` could be called exactly as
    in the default, uncustomized state.

   .. versionadded:: 2.7

.. function:: fileConfig(fname, defaults=None, disable_existing_loggers=True)

   Reads the logging configuration from a :mod:`configparser`\-format file
   named *fname*. The format of the file should be as described in
   :ref:`logging-config-fileformat`. This function can be called several times
   from an application, allowing an end user to select from various pre-canned
   configurations (if the developer provides a mechanism to present the choices
   and load the chosen configuration).

   :param defaults: Defaults to be passed to the ConfigParser can be specified
                    in this argument.

   :param disable_existing_loggers: If specified as ``False``, loggers which
                                    exist when this call is made are left
                                    enabled. The default is ``True`` because this
                                    enables old behaviour in a
                                    backward-compatible way. This behaviour is to
                                    disable any existing loggers unless they or
                                    their ancestors are explicitly named in the
                                    logging configuration.

   .. versionchanged:: 2.6
      The ``disable_existing_loggers`` keyword argument was added. Previously,
      existing loggers were *always* disabled.

.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)

   Starts up a socket server on the specified port, and listens for new
   configurations. If no port is specified, the module's default
   :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
   sent as a file suitable for processing by :func:`fileConfig`. Returns a
   :class:`~threading.Thread` instance on which you can call
   :meth:`~threading.Thread.start` to start the server, and which you can
   :meth:`~threading.Thread.join` when appropriate. To stop the server,
   call :func:`stopListening`.

   To send a configuration to the socket, read in the configuration file and
   send it to the socket as a string of bytes preceded by a four-byte length
   string packed in binary using ``struct.pack('>L', n)``.

   .. note::

      Because portions of the configuration are passed through
      :func:`eval`, use of this function may open its users to a security risk.
      While the function only binds to a socket on ``localhost``, and so does
      not accept connections from remote machines, there are scenarios where
      untrusted code could be run under the account of the process which calls
      :func:`listen`. Specifically, if the process calling :func:`listen` runs
      on a multi-user machine where users cannot trust each other, then a
      malicious user could arrange to run essentially arbitrary code in a
      victim user's process, simply by connecting to the victim's
      :func:`listen` socket and sending a configuration which runs whatever
      code the attacker wants to have executed in the victim's process. This is
      especially easy to do if the default port is used, but not hard even if a
      different port is used).

.. function:: stopListening()

   Stops the listening server which was created with a call to :func:`listen`.
   This is typically called before calling :meth:`join` on the return value from
   :func:`listen`.


.. _logging-config-dictschema:

Configuration dictionary schema
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Describing a logging configuration requires listing the various
objects to create and the connections between them; for example, you
may create a handler named 'console' and then say that the logger
named 'startup' will send its messages to the 'console' handler.
These objects aren't limited to those provided by the :mod:`logging`
module because you might write your own formatter or handler class.
The parameters to these classes may also need to include external
objects such as ``sys.stderr``.  The syntax for describing these
objects and connections is defined in :ref:`logging-config-dict-connections`
below.

Dictionary Schema Details
"""""""""""""""""""""""""

The dictionary passed to :func:`dictConfig` must contain the following
keys:

* *version* - to be set to an integer value representing the schema
  version.  The only valid value at present is 1, but having this key
  allows the schema to evolve while still preserving backwards
  compatibility.

All other keys are optional, but if present they will be interpreted
as described below.  In all cases below where a 'configuring dict' is
mentioned, it will be checked for the special ``'()'`` key to see if a
custom instantiation is required.  If so, the mechanism described in
:ref:`logging-config-dict-userdef` below is used to create an instance;
otherwise, the context is used to determine what to instantiate.

* *formatters* - the corresponding value will be a dict in which each
  key is a formatter id and each value is a dict describing how to
  configure the corresponding :class:`~logging.Formatter` instance.

  The configuring dict is searched for keys ``format`` and ``datefmt``
  (with defaults of ``None``) and these are used to construct a
  :class:`~logging.Formatter` instance.

* *filters* - the corresponding value will be a dict in which each key
  is a filter id and each value is a dict describing how to configure
  the corresponding Filter instance.

  The configuring dict is searched for the key ``name`` (defaulting to the
  empty string) and this is used to construct a :class:`logging.Filter`
  instance.

* *handlers* - the corresponding value will be a dict in which each
  key is a handler id and each value is a dict describing how to
  configure the corresponding Handler instance.

  The configuring dict is searched for the following keys:

  * ``class`` (mandatory).  This is the fully qualified name of the
    handler class.

  * ``level`` (optional).  The level of the handler.

  * ``formatter`` (optional).  The id of the formatter for this
    handler.

  * ``filters`` (optional).  A list of ids of the filters for this
    handler.

  All *other* keys are passed through as keyword arguments to the
  handler's constructor.  For example, given the snippet:

  .. code-block:: yaml

      handlers:
        console:
          class : logging.StreamHandler
          formatter: brief
          level   : INFO
          filters: [allow_foo]
          stream  : ext://sys.stdout
        file:
          class : logging.handlers.RotatingFileHandler
          formatter: precise
          filename: logconfig.log
          maxBytes: 1024
          backupCount: 3

  the handler with id ``console`` is instantiated as a
  :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
  stream.  The handler with id ``file`` is instantiated as a
  :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
  ``filename='logconfig.log', maxBytes=1024, backupCount=3``.

* *loggers* - the corresponding value will be a dict in which each key
  is a logger name and each value is a dict describing how to
  configure the corresponding Logger instance.

  The configuring dict is searched for the following keys:

  * ``level`` (optional).  The level of the logger.

  * ``propagate`` (optional).  The propagation setting of the logger.

  * ``filters`` (optional).  A list of ids of the filters for this
    logger.

  * ``handlers`` (optional).  A list of ids of the handlers for this
    logger.

  The specified loggers will be configured according to the level,
  propagation, filters and handlers specified.

* *root* - this will be the configuration for the root logger.
  Processing of the configuration will be as for any logger, except
  that the ``propagate`` setting will not be applicable.

* *incremental* - whether the configuration is to be interpreted as
  incremental to the existing configuration.  This value defaults to
  ``False``, which means that the specified configuration replaces the
  existing configuration with the same semantics as used by the
  existing :func:`fileConfig` API.

  If the specified value is ``True``, the configuration is processed
  as described in the section on :ref:`logging-config-dict-incremental`.

* *disable_existing_loggers* - whether any existing loggers are to be
  disabled. This setting mirrors the parameter of the same name in
  :func:`fileConfig`. If absent, this parameter defaults to ``True``.
  This value is ignored if *incremental* is ``True``.

.. _logging-config-dict-incremental:

Incremental Configuration
"""""""""""""""""""""""""

It is difficult to provide complete flexibility for incremental
configuration.  For example, because objects such as filters
and formatters are anonymous, once a configuration is set up, it is
not possible to refer to such anonymous objects when augmenting a
configuration.

Furthermore, there is not a compelling case for arbitrarily altering
the object graph of loggers, handlers, filters, formatters at
run-time, once a configuration is set up; the verbosity of loggers and
handlers can be controlled just by setting levels (and, in the case of
loggers, propagation flags).  Changing the object graph arbitrarily in
a safe way is problematic in a multi-threaded environment; while not
impossible, the benefits are not worth the complexity it adds to the
implementation.

Thus, when the ``incremental`` key of a configuration dict is present
and is ``True``, the system will completely ignore any ``formatters`` and
``filters`` entries, and process only the ``level``
settings in the ``handlers`` entries, and the ``level`` and
``propagate`` settings in the ``loggers`` and ``root`` entries.

Using a value in the configuration dict lets configurations to be sent
over the wire as pickled dicts to a socket listener. Thus, the logging
verbosity of a long-running application can be altered over time with
no need to stop and restart the application.

.. _logging-config-dict-connections:

Object connections
""""""""""""""""""

The schema describes a set of logging objects - loggers,
handlers, formatters, filters - which are connected to each other in
an object graph.  Thus, the schema needs to represent connections
between the objects.  For example, say that, once configured, a
particular logger has attached to it a particular handler.  For the
purposes of this discussion, we can say that the logger represents the
source, and the handler the destination, of a connection between the
two.  Of course in the configured objects this is represented by the
logger holding a reference to the handler.  In the configuration dict,
this is done by giving each destination object an id which identifies
it unambiguously, and then using the id in the source object's
configuration to indicate that a connection exists between the source
and the destination object with that id.

So, for example, consider the following YAML snippet:

.. code-block:: yaml

    formatters:
      brief:
        # configuration for formatter with id 'brief' goes here
      precise:
        # configuration for formatter with id 'precise' goes here
    handlers:
      h1: #This is an id
       # configuration of handler with id 'h1' goes here
       formatter: brief
      h2: #This is another id
       # configuration of handler with id 'h2' goes here
       formatter: precise
    loggers:
      foo.bar.baz:
        # other configuration for logger 'foo.bar.baz'
        handlers: [h1, h2]

(Note: YAML used here because it's a little more readable than the
equivalent Python source form for the dictionary.)

The ids for loggers are the logger names which would be used
programmatically to obtain a reference to those loggers, e.g.
``foo.bar.baz``.  The ids for Formatters and Filters can be any string
value (such as ``brief``, ``precise`` above) and they are transient,
in that they are only meaningful for processing the configuration
dictionary and used to determine connections between objects, and are
not persisted anywhere when the configuration call is complete.

The above snippet indicates that logger named ``foo.bar.baz`` should
have two handlers attached to it, which are described by the handler
ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
``brief``, and the formatter for ``h2`` is that described by id
``precise``.


.. _logging-config-dict-userdef:

User-defined objects
""""""""""""""""""""

The schema supports user-defined objects for handlers, filters and
formatters.  (Loggers do not need to have different types for
different instances, so there is no support in this configuration
schema for user-defined logger classes.)

Objects to be configured are described by dictionaries
which detail their configuration.  In some places, the logging system
will be able to infer from the context how an object is to be
instantiated, but when a user-defined object is to be instantiated,
the system will not know how to do this.  In order to provide complete
flexibility for user-defined object instantiation, the user needs
to provide a 'factory' - a callable which is called with a
configuration dictionary and which returns the instantiated object.
This is signalled by an absolute import path to the factory being
made available under the special key ``'()'``.  Here's a concrete
example:

.. code-block:: yaml

    formatters:
      brief:
        format: '%(message)s'
      default:
        format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
        datefmt: '%Y-%m-%d %H:%M:%S'
      custom:
          (): my.package.customFormatterFactory
          bar: baz
          spam: 99.9
          answer: 42

The above YAML snippet defines three formatters.  The first, with id
``brief``, is a standard :class:`logging.Formatter` instance with the
specified format string.  The second, with id ``default``, has a
longer format and also defines the time format explicitly, and will
result in a :class:`logging.Formatter` initialized with those two format
strings.  Shown in Python source form, the ``brief`` and ``default``
formatters have configuration sub-dictionaries::

    {
      'format' : '%(message)s'
    }

and::

    {
      'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
      'datefmt' : '%Y-%m-%d %H:%M:%S'
    }

respectively, and as these dictionaries do not contain the special key
``'()'``, the instantiation is inferred from the context: as a result,
standard :class:`logging.Formatter` instances are created.  The
configuration sub-dictionary for the third formatter, with id
``custom``, is::

  {
    '()' : 'my.package.customFormatterFactory',
    'bar' : 'baz',
    'spam' : 99.9,
    'answer' : 42
  }

and this contains the special key ``'()'``, which means that
user-defined instantiation is wanted.  In this case, the specified
factory callable will be used. If it is an actual callable it will be
used directly - otherwise, if you specify a string (as in the example)
the actual callable will be located using normal import mechanisms.
The callable will be called with the **remaining** items in the
configuration sub-dictionary as keyword arguments.  In the above
example, the formatter with id ``custom`` will be assumed to be
returned by the call::

    my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)

The key ``'()'`` has been used as the special key because it is not a
valid keyword parameter name, and so will not clash with the names of
the keyword arguments used in the call.  The ``'()'`` also serves as a
mnemonic that the corresponding value is a callable.


.. _logging-config-dict-externalobj:

Access to external objects
""""""""""""""""""""""""""

There are times where a configuration needs to refer to objects
external to the configuration, for example ``sys.stderr``.  If the
configuration dict is constructed using Python code, this is
straightforward, but a problem arises when the configuration is
provided via a text file (e.g. JSON, YAML).  In a text file, there is
no standard way to distinguish ``sys.stderr`` from the literal string
``'sys.stderr'``.  To facilitate this distinction, the configuration
system looks for certain special prefixes in string values and
treat them specially.  For example, if the literal string
``'ext://sys.stderr'`` is provided as a value in the configuration,
then the ``ext://`` will be stripped off and the remainder of the
value processed using normal import mechanisms.

The handling of such prefixes is done in a way analogous to protocol
handling: there is a generic mechanism to look for prefixes which
match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
in a prefix-dependent manner and the result of the processing replaces
the string value.  If the prefix is not recognised, then the string
value will be left as-is.


.. _logging-config-dict-internalobj:

Access to internal objects
""""""""""""""""""""""""""

As well as external objects, there is sometimes also a need to refer
to objects in the configuration.  This will be done implicitly by the
configuration system for things that it knows about.  For example, the
string value ``'DEBUG'`` for a ``level`` in a logger or handler will
automatically be converted to the value ``logging.DEBUG``, and the
``handlers``, ``filters`` and ``formatter`` entries will take an
object id and resolve to the appropriate destination object.

However, a more generic mechanism is needed for user-defined
objects which are not known to the :mod:`logging` module.  For
example, consider :class:`logging.handlers.MemoryHandler`, which takes
a ``target`` argument which is another handler to delegate to. Since
the system already knows about this class, then in the configuration,
the given ``target`` just needs to be the object id of the relevant
target handler, and the system will resolve to the handler from the
id.  If, however, a user defines a ``my.package.MyHandler`` which has
an ``alternate`` handler, the configuration system would not know that
the ``alternate`` referred to a handler.  To cater for this, a generic
resolution system allows the user to specify::

    handlers:
      file:
        # configuration of file handler goes here

      custom:
        (): my.package.MyHandler
        alternate: cfg://handlers.file

The literal string ``'cfg://handlers.file'`` will be resolved in an
analogous way to strings with the ``ext://`` prefix, but looking
in the configuration itself rather than the import namespace.  The
mechanism allows access by dot or by index, in a similar way to
that provided by ``str.format``.  Thus, given the following snippet::

    handlers:
      email:
        class: logging.handlers.SMTPHandler
        mailhost: localhost
        fromaddr: my_app@domain.tld
        toaddrs:
          - support_team@domain.tld
          - dev_team@domain.tld
        subject: Houston, we have a problem.

in the configuration, the string ``'cfg://handlers'`` would resolve to
the dict with key ``handlers``, the string ``'cfg://handlers.email``
would resolve to the dict with key ``email`` in the ``handlers`` dict,
and so on.  The string ``'cfg://handlers.email.toaddrs[1]`` would
resolve to ``'dev_team.domain.tld'`` and the string
``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
``'support_team@domain.tld'``. The ``subject`` value could be accessed
using either ``'cfg://handlers.email.subject'`` or, equivalently,
``'cfg://handlers.email[subject]'``.  The latter form only needs to be
used if the key contains spaces or non-alphanumeric characters.  If an
index value consists only of decimal digits, access will be attempted
using the corresponding integer value, falling back to the string
value if needed.

Given a string ``cfg://handlers.myhandler.mykey.123``, this will
resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
the system will attempt to retrieve the value from
``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
fails.


.. _logging-import-resolution:

Import resolution and custom importers
""""""""""""""""""""""""""""""""""""""

Import resolution, by default, uses the builtin :func:`__import__` function
to do its importing. You may want to replace this with your own importing
mechanism: if so, you can replace the :attr:`importer` attribute of the
:class:`DictConfigurator` or its superclass, the
:class:`BaseConfigurator` class. However, you need to be
careful because of the way functions are accessed from classes via
descriptors. If you are using a Python callable to do your imports, and you
want to define it at class level rather than instance level, you need to wrap
it with :func:`staticmethod`. For example::

   from importlib import import_module
   from logging.config import BaseConfigurator

   BaseConfigurator.importer = staticmethod(import_module)

You don't need to wrap with :func:`staticmethod` if you're setting the import
callable on a configurator *instance*.


.. _logging-config-fileformat:

Configuration file format
^^^^^^^^^^^^^^^^^^^^^^^^^

The configuration file format understood by :func:`fileConfig` is based on
:mod:`configparser` functionality. The file must contain sections called
``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
entities of each type which are defined in the file. For each such entity, there
is a separate section which identifies how that entity is configured.  Thus, for
a logger named ``log01`` in the ``[loggers]`` section, the relevant
configuration details are held in a section ``[logger_log01]``. Similarly, a
handler called ``hand01`` in the ``[handlers]`` section will have its
configuration held in a section called ``[handler_hand01]``, while a formatter
called ``form01`` in the ``[formatters]`` section will have its configuration
specified in a section called ``[formatter_form01]``. The root logger
configuration must be specified in a section called ``[logger_root]``.

.. note::

   The :func:`fileConfig` API is older than the :func:`dictConfig` API and does
   not provide functionality to cover certain aspects of logging. For example,
   you cannot configure :class:`~logging.Filter` objects, which provide for
   filtering of messages beyond simple integer levels, using :func:`fileConfig`.
   If you need to have instances of :class:`~logging.Filter` in your logging
   configuration, you will need to use :func:`dictConfig`. Note that future
   enhancements to configuration functionality will be added to
   :func:`dictConfig`, so it's worth considering transitioning to this newer
   API when it's convenient to do so.

Examples of these sections in the file are given below.

.. code-block:: ini

   [loggers]
   keys=root,log02,log03,log04,log05,log06,log07

   [handlers]
   keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09

   [formatters]
   keys=form01,form02,form03,form04,form05,form06,form07,form08,form09

The root logger must specify a level and a list of handlers. An example of a
root logger section is given below.

.. code-block:: ini

   [logger_root]
   level=NOTSET
   handlers=hand01

The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
logged. Level values are :func:`eval`\ uated in the context of the ``logging``
package's namespace.

The ``handlers`` entry is a comma-separated list of handler names, which must
appear in the ``[handlers]`` section. These names must appear in the
``[handlers]`` section and have corresponding sections in the configuration
file.

For loggers other than the root logger, some additional information is required.
This is illustrated by the following example.

.. code-block:: ini

   [logger_parser]
   level=DEBUG
   handlers=hand01
   propagate=1
   qualname=compiler.parser

The ``level`` and ``handlers`` entries are interpreted as for the root logger,
except that if a non-root logger's level is specified as ``NOTSET``, the system
consults loggers higher up the hierarchy to determine the effective level of the
logger. The ``propagate`` entry is set to 1 to indicate that messages must
propagate to handlers higher up the logger hierarchy from this logger, or 0 to
indicate that messages are **not** propagated to handlers up the hierarchy. The
``qualname`` entry is the hierarchical channel name of the logger, that is to
say the name used by the application to get the logger.

Sections which specify handler configuration are exemplified by the following.

.. code-block:: ini

   [handler_hand01]
   class=StreamHandler
   level=NOTSET
   formatter=form01
   args=(sys.stdout,)

The ``class`` entry indicates the handler's class (as determined by :func:`eval`
in the ``logging`` package's namespace). The ``level`` is interpreted as for
loggers, and ``NOTSET`` is taken to mean 'log everything'.

.. versionchanged:: 2.6
   Added support for resolving the handler’s class as a dotted module and
   class name.

The ``formatter`` entry indicates the key name of the formatter for this
handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
If a name is specified, it must appear in the ``[formatters]`` section and have
a corresponding section in the configuration file.

The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
package's namespace, is the list of arguments to the constructor for the handler
class. Refer to the constructors for the relevant handlers, or to the examples
below, to see how typical entries are constructed.

.. code-block:: ini

   [handler_hand02]
   class=FileHandler
   level=DEBUG
   formatter=form02
   args=('python.log', 'w')

   [handler_hand03]
   class=handlers.SocketHandler
   level=INFO
   formatter=form03
   args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)

   [handler_hand04]
   class=handlers.DatagramHandler
   level=WARN
   formatter=form04
   args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)

   [handler_hand05]
   class=handlers.SysLogHandler
   level=ERROR
   formatter=form05
   args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)

   [handler_hand06]
   class=handlers.NTEventLogHandler
   level=CRITICAL
   formatter=form06
   args=('Python Application', '', 'Application')

   [handler_hand07]
   class=handlers.SMTPHandler
   level=WARN
   formatter=form07
   args=('localhost', 'from@abc', ['user1@abc', 'user2@xyz'], 'Logger Subject')

   [handler_hand08]
   class=handlers.MemoryHandler
   level=NOTSET
   formatter=form08
   target=
   args=(10, ERROR)

   [handler_hand09]
   class=handlers.HTTPHandler
   level=NOTSET
   formatter=form09
   args=('localhost:9022', '/log', 'GET')

Sections which specify formatter configuration are typified by the following.

.. code-block:: ini

   [formatter_form01]
   format=F1 %(asctime)s %(levelname)s %(message)s
   datefmt=
   class=logging.Formatter

The ``format`` entry is the overall format string, and the ``datefmt`` entry is
the :func:`strftime`\ -compatible date/time format string.  If empty, the
package substitutes ISO8601 format date/times, which is almost equivalent to
specifying the date format string ``'%Y-%m-%d %H:%M:%S'``.  The ISO8601 format
also specifies milliseconds, which are appended to the result of using the above
format string, with a comma separator.  An example time in ISO8601 format is
``2003-01-23 00:29:50,411``.

The ``class`` entry is optional.  It indicates the name of the formatter's class
(as a dotted module and class name.)  This option is useful for instantiating a
:class:`~logging.Formatter` subclass.  Subclasses of
:class:`~logging.Formatter` can present exception tracebacks in an expanded or
condensed format.

.. note::

   Due to the use of :func:`eval` as described above, there are
   potential security risks which result from using the :func:`listen` to send
   and receive configurations via sockets. The risks are limited to where
   multiple users with no mutual trust run code on the same machine; see the
   :func:`listen` documentation for more information.

.. seealso::

   Module :mod:`logging`
      API reference for the logging module.

   Module :mod:`logging.handlers`
      Useful handlers included with the logging module.
PK	%�\�O�9�m�m.html/_sources/library/logging.handlers.rst.txtnu�[���:mod:`logging.handlers` --- Logging handlers
============================================

.. module:: logging.handlers
   :synopsis: Handlers for the logging module.


.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>

.. sidebar:: Important

   This page contains only reference information. For tutorials,
   please see

   * :ref:`Basic Tutorial <logging-basic-tutorial>`
   * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
   * :ref:`Logging Cookbook <logging-cookbook>`

**Source code:** :source:`Lib/logging/handlers.py`

--------------

.. currentmodule:: logging

The following useful handlers are provided in the package. Note that three of
the handlers (:class:`StreamHandler`, :class:`FileHandler` and
:class:`NullHandler`) are actually defined in the :mod:`logging` module itself,
but have been documented here along with the other handlers.

.. _stream-handler:

StreamHandler
^^^^^^^^^^^^^

The :class:`StreamHandler` class, located in the core :mod:`logging` package,
sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
file-like object (or, more precisely, any object which supports :meth:`write`
and :meth:`flush` methods).


.. class:: StreamHandler(stream=None)

   Returns a new instance of the :class:`StreamHandler` class. If *stream* is
   specified, the instance will use it for logging output; otherwise, *sys.stderr*
   will be used.


   .. method:: emit(record)

      If a formatter is specified, it is used to format the record. The record
      is then written to the stream with a newline terminator. If exception
      information is present, it is formatted using
      :func:`traceback.print_exception` and appended to the stream.


   .. method:: flush()

      Flushes the stream by calling its :meth:`flush` method. Note that the
      :meth:`close` method is inherited from :class:`~logging.Handler` and so
      does no output, so an explicit :meth:`flush` call may be needed at times.

.. _file-handler:

FileHandler
^^^^^^^^^^^

The :class:`FileHandler` class, located in the core :mod:`logging` package,
sends logging output to a disk file.  It inherits the output functionality from
:class:`StreamHandler`.


.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)

   Returns a new instance of the :class:`FileHandler` class. The specified file is
   opened and used as the stream for logging. If *mode* is not specified,
   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
   with that encoding.  If *delay* is true, then file opening is deferred until the
   first call to :meth:`emit`. By default, the file grows indefinitely.

   .. versionchanged:: 2.6
      *delay* was added.

   .. method:: close()

      Closes the file.


   .. method:: emit(record)

      Outputs the record to the file.


.. _null-handler:

NullHandler
^^^^^^^^^^^

.. versionadded:: 2.7

The :class:`NullHandler` class, located in the core :mod:`logging` package,
does not do any formatting or output. It is essentially a 'no-op' handler
for use by library developers.

.. class:: NullHandler()

   Returns a new instance of the :class:`NullHandler` class.

   .. method:: emit(record)

      This method does nothing.

   .. method:: handle(record)

      This method does nothing.

   .. method:: createLock()

      This method returns ``None`` for the lock, since there is no
      underlying I/O to which access needs to be serialized.


See :ref:`library-config` for more information on how to use
:class:`NullHandler`.

.. _watched-file-handler:

WatchedFileHandler
^^^^^^^^^^^^^^^^^^

.. currentmodule:: logging.handlers

.. versionadded:: 2.6

The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
module, is a :class:`FileHandler` which watches the file it is logging to. If
the file changes, it is closed and reopened using the file name.

A file change can happen because of usage of programs such as *newsyslog* and
*logrotate* which perform log file rotation. This handler, intended for use
under Unix/Linux, watches the file to see if it has changed since the last emit.
(A file is deemed to have changed if its device or inode have changed.) If the
file has changed, the old file stream is closed, and the file opened to get a
new stream.

This handler is not appropriate for use under Windows, because under Windows
open log files cannot be moved or renamed - logging opens the files with
exclusive locks - and so there is no need for such a handler. Furthermore,
*ST_INO* is not supported under Windows; :func:`~os.stat` always returns zero
for this value.


.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])

   Returns a new instance of the :class:`WatchedFileHandler` class. The specified
   file is opened and used as the stream for logging. If *mode* is not specified,
   :const:`'a'` is used.  If *encoding* is not ``None``, it is used to open the file
   with that encoding.  If *delay* is true, then file opening is deferred until the
   first call to :meth:`emit`.  By default, the file grows indefinitely.


   .. method:: emit(record)

      Outputs the record to the file, but first checks to see if the file has
      changed.  If it has, the existing stream is flushed and closed and the
      file opened again, before outputting the record to the file.

.. _rotating-file-handler:

RotatingFileHandler
^^^^^^^^^^^^^^^^^^^

The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
module, supports rotation of disk log files.


.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)

   Returns a new instance of the :class:`RotatingFileHandler` class. The specified
   file is opened and used as the stream for logging. If *mode* is not specified,
   ``'a'`` is used.  If *encoding* is not ``None``, it is used to open the file
   with that encoding.  If *delay* is true, then file opening is deferred until the
   first call to :meth:`emit`.  By default, the file grows indefinitely.

   You can use the *maxBytes* and *backupCount* values to allow the file to
   :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
   the file is closed and a new file is silently opened for output. Rollover occurs
   whenever the current log file is nearly *maxBytes* in length; if either of
   *maxBytes* or *backupCount* is zero, rollover never occurs.  If *backupCount*
   is non-zero, the system will save old log files by appending the extensions
   '.1', '.2' etc., to the filename. For example, with a *backupCount* of 5 and
   a base file name of :file:`app.log`, you would get :file:`app.log`,
   :file:`app.log.1`, :file:`app.log.2`, up to :file:`app.log.5`. The file being
   written to is always :file:`app.log`.  When this file is filled, it is closed
   and renamed to :file:`app.log.1`, and if files :file:`app.log.1`,
   :file:`app.log.2`, etc.  exist, then they are renamed to :file:`app.log.2`,
   :file:`app.log.3` etc.  respectively.

   .. versionchanged:: 2.6
      *delay* was added.


   .. method:: doRollover()

      Does a rollover, as described above.


   .. method:: emit(record)

      Outputs the record to the file, catering for rollover as described
      previously.

.. _timed-rotating-file-handler:

TimedRotatingFileHandler
^^^^^^^^^^^^^^^^^^^^^^^^

The :class:`TimedRotatingFileHandler` class, located in the
:mod:`logging.handlers` module, supports rotation of disk log files at certain
timed intervals.


.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)

   Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
   specified file is opened and used as the stream for logging. On rotating it also
   sets the filename suffix. Rotating happens based on the product of *when* and
   *interval*.

   You can use the *when* to specify the type of *interval*. The list of possible
   values is below.  Note that they are not case sensitive.

   +----------------+-----------------------+
   | Value          | Type of interval      |
   +================+=======================+
   | ``'S'``        | Seconds               |
   +----------------+-----------------------+
   | ``'M'``        | Minutes               |
   +----------------+-----------------------+
   | ``'H'``        | Hours                 |
   +----------------+-----------------------+
   | ``'D'``        | Days                  |
   +----------------+-----------------------+
   | ``'W0'-'W6'``  | Weekday (0=Monday)    |
   +----------------+-----------------------+
   | ``'midnight'`` | Roll over at midnight |
   +----------------+-----------------------+

   When using weekday-based rotation, specify 'W0' for Monday, 'W1' for
   Tuesday, and so on up to 'W6' for Sunday. In this case, the value passed for
   *interval* isn't used.

   The system will save old log files by appending extensions to the filename.
   The extensions are date-and-time based, using the strftime format
   ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
   rollover interval.

   When computing the next rollover time for the first time (when the handler
   is created), the last modification time of an existing log file, or else
   the current time, is used to compute when the next rotation will occur.

   If the *utc* argument is true, times in UTC will be used; otherwise
   local time is used.

   If *backupCount* is nonzero, at most *backupCount* files
   will be kept, and if more would be created when rollover occurs, the oldest
   one is deleted. The deletion logic uses the interval to determine which
   files to delete, so changing the interval may leave old files lying around.

   If *delay* is true, then file opening is deferred until the first call to
   :meth:`emit`.

   .. versionchanged:: 2.6
      *delay* and *utc* were added.


   .. method:: doRollover()

      Does a rollover, as described above.


   .. method:: emit(record)

      Outputs the record to the file, catering for rollover as described above.


.. _socket-handler:

SocketHandler
^^^^^^^^^^^^^

The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
sends logging output to a network socket. The base class uses a TCP socket.


.. class:: SocketHandler(host, port)

   Returns a new instance of the :class:`SocketHandler` class intended to
   communicate with a remote machine whose address is given by *host* and *port*.


   .. method:: close()

      Closes the socket.


   .. method:: emit()

      Pickles the record's attribute dictionary and writes it to the socket in
      binary format. If there is an error with the socket, silently drops the
      packet. If the connection was previously lost, re-establishes the
      connection. To unpickle the record at the receiving end into a
      :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
      function.


   .. method:: handleError()

      Handles an error which has occurred during :meth:`emit`. The most likely
      cause is a lost connection. Closes the socket so that we can retry on the
      next event.


   .. method:: makeSocket()

      This is a factory method which allows subclasses to define the precise
      type of socket they want. The default implementation creates a TCP socket
      (:const:`socket.SOCK_STREAM`).


   .. method:: makePickle(record)

      Pickles the record's attribute dictionary in binary format with a length
      prefix, and returns it ready for transmission across the socket.

      Note that pickles aren't completely secure. If you are concerned about
      security, you may want to override this method to implement a more secure
      mechanism. For example, you can sign pickles using HMAC and then verify
      them on the receiving end, or alternatively you can disable unpickling of
      global objects on the receiving end.


   .. method:: send(packet)

      Send a pickled string *packet* to the socket. This function allows for
      partial sends which can happen when the network is busy.


   .. method:: createSocket()

      Tries to create a socket; on failure, uses an exponential back-off
      algorithm.  On initial failure, the handler will drop the message it was
      trying to send.  When subsequent messages are handled by the same
      instance, it will not try connecting until some time has passed.  The
      default parameters are such that the initial delay is one second, and if
      after that delay the connection still can't be made, the handler will
      double the delay each time up to a maximum of 30 seconds.

      This behaviour is controlled by the following handler attributes:

      * ``retryStart`` (initial delay, defaulting to 1.0 seconds).
      * ``retryFactor`` (multiplier, defaulting to 2.0).
      * ``retryMax`` (maximum delay, defaulting to 30.0 seconds).

      This means that if the remote listener starts up *after* the handler has
      been used, you could lose messages (since the handler won't even attempt
      a connection until the delay has elapsed, but just silently drop messages
      during the delay period).


.. _datagram-handler:

DatagramHandler
^^^^^^^^^^^^^^^

The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
module, inherits from :class:`SocketHandler` to support sending logging messages
over UDP sockets.


.. class:: DatagramHandler(host, port)

   Returns a new instance of the :class:`DatagramHandler` class intended to
   communicate with a remote machine whose address is given by *host* and *port*.


   .. method:: emit()

      Pickles the record's attribute dictionary and writes it to the socket in
      binary format. If there is an error with the socket, silently drops the
      packet. To unpickle the record at the receiving end into a
      :class:`~logging.LogRecord`, use the :func:`~logging.makeLogRecord`
      function.


   .. method:: makeSocket()

      The factory method of :class:`SocketHandler` is here overridden to create
      a UDP socket (:const:`socket.SOCK_DGRAM`).


   .. method:: send(s)

      Send a pickled string to a socket.


.. _syslog-handler:

SysLogHandler
^^^^^^^^^^^^^

The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
supports sending logging messages to a remote or local Unix syslog.


.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)

   Returns a new instance of the :class:`SysLogHandler` class intended to
   communicate with a remote Unix machine whose address is given by *address* in
   the form of a ``(host, port)`` tuple.  If *address* is not specified,
   ``('localhost', 514)`` is used.  The address is used to open a socket.  An
   alternative to providing a ``(host, port)`` tuple is providing an address as a
   string, for example '/dev/log'. In this case, a Unix domain socket is used to
   send the message to the syslog. If *facility* is not specified,
   :const:`LOG_USER` is used. The type of socket opened depends on the
   *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
   opens a UDP socket. To open a TCP socket (for use with the newer syslog
   daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.

   Note that if your server is not listening on UDP port 514,
   :class:`SysLogHandler` may appear not to work. In that case, check what
   address you should be using for a domain socket - it's system dependent.
   For example, on Linux it's usually '/dev/log' but on OS/X it's
   '/var/run/syslog'. You'll need to check your platform and use the
   appropriate address (you may need to do this check at runtime if your
   application needs to run on several platforms). On Windows, you pretty
   much have to use the UDP option.

   .. versionchanged:: 2.7
      *socktype* was added.


   .. method:: close()

      Closes the socket to the remote host.


   .. method:: emit(record)

      The record is formatted, and then sent to the syslog server. If exception
      information is present, it is *not* sent to the server.


   .. method:: encodePriority(facility, priority)

      Encodes the facility and priority into an integer. You can pass in strings
      or integers - if strings are passed, internal mapping dictionaries are
      used to convert them to integers.

      The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
      mirror the values defined in the ``sys/syslog.h`` header file.

      **Priorities**

      +--------------------------+---------------+
      | Name (string)            | Symbolic value|
      +==========================+===============+
      | ``alert``                | LOG_ALERT     |
      +--------------------------+---------------+
      | ``crit`` or ``critical`` | LOG_CRIT      |
      +--------------------------+---------------+
      | ``debug``                | LOG_DEBUG     |
      +--------------------------+---------------+
      | ``emerg`` or ``panic``   | LOG_EMERG     |
      +--------------------------+---------------+
      | ``err`` or ``error``     | LOG_ERR       |
      +--------------------------+---------------+
      | ``info``                 | LOG_INFO      |
      +--------------------------+---------------+
      | ``notice``               | LOG_NOTICE    |
      +--------------------------+---------------+
      | ``warn`` or ``warning``  | LOG_WARNING   |
      +--------------------------+---------------+

      **Facilities**

      +---------------+---------------+
      | Name (string) | Symbolic value|
      +===============+===============+
      | ``auth``      | LOG_AUTH      |
      +---------------+---------------+
      | ``authpriv``  | LOG_AUTHPRIV  |
      +---------------+---------------+
      | ``cron``      | LOG_CRON      |
      +---------------+---------------+
      | ``daemon``    | LOG_DAEMON    |
      +---------------+---------------+
      | ``ftp``       | LOG_FTP       |
      +---------------+---------------+
      | ``kern``      | LOG_KERN      |
      +---------------+---------------+
      | ``lpr``       | LOG_LPR       |
      +---------------+---------------+
      | ``mail``      | LOG_MAIL      |
      +---------------+---------------+
      | ``news``      | LOG_NEWS      |
      +---------------+---------------+
      | ``syslog``    | LOG_SYSLOG    |
      +---------------+---------------+
      | ``user``      | LOG_USER      |
      +---------------+---------------+
      | ``uucp``      | LOG_UUCP      |
      +---------------+---------------+
      | ``local0``    | LOG_LOCAL0    |
      +---------------+---------------+
      | ``local1``    | LOG_LOCAL1    |
      +---------------+---------------+
      | ``local2``    | LOG_LOCAL2    |
      +---------------+---------------+
      | ``local3``    | LOG_LOCAL3    |
      +---------------+---------------+
      | ``local4``    | LOG_LOCAL4    |
      +---------------+---------------+
      | ``local5``    | LOG_LOCAL5    |
      +---------------+---------------+
      | ``local6``    | LOG_LOCAL6    |
      +---------------+---------------+
      | ``local7``    | LOG_LOCAL7    |
      +---------------+---------------+

   .. method:: mapPriority(levelname)

      Maps a logging level name to a syslog priority name.
      You may need to override this if you are using custom levels, or
      if the default algorithm is not suitable for your needs. The
      default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
      ``CRITICAL`` to the equivalent syslog names, and all other level
      names to 'warning'.

.. _nt-eventlog-handler:

NTEventLogHandler
^^^^^^^^^^^^^^^^^

The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
module, supports sending logging messages to a local Windows NT, Windows 2000 or
Windows XP event log. Before you can use it, you need Mark Hammond's Win32
extensions for Python installed.


.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')

   Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
   used to define the application name as it appears in the event log. An
   appropriate registry entry is created using this name. The *dllname* should give
   the fully qualified pathname of a .dll or .exe which contains message
   definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
   - this is installed with the Win32 extensions and contains some basic
   placeholder message definitions. Note that use of these placeholders will make
   your event logs big, as the entire message source is held in the log. If you
   want slimmer logs, you have to pass in the name of your own .dll or .exe which
   contains the message definitions you want to use in the event log). The
   *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
   defaults to ``'Application'``.


   .. method:: close()

      At this point, you can remove the application name from the registry as a
      source of event log entries. However, if you do this, you will not be able
      to see the events as you intended in the Event Log Viewer - it needs to be
      able to access the registry to get the .dll name. The current version does
      not do this.


   .. method:: emit(record)

      Determines the message ID, event category and event type, and then logs
      the message in the NT event log.


   .. method:: getEventCategory(record)

      Returns the event category for the record. Override this if you want to
      specify your own categories. This version returns 0.


   .. method:: getEventType(record)

      Returns the event type for the record. Override this if you want to
      specify your own types. This version does a mapping using the handler's
      typemap attribute, which is set up in :meth:`__init__` to a dictionary
      which contains mappings for :const:`DEBUG`, :const:`INFO`,
      :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
      your own levels, you will either need to override this method or place a
      suitable dictionary in the handler's *typemap* attribute.


   .. method:: getMessageID(record)

      Returns the message ID for the record. If you are using your own messages,
      you could do this by having the *msg* passed to the logger being an ID
      rather than a format string. Then, in here, you could use a dictionary
      lookup to get the message ID. This version returns 1, which is the base
      message ID in :file:`win32service.pyd`.

.. _smtp-handler:

SMTPHandler
^^^^^^^^^^^

The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
supports sending logging messages to an email address via SMTP.


.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None, secure=None)

   Returns a new instance of the :class:`SMTPHandler` class. The instance is
   initialized with the from and to addresses and subject line of the email.
   The *toaddrs* should be a list of strings. To specify a non-standard SMTP
   port, use the (host, port) tuple format for the *mailhost* argument. If you
   use a string, the standard SMTP port is used. If your SMTP server requires
   authentication, you can specify a (username, password) tuple for the
   *credentials* argument.

   To specify the use of a secure protocol (TLS), pass in a tuple to the
   *secure* argument. This will only be used when authentication credentials are
   supplied. The tuple should be either an empty tuple, or a single-value tuple
   with the name of a keyfile, or a 2-value tuple with the names of the keyfile
   and certificate file. (This tuple is passed to the
   :meth:`smtplib.SMTP.starttls` method.)

   .. versionchanged:: 2.6
      *credentials* was added.

   .. versionchanged:: 2.7
      *secure* was added.


   .. method:: emit(record)

      Formats the record and sends it to the specified addressees.


   .. method:: getSubject(record)

      If you want to specify a subject line which is record-dependent, override
      this method.

.. _memory-handler:

MemoryHandler
^^^^^^^^^^^^^

The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
supports buffering of logging records in memory, periodically flushing them to a
:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
event of a certain severity or greater is seen.

:class:`MemoryHandler` is a subclass of the more general
:class:`BufferingHandler`, which is an abstract class. This buffers logging
records in memory. Whenever each record is added to the buffer, a check is made
by calling :meth:`shouldFlush` to see if the buffer should be flushed.  If it
should, then :meth:`flush` is expected to do the flushing.


.. class:: BufferingHandler(capacity)

   Initializes the handler with a buffer of the specified capacity.


   .. method:: emit(record)

      Appends the record to the buffer. If :meth:`shouldFlush` returns true,
      calls :meth:`flush` to process the buffer.


   .. method:: flush()

      You can override this to implement custom flushing behavior. This version
      just zaps the buffer to empty.


   .. method:: shouldFlush(record)

      Returns true if the buffer is up to capacity. This method can be
      overridden to implement custom flushing strategies.


.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)

   Returns a new instance of the :class:`MemoryHandler` class. The instance is
   initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
   :const:`ERROR` is used. If no *target* is specified, the target will need to be
   set using :meth:`setTarget` before this handler does anything useful.


   .. method:: close()

      Calls :meth:`flush`, sets the target to :const:`None` and clears the
      buffer.


   .. method:: flush()

      For a :class:`MemoryHandler`, flushing means just sending the buffered
      records to the target, if there is one. The buffer is also cleared when
      this happens. Override if you want different behavior.


   .. method:: setTarget(target)

      Sets the target handler for this handler.


   .. method:: shouldFlush(record)

      Checks for buffer full or a record at the *flushLevel* or higher.


.. _http-handler:

HTTPHandler
^^^^^^^^^^^

The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
supports sending logging messages to a Web server, using either ``GET`` or
``POST`` semantics.


.. class:: HTTPHandler(host, url, method='GET')

   Returns a new instance of the :class:`HTTPHandler` class. The ``host`` can be
   of the form ``host:port``, should you need to use a specific port number.

   .. method:: mapLogRecord(record)

      Provides a dictionary, based on ``record``, which is to be URL-encoded
      and sent to the web server. The default implementation just returns
      ``record.__dict__``. This method can be overridden if e.g. only a
      subset of :class:`~logging.LogRecord` is to be sent to the web server, or
      if more specific customization of what's sent to the server is required.

   .. method:: emit(record)

      Sends the record to the Web server as a URL-encoded dictionary. The
      :meth:`mapLogRecord` method is used to convert the record to the
      dictionary to be sent.

   .. note:: Since preparing a record for sending it to a Web server is not
      the same as a generic formatting operation, using :meth:`setFormatter`
      to specify a :class:`Formatter` for a :class:`HTTPHandler` has no effect.
      Instead of calling :meth:`format`, this handler calls :meth:`mapLogRecord`
      and then :func:`urllib.urlencode` to encode the dictionary in a form
      suitable for sending to a Web server.

.. seealso::

   Module :mod:`logging`
      API reference for the logging module.

   Module :mod:`logging.config`
      Configuration API for the logging module.


PK	%�\��: "�"�%html/_sources/library/logging.rst.txtnu�[���:mod:`logging` --- Logging facility for Python
==============================================

.. module:: logging
   :synopsis: Flexible event logging system for applications.


.. moduleauthor:: Vinay Sajip <vinay_sajip@red-dove.com>
.. sectionauthor:: Vinay Sajip <vinay_sajip@red-dove.com>


.. index:: pair: Errors; logging

.. sidebar:: Important

   This page contains the API reference information. For tutorial
   information and discussion of more advanced topics, see

   * :ref:`Basic Tutorial <logging-basic-tutorial>`
   * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
   * :ref:`Logging Cookbook <logging-cookbook>`

**Source code:** :source:`Lib/logging/__init__.py`

--------------

.. versionadded:: 2.3

This module defines functions and classes which implement a flexible event
logging system for applications and libraries.

The key benefit of having the logging API provided by a standard library module
is that all Python modules can participate in logging, so your application log
can include your own messages integrated with messages from third-party
modules.

The module provides a lot of functionality and flexibility.  If you are
unfamiliar with logging, the best way to get to grips with it is to see the
tutorials (see the links on the right).

The basic classes defined by the module, together with their functions, are
listed below.

* Loggers expose the interface that application code directly uses.
* Handlers send the log records (created by loggers) to the appropriate
  destination.
* Filters provide a finer grained facility for determining which log records
  to output.
* Formatters specify the layout of log records in the final output.


.. _logger:

Logger Objects
--------------

Loggers have the following attributes and methods.  Note that Loggers are never
instantiated directly, but always through the module-level function
``logging.getLogger(name)``.  Multiple calls to :func:`getLogger` with the same
name will always return a reference to the same Logger object.

The ``name`` is potentially a period-separated hierarchical value, like
``foo.bar.baz`` (though it could also be just plain ``foo``, for example).
Loggers that are further down in the hierarchical list are children of loggers
higher up in the list.  For example, given a logger with a name of ``foo``,
loggers with names of ``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all
descendants of ``foo``.  The logger name hierarchy is analogous to the Python
package hierarchy, and identical to it if you organise your loggers on a
per-module basis using the recommended construction
``logging.getLogger(__name__)``.  That's because in a module, ``__name__``
is the module's name in the Python package namespace.


.. class:: Logger

.. attribute:: Logger.propagate

   If this evaluates to true, events logged to this logger will be passed to the
   handlers of higher level (ancestor) loggers, in addition to any handlers
   attached to this logger. Messages are passed directly to the ancestor
   loggers' handlers - neither the level nor filters of the ancestor loggers in
   question are considered.

   If this evaluates to false, logging messages are not passed to the handlers
   of ancestor loggers.

   The constructor sets this attribute to ``True``.

   .. note:: If you attach a handler to a logger *and* one or more of its
      ancestors, it may emit the same record multiple times. In general, you
      should not need to attach a handler to more than one logger - if you just
      attach it to the appropriate logger which is highest in the logger
      hierarchy, then it will see all events logged by all descendant loggers,
      provided that their propagate setting is left set to ``True``. A common
      scenario is to attach handlers only to the root logger, and to let
      propagation take care of the rest.

.. method:: Logger.setLevel(level)

   Sets the threshold for this logger to *level*. Logging messages which are less
   severe than *level* will be ignored. When a logger is created, the level is set to
   :const:`NOTSET` (which causes all messages to be processed when the logger is
   the root logger, or delegation to the parent when the logger is a non-root
   logger). Note that the root logger is created with level :const:`WARNING`.

   The term 'delegation to the parent' means that if a logger has a level of
   NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
   a level other than NOTSET is found, or the root is reached.

   If an ancestor is found with a level other than NOTSET, then that ancestor's
   level is treated as the effective level of the logger where the ancestor search
   began, and is used to determine how a logging event is handled.

   If the root is reached, and it has a level of NOTSET, then all messages will be
   processed. Otherwise, the root's level will be used as the effective level.

   See :ref:`levels` for a list of levels.


.. method:: Logger.isEnabledFor(lvl)

   Indicates if a message of severity *lvl* would be processed by this logger.
   This method checks first the module-level level set by
   ``logging.disable(lvl)`` and then the logger's effective level as determined
   by :meth:`getEffectiveLevel`.


.. method:: Logger.getEffectiveLevel()

   Indicates the effective level for this logger. If a value other than
   :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
   the hierarchy is traversed towards the root until a value other than
   :const:`NOTSET` is found, and that value is returned. The value returned is
   an integer, typically one of :const:`logging.DEBUG`, :const:`logging.INFO`
   etc.


.. method:: Logger.getChild(suffix)

   Returns a logger which is a descendant to this logger, as determined by the suffix.
   Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
   logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
   convenience method, useful when the parent logger is named using e.g. ``__name__``
   rather than a literal string.

   .. versionadded:: 2.7


.. method:: Logger.debug(msg, *args, **kwargs)

   Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
   message format string, and the *args* are the arguments which are merged into
   *msg* using the string formatting operator. (Note that this means that you can
   use keywords in the format string, together with a single dictionary argument.)

   There are two keyword arguments in *kwargs* which are inspected: *exc_info*
   which, if it does not evaluate as false, causes exception information to be
   added to the logging message. If an exception tuple (in the format returned by
   :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
   is called to get the exception information.

   The second keyword argument is *extra* which can be used to pass a
   dictionary which is used to populate the __dict__ of the LogRecord created for
   the logging event with user-defined attributes. These custom attributes can then
   be used as you like. For example, they could be incorporated into logged
   messages. For example::

      FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
      logging.basicConfig(format=FORMAT)
      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
      logger = logging.getLogger('tcpserver')
      logger.warning('Protocol problem: %s', 'connection reset', extra=d)

   would print something like  ::

      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

   The keys in the dictionary passed in *extra* should not clash with the keys used
   by the logging system. (See the :class:`Formatter` documentation for more
   information on which keys are used by the logging system.)

   If you choose to use these attributes in logged messages, you need to exercise
   some care. In the above example, for instance, the :class:`Formatter` has been
   set up with a format string which expects 'clientip' and 'user' in the attribute
   dictionary of the LogRecord. If these are missing, the message will not be
   logged because a string formatting exception will occur. So in this case, you
   always need to pass the *extra* dictionary with these keys.

   While this might be annoying, this feature is intended for use in specialized
   circumstances, such as multi-threaded servers where the same code executes in
   many contexts, and interesting conditions which arise are dependent on this
   context (such as remote client IP address and authenticated user name, in the
   above example). In such circumstances, it is likely that specialized
   :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.


.. method:: Logger.info(msg, *args, **kwargs)

   Logs a message with level :const:`INFO` on this logger. The arguments are
   interpreted as for :meth:`debug`.


.. method:: Logger.warning(msg, *args, **kwargs)

   Logs a message with level :const:`WARNING` on this logger. The arguments are
   interpreted as for :meth:`debug`.


.. method:: Logger.error(msg, *args, **kwargs)

   Logs a message with level :const:`ERROR` on this logger. The arguments are
   interpreted as for :meth:`debug`.


.. method:: Logger.critical(msg, *args, **kwargs)

   Logs a message with level :const:`CRITICAL` on this logger. The arguments are
   interpreted as for :meth:`debug`.


.. method:: Logger.log(lvl, msg, *args, **kwargs)

   Logs a message with integer level *lvl* on this logger. The other arguments are
   interpreted as for :meth:`debug`.


.. method:: Logger.exception(msg, *args, **kwargs)

   Logs a message with level :const:`ERROR` on this logger. The arguments are
   interpreted as for :meth:`debug`, except that any passed *exc_info* is not
   inspected. Exception info is always added to the logging message. This method
   should only be called from an exception handler.


.. method:: Logger.addFilter(filter)

   Adds the specified filter *filter* to this logger.


.. method:: Logger.removeFilter(filter)

   Removes the specified filter *filter* from this logger.


.. method:: Logger.filter(record)

   Applies this logger's filters to the record and returns a true value if the
   record is to be processed. The filters are consulted in turn, until one of
   them returns a false value. If none of them return a false value, the record
   will be processed (passed to handlers). If one returns a false value, no
   further processing of the record occurs.


.. method:: Logger.addHandler(hdlr)

   Adds the specified handler *hdlr* to this logger.


.. method:: Logger.removeHandler(hdlr)

   Removes the specified handler *hdlr* from this logger.


.. method:: Logger.findCaller()

   Finds the caller's source filename and line number. Returns the filename, line
   number and function name as a 3-element tuple.

   .. versionchanged:: 2.4
      The function name was added. In earlier versions, the filename and line
      number were returned as a 2-element tuple.

.. method:: Logger.handle(record)

   Handles a record by passing it to all handlers associated with this logger and
   its ancestors (until a false value of *propagate* is found). This method is used
   for unpickled records received from a socket, as well as those created locally.
   Logger-level filtering is applied using :meth:`~Logger.filter`.


.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)

   This is a factory method which can be overridden in subclasses to create
   specialized :class:`LogRecord` instances.

   .. versionchanged:: 2.5
      *func* and *extra* were added.


.. _levels:

Logging Levels
--------------

The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.

+--------------+---------------+
| Level        | Numeric value |
+==============+===============+
| ``CRITICAL`` | 50            |
+--------------+---------------+
| ``ERROR``    | 40            |
+--------------+---------------+
| ``WARNING``  | 30            |
+--------------+---------------+
| ``INFO``     | 20            |
+--------------+---------------+
| ``DEBUG``    | 10            |
+--------------+---------------+
| ``NOTSET``   | 0             |
+--------------+---------------+


.. _handler:

Handler Objects
---------------

Handlers have the following attributes and methods. Note that :class:`Handler`
is never instantiated directly; this class acts as a base for more useful
subclasses. However, the :meth:`__init__` method in subclasses needs to call
:meth:`Handler.__init__`.


.. method:: Handler.__init__(level=NOTSET)

   Initializes the :class:`Handler` instance by setting its level, setting the list
   of filters to the empty list and creating a lock (using :meth:`createLock`) for
   serializing access to an I/O mechanism.


.. method:: Handler.createLock()

   Initializes a thread lock which can be used to serialize access to underlying
   I/O functionality which may not be threadsafe.


.. method:: Handler.acquire()

   Acquires the thread lock created with :meth:`createLock`.


.. method:: Handler.release()

   Releases the thread lock acquired with :meth:`acquire`.


.. method:: Handler.setLevel(level)

   Sets the threshold for this handler to *level*. Logging messages which are less
   severe than *level* will be ignored. When a handler is created, the level is set
   to :const:`NOTSET` (which causes all messages to be processed).

   See :ref:`levels` for a list of levels.

.. method:: Handler.setFormatter(fmt)

   Sets the :class:`Formatter` for this handler to *fmt*.


.. method:: Handler.addFilter(filter)

   Adds the specified filter *filter* to this handler.


.. method:: Handler.removeFilter(filter)

   Removes the specified filter *filter* from this handler.


.. method:: Handler.filter(record)

   Applies this handler's filters to the record and returns a true value if the
   record is to be processed. The filters are consulted in turn, until one of
   them returns a false value. If none of them return a false value, the record
   will be emitted. If one returns a false value, the handler will not emit the
   record.


.. method:: Handler.flush()

   Ensure all logging output has been flushed. This version does nothing and is
   intended to be implemented by subclasses.


.. method:: Handler.close()

   Tidy up any resources used by the handler. This version does no output but
   removes the handler from an internal list of handlers which is closed when
   :func:`shutdown` is called. Subclasses should ensure that this gets called
   from overridden :meth:`close` methods.


.. method:: Handler.handle(record)

   Conditionally emits the specified logging record, depending on filters which may
   have been added to the handler. Wraps the actual emission of the record with
   acquisition/release of the I/O thread lock.


.. method:: Handler.handleError(record)

   This method should be called from handlers when an exception is encountered
   during an :meth:`emit` call. If the module-level attribute
   ``raiseExceptions`` is ``False``, exceptions get silently ignored. This is
   what is mostly wanted for a logging system - most users will not care about
   errors in the logging system, they are more interested in application
   errors. You could, however, replace this with a custom handler if you wish.
   The specified record is the one which was being processed when the exception
   occurred. (The default value of ``raiseExceptions`` is ``True``, as that is
   more useful during development).


.. method:: Handler.format(record)

   Do formatting for a record - if a formatter is set, use it. Otherwise, use the
   default formatter for the module.


.. method:: Handler.emit(record)

   Do whatever it takes to actually log the specified logging record. This version
   is intended to be implemented by subclasses and so raises a
   :exc:`NotImplementedError`.

For a list of handlers included as standard, see :mod:`logging.handlers`.

.. _formatter-objects:

Formatter Objects
-----------------

.. currentmodule:: logging

:class:`Formatter` objects have the following attributes and methods. They are
responsible for converting a :class:`LogRecord` to (usually) a string which can
be interpreted by either a human or an external system. The base
:class:`Formatter` allows a formatting string to be specified. If none is
supplied, the default value of ``'%(message)s'`` is used, which just includes
the message in the logging call. To have additional items of information in the
formatted output (such as a timestamp), keep reading.

A Formatter can be initialized with a format string which makes use of knowledge
of the :class:`LogRecord` attributes - such as the default value mentioned above
making use of the fact that the user's message and arguments are pre-formatted
into a :class:`LogRecord`'s *message* attribute.  This format string contains
standard Python %-style mapping keys. See section :ref:`string-formatting`
for more information on string formatting.

The useful mapping keys in a :class:`LogRecord` are given in the section on
:ref:`logrecord-attributes`.


.. class:: Formatter(fmt=None, datefmt=None)

   Returns a new instance of the :class:`Formatter` class.  The instance is
   initialized with a format string for the message as a whole, as well as a
   format string for the date/time portion of a message.  If no *fmt* is
   specified, ``'%(message)s'`` is used.  If no *datefmt* is specified, the
   ISO8601 date format is used.

   .. method:: format(record)

      The record's attribute dictionary is used as the operand to a string
      formatting operation. Returns the resulting string. Before formatting the
      dictionary, a couple of preparatory steps are carried out. The *message*
      attribute of the record is computed using *msg* % *args*. If the
      formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
      to format the event time. If there is exception information, it is
      formatted using :meth:`formatException` and appended to the message. Note
      that the formatted exception information is cached in attribute
      *exc_text*. This is useful because the exception information can be
      pickled and sent across the wire, but you should be careful if you have
      more than one :class:`Formatter` subclass which customizes the formatting
      of exception information. In this case, you will have to clear the cached
      value after a formatter has done its formatting, so that the next
      formatter to handle the event doesn't use the cached value but
      recalculates it afresh.


   .. method:: formatTime(record, datefmt=None)

      This method should be called from :meth:`format` by a formatter which
      wants to make use of a formatted time. This method can be overridden in
      formatters to provide for any specific requirement, but the basic behavior
      is as follows: if *datefmt* (a string) is specified, it is used with
      :func:`time.strftime` to format the creation time of the
      record. Otherwise, the ISO8601 format is used.  The resulting string is
      returned.

      This function uses a user-configurable function to convert the creation
      time to a tuple. By default, :func:`time.localtime` is used; to change
      this for a particular formatter instance, set the ``converter`` attribute
      to a function with the same signature as :func:`time.localtime` or
      :func:`time.gmtime`. To change it for all formatters, for example if you
      want all logging times to be shown in GMT, set the ``converter``
      attribute in the ``Formatter`` class.

   .. method:: formatException(exc_info)

      Formats the specified exception information (a standard exception tuple as
      returned by :func:`sys.exc_info`) as a string. This default implementation
      just uses :func:`traceback.print_exception`. The resulting string is
      returned.

.. _filter:

Filter Objects
--------------

``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
filtering than is provided by levels. The base filter class only allows events
which are below a certain point in the logger hierarchy. For example, a filter
initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C',
'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the
empty string, all events are passed.


.. class:: Filter(name='')

   Returns an instance of the :class:`Filter` class. If *name* is specified, it
   names a logger which, together with its children, will have its events allowed
   through the filter. If *name* is the empty string, allows every event.


   .. method:: filter(record)

      Is the specified record to be logged? Returns zero for no, nonzero for
      yes. If deemed appropriate, the record may be modified in-place by this
      method.

Note that filters attached to handlers are consulted before an event is
emitted by the handler, whereas filters attached to loggers are consulted
whenever an event is logged (using :meth:`debug`, :meth:`info`,
etc.), before sending an event to handlers. This means that events which have
been generated by descendant loggers will not be filtered by a logger's filter
setting, unless the filter has also been applied to those descendant loggers.

You don't actually need to subclass ``Filter``: you can pass any instance
which has a ``filter`` method with the same semantics.

Although filters are used primarily to filter records based on more
sophisticated criteria than levels, they get to see every record which is
processed by the handler or logger they're attached to: this can be useful if
you want to do things like counting how many records were processed by a
particular logger or handler, or adding, changing or removing attributes in
the LogRecord being processed. Obviously changing the LogRecord needs to be
done with some care, but it does allow the injection of contextual information
into logs (see :ref:`filters-contextual`).

.. _log-record:

LogRecord Objects
-----------------

:class:`LogRecord` instances are created automatically by the :class:`Logger`
every time something is logged, and can be created manually via
:func:`makeLogRecord` (for example, from a pickled event received over the
wire).


.. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None)

   Contains all the information pertinent to the event being logged.

   The primary information is passed in :attr:`msg` and :attr:`args`, which
   are combined using ``msg % args`` to create the :attr:`message` field of the
   record.

   :param name:  The name of the logger used to log the event represented by
                 this LogRecord. Note that this name will always have this
                 value, even though it may be emitted by a handler attached to
                 a different (ancestor) logger.
   :param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
                 Note that this is converted to *two* attributes of the LogRecord:
                 ``levelno`` for the numeric value and ``levelname`` for the
                 corresponding level name.
   :param pathname: The full pathname of the source file where the logging call
                    was made.
   :param lineno: The line number in the source file where the logging call was
                  made.
   :param msg: The event description message, possibly a format string with
               placeholders for variable data.
   :param args: Variable data to merge into the *msg* argument to obtain the
                event description.
   :param exc_info: An exception tuple with the current exception information,
                    or ``None`` if no exception information is available.
   :param func: The name of the function or method from which the logging call
                was invoked.

   .. versionchanged:: 2.5
      *func* was added.

   .. method:: getMessage()

      Returns the message for this :class:`LogRecord` instance after merging any
      user-supplied arguments with the message. If the user-supplied message
      argument to the logging call is not a string, :func:`str` is called on it to
      convert it to a string. This allows use of user-defined classes as
      messages, whose ``__str__`` method can return the actual format string to
      be used.


.. _logrecord-attributes:

LogRecord attributes
--------------------

The LogRecord has a number of attributes, most of which are derived from the
parameters to the constructor. (Note that the names do not always correspond
exactly between the LogRecord constructor parameters and the LogRecord
attributes.) These attributes can be used to merge data from the record into
the format string. The following table lists (in alphabetical order) the
attribute names, their meanings and the corresponding placeholder in a %-style
format string.

+----------------+-------------------------+-----------------------------------------------+
| Attribute name | Format                  | Description                                   |
+================+=========================+===============================================+
| args           | You shouldn't need to   | The tuple of arguments merged into ``msg`` to |
|                | format this yourself.   | produce ``message``, or a dict whose values   |
|                |                         | are used for the merge (when there is only one|
|                |                         | argument, and it is a dictionary).            |
+----------------+-------------------------+-----------------------------------------------+
| asctime        | ``%(asctime)s``         | Human-readable time when the                  |
|                |                         | :class:`LogRecord` was created.  By default   |
|                |                         | this is of the form '2003-07-08 16:49:45,896' |
|                |                         | (the numbers after the comma are millisecond  |
|                |                         | portion of the time).                         |
+----------------+-------------------------+-----------------------------------------------+
| created        | ``%(created)f``         | Time when the :class:`LogRecord` was created  |
|                |                         | (as returned by :func:`time.time`).           |
+----------------+-------------------------+-----------------------------------------------+
| exc_info       | You shouldn't need to   | Exception tuple (à la ``sys.exc_info``) or,   |
|                | format this yourself.   | if no exception has occurred, ``None``.       |
+----------------+-------------------------+-----------------------------------------------+
| filename       | ``%(filename)s``        | Filename portion of ``pathname``.             |
+----------------+-------------------------+-----------------------------------------------+
| funcName       | ``%(funcName)s``        | Name of function containing the logging call. |
+----------------+-------------------------+-----------------------------------------------+
| levelname      | ``%(levelname)s``       | Text logging level for the message            |
|                |                         | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
|                |                         | ``'ERROR'``, ``'CRITICAL'``).                 |
+----------------+-------------------------+-----------------------------------------------+
| levelno        | ``%(levelno)s``         | Numeric logging level for the message         |
|                |                         | (:const:`DEBUG`, :const:`INFO`,               |
|                |                         | :const:`WARNING`, :const:`ERROR`,             |
|                |                         | :const:`CRITICAL`).                           |
+----------------+-------------------------+-----------------------------------------------+
| lineno         | ``%(lineno)d``          | Source line number where the logging call was |
|                |                         | issued (if available).                        |
+----------------+-------------------------+-----------------------------------------------+
| module         | ``%(module)s``          | Module (name portion of ``filename``).        |
+----------------+-------------------------+-----------------------------------------------+
| msecs          | ``%(msecs)d``           | Millisecond portion of the time when the      |
|                |                         | :class:`LogRecord` was created.               |
+----------------+-------------------------+-----------------------------------------------+
| message        | ``%(message)s``         | The logged message, computed as ``msg %       |
|                |                         | args``. This is set when                      |
|                |                         | :meth:`Formatter.format` is invoked.          |
+----------------+-------------------------+-----------------------------------------------+
| msg            | You shouldn't need to   | The format string passed in the original      |
|                | format this yourself.   | logging call. Merged with ``args`` to         |
|                |                         | produce ``message``, or an arbitrary object   |
|                |                         | (see :ref:`arbitrary-object-messages`).       |
+----------------+-------------------------+-----------------------------------------------+
| name           | ``%(name)s``            | Name of the logger used to log the call.      |
+----------------+-------------------------+-----------------------------------------------+
| pathname       | ``%(pathname)s``        | Full pathname of the source file where the    |
|                |                         | logging call was issued (if available).       |
+----------------+-------------------------+-----------------------------------------------+
| process        | ``%(process)d``         | Process ID (if available).                    |
+----------------+-------------------------+-----------------------------------------------+
| processName    | ``%(processName)s``     | Process name (if available).                  |
+----------------+-------------------------+-----------------------------------------------+
| relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was   |
|                |                         | created, relative to the time the logging     |
|                |                         | module was loaded.                            |
+----------------+-------------------------+-----------------------------------------------+
| thread         | ``%(thread)d``          | Thread ID (if available).                     |
+----------------+-------------------------+-----------------------------------------------+
| threadName     | ``%(threadName)s``      | Thread name (if available).                   |
+----------------+-------------------------+-----------------------------------------------+

.. versionchanged:: 2.5
   *funcName* was added.

.. versionchanged:: 2.6
   *processName* was added.

.. _logger-adapter:

LoggerAdapter Objects
---------------------

:class:`LoggerAdapter` instances are used to conveniently pass contextual
information into logging calls. For a usage example, see the section on
:ref:`adding contextual information to your logging output <context-info>`.

.. versionadded:: 2.6


.. class:: LoggerAdapter(logger, extra)

   Returns an instance of :class:`LoggerAdapter` initialized with an
   underlying :class:`Logger` instance and a dict-like object.

   .. method:: process(msg, kwargs)

      Modifies the message and/or keyword arguments passed to a logging call in
      order to insert contextual information. This implementation takes the object
      passed as *extra* to the constructor and adds it to *kwargs* using key
      'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
      (possibly modified) versions of the arguments passed in.

In addition to the above, :class:`LoggerAdapter` supports the following
methods of :class:`Logger`: :meth:`~Logger.debug`, :meth:`~Logger.info`,
:meth:`~Logger.warning`, :meth:`~Logger.error`, :meth:`~Logger.exception`,
:meth:`~Logger.critical`, :meth:`~Logger.log` and :meth:`~Logger.isEnabledFor`.
These methods have the same signatures as their counterparts in :class:`Logger`,
so you can use the two types of instances interchangeably for these calls.

.. versionchanged:: 2.7
   The :meth:`~Logger.isEnabledFor` method was added to :class:`LoggerAdapter`.
   This method delegates to the underlying logger.


Thread Safety
-------------

The logging module is intended to be thread-safe without any special work
needing to be done by its clients. It achieves this though using threading
locks; there is one lock to serialize access to the module's shared data, and
each handler also creates a lock to serialize access to its underlying I/O.

If you are implementing asynchronous signal handlers using the :mod:`signal`
module, you may not be able to use logging from within such handlers. This is
because lock implementations in the :mod:`threading` module are not always
re-entrant, and so cannot be invoked from such signal handlers.


Module-Level Functions
----------------------

In addition to the classes described above, there are a number of module- level
functions.


.. function:: getLogger([name])

   Return a logger with the specified name or, if no name is specified, return a
   logger which is the root logger of the hierarchy. If specified, the name is
   typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
   Choice of these names is entirely up to the developer who is using logging.

   All calls to this function with a given name return the same logger instance.
   This means that logger instances never need to be passed between different parts
   of an application.


.. function:: getLoggerClass()

   Return either the standard :class:`Logger` class, or the last class passed to
   :func:`setLoggerClass`. This function may be called from within a new class
   definition, to ensure that installing a customized :class:`Logger` class will
   not undo customizations already applied by other code. For example::

      class MyLogger(logging.getLoggerClass()):
          # ... override behaviour here


.. function:: debug(msg[, *args[, **kwargs]])

   Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
   message format string, and the *args* are the arguments which are merged into
   *msg* using the string formatting operator. (Note that this means that you can
   use keywords in the format string, together with a single dictionary argument.)

   There are two keyword arguments in *kwargs* which are inspected: *exc_info*
   which, if it does not evaluate as false, causes exception information to be
   added to the logging message. If an exception tuple (in the format returned by
   :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
   is called to get the exception information.

   The other optional keyword argument is *extra* which can be used to pass a
   dictionary which is used to populate the __dict__ of the LogRecord created for
   the logging event with user-defined attributes. These custom attributes can then
   be used as you like. For example, they could be incorporated into logged
   messages. For example::

      FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
      logging.basicConfig(format=FORMAT)
      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
      logging.warning("Protocol problem: %s", "connection reset", extra=d)

   would print something like::

      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

   The keys in the dictionary passed in *extra* should not clash with the keys used
   by the logging system. (See the :class:`Formatter` documentation for more
   information on which keys are used by the logging system.)

   If you choose to use these attributes in logged messages, you need to exercise
   some care. In the above example, for instance, the :class:`Formatter` has been
   set up with a format string which expects 'clientip' and 'user' in the attribute
   dictionary of the LogRecord. If these are missing, the message will not be
   logged because a string formatting exception will occur. So in this case, you
   always need to pass the *extra* dictionary with these keys.

   While this might be annoying, this feature is intended for use in specialized
   circumstances, such as multi-threaded servers where the same code executes in
   many contexts, and interesting conditions which arise are dependent on this
   context (such as remote client IP address and authenticated user name, in the
   above example). In such circumstances, it is likely that specialized
   :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.

   .. versionchanged:: 2.5
      *extra* was added.


.. function:: info(msg[, *args[, **kwargs]])

   Logs a message with level :const:`INFO` on the root logger. The arguments are
   interpreted as for :func:`debug`.


.. function:: warning(msg[, *args[, **kwargs]])

   Logs a message with level :const:`WARNING` on the root logger. The arguments are
   interpreted as for :func:`debug`.


.. function:: error(msg[, *args[, **kwargs]])

   Logs a message with level :const:`ERROR` on the root logger. The arguments are
   interpreted as for :func:`debug`.


.. function:: critical(msg[, *args[, **kwargs]])

   Logs a message with level :const:`CRITICAL` on the root logger. The arguments
   are interpreted as for :func:`debug`.


.. function:: exception(msg[, *args[, **kwargs]])

   Logs a message with level :const:`ERROR` on the root logger. The arguments are
   interpreted as for :func:`debug`, except that any passed *exc_info* is not
   inspected. Exception info is always added to the logging message. This
   function should only be called from an exception handler.


.. function:: log(level, msg[, *args[, **kwargs]])

   Logs a message with level *level* on the root logger. The other arguments are
   interpreted as for :func:`debug`.

   .. note:: The above module-level convenience functions, which delegate to the
      root logger, call :func:`basicConfig` to ensure that at least one handler
      is available. Because of this, they should *not* be used in threads,
      in versions of Python earlier than 2.7.1 and 3.2, unless at least one
      handler has been added to the root logger *before* the threads are
      started. In earlier versions of Python, due to a thread safety shortcoming
      in :func:`basicConfig`, this can (under rare circumstances) lead to
      handlers being added multiple times to the root logger, which can in turn
      lead to multiple messages for the same event.

.. function:: disable(lvl)

   Provides an overriding level *lvl* for all loggers which takes precedence over
   the logger's own level. When the need arises to temporarily throttle logging
   output down across the whole application, this function can be useful. Its
   effect is to disable all logging calls of severity *lvl* and below, so that
   if you call it with a value of INFO, then all INFO and DEBUG events would be
   discarded, whereas those of severity WARNING and above would be processed
   according to the logger's effective level. If
   ``logging.disable(logging.NOTSET)`` is called, it effectively removes this
   overriding level, so that logging output again depends on the effective
   levels of individual loggers.


.. function:: addLevelName(lvl, levelName)

   Associates level *lvl* with text *levelName* in an internal dictionary, which is
   used to map numeric levels to a textual representation, for example when a
   :class:`Formatter` formats a message. This function can also be used to define
   your own levels. The only constraints are that all levels used must be
   registered using this function, levels should be positive integers and they
   should increase in increasing order of severity.

   .. note:: If you are thinking of defining your own levels, please see the
      section on :ref:`custom-levels`.

.. function:: getLevelName(lvl)

   Returns the textual representation of logging level *lvl*. If the level is one
   of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
   :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
   have associated levels with names using :func:`addLevelName` then the name you
   have associated with *lvl* is returned. If a numeric value corresponding to one
   of the defined levels is passed in, the corresponding string representation is
   returned. Otherwise, the string "Level %s" % lvl is returned.

   .. note:: Integer levels should be used when e.g. setting levels on instances
      of :class:`Logger` and handlers. This function is used to convert between
      an integer level and the level name displayed in the formatted log output
      by means of the ``%(levelname)s`` format specifier (see
      :ref:`logrecord-attributes`).


.. function:: makeLogRecord(attrdict)

   Creates and returns a new :class:`LogRecord` instance whose attributes are
   defined by *attrdict*. This function is useful for taking a pickled
   :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
   it as a :class:`LogRecord` instance at the receiving end.


.. function:: basicConfig([**kwargs])

   Does basic configuration for the logging system by creating a
   :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
   root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
   :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
   if no handlers are defined for the root logger.

   This function does nothing if the root logger already has handlers
   configured for it.

   .. versionchanged:: 2.4
      Formerly, :func:`basicConfig` did not take any keyword arguments.

   .. note:: This function should be called from the main thread before other
      threads are started. In versions of Python prior to 2.7.1 and 3.2, if
      this function is called from multiple threads, it is possible (in rare
      circumstances) that a handler will be added to the root logger more than
      once, leading to unexpected results such as messages being duplicated in
      the log.

   The following keyword arguments are supported.

   .. tabularcolumns:: |l|L|

   +--------------+---------------------------------------------+
   | Format       | Description                                 |
   +==============+=============================================+
   | *filename*   | Specifies that a FileHandler be created,    |
   |              | using the specified filename, rather than a |
   |              | StreamHandler.                              |
   +--------------+---------------------------------------------+
   | *filemode*   | If *filename* is specified, open the file   |
   |              | in this mode. Defaults to ``'a'``.          |
   +--------------+---------------------------------------------+
   | *format*     | Use the specified format string for the     |
   |              | handler.                                    |
   +--------------+---------------------------------------------+
   | *datefmt*    | Use the specified date/time format, as      |
   |              | accepted by :func:`time.strftime`.          |
   +--------------+---------------------------------------------+
   | *level*      | Set the root logger level to the specified  |
   |              | :ref:`level <levels>`.                      |
   +--------------+---------------------------------------------+
   | *stream*     | Use the specified stream to initialize the  |
   |              | StreamHandler. Note that this argument is   |
   |              | incompatible with *filename* - if both are  |
   |              | present, *stream* is ignored.               |
   +--------------+---------------------------------------------+


.. function:: shutdown()

   Informs the logging system to perform an orderly shutdown by flushing and
   closing all handlers. This should be called at application exit and no
   further use of the logging system should be made after this call.


.. function:: setLoggerClass(klass)

   Tells the logging system to use the class *klass* when instantiating a logger.
   The class should define :meth:`__init__` such that only a name argument is
   required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
   function is typically called before any loggers are instantiated by applications
   which need to use custom logger behavior.


Integration with the warnings module
------------------------------------

The :func:`captureWarnings` function can be used to integrate :mod:`logging`
with the :mod:`warnings` module.

.. function:: captureWarnings(capture)

   This function is used to turn the capture of warnings by logging on and
   off.

   If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
   be redirected to the logging system. Specifically, a warning will be
   formatted using :func:`warnings.formatwarning` and the resulting string
   logged to a logger named ``'py.warnings'`` with a severity of :const:`WARNING`.

   If *capture* is ``False``, the redirection of warnings to the logging system
   will stop, and warnings will be redirected to their original destinations
   (i.e. those in effect before ``captureWarnings(True)`` was called).


.. seealso::

   Module :mod:`logging.config`
      Configuration API for the logging module.

   Module :mod:`logging.handlers`
      Useful handlers included with the logging module.

   :pep:`282` - A Logging System
      The proposal which described this feature for inclusion in the Python standard
      library.

   `Original Python logging package <https://www.red-dove.com/python_logging.html>`_
      This is the original source for the :mod:`logging` package.  The version of the
      package available from this site is suitable for use with Python 1.5.2, 2.1.x
      and 2.2.x, which do not include the :mod:`logging` package in the standard
      library.

PK	%�\xi��!html/_sources/library/mac.rst.txtnu�[���.. _mac-specific-services:

**************************
Mac OS X specific services
**************************

This chapter describes modules that are only available on the Mac OS X platform.

See the chapters :ref:`mac-scripting` and :ref:`undoc-mac-modules` for more
modules, and the HOWTO :ref:`using-on-mac` for a general introduction to
Mac-specific Python programming.

.. note::

   Most of the OS X APIs that these modules use are deprecated or removed
   in recent versions of OS X.  Many are not available when Python is
   executing in 64-bit mode.  These modules have been removed in
   Python 3.  You should avoid using them in Python 2.


.. toctree::

   ic.rst
   macos.rst
   macostools.rst
   easydialogs.rst
   framework.rst
   autogil.rst
   carbon.rst
   colorpicker.rst
PK	%�\&�?��#html/_sources/library/macos.rst.txtnu�[���:mod:`MacOS` --- Access to Mac OS interpreter features
======================================================

.. module:: MacOS
   :platform: Mac
   :synopsis: Access to Mac OS-specific interpreter features.
   :deprecated:


This module provides access to MacOS specific functionality in the Python
interpreter, such as how the interpreter eventloop functions and the like. Use
with care.

.. note::

   This module has been removed in Python 3.x.

Note the capitalization of the module name; this is a historical artifact.


.. data:: runtimemodel

   Always ``'macho'``, from Python 2.4 on. In earlier versions of Python the value
   could also be ``'ppc'`` for the classic Mac OS 8 runtime model or ``'carbon'``
   for the Mac OS 9 runtime model.


.. data:: linkmodel

   The way the interpreter has been linked. As extension modules may be
   incompatible between linking models, packages could use this information to give
   more decent error messages. The value is one of ``'static'`` for a statically
   linked Python, ``'framework'`` for Python in a Mac OS X framework, ``'shared'``
   for Python in a standard Unix shared library. Older Pythons could also have the
   value ``'cfm'`` for Mac OS 9-compatible Python.


.. exception:: Error

   .. index:: module: macerrors

   This exception is raised on MacOS generated errors, either from functions in
   this module or from other mac-specific modules like the toolbox interfaces. The
   arguments are the integer error code (the :c:data:`OSErr` value) and a textual
   description of the error code. Symbolic names for all known error codes are
   defined in the standard module :mod:`macerrors`.


.. function:: GetErrorString(errno)

   Return the textual description of MacOS error code *errno*.


.. function:: DebugStr(message [, object])

   On Mac OS X the string is simply printed to stderr (on older Mac OS systems more
   elaborate functionality was available), but it provides a convenient location to
   attach a breakpoint in a low-level debugger like :program:`gdb`.

   .. note::

      Not available in 64-bit mode.


.. function:: SysBeep()

   Ring the bell.

   .. note::

      Not available in 64-bit mode.


.. function:: GetTicks()

   Get the number of clock ticks (1/60th of a second) since system boot.


.. function:: GetCreatorAndType(file)

   Return the file creator and file type as two four-character strings. The *file*
   parameter can be a pathname or an ``FSSpec`` or  ``FSRef`` object.

   .. note::

      It is not possible to use an ``FSSpec`` in 64-bit mode.


.. function:: SetCreatorAndType(file, creator, type)

   Set the file creator and file type. The *file* parameter can be a pathname or an
   ``FSSpec`` or  ``FSRef`` object. *creator* and *type* must be four character
   strings.

   .. note::

      It is not possible to use an ``FSSpec`` in 64-bit mode.

.. function:: openrf(name [, mode])

   Open the resource fork of a file. Arguments are the same as for the built-in
   function :func:`open`. The object returned has file-like semantics, but it is
   not a Python file object, so there may be subtle differences.


.. function:: WMAvailable()

   Checks whether the current process has access to the window manager. The method
   will return ``False`` if the window manager is not available, for instance when
   running on Mac OS X Server or when logged in via ssh, or when the current
   interpreter is not running from a fullblown application bundle. A script runs
   from an application bundle either when it has been started with
   :program:`pythonw` instead of :program:`python` or when running  as an applet.

.. function:: splash([resourceid])

   Opens a splash screen by resource id. Use resourceid ``0`` to close
   the splash screen.

   .. note::

      Not available in 64-bit mode.

PK	%�\��z||$html/_sources/library/macosa.rst.txtnu�[���
.. _mac-scripting:

*********************
MacPython OSA Modules
*********************

This chapter describes the current implementation of the Open Scripting
Architecture (OSA, also commonly referred to as AppleScript) for Python,
allowing you to control scriptable applications from your Python program,
and with a fairly pythonic interface. Development on this set of modules has
stopped.

For a description of the various components of AppleScript and OSA, and to get
an understanding of the architecture and terminology, you should read Apple's
documentation. The "Applescript Language Guide" explains the conceptual model
and the terminology, and documents the standard suite. The "Open Scripting
Architecture" document explains how to use OSA from an application programmers
point of view. In the Apple Help Viewer these books are located in the Developer
Documentation, Core Technologies section.

As an example of scripting an application, the following piece of AppleScript
will get the name of the frontmost :program:`Finder` window and print it::

   tell application "Finder"
       get name of window 1
   end tell

In Python, the following code fragment will do the same::

   import Finder

   f = Finder.Finder()
   print f.get(f.window(1).name)

As distributed the Python library includes packages that implement the standard
suites, plus packages that interface to a small number of common applications.

To send AppleEvents to an application you must first create the Python package
interfacing to the terminology of the application (what :program:`Script Editor`
calls the "Dictionary"). This can be done from within the :program:`PythonIDE`
or by running the :file:`gensuitemodule.py` module as a standalone program from
the command line.

The generated output is a package with a number of modules, one for every suite
used in the program plus an :mod:`__init__` module to glue it all together. The
Python inheritance graph follows the AppleScript inheritance graph, so if a
program's dictionary specifies that it includes support for the Standard Suite,
but extends one or two verbs with extra arguments then the output suite will
contain a module :mod:`Standard_Suite` that imports and re-exports everything
from :mod:`StdSuites.Standard_Suite` but overrides the methods that have extra
functionality. The output of :mod:`gensuitemodule` is pretty readable, and
contains the documentation that was in the original AppleScript dictionary in
Python docstrings, so reading it is a good source of documentation.

The output package implements a main class with the same name as the package
which contains all the AppleScript verbs as methods, with the direct object as
the first argument and all optional parameters as keyword arguments. AppleScript
classes are also implemented as Python classes, as are comparisons and all the
other thingies.

The main Python class implementing the verbs also allows access to the
properties and elements declared in the AppleScript class "application". In the
current release that is as far as the object orientation goes, so in the example
above we need to use ``f.get(f.window(1).name)`` instead of the more Pythonic
``f.window(1).name.get()``.

If an AppleScript identifier is not a Python identifier the name is mangled
according to a small number of rules:

* spaces are replaced with underscores

* other non-alphanumeric characters are replaced with ``_xx_`` where ``xx`` is
  the hexadecimal character value

* any Python reserved word gets an underscore appended

Python also has support for creating scriptable applications in Python, but The
following modules are relevant to MacPython AppleScript support:

.. toctree::

   gensuitemodule.rst
   aetools.rst
   aepack.rst
   aetypes.rst
   miniaeframe.rst


In addition, support modules have been pre-generated for :mod:`Finder`,
:mod:`Terminal`, :mod:`Explorer`, :mod:`Netscape`, :mod:`CodeWarrior`,
:mod:`SystemEvents` and :mod:`StdSuites`.
PK	%�\���(html/_sources/library/macostools.rst.txtnu�[���
:mod:`macostools` --- Convenience routines for file manipulation
================================================================

.. module:: macostools
   :platform: Mac
   :synopsis: Convenience routines for file manipulation.
   :deprecated:


This module contains some convenience routines for file-manipulation on the
Macintosh. All file parameters can be specified as pathnames, :class:`FSRef` or
:class:`FSSpec` objects.  This module expects a filesystem which supports forked
files, so it should not be used on UFS partitions.

.. note::

   This module has been removed in Python 3.



The :mod:`macostools` module defines the following functions:


.. function:: copy(src, dst[, createpath[, copytimes]])

   Copy file *src* to *dst*.  If *createpath* is non-zero the folders leading to
   *dst* are created if necessary. The method copies data and resource fork and
   some finder information (creator, type, flags) and optionally the creation,
   modification and backup times (default is to copy them). Custom icons, comments
   and icon position are not copied.

   .. note::

      This function does not work in 64-bit code because it uses APIs that
      are not available in 64-bit mode.

.. function:: copytree(src, dst)

   Recursively copy a file tree from *src* to *dst*, creating folders as needed.
   *src* and *dst* should be specified as pathnames.

   .. note::

      This function does not work in 64-bit code because it uses APIs that
      are not available in 64-bit mode.

.. function:: mkalias(src, dst)

   Create a finder alias *dst* pointing to *src*.

   .. note::

      This function does not work in 64-bit code because it uses APIs that
      are not available in 64-bit mode.


.. function:: touched(dst)

   Tell the finder that some bits of finder-information such as creator or type for
   file *dst* has changed. The file can be specified by pathname or fsspec. This
   call should tell the finder to redraw the files icon.

   .. deprecated:: 2.6
      The function is a no-op on OS X.


.. data:: BUFSIZ

   The buffer size for ``copy``, default 1 megabyte.

Note that the process of creating finder aliases is not specified in the Apple
documentation. Hence, aliases created with :func:`mkalias` could conceivably
have incompatible behaviour in some cases.


:mod:`findertools` --- The :program:`finder`'s Apple Events interface
======================================================================

.. module:: findertools
   :platform: Mac
   :synopsis: Wrappers around the finder's Apple Events interface.


.. index:: single: AppleEvents

This module contains routines that give Python programs access to some
functionality provided by the finder. They are implemented as wrappers around
the AppleEvent interface to the finder.

All file and folder parameters can be specified either as full pathnames, or as
:class:`FSRef` or :class:`FSSpec` objects.

The :mod:`findertools` module defines the following functions:


.. function:: launch(file)

   Tell the finder to launch *file*. What launching means depends on the file:
   applications are started, folders are opened and documents are opened in the
   correct application.


.. function:: Print(file)

   Tell the finder to print a file. The behaviour is identical to selecting the
   file and using the print command in the finder's file menu.


.. function:: copy(file, destdir)

   Tell the finder to copy a file or folder *file* to folder *destdir*. The
   function returns an :class:`Alias` object pointing to the new file.


.. function:: move(file, destdir)

   Tell the finder to move a file or folder *file* to folder *destdir*. The
   function returns an :class:`Alias` object pointing to the new file.


.. function:: sleep()

   Tell the finder to put the Macintosh to sleep, if your machine supports it.


.. function:: restart()

   Tell the finder to perform an orderly restart of the machine.


.. function:: shutdown()

   Tell the finder to perform an orderly shutdown of the machine.

PK	%�\nZ���%html/_sources/library/macpath.rst.txtnu�[���
:mod:`macpath` --- Mac OS 9 path manipulation functions
=======================================================

.. module:: macpath
   :synopsis: Mac OS 9 path manipulation functions.


This module is the Mac OS 9 (and earlier) implementation of the :mod:`os.path`
module. It can be used to manipulate old-style Macintosh pathnames on Mac OS X
(or any other platform).

The following functions are available in this module: :func:`normcase`,
:func:`normpath`, :func:`isabs`, :func:`join`, :func:`split`, :func:`isdir`,
:func:`isfile`, :func:`walk`, :func:`exists`. For other functions available in
:mod:`os.path` dummy counterparts are available.

PK	%�\veu_!
!
%html/_sources/library/mailbox.rst.txtnu�[���
:mod:`mailbox` --- Manipulate mailboxes in various formats
==========================================================

.. module:: mailbox
   :synopsis: Manipulate mailboxes in various formats
.. moduleauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>
.. sectionauthor:: Gregory K. Johnson <gkj@gregorykjohnson.com>


This module defines two classes, :class:`Mailbox` and :class:`Message`, for
accessing and manipulating on-disk mailboxes and the messages they contain.
:class:`Mailbox` offers a dictionary-like mapping from keys to messages.
:class:`Message` extends the :mod:`email.message` module's
:class:`~email.message.Message` class with format-specific state and behavior.
Supported mailbox formats are
Maildir, mbox, MH, Babyl, and MMDF.


.. seealso::

   Module :mod:`email`
      Represent and manipulate messages.


.. _mailbox-objects:

:class:`Mailbox` objects
------------------------


.. class:: Mailbox

   A mailbox, which may be inspected and modified.

   The :class:`Mailbox` class defines an interface and is not intended to be
   instantiated.  Instead, format-specific subclasses should inherit from
   :class:`Mailbox` and your code should instantiate a particular subclass.

   The :class:`Mailbox` interface is dictionary-like, with small keys
   corresponding to messages. Keys are issued by the :class:`Mailbox` instance
   with which they will be used and are only meaningful to that :class:`Mailbox`
   instance. A key continues to identify a message even if the corresponding
   message is modified, such as by replacing it with another message.

   Messages may be added to a :class:`Mailbox` instance using the set-like
   method :meth:`add` and removed using a ``del`` statement or the set-like
   methods :meth:`remove` and :meth:`discard`.

   :class:`Mailbox` interface semantics differ from dictionary semantics in some
   noteworthy ways. Each time a message is requested, a new representation
   (typically a :class:`Message` instance) is generated based upon the current
   state of the mailbox. Similarly, when a message is added to a
   :class:`Mailbox` instance, the provided message representation's contents are
   copied. In neither case is a reference to the message representation kept by
   the :class:`Mailbox` instance.

   The default :class:`Mailbox` iterator iterates over message representations,
   not keys as the default dictionary iterator does. Moreover, modification of a
   mailbox during iteration is safe and well-defined. Messages added to the
   mailbox after an iterator is created will not be seen by the
   iterator. Messages removed from the mailbox before the iterator yields them
   will be silently skipped, though using a key from an iterator may result in a
   :exc:`KeyError` exception if the corresponding message is subsequently
   removed.

   .. warning::

      Be very cautious when modifying mailboxes that might be simultaneously
      changed by some other process.  The safest mailbox format to use for such
      tasks is Maildir; try to avoid using single-file formats such as mbox for
      concurrent writing.  If you're modifying a mailbox, you *must* lock it by
      calling the :meth:`lock` and :meth:`unlock` methods *before* reading any
      messages in the file or making any changes by adding or deleting a
      message.  Failing to lock the mailbox runs the risk of losing messages or
      corrupting the entire mailbox.

   :class:`Mailbox` instances have the following methods:


   .. method:: add(message)

      Add *message* to the mailbox and return the key that has been assigned to
      it.

      Parameter *message* may be a :class:`Message` instance, an
      :class:`email.message.Message` instance, a string, or a file-like object
      (which should be open in text mode). If *message* is an instance of the
      appropriate format-specific :class:`Message` subclass (e.g., if it's an
      :class:`mboxMessage` instance and this is an :class:`mbox` instance), its
      format-specific information is used. Otherwise, reasonable defaults for
      format-specific information are used.


   .. method:: remove(key)
               __delitem__(key)
               discard(key)

      Delete the message corresponding to *key* from the mailbox.

      If no such message exists, a :exc:`KeyError` exception is raised if the
      method was called as :meth:`remove` or :meth:`__delitem__` but no
      exception is raised if the method was called as :meth:`discard`. The
      behavior of :meth:`discard` may be preferred if the underlying mailbox
      format supports concurrent modification by other processes.


   .. method:: __setitem__(key, message)

      Replace the message corresponding to *key* with *message*. Raise a
      :exc:`KeyError` exception if no message already corresponds to *key*.

      As with :meth:`add`, parameter *message* may be a :class:`Message`
      instance, an :class:`email.message.Message` instance, a string, or a
      file-like object (which should be open in text mode). If *message* is an
      instance of the appropriate format-specific :class:`Message` subclass
      (e.g., if it's an :class:`mboxMessage` instance and this is an
      :class:`mbox` instance), its format-specific information is
      used. Otherwise, the format-specific information of the message that
      currently corresponds to *key* is left unchanged.


   .. method:: iterkeys()
               keys()

      Return an iterator over all keys if called as :meth:`iterkeys` or return a
      list of keys if called as :meth:`keys`.


   .. method:: itervalues()
               __iter__()
               values()

      Return an iterator over representations of all messages if called as
      :meth:`itervalues` or :meth:`__iter__` or return a list of such
      representations if called as :meth:`values`. The messages are represented
      as instances of the appropriate format-specific :class:`Message` subclass
      unless a custom message factory was specified when the :class:`Mailbox`
      instance was initialized.

      .. note::

         The behavior of :meth:`__iter__` is unlike that of dictionaries, which
         iterate over keys.


   .. method:: iteritems()
               items()

      Return an iterator over (*key*, *message*) pairs, where *key* is a key and
      *message* is a message representation, if called as :meth:`iteritems` or
      return a list of such pairs if called as :meth:`items`. The messages are
      represented as instances of the appropriate format-specific
      :class:`Message` subclass unless a custom message factory was specified
      when the :class:`Mailbox` instance was initialized.


   .. method:: get(key, default=None)
               __getitem__(key)

      Return a representation of the message corresponding to *key*. If no such
      message exists, *default* is returned if the method was called as
      :meth:`get` and a :exc:`KeyError` exception is raised if the method was
      called as :meth:`__getitem__`. The message is represented as an instance
      of the appropriate format-specific :class:`Message` subclass unless a
      custom message factory was specified when the :class:`Mailbox` instance
      was initialized.


   .. method:: get_message(key)

      Return a representation of the message corresponding to *key* as an
      instance of the appropriate format-specific :class:`Message` subclass, or
      raise a :exc:`KeyError` exception if no such message exists.


   .. method:: get_string(key)

      Return a string representation of the message corresponding to *key*, or
      raise a :exc:`KeyError` exception if no such message exists.


   .. method:: get_file(key)

      Return a file-like representation of the message corresponding to *key*,
      or raise a :exc:`KeyError` exception if no such message exists. The
      file-like object behaves as if open in binary mode. This file should be
      closed once it is no longer needed.

      .. note::

         Unlike other representations of messages, file-like representations are
         not necessarily independent of the :class:`Mailbox` instance that
         created them or of the underlying mailbox. More specific documentation
         is provided by each subclass.


   .. method:: has_key(key)
               __contains__(key)

      Return ``True`` if *key* corresponds to a message, ``False`` otherwise.


   .. method:: __len__()

      Return a count of messages in the mailbox.


   .. method:: clear()

      Delete all messages from the mailbox.


   .. method:: pop(key[, default])

      Return a representation of the message corresponding to *key* and delete
      the message. If no such message exists, return *default* if it was
      supplied or else raise a :exc:`KeyError` exception. The message is
      represented as an instance of the appropriate format-specific
      :class:`Message` subclass unless a custom message factory was specified
      when the :class:`Mailbox` instance was initialized.


   .. method:: popitem()

      Return an arbitrary (*key*, *message*) pair, where *key* is a key and
      *message* is a message representation, and delete the corresponding
      message. If the mailbox is empty, raise a :exc:`KeyError` exception. The
      message is represented as an instance of the appropriate format-specific
      :class:`Message` subclass unless a custom message factory was specified
      when the :class:`Mailbox` instance was initialized.


   .. method:: update(arg)

      Parameter *arg* should be a *key*-to-*message* mapping or an iterable of
      (*key*, *message*) pairs. Updates the mailbox so that, for each given
      *key* and *message*, the message corresponding to *key* is set to
      *message* as if by using :meth:`__setitem__`. As with :meth:`__setitem__`,
      each *key* must already correspond to a message in the mailbox or else a
      :exc:`KeyError` exception will be raised, so in general it is incorrect
      for *arg* to be a :class:`Mailbox` instance.

      .. note::

         Unlike with dictionaries, keyword arguments are not supported.


   .. method:: flush()

      Write any pending changes to the filesystem. For some :class:`Mailbox`
      subclasses, changes are always written immediately and :meth:`flush` does
      nothing, but you should still make a habit of calling this method.


   .. method:: lock()

      Acquire an exclusive advisory lock on the mailbox so that other processes
      know not to modify it. An :exc:`ExternalClashError` is raised if the lock
      is not available. The particular locking mechanisms used depend upon the
      mailbox format.  You should *always* lock the mailbox before making any
      modifications to its contents.


   .. method:: unlock()

      Release the lock on the mailbox, if any.


   .. method:: close()

      Flush the mailbox, unlock it if necessary, and close any open files. For
      some :class:`Mailbox` subclasses, this method does nothing.


.. _mailbox-maildir:

:class:`Maildir`
^^^^^^^^^^^^^^^^


.. class:: Maildir(dirname, factory=rfc822.Message, create=True)

   A subclass of :class:`Mailbox` for mailboxes in Maildir format. Parameter
   *factory* is a callable object that accepts a file-like message representation
   (which behaves as if opened in binary mode) and returns a custom representation.
   If *factory* is ``None``, :class:`MaildirMessage` is used as the default message
   representation. If *create* is ``True``, the mailbox is created if it does not
   exist.

   It is for historical reasons that *factory* defaults to :class:`rfc822.Message`
   and that *dirname* is named as such rather than *path*. For a :class:`Maildir`
   instance that behaves like instances of other :class:`Mailbox` subclasses, set
   *factory* to ``None``.

   Maildir is a directory-based mailbox format invented for the qmail mail
   transfer agent and now widely supported by other programs. Messages in a
   Maildir mailbox are stored in separate files within a common directory
   structure. This design allows Maildir mailboxes to be accessed and modified
   by multiple unrelated programs without data corruption, so file locking is
   unnecessary.

   Maildir mailboxes contain three subdirectories, namely: :file:`tmp`,
   :file:`new`, and :file:`cur`. Messages are created momentarily in the
   :file:`tmp` subdirectory and then moved to the :file:`new` subdirectory to
   finalize delivery. A mail user agent may subsequently move the message to the
   :file:`cur` subdirectory and store information about the state of the message
   in a special "info" section appended to its file name.

   Folders of the style introduced by the Courier mail transfer agent are also
   supported. Any subdirectory of the main mailbox is considered a folder if
   ``'.'`` is the first character in its name. Folder names are represented by
   :class:`Maildir` without the leading ``'.'``. Each folder is itself a Maildir
   mailbox but should not contain other folders. Instead, a logical nesting is
   indicated using ``'.'`` to delimit levels, e.g., "Archived.2005.07".

   .. note::

      The Maildir specification requires the use of a colon (``':'``) in certain
      message file names. However, some operating systems do not permit this
      character in file names, If you wish to use a Maildir-like format on such
      an operating system, you should specify another character to use
      instead. The exclamation point (``'!'``) is a popular choice. For
      example::

         import mailbox
         mailbox.Maildir.colon = '!'

      The :attr:`colon` attribute may also be set on a per-instance basis.

   :class:`Maildir` instances have all of the methods of :class:`Mailbox` in
   addition to the following:


   .. method:: list_folders()

      Return a list of the names of all folders.


   .. method:: get_folder(folder)

      Return a :class:`Maildir` instance representing the folder whose name is
      *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
      does not exist.


   .. method:: add_folder(folder)

      Create a folder whose name is *folder* and return a :class:`Maildir`
      instance representing it.


   .. method:: remove_folder(folder)

      Delete the folder whose name is *folder*. If the folder contains any
      messages, a :exc:`NotEmptyError` exception will be raised and the folder
      will not be deleted.


   .. method:: clean()

      Delete temporary files from the mailbox that have not been accessed in the
      last 36 hours. The Maildir specification says that mail-reading programs
      should do this occasionally.

   Some :class:`Mailbox` methods implemented by :class:`Maildir` deserve special
   remarks:


   .. method:: add(message)
               __setitem__(key, message)
               update(arg)

      .. warning::

         These methods generate unique file names based upon the current process
         ID. When using multiple threads, undetected name clashes may occur and
         cause corruption of the mailbox unless threads are coordinated to avoid
         using these methods to manipulate the same mailbox simultaneously.


   .. method:: flush()

      All changes to Maildir mailboxes are immediately applied, so this method
      does nothing.


   .. method:: lock()
               unlock()

      Maildir mailboxes do not support (or require) locking, so these methods do
      nothing.


   .. method:: close()

      :class:`Maildir` instances do not keep any open files and the underlying
      mailboxes do not support locking, so this method does nothing.


   .. method:: get_file(key)

      Depending upon the host platform, it may not be possible to modify or
      remove the underlying message while the returned file remains open.


.. seealso::

   `maildir man page from qmail <http://www.qmail.org/man/man5/maildir.html>`_
      The original specification of the format.

   `Using maildir format <https://cr.yp.to/proto/maildir.html>`_
      Notes on Maildir by its inventor. Includes an updated name-creation scheme and
      details on "info" semantics.

   `maildir man page from Courier <http://www.courier-mta.org/maildir.html>`_
      Another specification of the format. Describes a common extension for supporting
      folders.


.. _mailbox-mbox:

:class:`mbox`
^^^^^^^^^^^^^


.. class:: mbox(path, factory=None, create=True)

   A subclass of :class:`Mailbox` for mailboxes in mbox format. Parameter *factory*
   is a callable object that accepts a file-like message representation (which
   behaves as if opened in binary mode) and returns a custom representation. If
   *factory* is ``None``, :class:`mboxMessage` is used as the default message
   representation. If *create* is ``True``, the mailbox is created if it does not
   exist.

   The mbox format is the classic format for storing mail on Unix systems. All
   messages in an mbox mailbox are stored in a single file with the beginning of
   each message indicated by a line whose first five characters are "From ".

   Several variations of the mbox format exist to address perceived shortcomings in
   the original. In the interest of compatibility, :class:`mbox` implements the
   original format, which is sometimes referred to as :dfn:`mboxo`. This means that
   the :mailheader:`Content-Length` header, if present, is ignored and that any
   occurrences of "From " at the beginning of a line in a message body are
   transformed to ">From " when storing the message, although occurrences of ">From
   " are not transformed to "From " when reading the message.

   Some :class:`Mailbox` methods implemented by :class:`mbox` deserve special
   remarks:


   .. method:: get_file(key)

      Using the file after calling :meth:`flush` or :meth:`close` on the
      :class:`mbox` instance may yield unpredictable results or raise an
      exception.


   .. method:: lock()
               unlock()

      Three locking mechanisms are used---dot locking and, if available, the
      :c:func:`flock` and :c:func:`lockf` system calls.


.. seealso::

   `mbox man page from qmail <http://www.qmail.org/man/man5/mbox.html>`_
      A specification of the format and its variations.

   `mbox man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mbox>`_
      Another specification of the format, with details on locking.

   `Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad <https://www.jwz.org/doc/content-length.html>`_
      An argument for using the original mbox format rather than a variation.

   `"mbox" is a family of several mutually incompatible mailbox formats <https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml>`_
      A history of mbox variations.


.. _mailbox-mh:

:class:`MH`
^^^^^^^^^^^


.. class:: MH(path, factory=None, create=True)

   A subclass of :class:`Mailbox` for mailboxes in MH format. Parameter *factory*
   is a callable object that accepts a file-like message representation (which
   behaves as if opened in binary mode) and returns a custom representation. If
   *factory* is ``None``, :class:`MHMessage` is used as the default message
   representation. If *create* is ``True``, the mailbox is created if it does not
   exist.

   MH is a directory-based mailbox format invented for the MH Message Handling
   System, a mail user agent. Each message in an MH mailbox resides in its own
   file. An MH mailbox may contain other MH mailboxes (called :dfn:`folders`) in
   addition to messages. Folders may be nested indefinitely. MH mailboxes also
   support :dfn:`sequences`, which are named lists used to logically group
   messages without moving them to sub-folders. Sequences are defined in a file
   called :file:`.mh_sequences` in each folder.

   The :class:`MH` class manipulates MH mailboxes, but it does not attempt to
   emulate all of :program:`mh`'s behaviors. In particular, it does not modify
   and is not affected by the :file:`context` or :file:`.mh_profile` files that
   are used by :program:`mh` to store its state and configuration.

   :class:`MH` instances have all of the methods of :class:`Mailbox` in addition
   to the following:


   .. method:: list_folders()

      Return a list of the names of all folders.


   .. method:: get_folder(folder)

      Return an :class:`MH` instance representing the folder whose name is
      *folder*. A :exc:`NoSuchMailboxError` exception is raised if the folder
      does not exist.


   .. method:: add_folder(folder)

      Create a folder whose name is *folder* and return an :class:`MH` instance
      representing it.


   .. method:: remove_folder(folder)

      Delete the folder whose name is *folder*. If the folder contains any
      messages, a :exc:`NotEmptyError` exception will be raised and the folder
      will not be deleted.


   .. method:: get_sequences()

      Return a dictionary of sequence names mapped to key lists. If there are no
      sequences, the empty dictionary is returned.


   .. method:: set_sequences(sequences)

      Re-define the sequences that exist in the mailbox based upon *sequences*,
      a dictionary of names mapped to key lists, like returned by
      :meth:`get_sequences`.


   .. method:: pack()

      Rename messages in the mailbox as necessary to eliminate gaps in
      numbering.  Entries in the sequences list are updated correspondingly.

      .. note::

         Already-issued keys are invalidated by this operation and should not be
         subsequently used.

   Some :class:`Mailbox` methods implemented by :class:`MH` deserve special
   remarks:


   .. method:: remove(key)
               __delitem__(key)
               discard(key)

      These methods immediately delete the message. The MH convention of marking
      a message for deletion by prepending a comma to its name is not used.


   .. method:: lock()
               unlock()

      Three locking mechanisms are used---dot locking and, if available, the
      :c:func:`flock` and :c:func:`lockf` system calls. For MH mailboxes, locking
      the mailbox means locking the :file:`.mh_sequences` file and, only for the
      duration of any operations that affect them, locking individual message
      files.


   .. method:: get_file(key)

      Depending upon the host platform, it may not be possible to remove the
      underlying message while the returned file remains open.


   .. method:: flush()

      All changes to MH mailboxes are immediately applied, so this method does
      nothing.


   .. method:: close()

      :class:`MH` instances do not keep any open files, so this method is
      equivalent to :meth:`unlock`.


.. seealso::

   `nmh - Message Handling System <http://www.nongnu.org/nmh/>`_
      Home page of :program:`nmh`, an updated version of the original :program:`mh`.

   `MH & nmh: Email for Users & Programmers <http://rand-mh.sourceforge.net/book/>`_
      A GPL-licensed book on :program:`mh` and :program:`nmh`, with some information
      on the mailbox format.


.. _mailbox-babyl:

:class:`Babyl`
^^^^^^^^^^^^^^


.. class:: Babyl(path, factory=None, create=True)

   A subclass of :class:`Mailbox` for mailboxes in Babyl format. Parameter
   *factory* is a callable object that accepts a file-like message representation
   (which behaves as if opened in binary mode) and returns a custom representation.
   If *factory* is ``None``, :class:`BabylMessage` is used as the default message
   representation. If *create* is ``True``, the mailbox is created if it does not
   exist.

   Babyl is a single-file mailbox format used by the Rmail mail user agent
   included with Emacs. The beginning of a message is indicated by a line
   containing the two characters Control-Underscore (``'\037'``) and Control-L
   (``'\014'``). The end of a message is indicated by the start of the next
   message or, in the case of the last message, a line containing a
   Control-Underscore (``'\037'``) character.

   Messages in a Babyl mailbox have two sets of headers, original headers and
   so-called visible headers. Visible headers are typically a subset of the
   original headers that have been reformatted or abridged to be more
   attractive. Each message in a Babyl mailbox also has an accompanying list of
   :dfn:`labels`, or short strings that record extra information about the
   message, and a list of all user-defined labels found in the mailbox is kept
   in the Babyl options section.

   :class:`Babyl` instances have all of the methods of :class:`Mailbox` in
   addition to the following:


   .. method:: get_labels()

      Return a list of the names of all user-defined labels used in the mailbox.

      .. note::

         The actual messages are inspected to determine which labels exist in
         the mailbox rather than consulting the list of labels in the Babyl
         options section, but the Babyl section is updated whenever the mailbox
         is modified.

   Some :class:`Mailbox` methods implemented by :class:`Babyl` deserve special
   remarks:


   .. method:: get_file(key)

      In Babyl mailboxes, the headers of a message are not stored contiguously
      with the body of the message. To generate a file-like representation, the
      headers and body are copied together into a :class:`~StringIO.StringIO` instance
      (from the :mod:`StringIO` module), which has an API identical to that of a
      file. As a result, the file-like object is truly independent of the
      underlying mailbox but does not save memory compared to a string
      representation.


   .. method:: lock()
               unlock()

      Three locking mechanisms are used---dot locking and, if available, the
      :c:func:`flock` and :c:func:`lockf` system calls.


.. seealso::

   `Format of Version 5 Babyl Files <https://quimby.gnus.org/notes/BABYL>`_
      A specification of the Babyl format.

   `Reading Mail with Rmail <https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html>`_
      The Rmail manual, with some information on Babyl semantics.


.. _mailbox-mmdf:

:class:`MMDF`
^^^^^^^^^^^^^


.. class:: MMDF(path, factory=None, create=True)

   A subclass of :class:`Mailbox` for mailboxes in MMDF format. Parameter *factory*
   is a callable object that accepts a file-like message representation (which
   behaves as if opened in binary mode) and returns a custom representation. If
   *factory* is ``None``, :class:`MMDFMessage` is used as the default message
   representation. If *create* is ``True``, the mailbox is created if it does not
   exist.

   MMDF is a single-file mailbox format invented for the Multichannel Memorandum
   Distribution Facility, a mail transfer agent. Each message is in the same
   form as an mbox message but is bracketed before and after by lines containing
   four Control-A (``'\001'``) characters. As with the mbox format, the
   beginning of each message is indicated by a line whose first five characters
   are "From ", but additional occurrences of "From " are not transformed to
   ">From " when storing messages because the extra message separator lines
   prevent mistaking such occurrences for the starts of subsequent messages.

   Some :class:`Mailbox` methods implemented by :class:`MMDF` deserve special
   remarks:


   .. method:: get_file(key)

      Using the file after calling :meth:`flush` or :meth:`close` on the
      :class:`MMDF` instance may yield unpredictable results or raise an
      exception.


   .. method:: lock()
               unlock()

      Three locking mechanisms are used---dot locking and, if available, the
      :c:func:`flock` and :c:func:`lockf` system calls.


.. seealso::

   `mmdf man page from tin <http://www.tin.org/bin/man.cgi?section=5&topic=mmdf>`_
      A specification of MMDF format from the documentation of tin, a newsreader.

   `MMDF <https://en.wikipedia.org/wiki/MMDF>`_
      A Wikipedia article describing the Multichannel Memorandum Distribution
      Facility.


.. _mailbox-message-objects:

:class:`Message` objects
------------------------


.. class:: Message([message])

   A subclass of the :mod:`email.message` module's
   :class:`~email.message.Message`. Subclasses of :class:`mailbox.Message` add
   mailbox-format-specific state and behavior.

   If *message* is omitted, the new instance is created in a default, empty state.
   If *message* is an :class:`email.message.Message` instance, its contents are
   copied; furthermore, any format-specific information is converted insofar as
   possible if *message* is a :class:`Message` instance. If *message* is a string
   or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
   and parsed.

   The format-specific state and behaviors offered by subclasses vary, but in
   general it is only the properties that are not specific to a particular
   mailbox that are supported (although presumably the properties are specific
   to a particular mailbox format). For example, file offsets for single-file
   mailbox formats and file names for directory-based mailbox formats are not
   retained, because they are only applicable to the original mailbox. But state
   such as whether a message has been read by the user or marked as important is
   retained, because it applies to the message itself.

   There is no requirement that :class:`Message` instances be used to represent
   messages retrieved using :class:`Mailbox` instances. In some situations, the
   time and memory required to generate :class:`Message` representations might
   not be acceptable. For such situations, :class:`Mailbox` instances also
   offer string and file-like representations, and a custom message factory may
   be specified when a :class:`Mailbox` instance is initialized.


.. _mailbox-maildirmessage:

:class:`MaildirMessage`
^^^^^^^^^^^^^^^^^^^^^^^


.. class:: MaildirMessage([message])

   A message with Maildir-specific behaviors. Parameter *message* has the same
   meaning as with the :class:`Message` constructor.

   Typically, a mail user agent application moves all of the messages in the
   :file:`new` subdirectory to the :file:`cur` subdirectory after the first time
   the user opens and closes the mailbox, recording that the messages are old
   whether or not they've actually been read. Each message in :file:`cur` has an
   "info" section added to its file name to store information about its state.
   (Some mail readers may also add an "info" section to messages in
   :file:`new`.)  The "info" section may take one of two forms: it may contain
   "2," followed by a list of standardized flags (e.g., "2,FR") or it may
   contain "1," followed by so-called experimental information. Standard flags
   for Maildir messages are as follows:

   +------+---------+--------------------------------+
   | Flag | Meaning | Explanation                    |
   +======+=========+================================+
   | D    | Draft   | Under composition              |
   +------+---------+--------------------------------+
   | F    | Flagged | Marked as important            |
   +------+---------+--------------------------------+
   | P    | Passed  | Forwarded, resent, or bounced  |
   +------+---------+--------------------------------+
   | R    | Replied | Replied to                     |
   +------+---------+--------------------------------+
   | S    | Seen    | Read                           |
   +------+---------+--------------------------------+
   | T    | Trashed | Marked for subsequent deletion |
   +------+---------+--------------------------------+

   :class:`MaildirMessage` instances offer the following methods:


   .. method:: get_subdir()

      Return either "new" (if the message should be stored in the :file:`new`
      subdirectory) or "cur" (if the message should be stored in the :file:`cur`
      subdirectory).

      .. note::

         A message is typically moved from :file:`new` to :file:`cur` after its
         mailbox has been accessed, whether or not the message is has been
         read. A message ``msg`` has been read if ``"S" in msg.get_flags()`` is
         ``True``.


   .. method:: set_subdir(subdir)

      Set the subdirectory the message should be stored in. Parameter *subdir*
      must be either "new" or "cur".


   .. method:: get_flags()

      Return a string specifying the flags that are currently set. If the
      message complies with the standard Maildir format, the result is the
      concatenation in alphabetical order of zero or one occurrence of each of
      ``'D'``, ``'F'``, ``'P'``, ``'R'``, ``'S'``, and ``'T'``. The empty string
      is returned if no flags are set or if "info" contains experimental
      semantics.


   .. method:: set_flags(flags)

      Set the flags specified by *flags* and unset all others.


   .. method:: add_flag(flag)

      Set the flag(s) specified by *flag* without changing other flags. To add
      more than one flag at a time, *flag* may be a string of more than one
      character. The current "info" is overwritten whether or not it contains
      experimental information rather than flags.


   .. method:: remove_flag(flag)

      Unset the flag(s) specified by *flag* without changing other flags. To
      remove more than one flag at a time, *flag* maybe a string of more than
      one character.  If "info" contains experimental information rather than
      flags, the current "info" is not modified.


   .. method:: get_date()

      Return the delivery date of the message as a floating-point number
      representing seconds since the epoch.


   .. method:: set_date(date)

      Set the delivery date of the message to *date*, a floating-point number
      representing seconds since the epoch.


   .. method:: get_info()

      Return a string containing the "info" for a message. This is useful for
      accessing and modifying "info" that is experimental (i.e., not a list of
      flags).


   .. method:: set_info(info)

      Set "info" to *info*, which should be a string.

When a :class:`MaildirMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:

+--------------------+----------------------------------------------+
| Resulting state    | :class:`mboxMessage` or :class:`MMDFMessage` |
|                    | state                                        |
+====================+==============================================+
| "cur" subdirectory | O flag                                       |
+--------------------+----------------------------------------------+
| F flag             | F flag                                       |
+--------------------+----------------------------------------------+
| R flag             | A flag                                       |
+--------------------+----------------------------------------------+
| S flag             | R flag                                       |
+--------------------+----------------------------------------------+
| T flag             | D flag                                       |
+--------------------+----------------------------------------------+

When a :class:`MaildirMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:

+-------------------------------+--------------------------+
| Resulting state               | :class:`MHMessage` state |
+===============================+==========================+
| "cur" subdirectory            | "unseen" sequence        |
+-------------------------------+--------------------------+
| "cur" subdirectory and S flag | no "unseen" sequence     |
+-------------------------------+--------------------------+
| F flag                        | "flagged" sequence       |
+-------------------------------+--------------------------+
| R flag                        | "replied" sequence       |
+-------------------------------+--------------------------+

When a :class:`MaildirMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:

+-------------------------------+-------------------------------+
| Resulting state               | :class:`BabylMessage` state   |
+===============================+===============================+
| "cur" subdirectory            | "unseen" label                |
+-------------------------------+-------------------------------+
| "cur" subdirectory and S flag | no "unseen" label             |
+-------------------------------+-------------------------------+
| P flag                        | "forwarded" or "resent" label |
+-------------------------------+-------------------------------+
| R flag                        | "answered" label              |
+-------------------------------+-------------------------------+
| T flag                        | "deleted" label               |
+-------------------------------+-------------------------------+


.. _mailbox-mboxmessage:

:class:`mboxMessage`
^^^^^^^^^^^^^^^^^^^^


.. class:: mboxMessage([message])

   A message with mbox-specific behaviors. Parameter *message* has the same meaning
   as with the :class:`Message` constructor.

   Messages in an mbox mailbox are stored together in a single file. The
   sender's envelope address and the time of delivery are typically stored in a
   line beginning with "From " that is used to indicate the start of a message,
   though there is considerable variation in the exact format of this data among
   mbox implementations. Flags that indicate the state of the message, such as
   whether it has been read or marked as important, are typically stored in
   :mailheader:`Status` and :mailheader:`X-Status` headers.

   Conventional flags for mbox messages are as follows:

   +------+----------+--------------------------------+
   | Flag | Meaning  | Explanation                    |
   +======+==========+================================+
   | R    | Read     | Read                           |
   +------+----------+--------------------------------+
   | O    | Old      | Previously detected by MUA     |
   +------+----------+--------------------------------+
   | D    | Deleted  | Marked for subsequent deletion |
   +------+----------+--------------------------------+
   | F    | Flagged  | Marked as important            |
   +------+----------+--------------------------------+
   | A    | Answered | Replied to                     |
   +------+----------+--------------------------------+

   The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
   "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
   flags and headers typically appear in the order mentioned.

   :class:`mboxMessage` instances offer the following methods:


   .. method:: get_from()

      Return a string representing the "From " line that marks the start of the
      message in an mbox mailbox. The leading "From " and the trailing newline
      are excluded.


   .. method:: set_from(from_, time_=None)

      Set the "From " line to *from_*, which should be specified without a
      leading "From " or trailing newline. For convenience, *time_* may be
      specified and will be formatted appropriately and appended to *from_*. If
      *time_* is specified, it should be a :class:`time.struct_time` instance, a
      tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
      :meth:`time.gmtime`).


   .. method:: get_flags()

      Return a string specifying the flags that are currently set. If the
      message complies with the conventional format, the result is the
      concatenation in the following order of zero or one occurrence of each of
      ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.


   .. method:: set_flags(flags)

      Set the flags specified by *flags* and unset all others. Parameter *flags*
      should be the concatenation in any order of zero or more occurrences of
      each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.


   .. method:: add_flag(flag)

      Set the flag(s) specified by *flag* without changing other flags. To add
      more than one flag at a time, *flag* may be a string of more than one
      character.


   .. method:: remove_flag(flag)

      Unset the flag(s) specified by *flag* without changing other flags. To
      remove more than one flag at a time, *flag* maybe a string of more than
      one character.

When an :class:`mboxMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the
:class:`MaildirMessage` instance's delivery date, and the following conversions
take place:

+-----------------+-------------------------------+
| Resulting state | :class:`MaildirMessage` state |
+=================+===============================+
| R flag          | S flag                        |
+-----------------+-------------------------------+
| O flag          | "cur" subdirectory            |
+-----------------+-------------------------------+
| D flag          | T flag                        |
+-----------------+-------------------------------+
| F flag          | F flag                        |
+-----------------+-------------------------------+
| A flag          | R flag                        |
+-----------------+-------------------------------+

When an :class:`mboxMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:

+-------------------+--------------------------+
| Resulting state   | :class:`MHMessage` state |
+===================+==========================+
| R flag and O flag | no "unseen" sequence     |
+-------------------+--------------------------+
| O flag            | "unseen" sequence        |
+-------------------+--------------------------+
| F flag            | "flagged" sequence       |
+-------------------+--------------------------+
| A flag            | "replied" sequence       |
+-------------------+--------------------------+

When an :class:`mboxMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:

+-------------------+-----------------------------+
| Resulting state   | :class:`BabylMessage` state |
+===================+=============================+
| R flag and O flag | no "unseen" label           |
+-------------------+-----------------------------+
| O flag            | "unseen" label              |
+-------------------+-----------------------------+
| D flag            | "deleted" label             |
+-------------------+-----------------------------+
| A flag            | "answered" label            |
+-------------------+-----------------------------+

When a :class:`Message` instance is created based upon an :class:`MMDFMessage`
instance, the "From " line is copied and all flags directly correspond:

+-----------------+----------------------------+
| Resulting state | :class:`MMDFMessage` state |
+=================+============================+
| R flag          | R flag                     |
+-----------------+----------------------------+
| O flag          | O flag                     |
+-----------------+----------------------------+
| D flag          | D flag                     |
+-----------------+----------------------------+
| F flag          | F flag                     |
+-----------------+----------------------------+
| A flag          | A flag                     |
+-----------------+----------------------------+


.. _mailbox-mhmessage:

:class:`MHMessage`
^^^^^^^^^^^^^^^^^^


.. class:: MHMessage([message])

   A message with MH-specific behaviors. Parameter *message* has the same meaning
   as with the :class:`Message` constructor.

   MH messages do not support marks or flags in the traditional sense, but they
   do support sequences, which are logical groupings of arbitrary messages. Some
   mail reading programs (although not the standard :program:`mh` and
   :program:`nmh`) use sequences in much the same way flags are used with other
   formats, as follows:

   +----------+------------------------------------------+
   | Sequence | Explanation                              |
   +==========+==========================================+
   | unseen   | Not read, but previously detected by MUA |
   +----------+------------------------------------------+
   | replied  | Replied to                               |
   +----------+------------------------------------------+
   | flagged  | Marked as important                      |
   +----------+------------------------------------------+

   :class:`MHMessage` instances offer the following methods:


   .. method:: get_sequences()

      Return a list of the names of sequences that include this message.


   .. method:: set_sequences(sequences)

      Set the list of sequences that include this message.


   .. method:: add_sequence(sequence)

      Add *sequence* to the list of sequences that include this message.


   .. method:: remove_sequence(sequence)

      Remove *sequence* from the list of sequences that include this message.

When an :class:`MHMessage` instance is created based upon a
:class:`MaildirMessage` instance, the following conversions take place:

+--------------------+-------------------------------+
| Resulting state    | :class:`MaildirMessage` state |
+====================+===============================+
| "unseen" sequence  | no S flag                     |
+--------------------+-------------------------------+
| "replied" sequence | R flag                        |
+--------------------+-------------------------------+
| "flagged" sequence | F flag                        |
+--------------------+-------------------------------+

When an :class:`MHMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:

+--------------------+----------------------------------------------+
| Resulting state    | :class:`mboxMessage` or :class:`MMDFMessage` |
|                    | state                                        |
+====================+==============================================+
| "unseen" sequence  | no R flag                                    |
+--------------------+----------------------------------------------+
| "replied" sequence | A flag                                       |
+--------------------+----------------------------------------------+
| "flagged" sequence | F flag                                       |
+--------------------+----------------------------------------------+

When an :class:`MHMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:

+--------------------+-----------------------------+
| Resulting state    | :class:`BabylMessage` state |
+====================+=============================+
| "unseen" sequence  | "unseen" label              |
+--------------------+-----------------------------+
| "replied" sequence | "answered" label            |
+--------------------+-----------------------------+


.. _mailbox-babylmessage:

:class:`BabylMessage`
^^^^^^^^^^^^^^^^^^^^^


.. class:: BabylMessage([message])

   A message with Babyl-specific behaviors. Parameter *message* has the same
   meaning as with the :class:`Message` constructor.

   Certain message labels, called :dfn:`attributes`, are defined by convention
   to have special meanings. The attributes are as follows:

   +-----------+------------------------------------------+
   | Label     | Explanation                              |
   +===========+==========================================+
   | unseen    | Not read, but previously detected by MUA |
   +-----------+------------------------------------------+
   | deleted   | Marked for subsequent deletion           |
   +-----------+------------------------------------------+
   | filed     | Copied to another file or mailbox        |
   +-----------+------------------------------------------+
   | answered  | Replied to                               |
   +-----------+------------------------------------------+
   | forwarded | Forwarded                                |
   +-----------+------------------------------------------+
   | edited    | Modified by the user                     |
   +-----------+------------------------------------------+
   | resent    | Resent                                   |
   +-----------+------------------------------------------+

   By default, Rmail displays only visible headers. The :class:`BabylMessage`
   class, though, uses the original headers because they are more
   complete. Visible headers may be accessed explicitly if desired.

   :class:`BabylMessage` instances offer the following methods:


   .. method:: get_labels()

      Return a list of labels on the message.


   .. method:: set_labels(labels)

      Set the list of labels on the message to *labels*.


   .. method:: add_label(label)

      Add *label* to the list of labels on the message.


   .. method:: remove_label(label)

      Remove *label* from the list of labels on the message.


   .. method:: get_visible()

      Return an :class:`Message` instance whose headers are the message's
      visible headers and whose body is empty.


   .. method:: set_visible(visible)

      Set the message's visible headers to be the same as the headers in
      *message*.  Parameter *visible* should be a :class:`Message` instance, an
      :class:`email.message.Message` instance, a string, or a file-like object
      (which should be open in text mode).


   .. method:: update_visible()

      When a :class:`BabylMessage` instance's original headers are modified, the
      visible headers are not automatically modified to correspond. This method
      updates the visible headers as follows: each visible header with a
      corresponding original header is set to the value of the original header,
      each visible header without a corresponding original header is removed,
      and any of :mailheader:`Date`, :mailheader:`From`, :mailheader:`Reply-To`,
      :mailheader:`To`, :mailheader:`CC`, and :mailheader:`Subject` that are
      present in the original headers but not the visible headers are added to
      the visible headers.

When a :class:`BabylMessage` instance is created based upon a
:class:`MaildirMessage` instance, the following conversions take place:

+-------------------+-------------------------------+
| Resulting state   | :class:`MaildirMessage` state |
+===================+===============================+
| "unseen" label    | no S flag                     |
+-------------------+-------------------------------+
| "deleted" label   | T flag                        |
+-------------------+-------------------------------+
| "answered" label  | R flag                        |
+-------------------+-------------------------------+
| "forwarded" label | P flag                        |
+-------------------+-------------------------------+

When a :class:`BabylMessage` instance is created based upon an
:class:`mboxMessage` or :class:`MMDFMessage` instance, the :mailheader:`Status`
and :mailheader:`X-Status` headers are omitted and the following conversions
take place:

+------------------+----------------------------------------------+
| Resulting state  | :class:`mboxMessage` or :class:`MMDFMessage` |
|                  | state                                        |
+==================+==============================================+
| "unseen" label   | no R flag                                    |
+------------------+----------------------------------------------+
| "deleted" label  | D flag                                       |
+------------------+----------------------------------------------+
| "answered" label | A flag                                       |
+------------------+----------------------------------------------+

When a :class:`BabylMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:

+------------------+--------------------------+
| Resulting state  | :class:`MHMessage` state |
+==================+==========================+
| "unseen" label   | "unseen" sequence        |
+------------------+--------------------------+
| "answered" label | "replied" sequence       |
+------------------+--------------------------+


.. _mailbox-mmdfmessage:

:class:`MMDFMessage`
^^^^^^^^^^^^^^^^^^^^


.. class:: MMDFMessage([message])

   A message with MMDF-specific behaviors. Parameter *message* has the same meaning
   as with the :class:`Message` constructor.

   As with message in an mbox mailbox, MMDF messages are stored with the
   sender's address and the delivery date in an initial line beginning with
   "From ".  Likewise, flags that indicate the state of the message are
   typically stored in :mailheader:`Status` and :mailheader:`X-Status` headers.

   Conventional flags for MMDF messages are identical to those of mbox message
   and are as follows:

   +------+----------+--------------------------------+
   | Flag | Meaning  | Explanation                    |
   +======+==========+================================+
   | R    | Read     | Read                           |
   +------+----------+--------------------------------+
   | O    | Old      | Previously detected by MUA     |
   +------+----------+--------------------------------+
   | D    | Deleted  | Marked for subsequent deletion |
   +------+----------+--------------------------------+
   | F    | Flagged  | Marked as important            |
   +------+----------+--------------------------------+
   | A    | Answered | Replied to                     |
   +------+----------+--------------------------------+

   The "R" and "O" flags are stored in the :mailheader:`Status` header, and the
   "D", "F", and "A" flags are stored in the :mailheader:`X-Status` header. The
   flags and headers typically appear in the order mentioned.

   :class:`MMDFMessage` instances offer the following methods, which are
   identical to those offered by :class:`mboxMessage`:


   .. method:: get_from()

      Return a string representing the "From " line that marks the start of the
      message in an mbox mailbox. The leading "From " and the trailing newline
      are excluded.


   .. method:: set_from(from_, time_=None)

      Set the "From " line to *from_*, which should be specified without a
      leading "From " or trailing newline. For convenience, *time_* may be
      specified and will be formatted appropriately and appended to *from_*. If
      *time_* is specified, it should be a :class:`time.struct_time` instance, a
      tuple suitable for passing to :meth:`time.strftime`, or ``True`` (to use
      :meth:`time.gmtime`).


   .. method:: get_flags()

      Return a string specifying the flags that are currently set. If the
      message complies with the conventional format, the result is the
      concatenation in the following order of zero or one occurrence of each of
      ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.


   .. method:: set_flags(flags)

      Set the flags specified by *flags* and unset all others. Parameter *flags*
      should be the concatenation in any order of zero or more occurrences of
      each of ``'R'``, ``'O'``, ``'D'``, ``'F'``, and ``'A'``.


   .. method:: add_flag(flag)

      Set the flag(s) specified by *flag* without changing other flags. To add
      more than one flag at a time, *flag* may be a string of more than one
      character.


   .. method:: remove_flag(flag)

      Unset the flag(s) specified by *flag* without changing other flags. To
      remove more than one flag at a time, *flag* maybe a string of more than
      one character.

When an :class:`MMDFMessage` instance is created based upon a
:class:`MaildirMessage` instance, a "From " line is generated based upon the
:class:`MaildirMessage` instance's delivery date, and the following conversions
take place:

+-----------------+-------------------------------+
| Resulting state | :class:`MaildirMessage` state |
+=================+===============================+
| R flag          | S flag                        |
+-----------------+-------------------------------+
| O flag          | "cur" subdirectory            |
+-----------------+-------------------------------+
| D flag          | T flag                        |
+-----------------+-------------------------------+
| F flag          | F flag                        |
+-----------------+-------------------------------+
| A flag          | R flag                        |
+-----------------+-------------------------------+

When an :class:`MMDFMessage` instance is created based upon an
:class:`MHMessage` instance, the following conversions take place:

+-------------------+--------------------------+
| Resulting state   | :class:`MHMessage` state |
+===================+==========================+
| R flag and O flag | no "unseen" sequence     |
+-------------------+--------------------------+
| O flag            | "unseen" sequence        |
+-------------------+--------------------------+
| F flag            | "flagged" sequence       |
+-------------------+--------------------------+
| A flag            | "replied" sequence       |
+-------------------+--------------------------+

When an :class:`MMDFMessage` instance is created based upon a
:class:`BabylMessage` instance, the following conversions take place:

+-------------------+-----------------------------+
| Resulting state   | :class:`BabylMessage` state |
+===================+=============================+
| R flag and O flag | no "unseen" label           |
+-------------------+-----------------------------+
| O flag            | "unseen" label              |
+-------------------+-----------------------------+
| D flag            | "deleted" label             |
+-------------------+-----------------------------+
| A flag            | "answered" label            |
+-------------------+-----------------------------+

When an :class:`MMDFMessage` instance is created based upon an
:class:`mboxMessage` instance, the "From " line is copied and all flags directly
correspond:

+-----------------+----------------------------+
| Resulting state | :class:`mboxMessage` state |
+=================+============================+
| R flag          | R flag                     |
+-----------------+----------------------------+
| O flag          | O flag                     |
+-----------------+----------------------------+
| D flag          | D flag                     |
+-----------------+----------------------------+
| F flag          | F flag                     |
+-----------------+----------------------------+
| A flag          | A flag                     |
+-----------------+----------------------------+


Exceptions
----------

The following exception classes are defined in the :mod:`mailbox` module:


.. exception:: Error()

   The based class for all other module-specific exceptions.


.. exception:: NoSuchMailboxError()

   Raised when a mailbox is expected but is not found, such as when instantiating a
   :class:`Mailbox` subclass with a path that does not exist (and with the *create*
   parameter set to ``False``), or when opening a folder that does not exist.


.. exception:: NotEmptyError()

   Raised when a mailbox is not empty but is expected to be, such as when deleting
   a folder that contains messages.


.. exception:: ExternalClashError()

   Raised when some mailbox-related condition beyond the control of the program
   causes it to be unable to proceed, such as when failing to acquire a lock that
   another program already holds a lock, or when a uniquely-generated file name
   already exists.


.. exception:: FormatError()

   Raised when the data in a file cannot be parsed, such as when an :class:`MH`
   instance attempts to read a corrupted :file:`.mh_sequences` file.


.. _mailbox-deprecated:

Deprecated classes and methods
------------------------------

.. deprecated:: 2.6

Older versions of the :mod:`mailbox` module do not support modification of
mailboxes, such as adding or removing message, and do not provide classes to
represent format-specific message properties. For backward compatibility, the
older mailbox classes are still available, but the newer classes should be used
in preference to them.  The old classes have been removed in Python 3.

Older mailbox objects support only iteration and provide a single public method:


.. method:: oldmailbox.next()

   Return the next message in the mailbox, created with the optional *factory*
   argument passed into the mailbox object's constructor. By default this is an
   :class:`rfc822.Message` object (see the :mod:`rfc822` module).  Depending on the
   mailbox implementation the *fp* attribute of this object may be a true file
   object or a class instance simulating a file object, taking care of things like
   message boundaries if multiple mail messages are contained in a single file,
   etc.  If no more messages are available, this method returns ``None``.

Most of the older mailbox classes have names that differ from the current
mailbox class names, except for :class:`Maildir`. For this reason, the new
:class:`Maildir` class defines a :meth:`!next` method and its constructor differs
slightly from those of the other new mailbox classes.

The older mailbox classes whose names are not the same as their newer
counterparts are as follows:


.. class:: UnixMailbox(fp[, factory])

   Access to a classic Unix-style mailbox, where all messages are contained in a
   single file and separated by ``From`` (a.k.a. ``From_``) lines.  The file object
   *fp* points to the mailbox file.  The optional *factory* parameter is a callable
   that should create new message objects.  *factory* is called with one argument,
   *fp* by the :meth:`!next` method of the mailbox object.  The default is the
   :class:`rfc822.Message` class (see the :mod:`rfc822` module -- and the note
   below).

   .. note::

      For reasons of this module's internal implementation, you will probably want to
      open the *fp* object in binary mode.  This is especially important on Windows.

   For maximum portability, messages in a Unix-style mailbox are separated by any
   line that begins exactly with the string ``'From '`` (note the trailing space)
   if preceded by exactly two newlines. Because of the wide-range of variations in
   practice, nothing else on the ``From_`` line should be considered.  However, the
   current implementation doesn't check for the leading two newlines.  This is
   usually fine for most applications.

   The :class:`UnixMailbox` class implements a more strict version of ``From_``
   line checking, using a regular expression that usually correctly matched
   ``From_`` delimiters.  It considers delimiter line to be separated by ``From
   name time`` lines.  For maximum portability, use the
   :class:`PortableUnixMailbox` class instead.  This class is identical to
   :class:`UnixMailbox` except that individual messages are separated by only
   ``From`` lines.


.. class:: PortableUnixMailbox(fp[, factory])

   A less-strict version of :class:`UnixMailbox`, which considers only the ``From``
   at the beginning of the line separating messages.  The "*name* *time*" portion
   of the From line is ignored, to protect against some variations that are
   observed in practice.  This works since lines in the message which begin with
   ``'From '`` are quoted by mail handling software at delivery-time.


.. class:: MmdfMailbox(fp[, factory])

   Access an MMDF-style mailbox, where all messages are contained in a single file
   and separated by lines consisting of 4 control-A characters.  The file object
   *fp* points to the mailbox file. Optional *factory* is as with the
   :class:`UnixMailbox` class.


.. class:: MHMailbox(dirname[, factory])

   Access an MH mailbox, a directory with each message in a separate file with a
   numeric name. The name of the mailbox directory is passed in *dirname*.
   *factory* is as with the :class:`UnixMailbox` class.


.. class:: BabylMailbox(fp[, factory])

   Access a Babyl mailbox, which is similar to an MMDF mailbox.  In Babyl format,
   each message has two sets of headers, the *original* headers and the *visible*
   headers.  The original headers appear before a line containing only ``'*** EOOH
   ***'`` (End-Of-Original-Headers) and the visible headers appear after the
   ``EOOH`` line.  Babyl-compliant mail readers will show you only the visible
   headers, and :class:`BabylMailbox` objects will return messages containing only
   the visible headers.  You'll have to do your own parsing of the mailbox file to
   get at the original headers.  Mail messages start with the EOOH line and end
   with a line containing only ``'\037\014'``.  *factory* is as with the
   :class:`UnixMailbox` class.

If you wish to use the older mailbox classes with the :mod:`email` module rather
than the deprecated :mod:`rfc822` module, you can do so as follows::

   import email
   import email.Errors
   import mailbox

   def msgfactory(fp):
       try:
           return email.message_from_file(fp)
       except email.Errors.MessageParseError:
           # Don't return None since that will
           # stop the mailbox iterator
           return ''

   mbox = mailbox.UnixMailbox(fp, msgfactory)

Alternatively, if you know your mailbox contains only well-formed MIME messages,
you can simplify this to::

   import email
   import mailbox

   mbox = mailbox.UnixMailbox(fp, email.message_from_file)


.. _mailbox-examples:

Examples
--------

A simple example of printing the subjects of all messages in a mailbox that seem
interesting::

   import mailbox
   for message in mailbox.mbox('~/mbox'):
       subject = message['subject']       # Could possibly be None.
       if subject and 'python' in subject.lower():
           print subject

To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
format-specific information that can be converted::

   import mailbox
   destination = mailbox.MH('~/Mail')
   destination.lock()
   for message in mailbox.Babyl('~/RMAIL'):
       destination.add(mailbox.MHMessage(message))
   destination.flush()
   destination.unlock()

This example sorts mail from several mailing lists into different mailboxes,
being careful to avoid mail corruption due to concurrent modification by other
programs, mail loss due to interruption of the program, or premature termination
due to malformed messages in the mailbox::

   import mailbox
   import email.errors

   list_names = ('python-list', 'python-dev', 'python-bugs')

   boxes = dict((name, mailbox.mbox('~/email/%s' % name)) for name in list_names)
   inbox = mailbox.Maildir('~/Maildir', factory=None)

   for key in inbox.iterkeys():
       try:
           message = inbox[key]
       except email.errors.MessageParseError:
           continue                # The message is malformed. Just leave it.

       for name in list_names:
           list_id = message['list-id']
           if list_id and name in list_id:
               # Get mailbox to use
               box = boxes[name]

               # Write copy to disk before removing original.
               # If there's a crash, you might duplicate a message, but
               # that's better than losing a message completely.
               box.lock()
               box.add(message)
               box.flush()
               box.unlock()

               # Remove original message
               inbox.lock()
               inbox.discard(key)
               inbox.flush()
               inbox.unlock()
               break               # Found destination, so stop looking.

   for box in boxes.itervalues():
       box.close()

PK	%�\�,��[[%html/_sources/library/mailcap.rst.txtnu�[���:mod:`mailcap` --- Mailcap file handling
========================================

.. module:: mailcap
   :synopsis: Mailcap file handling.

**Source code:** :source:`Lib/mailcap.py`

--------------

Mailcap files are used to configure how MIME-aware applications such as mail
readers and Web browsers react to files with different MIME types. (The name
"mailcap" is derived from the phrase "mail capability".)  For example, a mailcap
file might contain a line like ``video/mpeg; xmpeg %s``.  Then, if the user
encounters an email message or Web document with the MIME type
:mimetype:`video/mpeg`, ``%s`` will be replaced by a filename (usually one
belonging to a temporary file) and the :program:`xmpeg` program can be
automatically started to view the file.

The mailcap format is documented in :rfc:`1524`, "A User Agent Configuration
Mechanism For Multimedia Mail Format Information," but is not an Internet
standard.  However, mailcap files are supported on most Unix systems.


.. function:: findmatch(caps, MIMEtype[, key[, filename[, plist]]])

   Return a 2-tuple; the first element is a string containing the command line to
   be executed (which can be passed to :func:`os.system`), and the second element
   is the mailcap entry for a given MIME type.  If no matching MIME type can be
   found, ``(None, None)`` is returned.

   *key* is the name of the field desired, which represents the type of activity to
   be performed; the default value is 'view', since in the  most common case you
   simply want to view the body of the MIME-typed data.  Other possible values
   might be 'compose' and 'edit', if you wanted to create a new body of the given
   MIME type or alter the existing body data.  See :rfc:`1524` for a complete list
   of these fields.

   *filename* is the filename to be substituted for ``%s`` in the command line; the
   default value is ``'/dev/null'`` which is almost certainly not what you want, so
   usually you'll override it by specifying a filename.

   *plist* can be a list containing named parameters; the default value is simply
   an empty list.  Each entry in the list must be a string containing the parameter
   name, an equals sign (``'='``), and the parameter's value.  Mailcap entries can
   contain  named parameters like ``%{foo}``, which will be replaced by the value
   of the parameter named 'foo'.  For example, if the command line ``showpartial
   %{id} %{number} %{total}`` was in a mailcap file, and *plist* was set to
   ``['id=1', 'number=2', 'total=3']``, the resulting command line would be
   ``'showpartial 1 2 3'``.

   In a mailcap file, the "test" field can optionally be specified to test some
   external condition (such as the machine architecture, or the window system in
   use) to determine whether or not the mailcap line applies.  :func:`findmatch`
   will automatically check such conditions and skip the entry if the check fails.


.. function:: getcaps()

   Returns a dictionary mapping MIME types to a list of mailcap file entries. This
   dictionary must be passed to the :func:`findmatch` function.  An entry is stored
   as a list of dictionaries, but it shouldn't be necessary to know the details of
   this representation.

   The information is derived from all of the mailcap files found on the system.
   Settings in the user's mailcap file :file:`$HOME/.mailcap` will override
   settings in the system mailcap files :file:`/etc/mailcap`,
   :file:`/usr/etc/mailcap`, and :file:`/usr/local/etc/mailcap`.

An example usage::

   >>> import mailcap
   >>> d = mailcap.getcaps()
   >>> mailcap.findmatch(d, 'video/mpeg', filename='tmp1223')
   ('xmpeg tmp1223', {'view': 'xmpeg %s'})

PK	%�\Z�	���$html/_sources/library/markup.rst.txtnu�[���.. _markup:

**********************************
Structured Markup Processing Tools
**********************************

Python supports a variety of modules to work with various forms of structured
data markup.  This includes modules to work with the Standard Generalized Markup
Language (SGML) and the Hypertext Markup Language (HTML), and several interfaces
for working with the Extensible Markup Language (XML).

It is important to note that modules in the :mod:`xml` package require that
there be at least one SAX-compliant XML parser available. Starting with Python
2.3, the Expat parser is included with Python, so the :mod:`xml.parsers.expat`
module will always be available. You may still want to be aware of the `PyXML
add-on package <http://pyxml.sourceforge.net/>`_; that package provides an
extended set of XML libraries for Python.

The documentation for the :mod:`xml.dom` and :mod:`xml.sax` packages are the
definition of the Python bindings for the DOM and SAX interfaces.


.. toctree::

   htmlparser.rst
   sgmllib.rst
   htmllib.rst
   xml.rst
   xml.etree.elementtree.rst
   xml.dom.rst
   xml.dom.minidom.rst
   xml.dom.pulldom.rst
   xml.sax.rst
   xml.sax.handler.rst
   xml.sax.utils.rst
   xml.sax.reader.rst
   pyexpat.rst
PK	%�\\��-99%html/_sources/library/marshal.rst.txtnu�[���
:mod:`marshal` --- Internal Python object serialization
=======================================================

.. module:: marshal
   :synopsis: Convert Python objects to streams of bytes and back (with different
              constraints).


This module contains functions that can read and write Python values in a binary
format.  The format is specific to Python, but independent of machine
architecture issues (e.g., you can write a Python value to a file on a PC,
transport the file to a Sun, and read it back there).  Details of the format are
undocumented on purpose; it may change between Python versions (although it
rarely does). [#]_

.. index::
   module: pickle
   module: shelve

This is not a general "persistence" module.  For general persistence and
transfer of Python objects through RPC calls, see the modules :mod:`pickle` and
:mod:`shelve`.  The :mod:`marshal` module exists mainly to support reading and
writing the "pseudo-compiled" code for Python modules of :file:`.pyc` files.
Therefore, the Python maintainers reserve the right to modify the marshal format
in backward incompatible ways should the need arise.  If you're serializing and
de-serializing Python objects, use the :mod:`pickle` module instead -- the
performance is comparable, version independence is guaranteed, and pickle
supports a substantially wider range of objects than marshal.

.. warning::

   The :mod:`marshal` module is not intended to be secure against erroneous or
   maliciously constructed data.  Never unmarshal data received from an
   untrusted or unauthenticated source.

.. index:: object; code, code object

Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by
this module.  The following types are supported: booleans, integers, long
integers, floating point numbers, complex numbers, strings, Unicode objects,
tuples, lists, sets, frozensets, dictionaries, and code objects, where it should
be understood that tuples, lists, sets, frozensets and dictionaries are only
supported as long as the values contained therein are themselves supported; and
recursive lists, sets and dictionaries should not be written (they will cause
infinite loops).  The singletons :const:`None`, :const:`Ellipsis` and
:exc:`StopIteration` can also be marshalled and unmarshalled.

.. warning::

   On machines where C's ``long int`` type has more than 32 bits (such as the
   DEC Alpha), it is possible to create plain Python integers that are longer
   than 32 bits. If such an integer is marshaled and read back in on a machine
   where C's ``long int`` type has only 32 bits, a Python long integer object
   is returned instead.  While of a different type, the numeric value is the
   same.  (This behavior is new in Python 2.2.  In earlier versions, all but the
   least-significant 32 bits of the value were lost, and a warning message was
   printed.)

There are functions that read/write files as well as functions operating on
strings.

The module defines these functions:


.. function:: dump(value, file[, version])

   Write the value on the open file.  The value must be a supported type.  The
   file must be an open file object such as ``sys.stdout`` or returned by
   :func:`open` or :func:`os.popen`.  It may not be a wrapper such as
   TemporaryFile on Windows. It must be opened in binary mode (``'wb'``
   or ``'w+b'``).

   If the value has (or contains an object that has) an unsupported type, a
   :exc:`ValueError` exception is raised --- but garbage data will also be written
   to the file.  The object will not be properly read back by :func:`load`.

   .. versionadded:: 2.4
      The *version* argument indicates the data format that ``dump`` should use
      (see below).


.. function:: load(file)

   Read one value from the open file and return it.  If no valid value is read
   (e.g. because the data has a different Python version's incompatible marshal
   format), raise :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`.  The
   file must be an open file object opened in binary mode (``'rb'`` or
   ``'r+b'``).

   .. note::

      If an object containing an unsupported type was marshalled with :func:`dump`,
      :func:`load` will substitute ``None`` for the unmarshallable type.


.. function:: dumps(value[, version])

   Return the string that would be written to a file by ``dump(value, file)``.  The
   value must be a supported type.  Raise a :exc:`ValueError` exception if value
   has (or contains an object that has) an unsupported type.

   .. versionadded:: 2.4
      The *version* argument indicates the data format that ``dumps`` should use
      (see below).


.. function:: loads(string)

   Convert the string to a value.  If no valid value is found, raise
   :exc:`EOFError`, :exc:`ValueError` or :exc:`TypeError`.  Extra characters in the
   string are ignored.


In addition, the following constants are defined:

.. data:: version

   Indicates the format that the module uses. Version 0 is the historical format,
   version 1 (added in Python 2.4) shares interned strings and version 2 (added in
   Python 2.5) uses a binary format for floating point numbers. The current version
   is 2.

   .. versionadded:: 2.4


.. rubric:: Footnotes

.. [#] The name of this module stems from a bit of terminology used by the designers of
   Modula-3 (amongst others), who use the term "marshalling" for shipping of data
   around in a self-contained form. Strictly speaking, "to marshal" means to
   convert some data from internal to external form (in an RPC buffer for instance)
   and "unmarshalling" for the reverse process.

PK	%�\Jg��*�*"html/_sources/library/math.rst.txtnu�[���
:mod:`math` --- Mathematical functions
======================================

.. module:: math
   :synopsis: Mathematical functions (sin() etc.).

.. testsetup::

   from math import fsum

This module is always available.  It provides access to the mathematical
functions defined by the C standard.

These functions cannot be used with complex numbers; use the functions of the
same name from the :mod:`cmath` module if you require support for complex
numbers.  The distinction between functions which support complex numbers and
those which don't is made since most users do not want to learn quite as much
mathematics as required to understand complex numbers.  Receiving an exception
instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it
was generated in the first place.

The following functions are provided by this module.  Except when explicitly
noted otherwise, all return values are floats.


Number-theoretic and representation functions
---------------------------------------------

.. function:: ceil(x)

   Return the ceiling of *x* as a float, the smallest integer value greater than or
   equal to *x*.


.. function:: copysign(x, y)

   Return *x* with the sign of *y*.  On a platform that supports
   signed zeros, ``copysign(1.0, -0.0)`` returns *-1.0*.

   .. versionadded:: 2.6


.. function:: fabs(x)

   Return the absolute value of *x*.


.. function:: factorial(x)

   Return *x* factorial.  Raises :exc:`ValueError` if *x* is not integral or
   is negative.

   .. versionadded:: 2.6


.. function:: floor(x)

   Return the floor of *x* as a float, the largest integer value less than or equal
   to *x*.


.. function:: fmod(x, y)

   Return ``fmod(x, y)``, as defined by the platform C library. Note that the
   Python expression ``x % y`` may not return the same result.  The intent of the C
   standard is that ``fmod(x, y)`` be exactly (mathematically; to infinite
   precision) equal to ``x - n*y`` for some integer *n* such that the result has
   the same sign as *x* and magnitude less than ``abs(y)``.  Python's ``x % y``
   returns a result with the sign of *y* instead, and may not be exactly computable
   for float arguments. For example, ``fmod(-1e-100, 1e100)`` is ``-1e-100``, but
   the result of Python's ``-1e-100 % 1e100`` is ``1e100-1e-100``, which cannot be
   represented exactly as a float, and rounds to the surprising ``1e100``.  For
   this reason, function :func:`fmod` is generally preferred when working with
   floats, while Python's ``x % y`` is preferred when working with integers.


.. function:: frexp(x)

   Return the mantissa and exponent of *x* as the pair ``(m, e)``.  *m* is a float
   and *e* is an integer such that ``x == m * 2**e`` exactly. If *x* is zero,
   returns ``(0.0, 0)``, otherwise ``0.5 <= abs(m) < 1``.  This is used to "pick
   apart" the internal representation of a float in a portable way.


.. function:: fsum(iterable)

   Return an accurate floating point sum of values in the iterable.  Avoids
   loss of precision by tracking multiple intermediate partial sums::

        >>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
        0.9999999999999999
        >>> fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
        1.0

   The algorithm's accuracy depends on IEEE-754 arithmetic guarantees and the
   typical case where the rounding mode is half-even.  On some non-Windows
   builds, the underlying C library uses extended precision addition and may
   occasionally double-round an intermediate sum causing it to be off in its
   least significant bit.

   For further discussion and two alternative approaches, see the `ASPN cookbook
   recipes for accurate floating point summation
   <https://code.activestate.com/recipes/393090/>`_\.

   .. versionadded:: 2.6


.. function:: isinf(x)

   Check if the float *x* is positive or negative infinity.

   .. versionadded:: 2.6


.. function:: isnan(x)

   Check if the float *x* is a NaN (not a number).  For more information
   on NaNs, see the IEEE 754 standards.

   .. versionadded:: 2.6


.. function:: ldexp(x, i)

   Return ``x * (2**i)``.  This is essentially the inverse of function
   :func:`frexp`.


.. function:: modf(x)

   Return the fractional and integer parts of *x*.  Both results carry the sign
   of *x* and are floats.


.. function:: trunc(x)

   Return the :class:`~numbers.Real` value *x* truncated to an
   :class:`~numbers.Integral` (usually a long integer).  Uses the
   ``__trunc__`` method.

   .. versionadded:: 2.6


Note that :func:`frexp` and :func:`modf` have a different call/return pattern
than their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an 'output
parameter' (there is no such thing in Python).

For the :func:`ceil`, :func:`floor`, and :func:`modf` functions, note that *all*
floating-point numbers of sufficiently large magnitude are exact integers.
Python floats typically carry no more than 53 bits of precision (the same as the
platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
necessarily has no fractional bits.


Power and logarithmic functions
-------------------------------

.. function:: exp(x)

   Return ``e**x``.


.. function:: expm1(x)

   Return ``e**x - 1``.  For small floats *x*, the subtraction in
   ``exp(x) - 1`` can result in a significant loss of precision; the
   :func:`expm1` function provides a way to compute this quantity to
   full precision::

      >>> from math import exp, expm1
      >>> exp(1e-5) - 1  # gives result accurate to 11 places
      1.0000050000069649e-05
      >>> expm1(1e-5)    # result accurate to full precision
      1.0000050000166668e-05

   .. versionadded:: 2.7


.. function:: log(x[, base])

   With one argument, return the natural logarithm of *x* (to base *e*).

   With two arguments, return the logarithm of *x* to the given *base*,
   calculated as ``log(x)/log(base)``.

   .. versionchanged:: 2.3
      *base* argument added.


.. function:: log1p(x)

   Return the natural logarithm of *1+x* (base *e*). The
   result is calculated in a way which is accurate for *x* near zero.

   .. versionadded:: 2.6


.. function:: log10(x)

   Return the base-10 logarithm of *x*.  This is usually more accurate
   than ``log(x, 10)``.


.. function:: pow(x, y)

   Return ``x`` raised to the power ``y``.  Exceptional cases follow
   Annex 'F' of the C99 standard as far as possible.  In particular,
   ``pow(1.0, x)`` and ``pow(x, 0.0)`` always return ``1.0``, even
   when ``x`` is a zero or a NaN.  If both ``x`` and ``y`` are finite,
   ``x`` is negative, and ``y`` is not an integer then ``pow(x, y)``
   is undefined, and raises :exc:`ValueError`.

   Unlike the built-in ``**`` operator, :func:`math.pow` converts both
   its arguments to type :class:`float`.  Use ``**`` or the built-in
   :func:`pow` function for computing exact integer powers.

   .. versionchanged:: 2.6
      The outcome of ``1**nan`` and ``nan**0`` was undefined.


.. function:: sqrt(x)

   Return the square root of *x*.


Trigonometric functions
-----------------------

.. function:: acos(x)

   Return the arc cosine of *x*, in radians.


.. function:: asin(x)

   Return the arc sine of *x*, in radians.


.. function:: atan(x)

   Return the arc tangent of *x*, in radians.


.. function:: atan2(y, x)

   Return ``atan(y / x)``, in radians. The result is between ``-pi`` and ``pi``.
   The vector in the plane from the origin to point ``(x, y)`` makes this angle
   with the positive X axis. The point of :func:`atan2` is that the signs of both
   inputs are known to it, so it can compute the correct quadrant for the angle.
   For example, ``atan(1)`` and ``atan2(1, 1)`` are both ``pi/4``, but ``atan2(-1,
   -1)`` is ``-3*pi/4``.


.. function:: cos(x)

   Return the cosine of *x* radians.


.. function:: hypot(x, y)

   Return the Euclidean norm, ``sqrt(x*x + y*y)``. This is the length of the vector
   from the origin to point ``(x, y)``.


.. function:: sin(x)

   Return the sine of *x* radians.


.. function:: tan(x)

   Return the tangent of *x* radians.


Angular conversion
------------------

.. function:: degrees(x)

   Convert angle *x* from radians to degrees.


.. function:: radians(x)

   Convert angle *x* from degrees to radians.


Hyperbolic functions
--------------------

.. function:: acosh(x)

   Return the inverse hyperbolic cosine of *x*.

   .. versionadded:: 2.6


.. function:: asinh(x)

   Return the inverse hyperbolic sine of *x*.

   .. versionadded:: 2.6


.. function:: atanh(x)

   Return the inverse hyperbolic tangent of *x*.

   .. versionadded:: 2.6


.. function:: cosh(x)

   Return the hyperbolic cosine of *x*.


.. function:: sinh(x)

   Return the hyperbolic sine of *x*.


.. function:: tanh(x)

   Return the hyperbolic tangent of *x*.


Special functions
-----------------

.. function:: erf(x)

   Return the error function at *x*.

   .. versionadded:: 2.7


.. function:: erfc(x)

   Return the complementary error function at *x*.

   .. versionadded:: 2.7


.. function:: gamma(x)

   Return the Gamma function at *x*.

   .. versionadded:: 2.7


.. function:: lgamma(x)

   Return the natural logarithm of the absolute value of the Gamma
   function at *x*.

   .. versionadded:: 2.7


Constants
---------

.. data:: pi

   The mathematical constant π = 3.141592..., to available precision.


.. data:: e

   The mathematical constant e = 2.718281..., to available precision.


.. impl-detail::

   The :mod:`math` module consists mostly of thin wrappers around the platform C
   math library functions.  Behavior in exceptional cases follows Annex F of
   the C99 standard where appropriate.  The current implementation will raise
   :exc:`ValueError` for invalid operations like ``sqrt(-1.0)`` or ``log(0.0)``
   (where C99 Annex F recommends signaling invalid operation or divide-by-zero),
   and :exc:`OverflowError` for results that overflow (for example,
   ``exp(1000.0)``).  A NaN will not be returned from any of the functions
   above unless one or more of the input arguments was a NaN; in that case,
   most functions will return a NaN, but (again following C99 Annex F) there
   are some exceptions to this rule, for example ``pow(float('nan'), 0.0)`` or
   ``hypot(float('nan'), float('inf'))``.

   Note that Python makes no effort to distinguish signaling NaNs from
   quiet NaNs, and behavior for signaling NaNs remains unspecified.
   Typical behavior is to treat all NaNs as though they were quiet.

   .. versionchanged:: 2.6
      Behavior in special cases now aims to follow C99 Annex F.  In earlier
      versions of Python the behavior in special cases was loosely specified.


.. seealso::

   Module :mod:`cmath`
      Complex number versions of many of these functions.
PK	%�\���9�
�
!html/_sources/library/md5.rst.txtnu�[���
:mod:`md5` --- MD5 message digest algorithm
===========================================

.. module:: md5
   :synopsis: RSA's MD5 message digest algorithm.
   :deprecated:


.. deprecated:: 2.5
   Use the :mod:`hashlib` module instead.

.. index::
   single: message digest, MD5
   single: checksum; MD5

This module implements the interface to RSA's MD5 message digest  algorithm (see
also Internet :rfc:`1321`).  Its use is quite straightforward: use :func:`new`
to create an md5 object. You can now feed this object with arbitrary strings
using the :meth:`update` method, and at any point you can ask it for the
:dfn:`digest` (a strong kind of 128-bit checksum, a.k.a. "fingerprint") of the
concatenation of the strings fed to it so far using the :meth:`digest` method.

For example, to obtain the digest of the string ``'Nobody inspects the spammish
repetition'``:

   >>> import md5
   >>> m = md5.new()
   >>> m.update("Nobody inspects")
   >>> m.update(" the spammish repetition")
   >>> m.digest()
   '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

More condensed:

   >>> md5.new("Nobody inspects the spammish repetition").digest()
   '\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

The following values are provided as constants in the module and as attributes
of the md5 objects returned by :func:`new`:


.. data:: digest_size

   The size of the resulting digest in bytes.  This is always ``16``.

The md5 module provides the following functions:


.. function:: new([arg])

   Return a new md5 object.  If *arg* is present, the method call ``update(arg)``
   is made.


.. function:: md5([arg])

   For backward compatibility reasons, this is an alternative name for the
   :func:`new` function.

An md5 object has the following methods:


.. method:: md5.update(arg)

   Update the md5 object with the string *arg*.  Repeated calls are equivalent to a
   single call with the concatenation of all the arguments: ``m.update(a);
   m.update(b)`` is equivalent to ``m.update(a+b)``.


.. method:: md5.digest()

   Return the digest of the strings passed to the :meth:`update` method so far.
   This is a 16-byte string which may contain non-ASCII characters, including null
   bytes.


.. method:: md5.hexdigest()

   Like :meth:`digest` except the digest is returned as a string of length 32,
   containing only hexadecimal digits.  This may  be used to exchange the value
   safely in email or other non-binary environments.


.. method:: md5.copy()

   Return a copy ("clone") of the md5 object.  This can be used to efficiently
   compute the digests of strings that share a common initial substring.


.. seealso::

   Module :mod:`sha`
      Similar module implementing the Secure Hash Algorithm (SHA).  The SHA algorithm
      is considered a more secure hash.

PK	%�\�Rہ~~#html/_sources/library/mhlib.rst.txtnu�[���:mod:`mhlib` --- Access to MH mailboxes
=======================================

.. module:: mhlib
   :synopsis: Manipulate MH mailboxes from Python.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`mhlib` module has been removed in Python 3. Use the
    :mod:`mailbox` instead.

.. sectionauthor:: Skip Montanaro <skip@pobox.com>

The :mod:`mhlib` module provides a Python interface to MH folders and their
contents.

The module contains three basic classes, :class:`MH`, which represents a
particular collection of folders, :class:`Folder`, which represents a single
folder, and :class:`Message`, which represents a single message.


.. class:: MH([path[, profile]])

   :class:`MH` represents a collection of MH folders.


.. class:: Folder(mh, name)

   The :class:`Folder` class represents a single folder and its messages.


.. class:: Message(folder, number[, name])

   :class:`Message` objects represent individual messages in a folder.  The Message
   class is derived from :class:`mimetools.Message`.


.. _mh-objects:

MH Objects
----------

:class:`MH` instances have the following methods:


.. method:: MH.error(format[, ...])

   Print an error message -- can be overridden.


.. method:: MH.getprofile(key)

   Return a profile entry (``None`` if not set).


.. method:: MH.getpath()

   Return the mailbox pathname.


.. method:: MH.getcontext()

   Return the current folder name.


.. method:: MH.setcontext(name)

   Set the current folder name.


.. method:: MH.listfolders()

   Return a list of top-level folders.


.. method:: MH.listallfolders()

   Return a list of all folders.


.. method:: MH.listsubfolders(name)

   Return a list of direct subfolders of the given folder.


.. method:: MH.listallsubfolders(name)

   Return a list of all subfolders of the given folder.


.. method:: MH.makefolder(name)

   Create a new folder.


.. method:: MH.deletefolder(name)

   Delete a folder -- must have no subfolders.


.. method:: MH.openfolder(name)

   Return a new open folder object.


.. _mh-folder-objects:

Folder Objects
--------------

:class:`Folder` instances represent open folders and have the following methods:


.. method:: Folder.error(format[, ...])

   Print an error message -- can be overridden.


.. method:: Folder.getfullname()

   Return the folder's full pathname.


.. method:: Folder.getsequencesfilename()

   Return the full pathname of the folder's sequences file.


.. method:: Folder.getmessagefilename(n)

   Return the full pathname of message *n* of the folder.


.. method:: Folder.listmessages()

   Return a list of messages in the folder (as numbers).


.. method:: Folder.getcurrent()

   Return the current message number.


.. method:: Folder.setcurrent(n)

   Set the current message number to *n*.


.. method:: Folder.parsesequence(seq)

   Parse msgs syntax into list of messages.


.. method:: Folder.getlast()

   Get last message, or ``0`` if no messages are in the folder.


.. method:: Folder.setlast(n)

   Set last message (internal use only).


.. method:: Folder.getsequences()

   Return dictionary of sequences in folder.  The sequence names are used  as keys,
   and the values are the lists of message numbers in the sequences.


.. method:: Folder.putsequences(dict)

   Return dictionary of sequences in folder name: list.


.. method:: Folder.removemessages(list)

   Remove messages in list from folder.


.. method:: Folder.refilemessages(list, tofolder)

   Move messages in list to other folder.


.. method:: Folder.movemessage(n, tofolder, ton)

   Move one message to a given destination in another folder.


.. method:: Folder.copymessage(n, tofolder, ton)

   Copy one message to a given destination in another folder.


.. _mh-message-objects:

Message Objects
---------------

The :class:`Message` class adds one method to those of
:class:`mimetools.Message`:


.. method:: Message.openmessage(n)

   Return a new open message object (costs a file descriptor).

PK	%�\�6J��'html/_sources/library/mimetools.rst.txtnu�[���
:mod:`mimetools` --- Tools for parsing MIME messages
====================================================

.. module:: mimetools
   :synopsis: Tools for parsing MIME-style message bodies.
   :deprecated:


.. deprecated:: 2.3
   The :mod:`email` package should be used in preference to the :mod:`mimetools`
   module.  This module is present only to maintain backward compatibility, and
   it has been removed in 3.x.

.. index:: module: rfc822

This module defines a subclass of the :mod:`rfc822` module's :class:`Message`
class and a number of utility functions that are useful for the manipulation for
MIME multipart or encoded message.

It defines the following items:


.. class:: Message(fp[, seekable])

   Return a new instance of the :class:`Message` class.  This is a subclass of the
   :class:`rfc822.Message` class, with some additional methods (see below).  The
   *seekable* argument has the same meaning as for :class:`rfc822.Message`.


.. function:: choose_boundary()

   Return a unique string that has a high likelihood of being usable as a part
   boundary.  The string has the form ``'hostipaddr.uid.pid.timestamp.random'``.


.. function:: decode(input, output, encoding)

   Read data encoded using the allowed MIME *encoding* from open file object
   *input* and write the decoded data to open file object *output*.  Valid values
   for *encoding* include ``'base64'``, ``'quoted-printable'``, ``'uuencode'``,
   ``'x-uuencode'``, ``'uue'``, ``'x-uue'``, ``'7bit'``, and  ``'8bit'``.  Decoding
   messages encoded in ``'7bit'`` or ``'8bit'`` has no effect.  The input is simply
   copied to the output.


.. function:: encode(input, output, encoding)

   Read data from open file object *input* and write it encoded using the allowed
   MIME *encoding* to open file object *output*. Valid values for *encoding* are
   the same as for :meth:`decode`.


.. function:: copyliteral(input, output)

   Read lines from open file *input* until EOF and write them to open file
   *output*.


.. function:: copybinary(input, output)

   Read blocks until EOF from open file *input* and write them to open file
   *output*.  The block size is currently fixed at 8192.


.. seealso::

   Module :mod:`email`
      Comprehensive email handling package; supersedes the :mod:`mimetools` module.

   Module :mod:`rfc822`
      Provides the base class for :class:`mimetools.Message`.

   Module :mod:`multifile`
      Support for reading files which contain distinct parts, such as MIME data.

   http://faqs.cs.uu.nl/na-dir/mail/mime-faq/.html
      The MIME Frequently Asked Questions document.  For an overview of MIME, see the
      answer to question 1.1 in Part 1 of this document.


.. _mimetools-message-objects:

Additional Methods of Message Objects
-------------------------------------

The :class:`Message` class defines the following methods in addition to the
:class:`rfc822.Message` methods:


.. method:: Message.getplist()

   Return the parameter list of the :mailheader:`Content-Type` header. This is a
   list of strings.  For parameters of the form ``key=value``, *key* is converted
   to lower case but *value* is not.  For example, if the message contains the
   header ``Content-type: text/html; spam=1; Spam=2; Spam`` then :meth:`getplist`
   will return the Python list ``['spam=1', 'spam=2', 'Spam']``.


.. method:: Message.getparam(name)

   Return the *value* of the first parameter (as returned by :meth:`getplist`) of
   the form ``name=value`` for the given *name*.  If *value* is surrounded by
   quotes of the form '``<``...\ ``>``' or '``"``...\ ``"``', these are removed.


.. method:: Message.getencoding()

   Return the encoding specified in the :mailheader:`Content-Transfer-Encoding`
   message header.  If no such header exists, return ``'7bit'``.  The encoding is
   converted to lower case.


.. method:: Message.gettype()

   Return the message type (of the form ``type/subtype``) as specified in the
   :mailheader:`Content-Type` header.  If no such header exists, return
   ``'text/plain'``.  The type is converted to lower case.


.. method:: Message.getmaintype()

   Return the main type as specified in the :mailheader:`Content-Type` header.  If
   no such header exists, return ``'text'``.  The main type is converted to lower
   case.


.. method:: Message.getsubtype()

   Return the subtype as specified in the :mailheader:`Content-Type` header.  If no
   such header exists, return ``'plain'``.  The subtype is converted to lower case.

PK	%�\='.�o&o&'html/_sources/library/mimetypes.rst.txtnu�[���:mod:`mimetypes` --- Map filenames to MIME types
================================================

.. module:: mimetypes
   :synopsis: Mapping of filename extensions to MIME types.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. index:: pair: MIME; content type

**Source code:** :source:`Lib/mimetypes.py`

--------------

The :mod:`mimetypes` module converts between a filename or URL and the MIME type
associated with the filename extension.  Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not
supported for the latter conversion.

The module provides one class and a number of convenience functions. The
functions are the normal interface to this module, but some applications may be
interested in the class as well.

The functions described below provide the primary interface for this module.  If
the module has not been initialized, they will call :func:`init` if they rely on
the information :func:`init` sets up.


.. function:: guess_type(url, strict=True)

   .. index:: pair: MIME; headers

   Guess the type of a file based on its filename or URL, given by *url*.  The
   return value is a tuple ``(type, encoding)`` where *type* is ``None`` if the
   type can't be guessed (missing or unknown suffix) or a string of the form
   ``'type/subtype'``, usable for a MIME :mailheader:`content-type` header.

   *encoding* is ``None`` for no encoding or the name of the program used to encode
   (e.g. :program:`compress` or :program:`gzip`). The encoding is suitable for use
   as a :mailheader:`Content-Encoding` header, **not** as a
   :mailheader:`Content-Transfer-Encoding` header. The mappings are table driven.
   Encoding suffixes are case sensitive; type suffixes are first tried case
   sensitively, then case insensitively.

   The optional *strict* argument is a flag specifying whether the list of known MIME types
   is limited to only the official types `registered with IANA
   <https://www.iana.org/assignments/media-types/media-types.xhtml>`_.
   When *strict* is ``True`` (the default), only the IANA types are supported; when
   *strict* is ``False``, some additional non-standard but commonly used MIME types
   are also recognized.


.. function:: guess_all_extensions(type, strict=True)

   Guess the extensions for a file based on its MIME type, given by *type*. The
   return value is a list of strings giving all possible filename extensions,
   including the leading dot (``'.'``).  The extensions are not guaranteed to have
   been associated with any particular data stream, but would be mapped to the MIME
   type *type* by :func:`guess_type`.

   The optional *strict* argument has the same meaning as with the :func:`guess_type` function.


.. function:: guess_extension(type, strict=True)

   Guess the extension for a file based on its MIME type, given by *type*. The
   return value is a string giving a filename extension, including the leading dot
   (``'.'``).  The extension is not guaranteed to have been associated with any
   particular data stream, but would be mapped to the MIME type *type* by
   :func:`guess_type`.  If no extension can be guessed for *type*, ``None`` is
   returned.

   The optional *strict* argument has the same meaning as with the :func:`guess_type` function.

Some additional functions and data items are available for controlling the
behavior of the module.


.. function:: init(files=None)

   Initialize the internal data structures.  If given, *files* must be a sequence
   of file names which should be used to augment the default type map.  If omitted,
   the file names to use are taken from :const:`knownfiles`; on Windows, the
   current registry settings are loaded.  Each file named in *files* or
   :const:`knownfiles` takes precedence over those named before it.  Calling
   :func:`init` repeatedly is allowed.

   Specifying an empty list for *files* will prevent the system defaults from
   being applied: only the well-known values will be present from a built-in list.

   .. versionchanged:: 2.7
      Previously, Windows registry settings were ignored.


.. function:: read_mime_types(filename)

   Load the type map given in the file *filename*, if it exists.  The type map is
   returned as a dictionary mapping filename extensions, including the leading dot
   (``'.'``), to strings of the form ``'type/subtype'``.  If the file *filename*
   does not exist or cannot be read, ``None`` is returned.


.. function:: add_type(type, ext, strict=True)

   Add a mapping from the MIME type *type* to the extension *ext*. When the
   extension is already known, the new type will replace the old one. When the type
   is already known the extension will be added to the list of known extensions.

   When *strict* is ``True`` (the default), the mapping will be added to the
   official MIME types, otherwise to the non-standard ones.


.. data:: inited

   Flag indicating whether or not the global data structures have been initialized.
   This is set to ``True`` by :func:`init`.


.. data:: knownfiles

   .. index:: single: file; mime.types

   List of type map file names commonly installed.  These files are typically named
   :file:`mime.types` and are installed in different locations by different
   packages.


.. data:: suffix_map

   Dictionary mapping suffixes to suffixes.  This is used to allow recognition of
   encoded files for which the encoding and the type are indicated by the same
   extension.  For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz`
   to allow the encoding and type to be recognized separately.


.. data:: encodings_map

   Dictionary mapping filename extensions to encoding types.


.. data:: types_map

   Dictionary mapping filename extensions to MIME types.


.. data:: common_types

   Dictionary mapping filename extensions to non-standard, but commonly found MIME
   types.


An example usage of the module::

   >>> import mimetypes
   >>> mimetypes.init()
   >>> mimetypes.knownfiles
   ['/etc/mime.types', '/etc/httpd/mime.types', ... ]
   >>> mimetypes.suffix_map['.tgz']
   '.tar.gz'
   >>> mimetypes.encodings_map['.gz']
   'gzip'
   >>> mimetypes.types_map['.tgz']
   'application/x-tar-gz'


.. _mimetypes-objects:

MimeTypes Objects
-----------------

The :class:`MimeTypes` class may be useful for applications which may want more
than one MIME-type database; it provides an interface similar to the one of the
:mod:`mimetypes` module.


.. class:: MimeTypes(filenames=(), strict=True)

   This class represents a MIME-types database.  By default, it provides access to
   the same database as the rest of this module. The initial database is a copy of
   that provided by the module, and may be extended by loading additional
   :file:`mime.types`\ -style files into the database using the :meth:`read` or
   :meth:`readfp` methods.  The mapping dictionaries may also be cleared before
   loading additional data if the default data is not desired.

   The optional *filenames* parameter can be used to cause additional files to be
   loaded "on top" of the default database.


   .. attribute:: MimeTypes.suffix_map

      Dictionary mapping suffixes to suffixes.  This is used to allow recognition of
      encoded files for which the encoding and the type are indicated by the same
      extension.  For example, the :file:`.tgz` extension is mapped to :file:`.tar.gz`
      to allow the encoding and type to be recognized separately.  This is initially a
      copy of the global :data:`suffix_map` defined in the module.


   .. attribute:: MimeTypes.encodings_map

      Dictionary mapping filename extensions to encoding types.  This is initially a
      copy of the global :data:`encodings_map` defined in the module.


   .. attribute:: MimeTypes.types_map

      Tuple containing two dictionaries, mapping filename extensions to MIME types:
      the first dictionary is for the non-standards types and the second one is for
      the standard types. They are initialized by :data:`common_types` and
      :data:`types_map`.


   .. attribute:: MimeTypes.types_map_inv

      Tuple containing two dictionaries, mapping MIME types to a list of filename
      extensions: the first dictionary is for the non-standards types and the
      second one is for the standard types. They are initialized by
      :data:`common_types` and :data:`types_map`.


   .. method:: MimeTypes.guess_extension(type, strict=True)

      Similar to the :func:`guess_extension` function, using the tables stored as part
      of the object.


   .. method:: MimeTypes.guess_type(url, strict=True)

      Similar to the :func:`guess_type` function, using the tables stored as part of
      the object.


   .. method:: MimeTypes.guess_all_extensions(type, strict=True)

      Similar to the :func:`guess_all_extensions` function, using the tables stored
      as part of the object.


   .. method:: MimeTypes.read(filename, strict=True)

      Load MIME information from a file named *filename*.  This uses :meth:`readfp` to
      parse the file.

      If *strict* is ``True``, information will be added to list of standard types,
      else to the list of non-standard types.


   .. method:: MimeTypes.readfp(fp, strict=True)

      Load MIME type information from an open file *fp*.  The file must have the format of
      the standard :file:`mime.types` files.

      If *strict* is ``True``, information will be added to the list of standard
      types, else to the list of non-standard types.


   .. method:: MimeTypes.read_windows_registry(strict=True)

      Load MIME type information from the Windows registry.  Availability: Windows.

      If *strict* is ``True``, information will be added to the list of standard
      types, else to the list of non-standard types.

      .. versionadded:: 2.7
PK	%�\��r. 
 
(html/_sources/library/mimewriter.rst.txtnu�[���:mod:`MimeWriter` --- Generic MIME file writer
==============================================

.. module:: MimeWriter
   :synopsis: Write MIME format files.
   :deprecated:

.. sectionauthor:: Christopher G. Petrilli <petrilli@amber.org>


.. deprecated:: 2.3
   The :mod:`email` package should be used in preference to the :mod:`MimeWriter`
   module.  This module is present only to maintain backward compatibility.

This module defines the class :class:`~MimeWriter.MimeWriter`.  The :class:`~MimeWriter.MimeWriter`
class implements a basic formatter for creating MIME multi-part files.  It
doesn't seek around the output file nor does it use large amounts of buffer
space. You must write the parts out in the order that they should occur in the
final file. :class:`~MimeWriter.MimeWriter` does buffer the headers you add, allowing you
to rearrange their order.


.. class:: MimeWriter(fp)

   Return a new instance of the :class:`~MimeWriter.MimeWriter` class.  The only argument
   passed, *fp*, is a file object to be used for writing. Note that a
   :class:`~StringIO.StringIO` object could also be used.


.. _mimewriter-objects:

MimeWriter Objects
------------------

:class:`~MimeWriter.MimeWriter` instances have the following methods:


.. method:: MimeWriter.addheader(key, value[, prefix])

   Add a header line to the MIME message. The *key* is the name of the header,
   where the *value* obviously provides the value of the header. The optional
   argument *prefix* determines where the header  is inserted; ``0`` means append
   at the end, ``1`` is insert at the start. The default is to append.


.. method:: MimeWriter.flushheaders()

   Causes all headers accumulated so far to be written out (and forgotten). This is
   useful if you don't need a body part at all, e.g. for a subpart of type
   :mimetype:`message/rfc822` that's (mis)used to store some header-like
   information.


.. method:: MimeWriter.startbody(ctype[, plist[, prefix]])

   Returns a file-like object which can be used to write to the body of the
   message.  The content-type is set to the provided *ctype*, and the optional
   parameter *plist* provides additional parameters for the content-type
   declaration. *prefix* functions as in :meth:`addheader` except that the default
   is to insert at the start.


.. method:: MimeWriter.startmultipartbody(subtype[, boundary[, plist[, prefix]]])

   Returns a file-like object which can be used to write to the body of the
   message.  Additionally, this method initializes the multi-part code, where
   *subtype* provides the multipart subtype, *boundary* may provide a user-defined
   boundary specification, and *plist* provides optional parameters for the
   subtype. *prefix* functions as in :meth:`startbody`.  Subparts should be created
   using :meth:`nextpart`.


.. method:: MimeWriter.nextpart()

   Returns a new instance of :class:`~MimeWriter.MimeWriter` which represents an individual
   part in a multipart message.  This may be used to write the  part as well as
   used for creating recursively complex multipart messages. The message must first
   be initialized with :meth:`startmultipartbody` before using :meth:`nextpart`.


.. method:: MimeWriter.lastpart()

   This is used to designate the last part of a multipart message, and should
   *always* be used when writing multipart messages.

PK	%�\���
�
$html/_sources/library/mimify.rst.txtnu�[���
:mod:`mimify` --- MIME processing of mail messages
==================================================

.. module:: mimify
   :synopsis: Mimification and unmimification of mail messages.
   :deprecated:


.. deprecated:: 2.3
   The :mod:`email` package should be used in preference to the :mod:`mimify`
   module.  This module is present only to maintain backward compatibility.

The :mod:`mimify` module defines two functions to convert mail messages to and
from MIME format.  The mail message can be either a simple message or a
so-called multipart message.  Each part is treated separately. Mimifying (a part
of) a message entails encoding the message as quoted-printable if it contains
any characters that cannot be represented using 7-bit ASCII.  Unmimifying (a
part of) a message entails undoing the quoted-printable encoding.  Mimify and
unmimify are especially useful when a message has to be edited before being
sent.  Typical use would be::

   unmimify message
   edit message
   mimify message
   send message

The modules defines the following user-callable functions and user-settable
variables:


.. function:: mimify(infile, outfile)

   Copy the message in *infile* to *outfile*, converting parts to quoted-printable
   and adding MIME mail headers when necessary. *infile* and *outfile* can be file
   objects (actually, any object that has a :meth:`readline` method (for *infile*)
   or a :meth:`write` method (for *outfile*)) or strings naming the files. If
   *infile* and *outfile* are both strings, they may have the same value.


.. function:: unmimify(infile, outfile[, decode_base64])

   Copy the message in *infile* to *outfile*, decoding all quoted-printable parts.
   *infile* and *outfile* can be file objects (actually, any object that has a
   :meth:`readline` method (for *infile*) or a :meth:`write` method (for
   *outfile*)) or strings naming the files.  If *infile* and *outfile* are both
   strings, they may have the same value. If the *decode_base64* argument is
   provided and tests true, any parts that are coded in the base64 encoding are
   decoded as well.


.. function:: mime_decode_header(line)

   Return a decoded version of the encoded header line in *line*. This only
   supports the ISO 8859-1 charset (Latin-1).


.. function:: mime_encode_header(line)

   Return a MIME-encoded version of the header line in *line*.


.. data:: MAXLEN

   By default, a part will be encoded as quoted-printable when it contains any
   non-ASCII characters (characters with the 8th bit set), or if there are any
   lines longer than :const:`MAXLEN` characters (default value 200).


.. data:: CHARSET

   When not specified in the mail headers, a character set must be filled in.  The
   string used is stored in :const:`CHARSET`, and the default value is ISO-8859-1
   (also known as Latin1 (latin-one)).

This module can also be used from the command line.  Usage is as follows::

   mimify.py -e [-l length] [infile [outfile]]
   mimify.py -d [-b] [infile [outfile]]

to encode (mimify) and decode (unmimify) respectively.  *infile* defaults to
standard input, *outfile* defaults to standard output. The same file can be
specified for input and output.

If the **-l** option is given when encoding, if there are any lines longer than
the specified *length*, the containing part will be encoded.

If the **-b** option is given when decoding, any base64 parts will be decoded as
well.


.. seealso::

   Module :mod:`quopri`
      Encode and decode MIME quoted-printable files.

PK	%�\��	

)html/_sources/library/miniaeframe.rst.txtnu�[���
:mod:`MiniAEFrame` --- Open Scripting Architecture server support
=================================================================

.. module:: MiniAEFrame
   :platform: Mac
   :synopsis: Support to act as an Open Scripting Architecture (OSA) server ("Apple Events").


.. index::
   single: Open Scripting Architecture
   single: AppleEvents
   module: FrameWork

The module :mod:`MiniAEFrame` provides a framework for an application that can
function as an Open Scripting Architecture  (OSA) server, i.e. receive and
process AppleEvents. It can be used in conjunction with :mod:`FrameWork` or
standalone. As an example, it is used in :program:`PythonCGISlave`.

The :mod:`MiniAEFrame` module defines the following classes:


.. class:: AEServer()

   A class that handles AppleEvent dispatch. Your application should subclass this
   class together with either :class:`MiniApplication` or
   :class:`FrameWork.Application`. Your :meth:`__init__` method should call the
   :meth:`__init__` method for both classes.


.. class:: MiniApplication()

   A class that is more or less compatible with :class:`FrameWork.Application` but
   with less functionality. Its event loop supports the apple menu, command-dot and
   AppleEvents; other events are passed on to the Python interpreter and/or Sioux.
   Useful if your application wants to use :class:`AEServer` but does not provide
   its own windows, etc.


.. _aeserver-objects:

AEServer Objects
----------------


.. method:: AEServer.installaehandler(classe, type, callback)

   Installs an AppleEvent handler. *classe* and *type* are the four-character OSA
   Class and Type designators, ``'****'`` wildcards are allowed. When a matching
   AppleEvent is received the parameters are decoded and your callback is invoked.


.. method:: AEServer.callback(_object, **kwargs)

   Your callback is called with the OSA Direct Object as first positional
   parameter. The other parameters are passed as keyword arguments, with the
   4-character designator as name. Three extra keyword parameters are passed:
   ``_class`` and ``_type`` are the Class and Type designators and ``_attributes``
   is a dictionary with the AppleEvent attributes.

   The return value of your method is packed with :func:`aetools.packevent` and
   sent as reply.

Note that there are some serious problems with the current design. AppleEvents
which have non-identifier 4-character designators for arguments are not
implementable, and it is not possible to return an error to the originator. This
will be addressed in a future release.

PK	%�\��O���"html/_sources/library/misc.rst.txtnu�[���
.. _misc:

**********************
Miscellaneous Services
**********************

The modules described in this chapter provide miscellaneous services that are
available in all Python versions.  Here's an overview:


.. toctree::

   formatter.rst
PK	%�\�I6-�� html/_sources/library/mm.rst.txtnu�[���
.. _mmedia:

*******************
Multimedia Services
*******************

The modules described in this chapter implement various algorithms or interfaces
that are mainly useful for multimedia applications.  They are available at the
discretion of the installation.  Here's an overview:


.. toctree::

   audioop.rst
   imageop.rst
   aifc.rst
   sunau.rst
   wave.rst
   chunk.rst
   colorsys.rst
   imghdr.rst
   sndhdr.rst
   ossaudiodev.rst
PK	%�\�},5�(�("html/_sources/library/mmap.rst.txtnu�[���
:mod:`mmap` --- Memory-mapped file support
==========================================

.. module:: mmap
   :synopsis: Interface to memory-mapped files for Unix and Windows.


Memory-mapped file objects behave like both strings and like file objects.
Unlike normal string objects, however, these are mutable.  You can use mmap
objects in most places where strings are expected; for example, you can use
the :mod:`re` module to search through a memory-mapped file.  Since they're
mutable, you can change a single character by doing ``obj[index] = 'a'``, or
change a substring by assigning to a slice: ``obj[i1:i2] = '...'``.  You can
also read and write data starting at the current file position, and
:meth:`seek` through the file to different positions.

A memory-mapped file is created by the :class:`~mmap.mmap` constructor, which is
different on Unix and on Windows.  In either case you must provide a file
descriptor for a file opened for update. If you wish to map an existing Python
file object, use its :meth:`fileno` method to obtain the correct value for the
*fileno* parameter.  Otherwise, you can open the file using the
:func:`os.open` function, which returns a file descriptor directly (the file
still needs to be closed when done).

.. note::
   If you want to create a memory-mapping for a writable, buffered file, you
   should :func:`~io.IOBase.flush` the file first.  This is necessary to ensure
   that local modifications to the buffers are actually available to the
   mapping.

For both the Unix and Windows versions of the constructor, *access* may be
specified as an optional keyword parameter. *access* accepts one of three
values: :const:`ACCESS_READ`, :const:`ACCESS_WRITE`, or :const:`ACCESS_COPY`
to specify read-only, write-through or copy-on-write memory respectively.
*access* can be used on both Unix and Windows.  If *access* is not specified,
Windows mmap returns a write-through mapping.  The initial memory values for
all three access types are taken from the specified file.  Assignment to an
:const:`ACCESS_READ` memory map raises a :exc:`TypeError` exception.
Assignment to an :const:`ACCESS_WRITE` memory map affects both memory and the
underlying file.  Assignment to an :const:`ACCESS_COPY` memory map affects
memory but does not update the underlying file.

.. versionchanged:: 2.5
   To map anonymous memory, -1 should be passed as the fileno along with the
   length.

.. versionchanged:: 2.6
   mmap.mmap has formerly been a factory function creating mmap objects. Now
   mmap.mmap is the class itself.

.. class:: mmap(fileno, length[, tagname[, access[, offset]]])

   **(Windows version)** Maps *length* bytes from the file specified by the
   file handle *fileno*, and creates a mmap object.  If *length* is larger
   than the current size of the file, the file is extended to contain *length*
   bytes.  If *length* is ``0``, the maximum length of the map is the current
   size of the file, except that if the file is empty Windows raises an
   exception (you cannot create an empty mapping on Windows).

   *tagname*, if specified and not ``None``, is a string giving a tag name for
   the mapping.  Windows allows you to have many different mappings against
   the same file.  If you specify the name of an existing tag, that tag is
   opened, otherwise a new tag of this name is created.  If this parameter is
   omitted or ``None``, the mapping is created without a name.  Avoiding the
   use of the tag parameter will assist in keeping your code portable between
   Unix and Windows.

   *offset* may be specified as a non-negative integer offset. mmap references
   will be relative to the offset from the beginning of the file. *offset*
   defaults to 0.  *offset* must be a multiple of the :const:`ALLOCATIONGRANULARITY`.


.. class:: mmap(fileno, length[, flags[, prot[, access[, offset]]]])
   :noindex:

   **(Unix version)** Maps *length* bytes from the file specified by the file
   descriptor *fileno*, and returns a mmap object.  If *length* is ``0``, the
   maximum length of the map will be the current size of the file when
   :class:`~mmap.mmap` is called.

   *flags* specifies the nature of the mapping. :const:`MAP_PRIVATE` creates a
   private copy-on-write mapping, so changes to the contents of the mmap
   object will be private to this process, and :const:`MAP_SHARED` creates a
   mapping that's shared with all other processes mapping the same areas of
   the file.  The default value is :const:`MAP_SHARED`.

   *prot*, if specified, gives the desired memory protection; the two most
   useful values are :const:`PROT_READ` and :const:`PROT_WRITE`, to specify
   that the pages may be read or written.  *prot* defaults to
   :const:`PROT_READ \| PROT_WRITE`.

   *access* may be specified in lieu of *flags* and *prot* as an optional
   keyword parameter.  It is an error to specify both *flags*, *prot* and
   *access*.  See the description of *access* above for information on how to
   use this parameter.

   *offset* may be specified as a non-negative integer offset. mmap references
   will be relative to the offset from the beginning of the file. *offset*
   defaults to 0. *offset* must be a multiple of :const:`ALLOCATIONGRANULARITY`
   which is equal to :const:`PAGESIZE` on Unix systems.

   To ensure validity of the created memory mapping the file specified
   by the descriptor *fileno* is internally automatically synchronized
   with physical backing store on Mac OS X and OpenVMS.

   This example shows a simple way of using :class:`~mmap.mmap`::

      import mmap

      # write a simple example file
      with open("hello.txt", "wb") as f:
          f.write("Hello Python!\n")

      with open("hello.txt", "r+b") as f:
          # memory-map the file, size 0 means whole file
          mm = mmap.mmap(f.fileno(), 0)
          # read content via standard file methods
          print mm.readline()  # prints "Hello Python!"
          # read content via slice notation
          print mm[:5]  # prints "Hello"
          # update content using slice notation;
          # note that new content must have same size
          mm[6:] = " world!\n"
          # ... and read again using standard file methods
          mm.seek(0)
          print mm.readline()  # prints "Hello  world!"
          # close the map
          mm.close()


   The next example demonstrates how to create an anonymous map and exchange
   data between the parent and child processes::

      import mmap
      import os

      mm = mmap.mmap(-1, 13)
      mm.write("Hello world!")

      pid = os.fork()

      if pid == 0:  # In a child process
          mm.seek(0)
          print mm.readline()

          mm.close()


   Memory-mapped file objects support the following methods:


   .. method:: close()

      Closes the mmap. Subsequent calls to other methods of the object will
      result in a ValueError exception being raised. This will not close
      the open file.


   .. method:: find(string[, start[, end]])

      Returns the lowest index in the object where the substring *string* is
      found, such that *string* is contained in the range [*start*, *end*].
      Optional arguments *start* and *end* are interpreted as in slice notation.
      Returns ``-1`` on failure.


   .. method:: flush([offset, size])

      Flushes changes made to the in-memory copy of a file back to disk. Without
      use of this call there is no guarantee that changes are written back before
      the object is destroyed.  If *offset* and *size* are specified, only
      changes to the given range of bytes will be flushed to disk; otherwise, the
      whole extent of the mapping is flushed.  *offset* must be a multiple of the
      :const:`PAGESIZE` or :const:`ALLOCATIONGRANULARITY`.

      **(Windows version)** A nonzero value returned indicates success; zero
      indicates failure.

      **(Unix version)** A zero value is returned to indicate success. An
      exception is raised when the call failed.


   .. method:: move(dest, src, count)

      Copy the *count* bytes starting at offset *src* to the destination index
      *dest*.  If the mmap was created with :const:`ACCESS_READ`, then calls to
      move will raise a :exc:`TypeError` exception.


   .. method:: read(num)

      Return a string containing up to *num* bytes starting from the current
      file position; the file position is updated to point after the bytes that
      were returned.


   .. method:: read_byte()

      Returns a string of length 1 containing the character at the current file
      position, and advances the file position by 1.


   .. method:: readline()

      Returns a single line, starting at the current file position and up to the
      next newline.


   .. method:: resize(newsize)

      Resizes the map and the underlying file, if any. If the mmap was created
      with :const:`ACCESS_READ` or :const:`ACCESS_COPY`, resizing the map will
      raise a :exc:`TypeError` exception.


   .. method:: rfind(string[, start[, end]])

      Returns the highest index in the object where the substring *string* is
      found, such that *string* is contained in the range [*start*, *end*].
      Optional arguments *start* and *end* are interpreted as in slice notation.
      Returns ``-1`` on failure.


   .. method:: seek(pos[, whence])

      Set the file's current position.  *whence* argument is optional and
      defaults to ``os.SEEK_SET`` or ``0`` (absolute file positioning); other
      values are ``os.SEEK_CUR`` or ``1`` (seek relative to the current
      position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's end).


   .. method:: size()

      Return the length of the file, which can be larger than the size of the
      memory-mapped area.


   .. method:: tell()

      Returns the current position of the file pointer.


   .. method:: write(string)

      Write the bytes in *string* into memory at the current position of the
      file pointer; the file position is updated to point after the bytes that
      were written. If the mmap was created with :const:`ACCESS_READ`, then
      writing to it will raise a :exc:`TypeError` exception.


   .. method:: write_byte(byte)

      Write the single-character string *byte* into memory at the current
      position of the file pointer; the file position is advanced by ``1``. If
      the mmap was created with :const:`ACCESS_READ`, then writing to it will
      raise a :exc:`TypeError` exception.
PK	%�\^D4
4
*html/_sources/library/modulefinder.rst.txtnu�[���:mod:`modulefinder` --- Find modules used by a script
=====================================================

.. module:: modulefinder
   :synopsis: Find modules used by a script.
.. sectionauthor:: A.M. Kuchling <amk@amk.ca>


.. versionadded:: 2.3

**Source code:** :source:`Lib/modulefinder.py`

--------------

This module provides a :class:`ModuleFinder` class that can be used to determine
the set of modules imported by a script. ``modulefinder.py`` can also be run as
a script, giving the filename of a Python script as its argument, after which a
report of the imported modules will be printed.


.. function:: AddPackagePath(pkg_name, path)

   Record that the package named *pkg_name* can be found in the specified *path*.


.. function:: ReplacePackage(oldname, newname)

   Allows specifying that the module named *oldname* is in fact the package named
   *newname*.  The most common usage would be  to handle how the :mod:`_xmlplus`
   package replaces the :mod:`xml` package.


.. class:: ModuleFinder([path=None, debug=0, excludes=[], replace_paths=[]])

   This class provides :meth:`run_script` and :meth:`report` methods to determine
   the set of modules imported by a script. *path* can be a list of directories to
   search for modules; if not specified, ``sys.path`` is used.  *debug* sets the
   debugging level; higher values make the class print  debugging messages about
   what it's doing. *excludes* is a list of module names to exclude from the
   analysis. *replace_paths* is a list of ``(oldpath, newpath)`` tuples that will
   be replaced in module paths.


   .. method:: report()

      Print a report to standard output that lists the modules imported by the
      script and their paths, as well as modules that are missing or seem to be
      missing.

   .. method:: run_script(pathname)

      Analyze the contents of the *pathname* file, which must contain Python
      code.

   .. attribute:: modules

      A dictionary mapping module names to modules. See
      :ref:`modulefinder-example`.


.. _modulefinder-example:

Example usage of :class:`ModuleFinder`
--------------------------------------

The script that is going to get analyzed later on (bacon.py)::

   import re, itertools

   try:
       import baconhameggs
   except ImportError:
       pass

   try:
       import guido.python.ham
   except ImportError:
       pass


The script that will output the report of bacon.py::

   from modulefinder import ModuleFinder

   finder = ModuleFinder()
   finder.run_script('bacon.py')

   print 'Loaded modules:'
   for name, mod in finder.modules.iteritems():
       print '%s: ' % name,
       print ','.join(mod.globalnames.keys()[:3])

   print '-'*50
   print 'Modules not imported:'
   print '\n'.join(finder.badmodules.iterkeys())

Sample output (may vary depending on the architecture)::

    Loaded modules:
    _types:
    copy_reg:  _inverted_registry,_slotnames,__all__
    sre_compile:  isstring,_sre,_optimize_unicode
    _sre:
    sre_constants:  REPEAT_ONE,makedict,AT_END_LINE
    sys:
    re:  __module__,finditer,_expand
    itertools:
    __main__:  re,itertools,baconhameggs
    sre_parse:  __getslice__,_PATTERNENDERS,SRE_FLAG_UNICODE
    array:
    types:  __module__,IntType,TypeType
    ---------------------------------------------------
    Modules not imported:
    guido.python.ham
    baconhameggs


PK	%�\{�U�~~%html/_sources/library/modules.rst.txtnu�[���
.. _modules:

*****************
Importing Modules
*****************

The modules described in this chapter provide new ways to import other Python
modules and hooks for customizing the import process.

The full list of modules described in this chapter is:


.. toctree::

   imp.rst
   importlib.rst
   imputil.rst
   zipimport.rst
   pkgutil.rst
   modulefinder.rst
   runpy.rst
PK	%�\ZG��vJvJ$html/_sources/library/msilib.rst.txtnu�[���:mod:`msilib` --- Read and write Microsoft Installer files
==========================================================

.. module:: msilib
   :platform: Windows
   :synopsis: Creation of Microsoft Installer files, and CAB files.
.. moduleauthor:: Martin v. Löwis <martin@v.loewis.de>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. index:: single: msi

.. versionadded:: 2.5

The :mod:`msilib` supports the creation of Microsoft Installer (``.msi``) files.
Because these files often contain an embedded "cabinet" file (``.cab``), it also
exposes an API to create CAB files. Support for reading ``.cab`` files is
currently not implemented; read support for the ``.msi`` database is possible.

This package aims to provide complete access to all tables in an ``.msi`` file,
therefore, it is a fairly low-level API. Two primary applications of this
package are the :mod:`distutils` command ``bdist_msi``, and the creation of
Python installer package itself (although that currently uses a different
version of ``msilib``).

The package contents can be roughly split into four parts: low-level CAB
routines, low-level MSI routines, higher-level MSI routines, and standard table
structures.


.. function:: FCICreate(cabname, files)

   Create a new CAB file named *cabname*. *files* must be a list of tuples, each
   containing the name of the file on disk, and the name of the file inside the CAB
   file.

   The files are added to the CAB file in the order they appear in the list. All
   files are added into a single CAB file, using the MSZIP compression algorithm.

   Callbacks to Python for the various steps of MSI creation are currently not
   exposed.


.. function:: UuidCreate()

   Return the string representation of a new unique identifier. This wraps the
   Windows API functions :c:func:`UuidCreate` and :c:func:`UuidToString`.


.. function:: OpenDatabase(path, persist)

   Return a new database object by calling MsiOpenDatabase.   *path* is the file
   name of the MSI file; *persist* can be one of the constants
   ``MSIDBOPEN_CREATEDIRECT``, ``MSIDBOPEN_CREATE``, ``MSIDBOPEN_DIRECT``,
   ``MSIDBOPEN_READONLY``, or ``MSIDBOPEN_TRANSACT``, and may include the flag
   ``MSIDBOPEN_PATCHFILE``. See the Microsoft documentation for the meaning of
   these flags; depending on the flags, an existing database is opened, or a new
   one created.


.. function:: CreateRecord(count)

   Return a new record object by calling :c:func:`MSICreateRecord`. *count* is the
   number of fields of the record.


.. function:: init_database(name, schema, ProductName, ProductCode, ProductVersion, Manufacturer)

   Create and return a new database *name*, initialize it with *schema*, and set
   the properties *ProductName*, *ProductCode*, *ProductVersion*, and
   *Manufacturer*.

   *schema* must be a module object containing ``tables`` and
   ``_Validation_records`` attributes; typically, :mod:`msilib.schema` should be
   used.

   The database will contain just the schema and the validation records when this
   function returns.


.. function:: add_data(database, table, records)

   Add all *records* to the table named *table* in *database*.

   The *table* argument must be one of the predefined tables in the MSI schema,
   e.g. ``'Feature'``, ``'File'``, ``'Component'``, ``'Dialog'``, ``'Control'``,
   etc.

   *records* should be a list of tuples, each one containing all fields of a
   record according to the schema of the table.  For optional fields,
   ``None`` can be passed.

   Field values can be int or long numbers, strings, or instances of the Binary
   class.


.. class:: Binary(filename)

   Represents entries in the Binary table; inserting such an object using
   :func:`add_data` reads the file named *filename* into the table.


.. function:: add_tables(database, module)

   Add all table content from *module* to *database*. *module* must contain an
   attribute *tables* listing all tables for which content should be added, and one
   attribute per table that has the actual content.

   This is typically used to install the sequence tables.


.. function:: add_stream(database, name, path)

   Add the file *path* into the ``_Stream`` table of *database*, with the stream
   name *name*.


.. function:: gen_uuid()

   Return a new UUID, in the format that MSI typically requires (i.e. in curly
   braces, and with all hexdigits in upper-case).


.. seealso::

   `FCICreateFile <https://msdn.microsoft.com/library?url=/library/en-us/devnotes/winprog/fcicreate.asp>`_
   `UuidCreate <https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidcreate.asp>`_
   `UuidToString <https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidtostring.asp>`_

.. _database-objects:

Database Objects
----------------


.. method:: Database.OpenView(sql)

   Return a view object, by calling :c:func:`MSIDatabaseOpenView`. *sql* is the SQL
   statement to execute.


.. method:: Database.Commit()

   Commit the changes pending in the current transaction, by calling
   :c:func:`MSIDatabaseCommit`.


.. method:: Database.GetSummaryInformation(count)

   Return a new summary information object, by calling
   :c:func:`MsiGetSummaryInformation`.  *count* is the maximum number of updated
   values.


.. seealso::

   `MSIDatabaseOpenView <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabaseopenview.asp>`_
   `MSIDatabaseCommit <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabasecommit.asp>`_
   `MSIGetSummaryInformation <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msigetsummaryinformation.asp>`_

.. _view-objects:

View Objects
------------


.. method:: View.Execute(params)

   Execute the SQL query of the view, through :c:func:`MSIViewExecute`. If
   *params* is not ``None``, it is a record describing actual values of the
   parameter tokens in the query.


.. method:: View.GetColumnInfo(kind)

   Return a record describing the columns of the view, through calling
   :c:func:`MsiViewGetColumnInfo`. *kind* can be either ``MSICOLINFO_NAMES`` or
   ``MSICOLINFO_TYPES``.


.. method:: View.Fetch()

   Return a result record of the query, through calling :c:func:`MsiViewFetch`.


.. method:: View.Modify(kind, data)

   Modify the view, by calling :c:func:`MsiViewModify`. *kind* can be one of
   ``MSIMODIFY_SEEK``, ``MSIMODIFY_REFRESH``, ``MSIMODIFY_INSERT``,
   ``MSIMODIFY_UPDATE``, ``MSIMODIFY_ASSIGN``, ``MSIMODIFY_REPLACE``,
   ``MSIMODIFY_MERGE``, ``MSIMODIFY_DELETE``, ``MSIMODIFY_INSERT_TEMPORARY``,
   ``MSIMODIFY_VALIDATE``, ``MSIMODIFY_VALIDATE_NEW``,
   ``MSIMODIFY_VALIDATE_FIELD``, or ``MSIMODIFY_VALIDATE_DELETE``.

   *data* must be a record describing the new data.


.. method:: View.Close()

   Close the view, through :c:func:`MsiViewClose`.


.. seealso::

   `MsiViewExecute <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewexecute.asp>`_
   `MSIViewGetColumnInfo <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewgetcolumninfo.asp>`_
   `MsiViewFetch <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewfetch.asp>`_
   `MsiViewModify <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewmodify.asp>`_
   `MsiViewClose <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewclose.asp>`_

.. _summary-objects:

Summary Information Objects
---------------------------


.. method:: SummaryInformation.GetProperty(field)

   Return a property of the summary, through :c:func:`MsiSummaryInfoGetProperty`.
   *field* is the name of the property, and can be one of the constants
   ``PID_CODEPAGE``, ``PID_TITLE``, ``PID_SUBJECT``, ``PID_AUTHOR``,
   ``PID_KEYWORDS``, ``PID_COMMENTS``, ``PID_TEMPLATE``, ``PID_LASTAUTHOR``,
   ``PID_REVNUMBER``, ``PID_LASTPRINTED``, ``PID_CREATE_DTM``,
   ``PID_LASTSAVE_DTM``, ``PID_PAGECOUNT``, ``PID_WORDCOUNT``, ``PID_CHARCOUNT``,
   ``PID_APPNAME``, or ``PID_SECURITY``.


.. method:: SummaryInformation.GetPropertyCount()

   Return the number of summary properties, through
   :c:func:`MsiSummaryInfoGetPropertyCount`.


.. method:: SummaryInformation.SetProperty(field, value)

   Set a property through :c:func:`MsiSummaryInfoSetProperty`. *field* can have the
   same values as in :meth:`GetProperty`, *value* is the new value of the property.
   Possible value types are integer and string.


.. method:: SummaryInformation.Persist()

   Write the modified properties to the summary information stream, using
   :c:func:`MsiSummaryInfoPersist`.


.. seealso::

   `MsiSummaryInfoGetProperty <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetproperty.asp>`_
   `MsiSummaryInfoGetPropertyCount <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetpropertycount.asp>`_
   `MsiSummaryInfoSetProperty <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfosetproperty.asp>`_
   `MsiSummaryInfoPersist <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfopersist.asp>`_

.. _record-objects:

Record Objects
--------------


.. method:: Record.GetFieldCount()

   Return the number of fields of the record, through
   :c:func:`MsiRecordGetFieldCount`.


.. method:: Record.GetInteger(field)

   Return the value of *field* as an integer where possible.  *field* must
   be an integer.


.. method:: Record.GetString(field)

   Return the value of *field* as a string where possible.  *field* must
   be an integer.


.. method:: Record.SetString(field, value)

   Set *field* to *value* through :c:func:`MsiRecordSetString`. *field* must be an
   integer; *value* a string.


.. method:: Record.SetStream(field, value)

   Set *field* to the contents of the file named *value*, through
   :c:func:`MsiRecordSetStream`. *field* must be an integer; *value* a string.


.. method:: Record.SetInteger(field, value)

   Set *field* to *value* through :c:func:`MsiRecordSetInteger`. Both *field* and
   *value* must be an integer.


.. method:: Record.ClearData()

   Set all fields of the record to 0, through :c:func:`MsiRecordClearData`.


.. seealso::

   `MsiRecordGetFieldCount <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordgetfieldcount.asp>`_
   `MsiRecordSetString <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstring.asp>`_
   `MsiRecordSetStream <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstream.asp>`_
   `MsiRecordSetInteger <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetinteger.asp>`_
   `MsiRecordClear <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordclear.asp>`_

.. _msi-errors:

Errors
------

All wrappers around MSI functions raise :exc:`MSIError`; the string inside the
exception will contain more detail.


.. _cab:

CAB Objects
-----------


.. class:: CAB(name)

   The class :class:`CAB` represents a CAB file. During MSI construction, files
   will be added simultaneously to the ``Files`` table, and to a CAB file. Then,
   when all files have been added, the CAB file can be written, then added to the
   MSI file.

   *name* is the name of the CAB file in the MSI file.


   .. method:: append(full, file, logical)

      Add the file with the pathname *full* to the CAB file, under the name
      *logical*.  If there is already a file named *logical*, a new file name is
      created.

      Return the index of the file in the CAB file, and the new name of the file
      inside the CAB file.


   .. method:: commit(database)

      Generate a CAB file, add it as a stream to the MSI file, put it into the
      ``Media`` table, and remove the generated file from the disk.


.. _msi-directory:

Directory Objects
-----------------


.. class:: Directory(database, cab, basedir, physical,  logical, default, [componentflags])

   Create a new directory in the Directory table. There is a current component at
   each point in time for the directory, which is either explicitly created through
   :meth:`start_component`, or implicitly when files are added for the first time.
   Files are added into the current component, and into the cab file.  To create a
   directory, a base directory object needs to be specified (can be ``None``), the
   path to the physical directory, and a logical directory name.  *default*
   specifies the DefaultDir slot in the directory table. *componentflags* specifies
   the default flags that new components get.


   .. method:: start_component([component[, feature[, flags[, keyfile[, uuid]]]]])

      Add an entry to the Component table, and make this component the current
      component for this directory. If no component name is given, the directory
      name is used. If no *feature* is given, the current feature is used. If no
      *flags* are given, the directory's default flags are used. If no *keyfile*
      is given, the KeyPath is left null in the Component table.


   .. method:: add_file(file[, src[, version[, language]]])

      Add a file to the current component of the directory, starting a new one
      if there is no current component. By default, the file name in the source
      and the file table will be identical. If the *src* file is specified, it
      is interpreted relative to the current directory. Optionally, a *version*
      and a *language* can be specified for the entry in the File table.


   .. method:: glob(pattern[, exclude])

      Add a list of files to the current component as specified in the glob
      pattern.  Individual files can be excluded in the *exclude* list.


   .. method:: remove_pyc()

      Remove ``.pyc``/``.pyo`` files on uninstall.


.. seealso::

   `Directory Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/directory_table.asp>`_
   `File Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/file_table.asp>`_
   `Component Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/component_table.asp>`_
   `FeatureComponents Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/featurecomponents_table.asp>`_

.. _features:

Features
--------


.. class:: Feature(database, id, title, desc, display[, level=1[, parent[, directory[,  attributes=0]]]])

   Add a new record to the ``Feature`` table, using the values *id*, *parent.id*,
   *title*, *desc*, *display*, *level*, *directory*, and *attributes*. The
   resulting feature object can be passed to the :meth:`start_component` method of
   :class:`Directory`.


   .. method:: set_current()

      Make this feature the current feature of :mod:`msilib`. New components are
      automatically added to the default feature, unless a feature is explicitly
      specified.


.. seealso::

   `Feature Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/feature_table.asp>`_

.. _msi-gui:

GUI classes
-----------

:mod:`msilib` provides several classes that wrap the GUI tables in an MSI
database. However, no standard user interface is provided; use
:mod:`~distutils.command.bdist_msi` to create MSI files with a user-interface
for installing Python packages.


.. class:: Control(dlg, name)

   Base class of the dialog controls. *dlg* is the dialog object the control
   belongs to, and *name* is the control's name.


   .. method:: event(event, argument[,  condition=1[, ordering]])

      Make an entry into the ``ControlEvent`` table for this control.


   .. method:: mapping(event, attribute)

      Make an entry into the ``EventMapping`` table for this control.


   .. method:: condition(action, condition)

      Make an entry into the ``ControlCondition`` table for this control.


.. class:: RadioButtonGroup(dlg, name, property)

   Create a radio button control named *name*. *property* is the installer property
   that gets set when a radio button is selected.


   .. method:: add(name, x, y, width, height, text [, value])

      Add a radio button named *name* to the group, at the coordinates *x*, *y*,
      *width*, *height*, and with the label *text*. If *value* is omitted, it
      defaults to *name*.


.. class:: Dialog(db, name, x, y, w, h, attr, title, first,  default, cancel)

   Return a new :class:`Dialog` object. An entry in the ``Dialog`` table is made,
   with the specified coordinates, dialog attributes, title, name of the first,
   default, and cancel controls.


   .. method:: control(name, type, x, y, width, height,  attributes, property, text, control_next, help)

      Return a new :class:`Control` object. An entry in the ``Control`` table is
      made with the specified parameters.

      This is a generic method; for specific types, specialized methods are
      provided.


   .. method:: text(name, x, y, width, height, attributes, text)

      Add and return a ``Text`` control.


   .. method:: bitmap(name, x, y, width, height, text)

      Add and return a ``Bitmap`` control.


   .. method:: line(name, x, y, width, height)

      Add and return a ``Line`` control.


   .. method:: pushbutton(name, x, y, width, height, attributes,  text, next_control)

      Add and return a ``PushButton`` control.


   .. method:: radiogroup(name, x, y, width, height,  attributes, property, text, next_control)

      Add and return a ``RadioButtonGroup`` control.


   .. method:: checkbox(name, x, y, width, height,  attributes, property, text, next_control)

      Add and return a ``CheckBox`` control.


.. seealso::

   `Dialog Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/dialog_table.asp>`_
   `Control Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/control_table.asp>`_
   `Control Types <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controls.asp>`_
   `ControlCondition Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlcondition_table.asp>`_
   `ControlEvent Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlevent_table.asp>`_
   `EventMapping Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/eventmapping_table.asp>`_
   `RadioButton Table <https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/radiobutton_table.asp>`_

.. _msi-tables:

Precomputed tables
------------------

:mod:`msilib` provides a few subpackages that contain only schema and table
definitions. Currently, these definitions are based on MSI version 2.0.


.. data:: schema

   This is the standard MSI schema for MSI 2.0, with the *tables* variable
   providing a list of table definitions, and *_Validation_records* providing the
   data for MSI validation.


.. data:: sequence

   This module contains table contents for the standard sequence tables:
   *AdminExecuteSequence*, *AdminUISequence*, *AdvtExecuteSequence*,
   *InstallExecuteSequence*, and *InstallUISequence*.


.. data:: text

   This module contains definitions for the UIText and ActionText tables, for the
   standard installer actions.
PK	%�\��>���$html/_sources/library/msvcrt.rst.txtnu�[���
:mod:`msvcrt` --- Useful routines from the MS VC++ runtime
==========================================================

.. module:: msvcrt
   :platform: Windows
   :synopsis: Miscellaneous useful routines from the MS VC++ runtime.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


These functions provide access to some useful capabilities on Windows platforms.
Some higher-level modules use these functions to build the  Windows
implementations of their services.  For example, the :mod:`getpass` module uses
this in the implementation of the :func:`getpass` function.

Further documentation on these functions can be found in the Platform API
documentation.

The module implements both the normal and wide char variants of the console I/O
api. The normal API deals only with ASCII characters and is of limited use
for internationalized applications. The wide char API should be used where
ever possible.

.. _msvcrt-files:

File Operations
---------------


.. function:: locking(fd, mode, nbytes)

   Lock part of a file based on file descriptor *fd* from the C runtime.  Raises
   :exc:`IOError` on failure.  The locked region of the file extends from the
   current file position for *nbytes* bytes, and may continue beyond the end of the
   file.  *mode* must be one of the :const:`LK_\*` constants listed below. Multiple
   regions in a file may be locked at the same time, but may not overlap.  Adjacent
   regions are not merged; they must be unlocked individually.


.. data:: LK_LOCK
          LK_RLCK

   Locks the specified bytes. If the bytes cannot be locked, the program
   immediately tries again after 1 second.  If, after 10 attempts, the bytes cannot
   be locked, :exc:`IOError` is raised.


.. data:: LK_NBLCK
          LK_NBRLCK

   Locks the specified bytes. If the bytes cannot be locked, :exc:`IOError` is
   raised.


.. data:: LK_UNLCK

   Unlocks the specified bytes, which must have been previously locked.


.. function:: setmode(fd, flags)

   Set the line-end translation mode for the file descriptor *fd*. To set it to
   text mode, *flags* should be :const:`os.O_TEXT`; for binary, it should be
   :const:`os.O_BINARY`.


.. function:: open_osfhandle(handle, flags)

   Create a C runtime file descriptor from the file handle *handle*.  The *flags*
   parameter should be a bitwise OR of :const:`os.O_APPEND`, :const:`os.O_RDONLY`,
   and :const:`os.O_TEXT`.  The returned file descriptor may be used as a parameter
   to :func:`os.fdopen` to create a file object.


.. function:: get_osfhandle(fd)

   Return the file handle for the file descriptor *fd*.  Raises :exc:`IOError` if
   *fd* is not recognized.


.. _msvcrt-console:

Console I/O
-----------


.. function:: kbhit()

   Return true if a keypress is waiting to be read.


.. function:: getch()

   Read a keypress and return the resulting character.  Nothing is echoed to the
   console.  This call will block if a keypress is not already available, but will
   not wait for :kbd:`Enter` to be pressed. If the pressed key was a special
   function key, this will return ``'\000'`` or ``'\xe0'``; the next call will
   return the keycode.  The :kbd:`Control-C` keypress cannot be read with this
   function.


.. function:: getwch()

   Wide char variant of :func:`getch`, returning a Unicode value.

   .. versionadded:: 2.6


.. function:: getche()

   Similar to :func:`getch`, but the keypress will be echoed if it  represents a
   printable character.


.. function:: getwche()

   Wide char variant of :func:`getche`, returning a Unicode value.

   .. versionadded:: 2.6


.. function:: putch(char)

   Print the character *char* to the console without buffering.


.. function:: putwch(unicode_char)

   Wide char variant of :func:`putch`, accepting a Unicode value.

   .. versionadded:: 2.6


.. function:: ungetch(char)

   Cause the character *char* to be "pushed back" into the console buffer; it will
   be the next character read by :func:`getch` or :func:`getche`.


.. function:: ungetwch(unicode_char)

   Wide char variant of :func:`ungetch`, accepting a Unicode value.

   .. versionadded:: 2.6


.. _msvcrt-other:

Other Functions
---------------


.. function:: heapmin()

   Force the :c:func:`malloc` heap to clean itself up and return unused blocks to
   the operating system.  On failure, this raises :exc:`IOError`.
PK	%�\_n���'html/_sources/library/multifile.rst.txtnu�[���
:mod:`multifile` --- Support for files containing distinct parts
================================================================

.. module:: multifile
   :synopsis: Support for reading files which contain distinct parts, such as some MIME data.
   :deprecated:
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>


.. deprecated:: 2.5
   The :mod:`email` package should be used in preference to the :mod:`multifile`
   module. This module is present only to maintain backward compatibility.

The :class:`MultiFile` object enables you to treat sections of a text file as
file-like input objects, with ``''`` being returned by :meth:`readline` when a
given delimiter pattern is encountered.  The defaults of this class are designed
to make it useful for parsing MIME multipart messages, but by subclassing it and
overriding methods  it can be easily adapted for more general use.


.. class:: MultiFile(fp[, seekable])

   Create a multi-file.  You must instantiate this class with an input object
   argument for the :class:`MultiFile` instance to get lines from, such as a file
   object returned by :func:`open`.

   :class:`MultiFile` only ever looks at the input object's :meth:`readline`,
   :meth:`seek` and :meth:`tell` methods, and the latter two are only needed if you
   want random access to the individual MIME parts. To use :class:`MultiFile` on a
   non-seekable stream object, set the optional *seekable* argument to false; this
   will prevent using the input object's :meth:`seek` and :meth:`tell` methods.

It will be useful to know that in :class:`MultiFile`'s view of the world, text
is composed of three kinds of lines: data, section-dividers, and end-markers.
MultiFile is designed to support parsing of messages that may have multiple
nested message parts, each with its own pattern for section-divider and
end-marker lines.


.. seealso::

   Module :mod:`email`
      Comprehensive email handling package; supersedes the :mod:`multifile` module.


.. _multifile-objects:

MultiFile Objects
-----------------

A :class:`MultiFile` instance has the following methods:


.. method:: MultiFile.readline(str)

   Read a line.  If the line is data (not a section-divider or end-marker or real
   EOF) return it.  If the line matches the most-recently-stacked boundary, return
   ``''`` and set ``self.last`` to 1 or 0 according as the match is or is not an
   end-marker.  If the line matches any other stacked boundary, raise an error.  On
   encountering end-of-file on the underlying stream object, the method raises
   :exc:`Error` unless all boundaries have been popped.


.. method:: MultiFile.readlines(str)

   Return all lines remaining in this part as a list of strings.


.. method:: MultiFile.read()

   Read all lines, up to the next section.  Return them as a single (multiline)
   string.  Note that this doesn't take a size argument!


.. method:: MultiFile.seek(pos[, whence])

   Seek.  Seek indices are relative to the start of the current section. The *pos*
   and *whence* arguments are interpreted as for a file seek.


.. method:: MultiFile.tell()

   Return the file position relative to the start of the current section.


.. method:: MultiFile.next()

   Skip lines to the next section (that is, read lines until a section-divider or
   end-marker has been consumed).  Return true if there is such a section, false if
   an end-marker is seen.  Re-enable the most-recently-pushed boundary.


.. method:: MultiFile.is_data(str)

   Return true if *str* is data and false if it might be a section boundary.  As
   written, it tests for a prefix other than ``'-``\ ``-'`` at start of line (which
   all MIME boundaries have) but it is declared so it can be overridden in derived
   classes.

   Note that this test is used intended as a fast guard for the real boundary
   tests; if it always returns false it will merely slow processing, not cause it
   to fail.


.. method:: MultiFile.push(str)

   Push a boundary string.  When a decorated version of this boundary  is found as
   an input line, it will be interpreted as a section-divider  or end-marker
   (depending on the decoration, see :rfc:`2045`).  All subsequent reads will
   return the empty string to indicate end-of-file, until a call to :meth:`pop`
   removes the boundary a or :meth:`.next` call reenables it.

   It is possible to push more than one boundary.  Encountering the
   most-recently-pushed boundary will return EOF; encountering any other
   boundary will raise an error.


.. method:: MultiFile.pop()

   Pop a section boundary.  This boundary will no longer be interpreted as EOF.


.. method:: MultiFile.section_divider(str)

   Turn a boundary into a section-divider line.  By default, this method
   prepends ``'--'`` (which MIME section boundaries have) but it is declared so
   it can be overridden in derived classes.  This method need not append LF or
   CR-LF, as comparison with the result ignores trailing whitespace.


.. method:: MultiFile.end_marker(str)

   Turn a boundary string into an end-marker line.  By default, this method
   prepends ``'--'`` and appends ``'--'`` (like a MIME-multipart end-of-message
   marker) but it is declared so it can be overridden in derived classes.  This
   method need not append LF or CR-LF, as comparison with the result ignores
   trailing whitespace.

Finally, :class:`MultiFile` instances have two public instance variables:


.. attribute:: MultiFile.level

   Nesting depth of the current part.


.. attribute:: MultiFile.last

   True if the last end-of-file was for an end-of-message marker.


.. _multifile-example:

:class:`MultiFile` Example
--------------------------

.. sectionauthor:: Skip Montanaro <skip@pobox.com>


::

   import mimetools
   import multifile
   import StringIO

   def extract_mime_part_matching(stream, mimetype):
       """Return the first element in a multipart MIME message on stream
       matching mimetype."""

       msg = mimetools.Message(stream)
       msgtype = msg.gettype()
       params = msg.getplist()

       data = StringIO.StringIO()
       if msgtype[:10] == "multipart/":

           file = multifile.MultiFile(stream)
           file.push(msg.getparam("boundary"))
           while file.next():
               submsg = mimetools.Message(file)
               try:
                   data = StringIO.StringIO()
                   mimetools.decode(file, data, submsg.getencoding())
               except ValueError:
                   continue
               if submsg.gettype() == mimetype:
                   break
           file.pop()
       return data.getvalue()

PK	%�\�kk��i�i-html/_sources/library/multiprocessing.rst.txtnu�[���:mod:`multiprocessing` --- Process-based "threading" interface
==============================================================

.. module:: multiprocessing
   :synopsis: Process-based "threading" interface.

.. versionadded:: 2.6


Introduction
----------------------

:mod:`multiprocessing` is a package that supports spawning processes using an
API similar to the :mod:`threading` module.  The :mod:`multiprocessing` package
offers both local and remote concurrency, effectively side-stepping the
:term:`Global Interpreter Lock` by using subprocesses instead of threads.  Due
to this, the :mod:`multiprocessing` module allows the programmer to fully
leverage multiple processors on a given machine.  It runs on both Unix and
Windows.

The :mod:`multiprocessing` module also introduces APIs which do not have
analogs in the :mod:`threading` module.  A prime example of this is the
:class:`Pool` object which offers a convenient means of parallelizing the
execution of a function across multiple input values, distributing the
input data across processes (data parallelism).  The following example
demonstrates the common practice of defining such functions in a module so
that child processes can successfully import that module.  This basic example
of data parallelism using :class:`Pool`, ::

   from multiprocessing import Pool

   def f(x):
       return x*x

   if __name__ == '__main__':
       p = Pool(5)
       print(p.map(f, [1, 2, 3]))

will print to standard output ::

   [1, 4, 9]


The :class:`Process` class
~~~~~~~~~~~~~~~~~~~~~~~~~~

In :mod:`multiprocessing`, processes are spawned by creating a :class:`Process`
object and then calling its :meth:`~Process.start` method.  :class:`Process`
follows the API of :class:`threading.Thread`.  A trivial example of a
multiprocess program is ::

    from multiprocessing import Process

    def f(name):
        print 'hello', name

    if __name__ == '__main__':
        p = Process(target=f, args=('bob',))
        p.start()
        p.join()

To show the individual process IDs involved, here is an expanded example::

    from multiprocessing import Process
    import os

    def info(title):
        print title
        print 'module name:', __name__
        if hasattr(os, 'getppid'):  # only available on Unix
            print 'parent process:', os.getppid()
        print 'process id:', os.getpid()

    def f(name):
        info('function f')
        print 'hello', name

    if __name__ == '__main__':
        info('main line')
        p = Process(target=f, args=('bob',))
        p.start()
        p.join()

For an explanation of why (on Windows) the ``if __name__ == '__main__'`` part is
necessary, see :ref:`multiprocessing-programming`.


Exchanging objects between processes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:mod:`multiprocessing` supports two types of communication channel between
processes:

**Queues**

   The :class:`~multiprocessing.Queue` class is a near clone of :class:`Queue.Queue`.  For
   example::

      from multiprocessing import Process, Queue

      def f(q):
          q.put([42, None, 'hello'])

      if __name__ == '__main__':
          q = Queue()
          p = Process(target=f, args=(q,))
          p.start()
          print q.get()    # prints "[42, None, 'hello']"
          p.join()

   Queues are thread and process safe.

**Pipes**

   The :func:`Pipe` function returns a pair of connection objects connected by a
   pipe which by default is duplex (two-way).  For example::

      from multiprocessing import Process, Pipe

      def f(conn):
          conn.send([42, None, 'hello'])
          conn.close()

      if __name__ == '__main__':
          parent_conn, child_conn = Pipe()
          p = Process(target=f, args=(child_conn,))
          p.start()
          print parent_conn.recv()   # prints "[42, None, 'hello']"
          p.join()

   The two connection objects returned by :func:`Pipe` represent the two ends of
   the pipe.  Each connection object has :meth:`~Connection.send` and
   :meth:`~Connection.recv` methods (among others).  Note that data in a pipe
   may become corrupted if two processes (or threads) try to read from or write
   to the *same* end of the pipe at the same time.  Of course there is no risk
   of corruption from processes using different ends of the pipe at the same
   time.


Synchronization between processes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

:mod:`multiprocessing` contains equivalents of all the synchronization
primitives from :mod:`threading`.  For instance one can use a lock to ensure
that only one process prints to standard output at a time::

   from multiprocessing import Process, Lock

   def f(l, i):
       l.acquire()
       print 'hello world', i
       l.release()

   if __name__ == '__main__':
       lock = Lock()

       for num in range(10):
           Process(target=f, args=(lock, num)).start()

Without using the lock output from the different processes is liable to get all
mixed up.


Sharing state between processes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As mentioned above, when doing concurrent programming it is usually best to
avoid using shared state as far as possible.  This is particularly true when
using multiple processes.

However, if you really do need to use some shared data then
:mod:`multiprocessing` provides a couple of ways of doing so.

**Shared memory**

   Data can be stored in a shared memory map using :class:`Value` or
   :class:`Array`.  For example, the following code ::

      from multiprocessing import Process, Value, Array

      def f(n, a):
          n.value = 3.1415927
          for i in range(len(a)):
              a[i] = -a[i]

      if __name__ == '__main__':
          num = Value('d', 0.0)
          arr = Array('i', range(10))

          p = Process(target=f, args=(num, arr))
          p.start()
          p.join()

          print num.value
          print arr[:]

   will print ::

      3.1415927
      [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

   The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
   typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
   double precision float and ``'i'`` indicates a signed integer.  These shared
   objects will be process and thread-safe.

   For more flexibility in using shared memory one can use the
   :mod:`multiprocessing.sharedctypes` module which supports the creation of
   arbitrary ctypes objects allocated from shared memory.

**Server process**

   A manager object returned by :func:`Manager` controls a server process which
   holds Python objects and allows other processes to manipulate them using
   proxies.

   A manager returned by :func:`Manager` will support types :class:`list`,
   :class:`dict`, :class:`~managers.Namespace`, :class:`Lock`, :class:`RLock`,
   :class:`Semaphore`, :class:`BoundedSemaphore`, :class:`Condition`,
   :class:`Event`, :class:`~multiprocessing.Queue`, :class:`Value` and :class:`Array`.  For
   example, ::

      from multiprocessing import Process, Manager

      def f(d, l):
          d[1] = '1'
          d['2'] = 2
          d[0.25] = None
          l.reverse()

      if __name__ == '__main__':
          manager = Manager()

          d = manager.dict()
          l = manager.list(range(10))

          p = Process(target=f, args=(d, l))
          p.start()
          p.join()

          print d
          print l

   will print ::

       {0.25: None, 1: '1', '2': 2}
       [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

   Server process managers are more flexible than using shared memory objects
   because they can be made to support arbitrary object types.  Also, a single
   manager can be shared by processes on different computers over a network.
   They are, however, slower than using shared memory.


Using a pool of workers
~~~~~~~~~~~~~~~~~~~~~~~

The :class:`~multiprocessing.pool.Pool` class represents a pool of worker
processes.  It has methods which allows tasks to be offloaded to the worker
processes in a few different ways.

For example::

   from multiprocessing import Pool, TimeoutError
   import time
   import os

   def f(x):
       return x*x

   if __name__ == '__main__':
       pool = Pool(processes=4)              # start 4 worker processes

       # print "[0, 1, 4,..., 81]"
       print pool.map(f, range(10))

       # print same numbers in arbitrary order
       for i in pool.imap_unordered(f, range(10)):
           print i

       # evaluate "f(20)" asynchronously
       res = pool.apply_async(f, (20,))      # runs in *only* one process
       print res.get(timeout=1)              # prints "400"

       # evaluate "os.getpid()" asynchronously
       res = pool.apply_async(os.getpid, ()) # runs in *only* one process
       print res.get(timeout=1)              # prints the PID of that process

       # launching multiple evaluations asynchronously *may* use more processes
       multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
       print [res.get(timeout=1) for res in multiple_results]

       # make a single worker sleep for 10 secs
       res = pool.apply_async(time.sleep, (10,))
       try:
           print res.get(timeout=1)
       except TimeoutError:
           print "We lacked patience and got a multiprocessing.TimeoutError"

Note that the methods of a pool should only ever be used by the
process which created it.

.. note::

   Functionality within this package requires that the ``__main__`` module be
   importable by the children. This is covered in :ref:`multiprocessing-programming`
   however it is worth pointing out here. This means that some examples, such
   as the :class:`Pool` examples will not work in the interactive interpreter.
   For example::

      >>> from multiprocessing import Pool
      >>> p = Pool(5)
      >>> def f(x):
      ...     return x*x
      ...
      >>> p.map(f, [1,2,3])
      Process PoolWorker-1:
      Process PoolWorker-2:
      Process PoolWorker-3:
      Traceback (most recent call last):
      Traceback (most recent call last):
      Traceback (most recent call last):
      AttributeError: 'module' object has no attribute 'f'
      AttributeError: 'module' object has no attribute 'f'
      AttributeError: 'module' object has no attribute 'f'

   (If you try this it will actually output three full tracebacks
   interleaved in a semi-random fashion, and then you may have to
   stop the master process somehow.)


Reference
---------

The :mod:`multiprocessing` package mostly replicates the API of the
:mod:`threading` module.


:class:`Process` and exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. class:: Process(group=None, target=None, name=None, args=(), kwargs={})

   Process objects represent activity that is run in a separate process. The
   :class:`Process` class has equivalents of all the methods of
   :class:`threading.Thread`.

   The constructor should always be called with keyword arguments. *group*
   should always be ``None``; it exists solely for compatibility with
   :class:`threading.Thread`.  *target* is the callable object to be invoked by
   the :meth:`run()` method.  It defaults to ``None``, meaning nothing is
   called. *name* is the process name.  By default, a unique name is constructed
   of the form 'Process-N\ :sub:`1`:N\ :sub:`2`:...:N\ :sub:`k`' where N\
   :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
   is determined by the *generation* of the process.  *args* is the argument
   tuple for the target invocation.  *kwargs* is a dictionary of keyword
   arguments for the target invocation.  By default, no arguments are passed to
   *target*.

   If a subclass overrides the constructor, it must make sure it invokes the
   base class constructor (:meth:`Process.__init__`) before doing anything else
   to the process.

   .. method:: run()

      Method representing the process's activity.

      You may override this method in a subclass.  The standard :meth:`run`
      method invokes the callable object passed to the object's constructor as
      the target argument, if any, with sequential and keyword arguments taken
      from the *args* and *kwargs* arguments, respectively.

   .. method:: start()

      Start the process's activity.

      This must be called at most once per process object.  It arranges for the
      object's :meth:`run` method to be invoked in a separate process.

   .. method:: join([timeout])

      Block the calling thread until the process whose :meth:`join` method is
      called terminates or until the optional timeout occurs.

      If *timeout* is ``None`` then there is no timeout.

      A process can be joined many times.

      A process cannot join itself because this would cause a deadlock.  It is
      an error to attempt to join a process before it has been started.

   .. attribute:: name

      The process's name.

      The name is a string used for identification purposes only.  It has no
      semantics.  Multiple processes may be given the same name.  The initial
      name is set by the constructor.

   .. method:: is_alive

      Return whether the process is alive.

      Roughly, a process object is alive from the moment the :meth:`start`
      method returns until the child process terminates.

   .. attribute:: daemon

      The process's daemon flag, a Boolean value.  This must be set before
      :meth:`start` is called.

      The initial value is inherited from the creating process.

      When a process exits, it attempts to terminate all of its daemonic child
      processes.

      Note that a daemonic process is not allowed to create child processes.
      Otherwise a daemonic process would leave its children orphaned if it gets
      terminated when its parent process exits. Additionally, these are **not**
      Unix daemons or services, they are normal processes that will be
      terminated (and not joined) if non-daemonic processes have exited.

   In addition to the  :class:`threading.Thread` API, :class:`Process` objects
   also support the following attributes and methods:

   .. attribute:: pid

      Return the process ID.  Before the process is spawned, this will be
      ``None``.

   .. attribute:: exitcode

      The child's exit code.  This will be ``None`` if the process has not yet
      terminated.  A negative value *-N* indicates that the child was terminated
      by signal *N*.

   .. attribute:: authkey

      The process's authentication key (a byte string).

      When :mod:`multiprocessing` is initialized the main process is assigned a
      random string using :func:`os.urandom`.

      When a :class:`Process` object is created, it will inherit the
      authentication key of its parent process, although this may be changed by
      setting :attr:`authkey` to another byte string.

      See :ref:`multiprocessing-auth-keys`.

   .. method:: terminate()

      Terminate the process.  On Unix this is done using the ``SIGTERM`` signal;
      on Windows :c:func:`TerminateProcess` is used.  Note that exit handlers and
      finally clauses, etc., will not be executed.

      Note that descendant processes of the process will *not* be terminated --
      they will simply become orphaned.

      .. warning::

         If this method is used when the associated process is using a pipe or
         queue then the pipe or queue is liable to become corrupted and may
         become unusable by other process.  Similarly, if the process has
         acquired a lock or semaphore etc. then terminating it is liable to
         cause other processes to deadlock.

   Note that the :meth:`start`, :meth:`join`, :meth:`is_alive`,
   :meth:`terminate` and :attr:`exitcode` methods should only be called by
   the process that created the process object.

   Example usage of some of the methods of :class:`Process`:

   .. doctest::

       >>> import multiprocessing, time, signal
       >>> p = multiprocessing.Process(target=time.sleep, args=(1000,))
       >>> print p, p.is_alive()
       <Process(Process-1, initial)> False
       >>> p.start()
       >>> print p, p.is_alive()
       <Process(Process-1, started)> True
       >>> p.terminate()
       >>> time.sleep(0.1)
       >>> print p, p.is_alive()
       <Process(Process-1, stopped[SIGTERM])> False
       >>> p.exitcode == -signal.SIGTERM
       True


.. exception:: BufferTooShort

   Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
   buffer object is too small for the message read.

   If ``e`` is an instance of :exc:`BufferTooShort` then ``e.args[0]`` will give
   the message as a byte string.


Pipes and Queues
~~~~~~~~~~~~~~~~

When using multiple processes, one generally uses message passing for
communication between processes and avoids having to use any synchronization
primitives like locks.

For passing messages one can use :func:`Pipe` (for a connection between two
processes) or a queue (which allows multiple producers and consumers).

The :class:`~multiprocessing.Queue`, :class:`multiprocessing.queues.SimpleQueue` and :class:`JoinableQueue` types are multi-producer,
multi-consumer FIFO queues modelled on the :class:`Queue.Queue` class in the
standard library.  They differ in that :class:`~multiprocessing.Queue` lacks the
:meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join` methods introduced
into Python 2.5's :class:`Queue.Queue` class.

If you use :class:`JoinableQueue` then you **must** call
:meth:`JoinableQueue.task_done` for each task removed from the queue or else the
semaphore used to count the number of unfinished tasks may eventually overflow,
raising an exception.

Note that one can also create a shared queue by using a manager object -- see
:ref:`multiprocessing-managers`.

.. note::

   :mod:`multiprocessing` uses the usual :exc:`Queue.Empty` and
   :exc:`Queue.Full` exceptions to signal a timeout.  They are not available in
   the :mod:`multiprocessing` namespace so you need to import them from
   :mod:`Queue`.

.. note::

   When an object is put on a queue, the object is pickled and a
   background thread later flushes the pickled data to an underlying
   pipe.  This has some consequences which are a little surprising,
   but should not cause any practical difficulties -- if they really
   bother you then you can instead use a queue created with a
   :ref:`manager <multiprocessing-managers>`.

   (1) After putting an object on an empty queue there may be an
       infinitesimal delay before the queue's :meth:`~Queue.empty`
       method returns :const:`False` and :meth:`~Queue.get_nowait` can
       return without raising :exc:`Queue.Empty`.

   (2) If multiple processes are enqueuing objects, it is possible for
       the objects to be received at the other end out-of-order.
       However, objects enqueued by the same process will always be in
       the expected order with respect to each other.

.. warning::

   If a process is killed using :meth:`Process.terminate` or :func:`os.kill`
   while it is trying to use a :class:`~multiprocessing.Queue`, then the data in the queue is
   likely to become corrupted.  This may cause any other process to get an
   exception when it tries to use the queue later on.

.. warning::

   As mentioned above, if a child process has put items on a queue (and it has
   not used :meth:`JoinableQueue.cancel_join_thread
   <multiprocessing.Queue.cancel_join_thread>`), then that process will
   not terminate until all buffered items have been flushed to the pipe.

   This means that if you try joining that process you may get a deadlock unless
   you are sure that all items which have been put on the queue have been
   consumed.  Similarly, if the child process is non-daemonic then the parent
   process may hang on exit when it tries to join all its non-daemonic children.

   Note that a queue created using a manager does not have this issue.  See
   :ref:`multiprocessing-programming`.

For an example of the usage of queues for interprocess communication see
:ref:`multiprocessing-examples`.


.. function:: Pipe([duplex])

   Returns a pair ``(conn1, conn2)`` of :class:`Connection` objects representing
   the ends of a pipe.

   If *duplex* is ``True`` (the default) then the pipe is bidirectional.  If
   *duplex* is ``False`` then the pipe is unidirectional: ``conn1`` can only be
   used for receiving messages and ``conn2`` can only be used for sending
   messages.


.. class:: Queue([maxsize])

   Returns a process shared queue implemented using a pipe and a few
   locks/semaphores.  When a process first puts an item on the queue a feeder
   thread is started which transfers objects from a buffer into the pipe.

   The usual :exc:`Queue.Empty` and :exc:`Queue.Full` exceptions from the
   standard library's :mod:`Queue` module are raised to signal timeouts.

   :class:`~multiprocessing.Queue` implements all the methods of :class:`Queue.Queue` except for
   :meth:`~Queue.Queue.task_done` and :meth:`~Queue.Queue.join`.

   .. method:: qsize()

      Return the approximate size of the queue.  Because of
      multithreading/multiprocessing semantics, this number is not reliable.

      Note that this may raise :exc:`NotImplementedError` on Unix platforms like
      Mac OS X where ``sem_getvalue()`` is not implemented.

   .. method:: empty()

      Return ``True`` if the queue is empty, ``False`` otherwise.  Because of
      multithreading/multiprocessing semantics, this is not reliable.

   .. method:: full()

      Return ``True`` if the queue is full, ``False`` otherwise.  Because of
      multithreading/multiprocessing semantics, this is not reliable.

   .. method:: put(obj[, block[, timeout]])

      Put obj into the queue.  If the optional argument *block* is ``True``
      (the default) and *timeout* is ``None`` (the default), block if necessary until
      a free slot is available.  If *timeout* is a positive number, it blocks at
      most *timeout* seconds and raises the :exc:`Queue.Full` exception if no
      free slot was available within that time.  Otherwise (*block* is
      ``False``), put an item on the queue if a free slot is immediately
      available, else raise the :exc:`Queue.Full` exception (*timeout* is
      ignored in that case).

   .. method:: put_nowait(obj)

      Equivalent to ``put(obj, False)``.

   .. method:: get([block[, timeout]])

      Remove and return an item from the queue.  If optional args *block* is
      ``True`` (the default) and *timeout* is ``None`` (the default), block if
      necessary until an item is available.  If *timeout* is a positive number,
      it blocks at most *timeout* seconds and raises the :exc:`Queue.Empty`
      exception if no item was available within that time.  Otherwise (block is
      ``False``), return an item if one is immediately available, else raise the
      :exc:`Queue.Empty` exception (*timeout* is ignored in that case).

   .. method:: get_nowait()

      Equivalent to ``get(False)``.

   :class:`~multiprocessing.Queue` has a few additional methods not found in
   :class:`Queue.Queue`.  These methods are usually unnecessary for most
   code:

   .. method:: close()

      Indicate that no more data will be put on this queue by the current
      process.  The background thread will quit once it has flushed all buffered
      data to the pipe.  This is called automatically when the queue is garbage
      collected.

   .. method:: join_thread()

      Join the background thread.  This can only be used after :meth:`close` has
      been called.  It blocks until the background thread exits, ensuring that
      all data in the buffer has been flushed to the pipe.

      By default if a process is not the creator of the queue then on exit it
      will attempt to join the queue's background thread.  The process can call
      :meth:`cancel_join_thread` to make :meth:`join_thread` do nothing.

   .. method:: cancel_join_thread()

      Prevent :meth:`join_thread` from blocking.  In particular, this prevents
      the background thread from being joined automatically when the process
      exits -- see :meth:`join_thread`.

      A better name for this method might be
      ``allow_exit_without_flush()``.  It is likely to cause enqueued
      data to lost, and you almost certainly will not need to use it.
      It is really only there if you need the current process to exit
      immediately without waiting to flush enqueued data to the
      underlying pipe, and you don't care about lost data.

   .. note::

      This class's functionality requires a functioning shared semaphore
      implementation on the host operating system. Without one, the
      functionality in this class will be disabled, and attempts to
      instantiate a :class:`Queue` will result in an :exc:`ImportError`. See
      :issue:`3770` for additional information.  The same holds true for any
      of the specialized queue types listed below.


.. class:: multiprocessing.queues.SimpleQueue()

   It is a simplified :class:`~multiprocessing.Queue` type, very close to a locked :class:`Pipe`.

   .. method:: empty()

      Return ``True`` if the queue is empty, ``False`` otherwise.

   .. method:: get()

      Remove and return an item from the queue.

   .. method:: put(item)

      Put *item* into the queue.


.. class:: JoinableQueue([maxsize])

   :class:`JoinableQueue`, a :class:`~multiprocessing.Queue` subclass, is a queue which
   additionally has :meth:`task_done` and :meth:`join` methods.

   .. method:: task_done()

      Indicate that a formerly enqueued task is complete. Used by queue consumer
      threads.  For each :meth:`~Queue.get` used to fetch a task, a subsequent
      call to :meth:`task_done` tells the queue that the processing on the task
      is complete.

      If a :meth:`~Queue.Queue.join` is currently blocking, it will resume when all
      items have been processed (meaning that a :meth:`task_done` call was
      received for every item that had been :meth:`~Queue.put` into the queue).

      Raises a :exc:`ValueError` if called more times than there were items
      placed in the queue.


   .. method:: join()

      Block until all items in the queue have been gotten and processed.

      The count of unfinished tasks goes up whenever an item is added to the
      queue.  The count goes down whenever a consumer thread calls
      :meth:`task_done` to indicate that the item was retrieved and all work on
      it is complete.  When the count of unfinished tasks drops to zero,
      :meth:`~Queue.Queue.join` unblocks.


Miscellaneous
~~~~~~~~~~~~~

.. function:: active_children()

   Return list of all live children of the current process.

   Calling this has the side effect of "joining" any processes which have
   already finished.

.. function:: cpu_count()

   Return the number of CPUs in the system.  May raise
   :exc:`NotImplementedError`.

.. function:: current_process()

   Return the :class:`Process` object corresponding to the current process.

   An analogue of :func:`threading.current_thread`.

.. function:: freeze_support()

   Add support for when a program which uses :mod:`multiprocessing` has been
   frozen to produce a Windows executable.  (Has been tested with **py2exe**,
   **PyInstaller** and **cx_Freeze**.)

   One needs to call this function straight after the ``if __name__ ==
   '__main__'`` line of the main module.  For example::

      from multiprocessing import Process, freeze_support

      def f():
          print 'hello world!'

      if __name__ == '__main__':
          freeze_support()
          Process(target=f).start()

   If the ``freeze_support()`` line is omitted then trying to run the frozen
   executable will raise :exc:`RuntimeError`.

   Calling ``freeze_support()`` has no effect when invoked on any operating
   system other than Windows.  In addition, if the module is being run
   normally by the Python interpreter on Windows (the program has not been
   frozen), then ``freeze_support()`` has no effect.

.. function:: set_executable()

   Sets the path of the Python interpreter to use when starting a child process.
   (By default :data:`sys.executable` is used).  Embedders will probably need to
   do some thing like ::

      set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

   before they can create child processes.  (Windows only)


.. note::

   :mod:`multiprocessing` contains no analogues of
   :func:`threading.active_count`, :func:`threading.enumerate`,
   :func:`threading.settrace`, :func:`threading.setprofile`,
   :class:`threading.Timer`, or :class:`threading.local`.


Connection Objects
~~~~~~~~~~~~~~~~~~

.. currentmodule:: None

Connection objects allow the sending and receiving of picklable objects or
strings.  They can be thought of as message oriented connected sockets.

Connection objects are usually created using
:func:`Pipe <multiprocessing.Pipe>` -- see also
:ref:`multiprocessing-listeners-clients`.

.. class:: Connection

   .. method:: send(obj)

      Send an object to the other end of the connection which should be read
      using :meth:`recv`.

      The object must be picklable.  Very large pickles (approximately 32 MB+,
      though it depends on the OS) may raise a :exc:`ValueError` exception.

   .. method:: recv()

      Return an object sent from the other end of the connection using
      :meth:`send`.  Blocks until there is something to receive.  Raises
      :exc:`EOFError` if there is nothing left to receive
      and the other end was closed.

   .. method:: fileno()

      Return the file descriptor or handle used by the connection.

   .. method:: close()

      Close the connection.

      This is called automatically when the connection is garbage collected.

   .. method:: poll([timeout])

      Return whether there is any data available to be read.

      If *timeout* is not specified then it will return immediately.  If
      *timeout* is a number then this specifies the maximum time in seconds to
      block.  If *timeout* is ``None`` then an infinite timeout is used.

   .. method:: send_bytes(buffer[, offset[, size]])

      Send byte data from an object supporting the buffer interface as a
      complete message.

      If *offset* is given then data is read from that position in *buffer*.  If
      *size* is given then that many bytes will be read from buffer.  Very large
      buffers (approximately 32 MB+, though it depends on the OS) may raise a
      :exc:`ValueError` exception

   .. method:: recv_bytes([maxlength])

      Return a complete message of byte data sent from the other end of the
      connection as a string.  Blocks until there is something to receive.
      Raises :exc:`EOFError` if there is nothing left
      to receive and the other end has closed.

      If *maxlength* is specified and the message is longer than *maxlength*
      then :exc:`IOError` is raised and the connection will no longer be
      readable.

   .. method:: recv_bytes_into(buffer[, offset])

      Read into *buffer* a complete message of byte data sent from the other end
      of the connection and return the number of bytes in the message.  Blocks
      until there is something to receive.  Raises
      :exc:`EOFError` if there is nothing left to receive and the other end was
      closed.

      *buffer* must be an object satisfying the writable buffer interface.  If
      *offset* is given then the message will be written into the buffer from
      that position.  Offset must be a non-negative integer less than the
      length of *buffer* (in bytes).

      If the buffer is too short then a :exc:`BufferTooShort` exception is
      raised and the complete message is available as ``e.args[0]`` where ``e``
      is the exception instance.


For example:

.. doctest::

    >>> from multiprocessing import Pipe
    >>> a, b = Pipe()
    >>> a.send([1, 'hello', None])
    >>> b.recv()
    [1, 'hello', None]
    >>> b.send_bytes('thank you')
    >>> a.recv_bytes()
    'thank you'
    >>> import array
    >>> arr1 = array.array('i', range(5))
    >>> arr2 = array.array('i', [0] * 10)
    >>> a.send_bytes(arr1)
    >>> count = b.recv_bytes_into(arr2)
    >>> assert count == len(arr1) * arr1.itemsize
    >>> arr2
    array('i', [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])


.. warning::

    The :meth:`Connection.recv` method automatically unpickles the data it
    receives, which can be a security risk unless you can trust the process
    which sent the message.

    Therefore, unless the connection object was produced using :func:`Pipe` you
    should only use the :meth:`~Connection.recv` and :meth:`~Connection.send`
    methods after performing some sort of authentication.  See
    :ref:`multiprocessing-auth-keys`.

.. warning::

    If a process is killed while it is trying to read or write to a pipe then
    the data in the pipe is likely to become corrupted, because it may become
    impossible to be sure where the message boundaries lie.


Synchronization primitives
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. currentmodule:: multiprocessing

Generally synchronization primitives are not as necessary in a multiprocess
program as they are in a multithreaded program.  See the documentation for
:mod:`threading` module.

Note that one can also create synchronization primitives by using a manager
object -- see :ref:`multiprocessing-managers`.

.. class:: BoundedSemaphore([value])

   A bounded semaphore object: a close analog of
   :class:`threading.BoundedSemaphore`.

   A solitary difference from its close analog exists: its ``acquire`` method's
   first argument is named *block* and it supports an optional second argument
   *timeout*, as is consistent with :meth:`Lock.acquire`.

   .. note::
      On Mac OS X, this is indistinguishable from :class:`Semaphore` because
      ``sem_getvalue()`` is not implemented on that platform.

.. class:: Condition([lock])

   A condition variable: a clone of :class:`threading.Condition`.

   If *lock* is specified then it should be a :class:`Lock` or :class:`RLock`
   object from :mod:`multiprocessing`.

.. class:: Event()

   A clone of :class:`threading.Event`.
   This method returns the state of the internal semaphore on exit, so it
   will always return ``True`` except if a timeout is given and the operation
   times out.

   .. versionchanged:: 2.7
      Previously, the method always returned ``None``.


.. class:: Lock()

   A non-recursive lock object: a close analog of :class:`threading.Lock`.
   Once a process or thread has acquired a lock, subsequent attempts to
   acquire it from any process or thread will block until it is released;
   any process or thread may release it.  The concepts and behaviors of
   :class:`threading.Lock` as it applies to threads are replicated here in
   :class:`multiprocessing.Lock` as it applies to either processes or threads,
   except as noted.

   Note that :class:`Lock` is actually a factory function which returns an
   instance of ``multiprocessing.synchronize.Lock`` initialized with a
   default context.

   :class:`Lock` supports the :term:`context manager` protocol and thus may be
   used in :keyword:`with` statements.

   .. method:: acquire(block=True, timeout=None)

      Acquire a lock, blocking or non-blocking.

      With the *block* argument set to ``True`` (the default), the method call
      will block until the lock is in an unlocked state, then set it to locked
      and return ``True``.  Note that the name of this first argument differs
      from that in :meth:`threading.Lock.acquire`.

      With the *block* argument set to ``False``, the method call does not
      block.  If the lock is currently in a locked state, return ``False``;
      otherwise set the lock to a locked state and return ``True``.

      When invoked with a positive, floating-point value for *timeout*, block
      for at most the number of seconds specified by *timeout* as long as
      the lock can not be acquired.  Invocations with a negative value for
      *timeout* are equivalent to a *timeout* of zero.  Invocations with a
      *timeout* value of ``None`` (the default) set the timeout period to
      infinite.  The *timeout* argument has no practical implications if the
      *block* argument is set to ``False`` and is thus ignored.  Returns
      ``True`` if the lock has been acquired or ``False`` if the timeout period
      has elapsed.  Note that the *timeout* argument does not exist in this
      method's analog, :meth:`threading.Lock.acquire`.

   .. method:: release()

      Release a lock.  This can be called from any process or thread, not only
      the process or thread which originally acquired the lock.

      Behavior is the same as in :meth:`threading.Lock.release` except that
      when invoked on an unlocked lock, a :exc:`ValueError` is raised.


.. class:: RLock()

   A recursive lock object: a close analog of :class:`threading.RLock`.  A
   recursive lock must be released by the process or thread that acquired it.
   Once a process or thread has acquired a recursive lock, the same process
   or thread may acquire it again without blocking; that process or thread
   must release it once for each time it has been acquired.

   Note that :class:`RLock` is actually a factory function which returns an
   instance of ``multiprocessing.synchronize.RLock`` initialized with a
   default context.

   :class:`RLock` supports the :term:`context manager` protocol and thus may be
   used in :keyword:`with` statements.


   .. method:: acquire(block=True, timeout=None)

      Acquire a lock, blocking or non-blocking.

      When invoked with the *block* argument set to ``True``, block until the
      lock is in an unlocked state (not owned by any process or thread) unless
      the lock is already owned by the current process or thread.  The current
      process or thread then takes ownership of the lock (if it does not
      already have ownership) and the recursion level inside the lock increments
      by one, resulting in a return value of ``True``.  Note that there are
      several differences in this first argument's behavior compared to the
      implementation of :meth:`threading.RLock.acquire`, starting with the name
      of the argument itself.

      When invoked with the *block* argument set to ``False``, do not block.
      If the lock has already been acquired (and thus is owned) by another
      process or thread, the current process or thread does not take ownership
      and the recursion level within the lock is not changed, resulting in
      a return value of ``False``.  If the lock is in an unlocked state, the
      current process or thread takes ownership and the recursion level is
      incremented, resulting in a return value of ``True``.

      Use and behaviors of the *timeout* argument are the same as in
      :meth:`Lock.acquire`.  Note that the *timeout* argument does
      not exist in this method's analog, :meth:`threading.RLock.acquire`.


   .. method:: release()

      Release a lock, decrementing the recursion level.  If after the
      decrement the recursion level is zero, reset the lock to unlocked (not
      owned by any process or thread) and if any other processes or threads
      are blocked waiting for the lock to become unlocked, allow exactly one
      of them to proceed.  If after the decrement the recursion level is still
      nonzero, the lock remains locked and owned by the calling process or
      thread.

      Only call this method when the calling process or thread owns the lock.
      An :exc:`AssertionError` is raised if this method is called by a process
      or thread other than the owner or if the lock is in an unlocked (unowned)
      state.  Note that the type of exception raised in this situation
      differs from the implemented behavior in :meth:`threading.RLock.release`.


.. class:: Semaphore([value])

   A semaphore object: a close analog of :class:`threading.Semaphore`.

   A solitary difference from its close analog exists: its ``acquire`` method's
   first argument is named *block* and it supports an optional second argument
   *timeout*, as is consistent with :meth:`Lock.acquire`.

.. note::

   The :meth:`acquire` method of :class:`BoundedSemaphore`, :class:`Lock`,
   :class:`RLock` and :class:`Semaphore` has a timeout parameter not supported
   by the equivalents in :mod:`threading`.  The signature is
   ``acquire(block=True, timeout=None)`` with keyword parameters being
   acceptable.  If *block* is ``True`` and *timeout* is not ``None`` then it
   specifies a timeout in seconds.  If *block* is ``False`` then *timeout* is
   ignored.

   On Mac OS X, ``sem_timedwait`` is unsupported, so calling ``acquire()`` with
   a timeout will emulate that function's behavior using a sleeping loop.

.. note::

   If the SIGINT signal generated by :kbd:`Ctrl-C` arrives while the main thread is
   blocked by a call to :meth:`BoundedSemaphore.acquire`, :meth:`Lock.acquire`,
   :meth:`RLock.acquire`, :meth:`Semaphore.acquire`, :meth:`Condition.acquire`
   or :meth:`Condition.wait` then the call will be immediately interrupted and
   :exc:`KeyboardInterrupt` will be raised.

   This differs from the behaviour of :mod:`threading` where SIGINT will be
   ignored while the equivalent blocking calls are in progress.

.. note::

   Some of this package's functionality requires a functioning shared semaphore
   implementation on the host operating system. Without one, the
   :mod:`multiprocessing.synchronize` module will be disabled, and attempts to
   import it will result in an :exc:`ImportError`. See
   :issue:`3770` for additional information.


Shared :mod:`ctypes` Objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

It is possible to create shared objects using shared memory which can be
inherited by child processes.

.. function:: Value(typecode_or_type, *args[, lock])

   Return a :mod:`ctypes` object allocated from shared memory.  By default the
   return value is actually a synchronized wrapper for the object.

   *typecode_or_type* determines the type of the returned object: it is either a
   ctypes type or a one character typecode of the kind used by the :mod:`array`
   module.  *\*args* is passed on to the constructor for the type.

   If *lock* is ``True`` (the default) then a new recursive lock
   object is created to synchronize access to the value.  If *lock* is
   a :class:`Lock` or :class:`RLock` object then that will be used to
   synchronize access to the value.  If *lock* is ``False`` then
   access to the returned object will not be automatically protected
   by a lock, so it will not necessarily be "process-safe".

   Operations like ``+=`` which involve a read and write are not
   atomic.  So if, for instance, you want to atomically increment a
   shared value it is insufficient to just do ::

       counter.value += 1

   Assuming the associated lock is recursive (which it is by default)
   you can instead do ::

       with counter.get_lock():
           counter.value += 1

   Note that *lock* is a keyword-only argument.

.. function:: Array(typecode_or_type, size_or_initializer, *, lock=True)

   Return a ctypes array allocated from shared memory.  By default the return
   value is actually a synchronized wrapper for the array.

   *typecode_or_type* determines the type of the elements of the returned array:
   it is either a ctypes type or a one character typecode of the kind used by
   the :mod:`array` module.  If *size_or_initializer* is an integer, then it
   determines the length of the array, and the array will be initially zeroed.
   Otherwise, *size_or_initializer* is a sequence which is used to initialize
   the array and whose length determines the length of the array.

   If *lock* is ``True`` (the default) then a new lock object is created to
   synchronize access to the value.  If *lock* is a :class:`Lock` or
   :class:`RLock` object then that will be used to synchronize access to the
   value.  If *lock* is ``False`` then access to the returned object will not be
   automatically protected by a lock, so it will not necessarily be
   "process-safe".

   Note that *lock* is a keyword only argument.

   Note that an array of :data:`ctypes.c_char` has *value* and *raw*
   attributes which allow one to use it to store and retrieve strings.


The :mod:`multiprocessing.sharedctypes` module
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

.. module:: multiprocessing.sharedctypes
   :synopsis: Allocate ctypes objects from shared memory.

The :mod:`multiprocessing.sharedctypes` module provides functions for allocating
:mod:`ctypes` objects from shared memory which can be inherited by child
processes.

.. note::

   Although it is possible to store a pointer in shared memory remember that
   this will refer to a location in the address space of a specific process.
   However, the pointer is quite likely to be invalid in the context of a second
   process and trying to dereference the pointer from the second process may
   cause a crash.

.. function:: RawArray(typecode_or_type, size_or_initializer)

   Return a ctypes array allocated from shared memory.

   *typecode_or_type* determines the type of the elements of the returned array:
   it is either a ctypes type or a one character typecode of the kind used by
   the :mod:`array` module.  If *size_or_initializer* is an integer then it
   determines the length of the array, and the array will be initially zeroed.
   Otherwise *size_or_initializer* is a sequence which is used to initialize the
   array and whose length determines the length of the array.

   Note that setting and getting an element is potentially non-atomic -- use
   :func:`Array` instead to make sure that access is automatically synchronized
   using a lock.

.. function:: RawValue(typecode_or_type, *args)

   Return a ctypes object allocated from shared memory.

   *typecode_or_type* determines the type of the returned object: it is either a
   ctypes type or a one character typecode of the kind used by the :mod:`array`
   module.  *\*args* is passed on to the constructor for the type.

   Note that setting and getting the value is potentially non-atomic -- use
   :func:`Value` instead to make sure that access is automatically synchronized
   using a lock.

   Note that an array of :data:`ctypes.c_char` has ``value`` and ``raw``
   attributes which allow one to use it to store and retrieve strings -- see
   documentation for :mod:`ctypes`.

.. function:: Array(typecode_or_type, size_or_initializer, *args[, lock])

   The same as :func:`RawArray` except that depending on the value of *lock* a
   process-safe synchronization wrapper may be returned instead of a raw ctypes
   array.

   If *lock* is ``True`` (the default) then a new lock object is created to
   synchronize access to the value.  If *lock* is a
   :class:`~multiprocessing.Lock` or :class:`~multiprocessing.RLock` object
   then that will be used to synchronize access to the
   value.  If *lock* is ``False`` then access to the returned object will not be
   automatically protected by a lock, so it will not necessarily be
   "process-safe".

   Note that *lock* is a keyword-only argument.

.. function:: Value(typecode_or_type, *args[, lock])

   The same as :func:`RawValue` except that depending on the value of *lock* a
   process-safe synchronization wrapper may be returned instead of a raw ctypes
   object.

   If *lock* is ``True`` (the default) then a new lock object is created to
   synchronize access to the value.  If *lock* is a :class:`~multiprocessing.Lock` or
   :class:`~multiprocessing.RLock` object then that will be used to synchronize access to the
   value.  If *lock* is ``False`` then access to the returned object will not be
   automatically protected by a lock, so it will not necessarily be
   "process-safe".

   Note that *lock* is a keyword-only argument.

.. function:: copy(obj)

   Return a ctypes object allocated from shared memory which is a copy of the
   ctypes object *obj*.

.. function:: synchronized(obj[, lock])

   Return a process-safe wrapper object for a ctypes object which uses *lock* to
   synchronize access.  If *lock* is ``None`` (the default) then a
   :class:`multiprocessing.RLock` object is created automatically.

   A synchronized wrapper will have two methods in addition to those of the
   object it wraps: :meth:`get_obj` returns the wrapped object and
   :meth:`get_lock` returns the lock object used for synchronization.

   Note that accessing the ctypes object through the wrapper can be a lot slower
   than accessing the raw ctypes object.


The table below compares the syntax for creating shared ctypes objects from
shared memory with the normal ctypes syntax.  (In the table ``MyStruct`` is some
subclass of :class:`ctypes.Structure`.)

==================== ========================== ===========================
ctypes               sharedctypes using type    sharedctypes using typecode
==================== ========================== ===========================
c_double(2.4)        RawValue(c_double, 2.4)    RawValue('d', 2.4)
MyStruct(4, 6)       RawValue(MyStruct, 4, 6)
(c_short * 7)()      RawArray(c_short, 7)       RawArray('h', 7)
(c_int * 3)(9, 2, 8) RawArray(c_int, (9, 2, 8)) RawArray('i', (9, 2, 8))
==================== ========================== ===========================


Below is an example where a number of ctypes objects are modified by a child
process::

   from multiprocessing import Process, Lock
   from multiprocessing.sharedctypes import Value, Array
   from ctypes import Structure, c_double

   class Point(Structure):
       _fields_ = [('x', c_double), ('y', c_double)]

   def modify(n, x, s, A):
       n.value **= 2
       x.value **= 2
       s.value = s.value.upper()
       for a in A:
           a.x **= 2
           a.y **= 2

   if __name__ == '__main__':
       lock = Lock()

       n = Value('i', 7)
       x = Value(c_double, 1.0/3.0, lock=False)
       s = Array('c', 'hello world', lock=lock)
       A = Array(Point, [(1.875,-6.25), (-5.75,2.0), (2.375,9.5)], lock=lock)

       p = Process(target=modify, args=(n, x, s, A))
       p.start()
       p.join()

       print n.value
       print x.value
       print s.value
       print [(a.x, a.y) for a in A]


.. highlightlang:: none

The results printed are ::

    49
    0.1111111111111111
    HELLO WORLD
    [(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]

.. highlightlang:: python


.. _multiprocessing-managers:

Managers
~~~~~~~~

Managers provide a way to create data which can be shared between different
processes. A manager object controls a server process which manages *shared
objects*.  Other processes can access the shared objects by using proxies.

.. function:: multiprocessing.Manager()

   Returns a started :class:`~multiprocessing.managers.SyncManager` object which
   can be used for sharing objects between processes.  The returned manager
   object corresponds to a spawned child process and has methods which will
   create shared objects and return corresponding proxies.

.. module:: multiprocessing.managers
   :synopsis: Share data between process with shared objects.

Manager processes will be shutdown as soon as they are garbage collected or
their parent process exits.  The manager classes are defined in the
:mod:`multiprocessing.managers` module:

.. class:: BaseManager([address[, authkey]])

   Create a BaseManager object.

   Once created one should call :meth:`start` or ``get_server().serve_forever()`` to ensure
   that the manager object refers to a started manager process.

   *address* is the address on which the manager process listens for new
   connections.  If *address* is ``None`` then an arbitrary one is chosen.

   *authkey* is the authentication key which will be used to check the validity
   of incoming connections to the server process.  If *authkey* is ``None`` then
   ``current_process().authkey``.  Otherwise *authkey* is used and it
   must be a string.

   .. method:: start([initializer[, initargs]])

      Start a subprocess to start the manager.  If *initializer* is not ``None``
      then the subprocess will call ``initializer(*initargs)`` when it starts.

   .. method:: get_server()

      Returns a :class:`Server` object which represents the actual server under
      the control of the Manager. The :class:`Server` object supports the
      :meth:`serve_forever` method::

      >>> from multiprocessing.managers import BaseManager
      >>> manager = BaseManager(address=('', 50000), authkey='abc')
      >>> server = manager.get_server()
      >>> server.serve_forever()

      :class:`Server` additionally has an :attr:`address` attribute.

   .. method:: connect()

      Connect a local manager object to a remote manager process::

      >>> from multiprocessing.managers import BaseManager
      >>> m = BaseManager(address=('127.0.0.1', 5000), authkey='abc')
      >>> m.connect()

   .. method:: shutdown()

      Stop the process used by the manager.  This is only available if
      :meth:`start` has been used to start the server process.

      This can be called multiple times.

   .. method:: register(typeid[, callable[, proxytype[, exposed[, method_to_typeid[, create_method]]]]])

      A classmethod which can be used for registering a type or callable with
      the manager class.

      *typeid* is a "type identifier" which is used to identify a particular
      type of shared object.  This must be a string.

      *callable* is a callable used for creating objects for this type
      identifier.  If a manager instance will be created using the
      :meth:`from_address` classmethod or if the *create_method* argument is
      ``False`` then this can be left as ``None``.

      *proxytype* is a subclass of :class:`BaseProxy` which is used to create
      proxies for shared objects with this *typeid*.  If ``None`` then a proxy
      class is created automatically.

      *exposed* is used to specify a sequence of method names which proxies for
      this typeid should be allowed to access using
      :meth:`BaseProxy._callmethod`.  (If *exposed* is ``None`` then
      :attr:`proxytype._exposed_` is used instead if it exists.)  In the case
      where no exposed list is specified, all "public methods" of the shared
      object will be accessible.  (Here a "public method" means any attribute
      which has a :meth:`~object.__call__` method and whose name does not begin
      with ``'_'``.)

      *method_to_typeid* is a mapping used to specify the return type of those
      exposed methods which should return a proxy.  It maps method names to
      typeid strings.  (If *method_to_typeid* is ``None`` then
      :attr:`proxytype._method_to_typeid_` is used instead if it exists.)  If a
      method's name is not a key of this mapping or if the mapping is ``None``
      then the object returned by the method will be copied by value.

      *create_method* determines whether a method should be created with name
      *typeid* which can be used to tell the server process to create a new
      shared object and return a proxy for it.  By default it is ``True``.

   :class:`BaseManager` instances also have one read-only property:

   .. attribute:: address

      The address used by the manager.


.. class:: SyncManager

   A subclass of :class:`BaseManager` which can be used for the synchronization
   of processes.  Objects of this type are returned by
   :func:`multiprocessing.Manager`.

   It also supports creation of shared lists and dictionaries.

   .. method:: BoundedSemaphore([value])

      Create a shared :class:`threading.BoundedSemaphore` object and return a
      proxy for it.

   .. method:: Condition([lock])

      Create a shared :class:`threading.Condition` object and return a proxy for
      it.

      If *lock* is supplied then it should be a proxy for a
      :class:`threading.Lock` or :class:`threading.RLock` object.

   .. method:: Event()

      Create a shared :class:`threading.Event` object and return a proxy for it.

   .. method:: Lock()

      Create a shared :class:`threading.Lock` object and return a proxy for it.

   .. method:: Namespace()

      Create a shared :class:`Namespace` object and return a proxy for it.

   .. method:: Queue([maxsize])

      Create a shared :class:`Queue.Queue` object and return a proxy for it.

   .. method:: RLock()

      Create a shared :class:`threading.RLock` object and return a proxy for it.

   .. method:: Semaphore([value])

      Create a shared :class:`threading.Semaphore` object and return a proxy for
      it.

   .. method:: Array(typecode, sequence)

      Create an array and return a proxy for it.

   .. method:: Value(typecode, value)

      Create an object with a writable ``value`` attribute and return a proxy
      for it.

   .. method:: dict()
               dict(mapping)
               dict(sequence)

      Create a shared ``dict`` object and return a proxy for it.

   .. method:: list()
               list(sequence)

      Create a shared ``list`` object and return a proxy for it.

   .. note::

      Modifications to mutable values or items in dict and list proxies will not
      be propagated through the manager, because the proxy has no way of knowing
      when its values or items are modified.  To modify such an item, you can
      re-assign the modified object to the container proxy::

         # create a list proxy and append a mutable object (a dictionary)
         lproxy = manager.list()
         lproxy.append({})
         # now mutate the dictionary
         d = lproxy[0]
         d['a'] = 1
         d['b'] = 2
         # at this point, the changes to d are not yet synced, but by
         # reassigning the dictionary, the proxy is notified of the change
         lproxy[0] = d


.. class:: Namespace

    A type that can register with :class:`SyncManager`.

    A namespace object has no public methods, but does have writable attributes.
    Its representation shows the values of its attributes.

    However, when using a proxy for a namespace object, an attribute beginning with
    ``'_'`` will be an attribute of the proxy and not an attribute of the referent:

    .. doctest::

       >>> manager = multiprocessing.Manager()
       >>> Global = manager.Namespace()
       >>> Global.x = 10
       >>> Global.y = 'hello'
       >>> Global._z = 12.3    # this is an attribute of the proxy
       >>> print Global
       Namespace(x=10, y='hello')


Customized managers
>>>>>>>>>>>>>>>>>>>

To create one's own manager, one creates a subclass of :class:`BaseManager` and
uses the :meth:`~BaseManager.register` classmethod to register new types or
callables with the manager class.  For example::

   from multiprocessing.managers import BaseManager

   class MathsClass(object):
       def add(self, x, y):
           return x + y
       def mul(self, x, y):
           return x * y

   class MyManager(BaseManager):
       pass

   MyManager.register('Maths', MathsClass)

   if __name__ == '__main__':
       manager = MyManager()
       manager.start()
       maths = manager.Maths()
       print maths.add(4, 3)         # prints 7
       print maths.mul(7, 8)         # prints 56


Using a remote manager
>>>>>>>>>>>>>>>>>>>>>>

It is possible to run a manager server on one machine and have clients use it
from other machines (assuming that the firewalls involved allow it).

Running the following commands creates a server for a single shared queue which
remote clients can access::

   >>> from multiprocessing.managers import BaseManager
   >>> import Queue
   >>> queue = Queue.Queue()
   >>> class QueueManager(BaseManager): pass
   >>> QueueManager.register('get_queue', callable=lambda:queue)
   >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
   >>> s = m.get_server()
   >>> s.serve_forever()

One client can access the server as follows::

   >>> from multiprocessing.managers import BaseManager
   >>> class QueueManager(BaseManager): pass
   >>> QueueManager.register('get_queue')
   >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
   >>> m.connect()
   >>> queue = m.get_queue()
   >>> queue.put('hello')

Another client can also use it::

   >>> from multiprocessing.managers import BaseManager
   >>> class QueueManager(BaseManager): pass
   >>> QueueManager.register('get_queue')
   >>> m = QueueManager(address=('foo.bar.org', 50000), authkey='abracadabra')
   >>> m.connect()
   >>> queue = m.get_queue()
   >>> queue.get()
   'hello'

Local processes can also access that queue, using the code from above on the
client to access it remotely::

    >>> from multiprocessing import Process, Queue
    >>> from multiprocessing.managers import BaseManager
    >>> class Worker(Process):
    ...     def __init__(self, q):
    ...         self.q = q
    ...         super(Worker, self).__init__()
    ...     def run(self):
    ...         self.q.put('local hello')
    ...
    >>> queue = Queue()
    >>> w = Worker(queue)
    >>> w.start()
    >>> class QueueManager(BaseManager): pass
    ...
    >>> QueueManager.register('get_queue', callable=lambda: queue)
    >>> m = QueueManager(address=('', 50000), authkey='abracadabra')
    >>> s = m.get_server()
    >>> s.serve_forever()

Proxy Objects
~~~~~~~~~~~~~

A proxy is an object which *refers* to a shared object which lives (presumably)
in a different process.  The shared object is said to be the *referent* of the
proxy.  Multiple proxy objects may have the same referent.

A proxy object has methods which invoke corresponding methods of its referent
(although not every method of the referent will necessarily be available through
the proxy).  A proxy can usually be used in most of the same ways that its
referent can:

.. doctest::

   >>> from multiprocessing import Manager
   >>> manager = Manager()
   >>> l = manager.list([i*i for i in range(10)])
   >>> print l
   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
   >>> print repr(l)
   <ListProxy object, typeid 'list' at 0x...>
   >>> l[4]
   16
   >>> l[2:5]
   [4, 9, 16]

Notice that applying :func:`str` to a proxy will return the representation of
the referent, whereas applying :func:`repr` will return the representation of
the proxy.

An important feature of proxy objects is that they are picklable so they can be
passed between processes.  Note, however, that if a proxy is sent to the
corresponding manager's process then unpickling it will produce the referent
itself.  This means, for example, that one shared object can contain a second:

.. doctest::

   >>> a = manager.list()
   >>> b = manager.list()
   >>> a.append(b)         # referent of a now contains referent of b
   >>> print a, b
   [[]] []
   >>> b.append('hello')
   >>> print a, b
   [['hello']] ['hello']

.. note::

   The proxy types in :mod:`multiprocessing` do nothing to support comparisons
   by value.  So, for instance, we have:

   .. doctest::

       >>> manager.list([1,2,3]) == [1,2,3]
       False

   One should just use a copy of the referent instead when making comparisons.

.. class:: BaseProxy

   Proxy objects are instances of subclasses of :class:`BaseProxy`.

   .. method:: _callmethod(methodname[, args[, kwds]])

      Call and return the result of a method of the proxy's referent.

      If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::

         proxy._callmethod(methodname, args, kwds)

      will evaluate the expression ::

         getattr(obj, methodname)(*args, **kwds)

      in the manager's process.

      The returned value will be a copy of the result of the call or a proxy to
      a new shared object -- see documentation for the *method_to_typeid*
      argument of :meth:`BaseManager.register`.

      If an exception is raised by the call, then is re-raised by
      :meth:`_callmethod`.  If some other exception is raised in the manager's
      process then this is converted into a :exc:`RemoteError` exception and is
      raised by :meth:`_callmethod`.

      Note in particular that an exception will be raised if *methodname* has
      not been *exposed*.

      An example of the usage of :meth:`_callmethod`:

      .. doctest::

         >>> l = manager.list(range(10))
         >>> l._callmethod('__len__')
         10
         >>> l._callmethod('__getslice__', (2, 7))   # equiv to `l[2:7]`
         [2, 3, 4, 5, 6]
         >>> l._callmethod('__getitem__', (20,))     # equiv to `l[20]`
         Traceback (most recent call last):
         ...
         IndexError: list index out of range

   .. method:: _getvalue()

      Return a copy of the referent.

      If the referent is unpicklable then this will raise an exception.

   .. method:: __repr__

      Return a representation of the proxy object.

   .. method:: __str__

      Return the representation of the referent.


Cleanup
>>>>>>>

A proxy object uses a weakref callback so that when it gets garbage collected it
deregisters itself from the manager which owns its referent.

A shared object gets deleted from the manager process when there are no longer
any proxies referring to it.


Process Pools
~~~~~~~~~~~~~

.. module:: multiprocessing.pool
   :synopsis: Create pools of processes.

One can create a pool of processes which will carry out tasks submitted to it
with the :class:`Pool` class.

.. class:: multiprocessing.Pool([processes[, initializer[, initargs[, maxtasksperchild]]]])

   A process pool object which controls a pool of worker processes to which jobs
   can be submitted.  It supports asynchronous results with timeouts and
   callbacks and has a parallel map implementation.

   *processes* is the number of worker processes to use.  If *processes* is
   ``None`` then the number returned by :func:`cpu_count` is used.  If
   *initializer* is not ``None`` then each worker process will call
   ``initializer(*initargs)`` when it starts.

   Note that the methods of the pool object should only be called by
   the process which created the pool.

   .. versionadded:: 2.7
      *maxtasksperchild* is the number of tasks a worker process can complete
      before it will exit and be replaced with a fresh worker process, to enable
      unused resources to be freed. The default *maxtasksperchild* is ``None``, which
      means worker processes will live as long as the pool.

   .. note::

      Worker processes within a :class:`Pool` typically live for the complete
      duration of the Pool's work queue. A frequent pattern found in other
      systems (such as Apache, mod_wsgi, etc) to free resources held by
      workers is to allow a worker within a pool to complete only a set
      amount of work before being exiting, being cleaned up and a new
      process spawned to replace the old one. The *maxtasksperchild*
      argument to the :class:`Pool` exposes this ability to the end user.

   .. method:: apply(func[, args[, kwds]])

      Equivalent of the :func:`apply` built-in function.  It blocks until the
      result is ready, so :meth:`apply_async` is better suited for performing
      work in parallel. Additionally, *func* is only executed in one of the
      workers of the pool.

   .. method:: apply_async(func[, args[, kwds[, callback]]])

      A variant of the :meth:`apply` method which returns a result object.

      If *callback* is specified then it should be a callable which accepts a
      single argument.  When the result becomes ready *callback* is applied to
      it (unless the call failed).  *callback* should complete immediately since
      otherwise the thread which handles the results will get blocked.

   .. method:: map(func, iterable[, chunksize])

      A parallel equivalent of the :func:`map` built-in function (it supports only
      one *iterable* argument though).  It blocks until the result is ready.

      This method chops the iterable into a number of chunks which it submits to
      the process pool as separate tasks.  The (approximate) size of these
      chunks can be specified by setting *chunksize* to a positive integer.

   .. method:: map_async(func, iterable[, chunksize[, callback]])

      A variant of the :meth:`.map` method which returns a result object.

      If *callback* is specified then it should be a callable which accepts a
      single argument.  When the result becomes ready *callback* is applied to
      it (unless the call failed).  *callback* should complete immediately since
      otherwise the thread which handles the results will get blocked.

   .. method:: imap(func, iterable[, chunksize])

      An equivalent of :func:`itertools.imap`.

      The *chunksize* argument is the same as the one used by the :meth:`.map`
      method.  For very long iterables using a large value for *chunksize* can
      make the job complete **much** faster than using the default value of
      ``1``.

      Also if *chunksize* is ``1`` then the :meth:`!next` method of the iterator
      returned by the :meth:`imap` method has an optional *timeout* parameter:
      ``next(timeout)`` will raise :exc:`multiprocessing.TimeoutError` if the
      result cannot be returned within *timeout* seconds.

   .. method:: imap_unordered(func, iterable[, chunksize])

      The same as :meth:`imap` except that the ordering of the results from the
      returned iterator should be considered arbitrary.  (Only when there is
      only one worker process is the order guaranteed to be "correct".)

   .. method:: close()

      Prevents any more tasks from being submitted to the pool.  Once all the
      tasks have been completed the worker processes will exit.

   .. method:: terminate()

      Stops the worker processes immediately without completing outstanding
      work.  When the pool object is garbage collected :meth:`terminate` will be
      called immediately.

   .. method:: join()

      Wait for the worker processes to exit.  One must call :meth:`close` or
      :meth:`terminate` before using :meth:`join`.


.. class:: AsyncResult

   The class of the result returned by :meth:`Pool.apply_async` and
   :meth:`Pool.map_async`.

   .. method:: get([timeout])

      Return the result when it arrives.  If *timeout* is not ``None`` and the
      result does not arrive within *timeout* seconds then
      :exc:`multiprocessing.TimeoutError` is raised.  If the remote call raised
      an exception then that exception will be reraised by :meth:`get`.

   .. method:: wait([timeout])

      Wait until the result is available or until *timeout* seconds pass.

   .. method:: ready()

      Return whether the call has completed.

   .. method:: successful()

      Return whether the call completed without raising an exception.  Will
      raise :exc:`AssertionError` if the result is not ready.

The following example demonstrates the use of a pool::

   from multiprocessing import Pool
   import time

   def f(x):
       return x*x

   if __name__ == '__main__':
       pool = Pool(processes=4)              # start 4 worker processes

       result = pool.apply_async(f, (10,))   # evaluate "f(10)" asynchronously in a single process
       print result.get(timeout=1)           # prints "100" unless your computer is *very* slow

       print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

       it = pool.imap(f, range(10))
       print it.next()                       # prints "0"
       print it.next()                       # prints "1"
       print it.next(timeout=1)              # prints "4" unless your computer is *very* slow

       result = pool.apply_async(time.sleep, (10,))
       print result.get(timeout=1)           # raises multiprocessing.TimeoutError


.. _multiprocessing-listeners-clients:

Listeners and Clients
~~~~~~~~~~~~~~~~~~~~~

.. module:: multiprocessing.connection
   :synopsis: API for dealing with sockets.

Usually message passing between processes is done using queues or by using
:class:`Connection` objects returned by :func:`~multiprocessing.Pipe`.

However, the :mod:`multiprocessing.connection` module allows some extra
flexibility.  It basically gives a high level message oriented API for dealing
with sockets or Windows named pipes, and also has support for *digest
authentication* using the :mod:`hmac` module.


.. function:: deliver_challenge(connection, authkey)

   Send a randomly generated message to the other end of the connection and wait
   for a reply.

   If the reply matches the digest of the message using *authkey* as the key
   then a welcome message is sent to the other end of the connection.  Otherwise
   :exc:`AuthenticationError` is raised.

.. function:: answer_challenge(connection, authkey)

   Receive a message, calculate the digest of the message using *authkey* as the
   key, and then send the digest back.

   If a welcome message is not received, then :exc:`AuthenticationError` is
   raised.

.. function:: Client(address[, family[, authenticate[, authkey]]])

   Attempt to set up a connection to the listener which is using address
   *address*, returning a :class:`Connection`.

   The type of the connection is determined by *family* argument, but this can
   generally be omitted since it can usually be inferred from the format of
   *address*. (See :ref:`multiprocessing-address-formats`)

   If *authenticate* is ``True`` or *authkey* is a string then digest
   authentication is used.  The key used for authentication will be either
   *authkey* or ``current_process().authkey)`` if *authkey* is ``None``.
   If authentication fails then :exc:`AuthenticationError` is raised.  See
   :ref:`multiprocessing-auth-keys`.

.. class:: Listener([address[, family[, backlog[, authenticate[, authkey]]]]])

   A wrapper for a bound socket or Windows named pipe which is 'listening' for
   connections.

   *address* is the address to be used by the bound socket or named pipe of the
   listener object.

   .. note::

      If an address of '0.0.0.0' is used, the address will not be a connectable
      end point on Windows. If you require a connectable end-point,
      you should use '127.0.0.1'.

   *family* is the type of socket (or named pipe) to use.  This can be one of
   the strings ``'AF_INET'`` (for a TCP socket), ``'AF_UNIX'`` (for a Unix
   domain socket) or ``'AF_PIPE'`` (for a Windows named pipe).  Of these only
   the first is guaranteed to be available.  If *family* is ``None`` then the
   family is inferred from the format of *address*.  If *address* is also
   ``None`` then a default is chosen.  This default is the family which is
   assumed to be the fastest available.  See
   :ref:`multiprocessing-address-formats`.  Note that if *family* is
   ``'AF_UNIX'`` and address is ``None`` then the socket will be created in a
   private temporary directory created using :func:`tempfile.mkstemp`.

   If the listener object uses a socket then *backlog* (1 by default) is passed
   to the :meth:`~socket.socket.listen` method of the socket once it has been
   bound.

   If *authenticate* is ``True`` (``False`` by default) or *authkey* is not
   ``None`` then digest authentication is used.

   If *authkey* is a string then it will be used as the authentication key;
   otherwise it must be ``None``.

   If *authkey* is ``None`` and *authenticate* is ``True`` then
   ``current_process().authkey`` is used as the authentication key.  If
   *authkey* is ``None`` and *authenticate* is ``False`` then no
   authentication is done.  If authentication fails then
   :exc:`AuthenticationError` is raised.  See :ref:`multiprocessing-auth-keys`.

   .. method:: accept()

      Accept a connection on the bound socket or named pipe of the listener
      object and return a :class:`Connection` object.
      If authentication is attempted and fails, then
      :exc:`~multiprocessing.AuthenticationError` is raised.

   .. method:: close()

      Close the bound socket or named pipe of the listener object.  This is
      called automatically when the listener is garbage collected.  However it
      is advisable to call it explicitly.

   Listener objects have the following read-only properties:

   .. attribute:: address

      The address which is being used by the Listener object.

   .. attribute:: last_accepted

      The address from which the last accepted connection came.  If this is
      unavailable then it is ``None``.


The module defines the following exceptions:

.. exception:: ProcessError

   The base class of all :mod:`multiprocessing` exceptions.

.. exception:: BufferTooShort

   Exception raised by :meth:`Connection.recv_bytes_into()` when the supplied
   buffer object is too small for the message read.

.. exception:: AuthenticationError

   Raised when there is an authentication error.

.. exception:: TimeoutError

   Raised by methods with a timeout when the timeout expires.


**Examples**

The following server code creates a listener which uses ``'secret password'`` as
an authentication key.  It then waits for a connection and sends some data to
the client::

   from multiprocessing.connection import Listener
   from array import array

   address = ('localhost', 6000)     # family is deduced to be 'AF_INET'
   listener = Listener(address, authkey='secret password')

   conn = listener.accept()
   print 'connection accepted from', listener.last_accepted

   conn.send([2.25, None, 'junk', float])

   conn.send_bytes('hello')

   conn.send_bytes(array('i', [42, 1729]))

   conn.close()
   listener.close()

The following code connects to the server and receives some data from the
server::

   from multiprocessing.connection import Client
   from array import array

   address = ('localhost', 6000)
   conn = Client(address, authkey='secret password')

   print conn.recv()                 # => [2.25, None, 'junk', float]

   print conn.recv_bytes()            # => 'hello'

   arr = array('i', [0, 0, 0, 0, 0])
   print conn.recv_bytes_into(arr)     # => 8
   print arr                         # => array('i', [42, 1729, 0, 0, 0])

   conn.close()


.. _multiprocessing-address-formats:

Address Formats
>>>>>>>>>>>>>>>

* An ``'AF_INET'`` address is a tuple of the form ``(hostname, port)`` where
  *hostname* is a string and *port* is an integer.

* An ``'AF_UNIX'`` address is a string representing a filename on the
  filesystem.

* An ``'AF_PIPE'`` address is a string of the form
   :samp:`r'\\\\.\\pipe\\{PipeName}'`.  To use :func:`Client` to connect to a named
   pipe on a remote computer called *ServerName* one should use an address of the
   form :samp:`r'\\\\{ServerName}\\pipe\\{PipeName}'` instead.

Note that any string beginning with two backslashes is assumed by default to be
an ``'AF_PIPE'`` address rather than an ``'AF_UNIX'`` address.


.. _multiprocessing-auth-keys:

Authentication keys
~~~~~~~~~~~~~~~~~~~

When one uses :meth:`Connection.recv`, the
data received is automatically
unpickled.  Unfortunately unpickling data from an untrusted source is a security
risk.  Therefore :class:`Listener` and :func:`Client` use the :mod:`hmac` module
to provide digest authentication.

An authentication key is a string which can be thought of as a password: once a
connection is established both ends will demand proof that the other knows the
authentication key.  (Demonstrating that both ends are using the same key does
**not** involve sending the key over the connection.)

If authentication is requested but no authentication key is specified then the
return value of ``current_process().authkey`` is used (see
:class:`~multiprocessing.Process`).  This value will be automatically inherited by
any :class:`~multiprocessing.Process` object that the current process creates.
This means that (by default) all processes of a multi-process program will share
a single authentication key which can be used when setting up connections
between themselves.

Suitable authentication keys can also be generated by using :func:`os.urandom`.


Logging
~~~~~~~

Some support for logging is available.  Note, however, that the :mod:`logging`
package does not use process shared locks so it is possible (depending on the
handler type) for messages from different processes to get mixed up.

.. currentmodule:: multiprocessing
.. function:: get_logger()

   Returns the logger used by :mod:`multiprocessing`.  If necessary, a new one
   will be created.

   When first created the logger has level :data:`logging.NOTSET` and no
   default handler. Messages sent to this logger will not by default propagate
   to the root logger.

   Note that on Windows child processes will only inherit the level of the
   parent process's logger -- any other customization of the logger will not be
   inherited.

.. currentmodule:: multiprocessing
.. function:: log_to_stderr()

   This function performs a call to :func:`get_logger` but in addition to
   returning the logger created by get_logger, it adds a handler which sends
   output to :data:`sys.stderr` using format
   ``'[%(levelname)s/%(processName)s] %(message)s'``.

Below is an example session with logging turned on::

    >>> import multiprocessing, logging
    >>> logger = multiprocessing.log_to_stderr()
    >>> logger.setLevel(logging.INFO)
    >>> logger.warning('doomed')
    [WARNING/MainProcess] doomed
    >>> m = multiprocessing.Manager()
    [INFO/SyncManager-...] child process calling self.run()
    [INFO/SyncManager-...] created temp directory /.../pymp-...
    [INFO/SyncManager-...] manager serving at '/.../listener-...'
    >>> del m
    [INFO/MainProcess] sending shutdown message to manager
    [INFO/SyncManager-...] manager exiting with exitcode 0

In addition to having these two logging functions, the multiprocessing also
exposes two additional logging level attributes. These are  :const:`SUBWARNING`
and :const:`SUBDEBUG`. The table below illustrates where theses fit in the
normal level hierarchy.

+----------------+----------------+
| Level          | Numeric value  |
+================+================+
| ``SUBWARNING`` | 25             |
+----------------+----------------+
| ``SUBDEBUG``   | 5              |
+----------------+----------------+

For a full table of logging levels, see the :mod:`logging` module.

These additional logging levels are used primarily for certain debug messages
within the multiprocessing module. Below is the same example as above, except
with :const:`SUBDEBUG` enabled::

    >>> import multiprocessing, logging
    >>> logger = multiprocessing.log_to_stderr()
    >>> logger.setLevel(multiprocessing.SUBDEBUG)
    >>> logger.warning('doomed')
    [WARNING/MainProcess] doomed
    >>> m = multiprocessing.Manager()
    [INFO/SyncManager-...] child process calling self.run()
    [INFO/SyncManager-...] created temp directory /.../pymp-...
    [INFO/SyncManager-...] manager serving at '/.../pymp-djGBXN/listener-...'
    >>> del m
    [SUBDEBUG/MainProcess] finalizer calling ...
    [INFO/MainProcess] sending shutdown message to manager
    [DEBUG/SyncManager-...] manager received shutdown message
    [SUBDEBUG/SyncManager-...] calling <Finalize object, callback=unlink, ...
    [SUBDEBUG/SyncManager-...] finalizer calling <built-in function unlink> ...
    [SUBDEBUG/SyncManager-...] calling <Finalize object, dead>
    [SUBDEBUG/SyncManager-...] finalizer calling <function rmtree at 0x5aa730> ...
    [INFO/SyncManager-...] manager exiting with exitcode 0

The :mod:`multiprocessing.dummy` module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. module:: multiprocessing.dummy
   :synopsis: Dumb wrapper around threading.

:mod:`multiprocessing.dummy` replicates the API of :mod:`multiprocessing` but is
no more than a wrapper around the :mod:`threading` module.


.. _multiprocessing-programming:

Programming guidelines
----------------------

There are certain guidelines and idioms which should be adhered to when using
:mod:`multiprocessing`.


All platforms
~~~~~~~~~~~~~

Avoid shared state

    As far as possible one should try to avoid shifting large amounts of data
    between processes.

    It is probably best to stick to using queues or pipes for communication
    between processes rather than using the lower level synchronization
    primitives from the :mod:`threading` module.

Picklability

    Ensure that the arguments to the methods of proxies are picklable.

Thread safety of proxies

    Do not use a proxy object from more than one thread unless you protect it
    with a lock.

    (There is never a problem with different processes using the *same* proxy.)

Joining zombie processes

    On Unix when a process finishes but has not been joined it becomes a zombie.
    There should never be very many because each time a new process starts (or
    :func:`~multiprocessing.active_children` is called) all completed processes
    which have not yet been joined will be joined.  Also calling a finished
    process's :meth:`Process.is_alive <multiprocessing.Process.is_alive>` will
    join the process.  Even so it is probably good
    practice to explicitly join all the processes that you start.

Better to inherit than pickle/unpickle

    On Windows many types from :mod:`multiprocessing` need to be picklable so
    that child processes can use them.  However, one should generally avoid
    sending shared objects to other processes using pipes or queues.  Instead
    you should arrange the program so that a process which needs access to a
    shared resource created elsewhere can inherit it from an ancestor process.

Avoid terminating processes

    Using the :meth:`Process.terminate <multiprocessing.Process.terminate>`
    method to stop a process is liable to
    cause any shared resources (such as locks, semaphores, pipes and queues)
    currently being used by the process to become broken or unavailable to other
    processes.

    Therefore it is probably best to only consider using
    :meth:`Process.terminate <multiprocessing.Process.terminate>` on processes
    which never use any shared resources.

Joining processes that use queues

    Bear in mind that a process that has put items in a queue will wait before
    terminating until all the buffered items are fed by the "feeder" thread to
    the underlying pipe.  (The child process can call the
    :meth:`~multiprocessing.Queue.cancel_join_thread` method of the queue to avoid this behaviour.)

    This means that whenever you use a queue you need to make sure that all
    items which have been put on the queue will eventually be removed before the
    process is joined.  Otherwise you cannot be sure that processes which have
    put items on the queue will terminate.  Remember also that non-daemonic
    processes will be joined automatically.

    An example which will deadlock is the following::

        from multiprocessing import Process, Queue

        def f(q):
            q.put('X' * 1000000)

        if __name__ == '__main__':
            queue = Queue()
            p = Process(target=f, args=(queue,))
            p.start()
            p.join()                    # this deadlocks
            obj = queue.get()

    A fix here would be to swap the last two lines (or simply remove the
    ``p.join()`` line).

Explicitly pass resources to child processes

    On Unix a child process can make use of a shared resource created in a
    parent process using a global resource.  However, it is better to pass the
    object as an argument to the constructor for the child process.

    Apart from making the code (potentially) compatible with Windows this also
    ensures that as long as the child process is still alive the object will not
    be garbage collected in the parent process.  This might be important if some
    resource is freed when the object is garbage collected in the parent
    process.

    So for instance ::

        from multiprocessing import Process, Lock

        def f():
            ... do something using "lock" ...

        if __name__ == '__main__':
            lock = Lock()
            for i in range(10):
                Process(target=f).start()

    should be rewritten as ::

        from multiprocessing import Process, Lock

        def f(l):
            ... do something using "l" ...

        if __name__ == '__main__':
            lock = Lock()
            for i in range(10):
                Process(target=f, args=(lock,)).start()

Beware of replacing :data:`sys.stdin` with a "file like object"

    :mod:`multiprocessing` originally unconditionally called::

        os.close(sys.stdin.fileno())

    in the :meth:`multiprocessing.Process._bootstrap` method --- this resulted
    in issues with processes-in-processes. This has been changed to::

        sys.stdin.close()
        sys.stdin = open(os.devnull)

    Which solves the fundamental issue of processes colliding with each other
    resulting in a bad file descriptor error, but introduces a potential danger
    to applications which replace :func:`sys.stdin` with a "file-like object"
    with output buffering.  This danger is that if multiple processes call
    :meth:`~io.IOBase.close()` on this file-like object, it could result in the same
    data being flushed to the object multiple times, resulting in corruption.

    If you write a file-like object and implement your own caching, you can
    make it fork-safe by storing the pid whenever you append to the cache,
    and discarding the cache when the pid changes. For example::

       @property
       def cache(self):
           pid = os.getpid()
           if pid != self._pid:
               self._pid = pid
               self._cache = []
           return self._cache

    For more information, see :issue:`5155`, :issue:`5313` and :issue:`5331`

Windows
~~~~~~~

Since Windows lacks :func:`os.fork` it has a few extra restrictions:

More picklability

    Ensure that all arguments to :meth:`Process.__init__` are picklable.  This
    means, in particular, that bound or unbound methods cannot be used directly
    as the ``target`` argument on Windows --- just define a function and use
    that instead.

    Also, if you subclass :class:`~multiprocessing.Process` then make sure that
    instances will be picklable when the :meth:`Process.start
    <multiprocessing.Process.start>` method is called.

Global variables

    Bear in mind that if code run in a child process tries to access a global
    variable, then the value it sees (if any) may not be the same as the value
    in the parent process at the time that :meth:`Process.start
    <multiprocessing.Process.start>` was called.

    However, global variables which are just module level constants cause no
    problems.

Safe importing of main module

    Make sure that the main module can be safely imported by a new Python
    interpreter without causing unintended side effects (such a starting a new
    process).

    For example, under Windows running the following module would fail with a
    :exc:`RuntimeError`::

        from multiprocessing import Process

        def foo():
            print 'hello'

        p = Process(target=foo)
        p.start()

    Instead one should protect the "entry point" of the program by using ``if
    __name__ == '__main__':`` as follows::

       from multiprocessing import Process, freeze_support

       def foo():
           print 'hello'

       if __name__ == '__main__':
           freeze_support()
           p = Process(target=foo)
           p.start()

    (The ``freeze_support()`` line can be omitted if the program will be run
    normally instead of frozen.)

    This allows the newly spawned Python interpreter to safely import the module
    and then run the module's ``foo()`` function.

    Similar restrictions apply if a pool or manager is created in the main
    module.


.. _multiprocessing-examples:

Examples
--------

Demonstration of how to create and use customized managers and proxies:

.. literalinclude:: ../includes/mp_newtype.py


Using :class:`~multiprocessing.pool.Pool`:

.. literalinclude:: ../includes/mp_pool.py


Synchronization types like locks, conditions and queues:

.. literalinclude:: ../includes/mp_synchronize.py


An example showing how to use queues to feed tasks to a collection of worker
processes and collect the results:

.. literalinclude:: ../includes/mp_workers.py


An example of how a pool of worker processes can each run a
:class:`SimpleHTTPServer.HttpServer` instance while sharing a single listening
socket.

.. literalinclude:: ../includes/mp_webserver.py


Some simple benchmarks comparing :mod:`multiprocessing` with :mod:`threading`:

.. literalinclude:: ../includes/mp_benchmarks.py

PK	%�\d+�N��#html/_sources/library/mutex.rst.txtnu�[���
:mod:`mutex` --- Mutual exclusion support
=========================================

.. module:: mutex
   :synopsis: Lock and queue for mutual exclusion.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`mutex` module has been removed in Python 3.

.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`mutex` module defines a class that allows mutual-exclusion via
acquiring and releasing locks. It does not require (or imply)
:mod:`threading` or multi-tasking, though it could be useful for those
purposes.

The :mod:`mutex` module defines the following class:


.. class:: mutex()

   Create a new (unlocked) mutex.

   A mutex has two pieces of state --- a "locked" bit and a queue. When the mutex
   is not locked, the queue is empty. Otherwise, the queue contains zero or more
   ``(function, argument)`` pairs representing functions (or methods) waiting to
   acquire the lock. When the mutex is unlocked while the queue is not empty, the
   first queue entry is removed and its  ``function(argument)`` pair called,
   implying it now has the lock.

   Of course, no multi-threading is implied -- hence the funny interface for
   :meth:`lock`, where a function is called once the lock is acquired.


.. _mutex-objects:

Mutex Objects
-------------

:class:`~mutex.mutex` objects have following methods:


.. method:: mutex.test()

   Check whether the mutex is locked.


.. method:: mutex.testandset()

   "Atomic" test-and-set, grab the lock if it is not set, and return ``True``,
   otherwise, return ``False``.


.. method:: mutex.lock(function, argument)

   Execute ``function(argument)``, unless the mutex is locked. In the case it is
   locked, place the function and argument on the queue. See :meth:`unlock` for
   explanation of when ``function(argument)`` is executed in that case.


.. method:: mutex.unlock()

   Unlock the mutex if queue is empty, otherwise execute the first element in the
   queue.

PK	%�\�~ZI��%html/_sources/library/netdata.rst.txtnu�[���
.. _netdata:

**********************
Internet Data Handling
**********************

This chapter describes modules which support handling data formats commonly used
on the Internet.


.. toctree::

   email.rst
   json.rst
   mailcap.rst
   mailbox.rst
   mhlib.rst
   mimetools.rst
   mimetypes.rst
   mimewriter.rst
   mimify.rst
   multifile.rst
   rfc822.rst
   base64.rst
   binhex.rst
   binascii.rst
   quopri.rst
   uu.rst
PK	%�\;>��//#html/_sources/library/netrc.rst.txtnu�[���
:mod:`netrc` --- netrc file processing
======================================

.. module:: netrc
   :synopsis: Loading of .netrc files.
.. moduleauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>


.. versionadded:: 1.5.2

**Source code:** :source:`Lib/netrc.py`

--------------

The :class:`~netrc.netrc` class parses and encapsulates the netrc file format used by
the Unix :program:`ftp` program and other FTP clients.


.. class:: netrc([file])

   A :class:`~netrc.netrc` instance or subclass instance encapsulates data from  a netrc
   file.  The initialization argument, if present, specifies the file to parse.  If
   no argument is given, the file :file:`.netrc` in the user's home directory will
   be read.  Parse errors will raise :exc:`NetrcParseError` with diagnostic
   information including the file name, line number, and terminating token.
   If no argument is specified on a POSIX system, the presence of passwords in
   the :file:`.netrc` file will raise a :exc:`NetrcParseError` if the file
   ownership or permissions are insecure (owned by a user other than the user
   running the process, or accessible for read or write by any other user).
   This implements security behavior equivalent to that of ftp and other
   programs that use :file:`.netrc`.

   .. versionchanged:: 2.7.6 Added the POSIX permissions check.


.. exception:: NetrcParseError

   Exception raised by the :class:`~netrc.netrc` class when syntactical errors are
   encountered in source text.  Instances of this exception provide three
   interesting attributes:  :attr:`msg` is a textual explanation of the error,
   :attr:`filename` is the name of the source file, and :attr:`lineno` gives the
   line number on which the error was found.


.. _netrc-objects:

netrc Objects
-------------

A :class:`~netrc.netrc` instance has the following methods:


.. method:: netrc.authenticators(host)

   Return a 3-tuple ``(login, account, password)`` of authenticators for *host*.
   If the netrc file did not contain an entry for the given host, return the tuple
   associated with the 'default' entry.  If neither matching host nor default entry
   is available, return ``None``.


.. method:: netrc.__repr__()

   Dump the class data as a string in the format of a netrc file. (This discards
   comments and may reorder the entries.)

Instances of :class:`~netrc.netrc` have public instance variables:


.. attribute:: netrc.hosts

   Dictionary mapping host names to ``(login, account, password)`` tuples.  The
   'default' entry, if any, is represented as a pseudo-host by that name.


.. attribute:: netrc.macros

   Dictionary mapping macro names to string lists.

.. note::

   Passwords are limited to a subset of the ASCII character set. Versions of
   this module prior to 2.3 were extremely limited.  Starting with 2.3, all
   ASCII punctuation is allowed in passwords.  However, note that whitespace and
   non-printable characters are not allowed in passwords.  This is a limitation
   of the way the .netrc file is parsed and may be removed in the future.

PK	%�\
Pe?]
]
!html/_sources/library/new.rst.txtnu�[���:mod:`new` --- Creation of runtime internal objects
===================================================

.. module:: new
   :synopsis: Interface to the creation of runtime implementation objects.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`new` module has been removed in Python 3.  Use the :mod:`types`
   module's classes instead.

.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`new` module allows an interface to the interpreter object creation
functions. This is for use primarily in marshal-type functions, when a new
object needs to be created "magically" and not by using the regular creation
functions. This module provides a low-level interface to the interpreter, so
care must be exercised when using this module. It is possible to supply
non-sensical arguments which crash the interpreter when the object is used.

The :mod:`new` module defines the following functions:


.. function:: instance(class[, dict])

   This function creates an instance of *class* with dictionary *dict* without
   calling the :meth:`__init__` constructor.  If *dict* is omitted or ``None``, a
   new, empty dictionary is created for the new instance.  Note that there are no
   guarantees that the object will be in a consistent state.


.. function:: instancemethod(function, instance, class)

   This function will return a method object, bound to *instance*, or unbound if
   *instance* is ``None``.  *function* must be callable.


.. function:: function(code, globals[, name[, argdefs[, closure]]])

   Returns a (Python) function with the given code and globals. If *name* is given,
   it must be a string or ``None``.  If it is a string, the function will have the
   given name, otherwise the function name will be taken from ``code.co_name``.  If
   *argdefs* is given, it must be a tuple and will be used to determine the default
   values of parameters.  If *closure* is given, it must be ``None`` or a tuple of
   cell objects containing objects to bind to the names in ``code.co_freevars``.


.. function:: code(argcount, nlocals, stacksize, flags, codestring, constants, names, varnames, filename, name, firstlineno, lnotab)

   This function is an interface to the :c:func:`PyCode_New` C function.

   .. XXX This is still undocumented!


.. function:: module(name[, doc])

   This function returns a new module object with name *name*. *name* must be a
   string. The optional *doc* argument can have any type.


.. function:: classobj(name, baseclasses, dict)

   This function returns a new class object, with name *name*, derived from
   *baseclasses* (which should be a tuple of classes) and with namespace *dict*.

PK	%�\_�<<<!html/_sources/library/nis.rst.txtnu�[���
:mod:`nis` --- Interface to Sun's NIS (Yellow Pages)
====================================================

.. module:: nis
   :platform: Unix
   :synopsis: Interface to Sun's NIS (Yellow Pages) library.
.. moduleauthor:: Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`nis` module gives a thin wrapper around the NIS library, useful for
central administration of several hosts.

Because NIS exists only on Unix systems, this module is only available for Unix.

The :mod:`nis` module defines the following functions:


.. function:: match(key, mapname[, domain=default_domain])

   Return the match for *key* in map *mapname*, or raise an error
   (:exc:`nis.error`) if there is none. Both should be strings, *key* is 8-bit
   clean. Return value is an arbitrary array of bytes (may contain ``NULL`` and
   other joys).

   Note that *mapname* is first checked if it is an alias to another name.

   .. versionchanged:: 2.5
      The *domain* argument allows overriding the NIS domain used for the lookup. If
      unspecified, lookup is in the default NIS domain.


.. function:: cat(mapname[, domain=default_domain])

   Return a dictionary mapping *key* to *value* such that ``match(key,
   mapname)==value``. Note that both keys and values of the dictionary are
   arbitrary arrays of bytes.

   Note that *mapname* is first checked if it is an alias to another name.

   .. versionchanged:: 2.5
      The *domain* argument allows overriding the NIS domain used for the lookup. If
      unspecified, lookup is in the default NIS domain.


.. function:: maps([domain=default_domain])

   Return a list of all valid maps.

   .. versionchanged:: 2.5
      The *domain* argument allows overriding the NIS domain used for the lookup. If
      unspecified, lookup is in the default NIS domain.


.. function:: get_default_domain()

   Return the system default NIS domain.

   .. versionadded:: 2.5

The :mod:`nis` module defines the following exception:


.. exception:: error

   An error raised when a NIS function returns an error code.

PK	%�\����8�8%html/_sources/library/nntplib.rst.txtnu�[���
:mod:`nntplib` --- NNTP protocol client
=======================================

.. module:: nntplib
   :synopsis: NNTP protocol client (requires sockets).


.. index::
   pair: NNTP; protocol
   single: Network News Transfer Protocol

**Source code:** :source:`Lib/nntplib.py`

--------------

This module defines the class :class:`NNTP` which implements the client side of
the NNTP protocol.  It can be used to implement a news reader or poster, or
automated news processors.  For more information on NNTP (Network News Transfer
Protocol), see Internet :rfc:`977`.

Here are two small examples of how it can be used.  To list some statistics
about a newsgroup and print the subjects of the last 10 articles::

   >>> s = NNTP('news.gmane.org')
   >>> resp, count, first, last, name = s.group('gmane.comp.python.committers')
   >>> print 'Group', name, 'has', count, 'articles, range', first, 'to', last
   Group gmane.comp.python.committers has 1071 articles, range 1 to 1071
   >>> resp, subs = s.xhdr('subject', first + '-' + last)
   >>> for id, sub in subs[-10:]: print id, sub
   ...
   1062 Re: Mercurial Status?
   1063 Re: [python-committers]  (Windows) buildbots on 3.x
   1064 Re: Mercurial Status?
   1065 Re: Mercurial Status?
   1066 Python 2.6.6 status
   1067 Commit Privileges for Ask Solem
   1068 Re: Commit Privileges for Ask Solem
   1069 Re: Commit Privileges for Ask Solem
   1070 Re: Commit Privileges for Ask Solem
   1071 2.6.6 rc 2
   >>> s.quit()
   '205 Bye!'

To post an article from a file (this assumes that the article has valid
headers, and that you have right to post on the particular newsgroup)::

   >>> s = NNTP('news.gmane.org')
   >>> f = open('articlefile')
   >>> s.post(f)
   '240 Article posted successfully.'
   >>> s.quit()
   '205 Bye!'

The module itself defines the following items:


.. class:: NNTP(host[, port [, user[, password [, readermode] [, usenetrc]]]])

   Return a new instance of the :class:`NNTP` class, representing a connection
   to the NNTP server running on host *host*, listening at port *port*.  The
   default *port* is 119.  If the optional *user* and *password* are provided,
   or if suitable credentials are present in :file:`/.netrc` and the optional
   flag *usenetrc* is true (the default), the ``AUTHINFO USER`` and ``AUTHINFO
   PASS`` commands are used to identify and authenticate the user to the server.
   If the optional flag *readermode* is true, then a ``mode reader`` command is
   sent before authentication is performed.  Reader mode is sometimes necessary
   if you are connecting to an NNTP server on the local machine and intend to
   call reader-specific commands, such as ``group``.  If you get unexpected
   :exc:`NNTPPermanentError`\ s, you might need to set *readermode*.
   *readermode* defaults to ``None``. *usenetrc* defaults to ``True``.

   .. versionchanged:: 2.4
      *usenetrc* argument added.


.. exception:: NNTPError

   Derived from the standard exception :exc:`Exception`, this is the base class for
   all exceptions raised by the :mod:`nntplib` module.


.. exception:: NNTPReplyError

   Exception raised when an unexpected reply is received from the server.  For
   backwards compatibility, the exception ``error_reply`` is equivalent to this
   class.


.. exception:: NNTPTemporaryError

   Exception raised when an error code in the range 400--499 is received.  For
   backwards compatibility, the exception ``error_temp`` is equivalent to this
   class.


.. exception:: NNTPPermanentError

   Exception raised when an error code in the range 500--599 is received.  For
   backwards compatibility, the exception ``error_perm`` is equivalent to this
   class.


.. exception:: NNTPProtocolError

   Exception raised when a reply is received from the server that does not begin
   with a digit in the range 1--5.  For backwards compatibility, the exception
   ``error_proto`` is equivalent to this class.


.. exception:: NNTPDataError

   Exception raised when there is some error in the response data.  For backwards
   compatibility, the exception ``error_data`` is equivalent to this class.


.. _nntp-objects:

NNTP Objects
------------

NNTP instances have the following methods.  The *response* that is returned as
the first item in the return tuple of almost all methods is the server's
response: a string beginning with a three-digit code. If the server's response
indicates an error, the method raises one of the above exceptions.


.. method:: NNTP.getwelcome()

   Return the welcome message sent by the server in reply to the initial
   connection.  (This message sometimes contains disclaimers or help information
   that may be relevant to the user.)


.. method:: NNTP.set_debuglevel(level)

   Set the instance's debugging level.  This controls the amount of debugging
   output printed.  The default, ``0``, produces no debugging output.  A value of
   ``1`` produces a moderate amount of debugging output, generally a single line
   per request or response.  A value of ``2`` or higher produces the maximum amount
   of debugging output, logging each line sent and received on the connection
   (including message text).


.. method:: NNTP.newgroups(date, time, [file])

   Send a ``NEWGROUPS`` command.  The *date* argument should be a string of the
   form ``'yymmdd'`` indicating the date, and *time* should be a string of the form
   ``'hhmmss'`` indicating the time.  Return a pair ``(response, groups)`` where
   *groups* is a list of group names that are new since the given date and time. If
   the *file* parameter is supplied, then the output of the  ``NEWGROUPS`` command
   is stored in a file.  If *file* is a string,  then the method will open a file
   object with that name, write to it  then close it.  If *file* is a file object,
   then it will start calling :meth:`write` on it to store the lines of the command
   output. If *file* is supplied, then the returned *list* is an empty list.


.. method:: NNTP.newnews(group, date, time, [file])

   Send a ``NEWNEWS`` command.  Here, *group* is a group name or ``'*'``, and
   *date* and *time* have the same meaning as for :meth:`newgroups`.  Return a pair
   ``(response, articles)`` where *articles* is a list of message ids. If the
   *file* parameter is supplied, then the output of the  ``NEWNEWS`` command is
   stored in a file.  If *file* is a string,  then the method will open a file
   object with that name, write to it  then close it.  If *file* is a file object,
   then it will start calling :meth:`write` on it to store the lines of the command
   output. If *file* is supplied, then the returned *list* is an empty list.


.. method:: NNTP.list([file])

   Send a ``LIST`` command.  Return a pair ``(response, list)`` where *list* is a
   list of tuples.  Each tuple has the form ``(group, last, first, flag)``, where
   *group* is a group name, *last* and *first* are the last and first article
   numbers (as strings), and *flag* is ``'y'`` if posting is allowed, ``'n'`` if
   not, and ``'m'`` if the newsgroup is moderated.  (Note the ordering: *last*,
   *first*.) If the *file* parameter is supplied, then the output of the  ``LIST``
   command is stored in a file.  If *file* is a string,  then the method will open
   a file object with that name, write to it  then close it.  If *file* is a file
   object, then it will start calling :meth:`write` on it to store the lines of the
   command output. If *file* is supplied, then the returned *list* is an empty
   list.


.. method:: NNTP.descriptions(grouppattern)

   Send a ``LIST NEWSGROUPS`` command, where *grouppattern* is a wildmat string as
   specified in RFC2980 (it's essentially the same as DOS or UNIX shell wildcard
   strings).  Return a pair ``(response, list)``, where *list* is a list of tuples
   containing ``(name, title)``.

   .. versionadded:: 2.4


.. method:: NNTP.description(group)

   Get a description for a single group *group*.  If more than one group matches
   (if 'group' is a real wildmat string), return the first match.   If no group
   matches, return an empty string.

   This elides the response code from the server.  If the response code is needed,
   use :meth:`descriptions`.

   .. versionadded:: 2.4


.. method:: NNTP.group(name)

   Send a ``GROUP`` command, where *name* is the group name. Return a tuple
   ``(response, count, first, last, name)`` where *count* is the (estimated) number
   of articles in the group, *first* is the first article number in the group,
   *last* is the last article number in the group, and *name* is the group name.
   The numbers are returned as strings.


.. method:: NNTP.help([file])

   Send a ``HELP`` command.  Return a pair ``(response, list)`` where *list* is a
   list of help strings. If the *file* parameter is supplied, then the output of
   the  ``HELP`` command is stored in a file.  If *file* is a string,  then the
   method will open a file object with that name, write to it  then close it.  If
   *file* is a file object, then it will start calling :meth:`write` on it to store
   the lines of the command output. If *file* is supplied, then the returned *list*
   is an empty list.


.. method:: NNTP.stat(id)

   Send a ``STAT`` command, where *id* is the message id (enclosed in ``'<'`` and
   ``'>'``) or an article number (as a string). Return a triple ``(response,
   number, id)`` where *number* is the article number (as a string) and *id* is the
   message id  (enclosed in ``'<'`` and ``'>'``).


.. method:: NNTP.next()

   Send a ``NEXT`` command.  Return as for :meth:`.stat`.


.. method:: NNTP.last()

   Send a ``LAST`` command.  Return as for :meth:`.stat`.


.. method:: NNTP.head(id)

   Send a ``HEAD`` command, where *id* has the same meaning as for :meth:`.stat`.
   Return a tuple ``(response, number, id, list)`` where the first three are the
   same as for :meth:`.stat`, and *list* is a list of the article's headers (an
   uninterpreted list of lines, without trailing newlines).


.. method:: NNTP.body(id,[file])

   Send a ``BODY`` command, where *id* has the same meaning as for :meth:`.stat`.
   If the *file* parameter is supplied, then the body is stored in a file.  If
   *file* is a string, then the method will open a file object with that name,
   write to it then close it. If *file* is a file object, then it will start
   calling :meth:`write` on it to store the lines of the body. Return as for
   :meth:`head`.  If *file* is supplied, then the returned *list* is an empty list.


.. method:: NNTP.article(id)

   Send an ``ARTICLE`` command, where *id* has the same meaning as for
   :meth:`.stat`.  Return as for :meth:`head`.


.. method:: NNTP.slave()

   Send a ``SLAVE`` command.  Return the server's *response*.


.. method:: NNTP.xhdr(header, string, [file])

   Send an ``XHDR`` command.  This command is not defined in the RFC but is a
   common extension.  The *header* argument is a header keyword, e.g.
   ``'subject'``.  The *string* argument should have the form ``'first-last'``
   where *first* and *last* are the first and last article numbers to search.
   Return a pair ``(response, list)``, where *list* is a list of pairs ``(id,
   text)``, where *id* is an article number (as a string) and *text* is the text of
   the requested header for that article. If the *file* parameter is supplied, then
   the output of the  ``XHDR`` command is stored in a file.  If *file* is a string,
   then the method will open a file object with that name, write to it  then close
   it.  If *file* is a file object, then it will start calling :meth:`write` on it
   to store the lines of the command output. If *file* is supplied, then the
   returned *list* is an empty list.


.. method:: NNTP.post(file)

   Post an article using the ``POST`` command.  The *file* argument is an open file
   object which is read until EOF using its :meth:`~file.readline` method.  It should be
   a well-formed news article, including the required headers.  The :meth:`post`
   method automatically escapes lines beginning with ``.``.


.. method:: NNTP.ihave(id, file)

   Send an ``IHAVE`` command. *id* is a message id (enclosed in  ``'<'`` and
   ``'>'``). If the response is not an error, treat *file* exactly as for the
   :meth:`post` method.


.. method:: NNTP.date()

   Return a triple ``(response, date, time)``, containing the current date and time
   in a form suitable for the :meth:`newnews` and :meth:`newgroups` methods. This
   is an optional NNTP extension, and may not be supported by all servers.


.. method:: NNTP.xgtitle(name, [file])

   Process an ``XGTITLE`` command, returning a pair ``(response, list)``, where
   *list* is a list of tuples containing ``(name, title)``. If the *file* parameter
   is supplied, then the output of the  ``XGTITLE`` command is stored in a file.
   If *file* is a string,  then the method will open a file object with that name,
   write to it  then close it.  If *file* is a file object, then it will start
   calling :meth:`write` on it to store the lines of the command output. If *file*
   is supplied, then the returned *list* is an empty list. This is an optional NNTP
   extension, and may not be supported by all servers.

   RFC2980 says "It is suggested that this extension be deprecated".  Use
   :meth:`descriptions` or :meth:`description` instead.


.. method:: NNTP.xover(start, end, [file])

   Return a pair ``(resp, list)``.  *list* is a list of tuples, one for each
   article in the range delimited by the *start* and *end* article numbers.  Each
   tuple is of the form ``(article number, subject, poster, date, id, references,
   size, lines)``. If the *file* parameter is supplied, then the output of the
   ``XOVER`` command is stored in a file.  If *file* is a string,  then the method
   will open a file object with that name, write to it  then close it.  If *file*
   is a file object, then it will start calling :meth:`write` on it to store the
   lines of the command output. If *file* is supplied, then the returned *list* is
   an empty list. This is an optional NNTP extension, and may not be supported by
   all servers.


.. method:: NNTP.xpath(id)

   Return a pair ``(resp, path)``, where *path* is the directory path to the
   article with message ID *id*.  This is an optional NNTP extension, and may not
   be supported by all servers.


.. method:: NNTP.quit()

   Send a ``QUIT`` command and close the connection.  Once this method has been
   called, no other methods of the NNTP object should be called.

PK	%�\R��?GG%html/_sources/library/numbers.rst.txtnu�[���:mod:`numbers` --- Numeric abstract base classes
================================================

.. module:: numbers
   :synopsis: Numeric abstract base classes (Complex, Real, Integral, etc.).

.. versionadded:: 2.6


The :mod:`numbers` module (:pep:`3141`) defines a hierarchy of numeric
:term:`abstract base classes <abstract base class>` which progressively define
more operations.  None of the types defined in this module can be instantiated.


.. class:: Number

   The root of the numeric hierarchy. If you just want to check if an argument
   *x* is a number, without caring what kind, use ``isinstance(x, Number)``.


The numeric tower
-----------------

.. class:: Complex

   Subclasses of this type describe complex numbers and include the operations
   that work on the built-in :class:`complex` type. These are: conversions to
   :class:`complex` and :class:`bool`, :attr:`.real`, :attr:`.imag`, ``+``,
   ``-``, ``*``, ``/``, :func:`abs`, :meth:`conjugate`, ``==``, and ``!=``. All
   except ``-`` and ``!=`` are abstract.

   .. attribute:: real

      Abstract. Retrieves the real component of this number.

   .. attribute:: imag

      Abstract. Retrieves the imaginary component of this number.

   .. method:: conjugate()

      Abstract. Returns the complex conjugate. For example, ``(1+3j).conjugate()
      == (1-3j)``.

.. class:: Real

   To :class:`Complex`, :class:`Real` adds the operations that work on real
   numbers.

   In short, those are: a conversion to :class:`float`, :func:`math.trunc`,
   :func:`round`, :func:`math.floor`, :func:`math.ceil`, :func:`divmod`, ``//``,
   ``%``, ``<``, ``<=``, ``>``, and ``>=``.

   Real also provides defaults for :func:`complex`, :attr:`~Complex.real`,
   :attr:`~Complex.imag`, and :meth:`~Complex.conjugate`.


.. class:: Rational

   Subtypes :class:`Real` and adds
   :attr:`~Rational.numerator` and :attr:`~Rational.denominator` properties, which
   should be in lowest terms. With these, it provides a default for
   :func:`float`.

   .. attribute:: numerator

      Abstract.

   .. attribute:: denominator

      Abstract.


.. class:: Integral

   Subtypes :class:`Rational` and adds a conversion to :class:`int`.  Provides
   defaults for :func:`float`, :attr:`~Rational.numerator`, and
   :attr:`~Rational.denominator`.  Adds abstract methods for ``**`` and
   bit-string operations: ``<<``, ``>>``, ``&``, ``^``, ``|``, ``~``.


Notes for type implementors
---------------------------

Implementors should be careful to make equal numbers equal and hash
them to the same values. This may be subtle if there are two different
extensions of the real numbers. For example, :class:`fractions.Fraction`
implements :func:`hash` as follows::

    def __hash__(self):
        if self.denominator == 1:
            # Get integers right.
            return hash(self.numerator)
        # Expensive check, but definitely correct.
        if self == float(self):
            return hash(float(self))
        else:
            # Use tuple's hash to avoid a high collision rate on
            # simple fractions.
            return hash((self.numerator, self.denominator))


Adding More Numeric ABCs
~~~~~~~~~~~~~~~~~~~~~~~~

There are, of course, more possible ABCs for numbers, and this would
be a poor hierarchy if it precluded the possibility of adding
those. You can add ``MyFoo`` between :class:`Complex` and
:class:`Real` with::

    class MyFoo(Complex): ...
    MyFoo.register(Real)


Implementing the arithmetic operations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

We want to implement the arithmetic operations so that mixed-mode
operations either call an implementation whose author knew about the
types of both arguments, or convert both to the nearest built in type
and do the operation there. For subtypes of :class:`Integral`, this
means that :meth:`__add__` and :meth:`__radd__` should be defined as::

    class MyIntegral(Integral):

        def __add__(self, other):
            if isinstance(other, MyIntegral):
                return do_my_adding_stuff(self, other)
            elif isinstance(other, OtherTypeIKnowAbout):
                return do_my_other_adding_stuff(self, other)
            else:
                return NotImplemented

        def __radd__(self, other):
            if isinstance(other, MyIntegral):
                return do_my_adding_stuff(other, self)
            elif isinstance(other, OtherTypeIKnowAbout):
                return do_my_other_adding_stuff(other, self)
            elif isinstance(other, Integral):
                return int(other) + int(self)
            elif isinstance(other, Real):
                return float(other) + float(self)
            elif isinstance(other, Complex):
                return complex(other) + complex(self)
            else:
                return NotImplemented


There are 5 different cases for a mixed-type operation on subclasses
of :class:`Complex`. I'll refer to all of the above code that doesn't
refer to ``MyIntegral`` and ``OtherTypeIKnowAbout`` as
"boilerplate". ``a`` will be an instance of ``A``, which is a subtype
of :class:`Complex` (``a : A <: Complex``), and ``b : B <:
Complex``. I'll consider ``a + b``:

    1. If ``A`` defines an :meth:`__add__` which accepts ``b``, all is
       well.
    2. If ``A`` falls back to the boilerplate code, and it were to
       return a value from :meth:`__add__`, we'd miss the possibility
       that ``B`` defines a more intelligent :meth:`__radd__`, so the
       boilerplate should return :const:`NotImplemented` from
       :meth:`__add__`. (Or ``A`` may not implement :meth:`__add__` at
       all.)
    3. Then ``B``'s :meth:`__radd__` gets a chance. If it accepts
       ``a``, all is well.
    4. If it falls back to the boilerplate, there are no more possible
       methods to try, so this is where the default implementation
       should live.
    5. If ``B <: A``, Python tries ``B.__radd__`` before
       ``A.__add__``. This is ok, because it was implemented with
       knowledge of ``A``, so it can handle those instances before
       delegating to :class:`Complex`.

If ``A <: Complex`` and ``B <: Real`` without sharing any other knowledge,
then the appropriate shared operation is the one involving the built
in :class:`complex`, and both :meth:`__radd__` s land there, so ``a+b
== b+a``.

Because most of the operations on any given type will be very similar,
it can be useful to define a helper function which generates the
forward and reverse instances of any given operator. For example,
:class:`fractions.Fraction` uses::

    def _operator_fallbacks(monomorphic_operator, fallback_operator):
        def forward(a, b):
            if isinstance(b, (int, long, Fraction)):
                return monomorphic_operator(a, b)
            elif isinstance(b, float):
                return fallback_operator(float(a), b)
            elif isinstance(b, complex):
                return fallback_operator(complex(a), b)
            else:
                return NotImplemented
        forward.__name__ = '__' + fallback_operator.__name__ + '__'
        forward.__doc__ = monomorphic_operator.__doc__

        def reverse(b, a):
            if isinstance(a, Rational):
                # Includes ints.
                return monomorphic_operator(a, b)
            elif isinstance(a, numbers.Real):
                return fallback_operator(float(a), float(b))
            elif isinstance(a, numbers.Complex):
                return fallback_operator(complex(a), complex(b))
            else:
                return NotImplemented
        reverse.__name__ = '__r' + fallback_operator.__name__ + '__'
        reverse.__doc__ = monomorphic_operator.__doc__

        return forward, reverse

    def _add(a, b):
        """a + b"""
        return Fraction(a.numerator * b.denominator +
                        b.numerator * a.denominator,
                        a.denominator * b.denominator)

    __add__, __radd__ = _operator_fallbacks(_add, operator.add)

    # ...
PK	%�\<��z��%html/_sources/library/numeric.rst.txtnu�[���
.. _numeric:

********************************
Numeric and Mathematical Modules
********************************

The modules described in this chapter provide numeric and math-related functions
and data types. The :mod:`numbers` module defines an abstract hierarchy of
numeric types. The :mod:`math` and :mod:`cmath` modules contain various
mathematical functions for floating-point and complex numbers. For users more
interested in decimal accuracy than in speed, the :mod:`decimal` module supports
exact representations of decimal numbers.

The following modules are documented in this chapter:


.. toctree::

   numbers.rst
   math.rst
   cmath.rst
   decimal.rst
   fractions.rst
   random.rst
   itertools.rst
   functools.rst
   operator.rst
PK	%�\��LVLV&html/_sources/library/operator.rst.txtnu�[���:mod:`operator` --- Standard operators as functions
===================================================

.. module:: operator
   :synopsis: Functions corresponding to the standard operators.
.. sectionauthor:: Skip Montanaro <skip@automatrix.com>


.. testsetup::

   import operator
   from operator import itemgetter


The :mod:`operator` module exports a set of efficient functions corresponding to
the intrinsic operators of Python.  For example, ``operator.add(x, y)`` is
equivalent to the expression ``x+y``.  The function names are those used for
special class methods; variants without leading and trailing ``__`` are also
provided for convenience.

The functions fall into categories that perform object comparisons, logical
operations, mathematical operations, sequence operations, and abstract type
tests.

The object comparison functions are useful for all objects, and are named after
the rich comparison operators they support:


.. function:: lt(a, b)
              le(a, b)
              eq(a, b)
              ne(a, b)
              ge(a, b)
              gt(a, b)
              __lt__(a, b)
              __le__(a, b)
              __eq__(a, b)
              __ne__(a, b)
              __ge__(a, b)
              __gt__(a, b)

   Perform "rich comparisons" between *a* and *b*. Specifically, ``lt(a, b)`` is
   equivalent to ``a < b``, ``le(a, b)`` is equivalent to ``a <= b``, ``eq(a,
   b)`` is equivalent to ``a == b``, ``ne(a, b)`` is equivalent to ``a != b``,
   ``gt(a, b)`` is equivalent to ``a > b`` and ``ge(a, b)`` is equivalent to ``a
   >= b``.  Note that unlike the built-in :func:`cmp`, these functions can
   return any value, which may or may not be interpretable as a Boolean value.
   See :ref:`comparisons` for more information about rich comparisons.

   .. versionadded:: 2.2

The logical operations are also generally applicable to all objects, and support
truth tests, identity tests, and boolean operations:


.. function:: not_(obj)
              __not__(obj)

   Return the outcome of :keyword:`not` *obj*.  (Note that there is no
   :meth:`__not__` method for object instances; only the interpreter core defines
   this operation.  The result is affected by the :meth:`__nonzero__` and
   :meth:`__len__` methods.)


.. function:: truth(obj)

   Return :const:`True` if *obj* is true, and :const:`False` otherwise.  This is
   equivalent to using the :class:`bool` constructor.


.. function:: is_(a, b)

   Return ``a is b``.  Tests object identity.

   .. versionadded:: 2.3


.. function:: is_not(a, b)

   Return ``a is not b``.  Tests object identity.

   .. versionadded:: 2.3

The mathematical and bitwise operations are the most numerous:


.. function:: abs(obj)
              __abs__(obj)

   Return the absolute value of *obj*.


.. function:: add(a, b)
              __add__(a, b)

   Return ``a + b``, for *a* and *b* numbers.


.. function:: and_(a, b)
              __and__(a, b)

   Return the bitwise and of *a* and *b*.


.. function:: div(a, b)
              __div__(a, b)

   Return ``a / b`` when ``__future__.division`` is not in effect.  This is
   also known as "classic" division.


.. function:: floordiv(a, b)
              __floordiv__(a, b)

   Return ``a // b``.

   .. versionadded:: 2.2


.. function:: index(a)
              __index__(a)

   Return *a* converted to an integer.  Equivalent to ``a.__index__()``.

   .. versionadded:: 2.5


.. function:: inv(obj)
              invert(obj)
              __inv__(obj)
              __invert__(obj)

   Return the bitwise inverse of the number *obj*.  This is equivalent to ``~obj``.

   .. versionadded:: 2.0
      The names :func:`invert` and :func:`__invert__`.


.. function:: lshift(a, b)
              __lshift__(a, b)

   Return *a* shifted left by *b*.


.. function:: mod(a, b)
              __mod__(a, b)

   Return ``a % b``.


.. function:: mul(a, b)
              __mul__(a, b)

   Return ``a * b``, for *a* and *b* numbers.


.. function:: neg(obj)
              __neg__(obj)

   Return *obj* negated (``-obj``).


.. function:: or_(a, b)
              __or__(a, b)

   Return the bitwise or of *a* and *b*.


.. function:: pos(obj)
              __pos__(obj)

   Return *obj* positive (``+obj``).


.. function:: pow(a, b)
              __pow__(a, b)

   Return ``a ** b``, for *a* and *b* numbers.

   .. versionadded:: 2.3


.. function:: rshift(a, b)
              __rshift__(a, b)

   Return *a* shifted right by *b*.


.. function:: sub(a, b)
              __sub__(a, b)

   Return ``a - b``.


.. function:: truediv(a, b)
              __truediv__(a, b)

   Return ``a / b`` when ``__future__.division`` is in effect.  This is also
   known as "true" division.

   .. versionadded:: 2.2


.. function:: xor(a, b)
              __xor__(a, b)

   Return the bitwise exclusive or of *a* and *b*.


Operations which work with sequences (some of them with mappings too) include:

.. function:: concat(a, b)
              __concat__(a, b)

   Return ``a + b`` for *a* and *b* sequences.


.. function:: contains(a, b)
              __contains__(a, b)

   Return the outcome of the test ``b in a``. Note the reversed operands.

   .. versionadded:: 2.0
      The name :func:`__contains__`.


.. function:: countOf(a, b)

   Return the number of occurrences of *b* in *a*.


.. function:: delitem(a, b)
              __delitem__(a, b)

   Remove the value of *a* at index *b*.


.. function:: delslice(a, b, c)
              __delslice__(a, b, c)

   Delete the slice of *a* from index *b* to index *c-1*.

   .. deprecated:: 2.6
      This function is removed in Python 3.x.  Use :func:`delitem` with a slice
      index.


.. function:: getitem(a, b)
              __getitem__(a, b)

   Return the value of *a* at index *b*.


.. function:: getslice(a, b, c)
              __getslice__(a, b, c)

   Return the slice of *a* from index *b* to index *c-1*.

   .. deprecated:: 2.6
      This function is removed in Python 3.x.  Use :func:`getitem` with a slice
      index.


.. function:: indexOf(a, b)

   Return the index of the first of occurrence of *b* in *a*.


.. function:: repeat(a, b)
              __repeat__(a, b)

   .. deprecated:: 2.7
      Use :func:`__mul__` instead.

   Return ``a * b`` where *a* is a sequence and *b* is an integer.


.. function:: sequenceIncludes(...)

   .. deprecated:: 2.0
      Use :func:`contains` instead.

   Alias for :func:`contains`.


.. function:: setitem(a, b, c)
              __setitem__(a, b, c)

   Set the value of *a* at index *b* to *c*.


.. function:: setslice(a, b, c, v)
              __setslice__(a, b, c, v)

   Set the slice of *a* from index *b* to index *c-1* to the sequence *v*.

   .. deprecated:: 2.6
      This function is removed in Python 3.x.  Use :func:`setitem` with a slice
      index.

Example use of operator functions::

    >>> # Elementwise multiplication
    >>> map(mul, [0, 1, 2, 3], [10, 20, 30, 40])
    [0, 20, 60, 120]

    >>> # Dot product
    >>> sum(map(mul, [0, 1, 2, 3], [10, 20, 30, 40]))
    200

Many operations have an "in-place" version.  The following functions provide a
more primitive access to in-place operators than the usual syntax does; for
example, the :term:`statement` ``x += y`` is equivalent to
``x = operator.iadd(x, y)``.  Another way to put it is to say that
``z = operator.iadd(x, y)`` is equivalent to the compound statement
``z = x; z += y``.

.. function:: iadd(a, b)
              __iadd__(a, b)

   ``a = iadd(a, b)`` is equivalent to ``a += b``.

   .. versionadded:: 2.5


.. function:: iand(a, b)
              __iand__(a, b)

   ``a = iand(a, b)`` is equivalent to ``a &= b``.

   .. versionadded:: 2.5


.. function:: iconcat(a, b)
              __iconcat__(a, b)

   ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.

   .. versionadded:: 2.5


.. function:: idiv(a, b)
              __idiv__(a, b)

   ``a = idiv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division`` is
   not in effect.

   .. versionadded:: 2.5


.. function:: ifloordiv(a, b)
              __ifloordiv__(a, b)

   ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.

   .. versionadded:: 2.5


.. function:: ilshift(a, b)
              __ilshift__(a, b)

   ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.

   .. versionadded:: 2.5


.. function:: imod(a, b)
              __imod__(a, b)

   ``a = imod(a, b)`` is equivalent to ``a %= b``.

   .. versionadded:: 2.5


.. function:: imul(a, b)
              __imul__(a, b)

   ``a = imul(a, b)`` is equivalent to ``a *= b``.

   .. versionadded:: 2.5


.. function:: ior(a, b)
              __ior__(a, b)

   ``a = ior(a, b)`` is equivalent to ``a |= b``.

   .. versionadded:: 2.5


.. function:: ipow(a, b)
              __ipow__(a, b)

   ``a = ipow(a, b)`` is equivalent to ``a **= b``.

   .. versionadded:: 2.5


.. function:: irepeat(a, b)
              __irepeat__(a, b)

   .. deprecated:: 2.7
      Use :func:`__imul__` instead.

   ``a = irepeat(a, b)`` is equivalent to ``a *= b`` where *a* is a sequence and
   *b* is an integer.

   .. versionadded:: 2.5


.. function:: irshift(a, b)
              __irshift__(a, b)

   ``a = irshift(a, b)`` is equivalent to ``a >>= b``.

   .. versionadded:: 2.5


.. function:: isub(a, b)
              __isub__(a, b)

   ``a = isub(a, b)`` is equivalent to ``a -= b``.

   .. versionadded:: 2.5


.. function:: itruediv(a, b)
              __itruediv__(a, b)

   ``a = itruediv(a, b)`` is equivalent to ``a /= b`` when ``__future__.division``
   is in effect.

   .. versionadded:: 2.5


.. function:: ixor(a, b)
              __ixor__(a, b)

   ``a = ixor(a, b)`` is equivalent to ``a ^= b``.

   .. versionadded:: 2.5


The :mod:`operator` module also defines a few predicates to test the type of
objects; however, these are not all reliable.  It is preferable to test
abstract base classes instead (see :mod:`collections` and
:mod:`numbers` for details).

.. function:: isCallable(obj)

   .. deprecated:: 2.0
      Use ``isinstance(x, collections.Callable)`` instead.

   Returns true if the object *obj* can be called like a function, otherwise it
   returns false.  True is returned for functions, bound and unbound methods, class
   objects, and instance objects which support the :meth:`__call__` method.


.. function:: isMappingType(obj)

   .. deprecated:: 2.7
      Use ``isinstance(x, collections.Mapping)`` instead.

   Returns true if the object *obj* supports the mapping interface. This is true for
   dictionaries and all instance objects defining :meth:`__getitem__`.


.. function:: isNumberType(obj)

   .. deprecated:: 2.7
      Use ``isinstance(x, numbers.Number)`` instead.

   Returns true if the object *obj* represents a number.  This is true for all
   numeric types implemented in C.


.. function:: isSequenceType(obj)

   .. deprecated:: 2.7
      Use ``isinstance(x, collections.Sequence)`` instead.

   Returns true if the object *obj* supports the sequence protocol. This returns true
   for all objects which define sequence methods in C, and for all instance objects
   defining :meth:`__getitem__`.


The :mod:`operator` module also defines tools for generalized attribute and item
lookups.  These are useful for making fast field extractors as arguments for
:func:`map`, :func:`sorted`, :meth:`itertools.groupby`, or other functions that
expect a function argument.


.. function:: attrgetter(attr)
              attrgetter(*attrs)

   Return a callable object that fetches *attr* from its operand.
   If more than one attribute is requested, returns a tuple of attributes.
   The attribute names can also contain dots. For example:

   * After ``f = attrgetter('name')``, the call ``f(b)`` returns ``b.name``.

   * After ``f = attrgetter('name', 'date')``, the call ``f(b)`` returns
     ``(b.name, b.date)``.

   * After ``f = attrgetter('name.first', 'name.last')``, the call ``f(b)``
     returns ``(b.name.first, b.name.last)``.

   Equivalent to::

      def attrgetter(*items):
          if len(items) == 1:
              attr = items[0]
              def g(obj):
                  return resolve_attr(obj, attr)
          else:
              def g(obj):
                  return tuple(resolve_attr(obj, attr) for attr in items)
          return g

      def resolve_attr(obj, attr):
          for name in attr.split("."):
              obj = getattr(obj, name)
          return obj


   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      Added support for multiple attributes.

   .. versionchanged:: 2.6
      Added support for dotted attributes.


.. function:: itemgetter(item)
              itemgetter(*items)

   Return a callable object that fetches *item* from its operand using the
   operand's :meth:`__getitem__` method.  If multiple items are specified,
   returns a tuple of lookup values.  For example:

   * After ``f = itemgetter(2)``, the call ``f(r)`` returns ``r[2]``.

   * After ``g = itemgetter(2, 5, 3)``, the call ``g(r)`` returns
     ``(r[2], r[5], r[3])``.

   Equivalent to::

      def itemgetter(*items):
          if len(items) == 1:
              item = items[0]
              def g(obj):
                  return obj[item]
          else:
              def g(obj):
                  return tuple(obj[item] for item in items)
          return g

   The items can be any type accepted by the operand's :meth:`__getitem__`
   method.  Dictionaries accept any hashable value.  Lists, tuples, and
   strings accept an index or a slice:

      >>> itemgetter(1)('ABCDEFG')
      'B'
      >>> itemgetter(1,3,5)('ABCDEFG')
      ('B', 'D', 'F')
      >>> itemgetter(slice(2,None))('ABCDEFG')
      'CDEFG'

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      Added support for multiple item extraction.

   Example of using :func:`itemgetter` to retrieve specific fields from a
   tuple record:

      >>> inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
      >>> getcount = itemgetter(1)
      >>> map(getcount, inventory)
      [3, 2, 5, 1]
      >>> sorted(inventory, key=getcount)
      [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)]


.. function:: methodcaller(name[, args...])

   Return a callable object that calls the method *name* on its operand.  If
   additional arguments and/or keyword arguments are given, they will be given
   to the method as well.  For example:

   * After ``f = methodcaller('name')``, the call ``f(b)`` returns ``b.name()``.

   * After ``f = methodcaller('name', 'foo', bar=1)``, the call ``f(b)``
     returns ``b.name('foo', bar=1)``.

   Equivalent to::

      def methodcaller(name, *args, **kwargs):
          def caller(obj):
              return getattr(obj, name)(*args, **kwargs)
          return caller

   .. versionadded:: 2.6


.. _operator-map:

Mapping Operators to Functions
------------------------------

This table shows how abstract operations correspond to operator symbols in the
Python syntax and the functions in the :mod:`operator` module.

+-----------------------+-------------------------+---------------------------------------+
| Operation             | Syntax                  | Function                              |
+=======================+=========================+=======================================+
| Addition              | ``a + b``               | ``add(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Concatenation         | ``seq1 + seq2``         | ``concat(seq1, seq2)``                |
+-----------------------+-------------------------+---------------------------------------+
| Containment Test      | ``obj in seq``          | ``contains(seq, obj)``                |
+-----------------------+-------------------------+---------------------------------------+
| Division              | ``a / b``               | ``div(a, b)`` (without                |
|                       |                         | ``__future__.division``)              |
+-----------------------+-------------------------+---------------------------------------+
| Division              | ``a / b``               | ``truediv(a, b)`` (with               |
|                       |                         | ``__future__.division``)              |
+-----------------------+-------------------------+---------------------------------------+
| Division              | ``a // b``              | ``floordiv(a, b)``                    |
+-----------------------+-------------------------+---------------------------------------+
| Bitwise And           | ``a & b``               | ``and_(a, b)``                        |
+-----------------------+-------------------------+---------------------------------------+
| Bitwise Exclusive Or  | ``a ^ b``               | ``xor(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Bitwise Inversion     | ``~ a``                 | ``invert(a)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Bitwise Or            | ``a | b``               | ``or_(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Exponentiation        | ``a ** b``              | ``pow(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Identity              | ``a is b``              | ``is_(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Identity              | ``a is not b``          | ``is_not(a, b)``                      |
+-----------------------+-------------------------+---------------------------------------+
| Indexed Assignment    | ``obj[k] = v``          | ``setitem(obj, k, v)``                |
+-----------------------+-------------------------+---------------------------------------+
| Indexed Deletion      | ``del obj[k]``          | ``delitem(obj, k)``                   |
+-----------------------+-------------------------+---------------------------------------+
| Indexing              | ``obj[k]``              | ``getitem(obj, k)``                   |
+-----------------------+-------------------------+---------------------------------------+
| Left Shift            | ``a << b``              | ``lshift(a, b)``                      |
+-----------------------+-------------------------+---------------------------------------+
| Modulo                | ``a % b``               | ``mod(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Multiplication        | ``a * b``               | ``mul(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Negation (Arithmetic) | ``- a``                 | ``neg(a)``                            |
+-----------------------+-------------------------+---------------------------------------+
| Negation (Logical)    | ``not a``               | ``not_(a)``                           |
+-----------------------+-------------------------+---------------------------------------+
| Positive              | ``+ a``                 | ``pos(a)``                            |
+-----------------------+-------------------------+---------------------------------------+
| Right Shift           | ``a >> b``              | ``rshift(a, b)``                      |
+-----------------------+-------------------------+---------------------------------------+
| Sequence Repetition   | ``seq * i``             | ``repeat(seq, i)``                    |
+-----------------------+-------------------------+---------------------------------------+
| Slice Assignment      | ``seq[i:j] = values``   | ``setitem(seq, slice(i, j), values)`` |
+-----------------------+-------------------------+---------------------------------------+
| Slice Deletion        | ``del seq[i:j]``        | ``delitem(seq, slice(i, j))``         |
+-----------------------+-------------------------+---------------------------------------+
| Slicing               | ``seq[i:j]``            | ``getitem(seq, slice(i, j))``         |
+-----------------------+-------------------------+---------------------------------------+
| String Formatting     | ``s % obj``             | ``mod(s, obj)``                       |
+-----------------------+-------------------------+---------------------------------------+
| Subtraction           | ``a - b``               | ``sub(a, b)``                         |
+-----------------------+-------------------------+---------------------------------------+
| Truth Test            | ``obj``                 | ``truth(obj)``                        |
+-----------------------+-------------------------+---------------------------------------+
| Ordering              | ``a < b``               | ``lt(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+
| Ordering              | ``a <= b``              | ``le(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+
| Equality              | ``a == b``              | ``eq(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+
| Difference            | ``a != b``              | ``ne(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+
| Ordering              | ``a >= b``              | ``ge(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+
| Ordering              | ``a > b``               | ``gt(a, b)``                          |
+-----------------------+-------------------------+---------------------------------------+

PK	%�\�O��----&html/_sources/library/optparse.rst.txtnu�[���:mod:`optparse` --- Parser for command line options
===================================================

.. module:: optparse
   :synopsis: Command-line option parsing library.
   :deprecated:
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Greg Ward <gward@python.net>

.. versionadded:: 2.3

.. deprecated:: 2.7
   The :mod:`optparse` module is deprecated and will not be developed further;
   development will continue with the :mod:`argparse` module.

**Source code:** :source:`Lib/optparse.py`

--------------

:mod:`optparse` is a more convenient, flexible, and powerful library for parsing
command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
more declarative style of command-line parsing: you create an instance of
:class:`OptionParser`, populate it with options, and parse the command
line. :mod:`optparse` allows users to specify options in the conventional
GNU/POSIX syntax, and additionally generates usage and help messages for you.

Here's an example of using :mod:`optparse` in a simple script::

   from optparse import OptionParser
   ...
   parser = OptionParser()
   parser.add_option("-f", "--file", dest="filename",
                     help="write report to FILE", metavar="FILE")
   parser.add_option("-q", "--quiet",
                     action="store_false", dest="verbose", default=True,
                     help="don't print status messages to stdout")

   (options, args) = parser.parse_args()

With these few lines of code, users of your script can now do the "usual thing"
on the command-line, for example::

   <yourscript> --file=outfile -q

As it parses the command line, :mod:`optparse` sets attributes of the
``options`` object returned by :meth:`parse_args` based on user-supplied
command-line values.  When :meth:`parse_args` returns from parsing this command
line, ``options.filename`` will be ``"outfile"`` and ``options.verbose`` will be
``False``.  :mod:`optparse` supports both long and short options, allows short
options to be merged together, and allows options to be associated with their
arguments in a variety of ways.  Thus, the following command lines are all
equivalent to the above example::

   <yourscript> -f outfile --quiet
   <yourscript> --quiet --file outfile
   <yourscript> -q -foutfile
   <yourscript> -qfoutfile

Additionally, users can run one of  ::

   <yourscript> -h
   <yourscript> --help

and :mod:`optparse` will print out a brief summary of your script's options:

.. code-block:: text

   Usage: <yourscript> [options]

   Options:
     -h, --help            show this help message and exit
     -f FILE, --file=FILE  write report to FILE
     -q, --quiet           don't print status messages to stdout

where the value of *yourscript* is determined at runtime (normally from
``sys.argv[0]``).


.. _optparse-background:

Background
----------

:mod:`optparse` was explicitly designed to encourage the creation of programs
with straightforward, conventional command-line interfaces.  To that end, it
supports only the most common command-line syntax and semantics conventionally
used under Unix.  If you are unfamiliar with these conventions, read this
section to acquaint yourself with them.


.. _optparse-terminology:

Terminology
^^^^^^^^^^^

argument
   a string entered on the command-line, and passed by the shell to ``execl()``
   or ``execv()``.  In Python, arguments are elements of ``sys.argv[1:]``
   (``sys.argv[0]`` is the name of the program being executed).  Unix shells
   also use the term "word".

   It is occasionally desirable to substitute an argument list other than
   ``sys.argv[1:]``, so you should read "argument" as "an element of
   ``sys.argv[1:]``, or of some other list provided as a substitute for
   ``sys.argv[1:]``".

option
   an argument used to supply extra information to guide or customize the
   execution of a program.  There are many different syntaxes for options; the
   traditional Unix syntax is a hyphen ("-") followed by a single letter,
   e.g. ``-x`` or ``-F``.  Also, traditional Unix syntax allows multiple
   options to be merged into a single argument, e.g. ``-x -F`` is equivalent
   to ``-xF``.  The GNU project introduced ``--`` followed by a series of
   hyphen-separated words, e.g. ``--file`` or ``--dry-run``.  These are the
   only two option syntaxes provided by :mod:`optparse`.

   Some other option syntaxes that the world has seen include:

   * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
     as multiple options merged into a single argument)

   * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
     equivalent to the previous syntax, but they aren't usually seen in the same
     program)

   * a plus sign followed by a single letter, or a few letters, or a word, e.g.
     ``+f``, ``+rgb``

   * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
     ``/file``

   These option syntaxes are not supported by :mod:`optparse`, and they never
   will be.  This is deliberate: the first three are non-standard on any
   environment, and the last only makes sense if you're exclusively targeting
   VMS, MS-DOS, and/or Windows.

option argument
   an argument that follows an option, is closely associated with that option,
   and is consumed from the argument list when that option is. With
   :mod:`optparse`, option arguments may either be in a separate argument from
   their option:

   .. code-block:: text

      -f foo
      --file foo

   or included in the same argument:

   .. code-block:: text

      -ffoo
      --file=foo

   Typically, a given option either takes an argument or it doesn't. Lots of
   people want an "optional option arguments" feature, meaning that some options
   will take an argument if they see it, and won't if they don't.  This is
   somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
   an optional argument and ``-b`` is another option entirely, how do we
   interpret ``-ab``?  Because of this ambiguity, :mod:`optparse` does not
   support this feature.

positional argument
   something leftover in the argument list after options have been parsed, i.e.
   after options and their arguments have been parsed and removed from the
   argument list.

required option
   an option that must be supplied on the command-line; note that the phrase
   "required option" is self-contradictory in English.  :mod:`optparse` doesn't
   prevent you from implementing required options, but doesn't give you much
   help at it either.

For example, consider this hypothetical command-line::

   prog -v --report report.txt foo bar

``-v`` and ``--report`` are both options.  Assuming that ``--report``
takes one argument, ``report.txt`` is an option argument.  ``foo`` and
``bar`` are positional arguments.


.. _optparse-what-options-for:

What are options for?
^^^^^^^^^^^^^^^^^^^^^

Options are used to provide extra information to tune or customize the execution
of a program.  In case it wasn't clear, options are usually *optional*.  A
program should be able to run just fine with no options whatsoever.  (Pick a
random program from the Unix or GNU toolsets.  Can it run without any options at
all and still make sense?  The main exceptions are ``find``, ``tar``, and
``dd``\ ---all of which are mutant oddballs that have been rightly criticized
for their non-standard syntax and confusing interfaces.)

Lots of people want their programs to have "required options".  Think about it.
If it's required, then it's *not optional*!  If there is a piece of information
that your program absolutely requires in order to run successfully, that's what
positional arguments are for.

As an example of good command-line interface design, consider the humble ``cp``
utility, for copying files.  It doesn't make much sense to try to copy files
without supplying a destination and at least one source. Hence, ``cp`` fails if
you run it with no arguments.  However, it has a flexible, useful syntax that
does not require any options at all::

   cp SOURCE DEST
   cp SOURCE ... DEST-DIR

You can get pretty far with just that.  Most ``cp`` implementations provide a
bunch of options to tweak exactly how the files are copied: you can preserve
mode and modification time, avoid following symlinks, ask before clobbering
existing files, etc.  But none of this distracts from the core mission of
``cp``, which is to copy either one file to another, or several files to another
directory.


.. _optparse-what-positional-arguments-for:

What are positional arguments for?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Positional arguments are for those pieces of information that your program
absolutely, positively requires to run.

A good user interface should have as few absolute requirements as possible.  If
your program requires 17 distinct pieces of information in order to run
successfully, it doesn't much matter *how* you get that information from the
user---most people will give up and walk away before they successfully run the
program.  This applies whether the user interface is a command-line, a
configuration file, or a GUI: if you make that many demands on your users, most
of them will simply give up.

In short, try to minimize the amount of information that users are absolutely
required to supply---use sensible defaults whenever possible.  Of course, you
also want to make your programs reasonably flexible.  That's what options are
for.  Again, it doesn't matter if they are entries in a config file, widgets in
the "Preferences" dialog of a GUI, or command-line options---the more options
you implement, the more flexible your program is, and the more complicated its
implementation becomes.  Too much flexibility has drawbacks as well, of course;
too many options can overwhelm users and make your code much harder to maintain.


.. _optparse-tutorial:

Tutorial
--------

While :mod:`optparse` is quite flexible and powerful, it's also straightforward
to use in most cases.  This section covers the code patterns that are common to
any :mod:`optparse`\ -based program.

First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance::

   from optparse import OptionParser
   ...
   parser = OptionParser()

Then you can start defining options.  The basic syntax is::

   parser.add_option(opt_str, ...,
                     attr=value, ...)

Each option has one or more option strings, such as ``-f`` or ``--file``,
and several option attributes that tell :mod:`optparse` what to expect and what
to do when it encounters that option on the command line.

Typically, each option will have one short option string and one long option
string, e.g.::

   parser.add_option("-f", "--file", ...)

You're free to define as many short option strings and as many long option
strings as you like (including zero), as long as there is at least one option
string overall.

The option strings passed to :meth:`OptionParser.add_option` are effectively
labels for the
option defined by that call.  For brevity, we will frequently refer to
*encountering an option* on the command line; in reality, :mod:`optparse`
encounters *option strings* and looks up options from them.

Once all of your options are defined, instruct :mod:`optparse` to parse your
program's command line::

   (options, args) = parser.parse_args()

(If you like, you can pass a custom argument list to :meth:`parse_args`, but
that's rarely necessary: by default it uses ``sys.argv[1:]``.)

:meth:`parse_args` returns two values:

* ``options``, an object containing values for all of your options---e.g. if
  ``--file`` takes a single string argument, then ``options.file`` will be the
  filename supplied by the user, or ``None`` if the user did not supply that
  option

* ``args``, the list of positional arguments leftover after parsing options

This tutorial section only covers the four most important option attributes:
:attr:`~Option.action`, :attr:`~Option.type`, :attr:`~Option.dest`
(destination), and :attr:`~Option.help`. Of these, :attr:`~Option.action` is the
most fundamental.


.. _optparse-understanding-option-actions:

Understanding option actions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Actions tell :mod:`optparse` what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into :mod:`optparse`;
adding new actions is an advanced topic covered in section
:ref:`optparse-extending-optparse`.  Most actions tell :mod:`optparse` to store
a value in some variable---for example, take a string from the command line and
store it in an attribute of ``options``.

If you don't specify an option action, :mod:`optparse` defaults to ``store``.


.. _optparse-store-action:

The store action
^^^^^^^^^^^^^^^^

The most common option action is ``store``, which tells :mod:`optparse` to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.

For example::

   parser.add_option("-f", "--file",
                     action="store", type="string", dest="filename")

Now let's make up a fake command line and ask :mod:`optparse` to parse it::

   args = ["-f", "foo.txt"]
   (options, args) = parser.parse_args(args)

When :mod:`optparse` sees the option string ``-f``, it consumes the next
argument, ``foo.txt``, and stores it in ``options.filename``.  So, after this
call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.

Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
Here's an option that expects an integer argument::

   parser.add_option("-n", type="int", dest="num")

Note that this option has no long option string, which is perfectly acceptable.
Also, there's no explicit action, since the default is ``store``.

Let's parse another fake command-line.  This time, we'll jam the option argument
right up against the option: since ``-n42`` (one argument) is equivalent to
``-n 42`` (two arguments), the code ::

   (options, args) = parser.parse_args(["-n42"])
   print options.num

will print ``42``.

If you don't specify a type, :mod:`optparse` assumes ``string``.  Combined with
the fact that the default action is ``store``, that means our first example can
be a lot shorter::

   parser.add_option("-f", "--file", dest="filename")

If you don't supply a destination, :mod:`optparse` figures out a sensible
default from the option strings: if the first long option string is
``--foo-bar``, then the default destination is ``foo_bar``.  If there are no
long option strings, :mod:`optparse` looks at the first short option string: the
default destination for ``-f`` is ``f``.

:mod:`optparse` also includes built-in ``long`` and ``complex`` types.  Adding
types is covered in section :ref:`optparse-extending-optparse`.


.. _optparse-handling-boolean-options:

Handling boolean (flag) options
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Flag options---set a variable to true or false when a particular option is seen
---are quite common.  :mod:`optparse` supports them with two separate actions,
``store_true`` and ``store_false``.  For example, you might have a ``verbose``
flag that is turned on with ``-v`` and off with ``-q``::

   parser.add_option("-v", action="store_true", dest="verbose")
   parser.add_option("-q", action="store_false", dest="verbose")

Here we have two different options with the same destination, which is perfectly
OK.  (It just means you have to be a bit careful when setting default values---
see below.)

When :mod:`optparse` encounters ``-v`` on the command line, it sets
``options.verbose`` to ``True``; when it encounters ``-q``,
``options.verbose`` is set to ``False``.


.. _optparse-other-actions:

Other actions
^^^^^^^^^^^^^

Some other actions supported by :mod:`optparse` are:

``"store_const"``
   store a constant value

``"append"``
   append this option's argument to a list

``"count"``
   increment a counter by one

``"callback"``
   call a specified function

These are covered in section :ref:`optparse-reference-guide`, Reference Guide
and section :ref:`optparse-option-callbacks`.


.. _optparse-default-values:

Default values
^^^^^^^^^^^^^^

All of the above examples involve setting some variable (the "destination") when
certain command-line options are seen.  What happens if those options are never
seen?  Since we didn't supply any defaults, they are all set to ``None``.  This
is usually fine, but sometimes you want more control.  :mod:`optparse` lets you
supply a default value for each destination, which is assigned before the
command line is parsed.

First, consider the verbose/quiet example.  If we want :mod:`optparse` to set
``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::

   parser.add_option("-v", action="store_true", dest="verbose", default=True)
   parser.add_option("-q", action="store_false", dest="verbose")

Since default values apply to the *destination* rather than to any particular
option, and these two options happen to have the same destination, this is
exactly equivalent::

   parser.add_option("-v", action="store_true", dest="verbose")
   parser.add_option("-q", action="store_false", dest="verbose", default=True)

Consider this::

   parser.add_option("-v", action="store_true", dest="verbose", default=False)
   parser.add_option("-q", action="store_false", dest="verbose", default=True)

Again, the default value for ``verbose`` will be ``True``: the last default
value supplied for any particular destination is the one that counts.

A clearer way to specify default values is the :meth:`set_defaults` method of
OptionParser, which you can call at any time before calling :meth:`parse_args`::

   parser.set_defaults(verbose=True)
   parser.add_option(...)
   (options, args) = parser.parse_args()

As before, the last value specified for a given option destination is the one
that counts.  For clarity, try to use one method or the other of setting default
values, not both.


.. _optparse-generating-help:

Generating help
^^^^^^^^^^^^^^^

:mod:`optparse`'s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you have to do
is supply a :attr:`~Option.help` value for each option, and optionally a short
usage message for your whole program.  Here's an OptionParser populated with
user-friendly (documented) options::

   usage = "usage: %prog [options] arg1 arg2"
   parser = OptionParser(usage=usage)
   parser.add_option("-v", "--verbose",
                     action="store_true", dest="verbose", default=True,
                     help="make lots of noise [default]")
   parser.add_option("-q", "--quiet",
                     action="store_false", dest="verbose",
                     help="be vewwy quiet (I'm hunting wabbits)")
   parser.add_option("-f", "--filename",
                     metavar="FILE", help="write output to FILE")
   parser.add_option("-m", "--mode",
                     default="intermediate",
                     help="interaction mode: novice, intermediate, "
                          "or expert [default: %default]")

If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
command-line, or if you just call :meth:`parser.print_help`, it prints the
following to standard output:

.. code-block:: text

   Usage: <yourscript> [options] arg1 arg2

   Options:
     -h, --help            show this help message and exit
     -v, --verbose         make lots of noise [default]
     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                           expert [default: intermediate]

(If the help output is triggered by a help option, :mod:`optparse` exits after
printing the help text.)

There's a lot going on here to help :mod:`optparse` generate the best possible
help message:

* the script defines its own usage message::

     usage = "usage: %prog [options] arg1 arg2"

  :mod:`optparse` expands ``%prog`` in the usage string to the name of the
  current program, i.e. ``os.path.basename(sys.argv[0])``.  The expanded string
  is then printed before the detailed option help.

  If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
  default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
  take any positional arguments.

* every option defines a help string, and doesn't worry about line-wrapping---
  :mod:`optparse` takes care of wrapping lines and making the help output look
  good.

* options that take a value indicate this fact in their automatically-generated
  help message, e.g. for the "mode" option::

     -m MODE, --mode=MODE

  Here, "MODE" is called the meta-variable: it stands for the argument that the
  user is expected to supply to ``-m``/``--mode``.  By default,
  :mod:`optparse` converts the destination variable name to uppercase and uses
  that for the meta-variable.  Sometimes, that's not what you want---for
  example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
  resulting in this automatically-generated option description::

     -f FILE, --filename=FILE

  This is important for more than just saving space, though: the manually
  written help text uses the meta-variable ``FILE`` to clue the user in that
  there's a connection between the semi-formal syntax ``-f FILE`` and the informal
  semantic description "write output to FILE". This is a simple but effective
  way to make your help text a lot clearer and more useful for end users.

.. versionadded:: 2.4
   Options that have a default value can include ``%default`` in the help
   string---\ :mod:`optparse` will replace it with :func:`str` of the option's
   default value.  If an option has no default value (or the default value is
   ``None``), ``%default`` expands to ``none``.

Grouping Options
++++++++++++++++

When dealing with many options, it is convenient to group these options for
better help output.  An :class:`OptionParser` can contain several option groups,
each of which can contain several options.

An option group is obtained using the class :class:`OptionGroup`:

.. class:: OptionGroup(parser, title, description=None)

   where

   * parser is the :class:`OptionParser` instance the group will be insterted in
     to
   * title is the group title
   * description, optional, is a long description of the group

:class:`OptionGroup` inherits from :class:`OptionContainer` (like
:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
an option to the group.

Once all the options are declared, using the :class:`OptionParser` method
:meth:`add_option_group` the group is added to the previously defined parser.

Continuing with the parser defined in the previous section, adding an
:class:`OptionGroup` to a parser is easy::

    group = OptionGroup(parser, "Dangerous Options",
                        "Caution: use these options at your own risk.  "
                        "It is believed that some of them bite.")
    group.add_option("-g", action="store_true", help="Group option.")
    parser.add_option_group(group)

This would result in the following help output:

.. code-block:: text

   Usage: <yourscript> [options] arg1 arg2

   Options:
     -h, --help            show this help message and exit
     -v, --verbose         make lots of noise [default]
     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                           expert [default: intermediate]

     Dangerous Options:
       Caution: use these options at your own risk.  It is believed that some
       of them bite.

       -g                  Group option.

A bit more complete example might involve using more than one group: still
extending the previous example::

    group = OptionGroup(parser, "Dangerous Options",
                        "Caution: use these options at your own risk.  "
                        "It is believed that some of them bite.")
    group.add_option("-g", action="store_true", help="Group option.")
    parser.add_option_group(group)

    group = OptionGroup(parser, "Debug Options")
    group.add_option("-d", "--debug", action="store_true",
                     help="Print debug information")
    group.add_option("-s", "--sql", action="store_true",
                     help="Print all SQL statements executed")
    group.add_option("-e", action="store_true", help="Print every action done")
    parser.add_option_group(group)

that results in the following output:

.. code-block:: text

   Usage: <yourscript> [options] arg1 arg2

   Options:
     -h, --help            show this help message and exit
     -v, --verbose         make lots of noise [default]
     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
     -f FILE, --filename=FILE
                           write output to FILE
     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                           [default: intermediate]

     Dangerous Options:
       Caution: use these options at your own risk.  It is believed that some
       of them bite.

       -g                  Group option.

     Debug Options:
       -d, --debug         Print debug information
       -s, --sql           Print all SQL statements executed
       -e                  Print every action done

Another interesting method, in particular when working programmatically with
option groups is:

.. method:: OptionParser.get_option_group(opt_str)

   Return the :class:`OptionGroup` to which the short or long option
   string *opt_str* (e.g. ``'-o'`` or ``'--option'``) belongs. If
   there's no such :class:`OptionGroup`, return ``None``.

.. _optparse-printing-version-string:

Printing a version string
^^^^^^^^^^^^^^^^^^^^^^^^^

Similar to the brief usage string, :mod:`optparse` can also print a version
string for your program.  You have to supply the string as the ``version``
argument to OptionParser::

   parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")

``%prog`` is expanded just like it is in ``usage``.  Apart from that,
``version`` can contain anything you like.  When you supply it, :mod:`optparse`
automatically adds a ``--version`` option to your parser. If it encounters
this option on the command line, it expands your ``version`` string (by
replacing ``%prog``), prints it to stdout, and exits.

For example, if your script is called ``/usr/bin/foo``:

.. code-block:: shell-session

   $ /usr/bin/foo --version
   foo 1.0

The following two methods can be used to print and get the ``version`` string:

.. method:: OptionParser.print_version(file=None)

   Print the version message for the current program (``self.version``) to
   *file* (default stdout).  As with :meth:`print_usage`, any occurrence
   of ``%prog`` in ``self.version`` is replaced with the name of the current
   program.  Does nothing if ``self.version`` is empty or undefined.

.. method:: OptionParser.get_version()

   Same as :meth:`print_version` but returns the version string instead of
   printing it.


.. _optparse-how-optparse-handles-errors:

How :mod:`optparse` handles errors
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

There are two broad classes of errors that :mod:`optparse` has to worry about:
programmer errors and user errors.  Programmer errors are usually erroneous
calls to :func:`OptionParser.add_option`, e.g. invalid option strings, unknown
option attributes, missing option attributes, etc.  These are dealt with in the
usual way: raise an exception (either :exc:`optparse.OptionError` or
:exc:`TypeError`) and let the program crash.

Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is.  :mod:`optparse` can automatically detect
some user errors, such as bad option arguments (passing ``-n 4x`` where
``-n`` takes an integer argument), missing arguments (``-n`` at the end
of the command line, where ``-n`` takes an argument of any type).  Also,
you can call :func:`OptionParser.error` to signal an application-defined error
condition::

   (options, args) = parser.parse_args()
   ...
   if options.a and options.b:
       parser.error("options -a and -b are mutually exclusive")

In either case, :mod:`optparse` handles the error the same way: it prints the
program's usage message and an error message to standard error and exits with
error status 2.

Consider the first example above, where the user passes ``4x`` to an option
that takes an integer:

.. code-block:: shell-session

   $ /usr/bin/foo -n 4x
   Usage: foo [options]

   foo: error: option -n: invalid integer value: '4x'

Or, where the user fails to pass a value at all:

.. code-block:: shell-session

   $ /usr/bin/foo -n
   Usage: foo [options]

   foo: error: -n option requires an argument

:mod:`optparse`\ -generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
:func:`OptionParser.error` from your application code.

If :mod:`optparse`'s default error-handling behaviour does not suit your needs,
you'll need to subclass OptionParser and override its :meth:`~OptionParser.exit`
and/or :meth:`~OptionParser.error` methods.


.. _optparse-putting-it-all-together:

Putting it all together
^^^^^^^^^^^^^^^^^^^^^^^

Here's what :mod:`optparse`\ -based scripts usually look like::

   from optparse import OptionParser
   ...
   def main():
       usage = "usage: %prog [options] arg"
       parser = OptionParser(usage)
       parser.add_option("-f", "--file", dest="filename",
                         help="read data from FILENAME")
       parser.add_option("-v", "--verbose",
                         action="store_true", dest="verbose")
       parser.add_option("-q", "--quiet",
                         action="store_false", dest="verbose")
       ...
       (options, args) = parser.parse_args()
       if len(args) != 1:
           parser.error("incorrect number of arguments")
       if options.verbose:
           print "reading %s..." % options.filename
       ...

   if __name__ == "__main__":
       main()


.. _optparse-reference-guide:

Reference Guide
---------------


.. _optparse-creating-parser:

Creating the parser
^^^^^^^^^^^^^^^^^^^

The first step in using :mod:`optparse` is to create an OptionParser instance.

.. class:: OptionParser(...)

   The OptionParser constructor has no required arguments, but a number of
   optional keyword arguments.  You should always pass them as keyword
   arguments, i.e. do not rely on the order in which the arguments are declared.

   ``usage`` (default: ``"%prog [options]"``)
      The usage summary to print when your program is run incorrectly or with a
      help option.  When :mod:`optparse` prints the usage string, it expands
      ``%prog`` to ``os.path.basename(sys.argv[0])`` (or to ``prog`` if you
      passed that keyword argument).  To suppress a usage message, pass the
      special value :data:`optparse.SUPPRESS_USAGE`.

   ``option_list`` (default: ``[]``)
      A list of Option objects to populate the parser with.  The options in
      ``option_list`` are added after any options in ``standard_option_list`` (a
      class attribute that may be set by OptionParser subclasses), but before
      any version or help options. Deprecated; use :meth:`add_option` after
      creating the parser instead.

   ``option_class`` (default: optparse.Option)
      Class to use when adding options to the parser in :meth:`add_option`.

   ``version`` (default: ``None``)
      A version string to print when the user supplies a version option. If you
      supply a true value for ``version``, :mod:`optparse` automatically adds a
      version option with the single option string ``--version``.  The
      substring ``%prog`` is expanded the same as for ``usage``.

   ``conflict_handler`` (default: ``"error"``)
      Specifies what to do when options with conflicting option strings are
      added to the parser; see section
      :ref:`optparse-conflicts-between-options`.

   ``description`` (default: ``None``)
      A paragraph of text giving a brief overview of your program.
      :mod:`optparse` reformats this paragraph to fit the current terminal width
      and prints it when the user requests help (after ``usage``, but before the
      list of options).

   ``formatter`` (default: a new :class:`IndentedHelpFormatter`)
      An instance of optparse.HelpFormatter that will be used for printing help
      text.  :mod:`optparse` provides two concrete classes for this purpose:
      IndentedHelpFormatter and TitledHelpFormatter.

   ``add_help_option`` (default: ``True``)
      If true, :mod:`optparse` will add a help option (with option strings ``-h``
      and ``--help``) to the parser.

   ``prog``
      The string to use when expanding ``%prog`` in ``usage`` and ``version``
      instead of ``os.path.basename(sys.argv[0])``.

   ``epilog`` (default: ``None``)
      A paragraph of help text to print after the option help.

.. _optparse-populating-parser:

Populating the parser
^^^^^^^^^^^^^^^^^^^^^

There are several ways to populate the parser with options.  The preferred way
is by using :meth:`OptionParser.add_option`, as shown in section
:ref:`optparse-tutorial`.  :meth:`add_option` can be called in one of two ways:

* pass it an Option instance (as returned by :func:`make_option`)

* pass it any combination of positional and keyword arguments that are
  acceptable to :func:`make_option` (i.e., to the Option constructor), and it
  will create the Option instance for you

The other alternative is to pass a list of pre-constructed Option instances to
the OptionParser constructor, as in::

   option_list = [
       make_option("-f", "--filename",
                   action="store", type="string", dest="filename"),
       make_option("-q", "--quiet",
                   action="store_false", dest="verbose"),
       ]
   parser = OptionParser(option_list=option_list)

(:func:`make_option` is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version of
:mod:`optparse` may split Option into several classes, and :func:`make_option`
will pick the right class to instantiate.  Do not instantiate Option directly.)


.. _optparse-defining-options:

Defining options
^^^^^^^^^^^^^^^^

Each Option instance represents a set of synonymous command-line option strings,
e.g. ``-f`` and ``--file``.  You can specify any number of short or
long option strings, but you must specify at least one overall option string.

The canonical way to create an :class:`Option` instance is with the
:meth:`add_option` method of :class:`OptionParser`.

.. method:: OptionParser.add_option(option)
            OptionParser.add_option(*opt_str, attr=value, ...)

   To define an option with only a short option string::

      parser.add_option("-f", attr=value, ...)

   And to define an option with only a long option string::

      parser.add_option("--foo", attr=value, ...)

   The keyword arguments define attributes of the new Option object.  The most
   important option attribute is :attr:`~Option.action`, and it largely
   determines which other attributes are relevant or required.  If you pass
   irrelevant option attributes, or fail to pass required ones, :mod:`optparse`
   raises an :exc:`OptionError` exception explaining your mistake.

   An option's *action* determines what :mod:`optparse` does when it encounters
   this option on the command-line.  The standard option actions hard-coded into
   :mod:`optparse` are:

   ``"store"``
      store this option's argument (default)

   ``"store_const"``
      store a constant value

   ``"store_true"``
      store a true value

   ``"store_false"``
      store a false value

   ``"append"``
      append this option's argument to a list

   ``"append_const"``
      append a constant value to a list

   ``"count"``
      increment a counter by one

   ``"callback"``
      call a specified function

   ``"help"``
      print a usage message including all options and the documentation for them

   (If you don't supply an action, the default is ``"store"``.  For this action,
   you may also supply :attr:`~Option.type` and :attr:`~Option.dest` option
   attributes; see :ref:`optparse-standard-option-actions`.)

As you can see, most actions involve storing or updating a value somewhere.
:mod:`optparse` always creates a special object for this, conventionally called
``options`` (it happens to be an instance of :class:`optparse.Values`).  Option
arguments (and various other values) are stored as attributes of this object,
according to the :attr:`~Option.dest` (destination) option attribute.

For example, when you call ::

   parser.parse_args()

one of the first things :mod:`optparse` does is create the ``options`` object::

   options = Values()

If one of the options in this parser is defined with ::

   parser.add_option("-f", "--file", action="store", type="string", dest="filename")

and the command-line being parsed includes any of the following::

   -ffoo
   -f foo
   --file=foo
   --file foo

then :mod:`optparse`, on seeing this option, will do the equivalent of ::

   options.filename = "foo"

The :attr:`~Option.type` and :attr:`~Option.dest` option attributes are almost
as important as :attr:`~Option.action`, but :attr:`~Option.action` is the only
one that makes sense for *all* options.


.. _optparse-option-attributes:

Option attributes
^^^^^^^^^^^^^^^^^

The following option attributes may be passed as keyword arguments to
:meth:`OptionParser.add_option`.  If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
:mod:`optparse` raises :exc:`OptionError`.

.. attribute:: Option.action

   (default: ``"store"``)

   Determines :mod:`optparse`'s behaviour when this option is seen on the
   command line; the available options are documented :ref:`here
   <optparse-standard-option-actions>`.

.. attribute:: Option.type

   (default: ``"string"``)

   The argument type expected by this option (e.g., ``"string"`` or ``"int"``);
   the available option types are documented :ref:`here
   <optparse-standard-option-types>`.

.. attribute:: Option.dest

   (default: derived from option strings)

   If the option's action implies writing or modifying a value somewhere, this
   tells :mod:`optparse` where to write it: :attr:`~Option.dest` names an
   attribute of the ``options`` object that :mod:`optparse` builds as it parses
   the command line.

.. attribute:: Option.default

   The value to use for this option's destination if the option is not seen on
   the command line.  See also :meth:`OptionParser.set_defaults`.

.. attribute:: Option.nargs

   (default: 1)

   How many arguments of type :attr:`~Option.type` should be consumed when this
   option is seen.  If > 1, :mod:`optparse` will store a tuple of values to
   :attr:`~Option.dest`.

.. attribute:: Option.const

   For actions that store a constant value, the constant value to store.

.. attribute:: Option.choices

   For options of type ``"choice"``, the list of strings the user may choose
   from.

.. attribute:: Option.callback

   For options with action ``"callback"``, the callable to call when this option
   is seen.  See section :ref:`optparse-option-callbacks` for detail on the
   arguments passed to the callable.

.. attribute:: Option.callback_args
               Option.callback_kwargs

   Additional positional and keyword arguments to pass to ``callback`` after the
   four standard callback arguments.

.. attribute:: Option.help

   Help text to print for this option when listing all available options after
   the user supplies a :attr:`~Option.help` option (such as ``--help``).  If
   no help text is supplied, the option will be listed without help text.  To
   hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.

.. attribute:: Option.metavar

   (default: derived from option strings)

   Stand-in for the option argument(s) to use when printing help text.  See
   section :ref:`optparse-tutorial` for an example.


.. _optparse-standard-option-actions:

Standard option actions
^^^^^^^^^^^^^^^^^^^^^^^

The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide :mod:`optparse`'s behaviour; a few have required attributes, which you
must specify for any option using that action.

* ``"store"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
  :attr:`~Option.nargs`, :attr:`~Option.choices`]

  The option must be followed by an argument, which is converted to a value
  according to :attr:`~Option.type` and stored in :attr:`~Option.dest`.  If
  :attr:`~Option.nargs` > 1, multiple arguments will be consumed from the
  command line; all will be converted according to :attr:`~Option.type` and
  stored to :attr:`~Option.dest` as a tuple.  See the
  :ref:`optparse-standard-option-types` section.

  If :attr:`~Option.choices` is supplied (a list or tuple of strings), the type
  defaults to ``"choice"``.

  If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.

  If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
  from the first long option string (e.g., ``--foo-bar`` implies
  ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
  destination from the first short option string (e.g., ``-f`` implies ``f``).

  Example::

     parser.add_option("-f")
     parser.add_option("-p", type="float", nargs=3, dest="point")

  As it parses the command line ::

     -f foo.txt -p 1 -3.5 4 -fbar.txt

  :mod:`optparse` will set ::

     options.f = "foo.txt"
     options.point = (1.0, -3.5, 4.0)
     options.f = "bar.txt"

* ``"store_const"`` [required: :attr:`~Option.const`; relevant:
  :attr:`~Option.dest`]

  The value :attr:`~Option.const` is stored in :attr:`~Option.dest`.

  Example::

     parser.add_option("-q", "--quiet",
                       action="store_const", const=0, dest="verbose")
     parser.add_option("-v", "--verbose",
                       action="store_const", const=1, dest="verbose")
     parser.add_option("--noisy",
                       action="store_const", const=2, dest="verbose")

  If ``--noisy`` is seen, :mod:`optparse` will set  ::

     options.verbose = 2

* ``"store_true"`` [relevant: :attr:`~Option.dest`]

  A special case of ``"store_const"`` that stores a true value to
  :attr:`~Option.dest`.

* ``"store_false"`` [relevant: :attr:`~Option.dest`]

  Like ``"store_true"``, but stores a false value.

  Example::

     parser.add_option("--clobber", action="store_true", dest="clobber")
     parser.add_option("--no-clobber", action="store_false", dest="clobber")

* ``"append"`` [relevant: :attr:`~Option.type`, :attr:`~Option.dest`,
  :attr:`~Option.nargs`, :attr:`~Option.choices`]

  The option must be followed by an argument, which is appended to the list in
  :attr:`~Option.dest`.  If no default value for :attr:`~Option.dest` is
  supplied, an empty list is automatically created when :mod:`optparse` first
  encounters this option on the command-line.  If :attr:`~Option.nargs` > 1,
  multiple arguments are consumed, and a tuple of length :attr:`~Option.nargs`
  is appended to :attr:`~Option.dest`.

  The defaults for :attr:`~Option.type` and :attr:`~Option.dest` are the same as
  for the ``"store"`` action.

  Example::

     parser.add_option("-t", "--tracks", action="append", type="int")

  If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
  of::

     options.tracks = []
     options.tracks.append(int("3"))

  If, a little later on, ``--tracks=4`` is seen, it does::

     options.tracks.append(int("4"))

  The ``append`` action calls the ``append`` method on the current value of the
  option.  This means that any default value specified must have an ``append``
  method.  It also means that if the default value is non-empty, the default
  elements will be present in the parsed value for the option, with any values
  from the command line appended after those default values::

     >>> parser.add_option("--files", action="append", default=['~/.mypkg/defaults'])
     >>> opts, args = parser.parse_args(['--files', 'overrides.mypkg'])
     >>> opts.files
     ['~/.mypkg/defaults', 'overrides.mypkg']

* ``"append_const"`` [required: :attr:`~Option.const`; relevant:
  :attr:`~Option.dest`]

  Like ``"store_const"``, but the value :attr:`~Option.const` is appended to
  :attr:`~Option.dest`; as with ``"append"``, :attr:`~Option.dest` defaults to
  ``None``, and an empty list is automatically created the first time the option
  is encountered.

* ``"count"`` [relevant: :attr:`~Option.dest`]

  Increment the integer stored at :attr:`~Option.dest`.  If no default value is
  supplied, :attr:`~Option.dest` is set to zero before being incremented the
  first time.

  Example::

     parser.add_option("-v", action="count", dest="verbosity")

  The first time ``-v`` is seen on the command line, :mod:`optparse` does the
  equivalent of::

     options.verbosity = 0
     options.verbosity += 1

  Every subsequent occurrence of ``-v`` results in  ::

     options.verbosity += 1

* ``"callback"`` [required: :attr:`~Option.callback`; relevant:
  :attr:`~Option.type`, :attr:`~Option.nargs`, :attr:`~Option.callback_args`,
  :attr:`~Option.callback_kwargs`]

  Call the function specified by :attr:`~Option.callback`, which is called as ::

     func(option, opt_str, value, parser, *args, **kwargs)

  See section :ref:`optparse-option-callbacks` for more detail.

* ``"help"``

  Prints a complete help message for all the options in the current option
  parser.  The help message is constructed from the ``usage`` string passed to
  OptionParser's constructor and the :attr:`~Option.help` string passed to every
  option.

  If no :attr:`~Option.help` string is supplied for an option, it will still be
  listed in the help message.  To omit an option entirely, use the special value
  :data:`optparse.SUPPRESS_HELP`.

  :mod:`optparse` automatically adds a :attr:`~Option.help` option to all
  OptionParsers, so you do not normally need to create one.

  Example::

     from optparse import OptionParser, SUPPRESS_HELP

     # usually, a help option is added automatically, but that can
     # be suppressed using the add_help_option argument
     parser = OptionParser(add_help_option=False)

     parser.add_option("-h", "--help", action="help")
     parser.add_option("-v", action="store_true", dest="verbose",
                       help="Be moderately verbose")
     parser.add_option("--file", dest="filename",
                       help="Input file to read data from")
     parser.add_option("--secret", help=SUPPRESS_HELP)

  If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
  it will print something like the following help message to stdout (assuming
  ``sys.argv[0]`` is ``"foo.py"``):

  .. code-block:: text

     Usage: foo.py [options]

     Options:
       -h, --help        Show this help message and exit
       -v                Be moderately verbose
       --file=FILENAME   Input file to read data from

  After printing the help message, :mod:`optparse` terminates your process with
  ``sys.exit(0)``.

* ``"version"``

  Prints the version number supplied to the OptionParser to stdout and exits.
  The version number is actually formatted and printed by the
  ``print_version()`` method of OptionParser.  Generally only relevant if the
  ``version`` argument is supplied to the OptionParser constructor.  As with
  :attr:`~Option.help` options, you will rarely create ``version`` options,
  since :mod:`optparse` automatically adds them when needed.


.. _optparse-standard-option-types:

Standard option types
^^^^^^^^^^^^^^^^^^^^^

:mod:`optparse` has six built-in option types: ``"string"``, ``"int"``,
``"long"``, ``"choice"``, ``"float"`` and ``"complex"``.  If you need to add new
option types, see section :ref:`optparse-extending-optparse`.

Arguments to string options are not checked or converted in any way: the text on
the command line is stored in the destination (or passed to the callback) as-is.

Integer arguments (type ``"int"`` or ``"long"``) are parsed as follows:

* if the number starts with ``0x``, it is parsed as a hexadecimal number

* if the number starts with ``0``, it is parsed as an octal number

* if the number starts with ``0b``, it is parsed as a binary number

* otherwise, the number is parsed as a decimal number


The conversion is done by calling either :func:`int` or :func:`long` with the
appropriate base (2, 8, 10, or 16).  If this fails, so will :mod:`optparse`,
although with a more useful error message.

``"float"`` and ``"complex"`` option arguments are converted directly with
:func:`float` and :func:`complex`, with similar error-handling.

``"choice"`` options are a subtype of ``"string"`` options.  The
:attr:`~Option.choices` option attribute (a sequence of strings) defines the
set of allowed option arguments.  :func:`optparse.check_choice` compares
user-supplied option arguments against this master list and raises
:exc:`OptionValueError` if an invalid string is given.


.. _optparse-parsing-arguments:

Parsing arguments
^^^^^^^^^^^^^^^^^

The whole point of creating and populating an OptionParser is to call its
:meth:`parse_args` method::

   (options, args) = parser.parse_args(args=None, values=None)

where the input parameters are

``args``
   the list of arguments to process (default: ``sys.argv[1:]``)

``values``
   an :class:`optparse.Values` object to store option arguments in (default: a
   new instance of :class:`Values`) -- if you give an existing object, the
   option defaults will not be initialized on it

and the return values are

``options``
   the same object that was passed in as ``values``, or the optparse.Values
   instance created by :mod:`optparse`

``args``
   the leftover positional arguments after all options have been processed

The most common usage is to supply neither keyword argument.  If you supply
``values``, it will be modified with repeated :func:`setattr` calls (roughly one
for every option argument stored to an option destination) and returned by
:meth:`parse_args`.

If :meth:`parse_args` encounters any errors in the argument list, it calls the
OptionParser's :meth:`error` method with an appropriate end-user error message.
This ultimately terminates your process with an exit status of 2 (the
traditional Unix exit status for command-line errors).


.. _optparse-querying-manipulating-option-parser:

Querying and manipulating your option parser
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The default behavior of the option parser can be customized slightly, and you
can also poke around your option parser and see what's there.  OptionParser
provides several methods to help you out:

.. method:: OptionParser.disable_interspersed_args()

   Set parsing to stop on the first non-option.  For example, if ``-a`` and
   ``-b`` are both simple options that take no arguments, :mod:`optparse`
   normally accepts this syntax::

      prog -a arg1 -b arg2

   and treats it as equivalent to  ::

      prog -a -b arg1 arg2

   To disable this feature, call :meth:`disable_interspersed_args`.  This
   restores traditional Unix syntax, where option parsing stops with the first
   non-option argument.

   Use this if you have a command processor which runs another command which has
   options of its own and you want to make sure these options don't get
   confused.  For example, each command might have a different set of options.

.. method:: OptionParser.enable_interspersed_args()

   Set parsing to not stop on the first non-option, allowing interspersing
   switches with command arguments.  This is the default behavior.

.. method:: OptionParser.get_option(opt_str)

   Returns the Option instance with the option string *opt_str*, or ``None`` if
   no options have that option string.

.. method:: OptionParser.has_option(opt_str)

   Return true if the OptionParser has an option with option string *opt_str*
   (e.g., ``-q`` or ``--verbose``).

.. method:: OptionParser.remove_option(opt_str)

   If the :class:`OptionParser` has an option corresponding to *opt_str*, that
   option is removed.  If that option provided any other option strings, all of
   those option strings become invalid. If *opt_str* does not occur in any
   option belonging to this :class:`OptionParser`, raises :exc:`ValueError`.


.. _optparse-conflicts-between-options:

Conflicts between options
^^^^^^^^^^^^^^^^^^^^^^^^^

If you're not careful, it's easy to define options with conflicting option
strings::

   parser.add_option("-n", "--dry-run", ...)
   ...
   parser.add_option("-n", "--noisy", ...)

(This is particularly true if you've defined your own OptionParser subclass with
some standard options.)

Every time you add an option, :mod:`optparse` checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor::

   parser = OptionParser(..., conflict_handler=handler)

or with a separate call::

   parser.set_conflict_handler(handler)

The available conflict handlers are:

   ``"error"`` (default)
      assume option conflicts are a programming error and raise
      :exc:`OptionConflictError`

   ``"resolve"``
      resolve option conflicts intelligently (see below)


As an example, let's define an :class:`OptionParser` that resolves conflicts
intelligently and add conflicting options to it::

   parser = OptionParser(conflict_handler="resolve")
   parser.add_option("-n", "--dry-run", ..., help="do no harm")
   parser.add_option("-n", "--noisy", ..., help="be noisy")

At this point, :mod:`optparse` detects that a previously-added option is already
using the ``-n`` option string.  Since ``conflict_handler`` is ``"resolve"``,
it resolves the situation by removing ``-n`` from the earlier option's list of
option strings.  Now ``--dry-run`` is the only way for the user to activate
that option.  If the user asks for help, the help message will reflect that::

   Options:
     --dry-run     do no harm
     ...
     -n, --noisy   be noisy

It's possible to whittle away the option strings for a previously-added option
until there are none left, and the user has no way of invoking that option from
the command-line.  In that case, :mod:`optparse` removes that option completely,
so it doesn't show up in help text or anywhere else. Carrying on with our
existing OptionParser::

   parser.add_option("--dry-run", ..., help="new dry-run option")

At this point, the original ``-n``/``--dry-run`` option is no longer
accessible, so :mod:`optparse` removes it, leaving this help text::

   Options:
     ...
     -n, --noisy   be noisy
     --dry-run     new dry-run option


.. _optparse-cleanup:

Cleanup
^^^^^^^

OptionParser instances have several cyclic references.  This should not be a
problem for Python's garbage collector, but you may wish to break the cyclic
references explicitly by calling :meth:`~OptionParser.destroy` on your
OptionParser once you are done with it.  This is particularly useful in
long-running applications where large object graphs are reachable from your
OptionParser.


.. _optparse-other-methods:

Other methods
^^^^^^^^^^^^^

OptionParser supports several other public methods:

.. method:: OptionParser.set_usage(usage)

   Set the usage string according to the rules described above for the ``usage``
   constructor keyword argument.  Passing ``None`` sets the default usage
   string; use :data:`optparse.SUPPRESS_USAGE` to suppress a usage message.

.. method:: OptionParser.print_usage(file=None)

   Print the usage message for the current program (``self.usage``) to *file*
   (default stdout).  Any occurrence of the string ``%prog`` in ``self.usage``
   is replaced with the name of the current program.  Does nothing if
   ``self.usage`` is empty or not defined.

.. method:: OptionParser.get_usage()

   Same as :meth:`print_usage` but returns the usage string instead of
   printing it.

.. method:: OptionParser.set_defaults(dest=value, ...)

   Set default values for several option destinations at once.  Using
   :meth:`set_defaults` is the preferred way to set default values for options,
   since multiple options can share the same destination.  For example, if
   several "mode" options all set the same destination, any one of them can set
   the default, and the last one wins::

      parser.add_option("--advanced", action="store_const",
                        dest="mode", const="advanced",
                        default="novice")    # overridden below
      parser.add_option("--novice", action="store_const",
                        dest="mode", const="novice",
                        default="advanced")  # overrides above setting

   To avoid this confusion, use :meth:`set_defaults`::

      parser.set_defaults(mode="advanced")
      parser.add_option("--advanced", action="store_const",
                        dest="mode", const="advanced")
      parser.add_option("--novice", action="store_const",
                        dest="mode", const="novice")


.. _optparse-option-callbacks:

Option Callbacks
----------------

When :mod:`optparse`'s built-in actions and types aren't quite enough for your
needs, you have two choices: extend :mod:`optparse` or define a callback option.
Extending :mod:`optparse` is more general, but overkill for a lot of simple
cases.  Quite often a simple callback is all you need.

There are two steps to defining a callback option:

* define the option itself using the ``"callback"`` action

* write the callback; this is a function (or method) that takes at least four
  arguments, as described below


.. _optparse-defining-callback-option:

Defining a callback option
^^^^^^^^^^^^^^^^^^^^^^^^^^

As always, the easiest way to define a callback option is by using the
:meth:`OptionParser.add_option` method.  Apart from :attr:`~Option.action`, the
only option attribute you must specify is ``callback``, the function to call::

   parser.add_option("-c", action="callback", callback=my_callback)

``callback`` is a function (or other callable object), so you must have already
defined ``my_callback()`` when you create this callback option. In this simple
case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
which usually means that the option takes no arguments---the mere presence of
``-c`` on the command-line is all it needs to know.  In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments.  This is where writing callbacks gets tricky;
it's covered later in this section.

:mod:`optparse` always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
:attr:`~Option.callback_args` and :attr:`~Option.callback_kwargs`.  Thus, the
minimal callback function signature is::

   def my_callback(option, opt, value, parser):

The four arguments to a callback are described below.

There are several other option attributes that you can supply when you define a
callback option:

:attr:`~Option.type`
   has its usual meaning: as with the ``"store"`` or ``"append"`` actions, it
   instructs :mod:`optparse` to consume one argument and convert it to
   :attr:`~Option.type`.  Rather than storing the converted value(s) anywhere,
   though, :mod:`optparse` passes it to your callback function.

:attr:`~Option.nargs`
   also has its usual meaning: if it is supplied and > 1, :mod:`optparse` will
   consume :attr:`~Option.nargs` arguments, each of which must be convertible to
   :attr:`~Option.type`.  It then passes a tuple of converted values to your
   callback.

:attr:`~Option.callback_args`
   a tuple of extra positional arguments to pass to the callback

:attr:`~Option.callback_kwargs`
   a dictionary of extra keyword arguments to pass to the callback


.. _optparse-how-callbacks-called:

How callbacks are called
^^^^^^^^^^^^^^^^^^^^^^^^

All callbacks are called as follows::

   func(option, opt_str, value, parser, *args, **kwargs)

where

``option``
   is the Option instance that's calling the callback

``opt_str``
   is the option string seen on the command-line that's triggering the callback.
   (If an abbreviated long option was used, ``opt_str`` will be the full,
   canonical option string---e.g. if the user puts ``--foo`` on the
   command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
   ``"--foobar"``.)

``value``
   is the argument to this option seen on the command-line.  :mod:`optparse` will
   only expect an argument if :attr:`~Option.type` is set; the type of ``value`` will be
   the type implied by the option's type.  If :attr:`~Option.type` for this option is
   ``None`` (no argument expected), then ``value`` will be ``None``.  If :attr:`~Option.nargs`
   > 1, ``value`` will be a tuple of values of the appropriate type.

``parser``
   is the OptionParser instance driving the whole thing, mainly useful because
   you can access some other interesting data through its instance attributes:

   ``parser.largs``
      the current list of leftover arguments, ie. arguments that have been
      consumed but are neither options nor option arguments. Feel free to modify
      ``parser.largs``, e.g. by adding more arguments to it.  (This list will
      become ``args``, the second return value of :meth:`parse_args`.)

   ``parser.rargs``
      the current list of remaining arguments, ie. with ``opt_str`` and
      ``value`` (if applicable) removed, and only the arguments following them
      still there.  Feel free to modify ``parser.rargs``, e.g. by consuming more
      arguments.

   ``parser.values``
      the object where option values are by default stored (an instance of
      optparse.OptionValues).  This lets callbacks use the same mechanism as the
      rest of :mod:`optparse` for storing option values; you don't need to mess
      around with globals or closures.  You can also access or modify the
      value(s) of any options already encountered on the command-line.

``args``
   is a tuple of arbitrary positional arguments supplied via the
   :attr:`~Option.callback_args` option attribute.

``kwargs``
   is a dictionary of arbitrary keyword arguments supplied via
   :attr:`~Option.callback_kwargs`.


.. _optparse-raising-errors-in-callback:

Raising errors in a callback
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The callback function should raise :exc:`OptionValueError` if there are any
problems with the option or its argument(s).  :mod:`optparse` catches this and
terminates the program, printing the error message you supply to stderr.  Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.


.. _optparse-callback-example-1:

Callback example 1: trivial callback
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's an example of a callback option that takes no arguments, and simply
records that the option was seen::

   def record_foo_seen(option, opt_str, value, parser):
       parser.values.saw_foo = True

   parser.add_option("--foo", action="callback", callback=record_foo_seen)

Of course, you could do that with the ``"store_true"`` action.


.. _optparse-callback-example-2:

Callback example 2: check option order
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Here's a slightly more interesting example: record the fact that ``-a`` is
seen, but blow up if it comes after ``-b`` in the command-line.  ::

   def check_order(option, opt_str, value, parser):
       if parser.values.b:
           raise OptionValueError("can't use -a after -b")
       parser.values.a = 1
   ...
   parser.add_option("-a", action="callback", callback=check_order)
   parser.add_option("-b", action="store_true", dest="b")


.. _optparse-callback-example-3:

Callback example 3: check option order (generalized)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If you want to re-use this callback for several similar options (set a flag, but
blow up if ``-b`` has already been seen), it needs a bit of work: the error
message and the flag that it sets must be generalized.  ::

   def check_order(option, opt_str, value, parser):
       if parser.values.b:
           raise OptionValueError("can't use %s after -b" % opt_str)
       setattr(parser.values, option.dest, 1)
   ...
   parser.add_option("-a", action="callback", callback=check_order, dest='a')
   parser.add_option("-b", action="store_true", dest="b")
   parser.add_option("-c", action="callback", callback=check_order, dest='c')


.. _optparse-callback-example-4:

Callback example 4: check arbitrary condition
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Of course, you could put any condition in there---you're not limited to checking
the values of already-defined options.  For example, if you have options that
should not be called when the moon is full, all you have to do is this::

   def check_moon(option, opt_str, value, parser):
       if is_moon_full():
           raise OptionValueError("%s option invalid when moon is full"
                                  % opt_str)
       setattr(parser.values, option.dest, 1)
   ...
   parser.add_option("--foo",
                     action="callback", callback=check_moon, dest="foo")

(The definition of ``is_moon_full()`` is left as an exercise for the reader.)


.. _optparse-callback-example-5:

Callback example 5: fixed arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Things get slightly more interesting when you define callback options that take
a fixed number of arguments.  Specifying that a callback option takes arguments
is similar to defining a ``"store"`` or ``"append"`` option: if you define
:attr:`~Option.type`, then the option takes one argument that must be
convertible to that type; if you further define :attr:`~Option.nargs`, then the
option takes :attr:`~Option.nargs` arguments.

Here's an example that just emulates the standard ``"store"`` action::

   def store_value(option, opt_str, value, parser):
       setattr(parser.values, option.dest, value)
   ...
   parser.add_option("--foo",
                     action="callback", callback=store_value,
                     type="int", nargs=3, dest="foo")

Note that :mod:`optparse` takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them.  (Or whatever;
obviously you don't need a callback for this example.)


.. _optparse-callback-example-6:

Callback example 6: variable arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as :mod:`optparse` doesn't provide any
built-in capabilities for it.  And you have to deal with certain intricacies of
conventional Unix command-line parsing that :mod:`optparse` normally handles for
you.  In particular, callbacks should implement the conventional rules for bare
``--`` and ``-`` arguments:

* either ``--`` or ``-`` can be option arguments

* bare ``--`` (if not the argument to some option): halt command-line
  processing and discard the ``--``

* bare ``-`` (if not the argument to some option): halt command-line
  processing but keep the ``-`` (append it to ``parser.largs``)

If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about.  The exact implementation you
choose will be based on which trade-offs you're willing to make for your
application (which is why :mod:`optparse` doesn't support this sort of thing
directly).

Nevertheless, here's a stab at a callback for an option with variable
arguments::

    def vararg_callback(option, opt_str, value, parser):
        assert value is None
        value = []

        def floatable(str):
            try:
                float(str)
                return True
            except ValueError:
                return False

        for arg in parser.rargs:
            # stop on --foo like options
            if arg[:2] == "--" and len(arg) > 2:
                break
            # stop on -a, but not on -3 or -3.0
            if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
                break
            value.append(arg)

        del parser.rargs[:len(value)]
        setattr(parser.values, option.dest, value)

    ...
    parser.add_option("-c", "--callback", dest="vararg_attr",
                      action="callback", callback=vararg_callback)


.. _optparse-extending-optparse:

Extending :mod:`optparse`
-------------------------

Since the two major controlling factors in how :mod:`optparse` interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.


.. _optparse-adding-new-types:

Adding new types
^^^^^^^^^^^^^^^^

To add new types, you need to define your own subclass of :mod:`optparse`'s
:class:`Option` class.  This class has a couple of attributes that define
:mod:`optparse`'s types: :attr:`~Option.TYPES` and :attr:`~Option.TYPE_CHECKER`.

.. attribute:: Option.TYPES

   A tuple of type names; in your subclass, simply define a new tuple
   :attr:`TYPES` that builds on the standard one.

.. attribute:: Option.TYPE_CHECKER

   A dictionary mapping type names to type-checking functions.  A type-checking
   function has the following signature::

      def check_mytype(option, opt, value)

   where ``option`` is an :class:`Option` instance, ``opt`` is an option string
   (e.g., ``-f``), and ``value`` is the string from the command line that must
   be checked and converted to your desired type.  ``check_mytype()`` should
   return an object of the hypothetical type ``mytype``.  The value returned by
   a type-checking function will wind up in the OptionValues instance returned
   by :meth:`OptionParser.parse_args`, or be passed to a callback as the
   ``value`` parameter.

   Your type-checking function should raise :exc:`OptionValueError` if it
   encounters any problems.  :exc:`OptionValueError` takes a single string
   argument, which is passed as-is to :class:`OptionParser`'s :meth:`error`
   method, which in turn prepends the program name and the string ``"error:"``
   and prints everything to stderr before terminating the process.

Here's a silly example that demonstrates adding a ``"complex"`` option type to
parse Python-style complex numbers on the command line.  (This is even sillier
than it used to be, because :mod:`optparse` 1.3 added built-in support for
complex numbers, but never mind.)

First, the necessary imports::

   from copy import copy
   from optparse import Option, OptionValueError

You need to define your type-checker first, since it's referred to later (in the
:attr:`~Option.TYPE_CHECKER` class attribute of your Option subclass)::

   def check_complex(option, opt, value):
       try:
           return complex(value)
       except ValueError:
           raise OptionValueError(
               "option %s: invalid complex value: %r" % (opt, value))

Finally, the Option subclass::

   class MyOption (Option):
       TYPES = Option.TYPES + ("complex",)
       TYPE_CHECKER = copy(Option.TYPE_CHECKER)
       TYPE_CHECKER["complex"] = check_complex

(If we didn't make a :func:`copy` of :attr:`Option.TYPE_CHECKER`, we would end
up modifying the :attr:`~Option.TYPE_CHECKER` attribute of :mod:`optparse`'s
Option class.  This being Python, nothing stops you from doing that except good
manners and common sense.)

That's it!  Now you can write a script that uses the new option type just like
any other :mod:`optparse`\ -based script, except you have to instruct your
OptionParser to use MyOption instead of Option::

   parser = OptionParser(option_class=MyOption)
   parser.add_option("-c", type="complex")

Alternately, you can build your own option list and pass it to OptionParser; if
you don't use :meth:`add_option` in the above way, you don't need to tell
OptionParser which option class to use::

   option_list = [MyOption("-c", action="store", type="complex", dest="c")]
   parser = OptionParser(option_list=option_list)


.. _optparse-adding-new-actions:

Adding new actions
^^^^^^^^^^^^^^^^^^

Adding new actions is a bit trickier, because you have to understand that
:mod:`optparse` has a couple of classifications for actions:

"store" actions
   actions that result in :mod:`optparse` storing a value to an attribute of the
   current OptionValues instance; these options require a :attr:`~Option.dest`
   attribute to be supplied to the Option constructor.

"typed" actions
   actions that take a value from the command line and expect it to be of a
   certain type; or rather, a string that can be converted to a certain type.
   These options require a :attr:`~Option.type` attribute to the Option
   constructor.

These are overlapping sets: some default "store" actions are ``"store"``,
``"store_const"``, ``"append"``, and ``"count"``, while the default "typed"
actions are ``"store"``, ``"append"``, and ``"callback"``.

When you add an action, you need to categorize it by listing it in at least one
of the following class attributes of Option (all are lists of strings):

.. attribute:: Option.ACTIONS

   All actions must be listed in ACTIONS.

.. attribute:: Option.STORE_ACTIONS

   "store" actions are additionally listed here.

.. attribute:: Option.TYPED_ACTIONS

   "typed" actions are additionally listed here.

.. attribute:: Option.ALWAYS_TYPED_ACTIONS

   Actions that always take a type (i.e. whose options always take a value) are
   additionally listed here.  The only effect of this is that :mod:`optparse`
   assigns the default type, ``"string"``, to options with no explicit type
   whose action is listed in :attr:`ALWAYS_TYPED_ACTIONS`.

In order to actually implement your new action, you must override Option's
:meth:`take_action` method and add a case that recognizes your action.

For example, let's add an ``"extend"`` action.  This is similar to the standard
``"append"`` action, but instead of taking a single value from the command-line
and appending it to an existing list, ``"extend"`` will take multiple values in
a single comma-delimited string, and extend an existing list with them.  That
is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
line ::

   --names=foo,bar --names blah --names ding,dong

would result in a list  ::

   ["foo", "bar", "blah", "ding", "dong"]

Again we define a subclass of Option::

   class MyOption(Option):

       ACTIONS = Option.ACTIONS + ("extend",)
       STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
       TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
       ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

       def take_action(self, action, dest, opt, value, values, parser):
           if action == "extend":
               lvalue = value.split(",")
               values.ensure_value(dest, []).extend(lvalue)
           else:
               Option.take_action(
                   self, action, dest, opt, value, values, parser)

Features of note:

* ``"extend"`` both expects a value on the command-line and stores that value
  somewhere, so it goes in both :attr:`~Option.STORE_ACTIONS` and
  :attr:`~Option.TYPED_ACTIONS`.

* to ensure that :mod:`optparse` assigns the default type of ``"string"`` to
  ``"extend"`` actions, we put the ``"extend"`` action in
  :attr:`~Option.ALWAYS_TYPED_ACTIONS` as well.

* :meth:`MyOption.take_action` implements just this one new action, and passes
  control back to :meth:`Option.take_action` for the standard :mod:`optparse`
  actions.

* ``values`` is an instance of the optparse_parser.Values class, which provides
  the very useful :meth:`ensure_value` method. :meth:`ensure_value` is
  essentially :func:`getattr` with a safety valve; it is called as ::

     values.ensure_value(attr, value)

  If the ``attr`` attribute of ``values`` doesn't exist or is ``None``, then
  ensure_value() first sets it to ``value``, and then returns 'value. This is
  very handy for actions like ``"extend"``, ``"append"``, and ``"count"``, all
  of which accumulate data in a variable and expect that variable to be of a
  certain type (a list for the first two, an integer for the latter).  Using
  :meth:`ensure_value` means that scripts using your action don't have to worry
  about setting a default value for the option destinations in question; they
  can just leave the default as ``None`` and :meth:`ensure_value` will take care of
  getting it right when it's needed.
PK	%�\;�};&3&3%html/_sources/library/os.path.rst.txtnu�[���:mod:`os.path` --- Common pathname manipulations
================================================

.. module:: os.path
   :synopsis: Operations on pathnames.

.. index:: single: path; operations

This module implements some useful functions on pathnames. To read or
write files see :func:`open`, and for accessing the filesystem see the
:mod:`os` module.

.. note::

   On Windows, many of these functions do not properly support UNC pathnames.
   :func:`splitunc` and :func:`ismount` do handle them correctly.


Unlike a unix shell, Python does not do any *automatic* path expansions.
Functions such as :func:`expanduser` and :func:`expandvars` can be invoked
explicitly when an application desires shell-like path expansion.  (See also
the :mod:`glob` module.)

.. note::

   Since different operating systems have different path name conventions, there
   are several versions of this module in the standard library.  The
   :mod:`os.path` module is always the path module suitable for the operating
   system Python is running on, and therefore usable for local paths.  However,
   you can also import and use the individual modules if you want to manipulate
   a path that is *always* in one of the different formats.  They all have the
   same interface:

   * :mod:`posixpath` for UNIX-style paths
   * :mod:`ntpath` for Windows paths
   * :mod:`macpath` for old-style MacOS paths
   * :mod:`os2emxpath` for OS/2 EMX paths


.. function:: abspath(path)

   Return a normalized absolutized version of the pathname *path*. On most
   platforms, this is equivalent to calling the function :func:`normpath` as
   follows: ``normpath(join(os.getcwd(), path))``.

   .. versionadded:: 1.5.2


.. function:: basename(path)

   Return the base name of pathname *path*.  This is the second element of the
   pair returned by passing *path* to the function :func:`split`.  Note that
   the result of this function is different
   from the Unix :program:`basename` program; where :program:`basename` for
   ``'/foo/bar/'`` returns ``'bar'``, the :func:`basename` function returns an
   empty string (``''``).


.. function:: commonprefix(list)

   Return the longest path prefix (taken character-by-character) that is a prefix
   of all paths in  *list*.  If *list* is empty, return the empty string (``''``).
   Note that this may return invalid paths because it works a character at a time.


.. function:: dirname(path)

   Return the directory name of pathname *path*.  This is the first element of
   the pair returned by passing *path* to the function :func:`split`.


.. function:: exists(path)

   Return ``True`` if *path* refers to an existing path.  Returns ``False`` for
   broken symbolic links. On some platforms, this function may return ``False`` if
   permission is not granted to execute :func:`os.stat` on the requested file, even
   if the *path* physically exists.


.. function:: lexists(path)

   Return ``True`` if *path* refers to an existing path. Returns ``True`` for
   broken symbolic links.   Equivalent to :func:`exists` on platforms lacking
   :func:`os.lstat`.

   .. versionadded:: 2.4


.. function:: expanduser(path)

   On Unix and Windows, return the argument with an initial component of ``~`` or
   ``~user`` replaced by that *user*'s home directory.

   .. index:: module: pwd

   On Unix, an initial ``~`` is replaced by the environment variable :envvar:`HOME`
   if it is set; otherwise the current user's home directory is looked up in the
   password directory through the built-in module :mod:`pwd`. An initial ``~user``
   is looked up directly in the password directory.

   On Windows, :envvar:`HOME` and :envvar:`USERPROFILE` will be used if set,
   otherwise a combination of :envvar:`HOMEPATH` and :envvar:`HOMEDRIVE` will be
   used.  An initial ``~user`` is handled by stripping the last directory component
   from the created user path derived above.

   If the expansion fails or if the path does not begin with a tilde, the path is
   returned unchanged.


.. function:: expandvars(path)

   Return the argument with environment variables expanded.  Substrings of the form
   ``$name`` or ``${name}`` are replaced by the value of environment variable
   *name*.  Malformed variable names and references to non-existing variables are
   left unchanged.

   On Windows, ``%name%`` expansions are supported in addition to ``$name`` and
   ``${name}``.


.. function:: getatime(path)

   Return the time of last access of *path*.  The return value is a number giving
   the number of seconds since the epoch (see the  :mod:`time` module).  Raise
   :exc:`os.error` if the file does not exist or is inaccessible.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.3
      If :func:`os.stat_float_times` returns ``True``, the result is a floating point
      number.


.. function:: getmtime(path)

   Return the time of last modification of *path*.  The return value is a number
   giving the number of seconds since the epoch (see the  :mod:`time` module).
   Raise :exc:`os.error` if the file does not exist or is inaccessible.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.3
      If :func:`os.stat_float_times` returns ``True``, the result is a floating point
      number.


.. function:: getctime(path)

   Return the system's ctime which, on some systems (like Unix) is the time of the
   last metadata change, and, on others (like Windows), is the creation time for *path*.
   The return value is a number giving the number of seconds since the epoch (see
   the  :mod:`time` module).  Raise :exc:`os.error` if the file does not exist or
   is inaccessible.

   .. versionadded:: 2.3


.. function:: getsize(path)

   Return the size, in bytes, of *path*.  Raise :exc:`os.error` if the file does
   not exist or is inaccessible.

   .. versionadded:: 1.5.2


.. function:: isabs(path)

   Return ``True`` if *path* is an absolute pathname.  On Unix, that means it
   begins with a slash, on Windows that it begins with a (back)slash after chopping
   off a potential drive letter.


.. function:: isfile(path)

   Return ``True`` if *path* is an existing regular file.  This follows symbolic
   links, so both :func:`islink` and :func:`isfile` can be true for the same path.


.. function:: isdir(path)

   Return ``True`` if *path* is an existing directory.  This follows symbolic
   links, so both :func:`islink` and :func:`isdir` can be true for the same path.


.. function:: islink(path)

   Return ``True`` if *path* refers to a directory entry that is a symbolic link.
   Always ``False`` if symbolic links are not supported by the Python runtime.


.. function:: ismount(path)

   Return ``True`` if pathname *path* is a :dfn:`mount point`: a point in a file
   system where a different file system has been mounted.  The function checks
   whether *path*'s parent, :file:`path/..`, is on a different device than *path*,
   or whether :file:`path/..` and *path* point to the same i-node on the same
   device --- this should detect mount points for all Unix and POSIX variants.


.. function:: join(path, *paths)

   Join one or more path components intelligently.  The return value is the
   concatenation of *path* and any members of *\*paths* with exactly one
   directory separator (``os.sep``) following each non-empty part except the
   last, meaning that the result will only end in a separator if the last
   part is empty.  If a component is an absolute path, all previous
   components are thrown away and joining continues from the absolute path
   component.

   On Windows, the drive letter is not reset when an absolute path component
   (e.g., ``r'\foo'``) is encountered.  If a component contains a drive
   letter, all previous components are thrown away and the drive letter is
   reset.  Note that since there is a current directory for each drive,
   ``os.path.join("c:", "foo")`` represents a path relative to the current
   directory on drive :file:`C:` (:file:`c:foo`), not :file:`c:\\foo`.


.. function:: normcase(path)

   Normalize the case of a pathname.  On Unix and Mac OS X, this returns the
   path unchanged; on case-insensitive filesystems, it converts the path to
   lowercase.  On Windows, it also converts forward slashes to backward slashes.


.. function:: normpath(path)

   Normalize a pathname by collapsing redundant separators and up-level
   references so that ``A//B``, ``A/B/``, ``A/./B`` and ``A/foo/../B`` all
   become ``A/B``.  This string manipulation may change the meaning of a path
   that contains symbolic links.  On Windows, it converts forward slashes to
   backward slashes. To normalize case, use :func:`normcase`.


.. function:: realpath(path)

   Return the canonical path of the specified filename, eliminating any symbolic
   links encountered in the path (if they are supported by the operating system).

   .. versionadded:: 2.2


.. function:: relpath(path[, start])

   Return a relative filepath to *path* either from the current directory or
   from an optional *start* directory.  This is a path computation:  the
   filesystem is not accessed to confirm the existence or nature of *path* or
   *start*.

   *start* defaults to :attr:`os.curdir`.

   Availability:  Windows, Unix.

   .. versionadded:: 2.6


.. function:: samefile(path1, path2)

   Return ``True`` if both pathname arguments refer to the same file or directory
   (as indicated by device number and i-node number). Raise an exception if an
   :func:`os.stat` call on either pathname fails.

   Availability: Unix.


.. function:: sameopenfile(fp1, fp2)

   Return ``True`` if the file descriptors *fp1* and *fp2* refer to the same file.

   Availability: Unix.


.. function:: samestat(stat1, stat2)

   Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
   These structures may have been returned by :func:`os.fstat`,
   :func:`os.lstat`, or :func:`os.stat`.  This function implements the
   underlying comparison used by :func:`samefile` and :func:`sameopenfile`.

   Availability: Unix.


.. function:: split(path)

   Split the pathname *path* into a pair, ``(head, tail)`` where *tail* is the
   last pathname component and *head* is everything leading up to that.  The
   *tail* part will never contain a slash; if *path* ends in a slash, *tail*
   will be empty.  If there is no slash in *path*, *head* will be empty.  If
   *path* is empty, both *head* and *tail* are empty.  Trailing slashes are
   stripped from *head* unless it is the root (one or more slashes only).  In
   all cases, ``join(head, tail)`` returns a path to the same location as *path*
   (but the strings may differ).  Also see the functions :func:`dirname` and
   :func:`basename`.


.. function:: splitdrive(path)

   Split the pathname *path* into a pair ``(drive, tail)`` where *drive* is either
   a drive specification or the empty string.  On systems which do not use drive
   specifications, *drive* will always be the empty string.  In all cases, ``drive
   + tail`` will be the same as *path*.

   .. versionadded:: 1.3


.. function:: splitext(path)

   Split the pathname *path* into a pair ``(root, ext)``  such that ``root + ext ==
   path``, and *ext* is empty or begins with a period and contains at most one
   period. Leading periods on the basename are  ignored; ``splitext('.cshrc')``
   returns  ``('.cshrc', '')``.

   .. versionchanged:: 2.6
      Earlier versions could produce an empty root when the only period was the
      first character.


.. function:: splitunc(path)

   Split the pathname *path* into a pair ``(unc, rest)`` so that *unc* is the UNC
   mount point (such as ``r'\\host\mount'``), if present, and *rest* the rest of
   the path (such as  ``r'\path\file.ext'``).  For paths containing drive letters,
   *unc* will always be the empty string.

   Availability:  Windows.


.. function:: walk(path, visit, arg)

   Calls the function *visit* with arguments ``(arg, dirname, names)`` for each
   directory in the directory tree rooted at *path* (including *path* itself, if it
   is a directory).  The argument *dirname* specifies the visited directory, the
   argument *names* lists the files in the directory (gotten from
   ``os.listdir(dirname)``). The *visit* function may modify *names* to influence
   the set of directories visited below *dirname*, e.g. to avoid visiting certain
   parts of the tree.  (The object referred to by *names* must be modified in
   place, using :keyword:`del` or slice assignment.)

   .. note::

      Symbolic links to directories are not treated as subdirectories, and that
      :func:`walk` therefore will not visit them. To visit linked directories you must
      identify them with ``os.path.islink(file)`` and ``os.path.isdir(file)``, and
      invoke :func:`walk` as necessary.

   .. note::

      This function is deprecated and has been removed in Python 3 in favor of
      :func:`os.walk`.


.. data:: supports_unicode_filenames

   ``True`` if arbitrary Unicode strings can be used as file names (within limitations
   imposed by the file system).

   .. versionadded:: 2.3

PK	%�\/��B�B html/_sources/library/os.rst.txtnu�[���:mod:`os` --- Miscellaneous operating system interfaces
=======================================================

.. module:: os
   :synopsis: Miscellaneous operating system interfaces.


This module provides a portable way of using operating system dependent
functionality.  If you just want to read or write a file see :func:`open`, if
you want to manipulate paths, see the :mod:`os.path` module, and if you want to
read all the lines in all the files on the command line see the :mod:`fileinput`
module.  For creating temporary files and directories see the :mod:`tempfile`
module, and for high-level file and directory handling see the :mod:`shutil`
module.

Notes on the availability of these functions:

* The design of all built-in operating system dependent modules of Python is
  such that as long as the same functionality is available, it uses the same
  interface; for example, the function ``os.stat(path)`` returns stat
  information about *path* in the same format (which happens to have originated
  with the POSIX interface).

* Extensions peculiar to a particular operating system are also available
  through the :mod:`os` module, but using them is of course a threat to
  portability.

* An "Availability: Unix" note means that this function is commonly found on
  Unix systems.  It does not make any claims about its existence on a specific
  operating system.

* If not separately noted, all functions that claim "Availability: Unix" are
  supported on Mac OS X, which builds on a Unix core.

.. Availability notes get their own line and occur at the end of the function
.. documentation.

.. note::

   All functions in this module raise :exc:`OSError` in the case of invalid or
   inaccessible file names and paths, or other arguments that have the correct
   type, but are not accepted by the operating system.


.. exception:: error

   An alias for the built-in :exc:`OSError` exception.


.. data:: name

   The name of the operating system dependent module imported.  The following
   names have currently been registered: ``'posix'``, ``'nt'``,
   ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``.

   .. seealso::
      :attr:`sys.platform` has a finer granularity.  :func:`os.uname` gives
      system-dependent version information.

      The :mod:`platform` module provides detailed checks for the
      system's identity.


.. _os-procinfo:

Process Parameters
------------------

These functions and data items provide information and operate on the current
process and user.


.. data:: environ

   A :term:`mapping` object representing the string environment. For example,
   ``environ['HOME']`` is the pathname of your home directory (on some platforms),
   and is equivalent to ``getenv("HOME")`` in C.

   This mapping is captured the first time the :mod:`os` module is imported,
   typically during Python startup as part of processing :file:`site.py`.  Changes
   to the environment made after this time are not reflected in ``os.environ``,
   except for changes made by modifying ``os.environ`` directly.

   If the platform supports the :func:`putenv` function, this mapping may be used
   to modify the environment as well as query the environment.  :func:`putenv` will
   be called automatically when the mapping is modified.

   .. note::

      Calling :func:`putenv` directly does not change ``os.environ``, so it's better
      to modify ``os.environ``.

   .. note::

      On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
      cause memory leaks.  Refer to the system documentation for
      :c:func:`putenv`.

   If :func:`putenv` is not provided, a modified copy of this mapping  may be
   passed to the appropriate process-creation functions to cause  child processes
   to use a modified environment.

   If the platform supports the :func:`unsetenv` function, you can delete items in
   this mapping to unset environment variables. :func:`unsetenv` will be called
   automatically when an item is deleted from ``os.environ``, and when
   one of the :meth:`pop` or :meth:`clear` methods is called.

   .. versionchanged:: 2.6
      Also unset environment variables when calling :meth:`os.environ.clear`
      and :meth:`os.environ.pop`.


.. function:: chdir(path)
              fchdir(fd)
              getcwd()
   :noindex:

   These functions are described in :ref:`os-file-dir`.


.. function:: ctermid()

   Return the filename corresponding to the controlling terminal of the process.

   Availability: Unix.


.. function:: getegid()

   Return the effective group id of the current process.  This corresponds to the
   "set id" bit on the file being executed in the current process.

   Availability: Unix.


.. function:: geteuid()

   .. index:: single: user; effective id

   Return the current process's effective user id.

   Availability: Unix.


.. function:: getgid()

   .. index:: single: process; group

   Return the real group id of the current process.

   Availability: Unix.


.. function:: getgroups()

   Return list of supplemental group ids associated with the current process.

   Availability: Unix.

   .. note::

      On Mac OS X, :func:`getgroups` behavior differs somewhat from
      other Unix platforms. If the Python interpreter was built with a
      deployment target of :const:`10.5` or earlier, :func:`getgroups` returns
      the list of effective group ids associated with the current user process;
      this list is limited to a system-defined number of entries, typically 16,
      and may be modified by calls to :func:`setgroups` if suitably privileged.
      If built with a deployment target greater than :const:`10.5`,
      :func:`getgroups` returns the current group access list for the user
      associated with the effective user id of the process; the group access
      list may change over the lifetime of the process, it is not affected by
      calls to :func:`setgroups`, and its length is not limited to 16.  The
      deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
      obtained with :func:`sysconfig.get_config_var`.


.. function:: initgroups(username, gid)

   Call the system initgroups() to initialize the group access list with all of
   the groups of which the specified username is a member, plus the specified
   group id.

   Availability: Unix.

   .. versionadded:: 2.7


.. function:: getlogin()

   Return the name of the user logged in on the controlling terminal of the
   process.  For most purposes, it is more useful to use the environment
   variable :envvar:`LOGNAME` to find out who the user is, or
   ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the process's real
   user id.

   Availability: Unix.


.. function:: getpgid(pid)

   Return the process group id of the process with process id *pid*. If *pid* is 0,
   the process group id of the current process is returned.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: getpgrp()

   .. index:: single: process; group

   Return the id of the current process group.

   Availability: Unix.


.. function:: getpid()

   .. index:: single: process; id

   Return the current process id.

   Availability: Unix, Windows.


.. function:: getppid()

   .. index:: single: process; id of parent

   Return the parent's process id.

   Availability: Unix.


.. function:: getresuid()

   Return a tuple (ruid, euid, suid) denoting the current process's
   real, effective, and saved user ids.

   Availability: Unix.

   .. versionadded:: 2.7


.. function:: getresgid()

   Return a tuple (rgid, egid, sgid) denoting the current process's
   real, effective, and saved group ids.

   Availability: Unix.

   .. versionadded:: 2.7


.. function:: getuid()

   .. index:: single: user; id

   Return the current process's real user id.

   Availability: Unix.


.. function:: getenv(varname[, value])

   Return the value of the environment variable *varname* if it exists, or *value*
   if it doesn't.  *value* defaults to ``None``.

   Availability: most flavors of Unix, Windows.


.. function:: putenv(varname, value)

   .. index:: single: environment variables; setting

   Set the environment variable named *varname* to the string *value*.  Such
   changes to the environment affect subprocesses started with :func:`os.system`,
   :func:`popen` or :func:`fork` and :func:`execv`.

   Availability: most flavors of Unix, Windows.

   .. note::

      On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
      cause memory leaks. Refer to the system documentation for putenv.

   When :func:`putenv` is supported, assignments to items in ``os.environ`` are
   automatically translated into corresponding calls to :func:`putenv`; however,
   calls to :func:`putenv` don't update ``os.environ``, so it is actually
   preferable to assign to items of ``os.environ``.


.. function:: setegid(egid)

   Set the current process's effective group id.

   Availability: Unix.


.. function:: seteuid(euid)

   Set the current process's effective user id.

   Availability: Unix.


.. function:: setgid(gid)

   Set the current process' group id.

   Availability: Unix.


.. function:: setgroups(groups)

   Set the list of supplemental group ids associated with the current process to
   *groups*. *groups* must be a sequence, and each element must be an integer
   identifying a group. This operation is typically available only to the superuser.

   Availability: Unix.

   .. versionadded:: 2.2

   .. note:: On Mac OS X, the length of *groups* may not exceed the
      system-defined maximum number of effective group ids, typically 16.
      See the documentation for :func:`getgroups` for cases where it may not
      return the same group list set by calling setgroups().

.. function:: setpgrp()

   Call the system call :c:func:`setpgrp` or ``setpgrp(0, 0)`` depending on
   which version is implemented (if any).  See the Unix manual for the semantics.

   Availability: Unix.


.. function:: setpgid(pid, pgrp)

   Call the system call :c:func:`setpgid` to set the process group id of the
   process with id *pid* to the process group with id *pgrp*.  See the Unix manual
   for the semantics.

   Availability: Unix.


.. function:: setregid(rgid, egid)

   Set the current process's real and effective group ids.

   Availability: Unix.


.. function:: setresgid(rgid, egid, sgid)

   Set the current process's real, effective, and saved group ids.

   Availability: Unix.

   .. versionadded:: 2.7


.. function:: setresuid(ruid, euid, suid)

   Set the current process's real, effective, and saved user ids.

   Availability: Unix.

   .. versionadded:: 2.7


.. function:: setreuid(ruid, euid)

   Set the current process's real and effective user ids.

   Availability: Unix.


.. function:: getsid(pid)

   Call the system call :c:func:`getsid`.  See the Unix manual for the semantics.

   Availability: Unix.

   .. versionadded:: 2.4


.. function:: setsid()

   Call the system call :c:func:`setsid`.  See the Unix manual for the semantics.

   Availability: Unix.


.. function:: setuid(uid)

   .. index:: single: user; id, setting

   Set the current process's user id.

   Availability: Unix.


.. placed in this section since it relates to errno.... a little weak
.. function:: strerror(code)

   Return the error message corresponding to the error code in *code*.
   On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
   error number, :exc:`ValueError` is raised.

   Availability: Unix, Windows.


.. function:: umask(mask)

   Set the current numeric umask and return the previous umask.

   Availability: Unix, Windows.


.. function:: uname()

   .. index::
      single: gethostname() (in module socket)
      single: gethostbyaddr() (in module socket)

   Return a 5-tuple containing information identifying the current operating
   system.  The tuple contains 5 strings: ``(sysname, nodename, release, version,
   machine)``.  Some systems truncate the nodename to 8 characters or to the
   leading component; a better way to get the hostname is
   :func:`socket.gethostname`  or even
   ``socket.gethostbyaddr(socket.gethostname())``.

   Availability: recent flavors of Unix.


.. function:: unsetenv(varname)

   .. index:: single: environment variables; deleting

   Unset (delete) the environment variable named *varname*. Such changes to the
   environment affect subprocesses started with :func:`os.system`, :func:`popen` or
   :func:`fork` and :func:`execv`.

   When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
   automatically translated into a corresponding call to :func:`unsetenv`; however,
   calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
   preferable to delete items of ``os.environ``.

   Availability: most flavors of Unix, Windows.


.. _os-newstreams:

File Object Creation
--------------------

These functions create new file objects. (See also :func:`open`.)


.. function:: fdopen(fd[, mode[, bufsize]])

   .. index:: single: I/O control; buffering

   Return an open file object connected to the file descriptor *fd*.  The *mode*
   and *bufsize* arguments have the same meaning as the corresponding arguments
   to the built-in :func:`open` function.  If :func:`fdopen` raises an
   exception, it leaves *fd* untouched (unclosed).

   Availability: Unix, Windows.

   .. versionchanged:: 2.3
      When specified, the *mode* argument must now start with one of the letters
      ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.

   .. versionchanged:: 2.5
      On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
      set on the file descriptor (which the :c:func:`fdopen` implementation already
      does on most platforms).


.. function:: popen(command[, mode[, bufsize]])

   Open a pipe to or from *command*.  The return value is an open file object
   connected to the pipe, which can be read or written depending on whether *mode*
   is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
   the corresponding argument to the built-in :func:`open` function.  The exit
   status of the command (encoded in the format specified for :func:`wait`) is
   available as the return value of the :meth:`~file.close` method of the file object,
   except that when the exit status is zero (termination without errors), ``None``
   is returned.

   Availability: Unix, Windows.

   .. deprecated:: 2.6
      This function is obsolete.  Use the :mod:`subprocess` module.  Check
      especially the :ref:`subprocess-replacements` section.

   .. versionchanged:: 2.0
      This function worked unreliably under Windows in earlier versions of Python.
      This was due to the use of the :c:func:`_popen` function from the libraries
      provided with Windows.  Newer versions of Python do not use the broken
      implementation from the Windows libraries.


.. function:: tmpfile()

   Return a new file object opened in update mode (``w+b``).  The file has no
   directory entries associated with it and will be automatically deleted once
   there are no file descriptors for the file.

   Availability: Unix, Windows.

There are a number of different :func:`popen\*` functions that provide slightly
different ways to create subprocesses.

.. deprecated:: 2.6
   All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
   module.

For each of the :func:`popen\*` variants, if *bufsize* is specified, it
specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
file objects should be opened in binary or text mode.  The default value for
*mode* is ``'t'``.

Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
case arguments will be passed directly to the program without shell intervention
(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
(as with :func:`os.system`).

These methods do not make it possible to retrieve the exit status from the child
processes.  The only way to control the input and output streams and also
retrieve the return codes is to use the :mod:`subprocess` module; these are only
available on Unix.

For a discussion of possible deadlock conditions related to the use of these
functions, see :ref:`popen2-flow-control`.


.. function:: popen2(cmd[, mode[, bufsize]])

   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
   child_stdout)``.

   .. deprecated:: 2.6
      This function is obsolete.  Use the :mod:`subprocess` module.  Check
      especially the :ref:`subprocess-replacements` section.

   Availability: Unix, Windows.

   .. versionadded:: 2.0


.. function:: popen3(cmd[, mode[, bufsize]])

   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
   child_stdout, child_stderr)``.

   .. deprecated:: 2.6
      This function is obsolete.  Use the :mod:`subprocess` module.  Check
      especially the :ref:`subprocess-replacements` section.

   Availability: Unix, Windows.

   .. versionadded:: 2.0


.. function:: popen4(cmd[, mode[, bufsize]])

   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
   child_stdout_and_stderr)``.

   .. deprecated:: 2.6
      This function is obsolete.  Use the :mod:`subprocess` module.  Check
      especially the :ref:`subprocess-replacements` section.

   Availability: Unix, Windows.

   .. versionadded:: 2.0

(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
point of view of the child process, so *child_stdin* is the child's standard
input.)

This functionality is also available in the :mod:`popen2` module using functions
of the same names, but the return values of those functions have a different
order.


.. _os-fd-ops:

File Descriptor Operations
--------------------------

These functions operate on I/O streams referenced using file descriptors.

File descriptors are small integers corresponding to a file that has been opened
by the current process.  For example, standard input is usually file descriptor
0, standard output is 1, and standard error is 2.  Further files opened by a
process will then be assigned 3, 4, 5, and so forth.  The name "file descriptor"
is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
by file descriptors.

The :meth:`~file.fileno` method can be used to obtain the file descriptor
associated with a file object when required.  Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.

.. function:: close(fd)

   Close file descriptor *fd*.

   Availability: Unix, Windows.

   .. note::

      This function is intended for low-level I/O and must be applied to a file
      descriptor as returned by :func:`os.open` or :func:`pipe`.  To close a "file
      object" returned by the built-in function :func:`open` or by :func:`popen` or
      :func:`fdopen`, use its :meth:`~io.IOBase.close` method.


.. function:: closerange(fd_low, fd_high)

   Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
   ignoring errors. Equivalent to::

      for fd in xrange(fd_low, fd_high):
          try:
              os.close(fd)
          except OSError:
              pass

   Availability: Unix, Windows.

   .. versionadded:: 2.6


.. function:: dup(fd)

   Return a duplicate of file descriptor *fd*.

   Availability: Unix, Windows.


.. function:: dup2(fd, fd2)

   Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.

   Availability: Unix, Windows.


.. function:: fchmod(fd, mode)

   Change the mode of the file given by *fd* to the numeric *mode*.  See the docs
   for :func:`chmod` for possible values of *mode*.

   Availability: Unix.

   .. versionadded:: 2.6


.. function:: fchown(fd, uid, gid)

   Change the owner and group id of the file given by *fd* to the numeric *uid*
   and *gid*.  To leave one of the ids unchanged, set it to -1.

   Availability: Unix.

   .. versionadded:: 2.6


.. function:: fdatasync(fd)

   Force write of file with filedescriptor *fd* to disk. Does not force update of
   metadata.

   Availability: Unix.

   .. note::
      This function is not available on MacOS.


.. function:: fpathconf(fd, name)

   Return system configuration information relevant to an open file. *name*
   specifies the configuration value to retrieve; it may be a string which is the
   name of a defined system value; these names are specified in a number of
   standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
   additional names as well.  The names known to the host operating system are
   given in the ``pathconf_names`` dictionary.  For configuration variables not
   included in that mapping, passing an integer for *name* is also accepted.

   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
   specific value for *name* is not supported by the host system, even if it is
   included in ``pathconf_names``, an :exc:`OSError` is raised with
   :const:`errno.EINVAL` for the error number.

   Availability: Unix.


.. function:: fstat(fd)

   Return status for file descriptor *fd*, like :func:`~os.stat`.

   Availability: Unix, Windows.


.. function:: fstatvfs(fd)

   Return information about the filesystem containing the file associated with file
   descriptor *fd*, like :func:`statvfs`.

   Availability: Unix.


.. function:: fsync(fd)

   Force write of file with filedescriptor *fd* to disk.  On Unix, this calls the
   native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function.

   If you're starting with a Python file object *f*, first do ``f.flush()``, and
   then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
   with *f* are written to disk.

   Availability: Unix, and Windows starting in 2.2.3.


.. function:: ftruncate(fd, length)

   Truncate the file corresponding to file descriptor *fd*, so that it is at most
   *length* bytes in size.

   Availability: Unix.


.. function:: isatty(fd)

   Return ``True`` if the file descriptor *fd* is open and connected to a
   tty(-like) device, else ``False``.


.. function:: lseek(fd, pos, how)

   Set the current position of file descriptor *fd* to position *pos*, modified
   by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
   beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
   current position; :const:`SEEK_END` or ``2`` to set it relative to the end of
   the file. Return the new cursor position in bytes, starting from the beginning.

   Availability: Unix, Windows.


.. data:: SEEK_SET
          SEEK_CUR
          SEEK_END

   Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
   respectively.

   Availability: Windows, Unix.

   .. versionadded:: 2.5


.. function:: open(file, flags[, mode])

   Open the file *file* and set various flags according to *flags* and possibly its
   mode according to *mode*. The default *mode* is ``0777`` (octal), and the
   current umask value is first masked out.  Return the file descriptor for the
   newly opened file.

   For a description of the flag and mode values, see the C run-time documentation;
   flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
   this module too (see :ref:`open-constants`).  In particular, on Windows adding
   :const:`O_BINARY` is needed to open files in binary mode.

   Availability: Unix, Windows.

   .. note::

      This function is intended for low-level I/O.  For normal usage, use the
      built-in function :func:`open`, which returns a "file object" with
      :meth:`~file.read` and :meth:`~file.write` methods (and many more).  To
      wrap a file descriptor in a "file object", use :func:`fdopen`.


.. function:: openpty()

   .. index:: module: pty

   Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
   slave)`` for the pty and the tty, respectively. For a (slightly) more portable
   approach, use the :mod:`pty` module.

   Availability: some flavors of Unix.


.. function:: pipe()

   Create a pipe.  Return a pair of file descriptors ``(r, w)`` usable for reading
   and writing, respectively.

   Availability: Unix, Windows.


.. function:: read(fd, n)

   Read at most *n* bytes from file descriptor *fd*. Return a string containing the
   bytes read.  If the end of the file referred to by *fd* has been reached, an
   empty string is returned.

   Availability: Unix, Windows.

   .. note::

      This function is intended for low-level I/O and must be applied to a file
      descriptor as returned by :func:`os.open` or :func:`pipe`.  To read a "file object"
      returned by the built-in function :func:`open` or by :func:`popen` or
      :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
      :meth:`~file.readline` methods.


.. function:: tcgetpgrp(fd)

   Return the process group associated with the terminal given by *fd* (an open
   file descriptor as returned by :func:`os.open`).

   Availability: Unix.


.. function:: tcsetpgrp(fd, pg)

   Set the process group associated with the terminal given by *fd* (an open file
   descriptor as returned by :func:`os.open`) to *pg*.

   Availability: Unix.


.. function:: ttyname(fd)

   Return a string which specifies the terminal device associated with
   file descriptor *fd*.  If *fd* is not associated with a terminal device, an
   exception is raised.

   Availability: Unix.


.. function:: write(fd, str)

   Write the string *str* to file descriptor *fd*. Return the number of bytes
   actually written.

   Availability: Unix, Windows.

   .. note::

      This function is intended for low-level I/O and must be applied to a file
      descriptor as returned by :func:`os.open` or :func:`pipe`.  To write a "file
      object" returned by the built-in function :func:`open` or by :func:`popen` or
      :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
      :meth:`~file.write` method.


.. _open-constants:

``open()`` flag constants
~~~~~~~~~~~~~~~~~~~~~~~~~

The following constants are options for the *flags* parameter to the
:func:`~os.open` function.  They can be combined using the bitwise OR operator
``|``.  Some of them are not available on all platforms.  For descriptions of
their availability and use, consult the :manpage:`open(2)` manual page on Unix
or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.


.. data:: O_RDONLY
          O_WRONLY
          O_RDWR
          O_APPEND
          O_CREAT
          O_EXCL
          O_TRUNC

   The above constants are available on Unix and Windows.


.. data:: O_DSYNC
          O_RSYNC
          O_SYNC
          O_NDELAY
          O_NONBLOCK
          O_NOCTTY

   The above constants are only available on Unix.


.. data:: O_BINARY
          O_NOINHERIT
          O_SHORT_LIVED
          O_TEMPORARY
          O_RANDOM
          O_SEQUENTIAL
          O_TEXT

   The above constants are only available on Windows.


.. data:: O_ASYNC
          O_DIRECT
          O_DIRECTORY
          O_NOFOLLOW
          O_NOATIME
          O_SHLOCK
          O_EXLOCK

   The above constants are extensions and not present if they are not
   defined by the C library.


.. _os-file-dir:

Files and Directories
---------------------

.. function:: access(path, mode)

   Use the real uid/gid to test for access to *path*.  Note that most operations
   will use the effective uid/gid, therefore this routine can be used in a
   suid/sgid environment to test if the invoking user has the specified access to
   *path*.  *mode* should be :const:`F_OK` to test the existence of *path*, or it
   can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
   :const:`X_OK` to test permissions.  Return :const:`True` if access is allowed,
   :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
   information.

   Availability: Unix, Windows.

   .. note::

      Using :func:`access` to check if a user is authorized to e.g. open a file
      before actually doing so using :func:`open` creates a security hole,
      because the user might exploit the short time interval between checking
      and opening the file to manipulate it. It's preferable to use :term:`EAFP`
      techniques. For example::

         if os.access("myfile", os.R_OK):
             with open("myfile") as fp:
                 return fp.read()
         return "some default data"

      is better written as::

         try:
             fp = open("myfile")
         except IOError as e:
             if e.errno == errno.EACCES:
                 return "some default data"
             # Not a permission error.
             raise
         else:
             with fp:
                 return fp.read()

   .. note::

      I/O operations may fail even when :func:`access` indicates that they would
      succeed, particularly for operations on network filesystems which may have
      permissions semantics beyond the usual POSIX permission-bit model.


.. data:: F_OK

   Value to pass as the *mode* parameter of :func:`access` to test the existence of
   *path*.


.. data:: R_OK

   Value to include in the *mode* parameter of :func:`access` to test the
   readability of *path*.


.. data:: W_OK

   Value to include in the *mode* parameter of :func:`access` to test the
   writability of *path*.


.. data:: X_OK

   Value to include in the *mode* parameter of :func:`access` to determine if
   *path* can be executed.


.. function:: chdir(path)

   .. index:: single: directory; changing

   Change the current working directory to *path*.

   Availability: Unix, Windows.


.. function:: fchdir(fd)

   Change the current working directory to the directory represented by the file
   descriptor *fd*.  The descriptor must refer to an opened directory, not an open
   file.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: getcwd()

   Return a string representing the current working directory.

   Availability: Unix, Windows.


.. function:: getcwdu()

   Return a Unicode object representing the current working directory.

   Availability: Unix, Windows.

   .. versionadded:: 2.3


.. function:: chflags(path, flags)

   Set the flags of *path* to the numeric *flags*. *flags* may take a combination
   (bitwise OR) of the following values (as defined in the :mod:`stat` module):

   * :data:`stat.UF_NODUMP`
   * :data:`stat.UF_IMMUTABLE`
   * :data:`stat.UF_APPEND`
   * :data:`stat.UF_OPAQUE`
   * :data:`stat.UF_NOUNLINK`
   * :data:`stat.UF_COMPRESSED`
   * :data:`stat.UF_HIDDEN`
   * :data:`stat.SF_ARCHIVED`
   * :data:`stat.SF_IMMUTABLE`
   * :data:`stat.SF_APPEND`
   * :data:`stat.SF_NOUNLINK`
   * :data:`stat.SF_SNAPSHOT`

   Availability: Unix.

   .. versionadded:: 2.6


.. function:: chroot(path)

   Change the root directory of the current process to *path*. Availability:
   Unix.

   .. versionadded:: 2.2


.. function:: chmod(path, mode)

   Change the mode of *path* to the numeric *mode*. *mode* may take one of the
   following values (as defined in the :mod:`stat` module) or bitwise ORed
   combinations of them:


   * :data:`stat.S_ISUID`
   * :data:`stat.S_ISGID`
   * :data:`stat.S_ENFMT`
   * :data:`stat.S_ISVTX`
   * :data:`stat.S_IREAD`
   * :data:`stat.S_IWRITE`
   * :data:`stat.S_IEXEC`
   * :data:`stat.S_IRWXU`
   * :data:`stat.S_IRUSR`
   * :data:`stat.S_IWUSR`
   * :data:`stat.S_IXUSR`
   * :data:`stat.S_IRWXG`
   * :data:`stat.S_IRGRP`
   * :data:`stat.S_IWGRP`
   * :data:`stat.S_IXGRP`
   * :data:`stat.S_IRWXO`
   * :data:`stat.S_IROTH`
   * :data:`stat.S_IWOTH`
   * :data:`stat.S_IXOTH`

   Availability: Unix, Windows.

   .. note::

      Although Windows supports :func:`chmod`, you can only  set the file's read-only
      flag with it (via the ``stat.S_IWRITE``  and ``stat.S_IREAD``
      constants or a corresponding integer value).  All other bits are
      ignored.


.. function:: chown(path, uid, gid)

   Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
   one of the ids unchanged, set it to -1.

   Availability: Unix.


.. function:: lchflags(path, flags)

   Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
   follow symbolic links.

   Availability: Unix.

   .. versionadded:: 2.6


.. function:: lchmod(path, mode)

   Change the mode of *path* to the numeric *mode*. If path is a symlink, this
   affects the symlink rather than the target. See the docs for :func:`chmod`
   for possible values of *mode*.

   Availability: Unix.

   .. versionadded:: 2.6


.. function:: lchown(path, uid, gid)

   Change the owner and group id of *path* to the numeric *uid* and *gid*. This
   function will not follow symbolic links.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: link(source, link_name)

   Create a hard link pointing to *source* named *link_name*.

   Availability: Unix.


.. function:: listdir(path)

   Return a list containing the names of the entries in the directory given by
   *path*.  The list is in arbitrary order.  It does not include the special
   entries ``'.'`` and ``'..'`` even if they are present in the
   directory.

   Availability: Unix, Windows.

   .. versionchanged:: 2.3
      On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
      a list of Unicode objects. Undecodable filenames will still be returned as
      string objects.


.. function:: lstat(path)

   Perform the equivalent of an :c:func:`lstat` system call on the given path.
   Similar to :func:`~os.stat`, but does not follow symbolic links.  On
   platforms that do not support symbolic links, this is an alias for
   :func:`~os.stat`.


.. function:: mkfifo(path[, mode])

   Create a FIFO (a named pipe) named *path* with numeric mode *mode*.  The default
   *mode* is ``0666`` (octal).  The current umask value is first masked out from
   the mode.

   Availability: Unix.

   FIFOs are pipes that can be accessed like regular files.  FIFOs exist until they
   are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
   rendezvous between "client" and "server" type processes: the server opens the
   FIFO for reading, and the client opens it for writing.  Note that :func:`mkfifo`
   doesn't open the FIFO --- it just creates the rendezvous point.


.. function:: mknod(filename[, mode=0600[, device=0]])

   Create a filesystem node (file, device special file or named pipe) named
   *filename*. *mode* specifies both the permissions to use and the type of node to
   be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
   ``stat.S_IFCHR``, ``stat.S_IFBLK``,
   and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
   For ``stat.S_IFCHR`` and
   ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
   :func:`os.makedev`), otherwise it is ignored.

   .. versionadded:: 2.3


.. function:: major(device)

   Extract the device major number from a raw device number (usually the
   :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).

   .. versionadded:: 2.3


.. function:: minor(device)

   Extract the device minor number from a raw device number (usually the
   :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).

   .. versionadded:: 2.3


.. function:: makedev(major, minor)

   Compose a raw device number from the major and minor device numbers.

   .. versionadded:: 2.3


.. function:: mkdir(path[, mode])

   Create a directory named *path* with numeric mode *mode*. The default *mode* is
   ``0777`` (octal).  If the directory already exists,
   :exc:`OSError` is raised.

   .. _mkdir_modebits:

   On some systems, *mode* is ignored.  Where it is used, the current umask
   value is first masked out.  If bits other than the last 9 (i.e. the last 3
   digits of the octal representation of the *mode*) are set, their meaning is
   platform-dependent.  On some platforms, they are ignored and you should call
   :func:`chmod` explicitly to set them.

   It is also possible to create temporary directories; see the
   :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.

   Availability: Unix, Windows.


.. function:: makedirs(path[, mode])

   .. index::
      single: directory; creating
      single: UNC paths; and os.makedirs()

   Recursive directory creation function.  Like :func:`mkdir`, but makes all
   intermediate-level directories needed to contain the leaf directory.  Raises an
   :exc:`error` exception if the leaf directory already exists or cannot be
   created.  The default *mode* is ``0777`` (octal).

   The *mode* parameter is passed to :func:`mkdir`; see :ref:`the mkdir()
   description <mkdir_modebits>` for how it is interpreted.

   .. note::

      :func:`makedirs` will become confused if the path elements to create include
      :data:`os.pardir`.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.3
      This function now handles UNC paths correctly.


.. function:: pathconf(path, name)

   Return system configuration information relevant to a named file. *name*
   specifies the configuration value to retrieve; it may be a string which is the
   name of a defined system value; these names are specified in a number of
   standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
   additional names as well.  The names known to the host operating system are
   given in the ``pathconf_names`` dictionary.  For configuration variables not
   included in that mapping, passing an integer for *name* is also accepted.

   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
   specific value for *name* is not supported by the host system, even if it is
   included in ``pathconf_names``, an :exc:`OSError` is raised with
   :const:`errno.EINVAL` for the error number.

   Availability: Unix.


.. data:: pathconf_names

   Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
   the integer values defined for those names by the host operating system.  This
   can be used to determine the set of names known to the system. Availability:
   Unix.


.. function:: readlink(path)

   Return a string representing the path to which the symbolic link points.  The
   result may be either an absolute or relative pathname; if it is relative, it may
   be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
   result)``.

   .. versionchanged:: 2.6
      If the *path* is a Unicode object the result will also be a Unicode object.

   Availability: Unix.


.. function:: remove(path)

   Remove (delete) the file *path*.  If *path* is a directory, :exc:`OSError` is
   raised; see :func:`rmdir` below to remove a directory.  This is identical to
   the :func:`unlink` function documented below.  On Windows, attempting to
   remove a file that is in use causes an exception to be raised; on Unix, the
   directory entry is removed but the storage allocated to the file is not made
   available until the original file is no longer in use.

   Availability: Unix, Windows.


.. function:: removedirs(path)

   .. index:: single: directory; deleting

   Remove directories recursively.  Works like :func:`rmdir` except that, if the
   leaf directory is successfully removed, :func:`removedirs`  tries to
   successively remove every parent directory mentioned in  *path* until an error
   is raised (which is ignored, because it generally means that a parent directory
   is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
   the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
   they are empty. Raises :exc:`OSError` if the leaf directory could not be
   successfully removed.

   .. versionadded:: 1.5.2


.. function:: rename(src, dst)

   Rename the file or directory *src* to *dst*.  If *dst* is a directory,
   :exc:`OSError` will be raised.  On Unix, if *dst* exists and is a file, it will
   be replaced silently if the user has permission.  The operation may fail on some
   Unix flavors if *src* and *dst* are on different filesystems.  If successful,
   the renaming will be an atomic operation (this is a POSIX requirement).  On
   Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
   file; there may be no way to implement an atomic rename when *dst* names an
   existing file.

   Availability: Unix, Windows.


.. function:: renames(old, new)

   Recursive directory or file renaming function. Works like :func:`rename`, except
   creation of any intermediate directories needed to make the new pathname good is
   attempted first. After the rename, directories corresponding to rightmost path
   segments of the old name will be pruned away using :func:`removedirs`.

   .. versionadded:: 1.5.2

   .. note::

      This function can fail with the new directory structure made if you lack
      permissions needed to remove the leaf directory or file.


.. function:: rmdir(path)

   Remove (delete) the directory *path*.  Only works when the directory is
   empty, otherwise, :exc:`OSError` is raised.  In order to remove whole
   directory trees, :func:`shutil.rmtree` can be used.

   Availability: Unix, Windows.


.. function:: stat(path)

   Perform the equivalent of a :c:func:`stat` system call on the given path.
   (This function follows symlinks; to stat a symlink use :func:`lstat`.)

   The return value is an object whose attributes correspond to the members
   of the :c:type:`stat` structure, namely:

   * :attr:`st_mode` - protection bits,
   * :attr:`st_ino` - inode number,
   * :attr:`st_dev` - device,
   * :attr:`st_nlink` - number of hard links,
   * :attr:`st_uid` - user id of owner,
   * :attr:`st_gid` - group id of owner,
   * :attr:`st_size` - size of file, in bytes,
   * :attr:`st_atime` - time of most recent access,
   * :attr:`st_mtime` - time of most recent content modification,
   * :attr:`st_ctime` - platform dependent; time of most recent metadata change on
     Unix, or the time of creation on Windows)

   .. versionchanged:: 2.3
      If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
      seconds. Fractions of a second may be reported if the system supports that.
      See :func:`stat_float_times` for further discussion.

   On some Unix systems (such as Linux), the following attributes may also be
   available:

   * :attr:`st_blocks` - number of 512-byte blocks allocated for file
   * :attr:`st_blksize` - filesystem blocksize for efficient file system I/O
   * :attr:`st_rdev` - type of device if an inode device
   * :attr:`st_flags` - user defined flags for file

   On other Unix systems (such as FreeBSD), the following attributes may be
   available (but may be only filled out if root tries to use them):

   * :attr:`st_gen` - file generation number
   * :attr:`st_birthtime` - time of file creation

   On RISCOS systems, the following attributes are also available:

   * :attr:`st_ftype` (file type)
   * :attr:`st_attrs` (attributes)
   * :attr:`st_obtype` (object type).

   .. note::

      The exact meaning and resolution of the :attr:`st_atime`,
      :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
      system and the file system. For example, on Windows systems using the FAT
      or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
      :attr:`st_atime` has only 1-day resolution.  See your operating system
      documentation for details.

   For backward compatibility, the return value of :func:`~os.stat` is also accessible
   as a tuple of at least 10 integers giving the most important (and portable)
   members of the :c:type:`stat` structure, in the order :attr:`st_mode`,
   :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
   :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
   :attr:`st_ctime`. More items may be added at the end by some implementations.

   .. index:: module: stat

   The standard module :mod:`stat` defines functions and constants that are useful
   for extracting information from a :c:type:`stat` structure. (On Windows, some
   items are filled with dummy values.)

   Example::

      >>> import os
      >>> statinfo = os.stat('somefile.txt')
      >>> statinfo
      (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)
      >>> statinfo.st_size
      926

   Availability: Unix, Windows.

   .. versionchanged:: 2.2
      Added access to values as attributes of the returned object.

   .. versionchanged:: 2.5
      Added :attr:`st_gen` and :attr:`st_birthtime`.


.. function:: stat_float_times([newvalue])

   Determine whether :class:`stat_result` represents time stamps as float objects.
   If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
   ``False``, future calls return ints. If *newvalue* is omitted, return the
   current setting.

   For compatibility with older Python versions, accessing :class:`stat_result` as
   a tuple always returns integers.

   .. versionchanged:: 2.5
      Python now returns float values by default. Applications which do not work
      correctly with floating point time stamps can use this function to restore the
      old behaviour.

   The resolution of the timestamps (that is the smallest possible fraction)
   depends on the system. Some systems only support second resolution; on these
   systems, the fraction will always be zero.

   It is recommended that this setting is only changed at program startup time in
   the *__main__* module; libraries should never change this setting. If an
   application uses a library that works incorrectly if floating point time stamps
   are processed, this application should turn the feature off until the library
   has been corrected.


.. function:: statvfs(path)

   Perform a :c:func:`statvfs` system call on the given path.  The return value is
   an object whose attributes describe the filesystem on the given path, and
   correspond to the members of the :c:type:`statvfs` structure, namely:
   :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
   :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
   :attr:`f_flag`, :attr:`f_namemax`.

   .. index:: module: statvfs

   For backward compatibility, the return value is also accessible as a tuple whose
   values correspond to the attributes, in the order given above. The standard
   module :mod:`statvfs` defines constants that are useful for extracting
   information from a :c:type:`statvfs` structure when accessing it as a sequence;
   this remains useful when writing code that needs to work with versions of Python
   that don't support accessing the fields as attributes.

   Availability: Unix.

   .. versionchanged:: 2.2
      Added access to values as attributes of the returned object.


.. function:: symlink(source, link_name)

   Create a symbolic link pointing to *source* named *link_name*.

   Availability: Unix.


.. function:: tempnam([dir[, prefix]])

   Return a unique path name that is reasonable for creating a temporary file.
   This will be an absolute path that names a potential directory entry in the
   directory *dir* or a common location for temporary files if *dir* is omitted or
   ``None``.  If given and not ``None``, *prefix* is used to provide a short prefix
   to the filename.  Applications are responsible for properly creating and
   managing files created using paths returned by :func:`tempnam`; no automatic
   cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
   overrides *dir*, while on Windows :envvar:`TMP` is used.  The specific
   behavior of this function depends on the C library implementation; some aspects
   are underspecified in system documentation.

   .. warning::

      Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
      :func:`tmpfile` (section :ref:`os-newstreams`) instead.

   Availability: Unix, Windows.


.. function:: tmpnam()

   Return a unique path name that is reasonable for creating a temporary file.
   This will be an absolute path that names a potential directory entry in a common
   location for temporary files.  Applications are responsible for properly
   creating and managing files created using paths returned by :func:`tmpnam`; no
   automatic cleanup is provided.

   .. warning::

      Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
      :func:`tmpfile` (section :ref:`os-newstreams`) instead.

   Availability: Unix, Windows.  This function probably shouldn't be used on
   Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
   name in the root directory of the current drive, and that's generally a poor
   location for a temp file (depending on privileges, you may not even be able to
   open a file using this name).


.. data:: TMP_MAX

   The maximum number of unique names that :func:`tmpnam` will generate before
   reusing names.


.. function:: unlink(path)

   Remove (delete) the file *path*.  This is the same function as
   :func:`remove`; the :func:`unlink` name is its traditional Unix
   name.

   Availability: Unix, Windows.


.. function:: utime(path, times)

   Set the access and modified times of the file specified by *path*. If *times*
   is ``None``, then the file's access and modified times are set to the current
   time. (The effect is similar to running the Unix program :program:`touch` on
   the path.)  Otherwise, *times* must be a 2-tuple of numbers, of the form
   ``(atime, mtime)`` which is used to set the access and modified times,
   respectively. Whether a directory can be given for *path* depends on whether
   the operating system implements directories as files (for example, Windows
   does not).  Note that the exact times you set here may not be returned by a
   subsequent :func:`~os.stat` call, depending on the resolution with which your
   operating system records access and modification times; see :func:`~os.stat`.

   .. versionchanged:: 2.0
      Added support for ``None`` for *times*.

   Availability: Unix, Windows.


.. function:: walk(top, topdown=True, onerror=None, followlinks=False)

   .. index::
      single: directory; walking
      single: directory; traversal

   Generate the file names in a directory tree by walking the tree
   either top-down or bottom-up. For each directory in the tree rooted at directory
   *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
   filenames)``.

   *dirpath* is a string, the path to the directory.  *dirnames* is a list of the
   names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
   *filenames* is a list of the names of the non-directory files in *dirpath*.
   Note that the names in the lists contain no path components.  To get a full path
   (which begins with *top*) to a file or directory in *dirpath*, do
   ``os.path.join(dirpath, name)``.

   If optional argument *topdown* is ``True`` or not specified, the triple for a
   directory is generated before the triples for any of its subdirectories
   (directories are generated top-down).  If *topdown* is ``False``, the triple
   for a directory is generated after the triples for all of its subdirectories
   (directories are generated bottom-up). No matter the value of *topdown*, the
   list of subdirectories is retrieved before the tuples for the directory and
   its subdirectories are generated.

   When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
   (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
   recurse into the subdirectories whose names remain in *dirnames*; this can be
   used to prune the search, impose a specific order of visiting, or even to inform
   :func:`walk` about directories the caller creates or renames before it resumes
   :func:`walk` again.  Modifying *dirnames* when *topdown* is ``False`` has
   no effect on the behavior of the walk, because in bottom-up mode the directories
   in *dirnames* are generated before *dirpath* itself is generated.

   By default, errors from the :func:`listdir` call are ignored.  If optional
   argument *onerror* is specified, it should be a function; it will be called with
   one argument, an :exc:`OSError` instance.  It can report the error to continue
   with the walk, or raise the exception to abort the walk.  Note that the filename
   is available as the ``filename`` attribute of the exception object.

   By default, :func:`walk` will not walk down into symbolic links that resolve to
   directories. Set *followlinks* to ``True`` to visit directories pointed to by
   symlinks, on systems that support them.

   .. versionadded:: 2.6
      The *followlinks* parameter.

   .. note::

      Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
      link points to a parent directory of itself. :func:`walk` does not keep track of
      the directories it visited already.

   .. note::

      If you pass a relative pathname, don't change the current working directory
      between resumptions of :func:`walk`.  :func:`walk` never changes the current
      directory, and assumes that its caller doesn't either.

   This example displays the number of bytes taken by non-directory files in each
   directory under the starting directory, except that it doesn't look under any
   CVS subdirectory::

      import os
      from os.path import join, getsize
      for root, dirs, files in os.walk('python/Lib/email'):
          print root, "consumes",
          print sum(getsize(join(root, name)) for name in files),
          print "bytes in", len(files), "non-directory files"
          if 'CVS' in dirs:
              dirs.remove('CVS')  # don't visit CVS directories

   In the next example, walking the tree bottom-up is essential: :func:`rmdir`
   doesn't allow deleting a directory before the directory is empty::

      # Delete everything reachable from the directory named in "top",
      # assuming there are no symbolic links.
      # CAUTION:  This is dangerous!  For example, if top == '/', it
      # could delete all your disk files.
      import os
      for root, dirs, files in os.walk(top, topdown=False):
          for name in files:
              os.remove(os.path.join(root, name))
          for name in dirs:
              os.rmdir(os.path.join(root, name))

   .. versionadded:: 2.3


.. _os-process:

Process Management
------------------

These functions may be used to create and manage processes.

The various :func:`exec\* <execl>` functions take a list of arguments for the new
program loaded into the process.  In each case, the first of these arguments is
passed to the new program as its own name rather than as an argument a user may
have typed on a command line.  For the C programmer, this is the ``argv[0]``
passed to a program's :c:func:`main`.  For example, ``os.execv('/bin/echo',
['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
to be ignored.


.. function:: abort()

   Generate a :const:`SIGABRT` signal to the current process.  On Unix, the default
   behavior is to produce a core dump; on Windows, the process immediately returns
   an exit code of ``3``.  Be aware that calling this function will not call the
   Python signal handler registered for :const:`SIGABRT` with
   :func:`signal.signal`.

   Availability: Unix, Windows.


.. function:: execl(path, arg0, arg1, ...)
              execle(path, arg0, arg1, ..., env)
              execlp(file, arg0, arg1, ...)
              execlpe(file, arg0, arg1, ..., env)
              execv(path, args)
              execve(path, args, env)
              execvp(file, args)
              execvpe(file, args, env)

   These functions all execute a new program, replacing the current process; they
   do not return.  On Unix, the new executable is loaded into the current process,
   and will have the same process id as the caller.  Errors will be reported as
   :exc:`OSError` exceptions.

   The current process is replaced immediately. Open file objects and
   descriptors are not flushed, so if there may be data buffered
   on these open files, you should flush them using
   :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
   :func:`exec\* <execl>` function.

   The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
   command-line arguments are passed.  The "l" variants are perhaps the easiest
   to work with if the number of parameters is fixed when the code is written; the
   individual parameters simply become additional parameters to the :func:`execl\*`
   functions.  The "v" variants are good when the number of parameters is
   variable, with the arguments being passed in a list or tuple as the *args*
   parameter.  In either case, the arguments to the child process should start with
   the name of the command being run, but this is not enforced.

   The variants which include a "p" near the end (:func:`execlp`,
   :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
   :envvar:`PATH` environment variable to locate the program *file*.  When the
   environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
   discussed in the next paragraph), the new environment is used as the source of
   the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
   :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
   locate the executable; *path* must contain an appropriate absolute or relative
   path.

   For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
   that these all end in "e"), the *env* parameter must be a mapping which is
   used to define the environment variables for the new process (these are used
   instead of the current process' environment); the functions :func:`execl`,
   :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
   inherit the environment of the current process.

   Availability: Unix, Windows.


.. function:: _exit(n)

   Exit the process with status *n*, without calling cleanup handlers, flushing
   stdio buffers, etc.

   Availability: Unix, Windows.

   .. note::

      The standard way to exit is ``sys.exit(n)``.  :func:`_exit` should
      normally only be used in the child process after a :func:`fork`.

The following exit codes are defined and can be used with :func:`_exit`,
although they are not required.  These are typically used for system programs
written in Python, such as a mail server's external command delivery program.

.. note::

   Some of these may not be available on all Unix platforms, since there is some
   variation.  These constants are defined where they are defined by the underlying
   platform.


.. data:: EX_OK

   Exit code that means no error occurred.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_USAGE

   Exit code that means the command was used incorrectly, such as when the wrong
   number of arguments are given.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_DATAERR

   Exit code that means the input data was incorrect.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_NOINPUT

   Exit code that means an input file did not exist or was not readable.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_NOUSER

   Exit code that means a specified user did not exist.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_NOHOST

   Exit code that means a specified host did not exist.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_UNAVAILABLE

   Exit code that means that a required service is unavailable.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_SOFTWARE

   Exit code that means an internal software error was detected.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_OSERR

   Exit code that means an operating system error was detected, such as the
   inability to fork or create a pipe.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_OSFILE

   Exit code that means some system file did not exist, could not be opened, or had
   some other kind of error.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_CANTCREAT

   Exit code that means a user specified output file could not be created.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_IOERR

   Exit code that means that an error occurred while doing I/O on some file.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_TEMPFAIL

   Exit code that means a temporary failure occurred.  This indicates something
   that may not really be an error, such as a network connection that couldn't be
   made during a retryable operation.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_PROTOCOL

   Exit code that means that a protocol exchange was illegal, invalid, or not
   understood.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_NOPERM

   Exit code that means that there were insufficient permissions to perform the
   operation (but not intended for file system problems).

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_CONFIG

   Exit code that means that some kind of configuration error occurred.

   Availability: Unix.

   .. versionadded:: 2.3


.. data:: EX_NOTFOUND

   Exit code that means something like "an entry was not found".

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: fork()

   Fork a child process.  Return ``0`` in the child and the child's process id in the
   parent.  If an error occurs :exc:`OSError` is raised.

   Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
   known issues when using fork() from a thread.

   .. warning::

      See :mod:`ssl` for applications that use the SSL module with fork().

   Availability: Unix.


.. function:: forkpty()

   Fork a child process, using a new pseudo-terminal as the child's controlling
   terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
   new child's process id in the parent, and *fd* is the file descriptor of the
   master end of the pseudo-terminal.  For a more portable approach, use the
   :mod:`pty` module.  If an error occurs :exc:`OSError` is raised.

   Availability: some flavors of Unix.


.. function:: kill(pid, sig)

   .. index::
      single: process; killing
      single: process; signalling

   Send signal *sig* to the process *pid*.  Constants for the specific signals
   available on the host platform are defined in the :mod:`signal` module.

   Windows: The :data:`signal.CTRL_C_EVENT` and
   :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
   only be sent to console processes which share a common console window,
   e.g., some subprocesses. Any other value for *sig* will cause the process
   to be unconditionally killed by the TerminateProcess API, and the exit code
   will be set to *sig*. The Windows version of :func:`kill` additionally takes
   process handles to be killed.

   .. versionadded:: 2.7 Windows support


.. function:: killpg(pgid, sig)

   .. index::
      single: process; killing
      single: process; signalling

   Send the signal *sig* to the process group *pgid*.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: nice(increment)

   Add *increment* to the process's "niceness".  Return the new niceness.

   Availability: Unix.


.. function:: plock(op)

   Lock program segments into memory.  The value of *op* (defined in
   ``<sys/lock.h>``) determines which segments are locked.

   Availability: Unix.


.. function:: popen(...)
              popen2(...)
              popen3(...)
              popen4(...)
   :noindex:

   Run child processes, returning opened pipes for communications.  These functions
   are described in section :ref:`os-newstreams`.


.. function:: spawnl(mode, path, ...)
              spawnle(mode, path, ..., env)
              spawnlp(mode, file, ...)
              spawnlpe(mode, file, ..., env)
              spawnv(mode, path, args)
              spawnve(mode, path, args, env)
              spawnvp(mode, file, args)
              spawnvpe(mode, file, args, env)

   Execute the program *path* in a new process.

   (Note that the :mod:`subprocess` module provides more powerful facilities for
   spawning new processes and retrieving their results; using that module is
   preferable to using these functions.  Check especially the
   :ref:`subprocess-replacements` section.)

   If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
   process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
   exits normally, or ``-signal``, where *signal* is the signal that killed the
   process.  On Windows, the process id will actually be the process handle, so can
   be used with the :func:`waitpid` function.

   The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
   command-line arguments are passed.  The "l" variants are perhaps the easiest
   to work with if the number of parameters is fixed when the code is written; the
   individual parameters simply become additional parameters to the
   :func:`spawnl\*` functions.  The "v" variants are good when the number of
   parameters is variable, with the arguments being passed in a list or tuple as
   the *args* parameter.  In either case, the arguments to the child process must
   start with the name of the command being run.

   The variants which include a second "p" near the end (:func:`spawnlp`,
   :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
   :envvar:`PATH` environment variable to locate the program *file*.  When the
   environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
   discussed in the next paragraph), the new environment is used as the source of
   the :envvar:`PATH` variable.  The other variants, :func:`spawnl`,
   :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
   :envvar:`PATH` variable to locate the executable; *path* must contain an
   appropriate absolute or relative path.

   For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
   (note that these all end in "e"), the *env* parameter must be a mapping
   which is used to define the environment variables for the new process (they are
   used instead of the current process' environment); the functions
   :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
   the new process to inherit the environment of the current process.  Note that
   keys and values in the *env* dictionary must be strings; invalid keys or
   values will cause the function to fail, with a return value of ``127``.

   As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
   equivalent::

      import os
      os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')

      L = ['cp', 'index.html', '/dev/null']
      os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)

   Availability: Unix, Windows.  :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
   and :func:`spawnvpe` are not available on Windows.  :func:`spawnle` and
   :func:`spawnve` are not thread-safe on Windows; we advise you to use the
   :mod:`subprocess` module instead.

   .. versionadded:: 1.6


.. data:: P_NOWAIT
          P_NOWAITO

   Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
   functions.  If either of these values is given, the :func:`spawn\*` functions
   will return as soon as the new process has been created, with the process id as
   the return value.

   Availability: Unix, Windows.

   .. versionadded:: 1.6


.. data:: P_WAIT

   Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
   functions.  If this is given as *mode*, the :func:`spawn\*` functions will not
   return until the new process has run to completion and will return the exit code
   of the process the run is successful, or ``-signal`` if a signal kills the
   process.

   Availability: Unix, Windows.

   .. versionadded:: 1.6


.. data:: P_DETACH
          P_OVERLAY

   Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
   functions.  These are less portable than those listed above. :const:`P_DETACH`
   is similar to :const:`P_NOWAIT`, but the new process is detached from the
   console of the calling process. If :const:`P_OVERLAY` is used, the current
   process will be replaced; the :func:`spawn\*` function will not return.

   Availability: Windows.

   .. versionadded:: 1.6


.. function:: startfile(path[, operation])

   Start a file with its associated application.

   When *operation* is not specified or ``'open'``, this acts like double-clicking
   the file in Windows Explorer, or giving the file name as an argument to the
   :program:`start` command from the interactive command shell: the file is opened
   with whatever application (if any) its extension is associated.

   When another *operation* is given, it must be a "command verb" that specifies
   what should be done with the file. Common verbs documented by Microsoft are
   ``'print'`` and  ``'edit'`` (to be used on files) as well as ``'explore'`` and
   ``'find'`` (to be used on directories).

   :func:`startfile` returns as soon as the associated application is launched.
   There is no option to wait for the application to close, and no way to retrieve
   the application's exit status.  The *path* parameter is relative to the current
   directory.  If you want to use an absolute path, make sure the first character
   is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function
   doesn't work if it is.  Use the :func:`os.path.normpath` function to ensure that
   the path is properly encoded for Win32.

   Availability: Windows.

   .. versionadded:: 2.0

   .. versionadded:: 2.5
      The *operation* parameter.


.. function:: system(command)

   Execute the command (a string) in a subshell.  This is implemented by calling
   the Standard C function :c:func:`system`, and has the same limitations.
   Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
   executed command.

   On Unix, the return value is the exit status of the process encoded in the
   format specified for :func:`wait`.  Note that POSIX does not specify the meaning
   of the return value of the C :c:func:`system` function, so the return value of
   the Python function is system-dependent.

   On Windows, the return value is that returned by the system shell after running
   *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
   :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
   :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
   the command run; on systems using a non-native shell, consult your shell
   documentation.

   The :mod:`subprocess` module provides more powerful facilities for spawning new
   processes and retrieving their results; using that module is preferable to using
   this function.  See the
   :ref:`subprocess-replacements` section in the :mod:`subprocess` documentation
   for some helpful recipes.

   Availability: Unix, Windows.


.. function:: times()

   Return a 5-tuple of floating point numbers indicating accumulated (processor
   or other) times, in seconds.  The items are: user time, system time,
   children's user time, children's system time, and elapsed real time since a
   fixed point in the past, in that order.  See the Unix manual page
   :manpage:`times(2)` or the corresponding Windows Platform API documentation.
   On Windows, only the first two items are filled, the others are zero.

   Availability: Unix, Windows


.. function:: wait()

   Wait for completion of a child process, and return a tuple containing its pid
   and exit status indication: a 16-bit number, whose low byte is the signal number
   that killed the process, and whose high byte is the exit status (if the signal
   number is zero); the high bit of the low byte is set if a core file was
   produced.

   Availability: Unix.


.. function:: waitpid(pid, options)

   The details of this function differ on Unix and Windows.

   On Unix: Wait for completion of a child process given by process id *pid*, and
   return a tuple containing its process id and exit status indication (encoded as
   for :func:`wait`).  The semantics of the call are affected by the value of the
   integer *options*, which should be ``0`` for normal operation.

   If *pid* is greater than ``0``, :func:`waitpid` requests status information for
   that specific process.  If *pid* is ``0``, the request is for the status of any
   child in the process group of the current process.  If *pid* is ``-1``, the
   request pertains to any child of the current process.  If *pid* is less than
   ``-1``, status is requested for any process in the process group ``-pid`` (the
   absolute value of *pid*).

   An :exc:`OSError` is raised with the value of errno when the syscall
   returns -1.

   On Windows: Wait for completion of a process given by process handle *pid*, and
   return a tuple containing *pid*, and its exit status shifted left by 8 bits
   (shifting makes cross-platform use of the function easier). A *pid* less than or
   equal to ``0`` has no special meaning on Windows, and raises an exception. The
   value of integer *options* has no effect. *pid* can refer to any process whose
   id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
   functions called with :const:`P_NOWAIT` return suitable process handles.


.. function:: wait3(options)

   Similar to :func:`waitpid`, except no process id argument is given and a
   3-element tuple containing the child's process id, exit status indication, and
   resource usage information is returned.  Refer to :mod:`resource`.\
   :func:`~resource.getrusage` for details on resource usage information.  The
   option argument is the same as that provided to :func:`waitpid` and
   :func:`wait4`.

   Availability: Unix.

   .. versionadded:: 2.5


.. function:: wait4(pid, options)

   Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
   process id, exit status indication, and resource usage information is returned.
   Refer to :mod:`resource`.\ :func:`~resource.getrusage` for details on
   resource usage information.  The arguments to :func:`wait4` are the same as
   those provided to :func:`waitpid`.

   Availability: Unix.

   .. versionadded:: 2.5


.. data:: WNOHANG

   The option for :func:`waitpid` to return immediately if no child process status
   is available immediately. The function returns ``(0, 0)`` in this case.

   Availability: Unix.


.. data:: WCONTINUED

   This option causes child processes to be reported if they have been continued
   from a job control stop since their status was last reported.

   Availability: Some Unix systems.

   .. versionadded:: 2.3


.. data:: WUNTRACED

   This option causes child processes to be reported if they have been stopped but
   their current state has not been reported since they were stopped.

   Availability: Unix.

   .. versionadded:: 2.3

The following functions take a process status code as returned by
:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter.  They may be
used to determine the disposition of a process.


.. function:: WCOREDUMP(status)

   Return ``True`` if a core dump was generated for the process, otherwise
   return ``False``.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: WIFCONTINUED(status)

   Return ``True`` if the process has been continued from a job control stop,
   otherwise return ``False``.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: WIFSTOPPED(status)

   Return ``True`` if the process has been stopped, otherwise return
   ``False``.

   Availability: Unix.


.. function:: WIFSIGNALED(status)

   Return ``True`` if the process exited due to a signal, otherwise return
   ``False``.

   Availability: Unix.


.. function:: WIFEXITED(status)

   Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
   otherwise return ``False``.

   Availability: Unix.


.. function:: WEXITSTATUS(status)

   If ``WIFEXITED(status)`` is true, return the integer parameter to the
   :manpage:`exit(2)` system call.  Otherwise, the return value is meaningless.

   Availability: Unix.


.. function:: WSTOPSIG(status)

   Return the signal which caused the process to stop.

   Availability: Unix.


.. function:: WTERMSIG(status)

   Return the signal which caused the process to exit.

   Availability: Unix.


.. _os-path:

Miscellaneous System Information
--------------------------------


.. function:: confstr(name)

   Return string-valued system configuration values. *name* specifies the
   configuration value to retrieve; it may be a string which is the name of a
   defined system value; these names are specified in a number of standards (POSIX,
   Unix 95, Unix 98, and others).  Some platforms define additional names as well.
   The names known to the host operating system are given as the keys of the
   ``confstr_names`` dictionary.  For configuration variables not included in that
   mapping, passing an integer for *name* is also accepted.

   If the configuration value specified by *name* isn't defined, ``None`` is
   returned.

   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
   specific value for *name* is not supported by the host system, even if it is
   included in ``confstr_names``, an :exc:`OSError` is raised with
   :const:`errno.EINVAL` for the error number.

   Availability: Unix


.. data:: confstr_names

   Dictionary mapping names accepted by :func:`confstr` to the integer values
   defined for those names by the host operating system. This can be used to
   determine the set of names known to the system.

   Availability: Unix.


.. function:: getloadavg()

   Return the number of processes in the system run queue averaged over the last
   1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
   unobtainable.

   Availability: Unix.

   .. versionadded:: 2.3


.. function:: sysconf(name)

   Return integer-valued system configuration values. If the configuration value
   specified by *name* isn't defined, ``-1`` is returned.  The comments regarding
   the *name* parameter for :func:`confstr` apply here as well; the dictionary that
   provides information on the known names is given by ``sysconf_names``.

   Availability: Unix.


.. data:: sysconf_names

   Dictionary mapping names accepted by :func:`sysconf` to the integer values
   defined for those names by the host operating system. This can be used to
   determine the set of names known to the system.

   Availability: Unix.

The following data values are used to support path manipulation operations.  These
are defined for all platforms.

Higher-level operations on pathnames are defined in the :mod:`os.path` module.


.. data:: curdir

   The constant string used by the operating system to refer to the current
   directory. This is ``'.'`` for Windows and POSIX. Also available via
   :mod:`os.path`.


.. data:: pardir

   The constant string used by the operating system to refer to the parent
   directory. This is ``'..'`` for Windows and POSIX. Also available via
   :mod:`os.path`.


.. data:: sep

   The character used by the operating system to separate pathname components.
   This is ``'/'`` for POSIX and ``'\\'`` for Windows.  Note that knowing this
   is not sufficient to be able to parse or concatenate pathnames --- use
   :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
   useful. Also available via :mod:`os.path`.


.. data:: altsep

   An alternative character used by the operating system to separate pathname
   components, or ``None`` if only one separator character exists.  This is set to
   ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
   :mod:`os.path`.


.. data:: extsep

   The character which separates the base filename from the extension; for example,
   the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.

   .. versionadded:: 2.2


.. data:: pathsep

   The character conventionally used by the operating system to separate search
   path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
   Windows. Also available via :mod:`os.path`.


.. data:: defpath

   The default search path used by :func:`exec\*p\* <execl>` and
   :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
   key. Also available via :mod:`os.path`.


.. data:: linesep

   The string used to separate (or, rather, terminate) lines on the current
   platform.  This may be a single character, such as ``'\n'`` for POSIX, or
   multiple characters, for example, ``'\r\n'`` for Windows. Do not use
   *os.linesep* as a line terminator when writing files opened in text mode (the
   default); use a single ``'\n'`` instead, on all platforms.


.. data:: devnull

   The file path of the null device. For example: ``'/dev/null'`` for
   POSIX, ``'nul'`` for Windows.  Also available via :mod:`os.path`.

   .. versionadded:: 2.4


.. _os-miscfunc:

Miscellaneous Functions
-----------------------


.. function:: urandom(n)

   Return a string of *n* random bytes suitable for cryptographic use.

   This function returns random bytes from an OS-specific randomness source.  The
   returned data should be unpredictable enough for cryptographic applications,
   though its exact quality depends on the OS implementation.  On a UNIX-like
   system this will query ``/dev/urandom``, and on Windows it will use
   ``CryptGenRandom()``.  If a randomness source is not found,
   :exc:`NotImplementedError` will be raised.

   For an easy-to-use interface to the random number generator
   provided by your platform, please see :class:`random.SystemRandom`.

   .. versionadded:: 2.4
PK	%�\@U.ޝC�C)html/_sources/library/ossaudiodev.rst.txtnu�[���
:mod:`ossaudiodev` --- Access to OSS-compatible audio devices
=============================================================

.. module:: ossaudiodev
   :platform: Linux, FreeBSD
   :synopsis: Access to OSS-compatible audio devices.


.. versionadded:: 2.3

This module allows you to access the OSS (Open Sound System) audio interface.
OSS is available for a wide range of open-source and commercial Unices, and is
the standard audio interface for Linux and recent versions of FreeBSD.

.. Things will get more complicated for future Linux versions, since
   ALSA is in the standard kernel as of 2.5.x.  Presumably if you
   use ALSA, you'll have to make sure its OSS compatibility layer
   is active to use ossaudiodev, but you're gonna need it for the vast
   majority of Linux audio apps anyway.

   Sounds like things are also complicated for other BSDs.  In response
   to my python-dev query, Thomas Wouters said:

   > Likewise, googling shows OpenBSD also uses OSS/Free -- the commercial
   > OSS installation manual tells you to remove references to OSS/Free from the
   > kernel :)

   but Aleksander Piotrowsk actually has an OpenBSD box, and he quotes
   from its <soundcard.h>:
   >  * WARNING!  WARNING!
   >  * This is an OSS (Linux) audio emulator.
   >  * Use the Native NetBSD API for developing new code, and this
   >  * only for compiling Linux programs.

   There's also an ossaudio manpage on OpenBSD that explains things
   further.  Presumably NetBSD and OpenBSD have a different standard
   audio interface.  That's the great thing about standards, there are so
   many to choose from ... ;-)

   This probably all warrants a footnote or two, but I don't understand
   things well enough right now to write it!   --GPW


.. seealso::

   `Open Sound System Programmer's Guide <http://www.opensound.com/pguide/oss.pdf>`_
      the official documentation for the OSS C API

   The module defines a large number of constants supplied by the OSS device
   driver; see ``<sys/soundcard.h>`` on either Linux or FreeBSD for a listing.

:mod:`ossaudiodev` defines the following variables and functions:


.. exception:: OSSAudioError

   This exception is raised on certain errors.  The argument is a string describing
   what went wrong.

   (If :mod:`ossaudiodev` receives an error from a system call such as
   :c:func:`open`, :c:func:`write`, or :c:func:`ioctl`, it raises :exc:`IOError`.
   Errors detected directly by :mod:`ossaudiodev` result in :exc:`OSSAudioError`.)

   (For backwards compatibility, the exception class is also available as
   ``ossaudiodev.error``.)


.. function:: open(mode)
              open(device, mode)

   Open an audio device and return an OSS audio device object.  This object
   supports many file-like methods, such as :meth:`read`, :meth:`write`, and
   :meth:`fileno` (although there are subtle differences between conventional Unix
   read/write semantics and those of OSS audio devices).  It also supports a number
   of audio-specific methods; see below for the complete list of methods.

   *device* is the audio device filename to use.  If it is not specified, this
   module first looks in the environment variable :envvar:`AUDIODEV` for a device
   to use.  If not found, it falls back to :file:`/dev/dsp`.

   *mode* is one of ``'r'`` for read-only (record) access, ``'w'`` for
   write-only (playback) access and ``'rw'`` for both. Since many sound cards
   only allow one process to have the recorder or player open at a time, it is a
   good idea to open the device only for the activity needed.  Further, some
   sound cards are half-duplex: they can be opened for reading or writing, but
   not both at once.

   Note the unusual calling syntax: the *first* argument is optional, and the
   second is required.  This is a historical artifact for compatibility with the
   older :mod:`linuxaudiodev` module which :mod:`ossaudiodev` supersedes.

   .. XXX it might also be motivated
      by my unfounded-but-still-possibly-true belief that the default
      audio device varies unpredictably across operating systems.  -GW


.. function:: openmixer([device])

   Open a mixer device and return an OSS mixer device object.   *device* is the
   mixer device filename to use.  If it is not specified, this module first looks
   in the environment variable :envvar:`MIXERDEV` for a device to use.  If not
   found, it falls back to :file:`/dev/mixer`.


.. _ossaudio-device-objects:

Audio Device Objects
--------------------

Before you can write to or read from an audio device, you must call three
methods in the correct order:

#. :meth:`setfmt` to set the output format

#. :meth:`channels` to set the number of channels

#. :meth:`speed` to set the sample rate

Alternately, you can use the :meth:`setparameters` method to set all three audio
parameters at once.  This is more convenient, but may not be as flexible in all
cases.

The audio device objects returned by :func:`.open` define the following methods
and (read-only) attributes:


.. method:: oss_audio_device.close()

   Explicitly close the audio device.  When you are done writing to or reading from
   an audio device, you should explicitly close it.  A closed device cannot be used
   again.


.. method:: oss_audio_device.fileno()

   Return the file descriptor associated with the device.


.. method:: oss_audio_device.read(size)

   Read *size* bytes from the audio input and return them as a Python string.
   Unlike most Unix device drivers, OSS audio devices in blocking mode (the
   default) will block :func:`read` until the entire requested amount of data is
   available.


.. method:: oss_audio_device.write(data)

   Write the Python string *data* to the audio device and return the number of
   bytes written.  If the audio device is in blocking mode (the default), the
   entire string is always written (again, this is different from usual Unix device
   semantics).  If the device is in non-blocking mode, some data may not be written
   ---see :meth:`writeall`.


.. method:: oss_audio_device.writeall(data)

   Write the entire Python string *data* to the audio device: waits until the audio
   device is able to accept data, writes as much data as it will accept, and
   repeats until *data* has been completely written. If the device is in blocking
   mode (the default), this has the same effect as :meth:`write`; :meth:`writeall`
   is only useful in non-blocking mode.  Has no return value, since the amount of
   data written is always equal to the amount of data supplied.

The following methods each map to exactly one :c:func:`ioctl` system call.  The
correspondence is obvious: for example, :meth:`setfmt` corresponds to the
``SNDCTL_DSP_SETFMT`` ioctl, and :meth:`sync` to ``SNDCTL_DSP_SYNC`` (this can
be useful when consulting the OSS documentation).  If the underlying
:c:func:`ioctl` fails, they all raise :exc:`IOError`.


.. method:: oss_audio_device.nonblock()

   Put the device into non-blocking mode.  Once in non-blocking mode, there is no
   way to return it to blocking mode.


.. method:: oss_audio_device.getfmts()

   Return a bitmask of the audio output formats supported by the soundcard.  Some
   of the formats supported by OSS are:

   +-------------------------+---------------------------------------------+
   | Format                  | Description                                 |
   +=========================+=============================================+
   | :const:`AFMT_MU_LAW`    | a logarithmic encoding (used by Sun ``.au`` |
   |                         | files and :file:`/dev/audio`)               |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_A_LAW`     | a logarithmic encoding                      |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_IMA_ADPCM` | a 4:1 compressed format defined by the      |
   |                         | Interactive Multimedia Association          |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_U8`        | Unsigned, 8-bit audio                       |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_S16_LE`    | Signed, 16-bit audio, little-endian byte    |
   |                         | order (as used by Intel processors)         |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_S16_BE`    | Signed, 16-bit audio, big-endian byte order |
   |                         | (as used by 68k, PowerPC, Sparc)            |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_S8`        | Signed, 8 bit audio                         |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_U16_LE`    | Unsigned, 16-bit little-endian audio        |
   +-------------------------+---------------------------------------------+
   | :const:`AFMT_U16_BE`    | Unsigned, 16-bit big-endian audio           |
   +-------------------------+---------------------------------------------+

   Consult the OSS documentation for a full list of audio formats, and note that
   most devices support only a subset of these formats.  Some older devices only
   support :const:`AFMT_U8`; the most common format used today is
   :const:`AFMT_S16_LE`.


.. method:: oss_audio_device.setfmt(format)

   Try to set the current audio format to *format*---see :meth:`getfmts` for a
   list.  Returns the audio format that the device was set to, which may not be the
   requested format.  May also be used to return the current audio format---do this
   by passing an "audio format" of :const:`AFMT_QUERY`.


.. method:: oss_audio_device.channels(nchannels)

   Set the number of output channels to *nchannels*.  A value of 1 indicates
   monophonic sound, 2 stereophonic.  Some devices may have more than 2 channels,
   and some high-end devices may not support mono. Returns the number of channels
   the device was set to.


.. method:: oss_audio_device.speed(samplerate)

   Try to set the audio sampling rate to *samplerate* samples per second.  Returns
   the rate actually set.  Most sound devices don't support arbitrary sampling
   rates.  Common rates are:

   +-------+-------------------------------------------+
   | Rate  | Description                               |
   +=======+===========================================+
   | 8000  | default rate for :file:`/dev/audio`       |
   +-------+-------------------------------------------+
   | 11025 | speech recording                          |
   +-------+-------------------------------------------+
   | 22050 |                                           |
   +-------+-------------------------------------------+
   | 44100 | CD quality audio (at 16 bits/sample and 2 |
   |       | channels)                                 |
   +-------+-------------------------------------------+
   | 96000 | DVD quality audio (at 24 bits/sample)     |
   +-------+-------------------------------------------+


.. method:: oss_audio_device.sync()

   Wait until the sound device has played every byte in its buffer.  (This happens
   implicitly when the device is closed.)  The OSS documentation recommends closing
   and re-opening the device rather than using :meth:`sync`.


.. method:: oss_audio_device.reset()

   Immediately stop playing or recording and return the device to a state where it
   can accept commands.  The OSS documentation recommends closing and re-opening
   the device after calling :meth:`reset`.


.. method:: oss_audio_device.post()

   Tell the driver that there is likely to be a pause in the output, making it
   possible for the device to handle the pause more intelligently.  You might use
   this after playing a spot sound effect, before waiting for user input, or before
   doing disk I/O.

The following convenience methods combine several ioctls, or one ioctl and some
simple calculations.


.. method:: oss_audio_device.setparameters(format, nchannels, samplerate[, strict=False])

   Set the key audio sampling parameters---sample format, number of channels, and
   sampling rate---in one method call.  *format*,  *nchannels*, and *samplerate*
   should be as specified in the :meth:`setfmt`, :meth:`channels`, and
   :meth:`speed`  methods.  If *strict* is true, :meth:`setparameters` checks to
   see if each parameter was actually set to the requested value, and raises
   :exc:`OSSAudioError` if not.  Returns a tuple (*format*, *nchannels*,
   *samplerate*) indicating the parameter values that were actually set by the
   device driver (i.e., the same as the return values of :meth:`setfmt`,
   :meth:`channels`, and :meth:`speed`).

   For example,  ::

      (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate)

   is equivalent to  ::

      fmt = dsp.setfmt(fmt)
      channels = dsp.channels(channels)
      rate = dsp.rate(rate)


.. method:: oss_audio_device.bufsize()

   Returns the size of the hardware buffer, in samples.


.. method:: oss_audio_device.obufcount()

   Returns the number of samples that are in the hardware buffer yet to be played.


.. method:: oss_audio_device.obuffree()

   Returns the number of samples that could be queued into the hardware buffer to
   be played without blocking.

Audio device objects also support several read-only attributes:


.. attribute:: oss_audio_device.closed

   Boolean indicating whether the device has been closed.


.. attribute:: oss_audio_device.name

   String containing the name of the device file.


.. attribute:: oss_audio_device.mode

   The I/O mode for the file, either ``"r"``, ``"rw"``, or ``"w"``.


.. _mixer-device-objects:

Mixer Device Objects
--------------------

The mixer object provides two file-like methods:


.. method:: oss_mixer_device.close()

   This method closes the open mixer device file.  Any further attempts to use the
   mixer after this file is closed will raise an :exc:`IOError`.


.. method:: oss_mixer_device.fileno()

   Returns the file handle number of the open mixer device file.

The remaining methods are specific to audio mixing:


.. method:: oss_mixer_device.controls()

   This method returns a bitmask specifying the available mixer controls ("Control"
   being a specific mixable "channel", such as :const:`SOUND_MIXER_PCM` or
   :const:`SOUND_MIXER_SYNTH`).  This bitmask indicates a subset of all available
   mixer controls---the :const:`SOUND_MIXER_\*` constants defined at module level.
   To determine if, for example, the current mixer object supports a PCM mixer, use
   the following Python code::

      mixer=ossaudiodev.openmixer()
      if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM):
          # PCM is supported
          ... code ...

   For most purposes, the :const:`SOUND_MIXER_VOLUME` (master volume) and
   :const:`SOUND_MIXER_PCM` controls should suffice---but code that uses the mixer
   should be flexible when it comes to choosing mixer controls.  On the Gravis
   Ultrasound, for example, :const:`SOUND_MIXER_VOLUME` does not exist.


.. method:: oss_mixer_device.stereocontrols()

   Returns a bitmask indicating stereo mixer controls.  If a bit is set, the
   corresponding control is stereo; if it is unset, the control is either
   monophonic or not supported by the mixer (use in combination with
   :meth:`controls` to determine which).

   See the code example for the :meth:`controls` function for an example of getting
   data from a bitmask.


.. method:: oss_mixer_device.reccontrols()

   Returns a bitmask specifying the mixer controls that may be used to record.  See
   the code example for :meth:`controls` for an example of reading from a bitmask.


.. method:: oss_mixer_device.get(control)

   Returns the volume of a given mixer control.  The returned volume is a 2-tuple
   ``(left_volume,right_volume)``.  Volumes are specified as numbers from 0
   (silent) to 100 (full volume).  If the control is monophonic, a 2-tuple is still
   returned, but both volumes are the same.

   Raises :exc:`OSSAudioError` if an invalid control was is specified, or
   :exc:`IOError` if an unsupported control is specified.


.. method:: oss_mixer_device.set(control, (left, right))

   Sets the volume for a given mixer control to ``(left,right)``. ``left`` and
   ``right`` must be ints and between 0 (silent) and 100 (full volume).  On
   success, the new volume is returned as a 2-tuple. Note that this may not be
   exactly the same as the volume specified, because of the limited resolution of
   some soundcard's mixers.

   Raises :exc:`OSSAudioError` if an invalid mixer control was specified, or if the
   specified volumes were out-of-range.


.. method:: oss_mixer_device.get_recsrc()

   This method returns a bitmask indicating which control(s) are currently being
   used as a recording source.


.. method:: oss_mixer_device.set_recsrc(bitmask)

   Call this function to specify a recording source.  Returns a bitmask indicating
   the new recording source (or sources) if successful; raises :exc:`IOError` if an
   invalid source was specified.  To set the current recording source to the
   microphone input::

      mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)

PK	%�\ʙ*y�
�
&html/_sources/library/othergui.rst.txtnu�[���.. _other-gui-packages:

Other Graphical User Interface Packages
=======================================

Major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits are
available for Python:

.. seealso::

   `PyGTK <http://www.pygtk.org/>`_
      is a set of bindings for the `GTK <http://www.gtk.org/>`_ widget set. It
      provides an object oriented interface that is slightly higher level than
      the C one. It comes with many more widgets than Tkinter provides, and has
      good Python-specific reference documentation. There are also bindings to
      `GNOME <https://www.gnome.org/>`_.  An online `tutorial
      <http://www.pygtk.org/pygtk2tutorial/index.html>`_ is available.

   `PyQt <https://riverbankcomputing.com/software/pyqt/intro>`_
      PyQt is a :program:`sip`\ -wrapped binding to the Qt toolkit.  Qt is an
      extensive C++ GUI application development framework that is
      available for Unix, Windows and Mac OS X. :program:`sip` is a tool
      for generating bindings for C++ libraries as Python classes, and
      is specifically designed for Python. The *PyQt3* bindings have a
      book, `GUI Programming with Python: QT Edition
      <https://www.commandprompt.com/community/pyqt/>`_ by Boudewijn
      Rempt. The *PyQt4* bindings also have a book, `Rapid GUI Programming
      with Python and Qt <https://www.qtrac.eu/pyqtbook.html>`_, by Mark
      Summerfield.

   `wxPython <http://www.wxpython.org>`_
      wxPython is a cross-platform GUI toolkit for Python that is built around
      the popular `wxWidgets <https://www.wxwidgets.org/>`_ (formerly wxWindows)
      C++ toolkit.  It provides a native look and feel for applications on
      Windows, Mac OS X, and Unix systems by using each platform's native
      widgets where ever possible, (GTK+ on Unix-like systems).  In addition to
      an extensive set of widgets, wxPython provides classes for online
      documentation and context sensitive help, printing, HTML viewing,
      low-level device context drawing, drag and drop, system clipboard access,
      an XML-based resource format and more, including an ever growing library
      of user-contributed modules.  wxPython has a book, `wxPython in Action
      <https://www.manning.com/books/wxpython-in-action>`_, by Noel Rappin and
      Robin Dunn.

PyGTK, PyQt, and wxPython, all have a modern look and feel and more
widgets than Tkinter. In addition, there are many other GUI toolkits for
Python, both cross-platform, and platform-specific. See the `GUI Programming
<https://wiki.python.org/moin/GuiProgramming>`_ page in the Python Wiki for a
much more complete list, and also for links to documents where the
different GUI toolkits are compared.

PK	%�\N@�<<$html/_sources/library/parser.rst.txtnu�[���
:mod:`parser` --- Access Python parse trees
===========================================

.. module:: parser
   :synopsis: Access parse trees for Python source code.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. Copyright 1995 Virginia Polytechnic Institute and State University and Fred
   L. Drake, Jr.  This copyright notice must be distributed on all copies, but
   this document otherwise may be distributed as part of the Python
   distribution.  No fee may be charged for this document in any representation,
   either on paper or electronically.  This restriction does not affect other
   elements in a distributed package in any way.

.. index:: single: parsing; Python source code

The :mod:`parser` module provides an interface to Python's internal parser and
byte-code compiler.  The primary purpose for this interface is to allow Python
code to edit the parse tree of a Python expression and create executable code
from this.  This is better than trying to parse and modify an arbitrary Python
code fragment as a string because parsing is performed in a manner identical to
the code forming the application.  It is also faster.

.. note::

   From Python 2.5 onward, it's much more convenient to cut in at the Abstract
   Syntax Tree (AST) generation and compilation stage, using the :mod:`ast`
   module.

   The :mod:`parser` module exports the names documented here also with "st"
   replaced by "ast"; this is a legacy from the time when there was no other
   AST and has nothing to do with the AST found in Python 2.5.  This is also the
   reason for the functions' keyword arguments being called *ast*, not *st*.
   The "ast" functions have been removed in Python 3.

There are a few things to note about this module which are important to making
use of the data structures created.  This is not a tutorial on editing the parse
trees for Python code, but some examples of using the :mod:`parser` module are
presented.

Most importantly, a good understanding of the Python grammar processed by the
internal parser is required.  For full information on the language syntax, refer
to :ref:`reference-index`.  The parser
itself is created from a grammar specification defined in the file
:file:`Grammar/Grammar` in the standard Python distribution.  The parse trees
stored in the ST objects created by this module are the actual output from the
internal parser when created by the :func:`expr` or :func:`suite` functions,
described below.  The ST objects created by :func:`sequence2st` faithfully
simulate those structures.  Be aware that the values of the sequences which are
considered "correct" will vary from one version of Python to another as the
formal grammar for the language is revised.  However, transporting code from one
Python version to another as source text will always allow correct parse trees
to be created in the target version, with the only restriction being that
migrating to an older version of the interpreter will not support more recent
language constructs.  The parse trees are not typically compatible from one
version to another, whereas source code has always been forward-compatible.

Each element of the sequences returned by :func:`st2list` or :func:`st2tuple`
has a simple form.  Sequences representing non-terminal elements in the grammar
always have a length greater than one.  The first element is an integer which
identifies a production in the grammar.  These integers are given symbolic names
in the C header file :file:`Include/graminit.h` and the Python module
:mod:`symbol`.  Each additional element of the sequence represents a component
of the production as recognized in the input string: these are always sequences
which have the same form as the parent.  An important aspect of this structure
which should be noted is that keywords used to identify the parent node type,
such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the
node tree without any special treatment.  For example, the :keyword:`if` keyword
is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value
associated with all :const:`NAME` tokens, including variable and function names
defined by the user.  In an alternate form returned when line number information
is requested, the same token might be represented as ``(1, 'if', 12)``, where
the ``12`` represents the line number at which the terminal symbol was found.

Terminal elements are represented in much the same way, but without any child
elements and the addition of the source text which was identified.  The example
of the :keyword:`if` keyword above is representative.  The various types of
terminal symbols are defined in the C header file :file:`Include/token.h` and
the Python module :mod:`token`.

The ST objects are not required to support the functionality of this module,
but are provided for three purposes: to allow an application to amortize the
cost of processing complex parse trees, to provide a parse tree representation
which conserves memory space when compared to the Python list or tuple
representation, and to ease the creation of additional modules in C which
manipulate parse trees.  A simple "wrapper" class may be created in Python to
hide the use of ST objects.

The :mod:`parser` module defines functions for a few distinct purposes.  The
most important purposes are to create ST objects and to convert ST objects to
other representations such as parse trees and compiled code objects, but there
are also functions which serve to query the type of parse tree represented by an
ST object.


.. seealso::

   Module :mod:`symbol`
      Useful constants representing internal nodes of the parse tree.

   Module :mod:`token`
      Useful constants representing leaf nodes of the parse tree and functions for
      testing node values.


.. _creating-sts:

Creating ST Objects
-------------------

ST objects may be created from source code or from a parse tree. When creating
an ST object from source, different functions are used to create the ``'eval'``
and ``'exec'`` forms.


.. function:: expr(source)

   The :func:`expr` function parses the parameter *source* as if it were an input
   to ``compile(source, 'file.py', 'eval')``.  If the parse succeeds, an ST object
   is created to hold the internal parse tree representation, otherwise an
   appropriate exception is raised.


.. function:: suite(source)

   The :func:`suite` function parses the parameter *source* as if it were an input
   to ``compile(source, 'file.py', 'exec')``.  If the parse succeeds, an ST object
   is created to hold the internal parse tree representation, otherwise an
   appropriate exception is raised.


.. function:: sequence2st(sequence)

   This function accepts a parse tree represented as a sequence and builds an
   internal representation if possible.  If it can validate that the tree conforms
   to the Python grammar and all nodes are valid node types in the host version of
   Python, an ST object is created from the internal representation and returned
   to the called.  If there is a problem creating the internal representation, or
   if the tree cannot be validated, a :exc:`ParserError` exception is raised.  An
   ST object created this way should not be assumed to compile correctly; normal
   exceptions raised by compilation may still be initiated when the ST object is
   passed to :func:`compilest`.  This may indicate problems not related to syntax
   (such as a :exc:`MemoryError` exception), but may also be due to constructs such
   as the result of parsing ``del f(0)``, which escapes the Python parser but is
   checked by the bytecode compiler.

   Sequences representing terminal tokens may be represented as either two-element
   lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1,
   'name', 56)``.  If the third element is present, it is assumed to be a valid
   line number.  The line number may be specified for any subset of the terminal
   symbols in the input tree.


.. function:: tuple2st(sequence)

   This is the same function as :func:`sequence2st`.  This entry point is
   maintained for backward compatibility.


.. _converting-sts:

Converting ST Objects
---------------------

ST objects, regardless of the input used to create them, may be converted to
parse trees represented as list- or tuple- trees, or may be compiled into
executable code objects.  Parse trees may be extracted with or without line
numbering information.


.. function:: st2list(ast[, line_info])

   This function accepts an ST object from the caller in *ast* and returns a
   Python list representing the equivalent parse tree.  The resulting list
   representation can be used for inspection or the creation of a new parse tree in
   list form.  This function does not fail so long as memory is available to build
   the list representation.  If the parse tree will only be used for inspection,
   :func:`st2tuple` should be used instead to reduce memory consumption and
   fragmentation.  When the list representation is required, this function is
   significantly faster than retrieving a tuple representation and converting that
   to nested lists.

   If *line_info* is true, line number information will be included for all
   terminal tokens as a third element of the list representing the token.  Note
   that the line number provided specifies the line on which the token *ends*.
   This information is omitted if the flag is false or omitted.


.. function:: st2tuple(ast[, line_info])

   This function accepts an ST object from the caller in *ast* and returns a
   Python tuple representing the equivalent parse tree.  Other than returning a
   tuple instead of a list, this function is identical to :func:`st2list`.

   If *line_info* is true, line number information will be included for all
   terminal tokens as a third element of the list representing the token.  This
   information is omitted if the flag is false or omitted.


.. function:: compilest(ast, filename='<syntax-tree>')

   .. index:: builtin: eval

   The Python byte compiler can be invoked on an ST object to produce code objects
   which can be used as part of an :keyword:`exec` statement or a call to the
   built-in :func:`eval` function. This function provides the interface to the
   compiler, passing the internal parse tree from *ast* to the parser, using the
   source file name specified by the *filename* parameter. The default value
   supplied for *filename* indicates that the source was an ST object.

   Compiling an ST object may result in exceptions related to compilation; an
   example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``:
   this statement is considered legal within the formal grammar for Python but is
   not a legal language construct.  The :exc:`SyntaxError` raised for this
   condition is actually generated by the Python byte-compiler normally, which is
   why it can be raised at this point by the :mod:`parser` module.  Most causes of
   compilation failure can be diagnosed programmatically by inspection of the parse
   tree.


.. _querying-sts:

Queries on ST Objects
---------------------

Two functions are provided which allow an application to determine if an ST was
created as an expression or a suite.  Neither of these functions can be used to
determine if an ST was created from source code via :func:`expr` or
:func:`suite` or from a parse tree via :func:`sequence2st`.


.. function:: isexpr(ast)

   .. index:: builtin: compile

   When *ast* represents an ``'eval'`` form, this function returns true, otherwise
   it returns false.  This is useful, since code objects normally cannot be queried
   for this information using existing built-in functions.  Note that the code
   objects created by :func:`compilest` cannot be queried like this either, and
   are identical to those created by the built-in :func:`compile` function.


.. function:: issuite(ast)

   This function mirrors :func:`isexpr` in that it reports whether an ST object
   represents an ``'exec'`` form, commonly known as a "suite."  It is not safe to
   assume that this function is equivalent to ``not isexpr(ast)``, as additional
   syntactic fragments may be supported in the future.


.. _st-errors:

Exceptions and Error Handling
-----------------------------

The parser module defines a single exception, but may also pass other built-in
exceptions from other portions of the Python runtime environment.  See each
function for information about the exceptions it can raise.


.. exception:: ParserError

   Exception raised when a failure occurs within the parser module.  This is
   generally produced for validation failures rather than the built-in
   :exc:`SyntaxError` raised during normal parsing. The exception argument is
   either a string describing the reason of the failure or a tuple containing a
   sequence causing the failure from a parse tree passed to :func:`sequence2st`
   and an explanatory string.  Calls to :func:`sequence2st` need to be able to
   handle either type of exception, while calls to other functions in the module
   will only need to be aware of the simple string values.

Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may
raise exceptions which are normally raised by the parsing and compilation
process.  These include the built in exceptions :exc:`MemoryError`,
:exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`.  In these
cases, these exceptions carry all the meaning normally associated with them.
Refer to the descriptions of each function for detailed information.


.. _st-objects:

ST Objects
----------

Ordered and equality comparisons are supported between ST objects. Pickling of
ST objects (using the :mod:`pickle` module) is also supported.


.. data:: STType

   The type of the objects returned by :func:`expr`, :func:`suite` and
   :func:`sequence2st`.

ST objects have the following methods:


.. method:: ST.compile([filename])

   Same as ``compilest(st, filename)``.


.. method:: ST.isexpr()

   Same as ``isexpr(st)``.


.. method:: ST.issuite()

   Same as ``issuite(st)``.


.. method:: ST.tolist([line_info])

   Same as ``st2list(st, line_info)``.


.. method:: ST.totuple([line_info])

   Same as ``st2tuple(st, line_info)``.


Example: Emulation of :func:`compile`
-------------------------------------

While many useful operations may take place between parsing and bytecode
generation, the simplest operation is to do nothing.  For this purpose, using
the :mod:`parser` module to produce an intermediate data structure is equivalent
to the code ::

   >>> code = compile('a + 5', 'file.py', 'eval')
   >>> a = 5
   >>> eval(code)
   10

The equivalent operation using the :mod:`parser` module is somewhat longer, and
allows the intermediate internal parse tree to be retained as an ST object::

   >>> import parser
   >>> st = parser.expr('a + 5')
   >>> code = st.compile('file.py')
   >>> a = 5
   >>> eval(code)
   10

An application which needs both ST and code objects can package this code into
readily available functions::

   import parser

   def load_suite(source_string):
       st = parser.suite(source_string)
       return st, st.compile()

   def load_expression(source_string):
       st = parser.expr(source_string)
       return st, st.compile()
PK	%�\��>�>!html/_sources/library/pdb.rst.txtnu�[���.. _debugger:

:mod:`pdb` --- The Python Debugger
==================================

.. module:: pdb
   :synopsis: The Python debugger for interactive interpreters.

**Source code:** :source:`Lib/pdb.py`

--------------

.. index:: single: debugging

The module :mod:`pdb` defines an interactive source code debugger for Python
programs.  It supports setting (conditional) breakpoints and single stepping at
the source line level, inspection of stack frames, source code listing, and
evaluation of arbitrary Python code in the context of any stack frame.  It also
supports post-mortem debugging and can be called under program control.

.. index::
   single: Pdb (class in pdb)
   module: bdb
   module: cmd

The debugger is extensible --- it is actually defined as the class :class:`Pdb`.
This is currently undocumented but easily understood by reading the source.  The
extension interface uses the modules :mod:`bdb` and :mod:`cmd`.

The debugger's prompt is ``(Pdb)``. Typical usage to run a program under control
of the debugger is::

   >>> import pdb
   >>> import mymodule
   >>> pdb.run('mymodule.test()')
   > <string>(0)?()
   (Pdb) continue
   > <string>(1)?()
   (Pdb) continue
   NameError: 'spam'
   > <string>(1)?()
   (Pdb)

:file:`pdb.py` can also be invoked as a script to debug other scripts.  For
example::

   python -m pdb myscript.py

When invoked as a script, pdb will automatically enter post-mortem debugging if
the program being debugged exits abnormally. After post-mortem debugging (or
after normal exit of the program), pdb will restart the program. Automatic
restarting preserves pdb's state (such as breakpoints) and in most cases is more
useful than quitting the debugger upon program's exit.

.. versionadded:: 2.4
   Restarting post-mortem behavior added.

The typical usage to break into the debugger from a running program is to
insert ::

   import pdb; pdb.set_trace()

at the location you want to break into the debugger.  You can then step through
the code following this statement, and continue running without the debugger using
the ``c`` command.

The typical usage to inspect a crashed program is::

   >>> import pdb
   >>> import mymodule
   >>> mymodule.test()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "./mymodule.py", line 4, in test
       test2()
     File "./mymodule.py", line 3, in test2
       print spam
   NameError: spam
   >>> pdb.pm()
   > ./mymodule.py(3)test2()
   -> print spam
   (Pdb)


The module defines the following functions; each enters the debugger in a
slightly different way:

.. function:: run(statement[, globals[, locals]])

   Execute the *statement* (given as a string) under debugger control.  The
   debugger prompt appears before any code is executed; you can set breakpoints and
   type ``continue``, or you can step through the statement using ``step`` or
   ``next`` (all these commands are explained below).  The optional *globals* and
   *locals* arguments specify the environment in which the code is executed; by
   default the dictionary of the module :mod:`__main__` is used.  (See the
   explanation of the :keyword:`exec` statement or the :func:`eval` built-in
   function.)


.. function:: runeval(expression[, globals[, locals]])

   Evaluate the *expression* (given as a string) under debugger control.  When
   :func:`runeval` returns, it returns the value of the expression.  Otherwise this
   function is similar to :func:`run`.


.. function:: runcall(function[, argument, ...])

   Call the *function* (a function or method object, not a string) with the given
   arguments.  When :func:`runcall` returns, it returns whatever the function call
   returned.  The debugger prompt appears as soon as the function is entered.


.. function:: set_trace()

   Enter the debugger at the calling stack frame.  This is useful to hard-code a
   breakpoint at a given point in a program, even if the code is not otherwise
   being debugged (e.g. when an assertion fails).


.. function:: post_mortem([traceback])

   Enter post-mortem debugging of the given *traceback* object.  If no
   *traceback* is given, it uses the one of the exception that is currently
   being handled (an exception must be being handled if the default is to be
   used).


.. function:: pm()

   Enter post-mortem debugging of the traceback found in
   :data:`sys.last_traceback`.


The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
:class:`Pdb` class and calling the method of the same name.  If you want to
access further features, you have to do this yourself:

.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None)

   :class:`Pdb` is the debugger class.

   The *completekey*, *stdin* and *stdout* arguments are passed to the
   underlying :class:`cmd.Cmd` class; see the description there.

   The *skip* argument, if given, must be an iterable of glob-style module name
   patterns.  The debugger will not step into frames that originate in a module
   that matches one of these patterns. [1]_

   Example call to enable tracing with *skip*::

      import pdb; pdb.Pdb(skip=['django.*']).set_trace()

   .. versionadded:: 2.7
      The *skip* argument.

   .. method:: run(statement[, globals[, locals]])
               runeval(expression[, globals[, locals]])
               runcall(function[, argument, ...])
               set_trace()

      See the documentation for the functions explained above.


.. _debugger-commands:

Debugger Commands
=================

The debugger recognizes the following commands.  Most commands can be
abbreviated to one or two letters; e.g. ``h(elp)`` means that either ``h`` or
``help`` can be used to enter the help command (but not ``he`` or ``hel``, nor
``H`` or ``Help`` or ``HELP``).  Arguments to commands must be separated by
whitespace (spaces or tabs).  Optional arguments are enclosed in square brackets
(``[]``) in the command syntax; the square brackets must not be typed.
Alternatives in the command syntax are separated by a vertical bar (``|``).

Entering a blank line repeats the last command entered.  Exception: if the last
command was a ``list`` command, the next 11 lines are listed.

Commands that the debugger doesn't recognize are assumed to be Python statements
and are executed in the context of the program being debugged.  Python
statements can also be prefixed with an exclamation point (``!``).  This is a
powerful way to inspect the program being debugged; it is even possible to
change a variable or call a function.  When an exception occurs in such a
statement, the exception name is printed but the debugger's state is not
changed.

Multiple commands may be entered on a single line, separated by ``;;``.  (A
single ``;`` is not used as it is the separator for multiple commands in a line
that is passed to the Python parser.) No intelligence is applied to separating
the commands; the input is split at the first ``;;`` pair, even if it is in the
middle of a quoted string.

The debugger supports aliases.  Aliases can have parameters which allows one a
certain level of adaptability to the context under examination.

.. index::
   pair: .pdbrc; file
   triple: debugger; configuration; file

If a file :file:`.pdbrc`  exists in the user's home directory or in the current
directory, it is read in and executed as if it had been typed at the debugger
prompt. This is particularly useful for aliases.  If both files exist, the one
in the home directory is read first and aliases defined there can be overridden
by the local file.

h(elp) [*command*]
   Without argument, print the list of available commands.  With a *command* as
   argument, print help about that command.  ``help pdb`` displays the full
   documentation file; if the environment variable :envvar:`PAGER` is defined, the
   file is piped through that command instead.  Since the *command* argument must
   be an identifier, ``help exec`` must be entered to get help on the ``!``
   command.

w(here)
   Print a stack trace, with the most recent frame at the bottom.  An arrow
   indicates the current frame, which determines the context of most commands.

d(own)
   Move the current frame one level down in the stack trace (to a newer frame).

u(p)
   Move the current frame one level up in the stack trace (to an older frame).

b(reak) [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
   With a *lineno* argument, set a break there in the current file.  With a
   *function* argument, set a break at the first executable statement within that
   function. The line number may be prefixed with a filename and a colon, to
   specify a breakpoint in another file (probably one that hasn't been loaded yet).
   The file is searched on ``sys.path``. Note that each breakpoint is assigned a
   number to which all the other breakpoint commands refer.

   If a second argument is present, it is an expression which must evaluate to true
   before the breakpoint is honored.

   Without argument, list all breaks, including for each breakpoint, the number of
   times that breakpoint has been hit, the current ignore count, and the associated
   condition if any.

tbreak [[*filename*:]\ *lineno* | *function*\ [, *condition*]]
   Temporary breakpoint, which is removed automatically when it is first hit.  The
   arguments are the same as break.

cl(ear) [*filename:lineno* | *bpnumber* [*bpnumber ...*]]
   With a *filename:lineno* argument, clear all the breakpoints at this line.
   With a space separated list of breakpoint numbers, clear those breakpoints.
   Without argument, clear all breaks (but first ask confirmation).

disable [*bpnumber* [*bpnumber ...*]]
   Disables the breakpoints given as a space separated list of breakpoint numbers.
   Disabling a breakpoint means it cannot cause the program to stop execution, but
   unlike clearing a breakpoint, it remains in the list of breakpoints and can be
   (re-)enabled.

enable [*bpnumber* [*bpnumber ...*]]
   Enables the breakpoints specified.

ignore *bpnumber* [*count*]
   Sets the ignore count for the given breakpoint number.  If count is omitted, the
   ignore count is set to 0.  A breakpoint becomes active when the ignore count is
   zero.  When non-zero, the count is decremented each time the breakpoint is
   reached and the breakpoint is not disabled and any associated condition
   evaluates to true.

condition *bpnumber* [*condition*]
   Condition is an expression which must evaluate to true before the breakpoint is
   honored.  If condition is absent, any existing condition is removed; i.e., the
   breakpoint is made unconditional.

commands [*bpnumber*]
   Specify a list of commands for breakpoint number *bpnumber*.  The commands
   themselves appear on the following lines.  Type a line containing just 'end' to
   terminate the commands. An example::

      (Pdb) commands 1
      (com) print some_variable
      (com) end
      (Pdb)

   To remove all commands from a breakpoint, type commands and follow it
   immediately with  end; that is, give no commands.

   With no *bpnumber* argument, commands refers to the last breakpoint set.

   You can use breakpoint commands to start your program up again. Simply use the
   continue command, or step, or any other command that resumes execution.

   Specifying any command resuming execution (currently continue, step, next,
   return, jump, quit and their abbreviations) terminates the command list (as if
   that command was immediately followed by end). This is because any time you
   resume execution (even with a simple next or step), you may encounter another
   breakpoint—which could have its own command list, leading to ambiguities about
   which list to execute.

   If you use the 'silent' command in the command list, the usual message about
   stopping at a breakpoint is not printed.  This may be desirable for breakpoints
   that are to print a specific message and then continue.  If none of the other
   commands print anything, you see no sign that the breakpoint was reached.

   .. versionadded:: 2.5

s(tep)
   Execute the current line, stop at the first possible occasion (either in a
   function that is called or on the next line in the current function).

n(ext)
   Continue execution until the next line in the current function is reached or it
   returns.  (The difference between ``next`` and ``step`` is that ``step`` stops
   inside a called function, while ``next`` executes called functions at (nearly)
   full speed, only stopping at the next line in the current function.)

unt(il)
   Continue execution until the line with the line number greater than the
   current one is reached or when returning from current frame.

   .. versionadded:: 2.6

r(eturn)
   Continue execution until the current function returns.

c(ont(inue))
   Continue execution, only stop when a breakpoint is encountered.

j(ump) *lineno*
   Set the next line that will be executed.  Only available in the bottom-most
   frame.  This lets you jump back and execute code again, or jump forward to skip
   code that you don't want to run.

   It should be noted that not all jumps are allowed --- for instance it is not
   possible to jump into the middle of a :keyword:`for` loop or out of a
   :keyword:`finally` clause.

l(ist) [*first*\ [, *last*]]
   List source code for the current file.  Without arguments, list 11 lines around
   the current line or continue the previous listing.  With one argument, list 11
   lines around at that line.  With two arguments, list the given range; if the
   second argument is less than the first, it is interpreted as a count.

a(rgs)
   Print the argument list of the current function.

p *expression*
   Evaluate the *expression* in the current context and print its value.

   .. note::

      ``print`` can also be used, but is not a debugger command --- this executes the
      Python :keyword:`print` statement.

pp *expression*
   Like the ``p`` command, except the value of the expression is pretty-printed
   using the :mod:`pprint` module.

alias [*name* [command]]
   Creates an alias called *name* that executes *command*.  The command must *not*
   be enclosed in quotes.  Replaceable parameters can be indicated by ``%1``,
   ``%2``, and so on, while ``%*`` is replaced by all the parameters.  If no
   command is given, the current alias for *name* is shown. If no arguments are
   given, all aliases are listed.

   Aliases may be nested and can contain anything that can be legally typed at the
   pdb prompt.  Note that internal pdb commands *can* be overridden by aliases.
   Such a command is then hidden until the alias is removed.  Aliasing is
   recursively applied to the first word of the command line; all other words in
   the line are left alone.

   As an example, here are two useful aliases (especially when placed in the
   :file:`.pdbrc` file)::

      #Print instance variables (usage "pi classInst")
      alias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]
      #Print instance variables in self
      alias ps pi self

unalias *name*
   Deletes the specified alias.

[!]\ *statement*
   Execute the (one-line) *statement* in the context of the current stack frame.
   The exclamation point can be omitted unless the first word of the statement
   resembles a debugger command. To set a global variable, you can prefix the
   assignment command with a ``global`` command on the same line, e.g.::

      (Pdb) global list_options; list_options = ['-l']
      (Pdb)

run [*args* ...]
   Restart the debugged Python program. If an argument is supplied, it is split
   with "shlex" and the result is used as the new sys.argv. History, breakpoints,
   actions and debugger options are preserved. "restart" is an alias for "run".

   .. versionadded:: 2.6

q(uit)
   Quit from the debugger. The program being executed is aborted.


.. rubric:: Footnotes

.. [1] Whether a frame is considered to originate in a certain module
       is determined by the ``__name__`` in the frame globals.
PK	%�\K�p�::)html/_sources/library/persistence.rst.txtnu�[���
.. _persistence:

****************
Data Persistence
****************

The modules described in this chapter support storing Python data in a
persistent form on disk.  The :mod:`pickle` and :mod:`marshal` modules can turn
many Python data types into a stream of bytes and then recreate the objects from
the bytes.  The various DBM-related modules support a family of hash-based file
formats that store a mapping of strings to other strings.  The :mod:`bsddb`
module also provides such disk-based string-to-string mappings based on hashing,
and also supports B-Tree and record-based formats.

The list of modules described in this chapter is:


.. toctree::

   pickle.rst
   copy_reg.rst
   shelve.rst
   marshal.rst
   anydbm.rst
   whichdb.rst
   dbm.rst
   gdbm.rst
   dbhash.rst
   bsddb.rst
   dumbdbm.rst
   sqlite3.rst
PK	%�\i�Xh����$html/_sources/library/pickle.rst.txtnu�[���:mod:`pickle` --- Python object serialization
=============================================

.. index::
   single: persistence
   pair: persistent; objects
   pair: serializing; objects
   pair: marshalling; objects
   pair: flattening; objects
   pair: pickling; objects

.. module:: pickle
   :synopsis: Convert Python objects to streams of bytes and back.
.. sectionauthor:: Jim Kerr <jbkerr@sr.hp.com>.
.. sectionauthor:: Barry Warsaw <barry@zope.com>

The :mod:`pickle` module implements a fundamental, but powerful algorithm for
serializing and de-serializing a Python object structure.  "Pickling" is the
process whereby a Python object hierarchy is converted into a byte stream, and
"unpickling" is the inverse operation, whereby a byte stream is converted back
into an object hierarchy.  Pickling (and unpickling) is alternatively known as
"serialization", "marshalling," [#]_ or "flattening", however, to avoid
confusion, the terms used here are "pickling" and "unpickling".

This documentation describes both the :mod:`pickle` module and the
:mod:`cPickle` module.

.. warning::

   The :mod:`pickle` module is not secure against erroneous or maliciously
   constructed data.  Never unpickle data received from an untrusted or
   unauthenticated source.


Relationship to other Python modules
------------------------------------

The :mod:`pickle` module has an optimized cousin called the :mod:`cPickle`
module.  As its name implies, :mod:`cPickle` is written in C, so it can be up to
1000 times faster than :mod:`pickle`.  However it does not support subclassing
of the :func:`Pickler` and :func:`Unpickler` classes, because in :mod:`cPickle`
these are functions, not classes.  Most applications have no need for this
functionality, and can benefit from the improved performance of :mod:`cPickle`.
Other than that, the interfaces of the two modules are nearly identical; the
common interface is described in this manual and differences are pointed out
where necessary.  In the following discussions, we use the term "pickle" to
collectively describe the :mod:`pickle` and :mod:`cPickle` modules.

The data streams the two modules produce are guaranteed to be interchangeable.

Python has a more primitive serialization module called :mod:`marshal`, but in
general :mod:`pickle` should always be the preferred way to serialize Python
objects.  :mod:`marshal` exists primarily to support Python's :file:`.pyc`
files.

The :mod:`pickle` module differs from :mod:`marshal` in several significant ways:

* The :mod:`pickle` module keeps track of the objects it has already serialized,
  so that later references to the same object won't be serialized again.
  :mod:`marshal` doesn't do this.

  This has implications both for recursive objects and object sharing.  Recursive
  objects are objects that contain references to themselves.  These are not
  handled by marshal, and in fact, attempting to marshal recursive objects will
  crash your Python interpreter.  Object sharing happens when there are multiple
  references to the same object in different places in the object hierarchy being
  serialized.  :mod:`pickle` stores such objects only once, and ensures that all
  other references point to the master copy.  Shared objects remain shared, which
  can be very important for mutable objects.

* :mod:`marshal` cannot be used to serialize user-defined classes and their
  instances.  :mod:`pickle` can save and restore class instances transparently,
  however the class definition must be importable and live in the same module as
  when the object was stored.

* The :mod:`marshal` serialization format is not guaranteed to be portable
  across Python versions.  Because its primary job in life is to support
  :file:`.pyc` files, the Python implementers reserve the right to change the
  serialization format in non-backwards compatible ways should the need arise.
  The :mod:`pickle` serialization format is guaranteed to be backwards compatible
  across Python releases.

Note that serialization is a more primitive notion than persistence; although
:mod:`pickle` reads and writes file objects, it does not handle the issue of
naming persistent objects, nor the (even more complicated) issue of concurrent
access to persistent objects.  The :mod:`pickle` module can transform a complex
object into a byte stream and it can transform the byte stream into an object
with the same internal structure.  Perhaps the most obvious thing to do with
these byte streams is to write them onto a file, but it is also conceivable to
send them across a network or store them in a database.  The module
:mod:`shelve` provides a simple interface to pickle and unpickle objects on
DBM-style database files.


Data stream format
------------------

.. index::
   single: XDR
   single: External Data Representation

The data format used by :mod:`pickle` is Python-specific.  This has the
advantage that there are no restrictions imposed by external standards such as
XDR (which can't represent pointer sharing); however it means that non-Python
programs may not be able to reconstruct pickled Python objects.

By default, the :mod:`pickle` data format uses a printable ASCII representation.
This is slightly more voluminous than a binary representation.  The big
advantage of using printable ASCII (and of some other characteristics of
:mod:`pickle`'s representation) is that for debugging or recovery purposes it is
possible for a human to read the pickled file with a standard text editor.

There are currently 3 different protocols which can be used for pickling.

* Protocol version 0 is the original ASCII protocol and is backwards compatible
  with earlier versions of Python.

* Protocol version 1 is the old binary format which is also compatible with
  earlier versions of Python.

* Protocol version 2 was introduced in Python 2.3.  It provides much more
  efficient pickling of :term:`new-style class`\es.

Refer to :pep:`307` for more information.

If a *protocol* is not specified, protocol 0 is used. If *protocol* is specified
as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol version
available will be used.

.. versionchanged:: 2.3
   Introduced the *protocol* parameter.

A binary format, which is slightly more efficient, can be chosen by specifying a
*protocol* version >= 1.


Usage
-----

To serialize an object hierarchy, you first create a pickler, then you call the
pickler's :meth:`dump` method.  To de-serialize a data stream, you first create
an unpickler, then you call the unpickler's :meth:`load` method.  The
:mod:`pickle` module provides the following constant:


.. data:: HIGHEST_PROTOCOL

   The highest protocol version available.  This value can be passed as a
   *protocol* value.

   .. versionadded:: 2.3

.. note::

   Be sure to always open pickle files created with protocols >= 1 in binary mode.
   For the old ASCII-based pickle protocol 0 you can use either text mode or binary
   mode as long as you stay consistent.

   A pickle file written with protocol 0 in binary mode will contain lone linefeeds
   as line terminators and therefore will look "funny" when viewed in Notepad or
   other editors which do not support this format.

The :mod:`pickle` module provides the following functions to make the pickling
process more convenient:


.. function:: dump(obj, file[, protocol])

   Write a pickled representation of *obj* to the open file object *file*.  This is
   equivalent to ``Pickler(file, protocol).dump(obj)``.

   If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
   specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
   version will be used.

   .. versionchanged:: 2.3
      Introduced the *protocol* parameter.

   *file* must have a :meth:`write` method that accepts a single string argument.
   It can thus be a file object opened for writing, a :mod:`StringIO` object, or
   any other custom object that meets this interface.


.. function:: load(file)

   Read a string from the open file object *file* and interpret it as a pickle data
   stream, reconstructing and returning the original object hierarchy.  This is
   equivalent to ``Unpickler(file).load()``.

   *file* must have two methods, a :meth:`read` method that takes an integer
   argument, and a :meth:`readline` method that requires no arguments.  Both
   methods should return a string.  Thus *file* can be a file object opened for
   reading, a :mod:`StringIO` object, or any other custom object that meets this
   interface.

   This function automatically determines whether the data stream was written in
   binary mode or not.


.. function:: dumps(obj[, protocol])

   Return the pickled representation of the object as a string, instead of writing
   it to a file.

   If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
   specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest protocol
   version will be used.

   .. versionchanged:: 2.3
      The *protocol* parameter was added.


.. function:: loads(string)

   Read a pickled object hierarchy from a string.  Characters in the string past
   the pickled object's representation are ignored.

The :mod:`pickle` module also defines three exceptions:


.. exception:: PickleError

   A common base class for the other exceptions defined below.  This inherits from
   :exc:`Exception`.


.. exception:: PicklingError

   This exception is raised when an unpicklable object is passed to the
   :meth:`dump` method.


.. exception:: UnpicklingError

   This exception is raised when there is a problem unpickling an object. Note that
   other exceptions may also be raised during unpickling, including (but not
   necessarily limited to) :exc:`AttributeError`, :exc:`EOFError`,
   :exc:`ImportError`, and :exc:`IndexError`.

The :mod:`pickle` module also exports two callables [#]_, :class:`Pickler` and
:class:`Unpickler`:


.. class:: Pickler(file[, protocol])

   This takes a file-like object to which it will write a pickle data stream.

   If the *protocol* parameter is omitted, protocol 0 is used. If *protocol* is
   specified as a negative value or :const:`HIGHEST_PROTOCOL`, the highest
   protocol version will be used.

   .. versionchanged:: 2.3
      Introduced the *protocol* parameter.

   *file* must have a :meth:`write` method that accepts a single string argument.
   It can thus be an open file object, a :mod:`StringIO` object, or any other
   custom object that meets this interface.

   :class:`Pickler` objects define one (or two) public methods:


   .. method:: dump(obj)

      Write a pickled representation of *obj* to the open file object given in the
      constructor.  Either the binary or ASCII format will be used, depending on the
      value of the *protocol* argument passed to the constructor.


   .. method:: clear_memo()

      Clears the pickler's "memo".  The memo is the data structure that remembers
      which objects the pickler has already seen, so that shared or recursive objects
      pickled by reference and not by value.  This method is useful when re-using
      picklers.

      .. note::

         Prior to Python 2.3, :meth:`clear_memo` was only available on the picklers
         created by :mod:`cPickle`.  In the :mod:`pickle` module, picklers have an
         instance variable called :attr:`memo` which is a Python dictionary.  So to clear
         the memo for a :mod:`pickle` module pickler, you could do the following::

            mypickler.memo.clear()

         Code that does not need to support older versions of Python should simply use
         :meth:`clear_memo`.

It is possible to make multiple calls to the :meth:`dump` method of the same
:class:`Pickler` instance.  These must then be matched to the same number of
calls to the :meth:`load` method of the corresponding :class:`Unpickler`
instance.  If the same object is pickled by multiple :meth:`dump` calls, the
:meth:`load` will all yield references to the same object. [#]_

:class:`Unpickler` objects are defined as:


.. class:: Unpickler(file)

   This takes a file-like object from which it will read a pickle data stream.
   This class automatically determines whether the data stream was written in
   binary mode or not, so it does not need a flag as in the :class:`Pickler`
   factory.

   *file* must have two methods, a :meth:`read` method that takes an integer
   argument, and a :meth:`readline` method that requires no arguments.  Both
   methods should return a string.  Thus *file* can be a file object opened for
   reading, a :mod:`StringIO` object, or any other custom object that meets this
   interface.

   :class:`Unpickler` objects have one (or two) public methods:


   .. method:: load()

      Read a pickled object representation from the open file object given in
      the constructor, and return the reconstituted object hierarchy specified
      therein.

      This method automatically determines whether the data stream was written
      in binary mode or not.


   .. method:: noload()

      This is just like :meth:`load` except that it doesn't actually create any
      objects.  This is useful primarily for finding what's called "persistent
      ids" that may be referenced in a pickle data stream.  See section
      :ref:`pickle-protocol` below for more details.

      **Note:** the :meth:`noload` method is currently only available on
      :class:`Unpickler` objects created with the :mod:`cPickle` module.
      :mod:`pickle` module :class:`Unpickler`\ s do not have the :meth:`noload`
      method.


What can be pickled and unpickled?
----------------------------------

The following types can be pickled:

* ``None``, ``True``, and ``False``

* integers, long integers, floating point numbers, complex numbers

* normal and Unicode strings

* tuples, lists, sets, and dictionaries containing only picklable objects

* functions defined at the top level of a module

* built-in functions defined at the top level of a module

* classes that are defined at the top level of a module

* instances of such classes whose :attr:`~object.__dict__` or the result of
  calling :meth:`__getstate__` is picklable  (see section :ref:`pickle-protocol`
  for details).

Attempts to pickle unpicklable objects will raise the :exc:`PicklingError`
exception; when this happens, an unspecified number of bytes may have already
been written to the underlying file. Trying to pickle a highly recursive data
structure may exceed the maximum recursion depth, a :exc:`RuntimeError` will be
raised in this case. You can carefully raise this limit with
:func:`sys.setrecursionlimit`.

Note that functions (built-in and user-defined) are pickled by "fully qualified"
name reference, not by value.  This means that only the function name is
pickled, along with the name of the module the function is defined in.  Neither
the function's code, nor any of its function attributes are pickled.  Thus the
defining module must be importable in the unpickling environment, and the module
must contain the named object, otherwise an exception will be raised. [#]_

Similarly, classes are pickled by named reference, so the same restrictions in
the unpickling environment apply.  Note that none of the class's code or data is
pickled, so in the following example the class attribute ``attr`` is not
restored in the unpickling environment::

   class Foo:
       attr = 'a class attr'

   picklestring = pickle.dumps(Foo)

These restrictions are why picklable functions and classes must be defined in
the top level of a module.

Similarly, when class instances are pickled, their class's code and data are not
pickled along with them.  Only the instance data are pickled.  This is done on
purpose, so you can fix bugs in a class or add methods to the class and still
load objects that were created with an earlier version of the class.  If you
plan to have long-lived objects that will see many versions of a class, it may
be worthwhile to put a version number in the objects so that suitable
conversions can be made by the class's :meth:`__setstate__` method.


.. _pickle-protocol:

The pickle protocol
-------------------

.. currentmodule:: None

This section describes the "pickling protocol" that defines the interface
between the pickler/unpickler and the objects that are being serialized.  This
protocol provides a standard way for you to define, customize, and control how
your objects are serialized and de-serialized.  The description in this section
doesn't cover specific customizations that you can employ to make the unpickling
environment slightly safer from untrusted pickle data streams; see section
:ref:`pickle-sub` for more details.


.. _pickle-inst:

Pickling and unpickling normal class instances
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. method:: object.__getinitargs__()

   When a pickled class instance is unpickled, its :meth:`__init__` method is
   normally *not* invoked.  If it is desirable that the :meth:`__init__` method
   be called on unpickling, an old-style class can define a method
   :meth:`__getinitargs__`, which should return a *tuple* of positional
   arguments to be passed to the class constructor (:meth:`__init__` for
   example).  Keyword arguments are not supported.  The :meth:`__getinitargs__`
   method is called at pickle time; the tuple it returns is incorporated in the
   pickle for the instance.

.. method:: object.__getnewargs__()

   New-style types can provide a :meth:`__getnewargs__` method that is used for
   protocol 2.  Implementing this method is needed if the type establishes some
   internal invariants when the instance is created, or if the memory allocation
   is affected by the values passed to the :meth:`__new__` method for the type
   (as it is for tuples and strings).  Instances of a :term:`new-style class`
   ``C`` are created using ::

      obj = C.__new__(C, *args)

   where *args* is the result of calling :meth:`__getnewargs__` on the original
   object; if there is no :meth:`__getnewargs__`, an empty tuple is assumed.

.. method:: object.__getstate__()

   Classes can further influence how their instances are pickled; if the class
   defines the method :meth:`__getstate__`, it is called and the return state is
   pickled as the contents for the instance, instead of the contents of the
   instance's dictionary.  If there is no :meth:`__getstate__` method, the
   instance's :attr:`~object.__dict__` is pickled.

.. method:: object.__setstate__(state)

   Upon unpickling, if the class also defines the method :meth:`__setstate__`,
   it is called with the unpickled state. [#]_ If there is no
   :meth:`__setstate__` method, the pickled state must be a dictionary and its
   items are assigned to the new instance's dictionary.  If a class defines both
   :meth:`__getstate__` and :meth:`__setstate__`, the state object needn't be a
   dictionary and these methods can do what they want. [#]_

   .. note::

      For :term:`new-style class`\es, if :meth:`__getstate__` returns a false
      value, the :meth:`__setstate__` method will not be called.

.. note::

   At unpickling time, some methods like :meth:`__getattr__`,
   :meth:`__getattribute__`, or :meth:`__setattr__` may be called upon the
   instance.  In case those methods rely on some internal invariant being
   true, the type should implement either :meth:`__getinitargs__` or
   :meth:`__getnewargs__` to establish such an invariant; otherwise, neither
   :meth:`__new__` nor :meth:`__init__` will be called.


Pickling and unpickling extension types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. method:: object.__reduce__()

   When the :class:`Pickler` encounters an object of a type it knows nothing
   about --- such as an extension type --- it looks in two places for a hint of
   how to pickle it.  One alternative is for the object to implement a
   :meth:`__reduce__` method.  If provided, at pickling time :meth:`__reduce__`
   will be called with no arguments, and it must return either a string or a
   tuple.

   If a string is returned, it names a global variable whose contents are
   pickled as normal.  The string returned by :meth:`__reduce__` should be the
   object's local name relative to its module; the pickle module searches the
   module namespace to determine the object's module.

   When a tuple is returned, it must be between two and five elements long.
   Optional elements can either be omitted, or ``None`` can be provided as their
   value.  The contents of this tuple are pickled as normal and used to
   reconstruct the object at unpickling time.  The semantics of each element
   are:

   * A callable object that will be called to create the initial version of the
     object.  The next element of the tuple will provide arguments for this
     callable, and later elements provide additional state information that will
     subsequently be used to fully reconstruct the pickled data.

     In the unpickling environment this object must be either a class, a
     callable registered as a "safe constructor" (see below), or it must have an
     attribute :attr:`__safe_for_unpickling__` with a true value. Otherwise, an
     :exc:`UnpicklingError` will be raised in the unpickling environment.  Note
     that as usual, the callable itself is pickled by name.

   * A tuple of arguments for the callable object.

     .. versionchanged:: 2.5
        Formerly, this argument could also be ``None``.

   * Optionally, the object's state, which will be passed to the object's
     :meth:`__setstate__` method as described in section :ref:`pickle-inst`.  If
     the object has no :meth:`__setstate__` method, then, as above, the value
     must be a dictionary and it will be added to the object's
     :attr:`~object.__dict__`.

   * Optionally, an iterator (and not a sequence) yielding successive list
     items.  These list items will be pickled, and appended to the object using
     either ``obj.append(item)`` or ``obj.extend(list_of_items)``.  This is
     primarily used for list subclasses, but may be used by other classes as
     long as they have :meth:`append` and :meth:`extend` methods with the
     appropriate signature.  (Whether :meth:`append` or :meth:`extend` is used
     depends on which pickle protocol version is used as well as the number of
     items to append, so both must be supported.)

   * Optionally, an iterator (not a sequence) yielding successive dictionary
     items, which should be tuples of the form ``(key, value)``.  These items
     will be pickled and stored to the object using ``obj[key] = value``. This
     is primarily used for dictionary subclasses, but may be used by other
     classes as long as they implement :meth:`__setitem__`.

.. method:: object.__reduce_ex__(protocol)

   It is sometimes useful to know the protocol version when implementing
   :meth:`__reduce__`.  This can be done by implementing a method named
   :meth:`__reduce_ex__` instead of :meth:`__reduce__`. :meth:`__reduce_ex__`,
   when it exists, is called in preference over :meth:`__reduce__` (you may
   still provide :meth:`__reduce__` for backwards compatibility).  The
   :meth:`__reduce_ex__` method will be called with a single integer argument,
   the protocol version.

   The :class:`object` class implements both :meth:`__reduce__` and
   :meth:`__reduce_ex__`; however, if a subclass overrides :meth:`__reduce__`
   but not :meth:`__reduce_ex__`, the :meth:`__reduce_ex__` implementation
   detects this and calls :meth:`__reduce__`.

An alternative to implementing a :meth:`__reduce__` method on the object to be
pickled, is to register the callable with the :mod:`copy_reg` module.  This
module provides a way for programs to register "reduction functions" and
constructors for user-defined types.   Reduction functions have the same
semantics and interface as the :meth:`__reduce__` method described above, except
that they are called with a single argument, the object to be pickled.

The registered constructor is deemed a "safe constructor" for purposes of
unpickling as described above.


Pickling and unpickling external objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. index::
   single: persistent_id (pickle protocol)
   single: persistent_load (pickle protocol)

For the benefit of object persistence, the :mod:`pickle` module supports the
notion of a reference to an object outside the pickled data stream.  Such
objects are referenced by a "persistent id", which is just an arbitrary string
of printable ASCII characters. The resolution of such names is not defined by
the :mod:`pickle` module; it will delegate this resolution to user defined
functions on the pickler and unpickler. [#]_

To define external persistent id resolution, you need to set the
:attr:`~Pickler.persistent_id` attribute of the pickler object and the
:attr:`~Unpickler.persistent_load` attribute of the unpickler object.

To pickle objects that have an external persistent id, the pickler must have a
custom :func:`~Pickler.persistent_id` method that takes an object as an
argument and returns either ``None`` or the persistent id for that object.
When ``None`` is returned, the pickler simply pickles the object as normal.
When a persistent id string is returned, the pickler will pickle that string,
along with a marker so that the unpickler will recognize the string as a
persistent id.

To unpickle external objects, the unpickler must have a custom
:func:`~Unpickler.persistent_load` function that takes a persistent id string
and returns the referenced object.

Here's a silly example that *might* shed more light::

   import pickle
   from cStringIO import StringIO

   src = StringIO()
   p = pickle.Pickler(src)

   def persistent_id(obj):
       if hasattr(obj, 'x'):
           return 'the value %d' % obj.x
       else:
           return None

   p.persistent_id = persistent_id

   class Integer:
       def __init__(self, x):
           self.x = x
       def __str__(self):
           return 'My name is integer %d' % self.x

   i = Integer(7)
   print i
   p.dump(i)

   datastream = src.getvalue()
   print repr(datastream)
   dst = StringIO(datastream)

   up = pickle.Unpickler(dst)

   class FancyInteger(Integer):
       def __str__(self):
           return 'I am the integer %d' % self.x

   def persistent_load(persid):
       if persid.startswith('the value '):
           value = int(persid.split()[2])
           return FancyInteger(value)
       else:
           raise pickle.UnpicklingError, 'Invalid persistent id'

   up.persistent_load = persistent_load

   j = up.load()
   print j

In the :mod:`cPickle` module, the unpickler's :attr:`~Unpickler.persistent_load`
attribute can also be set to a Python list, in which case, when the unpickler
reaches a persistent id, the persistent id string will simply be appended to
this list.  This functionality exists so that a pickle data stream can be
"sniffed" for object references without actually instantiating all the objects
in a pickle.
[#]_  Setting :attr:`~Unpickler.persistent_load` to a list is usually used in
conjunction with the :meth:`~Unpickler.noload` method on the Unpickler.

.. BAW: Both pickle and cPickle support something called inst_persistent_id()
   which appears to give unknown types a second shot at producing a persistent
   id.  Since Jim Fulton can't remember why it was added or what it's for, I'm
   leaving it undocumented.


.. _pickle-sub:

Subclassing Unpicklers
----------------------

.. index::
   single: load_global() (pickle protocol)
   single: find_global() (pickle protocol)

By default, unpickling will import any class that it finds in the pickle data.
You can control exactly what gets unpickled and what gets called by customizing
your unpickler.  Unfortunately, exactly how you do this is different depending
on whether you're using :mod:`pickle` or :mod:`cPickle`. [#]_

In the :mod:`pickle` module, you need to derive a subclass from
:class:`Unpickler`, overriding the :meth:`load_global` method.
:meth:`load_global` should read two lines from the pickle data stream where the
first line will the name of the module containing the class and the second line
will be the name of the instance's class.  It then looks up the class, possibly
importing the module and digging out the attribute, then it appends what it
finds to the unpickler's stack.  Later on, this class will be assigned to the
:attr:`__class__` attribute of an empty class, as a way of magically creating an
instance without calling its class's :meth:`__init__`. Your job (should you
choose to accept it), would be to have :meth:`load_global` push onto the
unpickler's stack, a known safe version of any class you deem safe to unpickle.
It is up to you to produce such a class.  Or you could raise an error if you
want to disallow all unpickling of instances.  If this sounds like a hack,
you're right.  Refer to the source code to make this work.

Things are a little cleaner with :mod:`cPickle`, but not by much. To control
what gets unpickled, you can set the unpickler's :attr:`~Unpickler.find_global`
attribute to a function or ``None``.  If it is ``None`` then any attempts to
unpickle instances will raise an :exc:`UnpicklingError`.  If it is a function,
then it should accept a module name and a class name, and return the
corresponding class object.  It is responsible for looking up the class and
performing any necessary imports, and it may raise an error to prevent
instances of the class from being unpickled.

The moral of the story is that you should be really careful about the source of
the strings your application unpickles.


.. _pickle-example:

Example
-------

For the simplest code, use the :func:`dump` and :func:`load` functions.  Note
that a self-referencing list is pickled and restored correctly. ::

   import pickle

   data1 = {'a': [1, 2.0, 3, 4+6j],
            'b': ('string', u'Unicode string'),
            'c': None}

   selfref_list = [1, 2, 3]
   selfref_list.append(selfref_list)

   output = open('data.pkl', 'wb')

   # Pickle dictionary using protocol 0.
   pickle.dump(data1, output)

   # Pickle the list using the highest protocol available.
   pickle.dump(selfref_list, output, -1)

   output.close()

The following example reads the resulting pickled data.  When reading a
pickle-containing file, you should open the file in binary mode because you
can't be sure if the ASCII or binary format was used. ::

   import pprint, pickle

   pkl_file = open('data.pkl', 'rb')

   data1 = pickle.load(pkl_file)
   pprint.pprint(data1)

   data2 = pickle.load(pkl_file)
   pprint.pprint(data2)

   pkl_file.close()

Here's a larger example that shows how to modify pickling behavior for a class.
The :class:`TextReader` class opens a text file, and returns the line number and
line contents each time its :meth:`!readline` method is called. If a
:class:`TextReader` instance is pickled, all attributes *except* the file object
member are saved. When the instance is unpickled, the file is reopened, and
reading resumes from the last location. The :meth:`__setstate__` and
:meth:`__getstate__` methods are used to implement this behavior. ::

   #!/usr/local/bin/python

   class TextReader:
       """Print and number lines in a text file."""
       def __init__(self, file):
           self.file = file
           self.fh = open(file)
           self.lineno = 0

       def readline(self):
           self.lineno = self.lineno + 1
           line = self.fh.readline()
           if not line:
               return None
           if line.endswith("\n"):
               line = line[:-1]
           return "%d: %s" % (self.lineno, line)

       def __getstate__(self):
           odict = self.__dict__.copy() # copy the dict since we change it
           del odict['fh']              # remove filehandle entry
           return odict

       def __setstate__(self, dict):
           fh = open(dict['file'])      # reopen file
           count = dict['lineno']       # read from file...
           while count:                 # until line count is restored
               fh.readline()
               count = count - 1
           self.__dict__.update(dict)   # update attributes
           self.fh = fh                 # save the file object

A sample usage might be something like this::

   >>> import TextReader
   >>> obj = TextReader.TextReader("TextReader.py")
   >>> obj.readline()
   '1: #!/usr/local/bin/python'
   >>> obj.readline()
   '2: '
   >>> obj.readline()
   '3: class TextReader:'
   >>> import pickle
   >>> pickle.dump(obj, open('save.p', 'wb'))

If you want to see that :mod:`pickle` works across Python processes, start
another Python session, before continuing.  What follows can happen from either
the same process or a new process. ::

   >>> import pickle
   >>> reader = pickle.load(open('save.p', 'rb'))
   >>> reader.readline()
   '4:     """Print and number lines in a text file."""'


.. seealso::

   Module :mod:`copy_reg`
      Pickle interface constructor registration for extension types.

   Module :mod:`shelve`
      Indexed databases of objects; uses :mod:`pickle`.

   Module :mod:`copy`
      Shallow and deep object copying.

   Module :mod:`marshal`
      High-performance serialization of built-in types.


:mod:`cPickle` --- A faster :mod:`pickle`
=========================================

.. module:: cPickle
   :synopsis: Faster version of pickle, but not subclassable.
.. moduleauthor:: Jim Fulton <jim@zope.com>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. index:: module: pickle

The :mod:`cPickle` module supports serialization and de-serialization of Python
objects, providing an interface and functionality nearly identical to the
:mod:`pickle` module.  There are several differences, the most important being
performance and subclassability.

First, :mod:`cPickle` can be up to 1000 times faster than :mod:`pickle` because
the former is implemented in C.  Second, in the :mod:`cPickle` module the
callables :func:`Pickler` and :func:`Unpickler` are functions, not classes.
This means that you cannot use them to derive custom pickling and unpickling
subclasses.  Most applications have no need for this functionality and should
benefit from the greatly improved performance of the :mod:`cPickle` module.

The pickle data stream produced by :mod:`pickle` and :mod:`cPickle` are
identical, so it is possible to use :mod:`pickle` and :mod:`cPickle`
interchangeably with existing pickles. [#]_

There are additional minor differences in API between :mod:`cPickle` and
:mod:`pickle`, however for most applications, they are interchangeable.  More
documentation is provided in the :mod:`pickle` module documentation, which
includes a list of the documented differences.

.. rubric:: Footnotes

.. [#] Don't confuse this with the :mod:`marshal` module

.. [#] In the :mod:`pickle` module these callables are classes, which you could
   subclass to customize the behavior.  However, in the :mod:`cPickle` module these
   callables are factory functions and so cannot be subclassed.  One common reason
   to subclass is to control what objects can actually be unpickled.  See section
   :ref:`pickle-sub` for more details.

.. [#] *Warning*: this is intended for pickling multiple objects without intervening
   modifications to the objects or their parts.  If you modify an object and then
   pickle it again using the same :class:`Pickler` instance, the object is not
   pickled again --- a reference to it is pickled and the :class:`Unpickler` will
   return the old value, not the modified one. There are two problems here: (1)
   detecting changes, and (2) marshalling a minimal set of changes.  Garbage
   Collection may also become a problem here.

.. [#] The exception raised will likely be an :exc:`ImportError` or an
   :exc:`AttributeError` but it could be something else.

.. [#] These methods can also be used to implement copying class instances.

.. [#] This protocol is also used by the shallow and deep copying operations defined in
   the :mod:`copy` module.

.. [#] The actual mechanism for associating these user defined functions is slightly
   different for :mod:`pickle` and :mod:`cPickle`.  The description given here
   works the same for both implementations.  Users of the :mod:`pickle` module
   could also use subclassing to effect the same results, overriding the
   :meth:`persistent_id` and :meth:`persistent_load` methods in the derived
   classes.

.. [#] We'll leave you with the image of Guido and Jim sitting around sniffing pickles
   in their living rooms.

.. [#] A word of caution: the mechanisms described here use internal attributes and
   methods, which are subject to change in future versions of Python.  We intend to
   someday provide a common interface for controlling this behavior, which will
   work in either :mod:`pickle` or :mod:`cPickle`.

.. [#] Since the pickle data format is actually a tiny stack-oriented programming
   language, and some freedom is taken in the encodings of certain objects, it is
   possible that the two modules produce different data streams for the same input
   objects.  However it is guaranteed that they will always be able to read each
   other's data streams.

PK	%�\�^����)html/_sources/library/pickletools.rst.txtnu�[���:mod:`pickletools` --- Tools for pickle developers
==================================================

.. module:: pickletools
   :synopsis: Contains extensive comments about the pickle protocols and pickle-machine
              opcodes, as well as some useful functions.


.. versionadded:: 2.3

**Source code:** :source:`Lib/pickletools.py`

--------------

This module contains various constants relating to the intimate details of the
:mod:`pickle` module, some lengthy comments about the implementation, and a few
useful functions for analyzing pickled data.  The contents of this module are
useful for Python core developers who are working on the :mod:`pickle` and
:mod:`cPickle` implementations; ordinary users of the :mod:`pickle` module
probably won't find the :mod:`pickletools` module relevant.


.. function:: dis(pickle, out=None, memo=None, indentlevel=4)

   Outputs a symbolic disassembly of the pickle to the file-like object *out*,
   defaulting to ``sys.stdout``.  *pickle* can be a string or a file-like object.
   *memo* can be a Python dictionary that will be used as the pickle's memo; it can
   be used to perform disassemblies across multiple pickles created by the same
   pickler. Successive levels, indicated by ``MARK`` opcodes in the stream, are
   indented by *indentlevel* spaces.


.. function:: genops(pickle)

   Provides an :term:`iterator` over all of the opcodes in a pickle, returning a
   sequence of ``(opcode, arg, pos)`` triples.  *opcode* is an instance of an
   :class:`OpcodeInfo` class; *arg* is the decoded value, as a Python object, of
   the opcode's argument; *pos* is the position at which this opcode is located.
   *pickle* can be a string or a file-like object.

.. function:: optimize(picklestring)

   Returns a new equivalent pickle string after eliminating unused ``PUT``
   opcodes. The optimized pickle is shorter, takes less transmission time,
   requires less storage space, and unpickles more efficiently.

   .. versionadded:: 2.6
PK	%�\:7�N��#html/_sources/library/pipes.rst.txtnu�[���:mod:`pipes` --- Interface to shell pipelines
=============================================

.. module:: pipes
   :platform: Unix
   :synopsis: A Python interface to Unix shell pipelines.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

**Source code:** :source:`Lib/pipes.py`

--------------

The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
--- a sequence of converters from one file to  another.

Because the module uses :program:`/bin/sh` command lines, a POSIX or compatible
shell for :func:`os.system` and :func:`os.popen` is required.


.. class:: Template()

   An abstraction of a pipeline.

Example::

   >>> import pipes
   >>> t = pipes.Template()
   >>> t.append('tr a-z A-Z', '--')
   >>> f = t.open('pipefile', 'w')
   >>> f.write('hello world')
   >>> f.close()
   >>> open('pipefile').read()
   'HELLO WORLD'


.. function:: quote(s)

   .. deprecated:: 2.7
      Prior to Python 2.7, this function was not publicly documented.  It is
      finally exposed publicly in Python 3.3 as the
      :func:`quote <shlex.quote>` function in the :mod:`shlex` module.

   Return a shell-escaped version of the string *s*.  The returned value is a
   string that can safely be used as one token in a shell command line, for
   cases where you cannot use a list.

   This idiom would be unsafe::

      >>> filename = 'somefile; rm -rf ~'
      >>> command = 'ls -l {}'.format(filename)
      >>> print command  # executed by a shell: boom!
      ls -l somefile; rm -rf ~

   :func:`quote` lets you plug the security hole::

      >>> command = 'ls -l {}'.format(quote(filename))
      >>> print command
      ls -l 'somefile; rm -rf ~'
      >>> remote_command = 'ssh home {}'.format(quote(command))
      >>> print remote_command
      ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''

   The quoting is compatible with UNIX shells and with :func:`shlex.split`:

      >>> remote_command = shlex.split(remote_command)
      >>> remote_command
      ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
      >>> command = shlex.split(remote_command[-1])
      >>> command
      ['ls', '-l', 'somefile; rm -rf ~']


.. _template-objects:

Template Objects
----------------

Template objects following methods:


.. method:: Template.reset()

   Restore a pipeline template to its initial state.


.. method:: Template.clone()

   Return a new, equivalent, pipeline template.


.. method:: Template.debug(flag)

   If *flag* is true, turn debugging on. Otherwise, turn debugging off. When
   debugging is on, commands to be executed are printed, and the shell is given
   ``set -x`` command to be more verbose.


.. method:: Template.append(cmd, kind)

   Append a new action at the end. The *cmd* variable must be a valid bourne shell
   command. The *kind* variable consists of two letters.

   The first letter can be either of ``'-'`` (which means the command reads its
   standard input), ``'f'`` (which means the commands reads a given file on the
   command line) or ``'.'`` (which means the commands reads no input, and hence
   must be first.)

   Similarly, the second letter can be either of ``'-'`` (which means  the command
   writes to standard output), ``'f'`` (which means the  command writes a file on
   the command line) or ``'.'`` (which means the command does not write anything,
   and hence must be last.)


.. method:: Template.prepend(cmd, kind)

   Add a new action at the beginning. See :meth:`append` for explanations of the
   arguments.


.. method:: Template.open(file, mode)

   Return a file-like object, open to *file*, but read from or written to by the
   pipeline.  Note that only one of ``'r'``, ``'w'`` may be given.


.. method:: Template.copy(infile, outfile)

   Copy *infile* to *outfile* through the pipe.

PK	%�\}�""%html/_sources/library/pkgutil.rst.txtnu�[���:mod:`pkgutil` --- Package extension utility
============================================

.. module:: pkgutil
   :synopsis: Utilities for the import system.

.. versionadded:: 2.3

**Source code:** :source:`Lib/pkgutil.py`

--------------

This module provides utilities for the import system, in particular package
support.


.. function:: extend_path(path, name)

   Extend the search path for the modules which comprise a package.  Intended
   use is to place the following code in a package's :file:`__init__.py`::

      from pkgutil import extend_path
      __path__ = extend_path(__path__, __name__)

   This will add to the package's ``__path__`` all subdirectories of directories
   on ``sys.path`` named after the package.  This is useful if one wants to
   distribute different parts of a single logical package as multiple
   directories.

   It also looks for :file:`\*.pkg` files beginning where ``*`` matches the
   *name* argument.  This feature is similar to :file:`\*.pth` files (see the
   :mod:`site` module for more information), except that it doesn't special-case
   lines starting with ``import``.  A :file:`\*.pkg` file is trusted at face
   value: apart from checking for duplicates, all entries found in a
   :file:`\*.pkg` file are added to the path, regardless of whether they exist
   on the filesystem.  (This is a feature.)

   If the input path is not a list (as is the case for frozen packages) it is
   returned unchanged.  The input path is not modified; an extended copy is
   returned.  Items are only appended to the copy at the end.

   It is assumed that :data:`sys.path` is a sequence.  Items of :data:`sys.path`
   that are not (Unicode or 8-bit) strings referring to existing directories are
   ignored.  Unicode items on :data:`sys.path` that cause errors when used as
   filenames may cause this function to raise an exception (in line with
   :func:`os.path.isdir` behavior).


.. class:: ImpImporter(dirname=None)

   :pep:`302` Importer that wraps Python's "classic" import algorithm.

   If *dirname* is a string, a :pep:`302` importer is created that searches that
   directory.  If *dirname* is ``None``, a :pep:`302` importer is created that
   searches the current :data:`sys.path`, plus any modules that are frozen or
   built-in.

   Note that :class:`ImpImporter` does not currently support being used by
   placement on :data:`sys.meta_path`.


.. class:: ImpLoader(fullname, file, filename, etc)

   :pep:`302` Loader that wraps Python's "classic" import algorithm.


.. function:: find_loader(fullname)

   Find a :pep:`302` "loader" object for *fullname*.

   If *fullname* contains dots, path must be the containing package's
   ``__path__``.  Returns ``None`` if the module cannot be found or imported.
   This function uses :func:`iter_importers`, and is thus subject to the same
   limitations regarding platform-specific special import locations such as the
   Windows registry.


.. function:: get_importer(path_item)

   Retrieve a :pep:`302` importer for the given *path_item*.

   The returned importer is cached in :data:`sys.path_importer_cache` if it was
   newly created by a path hook.

   If there is no importer, a wrapper around the basic import machinery is
   returned.  This wrapper is never inserted into the importer cache (``None``
   is inserted instead).

   The cache (or part of it) can be cleared manually if a rescan of
   :data:`sys.path_hooks` is necessary.


.. function:: get_loader(module_or_name)

   Get a :pep:`302` "loader" object for *module_or_name*.

   If the module or package is accessible via the normal import mechanism, a
   wrapper around the relevant part of that machinery is returned.  Returns
   ``None`` if the module cannot be found or imported.  If the named module is
   not already imported, its containing package (if any) is imported, in order
   to establish the package ``__path__``.

   This function uses :func:`iter_importers`, and is thus subject to the same
   limitations regarding platform-specific special import locations such as the
   Windows registry.


.. function:: iter_importers(fullname='')

   Yield :pep:`302` importers for the given module name.

   If fullname contains a '.', the importers will be for the package containing
   fullname, otherwise they will be importers for :data:`sys.meta_path`,
   :data:`sys.path`, and Python's "classic" import machinery, in that order.  If
   the named module is in a package, that package is imported as a side effect
   of invoking this function.

   Non-:pep:`302` mechanisms (e.g. the Windows registry) used by the standard
   import machinery to find files in alternative locations are partially
   supported, but are searched *after* :data:`sys.path`.  Normally, these
   locations are searched *before* :data:`sys.path`, preventing :data:`sys.path`
   entries from shadowing them.

   For this to cause a visible difference in behaviour, there must be a module
   or package name that is accessible via both :data:`sys.path` and one of the
   non-:pep:`302` file system mechanisms.  In this case, the emulation will find
   the former version, while the builtin import mechanism will find the latter.

   Items of the following types can be affected by this discrepancy:
   ``imp.C_EXTENSION``, ``imp.PY_SOURCE``, ``imp.PY_COMPILED``,
   ``imp.PKG_DIRECTORY``.


.. function:: iter_modules(path=None, prefix='')

   Yields ``(module_loader, name, ispkg)`` for all submodules on *path*, or, if
   path is ``None``, all top-level modules on ``sys.path``.

   *path* should be either ``None`` or a list of paths to look for modules in.

   *prefix* is a string to output on the front of every module name on output.


.. function:: walk_packages(path=None, prefix='', onerror=None)

   Yields ``(module_loader, name, ispkg)`` for all modules recursively on
   *path*, or, if path is ``None``, all accessible modules.

   *path* should be either ``None`` or a list of paths to look for modules in.

   *prefix* is a string to output on the front of every module name on output.

   Note that this function must import all *packages* (*not* all modules!) on
   the given *path*, in order to access the ``__path__`` attribute to find
   submodules.

   *onerror* is a function which gets called with one argument (the name of the
   package which was being imported) if any exception occurs while trying to
   import a package.  If no *onerror* function is supplied, :exc:`ImportError`\s
   are caught and ignored, while all other exceptions are propagated,
   terminating the search.

   Examples::

      # list all modules python can access
      walk_packages()

      # list all submodules of ctypes
      walk_packages(ctypes.__path__, ctypes.__name__ + '.')


.. function:: get_data(package, resource)

   Get a resource from a package.

   This is a wrapper for the :pep:`302` loader :func:`get_data` API.  The
   *package* argument should be the name of a package, in standard module format
   (``foo.bar``).  The *resource* argument should be in the form of a relative
   filename, using ``/`` as the path separator.  The parent directory name
   ``..`` is not allowed, and nor is a rooted name (starting with a ``/``).

   The function returns a binary string that is the contents of the specified
   resource.

   For packages located in the filesystem, which have already been imported,
   this is the rough equivalent of::

      d = os.path.dirname(sys.modules[package].__file__)
      data = open(os.path.join(d, resource), 'rb').read()

   If the package cannot be located or loaded, or it uses a :pep:`302` loader
   which does not support :func:`get_data`, then ``None`` is returned.

   .. versionadded:: 2.6
PK	%�\���R%R%&html/_sources/library/platform.rst.txtnu�[���:mod:`platform` ---  Access to underlying platform's identifying data
=====================================================================

.. module:: platform
   :synopsis: Retrieves as much platform identifying data as possible.
.. moduleauthor:: Marc-Andre Lemburg <mal@egenix.com>
.. sectionauthor:: Bjorn Pettersen <bpettersen@corp.fairisaac.com>


.. versionadded:: 2.3

**Source code:** :source:`Lib/platform.py`

--------------

.. note::

   Specific platforms listed alphabetically, with Linux included in the Unix
   section.


Cross Platform
--------------


.. function:: architecture(executable=sys.executable, bits='', linkage='')

   Queries the given executable (defaults to the Python interpreter binary) for
   various architecture information.

   Returns a tuple ``(bits, linkage)`` which contain information about the bit
   architecture and the linkage format used for the executable. Both values are
   returned as strings.

   Values that cannot be determined are returned as given by the parameter presets.
   If bits is given as ``''``, the ``sizeof(pointer)`` (or
   ``sizeof(long)`` on Python version < 1.5.2) is used as indicator for the
   supported pointer size.

   The function relies on the system's :file:`file` command to do the actual work.
   This is available on most if not all Unix  platforms and some non-Unix platforms
   and then only if the executable points to the Python interpreter.  Reasonable
   defaults are used when the above needs are not met.

   .. note::

      On Mac OS X (and perhaps other platforms), executable files may be
      universal files containing multiple architectures.

      To get at the "64-bitness" of the current interpreter, it is more
      reliable to query the :attr:`sys.maxsize` attribute::

         is_64bits = sys.maxsize > 2**32


.. function:: machine()

   Returns the machine type, e.g. ``'i386'``. An empty string is returned if the
   value cannot be determined.


.. function:: node()

   Returns the computer's network name (may not be fully qualified!). An empty
   string is returned if the value cannot be determined.


.. function:: platform(aliased=0, terse=0)

   Returns a single string identifying the underlying platform with as much useful
   information as possible.

   The output is intended to be *human readable* rather than machine parseable. It
   may look different on different platforms and this is intended.

   If *aliased* is true, the function will use aliases for various platforms that
   report system names which differ from their common names, for example SunOS will
   be reported as Solaris.  The :func:`system_alias` function is used to implement
   this.

   Setting *terse* to true causes the function to return only the absolute minimum
   information needed to identify the platform.


.. function:: processor()

   Returns the (real) processor name, e.g. ``'amdk6'``.

   An empty string is returned if the value cannot be determined. Note that many
   platforms do not provide this information or simply return the same value as for
   :func:`machine`.  NetBSD does this.


.. function:: python_build()

   Returns a tuple ``(buildno, builddate)`` stating the Python build number and
   date as strings.


.. function:: python_compiler()

   Returns a string identifying the compiler used for compiling Python.


.. function:: python_branch()

   Returns a string identifying the Python implementation SCM branch.

   .. versionadded:: 2.6


.. function:: python_implementation()

   Returns a string identifying the Python implementation. Possible return values
   are: 'CPython', 'IronPython', 'Jython', 'PyPy'.

   .. versionadded:: 2.6


.. function:: python_revision()

   Returns a string identifying the Python implementation SCM revision.

   .. versionadded:: 2.6


.. function:: python_version()

   Returns the Python version as string ``'major.minor.patchlevel'``.

   Note that unlike the Python ``sys.version``, the returned value will always
   include the patchlevel (it defaults to 0).


.. function:: python_version_tuple()

   Returns the Python version as tuple ``(major, minor, patchlevel)`` of strings.

   Note that unlike the Python ``sys.version``, the returned value will always
   include the patchlevel (it defaults to ``'0'``).


.. function:: release()

   Returns the system's release, e.g. ``'2.2.0'`` or ``'NT'`` An empty string is
   returned if the value cannot be determined.


.. function:: system()

   Returns the system/OS name, e.g. ``'Linux'``, ``'Windows'``, or ``'Java'``. An
   empty string is returned if the value cannot be determined.


.. function:: system_alias(system, release, version)

   Returns ``(system, release, version)`` aliased to common marketing names used
   for some systems.  It also does some reordering of the information in some cases
   where it would otherwise cause confusion.


.. function:: version()

   Returns the system's release version, e.g. ``'#3 on degas'``. An empty string is
   returned if the value cannot be determined.


.. function:: uname()

   Fairly portable uname interface. Returns a tuple of strings ``(system, node,
   release, version, machine, processor)`` identifying the underlying platform.

   Note that unlike the :func:`os.uname` function this also returns possible
   processor information as additional tuple entry.

   Entries which cannot be determined are set to ``''``.


Java Platform
-------------


.. function:: java_ver(release='', vendor='', vminfo=('','',''), osinfo=('','',''))

   Version interface for Jython.

   Returns a tuple ``(release, vendor, vminfo, osinfo)`` with *vminfo* being a
   tuple ``(vm_name, vm_release, vm_vendor)`` and *osinfo* being a tuple
   ``(os_name, os_version, os_arch)``. Values which cannot be determined are set to
   the defaults given as parameters (which all default to ``''``).


Windows Platform
----------------


.. function:: win32_ver(release='', version='', csd='', ptype='')

   Get additional version information from the Windows Registry and return a tuple
   ``(release, version, csd, ptype)`` referring to OS release, version number,
   CSD level (service pack) and OS type (multi/single processor).

   As a hint: *ptype* is ``'Uniprocessor Free'`` on single processor NT machines
   and ``'Multiprocessor Free'`` on multi processor machines. The *'Free'* refers
   to the OS version being free of debugging code. It could also state *'Checked'*
   which means the OS version uses debugging code, i.e. code that checks arguments,
   ranges, etc.

   .. note::

      This function works best with Mark Hammond's
      :mod:`win32all` package installed, but also on Python 2.3 and
      later (support for this was added in Python 2.6). It obviously
      only runs on Win32 compatible platforms.


Win95/98 specific
^^^^^^^^^^^^^^^^^

.. function:: popen(cmd, mode='r', bufsize=None)

   Portable :func:`popen` interface.  Find a working popen implementation
   preferring :func:`win32pipe.popen`.  On Windows NT, :func:`win32pipe.popen`
   should work; on Windows 9x it hangs due to bugs in the MS C library.


Mac OS Platform
---------------


.. function:: mac_ver(release='', versioninfo=('','',''), machine='')

   Get Mac OS version information and return it as tuple ``(release, versioninfo,
   machine)`` with *versioninfo* being a tuple ``(version, dev_stage,
   non_release_version)``.

   Entries which cannot be determined are set to ``''``.  All tuple entries are
   strings.


Unix Platforms
--------------


.. function:: dist(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...))

   This is an old version of the functionality now provided by
   :func:`linux_distribution`. For new code, please use the
   :func:`linux_distribution`.

   The only difference between the two is that ``dist()`` always
   returns the short name of the distribution taken from the
   ``supported_dists`` parameter.

   .. deprecated:: 2.6

.. function:: linux_distribution(distname='', version='', id='', supported_dists=('SuSE','debian','redhat','mandrake',...), full_distribution_name=1)

   Tries to determine the name of the Linux OS distribution name.

   ``supported_dists`` may be given to define the set of Linux distributions to
   look for. It defaults to a list of currently supported Linux distributions
   identified by their release file name.

   If ``full_distribution_name`` is true (default), the full distribution read
   from the OS is returned. Otherwise the short name taken from
   ``supported_dists`` is used.

   Returns a tuple ``(distname,version,id)`` which defaults to the args given as
   parameters.  ``id`` is the item in parentheses after the version number.  It
   is usually the version codename.

   .. note::
      This function is deprecated since Python 3.5 and removed in Python 3.8.
      See alternative like the `distro <https://pypi.org/project/distro>`_ package.

   .. versionadded:: 2.6

.. function:: libc_ver(executable=sys.executable, lib='', version='', chunksize=2048)

   Tries to determine the libc version against which the file executable (defaults
   to the Python interpreter) is linked.  Returns a tuple of strings ``(lib,
   version)`` which default to the given parameters in case the lookup fails.

   Note that this function has intimate knowledge of how different libc versions
   add symbols to the executable is probably only usable for executables compiled
   using :program:`gcc`.

   The file is read and scanned in chunks of *chunksize* bytes.

PK	%�\�/�&&&html/_sources/library/plistlib.rst.txtnu�[���:mod:`plistlib` --- Generate and parse Mac OS X ``.plist`` files
================================================================

.. module:: plistlib
   :synopsis: Generate and parse Mac OS X plist files.
.. moduleauthor:: Jack Jansen
.. sectionauthor:: Georg Brandl <georg@python.org>
.. (harvested from docstrings in the original file)

.. versionchanged:: 2.6
   This module was previously only available in the Mac-specific library, it is
   now available for all platforms.

.. index::
   pair: plist; file
   single: property list

**Source code:** :source:`Lib/plistlib.py`

--------------

This module provides an interface for reading and writing the "property list"
XML files used mainly by Mac OS X.

The property list (``.plist``) file format is a simple XML pickle supporting
basic object types, like dictionaries, lists, numbers and strings.  Usually the
top level object is a dictionary.

Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
(but only with string keys), :class:`Data` or :class:`datetime.datetime`
objects.  String values (including dictionary keys) may be unicode strings --
they will be written out as UTF-8.

The ``<data>`` plist type is supported through the :class:`Data` class.  This is
a thin wrapper around a Python string.  Use :class:`Data` if your strings
contain control characters.

.. seealso::

   `PList manual page <https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/plist.5.html>`_
      Apple's documentation of the file format.


This module defines the following functions:

.. function:: readPlist(pathOrFile)

   Read a plist file. *pathOrFile* may either be a file name or a (readable)
   file object.  Return the unpacked root object (which usually is a
   dictionary).

   The XML data is parsed using the Expat parser from :mod:`xml.parsers.expat`
   -- see its documentation for possible exceptions on ill-formed XML.
   Unknown elements will simply be ignored by the plist parser.


.. function:: writePlist(rootObject, pathOrFile)

    Write *rootObject* to a plist file. *pathOrFile* may either be a file name
    or a (writable) file object.

    A :exc:`TypeError` will be raised if the object is of an unsupported type or
    a container that contains objects of unsupported types.


.. function:: readPlistFromString(data)

   Read a plist from a string.  Return the root object.


.. function:: writePlistToString(rootObject)

   Return *rootObject* as a plist-formatted string.



.. function:: readPlistFromResource(path, restype='plst', resid=0)

    Read a plist from the resource with type *restype* from the resource fork of
    *path*.  Availability: Mac OS X.

    .. note::

       In Python 3.x, this function has been removed.


.. function:: writePlistToResource(rootObject, path, restype='plst', resid=0)

    Write *rootObject* as a resource with type *restype* to the resource fork of
    *path*.  Availability: Mac OS X.

    .. note::

       In Python 3.x, this function has been removed.



The following class is available:

.. class:: Data(data)

   Return a "data" wrapper object around the string *data*.  This is used in
   functions converting from/to plists to represent the ``<data>`` type
   available in plists.

   It has one attribute, :attr:`data`, that can be used to retrieve the Python
   string stored in it.


Examples
--------

Generating a plist::

    pl = dict(
        aString="Doodah",
        aList=["A", "B", 12, 32.1, [1, 2, 3]],
        aFloat = 0.1,
        anInt = 728,
        aDict=dict(
            anotherString="<hello & hi there!>",
            aUnicodeValue=u'M\xe4ssig, Ma\xdf',
            aTrueValue=True,
            aFalseValue=False,
        ),
        someData = Data("<binary gunk>"),
        someMoreData = Data("<lots of binary gunk>" * 10),
        aDate = datetime.datetime.fromtimestamp(time.mktime(time.gmtime())),
    )
    # unicode keys are possible, but a little awkward to use:
    pl[u'\xc5benraa'] = "That was a unicode key."
    writePlist(pl, fileName)

Parsing a plist::

    pl = readPlist(pathOrFile)
    print pl["aKey"]
PK	%�\��Cnn$html/_sources/library/popen2.rst.txtnu�[���
:mod:`popen2` --- Subprocesses with accessible I/O streams
==========================================================

.. module:: popen2
   :synopsis: Subprocesses with accessible standard I/O streams.
   :deprecated:
.. sectionauthor:: Drew Csillag <drew_csillag@geocities.com>


.. deprecated:: 2.6
   This module is obsolete.  Use the :mod:`subprocess` module.  Check
   especially the :ref:`subprocess-replacements` section.

This module allows you to spawn processes and connect to their
input/output/error pipes and obtain their return codes under Unix and Windows.

The :mod:`subprocess` module provides more powerful facilities for spawning new
processes and retrieving their results.  Using the :mod:`subprocess` module is
preferable to using the :mod:`popen2` module.

The primary interface offered by this module is a trio of factory functions.
For each of these, if *bufsize* is specified,  it specifies the buffer size for
the I/O pipes.  *mode*, if provided, should be the string ``'b'`` or ``'t'``; on
Windows this is needed to determine whether the file objects should be opened in
binary or text mode.  The default value for *mode* is ``'t'``.

On Unix, *cmd* may be a sequence, in which case arguments will be passed
directly to the program without shell intervention (as with :func:`os.spawnv`).
If *cmd* is a string it will be passed to the shell (as with :func:`os.system`).

The only way to retrieve the return codes for the child processes is by using
the :meth:`poll` or :meth:`wait` methods on the :class:`Popen3` and
:class:`Popen4` classes; these are only available on Unix.  This information is
not available when using the :func:`popen2`, :func:`popen3`, and :func:`popen4`
functions, or the equivalent functions in the :mod:`os` module. (Note that the
tuples returned by the :mod:`os` module's functions are in a different order
from the ones returned by the :mod:`popen2` module.)


.. function:: popen2(cmd[, bufsize[, mode]])

   Executes *cmd* as a sub-process.  Returns the file objects ``(child_stdout,
   child_stdin)``.


.. function:: popen3(cmd[, bufsize[, mode]])

   Executes *cmd* as a sub-process.  Returns the file objects ``(child_stdout,
   child_stdin, child_stderr)``.


.. function:: popen4(cmd[, bufsize[, mode]])

   Executes *cmd* as a sub-process.  Returns the file objects
   ``(child_stdout_and_stderr, child_stdin)``.

   .. versionadded:: 2.0

On Unix, a class defining the objects returned by the factory functions is also
available.  These are not used for the Windows implementation, and are not
available on that platform.


.. class:: Popen3(cmd[, capturestderr[, bufsize]])

   This class represents a child process.  Normally, :class:`Popen3` instances are
   created using the :func:`popen2` and :func:`popen3` factory functions described
   above.

   If not using one of the helper functions to create :class:`Popen3` objects, the
   parameter *cmd* is the shell command to execute in a sub-process.  The
   *capturestderr* flag, if true, specifies that the object should capture standard
   error output of the child process. The default is false.  If the *bufsize*
   parameter is specified, it specifies the size of the I/O buffers to/from the
   child process.


.. class:: Popen4(cmd[, bufsize])

   Similar to :class:`Popen3`, but always captures standard error into the same
   file object as standard output.  These are typically created using
   :func:`popen4`.

   .. versionadded:: 2.0


.. _popen3-objects:

Popen3 and Popen4 Objects
-------------------------

Instances of the :class:`Popen3` and :class:`Popen4` classes have the following
methods:


.. method:: Popen3.poll()

   Returns ``-1`` if child process hasn't completed yet, or its status code
   (see :meth:`wait`) otherwise.


.. method:: Popen3.wait()

   Waits for and returns the status code of the child process.  The status code
   encodes both the return code of the process and information about whether it
   exited using the :c:func:`exit` system call or died due to a signal.  Functions
   to help interpret the status code are defined in the :mod:`os` module; see
   section :ref:`os-process` for the :func:`W\*` family of functions.

The following attributes are also available:


.. attribute:: Popen3.fromchild

   A file object that provides output from the child process.  For :class:`Popen4`
   instances, this will provide both the standard output and standard error
   streams.


.. attribute:: Popen3.tochild

   A file object that provides input to the child process.


.. attribute:: Popen3.childerr

   A file object that provides error output from the child process, if
   *capturestderr* was true for the constructor, otherwise ``None``.  This will
   always be ``None`` for :class:`Popen4` instances.


.. attribute:: Popen3.pid

   The process ID of the child process.


.. _popen2-flow-control:

Flow Control Issues
-------------------

Any time you are working with any form of inter-process communication, control
flow needs to be carefully thought out.  This remains the case with the file
objects provided by this module (or the :mod:`os` module equivalents).

When reading output from a child process that writes a lot of data to standard
error while the parent is reading from the child's standard output, a deadlock
can occur.  A similar situation can occur with other combinations of reads and
writes.  The essential factors are that more than :const:`_PC_PIPE_BUF` bytes
are being written by one process in a blocking fashion, while the other process
is reading from the first process, also in a blocking fashion.

.. Example explanation and suggested work-arounds substantially stolen
   from Martin von Löwis:
   https://mail.python.org/pipermail/python-dev/2000-September/009460.html

There are several ways to deal with this situation.

The simplest application change, in many cases, will be to follow this model in
the parent process::

   import popen2

   r, w, e = popen2.popen3('python slave.py')
   e.readlines()
   r.readlines()
   r.close()
   e.close()
   w.close()

with code like this in the child::

   import os
   import sys

   # note that each of these print statements
   # writes a single long string

   print >>sys.stderr, 400 * 'this is a test\n'
   os.close(sys.stderr.fileno())
   print >>sys.stdout, 400 * 'this is another test\n'

In particular, note that ``sys.stderr`` must be closed after writing all data,
or :meth:`readlines` won't return.  Also note that :func:`os.close` must be
used, as ``sys.stderr.close()`` won't close ``stderr`` (otherwise assigning to
``sys.stderr`` will silently close it, so no further errors can be printed).

Applications which need to support a more general approach should integrate I/O
over pipes with their :func:`select` loops, or use separate threads to read each
of the individual files provided by whichever :func:`popen\*` function or
:class:`Popen\*` class was used.


.. seealso::

   Module :mod:`subprocess`
      Module for spawning and managing subprocesses.

PK	%�\�hMLL$html/_sources/library/poplib.rst.txtnu�[���:mod:`poplib` --- POP3 protocol client
======================================

.. module:: poplib
   :synopsis: POP3 protocol client (requires sockets).
.. sectionauthor:: Andrew T. Csillag
.. revised by ESR, January 2000

.. index:: pair: POP3; protocol

**Source code:** :source:`Lib/poplib.py`

--------------

This module defines a class, :class:`POP3`, which encapsulates a connection to a
POP3 server and implements the protocol as defined in :rfc:`1725`.  The
:class:`POP3` class supports both the minimal and optional command sets.
Additionally, this module provides a class :class:`POP3_SSL`, which provides
support for connecting to POP3 servers that use SSL as an underlying protocol
layer.

Note that POP3, though widely supported, is obsolescent.  The implementation
quality of POP3 servers varies widely, and too many are quite poor. If your
mailserver supports IMAP, you would be better off using the
:class:`imaplib.IMAP4` class, as IMAP servers tend to be better implemented.

The :mod:`poplib` module provides two classes:


.. class:: POP3(host[, port[, timeout]])

   This class implements the actual POP3 protocol.  The connection is created when
   the instance is initialized. If *port* is omitted, the standard POP3 port (110)
   is used. The optional *timeout* parameter specifies a timeout in seconds for the
   connection attempt (if not specified, the global default timeout setting will
   be used).

   .. versionchanged:: 2.6
      *timeout* was added.


.. class:: POP3_SSL(host[, port[, keyfile[, certfile]]])

   This is a subclass of :class:`POP3` that connects to the server over an SSL
   encrypted socket.  If *port* is not specified, 995, the standard POP3-over-SSL
   port is used.  *keyfile* and *certfile* are also optional - they can contain a
   PEM formatted private key and certificate chain file for the SSL connection.

   .. versionadded:: 2.4

One exception is defined as an attribute of the :mod:`poplib` module:


.. exception:: error_proto

   Exception raised on any errors from this module (errors from :mod:`socket`
   module are not caught). The reason for the exception is passed to the
   constructor as a string.


.. seealso::

   Module :mod:`imaplib`
      The standard Python IMAP module.

   `Frequently Asked Questions About Fetchmail <http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html>`_
      The FAQ for the :program:`fetchmail` POP/IMAP client collects information on
      POP3 server variations and RFC noncompliance that may be useful if you need to
      write an application based on the POP protocol.


.. _pop3-objects:

POP3 Objects
------------

All POP3 commands are represented by methods of the same name, in lower-case;
most return the response text sent by the server.

An :class:`POP3` instance has the following methods:


.. method:: POP3.set_debuglevel(level)

   Set the instance's debugging level.  This controls the amount of debugging
   output printed.  The default, ``0``, produces no debugging output.  A value of
   ``1`` produces a moderate amount of debugging output, generally a single line
   per request.  A value of ``2`` or higher produces the maximum amount of
   debugging output, logging each line sent and received on the control connection.


.. method:: POP3.getwelcome()

   Returns the greeting string sent by the POP3 server.


.. method:: POP3.user(username)

   Send user command, response should indicate that a password is required.


.. method:: POP3.pass_(password)

   Send password, response includes message count and mailbox size. Note: the
   mailbox on the server is locked until :meth:`~poplib.quit` is called.


.. method:: POP3.apop(user, secret)

   Use the more secure APOP authentication to log into the POP3 server.


.. method:: POP3.rpop(user)

   Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.


.. method:: POP3.stat()

   Get mailbox status.  The result is a tuple of 2 integers: ``(message count,
   mailbox size)``.


.. method:: POP3.list([which])

   Request message list, result is in the form ``(response, ['mesg_num octets',
   ...], octets)``. If *which* is set, it is the message to list.


.. method:: POP3.retr(which)

   Retrieve whole message number *which*, and set its seen flag. Result is in form
   ``(response, ['line', ...], octets)``.


.. method:: POP3.dele(which)

   Flag message number *which* for deletion.  On most servers deletions are not
   actually performed until QUIT (the major exception is Eudora QPOP, which
   deliberately violates the RFCs by doing pending deletes on any disconnect).


.. method:: POP3.rset()

   Remove any deletion marks for the mailbox.


.. method:: POP3.noop()

   Do nothing.  Might be used as a keep-alive.


.. method:: POP3.quit()

   Signoff:  commit changes, unlock mailbox, drop connection.


.. method:: POP3.top(which, howmuch)

   Retrieves the message header plus *howmuch* lines of the message after the
   header of message number *which*. Result is in form ``(response, ['line', ...],
   octets)``.

   The POP3 TOP command this method uses, unlike the RETR command, doesn't set the
   message's seen flag; unfortunately, TOP is poorly specified in the RFCs and is
   frequently broken in off-brand servers. Test this method by hand against the
   POP3 servers you will use before trusting it.


.. method:: POP3.uidl([which])

   Return message digest (unique id) list. If *which* is specified, result contains
   the unique id for that message in the form ``'response mesgnum uid``, otherwise
   result is list ``(response, ['mesgnum uid', ...], octets)``.

Instances of :class:`POP3_SSL` have no additional methods. The interface of this
subclass is identical to its parent.


.. _pop3-example:

POP3 Example
------------

Here is a minimal example (without error checking) that opens a mailbox and
retrieves and prints all messages::

   import getpass, poplib

   M = poplib.POP3('localhost')
   M.user(getpass.getuser())
   M.pass_(getpass.getpass())
   numMessages = len(M.list()[1])
   for i in range(numMessages):
       for j in M.retr(i+1)[1]:
           print j

At the end of the module, there is a test section that contains a more extensive
example of usage.

PK	%�\H�o	..#html/_sources/library/posix.rst.txtnu�[���:mod:`posix` --- The most common POSIX system calls
===================================================

.. module:: posix
   :platform: Unix
   :synopsis: The most common POSIX system calls (normally used via module os).


This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised Unix
interface).

.. index:: module: os

**Do not import this module directly.**  Instead, import the module :mod:`os`,
which provides a *portable* version of this interface.  On Unix, the :mod:`os`
module provides a superset of the :mod:`posix` interface.  On non-Unix operating
systems the :mod:`posix` module is not available, but a subset is always
available through the :mod:`os` interface.  Once :mod:`os` is imported, there is
*no* performance penalty in using it instead of :mod:`posix`.  In addition,
:mod:`os` provides some additional functionality, such as automatically calling
:func:`~os.putenv` when an entry in ``os.environ`` is changed.

Errors are reported as exceptions; the usual exceptions are given for type
errors, while errors reported by the system calls raise :exc:`OSError`.


.. _posix-large-files:

Large File Support
------------------

.. index::
   single: large files
   single: file; large files

.. sectionauthor:: Steve Clift <clift@mail.anacapa.net>

Several operating systems (including AIX, HP-UX, Irix and Solaris) provide
support for files that are larger than 2 GB from a C programming model where
:c:type:`int` and :c:type:`long` are 32-bit values. This is typically accomplished
by defining the relevant size and offset types as 64-bit values. Such files are
sometimes referred to as :dfn:`large files`.

Large file support is enabled in Python when the size of an :c:type:`off_t` is
larger than a :c:type:`long` and the :c:type:`long long` type is available and is
at least as large as an :c:type:`off_t`. Python longs are then used to represent
file sizes, offsets and other values that can exceed the range of a Python int.
It may be necessary to configure and compile Python with certain compiler flags
to enable this mode. For example, it is enabled by default with recent versions
of Irix, but with Solaris 2.6 and 2.7 you need to do something like::

   CFLAGS="`getconf LFS_CFLAGS`" OPT="-g -O2 $CFLAGS" \
           ./configure

On large-file-capable Linux systems, this might work::

   CFLAGS='-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64' OPT="-g -O2 $CFLAGS" \
           ./configure


.. _posix-contents:

Notable Module Contents
-----------------------

In addition to many functions described in the :mod:`os` module documentation,
:mod:`posix` defines the following data item:

.. data:: environ

   A dictionary representing the string environment at the time the interpreter
   was started.  For example, ``environ['HOME']`` is the pathname of your home
   directory, equivalent to ``getenv("HOME")`` in C.

   Modifying this dictionary does not affect the string environment passed on by
   :func:`~os.execv`, :func:`~os.popen` or :func:`~os.system`; if you need to
   change the environment, pass ``environ`` to :func:`~os.execve` or add
   variable assignments and export statements to the command string for
   :func:`~os.system` or :func:`~os.popen`.

   .. note::

      The :mod:`os` module provides an alternate implementation of ``environ`` which
      updates the environment on modification.  Note also that updating ``os.environ``
      will render this dictionary obsolete.  Use of the :mod:`os` module version of
      this is recommended over direct access to the :mod:`posix` module.
PK	%�\,NO�  'html/_sources/library/posixfile.rst.txtnu�[���:mod:`posixfile` --- File-like objects with locking support
===========================================================

.. module:: posixfile
   :platform: Unix
   :synopsis: A file-like object with support for locking.
   :deprecated:
.. moduleauthor:: Jaap Vermeulen
.. sectionauthor:: Jaap Vermeulen


.. index:: pair: POSIX; file object

.. deprecated:: 1.5
   The locking operation that this module provides is done better and more portably
   by the :func:`fcntl.lockf` call.

.. index:: single: fcntl() (in module fcntl)

This module implements some additional functionality over the built-in file
objects.  In particular, it implements file locking, control over the file
flags, and an easy interface to duplicate the file object. The module defines a
new file object, the posixfile object.  It has all the standard file object
methods and adds the methods described below.  This module only works for
certain flavors of Unix, since it uses :func:`fcntl.fcntl` for file locking.

To instantiate a posixfile object, use the :func:`posixfile.open` function.  The
resulting object looks and feels roughly the same as a standard file object.

The :mod:`posixfile` module defines the following constants:


.. data:: SEEK_SET

   Offset is calculated from the start of the file.


.. data:: SEEK_CUR

   Offset is calculated from the current position in the file.


.. data:: SEEK_END

   Offset is calculated from the end of the file.

The :mod:`posixfile` module defines the following functions:


.. function:: open(filename[, mode[, bufsize]])

   Create a new posixfile object with the given filename and mode.  The *filename*,
   *mode* and *bufsize* arguments are interpreted the same way as by the built-in
   :func:`open` function.


.. function:: fileopen(fileobject)

   Create a new posixfile object with the given standard file object. The resulting
   object has the same filename and mode as the original file object.

The posixfile object defines the following additional methods:


.. method:: posixfile.lock(fmt, [len[, start[, whence]]])

   Lock the specified section of the file that the file object is referring to.
   The format is explained below in a table.  The *len* argument specifies the
   length of the section that should be locked. The default is ``0``. *start*
   specifies the starting offset of the section, where the default is ``0``.  The
   *whence* argument specifies where the offset is relative to. It accepts one of
   the constants :const:`SEEK_SET`, :const:`SEEK_CUR` or :const:`SEEK_END`.  The
   default is :const:`SEEK_SET`.  For more information about the arguments refer to
   the :manpage:`fcntl(2)` manual page on your system.


.. method:: posixfile.flags([flags])

   Set the specified flags for the file that the file object is referring to.  The
   new flags are ORed with the old flags, unless specified otherwise.  The format
   is explained below in a table.  Without the *flags* argument a string indicating
   the current flags is returned (this is the same as the ``?`` modifier).  For
   more information about the flags refer to the :manpage:`fcntl(2)` manual page on
   your system.


.. method:: posixfile.dup()

   Duplicate the file object and the underlying file pointer and file descriptor.
   The resulting object behaves as if it were newly opened.


.. method:: posixfile.dup2(fd)

   Duplicate the file object and the underlying file pointer and file descriptor.
   The new object will have the given file descriptor. Otherwise the resulting
   object behaves as if it were newly opened.


.. method:: posixfile.file()

   Return the standard file object that the posixfile object is based on.  This is
   sometimes necessary for functions that insist on a standard file object.

All methods raise :exc:`IOError` when the request fails.

Format characters for the :meth:`lock` method have the following meaning:

+--------+-----------------------------------------------+
| Format | Meaning                                       |
+========+===============================================+
| ``u``  | unlock the specified region                   |
+--------+-----------------------------------------------+
| ``r``  | request a read lock for the specified section |
+--------+-----------------------------------------------+
| ``w``  | request a write lock for the specified        |
|        | section                                       |
+--------+-----------------------------------------------+

In addition the following modifiers can be added to the format:

+----------+--------------------------------+-------+
| Modifier | Meaning                        | Notes |
+==========+================================+=======+
| ``|``    | wait until the lock has been   |       |
|          | granted                        |       |
+----------+--------------------------------+-------+
| ``?``    | return the first lock          | \(1)  |
|          | conflicting with the requested |       |
|          | lock, or ``None`` if there is  |       |
|          | no conflict.                   |       |
+----------+--------------------------------+-------+

Note:

(1)
   The lock returned is in the format ``(mode, len, start, whence, pid)`` where
   *mode* is a character representing the type of lock ('r' or 'w').  This modifier
   prevents a request from being granted; it is for query purposes only.

Format characters for the :meth:`flags` method have the following meanings:

+--------+-----------------------------------------------+
| Format | Meaning                                       |
+========+===============================================+
| ``a``  | append only flag                              |
+--------+-----------------------------------------------+
| ``c``  | close on exec flag                            |
+--------+-----------------------------------------------+
| ``n``  | no delay flag (also called non-blocking flag) |
+--------+-----------------------------------------------+
| ``s``  | synchronization flag                          |
+--------+-----------------------------------------------+

In addition the following modifiers can be added to the format:

+----------+---------------------------------+-------+
| Modifier | Meaning                         | Notes |
+==========+=================================+=======+
| ``!``    | turn the specified flags 'off', | \(1)  |
|          | instead of the default 'on'     |       |
+----------+---------------------------------+-------+
| ``=``    | replace the flags, instead of   | \(1)  |
|          | the default 'OR' operation      |       |
+----------+---------------------------------+-------+
| ``?``    | return a string in which the    | \(2)  |
|          | characters represent the flags  |       |
|          | that are set.                   |       |
+----------+---------------------------------+-------+

Notes:

(1)
   The ``!`` and ``=`` modifiers are mutually exclusive.

(2)
   This string represents the flags after they may have been altered by the same
   call.

Examples::

   import posixfile

   file = posixfile.open('testfile', 'w')
   file.lock('w|')
   ...
   file.lock('u')
   file.close()

PK	%�\���o#o#$html/_sources/library/pprint.rst.txtnu�[���:mod:`pprint` --- Data pretty printer
=====================================

.. module:: pprint
   :synopsis: Data pretty printer.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/pprint.py`

--------------

The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable.  This may be the case if objects
such as files, sockets, classes, or instances are included, as well as many
other built-in objects which are not representable as Python constants.

The formatted representation keeps objects on a single line if it can, and
breaks them onto multiple lines if they don't fit within the allowed width.
Construct :class:`PrettyPrinter` objects explicitly if you need to adjust the
width constraint.

.. versionchanged:: 2.5
   Dictionaries are sorted by key before the display is computed; before 2.5, a
   dictionary was sorted only if its display required more than one line, although
   that wasn't documented.

.. versionchanged:: 2.6
   Added support for :class:`set` and :class:`frozenset`.


The :mod:`pprint` module defines one class:

.. First the implementation class:


.. class:: PrettyPrinter(indent=1, width=80, depth=None, stream=None)

   Construct a :class:`PrettyPrinter` instance.  This constructor understands
   several keyword parameters.  An output stream may be set using the *stream*
   keyword; the only method used on the stream object is the file protocol's
   :meth:`write` method.  If not specified, the :class:`PrettyPrinter` adopts
   ``sys.stdout``.  Three additional parameters may be used to control the
   formatted representation.  The keywords are *indent*, *depth*, and *width*.  The
   amount of indentation added for each recursive level is specified by *indent*;
   the default is one.  Other values can cause output to look a little odd, but can
   make nesting easier to spot.  The number of levels which may be printed is
   controlled by *depth*; if the data structure being printed is too deep, the next
   contained level is replaced by ``...``.  By default, there is no constraint on
   the depth of the objects being formatted.  The desired output width is
   constrained using the *width* parameter; the default is 80 characters.  If a
   structure cannot be formatted within the constrained width, a best effort will
   be made.

      >>> import pprint
      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
      >>> stuff.insert(0, stuff[:])
      >>> pp = pprint.PrettyPrinter(indent=4)
      >>> pp.pprint(stuff)
      [   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
          'spam',
          'eggs',
          'lumberjack',
          'knights',
          'ni']
      >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
      ... ('parrot', ('fresh fruit',))))))))
      >>> pp = pprint.PrettyPrinter(depth=6)
      >>> pp.pprint(tup)
      ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead', (...)))))))

The :class:`PrettyPrinter` class supports several derivative functions:

.. function:: pformat(object, indent=1, width=80, depth=None)

   Return the formatted representation of *object* as a string.  *indent*, *width*
   and *depth* will be passed to the :class:`PrettyPrinter` constructor as
   formatting parameters.

   .. versionchanged:: 2.4
      The parameters *indent*, *width* and *depth* were added.


.. function:: pprint(object, stream=None, indent=1, width=80, depth=None)

   Prints the formatted representation of *object* on *stream*, followed by a
   newline.  If *stream* is ``None``, ``sys.stdout`` is used.  This may be used in
   the interactive interpreter instead of a :keyword:`print` statement for
   inspecting values.    *indent*, *width* and *depth* will be passed to the
   :class:`PrettyPrinter` constructor as formatting parameters.

      >>> import pprint
      >>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
      >>> stuff.insert(0, stuff)
      >>> pprint.pprint(stuff)
      [<Recursion on list with id=...>,
       'spam',
       'eggs',
       'lumberjack',
       'knights',
       'ni']

   .. versionchanged:: 2.4
      The parameters *indent*, *width* and *depth* were added.


.. function:: isreadable(object)

   .. index:: builtin: eval

   Determine if the formatted representation of *object* is "readable," or can be
   used to reconstruct the value using :func:`eval`.  This always returns ``False``
   for recursive objects.

      >>> pprint.isreadable(stuff)
      False


.. function:: isrecursive(object)

   Determine if *object* requires a recursive representation.


One more support function is also defined:

.. function:: saferepr(object)

   Return a string representation of *object*, protected against recursive data
   structures.  If the representation of *object* exposes a recursive entry, the
   recursive reference will be represented as ``<Recursion on typename with
   id=number>``.  The representation is not otherwise formatted.

   >>> pprint.saferepr(stuff)
   "[<Recursion on list with id=...>, 'spam', 'eggs', 'lumberjack', 'knights', 'ni']"


.. _prettyprinter-objects:

PrettyPrinter Objects
---------------------

:class:`PrettyPrinter` instances have the following methods:


.. method:: PrettyPrinter.pformat(object)

   Return the formatted representation of *object*.  This takes into account the
   options passed to the :class:`PrettyPrinter` constructor.


.. method:: PrettyPrinter.pprint(object)

   Print the formatted representation of *object* on the configured stream,
   followed by a newline.

The following methods provide the implementations for the corresponding
functions of the same names.  Using these methods on an instance is slightly
more efficient since new :class:`PrettyPrinter` objects don't need to be
created.


.. method:: PrettyPrinter.isreadable(object)

   .. index:: builtin: eval

   Determine if the formatted representation of the object is "readable," or can be
   used to reconstruct the value using :func:`eval`.  Note that this returns
   ``False`` for recursive objects.  If the *depth* parameter of the
   :class:`PrettyPrinter` is set and the object is deeper than allowed, this
   returns ``False``.


.. method:: PrettyPrinter.isrecursive(object)

   Determine if the object requires a recursive representation.

This method is provided as a hook to allow subclasses to modify the way objects
are converted to strings.  The default implementation uses the internals of the
:func:`saferepr` implementation.


.. method:: PrettyPrinter.format(object, context, maxlevels, level)

   Returns three values: the formatted version of *object* as a string, a flag
   indicating whether the result is readable, and a flag indicating whether
   recursion was detected.  The first argument is the object to be presented.  The
   second is a dictionary which contains the :func:`id` of objects that are part of
   the current presentation context (direct and indirect containers for *object*
   that are affecting the presentation) as the keys; if an object needs to be
   presented which is already represented in *context*, the third return value
   should be ``True``.  Recursive calls to the :meth:`.format` method should add
   additional entries for containers to this dictionary.  The third argument,
   *maxlevels*, gives the requested limit to recursion; this will be ``0`` if there
   is no requested limit.  This argument should be passed unmodified to recursive
   calls. The fourth argument, *level*, gives the current level; recursive calls
   should be passed a value less than that of the current call.

   .. versionadded:: 2.3

.. _pprint-example:

pprint Example
--------------

This example demonstrates several uses of the :func:`pprint` function and its
parameters.

   >>> import pprint
   >>> tup = ('spam', ('eggs', ('lumberjack', ('knights', ('ni', ('dead',
   ... ('parrot', ('fresh fruit',))))))))
   >>> stuff = ['a' * 10, tup, ['a' * 30, 'b' * 30], ['c' * 20, 'd' * 20]]
   >>> pprint.pprint(stuff)
   ['aaaaaaaaaa',
    ('spam',
     ('eggs',
      ('lumberjack',
       ('knights', ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
    ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
    ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
   >>> pprint.pprint(stuff, depth=3)
   ['aaaaaaaaaa',
    ('spam', ('eggs', (...))),
    ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
    ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
   >>> pprint.pprint(stuff, width=60)
   ['aaaaaaaaaa',
    ('spam',
     ('eggs',
      ('lumberjack',
       ('knights',
        ('ni', ('dead', ('parrot', ('fresh fruit',)))))))),
    ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
     'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
    ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
PK	%�\��~�o�o%html/_sources/library/profile.rst.txtnu�[���.. _profile:

********************
The Python Profilers
********************

**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py`

--------------

.. _profiler-introduction:

Introduction to the profilers
=============================

.. index::
   single: deterministic profiling
   single: profiling, deterministic

:mod:`cProfile` and :mod:`profile` provide :dfn:`deterministic profiling` of
Python programs. A :dfn:`profile` is a set of statistics that describes how
often and for how long various parts of the program executed. These statistics
can be formatted into reports via the :mod:`pstats` module.

The Python standard library provides three different implementations of the same
profiling interface:

1. :mod:`cProfile` is recommended for most users; it's a C extension with
   reasonable overhead that makes it suitable for profiling long-running
   programs.  Based on :mod:`lsprof`, contributed by Brett Rosen and Ted
   Czotter.

   .. versionadded:: 2.5

2. :mod:`profile`, a pure Python module whose interface is imitated by
   :mod:`cProfile`, but which adds significant overhead to profiled programs.
   If you're trying to extend the profiler in some way, the task might be easier
   with this module.  Originally designed and written by Jim Roskind.

   .. versionchanged:: 2.4
      Now also reports the time spent in calls to built-in functions
      and methods.

3. :mod:`hotshot` was an experimental C module that focused on minimizing
   the overhead of profiling, at the expense of longer data
   post-processing times.  It is no longer maintained and may be
   dropped in a future version of Python.


   .. versionchanged:: 2.5
      The results should be more meaningful than in the past: the timing core
      contained a critical bug.

The :mod:`profile` and :mod:`cProfile` modules export the same interface, so
they are mostly interchangeable; :mod:`cProfile` has a much lower overhead but
is newer and might not be available on all systems.
:mod:`cProfile` is really a compatibility layer on top of the internal
:mod:`_lsprof` module.  The :mod:`hotshot` module is reserved for specialized
usage.

.. note::

   The profiler modules are designed to provide an execution profile for a given
   program, not for benchmarking purposes (for that, there is :mod:`timeit` for
   reasonably accurate results).  This particularly applies to benchmarking
   Python code against C code: the profilers introduce overhead for Python code,
   but not for C-level functions, and so the C code would seem faster than any
   Python one.


.. _profile-instant:

Instant User's Manual
=====================

This section is provided for users that "don't want to read the manual." It
provides a very brief overview, and allows a user to rapidly perform profiling
on an existing application.

To profile a function that takes a single argument, you can do::

   import cProfile
   import re
   cProfile.run('re.compile("foo|bar")')

(Use :mod:`profile` instead of :mod:`cProfile` if the latter is not available on
your system.)

The above action would run :func:`re.compile` and print profile results like
the following::

         197 function calls (192 primitive calls) in 0.002 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.001    0.001 <string>:1(<module>)
        1    0.000    0.000    0.001    0.001 re.py:212(compile)
        1    0.000    0.000    0.001    0.001 re.py:268(_compile)
        1    0.000    0.000    0.000    0.000 sre_compile.py:172(_compile_charset)
        1    0.000    0.000    0.000    0.000 sre_compile.py:201(_optimize_charset)
        4    0.000    0.000    0.000    0.000 sre_compile.py:25(_identityfunction)
      3/1    0.000    0.000    0.000    0.000 sre_compile.py:33(_compile)

The first line indicates that 197 calls were monitored.  Of those calls, 192
were :dfn:`primitive`, meaning that the call was not induced via recursion. The
next line: ``Ordered by: standard name``, indicates that the text string in the
far right column was used to sort the output. The column headings include:

ncalls
   for the number of calls,

tottime
    for the total time spent in the given function (and excluding time made in
    calls to sub-functions)

percall
   is the quotient of ``tottime`` divided by ``ncalls``

cumtime
   is the cumulative time spent in this and all subfunctions (from invocation
   till exit). This figure is accurate *even* for recursive functions.

percall
   is the quotient of ``cumtime`` divided by primitive calls

filename:lineno(function)
   provides the respective data of each function

When there are two numbers in the first column (for example ``3/1``), it means
that the function recursed.  The second value is the number of primitive calls
and the former is the total number of calls.  Note that when the function does
not recurse, these two values are the same, and only the single figure is
printed.

Instead of printing the output at the end of the profile run, you can save the
results to a file by specifying a filename to the :func:`run` function::

   import cProfile
   import re
   cProfile.run('re.compile("foo|bar")', 'restats')

The :class:`pstats.Stats` class reads profile results from a file and formats
them in various ways.

The file :mod:`cProfile` can also be invoked as a script to profile another
script.  For example::

   python -m cProfile [-o output_file] [-s sort_order] myscript.py

``-o`` writes the profile results to a file instead of to stdout

``-s`` specifies one of the :func:`~pstats.Stats.sort_stats` sort values to sort
the output by. This only applies when ``-o`` is not supplied.

The :mod:`pstats` module's :class:`~pstats.Stats` class has a variety of methods
for manipulating and printing the data saved into a profile results file::

   import pstats
   p = pstats.Stats('restats')
   p.strip_dirs().sort_stats(-1).print_stats()

The :meth:`~pstats.Stats.strip_dirs` method removed the extraneous path from all
the module names. The :meth:`~pstats.Stats.sort_stats` method sorted all the
entries according to the standard module/line/name string that is printed. The
:meth:`~pstats.Stats.print_stats` method printed out all the statistics.  You
might try the following sort calls::

   p.sort_stats('name')
   p.print_stats()

The first call will actually sort the list by function name, and the second call
will print out the statistics.  The following are some interesting calls to
experiment with::

   p.sort_stats('cumulative').print_stats(10)

This sorts the profile by cumulative time in a function, and then only prints
the ten most significant lines.  If you want to understand what algorithms are
taking time, the above line is what you would use.

If you were looking to see what functions were looping a lot, and taking a lot
of time, you would do::

   p.sort_stats('time').print_stats(10)

to sort according to time spent within each function, and then print the
statistics for the top ten functions.

You might also try::

   p.sort_stats('file').print_stats('__init__')

This will sort all the statistics by file name, and then print out statistics
for only the class init methods (since they are spelled with ``__init__`` in
them).  As one final example, you could try::

   p.sort_stats('time', 'cum').print_stats(.5, 'init')

This line sorts statistics with a primary key of time, and a secondary key of
cumulative time, and then prints out some of the statistics. To be specific, the
list is first culled down to 50% (re: ``.5``) of its original size, then only
lines containing ``init`` are maintained, and that sub-sub-list is printed.

If you wondered what functions called the above functions, you could now (``p``
is still sorted according to the last criteria) do::

   p.print_callers(.5, 'init')

and you would get a list of callers for each of the listed functions.

If you want more functionality, you're going to have to read the manual, or
guess what the following functions do::

   p.print_callees()
   p.add('restats')

Invoked as a script, the :mod:`pstats` module is a statistics browser for
reading and examining profile dumps.  It has a simple line-oriented interface
(implemented using :mod:`cmd`) and interactive help.

:mod:`profile` and :mod:`cProfile` Module Reference
=======================================================

.. module:: cProfile
.. module:: profile
   :synopsis: Python source profiler.

Both the :mod:`profile` and :mod:`cProfile` modules provide the following
functions:

.. function:: run(command, filename=None, sort=-1)

   This function takes a single argument that can be passed to the :func:`exec`
   function, and an optional file name.  In all cases this routine executes::

      exec(command, __main__.__dict__, __main__.__dict__)

   and gathers profiling statistics from the execution. If no file name is
   present, then this function automatically creates a :class:`~pstats.Stats`
   instance and prints a simple profiling report. If the sort value is specified
   it is passed to this :class:`~pstats.Stats` instance to control how the
   results are sorted.

.. function:: runctx(command, globals, locals, filename=None)

   This function is similar to :func:`run`, with added arguments to supply the
   globals and locals dictionaries for the *command* string. This routine
   executes::

      exec(command, globals, locals)

   and gathers profiling statistics as in the :func:`run` function above.

.. class:: Profile(timer=None, timeunit=0.0, subcalls=True, builtins=True)

   This class is normally only used if more precise control over profiling is
   needed than what the :func:`cProfile.run` function provides.

   A custom timer can be supplied for measuring how long code takes to run via
   the *timer* argument. This must be a function that returns a single number
   representing the current time. If the number is an integer, the *timeunit*
   specifies a multiplier that specifies the duration of each unit of time. For
   example, if the timer returns times measured in thousands of seconds, the
   time unit would be ``.001``.

   Directly using the :class:`Profile` class allows formatting profile results
   without writing the profile data to a file::

      import cProfile, pstats, StringIO
      pr = cProfile.Profile()
      pr.enable()
      # ... do something ...
      pr.disable()
      s = StringIO.StringIO()
      sortby = 'cumulative'
      ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
      ps.print_stats()
      print s.getvalue()

   .. method:: enable()

      Start collecting profiling data.

   .. method:: disable()

      Stop collecting profiling data.

   .. method:: create_stats()

      Stop collecting profiling data and record the results internally
      as the current profile.

   .. method:: print_stats(sort=-1)

      Create a :class:`~pstats.Stats` object based on the current
      profile and print the results to stdout.

   .. method:: dump_stats(filename)

      Write the results of the current profile to *filename*.

   .. method:: run(cmd)

      Profile the cmd via :func:`exec`.

   .. method:: runctx(cmd, globals, locals)

      Profile the cmd via :func:`exec` with the specified global and
      local environment.

   .. method:: runcall(func, *args, **kwargs)

      Profile ``func(*args, **kwargs)``

.. _profile-stats:

The :class:`Stats` Class
========================

Analysis of the profiler data is done using the :class:`~pstats.Stats` class.

.. module:: pstats
   :synopsis: Statistics object for use with the profiler.

.. class:: Stats(*filenames or profile, stream=sys.stdout)

   This class constructor creates an instance of a "statistics object" from a
   *filename* (or list of filenames) or from a :class:`Profile` instance. Output
   will be printed to the stream specified by *stream*.

   The file selected by the above constructor must have been created by the
   corresponding version of :mod:`profile` or :mod:`cProfile`.  To be specific,
   there is *no* file compatibility guaranteed with future versions of this
   profiler, and there is no compatibility with files produced by other
   profilers, or the same profiler run on a different operating system.  If
   several files are provided, all the statistics for identical functions will
   be coalesced, so that an overall view of several processes can be considered
   in a single report.  If additional files need to be combined with data in an
   existing :class:`~pstats.Stats` object, the :meth:`~pstats.Stats.add` method
   can be used.

   Instead of reading the profile data from a file, a :class:`cProfile.Profile`
   or :class:`profile.Profile` object can be used as the profile data source.

   :class:`Stats` objects have the following methods:

   .. method:: strip_dirs()

      This method for the :class:`Stats` class removes all leading path
      information from file names.  It is very useful in reducing the size of
      the printout to fit within (close to) 80 columns.  This method modifies
      the object, and the stripped information is lost.  After performing a
      strip operation, the object is considered to have its entries in a
      "random" order, as it was just after object initialization and loading.
      If :meth:`~pstats.Stats.strip_dirs` causes two function names to be
      indistinguishable (they are on the same line of the same filename, and
      have the same function name), then the statistics for these two entries
      are accumulated into a single entry.


   .. method:: add(*filenames)

      This method of the :class:`Stats` class accumulates additional profiling
      information into the current profiling object.  Its arguments should refer
      to filenames created by the corresponding version of :func:`profile.run`
      or :func:`cProfile.run`. Statistics for identically named (re: file, line,
      name) functions are automatically accumulated into single function
      statistics.


   .. method:: dump_stats(filename)

      Save the data loaded into the :class:`Stats` object to a file named
      *filename*.  The file is created if it does not exist, and is overwritten
      if it already exists.  This is equivalent to the method of the same name
      on the :class:`profile.Profile` and :class:`cProfile.Profile` classes.

   .. versionadded:: 2.3


   .. method:: sort_stats(*keys)

      This method modifies the :class:`Stats` object by sorting it according to
      the supplied criteria.  The argument is typically a string identifying the
      basis of a sort (example: ``'time'`` or ``'name'``).

      When more than one key is provided, then additional keys are used as
      secondary criteria when there is equality in all keys selected before
      them.  For example, ``sort_stats('name', 'file')`` will sort all the
      entries according to their function name, and resolve all ties (identical
      function names) by sorting by file name.

      Abbreviations can be used for any key names, as long as the abbreviation
      is unambiguous.  The following are the keys currently defined:

      +------------------+----------------------+
      | Valid Arg        | Meaning              |
      +==================+======================+
      | ``'calls'``      | call count           |
      +------------------+----------------------+
      | ``'cumulative'`` | cumulative time      |
      +------------------+----------------------+
      | ``'cumtime'``    | cumulative time      |
      +------------------+----------------------+
      | ``'file'``       | file name            |
      +------------------+----------------------+
      | ``'filename'``   | file name            |
      +------------------+----------------------+
      | ``'module'``     | file name            |
      +------------------+----------------------+
      | ``'ncalls'``     | call count           |
      +------------------+----------------------+
      | ``'pcalls'``     | primitive call count |
      +------------------+----------------------+
      | ``'line'``       | line number          |
      +------------------+----------------------+
      | ``'name'``       | function name        |
      +------------------+----------------------+
      | ``'nfl'``        | name/file/line       |
      +------------------+----------------------+
      | ``'stdname'``    | standard name        |
      +------------------+----------------------+
      | ``'time'``       | internal time        |
      +------------------+----------------------+
      | ``'tottime'``    | internal time        |
      +------------------+----------------------+

      Note that all sorts on statistics are in descending order (placing most
      time consuming items first), where as name, file, and line number searches
      are in ascending order (alphabetical). The subtle distinction between
      ``'nfl'`` and ``'stdname'`` is that the standard name is a sort of the
      name as printed, which means that the embedded line numbers get compared
      in an odd way.  For example, lines 3, 20, and 40 would (if the file names
      were the same) appear in the string order 20, 3 and 40.  In contrast,
      ``'nfl'`` does a numeric compare of the line numbers.  In fact,
      ``sort_stats('nfl')`` is the same as ``sort_stats('name', 'file',
      'line')``.

      For backward-compatibility reasons, the numeric arguments ``-1``, ``0``,
      ``1``, and ``2`` are permitted.  They are interpreted as ``'stdname'``,
      ``'calls'``, ``'time'``, and ``'cumulative'`` respectively.  If this old
      style format (numeric) is used, only one sort key (the numeric key) will
      be used, and additional arguments will be silently ignored.

      .. For compatibility with the old profiler.


   .. method:: reverse_order()

      This method for the :class:`Stats` class reverses the ordering of the
      basic list within the object.  Note that by default ascending vs
      descending order is properly selected based on the sort key of choice.

      .. This method is provided primarily for compatibility with the old
         profiler.


   .. method:: print_stats(*restrictions)

      This method for the :class:`Stats` class prints out a report as described
      in the :func:`profile.run` definition.

      The order of the printing is based on the last
      :meth:`~pstats.Stats.sort_stats` operation done on the object (subject to
      caveats in :meth:`~pstats.Stats.add` and
      :meth:`~pstats.Stats.strip_dirs`).

      The arguments provided (if any) can be used to limit the list down to the
      significant entries.  Initially, the list is taken to be the complete set
      of profiled functions.  Each restriction is either an integer (to select a
      count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to
      select a percentage of lines), or a regular expression (to pattern match
      the standard name that is printed.  If several restrictions are provided,
      then they are applied sequentially.  For example::

         print_stats(.1, 'foo:')

      would first limit the printing to first 10% of list, and then only print
      functions that were part of filename :file:`.\*foo:`.  In contrast, the
      command::

         print_stats('foo:', .1)

      would limit the list to all functions having file names :file:`.\*foo:`,
      and then proceed to only print the first 10% of them.


   .. method:: print_callers(*restrictions)

      This method for the :class:`Stats` class prints a list of all functions
      that called each function in the profiled database.  The ordering is
      identical to that provided by :meth:`~pstats.Stats.print_stats`, and the
      definition of the restricting argument is also identical.  Each caller is
      reported on its own line.  The format differs slightly depending on the
      profiler that produced the stats:

      * With :mod:`profile`, a number is shown in parentheses after each caller
        to show how many times this specific call was made.  For convenience, a
        second non-parenthesized number repeats the cumulative time spent in the
        function at the right.

      * With :mod:`cProfile`, each caller is preceded by three numbers: the
        number of times this specific call was made, and the total and
        cumulative times spent in the current function while it was invoked by
        this specific caller.


   .. method:: print_callees(*restrictions)

      This method for the :class:`Stats` class prints a list of all function
      that were called by the indicated function.  Aside from this reversal of
      direction of calls (re: called vs was called by), the arguments and
      ordering are identical to the :meth:`~pstats.Stats.print_callers` method.


.. _deterministic-profiling:

What Is Deterministic Profiling?
================================

:dfn:`Deterministic profiling` is meant to reflect the fact that all *function
call*, *function return*, and *exception* events are monitored, and precise
timings are made for the intervals between these events (during which time the
user's code is executing).  In contrast, :dfn:`statistical profiling` (which is
not done by this module) randomly samples the effective instruction pointer, and
deduces where time is being spent.  The latter technique traditionally involves
less overhead (as the code does not need to be instrumented), but provides only
relative indications of where time is being spent.

In Python, since there is an interpreter active during execution, the presence
of instrumented code is not required to do deterministic profiling.  Python
automatically provides a :dfn:`hook` (optional callback) for each event.  In
addition, the interpreted nature of Python tends to add so much overhead to
execution, that deterministic profiling tends to only add small processing
overhead in typical applications.  The result is that deterministic profiling is
not that expensive, yet provides extensive run time statistics about the
execution of a Python program.

Call count statistics can be used to identify bugs in code (surprising counts),
and to identify possible inline-expansion points (high call counts).  Internal
time statistics can be used to identify "hot loops" that should be carefully
optimized.  Cumulative time statistics should be used to identify high level
errors in the selection of algorithms.  Note that the unusual handling of
cumulative times in this profiler allows statistics for recursive
implementations of algorithms to be directly compared to iterative
implementations.


.. _profile-limitations:

Limitations
===========

One limitation has to do with accuracy of timing information. There is a
fundamental problem with deterministic profilers involving accuracy.  The most
obvious restriction is that the underlying "clock" is only ticking at a rate
(typically) of about .001 seconds.  Hence no measurements will be more accurate
than the underlying clock.  If enough measurements are taken, then the "error"
will tend to average out. Unfortunately, removing this first error induces a
second source of error.

The second problem is that it "takes a while" from when an event is dispatched
until the profiler's call to get the time actually *gets* the state of the
clock.  Similarly, there is a certain lag when exiting the profiler event
handler from the time that the clock's value was obtained (and then squirreled
away), until the user's code is once again executing.  As a result, functions
that are called many times, or call many functions, will typically accumulate
this error. The error that accumulates in this fashion is typically less than
the accuracy of the clock (less than one clock tick), but it *can* accumulate
and become very significant.

The problem is more important with :mod:`profile` than with the lower-overhead
:mod:`cProfile`.  For this reason, :mod:`profile` provides a means of
calibrating itself for a given platform so that this error can be
probabilistically (on the average) removed. After the profiler is calibrated, it
will be more accurate (in a least square sense), but it will sometimes produce
negative numbers (when call counts are exceptionally low, and the gods of
probability work against you :-). )  Do *not* be alarmed by negative numbers in
the profile.  They should *only* appear if you have calibrated your profiler,
and the results are actually better than without calibration.


.. _profile-calibration:

Calibration
===========

The profiler of the :mod:`profile` module subtracts a constant from each event
handling time to compensate for the overhead of calling the time function, and
socking away the results.  By default, the constant is 0. The following
procedure can be used to obtain a better constant for a given platform (see
:ref:`profile-limitations`). ::

   import profile
   pr = profile.Profile()
   for i in range(5):
       print pr.calibrate(10000)

The method executes the number of Python calls given by the argument, directly
and again under the profiler, measuring the time for both. It then computes the
hidden overhead per profiler event, and returns that as a float.  For example,
on a 1.8Ghz Intel Core i5 running Mac OS X, and using Python's time.clock() as
the timer, the magical number is about 4.04e-6.

The object of this exercise is to get a fairly consistent result. If your
computer is *very* fast, or your timer function has poor resolution, you might
have to pass 100000, or even 1000000, to get consistent results.

When you have a consistent answer, there are three ways you can use it: [#]_ ::

   import profile

   # 1. Apply computed bias to all Profile instances created hereafter.
   profile.Profile.bias = your_computed_bias

   # 2. Apply computed bias to a specific Profile instance.
   pr = profile.Profile()
   pr.bias = your_computed_bias

   # 3. Specify computed bias in instance constructor.
   pr = profile.Profile(bias=your_computed_bias)

If you have a choice, you are better off choosing a smaller constant, and then
your results will "less often" show up as negative in profile statistics.

.. _profile-timers:

Using a custom timer
====================

If you want to change how current time is determined (for example, to force use
of wall-clock time or elapsed process time), pass the timing function you want
to the :class:`Profile` class constructor::

    pr = profile.Profile(your_time_func)

The resulting profiler will then call ``your_time_func``. Depending on whether
you are using :class:`profile.Profile` or :class:`cProfile.Profile`,
``your_time_func``'s return value will be interpreted differently:

:class:`profile.Profile`
   ``your_time_func`` should return a single number, or a list of numbers whose
   sum is the current time (like what :func:`os.times` returns).  If the
   function returns a single time number, or the list of returned numbers has
   length 2, then you will get an especially fast version of the dispatch
   routine.

   Be warned that you should calibrate the profiler class for the timer function
   that you choose (see :ref:`profile-calibration`).  For most machines, a timer
   that returns a lone integer value will provide the best results in terms of
   low overhead during profiling.  (:func:`os.times` is *pretty* bad, as it
   returns a tuple of floating point values).  If you want to substitute a
   better timer in the cleanest fashion, derive a class and hardwire a
   replacement dispatch method that best handles your timer call, along with the
   appropriate calibration constant.

:class:`cProfile.Profile`
   ``your_time_func`` should return a single number.  If it returns integers,
   you can also invoke the class constructor with a second argument specifying
   the real duration of one unit of time.  For example, if
   ``your_integer_time_func`` returns times measured in thousands of seconds,
   you would construct the :class:`Profile` instance as follows::

      pr = cProfile.Profile(your_integer_time_func, 0.001)

   As the :class:`cProfile.Profile` class cannot be calibrated, custom timer
   functions should be used with care and should be as fast as possible.  For
   the best results with a custom timer, it might be necessary to hard-code it
   in the C source of the internal :mod:`_lsprof` module.


.. rubric:: Footnotes

.. [#] Prior to Python 2.2, it was necessary to edit the profiler source code to
   embed the bias as a literal number.  You still can, but that method is no longer
   described, because no longer needed.
PK	%�\���J��!html/_sources/library/pty.rst.txtnu�[���
:mod:`pty` --- Pseudo-terminal utilities
========================================

.. module:: pty
   :platform: Linux
   :synopsis: Pseudo-Terminal Handling for Linux.
.. moduleauthor:: Steen Lumholt
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`pty` module defines operations for handling the pseudo-terminal
concept: starting another process and being able to write to and read from its
controlling terminal programmatically.

Because pseudo-terminal handling is highly platform dependent, there is code to
do it only for Linux. (The Linux code is supposed to work on other platforms,
but hasn't been tested yet.)

The :mod:`pty` module defines the following functions:


.. function:: fork()

   Fork. Connect the child's controlling terminal to a pseudo-terminal. Return
   value is ``(pid, fd)``. Note that the child  gets *pid* 0, and the *fd* is
   *invalid*. The parent's return value is the *pid* of the child, and *fd* is a
   file descriptor connected to the child's controlling terminal (and also to the
   child's standard input and output).


.. function:: openpty()

   Open a new pseudo-terminal pair, using :func:`os.openpty` if possible, or
   emulation code for generic Unix systems. Return a pair of file descriptors
   ``(master, slave)``, for the master and the slave end, respectively.


.. function:: spawn(argv[, master_read[, stdin_read]])

   Spawn a process, and connect its controlling terminal with the current
   process's standard io. This is often used to baffle programs which insist on
   reading from the controlling terminal.

   The functions *master_read* and *stdin_read* should be functions which read from
   a file descriptor. The defaults try to read 1024 bytes each time they are
   called.

PK	%�\��� �
�
!html/_sources/library/pwd.rst.txtnu�[���
:mod:`pwd` --- The password database
====================================

.. module:: pwd
   :platform: Unix
   :synopsis: The password database (getpwnam() and friends).


This module provides access to the Unix user account and password database.  It
is available on all Unix versions.

Password database entries are reported as a tuple-like object, whose attributes
correspond to the members of the ``passwd`` structure (Attribute field below,
see ``<pwd.h>``):

+-------+---------------+-----------------------------+
| Index | Attribute     | Meaning                     |
+=======+===============+=============================+
| 0     | ``pw_name``   | Login name                  |
+-------+---------------+-----------------------------+
| 1     | ``pw_passwd`` | Optional encrypted password |
+-------+---------------+-----------------------------+
| 2     | ``pw_uid``    | Numerical user ID           |
+-------+---------------+-----------------------------+
| 3     | ``pw_gid``    | Numerical group ID          |
+-------+---------------+-----------------------------+
| 4     | ``pw_gecos``  | User name or comment field  |
+-------+---------------+-----------------------------+
| 5     | ``pw_dir``    | User home directory         |
+-------+---------------+-----------------------------+
| 6     | ``pw_shell``  | User command interpreter    |
+-------+---------------+-----------------------------+

The uid and gid items are integers, all others are strings. :exc:`KeyError` is
raised if the entry asked for cannot be found.

.. note::

   .. index:: module: crypt

   In traditional Unix the field ``pw_passwd`` usually contains a password
   encrypted with a DES derived algorithm (see module :mod:`crypt`).  However most
   modern unices  use a so-called *shadow password* system.  On those unices the
   *pw_passwd* field only contains an asterisk (``'*'``) or the  letter ``'x'``
   where the encrypted password is stored in a file :file:`/etc/shadow` which is
   not world readable.  Whether the *pw_passwd* field contains anything useful is
   system-dependent.  If available, the :mod:`spwd` module should be used where
   access to the encrypted password is required.

It defines the following items:


.. function:: getpwuid(uid)

   Return the password database entry for the given numeric user ID.


.. function:: getpwnam(name)

   Return the password database entry for the given user name.


.. function:: getpwall()

   Return a list of all available password database entries, in arbitrary order.


.. seealso::

   Module :mod:`grp`
      An interface to the group database, similar to this.

   Module :mod:`spwd`
      An interface to the shadow password database, similar to this.

PK	%�\��8�	�	(html/_sources/library/py_compile.rst.txtnu�[���:mod:`py_compile` --- Compile Python source files
=================================================

.. module:: py_compile
   :synopsis: Generate byte-code files from Python source files.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. documentation based on module docstrings

.. index:: pair: file; byte-code

**Source code:** :source:`Lib/py_compile.py`

--------------

The :mod:`py_compile` module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.

Though not often needed, this function can be useful when installing modules for
shared use, especially if some of the users may not have permission to write the
byte-code cache files in the directory containing the source code.


.. exception:: PyCompileError

   Exception raised when an error occurs while attempting to compile the file.


.. function:: compile(file[, cfile[, dfile[, doraise]]])

   Compile a source file to byte-code and write out the byte-code cache  file.  The
   source code is loaded from the file named *file*.  The  byte-code is written to
   *cfile*, which defaults to *file* ``+`` ``'c'`` (``'o'`` if optimization is
   enabled in the current interpreter).  If *dfile* is specified, it is used as the
   name of the source file in error messages instead of *file*.  If *doraise* is
   true, a :exc:`PyCompileError` is raised when an error is encountered while
   compiling *file*. If *doraise* is false (the default), an error string is
   written to ``sys.stderr``, but no exception is raised.


.. function:: main([args])

   Compile several source files.  The files named in *args* (or on the command
   line, if *args* is not specified) are compiled and the resulting bytecode is
   cached in the normal manner.  This function does not search a directory
   structure to locate source files; it only compiles files named explicitly.
   If ``'-'`` is the only parameter in args, the list of files is taken from
   standard input.

   .. versionchanged:: 2.7
      Added support for ``'-'``.

When this module is run as a script, the :func:`main` is used to compile all the
files named on the command line.  The exit status is nonzero if one of the files
could not be compiled.

.. versionchanged:: 2.6
   Added the nonzero exit status when module is run as a script.


.. seealso::

   Module :mod:`compileall`
      Utilities to compile all Python source files in a directory tree.

PK
%�\$qR��$html/_sources/library/pyclbr.rst.txtnu�[���:mod:`pyclbr` --- Python class browser support
==============================================

.. module:: pyclbr
   :synopsis: Supports information extraction for a Python class browser.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/pyclbr.py`

--------------

The :mod:`pyclbr` module can be used to determine some limited information
about the classes, methods and top-level functions defined in a module.  The
information provided is sufficient to implement a traditional three-pane
class browser.  The information is extracted from the source code rather
than by importing the module, so this module is safe to use with untrusted
code.  This restriction makes it impossible to use this module with modules
not implemented in Python, including all standard and optional extension
modules.


.. function:: readmodule(module, path=None)

   Read a module and return a dictionary mapping class names to class
   descriptor objects.  The parameter *module* should be the name of a
   module as a string; it may be the name of a module within a package.  The
   *path* parameter should be a sequence, and is used to augment the value
   of ``sys.path``, which is used to locate module source code.


.. function:: readmodule_ex(module, path=None)

   Like :func:`readmodule`, but the returned dictionary, in addition to
   mapping class names to class descriptor objects, also maps top-level
   function names to function descriptor objects.  Moreover, if the module
   being read is a package, the key ``'__path__'`` in the returned
   dictionary has as its value a list which contains the package search
   path.


.. _pyclbr-class-objects:

Class Objects
-------------

The :class:`Class` objects used as values in the dictionary returned by
:func:`readmodule` and :func:`readmodule_ex` provide the following data
attributes:


.. attribute:: Class.module

   The name of the module defining the class described by the class descriptor.


.. attribute:: Class.name

   The name of the class.


.. attribute:: Class.super

   A list of :class:`Class` objects which describe the immediate base
   classes of the class being described.  Classes which are named as
   superclasses but which are not discoverable by :func:`readmodule` are
   listed as a string with the class name instead of as :class:`Class`
   objects.


.. attribute:: Class.methods

   A dictionary mapping method names to line numbers.


.. attribute:: Class.file

   Name of the file containing the ``class`` statement defining the class.


.. attribute:: Class.lineno

   The line number of the ``class`` statement within the file named by
   :attr:`~Class.file`.


.. _pyclbr-function-objects:

Function Objects
----------------

The :class:`Function` objects used as values in the dictionary returned by
:func:`readmodule_ex` provide the following attributes:


.. attribute:: Function.module

   The name of the module defining the function described by the function
   descriptor.


.. attribute:: Function.name

   The name of the function.


.. attribute:: Function.file

   Name of the file containing the ``def`` statement defining the function.


.. attribute:: Function.lineno

   The line number of the ``def`` statement within the file named by
   :attr:`~Function.file`.

PK
%�\�J����#html/_sources/library/pydoc.rst.txtnu�[���:mod:`pydoc` --- Documentation generator and online help system
===============================================================

.. module:: pydoc
   :synopsis: Documentation generator and online help system.
.. moduleauthor:: Ka-Ping Yee <ping@lfw.org>
.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>


.. versionadded:: 2.1

.. index::
   single: documentation; generation
   single: documentation; online
   single: help; online

**Source code:** :source:`Lib/pydoc.py`

--------------

The :mod:`pydoc` module automatically generates documentation from Python
modules.  The documentation can be presented as pages of text on the console,
served to a Web browser, or saved to HTML files.

For modules, classes, functions and methods, the displayed documentation is
derived from the docstring (i.e. the :attr:`__doc__` attribute) of the object,
and recursively of its documentable members.  If there is no docstring,
:mod:`pydoc` tries to obtain a description from the block of comment lines just
above the definition of the class, function or method in the source file, or at
the top of the module (see :func:`inspect.getcomments`).

The built-in function :func:`help` invokes the online help system in the
interactive interpreter, which uses :mod:`pydoc` to generate its documentation
as text on the console.  The same text documentation can also be viewed from
outside the Python interpreter by running :program:`pydoc` as a script at the
operating system's command prompt. For example, running ::

   pydoc sys

at a shell prompt will display documentation on the :mod:`sys` module, in a
style similar to the manual pages shown by the Unix :program:`man` command.  The
argument to :program:`pydoc` can be the name of a function, module, or package,
or a dotted reference to a class, method, or function within a module or module
in a package.  If the argument to :program:`pydoc` looks like a path (that is,
it contains the path separator for your operating system, such as a slash in
Unix), and refers to an existing Python source file, then documentation is
produced for that file.

.. note::

   In order to find objects and their documentation, :mod:`pydoc` imports the
   module(s) to be documented.  Therefore, any code on module level will be
   executed on that occasion.  Use an ``if __name__ == '__main__':`` guard to
   only execute code when a file is invoked as a script and not just imported.

When printing output to the console, :program:`pydoc` attempts to paginate the
output for easier reading.  If the :envvar:`PAGER` environment variable is set,
:program:`pydoc` will use its value as a pagination program.

Specifying a ``-w`` flag before the argument will cause HTML documentation
to be written out to a file in the current directory, instead of displaying text
on the console.

Specifying a ``-k`` flag before the argument will search the synopsis
lines of all available modules for the keyword given as the argument, again in a
manner similar to the Unix :program:`man` command.  The synopsis line of a
module is the first line of its documentation string.

You can also use :program:`pydoc` to start an HTTP server on the local machine
that will serve documentation to visiting Web browsers. :program:`pydoc -p 1234`
will start a HTTP server on port 1234, allowing you to browse
the documentation at ``http://localhost:1234/`` in your preferred Web browser.
:program:`pydoc -g` will start the server and additionally bring up a
small :mod:`Tkinter`\ -based graphical interface to help you search for
documentation pages.

When :program:`pydoc` generates documentation, it uses the current environment
and path to locate modules.  Thus, invoking :program:`pydoc spam`
documents precisely the version of the module you would get if you started the
Python interpreter and typed ``import spam``.

Module docs for core modules are assumed to reside in
https://docs.python.org/library/.  This can be overridden by setting the
:envvar:`PYTHONDOCS` environment variable to a different URL or to a local
directory containing the Library Reference Manual pages.

PK
%�\x7��p�p%html/_sources/library/pyexpat.rst.txtnu�[���
:mod:`xml.parsers.expat` --- Fast XML parsing using Expat
=========================================================

.. module:: xml.parsers.expat
   :synopsis: An interface to the Expat non-validating XML parser.
.. moduleauthor:: Paul Prescod <paul@prescod.net>


.. Markup notes:

   Many of the attributes of the XMLParser objects are callbacks.  Since
   signature information must be presented, these are described using the method
   directive.  Since they are attributes which are set by client code, in-text
   references to these attributes should be marked using the :member: role.


.. warning::

   The :mod:`pyexpat` module is not secure against maliciously
   constructed data.  If you need to parse untrusted or unauthenticated data see
   :ref:`xml-vulnerabilities`.


.. versionadded:: 2.0

.. index:: single: Expat

The :mod:`xml.parsers.expat` module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
:class:`xmlparser`, that represents the current state of an XML parser.  After
an :class:`xmlparser` object has been created, various attributes of the object
can be set to handler functions.  When an XML document is then fed to the
parser, the handler functions are called for the character data and markup in
the XML document.

.. index:: module: pyexpat

This module uses the :mod:`pyexpat` module to provide access to the Expat
parser.  Direct use of the :mod:`pyexpat` module is deprecated.

This module provides one exception and one type object:


.. exception:: ExpatError

   The exception raised when Expat reports an error.  See section
   :ref:`expaterror-objects` for more information on interpreting Expat errors.


.. exception:: error

   Alias for :exc:`ExpatError`.


.. data:: XMLParserType

   The type of the return values from the :func:`ParserCreate` function.

The :mod:`xml.parsers.expat` module contains two functions:


.. function:: ErrorString(errno)

   Returns an explanatory string for a given error number *errno*.


.. function:: ParserCreate([encoding[, namespace_separator]])

   Creates and returns a new :class:`xmlparser` object.   *encoding*, if specified,
   must be a string naming the encoding  used by the XML data.  Expat doesn't
   support as many encodings as Python does, and its repertoire of encodings can't
   be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII.  If
   *encoding* [1]_ is given it will override the implicit or explicit encoding of the
   document.

   Expat can optionally do XML namespace processing for you, enabled by providing a
   value for *namespace_separator*.  The value must be a one-character string; a
   :exc:`ValueError` will be raised if the string has an illegal length (``None``
   is considered the same as omission).  When namespace processing is enabled,
   element type names and attribute names that belong to a namespace will be
   expanded.  The element name passed to the element handlers
   :attr:`StartElementHandler` and :attr:`EndElementHandler` will be the
   concatenation of the namespace URI, the namespace separator character, and the
   local part of the name.  If the namespace separator is a zero byte (``chr(0)``)
   then the namespace URI and the local part will be concatenated without any
   separator.

   For example, if *namespace_separator* is set to a space character (``' '``) and
   the following document is parsed:

   .. code-block:: xml

      <?xml version="1.0"?>
      <root xmlns    = "http://default-namespace.org/"
            xmlns:py = "http://www.python.org/ns/">
        <py:elem1 />
        <elem2 xmlns="" />
      </root>

   :attr:`StartElementHandler` will receive the following strings for each
   element::

      http://default-namespace.org/ root
      http://www.python.org/ns/ elem1
      elem2

   Due to limitations in the ``Expat`` library used by :mod:`pyexpat`,
   the :class:`xmlparser` instance returned can only be used to parse a single
   XML document.  Call ``ParserCreate`` for each document to provide unique
   parser instances.

.. seealso::

   `The Expat XML Parser <http://www.libexpat.org/>`_
      Home page of the Expat project.


.. _xmlparser-objects:

XMLParser Objects
-----------------

:class:`xmlparser` objects have the following methods:


.. method:: xmlparser.Parse(data[, isfinal])

   Parses the contents of the string *data*, calling the appropriate handler
   functions to process the parsed data.  *isfinal* must be true on the final call
   to this method; it allows the parsing of a single file in fragments,
   not the submission of multiple files.
   *data* can be the empty string at any time.


.. method:: xmlparser.ParseFile(file)

   Parse XML data reading from the object *file*.  *file* only needs to provide
   the ``read(nbytes)`` method, returning the empty string when there's no more
   data.


.. method:: xmlparser.SetBase(base)

   Sets the base to be used for resolving relative URIs in system identifiers in
   declarations.  Resolving relative identifiers is left to the application: this
   value will be passed through as the *base* argument to the
   :func:`ExternalEntityRefHandler`, :func:`NotationDeclHandler`, and
   :func:`UnparsedEntityDeclHandler` functions.


.. method:: xmlparser.GetBase()

   Returns a string containing the base set by a previous call to :meth:`SetBase`,
   or ``None`` if  :meth:`SetBase` hasn't been called.


.. method:: xmlparser.GetInputContext()

   Returns the input data that generated the current event as a string. The data is
   in the encoding of the entity which contains the text. When called while an
   event handler is not active, the return value is ``None``.

   .. versionadded:: 2.1


.. method:: xmlparser.ExternalEntityParserCreate(context[, encoding])

   Create a "child" parser which can be used to parse an external parsed entity
   referred to by content parsed by the parent parser.  The *context* parameter
   should be the string passed to the :meth:`ExternalEntityRefHandler` handler
   function, described below. The child parser is created with the
   :attr:`ordered_attributes`, :attr:`returns_unicode` and
   :attr:`specified_attributes` set to the values of this parser.

.. method:: xmlparser.SetParamEntityParsing(flag)

   Control parsing of parameter entities (including the external DTD subset).
   Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`,
   :const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and
   :const:`XML_PARAM_ENTITY_PARSING_ALWAYS`.  Return true if setting the flag
   was successful.

.. method:: xmlparser.UseForeignDTD([flag])

   Calling this with a true value for *flag* (the default) will cause Expat to call
   the :attr:`ExternalEntityRefHandler` with :const:`None` for all arguments to
   allow an alternate DTD to be loaded.  If the document does not contain a
   document type declaration, the :attr:`ExternalEntityRefHandler` will still be
   called, but the :attr:`StartDoctypeDeclHandler` and
   :attr:`EndDoctypeDeclHandler` will not be called.

   Passing a false value for *flag* will cancel a previous call that passed a true
   value, but otherwise has no effect.

   This method can only be called before the :meth:`Parse` or :meth:`ParseFile`
   methods are called; calling it after either of those have been called causes
   :exc:`ExpatError` to be raised with the :attr:`code` attribute set to
   :const:`errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING`.

   .. versionadded:: 2.3

:class:`xmlparser` objects have the following attributes:


.. attribute:: xmlparser.buffer_size

   The size of the buffer used when :attr:`buffer_text` is true.
   A new buffer size can be set by assigning a new integer value
   to this attribute.
   When the size is changed, the buffer will be flushed.

   .. versionadded:: 2.3

   .. versionchanged:: 2.6
      The buffer size can now be changed.

.. attribute:: xmlparser.buffer_text

   Setting this to true causes the :class:`xmlparser` object to buffer textual
   content returned by Expat to avoid multiple calls to the
   :meth:`CharacterDataHandler` callback whenever possible.  This can improve
   performance substantially since Expat normally breaks character data into chunks
   at every line ending.  This attribute is false by default, and may be changed at
   any time.

   .. versionadded:: 2.3


.. attribute:: xmlparser.buffer_used

   If :attr:`buffer_text` is enabled, the number of bytes stored in the buffer.
   These bytes represent UTF-8 encoded text.  This attribute has no meaningful
   interpretation when :attr:`buffer_text` is false.

   .. versionadded:: 2.3


.. attribute:: xmlparser.ordered_attributes

   Setting this attribute to a non-zero integer causes the attributes to be
   reported as a list rather than a dictionary.  The attributes are presented in
   the order found in the document text.  For each attribute, two list entries are
   presented: the attribute name and the attribute value.  (Older versions of this
   module also used this format.)  By default, this attribute is false; it may be
   changed at any time.

   .. versionadded:: 2.1


.. attribute:: xmlparser.returns_unicode

   If this attribute is set to a non-zero integer, the handler functions will be
   passed Unicode strings.  If :attr:`returns_unicode` is :const:`False`, 8-bit
   strings containing UTF-8 encoded data will be passed to the handlers.  This is
   :const:`True` by default when Python is built with Unicode support.

   .. versionchanged:: 1.6
      Can be changed at any time to affect the result type.


.. attribute:: xmlparser.specified_attributes

   If set to a non-zero integer, the parser will report only those attributes which
   were specified in the document instance and not those which were derived from
   attribute declarations.  Applications which set this need to be especially
   careful to use what additional information is available from the declarations as
   needed to comply with the standards for the behavior of XML processors.  By
   default, this attribute is false; it may be changed at any time.

   .. versionadded:: 2.1

The following attributes contain values relating to the most recent error
encountered by an :class:`xmlparser` object, and will only have correct values
once a call to :meth:`Parse` or :meth:`ParseFile` has raised an
:exc:`xml.parsers.expat.ExpatError` exception.


.. attribute:: xmlparser.ErrorByteIndex

   Byte index at which an error occurred.


.. attribute:: xmlparser.ErrorCode

   Numeric code specifying the problem.  This value can be passed to the
   :func:`ErrorString` function, or compared to one of the constants defined in the
   ``errors`` object.


.. attribute:: xmlparser.ErrorColumnNumber

   Column number at which an error occurred.


.. attribute:: xmlparser.ErrorLineNumber

   Line number at which an error occurred.

The following attributes contain values relating to the current parse location
in an :class:`xmlparser` object.  During a callback reporting a parse event they
indicate the location of the first of the sequence of characters that generated
the event.  When called outside of a callback, the position indicated will be
just past the last parse event (regardless of whether there was an associated
callback).

.. versionadded:: 2.4


.. attribute:: xmlparser.CurrentByteIndex

   Current byte index in the parser input.


.. attribute:: xmlparser.CurrentColumnNumber

   Current column number in the parser input.


.. attribute:: xmlparser.CurrentLineNumber

   Current line number in the parser input.

Here is the list of handlers that can be set.  To set a handler on an
:class:`xmlparser` object *o*, use ``o.handlername = func``.  *handlername* must
be taken from the following list, and *func* must be a callable object accepting
the correct number of arguments.  The arguments are all strings, unless
otherwise stated.


.. method:: xmlparser.XmlDeclHandler(version, encoding, standalone)

   Called when the XML declaration is parsed.  The XML declaration is the
   (optional) declaration of the applicable version of the XML recommendation, the
   encoding of the document text, and an optional "standalone" declaration.
   *version* and *encoding* will be strings of the type dictated by the
   :attr:`returns_unicode` attribute, and *standalone* will be ``1`` if the
   document is declared standalone, ``0`` if it is declared not to be standalone,
   or ``-1`` if the standalone clause was omitted. This is only available with
   Expat version 1.95.0 or newer.

   .. versionadded:: 2.1


.. method:: xmlparser.StartDoctypeDeclHandler(doctypeName, systemId, publicId, has_internal_subset)

   Called when Expat begins parsing the document type declaration (``<!DOCTYPE
   ...``).  The *doctypeName* is provided exactly as presented.  The *systemId* and
   *publicId* parameters give the system and public identifiers if specified, or
   ``None`` if omitted.  *has_internal_subset* will be true if the document
   contains and internal document declaration subset. This requires Expat version
   1.2 or newer.


.. method:: xmlparser.EndDoctypeDeclHandler()

   Called when Expat is done parsing the document type declaration. This requires
   Expat version 1.2 or newer.


.. method:: xmlparser.ElementDeclHandler(name, model)

   Called once for each element type declaration.  *name* is the name of the
   element type, and *model* is a representation of the content model.


.. method:: xmlparser.AttlistDeclHandler(elname, attname, type, default, required)

   Called for each declared attribute for an element type.  If an attribute list
   declaration declares three attributes, this handler is called three times, once
   for each attribute.  *elname* is the name of the element to which the
   declaration applies and *attname* is the name of the attribute declared.  The
   attribute type is a string passed as *type*; the possible values are
   ``'CDATA'``, ``'ID'``, ``'IDREF'``, ... *default* gives the default value for
   the attribute used when the attribute is not specified by the document instance,
   or ``None`` if there is no default value (``#IMPLIED`` values).  If the
   attribute is required to be given in the document instance, *required* will be
   true. This requires Expat version 1.95.0 or newer.


.. method:: xmlparser.StartElementHandler(name, attributes)

   Called for the start of every element.  *name* is a string containing the
   element name, and *attributes* is a dictionary mapping attribute names to their
   values.


.. method:: xmlparser.EndElementHandler(name)

   Called for the end of every element.


.. method:: xmlparser.ProcessingInstructionHandler(target, data)

   Called for every processing instruction.


.. method:: xmlparser.CharacterDataHandler(data)

   Called for character data.  This will be called for normal character data, CDATA
   marked content, and ignorable whitespace.  Applications which must distinguish
   these cases can use the :attr:`StartCdataSectionHandler`,
   :attr:`EndCdataSectionHandler`, and :attr:`ElementDeclHandler` callbacks to
   collect the required information.


.. method:: xmlparser.UnparsedEntityDeclHandler(entityName, base, systemId, publicId, notationName)

   Called for unparsed (NDATA) entity declarations.  This is only present for
   version 1.2 of the Expat library; for more recent versions, use
   :attr:`EntityDeclHandler` instead.  (The underlying function in the Expat
   library has been declared obsolete.)


.. method:: xmlparser.EntityDeclHandler(entityName, is_parameter_entity, value, base, systemId, publicId, notationName)

   Called for all entity declarations.  For parameter and internal entities,
   *value* will be a string giving the declared contents of the entity; this will
   be ``None`` for external entities.  The *notationName* parameter will be
   ``None`` for parsed entities, and the name of the notation for unparsed
   entities. *is_parameter_entity* will be true if the entity is a parameter entity
   or false for general entities (most applications only need to be concerned with
   general entities). This is only available starting with version 1.95.0 of the
   Expat library.

   .. versionadded:: 2.1


.. method:: xmlparser.NotationDeclHandler(notationName, base, systemId, publicId)

   Called for notation declarations.  *notationName*, *base*, and *systemId*, and
   *publicId* are strings if given.  If the public identifier is omitted,
   *publicId* will be ``None``.


.. method:: xmlparser.StartNamespaceDeclHandler(prefix, uri)

   Called when an element contains a namespace declaration.  Namespace declarations
   are processed before the :attr:`StartElementHandler` is called for the element
   on which declarations are placed.


.. method:: xmlparser.EndNamespaceDeclHandler(prefix)

   Called when the closing tag is reached for an element  that contained a
   namespace declaration.  This is called once for each namespace declaration on
   the element in the reverse of the order for which the
   :attr:`StartNamespaceDeclHandler` was called to indicate the start of each
   namespace declaration's scope.  Calls to this handler are made after the
   corresponding :attr:`EndElementHandler` for the end of the element.


.. method:: xmlparser.CommentHandler(data)

   Called for comments.  *data* is the text of the comment, excluding the leading
   ``'<!-``\ ``-'`` and trailing ``'-``\ ``->'``.


.. method:: xmlparser.StartCdataSectionHandler()

   Called at the start of a CDATA section.  This and :attr:`EndCdataSectionHandler`
   are needed to be able to identify the syntactical start and end for CDATA
   sections.


.. method:: xmlparser.EndCdataSectionHandler()

   Called at the end of a CDATA section.


.. method:: xmlparser.DefaultHandler(data)

   Called for any characters in the XML document for which no applicable handler
   has been specified.  This means characters that are part of a construct which
   could be reported, but for which no handler has been supplied.


.. method:: xmlparser.DefaultHandlerExpand(data)

   This is the same as the :func:`DefaultHandler`,  but doesn't inhibit expansion
   of internal entities. The entity reference will not be passed to the default
   handler.


.. method:: xmlparser.NotStandaloneHandler()

   Called if the XML document hasn't been declared as being a standalone document.
   This happens when there is an external subset or a reference to a parameter
   entity, but the XML declaration does not set standalone to ``yes`` in an XML
   declaration.  If this handler returns ``0``, then the parser will raise an
   :const:`XML_ERROR_NOT_STANDALONE` error.  If this handler is not set, no
   exception is raised by the parser for this condition.


.. method:: xmlparser.ExternalEntityRefHandler(context, base, systemId, publicId)

   Called for references to external entities.  *base* is the current base, as set
   by a previous call to :meth:`SetBase`.  The public and system identifiers,
   *systemId* and *publicId*, are strings if given; if the public identifier is not
   given, *publicId* will be ``None``.  The *context* value is opaque and should
   only be used as described below.

   For external entities to be parsed, this handler must be implemented. It is
   responsible for creating the sub-parser using
   ``ExternalEntityParserCreate(context)``, initializing it with the appropriate
   callbacks, and parsing the entity.  This handler should return an integer; if it
   returns ``0``, the parser will raise an
   :const:`XML_ERROR_EXTERNAL_ENTITY_HANDLING` error, otherwise parsing will
   continue.

   If this handler is not provided, external entities are reported by the
   :attr:`DefaultHandler` callback, if provided.


.. _expaterror-objects:

ExpatError Exceptions
---------------------

.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


:exc:`ExpatError` exceptions have a number of interesting attributes:


.. attribute:: ExpatError.code

   Expat's internal error number for the specific error.  This will match one of
   the constants defined in the ``errors`` object from this module.

   .. versionadded:: 2.1


.. attribute:: ExpatError.lineno

   Line number on which the error was detected.  The first line is numbered ``1``.

   .. versionadded:: 2.1


.. attribute:: ExpatError.offset

   Character offset into the line where the error occurred.  The first column is
   numbered ``0``.

   .. versionadded:: 2.1


.. _expat-example:

Example
-------

The following program defines three handlers that just print out their
arguments. ::

   import xml.parsers.expat

   # 3 handler functions
   def start_element(name, attrs):
       print 'Start element:', name, attrs
   def end_element(name):
       print 'End element:', name
   def char_data(data):
       print 'Character data:', repr(data)

   p = xml.parsers.expat.ParserCreate()

   p.StartElementHandler = start_element
   p.EndElementHandler = end_element
   p.CharacterDataHandler = char_data

   p.Parse("""<?xml version="1.0"?>
   <parent id="top"><child1 name="paul">Text goes here</child1>
   <child2 name="fred">More text</child2>
   </parent>""", 1)

The output from this program is::

   Start element: parent {'id': 'top'}
   Start element: child1 {'name': 'paul'}
   Character data: 'Text goes here'
   End element: child1
   Character data: '\n'
   Start element: child2 {'name': 'fred'}
   Character data: 'More text'
   End element: child2
   Character data: '\n'
   End element: parent


.. _expat-content-models:

Content Model Descriptions
--------------------------

.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


Content models are described using nested tuples.  Each tuple contains four
values: the type, the quantifier, the name, and a tuple of children.  Children
are simply additional content model descriptions.

The values of the first two fields are constants defined in the ``model`` object
of the :mod:`xml.parsers.expat` module.  These constants can be collected in two
groups: the model type group and the quantifier group.

The constants in the model type group are:


.. data:: XML_CTYPE_ANY
   :noindex:

   The element named by the model name was declared to have a content model of
   ``ANY``.


.. data:: XML_CTYPE_CHOICE
   :noindex:

   The named element allows a choice from a number of options; this is used for
   content models such as ``(A | B | C)``.


.. data:: XML_CTYPE_EMPTY
   :noindex:

   Elements which are declared to be ``EMPTY`` have this model type.


.. data:: XML_CTYPE_MIXED
   :noindex:


.. data:: XML_CTYPE_NAME
   :noindex:


.. data:: XML_CTYPE_SEQ
   :noindex:

   Models which represent a series of models which follow one after the other are
   indicated with this model type.  This is used for models such as ``(A, B, C)``.

The constants in the quantifier group are:


.. data:: XML_CQUANT_NONE
   :noindex:

   No modifier is given, so it can appear exactly once, as for ``A``.


.. data:: XML_CQUANT_OPT
   :noindex:

   The model is optional: it can appear once or not at all, as for ``A?``.


.. data:: XML_CQUANT_PLUS
   :noindex:

   The model must occur one or more times (like ``A+``).


.. data:: XML_CQUANT_REP
   :noindex:

   The model must occur zero or more times, as for ``A*``.


.. _expat-errors:

Expat error constants
---------------------

The following constants are provided in the ``errors`` object of the
:mod:`xml.parsers.expat` module.  These constants are useful in interpreting
some of the attributes of the :exc:`ExpatError` exception objects raised when an
error has occurred.

The ``errors`` object has the following attributes:


.. data:: XML_ERROR_ASYNC_ENTITY
   :noindex:


.. data:: XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF
   :noindex:

   An entity reference in an attribute value referred to an external entity instead
   of an internal entity.


.. data:: XML_ERROR_BAD_CHAR_REF
   :noindex:

   A character reference referred to a character which is illegal in XML (for
   example, character ``0``, or '``&#0;``').


.. data:: XML_ERROR_BINARY_ENTITY_REF
   :noindex:

   An entity reference referred to an entity which was declared with a notation, so
   cannot be parsed.


.. data:: XML_ERROR_DUPLICATE_ATTRIBUTE
   :noindex:

   An attribute was used more than once in a start tag.


.. data:: XML_ERROR_INCORRECT_ENCODING
   :noindex:


.. data:: XML_ERROR_INVALID_TOKEN
   :noindex:

   Raised when an input byte could not properly be assigned to a character; for
   example, a NUL byte (value ``0``) in a UTF-8 input stream.


.. data:: XML_ERROR_JUNK_AFTER_DOC_ELEMENT
   :noindex:

   Something other than whitespace occurred after the document element.


.. data:: XML_ERROR_MISPLACED_XML_PI
   :noindex:

   An XML declaration was found somewhere other than the start of the input data.


.. data:: XML_ERROR_NO_ELEMENTS
   :noindex:

   The document contains no elements (XML requires all documents to contain exactly
   one top-level element)..


.. data:: XML_ERROR_NO_MEMORY
   :noindex:

   Expat was not able to allocate memory internally.


.. data:: XML_ERROR_PARAM_ENTITY_REF
   :noindex:

   A parameter entity reference was found where it was not allowed.


.. data:: XML_ERROR_PARTIAL_CHAR
   :noindex:

   An incomplete character was found in the input.


.. data:: XML_ERROR_RECURSIVE_ENTITY_REF
   :noindex:

   An entity reference contained another reference to the same entity; possibly via
   a different name, and possibly indirectly.


.. data:: XML_ERROR_SYNTAX
   :noindex:

   Some unspecified syntax error was encountered.


.. data:: XML_ERROR_TAG_MISMATCH
   :noindex:

   An end tag did not match the innermost open start tag.


.. data:: XML_ERROR_UNCLOSED_TOKEN
   :noindex:

   Some token (such as a start tag) was not closed before the end of the stream or
   the next token was encountered.


.. data:: XML_ERROR_UNDEFINED_ENTITY
   :noindex:

   A reference was made to an entity which was not defined.


.. data:: XML_ERROR_UNKNOWN_ENCODING
   :noindex:

   The document encoding is not supported by Expat.


.. data:: XML_ERROR_UNCLOSED_CDATA_SECTION
   :noindex:

   A CDATA marked section was not closed.


.. data:: XML_ERROR_EXTERNAL_ENTITY_HANDLING
   :noindex:


.. data:: XML_ERROR_NOT_STANDALONE
   :noindex:

   The parser determined that the document was not "standalone" though it declared
   itself to be in the XML declaration, and the :attr:`NotStandaloneHandler` was
   set and returned ``0``.


.. data:: XML_ERROR_UNEXPECTED_STATE
   :noindex:


.. data:: XML_ERROR_ENTITY_DECLARED_IN_PE
   :noindex:


.. data:: XML_ERROR_FEATURE_REQUIRES_XML_DTD
   :noindex:

   An operation was requested that requires DTD support to be compiled in, but
   Expat was configured without DTD support.  This should never be reported by a
   standard build of the :mod:`xml.parsers.expat` module.


.. data:: XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING
   :noindex:

   A behavioral change was requested after parsing started that can only be changed
   before parsing has started.  This is (currently) only raised by
   :meth:`UseForeignDTD`.


.. data:: XML_ERROR_UNBOUND_PREFIX
   :noindex:

   An undeclared prefix was found when namespace processing was enabled.


.. data:: XML_ERROR_UNDECLARING_PREFIX
   :noindex:

   The document attempted to remove the namespace declaration associated with a
   prefix.


.. data:: XML_ERROR_INCOMPLETE_PE
   :noindex:

   A parameter entity contained incomplete markup.


.. data:: XML_ERROR_XML_DECL
   :noindex:

   The document contained no document element at all.


.. data:: XML_ERROR_TEXT_DECL
   :noindex:

   There was an error parsing a text declaration in an external entity.


.. data:: XML_ERROR_PUBLICID
   :noindex:

   Characters were found in the public id that are not allowed.


.. data:: XML_ERROR_SUSPENDED
   :noindex:

   The requested operation was made on a suspended parser, but isn't allowed.  This
   includes attempts to provide additional input or to stop the parser.


.. data:: XML_ERROR_NOT_SUSPENDED
   :noindex:

   An attempt to resume the parser was made when the parser had not been suspended.


.. data:: XML_ERROR_ABORTED
   :noindex:

   This should not be reported to Python applications.


.. data:: XML_ERROR_FINISHED
   :noindex:

   The requested operation was made on a parser which was finished parsing input,
   but isn't allowed.  This includes attempts to provide additional input or to
   stop the parser.


.. data:: XML_ERROR_SUSPEND_PE
   :noindex:


.. rubric:: Footnotes

.. [1] The encoding string included in XML output should conform to the
   appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
   not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.

PK
%�\b�7q$html/_sources/library/python.rst.txtnu�[���
.. _python:

***********************
Python Runtime Services
***********************

The modules described in this chapter provide a wide range of services related
to the Python interpreter and its interaction with its environment.  Here's an
overview:


.. toctree::

   sys.rst
   sysconfig.rst
   __builtin__.rst
   future_builtins.rst
   __main__.rst
   warnings.rst
   contextlib.rst
   abc.rst
   atexit.rst
   traceback.rst
   __future__.rst
   gc.rst
   inspect.rst
   site.rst
   user.rst
   fpectl.rst
PK
%�\��6�zz#html/_sources/library/queue.rst.txtnu�[���:mod:`Queue` --- A synchronized queue class
===========================================

.. module:: Queue
   :synopsis: A synchronized queue class.

.. note::
   The :mod:`Queue` module has been renamed to :mod:`queue` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

**Source code:** :source:`Lib/Queue.py`

--------------

The :mod:`Queue` module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
exchanged safely between multiple threads.  The :class:`~Queue.Queue` class in this
module implements all the required locking semantics.  It depends on the
availability of thread support in Python; see the :mod:`threading`
module.

The module implements three types of queue, which differ only in the order in
which the entries are retrieved.  In a FIFO queue, the first tasks added are
the first retrieved. In a LIFO queue, the most recently added entry is
the first retrieved (operating like a stack).  With a priority queue,
the entries are kept sorted (using the :mod:`heapq` module) and the
lowest valued entry is retrieved first.

The :mod:`Queue` module defines the following classes and exceptions:

.. class:: Queue(maxsize=0)

   Constructor for a FIFO queue.  *maxsize* is an integer that sets the upperbound
   limit on the number of items that can be placed in the queue.  Insertion will
   block once this size has been reached, until queue items are consumed.  If
   *maxsize* is less than or equal to zero, the queue size is infinite.

.. class:: LifoQueue(maxsize=0)

   Constructor for a LIFO queue.  *maxsize* is an integer that sets the upperbound
   limit on the number of items that can be placed in the queue.  Insertion will
   block once this size has been reached, until queue items are consumed.  If
   *maxsize* is less than or equal to zero, the queue size is infinite.

   .. versionadded:: 2.6

.. class:: PriorityQueue(maxsize=0)

   Constructor for a priority queue.  *maxsize* is an integer that sets the upperbound
   limit on the number of items that can be placed in the queue.  Insertion will
   block once this size has been reached, until queue items are consumed.  If
   *maxsize* is less than or equal to zero, the queue size is infinite.

   The lowest valued entries are retrieved first (the lowest valued entry is the
   one returned by ``sorted(list(entries))[0]``).  A typical pattern for entries
   is a tuple in the form: ``(priority_number, data)``.

   .. versionadded:: 2.6

.. exception:: Empty

   Exception raised when non-blocking :meth:`~Queue.get` (or
   :meth:`~Queue.get_nowait`) is called
   on a :class:`~Queue.Queue` object which is empty.


.. exception:: Full

   Exception raised when non-blocking :meth:`~Queue.put` (or
   :meth:`~Queue.put_nowait`) is called
   on a :class:`~Queue.Queue` object which is full.

.. seealso::

   :class:`collections.deque` is an alternative implementation of unbounded
   queues with fast atomic :func:`append` and :func:`popleft` operations that
   do not require locking.


.. _queueobjects:

Queue Objects
-------------

Queue objects (:class:`~Queue.Queue`, :class:`LifoQueue`, or :class:`PriorityQueue`)
provide the public methods described below.


.. method:: Queue.qsize()

   Return the approximate size of the queue.  Note, qsize() > 0 doesn't
   guarantee that a subsequent get() will not block, nor will qsize() < maxsize
   guarantee that put() will not block.


.. method:: Queue.empty()

   Return ``True`` if the queue is empty, ``False`` otherwise.  If empty()
   returns ``True`` it doesn't guarantee that a subsequent call to put()
   will not block.  Similarly, if empty() returns ``False`` it doesn't
   guarantee that a subsequent call to get() will not block.


.. method:: Queue.full()

   Return ``True`` if the queue is full, ``False`` otherwise.  If full()
   returns ``True`` it doesn't guarantee that a subsequent call to get()
   will not block.  Similarly, if full() returns ``False`` it doesn't
   guarantee that a subsequent call to put() will not block.


.. method:: Queue.put(item[, block[, timeout]])

   Put *item* into the queue. If optional args *block* is true and *timeout* is
   ``None`` (the default), block if necessary until a free slot is available. If
   *timeout* is a positive number, it blocks at most *timeout* seconds and raises
   the :exc:`Full` exception if no free slot was available within that time.
   Otherwise (*block* is false), put an item on the queue if a free slot is
   immediately available, else raise the :exc:`Full` exception (*timeout* is
   ignored in that case).

   .. versionadded:: 2.3
      The *timeout* parameter.


.. method:: Queue.put_nowait(item)

   Equivalent to ``put(item, False)``.


.. method:: Queue.get([block[, timeout]])

   Remove and return an item from the queue. If optional args *block* is true and
   *timeout* is ``None`` (the default), block if necessary until an item is available.
   If *timeout* is a positive number, it blocks at most *timeout* seconds and
   raises the :exc:`Empty` exception if no item was available within that time.
   Otherwise (*block* is false), return an item if one is immediately available,
   else raise the :exc:`Empty` exception (*timeout* is ignored in that case).

   .. versionadded:: 2.3
      The *timeout* parameter.


.. method:: Queue.get_nowait()

   Equivalent to ``get(False)``.

Two methods are offered to support tracking whether enqueued tasks have been
fully processed by daemon consumer threads.


.. method:: Queue.task_done()

   Indicate that a formerly enqueued task is complete.  Used by queue consumer
   threads.  For each :meth:`get` used to fetch a task, a subsequent call to
   :meth:`task_done` tells the queue that the processing on the task is complete.

   If a :meth:`join` is currently blocking, it will resume when all items have been
   processed (meaning that a :meth:`task_done` call was received for every item
   that had been :meth:`put` into the queue).

   Raises a :exc:`ValueError` if called more times than there were items placed in
   the queue.

   .. versionadded:: 2.5


.. method:: Queue.join()

   Blocks until all items in the queue have been gotten and processed.

   The count of unfinished tasks goes up whenever an item is added to the queue.
   The count goes down whenever a consumer thread calls :meth:`task_done` to
   indicate that the item was retrieved and all work on it is complete. When the
   count of unfinished tasks drops to zero, :meth:`join` unblocks.

   .. versionadded:: 2.5

Example of how to wait for enqueued tasks to be completed::

   def worker():
       while True:
           item = q.get()
           do_work(item)
           q.task_done()

   q = Queue()
   for i in range(num_worker_threads):
        t = Thread(target=worker)
        t.daemon = True
        t.start()

   for item in source():
       q.put(item)

   q.join()       # block until all tasks are done

PK
%�\H�Un
n
$html/_sources/library/quopri.rst.txtnu�[���:mod:`quopri` --- Encode and decode MIME quoted-printable data
==============================================================

.. module:: quopri
   :synopsis: Encode and decode files using the MIME quoted-printable encoding.


.. index::
   pair: quoted-printable; encoding
   single: MIME; quoted-printable encoding

**Source code:** :source:`Lib/quopri.py`

--------------

This module performs quoted-printable transport encoding and decoding, as
defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One:
Mechanisms for Specifying and Describing the Format of Internet Message Bodies".
The quoted-printable encoding is designed for data where there are relatively
few nonprintable characters; the base64 encoding scheme available via the
:mod:`base64` module is more compact if there are many such characters, as when
sending a graphics file.

.. function:: decode(input, output[,header])

   Decode the contents of the *input* file and write the resulting decoded binary
   data to the *output* file. *input* and *output* must either be file objects or
   objects that mimic the file object interface. *input* will be read until
   ``input.readline()`` returns an empty string. If the optional argument *header*
   is present and true, underscore will be decoded as space. This is used to decode
   "Q"-encoded headers as described in :rfc:`1522`: "MIME (Multipurpose Internet
   Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text".


.. function:: encode(input, output, quotetabs)

   Encode the contents of the *input* file and write the resulting quoted-printable
   data to the *output* file. *input* and *output* must either be file objects or
   objects that mimic the file object interface. *input* will be read until
   ``input.readline()`` returns an empty string. *quotetabs* is a flag which
   controls whether to encode embedded spaces and tabs; when true it encodes such
   embedded whitespace, and when false it leaves them unencoded.  Note that spaces
   and tabs appearing at the end of lines are always encoded, as per :rfc:`1521`.


.. function:: decodestring(s[,header])

   Like :func:`decode`, except that it accepts a source string and returns the
   corresponding decoded string.


.. function:: encodestring(s[, quotetabs])

   Like :func:`encode`, except that it accepts a source string and returns the
   corresponding encoded string.  *quotetabs* is optional (defaulting to 0), and is
   passed straight through to :func:`encode`.


.. seealso::

   Module :mod:`mimify`
      General utilities for processing of MIME messages.

   Module :mod:`base64`
      Encode and decode MIME base64 data

PK
%�\�V�-44$html/_sources/library/random.rst.txtnu�[���:mod:`random` --- Generate pseudo-random numbers
================================================

.. module:: random
   :synopsis: Generate pseudo-random numbers with various common distributions.

**Source code:** :source:`Lib/random.py`

--------------

This module implements pseudo-random number generators for various
distributions.

For integers, uniform selection from a range. For sequences, uniform selection
of a random element, a function to generate a random permutation of a list
in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian),
lognormal, negative exponential, gamma, and beta distributions. For generating
distributions of angles, the von Mises distribution is available.

Almost all module functions depend on the basic function :func:`.random`, which
generates a random float uniformly in the semi-open range [0.0, 1.0).  Python
uses the Mersenne Twister as the core generator.  It produces 53-bit precision
floats and has a period of 2\*\*19937-1.  The underlying implementation in C is
both fast and threadsafe.  The Mersenne Twister is one of the most extensively
tested random number generators in existence.  However, being completely
deterministic, it is not suitable for all purposes, and is completely unsuitable
for cryptographic purposes.

The functions supplied by this module are actually bound methods of a hidden
instance of the :class:`random.Random` class.  You can instantiate your own
instances of :class:`Random` to get generators that don't share state.  This is
especially useful for multi-threaded programs, creating a different instance of
:class:`Random` for each thread, and using the :meth:`jumpahead` method to make
it likely that the generated sequences seen by each thread don't overlap.

Class :class:`Random` can also be subclassed if you want to use a different
basic generator of your own devising: in that case, override the :meth:`~Random.random`,
:meth:`~Random.seed`, :meth:`~Random.getstate`, :meth:`~Random.setstate` and
:meth:`~Random.jumpahead` methods.  Optionally, a new generator can supply a
:meth:`~Random.getrandbits` method --- this
allows :meth:`randrange` to produce selections over an arbitrarily large range.

.. versionadded:: 2.4
   the :meth:`getrandbits` method.

As an example of subclassing, the :mod:`random` module provides the
:class:`WichmannHill` class that implements an alternative generator in pure
Python.  The class provides a backward compatible way to reproduce results from
earlier versions of Python, which used the Wichmann-Hill algorithm as the core
generator.  Note that this Wichmann-Hill generator can no longer be recommended:
its period is too short by contemporary standards, and the sequence generated is
known to fail some stringent randomness tests.  See the references below for a
recent variant that repairs these flaws.

.. versionchanged:: 2.3
   MersenneTwister replaced Wichmann-Hill as the default generator.

The :mod:`random` module also provides the :class:`SystemRandom` class which
uses the system function :func:`os.urandom` to generate random numbers
from sources provided by the operating system.

.. warning::

   The pseudo-random generators of this module should not be used for
   security purposes.  Use :func:`os.urandom` or :class:`SystemRandom` if
   you require a cryptographically secure pseudo-random number generator.


Bookkeeping functions:


.. function:: seed(a=None)

   Initialize internal state of the random number generator.

   ``None`` or no argument seeds from current time or from an operating
   system specific randomness source if available (see the :func:`os.urandom`
   function for details on availability).

   If *a* is not ``None`` or an :class:`int` or a :class:`long`, then
   ``hash(a)`` is used instead.  Note that the hash values for some types
   are nondeterministic when :envvar:`PYTHONHASHSEED` is enabled.

   .. versionchanged:: 2.4
      formerly, operating system resources were not used.

.. function:: getstate()

   Return an object capturing the current internal state of the generator.  This
   object can be passed to :func:`setstate` to restore the state.

   .. versionadded:: 2.1

   .. versionchanged:: 2.6
      State values produced in Python 2.6 cannot be loaded into earlier versions.


.. function:: setstate(state)

   *state* should have been obtained from a previous call to :func:`getstate`, and
   :func:`setstate` restores the internal state of the generator to what it was at
   the time :func:`getstate` was called.

   .. versionadded:: 2.1


.. function:: jumpahead(n)

   Change the internal state to one different from and likely far away from the
   current state.  *n* is a non-negative integer which is used to scramble the
   current state vector.  This is most useful in multi-threaded programs, in
   conjunction with multiple instances of the :class:`Random` class:
   :meth:`setstate` or :meth:`seed` can be used to force all instances into the
   same internal state, and then :meth:`jumpahead` can be used to force the
   instances' states far apart.

   .. versionadded:: 2.1

   .. versionchanged:: 2.3
      Instead of jumping to a specific state, *n* steps ahead, ``jumpahead(n)``
      jumps to another state likely to be separated by many steps.


.. function:: getrandbits(k)

   Returns a python :class:`long` int with *k* random bits. This method is supplied
   with the MersenneTwister generator and some other generators may also provide it
   as an optional part of the API. When available, :meth:`getrandbits` enables
   :meth:`randrange` to handle arbitrarily large ranges.

   .. versionadded:: 2.4

Functions for integers:


.. function:: randrange(stop)
              randrange(start, stop[, step])

   Return a randomly selected element from ``range(start, stop, step)``.  This is
   equivalent to ``choice(range(start, stop, step))``, but doesn't actually build a
   range object.

   .. versionadded:: 1.5.2


.. function:: randint(a, b)

   Return a random integer *N* such that ``a <= N <= b``.

Functions for sequences:


.. function:: choice(seq)

   Return a random element from the non-empty sequence *seq*. If *seq* is empty,
   raises :exc:`IndexError`.


.. function:: shuffle(x[, random])

   Shuffle the sequence *x* in place. The optional argument *random* is a
   0-argument function returning a random float in [0.0, 1.0); by default, this is
   the function :func:`.random`.

   Note that for even rather small ``len(x)``, the total number of permutations of
   *x* is larger than the period of most random number generators; this implies
   that most permutations of a long sequence can never be generated.


.. function:: sample(population, k)

   Return a *k* length list of unique elements chosen from the population sequence.
   Used for random sampling without replacement.

   .. versionadded:: 2.3

   Returns a new list containing elements from the population while leaving the
   original population unchanged.  The resulting list is in selection order so that
   all sub-slices will also be valid random samples.  This allows raffle winners
   (the sample) to be partitioned into grand prize and second place winners (the
   subslices).

   Members of the population need not be :term:`hashable` or unique.  If the population
   contains repeats, then each occurrence is a possible selection in the sample.

   To choose a sample from a range of integers, use an :func:`xrange` object as an
   argument.  This is especially fast and space efficient for sampling from a large
   population:  ``sample(xrange(10000000), 60)``.

The following functions generate specific real-valued distributions. Function
parameters are named after the corresponding variables in the distribution's
equation, as used in common mathematical practice; most of these equations can
be found in any statistics text.


.. function:: random()

   Return the next random floating point number in the range [0.0, 1.0).


.. function:: uniform(a, b)

   Return a random floating point number *N* such that ``a <= N <= b`` for
   ``a <= b`` and ``b <= N <= a`` for ``b < a``.

   The end-point value ``b`` may or may not be included in the range
   depending on floating-point rounding in the equation ``a + (b-a) * random()``.


.. function:: triangular(low, high, mode)

   Return a random floating point number *N* such that ``low <= N <= high`` and
   with the specified *mode* between those bounds.  The *low* and *high* bounds
   default to zero and one.  The *mode* argument defaults to the midpoint
   between the bounds, giving a symmetric distribution.

   .. versionadded:: 2.6


.. function:: betavariate(alpha, beta)

   Beta distribution.  Conditions on the parameters are ``alpha > 0`` and
   ``beta > 0``. Returned values range between 0 and 1.


.. function:: expovariate(lambd)

   Exponential distribution.  *lambd* is 1.0 divided by the desired
   mean.  It should be nonzero.  (The parameter would be called
   "lambda", but that is a reserved word in Python.)  Returned values
   range from 0 to positive infinity if *lambd* is positive, and from
   negative infinity to 0 if *lambd* is negative.


.. function:: gammavariate(alpha, beta)

   Gamma distribution.  (*Not* the gamma function!)  Conditions on the
   parameters are ``alpha > 0`` and ``beta > 0``.

   The probability distribution function is::

                 x ** (alpha - 1) * math.exp(-x / beta)
       pdf(x) =  --------------------------------------
                   math.gamma(alpha) * beta ** alpha


.. function:: gauss(mu, sigma)

   Gaussian distribution.  *mu* is the mean, and *sigma* is the standard
   deviation.  This is slightly faster than the :func:`normalvariate` function
   defined below.


.. function:: lognormvariate(mu, sigma)

   Log normal distribution.  If you take the natural logarithm of this
   distribution, you'll get a normal distribution with mean *mu* and standard
   deviation *sigma*.  *mu* can have any value, and *sigma* must be greater than
   zero.


.. function:: normalvariate(mu, sigma)

   Normal distribution.  *mu* is the mean, and *sigma* is the standard deviation.


.. function:: vonmisesvariate(mu, kappa)

   *mu* is the mean angle, expressed in radians between 0 and 2\*\ *pi*, and *kappa*
   is the concentration parameter, which must be greater than or equal to zero.  If
   *kappa* is equal to zero, this distribution reduces to a uniform random angle
   over the range 0 to 2\*\ *pi*.


.. function:: paretovariate(alpha)

   Pareto distribution.  *alpha* is the shape parameter.


.. function:: weibullvariate(alpha, beta)

   Weibull distribution.  *alpha* is the scale parameter and *beta* is the shape
   parameter.


Alternative Generators:

.. class:: WichmannHill([seed])

   Class that implements the Wichmann-Hill algorithm as the core generator. Has all
   of the same methods as :class:`Random` plus the :meth:`whseed` method described
   below.  Because this class is implemented in pure Python, it is not threadsafe
   and may require locks between calls.  The period of the generator is
   6,953,607,871,644 which is small enough to require care that two independent
   random sequences do not overlap.


.. function:: whseed([x])

   This is obsolete, supplied for bit-level compatibility with versions of Python
   prior to 2.1. See :func:`seed` for details.  :func:`whseed` does not guarantee
   that distinct integer arguments yield distinct internal states, and can yield no
   more than about 2\*\*24 distinct internal states in all.


.. class:: SystemRandom([seed])

   Class that uses the :func:`os.urandom` function for generating random numbers
   from sources provided by the operating system. Not available on all systems.
   Does not rely on software state and sequences are not reproducible. Accordingly,
   the :meth:`seed` and :meth:`jumpahead` methods have no effect and are ignored.
   The :meth:`getstate` and :meth:`setstate` methods raise
   :exc:`NotImplementedError` if called.

   .. versionadded:: 2.4

Examples of basic usage::

   >>> random.random()        # Random float x, 0.0 <= x < 1.0
   0.37444887175646646
   >>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
   1.1800146073117523
   >>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
   7
   >>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
   26
   >>> random.choice('abcdefghij')  # Choose a random element
   'c'

   >>> items = [1, 2, 3, 4, 5, 6, 7]
   >>> random.shuffle(items)
   >>> items
   [7, 3, 2, 5, 6, 4, 1]

   >>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
   [4, 1, 5]



.. seealso::

   M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
   equidistributed uniform pseudorandom number generator", ACM Transactions on
   Modeling and Computer Simulation Vol. 8, No. 1, January pp.3--30 1998.

   Wichmann, B. A. & Hill, I. D., "Algorithm AS 183: An efficient and portable
   pseudo-random number generator", Applied Statistics 31 (1982) 188-190.

   `Complementary-Multiply-with-Carry recipe
   <http://code.activestate.com/recipes/576707/>`_ for a compatible alternative
   random number generator with a long period and comparatively simple update
   operations.
PK
%�\�f!�>�>� html/_sources/library/re.rst.txtnu�[���
:mod:`re` --- Regular expression operations
===========================================

.. module:: re
   :synopsis: Regular expression operations.
.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
.. sectionauthor:: Andrew M. Kuchling <amk@amk.ca>


This module provides regular expression matching operations similar to
those found in Perl. Both patterns and strings to be searched can be
Unicode strings as well as 8-bit strings.

Regular expressions use the backslash character (``'\'``) to indicate
special forms or to allow special characters to be used without invoking
their special meaning.  This collides with Python's usage of the same
character for the same purpose in string literals; for example, to match
a literal backslash, one might have to write ``'\\\\'`` as the pattern
string, because the regular expression must be ``\\``, and each
backslash must be expressed as ``\\`` inside a regular Python string
literal.

The solution is to use Python's raw string notation for regular expression
patterns; backslashes are not handled in any special way in a string literal
prefixed with ``'r'``.  So ``r"\n"`` is a two-character string containing
``'\'`` and ``'n'``, while ``"\n"`` is a one-character string containing a
newline.  Usually patterns will be expressed in Python code using this raw
string notation.

It is important to note that most regular expression operations are available as
module-level functions and :class:`RegexObject` methods.  The functions are
shortcuts that don't require you to compile a regex object first, but miss some
fine-tuning parameters.

.. seealso::

   The third-party `regex <https://pypi.org/project/regex/>`_ module,
   which has an API compatible with the standard library :mod:`re` module,
   but offers additional functionality and a more thorough Unicode support.


.. _re-syntax:

Regular Expression Syntax
-------------------------

A regular expression (or RE) specifies a set of strings that matches it; the
functions in this module let you check if a particular string matches a given
regular expression (or if a given regular expression matches a particular
string, which comes down to the same thing).

Regular expressions can be concatenated to form new regular expressions; if *A*
and *B* are both regular expressions, then *AB* is also a regular expression.
In general, if a string *p* matches *A* and another string *q* matches *B*, the
string *pq* will match AB.  This holds unless *A* or *B* contain low precedence
operations; boundary conditions between *A* and *B*; or have numbered group
references.  Thus, complex expressions can easily be constructed from simpler
primitive expressions like the ones described here.  For details of the theory
and implementation of regular expressions, consult the Friedl book referenced
above, or almost any textbook about compiler construction.

A brief explanation of the format of regular expressions follows.  For further
information and a gentler presentation, consult the :ref:`regex-howto`.

Regular expressions can contain both special and ordinary characters. Most
ordinary characters, like ``'A'``, ``'a'``, or ``'0'``, are the simplest regular
expressions; they simply match themselves.  You can concatenate ordinary
characters, so ``last`` matches the string ``'last'``.  (In the rest of this
section, we'll write RE's in ``this special style``, usually without quotes, and
strings to be matched ``'in single quotes'``.)

Some characters, like ``'|'`` or ``'('``, are special. Special
characters either stand for classes of ordinary characters, or affect
how the regular expressions around them are interpreted. Regular
expression pattern strings may not contain null bytes, but can specify
the null byte using the ``\number`` notation, e.g., ``'\x00'``.

Repetition qualifiers (``*``, ``+``, ``?``, ``{m,n}``, etc) cannot be
directly nested. This avoids ambiguity with the non-greedy modifier suffix
``?``, and with other modifiers in other implementations. To apply a second
repetition to an inner repetition, parentheses may be used. For example,
the expression ``(?:a{6})*`` matches any multiple of six ``'a'`` characters.


The special characters are:

``'.'``
   (Dot.)  In the default mode, this matches any character except a newline.  If
   the :const:`DOTALL` flag has been specified, this matches any character
   including a newline.

``'^'``
   (Caret.)  Matches the start of the string, and in :const:`MULTILINE` mode also
   matches immediately after each newline.

``'$'``
   Matches the end of the string or just before the newline at the end of the
   string, and in :const:`MULTILINE` mode also matches before a newline.  ``foo``
   matches both 'foo' and 'foobar', while the regular expression ``foo$`` matches
   only 'foo'.  More interestingly, searching for ``foo.$`` in ``'foo1\nfoo2\n'``
   matches 'foo2' normally, but 'foo1' in :const:`MULTILINE` mode; searching for
   a single ``$`` in ``'foo\n'`` will find two (empty) matches: one just before
   the newline, and one at the end of the string.

``'*'``
   Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
   many repetitions as are possible.  ``ab*`` will match 'a', 'ab', or 'a' followed
   by any number of 'b's.

``'+'``
   Causes the resulting RE to match 1 or more repetitions of the preceding RE.
   ``ab+`` will match 'a' followed by any non-zero number of 'b's; it will not
   match just 'a'.

``'?'``
   Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
   ``ab?`` will match either 'a' or 'ab'.

``*?``, ``+?``, ``??``
   The ``'*'``, ``'+'``, and ``'?'`` qualifiers are all :dfn:`greedy`; they match
   as much text as possible.  Sometimes this behaviour isn't desired; if the RE
   ``<.*>`` is matched against ``<a> b <c>``, it will match the entire
   string, and not just ``<a>``.  Adding ``?`` after the qualifier makes it
   perform the match in :dfn:`non-greedy` or :dfn:`minimal` fashion; as *few*
   characters as possible will be matched.  Using the RE ``<.*?>`` will match
   only ``<a>``.

``{m}``
   Specifies that exactly *m* copies of the previous RE should be matched; fewer
   matches cause the entire RE not to match.  For example, ``a{6}`` will match
   exactly six ``'a'`` characters, but not five.

``{m,n}``
   Causes the resulting RE to match from *m* to *n* repetitions of the preceding
   RE, attempting to match as many repetitions as possible.  For example,
   ``a{3,5}`` will match from 3 to 5 ``'a'`` characters.  Omitting *m* specifies a
   lower bound of zero,  and omitting *n* specifies an infinite upper bound.  As an
   example, ``a{4,}b`` will match ``aaaab`` or a thousand ``'a'`` characters
   followed by a ``b``, but not ``aaab``. The comma may not be omitted or the
   modifier would be confused with the previously described form.

``{m,n}?``
   Causes the resulting RE to match from *m* to *n* repetitions of the preceding
   RE, attempting to match as *few* repetitions as possible.  This is the
   non-greedy version of the previous qualifier.  For example, on the
   6-character string ``'aaaaaa'``, ``a{3,5}`` will match 5 ``'a'`` characters,
   while ``a{3,5}?`` will only match 3 characters.

``'\'``
   Either escapes special characters (permitting you to match characters like
   ``'*'``, ``'?'``, and so forth), or signals a special sequence; special
   sequences are discussed below.

   If you're not using a raw string to express the pattern, remember that Python
   also uses the backslash as an escape sequence in string literals; if the escape
   sequence isn't recognized by Python's parser, the backslash and subsequent
   character are included in the resulting string.  However, if Python would
   recognize the resulting sequence, the backslash should be repeated twice.  This
   is complicated and hard to understand, so it's highly recommended that you use
   raw strings for all but the simplest expressions.

``[]``
   Used to indicate a set of characters.  In a set:

   * Characters can be listed individually, e.g. ``[amk]`` will match ``'a'``,
     ``'m'``, or ``'k'``.

   * Ranges of characters can be indicated by giving two characters and separating
     them by a ``'-'``, for example ``[a-z]`` will match any lowercase ASCII letter,
     ``[0-5][0-9]`` will match all the two-digits numbers from ``00`` to ``59``, and
     ``[0-9A-Fa-f]`` will match any hexadecimal digit.  If ``-`` is escaped (e.g.
     ``[a\-z]``) or if it's placed as the first or last character (e.g. ``[a-]``),
     it will match a literal ``'-'``.

   * Special characters lose their special meaning inside sets.  For example,
     ``[(+*)]`` will match any of the literal characters ``'('``, ``'+'``,
     ``'*'``, or ``')'``.

   * Character classes such as ``\w`` or ``\S`` (defined below) are also accepted
     inside a set, although the characters they match depends on whether
     :const:`LOCALE` or  :const:`UNICODE` mode is in force.

   * Characters that are not within a range can be matched by :dfn:`complementing`
     the set.  If the first character of the set is ``'^'``, all the characters
     that are *not* in the set will be matched.  For example, ``[^5]`` will match
     any character except ``'5'``, and ``[^^]`` will match any character except
     ``'^'``.  ``^`` has no special meaning if it's not the first character in
     the set.

   * To match a literal ``']'`` inside a set, precede it with a backslash, or
     place it at the beginning of the set.  For example, both ``[()[\]{}]`` and
     ``[]()[{}]`` will both match a parenthesis.

``'|'``
   ``A|B``, where A and B can be arbitrary REs, creates a regular expression that
   will match either A or B.  An arbitrary number of REs can be separated by the
   ``'|'`` in this way.  This can be used inside groups (see below) as well.  As
   the target string is scanned, REs separated by ``'|'`` are tried from left to
   right. When one pattern completely matches, that branch is accepted. This means
   that once ``A`` matches, ``B`` will not be tested further, even if it would
   produce a longer overall match.  In other words, the ``'|'`` operator is never
   greedy.  To match a literal ``'|'``, use ``\|``, or enclose it inside a
   character class, as in ``[|]``.

``(...)``
   Matches whatever regular expression is inside the parentheses, and indicates the
   start and end of a group; the contents of a group can be retrieved after a match
   has been performed, and can be matched later in the string with the ``\number``
   special sequence, described below.  To match the literals ``'('`` or ``')'``,
   use ``\(`` or ``\)``, or enclose them inside a character class: ``[(] [)]``.

``(?...)``
   This is an extension notation (a ``'?'`` following a ``'('`` is not meaningful
   otherwise).  The first character after the ``'?'`` determines what the meaning
   and further syntax of the construct is. Extensions usually do not create a new
   group; ``(?P<name>...)`` is the only exception to this rule. Following are the
   currently supported extensions.

``(?iLmsux)``
   (One or more letters from the set ``'i'``, ``'L'``, ``'m'``, ``'s'``,
   ``'u'``, ``'x'``.)  The group matches the empty string; the letters
   set the corresponding flags: :const:`re.I` (ignore case),
   :const:`re.L` (locale dependent), :const:`re.M` (multi-line),
   :const:`re.S` (dot matches all), :const:`re.U` (Unicode dependent),
   and :const:`re.X` (verbose), for the entire regular expression. (The
   flags are described in :ref:`contents-of-module-re`.) This
   is useful if you wish to include the flags as part of the regular
   expression, instead of passing a *flag* argument to the
   :func:`re.compile` function.

   Note that the ``(?x)`` flag changes how the expression is parsed. It should be
   used first in the expression string, or after one or more whitespace characters.
   If there are non-whitespace characters before the flag, the results are
   undefined.

``(?:...)``
   A non-capturing version of regular parentheses.  Matches whatever regular
   expression is inside the parentheses, but the substring matched by the group
   *cannot* be retrieved after performing a match or referenced later in the
   pattern.

``(?P<name>...)``
   Similar to regular parentheses, but the substring matched by the group is
   accessible via the symbolic group name *name*.  Group names must be valid
   Python identifiers, and each group name must be defined only once within a
   regular expression.  A symbolic group is also a numbered group, just as if
   the group were not named.

   Named groups can be referenced in three contexts.  If the pattern is
   ``(?P<quote>['"]).*?(?P=quote)`` (i.e. matching a string quoted with either
   single or double quotes):

   +---------------------------------------+----------------------------------+
   | Context of reference to group "quote" | Ways to reference it             |
   +=======================================+==================================+
   | in the same pattern itself            | * ``(?P=quote)`` (as shown)      |
   |                                       | * ``\1``                         |
   +---------------------------------------+----------------------------------+
   | when processing match object ``m``    | * ``m.group('quote')``           |
   |                                       | * ``m.end('quote')`` (etc.)      |
   +---------------------------------------+----------------------------------+
   | in a string passed to the ``repl``    | * ``\g<quote>``                  |
   | argument of ``re.sub()``              | * ``\g<1>``                      |
   |                                       | * ``\1``                         |
   +---------------------------------------+----------------------------------+

``(?P=name)``
   A backreference to a named group; it matches whatever text was matched by the
   earlier group named *name*.

``(?#...)``
   A comment; the contents of the parentheses are simply ignored.

``(?=...)``
   Matches if ``...`` matches next, but doesn't consume any of the string.  This is
   called a lookahead assertion.  For example, ``Isaac (?=Asimov)`` will match
   ``'Isaac '`` only if it's followed by ``'Asimov'``.

``(?!...)``
   Matches if ``...`` doesn't match next.  This is a negative lookahead assertion.
   For example, ``Isaac (?!Asimov)`` will match ``'Isaac '`` only if it's *not*
   followed by ``'Asimov'``.

``(?<=...)``
   Matches if the current position in the string is preceded by a match for ``...``
   that ends at the current position.  This is called a :dfn:`positive lookbehind
   assertion`. ``(?<=abc)def`` will find a match in ``abcdef``, since the
   lookbehind will back up 3 characters and check if the contained pattern matches.
   The contained pattern must only match strings of some fixed length, meaning that
   ``abc`` or ``a|b`` are allowed, but ``a*`` and ``a{3,4}`` are not.  Group
   references are not supported even if they match strings of some fixed length.
   Note that
   patterns which start with positive lookbehind assertions will not match at the
   beginning of the string being searched; you will most likely want to use the
   :func:`search` function rather than the :func:`match` function:

      >>> import re
      >>> m = re.search('(?<=abc)def', 'abcdef')
      >>> m.group(0)
      'def'

   This example looks for a word following a hyphen:

      >>> m = re.search('(?<=-)\w+', 'spam-egg')
      >>> m.group(0)
      'egg'

``(?<!...)``
   Matches if the current position in the string is not preceded by a match for
   ``...``.  This is called a :dfn:`negative lookbehind assertion`.  Similar to
   positive lookbehind assertions, the contained pattern must only match strings of
   some fixed length and shouldn't contain group references.
   Patterns which start with negative lookbehind assertions may
   match at the beginning of the string being searched.

``(?(id/name)yes-pattern|no-pattern)``
   Will try to match with ``yes-pattern`` if the group with given *id* or *name*
   exists, and with ``no-pattern`` if it doesn't. ``no-pattern`` is optional and
   can be omitted. For example,  ``(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)`` is a poor email
   matching pattern, which will match with ``'<user@host.com>'`` as well as
   ``'user@host.com'``, but not with ``'<user@host.com'``.

   .. versionadded:: 2.4

The special sequences consist of ``'\'`` and a character from the list below.
If the ordinary character is not on the list, then the resulting RE will match
the second character.  For example, ``\$`` matches the character ``'$'``.

``\number``
   Matches the contents of the group of the same number.  Groups are numbered
   starting from 1.  For example, ``(.+) \1`` matches ``'the the'`` or ``'55 55'``,
   but not ``'thethe'`` (note the space after the group).  This special sequence
   can only be used to match one of the first 99 groups.  If the first digit of
   *number* is 0, or *number* is 3 octal digits long, it will not be interpreted as
   a group match, but as the character with octal value *number*. Inside the
   ``'['`` and ``']'`` of a character class, all numeric escapes are treated as
   characters.

``\A``
   Matches only at the start of the string.

``\b``
   Matches the empty string, but only at the beginning or end of a word.  A word is
   defined as a sequence of alphanumeric or underscore characters, so the end of a
   word is indicated by whitespace or a non-alphanumeric, non-underscore character.
   Note that formally, ``\b`` is defined as the boundary between a ``\w`` and
   a ``\W`` character (or vice versa), or between ``\w`` and the beginning/end
   of the string, so the precise set of characters deemed to be alphanumeric
   depends on the values of the ``UNICODE`` and ``LOCALE`` flags.
   For example, ``r'\bfoo\b'`` matches ``'foo'``, ``'foo.'``, ``'(foo)'``,
   ``'bar foo baz'`` but not ``'foobar'`` or ``'foo3'``.
   Inside a character range, ``\b`` represents the backspace character, for
   compatibility with Python's string literals.

``\B``
   Matches the empty string, but only when it is *not* at the beginning or end of a
   word.  This means that ``r'py\B'`` matches ``'python'``, ``'py3'``, ``'py2'``,
   but not ``'py'``, ``'py.'``, or ``'py!'``.
   ``\B`` is just the opposite of ``\b``, so is also subject to the settings
   of ``LOCALE`` and ``UNICODE``.

``\d``
   When the :const:`UNICODE` flag is not specified, matches any decimal digit; this
   is equivalent to the set ``[0-9]``.  With :const:`UNICODE`, it will match
   whatever is classified as a decimal digit in the Unicode character properties
   database.

``\D``
   When the :const:`UNICODE` flag is not specified, matches any non-digit
   character; this is equivalent to the set  ``[^0-9]``.  With :const:`UNICODE`, it
   will match  anything other than character marked as digits in the Unicode
   character  properties database.

``\s``
   When the :const:`UNICODE` flag is not specified, it matches any whitespace
   character, this is equivalent to the set ``[ \t\n\r\f\v]``. The
   :const:`LOCALE` flag has no extra effect on matching of the space.
   If :const:`UNICODE` is set, this will match the characters ``[ \t\n\r\f\v]``
   plus whatever is classified as space in the Unicode character properties
   database.

``\S``
   When the :const:`UNICODE` flag is not specified, matches any non-whitespace
   character; this is equivalent to the set ``[^ \t\n\r\f\v]`` The
   :const:`LOCALE` flag has no extra effect on non-whitespace match.  If
   :const:`UNICODE` is set, then any character not marked as space in the
   Unicode character properties database is matched.


``\w``
   When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
   any alphanumeric character and the underscore; this is equivalent to the set
   ``[a-zA-Z0-9_]``.  With :const:`LOCALE`, it will match the set ``[0-9_]`` plus
   whatever characters are defined as alphanumeric for the current locale.  If
   :const:`UNICODE` is set, this will match the characters ``[0-9_]`` plus whatever
   is classified as alphanumeric in the Unicode character properties database.

``\W``
   When the :const:`LOCALE` and :const:`UNICODE` flags are not specified, matches
   any non-alphanumeric character; this is equivalent to the set ``[^a-zA-Z0-9_]``.
   With :const:`LOCALE`, it will match any character not in the set ``[0-9_]``, and
   not defined as alphanumeric for the current locale. If :const:`UNICODE` is set,
   this will match anything other than ``[0-9_]`` plus characters classified as
   not alphanumeric in the Unicode character properties database.

``\Z``
   Matches only at the end of the string.

If both :const:`LOCALE` and :const:`UNICODE` flags are included for a
particular sequence, then :const:`LOCALE` flag takes effect first followed by
the :const:`UNICODE`.

Most of the standard escapes supported by Python string literals are also
accepted by the regular expression parser::

   \a      \b      \f      \n
   \r      \t      \v      \x
   \\

(Note that ``\b`` is used to represent word boundaries, and means "backspace"
only inside character classes.)

Octal escapes are included in a limited form: If the first digit is a 0, or if
there are three octal digits, it is considered an octal escape. Otherwise, it is
a group reference.  As for string literals, octal escapes are always at most
three digits in length.

.. seealso::

   Mastering Regular Expressions
      Book on regular expressions by Jeffrey Friedl, published by O'Reilly.  The
      second edition of the book no longer covers Python at all, but the first
      edition covered writing good regular expression patterns in great detail.



.. _contents-of-module-re:

Module Contents
---------------

The module defines several functions, constants, and an exception. Some of the
functions are simplified versions of the full featured methods for compiled
regular expressions.  Most non-trivial applications always use the compiled
form.


.. function:: compile(pattern, flags=0)

   Compile a regular expression pattern into a regular expression object, which
   can be used for matching using its :func:`~RegexObject.match` and
   :func:`~RegexObject.search` methods, described below.

   The expression's behaviour can be modified by specifying a *flags* value.
   Values can be any of the following variables, combined using bitwise OR (the
   ``|`` operator).

   The sequence ::

      prog = re.compile(pattern)
      result = prog.match(string)

   is equivalent to ::

      result = re.match(pattern, string)

   but using :func:`re.compile` and saving the resulting regular expression
   object for reuse is more efficient when the expression will be used several
   times in a single program.

   .. note::

      The compiled versions of the most recent patterns passed to
      :func:`re.match`, :func:`re.search` or :func:`re.compile` are cached, so
      programs that use only a few regular expressions at a time needn't worry
      about compiling regular expressions.


.. data:: DEBUG

   Display debug information about compiled expression.


.. data:: I
          IGNORECASE

   Perform case-insensitive matching; expressions like ``[A-Z]`` will match
   lowercase letters, too.  This is not affected by the current locale.  To
   get this effect on non-ASCII Unicode characters such as ``ü`` and ``Ü``,
   add the :const:`UNICODE` flag.


.. data:: L
          LOCALE

   Make ``\w``, ``\W``, ``\b``, ``\B``, ``\s`` and ``\S`` dependent on the
   current locale.


.. data:: M
          MULTILINE

   When specified, the pattern character ``'^'`` matches at the beginning of the
   string and at the beginning of each line (immediately following each newline);
   and the pattern character ``'$'`` matches at the end of the string and at the
   end of each line (immediately preceding each newline).  By default, ``'^'``
   matches only at the beginning of the string, and ``'$'`` only at the end of the
   string and immediately before the newline (if any) at the end of the string.


.. data:: S
          DOTALL

   Make the ``'.'`` special character match any character at all, including a
   newline; without this flag, ``'.'`` will match anything *except* a newline.


.. data:: U
          UNICODE

   Make the ``\w``, ``\W``, ``\b``, ``\B``, ``\d``, ``\D``, ``\s`` and ``\S``
   sequences dependent on the Unicode character properties database. Also
   enables non-ASCII matching for :const:`IGNORECASE`.

   .. versionadded:: 2.0


.. data:: X
          VERBOSE

   This flag allows you to write regular expressions that look nicer and are
   more readable by allowing you to visually separate logical sections of the
   pattern and add comments. Whitespace within the pattern is ignored, except
   when in a character class, or when preceded by an unescaped backslash,
   or within tokens like ``*?``, ``(?:`` or ``(?P<...>``.
   When a line contains a ``#`` that is not in a character class and is not
   preceded by an unescaped backslash, all characters from the leftmost such
   ``#`` through the end of the line are ignored.

   This means that the two following regular expression objects that match a
   decimal number are functionally equal::

      a = re.compile(r"""\d +  # the integral part
                         \.    # the decimal point
                         \d *  # some fractional digits""", re.X)
      b = re.compile(r"\d+\.\d*")


.. function:: search(pattern, string, flags=0)

   Scan through *string* looking for the first location where the regular expression
   *pattern* produces a match, and return a corresponding :class:`MatchObject`
   instance. Return ``None`` if no position in the string matches the pattern; note
   that this is different from finding a zero-length match at some point in the
   string.


.. function:: match(pattern, string, flags=0)

   If zero or more characters at the beginning of *string* match the regular
   expression *pattern*, return a corresponding :class:`MatchObject` instance.
   Return ``None`` if the string does not match the pattern; note that this is
   different from a zero-length match.

   Note that even in :const:`MULTILINE` mode, :func:`re.match` will only match
   at the beginning of the string and not at the beginning of each line.

   If you want to locate a match anywhere in *string*, use :func:`search`
   instead (see also :ref:`search-vs-match`).


.. function:: split(pattern, string, maxsplit=0, flags=0)

   Split *string* by the occurrences of *pattern*.  If capturing parentheses are
   used in *pattern*, then the text of all groups in the pattern are also returned
   as part of the resulting list. If *maxsplit* is nonzero, at most *maxsplit*
   splits occur, and the remainder of the string is returned as the final element
   of the list.  (Incompatibility note: in the original Python 1.5 release,
   *maxsplit* was ignored.  This has been fixed in later releases.)

      >>> re.split('\W+', 'Words, words, words.')
      ['Words', 'words', 'words', '']
      >>> re.split('(\W+)', 'Words, words, words.')
      ['Words', ', ', 'words', ', ', 'words', '.', '']
      >>> re.split('\W+', 'Words, words, words.', 1)
      ['Words', 'words, words.']
      >>> re.split('[a-f]+', '0a3B9', flags=re.IGNORECASE)
      ['0', '3', '9']

   If there are capturing groups in the separator and it matches at the start of
   the string, the result will start with an empty string.  The same holds for
   the end of the string:

      >>> re.split('(\W+)', '...words, words...')
      ['', '...', 'words', ', ', 'words', '...', '']

   That way, separator components are always found at the same relative
   indices within the result list (e.g., if there's one capturing group
   in the separator, the 0th, the 2nd and so forth).

   Note that *split* will never split a string on an empty pattern match.
   For example:

      >>> re.split('x*', 'foo')
      ['foo']
      >>> re.split("(?m)^$", "foo\n\nbar\n")
      ['foo\n\nbar\n']

   .. versionchanged:: 2.7
      Added the optional flags argument.



.. function:: findall(pattern, string, flags=0)

   Return all non-overlapping matches of *pattern* in *string*, as a list of
   strings.  The *string* is scanned left-to-right, and matches are returned in
   the order found.  If one or more groups are present in the pattern, return a
   list of groups; this will be a list of tuples if the pattern has more than
   one group.  Empty matches are included in the result.

   .. note::

      Due to the limitation of the current implementation the character
      following an empty match is not included in a next match, so
      ``findall(r'^|\w+', 'two words')`` returns ``['', 'wo', 'words']``
      (note missed "t").  This is changed in Python 3.7.

   .. versionadded:: 1.5.2

   .. versionchanged:: 2.4
      Added the optional flags argument.


.. function:: finditer(pattern, string, flags=0)

   Return an :term:`iterator` yielding :class:`MatchObject` instances over all
   non-overlapping matches for the RE *pattern* in *string*.  The *string* is
   scanned left-to-right, and matches are returned in the order found.  Empty
   matches are included in the result.  See also the note about :func:`findall`.

   .. versionadded:: 2.2

   .. versionchanged:: 2.4
      Added the optional flags argument.


.. function:: sub(pattern, repl, string, count=0, flags=0)

   Return the string obtained by replacing the leftmost non-overlapping occurrences
   of *pattern* in *string* by the replacement *repl*.  If the pattern isn't found,
   *string* is returned unchanged.  *repl* can be a string or a function; if it is
   a string, any backslash escapes in it are processed.  That is, ``\n`` is
   converted to a single newline character, ``\r`` is converted to a carriage return, and
   so forth.  Unknown escapes such as ``\j`` are left alone.  Backreferences, such
   as ``\6``, are replaced with the substring matched by group 6 in the pattern.
   For example:

      >>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
      ...        r'static PyObject*\npy_\1(void)\n{',
      ...        'def myfunc():')
      'static PyObject*\npy_myfunc(void)\n{'

   If *repl* is a function, it is called for every non-overlapping occurrence of
   *pattern*.  The function takes a single match object argument, and returns the
   replacement string.  For example:

      >>> def dashrepl(matchobj):
      ...     if matchobj.group(0) == '-': return ' '
      ...     else: return '-'
      >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files')
      'pro--gram files'
      >>> re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE)
      'Baked Beans & Spam'

   The pattern may be a string or an RE object.

   The optional argument *count* is the maximum number of pattern occurrences to be
   replaced; *count* must be a non-negative integer.  If omitted or zero, all
   occurrences will be replaced. Empty matches for the pattern are replaced only
   when not adjacent to a previous match, so ``sub('x*', '-', 'abc')`` returns
   ``'-a-b-c-'``.

   In string-type *repl* arguments, in addition to the character escapes and
   backreferences described above,
   ``\g<name>`` will use the substring matched by the group named ``name``, as
   defined by the ``(?P<name>...)`` syntax. ``\g<number>`` uses the corresponding
   group number; ``\g<2>`` is therefore equivalent to ``\2``, but isn't ambiguous
   in a replacement such as ``\g<2>0``.  ``\20`` would be interpreted as a
   reference to group 20, not a reference to group 2 followed by the literal
   character ``'0'``.  The backreference ``\g<0>`` substitutes in the entire
   substring matched by the RE.

   .. versionchanged:: 2.7
      Added the optional flags argument.


.. function:: subn(pattern, repl, string, count=0, flags=0)

   Perform the same operation as :func:`sub`, but return a tuple ``(new_string,
   number_of_subs_made)``.

   .. versionchanged:: 2.7
      Added the optional flags argument.


.. function:: escape(pattern)

   Escape all the characters in *pattern* except ASCII letters and numbers.
   This is useful if you want to match an arbitrary literal string that may
   have regular expression metacharacters in it.  For example::

      >>> print re.escape('python.exe')
      python\.exe

      >>> legal_chars = string.ascii_lowercase + string.digits + "!#$%&'*+-.^_`|~:"
      >>> print '[%s]+' % re.escape(legal_chars)
      [abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&\'\*\+\-\.\^\_\`\|\~\:]+

      >>> operators = ['+', '-', '*', '/', '**']
      >>> print '|'.join(map(re.escape, sorted(operators, reverse=True)))
      \/|\-|\+|\*\*|\*


.. function:: purge()

   Clear the regular expression cache.


.. exception:: error

   Exception raised when a string passed to one of the functions here is not a
   valid regular expression (for example, it might contain unmatched parentheses)
   or when some other error occurs during compilation or matching.  It is never an
   error if a string contains no match for a pattern.


.. _re-objects:

Regular Expression Objects
--------------------------

.. class:: RegexObject

   The :class:`RegexObject` class supports the following methods and attributes:

   .. method:: RegexObject.search(string[, pos[, endpos]])

      Scan through *string* looking for a location where this regular expression
      produces a match, and return a corresponding :class:`MatchObject` instance.
      Return ``None`` if no position in the string matches the pattern; note that this
      is different from finding a zero-length match at some point in the string.

      The optional second parameter *pos* gives an index in the string where the
      search is to start; it defaults to ``0``.  This is not completely equivalent to
      slicing the string; the ``'^'`` pattern character matches at the real beginning
      of the string and at positions just after a newline, but not necessarily at the
      index where the search is to start.

      The optional parameter *endpos* limits how far the string will be searched; it
      will be as if the string is *endpos* characters long, so only the characters
      from *pos* to ``endpos - 1`` will be searched for a match.  If *endpos* is less
      than *pos*, no match will be found, otherwise, if *rx* is a compiled regular
      expression object, ``rx.search(string, 0, 50)`` is equivalent to
      ``rx.search(string[:50], 0)``.

      >>> pattern = re.compile("d")
      >>> pattern.search("dog")     # Match at index 0
      <_sre.SRE_Match object at ...>
      >>> pattern.search("dog", 1)  # No match; search doesn't include the "d"


   .. method:: RegexObject.match(string[, pos[, endpos]])

      If zero or more characters at the *beginning* of *string* match this regular
      expression, return a corresponding :class:`MatchObject` instance.  Return
      ``None`` if the string does not match the pattern; note that this is different
      from a zero-length match.

      The optional *pos* and *endpos* parameters have the same meaning as for the
      :meth:`~RegexObject.search` method.

      >>> pattern = re.compile("o")
      >>> pattern.match("dog")      # No match as "o" is not at the start of "dog".
      >>> pattern.match("dog", 1)   # Match as "o" is the 2nd character of "dog".
      <_sre.SRE_Match object at ...>

      If you want to locate a match anywhere in *string*, use
      :meth:`~RegexObject.search` instead (see also :ref:`search-vs-match`).


   .. method:: RegexObject.split(string, maxsplit=0)

      Identical to the :func:`split` function, using the compiled pattern.


   .. method:: RegexObject.findall(string[, pos[, endpos]])

      Similar to the :func:`findall` function, using the compiled pattern, but
      also accepts optional *pos* and *endpos* parameters that limit the search
      region like for :meth:`match`.


   .. method:: RegexObject.finditer(string[, pos[, endpos]])

      Similar to the :func:`finditer` function, using the compiled pattern, but
      also accepts optional *pos* and *endpos* parameters that limit the search
      region like for :meth:`match`.


   .. method:: RegexObject.sub(repl, string, count=0)

      Identical to the :func:`sub` function, using the compiled pattern.


   .. method:: RegexObject.subn(repl, string, count=0)

      Identical to the :func:`subn` function, using the compiled pattern.


   .. attribute:: RegexObject.flags

      The regex matching flags.  This is a combination of the flags given to
      :func:`.compile` and any ``(?...)`` inline flags in the pattern.


   .. attribute:: RegexObject.groups

      The number of capturing groups in the pattern.


   .. attribute:: RegexObject.groupindex

      A dictionary mapping any symbolic group names defined by ``(?P<id>)`` to group
      numbers.  The dictionary is empty if no symbolic groups were used in the
      pattern.


   .. attribute:: RegexObject.pattern

      The pattern string from which the RE object was compiled.


.. _match-objects:

Match Objects
-------------

.. class:: MatchObject

   Match objects always have a boolean value of ``True``.
   Since :meth:`~regex.match` and :meth:`~regex.search` return ``None``
   when there is no match, you can test whether there was a match with a simple
   ``if`` statement::

      match = re.search(pattern, string)
      if match:
          process(match)

   Match objects support the following methods and attributes:


   .. method:: MatchObject.expand(template)

      Return the string obtained by doing backslash substitution on the template
      string *template*, as done by the :meth:`~RegexObject.sub` method.  Escapes
      such as ``\n`` are converted to the appropriate characters, and numeric
      backreferences (``\1``, ``\2``) and named backreferences (``\g<1>``,
      ``\g<name>``) are replaced by the contents of the corresponding group.


   .. method:: MatchObject.group([group1, ...])

      Returns one or more subgroups of the match.  If there is a single argument, the
      result is a single string; if there are multiple arguments, the result is a
      tuple with one item per argument. Without arguments, *group1* defaults to zero
      (the whole match is returned). If a *groupN* argument is zero, the corresponding
      return value is the entire matching string; if it is in the inclusive range
      [1..99], it is the string matching the corresponding parenthesized group.  If a
      group number is negative or larger than the number of groups defined in the
      pattern, an :exc:`IndexError` exception is raised. If a group is contained in a
      part of the pattern that did not match, the corresponding result is ``None``.
      If a group is contained in a part of the pattern that matched multiple times,
      the last match is returned.

         >>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
         >>> m.group(0)       # The entire match
         'Isaac Newton'
         >>> m.group(1)       # The first parenthesized subgroup.
         'Isaac'
         >>> m.group(2)       # The second parenthesized subgroup.
         'Newton'
         >>> m.group(1, 2)    # Multiple arguments give us a tuple.
         ('Isaac', 'Newton')

      If the regular expression uses the ``(?P<name>...)`` syntax, the *groupN*
      arguments may also be strings identifying groups by their group name.  If a
      string argument is not used as a group name in the pattern, an :exc:`IndexError`
      exception is raised.

      A moderately complicated example:

         >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
         >>> m.group('first_name')
         'Malcolm'
         >>> m.group('last_name')
         'Reynolds'

      Named groups can also be referred to by their index:

         >>> m.group(1)
         'Malcolm'
         >>> m.group(2)
         'Reynolds'

      If a group matches multiple times, only the last match is accessible:

         >>> m = re.match(r"(..)+", "a1b2c3")  # Matches 3 times.
         >>> m.group(1)                        # Returns only the last match.
         'c3'


   .. method:: MatchObject.groups([default])

      Return a tuple containing all the subgroups of the match, from 1 up to however
      many groups are in the pattern.  The *default* argument is used for groups that
      did not participate in the match; it defaults to ``None``.  (Incompatibility
      note: in the original Python 1.5 release, if the tuple was one element long, a
      string would be returned instead.  In later versions (from 1.5.1 on), a
      singleton tuple is returned in such cases.)

      For example:

         >>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
         >>> m.groups()
         ('24', '1632')

      If we make the decimal place and everything after it optional, not all groups
      might participate in the match.  These groups will default to ``None`` unless
      the *default* argument is given:

         >>> m = re.match(r"(\d+)\.?(\d+)?", "24")
         >>> m.groups()      # Second group defaults to None.
         ('24', None)
         >>> m.groups('0')   # Now, the second group defaults to '0'.
         ('24', '0')


   .. method:: MatchObject.groupdict([default])

      Return a dictionary containing all the *named* subgroups of the match, keyed by
      the subgroup name.  The *default* argument is used for groups that did not
      participate in the match; it defaults to ``None``.  For example:

         >>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
         >>> m.groupdict()
         {'first_name': 'Malcolm', 'last_name': 'Reynolds'}


   .. method:: MatchObject.start([group])
               MatchObject.end([group])

      Return the indices of the start and end of the substring matched by *group*;
      *group* defaults to zero (meaning the whole matched substring). Return ``-1`` if
      *group* exists but did not contribute to the match.  For a match object *m*, and
      a group *g* that did contribute to the match, the substring matched by group *g*
      (equivalent to ``m.group(g)``) is ::

         m.string[m.start(g):m.end(g)]

      Note that ``m.start(group)`` will equal ``m.end(group)`` if *group* matched a
      null string.  For example, after ``m = re.search('b(c?)', 'cba')``,
      ``m.start(0)`` is 1, ``m.end(0)`` is 2, ``m.start(1)`` and ``m.end(1)`` are both
      2, and ``m.start(2)`` raises an :exc:`IndexError` exception.

      An example that will remove *remove_this* from email addresses:

         >>> email = "tony@tiremove_thisger.net"
         >>> m = re.search("remove_this", email)
         >>> email[:m.start()] + email[m.end():]
         'tony@tiger.net'


   .. method:: MatchObject.span([group])

      For :class:`MatchObject` *m*, return the 2-tuple ``(m.start(group),
      m.end(group))``. Note that if *group* did not contribute to the match, this is
      ``(-1, -1)``.  *group* defaults to zero, the entire match.


   .. attribute:: MatchObject.pos

      The value of *pos* which was passed to the :meth:`~RegexObject.search` or
      :meth:`~RegexObject.match` method of the :class:`RegexObject`.  This is the
      index into the string at which the RE engine started looking for a match.


   .. attribute:: MatchObject.endpos

      The value of *endpos* which was passed to the :meth:`~RegexObject.search` or
      :meth:`~RegexObject.match` method of the :class:`RegexObject`.  This is the
      index into the string beyond which the RE engine will not go.


   .. attribute:: MatchObject.lastindex

      The integer index of the last matched capturing group, or ``None`` if no group
      was matched at all. For example, the expressions ``(a)b``, ``((a)(b))``, and
      ``((ab))`` will have ``lastindex == 1`` if applied to the string ``'ab'``, while
      the expression ``(a)(b)`` will have ``lastindex == 2``, if applied to the same
      string.


   .. attribute:: MatchObject.lastgroup

      The name of the last matched capturing group, or ``None`` if the group didn't
      have a name, or if no group was matched at all.


   .. attribute:: MatchObject.re

      The regular expression object whose :meth:`~RegexObject.match` or
      :meth:`~RegexObject.search` method produced this :class:`MatchObject`
      instance.


   .. attribute:: MatchObject.string

      The string passed to :meth:`~RegexObject.match` or
      :meth:`~RegexObject.search`.


Examples
--------


Checking For a Pair
^^^^^^^^^^^^^^^^^^^

In this example, we'll use the following helper function to display match
objects a little more gracefully:

.. testcode::

   def displaymatch(match):
       if match is None:
           return None
       return '<Match: %r, groups=%r>' % (match.group(), match.groups())

Suppose you are writing a poker program where a player's hand is represented as
a 5-character string with each character representing a card, "a" for ace, "k"
for king, "q" for queen, "j" for jack, "t" for 10, and "2" through "9"
representing the card with that value.

To see if a given string is a valid hand, one could do the following:

   >>> valid = re.compile(r"^[a2-9tjqk]{5}$")
   >>> displaymatch(valid.match("akt5q"))  # Valid.
   "<Match: 'akt5q', groups=()>"
   >>> displaymatch(valid.match("akt5e"))  # Invalid.
   >>> displaymatch(valid.match("akt"))    # Invalid.
   >>> displaymatch(valid.match("727ak"))  # Valid.
   "<Match: '727ak', groups=()>"

That last hand, ``"727ak"``, contained a pair, or two of the same valued cards.
To match this with a regular expression, one could use backreferences as such:

   >>> pair = re.compile(r".*(.).*\1")
   >>> displaymatch(pair.match("717ak"))     # Pair of 7s.
   "<Match: '717', groups=('7',)>"
   >>> displaymatch(pair.match("718ak"))     # No pairs.
   >>> displaymatch(pair.match("354aa"))     # Pair of aces.
   "<Match: '354aa', groups=('a',)>"

To find out what card the pair consists of, one could use the
:meth:`~MatchObject.group` method of :class:`MatchObject` in the following
manner:

.. doctest::

   >>> pair.match("717ak").group(1)
   '7'

   # Error because re.match() returns None, which doesn't have a group() method:
   >>> pair.match("718ak").group(1)
   Traceback (most recent call last):
     File "<pyshell#23>", line 1, in <module>
       re.match(r".*(.).*\1", "718ak").group(1)
   AttributeError: 'NoneType' object has no attribute 'group'

   >>> pair.match("354aa").group(1)
   'a'


Simulating scanf()
^^^^^^^^^^^^^^^^^^

.. index:: single: scanf()

Python does not currently have an equivalent to :c:func:`scanf`.  Regular
expressions are generally more powerful, though also more verbose, than
:c:func:`scanf` format strings.  The table below offers some more-or-less
equivalent mappings between :c:func:`scanf` format tokens and regular
expressions.

+--------------------------------+---------------------------------------------+
| :c:func:`scanf` Token          | Regular Expression                          |
+================================+=============================================+
| ``%c``                         | ``.``                                       |
+--------------------------------+---------------------------------------------+
| ``%5c``                        | ``.{5}``                                    |
+--------------------------------+---------------------------------------------+
| ``%d``                         | ``[-+]?\d+``                                |
+--------------------------------+---------------------------------------------+
| ``%e``, ``%E``, ``%f``, ``%g`` | ``[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?`` |
+--------------------------------+---------------------------------------------+
| ``%i``                         | ``[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)``     |
+--------------------------------+---------------------------------------------+
| ``%o``                         | ``[-+]?[0-7]+``                             |
+--------------------------------+---------------------------------------------+
| ``%s``                         | ``\S+``                                     |
+--------------------------------+---------------------------------------------+
| ``%u``                         | ``\d+``                                     |
+--------------------------------+---------------------------------------------+
| ``%x``, ``%X``                 | ``[-+]?(0[xX])?[\dA-Fa-f]+``                |
+--------------------------------+---------------------------------------------+

To extract the filename and numbers from a string like ::

   /usr/sbin/sendmail - 0 errors, 4 warnings

you would use a :c:func:`scanf` format like ::

   %s - %d errors, %d warnings

The equivalent regular expression would be ::

   (\S+) - (\d+) errors, (\d+) warnings


.. _search-vs-match:

search() vs. match()
^^^^^^^^^^^^^^^^^^^^

.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

Python offers two different primitive operations based on regular expressions:
:func:`re.match` checks for a match only at the beginning of the string, while
:func:`re.search` checks for a match anywhere in the string (this is what Perl
does by default).

For example::

   >>> re.match("c", "abcdef")    # No match
   >>> re.search("c", "abcdef")   # Match
   <_sre.SRE_Match object at ...>

Regular expressions beginning with ``'^'`` can be used with :func:`search` to
restrict the match at the beginning of the string::

   >>> re.match("c", "abcdef")    # No match
   >>> re.search("^c", "abcdef")  # No match
   >>> re.search("^a", "abcdef")  # Match
   <_sre.SRE_Match object at ...>

Note however that in :const:`MULTILINE` mode :func:`match` only matches at the
beginning of the string, whereas using :func:`search` with a regular expression
beginning with ``'^'`` will match at the beginning of each line.

   >>> re.match('X', 'A\nB\nX', re.MULTILINE)  # No match
   >>> re.search('^X', 'A\nB\nX', re.MULTILINE)  # Match
   <_sre.SRE_Match object at ...>


Making a Phonebook
^^^^^^^^^^^^^^^^^^

:func:`split` splits a string into a list delimited by the passed pattern.  The
method is invaluable for converting textual data into data structures that can be
easily read and modified by Python as demonstrated in the following example that
creates a phonebook.

First, here is the input.  Normally it may come from a file, here we are using
triple-quoted string syntax:

   >>> text = """Ross McFluff: 834.345.1254 155 Elm Street
   ...
   ... Ronald Heathmore: 892.345.3428 436 Finley Avenue
   ... Frank Burger: 925.541.7625 662 South Dogwood Way
   ...
   ...
   ... Heather Albrecht: 548.326.4584 919 Park Place"""

The entries are separated by one or more newlines. Now we convert the string
into a list with each nonempty line having its own entry:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> entries = re.split("\n+", text)
   >>> entries
   ['Ross McFluff: 834.345.1254 155 Elm Street',
   'Ronald Heathmore: 892.345.3428 436 Finley Avenue',
   'Frank Burger: 925.541.7625 662 South Dogwood Way',
   'Heather Albrecht: 548.326.4584 919 Park Place']

Finally, split each entry into a list with first name, last name, telephone
number, and address.  We use the ``maxsplit`` parameter of :func:`split`
because the address has spaces, our splitting pattern, in it:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> [re.split(":? ", entry, 3) for entry in entries]
   [['Ross', 'McFluff', '834.345.1254', '155 Elm Street'],
   ['Ronald', 'Heathmore', '892.345.3428', '436 Finley Avenue'],
   ['Frank', 'Burger', '925.541.7625', '662 South Dogwood Way'],
   ['Heather', 'Albrecht', '548.326.4584', '919 Park Place']]

The ``:?`` pattern matches the colon after the last name, so that it does not
occur in the result list.  With a ``maxsplit`` of ``4``, we could separate the
house number from the street name:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> [re.split(":? ", entry, 4) for entry in entries]
   [['Ross', 'McFluff', '834.345.1254', '155', 'Elm Street'],
   ['Ronald', 'Heathmore', '892.345.3428', '436', 'Finley Avenue'],
   ['Frank', 'Burger', '925.541.7625', '662', 'South Dogwood Way'],
   ['Heather', 'Albrecht', '548.326.4584', '919', 'Park Place']]


Text Munging
^^^^^^^^^^^^

:func:`sub` replaces every occurrence of a pattern with a string or the
result of a function.  This example demonstrates using :func:`sub` with
a function to "munge" text, or randomize the order of all the characters
in each word of a sentence except for the first and last characters::

   >>> def repl(m):
   ...     inner_word = list(m.group(2))
   ...     random.shuffle(inner_word)
   ...     return m.group(1) + "".join(inner_word) + m.group(3)
   >>> text = "Professor Abdolmalek, please report your absences promptly."
   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
   'Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.'
   >>> re.sub(r"(\w)(\w+)(\w)", repl, text)
   'Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.'


Finding all Adverbs
^^^^^^^^^^^^^^^^^^^

:func:`findall` matches *all* occurrences of a pattern, not just the first
one as :func:`search` does.  For example, if a writer wanted to
find all of the adverbs in some text, they might use :func:`findall` in
the following manner:

   >>> text = "He was carefully disguised but captured quickly by police."
   >>> re.findall(r"\w+ly", text)
   ['carefully', 'quickly']


Finding all Adverbs and their Positions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

If one wants more information about all matches of a pattern than the matched
text, :func:`finditer` is useful as it provides instances of
:class:`MatchObject` instead of strings.  Continuing with the previous example,
if a writer wanted to find all of the adverbs *and their positions*
in some text, they would use :func:`finditer` in the following manner:

   >>> text = "He was carefully disguised but captured quickly by police."
   >>> for m in re.finditer(r"\w+ly", text):
   ...     print '%02d-%02d: %s' % (m.start(), m.end(), m.group(0))
   07-16: carefully
   40-47: quickly


Raw String Notation
^^^^^^^^^^^^^^^^^^^

Raw string notation (``r"text"``) keeps regular expressions sane.  Without it,
every backslash (``'\'``) in a regular expression would have to be prefixed with
another one to escape it.  For example, the two following lines of code are
functionally identical:

   >>> re.match(r"\W(.)\1\W", " ff ")
   <_sre.SRE_Match object at ...>
   >>> re.match("\\W(.)\\1\\W", " ff ")
   <_sre.SRE_Match object at ...>

When one wants to match a literal backslash, it must be escaped in the regular
expression.  With raw string notation, this means ``r"\\"``.  Without raw string
notation, one must use ``"\\\\"``, making the following lines of code
functionally identical:

   >>> re.match(r"\\", r"\\")
   <_sre.SRE_Match object at ...>
   >>> re.match("\\\\", r"\\")
   <_sre.SRE_Match object at ...>
PK
%�\�JN))&html/_sources/library/readline.rst.txtnu�[���:mod:`readline` --- GNU readline interface
==========================================

.. module:: readline
   :platform: Unix
   :synopsis: GNU readline support for Python.
.. sectionauthor:: Skip Montanaro <skip@pobox.com>


The :mod:`readline` module defines a number of functions to facilitate
completion and reading/writing of history files from the Python interpreter.
This module can be used directly, or via the :mod:`rlcompleter` module, which
supports completion of Python identifiers at the interactive prompt.  Settings
made using  this module affect the behaviour of both the interpreter's
interactive prompt  and the prompts offered by the :func:`raw_input` and
:func:`input` built-in functions.

.. note::

  The underlying Readline library API may be implemented by
  the ``libedit`` library instead of GNU readline.
  On MacOS X the :mod:`readline` module detects which library is being used
  at run time.

  The configuration file for ``libedit`` is different from that
  of GNU readline. If you programmatically load configuration strings
  you can check for the text "libedit" in :const:`readline.__doc__`
  to differentiate between GNU readline and libedit.

Readline keybindings may be configured via an initialization file, typically
``.inputrc`` in your home directory.  See `Readline Init File
<https://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC9>`_
in the GNU Readline manual for information about the format and
allowable constructs of that file, and the capabilities of the
Readline library in general.


Init file
---------

The following functions relate to the init file and user configuration:


.. function:: parse_and_bind(string)

   Execute the init line provided in the *string* argument. This calls
   :c:func:`rl_parse_and_bind` in the underlying library.


.. function:: read_init_file([filename])

   Execute a readline initialization file. The default filename is the last filename
   used. This calls :c:func:`rl_read_init_file` in the underlying library.


Line buffer
-----------

The following functions operate on the line buffer:


.. function:: get_line_buffer()

   Return the current contents of the line buffer (:c:data:`rl_line_buffer`
   in the underlying library).


.. function:: insert_text(string)

   Insert text into the line buffer at the cursor position.  This calls
   :c:func:`rl_insert_text` in the underlying library, but ignores
   the return value.


.. function:: redisplay()

   Change what's displayed on the screen to reflect the current contents of the
   line buffer.  This calls :c:func:`rl_redisplay` in the underlying library.


History file
------------

The following functions operate on a history file:


.. function:: read_history_file([filename])

   Load a readline history file, and append it to the history list.
   The default filename is :file:`~/.history`.  This calls
   :c:func:`read_history` in the underlying library.


.. function:: write_history_file([filename])

   Save the history list to a readline history file, overwriting any
   existing file.  The default filename is :file:`~/.history`.  This calls
   :c:func:`write_history` in the underlying library.


.. function:: get_history_length()
              set_history_length(length)

   Set or return the desired number of lines to save in the history file.
   The :func:`write_history_file` function uses this value to truncate
   the history file, by calling :c:func:`history_truncate_file` in
   the underlying library.  Negative values imply
   unlimited history file size.


History list
------------

The following functions operate on a global history list:


.. function:: clear_history()

   Clear the current history.  This calls :c:func:`clear_history` in the
   underlying library.  The Python function only exists if Python was
   compiled for a version of the library that supports it.

   .. versionadded:: 2.4


.. function:: get_current_history_length()

   Return the number of items currently in the history.  (This is different from
   :func:`get_history_length`, which returns the maximum number of lines that will
   be written to a history file.)

   .. versionadded:: 2.3


.. function:: get_history_item(index)

   Return the current contents of history item at *index*.  The item index
   is one-based.  This calls :c:func:`history_get` in the underlying library.

   .. versionadded:: 2.3


.. function:: remove_history_item(pos)

   Remove history item specified by its position from the history.
   The position is zero-based.  This calls :c:func:`remove_history` in
   the underlying library.

   .. versionadded:: 2.4


.. function:: replace_history_item(pos, line)

   Replace history item specified by its position with *line*.
   The position is zero-based.  This calls :c:func:`replace_history_entry`
   in the underlying library.

   .. versionadded:: 2.4


.. function:: add_history(line)

   Append *line* to the history buffer, as if it was the last line typed.
   This calls :c:func:`add_history` in the underlying library.


Startup hooks
-------------

   .. versionadded:: 2.3


.. function:: set_startup_hook([function])

   Set or remove the function invoked by the :c:data:`rl_startup_hook`
   callback of the underlying library.  If *function* is specified, it will
   be used as the new hook function; if omitted or ``None``, any function
   already installed is removed.  The hook is called with no
   arguments just before readline prints the first prompt.


.. function:: set_pre_input_hook([function])

   Set or remove the function invoked by the :c:data:`rl_pre_input_hook`
   callback of the underlying library.  If *function* is specified, it will
   be used as the new hook function; if omitted or ``None``, any
   function already installed is removed.  The hook is called
   with no arguments after the first prompt has been printed and just before
   readline starts reading input characters.  This function only exists
   if Python was compiled for a version of the library that supports it.


Completion
----------

The following functions relate to implementing a custom word completion
function.  This is typically operated by the Tab key, and can suggest and
automatically complete a word being typed.  By default, Readline is set up
to be used by :mod:`rlcompleter` to complete Python identifiers for
the interactive interpreter.  If the :mod:`readline` module is to be used
with a custom completer, a different set of word delimiters should be set.


.. function:: set_completer([function])

   Set or remove the completer function.  If *function* is specified, it will be
   used as the new completer function; if omitted or ``None``, any completer
   function already installed is removed.  The completer function is called as
   ``function(text, state)``, for *state* in ``0``, ``1``, ``2``, ..., until it
   returns a non-string value.  It should return the next possible completion
   starting with *text*.

   The installed completer function is invoked by the *entry_func* callback
   passed to :c:func:`rl_completion_matches` in the underlying library.
   The *text* string comes from the first parameter to the
   :c:data:`rl_attempted_completion_function` callback of the
   underlying library.


.. function:: get_completer()

   Get the completer function, or ``None`` if no completer function has been set.

   .. versionadded:: 2.3


.. function:: get_completion_type()

   Get the type of completion being attempted.  This returns the
   :c:data:`rl_completion_type` variable in the underlying library as
   an integer.

   .. versionadded:: 2.6

.. function:: get_begidx()
              get_endidx()

   Get the beginning or ending index of the completion scope.
   These indexes are the *start* and *end* arguments passed to the
   :c:data:`rl_attempted_completion_function` callback of the
   underlying library.


.. function:: set_completer_delims(string)
              get_completer_delims()

   Set or get the word delimiters for completion.  These determine the
   start of the word to be considered for completion (the completion scope).
   These functions access the :c:data:`rl_completer_word_break_characters`
   variable in the underlying library.

.. function:: set_completion_display_matches_hook([function])

   Set or remove the completion display function.  If *function* is
   specified, it will be used as the new completion display function;
   if omitted or ``None``, any completion display function already
   installed is removed.  This sets or clears the
   :c:data:`rl_completion_display_matches_hook` callback in the
   underlying library.  The completion display function is called as
   ``function(substitution, [matches], longest_match_length)`` once
   each time matches need to be displayed.

   .. versionadded:: 2.6

.. _readline-example:

Example
-------

The following example demonstrates how to use the :mod:`readline` module's
history reading and writing functions to automatically load and save a history
file named :file:`.pyhist` from the user's home directory.  The code below would
normally be executed automatically during interactive sessions from the user's
:envvar:`PYTHONSTARTUP` file. ::

   import os
   import readline
   histfile = os.path.join(os.path.expanduser("~"), ".pyhist")
   try:
       readline.read_history_file(histfile)
       # default history len is -1 (infinite), which may grow unruly
       readline.set_history_length(1000)
   except IOError:
       pass
   import atexit
   atexit.register(readline.write_history_file, histfile)
   del os, histfile

The following example extends the :class:`code.InteractiveConsole` class to
support history save/restore. ::

   import code
   import readline
   import atexit
   import os

   class HistoryConsole(code.InteractiveConsole):
       def __init__(self, locals=None, filename="<console>",
                    histfile=os.path.expanduser("~/.console-history")):
           code.InteractiveConsole.__init__(self, locals, filename)
           self.init_history(histfile)

       def init_history(self, histfile):
           readline.parse_and_bind("tab: complete")
           if hasattr(readline, "read_history_file"):
               try:
                   readline.read_history_file(histfile)
               except IOError:
                   pass
               atexit.register(self.save_history, histfile)

       def save_history(self, histfile):
           readline.set_history_length(1000)
           readline.write_history_file(histfile)

PK
%�\��\�nn"html/_sources/library/repr.rst.txtnu�[���:mod:`repr` --- Alternate :func:`repr` implementation
=====================================================

.. module:: repr
   :synopsis: Alternate repr() implementation with size limits.
   :noindex:
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

.. note::
   The :mod:`repr` module has been renamed to :mod:`reprlib` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

**Source code:** :source:`Lib/repr.py`

--------------

The :mod:`repr` module provides a means for producing object representations
with limits on the size of the resulting strings. This is used in the Python
debugger and may be useful in other contexts as well.

This module provides a class, an instance, and a function:


.. class:: Repr()

   Class which provides formatting services useful in implementing functions
   similar to the built-in :ref:`repr() <func-repr>`; size limits for different
   object types are added to avoid the generation of representations which are
   excessively long.


.. data:: aRepr

   This is an instance of :class:`Repr` which is used to provide the :func:`.repr`
   function described below.  Changing the attributes of this object will affect
   the size limits used by :func:`.repr` and the Python debugger.


.. function:: repr(obj)

   This is the :meth:`~Repr.repr` method of ``aRepr``.  It returns a string
   similar to that returned by the built-in function of the same name, but with
   limits on most sizes.


.. _repr-objects:

Repr Objects
------------

:class:`Repr` instances provide several attributes which can be used to provide
size limits for the representations of different object types,  and methods
which format specific object types.


.. attribute:: Repr.maxlevel

   Depth limit on the creation of recursive representations.  The default is ``6``.


.. attribute:: Repr.maxdict
               Repr.maxlist
               Repr.maxtuple
               Repr.maxset
               Repr.maxfrozenset
               Repr.maxdeque
               Repr.maxarray

   Limits on the number of entries represented for the named object type.  The
   default is ``4`` for :attr:`maxdict`, ``5`` for :attr:`maxarray`, and  ``6`` for
   the others.

   .. versionadded:: 2.4
      :attr:`maxset`, :attr:`maxfrozenset`, and :attr:`set`.


.. attribute:: Repr.maxlong

   Maximum number of characters in the representation for a long integer.  Digits
   are dropped from the middle.  The default is ``40``.


.. attribute:: Repr.maxstring

   Limit on the number of characters in the representation of the string.  Note
   that the "normal" representation of the string is used as the character source:
   if escape sequences are needed in the representation, these may be mangled when
   the representation is shortened.  The default is ``30``.


.. attribute:: Repr.maxother

   This limit is used to control the size of object types for which no specific
   formatting method is available on the :class:`Repr` object. It is applied in a
   similar manner as :attr:`maxstring`.  The default is ``20``.


.. method:: Repr.repr(obj)

   The equivalent to the built-in :ref:`repr() <func-repr>` that uses the
   formatting imposed by the instance.


.. method:: Repr.repr1(obj, level)

   Recursive implementation used by :meth:`.repr`.  This uses the type of *obj* to
   determine which formatting method to call, passing it *obj* and *level*.  The
   type-specific methods should call :meth:`repr1` to perform recursive formatting,
   with ``level - 1`` for the value of *level* in the recursive  call.


.. method:: Repr.repr_TYPE(obj, level)
   :noindex:

   Formatting methods for specific types are implemented as methods with a name
   based on the type name.  In the method name, **TYPE** is replaced by
   ``string.join(string.split(type(obj).__name__, '_'))``. Dispatch to these
   methods is handled by :meth:`repr1`. Type-specific methods which need to
   recursively format a value should call ``self.repr1(subobj, level - 1)``.


.. _subclassing-reprs:

Subclassing Repr Objects
------------------------

The use of dynamic dispatching by :meth:`Repr.repr1` allows subclasses of
:class:`Repr` to add support for additional built-in object types or to modify
the handling of types already supported. This example shows how special support
for file objects could be added::

   import repr as reprlib
   import sys

   class MyRepr(reprlib.Repr):
       def repr_file(self, obj, level):
           if obj.name in ['<stdin>', '<stdout>', '<stderr>']:
               return obj.name
           else:
               return repr(obj)

   aRepr = MyRepr()
   print aRepr.repr(sys.stdin)          # prints '<stdin>'

PK
%�\�bO�{%{%&html/_sources/library/resource.rst.txtnu�[���
:mod:`resource` --- Resource usage information
==============================================

.. module:: resource
   :platform: Unix
   :synopsis: An interface to provide resource usage information on the current process.
.. moduleauthor:: Jeremy Hylton <jeremy@alum.mit.edu>
.. sectionauthor:: Jeremy Hylton <jeremy@alum.mit.edu>


This module provides basic mechanisms for measuring and controlling system
resources utilized by a program.

Symbolic constants are used to specify particular system resources and to
request usage information about either the current process or its children.

A single exception is defined for errors:


.. exception:: error

   The functions described below may raise this error if the underlying system call
   failures unexpectedly.


Resource Limits
---------------

Resources usage can be limited using the :func:`setrlimit` function described
below. Each resource is controlled by a pair of limits: a soft limit and a hard
limit. The soft limit is the current limit, and may be lowered or raised by a
process over time. The soft limit can never exceed the hard limit. The hard
limit can be lowered to any value greater than the soft limit, but not raised.
(Only processes with the effective UID of the super-user can raise a hard
limit.)

The specific resources that can be limited are system dependent. They are
described in the :manpage:`getrlimit(2)` man page.  The resources listed below
are supported when the underlying operating system supports them; resources
which cannot be checked or controlled by the operating system are not defined in
this module for those platforms.


.. data:: RLIM_INFINITY

   Constant used to represent the limit for an unlimited resource.


.. function:: getrlimit(resource)

   Returns a tuple ``(soft, hard)`` with the current soft and hard limits of
   *resource*. Raises :exc:`ValueError` if an invalid resource is specified, or
   :exc:`error` if the underlying system call fails unexpectedly.


.. function:: setrlimit(resource, limits)

   Sets new limits of consumption of *resource*. The *limits* argument must be a
   tuple ``(soft, hard)`` of two integers describing the new limits. A value of
   :data:`~resource.RLIM_INFINITY` can be used to request a limit that is
   unlimited.

   Raises :exc:`ValueError` if an invalid resource is specified, if the new soft
   limit exceeds the hard limit, or if a process tries to raise its hard limit.
   Specifying a limit of :data:`~resource.RLIM_INFINITY` when the hard or
   system limit for that resource is not unlimited will result in a
   :exc:`ValueError`.  A process with the effective UID of super-user can
   request any valid limit value, including unlimited, but :exc:`ValueError`
   will still be raised if the requested limit exceeds the system imposed
   limit.

   ``setrlimit`` may also raise :exc:`error` if the underlying system call
   fails.

These symbols define resources whose consumption can be controlled using the
:func:`setrlimit` and :func:`getrlimit` functions described below. The values of
these symbols are exactly the constants used by C programs.

The Unix man page for :manpage:`getrlimit(2)` lists the available resources.
Note that not all systems use the same symbol or same value to denote the same
resource.  This module does not attempt to mask platform differences --- symbols
not defined for a platform will not be available from this module on that
platform.


.. data:: RLIMIT_CORE

   The maximum size (in bytes) of a core file that the current process can create.
   This may result in the creation of a partial core file if a larger core would be
   required to contain the entire process image.


.. data:: RLIMIT_CPU

   The maximum amount of processor time (in seconds) that a process can use. If
   this limit is exceeded, a :const:`SIGXCPU` signal is sent to the process. (See
   the :mod:`signal` module documentation for information about how to catch this
   signal and do something useful, e.g. flush open files to disk.)


.. data:: RLIMIT_FSIZE

   The maximum size of a file which the process may create.


.. data:: RLIMIT_DATA

   The maximum size (in bytes) of the process's heap.


.. data:: RLIMIT_STACK

   The maximum size (in bytes) of the call stack for the current process.  This only
   affects the stack of the main thread in a multi-threaded process.


.. data:: RLIMIT_RSS

   The maximum resident set size that should be made available to the process.


.. data:: RLIMIT_NPROC

   The maximum number of processes the current process may create.


.. data:: RLIMIT_NOFILE

   The maximum number of open file descriptors for the current process.


.. data:: RLIMIT_OFILE

   The BSD name for :const:`RLIMIT_NOFILE`.


.. data:: RLIMIT_MEMLOCK

   The maximum address space which may be locked in memory.


.. data:: RLIMIT_VMEM

   The largest area of mapped memory which the process may occupy.


.. data:: RLIMIT_AS

   The maximum area (in bytes) of address space which may be taken by the process.


Resource Usage
--------------

These functions are used to retrieve resource usage information:


.. function:: getrusage(who)

   This function returns an object that describes the resources consumed by either
   the current process or its children, as specified by the *who* parameter.  The
   *who* parameter should be specified using one of the :const:`RUSAGE_\*`
   constants described below.

   The fields of the return value each describe how a particular system resource
   has been used, e.g. amount of time spent running is user mode or number of times
   the process was swapped out of main memory. Some values are dependent on the
   clock tick internal, e.g. the amount of memory the process is using.

   For backward compatibility, the return value is also accessible as a tuple of 16
   elements.

   The fields :attr:`ru_utime` and :attr:`ru_stime` of the return value are
   floating point values representing the amount of time spent executing in user
   mode and the amount of time spent executing in system mode, respectively. The
   remaining values are integers. Consult the :manpage:`getrusage(2)` man page for
   detailed information about these values. A brief summary is presented here:

   +--------+---------------------+-------------------------------+
   | Index  | Field               | Resource                      |
   +========+=====================+===============================+
   | ``0``  | :attr:`ru_utime`    | time in user mode (float)     |
   +--------+---------------------+-------------------------------+
   | ``1``  | :attr:`ru_stime`    | time in system mode (float)   |
   +--------+---------------------+-------------------------------+
   | ``2``  | :attr:`ru_maxrss`   | maximum resident set size     |
   +--------+---------------------+-------------------------------+
   | ``3``  | :attr:`ru_ixrss`    | shared memory size            |
   +--------+---------------------+-------------------------------+
   | ``4``  | :attr:`ru_idrss`    | unshared memory size          |
   +--------+---------------------+-------------------------------+
   | ``5``  | :attr:`ru_isrss`    | unshared stack size           |
   +--------+---------------------+-------------------------------+
   | ``6``  | :attr:`ru_minflt`   | page faults not requiring I/O |
   +--------+---------------------+-------------------------------+
   | ``7``  | :attr:`ru_majflt`   | page faults requiring I/O     |
   +--------+---------------------+-------------------------------+
   | ``8``  | :attr:`ru_nswap`    | number of swap outs           |
   +--------+---------------------+-------------------------------+
   | ``9``  | :attr:`ru_inblock`  | block input operations        |
   +--------+---------------------+-------------------------------+
   | ``10`` | :attr:`ru_oublock`  | block output operations       |
   +--------+---------------------+-------------------------------+
   | ``11`` | :attr:`ru_msgsnd`   | messages sent                 |
   +--------+---------------------+-------------------------------+
   | ``12`` | :attr:`ru_msgrcv`   | messages received             |
   +--------+---------------------+-------------------------------+
   | ``13`` | :attr:`ru_nsignals` | signals received              |
   +--------+---------------------+-------------------------------+
   | ``14`` | :attr:`ru_nvcsw`    | voluntary context switches    |
   +--------+---------------------+-------------------------------+
   | ``15`` | :attr:`ru_nivcsw`   | involuntary context switches  |
   +--------+---------------------+-------------------------------+

   This function will raise a :exc:`ValueError` if an invalid *who* parameter is
   specified. It may also raise :exc:`error` exception in unusual circumstances.

   .. versionchanged:: 2.3
      Added access to values as attributes of the returned object.


.. function:: getpagesize()

   Returns the number of bytes in a system page. (This need not be the same as the
   hardware page size.)

The following :const:`RUSAGE_\*` symbols are passed to the :func:`getrusage`
function to specify which processes information should be provided for.


.. data:: RUSAGE_SELF

   :const:`RUSAGE_SELF` should be used to request information pertaining only to
   the process itself.


.. data:: RUSAGE_CHILDREN

   Pass to :func:`getrusage` to request resource information for child processes of
   the calling process.


.. data:: RUSAGE_BOTH

   Pass to :func:`getrusage` to request resources consumed by both the current
   process and child processes.  May not be available on all systems.

PK
%�\�����(html/_sources/library/restricted.rst.txtnu�[���
.. _restricted:

********************
Restricted Execution
********************

.. warning::

   In Python 2.3 these modules have been disabled due to various known and not
   readily fixable security holes.  The modules are still documented here to help
   in reading old code that uses the :mod:`rexec` and :mod:`Bastion` modules.

*Restricted execution* is the basic framework in Python that allows for the
segregation of trusted and untrusted code.  The framework is based on the notion
that trusted Python code (a *supervisor*) can create a "padded cell' (or
environment) with limited permissions, and run the untrusted code within this
cell.  The untrusted code cannot break out of its cell, and can only interact
with sensitive system resources through interfaces defined and managed by the
trusted code.  The term "restricted execution" is favored over "safe-Python"
since true safety is hard to define, and is determined by the way the restricted
environment is created.  Note that the restricted environments can be nested,
with inner cells creating subcells of lesser, but never greater, privilege.

An interesting aspect of Python's restricted execution model is that the
interfaces presented to untrusted code usually have the same names as those
presented to trusted code.  Therefore no special interfaces need to be learned
to write code designed to run in a restricted environment.  And because the
exact nature of the padded cell is determined by the supervisor, different
restrictions can be imposed, depending on the application.  For example, it
might be deemed "safe" for untrusted code to read any file within a specified
directory, but never to write a file.  In this case, the supervisor may redefine
the built-in :func:`open` function so that it raises an exception whenever the
*mode* parameter is ``'w'``.  It might also perform a :c:func:`chroot`\ -like
operation on the *filename* parameter, such that root is always relative to some
safe "sandbox" area of the filesystem.  In this case, the untrusted code would
still see a built-in :func:`open` function in its environment, with the same
calling interface.  The semantics would be identical too, with :exc:`IOError`\ s
being raised when the supervisor determined that an unallowable parameter is
being used.

The Python run-time determines whether a particular code block is executing in
restricted execution mode based on the identity of the ``__builtins__`` object
in its global variables: if this is (the dictionary of) the standard
:mod:`__builtin__` module, the code is deemed to be unrestricted, else it is
deemed to be restricted.

Python code executing in restricted mode faces a number of limitations that are
designed to prevent it from escaping from the padded cell. For instance, the
function object attribute :attr:`func_globals` and the class and instance object
attribute :attr:`~object.__dict__` are unavailable.

Two modules provide the framework for setting up restricted execution
environments:


.. toctree::

   rexec.rst
   bastion.rst

.. seealso::

   `Grail Home Page <http://grail.sourceforge.net/>`_
      Grail, an Internet browser written in Python, uses these modules to support
      Python applets.  More information on the use of Python's restricted execution
      mode in Grail is available on the Web site.

PK
%�\���-�-#html/_sources/library/rexec.rst.txtnu�[���:mod:`rexec` --- Restricted execution framework
===============================================

.. module:: rexec
   :synopsis: Basic restricted execution framework.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`rexec` module has been removed in Python 3.

.. versionchanged:: 2.3
   Disabled module.

.. warning::

   The documentation has been left in place to help in reading old code that uses
   the module.

This module contains the :class:`RExec` class, which supports :meth:`r_eval`,
:meth:`r_execfile`, :meth:`r_exec`, and :meth:`r_import` methods, which are
restricted versions of the standard Python functions :meth:`eval`,
:meth:`execfile` and the :keyword:`exec` and :keyword:`import` statements. Code
executed in this restricted environment will only have access to modules and
functions that are deemed safe; you can subclass :class:`RExec` to add or remove
capabilities as desired.

.. warning::

   While the :mod:`rexec` module is designed to perform as described below, it does
   have a few known vulnerabilities which could be exploited by carefully written
   code.  Thus it should not be relied upon in situations requiring "production
   ready" security.  In such situations, execution via sub-processes or very
   careful "cleansing" of both code and data to be processed may be necessary.
   Alternatively, help in patching known :mod:`rexec` vulnerabilities would be
   welcomed.

.. note::

   The :class:`RExec` class can prevent code from performing unsafe operations like
   reading or writing disk files, or using TCP/IP sockets.  However, it does not
   protect against code using extremely large amounts of memory or processor time.


.. class:: RExec([hooks[, verbose]])

   Returns an instance of the :class:`RExec` class.

   *hooks* is an instance of the :class:`RHooks` class or a subclass of it. If it
   is omitted or ``None``, the default :class:`RHooks` class is instantiated.
   Whenever the :mod:`rexec` module searches for a module (even a built-in one) or
   reads a module's code, it doesn't actually go out to the file system itself.
   Rather, it calls methods of an :class:`RHooks` instance that was passed to or
   created by its constructor.  (Actually, the :class:`RExec` object doesn't make
   these calls --- they are made by a module loader object that's part of the
   :class:`RExec` object.  This allows another level of flexibility, which can be
   useful when changing the mechanics of :keyword:`import` within the restricted
   environment.)

   By providing an alternate :class:`RHooks` object, we can control the file system
   accesses made to import a module, without changing the actual algorithm that
   controls the order in which those accesses are made.  For instance, we could
   substitute an :class:`RHooks` object that passes all filesystem requests to a
   file server elsewhere, via some RPC mechanism such as ILU.  Grail's applet
   loader uses this to support importing applets from a URL for a directory.

   If *verbose* is true, additional debugging output may be sent to standard
   output.

It is important to be aware that code running in a restricted environment can
still call the :func:`sys.exit` function.  To disallow restricted code from
exiting the interpreter, always protect calls that cause restricted code to run
with a :keyword:`try`/:keyword:`except` statement that catches the
:exc:`SystemExit` exception.  Removing the :func:`sys.exit` function from the
restricted environment is not sufficient --- the restricted code could still use
``raise SystemExit``.  Removing :exc:`SystemExit` is not a reasonable option;
some library code makes use of this and would break were it not available.


.. seealso::

   `Grail Home Page <http://grail.sourceforge.net/>`_
      Grail is a Web browser written entirely in Python.  It uses the :mod:`rexec`
      module as a foundation for supporting Python applets, and can be used as an
      example usage of this module.


.. _rexec-objects:

RExec Objects
-------------

:class:`RExec` instances support the following methods:


.. method:: RExec.r_eval(code)

   *code* must either be a string containing a Python expression, or a compiled
   code object, which will be evaluated in the restricted environment's
   :mod:`__main__` module.  The value of the expression or code object will be
   returned.


.. method:: RExec.r_exec(code)

   *code* must either be a string containing one or more lines of Python code, or a
   compiled code object, which will be executed in the restricted environment's
   :mod:`__main__` module.


.. method:: RExec.r_execfile(filename)

   Execute the Python code contained in the file *filename* in the restricted
   environment's :mod:`__main__` module.

Methods whose names begin with ``s_`` are similar to the functions beginning
with ``r_``, but the code will be granted access to restricted versions of the
standard I/O streams ``sys.stdin``, ``sys.stderr``, and ``sys.stdout``.


.. method:: RExec.s_eval(code)

   *code* must be a string containing a Python expression, which will be evaluated
   in the restricted environment.


.. method:: RExec.s_exec(code)

   *code* must be a string containing one or more lines of Python code, which will
   be executed in the restricted environment.


.. method:: RExec.s_execfile(code)

   Execute the Python code contained in the file *filename* in the restricted
   environment.

:class:`RExec` objects must also support various methods which will be
implicitly called by code executing in the restricted environment. Overriding
these methods in a subclass is used to change the policies enforced by a
restricted environment.


.. method:: RExec.r_import(modulename[, globals[, locals[, fromlist]]])

   Import the module *modulename*, raising an :exc:`ImportError` exception if the
   module is considered unsafe.


.. method:: RExec.r_open(filename[, mode[, bufsize]])

   Method called when :func:`open` is called in the restricted environment.  The
   arguments are identical to those of :func:`open`, and a file object (or a class
   instance compatible with file objects) should be returned.  :class:`RExec`'s
   default behaviour is allow opening any file for reading, but forbidding any
   attempt to write a file.  See the example below for an implementation of a less
   restrictive :meth:`r_open`.


.. method:: RExec.r_reload(module)

   Reload the module object *module*, re-parsing and re-initializing it.


.. method:: RExec.r_unload(module)

   Unload the module object *module* (remove it from the restricted environment's
   ``sys.modules`` dictionary).

And their equivalents with access to restricted standard I/O streams:


.. method:: RExec.s_import(modulename[, globals[, locals[, fromlist]]])

   Import the module *modulename*, raising an :exc:`ImportError` exception if the
   module is considered unsafe.


.. method:: RExec.s_reload(module)

   Reload the module object *module*, re-parsing and re-initializing it.


.. method:: RExec.s_unload(module)

   Unload the module object *module*.

   .. XXX what are the semantics of this?


.. _rexec-extension:

Defining restricted environments
--------------------------------

The :class:`RExec` class has the following class attributes, which are used by
the :meth:`__init__` method.  Changing them on an existing instance won't have
any effect; instead, create a subclass of :class:`RExec` and assign them new
values in the class definition. Instances of the new class will then use those
new values.  All these attributes are tuples of strings.


.. attribute:: RExec.nok_builtin_names

   Contains the names of built-in functions which will *not* be available to
   programs running in the restricted environment.  The value for :class:`RExec` is
   ``('open', 'reload', '__import__')``. (This gives the exceptions, because by far
   the majority of built-in functions are harmless.  A subclass that wants to
   override this variable should probably start with the value from the base class
   and concatenate additional forbidden functions --- when new dangerous built-in
   functions are added to Python, they will also be added to this module.)


.. attribute:: RExec.ok_builtin_modules

   Contains the names of built-in modules which can be safely imported. The value
   for :class:`RExec` is ``('audioop', 'array', 'binascii', 'cmath', 'errno',
   'imageop', 'marshal', 'math', 'md5', 'operator', 'parser', 'regex', 'select',
   'sha', '_sre', 'strop', 'struct', 'time')``.  A similar remark about overriding
   this variable applies --- use the value from the base class as a starting point.


.. attribute:: RExec.ok_path

   Contains the directories which will be searched when an :keyword:`import` is
   performed in the restricted environment.   The value for :class:`RExec` is the
   same as ``sys.path`` (at the time the module is loaded) for unrestricted code.


.. attribute:: RExec.ok_posix_names

   Contains the names of the functions in the :mod:`os` module which will be
   available to programs running in the restricted environment.  The value for
   :class:`RExec` is ``('error', 'fstat', 'listdir', 'lstat', 'readlink', 'stat',
   'times', 'uname', 'getpid', 'getppid', 'getcwd', 'getuid', 'getgid', 'geteuid',
   'getegid')``.

   .. Should this be called ok_os_names?


.. attribute:: RExec.ok_sys_names

   Contains the names of the functions and variables in the :mod:`sys` module which
   will be available to programs running in the restricted environment.  The value
   for :class:`RExec` is ``('ps1', 'ps2', 'copyright', 'version', 'platform',
   'exit', 'maxint')``.


.. attribute:: RExec.ok_file_types

   Contains the file types from which modules are allowed to be loaded. Each file
   type is an integer constant defined in the :mod:`imp` module. The meaningful
   values are :const:`PY_SOURCE`, :const:`PY_COMPILED`, and :const:`C_EXTENSION`.
   The value for :class:`RExec` is ``(C_EXTENSION, PY_SOURCE)``.  Adding
   :const:`PY_COMPILED` in subclasses is not recommended; an attacker could exit
   the restricted execution mode by putting a forged byte-compiled file
   (:file:`.pyc`) anywhere in your file system, for example by writing it to
   :file:`/tmp` or uploading it to the :file:`/incoming` directory of your public
   FTP server.


An example
----------

Let us say that we want a slightly more relaxed policy than the standard
:class:`RExec` class.  For example, if we're willing to allow files in
:file:`/tmp` to be written, we can subclass the :class:`RExec` class::

   class TmpWriterRExec(rexec.RExec):
       def r_open(self, file, mode='r', buf=-1):
           if mode in ('r', 'rb'):
               pass
           elif mode in ('w', 'wb', 'a', 'ab'):
               # check filename: must begin with /tmp/
               if file[:5]!='/tmp/':
                   raise IOError("can't write outside /tmp")
               elif (string.find(file, '/../') >= 0 or
                    file[:3] == '../' or file[-3:] == '/..'):
                   raise IOError("'..' in filename forbidden")
           else: raise IOError("Illegal open() mode")
           return open(file, mode, buf)

Notice that the above code will occasionally forbid a perfectly valid filename;
for example, code in the restricted environment won't be able to open a file
called :file:`/tmp/foo/../bar`.  To fix this, the :meth:`r_open` method would
have to simplify the filename to :file:`/tmp/bar`, which would require splitting
apart the filename and performing various operations on it.  In cases where
security is at stake, it may be preferable to write simple code which is
sometimes overly restrictive, instead of more general code that is also more
complex and may harbor a subtle security hole.
PK
%�\��0�6�6$html/_sources/library/rfc822.rst.txtnu�[���
:mod:`rfc822` --- Parse RFC 2822 mail headers
=============================================

.. module:: rfc822
   :synopsis: Parse 2822 style mail messages.
   :deprecated:


.. deprecated:: 2.3
   The :mod:`email` package should be used in preference to the :mod:`rfc822`
   module.  This module is present only to maintain backward compatibility, and
   has been removed in Python 3.

This module defines a class, :class:`Message`, which represents an "email
message" as defined by the Internet standard :rfc:`2822`. [#]_  Such messages
consist of a collection of message headers, and a message body.  This module
also defines a helper class :class:`AddressList` for parsing :rfc:`2822`
addresses.  Please refer to the RFC for information on the specific syntax of
:rfc:`2822` messages.

.. index:: module: mailbox

The :mod:`mailbox` module provides classes  to read mailboxes produced by
various end-user mail programs.


.. class:: Message(file[, seekable])

   A :class:`Message` instance is instantiated with an input object as parameter.
   Message relies only on the input object having a :meth:`readline` method; in
   particular, ordinary file objects qualify.  Instantiation reads headers from the
   input object up to a delimiter line (normally a blank line) and stores them in
   the instance.  The message body, following the headers, is not consumed.

   This class can work with any input object that supports a :meth:`readline`
   method.  If the input object has seek and tell capability, the
   :meth:`rewindbody` method will work; also, illegal lines will be pushed back
   onto the input stream.  If the input object lacks seek but has an :meth:`unread`
   method that can push back a line of input, :class:`Message` will use that to
   push back illegal lines.  Thus this class can be used to parse messages coming
   from a buffered stream.

   The optional *seekable* argument is provided as a workaround for certain stdio
   libraries in which :c:func:`tell` discards buffered data before discovering that
   the :c:func:`lseek` system call doesn't work.  For maximum portability, you
   should set the seekable argument to zero to prevent that initial :meth:`tell`
   when passing in an unseekable object such as a file object created from a socket
   object.

   Input lines as read from the file may either be terminated by CR-LF or by a
   single linefeed; a terminating CR-LF is replaced by a single linefeed before the
   line is stored.

   All header matching is done independent of upper or lower case; e.g.
   ``m['From']``, ``m['from']`` and ``m['FROM']`` all yield the same result.


.. class:: AddressList(field)

   You may instantiate the :class:`AddressList` helper class using a single string
   parameter, a comma-separated list of :rfc:`2822` addresses to be parsed.  (The
   parameter ``None`` yields an empty list.)


.. function:: quote(str)

   Return a new string with backslashes in *str* replaced by two backslashes and
   double quotes replaced by backslash-double quote.


.. function:: unquote(str)

   Return a new string which is an *unquoted* version of *str*. If *str* ends and
   begins with double quotes, they are stripped off.  Likewise if *str* ends and
   begins with angle brackets, they are stripped off.


.. function:: parseaddr(address)

   Parse *address*, which should be the value of some address-containing field such
   as :mailheader:`To` or :mailheader:`Cc`, into its constituent "realname" and
   "email address" parts. Returns a tuple of that information, unless the parse
   fails, in which case a 2-tuple ``(None, None)`` is returned.


.. function:: dump_address_pair(pair)

   The inverse of :meth:`parseaddr`, this takes a 2-tuple of the form ``(realname,
   email_address)`` and returns the string value suitable for a :mailheader:`To` or
   :mailheader:`Cc` header.  If the first element of *pair* is false, then the
   second element is returned unmodified.


.. function:: parsedate(date)

   Attempts to parse a date according to the rules in :rfc:`2822`. however, some
   mailers don't follow that format as specified, so :func:`parsedate` tries to
   guess correctly in such cases.  *date* is a string containing an :rfc:`2822`
   date, such as  ``'Mon, 20 Nov 1995 19:12:08 -0500'``.  If it succeeds in parsing
   the date, :func:`parsedate` returns a 9-tuple that can be passed directly to
   :func:`time.mktime`; otherwise ``None`` will be returned.  Note that indexes 6,
   7, and 8 of the result tuple are not usable.


.. function:: parsedate_tz(date)

   Performs the same function as :func:`parsedate`, but returns either ``None`` or
   a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
   :func:`time.mktime`, and the tenth is the offset of the date's timezone from UTC
   (which is the official term for Greenwich Mean Time).  (Note that the sign of
   the timezone offset is the opposite of the sign of the ``time.timezone``
   variable for the same timezone; the latter variable follows the POSIX standard
   while this module follows :rfc:`2822`.)  If the input string has no timezone,
   the last element of the tuple returned is ``None``.  Note that indexes 6, 7, and
   8 of the result tuple are not usable.


.. function:: mktime_tz(tuple)

   Turn a 10-tuple as returned by :func:`parsedate_tz` into a UTC timestamp.  If
   the timezone item in the tuple is ``None``, assume local time.  Minor
   deficiency: this first interprets the first 8 elements as a local time and then
   compensates for the timezone difference; this may yield a slight error around
   daylight savings time switch dates.  Not enough to worry about for common use.


.. seealso::

   Module :mod:`email`
      Comprehensive email handling package; supersedes the :mod:`rfc822` module.

   Module :mod:`mailbox`
      Classes to read various mailbox formats produced  by end-user mail programs.

   Module :mod:`mimetools`
      Subclass of :class:`rfc822.Message` that handles MIME encoded messages.


.. _message-objects:

Message Objects
---------------

A :class:`Message` instance has the following methods:


.. method:: Message.rewindbody()

   Seek to the start of the message body.  This only works if the file object is
   seekable.


.. method:: Message.isheader(line)

   Returns a line's canonicalized fieldname (the dictionary key that will be used
   to index it) if the line is a legal :rfc:`2822` header; otherwise returns
   ``None`` (implying that parsing should stop here and the line be pushed back on
   the input stream).  It is sometimes useful to override this method in a
   subclass.


.. method:: Message.islast(line)

   Return true if the given line is a delimiter on which Message should stop.  The
   delimiter line is consumed, and the file object's read location positioned
   immediately after it.  By default this method just checks that the line is
   blank, but you can override it in a subclass.


.. method:: Message.iscomment(line)

   Return ``True`` if the given line should be ignored entirely, just skipped. By
   default this is a stub that always returns ``False``, but you can override it in
   a subclass.


.. method:: Message.getallmatchingheaders(name)

   Return a list of lines consisting of all headers matching *name*, if any.  Each
   physical line, whether it is a continuation line or not, is a separate list
   item.  Return the empty list if no header matches *name*.


.. method:: Message.getfirstmatchingheader(name)

   Return a list of lines comprising the first header matching *name*, and its
   continuation line(s), if any.  Return ``None`` if there is no header matching
   *name*.


.. method:: Message.getrawheader(name)

   Return a single string consisting of the text after the colon in the first
   header matching *name*.  This includes leading whitespace, the trailing
   linefeed, and internal linefeeds and whitespace if there any continuation
   line(s) were present.  Return ``None`` if there is no header matching *name*.


.. method:: Message.getheader(name[, default])

   Return a single string consisting of the last header matching *name*,
   but strip leading and trailing whitespace.
   Internal whitespace is not stripped.  The optional *default* argument can be
   used to specify a different default to be returned when there is no header
   matching *name*; it defaults to ``None``.
   This is the preferred way to get parsed headers.


.. method:: Message.get(name[, default])

   An alias for :meth:`getheader`, to make the interface more compatible  with
   regular dictionaries.


.. method:: Message.getaddr(name)

   Return a pair ``(full name, email address)`` parsed from the string returned by
   ``getheader(name)``.  If no header matching *name* exists, return ``(None,
   None)``; otherwise both the full name and the address are (possibly empty)
   strings.

   Example: If *m*'s first :mailheader:`From` header contains the string
   ``'jack@cwi.nl (Jack Jansen)'``, then ``m.getaddr('From')`` will yield the pair
   ``('Jack Jansen', 'jack@cwi.nl')``. If the header contained ``'Jack Jansen
   <jack@cwi.nl>'`` instead, it would yield the exact same result.


.. method:: Message.getaddrlist(name)

   This is similar to ``getaddr(list)``, but parses a header containing a list of
   email addresses (e.g. a :mailheader:`To` header) and returns a list of ``(full
   name, email address)`` pairs (even if there was only one address in the header).
   If there is no header matching *name*, return an empty list.

   If multiple headers exist that match the named header (e.g. if there are several
   :mailheader:`Cc` headers), all are parsed for addresses. Any continuation lines
   the named headers contain are also parsed.


.. method:: Message.getdate(name)

   Retrieve a header using :meth:`getheader` and parse it into a 9-tuple compatible
   with :func:`time.mktime`; note that fields 6, 7, and 8  are not usable.  If
   there is no header matching *name*, or it is unparsable, return ``None``.

   Date parsing appears to be a black art, and not all mailers adhere to the
   standard.  While it has been tested and found correct on a large collection of
   email from many sources, it is still possible that this function may
   occasionally yield an incorrect result.


.. method:: Message.getdate_tz(name)

   Retrieve a header using :meth:`getheader` and parse it into a 10-tuple; the
   first 9 elements will make a tuple compatible with :func:`time.mktime`, and the
   10th is a number giving the offset of the date's timezone from UTC.  Note that
   fields 6, 7, and 8  are not usable.  Similarly to :meth:`getdate`, if there is
   no header matching *name*, or it is unparsable, return ``None``.

:class:`Message` instances also support a limited mapping interface. In
particular: ``m[name]`` is like ``m.getheader(name)`` but raises :exc:`KeyError`
if there is no matching header; and ``len(m)``, ``m.get(name[, default])``,
``name in m``, ``m.keys()``, ``m.values()`` ``m.items()``, and
``m.setdefault(name[, default])`` act as expected, with the one difference
that :meth:`setdefault` uses an empty string as the default value.
:class:`Message` instances also support the mapping writable interface ``m[name]
= value`` and ``del m[name]``.  :class:`Message` objects do not support the
:meth:`clear`, :meth:`copy`, :meth:`popitem`, or :meth:`update` methods of the
mapping interface.  (Support for :meth:`get` and :meth:`setdefault` was only
added in Python 2.2.)

Finally, :class:`Message` instances have some public instance variables:


.. attribute:: Message.headers

   A list containing the entire set of header lines, in the order in which they
   were read (except that setitem calls may disturb this order). Each line contains
   a trailing newline.  The blank line terminating the headers is not contained in
   the list.


.. attribute:: Message.fp

   The file or file-like object passed at instantiation time.  This can be used to
   read the message content.


.. attribute:: Message.unixfrom

   The Unix ``From`` line, if the message had one, or an empty string.  This is
   needed to regenerate the message in some contexts, such as an ``mbox``\ -style
   mailbox file.


.. _addresslist-objects:

AddressList Objects
-------------------

An :class:`AddressList` instance has the following methods:


.. method:: AddressList.__len__()

   Return the number of addresses in the address list.


.. method:: AddressList.__str__()

   Return a canonicalized string representation of the address list. Addresses are
   rendered in "name" <host@domain> form, comma-separated.


.. method:: AddressList.__add__(alist)

   Return a new :class:`AddressList` instance that contains all addresses in both
   :class:`AddressList` operands, with duplicates removed (set union).


.. method:: AddressList.__iadd__(alist)

   In-place version of :meth:`__add__`; turns this :class:`AddressList` instance
   into the union of itself and the right-hand instance, *alist*.


.. method:: AddressList.__sub__(alist)

   Return a new :class:`AddressList` instance that contains every address in the
   left-hand :class:`AddressList` operand that is not present in the right-hand
   address operand (set difference).


.. method:: AddressList.__isub__(alist)

   In-place version of :meth:`__sub__`, removing addresses in this list which are
   also in *alist*.

Finally, :class:`AddressList` instances have one public instance variable:


.. attribute:: AddressList.addresslist

   A list of tuple string pairs, one per address.  In each member, the first is the
   canonicalized name part, the second is the actual route-address (``'@'``\
   -separated username-host.domain pair).

.. rubric:: Footnotes

.. [#] This module originally conformed to :rfc:`822`, hence the name.  Since then,
   :rfc:`2822` has been released as an update to :rfc:`822`.  This module should be
   considered :rfc:`2822`\ -conformant, especially in cases where the syntax or
   semantics have changed since :rfc:`822`.

PK
%�\=E�	�	)html/_sources/library/rlcompleter.rst.txtnu�[���:mod:`rlcompleter` --- Completion function for GNU readline
===========================================================

.. module:: rlcompleter
   :synopsis: Python identifier completion, suitable for the GNU readline library.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

**Source code:** :source:`Lib/rlcompleter.py`

--------------

The :mod:`rlcompleter` module defines a completion function suitable for the
:mod:`readline` module by completing valid Python identifiers and keywords.

When this module is imported on a Unix platform with the :mod:`readline` module
available, an instance of the :class:`Completer` class is automatically created
and its :meth:`complete` method is set as the :mod:`readline` completer.

Example::

   >>> import rlcompleter
   >>> import readline
   >>> readline.parse_and_bind("tab: complete")
   >>> readline. <TAB PRESSED>
   readline.__doc__          readline.get_line_buffer(  readline.read_init_file(
   readline.__file__         readline.insert_text(      readline.set_completer(
   readline.__name__         readline.parse_and_bind(
   >>> readline.

The :mod:`rlcompleter` module is designed for use with Python's interactive
mode.  A user can add the following lines to his or her initialization file
(identified by the :envvar:`PYTHONSTARTUP` environment variable) to get
automatic :kbd:`Tab` completion::

   try:
       import readline
   except ImportError:
       print "Module readline not available."
   else:
       import rlcompleter
       readline.parse_and_bind("tab: complete")

On platforms without :mod:`readline`, the :class:`Completer` class defined by
this module can still be used for custom purposes.


.. _completer-objects:

Completer Objects
-----------------

Completer objects have the following method:


.. method:: Completer.complete(text, state)

   Return the *state*\ th completion for *text*.

   If called for *text* that doesn't include a period character (``'.'``), it will
   complete from names currently defined in :mod:`__main__`, :mod:`__builtin__` and
   keywords (as defined by the :mod:`keyword` module).

   If called for a dotted name, it will try to evaluate anything without obvious
   side-effects (functions will not be evaluated, but it can generate calls to
   :meth:`__getattr__`) up to the last part, and find matches for the rest via the
   :func:`dir` function.  Any exception raised during the evaluation of the
   expression is caught, silenced and :const:`None` is returned.

PK
%�\kYmƎ�)html/_sources/library/robotparser.rst.txtnu�[���
:mod:`robotparser` ---  Parser for robots.txt
=============================================

.. module:: robotparser
   :synopsis: Loads a robots.txt file and answers questions about
              fetchability of other URLs.
.. sectionauthor:: Skip Montanaro <skip@pobox.com>


.. index::
   single: WWW
   single: World Wide Web
   single: URL
   single: robots.txt

.. note::
   The :mod:`robotparser` module has been renamed :mod:`urllib.robotparser` in
   Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.

This module provides a single class, :class:`RobotFileParser`, which answers
questions about whether or not a particular user agent can fetch a URL on the
Web site that published the :file:`robots.txt` file.  For more details on the
structure of :file:`robots.txt` files, see http://www.robotstxt.org/orig.html.


.. class:: RobotFileParser(url='')

   This class provides methods to read, parse and answer questions about the
   :file:`robots.txt` file at *url*.


   .. method:: set_url(url)

      Sets the URL referring to a :file:`robots.txt` file.


   .. method:: read()

      Reads the :file:`robots.txt` URL and feeds it to the parser.


   .. method:: parse(lines)

      Parses the lines argument.


   .. method:: can_fetch(useragent, url)

      Returns ``True`` if the *useragent* is allowed to fetch the *url*
      according to the rules contained in the parsed :file:`robots.txt`
      file.


   .. method:: mtime()

      Returns the time the ``robots.txt`` file was last fetched.  This is
      useful for long-running web spiders that need to check for new
      ``robots.txt`` files periodically.


   .. method:: modified()

      Sets the time the ``robots.txt`` file was last fetched to the current
      time.

The following example demonstrates basic use of the RobotFileParser class. ::

   >>> import robotparser
   >>> rp = robotparser.RobotFileParser()
   >>> rp.set_url("http://www.musi-cal.com/robots.txt")
   >>> rp.read()
   >>> rp.can_fetch("*", "http://www.musi-cal.com/cgi-bin/search?city=San+Francisco")
   False
   >>> rp.can_fetch("*", "http://www.musi-cal.com/")
   True

PK
%�\��#html/_sources/library/runpy.rst.txtnu�[���:mod:`runpy` --- Locating and executing Python modules
======================================================

.. module:: runpy
   :synopsis: Locate and run Python modules without importing them first.
.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>


.. versionadded:: 2.5

**Source code:** :source:`Lib/runpy.py`

--------------

The :mod:`runpy` module is used to locate and run Python modules without
importing them first. Its main use is to implement the :option:`-m` command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.

The :mod:`runpy` module provides two functions:


.. function:: run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)

   .. index::
      module: __main__

   Execute the code of the specified module and return the resulting module
   globals dictionary. The module's code is first located using the standard
   import mechanism (refer to :pep:`302` for details) and then executed in a
   fresh module namespace.

   If the supplied module name refers to a package rather than a normal
   module, then that package is imported and the ``__main__`` submodule within
   that package is then executed and the resulting module globals dictionary
   returned.

   The optional dictionary argument *init_globals* may be used to pre-populate
   the module's globals dictionary before the code is executed. The supplied
   dictionary will not be modified. If any of the special global variables
   below are defined in the supplied dictionary, those definitions are
   overridden by :func:`run_module`.

   The special global variables ``__name__``, ``__file__``, ``__loader__``
   and ``__package__`` are set in the globals dictionary before the module
   code is executed (Note that this is a minimal set of variables - other
   variables may be set implicitly as an interpreter implementation detail).

   ``__name__`` is set to *run_name* if this optional argument is not
   :const:`None`, to ``mod_name + '.__main__'`` if the named module is a
   package and to the *mod_name* argument otherwise.

   ``__file__`` is set to the name provided by the module loader. If the
   loader does not make filename information available, this variable is set
   to :const:`None`.

   ``__loader__`` is set to the :pep:`302` module loader used to retrieve the
   code for the module (This loader may be a wrapper around the standard
   import mechanism).

   ``__package__`` is set to *mod_name* if the named module is a package and
   to ``mod_name.rpartition('.')[0]`` otherwise.

   If the argument *alter_sys* is supplied and evaluates to :const:`True`,
   then ``sys.argv[0]`` is updated with the value of ``__file__`` and
   ``sys.modules[__name__]`` is updated with a temporary module object for the
   module being executed. Both ``sys.argv[0]`` and ``sys.modules[__name__]``
   are restored to their original values before the function returns.

   Note that this manipulation of :mod:`sys` is not thread-safe. Other threads
   may see the partially initialised module, as well as the altered list of
   arguments. It is recommended that the :mod:`sys` module be left alone when
   invoking this function from threaded code.

   .. seealso::
      The :option:`-m` option offering equivalent functionality from the
      command line.

   .. versionchanged:: 2.7
         Added ability to execute packages by looking for a ``__main__``
         submodule


.. function:: run_path(file_path, init_globals=None, run_name=None)

   .. index::
      module: __main__

   Execute the code at the named filesystem location and return the resulting
   module globals dictionary. As with a script name supplied to the CPython
   command line, the supplied path may refer to a Python source file, a
   compiled bytecode file or a valid sys.path entry containing a ``__main__``
   module (e.g. a zipfile containing a top-level ``__main__.py`` file).

   For a simple script, the specified code is simply executed in a fresh
   module namespace. For a valid sys.path entry (typically a zipfile or
   directory), the entry is first added to the beginning of ``sys.path``. The
   function then looks for and executes a :mod:`__main__` module using the
   updated path. Note that there is no special protection against invoking
   an existing :mod:`__main__` entry located elsewhere on ``sys.path`` if
   there is no such module at the specified location.

   The optional dictionary argument *init_globals* may be used to pre-populate
   the module's globals dictionary before the code is executed. The supplied
   dictionary will not be modified. If any of the special global variables
   below are defined in the supplied dictionary, those definitions are
   overridden by :func:`run_path`.

   The special global variables ``__name__``, ``__file__``, ``__loader__``
   and ``__package__`` are set in the globals dictionary before the module
   code is executed (Note that this is a minimal set of variables - other
   variables may be set implicitly as an interpreter implementation detail).

   ``__name__`` is set to *run_name* if this optional argument is not
   :const:`None` and to ``'<run_path>'`` otherwise.

   ``__file__`` is set to the name provided by the module loader. If the
   loader does not make filename information available, this variable is set
   to :const:`None`. For a simple script, this will be set to ``file_path``.

   ``__loader__`` is set to the :pep:`302` module loader used to retrieve the
   code for the module (This loader may be a wrapper around the standard
   import mechanism). For a simple script, this will be set to :const:`None`.

   ``__package__`` is set to ``__name__.rpartition('.')[0]``.

   A number of alterations are also made to the :mod:`sys` module. Firstly,
   ``sys.path`` may be altered as described above. ``sys.argv[0]`` is updated
   with the value of ``file_path`` and ``sys.modules[__name__]`` is updated
   with a temporary module object for the module being executed. All
   modifications to items in :mod:`sys` are reverted before the function
   returns.

   Note that, unlike :func:`run_module`, the alterations made to :mod:`sys`
   are not optional in this function as these adjustments are essential to
   allowing the execution of sys.path entries. As the thread-safety
   limitations still apply, use of this function in threaded code should be
   either serialised with the import lock or delegated to a separate process.

   .. seealso::
      :ref:`using-on-interface-options` for equivalent functionality on the
      command line (``python path/to/script``).

   .. versionadded:: 2.7

.. seealso::

   :pep:`338` -- Executing modules as scripts
      PEP written and implemented by Nick Coghlan.

   :pep:`366` -- Main module explicit relative imports
      PEP written and implemented by Nick Coghlan.

   :ref:`using-on-general` - CPython command line details
PK
%�\�#�$$#html/_sources/library/sched.rst.txtnu�[���:mod:`sched` --- Event scheduler
================================

.. module:: sched
   :synopsis: General purpose event scheduler.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

.. index:: single: event scheduling

**Source code:** :source:`Lib/sched.py`

--------------

The :mod:`sched` module defines a class which implements a general purpose event
scheduler:

.. class:: scheduler(timefunc, delayfunc)

   The :class:`scheduler` class defines a generic interface to scheduling events.
   It needs two functions to actually deal with the "outside world" --- *timefunc*
   should be callable without arguments, and return  a number (the "time", in any
   units whatsoever).  The *delayfunc* function should be callable with one
   argument, compatible with the output of *timefunc*, and should delay that many
   time units. *delayfunc* will also be called with the argument ``0`` after each
   event is run to allow other threads an opportunity to run in multi-threaded
   applications.

Example::

   >>> import sched, time
   >>> s = sched.scheduler(time.time, time.sleep)
   >>> def print_time(): print "From print_time", time.time()
   ...
   >>> def print_some_times():
   ...     print time.time()
   ...     s.enter(5, 1, print_time, ())
   ...     s.enter(10, 1, print_time, ())
   ...     s.run()
   ...     print time.time()
   ...
   >>> print_some_times()
   930343690.257
   From print_time 930343695.274
   From print_time 930343700.273
   930343700.276

In multi-threaded environments, the :class:`scheduler` class has limitations
with respect to thread-safety, inability to insert a new task before
the one currently pending in a running scheduler, and holding up the main
thread until the event queue is empty.  Instead, the preferred approach
is to use the :class:`threading.Timer` class instead.

Example::

    >>> import time
    >>> from threading import Timer
    >>> def print_time():
    ...     print "From print_time", time.time()
    ...
    >>> def print_some_times():
    ...     print time.time()
    ...     Timer(5, print_time, ()).start()
    ...     Timer(10, print_time, ()).start()
    ...     time.sleep(11)  # sleep while time-delay events execute
    ...     print time.time()
    ...
    >>> print_some_times()
    930343690.257
    From print_time 930343695.274
    From print_time 930343700.273
    930343701.301


.. _scheduler-objects:

Scheduler Objects
-----------------

:class:`scheduler` instances have the following methods and attributes:


.. method:: scheduler.enterabs(time, priority, action, argument)

   Schedule a new event. The *time* argument should be a numeric type compatible
   with the return value of the *timefunc* function passed  to the constructor.
   Events scheduled for the same *time* will be executed in the order of their
   *priority*. A lower number represents a higher priority.

   Executing the event means executing ``action(*argument)``.  *argument* must be a
   sequence holding the parameters for *action*.

   Return value is an event which may be used for later cancellation of the event
   (see :meth:`cancel`).


.. method:: scheduler.enter(delay, priority, action, argument)

   Schedule an event for *delay* more time units. Other than the relative time, the
   other arguments, the effect and the return value are the same as those for
   :meth:`enterabs`.


.. method:: scheduler.cancel(event)

   Remove the event from the queue. If *event* is not an event currently in the
   queue, this method will raise a :exc:`ValueError`.


.. method:: scheduler.empty()

   Return true if the event queue is empty.


.. method:: scheduler.run()

   Run all scheduled events. This function will wait  (using the :func:`delayfunc`
   function passed to the constructor) for the next event, then execute it and so
   on until there are no more scheduled events.

   Either *action* or *delayfunc* can raise an exception.  In either case, the
   scheduler will maintain a consistent state and propagate the exception.  If an
   exception is raised by *action*, the event will not be attempted in future calls
   to :meth:`run`.

   If a sequence of events takes longer to run than the time available before the
   next event, the scheduler will simply fall behind.  No events will be dropped;
   the calling code is responsible for canceling  events which are no longer
   pertinent.

.. attribute:: scheduler.queue

   Read-only attribute returning a list of upcoming events in the order they
   will be run.  Each event is shown as a :term:`named tuple` with the
   following fields:  time, priority, action, argument.

   .. versionadded:: 2.6
PK
%�\!��!cc*html/_sources/library/scrolledtext.rst.txtnu�[���:mod:`ScrolledText` --- Scrolled Text Widget
============================================

.. module:: ScrolledText
   :platform: Tk
   :synopsis: Text widget with a vertical scroll bar.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The :mod:`ScrolledText` module provides a class of the same name which
implements a basic text widget which has a vertical scroll bar configured to do
the "right thing."  Using the :class:`~ScrolledText.ScrolledText` class is a lot easier than
setting up a text widget and scroll bar directly.  The constructor is the same
as that of the :class:`Tkinter.Text` class.

.. note::

   :mod:`ScrolledText` has been renamed to :mod:`tkinter.scrolledtext` in Python
   3.  The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.

The text widget and scrollbar are packed together in a :class:`Frame`, and the
methods of the :class:`Grid` and :class:`Pack` geometry managers are acquired
from the :class:`Frame` object.  This allows the :class:`~ScrolledText.ScrolledText` widget to
be used directly to achieve most normal geometry management behavior.

Should more specific control be necessary, the following attributes are
available:


.. attribute:: ScrolledText.frame

   The frame which surrounds the text and scroll bar widgets.


.. attribute:: ScrolledText.vbar

   The scroll bar widget.
PK
%�\RU�P�P$html/_sources/library/select.rst.txtnu�[���
:mod:`select` --- Waiting for I/O completion
============================================

.. module:: select
   :synopsis: Wait for I/O completion on multiple streams.


This module provides access to the :c:func:`select` and :c:func:`poll` functions
available in most operating systems, :c:func:`epoll` available on Linux 2.5+ and
:c:func:`kqueue` available on most BSD.
Note that on Windows, it only works for sockets; on other operating systems,
it also works for other file types (in particular, on Unix, it works on pipes).
It cannot be used on regular files to determine whether a file has grown since
it was last read.

The module defines the following:


.. exception:: error

   The exception raised when an error occurs.  The accompanying value is a pair
   containing the numeric error code from :c:data:`errno` and the corresponding
   string, as would be printed by the C function :c:func:`perror`.


.. function:: epoll([sizehint=-1])

   (Only supported on Linux 2.5.44 and newer.)  Returns an edge polling object,
   which can be used as Edge or Level Triggered interface for I/O events; see
   section :ref:`epoll-objects` below for the methods supported by epolling
   objects.

   .. versionadded:: 2.6


.. function:: poll()

   (Not supported by all operating systems.)  Returns a polling object, which
   supports registering and unregistering file descriptors, and then polling them
   for I/O events; see section :ref:`poll-objects` below for the methods supported
   by polling objects.


.. function:: kqueue()

   (Only supported on BSD.)  Returns a kernel queue object; see section
   :ref:`kqueue-objects` below for the methods supported by kqueue objects.

   .. versionadded:: 2.6


.. function:: kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)

   (Only supported on BSD.)  Returns a kernel event object; see section
   :ref:`kevent-objects` below for the methods supported by kevent objects.

   .. versionadded:: 2.6


.. function:: select(rlist, wlist, xlist[, timeout])

   This is a straightforward interface to the Unix :c:func:`select` system call.
   The first three arguments are sequences of 'waitable objects': either
   integers representing file descriptors or objects with a parameterless method
   named :meth:`~io.IOBase.fileno` returning such an integer:

   * *rlist*: wait until ready for reading
   * *wlist*: wait until ready for writing
   * *xlist*: wait for an "exceptional condition" (see the manual page for what
     your system considers such a condition)

   Empty sequences are allowed, but acceptance of three empty sequences is
   platform-dependent. (It is known to work on Unix but not on Windows.)  The
   optional *timeout* argument specifies a time-out as a floating point number
   in seconds.  When the *timeout* argument is omitted the function blocks until
   at least one file descriptor is ready.  A time-out value of zero specifies a
   poll and never blocks.

   The return value is a triple of lists of objects that are ready: subsets of the
   first three arguments.  When the time-out is reached without a file descriptor
   becoming ready, three empty lists are returned.

   .. index::
      single: socket() (in module socket)
      single: popen() (in module os)

   Among the acceptable object types in the sequences are Python file objects (e.g.
   ``sys.stdin``, or objects returned by :func:`open` or :func:`os.popen`), socket
   objects returned by :func:`socket.socket`.  You may also define a :dfn:`wrapper`
   class yourself, as long as it has an appropriate :meth:`~io.IOBase.fileno`
   method (that really returns a file descriptor, not just a random integer).

   .. note::

      .. index:: single: WinSock

      File objects on Windows are not acceptable, but sockets are.  On Windows,
      the underlying :c:func:`select` function is provided by the WinSock
      library, and does not handle file descriptors that don't originate from
      WinSock.

.. attribute:: select.PIPE_BUF

   Files reported as ready for writing by :func:`select`, :func:`poll` or
   similar interfaces in this module are guaranteed to not block on a write
   of up to :const:`PIPE_BUF` bytes.
   This value is guaranteed by POSIX to be at least 512.  Availability: Unix.

   .. versionadded:: 2.7


.. _epoll-objects:

Edge and Level Trigger Polling (epoll) Objects
----------------------------------------------

   http://linux.die.net/man/4/epoll

   *eventmask*

   +-----------------------+-----------------------------------------------+
   | Constant              | Meaning                                       |
   +=======================+===============================================+
   | :const:`EPOLLIN`      | Available for read                            |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLOUT`     | Available for write                           |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLPRI`     | Urgent data for read                          |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLERR`     | Error condition happened on the assoc. fd     |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLHUP`     | Hang up happened on the assoc. fd             |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLET`      | Set Edge Trigger behavior, the default is     |
   |                       | Level Trigger behavior                        |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLONESHOT` | Set one-shot behavior. After one event is     |
   |                       | pulled out, the fd is internally disabled     |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLRDNORM`  | Equivalent to :const:`EPOLLIN`                |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLRDBAND`  | Priority data band can be read.               |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLWRNORM`  | Equivalent to :const:`EPOLLOUT`               |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLWRBAND`  | Priority data may be written.                 |
   +-----------------------+-----------------------------------------------+
   | :const:`EPOLLMSG`     | Ignored.                                      |
   +-----------------------+-----------------------------------------------+


.. method:: epoll.close()

   Close the control file descriptor of the epoll object.


.. method:: epoll.fileno()

   Return the file descriptor number of the control fd.


.. method:: epoll.fromfd(fd)

   Create an epoll object from a given file descriptor.


.. method:: epoll.register(fd[, eventmask])

   Register a fd descriptor with the epoll object.

   .. note::

     Registering a file descriptor that's already registered raises an
     IOError -- contrary to :ref:`poll-objects`'s register.


.. method:: epoll.modify(fd, eventmask)

   Modify a register file descriptor.


.. method:: epoll.unregister(fd)

   Remove a registered file descriptor from the epoll object.


.. method:: epoll.poll([timeout=-1[, maxevents=-1]])

   Wait for events. timeout in seconds (float)


.. _poll-objects:

Polling Objects
---------------

The :c:func:`poll` system call, supported on most Unix systems, provides better
scalability for network servers that service many, many clients at the same
time. :c:func:`poll` scales better because the system call only requires listing
the file descriptors of interest, while :c:func:`select` builds a bitmap, turns
on bits for the fds of interest, and then afterward the whole bitmap has to be
linearly scanned again. :c:func:`select` is O(highest file descriptor), while
:c:func:`poll` is O(number of file descriptors).


.. method:: poll.register(fd[, eventmask])

   Register a file descriptor with the polling object.  Future calls to the
   :meth:`poll` method will then check whether the file descriptor has any
   pending I/O events.  *fd* can be either an integer, or an object with a
   :meth:`~io.IOBase.fileno` method that returns an integer.  File objects
   implement :meth:`!fileno`, so they can also be used as the argument.

   *eventmask* is an optional bitmask describing the type of events you want to
   check for, and can be a combination of the constants :const:`POLLIN`,
   :const:`POLLPRI`, and :const:`POLLOUT`, described in the table below.  If not
   specified, the default value used will check for all 3 types of events.

   +-------------------+------------------------------------------+
   | Constant          | Meaning                                  |
   +===================+==========================================+
   | :const:`POLLIN`   | There is data to read                    |
   +-------------------+------------------------------------------+
   | :const:`POLLPRI`  | There is urgent data to read             |
   +-------------------+------------------------------------------+
   | :const:`POLLOUT`  | Ready for output: writing will not block |
   +-------------------+------------------------------------------+
   | :const:`POLLERR`  | Error condition of some sort             |
   +-------------------+------------------------------------------+
   | :const:`POLLHUP`  | Hung up                                  |
   +-------------------+------------------------------------------+
   | :const:`POLLNVAL` | Invalid request: descriptor not open     |
   +-------------------+------------------------------------------+

   Registering a file descriptor that's already registered is not an error, and has
   the same effect as registering the descriptor exactly once.


.. method:: poll.modify(fd, eventmask)

   Modifies an already registered fd. This has the same effect as
   ``register(fd, eventmask)``.  Attempting to modify a file descriptor
   that was never registered causes an :exc:`IOError` exception with errno
   :const:`ENOENT` to be raised.

   .. versionadded:: 2.6


.. method:: poll.unregister(fd)

   Remove a file descriptor being tracked by a polling object.  Just like the
   :meth:`register` method, *fd* can be an integer or an object with a
   :meth:`~io.IOBase.fileno` method that returns an integer.

   Attempting to remove a file descriptor that was never registered causes a
   :exc:`KeyError` exception to be raised.


.. method:: poll.poll([timeout])

   Polls the set of registered file descriptors, and returns a possibly-empty list
   containing ``(fd, event)`` 2-tuples for the descriptors that have events or
   errors to report. *fd* is the file descriptor, and *event* is a bitmask with
   bits set for the reported events for that descriptor --- :const:`POLLIN` for
   waiting input, :const:`POLLOUT` to indicate that the descriptor can be written
   to, and so forth. An empty list indicates that the call timed out and no file
   descriptors had any events to report. If *timeout* is given, it specifies the
   length of time in milliseconds which the system will wait for events before
   returning. If *timeout* is omitted, negative, or :const:`None`, the call will
   block until there is an event for this poll object.


.. _kqueue-objects:

Kqueue Objects
--------------

.. method:: kqueue.close()

   Close the control file descriptor of the kqueue object.


.. method:: kqueue.fileno()

   Return the file descriptor number of the control fd.


.. method:: kqueue.fromfd(fd)

   Create a kqueue object from a given file descriptor.


.. method:: kqueue.control(changelist, max_events[, timeout=None]) -> eventlist

   Low level interface to kevent

   - changelist must be an iterable of kevent object or ``None``
   - max_events must be 0 or a positive integer
   - timeout in seconds (floats possible)


.. _kevent-objects:

Kevent Objects
--------------

https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2

.. attribute:: kevent.ident

   Value used to identify the event. The interpretation depends on the filter
   but it's usually the file descriptor. In the constructor ident can either
   be an int or an object with a fileno() function. kevent stores the integer
   internally.

.. attribute:: kevent.filter

   Name of the kernel filter.

   +---------------------------+---------------------------------------------+
   | Constant                  | Meaning                                     |
   +===========================+=============================================+
   | :const:`KQ_FILTER_READ`   | Takes a descriptor and returns whenever     |
   |                           | there is data available to read             |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_WRITE`  | Takes a descriptor and returns whenever     |
   |                           | there is data available to write            |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_AIO`    | AIO requests                                |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_VNODE`  | Returns when one or more of the requested   |
   |                           | events watched in *fflag* occurs            |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_PROC`   | Watch for events on a process id            |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_NETDEV` | Watch for events on a network device        |
   |                           | [not available on Mac OS X]                 |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_SIGNAL` | Returns whenever the watched signal is      |
   |                           | delivered to the process                    |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_FILTER_TIMER`  | Establishes an arbitrary timer              |
   +---------------------------+---------------------------------------------+

.. attribute:: kevent.flags

   Filter action.

   +---------------------------+---------------------------------------------+
   | Constant                  | Meaning                                     |
   +===========================+=============================================+
   | :const:`KQ_EV_ADD`        | Adds or modifies an event                   |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_DELETE`     | Removes an event from the queue             |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_ENABLE`     | Permitscontrol() to returns the event       |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_DISABLE`    | Disablesevent                               |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_ONESHOT`    | Removes event after first occurrence        |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_CLEAR`      | Reset the state after an event is retrieved |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_SYSFLAGS`   | internal event                              |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_FLAG1`      | internal event                              |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_EOF`        | Filter specific EOF condition               |
   +---------------------------+---------------------------------------------+
   | :const:`KQ_EV_ERROR`      | See return values                           |
   +---------------------------+---------------------------------------------+


.. attribute:: kevent.fflags

   Filter specific flags.

   :const:`KQ_FILTER_READ` and  :const:`KQ_FILTER_WRITE` filter flags:

   +----------------------------+--------------------------------------------+
   | Constant                   | Meaning                                    |
   +============================+============================================+
   | :const:`KQ_NOTE_LOWAT`     | low water mark of a socket buffer          |
   +----------------------------+--------------------------------------------+

   :const:`KQ_FILTER_VNODE` filter flags:

   +----------------------------+--------------------------------------------+
   | Constant                   | Meaning                                    |
   +============================+============================================+
   | :const:`KQ_NOTE_DELETE`    | *unlink()* was called                      |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_WRITE`     | a write occurred                           |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_EXTEND`    | the file was extended                      |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_ATTRIB`    | an attribute was changed                   |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_LINK`      | the link count has changed                 |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_RENAME`    | the file was renamed                       |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_REVOKE`    | access to the file was revoked             |
   +----------------------------+--------------------------------------------+

   :const:`KQ_FILTER_PROC` filter flags:

   +----------------------------+--------------------------------------------+
   | Constant                   | Meaning                                    |
   +============================+============================================+
   | :const:`KQ_NOTE_EXIT`      | the process has exited                     |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_FORK`      | the process has called *fork()*            |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_EXEC`      | the process has executed a new process     |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_PCTRLMASK` | internal filter flag                       |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_PDATAMASK` | internal filter flag                       |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_TRACK`     | follow a process across *fork()*           |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_CHILD`     | returned on the child process for          |
   |                            | *NOTE_TRACK*                               |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_TRACKERR`  | unable to attach to a child                |
   +----------------------------+--------------------------------------------+

   :const:`KQ_FILTER_NETDEV` filter flags (not available on Mac OS X):

   +----------------------------+--------------------------------------------+
   | Constant                   | Meaning                                    |
   +============================+============================================+
   | :const:`KQ_NOTE_LINKUP`    | link is up                                 |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_LINKDOWN`  | link is down                               |
   +----------------------------+--------------------------------------------+
   | :const:`KQ_NOTE_LINKINV`   | link state is invalid                      |
   +----------------------------+--------------------------------------------+


.. attribute:: kevent.data

   Filter specific data.


.. attribute:: kevent.udata

   User defined value.
PK
%�\�	�}:}:"html/_sources/library/sets.rst.txtnu�[���
:mod:`sets` --- Unordered collections of unique elements
========================================================

.. module:: sets
   :synopsis: Implementation of sets of unique elements.
   :deprecated:
.. moduleauthor:: Greg V. Wilson <gvwilson@nevex.com>
.. moduleauthor:: Alex Martelli <aleax@aleax.it>
.. moduleauthor:: Guido van Rossum <guido@python.org>
.. sectionauthor:: Raymond D. Hettinger <python@rcn.com>


.. versionadded:: 2.3

.. deprecated:: 2.6
   The built-in :class:`set`/:class:`frozenset` types replace this module.

The :mod:`sets` module provides classes for constructing and manipulating
unordered collections of unique elements.  Common uses include membership
testing, removing duplicates from a sequence, and computing standard math
operations on sets such as intersection, union, difference, and symmetric
difference.

Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
set``.  Being an unordered collection, sets do not record element position or
order of insertion.  Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.

Most set applications use the :class:`Set` class which provides every set method
except for :meth:`__hash__`. For advanced applications requiring a hash method,
the :class:`ImmutableSet` class adds a :meth:`__hash__` method but omits methods
which alter the contents of the set. Both :class:`Set` and :class:`ImmutableSet`
derive from :class:`BaseSet`, an abstract class useful for determining whether
something is a set: ``isinstance(obj, BaseSet)``.

The set classes are implemented using dictionaries.  Accordingly, the
requirements for set elements are the same as those for dictionary keys; namely,
that the element defines both :meth:`__eq__` and :meth:`__hash__`. As a result,
sets cannot contain mutable elements such as lists or dictionaries. However,
they can contain immutable collections such as tuples or instances of
:class:`ImmutableSet`.  For convenience in implementing sets of sets, inner sets
are automatically converted to immutable form, for example,
``Set([Set(['dog'])])`` is transformed to ``Set([ImmutableSet(['dog'])])``.


.. class:: Set([iterable])

   Constructs a new empty :class:`Set` object.  If the optional *iterable*
   parameter is supplied, updates the set with elements obtained from iteration.
   All of the elements in *iterable* should be immutable or be transformable to an
   immutable using the protocol described in section :ref:`immutable-transforms`.


.. class:: ImmutableSet([iterable])

   Constructs a new empty :class:`ImmutableSet` object.  If the optional *iterable*
   parameter is supplied, updates the set with elements obtained from iteration.
   All of the elements in *iterable* should be immutable or be transformable to an
   immutable using the protocol described in section :ref:`immutable-transforms`.

   Because :class:`ImmutableSet` objects provide a :meth:`__hash__` method, they
   can be used as set elements or as dictionary keys.  :class:`ImmutableSet`
   objects do not have methods for adding or removing elements, so all of the
   elements must be known when the constructor is called.


.. _set-objects:

Set Objects
-----------

Instances of :class:`Set` and :class:`ImmutableSet` both provide the following
operations:

+-------------------------------+------------+---------------------------------+
| Operation                     | Equivalent | Result                          |
+===============================+============+=================================+
| ``len(s)``                    |            | number of elements in set *s*   |
|                               |            | (cardinality)                   |
+-------------------------------+------------+---------------------------------+
| ``x in s``                    |            | test *x* for membership in *s*  |
+-------------------------------+------------+---------------------------------+
| ``x not in s``                |            | test *x* for non-membership in  |
|                               |            | *s*                             |
+-------------------------------+------------+---------------------------------+
| ``s.issubset(t)``             | ``s <= t`` | test whether every element in   |
|                               |            | *s* is in *t*                   |
+-------------------------------+------------+---------------------------------+
| ``s.issuperset(t)``           | ``s >= t`` | test whether every element in   |
|                               |            | *t* is in *s*                   |
+-------------------------------+------------+---------------------------------+
| ``s.union(t)``                | ``s | t``  | new set with elements from both |
|                               |            | *s* and *t*                     |
+-------------------------------+------------+---------------------------------+
| ``s.intersection(t)``         | ``s & t``  | new set with elements common to |
|                               |            | *s* and *t*                     |
+-------------------------------+------------+---------------------------------+
| ``s.difference(t)``           | ``s - t``  | new set with elements in *s*    |
|                               |            | but not in *t*                  |
+-------------------------------+------------+---------------------------------+
| ``s.symmetric_difference(t)`` | ``s ^ t``  | new set with elements in either |
|                               |            | *s* or *t* but not both         |
+-------------------------------+------------+---------------------------------+
| ``s.copy()``                  |            | new set with a shallow copy of  |
|                               |            | *s*                             |
+-------------------------------+------------+---------------------------------+

Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
:meth:`difference`, and :meth:`symmetric_difference` will accept any iterable as
an argument. In contrast, their operator based counterparts require their
arguments to be sets.  This precludes error-prone constructions like
``Set('abc') & 'cbs'`` in favor of the more readable
``Set('abc').intersection('cbs')``.

.. versionchanged:: 2.3.1
   Formerly all arguments were required to be sets.

In addition, both :class:`Set` and :class:`ImmutableSet` support set to set
comparisons.  Two sets are equal if and only if every element of each set is
contained in the other (each is a subset of the other). A set is less than
another set if and only if the first set is a proper subset of the second set
(is a subset, but is not equal). A set is greater than another set if and only
if the first set is a proper superset of the second set (is a superset, but is
not equal).

The subset and equality comparisons do not generalize to a complete ordering
function.  For example, any two disjoint sets are not equal and are not subsets
of each other, so *all* of the following return ``False``:  ``a<b``, ``a==b``,
or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__` method.

Since sets only define partial ordering (subset relationships), the output of
the :meth:`list.sort` method is undefined for lists of sets.

The following table lists operations available in :class:`ImmutableSet` but not
found in :class:`Set`:

+-------------+------------------------------+
| Operation   | Result                       |
+=============+==============================+
| ``hash(s)`` | returns a hash value for *s* |
+-------------+------------------------------+

The following table lists operations available in :class:`Set` but not found in
:class:`ImmutableSet`:

+--------------------------------------+-------------+---------------------------------+
| Operation                            | Equivalent  | Result                          |
+======================================+=============+=================================+
| ``s.update(t)``                      | *s* \|= *t* | return set *s* with elements    |
|                                      |             | added from *t*                  |
+--------------------------------------+-------------+---------------------------------+
| ``s.intersection_update(t)``         | *s* &= *t*  | return set *s* keeping only     |
|                                      |             | elements also found in *t*      |
+--------------------------------------+-------------+---------------------------------+
| ``s.difference_update(t)``           | *s* -= *t*  | return set *s* after removing   |
|                                      |             | elements found in *t*           |
+--------------------------------------+-------------+---------------------------------+
| ``s.symmetric_difference_update(t)`` | *s* ^= *t*  | return set *s* with elements    |
|                                      |             | from *s* or *t* but not both    |
+--------------------------------------+-------------+---------------------------------+
| ``s.add(x)``                         |             | add element *x* to set *s*      |
+--------------------------------------+-------------+---------------------------------+
| ``s.remove(x)``                      |             | remove *x* from set *s*; raises |
|                                      |             | :exc:`KeyError` if not present  |
+--------------------------------------+-------------+---------------------------------+
| ``s.discard(x)``                     |             | removes *x* from set *s* if     |
|                                      |             | present                         |
+--------------------------------------+-------------+---------------------------------+
| ``s.pop()``                          |             | remove and return an arbitrary  |
|                                      |             | element from *s*; raises        |
|                                      |             | :exc:`KeyError` if empty        |
+--------------------------------------+-------------+---------------------------------+
| ``s.clear()``                        |             | remove all elements from set    |
|                                      |             | *s*                             |
+--------------------------------------+-------------+---------------------------------+

Note, the non-operator versions of :meth:`update`, :meth:`intersection_update`,
:meth:`difference_update`, and :meth:`symmetric_difference_update` will accept
any iterable as an argument.

.. versionchanged:: 2.3.1
   Formerly all arguments were required to be sets.

Also note, the module also includes a :meth:`union_update` method which is an
alias for :meth:`update`.  The method is included for backwards compatibility.
Programmers should prefer the :meth:`update` method because it is supported by
the built-in :class:`set()` and :class:`frozenset()` types.


.. _set-example:

Example
-------

   >>> from sets import Set
   >>> engineers = Set(['John', 'Jane', 'Jack', 'Janice'])
   >>> programmers = Set(['Jack', 'Sam', 'Susan', 'Janice'])
   >>> managers = Set(['Jane', 'Jack', 'Susan', 'Zack'])
   >>> employees = engineers | programmers | managers           # union
   >>> engineering_management = engineers & managers            # intersection
   >>> fulltime_management = managers - engineers - programmers # difference
   >>> engineers.add('Marvin')                                  # add element
   >>> print engineers # doctest: +SKIP
   Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
   >>> employees.issuperset(engineers)     # superset test
   False
   >>> employees.update(engineers)         # update from another set
   >>> employees.issuperset(engineers)
   True
   >>> for group in [engineers, programmers, managers, employees]: # doctest: +SKIP
   ...     group.discard('Susan')          # unconditionally remove element
   ...     print group
   ...
   Set(['Jane', 'Marvin', 'Janice', 'John', 'Jack'])
   Set(['Janice', 'Jack', 'Sam'])
   Set(['Jane', 'Zack', 'Jack'])
   Set(['Jack', 'Sam', 'Jane', 'Marvin', 'Janice', 'John', 'Zack'])


.. _immutable-transforms:

Protocol for automatic conversion to immutable
----------------------------------------------

Sets can only contain immutable elements.  For convenience, mutable :class:`Set`
objects are automatically copied to an :class:`ImmutableSet` before being added
as a set element.

The mechanism is to always add a :term:`hashable` element, or if it is not
hashable, the element is checked to see if it has an :meth:`__as_immutable__`
method which returns an immutable equivalent.

Since :class:`Set` objects have a :meth:`__as_immutable__` method returning an
instance of :class:`ImmutableSet`, it is possible to construct sets of sets.

A similar mechanism is needed by the :meth:`__contains__` and :meth:`remove`
methods which need to hash an element to check for membership in a set.  Those
methods check an element for hashability and, if not, check for a
:meth:`__as_temporarily_immutable__` method which returns the element wrapped by
a class that provides temporary methods for :meth:`__hash__`, :meth:`__eq__`,
and :meth:`__ne__`.

The alternate mechanism spares the need to build a separate copy of the original
mutable object.

:class:`Set` objects implement the :meth:`__as_temporarily_immutable__` method
which returns the :class:`Set` object wrapped by a new class
:class:`_TemporarilyImmutableSet`.

The two mechanisms for adding hashability are normally invisible to the user;
however, a conflict can arise in a multi-threaded environment where one thread
is updating a set while another has temporarily wrapped it in
:class:`_TemporarilyImmutableSet`.  In other words, sets of mutable sets are not
thread-safe.


.. _comparison-to-builtin-set:

Comparison to the built-in :class:`set` types
---------------------------------------------

The built-in :class:`set` and :class:`frozenset` types were designed based on
lessons learned from the :mod:`sets` module.  The key differences are:

* :class:`Set` and :class:`ImmutableSet` were renamed to :class:`set` and
  :class:`frozenset`.

* There is no equivalent to :class:`BaseSet`.  Instead, use ``isinstance(x,
  (set, frozenset))``.

* The hash algorithm for the built-ins performs significantly better (fewer
  collisions) for most datasets.

* The built-in versions have more space efficient pickles.

* The built-in versions do not have a :meth:`union_update` method. Instead, use
  the :meth:`update` method which is equivalent.

* The built-in versions do not have a ``_repr(sorted=True)`` method.
  Instead, use the built-in :func:`repr` and :func:`sorted` functions:
  ``repr(sorted(s))``.

* The built-in version does not have a protocol for automatic conversion to
  immutable.  Many found this feature to be confusing and no one in the community
  reported having found real uses for it.

PK
%�\��	BB!html/_sources/library/sgi.rst.txtnu�[���
.. _sgi:

**************************
SGI IRIX Specific Services
**************************

The modules described in this chapter provide interfaces to features that are
unique to SGI's IRIX operating system (versions 4 and 5).


.. toctree::

   al.rst
   cd.rst
   fl.rst
   fm.rst
   gl.rst
   imgfile.rst
   jpeg.rst
PK
%�\g�Ko�)�)%html/_sources/library/sgmllib.rst.txtnu�[���:mod:`sgmllib` --- Simple SGML parser
=====================================

.. module:: sgmllib
   :synopsis: Only as much of an SGML parser as needed to parse HTML.
   :deprecated:

.. deprecated:: 2.6
    The :mod:`sgmllib` module has been removed in Python 3.

.. index:: single: SGML

This module defines a class :class:`SGMLParser` which serves as the basis for
parsing text files formatted in SGML (Standard Generalized Mark-up Language).
In fact, it does not provide a full SGML parser --- it only parses SGML insofar
as it is used by HTML, and the module only exists as a base for the
:mod:`htmllib` module.  Another HTML parser which supports XHTML and offers a
somewhat different interface is available in the :mod:`HTMLParser` module.


.. class:: SGMLParser()

   The :class:`SGMLParser` class is instantiated without arguments. The parser is
   hardcoded to recognize the following constructs:

   * Opening and closing tags of the form ``<tag attr="value" ...>`` and
     ``</tag>``, respectively.

   * Numeric character references of the form ``&#name;``.

   * Entity references of the form ``&name;``.

   * SGML comments of the form ``<!--text-->``.  Note that spaces, tabs, and
     newlines are allowed between the trailing ``>`` and the immediately preceding
     ``--``.

A single exception is defined as well:


.. exception:: SGMLParseError

   Exception raised by the :class:`SGMLParser` class when it encounters an error
   while parsing.

   .. versionadded:: 2.1

:class:`SGMLParser` instances have the following methods:


.. method:: SGMLParser.reset()

   Reset the instance.  Loses all unprocessed data.  This is called implicitly at
   instantiation time.


.. method:: SGMLParser.setnomoretags()

   Stop processing tags.  Treat all following input as literal input (CDATA).
   (This is only provided so the HTML tag ``<PLAINTEXT>`` can be implemented.)


.. method:: SGMLParser.setliteral()

   Enter literal mode (CDATA mode).


.. method:: SGMLParser.feed(data)

   Feed some text to the parser.  It is processed insofar as it consists of
   complete elements; incomplete data is buffered until more data is fed or
   :meth:`close` is called.


.. method:: SGMLParser.close()

   Force processing of all buffered data as if it were followed by an end-of-file
   mark.  This method may be redefined by a derived class to define additional
   processing at the end of the input, but the redefined version should always call
   :meth:`close`.


.. method:: SGMLParser.get_starttag_text()

   Return the text of the most recently opened start tag.  This should not normally
   be needed for structured processing, but may be useful in dealing with HTML "as
   deployed" or for re-generating input with minimal changes (whitespace between
   attributes can be preserved, etc.).


.. method:: SGMLParser.handle_starttag(tag, method, attributes)

   This method is called to handle start tags for which either a :meth:`start_tag`
   or :meth:`do_tag` method has been defined.  The *tag* argument is the name of
   the tag converted to lower case, and the *method* argument is the bound method
   which should be used to support semantic interpretation of the start tag. The
   *attributes* argument is a list of ``(name, value)`` pairs containing the
   attributes found inside the tag's ``<>`` brackets.

   The *name* has been translated to lower case. Double quotes and backslashes in
   the *value* have been interpreted, as well as known character references and
   known entity references terminated by a semicolon (normally, entity references
   can be terminated by any non-alphanumerical character, but this would break the
   very common case of ``<A HREF="url?spam=1&eggs=2">`` when ``eggs`` is a valid
   entity name).

   For instance, for the tag ``<A HREF="http://www.cwi.nl/">``, this method would
   be called as ``unknown_starttag('a', [('href', 'http://www.cwi.nl/')])``.  The
   base implementation simply calls *method* with *attributes* as the only
   argument.

   .. versionadded:: 2.5
      Handling of entity and character references within attribute values.


.. method:: SGMLParser.handle_endtag(tag, method)

   This method is called to handle endtags for which an :meth:`end_tag` method has
   been defined.  The *tag* argument is the name of the tag converted to lower
   case, and the *method* argument is the bound method which should be used to
   support semantic interpretation of the end tag.  If no :meth:`end_tag` method is
   defined for the closing element, this handler is not called.  The base
   implementation simply calls *method*.


.. method:: SGMLParser.handle_data(data)

   This method is called to process arbitrary data.  It is intended to be
   overridden by a derived class; the base class implementation does nothing.


.. method:: SGMLParser.handle_charref(ref)

   This method is called to process a character reference of the form ``&#ref;``.
   The base implementation uses :meth:`convert_charref` to convert the reference to
   a string.  If that method returns a string, it is passed to :meth:`handle_data`,
   otherwise ``unknown_charref(ref)`` is called to handle the error.

   .. versionchanged:: 2.5
      Use :meth:`convert_charref` instead of hard-coding the conversion.


.. method:: SGMLParser.convert_charref(ref)

   Convert a character reference to a string, or ``None``.  *ref* is the reference
   passed in as a string.  In the base implementation, *ref* must be a decimal
   number in the range 0--255.  It converts the code point found using the
   :meth:`convert_codepoint` method. If *ref* is invalid or out of range, this
   method returns ``None``.  This method is called by the default
   :meth:`handle_charref` implementation and by the attribute value parser.

   .. versionadded:: 2.5


.. method:: SGMLParser.convert_codepoint(codepoint)

   Convert a code point to a :class:`str` value.  Encodings can be handled here if
   appropriate, though the rest of :mod:`sgmllib` is oblivious on this matter.

   .. versionadded:: 2.5


.. method:: SGMLParser.handle_entityref(ref)

   This method is called to process a general entity reference of the form
   ``&ref;`` where *ref* is a general entity reference.  It converts *ref* by
   passing it to :meth:`convert_entityref`.  If a translation is returned, it calls
   the method :meth:`handle_data` with the translation; otherwise, it calls the
   method ``unknown_entityref(ref)``. The default :attr:`entitydefs` defines
   translations for ``&amp;``, ``&apos;``, ``&gt;``, ``&lt;``, and ``&quot;``.

   .. versionchanged:: 2.5
      Use :meth:`convert_entityref` instead of hard-coding the conversion.


.. method:: SGMLParser.convert_entityref(ref)

   Convert a named entity reference to a :class:`str` value, or ``None``.  The
   resulting value will not be parsed.  *ref* will be only the name of the entity.
   The default implementation looks for *ref* in the instance (or class) variable
   :attr:`entitydefs` which should be a mapping from entity names to corresponding
   translations.  If no translation is available for *ref*, this method returns
   ``None``.  This method is called by the default :meth:`handle_entityref`
   implementation and by the attribute value parser.

   .. versionadded:: 2.5


.. method:: SGMLParser.handle_comment(comment)

   This method is called when a comment is encountered.  The *comment* argument is
   a string containing the text between the ``<!--`` and ``-->`` delimiters, but
   not the delimiters themselves.  For example, the comment ``<!--text-->`` will
   cause this method to be called with the argument ``'text'``.  The default method
   does nothing.


.. method:: SGMLParser.handle_decl(data)

   Method called when an SGML declaration is read by the parser.  In practice, the
   ``DOCTYPE`` declaration is the only thing observed in HTML, but the parser does
   not discriminate among different (or broken) declarations.  Internal subsets in
   a ``DOCTYPE`` declaration are not supported.  The *data* parameter will be the
   entire contents of the declaration inside the ``<!``...\ ``>`` markup.  The
   default implementation does nothing.


.. method:: SGMLParser.report_unbalanced(tag)

   This method is called when an end tag is found which does not correspond to any
   open element.


.. method:: SGMLParser.unknown_starttag(tag, attributes)

   This method is called to process an unknown start tag.  It is intended to be
   overridden by a derived class; the base class implementation does nothing.


.. method:: SGMLParser.unknown_endtag(tag)

   This method is called to process an unknown end tag.  It is intended to be
   overridden by a derived class; the base class implementation does nothing.


.. method:: SGMLParser.unknown_charref(ref)

   This method is called to process unresolvable numeric character references.
   Refer to :meth:`handle_charref` to determine what is handled by default.  It is
   intended to be overridden by a derived class; the base class implementation does
   nothing.


.. method:: SGMLParser.unknown_entityref(ref)

   This method is called to process an unknown entity reference.  It is intended to
   be overridden by a derived class; the base class implementation does nothing.

Apart from overriding or extending the methods listed above, derived classes may
also define methods of the following form to define processing of specific tags.
Tag names in the input stream are case independent; the *tag* occurring in
method names must be in lower case:


.. method:: SGMLParser.start_tag(attributes)
   :noindex:

   This method is called to process an opening tag *tag*.  It has preference over
   :meth:`do_tag`.  The *attributes* argument has the same meaning as described for
   :meth:`handle_starttag` above.


.. method:: SGMLParser.do_tag(attributes)
   :noindex:

   This method is called to process an opening tag *tag*  for which no
   :meth:`start_tag` method is defined.   The *attributes* argument has the same
   meaning as described for :meth:`handle_starttag` above.


.. method:: SGMLParser.end_tag()
   :noindex:

   This method is called to process a closing tag *tag*.

Note that the parser maintains a stack of open elements for which no end tag has
been found yet.  Only tags processed by :meth:`start_tag` are pushed on this
stack.  Definition of an :meth:`end_tag` method is optional for these tags.  For
tags processed by :meth:`do_tag` or by :meth:`unknown_tag`, no :meth:`end_tag`
method must be defined; if defined, it will not be used.  If both
:meth:`start_tag` and :meth:`do_tag` methods exist for a tag, the
:meth:`start_tag` method takes precedence.

PK
%�\�M��
�
!html/_sources/library/sha.rst.txtnu�[���
:mod:`sha` --- SHA-1 message digest algorithm
=============================================

.. module:: sha
   :synopsis: NIST's secure hash algorithm, SHA.
   :deprecated:
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. deprecated:: 2.5
   Use the :mod:`hashlib` module instead.

.. index::
   single: NIST
   single: Secure Hash Algorithm
   single: checksum; SHA

This module implements the interface to NIST's secure hash  algorithm, known as
SHA-1.  SHA-1 is an improved version of the original SHA hash algorithm.  It is
used in the same way as the :mod:`md5` module: use :func:`new` to create an sha
object, then feed this object with arbitrary strings using the :meth:`update`
method, and at any point you can ask it for the :dfn:`digest` of the
concatenation of the strings fed to it so far.  SHA-1 digests are 160 bits
instead of MD5's 128 bits.


.. function:: new([string])

   Return a new sha object.  If *string* is present, the method call
   ``update(string)`` is made.

The following values are provided as constants in the module and as attributes
of the sha objects returned by :func:`new`:


.. data:: blocksize

   Size of the blocks fed into the hash function; this is always ``1``.  This size
   is used to allow an arbitrary string to be hashed.


.. data:: digest_size

   The size of the resulting digest in bytes.  This is always ``20``.

An sha object has the same methods as md5 objects:


.. method:: sha.update(arg)

   Update the sha object with the string *arg*.  Repeated calls are equivalent to a
   single call with the concatenation of all the arguments: ``m.update(a);
   m.update(b)`` is equivalent to ``m.update(a+b)``.


.. method:: sha.digest()

   Return the digest of the strings passed to the :meth:`update` method so far.
   This is a 20-byte string which may contain non-ASCII characters, including null
   bytes.


.. method:: sha.hexdigest()

   Like :meth:`digest` except the digest is returned as a string of length 40,
   containing only hexadecimal digits.  This may  be used to exchange the value
   safely in email or other non-binary environments.


.. method:: sha.copy()

   Return a copy ("clone") of the sha object.  This can be used to efficiently
   compute the digests of strings that share a common initial substring.


.. seealso::

   `Secure Hash Standard <http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf>`_
      The Secure Hash Algorithm is defined by NIST document FIPS PUB 180-2: `Secure
      Hash Standard
      <http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf>`_,
      published in August 2002.

   `Cryptographic Toolkit (Secure Hashing) <http://csrc.nist.gov/CryptoToolkit/tkhash.html>`_
      Links from NIST to various information on secure hashing.

PK
%�\�~��  $html/_sources/library/shelve.rst.txtnu�[���:mod:`shelve` --- Python object persistence
===========================================

.. module:: shelve
   :synopsis: Python object persistence.


.. index:: module: pickle

**Source code:** :source:`Lib/shelve.py`

--------------

A "shelf" is a persistent, dictionary-like object.  The difference with "dbm"
databases is that the values (not the keys!) in a shelf can be essentially
arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
This includes most class instances, recursive data types, and objects containing
lots of shared  sub-objects.  The keys are ordinary strings.


.. function:: open(filename, flag='c', protocol=None, writeback=False)

   Open a persistent dictionary.  The filename specified is the base filename for
   the underlying database.  As a side-effect, an extension may be added to the
   filename and more than one file may be created.  By default, the underlying
   database file is opened for reading and writing.  The optional *flag* parameter
   has the same interpretation as the *flag* parameter of :func:`anydbm.open`.

   By default, version 0 pickles are used to serialize values.  The version of the
   pickle protocol can be specified with the *protocol* parameter.

   .. versionchanged:: 2.3
      The *protocol* parameter was added.

   Because of Python semantics, a shelf cannot know when a mutable
   persistent-dictionary entry is modified.  By default modified objects are
   written *only* when assigned to the shelf (see :ref:`shelve-example`).  If the
   optional *writeback* parameter is set to ``True``, all entries accessed are also
   cached in memory, and written back on :meth:`~Shelf.sync` and
   :meth:`~Shelf.close`; this can make it handier to mutate mutable entries in
   the persistent dictionary, but, if many entries are accessed, it can consume
   vast amounts of memory for the cache, and it can make the close operation
   very slow since all accessed entries are written back (there is no way to
   determine which accessed entries are mutable, nor which ones were actually
   mutated).

   Like file objects, shelve objects should be closed explicitly to ensure
   that the persistent data is flushed to disk.

.. warning::

   Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure
   to load a shelf from an untrusted source.  Like with pickle, loading a shelf
   can execute arbitrary code.

Shelf objects support most of the methods supported by dictionaries.  This
eases the transition from dictionary based scripts to those requiring
persistent storage.

Note, the Python 3 transition methods (:meth:`~dict.viewkeys`,
:meth:`~dict.viewvalues`, and :meth:`~dict.viewitems`) are not supported.

Two additional methods are supported:

.. method:: Shelf.sync()

   Write back all entries in the cache if the shelf was opened with *writeback*
   set to :const:`True`.  Also empty the cache and synchronize the persistent
   dictionary on disk, if feasible.  This is called automatically when the shelf
   is closed with :meth:`close`.

.. method:: Shelf.close()

   Synchronize and close the persistent *dict* object.  Operations on a closed
   shelf will fail with a :exc:`ValueError`.


.. seealso::

   `Persistent dictionary recipe <https://code.activestate.com/recipes/576642/>`_
   with widely supported storage formats and having the speed of native
   dictionaries.


Restrictions
------------

  .. index::
     module: dbm
     module: gdbm
     module: bsddb

* The choice of which database package will be used (such as :mod:`dbm`,
  :mod:`gdbm` or :mod:`bsddb`) depends on which interface is available.  Therefore
  it is not safe to open the database directly using :mod:`dbm`.  The database is
  also (unfortunately) subject to the limitations of :mod:`dbm`, if it is used ---
  this means that (the pickled representation of) the objects stored in the
  database should be fairly small, and in rare cases key collisions may cause the
  database to refuse updates.

* The :mod:`shelve` module does not support *concurrent* read/write access to
  shelved objects.  (Multiple simultaneous read accesses are safe.)  When a
  program has a shelf open for writing, no other program should have it open for
  reading or writing.  Unix file locking can be used to solve this, but this
  differs across Unix versions and requires knowledge about the database
  implementation used.


.. class:: Shelf(dict, protocol=None, writeback=False)

   A subclass of :class:`UserDict.DictMixin` which stores pickled values in the
   *dict* object.

   By default, version 0 pickles are used to serialize values.  The version of the
   pickle protocol can be specified with the *protocol* parameter. See the
   :mod:`pickle` documentation for a discussion of the pickle protocols.

   .. versionchanged:: 2.3
      The *protocol* parameter was added.

   If the *writeback* parameter is ``True``, the object will hold a cache of all
   entries accessed and write them back to the *dict* at sync and close times.
   This allows natural operations on mutable entries, but can consume much more
   memory and make sync and close take a long time.


.. class:: BsdDbShelf(dict, protocol=None, writeback=False)

   A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`,
   :meth:`previous`, :meth:`last` and :meth:`set_location` which are available in
   the :mod:`bsddb` module but not in other database modules.  The *dict* object
   passed to the constructor must support those methods.  This is generally
   accomplished by calling one of :func:`bsddb.hashopen`, :func:`bsddb.btopen` or
   :func:`bsddb.rnopen`.  The optional *protocol* and *writeback* parameters have
   the same interpretation as for the :class:`Shelf` class.


.. class:: DbfilenameShelf(filename, flag='c', protocol=None, writeback=False)

   A subclass of :class:`Shelf` which accepts a *filename* instead of a dict-like
   object.  The underlying file will be opened using :func:`anydbm.open`.  By
   default, the file will be created and opened for both read and write.  The
   optional *flag* parameter has the same interpretation as for the :func:`.open`
   function.  The optional *protocol* and *writeback* parameters have the same
   interpretation as for the :class:`Shelf` class.


.. _shelve-example:

Example
-------

To summarize the interface (``key`` is a string, ``data`` is an arbitrary
object)::

   import shelve

   d = shelve.open(filename) # open -- file may get suffix added by low-level
                             # library

   d[key] = data   # store data at key (overwrites old data if
                   # using an existing key)
   data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                   # such key)
   del d[key]      # delete data stored at key (raises KeyError
                   # if no such key)
   flag = d.has_key(key)   # true if the key exists
   klist = d.keys() # a list of all existing keys (slow!)

   # as d was opened WITHOUT writeback=True, beware:
   d['xx'] = range(4)  # this works as expected, but...
   d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

   # having opened d without writeback=True, you need to code carefully:
   temp = d['xx']      # extracts the copy
   temp.append(5)      # mutates the copy
   d['xx'] = temp      # stores the copy right back, to persist it

   # or, d=shelve.open(filename,writeback=True) would let you just code
   # d['xx'].append(5) and have it work as expected, BUT it would also
   # consume more memory and make the d.close() operation slower.

   d.close()       # close it


.. seealso::

   Module :mod:`anydbm`
      Generic interface to ``dbm``\ -style databases.

   Module :mod:`bsddb`
      BSD ``db`` database interface.

   Module :mod:`dbhash`
      Thin layer around the :mod:`bsddb` which provides an :func:`~dbhash.open`
      function like the other database modules.

   Module :mod:`dbm`
      Standard Unix database interface.

   Module :mod:`dumbdbm`
      Portable implementation of the ``dbm`` interface.

   Module :mod:`gdbm`
      GNU database interface, based on the ``dbm`` interface.

   Module :mod:`pickle`
      Object serialization used by :mod:`shelve`.

   Module :mod:`cPickle`
      High-performance version of :mod:`pickle`.

PK
%�\t�1,1,#html/_sources/library/shlex.rst.txtnu�[���:mod:`shlex` --- Simple lexical analysis
========================================

.. module:: shlex
   :synopsis: Simple lexical analysis for Unix shell-like languages.
.. moduleauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
.. moduleauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>
.. sectionauthor:: Gustavo Niemeyer <niemeyer@conectiva.com>


.. versionadded:: 1.5.2

**Source code:** :source:`Lib/shlex.py`

--------------


The :class:`~shlex.shlex` class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the Unix shell.  This will often be useful
for writing minilanguages, (for example, in run control files for Python
applications) or for parsing quoted strings.

Prior to Python 2.7.3, this module did not support Unicode input.

The :mod:`shlex` module defines the following functions:


.. function:: split(s[, comments[, posix]])

   Split the string *s* using shell-like syntax. If *comments* is :const:`False`
   (the default), the parsing of comments in the given string will be disabled
   (setting the :attr:`~shlex.commenters` attribute of the
   :class:`~shlex.shlex` instance to the empty string).  This function operates
   in POSIX mode by default, but uses non-POSIX mode if the *posix* argument is
   false.

   .. versionadded:: 2.3

   .. versionchanged:: 2.6
      Added the *posix* parameter.

   .. note::

      Since the :func:`split` function instantiates a :class:`~shlex.shlex`
      instance, passing ``None`` for *s* will read the string to split from
      standard input.

The :mod:`shlex` module defines the following class:


.. class:: shlex([instream[, infile[, posix]]])

   A :class:`~shlex.shlex` instance or subclass instance is a lexical analyzer
   object.  The initialization argument, if present, specifies where to read
   characters from. It must be a file-/stream-like object with
   :meth:`~io.TextIOBase.read` and :meth:`~io.TextIOBase.readline` methods, or
   a string (strings are accepted since Python 2.3).  If no argument is given,
   input will be taken from ``sys.stdin``.  The second optional argument is a
   filename string, which sets the initial value of the :attr:`~shlex.infile`
   attribute.  If the *instream* argument is omitted or equal to ``sys.stdin``,
   this second argument defaults to "stdin".  The *posix* argument was
   introduced in Python 2.3, and defines the operational mode.  When *posix* is
   not true (default), the :class:`~shlex.shlex` instance will operate in
   compatibility mode.  When operating in POSIX mode, :class:`~shlex.shlex`
   will try to be as close as possible to the POSIX shell parsing rules.


.. seealso::

   Module :mod:`ConfigParser`
      Parser for configuration files similar to the Windows :file:`.ini` files.


.. _shlex-objects:

shlex Objects
-------------

A :class:`~shlex.shlex` instance has the following methods:


.. method:: shlex.get_token()

   Return a token.  If tokens have been stacked using :meth:`push_token`, pop a
   token off the stack.  Otherwise, read one from the input stream.  If reading
   encounters an immediate end-of-file, :attr:`eof` is returned (the empty
   string (``''``) in non-POSIX mode, and ``None`` in POSIX mode).


.. method:: shlex.push_token(str)

   Push the argument onto the token stack.


.. method:: shlex.read_token()

   Read a raw token.  Ignore the pushback stack, and do not interpret source
   requests.  (This is not ordinarily a useful entry point, and is documented here
   only for the sake of completeness.)


.. method:: shlex.sourcehook(filename)

   When :class:`~shlex.shlex` detects a source request (see :attr:`source`
   below) this method is given the following token as argument, and expected
   to return a tuple consisting of a filename and an open file-like object.

   Normally, this method first strips any quotes off the argument.  If the result
   is an absolute pathname, or there was no previous source request in effect, or
   the previous source was a stream (such as ``sys.stdin``), the result is left
   alone.  Otherwise, if the result is a relative pathname, the directory part of
   the name of the file immediately before it on the source inclusion stack is
   prepended (this behavior is like the way the C preprocessor handles ``#include
   "file.h"``).

   The result of the manipulations is treated as a filename, and returned as the
   first component of the tuple, with :func:`open` called on it to yield the second
   component. (Note: this is the reverse of the order of arguments in instance
   initialization!)

   This hook is exposed so that you can use it to implement directory search paths,
   addition of file extensions, and other namespace hacks. There is no
   corresponding 'close' hook, but a shlex instance will call the
   :meth:`~io.IOBase.close` method of the sourced input stream when it returns
   EOF.

   For more explicit control of source stacking, use the :meth:`push_source` and
   :meth:`pop_source` methods.


.. method:: shlex.push_source(stream[, filename])

   Push an input source stream onto the input stack.  If the filename argument is
   specified it will later be available for use in error messages.  This is the
   same method used internally by the :meth:`sourcehook` method.

   .. versionadded:: 2.1


.. method:: shlex.pop_source()

   Pop the last-pushed input source from the input stack. This is the same method
   used internally when the lexer reaches EOF on a stacked input stream.

   .. versionadded:: 2.1


.. method:: shlex.error_leader([file[, line]])

   This method generates an error message leader in the format of a Unix C compiler
   error label; the format is ``'"%s", line %d: '``, where the ``%s`` is replaced
   with the name of the current source file and the ``%d`` with the current input
   line number (the optional arguments can be used to override these).

   This convenience is provided to encourage :mod:`shlex` users to generate error
   messages in the standard, parseable format understood by Emacs and other Unix
   tools.

Instances of :class:`~shlex.shlex` subclasses have some public instance
variables which either control lexical analysis or can be used for debugging:


.. attribute:: shlex.commenters

   The string of characters that are recognized as comment beginners. All
   characters from the comment beginner to end of line are ignored. Includes just
   ``'#'`` by default.


.. attribute:: shlex.wordchars

   The string of characters that will accumulate into multi-character tokens.  By
   default, includes all ASCII alphanumerics and underscore.


.. attribute:: shlex.whitespace

   Characters that will be considered whitespace and skipped.  Whitespace bounds
   tokens.  By default, includes space, tab, linefeed and carriage-return.


.. attribute:: shlex.escape

   Characters that will be considered as escape. This will be only used in POSIX
   mode, and includes just ``'\'`` by default.

   .. versionadded:: 2.3


.. attribute:: shlex.quotes

   Characters that will be considered string quotes.  The token accumulates until
   the same quote is encountered again (thus, different quote types protect each
   other as in the shell.)  By default, includes ASCII single and double quotes.


.. attribute:: shlex.escapedquotes

   Characters in :attr:`quotes` that will interpret escape characters defined in
   :attr:`escape`.  This is only used in POSIX mode, and includes just ``'"'`` by
   default.

   .. versionadded:: 2.3


.. attribute:: shlex.whitespace_split

   If ``True``, tokens will only be split in whitespaces. This is useful, for
   example, for parsing command lines with :class:`~shlex.shlex`, getting
   tokens in a similar way to shell arguments.

   .. versionadded:: 2.3


.. attribute:: shlex.infile

   The name of the current input file, as initially set at class instantiation time
   or stacked by later source requests.  It may be useful to examine this when
   constructing error messages.


.. attribute:: shlex.instream

   The input stream from which this :class:`~shlex.shlex` instance is reading
   characters.


.. attribute:: shlex.source

   This attribute is ``None`` by default.  If you assign a string to it, that
   string will be recognized as a lexical-level inclusion request similar to the
   ``source`` keyword in various shells.  That is, the immediately following token
   will be opened as a filename and input will
   be taken from that stream until EOF, at which
   point the :meth:`~io.IOBase.close` method of that stream will be called and
   the input source will again become the original input stream.  Source
   requests may be stacked any number of levels deep.


.. attribute:: shlex.debug

   If this attribute is numeric and ``1`` or more, a :class:`~shlex.shlex`
   instance will print verbose progress output on its behavior.  If you need
   to use this, you can read the module source code to learn the details.


.. attribute:: shlex.lineno

   Source line number (count of newlines seen so far plus one).


.. attribute:: shlex.token

   The token buffer.  It may be useful to examine this when catching exceptions.


.. attribute:: shlex.eof

   Token used to determine end of file. This will be set to the empty string
   (``''``), in non-POSIX mode, and to ``None`` in POSIX mode.

   .. versionadded:: 2.3


.. _shlex-parsing-rules:

Parsing Rules
-------------

When operating in non-POSIX mode, :class:`~shlex.shlex` will try to obey to the
following rules.

* Quote characters are not recognized within words (``Do"Not"Separate`` is
  parsed as the single word ``Do"Not"Separate``);

* Escape characters are not recognized;

* Enclosing characters in quotes preserve the literal value of all characters
  within the quotes;

* Closing quotes separate words (``"Do"Separate`` is parsed as ``"Do"`` and
  ``Separate``);

* If :attr:`~shlex.whitespace_split` is ``False``, any character not
  declared to be a word character, whitespace, or a quote will be returned as
  a single-character token. If it is ``True``, :class:`~shlex.shlex` will only
  split words in whitespaces;

* EOF is signaled with an empty string (``''``);

* It's not possible to parse empty strings, even if quoted.

When operating in POSIX mode, :class:`~shlex.shlex` will try to obey to the
following parsing rules.

* Quotes are stripped out, and do not separate words (``"Do"Not"Separate"`` is
  parsed as the single word ``DoNotSeparate``);

* Non-quoted escape characters (e.g. ``'\'``) preserve the literal value of the
  next character that follows;

* Enclosing characters in quotes which are not part of
  :attr:`~shlex.escapedquotes` (e.g. ``"'"``) preserve the literal value
  of all characters within the quotes;

* Enclosing characters in quotes which are part of
  :attr:`~shlex.escapedquotes` (e.g. ``'"'``) preserves the literal value
  of all characters within the quotes, with the exception of the characters
  mentioned in :attr:`~shlex.escape`.  The escape characters retain its
  special meaning only when followed by the quote in use, or the escape
  character itself. Otherwise the escape character will be considered a
  normal character.

* EOF is signaled with a :const:`None` value;

* Quoted empty strings (``''``) are allowed;

PK
%�\�gz��4�4$html/_sources/library/shutil.rst.txtnu�[���:mod:`shutil` --- High-level file operations
============================================

.. module:: shutil
   :synopsis: High-level file operations, including copying.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. partly based on the docstrings

.. index::
   single: file; copying
   single: copying files

**Source code:** :source:`Lib/shutil.py`

--------------

The :mod:`shutil` module offers a number of high-level operations on files and
collections of files.  In particular, functions are provided  which support file
copying and removal. For operations on individual files, see also the
:mod:`os` module.

.. warning::

   Even the higher-level file copying functions (:func:`shutil.copy`,
   :func:`shutil.copy2`) can't copy all file metadata.

   On POSIX platforms, this means that file owner and group are lost as well
   as ACLs.  On Mac OS, the resource fork and other metadata are not used.
   This means that resources will be lost and file type and creator codes will
   not be correct. On Windows, file owners, ACLs and alternate data streams
   are not copied.


.. _file-operations:

Directory and files operations
------------------------------

.. function:: copyfileobj(fsrc, fdst[, length])

   Copy the contents of the file-like object *fsrc* to the file-like object *fdst*.
   The integer *length*, if given, is the buffer size. In particular, a negative
   *length* value means to copy the data without looping over the source data in
   chunks; by default the data is read in chunks to avoid uncontrolled memory
   consumption. Note that if the current file position of the *fsrc* object is not
   0, only the contents from the current file position to the end of the file will
   be copied.


.. function:: copyfile(src, dst)

   Copy the contents (no metadata) of the file named *src* to a file named
   *dst*.  *dst* must be the complete target file name; look at
   :func:`shutil.copy` for a copy that accepts a target directory path.  If
   *src* and *dst* are the same files, :exc:`Error` is raised.
   The destination location must be writable; otherwise,  an :exc:`IOError` exception
   will be raised. If *dst* already exists, it will be replaced.   Special files
   such as character or block devices and pipes cannot be copied with this
   function.  *src* and *dst* are path names given as strings.


.. function:: copymode(src, dst)

   Copy the permission bits from *src* to *dst*.  The file contents, owner, and
   group are unaffected.  *src* and *dst* are path names given as strings.


.. function:: copystat(src, dst)

   Copy the permission bits, last access time, last modification time, and flags
   from *src* to *dst*.  The file contents, owner, and group are unaffected.  *src*
   and *dst* are path names given as strings.


.. function:: copy(src, dst)

   Copy the file *src* to the file or directory *dst*.  If *dst* is a directory, a
   file with the same basename as *src*  is created (or overwritten) in the
   directory specified.  Permission bits are copied.  *src* and *dst* are path
   names given as strings.


.. function:: copy2(src, dst)

   Identical to :func:`~shutil.copy` except that :func:`copy2`
   also attempts to preserve file metadata.

   :func:`copy2` uses :func:`copystat` to copy the file metadata.
   Please see :func:`copystat` for more information.


.. function:: ignore_patterns(\*patterns)

   This factory function creates a function that can be used as a callable for
   :func:`copytree`\'s *ignore* argument, ignoring files and directories that
   match one of the glob-style *patterns* provided.  See the example below.

   .. versionadded:: 2.6


.. function:: copytree(src, dst, symlinks=False, ignore=None)

   Recursively copy an entire directory tree rooted at *src*.  The destination
   directory, named by *dst*, must not already exist; it will be created as
   well as missing parent directories.  Permissions and times of directories
   are copied with :func:`copystat`, individual files are copied using
   :func:`shutil.copy2`.

   If *symlinks* is true, symbolic links in the source tree are represented as
   symbolic links in the new tree, but the metadata of the original links is NOT
   copied; if false or omitted, the contents and metadata of the linked files
   are copied to the new tree.

   If *ignore* is given, it must be a callable that will receive as its
   arguments the directory being visited by :func:`copytree`, and a list of its
   contents, as returned by :func:`os.listdir`.  Since :func:`copytree` is
   called recursively, the *ignore* callable will be called once for each
   directory that is copied.  The callable must return a sequence of directory
   and file names relative to the current directory (i.e. a subset of the items
   in its second argument); these names will then be ignored in the copy
   process.  :func:`ignore_patterns` can be used to create such a callable that
   ignores names based on glob-style patterns.

   If exception(s) occur, an :exc:`Error` is raised with a list of reasons.

   The source code for this should be considered an example rather than the
   ultimate tool.

   .. versionchanged:: 2.3
      :exc:`Error` is raised if any exceptions occur during copying, rather than
      printing a message.

   .. versionchanged:: 2.5
      Create intermediate directories needed to create *dst*, rather than raising an
      error. Copy permissions and times of directories using :func:`copystat`.

   .. versionchanged:: 2.6
      Added the *ignore* argument to be able to influence what is being copied.


.. function:: rmtree(path[, ignore_errors[, onerror]])

   .. index:: single: directory; deleting

   Delete an entire directory tree; *path* must point to a directory (but not a
   symbolic link to a directory).  If *ignore_errors* is true, errors resulting
   from failed removals will be ignored; if false or omitted, such errors are
   handled by calling a handler specified by *onerror* or, if that is omitted,
   they raise an exception.

   If *onerror* is provided, it must be a callable that accepts three
   parameters: *function*, *path*, and *excinfo*. The first parameter,
   *function*, is the function which raised the exception; it will be
   :func:`os.path.islink`, :func:`os.listdir`, :func:`os.remove` or
   :func:`os.rmdir`.  The second parameter, *path*, will be the path name passed
   to *function*.  The third parameter, *excinfo*, will be the exception
   information return by :func:`sys.exc_info`.  Exceptions raised by *onerror*
   will not be caught.

   .. versionchanged:: 2.6
      Explicitly check for *path* being a symbolic link and raise :exc:`OSError`
      in that case.


.. function:: move(src, dst)

   Recursively move a file or directory (*src*) to another location (*dst*).

   If the destination is an existing directory, then *src* is moved inside that
   directory. If the destination already exists but is not a directory, it may
   be overwritten depending on :func:`os.rename` semantics.

   If the destination is on the current filesystem, then :func:`os.rename` is
   used.  Otherwise, *src* is copied (using :func:`shutil.copy2`) to *dst* and
   then removed.

   .. versionadded:: 2.3


.. exception:: Error

   This exception collects exceptions that are raised during a multi-file
   operation. For :func:`copytree`, the exception argument is a list of 3-tuples
   (*srcname*, *dstname*, *exception*).

   .. versionadded:: 2.3


.. _copytree-example:

copytree example
::::::::::::::::

This example is the implementation of the :func:`copytree` function, described
above, with the docstring omitted.  It demonstrates many of the other functions
provided by this module. ::

   def copytree(src, dst, symlinks=False, ignore=None):
       names = os.listdir(src)
       if ignore is not None:
           ignored_names = ignore(src, names)
       else:
           ignored_names = set()

       os.makedirs(dst)
       errors = []
       for name in names:
           if name in ignored_names:
               continue
           srcname = os.path.join(src, name)
           dstname = os.path.join(dst, name)
           try:
               if symlinks and os.path.islink(srcname):
                   linkto = os.readlink(srcname)
                   os.symlink(linkto, dstname)
               elif os.path.isdir(srcname):
                   copytree(srcname, dstname, symlinks, ignore)
               else:
                   copy2(srcname, dstname)
               # XXX What about devices, sockets etc.?
           except (IOError, os.error) as why:
               errors.append((srcname, dstname, str(why)))
           # catch the Error from the recursive copytree so that we can
           # continue with other files
           except Error as err:
               errors.extend(err.args[0])
       try:
           copystat(src, dst)
       except WindowsError:
           # can't copy file access times on Windows
           pass
       except OSError as why:
           errors.extend((src, dst, str(why)))
       if errors:
           raise Error(errors)

Another example that uses the :func:`ignore_patterns` helper::

   from shutil import copytree, ignore_patterns

   copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

This will copy everything except ``.pyc`` files and files or directories whose
name starts with ``tmp``.

Another example that uses the *ignore* argument to add a logging call::

   from shutil import copytree
   import logging

   def _logpath(path, names):
       logging.info('Working in %s' % path)
       return []   # nothing will be ignored

   copytree(source, destination, ignore=_logpath)


.. _archiving-operations:

Archiving operations
--------------------

High-level utilities to create and read compressed and archived files are also
provided.  They rely on the :mod:`zipfile` and :mod:`tarfile` modules.

.. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])

   Create an archive file (eg. zip or tar) and returns its name.

   *base_name* is the name of the file to create, including the path, minus
   any format-specific extension. *format* is the archive format: one of
   "zip" (if the :mod:`zlib` module or external ``zip`` executable is
   available), "tar", "gztar" (if the :mod:`zlib` module is available), or
   "bztar" (if the :mod:`bz2` module is available).

   *root_dir* is a directory that will be the root directory of the
   archive; ie. we typically chdir into *root_dir* before creating the
   archive.

   *base_dir* is the directory where we start archiving from;
   ie. *base_dir* will be the common prefix of all files and
   directories in the archive.

   *root_dir* and *base_dir* both default to the current directory.

   *owner* and *group* are used when creating a tar archive. By default,
   uses the current owner and group.

   *logger* must be an object compatible with :pep:`282`, usually an instance of
   :class:`logging.Logger`.

   .. versionadded:: 2.7


.. function:: get_archive_formats()

   Return a list of supported formats for archiving.
   Each element of the returned sequence is a tuple ``(name, description)``.

   By default :mod:`shutil` provides these formats:

   - *zip*: ZIP file (if the :mod:`zlib` module or external ``zip``
     executable is available).
   - *tar*: uncompressed tar file.
   - *gztar*: gzip'ed tar-file (if the :mod:`zlib` module is available).
   - *bztar*: bzip2'ed tar-file (if the :mod:`bz2` module is available).

   You can register new formats or provide your own archiver for any existing
   formats, by using :func:`register_archive_format`.

   .. versionadded:: 2.7


.. function:: register_archive_format(name, function, [extra_args, [description]])

   Register an archiver for the format *name*. *function* is a callable that
   will be used to invoke the archiver.

   If given, *extra_args* is a sequence of ``(name, value)`` that will be
   used as extra keywords arguments when the archiver callable is used.

   *description* is used by :func:`get_archive_formats` which returns the
   list of archivers. Defaults to an empty list.

   .. versionadded:: 2.7


.. function::  unregister_archive_format(name)

   Remove the archive format *name* from the list of supported formats.

   .. versionadded:: 2.7


.. _archiving-example:

Archiving example
:::::::::::::::::

In this example, we create a gzip'ed tar-file archive containing all files
found in the :file:`.ssh` directory of the user::

    >>> from shutil import make_archive
    >>> import os
    >>> archive_name = os.path.expanduser(os.path.join('~', 'myarchive'))
    >>> root_dir = os.path.expanduser(os.path.join('~', '.ssh'))
    >>> make_archive(archive_name, 'gztar', root_dir)
    '/Users/tarek/myarchive.tar.gz'

The resulting archive contains:

.. code-block:: shell-session

    $ tar -tzvf /Users/tarek/myarchive.tar.gz
    drwx------ tarek/staff       0 2010-02-01 16:23:40 ./
    -rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys
    -rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config
    -rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa
    -rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub
    -rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa
    -rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub
    -rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts
PK
%�\t�,�)�)$html/_sources/library/signal.rst.txtnu�[���
:mod:`signal` --- Set handlers for asynchronous events
======================================================

.. module:: signal
   :synopsis: Set handlers for asynchronous events.


This module provides mechanisms to use signal handlers in Python. Some general
rules for working with signals and their handlers:

* A handler for a particular signal, once set, remains installed until it is
  explicitly reset (Python emulates the BSD style interface regardless of the
  underlying implementation), with the exception of the handler for
  :const:`SIGCHLD`, which follows the underlying implementation.

* There is no way to "block" signals temporarily from critical sections (since
  this is not supported by all Unix flavors).

* Although Python signal handlers are called asynchronously as far as the Python
  user is concerned, they can only occur between the "atomic" instructions of the
  Python interpreter.  This means that signals arriving during long calculations
  implemented purely in C (such as regular expression matches on large bodies of
  text) may be delayed for an arbitrary amount of time.

* When a signal arrives during an I/O operation, it is possible that the I/O
  operation raises an exception after the signal handler returns. This is
  dependent on the underlying Unix system's semantics regarding interrupted system
  calls.

* Because the C signal handler always returns, it makes little sense to catch
  synchronous errors like :const:`SIGFPE` or :const:`SIGSEGV`.

* Python installs a small number of signal handlers by default: :const:`SIGPIPE`
  is ignored (so write errors on pipes and sockets can be reported as ordinary
  Python exceptions) and :const:`SIGINT` is translated into a
  :exc:`KeyboardInterrupt` exception.  All of these can be overridden.

* Some care must be taken if both signals and threads are used in the same
  program.  The fundamental thing to remember in using signals and threads
  simultaneously is: always perform :func:`signal` operations in the main thread
  of execution.  Any thread can perform an :func:`alarm`, :func:`getsignal`,
  :func:`pause`, :func:`setitimer` or :func:`getitimer`; only the main thread
  can set a new signal handler, and the main thread will be the only one to
  receive signals (this is enforced by the Python :mod:`signal` module, even
  if the underlying thread implementation supports sending signals to
  individual threads).  This means that signals can't be used as a means of
  inter-thread communication.  Use locks instead.

The variables defined in the :mod:`signal` module are:


.. data:: SIG_DFL

   This is one of two standard signal handling options; it will simply perform
   the default function for the signal.  For example, on most systems the
   default action for :const:`SIGQUIT` is to dump core and exit, while the
   default action for :const:`SIGCHLD` is to simply ignore it.


.. data:: SIG_IGN

   This is another standard signal handler, which will simply ignore the given
   signal.


.. data:: SIG*

   All the signal numbers are defined symbolically.  For example, the hangup signal
   is defined as :const:`signal.SIGHUP`; the variable names are identical to the
   names used in C programs, as found in ``<signal.h>``. The Unix man page for
   ':c:func:`signal`' lists the existing signals (on some systems this is
   :manpage:`signal(2)`, on others the list is in :manpage:`signal(7)`). Note that
   not all systems define the same set of signal names; only those names defined by
   the system are defined by this module.


.. data:: CTRL_C_EVENT

   The signal corresponding to the :kbd:`Ctrl+C` keystroke event. This signal can
   only be used with :func:`os.kill`.

   Availability: Windows.

   .. versionadded:: 2.7


.. data:: CTRL_BREAK_EVENT

   The signal corresponding to the :kbd:`Ctrl+Break` keystroke event. This signal can
   only be used with :func:`os.kill`.

   Availability: Windows.

   .. versionadded:: 2.7


.. data:: NSIG

   One more than the number of the highest signal number.


.. data:: ITIMER_REAL

   Decrements interval timer in real time, and delivers :const:`SIGALRM` upon expiration.


.. data:: ITIMER_VIRTUAL

   Decrements interval timer only when the process is executing, and delivers
   SIGVTALRM upon expiration.


.. data:: ITIMER_PROF

   Decrements interval timer both when the process executes and when the
   system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
   this timer is usually used to profile the time spent by the application
   in user and kernel space. SIGPROF is delivered upon expiration.


The :mod:`signal` module defines one exception:

.. exception:: ItimerError

   Raised to signal an error from the underlying :func:`setitimer` or
   :func:`getitimer` implementation. Expect this error if an invalid
   interval timer or a negative time is passed to :func:`setitimer`.
   This error is a subtype of :exc:`IOError`.


The :mod:`signal` module defines the following functions:


.. function:: alarm(time)

   If *time* is non-zero, this function requests that a :const:`SIGALRM` signal be
   sent to the process in *time* seconds. Any previously scheduled alarm is
   canceled (only one alarm can be scheduled at any time).  The returned value is
   then the number of seconds before any previously set alarm was to have been
   delivered. If *time* is zero, no alarm is scheduled, and any scheduled alarm is
   canceled.  If the return value is zero, no alarm is currently scheduled.  (See
   the Unix man page :manpage:`alarm(2)`.) Availability: Unix.


.. function:: getsignal(signalnum)

   Return the current signal handler for the signal *signalnum*. The returned value
   may be a callable Python object, or one of the special values
   :const:`signal.SIG_IGN`, :const:`signal.SIG_DFL` or :const:`None`.  Here,
   :const:`signal.SIG_IGN` means that the signal was previously ignored,
   :const:`signal.SIG_DFL` means that the default way of handling the signal was
   previously in use, and ``None`` means that the previous signal handler was not
   installed from Python.


.. function:: pause()

   Cause the process to sleep until a signal is received; the appropriate handler
   will then be called.  Returns nothing.  Not on Windows. (See the Unix man page
   :manpage:`signal(2)`.)


.. function:: setitimer(which, seconds[, interval])

   Sets given interval timer (one of :const:`signal.ITIMER_REAL`,
   :const:`signal.ITIMER_VIRTUAL` or :const:`signal.ITIMER_PROF`) specified
   by *which* to fire after *seconds* (float is accepted, different from
   :func:`alarm`) and after that every *interval* seconds. The interval
   timer specified by *which* can be cleared by setting seconds to zero.

   When an interval timer fires, a signal is sent to the process.
   The signal sent is dependent on the timer being used;
   :const:`signal.ITIMER_REAL` will deliver :const:`SIGALRM`,
   :const:`signal.ITIMER_VIRTUAL` sends :const:`SIGVTALRM`,
   and :const:`signal.ITIMER_PROF` will deliver :const:`SIGPROF`.

   The old values are returned as a tuple: (delay, interval).

   Attempting to pass an invalid interval timer will cause an
   :exc:`ItimerError`.  Availability: Unix.

   .. versionadded:: 2.6


.. function:: getitimer(which)

   Returns current value of a given interval timer specified by *which*.
   Availability: Unix.

   .. versionadded:: 2.6


.. function:: set_wakeup_fd(fd)

   Set the wakeup fd to *fd*.  When a signal is received, a ``'\0'`` byte is
   written to the fd.  This can be used by a library to wakeup a poll or select
   call, allowing the signal to be fully processed.

   The old wakeup fd is returned (or -1 if file descriptor wakeup was not
   enabled).  If *fd* is -1, file descriptor wakeup is disabled.
   If not -1, *fd* must be non-blocking.  It is up to the library to remove
   any bytes from *fd* before calling poll or select again.

   When threads are enabled, this function can only be called from the main thread;
   attempting to call it from other threads will cause a :exc:`ValueError`
   exception to be raised.

   .. versionadded:: 2.6


.. function:: siginterrupt(signalnum, flag)

   Change system call restart behaviour: if *flag* is :const:`False`, system
   calls will be restarted when interrupted by signal *signalnum*, otherwise
   system calls will be interrupted.  Returns nothing.  Availability: Unix (see
   the man page :manpage:`siginterrupt(3)` for further information).

   Note that installing a signal handler with :func:`signal` will reset the
   restart behaviour to interruptible by implicitly calling
   :c:func:`siginterrupt` with a true *flag* value for the given signal.

   .. versionadded:: 2.6


.. function:: signal(signalnum, handler)

   Set the handler for signal *signalnum* to the function *handler*.  *handler* can
   be a callable Python object taking two arguments (see below), or one of the
   special values :const:`signal.SIG_IGN` or :const:`signal.SIG_DFL`.  The previous
   signal handler will be returned (see the description of :func:`getsignal`
   above).  (See the Unix man page :manpage:`signal(2)`.)

   When threads are enabled, this function can only be called from the main thread;
   attempting to call it from other threads will cause a :exc:`ValueError`
   exception to be raised.

   The *handler* is called with two arguments: the signal number and the current
   stack frame (``None`` or a frame object; for a description of frame objects,
   see the :ref:`description in the type hierarchy <frame-objects>` or see the
   attribute descriptions in the :mod:`inspect` module).

   On Windows, :func:`signal` can only be called with :const:`SIGABRT`,
   :const:`SIGFPE`, :const:`SIGILL`, :const:`SIGINT`, :const:`SIGSEGV`, or
   :const:`SIGTERM`. A :exc:`ValueError` will be raised in any other case.


.. _signal-example:

Example
-------

Here is a minimal example program. It uses the :func:`alarm` function to limit
the time spent waiting to open a file; this is useful if the file is for a
serial device that may not be turned on, which would normally cause the
:func:`os.open` to hang indefinitely.  The solution is to set a 5-second alarm
before opening the file; if the operation takes too long, the alarm signal will
be sent, and the handler raises an exception. ::

   import signal, os

   def handler(signum, frame):
       print 'Signal handler called with signal', signum
       raise IOError("Couldn't open device!")

   # Set the signal handler and a 5-second alarm
   signal.signal(signal.SIGALRM, handler)
   signal.alarm(5)

   # This open() may hang indefinitely
   fd = os.open('/dev/ttyS0', os.O_RDWR)

   signal.alarm(0)          # Disable the alarm

PK
%�\qN2���.html/_sources/library/simplehttpserver.rst.txtnu�[���
:mod:`SimpleHTTPServer` --- Simple HTTP request handler
=======================================================

.. module:: SimpleHTTPServer
   :synopsis: This module provides a basic request handler for HTTP servers.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

.. note::
   The :mod:`SimpleHTTPServer` module has been merged into :mod:`http.server` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.

.. warning::

   mod:`SimpleHTTServer` is not recommended for production. It only implements
   basic security checks.

The :mod:`SimpleHTTPServer` module defines a single class,
:class:`SimpleHTTPRequestHandler`, which is interface-compatible with
:class:`BaseHTTPServer.BaseHTTPRequestHandler`.

The :mod:`SimpleHTTPServer` module defines the following class:


.. class:: SimpleHTTPRequestHandler(request, client_address, server)

   This class serves files from the current directory and below, directly
   mapping the directory structure to HTTP requests.

   A lot of the work, such as parsing the request, is done by the base class
   :class:`BaseHTTPServer.BaseHTTPRequestHandler`.  This class implements the
   :func:`do_GET` and :func:`do_HEAD` functions.

   The following are defined as class-level attributes of
   :class:`SimpleHTTPRequestHandler`:


   .. attribute:: server_version

   This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is
   defined at the module level.


   .. attribute:: extensions_map

      A dictionary mapping suffixes into MIME types. The default is
      signified by an empty string, and is considered to be
      ``application/octet-stream``. The mapping is used case-insensitively,
      and so should contain only lower-cased keys.

   The :class:`SimpleHTTPRequestHandler` class defines the following methods:


   .. method:: do_HEAD()

      This method serves the ``'HEAD'`` request type: it sends the headers it
      would send for the equivalent ``GET`` request. See the :meth:`do_GET`
      method for a more complete explanation of the possible headers.


   .. method:: do_GET()

      The request is mapped to a local file by interpreting the request as a
      path relative to the current working directory.

      If the request was mapped to a directory, the directory is checked for a
      file named ``index.html`` or ``index.htm`` (in that order). If found, the
      file's contents are returned; otherwise a directory listing is generated
      by calling the :meth:`list_directory` method. This method uses
      :func:`os.listdir` to scan the directory, and returns a ``404`` error
      response if the :func:`listdir` fails.

      If the request was mapped to a file, it is opened and the contents are
      returned.  Any :exc:`IOError` exception in opening the requested file is
      mapped to a ``404``, ``'File not found'`` error. Otherwise, the content
      type is guessed by calling the :meth:`guess_type` method, which in turn
      uses the *extensions_map* variable.

      A ``'Content-type:'`` header with the guessed content type is output,
      followed by a ``'Content-Length:'`` header with the file's size and a
      ``'Last-Modified:'`` header with the file's modification time.

      Then follows a blank line signifying the end of the headers, and then the
      contents of the file are output. If the file's MIME type starts with
      ``text/`` the file is opened in text mode; otherwise binary mode is used.

      The :func:`test` function in the :mod:`SimpleHTTPServer` module is an
      example which creates a server using the :class:`SimpleHTTPRequestHandler`
      as the Handler.

      .. versionadded:: 2.5
         The ``'Last-Modified'`` header.


The :mod:`SimpleHTTPServer` module can be used in the following manner in order
to set up a very basic web server serving files relative to the current
directory. ::

   import SimpleHTTPServer
   import SocketServer

   PORT = 8000

   Handler = SimpleHTTPServer.SimpleHTTPRequestHandler

   httpd = SocketServer.TCPServer(("", PORT), Handler)

   print "serving at port", PORT
   httpd.serve_forever()

The :mod:`SimpleHTTPServer` module can also be invoked directly using the
:option:`-m` switch of the interpreter with a ``port number`` argument.
Similar to the previous example, this serves the files relative to the
current directory. ::

   python -m SimpleHTTPServer 8000

.. seealso::

   Module :mod:`BaseHTTPServer`
      Base class implementation for Web server and request handler.

PK
%�\���ǁ*�*0html/_sources/library/simplexmlrpcserver.rst.txtnu�[���:mod:`SimpleXMLRPCServer` --- Basic XML-RPC server
==================================================

.. module:: SimpleXMLRPCServer
   :synopsis: Basic XML-RPC server implementation.
.. moduleauthor:: Brian Quinlan <brianq@activestate.com>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

.. note::
   The :mod:`SimpleXMLRPCServer` module has been merged into
   :mod:`xmlrpc.server` in Python 3.  The :term:`2to3` tool will automatically
   adapt imports when converting your sources to Python 3.


.. versionadded:: 2.2

**Source code:** :source:`Lib/SimpleXMLRPCServer.py`

--------------

The :mod:`SimpleXMLRPCServer` module provides a basic server framework for
XML-RPC servers written in Python.  Servers can either be free standing, using
:class:`~SimpleXMLRPCServer.SimpleXMLRPCServer`, or embedded in a CGI environment, using
:class:`CGIXMLRPCRequestHandler`.


.. class:: SimpleXMLRPCServer(addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]])

   Create a new server instance.  This class provides methods for registration of
   functions that can be called by the XML-RPC protocol.  The *requestHandler*
   parameter should be a factory for request handler instances; it defaults to
   :class:`SimpleXMLRPCRequestHandler`.  The *addr* and *requestHandler* parameters
   are passed to the :class:`SocketServer.TCPServer` constructor.  If *logRequests*
   is true (the default), requests will be logged; setting this parameter to false
   will turn off logging.   The *allow_none* and *encoding* parameters are passed
   on to  :mod:`xmlrpclib` and control the XML-RPC responses that will be returned
   from the server. The *bind_and_activate* parameter controls whether
   :meth:`server_bind` and :meth:`server_activate` are called immediately by the
   constructor; it defaults to true. Setting it to false allows code to manipulate
   the *allow_reuse_address* class variable before the address is bound.

   .. versionchanged:: 2.5
      The *allow_none* and *encoding* parameters were added.

   .. versionchanged:: 2.6
      The *bind_and_activate* parameter was added.


.. class:: CGIXMLRPCRequestHandler([allow_none[, encoding]])

   Create a new instance to handle XML-RPC requests in a CGI environment.  The
   *allow_none* and *encoding* parameters are passed on to  :mod:`xmlrpclib` and
   control the XML-RPC responses that will be returned  from the server.

   .. versionadded:: 2.3

   .. versionchanged:: 2.5
      The *allow_none* and *encoding* parameters were added.


.. class:: SimpleXMLRPCRequestHandler()

   Create a new request handler instance.  This request handler supports ``POST``
   requests and modifies logging so that the *logRequests* parameter to the
   :class:`~SimpleXMLRPCServer.SimpleXMLRPCServer` constructor parameter is honored.


.. _simple-xmlrpc-servers:

SimpleXMLRPCServer Objects
--------------------------

The :class:`~SimpleXMLRPCServer.SimpleXMLRPCServer` class is based on
:class:`SocketServer.TCPServer` and provides a means of creating simple, stand
alone XML-RPC servers.


.. method:: SimpleXMLRPCServer.register_function(function[, name])

   Register a function that can respond to XML-RPC requests.  If *name* is given,
   it will be the method name associated with *function*, otherwise
   ``function.__name__`` will be used.  *name* can be either a normal or Unicode
   string, and may contain characters not legal in Python identifiers, including
   the period character.


.. method:: SimpleXMLRPCServer.register_instance(instance[, allow_dotted_names])

   Register an object which is used to expose method names which have not been
   registered using :meth:`register_function`.  If *instance* contains a
   :meth:`_dispatch` method, it is called with the requested method name and the
   parameters from the request.  Its API is ``def _dispatch(self, method, params)``
   (note that *params* does not represent a variable argument list).  If it calls
   an underlying function to perform its task, that function is called as
   ``func(*params)``, expanding the parameter list. The return value from
   :meth:`_dispatch` is returned to the client as the result.  If *instance* does
   not have a :meth:`_dispatch` method, it is searched for an attribute matching
   the name of the requested method.

   If the optional *allow_dotted_names* argument is true and the instance does not
   have a :meth:`_dispatch` method, then if the requested method name contains
   periods, each component of the method name is searched for individually, with
   the effect that a simple hierarchical search is performed.  The value found from
   this search is then called with the parameters from the request, and the return
   value is passed back to the client.

   .. warning::

      Enabling the *allow_dotted_names* option allows intruders to access your
      module's global variables and may allow intruders to execute arbitrary code on
      your machine.  Only use this option on a secure, closed network.

   .. versionchanged:: 2.3.5, 2.4.1
      *allow_dotted_names* was added to plug a security hole; prior versions are
      insecure.


.. method:: SimpleXMLRPCServer.register_introspection_functions()

   Registers the XML-RPC introspection functions ``system.listMethods``,
   ``system.methodHelp`` and ``system.methodSignature``.

   .. versionadded:: 2.3


.. method:: SimpleXMLRPCServer.register_multicall_functions()

   Registers the XML-RPC multicall function system.multicall.


.. attribute:: SimpleXMLRPCRequestHandler.rpc_paths

   An attribute value that must be a tuple listing valid path portions of the URL
   for receiving XML-RPC requests.  Requests posted to other paths will result in a
   404 "no such page" HTTP error.  If this tuple is empty, all paths will be
   considered valid. The default value is ``('/', '/RPC2')``.

   .. versionadded:: 2.5

.. attribute:: SimpleXMLRPCRequestHandler.encode_threshold

   If this attribute is not ``None``, responses larger than this value
   will be encoded using the *gzip* transfer encoding, if permitted by
   the client.  The default is ``1400`` which corresponds roughly
   to a single TCP packet.

   .. versionadded:: 2.7

.. _simplexmlrpcserver-example:

SimpleXMLRPCServer Example
^^^^^^^^^^^^^^^^^^^^^^^^^^
Server code::

   from SimpleXMLRPCServer import SimpleXMLRPCServer
   from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

   # Restrict to a particular path.
   class RequestHandler(SimpleXMLRPCRequestHandler):
       rpc_paths = ('/RPC2',)

   # Create server
   server = SimpleXMLRPCServer(("localhost", 8000),
                               requestHandler=RequestHandler)
   server.register_introspection_functions()

   # Register pow() function; this will use the value of
   # pow.__name__ as the name, which is just 'pow'.
   server.register_function(pow)

   # Register a function under a different name
   def adder_function(x,y):
       return x + y
   server.register_function(adder_function, 'add')

   # Register an instance; all the methods of the instance are
   # published as XML-RPC methods (in this case, just 'div').
   class MyFuncs:
       def div(self, x, y):
           return x // y

   server.register_instance(MyFuncs())

   # Run the server's main loop
   server.serve_forever()

The following client code will call the methods made available by the preceding
server::

   import xmlrpclib

   s = xmlrpclib.ServerProxy('http://localhost:8000')
   print s.pow(2,3)  # Returns 2**3 = 8
   print s.add(2,3)  # Returns 5
   print s.div(5,2)  # Returns 5//2 = 2

   # Print list of available methods
   print s.system.listMethods()

The following :class:`~SimpleXMLRPCServer.SimpleXMLRPCServer` example is included in the module
`Lib/SimpleXMLRPCServer.py`::

    server = SimpleXMLRPCServer(("localhost", 8000))
    server.register_function(pow)
    server.register_function(lambda x,y: x+y, 'add')
    server.register_multicall_functions()
    server.serve_forever()

This demo server can be run from the command line as::

    python -m SimpleXMLRPCServer

Example client code which talks to the above server is included with
`Lib/xmlrpclib.py`::

    server = ServerProxy("http://localhost:8000")
    print server
    multi = MultiCall(server)
    multi.pow(2, 9)
    multi.add(5, 1)
    multi.add(24, 11)
    try:
        for response in multi():
            print response
    except Error, v:
        print "ERROR", v

And the client can be invoked directly using the following command::

    python -m xmlrpclib


CGIXMLRPCRequestHandler
-----------------------

The :class:`CGIXMLRPCRequestHandler` class can be used to  handle XML-RPC
requests sent to Python CGI scripts.


.. method:: CGIXMLRPCRequestHandler.register_function(function[, name])

   Register a function that can respond to XML-RPC requests. If  *name* is given,
   it will be the method name associated with  function, otherwise
   *function.__name__* will be used. *name* can be either a normal or Unicode
   string, and may contain  characters not legal in Python identifiers, including
   the period character.


.. method:: CGIXMLRPCRequestHandler.register_instance(instance)

   Register an object which is used to expose method names  which have not been
   registered using :meth:`register_function`. If  instance contains a
   :meth:`_dispatch` method, it is called with the  requested method name and the
   parameters from the  request; the return value is returned to the client as the
   result. If instance does not have a :meth:`_dispatch` method, it is searched
   for an attribute matching the name of the requested method; if  the requested
   method name contains periods, each  component of the method name is searched for
   individually,  with the effect that a simple hierarchical search is performed.
   The value found from this search is then called with the  parameters from the
   request, and the return value is passed  back to the client.


.. method:: CGIXMLRPCRequestHandler.register_introspection_functions()

   Register the XML-RPC introspection functions  ``system.listMethods``,
   ``system.methodHelp`` and  ``system.methodSignature``.


.. method:: CGIXMLRPCRequestHandler.register_multicall_functions()

   Register the XML-RPC multicall function ``system.multicall``.


.. method:: CGIXMLRPCRequestHandler.handle_request([request_text = None])

   Handle an XML-RPC request. If *request_text* is given, it should be the POST
   data provided by the HTTP server,  otherwise the contents of stdin will be used.

Example::

   class MyFuncs:
       def div(self, x, y): return x // y


   handler = CGIXMLRPCRequestHandler()
   handler.register_function(pow)
   handler.register_function(lambda x,y: x+y, 'add')
   handler.register_introspection_functions()
   handler.register_instance(MyFuncs())
   handler.handle_request()

PK
%�\٣6���"html/_sources/library/site.rst.txtnu�[���:mod:`site` --- Site-specific configuration hook
================================================

.. module:: site
   :synopsis: Module responsible for site-specific configuration.

**Source code:** :source:`Lib/site.py`

--------------

.. highlightlang:: none

**This module is automatically imported during initialization.** The automatic
import can be suppressed using the interpreter's :option:`-S` option.

.. index:: triple: module; search; path

Importing this module will append site-specific paths to the module search path
and add a few builtins.

.. index::
   pair: site-python; directory
   pair: site-packages; directory

It starts by constructing up to four directories from a head and a tail part.
For the head part, it uses ``sys.prefix`` and ``sys.exec_prefix``; empty heads
are skipped.  For the tail part, it uses the empty string and then
:file:`lib/site-packages` (on Windows) or
:file:`lib/python{X.Y}/site-packages` and then :file:`lib/site-python` (on
Unix and Macintosh).  For each of the distinct head-tail combinations, it sees
if it refers to an existing directory, and if so, adds it to ``sys.path`` and
also inspects the newly added path for configuration files.

A path configuration file is a file whose name has the form :file:`{name}.pth`
and exists in one of the four directories mentioned above; its contents are
additional items (one per line) to be added to ``sys.path``.  Non-existing items
are never added to ``sys.path``, and no check is made that the item refers to a
directory rather than a file.  No item is added to ``sys.path`` more than
once.  Blank lines and lines beginning with ``#`` are skipped.  Lines starting
with ``import`` (followed by space or tab) are executed.

.. versionchanged:: 2.6
   A space or tab is now required after the import keyword.

.. index::
   single: package
   triple: path; configuration; file

For example, suppose ``sys.prefix`` and ``sys.exec_prefix`` are set to
:file:`/usr/local`.  The Python X.Y library is then installed in
:file:`/usr/local/lib/python{X.Y}`.  Suppose this has
a subdirectory :file:`/usr/local/lib/python{X.Y}/site-packages` with three
subsubdirectories, :file:`foo`, :file:`bar` and :file:`spam`, and two path
configuration files, :file:`foo.pth` and :file:`bar.pth`.  Assume
:file:`foo.pth` contains the following::

   # foo package configuration

   foo
   bar
   bletch

and :file:`bar.pth` contains::

   # bar package configuration

   bar

Then the following version-specific directories are added to
``sys.path``, in this order::

   /usr/local/lib/pythonX.Y/site-packages/bar
   /usr/local/lib/pythonX.Y/site-packages/foo

Note that :file:`bletch` is omitted because it doesn't exist; the :file:`bar`
directory precedes the :file:`foo` directory because :file:`bar.pth` comes
alphabetically before :file:`foo.pth`; and :file:`spam` is omitted because it is
not mentioned in either path configuration file.

.. index:: module: sitecustomize

After these path manipulations, an attempt is made to import a module named
:mod:`sitecustomize`, which can perform arbitrary site-specific customizations.
It is typically created by a system administrator in the site-packages
directory.  If this import fails with an :exc:`ImportError` exception, it is
silently ignored.  If Python is started without output streams available, as
with :file:`pythonw.exe` on Windows (which is used by default to start IDLE),
attempted output from :mod:`sitecustomize` is ignored. Any exception other
than :exc:`ImportError` causes a silent and perhaps mysterious failure of the
process.

.. index:: module: usercustomize

After this, an attempt is made to import a module named :mod:`usercustomize`,
which can perform arbitrary user-specific customizations, if
:data:`ENABLE_USER_SITE` is true.  This file is intended to be created in the
user site-packages directory (see below), which is part of ``sys.path`` unless
disabled by :option:`-s`.  An :exc:`ImportError` will be silently ignored.

Note that for some non-Unix systems, ``sys.prefix`` and ``sys.exec_prefix`` are
empty, and the path manipulations are skipped; however the import of
:mod:`sitecustomize` and :mod:`usercustomize` is still attempted.


.. data:: PREFIXES

   A list of prefixes for site-packages directories.

   .. versionadded:: 2.6


.. data:: ENABLE_USER_SITE

   Flag showing the status of the user site-packages directory.  ``True`` means
   that it is enabled and was added to ``sys.path``.  ``False`` means that it
   was disabled by user request (with :option:`-s` or
   :envvar:`PYTHONNOUSERSITE`).  ``None`` means it was disabled for security
   reasons (mismatch between user or group id and effective id) or by an
   administrator.

   .. versionadded:: 2.6


.. data:: USER_SITE

   Path to the user site-packages for the running Python.  Can be ``None`` if
   :func:`getusersitepackages` hasn't been called yet.  Default value is
   :file:`~/.local/lib/python{X.Y}/site-packages` for UNIX and non-framework Mac
   OS X builds, :file:`~/Library/Python/{X.Y}/lib/python/site-packages` for Mac
   framework builds, and :file:`{%APPDATA%}\\Python\\Python{XY}\\site-packages`
   on Windows.  This directory is a site directory, which means that
   :file:`.pth` files in it will be processed.

   .. versionadded:: 2.6


.. data:: USER_BASE

   Path to the base directory for the user site-packages.  Can be ``None`` if
   :func:`getuserbase` hasn't been called yet.  Default value is
   :file:`~/.local` for UNIX and Mac OS X non-framework builds,
   :file:`~/Library/Python/{X.Y}` for Mac framework builds, and
   :file:`{%APPDATA%}\\Python` for Windows.  This value is used by Distutils to
   compute the installation directories for scripts, data files, Python modules,
   etc. for the :ref:`user installation scheme <inst-alt-install-user>`.  See
   also :envvar:`PYTHONUSERBASE`.

   .. versionadded:: 2.6


.. function:: addsitedir(sitedir, known_paths=None)

   Add a directory to sys.path and process its :file:`.pth` files.  Typically
   used in :mod:`sitecustomize` or :mod:`usercustomize` (see above).


.. function:: getsitepackages()

   Return a list containing all global site-packages directories (and possibly
   site-python).

   .. versionadded:: 2.7


.. function:: getuserbase()

   Return the path of the user base directory, :data:`USER_BASE`.  If it is not
   initialized yet, this function will also set it, respecting
   :envvar:`PYTHONUSERBASE`.

   .. versionadded:: 2.7


.. function:: getusersitepackages()

   Return the path of the user-specific site-packages directory,
   :data:`USER_SITE`.  If it is not initialized yet, this function will also set
   it, respecting :envvar:`PYTHONNOUSERSITE` and :data:`USER_BASE`.

   .. versionadded:: 2.7


The :mod:`site` module also provides a way to get the user directories from the
command line:

.. code-block:: sh

   $ python -m site --user-site
   /home/user/.local/lib/python2.7/site-packages

.. program:: site

If it is called without arguments, it will print the contents of
:data:`sys.path` on the standard output, followed by the value of
:data:`USER_BASE` and whether the directory exists, then the same thing for
:data:`USER_SITE`, and finally the value of :data:`ENABLE_USER_SITE`.

.. cmdoption:: --user-base

   Print the path to the user base directory.

.. cmdoption:: --user-site

   Print the path to the user site-packages directory.

If both options are given, user base and user site will be printed (always in
this order), separated by :data:`os.pathsep`.

If any option is given, the script will exit with one of these values: ``0`` if
the user site-packages directory is enabled, ``1`` if it was disabled by the
user, ``2`` if it is disabled for security reasons or by an administrator, and a
value greater than 2 if there is an error.

.. seealso::

   :pep:`370` -- Per user site-packages directory
PK
%�\�4�2�	�	#html/_sources/library/smtpd.rst.txtnu�[���:mod:`smtpd` --- SMTP Server
============================

.. module:: smtpd
   :synopsis: A SMTP server implementation in Python.

.. moduleauthor:: Barry Warsaw <barry@zope.com>
.. sectionauthor:: Moshe Zadka <moshez@moshez.org>

**Source code:** :source:`Lib/smtpd.py`

--------------

This module offers several classes to implement SMTP servers.  One is a generic
do-nothing implementation, which can be overridden, while the other two offer
specific mail-sending strategies.


SMTPServer Objects
------------------


.. class:: SMTPServer(localaddr, remoteaddr)

   Create a new :class:`SMTPServer` object, which binds to local address
   *localaddr*.  It will treat *remoteaddr* as an upstream SMTP relayer.  Both
   *localaddr* and *remoteaddr* should be a :ref:`(host, port) <host_port>`
   tuple.  The object inherits from :class:`asyncore.dispatcher`, and so will
   insert itself into :mod:`asyncore`'s event loop on instantiation.


   .. method:: process_message(peer, mailfrom, rcpttos, data)

      Raise :exc:`NotImplementedError` exception. Override this in subclasses to
      do something useful with this message. Whatever was passed in the
      constructor as *remoteaddr* will be available as the :attr:`_remoteaddr`
      attribute. *peer* is the remote host's address, *mailfrom* is the envelope
      originator, *rcpttos* are the envelope recipients and *data* is a string
      containing the contents of the e-mail (which should be in :rfc:`2822`
      format).


DebuggingServer Objects
-----------------------


.. class:: DebuggingServer(localaddr, remoteaddr)

   Create a new debugging server.  Arguments are as per :class:`SMTPServer`.
   Messages will be discarded, and printed on stdout.


PureProxy Objects
-----------------


.. class:: PureProxy(localaddr, remoteaddr)

   Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
   Everything will be relayed to *remoteaddr*.  Note that running this has a good
   chance to make you into an open relay, so please be careful.


MailmanProxy Objects
--------------------


.. class:: MailmanProxy(localaddr, remoteaddr)

   Create a new pure proxy server. Arguments are as per :class:`SMTPServer`.
   Everything will be relayed to *remoteaddr*, unless local mailman configurations
   knows about an address, in which case it will be handled via mailman.  Note that
   running this has a good chance to make you into an open relay, so please be
   careful.

PK
%�\v::::%html/_sources/library/smtplib.rst.txtnu�[���:mod:`smtplib` --- SMTP protocol client
=======================================

.. module:: smtplib
   :synopsis: SMTP protocol client (requires sockets).
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>


.. index::
   pair: SMTP; protocol
   single: Simple Mail Transfer Protocol

**Source code:** :source:`Lib/smtplib.py`

--------------

The :mod:`smtplib` module defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon.  For
details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer
Protocol) and :rfc:`1869` (SMTP Service Extensions).


.. class:: SMTP([host[, port[, local_hostname[, timeout]]]])

   An :class:`SMTP` instance encapsulates an SMTP connection.  It has methods
   that support a full repertoire of SMTP and ESMTP operations. If the optional
   host and port parameters are given, the SMTP :meth:`connect` method is
   called with those parameters during initialization.  If specified,
   *local_hostname* is used as the FQDN of the local host in the HELO/EHLO
   command.  Otherwise, the local hostname is found using
   :func:`socket.getfqdn`.  If the :meth:`connect` call returns anything other
   than a success code, an :exc:`SMTPConnectError` is raised. The optional
   *timeout* parameter specifies a timeout in seconds for blocking operations
   like the connection attempt (if not specified, the global default timeout
   setting will be used).  If the timeout expires, :exc:`socket.timeout`
   is raised.

   For normal use, you should only require the initialization/connect,
   :meth:`sendmail`, and :meth:`SMTP.quit` methods.
   An example is included below.

   .. versionchanged:: 2.6
      *timeout* was added.


.. class:: SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]])

   An :class:`SMTP_SSL` instance behaves exactly the same as instances of
   :class:`SMTP`. :class:`SMTP_SSL` should be used for situations where SSL is
   required from the beginning of the connection and using :meth:`starttls` is
   not appropriate. If *host* is not specified, the local host is used. If
   *port* is omitted, the standard SMTP-over-SSL port (465) is used.
   *local_hostname* has the same meaning as it does for the :class:`SMTP`
   class.  *keyfile* and *certfile* are also optional, and can contain a PEM
   formatted private key and certificate chain file for the SSL connection. The
   optional *timeout* parameter specifies a timeout in seconds for blocking
   operations like the connection attempt (if not specified, the global default
   timeout setting will be used).  If the timeout expires, :exc:`socket.timeout`
   is raised.

   .. versionadded:: 2.6


.. class:: LMTP([host[, port[, local_hostname]]])

   The LMTP protocol, which is very similar to ESMTP, is heavily based on the
   standard SMTP client. It's common to use Unix sockets for LMTP, so our
   :meth:`connect` method must support that as well as a regular host:port
   server.  *local_hostname* has the same meaning as it does for the
   :class:`SMTP` class.  To specify a Unix socket, you must use an absolute
   path for *host*, starting with a '/'.

   Authentication is supported, using the regular SMTP mechanism. When using a
   Unix socket, LMTP generally don't support or require any authentication, but
   your mileage might vary.

   .. versionadded:: 2.6

A nice selection of exceptions is defined as well:


.. exception:: SMTPException

   The base exception class for all the other exceptions provided by this
   module.


.. exception:: SMTPServerDisconnected

   This exception is raised when the server unexpectedly disconnects, or when an
   attempt is made to use the :class:`SMTP` instance before connecting it to a
   server.


.. exception:: SMTPResponseException

   Base class for all exceptions that include an SMTP error code. These exceptions
   are generated in some instances when the SMTP server returns an error code.  The
   error code is stored in the :attr:`smtp_code` attribute of the error, and the
   :attr:`smtp_error` attribute is set to the error message.


.. exception:: SMTPSenderRefused

   Sender address refused.  In addition to the attributes set by on all
   :exc:`SMTPResponseException` exceptions, this sets 'sender' to the string that
   the SMTP server refused.


.. exception:: SMTPRecipientsRefused

   All recipient addresses refused.  The errors for each recipient are accessible
   through the attribute :attr:`recipients`, which is a dictionary of exactly the
   same sort as :meth:`SMTP.sendmail` returns.


.. exception:: SMTPDataError

   The SMTP server refused to accept the message data.


.. exception:: SMTPConnectError

   Error occurred during establishment of a connection  with the server.


.. exception:: SMTPHeloError

   The server refused our ``HELO`` message.


.. exception:: SMTPAuthenticationError

   SMTP authentication went wrong.  Most probably the server didn't accept the
   username/password combination provided.


.. seealso::

   :rfc:`821` - Simple Mail Transfer Protocol
      Protocol definition for SMTP.  This document covers the model, operating
      procedure, and protocol details for SMTP.

   :rfc:`1869` - SMTP Service Extensions
      Definition of the ESMTP extensions for SMTP.  This describes a framework for
      extending SMTP with new commands, supporting dynamic discovery of the commands
      provided by the server, and defines a few additional commands.


.. _smtp-objects:

SMTP Objects
------------

An :class:`SMTP` instance has the following methods:


.. method:: SMTP.set_debuglevel(level)

   Set the debug output level.  A true value for *level* results in debug messages
   for connection and for all messages sent to and received from the server.


.. method:: SMTP.docmd(cmd, [, argstring])

   Send a command *cmd* to the server.  The optional argument *argstring* is simply
   concatenated to the command, separated by a space.

   This returns a 2-tuple composed of a numeric response code and the actual
   response line (multiline responses are joined into one long line.)

   In normal operation it should not be necessary to call this method explicitly.
   It is used to implement other methods and may be useful for testing private
   extensions.

   If the connection to the server is lost while waiting for the reply,
   :exc:`SMTPServerDisconnected` will be raised.


.. method:: SMTP.connect([host[, port]])

   Connect to a host on a given port.  The defaults are to connect to the local
   host at the standard SMTP port (25). If the hostname ends with a colon (``':'``)
   followed by a number, that suffix will be stripped off and the number
   interpreted as the port number to use. This method is automatically invoked by
   the constructor if a host is specified during instantiation.  Returns a
   2-tuple of the response code and message sent by the server in its
   connection response.


.. method:: SMTP.helo([hostname])

   Identify yourself to the SMTP server using ``HELO``.  The hostname argument
   defaults to the fully qualified domain name of the local host.
   The message returned by the server is stored as the :attr:`helo_resp` attribute
   of the object.

   In normal operation it should not be necessary to call this method explicitly.
   It will be implicitly called by the :meth:`sendmail` when necessary.


.. method:: SMTP.ehlo([hostname])

   Identify yourself to an ESMTP server using ``EHLO``.  The hostname argument
   defaults to the fully qualified domain name of the local host.  Examine the
   response for ESMTP option and store them for use by :meth:`has_extn`.
   Also sets several informational attributes: the message returned by
   the server is stored as the :attr:`ehlo_resp` attribute, :attr:`does_esmtp`
   is set to true or false depending on whether the server supports ESMTP, and
   :attr:`esmtp_features` will be a dictionary containing the names of the
   SMTP service extensions this server supports, and their
   parameters (if any).

   Unless you wish to use :meth:`has_extn` before sending mail, it should not be
   necessary to call this method explicitly.  It will be implicitly called by
   :meth:`sendmail` when necessary.

.. method:: SMTP.ehlo_or_helo_if_needed()

   This method call :meth:`ehlo` and or :meth:`helo` if there has been no
   previous ``EHLO`` or ``HELO`` command this session.  It tries ESMTP ``EHLO``
   first.

   :exc:`SMTPHeloError`
     The server didn't reply properly to the ``HELO`` greeting.

   .. versionadded:: 2.6

.. method:: SMTP.has_extn(name)

   Return :const:`True` if *name* is in the set of SMTP service extensions returned
   by the server, :const:`False` otherwise. Case is ignored.


.. method:: SMTP.verify(address)

   Check the validity of an address on this server using SMTP ``VRFY``. Returns a
   tuple consisting of code 250 and a full :rfc:`822` address (including human
   name) if the user address is valid. Otherwise returns an SMTP error code of 400
   or greater and an error string.

   .. note::

      Many sites disable SMTP ``VRFY`` in order to foil spammers.


.. method:: SMTP.login(user, password)

   Log in on an SMTP server that requires authentication. The arguments are the
   username and the password to authenticate with. If there has been no previous
   ``EHLO`` or ``HELO`` command this session, this method tries ESMTP ``EHLO``
   first. This method will return normally if the authentication was successful, or
   may raise the following exceptions:

   :exc:`SMTPHeloError`
      The server didn't reply properly to the ``HELO`` greeting.

   :exc:`SMTPAuthenticationError`
      The server didn't accept the username/password combination.

   :exc:`SMTPException`
      No suitable authentication method was found.


.. method:: SMTP.starttls([keyfile[, certfile]])

   Put the SMTP connection in TLS (Transport Layer Security) mode.  All SMTP
   commands that follow will be encrypted.  You should then call :meth:`ehlo`
   again.

   If *keyfile* and *certfile* are provided, these are passed to the :mod:`socket`
   module's :func:`ssl` function.

   If there has been no previous ``EHLO`` or ``HELO`` command this session,
   this method tries ESMTP ``EHLO`` first.

   .. versionchanged:: 2.6

   :exc:`SMTPHeloError`
      The server didn't reply properly to the ``HELO`` greeting.

   :exc:`SMTPException`
     The server does not support the STARTTLS extension.

   .. versionchanged:: 2.6

   :exc:`RuntimeError`
     SSL/TLS support is not available to your Python interpreter.


.. method:: SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])

   Send mail.  The required arguments are an :rfc:`822` from-address string, a list
   of :rfc:`822` to-address strings (a bare string will be treated as a list with 1
   address), and a message string.  The caller may pass a list of ESMTP options
   (such as ``8bitmime``) to be used in ``MAIL FROM`` commands as *mail_options*.
   ESMTP options (such as ``DSN`` commands) that should be used with all ``RCPT``
   commands can be passed as *rcpt_options*.  (If you need to use different ESMTP
   options to different recipients you have to use the low-level methods such as
   :meth:`mail`, :meth:`rcpt` and :meth:`data` to send the message.)

   .. note::

      The *from_addr* and *to_addrs* parameters are used to construct the message
      envelope used by the transport agents. The :class:`SMTP` does not modify the
      message headers in any way.

   If there has been no previous ``EHLO`` or ``HELO`` command this session, this
   method tries ESMTP ``EHLO`` first. If the server does ESMTP, message size and
   each of the specified options will be passed to it (if the option is in the
   feature set the server advertises).  If ``EHLO`` fails, ``HELO`` will be tried
   and ESMTP options suppressed.

   This method will return normally if the mail is accepted for at least one
   recipient. Otherwise it will raise an exception.  That is, if this method does
   not raise an exception, then someone should get your mail. If this method does
   not raise an exception, it returns a dictionary, with one entry for each
   recipient that was refused.  Each entry contains a tuple of the SMTP error code
   and the accompanying error message sent by the server.

   This method may raise the following exceptions:

   :exc:`SMTPRecipientsRefused`
      All recipients were refused.  Nobody got the mail.  The :attr:`recipients`
      attribute of the exception object is a dictionary with information about the
      refused recipients (like the one returned when at least one recipient was
      accepted).

   :exc:`SMTPHeloError`
      The server didn't reply properly to the ``HELO`` greeting.

   :exc:`SMTPSenderRefused`
      The server didn't accept the *from_addr*.

   :exc:`SMTPDataError`
      The server replied with an unexpected error code (other than a refusal of a
      recipient).

   Unless otherwise noted, the connection will be open even after an exception is
   raised.


.. method:: SMTP.quit()

   Terminate the SMTP session and close the connection.  Return the result of
   the SMTP ``QUIT`` command.

   .. versionchanged:: 2.6
      Return a value.


Low-level methods corresponding to the standard SMTP/ESMTP commands ``HELP``,
``RSET``, ``NOOP``, ``MAIL``, ``RCPT``, and ``DATA`` are also supported.
Normally these do not need to be called directly, so they are not documented
here.  For details, consult the module code.


.. _smtp-example:

SMTP Example
------------

This example prompts the user for addresses needed in the message envelope ('To'
and 'From' addresses), and the message to be delivered.  Note that the headers
to be included with the message must be included in the message as entered; this
example doesn't do any processing of the :rfc:`822` headers.  In particular, the
'To' and 'From' addresses must be included in the message headers explicitly. ::

   import smtplib

   def prompt(prompt):
       return raw_input(prompt).strip()

   fromaddr = prompt("From: ")
   toaddrs  = prompt("To: ").split()
   print "Enter message, end with ^D (Unix) or ^Z (Windows):"

   # Add the From: and To: headers at the start!
   msg = ("From: %s\r\nTo: %s\r\n\r\n"
          % (fromaddr, ", ".join(toaddrs)))
   while 1:
       try:
           line = raw_input()
       except EOFError:
           break
       if not line:
           break
       msg = msg + line

   print "Message length is " + repr(len(msg))

   server = smtplib.SMTP('localhost')
   server.set_debuglevel(1)
   server.sendmail(fromaddr, toaddrs, msg)
   server.quit()

.. note::

   In general, you will want to use the :mod:`email` package's features to
   construct an email message, which you can then convert to a string and send
   via :meth:`sendmail`; see :ref:`email-examples`.
PK
%�\����$html/_sources/library/sndhdr.rst.txtnu�[���:mod:`sndhdr` --- Determine type of sound file
==============================================

.. module:: sndhdr
   :synopsis: Determine type of a sound file.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. Based on comments in the module source file.

.. index::
   single: A-LAW
   single: u-LAW

**Source code:** :source:`Lib/sndhdr.py`

--------------

The :mod:`sndhdr` provides utility functions which attempt to determine the type
of sound data which is in a file.  When these functions are able to determine
what type of sound data is stored in a file, they return a tuple ``(type,
sampling_rate, channels, frames, bits_per_sample)``.  The value for *type*
indicates the data type and will be one of the strings ``'aifc'``, ``'aiff'``,
``'au'``, ``'hcom'``, ``'sndr'``, ``'sndt'``, ``'voc'``, ``'wav'``, ``'8svx'``,
``'sb'``, ``'ub'``, or ``'ul'``.  The *sampling_rate* will be either the actual
value or ``0`` if unknown or difficult to decode.  Similarly, *channels* will be
either the number of channels or ``0`` if it cannot be determined or if the
value is difficult to decode.  The value for *frames* will be either the number
of frames or ``-1``.  The last item in the tuple, *bits_per_sample*, will either
be the sample size in bits or ``'A'`` for A-LAW or ``'U'`` for u-LAW.


.. function:: what(filename)

   Determines the type of sound data stored in the file *filename* using
   :func:`whathdr`.  If it succeeds, returns a tuple as described above, otherwise
   ``None`` is returned.


.. function:: whathdr(filename)

   Determines the type of sound data stored in a file based on the file  header.
   The name of the file is given by *filename*.  This function returns a tuple as
   described above on success, or ``None``.

PK
%�\<��G=�=�$html/_sources/library/socket.rst.txtnu�[���:mod:`socket` --- Low-level networking interface
================================================

.. module:: socket
   :synopsis: Low-level networking interface.


This module provides access to the BSD *socket* interface. It is available on
all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional
platforms.

.. note::

   Some behavior may be platform dependent, since calls are made to the operating
   system socket APIs.

For an introduction to socket programming (in C), see the following papers: An
Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and
An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J.  Leffler et
al, both in the UNIX Programmer's Manual, Supplementary Documents 1 (sections
PS1:7 and PS1:8).  The platform-specific reference material for the various
socket-related system calls are also a valuable source of information on the
details of socket semantics.  For Unix, refer to the manual pages; for Windows,
see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.

.. index:: object: socket

The Python interface is a straightforward transliteration of the Unix system
call and library interface for sockets to Python's object-oriented style: the
:func:`.socket` function returns a :dfn:`socket object` whose methods implement
the various socket system calls.  Parameter types are somewhat higher-level than
in the C interface: as with :meth:`read` and :meth:`write` operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
is implicit on send operations.

.. _host_port:

Socket addresses are represented as follows: A single string is used for the
:const:`AF_UNIX` address family. A pair ``(host, port)`` is used for the
:const:`AF_INET` address family, where *host* is a string representing either a
hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address
like ``'100.50.200.5'``, and *port* is an integer. For
:const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo``
and ``sin6_scope_id`` member in :const:`struct sockaddr_in6` in C. For
:mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
backward compatibility. Note, however, omission of *scopeid* can cause problems
in manipulating scoped IPv6 addresses. Other address families are currently not
supported. The address format required by a particular socket object is
automatically selected based on the address family specified when the socket
object was created.

For IPv4 addresses, two special forms are accepted instead of a host address:
the empty string represents :const:`INADDR_ANY`, and the string
``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. The behavior is not
available for IPv6 for backward compatibility, therefore, you may want to avoid
these if you intend to support IPv6 with your Python programs.

If you use a hostname in the *host* portion of IPv4/v6 socket address, the
program may show a nondeterministic behavior, as Python uses the first address
returned from the DNS resolution.  The socket address will be resolved
differently into an actual IPv4/v6 address, depending on the results from DNS
resolution and/or the host configuration.  For deterministic behavior use a
numeric address in *host* portion.

.. versionadded:: 2.5
   AF_NETLINK sockets are represented as  pairs ``pid, groups``.

.. versionadded:: 2.6
   Linux-only support for TIPC is also available using the :const:`AF_TIPC`
   address family. TIPC is an open, non-IP based networked protocol designed
   for use in clustered computer environments.  Addresses are represented by a
   tuple, and the fields depend on the address type. The general tuple form is
   ``(addr_type, v1, v2, v3 [, scope])``, where:

   - *addr_type* is one of :const:`TIPC_ADDR_NAMESEQ`, :const:`TIPC_ADDR_NAME`,
     or :const:`TIPC_ADDR_ID`.
   - *scope* is one of :const:`TIPC_ZONE_SCOPE`, :const:`TIPC_CLUSTER_SCOPE`,
     and :const:`TIPC_NODE_SCOPE`.
   - If *addr_type* is :const:`TIPC_ADDR_NAME`, then *v1* is the server type, *v2* is
     the port identifier, and *v3* should be 0.

     If *addr_type* is :const:`TIPC_ADDR_NAMESEQ`, then *v1* is the server type, *v2*
     is the lower port number, and *v3* is the upper port number.

     If *addr_type* is :const:`TIPC_ADDR_ID`, then *v1* is the node, *v2* is the
     reference, and *v3* should be set to 0.


All errors raise exceptions.  The normal exceptions for invalid argument types
and out-of-memory conditions can be raised; errors related to socket or address
semantics raise the error :exc:`socket.error`.

Non-blocking mode is supported through :meth:`~socket.setblocking`.  A
generalization of this based on timeouts is supported through
:meth:`~socket.settimeout`.

The module :mod:`socket` exports the following constants and functions:


.. exception:: error

   .. index:: module: errno

   This exception is raised for socket-related errors. The accompanying value is
   either a string telling what went wrong or a pair ``(errno, string)``
   representing an error returned by a system call, similar to the value
   accompanying :exc:`os.error`. See the module :mod:`errno`, which contains names
   for the error codes defined by the underlying operating system.

   .. versionchanged:: 2.6
      :exc:`socket.error` is now a child class of :exc:`IOError`.


.. exception:: herror

   This exception is raised for address-related errors, i.e. for functions that use
   *h_errno* in the C API, including :func:`gethostbyname_ex` and
   :func:`gethostbyaddr`.

   The accompanying value is a pair ``(h_errno, string)`` representing an error
   returned by a library call. *string* represents the description of *h_errno*, as
   returned by the :c:func:`hstrerror` C function.


.. exception:: gaierror

   This exception is raised for address-related errors, for :func:`getaddrinfo` and
   :func:`getnameinfo`. The accompanying value is a pair ``(error, string)``
   representing an error returned by a library call. *string* represents the
   description of *error*, as returned by the :c:func:`gai_strerror` C function. The
   *error* value will match one of the :const:`EAI_\*` constants defined in this
   module.


.. exception:: timeout

   This exception is raised when a timeout occurs on a socket which has had
   timeouts enabled via a prior call to :meth:`settimeout`.  The accompanying value
   is a string whose value is currently always "timed out".

   .. versionadded:: 2.3


.. data:: AF_UNIX
          AF_INET
          AF_INET6

   These constants represent the address (and protocol) families, used for the
   first argument to :func:`.socket`.  If the :const:`AF_UNIX` constant is not
   defined then this protocol is unsupported.


.. data:: SOCK_STREAM
          SOCK_DGRAM
          SOCK_RAW
          SOCK_RDM
          SOCK_SEQPACKET

   These constants represent the socket types, used for the second argument to
   :func:`socket`. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be
   generally useful.)


.. data:: SO_*
          SOMAXCONN
          MSG_*
          SOL_*
          IPPROTO_*
          IPPORT_*
          INADDR_*
          IP_*
          IPV6_*
          EAI_*
          AI_*
          NI_*
          TCP_*

   Many constants of these forms, documented in the Unix documentation on sockets
   and/or the IP protocol, are also defined in the socket module. They are
   generally used in arguments to the :meth:`setsockopt` and :meth:`getsockopt`
   methods of socket objects.  In most cases, only those symbols that are defined
   in the Unix header files are defined; for a few symbols, default values are
   provided.

.. data:: SIO_*
          RCVALL_*

   Constants for Windows' WSAIoctl(). The constants are used as arguments to the
   :meth:`~socket.socket.ioctl` method of socket objects.

   .. versionadded:: 2.6

.. data:: TIPC_*

   TIPC related constants, matching the ones exported by the C socket API. See
   the TIPC documentation for more information.

   .. versionadded:: 2.6

.. data:: has_ipv6

   This constant contains a boolean value which indicates if IPv6 is supported on
   this platform.

   .. versionadded:: 2.3


.. function:: create_connection(address[, timeout[, source_address]])

   Connect to a TCP service listening on the Internet *address* (a 2-tuple
   ``(host, port)``), and return the socket object.  This is a higher-level
   function than :meth:`socket.connect`: if *host* is a non-numeric hostname,
   it will try to resolve it for both :data:`AF_INET` and :data:`AF_INET6`,
   and then try to connect to all possible addresses in turn until a
   connection succeeds.  This makes it easy to write clients that are
   compatible to both IPv4 and IPv6.

   Passing the optional *timeout* parameter will set the timeout on the
   socket instance before attempting to connect.  If no *timeout* is
   supplied, the global default timeout setting returned by
   :func:`getdefaulttimeout` is used.

   If supplied, *source_address* must be a 2-tuple ``(host, port)`` for the
   socket to bind to as its source address before connecting.  If host or port
   are '' or 0 respectively the OS default behavior will be used.

   .. versionadded:: 2.6

   .. versionchanged:: 2.7
      *source_address* was added.


.. function:: getaddrinfo(host, port[, family[, socktype[, proto[, flags]]]])

   Translate the *host*/*port* argument into a sequence of 5-tuples that contain
   all the necessary arguments for creating a socket connected to that service.
   *host* is a domain name, a string representation of an IPv4/v6 address
   or ``None``. *port* is a string service name such as ``'http'``, a numeric
   port number or ``None``.  By passing ``None`` as the value of *host*
   and *port*, you can pass ``NULL`` to the underlying C API.

   The *family*, *socktype* and *proto* arguments can be optionally specified
   in order to narrow the list of addresses returned.  By default, their value
   is ``0``, meaning that the full range of results is selected.
   The *flags* argument can be one or several of the ``AI_*`` constants,
   and will influence how results are computed and returned.  Its default value
   is ``0``.  For example, :const:`AI_NUMERICHOST` will disable domain name
   resolution and will raise an error if *host* is a domain name.

   The function returns a list of 5-tuples with the following structure:

   ``(family, socktype, proto, canonname, sockaddr)``

   In these tuples, *family*, *socktype*, *proto* are all integers and are
   meant to be passed to the :func:`.socket` function.  *canonname* will be
   a string representing the canonical name of the *host* if
   :const:`AI_CANONNAME` is part of the *flags* argument; else *canonname*
   will be empty.  *sockaddr* is a tuple describing a socket address, whose
   format depends on the returned *family* (a ``(address, port)`` 2-tuple for
   :const:`AF_INET`, a ``(address, port, flow info, scope id)`` 4-tuple for
   :const:`AF_INET6`), and is meant to be passed to the :meth:`socket.connect`
   method.

   The following example fetches address information for a hypothetical TCP
   connection to ``example.org`` on port 80 (results may differ on your
   system if IPv6 isn't enabled)::

      >>> socket.getaddrinfo("example.org", 80, 0, 0, socket.IPPROTO_TCP)
      [(10, 1, 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),
       (2, 1, 6, '', ('93.184.216.34', 80))]

   .. versionadded:: 2.2


.. function:: getfqdn([name])

   Return a fully qualified domain name for *name*. If *name* is omitted or empty,
   it is interpreted as the local host.  To find the fully qualified name, the
   hostname returned by :func:`gethostbyaddr` is checked, followed by aliases for the
   host, if available.  The first name which includes a period is selected.  In
   case no fully qualified domain name is available, the hostname as returned by
   :func:`gethostname` is returned.

   .. versionadded:: 2.0


.. function:: gethostbyname(hostname)

   Translate a host name to IPv4 address format.  The IPv4 address is returned as a
   string, such as  ``'100.50.200.5'``.  If the host name is an IPv4 address itself
   it is returned unchanged.  See :func:`gethostbyname_ex` for a more complete
   interface. :func:`gethostbyname` does not support IPv6 name resolution, and
   :func:`getaddrinfo` should be used instead for IPv4/v6 dual stack support.


.. function:: gethostbyname_ex(hostname)

   Translate a host name to IPv4 address format, extended interface. Return a
   triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the primary
   host name responding to the given *ip_address*, *aliaslist* is a (possibly
   empty) list of alternative host names for the same address, and *ipaddrlist* is
   a list of IPv4 addresses for the same interface on the same host (often but not
   always a single address). :func:`gethostbyname_ex` does not support IPv6 name
   resolution, and :func:`getaddrinfo` should be used instead for IPv4/v6 dual
   stack support.


.. function:: gethostname()

   Return a string containing the hostname of the machine where  the Python
   interpreter is currently executing.

   If you want to know the current machine's IP address, you may want to use
   ``gethostbyname(gethostname())``. This operation assumes that there is a
   valid address-to-host mapping for the host, and the assumption does not
   always hold.

   Note: :func:`gethostname` doesn't always return the fully qualified domain
   name; use ``getfqdn()`` (see above).


.. function:: gethostbyaddr(ip_address)

   Return a triple ``(hostname, aliaslist, ipaddrlist)`` where *hostname* is the
   primary host name responding to the given *ip_address*, *aliaslist* is a
   (possibly empty) list of alternative host names for the same address, and
   *ipaddrlist* is a list of IPv4/v6 addresses for the same interface on the same
   host (most likely containing only a single address). To find the fully qualified
   domain name, use the function :func:`getfqdn`. :func:`gethostbyaddr` supports
   both IPv4 and IPv6.


.. function:: getnameinfo(sockaddr, flags)

   Translate a socket address *sockaddr* into a 2-tuple ``(host, port)``. Depending
   on the settings of *flags*, the result can contain a fully-qualified domain name
   or numeric address representation in *host*.  Similarly, *port* can contain a
   string port name or a numeric port number.

   .. versionadded:: 2.2


.. function:: getprotobyname(protocolname)

   Translate an Internet protocol name (for example, ``'icmp'``) to a constant
   suitable for passing as the (optional) third argument to the :func:`.socket`
   function.  This is usually only needed for sockets opened in "raw" mode
   (:const:`SOCK_RAW`); for the normal socket modes, the correct protocol is chosen
   automatically if the protocol is omitted or zero.


.. function:: getservbyname(servicename[, protocolname])

   Translate an Internet service name and protocol name to a port number for that
   service.  The optional protocol name, if given, should be ``'tcp'`` or
   ``'udp'``, otherwise any protocol will match.


.. function:: getservbyport(port[, protocolname])

   Translate an Internet port number and protocol name to a service name for that
   service.  The optional protocol name, if given, should be ``'tcp'`` or
   ``'udp'``, otherwise any protocol will match.


.. function:: socket([family[, type[, proto]]])

   Create a new socket using the given address family, socket type and protocol
   number.  The address family should be :const:`AF_INET` (the default),
   :const:`AF_INET6` or :const:`AF_UNIX`.  The socket type should be
   :const:`SOCK_STREAM` (the default), :const:`SOCK_DGRAM` or perhaps one of the
   other ``SOCK_`` constants.  The protocol number is usually zero and may be
   omitted in that case.


.. function:: socketpair([family[, type[, proto]]])

   Build a pair of connected socket objects using the given address family, socket
   type, and protocol number.  Address family, socket type, and protocol number are
   as for the :func:`.socket` function above. The default family is :const:`AF_UNIX`
   if defined on the platform; otherwise, the default is :const:`AF_INET`.
   Availability: Unix.

   .. versionadded:: 2.4


.. function:: fromfd(fd, family, type[, proto])

   Duplicate the file descriptor *fd* (an integer as returned by a file object's
   :meth:`fileno` method) and build a socket object from the result.  Address
   family, socket type and protocol number are as for the :func:`.socket` function
   above. The file descriptor should refer to a socket, but this is not checked ---
   subsequent operations on the object may fail if the file descriptor is invalid.
   This function is rarely needed, but can be used to get or set socket options on
   a socket passed to a program as standard input or output (such as a server
   started by the Unix inet daemon).  The socket is assumed to be in blocking mode.
   Availability: Unix.


.. function:: ntohl(x)

   Convert 32-bit positive integers from network to host byte order.  On machines
   where the host byte order is the same as network byte order, this is a no-op;
   otherwise, it performs a 4-byte swap operation.


.. function:: ntohs(x)

   Convert 16-bit positive integers from network to host byte order.  On machines
   where the host byte order is the same as network byte order, this is a no-op;
   otherwise, it performs a 2-byte swap operation.


.. function:: htonl(x)

   Convert 32-bit positive integers from host to network byte order.  On machines
   where the host byte order is the same as network byte order, this is a no-op;
   otherwise, it performs a 4-byte swap operation.


.. function:: htons(x)

   Convert 16-bit positive integers from host to network byte order.  On machines
   where the host byte order is the same as network byte order, this is a no-op;
   otherwise, it performs a 2-byte swap operation.


.. function:: inet_aton(ip_string)

   Convert an IPv4 address from dotted-quad string format (for example,
   '123.45.67.89') to 32-bit packed binary format, as a string four characters in
   length.  This is useful when conversing with a program that uses the standard C
   library and needs objects of type :c:type:`struct in_addr`, which is the C type
   for the 32-bit packed binary this function returns.

   :func:`inet_aton` also accepts strings with less than three dots; see the
   Unix manual page :manpage:`inet(3)` for details.

   If the IPv4 address string passed to this function is invalid,
   :exc:`socket.error` will be raised. Note that exactly what is valid depends on
   the underlying C implementation of :c:func:`inet_aton`.

   :func:`inet_aton` does not support IPv6, and :func:`inet_pton` should be used
   instead for IPv4/v6 dual stack support.


.. function:: inet_ntoa(packed_ip)

   Convert a 32-bit packed IPv4 address (a string four characters in length) to its
   standard dotted-quad string representation (for example, '123.45.67.89').  This
   is useful when conversing with a program that uses the standard C library and
   needs objects of type :c:type:`struct in_addr`, which is the C type for the
   32-bit packed binary data this function takes as an argument.

   If the string passed to this function is not exactly 4 bytes in length,
   :exc:`socket.error` will be raised. :func:`inet_ntoa` does not support IPv6, and
   :func:`inet_ntop` should be used instead for IPv4/v6 dual stack support.


.. function:: inet_pton(address_family, ip_string)

   Convert an IP address from its family-specific string format to a packed, binary
   format. :func:`inet_pton` is useful when a library or network protocol calls for
   an object of type :c:type:`struct in_addr` (similar to :func:`inet_aton`) or
   :c:type:`struct in6_addr`.

   Supported values for *address_family* are currently :const:`AF_INET` and
   :const:`AF_INET6`. If the IP address string *ip_string* is invalid,
   :exc:`socket.error` will be raised. Note that exactly what is valid depends on
   both the value of *address_family* and the underlying implementation of
   :c:func:`inet_pton`.

   Availability: Unix (maybe not all platforms).

   .. versionadded:: 2.3


.. function:: inet_ntop(address_family, packed_ip)

   Convert a packed IP address (a string of some number of characters) to its
   standard, family-specific string representation (for example, ``'7.10.0.5'`` or
   ``'5aef:2b::8'``) :func:`inet_ntop` is useful when a library or network protocol
   returns an object of type :c:type:`struct in_addr` (similar to :func:`inet_ntoa`)
   or :c:type:`struct in6_addr`.

   Supported values for *address_family* are currently :const:`AF_INET` and
   :const:`AF_INET6`. If the string *packed_ip* is not the correct length for the
   specified address family, :exc:`ValueError` will be raised.  A
   :exc:`socket.error` is raised for errors from the call to :func:`inet_ntop`.

   Availability: Unix (maybe not all platforms).

   .. versionadded:: 2.3


.. function:: getdefaulttimeout()

   Return the default timeout in seconds (float) for new socket objects. A value
   of ``None`` indicates that new socket objects have no timeout. When the socket
   module is first imported, the default is ``None``.

   .. versionadded:: 2.3


.. function:: setdefaulttimeout(timeout)

   Set the default timeout in seconds (float) for new socket objects. A value of
   ``None`` indicates that new socket objects have no timeout. When the socket
   module is first imported, the default is ``None``.

   .. versionadded:: 2.3


.. data:: SocketType

   This is a Python type object that represents the socket object type. It is the
   same as ``type(socket(...))``.


.. seealso::

   Module :mod:`SocketServer`
      Classes that simplify writing network servers.

   Module :mod:`ssl`
      A TLS/SSL wrapper for socket objects.


.. _socket-objects:

Socket Objects
--------------

Socket objects have the following methods.  Except for :meth:`makefile` these
correspond to Unix system calls applicable to sockets.


.. method:: socket.accept()

   Accept a connection. The socket must be bound to an address and listening for
   connections. The return value is a pair ``(conn, address)`` where *conn* is a
   *new* socket object usable to send and receive data on the connection, and
   *address* is the address bound to the socket on the other end of the connection.


.. method:: socket.bind(address)

   Bind the socket to *address*.  The socket must not already be bound. (The format
   of *address* depends on the address family --- see above.)

   .. note::

      This method has historically accepted a pair of parameters for :const:`AF_INET`
      addresses instead of only a tuple.  This was never intentional and is no longer
      available in Python 2.0 and later.


.. method:: socket.close()

   Close the socket.  All future operations on the socket object will fail. The
   remote end will receive no more data (after queued data is flushed). Sockets are
   automatically closed when they are garbage-collected.

   .. note::

      :meth:`close()` releases the resource associated with a connection but
      does not necessarily close the connection immediately.  If you want
      to close the connection in a timely fashion, call :meth:`shutdown()`
      before :meth:`close()`.


.. method:: socket.connect(address)

   Connect to a remote socket at *address*. (The format of *address* depends on the
   address family --- see above.)

   .. note::

      This method has historically accepted a pair of parameters for :const:`AF_INET`
      addresses instead of only a tuple.  This was never intentional and is no longer
      available in Python 2.0 and later.


.. method:: socket.connect_ex(address)

   Like ``connect(address)``, but return an error indicator instead of raising an
   exception for errors returned by the C-level :c:func:`connect` call (other
   problems, such as "host not found," can still raise exceptions).  The error
   indicator is ``0`` if the operation succeeded, otherwise the value of the
   :c:data:`errno` variable.  This is useful to support, for example, asynchronous
   connects.

   .. note::

      This method has historically accepted a pair of parameters for :const:`AF_INET`
      addresses instead of only a tuple. This was never intentional and is no longer
      available in Python 2.0 and later.


.. method:: socket.fileno()

   Return the socket's file descriptor (a small integer).  This is useful with
   :func:`select.select`.

   Under Windows the small integer returned by this method cannot be used where a
   file descriptor can be used (such as :func:`os.fdopen`).  Unix does not have
   this limitation.


.. method:: socket.getpeername()

   Return the remote address to which the socket is connected.  This is useful to
   find out the port number of a remote IPv4/v6 socket, for instance. (The format
   of the address returned depends on the address family --- see above.)  On some
   systems this function is not supported.


.. method:: socket.getsockname()

   Return the socket's own address.  This is useful to find out the port number of
   an IPv4/v6 socket, for instance. (The format of the address returned depends on
   the address family --- see above.)


.. method:: socket.getsockopt(level, optname[, buflen])

   Return the value of the given socket option (see the Unix man page
   :manpage:`getsockopt(2)`).  The needed symbolic constants (:const:`SO_\*` etc.)
   are defined in this module.  If *buflen* is absent, an integer option is assumed
   and its integer value is returned by the function.  If *buflen* is present, it
   specifies the maximum length of the buffer used to receive the option in, and
   this buffer is returned as a string.  It is up to the caller to decode the
   contents of the buffer (see the optional built-in module :mod:`struct` for a way
   to decode C structures encoded as strings).


.. method:: socket.ioctl(control, option)

   :platform: Windows

   The :meth:`ioctl` method is a limited interface to the WSAIoctl system
   interface.  Please refer to the `Win32 documentation
   <https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx>`_ for more
   information.

   On other platforms, the generic :func:`fcntl.fcntl` and :func:`fcntl.ioctl`
   functions may be used; they accept a socket object as their first argument.

   .. versionadded:: 2.6


.. method:: socket.listen(backlog)

   Listen for connections made to the socket.  The *backlog* argument specifies the
   maximum number of queued connections and should be at least 0; the maximum value
   is system-dependent (usually 5), the minimum value is forced to 0.


.. method:: socket.makefile([mode[, bufsize]])

   .. index:: single: I/O control; buffering

   Return a :dfn:`file object` associated with the socket.  (File objects are
   described in :ref:`bltin-file-objects`.) The file object does not close the
   socket explicitly when its :meth:`close` method is called, but only removes
   its reference to the socket object, so that the socket will be closed if it
   is not referenced from anywhere else.

   The socket must be in blocking mode (it can not have a timeout). The optional
   *mode* and *bufsize* arguments are interpreted the same way as by the built-in
   :func:`file` function.

   .. note::

      On Windows, the file-like object created by :meth:`makefile` cannot be
      used where a file object with a file descriptor is expected, such as the
      stream arguments of :meth:`subprocess.Popen`.


.. method:: socket.recv(bufsize[, flags])

   Receive data from the socket.  The return value is a string representing the
   data received.  The maximum amount of data to be received at once is specified
   by *bufsize*.  See the Unix manual page :manpage:`recv(2)` for the meaning of
   the optional argument *flags*; it defaults to zero.

   .. note::

      For best match with hardware and network realities, the value of  *bufsize*
      should be a relatively small power of 2, for example, 4096.


.. method:: socket.recvfrom(bufsize[, flags])

   Receive data from the socket.  The return value is a pair ``(string, address)``
   where *string* is a string representing the data received and *address* is the
   address of the socket sending the data.  See the Unix manual page
   :manpage:`recv(2)` for the meaning of the optional argument *flags*; it defaults
   to zero. (The format of *address* depends on the address family --- see above.)


.. method:: socket.recvfrom_into(buffer[, nbytes[, flags]])

   Receive data from the socket, writing it into *buffer* instead of  creating a
   new string.  The return value is a pair ``(nbytes, address)`` where *nbytes* is
   the number of bytes received and *address* is the address of the socket sending
   the data.  See the Unix manual page :manpage:`recv(2)` for the meaning of the
   optional argument *flags*; it defaults to zero.  (The format of *address*
   depends on the address family --- see above.)

   .. versionadded:: 2.5


.. method:: socket.recv_into(buffer[, nbytes[, flags]])

   Receive up to *nbytes* bytes from the socket, storing the data into a buffer
   rather than creating a new string.  If *nbytes* is not specified (or 0),
   receive up to the size available in the given buffer.  Returns the number of
   bytes received.  See the Unix manual page :manpage:`recv(2)` for the meaning
   of the optional argument *flags*; it defaults to zero.

   .. versionadded:: 2.5


.. method:: socket.send(string[, flags])

   Send data to the socket.  The socket must be connected to a remote socket.  The
   optional *flags* argument has the same meaning as for :meth:`recv` above.
   Returns the number of bytes sent. Applications are responsible for checking that
   all data has been sent; if only some of the data was transmitted, the
   application needs to attempt delivery of the remaining data. For further
   information on this concept, consult the :ref:`socket-howto`.


.. method:: socket.sendall(string[, flags])

   Send data to the socket.  The socket must be connected to a remote socket.  The
   optional *flags* argument has the same meaning as for :meth:`recv` above.
   Unlike :meth:`send`, this method continues to send data from *string* until
   either all data has been sent or an error occurs.  ``None`` is returned on
   success.  On error, an exception is raised, and there is no way to determine how
   much data, if any, was successfully sent.


.. method:: socket.sendto(string, address)
            socket.sendto(string, flags, address)

   Send data to the socket.  The socket should not be connected to a remote socket,
   since the destination socket is specified by *address*.  The optional *flags*
   argument has the same meaning as for :meth:`recv` above.  Return the number of
   bytes sent. (The format of *address* depends on the address family --- see
   above.)


.. method:: socket.setblocking(flag)

   Set blocking or non-blocking mode of the socket: if *flag* is 0, the socket is
   set to non-blocking, else to blocking mode.  Initially all sockets are in
   blocking mode.  In non-blocking mode, if a :meth:`recv` call doesn't find any
   data, or if a :meth:`send` call can't immediately dispose of the data, an
   :exc:`error` exception is raised; in blocking mode, the calls block until they
   can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``;
   ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``.


.. method:: socket.settimeout(value)

   Set a timeout on blocking socket operations.  The *value* argument can be a
   nonnegative float expressing seconds, or ``None``. If a float is given,
   subsequent socket operations will raise a :exc:`timeout` exception if the
   timeout period *value* has elapsed before the operation has completed.  Setting
   a timeout of ``None`` disables timeouts on socket operations.
   ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``;
   ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``.

   .. versionadded:: 2.3


.. method:: socket.gettimeout()

   Return the timeout in seconds (float) associated with socket operations, or
   ``None`` if no timeout is set.  This reflects the last call to
   :meth:`setblocking` or :meth:`settimeout`.

   .. versionadded:: 2.3

Some notes on socket blocking and timeouts: A socket object can be in one of
three modes: blocking, non-blocking, or timeout.  Sockets are always created in
blocking mode.  In blocking mode, operations block until complete or
the system returns an error (such as connection timed out).  In
non-blocking mode, operations fail (with an error that is unfortunately
system-dependent) if they cannot be completed immediately.  In timeout mode,
operations fail if they cannot be completed within the timeout specified for the
socket or if the system returns an error.  The :meth:`~socket.setblocking`
method is simply a shorthand for certain :meth:`~socket.settimeout` calls.

Timeout mode internally sets the socket in non-blocking mode.  The blocking and
timeout modes are shared between file descriptors and socket objects that refer
to the same network endpoint.  A consequence of this is that file objects
returned by the :meth:`~socket.makefile` method must only be used when the
socket is in blocking mode; in timeout or non-blocking mode file operations
that cannot be completed immediately will fail.

Note that the :meth:`~socket.connect` operation is subject to the timeout
setting, and in general it is recommended to call :meth:`~socket.settimeout`
before calling :meth:`~socket.connect` or pass a timeout parameter to
:meth:`create_connection`.  The system network stack may return a connection
timeout error of its own regardless of any Python socket timeout setting.


.. method:: socket.setsockopt(level, optname, value)

   .. index:: module: struct

   Set the value of the given socket option (see the Unix manual page
   :manpage:`setsockopt(2)`).  The needed symbolic constants are defined in the
   :mod:`socket` module (:const:`SO_\*` etc.).  The value can be an integer or a
   string representing a buffer.  In the latter case it is up to the caller to
   ensure that the string contains the proper bits (see the optional built-in
   module :mod:`struct` for a way to encode C structures as strings).


.. method:: socket.shutdown(how)

   Shut down one or both halves of the connection.  If *how* is :const:`SHUT_RD`,
   further receives are disallowed.  If *how* is :const:`SHUT_WR`, further sends
   are disallowed.  If *how* is :const:`SHUT_RDWR`, further sends and receives are
   disallowed.  Depending on the platform, shutting down one half of the connection
   can also close the opposite half (e.g. on Mac OS X, ``shutdown(SHUT_WR)`` does
   not allow further reads on the other end of the connection).

Note that there are no methods :meth:`read` or :meth:`write`; use
:meth:`~socket.recv` and :meth:`~socket.send` without *flags* argument instead.

Socket objects also have these (read-only) attributes that correspond to the
values given to the :class:`~socket.socket` constructor.


.. attribute:: socket.family

   The socket family.

   .. versionadded:: 2.5


.. attribute:: socket.type

   The socket type.

   .. versionadded:: 2.5


.. attribute:: socket.proto

   The socket protocol.

   .. versionadded:: 2.5


.. _socket-example:

Example
-------

Here are four minimal example programs using the TCP/IP protocol: a server that
echoes all data that it receives back (servicing only one client), and a client
using it.  Note that a server must perform the sequence :func:`.socket`,
:meth:`~socket.bind`, :meth:`~socket.listen`, :meth:`~socket.accept` (possibly
repeating the :meth:`~socket.accept` to service more than one client), while a
client only needs the sequence :func:`.socket`, :meth:`~socket.connect`.  Also
note that the server does not :meth:`~socket.sendall`/:meth:`~socket.recv` on
the socket it is listening on but on the new socket returned by
:meth:`~socket.accept`.

The first two examples support IPv4 only. ::

   # Echo server program
   import socket

   HOST = ''                 # Symbolic name meaning all available interfaces
   PORT = 50007              # Arbitrary non-privileged port
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.bind((HOST, PORT))
   s.listen(1)
   conn, addr = s.accept()
   print 'Connected by', addr
   while 1:
       data = conn.recv(1024)
       if not data: break
       conn.sendall(data)
   conn.close()

::

   # Echo client program
   import socket

   HOST = 'daring.cwi.nl'    # The remote host
   PORT = 50007              # The same port as used by the server
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.connect((HOST, PORT))
   s.sendall('Hello, world')
   data = s.recv(1024)
   s.close()
   print 'Received', repr(data)

The next two examples are identical to the above two, but support both IPv4 and
IPv6. The server side will listen to the first address family available (it
should listen to both instead). On most of IPv6-ready systems, IPv6 will take
precedence and the server may not accept IPv4 traffic. The client side will try
to connect to the all addresses returned as a result of the name resolution, and
sends traffic to the first one connected successfully. ::

   # Echo server program
   import socket
   import sys

   HOST = None               # Symbolic name meaning all available interfaces
   PORT = 50007              # Arbitrary non-privileged port
   s = None
   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
       af, socktype, proto, canonname, sa = res
       try:
           s = socket.socket(af, socktype, proto)
       except socket.error as msg:
           s = None
           continue
       try:
           s.bind(sa)
           s.listen(1)
       except socket.error as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print 'could not open socket'
       sys.exit(1)
   conn, addr = s.accept()
   print 'Connected by', addr
   while 1:
       data = conn.recv(1024)
       if not data: break
       conn.send(data)
   conn.close()

::

   # Echo client program
   import socket
   import sys

   HOST = 'daring.cwi.nl'    # The remote host
   PORT = 50007              # The same port as used by the server
   s = None
   for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
       af, socktype, proto, canonname, sa = res
       try:
           s = socket.socket(af, socktype, proto)
       except socket.error as msg:
           s = None
           continue
       try:
           s.connect(sa)
       except socket.error as msg:
           s.close()
           s = None
           continue
       break
   if s is None:
       print 'could not open socket'
       sys.exit(1)
   s.sendall('Hello, world')
   data = s.recv(1024)
   s.close()
   print 'Received', repr(data)


The last example shows how to write a very simple network sniffer with raw
sockets on Windows. The example requires administrator privileges to modify
the interface::

   import socket

   # the public network interface
   HOST = socket.gethostbyname(socket.gethostname())

   # create a raw socket and bind it to the public interface
   s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_IP)
   s.bind((HOST, 0))

   # Include IP headers
   s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

   # receive all packages
   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

   # receive a package
   print s.recvfrom(65565)

   # disabled promiscuous mode
   s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)


Running an example several times with too small delay between executions, could
lead to this error::

   socket.error: [Errno 98] Address already in use

This is because the previous execution has left the socket in a ``TIME_WAIT``
state, and can't be immediately reused.

There is a :mod:`socket` flag to set, in order to prevent this,
:data:`socket.SO_REUSEADDR`::

   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
   s.bind((HOST, PORT))

the :data:`SO_REUSEADDR` flag tells the kernel to reuse a local socket in
``TIME_WAIT`` state, without waiting for its natural timeout to expire.
PK
%�\�=�W�W*html/_sources/library/socketserver.rst.txtnu�[���:mod:`SocketServer` --- A framework for network servers
=======================================================

.. module:: SocketServer
   :synopsis: A framework for network servers.

.. note::

   The :mod:`SocketServer` module has been renamed to :mod:`socketserver` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.

**Source code:** :source:`Lib/SocketServer.py`

--------------

The :mod:`SocketServer` module simplifies the task of writing network servers.

There are four basic concrete server classes:


.. class:: TCPServer(server_address, RequestHandlerClass, bind_and_activate=True)

   This uses the Internet TCP protocol, which provides for
   continuous streams of data between the client and server.
   If *bind_and_activate* is true, the constructor automatically attempts to
   invoke :meth:`~BaseServer.server_bind` and
   :meth:`~BaseServer.server_activate`.  The other parameters are passed to
   the :class:`BaseServer` base class.


.. class:: UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)

   This uses datagrams, which are discrete packets of information that may
   arrive out of order or be lost while in transit.  The parameters are
   the same as for :class:`TCPServer`.


.. class:: UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True)
           UnixDatagramServer(server_address, RequestHandlerClass, bind_and_activate=True)

   These more infrequently used classes are similar to the TCP and
   UDP classes, but use Unix domain sockets; they're not available on
   non-Unix platforms.  The parameters are the same as for
   :class:`TCPServer`.


These four classes process requests :dfn:`synchronously`; each request must be
completed before the next request can be started.  This isn't suitable if each
request takes a long time to complete, because it requires a lot of computation,
or because it returns a lot of data which the client is slow to process.  The
solution is to create a separate process or thread to handle each request; the
:class:`ForkingMixIn` and :class:`ThreadingMixIn` mix-in classes can be used to
support asynchronous behaviour.

Creating a server requires several steps.  First, you must create a request
handler class by subclassing the :class:`BaseRequestHandler` class and
overriding its :meth:`~BaseRequestHandler.handle` method;
this method will process incoming
requests.  Second, you must instantiate one of the server classes, passing it
the server's address and the request handler class.  Then call the
:meth:`~BaseServer.handle_request` or
:meth:`~BaseServer.serve_forever` method of the server object to
process one or many requests.  Finally, call :meth:`~BaseServer.server_close`
to close the socket.

When inheriting from :class:`ThreadingMixIn` for threaded connection behavior,
you should explicitly declare how you want your threads to behave on an abrupt
shutdown. The :class:`ThreadingMixIn` class defines an attribute
*daemon_threads*, which indicates whether or not the server should wait for
thread termination. You should set the flag explicitly if you would like threads
to behave autonomously; the default is :const:`False`, meaning that Python will
not exit until all threads created by :class:`ThreadingMixIn` have exited.

Server classes have the same external methods and attributes, no matter what
network protocol they use.


Server Creation Notes
---------------------

There are five classes in an inheritance diagram, four of which represent
synchronous servers of four types::

   +------------+
   | BaseServer |
   +------------+
         |
         v
   +-----------+        +------------------+
   | TCPServer |------->| UnixStreamServer |
   +-----------+        +------------------+
         |
         v
   +-----------+        +--------------------+
   | UDPServer |------->| UnixDatagramServer |
   +-----------+        +--------------------+

Note that :class:`UnixDatagramServer` derives from :class:`UDPServer`, not from
:class:`UnixStreamServer` --- the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both Unix
server classes.


.. class:: ForkingMixIn
           ThreadingMixIn

   Forking and threading versions of each type of server can be created
   using these mix-in classes.  For instance, :class:`ThreadingUDPServer`
   is created as follows::

      class ThreadingUDPServer(ThreadingMixIn, UDPServer):
          pass

   The mix-in class comes first, since it overrides a method defined in
   :class:`UDPServer`.  Setting the various attributes also changes the
   behavior of the underlying server mechanism.

   :class:`ForkingMixIn` and the Forking classes mentioned below are
   only available on POSIX platforms that support :func:`~os.fork`.


.. class:: ForkingTCPServer
           ForkingUDPServer
           ThreadingTCPServer
           ThreadingUDPServer

   These classes are pre-defined using the mix-in classes.


To implement a service, you must derive a class from :class:`BaseRequestHandler`
and redefine its :meth:`~BaseRequestHandler.handle` method.
You can then run various versions of
the service by combining one of the server classes with your request handler
class.  The request handler class must be different for datagram or stream
services.  This can be hidden by using the handler subclasses
:class:`StreamRequestHandler` or :class:`DatagramRequestHandler`.

Of course, you still have to use your head!  For instance, it makes no sense to
use a forking server if the service contains state in memory that can be
modified by different requests, since the modifications in the child process
would never reach the initial state kept in the parent process and passed to
each child.  In this case, you can use a threading server, but you will probably
have to use locks to protect the integrity of the shared data.

On the other hand, if you are building an HTTP server where all data is stored
externally (for instance, in the file system), a synchronous class will
essentially render the service "deaf" while one request is being handled --
which may be for a very long time if a client is slow to receive all the data it
has requested.  Here a threading or forking server is appropriate.

In some cases, it may be appropriate to process part of a request synchronously,
but to finish processing in a forked child depending on the request data.  This
can be implemented by using a synchronous server and doing an explicit fork in
the request handler class :meth:`~BaseRequestHandler.handle` method.

Another approach to handling multiple simultaneous requests in an environment
that supports neither threads nor :func:`~os.fork` (or where these are too
expensive or inappropriate for the service) is to maintain an explicit table of
partially finished requests and to use :func:`~select.select` to decide which
request to work on next (or whether to handle a new incoming request).  This is
particularly important for stream services where each client can potentially be
connected for a long time (if threads or subprocesses cannot be used). See
:mod:`asyncore` for another way to manage this.

.. XXX should data and methods be intermingled, or separate?
   how should the distinction between class and instance variables be drawn?


Server Objects
--------------

.. class:: BaseServer(server_address, RequestHandlerClass)

   This is the superclass of all Server objects in the module.  It defines the
   interface, given below, but does not implement most of the methods, which is
   done in subclasses.  The two parameters are stored in the respective
   :attr:`server_address` and :attr:`RequestHandlerClass` attributes.


   .. method:: fileno()

      Return an integer file descriptor for the socket on which the server is
      listening.  This function is most commonly passed to :func:`select.select`, to
      allow monitoring multiple servers in the same process.


   .. method:: handle_request()

      Process a single request.  This function calls the following methods in
      order: :meth:`get_request`, :meth:`verify_request`, and
      :meth:`process_request`.  If the user-provided
      :meth:`~BaseRequestHandler.handle` method of the
      handler class raises an exception, the server's :meth:`handle_error` method
      will be called.  If no request is received within :attr:`timeout`
      seconds, :meth:`handle_timeout` will be called and :meth:`handle_request`
      will return.


   .. method:: serve_forever(poll_interval=0.5)

      Handle requests until an explicit :meth:`shutdown` request.  Poll for
      shutdown every *poll_interval* seconds.
      Ignores the :attr:`timeout` attribute.
      If you need to do periodic tasks, do them in another thread.


   .. method:: shutdown()

      Tell the :meth:`serve_forever` loop to stop and wait until it does.

      .. versionadded:: 2.6


   .. method:: server_close()

      Clean up the server. May be overridden.

      .. versionadded:: 2.6


   .. attribute:: address_family

      The family of protocols to which the server's socket belongs.
      Common examples are :const:`socket.AF_INET` and :const:`socket.AF_UNIX`.


   .. attribute:: RequestHandlerClass

      The user-provided request handler class; an instance of this class is created
      for each request.


   .. attribute:: server_address

      The address on which the server is listening.  The format of addresses varies
      depending on the protocol family;
      see the documentation for the :mod:`socket` module
      for details.  For Internet protocols, this is a tuple containing a string giving
      the address, and an integer port number: ``('127.0.0.1', 80)``, for example.


   .. attribute:: socket

      The socket object on which the server will listen for incoming requests.


   The server classes support the following class variables:

   .. XXX should class variables be covered before instance variables, or vice versa?

   .. attribute:: allow_reuse_address

      Whether the server will allow the reuse of an address. This defaults to
      :const:`False`, and can be set in subclasses to change the policy.


   .. attribute:: request_queue_size

      The size of the request queue.  If it takes a long time to process a single
      request, any requests that arrive while the server is busy are placed into a
      queue, up to :attr:`request_queue_size` requests.  Once the queue is full,
      further requests from clients will get a "Connection denied" error.  The default
      value is usually 5, but this can be overridden by subclasses.


   .. attribute:: socket_type

      The type of socket used by the server; :const:`socket.SOCK_STREAM` and
      :const:`socket.SOCK_DGRAM` are two common values.


   .. attribute:: timeout

      Timeout duration, measured in seconds, or :const:`None` if no timeout is
      desired.  If :meth:`handle_request` receives no incoming requests within the
      timeout period, the :meth:`handle_timeout` method is called.


   There are various server methods that can be overridden by subclasses of base
   server classes like :class:`TCPServer`; these methods aren't useful to external
   users of the server object.

   .. XXX should the default implementations of these be documented, or should
      it be assumed that the user will look at SocketServer.py?

   .. method:: finish_request(request, client_address)

      Actually processes the request by instantiating :attr:`RequestHandlerClass` and
      calling its :meth:`~BaseRequestHandler.handle` method.


   .. method:: get_request()

      Must accept a request from the socket, and return a 2-tuple containing the *new*
      socket object to be used to communicate with the client, and the client's
      address.


   .. method:: handle_error(request, client_address)

      This function is called if the :meth:`~BaseRequestHandler.handle`
      method of a :attr:`RequestHandlerClass` instance raises
      an exception.  The default action is to print the traceback to
      standard output and continue handling further requests.


   .. method:: handle_timeout()

      This function is called when the :attr:`timeout` attribute has been set to a
      value other than :const:`None` and the timeout period has passed with no
      requests being received.  The default action for forking servers is
      to collect the status of any child processes that have exited, while
      in threading servers this method does nothing.


   .. method:: process_request(request, client_address)

      Calls :meth:`finish_request` to create an instance of the
      :attr:`RequestHandlerClass`.  If desired, this function can create a new process
      or thread to handle the request; the :class:`ForkingMixIn` and
      :class:`ThreadingMixIn` classes do this.


   .. Is there any point in documenting the following two functions?
      What would the purpose of overriding them be: initializing server
      instance variables, adding new network families?

   .. method:: server_activate()

      Called by the server's constructor to activate the server.  The default behavior
      for a TCP server just invokes :meth:`~socket.socket.listen`
      on the server's socket. May be overridden.


   .. method:: server_bind()

      Called by the server's constructor to bind the socket to the desired address.
      May be overridden.


   .. method:: verify_request(request, client_address)

      Must return a Boolean value; if the value is :const:`True`, the request will be
      processed, and if it's :const:`False`, the request will be denied. This function
      can be overridden to implement access controls for a server. The default
      implementation always returns :const:`True`.


Request Handler Objects
-----------------------

.. class:: BaseRequestHandler

   This is the superclass of all request handler objects.  It defines
   the interface, given below.  A concrete request handler subclass must
   define a new :meth:`handle` method, and can override any of
   the other methods.  A new instance of the subclass is created for each
   request.


   .. method:: setup()

      Called before the :meth:`handle` method to perform any initialization actions
      required.  The default implementation does nothing.


   .. method:: handle()

      This function must do all the work required to service a request.  The
      default implementation does nothing.  Several instance attributes are
      available to it; the request is available as :attr:`self.request`; the client
      address as :attr:`self.client_address`; and the server instance as
      :attr:`self.server`, in case it needs access to per-server information.

      The type of :attr:`self.request` is different for datagram or stream
      services.  For stream services, :attr:`self.request` is a socket object; for
      datagram services, :attr:`self.request` is a pair of string and socket.


   .. method:: finish()

      Called after the :meth:`handle` method to perform any clean-up actions
      required.  The default implementation does nothing.  If :meth:`setup`
      raises an exception, this function will not be called.


.. class:: StreamRequestHandler
           DatagramRequestHandler

   These :class:`BaseRequestHandler` subclasses override the
   :meth:`~BaseRequestHandler.setup` and :meth:`~BaseRequestHandler.finish`
   methods, and provide :attr:`self.rfile` and :attr:`self.wfile` attributes.
   The :attr:`self.rfile` and :attr:`self.wfile` attributes can be
   read or written, respectively, to get the request data or return data
   to the client.


Examples
--------

:class:`SocketServer.TCPServer` Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is the server side::

   import SocketServer

   class MyTCPHandler(SocketServer.BaseRequestHandler):
       """
       The request handler class for our server.

       It is instantiated once per connection to the server, and must
       override the handle() method to implement communication to the
       client.
       """

       def handle(self):
           # self.request is the TCP socket connected to the client
           self.data = self.request.recv(1024).strip()
           print "{} wrote:".format(self.client_address[0])
           print self.data
           # just send back the same data, but upper-cased
           self.request.sendall(self.data.upper())

   if __name__ == "__main__":
       HOST, PORT = "localhost", 9999

       # Create the server, binding to localhost on port 9999
       server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

       # Activate the server; this will keep running until you
       # interrupt the program with Ctrl-C
       server.serve_forever()

An alternative request handler class that makes use of streams (file-like
objects that simplify communication by providing the standard file interface)::

   class MyTCPHandler(SocketServer.StreamRequestHandler):

       def handle(self):
           # self.rfile is a file-like object created by the handler;
           # we can now use e.g. readline() instead of raw recv() calls
           self.data = self.rfile.readline().strip()
           print "{} wrote:".format(self.client_address[0])
           print self.data
           # Likewise, self.wfile is a file-like object used to write back
           # to the client
           self.wfile.write(self.data.upper())

The difference is that the ``readline()`` call in the second handler will call
``recv()`` multiple times until it encounters a newline character, while the
single ``recv()`` call in the first handler will just return what has been sent
from the client in one ``sendall()`` call.


This is the client side::

   import socket
   import sys

   HOST, PORT = "localhost", 9999
   data = " ".join(sys.argv[1:])

   # Create a socket (SOCK_STREAM means a TCP socket)
   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

   try:
       # Connect to server and send data
       sock.connect((HOST, PORT))
       sock.sendall(data + "\n")

       # Receive data from the server and shut down
       received = sock.recv(1024)
   finally:
       sock.close()

   print "Sent:     {}".format(data)
   print "Received: {}".format(received)


The output of the example should look something like this:

Server:

.. code-block:: shell-session

   $ python TCPServer.py
   127.0.0.1 wrote:
   hello world with TCP
   127.0.0.1 wrote:
   python is nice

Client:

.. code-block:: shell-session

   $ python TCPClient.py hello world with TCP
   Sent:     hello world with TCP
   Received: HELLO WORLD WITH TCP
   $ python TCPClient.py python is nice
   Sent:     python is nice
   Received: PYTHON IS NICE


:class:`SocketServer.UDPServer` Example
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is the server side::

   import SocketServer

   class MyUDPHandler(SocketServer.BaseRequestHandler):
       """
       This class works similar to the TCP handler class, except that
       self.request consists of a pair of data and client socket, and since
       there is no connection the client address must be given explicitly
       when sending data back via sendto().
       """

       def handle(self):
           data = self.request[0].strip()
           socket = self.request[1]
           print "{} wrote:".format(self.client_address[0])
           print data
           socket.sendto(data.upper(), self.client_address)

   if __name__ == "__main__":
       HOST, PORT = "localhost", 9999
       server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
       server.serve_forever()

This is the client side::

   import socket
   import sys

   HOST, PORT = "localhost", 9999
   data = " ".join(sys.argv[1:])

   # SOCK_DGRAM is the socket type to use for UDP sockets
   sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

   # As you can see, there is no connect() call; UDP has no connections.
   # Instead, data is directly sent to the recipient via sendto().
   sock.sendto(data + "\n", (HOST, PORT))
   received = sock.recv(1024)

   print "Sent:     {}".format(data)
   print "Received: {}".format(received)

The output of the example should look exactly like for the TCP server example.


Asynchronous Mixins
~~~~~~~~~~~~~~~~~~~

To build asynchronous handlers, use the :class:`ThreadingMixIn` and
:class:`ForkingMixIn` classes.

An example for the :class:`ThreadingMixIn` class::

   import socket
   import threading
   import SocketServer

   class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

       def handle(self):
           data = self.request.recv(1024)
           cur_thread = threading.current_thread()
           response = "{}: {}".format(cur_thread.name, data)
           self.request.sendall(response)

   class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
       pass

   def client(ip, port, message):
       sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
       sock.connect((ip, port))
       try:
           sock.sendall(message)
           response = sock.recv(1024)
           print "Received: {}".format(response)
       finally:
           sock.close()

   if __name__ == "__main__":
       # Port 0 means to select an arbitrary unused port
       HOST, PORT = "localhost", 0

       server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
       ip, port = server.server_address

       # Start a thread with the server -- that thread will then start one
       # more thread for each request
       server_thread = threading.Thread(target=server.serve_forever)
       # Exit the server thread when the main thread terminates
       server_thread.daemon = True
       server_thread.start()
       print "Server loop running in thread:", server_thread.name

       client(ip, port, "Hello World 1")
       client(ip, port, "Hello World 2")
       client(ip, port, "Hello World 3")

       server.shutdown()
       server.server_close()


The output of the example should look something like this:

.. code-block:: shell-session

   $ python ThreadedTCPServer.py
   Server loop running in thread: Thread-1
   Received: Thread-2: Hello World 1
   Received: Thread-3: Hello World 2
   Received: Thread-4: Hello World 3


The :class:`ForkingMixIn` class is used in the same way, except that the server
will spawn a new process for each request.
Available only on POSIX platforms that support :func:`~os.fork`.
PK
%�\��\WW$html/_sources/library/someos.rst.txtnu�[���
.. _someos:

**********************************
Optional Operating System Services
**********************************

The modules described in this chapter provide interfaces to operating system
features that are available on selected operating systems only. The interfaces
are generally modeled after the Unix or C interfaces but they are available on
some other systems as well (e.g. Windows or NT).  Here's an overview:


.. toctree::

   select.rst
   threading.rst
   thread.rst
   dummy_threading.rst
   dummy_thread.rst
   multiprocessing.rst
   mmap.rst
   readline.rst
   rlcompleter.rst
PK
%�\
���		"html/_sources/library/spwd.rst.txtnu�[���
:mod:`spwd` --- The shadow password database
============================================

.. module:: spwd
   :platform: Unix
   :synopsis: The shadow password database (getspnam() and friends).


.. versionadded:: 2.5

This module provides access to the Unix shadow password database. It is
available on various Unix versions.

You must have enough privileges to access the shadow password database (this
usually means you have to be root).

Shadow password database entries are reported as a tuple-like object, whose
attributes correspond to the members of the ``spwd`` structure (Attribute field
below, see ``<shadow.h>``):

+-------+---------------+---------------------------------+
| Index | Attribute     | Meaning                         |
+=======+===============+=================================+
| 0     | ``sp_nam``    | Login name                      |
+-------+---------------+---------------------------------+
| 1     | ``sp_pwd``    | Encrypted password              |
+-------+---------------+---------------------------------+
| 2     | ``sp_lstchg`` | Date of last change             |
+-------+---------------+---------------------------------+
| 3     | ``sp_min``    | Minimal number of days between  |
|       |               | changes                         |
+-------+---------------+---------------------------------+
| 4     | ``sp_max``    | Maximum number of days between  |
|       |               | changes                         |
+-------+---------------+---------------------------------+
| 5     | ``sp_warn``   | Number of days before password  |
|       |               | expires to warn user about it   |
+-------+---------------+---------------------------------+
| 6     | ``sp_inact``  | Number of days after password   |
|       |               | expires until account is        |
|       |               | blocked                         |
+-------+---------------+---------------------------------+
| 7     | ``sp_expire`` | Number of days since 1970-01-01 |
|       |               | until account is disabled       |
+-------+---------------+---------------------------------+
| 8     | ``sp_flag``   | Reserved                        |
+-------+---------------+---------------------------------+

The sp_nam and sp_pwd items are strings, all others are integers.
:exc:`KeyError` is raised if the entry asked for cannot be found.

It defines the following items:


.. function:: getspnam(name)

   Return the shadow password database entry for the given user name.


.. function:: getspall()

   Return a list of all available shadow password database entries, in arbitrary
   order.


.. seealso::

   Module :mod:`grp`
      An interface to the group database, similar to this.

   Module :mod:`pwd`
      An interface to the normal password database, similar to this.

PK
%�\F�x�x�%html/_sources/library/sqlite3.rst.txtnu�[���:mod:`sqlite3` --- DB-API 2.0 interface for SQLite databases
============================================================

.. module:: sqlite3
   :synopsis: A DB-API 2.0 implementation using SQLite 3.x.
.. sectionauthor:: Gerhard Häring <gh@ghaering.de>


.. versionadded:: 2.5

SQLite is a C library that provides a lightweight disk-based database that
doesn't require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage.  It's also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.

The sqlite3 module was written by Gerhard Häring.  It provides a SQL interface
compliant with the DB-API 2.0 specification described by :pep:`249`.

To use the module, you must first create a :class:`Connection` object that
represents the database.  Here the data will be stored in the
:file:`example.db` file::

   import sqlite3
   conn = sqlite3.connect('example.db')

You can also supply the special name ``:memory:`` to create a database in RAM.

Once you have a :class:`Connection`, you can create a :class:`Cursor`  object
and call its :meth:`~Cursor.execute` method to perform SQL commands::

   c = conn.cursor()

   # Create table
   c.execute('''CREATE TABLE stocks
                (date text, trans text, symbol text, qty real, price real)''')

   # Insert a row of data
   c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

   # Save (commit) the changes
   conn.commit()

   # We can also close the connection if we are done with it.
   # Just be sure any changes have been committed or they will be lost.
   conn.close()

The data you've saved is persistent and is available in subsequent sessions::

   import sqlite3
   conn = sqlite3.connect('example.db')
   c = conn.cursor()

Usually your SQL operations will need to use values from Python variables.  You
shouldn't assemble your query using Python's string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack
(see https://xkcd.com/327/ for humorous example of what can go wrong).

Instead, use the DB-API's parameter substitution.  Put ``?`` as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor's :meth:`~Cursor.execute` method.  (Other database
modules may use a different placeholder, such as ``%s`` or ``:1``.) For
example::

   # Never do this -- insecure!
   symbol = 'RHAT'
   c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)

   # Do this instead
   t = ('RHAT',)
   c.execute('SELECT * FROM stocks WHERE symbol=?', t)
   print c.fetchone()

   # Larger example that inserts many records at a time
   purchases = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
                ('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
                ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
               ]
   c.executemany('INSERT INTO stocks VALUES (?,?,?,?,?)', purchases)

To retrieve data after executing a SELECT statement, you can either treat the
cursor as an :term:`iterator`, call the cursor's :meth:`~Cursor.fetchone` method to
retrieve a single matching row, or call :meth:`~Cursor.fetchall` to get a list of the
matching rows.

This example uses the iterator form::

   >>> for row in c.execute('SELECT * FROM stocks ORDER BY price'):
           print row

   (u'2006-01-05', u'BUY', u'RHAT', 100, 35.14)
   (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
   (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
   (u'2006-04-05', u'BUY', u'MSFT', 1000, 72.0)


.. seealso::

   https://github.com/ghaering/pysqlite
      The pysqlite web page -- sqlite3 is developed externally under the name
      "pysqlite".

   https://www.sqlite.org
      The SQLite web page; the documentation describes the syntax and the
      available data types for the supported SQL dialect.

   http://www.w3schools.com/sql/
      Tutorial, reference and examples for learning SQL syntax.

   :pep:`249` - Database API Specification 2.0
      PEP written by Marc-André Lemburg.


.. _sqlite3-module-contents:

Module functions and constants
------------------------------


.. data:: version

   The version number of this module, as a string. This is not the version of
   the SQLite library.

.. data:: version_info

   The version number of this module, as a tuple of integers. This is not the
   version of the SQLite library.

.. data:: sqlite_version

   The version number of the run-time SQLite library, as a string.

.. data:: sqlite_version_info

   The version number of the run-time SQLite library, as a tuple of integers.

.. data:: PARSE_DECLTYPES

   This constant is meant to be used with the *detect_types* parameter of the
   :func:`connect` function.

   Setting it makes the :mod:`sqlite3` module parse the declared type for each
   column it returns.  It will parse out the first word of the declared type,
   i. e.  for "integer primary key", it will parse out "integer", or for
   "number(10)" it will parse out "number". Then for that column, it will look
   into the converters dictionary and use the converter function registered for
   that type there.


.. data:: PARSE_COLNAMES

   This constant is meant to be used with the *detect_types* parameter of the
   :func:`connect` function.

   Setting this makes the SQLite interface parse the column name for each column it
   returns.  It will look for a string formed [mytype] in there, and then decide
   that 'mytype' is the type of the column. It will try to find an entry of
   'mytype' in the converters dictionary and then use the converter function found
   there to return the value. The column name found in :attr:`Cursor.description`
   is only the first word of the column name, i.  e. if you use something like
   ``'as "x [datetime]"'`` in your SQL, then we will parse out everything until the
   first blank for the column name: the column name would simply be "x".


.. function:: connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements])

   Opens a connection to the SQLite database file *database*. You can use
   ``":memory:"`` to open a database connection to a database that resides in RAM
   instead of on disk.

   When a database is accessed by multiple connections, and one of the processes
   modifies the database, the SQLite database is locked until that transaction is
   committed. The *timeout* parameter specifies how long the connection should wait
   for the lock to go away until raising an exception. The default for the timeout
   parameter is 5.0 (five seconds).

   For the *isolation_level* parameter, please see the
   :attr:`Connection.isolation_level` property of :class:`Connection` objects.

   SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
   you want to use other types you must add support for them yourself. The
   *detect_types* parameter and the using custom **converters** registered with the
   module-level :func:`register_converter` function allow you to easily do that.

   *detect_types* defaults to 0 (i. e. off, no type detection), you can set it to
   any combination of :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES` to turn
   type detection on.

   By default, the :mod:`sqlite3` module uses its :class:`Connection` class for the
   connect call.  You can, however, subclass the :class:`Connection` class and make
   :func:`connect` use your class instead by providing your class for the *factory*
   parameter.

   Consult the section :ref:`sqlite3-types` of this manual for details.

   The :mod:`sqlite3` module internally uses a statement cache to avoid SQL parsing
   overhead. If you want to explicitly set the number of statements that are cached
   for the connection, you can set the *cached_statements* parameter. The currently
   implemented default is to cache 100 statements.


.. function:: register_converter(typename, callable)

   Registers a callable to convert a bytestring from the database into a custom
   Python type. The callable will be invoked for all database values that are of
   the type *typename*. Confer the parameter *detect_types* of the :func:`connect`
   function for how the type detection works. Note that *typename* and the name of
   the type in your query are matched in case-insensitive manner.


.. function:: register_adapter(type, callable)

   Registers a callable to convert the custom Python type *type* into one of
   SQLite's supported types. The callable *callable* accepts as single parameter
   the Python value, and must return a value of the following types: int, long,
   float, str (UTF-8 encoded), unicode or buffer.


.. function:: complete_statement(sql)

   Returns :const:`True` if the string *sql* contains one or more complete SQL
   statements terminated by semicolons. It does not verify that the SQL is
   syntactically correct, only that there are no unclosed string literals and the
   statement is terminated by a semicolon.

   This can be used to build a shell for SQLite, as in the following example:


   .. literalinclude:: ../includes/sqlite3/complete_statement.py


.. function:: enable_callback_tracebacks(flag)

   By default you will not get any tracebacks in user-defined functions,
   aggregates, converters, authorizer callbacks etc. If you want to debug them,
   you can call this function with *flag* set to ``True``. Afterwards, you will
   get tracebacks from callbacks on ``sys.stderr``. Use :const:`False` to
   disable the feature again.


.. _sqlite3-connection-objects:

Connection Objects
------------------

.. class:: Connection

   A SQLite database connection has the following attributes and methods:

   .. attribute:: isolation_level

      Get or set the current isolation level. :const:`None` for autocommit mode or
      one of "DEFERRED", "IMMEDIATE" or "EXCLUSIVE". See section
      :ref:`sqlite3-controlling-transactions` for a more detailed explanation.


   .. method:: cursor(factory=Cursor)

      The cursor method accepts a single optional parameter *factory*. If
      supplied, this must be a callable returning an instance of :class:`Cursor`
      or its subclasses.

   .. method:: commit()

      This method commits the current transaction. If you don't call this method,
      anything you did since the last call to ``commit()`` is not visible from
      other database connections. If you wonder why you don't see the data you've
      written to the database, please check you didn't forget to call this method.

   .. method:: rollback()

      This method rolls back any changes to the database since the last call to
      :meth:`commit`.

   .. method:: close()

      This closes the database connection. Note that this does not automatically
      call :meth:`commit`. If you just close your database connection without
      calling :meth:`commit` first, your changes will be lost!

   .. method:: execute(sql, [parameters])

      This is a nonstandard shortcut that creates an intermediate cursor object by
      calling the cursor method, then calls the cursor's :meth:`execute
      <Cursor.execute>` method with the parameters given.


   .. method:: executemany(sql, [parameters])

      This is a nonstandard shortcut that creates an intermediate cursor object by
      calling the cursor method, then calls the cursor's :meth:`executemany
      <Cursor.executemany>` method with the parameters given.

   .. method:: executescript(sql_script)

      This is a nonstandard shortcut that creates an intermediate cursor object by
      calling the cursor method, then calls the cursor's :meth:`executescript
      <Cursor.executescript>` method with the parameters given.


   .. method:: create_function(name, num_params, func)

      Creates a user-defined function that you can later use from within SQL
      statements under the function name *name*. *num_params* is the number of
      parameters the function accepts, and *func* is a Python callable that is called
      as the SQL function.

      The function can return any of the types supported by SQLite: unicode, str, int,
      long, float, buffer and ``None``.

      Example:

      .. literalinclude:: ../includes/sqlite3/md5func.py


   .. method:: create_aggregate(name, num_params, aggregate_class)

      Creates a user-defined aggregate function.

      The aggregate class must implement a ``step`` method, which accepts the number
      of parameters *num_params*, and a ``finalize`` method which will return the
      final result of the aggregate.

      The ``finalize`` method can return any of the types supported by SQLite:
      unicode, str, int, long, float, buffer and ``None``.

      Example:

      .. literalinclude:: ../includes/sqlite3/mysumaggr.py


   .. method:: create_collation(name, callable)

      Creates a collation with the specified *name* and *callable*. The callable will
      be passed two string arguments. It should return -1 if the first is ordered
      lower than the second, 0 if they are ordered equal and 1 if the first is ordered
      higher than the second.  Note that this controls sorting (ORDER BY in SQL) so
      your comparisons don't affect other SQL operations.

      Note that the callable will get its parameters as Python bytestrings, which will
      normally be encoded in UTF-8.

      The following example shows a custom collation that sorts "the wrong way":

      .. literalinclude:: ../includes/sqlite3/collation_reverse.py

      To remove a collation, call ``create_collation`` with ``None`` as callable::

         con.create_collation("reverse", None)


   .. method:: interrupt()

      You can call this method from a different thread to abort any queries that might
      be executing on the connection. The query will then abort and the caller will
      get an exception.


   .. method:: set_authorizer(authorizer_callback)

      This routine registers a callback. The callback is invoked for each attempt to
      access a column of a table in the database. The callback should return
      :const:`SQLITE_OK` if access is allowed, :const:`SQLITE_DENY` if the entire SQL
      statement should be aborted with an error and :const:`SQLITE_IGNORE` if the
      column should be treated as a NULL value. These constants are available in the
      :mod:`sqlite3` module.

      The first argument to the callback signifies what kind of operation is to be
      authorized. The second and third argument will be arguments or :const:`None`
      depending on the first argument. The 4th argument is the name of the database
      ("main", "temp", etc.) if applicable. The 5th argument is the name of the
      inner-most trigger or view that is responsible for the access attempt or
      :const:`None` if this access attempt is directly from input SQL code.

      Please consult the SQLite documentation about the possible values for the first
      argument and the meaning of the second and third argument depending on the first
      one. All necessary constants are available in the :mod:`sqlite3` module.


   .. method:: set_progress_handler(handler, n)

      This routine registers a callback. The callback is invoked for every *n*
      instructions of the SQLite virtual machine. This is useful if you want to
      get called from SQLite during long-running operations, for example to update
      a GUI.

      If you want to clear any previously installed progress handler, call the
      method with :const:`None` for *handler*.

      .. versionadded:: 2.6


   .. method:: enable_load_extension(enabled)

      This routine allows/disallows the SQLite engine to load SQLite extensions
      from shared libraries.  SQLite extensions can define new functions,
      aggregates or whole new virtual table implementations.  One well-known
      extension is the fulltext-search extension distributed with SQLite.

      Loadable extensions are disabled by default. See [#f1]_.

      .. versionadded:: 2.7

      .. literalinclude:: ../includes/sqlite3/load_extension.py

   .. method:: load_extension(path)

      This routine loads a SQLite extension from a shared library.  You have to
      enable extension loading with :meth:`enable_load_extension` before you can
      use this routine.

      Loadable extensions are disabled by default. See [#f1]_.

      .. versionadded:: 2.7

   .. attribute:: row_factory

      You can change this attribute to a callable that accepts the cursor and the
      original row as a tuple and will return the real result row.  This way, you can
      implement more advanced ways of returning results, such  as returning an object
      that can also access columns by name.

      Example:

      .. literalinclude:: ../includes/sqlite3/row_factory.py

      If returning a tuple doesn't suffice and you want name-based access to
      columns, you should consider setting :attr:`row_factory` to the
      highly-optimized :class:`sqlite3.Row` type. :class:`Row` provides both
      index-based and case-insensitive name-based access to columns with almost no
      memory overhead. It will probably be better than your own custom
      dictionary-based approach or even a db_row based solution.

      .. XXX what's a db_row-based solution?


   .. attribute:: text_factory

      Using this attribute you can control what objects are returned for the ``TEXT``
      data type. By default, this attribute is set to :class:`unicode` and the
      :mod:`sqlite3` module will return Unicode objects for ``TEXT``. If you want to
      return bytestrings instead, you can set it to :class:`str`.

      For efficiency reasons, there's also a way to return Unicode objects only for
      non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
      :const:`sqlite3.OptimizedUnicode`.

      You can also set it to any other callable that accepts a single bytestring
      parameter and returns the resulting object.

      See the following example code for illustration:

      .. literalinclude:: ../includes/sqlite3/text_factory.py


   .. attribute:: total_changes

      Returns the total number of database rows that have been modified, inserted, or
      deleted since the database connection was opened.


   .. attribute:: iterdump

      Returns an iterator to dump the database in an SQL text format.  Useful when
      saving an in-memory database for later restoration.  This function provides
      the same capabilities as the :kbd:`.dump` command in the :program:`sqlite3`
      shell.

      .. versionadded:: 2.6

      Example::

         # Convert file existing_db.db to SQL dump file dump.sql
         import sqlite3, os

         con = sqlite3.connect('existing_db.db')
         with open('dump.sql', 'w') as f:
             for line in con.iterdump():
                 f.write('%s\n' % line)


.. _sqlite3-cursor-objects:

Cursor Objects
--------------

.. class:: Cursor

   A :class:`Cursor` instance has the following attributes and methods.

   .. method:: execute(sql, [parameters])

      Executes an SQL statement. The SQL statement may be parameterized (i. e.
      placeholders instead of SQL literals). The :mod:`sqlite3` module supports two
      kinds of placeholders: question marks (qmark style) and named placeholders
      (named style).

      Here's an example of both styles:

      .. literalinclude:: ../includes/sqlite3/execute_1.py

      :meth:`execute` will only execute a single SQL statement. If you try to execute
      more than one statement with it, it will raise a Warning. Use
      :meth:`executescript` if you want to execute multiple SQL statements with one
      call.


   .. method:: executemany(sql, seq_of_parameters)

      Executes an SQL command against all parameter sequences or mappings found in
      the sequence *sql*.  The :mod:`sqlite3` module also allows using an
      :term:`iterator` yielding parameters instead of a sequence.

      .. literalinclude:: ../includes/sqlite3/executemany_1.py

      Here's a shorter example using a :term:`generator`:

      .. literalinclude:: ../includes/sqlite3/executemany_2.py


   .. method:: executescript(sql_script)

      This is a nonstandard convenience method for executing multiple SQL statements
      at once. It issues a ``COMMIT`` statement first, then executes the SQL script it
      gets as a parameter.

      *sql_script* can be a bytestring or a Unicode string.

      Example:

      .. literalinclude:: ../includes/sqlite3/executescript.py


   .. method:: fetchone()

      Fetches the next row of a query result set, returning a single sequence,
      or :const:`None` when no more data is available.


   .. method:: fetchmany([size=cursor.arraysize])

      Fetches the next set of rows of a query result, returning a list.  An empty
      list is returned when no more rows are available.

      The number of rows to fetch per call is specified by the *size* parameter.
      If it is not given, the cursor's arraysize determines the number of rows
      to be fetched. The method should try to fetch as many rows as indicated by
      the size parameter. If this is not possible due to the specified number of
      rows not being available, fewer rows may be returned.

      Note there are performance considerations involved with the *size* parameter.
      For optimal performance, it is usually best to use the arraysize attribute.
      If the *size* parameter is used, then it is best for it to retain the same
      value from one :meth:`fetchmany` call to the next.

   .. method:: fetchall()

      Fetches all (remaining) rows of a query result, returning a list.  Note that
      the cursor's arraysize attribute can affect the performance of this operation.
      An empty list is returned when no rows are available.


   .. attribute:: rowcount

      Although the :class:`Cursor` class of the :mod:`sqlite3` module implements this
      attribute, the database engine's own support for the determination of "rows
      affected"/"rows selected" is quirky.

      For :meth:`executemany` statements, the number of modifications are summed up
      into :attr:`rowcount`.

      As required by the Python DB API Spec, the :attr:`rowcount` attribute "is -1 in
      case no ``executeXX()`` has been performed on the cursor or the rowcount of the
      last operation is not determinable by the interface". This includes ``SELECT``
      statements because we cannot determine the number of rows a query produced
      until all rows were fetched.

      With SQLite versions before 3.6.5, :attr:`rowcount` is set to 0 if
      you make a ``DELETE FROM table`` without any condition.

   .. attribute:: lastrowid

      This read-only attribute provides the rowid of the last modified row. It is
      only set if you issued an ``INSERT`` statement using the :meth:`execute`
      method. For operations other than ``INSERT`` or when :meth:`executemany` is
      called, :attr:`lastrowid` is set to :const:`None`.

   .. attribute:: description

      This read-only attribute provides the column names of the last query. To
      remain compatible with the Python DB API, it returns a 7-tuple for each
      column where the last six items of each tuple are :const:`None`.

      It is set for ``SELECT`` statements without any matching rows as well.

   .. attribute:: connection

      This read-only attribute provides the SQLite database :class:`Connection`
      used by the :class:`Cursor` object.  A :class:`Cursor` object created by
      calling :meth:`con.cursor() <Connection.cursor>` will have a
      :attr:`connection` attribute that refers to *con*::

         >>> con = sqlite3.connect(":memory:")
         >>> cur = con.cursor()
         >>> cur.connection == con
         True

.. _sqlite3-row-objects:

Row Objects
-----------

.. class:: Row

   A :class:`Row` instance serves as a highly optimized
   :attr:`~Connection.row_factory` for :class:`Connection` objects.
   It tries to mimic a tuple in most of its features.

   It supports mapping access by column name and index, iteration,
   representation, equality testing and :func:`len`.

   If two :class:`Row` objects have exactly the same columns and their
   members are equal, they compare equal.

   .. versionchanged:: 2.6
      Added iteration and equality (hashability).

   .. method:: keys

      This method returns a list of column names. Immediately after a query,
      it is the first member of each tuple in :attr:`Cursor.description`.

      .. versionadded:: 2.6

Let's assume we initialize a table as in the example given above::

   conn = sqlite3.connect(":memory:")
   c = conn.cursor()
   c.execute('''create table stocks
   (date text, trans text, symbol text,
    qty real, price real)''')
   c.execute("""insert into stocks
             values ('2006-01-05','BUY','RHAT',100,35.14)""")
   conn.commit()
   c.close()

Now we plug :class:`Row` in::

   >>> conn.row_factory = sqlite3.Row
   >>> c = conn.cursor()
   >>> c.execute('select * from stocks')
   <sqlite3.Cursor object at 0x7f4e7dd8fa80>
   >>> r = c.fetchone()
   >>> type(r)
   <type 'sqlite3.Row'>
   >>> r
   (u'2006-01-05', u'BUY', u'RHAT', 100.0, 35.14)
   >>> len(r)
   5
   >>> r[2]
   u'RHAT'
   >>> r.keys()
   ['date', 'trans', 'symbol', 'qty', 'price']
   >>> r['qty']
   100.0
   >>> for member in r:
   ...     print member
   ...
   2006-01-05
   BUY
   RHAT
   100.0
   35.14


.. _sqlite3-types:

SQLite and Python types
-----------------------


Introduction
^^^^^^^^^^^^

SQLite natively supports the following types: ``NULL``, ``INTEGER``,
``REAL``, ``TEXT``, ``BLOB``.

The following Python types can thus be sent to SQLite without any problem:

+-----------------------------+-------------+
| Python type                 | SQLite type |
+=============================+=============+
| :const:`None`               | ``NULL``    |
+-----------------------------+-------------+
| :class:`int`                | ``INTEGER`` |
+-----------------------------+-------------+
| :class:`long`               | ``INTEGER`` |
+-----------------------------+-------------+
| :class:`float`              | ``REAL``    |
+-----------------------------+-------------+
| :class:`str` (UTF8-encoded) | ``TEXT``    |
+-----------------------------+-------------+
| :class:`unicode`            | ``TEXT``    |
+-----------------------------+-------------+
| :class:`buffer`             | ``BLOB``    |
+-----------------------------+-------------+

This is how SQLite types are converted to Python types by default:

+-------------+----------------------------------------------+
| SQLite type | Python type                                  |
+=============+==============================================+
| ``NULL``    | :const:`None`                                |
+-------------+----------------------------------------------+
| ``INTEGER`` | :class:`int` or :class:`long`,               |
|             | depending on size                            |
+-------------+----------------------------------------------+
| ``REAL``    | :class:`float`                               |
+-------------+----------------------------------------------+
| ``TEXT``    | depends on :attr:`~Connection.text_factory`, |
|             | :class:`unicode` by default                  |
+-------------+----------------------------------------------+
| ``BLOB``    | :class:`buffer`                              |
+-------------+----------------------------------------------+

The type system of the :mod:`sqlite3` module is extensible in two ways: you can
store additional Python types in a SQLite database via object adaptation, and
you can let the :mod:`sqlite3` module convert SQLite types to different Python
types via converters.


Using adapters to store additional Python types in SQLite databases
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

As described before, SQLite supports only a limited set of types natively. To
use other Python types with SQLite, you must **adapt** them to one of the
sqlite3 module's supported types for SQLite: one of NoneType, int, long, float,
str, unicode, buffer.

There are two ways to enable the :mod:`sqlite3` module to adapt a custom Python
type to one of the supported ones.


Letting your object adapt itself
""""""""""""""""""""""""""""""""

This is a good approach if you write the class yourself. Let's suppose you have
a class like this::

   class Point(object):
       def __init__(self, x, y):
           self.x, self.y = x, y

Now you want to store the point in a single SQLite column.  First you'll have to
choose one of the supported types first to be used for representing the point.
Let's just use str and separate the coordinates using a semicolon. Then you need
to give your class a method ``__conform__(self, protocol)`` which must return
the converted value. The parameter *protocol* will be :class:`PrepareProtocol`.

.. literalinclude:: ../includes/sqlite3/adapter_point_1.py


Registering an adapter callable
"""""""""""""""""""""""""""""""

The other possibility is to create a function that converts the type to the
string representation and register the function with :meth:`register_adapter`.

.. note::

   The type/class to adapt must be a :term:`new-style class`, i. e. it must have
   :class:`object` as one of its bases.

.. literalinclude:: ../includes/sqlite3/adapter_point_2.py

The :mod:`sqlite3` module has two default adapters for Python's built-in
:class:`datetime.date` and :class:`datetime.datetime` types.  Now let's suppose
we want to store :class:`datetime.datetime` objects not in ISO representation,
but as a Unix timestamp.

.. literalinclude:: ../includes/sqlite3/adapter_datetime.py


Converting SQLite values to custom Python types
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Writing an adapter lets you send custom Python types to SQLite. But to make it
really useful we need to make the Python to SQLite to Python roundtrip work.

Enter converters.

Let's go back to the :class:`Point` class. We stored the x and y coordinates
separated via semicolons as strings in SQLite.

First, we'll define a converter function that accepts the string as a parameter
and constructs a :class:`Point` object from it.

.. note::

   Converter functions **always** get called with a string, no matter under which
   data type you sent the value to SQLite.

::

   def convert_point(s):
       x, y = map(float, s.split(";"))
       return Point(x, y)

Now you need to make the :mod:`sqlite3` module know that what you select from
the database is actually a point. There are two ways of doing this:

* Implicitly via the declared type

* Explicitly via the column name

Both ways are described in section :ref:`sqlite3-module-contents`, in the entries
for the constants :const:`PARSE_DECLTYPES` and :const:`PARSE_COLNAMES`.

The following example illustrates both approaches.

.. literalinclude:: ../includes/sqlite3/converter_point.py


Default adapters and converters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

There are default adapters for the date and datetime types in the datetime
module. They will be sent as ISO dates/ISO timestamps to SQLite.

The default converters are registered under the name "date" for
:class:`datetime.date` and under the name "timestamp" for
:class:`datetime.datetime`.

This way, you can use date/timestamps from Python without any additional
fiddling in most cases. The format of the adapters is also compatible with the
experimental SQLite date/time functions.

The following example demonstrates this.

.. literalinclude:: ../includes/sqlite3/pysqlite_datetime.py

If a timestamp stored in SQLite has a fractional part longer than 6
numbers, its value will be truncated to microsecond precision by the
timestamp converter.


.. _sqlite3-controlling-transactions:

Controlling Transactions
------------------------

By default, the :mod:`sqlite3` module opens transactions implicitly before a
Data Modification Language (DML)  statement (i.e.
``INSERT``/``UPDATE``/``DELETE``/``REPLACE``), and commits transactions
implicitly before a non-DML, non-query statement (i. e.
anything other than ``SELECT`` or the aforementioned).

So if you are within a transaction and issue a command like ``CREATE TABLE
...``, ``VACUUM``, ``PRAGMA``, the :mod:`sqlite3` module will commit implicitly
before executing that command. There are two reasons for doing that. The first
is that some of these commands don't work within transactions. The other reason
is that sqlite3 needs to keep track of the transaction state (if a transaction
is active or not).

You can control which kind of ``BEGIN`` statements sqlite3 implicitly executes
(or none at all) via the *isolation_level* parameter to the :func:`connect`
call, or via the :attr:`isolation_level` property of connections.

If you want **autocommit mode**, then set :attr:`isolation_level` to ``None``.

Otherwise leave it at its default, which will result in a plain "BEGIN"
statement, or set it to one of SQLite's supported isolation levels: "DEFERRED",
"IMMEDIATE" or "EXCLUSIVE".



Using :mod:`sqlite3` efficiently
--------------------------------


Using shortcut methods
^^^^^^^^^^^^^^^^^^^^^^

Using the nonstandard :meth:`execute`, :meth:`executemany` and
:meth:`executescript` methods of the :class:`Connection` object, your code can
be written more concisely because you don't have to create the (often
superfluous) :class:`Cursor` objects explicitly. Instead, the :class:`Cursor`
objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a ``SELECT`` statement and iterate over it
directly using only a single call on the :class:`Connection` object.

.. literalinclude:: ../includes/sqlite3/shortcut_methods.py


Accessing columns by name instead of by index
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

One useful feature of the :mod:`sqlite3` module is the built-in
:class:`sqlite3.Row` class designed to be used as a row factory.

Rows wrapped with this class can be accessed both by index (like tuples) and
case-insensitively by name:

.. literalinclude:: ../includes/sqlite3/rowclass.py


Using the connection as a context manager
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. versionadded:: 2.6

Connection objects can be used as context managers
that automatically commit or rollback transactions.  In the event of an
exception, the transaction is rolled back; otherwise, the transaction is
committed:

.. literalinclude:: ../includes/sqlite3/ctx_manager.py


Common issues
-------------

Multithreading
^^^^^^^^^^^^^^

Older SQLite versions had issues with sharing connections between threads.
That's why the Python module disallows sharing connections and cursors between
threads. If you still try to do so, you will get an exception at runtime.

The only exception is calling the :meth:`~Connection.interrupt` method, which
only makes sense to call from a different thread.

.. rubric:: Footnotes

.. [#f1] The sqlite3 module is not built with loadable extension support by
   default, because some platforms (notably Mac OS X) have SQLite libraries
   which are compiled without this feature. To get loadable extension support,
   you must modify setup.py and remove the line that sets
   SQLITE_OMIT_LOAD_EXTENSION.

PK
%�\v��_
+
+!html/_sources/library/ssl.rst.txtnu�[���:mod:`ssl` --- TLS/SSL wrapper for socket objects
=================================================

.. module:: ssl
   :synopsis: TLS/SSL wrapper for socket objects

.. moduleauthor:: Bill Janssen <bill.janssen@gmail.com>
.. sectionauthor::  Bill Janssen <bill.janssen@gmail.com>


.. index:: single: OpenSSL; (use in module ssl)

.. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer

.. versionadded:: 2.6

**Source code:** :source:`Lib/ssl.py`

--------------

This module provides access to Transport Layer Security (often known as "Secure
Sockets Layer") encryption and peer authentication facilities for network
sockets, both client-side and server-side.  This module uses the OpenSSL
library. It is available on all modern Unix systems, Windows, Mac OS X, and
probably additional platforms, as long as OpenSSL is installed on that platform.

.. versionchanged:: 2.7.13
   Updated to support linking with OpenSSL 1.1.0

.. note::

   Some behavior may be platform dependent, since calls are made to the
   operating system socket APIs.  The installed version of OpenSSL may also
   cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with
   openssl version 1.0.1.

.. warning::
   Don't use this module without reading the :ref:`ssl-security`.  Doing so
   may lead to a false sense of security, as the default settings of the
   ssl module are not necessarily appropriate for your application.


This section documents the objects and functions in the ``ssl`` module; for more
general information about TLS, SSL, and certificates, the reader is referred to
the documents in the "See Also" section at the bottom.

This module provides a class, :class:`ssl.SSLSocket`, which is derived from the
:class:`socket.socket` type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL.  It supports
additional methods such as :meth:`getpeercert`, which retrieves the
certificate of the other side of the connection, and :meth:`cipher`,which
retrieves the cipher being used for the secure connection.

For more sophisticated applications, the :class:`ssl.SSLContext` class
helps manage settings and certificates, which can then be inherited
by SSL sockets created through the :meth:`SSLContext.wrap_socket` method.


Functions, Constants, and Exceptions
------------------------------------

.. exception:: SSLError

   Raised to signal an error from the underlying SSL implementation (currently
   provided by the OpenSSL library).  This signifies some problem in the
   higher-level encryption and authentication layer that's superimposed on the
   underlying network connection.  This error is a subtype of
   :exc:`socket.error`, which in turn is a subtype of :exc:`IOError`.  The
   error code and message of :exc:`SSLError` instances are provided by the
   OpenSSL library.

   .. attribute:: library

      A string mnemonic designating the OpenSSL submodule in which the error
      occurred, such as ``SSL``, ``PEM`` or ``X509``.  The range of possible
      values depends on the OpenSSL version.

      .. versionadded:: 2.7.9

   .. attribute:: reason

      A string mnemonic designating the reason this error occurred, for
      example ``CERTIFICATE_VERIFY_FAILED``.  The range of possible
      values depends on the OpenSSL version.

      .. versionadded:: 2.7.9

.. exception:: SSLZeroReturnError

   A subclass of :exc:`SSLError` raised when trying to read or write and
   the SSL connection has been closed cleanly.  Note that this doesn't
   mean that the underlying transport (read TCP) has been closed.

   .. versionadded:: 2.7.9

.. exception:: SSLWantReadError

   A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
   <ssl-nonblocking>` when trying to read or write data, but more data needs
   to be received on the underlying TCP transport before the request can be
   fulfilled.

   .. versionadded:: 2.7.9

.. exception:: SSLWantWriteError

   A subclass of :exc:`SSLError` raised by a :ref:`non-blocking SSL socket
   <ssl-nonblocking>` when trying to read or write data, but more data needs
   to be sent on the underlying TCP transport before the request can be
   fulfilled.

   .. versionadded:: 2.7.9

.. exception:: SSLSyscallError

   A subclass of :exc:`SSLError` raised when a system error was encountered
   while trying to fulfill an operation on a SSL socket.  Unfortunately,
   there is no easy way to inspect the original errno number.

   .. versionadded:: 2.7.9

.. exception:: SSLEOFError

   A subclass of :exc:`SSLError` raised when the SSL connection has been
   terminated abruptly.  Generally, you shouldn't try to reuse the underlying
   transport when this error is encountered.

   .. versionadded:: 2.7.9

.. exception:: CertificateError

   Raised to signal an error with a certificate (such as mismatching
   hostname).  Certificate errors detected by OpenSSL, though, raise
   an :exc:`SSLError`.


Socket creation
^^^^^^^^^^^^^^^

The following function allows for standalone socket creation.  Starting from
Python 2.7.9, it can be more flexible to use :meth:`SSLContext.wrap_socket`
instead.

.. function:: wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version={see docs}, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)

   Takes an instance ``sock`` of :class:`socket.socket`, and returns an instance
   of :class:`ssl.SSLSocket`, a subtype of :class:`socket.socket`, which wraps
   the underlying socket in an SSL context.  ``sock`` must be a
   :data:`~socket.SOCK_STREAM` socket; other socket types are unsupported.

   For client-side sockets, the context construction is lazy; if the
   underlying socket isn't connected yet, the context construction will be
   performed after :meth:`connect` is called on the socket.  For
   server-side sockets, if the socket has no remote peer, it is assumed
   to be a listening socket, and the server-side SSL wrapping is
   automatically performed on client connections accepted via the
   :meth:`accept` method.  :func:`wrap_socket` may raise :exc:`SSLError`.

   The ``keyfile`` and ``certfile`` parameters specify optional files which
   contain a certificate to be used to identify the local side of the
   connection.  See the discussion of :ref:`ssl-certificates` for more
   information on how the certificate is stored in the ``certfile``.

   The parameter ``server_side`` is a boolean which identifies whether
   server-side or client-side behavior is desired from this socket.

   The parameter ``cert_reqs`` specifies whether a certificate is required from
   the other side of the connection, and whether it will be validated if
   provided.  It must be one of the three values :const:`CERT_NONE`
   (certificates ignored), :const:`CERT_OPTIONAL` (not required, but validated
   if provided), or :const:`CERT_REQUIRED` (required and validated).  If the
   value of this parameter is not :const:`CERT_NONE`, then the ``ca_certs``
   parameter must point to a file of CA certificates.

   The ``ca_certs`` file contains a set of concatenated "certification
   authority" certificates, which are used to validate certificates passed from
   the other end of the connection.  See the discussion of
   :ref:`ssl-certificates` for more information about how to arrange the
   certificates in this file.

   The parameter ``ssl_version`` specifies which version of the SSL protocol to
   use.  Typically, the server chooses a particular protocol version, and the
   client must adapt to the server's choice.  Most of the versions are not
   interoperable with the other versions.  If not specified, the default is
   :data:`PROTOCOL_SSLv23`; it provides the most compatibility with other
   versions.

   Here's a table showing which versions in a client (down the side) can connect
   to which versions in a server (along the top):

     .. table::

       ========================  =========  =========  ==========  =========  ===========  ===========
        *client* / **server**    **SSLv2**  **SSLv3**  **SSLv23**  **TLSv1**  **TLSv1.1**  **TLSv1.2**
       ------------------------  ---------  ---------  ----------  ---------  -----------  -----------
        *SSLv2*                    yes        no         yes         no         no         no
        *SSLv3*                    no         yes        yes         no         no         no
        *SSLv23* [1]_              no         yes        yes         yes        yes        yes
        *TLSv1*                    no         no         yes         yes        no         no
        *TLSv1.1*                  no         no         yes         no         yes        no
        *TLSv1.2*                  no         no         yes         no         no         yes
       ========================  =========  =========  ==========  =========  ===========  ===========

   .. rubric:: Footnotes
   .. [1] TLS 1.3 protocol will be available with :data:`PROTOCOL_SSLv23` in
      OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just
      TLS 1.3.

   .. note::

      Which connections succeed will vary depending on the version of
      OpenSSL.  For example, before OpenSSL 1.0.0, an SSLv23 client
      would always attempt SSLv2 connections.

   The *ciphers* parameter sets the available ciphers for this SSL object.
   It should be a string in the `OpenSSL cipher list format
   <https://www.openssl.org/docs/manmaster/man1/ciphers.html>`_.

   The parameter ``do_handshake_on_connect`` specifies whether to do the SSL
   handshake automatically after doing a :meth:`socket.connect`, or whether the
   application program will call it explicitly, by invoking the
   :meth:`SSLSocket.do_handshake` method.  Calling
   :meth:`SSLSocket.do_handshake` explicitly gives the program control over the
   blocking behavior of the socket I/O involved in the handshake.

   The parameter ``suppress_ragged_eofs`` specifies how the
   :meth:`SSLSocket.read` method should signal unexpected EOF from the other end
   of the connection.  If specified as :const:`True` (the default), it returns a
   normal EOF (an empty bytes object) in response to unexpected EOF errors
   raised from the underlying socket; if :const:`False`, it will raise the
   exceptions back to the caller.

   .. versionchanged:: 2.7
      New optional argument *ciphers*.


Context creation
^^^^^^^^^^^^^^^^

A convenience function helps create :class:`SSLContext` objects for common
purposes.

.. function:: create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)

   Return a new :class:`SSLContext` object with default settings for
   the given *purpose*.  The settings are chosen by the :mod:`ssl` module,
   and usually represent a higher security level than when calling the
   :class:`SSLContext` constructor directly.

   *cafile*, *capath*, *cadata* represent optional CA certificates to
   trust for certificate verification, as in
   :meth:`SSLContext.load_verify_locations`.  If all three are
   :const:`None`, this function can choose to trust the system's default
   CA certificates instead.

   The settings are: :data:`PROTOCOL_SSLv23`, :data:`OP_NO_SSLv2`, and
   :data:`OP_NO_SSLv3` with high encryption cipher suites without RC4 and
   without unauthenticated cipher suites. Passing :data:`~Purpose.SERVER_AUTH`
   as *purpose* sets :data:`~SSLContext.verify_mode` to :data:`CERT_REQUIRED`
   and either loads CA certificates (when at least one of *cafile*, *capath* or
   *cadata* is given) or uses :meth:`SSLContext.load_default_certs` to load
   default CA certificates.

   .. note::
      The protocol, options, cipher and other settings may change to more
      restrictive values anytime without prior deprecation.  The values
      represent a fair balance between compatibility and security.

      If your application needs specific settings, you should create a
      :class:`SSLContext` and apply the settings yourself.

   .. note::
      If you find that when certain older clients or servers attempt to connect
      with a :class:`SSLContext` created by this function that they get an error
      stating "Protocol or cipher suite mismatch", it may be that they only
      support SSL3.0 which this function excludes using the
      :data:`OP_NO_SSLv3`. SSL3.0 is widely considered to be `completely broken
      <https://en.wikipedia.org/wiki/POODLE>`_. If you still wish to continue to
      use this function but still allow SSL 3.0 connections you can re-enable
      them using::

         ctx = ssl.create_default_context(Purpose.CLIENT_AUTH)
         ctx.options &= ~ssl.OP_NO_SSLv3

   .. versionadded:: 2.7.9

   .. versionchanged:: 2.7.10

     RC4 was dropped from the default cipher string.

   .. versionchanged:: 2.7.13

     ChaCha20/Poly1305 was added to the default cipher string.

     3DES was dropped from the default cipher string.

.. function:: _https_verify_certificates(enable=True)

   Specifies whether or not server certificates are verified when creating
   client HTTPS connections without specifying a particular SSL context.

   Starting with Python 2.7.9, :mod:`httplib` and modules which use it, such as
   :mod:`urllib2` and :mod:`xmlrpclib`, default to verifying remote server
   certificates received when establishing client HTTPS connections. This
   default verification checks that the certificate is signed by a Certificate
   Authority in the system trust store and that the Common Name (or Subject
   Alternate Name) on the presented certificate matches the requested host.

   Setting *enable* to :const:`True` ensures this default behaviour is in
   effect.

   Setting *enable* to :const:`False` reverts the default HTTPS certificate
   handling to that of Python 2.7.8 and earlier, allowing connections to
   servers using self-signed certificates, servers using certificates signed
   by a Certicate Authority not present in the system trust store, and servers
   where the hostname does not match the presented server certificate.

   The leading underscore on this function denotes that it intentionally does
   not exist in any implementation of Python 3 and may not be present in all
   Python 2.7 implementations. The portable approach to bypassing certificate
   checks or the system trust store when necessary is for tools to enable that
   on a case-by-case basis by explicitly passing in a suitably configured SSL
   context, rather than reverting the default behaviour of the standard library
   client modules.

   .. versionadded:: 2.7.12

   .. seealso::

      * `CVE-2014-9365 <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9365>`_
        -- HTTPS man-in-the-middle attack against Python clients using default settings
      * :pep:`476` -- Enabling certificate verification by default for HTTPS
      * :pep:`493` -- HTTPS verification migration tools for Python 2.7


Random generation
^^^^^^^^^^^^^^^^^

   .. deprecated:: 2.7.13

       OpenSSL has deprecated :func:`ssl.RAND_pseudo_bytes`, use
       :func:`ssl.RAND_bytes` instead.


.. function:: RAND_status()

   Return ``True`` if the SSL pseudo-random number generator has been seeded
   with 'enough' randomness, and ``False`` otherwise.  You can use
   :func:`ssl.RAND_egd` and :func:`ssl.RAND_add` to increase the randomness of
   the pseudo-random number generator.

.. function:: RAND_egd(path)

   If you are running an entropy-gathering daemon (EGD) somewhere, and *path*
   is the pathname of a socket connection open to it, this will read 256 bytes
   of randomness from the socket, and add it to the SSL pseudo-random number
   generator to increase the security of generated secret keys.  This is
   typically only necessary on systems without better sources of randomness.

   See http://egd.sourceforge.net/ or http://prngd.sourceforge.net/ for sources
   of entropy-gathering daemons.

   Availability: not available with LibreSSL and OpenSSL > 1.1.0

.. function:: RAND_add(bytes, entropy)

   Mix the given *bytes* into the SSL pseudo-random number generator.  The
   parameter *entropy* (a float) is a lower bound on the entropy contained in
   string (so you can always use :const:`0.0`).  See :rfc:`1750` for more
   information on sources of entropy.

Certificate handling
^^^^^^^^^^^^^^^^^^^^

.. function:: match_hostname(cert, hostname)

   Verify that *cert* (in decoded format as returned by
   :meth:`SSLSocket.getpeercert`) matches the given *hostname*.  The rules
   applied are those for checking the identity of HTTPS servers as outlined
   in :rfc:`2818` and :rfc:`6125`, except that IP addresses are not currently
   supported. In addition to HTTPS, this function should be suitable for
   checking the identity of servers in various SSL-based protocols such as
   FTPS, IMAPS, POPS and others.

   :exc:`CertificateError` is raised on failure. On success, the function
   returns nothing::

      >>> cert = {'subject': ((('commonName', 'example.com'),),)}
      >>> ssl.match_hostname(cert, "example.com")
      >>> ssl.match_hostname(cert, "example.org")
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
        File "/home/py3k/Lib/ssl.py", line 130, in match_hostname
      ssl.CertificateError: hostname 'example.org' doesn't match 'example.com'

   .. versionadded:: 2.7.9


.. function:: cert_time_to_seconds(cert_time)

   Return the time in seconds since the Epoch, given the ``cert_time``
   string representing the "notBefore" or "notAfter" date from a
   certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C
   locale).

   Here's an example:

   .. doctest:: newcontext

      >>> import ssl
      >>> timestamp = ssl.cert_time_to_seconds("Jan  5 09:34:43 2018 GMT")
      >>> timestamp
      1515144883
      >>> from datetime import datetime
      >>> print(datetime.utcfromtimestamp(timestamp))
      2018-01-05 09:34:43

   "notBefore" or "notAfter" dates must use GMT (:rfc:`5280`).

   .. versionchanged:: 2.7.9
      Interpret the input time as a time in UTC as specified by 'GMT'
      timezone in the input string. Local timezone was used
      previously. Return an integer (no fractions of a second in the
      input format)

.. function:: get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None)

   Given the address ``addr`` of an SSL-protected server, as a (*hostname*,
   *port-number*) pair, fetches the server's certificate, and returns it as a
   PEM-encoded string.  If ``ssl_version`` is specified, uses that version of
   the SSL protocol to attempt to connect to the server.  If ``ca_certs`` is
   specified, it should be a file containing a list of root certificates, the
   same format as used for the same parameter in :func:`wrap_socket`.  The call
   will attempt to validate the server certificate against that set of root
   certificates, and will fail if the validation attempt fails.

   .. versionchanged:: 2.7.9

      This function is now IPv6-compatible, and the default *ssl_version* is
      changed from :data:`PROTOCOL_SSLv3` to :data:`PROTOCOL_SSLv23` for
      maximum compatibility with modern servers.

.. function:: DER_cert_to_PEM_cert(DER_cert_bytes)

   Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
   string version of the same certificate.

.. function:: PEM_cert_to_DER_cert(PEM_cert_string)

   Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
   bytes for that same certificate.

.. function:: get_default_verify_paths()

   Returns a named tuple with paths to OpenSSL's default cafile and capath.
   The paths are the same as used by
   :meth:`SSLContext.set_default_verify_paths`. The return value is a
   :term:`named tuple` ``DefaultVerifyPaths``:

   * :attr:`cafile` - resolved path to cafile or ``None`` if the file doesn't exist,
   * :attr:`capath` - resolved path to capath or ``None`` if the directory doesn't exist,
   * :attr:`openssl_cafile_env` - OpenSSL's environment key that points to a cafile,
   * :attr:`openssl_cafile` - hard coded path to a cafile,
   * :attr:`openssl_capath_env` - OpenSSL's environment key that points to a capath,
   * :attr:`openssl_capath` - hard coded path to a capath directory

   Availability: LibreSSL ignores the environment vars
   :attr:`openssl_cafile_env` and :attr:`openssl_capath_env`

   .. versionadded:: 2.7.9

.. function:: enum_certificates(store_name)

   Retrieve certificates from Windows' system cert store. *store_name* may be
   one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
   stores, too.

   The function returns a list of (cert_bytes, encoding_type, trust) tuples.
   The encoding_type specifies the encoding of cert_bytes. It is either
   :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
   PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set
   of OIDS or exactly ``True`` if the certificate is trustworthy for all
   purposes.

   Example::

      >>> ssl.enum_certificates("CA")
      [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}),
       (b'data...', 'x509_asn', True)]

   Availability: Windows.

   .. versionadded:: 2.7.9

.. function:: enum_crls(store_name)

   Retrieve CRLs from Windows' system cert store. *store_name* may be
   one of ``CA``, ``ROOT`` or ``MY``. Windows may provide additional cert
   stores, too.

   The function returns a list of (cert_bytes, encoding_type, trust) tuples.
   The encoding_type specifies the encoding of cert_bytes. It is either
   :const:`x509_asn` for X.509 ASN.1 data or :const:`pkcs_7_asn` for
   PKCS#7 ASN.1 data.

   Availability: Windows.

   .. versionadded:: 2.7.9


Constants
^^^^^^^^^

.. data:: CERT_NONE

   Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
   parameter to :func:`wrap_socket`.  In this mode (the default), no
   certificates will be required from the other side of the socket connection.
   If a certificate is received from the other end, no attempt to validate it
   is made.

   See the discussion of :ref:`ssl-security` below.

.. data:: CERT_OPTIONAL

   Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
   parameter to :func:`wrap_socket`.  In this mode no certificates will be
   required from the other side of the socket connection; but if they
   are provided, validation will be attempted and an :class:`SSLError`
   will be raised on failure.

   Use of this setting requires a valid set of CA certificates to
   be passed, either to :meth:`SSLContext.load_verify_locations` or as a
   value of the ``ca_certs`` parameter to :func:`wrap_socket`.

.. data:: CERT_REQUIRED

   Possible value for :attr:`SSLContext.verify_mode`, or the ``cert_reqs``
   parameter to :func:`wrap_socket`.  In this mode, certificates are
   required from the other side of the socket connection; an :class:`SSLError`
   will be raised if no certificate is provided, or if its validation fails.

   Use of this setting requires a valid set of CA certificates to
   be passed, either to :meth:`SSLContext.load_verify_locations` or as a
   value of the ``ca_certs`` parameter to :func:`wrap_socket`.

.. data:: VERIFY_DEFAULT

   Possible value for :attr:`SSLContext.verify_flags`. In this mode, certificate
   revocation lists (CRLs) are not checked. By default OpenSSL does neither
   require nor verify CRLs.

   .. versionadded:: 2.7.9

.. data:: VERIFY_CRL_CHECK_LEAF

   Possible value for :attr:`SSLContext.verify_flags`. In this mode, only the
   peer cert is check but non of the intermediate CA certificates. The mode
   requires a valid CRL that is signed by the peer cert's issuer (its direct
   ancestor CA). If no proper has been loaded
   :attr:`SSLContext.load_verify_locations`, validation will fail.

   .. versionadded:: 2.7.9

.. data:: VERIFY_CRL_CHECK_CHAIN

   Possible value for :attr:`SSLContext.verify_flags`. In this mode, CRLs of
   all certificates in the peer cert chain are checked.

   .. versionadded:: 2.7.9

.. data:: VERIFY_X509_STRICT

   Possible value for :attr:`SSLContext.verify_flags` to disable workarounds
   for broken X.509 certificates.

   .. versionadded:: 2.7.9

.. data:: VERIFY_X509_TRUSTED_FIRST

   Possible value for :attr:`SSLContext.verify_flags`. It instructs OpenSSL to
   prefer trusted certificates when building the trust chain to validate a
   certificate. This flag is enabled by default.

   .. versionadded:: 2.7.10

.. data:: PROTOCOL_TLS

   Selects the highest protocol version that both the client and server support.
   Despite the name, this option can select "TLS" protocols as well as "SSL".

   .. versionadded:: 2.7.13

.. data:: PROTOCOL_SSLv23

   Alias for ``PROTOCOL_TLS``.

   .. deprecated:: 2.7.13 Use ``PROTOCOL_TLS`` instead.

.. data:: PROTOCOL_SSLv2

   Selects SSL version 2 as the channel encryption protocol.

   This protocol is not available if OpenSSL is compiled with the
   ``OPENSSL_NO_SSL2`` flag.

   .. warning::

      SSL version 2 is insecure.  Its use is highly discouraged.

   .. deprecated:: 2.7.13 OpenSSL has removed support for SSLv2.

.. data:: PROTOCOL_SSLv3

   Selects SSL version 3 as the channel encryption protocol.

   This protocol is not be available if OpenSSL is compiled with the
   ``OPENSSL_NO_SSLv3`` flag.

   .. warning::

      SSL version 3 is insecure.  Its use is highly discouraged.

   .. deprecated:: 2.7.13

      OpenSSL has deprecated all version specific protocols. Use the default
      protocol with flags like ``OP_NO_SSLv3`` instead.

.. data:: PROTOCOL_TLSv1

   Selects TLS version 1.0 as the channel encryption protocol.

   .. deprecated:: 2.7.13

      OpenSSL has deprecated all version specific protocols. Use the default
      protocol with flags like ``OP_NO_SSLv3`` instead.

.. data:: PROTOCOL_TLSv1_1

   Selects TLS version 1.1 as the channel encryption protocol.
   Available only with openssl version 1.0.1+.

   .. versionadded:: 2.7.9

   .. deprecated:: 2.7.13

      OpenSSL has deprecated all version specific protocols. Use the default
      protocol with flags like ``OP_NO_SSLv3`` instead.

.. data:: PROTOCOL_TLSv1_2

   Selects TLS version 1.2 as the channel encryption protocol. This is the
   most modern version, and probably the best choice for maximum protection,
   if both sides can speak it.  Available only with openssl version 1.0.1+.

   .. versionadded:: 2.7.9

   .. deprecated:: 2.7.13

      OpenSSL has deprecated all version specific protocols. Use the default
      protocol with flags like ``OP_NO_SSLv3`` instead.


.. data:: OP_ALL

   Enables workarounds for various bugs present in other SSL implementations.
   This option is set by default.  It does not necessarily set the same
   flags as OpenSSL's ``SSL_OP_ALL`` constant.

   .. versionadded:: 2.7.9

.. data:: OP_NO_SSLv2

   Prevents an SSLv2 connection.  This option is only applicable in
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
   choosing SSLv2 as the protocol version.

   .. versionadded:: 2.7.9

.. data:: OP_NO_SSLv3

   Prevents an SSLv3 connection.  This option is only applicable in
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
   choosing SSLv3 as the protocol version.

   .. versionadded:: 2.7.9

.. data:: OP_NO_TLSv1

   Prevents a TLSv1 connection.  This option is only applicable in
   conjunction with :const:`PROTOCOL_SSLv23`.  It prevents the peers from
   choosing TLSv1 as the protocol version.

   .. versionadded:: 2.7.9

.. data:: OP_NO_TLSv1_1

   Prevents a TLSv1.1 connection. This option is only applicable in conjunction
   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.1 as
   the protocol version. Available only with openssl version 1.0.1+.

   .. versionadded:: 2.7.9

.. data:: OP_NO_TLSv1_2

   Prevents a TLSv1.2 connection. This option is only applicable in conjunction
   with :const:`PROTOCOL_SSLv23`. It prevents the peers from choosing TLSv1.2 as
   the protocol version. Available only with openssl version 1.0.1+.

   .. versionadded:: 2.7.9

.. data:: OP_NO_TLSv1_3

   Prevents a TLSv1.3 connection. This option is only applicable in conjunction
   with :const:`PROTOCOL_TLS`. It prevents the peers from choosing TLSv1.3 as
   the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later.
   When Python has been compiled against an older version of OpenSSL, the
   flag defaults to *0*.

   .. versionadded:: 2.7.15

.. data:: OP_CIPHER_SERVER_PREFERENCE

   Use the server's cipher ordering preference, rather than the client's.
   This option has no effect on client sockets and SSLv2 server sockets.

   .. versionadded:: 2.7.9

.. data:: OP_SINGLE_DH_USE

   Prevents re-use of the same DH key for distinct SSL sessions.  This
   improves forward secrecy but requires more computational resources.
   This option only applies to server sockets.

   .. versionadded:: 2.7.9

.. data:: OP_SINGLE_ECDH_USE

   Prevents re-use of the same ECDH key for distinct SSL sessions.  This
   improves forward secrecy but requires more computational resources.
   This option only applies to server sockets.

   .. versionadded:: 2.7.9

.. data:: OP_ENABLE_MIDDLEBOX_COMPAT

   Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make
   a TLS 1.3 connection look more like a TLS 1.2 connection.

   This option is only available with OpenSSL 1.1.1 and later.

   .. versionadded:: 2.7.16

.. data:: OP_NO_COMPRESSION

   Disable compression on the SSL channel.  This is useful if the application
   protocol supports its own compression scheme.

   This option is only available with OpenSSL 1.0.0 and later.

   .. versionadded:: 2.7.9

.. data:: HAS_ALPN

   Whether the OpenSSL library has built-in support for the *Application-Layer
   Protocol Negotiation* TLS extension as described in :rfc:`7301`.

   .. versionadded:: 2.7.10

.. data:: HAS_ECDH

   Whether the OpenSSL library has built-in support for Elliptic Curve-based
   Diffie-Hellman key exchange.  This should be true unless the feature was
   explicitly disabled by the distributor.

   .. versionadded:: 2.7.9

.. data:: HAS_SNI

   Whether the OpenSSL library has built-in support for the *Server Name
   Indication* extension (as defined in :rfc:`4366`).

   .. versionadded:: 2.7.9

.. data:: HAS_NPN

   Whether the OpenSSL library has built-in support for *Next Protocol
   Negotiation* as described in the `NPN draft specification
   <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. When true,
   you can use the :meth:`SSLContext.set_npn_protocols` method to advertise
   which protocols you want to support.

   .. versionadded:: 2.7.9

.. data:: HAS_TLSv1_3

   Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.

   .. versionadded:: 2.7.15

.. data:: CHANNEL_BINDING_TYPES

   List of supported TLS channel binding types.  Strings in this list
   can be used as arguments to :meth:`SSLSocket.get_channel_binding`.

   .. versionadded:: 2.7.9

.. data:: OPENSSL_VERSION

   The version string of the OpenSSL library loaded by the interpreter::

    >>> ssl.OPENSSL_VERSION
    'OpenSSL 0.9.8k 25 Mar 2009'

   .. versionadded:: 2.7

.. data:: OPENSSL_VERSION_INFO

   A tuple of five integers representing version information about the
   OpenSSL library::

    >>> ssl.OPENSSL_VERSION_INFO
    (0, 9, 8, 11, 15)

   .. versionadded:: 2.7

.. data:: OPENSSL_VERSION_NUMBER

   The raw version number of the OpenSSL library, as a single integer::

    >>> ssl.OPENSSL_VERSION_NUMBER
    9470143L
    >>> hex(ssl.OPENSSL_VERSION_NUMBER)
    '0x9080bfL'

   .. versionadded:: 2.7

.. data:: ALERT_DESCRIPTION_HANDSHAKE_FAILURE
          ALERT_DESCRIPTION_INTERNAL_ERROR
          ALERT_DESCRIPTION_*

   Alert Descriptions from :rfc:`5246` and others. The `IANA TLS Alert Registry
   <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6>`_
   contains this list and references to the RFCs where their meaning is defined.

   Used as the return value of the callback function in
   :meth:`SSLContext.set_servername_callback`.

   .. versionadded:: 2.7.9

.. data:: Purpose.SERVER_AUTH

   Option for :func:`create_default_context` and
   :meth:`SSLContext.load_default_certs`.  This value indicates that the
   context may be used to authenticate Web servers (therefore, it will
   be used to create client-side sockets).

   .. versionadded:: 2.7.9

.. data:: Purpose.CLIENT_AUTH

   Option for :func:`create_default_context` and
   :meth:`SSLContext.load_default_certs`.  This value indicates that the
   context may be used to authenticate Web clients (therefore, it will
   be used to create server-side sockets).

   .. versionadded:: 2.7.9


SSL Sockets
-----------

SSL sockets provide the following methods of :ref:`socket-objects`:

- :meth:`~socket.socket.accept()`
- :meth:`~socket.socket.bind()`
- :meth:`~socket.socket.close()`
- :meth:`~socket.socket.connect()`
- :meth:`~socket.socket.fileno()`
- :meth:`~socket.socket.getpeername()`, :meth:`~socket.socket.getsockname()`
- :meth:`~socket.socket.getsockopt()`, :meth:`~socket.socket.setsockopt()`
- :meth:`~socket.socket.gettimeout()`, :meth:`~socket.socket.settimeout()`,
  :meth:`~socket.socket.setblocking()`
- :meth:`~socket.socket.listen()`
- :meth:`~socket.socket.makefile()`
- :meth:`~socket.socket.recv()`, :meth:`~socket.socket.recv_into()`
  (but passing a non-zero ``flags`` argument is not allowed)
- :meth:`~socket.socket.send()`, :meth:`~socket.socket.sendall()` (with
  the same limitation)
- :meth:`~socket.socket.shutdown()`

However, since the SSL (and TLS) protocol has its own framing atop
of TCP, the SSL sockets abstraction can, in certain respects, diverge from
the specification of normal, OS-level sockets.  See especially the
:ref:`notes on non-blocking sockets <ssl-nonblocking>`.

SSL sockets also have the following additional methods and attributes:

.. method:: SSLSocket.do_handshake()

   Perform the SSL setup handshake.

   .. versionchanged:: 2.7.9

      The handshake method also performs :func:`match_hostname` when the
      :attr:`~SSLContext.check_hostname` attribute of the socket's
      :attr:`~SSLSocket.context` is true.

.. method:: SSLSocket.getpeercert(binary_form=False)

   If there is no certificate for the peer on the other end of the connection,
   return ``None``.  If the SSL handshake hasn't been done yet, raise
   :exc:`ValueError`.

   If the ``binary_form`` parameter is :const:`False`, and a certificate was
   received from the peer, this method returns a :class:`dict` instance.  If the
   certificate was not validated, the dict is empty.  If the certificate was
   validated, it returns a dict with several keys, amongst them ``subject``
   (the principal for which the certificate was issued) and ``issuer``
   (the principal issuing the certificate).  If a certificate contains an
   instance of the *Subject Alternative Name* extension (see :rfc:`3280`),
   there will also be a ``subjectAltName`` key in the dictionary.

   The ``subject`` and ``issuer`` fields are tuples containing the sequence
   of relative distinguished names (RDNs) given in the certificate's data
   structure for the respective fields, and each RDN is a sequence of
   name-value pairs.  Here is a real-world example::

      {'issuer': ((('countryName', 'IL'),),
                  (('organizationName', 'StartCom Ltd.'),),
                  (('organizationalUnitName',
                    'Secure Digital Certificate Signing'),),
                  (('commonName',
                    'StartCom Class 2 Primary Intermediate Server CA'),)),
       'notAfter': 'Nov 22 08:15:19 2013 GMT',
       'notBefore': 'Nov 21 03:09:52 2011 GMT',
       'serialNumber': '95F0',
       'subject': ((('description', '571208-SLe257oHY9fVQ07Z'),),
                   (('countryName', 'US'),),
                   (('stateOrProvinceName', 'California'),),
                   (('localityName', 'San Francisco'),),
                   (('organizationName', 'Electronic Frontier Foundation, Inc.'),),
                   (('commonName', '*.eff.org'),),
                   (('emailAddress', 'hostmaster@eff.org'),)),
       'subjectAltName': (('DNS', '*.eff.org'), ('DNS', 'eff.org')),
       'version': 3}

   .. note::

      To validate a certificate for a particular service, you can use the
      :func:`match_hostname` function.

   If the ``binary_form`` parameter is :const:`True`, and a certificate was
   provided, this method returns the DER-encoded form of the entire certificate
   as a sequence of bytes, or :const:`None` if the peer did not provide a
   certificate.  Whether the peer provides a certificate depends on the SSL
   socket's role:

   * for a client SSL socket, the server will always provide a certificate,
     regardless of whether validation was required;

   * for a server SSL socket, the client will only provide a certificate
     when requested by the server; therefore :meth:`getpeercert` will return
     :const:`None` if you used :const:`CERT_NONE` (rather than
     :const:`CERT_OPTIONAL` or :const:`CERT_REQUIRED`).

   .. versionchanged:: 2.7.9
      The returned dictionary includes additional items such as ``issuer`` and
      ``notBefore``. Additionall :exc:`ValueError` is raised when the handshake
      isn't done. The returned dictionary includes additional X509v3 extension
      items such as ``crlDistributionPoints``, ``caIssuers`` and ``OCSP`` URIs.

.. method:: SSLSocket.cipher()

   Returns a three-value tuple containing the name of the cipher being used, the
   version of the SSL protocol that defines its use, and the number of secret
   bits being used.  If no connection has been established, returns ``None``.

.. method:: SSLSocket.compression()

   Return the compression algorithm being used as a string, or ``None``
   if the connection isn't compressed.

   If the higher-level protocol supports its own compression mechanism,
   you can use :data:`OP_NO_COMPRESSION` to disable SSL-level compression.

   .. versionadded:: 2.7.9

.. method:: SSLSocket.get_channel_binding(cb_type="tls-unique")

   Get channel binding data for current connection, as a bytes object.  Returns
   ``None`` if not connected or the handshake has not been completed.

   The *cb_type* parameter allow selection of the desired channel binding
   type. Valid channel binding types are listed in the
   :data:`CHANNEL_BINDING_TYPES` list.  Currently only the 'tls-unique' channel
   binding, defined by :rfc:`5929`, is supported.  :exc:`ValueError` will be
   raised if an unsupported channel binding type is requested.

   .. versionadded:: 2.7.9

.. method:: SSLSocket.selected_alpn_protocol()

   Return the protocol that was selected during the TLS handshake.  If
   :meth:`SSLContext.set_alpn_protocols` was not called, if the other party does
   not support ALPN, if this socket does not support any of the client's
   proposed protocols, or if the handshake has not happened yet, ``None`` is
   returned.

   .. versionadded:: 2.7.10

.. method:: SSLSocket.selected_npn_protocol()

   Return the higher-level protocol that was selected during the TLS/SSL
   handshake. If :meth:`SSLContext.set_npn_protocols` was not called, or
   if the other party does not support NPN, or if the handshake has not yet
   happened, this will return ``None``.

   .. versionadded:: 2.7.9

.. method:: SSLSocket.unwrap()

   Performs the SSL shutdown handshake, which removes the TLS layer from the
   underlying socket, and returns the underlying socket object.  This can be
   used to go from encrypted operation over a connection to unencrypted.  The
   returned socket should always be used for further communication with the
   other side of the connection, rather than the original socket.

.. method:: SSLSocket.version()

   Return the actual SSL protocol version negotiated by the connection
   as a string, or ``None`` is no secure connection is established.
   As of this writing, possible return values include ``"SSLv2"``,
   ``"SSLv3"``, ``"TLSv1"``, ``"TLSv1.1"`` and ``"TLSv1.2"``.
   Recent OpenSSL versions may define more return values.

   .. versionadded:: 2.7.9

.. attribute:: SSLSocket.context

   The :class:`SSLContext` object this SSL socket is tied to.  If the SSL
   socket was created using the top-level :func:`wrap_socket` function
   (rather than :meth:`SSLContext.wrap_socket`), this is a custom context
   object created for this SSL socket.

   .. versionadded:: 2.7.9


SSL Contexts
------------

.. versionadded:: 2.7.9

An SSL context holds various data longer-lived than single SSL connections,
such as SSL configuration options, certificate(s) and private key(s).
It also manages a cache of SSL sessions for server-side sockets, in order
to speed up repeated connections from the same clients.

.. class:: SSLContext(protocol)

   Create a new SSL context.  You must pass *protocol* which must be one
   of the ``PROTOCOL_*`` constants defined in this module.
   :data:`PROTOCOL_SSLv23` is currently recommended for maximum
   interoperability.

   .. seealso::
      :func:`create_default_context` lets the :mod:`ssl` module choose
      security settings for a given purpose.

   .. versionchanged:: 2.7.16

      The context is created with secure default values. The options
      :data:`OP_NO_COMPRESSION`, :data:`OP_CIPHER_SERVER_PREFERENCE`,
      :data:`OP_SINGLE_DH_USE`, :data:`OP_SINGLE_ECDH_USE`,
      :data:`OP_NO_SSLv2` (except for :data:`PROTOCOL_SSLv2`),
      and :data:`OP_NO_SSLv3` (except for :data:`PROTOCOL_SSLv3`) are
      set by default. The initial cipher suite list contains only ``HIGH``
      ciphers, no ``NULL`` ciphers and no ``MD5`` ciphers (except for
      :data:`PROTOCOL_SSLv2`).


:class:`SSLContext` objects have the following methods and attributes:

.. method:: SSLContext.cert_store_stats()

   Get statistics about quantities of loaded X.509 certificates, count of
   X.509 certificates flagged as CA certificates and certificate revocation
   lists as dictionary.

   Example for a context with one CA cert and one other cert::

      >>> context.cert_store_stats()
      {'crl': 0, 'x509_ca': 1, 'x509': 2}


.. method:: SSLContext.load_cert_chain(certfile, keyfile=None, password=None)

   Load a private key and the corresponding certificate.  The *certfile*
   string must be the path to a single file in PEM format containing the
   certificate as well as any number of CA certificates needed to establish
   the certificate's authenticity.  The *keyfile* string, if present, must
   point to a file containing the private key in.  Otherwise the private
   key will be taken from *certfile* as well.  See the discussion of
   :ref:`ssl-certificates` for more information on how the certificate
   is stored in the *certfile*.

   The *password* argument may be a function to call to get the password for
   decrypting the private key.  It will only be called if the private key is
   encrypted and a password is necessary.  It will be called with no arguments,
   and it should return a string, bytes, or bytearray.  If the return value is
   a string it will be encoded as UTF-8 before using it to decrypt the key.
   Alternatively a string, bytes, or bytearray value may be supplied directly
   as the *password* argument.  It will be ignored if the private key is not
   encrypted and no password is needed.

   If the *password* argument is not specified and a password is required,
   OpenSSL's built-in password prompting mechanism will be used to
   interactively prompt the user for a password.

   An :class:`SSLError` is raised if the private key doesn't
   match with the certificate.

.. method:: SSLContext.load_default_certs(purpose=Purpose.SERVER_AUTH)

   Load a set of default "certification authority" (CA) certificates from
   default locations. On Windows it loads CA certs from the ``CA`` and
   ``ROOT`` system stores. On other systems it calls
   :meth:`SSLContext.set_default_verify_paths`. In the future the method may
   load CA certificates from other locations, too.

   The *purpose* flag specifies what kind of CA certificates are loaded. The
   default settings :data:`Purpose.SERVER_AUTH` loads certificates, that are
   flagged and trusted for TLS web server authentication (client side
   sockets). :data:`Purpose.CLIENT_AUTH` loads CA certificates for client
   certificate verification on the server side.

.. method:: SSLContext.load_verify_locations(cafile=None, capath=None, cadata=None)

   Load a set of "certification authority" (CA) certificates used to validate
   other peers' certificates when :data:`verify_mode` is other than
   :data:`CERT_NONE`.  At least one of *cafile* or *capath* must be specified.

   This method can also load certification revocation lists (CRLs) in PEM or
   DER format. In order to make use of CRLs, :attr:`SSLContext.verify_flags`
   must be configured properly.

   The *cafile* string, if present, is the path to a file of concatenated
   CA certificates in PEM format. See the discussion of
   :ref:`ssl-certificates` for more information about how to arrange the
   certificates in this file.

   The *capath* string, if present, is
   the path to a directory containing several CA certificates in PEM format,
   following an `OpenSSL specific layout
   <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html>`_.

   The *cadata* object, if present, is either an ASCII string of one or more
   PEM-encoded certificates or a bytes-like object of DER-encoded
   certificates. Like with *capath* extra lines around PEM-encoded
   certificates are ignored but at least one certificate must be present.

.. method:: SSLContext.get_ca_certs(binary_form=False)

   Get a list of loaded "certification authority" (CA) certificates. If the
   ``binary_form`` parameter is :const:`False` each list
   entry is a dict like the output of :meth:`SSLSocket.getpeercert`. Otherwise
   the method returns a list of DER-encoded certificates. The returned list
   does not contain certificates from *capath* unless a certificate was
   requested and loaded by a SSL connection.

   .. note::
      Certificates in a capath directory aren't loaded unless they have
      been used at least once.

.. method:: SSLContext.set_default_verify_paths()

   Load a set of default "certification authority" (CA) certificates from
   a filesystem path defined when building the OpenSSL library.  Unfortunately,
   there's no easy way to know whether this method succeeds: no error is
   returned if no certificates are to be found.  When the OpenSSL library is
   provided as part of the operating system, though, it is likely to be
   configured properly.

.. method:: SSLContext.set_ciphers(ciphers)

   Set the available ciphers for sockets created with this context.
   It should be a string in the `OpenSSL cipher list format
   <https://www.openssl.org/docs/manmaster/man1/ciphers.html>`_.
   If no cipher can be selected (because compile-time options or other
   configuration forbids use of all the specified ciphers), an
   :class:`SSLError` will be raised.

   .. note::
      when connected, the :meth:`SSLSocket.cipher` method of SSL sockets will
      give the currently selected cipher.

      OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites
      cannot be disabled with :meth:`~SSLContext.set_ciphers`.

.. method:: SSLContext.set_alpn_protocols(protocols)

   Specify which protocols the socket should advertise during the SSL/TLS
   handshake. It should be a list of ASCII strings, like ``['http/1.1',
   'spdy/2']``, ordered by preference. The selection of a protocol will happen
   during the handshake, and will play out according to :rfc:`7301`. After a
   successful handshake, the :meth:`SSLSocket.selected_alpn_protocol` method will
   return the agreed-upon protocol.

   This method will raise :exc:`NotImplementedError` if :data:`HAS_ALPN` is
   False.

   OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise :exc:`SSLError`
   when both sides support ALPN but cannot agree on a protocol. 1.1.0f+
   behaves like 1.0.2, :meth:`SSLSocket.selected_alpn_protocol` returns None.

   .. versionadded:: 2.7.10

.. method:: SSLContext.set_npn_protocols(protocols)

   Specify which protocols the socket should advertise during the SSL/TLS
   handshake. It should be a list of strings, like ``['http/1.1', 'spdy/2']``,
   ordered by preference. The selection of a protocol will happen during the
   handshake, and will play out according to the `NPN draft specification
   <https://tools.ietf.org/html/draft-agl-tls-nextprotoneg>`_. After a
   successful handshake, the :meth:`SSLSocket.selected_npn_protocol` method will
   return the agreed-upon protocol.

   This method will raise :exc:`NotImplementedError` if :data:`HAS_NPN` is
   False.

.. method:: SSLContext.set_servername_callback(server_name_callback)

   Register a callback function that will be called after the TLS Client Hello
   handshake message has been received by the SSL/TLS server when the TLS client
   specifies a server name indication. The server name indication mechanism
   is specified in :rfc:`6066` section 3 - Server Name Indication.

   Only one callback can be set per ``SSLContext``.  If *server_name_callback*
   is ``None`` then the callback is disabled. Calling this function a
   subsequent time will disable the previously registered callback.

   The callback function, *server_name_callback*, will be called with three
   arguments; the first being the :class:`ssl.SSLSocket`, the second is a string
   that represents the server name that the client is intending to communicate
   (or :const:`None` if the TLS Client Hello does not contain a server name)
   and the third argument is the original :class:`SSLContext`. The server name
   argument is the IDNA decoded server name.

   A typical use of this callback is to change the :class:`ssl.SSLSocket`'s
   :attr:`SSLSocket.context` attribute to a new object of type
   :class:`SSLContext` representing a certificate chain that matches the server
   name.

   Due to the early negotiation phase of the TLS connection, only limited
   methods and attributes are usable like
   :meth:`SSLSocket.selected_alpn_protocol` and :attr:`SSLSocket.context`.
   :meth:`SSLSocket.getpeercert`, :meth:`SSLSocket.getpeercert`,
   :meth:`SSLSocket.cipher` and :meth:`SSLSocket.compress` methods require that
   the TLS connection has progressed beyond the TLS Client Hello and therefore
   will not contain return meaningful values nor can they be called safely.

   The *server_name_callback* function must return ``None`` to allow the
   TLS negotiation to continue.  If a TLS failure is required, a constant
   :const:`ALERT_DESCRIPTION_* <ALERT_DESCRIPTION_INTERNAL_ERROR>` can be
   returned.  Other return values will result in a TLS fatal error with
   :const:`ALERT_DESCRIPTION_INTERNAL_ERROR`.

   If there is an IDNA decoding error on the server name, the TLS connection
   will terminate with an :const:`ALERT_DESCRIPTION_INTERNAL_ERROR` fatal TLS
   alert message to the client.

   If an exception is raised from the *server_name_callback* function the TLS
   connection will terminate with a fatal TLS alert message
   :const:`ALERT_DESCRIPTION_HANDSHAKE_FAILURE`.

   This method will raise :exc:`NotImplementedError` if the OpenSSL library
   had OPENSSL_NO_TLSEXT defined when it was built.

.. method:: SSLContext.load_dh_params(dhfile)

   Load the key generation parameters for Diffie-Helman (DH) key exchange.
   Using DH key exchange improves forward secrecy at the expense of
   computational resources (both on the server and on the client).
   The *dhfile* parameter should be the path to a file containing DH
   parameters in PEM format.

   This setting doesn't apply to client sockets.  You can also use the
   :data:`OP_SINGLE_DH_USE` option to further improve security.

.. method:: SSLContext.set_ecdh_curve(curve_name)

   Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
   exchange.  ECDH is significantly faster than regular DH while arguably
   as secure.  The *curve_name* parameter should be a string describing
   a well-known elliptic curve, for example ``prime256v1`` for a widely
   supported curve.

   This setting doesn't apply to client sockets.  You can also use the
   :data:`OP_SINGLE_ECDH_USE` option to further improve security.

   This method is not available if :data:`HAS_ECDH` is ``False``.

   .. seealso::
      `SSL/TLS & Perfect Forward Secrecy <http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html>`_
         Vincent Bernat.

.. method:: SSLContext.wrap_socket(sock, server_side=False, \
      do_handshake_on_connect=True, suppress_ragged_eofs=True, \
      server_hostname=None)

   Wrap an existing Python socket *sock* and return an :class:`SSLSocket`
   object.  *sock* must be a :data:`~socket.SOCK_STREAM` socket; other socket
   types are unsupported.

   The returned SSL socket is tied to the context, its settings and
   certificates.  The parameters *server_side*, *do_handshake_on_connect*
   and *suppress_ragged_eofs* have the same meaning as in the top-level
   :func:`wrap_socket` function.

   On client connections, the optional parameter *server_hostname* specifies
   the hostname of the service which we are connecting to.  This allows a
   single server to host multiple SSL-based services with distinct certificates,
   quite similarly to HTTP virtual hosts. Specifying *server_hostname* will
   raise a :exc:`ValueError` if *server_side* is true.

   .. versionchanged:: 2.7.9
      Always allow a server_hostname to be passed, even if OpenSSL does not
      have SNI.

.. method:: SSLContext.session_stats()

   Get statistics about the SSL sessions created or managed by this context.
   A dictionary is returned which maps the names of each `piece of information
   <https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html>`_ to their
   numeric values.  For example, here is the total number of hits and misses
   in the session cache since the context was created::

      >>> stats = context.session_stats()
      >>> stats['hits'], stats['misses']
      (0, 0)

.. attribute:: SSLContext.check_hostname

   Wether to match the peer cert's hostname with :func:`match_hostname` in
   :meth:`SSLSocket.do_handshake`. The context's
   :attr:`~SSLContext.verify_mode` must be set to :data:`CERT_OPTIONAL` or
   :data:`CERT_REQUIRED`, and you must pass *server_hostname* to
   :meth:`~SSLContext.wrap_socket` in order to match the hostname.

   Example::

      import socket, ssl

      context = ssl.SSLContext(ssl.PROTOCOL_TLS)
      context.verify_mode = ssl.CERT_REQUIRED
      context.check_hostname = True
      context.load_default_certs()

      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      ssl_sock = context.wrap_socket(s, server_hostname='www.verisign.com')
      ssl_sock.connect(('www.verisign.com', 443))

   .. note::

     This features requires OpenSSL 0.9.8f or newer.

.. attribute:: SSLContext.options

   An integer representing the set of SSL options enabled on this context.
   The default value is :data:`OP_ALL`, but you can specify other options
   such as :data:`OP_NO_SSLv2` by ORing them together.

   .. note::
      With versions of OpenSSL older than 0.9.8m, it is only possible
      to set options, not to clear them.  Attempting to clear an option
      (by resetting the corresponding bits) will raise a ``ValueError``.

.. attribute:: SSLContext.protocol

   The protocol version chosen when constructing the context.  This attribute
   is read-only.

.. attribute:: SSLContext.verify_flags

   The flags for certificate verification operations. You can set flags like
   :data:`VERIFY_CRL_CHECK_LEAF` by ORing them together. By default OpenSSL
   does neither require nor verify certificate revocation lists (CRLs).
   Available only with openssl version 0.9.8+.

.. attribute:: SSLContext.verify_mode

   Whether to try to verify other peers' certificates and how to behave
   if verification fails.  This attribute must be one of
   :data:`CERT_NONE`, :data:`CERT_OPTIONAL` or :data:`CERT_REQUIRED`.


.. index:: single: certificates

.. index:: single: X509 certificate

.. _ssl-certificates:

Certificates
------------

Certificates in general are part of a public-key / private-key system.  In this
system, each *principal*, (which may be a machine, or a person, or an
organization) is assigned a unique two-part encryption key.  One part of the key
is public, and is called the *public key*; the other part is kept secret, and is
called the *private key*.  The two parts are related, in that if you encrypt a
message with one of the parts, you can decrypt it with the other part, and
**only** with the other part.

A certificate contains information about two principals.  It contains the name
of a *subject*, and the subject's public key.  It also contains a statement by a
second principal, the *issuer*, that the subject is who they claim to be, and
that this is indeed the subject's public key.  The issuer's statement is signed
with the issuer's private key, which only the issuer knows.  However, anyone can
verify the issuer's statement by finding the issuer's public key, decrypting the
statement with it, and comparing it to the other information in the certificate.
The certificate also contains information about the time period over which it is
valid.  This is expressed as two fields, called "notBefore" and "notAfter".

In the Python use of certificates, a client or server can use a certificate to
prove who they are.  The other side of a network connection can also be required
to produce a certificate, and that certificate can be validated to the
satisfaction of the client or server that requires such validation.  The
connection attempt can be set to raise an exception if the validation fails.
Validation is done automatically, by the underlying OpenSSL framework; the
application need not concern itself with its mechanics.  But the application
does usually need to provide sets of certificates to allow this process to take
place.

Python uses files to contain certificates.  They should be formatted as "PEM"
(see :rfc:`1422`), which is a base-64 encoded form wrapped with a header line
and a footer line::

      -----BEGIN CERTIFICATE-----
      ... (certificate in base64 PEM encoding) ...
      -----END CERTIFICATE-----

Certificate chains
^^^^^^^^^^^^^^^^^^

The Python files which contain certificates can contain a sequence of
certificates, sometimes called a *certificate chain*.  This chain should start
with the specific certificate for the principal who "is" the client or server,
and then the certificate for the issuer of that certificate, and then the
certificate for the issuer of *that* certificate, and so on up the chain till
you get to a certificate which is *self-signed*, that is, a certificate which
has the same subject and issuer, sometimes called a *root certificate*.  The
certificates should just be concatenated together in the certificate file.  For
example, suppose we had a three certificate chain, from our server certificate
to the certificate of the certification authority that signed our server
certificate, to the root certificate of the agency which issued the
certification authority's certificate::

      -----BEGIN CERTIFICATE-----
      ... (certificate for your server)...
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      ... (the certificate for the CA)...
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      ... (the root certificate for the CA's issuer)...
      -----END CERTIFICATE-----

CA certificates
^^^^^^^^^^^^^^^

If you are going to require validation of the other side of the connection's
certificate, you need to provide a "CA certs" file, filled with the certificate
chains for each issuer you are willing to trust.  Again, this file just contains
these chains concatenated together.  For validation, Python will use the first
chain it finds in the file which matches.  The platform's certificates file can
be used by calling :meth:`SSLContext.load_default_certs`, this is done
automatically with :func:`.create_default_context`.

Combined key and certificate
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Often the private key is stored in the same file as the certificate; in this
case, only the ``certfile`` parameter to :meth:`SSLContext.load_cert_chain`
and :func:`wrap_socket` needs to be passed.  If the private key is stored
with the certificate, it should come before the first certificate in
the certificate chain::

   -----BEGIN RSA PRIVATE KEY-----
   ... (private key in base64 encoding) ...
   -----END RSA PRIVATE KEY-----
   -----BEGIN CERTIFICATE-----
   ... (certificate in base64 PEM encoding) ...
   -----END CERTIFICATE-----

Self-signed certificates
^^^^^^^^^^^^^^^^^^^^^^^^

If you are going to create a server that provides SSL-encrypted connection
services, you will need to acquire a certificate for that service.  There are
many ways of acquiring appropriate certificates, such as buying one from a
certification authority.  Another common practice is to generate a self-signed
certificate.  The simplest way to do this is with the OpenSSL package, using
something like the following::

  % openssl req -new -x509 -days 365 -nodes -out cert.pem -keyout cert.pem
  Generating a 1024 bit RSA private key
  .......++++++
  .............................++++++
  writing new private key to 'cert.pem'
  -----
  You are about to be asked to enter information that will be incorporated
  into your certificate request.
  What you are about to enter is what is called a Distinguished Name or a DN.
  There are quite a few fields but you can leave some blank
  For some fields there will be a default value,
  If you enter '.', the field will be left blank.
  -----
  Country Name (2 letter code) [AU]:US
  State or Province Name (full name) [Some-State]:MyState
  Locality Name (eg, city) []:Some City
  Organization Name (eg, company) [Internet Widgits Pty Ltd]:My Organization, Inc.
  Organizational Unit Name (eg, section) []:My Group
  Common Name (eg, YOUR name) []:myserver.mygroup.myorganization.com
  Email Address []:ops@myserver.mygroup.myorganization.com
  %

The disadvantage of a self-signed certificate is that it is its own root
certificate, and no one else will have it in their cache of known (and trusted)
root certificates.


Examples
--------

Testing for SSL support
^^^^^^^^^^^^^^^^^^^^^^^

To test for the presence of SSL support in a Python installation, user code
should use the following idiom::

   try:
       import ssl
   except ImportError:
       pass
   else:
       ...  # do something that requires SSL support

Client-side operation
^^^^^^^^^^^^^^^^^^^^^

This example creates a SSL context with the recommended security settings
for client sockets, including automatic certificate verification::

   >>> context = ssl.create_default_context()

If you prefer to tune security settings yourself, you might create
a context from scratch (but beware that you might not get the settings
right)::

   >>> context = ssl.SSLContext(ssl.PROTOCOL_TLS)
   >>> context.verify_mode = ssl.CERT_REQUIRED
   >>> context.check_hostname = True
   >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt")

(this snippet assumes your operating system places a bundle of all CA
certificates in ``/etc/ssl/certs/ca-bundle.crt``; if not, you'll get an
error and have to adjust the location)

When you use the context to connect to a server, :const:`CERT_REQUIRED`
validates the server certificate: it ensures that the server certificate
was signed with one of the CA certificates, and checks the signature for
correctness::

   >>> conn = context.wrap_socket(socket.socket(socket.AF_INET),
   ...                            server_hostname="www.python.org")
   >>> conn.connect(("www.python.org", 443))

You may then fetch the certificate::

   >>> cert = conn.getpeercert()

Visual inspection shows that the certificate does identify the desired service
(that is, the HTTPS host ``www.python.org``)::

   >>> pprint.pprint(cert)
   {'OCSP': ('http://ocsp.digicert.com',),
    'caIssuers': ('http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt',),
    'crlDistributionPoints': ('http://crl3.digicert.com/sha2-ev-server-g1.crl',
                              'http://crl4.digicert.com/sha2-ev-server-g1.crl'),
    'issuer': ((('countryName', 'US'),),
               (('organizationName', 'DigiCert Inc'),),
               (('organizationalUnitName', 'www.digicert.com'),),
               (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)),
    'notAfter': 'Sep  9 12:00:00 2016 GMT',
    'notBefore': 'Sep  5 00:00:00 2014 GMT',
    'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26',
    'subject': ((('businessCategory', 'Private Organization'),),
                (('1.3.6.1.4.1.311.60.2.1.3', 'US'),),
                (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),),
                (('serialNumber', '3359300'),),
                (('streetAddress', '16 Allen Rd'),),
                (('postalCode', '03894-4801'),),
                (('countryName', 'US'),),
                (('stateOrProvinceName', 'NH'),),
                (('localityName', 'Wolfeboro,'),),
                (('organizationName', 'Python Software Foundation'),),
                (('commonName', 'www.python.org'),)),
    'subjectAltName': (('DNS', 'www.python.org'),
                       ('DNS', 'python.org'),
                       ('DNS', 'pypi.org'),
                       ('DNS', 'docs.python.org'),
                       ('DNS', 'testpypi.python.org'),
                       ('DNS', 'bugs.python.org'),
                       ('DNS', 'wiki.python.org'),
                       ('DNS', 'hg.python.org'),
                       ('DNS', 'mail.python.org'),
                       ('DNS', 'packaging.python.org'),
                       ('DNS', 'pythonhosted.org'),
                       ('DNS', 'www.pythonhosted.org'),
                       ('DNS', 'test.pythonhosted.org'),
                       ('DNS', 'us.pycon.org'),
                       ('DNS', 'id.python.org')),
    'version': 3}

Now the SSL channel is established and the certificate verified, you can
proceed to talk with the server::

   >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n")
   >>> pprint.pprint(conn.recv(1024).split(b"\r\n"))
   [b'HTTP/1.1 200 OK',
    b'Date: Sat, 18 Oct 2014 18:27:20 GMT',
    b'Server: nginx',
    b'Content-Type: text/html; charset=utf-8',
    b'X-Frame-Options: SAMEORIGIN',
    b'Content-Length: 45679',
    b'Accept-Ranges: bytes',
    b'Via: 1.1 varnish',
    b'Age: 2188',
    b'X-Served-By: cache-lcy1134-LCY',
    b'X-Cache: HIT',
    b'X-Cache-Hits: 11',
    b'Vary: Cookie',
    b'Strict-Transport-Security: max-age=63072000; includeSubDomains',
    b'Connection: close',
    b'',
    b'']

See the discussion of :ref:`ssl-security` below.


Server-side operation
^^^^^^^^^^^^^^^^^^^^^

For server operation, typically you'll need to have a server certificate, and
private key, each in a file.  You'll first create a context holding the key
and the certificate, so that clients can check your authenticity.  Then
you'll open a socket, bind it to a port, call :meth:`listen` on it, and start
waiting for clients to connect::

   import socket, ssl

   context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
   context.load_cert_chain(certfile="mycertfile", keyfile="mykeyfile")

   bindsocket = socket.socket()
   bindsocket.bind(('myaddr.mydomain.com', 10023))
   bindsocket.listen(5)

When a client connects, you'll call :meth:`accept` on the socket to get the
new socket from the other end, and use the context's :meth:`SSLContext.wrap_socket`
method to create a server-side SSL socket for the connection::

   while True:
       newsocket, fromaddr = bindsocket.accept()
       connstream = context.wrap_socket(newsocket, server_side=True)
       try:
           deal_with_client(connstream)
       finally:
           connstream.shutdown(socket.SHUT_RDWR)
           connstream.close()

Then you'll read data from the ``connstream`` and do something with it till you
are finished with the client (or the client is finished with you)::

   def deal_with_client(connstream):
       data = connstream.read()
       # null data means the client is finished with us
       while data:
           if not do_something(connstream, data):
               # we'll assume do_something returns False
               # when we're finished with client
               break
           data = connstream.read()
       # finished with client

And go back to listening for new client connections (of course, a real server
would probably handle each client connection in a separate thread, or put
the sockets in non-blocking mode and use an event loop).


.. _ssl-nonblocking:

Notes on non-blocking sockets
-----------------------------

When working with non-blocking sockets, there are several things you need
to be aware of:

- Calling :func:`~select.select` tells you that the OS-level socket can be
  read from (or written to), but it does not imply that there is sufficient
  data at the upper SSL layer.  For example, only part of an SSL frame might
  have arrived.  Therefore, you must be ready to handle :meth:`SSLSocket.recv`
  and :meth:`SSLSocket.send` failures, and retry after another call to
  :func:`~select.select`.

- Conversely, since the SSL layer has its own framing, a SSL socket may
  still have data available for reading without :func:`~select.select`
  being aware of it.  Therefore, you should first call
  :meth:`SSLSocket.recv` to drain any potentially available data, and then
  only block on a :func:`~select.select` call if still necessary.

  (of course, similar provisions apply when using other primitives such as
  :func:`~select.poll`, or those in the :mod:`selectors` module)

- The SSL handshake itself will be non-blocking: the
  :meth:`SSLSocket.do_handshake` method has to be retried until it returns
  successfully.  Here is a synopsis using :func:`~select.select` to wait for
  the socket's readiness::

    while True:
        try:
            sock.do_handshake()
            break
        except ssl.SSLWantReadError:
            select.select([sock], [], [])
        except ssl.SSLWantWriteError:
            select.select([], [sock], [])


.. _ssl-security:

Security considerations
-----------------------

Best defaults
^^^^^^^^^^^^^

For **client use**, if you don't have any special requirements for your
security policy, it is highly recommended that you use the
:func:`create_default_context` function to create your SSL context.
It will load the system's trusted CA certificates, enable certificate
validation and hostname checking, and try to choose reasonably secure
protocol and cipher settings.

If a client certificate is needed for the connection, it can be added with
:meth:`SSLContext.load_cert_chain`.

By contrast, if you create the SSL context by calling the :class:`SSLContext`
constructor yourself, it will not have certificate validation nor hostname
checking enabled by default.  If you do so, please read the paragraphs below
to achieve a good security level.

Manual settings
^^^^^^^^^^^^^^^

Verifying certificates
''''''''''''''''''''''

When calling the :class:`SSLContext` constructor directly,
:const:`CERT_NONE` is the default.  Since it does not authenticate the other
peer, it can be insecure, especially in client mode where most of time you
would like to ensure the authenticity of the server you're talking to.
Therefore, when in client mode, it is highly recommended to use
:const:`CERT_REQUIRED`.  However, it is in itself not sufficient; you also
have to check that the server certificate, which can be obtained by calling
:meth:`SSLSocket.getpeercert`, matches the desired service.  For many
protocols and applications, the service can be identified by the hostname;
in this case, the :func:`match_hostname` function can be used.  This common
check is automatically performed when :attr:`SSLContext.check_hostname` is
enabled.

In server mode, if you want to authenticate your clients using the SSL layer
(rather than using a higher-level authentication mechanism), you'll also have
to specify :const:`CERT_REQUIRED` and similarly check the client certificate.

   .. note::

      In client mode, :const:`CERT_OPTIONAL` and :const:`CERT_REQUIRED` are
      equivalent unless anonymous ciphers are enabled (they are disabled
      by default).

Protocol versions
'''''''''''''''''

SSL versions 2 and 3 are considered insecure and are therefore dangerous to
use.  If you want maximum compatibility between clients and servers, it is
recommended to use :const:`PROTOCOL_SSLv23` as the protocol version and then
disable SSLv2 and SSLv3 explicitly using the :data:`SSLContext.options`
attribute::

   context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
   context.options |= ssl.OP_NO_SSLv2
   context.options |= ssl.OP_NO_SSLv3

The SSL context created above will only allow TLSv1 and later (if
supported by your system) connections.

Cipher selection
''''''''''''''''

If you have advanced security requirements, fine-tuning of the ciphers
enabled when negotiating a SSL session is possible through the
:meth:`SSLContext.set_ciphers` method.  Starting from Python 2.7.9, the
ssl module disables certain weak ciphers by default, but you may want
to further restrict the cipher choice. Be sure to read OpenSSL's documentation
about the `cipher list format <https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT>`_.
If you want to check which ciphers are enabled by a given cipher list, use the
``openssl ciphers`` command on your system.

Multi-processing
^^^^^^^^^^^^^^^^

If using this module as part of a multi-processed application (using,
for example the :mod:`multiprocessing` or :mod:`concurrent.futures` modules),
be aware that OpenSSL's internal random number generator does not properly
handle forked processes.  Applications must change the PRNG state of the
parent process if they use any SSL feature with :func:`os.fork`.  Any
successful call of :func:`~ssl.RAND_add`, :func:`~ssl.RAND_bytes` or
:func:`~ssl.RAND_pseudo_bytes` is sufficient.


.. ssl-libressl:

LibreSSL support
----------------

LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for
LibreSSL. Some features are not available when the ssl module is compiled
with LibreSSL.

* LibreSSL >= 2.6.1 no longer supports NPN. The methods
  :meth:`SSLContext.set_npn_protocols` and
  :meth:`SSLSocket.selected_npn_protocol` are not available.
* :meth:`SSLContext.set_default_verify_paths` ignores the env vars
  :envvar:`SSL_CERT_FILE` and :envvar:`SSL_CERT_PATH` although
  :func:`get_default_verify_paths` still reports them.


.. seealso::

   Class :class:`socket.socket`
       Documentation of underlying :mod:`socket` class

   `SSL/TLS Strong Encryption: An Introduction <https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html>`_
       Intro from the Apache webserver documentation

   `RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management <https://www.ietf.org/rfc/rfc1422>`_
       Steve Kent

   `RFC 1750: Randomness Recommendations for Security <https://www.ietf.org/rfc/rfc1750>`_
       D. Eastlake et. al.

   `RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile <https://www.ietf.org/rfc/rfc3280>`_
       Housley et. al.

   `RFC 4366: Transport Layer Security (TLS) Extensions <https://www.ietf.org/rfc/rfc4366>`_
       Blake-Wilson et. al.

   `RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 <https://tools.ietf.org/html/rfc5246>`_
       T. Dierks et. al.

   `RFC 6066: Transport Layer Security (TLS) Extensions <https://tools.ietf.org/html/rfc6066>`_
       D. Eastlake

   `IANA TLS: Transport Layer Security (TLS) Parameters <https://www.iana.org/assignments/tls-parameters/tls-parameters.xml>`_
       IANA

   `RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) <https://tools.ietf.org/html/rfc7525>`_
       IETF

   `Mozilla's Server Side TLS recommendations <https://wiki.mozilla.org/Security/Server_Side_TLS>`_
       Mozilla
PK
%�\���bb"html/_sources/library/stat.rst.txtnu�[���:mod:`stat` --- Interpreting :func:`~os.stat` results
=====================================================

.. module:: stat
   :synopsis: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
.. sectionauthor:: Skip Montanaro <skip@automatrix.com>

**Source code:** :source:`Lib/stat.py`

--------------

The :mod:`stat` module defines constants and functions for interpreting the
results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they
exist).  For complete details about the :c:func:`stat`, :c:func:`fstat` and
:c:func:`lstat` calls, consult the documentation for your system.

The :mod:`stat` module defines the following functions to test for specific file
types:


.. function:: S_ISDIR(mode)

   Return non-zero if the mode is from a directory.


.. function:: S_ISCHR(mode)

   Return non-zero if the mode is from a character special device file.


.. function:: S_ISBLK(mode)

   Return non-zero if the mode is from a block special device file.


.. function:: S_ISREG(mode)

   Return non-zero if the mode is from a regular file.


.. function:: S_ISFIFO(mode)

   Return non-zero if the mode is from a FIFO (named pipe).


.. function:: S_ISLNK(mode)

   Return non-zero if the mode is from a symbolic link.


.. function:: S_ISSOCK(mode)

   Return non-zero if the mode is from a socket.

Two additional functions are defined for more general manipulation of the file's
mode:


.. function:: S_IMODE(mode)

   Return the portion of the file's mode that can be set by :func:`os.chmod`\
   ---that is, the file's permission bits, plus the sticky bit, set-group-id, and
   set-user-id bits (on systems that support them).


.. function:: S_IFMT(mode)

   Return the portion of the file's mode that describes the file type (used by the
   :func:`S_IS\*` functions above).

Normally, you would use the :func:`os.path.is\*` functions for testing the type
of a file; the functions here are useful when you are doing multiple tests of
the same file and wish to avoid the overhead of the :c:func:`stat` system call
for each test.  These are also useful when checking for information about a file
that isn't handled by :mod:`os.path`, like the tests for block and character
devices.

Example::

   import os, sys
   from stat import *

   def walktree(top, callback):
       '''recursively descend the directory tree rooted at top,
          calling the callback function for each regular file'''

       for f in os.listdir(top):
           pathname = os.path.join(top, f)
           mode = os.stat(pathname).st_mode
           if S_ISDIR(mode):
               # It's a directory, recurse into it
               walktree(pathname, callback)
           elif S_ISREG(mode):
               # It's a file, call the callback function
               callback(pathname)
           else:
               # Unknown file type, print a message
               print 'Skipping %s' % pathname

   def visitfile(file):
       print 'visiting', file

   if __name__ == '__main__':
       walktree(sys.argv[1], visitfile)

All the variables below are simply symbolic indexes into the 10-tuple returned
by :func:`os.stat`, :func:`os.fstat` or :func:`os.lstat`.


.. data:: ST_MODE

   Inode protection mode.


.. data:: ST_INO

   Inode number.


.. data:: ST_DEV

   Device inode resides on.


.. data:: ST_NLINK

   Number of links to the inode.


.. data:: ST_UID

   User id of the owner.


.. data:: ST_GID

   Group id of the owner.


.. data:: ST_SIZE

   Size in bytes of a plain file; amount of data waiting on some special files.


.. data:: ST_ATIME

   Time of last access.


.. data:: ST_MTIME

   Time of last modification.


.. data:: ST_CTIME

   The "ctime" as reported by the operating system.  On some systems (like Unix) is
   the time of the last metadata change, and, on others (like Windows), is the
   creation time (see platform documentation for details).

The interpretation of "file size" changes according to the file type.  For plain
files this is the size of the file in bytes.  For FIFOs and sockets under most
flavors of Unix (including Linux in particular), the "size" is the number of
bytes waiting to be read at the time of the call to :func:`os.stat`,
:func:`os.fstat`, or :func:`os.lstat`; this can sometimes be useful, especially
for polling one of these special files after a non-blocking open.  The meaning
of the size field for other character and block devices varies more, depending
on the implementation of the underlying system call.

The variables below define the flags used in the :data:`ST_MODE` field.

Use of the functions above is more portable than use of the first set of flags:

.. data:: S_IFSOCK

   Socket.

.. data:: S_IFLNK

   Symbolic link.

.. data:: S_IFREG

   Regular file.

.. data:: S_IFBLK

   Block device.

.. data:: S_IFDIR

   Directory.

.. data:: S_IFCHR

   Character device.

.. data:: S_IFIFO

   FIFO.

The following flags can also be used in the *mode* argument of :func:`os.chmod`:

.. data:: S_ISUID

   Set UID bit.

.. data:: S_ISGID

   Set-group-ID bit.  This bit has several special uses.  For a directory
   it indicates that BSD semantics is to be used for that directory:
   files created there inherit their group ID from the directory, not
   from the effective group ID of the creating process, and directories
   created there will also get the :data:`S_ISGID` bit set.  For a
   file that does not have the group execution bit (:data:`S_IXGRP`)
   set, the set-group-ID bit indicates mandatory file/record locking
   (see also :data:`S_ENFMT`).

.. data:: S_ISVTX

   Sticky bit.  When this bit is set on a directory it means that a file
   in that directory can be renamed or deleted only by the owner of the
   file, by the owner of the directory, or by a privileged process.

.. data:: S_IRWXU

   Mask for file owner permissions.

.. data:: S_IRUSR

   Owner has read permission.

.. data:: S_IWUSR

   Owner has write permission.

.. data:: S_IXUSR

   Owner has execute permission.

.. data:: S_IRWXG

   Mask for group permissions.

.. data:: S_IRGRP

   Group has read permission.

.. data:: S_IWGRP

   Group has write permission.

.. data:: S_IXGRP

   Group has execute permission.

.. data:: S_IRWXO

   Mask for permissions for others (not in group).

.. data:: S_IROTH

   Others have read permission.

.. data:: S_IWOTH

   Others have write permission.

.. data:: S_IXOTH

   Others have execute permission.

.. data:: S_ENFMT

   System V file locking enforcement.  This flag is shared with :data:`S_ISGID`:
   file/record locking is enforced on files that do not have the group
   execution bit (:data:`S_IXGRP`) set.

.. data:: S_IREAD

   Unix V7 synonym for :data:`S_IRUSR`.

.. data:: S_IWRITE

   Unix V7 synonym for :data:`S_IWUSR`.

.. data:: S_IEXEC

   Unix V7 synonym for :data:`S_IXUSR`.

The following flags can be used in the *flags* argument of :func:`os.chflags`:

.. data:: UF_NODUMP

   Do not dump the file.

.. data:: UF_IMMUTABLE

   The file may not be changed.

.. data:: UF_APPEND

   The file may only be appended to.

.. data:: UF_OPAQUE

   The directory is opaque when viewed through a union stack.

.. data:: UF_NOUNLINK

   The file may not be renamed or deleted.

.. data:: UF_COMPRESSED

   The file is stored compressed (Mac OS X 10.6+).

.. data:: UF_HIDDEN

   The file should not be displayed in a GUI (Mac OS X 10.5+).

.. data:: SF_ARCHIVED

   The file may be archived.

.. data:: SF_IMMUTABLE

   The file may not be changed.

.. data:: SF_APPEND

   The file may only be appended to.

.. data:: SF_NOUNLINK

   The file may not be renamed or deleted.

.. data:: SF_SNAPSHOT

   The file is a snapshot file.

See the \*BSD or Mac OS systems man page :manpage:`chflags(2)` for more information.

PK
%�\�X.�%html/_sources/library/statvfs.rst.txtnu�[���:mod:`statvfs` --- Constants used with :func:`os.statvfs`
=========================================================

.. module:: statvfs
   :synopsis: Constants for interpreting the result of os.statvfs().
   :deprecated:

.. deprecated:: 2.6
   The :mod:`statvfs` module has been removed in Python 3.


.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`statvfs` module defines constants so interpreting the result if
:func:`os.statvfs`, which returns a tuple, can be made without remembering
"magic numbers."  Each of the constants defined in this module is the *index* of
the entry in the tuple returned by :func:`os.statvfs` that contains the
specified information.


.. data:: F_BSIZE

   Preferred file system block size.


.. data:: F_FRSIZE

   Fundamental file system block size.


.. data:: F_BLOCKS

   Total number of blocks in the filesystem.


.. data:: F_BFREE

   Total number of free blocks.


.. data:: F_BAVAIL

   Free blocks available to non-super user.


.. data:: F_FILES

   Total number of file nodes.


.. data:: F_FFREE

   Total number of free file nodes.


.. data:: F_FAVAIL

   Free nodes available to non-super user.


.. data:: F_FLAG

   Flags. System dependent: see :c:func:`statvfs` man page.


.. data:: F_NAMEMAX

   Maximum file name length.

PK
%�\��#�,�,�&html/_sources/library/stdtypes.rst.txtnu�[���.. XXX: reference/datamodel and this have quite a few overlaps!


.. _bltin-types:

**************
Built-in Types
**************

The following sections describe the standard types that are built into the
interpreter.

.. note::

   Historically (until release 2.2), Python's built-in types have differed from
   user-defined types because it was not possible to use the built-in types as the
   basis for object-oriented inheritance. This limitation no longer
   exists.

.. index:: pair: built-in; types

The principal built-in types are numerics, sequences, mappings, files, classes,
instances and exceptions.

.. index:: statement: print

Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted
to a string (with the :ref:`repr() <func-repr>` function or the slightly different
:func:`str` function).  The latter function is implicitly used when an object is
written by the :func:`print` function.


.. _truth:

Truth Value Testing
===================

.. index::
   statement: if
   statement: while
   pair: truth; value
   pair: Boolean; operations
   single: false

Any object can be tested for truth value, for use in an :keyword:`if` or
:keyword:`while` condition or as operand of the Boolean operations below. The
following values are considered false:

  .. index:: single: None (Built-in object)

* ``None``

  .. index:: single: False (Built-in object)

* ``False``

* zero of any numeric type, for example, ``0``, ``0L``, ``0.0``, ``0j``.

* any empty sequence, for example, ``''``, ``()``, ``[]``.

* any empty mapping, for example, ``{}``.

* instances of user-defined classes, if the class defines a :meth:`__nonzero__`
  or :meth:`__len__` method, when that method returns the integer zero or
  :class:`bool` value ``False``. [1]_

.. index:: single: true

All other values are considered true --- so objects of many types are always
true.

.. index::
   operator: or
   operator: and
   single: False
   single: True

Operations and built-in functions that have a Boolean result always return ``0``
or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
(Important exception: the Boolean operations ``or`` and ``and`` always return
one of their operands.)


.. _boolean:

Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
====================================================================

.. index:: pair: Boolean; operations

These are the Boolean operations, ordered by ascending priority:

+-------------+---------------------------------+-------+
| Operation   | Result                          | Notes |
+=============+=================================+=======+
| ``x or y``  | if *x* is false, then *y*, else | \(1)  |
|             | *x*                             |       |
+-------------+---------------------------------+-------+
| ``x and y`` | if *x* is false, then *x*, else | \(2)  |
|             | *y*                             |       |
+-------------+---------------------------------+-------+
| ``not x``   | if *x* is false, then ``True``, | \(3)  |
|             | else ``False``                  |       |
+-------------+---------------------------------+-------+

.. index::
   operator: and
   operator: or
   operator: not

Notes:

(1)
   This is a short-circuit operator, so it only evaluates the second
   argument if the first one is false.

(2)
   This is a short-circuit operator, so it only evaluates the second
   argument if the first one is true.

(3)
   ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
   interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.


.. _stdcomparisons:

Comparisons
===========

.. index::
   pair: chaining; comparisons
   pair: operator; comparison
   operator: ==
   operator: <
   operator: <=
   operator: >
   operator: >=
   operator: !=
   operator: is
   operator: is not

Comparison operations are supported by all objects.  They all have the same
priority (which is higher than that of the Boolean operations). Comparisons can
be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
evaluated at all when ``x < y`` is found to be false).

This table summarizes the comparison operations:

+------------+-------------------------+-------+
| Operation  | Meaning                 | Notes |
+============+=========================+=======+
| ``<``      | strictly less than      |       |
+------------+-------------------------+-------+
| ``<=``     | less than or equal      |       |
+------------+-------------------------+-------+
| ``>``      | strictly greater than   |       |
+------------+-------------------------+-------+
| ``>=``     | greater than or equal   |       |
+------------+-------------------------+-------+
| ``==``     | equal                   |       |
+------------+-------------------------+-------+
| ``!=``     | not equal               | \(1)  |
+------------+-------------------------+-------+
| ``is``     | object identity         |       |
+------------+-------------------------+-------+
| ``is not`` | negated object identity |       |
+------------+-------------------------+-------+

Notes:

(1)
    ``!=`` can also be written ``<>``, but this is an obsolete usage
    kept for backwards compatibility only. New code should always use
    ``!=``.

.. index::
   pair: object; numeric
   pair: objects; comparing

Objects of different types, except different numeric types and different string
types, never compare equal; such objects are ordered consistently but
arbitrarily (so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (for example, file objects) support only a degenerate
notion of comparison where any two objects of that type are unequal.  Again,
such objects are ordered arbitrarily but consistently. The ``<``, ``<=``, ``>``
and ``>=`` operators will raise a :exc:`TypeError` exception when any operand is
a complex number.

.. index::
   single: __cmp__() (instance method)
   single: __eq__() (instance method)
   single: __ne__() (instance method)
   single: __lt__() (instance method)
   single: __le__() (instance method)
   single: __gt__() (instance method)
   single: __ge__() (instance method)

Non-identical instances of a class normally compare as non-equal unless the
class defines the :meth:`__eq__` method or the :meth:`__cmp__` method.

Instances of a class cannot be ordered with respect to other instances of the
same class, or other types of object, unless the class defines either enough of
the rich comparison methods (:meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and
:meth:`__ge__`) or the :meth:`__cmp__` method.

.. impl-detail::

   Objects of different types except numbers are ordered by their type names;
   objects of the same types that don't support proper comparison are ordered by
   their address.

.. index::
   operator: in
   operator: not in

Two more operations with the same syntactic priority, ``in`` and ``not in``, are
supported only by sequence types (below).


.. _typesnumeric:

Numeric Types --- :class:`int`, :class:`float`, :class:`long`, :class:`complex`
===============================================================================

.. index::
   object: numeric
   object: Boolean
   object: integer
   object: long integer
   object: floating point
   object: complex number
   pair: C; language

There are four distinct numeric types: :dfn:`plain integers`, :dfn:`long
integers`, :dfn:`floating point numbers`, and :dfn:`complex numbers`. In
addition, Booleans are a subtype of plain integers. Plain integers (also just
called :dfn:`integers`) are implemented using :c:type:`long` in C, which gives
them at least 32 bits of precision (``sys.maxint`` is always set to the maximum
plain integer value for the current platform, the minimum value is
``-sys.maxint - 1``).  Long integers have unlimited precision.  Floating point
numbers are usually implemented using :c:type:`double` in C; information about
the precision and internal representation of floating point numbers for the
machine on which your program is running is available in
:data:`sys.float_info`.  Complex numbers have a real and imaginary part, which
are each a floating point number.  To extract these parts from a complex number
*z*, use ``z.real`` and ``z.imag``. (The standard library includes additional
numeric types, :mod:`fractions` that hold rationals, and :mod:`decimal` that
hold floating-point numbers with user-definable precision.)

.. index::
   pair: numeric; literals
   pair: integer; literals
   triple: long; integer; literals
   pair: floating point; literals
   pair: complex number; literals
   pair: hexadecimal; literals
   pair: octal; literals

Numbers are created by numeric literals or as the result of built-in functions
and operators.  Unadorned integer literals (including binary, hex, and octal
numbers) yield plain integers unless the value they denote is too large to be
represented as a plain integer, in which case they yield a long integer.
Integer literals with an ``'L'`` or ``'l'`` suffix yield long integers (``'L'``
is preferred because ``1l`` looks too much like eleven!).  Numeric literals
containing a decimal point or an exponent sign yield floating point numbers.
Appending ``'j'`` or ``'J'`` to a numeric literal yields an imaginary number
(a complex number with a zero real part) which you can add to an integer or
float to get a complex number with real and imaginary parts.

.. index::
   single: arithmetic
   builtin: int
   builtin: long
   builtin: float
   builtin: complex
   operator: +
   operator: -
   operator: *
   operator: /
   operator: //
   operator: %
   operator: **

Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the "narrower" type is
widened to that of the other, where plain integer is narrower than long integer
is narrower than floating point is narrower than complex. Comparisons between
numbers of mixed type use the same rule. [2]_ The constructors :func:`int`,
:func:`long`, :func:`float`, and :func:`complex` can be used to produce numbers
of a specific type.

All built-in numeric types support the following operations. See
:ref:`power` and later sections for the operators' priorities.

+--------------------+---------------------------------+--------+
| Operation          | Result                          | Notes  |
+====================+=================================+========+
| ``x + y``          | sum of *x* and *y*              |        |
+--------------------+---------------------------------+--------+
| ``x - y``          | difference of *x* and *y*       |        |
+--------------------+---------------------------------+--------+
| ``x * y``          | product of *x* and *y*          |        |
+--------------------+---------------------------------+--------+
| ``x / y``          | quotient of *x* and *y*         | \(1)   |
+--------------------+---------------------------------+--------+
| ``x // y``         | (floored) quotient of *x* and   | (4)(5) |
|                    | *y*                             |        |
+--------------------+---------------------------------+--------+
| ``x % y``          | remainder of ``x / y``          | \(4)   |
+--------------------+---------------------------------+--------+
| ``-x``             | *x* negated                     |        |
+--------------------+---------------------------------+--------+
| ``+x``             | *x* unchanged                   |        |
+--------------------+---------------------------------+--------+
| ``abs(x)``         | absolute value or magnitude of  | \(3)   |
|                    | *x*                             |        |
+--------------------+---------------------------------+--------+
| ``int(x)``         | *x* converted to integer        | \(2)   |
+--------------------+---------------------------------+--------+
| ``long(x)``        | *x* converted to long integer   | \(2)   |
+--------------------+---------------------------------+--------+
| ``float(x)``       | *x* converted to floating point | \(6)   |
+--------------------+---------------------------------+--------+
| ``complex(re,im)`` | a complex number with real part |        |
|                    | *re*, imaginary part *im*.      |        |
|                    | *im* defaults to zero.          |        |
+--------------------+---------------------------------+--------+
| ``c.conjugate()``  | conjugate of the complex number |        |
|                    | *c*. (Identity on real numbers) |        |
+--------------------+---------------------------------+--------+
| ``divmod(x, y)``   | the pair ``(x // y, x % y)``    | (3)(4) |
+--------------------+---------------------------------+--------+
| ``pow(x, y)``      | *x* to the power *y*            | (3)(7) |
+--------------------+---------------------------------+--------+
| ``x ** y``         | *x* to the power *y*            | \(7)   |
+--------------------+---------------------------------+--------+

.. index::
   triple: operations on; numeric; types
   single: conjugate() (complex number method)

Notes:

(1)
   .. index::
      pair: integer; division
      triple: long; integer; division

   For (plain or long) integer division, the result is an integer. The result is
   always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
   (-1)/(-2) is 0.  Note that the result is a long integer if either operand is a
   long integer, regardless of the numeric value.

(2)
   .. index::
      module: math
      single: floor() (in module math)
      single: ceil() (in module math)
      single: trunc() (in module math)
      pair: numeric; conversions

   Conversion from floats using :func:`int` or :func:`long` truncates toward
   zero like the related function, :func:`math.trunc`.  Use the function
   :func:`math.floor` to round downward and :func:`math.ceil` to round
   upward.

(3)
   See :ref:`built-in-funcs` for a full description.

(4)
   .. deprecated:: 2.3
      The floor division operator, the modulo operator, and the :func:`divmod`
      function are no longer defined for complex numbers.  Instead, convert to
      a floating point number using the :func:`abs` function if appropriate.

(5)
   Also referred to as integer division.  The resultant value is a whole integer,
   though the result's type is not necessarily int.

(6)
   float also accepts the strings "nan" and "inf" with an optional prefix "+"
   or "-" for Not a Number (NaN) and positive or negative infinity.

   .. versionadded:: 2.6

(7)
   Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
   programming languages.

All :class:`numbers.Real` types (:class:`int`, :class:`long`, and
:class:`float`) also include the following operations:

+--------------------+---------------------------------------------+
| Operation          | Result                                      |
+====================+=============================================+
| :func:`math.trunc(\| *x* truncated to :class:`~numbers.Integral` |
| x) <math.trunc>`   |                                             |
+--------------------+---------------------------------------------+
| :func:`round(x[,   | *x* rounded to *n* digits,                  |
| n]) <round>`       | rounding ties away from zero. If *n*        |
|                    | is omitted, it defaults to 0.               |
+--------------------+---------------------------------------------+
| :func:`math.floor(\| the greatest integer as a float <= *x*      |
| x) <math.floor>`   |                                             |
+--------------------+---------------------------------------------+
| :func:`math.ceil(x)| the least integer as a float >= *x*         |
| <math.ceil>`       |                                             |
+--------------------+---------------------------------------------+

.. XXXJH exceptions: overflow (when? what operations?) zerodivision


.. _bitstring-ops:

Bitwise Operations on Integer Types
--------------------------------------

.. index::
   triple: operations on; integer; types
   pair: bitwise; operations
   pair: shifting; operations
   pair: masking; operations
   operator: |
   operator: ^
   operator: &
   operator: <<
   operator: >>
   operator: ~

Bitwise operations only make sense for integers.  Negative numbers are treated
as their 2's complement value (this assumes a sufficiently large number of bits
that no overflow occurs during the operation).

The priorities of the binary bitwise operations are all lower than the numeric
operations and higher than the comparisons; the unary operation ``~`` has the
same priority as the other unary numeric operations (``+`` and ``-``).

This table lists the bitwise operations sorted in ascending priority:

+------------+--------------------------------+----------+
| Operation  | Result                         | Notes    |
+============+================================+==========+
| ``x | y``  | bitwise :dfn:`or` of *x* and   |          |
|            | *y*                            |          |
+------------+--------------------------------+----------+
| ``x ^ y``  | bitwise :dfn:`exclusive or` of |          |
|            | *x* and *y*                    |          |
+------------+--------------------------------+----------+
| ``x & y``  | bitwise :dfn:`and` of *x* and  |          |
|            | *y*                            |          |
+------------+--------------------------------+----------+
| ``x << n`` | *x* shifted left by *n* bits   | (1)(2)   |
+------------+--------------------------------+----------+
| ``x >> n`` | *x* shifted right by *n* bits  | (1)(3)   |
+------------+--------------------------------+----------+
| ``~x``     | the bits of *x* inverted       |          |
+------------+--------------------------------+----------+

Notes:

(1)
   Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.

(2)
   A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``.  A
   long integer is returned if the result exceeds the range of plain integers.

(3)
   A right shift by *n* bits is equivalent to division by ``pow(2, n)``.


Additional Methods on Integer Types
-----------------------------------

The integer types implement the :class:`numbers.Integral` :term:`abstract base
class`. In addition, they provide one more method:

.. method:: int.bit_length()
.. method:: long.bit_length()

    Return the number of bits necessary to represent an integer in binary,
    excluding the sign and leading zeros::

        >>> n = -37
        >>> bin(n)
        '-0b100101'
        >>> n.bit_length()
        6

    More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
    unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
    Equivalently, when ``abs(x)`` is small enough to have a correctly
    rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
    If ``x`` is zero, then ``x.bit_length()`` returns ``0``.

    Equivalent to::

        def bit_length(self):
            s = bin(self)       # binary representation:  bin(-37) --> '-0b100101'
            s = s.lstrip('-0b') # remove leading zeros and minus sign
            return len(s)       # len('100101') --> 6

    .. versionadded:: 2.7


Additional Methods on Float
---------------------------

The float type implements the :class:`numbers.Real` :term:`abstract base
class`. float also has the following additional methods.

.. method:: float.as_integer_ratio()

   Return a pair of integers whose ratio is exactly equal to the
   original float and with a positive denominator.  Raises
   :exc:`OverflowError` on infinities and a :exc:`ValueError` on
   NaNs.

   .. versionadded:: 2.6

.. method:: float.is_integer()

   Return ``True`` if the float instance is finite with integral
   value, and ``False`` otherwise::

      >>> (-2.0).is_integer()
      True
      >>> (3.2).is_integer()
      False

   .. versionadded:: 2.6

Two methods support conversion to
and from hexadecimal strings.  Since Python's floats are stored
internally as binary numbers, converting a float to or from a
*decimal* string usually involves a small rounding error.  In
contrast, hexadecimal strings allow exact representation and
specification of floating-point numbers.  This can be useful when
debugging, and in numerical work.


.. method:: float.hex()

   Return a representation of a floating-point number as a hexadecimal
   string.  For finite floating-point numbers, this representation
   will always include a leading ``0x`` and a trailing ``p`` and
   exponent.

   .. versionadded:: 2.6


.. method:: float.fromhex(s)

   Class method to return the float represented by a hexadecimal
   string *s*.  The string *s* may have leading and trailing
   whitespace.

   .. versionadded:: 2.6


Note that :meth:`float.hex` is an instance method, while
:meth:`float.fromhex` is a class method.

A hexadecimal string takes the form::

   [sign] ['0x'] integer ['.' fraction] ['p' exponent]

where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
and ``fraction`` are strings of hexadecimal digits, and ``exponent``
is a decimal integer with an optional leading sign.  Case is not
significant, and there must be at least one hexadecimal digit in
either the integer or the fraction.  This syntax is similar to the
syntax specified in section 6.4.4.2 of the C99 standard, and also to
the syntax used in Java 1.5 onwards.  In particular, the output of
:meth:`float.hex` is usable as a hexadecimal floating-point literal in
C or Java code, and hexadecimal strings produced by C's ``%a`` format
character or Java's ``Double.toHexString`` are accepted by
:meth:`float.fromhex`.


Note that the exponent is written in decimal rather than hexadecimal,
and that it gives the power of 2 by which to multiply the coefficient.
For example, the hexadecimal string ``0x3.a7p10`` represents the
floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
``3740.0``::

   >>> float.fromhex('0x3.a7p10')
   3740.0


Applying the reverse conversion to ``3740.0`` gives a different
hexadecimal string representing the same number::

   >>> float.hex(3740.0)
   '0x1.d380000000000p+11'


.. _typeiter:

Iterator Types
==============

.. versionadded:: 2.2

.. index::
   single: iterator protocol
   single: protocol; iterator
   single: sequence; iteration
   single: container; iteration over

Python supports a concept of iteration over containers.  This is implemented
using two distinct methods; these are used to allow user-defined classes to
support iteration.  Sequences, described below in more detail, always support
the iteration methods.

One method needs to be defined for container objects to provide iteration
support:

.. XXX duplicated in reference/datamodel!

.. method:: container.__iter__()

   Return an iterator object.  The object is required to support the iterator
   protocol described below.  If a container supports different types of
   iteration, additional methods can be provided to specifically request
   iterators for those iteration types.  (An example of an object supporting
   multiple forms of iteration would be a tree structure which supports both
   breadth-first and depth-first traversal.)  This method corresponds to the
   :c:member:`~PyTypeObject.tp_iter` slot of the type structure for Python objects in the Python/C
   API.

The iterator objects themselves are required to support the following two
methods, which together form the :dfn:`iterator protocol`:


.. method:: iterator.__iter__()

   Return the iterator object itself.  This is required to allow both containers
   and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
   This method corresponds to the :c:member:`~PyTypeObject.tp_iter` slot of the type structure for
   Python objects in the Python/C API.


.. method:: iterator.next()

   Return the next item from the container.  If there are no further items, raise
   the :exc:`StopIteration` exception.  This method corresponds to the
   :c:member:`~PyTypeObject.tp_iternext` slot of the type structure for Python objects in the
   Python/C API.

Python defines several iterator objects to support iteration over general and
specific sequence types, dictionaries, and other more specialized forms.  The
specific types are not important beyond their implementation of the iterator
protocol.

The intention of the protocol is that once an iterator's :meth:`~iterator.next` method
raises :exc:`StopIteration`, it will continue to do so on subsequent calls.
Implementations that do not obey this property are deemed broken.  (This
constraint was added in Python 2.3; in Python 2.2, various iterators are broken
according to this rule.)


.. _generator-types:

Generator Types
---------------

Python's :term:`generator`\s provide a convenient way to implement the iterator
protocol.  If a container object's :meth:`__iter__` method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the :meth:`~iterator.__iter__` and
:meth:`~iterator.next` methods.  More information about generators can be found
in :ref:`the documentation for the yield expression <yieldexpr>`.


.. _typesseq:

Sequence Types --- :class:`str`, :class:`unicode`, :class:`list`, :class:`tuple`, :class:`bytearray`, :class:`buffer`, :class:`xrange`
======================================================================================================================================

There are seven sequence types: strings, Unicode strings, lists, tuples,
bytearrays, buffers, and xrange objects.

For other containers see the built in :class:`dict` and :class:`set` classes,
and the :mod:`collections` module.


.. index::
   object: sequence
   object: string
   object: Unicode
   object: tuple
   object: list
   object: bytearray
   object: buffer
   object: xrange

String literals are written in single or double quotes: ``'xyzzy'``,
``"frobozz"``.  See :ref:`strings` for more about string literals.
Unicode strings are much like strings, but are specified in the syntax
using a preceding ``'u'`` character: ``u'abc'``, ``u"def"``. In addition
to the functionality described here, there are also string-specific
methods described in the :ref:`string-methods` section. Lists are
constructed with square brackets, separating items with commas: ``[a, b, c]``.
Tuples are constructed by the comma operator (not within square
brackets), with or without enclosing parentheses, but an empty tuple
must have the enclosing parentheses, such as ``a, b, c`` or ``()``.  A
single item tuple must have a trailing comma, such as ``(d,)``.

Bytearray objects are created with the built-in function :func:`bytearray`.

Buffer objects are not directly supported by Python syntax, but can be created
by calling the built-in function :func:`buffer`.  They don't support
concatenation or repetition.

Objects of type xrange are similar to buffers in that there is no specific syntax to
create them, but they are created using the :func:`xrange` function.  They don't
support slicing, concatenation or repetition, and using ``in``, ``not in``,
:func:`min` or :func:`max` on them is inefficient.

Most sequence types support the following operations.  The ``in`` and ``not in``
operations have the same priorities as the comparison operations.  The ``+`` and
``*`` operations have the same priority as the corresponding numeric operations.
[3]_ Additional methods are provided for :ref:`typesseq-mutable`.

This table lists the sequence operations sorted in ascending priority.
In the table, *s* and *t* are sequences of the same type; *n*, *i* and *j* are integers:

+------------------+--------------------------------+----------+
| Operation        | Result                         | Notes    |
+==================+================================+==========+
| ``x in s``       | ``True`` if an item of *s* is  | \(1)     |
|                  | equal to *x*, else ``False``   |          |
+------------------+--------------------------------+----------+
| ``x not in s``   | ``False`` if an item of *s* is | \(1)     |
|                  | equal to *x*, else ``True``    |          |
+------------------+--------------------------------+----------+
| ``s + t``        | the concatenation of *s* and   | \(6)     |
|                  | *t*                            |          |
+------------------+--------------------------------+----------+
| ``s * n, n * s`` | equivalent to adding *s* to    | \(2)     |
|                  | itself *n* times               |          |
+------------------+--------------------------------+----------+
| ``s[i]``         | *i*\ th item of *s*, origin 0  | \(3)     |
+------------------+--------------------------------+----------+
| ``s[i:j]``       | slice of *s* from *i* to *j*   | (3)(4)   |
+------------------+--------------------------------+----------+
| ``s[i:j:k]``     | slice of *s* from *i* to *j*   | (3)(5)   |
|                  | with step *k*                  |          |
+------------------+--------------------------------+----------+
| ``len(s)``       | length of *s*                  |          |
+------------------+--------------------------------+----------+
| ``min(s)``       | smallest item of *s*           |          |
+------------------+--------------------------------+----------+
| ``max(s)``       | largest item of *s*            |          |
+------------------+--------------------------------+----------+
| ``s.index(x)``   | index of the first occurrence  |          |
|                  | of *x* in *s*                  |          |
+------------------+--------------------------------+----------+
| ``s.count(x)``   | total number of occurrences of |          |
|                  | *x* in *s*                     |          |
+------------------+--------------------------------+----------+

Sequence types also support comparisons. In particular, tuples and lists
are compared lexicographically by comparing corresponding
elements. This means that to compare equal, every element must compare
equal and the two sequences must be of the same type and have the same
length. (For full details see :ref:`comparisons` in the language
reference.)

.. index::
   triple: operations on; sequence; types
   builtin: len
   builtin: min
   builtin: max
   pair: concatenation; operation
   pair: repetition; operation
   pair: subscript; operation
   pair: slice; operation
   pair: extended slice; operation
   operator: in
   operator: not in

Notes:

(1)
   When *s* is a string or Unicode string object the ``in`` and ``not in``
   operations act like a substring test.  In Python versions before 2.3, *x* had to
   be a string of length 1. In Python 2.3 and beyond, *x* may be a string of any
   length.

(2)
   Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
   sequence of the same type as *s*).  Note that items in the sequence *s*
   are not copied; they are referenced multiple times.  This often haunts
   new Python programmers; consider:

      >>> lists = [[]] * 3
      >>> lists
      [[], [], []]
      >>> lists[0].append(3)
      >>> lists
      [[3], [3], [3]]

   What has happened is that ``[[]]`` is a one-element list containing an empty
   list, so all three elements of ``[[]] * 3`` are references to this single empty
   list.  Modifying any of the elements of ``lists`` modifies this single list.
   You can create a list of different lists this way:

      >>> lists = [[] for i in range(3)]
      >>> lists[0].append(3)
      >>> lists[1].append(5)
      >>> lists[2].append(7)
      >>> lists
      [[3], [5], [7]]

   Further explanation is available in the FAQ entry
   :ref:`faq-multidimensional-list`.

(3)
   If *i* or *j* is negative, the index is relative to the end of sequence *s*:
   ``len(s) + i`` or ``len(s) + j`` is substituted.  But note that ``-0`` is still
   ``0``.

(4)
   The slice of *s* from *i* to *j* is defined as the sequence of items with index
   *k* such that ``i <= k < j``.  If *i* or *j* is greater than ``len(s)``, use
   ``len(s)``.  If *i* is omitted or ``None``, use ``0``.  If *j* is omitted or
   ``None``, use ``len(s)``.  If *i* is greater than or equal to *j*, the slice is
   empty.

(5)
   The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
   items with index  ``x = i + n*k`` such that ``0 <= n < (j-i)/k``.  In other words,
   the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
   *j* is reached (but never including *j*).  When *k* is positive,
   *i* and *j* are reduced to ``len(s)`` if they are greater.
   When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if
   they are greater.  If *i* or *j* are omitted or ``None``, they become
   "end" values (which end depends on the sign of *k*).  Note, *k* cannot be zero.
   If *k* is ``None``, it is treated like ``1``.

(6)
   .. impl-detail::

      If *s* and *t* are both strings, some Python implementations such as
      CPython can usually perform an in-place optimization for assignments of
      the form ``s = s + t`` or ``s += t``.  When applicable, this optimization
      makes quadratic run-time much less likely.  This optimization is both
      version and implementation dependent.  For performance sensitive code, it
      is preferable to use the :meth:`str.join` method which assures consistent
      linear concatenation performance across versions and implementations.

   .. versionchanged:: 2.4
      Formerly, string concatenation never occurred in-place.


.. _string-methods:

String Methods
--------------

.. index:: pair: string; methods

Below are listed the string methods which both 8-bit strings and
Unicode objects support.  Some of them are also available on :class:`bytearray`
objects.

In addition, Python's strings support the sequence type methods
described in the :ref:`typesseq` section. To output formatted strings
use template strings or the ``%`` operator described in the
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.

.. method:: str.capitalize()

   Return a copy of the string with its first character capitalized and the
   rest lowercased.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.center(width[, fillchar])

   Return centered in a string of length *width*. Padding is done using the
   specified *fillchar* (default is a space).

   .. versionchanged:: 2.4
      Support for the *fillchar* argument.


.. method:: str.count(sub[, start[, end]])

   Return the number of non-overlapping occurrences of substring *sub* in the
   range [*start*, *end*].  Optional arguments *start* and *end* are
   interpreted as in slice notation.


.. method:: str.decode([encoding[, errors]])

   Decodes the string using the codec registered for *encoding*. *encoding*
   defaults to the default string encoding.  *errors* may be given to set a
   different error handling scheme.  The default is ``'strict'``, meaning that
   encoding errors raise :exc:`UnicodeError`.  Other possible values are
   ``'ignore'``, ``'replace'`` and any other name registered via
   :func:`codecs.register_error`, see section :ref:`codec-base-classes`.

   .. versionadded:: 2.2

   .. versionchanged:: 2.3
      Support for other error handling schemes added.

   .. versionchanged:: 2.7
      Support for keyword arguments added.

.. method:: str.encode([encoding[,errors]])

   Return an encoded version of the string.  Default encoding is the current
   default string encoding.  *errors* may be given to set a different error
   handling scheme.  The default for *errors* is ``'strict'``, meaning that
   encoding errors raise a :exc:`UnicodeError`.  Other possible values are
   ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and
   any other name registered via :func:`codecs.register_error`, see section
   :ref:`codec-base-classes`. For a list of possible encodings, see section
   :ref:`standard-encodings`.

   .. versionadded:: 2.0

   .. versionchanged:: 2.3
      Support for ``'xmlcharrefreplace'`` and ``'backslashreplace'`` and other error
      handling schemes added.

   .. versionchanged:: 2.7
      Support for keyword arguments added.

.. method:: str.endswith(suffix[, start[, end]])

   Return ``True`` if the string ends with the specified *suffix*, otherwise return
   ``False``.  *suffix* can also be a tuple of suffixes to look for.  With optional
   *start*, test beginning at that position.  With optional *end*, stop comparing
   at that position.

   .. versionchanged:: 2.5
      Accept tuples as *suffix*.


.. method:: str.expandtabs([tabsize])

   Return a copy of the string where all tab characters are replaced by one or
   more spaces, depending on the current column and the given tab size.  Tab
   positions occur every *tabsize* characters (default is 8, giving tab
   positions at columns 0, 8, 16 and so on).  To expand the string, the current
   column is set to zero and the string is examined character by character.  If
   the character is a tab (``\t``), one or more space characters are inserted
   in the result until the current column is equal to the next tab position.
   (The tab character itself is not copied.)  If the character is a newline
   (``\n``) or return (``\r``), it is copied and the current column is reset to
   zero.  Any other character is copied unchanged and the current column is
   incremented by one regardless of how the character is represented when
   printed.

      >>> '01\t012\t0123\t01234'.expandtabs()
      '01      012     0123    01234'
      >>> '01\t012\t0123\t01234'.expandtabs(4)
      '01  012 0123    01234'


.. method:: str.find(sub[, start[, end]])

   Return the lowest index in the string where substring *sub* is found within
   the slice ``s[start:end]``.  Optional arguments *start* and *end* are
   interpreted as in slice notation.  Return ``-1`` if *sub* is not found.

   .. note::

      The :meth:`~str.find` method should be used only if you need to know the
      position of *sub*.  To check if *sub* is a substring or not, use the
      :keyword:`in` operator::

         >>> 'Py' in 'Python'
         True


.. method:: str.format(*args, **kwargs)

   Perform a string formatting operation.  The string on which this method is
   called can contain literal text or replacement fields delimited by braces
   ``{}``.  Each replacement field contains either the numeric index of a
   positional argument, or the name of a keyword argument.  Returns a copy of
   the string where each replacement field is replaced with the string value of
   the corresponding argument.

      >>> "The sum of 1 + 2 is {0}".format(1+2)
      'The sum of 1 + 2 is 3'

   See :ref:`formatstrings` for a description of the various formatting options
   that can be specified in format strings.

   This method of string formatting is the new standard in Python 3, and
   should be preferred to the ``%`` formatting described in
   :ref:`string-formatting` in new code.

   .. versionadded:: 2.6


.. method:: str.index(sub[, start[, end]])

   Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.


.. method:: str.isalnum()

   Return true if all characters in the string are alphanumeric and there is at
   least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.isalpha()

   Return true if all characters in the string are alphabetic and there is at least
   one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.isdigit()

   Return true if all characters in the string are digits and there is at least one
   character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.islower()

   Return true if all cased characters [4]_ in the string are lowercase and there is at
   least one cased character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.isspace()

   Return true if there are only whitespace characters in the string and there is
   at least one character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.istitle()

   Return true if the string is a titlecased string and there is at least one
   character, for example uppercase characters may only follow uncased characters
   and lowercase characters only cased ones.  Return false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.isupper()

   Return true if all cased characters [4]_ in the string are uppercase and there is at
   least one cased character, false otherwise.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.join(iterable)

   Return a string which is the concatenation of the strings in *iterable*.
   If there is any Unicode object in *iterable*, return a Unicode instead.
   A :exc:`TypeError` will be raised if there are any non-string or non Unicode
   object values in *iterable*.  The separator between elements is the string
   providing this method.


.. method:: str.ljust(width[, fillchar])

   Return the string left justified in a string of length *width*. Padding is done
   using the specified *fillchar* (default is a space).  The original string is
   returned if *width* is less than or equal to ``len(s)``.

   .. versionchanged:: 2.4
      Support for the *fillchar* argument.


.. method:: str.lower()

   Return a copy of the string with all the cased characters [4]_ converted to
   lowercase.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.lstrip([chars])

   Return a copy of the string with leading characters removed.  The *chars*
   argument is a string specifying the set of characters to be removed.  If omitted
   or ``None``, the *chars* argument defaults to removing whitespace.  The *chars*
   argument is not a prefix; rather, all combinations of its values are stripped:

      >>> '   spacious   '.lstrip()
      'spacious   '
      >>> 'www.example.com'.lstrip('cmowz.')
      'example.com'

   .. versionchanged:: 2.2.2
      Support for the *chars* argument.


.. method:: str.partition(sep)

   Split the string at the first occurrence of *sep*, and return a 3-tuple
   containing the part before the separator, the separator itself, and the part
   after the separator.  If the separator is not found, return a 3-tuple containing
   the string itself, followed by two empty strings.

   .. versionadded:: 2.5


.. method:: str.replace(old, new[, count])

   Return a copy of the string with all occurrences of substring *old* replaced by
   *new*.  If the optional argument *count* is given, only the first *count*
   occurrences are replaced.


.. method:: str.rfind(sub [,start [,end]])

   Return the highest index in the string where substring *sub* is found, such
   that *sub* is contained within ``s[start:end]``.  Optional arguments *start*
   and *end* are interpreted as in slice notation.  Return ``-1`` on failure.


.. method:: str.rindex(sub[, start[, end]])

   Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
   found.


.. method:: str.rjust(width[, fillchar])

   Return the string right justified in a string of length *width*. Padding is done
   using the specified *fillchar* (default is a space). The original string is
   returned if *width* is less than or equal to ``len(s)``.

   .. versionchanged:: 2.4
      Support for the *fillchar* argument.


.. method:: str.rpartition(sep)

   Split the string at the last occurrence of *sep*, and return a 3-tuple
   containing the part before the separator, the separator itself, and the part
   after the separator.  If the separator is not found, return a 3-tuple containing
   two empty strings, followed by the string itself.

   .. versionadded:: 2.5


.. method:: str.rsplit([sep [,maxsplit]])

   Return a list of the words in the string, using *sep* as the delimiter string.
   If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
   ones.  If *sep* is not specified or ``None``, any whitespace string is a
   separator.  Except for splitting from the right, :meth:`rsplit` behaves like
   :meth:`split` which is described in detail below.

   .. versionadded:: 2.4


.. method:: str.rstrip([chars])

   Return a copy of the string with trailing characters removed.  The *chars*
   argument is a string specifying the set of characters to be removed.  If omitted
   or ``None``, the *chars* argument defaults to removing whitespace.  The *chars*
   argument is not a suffix; rather, all combinations of its values are stripped:

      >>> '   spacious   '.rstrip()
      '   spacious'
      >>> 'mississippi'.rstrip('ipz')
      'mississ'

   .. versionchanged:: 2.2.2
      Support for the *chars* argument.


.. method:: str.split([sep[, maxsplit]])

   Return a list of the words in the string, using *sep* as the delimiter
   string.  If *maxsplit* is given, at most *maxsplit* splits are done (thus,
   the list will have at most ``maxsplit+1`` elements).  If *maxsplit* is not
   specified or ``-1``, then there is no limit on the number of splits
   (all possible splits are made).

   If *sep* is given, consecutive delimiters are not grouped together and are
   deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
   ``['1', '', '2']``).  The *sep* argument may consist of multiple characters
   (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
   Splitting an empty string with a specified separator returns ``['']``.

   If *sep* is not specified or is ``None``, a different splitting algorithm is
   applied: runs of consecutive whitespace are regarded as a single separator,
   and the result will contain no empty strings at the start or end if the
   string has leading or trailing whitespace.  Consequently, splitting an empty
   string or a string consisting of just whitespace with a ``None`` separator
   returns ``[]``.

   For example, ``' 1  2   3  '.split()`` returns ``['1', '2', '3']``, and
   ``'  1  2   3  '.split(None, 1)`` returns ``['1', '2   3  ']``.


.. index::
   single: universal newlines; str.splitlines method

.. method:: str.splitlines([keepends])

   Return a list of the lines in the string, breaking at line boundaries.
   This method uses the :term:`universal newlines` approach to splitting lines.
   Line breaks are not included in the resulting list unless *keepends* is
   given and true.

   Python recognizes ``"\r"``, ``"\n"``, and ``"\r\n"`` as line boundaries for
   8-bit strings.

   For example::

      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
      ['ab c', '', 'de fg', 'kl']
      >>> 'ab c\n\nde fg\rkl\r\n'.splitlines(True)
      ['ab c\n', '\n', 'de fg\r', 'kl\r\n']

   Unlike :meth:`~str.split` when a delimiter string *sep* is given, this
   method returns an empty list for the empty string, and a terminal line
   break does not result in an extra line::

      >>> "".splitlines()
      []
      >>> "One line\n".splitlines()
      ['One line']

   For comparison, ``split('\n')`` gives::

      >>> ''.split('\n')
      ['']
      >>> 'Two lines\n'.split('\n')
      ['Two lines', '']

.. method:: unicode.splitlines([keepends])

   Return a list of the lines in the string, like :meth:`str.splitlines`.
   However, the Unicode method splits on the following line boundaries,
   which are a superset of the :term:`universal newlines` recognized for
   8-bit strings.

   +-----------------------+-----------------------------+
   | Representation        | Description                 |
   +=======================+=============================+
   | ``\n``                | Line Feed                   |
   +-----------------------+-----------------------------+
   | ``\r``                | Carriage Return             |
   +-----------------------+-----------------------------+
   | ``\r\n``              | Carriage Return + Line Feed |
   +-----------------------+-----------------------------+
   | ``\v`` or ``\x0b``    | Line Tabulation             |
   +-----------------------+-----------------------------+
   | ``\f`` or ``\x0c``    | Form Feed                   |
   +-----------------------+-----------------------------+
   | ``\x1c``              | File Separator              |
   +-----------------------+-----------------------------+
   | ``\x1d``              | Group Separator             |
   +-----------------------+-----------------------------+
   | ``\x1e``              | Record Separator            |
   +-----------------------+-----------------------------+
   | ``\x85``              | Next Line (C1 Control Code) |
   +-----------------------+-----------------------------+
   | ``\u2028``            | Line Separator              |
   +-----------------------+-----------------------------+
   | ``\u2029``            | Paragraph Separator         |
   +-----------------------+-----------------------------+

   .. versionchanged:: 2.7

      ``\v`` and ``\f`` added to list of line boundaries.


.. method:: str.startswith(prefix[, start[, end]])

   Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
   *prefix* can also be a tuple of prefixes to look for.  With optional *start*,
   test string beginning at that position.  With optional *end*, stop comparing
   string at that position.

   .. versionchanged:: 2.5
      Accept tuples as *prefix*.


.. method:: str.strip([chars])

   Return a copy of the string with the leading and trailing characters removed.
   The *chars* argument is a string specifying the set of characters to be removed.
   If omitted or ``None``, the *chars* argument defaults to removing whitespace.
   The *chars* argument is not a prefix or suffix; rather, all combinations of its
   values are stripped:

      >>> '   spacious   '.strip()
      'spacious'
      >>> 'www.example.com'.strip('cmowz.')
      'example'

   .. versionchanged:: 2.2.2
      Support for the *chars* argument.


.. method:: str.swapcase()

   Return a copy of the string with uppercase characters converted to lowercase and
   vice versa.

   For 8-bit strings, this method is locale-dependent.


.. method:: str.title()

   Return a titlecased version of the string where words start with an uppercase
   character and the remaining characters are lowercase.

   The algorithm uses a simple language-independent definition of a word as
   groups of consecutive letters.  The definition works in many contexts but
   it means that apostrophes in contractions and possessives form word
   boundaries, which may not be the desired result::

        >>> "they're bill's friends from the UK".title()
        "They'Re Bill'S Friends From The Uk"

   A workaround for apostrophes can be constructed using regular expressions::

        >>> import re
        >>> def titlecase(s):
        ...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
        ...                   lambda mo: mo.group(0)[0].upper() +
        ...                              mo.group(0)[1:].lower(),
        ...                   s)
        ...
        >>> titlecase("they're bill's friends.")
        "They're Bill's Friends."

   For 8-bit strings, this method is locale-dependent.


.. method:: str.translate(table[, deletechars])

   Return a copy of the string where all characters occurring in the optional
   argument *deletechars* are removed, and the remaining characters have been
   mapped through the given translation table, which must be a string of length
   256.

   You can use the :func:`~string.maketrans` helper function in the :mod:`string`
   module to create a translation table. For string objects, set the *table*
   argument to ``None`` for translations that only delete characters:

      >>> 'read this short text'.translate(None, 'aeiou')
      'rd ths shrt txt'

   .. versionadded:: 2.6
      Support for a ``None`` *table* argument.

   For Unicode objects, the :meth:`translate` method does not accept the optional
   *deletechars* argument.  Instead, it returns a copy of the *s* where all
   characters have been mapped through the given translation table which must be a
   mapping of Unicode ordinals to Unicode ordinals, Unicode strings or ``None``.
   Unmapped characters are left untouched. Characters mapped to ``None`` are
   deleted.  Note, a more flexible approach is to create a custom character mapping
   codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
   example).


.. method:: str.upper()

   Return a copy of the string with all the cased characters [4]_ converted to
   uppercase.  Note that ``s.upper().isupper()`` might be ``False`` if ``s``
   contains uncased characters or if the Unicode category of the resulting
   character(s) is not "Lu" (Letter, uppercase), but e.g. "Lt" (Letter, titlecase).

   For 8-bit strings, this method is locale-dependent.


.. method:: str.zfill(width)

   Return the numeric string left filled with zeros in a string of length
   *width*.  A sign prefix is handled correctly.  The original string is
   returned if *width* is less than or equal to ``len(s)``.


   .. versionadded:: 2.2.2

The following methods are present only on unicode objects:

.. method:: unicode.isnumeric()

   Return ``True`` if there are only numeric characters in S, ``False``
   otherwise. Numeric characters include digit characters, and all characters
   that have the Unicode numeric value property, e.g. U+2155,
   VULGAR FRACTION ONE FIFTH.

.. method:: unicode.isdecimal()

   Return ``True`` if there are only decimal characters in S, ``False``
   otherwise. Decimal characters include digit characters, and all characters
   that can be used to form decimal-radix numbers, e.g. U+0660,
   ARABIC-INDIC DIGIT ZERO.


.. _string-formatting:

String Formatting Operations
----------------------------

.. index::
   single: formatting, string (%)
   single: interpolation, string (%)
   single: string; formatting
   single: string; interpolation
   single: printf-style formatting
   single: sprintf-style formatting
   single: % formatting
   single: % interpolation

String and Unicode objects have one unique built-in operation: the ``%``
operator (modulo).  This is also known as the string *formatting* or
*interpolation* operator.  Given ``format % values`` (where *format* is a string
or Unicode object), ``%`` conversion specifications in *format* are replaced
with zero or more elements of *values*.  The effect is similar to the using
:c:func:`sprintf` in the C language.  If *format* is a Unicode object, or if any
of the objects being converted using the ``%s`` conversion are Unicode objects,
the result will also be a Unicode object.

If *format* requires a single argument, *values* may be a single non-tuple
object. [5]_  Otherwise, *values* must be a tuple with exactly the number of
items specified by the format string, or a single mapping object (for example, a
dictionary).

A conversion specifier contains two or more characters and has the following
components, which must occur in this order:

#. The ``'%'`` character, which marks the start of the specifier.

#. Mapping key (optional), consisting of a parenthesised sequence of characters
   (for example, ``(somename)``).

#. Conversion flags (optional), which affect the result of some conversion
   types.

#. Minimum field width (optional).  If specified as an ``'*'`` (asterisk), the
   actual width is read from the next element of the tuple in *values*, and the
   object to convert comes after the minimum field width and optional precision.

#. Precision (optional), given as a ``'.'`` (dot) followed by the precision.  If
   specified as ``'*'`` (an asterisk), the actual width is read from the next
   element of the tuple in *values*, and the value to convert comes after the
   precision.

#. Length modifier (optional).

#. Conversion type.

When the right argument is a dictionary (or other mapping type), then the
formats in the string *must* include a parenthesised mapping key into that
dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping.  For example:

   >>> print '%(language)s has %(number)03d quote types.' % \
   ...       {"language": "Python", "number": 2}
   Python has 002 quote types.

In this case no ``*`` specifiers may occur in a format (since they require a
sequential parameter list).

The conversion flag characters are:

+---------+---------------------------------------------------------------------+
| Flag    | Meaning                                                             |
+=========+=====================================================================+
| ``'#'`` | The value conversion will use the "alternate form" (where defined   |
|         | below).                                                             |
+---------+---------------------------------------------------------------------+
| ``'0'`` | The conversion will be zero padded for numeric values.              |
+---------+---------------------------------------------------------------------+
| ``'-'`` | The converted value is left adjusted (overrides the ``'0'``         |
|         | conversion if both are given).                                      |
+---------+---------------------------------------------------------------------+
| ``' '`` | (a space) A blank should be left before a positive number (or empty |
|         | string) produced by a signed conversion.                            |
+---------+---------------------------------------------------------------------+
| ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion   |
|         | (overrides a "space" flag).                                         |
+---------+---------------------------------------------------------------------+

A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.

The conversion types are:

+------------+-----------------------------------------------------+-------+
| Conversion | Meaning                                             | Notes |
+============+=====================================================+=======+
| ``'d'``    | Signed integer decimal.                             |       |
+------------+-----------------------------------------------------+-------+
| ``'i'``    | Signed integer decimal.                             |       |
+------------+-----------------------------------------------------+-------+
| ``'o'``    | Signed octal value.                                 | \(1)  |
+------------+-----------------------------------------------------+-------+
| ``'u'``    | Obsolete type -- it is identical to ``'d'``.        | \(7)  |
+------------+-----------------------------------------------------+-------+
| ``'x'``    | Signed hexadecimal (lowercase).                     | \(2)  |
+------------+-----------------------------------------------------+-------+
| ``'X'``    | Signed hexadecimal (uppercase).                     | \(2)  |
+------------+-----------------------------------------------------+-------+
| ``'e'``    | Floating point exponential format (lowercase).      | \(3)  |
+------------+-----------------------------------------------------+-------+
| ``'E'``    | Floating point exponential format (uppercase).      | \(3)  |
+------------+-----------------------------------------------------+-------+
| ``'f'``    | Floating point decimal format.                      | \(3)  |
+------------+-----------------------------------------------------+-------+
| ``'F'``    | Floating point decimal format.                      | \(3)  |
+------------+-----------------------------------------------------+-------+
| ``'g'``    | Floating point format. Uses lowercase exponential   | \(4)  |
|            | format if exponent is less than -4 or not less than |       |
|            | precision, decimal format otherwise.                |       |
+------------+-----------------------------------------------------+-------+
| ``'G'``    | Floating point format. Uses uppercase exponential   | \(4)  |
|            | format if exponent is less than -4 or not less than |       |
|            | precision, decimal format otherwise.                |       |
+------------+-----------------------------------------------------+-------+
| ``'c'``    | Single character (accepts integer or single         |       |
|            | character string).                                  |       |
+------------+-----------------------------------------------------+-------+
| ``'r'``    | String (converts any Python object using            | \(5)  |
|            | :ref:`repr() <func-repr>`).                         |       |
+------------+-----------------------------------------------------+-------+
| ``'s'``    | String (converts any Python object using            | \(6)  |
|            | :func:`str`).                                       |       |
+------------+-----------------------------------------------------+-------+
| ``'%'``    | No argument is converted, results in a ``'%'``      |       |
|            | character in the result.                            |       |
+------------+-----------------------------------------------------+-------+

Notes:

(1)
   The alternate form causes a leading zero (``'0'``) to be inserted between
   left-hand padding and the formatting of the number if the leading character
   of the result is not already a zero.

(2)
   The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
   the ``'x'`` or ``'X'`` format was used) to be inserted before the first digit.

(3)
   The alternate form causes the result to always contain a decimal point, even if
   no digits follow it.

   The precision determines the number of digits after the decimal point and
   defaults to 6.

(4)
   The alternate form causes the result to always contain a decimal point, and
   trailing zeroes are not removed as they would otherwise be.

   The precision determines the number of significant digits before and after the
   decimal point and defaults to 6.

(5)
   The ``%r`` conversion was added in Python 2.0.

   The precision determines the maximal number of characters used.

(6)
   If the object or format provided is a :class:`unicode` string, the resulting
   string will also be :class:`unicode`.

   The precision determines the maximal number of characters used.

(7)
   See :pep:`237`.

Since Python strings have an explicit length, ``%s`` conversions do not assume
that ``'\0'`` is the end of the string.

.. XXX Examples?

.. versionchanged:: 2.7
   ``%f`` conversions for numbers whose absolute value is over 1e50 are no
   longer replaced by ``%g`` conversions.

.. index::
   module: string
   module: re

Additional string operations are defined in standard modules :mod:`string` and
:mod:`re`.


.. _typesseq-xrange:

XRange Type
-----------

.. index:: object: xrange

The :class:`xrange` type is an immutable sequence which is commonly used for
looping.  The advantage of the :class:`xrange` type is that an :class:`xrange`
object will always take the same amount of memory, no matter the size of the
range it represents.  There are no consistent performance advantages.

XRange objects have very little behavior: they only support indexing, iteration,
and the :func:`len` function.


.. _typesseq-mutable:

Mutable Sequence Types
----------------------

.. index::
   triple: mutable; sequence; types
   object: list

List and :class:`bytearray` objects support additional operations that allow
in-place modification of the object. Other mutable sequence types (when added
to the language) should also support these operations. Strings and tuples
are immutable sequence types: such objects cannot be modified once created.
The following operations are defined on mutable sequence types (where *x* is
an arbitrary object):

.. index::
   triple: operations on; sequence; types
   triple: operations on; list; type
   pair: subscript; assignment
   pair: slice; assignment
   pair: extended slice; assignment
   statement: del
   single: append() (list method)
   single: extend() (list method)
   single: count() (list method)
   single: index() (list method)
   single: insert() (list method)
   single: pop() (list method)
   single: remove() (list method)
   single: reverse() (list method)
   single: sort() (list method)

+------------------------------+--------------------------------+---------------------+
| Operation                    | Result                         | Notes               |
+==============================+================================+=====================+
| ``s[i] = x``                 | item *i* of *s* is replaced by |                     |
|                              | *x*                            |                     |
+------------------------------+--------------------------------+---------------------+
| ``s[i:j] = t``               | slice of *s* from *i* to *j*   |                     |
|                              | is replaced by the contents of |                     |
|                              | the iterable *t*               |                     |
+------------------------------+--------------------------------+---------------------+
| ``del s[i:j]``               | same as ``s[i:j] = []``        |                     |
+------------------------------+--------------------------------+---------------------+
| ``s[i:j:k] = t``             | the elements of ``s[i:j:k]``   | \(1)                |
|                              | are replaced by those of *t*   |                     |
+------------------------------+--------------------------------+---------------------+
| ``del s[i:j:k]``             | removes the elements of        |                     |
|                              | ``s[i:j:k]`` from the list     |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.append(x)``              | same as ``s[len(s):len(s)] =   | \(2)                |
|                              | [x]``                          |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.extend(t)`` or           | for the most part the same as  | \(3)                |
| ``s += t``                   | ``s[len(s):len(s)] = t``       |                     |
+------------------------------+--------------------------------+---------------------+
| ``s *= n``                   | updates *s* with its contents  | \(11)               |
|                              | repeated *n* times             |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.count(x)``               | return number of *i*'s for     |                     |
|                              | which ``s[i] == x``            |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.index(x[, i[, j]])``     | return smallest *k* such that  | \(4)                |
|                              | ``s[k] == x`` and ``i <= k <   |                     |
|                              | j``                            |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.insert(i, x)``           | same as ``s[i:i] = [x]``       | \(5)                |
+------------------------------+--------------------------------+---------------------+
| ``s.pop([i])``               | same as ``x = s[i]; del s[i];  | \(6)                |
|                              | return x``                     |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.remove(x)``              | same as ``del s[s.index(x)]``  | \(4)                |
+------------------------------+--------------------------------+---------------------+
| ``s.reverse()``              | reverses the items of *s* in   | \(7)                |
|                              | place                          |                     |
+------------------------------+--------------------------------+---------------------+
| ``s.sort([cmp[, key[,        | sort the items of *s* in place | (7)(8)(9)(10)       |
| reverse]]])``                |                                |                     |
+------------------------------+--------------------------------+---------------------+

Notes:

(1)
   *t* must have the same length as the slice it is  replacing.

(2)
   The C implementation of Python has historically accepted multiple parameters and
   implicitly joined them into a tuple; this no longer works in Python 2.0.  Use of
   this misfeature has been deprecated since Python 1.4.

(3)
   *t* can be any iterable object.

(4)
   Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
   passed as the second or third parameter to the :meth:`index` method, the list
   length is added, as for slice indices.  If it is still negative, it is truncated
   to zero, as for slice indices.

   .. versionchanged:: 2.3
      Previously, :meth:`index` didn't have arguments for specifying start and stop
      positions.

(5)
   When a negative index is passed as the first parameter to the :meth:`insert`
   method, the list length is added, as for slice indices.  If it is still
   negative, it is truncated to zero, as for slice indices.

   .. versionchanged:: 2.3
      Previously, all negative indices were truncated to zero.

(6)
   The :meth:`pop` method's optional argument *i* defaults to ``-1``, so that
   by default the last item is removed and returned.

(7)
   The :meth:`sort` and :meth:`reverse` methods modify the list in place for
   economy of space when sorting or reversing a large list.  To remind you that
   they operate by side effect, they don't return the sorted or reversed list.

(8)
   The :meth:`sort` method takes optional arguments for controlling the
   comparisons.

   *cmp* specifies a custom comparison function of two arguments (list items) which
   should return a negative, zero or positive number depending on whether the first
   argument is considered smaller than, equal to, or larger than the second
   argument: ``cmp=lambda x,y: cmp(x.lower(), y.lower())``.  The default value
   is ``None``.

   *key* specifies a function of one argument that is used to extract a comparison
   key from each list element: ``key=str.lower``.  The default value is ``None``.

   *reverse* is a boolean value.  If set to ``True``, then the list elements are
   sorted as if each comparison were reversed.

   In general, the *key* and *reverse* conversion processes are much faster than
   specifying an equivalent *cmp* function.  This is because *cmp* is called
   multiple times for each list element while *key* and *reverse* touch each
   element only once.  Use :func:`functools.cmp_to_key` to convert an
   old-style *cmp* function to a *key* function.

   .. versionchanged:: 2.3
      Support for ``None`` as an equivalent to omitting *cmp* was added.

   .. versionchanged:: 2.4
      Support for *key* and *reverse* was added.

(9)
   Starting with Python 2.3, the :meth:`sort` method is guaranteed to be stable.  A
   sort is stable if it guarantees not to change the relative order of elements
   that compare equal --- this is helpful for sorting in multiple passes (for
   example, sort by department, then by salary grade).

(10)
   .. impl-detail::

      While a list is being sorted, the effect of attempting to mutate, or even
      inspect, the list is undefined.  The C implementation of Python 2.3 and
      newer makes the list appear empty for the duration, and raises
      :exc:`ValueError` if it can detect that the list has been mutated during a
      sort.

(11)
   The value *n* is an integer, or an object implementing
   :meth:`~object.__index__`.  Zero and negative values of *n* clear
   the sequence.  Items in the sequence are not copied; they are referenced
   multiple times, as explained for ``s * n`` under :ref:`typesseq`.


.. _types-set:

Set Types --- :class:`set`, :class:`frozenset`
==============================================

.. index:: object: set

A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
Common uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference.
(For other containers see the built in :class:`dict`, :class:`list`,
and :class:`tuple` classes, and the :mod:`collections` module.)


.. versionadded:: 2.4

Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
set``.  Being an unordered collection, sets do not record element position or
order of insertion.  Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.

There are currently two built-in set types, :class:`set` and :class:`frozenset`.
The :class:`set` type is mutable --- the contents can be changed using methods
like :meth:`~set.add` and :meth:`~set.remove`.  Since it is mutable, it has no
hash value and cannot be used as either a dictionary key or as an element of
another set.  The :class:`frozenset` type is immutable and :term:`hashable` ---
its contents cannot be altered after it is created; it can therefore be used as
a dictionary key or as an element of another set.

As of Python 2.7, non-empty sets (not frozensets) can be created by placing a
comma-separated list of elements within braces, for example: ``{'jack',
'sjoerd'}``, in addition to the :class:`set` constructor.

The constructors for both classes work the same:

.. class:: set([iterable])
           frozenset([iterable])

   Return a new set or frozenset object whose elements are taken from
   *iterable*.  The elements of a set must be :term:`hashable`.  To
   represent sets of sets, the inner sets must be :class:`frozenset`
   objects.  If *iterable* is not specified, a new empty set is
   returned.

   Instances of :class:`set` and :class:`frozenset` provide the following
   operations:

   .. describe:: len(s)

      Return the number of elements in set *s* (cardinality of *s*).

   .. describe:: x in s

      Test *x* for membership in *s*.

   .. describe:: x not in s

      Test *x* for non-membership in *s*.

   .. method:: isdisjoint(other)

      Return ``True`` if the set has no elements in common with *other*.  Sets are
      disjoint if and only if their intersection is the empty set.

      .. versionadded:: 2.6

   .. method:: issubset(other)
               set <= other

      Test whether every element in the set is in *other*.

   .. method:: set < other

      Test whether the set is a proper subset of *other*, that is,
      ``set <= other and set != other``.

   .. method:: issuperset(other)
               set >= other

      Test whether every element in *other* is in the set.

   .. method:: set > other

      Test whether the set is a proper superset of *other*, that is, ``set >=
      other and set != other``.

   .. method:: union(*others)
               set | other | ...

      Return a new set with elements from the set and all others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: intersection(*others)
               set & other & ...

      Return a new set with elements common to the set and all others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: difference(*others)
               set - other - ...

      Return a new set with elements in the set that are not in the others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: symmetric_difference(other)
               set ^ other

      Return a new set with elements in either the set or *other* but not both.

   .. method:: copy()

      Return a new set with a shallow copy of *s*.


   Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
   :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
   :meth:`issuperset` methods will accept any iterable as an argument.  In
   contrast, their operator based counterparts require their arguments to be
   sets.  This precludes error-prone constructions like ``set('abc') & 'cbs'``
   in favor of the more readable ``set('abc').intersection('cbs')``.

   Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
   sets are equal if and only if every element of each set is contained in the
   other (each is a subset of the other). A set is less than another set if and
   only if the first set is a proper subset of the second set (is a subset, but
   is not equal). A set is greater than another set if and only if the first set
   is a proper superset of the second set (is a superset, but is not equal).

   Instances of :class:`set` are compared to instances of :class:`frozenset`
   based on their members.  For example, ``set('abc') == frozenset('abc')``
   returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.

   The subset and equality comparisons do not generalize to a total ordering
   function.  For example, any two non-empty disjoint sets are not equal and are not
   subsets of each other, so *all* of the following return ``False``: ``a<b``,
   ``a==b``, or ``a>b``. Accordingly, sets do not implement the :meth:`__cmp__`
   method.

   Since sets only define partial ordering (subset relationships), the output of
   the :meth:`list.sort` method is undefined for lists of sets.

   Set elements, like dictionary keys, must be :term:`hashable`.

   Binary operations that mix :class:`set` instances with :class:`frozenset`
   return the type of the first operand.  For example: ``frozenset('ab') |
   set('bc')`` returns an instance of :class:`frozenset`.

   The following table lists operations available for :class:`set` that do not
   apply to immutable instances of :class:`frozenset`:

   .. method:: update(*others)
               set |= other | ...

      Update the set, adding elements from all others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: intersection_update(*others)
               set &= other & ...

      Update the set, keeping only elements found in it and all others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: difference_update(*others)
               set -= other | ...

      Update the set, removing elements found in others.

      .. versionchanged:: 2.6
         Accepts multiple input iterables.

   .. method:: symmetric_difference_update(other)
               set ^= other

      Update the set, keeping only elements found in either set, but not in both.

   .. method:: add(elem)

      Add element *elem* to the set.

   .. method:: remove(elem)

      Remove element *elem* from the set.  Raises :exc:`KeyError` if *elem* is
      not contained in the set.

   .. method:: discard(elem)

      Remove element *elem* from the set if it is present.

   .. method:: pop()

      Remove and return an arbitrary element from the set.  Raises
      :exc:`KeyError` if the set is empty.

   .. method:: clear()

      Remove all elements from the set.


   Note, the non-operator versions of the :meth:`update`,
   :meth:`intersection_update`, :meth:`difference_update`, and
   :meth:`symmetric_difference_update` methods will accept any iterable as an
   argument.

   Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
   :meth:`discard` methods may be a set.  To support searching for an equivalent
   frozenset, a temporary one is created from *elem*.


.. seealso::

   :ref:`comparison-to-builtin-set`
      Differences between the :mod:`sets` module and the built-in set types.


.. _typesmapping:

Mapping Types --- :class:`dict`
===============================

.. index::
   object: mapping
   object: dictionary
   triple: operations on; mapping; types
   triple: operations on; dictionary; type
   statement: del
   builtin: len

A :term:`mapping` object maps :term:`hashable` values to arbitrary objects.
Mappings are mutable objects.  There is currently only one standard mapping
type, the :dfn:`dictionary`.  (For other containers see the built in
:class:`list`, :class:`set`, and :class:`tuple` classes, and the
:mod:`collections` module.)

A dictionary's keys are *almost* arbitrary values.  Values that are not
:term:`hashable`, that is, values containing lists, dictionaries or other
mutable types (that are compared by value rather than by object identity) may
not be used as keys.  Numeric types used for keys obey the normal rules for
numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
then they can be used interchangeably to index the same dictionary entry.  (Note
however, that since computers store floating-point numbers as approximations it
is usually unwise to use them as dictionary keys.)

Dictionaries can be created by placing a comma-separated list of ``key: value``
pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.

.. class:: dict(**kwarg)
           dict(mapping, **kwarg)
           dict(iterable, **kwarg)

   Return a new dictionary initialized from an optional positional argument
   and a possibly empty set of keyword arguments.

   If no positional argument is given, an empty dictionary is created.
   If a positional argument is given and it is a mapping object, a dictionary
   is created with the same key-value pairs as the mapping object.  Otherwise,
   the positional argument must be an :term:`iterable` object.  Each item in
   the iterable must itself be an iterable with exactly two objects.  The
   first object of each item becomes a key in the new dictionary, and the
   second object the corresponding value.  If a key occurs more than once, the
   last value for that key becomes the corresponding value in the new
   dictionary.

   If keyword arguments are given, the keyword arguments and their values are
   added to the dictionary created from the positional argument.  If a key
   being added is already present, the value from the keyword argument
   replaces the value from the positional argument.

   To illustrate, the following examples all return a dictionary equal to
   ``{"one": 1, "two": 2, "three": 3}``::

      >>> a = dict(one=1, two=2, three=3)
      >>> b = {'one': 1, 'two': 2, 'three': 3}
      >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
      >>> d = dict([('two', 2), ('one', 1), ('three', 3)])
      >>> e = dict({'three': 3, 'one': 1, 'two': 2})
      >>> a == b == c == d == e
      True

   Providing keyword arguments as in the first example only works for keys that
   are valid Python identifiers.  Otherwise, any valid keys can be used.

   .. versionadded:: 2.2

   .. versionchanged:: 2.3
      Support for building a dictionary from keyword arguments added.


   These are the operations that dictionaries support (and therefore, custom
   mapping types should support too):

   .. describe:: len(d)

      Return the number of items in the dictionary *d*.

   .. describe:: d[key]

      Return the item of *d* with key *key*.  Raises a :exc:`KeyError` if *key*
      is not in the map.

      .. index:: __missing__()

      If a subclass of dict defines a method :meth:`__missing__` and *key*
      is not present, the ``d[key]`` operation calls that method with the key *key*
      as argument.  The ``d[key]`` operation then returns or raises whatever is
      returned or raised by the ``__missing__(key)`` call.
      No other operations or methods invoke :meth:`__missing__`. If
      :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
      :meth:`__missing__` must be a method; it cannot be an instance variable::

          >>> class Counter(dict):
          ...     def __missing__(self, key):
          ...         return 0
          >>> c = Counter()
          >>> c['red']
          0
          >>> c['red'] += 1
          >>> c['red']
          1

      The example above shows part of the implementation of
      :class:`collections.Counter`.  A different ``__missing__`` method is used
      by :class:`collections.defaultdict`.

      .. versionadded:: 2.5
         Recognition of __missing__ methods of dict subclasses.

   .. describe:: d[key] = value

      Set ``d[key]`` to *value*.

   .. describe:: del d[key]

      Remove ``d[key]`` from *d*.  Raises a :exc:`KeyError` if *key* is not in the
      map.

   .. describe:: key in d

      Return ``True`` if *d* has a key *key*, else ``False``.

      .. versionadded:: 2.2

   .. describe:: key not in d

      Equivalent to ``not key in d``.

      .. versionadded:: 2.2

   .. describe:: iter(d)

      Return an iterator over the keys of the dictionary.  This is a shortcut
      for :meth:`iterkeys`.

   .. method:: clear()

      Remove all items from the dictionary.

   .. method:: copy()

      Return a shallow copy of the dictionary.

   .. method:: fromkeys(seq[, value])

      Create a new dictionary with keys from *seq* and values set to *value*.

      :func:`fromkeys` is a class method that returns a new dictionary. *value*
      defaults to ``None``.

      .. versionadded:: 2.3

   .. method:: get(key[, default])

      Return the value for *key* if *key* is in the dictionary, else *default*.
      If *default* is not given, it defaults to ``None``, so that this method
      never raises a :exc:`KeyError`.

   .. method:: has_key(key)

      Test for the presence of *key* in the dictionary.  :meth:`has_key` is
      deprecated in favor of ``key in d``.

   .. method:: items()

      Return a copy of the dictionary's list of ``(key, value)`` pairs.

      .. impl-detail::

         Keys and values are listed in an arbitrary order which is non-random,
         varies across Python implementations, and depends on the dictionary's
         history of insertions and deletions.

      If :meth:`items`, :meth:`keys`, :meth:`values`, :meth:`iteritems`,
      :meth:`iterkeys`, and :meth:`itervalues` are called with no intervening
      modifications to the dictionary, the lists will directly correspond.  This
      allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs =
      zip(d.values(), d.keys())``.  The same relationship holds for the
      :meth:`iterkeys` and :meth:`itervalues` methods: ``pairs =
      zip(d.itervalues(), d.iterkeys())`` provides the same value for
      ``pairs``. Another way to create the same list is ``pairs = [(v, k) for
      (k, v) in d.iteritems()]``.

   .. method:: iteritems()

      Return an iterator over the dictionary's ``(key, value)`` pairs.  See the
      note for :meth:`dict.items`.

      Using :meth:`iteritems` while adding or deleting entries in the dictionary
      may raise a :exc:`RuntimeError` or fail to iterate over all entries.

      .. versionadded:: 2.2

   .. method:: iterkeys()

      Return an iterator over the dictionary's keys.  See the note for
      :meth:`dict.items`.

      Using :meth:`iterkeys` while adding or deleting entries in the dictionary
      may raise a :exc:`RuntimeError` or fail to iterate over all entries.

      .. versionadded:: 2.2

   .. method:: itervalues()

      Return an iterator over the dictionary's values.  See the note for
      :meth:`dict.items`.

      Using :meth:`itervalues` while adding or deleting entries in the
      dictionary may raise a :exc:`RuntimeError` or fail to iterate over all
      entries.

      .. versionadded:: 2.2

   .. method:: keys()

      Return a copy of the dictionary's list of keys.  See the note for
      :meth:`dict.items`.

   .. method:: pop(key[, default])

      If *key* is in the dictionary, remove it and return its value, else return
      *default*.  If *default* is not given and *key* is not in the dictionary,
      a :exc:`KeyError` is raised.

      .. versionadded:: 2.3

   .. method:: popitem()

      Remove and return an arbitrary ``(key, value)`` pair from the dictionary.

      :func:`popitem` is useful to destructively iterate over a dictionary, as
      often used in set algorithms.  If the dictionary is empty, calling
      :func:`popitem` raises a :exc:`KeyError`.

   .. method:: setdefault(key[, default])

      If *key* is in the dictionary, return its value.  If not, insert *key*
      with a value of *default* and return *default*.  *default* defaults to
      ``None``.

   .. method:: update([other])

      Update the dictionary with the key/value pairs from *other*, overwriting
      existing keys.  Return ``None``.

      :func:`update` accepts either another dictionary object or an iterable of
      key/value pairs (as tuples or other iterables of length two).  If keyword
      arguments are specified, the dictionary is then updated with those
      key/value pairs: ``d.update(red=1, blue=2)``.

      .. versionchanged:: 2.4
          Allowed the argument to be an iterable of key/value pairs and allowed
          keyword arguments.

   .. method:: values()

      Return a copy of the dictionary's list of values.  See the note for
      :meth:`dict.items`.

   .. method:: viewitems()

      Return a new view of the dictionary's items (``(key, value)`` pairs).  See
      below for documentation of view objects.

      .. versionadded:: 2.7

   .. method:: viewkeys()

      Return a new view of the dictionary's keys.  See below for documentation of
      view objects.

      .. versionadded:: 2.7

   .. method:: viewvalues()

      Return a new view of the dictionary's values.  See below for documentation of
      view objects.

      .. versionadded:: 2.7

   Dictionaries compare equal if and only if they have the same ``(key,
   value)`` pairs.


.. _dict-views:

Dictionary view objects
-----------------------

The objects returned by :meth:`dict.viewkeys`, :meth:`dict.viewvalues` and
:meth:`dict.viewitems` are *view objects*.  They provide a dynamic view on the
dictionary's entries, which means that when the dictionary changes, the view
reflects these changes.

Dictionary views can be iterated over to yield their respective data, and
support membership tests:

.. describe:: len(dictview)

   Return the number of entries in the dictionary.

.. describe:: iter(dictview)

   Return an iterator over the keys, values or items (represented as tuples of
   ``(key, value)``) in the dictionary.

   Keys and values are iterated over in an arbitrary order which is non-random,
   varies across Python implementations, and depends on the dictionary's history
   of insertions and deletions. If keys, values and items views are iterated
   over with no intervening modifications to the dictionary, the order of items
   will directly correspond.  This allows the creation of ``(value, key)`` pairs
   using :func:`zip`: ``pairs = zip(d.values(), d.keys())``.  Another way to
   create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.

   Iterating views while adding or deleting entries in the dictionary may raise
   a :exc:`RuntimeError` or fail to iterate over all entries.

.. describe:: x in dictview

   Return ``True`` if *x* is in the underlying dictionary's keys, values or
   items (in the latter case, *x* should be a ``(key, value)`` tuple).


Keys views are set-like since their entries are unique and hashable.  If all
values are hashable, so that (key, value) pairs are unique and hashable, then
the items view is also set-like.  (Values views are not treated as set-like
since the entries are generally not unique.)  Then these set operations are
available ("other" refers either to another view or a set):

.. describe:: dictview & other

   Return the intersection of the dictview and the other object as a new set.

.. describe:: dictview | other

   Return the union of the dictview and the other object as a new set.

.. describe:: dictview - other

   Return the difference between the dictview and the other object (all elements
   in *dictview* that aren't in *other*) as a new set.

.. describe:: dictview ^ other

   Return the symmetric difference (all elements either in *dictview* or
   *other*, but not in both) of the dictview and the other object as a new set.


An example of dictionary view usage::

   >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
   >>> keys = dishes.viewkeys()
   >>> values = dishes.viewvalues()

   >>> # iteration
   >>> n = 0
   >>> for val in values:
   ...     n += val
   >>> print(n)
   504

   >>> # keys and values are iterated over in the same order
   >>> list(keys)
   ['eggs', 'bacon', 'sausage', 'spam']
   >>> list(values)
   [2, 1, 1, 500]

   >>> # view objects are dynamic and reflect dict changes
   >>> del dishes['eggs']
   >>> del dishes['sausage']
   >>> list(keys)
   ['spam', 'bacon']

   >>> # set operations
   >>> keys & {'eggs', 'bacon', 'salad'}
   {'bacon'}


.. _bltin-file-objects:

File Objects
============

.. index::
   object: file
   builtin: file
   module: os
   module: socket

File objects are implemented using C's ``stdio`` package and can be
created with the built-in :func:`open` function.  File
objects are also returned by some other built-in functions and methods,
such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
method of socket objects. Temporary files can be created using the
:mod:`tempfile` module, and high-level file operations such as copying,
moving, and deleting files and directories can be achieved with the
:mod:`shutil` module.

When a file operation fails for an I/O-related reason, the exception
:exc:`IOError` is raised.  This includes situations where the operation is not
defined for some reason, like :meth:`seek` on a tty device or writing a file
opened for reading.

Files have the following methods:


.. method:: file.close()

   Close the file.  A closed file cannot be read or written any more. Any operation
   which requires that the file be open will raise a :exc:`ValueError` after the
   file has been closed.  Calling :meth:`close` more than once is allowed.

   As of Python 2.5, you can avoid having to call this method explicitly if you use
   the :keyword:`with` statement.  For example, the following code will
   automatically close *f* when the :keyword:`with` block is exited::

      from __future__ import with_statement # This isn't required in Python 2.6

      with open("hello.txt") as f:
          for line in f:
              print line,

   In older versions of Python, you would have needed to do this to get the same
   effect::

      f = open("hello.txt")
      try:
          for line in f:
              print line,
      finally:
          f.close()

   .. note::

      Not all "file-like" types in Python support use as a context manager for the
      :keyword:`with` statement.  If your code is intended to work with any file-like
      object, you can use the function :func:`contextlib.closing` instead of using
      the object directly.


.. method:: file.flush()

   Flush the internal buffer, like ``stdio``'s :c:func:`fflush`.  This may be a
   no-op on some file-like objects.

   .. note::

      :meth:`flush` does not necessarily write the file's data to disk.  Use
      :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.


.. method:: file.fileno()

   .. index::
      pair: file; descriptor
      module: fcntl

   Return the integer "file descriptor" that is used by the underlying
   implementation to request I/O operations from the operating system.  This can be
   useful for other, lower level interfaces that use file descriptors, such as the
   :mod:`fcntl` module or :func:`os.read` and friends.

   .. note::

      File-like objects which do not have a real file descriptor should *not* provide
      this method!


.. method:: file.isatty()

   Return ``True`` if the file is connected to a tty(-like) device, else ``False``.

   .. note::

      If a file-like object is not associated with a real file, this method should
      *not* be implemented.


.. method:: file.next()

   A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
   *f* is closed).  When a file is used as an iterator, typically in a
   :keyword:`for` loop (for example, ``for line in f: print line.strip()``), the
   :meth:`~file.next` method is called repeatedly.  This method returns the next input
   line, or raises :exc:`StopIteration` when EOF is hit when the file is open for
   reading (behavior is undefined when the file is open for writing).  In order to
   make a :keyword:`for` loop the most efficient way of looping over the lines of a
   file (a very common operation), the :meth:`~file.next` method uses a hidden read-ahead
   buffer.  As a consequence of using a read-ahead buffer, combining :meth:`~file.next`
   with other file methods (like :meth:`~file.readline`) does not work right.  However,
   using :meth:`seek` to reposition the file to an absolute position will flush the
   read-ahead buffer.

   .. versionadded:: 2.3


.. method:: file.read([size])

   Read at most *size* bytes from the file (less if the read hits EOF before
   obtaining *size* bytes).  If the *size* argument is negative or omitted, read
   all data until EOF is reached.  The bytes are returned as a string object.  An
   empty string is returned when EOF is encountered immediately.  (For certain
   files, like ttys, it makes sense to continue reading after an EOF is hit.)  Note
   that this method may call the underlying C function :c:func:`fread` more than
   once in an effort to acquire as close to *size* bytes as possible. Also note
   that when in non-blocking mode, less data than was requested may be
   returned, even if no *size* parameter was given.

   .. note::
      This function is simply a wrapper for the underlying
      :c:func:`fread` C function, and will behave the same in corner cases,
      such as whether the EOF value is cached.


.. method:: file.readline([size])

   Read one entire line from the file.  A trailing newline character is kept in
   the string (but may be absent when a file ends with an incomplete line). [6]_
   If the *size* argument is present and non-negative, it is a maximum byte
   count (including the trailing newline) and an incomplete line may be
   returned. When *size* is not 0, an empty string is returned *only* when EOF
   is encountered immediately.

   .. note::

      Unlike ``stdio``'s :c:func:`fgets`, the returned string contains null characters
      (``'\0'``) if they occurred in the input.


.. method:: file.readlines([sizehint])

   Read until EOF using :meth:`~file.readline` and return a list containing the lines
   thus read.  If the optional *sizehint* argument is present, instead of
   reading up to EOF, whole lines totalling approximately *sizehint* bytes
   (possibly after rounding up to an internal buffer size) are read.  Objects
   implementing a file-like interface may choose to ignore *sizehint* if it
   cannot be implemented, or cannot be implemented efficiently.


.. method:: file.xreadlines()

   This method returns the same thing as ``iter(f)``.

   .. versionadded:: 2.1

   .. deprecated:: 2.3
      Use ``for line in file`` instead.


.. method:: file.seek(offset[, whence])

   Set the file's current position, like ``stdio``'s :c:func:`fseek`. The *whence*
   argument is optional and defaults to  ``os.SEEK_SET`` or ``0`` (absolute file
   positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
   current position) and ``os.SEEK_END`` or ``2``  (seek relative to the file's
   end).  There is no return value.

   For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
   ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.

   Note that if the file is opened for appending
   (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
   next write.  If the file is only opened for writing in append mode (mode
   ``'a'``), this method is essentially a no-op, but it remains useful for files
   opened in append mode with reading enabled (mode ``'a+'``).  If the file is
   opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
   legal.  Use of other offsets causes undefined behavior.

   Note that not all file objects are seekable.

   .. versionchanged:: 2.6
      Passing float values as offset has been deprecated.


.. method:: file.tell()

   Return the file's current position, like ``stdio``'s :c:func:`ftell`.

   .. note::

      On Windows, :meth:`tell` can return illegal values (after an :c:func:`fgets`)
      when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
      circumvent this problem.


.. method:: file.truncate([size])

   Truncate the file's size.  If the optional *size* argument is present, the file
   is truncated to (at most) that size.  The size defaults to the current position.
   The current file position is not changed.  Note that if a specified size exceeds
   the file's current size, the result is platform-dependent:  possibilities
   include that the file may remain unchanged, increase to the specified size as if
   zero-filled, or increase to the specified size with undefined new content.
   Availability:  Windows, many Unix variants.


.. method:: file.write(str)

   Write a string to the file.  There is no return value.  Due to buffering, the
   string may not actually show up in the file until the :meth:`flush` or
   :meth:`close` method is called.


.. method:: file.writelines(sequence)

   Write a sequence of strings to the file.  The sequence can be any iterable
   object producing strings, typically a list of strings. There is no return value.
   (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
   add line separators.)

Files support the iterator protocol.  Each iteration returns the same result as
:meth:`~file.readline`, and iteration ends when the :meth:`~file.readline` method returns
an empty string.

File objects also offer a number of other interesting attributes. These are not
required for file-like objects, but should be implemented if they make sense for
the particular object.


.. attribute:: file.closed

   bool indicating the current state of the file object.  This is a read-only
   attribute; the :meth:`close` method changes the value. It may not be available
   on all file-like objects.


.. attribute:: file.encoding

   The encoding that this file uses. When Unicode strings are written to a file,
   they will be converted to byte strings using this encoding. In addition, when
   the file is connected to a terminal, the attribute gives the encoding that the
   terminal is likely to use (that  information might be incorrect if the user has
   misconfigured the  terminal). The attribute is read-only and may not be present
   on all file-like objects. It may also be ``None``, in which case the file uses
   the system default encoding for converting Unicode strings.

   .. versionadded:: 2.3


.. attribute:: file.errors

   The Unicode error handler used along with the encoding.

   .. versionadded:: 2.6


.. attribute:: file.mode

   The I/O mode for the file.  If the file was created using the :func:`open`
   built-in function, this will be the value of the *mode* parameter.  This is a
   read-only attribute and may not be present on all file-like objects.


.. attribute:: file.name

   If the file object was created using :func:`open`, the name of the file.
   Otherwise, some string that indicates the source of the file object, of the
   form ``<...>``.  This is a read-only attribute and may not be present on all
   file-like objects.

   .. index::
      single: universal newlines; file.newlines attribute


.. attribute:: file.newlines

   If Python was built with :term:`universal newlines` enabled (the default) this
   read-only attribute exists, and for files opened in universal newline read
   mode it keeps track of the types of newlines encountered while reading the
   file. The values it can take are ``'\r'``, ``'\n'``, ``'\r\n'``, ``None``
   (unknown, no newlines read yet) or a tuple containing all the newline types
   seen, to indicate that multiple newline conventions were encountered. For
   files not opened in universal newlines read mode the value of this attribute
   will be ``None``.


.. attribute:: file.softspace

   Boolean that indicates whether a space character needs to be printed before
   another value when using the :keyword:`print` statement. Classes that are trying
   to simulate a file object should also have a writable :attr:`softspace`
   attribute, which should be initialized to zero.  This will be automatic for most
   classes implemented in Python (care may be needed for objects that override
   attribute access); types implemented in C will have to provide a writable
   :attr:`softspace` attribute.

   .. note::

      This attribute is not used to control the :keyword:`print` statement, but to
      allow the implementation of :keyword:`print` to keep track of its internal
      state.


.. _typememoryview:

memoryview type
===============

.. versionadded:: 2.7

:class:`memoryview` objects allow Python code to access the internal data
of an object that supports the buffer protocol without copying.  Memory
is generally interpreted as simple bytes.

.. class:: memoryview(obj)

   Create a :class:`memoryview` that references *obj*.  *obj* must support the
   buffer protocol.  Built-in objects that support the buffer protocol include
   :class:`str` and :class:`bytearray` (but not :class:`unicode`).

   A :class:`memoryview` has the notion of an *element*, which is the
   atomic memory unit handled by the originating object *obj*.  For many
   simple types such as :class:`str` and :class:`bytearray`, an element
   is a single byte, but other third-party types may expose larger elements.

   ``len(view)`` returns the total number of elements in the memoryview,
   *view*.  The :class:`~memoryview.itemsize` attribute will give you the
   number of bytes in a single element.

   A :class:`memoryview` supports slicing to expose its data.  Taking a single
   index will return a single element as a :class:`str` object.  Full
   slicing will result in a subview::

      >>> v = memoryview('abcefg')
      >>> v[1]
      'b'
      >>> v[-1]
      'g'
      >>> v[1:4]
      <memory at 0x77ab28>
      >>> v[1:4].tobytes()
      'bce'

   If the object the memoryview is over supports changing its data, the
   memoryview supports slice assignment::

      >>> data = bytearray('abcefg')
      >>> v = memoryview(data)
      >>> v.readonly
      False
      >>> v[0] = 'z'
      >>> data
      bytearray(b'zbcefg')
      >>> v[1:4] = '123'
      >>> data
      bytearray(b'z123fg')
      >>> v[2] = 'spam'
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      ValueError: cannot modify size of memoryview object

   Notice how the size of the memoryview object cannot be changed.

   :class:`memoryview` has two methods:

   .. method:: tobytes()

      Return the data in the buffer as a bytestring (an object of class
      :class:`str`). ::

         >>> m = memoryview("abc")
         >>> m.tobytes()
         'abc'

   .. method:: tolist()

      Return the data in the buffer as a list of integers. ::

         >>> memoryview("abc").tolist()
         [97, 98, 99]

   There are also several readonly attributes available:

   .. attribute:: format

      A string containing the format (in :mod:`struct` module style) for each
      element in the view.  This defaults to ``'B'``, a simple bytestring.

   .. attribute:: itemsize

      The size in bytes of each element of the memoryview.

   .. attribute:: shape

      A tuple of integers the length of :attr:`ndim` giving the shape of the
      memory as an N-dimensional array.

   .. attribute:: ndim

      An integer indicating how many dimensions of a multi-dimensional array the
      memory represents.

   .. attribute:: strides

      A tuple of integers the length of :attr:`ndim` giving the size in bytes to
      access each element for each dimension of the array.

   .. attribute:: readonly

      A bool indicating whether the memory is read only.

   .. memoryview.suboffsets isn't documented because it only seems useful for C


.. _typecontextmanager:

Context Manager Types
=====================

.. versionadded:: 2.5

.. index::
   single: context manager
   single: context management protocol
   single: protocol; context management

Python's :keyword:`with` statement supports the concept of a runtime context
defined by a context manager.  This is implemented using two separate methods
that allow user-defined classes to define a runtime context that is entered
before the statement body is executed and exited when the statement ends.

The :dfn:`context management protocol` consists of a pair of methods that need
to be provided for a context manager object to define a runtime context:


.. method:: contextmanager.__enter__()

   Enter the runtime context and return either this object or another object
   related to the runtime context. The value returned by this method is bound to
   the identifier in the :keyword:`as` clause of :keyword:`with` statements using
   this context manager.

   An example of a context manager that returns itself is a file object. File
   objects return themselves from __enter__() to allow :func:`open` to be used as
   the context expression in a :keyword:`with` statement.

   An example of a context manager that returns a related object is the one
   returned by :func:`decimal.localcontext`. These managers set the active
   decimal context to a copy of the original decimal context and then return the
   copy. This allows changes to be made to the current decimal context in the body
   of the :keyword:`with` statement without affecting code outside the
   :keyword:`with` statement.


.. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)

   Exit the runtime context and return a Boolean flag indicating if any exception
   that occurred should be suppressed. If an exception occurred while executing the
   body of the :keyword:`with` statement, the arguments contain the exception type,
   value and traceback information. Otherwise, all three arguments are ``None``.

   Returning a true value from this method will cause the :keyword:`with` statement
   to suppress the exception and continue execution with the statement immediately
   following the :keyword:`with` statement. Otherwise the exception continues
   propagating after this method has finished executing. Exceptions that occur
   during execution of this method will replace any exception that occurred in the
   body of the :keyword:`with` statement.

   The exception passed in should never be reraised explicitly - instead, this
   method should return a false value to indicate that the method completed
   successfully and does not want to suppress the raised exception. This allows
   context management code (such as ``contextlib.nested``) to easily detect whether
   or not an :meth:`__exit__` method has actually failed.

Python defines several context managers to support easy thread synchronisation,
prompt closure of files or other objects, and simpler manipulation of the active
decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
:mod:`contextlib` module for some examples.

Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
provide a convenient way to implement these protocols.  If a generator function is
decorated with the ``contextlib.contextmanager`` decorator, it will return a
context manager implementing the necessary :meth:`__enter__` and
:meth:`__exit__` methods, rather than the iterator produced by an undecorated
generator function.

Note that there is no specific slot for any of these methods in the type
structure for Python objects in the Python/C API. Extension types wanting to
define these methods must provide them as a normal Python accessible method.
Compared to the overhead of setting up the runtime context, the overhead of a
single class dictionary lookup is negligible.


.. _typesother:

Other Built-in Types
====================

The interpreter supports several other kinds of objects. Most of these support
only one or two operations.


.. _typesmodules:

Modules
-------

The only special operation on a module is attribute access: ``m.name``, where
*m* is a module and *name* accesses a name defined in *m*'s symbol table.
Module attributes can be assigned to.  (Note that the :keyword:`import`
statement is not, strictly speaking, an operation on a module object; ``import
foo`` does not require a module object named *foo* to exist, rather it requires
an (external) *definition* for a module named *foo* somewhere.)

A special attribute of every module is :attr:`~object.__dict__`. This is the
dictionary containing the module's symbol table. Modifying this dictionary will
actually change the module's symbol table, but direct assignment to the
:attr:`~object.__dict__` attribute is not possible (you can write
``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but you can't write
``m.__dict__ = {}``).  Modifying :attr:`~object.__dict__` directly is
not recommended.

Modules built into the interpreter are written like this: ``<module 'sys'
(built-in)>``.  If loaded from a file, they are written as ``<module 'os' from
'/usr/local/lib/pythonX.Y/os.pyc'>``.


.. _typesobjects:

Classes and Class Instances
---------------------------

See :ref:`objects` and :ref:`class` for these.


.. _typesfunctions:

Functions
---------

Function objects are created by function definitions.  The only operation on a
function object is to call it: ``func(argument-list)``.

There are really two flavors of function objects: built-in functions and
user-defined functions.  Both support the same operation (to call the function),
but the implementation is different, hence the different object types.

See :ref:`function` for more information.


.. _typesmethods:

Methods
-------

.. index:: object: method

Methods are functions that are called using the attribute notation. There are
two flavors: built-in methods (such as :meth:`append` on lists) and class
instance methods.  Built-in methods are described with the types that support
them.

The implementation adds two special read-only attributes to class instance
methods: ``m.im_self`` is the object on which the method operates, and
``m.im_func`` is the function implementing the method.  Calling ``m(arg-1,
arg-2, ..., arg-n)`` is completely equivalent to calling ``m.im_func(m.im_self,
arg-1, arg-2, ..., arg-n)``.

Class instance methods are either *bound* or *unbound*, referring to whether the
method was accessed through an instance or a class, respectively.  When a method
is unbound, its ``im_self`` attribute will be ``None`` and if called, an
explicit ``self`` object must be passed as the first argument.  In this case,
``self`` must be an instance of the unbound method's class (or a subclass of
that class), otherwise a :exc:`TypeError` is raised.

Like function objects, methods objects support getting arbitrary attributes.
However, since method attributes are actually stored on the underlying function
object (``meth.im_func``), setting method attributes on either bound or unbound
methods is disallowed.  Attempting to set an attribute on a method results in
an :exc:`AttributeError` being raised.  In order to set a method attribute, you
need to explicitly set it on the underlying function object::

   >>> class C:
   ...     def method(self):
   ...         pass
   ...
   >>> c = C()
   >>> c.method.whoami = 'my name is method'  # can't set on the method
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   AttributeError: 'instancemethod' object has no attribute 'whoami'
   >>> c.method.im_func.whoami = 'my name is method'
   >>> c.method.whoami
   'my name is method'


See :ref:`types` for more information.


.. index:: object; code, code object

.. _bltin-code-objects:

Code Objects
------------

.. index::
   builtin: compile
   single: func_code (function object attribute)

Code objects are used by the implementation to represent "pseudo-compiled"
executable Python code such as a function body. They differ from function
objects because they don't contain a reference to their global execution
environment.  Code objects are returned by the built-in :func:`compile` function
and can be extracted from function objects through their :attr:`func_code`
attribute. See also the :mod:`code` module.

.. index::
   statement: exec
   builtin: eval

A code object can be executed or evaluated by passing it (instead of a source
string) to the :keyword:`exec` statement or the built-in :func:`eval` function.

See :ref:`types` for more information.


.. _bltin-type-objects:

Type Objects
------------

.. index::
   builtin: type
   module: types

Type objects represent the various object types.  An object's type is accessed
by the built-in function :func:`type`.  There are no special operations on
types.  The standard module :mod:`types` defines names for all standard built-in
types.

Types are written like this: ``<type 'int'>``.


.. _bltin-null-object:

The Null Object
---------------

This object is returned by functions that don't explicitly return a value.  It
supports no special operations.  There is exactly one null object, named
``None`` (a built-in name).

It is written as ``None``.


.. _bltin-ellipsis-object:

The Ellipsis Object
-------------------

This object is used by extended slice notation (see :ref:`slicings`).  It
supports no special operations.  There is exactly one ellipsis object, named
:const:`Ellipsis` (a built-in name).

It is written as ``Ellipsis``.  When in a subscript, it can also be written as
``...``, for example ``seq[...]``.


The NotImplemented Object
-------------------------

This object is returned from comparisons and binary operations when they are
asked to operate on types they don't support. See :ref:`comparisons` for more
information.

It is written as ``NotImplemented``.


Boolean Values
--------------

Boolean values are the two constant objects ``False`` and ``True``.  They are
used to represent truth values (although other values can also be considered
false or true).  In numeric contexts (for example when used as the argument to
an arithmetic operator), they behave like the integers 0 and 1, respectively.
The built-in function :func:`bool` can be used to convert any value to a
Boolean, if the value can be interpreted as a truth value (see section
:ref:`truth` above).

.. index::
   single: False
   single: True
   pair: Boolean; values

They are written as ``False`` and ``True``, respectively.


.. _typesinternal:

Internal Objects
----------------

See :ref:`types` for this information.  It describes stack frame objects,
traceback objects, and slice objects.


.. _specialattrs:

Special Attributes
==================

The implementation adds a few special read-only attributes to several object
types, where they are relevant.  Some of these are not reported by the
:func:`dir` built-in function.


.. attribute:: object.__dict__

   A dictionary or other mapping object used to store an object's (writable)
   attributes.


.. attribute:: object.__methods__

   .. deprecated:: 2.2
      Use the built-in function :func:`dir` to get a list of an object's attributes.
      This attribute is no longer available.


.. attribute:: object.__members__

   .. deprecated:: 2.2
      Use the built-in function :func:`dir` to get a list of an object's attributes.
      This attribute is no longer available.


.. attribute:: instance.__class__

   The class to which a class instance belongs.


.. attribute:: class.__bases__

   The tuple of base classes of a class object.


.. attribute:: definition.__name__

   The name of the class, type, function, method, descriptor, or
   generator instance.


The following attributes are only supported by :term:`new-style class`\ es.

.. attribute:: class.__mro__

   This attribute is a tuple of classes that are considered when looking for
   base classes during method resolution.


.. method:: class.mro()

   This method can be overridden by a metaclass to customize the method
   resolution order for its instances.  It is called at class instantiation, and
   its result is stored in :attr:`~class.__mro__`.


.. method:: class.__subclasses__

   Each new-style class keeps a list of weak references to its immediate
   subclasses.  This method returns a list of all those references still alive.
   Example::

      >>> int.__subclasses__()
      [<type 'bool'>]


.. rubric:: Footnotes

.. [1] Additional information on these special methods may be found in the Python
   Reference Manual (:ref:`customization`).

.. [2] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
   similarly for tuples.

.. [3] They must have since the parser can't tell the type of the operands.

.. [4] Cased characters are those with general category property being one of
   "Lu" (Letter, uppercase), "Ll" (Letter, lowercase), or "Lt" (Letter, titlecase).

.. [5] To format only a tuple you should therefore provide a singleton tuple whose only
   element is the tuple to be formatted.

.. [6] The advantage of leaving the newline on is that returning an empty string is
   then an unambiguous EOF indication.  It is also possible (in cases where it
   might matter, for example, if you want to make an exact copy of a file while
   scanning its lines) to tell whether the last line of a file ended in a newline
   or not (yes this happens!).
PK
%�\�8S�5�5�$html/_sources/library/string.rst.txtnu�[���:mod:`string` --- Common string operations
==========================================

.. module:: string
   :synopsis: Common string operations.


.. index:: module: re

**Source code:** :source:`Lib/string.py`

--------------

The :mod:`string` module contains a number of useful constants and
classes, as well as some deprecated legacy functions that are also
available as methods on strings. In addition, Python's built-in string
classes support the sequence type methods described in the
:ref:`typesseq` section, and also the string-specific methods described
in the :ref:`string-methods` section. To output formatted strings use
template strings or the ``%`` operator described in the
:ref:`string-formatting` section. Also, see the :mod:`re` module for
string functions based on regular expressions.

String constants
----------------

The constants defined in this module are:


.. data:: ascii_letters

   The concatenation of the :const:`ascii_lowercase` and :const:`ascii_uppercase`
   constants described below.  This value is not locale-dependent.


.. data:: ascii_lowercase

   The lowercase letters ``'abcdefghijklmnopqrstuvwxyz'``.  This value is not
   locale-dependent and will not change.


.. data:: ascii_uppercase

   The uppercase letters ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.  This value is not
   locale-dependent and will not change.


.. data:: digits

   The string ``'0123456789'``.


.. data:: hexdigits

   The string ``'0123456789abcdefABCDEF'``.


.. data:: letters

   The concatenation of the strings :const:`lowercase` and :const:`uppercase`
   described below.  The specific value is locale-dependent, and will be updated
   when :func:`locale.setlocale` is called.


.. data:: lowercase

   A string containing all the characters that are considered lowercase letters.
   On most systems this is the string ``'abcdefghijklmnopqrstuvwxyz'``.  The
   specific value is locale-dependent, and will be updated when
   :func:`locale.setlocale` is called.


.. data:: octdigits

   The string ``'01234567'``.


.. data:: punctuation

   String of ASCII characters which are considered punctuation characters in the
   ``C`` locale.


.. data:: printable

   String of characters which are considered printable.  This is a combination of
   :const:`digits`, :const:`letters`, :const:`punctuation`, and
   :const:`whitespace`.


.. data:: uppercase

   A string containing all the characters that are considered uppercase letters.
   On most systems this is the string ``'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.  The
   specific value is locale-dependent, and will be updated when
   :func:`locale.setlocale` is called.


.. data:: whitespace

   A string containing all characters that are considered whitespace. On most
   systems this includes the characters space, tab, linefeed, return, formfeed, and
   vertical tab.


.. _new-string-formatting:

Custom String Formatting
------------------------

.. versionadded:: 2.6

The built-in str and unicode classes provide the ability
to do complex variable substitutions and value formatting via the
:meth:`str.format` method described in :pep:`3101`.  The :class:`Formatter`
class in the :mod:`string` module allows you to create and customize your own
string formatting behaviors using the same implementation as the built-in
:meth:`~str.format` method.

.. class:: Formatter

   The :class:`Formatter` class has the following public methods:

   .. method:: format(format_string, *args, **kwargs)

      The primary API method.  It takes a format string and
      an arbitrary set of positional and keyword arguments.
      It is just a wrapper that calls :meth:`vformat`.

   .. method:: vformat(format_string, args, kwargs)

      This function does the actual work of formatting.  It is exposed as a
      separate function for cases where you want to pass in a predefined
      dictionary of arguments, rather than unpacking and repacking the
      dictionary as individual arguments using the ``*args`` and ``**kwargs``
      syntax.  :meth:`vformat` does the work of breaking up the format string
      into character data and replacement fields.  It calls the various
      methods described below.

   In addition, the :class:`Formatter` defines a number of methods that are
   intended to be replaced by subclasses:

   .. method:: parse(format_string)

      Loop over the format_string and return an iterable of tuples
      (*literal_text*, *field_name*, *format_spec*, *conversion*).  This is used
      by :meth:`vformat` to break the string into either literal text, or
      replacement fields.

      The values in the tuple conceptually represent a span of literal text
      followed by a single replacement field.  If there is no literal text
      (which can happen if two replacement fields occur consecutively), then
      *literal_text* will be a zero-length string.  If there is no replacement
      field, then the values of *field_name*, *format_spec* and *conversion*
      will be ``None``.

   .. method:: get_field(field_name, args, kwargs)

      Given *field_name* as returned by :meth:`parse` (see above), convert it to
      an object to be formatted.  Returns a tuple (obj, used_key).  The default
      version takes strings of the form defined in :pep:`3101`, such as
      "0[name]" or "label.title".  *args* and *kwargs* are as passed in to
      :meth:`vformat`.  The return value *used_key* has the same meaning as the
      *key* parameter to :meth:`get_value`.

   .. method:: get_value(key, args, kwargs)

      Retrieve a given field value.  The *key* argument will be either an
      integer or a string.  If it is an integer, it represents the index of the
      positional argument in *args*; if it is a string, then it represents a
      named argument in *kwargs*.

      The *args* parameter is set to the list of positional arguments to
      :meth:`vformat`, and the *kwargs* parameter is set to the dictionary of
      keyword arguments.

      For compound field names, these functions are only called for the first
      component of the field name; Subsequent components are handled through
      normal attribute and indexing operations.

      So for example, the field expression '0.name' would cause
      :meth:`get_value` to be called with a *key* argument of 0.  The ``name``
      attribute will be looked up after :meth:`get_value` returns by calling the
      built-in :func:`getattr` function.

      If the index or keyword refers to an item that does not exist, then an
      :exc:`IndexError` or :exc:`KeyError` should be raised.

   .. method:: check_unused_args(used_args, args, kwargs)

      Implement checking for unused arguments if desired.  The arguments to this
      function is the set of all argument keys that were actually referred to in
      the format string (integers for positional arguments, and strings for
      named arguments), and a reference to the *args* and *kwargs* that was
      passed to vformat.  The set of unused args can be calculated from these
      parameters.  :meth:`check_unused_args` is assumed to raise an exception if
      the check fails.

   .. method:: format_field(value, format_spec)

      :meth:`format_field` simply calls the global :func:`format` built-in.  The
      method is provided so that subclasses can override it.

   .. method:: convert_field(value, conversion)

      Converts the value (returned by :meth:`get_field`) given a conversion type
      (as in the tuple returned by the :meth:`parse` method).  The default
      version understands 's' (str), 'r' (repr) and 'a' (ascii) conversion
      types.


.. _formatstrings:

Format String Syntax
--------------------

The :meth:`str.format` method and the :class:`Formatter` class share the same
syntax for format strings (although in the case of :class:`Formatter`,
subclasses can define their own format string syntax).

Format strings contain "replacement fields" surrounded by curly braces ``{}``.
Anything that is not contained in braces is considered literal text, which is
copied unchanged to the output.  If you need to include a brace character in the
literal text, it can be escaped by doubling: ``{{`` and ``}}``.

The grammar for a replacement field is as follows:

   .. productionlist:: sf
      replacement_field: "{" [`field_name`] ["!" `conversion`] [":" `format_spec`] "}"
      field_name: arg_name ("." `attribute_name` | "[" `element_index` "]")*
      arg_name: [`identifier` | `integer`]
      attribute_name: `identifier`
      element_index: `integer` | `index_string`
      index_string: <any source character except "]"> +
      conversion: "r" | "s"
      format_spec: <described in the next section>

In less formal terms, the replacement field can start with a *field_name* that specifies
the object whose value is to be formatted and inserted
into the output instead of the replacement field.
The *field_name* is optionally followed by a  *conversion* field, which is
preceded by an exclamation point ``'!'``, and a *format_spec*, which is preceded
by a colon ``':'``.  These specify a non-default format for the replacement value.

See also the :ref:`formatspec` section.

The *field_name* itself begins with an *arg_name* that is either a number or a
keyword.  If it's a number, it refers to a positional argument, and if it's a keyword,
it refers to a named keyword argument.  If the numerical arg_names in a format string
are 0, 1, 2, ... in sequence, they can all be omitted (not just some)
and the numbers 0, 1, 2, ... will be automatically inserted in that order.
Because *arg_name* is not quote-delimited, it is not possible to specify arbitrary
dictionary keys (e.g., the strings ``'10'`` or ``':-]'``) within a format string.
The *arg_name* can be followed by any number of index or
attribute expressions. An expression of the form ``'.name'`` selects the named
attribute using :func:`getattr`, while an expression of the form ``'[index]'``
does an index lookup using :func:`__getitem__`.

.. versionchanged:: 2.7
   The positional argument specifiers can be omitted for :meth:`str.format` and
   :meth:`unicode.format`, so ``'{} {}'`` is equivalent to ``'{0} {1}'``,
   ``u'{} {}'`` is equivalent to ``u'{0} {1}'``.

Some simple format string examples::

   "First, thou shalt count to {0}"  # References first positional argument
   "Bring me a {}"                   # Implicitly references the first positional argument
   "From {} to {}"                   # Same as "From {0} to {1}"
   "My quest is {name}"              # References keyword argument 'name'
   "Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
   "Units destroyed: {players[0]}"   # First element of keyword argument 'players'.

The *conversion* field causes a type coercion before formatting.  Normally, the
job of formatting a value is done by the :meth:`__format__` method of the value
itself.  However, in some cases it is desirable to force a type to be formatted
as a string, overriding its own definition of formatting.  By converting the
value to a string before calling :meth:`__format__`, the normal formatting logic
is bypassed.

Two conversion flags are currently supported: ``'!s'`` which calls :func:`str`
on the value, and ``'!r'`` which calls :func:`repr`.

Some examples::

   "Harold's a clever {0!s}"        # Calls str() on the argument first
   "Bring out the holy {name!r}"    # Calls repr() on the argument first

The *format_spec* field contains a specification of how the value should be
presented, including such details as field width, alignment, padding, decimal
precision and so on.  Each value type can define its own "formatting
mini-language" or interpretation of the *format_spec*.

Most built-in types support a common formatting mini-language, which is
described in the next section.

A *format_spec* field can also include nested replacement fields within it.
These nested replacement fields may contain a field name, conversion flag
and format specification, but deeper nesting is
not allowed.  The replacement fields within the
format_spec are substituted before the *format_spec* string is interpreted.
This allows the formatting of a value to be dynamically specified.

See the :ref:`formatexamples` section for some examples.


.. _formatspec:

Format Specification Mini-Language
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see
:ref:`formatstrings`).  They can also be passed directly to the built-in
:func:`format` function.  Each formattable type may define how the format
specification is to be interpreted.

Most built-in types implement the following options for format specifications,
although some of the formatting options are only supported by the numeric types.

A general convention is that an empty format string (``""``) produces
the same result as if you had called :func:`str` on the value. A
non-empty format string typically modifies the result.

The general form of a *standard format specifier* is:

.. productionlist:: sf
   format_spec: [[`fill`]`align`][`sign`][#][0][`width`][,][.`precision`][`type`]
   fill: <any character>
   align: "<" | ">" | "=" | "^"
   sign: "+" | "-" | " "
   width: `integer`
   precision: `integer`
   type: "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

If a valid *align* value is specified, it can be preceded by a *fill*
character that can be any character and defaults to a space if omitted.
It is not possible to use a literal curly brace ("``{``" or "``}``") as
the *fill* character when using the :meth:`str.format`
method.  However, it is possible to insert a curly brace
with a nested replacement field.  This limitation doesn't
affect the :func:`format` function.

The meaning of the various alignment options is as follows:

   +---------+----------------------------------------------------------+
   | Option  | Meaning                                                  |
   +=========+==========================================================+
   | ``'<'`` | Forces the field to be left-aligned within the available |
   |         | space (this is the default for most objects).            |
   +---------+----------------------------------------------------------+
   | ``'>'`` | Forces the field to be right-aligned within the          |
   |         | available space (this is the default for numbers).       |
   +---------+----------------------------------------------------------+
   | ``'='`` | Forces the padding to be placed after the sign (if any)  |
   |         | but before the digits.  This is used for printing fields |
   |         | in the form '+000000120'. This alignment option is only  |
   |         | valid for numeric types.  It becomes the default when '0'|
   |         | immediately precedes the field width.                    |
   +---------+----------------------------------------------------------+
   | ``'^'`` | Forces the field to be centered within the available     |
   |         | space.                                                   |
   +---------+----------------------------------------------------------+

Note that unless a minimum field width is defined, the field width will always
be the same size as the data to fill it, so that the alignment option has no
meaning in this case.

The *sign* option is only valid for number types, and can be one of the
following:

   +---------+----------------------------------------------------------+
   | Option  | Meaning                                                  |
   +=========+==========================================================+
   | ``'+'`` | indicates that a sign should be used for both            |
   |         | positive as well as negative numbers.                    |
   +---------+----------------------------------------------------------+
   | ``'-'`` | indicates that a sign should be used only for negative   |
   |         | numbers (this is the default behavior).                  |
   +---------+----------------------------------------------------------+
   | space   | indicates that a leading space should be used on         |
   |         | positive numbers, and a minus sign on negative numbers.  |
   +---------+----------------------------------------------------------+

The ``'#'`` option is only valid for integers, and only for binary, octal, or
hexadecimal output.  If present, it specifies that the output will be prefixed
by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.

The ``','`` option signals the use of a comma for a thousands separator.
For a locale aware separator, use the ``'n'`` integer presentation type
instead.

.. versionchanged:: 2.7
   Added the ``','`` option (see also :pep:`378`).

*width* is a decimal integer defining the minimum field width.  If not
specified, then the field width will be determined by the content.

When no explicit alignment is given, preceding the *width* field by a zero
(``'0'``) character enables
sign-aware zero-padding for numeric types.  This is equivalent to a *fill*
character of ``'0'`` with an *alignment* type of ``'='``.

The *precision* is a decimal number indicating how many digits should be
displayed after the decimal point for a floating point value formatted with
``'f'`` and ``'F'``, or before and after the decimal point for a floating point
value formatted with ``'g'`` or ``'G'``.  For non-number types the field
indicates the maximum field size - in other words, how many characters will be
used from the field content. The *precision* is not allowed for integer values.

Finally, the *type* determines how the data should be presented.

The available string presentation types are:

   +---------+----------------------------------------------------------+
   | Type    | Meaning                                                  |
   +=========+==========================================================+
   | ``'s'`` | String format. This is the default type for strings and  |
   |         | may be omitted.                                          |
   +---------+----------------------------------------------------------+
   | None    | The same as ``'s'``.                                     |
   +---------+----------------------------------------------------------+

The available integer presentation types are:

   +---------+----------------------------------------------------------+
   | Type    | Meaning                                                  |
   +=========+==========================================================+
   | ``'b'`` | Binary format. Outputs the number in base 2.             |
   +---------+----------------------------------------------------------+
   | ``'c'`` | Character. Converts the integer to the corresponding     |
   |         | unicode character before printing.                       |
   +---------+----------------------------------------------------------+
   | ``'d'`` | Decimal Integer. Outputs the number in base 10.          |
   +---------+----------------------------------------------------------+
   | ``'o'`` | Octal format. Outputs the number in base 8.              |
   +---------+----------------------------------------------------------+
   | ``'x'`` | Hex format. Outputs the number in base 16, using lower-  |
   |         | case letters for the digits above 9.                     |
   +---------+----------------------------------------------------------+
   | ``'X'`` | Hex format. Outputs the number in base 16, using upper-  |
   |         | case letters for the digits above 9.                     |
   +---------+----------------------------------------------------------+
   | ``'n'`` | Number. This is the same as ``'d'``, except that it uses |
   |         | the current locale setting to insert the appropriate     |
   |         | number separator characters.                             |
   +---------+----------------------------------------------------------+
   | None    | The same as ``'d'``.                                     |
   +---------+----------------------------------------------------------+

In addition to the above presentation types, integers can be formatted
with the floating point presentation types listed below (except
``'n'`` and ``None``). When doing so, :func:`float` is used to convert the
integer to a floating point number before formatting.

The available presentation types for floating point and decimal values are:

   +---------+----------------------------------------------------------+
   | Type    | Meaning                                                  |
   +=========+==========================================================+
   | ``'e'`` | Exponent notation. Prints the number in scientific       |
   |         | notation using the letter 'e' to indicate the exponent.  |
   |         | The default precision is ``6``.                          |
   +---------+----------------------------------------------------------+
   | ``'E'`` | Exponent notation. Same as ``'e'`` except it uses an     |
   |         | upper case 'E' as the separator character.               |
   +---------+----------------------------------------------------------+
   | ``'f'`` | Fixed-point notation. Displays the number as a           |
   |         | fixed-point number.  The default precision is ``6``.     |
   +---------+----------------------------------------------------------+
   | ``'F'`` | Fixed point notation. Same as ``'f'``.                   |
   +---------+----------------------------------------------------------+
   | ``'g'`` | General format.  For a given precision ``p >= 1``,       |
   |         | this rounds the number to ``p`` significant digits and   |
   |         | then formats the result in either fixed-point format     |
   |         | or in scientific notation, depending on its magnitude.   |
   |         |                                                          |
   |         | The precise rules are as follows: suppose that the       |
   |         | result formatted with presentation type ``'e'`` and      |
   |         | precision ``p-1`` would have exponent ``exp``.  Then     |
   |         | if ``-4 <= exp < p``, the number is formatted            |
   |         | with presentation type ``'f'`` and precision             |
   |         | ``p-1-exp``.  Otherwise, the number is formatted         |
   |         | with presentation type ``'e'`` and precision ``p-1``.    |
   |         | In both cases insignificant trailing zeros are removed   |
   |         | from the significand, and the decimal point is also      |
   |         | removed if there are no remaining digits following it.   |
   |         |                                                          |
   |         | Positive and negative infinity, positive and negative    |
   |         | zero, and nans, are formatted as ``inf``, ``-inf``,      |
   |         | ``0``, ``-0`` and ``nan`` respectively, regardless of    |
   |         | the precision.                                           |
   |         |                                                          |
   |         | A precision of ``0`` is treated as equivalent to a       |
   |         | precision of ``1``.  The default precision is ``6``.     |
   +---------+----------------------------------------------------------+
   | ``'G'`` | General format. Same as ``'g'`` except switches to       |
   |         | ``'E'`` if the number gets too large. The                |
   |         | representations of infinity and NaN are uppercased, too. |
   +---------+----------------------------------------------------------+
   | ``'n'`` | Number. This is the same as ``'g'``, except that it uses |
   |         | the current locale setting to insert the appropriate     |
   |         | number separator characters.                             |
   +---------+----------------------------------------------------------+
   | ``'%'`` | Percentage. Multiplies the number by 100 and displays    |
   |         | in fixed (``'f'``) format, followed by a percent sign.   |
   +---------+----------------------------------------------------------+
   | None    | The same as ``'g'``.                                     |
   +---------+----------------------------------------------------------+



.. _formatexamples:

Format examples
^^^^^^^^^^^^^^^

This section contains examples of the :meth:`str.format` syntax and
comparison with the old ``%``-formatting.

In most of the cases the syntax is similar to the old ``%``-formatting, with the
addition of the ``{}`` and with ``:`` used instead of ``%``.
For example, ``'%03.2f'`` can be translated to ``'{:03.2f}'``.

The new format syntax also supports new and different options, shown in the
following examples.

Accessing arguments by position::

   >>> '{0}, {1}, {2}'.format('a', 'b', 'c')
   'a, b, c'
   >>> '{}, {}, {}'.format('a', 'b', 'c')  # 2.7+ only
   'a, b, c'
   >>> '{2}, {1}, {0}'.format('a', 'b', 'c')
   'c, b, a'
   >>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
   'c, b, a'
   >>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
   'abracadabra'

Accessing arguments by name::

   >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
   'Coordinates: 37.24N, -115.81W'
   >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}
   >>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
   'Coordinates: 37.24N, -115.81W'

Accessing arguments' attributes::

   >>> c = 3-5j
   >>> ('The complex number {0} is formed from the real part {0.real} '
   ...  'and the imaginary part {0.imag}.').format(c)
   'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
   >>> class Point(object):
   ...     def __init__(self, x, y):
   ...         self.x, self.y = x, y
   ...     def __str__(self):
   ...         return 'Point({self.x}, {self.y})'.format(self=self)
   ...
   >>> str(Point(4, 2))
   'Point(4, 2)'


Accessing arguments' items::

   >>> coord = (3, 5)
   >>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
   'X: 3;  Y: 5'

Replacing ``%s`` and ``%r``::

   >>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
   "repr() shows quotes: 'test1'; str() doesn't: test2"

Aligning the text and specifying a width::

   >>> '{:<30}'.format('left aligned')
   'left aligned                  '
   >>> '{:>30}'.format('right aligned')
   '                 right aligned'
   >>> '{:^30}'.format('centered')
   '           centered           '
   >>> '{:*^30}'.format('centered')  # use '*' as a fill char
   '***********centered***********'

Replacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign::

   >>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always
   '+3.140000; -3.140000'
   >>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers
   ' 3.140000; -3.140000'
   >>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'
   '3.140000; -3.140000'

Replacing ``%x`` and ``%o`` and converting the value to different bases::

   >>> # format also supports binary numbers
   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
   'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
   >>> # with 0x, 0o, or 0b as prefix:
   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
   'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

Using the comma as a thousands separator::

   >>> '{:,}'.format(1234567890)
   '1,234,567,890'

Expressing a percentage::

   >>> points = 19.5
   >>> total = 22
   >>> 'Correct answers: {:.2%}'.format(points/total)
   'Correct answers: 88.64%'

Using type-specific formatting::

   >>> import datetime
   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
   >>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
   '2010-07-04 12:15:58'

Nesting arguments and more complex examples::

   >>> for align, text in zip('<^>', ['left', 'center', 'right']):
   ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
   ...
   'left<<<<<<<<<<<<'
   '^^^^^center^^^^^'
   '>>>>>>>>>>>right'
   >>>
   >>> octets = [192, 168, 0, 1]
   >>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
   'C0A80001'
   >>> int(_, 16)
   3232235521
   >>>
   >>> width = 5
   >>> for num in range(5,12):
   ...     for base in 'dXob':
   ...         print '{0:{width}{base}}'.format(num, base=base, width=width),
   ...     print
   ...
       5     5     5   101
       6     6     6   110
       7     7     7   111
       8     8    10  1000
       9     9    11  1001
      10     A    12  1010
      11     B    13  1011



Template strings
----------------

.. versionadded:: 2.4

Templates provide simpler string substitutions as described in :pep:`292`.
Instead of the normal ``%``\ -based substitutions, Templates support ``$``\
-based substitutions, using the following rules:

* ``$$`` is an escape; it is replaced with a single ``$``.

* ``$identifier`` names a substitution placeholder matching a mapping key of
  ``"identifier"``.  By default, ``"identifier"`` must spell a Python
  identifier.  The first non-identifier character after the ``$`` character
  terminates this placeholder specification.

* ``${identifier}`` is equivalent to ``$identifier``.  It is required when valid
  identifier characters follow the placeholder but are not part of the
  placeholder, such as ``"${noun}ification"``.

Any other appearance of ``$`` in the string will result in a :exc:`ValueError`
being raised.

The :mod:`string` module provides a :class:`Template` class that implements
these rules.  The methods of :class:`Template` are:


.. class:: Template(template)

   The constructor takes a single argument which is the template string.


   .. method:: substitute(mapping[, **kws])

      Performs the template substitution, returning a new string.  *mapping* is
      any dictionary-like object with keys that match the placeholders in the
      template.  Alternatively, you can provide keyword arguments, where the
      keywords are the placeholders.  When both *mapping* and *kws* are given
      and there are duplicates, the placeholders from *kws* take precedence.


   .. method:: safe_substitute(mapping[, **kws])

      Like :meth:`substitute`, except that if placeholders are missing from
      *mapping* and *kws*, instead of raising a :exc:`KeyError` exception, the
      original placeholder will appear in the resulting string intact.  Also,
      unlike with :meth:`substitute`, any other appearances of the ``$`` will
      simply return ``$`` instead of raising :exc:`ValueError`.

      While other exceptions may still occur, this method is called "safe"
      because it always tries to return a usable string instead of
      raising an exception.  In another sense, :meth:`safe_substitute` may be
      anything other than safe, since it will silently ignore malformed
      templates containing dangling delimiters, unmatched braces, or
      placeholders that are not valid Python identifiers.

   :class:`Template` instances also provide one public data attribute:

   .. attribute:: template

      This is the object passed to the constructor's *template* argument.  In
      general, you shouldn't change it, but read-only access is not enforced.

Here is an example of how to use a Template::

   >>> from string import Template
   >>> s = Template('$who likes $what')
   >>> s.substitute(who='tim', what='kung pao')
   'tim likes kung pao'
   >>> d = dict(who='tim')
   >>> Template('Give $who $100').substitute(d)
   Traceback (most recent call last):
   ...
   ValueError: Invalid placeholder in string: line 1, col 11
   >>> Template('$who likes $what').substitute(d)
   Traceback (most recent call last):
   ...
   KeyError: 'what'
   >>> Template('$who likes $what').safe_substitute(d)
   'tim likes $what'

Advanced usage: you can derive subclasses of :class:`Template` to customize the
placeholder syntax, delimiter character, or the entire regular expression used
to parse template strings.  To do this, you can override these class attributes:

* *delimiter* -- This is the literal string describing a placeholder introducing
  delimiter.  The default value is ``$``.  Note that this should *not* be a
  regular expression, as the implementation will call :meth:`re.escape` on this
  string as needed.

* *idpattern* -- This is the regular expression describing the pattern for
  non-braced placeholders (the braces will be added automatically as
  appropriate).  The default value is the regular expression
  ``[_a-z][_a-z0-9]*``.

Alternatively, you can provide the entire regular expression pattern by
overriding the class attribute *pattern*.  If you do this, the value must be a
regular expression object with four named capturing groups.  The capturing
groups correspond to the rules given above, along with the invalid placeholder
rule:

* *escaped* -- This group matches the escape sequence, e.g. ``$$``, in the
  default pattern.

* *named* -- This group matches the unbraced placeholder name; it should not
  include the delimiter in capturing group.

* *braced* -- This group matches the brace enclosed placeholder name; it should
  not include either the delimiter or braces in the capturing group.

* *invalid* -- This group matches any other delimiter pattern (usually a single
  delimiter), and it should appear last in the regular expression.


String functions
----------------

The following functions are available to operate on string and Unicode objects.
They are not available as string methods.


.. function:: capwords(s[, sep])

   Split the argument into words using :meth:`str.split`, capitalize each word
   using :meth:`str.capitalize`, and join the capitalized words using
   :meth:`str.join`.  If the optional second argument *sep* is absent
   or ``None``, runs of whitespace characters are replaced by a single space
   and leading and trailing whitespace are removed, otherwise *sep* is used to
   split and join the words.


.. function:: maketrans(from, to)

   Return a translation table suitable for passing to :func:`translate`, that will
   map each character in *from* into the character at the same position in *to*;
   *from* and *to* must have the same length.

   .. note::

      Don't use strings derived from :const:`lowercase` and :const:`uppercase` as
      arguments; in some locales, these don't have the same length.  For case
      conversions, always use :meth:`str.lower` and :meth:`str.upper`.


Deprecated string functions
---------------------------

The following list of functions are also defined as methods of string and
Unicode objects; see section :ref:`string-methods` for more information on
those.  You should consider these functions as deprecated, although they will
not be removed until Python 3.  The functions defined in this module are:


.. function:: atof(s)

   .. deprecated:: 2.0
      Use the :func:`float` built-in function.

   .. index:: builtin: float

   Convert a string to a floating point number.  The string must have the standard
   syntax for a floating point literal in Python, optionally preceded by a sign
   (``+`` or ``-``).  Note that this behaves identical to the built-in function
   :func:`float` when passed a string.

   .. note::

      .. index::
         single: NaN
         single: Infinity

      When passing in a string, values for NaN and Infinity may be returned, depending
      on the underlying C library.  The specific set of strings accepted which cause
      these values to be returned depends entirely on the C library and is known to
      vary.


.. function:: atoi(s[, base])

   .. deprecated:: 2.0
      Use the :func:`int` built-in function.

   .. index:: builtin: eval

   Convert string *s* to an integer in the given *base*.  The string must consist
   of one or more digits, optionally preceded by a sign (``+`` or ``-``).  The
   *base* defaults to 10.  If it is 0, a default base is chosen depending on the
   leading characters of the string (after stripping the sign): ``0x`` or ``0X``
   means 16, ``0`` means 8, anything else means 10.  If *base* is 16, a leading
   ``0x`` or ``0X`` is always accepted, though not required.  This behaves
   identically to the built-in function :func:`int` when passed a string.  (Also
   note: for a more flexible interpretation of numeric literals, use the built-in
   function :func:`eval`.)


.. function:: atol(s[, base])

   .. deprecated:: 2.0
      Use the :func:`long` built-in function.

   .. index:: builtin: long

   Convert string *s* to a long integer in the given *base*. The string must
   consist of one or more digits, optionally preceded by a sign (``+`` or ``-``).
   The *base* argument has the same meaning as for :func:`atoi`.  A trailing ``l``
   or ``L`` is not allowed, except if the base is 0.  Note that when invoked
   without *base* or with *base* set to 10, this behaves identical to the built-in
   function :func:`long` when passed a string.


.. function:: capitalize(word)

   Return a copy of *word* with only its first character capitalized.


.. function:: expandtabs(s[, tabsize])

   Expand tabs in a string replacing them by one or more spaces, depending on the
   current column and the given tab size.  The column number is reset to zero after
   each newline occurring in the string. This doesn't understand other non-printing
   characters or escape sequences.  The tab size defaults to 8.


.. function:: find(s, sub[, start[,end]])

   Return the lowest index in *s* where the substring *sub* is found such that
   *sub* is wholly contained in ``s[start:end]``.  Return ``-1`` on failure.
   Defaults for *start* and *end* and interpretation of negative values is the same
   as for slices.


.. function:: rfind(s, sub[, start[, end]])

   Like :func:`find` but find the highest index.


.. function:: index(s, sub[, start[, end]])

   Like :func:`find` but raise :exc:`ValueError` when the substring is not found.


.. function:: rindex(s, sub[, start[, end]])

   Like :func:`rfind` but raise :exc:`ValueError` when the substring is not found.


.. function:: count(s, sub[, start[, end]])

   Return the number of (non-overlapping) occurrences of substring *sub* in string
   ``s[start:end]``. Defaults for *start* and *end* and interpretation of negative
   values are the same as for slices.


.. function:: lower(s)

   Return a copy of *s*, but with upper case letters converted to lower case.


.. function:: split(s[, sep[, maxsplit]])

   Return a list of the words of the string *s*.  If the optional second argument
   *sep* is absent or ``None``, the words are separated by arbitrary strings of
   whitespace characters (space, tab, newline, return, formfeed).  If the second
   argument *sep* is present and not ``None``, it specifies a string to be used as
   the  word separator.  The returned list will then have one more item than the
   number of non-overlapping occurrences of the separator in the string.
   If *maxsplit* is given, at most *maxsplit* number of splits occur, and the
   remainder of the string is returned as the final element of the list (thus,
   the list will have at most ``maxsplit+1`` elements).  If *maxsplit* is not
   specified or ``-1``, then there is no limit on the number of splits (all
   possible splits are made).

   The behavior of split on an empty string depends on the value of *sep*. If *sep*
   is not specified, or specified as ``None``, the result will be an empty list.
   If *sep* is specified as any string, the result will be a list containing one
   element which is an empty string.


.. function:: rsplit(s[, sep[, maxsplit]])

   Return a list of the words of the string *s*, scanning *s* from the end.  To all
   intents and purposes, the resulting list of words is the same as returned by
   :func:`split`, except when the optional third argument *maxsplit* is explicitly
   specified and nonzero.  If *maxsplit* is given, at most *maxsplit* number of
   splits -- the *rightmost* ones -- occur, and the remainder of the string is
   returned as the first element of the list (thus, the list will have at most
   ``maxsplit+1`` elements).

   .. versionadded:: 2.4


.. function:: splitfields(s[, sep[, maxsplit]])

   This function behaves identically to :func:`split`.  (In the past, :func:`split`
   was only used with one argument, while :func:`splitfields` was only used with
   two arguments.)


.. function:: join(words[, sep])

   Concatenate a list or tuple of words with intervening occurrences of  *sep*.
   The default value for *sep* is a single space character.  It is always true that
   ``string.join(string.split(s, sep), sep)`` equals *s*.


.. function:: joinfields(words[, sep])

   This function behaves identically to :func:`join`.  (In the past,  :func:`join`
   was only used with one argument, while :func:`joinfields` was only used with two
   arguments.) Note that there is no :meth:`joinfields` method on string objects;
   use the :meth:`join` method instead.


.. function:: lstrip(s[, chars])

   Return a copy of the string with leading characters removed.  If *chars* is
   omitted or ``None``, whitespace characters are removed.  If given and not
   ``None``, *chars* must be a string; the characters in the string will be
   stripped from the beginning of the string this method is called on.

   .. versionchanged:: 2.2.3
      The *chars* parameter was added.  The *chars* parameter cannot be passed in
      earlier 2.2 versions.


.. function:: rstrip(s[, chars])

   Return a copy of the string with trailing characters removed.  If *chars* is
   omitted or ``None``, whitespace characters are removed.  If given and not
   ``None``, *chars* must be a string; the characters in the string will be
   stripped from the end of the string this method is called on.

   .. versionchanged:: 2.2.3
      The *chars* parameter was added.  The *chars* parameter cannot be passed in
      earlier 2.2 versions.


.. function:: strip(s[, chars])

   Return a copy of the string with leading and trailing characters removed.  If
   *chars* is omitted or ``None``, whitespace characters are removed.  If given and
   not ``None``, *chars* must be a string; the characters in the string will be
   stripped from the both ends of the string this method is called on.

   .. versionchanged:: 2.2.3
      The *chars* parameter was added.  The *chars* parameter cannot be passed in
      earlier 2.2 versions.


.. function:: swapcase(s)

   Return a copy of *s*, but with lower case letters converted to upper case and
   vice versa.


.. function:: translate(s, table[, deletechars])

   Delete all characters from *s* that are in *deletechars* (if  present), and then
   translate the characters using *table*, which  must be a 256-character string
   giving the translation for each character value, indexed by its ordinal.  If
   *table* is ``None``, then only the character deletion step is performed.


.. function:: upper(s)

   Return a copy of *s*, but with lower case letters converted to upper case.


.. function:: ljust(s, width[, fillchar])
              rjust(s, width[, fillchar])
              center(s, width[, fillchar])

   These functions respectively left-justify, right-justify and center a string in
   a field of given width.  They return a string that is at least *width*
   characters wide, created by padding the string *s* with the character *fillchar*
   (default is a space) until the given width on the right, left or both sides.
   The string is never truncated.


.. function:: zfill(s, width)

   Pad a numeric string *s* on the left with zero digits until the
   given *width* is reached.  Strings starting with a sign are handled
   correctly.


.. function:: replace(s, old, new[, maxreplace])

   Return a copy of string *s* with all occurrences of substring *old* replaced
   by *new*.  If the optional argument *maxreplace* is given, the first
   *maxreplace* occurrences are replaced.

PK
%�\
8QFF&html/_sources/library/stringio.rst.txtnu�[���
:mod:`StringIO` --- Read and write strings as files
===================================================

.. module:: StringIO
   :synopsis: Read and write strings as if they were files.


This module implements a file-like class, :class:`~StringIO.StringIO`, that reads and
writes a string buffer (also known as *memory files*).  See the description of
file objects for operations (section :ref:`bltin-file-objects`). (For
standard strings, see :class:`str` and :class:`unicode`.)


.. class:: StringIO([buffer])

   When a :class:`~StringIO.StringIO` object is created, it can be initialized to an existing
   string by passing the string to the constructor. If no string is given, the
   :class:`~StringIO.StringIO` will start empty. In both cases, the initial file position
   starts at zero.

   The :class:`~StringIO.StringIO` object can accept either Unicode or 8-bit strings, but
   mixing the two may take some care.  If both are used, 8-bit strings that cannot
   be interpreted as 7-bit ASCII (that use the 8th bit) will cause a
   :exc:`UnicodeError` to be raised when :meth:`getvalue` is called.

The following methods of :class:`~StringIO.StringIO` objects require special mention:


.. method:: StringIO.getvalue()

   Retrieve the entire contents of the "file" at any time before the
   :class:`~StringIO.StringIO` object's :meth:`close` method is called.  See the note above
   for information about mixing Unicode and 8-bit strings; such mixing can cause
   this method to raise :exc:`UnicodeError`.


.. method:: StringIO.close()

   Free the memory buffer.  Attempting to do further operations with a closed
   :class:`~StringIO.StringIO` object will raise a :exc:`ValueError`.

Example usage::

   import StringIO

   output = StringIO.StringIO()
   output.write('First line.\n')
   print >>output, 'Second line.'

   # Retrieve file contents -- this will be
   # 'First line.\nSecond line.\n'
   contents = output.getvalue()

   # Close object and discard memory buffer --
   # .getvalue() will now raise an exception.
   output.close()


:mod:`cStringIO` --- Faster version of :mod:`StringIO`
======================================================

.. module:: cStringIO
   :synopsis: Faster version of StringIO, but not subclassable.
.. moduleauthor:: Jim Fulton <jim@zope.com>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


The module :mod:`cStringIO` provides an interface similar to that of the
:mod:`StringIO` module.  Heavy use of :class:`StringIO.StringIO` objects can be
made more efficient by using the function :func:`StringIO` from this module
instead.


.. function:: StringIO([s])

   Return a StringIO-like stream for reading or writing.

   Since this is a factory function which returns objects of built-in types,
   there's no way to build your own version using subclassing.  It's not
   possible to set attributes on it.  Use the original :mod:`StringIO` module in
   those cases.

   Unlike the :mod:`StringIO` module, this module is not able to accept Unicode
   strings that cannot be encoded as plain ASCII strings.

   Another difference from the :mod:`StringIO` module is that calling
   :func:`StringIO` with a string parameter creates a read-only object. Unlike an
   object created without a string parameter, it does not have write methods.
   These objects are not generally visible.  They turn up in tracebacks as
   :class:`StringI` and :class:`StringO`.



The following data objects are provided as well:


.. data:: InputType

   The type object of the objects created by calling :func:`StringIO` with a string
   parameter.


.. data:: OutputType

   The type object of the objects returned by calling :func:`StringIO` with no
   parameters.

There is a C API to the module as well; refer to the module source for  more
information.

Example usage::

   import cStringIO

   output = cStringIO.StringIO()
   output.write('First line.\n')
   print >>output, 'Second line.'

   # Retrieve file contents -- this will be
   # 'First line.\nSecond line.\n'
   contents = output.getvalue()

   # Close object and discard memory buffer --
   # .getvalue() will now raise an exception.
   output.close()

PK
%�\�lЎ�(html/_sources/library/stringprep.rst.txtnu�[���
:mod:`stringprep` --- Internet String Preparation
=================================================

.. module:: stringprep
   :synopsis: String preparation, as per RFC 3453
.. moduleauthor:: Martin v. Löwis <martin@v.loewis.de>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.3

When identifying things (such as host names) in the internet, it is often
necessary to compare such identifications for "equality". Exactly how this
comparison is executed may depend on the application domain, e.g. whether it
should be case-insensitive or not. It may be also necessary to restrict the
possible identifications, to allow only identifications consisting of
"printable" characters.

:rfc:`3454` defines a procedure for "preparing" Unicode strings in internet
protocols. Before passing strings onto the wire, they are processed with the
preparation procedure, after which they have a certain normalized form. The RFC
defines a set of tables, which can be combined into profiles. Each profile must
define which tables it uses, and what other optional parts of the ``stringprep``
procedure are part of the profile. One example of a ``stringprep`` profile is
``nameprep``, which is used for internationalized domain names.

The module :mod:`stringprep` only exposes the tables from RFC 3454. As these
tables would be very large to represent them as dictionaries or lists, the
module uses the Unicode character database internally. The module source code
itself was generated using the ``mkstringprep.py`` utility.

As a result, these tables are exposed as functions, not as data structures.
There are two kinds of tables in the RFC: sets and mappings. For a set,
:mod:`stringprep` provides the "characteristic function", i.e. a function that
returns true if the parameter is part of the set. For mappings, it provides the
mapping function: given the key, it returns the associated value. Below is a
list of all functions available in the module.


.. function:: in_table_a1(code)

   Determine whether *code* is in tableA.1 (Unassigned code points in Unicode 3.2).


.. function:: in_table_b1(code)

   Determine whether *code* is in tableB.1 (Commonly mapped to nothing).


.. function:: map_table_b2(code)

   Return the mapped value for *code* according to tableB.2 (Mapping for
   case-folding used with NFKC).


.. function:: map_table_b3(code)

   Return the mapped value for *code* according to tableB.3 (Mapping for
   case-folding used with no normalization).


.. function:: in_table_c11(code)

   Determine whether *code* is in tableC.1.1  (ASCII space characters).


.. function:: in_table_c12(code)

   Determine whether *code* is in tableC.1.2  (Non-ASCII space characters).


.. function:: in_table_c11_c12(code)

   Determine whether *code* is in tableC.1  (Space characters, union of C.1.1 and
   C.1.2).


.. function:: in_table_c21(code)

   Determine whether *code* is in tableC.2.1  (ASCII control characters).


.. function:: in_table_c22(code)

   Determine whether *code* is in tableC.2.2  (Non-ASCII control characters).


.. function:: in_table_c21_c22(code)

   Determine whether *code* is in tableC.2  (Control characters, union of C.2.1 and
   C.2.2).


.. function:: in_table_c3(code)

   Determine whether *code* is in tableC.3  (Private use).


.. function:: in_table_c4(code)

   Determine whether *code* is in tableC.4  (Non-character code points).


.. function:: in_table_c5(code)

   Determine whether *code* is in tableC.5  (Surrogate codes).


.. function:: in_table_c6(code)

   Determine whether *code* is in tableC.6  (Inappropriate for plain text).


.. function:: in_table_c7(code)

   Determine whether *code* is in tableC.7  (Inappropriate for canonical
   representation).


.. function:: in_table_c8(code)

   Determine whether *code* is in tableC.8  (Change display properties or are
   deprecated).


.. function:: in_table_c9(code)

   Determine whether *code* is in tableC.9  (Tagging characters).


.. function:: in_table_d1(code)

   Determine whether *code* is in tableD.1  (Characters with bidirectional property
   "R" or "AL").


.. function:: in_table_d2(code)

   Determine whether *code* is in tableD.2  (Characters with bidirectional property
   "L").

PK
%�\�����%html/_sources/library/strings.rst.txtnu�[���
.. _stringservices:

***************
String Services
***************

The modules described in this chapter provide a wide range of string
manipulation operations.

In addition, Python's built-in string classes support the sequence type
methods described in the :ref:`typesseq` section, and also the
string-specific methods described in the :ref:`string-methods` section.
To output formatted strings use template strings or the ``%`` operator
described in the :ref:`string-formatting` section. Also, see the
:mod:`re` module for string functions based on regular expressions.


.. toctree::

   string.rst
   re.rst
   struct.rst
   difflib.rst
   stringio.rst
   textwrap.rst
   codecs.rst
   unicodedata.rst
   stringprep.rst
   fpformat.rst

PK
%�\٦� �B�B$html/_sources/library/struct.rst.txtnu�[���
:mod:`struct` --- Interpret strings as packed binary data
=========================================================

.. module:: struct
   :synopsis: Interpret strings as packed binary data.

.. index::
   pair: C; structures
   triple: packing; binary; data

This module performs conversions between Python values and C structs represented
as Python strings.  This can be used in handling binary data stored in files or
from network connections, among other sources.  It uses
:ref:`struct-format-strings` as compact descriptions of the layout of the C
structs and the intended conversion to/from Python values.

.. note::

   By default, the result of packing a given C struct includes pad bytes in
   order to maintain proper alignment for the C types involved; similarly,
   alignment is taken into account when unpacking.  This behavior is chosen so
   that the bytes of a packed struct correspond exactly to the layout in memory
   of the corresponding C struct.  To handle platform-independent data formats
   or omit implicit pad bytes, use ``standard`` size and alignment instead of
   ``native`` size and alignment: see :ref:`struct-alignment` for details.

Functions and Exceptions
------------------------

The module defines the following exception and functions:


.. exception:: error

   Exception raised on various occasions; argument is a string describing what
   is wrong.


.. function:: pack(fmt, v1, v2, ...)

   Return a string containing the values ``v1, v2, ...`` packed according to the
   given format.  The arguments must match the values required by the format
   exactly.


.. function:: pack_into(fmt, buffer, offset, v1, v2, ...)

   Pack the values ``v1, v2, ...`` according to the given format, write the
   packed bytes into the writable *buffer* starting at *offset*. Note that the
   offset is a required argument.

   .. versionadded:: 2.5


.. function:: unpack(fmt, string)

   Unpack the string (presumably packed by ``pack(fmt, ...)``) according to the
   given format.  The result is a tuple even if it contains exactly one item.
   The string must contain exactly the amount of data required by the format
   (``len(string)`` must equal ``calcsize(fmt)``).


.. function:: unpack_from(fmt, buffer[,offset=0])

   Unpack the *buffer* according to the given format. The result is a tuple even
   if it contains exactly one item. The *buffer* must contain at least the
   amount of data required by the format (``len(buffer[offset:])`` must be at
   least ``calcsize(fmt)``).

   .. versionadded:: 2.5


.. function:: calcsize(fmt)

   Return the size of the struct (and hence of the string) corresponding to the
   given format.

.. _struct-format-strings:

Format Strings
--------------

Format strings are the mechanism used to specify the expected layout when
packing and unpacking data.  They are built up from :ref:`format-characters`,
which specify the type of data being packed/unpacked.  In addition, there are
special characters for controlling the :ref:`struct-alignment`.


.. _struct-alignment:

Byte Order, Size, and Alignment
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

By default, C types are represented in the machine's native format and byte
order, and properly aligned by skipping pad bytes if necessary (according to the
rules used by the C compiler).

Alternatively, the first character of the format string can be used to indicate
the byte order, size and alignment of the packed data, according to the
following table:

+-----------+------------------------+----------+-----------+
| Character | Byte order             | Size     | Alignment |
+===========+========================+==========+===========+
| ``@``     | native                 | native   | native    |
+-----------+------------------------+----------+-----------+
| ``=``     | native                 | standard | none      |
+-----------+------------------------+----------+-----------+
| ``<``     | little-endian          | standard | none      |
+-----------+------------------------+----------+-----------+
| ``>``     | big-endian             | standard | none      |
+-----------+------------------------+----------+-----------+
| ``!``     | network (= big-endian) | standard | none      |
+-----------+------------------------+----------+-----------+

If the first character is not one of these, ``'@'`` is assumed.

Native byte order is big-endian or little-endian, depending on the host
system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
switchable endianness (bi-endian). Use ``sys.byteorder`` to check the
endianness of your system.

Native size and alignment are determined using the C compiler's
``sizeof`` expression.  This is always combined with native byte order.

Standard size depends only on the format character;  see the table in
the :ref:`format-characters` section.

Note the difference between ``'@'`` and ``'='``: both use native byte order, but
the size and alignment of the latter is standardized.

The form ``'!'`` is available for those poor souls who claim they can't remember
whether network byte order is big-endian or little-endian.

There is no way to indicate non-native byte order (force byte-swapping); use the
appropriate choice of ``'<'`` or ``'>'``.

Notes:

(1) Padding is only automatically added between successive structure members.
    No padding is added at the beginning or the end of the encoded struct.

(2) No padding is added when using non-native size and alignment, e.g.
    with '<', '>', '=', and '!'.

(3) To align the end of a structure to the alignment requirement of a
    particular type, end the format with the code for that type with a repeat
    count of zero.  See :ref:`struct-examples`.


.. _format-characters:

Format Characters
^^^^^^^^^^^^^^^^^

Format characters have the following meaning; the conversion between C and
Python values should be obvious given their types.  The 'Standard size' column
refers to the size of the packed value in bytes when using standard size; that
is, when the format string starts with one of ``'<'``, ``'>'``, ``'!'`` or
``'='``.  When using native size, the size of the packed value is
platform-dependent.

+--------+--------------------------+--------------------+----------------+------------+
| Format | C Type                   | Python type        | Standard size  | Notes      |
+========+==========================+====================+================+============+
| ``x``  | pad byte                 | no value           |                |            |
+--------+--------------------------+--------------------+----------------+------------+
| ``c``  | :c:type:`char`           | string of length 1 | 1              |            |
+--------+--------------------------+--------------------+----------------+------------+
| ``b``  | :c:type:`signed char`    | integer            | 1              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``B``  | :c:type:`unsigned char`  | integer            | 1              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``?``  | :c:type:`_Bool`          | bool               | 1              | \(1)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``h``  | :c:type:`short`          | integer            | 2              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``H``  | :c:type:`unsigned short` | integer            | 2              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``i``  | :c:type:`int`            | integer            | 4              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``I``  | :c:type:`unsigned int`   | integer            | 4              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``l``  | :c:type:`long`           | integer            | 4              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``L``  | :c:type:`unsigned long`  | integer            | 4              | \(3)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``q``  | :c:type:`long long`      | integer            | 8              | \(2), \(3) |
+--------+--------------------------+--------------------+----------------+------------+
| ``Q``  | :c:type:`unsigned long   | integer            | 8              | \(2), \(3) |
|        | long`                    |                    |                |            |
+--------+--------------------------+--------------------+----------------+------------+
| ``f``  | :c:type:`float`          | float              | 4              | \(4)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``d``  | :c:type:`double`         | float              | 8              | \(4)       |
+--------+--------------------------+--------------------+----------------+------------+
| ``s``  | :c:type:`char[]`         | string             |                |            |
+--------+--------------------------+--------------------+----------------+------------+
| ``p``  | :c:type:`char[]`         | string             |                |            |
+--------+--------------------------+--------------------+----------------+------------+
| ``P``  | :c:type:`void \*`        | integer            |                | \(5), \(3) |
+--------+--------------------------+--------------------+----------------+------------+

Notes:

(1)
   The ``'?'`` conversion code corresponds to the :c:type:`_Bool` type defined by
   C99. If this type is not available, it is simulated using a :c:type:`char`. In
   standard mode, it is always represented by one byte.

   .. versionadded:: 2.6

(2)
   The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
   the platform C compiler supports C :c:type:`long long`, or, on Windows,
   :c:type:`__int64`.  They are always available in standard modes.

   .. versionadded:: 2.2

(3)
   When attempting to pack a non-integer using any of the integer conversion
   codes, if the non-integer has a :meth:`__index__` method then that method is
   called to convert the argument to an integer before packing.  If no
   :meth:`__index__` method exists, or the call to :meth:`__index__` raises
   :exc:`TypeError`, then the :meth:`__int__` method is tried.  However, the use
   of :meth:`__int__` is deprecated, and will raise :exc:`DeprecationWarning`.

   .. versionchanged:: 2.7
      Use of the :meth:`__index__` method for non-integers is new in 2.7.

   .. versionchanged:: 2.7
      Prior to version 2.7, not all integer conversion codes would use the
      :meth:`__int__` method to convert, and :exc:`DeprecationWarning` was
      raised only for float arguments.

(4)
   For the ``'f'`` and ``'d'`` conversion codes, the packed representation uses
   the IEEE 754 binary32 (for ``'f'``) or binary64 (for ``'d'``) format,
   regardless of the floating-point format used by the platform.

(5)
   The ``'P'`` format character is only available for the native byte ordering
   (selected as the default or with the ``'@'`` byte order character). The byte
   order character ``'='`` chooses to use little- or big-endian ordering based
   on the host system. The struct module does not interpret this as native
   ordering, so the ``'P'`` format is not available.


A format character may be preceded by an integral repeat count.  For example,
the format string ``'4h'`` means exactly the same as ``'hhhh'``.

Whitespace characters between formats are ignored; a count and its format must
not contain whitespace though.

For the ``'s'`` format character, the count is interpreted as the size of the
string, not a repeat count like for the other format characters; for example,
``'10s'`` means a single 10-byte string, while ``'10c'`` means 10 characters.
If a count is not given, it defaults to 1.  For packing, the string is
truncated or padded with null bytes as appropriate to make it fit. For
unpacking, the resulting string always has exactly the specified number of
bytes.  As a special case, ``'0s'`` means a single, empty string (while
``'0c'`` means 0 characters).

The ``'p'`` format character encodes a "Pascal string", meaning a short
variable-length string stored in a *fixed number of bytes*, given by the count.
The first byte stored is the length of the string, or 255, whichever is smaller.
The bytes of the string follow.  If the string passed in to :func:`pack` is too
long (longer than the count minus 1), only the leading ``count-1`` bytes of the
string are stored.  If the string is shorter than ``count-1``, it is padded with
null bytes so that exactly count bytes in all are used.  Note that for
:func:`unpack`, the ``'p'`` format character consumes count bytes, but that the
string returned can never contain more than 255 characters.

For the ``'P'`` format character, the return value is a Python integer or long
integer, depending on the size needed to hold a pointer when it has been cast to
an integer type.  A *NULL* pointer will always be returned as the Python integer
``0``. When packing pointer-sized values, Python integer or long integer objects
may be used.  For example, the Alpha and Merced processors use 64-bit pointer
values, meaning a Python long integer will be used to hold the pointer; other
platforms use 32-bit pointers and will use a Python integer.

For the ``'?'`` format character, the return value is either :const:`True` or
:const:`False`. When packing, the truth value of the argument object is used.
Either 0 or 1 in the native or standard bool representation will be packed, and
any non-zero value will be ``True`` when unpacking.



.. _struct-examples:

Examples
^^^^^^^^

.. note::
   All examples assume a native byte order, size, and alignment with a
   big-endian machine.

A basic example of packing/unpacking three integers::

   >>> from struct import *
   >>> pack('hhl', 1, 2, 3)
   '\x00\x01\x00\x02\x00\x00\x00\x03'
   >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03')
   (1, 2, 3)
   >>> calcsize('hhl')
   8

Unpacked fields can be named by assigning them to variables or by wrapping
the result in a named tuple::

    >>> record = 'raymond   \x32\x12\x08\x01\x08'
    >>> name, serialnum, school, gradelevel = unpack('<10sHHb', record)

    >>> from collections import namedtuple
    >>> Student = namedtuple('Student', 'name serialnum school gradelevel')
    >>> Student._make(unpack('<10sHHb', record))
    Student(name='raymond   ', serialnum=4658, school=264, gradelevel=8)

The ordering of format characters may have an impact on size since the padding
needed to satisfy alignment requirements is different::

    >>> pack('ci', '*', 0x12131415)
    '*\x00\x00\x00\x12\x13\x14\x15'
    >>> pack('ic', 0x12131415, '*')
    '\x12\x13\x14\x15*'
    >>> calcsize('ci')
    8
    >>> calcsize('ic')
    5

The following format ``'llh0l'`` specifies two pad bytes at the end, assuming
longs are aligned on 4-byte boundaries::

    >>> pack('llh0l', 1, 2, 3)
    '\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00'

This only works when native size and alignment are in effect; standard size and
alignment does not enforce any alignment.


.. seealso::

   Module :mod:`array`
      Packed binary storage of homogeneous data.

   Module :mod:`xdrlib`
      Packing and unpacking of XDR data.


.. _struct-objects:

Classes
-------

The :mod:`struct` module also defines the following type:


.. class:: Struct(format)

   Return a new Struct object which writes and reads binary data according to
   the format string *format*.  Creating a Struct object once and calling its
   methods is more efficient than calling the :mod:`struct` functions with the
   same format since the format string only needs to be compiled once.

   .. versionadded:: 2.5

   Compiled Struct objects support the following methods and attributes:


   .. method:: pack(v1, v2, ...)

      Identical to the :func:`pack` function, using the compiled format.
      (``len(result)`` will equal :attr:`self.size`.)


   .. method:: pack_into(buffer, offset, v1, v2, ...)

      Identical to the :func:`pack_into` function, using the compiled format.


   .. method:: unpack(string)

      Identical to the :func:`unpack` function, using the compiled format.
      (``len(string)`` must equal :attr:`self.size`).


   .. method:: unpack_from(buffer, offset=0)

      Identical to the :func:`unpack_from` function, using the compiled format.
      (``len(buffer[offset:])`` must be at least :attr:`self.size`).


   .. attribute:: format

      The format string used to construct this Struct object.

   .. attribute:: size

      The calculated size of the struct (and hence of the string) corresponding
      to :attr:`format`.

PK
%�\
p�p�(html/_sources/library/subprocess.rst.txtnu�[���
:mod:`subprocess` --- Subprocess management
===========================================

.. module:: subprocess
   :synopsis: Subprocess management.
.. moduleauthor:: Peter Åstrand <astrand@lysator.liu.se>
.. sectionauthor:: Peter Åstrand <astrand@lysator.liu.se>


.. versionadded:: 2.4

The :mod:`subprocess` module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes.  This module intends to
replace several older modules and functions::

   os.system
   os.spawn*
   os.popen*
   popen2.*
   commands.*

Information about how this module can be used to replace the older
functions can be found in the subprocess-replacements_ section.

.. seealso::

   POSIX users (Linux, BSD, etc.) are strongly encouraged to install
   and use the much more recent subprocess32_ module instead of the
   version included with python 2.7.  It is a drop in replacement with
   better behavior in many situations.

   :pep:`324` -- PEP proposing the subprocess module

.. _subprocess32: https://pypi.org/project/subprocess32/

Using the :mod:`subprocess` Module
----------------------------------

The recommended way to launch subprocesses is to use the following
convenience functions.  For more advanced use cases when these do not
meet your needs, use the underlying :class:`Popen` interface.


.. function:: call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

   Run the command described by *args*.  Wait for command to complete, then
   return the :attr:`returncode` attribute.

   The arguments shown above are merely the most common ones, described below
   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
   the abbreviated signature). The full function signature is the same as
   that of the :class:`Popen` constructor - this functions passes all
   supplied arguments directly through to that interface.

   Examples::

      >>> subprocess.call(["ls", "-l"])
      0

      >>> subprocess.call("exit 1", shell=True)
      1

   .. warning::

      Using ``shell=True`` can be a security hazard.  See the warning
      under :ref:`frequently-used-arguments` for details.

   .. note::

      Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function
      as that can deadlock based on the child process output volume.
      Use :class:`Popen` with the :meth:`communicate` method when you
      need pipes.


.. function:: check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

   Run command with arguments.  Wait for command to complete. If the return
   code was zero then return, otherwise raise :exc:`CalledProcessError`. The
   :exc:`CalledProcessError` object will have the return code in the
   :attr:`~CalledProcessError.returncode` attribute.

   The arguments shown above are merely the most common ones, described below
   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
   the abbreviated signature). The full function signature is the same as
   that of the :class:`Popen` constructor - this functions passes all
   supplied arguments directly through to that interface.

   Examples::

      >>> subprocess.check_call(["ls", "-l"])
      0

      >>> subprocess.check_call("exit 1", shell=True)
      Traceback (most recent call last):
         ...
      subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

   .. versionadded:: 2.5

   .. warning::

      Using ``shell=True`` can be a security hazard.  See the warning
      under :ref:`frequently-used-arguments` for details.

   .. note::

      Do not use ``stdout=PIPE`` or ``stderr=PIPE`` with this function
      as that can deadlock based on the child process output volume.
      Use :class:`Popen` with the :meth:`communicate` method when you
      need pipes.


.. function:: check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

   Run command with arguments and return its output as a byte string.

   If the return code was non-zero it raises a :exc:`CalledProcessError`. The
   :exc:`CalledProcessError` object will have the return code in the
   :attr:`~CalledProcessError.returncode` attribute and any output in the
   :attr:`~CalledProcessError.output` attribute.

   The arguments shown above are merely the most common ones, described below
   in :ref:`frequently-used-arguments` (hence the slightly odd notation in
   the abbreviated signature). The full function signature is largely the
   same as that of the :class:`Popen` constructor, except that *stdout* is
   not permitted as it is used internally. All other supplied arguments are
   passed directly through to the :class:`Popen` constructor.

   Examples::

      >>> subprocess.check_output(["echo", "Hello World!"])
      'Hello World!\n'

      >>> subprocess.check_output("exit 1", shell=True)
      Traceback (most recent call last):
         ...
      subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

   To also capture standard error in the result, use
   ``stderr=subprocess.STDOUT``::

      >>> subprocess.check_output(
      ...     "ls non_existent_file; exit 0",
      ...     stderr=subprocess.STDOUT,
      ...     shell=True)
      'ls: non_existent_file: No such file or directory\n'

   .. versionadded:: 2.7

   .. warning::

      Using ``shell=True`` can be a security hazard.  See the warning
      under :ref:`frequently-used-arguments` for details.

   .. note::

      Do not use ``stderr=PIPE`` with this function as that can deadlock
      based on the child process error volume.  Use :class:`Popen` with
      the :meth:`communicate` method when you need a stderr pipe.


.. data:: PIPE

   Special value that can be used as the *stdin*, *stdout* or *stderr* argument
   to :class:`Popen` and indicates that a pipe to the standard stream should be
   opened.


.. data:: STDOUT

   Special value that can be used as the *stderr* argument to :class:`Popen` and
   indicates that standard error should go into the same handle as standard
   output.


.. exception:: CalledProcessError

    Exception raised when a process run by :func:`check_call` or
    :func:`check_output` returns a non-zero exit status.

    .. attribute:: returncode

        Exit status of the child process.

    .. attribute:: cmd

        Command that was used to spawn the child process.

    .. attribute:: output

        Output of the child process if this exception is raised by
        :func:`check_output`.  Otherwise, ``None``.



.. _frequently-used-arguments:

Frequently Used Arguments
^^^^^^^^^^^^^^^^^^^^^^^^^

To support a wide variety of use cases, the :class:`Popen` constructor (and
the convenience functions) accept a large number of optional arguments. For
most typical use cases, many of these arguments can be safely left at their
default values. The arguments that are most commonly needed are:

   *args* is required for all calls and should be a string, or a sequence of
   program arguments. Providing a sequence of arguments is generally
   preferred, as it allows the module to take care of any required escaping
   and quoting of arguments (e.g. to permit spaces in file names). If passing
   a single string, either *shell* must be :const:`True` (see below) or else
   the string must simply name the program to be executed without specifying
   any arguments.

   *stdin*, *stdout* and *stderr* specify the executed program's standard input,
   standard output and standard error file handles, respectively.  Valid values
   are :data:`PIPE`, an existing file descriptor (a positive integer), an
   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
   to the child should be created.  With the default settings of ``None``, no
   redirection will occur; the child's file handles will be inherited from the
   parent.  Additionally, *stderr* can be :data:`STDOUT`, which indicates that
   the stderr data from the child process should be captured into the same file
   handle as for stdout.

   .. index::
      single: universal newlines; subprocess module

   When *stdout* or *stderr* are pipes and *universal_newlines* is
   ``True`` then all line endings will be converted to ``'\n'`` as described
   for the :term:`universal newlines` ``'U'`` mode argument to :func:`open`.

   If *shell* is ``True``, the specified command will be executed through
   the shell.  This can be useful if you are using Python primarily for the
   enhanced control flow it offers over most system shells and still want
   convenient access to other shell features such as shell pipes, filename
   wildcards, environment variable expansion, and expansion of ``~`` to a
   user's home directory.  However, note that Python itself offers
   implementations of many shell-like features (in particular, :mod:`glob`,
   :mod:`fnmatch`, :func:`os.walk`, :func:`os.path.expandvars`,
   :func:`os.path.expanduser`, and :mod:`shutil`).

   .. warning::

      Executing shell commands that incorporate unsanitized input from an
      untrusted source makes a program vulnerable to `shell injection
      <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
      a serious security flaw which can result in arbitrary command execution.
      For this reason, the use of ``shell=True`` is **strongly discouraged**
      in cases where the command string is constructed from external input::

         >>> from subprocess import call
         >>> filename = input("What file would you like to display?\n")
         What file would you like to display?
         non_existent; rm -rf / #
         >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...

      ``shell=False`` disables all shell based features, but does not suffer
      from this vulnerability; see the Note in the :class:`Popen` constructor
      documentation for helpful hints in getting ``shell=False`` to work.

      When using ``shell=True``, :func:`pipes.quote` can be used to properly
      escape whitespace and shell metacharacters in strings that are going to
      be used to construct shell commands.

These options, along with all of the other options, are described in more
detail in the :class:`Popen` constructor documentation.


Popen Constructor
^^^^^^^^^^^^^^^^^

The underlying process creation and management in this module is handled by
the :class:`Popen` class. It offers a lot of flexibility so that developers
are able to handle the less common cases not covered by the convenience
functions.


.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, \
                 stderr=None, preexec_fn=None, close_fds=False, shell=False, \
                 cwd=None, env=None, universal_newlines=False, \
                 startupinfo=None, creationflags=0)

   Execute a child program in a new process.  On Unix, the class uses
   :meth:`os.execvp`-like behavior to execute the child program.  On Windows,
   the class uses the Windows ``CreateProcess()`` function.  The arguments to
   :class:`Popen` are as follows.

   *args* should be a sequence of program arguments or else a single string.
   By default, the program to execute is the first item in *args* if *args* is
   a sequence.  If *args* is a string, the interpretation is
   platform-dependent and described below.  See the *shell* and *executable*
   arguments for additional differences from the default behavior.  Unless
   otherwise stated, it is recommended to pass *args* as a sequence.

   On Unix, if *args* is a string, the string is interpreted as the name or
   path of the program to execute.  However, this can only be done if not
   passing arguments to the program.

   .. note::

      :meth:`shlex.split` can be useful when determining the correct
      tokenization for *args*, especially in complex cases::

         >>> import shlex, subprocess
         >>> command_line = raw_input()
         /bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
         >>> args = shlex.split(command_line)
         >>> print args
         ['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
         >>> p = subprocess.Popen(args) # Success!

      Note in particular that options (such as *-input*) and arguments (such
      as *eggs.txt*) that are separated by whitespace in the shell go in separate
      list elements, while arguments that need quoting or backslash escaping when
      used in the shell (such as filenames containing spaces or the *echo* command
      shown above) are single list elements.

   On Windows, if *args* is a sequence, it will be converted to a string in a
   manner described in :ref:`converting-argument-sequence`.  This is because
   the underlying ``CreateProcess()`` operates on strings.

   The *shell* argument (which defaults to ``False``) specifies whether to use
   the shell as the program to execute.  If *shell* is ``True``, it is
   recommended to pass *args* as a string rather than as a sequence.

   On Unix with ``shell=True``, the shell defaults to :file:`/bin/sh`.  If
   *args* is a string, the string specifies the command
   to execute through the shell.  This means that the string must be
   formatted exactly as it would be when typed at the shell prompt.  This
   includes, for example, quoting or backslash escaping filenames with spaces in
   them.  If *args* is a sequence, the first item specifies the command string, and
   any additional items will be treated as additional arguments to the shell
   itself.  That is to say, :class:`Popen` does the equivalent of::

      Popen(['/bin/sh', '-c', args[0], args[1], ...])

   On Windows with ``shell=True``, the :envvar:`COMSPEC` environment variable
   specifies the default shell.  The only time you need to specify
   ``shell=True`` on Windows is when the command you wish to execute is built
   into the shell (e.g. :command:`dir` or :command:`copy`).  You do not need
   ``shell=True`` to run a batch file or console-based executable.

   .. warning::

      Passing ``shell=True`` can be a security hazard if combined with
      untrusted input.  See the warning under :ref:`frequently-used-arguments`
      for details.

   *bufsize*, if given, has the same meaning as the corresponding argument to the
   built-in open() function: :const:`0` means unbuffered, :const:`1` means line
   buffered, any other positive value means use a buffer of (approximately) that
   size.  A negative *bufsize* means to use the system default, which usually means
   fully buffered.  The default value for *bufsize* is :const:`0` (unbuffered).

   .. note::

      If you experience performance issues, it is recommended that you try to
      enable buffering by setting *bufsize* to either -1 or a large enough
      positive value (such as 4096).

   The *executable* argument specifies a replacement program to execute.   It
   is very seldom needed.  When ``shell=False``, *executable* replaces the
   program to execute specified by *args*.  However, the original *args* is
   still passed to the program.  Most programs treat the program specified
   by *args* as the command name, which can then be different from the program
   actually executed.  On Unix, the *args* name
   becomes the display name for the executable in utilities such as
   :program:`ps`.  If ``shell=True``, on Unix the *executable* argument
   specifies a replacement shell for the default :file:`/bin/sh`.

   *stdin*, *stdout* and *stderr* specify the executed program's standard input,
   standard output and standard error file handles, respectively.  Valid values
   are :data:`PIPE`, an existing file descriptor (a positive integer), an
   existing file object, and ``None``.  :data:`PIPE` indicates that a new pipe
   to the child should be created.  With the default settings of ``None``, no
   redirection will occur; the child's file handles will be inherited from the
   parent.  Additionally, *stderr* can be :data:`STDOUT`, which indicates that
   the stderr data from the child process should be captured into the same file
   handle as for stdout.

   If *preexec_fn* is set to a callable object, this object will be called in the
   child process just before the child is executed. (Unix only)

   If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
   :const:`2` will be closed before the child process is executed. (Unix only).
   Or, on Windows, if *close_fds* is true then no handles will be inherited by the
   child process.  Note that on Windows, you cannot set *close_fds* to true and
   also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.

   If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
   before it is executed.  Note that this directory is not considered when
   searching the executable, so you can't specify the program's path relative to
   *cwd*.

   If *env* is not ``None``, it must be a mapping that defines the environment
   variables for the new process; these are used instead of inheriting the current
   process' environment, which is the default behavior.

   .. note::

      If specified, *env* must provide any variables required
      for the program to execute.  On Windows, in order to run a
      `side-by-side assembly`_ the specified *env* **must** include a valid
      :envvar:`SystemRoot`.

   .. _side-by-side assembly: https://en.wikipedia.org/wiki/Side-by-Side_Assembly

   If *universal_newlines* is ``True``, the file objects *stdout* and *stderr*
   are opened as text files in :term:`universal newlines` mode.  Lines may be
   terminated by any of ``'\n'``, the Unix end-of-line convention, ``'\r'``,
   the old Macintosh convention or ``'\r\n'``, the Windows convention. All of
   these external representations are seen as ``'\n'`` by the Python program.

   .. note::

      This feature is only available if Python is built with universal newline
      support (the default).  Also, the newlines attribute of the file objects
      :attr:`stdout`, :attr:`stdin` and :attr:`stderr` are not updated by the
      communicate() method.

   If given, *startupinfo* will be a :class:`STARTUPINFO` object, which is
   passed to the underlying ``CreateProcess`` function.
   *creationflags*, if given, can be :data:`CREATE_NEW_CONSOLE` or
   :data:`CREATE_NEW_PROCESS_GROUP`. (Windows only)


Exceptions
^^^^^^^^^^

Exceptions raised in the child process, before the new program has started to
execute, will be re-raised in the parent.  Additionally, the exception object
will have one extra attribute called :attr:`child_traceback`, which is a string
containing traceback information from the child's point of view.

The most common exception raised is :exc:`OSError`.  This occurs, for example,
when trying to execute a non-existent file.  Applications should prepare for
:exc:`OSError` exceptions.

A :exc:`ValueError` will be raised if :class:`Popen` is called with invalid
arguments.

:func:`check_call` and :func:`check_output` will raise
:exc:`CalledProcessError` if the called process returns a non-zero return
code.


Security
^^^^^^^^

Unlike some other popen functions, this implementation will never call a
system shell implicitly.  This means that all characters, including shell
metacharacters, can safely be passed to child processes. Obviously, if the
shell is invoked explicitly, then it is the application's responsibility to
ensure that all whitespace and metacharacters are quoted appropriately.


Popen Objects
-------------

Instances of the :class:`Popen` class have the following methods:


.. method:: Popen.poll()

   Check if child process has terminated.  Set and return
   :attr:`~Popen.returncode` attribute.


.. method:: Popen.wait()

   Wait for child process to terminate.  Set and return
   :attr:`~Popen.returncode` attribute.

   .. warning::

      This will deadlock when using ``stdout=PIPE`` and/or
      ``stderr=PIPE`` and the child process generates enough output to
      a pipe such that it blocks waiting for the OS pipe buffer to
      accept more data.  Use :meth:`communicate` to avoid that.


.. method:: Popen.communicate(input=None)

   Interact with process: Send data to stdin.  Read data from stdout and stderr,
   until end-of-file is reached.  Wait for process to terminate. The optional
   *input* argument should be a string to be sent to the child process, or
   ``None``, if no data should be sent to the child.

   :meth:`communicate` returns a tuple ``(stdoutdata, stderrdata)``.

   Note that if you want to send data to the process's stdin, you need to create
   the Popen object with ``stdin=PIPE``.  Similarly, to get anything other than
   ``None`` in the result tuple, you need to give ``stdout=PIPE`` and/or
   ``stderr=PIPE`` too.

   .. note::

      The data read is buffered in memory, so do not use this method if the data
      size is large or unlimited.


.. method:: Popen.send_signal(signal)

   Sends the signal *signal* to the child.

   .. note::

      On Windows, SIGTERM is an alias for :meth:`terminate`. CTRL_C_EVENT and
      CTRL_BREAK_EVENT can be sent to processes started with a *creationflags*
      parameter which includes `CREATE_NEW_PROCESS_GROUP`.

   .. versionadded:: 2.6


.. method:: Popen.terminate()

   Stop the child. On Posix OSs the method sends SIGTERM to the
   child. On Windows the Win32 API function :c:func:`TerminateProcess` is called
   to stop the child.

   .. versionadded:: 2.6


.. method:: Popen.kill()

   Kills the child. On Posix OSs the function sends SIGKILL to the child.
   On Windows :meth:`kill` is an alias for :meth:`terminate`.

   .. versionadded:: 2.6


The following attributes are also available:

.. warning::

   Use :meth:`~Popen.communicate` rather than :attr:`.stdin.write <Popen.stdin>`,
   :attr:`.stdout.read <Popen.stdout>` or :attr:`.stderr.read <Popen.stderr>` to avoid
   deadlocks due to any of the other OS pipe buffers filling up and blocking the
   child process.


.. attribute:: Popen.stdin

   If the *stdin* argument was :data:`PIPE`, this attribute is a file object
   that provides input to the child process.  Otherwise, it is ``None``.


.. attribute:: Popen.stdout

   If the *stdout* argument was :data:`PIPE`, this attribute is a file object
   that provides output from the child process.  Otherwise, it is ``None``.


.. attribute:: Popen.stderr

   If the *stderr* argument was :data:`PIPE`, this attribute is a file object
   that provides error output from the child process.  Otherwise, it is
   ``None``.


.. attribute:: Popen.pid

   The process ID of the child process.

   Note that if you set the *shell* argument to ``True``, this is the process ID
   of the spawned shell.


.. attribute:: Popen.returncode

   The child return code, set by :meth:`poll` and :meth:`wait` (and indirectly
   by :meth:`communicate`).  A ``None`` value indicates that the process
   hasn't terminated yet.

   A negative value ``-N`` indicates that the child was terminated by signal
   ``N`` (Unix only).


Windows Popen Helpers
---------------------

The :class:`STARTUPINFO` class and following constants are only available
on Windows.

.. class:: STARTUPINFO()

   Partial support of the Windows
   `STARTUPINFO <https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx>`__
   structure is used for :class:`Popen` creation.

   .. attribute:: dwFlags

      A bit field that determines whether certain :class:`STARTUPINFO`
      attributes are used when the process creates a window. ::

         si = subprocess.STARTUPINFO()
         si.dwFlags = subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW

   .. attribute:: hStdInput

      If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
      is the standard input handle for the process. If
      :data:`STARTF_USESTDHANDLES` is not specified, the default for standard
      input is the keyboard buffer.

   .. attribute:: hStdOutput

      If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
      is the standard output handle for the process. Otherwise, this attribute
      is ignored and the default for standard output is the console window's
      buffer.

   .. attribute:: hStdError

      If :attr:`dwFlags` specifies :data:`STARTF_USESTDHANDLES`, this attribute
      is the standard error handle for the process. Otherwise, this attribute is
      ignored and the default for standard error is the console window's buffer.

   .. attribute:: wShowWindow

      If :attr:`dwFlags` specifies :data:`STARTF_USESHOWWINDOW`, this attribute
      can be any of the values that can be specified in the ``nCmdShow``
      parameter for the
      `ShowWindow <https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx>`__
      function, except for ``SW_SHOWDEFAULT``. Otherwise, this attribute is
      ignored.

      :data:`SW_HIDE` is provided for this attribute. It is used when
      :class:`Popen` is called with ``shell=True``.


Constants
^^^^^^^^^

The :mod:`subprocess` module exposes the following constants.

.. data:: STD_INPUT_HANDLE

   The standard input device. Initially, this is the console input buffer,
   ``CONIN$``.

.. data:: STD_OUTPUT_HANDLE

   The standard output device. Initially, this is the active console screen
   buffer, ``CONOUT$``.

.. data:: STD_ERROR_HANDLE

   The standard error device. Initially, this is the active console screen
   buffer, ``CONOUT$``.

.. data:: SW_HIDE

   Hides the window. Another window will be activated.

.. data:: STARTF_USESTDHANDLES

   Specifies that the :attr:`STARTUPINFO.hStdInput`,
   :attr:`STARTUPINFO.hStdOutput`, and :attr:`STARTUPINFO.hStdError` attributes
   contain additional information.

.. data:: STARTF_USESHOWWINDOW

   Specifies that the :attr:`STARTUPINFO.wShowWindow` attribute contains
   additional information.

.. data:: CREATE_NEW_CONSOLE

   The new process has a new console, instead of inheriting its parent's
   console (the default).

   This flag is always set when :class:`Popen` is created with ``shell=True``.

.. data:: CREATE_NEW_PROCESS_GROUP

   A :class:`Popen` ``creationflags`` parameter to specify that a new process
   group will be created. This flag is necessary for using :func:`os.kill`
   on the subprocess.

   This flag is ignored if :data:`CREATE_NEW_CONSOLE` is specified.


.. _subprocess-replacements:

Replacing Older Functions with the :mod:`subprocess` Module
-----------------------------------------------------------

In this section, "a becomes b" means that b can be used as a replacement for a.

.. note::

   All "a" functions in this section fail (more or less) silently if the
   executed program cannot be found; the "b" replacements raise :exc:`OSError`
   instead.

   In addition, the replacements using :func:`check_output` will fail with a
   :exc:`CalledProcessError` if the requested operation produces a non-zero
   return code. The output is still available as the
   :attr:`~CalledProcessError.output` attribute of the raised exception.

In the following examples, we assume that the relevant functions have already
been imported from the :mod:`subprocess` module.


Replacing /bin/sh shell backquote
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   output=`mycmd myarg`

becomes::

   output = check_output(["mycmd", "myarg"])

Replacing shell pipeline
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: bash

   output=`dmesg | grep hda`

becomes::

   p1 = Popen(["dmesg"], stdout=PIPE)
   p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
   p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
   output = p2.communicate()[0]

The p1.stdout.close() call after starting the p2 is important in order for p1
to receive a SIGPIPE if p2 exits before p1.

Alternatively, for trusted input, the shell's own pipeline support may still
be used directly:

.. code-block:: bash

   output=`dmesg | grep hda`

becomes::

   output=check_output("dmesg | grep hda", shell=True)


Replacing :func:`os.system`
^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   status = os.system("mycmd" + " myarg")
   # becomes
   status = subprocess.call("mycmd" + " myarg", shell=True)

Notes:

* Calling the program through the shell is usually not required.

A more realistic example would look like this::

   try:
       retcode = call("mycmd" + " myarg", shell=True)
       if retcode < 0:
           print >>sys.stderr, "Child was terminated by signal", -retcode
       else:
           print >>sys.stderr, "Child returned", retcode
   except OSError as e:
       print >>sys.stderr, "Execution failed:", e


Replacing the :func:`os.spawn <os.spawnl>` family
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

P_NOWAIT example::

   pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
   ==>
   pid = Popen(["/bin/mycmd", "myarg"]).pid

P_WAIT example::

   retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
   ==>
   retcode = call(["/bin/mycmd", "myarg"])

Vector example::

   os.spawnvp(os.P_NOWAIT, path, args)
   ==>
   Popen([path] + args[1:])

Environment example::

   os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
   ==>
   Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})


Replacing :func:`os.popen`, :func:`os.popen2`, :func:`os.popen3`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   pipe = os.popen("cmd", 'r', bufsize)
   ==>
   pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout

::

   pipe = os.popen("cmd", 'w', bufsize)
   ==>
   pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin

::

   (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
   ==>
   p = Popen("cmd", shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdin, child_stdout) = (p.stdin, p.stdout)

::

   (child_stdin,
    child_stdout,
    child_stderr) = os.popen3("cmd", mode, bufsize)
   ==>
   p = Popen("cmd", shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
   (child_stdin,
    child_stdout,
    child_stderr) = (p.stdin, p.stdout, p.stderr)

::

   (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
                                                      bufsize)
   ==>
   p = Popen("cmd", shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
   (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)

On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
the command to execute, in which case arguments will be passed
directly to the program without shell intervention.  This usage can be
replaced as follows::

   (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
                                           bufsize)
   ==>
   p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
   (child_stdin, child_stdout) = (p.stdin, p.stdout)

Return code handling translates as follows::

   pipe = os.popen("cmd", 'w')
   ...
   rc = pipe.close()
   if rc is not None and rc >> 8:
       print "There were some errors"
   ==>
   process = Popen("cmd", shell=True, stdin=PIPE)
   ...
   process.stdin.close()
   if process.wait() != 0:
       print "There were some errors"


Replacing functions from the :mod:`popen2` module
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
   ==>
   p = Popen("somestring", shell=True, bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdout, child_stdin) = (p.stdout, p.stdin)

On Unix, popen2 also accepts a sequence as the command to execute, in
which case arguments will be passed directly to the program without
shell intervention.  This usage can be replaced as follows::

   (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
                                               mode)
   ==>
   p = Popen(["mycmd", "myarg"], bufsize=bufsize,
             stdin=PIPE, stdout=PIPE, close_fds=True)
   (child_stdout, child_stdin) = (p.stdout, p.stdin)

:class:`popen2.Popen3` and :class:`popen2.Popen4` basically work as
:class:`subprocess.Popen`, except that:

* :class:`Popen` raises an exception if the execution fails.

* the *capturestderr* argument is replaced with the *stderr* argument.

* ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.

* popen2 closes all file descriptors by default, but you have to specify
  ``close_fds=True`` with :class:`Popen`.


Notes
-----

.. _converting-argument-sequence:

Converting an argument sequence to a string on Windows
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

On Windows, an *args* sequence is converted to a string that can be parsed
using the following rules (which correspond to the rules used by the MS C
runtime):

1. Arguments are delimited by white space, which is either a
   space or a tab.

2. A string surrounded by double quotation marks is
   interpreted as a single argument, regardless of white space
   contained within.  A quoted string can be embedded in an
   argument.

3. A double quotation mark preceded by a backslash is
   interpreted as a literal double quotation mark.

4. Backslashes are interpreted literally, unless they
   immediately precede a double quotation mark.

5. If backslashes immediately precede a double quotation mark,
   every pair of backslashes is interpreted as a literal
   backslash.  If the number of backslashes is odd, the last
   backslash escapes the next double quotation mark as
   described in rule 3.

PK
%�\�3����!html/_sources/library/sun.rst.txtnu�[���
.. _sunos:

***********************
SunOS Specific Services
***********************

The modules described in this chapter provide interfaces to features that are
unique to SunOS 5 (also known as Solaris version 2).


.. toctree::

   sunaudio.rst
PK
%�\�E!��#html/_sources/library/sunau.rst.txtnu�[���:mod:`sunau` --- Read and write Sun AU files
============================================

.. module:: sunau
   :synopsis: Provide an interface to the Sun AU sound format.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

**Source code:** :source:`Lib/sunau.py`

--------------

The :mod:`sunau` module provides a convenient interface to the Sun AU sound
format.  Note that this module is interface-compatible with the modules
:mod:`aifc` and :mod:`wave`.

An audio file consists of a header followed by the data.  The fields of the
header are:

+---------------+-----------------------------------------------+
| Field         | Contents                                      |
+===============+===============================================+
| magic word    | The four bytes ``.snd``.                      |
+---------------+-----------------------------------------------+
| header size   | Size of the header, including info, in bytes. |
+---------------+-----------------------------------------------+
| data size     | Physical size of the data, in bytes.          |
+---------------+-----------------------------------------------+
| encoding      | Indicates how the audio samples are encoded.  |
+---------------+-----------------------------------------------+
| sample rate   | The sampling rate.                            |
+---------------+-----------------------------------------------+
| # of channels | The number of channels in the samples.        |
+---------------+-----------------------------------------------+
| info          | ASCII string giving a description of the      |
|               | audio file (padded with null bytes).          |
+---------------+-----------------------------------------------+

Apart from the info field, all header fields are 4 bytes in size. They are all
32-bit unsigned integers encoded in big-endian byte order.

The :mod:`sunau` module defines the following functions:


.. function:: open(file, mode)

   If *file* is a string, open the file by that name, otherwise treat it as a
   seekable file-like object. *mode* can be any of

   ``'r'``
      Read only mode.

   ``'w'``
      Write only mode.

   Note that it does not allow read/write files.

   A *mode* of ``'r'`` returns an :class:`AU_read` object, while a *mode* of ``'w'``
   or ``'wb'`` returns an :class:`AU_write` object.


.. function:: openfp(file, mode)

   A synonym for :func:`.open`, maintained for backwards compatibility.


The :mod:`sunau` module defines the following exception:

.. exception:: Error

   An error raised when something is impossible because of Sun AU specs or
   implementation deficiency.


The :mod:`sunau` module defines the following data items:

.. data:: AUDIO_FILE_MAGIC

   An integer every valid Sun AU file begins with, stored in big-endian form.  This
   is the string ``.snd`` interpreted as an integer.


.. data:: AUDIO_FILE_ENCODING_MULAW_8
          AUDIO_FILE_ENCODING_LINEAR_8
          AUDIO_FILE_ENCODING_LINEAR_16
          AUDIO_FILE_ENCODING_LINEAR_24
          AUDIO_FILE_ENCODING_LINEAR_32
          AUDIO_FILE_ENCODING_ALAW_8

   Values of the encoding field from the AU header which are supported by this
   module.


.. data:: AUDIO_FILE_ENCODING_FLOAT
          AUDIO_FILE_ENCODING_DOUBLE
          AUDIO_FILE_ENCODING_ADPCM_G721
          AUDIO_FILE_ENCODING_ADPCM_G722
          AUDIO_FILE_ENCODING_ADPCM_G723_3
          AUDIO_FILE_ENCODING_ADPCM_G723_5

   Additional known values of the encoding field from the AU header, but which are
   not supported by this module.


.. _au-read-objects:

AU_read Objects
---------------

AU_read objects, as returned by :func:`.open` above, have the following methods:


.. method:: AU_read.close()

   Close the stream, and make the instance unusable. (This is  called automatically
   on deletion.)


.. method:: AU_read.getnchannels()

   Returns number of audio channels (1 for mono, 2 for stereo).


.. method:: AU_read.getsampwidth()

   Returns sample width in bytes.


.. method:: AU_read.getframerate()

   Returns sampling frequency.


.. method:: AU_read.getnframes()

   Returns number of audio frames.


.. method:: AU_read.getcomptype()

   Returns compression type. Supported compression types are ``'ULAW'``, ``'ALAW'``
   and ``'NONE'``.


.. method:: AU_read.getcompname()

   Human-readable version of :meth:`getcomptype`.  The supported types have the
   respective names ``'CCITT G.711 u-law'``, ``'CCITT G.711 A-law'`` and ``'not
   compressed'``.


.. method:: AU_read.getparams()

   Returns a tuple ``(nchannels, sampwidth, framerate, nframes, comptype,
   compname)``, equivalent to output of the :meth:`get\*` methods.


.. method:: AU_read.readframes(n)

   Reads and returns at most *n* frames of audio, as a string of bytes.  The data
   will be returned in linear format.  If the original data is in u-LAW format, it
   will be converted.


.. method:: AU_read.rewind()

   Rewind the file pointer to the beginning of the audio stream.

The following two methods define a term "position" which is compatible between
them, and is otherwise implementation dependent.


.. method:: AU_read.setpos(pos)

   Set the file pointer to the specified position.  Only values returned from
   :meth:`tell` should be used for *pos*.


.. method:: AU_read.tell()

   Return current file pointer position.  Note that the returned value has nothing
   to do with the actual position in the file.

The following two functions are defined for compatibility with the  :mod:`aifc`,
and don't do anything interesting.


.. method:: AU_read.getmarkers()

   Returns ``None``.


.. method:: AU_read.getmark(id)

   Raise an error.


.. _au-write-objects:

AU_write Objects
----------------

AU_write objects, as returned by :func:`.open` above, have the following methods:


.. method:: AU_write.setnchannels(n)

   Set the number of channels.


.. method:: AU_write.setsampwidth(n)

   Set the sample width (in bytes.)


.. method:: AU_write.setframerate(n)

   Set the frame rate.


.. method:: AU_write.setnframes(n)

   Set the number of frames. This can be later changed, when and if more  frames
   are written.


.. method:: AU_write.setcomptype(type, name)

   Set the compression type and description. Only ``'NONE'`` and ``'ULAW'`` are
   supported on output.


.. method:: AU_write.setparams(tuple)

   The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype,
   compname)``, with values valid for the :meth:`set\*` methods.  Set all
   parameters.


.. method:: AU_write.tell()

   Return current position in the file, with the same disclaimer for the
   :meth:`AU_read.tell` and :meth:`AU_read.setpos` methods.


.. method:: AU_write.writeframesraw(data)

   Write audio frames, without correcting *nframes*.


.. method:: AU_write.writeframes(data)

   Write audio frames and make sure *nframes* is correct.


.. method:: AU_write.close()

   Make sure *nframes* is correct, and close the file.

   This method is called upon deletion.

Note that it is invalid to set any parameters after calling  :meth:`writeframes`
or :meth:`writeframesraw`.

PK
%�\�:��&html/_sources/library/sunaudio.rst.txtnu�[���
:mod:`sunaudiodev` --- Access to Sun audio hardware
===================================================

.. module:: sunaudiodev
   :platform: SunOS
   :synopsis: Access to Sun audio hardware.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`sunaudiodev` module has been removed in Python 3.



.. index:: single: u-LAW

This module allows you to access the Sun audio interface. The Sun audio hardware
is capable of recording and playing back audio data in u-LAW format with a
sample rate of 8K per second. A full description can be found in the
:manpage:`audio(7I)` manual page.

.. index:: module: SUNAUDIODEV

The module :mod:`SUNAUDIODEV`  defines constants which may be used with this
module.

This module defines the following variables and functions:


.. exception:: error

   This exception is raised on all errors. The argument is a string describing what
   went wrong.


.. function:: open(mode)

   This function opens the audio device and returns a Sun audio device object. This
   object can then be used to do I/O on. The *mode* parameter is one of ``'r'`` for
   record-only access, ``'w'`` for play-only access, ``'rw'`` for both and
   ``'control'`` for access to the control device. Since only one process is
   allowed to have the recorder or player open at the same time it is a good idea
   to open the device only for the activity needed. See :manpage:`audio(7I)` for
   details.

   As per the manpage, this module first looks in the environment variable
   ``AUDIODEV`` for the base audio device filename.  If not found, it falls back to
   :file:`/dev/audio`.  The control device is calculated by appending "ctl" to the
   base audio device.


.. _audio-device-objects:

Audio Device Objects
--------------------

The audio device objects are returned by :func:`.open` define the following
methods (except ``control`` objects which only provide :meth:`getinfo`,
:meth:`setinfo`, :meth:`fileno`, and :meth:`drain`):


.. method:: audio device.close()

   This method explicitly closes the device. It is useful in situations where
   deleting the object does not immediately close it since there are other
   references to it. A closed device should not be used again.


.. method:: audio device.fileno()

   Returns the file descriptor associated with the device.  This can be used to set
   up ``SIGPOLL`` notification, as described below.


.. method:: audio device.drain()

   This method waits until all pending output is processed and then returns.
   Calling this method is often not necessary: destroying the object will
   automatically close the audio device and this will do an implicit drain.


.. method:: audio device.flush()

   This method discards all pending output. It can be used avoid the slow response
   to a user's stop request (due to buffering of up to one second of sound).


.. method:: audio device.getinfo()

   This method retrieves status information like input and output volume, etc. and
   returns it in the form of an audio status object. This object has no methods but
   it contains a number of attributes describing the current device status. The
   names and meanings of the attributes are described in ``<sun/audioio.h>`` and in
   the :manpage:`audio(7I)` manual page.  Member names are slightly different from
   their C counterparts: a status object is only a single structure. Members of the
   :c:data:`play` substructure have ``o_`` prepended to their name and members of
   the :c:data:`record` structure have ``i_``. So, the C member
   :c:data:`play.sample_rate` is accessed as :attr:`o_sample_rate`,
   :c:data:`record.gain` as :attr:`i_gain` and :c:data:`monitor_gain` plainly as
   :attr:`monitor_gain`.


.. method:: audio device.ibufcount()

   This method returns the number of samples that are buffered on the recording
   side, i.e. the program will not block on a :func:`read` call of so many samples.


.. method:: audio device.obufcount()

   This method returns the number of samples buffered on the playback side.
   Unfortunately, this number cannot be used to determine a number of samples that
   can be written without blocking since the kernel output queue length seems to be
   variable.


.. method:: audio device.read(size)

   This method reads *size* samples from the audio input and returns them as a
   Python string. The function blocks until enough data is available.


.. method:: audio device.setinfo(status)

   This method sets the audio device status parameters. The *status* parameter is
   a device status object as returned by :func:`getinfo` and possibly modified by
   the program.


.. method:: audio device.write(samples)

   Write is passed a Python string containing audio samples to be played. If there
   is enough buffer space free it will immediately return, otherwise it will block.

The audio device supports asynchronous notification of various events, through
the SIGPOLL signal.  Here's an example of how you might enable this in Python::

   def handle_sigpoll(signum, frame):
       print 'I got a SIGPOLL update'

   import fcntl, signal, STROPTS

   signal.signal(signal.SIGPOLL, handle_sigpoll)
   fcntl.ioctl(audio_obj.fileno(), STROPTS.I_SETSIG, STROPTS.S_MSG)


:mod:`SUNAUDIODEV` --- Constants used with :mod:`sunaudiodev`
=============================================================

.. module:: SUNAUDIODEV
   :platform: SunOS
   :synopsis: Constants for use with sunaudiodev.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`SUNAUDIODEV` module has been removed in Python 3.



.. index:: module: sunaudiodev

This is a companion module to :mod:`sunaudiodev` which defines useful symbolic
constants like :const:`MIN_GAIN`, :const:`MAX_GAIN`, :const:`SPEAKER`, etc. The
names of the constants are the same names as used in the C include file
``<sun/audioio.h>``, with the leading string ``AUDIO_`` stripped.

PK
%�\J�$W��$html/_sources/library/symbol.rst.txtnu�[���:mod:`symbol` --- Constants used with Python parse trees
========================================================

.. module:: symbol
   :synopsis: Constants representing internal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/symbol.py`

--------------

This module provides constants which represent the numeric values of internal
nodes of the parse tree.  Unlike most Python constants, these use lower-case
names.  Refer to the file :file:`Grammar/Grammar` in the Python distribution for
the definitions of the names in the context of the language grammar.  The
specific numeric values which the names map to may change between Python
versions.

This module also provides one additional data object:


.. data:: sym_name

   Dictionary mapping the numeric values of the constants defined in this module
   back to name strings, allowing more human-readable representation of parse trees
   to be generated.

PK
%�\�ɘ��&html/_sources/library/symtable.rst.txtnu�[���:mod:`symtable` --- Access to the compiler's symbol tables
==========================================================

.. module:: symtable
   :synopsis: Interface to the compiler's internal symbol tables.

**Source code:** :source:`Lib/symtable.py`

--------------

.. moduleauthor:: Jeremy Hylton <jeremy@alum.mit.edu>
.. sectionauthor:: Benjamin Peterson <benjamin@python.org>


Symbol tables are generated by the compiler from AST just before bytecode is
generated.  The symbol table is responsible for calculating the scope of every
identifier in the code.  :mod:`symtable` provides an interface to examine these
tables.


Generating Symbol Tables
------------------------

.. function:: symtable(code, filename, compile_type)

   Return the toplevel :class:`SymbolTable` for the Python source *code*.
   *filename* is the name of the file containing the code.  *compile_type* is
   like the *mode* argument to :func:`compile`.


Examining Symbol Tables
-----------------------

.. class:: SymbolTable

   A namespace table for a block.  The constructor is not public.

   .. method:: get_type()

      Return the type of the symbol table.  Possible values are ``'class'``,
      ``'module'``, and ``'function'``.

   .. method:: get_id()

      Return the table's identifier.

   .. method:: get_name()

      Return the table's name.  This is the name of the class if the table is
      for a class, the name of the function if the table is for a function, or
      ``'top'`` if the table is global (:meth:`get_type` returns ``'module'``).

   .. method:: get_lineno()

      Return the number of the first line in the block this table represents.

   .. method:: is_optimized()

      Return ``True`` if the locals in this table can be optimized.

   .. method:: is_nested()

      Return ``True`` if the block is a nested class or function.

   .. method:: has_children()

      Return ``True`` if the block has nested namespaces within it.  These can
      be obtained with :meth:`get_children`.

   .. method:: has_exec()

      Return ``True`` if the block uses ``exec``.

   .. method:: has_import_star()

      Return ``True`` if the block uses a starred from-import.

   .. method:: get_identifiers()

      Return a list of names of symbols in this table.

   .. method:: lookup(name)

      Lookup *name* in the table and return a :class:`Symbol` instance.

   .. method:: get_symbols()

      Return a list of :class:`Symbol` instances for names in the table.

   .. method:: get_children()

      Return a list of the nested symbol tables.


.. class:: Function

   A namespace for a function or method.  This class inherits
   :class:`SymbolTable`.

   .. method:: get_parameters()

      Return a tuple containing names of parameters to this function.

   .. method:: get_locals()

      Return a tuple containing names of locals in this function.

   .. method:: get_globals()

      Return a tuple containing names of globals in this function.

   .. method:: get_frees()

      Return a tuple containing names of free variables in this function.


.. class:: Class

   A namespace of a class.  This class inherits :class:`SymbolTable`.

   .. method:: get_methods()

      Return a tuple containing the names of methods declared in the class.


.. class:: Symbol

   An entry in a :class:`SymbolTable` corresponding to an identifier in the
   source.  The constructor is not public.

   .. method:: get_name()

      Return the symbol's name.

   .. method:: is_referenced()

      Return ``True`` if the symbol is used in its block.

   .. method:: is_imported()

      Return ``True`` if the symbol is created from an import statement.

   .. method:: is_parameter()

      Return ``True`` if the symbol is a parameter.

   .. method:: is_global()

      Return ``True`` if the symbol is global.

   .. method:: is_declared_global()

      Return ``True`` if the symbol is declared global with a global statement.

   .. method:: is_local()

      Return ``True`` if the symbol is local to its block.

   .. method:: is_free()

      Return ``True`` if the symbol is referenced in its block, but not assigned
      to.

   .. method:: is_assigned()

      Return ``True`` if the symbol is assigned to in its block.

   .. method:: is_namespace()

      Return ``True`` if name binding introduces new namespace.

      If the name is used as the target of a function or class statement, this
      will be true.

      For example::

         >>> table = symtable.symtable("def some_func(): pass", "string", "exec")
         >>> table.lookup("some_func").is_namespace()
         True

      Note that a single name can be bound to multiple objects.  If the result
      is ``True``, the name may also be bound to other objects, like an int or
      list, that does not introduce a new namespace.

   .. method:: get_namespaces()

      Return a list of namespaces bound to this name.

   .. method:: get_namespace()

      Return the namespace bound to this name.  If more than one namespace is
      bound, a :exc:`ValueError` is raised.
PK
%�\{�a ���!html/_sources/library/sys.rst.txtnu�[���:mod:`sys` --- System-specific parameters and functions
=======================================================

.. module:: sys
   :synopsis: Access system-specific parameters and functions.


This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter. It is
always available.


.. data:: argv

   The list of command line arguments passed to a Python script. ``argv[0]`` is the
   script name (it is operating system dependent whether this is a full pathname or
   not).  If the command was executed using the :option:`-c` command line option to
   the interpreter, ``argv[0]`` is set to the string ``'-c'``.  If no script name
   was passed to the Python interpreter, ``argv[0]`` is the empty string.

   To loop over the standard input, or the list of files given on the
   command line, see the :mod:`fileinput` module.


.. data:: byteorder

   An indicator of the native byte order.  This will have the value ``'big'`` on
   big-endian (most-significant byte first) platforms, and ``'little'`` on
   little-endian (least-significant byte first) platforms.

   .. versionadded:: 2.0


.. data:: builtin_module_names

   A tuple of strings giving the names of all modules that are compiled into this
   Python interpreter.  (This information is not available in any other way ---
   ``modules.keys()`` only lists the imported modules.)


.. function:: call_tracing(func, args)

   Call ``func(*args)``, while tracing is enabled.  The tracing state is saved,
   and restored afterwards.  This is intended to be called from a debugger from
   a checkpoint, to recursively debug some other code.


.. data:: copyright

   A string containing the copyright pertaining to the Python interpreter.


.. function:: _clear_type_cache()

   Clear the internal type cache. The type cache is used to speed up attribute
   and method lookups. Use the function *only* to drop unnecessary references
   during reference leak debugging.

   This function should be used for internal and specialized purposes only.

   .. versionadded:: 2.6


.. function:: _current_frames()

   Return a dictionary mapping each thread's identifier to the topmost stack frame
   currently active in that thread at the time the function is called. Note that
   functions in the :mod:`traceback` module can build the call stack given such a
   frame.

   This is most useful for debugging deadlock:  this function does not require the
   deadlocked threads' cooperation, and such threads' call stacks are frozen for as
   long as they remain deadlocked.  The frame returned for a non-deadlocked thread
   may bear no relationship to that thread's current activity by the time calling
   code examines the frame.

   This function should be used for internal and specialized purposes only.

   .. versionadded:: 2.5


.. data:: dllhandle

   Integer specifying the handle of the Python DLL. Availability: Windows.


.. function:: displayhook(value)

   If *value* is not ``None``, this function prints it to ``sys.stdout``, and saves
   it in ``__builtin__._``.

   ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
   entered in an interactive Python session.  The display of these values can be
   customized by assigning another one-argument function to ``sys.displayhook``.


.. data:: dont_write_bytecode

   If this is true, Python won't try to write ``.pyc`` or ``.pyo`` files on the
   import of source modules.  This value is initially set to ``True`` or
   ``False`` depending on the :option:`-B` command line option and the
   :envvar:`PYTHONDONTWRITEBYTECODE` environment variable, but you can set it
   yourself to control bytecode file generation.

   .. versionadded:: 2.6


.. function:: excepthook(type, value, traceback)

   This function prints out a given traceback and exception to ``sys.stderr``.

   When an exception is raised and uncaught, the interpreter calls
   ``sys.excepthook`` with three arguments, the exception class, exception
   instance, and a traceback object.  In an interactive session this happens just
   before control is returned to the prompt; in a Python program this happens just
   before the program exits.  The handling of such top-level exceptions can be
   customized by assigning another three-argument function to ``sys.excepthook``.


.. data:: __displayhook__
          __excepthook__

   These objects contain the original values of ``displayhook`` and ``excepthook``
   at the start of the program.  They are saved so that ``displayhook`` and
   ``excepthook`` can be restored in case they happen to get replaced with broken
   objects.


.. function:: exc_info()

   This function returns a tuple of three values that give information about the
   exception that is currently being handled.  The information returned is specific
   both to the current thread and to the current stack frame.  If the current stack
   frame is not handling an exception, the information is taken from the calling
   stack frame, or its caller, and so on until a stack frame is found that is
   handling an exception.  Here, "handling an exception" is defined as "executing
   or having executed an except clause."  For any stack frame, only information
   about the most recently handled exception is accessible.

   .. index:: object: traceback

   If no exception is being handled anywhere on the stack, a tuple containing three
   ``None`` values is returned.  Otherwise, the values returned are ``(type, value,
   traceback)``.  Their meaning is: *type* gets the exception type of the exception
   being handled (a class object); *value* gets the exception parameter (its
   :dfn:`associated value` or the second argument to :keyword:`raise`, which is
   always a class instance if the exception type is a class object); *traceback*
   gets a traceback object (see the Reference Manual) which encapsulates the call
   stack at the point where the exception originally occurred.

   If :func:`exc_clear` is called, this function will return three ``None`` values
   until either another exception is raised in the current thread or the execution
   stack returns to a frame where another exception is being handled.

   .. warning::

      Assigning the *traceback* return value to a local variable in a function that is
      handling an exception will cause a circular reference.  This will prevent
      anything referenced by a local variable in the same function or by the traceback
      from being garbage collected.  Since most functions don't need access to the
      traceback, the best solution is to use something like ``exctype, value =
      sys.exc_info()[:2]`` to extract only the exception type and value.  If you do
      need the traceback, make sure to delete it after use (best done with a
      :keyword:`try` ... :keyword:`finally` statement) or to call :func:`exc_info` in
      a function that does not itself handle an exception.

   .. note::

      Beginning with Python 2.2, such cycles are automatically reclaimed when garbage
      collection is enabled and they become unreachable, but it remains more efficient
      to avoid creating cycles.


.. function:: exc_clear()

   This function clears all information relating to the current or last exception
   that occurred in the current thread.  After calling this function,
   :func:`exc_info` will return three ``None`` values until another exception is
   raised in the current thread or the execution stack returns to a frame where
   another exception is being handled.

   This function is only needed in only a few obscure situations.  These include
   logging and error handling systems that report information on the last or
   current exception.  This function can also be used to try to free resources and
   trigger object finalization, though no guarantee is made as to what objects will
   be freed, if any.

   .. versionadded:: 2.3


.. data:: exc_type
          exc_value
          exc_traceback

   .. deprecated:: 1.5
      Use :func:`exc_info` instead.

   Since they are global variables, they are not specific to the current thread, so
   their use is not safe in a multi-threaded program.  When no exception is being
   handled, ``exc_type`` is set to ``None`` and the other two are undefined.


.. data:: exec_prefix

   A string giving the site-specific directory prefix where the platform-dependent
   Python files are installed; by default, this is also ``'/usr/local'``.  This can
   be set at build time with the ``--exec-prefix`` argument to the
   :program:`configure` script.  Specifically, all configuration files (e.g. the
   :file:`pyconfig.h` header file) are installed in the directory
   :file:`{exec_prefix}/lib/python{X.Y}/config`, and shared library modules are
   installed in :file:`{exec_prefix}/lib/python{X.Y}/lib-dynload`, where *X.Y*
   is the version number of Python, for example ``2.7``.


.. data:: executable

   A string giving the absolute path of the executable binary for the Python
   interpreter, on systems where this makes sense. If Python is unable to retrieve
   the real path to its executable, :data:`sys.executable` will be an empty string
   or ``None``.


.. function:: exit([arg])

   Exit from Python.  This is implemented by raising the :exc:`SystemExit`
   exception, so cleanup actions specified by finally clauses of :keyword:`try`
   statements are honored, and it is possible to intercept the exit attempt at
   an outer level.

   The optional argument *arg* can be an integer giving the exit status
   (defaulting to zero), or another type of object.  If it is an integer, zero
   is considered "successful termination" and any nonzero value is considered
   "abnormal termination" by shells and the like.  Most systems require it to be
   in the range 0--127, and produce undefined results otherwise.  Some systems
   have a convention for assigning specific meanings to specific exit codes, but
   these are generally underdeveloped; Unix programs generally use 2 for command
   line syntax errors and 1 for all other kind of errors.  If another type of
   object is passed, ``None`` is equivalent to passing zero, and any other
   object is printed to :data:`stderr` and results in an exit code of 1.  In
   particular, ``sys.exit("some error message")`` is a quick way to exit a
   program when an error occurs.

   Since :func:`exit` ultimately "only" raises an exception, it will only exit
   the process when called from the main thread, and the exception is not
   intercepted.


.. data:: exitfunc

   This value is not actually defined by the module, but can be set by the user (or
   by a program) to specify a clean-up action at program exit.  When set, it should
   be a parameterless function.  This function will be called when the interpreter
   exits.  Only one function may be installed in this way; to allow multiple
   functions which will be called at termination, use the :mod:`atexit` module.

   .. note::

      The exit function is not called when the program is killed by a signal, when a
      Python fatal internal error is detected, or when ``os._exit()`` is called.

   .. deprecated:: 2.4
      Use :mod:`atexit` instead.


.. data:: flags

   The struct sequence *flags* exposes the status of command line flags. The
   attributes are read only.

   ============================= ===================================
   attribute                     flag
   ============================= ===================================
   :const:`debug`                :option:`-d`
   :const:`py3k_warning`         :option:`-3`
   :const:`division_warning`     :option:`-Q`
   :const:`division_new`         :option:`-Qnew <-Q>`
   :const:`inspect`              :option:`-i`
   :const:`interactive`          :option:`-i`
   :const:`optimize`             :option:`-O` or :option:`-OO`
   :const:`dont_write_bytecode`  :option:`-B`
   :const:`no_user_site`         :option:`-s`
   :const:`no_site`              :option:`-S`
   :const:`ignore_environment`   :option:`-E`
   :const:`tabcheck`             :option:`-t` or :option:`-tt <-t>`
   :const:`verbose`              :option:`-v`
   :const:`unicode`              :option:`-U`
   :const:`bytes_warning`        :option:`-b`
   :const:`hash_randomization`   :option:`-R`
   ============================= ===================================

   .. versionadded:: 2.6

   .. versionadded:: 2.7.3
      The ``hash_randomization`` attribute.

.. data:: float_info

   A structseq holding information about the float type. It contains low level
   information about the precision and internal representation.  The values
   correspond to the various floating-point constants defined in the standard
   header file :file:`float.h` for the 'C' programming language; see section
   5.2.4.2.2 of the 1999 ISO/IEC C standard [C99]_, 'Characteristics of
   floating types', for details.

   .. tabularcolumns:: |l|l|L|

   +---------------------+----------------+--------------------------------------------------+
   | attribute           | float.h macro  | explanation                                      |
   +=====================+================+==================================================+
   | :const:`epsilon`    | DBL_EPSILON    | difference between 1 and the least value greater |
   |                     |                | than 1 that is representable as a float          |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`dig`        | DBL_DIG        | maximum number of decimal digits that can be     |
   |                     |                | faithfully represented in a float;  see below    |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`mant_dig`   | DBL_MANT_DIG   | float precision: the number of base-``radix``    |
   |                     |                | digits in the significand of a float             |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`max`        | DBL_MAX        | maximum representable finite float               |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`max_exp`    | DBL_MAX_EXP    | maximum integer e such that ``radix**(e-1)`` is  |
   |                     |                | a representable finite float                     |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`max_10_exp` | DBL_MAX_10_EXP | maximum integer e such that ``10**e`` is in the  |
   |                     |                | range of representable finite floats             |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`min`        | DBL_MIN        | minimum positive normalized float                |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`min_exp`    | DBL_MIN_EXP    | minimum integer e such that ``radix**(e-1)`` is  |
   |                     |                | a normalized float                               |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`min_10_exp` | DBL_MIN_10_EXP | minimum integer e such that ``10**e`` is a       |
   |                     |                | normalized float                                 |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`radix`      | FLT_RADIX      | radix of exponent representation                 |
   +---------------------+----------------+--------------------------------------------------+
   | :const:`rounds`     | FLT_ROUNDS     | integer constant representing the rounding mode  |
   |                     |                | used for arithmetic operations.  This reflects   |
   |                     |                | the value of the system FLT_ROUNDS macro at      |
   |                     |                | interpreter startup time.  See section 5.2.4.2.2 |
   |                     |                | of the C99 standard for an explanation of the    |
   |                     |                | possible values and their meanings.              |
   +---------------------+----------------+--------------------------------------------------+

   The attribute :attr:`sys.float_info.dig` needs further explanation.  If
   ``s`` is any string representing a decimal number with at most
   :attr:`sys.float_info.dig` significant digits, then converting ``s`` to a
   float and back again will recover a string representing the same decimal
   value::

      >>> import sys
      >>> sys.float_info.dig
      15
      >>> s = '3.14159265358979'    # decimal string with 15 significant digits
      >>> format(float(s), '.15g')  # convert to float and back -> same value
      '3.14159265358979'

   But for strings with more than :attr:`sys.float_info.dig` significant digits,
   this isn't always true::

      >>> s = '9876543211234567'    # 16 significant digits is too many!
      >>> format(float(s), '.16g')  # conversion changes value
      '9876543211234568'

   .. versionadded:: 2.6

.. data:: float_repr_style

   A string indicating how the :func:`repr` function behaves for
   floats.  If the string has value ``'short'`` then for a finite
   float ``x``, ``repr(x)`` aims to produce a short string with the
   property that ``float(repr(x)) == x``.  This is the usual behaviour
   in Python 2.7 and later.  Otherwise, ``float_repr_style`` has value
   ``'legacy'`` and ``repr(x)`` behaves in the same way as it did in
   versions of Python prior to 2.7.

   .. versionadded:: 2.7


.. function:: getcheckinterval()

   Return the interpreter's "check interval"; see :func:`setcheckinterval`.

   .. versionadded:: 2.3


.. function:: getdefaultencoding()

   Return the name of the current default string encoding used by the Unicode
   implementation.

   .. versionadded:: 2.0


.. function:: getdlopenflags()

   Return the current value of the flags that are used for :c:func:`dlopen` calls.
   The flag constants are defined in the :mod:`dl` and :mod:`DLFCN` modules.
   Availability: Unix.

   .. versionadded:: 2.2


.. function:: getfilesystemencoding()

   Return the name of the encoding used to convert Unicode filenames into system
   file names, or ``None`` if the system default encoding is used. The result value
   depends on the operating system:

   * On Mac OS X, the encoding is ``'utf-8'``.

   * On Unix, the encoding is the user's preference according to the result of
     nl_langinfo(CODESET), or ``None`` if the ``nl_langinfo(CODESET)``
     failed.

   * On Windows NT+, file names are Unicode natively, so no conversion is
     performed. :func:`getfilesystemencoding` still returns ``'mbcs'``, as
     this is the encoding that applications should use when they explicitly
     want to convert Unicode strings to byte strings that are equivalent when
     used as file names.

   * On Windows 9x, the encoding is ``'mbcs'``.

   .. versionadded:: 2.3


.. function:: getrefcount(object)

   Return the reference count of the *object*.  The count returned is generally one
   higher than you might expect, because it includes the (temporary) reference as
   an argument to :func:`getrefcount`.


.. function:: getrecursionlimit()

   Return the current value of the recursion limit, the maximum depth of the Python
   interpreter stack.  This limit prevents infinite recursion from causing an
   overflow of the C stack and crashing Python.  It can be set by
   :func:`setrecursionlimit`.


.. function:: getsizeof(object[, default])

   Return the size of an object in bytes. The object can be any type of
   object. All built-in objects will return correct results, but this
   does not have to hold true for third-party extensions as it is implementation
   specific.

   If given, *default* will be returned if the object does not provide means to
   retrieve the size.  Otherwise a :exc:`TypeError` will be raised.

   :func:`getsizeof` calls the object's ``__sizeof__`` method and adds an
   additional garbage collector overhead if the object is managed by the garbage
   collector.

   .. versionadded:: 2.6


.. function:: _getframe([depth])

   Return a frame object from the call stack.  If optional integer *depth* is
   given, return the frame object that many calls below the top of the stack.  If
   that is deeper than the call stack, :exc:`ValueError` is raised.  The default
   for *depth* is zero, returning the frame at the top of the call stack.

   .. impl-detail::

      This function should be used for internal and specialized purposes only.
      It is not guaranteed to exist in all implementations of Python.


.. function:: getprofile()

   .. index::
      single: profile function
      single: profiler

   Get the profiler function as set by :func:`setprofile`.

   .. versionadded:: 2.6


.. function:: gettrace()

   .. index::
      single: trace function
      single: debugger

   Get the trace function as set by :func:`settrace`.

   .. impl-detail::

      The :func:`gettrace` function is intended only for implementing debuggers,
      profilers, coverage tools and the like.  Its behavior is part of the
      implementation platform, rather than part of the language definition, and
      thus may not be available in all Python implementations.

   .. versionadded:: 2.6


.. function:: getwindowsversion()

   Return a named tuple describing the Windows version
   currently running.  The named elements are *major*, *minor*,
   *build*, *platform*, *service_pack*, *service_pack_minor*,
   *service_pack_major*, *suite_mask*, and *product_type*.
   *service_pack* contains a string while all other values are
   integers. The components can also be accessed by name, so
   ``sys.getwindowsversion()[0]`` is equivalent to
   ``sys.getwindowsversion().major``. For compatibility with prior
   versions, only the first 5 elements are retrievable by indexing.

   *platform* may be one of the following values:

   +-----------------------------------------+-------------------------+
   | Constant                                | Platform                |
   +=========================================+=========================+
   | :const:`0 (VER_PLATFORM_WIN32s)`        | Win32s on Windows 3.1   |
   +-----------------------------------------+-------------------------+
   | :const:`1 (VER_PLATFORM_WIN32_WINDOWS)` | Windows 95/98/ME        |
   +-----------------------------------------+-------------------------+
   | :const:`2 (VER_PLATFORM_WIN32_NT)`      | Windows NT/2000/XP/x64  |
   +-----------------------------------------+-------------------------+
   | :const:`3 (VER_PLATFORM_WIN32_CE)`      | Windows CE              |
   +-----------------------------------------+-------------------------+

   *product_type* may be one of the following values:

   +---------------------------------------+---------------------------------+
   | Constant                              | Meaning                         |
   +=======================================+=================================+
   | :const:`1 (VER_NT_WORKSTATION)`       | The system is a workstation.    |
   +---------------------------------------+---------------------------------+
   | :const:`2 (VER_NT_DOMAIN_CONTROLLER)` | The system is a domain          |
   |                                       | controller.                     |
   +---------------------------------------+---------------------------------+
   | :const:`3 (VER_NT_SERVER)`            | The system is a server, but not |
   |                                       | a domain controller.            |
   +---------------------------------------+---------------------------------+


   This function wraps the Win32 :c:func:`GetVersionEx` function; see the
   Microsoft documentation on :c:func:`OSVERSIONINFOEX` for more information
   about these fields.

   Availability: Windows.

   .. versionadded:: 2.3
   .. versionchanged:: 2.7
      Changed to a named tuple and added *service_pack_minor*,
      *service_pack_major*, *suite_mask*, and *product_type*.


.. data:: hexversion

   The version number encoded as a single integer.  This is guaranteed to increase
   with each version, including proper support for non-production releases.  For
   example, to test that the Python interpreter is at least version 1.5.2, use::

      if sys.hexversion >= 0x010502F0:
          # use some advanced feature
          ...
      else:
          # use an alternative implementation or warn the user
          ...

   This is called ``hexversion`` since it only really looks meaningful when viewed
   as the result of passing it to the built-in :func:`hex` function.  The
   ``version_info`` value may be used for a more human-friendly encoding of the
   same information.

   The ``hexversion`` is a 32-bit number with the following layout:

   +-------------------------+------------------------------------------------+
   | Bits (big endian order) | Meaning                                        |
   +=========================+================================================+
   | :const:`1-8`            |  ``PY_MAJOR_VERSION``  (the ``2`` in           |
   |                         |  ``2.1.0a3``)                                  |
   +-------------------------+------------------------------------------------+
   | :const:`9-16`           |  ``PY_MINOR_VERSION``  (the ``1`` in           |
   |                         |  ``2.1.0a3``)                                  |
   +-------------------------+------------------------------------------------+
   | :const:`17-24`          |  ``PY_MICRO_VERSION``  (the ``0`` in           |
   |                         |  ``2.1.0a3``)                                  |
   +-------------------------+------------------------------------------------+
   | :const:`25-28`          |  ``PY_RELEASE_LEVEL``  (``0xA`` for alpha,     |
   |                         |  ``0xB`` for beta, ``0xC`` for release         |
   |                         |  candidate and ``0xF`` for final)              |
   +-------------------------+------------------------------------------------+
   | :const:`29-32`          |  ``PY_RELEASE_SERIAL``  (the ``3`` in          |
   |                         |  ``2.1.0a3``, zero for final releases)         |
   +-------------------------+------------------------------------------------+

   Thus ``2.1.0a3`` is hexversion ``0x020100a3``.

   .. versionadded:: 1.5.2


.. data:: long_info

   A struct sequence that holds information about Python's
   internal representation of integers.  The attributes are read only.

   .. tabularcolumns:: |l|L|

   +-------------------------+----------------------------------------------+
   | Attribute               | Explanation                                  |
   +=========================+==============================================+
   | :const:`bits_per_digit` | number of bits held in each digit.  Python   |
   |                         | integers are stored internally in base       |
   |                         | ``2**long_info.bits_per_digit``              |
   +-------------------------+----------------------------------------------+
   | :const:`sizeof_digit`   | size in bytes of the C type used to          |
   |                         | represent a digit                            |
   +-------------------------+----------------------------------------------+

   .. versionadded:: 2.7


.. data:: last_type
          last_value
          last_traceback

   These three variables are not always defined; they are set when an exception is
   not handled and the interpreter prints an error message and a stack traceback.
   Their intended use is to allow an interactive user to import a debugger module
   and engage in post-mortem debugging without having to re-execute the command
   that caused the error.  (Typical use is ``import pdb; pdb.pm()`` to enter the
   post-mortem debugger; see chapter :ref:`debugger` for
   more information.)

   The meaning of the variables is the same as that of the return values from
   :func:`exc_info` above.  (Since there is only one interactive thread,
   thread-safety is not a concern for these variables, unlike for ``exc_type``
   etc.)


.. data:: maxint

   The largest positive integer supported by Python's regular integer type.  This
   is at least 2\*\*31-1.  The largest negative integer is ``-maxint-1`` --- the
   asymmetry results from the use of 2's complement binary arithmetic.

.. data:: maxsize

   The largest positive integer supported by the platform's Py_ssize_t type,
   and thus the maximum size lists, strings, dicts, and many other containers
   can have.

.. data:: maxunicode

   An integer giving the largest supported code point for a Unicode character.  The
   value of this depends on the configuration option that specifies whether Unicode
   characters are stored as UCS-2 or UCS-4.


.. data:: meta_path

    A list of :term:`finder` objects that have their :meth:`find_module`
    methods called to see if one of the objects can find the module to be
    imported. The :meth:`find_module` method is called at least with the
    absolute name of the module being imported. If the module to be imported is
    contained in package then the parent package's :attr:`__path__` attribute
    is passed in as a second argument. The method returns ``None`` if
    the module cannot be found, else returns a :term:`loader`.

    :data:`sys.meta_path` is searched before any implicit default finders or
    :data:`sys.path`.

    See :pep:`302` for the original specification.


.. data:: modules

   .. index:: builtin: reload

   This is a dictionary that maps module names to modules which have already been
   loaded.  This can be manipulated to force reloading of modules and other tricks.
   Note that removing a module from this dictionary is *not* the same as calling
   :func:`reload` on the corresponding module object.


.. data:: path

   .. index:: triple: module; search; path

   A list of strings that specifies the search path for modules. Initialized from
   the environment variable :envvar:`PYTHONPATH`, plus an installation-dependent
   default.

   As initialized upon program startup, the first item of this list, ``path[0]``,
   is the directory containing the script that was used to invoke the Python
   interpreter.  If the script directory is not available (e.g.  if the interpreter
   is invoked interactively or if the script is read from standard input),
   ``path[0]`` is the empty string, which directs Python to search modules in the
   current directory first.  Notice that the script directory is inserted *before*
   the entries inserted as a result of :envvar:`PYTHONPATH`.

   A program is free to modify this list for its own purposes.

   .. versionchanged:: 2.3
      Unicode strings are no longer ignored.

   .. seealso::
      Module :mod:`site` This describes how to use .pth files to extend
      :data:`sys.path`.


.. data:: path_hooks

    A list of callables that take a path argument to try to create a
    :term:`finder` for the path. If a finder can be created, it is to be
    returned by the callable, else raise :exc:`ImportError`.

    Originally specified in :pep:`302`.


.. data:: path_importer_cache

    A dictionary acting as a cache for :term:`finder` objects. The keys are
    paths that have been passed to :data:`sys.path_hooks` and the values are
    the finders that are found. If a path is a valid file system path but no
    explicit finder is found on :data:`sys.path_hooks` then ``None`` is
    stored to represent the implicit default finder should be used. If the path
    is not an existing path then :class:`imp.NullImporter` is set.

    Originally specified in :pep:`302`.


.. data:: platform

   This string contains a platform identifier that can be used to append
   platform-specific components to :data:`sys.path`, for instance.

   For most Unix systems, this is the lowercased OS name as returned by ``uname
   -s`` with the first part of the version as returned by ``uname -r`` appended,
   e.g. ``'sunos5'``, *at the time when Python was built*.  Unless you want to
   test for a specific system version, it is therefore recommended to use the
   following idiom::

      if sys.platform.startswith('freebsd'):
          # FreeBSD-specific code here...
      elif sys.platform.startswith('linux'):
          # Linux-specific code here...

   .. versionchanged:: 2.7.3
      Since lots of code check for ``sys.platform == 'linux2'``, and there is
      no essential change between Linux 2.x and 3.x, ``sys.platform`` is always
      set to ``'linux2'``, even on Linux 3.x.  In Python 3.3 and later, the
      value will always be set to ``'linux'``, so it is recommended to always
      use the ``startswith`` idiom presented above.

   For other systems, the values are:

   ===================== ===========================
   System                :data:`platform` value
   ===================== ===========================
   Linux (2.x *and* 3.x) ``'linux2'``
   Windows               ``'win32'``
   Windows/Cygwin        ``'cygwin'``
   Mac OS X              ``'darwin'``
   OS/2                  ``'os2'``
   OS/2 EMX              ``'os2emx'``
   RiscOS                ``'riscos'``
   AtheOS                ``'atheos'``
   ===================== ===========================

   .. seealso::
      :attr:`os.name` has a coarser granularity.  :func:`os.uname` gives
      system-dependent version information.

      The :mod:`platform` module provides detailed checks for the
      system's identity.

.. data:: prefix

   A string giving the site-specific directory prefix where the platform
   independent Python files are installed; by default, this is the string
   ``'/usr/local'``.  This can be set at build time with the ``--prefix``
   argument to the :program:`configure` script.  The main collection of Python
   library modules is installed in the directory :file:`{prefix}/lib/python{X.Y}`
   while the platform independent header files (all except :file:`pyconfig.h`) are
   stored in :file:`{prefix}/include/python{X.Y}`, where *X.Y* is the version
   number of Python, for example ``2.7``.


.. data:: ps1
          ps2

   .. index::
      single: interpreter prompts
      single: prompts, interpreter

   Strings specifying the primary and secondary prompt of the interpreter.  These
   are only defined if the interpreter is in interactive mode.  Their initial
   values in this case are ``'>>> '`` and ``'... '``.  If a non-string object is
   assigned to either variable, its :func:`str` is re-evaluated each time the
   interpreter prepares to read a new interactive command; this can be used to
   implement a dynamic prompt.


.. data:: py3kwarning

   Bool containing the status of the Python 3 warning flag. It's ``True``
   when Python is started with the -3 option.  (This should be considered
   read-only; setting it to a different value doesn't have an effect on
   Python 3 warnings.)

   .. versionadded:: 2.6


.. function:: setcheckinterval(interval)

   Set the interpreter's "check interval".  This integer value determines how often
   the interpreter checks for periodic things such as thread switches and signal
   handlers.  The default is ``100``, meaning the check is performed every 100
   Python virtual instructions. Setting it to a larger value may increase
   performance for programs using threads.  Setting it to a value ``<=`` 0 checks
   every virtual instruction, maximizing responsiveness as well as overhead.


.. function:: setdefaultencoding(name)

   Set the current default string encoding used by the Unicode implementation.  If
   *name* does not match any available encoding, :exc:`LookupError` is raised.
   This function is only intended to be used by the :mod:`site` module
   implementation and, where needed, by :mod:`sitecustomize`.  Once used by the
   :mod:`site` module, it is removed from the :mod:`sys` module's namespace.

   .. Note that :mod:`site` is not imported if the :option:`-S` option is passed
      to the interpreter, in which case this function will remain available.

   .. versionadded:: 2.0


.. function:: setdlopenflags(n)

   Set the flags used by the interpreter for :c:func:`dlopen` calls, such as when
   the interpreter loads extension modules.  Among other things, this will enable a
   lazy resolving of symbols when importing a module, if called as
   ``sys.setdlopenflags(0)``.  To share symbols across extension modules, call as
   ``sys.setdlopenflags(dl.RTLD_NOW | dl.RTLD_GLOBAL)``.  Symbolic names for the
   flag modules can be either found in the :mod:`dl` module, or in the :mod:`DLFCN`
   module. If :mod:`DLFCN` is not available, it can be generated from
   :file:`/usr/include/dlfcn.h` using the :program:`h2py` script. Availability:
   Unix.

   .. versionadded:: 2.2


.. function:: setprofile(profilefunc)

   .. index::
      single: profile function
      single: profiler

   Set the system's profile function, which allows you to implement a Python source
   code profiler in Python.  See chapter :ref:`profile` for more information on the
   Python profiler.  The system's profile function is called similarly to the
   system's trace function (see :func:`settrace`), but it is called with different events,
   for example it isn't called for each executed line of code (only on call and return,
   but the return event is reported even when an exception has been set). The function is
   thread-specific, but there is no way for the profiler to know about context switches between
   threads, so it does not make sense to use this in the presence of multiple threads. Also,
   its return value is not used, so it can simply return ``None``.

   Profile functions should have three arguments: *frame*, *event*, and
   *arg*. *frame* is the current stack frame.  *event* is a string: ``'call'``,
   ``'return'``, ``'c_call'``, ``'c_return'``, or ``'c_exception'``. *arg* depends
   on the event type.

   The events have the following meaning:

   ``'call'``
      A function is called (or some other code block entered).  The
      profile function is called; *arg* is ``None``.

   ``'return'``
      A function (or other code block) is about to return.  The profile
      function is called; *arg* is the value that will be returned, or ``None``
      if the event is caused by an exception being raised.

   ``'c_call'``
      A C function is about to be called.  This may be an extension function or
      a built-in.  *arg* is the C function object.

   ``'c_return'``
      A C function has returned. *arg* is the C function object.

   ``'c_exception'``
      A C function has raised an exception.  *arg* is the C function object.

.. function:: setrecursionlimit(limit)

   Set the maximum depth of the Python interpreter stack to *limit*.  This limit
   prevents infinite recursion from causing an overflow of the C stack and crashing
   Python.

   The highest possible limit is platform-dependent.  A user may need to set the
   limit higher when she has a program that requires deep recursion and a platform
   that supports a higher limit.  This should be done with care, because a too-high
   limit can lead to a crash.


.. function:: settrace(tracefunc)

   .. index::
      single: trace function
      single: debugger

   Set the system's trace function, which allows you to implement a Python
   source code debugger in Python.  The function is thread-specific; for a
   debugger to support multiple threads, it must be registered using
   :func:`settrace` for each thread being debugged.

   Trace functions should have three arguments: *frame*, *event*, and
   *arg*. *frame* is the current stack frame.  *event* is a string: ``'call'``,
   ``'line'``, ``'return'`` or ``'exception'``.  *arg* depends on
   the event type.

   The trace function is invoked (with *event* set to ``'call'``) whenever a new
   local scope is entered; it should return a reference to a local trace
   function to be used that scope, or ``None`` if the scope shouldn't be traced.

   The local trace function should return a reference to itself (or to another
   function for further tracing in that scope), or ``None`` to turn off tracing
   in that scope.

   The events have the following meaning:

   ``'call'``
      A function is called (or some other code block entered).  The
      global trace function is called; *arg* is ``None``; the return value
      specifies the local trace function.

   ``'line'``
      The interpreter is about to execute a new line of code or re-execute the
      condition of a loop.  The local trace function is called; *arg* is
      ``None``; the return value specifies the new local trace function.  See
      :file:`Objects/lnotab_notes.txt` for a detailed explanation of how this
      works.

   ``'return'``
      A function (or other code block) is about to return.  The local trace
      function is called; *arg* is the value that will be returned, or ``None``
      if the event is caused by an exception being raised.  The trace function's
      return value is ignored.

   ``'exception'``
      An exception has occurred.  The local trace function is called; *arg* is a
      tuple ``(exception, value, traceback)``; the return value specifies the
      new local trace function.

   Note that as an exception is propagated down the chain of callers, an
   ``'exception'`` event is generated at each level.

   For more information on code and frame objects, refer to :ref:`types`.

   .. impl-detail::

      The :func:`settrace` function is intended only for implementing debuggers,
      profilers, coverage tools and the like.  Its behavior is part of the
      implementation platform, rather than part of the language definition, and
      thus may not be available in all Python implementations.


.. function:: settscdump(on_flag)

   Activate dumping of VM measurements using the Pentium timestamp counter, if
   *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
   available only if Python was compiled with ``--with-tsc``. To understand
   the output of this dump, read :file:`Python/ceval.c` in the Python sources.

   .. versionadded:: 2.4

   .. impl-detail::

      This function is intimately bound to CPython implementation details and
      thus not likely to be implemented elsewhere.


.. data:: stdin
          stdout
          stderr

   .. index::
      builtin: input
      builtin: raw_input

   File objects corresponding to the interpreter's standard input, output and error
   streams.  ``stdin`` is used for all interpreter input except for scripts but
   including calls to :func:`input` and :func:`raw_input`.  ``stdout`` is used for
   the output of :keyword:`print` and :term:`expression` statements and for the
   prompts of :func:`input` and :func:`raw_input`. The interpreter's own prompts
   and (almost all of) its error messages go to ``stderr``.  ``stdout`` and
   ``stderr`` needn't be built-in file objects: any object is acceptable as long
   as it has a :meth:`write` method that takes a string argument.  (Changing these
   objects doesn't affect the standard I/O streams of processes executed by
   :func:`os.popen`, :func:`os.system` or the :func:`exec\*` family of functions in
   the :mod:`os` module.)


.. data:: __stdin__
          __stdout__
          __stderr__

   These objects contain the original values of ``stdin``, ``stderr`` and
   ``stdout`` at the start of the program.  They are used during finalization,
   and could be useful to print to the actual standard stream no matter if the
   ``sys.std*`` object has been redirected.

   It can also be used to restore the actual files to known working file objects
   in case they have been overwritten with a broken object.  However, the
   preferred way to do this is to explicitly save the previous stream before
   replacing it, and restore the saved object.


.. data:: subversion

   A triple (repo, branch, version) representing the Subversion information of the
   Python interpreter. *repo* is the name of the repository, ``'CPython'``.
   *branch* is a string of one of the forms ``'trunk'``, ``'branches/name'`` or
   ``'tags/name'``. *version* is the output of ``svnversion``, if the interpreter
   was built from a Subversion checkout; it contains the revision number (range)
   and possibly a trailing 'M' if there were local modifications. If the tree was
   exported (or svnversion was not available), it is the revision of
   ``Include/patchlevel.h`` if the branch is a tag. Otherwise, it is ``None``.

   .. versionadded:: 2.5

   .. note::
      Python is now `developed <https://docs.python.org/devguide/>`_ using
      Mercurial.  In recent Python 2.7 bugfix releases, :data:`subversion`
      therefore contains placeholder information.  It is removed in Python
      3.3.


.. data:: tracebacklimit

   When this variable is set to an integer value, it determines the maximum number
   of levels of traceback information printed when an unhandled exception occurs.
   The default is ``1000``.  When set to ``0`` or less, all traceback information
   is suppressed and only the exception type and value are printed.


.. data:: version

   A string containing the version number of the Python interpreter plus additional
   information on the build number and compiler used.  This string is displayed
   when the interactive interpreter is started.  Do not extract version information
   out of it, rather, use :data:`version_info` and the functions provided by the
   :mod:`platform` module.


.. data:: api_version

   The C API version for this interpreter.  Programmers may find this useful when
   debugging version conflicts between Python and extension modules.

   .. versionadded:: 2.3


.. data:: version_info

   A tuple containing the five components of the version number: *major*, *minor*,
   *micro*, *releaselevel*, and *serial*.  All values except *releaselevel* are
   integers; the release level is ``'alpha'``, ``'beta'``, ``'candidate'``, or
   ``'final'``.  The ``version_info`` value corresponding to the Python version 2.0
   is ``(2, 0, 0, 'final', 0)``.  The components can also be accessed by name,
   so ``sys.version_info[0]`` is equivalent to ``sys.version_info.major``
   and so on.

   .. versionadded:: 2.0
   .. versionchanged:: 2.7
      Added named component attributes


.. data:: warnoptions

   This is an implementation detail of the warnings framework; do not modify this
   value.  Refer to the :mod:`warnings` module for more information on the warnings
   framework.


.. data:: winver

   The version number used to form registry keys on Windows platforms. This is
   stored as string resource 1000 in the Python DLL.  The value is normally the
   first three characters of :const:`version`.  It is provided in the :mod:`sys`
   module for informational purposes; modifying this value has no effect on the
   registry keys used by Python. Availability: Windows.

.. rubric:: Citations

.. [C99] ISO/IEC 9899:1999.  "Programming languages -- C."  A public draft of this standard is available at http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\ .
PK
%�\|�����'html/_sources/library/sysconfig.rst.txtnu�[���:mod:`sysconfig` --- Provide access to Python's configuration information
=========================================================================

.. module:: sysconfig
   :synopsis: Python's configuration information
.. moduleauthor:: Tarek Ziade <tarek@ziade.org>
.. sectionauthor:: Tarek Ziade <tarek@ziade.org>
.. index::
   single: configuration information

.. versionadded:: 2.7

**Source code:** :source:`Lib/sysconfig.py`

--------------

The :mod:`sysconfig` module provides access to Python's configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.

Configuration variables
-----------------------

A Python distribution contains a :file:`Makefile` and a :file:`pyconfig.h`
header file that are necessary to build both the Python binary itself and
third-party C extensions compiled using :mod:`distutils`.

:mod:`sysconfig` puts all variables found in these files in a dictionary that
can be accessed using :func:`get_config_vars` or :func:`get_config_var`.

Notice that on Windows, it's a much smaller set.

.. function:: get_config_vars(\*args)

   With no arguments, return a dictionary of all configuration variables
   relevant for the current platform.

   With arguments, return a list of values that result from looking up each
   argument in the configuration variable dictionary.

   For each argument, if the value is not found, return ``None``.


.. function:: get_config_var(name)

   Return the value of a single variable *name*. Equivalent to
   ``get_config_vars().get(name)``.

   If *name* is not found, return ``None``.

Example of usage::

   >>> import sysconfig
   >>> sysconfig.get_config_var('Py_ENABLE_SHARED')
   0
   >>> sysconfig.get_config_var('LIBDIR')
   '/usr/local/lib'
   >>> sysconfig.get_config_vars('AR', 'CXX')
   ['ar', 'g++']


Installation paths
------------------

Python uses an installation scheme that differs depending on the platform and on
the installation options.  These schemes are stored in :mod:`sysconfig` under
unique identifiers based on the value returned by :const:`os.name`.

Every new component that is installed using :mod:`distutils` or a
Distutils-based system will follow the same scheme to copy its file in the right
places.

Python currently supports seven schemes:

- *posix_prefix*: scheme for Posix platforms like Linux or Mac OS X.  This is
  the default scheme used when Python or a component is installed.
- *posix_home*: scheme for Posix platforms used when a *home* option is used
  upon installation.  This scheme is used when a component is installed through
  Distutils with a specific home prefix.
- *posix_user*: scheme for Posix platforms used when a component is installed
  through Distutils and the *user* option is used.  This scheme defines paths
  located under the user home directory.
- *nt*: scheme for NT platforms like Windows.
- *nt_user*: scheme for NT platforms, when the *user* option is used.
- *os2*: scheme for OS/2 platforms.
- *os2_home*: scheme for OS/2 platforms, when the *user* option is used.

Each scheme is itself composed of a series of paths and each path has a unique
identifier.  Python currently uses eight paths:

- *stdlib*: directory containing the standard Python library files that are not
  platform-specific.
- *platstdlib*: directory containing the standard Python library files that are
  platform-specific.
- *platlib*: directory for site-specific, platform-specific files.
- *purelib*: directory for site-specific, non-platform-specific files.
- *include*: directory for non-platform-specific header files.
- *platinclude*: directory for platform-specific header files.
- *scripts*: directory for script files.
- *data*: directory for data files.

:mod:`sysconfig` provides some functions to determine these paths.

.. function:: get_scheme_names()

   Return a tuple containing all schemes currently supported in
   :mod:`sysconfig`.


.. function:: get_path_names()

   Return a tuple containing all path names currently supported in
   :mod:`sysconfig`.


.. function:: get_path(name, [scheme, [vars, [expand]]])

   Return an installation path corresponding to the path *name*, from the
   install scheme named *scheme*.

   *name* has to be a value from the list returned by :func:`get_path_names`.

   :mod:`sysconfig` stores installation paths corresponding to each path name,
   for each platform, with variables to be expanded.  For instance the *stdlib*
   path for the *nt* scheme is: ``{base}/Lib``.

   :func:`get_path` will use the variables returned by :func:`get_config_vars`
   to expand the path.  All variables have default values for each platform so
   one may call this function and get the default value.

   If *scheme* is provided, it must be a value from the list returned by
   :func:`get_scheme_names`.  Otherwise, the default scheme for the current
   platform is used.

   If *vars* is provided, it must be a dictionary of variables that will update
   the dictionary return by :func:`get_config_vars`.

   If *expand* is set to ``False``, the path will not be expanded using the
   variables.

   If *name* is not found, return ``None``.


.. function:: get_paths([scheme, [vars, [expand]]])

   Return a dictionary containing all installation paths corresponding to an
   installation scheme. See :func:`get_path` for more information.

   If *scheme* is not provided, will use the default scheme for the current
   platform.

   If *vars* is provided, it must be a dictionary of variables that will
   update the dictionary used to expand the paths.

   If *expand* is set to false, the paths will not be expanded.

   If *scheme* is not an existing scheme, :func:`get_paths` will raise a
   :exc:`KeyError`.


Other functions
---------------

.. function:: get_python_version()

   Return the ``MAJOR.MINOR`` Python version number as a string.  Similar to
   ``sys.version[:3]``.


.. function:: get_platform()

   Return a string that identifies the current platform.

   This is used mainly to distinguish platform-specific build directories and
   platform-specific built distributions.  Typically includes the OS name and
   version and the architecture (as supplied by :func:`os.uname`), although the
   exact information included depends on the OS; e.g. for IRIX the architecture
   isn't particularly important (IRIX only runs on SGI hardware), but for Linux
   the kernel version isn't particularly important.

   Examples of returned values:

   - linux-i586
   - linux-alpha (?)
   - solaris-2.6-sun4u
   - irix-5.3
   - irix64-6.2

   Windows will return one of:

   - win-amd64 (64bit Windows on AMD64, aka x86_64, Intel64, and EM64T)
   - win-ia64 (64bit Windows on Itanium)
   - win32 (all others - specifically, sys.platform is returned)

   Mac OS X can return:

   - macosx-10.6-ppc
   - macosx-10.4-ppc64
   - macosx-10.3-i386
   - macosx-10.4-fat

   For other non-POSIX platforms, currently just returns :data:`sys.platform`.


.. function:: is_python_build()

   Return ``True`` if the current Python installation was built from source.


.. function:: parse_config_h(fp[, vars])

   Parse a :file:`config.h`\-style file.

   *fp* is a file-like object pointing to the :file:`config.h`\-like file.

   A dictionary containing name/value pairs is returned.  If an optional
   dictionary is passed in as the second argument, it is used instead of a new
   dictionary, and updated with the values read in the file.


.. function:: get_config_h_filename()

   Return the path of :file:`pyconfig.h`.

.. function:: get_makefile_filename()

   Return the path of :file:`Makefile`.
PK
%�\$���[[$html/_sources/library/syslog.rst.txtnu�[���:mod:`syslog` --- Unix syslog library routines
==============================================

.. module:: syslog
   :platform: Unix
   :synopsis: An interface to the Unix syslog library routines.


This module provides an interface to the Unix ``syslog`` library routines.
Refer to the Unix manual pages for a detailed description of the ``syslog``
facility.

This module wraps the system ``syslog`` family of routines.  A pure Python
library that can speak to a syslog server is available in the
:mod:`logging.handlers` module as :class:`SysLogHandler`.

The module defines the following functions:


.. function:: syslog(message)
              syslog(priority, message)

   Send the string *message* to the system logger.  A trailing newline is added
   if necessary.  Each message is tagged with a priority composed of a
   *facility* and a *level*.  The optional *priority* argument, which defaults
   to :const:`LOG_INFO`, determines the message priority.  If the facility is
   not encoded in *priority* using logical-or (``LOG_INFO | LOG_USER``), the
   value given in the :func:`openlog` call is used.

   If :func:`openlog` has not been called prior to the call to :func:`syslog`,
   ``openlog()`` will be called with no arguments.


.. function:: openlog([ident[, logoption[, facility]]])

   Logging options of subsequent :func:`syslog` calls can be set by calling
   :func:`openlog`.  :func:`syslog` will call :func:`openlog` with no arguments
   if the log is not currently open.

   The optional *ident* keyword argument is a string which is prepended to every
   message, and defaults to ``sys.argv[0]`` with leading path components
   stripped.  The optional *logoption* keyword argument (default is 0) is a bit
   field -- see below for possible values to combine.  The optional *facility*
   keyword argument (default is :const:`LOG_USER`) sets the default facility for
   messages which do not have a facility explicitly encoded.


.. function:: closelog()

   Reset the syslog module values and call the system library ``closelog()``.

   This causes the module to behave as it does when initially imported.  For
   example, :func:`openlog` will be called on the first :func:`syslog` call (if
   :func:`openlog` hasn't already been called), and *ident* and other
   :func:`openlog` parameters are reset to defaults.


.. function:: setlogmask(maskpri)

   Set the priority mask to *maskpri* and return the previous mask value.  Calls
   to :func:`syslog` with a priority level not set in *maskpri* are ignored.
   The default is to log all priorities.  The function ``LOG_MASK(pri)``
   calculates the mask for the individual priority *pri*.  The function
   ``LOG_UPTO(pri)`` calculates the mask for all priorities up to and including
   *pri*.

The module defines the following constants:

Priority levels (high to low):
   :const:`LOG_EMERG`, :const:`LOG_ALERT`, :const:`LOG_CRIT`, :const:`LOG_ERR`,
   :const:`LOG_WARNING`, :const:`LOG_NOTICE`, :const:`LOG_INFO`,
   :const:`LOG_DEBUG`.

Facilities:
   :const:`LOG_KERN`, :const:`LOG_USER`, :const:`LOG_MAIL`, :const:`LOG_DAEMON`,
   :const:`LOG_AUTH`, :const:`LOG_LPR`, :const:`LOG_NEWS`, :const:`LOG_UUCP`,
   :const:`LOG_CRON`, :const:`LOG_SYSLOG` and :const:`LOG_LOCAL0` to
   :const:`LOG_LOCAL7`.

Log options:
   :const:`LOG_PID`, :const:`LOG_CONS`, :const:`LOG_NDELAY`, :const:`LOG_NOWAIT`
   and :const:`LOG_PERROR` if defined in ``<syslog.h>``.


Examples
--------

Simple example
~~~~~~~~~~~~~~

A simple set of examples::

   import syslog

   syslog.syslog('Processing started')
   if error:
       syslog.syslog(syslog.LOG_ERR, 'Processing started')

An example of setting some log options, these would include the process ID in
logged messages, and write the messages to the destination facility used for
mail logging::

   syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
   syslog.syslog('E-mail processing initiated...')
PK
%�\tB����&html/_sources/library/tabnanny.rst.txtnu�[���:mod:`tabnanny` --- Detection of ambiguous indentation
======================================================

.. module:: tabnanny
   :synopsis: Tool for detecting white space related problems in Python source files in a
              directory tree.
.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>

.. rudimentary documentation based on module comments

**Source code:** :source:`Lib/tabnanny.py`

--------------

For the time being this module is intended to be called as a script. However it
is possible to import it into an IDE and use the function :func:`check`
described below.

.. note::

   The API provided by this module is likely to change in future releases; such
   changes may not be backward compatible.


.. function:: check(file_or_dir)

   If *file_or_dir* is a directory and not a symbolic link, then recursively
   descend the directory tree named by *file_or_dir*, checking all :file:`.py`
   files along the way.  If *file_or_dir* is an ordinary Python source file, it is
   checked for whitespace related problems.  The diagnostic messages are written to
   standard output using the print statement.


.. data:: verbose

   Flag indicating whether to print verbose messages. This is incremented by the
   ``-v`` option if called as a script.


.. data:: filename_only

   Flag indicating whether to print only the filenames of files containing
   whitespace related problems.  This is set to true by the ``-q`` option if called
   as a script.


.. exception:: NannyNag

   Raised by :func:`process_tokens` if detecting an ambiguous indent. Captured and
   handled in :func:`check`.


.. function:: process_tokens(tokens)

   This function is used by :func:`check` to process tokens generated by the
   :mod:`tokenize` module.

.. XXX document errprint, format_witnesses, Whitespace, check_equal, indents,
   reset_globals


.. seealso::

   Module :mod:`tokenize`
      Lexical scanner for Python source code.
PK
%�\sS�/6n6n%html/_sources/library/tarfile.rst.txtnu�[���:mod:`tarfile` --- Read and write tar archive files
===================================================

.. module:: tarfile
   :synopsis: Read and write tar-format archive files.


.. versionadded:: 2.3

.. moduleauthor:: Lars Gustäbel <lars@gustaebel.de>
.. sectionauthor:: Lars Gustäbel <lars@gustaebel.de>

**Source code:** :source:`Lib/tarfile.py`

--------------

The :mod:`tarfile` module makes it possible to read and write tar
archives, including those using gzip or bz2 compression.
Use the :mod:`zipfile` module to read or write :file:`.zip` files, or the
higher-level functions in :ref:`shutil <archiving-operations>`.

Some facts and figures:

* reads and writes :mod:`gzip` and :mod:`bz2` compressed archives
  if the respective modules are available.

* read/write support for the POSIX.1-1988 (ustar) format.

* read/write support for the GNU tar format including *longname* and *longlink*
  extensions, read-only support for the *sparse* extension.

* read/write support for the POSIX.1-2001 (pax) format.

  .. versionadded:: 2.6

* handles directories, regular files, hardlinks, symbolic links, fifos,
  character devices and block devices and is able to acquire and restore file
  information like timestamp, access permissions and owner.

.. note::
   Handling of multi-stream bzip2 files is not supported.  Modules such as
   `bz2file <https://github.com/nvawda/bz2file>`_ let you overcome this.


.. function:: open(name=None, mode='r', fileobj=None, bufsize=10240, \*\*kwargs)

   Return a :class:`TarFile` object for the pathname *name*. For detailed
   information on :class:`TarFile` objects and the keyword arguments that are
   allowed, see :ref:`tarfile-objects`.

   *mode* has to be a string of the form ``'filemode[:compression]'``, it defaults
   to ``'r'``. Here is a full list of mode combinations:

   +------------------+---------------------------------------------+
   | mode             | action                                      |
   +==================+=============================================+
   | ``'r' or 'r:*'`` | Open for reading with transparent           |
   |                  | compression (recommended).                  |
   +------------------+---------------------------------------------+
   | ``'r:'``         | Open for reading exclusively without        |
   |                  | compression.                                |
   +------------------+---------------------------------------------+
   | ``'r:gz'``       | Open for reading with gzip compression.     |
   +------------------+---------------------------------------------+
   | ``'r:bz2'``      | Open for reading with bzip2 compression.    |
   +------------------+---------------------------------------------+
   | ``'a' or 'a:'``  | Open for appending with no compression. The |
   |                  | file is created if it does not exist.       |
   +------------------+---------------------------------------------+
   | ``'w' or 'w:'``  | Open for uncompressed writing.              |
   +------------------+---------------------------------------------+
   | ``'w:gz'``       | Open for gzip compressed writing.           |
   +------------------+---------------------------------------------+
   | ``'w:bz2'``      | Open for bzip2 compressed writing.          |
   +------------------+---------------------------------------------+

   Note that ``'a:gz'`` or ``'a:bz2'`` is not possible. If *mode* is not suitable
   to open a certain (compressed) file for reading, :exc:`ReadError` is raised. Use
   *mode* ``'r'`` to avoid this.  If a compression method is not supported,
   :exc:`CompressionError` is raised.

   If *fileobj* is specified, it is used as an alternative to a file object opened
   for *name*. It is supposed to be at position 0.

   For modes ``'w:gz'``, ``'r:gz'``, ``'w:bz2'``, ``'r:bz2'``, :func:`tarfile.open`
   accepts the keyword argument *compresslevel* (default ``9``) to
   specify the compression level of the file.

   For special purposes, there is a second format for *mode*:
   ``'filemode|[compression]'``.  :func:`tarfile.open` will return a :class:`TarFile`
   object that processes its data as a stream of blocks.  No random seeking will
   be done on the file. If given, *fileobj* may be any object that has a
   :meth:`read` or :meth:`write` method (depending on the *mode*). *bufsize*
   specifies the blocksize and defaults to ``20 * 512`` bytes. Use this variant
   in combination with e.g. ``sys.stdin``, a socket file object or a tape
   device. However, such a :class:`TarFile` object is limited in that it does
   not allow random access, see :ref:`tar-examples`.  The currently
   possible modes:

   +-------------+--------------------------------------------+
   | Mode        | Action                                     |
   +=============+============================================+
   | ``'r|*'``   | Open a *stream* of tar blocks for reading  |
   |             | with transparent compression.              |
   +-------------+--------------------------------------------+
   | ``'r|'``    | Open a *stream* of uncompressed tar blocks |
   |             | for reading.                               |
   +-------------+--------------------------------------------+
   | ``'r|gz'``  | Open a gzip compressed *stream* for        |
   |             | reading.                                   |
   +-------------+--------------------------------------------+
   | ``'r|bz2'`` | Open a bzip2 compressed *stream* for       |
   |             | reading.                                   |
   +-------------+--------------------------------------------+
   | ``'w|'``    | Open an uncompressed *stream* for writing. |
   +-------------+--------------------------------------------+
   | ``'w|gz'``  | Open a gzip compressed *stream* for        |
   |             | writing.                                   |
   +-------------+--------------------------------------------+
   | ``'w|bz2'`` | Open a bzip2 compressed *stream* for       |
   |             | writing.                                   |
   +-------------+--------------------------------------------+


.. class:: TarFile

   Class for reading and writing tar archives. Do not use this class directly,
   better use :func:`tarfile.open` instead. See :ref:`tarfile-objects`.


.. function:: is_tarfile(name)

   Return :const:`True` if *name* is a tar archive file, that the :mod:`tarfile`
   module can read.


.. class:: TarFileCompat(filename, mode='r', compression=TAR_PLAIN)

   Class for limited access to tar archives with a :mod:`zipfile`\ -like interface.
   Please consult the documentation of the :mod:`zipfile` module for more details.
   *compression* must be one of the following constants:


   .. data:: TAR_PLAIN

      Constant for an uncompressed tar archive.


   .. data:: TAR_GZIPPED

      Constant for a :mod:`gzip` compressed tar archive.


   .. deprecated:: 2.6
      The :class:`TarFileCompat` class has been removed in Python 3.


.. exception:: TarError

   Base class for all :mod:`tarfile` exceptions.


.. exception:: ReadError

   Is raised when a tar archive is opened, that either cannot be handled by the
   :mod:`tarfile` module or is somehow invalid.


.. exception:: CompressionError

   Is raised when a compression method is not supported or when the data cannot be
   decoded properly.


.. exception:: StreamError

   Is raised for the limitations that are typical for stream-like :class:`TarFile`
   objects.


.. exception:: ExtractError

   Is raised for *non-fatal* errors when using :meth:`TarFile.extract`, but only if
   :attr:`TarFile.errorlevel`\ ``== 2``.


The following constants are available at the module level:

.. data:: ENCODING

   The default character encoding: ``'utf-8'`` on Windows, the value returned by
   :func:`sys.getfilesystemencoding` otherwise.


.. exception:: HeaderError

   Is raised by :meth:`TarInfo.frombuf` if the buffer it gets is invalid.

   .. versionadded:: 2.6


Each of the following constants defines a tar archive format that the
:mod:`tarfile` module is able to create. See section :ref:`tar-formats` for
details.


.. data:: USTAR_FORMAT

   POSIX.1-1988 (ustar) format.


.. data:: GNU_FORMAT

   GNU tar format.


.. data:: PAX_FORMAT

   POSIX.1-2001 (pax) format.


.. data:: DEFAULT_FORMAT

   The default format for creating archives. This is currently :const:`GNU_FORMAT`.


.. seealso::

   Module :mod:`zipfile`
      Documentation of the :mod:`zipfile` standard module.

   :ref:`archiving-operations`
      Documentation of the higher-level archiving facilities provided by the
      standard :mod:`shutil` module.

   `GNU tar manual, Basic Tar Format <https://www.gnu.org/software/tar/manual/html_node/Standard.html>`_
      Documentation for tar archive files, including GNU tar extensions.


.. _tarfile-objects:

TarFile Objects
---------------

The :class:`TarFile` object provides an interface to a tar archive. A tar
archive is a sequence of blocks. An archive member (a stored file) is made up of
a header block followed by data blocks. It is possible to store a file in a tar
archive several times. Each archive member is represented by a :class:`TarInfo`
object, see :ref:`tarinfo-objects` for details.

A :class:`TarFile` object can be used as a context manager in a :keyword:`with`
statement. It will automatically be closed when the block is completed. Please
note that in the event of an exception an archive opened for writing will not
be finalized; only the internally used file object will be closed. See the
:ref:`tar-examples` section for a use case.

.. versionadded:: 2.7
   Added support for the context management protocol.

.. class:: TarFile(name=None, mode='r', fileobj=None, format=DEFAULT_FORMAT, tarinfo=TarInfo, dereference=False, ignore_zeros=False, encoding=ENCODING, errors=None, pax_headers=None, debug=0, errorlevel=0)

   All following arguments are optional and can be accessed as instance attributes
   as well.

   *name* is the pathname of the archive. It can be omitted if *fileobj* is given.
   In this case, the file object's :attr:`name` attribute is used if it exists.

   *mode* is either ``'r'`` to read from an existing archive, ``'a'`` to append
   data to an existing file or ``'w'`` to create a new file overwriting an existing
   one.

   If *fileobj* is given, it is used for reading or writing data. If it can be
   determined, *mode* is overridden by *fileobj*'s mode. *fileobj* will be used
   from position 0.

   .. note::

      *fileobj* is not closed, when :class:`TarFile` is closed.

   *format* controls the archive format. It must be one of the constants
   :const:`USTAR_FORMAT`, :const:`GNU_FORMAT` or :const:`PAX_FORMAT` that are
   defined at module level.

   .. versionadded:: 2.6

   The *tarinfo* argument can be used to replace the default :class:`TarInfo` class
   with a different one.

   .. versionadded:: 2.6

   If *dereference* is :const:`False`, add symbolic and hard links to the archive. If it
   is :const:`True`, add the content of the target files to the archive. This has no
   effect on systems that do not support symbolic links.

   If *ignore_zeros* is :const:`False`, treat an empty block as the end of the archive.
   If it is :const:`True`, skip empty (and invalid) blocks and try to get as many members
   as possible. This is only useful for reading concatenated or damaged archives.

   *debug* can be set from ``0`` (no debug messages) up to ``3`` (all debug
   messages). The messages are written to ``sys.stderr``.

   If *errorlevel* is ``0``, all errors are ignored when using :meth:`TarFile.extract`.
   Nevertheless, they appear as error messages in the debug output, when debugging
   is enabled.  If ``1``, all *fatal* errors are raised as :exc:`OSError` or
   :exc:`IOError` exceptions. If ``2``, all *non-fatal* errors are raised as
   :exc:`TarError` exceptions as well.

   The *encoding* and *errors* arguments control the way strings are converted to
   unicode objects and vice versa. The default settings will work for most users.
   See section :ref:`tar-unicode` for in-depth information.

   .. versionadded:: 2.6

   The *pax_headers* argument is an optional dictionary of unicode strings which
   will be added as a pax global header if *format* is :const:`PAX_FORMAT`.

   .. versionadded:: 2.6


.. classmethod:: TarFile.open(...)

   Alternative constructor. The :func:`tarfile.open` function is actually a
   shortcut to this classmethod.


.. method:: TarFile.getmember(name)

   Return a :class:`TarInfo` object for member *name*. If *name* can not be found
   in the archive, :exc:`KeyError` is raised.

   .. note::

      If a member occurs more than once in the archive, its last occurrence is assumed
      to be the most up-to-date version.


.. method:: TarFile.getmembers()

   Return the members of the archive as a list of :class:`TarInfo` objects. The
   list has the same order as the members in the archive.


.. method:: TarFile.getnames()

   Return the members as a list of their names. It has the same order as the list
   returned by :meth:`getmembers`.


.. method:: TarFile.list(verbose=True)

   Print a table of contents to ``sys.stdout``. If *verbose* is :const:`False`,
   only the names of the members are printed. If it is :const:`True`, output
   similar to that of :program:`ls -l` is produced.


.. method:: TarFile.next()

   Return the next member of the archive as a :class:`TarInfo` object, when
   :class:`TarFile` is opened for reading. Return :const:`None` if there is no more
   available.


.. method:: TarFile.extractall(path=".", members=None)

   Extract all members from the archive to the current working directory or
   directory *path*. If optional *members* is given, it must be a subset of the
   list returned by :meth:`getmembers`. Directory information like owner,
   modification time and permissions are set after all members have been extracted.
   This is done to work around two problems: A directory's modification time is
   reset each time a file is created in it. And, if a directory's permissions do
   not allow writing, extracting files to it will fail.

   .. warning::

      Never extract archives from untrusted sources without prior inspection.
      It is possible that files are created outside of *path*, e.g. members
      that have absolute filenames starting with ``"/"`` or filenames with two
      dots ``".."``.

   .. versionadded:: 2.5


.. method:: TarFile.extract(member, path="")

   Extract a member from the archive to the current working directory, using its
   full name. Its file information is extracted as accurately as possible. *member*
   may be a filename or a :class:`TarInfo` object. You can specify a different
   directory using *path*.

   .. note::

      The :meth:`extract` method does not take care of several extraction issues.
      In most cases you should consider using the :meth:`extractall` method.

   .. warning::

      See the warning for :meth:`extractall`.


.. method:: TarFile.extractfile(member)

   Extract a member from the archive as a file object. *member* may be a filename
   or a :class:`TarInfo` object. If *member* is a regular file, a file-like object
   is returned. If *member* is a link, a file-like object is constructed from the
   link's target. If *member* is none of the above, :const:`None` is returned.

   .. note::

      The file-like object is read-only.  It provides the methods
      :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`seek`, :meth:`tell`,
      and :meth:`close`, and also supports iteration over its lines.


.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, filter=None)

   Add the file *name* to the archive. *name* may be any type of file (directory,
   fifo, symbolic link, etc.). If given, *arcname* specifies an alternative name
   for the file in the archive. Directories are added recursively by default. This
   can be avoided by setting *recursive* to :const:`False`. If *exclude* is given
   it must be a function that takes one filename argument and returns a boolean
   value. Depending on this value the respective file is either excluded
   (:const:`True`) or added (:const:`False`). If *filter* is specified it must
   be a function that takes a :class:`TarInfo` object argument and returns the
   changed :class:`TarInfo` object. If it instead returns :const:`None` the :class:`TarInfo`
   object will be excluded from the archive. See :ref:`tar-examples` for an
   example.

   .. versionchanged:: 2.6
      Added the *exclude* parameter.

   .. versionchanged:: 2.7
      Added the *filter* parameter.

   .. deprecated:: 2.7
      The *exclude* parameter is deprecated, please use the *filter* parameter
      instead.  For maximum portability, *filter* should be used as a keyword
      argument rather than as a positional argument so that code won't be
      affected when *exclude* is ultimately removed.


.. method:: TarFile.addfile(tarinfo, fileobj=None)

   Add the :class:`TarInfo` object *tarinfo* to the archive. If *fileobj* is given,
   ``tarinfo.size`` bytes are read from it and added to the archive.  You can
   create :class:`TarInfo` objects directly, or by using :meth:`gettarinfo`.

   .. note::
      On Windows platforms, *fileobj* should always be opened with mode ``'rb'`` to
      avoid irritation about the file size.


.. method:: TarFile.gettarinfo(name=None, arcname=None, fileobj=None)

   Create a :class:`TarInfo` object from the result of :func:`os.stat` or
   equivalent on an existing file.  The file is either named by *name*, or
   specified as a file object *fileobj* with a file descriptor.  If
   given, *arcname* specifies an alternative name for the file in the
   archive, otherwise, the name is taken from *fileobj*’s
   :attr:`~file.name` attribute, or the *name* argument.

   You can modify some
   of the :class:`TarInfo`’s attributes before you add it using :meth:`addfile`.
   If the file object is not an ordinary file object positioned at the
   beginning of the file, attributes such as :attr:`~TarInfo.size` may need
   modifying.  This is the case for objects such as :class:`~gzip.GzipFile`.
   The :attr:`~TarInfo.name` may also be modified, in which case *arcname*
   could be a dummy string.


.. method:: TarFile.close()

   Close the :class:`TarFile`. In write mode, two finishing zero blocks are
   appended to the archive.


.. attribute:: TarFile.posix

   Setting this to :const:`True` is equivalent to setting the :attr:`format`
   attribute to :const:`USTAR_FORMAT`, :const:`False` is equivalent to
   :const:`GNU_FORMAT`.

   .. versionchanged:: 2.4
      *posix* defaults to :const:`False`.

   .. deprecated:: 2.6
      Use the :attr:`format` attribute instead.


.. attribute:: TarFile.pax_headers

   A dictionary containing key-value pairs of pax global headers.

   .. versionadded:: 2.6


.. _tarinfo-objects:

TarInfo Objects
---------------

A :class:`TarInfo` object represents one member in a :class:`TarFile`. Aside
from storing all required attributes of a file (like file type, size, time,
permissions, owner etc.), it provides some useful methods to determine its type.
It does *not* contain the file's data itself.

:class:`TarInfo` objects are returned by :class:`TarFile`'s methods
:meth:`getmember`, :meth:`getmembers` and :meth:`gettarinfo`.


.. class:: TarInfo(name="")

   Create a :class:`TarInfo` object.


.. method:: TarInfo.frombuf(buf)

   Create and return a :class:`TarInfo` object from string buffer *buf*.

   .. versionadded:: 2.6
      Raises :exc:`HeaderError` if the buffer is invalid..


.. method:: TarInfo.fromtarfile(tarfile)

   Read the next member from the :class:`TarFile` object *tarfile* and return it as
   a :class:`TarInfo` object.

   .. versionadded:: 2.6


.. method:: TarInfo.tobuf(format=DEFAULT_FORMAT, encoding=ENCODING, errors='strict')

   Create a string buffer from a :class:`TarInfo` object. For information on the
   arguments see the constructor of the :class:`TarFile` class.

   .. versionchanged:: 2.6
      The arguments were added.

A ``TarInfo`` object has the following public data attributes:


.. attribute:: TarInfo.name

   Name of the archive member.


.. attribute:: TarInfo.size

   Size in bytes.


.. attribute:: TarInfo.mtime

   Time of last modification.


.. attribute:: TarInfo.mode

   Permission bits.


.. attribute:: TarInfo.type

   File type.  *type* is usually one of these constants: :const:`REGTYPE`,
   :const:`AREGTYPE`, :const:`LNKTYPE`, :const:`SYMTYPE`, :const:`DIRTYPE`,
   :const:`FIFOTYPE`, :const:`CONTTYPE`, :const:`CHRTYPE`, :const:`BLKTYPE`,
   :const:`GNUTYPE_SPARSE`.  To determine the type of a :class:`TarInfo` object
   more conveniently, use the ``is*()`` methods below.


.. attribute:: TarInfo.linkname

   Name of the target file name, which is only present in :class:`TarInfo` objects
   of type :const:`LNKTYPE` and :const:`SYMTYPE`.


.. attribute:: TarInfo.uid

   User ID of the user who originally stored this member.


.. attribute:: TarInfo.gid

   Group ID of the user who originally stored this member.


.. attribute:: TarInfo.uname

   User name.


.. attribute:: TarInfo.gname

   Group name.


.. attribute:: TarInfo.pax_headers

   A dictionary containing key-value pairs of an associated pax extended header.

   .. versionadded:: 2.6

A :class:`TarInfo` object also provides some convenient query methods:


.. method:: TarInfo.isfile()

   Return :const:`True` if the :class:`Tarinfo` object is a regular file.


.. method:: TarInfo.isreg()

   Same as :meth:`isfile`.


.. method:: TarInfo.isdir()

   Return :const:`True` if it is a directory.


.. method:: TarInfo.issym()

   Return :const:`True` if it is a symbolic link.


.. method:: TarInfo.islnk()

   Return :const:`True` if it is a hard link.


.. method:: TarInfo.ischr()

   Return :const:`True` if it is a character device.


.. method:: TarInfo.isblk()

   Return :const:`True` if it is a block device.


.. method:: TarInfo.isfifo()

   Return :const:`True` if it is a FIFO.


.. method:: TarInfo.isdev()

   Return :const:`True` if it is one of character device, block device or FIFO.


.. _tar-examples:

Examples
--------

How to extract an entire tar archive to the current working directory::

   import tarfile
   tar = tarfile.open("sample.tar.gz")
   tar.extractall()
   tar.close()

How to extract a subset of a tar archive with :meth:`TarFile.extractall` using
a generator function instead of a list::

   import os
   import tarfile

   def py_files(members):
       for tarinfo in members:
           if os.path.splitext(tarinfo.name)[1] == ".py":
               yield tarinfo

   tar = tarfile.open("sample.tar.gz")
   tar.extractall(members=py_files(tar))
   tar.close()

How to create an uncompressed tar archive from a list of filenames::

   import tarfile
   tar = tarfile.open("sample.tar", "w")
   for name in ["foo", "bar", "quux"]:
       tar.add(name)
   tar.close()

The same example using the :keyword:`with` statement::

    import tarfile
    with tarfile.open("sample.tar", "w") as tar:
        for name in ["foo", "bar", "quux"]:
            tar.add(name)

How to read a gzip compressed tar archive and display some member information::

   import tarfile
   tar = tarfile.open("sample.tar.gz", "r:gz")
   for tarinfo in tar:
       print tarinfo.name, "is", tarinfo.size, "bytes in size and is",
       if tarinfo.isreg():
           print "a regular file."
       elif tarinfo.isdir():
           print "a directory."
       else:
           print "something else."
   tar.close()

How to create an archive and reset the user information using the *filter*
parameter in :meth:`TarFile.add`::

    import tarfile
    def reset(tarinfo):
        tarinfo.uid = tarinfo.gid = 0
        tarinfo.uname = tarinfo.gname = "root"
        return tarinfo
    tar = tarfile.open("sample.tar.gz", "w:gz")
    tar.add("foo", filter=reset)
    tar.close()


.. _tar-formats:

Supported tar formats
---------------------

There are three tar formats that can be created with the :mod:`tarfile` module:

* The POSIX.1-1988 ustar format (:const:`USTAR_FORMAT`). It supports filenames
  up to a length of at best 256 characters and linknames up to 100 characters. The
  maximum file size is 8 gigabytes. This is an old and limited but widely
  supported format.

* The GNU tar format (:const:`GNU_FORMAT`). It supports long filenames and
  linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
  standard on GNU/Linux systems. :mod:`tarfile` fully supports the GNU tar
  extensions for long names, sparse file support is read-only.

* The POSIX.1-2001 pax format (:const:`PAX_FORMAT`). It is the most flexible
  format with virtually no limits. It supports long filenames and linknames, large
  files and stores pathnames in a portable way. However, not all tar
  implementations today are able to handle pax archives properly.

  The *pax* format is an extension to the existing *ustar* format. It uses extra
  headers for information that cannot be stored otherwise. There are two flavours
  of pax headers: Extended headers only affect the subsequent file header, global
  headers are valid for the complete archive and affect all following files. All
  the data in a pax header is encoded in *UTF-8* for portability reasons.

There are some more variants of the tar format which can be read, but not
created:

* The ancient V7 format. This is the first tar format from Unix Seventh Edition,
  storing only regular files and directories. Names must not be longer than 100
  characters, there is no user/group name information. Some archives have
  miscalculated header checksums in case of fields with non-ASCII characters.

* The SunOS tar extended format. This format is a variant of the POSIX.1-2001
  pax format, but is not compatible.

.. _tar-unicode:

Unicode issues
--------------

The tar format was originally conceived to make backups on tape drives with the
main focus on preserving file system information. Nowadays tar archives are
commonly used for file distribution and exchanging archives over networks. One
problem of the original format (that all other formats are merely variants of)
is that there is no concept of supporting different character encodings. For
example, an ordinary tar archive created on a *UTF-8* system cannot be read
correctly on a *Latin-1* system if it contains non-ASCII characters. Names (i.e.
filenames, linknames, user/group names) containing these characters will appear
damaged.  Unfortunately, there is no way to autodetect the encoding of an
archive.

The pax format was designed to solve this problem. It stores non-ASCII names
using the universal character encoding *UTF-8*. When a pax archive is read,
these *UTF-8* names are converted to the encoding of the local file system.

The details of unicode conversion are controlled by the *encoding* and *errors*
keyword arguments of the :class:`TarFile` class.

The default value for *encoding* is the local character encoding. It is deduced
from :func:`sys.getfilesystemencoding` and :func:`sys.getdefaultencoding`. In
read mode, *encoding* is used exclusively to convert unicode names from a pax
archive to strings in the local character encoding. In write mode, the use of
*encoding* depends on the chosen archive format. In case of :const:`PAX_FORMAT`,
input names that contain non-ASCII characters need to be decoded before being
stored as *UTF-8* strings. The other formats do not make use of *encoding*
unless unicode objects are used as input names. These are converted to 8-bit
character strings before they are added to the archive.

The *errors* argument defines how characters are treated that cannot be
converted to or from *encoding*. Possible values are listed in section
:ref:`codec-base-classes`. In read mode, there is an additional scheme
``'utf-8'`` which means that bad characters are replaced by their *UTF-8*
representation. This is the default scheme. In write mode the default value for
*errors* is ``'strict'`` to ensure that name information is not altered
unnoticed.

PK
%�\S�S�::'html/_sources/library/telnetlib.rst.txtnu�[���:mod:`telnetlib` --- Telnet client
==================================

.. module:: telnetlib
   :synopsis: Telnet client class.
.. sectionauthor:: Skip Montanaro <skip@pobox.com>


.. index:: single: protocol; Telnet

**Source code:** :source:`Lib/telnetlib.py`

--------------

The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
Telnet protocol.  See :rfc:`854` for details about the protocol. In addition, it
provides symbolic constants for the protocol characters (see below), and for the
telnet options. The symbolic names of the telnet options follow the definitions
in ``arpa/telnet.h``, with the leading ``TELOPT_`` removed. For symbolic names
of options which are traditionally not included in ``arpa/telnet.h``, see the
module source itself.

The symbolic constants for the telnet commands are: IAC, DONT, DO, WONT, WILL,
SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP
(Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase
Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).


.. class:: Telnet([host[, port[, timeout]]])

   :class:`Telnet` represents a connection to a Telnet server. The instance is
   initially not connected by default; the :meth:`open` method must be used to
   establish a connection.  Alternatively, the host name and optional port
   number can be passed to the constructor, to, in which case the connection to
   the server will be established before the constructor returns.  The optional
   *timeout* parameter specifies a timeout in seconds for blocking operations
   like the connection attempt (if not specified, the global default timeout
   setting will be used).

   Do not reopen an already connected instance.

   This class has many :meth:`read_\*` methods.  Note that some of them  raise
   :exc:`EOFError` when the end of the connection is read, because they can return
   an empty string for other reasons.  See the individual descriptions below.

   .. versionchanged:: 2.6
      *timeout* was added.


.. seealso::

   :rfc:`854` - Telnet Protocol Specification
      Definition of the Telnet protocol.


.. _telnet-objects:

Telnet Objects
--------------

:class:`Telnet` instances have the following methods:


.. method:: Telnet.read_until(expected[, timeout])

   Read until a given string, *expected*, is encountered or until *timeout* seconds
   have passed.

   When no match is found, return whatever is available instead, possibly the empty
   string.  Raise :exc:`EOFError` if the connection is closed and no cooked data is
   available.


.. method:: Telnet.read_all()

   Read all data until EOF; block until connection closed.


.. method:: Telnet.read_some()

   Read at least one byte of cooked data unless EOF is hit. Return ``''`` if EOF is
   hit.  Block if no data is immediately available.


.. method:: Telnet.read_very_eager()

   Read everything that can be without blocking in I/O (eager).

   Raise :exc:`EOFError` if connection closed and no cooked data available.  Return
   ``''`` if no cooked data available otherwise. Do not block unless in the midst
   of an IAC sequence.


.. method:: Telnet.read_eager()

   Read readily available data.

   Raise :exc:`EOFError` if connection closed and no cooked data available.  Return
   ``''`` if no cooked data available otherwise. Do not block unless in the midst
   of an IAC sequence.


.. method:: Telnet.read_lazy()

   Process and return data already in the queues (lazy).

   Raise :exc:`EOFError` if connection closed and no data available. Return ``''``
   if no cooked data available otherwise.  Do not block unless in the midst of an
   IAC sequence.


.. method:: Telnet.read_very_lazy()

   Return any data available in the cooked queue (very lazy).

   Raise :exc:`EOFError` if connection closed and no data available. Return ``''``
   if no cooked data available otherwise.  This method never blocks.


.. method:: Telnet.read_sb_data()

   Return the data collected between a SB/SE pair (suboption begin/end). The
   callback should access these data when it was invoked with a ``SE`` command.
   This method never blocks.

   .. versionadded:: 2.3


.. method:: Telnet.open(host[, port[, timeout]])

   Connect to a host. The optional second argument is the port number, which
   defaults to the standard Telnet port (23). The optional *timeout* parameter
   specifies a timeout in seconds for blocking operations like the connection
   attempt (if not specified, the global default timeout setting will be used).

   Do not try to reopen an already connected instance.

   .. versionchanged:: 2.6
      *timeout* was added.


.. method:: Telnet.msg(msg[, *args])

   Print a debug message when the debug level is ``>`` 0. If extra arguments are
   present, they are substituted in the message using the standard string
   formatting operator.


.. method:: Telnet.set_debuglevel(debuglevel)

   Set the debug level.  The higher the value of *debuglevel*, the more debug
   output you get (on ``sys.stdout``).


.. method:: Telnet.close()

   Close the connection.


.. method:: Telnet.get_socket()

   Return the socket object used internally.


.. method:: Telnet.fileno()

   Return the file descriptor of the socket object used internally.


.. method:: Telnet.write(buffer)

   Write a string to the socket, doubling any IAC characters. This can block if the
   connection is blocked.  May raise :exc:`socket.error` if the connection is
   closed.


.. method:: Telnet.interact()

   Interaction function, emulates a very dumb Telnet client.


.. method:: Telnet.mt_interact()

   Multithreaded version of :meth:`interact`.


.. method:: Telnet.expect(list[, timeout])

   Read until one from a list of a regular expressions matches.

   The first argument is a list of regular expressions, either compiled
   (:class:`regex objects <re-objects>`) or uncompiled (strings). The optional second
   argument is a timeout, in seconds; the default is to block indefinitely.

   Return a tuple of three items: the index in the list of the first regular
   expression that matches; the match object returned; and the text read up till
   and including the match.

   If end of file is found and no text was read, raise :exc:`EOFError`.  Otherwise,
   when nothing matches, return ``(-1, None, text)`` where *text* is the text
   received so far (may be the empty string if a timeout happened).

   If a regular expression ends with a greedy match (such as ``.*``) or if more
   than one expression can match the same input, the results are
   non-deterministic, and may depend on the I/O timing.


.. method:: Telnet.set_option_negotiation_callback(callback)

   Each time a telnet option is read on the input flow, this *callback* (if set) is
   called with the following parameters: callback(telnet socket, command
   (DO/DONT/WILL/WONT), option).  No other action is done afterwards by telnetlib.


.. _telnet-example:

Telnet Example
--------------

.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>


A simple example illustrating typical use::

   import getpass
   import sys
   import telnetlib

   HOST = "localhost"
   user = raw_input("Enter your remote account: ")
   password = getpass.getpass()

   tn = telnetlib.Telnet(HOST)

   tn.read_until("login: ")
   tn.write(user + "\n")
   if password:
       tn.read_until("Password: ")
       tn.write(password + "\n")

   tn.write("ls\n")
   tn.write("exit\n")

   print tn.read_all()

PK
%�\-�	))&html/_sources/library/tempfile.rst.txtnu�[���:mod:`tempfile` --- Generate temporary files and directories
============================================================

.. sectionauthor:: Zack Weinberg <zack@codesourcery.com>


.. module:: tempfile
   :synopsis: Generate temporary files and directories.


.. index::
   pair: temporary; file name
   pair: temporary; file

**Source code:** :source:`Lib/tempfile.py`

--------------

This module generates temporary files and directories.  It works on all
supported platforms.

In version 2.3 of Python, this module was overhauled for enhanced security.  It
now provides three new functions, :func:`NamedTemporaryFile`, :func:`mkstemp`,
and :func:`mkdtemp`, which should eliminate all remaining need to use the
insecure :func:`mktemp` function.  Temporary file names created by this module
no longer contain the process ID; instead a string of six random characters is
used.

Also, all the user-callable functions now take additional arguments which
allow direct control over the location and name of temporary files.  It is
no longer necessary to use the global *tempdir* and *template* variables.
To maintain backward compatibility, the argument order is somewhat odd; it
is recommended to use keyword arguments for clarity.

The module defines the following user-callable functions:


.. function:: TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]])

   Return a file-like object that can be used as a temporary storage area.
   The file is created using :func:`mkstemp`. It will be destroyed as soon
   as it is closed (including an implicit close when the object is garbage
   collected).  Under Unix, the directory entry for the file is removed
   immediately after the file is created.  Other platforms do not support
   this; your code should not rely on a temporary file created using this
   function having or not having a visible name in the file system.

   The *mode* parameter defaults to ``'w+b'`` so that the file created can
   be read and written without being closed.  Binary mode is used so that it
   behaves consistently on all platforms without regard for the data that is
   stored.  *bufsize* defaults to ``-1``, meaning that the operating system
   default is used.

   The *dir*, *prefix* and *suffix* parameters are passed to :func:`mkstemp`.

   The returned object is a true file object on POSIX platforms.  On other
   platforms, it is a file-like object whose :attr:`!file` attribute is the
   underlying true file object. This file-like object can be used in a
   :keyword:`with` statement, just like a normal file.


.. function:: NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]])

   This function operates exactly as :func:`TemporaryFile` does, except that
   the file is guaranteed to have a visible name in the file system (on
   Unix, the directory entry is not unlinked).  That name can be retrieved
   from the :attr:`name` attribute of the returned
   file-like object.  Whether the name can be
   used to open the file a second time, while the named temporary file is
   still open, varies across platforms (it can be so used on Unix; it cannot
   on Windows NT or later).  If *delete* is true (the default), the file is
   deleted as soon as it is closed.

   The returned object is always a file-like object whose :attr:`!file`
   attribute is the underlying true file object. This file-like object can
   be used in a :keyword:`with` statement, just like a normal file.

   .. versionadded:: 2.3

   .. versionadded:: 2.6
      The *delete* parameter.


.. function:: SpooledTemporaryFile([max_size=0, [mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]])

   This function operates exactly as :func:`TemporaryFile` does, except that
   data is spooled in memory until the file size exceeds *max_size*, or
   until the file's :func:`fileno` method is called, at which point the
   contents are written to disk and operation proceeds as with
   :func:`TemporaryFile`.  Also, it's ``truncate`` method does not
   accept a ``size`` argument.

   The resulting file has one additional method, :func:`rollover`, which
   causes the file to roll over to an on-disk file regardless of its size.

   The returned object is a file-like object whose :attr:`_file` attribute
   is either a :class:`~StringIO.StringIO` object or a true file object, depending on
   whether :func:`rollover` has been called. This file-like object can be
   used in a :keyword:`with` statement, just like a normal file.

   .. versionadded:: 2.6


.. function:: mkstemp([suffix=''[, prefix='tmp'[, dir=None[, text=False]]]])

   Creates a temporary file in the most secure manner possible.  There are
   no race conditions in the file's creation, assuming that the platform
   properly implements the :const:`os.O_EXCL` flag for :func:`os.open`.  The
   file is readable and writable only by the creating user ID.  If the
   platform uses permission bits to indicate whether a file is executable,
   the file is executable by no one.  The file descriptor is not inherited
   by child processes.

   Unlike :func:`TemporaryFile`, the user of :func:`mkstemp` is responsible
   for deleting the temporary file when done with it.

   If *suffix* is specified, the file name will end with that suffix,
   otherwise there will be no suffix.  :func:`mkstemp` does not put a dot
   between the file name and the suffix; if you need one, put it at the
   beginning of *suffix*.

   If *prefix* is specified, the file name will begin with that prefix;
   otherwise, a default prefix is used.

   If *dir* is specified, the file will be created in that directory;
   otherwise, a default directory is used.  The default directory is chosen
   from a platform-dependent list, but the user of the application can
   control the directory location by setting the *TMPDIR*, *TEMP* or *TMP*
   environment variables.  There is thus no guarantee that the generated
   filename will have any nice properties, such as not requiring quoting
   when passed to external commands via ``os.popen()``.

   If *text* is specified, it indicates whether to open the file in binary
   mode (the default) or text mode.  On some platforms, this makes no
   difference.

   :func:`mkstemp` returns a tuple containing an OS-level handle to an open
   file (as would be returned by :func:`os.open`) and the absolute pathname
   of that file, in that order.

   .. versionadded:: 2.3


.. function:: mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]])

   Creates a temporary directory in the most secure manner possible. There
   are no race conditions in the directory's creation.  The directory is
   readable, writable, and searchable only by the creating user ID.

   The user of :func:`mkdtemp` is responsible for deleting the temporary
   directory and its contents when done with it.

   The *prefix*, *suffix*, and *dir* arguments are the same as for
   :func:`mkstemp`.

   :func:`mkdtemp` returns the absolute pathname of the new directory.

   .. versionadded:: 2.3


.. function:: mktemp([suffix=''[, prefix='tmp'[, dir=None]]])

   .. deprecated:: 2.3
      Use :func:`mkstemp` instead.

   Return an absolute pathname of a file that did not exist at the time the
   call is made.  The *prefix*, *suffix*, and *dir* arguments are the same
   as for :func:`mkstemp`.

   .. warning::

      Use of this function may introduce a security hole in your program.  By
      the time you get around to doing anything with the file name it returns,
      someone else may have beaten you to the punch.  :func:`mktemp` usage can
      be replaced easily with :func:`NamedTemporaryFile`, passing it the
      ``delete=False`` parameter::

         >>> f = NamedTemporaryFile(delete=False)
         >>> f
         <open file '<fdopen>', mode 'w+b' at 0x384698>
         >>> f.name
         '/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0'
         >>> f.write("Hello World!\n")
         >>> f.close()
         >>> os.unlink(f.name)
         >>> os.path.exists(f.name)
         False

The module uses a global variable that tell it how to construct a
temporary name.  They are initialized at the first call to any of the
functions above.  The caller may change them, but this is discouraged; use
the appropriate function arguments, instead.


.. data:: tempdir

   When set to a value other than ``None``, this variable defines the
   default value for the *dir* argument to all the functions defined in this
   module.

   If ``tempdir`` is unset or ``None`` at any call to any of the above
   functions, Python searches a standard list of directories and sets
   *tempdir* to the first one which the calling user can create files in.
   The list is:

   #. The directory named by the :envvar:`TMPDIR` environment variable.

   #. The directory named by the :envvar:`TEMP` environment variable.

   #. The directory named by the :envvar:`TMP` environment variable.

   #. A platform-specific location:

      * On RiscOS, the directory named by the :envvar:`Wimp$ScrapDir` environment
        variable.

      * On Windows, the directories :file:`C:\\TEMP`, :file:`C:\\TMP`,
        :file:`\\TEMP`, and :file:`\\TMP`, in that order.

      * On all other platforms, the directories :file:`/tmp`, :file:`/var/tmp`, and
        :file:`/usr/tmp`, in that order.

   #. As a last resort, the current working directory.


.. function:: gettempdir()

   Return the directory currently selected to create temporary files in. If
   :data:`tempdir` is not ``None``, this simply returns its contents; otherwise,
   the search described above is performed, and the result returned.

   .. versionadded:: 2.3


.. data:: template

   .. deprecated:: 2.0
      Use :func:`gettempprefix` instead.

   When set to a value other than ``None``, this variable defines the prefix of the
   final component of the filenames returned by :func:`mktemp`.  A string of six
   random letters and digits is appended to the prefix to make the filename unique.
   The default prefix is :file:`tmp`.

   Older versions of this module used to require that ``template`` be set to
   ``None`` after a call to :func:`os.fork`; this has not been necessary since
   version 1.5.2.


.. function:: gettempprefix()

   Return the filename prefix used to create temporary files.  This does not
   contain the directory component.  Using this function is preferred over reading
   the *template* variable directly.

   .. versionadded:: 1.5.2

PK
%�\����%html/_sources/library/termios.rst.txtnu�[���
:mod:`termios` --- POSIX style tty control
==========================================

.. module:: termios
   :platform: Unix
   :synopsis: POSIX style tty control.


.. index::
   pair: POSIX; I/O control
   pair: tty; I/O control

This module provides an interface to the POSIX calls for tty I/O control. For a
complete description of these calls, see :manpage:`termios(2)` Unix manual
page.  It is only available for those Unix versions that support POSIX
*termios* style tty I/O control configured during installation.

All functions in this module take a file descriptor *fd* as their first
argument.  This can be an integer file descriptor, such as returned by
``sys.stdin.fileno()``, or a file object, such as ``sys.stdin`` itself.

This module also defines all the constants needed to work with the functions
provided here; these have the same name as their counterparts in C.  Please
refer to your system documentation for more information on using these terminal
control interfaces.

The module defines the following functions:


.. function:: tcgetattr(fd)

   Return a list containing the tty attributes for file descriptor *fd*, as
   follows: ``[iflag, oflag, cflag, lflag, ispeed, ospeed, cc]`` where *cc* is a
   list of the tty special characters (each a string of length 1, except the
   items with indices :const:`VMIN` and :const:`VTIME`, which are integers when
   these fields are defined).  The interpretation of the flags and the speeds as
   well as the indexing in the *cc* array must be done using the symbolic
   constants defined in the :mod:`termios` module.


.. function:: tcsetattr(fd, when, attributes)

   Set the tty attributes for file descriptor *fd* from the *attributes*, which is
   a list like the one returned by :func:`tcgetattr`.  The *when* argument
   determines when the attributes are changed: :const:`TCSANOW` to change
   immediately, :const:`TCSADRAIN` to change after transmitting all queued output,
   or :const:`TCSAFLUSH` to change after transmitting all queued output and
   discarding all queued input.


.. function:: tcsendbreak(fd, duration)

   Send a break on file descriptor *fd*.  A zero *duration* sends a break for 0.25
   --0.5 seconds; a nonzero *duration* has a system dependent meaning.


.. function:: tcdrain(fd)

   Wait until all output written to file descriptor *fd* has been transmitted.


.. function:: tcflush(fd, queue)

   Discard queued data on file descriptor *fd*.  The *queue* selector specifies
   which queue: :const:`TCIFLUSH` for the input queue, :const:`TCOFLUSH` for the
   output queue, or :const:`TCIOFLUSH` for both queues.


.. function:: tcflow(fd, action)

   Suspend or resume input or output on file descriptor *fd*.  The *action*
   argument can be :const:`TCOOFF` to suspend output, :const:`TCOON` to restart
   output, :const:`TCIOFF` to suspend input, or :const:`TCION` to restart input.


.. seealso::

   Module :mod:`tty`
      Convenience functions for common terminal control operations.


Example
-------

.. _termios-example:

Here's a function that prompts for a password with echoing turned off.  Note the
technique using a separate :func:`tcgetattr` call and a :keyword:`try` ...
:keyword:`finally` statement to ensure that the old tty attributes are restored
exactly no matter what happens::

   def getpass(prompt="Password: "):
       import termios, sys
       fd = sys.stdin.fileno()
       old = termios.tcgetattr(fd)
       new = termios.tcgetattr(fd)
       new[3] = new[3] & ~termios.ECHO          # lflags
       try:
           termios.tcsetattr(fd, termios.TCSADRAIN, new)
           passwd = raw_input(prompt)
       finally:
           termios.tcsetattr(fd, termios.TCSADRAIN, old)
       return passwd

PK
%�\o��P�D�D"html/_sources/library/test.rst.txtnu�[���
:mod:`test` --- Regression tests package for Python
===================================================

.. module:: test
   :synopsis: Regression tests package containing the testing suite for Python.
.. sectionauthor:: Brett Cannon <brett@python.org>

.. note::
    The :mod:`test` package is meant for internal use by Python only. It is
    documented for the benefit of the core developers of Python. Any use of
    this package outside of Python's standard library is discouraged as code
    mentioned here can change or be removed without notice between releases of
    Python.


The :mod:`test` package contains all regression tests for Python as well as the
modules :mod:`test.support` and :mod:`test.regrtest`.
:mod:`test.support` is used to enhance your tests while
:mod:`test.regrtest` drives the testing suite.

Each module in the :mod:`test` package whose name starts with ``test_`` is a
testing suite for a specific module or feature. All new tests should be written
using the :mod:`unittest` or :mod:`doctest` module.  Some older tests are
written using a "traditional" testing style that compares output printed to
``sys.stdout``; this style of test is considered deprecated.


.. seealso::

   Module :mod:`unittest`
      Writing PyUnit regression tests.

   Module :mod:`doctest`
      Tests embedded in documentation strings.


.. _writing-tests:

Writing Unit Tests for the :mod:`test` package
----------------------------------------------

It is preferred that tests that use the :mod:`unittest` module follow a few
guidelines. One is to name the test module by starting it with ``test_`` and end
it with the name of the module being tested. The test methods in the test module
should start with ``test_`` and end with a description of what the method is
testing. This is needed so that the methods are recognized by the test driver as
test methods. Also, no documentation string for the method should be included. A
comment (such as ``# Tests function returns only True or False``) should be used
to provide documentation for test methods. This is done because documentation
strings get printed out if they exist and thus what test is being run is not
stated.

A basic boilerplate is often used::

   import unittest
   from test import support

   class MyTestCase1(unittest.TestCase):

       # Only use setUp() and tearDown() if necessary

       def setUp(self):
           ... code to execute in preparation for tests ...

       def tearDown(self):
           ... code to execute to clean up after tests ...

       def test_feature_one(self):
           # Test feature one.
           ... testing code ...

       def test_feature_two(self):
           # Test feature two.
           ... testing code ...

       ... more test methods ...

   class MyTestCase2(unittest.TestCase):
       ... same structure as MyTestCase1 ...

   ... more test classes ...

   def test_main():
       support.run_unittest(MyTestCase1,
                            MyTestCase2,
                            ... list other tests ...
                            )

   if __name__ == '__main__':
       test_main()

This boilerplate code allows the testing suite to be run by :mod:`test.regrtest`
as well as on its own as a script.

The goal for regression testing is to try to break code. This leads to a few
guidelines to be followed:

* The testing suite should exercise all classes, functions, and constants. This
  includes not just the external API that is to be presented to the outside
  world but also "private" code.

* Whitebox testing (examining the code being tested when the tests are being
  written) is preferred. Blackbox testing (testing only the published user
  interface) is not complete enough to make sure all boundary and edge cases
  are tested.

* Make sure all possible values are tested including invalid ones. This makes
  sure that not only all valid values are acceptable but also that improper
  values are handled correctly.

* Exhaust as many code paths as possible. Test where branching occurs and thus
  tailor input to make sure as many different paths through the code are taken.

* Add an explicit test for any bugs discovered for the tested code. This will
  make sure that the error does not crop up again if the code is changed in the
  future.

* Make sure to clean up after your tests (such as close and remove all temporary
  files).

* If a test is dependent on a specific condition of the operating system then
  verify the condition already exists before attempting the test.

* Import as few modules as possible and do it as soon as possible. This
  minimizes external dependencies of tests and also minimizes possible anomalous
  behavior from side-effects of importing a module.

* Try to maximize code reuse. On occasion, tests will vary by something as small
  as what type of input is used. Minimize code duplication by subclassing a
  basic test class with a class that specifies the input::

     class TestFuncAcceptsSequences(unittest.TestCase):

         func = mySuperWhammyFunction

         def test_func(self):
             self.func(self.arg)

     class AcceptLists(TestFuncAcceptsSequences):
         arg = [1, 2, 3]

     class AcceptStrings(TestFuncAcceptsSequences):
         arg = 'abc'

     class AcceptTuples(TestFuncAcceptsSequences):
         arg = (1, 2, 3)


.. seealso::

   Test Driven Development
      A book by Kent Beck on writing tests before code.


.. _regrtest:

Running tests using the command-line interface
----------------------------------------------

The :mod:`test.regrtest` module can be run as a script to drive Python's regression
test suite, thanks to the :option:`-m` option: :program:`python -m test.regrtest`.
Running the script by itself automatically starts running all regression
tests in the :mod:`test` package. It does this by finding all modules in the
package whose name starts with ``test_``, importing them, and executing the
function :func:`test_main` if present. The names of tests to execute may also
be passed to the script. Specifying a single regression test (:program:`python
-m test.regrtest test_spam`) will minimize output and only print whether
the test passed or failed and thus minimize output.

Running :mod:`test.regrtest` directly allows what resources are available for
tests to use to be set. You do this by using the ``-u`` command-line
option. Specifying ``all`` as the value for the ``-u`` option enables all
possible resources: :program:`python -m test.regrtest -uall`.
If all but one resource is desired (a more common case), a
comma-separated list of resources that are not desired may be listed after
``all``. The command :program:`python -m test.regrtest -uall,-audio,-largefile`
will run :mod:`test.regrtest` with all resources except the ``audio`` and
``largefile`` resources. For a list of all resources and more command-line
options, run :program:`python -m test.regrtest -h`.

Some other ways to execute the regression tests depend on what platform the
tests are being executed on. On Unix, you can run :program:`make test` at the
top-level directory where Python was built. On Windows, executing
:program:`rt.bat` from your :file:`PCBuild` directory will run all regression
tests.

.. versionchanged:: 2.7.14
   The :mod:`test` package can be run as a script: :program:`python -m test`.
   This works the same as running the :mod:`test.regrtest` module.


:mod:`test.support` --- Utility functions for tests
===================================================

.. module:: test.support
   :synopsis: Support for Python regression tests.

.. note::

   The :mod:`test.test_support` module has been renamed to :mod:`test.support`
   in Python 3.x and 2.7.14.  The name ``test.test_support`` has been retained
   as an alias in 2.7.

The :mod:`test.support` module provides support for Python's regression
tests.

This module defines the following exceptions:


.. exception:: TestFailed

   Exception to be raised when a test fails. This is deprecated in favor of
   :mod:`unittest`\ -based tests and :class:`unittest.TestCase`'s assertion
   methods.


.. exception:: ResourceDenied

   Subclass of :exc:`unittest.SkipTest`. Raised when a resource (such as a
   network connection) is not available. Raised by the :func:`requires`
   function.

The :mod:`test.support` module defines the following constants:


.. data:: verbose

   :const:`True` when verbose output is enabled. Should be checked when more
   detailed information is desired about a running test. *verbose* is set by
   :mod:`test.regrtest`.


.. data:: have_unicode

   :const:`True` when Unicode support is available.


.. data:: is_jython

   :const:`True` if the running interpreter is Jython.


.. data:: TESTFN

   Set to a name that is safe to use as the name of a temporary file.  Any
   temporary file that is created should be closed and unlinked (removed).

The :mod:`test.support` module defines the following functions:


.. function:: forget(module_name)

   Remove the module named *module_name* from ``sys.modules`` and delete any
   byte-compiled files of the module.


.. function:: is_resource_enabled(resource)

   Return :const:`True` if *resource* is enabled and available. The list of
   available resources is only set when :mod:`test.regrtest` is executing the
   tests.


.. function:: requires(resource[, msg])

   Raise :exc:`ResourceDenied` if *resource* is not available. *msg* is the
   argument to :exc:`ResourceDenied` if it is raised. Always returns
   :const:`True` if called by a function whose ``__name__`` is ``'__main__'``.
   Used when tests are executed by :mod:`test.regrtest`.


.. function:: findfile(filename)

   Return the path to the file named *filename*. If no match is found
   *filename* is returned. This does not equal a failure since it could be the
   path to the file.


.. function:: run_unittest(*classes)

   Execute :class:`unittest.TestCase` subclasses passed to the function. The
   function scans the classes for methods starting with the prefix ``test_``
   and executes the tests individually.

   It is also legal to pass strings as parameters; these should be keys in
   ``sys.modules``. Each associated module will be scanned by
   ``unittest.TestLoader.loadTestsFromModule()``. This is usually seen in the
   following :func:`test_main` function::

      def test_main():
          support.run_unittest(__name__)

   This will run all tests defined in the named module.


.. function:: check_warnings(*filters, quiet=True)

   A convenience wrapper for :func:`warnings.catch_warnings()` that makes it
   easier to test that a warning was correctly raised.  It is approximately
   equivalent to calling ``warnings.catch_warnings(record=True)`` with
   :meth:`warnings.simplefilter` set to ``always`` and with the option to
   automatically validate the results that are recorded.

   ``check_warnings`` accepts 2-tuples of the form ``("message regexp",
   WarningCategory)`` as positional arguments. If one or more *filters* are
   provided, or if the optional keyword argument *quiet* is :const:`False`,
   it checks to make sure the warnings are as expected:  each specified filter
   must match at least one of the warnings raised by the enclosed code or the
   test fails, and if any warnings are raised that do not match any of the
   specified filters the test fails.  To disable the first of these checks,
   set *quiet* to :const:`True`.

   If no arguments are specified, it defaults to::

      check_warnings(("", Warning), quiet=True)

   In this case all warnings are caught and no errors are raised.

   On entry to the context manager, a :class:`WarningRecorder` instance is
   returned. The underlying warnings list from
   :func:`~warnings.catch_warnings` is available via the recorder object's
   :attr:`warnings` attribute.  As a convenience, the attributes of the object
   representing the most recent warning can also be accessed directly through
   the recorder object (see example below).  If no warning has been raised,
   then any of the attributes that would otherwise be expected on an object
   representing a warning will return :const:`None`.

   The recorder object also has a :meth:`reset` method, which clears the
   warnings list.

   The context manager is designed to be used like this::

      with check_warnings(("assertion is always true", SyntaxWarning),
                          ("", UserWarning)):
          exec('assert(False, "Hey!")')
          warnings.warn(UserWarning("Hide me!"))

   In this case if either warning was not raised, or some other warning was
   raised, :func:`check_warnings` would raise an error.

   When a test needs to look more deeply into the warnings, rather than
   just checking whether or not they occurred, code like this can be used::

      with check_warnings(quiet=True) as w:
          warnings.warn("foo")
          assert str(w.args[0]) == "foo"
          warnings.warn("bar")
          assert str(w.args[0]) == "bar"
          assert str(w.warnings[0].args[0]) == "foo"
          assert str(w.warnings[1].args[0]) == "bar"
          w.reset()
          assert len(w.warnings) == 0

   Here all warnings will be caught, and the test code tests the captured
   warnings directly.

   .. versionadded:: 2.6
   .. versionchanged:: 2.7
      New optional arguments *filters* and *quiet*.


.. function:: check_py3k_warnings(*filters, quiet=False)

   Similar to :func:`check_warnings`, but for Python 3 compatibility warnings.
   If ``sys.py3kwarning == 1``, it checks if the warning is effectively raised.
   If ``sys.py3kwarning == 0``, it checks that no warning is raised.  It
   accepts 2-tuples of the form ``("message regexp", WarningCategory)`` as
   positional arguments.  When the optional keyword argument *quiet* is
   :const:`True`, it does not fail if a filter catches nothing.  Without
   arguments, it defaults to::

      check_py3k_warnings(("", DeprecationWarning), quiet=False)

   .. versionadded:: 2.7


.. function:: captured_stdout()

   This is a context manager that runs the :keyword:`with` statement body using
   a :class:`StringIO.StringIO` object as sys.stdout.  That object can be
   retrieved using the ``as`` clause of the :keyword:`with` statement.

   Example use::

      with captured_stdout() as s:
          print "hello"
      assert s.getvalue() == "hello\n"

   .. versionadded:: 2.6


.. function:: import_module(name, deprecated=False)

   This function imports and returns the named module. Unlike a normal
   import, this function raises :exc:`unittest.SkipTest` if the module
   cannot be imported.

   Module and package deprecation messages are suppressed during this import
   if *deprecated* is :const:`True`.

   .. versionadded:: 2.7


.. function:: import_fresh_module(name, fresh=(), blocked=(), deprecated=False)

   This function imports and returns a fresh copy of the named Python module
   by removing the named module from ``sys.modules`` before doing the import.
   Note that unlike :func:`reload`, the original module is not affected by
   this operation.

   *fresh* is an iterable of additional module names that are also removed
   from the ``sys.modules`` cache before doing the import.

   *blocked* is an iterable of module names that are replaced with :const:`0`
   in the module cache during the import to ensure that attempts to import
   them raise :exc:`ImportError`.

   The named module and any modules named in the *fresh* and *blocked*
   parameters are saved before starting the import and then reinserted into
   ``sys.modules`` when the fresh import is complete.

   Module and package deprecation messages are suppressed during this import
   if *deprecated* is :const:`True`.

   This function will raise :exc:`unittest.SkipTest` if the named module
   cannot be imported.

   Example use::

      # Get copies of the warnings module for testing without
      # affecting the version being used by the rest of the test suite
      # One copy uses the C implementation, the other is forced to use
      # the pure Python fallback implementation
      py_warnings = import_fresh_module('warnings', blocked=['_warnings'])
      c_warnings = import_fresh_module('warnings', fresh=['_warnings'])

   .. versionadded:: 2.7


The :mod:`test.support` module defines the following classes:

.. class:: TransientResource(exc[, **kwargs])

   Instances are a context manager that raises :exc:`ResourceDenied` if the
   specified exception type is raised.  Any keyword arguments are treated as
   attribute/value pairs to be compared against any exception raised within the
   :keyword:`with` statement.  Only if all pairs match properly against
   attributes on the exception is :exc:`ResourceDenied` raised.

   .. versionadded:: 2.6
.. class:: EnvironmentVarGuard()

   Class used to temporarily set or unset environment variables.  Instances can
   be used as a context manager and have a complete dictionary interface for
   querying/modifying the underlying ``os.environ``. After exit from the
   context manager all changes to environment variables done through this
   instance will be rolled back.

   .. versionadded:: 2.6
   .. versionchanged:: 2.7
      Added dictionary interface.


.. method:: EnvironmentVarGuard.set(envvar, value)

   Temporarily set the environment variable ``envvar`` to the value of
   ``value``.


.. method:: EnvironmentVarGuard.unset(envvar)

   Temporarily unset the environment variable ``envvar``.


.. class:: WarningsRecorder()

   Class used to record warnings for unit tests. See documentation of
   :func:`check_warnings` above for more details.

   .. versionadded:: 2.6
PK
%�\<,��h!h!&html/_sources/library/textwrap.rst.txtnu�[���:mod:`textwrap` --- Text wrapping and filling
=============================================

.. module:: textwrap
   :synopsis: Text wrapping and filling
.. moduleauthor:: Greg Ward <gward@python.net>
.. sectionauthor:: Greg Ward <gward@python.net>

.. versionadded:: 2.3

**Source code:** :source:`Lib/textwrap.py`

--------------

The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and
:func:`fill`, as well as :class:`TextWrapper`, the class that does all the work,
and a utility function  :func:`dedent`.  If you're just wrapping or filling one
or two  text strings, the convenience functions should be good enough;
otherwise,  you should use an instance of :class:`TextWrapper` for efficiency.

.. function:: wrap(text[, width[, ...]])

   Wraps the single paragraph in *text* (a string) so every line is at most *width*
   characters long.  Returns a list of output lines, without final newlines.

   Optional keyword arguments correspond to the instance attributes of
   :class:`TextWrapper`, documented below.  *width* defaults to ``70``.

   See the :meth:`TextWrapper.wrap` method for additional details on how
   :func:`wrap` behaves.


.. function:: fill(text[, width[, ...]])

   Wraps the single paragraph in *text*, and returns a single string containing the
   wrapped paragraph.  :func:`fill` is shorthand for  ::

      "\n".join(wrap(text, ...))

   In particular, :func:`fill` accepts exactly the same keyword arguments as
   :func:`wrap`.

Both :func:`wrap` and :func:`fill` work by creating a :class:`TextWrapper`
instance and calling a single method on it.  That instance is not reused, so for
applications that wrap/fill many text strings, it will be more efficient for you
to create your own :class:`TextWrapper` object.

Text is preferably wrapped on whitespaces and right after the hyphens in
hyphenated words; only then will long words be broken if necessary, unless
:attr:`TextWrapper.break_long_words` is set to false.

An additional utility function, :func:`dedent`, is provided to remove
indentation from strings that have unwanted whitespace to the left of the text.


.. function:: dedent(text)

   Remove any common leading whitespace from every line in *text*.

   This can be used to make triple-quoted strings line up with the left edge of the
   display, while still presenting them in the source code in indented form.

   Note that tabs and spaces are both treated as whitespace, but they are not
   equal: the lines ``"  hello"`` and ``"\thello"`` are considered to have no
   common leading whitespace.  (This behaviour is new in Python 2.5; older versions
   of this module incorrectly expanded tabs before searching for common leading
   whitespace.)

   For example::

      def test():
          # end first line with \ to avoid the empty line!
          s = '''\
          hello
            world
          '''
          print repr(s)          # prints '    hello\n      world\n    '
          print repr(dedent(s))  # prints 'hello\n  world\n'


.. class:: TextWrapper(...)

   The :class:`TextWrapper` constructor accepts a number of optional keyword
   arguments.  Each argument corresponds to one instance attribute, so for example
   ::

      wrapper = TextWrapper(initial_indent="* ")

   is the same as  ::

      wrapper = TextWrapper()
      wrapper.initial_indent = "* "

   You can re-use the same :class:`TextWrapper` object many times, and you can
   change any of its options through direct assignment to instance attributes
   between uses.

   The :class:`TextWrapper` instance attributes (and keyword arguments to the
   constructor) are as follows:


   .. attribute:: width

      (default: ``70``) The maximum length of wrapped lines.  As long as there
      are no individual words in the input text longer than :attr:`width`,
      :class:`TextWrapper` guarantees that no output line will be longer than
      :attr:`width` characters.


   .. attribute:: expand_tabs

      (default: ``True``) If true, then all tab characters in *text* will be
      expanded to spaces using the :meth:`expandtabs` method of *text*.


   .. attribute:: replace_whitespace

      (default: ``True``) If true, after tab expansion but before wrapping,
      the :meth:`wrap` method will replace each whitespace character
      with a single space.  The whitespace characters replaced are
      as follows: tab, newline, vertical tab, formfeed, and carriage
      return (``'\t\n\v\f\r'``).

      .. note::

         If :attr:`expand_tabs` is false and :attr:`replace_whitespace` is true,
         each tab character will be replaced by a single space, which is *not*
         the same as tab expansion.

      .. note::

         If :attr:`replace_whitespace` is false, newlines may appear in the
         middle of a line and cause strange output. For this reason, text should
         be split into paragraphs (using :meth:`str.splitlines` or similar)
         which are wrapped separately.


   .. attribute:: drop_whitespace

      (default: ``True``) If true, whitespace at the beginning and ending of
      every line (after wrapping but before indenting) is dropped.
      Whitespace at the beginning of the paragraph, however, is not dropped
      if non-whitespace follows it.  If whitespace being dropped takes up an
      entire line, the whole line is dropped.

      .. versionadded:: 2.6
         Whitespace was always dropped in earlier versions.


   .. attribute:: initial_indent

      (default: ``''``) String that will be prepended to the first line of
      wrapped output.  Counts towards the length of the first line.  The empty
      string is not indented.


   .. attribute:: subsequent_indent

      (default: ``''``) String that will be prepended to all lines of wrapped
      output except the first.  Counts towards the length of each line except
      the first.


   .. attribute:: fix_sentence_endings

      (default: ``False``) If true, :class:`TextWrapper` attempts to detect
      sentence endings and ensure that sentences are always separated by exactly
      two spaces.  This is generally desired for text in a monospaced font.
      However, the sentence detection algorithm is imperfect: it assumes that a
      sentence ending consists of a lowercase letter followed by one of ``'.'``,
      ``'!'``, or ``'?'``, possibly followed by one of ``'"'`` or ``"'"``,
      followed by a space.  One problem with this is algorithm is that it is
      unable to detect the difference between "Dr." in ::

         [...] Dr. Frankenstein's monster [...]

      and "Spot." in ::

         [...] See Spot. See Spot run [...]

      :attr:`fix_sentence_endings` is false by default.

      Since the sentence detection algorithm relies on ``string.lowercase`` for
      the definition of "lowercase letter," and a convention of using two spaces
      after a period to separate sentences on the same line, it is specific to
      English-language texts.


   .. attribute:: break_long_words

      (default: ``True``) If true, then words longer than :attr:`width` will be
      broken in order to ensure that no lines are longer than :attr:`width`.  If
      it is false, long words will not be broken, and some lines may be longer
      than :attr:`width`.  (Long words will be put on a line by themselves, in
      order to minimize the amount by which :attr:`width` is exceeded.)


   .. attribute:: break_on_hyphens

      (default: ``True``) If true, wrapping will occur preferably on whitespaces
      and right after hyphens in compound words, as it is customary in English.
      If false, only whitespaces will be considered as potentially good places
      for line breaks, but you need to set :attr:`break_long_words` to false if
      you want truly insecable words.  Default behaviour in previous versions
      was to always allow breaking hyphenated words.

      .. versionadded:: 2.6


   :class:`TextWrapper` also provides two public methods, analogous to the
   module-level convenience functions:

   .. method:: wrap(text)

      Wraps the single paragraph in *text* (a string) so every line is at most
      :attr:`width` characters long.  All wrapping options are taken from
      instance attributes of the :class:`TextWrapper` instance.  Returns a list
      of output lines, without final newlines.  If the wrapped output has no
      content, the returned list is empty.


   .. method:: fill(text)

      Wraps the single paragraph in *text*, and returns a single string
      containing the wrapped paragraph.

PK
%�\үͳ��$html/_sources/library/thread.rst.txtnu�[���:mod:`thread` --- Multiple threads of control
=============================================

.. module:: thread
   :synopsis: Create multiple threads of control within one interpreter.

.. note::
   The :mod:`thread` module has been renamed to :mod:`_thread` in Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3; however, you should consider using the high-level
   :mod:`threading` module instead.


.. index::
   single: light-weight processes
   single: processes, light-weight
   single: binary semaphores
   single: semaphores, binary

This module provides low-level primitives for working with multiple threads
(also called :dfn:`light-weight processes` or :dfn:`tasks`) --- multiple threads of
control sharing their global data space.  For synchronization, simple locks
(also called :dfn:`mutexes` or :dfn:`binary semaphores`) are provided.
The :mod:`threading` module provides an easier to use and higher-level
threading API built on top of this module.

.. index::
   single: pthreads
   pair: threads; POSIX

The module is optional.  It is supported on Windows, Linux, SGI IRIX, Solaris
2.x, as well as on systems that have a POSIX thread (a.k.a. "pthread")
implementation.  For systems lacking the :mod:`thread` module, the
:mod:`dummy_thread` module is available. It duplicates this module's interface
and can be used as a drop-in replacement.

It defines the following constant and functions:


.. exception:: error

   Raised on thread-specific errors.


.. data:: LockType

   This is the type of lock objects.


.. function:: start_new_thread(function, args[, kwargs])

   Start a new thread and return its identifier.  The thread executes the function
   *function* with the argument list *args* (which must be a tuple).  The optional
   *kwargs* argument specifies a dictionary of keyword arguments. When the function
   returns, the thread silently exits.  When the function terminates with an
   unhandled exception, a stack trace is printed and then the thread exits (but
   other threads continue to run).


.. function:: interrupt_main()

   Raise a :exc:`KeyboardInterrupt` exception in the main thread.  A subthread can
   use this function to interrupt the main thread.

   .. versionadded:: 2.3


.. function:: exit()

   Raise the :exc:`SystemExit` exception.  When not caught, this will cause the
   thread to exit silently.

..
   function:: exit_prog(status)

      Exit all threads and report the value of the integer argument
      *status* as the exit status of the entire program.
      **Caveat:** code in pending :keyword:`finally` clauses, in this thread
      or in other threads, is not executed.


.. function:: allocate_lock()

   Return a new lock object.  Methods of locks are described below.  The lock is
   initially unlocked.


.. function:: get_ident()

   Return the 'thread identifier' of the current thread.  This is a nonzero
   integer.  Its value has no direct meaning; it is intended as a magic cookie to
   be used e.g. to index a dictionary of thread-specific data.  Thread identifiers
   may be recycled when a thread exits and another thread is created.


.. function:: stack_size([size])

   Return the thread stack size used when creating new threads.  The optional
   *size* argument specifies the stack size to be used for subsequently created
   threads, and must be 0 (use platform or configured default) or a positive
   integer value of at least 32,768 (32kB). If *size* is not specified,
   0 is used. If changing the thread stack size is
   unsupported, the :exc:`error` exception is raised.  If the specified stack size is
   invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32kB
   is currently the minimum supported stack size value to guarantee sufficient
   stack space for the interpreter itself.  Note that some platforms may have
   particular restrictions on values for the stack size, such as requiring a
   minimum stack size > 32kB or requiring allocation in multiples of the system
   memory page size - platform documentation should be referred to for more
   information (4kB pages are common; using multiples of 4096 for the stack size is
   the suggested approach in the absence of more specific information).
   Availability: Windows, systems with POSIX threads.

   .. versionadded:: 2.5


Lock objects have the following methods:


.. method:: lock.acquire([waitflag])

   Without the optional argument, this method acquires the lock unconditionally, if
   necessary waiting until it is released by another thread (only one thread at a
   time can acquire a lock --- that's their reason for existence).  If the integer
   *waitflag* argument is present, the action depends on its value: if it is zero,
   the lock is only acquired if it can be acquired immediately without waiting,
   while if it is nonzero, the lock is acquired unconditionally as before.  The
   return value is ``True`` if the lock is acquired successfully, ``False`` if not.


.. method:: lock.release()

   Releases the lock.  The lock must have been acquired earlier, but not
   necessarily by the same thread.


.. method:: lock.locked()

   Return the status of the lock: ``True`` if it has been acquired by some thread,
   ``False`` if not.

In addition to these methods, lock objects can also be used via the
:keyword:`with` statement, e.g.::

   import thread

   a_lock = thread.allocate_lock()

   with a_lock:
       print "a_lock is locked while this executes"

**Caveats:**

  .. index:: module: signal

* Threads interact strangely with interrupts: the :exc:`KeyboardInterrupt`
  exception will be received by an arbitrary thread.  (When the :mod:`signal`
  module is available, interrupts always go to the main thread.)

* Calling :func:`sys.exit` or raising the :exc:`SystemExit` exception is
  equivalent to calling :func:`thread.exit`.

* It is not possible to interrupt the :meth:`acquire` method on a lock --- the
  :exc:`KeyboardInterrupt` exception will happen after the lock has been acquired.

  .. index:: pair: threads; IRIX

* When the main thread exits, it is system defined whether the other threads
  survive.  On SGI IRIX using the native thread implementation, they survive.  On
  most other systems, they are killed without executing :keyword:`try` ...
  :keyword:`finally` clauses or executing object destructors.

* When the main thread exits, it does not do any of its usual cleanup (except
  that :keyword:`try` ... :keyword:`finally` clauses are honored), and the
  standard I/O files are not flushed.

PK
%�\�n}�~�~'html/_sources/library/threading.rst.txtnu�[���:mod:`threading` --- Higher-level threading interface
=====================================================

.. module:: threading
   :synopsis: Higher-level threading interface.

**Source code:** :source:`Lib/threading.py`

--------------

This module constructs higher-level threading interfaces on top of the  lower
level :mod:`thread` module.
See also the :mod:`mutex` and :mod:`Queue` modules.

The :mod:`dummy_threading` module is provided for situations where
:mod:`threading` cannot be used because :mod:`thread` is missing.

.. note::

   Starting with Python 2.6, this module provides :pep:`8` compliant aliases and
   properties to replace the ``camelCase`` names that were inspired by Java's
   threading API. This updated API is compatible with that of the
   :mod:`multiprocessing` module. However, no schedule has been set for the
   deprecation of the ``camelCase`` names and they remain fully supported in
   both Python 2.x and 3.x.

.. note::

   Starting with Python 2.5, several Thread methods raise :exc:`RuntimeError`
   instead of :exc:`AssertionError` if called erroneously.

.. impl-detail::

   In CPython, due to the :term:`Global Interpreter Lock`, only one thread
   can execute Python code at once (even though certain performance-oriented
   libraries might overcome this limitation).
   If you want your application to make better use of the computational
   resources of multi-core machines, you are advised to use
   :mod:`multiprocessing`. However, threading is still an appropriate model
   if you want to run multiple I/O-bound tasks simultaneously.


This module defines the following functions and objects:

.. function:: active_count()
              activeCount()

   Return the number of :class:`Thread` objects currently alive.  The returned
   count is equal to the length of the list returned by :func:`.enumerate`.

   .. versionchanged:: 2.6
      Added ``active_count()`` spelling.


.. function:: Condition()
   :noindex:

   A factory function that returns a new condition variable object. A condition
   variable allows one or more threads to wait until they are notified by another
   thread.

   See :ref:`condition-objects`.


.. function:: current_thread()
              currentThread()

   Return the current :class:`Thread` object, corresponding to the caller's thread
   of control.  If the caller's thread of control was not created through the
   :mod:`threading` module, a dummy thread object with limited functionality is
   returned.

   .. versionchanged:: 2.6
      Added ``current_thread()`` spelling.


.. function:: enumerate()

   Return a list of all :class:`Thread` objects currently alive.  The list
   includes daemonic threads, dummy thread objects created by
   :func:`current_thread`, and the main thread.  It excludes terminated threads
   and threads that have not yet been started.


.. function:: Event()
   :noindex:

   A factory function that returns a new event object.  An event manages a flag
   that can be set to true with the :meth:`~Event.set` method and reset to false
   with the :meth:`clear` method.  The :meth:`wait` method blocks until the flag
   is true.

   See :ref:`event-objects`.


.. class:: local

   A class that represents thread-local data.  Thread-local data are data whose
   values are thread specific.  To manage thread-local data, just create an
   instance of :class:`local` (or a subclass) and store attributes on it::

      mydata = threading.local()
      mydata.x = 1

   The instance's values will be different for separate threads.

   For more details and extensive examples, see the documentation string of the
   :mod:`_threading_local` module.

   .. versionadded:: 2.4


.. function:: Lock()

   A factory function that returns a new primitive lock object.  Once a thread has
   acquired it, subsequent attempts to acquire it block, until it is released; any
   thread may release it.

   See :ref:`lock-objects`.


.. function:: RLock()

   A factory function that returns a new reentrant lock object. A reentrant lock
   must be released by the thread that acquired it. Once a thread has acquired a
   reentrant lock, the same thread may acquire it again without blocking; the
   thread must release it once for each time it has acquired it.

   See :ref:`rlock-objects`.


.. function:: Semaphore([value])
   :noindex:

   A factory function that returns a new semaphore object.  A semaphore manages a
   counter representing the number of :meth:`release` calls minus the number of
   :meth:`acquire` calls, plus an initial value. The :meth:`acquire` method blocks
   if necessary until it can return without making the counter negative.  If not
   given, *value* defaults to 1.

   See :ref:`semaphore-objects`.


.. function:: BoundedSemaphore([value])

   A factory function that returns a new bounded semaphore object.  A bounded
   semaphore checks to make sure its current value doesn't exceed its initial
   value.  If it does, :exc:`ValueError` is raised. In most situations semaphores
   are used to guard resources with limited capacity.  If the semaphore is released
   too many times it's a sign of a bug.  If not given, *value* defaults to 1.


.. class:: Thread
   :noindex:

   A class that represents a thread of control.  This class can be safely
   subclassed in a limited fashion.

   See :ref:`thread-objects`.


.. class:: Timer
   :noindex:

   A thread that executes a function after a specified interval has passed.

   See :ref:`timer-objects`.


.. function:: settrace(func)

   .. index:: single: trace function

   Set a trace function for all threads started from the :mod:`threading` module.
   The *func* will be passed to  :func:`sys.settrace` for each thread, before its
   :meth:`~Thread.run` method is called.

   .. versionadded:: 2.3


.. function:: setprofile(func)

   .. index:: single: profile function

   Set a profile function for all threads started from the :mod:`threading` module.
   The *func* will be passed to  :func:`sys.setprofile` for each thread, before its
   :meth:`~Thread.run` method is called.

   .. versionadded:: 2.3


.. function:: stack_size([size])

   Return the thread stack size used when creating new threads.  The optional
   *size* argument specifies the stack size to be used for subsequently created
   threads, and must be 0 (use platform or configured default) or a positive
   integer value of at least 32,768 (32 KiB). If *size* is not specified,
   0 is used.  If changing the thread stack size is
   unsupported, a :exc:`ThreadError` is raised.  If the specified stack size is
   invalid, a :exc:`ValueError` is raised and the stack size is unmodified.  32kB
   is currently the minimum supported stack size value to guarantee sufficient
   stack space for the interpreter itself.  Note that some platforms may have
   particular restrictions on values for the stack size, such as requiring a
   minimum stack size > 32kB or requiring allocation in multiples of the system
   memory page size - platform documentation should be referred to for more
   information (4kB pages are common; using multiples of 4096 for the stack size is
   the suggested approach in the absence of more specific information).
   Availability: Windows, systems with POSIX threads.

   .. versionadded:: 2.5


.. exception:: ThreadError

   Raised for various threading-related errors as described below.  Note that
   many interfaces use :exc:`RuntimeError` instead of :exc:`ThreadError`.


Detailed interfaces for the objects are documented below.

The design of this module is loosely based on Java's threading model. However,
where Java makes locks and condition variables basic behavior of every object,
they are separate objects in Python.  Python's :class:`Thread` class supports a
subset of the behavior of Java's Thread class; currently, there are no
priorities, no thread groups, and threads cannot be destroyed, stopped,
suspended, resumed, or interrupted.  The static methods of Java's Thread class,
when implemented, are mapped to module-level functions.

All of the methods described below are executed atomically.


.. _thread-objects:

Thread Objects
--------------

This class represents an activity that is run in a separate thread of control.
There are two ways to specify the activity: by passing a callable object to the
constructor, or by overriding the :meth:`run` method in a subclass.  No other
methods (except for the constructor) should be overridden in a subclass.  In
other words,  *only*  override the :meth:`__init__` and :meth:`run` methods of
this class.

Once a thread object is created, its activity must be started by calling the
thread's :meth:`start` method.  This invokes the :meth:`run` method in a
separate thread of control.

Once the thread's activity is started, the thread is considered 'alive'. It
stops being alive when its :meth:`run` method terminates -- either normally, or
by raising an unhandled exception.  The :meth:`is_alive` method tests whether the
thread is alive.

Other threads can call a thread's :meth:`join` method.  This blocks the calling
thread until the thread whose :meth:`join` method is called is terminated.

A thread has a name.  The name can be passed to the constructor, and read or
changed through the :attr:`name` attribute.

A thread can be flagged as a "daemon thread".  The significance of this flag is
that the entire Python program exits when only daemon threads are left.  The
initial value is inherited from the creating thread.  The flag can be set
through the :attr:`daemon` property.

.. note::
   Daemon threads are abruptly stopped at shutdown.  Their resources (such
   as open files, database transactions, etc.) may not be released properly.
   If you want your threads to stop gracefully, make them non-daemonic and
   use a suitable signalling mechanism such as an :class:`Event`.

There is a "main thread" object; this corresponds to the initial thread of
control in the Python program.  It is not a daemon thread.

There is the possibility that "dummy thread objects" are created. These are
thread objects corresponding to "alien threads", which are threads of control
started outside the threading module, such as directly from C code.  Dummy
thread objects have limited functionality; they are always considered alive and
daemonic, and cannot be :meth:`join`\ ed.  They are never deleted, since it is
impossible to detect the termination of alien threads.


.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})

   This constructor should always be called with keyword arguments.  Arguments
   are:

   *group* should be ``None``; reserved for future extension when a
   :class:`ThreadGroup` class is implemented.

   *target* is the callable object to be invoked by the :meth:`run` method.
   Defaults to ``None``, meaning nothing is called.

   *name* is the thread name.  By default, a unique name is constructed of the
   form "Thread-*N*" where *N* is a small decimal number.

   *args* is the argument tuple for the target invocation.  Defaults to ``()``.

   *kwargs* is a dictionary of keyword arguments for the target invocation.
   Defaults to ``{}``.

   If the subclass overrides the constructor, it must make sure to invoke the
   base class constructor (``Thread.__init__()``) before doing anything else to
   the thread.

   .. method:: start()

      Start the thread's activity.

      It must be called at most once per thread object.  It arranges for the
      object's :meth:`run` method to be invoked in a separate thread of control.

      This method will raise a :exc:`RuntimeError` if called more than once
      on the same thread object.

   .. method:: run()

      Method representing the thread's activity.

      You may override this method in a subclass.  The standard :meth:`run`
      method invokes the callable object passed to the object's constructor as
      the *target* argument, if any, with sequential and keyword arguments taken
      from the *args* and *kwargs* arguments, respectively.

   .. method:: join([timeout])

      Wait until the thread terminates. This blocks the calling thread until the
      thread whose :meth:`join` method is called terminates -- either normally
      or through an unhandled exception -- or until the optional timeout occurs.

      When the *timeout* argument is present and not ``None``, it should be a
      floating point number specifying a timeout for the operation in seconds
      (or fractions thereof). As :meth:`join` always returns ``None``, you must
      call :meth:`isAlive` after :meth:`join` to decide whether a timeout
      happened -- if the thread is still alive, the :meth:`join` call timed out.

      When the *timeout* argument is not present or ``None``, the operation will
      block until the thread terminates.

      A thread can be :meth:`join`\ ed many times.

      :meth:`join` raises a :exc:`RuntimeError` if an attempt is made to join
      the current thread as that would cause a deadlock. It is also an error to
      :meth:`join` a thread before it has been started and attempts to do so
      raises the same exception.

   .. attribute:: name

      A string used for identification purposes only. It has no semantics.
      Multiple threads may be given the same name.  The initial name is set by
      the constructor.

      .. versionadded:: 2.6

   .. method:: getName()
               setName()

      Pre-2.6 API for :attr:`~Thread.name`.

   .. attribute:: ident

      The 'thread identifier' of this thread or ``None`` if the thread has not
      been started.  This is a nonzero integer.  See the
      :func:`thread.get_ident()` function.  Thread identifiers may be recycled
      when a thread exits and another thread is created.  The identifier is
      available even after the thread has exited.

      .. versionadded:: 2.6

   .. method:: is_alive()
               isAlive()

      Return whether the thread is alive.

      This method returns ``True`` just before the :meth:`run` method starts
      until just after the :meth:`run` method terminates.  The module function
      :func:`.enumerate` returns a list of all alive threads.

      .. versionchanged:: 2.6
         Added ``is_alive()`` spelling.

   .. attribute:: daemon

      A boolean value indicating whether this thread is a daemon thread (True)
      or not (False).  This must be set before :meth:`start` is called,
      otherwise :exc:`RuntimeError` is raised.  Its initial value is inherited
      from the creating thread; the main thread is not a daemon thread and
      therefore all threads created in the main thread default to :attr:`daemon`
      = ``False``.

      The entire Python program exits when no alive non-daemon threads are left.

      .. versionadded:: 2.6

   .. method:: isDaemon()
               setDaemon()

      Pre-2.6 API for :attr:`~Thread.daemon`.


.. _lock-objects:

Lock Objects
------------

A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked.  In Python, it is currently the lowest level
synchronization primitive available, implemented directly by the :mod:`thread`
extension module.

A primitive lock is in one of two states, "locked" or "unlocked". It is created
in the unlocked state.  It has two basic methods, :meth:`acquire` and
:meth:`release`.  When the state is unlocked, :meth:`acquire` changes the state
to locked and returns immediately.  When the state is locked, :meth:`acquire`
blocks until a call to :meth:`release` in another thread changes it to unlocked,
then the :meth:`acquire` call resets it to locked and returns.  The
:meth:`release` method should only be called in the locked state; it changes the
state to unlocked and returns immediately. If an attempt is made to release an
unlocked lock, a :exc:`ThreadError` will be raised.

When more than one thread is blocked in :meth:`acquire` waiting for the state to
turn to unlocked, only one thread proceeds when a :meth:`release` call resets
the state to unlocked; which one of the waiting threads proceeds is not defined,
and may vary across implementations.

All methods are executed atomically.


.. method:: Lock.acquire([blocking])

   Acquire a lock, blocking or non-blocking.

   When invoked with the *blocking* argument set to ``True`` (the default),
   block until the lock is unlocked, then set it to locked and return ``True``.

   When invoked with the *blocking* argument set to ``False``, do not block.
   If a call with *blocking* set to ``True`` would block, return ``False``
   immediately; otherwise, set the lock to locked and return ``True``.


.. method:: Lock.release()

   Release a lock.

   When the lock is locked, reset it to unlocked, and return.  If any other threads
   are blocked waiting for the lock to become unlocked, allow exactly one of them
   to proceed.

   When invoked on an unlocked lock, a :exc:`ThreadError` is raised.

   There is no return value.


.. _rlock-objects:

RLock Objects
-------------

A reentrant lock is a synchronization primitive that may be acquired multiple
times by the same thread.  Internally, it uses the concepts of "owning thread"
and "recursion level" in addition to the locked/unlocked state used by primitive
locks.  In the locked state, some thread owns the lock; in the unlocked state,
no thread owns it.

To lock the lock, a thread calls its :meth:`acquire` method; this returns once
the thread owns the lock.  To unlock the lock, a thread calls its
:meth:`release` method. :meth:`acquire`/:meth:`release` call pairs may be
nested; only the final :meth:`release` (the :meth:`release` of the outermost
pair) resets the lock to unlocked and allows another thread blocked in
:meth:`acquire` to proceed.


.. method:: RLock.acquire([blocking=1])

   Acquire a lock, blocking or non-blocking.

   When invoked without arguments: if this thread already owns the lock, increment
   the recursion level by one, and return immediately.  Otherwise, if another
   thread owns the lock, block until the lock is unlocked.  Once the lock is
   unlocked (not owned by any thread), then grab ownership, set the recursion level
   to one, and return.  If more than one thread is blocked waiting until the lock
   is unlocked, only one at a time will be able to grab ownership of the lock.
   There is no return value in this case.

   When invoked with the *blocking* argument set to true, do the same thing as when
   called without arguments, and return true.

   When invoked with the *blocking* argument set to false, do not block.  If a call
   without an argument would block, return false immediately; otherwise, do the
   same thing as when called without arguments, and return true.


.. method:: RLock.release()

   Release a lock, decrementing the recursion level.  If after the decrement it is
   zero, reset the lock to unlocked (not owned by any thread), and if any other
   threads are blocked waiting for the lock to become unlocked, allow exactly one
   of them to proceed.  If after the decrement the recursion level is still
   nonzero, the lock remains locked and owned by the calling thread.

   Only call this method when the calling thread owns the lock. A
   :exc:`RuntimeError` is raised if this method is called when the lock is
   unlocked.

   There is no return value.


.. _condition-objects:

Condition Objects
-----------------

A condition variable is always associated with some kind of lock; this can be
passed in or one will be created by default.  (Passing one in is useful when
several condition variables must share the same lock.)

A condition variable has :meth:`acquire` and :meth:`release` methods that call
the corresponding methods of the associated lock. It also has a :meth:`wait`
method, and :meth:`notify` and :meth:`notifyAll` methods.  These three must only
be called when the calling thread has acquired the lock, otherwise a
:exc:`RuntimeError` is raised.

The :meth:`wait` method releases the lock, and then blocks until it is awakened
by a :meth:`notify` or :meth:`notifyAll` call for the same condition variable in
another thread.  Once awakened, it re-acquires the lock and returns.  It is also
possible to specify a timeout.

The :meth:`notify` method wakes up one of the threads waiting for the condition
variable, if any are waiting.  The :meth:`notifyAll` method wakes up all threads
waiting for the condition variable.

Note: the :meth:`notify` and :meth:`notifyAll` methods don't release the lock;
this means that the thread or threads awakened will not return from their
:meth:`wait` call immediately, but only when the thread that called
:meth:`notify` or :meth:`notifyAll` finally relinquishes ownership of the lock.

Tip: the typical programming style using condition variables uses the lock to
synchronize access to some shared state; threads that are interested in a
particular change of state call :meth:`wait` repeatedly until they see the
desired state, while threads that modify the state call :meth:`notify` or
:meth:`notifyAll` when they change the state in such a way that it could
possibly be a desired state for one of the waiters.  For example, the following
code is a generic producer-consumer situation with unlimited buffer capacity::

   # Consume one item
   cv.acquire()
   while not an_item_is_available():
       cv.wait()
   get_an_available_item()
   cv.release()

   # Produce one item
   cv.acquire()
   make_an_item_available()
   cv.notify()
   cv.release()

To choose between :meth:`notify` and :meth:`notifyAll`, consider whether one
state change can be interesting for only one or several waiting threads.  E.g.
in a typical producer-consumer situation, adding one item to the buffer only
needs to wake up one consumer thread.


.. class:: Condition([lock])

   If the *lock* argument is given and not ``None``, it must be a :class:`Lock`
   or :class:`RLock` object, and it is used as the underlying lock.  Otherwise,
   a new :class:`RLock` object is created and used as the underlying lock.

   .. method:: acquire(*args)

      Acquire the underlying lock. This method calls the corresponding method on
      the underlying lock; the return value is whatever that method returns.

   .. method:: release()

      Release the underlying lock. This method calls the corresponding method on
      the underlying lock; there is no return value.

   .. method:: wait([timeout])

      Wait until notified or until a timeout occurs. If the calling thread has not
      acquired the lock when this method is called, a :exc:`RuntimeError` is raised.

      This method releases the underlying lock, and then blocks until it is
      awakened by a :meth:`notify` or :meth:`notifyAll` call for the same
      condition variable in another thread, or until the optional timeout
      occurs.  Once awakened or timed out, it re-acquires the lock and returns.

      When the *timeout* argument is present and not ``None``, it should be a
      floating point number specifying a timeout for the operation in seconds
      (or fractions thereof).

      When the underlying lock is an :class:`RLock`, it is not released using
      its :meth:`release` method, since this may not actually unlock the lock
      when it was acquired multiple times recursively.  Instead, an internal
      interface of the :class:`RLock` class is used, which really unlocks it
      even when it has been recursively acquired several times. Another internal
      interface is then used to restore the recursion level when the lock is
      reacquired.

   .. method:: notify(n=1)

      By default, wake up one thread waiting on this condition, if any.  If the
      calling thread has not acquired the lock when this method is called, a
      :exc:`RuntimeError` is raised.

      This method wakes up at most *n* of the threads waiting for the condition
      variable; it is a no-op if no threads are waiting.

      The current implementation wakes up exactly *n* threads, if at least *n*
      threads are waiting.  However, it's not safe to rely on this behavior.
      A future, optimized implementation may occasionally wake up more than
      *n* threads.

      Note: an awakened thread does not actually return from its :meth:`wait`
      call until it can reacquire the lock.  Since :meth:`notify` does not
      release the lock, its caller should.

   .. method:: notify_all()
               notifyAll()

      Wake up all threads waiting on this condition.  This method acts like
      :meth:`notify`, but wakes up all waiting threads instead of one. If the
      calling thread has not acquired the lock when this method is called, a
      :exc:`RuntimeError` is raised.

      .. versionchanged:: 2.6
         Added ``notify_all()`` spelling.


.. _semaphore-objects:

Semaphore Objects
-----------------

This is one of the oldest synchronization primitives in the history of computer
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
used :meth:`P` and :meth:`V` instead of :meth:`acquire` and :meth:`release`).

A semaphore manages an internal counter which is decremented by each
:meth:`acquire` call and incremented by each :meth:`release` call.  The counter
can never go below zero; when :meth:`acquire` finds that it is zero, it blocks,
waiting until some other thread calls :meth:`release`.


.. class:: Semaphore([value])

   The optional argument gives the initial *value* for the internal counter; it
   defaults to ``1``. If the *value* given is less than 0, :exc:`ValueError` is
   raised.

   .. method:: acquire([blocking])

      Acquire a semaphore.

      When invoked without arguments: if the internal counter is larger than
      zero on entry, decrement it by one and return immediately.  If it is zero
      on entry, block, waiting until some other thread has called
      :meth:`release` to make it larger than zero.  This is done with proper
      interlocking so that if multiple :meth:`acquire` calls are blocked,
      :meth:`release` will wake exactly one of them up.  The implementation may
      pick one at random, so the order in which blocked threads are awakened
      should not be relied on.  There is no return value in this case.

      When invoked with *blocking* set to true, do the same thing as when called
      without arguments, and return true.

      When invoked with *blocking* set to false, do not block.  If a call
      without an argument would block, return false immediately; otherwise, do
      the same thing as when called without arguments, and return true.

   .. method:: release()

      Release a semaphore, incrementing the internal counter by one.  When it
      was zero on entry and another thread is waiting for it to become larger
      than zero again, wake up that thread.


.. _semaphore-examples:

:class:`Semaphore` Example
^^^^^^^^^^^^^^^^^^^^^^^^^^

Semaphores are often used to guard resources with limited capacity, for example,
a database server.  In any situation where the size of the resource is fixed,
you should use a bounded semaphore.  Before spawning any worker threads, your
main thread would initialize the semaphore::

   maxconnections = 5
   ...
   pool_sema = BoundedSemaphore(value=maxconnections)

Once spawned, worker threads call the semaphore's acquire and release methods
when they need to connect to the server::

   pool_sema.acquire()
   conn = connectdb()
   ... use connection ...
   conn.close()
   pool_sema.release()

The use of a bounded semaphore reduces the chance that a programming error which
causes the semaphore to be released more than it's acquired will go undetected.


.. _event-objects:

Event Objects
-------------

This is one of the simplest mechanisms for communication between threads: one
thread signals an event and other threads wait for it.

An event object manages an internal flag that can be set to true with the
:meth:`~Event.set` method and reset to false with the :meth:`~Event.clear`
method.  The :meth:`~Event.wait` method blocks until the flag is true.


.. class:: Event()

   The internal flag is initially false.

   .. method:: is_set()
               isSet()

      Return true if and only if the internal flag is true.

      .. versionchanged:: 2.6
         Added ``is_set()`` spelling.

   .. method:: set()

      Set the internal flag to true. All threads waiting for it to become true
      are awakened. Threads that call :meth:`wait` once the flag is true will
      not block at all.

   .. method:: clear()

      Reset the internal flag to false. Subsequently, threads calling
      :meth:`wait` will block until :meth:`.set` is called to set the internal
      flag to true again.

   .. method:: wait([timeout])

      Block until the internal flag is true.  If the internal flag is true on
      entry, return immediately.  Otherwise, block until another thread calls
      :meth:`.set` to set the flag to true, or until the optional timeout
      occurs.

      When the timeout argument is present and not ``None``, it should be a
      floating point number specifying a timeout for the operation in seconds
      (or fractions thereof).

      This method returns the internal flag on exit, so it will always return
      ``True`` except if a timeout is given and the operation times out.

      .. versionchanged:: 2.7
         Previously, the method always returned ``None``.


.. _timer-objects:

Timer Objects
-------------

This class represents an action that should be run only after a certain amount
of time has passed --- a timer.  :class:`Timer` is a subclass of :class:`Thread`
and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their :meth:`~Timer.start`
method.  The timer can be stopped (before its action has begun) by calling the
:meth:`~Timer.cancel` method.  The interval the timer will wait before
executing its action may not be exactly the same as the interval specified by
the user.

For example::

   def hello():
       print "hello, world"

   t = Timer(30.0, hello)
   t.start()  # after 30 seconds, "hello, world" will be printed


.. class:: Timer(interval, function, args=[], kwargs={})

   Create a timer that will run *function* with arguments *args* and  keyword
   arguments *kwargs*, after *interval* seconds have passed.

   .. method:: cancel()

      Stop the timer, and cancel the execution of the timer's action.  This will
      only work if the timer is still in its waiting stage.


.. _with-locks:

Using locks, conditions, and semaphores in the :keyword:`with` statement
------------------------------------------------------------------------

All of the objects provided by this module that have :meth:`acquire` and
:meth:`release` methods can be used as context managers for a :keyword:`with`
statement.  The :meth:`acquire` method will be called when the block is entered,
and :meth:`release` will be called when the block is exited.

Currently, :class:`Lock`, :class:`RLock`, :class:`Condition`,
:class:`Semaphore`, and :class:`BoundedSemaphore` objects may be used as
:keyword:`with` statement context managers.  For example::

   import threading

   some_rlock = threading.RLock()

   with some_rlock:
       print "some_rlock is locked while this executes"


.. _threaded-imports:

Importing in threaded code
--------------------------

While the import machinery is thread-safe, there are two key restrictions on
threaded imports due to inherent limitations in the way that thread-safety is
provided:

* Firstly, other than in the main module, an import should not have the
  side effect of spawning a new thread and then waiting for that thread in
  any way. Failing to abide by this restriction can lead to a deadlock if
  the spawned thread directly or indirectly attempts to import a module.
* Secondly, all import attempts must be completed before the interpreter
  starts shutting itself down. This can be most easily achieved by only
  performing imports from non-daemon threads created through the threading
  module. Daemon threads and threads created directly with the thread
  module will require some other form of synchronization to ensure they do
  not attempt imports after system shutdown has commenced. Failure to
  abide by this restriction will lead to intermittent exceptions and
  crashes during interpreter shutdown (as the late imports attempt to
  access machinery which is no longer in a valid state).
PK
%�\�Wm�e�e"html/_sources/library/time.rst.txtnu�[���
:mod:`time` --- Time access and conversions
===========================================

.. module:: time
   :synopsis: Time access and conversions.


This module provides various time-related functions. For related
functionality, see also the :mod:`datetime` and :mod:`calendar` modules.

Although this module is always available,
not all functions are available on all platforms.  Most of the functions
defined in this module call platform C library functions with the same name.  It
may sometimes be helpful to consult the platform documentation, because the
semantics of these functions varies among platforms.

An explanation of some terminology and conventions is in order.

.. index:: single: epoch

* The :dfn:`epoch` is the point where the time starts.  On January 1st of that
  year, at 0 hours, the "time since the epoch" is zero.  For Unix, the epoch is
  1970.  To find out what the epoch is, look at ``gmtime(0)``.

.. index:: single: Year 2038

* The functions in this module do not handle dates and times before the epoch or
  far in the future.  The cut-off point in the future is determined by the C
  library; for Unix, it is typically in 2038.

.. index::
   single: Year 2000
   single: Y2K

.. _time-y2kissues:

* **Year 2000 (Y2K) issues**:  Python depends on the platform's C library, which
  generally doesn't have year 2000 issues, since all dates and times are
  represented internally as seconds since the epoch.  Functions accepting a
  :class:`struct_time` (see below) generally require a 4-digit year.  For backward
  compatibility, 2-digit years are supported if the module variable
  ``accept2dyear`` is a non-zero integer; this variable is initialized to ``1``
  unless the environment variable :envvar:`PYTHONY2K` is set to a non-empty
  string, in which case it is initialized to ``0``.  Thus, you can set
  :envvar:`PYTHONY2K` to a non-empty string in the environment to require 4-digit
  years for all year input.  When 2-digit years are accepted, they are converted
  according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999,
  and values 0--68 are mapped to 2000--2068. Values 100--1899 are always illegal.

.. index::
   single: UTC
   single: Coordinated Universal Time
   single: Greenwich Mean Time

* UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or
  GMT).  The acronym UTC is not a mistake but a compromise between English and
  French.

.. index:: single: Daylight Saving Time

* DST is Daylight Saving Time, an adjustment of the timezone by (usually) one
  hour during part of the year.  DST rules are magic (determined by local law) and
  can change from year to year.  The C library has a table containing the local
  rules (often it is read from a system file for flexibility) and is the only
  source of True Wisdom in this respect.

* The precision of the various real-time functions may be less than suggested by
  the units in which their value or argument is expressed. E.g. on most Unix
  systems, the clock "ticks" only 50 or 100 times a second.

* On the other hand, the precision of :func:`.time` and :func:`sleep` is better
  than their Unix equivalents: times are expressed as floating point numbers,
  :func:`.time` returns the most accurate time available (using Unix
  :c:func:`gettimeofday` where available), and :func:`sleep` will accept a time
  with a nonzero fraction (Unix :c:func:`select` is used to implement this, where
  available).

* The time value as returned by :func:`gmtime`, :func:`localtime`, and
  :func:`strptime`, and accepted by :func:`asctime`, :func:`mktime` and
  :func:`strftime`, may be considered as a sequence of 9 integers.  The return
  values of :func:`gmtime`, :func:`localtime`, and :func:`strptime` also offer
  attribute names for individual fields.

  See :class:`struct_time` for a description of these objects.

  .. versionchanged:: 2.2
     The time value sequence was changed from a tuple to a :class:`struct_time`, with
     the addition of attribute names for the fields.

* Use the following functions to convert between time representations:

  +-------------------------+-------------------------+-------------------------+
  | From                    | To                      | Use                     |
  +=========================+=========================+=========================+
  | seconds since the epoch | :class:`struct_time` in | :func:`gmtime`          |
  |                         | UTC                     |                         |
  +-------------------------+-------------------------+-------------------------+
  | seconds since the epoch | :class:`struct_time` in | :func:`localtime`       |
  |                         | local time              |                         |
  +-------------------------+-------------------------+-------------------------+
  | :class:`struct_time` in | seconds since the epoch | :func:`calendar.timegm` |
  | UTC                     |                         |                         |
  +-------------------------+-------------------------+-------------------------+
  | :class:`struct_time` in | seconds since the epoch | :func:`mktime`          |
  | local time              |                         |                         |
  +-------------------------+-------------------------+-------------------------+


The module defines the following functions and data items:

.. data:: accept2dyear

   Boolean value indicating whether two-digit year values will be accepted.  This
   is true by default, but will be set to false if the environment variable
   :envvar:`PYTHONY2K` has been set to a non-empty string.  It may also be modified
   at run time.


.. data:: altzone

   The offset of the local DST timezone, in seconds west of UTC, if one is defined.
   This is negative if the local DST timezone is east of UTC (as in Western Europe,
   including the UK).  Only use this if ``daylight`` is nonzero.


.. function:: asctime([t])

   Convert a tuple or :class:`struct_time` representing a time as returned by
   :func:`gmtime` or :func:`localtime` to a 24-character string of the following
   form: ``'Sun Jun 20 23:21:05 1993'``.  If *t* is not provided, the current time
   as returned by :func:`localtime` is used. Locale information is not used by
   :func:`asctime`.

   .. note::

      Unlike the C function of the same name, there is no trailing newline.

   .. versionchanged:: 2.1
      Allowed *t* to be omitted.


.. function:: clock()

   .. index::
      single: CPU time
      single: processor time
      single: benchmarking

   On Unix, return the current processor time as a floating point number expressed
   in seconds.  The precision, and in fact the very definition of the meaning of
   "processor time", depends on that of the C function of the same name, but in any
   case, this is the function to use for benchmarking Python or timing algorithms.

   On Windows, this function returns wall-clock seconds elapsed since the first
   call to this function, as a floating point number, based on the Win32 function
   :c:func:`QueryPerformanceCounter`. The resolution is typically better than one
   microsecond.


.. function:: ctime([secs])

   Convert a time expressed in seconds since the epoch to a string representing
   local time. If *secs* is not provided or :const:`None`, the current time as
   returned by :func:`.time` is used.  ``ctime(secs)`` is equivalent to
   ``asctime(localtime(secs))``. Locale information is not used by :func:`ctime`.

   .. versionchanged:: 2.1
      Allowed *secs* to be omitted.

   .. versionchanged:: 2.4
      If *secs* is :const:`None`, the current time is used.


.. data:: daylight

   Nonzero if a DST timezone is defined.


.. function:: gmtime([secs])

   Convert a time expressed in seconds since the epoch to a :class:`struct_time` in
   UTC in which the dst flag is always zero.  If *secs* is not provided or
   :const:`None`, the current time as returned by :func:`.time` is used.  Fractions
   of a second are ignored.  See above for a description of the
   :class:`struct_time` object. See :func:`calendar.timegm` for the inverse of this
   function.

   .. versionchanged:: 2.1
      Allowed *secs* to be omitted.

   .. versionchanged:: 2.4
      If *secs* is :const:`None`, the current time is used.


.. function:: localtime([secs])

   Like :func:`gmtime` but converts to local time.  If *secs* is not provided or
   :const:`None`, the current time as returned by :func:`.time` is used.  The dst
   flag is set to ``1`` when DST applies to the given time.

   .. versionchanged:: 2.1
      Allowed *secs* to be omitted.

   .. versionchanged:: 2.4
      If *secs* is :const:`None`, the current time is used.


.. function:: mktime(t)

   This is the inverse function of :func:`localtime`.  Its argument is the
   :class:`struct_time` or full 9-tuple (since the dst flag is needed; use ``-1``
   as the dst flag if it is unknown) which expresses the time in *local* time, not
   UTC.  It returns a floating point number, for compatibility with :func:`.time`.
   If the input value cannot be represented as a valid time, either
   :exc:`OverflowError` or :exc:`ValueError` will be raised (which depends on
   whether the invalid value is caught by Python or the underlying C libraries).
   The earliest date for which it can generate a time is platform-dependent.


.. function:: sleep(secs)

   Suspend execution of the current thread for the given number of seconds.
   The argument may be a floating point number to indicate a more precise sleep
   time. The actual suspension time may be less than that requested because any
   caught signal will terminate the :func:`sleep` following execution of that
   signal's catching routine.  Also, the suspension time may be longer than
   requested by an arbitrary amount because of the scheduling of other activity
   in the system.


.. function:: strftime(format[, t])

   Convert a tuple or :class:`struct_time` representing a time as returned by
   :func:`gmtime` or :func:`localtime` to a string as specified by the *format*
   argument.  If *t* is not provided, the current time as returned by
   :func:`localtime` is used.  *format* must be a string.  :exc:`ValueError` is
   raised if any field in *t* is outside of the allowed range. :func:`strftime`
   returns a locale dependent byte string; the result may be converted to unicode
   by doing ``strftime(<myformat>).decode(locale.getlocale()[1])``.

   .. versionchanged:: 2.1
      Allowed *t* to be omitted.

   .. versionchanged:: 2.4
      :exc:`ValueError` raised if a field in *t* is out of range.

   .. versionchanged:: 2.5
      0 is now a legal argument for any position in the time tuple; if it is normally
      illegal the value is forced to a correct one.

   The following directives can be embedded in the *format* string. They are shown
   without the optional field width and precision specification, and are replaced
   by the indicated characters in the :func:`strftime` result:

   +-----------+--------------------------------+-------+
   | Directive | Meaning                        | Notes |
   +===========+================================+=======+
   | ``%a``    | Locale's abbreviated weekday   |       |
   |           | name.                          |       |
   +-----------+--------------------------------+-------+
   | ``%A``    | Locale's full weekday name.    |       |
   +-----------+--------------------------------+-------+
   | ``%b``    | Locale's abbreviated month     |       |
   |           | name.                          |       |
   +-----------+--------------------------------+-------+
   | ``%B``    | Locale's full month name.      |       |
   +-----------+--------------------------------+-------+
   | ``%c``    | Locale's appropriate date and  |       |
   |           | time representation.           |       |
   +-----------+--------------------------------+-------+
   | ``%d``    | Day of the month as a decimal  |       |
   |           | number [01,31].                |       |
   +-----------+--------------------------------+-------+
   | ``%H``    | Hour (24-hour clock) as a      |       |
   |           | decimal number [00,23].        |       |
   +-----------+--------------------------------+-------+
   | ``%I``    | Hour (12-hour clock) as a      |       |
   |           | decimal number [01,12].        |       |
   +-----------+--------------------------------+-------+
   | ``%j``    | Day of the year as a decimal   |       |
   |           | number [001,366].              |       |
   +-----------+--------------------------------+-------+
   | ``%m``    | Month as a decimal number      |       |
   |           | [01,12].                       |       |
   +-----------+--------------------------------+-------+
   | ``%M``    | Minute as a decimal number     |       |
   |           | [00,59].                       |       |
   +-----------+--------------------------------+-------+
   | ``%p``    | Locale's equivalent of either  | \(1)  |
   |           | AM or PM.                      |       |
   +-----------+--------------------------------+-------+
   | ``%S``    | Second as a decimal number     | \(2)  |
   |           | [00,61].                       |       |
   +-----------+--------------------------------+-------+
   | ``%U``    | Week number of the year        | \(3)  |
   |           | (Sunday as the first day of    |       |
   |           | the week) as a decimal number  |       |
   |           | [00,53].  All days in a new    |       |
   |           | year preceding the first       |       |
   |           | Sunday are considered to be in |       |
   |           | week 0.                        |       |
   +-----------+--------------------------------+-------+
   | ``%w``    | Weekday as a decimal number    |       |
   |           | [0(Sunday),6].                 |       |
   +-----------+--------------------------------+-------+
   | ``%W``    | Week number of the year        | \(3)  |
   |           | (Monday as the first day of    |       |
   |           | the week) as a decimal number  |       |
   |           | [00,53].  All days in a new    |       |
   |           | year preceding the first       |       |
   |           | Monday are considered to be in |       |
   |           | week 0.                        |       |
   +-----------+--------------------------------+-------+
   | ``%x``    | Locale's appropriate date      |       |
   |           | representation.                |       |
   +-----------+--------------------------------+-------+
   | ``%X``    | Locale's appropriate time      |       |
   |           | representation.                |       |
   +-----------+--------------------------------+-------+
   | ``%y``    | Year without century as a      |       |
   |           | decimal number [00,99].        |       |
   +-----------+--------------------------------+-------+
   | ``%Y``    | Year with century as a decimal |       |
   |           | number.                        |       |
   +-----------+--------------------------------+-------+
   | ``%Z``    | Time zone name (no characters  |       |
   |           | if no time zone exists).       |       |
   +-----------+--------------------------------+-------+
   | ``%%``    | A literal ``'%'`` character.   |       |
   +-----------+--------------------------------+-------+

   Notes:

   (1)
      When used with the :func:`strptime` function, the ``%p`` directive only affects
      the output hour field if the ``%I`` directive is used to parse the hour.

   (2)
      The range really is ``0`` to ``61``; this accounts for leap seconds and the
      (very rare) double leap seconds.

   (3)
      When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
      calculations when the day of the week and the year are specified.

   Here is an example, a format for dates compatible with that specified  in the
   :rfc:`2822` Internet email standard.  [#]_ ::

      >>> from time import gmtime, strftime
      >>> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
      'Thu, 28 Jun 2001 14:17:15 +0000'

   Additional directives may be supported on certain platforms, but only the
   ones listed here have a meaning standardized by ANSI C.  To see the full set
   of format codes supported on your platform, consult the :manpage:`strftime(3)`
   documentation.

   On some platforms, an optional field width and precision specification can
   immediately follow the initial ``'%'`` of a directive in the following order;
   this is also not portable. The field width is normally 2 except for ``%j`` where
   it is 3.


.. function:: strptime(string[, format])

   Parse a string representing a time according to a format.  The return  value is
   a :class:`struct_time` as returned by :func:`gmtime` or :func:`localtime`.

   The *format* parameter uses the same directives as those used by
   :func:`strftime`; it defaults to ``"%a %b %d %H:%M:%S %Y"`` which matches the
   formatting returned by :func:`ctime`. If *string* cannot be parsed according to
   *format*, or if it has excess data after parsing, :exc:`ValueError` is raised.
   The default values used to fill in any missing data when more accurate values
   cannot be inferred are ``(1900, 1, 1, 0, 0, 0, 0, 1, -1)``.

   For example:

      >>> import time
      >>> time.strptime("30 Nov 00", "%d %b %y")   # doctest: +NORMALIZE_WHITESPACE
      time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
                       tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)

   Support for the ``%Z`` directive is based on the values contained in ``tzname``
   and whether ``daylight`` is true.  Because of this, it is platform-specific
   except for recognizing UTC and GMT which are always known (and are considered to
   be non-daylight savings timezones).

   Only the directives specified in the documentation are supported.  Because
   ``strftime()`` is implemented per platform it can sometimes offer more
   directives than those listed.  But ``strptime()`` is independent of any platform
   and thus does not necessarily support all directives available that are not
   documented as supported.


.. class:: struct_time

   The type of the time value sequence returned by :func:`gmtime`,
   :func:`localtime`, and :func:`strptime`.  It is an object with a :term:`named
   tuple` interface: values can be accessed by index and by attribute name.  The
   following values are present:

   +-------+-------------------+---------------------------------+
   | Index | Attribute         | Values                          |
   +=======+===================+=================================+
   | 0     | :attr:`tm_year`   | (for example, 1993)             |
   +-------+-------------------+---------------------------------+
   | 1     | :attr:`tm_mon`    | range [1, 12]                   |
   +-------+-------------------+---------------------------------+
   | 2     | :attr:`tm_mday`   | range [1, 31]                   |
   +-------+-------------------+---------------------------------+
   | 3     | :attr:`tm_hour`   | range [0, 23]                   |
   +-------+-------------------+---------------------------------+
   | 4     | :attr:`tm_min`    | range [0, 59]                   |
   +-------+-------------------+---------------------------------+
   | 5     | :attr:`tm_sec`    | range [0, 61]; see **(2)** in   |
   |       |                   | :func:`strftime` description    |
   +-------+-------------------+---------------------------------+
   | 6     | :attr:`tm_wday`   | range [0, 6], Monday is 0       |
   +-------+-------------------+---------------------------------+
   | 7     | :attr:`tm_yday`   | range [1, 366]                  |
   +-------+-------------------+---------------------------------+
   | 8     | :attr:`tm_isdst`  | 0, 1 or -1; see below           |
   +-------+-------------------+---------------------------------+

   .. versionadded:: 2.2

   Note that unlike the C structure, the month value is a range of [1, 12], not
   [0, 11].  A year value will be handled as described under :ref:`Year 2000
   (Y2K) issues <time-y2kissues>` above.

   In calls to :func:`mktime`, :attr:`tm_isdst` may be set to 1 when daylight
   savings time is in effect, and 0 when it is not.  A value of -1 indicates
   that this is not known, and will usually result in the correct state being
   filled in.

   When a tuple with an incorrect length is passed to a function expecting a
   :class:`struct_time`, or having elements of the wrong type, a
   :exc:`TypeError` is raised.


.. function:: time()

   Return the time in seconds since the epoch as a floating point number.
   Note that even though the time is always returned as a floating point
   number, not all systems provide time with a better precision than 1 second.
   While this function normally returns non-decreasing values, it can return a
   lower value than a previous call if the system clock has been set back between
   the two calls.


.. data:: timezone

   The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
   most of Western Europe, positive in the US, zero in the UK).


.. data:: tzname

   A tuple of two strings: the first is the name of the local non-DST timezone, the
   second is the name of the local DST timezone.  If no DST timezone is defined,
   the second string should not be used.


.. function:: tzset()

   Reset the time conversion rules used by the library routines. The environment
   variable :envvar:`TZ` specifies how this is done. It will also set the variables
   ``tzname`` (from the :envvar:`TZ` environment variable), ``timezone`` (non-DST
   seconds West of UTC), ``altzone`` (DST seconds west of UTC) and ``daylight``
   (to 0 if this timezone does not have any daylight saving time rules, or to
   nonzero if there is a time, past, present or future when daylight saving time
   applies).

   .. versionadded:: 2.3

   Availability: Unix.

   .. note::

      Although in many cases, changing the :envvar:`TZ` environment variable may
      affect the output of functions like :func:`localtime` without calling
      :func:`tzset`, this behavior should not be relied on.

      The :envvar:`TZ` environment variable should contain no whitespace.

   The standard format of the :envvar:`TZ` environment variable is (whitespace
   added for clarity)::

      std offset [dst [offset [,start[/time], end[/time]]]]

   Where the components are:

   ``std`` and ``dst``
      Three or more alphanumerics giving the timezone abbreviations. These will be
      propagated into time.tzname

   ``offset``
      The offset has the form: ``± hh[:mm[:ss]]``. This indicates the value
      added the local time to arrive at UTC.  If preceded by a '-', the timezone
      is east of the Prime Meridian; otherwise, it is west. If no offset follows
      dst, summer time is assumed to be one hour ahead of standard time.

   ``start[/time], end[/time]``
      Indicates when to change to and back from DST. The format of the
      start and end dates are one of the following:

      :samp:`J{n}`
         The Julian day *n* (1 <= *n* <= 365). Leap days are not counted, so in
         all years February 28 is day 59 and March 1 is day 60.

      :samp:`{n}`
         The zero-based Julian day (0 <= *n* <= 365). Leap days are counted, and
         it is possible to refer to February 29.

      :samp:`M{m}.{n}.{d}`
         The *d*'th day (0 <= *d* <= 6) or week *n* of month *m* of the year (1
         <= *n* <= 5, 1 <= *m* <= 12, where week 5 means "the last *d* day in
         month *m*" which may occur in either the fourth or the fifth
         week). Week 1 is the first week in which the *d*'th day occurs. Day
         zero is Sunday.

      ``time`` has the same format as ``offset`` except that no leading sign
      ('-' or '+') is allowed. The default, if time is not given, is 02:00:00.

   ::

      >>> os.environ['TZ'] = 'EST+05EDT,M4.1.0,M10.5.0'
      >>> time.tzset()
      >>> time.strftime('%X %x %Z')
      '02:07:36 05/08/03 EDT'
      >>> os.environ['TZ'] = 'AEST-10AEDT-11,M10.5.0,M3.5.0'
      >>> time.tzset()
      >>> time.strftime('%X %x %Z')
      '16:08:12 05/08/03 AEST'

   On many Unix systems (including \*BSD, Linux, Solaris, and Darwin), it is more
   convenient to use the system's zoneinfo (:manpage:`tzfile(5)`)  database to
   specify the timezone rules. To do this, set the  :envvar:`TZ` environment
   variable to the path of the required timezone  datafile, relative to the root of
   the systems 'zoneinfo' timezone database, usually located at
   :file:`/usr/share/zoneinfo`. For example,  ``'US/Eastern'``,
   ``'Australia/Melbourne'``, ``'Egypt'`` or  ``'Europe/Amsterdam'``. ::

      >>> os.environ['TZ'] = 'US/Eastern'
      >>> time.tzset()
      >>> time.tzname
      ('EST', 'EDT')
      >>> os.environ['TZ'] = 'Egypt'
      >>> time.tzset()
      >>> time.tzname
      ('EET', 'EEST')


.. seealso::

   Module :mod:`datetime`
      More object-oriented interface to dates and times.

   Module :mod:`locale`
      Internationalization services.  The locale setting affects the interpretation
      of many format specifiers in :func:`strftime` and :func:`strptime`.

   Module :mod:`calendar`
      General calendar-related functions.   :func:`~calendar.timegm` is the
      inverse of :func:`gmtime` from this module.

.. rubric:: Footnotes

.. [#] The use of ``%Z`` is now deprecated, but the ``%z`` escape that expands to the
   preferred  hour/minute offset is not supported by all ANSI C libraries. Also, a
   strict reading of the original 1982 :rfc:`822` standard calls for a two-digit
   year (%y rather than %Y), but practice moved to 4-digit years long before the
   year 2000.  After that, :rfc:`822` became obsolete and the 4-digit year has
   been first recommended by :rfc:`1123` and then mandated by :rfc:`2822`.

PK
%�\���N-N-$html/_sources/library/timeit.rst.txtnu�[���:mod:`timeit` --- Measure execution time of small code snippets
===============================================================

.. module:: timeit
   :synopsis: Measure the execution time of small code snippets.


.. versionadded:: 2.3

.. index::
   single: Benchmarking
   single: Performance

**Source code:** :source:`Lib/timeit.py`

--------------

This module provides a simple way to time small bits of Python code. It has both
a :ref:`timeit-command-line-interface` as well as a :ref:`callable <python-interface>`
one.  It avoids a number of common traps for measuring execution times.
See also Tim Peters' introduction to the "Algorithms" chapter in the *Python
Cookbook*, published by O'Reilly.


Basic Examples
--------------

The following example shows how the :ref:`timeit-command-line-interface`
can be used to compare three different expressions:

.. code-block:: sh

   $ python -m timeit '"-".join(str(n) for n in range(100))'
   10000 loops, best of 3: 40.3 usec per loop
   $ python -m timeit '"-".join([str(n) for n in range(100)])'
   10000 loops, best of 3: 33.4 usec per loop
   $ python -m timeit '"-".join(map(str, range(100)))'
   10000 loops, best of 3: 25.2 usec per loop

This can be achieved from the :ref:`python-interface` with::

   >>> import timeit
   >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
   0.8187260627746582
   >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
   0.7288308143615723
   >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
   0.5858950614929199

Note however that :mod:`timeit` will automatically determine the number of
repetitions only when the command-line interface is used.  In the
:ref:`timeit-examples` section you can find more advanced examples.


.. _python-interface:

Python Interface
----------------

The module defines three convenience functions and a public class:


.. function:: timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)

   Create a :class:`Timer` instance with the given statement, *setup* code and
   *timer* function and run its :meth:`.timeit` method with *number* executions.

   .. versionadded:: 2.6


.. function:: repeat(stmt='pass', setup='pass', timer=<default timer>, repeat=3, number=1000000)

   Create a :class:`Timer` instance with the given statement, *setup* code and
   *timer* function and run its :meth:`.repeat` method with the given *repeat*
   count and *number* executions.

   .. versionadded:: 2.6


.. function:: default_timer()

   Define a default timer, in a platform-specific manner.  On Windows,
   :func:`time.clock` has microsecond granularity, but :func:`time.time`'s
   granularity is 1/60th of a second.  On Unix, :func:`time.clock` has 1/100th of
   a second granularity, and :func:`time.time` is much more precise.  On either
   platform, :func:`default_timer` measures wall clock time, not the CPU
   time.  This means that other processes running on the same computer may
   interfere with the timing.


.. class:: Timer(stmt='pass', setup='pass', timer=<timer function>)

   Class for timing execution speed of small code snippets.

   The constructor takes a statement to be timed, an additional statement used
   for setup, and a timer function.  Both statements default to ``'pass'``;
   the timer function is platform-dependent (see the module doc string).
   *stmt* and *setup* may also contain multiple statements separated by ``;``
   or newlines, as long as they don't contain multi-line string literals.

   To measure the execution time of the first statement, use the :meth:`.timeit`
   method.  The :meth:`.repeat` method is a convenience to call :meth:`.timeit`
   multiple times and return a list of results.

   .. versionchanged:: 2.6
      The *stmt* and *setup* parameters can now also take objects that are
      callable without arguments.  This will embed calls to them in a timer
      function that will then be executed by :meth:`.timeit`.  Note that the
      timing overhead is a little larger in this case because of the extra
      function calls.


   .. method:: Timer.timeit(number=1000000)

      Time *number* executions of the main statement.  This executes the setup
      statement once, and then returns the time it takes to execute the main
      statement a number of times, measured in seconds as a float.
      The argument is the number of times through the loop, defaulting to one
      million.  The main statement, the setup statement and the timer function
      to be used are passed to the constructor.

      .. note::

         By default, :meth:`.timeit` temporarily turns off :term:`garbage
         collection` during the timing.  The advantage of this approach is that
         it makes independent timings more comparable.  This disadvantage is
         that GC may be an important component of the performance of the
         function being measured.  If so, GC can be re-enabled as the first
         statement in the *setup* string.  For example::

            timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit()


   .. method:: Timer.repeat(repeat=3, number=1000000)

      Call :meth:`.timeit` a few times.

      This is a convenience function that calls the :meth:`.timeit` repeatedly,
      returning a list of results.  The first argument specifies how many times
      to call :meth:`.timeit`.  The second argument specifies the *number*
      argument for :meth:`.timeit`.

      .. note::

         It's tempting to calculate mean and standard deviation from the result
         vector and report these.  However, this is not very useful.
         In a typical case, the lowest value gives a lower bound for how fast
         your machine can run the given code snippet; higher values in the
         result vector are typically not caused by variability in Python's
         speed, but by other processes interfering with your timing accuracy.
         So the :func:`min` of the result is probably the only number you
         should be interested in.  After that, you should look at the entire
         vector and apply common sense rather than statistics.


   .. method:: Timer.print_exc(file=None)

      Helper to print a traceback from the timed code.

      Typical use::

         t = Timer(...)       # outside the try/except
         try:
             t.timeit(...)    # or t.repeat(...)
         except:
             t.print_exc()

      The advantage over the standard traceback is that source lines in the
      compiled template will be displayed. The optional *file* argument directs
      where the traceback is sent; it defaults to :data:`sys.stderr`.


.. _timeit-command-line-interface:

Command-Line Interface
----------------------

When called as a program from the command line, the following form is used::

   python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]

Where the following options are understood:

.. program:: timeit

.. cmdoption:: -n N, --number=N

   how many times to execute 'statement'

.. cmdoption:: -r N, --repeat=N

   how many times to repeat the timer (default 3)

.. cmdoption:: -s S, --setup=S

   statement to be executed once initially (default ``pass``)

.. cmdoption:: -t, --time

   use :func:`time.time` (default on all platforms but Windows)

.. cmdoption:: -c, --clock

   use :func:`time.clock` (default on Windows)

.. cmdoption:: -v, --verbose

   print raw timing results; repeat for more digits precision

.. cmdoption:: -h, --help

   print a short usage message and exit

A multi-line statement may be given by specifying each line as a separate
statement argument; indented lines are possible by enclosing an argument in
quotes and using leading spaces.  Multiple :option:`-s` options are treated
similarly.

If :option:`-n` is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.

:func:`default_timer` measurations can be affected by other programs running on
the same machine, so
the best thing to do when accurate timing is necessary is to repeat
the timing a few times and use the best time.  The :option:`-r` option is good
for this; the default of 3 repetitions is probably enough in most cases.  On
Unix, you can use :func:`time.clock` to measure CPU time.

.. note::

   There is a certain baseline overhead associated with executing a pass statement.
   The code here doesn't try to hide it, but you should be aware of it.  The
   baseline overhead can be measured by invoking the program without arguments, and
   it might differ between Python versions.  Also, to fairly compare older Python
   versions to Python 2.3, you may want to use Python's :option:`!-O`
   option (see :ref:`Optimizations <using-on-optimizations>`) for
   the older versions to avoid timing ``SET_LINENO`` instructions.


.. _timeit-examples:

Examples
--------

It is possible to provide a setup statement that is executed only once at the beginning:

.. code-block:: sh

   $ python -m timeit -s 'text = "sample string"; char = "g"'  'char in text'
   10000000 loops, best of 3: 0.0877 usec per loop
   $ python -m timeit -s 'text = "sample string"; char = "g"'  'text.find(char)'
   1000000 loops, best of 3: 0.342 usec per loop

::

   >>> import timeit
   >>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
   0.41440500499993504
   >>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
   1.7246671520006203

The same can be done using the :class:`Timer` class and its methods::

   >>> import timeit
   >>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
   >>> t.timeit()
   0.3955516149999312
   >>> t.repeat()
   [0.40193588800002544, 0.3960157959998014, 0.39594301399984033]


The following examples show how to time expressions that contain multiple lines.
Here we compare the cost of using :func:`hasattr` vs. :keyword:`try`/:keyword:`except`
to test for missing and present object attributes:

.. code-block:: sh

   $ python -m timeit 'try:' '  str.__nonzero__' 'except AttributeError:' '  pass'
   100000 loops, best of 3: 15.7 usec per loop
   $ python -m timeit 'if hasattr(str, "__nonzero__"): pass'
   100000 loops, best of 3: 4.26 usec per loop

   $ python -m timeit 'try:' '  int.__nonzero__' 'except AttributeError:' '  pass'
   1000000 loops, best of 3: 1.43 usec per loop
   $ python -m timeit 'if hasattr(int, "__nonzero__"): pass'
   100000 loops, best of 3: 2.23 usec per loop

::

   >>> import timeit
   >>> # attribute is missing
   >>> s = """\
   ... try:
   ...     str.__nonzero__
   ... except AttributeError:
   ...     pass
   ... """
   >>> timeit.timeit(stmt=s, number=100000)
   0.9138244460009446
   >>> s = "if hasattr(str, '__bool__'): pass"
   >>> timeit.timeit(stmt=s, number=100000)
   0.5829014980008651
   >>>
   >>> # attribute is present
   >>> s = """\
   ... try:
   ...     int.__nonzero__
   ... except AttributeError:
   ...     pass
   ... """
   >>> timeit.timeit(stmt=s, number=100000)
   0.04215312199994514
   >>> s = "if hasattr(int, '__bool__'): pass"
   >>> timeit.timeit(stmt=s, number=100000)
   0.08588060699912603

To give the :mod:`timeit` module access to functions you define, you can pass a
*setup* parameter which contains an import statement::

   def test():
       """Stupid test function"""
       L = []
       for i in range(100):
           L.append(i)

   if __name__ == '__main__':
       import timeit
       print(timeit.timeit("test()", setup="from __main__ import test"))
PK
%�\���X�X!html/_sources/library/tix.rst.txtnu�[���:mod:`Tix` --- Extension widgets for Tk
=======================================

.. module:: Tix
   :synopsis: Tk Extension Widgets for Tkinter
.. sectionauthor:: Mike Clarkson <mikeclarkson@users.sourceforge.net>


.. index:: single: Tix

The :mod:`Tix` (Tk Interface Extension) module provides an additional rich set
of widgets. Although the standard Tk library has many useful widgets, they are
far from complete. The :mod:`Tix` library provides most of the commonly needed
widgets that are missing from standard Tk: :class:`HList`, :class:`ComboBox`,
:class:`Control` (a.k.a. SpinBox) and an assortment of scrollable widgets.
:mod:`Tix` also includes many more widgets that are generally useful in a wide
range of applications: :class:`NoteBook`, :class:`FileEntry`,
:class:`PanedWindow`, etc; there are more than 40 of them.

With all these new widgets, you can introduce new interaction techniques into
applications, creating more useful and more intuitive user interfaces. You can
design your application by choosing the most appropriate widgets to match the
special needs of your application and users.

.. note::

   :mod:`Tix` has been renamed to :mod:`tkinter.tix` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

.. seealso::

   `Tix Homepage <http://tix.sourceforge.net/>`_
      The home page for :mod:`Tix`.  This includes links to additional documentation
      and downloads.

   `Tix Man Pages <http://tix.sourceforge.net/dist/current/man/>`_
      On-line version of the man pages and reference material.

   `Tix Programming Guide <http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html>`_
      On-line version of the programmer's reference material.

   `Tix Development Applications <http://tix.sourceforge.net/Tixapps/src/Tide.html>`_
      Tix applications for development of Tix and Tkinter programs. Tide applications
      work under Tk or Tkinter, and include :program:`TixInspect`, an inspector to
      remotely modify and debug Tix/Tk/Tkinter applications.


Using Tix
---------


.. class:: Tix(screenName[, baseName[, className]])

   Toplevel widget of Tix which represents mostly the main window of an
   application. It has an associated Tcl interpreter.

   Classes in the :mod:`Tix` module subclasses the classes in the :mod:`Tkinter`
   module. The former imports the latter, so to use :mod:`Tix` with Tkinter, all
   you need to do is to import one module. In general, you can just import
   :mod:`Tix`, and replace the toplevel call to :class:`Tkinter.Tk` with
   :class:`Tix.Tk`::

      import Tix
      from Tkconstants import *
      root = Tix.Tk()

To use :mod:`Tix`, you must have the :mod:`Tix` widgets installed, usually
alongside your installation of the Tk widgets. To test your installation, try
the following::

   import Tix
   root = Tix.Tk()
   root.tk.eval('package require Tix')

If this fails, you have a Tk installation problem which must be resolved before
proceeding. Use the environment variable :envvar:`TIX_LIBRARY` to point to the
installed :mod:`Tix` library directory, and make sure you have the dynamic
object library (:file:`tix8183.dll` or :file:`libtix8183.so`) in  the same
directory that contains your Tk dynamic object library (:file:`tk8183.dll` or
:file:`libtk8183.so`). The directory with the dynamic object library should also
have a file called :file:`pkgIndex.tcl` (case sensitive), which contains the
line::

   package ifneeded Tix 8.1 [list load "[file join $dir tix8183.dll]" Tix]


Tix Widgets
-----------

`Tix <http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm>`_
introduces over 40 widget classes to the :mod:`Tkinter`  repertoire.  There is a
demo of all the :mod:`Tix` widgets in the :file:`Demo/tix` directory of the
standard distribution.

.. The Python sample code is still being added to Python, hence commented out


Basic Widgets
^^^^^^^^^^^^^


.. class:: Balloon()

   A `Balloon
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm>`_ that
   pops up over a widget to provide help.  When the user moves the cursor inside a
   widget to which a Balloon widget has been bound, a small pop-up window with a
   descriptive message will be shown on the screen.

.. Python Demo of:
.. \ulink{Balloon}{http://tix.sourceforge.net/dist/current/demos/samples/Balloon.tcl}


.. class:: ButtonBox()

   The `ButtonBox
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm>`_
   widget creates a box of buttons, such as is commonly used for ``Ok Cancel``.

.. Python Demo of:
.. \ulink{ButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/BtnBox.tcl}


.. class:: ComboBox()

   The `ComboBox
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm>`_
   widget is similar to the combo box control in MS Windows. The user can select a
   choice by either typing in the entry subwidget or selecting from the listbox
   subwidget.

.. Python Demo of:
.. \ulink{ComboBox}{http://tix.sourceforge.net/dist/current/demos/samples/ComboBox.tcl}


.. class:: Control()

   The `Control
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm>`_
   widget is also known as the :class:`SpinBox` widget. The user can adjust the
   value by pressing the two arrow buttons or by entering the value directly into
   the entry. The new value will be checked against the user-defined upper and
   lower limits.

.. Python Demo of:
.. \ulink{Control}{http://tix.sourceforge.net/dist/current/demos/samples/Control.tcl}


.. class:: LabelEntry()

   The `LabelEntry
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm>`_
   widget packages an entry widget and a label into one mega widget. It can
   be used to simplify the creation of "entry-form" type of interface.

.. Python Demo of:
.. \ulink{LabelEntry}{http://tix.sourceforge.net/dist/current/demos/samples/LabEntry.tcl}


.. class:: LabelFrame()

   The `LabelFrame
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm>`_
   widget packages a frame widget and a label into one mega widget.  To create
   widgets inside a LabelFrame widget, one creates the new widgets relative to the
   :attr:`frame` subwidget and manage them inside the :attr:`frame` subwidget.

.. Python Demo of:
.. \ulink{LabelFrame}{http://tix.sourceforge.net/dist/current/demos/samples/LabFrame.tcl}


.. class:: Meter()

   The `Meter
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm>`_ widget
   can be used to show the progress of a background job which may take a long time
   to execute.

.. Python Demo of:
.. \ulink{Meter}{http://tix.sourceforge.net/dist/current/demos/samples/Meter.tcl}


.. class:: OptionMenu()

   The `OptionMenu
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm>`_
   creates a menu button of options.

.. Python Demo of:
.. \ulink{OptionMenu}{http://tix.sourceforge.net/dist/current/demos/samples/OptMenu.tcl}


.. class:: PopupMenu()

   The `PopupMenu
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm>`_
   widget can be used as a replacement of the ``tk_popup`` command. The advantage
   of the :mod:`Tix` :class:`PopupMenu` widget is it requires less application code
   to manipulate.

.. Python Demo of:
.. \ulink{PopupMenu}{http://tix.sourceforge.net/dist/current/demos/samples/PopMenu.tcl}


.. class:: Select()

   The `Select
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm>`_ widget
   is a container of button subwidgets. It can be used to provide radio-box or
   check-box style of selection options for the user.

.. Python Demo of:
.. \ulink{Select}{http://tix.sourceforge.net/dist/current/demos/samples/Select.tcl}


.. class:: StdButtonBox()

   The `StdButtonBox
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm>`_
   widget is a group of standard buttons for Motif-like dialog boxes.

.. Python Demo of:
.. \ulink{StdButtonBox}{http://tix.sourceforge.net/dist/current/demos/samples/StdBBox.tcl}


File Selectors
^^^^^^^^^^^^^^


.. class:: DirList()

   The `DirList
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm>`_
   widget displays a list view of a directory, its previous directories and its
   sub-directories. The user can choose one of the directories displayed in the
   list or change to another directory.

.. Python Demo of:
.. \ulink{DirList}{http://tix.sourceforge.net/dist/current/demos/samples/DirList.tcl}


.. class:: DirTree()

   The `DirTree
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm>`_
   widget displays a tree view of a directory, its previous directories and its
   sub-directories. The user can choose one of the directories displayed in the
   list or change to another directory.

.. Python Demo of:
.. \ulink{DirTree}{http://tix.sourceforge.net/dist/current/demos/samples/DirTree.tcl}


.. class:: DirSelectDialog()

   The `DirSelectDialog
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm>`_
   widget presents the directories in the file system in a dialog window.  The user
   can use this dialog window to navigate through the file system to select the
   desired directory.

.. Python Demo of:
.. \ulink{DirSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/DirDlg.tcl}


.. class:: DirSelectBox()

   The :class:`DirSelectBox` is similar to the standard Motif(TM)
   directory-selection box. It is generally used for the user to choose a
   directory.  DirSelectBox stores the directories mostly recently selected into
   a ComboBox widget so that they can be quickly selected again.


.. class:: ExFileSelectBox()

   The `ExFileSelectBox
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm>`_
   widget is usually embedded in a tixExFileSelectDialog widget. It provides a
   convenient method for the user to select files. The style of the
   :class:`ExFileSelectBox` widget is very similar to the standard file dialog on
   MS Windows 3.1.

.. Python Demo of:
.. \ulink{ExFileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/EFileDlg.tcl}


.. class:: FileSelectBox()

   The `FileSelectBox
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm>`_
   is similar to the standard Motif(TM) file-selection box. It is generally used
   for the user to choose a file. FileSelectBox stores the files mostly recently
   selected into a :class:`ComboBox` widget so that they can be quickly selected
   again.

.. Python Demo of:
.. \ulink{FileSelectDialog}{http://tix.sourceforge.net/dist/current/demos/samples/FileDlg.tcl}


.. class:: FileEntry()

   The `FileEntry
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm>`_
   widget can be used to input a filename. The user can type in the filename
   manually. Alternatively, the user can press the button widget that sits next to
   the entry, which will bring up a file selection dialog.

.. Python Demo of:
.. \ulink{FileEntry}{http://tix.sourceforge.net/dist/current/demos/samples/FileEnt.tcl}


Hierarchical ListBox
^^^^^^^^^^^^^^^^^^^^


.. class:: HList()

   The `HList
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm>`_ widget
   can be used to display any data that have a hierarchical structure, for example,
   file system directory trees. The list entries are indented and connected by
   branch lines according to their places in the hierarchy.

.. Python Demo of:
.. \ulink{HList}{http://tix.sourceforge.net/dist/current/demos/samples/HList1.tcl}


.. class:: CheckList()

   The `CheckList
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm>`_
   widget displays a list of items to be selected by the user. CheckList acts
   similarly to the Tk checkbutton or radiobutton widgets, except it is capable of
   handling many more items than checkbuttons or radiobuttons.

.. Python Demo of:
.. \ulink{ CheckList}{http://tix.sourceforge.net/dist/current/demos/samples/ChkList.tcl}
.. Python Demo of:
.. \ulink{ScrolledHList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList.tcl}
.. Python Demo of:
.. \ulink{ScrolledHList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/SHList2.tcl}


.. class:: Tree()

   The `Tree
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm>`_ widget
   can be used to display hierarchical data in a tree form. The user can adjust the
   view of the tree by opening or closing parts of the tree.

.. Python Demo of:
.. \ulink{Tree}{http://tix.sourceforge.net/dist/current/demos/samples/Tree.tcl}
.. Python Demo of:
.. \ulink{Tree (Dynamic)}{http://tix.sourceforge.net/dist/current/demos/samples/DynTree.tcl}


Tabular ListBox
^^^^^^^^^^^^^^^


.. class:: TList()

   The `TList
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm>`_ widget
   can be used to display data in a tabular format. The list entries of a
   :class:`TList` widget are similar to the entries in the Tk listbox widget.  The
   main differences are (1) the :class:`TList` widget can display the list entries
   in a two dimensional format and (2) you can use graphical images as well as
   multiple colors and fonts for the list entries.

.. Python Demo of:
.. \ulink{ScrolledTList (1)}{http://tix.sourceforge.net/dist/current/demos/samples/STList1.tcl}
.. Python Demo of:
.. \ulink{ScrolledTList (2)}{http://tix.sourceforge.net/dist/current/demos/samples/STList2.tcl}
.. Grid has yet to be added to Python
.. \subsubsection{Grid Widget}
.. Python Demo of:
.. \ulink{Simple Grid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid0.tcl}
.. Python Demo of:
.. \ulink{ScrolledGrid}{http://tix.sourceforge.net/dist/current/demos/samples/SGrid1.tcl}
.. Python Demo of:
.. \ulink{Editable Grid}{http://tix.sourceforge.net/dist/current/demos/samples/EditGrid.tcl}


Manager Widgets
^^^^^^^^^^^^^^^


.. class:: PanedWindow()

   The `PanedWindow
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm>`_
   widget allows the user to interactively manipulate the sizes of several panes.
   The panes can be arranged either vertically or horizontally.  The user changes
   the sizes of the panes by dragging the resize handle between two panes.

.. Python Demo of:
.. \ulink{PanedWindow}{http://tix.sourceforge.net/dist/current/demos/samples/PanedWin.tcl}


.. class:: ListNoteBook()

   The `ListNoteBook
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm>`_
   widget is very similar to the :class:`TixNoteBook` widget: it can be used to
   display many windows in a limited space using a notebook metaphor. The notebook
   is divided into a stack of pages (windows). At one time only one of these pages
   can be shown. The user can navigate through these pages by choosing the name of
   the desired page in the :attr:`hlist` subwidget.

.. Python Demo of:
.. \ulink{ListNoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/ListNBK.tcl}


.. class:: NoteBook()

   The `NoteBook
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm>`_
   widget can be used to display many windows in a limited space using a notebook
   metaphor. The notebook is divided into a stack of pages. At one time only one of
   these pages can be shown. The user can navigate through these pages by choosing
   the visual "tabs" at the top of the NoteBook widget.

.. Python Demo of:
.. \ulink{NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/NoteBook.tcl}

.. \subsubsection{Scrolled Widgets}
.. Python Demo of:
.. \ulink{ScrolledListBox}{http://tix.sourceforge.net/dist/current/demos/samples/SListBox.tcl}
.. Python Demo of:
.. \ulink{ScrolledText}{http://tix.sourceforge.net/dist/current/demos/samples/SText.tcl}
.. Python Demo of:
.. \ulink{ScrolledWindow}{http://tix.sourceforge.net/dist/current/demos/samples/SWindow.tcl}
.. Python Demo of:
.. \ulink{Canvas Object View}{http://tix.sourceforge.net/dist/current/demos/samples/CObjView.tcl}


Image Types
^^^^^^^^^^^

The :mod:`Tix` module adds:

* `pixmap <http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm>`_
  capabilities to all :mod:`Tix` and :mod:`Tkinter` widgets to create color images
  from XPM files.

  .. Python Demo of:
  .. \ulink{XPM Image In Button}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm.tcl}
  .. Python Demo of:
  .. \ulink{XPM Image In Menu}{http://tix.sourceforge.net/dist/current/demos/samples/Xpm1.tcl}

* `Compound
  <http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm>`_ image
  types can be used to create images that consists of multiple horizontal lines;
  each line is composed of a series of items (texts, bitmaps, images or spaces)
  arranged from left to right. For example, a compound image can be used to
  display a bitmap and a text string simultaneously in a Tk :class:`Button`
  widget.

  .. Python Demo of:
  .. \ulink{Compound Image In Buttons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg.tcl}
  .. Python Demo of:
  .. \ulink{Compound Image In NoteBook}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg2.tcl}
  .. Python Demo of:
  .. \ulink{Compound Image Notebook Color Tabs}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg4.tcl}
  .. Python Demo of:
  .. \ulink{Compound Image Icons}{http://tix.sourceforge.net/dist/current/demos/samples/CmpImg3.tcl}


Miscellaneous Widgets
^^^^^^^^^^^^^^^^^^^^^


.. class:: InputOnly()

   The `InputOnly
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm>`_
   widgets are to accept inputs from the user, which can be done with the ``bind``
   command (Unix only).


Form Geometry Manager
^^^^^^^^^^^^^^^^^^^^^

In addition, :mod:`Tix` augments :mod:`Tkinter` by providing:


.. class:: Form()

   The `Form
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm>`_ geometry
   manager based on attachment rules for all Tk widgets.



Tix Commands
------------


.. class:: tixCommand()

   The `tix commands
   <http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm>`_ provide
   access to miscellaneous elements of :mod:`Tix`'s internal state and the
   :mod:`Tix` application context.  Most of the information manipulated by these
   methods pertains to the application as a whole, or to a screen or display,
   rather than to a particular window.

   To view the current settings, the common usage is::

      import Tix
      root = Tix.Tk()
      print root.tix_configure()


.. method:: tixCommand.tix_configure(cnf=None **kw)

   Query or modify the configuration options of the Tix application context. If no
   option is specified, returns a dictionary all of the available options.  If
   option is specified with no value, then the method returns a list describing the
   one named option (this list will be identical to the corresponding sublist of
   the value returned if no option is specified).  If one or more option-value
   pairs are specified, then the method modifies the given option(s) to have the
   given value(s); in this case the method returns an empty string. Option may be
   any of the configuration options.


.. method:: tixCommand.tix_cget(option)

   Returns the current value of the configuration option given by *option*. Option
   may be any of the configuration options.


.. method:: tixCommand.tix_getbitmap(name)

   Locates a bitmap file of the name ``name.xpm`` or ``name`` in one of the bitmap
   directories (see the :meth:`tix_addbitmapdir` method).  By using
   :meth:`tix_getbitmap`, you can avoid hard coding the pathnames of the bitmap
   files in your application. When successful, it returns the complete pathname of
   the bitmap file, prefixed with the character ``@``.  The returned value can be
   used to configure the ``bitmap`` option of the Tk and Tix widgets.


.. method:: tixCommand.tix_addbitmapdir(directory)

   Tix maintains a list of directories under which the :meth:`tix_getimage` and
   :meth:`tix_getbitmap` methods will search for image files.  The standard bitmap
   directory is :file:`$TIX_LIBRARY/bitmaps`. The :meth:`tix_addbitmapdir` method
   adds *directory* into this list. By using this method, the image files of an
   applications can also be located using the :meth:`tix_getimage` or
   :meth:`tix_getbitmap` method.


.. method:: tixCommand.tix_filedialog([dlgclass])

   Returns the file selection dialog that may be shared among different calls from
   this application.  This method will create a file selection dialog widget when
   it is called the first time. This dialog will be returned by all subsequent
   calls to :meth:`tix_filedialog`.  An optional dlgclass parameter can be passed
   as a string to specified what type of file selection dialog widget is desired.
   Possible options are ``tix``, ``FileSelectDialog`` or ``tixExFileSelectDialog``.


.. method:: tixCommand.tix_getimage(self, name)

   Locates an image file of the name :file:`name.xpm`, :file:`name.xbm` or
   :file:`name.ppm` in one of the bitmap directories (see the
   :meth:`tix_addbitmapdir` method above). If more than one file with the same name
   (but different extensions) exist, then the image type is chosen according to the
   depth of the X display: xbm images are chosen on monochrome displays and color
   images are chosen on color displays. By using :meth:`tix_getimage`, you can
   avoid hard coding the pathnames of the image files in your application. When
   successful, this method returns the name of the newly created image, which can
   be used to configure the ``image`` option of the Tk and Tix widgets.


.. method:: tixCommand.tix_option_get(name)

   Gets the options maintained by the Tix scheme mechanism.


.. method:: tixCommand.tix_resetoptions(newScheme, newFontSet[, newScmPrio])

   Resets the scheme and fontset of the Tix application to *newScheme* and
   *newFontSet*, respectively.  This affects only those widgets created after this
   call.  Therefore, it is best to call the resetoptions method before the creation
   of any widgets in a Tix application.

   The optional parameter *newScmPrio* can be given to reset the priority level of
   the Tk options set by the Tix schemes.

   Because of the way Tk handles the X option database, after Tix has been has
   imported and inited, it is not possible to reset the color schemes and font sets
   using the :meth:`tix_config` method. Instead, the :meth:`tix_resetoptions`
   method must be used.
PK
%�\W��LL html/_sources/library/tk.rst.txtnu�[���.. _tkinter:

*********************************
Graphical User Interfaces with Tk
*********************************

.. index::
   single: GUI
   single: Graphical User Interface
   single: Tkinter
   single: Tk

Tk/Tcl has long been an integral part of Python.  It provides a robust and
platform independent windowing toolkit, that is available to Python programmers
using the :mod:`Tkinter` module, and its extensions, the :mod:`Tix` and
the :mod:`ttk` modules.

The :mod:`Tkinter` module is a thin object-oriented layer on top of Tcl/Tk. To
use :mod:`Tkinter`, you don't need to write Tcl code, but you will need to
consult the Tk documentation, and occasionally the Tcl documentation.
:mod:`Tkinter` is a set of wrappers that implement the Tk widgets as Python
classes.  In addition, the internal module :mod:`_tkinter` provides a threadsafe
mechanism which allows Python and Tcl to interact.

:mod:`Tkinter`'s chief virtues are that it is fast, and that it usually comes
bundled with Python. Although its standard documentation is weak, good
material is available, which includes: references, tutorials, a book and
others. :mod:`Tkinter` is also famous for having an outdated look and feel,
which has been vastly improved in Tk 8.5. Nevertheless, there are many other
GUI libraries that you could be interested in. For more information about
alternatives, see the :ref:`other-gui-packages` section.

.. toctree::

   tkinter.rst
   ttk.rst
   tix.rst
   scrolledtext.rst
   turtle.rst
   idle.rst
   othergui.rst

.. Other sections I have in mind are
   Tkinter internals
   Freezing Tkinter applications


PK
%�\�������%html/_sources/library/tkinter.rst.txtnu�[���:mod:`Tkinter` --- Python interface to Tcl/Tk
=============================================

.. module:: Tkinter
   :synopsis: Interface to Tcl/Tk for graphical user interfaces
.. moduleauthor:: Guido van Rossum <guido@Python.org>


The :mod:`Tkinter` module ("Tk interface") is the standard Python interface to
the Tk GUI toolkit.  Both Tk and :mod:`Tkinter` are available on most Unix
platforms, as well as on Windows systems.  (Tk itself is not part of Python; it
is maintained at ActiveState.)

Running ``python -m Tkinter`` from the command line should open a window
demonstrating a simple Tk interface, letting you know that :mod:`Tkinter` is
properly installed on your system, and also showing what version of Tcl/Tk is
installed, so you can read the Tcl/Tk documentation specific to that version.

.. note::

   :mod:`Tkinter` has been renamed to :mod:`tkinter` in Python 3.  The
   :term:`2to3` tool will automatically adapt imports when converting your
   sources to Python 3.

.. seealso::

   Tkinter documentation:

   `Python Tkinter Resources <https://wiki.python.org/moin/TkInter>`_
      The Python Tkinter Topic Guide provides a great deal of information on using Tk
      from Python and links to other sources of information on Tk.

   `TKDocs <http://www.tkdocs.com/>`_
      Extensive tutorial plus friendlier widget pages for some of the widgets.

   `Tkinter reference: a GUI for Python <https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html>`_
      On-line reference material.

   `Tkinter docs from effbot <http://effbot.org/tkinterbook/>`_
      Online reference for tkinter supported by effbot.org.

   `Programming Python <http://learning-python.com/about-pp4e.html>`_
      Book by Mark Lutz, has excellent coverage of Tkinter.

   `Modern Tkinter for Busy Python Developers <https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/>`_
      Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.

   `Python and Tkinter Programming <https://www.manning.com/books/python-and-tkinter-programming>`_
      Book by John Grayson (ISBN 1-884777-81-3).

   Tcl/Tk documentation:

   `Tk commands <https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm>`_
      Most commands are available as :mod:`Tkinter` or :mod:`Tkinter.ttk` classes.
      Change '8.6' to match the version of your Tcl/Tk installation.

   `Tcl/Tk recent man pages <https://www.tcl.tk/doc/>`_
      Recent Tcl/Tk manuals on www.tcl.tk.

   `ActiveState Tcl Home Page <http://tcl.activestate.com/>`_
      The Tk/Tcl development is largely taking place at ActiveState.

   `Tcl and the Tk Toolkit <https://www.amazon.com/exec/obidos/ASIN/020163337X>`_
      Book by John Ousterhout, the inventor of Tcl.

   `Practical Programming in Tcl and Tk <http://www.beedub.com/book/>`_
      Brent Welch's encyclopedic book.


Tkinter Modules
---------------

Most of the time, the :mod:`Tkinter` module is all you really need, but a number
of additional modules are available as well.  The Tk interface is located in a
binary module named :mod:`_tkinter`. This module contains the low-level
interface to Tk, and should never be used directly by application programmers.
It is usually a shared library (or DLL), but might in some cases be statically
linked with the Python interpreter.

In addition to the Tk interface module, :mod:`Tkinter` includes a number of
Python modules. The two most important modules are the :mod:`Tkinter` module
itself, and a module called :mod:`Tkconstants`. The former automatically imports
the latter, so to use Tkinter, all you need to do is to import one module::

   import Tkinter

Or, more often::

   from Tkinter import *


.. class:: Tk(screenName=None, baseName=None, className='Tk', useTk=1)

   The :class:`Tk` class is instantiated without arguments. This creates a toplevel
   widget of Tk which usually is the main window of an application. Each instance
   has its own associated Tcl interpreter.

   .. FIXME: The following keyword arguments are currently recognized:

   .. versionchanged:: 2.4
      The *useTk* parameter was added.


.. function:: Tcl(screenName=None, baseName=None, className='Tk', useTk=0)

   The :func:`Tcl` function is a factory function which creates an object much like
   that created by the :class:`Tk` class, except that it does not initialize the Tk
   subsystem.  This is most often useful when driving the Tcl interpreter in an
   environment where one doesn't want to create extraneous toplevel windows, or
   where one cannot (such as Unix/Linux systems without an X server).  An object
   created by the :func:`Tcl` object can have a Toplevel window created (and the Tk
   subsystem initialized) by calling its :meth:`loadtk` method.

   .. versionadded:: 2.4

Other modules that provide Tk support include:

:mod:`ScrolledText`
   Text widget with a vertical scroll bar built in.

:mod:`tkColorChooser`
   Dialog to let the user choose a color.

:mod:`tkCommonDialog`
   Base class for the dialogs defined in the other modules listed here.

:mod:`tkFileDialog`
   Common dialogs to allow the user to specify a file to open or save.

:mod:`tkFont`
   Utilities to help work with fonts.

:mod:`tkMessageBox`
   Access to standard Tk dialog boxes.

:mod:`tkSimpleDialog`
   Basic dialogs and convenience functions.

:mod:`Tkdnd`
   Drag-and-drop support for :mod:`Tkinter`. This is experimental and should become
   deprecated when it is replaced  with the Tk DND.

:mod:`turtle`
   Turtle graphics in a Tk window.

These have been renamed as well in Python 3; they were all made submodules of
the new ``tkinter`` package.


Tkinter Life Preserver
----------------------

.. sectionauthor:: Matt Conway


This section is not designed to be an exhaustive tutorial on either Tk or
Tkinter.  Rather, it is intended as a stop gap, providing some introductory
orientation on the system.

Credits:

* Tkinter was written by Steen Lumholt and Guido van Rossum.

* Tk was written by John Ousterhout while at Berkeley.

* This Life Preserver was written by Matt Conway at the University of Virginia.

* The html rendering, and some liberal editing, was produced from a FrameMaker
  version by Ken Manheimer.

* Fredrik Lundh elaborated and revised the class interface descriptions, to get
  them current with Tk 4.2.

* Mike Clarkson converted the documentation to LaTeX, and compiled the  User
  Interface chapter of the reference manual.


How To Use This Section
^^^^^^^^^^^^^^^^^^^^^^^

This section is designed in two parts: the first half (roughly) covers
background material, while the second half can be taken to the keyboard as a
handy reference.

When trying to answer questions of the form "how do I do blah", it is often best
to find out how to do "blah" in straight Tk, and then convert this back into the
corresponding :mod:`Tkinter` call. Python programmers can often guess at the
correct Python command by looking at the Tk documentation. This means that in
order to use Tkinter, you will have to know a little bit about Tk. This document
can't fulfill that role, so the best we can do is point you to the best
documentation that exists. Here are some hints:

* The authors strongly suggest getting a copy of the Tk man pages. Specifically,
  the man pages in the ``mann`` directory are most useful. The ``man3`` man pages
  describe the C interface to the Tk library and thus are not especially helpful
  for script writers.

* Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
  Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
  the novice.  The book is not exhaustive, and for many details it defers to the
  man pages.

* :file:`Tkinter.py` is a last resort for most, but can be a good place to go
  when nothing else makes sense.


A Simple Hello World Program
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

::

   from Tkinter import *

   class Application(Frame):
       def say_hi(self):
           print "hi there, everyone!"

       def createWidgets(self):
           self.QUIT = Button(self)
           self.QUIT["text"] = "QUIT"
           self.QUIT["fg"]   = "red"
           self.QUIT["command"] =  self.quit

           self.QUIT.pack({"side": "left"})

           self.hi_there = Button(self)
           self.hi_there["text"] = "Hello",
           self.hi_there["command"] = self.say_hi

           self.hi_there.pack({"side": "left"})

       def __init__(self, master=None):
           Frame.__init__(self, master)
           self.pack()
           self.createWidgets()

   root = Tk()
   app = Application(master=root)
   app.mainloop()
   root.destroy()


A (Very) Quick Look at Tcl/Tk
-----------------------------

The class hierarchy looks complicated, but in actual practice, application
programmers almost always refer to the classes at the very bottom of the
hierarchy.

Notes:

* These classes are provided for the purposes of organizing certain functions
  under one namespace. They aren't meant to be instantiated independently.

* The :class:`Tk` class is meant to be instantiated only once in an application.
  Application programmers need not instantiate one explicitly, the system creates
  one whenever any of the other classes are instantiated.

* The :class:`Widget` class is not meant to be instantiated, it is meant only
  for subclassing to make "real" widgets (in C++, this is called an 'abstract
  class').

To make use of this reference material, there will be times when you will need
to know how to read short passages of Tk and how to identify the various parts
of a Tk command.   (See section :ref:`tkinter-basic-mapping` for the
:mod:`Tkinter` equivalents of what's below.)

Tk scripts are Tcl programs.  Like all Tcl programs, Tk scripts are just lists
of tokens separated by spaces.  A Tk widget is just its *class*, the *options*
that help configure it, and the *actions* that make it do useful things.

To make a widget in Tk, the command is always of the form::

   classCommand newPathname options

*classCommand*
   denotes which kind of widget to make (a button, a label, a menu...)

*newPathname*
   is the new name for this widget.  All names in Tk must be unique.  To help
   enforce this, widgets in Tk are named with *pathnames*, just like files in a
   file system.  The top level widget, the *root*, is called ``.`` (period) and
   children are delimited by more periods.  For example,
   ``.myApp.controlPanel.okButton`` might be the name of a widget.

*options*
   configure the widget's appearance and in some cases, its behavior.  The options
   come in the form of a list of flags and values. Flags are preceded by a '-',
   like Unix shell command flags, and values are put in quotes if they are more
   than one word.

For example::

   button   .fred   -fg red -text "hi there"
      ^       ^     \_____________________/
      |       |                |
    class    new            options
   command  widget  (-opt val -opt val ...)

Once created, the pathname to the widget becomes a new command.  This new
*widget command* is the programmer's handle for getting the new widget to
perform some *action*.  In C, you'd express this as someAction(fred,
someOptions), in C++, you would express this as fred.someAction(someOptions),
and in Tk, you say::

   .fred someAction someOptions

Note that the object name, ``.fred``, starts with a dot.

As you'd expect, the legal values for *someAction* will depend on the widget's
class: ``.fred disable`` works if fred is a button (fred gets greyed out), but
does not work if fred is a label (disabling of labels is not supported in Tk).

The legal values of *someOptions* is action dependent.  Some actions, like
``disable``, require no arguments, others, like a text-entry box's ``delete``
command, would need arguments to specify what range of text to delete.


.. _tkinter-basic-mapping:

Mapping Basic Tk into Tkinter
-----------------------------

Class commands in Tk correspond to class constructors in Tkinter. ::

   button .fred                =====>  fred = Button()

The master of an object is implicit in the new name given to it at creation
time.  In Tkinter, masters are specified explicitly. ::

   button .panel.fred          =====>  fred = Button(panel)

The configuration options in Tk are given in lists of hyphened tags followed by
values.  In Tkinter, options are specified as keyword-arguments in the instance
constructor, and keyword-args for configure calls or as instance indices, in
dictionary style, for established instances.  See section
:ref:`tkinter-setting-options` on setting options. ::

   button .fred -fg red        =====>  fred = Button(panel, fg = "red")
   .fred configure -fg red     =====>  fred["fg"] = red
                               OR ==>  fred.config(fg = "red")

In Tk, to perform an action on a widget, use the widget name as a command, and
follow it with an action name, possibly with arguments (options).  In Tkinter,
you call methods on the class instance to invoke actions on the widget.  The
actions (methods) that a given widget can perform are listed in the Tkinter.py
module. ::

   .fred invoke                =====>  fred.invoke()

To give a widget to the packer (geometry manager), you call pack with optional
arguments.  In Tkinter, the Pack class holds all this functionality, and the
various forms of the pack command are implemented as methods.  All widgets in
:mod:`Tkinter` are subclassed from the Packer, and so inherit all the packing
methods. See the :mod:`Tix` module documentation for additional information on
the Form geometry manager. ::

   pack .fred -side left       =====>  fred.pack(side = "left")


How Tk and Tkinter are Related
------------------------------

From the top down:

Your App Here (Python)
   A Python application makes a :mod:`Tkinter` call.

Tkinter (Python Module)
   This call (say, for example, creating a button widget), is implemented in the
   *Tkinter* module, which is written in Python.  This Python function will parse
   the commands and the arguments and convert them into a form that makes them look
   as if they had come from a Tk script instead of a Python script.

tkinter (C)
   These commands and their arguments will be passed to a C function in the
   *tkinter* - note the lowercase - extension module.

Tk Widgets (C and Tcl)
   This C function is able to make calls into other C modules, including the C
   functions that make up the Tk library.  Tk is implemented in C and some Tcl.
   The Tcl part of the Tk widgets is used to bind certain default behaviors to
   widgets, and is executed once at the point where the Python :mod:`Tkinter`
   module is imported. (The user never sees this stage).

Tk (C)
   The Tk part of the Tk Widgets implement the final mapping to ...

Xlib (C)
   the Xlib library to draw graphics on the screen.


Handy Reference
---------------


.. _tkinter-setting-options:

Setting Options
^^^^^^^^^^^^^^^

Options control things like the color and border width of a widget. Options can
be set in three ways:

At object creation time, using keyword arguments
   ::

      fred = Button(self, fg = "red", bg = "blue")

After object creation, treating the option name like a dictionary index
   ::

      fred["fg"] = "red"
      fred["bg"] = "blue"

Use the config() method to update multiple attrs subsequent to object creation
   ::

      fred.config(fg = "red", bg = "blue")

For a complete explanation of a given option and its behavior, see the Tk man
pages for the widget in question.

Note that the man pages list "STANDARD OPTIONS" and "WIDGET SPECIFIC OPTIONS"
for each widget.  The former is a list of options that are common to many
widgets, the latter are the options that are idiosyncratic to that particular
widget.  The Standard Options are documented on the :manpage:`options(3)` man
page.

No distinction between standard and widget-specific options is made in this
document.  Some options don't apply to some kinds of widgets. Whether a given
widget responds to a particular option depends on the class of the widget;
buttons have a ``command`` option, labels do not.

The options supported by a given widget are listed in that widget's man page, or
can be queried at runtime by calling the :meth:`config` method without
arguments, or by calling the :meth:`keys` method on that widget.  The return
value of these calls is a dictionary whose key is the name of the option as a
string (for example, ``'relief'``) and whose values are 5-tuples.

Some options, like ``bg`` are synonyms for common options with long names
(``bg`` is shorthand for "background"). Passing the ``config()`` method the name
of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
back will contain the name of the synonym and the "real" option (such as
``('bg', 'background')``).

+-------+---------------------------------+--------------+
| Index | Meaning                         | Example      |
+=======+=================================+==============+
| 0     | option name                     | ``'relief'`` |
+-------+---------------------------------+--------------+
| 1     | option name for database lookup | ``'relief'`` |
+-------+---------------------------------+--------------+
| 2     | option class for database       | ``'Relief'`` |
|       | lookup                          |              |
+-------+---------------------------------+--------------+
| 3     | default value                   | ``'raised'`` |
+-------+---------------------------------+--------------+
| 4     | current value                   | ``'groove'`` |
+-------+---------------------------------+--------------+

Example::

   >>> print fred.config()
   {'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

Of course, the dictionary printed will include all the options available and
their values.  This is meant only as an example.


The Packer
^^^^^^^^^^

.. index:: single: packing (widgets)

The packer is one of Tk's geometry-management mechanisms.    Geometry managers
are used to specify the relative positioning of the positioning of widgets
within their container - their mutual *master*.  In contrast to the more
cumbersome *placer* (which is used less commonly, and we do not cover here), the
packer takes qualitative relationship specification - *above*, *to the left of*,
*filling*, etc - and works everything out to determine the exact placement
coordinates for you.

The size of any *master* widget is determined by the size of the "slave widgets"
inside.  The packer is used to control where slave widgets appear inside the
master into which they are packed.  You can pack widgets into frames, and frames
into other frames, in order to achieve the kind of layout you desire.
Additionally, the arrangement is dynamically adjusted to accommodate incremental
changes to the configuration, once it is packed.

Note that widgets do not appear until they have had their geometry specified
with a geometry manager.  It's a common early mistake to leave out the geometry
specification, and then be surprised when the widget is created but nothing
appears.  A widget will appear only after it has had, for example, the packer's
:meth:`pack` method applied to it.

The pack() method can be called with keyword-option/value pairs that control
where the widget is to appear within its container, and how it is to behave when
the main application window is resized.  Here are some examples::

   fred.pack()                     # defaults to side = "top"
   fred.pack(side = "left")
   fred.pack(expand = 1)


Packer Options
^^^^^^^^^^^^^^

For more extensive information on the packer and the options that it can take,
see the man pages and page 183 of John Ousterhout's book.

anchor
   Anchor type.  Denotes where the packer is to place each slave in its parcel.

expand
   Boolean, ``0`` or ``1``.

fill
   Legal values: ``'x'``, ``'y'``, ``'both'``, ``'none'``.

ipadx and ipady
   A distance - designating internal padding on each side of the slave widget.

padx and pady
   A distance - designating external padding on each side of the slave widget.

side
   Legal values are: ``'left'``, ``'right'``, ``'top'``, ``'bottom'``.


Coupling Widget Variables
^^^^^^^^^^^^^^^^^^^^^^^^^

The current-value setting of some widgets (like text entry widgets) can be
connected directly to application variables by using special options.  These
options are ``variable``, ``textvariable``, ``onvalue``, ``offvalue``, and
``value``.  This connection works both ways: if the variable changes for any
reason, the widget it's connected to will be updated to reflect the new value.

Unfortunately, in the current implementation of :mod:`Tkinter` it is not
possible to hand over an arbitrary Python variable to a widget through a
``variable`` or ``textvariable`` option.  The only kinds of variables for which
this works are variables that are subclassed from a class called Variable,
defined in the :mod:`Tkinter` module.

There are many useful subclasses of Variable already defined:
:class:`StringVar`, :class:`IntVar`, :class:`DoubleVar`, and
:class:`BooleanVar`.  To read the current value of such a variable, call the
:meth:`get` method on it, and to change its value you call the :meth:`!set`
method.  If you follow this protocol, the widget will always track the value of
the variable, with no further intervention on your part.

For example::

   class App(Frame):
       def __init__(self, master=None):
           Frame.__init__(self, master)
           self.pack()

           self.entrythingy = Entry()
           self.entrythingy.pack()

           # here is the application variable
           self.contents = StringVar()
           # set it to some value
           self.contents.set("this is a variable")
           # tell the entry widget to watch this variable
           self.entrythingy["textvariable"] = self.contents

           # and here we get a callback when the user hits return.
           # we will have the program print out the value of the
           # application variable when the user hits return
           self.entrythingy.bind('<Key-Return>',
                                 self.print_contents)

       def print_contents(self, event):
           print "hi. contents of entry is now ---->", \
                 self.contents.get()


The Window Manager
^^^^^^^^^^^^^^^^^^

.. index:: single: window manager (widgets)

In Tk, there is a utility command, ``wm``, for interacting with the window
manager.  Options to the ``wm`` command allow you to control things like titles,
placement, icon bitmaps, and the like.  In :mod:`Tkinter`, these commands have
been implemented as methods on the :class:`Wm` class.  Toplevel widgets are
subclassed from the :class:`Wm` class, and so can call the :class:`Wm` methods
directly.

To get at the toplevel window that contains a given widget, you can often just
refer to the widget's master.  Of course if the widget has been packed inside of
a frame, the master won't represent a toplevel window.  To get at the toplevel
window that contains an arbitrary widget, you can call the :meth:`_root` method.
This method begins with an underscore to denote the fact that this function is
part of the implementation, and not an interface to Tk functionality.

Here are some examples of typical usage::

   from Tkinter import *
   class App(Frame):
       def __init__(self, master=None):
           Frame.__init__(self, master)
           self.pack()


   # create the application
   myapp = App()

   #
   # here are method calls to the window manager class
   #
   myapp.master.title("My Do-Nothing Application")
   myapp.master.maxsize(1000, 400)

   # start the program
   myapp.mainloop()


Tk Option Data Types
^^^^^^^^^^^^^^^^^^^^

.. index:: single: Tk Option Data Types

anchor
   Legal values are points of the compass: ``"n"``, ``"ne"``, ``"e"``, ``"se"``,
   ``"s"``, ``"sw"``, ``"w"``, ``"nw"``, and also ``"center"``.

bitmap
   There are eight built-in, named bitmaps: ``'error'``, ``'gray25'``,
   ``'gray50'``, ``'hourglass'``, ``'info'``, ``'questhead'``, ``'question'``,
   ``'warning'``.  To specify an X bitmap filename, give the full path to the file,
   preceded with an ``@``, as in ``"@/usr/contrib/bitmap/gumby.bit"``.

boolean
   You can pass integers 0 or 1 or the strings ``"yes"`` or ``"no"``.

callback
   This is any Python function that takes no arguments.  For example::

      def print_it():
              print "hi there"
      fred["command"] = print_it

color
   Colors can be given as the names of X colors in the rgb.txt file, or as strings
   representing RGB values in 4 bit: ``"#RGB"``, 8 bit: ``"#RRGGBB"``, 12 bit"
   ``"#RRRGGGBBB"``, or 16 bit ``"#RRRRGGGGBBBB"`` ranges, where R,G,B here
   represent any legal hex digit.  See page 160 of Ousterhout's book for details.

cursor
   The standard X cursor names from :file:`cursorfont.h` can be used, without the
   ``XC_`` prefix.  For example to get a hand cursor (:const:`XC_hand2`), use the
   string ``"hand2"``.  You can also specify a bitmap and mask file of your own.
   See page 179 of Ousterhout's book.

distance
   Screen distances can be specified in either pixels or absolute distances.
   Pixels are given as numbers and absolute distances as strings, with the trailing
   character denoting units: ``c`` for centimetres, ``i`` for inches, ``m`` for
   millimetres, ``p`` for printer's points.  For example, 3.5 inches is expressed
   as ``"3.5i"``.

font
   Tk uses a list font name format, such as ``{courier 10 bold}``. Font sizes with
   positive numbers are measured in points; sizes with negative numbers are
   measured in pixels.

geometry
   This is a string of the form ``widthxheight``, where width and height are
   measured in pixels for most widgets (in characters for widgets displaying text).
   For example: ``fred["geometry"] = "200x100"``.

justify
   Legal values are the strings: ``"left"``, ``"center"``, ``"right"``, and
   ``"fill"``.

region
   This is a string with four space-delimited elements, each of which is a legal
   distance (see above).  For example: ``"2 3 4 5"`` and ``"3i 2i 4.5i 2i"`` and
   ``"3c 2c 4c 10.43c"``  are all legal regions.

relief
   Determines what the border style of a widget will be.  Legal values are:
   ``"raised"``, ``"sunken"``, ``"flat"``, ``"groove"``, and ``"ridge"``.

scrollcommand
   This is almost always the :meth:`!set` method of some scrollbar widget, but can
   be any widget method that takes a single argument.   Refer to the file
   :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
   distribution for an example.

wrap:
   Must be one of: ``"none"``, ``"char"``, or ``"word"``.


Bindings and Events
^^^^^^^^^^^^^^^^^^^

.. index::
   single: bind (widgets)
   single: events (widgets)

The bind method from the widget command allows you to watch for certain events
and to have a callback function trigger when that event type occurs.  The form
of the bind method is::

   def bind(self, sequence, func, add=''):

where:

sequence
   is a string that denotes the target kind of event.  (See the bind man page and
   page 201 of John Ousterhout's book for details).

func
   is a Python function, taking one argument, to be invoked when the event occurs.
   An Event instance will be passed as the argument. (Functions deployed this way
   are commonly known as *callbacks*.)

add
   is optional, either ``''`` or ``'+'``.  Passing an empty string denotes that
   this binding is to replace any other bindings that this event is associated
   with.  Passing a ``'+'`` means that this function is to be added to the list
   of functions bound to this event type.

For example::

   def turnRed(self, event):
       event.widget["activeforeground"] = "red"

   self.button.bind("<Enter>", self.turnRed)

Notice how the widget field of the event is being accessed in the
:meth:`turnRed` callback.  This field contains the widget that caught the X
event.  The following table lists the other event fields you can access, and how
they are denoted in Tk, which can be useful when referring to the Tk man pages.
::

   Tk      Tkinter Event Field             Tk      Tkinter Event Field
   --      -------------------             --      -------------------
   %f      focus                           %A      char
   %h      height                          %E      send_event
   %k      keycode                         %K      keysym
   %s      state                           %N      keysym_num
   %t      time                            %T      type
   %w      width                           %W      widget
   %x      x                               %X      x_root
   %y      y                               %Y      y_root


The index Parameter
^^^^^^^^^^^^^^^^^^^

A number of widgets require"index" parameters to be passed.  These are used to
point at a specific place in a Text widget, or to particular characters in an
Entry widget, or to particular menu items in a Menu widget.

Entry widget indexes (index, view index, etc.)
   Entry widgets have options that refer to character positions in the text being
   displayed.  You can use these :mod:`Tkinter` functions to access these special
   points in text widgets:

   AtEnd()
      refers to the last position in the text

   AtInsert()
      refers to the point where the text cursor is

   AtSelFirst()
      indicates the beginning point of the selected text

   AtSelLast()
      denotes the last point of the selected text and finally

   At(x[, y])
      refers to the character at pixel location *x*, *y* (with *y* not used in the
      case of a text entry widget, which contains a single line of text).

Text widget indexes
   The index notation for Text widgets is very rich and is best described in the Tk
   man pages.

Menu indexes (menu.invoke(), menu.entryconfig(), etc.)
   Some options and methods for menus manipulate specific menu entries. Anytime a
   menu index is needed for an option or a parameter, you may pass in:

   * an integer which refers to the numeric position of the entry in the widget,
     counted from the top, starting with 0;

   * the string ``'active'``, which refers to the menu position that is currently
     under the cursor;

   * the string ``"last"`` which refers to the last menu item;

   * An integer preceded by ``@``, as in ``@6``, where the integer is interpreted
     as a y pixel coordinate in the menu's coordinate system;

   * the string ``"none"``, which indicates no menu entry at all, most often used
     with menu.activate() to deactivate all entries, and finally,

   * a text string that is pattern matched against the label of the menu entry, as
     scanned from the top of the menu to the bottom.  Note that this index type is
     considered after all the others, which means that matches for menu items
     labelled ``last``, ``active``, or ``none`` may be interpreted as the above
     literals, instead.


Images
^^^^^^

Images of different formats can be created through the corresponding subclass
of :class:`Tkinter.Image`:

* :class:`BitmapImage` for images in XBM format.

* :class:`PhotoImage` for images in PGM, PPM, GIF and PNG formats. The latter
  is supported starting with Tk 8.6.

Either type of image is created through either the ``file`` or the ``data``
option (other options are available as well).

The image object can then be used wherever an ``image`` option is supported by
some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
reference to the image. When the last Python reference to the image object is
deleted, the image data is deleted as well, and Tk will display an empty box
wherever the image was used.

.. seealso::

    The `Pillow <http://python-pillow.org/>`_ package adds support for
    formats such as BMP, JPEG, TIFF, and WebP, among others.

.. _tkinter-file-handlers:

File Handlers
-------------

Tk allows you to register and unregister a callback function which will be
called from the Tk mainloop when I/O is possible on a file descriptor.
Only one handler may be registered per file descriptor. Example code::

   import Tkinter
   widget = Tkinter.Tk()
   mask = Tkinter.READABLE | Tkinter.WRITABLE
   widget.tk.createfilehandler(file, mask, callback)
   ...
   widget.tk.deletefilehandler(file)

This feature is not available on Windows.

Since you don't know how many bytes are available for reading, you may not
want to use the :class:`~io.BufferedIOBase` or :class:`~io.TextIOBase`
:meth:`~io.BufferedIOBase.read` or :meth:`~io.IOBase.readline` methods,
since these will insist on reading a predefined number of bytes.
For sockets, the :meth:`~socket.socket.recv` or
:meth:`~socket.socket.recvfrom` methods will work fine; for other files,
use raw reads or ``os.read(file.fileno(), maxbytecount)``.


.. method:: Widget.tk.createfilehandler(file, mask, func)

   Registers the file handler callback function *func*. The *file* argument
   may either be an object with a :meth:`~io.IOBase.fileno` method (such as
   a file or socket object), or an integer file descriptor. The *mask*
   argument is an ORed combination of any of the three constants below.
   The callback is called as follows::

      callback(file, mask)


.. method:: Widget.tk.deletefilehandler(file)

   Unregisters a file handler.


.. data:: READABLE
          WRITABLE
          EXCEPTION

   Constants used in the *mask* arguments.

PK
%�\8�1�	�	#html/_sources/library/token.rst.txtnu�[���:mod:`token` --- Constants used with Python parse trees
=======================================================

.. module:: token
   :synopsis: Constants representing terminal nodes of the parse tree.
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/token.py`

--------------

This module provides constants which represent the numeric values of leaf nodes
of the parse tree (terminal tokens).  Refer to the file :file:`Grammar/Grammar`
in the Python distribution for the definitions of the names in the context of
the language grammar.  The specific numeric values which the names map to may
change between Python versions.

The module also provides a mapping from numeric codes to names and some
functions.  The functions mirror definitions in the Python C header files.


.. data:: tok_name

   Dictionary mapping the numeric values of the constants defined in this module
   back to name strings, allowing more human-readable representation of parse trees
   to be generated.


.. function:: ISTERMINAL(x)

   Return true for terminal token values.


.. function:: ISNONTERMINAL(x)

   Return true for non-terminal token values.


.. function:: ISEOF(x)

   Return true if *x* is the marker indicating the end of input.


The token constants are:

.. data:: ENDMARKER
          NAME
          NUMBER
          STRING
          NEWLINE
          INDENT
          DEDENT
          LPAR
          RPAR
          LSQB
          RSQB
          COLON
          COMMA
          SEMI
          PLUS
          MINUS
          STAR
          SLASH
          VBAR
          AMPER
          LESS
          GREATER
          EQUAL
          DOT
          PERCENT
          BACKQUOTE
          LBRACE
          RBRACE
          EQEQUAL
          NOTEQUAL
          LESSEQUAL
          GREATEREQUAL
          TILDE
          CIRCUMFLEX
          LEFTSHIFT
          RIGHTSHIFT
          DOUBLESTAR
          PLUSEQUAL
          MINEQUAL
          STAREQUAL
          SLASHEQUAL
          PERCENTEQUAL
          AMPEREQUAL
          VBAREQUAL
          CIRCUMFLEXEQUAL
          LEFTSHIFTEQUAL
          RIGHTSHIFTEQUAL
          DOUBLESTAREQUAL
          DOUBLESLASH
          DOUBLESLASHEQUAL
          AT
          OP
          ERRORTOKEN
          N_TOKENS
          NT_OFFSET


.. seealso::

   Module :mod:`parser`
      The second example for the :mod:`parser` module shows how to use the
      :mod:`symbol` module.

PK
%�\�=����&html/_sources/library/tokenize.rst.txtnu�[���:mod:`tokenize` --- Tokenizer for Python source
===============================================

.. module:: tokenize
   :synopsis: Lexical scanner for Python source code.
.. moduleauthor:: Ka Ping Yee
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/tokenize.py`

--------------

The :mod:`tokenize` module provides a lexical scanner for Python source code,
implemented in Python.  The scanner in this module returns comments as tokens as
well, making it useful for implementing "pretty-printers," including colorizers
for on-screen displays.

To simplify token stream handling, all :ref:`operators` and :ref:`delimiters`
tokens are returned using the generic :data:`token.OP` token type.  The exact
type can be determined by checking the second field (containing the actual
token string matched) of the tuple returned from
:func:`tokenize.generate_tokens` for the character sequence that identifies a
specific operator token.

The primary entry point is a :term:`generator`:

.. function:: generate_tokens(readline)

   The :func:`generate_tokens` generator requires one argument, *readline*,
   which must be a callable object which provides the same interface as the
   :meth:`~file.readline` method of built-in file objects (see section
   :ref:`bltin-file-objects`).  Each call to the function should return one line
   of input as a string. Alternately, *readline* may be a callable object that
   signals completion by raising :exc:`StopIteration`.

   The generator produces 5-tuples with these members: the token type; the token
   string; a 2-tuple ``(srow, scol)`` of ints specifying the row and column
   where the token begins in the source; a 2-tuple ``(erow, ecol)`` of ints
   specifying the row and column where the token ends in the source; and the
   line on which the token was found.  The line passed (the last tuple item) is
   the *logical* line; continuation lines are included.

   .. versionadded:: 2.2

An older entry point is retained for backward compatibility:


.. function:: tokenize(readline[, tokeneater])

   The :func:`.tokenize` function accepts two parameters: one representing the input
   stream, and one providing an output mechanism for :func:`.tokenize`.

   The first parameter, *readline*, must be a callable object which provides the
   same interface as the :meth:`~file.readline` method of built-in file objects (see
   section :ref:`bltin-file-objects`).  Each call to the function should return one
   line of input as a string. Alternately, *readline* may be a callable object that
   signals completion by raising :exc:`StopIteration`.

   .. versionchanged:: 2.5
      Added :exc:`StopIteration` support.

   The second parameter, *tokeneater*, must also be a callable object.  It is
   called once for each token, with five arguments, corresponding to the tuples
   generated by :func:`generate_tokens`.

All constants from the :mod:`token` module are also exported from
:mod:`tokenize`, as are two additional token type values that might be passed to
the *tokeneater* function by :func:`.tokenize`:


.. data:: COMMENT

   Token value used to indicate a comment.


.. data:: NL

   Token value used to indicate a non-terminating newline.  The NEWLINE token
   indicates the end of a logical line of Python code; NL tokens are generated when
   a logical line of code is continued over multiple physical lines.

Another function is provided to reverse the tokenization process. This is useful
for creating tools that tokenize a script, modify the token stream, and write
back the modified script.


.. function:: untokenize(iterable)

   Converts tokens back into Python source code.  The *iterable* must return
   sequences with at least two elements, the token type and the token string.  Any
   additional sequence elements are ignored.

   The reconstructed script is returned as a single string.  The result is
   guaranteed to tokenize back to match the input so that the conversion is
   lossless and round-trips are assured.  The guarantee applies only to the token
   type and token string as the spacing between tokens (column positions) may
   change.

   .. versionadded:: 2.5

.. exception:: TokenError

   Raised when either a docstring or expression that may be split over several
   lines is not completed anywhere in the file, for example::

      """Beginning of
      docstring

   or::

      [1,
       2,
       3

Note that unclosed single-quoted strings do not cause an error to be
raised. They are tokenized as ``ERRORTOKEN``, followed by the tokenization of
their contents.

Example of a script re-writer that transforms float literals into Decimal
objects::

   def decistmt(s):
       """Substitute Decimals for floats in a string of statements.

       >>> from decimal import Decimal
       >>> s = 'print +21.3e-5*-.1234/81.7'
       >>> decistmt(s)
       "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"

       >>> exec(s)
       -3.21716034272e-007
       >>> exec(decistmt(s))
       -3.217160342717258261933904529E-7

       """
       result = []
       g = generate_tokens(StringIO(s).readline)   # tokenize the string
       for toknum, tokval, _, _, _  in g:
           if toknum == NUMBER and '.' in tokval:  # replace NUMBER tokens
               result.extend([
                   (NAME, 'Decimal'),
                   (OP, '('),
                   (STRING, repr(tokval)),
                   (OP, ')')
               ])
           else:
               result.append((toknum, tokval))
       return untokenize(result)

PK
%�\��DD#html/_sources/library/trace.rst.txtnu�[���:mod:`trace` --- Trace or track Python statement execution
==========================================================

.. module:: trace
   :synopsis: Trace or track Python statement execution.

**Source code:** :source:`Lib/trace.py`

--------------

The :mod:`trace` module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run.  It can be used in another program
or from the command line.

.. _trace-cli:

Command-Line Usage
------------------

The :mod:`trace` module can be invoked from the command line.  It can be as
simple as ::

   python -m trace --count -C . somefile.py ...

The above will execute :file:`somefile.py` and generate annotated listings of
all Python modules imported during the execution into the current directory.

.. program:: trace

.. cmdoption:: --help

   Display usage and exit.

.. cmdoption:: --version

   Display the version of the module and exit.

Main options
^^^^^^^^^^^^

At least one of the following options must be specified when invoking
:mod:`trace`.  The :option:`--listfuncs <-l>` option is mutually exclusive with
the :option:`--trace <-t>` and :option:`--count <-c>` options. When
:option:`--listfuncs <-l>` is provided, neither :option:`--count <-c>` nor
:option:`--trace <-t>` are accepted, and vice versa.

.. program:: trace

.. cmdoption:: -c, --count

   Produce a set of annotated listing files upon program completion that shows
   how many times each statement was executed.  See also
   :option:`--coverdir <-C>`, :option:`--file <-f>` and
   :option:`--no-report <-R>` below.

.. cmdoption:: -t, --trace

   Display lines as they are executed.

.. cmdoption:: -l, --listfuncs

   Display the functions executed by running the program.

.. cmdoption:: -r, --report

   Produce an annotated list from an earlier program run that used the
   :option:`--count <-c>` and :option:`--file <-f>` option.  This does not
   execute any code.

.. cmdoption:: -T, --trackcalls

   Display the calling relationships exposed by running the program.

Modifiers
^^^^^^^^^

.. program:: trace

.. cmdoption:: -f, --file=<file>

   Name of a file to accumulate counts over several tracing runs.  Should be
   used with the :option:`--count <-c>` option.

.. cmdoption:: -C, --coverdir=<dir>

   Directory where the report files go.  The coverage report for
   ``package.module`` is written to file :file:`{dir}/{package}/{module}.cover`.

.. cmdoption:: -m, --missing

   When generating annotated listings, mark lines which were not executed with
   ``>>>>>>``.

.. cmdoption:: -s, --summary

   When using :option:`--count <-c>` or :option:`--report <-r>`, write a brief
   summary to stdout for each file processed.

.. cmdoption:: -R, --no-report

   Do not generate annotated listings.  This is useful if you intend to make
   several runs with :option:`--count <-c>`, and then produce a single set of
   annotated listings at the end.

.. cmdoption:: -g, --timing

   Prefix each line with the time since the program started.  Only used while
   tracing.

Filters
^^^^^^^

These options may be repeated multiple times.

.. program:: trace

.. cmdoption:: --ignore-module=<mod>

   Ignore each of the given module names and its submodules (if it is a
   package).  The argument can be a list of names separated by a comma.

.. cmdoption:: --ignore-dir=<dir>

   Ignore all modules and packages in the named directory and subdirectories.
   The argument can be a list of directories separated by :data:`os.pathsep`.

.. _trace-api:

Programmatic Interface
----------------------

.. class:: Trace([count=1[, trace=1[, countfuncs=0[, countcallers=0[, ignoremods=()[, ignoredirs=()[, infile=None[, outfile=None[, timing=False]]]]]]]]])

   Create an object to trace execution of a single statement or expression.  All
   parameters are optional.  *count* enables counting of line numbers.  *trace*
   enables line execution tracing.  *countfuncs* enables listing of the
   functions called during the run.  *countcallers* enables call relationship
   tracking.  *ignoremods* is a list of modules or packages to ignore.
   *ignoredirs* is a list of directories whose modules or packages should be
   ignored.  *infile* is the name of the file from which to read stored count
   information.  *outfile* is the name of the file in which to write updated
   count information.  *timing* enables a timestamp relative to when tracing was
   started to be displayed.

    .. method:: run(cmd)

       Execute the command and gather statistics from the execution with
       the current tracing parameters.  *cmd* must be a string or code object,
       suitable for passing into :func:`exec`.

    .. method:: runctx(cmd, globals=None, locals=None)

       Execute the command and gather statistics from the execution with the
       current tracing parameters, in the defined global and local
       environments.  If not defined, *globals* and *locals* default to empty
       dictionaries.

    .. method:: runfunc(func, *args, **kwds)

       Call *func* with the given arguments under control of the :class:`Trace`
       object with the current tracing parameters.

    .. method:: results()

       Return a :class:`CoverageResults` object that contains the cumulative
       results of all previous calls to ``run``, ``runctx`` and ``runfunc``
       for the given :class:`Trace` instance.  Does not reset the accumulated
       trace results.

.. class:: CoverageResults

   A container for coverage results, created by :meth:`Trace.results`.  Should
   not be created directly by the user.

    .. method:: update(other)

       Merge in data from another :class:`CoverageResults` object.

    .. method:: write_results([show_missing=True[, summary=False[, coverdir=None]]])

       Write coverage results.  Set *show_missing* to show lines that had no
       hits.  Set *summary* to include in the output the coverage summary per
       module.  *coverdir* specifies the directory into which the coverage
       result files will be output.  If ``None``, the results for each source
       file are placed in its directory.

A simple example demonstrating the use of the programmatic interface::

   import sys
   import trace

   # create a Trace object, telling it what to ignore, and whether to
   # do tracing or line-counting or both.
   tracer = trace.Trace(
       ignoredirs=[sys.prefix, sys.exec_prefix],
       trace=0,
       count=1)

   # run the new command using the given tracer
   tracer.run('main()')

   # make a report, placing output in the current directory
   r = tracer.results()
   r.write_results(show_missing=True, coverdir=".")

PK
%�\�
>��)�)'html/_sources/library/traceback.rst.txtnu�[���:mod:`traceback` --- Print or retrieve a stack traceback
========================================================

.. module:: traceback
   :synopsis: Print or retrieve a stack traceback.


This module provides a standard interface to extract, format and print stack
traces of Python programs.  It exactly mimics the behavior of the Python
interpreter when it prints a stack trace.  This is useful when you want to print
stack traces under program control, such as in a "wrapper" around the
interpreter.

.. index:: object: traceback

The module uses traceback objects --- this is the object type that is stored in
the variables :data:`sys.exc_traceback` (deprecated) and
:data:`sys.last_traceback` and returned as the third item from
:func:`sys.exc_info`.

The module defines the following functions:


.. function:: print_tb(tb[, limit[, file]])

   Print up to *limit* stack trace entries from the traceback object *tb*. If
   *limit* is omitted or ``None``, all entries are printed. If *file* is omitted
   or ``None``, the output goes to ``sys.stderr``; otherwise it should be an
   open file or file-like object to receive the output.


.. function:: print_exception(etype, value, tb[, limit[, file]])

   Print exception information and up to *limit* stack trace entries from the
   traceback *tb* to *file*. This differs from :func:`print_tb` in the following
   ways: (1) if *tb* is not ``None``, it prints a header ``Traceback (most
   recent call last):``; (2) it prints the exception *etype* and *value* after
   the stack trace; (3) if *etype* is :exc:`SyntaxError` and *value* has the
   appropriate format, it prints the line where the syntax error occurred with a
   caret indicating the approximate position of the error.


.. function:: print_exc([limit[, file]])

   This is a shorthand for ``print_exception(sys.exc_type, sys.exc_value,
   sys.exc_traceback, limit, file)``.  (In fact, it uses :func:`sys.exc_info` to
   retrieve the same information in a thread-safe way instead of using the
   deprecated variables.)


.. function:: format_exc([limit])

   This is like ``print_exc(limit)`` but returns a string instead of printing to
   a file.

   .. versionadded:: 2.4


.. function:: print_last([limit[, file]])

   This is a shorthand for ``print_exception(sys.last_type, sys.last_value,
   sys.last_traceback, limit, file)``.  In general it will work only after
   an exception has reached an interactive prompt (see :data:`sys.last_type`).


.. function:: print_stack([f[, limit[, file]]])

   This function prints a stack trace from its invocation point. The optional
   *f* argument can be used to specify an alternate stack frame to start. The
   optional *limit* and *file* arguments have the same meaning as for
   :func:`print_exception`.


.. function:: extract_tb(tb[, limit])

   Return a list of up to *limit* "pre-processed" stack trace entries extracted
   from the traceback object *tb*.  It is useful for alternate formatting of
   stack traces.  If *limit* is omitted or ``None``, all entries are extracted.
   A "pre-processed" stack trace entry is a 4-tuple (*filename*, *line number*,
   function name*, *text*) representing the information that is usually printed
   for a stack trace.  The *text* is a string with leading and trailing
   whitespace stripped; if the source is not available it is ``None``.


.. function:: extract_stack([f[, limit]])

   Extract the raw traceback from the current stack frame.  The return value has
   the same format as for :func:`extract_tb`.  The optional *f* and *limit*
   arguments have the same meaning as for :func:`print_stack`.


.. function:: format_list(extracted_list)

   Given a list of tuples as returned by :func:`extract_tb` or
   :func:`extract_stack`, return a list of strings ready for printing.  Each
   string in the resulting list corresponds to the item with the same index in
   the argument list.  Each string ends in a newline; the strings may contain
   internal newlines as well, for those items whose source text line is not
   ``None``.


.. function:: format_exception_only(etype, value)

   Format the exception part of a traceback.  The arguments are the exception
   type, *etype* and *value* such as given by ``sys.last_type`` and
   ``sys.last_value``.  The return value is a list of strings, each ending in a
   newline.  Normally, the list contains a single string; however, for
   :exc:`SyntaxError` exceptions, it contains several lines that (when printed)
   display detailed information about where the syntax error occurred.  The
   message indicating which exception occurred is the always last string in the
   list.


.. function:: format_exception(etype, value, tb[, limit])

   Format a stack trace and the exception information.  The arguments  have the
   same meaning as the corresponding arguments to :func:`print_exception`.  The
   return value is a list of strings, each ending in a newline and some
   containing internal newlines.  When these lines are concatenated and printed,
   exactly the same text is printed as does :func:`print_exception`.


.. function:: format_tb(tb[, limit])

   A shorthand for ``format_list(extract_tb(tb, limit))``.


.. function:: format_stack([f[, limit]])

   A shorthand for ``format_list(extract_stack(f, limit))``.


.. function:: tb_lineno(tb)

   This function returns the current line number set in the traceback object.
   This function was necessary because in versions of Python prior to 2.3 when
   the :option:`-O` flag was passed to Python the ``tb.tb_lineno`` was not
   updated correctly.  This function has no use in versions past 2.3.


.. _traceback-example:

Traceback Examples
------------------

This simple example implements a basic read-eval-print loop, similar to (but
less useful than) the standard Python interactive interpreter loop.  For a more
complete implementation of the interpreter loop, refer to the :mod:`code`
module. ::

   import sys, traceback

   def run_user_code(envdir):
       source = raw_input(">>> ")
       try:
           exec source in envdir
       except:
           print "Exception in user code:"
           print '-'*60
           traceback.print_exc(file=sys.stdout)
           print '-'*60

   envdir = {}
   while 1:
       run_user_code(envdir)


The following example demonstrates the different ways to print and format the
exception and traceback::

   import sys, traceback

   def lumberjack():
       bright_side_of_death()

   def bright_side_of_death():
       return tuple()[0]

   try:
       lumberjack()
   except IndexError:
       exc_type, exc_value, exc_traceback = sys.exc_info()
       print "*** print_tb:"
       traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
       print "*** print_exception:"
       traceback.print_exception(exc_type, exc_value, exc_traceback,
                                 limit=2, file=sys.stdout)
       print "*** print_exc:"
       traceback.print_exc()
       print "*** format_exc, first and last line:"
       formatted_lines = traceback.format_exc().splitlines()
       print formatted_lines[0]
       print formatted_lines[-1]
       print "*** format_exception:"
       print repr(traceback.format_exception(exc_type, exc_value,
                                             exc_traceback))
       print "*** extract_tb:"
       print repr(traceback.extract_tb(exc_traceback))
       print "*** format_tb:"
       print repr(traceback.format_tb(exc_traceback))
       print "*** tb_lineno:", exc_traceback.tb_lineno


The output for the example would look similar to this::

   *** print_tb:
     File "<doctest...>", line 10, in <module>
       lumberjack()
   *** print_exception:
   Traceback (most recent call last):
     File "<doctest...>", line 10, in <module>
       lumberjack()
     File "<doctest...>", line 4, in lumberjack
       bright_side_of_death()
   IndexError: tuple index out of range
   *** print_exc:
   Traceback (most recent call last):
     File "<doctest...>", line 10, in <module>
       lumberjack()
     File "<doctest...>", line 4, in lumberjack
       bright_side_of_death()
   IndexError: tuple index out of range
   *** format_exc, first and last line:
   Traceback (most recent call last):
   IndexError: tuple index out of range
   *** format_exception:
   ['Traceback (most recent call last):\n',
    '  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
    '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
    '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n',
    'IndexError: tuple index out of range\n']
   *** extract_tb:
   [('<doctest...>', 10, '<module>', 'lumberjack()'),
    ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'),
    ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')]
   *** format_tb:
   ['  File "<doctest...>", line 10, in <module>\n    lumberjack()\n',
    '  File "<doctest...>", line 4, in lumberjack\n    bright_side_of_death()\n',
    '  File "<doctest...>", line 7, in bright_side_of_death\n    return tuple()[0]\n']
   *** tb_lineno: 10


The following example shows the different ways to print and format the stack::

   >>> import traceback
   >>> def another_function():
   ...     lumberstack()
   ...
   >>> def lumberstack():
   ...     traceback.print_stack()
   ...     print repr(traceback.extract_stack())
   ...     print repr(traceback.format_stack())
   ...
   >>> another_function()
     File "<doctest>", line 10, in <module>
       another_function()
     File "<doctest>", line 3, in another_function
       lumberstack()
     File "<doctest>", line 6, in lumberstack
       traceback.print_stack()
   [('<doctest>', 10, '<module>', 'another_function()'),
    ('<doctest>', 3, 'another_function', 'lumberstack()'),
    ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')]
   ['  File "<doctest>", line 10, in <module>\n    another_function()\n',
    '  File "<doctest>", line 3, in another_function\n    lumberstack()\n',
    '  File "<doctest>", line 8, in lumberstack\n    print repr(traceback.format_stack())\n']


This last example demonstrates the final few formatting functions:

.. doctest::
   :options: +NORMALIZE_WHITESPACE

   >>> import traceback
   >>> traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'),
   ...                        ('eggs.py', 42, 'eggs', 'return "bacon"')])
   ['  File "spam.py", line 3, in <module>\n    spam.eggs()\n',
    '  File "eggs.py", line 42, in eggs\n    return "bacon"\n']
   >>> an_error = IndexError('tuple index out of range')
   >>> traceback.format_exception_only(type(an_error), an_error)
   ['IndexError: tuple index out of range\n']
PK
%�\�#
C�C�!html/_sources/library/ttk.rst.txtnu�[���:mod:`ttk` --- Tk themed widgets
================================

.. module:: ttk
   :synopsis: Tk themed widget set
.. sectionauthor:: Guilherme Polo <ggpolo@gmail.com>


.. index:: single: ttk

The :mod:`ttk` module provides access to the Tk themed widget set, which has
been introduced in Tk 8.5. If Python is not compiled against Tk 8.5 code may
still use this module as long as Tile is installed. However, some features
provided by the new Tk, like anti-aliased font rendering under X11, window
transparency (on X11 you will need a composition window manager) will be
missing.

The basic idea of :mod:`ttk` is to separate, to the extent possible, the code
implementing a widget's behavior from the code implementing its appearance.


.. seealso::

   `Tk Widget Styling Support <https://www.tcl.tk/cgi-bin/tct/tip/48>`_
      The document which brought up theming support for Tk


Using Ttk
---------

To start using Ttk, import its module::

   import ttk

But code like this::

   from Tkinter import *

may optionally want to use this::

   from Tkinter import *
   from ttk import *

And then several :mod:`ttk` widgets (:class:`Button`, :class:`Checkbutton`,
:class:`Entry`, :class:`Frame`, :class:`Label`, :class:`LabelFrame`,
:class:`Menubutton`, :class:`PanedWindow`, :class:`Radiobutton`, :class:`Scale`
and :class:`Scrollbar`) will automatically substitute for the Tk widgets.

This has the direct benefit of using the new widgets, giving better look & feel
across platforms, but be aware that they are not totally compatible. The main
difference is that widget options such as "fg", "bg" and others related to
widget styling are no longer present in Ttk widgets. Use :class:`ttk.Style` to
achieve the same (or better) styling.

.. seealso::

   `Converting existing applications to use the Tile widgets <http://tktable.sourceforge.net/tile/doc/converting.txt>`_
     A text which talks in Tcl terms about differences typically found when
     converting applications to use the new widgets.


Ttk Widgets
-----------

Ttk comes with 17 widgets, 11 of which already exist in Tkinter:
:class:`Button`, :class:`Checkbutton`, :class:`Entry`, :class:`Frame`,
:class:`Label`, :class:`LabelFrame`, :class:`Menubutton`,
:class:`PanedWindow`, :class:`Radiobutton`, :class:`Scale` and
:class:`Scrollbar`. The 6 new widget classes are: :class:`Combobox`,
:class:`Notebook`, :class:`Progressbar`, :class:`Separator`,
:class:`Sizegrip` and :class:`Treeview`.  All of these classes are
subclasses of :class:`Widget`.

As said previously, you will notice changes in look-and-feel as well in the
styling code. To demonstrate the latter, a very simple example is shown below.

Tk code::

   l1 = Tkinter.Label(text="Test", fg="black", bg="white")
   l2 = Tkinter.Label(text="Test", fg="black", bg="white")


Corresponding Ttk code::

   style = ttk.Style()
   style.configure("BW.TLabel", foreground="black", background="white")

   l1 = ttk.Label(text="Test", style="BW.TLabel")
   l2 = ttk.Label(text="Test", style="BW.TLabel")

For more information about TtkStyling_ read the :class:`Style` class
documentation.

Widget
------

:class:`ttk.Widget` defines standard options and methods supported by Tk
themed widgets and is not supposed to be directly instantiated.


Standard Options
^^^^^^^^^^^^^^^^

All the :mod:`ttk` widgets accept the following options:

   +-----------+--------------------------------------------------------------+
   | Option    | Description                                                  |
   +===========+==============================================================+
   | class     | Specifies the window class. The class is used when querying  |
   |           | the option database for the window's other options, to       |
   |           | determine the default bindtags for the window, and to select |
   |           | the widget's default layout and style. This is a read-only   |
   |           | option which may only be specified when the window is        |
   |           | created.                                                     |
   +-----------+--------------------------------------------------------------+
   | cursor    | Specifies the mouse cursor to be used for the widget. If set |
   |           | to the empty string (the default), the cursor is inherited   |
   |           | from the parent widget.                                      |
   +-----------+--------------------------------------------------------------+
   | takefocus | Determines whether the window accepts the focus during       |
   |           | keyboard traversal. 0, 1 or an empty string is returned.     |
   |           | If 0, the window should be skipped entirely                  |
   |           | during keyboard traversal. If 1, the window                  |
   |           | should receive the input focus as long as it is viewable.    |
   |           | An empty string means that the traversal scripts make the    |
   |           | decision about whether or not to focus on the window.        |
   +-----------+--------------------------------------------------------------+
   | style     | May be used to specify a custom widget style.                |
   +-----------+--------------------------------------------------------------+


Scrollable Widget Options
^^^^^^^^^^^^^^^^^^^^^^^^^

The following options are supported by widgets that are controlled by a
scrollbar.

   +----------------+---------------------------------------------------------+
   | option         | description                                             |
   +================+=========================================================+
   | xscrollcommand | Used to communicate with horizontal scrollbars.         |
   |                |                                                         |
   |                | When the view in the widget's window changes, the widget|
   |                | will generate a Tcl command based on the scrollcommand. |
   |                |                                                         |
   |                | Usually this option consists of the                     |
   |                | :meth:`Scrollbar.set` method of some scrollbar. This    |
   |                | will cause                                              |
   |                | the scrollbar to be updated whenever the view in the    |
   |                | window changes.                                         |
   +----------------+---------------------------------------------------------+
   | yscrollcommand | Used to communicate with vertical scrollbars.           |
   |                | For more information, see above.                        |
   +----------------+---------------------------------------------------------+


Label Options
^^^^^^^^^^^^^

The following options are supported by labels, buttons and other button-like
widgets.

.. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
..

   +--------------+-----------------------------------------------------------+
   | option       | description                                               |
   +==============+===========================================================+
   | text         | Specifies a text string to be displayed inside the widget.|
   +--------------+-----------------------------------------------------------+
   | textvariable | Specifies a name whose value will be used in place of the |
   |              | text option resource.                                     |
   +--------------+-----------------------------------------------------------+
   | underline    | If set, specifies the index (0-based) of a character to   |
   |              | underline in the text string. The underline character is  |
   |              | used for mnemonic activation.                             |
   +--------------+-----------------------------------------------------------+
   | image        | Specifies an image to display. This is a list of 1 or more|
   |              | elements. The first element is the default image name. The|
   |              | rest of the list is a sequence of statespec/value pairs as|
   |              | defined by :meth:`Style.map`, specifying different images |
   |              | to use when the widget is in a particular state or a      |
   |              | combination of states. All images in the list should have |
   |              | the same size.                                            |
   +--------------+-----------------------------------------------------------+
   | compound     | Specifies how to display the image relative to the text,  |
   |              | in the case both text and image options are present.      |
   |              | Valid values are:                                         |
   |              |                                                           |
   |              | * text: display text only                                 |
   |              | * image: display image only                               |
   |              | * top, bottom, left, right: display image above, below,   |
   |              |   left of, or right of the text, respectively.            |
   |              | * none: the default. display the image if present,        |
   |              |   otherwise the text.                                     |
   +--------------+-----------------------------------------------------------+
   | width        | If greater than zero, specifies how much space, in        |
   |              | character widths, to allocate for the text label; if less |
   |              | than zero, specifies a minimum width. If zero or          |
   |              | unspecified, the natural width of the text label is used. |
   +--------------+-----------------------------------------------------------+


Compatibility Options
^^^^^^^^^^^^^^^^^^^^^

   +--------+----------------------------------------------------------------+
   | option | description                                                    |
   +========+================================================================+
   | state  | May be set to "normal" or "disabled" to control the "disabled" |
   |        | state bit. This is a write-only option: setting it changes the |
   |        | widget state, but the :meth:`Widget.state` method does not     |
   |        | affect this option.                                            |
   +--------+----------------------------------------------------------------+

Widget States
^^^^^^^^^^^^^

The widget state is a bitmap of independent state flags.

   +------------+-------------------------------------------------------------+
   | flag       | description                                                 |
   +============+=============================================================+
   | active     | The mouse cursor is over the widget and pressing a mouse    |
   |            | button will cause some action to occur.                     |
   +------------+-------------------------------------------------------------+
   | disabled   | Widget is disabled under program control.                   |
   +------------+-------------------------------------------------------------+
   | focus      | Widget has keyboard focus.                                  |
   +------------+-------------------------------------------------------------+
   | pressed    | Widget is being pressed.                                    |
   +------------+-------------------------------------------------------------+
   | selected   | "On", "true", or "current" for things like Checkbuttons and |
   |            | radiobuttons.                                               |
   +------------+-------------------------------------------------------------+
   | background | Windows and Mac have a notion of an "active" or foreground  |
   |            | window. The *background* state is set for widgets in a      |
   |            | background window, and cleared for those in the foreground  |
   |            | window.                                                     |
   +------------+-------------------------------------------------------------+
   | readonly   | Widget should not allow user modification.                  |
   +------------+-------------------------------------------------------------+
   | alternate  | A widget-specific alternate display format.                 |
   +------------+-------------------------------------------------------------+
   | invalid    | The widget's value is invalid.                              |
   +------------+-------------------------------------------------------------+

A state specification is a sequence of state names, optionally prefixed with
an exclamation point indicating that the bit is off.


ttk.Widget
^^^^^^^^^^

Besides the methods described below, the :class:`ttk.Widget` class supports the
:meth:`Tkinter.Widget.cget` and :meth:`Tkinter.Widget.configure` methods.

.. class:: Widget

   .. method:: identify(x, y)

      Returns the name of the element at position *x* *y*, or the empty string
      if the point does not lie within any element.

      *x* and *y* are pixel coordinates relative to the widget.


   .. method:: instate(statespec, callback=None, *args, **kw)

      Test the widget's state. If a callback is not specified, returns ``True``
      if the widget state matches *statespec* and ``False`` otherwise. If callback
      is specified then it is called with *args* if widget state matches
      *statespec*.


   .. method:: state([statespec=None])

      Modify or read widget state. If *statespec* is specified, sets the
      widget state accordingly and returns a new *statespec* indicating
      which flags were changed. If *statespec* is not specified, returns
      the currently-enabled state flags.

   *statespec* will usually be a list or a tuple.


Combobox
--------

The :class:`ttk.Combobox` widget combines a text field with a pop-down list of
values. This widget is a subclass of :class:`Entry`.

Besides the methods inherited from :class:`Widget` (:meth:`Widget.cget`,
:meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate`
and :meth:`Widget.state`) and those inherited from :class:`Entry`
(:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`,
:meth:`Entry.index`, :meth:`Entry.insert`, :meth:`Entry.selection`,
:meth:`Entry.xview`), this class has some other methods, described at
:class:`ttk.Combobox`.


Options
^^^^^^^

This widget accepts the following options:

   +-----------------+--------------------------------------------------------+
   | option          | description                                            |
   +=================+========================================================+
   | exportselection | Boolean value. If set, the widget selection is linked  |
   |                 | to the Window Manager selection (which can be returned |
   |                 | by invoking :meth:`Misc.selection_get`, for example).  |
   +-----------------+--------------------------------------------------------+
   | justify         | Specifies how the text is aligned within the widget.   |
   |                 | One of "left", "center", or "right".                   |
   +-----------------+--------------------------------------------------------+
   | height          | Specifies the height of the pop-down listbox, in rows. |
   +-----------------+--------------------------------------------------------+
   | postcommand     | A script (possibly registered with                     |
   |                 | :meth:`Misc.register`) that                            |
   |                 | is called immediately before displaying the values. It |
   |                 | may specify which values to display.                   |
   +-----------------+--------------------------------------------------------+
   | state           | One of "normal", "readonly", or "disabled". In the     |
   |                 | "readonly" state, the value may not be edited directly,|
   |                 | and the user can only select one of the values from the|
   |                 | dropdown list. In the "normal" state, the text field is|
   |                 | directly editable. In the "disabled" state, no         |
   |                 | interaction is possible.                               |
   +-----------------+--------------------------------------------------------+
   | textvariable    | Specifies a name whose value is linked to the widget   |
   |                 | value. Whenever the value associated with that name    |
   |                 | changes, the widget value is updated, and vice versa.  |
   |                 | See :class:`Tkinter.StringVar`.                        |
   +-----------------+--------------------------------------------------------+
   | values          | Specifies the list of values to display in the         |
   |                 | drop-down listbox.                                     |
   +-----------------+--------------------------------------------------------+
   | width           | Specifies an integer value indicating the desired width|
   |                 | of the entry window, in average-size characters of the |
   |                 | widget's font.                                         |
   +-----------------+--------------------------------------------------------+


Virtual events
^^^^^^^^^^^^^^

The combobox widget generates a **<<ComboboxSelected>>** virtual event
when the user selects an element from the list of values.


ttk.Combobox
^^^^^^^^^^^^

.. class:: Combobox

   .. method:: current([newindex=None])

      If *newindex* is specified, sets the combobox value to the element
      position *newindex*. Otherwise, returns the index of the current value or
      -1 if the current value is not in the values list.


   .. method:: get()

      Returns the current value of the combobox.


   .. method:: set(value)

      Sets the value of the combobox to *value*.


Notebook
--------

The Ttk Notebook widget manages a collection of windows and displays a single
one at a time. Each child window is associated with a tab, which the user
may select to change the currently-displayed window.


Options
^^^^^^^

This widget accepts the following specific options:

   +---------+----------------------------------------------------------------+
   | option  | description                                                    |
   +=========+================================================================+
   | height  | If present and greater than zero, specifies the desired height |
   |         | of the pane area (not including internal padding or tabs).     |
   |         | Otherwise, the maximum height of all panes is used.            |
   +---------+----------------------------------------------------------------+
   | padding | Specifies the amount of extra space to add around the outside  |
   |         | of the notebook. The padding is a list of up to four length    |
   |         | specifications: left top right bottom. If fewer than four      |
   |         | elements are specified, bottom defaults to top, right defaults |
   |         | to left, and top defaults to left.                             |
   +---------+----------------------------------------------------------------+
   | width   | If present and greater than zero, specifies the desired width  |
   |         | of the pane area (not including internal padding). Otherwise,  |
   |         | the maximum width of all panes is used.                        |
   +---------+----------------------------------------------------------------+


Tab Options
^^^^^^^^^^^

There are also specific options for tabs:

   +-----------+--------------------------------------------------------------+
   | option    | description                                                  |
   +===========+==============================================================+
   | state     | Either "normal", "disabled" or "hidden". If "disabled", then |
   |           | the tab is not selectable. If "hidden", then the tab is not  |
   |           | shown.                                                       |
   +-----------+--------------------------------------------------------------+
   | sticky    | Specifies how the child window is positioned within the pane |
   |           | area. Value is a string containing zero or more of the       |
   |           | characters "n", "s", "e" or "w". Each letter refers to a     |
   |           | side (north, south, east or west) that the child window will |
   |           | stick to, as per the :meth:`grid` geometry manager.          |
   +-----------+--------------------------------------------------------------+
   | padding   | Specifies the amount of extra space to add between the       |
   |           | notebook and this pane. Syntax is the same as for the option |
   |           | padding used by this widget.                                 |
   +-----------+--------------------------------------------------------------+
   | text      | Specifies a text to be displayed in the tab.                 |
   +-----------+--------------------------------------------------------------+
   | image     | Specifies an image to display in the tab. See the option     |
   |           | image described in :class:`Widget`.                          |
   +-----------+--------------------------------------------------------------+
   | compound  | Specifies how to display the image relative to the text, in  |
   |           | the case both text and image options are present. See        |
   |           | `Label Options`_ for legal values.                           |
   +-----------+--------------------------------------------------------------+
   | underline | Specifies the index (0-based) of a character to underline in |
   |           | the text string. The underlined character is used for        |
   |           | mnemonic activation if :meth:`Notebook.enable_traversal` is  |
   |           | called.                                                      |
   +-----------+--------------------------------------------------------------+


Tab Identifiers
^^^^^^^^^^^^^^^

The *tab_id* present in several methods of :class:`ttk.Notebook` may take any
of the following forms:

* An integer between zero and the number of tabs.
* The name of a child window.
* A positional specification of the form "@x,y", which identifies the tab.
* The literal string "current", which identifies the currently-selected tab.
* The literal string "end", which returns the number of tabs (only valid for
  :meth:`Notebook.index`).


Virtual Events
^^^^^^^^^^^^^^

This widget generates a **<<NotebookTabChanged>>** virtual event after a new
tab is selected.


ttk.Notebook
^^^^^^^^^^^^

.. class:: Notebook

   .. method:: add(child, **kw)

      Adds a new tab to the notebook.

      If window is currently managed by the notebook but hidden, it is
      restored to its previous position.

      See `Tab Options`_ for the list of available options.


   .. method:: forget(tab_id)

      Removes the tab specified by *tab_id*, unmaps and unmanages the
      associated window.


   .. method:: hide(tab_id)

      Hides the tab specified by *tab_id*.

      The tab will not be displayed, but the associated window remains
      managed by the notebook and its configuration remembered. Hidden tabs
      may be restored with the :meth:`add` command.


   .. method:: identify(x, y)

      Returns the name of the tab element at position *x*, *y*, or the empty
      string if none.


   .. method:: index(tab_id)

      Returns the numeric index of the tab specified by *tab_id*, or the total
      number of tabs if *tab_id* is the string "end".


   .. method:: insert(pos, child, **kw)

      Inserts a pane at the specified position.

      *pos* is either the string "end", an integer index, or the name of a
      managed child. If *child* is already managed by the notebook, moves it to
      the specified position.

      See `Tab Options`_ for the list of available options.


   .. method:: select([tab_id])

      Selects the specified *tab_id*.

      The associated child window will be displayed, and the
      previously-selected window (if different) is unmapped. If *tab_id* is
      omitted, returns the widget name of the currently selected pane.


   .. method:: tab(tab_id, option=None, **kw)

      Query or modify the options of the specific *tab_id*.

      If *kw* is not given, returns a dictionary of the tab option values. If
      *option* is specified, returns the value of that *option*. Otherwise,
      sets the options to the corresponding values.


   .. method:: tabs()

      Returns a list of windows managed by the notebook.


   .. method:: enable_traversal()

      Enable keyboard traversal for a toplevel window containing this notebook.

      This will extend the bindings for the toplevel window containing the
      notebook as follows:

      * :kbd:`Control-Tab`: selects the tab following the currently selected one.
      * :kbd:`Shift-Control-Tab`: selects the tab preceding the currently selected one.
      * :kbd:`Alt-K`: where *K* is the mnemonic (underlined) character of any tab, will
        select that tab.

      Multiple notebooks in a single toplevel may be enabled for traversal,
      including nested notebooks. However, notebook traversal only works
      properly if all panes have the notebook they are in as master.


Progressbar
-----------

The :class:`ttk.Progressbar` widget shows the status of a long-running
operation. It can operate in two modes: determinate mode shows the amount
completed relative to the total amount of work to be done, and indeterminate
mode provides an animated display to let the user know that something is
happening.


Options
^^^^^^^

This widget accepts the following specific options:

   +----------+---------------------------------------------------------------+
   | option   | description                                                   |
   +==========+===============================================================+
   | orient   | One of "horizontal" or "vertical". Specifies the orientation  |
   |          | of the progress bar.                                          |
   +----------+---------------------------------------------------------------+
   | length   | Specifies the length of the long axis of the progress bar     |
   |          | (width if horizontal, height if vertical).                    |
   +----------+---------------------------------------------------------------+
   | mode     | One of "determinate" or "indeterminate".                      |
   +----------+---------------------------------------------------------------+
   | maximum  | A number specifying the maximum value. Defaults to 100.       |
   +----------+---------------------------------------------------------------+
   | value    | The current value of the progress bar. In "determinate" mode, |
   |          | this represents the amount of work completed. In              |
   |          | "indeterminate" mode, it is interpreted as modulo *maximum*;  |
   |          | that is, the progress bar completes one "cycle" when its value|
   |          | increases by *maximum*.                                       |
   +----------+---------------------------------------------------------------+
   | variable | A name which is linked to the option value. If specified, the |
   |          | value of the progress bar is automatically set to the value of|
   |          | this name whenever the latter is modified.                    |
   +----------+---------------------------------------------------------------+
   | phase    | Read-only option. The widget periodically increments the value|
   |          | of this option whenever its value is greater than 0 and, in   |
   |          | determinate mode, less than maximum. This option may be used  |
   |          | by the current theme to provide additional animation effects. |
   +----------+---------------------------------------------------------------+


ttk.Progressbar
^^^^^^^^^^^^^^^

.. class:: Progressbar

   .. method:: start([interval])

      Begin autoincrement mode: schedules a recurring timer event that calls
      :meth:`Progressbar.step` every *interval* milliseconds. If omitted,
      *interval* defaults to 50 milliseconds.


   .. method:: step([amount])

      Increments the progress bar's value by *amount*.

      *amount* defaults to 1.0 if omitted.


   .. method:: stop()

      Stop autoincrement mode: cancels any recurring timer event initiated by
      :meth:`Progressbar.start` for this progress bar.


Separator
---------

The :class:`ttk.Separator` widget displays a horizontal or vertical separator
bar.

It has no other methods besides the ones inherited from :class:`ttk.Widget`.


Options
^^^^^^^

This widget accepts the following specific option:

   +--------+----------------------------------------------------------------+
   | option | description                                                    |
   +========+================================================================+
   | orient | One of "horizontal" or "vertical". Specifies the orientation of|
   |        | the separator.                                                 |
   +--------+----------------------------------------------------------------+


Sizegrip
--------

The :class:`ttk.Sizegrip` widget (also known as a grow box) allows the user to
resize the containing toplevel window by pressing and dragging the grip.

This widget has neither specific options nor specific methods, besides the
ones inherited from :class:`ttk.Widget`.


Platform-specific notes
^^^^^^^^^^^^^^^^^^^^^^^

* On Mac OS X, toplevel windows automatically include a built-in size grip
  by default. Adding a :class:`Sizegrip` is harmless, since the built-in
  grip will just mask the widget.


Bugs
^^^^

* If the containing toplevel's position was specified relative to the right
  or bottom of the screen (e.g. ....), the :class:`Sizegrip` widget will
  not resize the window.
* This widget supports only "southeast" resizing.


Treeview
--------

The :class:`ttk.Treeview` widget displays a hierarchical collection of items.
Each item has a textual label, an optional image, and an optional list of data
values. The data values are displayed in successive columns after the tree
label.

The order in which data values are displayed may be controlled by setting
the widget option ``displaycolumns``. The tree widget can also display column
headings. Columns may be accessed by number or symbolic names listed in the
widget option columns. See `Column Identifiers`_.

Each item is identified by a unique name. The widget will generate item IDs
if they are not supplied by the caller. There is a distinguished root item,
named ``{}``. The root item itself is not displayed; its children appear at the
top level of the hierarchy.

Each item also has a list of tags, which can be used to associate event bindings
with individual items and control the appearance of the item.

The Treeview widget supports horizontal and vertical scrolling, according to
the options described in `Scrollable Widget Options`_ and the methods
:meth:`Treeview.xview` and :meth:`Treeview.yview`.


Options
^^^^^^^

This widget accepts the following specific options:

.. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
..

   +----------------+--------------------------------------------------------+
   | option         | description                                            |
   +================+========================================================+
   | columns        | A list of column identifiers, specifying the number of |
   |                | columns and their names.                               |
   +----------------+--------------------------------------------------------+
   | displaycolumns | A list of column identifiers (either symbolic or       |
   |                | integer indices) specifying which data columns are     |
   |                | displayed and the order in which they appear, or the   |
   |                | string "#all".                                         |
   +----------------+--------------------------------------------------------+
   | height         | Specifies the number of rows which should be visible.  |
   |                | Note: the requested width is determined from the sum   |
   |                | of the column widths.                                  |
   +----------------+--------------------------------------------------------+
   | padding        | Specifies the internal padding for the widget. The     |
   |                | padding is a list of up to four length specifications. |
   +----------------+--------------------------------------------------------+
   | selectmode     | Controls how the built-in class bindings manage the    |
   |                | selection. One of "extended", "browse" or "none".      |
   |                | If set to "extended" (the default), multiple items may |
   |                | be selected. If "browse", only a single item will be   |
   |                | selected at a time. If "none", the selection will not  |
   |                | be changed.                                            |
   |                |                                                        |
   |                | Note that the application code and tag bindings can set|
   |                | the selection however they wish, regardless of the     |
   |                | value  of this option.                                 |
   +----------------+--------------------------------------------------------+
   | show           | A list containing zero or more of the following values,|
   |                | specifying which elements of the tree to display.      |
   |                |                                                        |
   |                | * tree: display tree labels in column #0.              |
   |                | * headings: display the heading row.                   |
   |                |                                                        |
   |                | The default is "tree headings", i.e., show all         |
   |                | elements.                                              |
   |                |                                                        |
   |                | **Note**: Column #0 always refers to the tree column,  |
   |                | even if show="tree" is not specified.                  |
   +----------------+--------------------------------------------------------+


Item Options
^^^^^^^^^^^^

The following item options may be specified for items in the insert and item
widget commands.

   +--------+---------------------------------------------------------------+
   | option | description                                                   |
   +========+===============================================================+
   | text   | The textual label to display for the item.                    |
   +--------+---------------------------------------------------------------+
   | image  | A Tk Image, displayed to the left of the label.               |
   +--------+---------------------------------------------------------------+
   | values | The list of values associated with the item.                  |
   |        |                                                               |
   |        | Each item should have the same number of values as the widget |
   |        | option columns. If there are fewer values than columns, the   |
   |        | remaining values are assumed empty. If there are more values  |
   |        | than columns, the extra values are ignored.                   |
   +--------+---------------------------------------------------------------+
   | open   | True/False value indicating whether the item's children should|
   |        | be displayed or hidden.                                       |
   +--------+---------------------------------------------------------------+
   | tags   | A list of tags associated with this item.                     |
   +--------+---------------------------------------------------------------+


Tag Options
^^^^^^^^^^^

The following options may be specified on tags:

   +------------+-----------------------------------------------------------+
   | option     | description                                               |
   +============+===========================================================+
   | foreground | Specifies the text foreground color.                      |
   +------------+-----------------------------------------------------------+
   | background | Specifies the cell or item background color.              |
   +------------+-----------------------------------------------------------+
   | font       | Specifies the font to use when drawing text.              |
   +------------+-----------------------------------------------------------+
   | image      | Specifies the item image, in case the item's image option |
   |            | is empty.                                                 |
   +------------+-----------------------------------------------------------+


Column Identifiers
^^^^^^^^^^^^^^^^^^

Column identifiers take any of the following forms:

* A symbolic name from the list of columns option.
* An integer n, specifying the nth data column.
* A string of the form #n, where n is an integer, specifying the nth display
  column.

Notes:

* Item's option values may be displayed in a different order than the order
  in which they are stored.
* Column #0 always refers to the tree column, even if show="tree" is not
  specified.

A data column number is an index into an item's option values list; a display
column number is the column number in the tree where the values are displayed.
Tree labels are displayed in column #0. If option displaycolumns is not set,
then data column n is displayed in column #n+1. Again, **column #0 always
refers to the tree column**.


Virtual Events
^^^^^^^^^^^^^^

The Treeview widget generates the following virtual events.

   +--------------------+--------------------------------------------------+
   | event              | description                                      |
   +====================+==================================================+
   | <<TreeviewSelect>> | Generated whenever the selection changes.        |
   +--------------------+--------------------------------------------------+
   | <<TreeviewOpen>>   | Generated just before settings the focus item to |
   |                    | open=True.                                       |
   +--------------------+--------------------------------------------------+
   | <<TreeviewClose>>  | Generated just after setting the focus item to   |
   |                    | open=False.                                      |
   +--------------------+--------------------------------------------------+

The :meth:`Treeview.focus` and :meth:`Treeview.selection` methods can be used
to determine the affected item or items.


ttk.Treeview
^^^^^^^^^^^^

.. class:: Treeview

   .. method:: bbox(item, column=None)

      Returns the bounding box (relative to the treeview widget's window) of
      the specified *item* in the form (x, y, width, height).

      If *column* is specified, returns the bounding box of that cell. If the
      *item* is not visible (i.e., if it is a descendant of a closed item or is
      scrolled offscreen), returns an empty string.


   .. method:: get_children([item])

      Returns the list of children belonging to *item*.

      If *item* is not specified, returns root children.


   .. method:: set_children(item, *newchildren)

      Replaces *item*'s child with *newchildren*.

      Children present in *item* that are not present in *newchildren* are
      detached from the tree. No items in *newchildren* may be an ancestor of
      *item*. Note that not specifying *newchildren* results in detaching
      *item*'s children.


   .. method:: column(column, option=None, **kw)

      Query or modify the options for the specified *column*.

      If *kw* is not given, returns a dict of the column option values. If
      *option* is specified then the value for that *option* is returned.
      Otherwise, sets the options to the corresponding values.

      The valid options/values are:

      * id
         Returns the column name. This is a read-only option.
      * anchor: One of the standard Tk anchor values.
         Specifies how the text in this column should be aligned with respect
         to the cell.
      * minwidth: width
         The minimum width of the column in pixels. The treeview widget will
         not make the column any smaller than specified by this option when
         the widget is resized or the user drags a column.
      * stretch: True/False
         Specifies whether the column's width should be adjusted when
         the widget is resized.
      * width: width
         The width of the column in pixels.

      To configure the tree column, call this with column = "#0"

   .. method:: delete(*items)

      Delete all specified *items* and all their descendants.

      The root item may not be deleted.


   .. method:: detach(*items)

      Unlinks all of the specified *items* from the tree.

      The items and all of their descendants are still present, and may be
      reinserted at another point in the tree, but will not be displayed.

      The root item may not be detached.


   .. method:: exists(item)

      Returns ``True`` if the specified *item* is present in the tree.


   .. method:: focus([item=None])

      If *item* is specified, sets the focus item to *item*. Otherwise, returns
      the current focus item, or '' if there is none.


   .. method:: heading(column, option=None, **kw)

      Query or modify the heading options for the specified *column*.

      If *kw* is not given, returns a dict of the heading option values. If
      *option* is specified then the value for that *option* is returned.
      Otherwise, sets the options to the corresponding values.

      The valid options/values are:

      * text: text
         The text to display in the column heading.
      * image: imageName
         Specifies an image to display to the right of the column heading.
      * anchor: anchor
         Specifies how the heading text should be aligned. One of the standard
         Tk anchor values.
      * command: callback
         A callback to be invoked when the heading label is pressed.

      To configure the tree column heading, call this with column = "#0".


   .. method:: identify(component, x, y)

      Returns a description of the specified *component* under the point given
      by *x* and *y*, or the empty string if no such *component* is present at
      that position.


   .. method:: identify_row(y)

      Returns the item ID of the item at position *y*.


   .. method:: identify_column(x)

      Returns the data column identifier of the cell at position *x*.

      The tree column has ID #0.


   .. method:: identify_region(x, y)

      Returns one of:

      +-----------+--------------------------------------+
      | region    | meaning                              |
      +===========+======================================+
      | heading   | Tree heading area.                   |
      +-----------+--------------------------------------+
      | separator | Space between two columns headings.  |
      +-----------+--------------------------------------+
      | tree      | The tree area.                       |
      +-----------+--------------------------------------+
      | cell      | A data cell.                         |
      +-----------+--------------------------------------+

      Availability: Tk 8.6.


   .. method:: identify_element(x, y)

      Returns the element at position *x*, *y*.

      Availability: Tk 8.6.


   .. method:: index(item)

      Returns the integer index of *item* within its parent's list of children.


   .. method:: insert(parent, index, iid=None, **kw)

      Creates a new item and returns the item identifier of the newly created
      item.

      *parent* is the item ID of the parent item, or the empty string to create
      a new top-level item. *index* is an integer, or the value "end",
      specifying where in the list of parent's children to insert the new item.
      If *index* is less than or equal to zero, the new node is inserted at
      the beginning; if *index* is greater than or equal to the current number
      of children, it is inserted at the end. If *iid* is specified, it is used
      as the item identifier; *iid* must not already exist in the tree.
      Otherwise, a new unique identifier is generated.

      See `Item Options`_ for the list of available points.


   .. method:: item(item[, option[, **kw]])

      Query or modify the options for the specified *item*.

      If no options are given, a dict with options/values for the item is
      returned.
      If *option* is specified then the value for that option is returned.
      Otherwise, sets the options to the corresponding values as given by *kw*.


   .. method:: move(item, parent, index)

      Moves *item* to position *index* in *parent*'s list of children.

      It is illegal to move an item under one of its descendants. If *index* is
      less than or equal to zero, *item* is moved to the beginning; if greater
      than or equal to the number of children, it is moved to the end. If *item*
      was detached it is reattached.


   .. method:: next(item)

      Returns the identifier of *item*'s next sibling, or '' if *item* is the
      last child of its parent.


   .. method:: parent(item)

      Returns the ID of the parent of *item*, or '' if *item* is at the top
      level of the hierarchy.


   .. method:: prev(item)

      Returns the identifier of *item*'s previous sibling, or '' if *item* is
      the first child of its parent.


   .. method:: reattach(item, parent, index)

      An alias for :meth:`Treeview.move`.


   .. method:: see(item)

      Ensure that *item* is visible.

      Sets all of *item*'s ancestors open option to ``True``, and scrolls the
      widget if necessary so that *item* is within the visible portion of
      the tree.


   .. method:: selection([selop=None[, items=None]])

      If *selop* is not specified, returns selected items. Otherwise, it will
      act according to the following selection methods.


   .. method:: selection_set(items)

      *items* becomes the new selection.


   .. method:: selection_add(items)

      Add *items* to the selection.


   .. method:: selection_remove(items)

      Remove *items* from the selection.


   .. method:: selection_toggle(items)

      Toggle the selection state of each item in *items*.


   .. method:: set(item, column=None, value=None)

      With one argument, returns a dictionary of column/value pairs for the
      specified *item*. With two arguments, returns the current value of the
      specified *column*. With three arguments, sets the value of given
      *column* in given *item* to the specified *value*.


   .. method:: tag_bind(tagname, sequence=None, callback=None)

      Bind a callback for the given event *sequence* to the tag *tagname*.
      When an event is delivered to an item, the callbacks for each of the
      item's tags option are called.


   .. method:: tag_configure(tagname, option=None, **kw)

      Query or modify the options for the specified *tagname*.

      If *kw* is not given, returns a dict of the option settings for
      *tagname*. If *option* is specified, returns the value for that *option*
      for the specified *tagname*. Otherwise, sets the options to the
      corresponding values for the given *tagname*.


   .. method:: tag_has(tagname[, item])

      If *item* is specified, returns 1 or 0 depending on whether the specified
      *item* has the given *tagname*. Otherwise, returns a list of all items
      that have the specified tag.

      Availability: Tk 8.6


   .. method:: xview(*args)

      Query or modify horizontal position of the treeview.


   .. method:: yview(*args)

      Query or modify vertical position of the treeview.


.. _TtkStyling:

Ttk Styling
-----------

Each widget in :mod:`ttk` is assigned a style, which specifies the set of
elements making up the widget and how they are arranged, along with dynamic and
default settings for element options. By default the style name is the same as
the widget's class name, but it may be overridden by the widget's style
option. If the class name of a widget is unknown, use the method
:meth:`Misc.winfo_class` (somewidget.winfo_class()).

.. seealso::

   `Tcl'2004 conference presentation <http://tktable.sourceforge.net/tile/tile-tcl2004.pdf>`_
      This document explains how the theme engine works


.. class:: Style

   This class is used to manipulate the style database.


   .. method:: configure(style, query_opt=None, **kw)

      Query or set the default value of the specified option(s) in *style*.

      Each key in *kw* is an option and each value is a string identifying
      the value for that option.

      For example, to change every default button to be a flat button with some
      padding and a different background color do::

         import ttk
         import Tkinter

         root = Tkinter.Tk()

         ttk.Style().configure("TButton", padding=6, relief="flat",
            background="#ccc")

         btn = ttk.Button(text="Sample")
         btn.pack()

         root.mainloop()


   .. method:: map(style, query_opt=None, **kw)

      Query or sets dynamic values of the specified option(s) in *style*.

      Each key in *kw* is an option and each value should be a list or a
      tuple (usually) containing statespecs grouped in tuples, lists, or
      something else of your preference. A statespec is a compound of one
      or more states and then a value.

      An example::

         import Tkinter
         import ttk

         root = Tkinter.Tk()

         style = ttk.Style()
         style.map("C.TButton",
             foreground=[('pressed', 'red'), ('active', 'blue')],
             background=[('pressed', '!disabled', 'black'), ('active', 'white')]
             )

         colored_btn = ttk.Button(text="Test", style="C.TButton").pack()

         root.mainloop()


      Note that the order of the (states, value) sequences for an
      option matters.  In the previous example, if you change the
      order to ``[('active', 'blue'), ('pressed', 'red')]`` in the
      foreground option, for example, you would get a blue foreground
      when the widget is in the active or pressed states.

   .. method:: lookup(style, option, state=None, default=None)

      Returns the value specified for *option* in *style*.

      If *state* is specified, it is expected to be a sequence of one or more
      states. If the *default* argument is set, it is used as a fallback value
      in case no specification for option is found.

      To check what font a Button uses by default, do::

         import ttk

         print ttk.Style().lookup("TButton", "font")


   .. method:: layout(style, layoutspec=None)

      Define the widget layout for given *style*. If *layoutspec* is omitted,
      return the layout specification for given style.

      *layoutspec*, if specified, is expected to be a list or some other
      sequence type (excluding strings), where each item should be a tuple and
      the first item is the layout name and the second item should have the
      format described in `Layouts`_.

      To understand the format, see the following example (it is not
      intended to do anything useful)::

         import ttk
         import Tkinter

         root = Tkinter.Tk()

         style = ttk.Style()
         style.layout("TMenubutton", [
            ("Menubutton.background", None),
            ("Menubutton.button", {"children":
                [("Menubutton.focus", {"children":
                    [("Menubutton.padding", {"children":
                        [("Menubutton.label", {"side": "left", "expand": 1})]
                    })]
                })]
            }),
         ])

         mbtn = ttk.Menubutton(text='Text')
         mbtn.pack()
         root.mainloop()


   .. method:: element_create(elementname, etype, *args, **kw)

      Create a new element in the current theme, of the given *etype* which is
      expected to be either "image", "from" or "vsapi". The latter is only
      available in Tk 8.6a for Windows XP and Vista and is not described here.

      If "image" is used, *args* should contain the default image name followed
      by statespec/value pairs (this is the imagespec), and *kw* may have the
      following options:

       * border=padding
          padding is a list of up to four integers, specifying the left, top,
          right, and bottom borders, respectively.

       * height=height
          Specifies a minimum height for the element. If less than zero, the
          base image's height is used as a default.

       * padding=padding
          Specifies the element's interior padding. Defaults to border's value
          if not specified.

       * sticky=spec
          Specifies how the image is placed within the final parcel. spec
          contains zero or more characters "n", "s", "w", or "e".

       * width=width
          Specifies a minimum width for the element. If less than zero, the
          base image's width is used as a default.

      If "from" is used as the value of *etype*,
      :meth:`element_create` will clone an existing
      element. *args* is expected to contain a themename, from which
      the element will be cloned, and optionally an element to clone from.
      If this element to clone from is not specified, an empty element will
      be used. *kw* is discarded.


   .. method:: element_names()

      Returns the list of elements defined in the current theme.


   .. method:: element_options(elementname)

      Returns the list of *elementname*'s options.


   .. method:: theme_create(themename, parent=None, settings=None)

      Create a new theme.

      It is an error if *themename* already exists. If *parent* is specified,
      the new theme will inherit styles, elements and layouts from the parent
      theme. If *settings* are present they are expected to have the same
      syntax used for :meth:`theme_settings`.


   .. method:: theme_settings(themename, settings)

      Temporarily sets the current theme to *themename*, apply specified
      *settings* and then restore the previous theme.

      Each key in *settings* is a style and each value may contain the keys
      'configure', 'map', 'layout' and 'element create' and they are expected
      to have the same format as specified by the methods
      :meth:`Style.configure`, :meth:`Style.map`, :meth:`Style.layout` and
      :meth:`Style.element_create` respectively.

      As an example, let's change the Combobox for the default theme a bit::

         import ttk
         import Tkinter

         root = Tkinter.Tk()

         style = ttk.Style()
         style.theme_settings("default", {
            "TCombobox": {
                "configure": {"padding": 5},
                "map": {
                    "background": [("active", "green2"),
                                   ("!disabled", "green4")],
                    "fieldbackground": [("!disabled", "green3")],
                    "foreground": [("focus", "OliveDrab1"),
                                   ("!disabled", "OliveDrab2")]
                }
            }
         })

         combo = ttk.Combobox().pack()

         root.mainloop()


   .. method:: theme_names()

      Returns a list of all known themes.


   .. method:: theme_use([themename])

      If *themename* is not given, returns the theme in use.  Otherwise, sets
      the current theme to *themename*, refreshes all widgets and emits a
      <<ThemeChanged>> event.


Layouts
^^^^^^^

A layout can be just ``None``, if it takes no options, or a dict of
options specifying how to arrange the element. The layout mechanism
uses a simplified version of the pack geometry manager: given an
initial cavity, each element is allocated a parcel. Valid
options/values are:

 * side: whichside
    Specifies which side of the cavity to place the element; one of
    top, right, bottom or left. If omitted, the element occupies the
    entire cavity.

 * sticky: nswe
    Specifies where the element is placed inside its allocated parcel.

 * unit: 0 or 1
    If set to 1, causes the element and all of its descendants to be treated as
    a single element for the purposes of :meth:`Widget.identify` et al. It's
    used for things like scrollbar thumbs with grips.

 * children: [sublayout... ]
    Specifies a list of elements to place inside the element. Each
    element is a tuple (or other sequence type) where the first item is
    the layout name, and the other is a `Layout`_.

.. _Layout: `Layouts`_
PK
%�\M��T��!html/_sources/library/tty.rst.txtnu�[���
:mod:`tty` --- Terminal control functions
=========================================

.. module:: tty
   :platform: Unix
   :synopsis: Utility functions that perform common terminal control operations.
.. moduleauthor:: Steen Lumholt
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>


The :mod:`tty` module defines functions for putting the tty into cbreak and raw
modes.

Because it requires the :mod:`termios` module, it will work only on Unix.

The :mod:`tty` module defines the following functions:


.. function:: setraw(fd[, when])

   Change the mode of the file descriptor *fd* to raw. If *when* is omitted, it
   defaults to :const:`termios.TCSAFLUSH`, and is passed to
   :func:`termios.tcsetattr`.


.. function:: setcbreak(fd[, when])

   Change the mode of file descriptor *fd* to cbreak. If *when* is omitted, it
   defaults to :const:`termios.TCSAFLUSH`, and is passed to
   :func:`termios.tcsetattr`.


.. seealso::

   Module :mod:`termios`
      Low-level terminal control interface.

PK
%�\h�a�a�$html/_sources/library/turtle.rst.txtnu�[���========================================
:mod:`turtle` --- Turtle graphics for Tk
========================================

.. module:: turtle
   :synopsis: Turtle graphics for Tk
.. sectionauthor:: Gregor Lingl <gregor.lingl@aon.at>

.. testsetup:: default

   from turtle import *
   turtle = Turtle()

Introduction
============

Turtle graphics is a popular way for introducing programming to kids.  It was
part of the original Logo programming language developed by Wally Feurzig and
Seymour Papert in 1966.

Imagine a robotic turtle starting at (0, 0) in the x-y plane.  After an ``import turtle``, give it the
command ``turtle.forward(15)``, and it moves (on-screen!) 15 pixels in the
direction it is facing, drawing a line as it moves.  Give it the command
``turtle.right(25)``, and it rotates in-place 25 degrees clockwise.

By combining together these and similar commands, intricate shapes and pictures
can easily be drawn.

The :mod:`turtle` module is an extended reimplementation of the same-named
module from the Python standard distribution up to version Python 2.5.

It tries to keep the merits of the old turtle module and to be (nearly) 100%
compatible with it.  This means in the first place to enable the learning
programmer to use all the commands, classes and methods interactively when using
the module from within IDLE run with the ``-n`` switch.

The turtle module provides turtle graphics primitives, in both object-oriented
and procedure-oriented ways.  Because it uses :mod:`Tkinter` for the underlying
graphics, it needs a version of Python installed with Tk support.

The object-oriented interface uses essentially two+two classes:

1. The :class:`TurtleScreen` class defines graphics windows as a playground for
   the drawing turtles.  Its constructor needs a :class:`Tkinter.Canvas` or a
   :class:`ScrolledCanvas` as argument.  It should be used when :mod:`turtle` is
   used as part of some application.

   The function :func:`Screen` returns a singleton object of a
   :class:`TurtleScreen` subclass. This function should be used when
   :mod:`turtle` is used as a standalone tool for doing graphics.
   As a singleton object, inheriting from its class is not possible.

   All methods of TurtleScreen/Screen also exist as functions, i.e. as part of
   the procedure-oriented interface.

2. :class:`RawTurtle` (alias: :class:`RawPen`) defines Turtle objects which draw
   on a :class:`TurtleScreen`.  Its constructor needs a Canvas, ScrolledCanvas
   or TurtleScreen as argument, so the RawTurtle objects know where to draw.

   Derived from RawTurtle is the subclass :class:`Turtle` (alias: :class:`Pen`),
   which draws on "the" :class:`Screen` - instance which is automatically
   created, if not already present.

   All methods of RawTurtle/Turtle also exist as functions, i.e. part of the
   procedure-oriented interface.

The procedural interface provides functions which are derived from the methods
of the classes :class:`Screen` and :class:`Turtle`.  They have the same names as
the corresponding methods.  A screen object is automatically created whenever a
function derived from a Screen method is called.  An (unnamed) turtle object is
automatically created whenever any of the functions derived from a Turtle method
is called.

To use multiple turtles an a screen one has to use the object-oriented interface.

.. note::
   In the following documentation the argument list for functions is given.
   Methods, of course, have the additional first argument *self* which is
   omitted here.


Overview over available Turtle and Screen methods
=================================================

Turtle methods
--------------

Turtle motion
   Move and draw
      | :func:`forward` | :func:`fd`
      | :func:`backward` | :func:`bk` | :func:`back`
      | :func:`right` | :func:`rt`
      | :func:`left` | :func:`lt`
      | :func:`goto` | :func:`setpos` | :func:`setposition`
      | :func:`setx`
      | :func:`sety`
      | :func:`setheading` | :func:`seth`
      | :func:`home`
      | :func:`circle`
      | :func:`dot`
      | :func:`stamp`
      | :func:`clearstamp`
      | :func:`clearstamps`
      | :func:`undo`
      | :func:`speed`

   Tell Turtle's state
      | :func:`position` | :func:`pos`
      | :func:`towards`
      | :func:`xcor`
      | :func:`ycor`
      | :func:`heading`
      | :func:`distance`

   Setting and measurement
      | :func:`degrees`
      | :func:`radians`

Pen control
   Drawing state
      | :func:`pendown` | :func:`pd` | :func:`down`
      | :func:`penup` | :func:`pu` | :func:`up`
      | :func:`pensize` | :func:`width`
      | :func:`pen`
      | :func:`isdown`

   Color control
      | :func:`color`
      | :func:`pencolor`
      | :func:`fillcolor`

   Filling
      | :func:`fill`
      | :func:`begin_fill`
      | :func:`end_fill`

   More drawing control
      | :func:`reset`
      | :func:`clear`
      | :func:`write`

Turtle state
   Visibility
      | :func:`showturtle` | :func:`st`
      | :func:`hideturtle` | :func:`ht`
      | :func:`isvisible`

   Appearance
      | :func:`shape`
      | :func:`resizemode`
      | :func:`shapesize` | :func:`turtlesize`
      | :func:`settiltangle`
      | :func:`tiltangle`
      | :func:`tilt`

Using events
   | :func:`onclick`
   | :func:`onrelease`
   | :func:`ondrag`
   | :func:`mainloop` | :func:`done`

Special Turtle methods
   | :func:`begin_poly`
   | :func:`end_poly`
   | :func:`get_poly`
   | :func:`clone`
   | :func:`getturtle` | :func:`getpen`
   | :func:`getscreen`
   | :func:`setundobuffer`
   | :func:`undobufferentries`
   | :func:`tracer`
   | :func:`window_width`
   | :func:`window_height`


Methods of TurtleScreen/Screen
------------------------------

Window control
   | :func:`bgcolor`
   | :func:`bgpic`
   | :func:`clear` | :func:`clearscreen`
   | :func:`reset` | :func:`resetscreen`
   | :func:`screensize`
   | :func:`setworldcoordinates`

Animation control
   | :func:`delay`
   | :func:`tracer`
   | :func:`update`

Using screen events
   | :func:`listen`
   | :func:`onkey`
   | :func:`onclick` | :func:`onscreenclick`
   | :func:`ontimer`

Settings and special methods
   | :func:`mode`
   | :func:`colormode`
   | :func:`getcanvas`
   | :func:`getshapes`
   | :func:`register_shape` | :func:`addshape`
   | :func:`turtles`
   | :func:`window_height`
   | :func:`window_width`

Methods specific to Screen
   | :func:`bye`
   | :func:`exitonclick`
   | :func:`setup`
   | :func:`title`


Methods of RawTurtle/Turtle and corresponding functions
=======================================================

Most of the examples in this section refer to a Turtle instance called
``turtle``.

Turtle motion
-------------

.. function:: forward(distance)
              fd(distance)

   :param distance: a number (integer or float)

   Move the turtle forward by the specified *distance*, in the direction the
   turtle is headed.

   .. doctest::

      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.forward(25)
      >>> turtle.position()
      (25.00,0.00)
      >>> turtle.forward(-75)
      >>> turtle.position()
      (-50.00,0.00)


.. function:: back(distance)
              bk(distance)
              backward(distance)

   :param distance: a number

   Move the turtle backward by *distance*, opposite to the direction the
   turtle is headed.  Do not change the turtle's heading.

   .. doctest::
      :hide:

      >>> turtle.goto(0, 0)

   .. doctest::

      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.backward(30)
      >>> turtle.position()
      (-30.00,0.00)


.. function:: right(angle)
              rt(angle)

   :param angle: a number (integer or float)

   Turn turtle right by *angle* units.  (Units are by default degrees, but
   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
   orientation depends on the turtle mode, see :func:`mode`.

   .. doctest::
      :hide:

      >>> turtle.setheading(22)

   .. doctest::

      >>> turtle.heading()
      22.0
      >>> turtle.right(45)
      >>> turtle.heading()
      337.0


.. function:: left(angle)
              lt(angle)

   :param angle: a number (integer or float)

   Turn turtle left by *angle* units.  (Units are by default degrees, but
   can be set via the :func:`degrees` and :func:`radians` functions.)  Angle
   orientation depends on the turtle mode, see :func:`mode`.

   .. doctest::
      :hide:

      >>> turtle.setheading(22)

   .. doctest::

      >>> turtle.heading()
      22.0
      >>> turtle.left(45)
      >>> turtle.heading()
      67.0


.. function:: goto(x, y=None)
              setpos(x, y=None)
              setposition(x, y=None)

   :param x: a number or a pair/vector of numbers
   :param y: a number or ``None``

   If *y* is ``None``, *x* must be a pair of coordinates or a :class:`Vec2D`
   (e.g. as returned by :func:`pos`).

   Move turtle to an absolute position.  If the pen is down, draw line.  Do
   not change the turtle's orientation.

   .. doctest::
      :hide:

      >>> turtle.goto(0, 0)

   .. doctest::

       >>> tp = turtle.pos()
       >>> tp
       (0.00,0.00)
       >>> turtle.setpos(60,30)
       >>> turtle.pos()
       (60.00,30.00)
       >>> turtle.setpos((20,80))
       >>> turtle.pos()
       (20.00,80.00)
       >>> turtle.setpos(tp)
       >>> turtle.pos()
       (0.00,0.00)


.. function:: setx(x)

   :param x: a number (integer or float)

   Set the turtle's first coordinate to *x*, leave second coordinate
   unchanged.

   .. doctest::
      :hide:

      >>> turtle.goto(0, 240)

   .. doctest::

      >>> turtle.position()
      (0.00,240.00)
      >>> turtle.setx(10)
      >>> turtle.position()
      (10.00,240.00)


.. function:: sety(y)

   :param y: a number (integer or float)

   Set the turtle's second coordinate to *y*, leave first coordinate unchanged.

   .. doctest::
      :hide:

      >>> turtle.goto(0, 40)

   .. doctest::

      >>> turtle.position()
      (0.00,40.00)
      >>> turtle.sety(-10)
      >>> turtle.position()
      (0.00,-10.00)


.. function:: setheading(to_angle)
              seth(to_angle)

   :param to_angle: a number (integer or float)

   Set the orientation of the turtle to *to_angle*.  Here are some common
   directions in degrees:

   =================== ====================
    standard mode           logo mode
   =================== ====================
      0 - east                0 - north
     90 - north              90 - east
    180 - west              180 - south
    270 - south             270 - west
   =================== ====================

   .. doctest::

      >>> turtle.setheading(90)
      >>> turtle.heading()
      90.0


.. function:: home()

   Move turtle to the origin -- coordinates (0,0) -- and set its heading to
   its start-orientation (which depends on the mode, see :func:`mode`).

   .. doctest::
      :hide:

      >>> turtle.setheading(90)
      >>> turtle.goto(0, -10)

   .. doctest::

      >>> turtle.heading()
      90.0
      >>> turtle.position()
      (0.00,-10.00)
      >>> turtle.home()
      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.heading()
      0.0


.. function:: circle(radius, extent=None, steps=None)

   :param radius: a number
   :param extent: a number (or ``None``)
   :param steps: an integer (or ``None``)

   Draw a circle with given *radius*.  The center is *radius* units left of
   the turtle; *extent* -- an angle -- determines which part of the circle
   is drawn.  If *extent* is not given, draw the entire circle.  If *extent*
   is not a full circle, one endpoint of the arc is the current pen
   position.  Draw the arc in counterclockwise direction if *radius* is
   positive, otherwise in clockwise direction.  Finally the direction of the
   turtle is changed by the amount of *extent*.

   As the circle is approximated by an inscribed regular polygon, *steps*
   determines the number of steps to use.  If not given, it will be
   calculated automatically.  May be used to draw regular polygons.

   .. doctest::

      >>> turtle.home()
      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.heading()
      0.0
      >>> turtle.circle(50)
      >>> turtle.position()
      (-0.00,0.00)
      >>> turtle.heading()
      0.0
      >>> turtle.circle(120, 180)  # draw a semicircle
      >>> turtle.position()
      (0.00,240.00)
      >>> turtle.heading()
      180.0


.. function:: dot(size=None, *color)

   :param size: an integer >= 1 (if given)
   :param color: a colorstring or a numeric color tuple

   Draw a circular dot with diameter *size*, using *color*.  If *size* is
   not given, the maximum of pensize+4 and 2*pensize is used.


   .. doctest::

      >>> turtle.home()
      >>> turtle.dot()
      >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
      >>> turtle.position()
      (100.00,-0.00)
      >>> turtle.heading()
      0.0


.. function:: stamp()

   Stamp a copy of the turtle shape onto the canvas at the current turtle
   position.  Return a stamp_id for that stamp, which can be used to delete
   it by calling ``clearstamp(stamp_id)``.

   .. doctest::

      >>> turtle.color("blue")
      >>> turtle.stamp()
      11
      >>> turtle.fd(50)


.. function:: clearstamp(stampid)

   :param stampid: an integer, must be return value of previous
                   :func:`stamp` call

   Delete stamp with given *stampid*.

   .. doctest::

      >>> turtle.position()
      (150.00,-0.00)
      >>> turtle.color("blue")
      >>> astamp = turtle.stamp()
      >>> turtle.fd(50)
      >>> turtle.position()
      (200.00,-0.00)
      >>> turtle.clearstamp(astamp)
      >>> turtle.position()
      (200.00,-0.00)


.. function:: clearstamps(n=None)

   :param n: an integer (or ``None``)

   Delete all or first/last *n* of turtle's stamps.  If *n* is ``None``, delete
   all stamps, if *n* > 0 delete first *n* stamps, else if *n* < 0 delete
   last *n* stamps.

   .. doctest::

      >>> for i in range(8):
      ...     turtle.stamp(); turtle.fd(30)
      13
      14
      15
      16
      17
      18
      19
      20
      >>> turtle.clearstamps(2)
      >>> turtle.clearstamps(-2)
      >>> turtle.clearstamps()


.. function:: undo()

   Undo (repeatedly) the last turtle action(s).  Number of available
   undo actions is determined by the size of the undobuffer.

   .. doctest::

      >>> for i in range(4):
      ...     turtle.fd(50); turtle.lt(80)
      ...
      >>> for i in range(8):
      ...     turtle.undo()


.. function:: speed(speed=None)

   :param speed: an integer in the range 0..10 or a speedstring (see below)

   Set the turtle's speed to an integer value in the range 0..10.  If no
   argument is given, return current speed.

   If input is a number greater than 10 or smaller than 0.5, speed is set
   to 0.  Speedstrings are mapped to speedvalues as follows:

   * "fastest":  0
   * "fast":  10
   * "normal":  6
   * "slow":  3
   * "slowest":  1

   Speeds from 1 to 10 enforce increasingly faster animation of line drawing
   and turtle turning.

   Attention: *speed* = 0 means that *no* animation takes
   place. forward/back makes turtle jump and likewise left/right make the
   turtle turn instantly.

   .. doctest::

      >>> turtle.speed()
      3
      >>> turtle.speed('normal')
      >>> turtle.speed()
      6
      >>> turtle.speed(9)
      >>> turtle.speed()
      9


Tell Turtle's state
-------------------

.. function:: position()
              pos()

   Return the turtle's current location (x,y) (as a :class:`Vec2D` vector).

   .. doctest::

      >>> turtle.pos()
      (440.00,-0.00)


.. function:: towards(x, y=None)

   :param x: a number or a pair/vector of numbers or a turtle instance
   :param y: a number if *x* is a number, else ``None``

   Return the angle between the line from turtle position to position specified
   by (x,y), the vector or the other turtle.  This depends on the turtle's start
   orientation which depends on the mode - "standard"/"world" or "logo").

   .. doctest::

      >>> turtle.goto(10, 10)
      >>> turtle.towards(0,0)
      225.0


.. function:: xcor()

   Return the turtle's x coordinate.

   .. doctest::

      >>> turtle.home()
      >>> turtle.left(50)
      >>> turtle.forward(100)
      >>> turtle.pos()
      (64.28,76.60)
      >>> print turtle.xcor()
      64.2787609687


.. function:: ycor()

   Return the turtle's y coordinate.

   .. doctest::

      >>> turtle.home()
      >>> turtle.left(60)
      >>> turtle.forward(100)
      >>> print turtle.pos()
      (50.00,86.60)
      >>> print turtle.ycor()
      86.6025403784


.. function:: heading()

   Return the turtle's current heading (value depends on the turtle mode, see
   :func:`mode`).

   .. doctest::

      >>> turtle.home()
      >>> turtle.left(67)
      >>> turtle.heading()
      67.0


.. function:: distance(x, y=None)

   :param x: a number or a pair/vector of numbers or a turtle instance
   :param y: a number if *x* is a number, else ``None``

   Return the distance from the turtle to (x,y), the given vector, or the given
   other turtle, in turtle step units.

   .. doctest::

      >>> turtle.home()
      >>> turtle.distance(30,40)
      50.0
      >>> turtle.distance((30,40))
      50.0
      >>> joe = Turtle()
      >>> joe.forward(77)
      >>> turtle.distance(joe)
      77.0


Settings for measurement
------------------------

.. function:: degrees(fullcircle=360.0)

   :param fullcircle: a number

   Set angle measurement units, i.e. set number of "degrees" for a full circle.
   Default value is 360 degrees.

   .. doctest::

      >>> turtle.home()
      >>> turtle.left(90)
      >>> turtle.heading()
      90.0

      Change angle measurement unit to grad (also known as gon,
      grade, or gradian and equals 1/100-th of the right angle.)
      >>> turtle.degrees(400.0)
      >>> turtle.heading()
      100.0
      >>> turtle.degrees(360)
      >>> turtle.heading()
      90.0


.. function:: radians()

   Set the angle measurement units to radians.  Equivalent to
   ``degrees(2*math.pi)``.

   .. doctest::

      >>> turtle.home()
      >>> turtle.left(90)
      >>> turtle.heading()
      90.0
      >>> turtle.radians()
      >>> turtle.heading()
      1.5707963267948966

   .. doctest::
      :hide:

      >>> turtle.degrees(360)


Pen control
-----------

Drawing state
~~~~~~~~~~~~~

.. function:: pendown()
              pd()
              down()

   Pull the pen down -- drawing when moving.


.. function:: penup()
              pu()
              up()

   Pull the pen up -- no drawing when moving.


.. function:: pensize(width=None)
              width(width=None)

   :param width: a positive number

   Set the line thickness to *width* or return it.  If resizemode is set to
   "auto" and turtleshape is a polygon, that polygon is drawn with the same line
   thickness.  If no argument is given, the current pensize is returned.

   .. doctest::

      >>> turtle.pensize()
      1
      >>> turtle.pensize(10)   # from here on lines of width 10 are drawn


.. function:: pen(pen=None, **pendict)

   :param pen: a dictionary with some or all of the below listed keys
   :param pendict: one or more keyword-arguments with the below listed keys as keywords

   Return or set the pen's attributes in a "pen-dictionary" with the following
   key/value pairs:

   * "shown": True/False
   * "pendown": True/False
   * "pencolor": color-string or color-tuple
   * "fillcolor": color-string or color-tuple
   * "pensize": positive number
   * "speed": number in range 0..10
   * "resizemode": "auto" or "user" or "noresize"
   * "stretchfactor": (positive number, positive number)
   * "outline": positive number
   * "tilt": number

   This dictionary can be used as argument for a subsequent call to :func:`pen`
   to restore the former pen-state.  Moreover one or more of these attributes
   can be provided as keyword-arguments.  This can be used to set several pen
   attributes in one statement.

   .. doctest::
      :options: +NORMALIZE_WHITESPACE

      >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
      >>> sorted(turtle.pen().items())
      [('fillcolor', 'black'), ('outline', 1), ('pencolor', 'red'),
       ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
      >>> penstate=turtle.pen()
      >>> turtle.color("yellow", "")
      >>> turtle.penup()
      >>> sorted(turtle.pen().items())
      [('fillcolor', ''), ('outline', 1), ('pencolor', 'yellow'),
       ('pendown', False), ('pensize', 10), ('resizemode', 'noresize'),
       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]
      >>> turtle.pen(penstate, fillcolor="green")
      >>> sorted(turtle.pen().items())
      [('fillcolor', 'green'), ('outline', 1), ('pencolor', 'red'),
       ('pendown', True), ('pensize', 10), ('resizemode', 'noresize'),
       ('shown', True), ('speed', 9), ('stretchfactor', (1, 1)), ('tilt', 0)]


.. function:: isdown()

   Return ``True`` if pen is down, ``False`` if it's up.

   .. doctest::

      >>> turtle.penup()
      >>> turtle.isdown()
      False
      >>> turtle.pendown()
      >>> turtle.isdown()
      True


Color control
~~~~~~~~~~~~~

.. function:: pencolor(*args)

   Return or set the pencolor.

   Four input formats are allowed:

   ``pencolor()``
      Return the current pencolor as color specification string or
      as a tuple (see example).  May be used as input to another
      color/pencolor/fillcolor call.

   ``pencolor(colorstring)``
      Set pencolor to *colorstring*, which is a Tk color specification string,
      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.

   ``pencolor((r, g, b))``
      Set pencolor to the RGB color represented by the tuple of *r*, *g*, and
      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
      colormode is either 1.0 or 255 (see :func:`colormode`).

   ``pencolor(r, g, b)``
      Set pencolor to the RGB color represented by *r*, *g*, and *b*.  Each of
      *r*, *g*, and *b* must be in the range 0..colormode.

    If turtleshape is a polygon, the outline of that polygon is drawn with the
    newly set pencolor.

   .. doctest::

       >>> colormode()
       1.0
       >>> turtle.pencolor()
       'red'
       >>> turtle.pencolor("brown")
       >>> turtle.pencolor()
       'brown'
       >>> tup = (0.2, 0.8, 0.55)
       >>> turtle.pencolor(tup)
       >>> turtle.pencolor()
       (0.2, 0.8, 0.5490196078431373)
       >>> colormode(255)
       >>> turtle.pencolor()
       (51, 204, 140)
       >>> turtle.pencolor('#32c18f')
       >>> turtle.pencolor()
       (50, 193, 143)


.. function:: fillcolor(*args)

   Return or set the fillcolor.

   Four input formats are allowed:

   ``fillcolor()``
      Return the current fillcolor as color specification string, possibly
      in tuple format (see example).  May be used as input to another
      color/pencolor/fillcolor call.

   ``fillcolor(colorstring)``
      Set fillcolor to *colorstring*, which is a Tk color specification string,
      such as ``"red"``, ``"yellow"``, or ``"#33cc8c"``.

   ``fillcolor((r, g, b))``
      Set fillcolor to the RGB color represented by the tuple of *r*, *g*, and
      *b*.  Each of *r*, *g*, and *b* must be in the range 0..colormode, where
      colormode is either 1.0 or 255 (see :func:`colormode`).

   ``fillcolor(r, g, b)``
      Set fillcolor to the RGB color represented by *r*, *g*, and *b*.  Each of
      *r*, *g*, and *b* must be in the range 0..colormode.

    If turtleshape is a polygon, the interior of that polygon is drawn
    with the newly set fillcolor.

   .. doctest::

       >>> turtle.fillcolor("violet")
       >>> turtle.fillcolor()
       'violet'
       >>> col = turtle.pencolor()
       >>> col
       (50, 193, 143)
       >>> turtle.fillcolor(col)
       >>> turtle.fillcolor()
       (50, 193, 143)
       >>> turtle.fillcolor('#ffffff')
       >>> turtle.fillcolor()
       (255, 255, 255)


.. function:: color(*args)

   Return or set pencolor and fillcolor.

   Several input formats are allowed.  They use 0 to 3 arguments as
   follows:

   ``color()``
      Return the current pencolor and the current fillcolor as a pair of color
      specification strings or tuples as returned by :func:`pencolor` and
      :func:`fillcolor`.

   ``color(colorstring)``, ``color((r,g,b))``, ``color(r,g,b)``
      Inputs as in :func:`pencolor`, set both, fillcolor and pencolor, to the
      given value.

   ``color(colorstring1, colorstring2)``, ``color((r1,g1,b1), (r2,g2,b2))``
      Equivalent to ``pencolor(colorstring1)`` and ``fillcolor(colorstring2)``
      and analogously if the other input format is used.

    If turtleshape is a polygon, outline and interior of that polygon is drawn
    with the newly set colors.

   .. doctest::

       >>> turtle.color("red", "green")
       >>> turtle.color()
       ('red', 'green')
       >>> color("#285078", "#a0c8f0")
       >>> color()
       ((40, 80, 120), (160, 200, 240))


See also: Screen method :func:`colormode`.


Filling
~~~~~~~

.. doctest::
   :hide:

   >>> turtle.home()

.. function:: fill(flag)

   :param flag: True/False (or 1/0 respectively)

   Call ``fill(True)`` before drawing the shape you want to fill, and
   ``fill(False)`` when done.  When used without argument: return fillstate
   (``True`` if filling, ``False`` else).

   .. doctest::

      >>> turtle.fill(True)
      >>> for _ in range(3):
      ...    turtle.forward(100)
      ...    turtle.left(120)
      ...
      >>> turtle.fill(False)


.. function:: begin_fill()

   Call just before drawing a shape to be filled.  Equivalent to ``fill(True)``.


.. function:: end_fill()

   Fill the shape drawn after the last call to :func:`begin_fill`.  Equivalent
   to ``fill(False)``.

   .. doctest::

      >>> turtle.color("black", "red")
      >>> turtle.begin_fill()
      >>> turtle.circle(80)
      >>> turtle.end_fill()


More drawing control
~~~~~~~~~~~~~~~~~~~~

.. function:: reset()

   Delete the turtle's drawings from the screen, re-center the turtle and set
   variables to the default values.

   .. doctest::

      >>> turtle.goto(0,-22)
      >>> turtle.left(100)
      >>> turtle.position()
      (0.00,-22.00)
      >>> turtle.heading()
      100.0
      >>> turtle.reset()
      >>> turtle.position()
      (0.00,0.00)
      >>> turtle.heading()
      0.0


.. function:: clear()

   Delete the turtle's drawings from the screen.  Do not move turtle.  State and
   position of the turtle as well as drawings of other turtles are not affected.


.. function:: write(arg, move=False, align="left", font=("Arial", 8, "normal"))

   :param arg: object to be written to the TurtleScreen
   :param move: True/False
   :param align: one of the strings "left", "center" or right"
   :param font: a triple (fontname, fontsize, fonttype)

   Write text - the string representation of *arg* - at the current turtle
   position according to *align* ("left", "center" or right") and with the given
   font.  If *move* is true, the pen is moved to the bottom-right corner of the
   text.  By default, *move* is ``False``.

   >>> turtle.write("Home = ", True, align="center")
   >>> turtle.write((0,0), True)


Turtle state
------------

Visibility
~~~~~~~~~~

.. function:: hideturtle()
              ht()

   Make the turtle invisible.  It's a good idea to do this while you're in the
   middle of doing some complex drawing, because hiding the turtle speeds up the
   drawing observably.

   .. doctest::

      >>> turtle.hideturtle()


.. function:: showturtle()
              st()

   Make the turtle visible.

   .. doctest::

      >>> turtle.showturtle()


.. function:: isvisible()

   Return ``True`` if the Turtle is shown, ``False`` if it's hidden.

   >>> turtle.hideturtle()
   >>> turtle.isvisible()
   False
   >>> turtle.showturtle()
   >>> turtle.isvisible()
   True


Appearance
~~~~~~~~~~

.. function:: shape(name=None)

   :param name: a string which is a valid shapename

   Set turtle shape to shape with given *name* or, if name is not given, return
   name of current shape.  Shape with *name* must exist in the TurtleScreen's
   shape dictionary.  Initially there are the following polygon shapes: "arrow",
   "turtle", "circle", "square", "triangle", "classic".  To learn about how to
   deal with shapes see Screen method :func:`register_shape`.

   .. doctest::

      >>> turtle.shape()
      'classic'
      >>> turtle.shape("turtle")
      >>> turtle.shape()
      'turtle'


.. function:: resizemode(rmode=None)

   :param rmode: one of the strings "auto", "user", "noresize"

   Set resizemode to one of the values: "auto", "user", "noresize".  If *rmode*
   is not given, return current resizemode.  Different resizemodes have the
   following effects:

   - "auto": adapts the appearance of the turtle corresponding to the value of pensize.
   - "user": adapts the appearance of the turtle according to the values of
     stretchfactor and outlinewidth (outline), which are set by
     :func:`shapesize`.
   - "noresize": no adaption of the turtle's appearance takes place.

   resizemode("user") is called by :func:`shapesize` when used with arguments.

   .. doctest::

      >>> turtle.resizemode()
      'noresize'
      >>> turtle.resizemode("auto")
      >>> turtle.resizemode()
      'auto'


.. function:: shapesize(stretch_wid=None, stretch_len=None, outline=None)
              turtlesize(stretch_wid=None, stretch_len=None, outline=None)

   :param stretch_wid: positive number
   :param stretch_len: positive number
   :param outline: positive number

   Return or set the pen's attributes x/y-stretchfactors and/or outline.  Set
   resizemode to "user".  If and only if resizemode is set to "user", the turtle
   will be displayed stretched according to its stretchfactors: *stretch_wid* is
   stretchfactor perpendicular to its orientation, *stretch_len* is
   stretchfactor in direction of its orientation, *outline* determines the width
   of the shapes's outline.

   .. doctest::

      >>> turtle.shapesize()
      (1, 1, 1)
      >>> turtle.resizemode("user")
      >>> turtle.shapesize(5, 5, 12)
      >>> turtle.shapesize()
      (5, 5, 12)
      >>> turtle.shapesize(outline=8)
      >>> turtle.shapesize()
      (5, 5, 8)


.. function:: tilt(angle)

   :param angle: a number

   Rotate the turtleshape by *angle* from its current tilt-angle, but do *not*
   change the turtle's heading (direction of movement).

   .. doctest::

      >>> turtle.reset()
      >>> turtle.shape("circle")
      >>> turtle.shapesize(5,2)
      >>> turtle.tilt(30)
      >>> turtle.fd(50)
      >>> turtle.tilt(30)
      >>> turtle.fd(50)


.. function:: settiltangle(angle)

   :param angle: a number

   Rotate the turtleshape to point in the direction specified by *angle*,
   regardless of its current tilt-angle.  *Do not* change the turtle's heading
   (direction of movement).

   .. doctest::

      >>> turtle.reset()
      >>> turtle.shape("circle")
      >>> turtle.shapesize(5,2)
      >>> turtle.settiltangle(45)
      >>> turtle.fd(50)
      >>> turtle.settiltangle(-45)
      >>> turtle.fd(50)


.. function:: tiltangle()

   Return the current tilt-angle, i.e. the angle between the orientation of the
   turtleshape and the heading of the turtle (its direction of movement).

   .. doctest::

      >>> turtle.reset()
      >>> turtle.shape("circle")
      >>> turtle.shapesize(5,2)
      >>> turtle.tilt(45)
      >>> turtle.tiltangle()
      45.0


Using events
------------

.. function:: onclick(fun, btn=1, add=None)

   :param fun: a function with two arguments which will be called with the
               coordinates of the clicked point on the canvas
   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
               added, otherwise it will replace a former binding

   Bind *fun* to mouse-click events on this turtle.  If *fun* is ``None``,
   existing bindings are removed.  Example for the anonymous turtle, i.e. the
   procedural way:

   .. doctest::

      >>> def turn(x, y):
      ...     left(180)
      ...
      >>> onclick(turn)  # Now clicking into the turtle will turn it.
      >>> onclick(None)  # event-binding will be removed


.. function:: onrelease(fun, btn=1, add=None)

   :param fun: a function with two arguments which will be called with the
               coordinates of the clicked point on the canvas
   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
               added, otherwise it will replace a former binding

   Bind *fun* to mouse-button-release events on this turtle.  If *fun* is
   ``None``, existing bindings are removed.

   .. doctest::

      >>> class MyTurtle(Turtle):
      ...     def glow(self,x,y):
      ...         self.fillcolor("red")
      ...     def unglow(self,x,y):
      ...         self.fillcolor("")
      ...
      >>> turtle = MyTurtle()
      >>> turtle.onclick(turtle.glow)     # clicking on turtle turns fillcolor red,
      >>> turtle.onrelease(turtle.unglow) # releasing turns it to transparent.


.. function:: ondrag(fun, btn=1, add=None)

   :param fun: a function with two arguments which will be called with the
               coordinates of the clicked point on the canvas
   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
               added, otherwise it will replace a former binding

   Bind *fun* to mouse-move events on this turtle.  If *fun* is ``None``,
   existing bindings are removed.

   Remark: Every sequence of mouse-move-events on a turtle is preceded by a
   mouse-click event on that turtle.

   .. doctest::

      >>> turtle.ondrag(turtle.goto)

   Subsequently, clicking and dragging the Turtle will move it across
   the screen thereby producing handdrawings (if pen is down).


.. function:: mainloop()
              done()

   Starts event loop - calling Tkinter's mainloop function. Must be the last
   statement in a turtle graphics program.

      >>> turtle.mainloop()


Special Turtle methods
----------------------

.. function:: begin_poly()

   Start recording the vertices of a polygon.  Current turtle position is first
   vertex of polygon.


.. function:: end_poly()

   Stop recording the vertices of a polygon.  Current turtle position is last
   vertex of polygon.  This will be connected with the first vertex.


.. function:: get_poly()

   Return the last recorded polygon.

   .. doctest::

      >>> turtle.home()
      >>> turtle.begin_poly()
      >>> turtle.fd(100)
      >>> turtle.left(20)
      >>> turtle.fd(30)
      >>> turtle.left(60)
      >>> turtle.fd(50)
      >>> turtle.end_poly()
      >>> p = turtle.get_poly()
      >>> register_shape("myFavouriteShape", p)


.. function:: clone()

   Create and return a clone of the turtle with same position, heading and
   turtle properties.

   .. doctest::

      >>> mick = Turtle()
      >>> joe = mick.clone()


.. function:: getturtle()
              getpen()

   Return the Turtle object itself.  Only reasonable use: as a function to
   return the "anonymous turtle":

   .. doctest::

      >>> pet = getturtle()
      >>> pet.fd(50)
      >>> pet
      <turtle.Turtle object at 0x...>


.. function:: getscreen()

   Return the :class:`TurtleScreen` object the turtle is drawing on.
   TurtleScreen methods can then be called for that object.

   .. doctest::

      >>> ts = turtle.getscreen()
      >>> ts
      <turtle._Screen object at 0x...>
      >>> ts.bgcolor("pink")


.. function:: setundobuffer(size)

   :param size: an integer or ``None``

   Set or disable undobuffer.  If *size* is an integer an empty undobuffer of
   given size is installed.  *size* gives the maximum number of turtle actions
   that can be undone by the :func:`undo` method/function.  If *size* is
   ``None``, the undobuffer is disabled.

   .. doctest::

      >>> turtle.setundobuffer(42)


.. function:: undobufferentries()

   Return number of entries in the undobuffer.

   .. doctest::

      >>> while undobufferentries():
      ...     undo()


.. function:: tracer(flag=None, delay=None)

   A replica of the corresponding TurtleScreen method.

   .. deprecated:: 2.6


.. function:: window_width()
              window_height()

   Both are replicas of the corresponding TurtleScreen methods.

   .. deprecated:: 2.6


.. _compoundshapes:

Excursus about the use of compound shapes
-----------------------------------------

To use compound turtle shapes, which consist of several polygons of different
color, you must use the helper class :class:`Shape` explicitly as described
below:

1. Create an empty Shape object of type "compound".
2. Add as many components to this object as desired, using the
   :meth:`addcomponent` method.

   For example:

   .. doctest::

      >>> s = Shape("compound")
      >>> poly1 = ((0,0),(10,-5),(0,10),(-10,-5))
      >>> s.addcomponent(poly1, "red", "blue")
      >>> poly2 = ((0,0),(10,-5),(-10,-5))
      >>> s.addcomponent(poly2, "blue", "red")

3. Now add the Shape to the Screen's shapelist and use it:

   .. doctest::

      >>> register_shape("myshape", s)
      >>> shape("myshape")


.. note::

   The :class:`Shape` class is used internally by the :func:`register_shape`
   method in different ways.  The application programmer has to deal with the
   Shape class *only* when using compound shapes like shown above!


Methods of TurtleScreen/Screen and corresponding functions
==========================================================

Most of the examples in this section refer to a TurtleScreen instance called
``screen``.

.. doctest::
   :hide:

   >>> screen = Screen()

Window control
--------------

.. function:: bgcolor(*args)

   :param args: a color string or three numbers in the range 0..colormode or a
                3-tuple of such numbers


   Set or return background color of the TurtleScreen.

   .. doctest::

      >>> screen.bgcolor("orange")
      >>> screen.bgcolor()
      'orange'
      >>> screen.bgcolor("#800080")
      >>> screen.bgcolor()
      (128, 0, 128)


.. function:: bgpic(picname=None)

   :param picname: a string, name of a gif-file or ``"nopic"``, or ``None``

   Set background image or return name of current backgroundimage.  If *picname*
   is a filename, set the corresponding image as background.  If *picname* is
   ``"nopic"``, delete background image, if present.  If *picname* is ``None``,
   return the filename of the current backgroundimage. ::

       >>> screen.bgpic()
       'nopic'
       >>> screen.bgpic("landscape.gif")
       >>> screen.bgpic()
       "landscape.gif"


.. function:: clear()
              clearscreen()

   Delete all drawings and all turtles from the TurtleScreen.  Reset the now
   empty TurtleScreen to its initial state: white background, no background
   image, no event bindings and tracing on.

   .. note::
      This TurtleScreen method is available as a global function only under the
      name ``clearscreen``.  The global function ``clear`` is another one
      derived from the Turtle method ``clear``.


.. function:: reset()
              resetscreen()

   Reset all Turtles on the Screen to their initial state.

   .. note::
      This TurtleScreen method is available as a global function only under the
      name ``resetscreen``.  The global function ``reset`` is another one
      derived from the Turtle method ``reset``.


.. function:: screensize(canvwidth=None, canvheight=None, bg=None)

   :param canvwidth: positive integer, new width of canvas in pixels
   :param canvheight: positive integer, new height of canvas in pixels
   :param bg: colorstring or color-tuple, new background color

   If no arguments are given, return current (canvaswidth, canvasheight).  Else
   resize the canvas the turtles are drawing on.  Do not alter the drawing
   window.  To observe hidden parts of the canvas, use the scrollbars. With this
   method, one can make visible those parts of a drawing which were outside the
   canvas before.

      >>> screen.screensize()
      (400, 300)
      >>> screen.screensize(2000,1500)
      >>> screen.screensize()
      (2000, 1500)

   e.g. to search for an erroneously escaped turtle ;-)


.. function:: setworldcoordinates(llx, lly, urx, ury)

   :param llx: a number, x-coordinate of lower left corner of canvas
   :param lly: a number, y-coordinate of lower left corner of canvas
   :param urx: a number, x-coordinate of upper right corner of canvas
   :param ury: a number, y-coordinate of upper right corner of canvas

   Set up user-defined coordinate system and switch to mode "world" if
   necessary.  This performs a ``screen.reset()``.  If mode "world" is already
   active, all drawings are redrawn according to the new coordinates.

   **ATTENTION**: in user-defined coordinate systems angles may appear
   distorted.

   .. doctest::

      >>> screen.reset()
      >>> screen.setworldcoordinates(-50,-7.5,50,7.5)
      >>> for _ in range(72):
      ...     left(10)
      ...
      >>> for _ in range(8):
      ...     left(45); fd(2)   # a regular octagon

   .. doctest::
      :hide:

      >>> screen.reset()
      >>> for t in turtles():
      ...      t.reset()


Animation control
-----------------

.. function:: delay(delay=None)

   :param delay: positive integer

   Set or return the drawing *delay* in milliseconds.  (This is approximately
   the time interval between two consecutive canvas updates.)  The longer the
   drawing delay, the slower the animation.

   Optional argument:

   .. doctest::

      >>> screen.delay()
      10
      >>> screen.delay(5)
      >>> screen.delay()
      5


.. function:: tracer(n=None, delay=None)

   :param n: nonnegative integer
   :param delay: nonnegative integer

   Turn turtle animation on/off and set delay for update drawings.  If *n* is
   given, only each n-th regular screen update is really performed.  (Can be
   used to accelerate the drawing of complex graphics.)  Second argument sets
   delay value (see :func:`delay`).

   .. doctest::

      >>> screen.tracer(8, 25)
      >>> dist = 2
      >>> for i in range(200):
      ...     fd(dist)
      ...     rt(90)
      ...     dist += 2


.. function:: update()

   Perform a TurtleScreen update. To be used when tracer is turned off.

See also the RawTurtle/Turtle method :func:`speed`.


Using screen events
-------------------

.. function:: listen(xdummy=None, ydummy=None)

   Set focus on TurtleScreen (in order to collect key-events).  Dummy arguments
   are provided in order to be able to pass :func:`listen` to the onclick method.


.. function:: onkey(fun, key)

   :param fun: a function with no arguments or ``None``
   :param key: a string: key (e.g. "a") or key-symbol (e.g. "space")

   Bind *fun* to key-release event of key.  If *fun* is ``None``, event bindings
   are removed. Remark: in order to be able to register key-events, TurtleScreen
   must have the focus. (See method :func:`listen`.)

   .. doctest::

      >>> def f():
      ...     fd(50)
      ...     lt(60)
      ...
      >>> screen.onkey(f, "Up")
      >>> screen.listen()


.. function:: onclick(fun, btn=1, add=None)
              onscreenclick(fun, btn=1, add=None)

   :param fun: a function with two arguments which will be called with the
               coordinates of the clicked point on the canvas
   :param btn: number of the mouse-button, defaults to 1 (left mouse button)
   :param add: ``True`` or ``False`` -- if ``True``, a new binding will be
               added, otherwise it will replace a former binding

   Bind *fun* to mouse-click events on this screen.  If *fun* is ``None``,
   existing bindings are removed.

   Example for a TurtleScreen instance named ``screen`` and a Turtle instance
   named turtle:

   .. doctest::

      >>> screen.onclick(turtle.goto) # Subsequently clicking into the TurtleScreen will
      >>>                             # make the turtle move to the clicked point.
      >>> screen.onclick(None)        # remove event binding again

   .. note::
      This TurtleScreen method is available as a global function only under the
      name ``onscreenclick``.  The global function ``onclick`` is another one
      derived from the Turtle method ``onclick``.


.. function:: ontimer(fun, t=0)

   :param fun: a function with no arguments
   :param t: a number >= 0

   Install a timer that calls *fun* after *t* milliseconds.

   .. doctest::

      >>> running = True
      >>> def f():
      ...     if running:
      ...         fd(50)
      ...         lt(60)
      ...         screen.ontimer(f, 250)
      >>> f()   ### makes the turtle march around
      >>> running = False


Settings and special methods
----------------------------

.. function:: mode(mode=None)

   :param mode: one of the strings "standard", "logo" or "world"

   Set turtle mode ("standard", "logo" or "world") and perform reset.  If mode
   is not given, current mode is returned.

   Mode "standard" is compatible with old :mod:`turtle`.  Mode "logo" is
   compatible with most Logo turtle graphics.  Mode "world" uses user-defined
   "world coordinates". **Attention**: in this mode angles appear distorted if
   ``x/y`` unit-ratio doesn't equal 1.

   ============ ========================= ===================
       Mode      Initial turtle heading     positive angles
   ============ ========================= ===================
    "standard"    to the right (east)       counterclockwise
      "logo"        upward    (north)         clockwise
   ============ ========================= ===================

   .. doctest::

      >>> mode("logo")   # resets turtle heading to north
      >>> mode()
      'logo'


.. function:: colormode(cmode=None)

   :param cmode: one of the values 1.0 or 255

   Return the colormode or set it to 1.0 or 255.  Subsequently *r*, *g*, *b*
   values of color triples have to be in the range 0..\ *cmode*.

   .. doctest::

      >>> screen.colormode(1)
      >>> turtle.pencolor(240, 160, 80)
      Traceback (most recent call last):
           ...
      TurtleGraphicsError: bad color sequence: (240, 160, 80)
      >>> screen.colormode()
      1.0
      >>> screen.colormode(255)
      >>> screen.colormode()
      255
      >>> turtle.pencolor(240,160,80)


.. function:: getcanvas()

   Return the Canvas of this TurtleScreen.  Useful for insiders who know what to
   do with a Tkinter Canvas.

   .. doctest::

      >>> cv = screen.getcanvas()
      >>> cv
      <turtle.ScrolledCanvas instance at 0x...>


.. function:: getshapes()

   Return a list of names of all currently available turtle shapes.

   .. doctest::

      >>> screen.getshapes()
      ['arrow', 'blank', 'circle', ..., 'turtle']


.. function:: register_shape(name, shape=None)
              addshape(name, shape=None)

   There are three different ways to call this function:

   (1) *name* is the name of a gif-file and *shape* is ``None``: Install the
       corresponding image shape. ::

       >>> screen.register_shape("turtle.gif")

       .. note::
          Image shapes *do not* rotate when turning the turtle, so they do not
          display the heading of the turtle!

   (2) *name* is an arbitrary string and *shape* is a tuple of pairs of
       coordinates: Install the corresponding polygon shape.

       .. doctest::

          >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3)))

   (3) *name* is an arbitrary string and shape is a (compound) :class:`Shape`
       object: Install the corresponding compound shape.

   Add a turtle shape to TurtleScreen's shapelist.  Only thusly registered
   shapes can be used by issuing the command ``shape(shapename)``.


.. function:: turtles()

   Return the list of turtles on the screen.

   .. doctest::

      >>> for turtle in screen.turtles():
      ...     turtle.color("red")


.. function:: window_height()

   Return the height of the turtle window. ::

       >>> screen.window_height()
       480


.. function:: window_width()

   Return the width of the turtle window. ::

       >>> screen.window_width()
       640


.. _screenspecific:

Methods specific to Screen, not inherited from TurtleScreen
-----------------------------------------------------------

.. function:: bye()

   Shut the turtlegraphics window.


.. function:: exitonclick()

   Bind bye() method to mouse clicks on the Screen.


   If the value "using_IDLE" in the configuration dictionary is ``False``
   (default value), also enter mainloop.  Remark: If IDLE with the ``-n`` switch
   (no subprocess) is used, this value should be set to ``True`` in
   :file:`turtle.cfg`.  In this case IDLE's own mainloop is active also for the
   client script.


.. function:: setup(width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])

   Set the size and position of the main window.  Default values of arguments
   are stored in the configuration dictionary and can be changed via a
   :file:`turtle.cfg` file.

   :param width: if an integer, a size in pixels, if a float, a fraction of the
                 screen; default is 50% of screen
   :param height: if an integer, the height in pixels, if a float, a fraction of
                  the screen; default is 75% of screen
   :param startx: if positive, starting position in pixels from the left
                  edge of the screen, if negative from the right edge, if ``None``,
                  center window horizontally
   :param starty: if positive, starting position in pixels from the top
                  edge of the screen, if negative from the bottom edge, if ``None``,
                  center window vertically

   .. doctest::

      >>> screen.setup (width=200, height=200, startx=0, starty=0)
      >>>              # sets window to 200x200 pixels, in upper left of screen
      >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
      >>>              # sets window to 75% of screen by 50% of screen and centers


.. function:: title(titlestring)

   :param titlestring: a string that is shown in the titlebar of the turtle
                       graphics window

   Set title of turtle window to *titlestring*.

   .. doctest::

      >>> screen.title("Welcome to the turtle zoo!")


The public classes of the module :mod:`turtle`
==============================================


.. class:: RawTurtle(canvas)
           RawPen(canvas)

   :param canvas: a :class:`Tkinter.Canvas`, a :class:`ScrolledCanvas` or a
                  :class:`TurtleScreen`

   Create a turtle.  The turtle has all methods described above as "methods of
   Turtle/RawTurtle".


.. class:: Turtle()

   Subclass of RawTurtle, has the same interface but draws on a default
   :class:`Screen` object created automatically when needed for the first time.


.. class:: TurtleScreen(cv)

   :param cv: a :class:`Tkinter.Canvas`

   Provides screen oriented methods like :func:`setbg` etc. that are described
   above.

.. class:: Screen()

   Subclass of TurtleScreen, with :ref:`four methods added <screenspecific>`.


.. class:: ScrolledCanvas(master)

   :param master: some Tkinter widget to contain the ScrolledCanvas, i.e.
      a Tkinter-canvas with scrollbars added

   Used by class Screen, which thus automatically provides a ScrolledCanvas as
   playground for the turtles.

.. class:: Shape(type_, data)

   :param type\_: one of the strings "polygon", "image", "compound"

   Data structure modeling shapes.  The pair ``(type_, data)`` must follow this
   specification:


   =========== ===========
   *type_*     *data*
   =========== ===========
   "polygon"   a polygon-tuple, i.e. a tuple of pairs of coordinates
   "image"     an image  (in this form only used internally!)
   "compound"  ``None`` (a compound shape has to be constructed using the
               :meth:`addcomponent` method)
   =========== ===========

   .. method:: addcomponent(poly, fill, outline=None)

      :param poly: a polygon, i.e. a tuple of pairs of numbers
      :param fill: a color the *poly* will be filled with
      :param outline: a color for the poly's outline (if given)

      Example:

      .. doctest::

         >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
         >>> s = Shape("compound")
         >>> s.addcomponent(poly, "red", "blue")
         >>> # ... add more components and then use register_shape()

      See :ref:`compoundshapes`.


.. class:: Vec2D(x, y)

   A two-dimensional vector class, used as a helper class for implementing
   turtle graphics.  May be useful for turtle graphics programs too.  Derived
   from tuple, so a vector is a tuple!

   Provides (for *a*, *b* vectors, *k* number):

   * ``a + b`` vector addition
   * ``a - b`` vector subtraction
   * ``a * b`` inner product
   * ``k * a`` and ``a * k`` multiplication with scalar
   * ``abs(a)`` absolute value of a
   * ``a.rotate(angle)`` rotation


Help and configuration
======================

How to use help
---------------

The public methods of the Screen and Turtle classes are documented extensively
via docstrings.  So these can be used as online-help via the Python help
facilities:

- When using IDLE, tooltips show the signatures and first lines of the
  docstrings of typed in function-/method calls.

- Calling :func:`help` on methods or functions displays the docstrings::

     >>> help(Screen.bgcolor)
     Help on method bgcolor in module turtle:

     bgcolor(self, *args) unbound turtle.Screen method
         Set or return backgroundcolor of the TurtleScreen.

         Arguments (if given): a color string or three numbers
         in the range 0..colormode or a 3-tuple of such numbers.


           >>> screen.bgcolor("orange")
           >>> screen.bgcolor()
           "orange"
           >>> screen.bgcolor(0.5,0,0.5)
           >>> screen.bgcolor()
           "#800080"

     >>> help(Turtle.penup)
     Help on method penup in module turtle:

     penup(self) unbound turtle.Turtle method
         Pull the pen up -- no drawing when moving.

         Aliases: penup | pu | up

         No argument

         >>> turtle.penup()

- The docstrings of the functions which are derived from methods have a modified
  form::

     >>> help(bgcolor)
     Help on function bgcolor in module turtle:

     bgcolor(*args)
         Set or return backgroundcolor of the TurtleScreen.

         Arguments (if given): a color string or three numbers
         in the range 0..colormode or a 3-tuple of such numbers.

         Example::

           >>> bgcolor("orange")
           >>> bgcolor()
           "orange"
           >>> bgcolor(0.5,0,0.5)
           >>> bgcolor()
           "#800080"

     >>> help(penup)
     Help on function penup in module turtle:

     penup()
         Pull the pen up -- no drawing when moving.

         Aliases: penup | pu | up

         No argument

         Example:
         >>> penup()

These modified docstrings are created automatically together with the function
definitions that are derived from the methods at import time.


Translation of docstrings into different languages
--------------------------------------------------

There is a utility to create a dictionary the keys of which are the method names
and the values of which are the docstrings of the public methods of the classes
Screen and Turtle.

.. function:: write_docstringdict(filename="turtle_docstringdict")

   :param filename: a string, used as filename

   Create and write docstring-dictionary to a Python script with the given
   filename.  This function has to be called explicitly (it is not used by the
   turtle graphics classes).  The docstring dictionary will be written to the
   Python script :file:`{filename}.py`.  It is intended to serve as a template
   for translation of the docstrings into different languages.

If you (or your students) want to use :mod:`turtle` with online help in your
native language, you have to translate the docstrings and save the resulting
file as e.g. :file:`turtle_docstringdict_german.py`.

If you have an appropriate entry in your :file:`turtle.cfg` file this dictionary
will be read in at import time and will replace the original English docstrings.

At the time of this writing there are docstring dictionaries in German and in
Italian.  (Requests please to glingl@aon.at.)



How to configure Screen and Turtles
-----------------------------------

The built-in default configuration mimics the appearance and behaviour of the
old turtle module in order to retain best possible compatibility with it.

If you want to use a different configuration which better reflects the features
of this module or which better fits to your needs, e.g. for use in a classroom,
you can prepare a configuration file ``turtle.cfg`` which will be read at import
time and modify the configuration according to its settings.

The built in configuration would correspond to the following turtle.cfg::

   width = 0.5
   height = 0.75
   leftright = None
   topbottom = None
   canvwidth = 400
   canvheight = 300
   mode = standard
   colormode = 1.0
   delay = 10
   undobuffersize = 1000
   shape = classic
   pencolor = black
   fillcolor = black
   resizemode = noresize
   visible = True
   language = english
   exampleturtle = turtle
   examplescreen = screen
   title = Python Turtle Graphics
   using_IDLE = False

Short explanation of selected entries:

- The first four lines correspond to the arguments of the :meth:`Screen.setup`
  method.
- Line 5 and 6 correspond to the arguments of the method
  :meth:`Screen.screensize`.
- *shape* can be any of the built-in shapes, e.g: arrow, turtle, etc.  For more
  info try ``help(shape)``.
- If you want to use no fillcolor (i.e. make the turtle transparent), you have
  to write ``fillcolor = ""`` (but all nonempty strings must not have quotes in
  the cfg-file).
- If you want to reflect the turtle its state, you have to use ``resizemode =
  auto``.
- If you set e.g. ``language = italian`` the docstringdict
  :file:`turtle_docstringdict_italian.py` will be loaded at import time (if
  present on the import path, e.g. in the same directory as :mod:`turtle`.
- The entries *exampleturtle* and *examplescreen* define the names of these
  objects as they occur in the docstrings.  The transformation of
  method-docstrings to function-docstrings will delete these names from the
  docstrings.
- *using_IDLE*: Set this to ``True`` if you regularly work with IDLE and its -n
  switch ("no subprocess").  This will prevent :func:`exitonclick` to enter the
  mainloop.

There can be a :file:`turtle.cfg` file in the directory where :mod:`turtle` is
stored and an additional one in the current working directory.  The latter will
override the settings of the first one.

The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file.  You can
study it as an example and see its effects when running the demos (preferably
not from within the demo-viewer).


Demo scripts
============

There is a set of demo scripts in the turtledemo directory located in the
:file:`Demo/turtle` directory in the source distribution.

It contains:

- a set of 15 demo scripts demonstrating different features of the new module
  :mod:`turtle`
- a demo viewer :file:`turtleDemo.py` which can be used to view the sourcecode
  of the scripts and run them at the same time. 14 of the examples can be
  accessed via the Examples menu; all of them can also be run standalone.
- The example :file:`turtledemo_two_canvases.py` demonstrates the simultaneous
  use of two canvases with the turtle module.  Therefore it only can be run
  standalone.
- There is a :file:`turtle.cfg` file in this directory, which also serves as an
  example for how to write and use such files.

The demoscripts are:

.. tabularcolumns:: |l|L|L|

+----------------+------------------------------+-----------------------+
| Name           | Description                  | Features              |
+================+==============================+=======================+
| bytedesign     | complex classical            | :func:`tracer`, delay,|
|                | turtlegraphics pattern       | :func:`update`        |
+----------------+------------------------------+-----------------------+
| chaos          | graphs Verhulst dynamics,    | world coordinates     |
|                | shows that computer's        |                       |
|                | computations can generate    |                       |
|                | results sometimes against the|                       |
|                | common sense expectations    |                       |
+----------------+------------------------------+-----------------------+
| clock          | analog clock showing time    | turtles as clock's    |
|                | of your computer             | hands, ontimer        |
+----------------+------------------------------+-----------------------+
| colormixer     | experiment with r, g, b      | :func:`ondrag`        |
+----------------+------------------------------+-----------------------+
| fractalcurves  | Hilbert & Koch curves        | recursion             |
+----------------+------------------------------+-----------------------+
| lindenmayer    | ethnomathematics             | L-System              |
|                | (indian kolams)              |                       |
+----------------+------------------------------+-----------------------+
| minimal_hanoi  | Towers of Hanoi              | Rectangular Turtles   |
|                |                              | as Hanoi discs        |
|                |                              | (shape, shapesize)    |
+----------------+------------------------------+-----------------------+
| paint          | super minimalistic           | :func:`onclick`       |
|                | drawing program              |                       |
+----------------+------------------------------+-----------------------+
| peace          | elementary                   | turtle: appearance    |
|                |                              | and animation         |
+----------------+------------------------------+-----------------------+
| penrose        | aperiodic tiling with        | :func:`stamp`         |
|                | kites and darts              |                       |
+----------------+------------------------------+-----------------------+
| planet_and_moon| simulation of                | compound shapes,      |
|                | gravitational system         | :class:`Vec2D`        |
+----------------+------------------------------+-----------------------+
| tree           | a (graphical) breadth        | :func:`clone`         |
|                | first tree (using generators)|                       |
+----------------+------------------------------+-----------------------+
| wikipedia      | a pattern from the wikipedia | :func:`clone`,        |
|                | article on turtle graphics   | :func:`undo`          |
+----------------+------------------------------+-----------------------+
| yinyang        | another elementary example   | :func:`circle`        |
+----------------+------------------------------+-----------------------+

Have fun!

.. doctest::
   :hide:

   >>> for turtle in turtles():
   ...      turtle.reset()
   >>> turtle.penup()
   >>> turtle.goto(-200,25)
   >>> turtle.pendown()
   >>> turtle.write("No one expects the Spanish Inquisition!",
   ...      font=("Arial", 20, "normal"))
   >>> turtle.penup()
   >>> turtle.goto(-100,-50)
   >>> turtle.pendown()
   >>> turtle.write("Our two chief Turtles are...",
   ...      font=("Arial", 16, "normal"))
   >>> turtle.penup()
   >>> turtle.goto(-450,-75)
   >>> turtle.write(str(turtles()))
PK
%�\�&�88#html/_sources/library/types.rst.txtnu�[���:mod:`types` --- Names for built-in types
=========================================

.. module:: types
   :synopsis: Names for built-in types.

**Source code:** :source:`Lib/types.py`

--------------

This module defines names for some object types that are used by the standard
Python interpreter, but not for the types defined by various extension modules.
Also, it does not include some of the types that arise during processing such as
the ``listiterator`` type. It is safe to use ``from types import *`` --- the
module does not export any names besides the ones listed here. New names
exported by future versions of this module will all end in ``Type``.

Typical use is for functions that do different things depending on their
argument types, like the following::

   from types import *
   def delete(mylist, item):
       if type(item) is IntType:
          del mylist[item]
       else:
          mylist.remove(item)

Starting in Python 2.2, built-in factory functions such as :func:`int` and
:func:`str` are also names for the corresponding types.  This is now the
preferred way to access the type instead of using the :mod:`types` module.
Accordingly, the example above should be written as follows::

   def delete(mylist, item):
       if isinstance(item, int):
          del mylist[item]
       else:
          mylist.remove(item)

The module defines the following names:


.. data:: NoneType

   The type of ``None``.


.. data:: TypeType

   .. index:: builtin: type

   The type of type objects (such as returned by :func:`type`); alias of the
   built-in :class:`type`.


.. data:: BooleanType

   The type of the :class:`bool` values ``True`` and ``False``; alias of the
   built-in :class:`bool`.

   .. versionadded:: 2.3


.. data:: IntType

   The type of integers (e.g. ``1``); alias of the built-in :class:`int`.


.. data:: LongType

   The type of long integers (e.g. ``1L``); alias of the built-in :class:`long`.


.. data:: FloatType

   The type of floating point numbers (e.g. ``1.0``); alias of the built-in
   :class:`float`.


.. data:: ComplexType

   The type of complex numbers (e.g. ``1.0j``).  This is not defined if Python was
   built without complex number support.


.. data:: StringType

   The type of character strings (e.g. ``'Spam'``); alias of the built-in
   :class:`str`.


.. data:: UnicodeType

   The type of Unicode character strings (e.g. ``u'Spam'``).  This is not defined
   if Python was built without Unicode support.  It's an alias of the built-in
   :class:`unicode`.


.. data:: TupleType

   The type of tuples (e.g. ``(1, 2, 3, 'Spam')``); alias of the built-in
   :class:`tuple`.


.. data:: ListType

   The type of lists (e.g. ``[0, 1, 2, 3]``); alias of the built-in
   :class:`list`.


.. data:: DictType

   The type of dictionaries (e.g. ``{'Bacon': 1, 'Ham': 0}``); alias of the
   built-in :class:`dict`.


.. data:: DictionaryType

   An alternate name for ``DictType``.


.. data:: FunctionType
          LambdaType

   The type of user-defined functions and functions created by :keyword:`lambda`
   expressions.


.. data:: GeneratorType

   The type of :term:`generator`-iterator objects, produced by calling a
   generator function.

   .. versionadded:: 2.2


.. data:: CodeType

   .. index:: builtin: compile

   The type for code objects such as returned by :func:`compile`.


.. data:: ClassType

   The type of user-defined old-style classes.


.. data:: InstanceType

   The type of instances of user-defined old-style classes.


.. data:: MethodType

   The type of methods of user-defined class instances.


.. data:: UnboundMethodType

   An alternate name for ``MethodType``.


.. data:: BuiltinFunctionType
          BuiltinMethodType

   The type of built-in functions like :func:`len` or :func:`sys.exit`, and
   methods of built-in classes.  (Here, the term "built-in" means "written in
   C".)


.. data:: ModuleType

   The type of modules.


.. data:: FileType

   The type of open file objects such as ``sys.stdout``; alias of the built-in
   :class:`file`.


.. data:: XRangeType

   .. index:: builtin: xrange

   The type of range objects returned by :func:`xrange`; alias of the built-in
   :class:`xrange`.


.. data:: SliceType

   .. index:: builtin: slice

   The type of objects returned by :func:`slice`; alias of the built-in
   :class:`slice`.


.. data:: EllipsisType

   The type of ``Ellipsis``.


.. data:: TracebackType

   The type of traceback objects such as found in ``sys.exc_traceback``.


.. data:: FrameType

   The type of frame objects such as found in ``tb.tb_frame`` if ``tb`` is a
   traceback object.


.. data:: BufferType

   .. index:: builtin: buffer

   The type of buffer objects created by the :func:`buffer` function.


.. data:: DictProxyType

   The type of dict proxies, such as ``TypeType.__dict__``.


.. data:: NotImplementedType

   The type of ``NotImplemented``


.. data:: GetSetDescriptorType

   The type of objects defined in extension modules with ``PyGetSetDef``, such
   as ``FrameType.f_locals`` or ``array.array.typecode``.  This type is used as
   descriptor for object attributes; it has the same purpose as the
   :class:`property` type, but for classes defined in extension modules.

   .. versionadded:: 2.5


.. data:: MemberDescriptorType

   The type of objects defined in extension modules with ``PyMemberDef``, such
   as ``datetime.timedelta.days``.  This type is used as descriptor for simple C
   data members which use standard conversion functions; it has the same purpose
   as the :class:`property` type, but for classes defined in extension modules.

   .. impl-detail::

      In other implementations of Python, this type may be identical to
      ``GetSetDescriptorType``.

   .. versionadded:: 2.5


.. data:: StringTypes

   A sequence containing ``StringType`` and ``UnicodeType`` used to facilitate
   easier checking for any string object.  Using this is more portable than using a
   sequence of the two string types constructed elsewhere since it only contains
   ``UnicodeType`` if it has been built in the running version of Python.  For
   example: ``isinstance(s, types.StringTypes)``.

   .. versionadded:: 2.2
PK
%�\�z�(��#html/_sources/library/undoc.rst.txtnu�[���
.. _undoc:

********************
Undocumented Modules
********************

Here's a quick listing of modules that are currently undocumented, but that
should be documented.  Feel free to contribute documentation for them!  (Send
via email to docs@python.org.)

The idea and original contents for this chapter were taken from a posting by
Fredrik Lundh; the specific contents of this chapter have been substantially
revised.


Miscellaneous useful utilities
==============================

Some of these are very old and/or not very robust; marked with "hmm."

:mod:`ihooks`
   --- Import hook support (for :mod:`rexec`; may become obsolete).  Removed in
   Python 3.x.


Platform specific modules
=========================

These modules are used to implement the :mod:`os.path` module, and are not
documented beyond this mention.  There's little need to document these.

:mod:`ntpath`
   --- Implementation of :mod:`os.path` on Win32, Win64, WinCE, and OS/2 platforms.

:mod:`posixpath`
   --- Implementation of :mod:`os.path` on POSIX.

:mod:`bsddb185`
   --- Backwards compatibility module for systems which still use the Berkeley DB
   1.85 module.  It is normally only available on certain BSD Unix-based systems.
   It should never be used directly.


Multimedia
==========

:mod:`audiodev`
   --- Platform-independent API for playing audio data.  Removed in Python 3.x.

:mod:`linuxaudiodev`
   --- Play audio data on the Linux audio device.  Replaced in Python 2.3 by the
   :mod:`ossaudiodev` module.  Removed in Python 3.x.

:mod:`sunaudio`
   --- Interpret Sun audio headers (may become obsolete or a tool/demo).
   Removed in Python 3.x.

:mod:`toaiff`
   --- Convert "arbitrary" sound files to AIFF files; should probably become a tool
   or demo.  Requires the external program :program:`sox`.  Removed in Python 3.x.


.. _undoc-mac-modules:

Undocumented Mac OS modules
===========================


:mod:`applesingle` --- AppleSingle decoder
------------------------------------------

.. module:: applesingle
   :platform: Mac
   :synopsis: Rudimentary decoder for AppleSingle format files.
   :deprecated:

.. deprecated:: 2.6


:mod:`buildtools` --- Helper module for BuildApplet and Friends
---------------------------------------------------------------

.. module:: buildtools
   :platform: Mac
   :synopsis: Helper module for BuildApplet, BuildApplication and macfreeze.
   :deprecated:


.. deprecated:: 2.4

:mod:`cfmfile` --- Code Fragment Resource module
------------------------------------------------

.. module:: cfmfile
   :platform: Mac
   :synopsis: Code Fragment Resource module.
   :deprecated:


:mod:`cfmfile` is a module that understands Code Fragments and the accompanying
"cfrg" resources. It can parse them and merge them, and is used by
BuildApplication to combine all plugin modules to a single executable.

.. deprecated:: 2.4

:mod:`icopen` --- Internet Config replacement for :meth:`open`
--------------------------------------------------------------

.. module:: icopen
   :platform: Mac
   :synopsis: Internet Config replacement for open().
   :deprecated:


Importing :mod:`icopen` will replace the built-in :meth:`open` with a version
that uses Internet Config to set file type and creator for new files.

.. deprecated:: 2.6


:mod:`macerrors` --- Mac OS Errors
----------------------------------

.. module:: macerrors
   :platform: Mac
   :synopsis: Constant definitions for many Mac OS error codes.
   :deprecated:


:mod:`macerrors` contains constant definitions for many Mac OS error codes.

.. deprecated:: 2.6


:mod:`macresource` --- Locate script resources
----------------------------------------------

.. module:: macresource
   :platform: Mac
   :synopsis: Locate script resources.
   :deprecated:


:mod:`macresource` helps scripts finding their resources, such as dialogs and
menus, without requiring special case code for when the script is run under
MacPython, as a MacPython applet or under OSX Python.

.. deprecated:: 2.6


:mod:`Nav` --- NavServices calls
--------------------------------

.. module:: Nav
   :platform: Mac
   :synopsis: Interface to Navigation Services.
   :deprecated:


A low-level interface to Navigation Services.

.. deprecated:: 2.6


:mod:`PixMapWrapper` --- Wrapper for PixMap objects
---------------------------------------------------

.. module:: PixMapWrapper
   :platform: Mac
   :synopsis: Wrapper for PixMap objects.
   :deprecated:


:mod:`PixMapWrapper` wraps a PixMap object with a Python object that allows
access to the fields by name. It also has methods to convert to and from
:mod:`PIL` images.

.. deprecated:: 2.6


:mod:`videoreader` --- Read QuickTime movies
--------------------------------------------

.. module:: videoreader
   :platform: Mac
   :synopsis: Read QuickTime movies frame by frame for further processing.
   :deprecated:


:mod:`videoreader` reads and decodes QuickTime movies and passes a stream of
images to your program. It also provides some support for audio tracks.

.. deprecated:: 2.6


:mod:`W` --- Widgets built on :mod:`FrameWork`
----------------------------------------------

.. module:: W
   :platform: Mac
   :synopsis: Widgets for the Mac, built on top of FrameWork.
   :deprecated:


The :mod:`W` widgets are used extensively in the :program:`IDE`.

.. deprecated:: 2.6


.. _obsolete-modules:

Obsolete
========

These modules are not normally available for import; additional work must be
done to make them available.

These extension modules written in C are not built by default. Under Unix, these
must be enabled by uncommenting the appropriate lines in :file:`Modules/Setup`
in the build tree and either rebuilding Python if the modules are statically
linked, or building and installing the shared object if using dynamically-loaded
extensions.

.. (lib-old is empty as of Python 2.5)

   Those which are written in Python will be installed into the directory
   \file{lib-old/} installed as part of the standard library.  To use
   these, the directory must be added to \code{sys.path}, possibly using
   \envvar{PYTHONPATH}.

:mod:`timing`
   --- Measure time intervals to high resolution (use :func:`time.clock`
   instead).  Removed in Python 3.x.


SGI-specific Extension modules
==============================

The following are SGI specific, and may be out of touch with the current version
of reality.

:mod:`cl`
   --- Interface to the SGI compression library.

:mod:`sv`
   --- Interface to the "simple video" board on SGI Indigo (obsolete hardware).
   Removed in Python 3.x.
PK
%�\��hh)html/_sources/library/unicodedata.rst.txtnu�[���
:mod:`unicodedata` --- Unicode Database
=======================================

.. module:: unicodedata
   :synopsis: Access the Unicode Database.
.. moduleauthor:: Marc-Andre Lemburg <mal@lemburg.com>
.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. index::
   single: Unicode
   single: character
   pair: Unicode; database

This module provides access to the Unicode Character Database which defines
character properties for all Unicode characters. The data in this database is
based on the :file:`UnicodeData.txt` file version 5.2.0 which is publicly
available from ftp://ftp.unicode.org/.

The module uses the same names and symbols as defined by the UnicodeData File
Format 5.2.0 (see http://www.unicode.org/reports/tr44/tr44-4.html).
It defines the following functions:


.. function:: lookup(name)

   Look up character by name.  If a character with the given name is found, return
   the corresponding Unicode character.  If not found, :exc:`KeyError` is raised.


.. function:: name(unichr[, default])

   Returns the name assigned to the Unicode character *unichr* as a string. If no
   name is defined, *default* is returned, or, if not given, :exc:`ValueError` is
   raised.


.. function:: decimal(unichr[, default])

   Returns the decimal value assigned to the Unicode character *unichr* as integer.
   If no such value is defined, *default* is returned, or, if not given,
   :exc:`ValueError` is raised.


.. function:: digit(unichr[, default])

   Returns the digit value assigned to the Unicode character *unichr* as integer.
   If no such value is defined, *default* is returned, or, if not given,
   :exc:`ValueError` is raised.


.. function:: numeric(unichr[, default])

   Returns the numeric value assigned to the Unicode character *unichr* as float.
   If no such value is defined, *default* is returned, or, if not given,
   :exc:`ValueError` is raised.


.. function:: category(unichr)

   Returns the general category assigned to the Unicode character *unichr* as
   string.


.. function:: bidirectional(unichr)

   Returns the bidirectional class assigned to the Unicode character *unichr* as
   string. If no such value is defined, an empty string is returned.


.. function:: combining(unichr)

   Returns the canonical combining class assigned to the Unicode character *unichr*
   as integer. Returns ``0`` if no combining class is defined.


.. function:: east_asian_width(unichr)

   Returns the east asian width assigned to the Unicode character *unichr* as
   string.

   .. versionadded:: 2.4


.. function:: mirrored(unichr)

   Returns the mirrored property assigned to the Unicode character *unichr* as
   integer. Returns ``1`` if the character has been identified as a "mirrored"
   character in bidirectional text, ``0`` otherwise.


.. function:: decomposition(unichr)

   Returns the character decomposition mapping assigned to the Unicode character
   *unichr* as string. An empty string is returned in case no such mapping is
   defined.


.. function:: normalize(form, unistr)

   Return the normal form *form* for the Unicode string *unistr*. Valid values for
   *form* are 'NFC', 'NFKC', 'NFD', and 'NFKD'.

   The Unicode standard defines various normalization forms of a Unicode string,
   based on the definition of canonical equivalence and compatibility equivalence.
   In Unicode, several characters can be expressed in various way. For example, the
   character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as
   the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).

   For each character, there are two normal forms: normal form C and normal form D.
   Normal form D (NFD) is also known as canonical decomposition, and translates
   each character into its decomposed form. Normal form C (NFC) first applies a
   canonical decomposition, then composes pre-combined characters again.

   In addition to these two forms, there are two additional normal forms based on
   compatibility equivalence. In Unicode, certain characters are supported which
   normally would be unified with other characters. For example, U+2160 (ROMAN
   NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I).
   However, it is supported in Unicode for compatibility with existing character
   sets (e.g. gb2312).

   The normal form KD (NFKD) will apply the compatibility decomposition, i.e.
   replace all compatibility characters with their equivalents. The normal form KC
   (NFKC) first applies the compatibility decomposition, followed by the canonical
   composition.

   Even if two unicode strings are normalized and look the same to
   a human reader, if one has combining characters and the other
   doesn't, they may not compare equal.

   .. versionadded:: 2.3

In addition, the module exposes the following constant:


.. data:: unidata_version

   The version of the Unicode database used in this module.

   .. versionadded:: 2.3


.. data:: ucd_3_2_0

   This is an object that has the same methods as the entire module, but uses the
   Unicode database version 3.2 instead, for applications that require this
   specific version of the Unicode database (such as IDNA).

   .. versionadded:: 2.5

Examples:

   >>> import unicodedata
   >>> unicodedata.lookup('LEFT CURLY BRACKET')
   u'{'
   >>> unicodedata.name(u'/')
   'SOLIDUS'
   >>> unicodedata.decimal(u'9')
   9
   >>> unicodedata.decimal(u'a')
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: not a decimal
   >>> unicodedata.category(u'A')  # 'L'etter, 'u'ppercase
   'Lu'
   >>> unicodedata.bidirectional(u'\u0660') # 'A'rabic, 'N'umber
   'AN'

PK
%�\����DD&html/_sources/library/unittest.rst.txtnu�[���:mod:`unittest` --- Unit testing framework
==========================================

.. module:: unittest
   :synopsis: Unit testing framework for Python.
.. moduleauthor:: Steve Purcell <stephen_purcell@yahoo.com>
.. sectionauthor:: Steve Purcell <stephen_purcell@yahoo.com>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Raymond Hettinger <python@rcn.com>

.. versionadded:: 2.1

(If you are already familiar with the basic concepts of testing, you might want
to skip to :ref:`the list of assert methods <assert-methods>`.)

The Python unit testing framework, sometimes referred to as "PyUnit," is a
Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
turn, a Java version of Kent's Smalltalk testing framework.  Each is the de
facto standard unit testing framework for its respective language.

:mod:`unittest` supports test automation, sharing of setup and shutdown code for
tests, aggregation of tests into collections, and independence of the tests from
the reporting framework.  The :mod:`unittest` module provides classes that make
it easy to support these qualities for a set of tests.

To achieve this, :mod:`unittest` supports some important concepts:

test fixture
   A :dfn:`test fixture` represents the preparation needed to perform one or more
   tests, and any associate cleanup actions.  This may involve, for example,
   creating temporary or proxy databases, directories, or starting a server
   process.

test case
   A :dfn:`test case` is the smallest unit of testing.  It checks for a specific
   response to a particular set of inputs.  :mod:`unittest` provides a base class,
   :class:`TestCase`, which may be used to create new test cases.

test suite
   A :dfn:`test suite` is a collection of test cases, test suites, or both.  It is
   used to aggregate tests that should be executed together.

test runner
   A :dfn:`test runner` is a component which orchestrates the execution of tests
   and provides the outcome to the user.  The runner may use a graphical interface,
   a textual interface, or return a special value to indicate the results of
   executing the tests.

The test case and test fixture concepts are supported through the
:class:`TestCase` and :class:`FunctionTestCase` classes; the former should be
used when creating new tests, and the latter can be used when integrating
existing test code with a :mod:`unittest`\ -driven framework. When building test
fixtures using :class:`TestCase`, the :meth:`~TestCase.setUp` and
:meth:`~TestCase.tearDown` methods can be overridden to provide initialization
and cleanup for the fixture.  With :class:`FunctionTestCase`, existing functions
can be passed to the constructor for these purposes.  When the test is run, the
fixture initialization is run first; if it succeeds, the cleanup method is run
after the test has been executed, regardless of the outcome of the test.  Each
instance of the :class:`TestCase` will only be used to run a single test method,
so a new fixture is created for each test.

Test suites are implemented by the :class:`TestSuite` class.  This class allows
individual tests and test suites to be aggregated; when the suite is executed,
all tests added directly to the suite and in "child" test suites are run.

A test runner is an object that provides a single method,
:meth:`~TestRunner.run`, which accepts a :class:`TestCase` or :class:`TestSuite`
object as a parameter, and returns a result object.  The class
:class:`TestResult` is provided for use as the result object. :mod:`unittest`
provides the :class:`TextTestRunner` as an example test runner which reports
test results on the standard error stream by default.  Alternate runners can be
implemented for other environments (such as graphical environments) without any
need to derive from a specific class.


.. seealso::

   Module :mod:`doctest`
      Another test-support module with a very different flavor.

   `unittest2: A backport of new unittest features for Python 2.4-2.6 <https://pypi.org/project/unittest2>`_
      Many new features were added to unittest in Python 2.7, including test
      discovery. unittest2 allows you to use these features with earlier
      versions of Python.

   `Simple Smalltalk Testing: With Patterns <https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm>`_
      Kent Beck's original paper on testing frameworks using the pattern shared
      by :mod:`unittest`.

   `Nose <https://nose.readthedocs.io/>`_ and `pytest <https://docs.pytest.org/>`_
      Third-party unittest frameworks with a lighter-weight syntax for writing
      tests.  For example, ``assert func(10) == 42``.

   `The Python Testing Tools Taxonomy <https://wiki.python.org/moin/PythonTestingToolsTaxonomy>`_
      An extensive list of Python testing tools including functional testing
      frameworks and mock object libraries.

   `Testing in Python Mailing List <http://lists.idyll.org/listinfo/testing-in-python>`_
      A special-interest-group for discussion of testing, and testing tools,
      in Python.


.. _unittest-minimal-example:

Basic example
-------------

The :mod:`unittest` module provides a rich set of tools for constructing and
running tests.  This section demonstrates that a small subset of the tools
suffice to meet the needs of most users.

Here is a short script to test three string methods::

  import unittest

  class TestStringMethods(unittest.TestCase):

      def test_upper(self):
          self.assertEqual('foo'.upper(), 'FOO')

      def test_isupper(self):
          self.assertTrue('FOO'.isupper())
          self.assertFalse('Foo'.isupper())

      def test_split(self):
          s = 'hello world'
          self.assertEqual(s.split(), ['hello', 'world'])
          # check that s.split fails when the separator is not a string
          with self.assertRaises(TypeError):
              s.split(2)

  if __name__ == '__main__':
      unittest.main()


A testcase is created by subclassing :class:`unittest.TestCase`.  The three
individual tests are defined with methods whose names start with the letters
``test``.  This naming convention informs the test runner about which methods
represent tests.

The crux of each test is a call to :meth:`~TestCase.assertEqual` to check for an
expected result; :meth:`~TestCase.assertTrue` or :meth:`~TestCase.assertFalse`
to verify a condition; or :meth:`~TestCase.assertRaises` to verify that a
specific exception gets raised.  These methods are used instead of the
:keyword:`assert` statement so the test runner can accumulate all test results
and produce a report.

The :meth:`~TestCase.setUp` and :meth:`~TestCase.tearDown` methods allow you
to define instructions that will be executed before and after each test method.
They are covered in more detail in the section :ref:`organizing-tests`.

The final block shows a simple way to run the tests. :func:`unittest.main`
provides a command-line interface to the test script.  When run from the command
line, the above script produces an output that looks like this::

   ...
   ----------------------------------------------------------------------
   Ran 3 tests in 0.000s

   OK

Instead of :func:`unittest.main`, there are other ways to run the tests with a
finer level of control, less terse output, and no requirement to be run from the
command line.  For example, the last two lines may be replaced with::

   suite = unittest.TestLoader().loadTestsFromTestCase(TestStringMethods)
   unittest.TextTestRunner(verbosity=2).run(suite)

Running the revised script from the interpreter or another script produces the
following output::

   test_isupper (__main__.TestStringMethods) ... ok
   test_split (__main__.TestStringMethods) ... ok
   test_upper (__main__.TestStringMethods) ... ok

   ----------------------------------------------------------------------
   Ran 3 tests in 0.001s

   OK

The above examples show the most commonly used :mod:`unittest` features which
are sufficient to meet many everyday testing needs.  The remainder of the
documentation explores the full feature set from first principles.


.. _unittest-command-line-interface:

Command-Line Interface
----------------------

The unittest module can be used from the command line to run tests from
modules, classes or even individual test methods::

   python -m unittest test_module1 test_module2
   python -m unittest test_module.TestClass
   python -m unittest test_module.TestClass.test_method

You can pass in a list with any combination of module names, and fully
qualified class or method names.

You can run tests with more detail (higher verbosity) by passing in the -v flag::

   python -m unittest -v test_module

For a list of all the command-line options::

   python -m unittest -h

..  versionchanged:: 2.7
   In earlier versions it was only possible to run individual test methods and
   not modules or classes.


Command-line options
~~~~~~~~~~~~~~~~~~~~

:program:`unittest` supports these command-line options:

.. program:: unittest

.. cmdoption:: -b, --buffer

   The standard output and standard error streams are buffered during the test
   run. Output during a passing test is discarded. Output is echoed normally
   on test fail or error and is added to the failure messages.

.. cmdoption:: -c, --catch

   :kbd:`Control-C` during the test run waits for the current test to end and then
   reports all the results so far. A second :kbd:`Control-C` raises the normal
   :exc:`KeyboardInterrupt` exception.

   See `Signal Handling`_ for the functions that provide this functionality.

.. cmdoption:: -f, --failfast

   Stop the test run on the first error or failure.

.. versionadded:: 2.7
   The command-line options ``-b``, ``-c`` and ``-f`` were added.

The command line can also be used for test discovery, for running all of the
tests in a project or just a subset.


.. _unittest-test-discovery:

Test Discovery
--------------

.. versionadded:: 2.7

Unittest supports simple test discovery. In order to be compatible with test
discovery, all of the test files must be :ref:`modules <tut-modules>` or
:ref:`packages <tut-packages>` importable from the top-level directory of
the project (this means that their filenames must be valid
:ref:`identifiers <identifiers>`).

Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
used from the command line. The basic command-line usage is::

   cd project_directory
   python -m unittest discover

The ``discover`` sub-command has the following options:

.. program:: unittest discover

.. cmdoption:: -v, --verbose

   Verbose output

.. cmdoption:: -s, --start-directory directory

   Directory to start discovery (``.`` default)

.. cmdoption:: -p, --pattern pattern

   Pattern to match test files (``test*.py`` default)

.. cmdoption:: -t, --top-level-directory directory

   Top level directory of project (defaults to start directory)

The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
as positional arguments in that order. The following two command lines
are equivalent::

   python -m unittest discover -s project_directory -p "*_test.py"
   python -m unittest discover project_directory "*_test.py"

As well as being a path it is possible to pass a package name, for example
``myproject.subpackage.test``, as the start directory. The package name you
supply will then be imported and its location on the filesystem will be used
as the start directory.

.. caution::

    Test discovery loads tests by importing them. Once test discovery has
    found all the test files from the start directory you specify it turns the
    paths into package names to import. For example :file:`foo/bar/baz.py` will be
    imported as ``foo.bar.baz``.

    If you have a package installed globally and attempt test discovery on
    a different copy of the package then the import *could* happen from the
    wrong place. If this happens test discovery will warn you and exit.

    If you supply the start directory as a package name rather than a
    path to a directory then discover assumes that whichever location it
    imports from is the location you intended, so you will not get the
    warning.

Test modules and packages can customize test loading and discovery by through
the `load_tests protocol`_.


.. _organizing-tests:

Organizing test code
--------------------

The basic building blocks of unit testing are :dfn:`test cases` --- single
scenarios that must be set up and checked for correctness.  In :mod:`unittest`,
test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
class. To make your own test cases you must write subclasses of
:class:`TestCase`, or use :class:`FunctionTestCase`.

An instance of a :class:`TestCase`\ -derived class is an object that can
completely run a single test method, together with optional set-up and tidy-up
code.

The testing code of a :class:`TestCase` instance should be entirely self
contained, such that it can be run either in isolation or in arbitrary
combination with any number of other test cases.

The simplest :class:`TestCase` subclass will simply override the
:meth:`~TestCase.runTest` method in order to perform specific testing code::

   import unittest

   class DefaultWidgetSizeTestCase(unittest.TestCase):
       def runTest(self):
           widget = Widget('The widget')
           self.assertEqual(widget.size(), (50, 50), 'incorrect default size')

Note that in order to test something, we use one of the :meth:`assert\*`
methods provided by the :class:`TestCase` base class.  If the test fails, an
exception will be raised, and :mod:`unittest` will identify the test case as a
:dfn:`failure`.  Any other exceptions will be treated as :dfn:`errors`. This
helps you identify where the problem is: :dfn:`failures` are caused by incorrect
results - a 5 where you expected a 6. :dfn:`Errors` are caused by incorrect
code - e.g., a :exc:`TypeError` caused by an incorrect function call.

The way to run a test case will be described later.  For now, note that to
construct an instance of such a test case, we call its constructor without
arguments::

   testCase = DefaultWidgetSizeTestCase()

Now, such test cases can be numerous, and their set-up can be repetitive.  In
the above case, constructing a :class:`Widget` in each of 100 Widget test case
subclasses would mean unsightly duplication.

Luckily, we can factor out such set-up code by implementing a method called
:meth:`~TestCase.setUp`, which the testing framework will automatically call for
us when we run the test::

   import unittest

   class SimpleWidgetTestCase(unittest.TestCase):
       def setUp(self):
           self.widget = Widget('The widget')

   class DefaultWidgetSizeTestCase(SimpleWidgetTestCase):
       def runTest(self):
           self.assertEqual(self.widget.size(), (50,50),
                            'incorrect default size')

   class WidgetResizeTestCase(SimpleWidgetTestCase):
       def runTest(self):
           self.widget.resize(100,150)
           self.assertEqual(self.widget.size(), (100,150),
                            'wrong size after resize')

If the :meth:`~TestCase.setUp` method raises an exception while the test is
running, the framework will consider the test to have suffered an error, and the
:meth:`~TestCase.runTest` method will not be executed.

Similarly, we can provide a :meth:`~TestCase.tearDown` method that tidies up
after the :meth:`~TestCase.runTest` method has been run::

   import unittest

   class SimpleWidgetTestCase(unittest.TestCase):
       def setUp(self):
           self.widget = Widget('The widget')

       def tearDown(self):
           self.widget.dispose()
           self.widget = None

If :meth:`~TestCase.setUp` succeeded, the :meth:`~TestCase.tearDown` method will
be run whether :meth:`~TestCase.runTest` succeeded or not.

Such a working environment for the testing code is called a :dfn:`fixture`.

Often, many small test cases will use the same fixture.  In this case, we would
end up subclassing :class:`SimpleWidgetTestCase` into many small one-method
classes such as :class:`DefaultWidgetSizeTestCase`.  This is time-consuming and
discouraging, so in the same vein as JUnit, :mod:`unittest` provides a simpler
mechanism::

   import unittest

   class WidgetTestCase(unittest.TestCase):
       def setUp(self):
           self.widget = Widget('The widget')

       def tearDown(self):
           self.widget.dispose()
           self.widget = None

       def test_default_size(self):
           self.assertEqual(self.widget.size(), (50,50),
                            'incorrect default size')

       def test_resize(self):
           self.widget.resize(100,150)
           self.assertEqual(self.widget.size(), (100,150),
                            'wrong size after resize')

Here we have not provided a :meth:`~TestCase.runTest` method, but have instead
provided two different test methods.  Class instances will now each run one of
the :meth:`test_\*` methods, with ``self.widget`` created and destroyed
separately for each instance.  When creating an instance we must specify the
test method it is to run.  We do this by passing the method name in the
constructor::

   defaultSizeTestCase = WidgetTestCase('test_default_size')
   resizeTestCase = WidgetTestCase('test_resize')

Test case instances are grouped together according to the features they test.
:mod:`unittest` provides a mechanism for this: the :dfn:`test suite`,
represented by :mod:`unittest`'s :class:`TestSuite` class::

   widgetTestSuite = unittest.TestSuite()
   widgetTestSuite.addTest(WidgetTestCase('test_default_size'))
   widgetTestSuite.addTest(WidgetTestCase('test_resize'))

For the ease of running tests, as we will see later, it is a good idea to
provide in each test module a callable object that returns a pre-built test
suite::

   def suite():
       suite = unittest.TestSuite()
       suite.addTest(WidgetTestCase('test_default_size'))
       suite.addTest(WidgetTestCase('test_resize'))
       return suite

or even::

   def suite():
       tests = ['test_default_size', 'test_resize']

       return unittest.TestSuite(map(WidgetTestCase, tests))

Since it is a common pattern to create a :class:`TestCase` subclass with many
similarly named test functions, :mod:`unittest` provides a :class:`TestLoader`
class that can be used to automate the process of creating a test suite and
populating it with individual tests. For example, ::

   suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)

will create a test suite that will run ``WidgetTestCase.test_default_size()`` and
``WidgetTestCase.test_resize``. :class:`TestLoader` uses the ``'test'`` method
name prefix to identify test methods automatically.

Note that the order in which the various test cases will be run is
determined by sorting the test function names with respect to the
built-in ordering for strings.

Often it is desirable to group suites of test cases together, so as to run tests
for the whole system at once.  This is easy, since :class:`TestSuite` instances
can be added to a :class:`TestSuite` just as :class:`TestCase` instances can be
added to a :class:`TestSuite`::

   suite1 = module1.TheTestSuite()
   suite2 = module2.TheTestSuite()
   alltests = unittest.TestSuite([suite1, suite2])

You can place the definitions of test cases and test suites in the same modules
as the code they are to test (such as :file:`widget.py`), but there are several
advantages to placing the test code in a separate module, such as
:file:`test_widget.py`:

* The test module can be run standalone from the command line.

* The test code can more easily be separated from shipped code.

* There is less temptation to change test code to fit the code it tests without
  a good reason.

* Test code should be modified much less frequently than the code it tests.

* Tested code can be refactored more easily.

* Tests for modules written in C must be in separate modules anyway, so why not
  be consistent?

* If the testing strategy changes, there is no need to change the source code.


.. _legacy-unit-tests:

Re-using old test code
----------------------

Some users will find that they have existing test code that they would like to
run from :mod:`unittest`, without converting every old test function to a
:class:`TestCase` subclass.

For this reason, :mod:`unittest` provides a :class:`FunctionTestCase` class.
This subclass of :class:`TestCase` can be used to wrap an existing test
function.  Set-up and tear-down functions can also be provided.

Given the following test function::

   def testSomething():
       something = makeSomething()
       assert something.name is not None
       # ...

one can create an equivalent test case instance as follows::

   testcase = unittest.FunctionTestCase(testSomething)

If there are additional set-up and tear-down methods that should be called as
part of the test case's operation, they can also be provided like so::

   testcase = unittest.FunctionTestCase(testSomething,
                                        setUp=makeSomethingDB,
                                        tearDown=deleteSomethingDB)

To make migrating existing test suites easier, :mod:`unittest` supports tests
raising :exc:`AssertionError` to indicate test failure. However, it is
recommended that you use the explicit :meth:`TestCase.fail\*` and
:meth:`TestCase.assert\*` methods instead, as future versions of :mod:`unittest`
may treat :exc:`AssertionError` differently.

.. note::

   Even though :class:`FunctionTestCase` can be used to quickly convert an
   existing test base over to a :mod:`unittest`\ -based system, this approach is
   not recommended.  Taking the time to set up proper :class:`TestCase`
   subclasses will make future test refactorings infinitely easier.

In some cases, the existing tests may have been written using the :mod:`doctest`
module.  If so, :mod:`doctest` provides a :class:`DocTestSuite` class that can
automatically build :class:`unittest.TestSuite` instances from the existing
:mod:`doctest`\ -based tests.


.. _unittest-skipping:

Skipping tests and expected failures
------------------------------------

.. versionadded:: 2.7

Unittest supports skipping individual test methods and even whole classes of
tests.  In addition, it supports marking a test as an "expected failure," a test
that is broken and will fail, but shouldn't be counted as a failure on a
:class:`TestResult`.

Skipping a test is simply a matter of using the :func:`skip` :term:`decorator`
or one of its conditional variants.

Basic skipping looks like this::

   class MyTestCase(unittest.TestCase):

       @unittest.skip("demonstrating skipping")
       def test_nothing(self):
           self.fail("shouldn't happen")

       @unittest.skipIf(mylib.__version__ < (1, 3),
                        "not supported in this library version")
       def test_format(self):
           # Tests that work for only a certain version of the library.
           pass

       @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
       def test_windows_support(self):
           # windows specific testing code
           pass

This is the output of running the example above in verbose mode::

   test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
   test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
   test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'

   ----------------------------------------------------------------------
   Ran 3 tests in 0.005s

   OK (skipped=3)

Classes can be skipped just like methods::

   @unittest.skip("showing class skipping")
   class MySkippedTestCase(unittest.TestCase):
       def test_not_run(self):
           pass

:meth:`TestCase.setUp` can also skip the test.  This is useful when a resource
that needs to be set up is not available.

Expected failures use the :func:`expectedFailure` decorator. ::

   class ExpectedFailureTestCase(unittest.TestCase):
       @unittest.expectedFailure
       def test_fail(self):
           self.assertEqual(1, 0, "broken")

It's easy to roll your own skipping decorators by making a decorator that calls
:func:`skip` on the test when it wants it to be skipped.  This decorator skips
the test unless the passed object has a certain attribute::

   def skipUnlessHasattr(obj, attr):
       if hasattr(obj, attr):
           return lambda func: func
       return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

The following decorators implement test skipping and expected failures:

.. function:: skip(reason)

   Unconditionally skip the decorated test.  *reason* should describe why the
   test is being skipped.

.. function:: skipIf(condition, reason)

   Skip the decorated test if *condition* is true.

.. function:: skipUnless(condition, reason)

   Skip the decorated test unless *condition* is true.

.. function:: expectedFailure

   Mark the test as an expected failure.  If the test fails when run, the test
   is not counted as a failure.

.. exception:: SkipTest(reason)

   This exception is raised to skip a test.

   Usually you can use :meth:`TestCase.skipTest` or one of the skipping
   decorators instead of raising this directly.

Skipped tests will not have :meth:`setUp` or :meth:`tearDown` run around them.
Skipped classes will not have :meth:`setUpClass` or :meth:`tearDownClass` run.


.. _unittest-contents:

Classes and functions
---------------------

This section describes in depth the API of :mod:`unittest`.


.. _testcase-objects:

Test cases
~~~~~~~~~~

.. class:: TestCase(methodName='runTest')

   Instances of the :class:`TestCase` class represent the smallest testable units
   in the :mod:`unittest` universe.  This class is intended to be used as a base
   class, with specific tests being implemented by concrete subclasses.  This class
   implements the interface needed by the test runner to allow it to drive the
   test, and methods that the test code can use to check for and report various
   kinds of failure.

   Each instance of :class:`TestCase` will run a single test method: the method
   named *methodName*.  If you remember, we had an earlier example that went
   something like this::

      def suite():
          suite = unittest.TestSuite()
          suite.addTest(WidgetTestCase('test_default_size'))
          suite.addTest(WidgetTestCase('test_resize'))
          return suite

   Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
   single test.

   *methodName* defaults to :meth:`runTest`.

   :class:`TestCase` instances provide three groups of methods: one group used
   to run the test, another used by the test implementation to check conditions
   and report failures, and some inquiry methods allowing information about the
   test itself to be gathered.

   Methods in the first group (running the test) are:


   .. method:: setUp()

      Method called to prepare the test fixture.  This is called immediately
      before calling the test method; other than :exc:`AssertionError` or :exc:`SkipTest`,
      any exception raised by this method will be considered an error rather than
      a test failure. The default implementation does nothing.


   .. method:: tearDown()

      Method called immediately after the test method has been called and the
      result recorded.  This is called even if the test method raised an
      exception, so the implementation in subclasses may need to be particularly
      careful about checking internal state.  Any exception, other than
      :exc:`AssertionError` or :exc:`SkipTest`, raised by this method will be
      considered an additional error rather than a test failure (thus increasing
      the total number of reported errors). This method will only be called if
      the :meth:`setUp` succeeds, regardless of the outcome of the test method.
      The default implementation does nothing.


   .. method:: setUpClass()

      A class method called before tests in an individual class are run.
      ``setUpClass`` is called with the class as the only argument
      and must be decorated as a :func:`classmethod`::

        @classmethod
        def setUpClass(cls):
            ...

      See `Class and Module Fixtures`_ for more details.

      .. versionadded:: 2.7


   .. method:: tearDownClass()

      A class method called after tests in an individual class have run.
      ``tearDownClass`` is called with the class as the only argument
      and must be decorated as a :meth:`classmethod`::

        @classmethod
        def tearDownClass(cls):
            ...

      See `Class and Module Fixtures`_ for more details.

      .. versionadded:: 2.7


   .. method:: run(result=None)

      Run the test, collecting the result into the test result object passed as
      *result*.  If *result* is omitted or ``None``, a temporary result
      object is created (by calling the :meth:`defaultTestResult` method) and
      used. The result object is not returned to :meth:`run`'s caller.

      The same effect may be had by simply calling the :class:`TestCase`
      instance.


   .. method:: skipTest(reason)

      Calling this during a test method or :meth:`setUp` skips the current
      test.  See :ref:`unittest-skipping` for more information.

      .. versionadded:: 2.7


   .. method:: debug()

      Run the test without collecting the result.  This allows exceptions raised
      by the test to be propagated to the caller, and can be used to support
      running tests under a debugger.

   .. _assert-methods:

   The :class:`TestCase` class provides several assert methods to check for and
   report failures.  The following table lists the most commonly used methods
   (see the tables below for more assert methods):

   +-----------------------------------------+-----------------------------+---------------+
   | Method                                  | Checks that                 | New in        |
   +=========================================+=============================+===============+
   | :meth:`assertEqual(a, b)                | ``a == b``                  |               |
   | <TestCase.assertEqual>`                 |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertNotEqual(a, b)             | ``a != b``                  |               |
   | <TestCase.assertNotEqual>`              |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertTrue(x)                    | ``bool(x) is True``         |               |
   | <TestCase.assertTrue>`                  |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertFalse(x)                   | ``bool(x) is False``        |               |
   | <TestCase.assertFalse>`                 |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIs(a, b)                   | ``a is b``                  | 2.7           |
   | <TestCase.assertIs>`                    |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIsNot(a, b)                | ``a is not b``              | 2.7           |
   | <TestCase.assertIsNot>`                 |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIsNone(x)                  | ``x is None``               | 2.7           |
   | <TestCase.assertIsNone>`                |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIsNotNone(x)               | ``x is not None``           | 2.7           |
   | <TestCase.assertIsNotNone>`             |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIn(a, b)                   | ``a in b``                  | 2.7           |
   | <TestCase.assertIn>`                    |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertNotIn(a, b)                | ``a not in b``              | 2.7           |
   | <TestCase.assertNotIn>`                 |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertIsInstance(a, b)           | ``isinstance(a, b)``        | 2.7           |
   | <TestCase.assertIsInstance>`            |                             |               |
   +-----------------------------------------+-----------------------------+---------------+
   | :meth:`assertNotIsInstance(a, b)        | ``not isinstance(a, b)``    | 2.7           |
   | <TestCase.assertNotIsInstance>`         |                             |               |
   +-----------------------------------------+-----------------------------+---------------+

   All the assert methods (except :meth:`assertRaises`,
   :meth:`assertRaisesRegexp`)
   accept a *msg* argument that, if specified, is used as the error message on
   failure (see also :data:`longMessage`).

   .. method:: assertEqual(first, second, msg=None)

      Test that *first* and *second* are equal.  If the values do not compare
      equal, the test will fail.

      In addition, if *first* and *second* are the exact same type and one of
      list, tuple, dict, set, frozenset or unicode or any type that a subclass
      registers with :meth:`addTypeEqualityFunc` the type-specific equality
      function will be called in order to generate a more useful default
      error message (see also the :ref:`list of type-specific methods
      <type-specific-methods>`).

      .. versionchanged:: 2.7
         Added the automatic calling of type-specific equality function.


   .. method:: assertNotEqual(first, second, msg=None)

      Test that *first* and *second* are not equal.  If the values do compare
      equal, the test will fail.

   .. method:: assertTrue(expr, msg=None)
               assertFalse(expr, msg=None)

      Test that *expr* is true (or false).

      Note that this is equivalent to ``bool(expr) is True`` and not to ``expr
      is True`` (use ``assertIs(expr, True)`` for the latter).  This method
      should also be avoided when more specific methods are available (e.g.
      ``assertEqual(a, b)`` instead of ``assertTrue(a == b)``), because they
      provide a better error message in case of failure.


   .. method:: assertIs(first, second, msg=None)
               assertIsNot(first, second, msg=None)

      Test that *first* and *second* evaluate (or don't evaluate) to the same object.

      .. versionadded:: 2.7


   .. method:: assertIsNone(expr, msg=None)
               assertIsNotNone(expr, msg=None)

      Test that *expr* is (or is not) ``None``.

      .. versionadded:: 2.7


   .. method:: assertIn(first, second, msg=None)
               assertNotIn(first, second, msg=None)

      Test that *first* is (or is not) in *second*.

      .. versionadded:: 2.7


   .. method:: assertIsInstance(obj, cls, msg=None)
               assertNotIsInstance(obj, cls, msg=None)

      Test that *obj* is (or is not) an instance of *cls* (which can be a
      class or a tuple of classes, as supported by :func:`isinstance`).
      To check for the exact type, use :func:`assertIs(type(obj), cls) <assertIs>`.

      .. versionadded:: 2.7


   It is also possible to check that exceptions and warnings are raised using
   the following methods:

   +---------------------------------------------------------+--------------------------------------+------------+
   | Method                                                  | Checks that                          | New in     |
   +=========================================================+======================================+============+
   | :meth:`assertRaises(exc, fun, *args, **kwds)            | ``fun(*args, **kwds)`` raises *exc*  |            |
   | <TestCase.assertRaises>`                                |                                      |            |
   +---------------------------------------------------------+--------------------------------------+------------+
   | :meth:`assertRaisesRegexp(exc, r, fun, *args, **kwds)   | ``fun(*args, **kwds)`` raises *exc*  | 2.7        |
   | <TestCase.assertRaisesRegexp>`                          | and the message matches regex *r*    |            |
   +---------------------------------------------------------+--------------------------------------+------------+

   .. method:: assertRaises(exception, callable, *args, **kwds)
               assertRaises(exception)

      Test that an exception is raised when *callable* is called with any
      positional or keyword arguments that are also passed to
      :meth:`assertRaises`.  The test passes if *exception* is raised, is an
      error if another exception is raised, or fails if no exception is raised.
      To catch any of a group of exceptions, a tuple containing the exception
      classes may be passed as *exception*.

      If only the *exception* argument is given, returns a context manager so
      that the code under test can be written inline rather than as a function::

         with self.assertRaises(SomeException):
             do_something()

      The context manager will store the caught exception object in its
      :attr:`exception` attribute.  This can be useful if the intention
      is to perform additional checks on the exception raised::

        with self.assertRaises(SomeException) as cm:
            do_something()

        the_exception = cm.exception
        self.assertEqual(the_exception.error_code, 3)

      .. versionchanged:: 2.7
         Added the ability to use :meth:`assertRaises` as a context manager.


   .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
               assertRaisesRegexp(exception, regexp)

      Like :meth:`assertRaises` but also tests that *regexp* matches
      on the string representation of the raised exception.  *regexp* may be
      a regular expression object or a string containing a regular expression
      suitable for use by :func:`re.search`.  Examples::

         self.assertRaisesRegexp(ValueError, "invalid literal for.*XYZ'$",
                                 int, 'XYZ')

      or::

         with self.assertRaisesRegexp(ValueError, 'literal'):
            int('XYZ')

      .. versionadded:: 2.7



   There are also other methods used to perform more specific checks, such as:

   +---------------------------------------+--------------------------------+--------------+
   | Method                                | Checks that                    | New in       |
   +=======================================+================================+==============+
   | :meth:`assertAlmostEqual(a, b)        | ``round(a-b, 7) == 0``         |              |
   | <TestCase.assertAlmostEqual>`         |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertNotAlmostEqual(a, b)     | ``round(a-b, 7) != 0``         |              |
   | <TestCase.assertNotAlmostEqual>`      |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertGreater(a, b)            | ``a > b``                      | 2.7          |
   | <TestCase.assertGreater>`             |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertGreaterEqual(a, b)       | ``a >= b``                     | 2.7          |
   | <TestCase.assertGreaterEqual>`        |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertLess(a, b)               | ``a < b``                      | 2.7          |
   | <TestCase.assertLess>`                |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertLessEqual(a, b)          | ``a <= b``                     | 2.7          |
   | <TestCase.assertLessEqual>`           |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertRegexpMatches(s, r)      | ``r.search(s)``                | 2.7          |
   | <TestCase.assertRegexpMatches>`       |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertNotRegexpMatches(s, r)   | ``not r.search(s)``            | 2.7          |
   | <TestCase.assertNotRegexpMatches>`    |                                |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertItemsEqual(a, b)         | sorted(a) == sorted(b) and     | 2.7          |
   | <TestCase.assertItemsEqual>`          | works with unhashable objs     |              |
   +---------------------------------------+--------------------------------+--------------+
   | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs        | 2.7          |
   | <TestCase.assertDictContainsSubset>`  | in *a* exist in *b*            |              |
   +---------------------------------------+--------------------------------+--------------+


   .. method:: assertAlmostEqual(first, second, places=7, msg=None, delta=None)
               assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)

      Test that *first* and *second* are approximately (or not approximately)
      equal by computing the difference, rounding to the given number of
      decimal *places* (default 7), and comparing to zero.  Note that these
      methods round the values to the given number of *decimal places* (i.e.
      like the :func:`round` function) and not *significant digits*.

      If *delta* is supplied instead of *places* then the difference
      between *first* and *second* must be less or equal to (or greater than) *delta*.

      Supplying both *delta* and *places* raises a ``TypeError``.

      .. versionchanged:: 2.7
         :meth:`assertAlmostEqual` automatically considers almost equal objects
         that compare equal.  :meth:`assertNotAlmostEqual` automatically fails
         if the objects compare equal.  Added the *delta* keyword argument.



   .. method:: assertGreater(first, second, msg=None)
               assertGreaterEqual(first, second, msg=None)
               assertLess(first, second, msg=None)
               assertLessEqual(first, second, msg=None)

      Test that *first* is respectively >, >=, < or <= than *second* depending
      on the method name.  If not, the test will fail::

         >>> self.assertGreaterEqual(3, 4)
         AssertionError: "3" unexpectedly not greater than or equal to "4"

      .. versionadded:: 2.7


   .. method:: assertRegexpMatches(text, regexp, msg=None)

      Test that a *regexp* search matches *text*.  In case
      of failure, the error message will include the pattern and the *text* (or
      the pattern and the part of *text* that unexpectedly matched).  *regexp*
      may be a regular expression object or a string containing a regular
      expression suitable for use by :func:`re.search`.

      .. versionadded:: 2.7


   .. method:: assertNotRegexpMatches(text, regexp, msg=None)

      Verifies that a *regexp* search does not match *text*.  Fails with an error
      message including the pattern and the part of *text* that matches.  *regexp*
      may be a regular expression object or a string containing a regular
      expression suitable for use by :func:`re.search`.

      .. versionadded:: 2.7


   .. method:: assertItemsEqual(actual, expected, msg=None)

      Test that sequence *expected* contains the same elements as *actual*,
      regardless of their order. When they don't, an error message listing the
      differences between the sequences will be generated.

      Duplicate elements are *not* ignored when comparing *actual* and
      *expected*. It verifies if each element has the same count in both
      sequences. It is the equivalent of ``assertEqual(sorted(expected),
      sorted(actual))`` but it works with sequences of unhashable objects as
      well.

      In Python 3, this method is named ``assertCountEqual``.

      .. versionadded:: 2.7


   .. method:: assertDictContainsSubset(expected, actual, msg=None)

      Tests whether the key/value pairs in dictionary *actual* are a
      superset of those in *expected*.  If not, an error message listing
      the missing keys and mismatched values is generated.

      .. versionadded:: 2.7
      .. deprecated:: 3.2



   .. _type-specific-methods:

   The :meth:`assertEqual` method dispatches the equality check for objects of
   the same type to different type-specific methods.  These methods are already
   implemented for most of the built-in types, but it's also possible to
   register new methods using :meth:`addTypeEqualityFunc`:

   .. method:: addTypeEqualityFunc(typeobj, function)

      Registers a type-specific method called by :meth:`assertEqual` to check
      if two objects of exactly the same *typeobj* (not subclasses) compare
      equal.  *function* must take two positional arguments and a third msg=None
      keyword argument just as :meth:`assertEqual` does.  It must raise
      :data:`self.failureException(msg) <failureException>` when inequality
      between the first two parameters is detected -- possibly providing useful
      information and explaining the inequalities in details in the error
      message.

      .. versionadded:: 2.7

   The list of type-specific methods automatically used by
   :meth:`~TestCase.assertEqual` are summarized in the following table.  Note
   that it's usually not necessary to invoke these methods directly.

   +-----------------------------------------+-----------------------------+--------------+
   | Method                                  | Used to compare             | New in       |
   +=========================================+=============================+==============+
   | :meth:`assertMultiLineEqual(a, b)       | strings                     | 2.7          |
   | <TestCase.assertMultiLineEqual>`        |                             |              |
   +-----------------------------------------+-----------------------------+--------------+
   | :meth:`assertSequenceEqual(a, b)        | sequences                   | 2.7          |
   | <TestCase.assertSequenceEqual>`         |                             |              |
   +-----------------------------------------+-----------------------------+--------------+
   | :meth:`assertListEqual(a, b)            | lists                       | 2.7          |
   | <TestCase.assertListEqual>`             |                             |              |
   +-----------------------------------------+-----------------------------+--------------+
   | :meth:`assertTupleEqual(a, b)           | tuples                      | 2.7          |
   | <TestCase.assertTupleEqual>`            |                             |              |
   +-----------------------------------------+-----------------------------+--------------+
   | :meth:`assertSetEqual(a, b)             | sets or frozensets          | 2.7          |
   | <TestCase.assertSetEqual>`              |                             |              |
   +-----------------------------------------+-----------------------------+--------------+
   | :meth:`assertDictEqual(a, b)            | dicts                       | 2.7          |
   | <TestCase.assertDictEqual>`             |                             |              |
   +-----------------------------------------+-----------------------------+--------------+



   .. method:: assertMultiLineEqual(first, second, msg=None)

      Test that the multiline string *first* is equal to the string *second*.
      When not equal a diff of the two strings highlighting the differences
      will be included in the error message. This method is used by default
      when comparing Unicode strings with :meth:`assertEqual`.

      .. versionadded:: 2.7


   .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)

      Tests that two sequences are equal.  If a *seq_type* is supplied, both
      *seq1* and *seq2* must be instances of *seq_type* or a failure will
      be raised.  If the sequences are different an error message is
      constructed that shows the difference between the two.

      This method is not called directly by :meth:`assertEqual`, but
      it's used to implement :meth:`assertListEqual` and
      :meth:`assertTupleEqual`.

      .. versionadded:: 2.7


   .. method:: assertListEqual(list1, list2, msg=None)
               assertTupleEqual(tuple1, tuple2, msg=None)

      Tests that two lists or tuples are equal.  If not, an error message is
      constructed that shows only the differences between the two.  An error
      is also raised if either of the parameters are of the wrong type.
      These methods are used by default when comparing lists or tuples with
      :meth:`assertEqual`.

      .. versionadded:: 2.7


   .. method:: assertSetEqual(set1, set2, msg=None)

      Tests that two sets are equal.  If not, an error message is constructed
      that lists the differences between the sets.  This method is used by
      default when comparing sets or frozensets with :meth:`assertEqual`.

      Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
      method.

      .. versionadded:: 2.7


   .. method:: assertDictEqual(expected, actual, msg=None)

      Test that two dictionaries are equal.  If not, an error message is
      constructed that shows the differences in the dictionaries. This
      method will be used by default to compare dictionaries in
      calls to :meth:`assertEqual`.

      .. versionadded:: 2.7



   .. _other-methods-and-attrs:

   Finally the :class:`TestCase` provides the following methods and attributes:


   .. method:: fail(msg=None)

      Signals a test failure unconditionally, with *msg* or ``None`` for
      the error message.


   .. attribute:: failureException

      This class attribute gives the exception raised by the test method.  If a
      test framework needs to use a specialized exception, possibly to carry
      additional information, it must subclass this exception in order to "play
      fair" with the framework.  The initial value of this attribute is
      :exc:`AssertionError`.


   .. attribute:: longMessage

      If set to ``True`` then any explicit failure message you pass in to the
      :ref:`assert methods <assert-methods>` will be appended to the end of the
      normal failure message.  The normal messages contain useful information
      about the objects involved, for example the message from assertEqual
      shows you the repr of the two unequal objects. Setting this attribute
      to ``True`` allows you to have a custom error message in addition to the
      normal one.

      This attribute defaults to ``False``, meaning that a custom message passed
      to an assert method will silence the normal message.

      The class setting can be overridden in individual tests by assigning an
      instance attribute to ``True`` or ``False`` before calling the assert methods.

      .. versionadded:: 2.7


   .. attribute:: maxDiff

      This attribute controls the maximum length of diffs output by assert
      methods that report diffs on failure. It defaults to 80*8 characters.
      Assert methods affected by this attribute are
      :meth:`assertSequenceEqual` (including all the sequence comparison
      methods that delegate to it), :meth:`assertDictEqual` and
      :meth:`assertMultiLineEqual`.

      Setting ``maxDiff`` to ``None`` means that there is no maximum length of
      diffs.

      .. versionadded:: 2.7


   Testing frameworks can use the following methods to collect information on
   the test:


   .. method:: countTestCases()

      Return the number of tests represented by this test object.  For
      :class:`TestCase` instances, this will always be ``1``.


   .. method:: defaultTestResult()

      Return an instance of the test result class that should be used for this
      test case class (if no other result instance is provided to the
      :meth:`run` method).

      For :class:`TestCase` instances, this will always be an instance of
      :class:`TestResult`; subclasses of :class:`TestCase` should override this
      as necessary.


   .. method:: id()

      Return a string identifying the specific test case.  This is usually the
      full name of the test method, including the module and class name.


   .. method:: shortDescription()

      Returns a description of the test, or ``None`` if no description
      has been provided.  The default implementation of this method
      returns the first line of the test method's docstring, if available,
      or :const:`None`.



   .. method:: addCleanup(function, *args, **kwargs)

      Add a function to be called after :meth:`tearDown` to cleanup resources
      used during the test. Functions will be called in reverse order to the
      order they are added (LIFO). They are called with any arguments and
      keyword arguments passed into :meth:`addCleanup` when they are
      added.

      If :meth:`setUp` fails, meaning that :meth:`tearDown` is not called,
      then any cleanup functions added will still be called.

      .. versionadded:: 2.7


   .. method:: doCleanups()

      This method is called unconditionally after :meth:`tearDown`, or
      after :meth:`setUp` if :meth:`setUp` raises an exception.

      It is responsible for calling all the cleanup functions added by
      :meth:`addCleanup`. If you need cleanup functions to be called
      *prior* to :meth:`tearDown` then you can call :meth:`doCleanups`
      yourself.

      :meth:`doCleanups` pops methods off the stack of cleanup
      functions one at a time, so it can be called at any time.

      .. versionadded:: 2.7


.. class:: FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)

   This class implements the portion of the :class:`TestCase` interface which
   allows the test runner to drive the test, but does not provide the methods
   which test code can use to check and report errors.  This is used to create
   test cases using legacy test code, allowing it to be integrated into a
   :mod:`unittest`-based test framework.


Deprecated aliases
##################

For historical reasons, some of the :class:`TestCase` methods had one or more
aliases that are now deprecated.  The following table lists the correct names
along with their deprecated aliases:

   ==============================  ===============================
    Method Name                     Deprecated alias(es)
   ==============================  ===============================
    :meth:`.assertEqual`            failUnlessEqual, assertEquals
    :meth:`.assertNotEqual`         failIfEqual
    :meth:`.assertTrue`             failUnless, assert\_
    :meth:`.assertFalse`            failIf
    :meth:`.assertRaises`           failUnlessRaises
    :meth:`.assertAlmostEqual`      failUnlessAlmostEqual
    :meth:`.assertNotAlmostEqual`   failIfAlmostEqual
   ==============================  ===============================

   .. deprecated:: 2.7
         the aliases listed in the second column



.. _testsuite-objects:

Grouping tests
~~~~~~~~~~~~~~

.. class:: TestSuite(tests=())

   This class represents an aggregation of individual test cases and test suites.
   The class presents the interface needed by the test runner to allow it to be run
   as any other test case.  Running a :class:`TestSuite` instance is the same as
   iterating over the suite, running each test individually.

   If *tests* is given, it must be an iterable of individual test cases or other
   test suites that will be used to build the suite initially. Additional methods
   are provided to add test cases and suites to the collection later on.

   :class:`TestSuite` objects behave much like :class:`TestCase` objects, except
   they do not actually implement a test.  Instead, they are used to aggregate
   tests into groups of tests that should be run together. Some additional
   methods are available to add tests to :class:`TestSuite` instances:


   .. method:: TestSuite.addTest(test)

      Add a :class:`TestCase` or :class:`TestSuite` to the suite.


   .. method:: TestSuite.addTests(tests)

      Add all the tests from an iterable of :class:`TestCase` and :class:`TestSuite`
      instances to this test suite.

      This is equivalent to iterating over *tests*, calling :meth:`addTest` for
      each element.

   :class:`TestSuite` shares the following methods with :class:`TestCase`:


   .. method:: run(result)

      Run the tests associated with this suite, collecting the result into the
      test result object passed as *result*.  Note that unlike
      :meth:`TestCase.run`, :meth:`TestSuite.run` requires the result object to
      be passed in.


   .. method:: debug()

      Run the tests associated with this suite without collecting the
      result. This allows exceptions raised by the test to be propagated to the
      caller and can be used to support running tests under a debugger.


   .. method:: countTestCases()

      Return the number of tests represented by this test object, including all
      individual tests and sub-suites.


   .. method:: __iter__()

      Tests grouped by a :class:`TestSuite` are always accessed by iteration.
      Subclasses can lazily provide tests by overriding :meth:`__iter__`. Note
      that this method maybe called several times on a single suite
      (for example when counting tests or comparing for equality)
      so the tests returned must be the same for repeated iterations.

      .. versionchanged:: 2.7
         In earlier versions the :class:`TestSuite` accessed tests directly rather
         than through iteration, so overriding :meth:`__iter__` wasn't sufficient
         for providing tests.

   In the typical usage of a :class:`TestSuite` object, the :meth:`run` method
   is invoked by a :class:`TestRunner` rather than by the end-user test harness.


Loading and running tests
~~~~~~~~~~~~~~~~~~~~~~~~~

.. class:: TestLoader()

   The :class:`TestLoader` class is used to create test suites from classes and
   modules.  Normally, there is no need to create an instance of this class; the
   :mod:`unittest` module provides an instance that can be shared as
   :data:`unittest.defaultTestLoader`.  Using a subclass or instance, however,
   allows customization of some configurable properties.

   :class:`TestLoader` objects have the following methods:


   .. method:: loadTestsFromTestCase(testCaseClass)

      Return a suite of all test cases contained in the :class:`TestCase`\ -derived
      :class:`testCaseClass`.


   .. method:: loadTestsFromModule(module)

      Return a suite of all test cases contained in the given module. This
      method searches *module* for classes derived from :class:`TestCase` and
      creates an instance of the class for each test method defined for the
      class.

      .. note::

         While using a hierarchy of :class:`TestCase`\ -derived classes can be
         convenient in sharing fixtures and helper functions, defining test
         methods on base classes that are not intended to be instantiated
         directly does not play well with this method.  Doing so, however, can
         be useful when the fixtures are different and defined in subclasses.

      If a module provides a ``load_tests`` function it will be called to
      load the tests. This allows modules to customize test loading.
      This is the `load_tests protocol`_.

      .. versionchanged:: 2.7
         Support for ``load_tests`` added.


   .. method:: loadTestsFromName(name, module=None)

      Return a suite of all test cases given a string specifier.

      The specifier *name* is a "dotted name" that may resolve either to a
      module, a test case class, a test method within a test case class, a
      :class:`TestSuite` instance, or a callable object which returns a
      :class:`TestCase` or :class:`TestSuite` instance.  These checks are
      applied in the order listed here; that is, a method on a possible test
      case class will be picked up as "a test method within a test case class",
      rather than "a callable object".

      For example, if you have a module :mod:`SampleTests` containing a
      :class:`TestCase`\ -derived class :class:`SampleTestCase` with three test
      methods (:meth:`test_one`, :meth:`test_two`, and :meth:`test_three`), the
      specifier ``'SampleTests.SampleTestCase'`` would cause this method to
      return a suite which will run all three test methods. Using the specifier
      ``'SampleTests.SampleTestCase.test_two'`` would cause it to return a test
      suite which will run only the :meth:`test_two` test method. The specifier
      can refer to modules and packages which have not been imported; they will
      be imported as a side-effect.

      The method optionally resolves *name* relative to the given *module*.


   .. method:: loadTestsFromNames(names, module=None)

      Similar to :meth:`loadTestsFromName`, but takes a sequence of names rather
      than a single name.  The return value is a test suite which supports all
      the tests defined for each name.


   .. method:: getTestCaseNames(testCaseClass)

      Return a sorted sequence of method names found within *testCaseClass*;
      this should be a subclass of :class:`TestCase`.


   .. method:: discover(start_dir, pattern='test*.py', top_level_dir=None)

      Find all the test modules by recursing into subdirectories from the
      specified start directory, and return a TestSuite object containing them.
      Only test files that match *pattern* will be loaded. (Using shell style
      pattern matching.) Only module names that are importable (i.e. are valid
      Python identifiers) will be loaded.

      All test modules must be importable from the top level of the project. If
      the start directory is not the top level directory then the top level
      directory must be specified separately.

      If importing a module fails, for example due to a syntax error, then this
      will be recorded as a single error and discovery will continue.

      If a test package name (directory with :file:`__init__.py`) matches the
      pattern then the package will be checked for a ``load_tests``
      function. If this exists then it will be called with *loader*, *tests*,
      *pattern*.

      If load_tests exists then discovery does *not* recurse into the package,
      ``load_tests`` is responsible for loading all tests in the package.

      The pattern is deliberately not stored as a loader attribute so that
      packages can continue discovery themselves. *top_level_dir* is stored so
      ``load_tests`` does not need to pass this argument in to
      ``loader.discover()``.

      *start_dir* can be a dotted module name as well as a directory.

      .. versionadded:: 2.7

   The following attributes of a :class:`TestLoader` can be configured either by
   subclassing or assignment on an instance:


   .. attribute:: testMethodPrefix

      String giving the prefix of method names which will be interpreted as test
      methods.  The default value is ``'test'``.

      This affects :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*`
      methods.


   .. attribute:: sortTestMethodsUsing

      Function to be used to compare method names when sorting them in
      :meth:`getTestCaseNames` and all the :meth:`loadTestsFrom\*` methods. The
      default value is the built-in :func:`cmp` function; the attribute can also
      be set to :const:`None` to disable the sort.


   .. attribute:: suiteClass

      Callable object that constructs a test suite from a list of tests. No
      methods on the resulting object are needed.  The default value is the
      :class:`TestSuite` class.

      This affects all the :meth:`loadTestsFrom\*` methods.


.. class:: TestResult

   This class is used to compile information about which tests have succeeded
   and which have failed.

   A :class:`TestResult` object stores the results of a set of tests.  The
   :class:`TestCase` and :class:`TestSuite` classes ensure that results are
   properly recorded; test authors do not need to worry about recording the
   outcome of tests.

   Testing frameworks built on top of :mod:`unittest` may want access to the
   :class:`TestResult` object generated by running a set of tests for reporting
   purposes; a :class:`TestResult` instance is returned by the
   :meth:`TestRunner.run` method for this purpose.

   :class:`TestResult` instances have the following attributes that will be of
   interest when inspecting the results of running a set of tests:


   .. attribute:: errors

      A list containing 2-tuples of :class:`TestCase` instances and strings
      holding formatted tracebacks. Each tuple represents a test which raised an
      unexpected exception.

      .. versionchanged:: 2.2
         Contains formatted tracebacks instead of :func:`sys.exc_info` results.


   .. attribute:: failures

      A list containing 2-tuples of :class:`TestCase` instances and strings
      holding formatted tracebacks. Each tuple represents a test where a failure
      was explicitly signalled using the :meth:`TestCase.assert\*` methods.

      .. versionchanged:: 2.2
         Contains formatted tracebacks instead of :func:`sys.exc_info` results.

   .. attribute:: skipped

      A list containing 2-tuples of :class:`TestCase` instances and strings
      holding the reason for skipping the test.

      .. versionadded:: 2.7

   .. attribute:: expectedFailures

      A list containing 2-tuples of :class:`TestCase` instances and strings
      holding formatted tracebacks.  Each tuple represents an expected failure
      of the test case.

   .. attribute:: unexpectedSuccesses

      A list containing :class:`TestCase` instances that were marked as expected
      failures, but succeeded.

   .. attribute:: shouldStop

      Set to ``True`` when the execution of tests should stop by :meth:`stop`.


   .. attribute:: testsRun

      The total number of tests run so far.


   .. attribute:: buffer

      If set to true, ``sys.stdout`` and ``sys.stderr`` will be buffered in between
      :meth:`startTest` and :meth:`stopTest` being called. Collected output will
      only be echoed onto the real ``sys.stdout`` and ``sys.stderr`` if the test
      fails or errors. Any output is also attached to the failure / error message.

      .. versionadded:: 2.7


   .. attribute:: failfast

      If set to true :meth:`stop` will be called on the first failure or error,
      halting the test run.

      .. versionadded:: 2.7


   .. method:: wasSuccessful()

      Return ``True`` if all tests run so far have passed, otherwise returns
      ``False``.


   .. method:: stop()

      This method can be called to signal that the set of tests being run should
      be aborted by setting the :attr:`shouldStop` attribute to ``True``.
      :class:`TestRunner` objects should respect this flag and return without
      running any additional tests.

      For example, this feature is used by the :class:`TextTestRunner` class to
      stop the test framework when the user signals an interrupt from the
      keyboard.  Interactive tools which provide :class:`TestRunner`
      implementations can use this in a similar manner.

   The following methods of the :class:`TestResult` class are used to maintain
   the internal data structures, and may be extended in subclasses to support
   additional reporting requirements.  This is particularly useful in building
   tools which support interactive reporting while tests are being run.


   .. method:: startTest(test)

      Called when the test case *test* is about to be run.

   .. method:: stopTest(test)

      Called after the test case *test* has been executed, regardless of the
      outcome.

   .. method:: startTestRun()

      Called once before any tests are executed.

      .. versionadded:: 2.7


   .. method:: stopTestRun()

      Called once after all tests are executed.

      .. versionadded:: 2.7


   .. method:: addError(test, err)

      Called when the test case *test* raises an unexpected exception. *err* is a
      tuple of the form returned by :func:`sys.exc_info`: ``(type, value,
      traceback)``.

      The default implementation appends a tuple ``(test, formatted_err)`` to
      the instance's :attr:`errors` attribute, where *formatted_err* is a
      formatted traceback derived from *err*.


   .. method:: addFailure(test, err)

      Called when the test case *test* signals a failure. *err* is a tuple of
      the form returned by :func:`sys.exc_info`: ``(type, value, traceback)``.

      The default implementation appends a tuple ``(test, formatted_err)`` to
      the instance's :attr:`failures` attribute, where *formatted_err* is a
      formatted traceback derived from *err*.


   .. method:: addSuccess(test)

      Called when the test case *test* succeeds.

      The default implementation does nothing.


   .. method:: addSkip(test, reason)

      Called when the test case *test* is skipped.  *reason* is the reason the
      test gave for skipping.

      The default implementation appends a tuple ``(test, reason)`` to the
      instance's :attr:`skipped` attribute.


   .. method:: addExpectedFailure(test, err)

      Called when the test case *test* fails, but was marked with the
      :func:`expectedFailure` decorator.

      The default implementation appends a tuple ``(test, formatted_err)`` to
      the instance's :attr:`expectedFailures` attribute, where *formatted_err*
      is a formatted traceback derived from *err*.


   .. method:: addUnexpectedSuccess(test)

      Called when the test case *test* was marked with the
      :func:`expectedFailure` decorator, but succeeded.

      The default implementation appends the test to the instance's
      :attr:`unexpectedSuccesses` attribute.

.. class:: TextTestResult(stream, descriptions, verbosity)

    A concrete implementation of :class:`TestResult` used by the
    :class:`TextTestRunner`.

    .. versionadded:: 2.7
        This class was previously named ``_TextTestResult``. The old name still
        exists as an alias but is deprecated.

.. data:: defaultTestLoader

   Instance of the :class:`TestLoader` class intended to be shared.  If no
   customization of the :class:`TestLoader` is needed, this instance can be used
   instead of repeatedly creating new instances.


.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, \
                          failfast=False, buffer=False, resultclass=None)

   A basic test runner implementation which prints results on standard error. It
   has a few configurable parameters, but is essentially very simple.  Graphical
   applications which run test suites should provide alternate implementations.

   .. method:: _makeResult()

      This method returns the instance of ``TestResult`` used by :meth:`run`.
      It is not intended to be called directly, but can be overridden in
      subclasses to provide a custom ``TestResult``.

      ``_makeResult()`` instantiates the class or callable passed in the
      ``TextTestRunner`` constructor as the ``resultclass`` argument. It
      defaults to :class:`TextTestResult` if no ``resultclass`` is provided.
      The result class is instantiated with the following arguments::

            stream, descriptions, verbosity


.. function:: main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[, buffer]]]]]]]]]])

   A command-line program that loads a set of tests from *module* and runs them;
   this is primarily for making test modules conveniently executable.
   The simplest use for this function is to include the following line at the
   end of a test script::

      if __name__ == '__main__':
          unittest.main()

   You can run tests with more detailed information by passing in the verbosity
   argument::

      if __name__ == '__main__':
          unittest.main(verbosity=2)

   The *defaultTest* argument is the name of the test to run if no test names
   are specified via *argv*.  If not specified or ``None`` and no test names are
   provided via *argv*, all tests found in *module* are run.

   The *argv* argument can be a list of options passed to the program, with the
   first element being the program name.  If not specified or ``None``,
   the values of :data:`sys.argv` are used.

   The *testRunner* argument can either be a test runner class or an already
   created instance of it. By default ``main`` calls :func:`sys.exit` with
   an exit code indicating success or failure of the tests run.

   The *testLoader* argument has to be a :class:`TestLoader` instance,
   and defaults to :data:`defaultTestLoader`.

   ``main`` supports being used from the interactive interpreter by passing in the
   argument ``exit=False``. This displays the result on standard output without
   calling :func:`sys.exit`::

      >>> from unittest import main
      >>> main(module='test_module', exit=False)

   The *failfast*, *catchbreak* and *buffer* parameters have the same
   effect as the same-name `command-line options`_.

   Calling ``main`` actually returns an instance of the ``TestProgram`` class.
   This stores the result of the tests run as the ``result`` attribute.

   .. versionchanged:: 2.7
      The *exit*, *verbosity*, *failfast*, *catchbreak* and *buffer*
      parameters were added.


load_tests Protocol
###################

.. versionadded:: 2.7

Modules or packages can customize how tests are loaded from them during normal
test runs or test discovery by implementing a function called ``load_tests``.

If a test module defines ``load_tests`` it will be called by
:meth:`TestLoader.loadTestsFromModule` with the following arguments::

    load_tests(loader, standard_tests, None)

It should return a :class:`TestSuite`.

*loader* is the instance of :class:`TestLoader` doing the loading.
*standard_tests* are the tests that would be loaded by default from the
module. It is common for test modules to only want to add or remove tests
from the standard set of tests.
The third argument is used when loading packages as part of test discovery.

A typical ``load_tests`` function that loads tests from a specific set of
:class:`TestCase` classes may look like::

    test_cases = (TestCase1, TestCase2, TestCase3)

    def load_tests(loader, tests, pattern):
        suite = TestSuite()
        for test_class in test_cases:
            tests = loader.loadTestsFromTestCase(test_class)
            suite.addTests(tests)
        return suite

If discovery is started, either from the command line or by calling
:meth:`TestLoader.discover`, with a pattern that matches a package
name then the package :file:`__init__.py` will be checked for ``load_tests``.

.. note::

   The default pattern is ``'test*.py'``. This matches all Python files
   that start with ``'test'`` but *won't* match any test directories.

   A pattern like ``'test*'`` will match test packages as well as
   modules.

If the package :file:`__init__.py` defines ``load_tests`` then it will be
called and discovery not continued into the package. ``load_tests``
is called with the following arguments::

    load_tests(loader, standard_tests, pattern)

This should return a :class:`TestSuite` representing all the tests
from the package. (``standard_tests`` will only contain tests
collected from :file:`__init__.py`.)

Because the pattern is passed into ``load_tests`` the package is free to
continue (and potentially modify) test discovery. A 'do nothing'
``load_tests`` function for a test package would look like::

    def load_tests(loader, standard_tests, pattern):
        # top level directory cached on loader instance
        this_dir = os.path.dirname(__file__)
        package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
        standard_tests.addTests(package_tests)
        return standard_tests


Class and Module Fixtures
-------------------------

Class and module level fixtures are implemented in :class:`TestSuite`. When
the test suite encounters a test from a new class then :meth:`tearDownClass`
from the previous class (if there is one) is called, followed by
:meth:`setUpClass` from the new class.

Similarly if a test is from a different module from the previous test then
``tearDownModule`` from the previous module is run, followed by
``setUpModule`` from the new module.

After all the tests have run the final ``tearDownClass`` and
``tearDownModule`` are run.

Note that shared fixtures do not play well with [potential] features like test
parallelization and they break test isolation. They should be used with care.

The default ordering of tests created by the unittest test loaders is to group
all tests from the same modules and classes together. This will lead to
``setUpClass`` / ``setUpModule`` (etc) being called exactly once per class and
module. If you randomize the order, so that tests from different modules and
classes are adjacent to each other, then these shared fixture functions may be
called multiple times in a single test run.

Shared fixtures are not intended to work with suites with non-standard
ordering. A ``BaseTestSuite`` still exists for frameworks that don't want to
support shared fixtures.

If there are any exceptions raised during one of the shared fixture functions
the test is reported as an error. Because there is no corresponding test
instance an ``_ErrorHolder`` object (that has the same interface as a
:class:`TestCase`) is created to represent the error. If you are just using
the standard unittest test runner then this detail doesn't matter, but if you
are a framework author it may be relevant.


setUpClass and tearDownClass
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These must be implemented as class methods::

    import unittest

    class Test(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            cls._connection = createExpensiveConnectionObject()

        @classmethod
        def tearDownClass(cls):
            cls._connection.destroy()

If you want the ``setUpClass`` and ``tearDownClass`` on base classes called
then you must call up to them yourself. The implementations in
:class:`TestCase` are empty.

If an exception is raised during a ``setUpClass`` then the tests in the class
are not run and the ``tearDownClass`` is not run. Skipped classes will not
have ``setUpClass`` or ``tearDownClass`` run. If the exception is a
:exc:`SkipTest` exception then the class will be reported as having been skipped
instead of as an error.


setUpModule and tearDownModule
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These should be implemented as functions::

    def setUpModule():
        createConnection()

    def tearDownModule():
        closeConnection()

If an exception is raised in a ``setUpModule`` then none of the tests in the
module will be run and the ``tearDownModule`` will not be run. If the exception is a
:exc:`SkipTest` exception then the module will be reported as having been skipped
instead of as an error.


Signal Handling
---------------

The :option:`-c/--catch <unittest -c>` command-line option to unittest,
along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
more friendly handling of control-C during a test run. With catch break
behavior enabled control-C will allow the currently running test to complete,
and the test run will then end and report all the results so far. A second
control-c will raise a :exc:`KeyboardInterrupt` in the usual way.

The control-c handling signal handler attempts to remain compatible with code or
tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
handler is called but *isn't* the installed :const:`signal.SIGINT` handler,
i.e. it has been replaced by the system under test and delegated to, then it
calls the default handler. This will normally be the expected behavior by code
that replaces an installed handler and delegates to it. For individual tests
that need ``unittest`` control-c handling disabled the :func:`removeHandler`
decorator can be used.

There are a few utility functions for framework authors to enable control-c
handling functionality within test frameworks.

.. function:: installHandler()

   Install the control-c handler. When a :const:`signal.SIGINT` is received
   (usually in response to the user pressing control-c) all registered results
   have :meth:`~TestResult.stop` called.

   .. versionadded:: 2.7

.. function:: registerResult(result)

   Register a :class:`TestResult` object for control-c handling. Registering a
   result stores a weak reference to it, so it doesn't prevent the result from
   being garbage collected.

   Registering a :class:`TestResult` object has no side-effects if control-c
   handling is not enabled, so test frameworks can unconditionally register
   all results they create independently of whether or not handling is enabled.

   .. versionadded:: 2.7

.. function:: removeResult(result)

   Remove a registered result. Once a result has been removed then
   :meth:`~TestResult.stop` will no longer be called on that result object in
   response to a control-c.

   .. versionadded:: 2.7

.. function:: removeHandler(function=None)

   When called without arguments this function removes the control-c handler
   if it has been installed. This function can also be used as a test decorator
   to temporarily remove the handler while the test is being executed::

      @unittest.removeHandler
      def test_signal_handling(self):
          ...

   .. versionadded:: 2.7

PK
%�\}2$��"html/_sources/library/unix.rst.txtnu�[���
.. _unix:

**********************
Unix Specific Services
**********************

The modules described in this chapter provide interfaces to features that are
unique to the Unix operating system, or in some cases to some or many variants
of it.  Here's an overview:


.. toctree::

   posix.rst
   pwd.rst
   spwd.rst
   grp.rst
   crypt.rst
   dl.rst
   termios.rst
   tty.rst
   pty.rst
   fcntl.rst
   pipes.rst
   posixfile.rst
   resource.rst
   nis.rst
   syslog.rst
   commands.rst
PK
%�\�:#�a�a$html/_sources/library/urllib.rst.txtnu�[���:mod:`urllib` --- Open arbitrary resources by URL
=================================================

.. module:: urllib
   :synopsis: Open an arbitrary network resource by URL (requires sockets).

.. note::
    The :mod:`urllib` module has been split into parts and renamed in
    Python 3 to :mod:`urllib.request`, :mod:`urllib.parse`,
    and :mod:`urllib.error`. The :term:`2to3` tool will automatically adapt
    imports when converting your sources to Python 3.
    Also note that the :func:`urllib.request.urlopen` function in Python 3 is
    equivalent to :func:`urllib2.urlopen` and that :func:`urllib.urlopen` has
    been removed.

.. index::
   single: WWW
   single: World Wide Web
   single: URL

This module provides a high-level interface for fetching data across the World
Wide Web.  In particular, the :func:`urlopen` function is similar to the
built-in function :func:`open`, but accepts Universal Resource Locators (URLs)
instead of filenames.  Some restrictions apply --- it can only open URLs for
reading, and no seek operations are available.

.. seealso::

    The `Requests package <http://docs.python-requests.org/>`_
    is recommended for a higher-level HTTP client interface.

.. versionchanged:: 2.7.9

    For HTTPS URIs, :mod:`urllib` performs all the neccessary certificate and hostname checks by default.

.. warning::

    For Python versions earlier than 2.7.9, urllib does not attempt to validate the server certificates of HTTPS URIs. Use at your own risk!


High-level interface
--------------------

.. function:: urlopen(url[, data[, proxies[, context]]])

   Open a network object denoted by a URL for reading.  If the URL does not
   have a scheme identifier, or if it has :file:`file:` as its scheme
   identifier, this opens a local file (without :term:`universal newlines`);
   otherwise it opens a socket to a server somewhere on the network.  If the
   connection cannot be made the :exc:`IOError` exception is raised.  If all
   went well, a file-like object is returned.  This supports the following
   methods: :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`fileno`,
   :meth:`close`, :meth:`info`, :meth:`getcode` and :meth:`geturl`.  It also
   has proper support for the :term:`iterator` protocol. One caveat: the
   :meth:`read` method, if the size argument is omitted or negative, may not
   read until the end of the data stream; there is no good way to determine
   that the entire stream from a socket has been read in the general case.

   Except for the :meth:`info`, :meth:`getcode` and :meth:`geturl` methods,
   these methods have the same interface as for file objects --- see section
   :ref:`bltin-file-objects` in this manual.  (It is not a built-in file object,
   however, so it can't be used at those few places where a true built-in file
   object is required.)

   .. index:: module: mimetools

   The :meth:`info` method returns an instance of the class
   :class:`mimetools.Message` containing meta-information associated with the
   URL.  When the method is HTTP, these headers are those returned by the server
   at the head of the retrieved HTML page (including Content-Length and
   Content-Type).  When the method is FTP, a Content-Length header will be
   present if (as is now usual) the server passed back a file length in response
   to the FTP retrieval request. A Content-Type header will be present if the
   MIME type can be guessed.  When the method is local-file, returned headers
   will include a Date representing the file's last-modified time, a
   Content-Length giving file size, and a Content-Type containing a guess at the
   file's type. See also the description of the :mod:`mimetools` module.

   The :meth:`geturl` method returns the real URL of the page.  In some cases, the
   HTTP server redirects a client to another URL.  The :func:`urlopen` function
   handles this transparently, but in some cases the caller needs to know which URL
   the client was redirected to.  The :meth:`geturl` method can be used to get at
   this redirected URL.

   The :meth:`getcode` method returns the HTTP status code that was sent with the
   response, or ``None`` if the URL is no HTTP URL.

   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
   argument may be given to specify a ``POST`` request (normally the request type
   is ``GET``).  The *data* argument must be in standard
   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
   function below.

   The :func:`urlopen` function works transparently with proxies which do not
   require authentication.  In a Unix or Windows environment, set the
   :envvar:`http_proxy`, or :envvar:`ftp_proxy` environment variables to a URL that
   identifies the proxy server before starting the Python interpreter.  For example
   (the ``'%'`` is the command prompt)::

      % http_proxy="http://www.someproxy.com:3128"
      % export http_proxy
      % python
      ...

   The :envvar:`no_proxy` environment variable can be used to specify hosts which
   shouldn't be reached via proxy; if set, it should be a comma-separated list
   of hostname suffixes, optionally with ``:port`` appended, for example
   ``cern.ch,ncsa.uiuc.edu,some.host:8080``.

   In a Windows environment, if no proxy environment variables are set, proxy
   settings are obtained from the registry's Internet Settings section.

   .. index:: single: Internet Config

   In a Mac OS X  environment, :func:`urlopen` will retrieve proxy information
   from the OS X System Configuration Framework, which can be managed with
   Network System Preferences panel.


   Alternatively, the optional *proxies* argument may be used to explicitly specify
   proxies.  It must be a dictionary mapping scheme names to proxy URLs, where an
   empty dictionary causes no proxies to be used, and ``None`` (the default value)
   causes environmental proxy settings to be used as discussed above.  For
   example::

      # Use http://www.someproxy.com:3128 for HTTP proxying
      proxies = {'http': 'http://www.someproxy.com:3128'}
      filehandle = urllib.urlopen(some_url, proxies=proxies)
      # Don't use any proxies
      filehandle = urllib.urlopen(some_url, proxies={})
      # Use proxies from environment - both versions are equivalent
      filehandle = urllib.urlopen(some_url, proxies=None)
      filehandle = urllib.urlopen(some_url)

   Proxies which require authentication for use are not currently supported;
   this is considered an implementation limitation.

   The *context* parameter may be set to a :class:`ssl.SSLContext` instance to
   configure the SSL settings that are used if :func:`urlopen` makes a HTTPS
   connection.

   .. versionchanged:: 2.3
      Added the *proxies* support.

   .. versionchanged:: 2.6
      Added :meth:`getcode` to returned object and support for the
      :envvar:`no_proxy` environment variable.

   .. versionchanged:: 2.7.9
      The *context* parameter was added.  All the neccessary certificate and hostname
      checks are done by default.

   .. deprecated:: 2.6
      The :func:`urlopen` function has been removed in Python 3 in favor
      of :func:`urllib2.urlopen`.


.. function:: urlretrieve(url[, filename[, reporthook[, data[, context]]]])

   Copy a network object denoted by a URL to a local file, if necessary. If the URL
   points to a local file, or a valid cached copy of the object exists, the object
   is not copied.  Return a tuple ``(filename, headers)`` where *filename* is the
   local file name under which the object can be found, and *headers* is whatever
   the :meth:`info` method of the object returned by :func:`urlopen` returned (for
   a remote object, possibly cached). Exceptions are the same as for
   :func:`urlopen`.

   The second argument, if present, specifies the file location to copy to (if
   absent, the location will be a tempfile with a generated name). The third
   argument, if present, is a callable that will be called once on
   establishment of the network connection and once after each block read
   thereafter.  The callable will be passed three arguments; a count of blocks
   transferred so far, a block size in bytes, and the total size of the file.  The
   third argument may be ``-1`` on older FTP servers which do not return a file
   size in response to a retrieval request.

   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
   argument may be given to specify a ``POST`` request (normally the request type
   is ``GET``).  The *data* argument must in standard
   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
   function below.

   The *context* parameter may be set to a :class:`ssl.SSLContext` instance to
   configure the SSL settings that are used if :func:`urlretrieve` makes a HTTPS
   connection.

   .. versionchanged:: 2.5
      :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
      the amount of data available  was less than the expected amount (which is the
      size reported by a  *Content-Length* header). This can occur, for example, when
      the  download is interrupted.

      The *Content-Length* is treated as a lower bound: if there's more data  to read,
      :func:`urlretrieve` reads more data, but if less data is available,  it raises
      the exception.

      You can still retrieve the downloaded data in this case, it is stored  in the
      :attr:`content` attribute of the exception instance.

      If no *Content-Length* header was supplied, :func:`urlretrieve` can not check
      the size of the data it has downloaded, and just returns it.  In this case you
      just have to assume that the download was successful.

   .. versionchanged:: 2.7.9
      The *context* parameter was added.  All the neccessary certificate and hostname
      checks are done by default.


.. data:: _urlopener

   The public functions :func:`urlopen` and :func:`urlretrieve` create an instance
   of the :class:`FancyURLopener` class and use it to perform their requested
   actions.  To override this functionality, programmers can create a subclass of
   :class:`URLopener` or :class:`FancyURLopener`, then assign an instance of that
   class to the ``urllib._urlopener`` variable before calling the desired function.
   For example, applications may want to specify a different
   :mailheader:`User-Agent` header than :class:`URLopener` defines.  This can be
   accomplished with the following code::

      import urllib

      class AppURLopener(urllib.FancyURLopener):
          version = "App/1.7"

      urllib._urlopener = AppURLopener()


.. function:: urlcleanup()

   Clear the cache that may have been built up by previous calls to
   :func:`urlretrieve`.


Utility functions
-----------------

.. function:: quote(string[, safe])

   Replace special characters in *string* using the ``%xx`` escape. Letters,
   digits, and the characters ``'_.-'`` are never quoted. By default, this
   function is intended for quoting the path section of the URL. The optional
   *safe* parameter specifies additional characters that should not be quoted
   --- its default value is ``'/'``.

   Example: ``quote('/~connolly/')`` yields ``'/%7econnolly/'``.


.. function:: quote_plus(string[, safe])

   Like :func:`quote`, but also replaces spaces by plus signs, as required for
   quoting HTML form values when building up a query string to go into a URL.
   Plus signs in the original string are escaped unless they are included in
   *safe*.  It also does not have *safe* default to ``'/'``.


.. function:: unquote(string)

   Replace ``%xx`` escapes by their single-character equivalent.

   Example: ``unquote('/%7Econnolly/')`` yields ``'/~connolly/'``.


.. function:: unquote_plus(string)

   Like :func:`unquote`, but also replaces plus signs by spaces, as required for
   unquoting HTML form values.


.. function:: urlencode(query[, doseq])

   Convert a mapping object or a sequence of two-element tuples to a
   "percent-encoded" string, suitable to pass to :func:`urlopen` above as the
   optional *data* argument.  This is useful to pass a dictionary of form
   fields to a ``POST`` request.  The resulting string is a series of
   ``key=value`` pairs separated by ``'&'`` characters, where both *key* and
   *value* are quoted using :func:`quote_plus` above.  When a sequence of
   two-element tuples is used as the *query* argument, the first element of
   each tuple is a key and the second is a value. The value element in itself
   can be a sequence and in that case, if the optional parameter *doseq* is
   evaluates to ``True``, individual ``key=value`` pairs separated by ``'&'`` are
   generated for each element of the value sequence for the key.  The order of
   parameters in the encoded string will match the order of parameter tuples in
   the sequence. The :mod:`urlparse` module provides the functions
   :func:`parse_qs` and :func:`parse_qsl` which are used to parse query strings
   into Python data structures.


.. function:: pathname2url(path)

   Convert the pathname *path* from the local syntax for a path to the form used in
   the path component of a URL.  This does not produce a complete URL.  The return
   value will already be quoted using the :func:`quote` function.


.. function:: url2pathname(path)

   Convert the path component *path* from a percent-encoded URL to the local syntax for a
   path.  This does not accept a complete URL.  This function uses :func:`unquote`
   to decode *path*.


.. function:: getproxies()

   This helper function returns a dictionary of scheme to proxy server URL
   mappings. It scans the environment for variables named ``<scheme>_proxy``,
   in case insensitive way, for all operating systems first, and when it cannot
   find it, looks for proxy information from Mac OSX System Configuration for
   Mac OS X and Windows Systems Registry for Windows.
   If both lowercase and uppercase environment variables exist (and disagree),
   lowercase is preferred.

   .. note::

      If the environment variable ``REQUEST_METHOD`` is set, which usually
      indicates your script is running in a CGI environment, the environment
      variable ``HTTP_PROXY`` (uppercase ``_PROXY``) will be ignored. This is
      because that variable can be injected by a client using the "Proxy:" HTTP
      header. If you need to use an HTTP proxy in a CGI environment, either use
      ``ProxyHandler`` explicitly, or make sure the variable name is in
      lowercase (or at least the ``_proxy`` suffix).

.. note::
    urllib also exposes certain utility functions like splittype, splithost and
    others parsing URL into various components. But it is recommended to use
    :mod:`urlparse` for parsing URLs rather than using these functions directly.
    Python 3 does not expose these helper functions from :mod:`urllib.parse`
    module.


URL Opener objects
------------------

.. class:: URLopener([proxies[, context[, **x509]]])

   Base class for opening and reading URLs.  Unless you need to support opening
   objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
   you probably want to use :class:`FancyURLopener`.

   By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
   of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
   Applications can define their own :mailheader:`User-Agent` header by subclassing
   :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
   :attr:`version` to an appropriate string value in the subclass definition.

   The optional *proxies* parameter should be a dictionary mapping scheme names to
   proxy URLs, where an empty dictionary turns proxies off completely.  Its default
   value is ``None``, in which case environmental proxy settings will be used if
   present, as discussed in the definition of :func:`urlopen`, above.

   The *context* parameter may be a :class:`ssl.SSLContext` instance.  If given,
   it defines the SSL settings the opener uses to make HTTPS connections.

   Additional keyword parameters, collected in *x509*, may be used for
   authentication of the client when using the :file:`https:` scheme.  The keywords
   *key_file* and *cert_file* are supported to provide an  SSL key and certificate;
   both are needed to support client authentication.

   :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
   returns an error code.

   .. versionchanged:: 2.7.9
      The *context* parameter was added.  All the neccessary certificate and hostname
      checks are done by default.

   .. method:: open(fullurl[, data])

      Open *fullurl* using the appropriate protocol.  This method sets up cache and
      proxy information, then calls the appropriate open method with its input
      arguments.  If the scheme is not recognized, :meth:`open_unknown` is called.
      The *data* argument has the same meaning as the *data* argument of
      :func:`urlopen`.


   .. method:: open_unknown(fullurl[, data])

      Overridable interface to open unknown URL types.


   .. method:: retrieve(url[, filename[, reporthook[, data]]])

      Retrieves the contents of *url* and places it in *filename*.  The return value
      is a tuple consisting of a local filename and either a
      :class:`mimetools.Message` object containing the response headers (for remote
      URLs) or ``None`` (for local URLs).  The caller must then open and read the
      contents of *filename*.  If *filename* is not given and the URL refers to a
      local file, the input filename is returned.  If the URL is non-local and
      *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
      with a suffix that matches the suffix of the last path component of the input
      URL.  If *reporthook* is given, it must be a function accepting three numeric
      parameters.  It will be called after each chunk of data is read from the
      network.  *reporthook* is ignored for local URLs.

      If the *url* uses the :file:`http:` scheme identifier, the optional *data*
      argument may be given to specify a ``POST`` request (normally the request type
      is ``GET``).  The *data* argument must in standard
      :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
      function below.


   .. attribute:: version

      Variable that specifies the user agent of the opener object.  To get
      :mod:`urllib` to tell servers that it is a particular user agent, set this in a
      subclass as a class variable or in the constructor before calling the base
      constructor.


.. class:: FancyURLopener(...)

   :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
   for the following HTTP response codes: 301, 302, 303, 307 and 401.  For the 30x
   response codes listed above, the :mailheader:`Location` header is used to fetch
   the actual URL.  For 401 response codes (authentication required), basic HTTP
   authentication is performed.  For the 30x response codes, recursion is bounded
   by the value of the *maxtries* attribute, which defaults to 10.

   For all other response codes, the method :meth:`http_error_default` is called
   which you can override in subclasses to handle the error appropriately.

   .. note::

      According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
      must not be automatically redirected without confirmation by the user.  In
      reality, browsers do allow automatic redirection of these responses, changing
      the POST to a GET, and :mod:`urllib` reproduces this behaviour.

   The parameters to the constructor are the same as those for :class:`URLopener`.

   .. note::

      When performing basic authentication, a :class:`FancyURLopener` instance calls
      its :meth:`prompt_user_passwd` method.  The default implementation asks the
      users for the required information on the controlling terminal.  A subclass may
      override this method to support more appropriate behavior if needed.

   The :class:`FancyURLopener` class offers one additional method that should be
   overloaded to provide the appropriate behavior:

   .. method:: prompt_user_passwd(host, realm)

      Return information needed to authenticate the user at the given host in the
      specified security realm.  The return value should be a tuple, ``(user,
      password)``, which can be used for basic authentication.

      The implementation prompts for this information on the terminal; an application
      should override this method to use an appropriate interaction model in the local
      environment.

.. exception:: ContentTooShortError(msg[, content])

   This exception is raised when the :func:`urlretrieve` function detects that the
   amount of the downloaded data is less than the  expected amount (given by the
   *Content-Length* header). The :attr:`content` attribute stores the downloaded
   (and supposedly truncated) data.

   .. versionadded:: 2.5


:mod:`urllib` Restrictions
--------------------------

  .. index::
     pair: HTTP; protocol
     pair: FTP; protocol

* Currently, only the following protocols are supported: HTTP, (versions 0.9 and
  1.0),  FTP, and local files.

* The caching feature of :func:`urlretrieve` has been disabled until I find the
  time to hack proper processing of Expiration time headers.

* There should be a function to query whether a particular URL is in the cache.

* For backward compatibility, if a URL appears to point to a local file but the
  file can't be opened, the URL is re-interpreted using the FTP protocol.  This
  can sometimes cause confusing error messages.

* The :func:`urlopen` and :func:`urlretrieve` functions can cause arbitrarily
  long delays while waiting for a network connection to be set up.  This means
  that it is difficult to build an interactive Web client using these functions
  without using threads.

  .. index::
     single: HTML
     pair: HTTP; protocol
     module: htmllib

* The data returned by :func:`urlopen` or :func:`urlretrieve` is the raw data
  returned by the server.  This may be binary data (such as an image), plain text
  or (for example) HTML.  The HTTP protocol provides type information in the reply
  header, which can be inspected by looking at the :mailheader:`Content-Type`
  header.  If the returned data is HTML, you can use the module :mod:`htmllib` to
  parse it.

  .. index:: single: FTP

* The code handling the FTP protocol cannot differentiate between a file and a
  directory.  This can lead to unexpected behavior when attempting to read a URL
  that points to a file that is not accessible.  If the URL ends in a ``/``, it is
  assumed to refer to a directory and will be handled accordingly.  But if an
  attempt to read a file leads to a 550 error (meaning the URL cannot be found or
  is not accessible, often for permission reasons), then the path is treated as a
  directory in order to handle the case when a directory is specified by a URL but
  the trailing ``/`` has been left off.  This can cause misleading results when
  you try to fetch a file whose read permissions make it inaccessible; the FTP
  code will try to read it, fail with a 550 error, and then perform a directory
  listing for the unreadable file. If fine-grained control is needed, consider
  using the :mod:`ftplib` module, subclassing :class:`FancyURLopener`, or changing
  *_urlopener* to meet your needs.

* This module does not support the use of proxies which require authentication.
  This may be implemented in the future.

  .. index:: module: urlparse

* Although the :mod:`urllib` module contains (undocumented) routines to parse
  and unparse URL strings, the recommended interface for URL manipulation is in
  module :mod:`urlparse`.


.. _urllib-examples:

Examples
--------

Here is an example session that uses the ``GET`` method to retrieve a URL
containing parameters::

   >>> import urllib
   >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
   >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
   >>> print f.read()

The following example uses the ``POST`` method instead::

   >>> import urllib
   >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
   >>> f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
   >>> print f.read()

The following example uses an explicitly specified HTTP proxy, overriding
environment settings::

   >>> import urllib
   >>> proxies = {'http': 'http://proxy.example.com:8080/'}
   >>> opener = urllib.FancyURLopener(proxies)
   >>> f = opener.open("http://www.python.org")
   >>> f.read()

The following example uses no proxies at all, overriding environment settings::

   >>> import urllib
   >>> opener = urllib.FancyURLopener({})
   >>> f = opener.open("http://www.python.org/")
   >>> f.read()

PK
%�\;��3����%html/_sources/library/urllib2.rst.txtnu�[���:mod:`urllib2` --- extensible library for opening URLs
======================================================

.. module:: urllib2
   :synopsis: Next generation URL opening library.
.. moduleauthor:: Jeremy Hylton <jhylton@users.sourceforge.net>
.. sectionauthor:: Moshe Zadka <moshez@users.sourceforge.net>


.. note::
   The :mod:`urllib2` module has been split across several modules in
   Python 3 named :mod:`urllib.request` and :mod:`urllib.error`.
   The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.


The :mod:`urllib2` module defines functions and classes which help in opening
URLs (mostly HTTP) in a complex world --- basic and digest authentication,
redirections, cookies and more.

.. seealso::

    The `Requests package <http://requests.readthedocs.org/>`_
    is recommended for a higher-level HTTP client interface.


The :mod:`urllib2` module defines the following functions:


.. function:: urlopen(url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]])

   Open the URL *url*, which can be either a string or a :class:`Request` object.

   *data* may be a string specifying additional data to send to the server, or
   ``None`` if no such data is needed.  Currently HTTP requests are the only ones
   that use *data*; the HTTP request will be a POST instead of a GET when the
   *data* parameter is provided.  *data* should be a buffer in the standard
   :mimetype:`application/x-www-form-urlencoded` format.  The
   :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
   returns a string in this format. urllib2 module sends HTTP/1.1 requests with
   ``Connection:close`` header included.

   The optional *timeout* parameter specifies a timeout in seconds for blocking
   operations like the connection attempt (if not specified, the global default
   timeout setting will be used).  This actually only works for HTTP, HTTPS and
   FTP connections.

   If *context* is specified, it must be a :class:`ssl.SSLContext` instance
   describing the various SSL options. See :class:`~httplib.HTTPSConnection` for
   more details.

   The optional *cafile* and *capath* parameters specify a set of trusted CA
   certificates for HTTPS requests.  *cafile* should point to a single file
   containing a bundle of CA certificates, whereas *capath* should point to a
   directory of hashed certificate files.  More information can be found in
   :meth:`ssl.SSLContext.load_verify_locations`.

   The *cadefault* parameter is ignored.

   This function returns a file-like object with three additional methods:

   * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to
     determine if a redirect was followed

   * :meth:`info` --- return the meta-information of the page, such as headers,
     in the form of an :class:`mimetools.Message` instance
     (see `Quick Reference to HTTP Headers <https://www.cs.tut.fi/~jkorpela/http.html>`_)

   * :meth:`getcode` --- return the HTTP status code of the response.

   Raises :exc:`URLError` on errors.

   Note that ``None`` may be returned if no handler handles the request (though the
   default installed global :class:`OpenerDirector` uses :class:`UnknownHandler` to
   ensure this never happens).

   In addition, if proxy settings are detected (for example, when a ``*_proxy``
   environment variable like :envvar:`http_proxy` is set),
   :class:`ProxyHandler` is default installed and makes sure the requests are
   handled through the proxy.

   .. versionchanged:: 2.6
     *timeout* was added.

   .. versionchanged:: 2.7.9
      *cafile*, *capath*, *cadefault*, and *context* were added.


.. function:: install_opener(opener)

   Install an :class:`OpenerDirector` instance as the default global opener.
   Installing an opener is only necessary if you want urlopen to use that opener;
   otherwise, simply call :meth:`OpenerDirector.open` instead of :func:`urlopen`.
   The code does not check for a real :class:`OpenerDirector`, and any class with
   the appropriate interface will work.


.. function:: build_opener([handler, ...])

   Return an :class:`OpenerDirector` instance, which chains the handlers in the
   order given. *handler*\s can be either instances of :class:`BaseHandler`, or
   subclasses of :class:`BaseHandler` (in which case it must be possible to call
   the constructor without any parameters).  Instances of the following classes
   will be in front of the *handler*\s, unless the *handler*\s contain them,
   instances of them or subclasses of them: :class:`ProxyHandler` (if proxy
   settings are detected),
   :class:`UnknownHandler`, :class:`HTTPHandler`, :class:`HTTPDefaultErrorHandler`,
   :class:`HTTPRedirectHandler`, :class:`FTPHandler`, :class:`FileHandler`,
   :class:`HTTPErrorProcessor`.

   If the Python installation has SSL support (i.e., if the :mod:`ssl` module can be imported),
   :class:`HTTPSHandler` will also be added.

   Beginning in Python 2.3, a :class:`BaseHandler` subclass may also change its
   :attr:`handler_order` attribute to modify its position in the handlers
   list.

The following exceptions are raised as appropriate:


.. exception:: URLError

   The handlers raise this exception (or derived exceptions) when they run into a
   problem.  It is a subclass of :exc:`IOError`.

   .. attribute:: reason

      The reason for this error.  It can be a message string or another exception
      instance (:exc:`socket.error` for remote URLs, :exc:`OSError` for local
      URLs).


.. exception:: HTTPError

   Though being an exception (a subclass of :exc:`URLError`), an :exc:`HTTPError`
   can also function as a non-exceptional file-like return value (the same thing
   that :func:`urlopen` returns).  This is useful when handling exotic HTTP
   errors, such as requests for authentication.

   .. attribute:: code

      An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
      This numeric value corresponds to a value found in the dictionary of
      codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`.

   .. attribute:: reason

      The reason for this error.  It can be a message string or another exception
      instance.

The following classes are provided:


.. class:: Request(url[, data][, headers][, origin_req_host][, unverifiable])

   This class is an abstraction of a URL request.

   *url* should be a string containing a valid URL.

   *data* may be a string specifying additional data to send to the server, or
   ``None`` if no such data is needed.  Currently HTTP requests are the only ones
   that use *data*; the HTTP request will be a POST instead of a GET when the
   *data* parameter is provided.  *data* should be a buffer in the standard
   :mimetype:`application/x-www-form-urlencoded` format.  The
   :func:`urllib.urlencode` function takes a mapping or sequence of 2-tuples and
   returns a string in this format.

   *headers* should be a dictionary, and will be treated as if :meth:`add_header`
   was called with each key and value as arguments.  This is often used to "spoof"
   the ``User-Agent`` header value, which is used by a browser to identify itself --
   some HTTP servers only allow requests coming from common browsers as opposed
   to scripts.  For example, Mozilla Firefox may identify itself as ``"Mozilla/5.0
   (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"``, while :mod:`urllib2`'s
   default user agent string is ``"Python-urllib/2.6"`` (on Python 2.6).

   The final two arguments are only of interest for correct handling of third-party
   HTTP cookies:

   *origin_req_host* should be the request-host of the origin transaction, as
   defined by :rfc:`2965`.  It defaults to ``cookielib.request_host(self)``.  This
   is the host name or IP address of the original request that was initiated by the
   user.  For example, if the request is for an image in an HTML document, this
   should be the request-host of the request for the page containing the image.

   *unverifiable* should indicate whether the request is unverifiable, as defined
   by RFC 2965.  It defaults to ``False``.  An unverifiable request is one whose URL
   the user did not have the option to approve.  For example, if the request is for
   an image in an HTML document, and the user had no option to approve the
   automatic fetching of the image, this should be true.


.. class:: OpenerDirector()

   The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
   together. It manages the chaining of handlers, and recovery from errors.


.. class:: BaseHandler()

   This is the base class for all registered handlers --- and handles only the
   simple mechanics of registration.


.. class:: HTTPDefaultErrorHandler()

   A class which defines a default handler for HTTP error responses; all responses
   are turned into :exc:`HTTPError` exceptions.


.. class:: HTTPRedirectHandler()

   A class to handle redirections.


.. class:: HTTPCookieProcessor([cookiejar])

   A class to handle HTTP Cookies.


.. class:: ProxyHandler([proxies])

   Cause requests to go through a proxy. If *proxies* is given, it must be a
   dictionary mapping protocol names to URLs of proxies. The default is to read
   the list of proxies from the environment variables
   :envvar:`<protocol>_proxy`.  If no proxy environment variables are set, then
   in a Windows environment proxy settings are obtained from the registry's
   Internet Settings section, and in a Mac OS X environment proxy information
   is retrieved from the OS X System Configuration Framework.

   To disable autodetected proxy pass an empty dictionary.

    .. note::

       ``HTTP_PROXY`` will be ignored if a variable ``REQUEST_METHOD`` is set;
       see the documentation on :func:`~urllib.getproxies`.


.. class:: HTTPPasswordMgr()

   Keep a database of  ``(realm, uri) -> (user, password)`` mappings.


.. class:: HTTPPasswordMgrWithDefaultRealm()

   Keep a database of  ``(realm, uri) -> (user, password)`` mappings. A realm of
   ``None`` is considered a catch-all realm, which is searched if no other realm
   fits.


.. class:: AbstractBasicAuthHandler([password_mgr])

   This is a mixin class that helps with HTTP authentication, both to the remote
   host and to a proxy. *password_mgr*, if given, should be something that is
   compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: HTTPBasicAuthHandler([password_mgr])

   Handle authentication with the remote host. *password_mgr*, if given, should be
   something that is compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: ProxyBasicAuthHandler([password_mgr])

   Handle authentication with the proxy. *password_mgr*, if given, should be
   something that is compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: AbstractDigestAuthHandler([password_mgr])

   This is a mixin class that helps with HTTP authentication, both to the remote
   host and to a proxy. *password_mgr*, if given, should be something that is
   compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: HTTPDigestAuthHandler([password_mgr])

   Handle authentication with the remote host. *password_mgr*, if given, should be
   something that is compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: ProxyDigestAuthHandler([password_mgr])

   Handle authentication with the proxy. *password_mgr*, if given, should be
   something that is compatible with :class:`HTTPPasswordMgr`; refer to section
   :ref:`http-password-mgr` for information on the interface that must be
   supported.


.. class:: HTTPHandler()

   A class to handle opening of HTTP URLs.


.. class:: HTTPSHandler([debuglevel[, context]])

   A class to handle opening of HTTPS URLs. *context* has the same meaning as
   for :class:`httplib.HTTPSConnection`.

   .. versionchanged:: 2.7.9
      *context* added.


.. class:: FileHandler()

   Open local files.


.. class:: FTPHandler()

   Open FTP URLs.


.. class:: CacheFTPHandler()

   Open FTP URLs, keeping a cache of open FTP connections to minimize delays.


.. class:: UnknownHandler()

   A catch-all class to handle unknown URLs.


.. class:: HTTPErrorProcessor()

   Process HTTP error responses.


.. _request-objects:

Request Objects
---------------

The following methods describe all of :class:`Request`'s public interface, and
so all must be overridden in subclasses.


.. method:: Request.add_data(data)

   Set the :class:`Request` data to *data*.  This is ignored by all handlers except
   HTTP handlers --- and there it should be a byte string, and will change the
   request to be ``POST`` rather than ``GET``.


.. method:: Request.get_method()

   Return a string indicating the HTTP request method.  This is only meaningful for
   HTTP requests, and currently always returns ``'GET'`` or ``'POST'``.


.. method:: Request.has_data()

   Return whether the instance has a non-\ ``None`` data.


.. method:: Request.get_data()

   Return the instance's data.


.. method:: Request.add_header(key, val)

   Add another header to the request.  Headers are currently ignored by all
   handlers except HTTP handlers, where they are added to the list of headers sent
   to the server.  Note that there cannot be more than one header with the same
   name, and later calls will overwrite previous calls in case the *key* collides.
   Currently, this is no loss of HTTP functionality, since all headers which have
   meaning when used more than once have a (header-specific) way of gaining the
   same functionality using only one header.


.. method:: Request.add_unredirected_header(key, header)

   Add a header that will not be added to a redirected request.

   .. versionadded:: 2.4


.. method:: Request.has_header(header)

   Return whether the instance has the named header (checks both regular and
   unredirected).

   .. versionadded:: 2.4


.. method:: Request.get_full_url()

   Return the URL given in the constructor.


.. method:: Request.get_type()

   Return the type of the URL --- also known as the scheme.


.. method:: Request.get_host()

   Return the host to which a connection will be made.


.. method:: Request.get_selector()

   Return the selector --- the part of the URL that is sent to the server.


.. method:: Request.get_header(header_name, default=None)

   Return the value of the given header. If the header is not present, return
   the default value.


.. method:: Request.header_items()

   Return a list of tuples (header_name, header_value) of the Request headers.


.. method:: Request.set_proxy(host, type)

   Prepare the request by connecting to a proxy server. The *host* and *type* will
   replace those of the instance, and the instance's selector will be the original
   URL given in the constructor.


.. method:: Request.get_origin_req_host()

   Return the request-host of the origin transaction, as defined by :rfc:`2965`.
   See the documentation for the :class:`Request` constructor.


.. method:: Request.is_unverifiable()

   Return whether the request is unverifiable, as defined by RFC 2965. See the
   documentation for the :class:`Request` constructor.


.. _opener-director-objects:

OpenerDirector Objects
----------------------

:class:`OpenerDirector` instances have the following methods:


.. method:: OpenerDirector.add_handler(handler)

   *handler* should be an instance of :class:`BaseHandler`.  The following
   methods are searched, and added to the possible chains (note that HTTP errors
   are a special case).

   * :samp:`{protocol}_open` --- signal that the handler knows how to open
     *protocol* URLs.

   * :samp:`http_error_{type}` --- signal that the handler knows how to handle
     HTTP errors with HTTP error code *type*.

   * :samp:`{protocol}_error` --- signal that the handler knows how to handle
     errors from (non-\ ``http``) *protocol*.

   * :samp:`{protocol}_request` --- signal that the handler knows how to
     pre-process *protocol* requests.

   * :samp:`{protocol}_response` --- signal that the handler knows how to
     post-process *protocol* responses.


.. method:: OpenerDirector.open(url[, data][, timeout])

   Open the given *url* (which can be a request object or a string), optionally
   passing the given *data*. Arguments, return values and exceptions raised are
   the same as those of :func:`urlopen` (which simply calls the :meth:`open`
   method on the currently installed global :class:`OpenerDirector`).  The
   optional *timeout* parameter specifies a timeout in seconds for blocking
   operations like the connection attempt (if not specified, the global default
   timeout setting will be used). The timeout feature actually works only for
   HTTP, HTTPS and FTP connections).

   .. versionchanged:: 2.6
      *timeout* was added.


.. method:: OpenerDirector.error(proto[, arg[, ...]])

   Handle an error of the given protocol.  This will call the registered error
   handlers for the given protocol with the given arguments (which are protocol
   specific).  The HTTP protocol is a special case which uses the HTTP response
   code to determine the specific error handler; refer to the :meth:`http_error_\*`
   methods of the handler classes.

   Return values and exceptions raised are the same as those of :func:`urlopen`.

OpenerDirector objects open URLs in three stages:

The order in which these methods are called within each stage is determined by
sorting the handler instances.

#. Every handler with a method named like :samp:`{protocol}_request` has that
   method called to pre-process the request.

#. Handlers with a method named like :samp:`{protocol}_open` are called to handle
   the request. This stage ends when a handler either returns a non-\ :const:`None`
   value (ie. a response), or raises an exception (usually :exc:`URLError`).
   Exceptions are allowed to propagate.

   In fact, the above algorithm is first tried for methods named
   :meth:`default_open`.  If all such methods return :const:`None`, the
   algorithm is repeated for methods named like :samp:`{protocol}_open`.  If all
   such methods return :const:`None`, the algorithm is repeated for methods
   named :meth:`unknown_open`.

   Note that the implementation of these methods may involve calls of the parent
   :class:`OpenerDirector` instance's :meth:`~OpenerDirector.open` and
   :meth:`~OpenerDirector.error` methods.

#. Every handler with a method named like :samp:`{protocol}_response` has that
   method called to post-process the response.


.. _base-handler-objects:

BaseHandler Objects
-------------------

:class:`BaseHandler` objects provide a couple of methods that are directly
useful, and others that are meant to be used by derived classes.  These are
intended for direct use:


.. method:: BaseHandler.add_parent(director)

   Add a director as parent.


.. method:: BaseHandler.close()

   Remove any parents.

The following attributes and methods should only be used by classes derived from
:class:`BaseHandler`.

.. note::

   The convention has been adopted that subclasses defining
   :meth:`protocol_request` or :meth:`protocol_response` methods are named
   :class:`\*Processor`; all others are named :class:`\*Handler`.


.. attribute:: BaseHandler.parent

   A valid :class:`OpenerDirector`, which can be used to open using a different
   protocol, or handle errors.


.. method:: BaseHandler.default_open(req)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   define it if they want to catch all URLs.

   This method, if implemented, will be called by the parent
   :class:`OpenerDirector`.  It should return a file-like object as described in
   the return value of the :meth:`open` of :class:`OpenerDirector`, or ``None``.
   It should raise :exc:`URLError`, unless a truly exceptional thing happens (for
   example, :exc:`MemoryError` should not be mapped to :exc:`URLError`).

   This method will be called before any protocol-specific open method.


.. method:: BaseHandler.protocol_open(req)
   :noindex:

   ("protocol" is to be replaced by the protocol name.)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   define it if they want to handle URLs with the given *protocol*.

   This method, if defined, will be called by the parent :class:`OpenerDirector`.
   Return values should be the same as for  :meth:`default_open`.


.. method:: BaseHandler.unknown_open(req)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   define it if they want to catch all URLs with no specific registered handler to
   open it.

   This method, if implemented, will be called by the :attr:`parent`
   :class:`OpenerDirector`.  Return values should be the same as for
   :meth:`default_open`.


.. method:: BaseHandler.http_error_default(req, fp, code, msg, hdrs)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   override it if they intend to provide a catch-all for otherwise unhandled HTTP
   errors.  It will be called automatically by the  :class:`OpenerDirector` getting
   the error, and should not normally be called in other circumstances.

   *req* will be a :class:`Request` object, *fp* will be a file-like object with
   the HTTP error body, *code* will be the three-digit code of the error, *msg*
   will be the user-visible explanation of the code and *hdrs* will be a mapping
   object with the headers of the error.

   Return values and exceptions raised should be the same as those of
   :func:`urlopen`.


.. method:: BaseHandler.http_error_nnn(req, fp, code, msg, hdrs)

   *nnn* should be a three-digit HTTP error code.  This method is also not defined
   in :class:`BaseHandler`, but will be called, if it exists, on an instance of a
   subclass, when an HTTP error with code *nnn* occurs.

   Subclasses should override this method to handle specific HTTP errors.

   Arguments, return values and exceptions raised should be the same as for
   :meth:`http_error_default`.


.. method:: BaseHandler.protocol_request(req)
   :noindex:

   ("protocol" is to be replaced by the protocol name.)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   define it if they want to pre-process requests of the given *protocol*.

   This method, if defined, will be called by the parent :class:`OpenerDirector`.
   *req* will be a :class:`Request` object. The return value should be a
   :class:`Request` object.


.. method:: BaseHandler.protocol_response(req, response)
   :noindex:

   ("protocol" is to be replaced by the protocol name.)

   This method is *not* defined in :class:`BaseHandler`, but subclasses should
   define it if they want to post-process responses of the given *protocol*.

   This method, if defined, will be called by the parent :class:`OpenerDirector`.
   *req* will be a :class:`Request` object. *response* will be an object
   implementing the same interface as the return value of :func:`urlopen`.  The
   return value should implement the same interface as the return value of
   :func:`urlopen`.


.. _http-redirect-handler:

HTTPRedirectHandler Objects
---------------------------

.. note::

   Some HTTP redirections require action from this module's client code.  If this
   is the case, :exc:`HTTPError` is raised.  See :rfc:`2616` for details of the
   precise meanings of the various redirection codes.


.. method:: HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)

   Return a :class:`Request` or ``None`` in response to a redirect. This is called
   by the default implementations of the :meth:`http_error_30\*` methods when a
   redirection is received from the server.  If a redirection should take place,
   return a new :class:`Request` to allow :meth:`http_error_30\*` to perform the
   redirect to *newurl*.  Otherwise, raise :exc:`HTTPError` if no other handler
   should try to handle this URL, or return ``None`` if you can't but another
   handler might.

   .. note::

      The default implementation of this method does not strictly follow :rfc:`2616`,
      which says that 301 and 302 responses to ``POST`` requests must not be
      automatically redirected without confirmation by the user.  In reality, browsers
      do allow automatic redirection of these responses, changing the POST to a
      ``GET``, and the default implementation reproduces this behavior.


.. method:: HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)

   Redirect to the ``Location:`` or ``URI:`` URL.  This method is called by the
   parent :class:`OpenerDirector` when getting an HTTP 'moved permanently' response.


.. method:: HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)

   The same as :meth:`http_error_301`, but called for the 'found' response.


.. method:: HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)

   The same as :meth:`http_error_301`, but called for the 'see other' response.


.. method:: HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)

   The same as :meth:`http_error_301`, but called for the 'temporary redirect'
   response.


.. _http-cookie-processor:

HTTPCookieProcessor Objects
---------------------------

.. versionadded:: 2.4

:class:`HTTPCookieProcessor` instances have one attribute:


.. attribute:: HTTPCookieProcessor.cookiejar

   The :class:`cookielib.CookieJar` in which cookies are stored.


.. _proxy-handler:

ProxyHandler Objects
--------------------


.. method:: ProxyHandler.protocol_open(request)
   :noindex:

   ("protocol" is to be replaced by the protocol name.)

   The :class:`ProxyHandler` will have a method :samp:`{protocol}_open` for every
   *protocol* which has a proxy in the *proxies* dictionary given in the
   constructor.  The method will modify requests to go through the proxy, by
   calling ``request.set_proxy()``, and call the next handler in the chain to
   actually execute the protocol.


.. _http-password-mgr:

HTTPPasswordMgr Objects
-----------------------

These methods are available on :class:`HTTPPasswordMgr` and
:class:`HTTPPasswordMgrWithDefaultRealm` objects.


.. method:: HTTPPasswordMgr.add_password(realm, uri, user, passwd)

   *uri* can be either a single URI, or a sequence of URIs. *realm*, *user* and
   *passwd* must be strings. This causes ``(user, passwd)`` to be used as
   authentication tokens when authentication for *realm* and a super-URI of any of
   the given URIs is given.


.. method:: HTTPPasswordMgr.find_user_password(realm, authuri)

   Get user/password for given realm and URI, if any.  This method will return
   ``(None, None)`` if there is no matching user/password.

   For :class:`HTTPPasswordMgrWithDefaultRealm` objects, the realm ``None`` will be
   searched if the given *realm* has no matching user/password.


.. _abstract-basic-auth-handler:

AbstractBasicAuthHandler Objects
--------------------------------


.. method:: AbstractBasicAuthHandler.http_error_auth_reqed(authreq, host, req, headers)

   Handle an authentication request by getting a user/password pair, and re-trying
   the request.  *authreq* should be the name of the header where the information
   about the realm is included in the request, *host* specifies the URL and path to
   authenticate for, *req* should be the (failed) :class:`Request` object, and
   *headers* should be the error headers.

   *host* is either an authority (e.g. ``"python.org"``) or a URL containing an
   authority component (e.g. ``"http://python.org/"``). In either case, the
   authority must not contain a userinfo component (so, ``"python.org"`` and
   ``"python.org:80"`` are fine, ``"joe:password@python.org"`` is not).


.. _http-basic-auth-handler:

HTTPBasicAuthHandler Objects
----------------------------


.. method:: HTTPBasicAuthHandler.http_error_401(req, fp, code,  msg, hdrs)

   Retry the request with authentication information, if available.


.. _proxy-basic-auth-handler:

ProxyBasicAuthHandler Objects
-----------------------------


.. method:: ProxyBasicAuthHandler.http_error_407(req, fp, code,  msg, hdrs)

   Retry the request with authentication information, if available.


.. _abstract-digest-auth-handler:

AbstractDigestAuthHandler Objects
---------------------------------


.. method:: AbstractDigestAuthHandler.http_error_auth_reqed(authreq, host, req, headers)

   *authreq* should be the name of the header where the information about the realm
   is included in the request, *host* should be the host to authenticate to, *req*
   should be the (failed) :class:`Request` object, and *headers* should be the
   error headers.


.. _http-digest-auth-handler:

HTTPDigestAuthHandler Objects
-----------------------------


.. method:: HTTPDigestAuthHandler.http_error_401(req, fp, code,  msg, hdrs)

   Retry the request with authentication information, if available.


.. _proxy-digest-auth-handler:

ProxyDigestAuthHandler Objects
------------------------------


.. method:: ProxyDigestAuthHandler.http_error_407(req, fp, code,  msg, hdrs)

   Retry the request with authentication information, if available.


.. _http-handler-objects:

HTTPHandler Objects
-------------------


.. method:: HTTPHandler.http_open(req)

   Send an HTTP request, which can be either GET or POST, depending on
   ``req.has_data()``.


.. _https-handler-objects:

HTTPSHandler Objects
--------------------


.. method:: HTTPSHandler.https_open(req)

   Send an HTTPS request, which can be either GET or POST, depending on
   ``req.has_data()``.


.. _file-handler-objects:

FileHandler Objects
-------------------


.. method:: FileHandler.file_open(req)

   Open the file locally, if there is no host name, or the host name is
   ``'localhost'``. Change the protocol to ``ftp`` otherwise, and retry opening it
   using :attr:`parent`.


.. _ftp-handler-objects:

FTPHandler Objects
------------------


.. method:: FTPHandler.ftp_open(req)

   Open the FTP file indicated by *req*. The login is always done with empty
   username and password.


.. _cacheftp-handler-objects:

CacheFTPHandler Objects
-----------------------

:class:`CacheFTPHandler` objects are :class:`FTPHandler` objects with the
following additional methods:


.. method:: CacheFTPHandler.setTimeout(t)

   Set timeout of connections to *t* seconds.


.. method:: CacheFTPHandler.setMaxConns(m)

   Set maximum number of cached connections to *m*.


.. _unknown-handler-objects:

UnknownHandler Objects
----------------------


.. method:: UnknownHandler.unknown_open()

   Raise a :exc:`URLError` exception.


.. _http-error-processor-objects:

HTTPErrorProcessor Objects
--------------------------

.. versionadded:: 2.4


.. method:: HTTPErrorProcessor.http_response()

   Process HTTP error responses.

   For 200 error codes, the response object is returned immediately.

   For non-200 error codes, this simply passes the job on to the
   :samp:`{protocol}_error_code` handler methods, via
   :meth:`OpenerDirector.error`.  Eventually,
   :class:`urllib2.HTTPDefaultErrorHandler` will raise an :exc:`HTTPError` if no
   other handler handles the error.

.. method:: HTTPErrorProcessor.https_response()

   Process HTTPS error responses.

   The behavior is same as :meth:`http_response`.


.. _urllib2-examples:

Examples
--------

In addition to the examples below, more examples are given in
:ref:`urllib-howto`.

This example gets the python.org main page and displays the first 100 bytes of
it::

   >>> import urllib2
   >>> f = urllib2.urlopen('http://www.python.org/')
   >>> print f.read(100)
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   <?xml-stylesheet href="./css/ht2html

Here we are sending a data-stream to the stdin of a CGI and reading the data it
returns to us. Note that this example will only work when the Python
installation supports SSL. ::

   >>> import urllib2
   >>> req = urllib2.Request(url='https://localhost/cgi-bin/test.cgi',
   ...                       data='This data is passed to stdin of the CGI')
   >>> f = urllib2.urlopen(req)
   >>> print f.read()
   Got Data: "This data is passed to stdin of the CGI"

The code for the sample CGI used in the above example is::

   #!/usr/bin/env python
   import sys
   data = sys.stdin.read()
   print 'Content-type: text-plain\n\nGot Data: "%s"' % data

Use of Basic HTTP Authentication::

   import urllib2
   # Create an OpenerDirector with support for Basic HTTP Authentication...
   auth_handler = urllib2.HTTPBasicAuthHandler()
   auth_handler.add_password(realm='PDQ Application',
                             uri='https://mahler:8092/site-updates.py',
                             user='klem',
                             passwd='kadidd!ehopper')
   opener = urllib2.build_opener(auth_handler)
   # ...and install it globally so it can be used with urlopen.
   urllib2.install_opener(opener)
   urllib2.urlopen('http://www.example.com/login.html')

:func:`build_opener` provides many handlers by default, including a
:class:`ProxyHandler`.  By default, :class:`ProxyHandler` uses the environment
variables named ``<scheme>_proxy``, where ``<scheme>`` is the URL scheme
involved.  For example, the :envvar:`http_proxy` environment variable is read to
obtain the HTTP proxy's URL.

This example replaces the default :class:`ProxyHandler` with one that uses
programmatically-supplied proxy URLs, and adds proxy authorization support with
:class:`ProxyBasicAuthHandler`. ::

   proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
   proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
   proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

   opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
   # This time, rather than install the OpenerDirector, we use it directly:
   opener.open('http://www.example.com/login.html')

Adding HTTP headers:

Use the *headers* argument to the :class:`Request` constructor, or::

   import urllib2
   req = urllib2.Request('http://www.example.com/')
   req.add_header('Referer', 'http://www.python.org/')
   # Customize the default User-Agent header value:
   req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
   r = urllib2.urlopen(req)

:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
every :class:`Request`.  To change this::

   import urllib2
   opener = urllib2.build_opener()
   opener.addheaders = [('User-agent', 'Mozilla/5.0')]
   opener.open('http://www.example.com/')

Also, remember that a few standard headers (:mailheader:`Content-Length`,
:mailheader:`Content-Type` and :mailheader:`Host`) are added when the
:class:`Request` is passed to :func:`urlopen` (or :meth:`OpenerDirector.open`).

PK
%�\�Vt��>�>&html/_sources/library/urlparse.rst.txtnu�[���:mod:`urlparse` --- Parse URLs into components
==============================================

.. module:: urlparse
   :synopsis: Parse URLs into or assemble them from components.


.. index::
   single: WWW
   single: World Wide Web
   single: URL
   pair: URL; parsing
   pair: relative; URL

.. note::
   The :mod:`urlparse` module is renamed to :mod:`urllib.parse` in Python 3.
   The :term:`2to3` tool will automatically adapt imports when converting
   your sources to Python 3.

**Source code:** :source:`Lib/urlparse.py`

--------------

This module defines a standard interface to break Uniform Resource Locator (URL)
strings up in components (addressing scheme, network location, path etc.), to
combine the components back into a URL string, and to convert a "relative URL"
to an absolute URL given a "base URL."

The module has been designed to match the Internet RFC on Relative Uniform
Resource Locators. It supports the following URL schemes: ``file``, ``ftp``,
``gopher``, ``hdl``, ``http``, ``https``, ``imap``, ``mailto``, ``mms``,
``news``,  ``nntp``, ``prospero``, ``rsync``, ``rtsp``, ``rtspu``,  ``sftp``,
``shttp``, ``sip``, ``sips``, ``snews``, ``svn``,  ``svn+ssh``, ``telnet``,
``wais``.

.. versionadded:: 2.5
   Support for the ``sftp`` and ``sips`` schemes.

The :mod:`urlparse` module defines the following functions:


.. function:: urlparse(urlstring[, scheme[, allow_fragments]])

   Parse a URL into six components, returning a 6-tuple.  This corresponds to the
   general structure of a URL: ``scheme://netloc/path;parameters?query#fragment``.
   Each tuple item is a string, possibly empty. The components are not broken up in
   smaller parts (for example, the network location is a single string), and %
   escapes are not expanded. The delimiters as shown above are not part of the
   result, except for a leading slash in the *path* component, which is retained if
   present.  For example:

      >>> from urlparse import urlparse
      >>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
      >>> o   # doctest: +NORMALIZE_WHITESPACE
      ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                  params='', query='', fragment='')
      >>> o.scheme
      'http'
      >>> o.port
      80
      >>> o.geturl()
      'http://www.cwi.nl:80/%7Eguido/Python.html'


   Following the syntax specifications in :rfc:`1808`, urlparse recognizes
   a netloc only if it is properly introduced by '//'.  Otherwise the
   input is presumed to be a relative URL and thus to start with
   a path component.

       >>> from urlparse import urlparse
       >>> urlparse('//www.cwi.nl:80/%7Eguido/Python.html')
       ParseResult(scheme='', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
                  params='', query='', fragment='')
       >>> urlparse('www.cwi.nl/%7Eguido/Python.html')
       ParseResult(scheme='', netloc='', path='www.cwi.nl/%7Eguido/Python.html',
                  params='', query='', fragment='')
       >>> urlparse('help/Python.html')
       ParseResult(scheme='', netloc='', path='help/Python.html', params='',
                  query='', fragment='')

   If the *scheme* argument is specified, it gives the default addressing
   scheme, to be used only if the URL does not specify one.  The default value for
   this argument is the empty string.

   If the *allow_fragments* argument is false, fragment identifiers are not
   recognized and parsed as part of the preceding component, even if the URL's
   addressing scheme normally does support them.  The default value for this
   argument is :const:`True`.

   The return value is actually an instance of a subclass of :class:`tuple`.  This
   class has the following additional read-only convenience attributes:

   +------------------+-------+--------------------------+----------------------+
   | Attribute        | Index | Value                    | Value if not present |
   +==================+=======+==========================+======================+
   | :attr:`scheme`   | 0     | URL scheme specifier     | *scheme* parameter   |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`netloc`   | 1     | Network location part    | empty string         |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`path`     | 2     | Hierarchical path        | empty string         |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`params`   | 3     | Parameters for last path | empty string         |
   |                  |       | element                  |                      |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`query`    | 4     | Query component          | empty string         |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`fragment` | 5     | Fragment identifier      | empty string         |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`username` |       | User name                | :const:`None`        |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`password` |       | Password                 | :const:`None`        |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`hostname` |       | Host name (lower case)   | :const:`None`        |
   +------------------+-------+--------------------------+----------------------+
   | :attr:`port`     |       | Port number as integer,  | :const:`None`        |
   |                  |       | if present               |                      |
   +------------------+-------+--------------------------+----------------------+

   See section :ref:`urlparse-result-object` for more information on the result
   object.

   .. versionchanged:: 2.5
      Added attributes to return value.

   .. versionchanged:: 2.7
      Added IPv6 URL parsing capabilities.


.. function:: parse_qs(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]])

   Parse a query string given as a string argument (data of type
   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a
   dictionary.  The dictionary keys are the unique query variable names and the
   values are lists of values for each name.

   The optional argument *keep_blank_values* is a flag indicating whether blank
   values in percent-encoded queries should be treated as blank strings.   A true value
   indicates that blanks should be retained as  blank strings.  The default false
   value indicates that blank values are to be ignored and treated as if they were
   not included.

   The optional argument *strict_parsing* is a flag indicating what to do with
   parsing errors.  If false (the default), errors are silently ignored.  If true,
   errors raise a :exc:`ValueError` exception.

   The optional argument *max_num_fields* is the maximum number of fields to
   read. If set, then throws a :exc:`ValueError` if there are more than
   *max_num_fields* fields read.

   Use the :func:`urllib.urlencode` function to convert such dictionaries into
   query strings.

   .. versionadded:: 2.6
      Copied from the :mod:`cgi` module.

   .. versionchanged:: 2.7.16
      Added *max_num_fields* parameter.

.. function:: parse_qsl(qs[, keep_blank_values[, strict_parsing[, max_num_fields]]])

   Parse a query string given as a string argument (data of type
   :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a list of
   name, value pairs.

   The optional argument *keep_blank_values* is a flag indicating whether blank
   values in percent-encoded queries should be treated as blank strings.   A true value
   indicates that blanks should be retained as  blank strings.  The default false
   value indicates that blank values are to be ignored and treated as if they were
   not included.

   The optional argument *strict_parsing* is a flag indicating what to do with
   parsing errors.  If false (the default), errors are silently ignored.  If true,
   errors raise a :exc:`ValueError` exception.

   The optional argument *max_num_fields* is the maximum number of fields to
   read. If set, then throws a :exc:`ValueError` if there are more than
   *max_num_fields* fields read.

   Use the :func:`urllib.urlencode` function to convert such lists of pairs into
   query strings.

   .. versionadded:: 2.6
      Copied from the :mod:`cgi` module.

   .. versionchanged:: 2.7.16
      Added *max_num_fields* parameter.

.. function:: urlunparse(parts)

   Construct a URL from a tuple as returned by ``urlparse()``. The *parts* argument
   can be any six-item iterable. This may result in a slightly different, but
   equivalent URL, if the URL that was parsed originally had unnecessary delimiters
   (for example, a ? with an empty query; the RFC states that these are
   equivalent).


.. function:: urlsplit(urlstring[, scheme[, allow_fragments]])

   This is similar to :func:`urlparse`, but does not split the params from the URL.
   This should generally be used instead of :func:`urlparse` if the more recent URL
   syntax allowing parameters to be applied to each segment of the *path* portion
   of the URL (see :rfc:`2396`) is wanted.  A separate function is needed to
   separate the path segments and parameters.  This function returns a 5-tuple:
   (addressing scheme, network location, path, query, fragment identifier).

   The return value is actually an instance of a subclass of :class:`tuple`.  This
   class has the following additional read-only convenience attributes:

   +------------------+-------+-------------------------+----------------------+
   | Attribute        | Index | Value                   | Value if not present |
   +==================+=======+=========================+======================+
   | :attr:`scheme`   | 0     | URL scheme specifier    | *scheme* parameter   |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`netloc`   | 1     | Network location part   | empty string         |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`path`     | 2     | Hierarchical path       | empty string         |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`query`    | 3     | Query component         | empty string         |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`fragment` | 4     | Fragment identifier     | empty string         |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`username` |       | User name               | :const:`None`        |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`password` |       | Password                | :const:`None`        |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`hostname` |       | Host name (lower case)  | :const:`None`        |
   +------------------+-------+-------------------------+----------------------+
   | :attr:`port`     |       | Port number as integer, | :const:`None`        |
   |                  |       | if present              |                      |
   +------------------+-------+-------------------------+----------------------+

   See section :ref:`urlparse-result-object` for more information on the result
   object.

   .. versionadded:: 2.2

   .. versionchanged:: 2.5
      Added attributes to return value.


.. function:: urlunsplit(parts)

   Combine the elements of a tuple as returned by :func:`urlsplit` into a complete
   URL as a string. The *parts* argument can be any five-item iterable. This may
   result in a slightly different, but equivalent URL, if the URL that was parsed
   originally had unnecessary delimiters (for example, a ? with an empty query; the
   RFC states that these are equivalent).

   .. versionadded:: 2.2


.. function:: urljoin(base, url[, allow_fragments])

   Construct a full ("absolute") URL by combining a "base URL" (*base*) with
   another URL (*url*).  Informally, this uses components of the base URL, in
   particular the addressing scheme, the network location and (part of) the path,
   to provide missing components in the relative URL.  For example:

      >>> from urlparse import urljoin
      >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html', 'FAQ.html')
      'http://www.cwi.nl/%7Eguido/FAQ.html'

   The *allow_fragments* argument has the same meaning and default as for
   :func:`urlparse`.

   .. note::

      If *url* is an absolute URL (that is, starting with ``//`` or ``scheme://``),
      the *url*'s host name and/or scheme will be present in the result.  For example:

   .. doctest::

      >>> urljoin('http://www.cwi.nl/%7Eguido/Python.html',
      ...         '//www.python.org/%7Eguido')
      'http://www.python.org/%7Eguido'

   If you do not want that behavior, preprocess the *url* with :func:`urlsplit` and
   :func:`urlunsplit`, removing possible *scheme* and *netloc* parts.


.. function:: urldefrag(url)

   If *url* contains a fragment identifier, returns a modified version of *url*
   with no fragment identifier, and the fragment identifier as a separate string.
   If there is no fragment identifier in *url*, returns *url* unmodified and an
   empty string.


.. seealso::

   :rfc:`3986` - Uniform Resource Identifiers
      This is the current standard (STD66). Any changes to urlparse module
      should conform to this. Certain deviations could be observed, which are
      mostly for backward compatibility purposes and for certain de-facto
      parsing requirements as commonly observed in major browsers.

   :rfc:`2732` - Format for Literal IPv6 Addresses in URL's.
      This specifies the parsing requirements of IPv6 URLs.

   :rfc:`2396` - Uniform Resource Identifiers (URI): Generic Syntax
      Document describing the generic syntactic requirements for both Uniform Resource
      Names (URNs) and Uniform Resource Locators (URLs).

   :rfc:`2368` - The mailto URL scheme.
      Parsing requirements for mailto URL schemes.

   :rfc:`1808` - Relative Uniform Resource Locators
      This Request For Comments includes the rules for joining an absolute and a
      relative URL, including a fair number of "Abnormal Examples" which govern the
      treatment of border cases.

   :rfc:`1738` - Uniform Resource Locators (URL)
      This specifies the formal syntax and semantics of absolute URLs.


.. _urlparse-result-object:

Results of :func:`urlparse` and :func:`urlsplit`
------------------------------------------------

The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
subclasses of the :class:`tuple` type.  These subclasses add the attributes
described in those functions, as well as provide an additional method:


.. method:: ParseResult.geturl()

   Return the re-combined version of the original URL as a string. This may differ
   from the original URL in that the scheme will always be normalized to lower case
   and empty components may be dropped. Specifically, empty parameters, queries,
   and fragment identifiers will be removed.

   The result of this method is a fixpoint if passed back through the original
   parsing function:

      >>> import urlparse
      >>> url = 'HTTP://www.Python.org/doc/#'

      >>> r1 = urlparse.urlsplit(url)
      >>> r1.geturl()
      'http://www.Python.org/doc/'

      >>> r2 = urlparse.urlsplit(r1.geturl())
      >>> r2.geturl()
      'http://www.Python.org/doc/'

   .. versionadded:: 2.5

The following classes provide the implementations of the parse results:


.. class:: ParseResult(scheme, netloc, path, params, query, fragment)

   Concrete class for :func:`urlparse` results.


.. class:: SplitResult(scheme, netloc, path, query, fragment)

   Concrete class for :func:`urlsplit` results.

PK
%�\v'�
�
"html/_sources/library/user.rst.txtnu�[���
:mod:`user` --- User-specific configuration hook
================================================

.. module:: user
   :synopsis: A standard way to reference user-specific modules.
   :deprecated:

.. deprecated:: 2.6
   The :mod:`user` module has been removed in Python 3.

.. index::
   pair: .pythonrc.py; file
   triple: user; configuration; file

As a policy, Python doesn't run user-specified code on startup of Python
programs.  (Only interactive sessions execute the script specified in the
:envvar:`PYTHONSTARTUP` environment variable if it exists).

However, some programs or sites may find it convenient to allow users to have a
standard customization file, which gets run when a program requests it.  This
module implements such a mechanism.  A program that wishes to use the mechanism
must execute the statement ::

   import user

.. index:: builtin: execfile

The :mod:`user` module looks for a file :file:`.pythonrc.py` in the user's home
directory and if it can be opened, executes it (using :func:`execfile`) in its
own (the module :mod:`user`'s) global namespace.  Errors during this phase are
not caught; that's up to the program that imports the :mod:`user` module, if it
wishes.  The home directory is assumed to be named by the :envvar:`HOME`
environment variable; if this is not set, the current directory is used.

The user's :file:`.pythonrc.py` could conceivably test for ``sys.version`` if it
wishes to do different things depending on the Python version.

A warning to users: be very conservative in what you place in your
:file:`.pythonrc.py` file.  Since you don't know which programs will use it,
changing the behavior of standard modules or functions is generally not a good
idea.

A suggestion for programmers who wish to use this mechanism: a simple way to let
users specify options for your package is to have them define variables in their
:file:`.pythonrc.py` file that you test in your module.  For example, a module
:mod:`spam` that has a verbosity level can look for a variable
``user.spam_verbose``, as follows::

   import user

   verbose = bool(getattr(user, "spam_verbose", 0))

(The three-argument form of :func:`getattr` is used in case the user has not
defined ``spam_verbose`` in their :file:`.pythonrc.py` file.)

Programs with extensive customization needs are better off reading a
program-specific customization file.

Programs with security or privacy concerns should *not* import this module; a
user can easily break into a program by placing arbitrary code in the
:file:`.pythonrc.py` file.

Modules for general use should *not* import this module; it may interfere with
the operation of the importing program.


.. seealso::

   Module :mod:`site`
      Site-wide customization mechanism.

PK
%�\�z�J$J$&html/_sources/library/userdict.rst.txtnu�[���:mod:`UserDict` --- Class wrapper for dictionary objects
========================================================

.. module:: UserDict
   :synopsis: Class wrapper for dictionary objects.


**Source code:** :source:`Lib/UserDict.py`

--------------

The module defines a mixin,  :class:`DictMixin`, defining all dictionary methods
for classes that already have a minimum mapping interface.  This greatly
simplifies writing classes that need to be substitutable for dictionaries (such
as the shelve module).

This module also defines a class, :class:`~UserDict.UserDict`, that acts as a wrapper
around dictionary objects.  The need for this class has been largely supplanted
by the ability to subclass directly from :class:`dict` (a feature that became
available starting with Python version 2.2).  Prior to the introduction of
:class:`dict`, the :class:`~UserDict.UserDict` class was used to create dictionary-like
sub-classes that obtained new behaviors by overriding existing methods or adding
new ones.

The :mod:`UserDict` module defines the :class:`~UserDict.UserDict` class and
:class:`DictMixin`:


.. class:: UserDict([initialdata])

   Class that simulates a dictionary.  The instance's contents are kept in a
   regular dictionary, which is accessible via the :attr:`data` attribute of
   :class:`~UserDict.UserDict` instances.  If *initialdata* is provided, :attr:`data` is
   initialized with its contents; note that a reference to *initialdata* will not
   be kept, allowing it be used for other purposes.

   .. note::

      For backward compatibility, instances of :class:`~UserDict.UserDict` are not iterable.


.. class:: IterableUserDict([initialdata])

   Subclass of :class:`~UserDict.UserDict` that supports direct iteration (e.g.  ``for key in
   myDict``).

In addition to supporting the methods and operations of mappings (see section
:ref:`typesmapping`), :class:`~UserDict.UserDict` and :class:`IterableUserDict` instances
provide the following attribute:


.. attribute:: IterableUserDict.data

   A real dictionary used to store the contents of the :class:`~UserDict.UserDict` class.


.. class:: DictMixin()

   Mixin defining all dictionary methods for classes that already have a minimum
   dictionary interface including :meth:`__getitem__`, :meth:`__setitem__`,
   :meth:`__delitem__`, and :meth:`keys`.

   This mixin should be used as a superclass.  Adding each of the above methods
   adds progressively more functionality.  For instance, defining all but
   :meth:`__delitem__` will preclude only :meth:`pop` and :meth:`popitem` from the
   full interface.

   In addition to the four base methods, progressively more efficiency comes with
   defining :meth:`__contains__`, :meth:`__iter__`, and :meth:`iteritems`.

   Since the mixin has no knowledge of the subclass constructor, it does not define
   :meth:`__init__` or :meth:`copy`.

   Starting with Python version 2.6, it is recommended to use
   :class:`collections.MutableMapping` instead of :class:`DictMixin`.

   Note that DictMixin does not implement the :meth:`~dict.viewkeys`,
   :meth:`~dict.viewvalues`, or :meth:`~dict.viewitems` methods.

:mod:`UserList` --- Class wrapper for list objects
==================================================

.. module:: UserList
   :synopsis: Class wrapper for list objects.


.. note::

   When Python 2.2 was released, many of the use cases for this class were
   subsumed by the ability to subclass :class:`list` directly.  However, a
   handful of use cases remain.

   This module provides a list-interface around an underlying data store.  By
   default, that data store is a :class:`list`; however, it can be used to wrap
   a list-like interface around other objects (such as persistent storage).

   In addition, this class can be mixed-in with built-in classes using multiple
   inheritance.  This can sometimes be useful.  For example, you can inherit
   from :class:`~UserList.UserList` and :class:`str` at the same time.  That would not be
   possible with both a real :class:`list` and a real :class:`str`.

This module defines a class that acts as a wrapper around list objects.  It is a
useful base class for your own list-like classes, which can inherit from them
and override existing methods or add new ones.  In this way one can add new
behaviors to lists.

The :mod:`UserList` module defines the :class:`~UserList.UserList` class:


.. class:: UserList([list])

   Class that simulates a list.  The instance's contents are kept in a regular
   list, which is accessible via the :attr:`data` attribute of :class:`~UserList.UserList`
   instances.  The instance's contents are initially set to a copy of *list*,
   defaulting to the empty list ``[]``.  *list* can be any iterable, e.g. a
   real Python list or a :class:`~UserList.UserList` object.

   .. note::
      The :class:`~UserList.UserList` class has been moved to the :mod:`collections`
      module in Python 3. The :term:`2to3` tool will automatically adapt
      imports when converting your sources to Python 3.


In addition to supporting the methods and operations of mutable sequences (see
section :ref:`typesseq`), :class:`~UserList.UserList` instances provide the following
attribute:


.. attribute:: UserList.data

   A real Python list object used to store the contents of the :class:`~UserList.UserList`
   class.

**Subclassing requirements:** Subclasses of :class:`~UserList.UserList` are expected to
offer a constructor which can be called with either no arguments or one
argument.  List operations which return a new sequence attempt to create an
instance of the actual implementation class.  To do so, it assumes that the
constructor can be called with a single parameter, which is a sequence object
used as a data source.

If a derived class does not wish to comply with this requirement, all of the
special methods supported by this class will need to be overridden; please
consult the sources for information about the methods which need to be provided
in that case.

.. versionchanged:: 2.0
   Python versions 1.5.2 and 1.6 also required that the constructor be callable
   with no parameters, and offer a mutable :attr:`data` attribute.  Earlier
   versions of Python did not attempt to create instances of the derived class.


:mod:`UserString` --- Class wrapper for string objects
======================================================

.. module:: UserString
   :synopsis: Class wrapper for string objects.
.. moduleauthor:: Peter Funk <pf@artcom-gmbh.de>
.. sectionauthor:: Peter Funk <pf@artcom-gmbh.de>


.. note::

   This :class:`~UserString.UserString` class from this module is available for backward
   compatibility only.  If you are writing code that does not need to work with
   versions of Python earlier than Python 2.2, please consider subclassing directly
   from the built-in :class:`str` type instead of using :class:`~UserString.UserString` (there
   is no built-in equivalent to :class:`MutableString`).

This module defines a class that acts as a wrapper around string objects.  It is
a useful base class for your own string-like classes, which can inherit from
them and override existing methods or add new ones.  In this way one can add new
behaviors to strings.

It should be noted that these classes are highly inefficient compared to real
string or Unicode objects; this is especially the case for
:class:`MutableString`.

The :mod:`UserString` module defines the following classes:


.. class:: UserString([sequence])

   Class that simulates a string or a Unicode string object.  The instance's
   content is kept in a regular string or Unicode string object, which is
   accessible via the :attr:`data` attribute of :class:`~UserString.UserString` instances.  The
   instance's contents are initially set to a copy of *sequence*.  *sequence* can
   be either a regular Python string or Unicode string, an instance of
   :class:`~UserString.UserString` (or a subclass) or an arbitrary sequence which can be
   converted into a string using the built-in :func:`str` function.

   .. note::
      The :class:`~UserString.UserString` class has been moved to the :mod:`collections`
      module in Python 3. The :term:`2to3` tool will automatically adapt
      imports when converting your sources to Python 3.



.. class:: MutableString([sequence])

   This class is derived from the :class:`~UserString.UserString` above and redefines strings
   to be *mutable*.  Mutable strings can't be used as dictionary keys, because
   dictionaries require *immutable* objects as keys.  The main intention of this
   class is to serve as an educational example for inheritance and necessity to
   remove (override) the :meth:`__hash__` method in order to trap attempts to use a
   mutable object as dictionary key, which would be otherwise very error prone and
   hard to track down.

   .. deprecated:: 2.6
      The :class:`MutableString` class has been removed in Python 3.

In addition to supporting the methods and operations of string and Unicode
objects (see section :ref:`string-methods`), :class:`~UserString.UserString` instances
provide the following attribute:


.. attribute:: MutableString.data

   A real Python string or Unicode object used to store the content of the
   :class:`~UserString.UserString` class.

PK
%�\F�{�A	A	 html/_sources/library/uu.rst.txtnu�[���:mod:`uu` --- Encode and decode uuencode files
==============================================

.. module:: uu
   :synopsis: Encode and decode files in uuencode format.
.. moduleauthor:: Lance Ellinghouse

**Source code:** :source:`Lib/uu.py`

--------------

This module encodes and decodes files in uuencode format, allowing arbitrary
binary data to be transferred over ASCII-only connections. Wherever a file
argument is expected, the methods accept a file-like object.  For backwards
compatibility, a string containing a pathname is also accepted, and the
corresponding file will be opened for reading and writing; the pathname ``'-'``
is understood to mean the standard input or output.  However, this interface is
deprecated; it's better for the caller to open the file itself, and be sure
that, when required, the mode is ``'rb'`` or ``'wb'`` on Windows.

.. index::
   single: Jansen, Jack
   single: Ellinghouse, Lance

This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.

The :mod:`uu` module defines the following functions:


.. function:: encode(in_file, out_file[, name[, mode]])

   Uuencode file *in_file* into file *out_file*.  The uuencoded file will have the
   header specifying *name* and *mode* as the defaults for the results of decoding
   the file. The default defaults are taken from *in_file*, or ``'-'`` and ``0666``
   respectively.


.. function:: decode(in_file[, out_file[, mode[, quiet]]])

   This call decodes uuencoded file *in_file* placing the result on file
   *out_file*. If *out_file* is a pathname, *mode* is used to set the permission
   bits if the file must be created. Defaults for *out_file* and *mode* are taken
   from the uuencode header.  However, if the file specified in the header already
   exists, a :exc:`uu.Error` is raised.

   :func:`decode` may print a warning to standard error if the input was produced
   by an incorrect uuencoder and Python could recover from that error.  Setting
   *quiet* to a true value silences this warning.


.. exception:: Error()

   Subclass of :exc:`Exception`, this can be raised by :func:`uu.decode` under
   various situations, such as described above, but also including a badly
   formatted header, or truncated input file.


.. seealso::

   Module :mod:`binascii`
      Support module containing ASCII-to-binary and binary-to-ASCII conversions.
PK
%�\ux� � "html/_sources/library/uuid.rst.txtnu�[���
:mod:`uuid` --- UUID objects according to RFC 4122
==================================================

.. module:: uuid
   :synopsis: UUID objects (universally unique identifiers) according to RFC 4122
.. moduleauthor:: Ka-Ping Yee <ping@zesty.ca>
.. sectionauthor:: George Yoshida <quiver@users.sourceforge.net>


.. versionadded:: 2.5

This module provides immutable :class:`UUID` objects (the :class:`UUID` class)
and the functions :func:`uuid1`, :func:`uuid3`, :func:`uuid4`, :func:`uuid5` for
generating version 1, 3, 4, and 5 UUIDs as specified in :rfc:`4122`.

If all you want is a unique ID, you should probably call :func:`uuid1` or
:func:`uuid4`.  Note that :func:`uuid1` may compromise privacy since it creates
a UUID containing the computer's network address.  :func:`uuid4` creates a
random UUID.


.. class:: UUID([hex[, bytes[, bytes_le[, fields[, int[, version]]]]]])

   Create a UUID from either a string of 32 hexadecimal digits, a string of 16
   bytes in big-endian order as the *bytes* argument, a string of 16 bytes in
   little-endian order as the *bytes_le* argument, a tuple of six integers
   (32-bit *time_low*, 16-bit *time_mid*, 16-bit *time_hi_version*,
   8-bit *clock_seq_hi_variant*, 8-bit *clock_seq_low*, 48-bit *node*) as the
   *fields* argument, or a single 128-bit integer as the *int* argument.
   When a string of hex digits is given, curly braces, hyphens,
   and a URN prefix are all optional.  For example, these
   expressions all yield the same UUID::

      UUID('{12345678-1234-5678-1234-567812345678}')
      UUID('12345678123456781234567812345678')
      UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
      UUID(bytes='\x12\x34\x56\x78'*4)
      UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
                    '\x12\x34\x56\x78\x12\x34\x56\x78')
      UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
      UUID(int=0x12345678123456781234567812345678)

   Exactly one of *hex*, *bytes*, *bytes_le*, *fields*, or *int* must be given.
   The *version* argument is optional; if given, the resulting UUID will have its
   variant and version number set according to RFC 4122, overriding bits in the
   given *hex*, *bytes*, *bytes_le*, *fields*, or *int*.

:class:`UUID` instances have these read-only attributes:


.. attribute:: UUID.bytes

   The UUID as a 16-byte string (containing the six integer fields in big-endian
   byte order).


.. attribute:: UUID.bytes_le

   The UUID as a 16-byte string (with *time_low*, *time_mid*, and *time_hi_version*
   in little-endian byte order).


.. attribute:: UUID.fields

   A tuple of the six integer fields of the UUID, which are also available as six
   individual attributes and two derived attributes:

   +------------------------------+-------------------------------+
   | Field                        | Meaning                       |
   +==============================+===============================+
   | :attr:`time_low`             | the first 32 bits of the UUID |
   +------------------------------+-------------------------------+
   | :attr:`time_mid`             | the next 16 bits of the UUID  |
   +------------------------------+-------------------------------+
   | :attr:`time_hi_version`      | the next 16 bits of the UUID  |
   +------------------------------+-------------------------------+
   | :attr:`clock_seq_hi_variant` | the next 8 bits of the UUID   |
   +------------------------------+-------------------------------+
   | :attr:`clock_seq_low`        | the next 8 bits of the UUID   |
   +------------------------------+-------------------------------+
   | :attr:`node`                 | the last 48 bits of the UUID  |
   +------------------------------+-------------------------------+
   | :attr:`time`                 | the 60-bit timestamp          |
   +------------------------------+-------------------------------+
   | :attr:`clock_seq`            | the 14-bit sequence number    |
   +------------------------------+-------------------------------+


.. attribute:: UUID.hex

   The UUID as a 32-character hexadecimal string.


.. attribute:: UUID.int

   The UUID as a 128-bit integer.


.. attribute:: UUID.urn

   The UUID as a URN as specified in RFC 4122.


.. attribute:: UUID.variant

   The UUID variant, which determines the internal layout of the UUID. This will be
   one of the constants :const:`RESERVED_NCS`, :const:`RFC_4122`,
   :const:`RESERVED_MICROSOFT`, or :const:`RESERVED_FUTURE`.


.. attribute:: UUID.version

   The UUID version number (1 through 5, meaningful only when the variant is
   :const:`RFC_4122`).

The :mod:`uuid` module defines the following functions:


.. function:: getnode()

   Get the hardware address as a 48-bit positive integer.  The first time this
   runs, it may launch a separate program, which could be quite slow.  If all
   attempts to obtain the hardware address fail, we choose a random 48-bit number
   with its eighth bit set to 1 as recommended in RFC 4122.  "Hardware address"
   means the MAC address of a network interface, and on a machine with multiple
   network interfaces the MAC address of any one of them may be returned.

.. index:: single: getnode


.. function:: uuid1([node[, clock_seq]])

   Generate a UUID from a host ID, sequence number, and the current time. If *node*
   is not given, :func:`getnode` is used to obtain the hardware address. If
   *clock_seq* is given, it is used as the sequence number; otherwise a random
   14-bit sequence number is chosen.

.. index:: single: uuid1


.. function:: uuid3(namespace, name)

   Generate a UUID based on the MD5 hash of a namespace identifier (which is a
   UUID) and a name (which is a string).

.. index:: single: uuid3


.. function:: uuid4()

   Generate a random UUID.

.. index:: single: uuid4


.. function:: uuid5(namespace, name)

   Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a
   UUID) and a name (which is a string).

.. index:: single: uuid5

The :mod:`uuid` module defines the following namespace identifiers for use with
:func:`uuid3` or :func:`uuid5`.


.. data:: NAMESPACE_DNS

   When this namespace is specified, the *name* string is a fully-qualified domain
   name.


.. data:: NAMESPACE_URL

   When this namespace is specified, the *name* string is a URL.


.. data:: NAMESPACE_OID

   When this namespace is specified, the *name* string is an ISO OID.


.. data:: NAMESPACE_X500

   When this namespace is specified, the *name* string is an X.500 DN in DER or a
   text output format.

The :mod:`uuid` module defines the following constants for the possible values
of the :attr:`variant` attribute:


.. data:: RESERVED_NCS

   Reserved for NCS compatibility.


.. data:: RFC_4122

   Specifies the UUID layout given in :rfc:`4122`.


.. data:: RESERVED_MICROSOFT

   Reserved for Microsoft compatibility.


.. data:: RESERVED_FUTURE

   Reserved for future definition.


.. seealso::

   :rfc:`4122` - A Universally Unique IDentifier (UUID) URN Namespace
      This specification defines a Uniform Resource Name namespace for UUIDs, the
      internal format of UUIDs, and methods of generating UUIDs.


.. _uuid-example:

Example
-------

Here are some examples of typical usage of the :mod:`uuid` module::

   >>> import uuid

   >>> # make a UUID based on the host ID and current time
   >>> uuid.uuid1()
   UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

   >>> # make a UUID using an MD5 hash of a namespace UUID and a name
   >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
   UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

   >>> # make a random UUID
   >>> uuid.uuid4()
   UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

   >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
   >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
   UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

   >>> # make a UUID from a string of hex digits (braces and hyphens ignored)
   >>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

   >>> # convert a UUID to a string of hex digits in standard form
   >>> str(x)
   '00010203-0405-0607-0809-0a0b0c0d0e0f'

   >>> # get the raw 16 bytes of the UUID
   >>> x.bytes
   '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

   >>> # make a UUID from a 16-byte string
   >>> uuid.UUID(bytes=x.bytes)
   UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

PK
%�\���6gMgM&html/_sources/library/warnings.rst.txtnu�[���:mod:`warnings` --- Warning control
===================================

.. index:: single: warnings

.. module:: warnings
   :synopsis: Issue warning messages and control their disposition.


.. versionadded:: 2.1

**Source code:** :source:`Lib/warnings.py`

--------------

Warning messages are typically issued in situations where it is useful to alert
the user of some condition in a program, where that condition (normally) doesn't
warrant raising an exception and terminating the program.  For example, one
might want to issue a warning when a program uses an obsolete module.

Python programmers issue warnings by calling the :func:`warn` function defined
in this module.  (C programmers use :c:func:`PyErr_WarnEx`; see
:ref:`exceptionhandling` for details).

Warning messages are normally written to ``sys.stderr``, but their disposition
can be changed flexibly, from ignoring all warnings to turning them into
exceptions.  The disposition of warnings can vary based on the warning category
(see below), the text of the warning message, and the source location where it
is issued.  Repetitions of a particular warning for the same source location are
typically suppressed.

There are two stages in warning control: first, each time a warning is issued, a
determination is made whether a message should be issued or not; next, if a
message is to be issued, it is formatted and printed using a user-settable hook.

The determination whether to issue a warning message is controlled by the
warning filter, which is a sequence of matching rules and actions. Rules can be
added to the filter by calling :func:`filterwarnings` and reset to its default
state by calling :func:`resetwarnings`.

The printing of warning messages is done by calling :func:`showwarning`, which
may be overridden; the default implementation of this function formats the
message by calling :func:`formatwarning`, which is also available for use by
custom implementations.

.. seealso::
   :func:`logging.captureWarnings` allows you to handle all warnings with
   the standard logging infrastructure.


.. _warning-categories:

Warning Categories
------------------

There are a number of built-in exceptions that represent warning categories.
This categorization is useful to be able to filter out groups of warnings.  The
following warnings category classes are currently defined:

.. tabularcolumns:: |l|p{0.6\linewidth}|

+----------------------------------+-----------------------------------------------+
| Class                            | Description                                   |
+==================================+===============================================+
| :exc:`Warning`                   | This is the base class of all warning         |
|                                  | category classes.  It is a subclass of        |
|                                  | :exc:`Exception`.                             |
+----------------------------------+-----------------------------------------------+
| :exc:`UserWarning`               | The default category for :func:`warn`.        |
+----------------------------------+-----------------------------------------------+
| :exc:`DeprecationWarning`        | Base category for warnings about deprecated   |
|                                  | features (ignored by default).                |
+----------------------------------+-----------------------------------------------+
| :exc:`SyntaxWarning`             | Base category for warnings about dubious      |
|                                  | syntactic features.                           |
+----------------------------------+-----------------------------------------------+
| :exc:`RuntimeWarning`            | Base category for warnings about dubious      |
|                                  | runtime features.                             |
+----------------------------------+-----------------------------------------------+
| :exc:`FutureWarning`             | Base category for warnings about constructs   |
|                                  | that will change semantically in the future.  |
+----------------------------------+-----------------------------------------------+
| :exc:`PendingDeprecationWarning` | Base category for warnings about features     |
|                                  | that will be deprecated in the future         |
|                                  | (ignored by default).                         |
+----------------------------------+-----------------------------------------------+
| :exc:`ImportWarning`             | Base category for warnings triggered during   |
|                                  | the process of importing a module (ignored by |
|                                  | default).                                     |
+----------------------------------+-----------------------------------------------+
| :exc:`UnicodeWarning`            | Base category for warnings related to         |
|                                  | Unicode.                                      |
+----------------------------------+-----------------------------------------------+

While these are technically built-in exceptions, they are documented here,
because conceptually they belong to the warnings mechanism.

User code can define additional warning categories by subclassing one of the
standard warning categories.  A warning category must always be a subclass of
the :exc:`Warning` class.

.. versionchanged:: 2.7
   :exc:`DeprecationWarning` is ignored by default.


.. _warning-filter:

The Warnings Filter
-------------------

The warnings filter controls whether warnings are ignored, displayed, or turned
into errors (raising an exception).

Conceptually, the warnings filter maintains an ordered list of filter
specifications; any specific warning is matched against each filter
specification in the list in turn until a match is found; the match determines
the disposition of the match.  Each entry is a tuple of the form (*action*,
*message*, *category*, *module*, *lineno*), where:

* *action* is one of the following strings:

  +---------------+----------------------------------------------+
  | Value         | Disposition                                  |
  +===============+==============================================+
  | ``"error"``   | turn matching warnings into exceptions       |
  +---------------+----------------------------------------------+
  | ``"ignore"``  | never print matching warnings                |
  +---------------+----------------------------------------------+
  | ``"always"``  | always print matching warnings               |
  +---------------+----------------------------------------------+
  | ``"default"`` | print the first occurrence of matching       |
  |               | warnings for each location where the warning |
  |               | is issued                                    |
  +---------------+----------------------------------------------+
  | ``"module"``  | print the first occurrence of matching       |
  |               | warnings for each module where the warning   |
  |               | is issued                                    |
  +---------------+----------------------------------------------+
  | ``"once"``    | print only the first occurrence of matching  |
  |               | warnings, regardless of location             |
  +---------------+----------------------------------------------+

* *message* is a string containing a regular expression that the start of
  the warning message must match.  The expression is compiled to always be
  case-insensitive.

* *category* is a class (a subclass of :exc:`Warning`) of which the warning
  category must be a subclass in order to match.

* *module* is a string containing a regular expression that the module name must
  match.  The expression is compiled to be case-sensitive.

* *lineno* is an integer that the line number where the warning occurred must
  match, or ``0`` to match all line numbers.

Since the :exc:`Warning` class is derived from the built-in :exc:`Exception`
class, to turn a warning into an error we simply raise ``category(message)``.

The warnings filter is initialized by :option:`-W` options passed to the Python
interpreter command line.  The interpreter saves the arguments for all
:option:`-W` options without interpretation in ``sys.warnoptions``; the
:mod:`warnings` module parses these when it is first imported (invalid options
are ignored, after printing a message to ``sys.stderr``).


Default Warning Filters
~~~~~~~~~~~~~~~~~~~~~~~

By default, Python installs several warning filters, which can be overridden by
the command-line options passed to :option:`-W` and calls to
:func:`filterwarnings`.

* :exc:`DeprecationWarning` and :exc:`PendingDeprecationWarning`, and
  :exc:`ImportWarning` are ignored.

* :exc:`BytesWarning` is ignored unless the :option:`-b` option is given once or
  twice; in this case this warning is either printed (``-b``) or turned into an
  exception (``-bb``).


.. _warning-suppress:

Temporarily Suppressing Warnings
--------------------------------

If you are using code that you know will raise a warning, such as a deprecated
function, but do not want to see the warning, then it is possible to suppress
the warning using the :class:`catch_warnings` context manager::

    import warnings

    def fxn():
        warnings.warn("deprecated", DeprecationWarning)

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        fxn()

While within the context manager all warnings will simply be ignored. This
allows you to use known-deprecated code without having to see the warning while
not suppressing the warning for other code that might not be aware of its use
of deprecated code.  Note: this can only be guaranteed in a single-threaded
application. If two or more threads use the :class:`catch_warnings` context
manager at the same time, the behavior is undefined.



.. _warning-testing:

Testing Warnings
----------------

To test warnings raised by code, use the :class:`catch_warnings` context
manager. With it you can temporarily mutate the warnings filter to facilitate
your testing. For instance, do the following to capture all raised warnings to
check::

    import warnings

    def fxn():
        warnings.warn("deprecated", DeprecationWarning)

    with warnings.catch_warnings(record=True) as w:
        # Cause all warnings to always be triggered.
        warnings.simplefilter("always")
        # Trigger a warning.
        fxn()
        # Verify some things
        assert len(w) == 1
        assert issubclass(w[-1].category, DeprecationWarning)
        assert "deprecated" in str(w[-1].message)

One can also cause all warnings to be exceptions by using ``error`` instead of
``always``. One thing to be aware of is that if a warning has already been
raised because of a ``once``/``default`` rule, then no matter what filters are
set the warning will not be seen again unless the warnings registry related to
the warning has been cleared.

Once the context manager exits, the warnings filter is restored to its state
when the context was entered. This prevents tests from changing the warnings
filter in unexpected ways between tests and leading to indeterminate test
results. The :func:`showwarning` function in the module is also restored to
its original value.  Note: this can only be guaranteed in a single-threaded
application. If two or more threads use the :class:`catch_warnings` context
manager at the same time, the behavior is undefined.

When testing multiple operations that raise the same kind of warning, it
is important to test them in a manner that confirms each operation is raising
a new warning (e.g. set warnings to be raised as exceptions and check the
operations raise exceptions, check that the length of the warning list
continues to increase after each operation, or else delete the previous
entries from the warnings list before each new operation).


Updating Code For New Versions of Python
----------------------------------------

Warnings that are only of interest to the developer are ignored by default. As
such you should make sure to test your code with typically ignored warnings
made visible. You can do this from the command-line by passing :option:`-Wd <-W>`
to the interpreter (this is shorthand for :option:`!-W default`).  This enables
default handling for all warnings, including those that are ignored by default.
To change what action is taken for encountered warnings you simply change what
argument is passed to :option:`-W`, e.g. :option:`!-W error`. See the
:option:`-W` flag for more details on what is possible.

To programmatically do the same as :option:`!-Wd`, use::

  warnings.simplefilter('default')

Make sure to execute this code as soon as possible. This prevents the
registering of what warnings have been raised from unexpectedly influencing how
future warnings are treated.

Having certain warnings ignored by default is done to prevent a user from
seeing warnings that are only of interest to the developer. As you do not
necessarily have control over what interpreter a user uses to run their code,
it is possible that a new version of Python will be released between your
release cycles.  The new interpreter release could trigger new warnings in your
code that were not there in an older interpreter, e.g.
:exc:`DeprecationWarning` for a module that you are using. While you as a
developer want to be notified that your code is using a deprecated module, to a
user this information is essentially noise and provides no benefit to them.


.. _warning-functions:

Available Functions
-------------------


.. function:: warn(message[, category[, stacklevel]])

   Issue a warning, or maybe ignore it or raise an exception.  The *category*
   argument, if given, must be a warning category class (see above); it defaults to
   :exc:`UserWarning`.  Alternatively *message* can be a :exc:`Warning` instance,
   in which case *category* will be ignored and ``message.__class__`` will be used.
   In this case the message text will be ``str(message)``. This function raises an
   exception if the particular warning issued is changed into an error by the
   warnings filter see above.  The *stacklevel* argument can be used by wrapper
   functions written in Python, like this::

      def deprecation(message):
          warnings.warn(message, DeprecationWarning, stacklevel=2)

   This makes the warning refer to :func:`deprecation`'s caller, rather than to the
   source of :func:`deprecation` itself (since the latter would defeat the purpose
   of the warning message).


.. function:: warn_explicit(message, category, filename, lineno[, module[, registry[, module_globals]]])

   This is a low-level interface to the functionality of :func:`warn`, passing in
   explicitly the message, category, filename and line number, and optionally the
   module name and the registry (which should be the ``__warningregistry__``
   dictionary of the module).  The module name defaults to the filename with
   ``.py`` stripped; if no registry is passed, the warning is never suppressed.
   *message* must be a string and *category* a subclass of :exc:`Warning` or
   *message* may be a :exc:`Warning` instance, in which case *category* will be
   ignored.

   *module_globals*, if supplied, should be the global namespace in use by the code
   for which the warning is issued.  (This argument is used to support displaying
   source for modules found in zipfiles or other non-filesystem import
   sources).

   .. versionchanged:: 2.5
      Added the *module_globals* parameter.


.. function:: warnpy3k(message[, category[, stacklevel]])

   Issue a warning related to Python 3.x deprecation. Warnings are only shown
   when Python is started with the -3 option. Like :func:`warn` *message* must
   be a string and *category* a subclass of :exc:`Warning`. :func:`warnpy3k`
   is using :exc:`DeprecationWarning` as default warning class.

   .. versionadded:: 2.6


.. function:: showwarning(message, category, filename, lineno[, file[, line]])

   Write a warning to a file.  The default implementation calls
   ``formatwarning(message, category, filename, lineno, line)`` and writes the
   resulting string to *file*, which defaults to ``sys.stderr``.  You may replace
   this function with an alternative implementation by assigning to
   ``warnings.showwarning``.
   *line* is a line of source code to be included in the warning
   message; if *line* is not supplied, :func:`showwarning` will
   try to read the line specified by *filename* and *lineno*.

   .. versionchanged:: 2.7
      The *line* argument is required to be supported.


.. function:: formatwarning(message, category, filename, lineno[, line])

   Format a warning the standard way.  This returns a string which may contain
   embedded newlines and ends in a newline.  *line* is a line of source code to
   be included in the warning message; if *line* is not supplied,
   :func:`formatwarning` will try to read the line specified by *filename* and
   *lineno*.

   .. versionchanged:: 2.6
      Added the *line* argument.


.. function:: filterwarnings(action[, message[, category[, module[, lineno[, append]]]]])

   Insert an entry into the list of :ref:`warnings filter specifications
   <warning-filter>`.  The entry is inserted at the front by default; if
   *append* is true, it is inserted at the end.  This checks the types of the
   arguments, compiles the *message* and *module* regular expressions, and
   inserts them as a tuple in the list of warnings filters.  Entries closer to
   the front of the list override entries later in the list, if both match a
   particular warning.  Omitted arguments default to a value that matches
   everything.


.. function:: simplefilter(action[, category[, lineno[, append]]])

   Insert a simple entry into the list of :ref:`warnings filter specifications
   <warning-filter>`.  The meaning of the function parameters is as for
   :func:`filterwarnings`, but regular expressions are not needed as the filter
   inserted always matches any message in any module as long as the category and
   line number match.


.. function:: resetwarnings()

   Reset the warnings filter.  This discards the effect of all previous calls to
   :func:`filterwarnings`, including that of the :option:`-W` command line options
   and calls to :func:`simplefilter`.


Available Context Managers
--------------------------

.. class:: catch_warnings([\*, record=False, module=None])

    A context manager that copies and, upon exit, restores the warnings filter
    and the :func:`showwarning` function.
    If the *record* argument is :const:`False` (the default) the context manager
    returns :class:`None` on entry. If *record* is :const:`True`, a list is
    returned that is progressively populated with objects as seen by a custom
    :func:`showwarning` function (which also suppresses output to ``sys.stdout``).
    Each object in the list has attributes with the same names as the arguments to
    :func:`showwarning`.

    The *module* argument takes a module that will be used instead of the
    module returned when you import :mod:`warnings` whose filter will be
    protected. This argument exists primarily for testing the :mod:`warnings`
    module itself.

    .. note::

        The :class:`catch_warnings` manager works by replacing and
        then later restoring the module's
        :func:`showwarning` function and internal list of filter
        specifications.  This means the context manager is modifying
        global state and therefore is not thread-safe.

    .. note::

        In Python 3, the arguments to the constructor for
        :class:`catch_warnings` are keyword-only arguments.

    .. versionadded:: 2.6

PK
%�\G)D���"html/_sources/library/wave.rst.txtnu�[���:mod:`wave` --- Read and write WAV files
========================================

.. module:: wave
   :synopsis: Provide an interface to the WAV sound format.
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
.. Documentations stolen from comments in file.

**Source code:** :source:`Lib/wave.py`

--------------

The :mod:`wave` module provides a convenient interface to the WAV sound format.
It does not support compression/decompression, but it does support mono/stereo.

The :mod:`wave` module defines the following function and exception:


.. function:: open(file[, mode])

   If *file* is a string, open the file by that name, otherwise treat it as a
   seekable file-like object.  *mode* can be any of

   ``'r'``, ``'rb'``
      Read only mode.

   ``'w'``, ``'wb'``
      Write only mode.

   Note that it does not allow read/write WAV files.

   A *mode* of ``'r'`` or ``'rb'`` returns a :class:`Wave_read` object, while a
   *mode* of ``'w'`` or ``'wb'`` returns a :class:`Wave_write` object.  If
   *mode* is omitted and a file-like object is passed as *file*, ``file.mode``
   is used as the default value for *mode* (the ``'b'`` flag is still added if
   necessary).

   If you pass in a file-like object, the wave object will not close it when its
   :meth:`close` method is called; it is the caller's responsibility to close
   the file object.


.. function:: openfp(file, mode)

   A synonym for :func:`.open`, maintained for backwards compatibility.


.. exception:: Error

   An error raised when something is impossible because it violates the WAV
   specification or hits an implementation deficiency.


.. _wave-read-objects:

Wave_read Objects
-----------------

Wave_read objects, as returned by :func:`.open`, have the following methods:


.. method:: Wave_read.close()

   Close the stream if it was opened by :mod:`wave`, and make the instance
   unusable.  This is called automatically on object collection.


.. method:: Wave_read.getnchannels()

   Returns number of audio channels (``1`` for mono, ``2`` for stereo).


.. method:: Wave_read.getsampwidth()

   Returns sample width in bytes.


.. method:: Wave_read.getframerate()

   Returns sampling frequency.


.. method:: Wave_read.getnframes()

   Returns number of audio frames.


.. method:: Wave_read.getcomptype()

   Returns compression type (``'NONE'`` is the only supported type).


.. method:: Wave_read.getcompname()

   Human-readable version of :meth:`getcomptype`. Usually ``'not compressed'``
   parallels ``'NONE'``.


.. method:: Wave_read.getparams()

   Returns a tuple ``(nchannels, sampwidth, framerate, nframes, comptype,
   compname)``, equivalent to output of the :meth:`get\*` methods.


.. method:: Wave_read.readframes(n)

   Reads and returns at most *n* frames of audio, as a string of bytes.


.. method:: Wave_read.rewind()

   Rewind the file pointer to the beginning of the audio stream.

The following two methods are defined for compatibility with the :mod:`aifc`
module, and don't do anything interesting.


.. method:: Wave_read.getmarkers()

   Returns ``None``.


.. method:: Wave_read.getmark(id)

   Raise an error.

The following two methods define a term "position" which is compatible between
them, and is otherwise implementation dependent.


.. method:: Wave_read.setpos(pos)

   Set the file pointer to the specified position.


.. method:: Wave_read.tell()

   Return current file pointer position.


.. _wave-write-objects:

Wave_write Objects
------------------

Wave_write objects, as returned by :func:`.open`, have the following methods:


.. method:: Wave_write.close()

   Make sure *nframes* is correct, and close the file if it was opened by
   :mod:`wave`.  This method is called upon object collection.


.. method:: Wave_write.setnchannels(n)

   Set the number of channels.


.. method:: Wave_write.setsampwidth(n)

   Set the sample width to *n* bytes.


.. method:: Wave_write.setframerate(n)

   Set the frame rate to *n*.


.. method:: Wave_write.setnframes(n)

   Set the number of frames to *n*. This will be changed later if more frames are
   written.


.. method:: Wave_write.setcomptype(type, name)

   Set the compression type and description. At the moment, only compression type
   ``NONE`` is supported, meaning no compression.


.. method:: Wave_write.setparams(tuple)

   The *tuple* should be ``(nchannels, sampwidth, framerate, nframes, comptype,
   compname)``, with values valid for the :meth:`set\*` methods.  Sets all
   parameters.


.. method:: Wave_write.tell()

   Return current position in the file, with the same disclaimer for the
   :meth:`Wave_read.tell` and :meth:`Wave_read.setpos` methods.


.. method:: Wave_write.writeframesraw(data)

   Write audio frames, without correcting *nframes*.


.. method:: Wave_write.writeframes(data)

   Write audio frames and make sure *nframes* is correct.


Note that it is invalid to set any parameters after calling :meth:`writeframes`
or :meth:`writeframesraw`, and any attempt to do so will raise
:exc:`wave.Error`.

PK
%�\�1�W~2~2%html/_sources/library/weakref.rst.txtnu�[���:mod:`weakref` --- Weak references
==================================

.. module:: weakref
   :synopsis: Support for weak references and weak dictionaries.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. moduleauthor:: Neil Schemenauer <nas@arctrix.com>
.. moduleauthor:: Martin von Löwis <martin@loewis.home.cs.tu-berlin.de>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. versionadded:: 2.1

**Source code:** :source:`Lib/weakref.py`

--------------

The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
references` to objects.

.. When making changes to the examples in this file, be sure to update
   Lib/test/test_weakref.py::libreftest too!

In the following, the term :dfn:`referent` means the object which is referred to
by a weak reference.

A weak reference to an object is not enough to keep the object alive: when the
only remaining references to a referent are weak references,
:term:`garbage collection` is free to destroy the referent and reuse its memory
for something else.  A primary use for weak references is to implement caches or
mappings holding large objects, where it's desired that a large object not be
kept alive solely because it appears in a cache or mapping.

For example, if you have a number of large binary image objects, you may wish to
associate a name with each.  If you used a Python dictionary to map names to
images, or images to names, the image objects would remain alive just because
they appeared as values or keys in the dictionaries.  The
:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` classes supplied by
the :mod:`weakref` module are an alternative, using weak references to construct
mappings that don't keep objects alive solely because they appear in the mapping
objects.  If, for example, an image object is a value in a
:class:`WeakValueDictionary`, then when the last remaining references to that
image object are the weak references held by weak mappings, garbage collection
can reclaim the object, and its corresponding entries in weak mappings are
simply deleted.

:class:`WeakKeyDictionary` and :class:`WeakValueDictionary` use weak references
in their implementation, setting up callback functions on the weak references
that notify the weak dictionaries when a key or value has been reclaimed by
garbage collection.  Most programs should find that using one of these weak
dictionary types is all they need -- it's not usually necessary to create your
own weak references directly.  The low-level machinery used by the weak
dictionary implementations is exposed by the :mod:`weakref` module for the
benefit of advanced uses.

Not all objects can be weakly referenced; those objects which can include class
instances, functions written in Python (but not in C), methods (both bound and
unbound), sets, frozensets, file objects, :term:`generator`\s, type objects,
:class:`DBcursor` objects from the :mod:`bsddb` module, sockets, arrays, deques,
regular expression pattern objects, and code objects.

.. versionchanged:: 2.4
   Added support for files, sockets, arrays, and patterns.

.. versionchanged:: 2.7
   Added support for thread.lock, threading.Lock, and code objects.

Several built-in types such as :class:`list` and :class:`dict` do not directly
support weak references but can add support through subclassing::

   class Dict(dict):
       pass

   obj = Dict(red=1, green=2, blue=3)   # this object is weak referenceable

.. impl-detail::

   Other built-in types such as :class:`tuple` and :class:`long` do not support
   weak references even when subclassed.

Extension types can easily be made to support weak references; see
:ref:`weakref-support`.


.. class:: ref(object[, callback])

   Return a weak reference to *object*.  The original object can be retrieved by
   calling the reference object if the referent is still alive; if the referent is
   no longer alive, calling the reference object will cause :const:`None` to be
   returned.  If *callback* is provided and not :const:`None`, and the returned
   weakref object is still alive, the callback will be called when the object is
   about to be finalized; the weak reference object will be passed as the only
   parameter to the callback; the referent will no longer be available.

   It is allowable for many weak references to be constructed for the same object.
   Callbacks registered for each weak reference will be called from the most
   recently registered callback to the oldest registered callback.

   Exceptions raised by the callback will be noted on the standard error output,
   but cannot be propagated; they are handled in exactly the same way as exceptions
   raised from an object's :meth:`__del__` method.

   Weak references are :term:`hashable` if the *object* is hashable.  They will maintain
   their hash value even after the *object* was deleted.  If :func:`hash` is called
   the first time only after the *object* was deleted, the call will raise
   :exc:`TypeError`.

   Weak references support tests for equality, but not ordering.  If the referents
   are still alive, two references have the same equality relationship as their
   referents (regardless of the *callback*).  If either referent has been deleted,
   the references are equal only if the reference objects are the same object.

   .. versionchanged:: 2.4
      This is now a subclassable type rather than a factory function; it derives from
      :class:`object`.


.. function:: proxy(object[, callback])

   Return a proxy to *object* which uses a weak reference.  This supports use of
   the proxy in most contexts instead of requiring the explicit dereferencing used
   with weak reference objects.  The returned object will have a type of either
   ``ProxyType`` or ``CallableProxyType``, depending on whether *object* is
   callable.  Proxy objects are not :term:`hashable` regardless of the referent; this
   avoids a number of problems related to their fundamentally mutable nature, and
   prevent their use as dictionary keys.  *callback* is the same as the parameter
   of the same name to the :func:`ref` function.


.. function:: getweakrefcount(object)

   Return the number of weak references and proxies which refer to *object*.


.. function:: getweakrefs(object)

   Return a list of all weak reference and proxy objects which refer to *object*.


.. class:: WeakKeyDictionary([dict])

   Mapping class that references keys weakly.  Entries in the dictionary will be
   discarded when there is no longer a strong reference to the key.  This can be
   used to associate additional data with an object owned by other parts of an
   application without adding attributes to those objects.  This can be especially
   useful with objects that override attribute accesses.

   .. note::

      Caution: Because a :class:`WeakKeyDictionary` is built on top of a Python
      dictionary, it must not change size when iterating over it.  This can be
      difficult to ensure for a :class:`WeakKeyDictionary` because actions
      performed by the program during iteration may cause items in the
      dictionary to vanish "by magic" (as a side effect of garbage collection).

:class:`WeakKeyDictionary` objects have the following additional methods.  These
expose the internal references directly.  The references are not guaranteed to
be "live" at the time they are used, so the result of calling the references
needs to be checked before being used.  This can be used to avoid creating
references that will cause the garbage collector to keep the keys around longer
than needed.


.. method:: WeakKeyDictionary.iterkeyrefs()

   Return an iterable of the weak references to the keys.

   .. versionadded:: 2.5


.. method:: WeakKeyDictionary.keyrefs()

   Return a list of weak references to the keys.

   .. versionadded:: 2.5


.. class:: WeakValueDictionary([dict])

   Mapping class that references values weakly.  Entries in the dictionary will be
   discarded when no strong reference to the value exists any more.

   .. note::

      Caution:  Because a :class:`WeakValueDictionary` is built on top of a Python
      dictionary, it must not change size when iterating over it.  This can be
      difficult to ensure for a :class:`WeakValueDictionary` because actions performed
      by the program during iteration may cause items in the dictionary to vanish "by
      magic" (as a side effect of garbage collection).

:class:`WeakValueDictionary` objects have the following additional methods.
These methods have the same issues as the :meth:`iterkeyrefs` and
:meth:`keyrefs` methods of :class:`WeakKeyDictionary` objects.


.. method:: WeakValueDictionary.itervaluerefs()

   Return an iterable of the weak references to the values.

   .. versionadded:: 2.5


.. method:: WeakValueDictionary.valuerefs()

   Return a list of weak references to the values.

   .. versionadded:: 2.5


.. class:: WeakSet([elements])

   Set class that keeps weak references to its elements.  An element will be
   discarded when no strong reference to it exists any more.

   .. versionadded:: 2.7


.. data:: ReferenceType

   The type object for weak references objects.


.. data:: ProxyType

   The type object for proxies of objects which are not callable.


.. data:: CallableProxyType

   The type object for proxies of callable objects.


.. data:: ProxyTypes

   Sequence containing all the type objects for proxies.  This can make it simpler
   to test if an object is a proxy without being dependent on naming both proxy
   types.


.. exception:: ReferenceError

   Exception raised when a proxy object is used but the underlying object has been
   collected.  This is the same as the standard :exc:`ReferenceError` exception.


.. seealso::

   :pep:`205` - Weak References
      The proposal and rationale for this feature, including links to earlier
      implementations and information about similar features in other languages.


.. _weakref-objects:

Weak Reference Objects
----------------------

Weak reference objects have no attributes or methods, but do allow the referent
to be obtained, if it still exists, by calling it:

   >>> import weakref
   >>> class Object:
   ...     pass
   ...
   >>> o = Object()
   >>> r = weakref.ref(o)
   >>> o2 = r()
   >>> o is o2
   True

If the referent no longer exists, calling the reference object returns
:const:`None`:

   >>> del o, o2
   >>> print r()
   None

Testing that a weak reference object is still live should be done using the
expression ``ref() is not None``.  Normally, application code that needs to use
a reference object should follow this pattern::

   # r is a weak reference object
   o = r()
   if o is None:
       # referent has been garbage collected
       print "Object has been deallocated; can't frobnicate."
   else:
       print "Object is still live!"
       o.do_something_useful()

Using a separate test for "liveness" creates race conditions in threaded
applications; another thread can cause a weak reference to become invalidated
before the weak reference is called; the idiom shown above is safe in threaded
applications as well as single-threaded applications.

Specialized versions of :class:`ref` objects can be created through subclassing.
This is used in the implementation of the :class:`WeakValueDictionary` to reduce
the memory overhead for each entry in the mapping.  This may be most useful to
associate additional information with a reference, but could also be used to
insert additional processing on calls to retrieve the referent.

This example shows how a subclass of :class:`ref` can be used to store
additional information about an object and affect the value that's returned when
the referent is accessed::

   import weakref

   class ExtendedRef(weakref.ref):
       def __init__(self, ob, callback=None, **annotations):
           super(ExtendedRef, self).__init__(ob, callback)
           self.__counter = 0
           for k, v in annotations.iteritems():
               setattr(self, k, v)

       def __call__(self):
           """Return a pair containing the referent and the number of
           times the reference has been called.
           """
           ob = super(ExtendedRef, self).__call__()
           if ob is not None:
               self.__counter += 1
               ob = (ob, self.__counter)
           return ob


.. _weakref-example:

Example
-------

This simple example shows how an application can use object IDs to retrieve
objects that it has seen before.  The IDs of the objects can then be used in
other data structures without forcing the objects to remain alive, but the
objects can still be retrieved by ID if they do.

.. Example contributed by Tim Peters.

::

   import weakref

   _id2obj_dict = weakref.WeakValueDictionary()

   def remember(obj):
       oid = id(obj)
       _id2obj_dict[oid] = obj
       return oid

   def id2obj(oid):
       return _id2obj_dict[oid]

PK
%�\	�Ň&�&(html/_sources/library/webbrowser.rst.txtnu�[���:mod:`webbrowser` --- Convenient Web-browser controller
=======================================================

.. module:: webbrowser
   :synopsis: Easy-to-use controller for Web browsers.
.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>

**Source code:** :source:`Lib/webbrowser.py`

--------------

The :mod:`webbrowser` module provides a high-level interface to allow displaying
Web-based documents to users. Under most circumstances, simply calling the
:func:`.open` function from this module will do the right thing.

Under Unix, graphical browsers are preferred under X11, but text-mode browsers
will be used if graphical browsers are not available or an X11 display isn't
available.  If text-mode browsers are used, the calling process will block until
the user exits the browser.

If the environment variable :envvar:`BROWSER` exists, it is interpreted to
override the platform default list of browsers, as an :data:`os.pathsep`-separated
list of browsers to try in order.  When the value of a list part contains the
string ``%s``, then it is  interpreted as a literal browser command line to be
used with the argument URL substituted for ``%s``; if the part does not contain
``%s``, it is simply interpreted as the name of the browser to launch. [1]_

For non-Unix platforms, or when a remote browser is available on Unix, the
controlling process will not wait for the user to finish with the browser, but
allow the remote browser to maintain its own windows on the display.  If remote
browsers are not available on Unix, the controlling process will launch a new
browser and wait.

The script :program:`webbrowser` can be used as a command-line interface for the
module. It accepts a URL as the argument. It accepts the following optional
parameters: ``-n`` opens the URL in a new browser window, if possible;
``-t`` opens the URL in a new browser page ("tab"). The options are,
naturally, mutually exclusive.  Usage example::

   python -m webbrowser -t "http://www.python.org"

The following exception is defined:


.. exception:: Error

   Exception raised when a browser control error occurs.

The following functions are defined:


.. function:: open(url, new=0, autoraise=True)

   Display *url* using the default browser. If *new* is 0, the *url* is opened
   in the same browser window if possible.  If *new* is 1, a new browser window
   is opened if possible.  If *new* is 2, a new browser page ("tab") is opened
   if possible.  If *autoraise* is ``True``, the window is raised if possible
   (note that under many window managers this will occur regardless of the
   setting of this variable).

   Note that on some platforms, trying to open a filename using this function,
   may work and start the operating system's associated program.  However, this
   is neither supported nor portable.

   .. versionchanged:: 2.5
      *new* can now be 2.


.. function:: open_new(url)

   Open *url* in a new window of the default browser, if possible, otherwise, open
   *url* in the only browser window.

.. function:: open_new_tab(url)

   Open *url* in a new page ("tab") of the default browser, if possible, otherwise
   equivalent to :func:`open_new`.

   .. versionadded:: 2.5


.. function:: get([name])

   Return a controller object for the browser type *name*.  If *name* is empty,
   return a controller for a default browser appropriate to the caller's
   environment.


.. function:: register(name, constructor[, instance])

   Register the browser type *name*.  Once a browser type is registered, the
   :func:`get` function can return a controller for that browser type.  If
   *instance* is not provided, or is ``None``, *constructor* will be called without
   parameters to create an instance when needed.  If *instance* is provided,
   *constructor* will never be called, and may be ``None``.

   This entry point is only useful if you plan to either set the :envvar:`BROWSER`
   variable or call :func:`get` with a nonempty argument matching the name of a
   handler you declare.

A number of browser types are predefined.  This table gives the type names that
may be passed to the :func:`get` function and the corresponding instantiations
for the controller classes, all defined in this module.

+-----------------------+-----------------------------------------+-------+
| Type Name             | Class Name                              | Notes |
+=======================+=========================================+=======+
| ``'mozilla'``         | :class:`Mozilla('mozilla')`             |       |
+-----------------------+-----------------------------------------+-------+
| ``'firefox'``         | :class:`Mozilla('mozilla')`             |       |
+-----------------------+-----------------------------------------+-------+
| ``'netscape'``        | :class:`Mozilla('netscape')`            |       |
+-----------------------+-----------------------------------------+-------+
| ``'galeon'``          | :class:`Galeon('galeon')`               |       |
+-----------------------+-----------------------------------------+-------+
| ``'epiphany'``        | :class:`Galeon('epiphany')`             |       |
+-----------------------+-----------------------------------------+-------+
| ``'skipstone'``       | :class:`BackgroundBrowser('skipstone')` |       |
+-----------------------+-----------------------------------------+-------+
| ``'kfmclient'``       | :class:`Konqueror()`                    | \(1)  |
+-----------------------+-----------------------------------------+-------+
| ``'konqueror'``       | :class:`Konqueror()`                    | \(1)  |
+-----------------------+-----------------------------------------+-------+
| ``'kfm'``             | :class:`Konqueror()`                    | \(1)  |
+-----------------------+-----------------------------------------+-------+
| ``'mosaic'``          | :class:`BackgroundBrowser('mosaic')`    |       |
+-----------------------+-----------------------------------------+-------+
| ``'opera'``           | :class:`Opera()`                        |       |
+-----------------------+-----------------------------------------+-------+
| ``'grail'``           | :class:`Grail()`                        |       |
+-----------------------+-----------------------------------------+-------+
| ``'links'``           | :class:`GenericBrowser('links')`        |       |
+-----------------------+-----------------------------------------+-------+
| ``'elinks'``          | :class:`Elinks('elinks')`               |       |
+-----------------------+-----------------------------------------+-------+
| ``'lynx'``            | :class:`GenericBrowser('lynx')`         |       |
+-----------------------+-----------------------------------------+-------+
| ``'w3m'``             | :class:`GenericBrowser('w3m')`          |       |
+-----------------------+-----------------------------------------+-------+
| ``'windows-default'`` | :class:`WindowsDefault`                 | \(2)  |
+-----------------------+-----------------------------------------+-------+
| ``'macosx'``          | :class:`MacOSX('default')`              | \(3)  |
+-----------------------+-----------------------------------------+-------+
| ``'safari'``          | :class:`MacOSX('safari')`               | \(3)  |
+-----------------------+-----------------------------------------+-------+
| ``'google-chrome'``   | :class:`Chrome('google-chrome')`        | \(4)  |
+-----------------------+-----------------------------------------+-------+
| ``'chrome'``          | :class:`Chrome('chrome')`               | \(4)  |
+-----------------------+-----------------------------------------+-------+
| ``'chromium'``        | :class:`Chromium('chromium')`           | \(4)  |
+-----------------------+-----------------------------------------+-------+
| ``'chromium-browser'``| :class:`Chromium('chromium-browser')`   | \(4)  |
+-----------------------+-----------------------------------------+-------+

Notes:

(1)
   "Konqueror" is the file manager for the KDE desktop environment for Unix, and
   only makes sense to use if KDE is running.  Some way of reliably detecting KDE
   would be nice; the :envvar:`KDEDIR` variable is not sufficient.  Note also that
   the name "kfm" is used even when using the :program:`konqueror` command with KDE
   2 --- the implementation selects the best strategy for running Konqueror.

(2)
   Only on Windows platforms.

(3)
   Only on Mac OS X platform.

(4)
   Support for Chrome/Chromium has been added in version 2.7.5.

Here are some simple examples::

   url = 'http://www.python.org/'

   # Open URL in a new tab, if a browser window is already open.
   webbrowser.open_new_tab(url + 'doc/')

   # Open URL in new window, raising the window if possible.
   webbrowser.open_new(url)


.. _browser-controllers:

Browser Controller Objects
--------------------------

Browser controllers provide these methods which parallel three of the
module-level convenience functions:


.. method:: controller.open(url, new=0, autoraise=True)

   Display *url* using the browser handled by this controller. If *new* is 1, a new
   browser window is opened if possible. If *new* is 2, a new browser page ("tab")
   is opened if possible.


.. method:: controller.open_new(url)

   Open *url* in a new window of the browser handled by this controller, if
   possible, otherwise, open *url* in the only browser window.  Alias
   :func:`open_new`.


.. method:: controller.open_new_tab(url)

   Open *url* in a new page ("tab") of the browser handled by this controller, if
   possible, otherwise equivalent to :func:`open_new`.

   .. versionadded:: 2.5


.. rubric:: Footnotes

.. [1] Executables named here without a full path will be searched in the
       directories given in the :envvar:`PATH` environment variable.
PK
%�\3�p_��%html/_sources/library/whichdb.rst.txtnu�[���:mod:`whichdb` --- Guess which DBM module created a database
============================================================

.. module:: whichdb
   :synopsis: Guess which DBM-style module created a given database.

.. note::
   The :mod:`whichdb` module's only function has been put into the :mod:`dbm`
   module in Python 3.  The :term:`2to3` tool will automatically adapt imports
   when converting your sources to Python 3.


The single function in this module attempts to guess which of the several simple
database modules available—:mod:`dbm`, :mod:`gdbm`, or :mod:`dbhash`\
—should be used to open a given file.


.. function:: whichdb(filename)

   Returns one of the following values: ``None`` if the file can't be opened
   because it's unreadable or doesn't exist; the empty string (``''``) if the
   file's format can't be guessed; or a string containing the required module name,
   such as ``'dbm'`` or ``'gdbm'``.

PK
%�\(#Bf%html/_sources/library/windows.rst.txtnu�[���.. _mswin-specific-services:

****************************
MS Windows Specific Services
****************************

This chapter describes modules that are only available on MS Windows platforms.


.. toctree::

   msilib.rst
   msvcrt.rst
   _winreg.rst
   winsound.rst
PK
%�\ԐVC��&html/_sources/library/winsound.rst.txtnu�[���
:mod:`winsound` --- Sound-playing interface for Windows
=======================================================

.. module:: winsound
   :platform: Windows
   :synopsis: Access to the sound-playing machinery for Windows.
.. moduleauthor:: Toby Dickenson <htrd90@zepler.org>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>


.. versionadded:: 1.5.2

The :mod:`winsound` module provides access to the basic sound-playing machinery
provided by Windows platforms.  It includes functions and several constants.


.. function:: Beep(frequency, duration)

   Beep the PC's speaker. The *frequency* parameter specifies frequency, in hertz,
   of the sound, and must be in the range 37 through 32,767. The *duration*
   parameter specifies the number of milliseconds the sound should last.  If the
   system is not able to beep the speaker, :exc:`RuntimeError` is raised.

   .. versionadded:: 1.6


.. function:: PlaySound(sound, flags)

   Call the underlying :c:func:`PlaySound` function from the Platform API.  The
   *sound* parameter may be a filename, audio data as a string, or ``None``.  Its
   interpretation depends on the value of *flags*, which can be a bitwise ORed
   combination of the constants described below. If the *sound* parameter is
   ``None``, any currently playing waveform sound is stopped. If the system
   indicates an error, :exc:`RuntimeError` is raised.


.. function:: MessageBeep([type=MB_OK])

   Call the underlying :c:func:`MessageBeep` function from the Platform API.  This
   plays a sound as specified in the registry.  The *type* argument specifies which
   sound to play; possible values are ``-1``, ``MB_ICONASTERISK``,
   ``MB_ICONEXCLAMATION``, ``MB_ICONHAND``, ``MB_ICONQUESTION``, and ``MB_OK``, all
   described below.  The value ``-1`` produces a "simple beep"; this is the final
   fallback if a sound cannot be played otherwise.

   .. versionadded:: 2.3


.. data:: SND_FILENAME

   The *sound* parameter is the name of a WAV file. Do not use with
   :const:`SND_ALIAS`.


.. data:: SND_ALIAS

   The *sound* parameter is a sound association name from the registry.  If the
   registry contains no such name, play the system default sound unless
   :const:`SND_NODEFAULT` is also specified. If no default sound is registered,
   raise :exc:`RuntimeError`. Do not use with :const:`SND_FILENAME`.

   All Win32 systems support at least the following; most systems support many
   more:

   +--------------------------+----------------------------------------+
   | :func:`PlaySound` *name* | Corresponding Control Panel Sound name |
   +==========================+========================================+
   | ``'SystemAsterisk'``     | Asterisk                               |
   +--------------------------+----------------------------------------+
   | ``'SystemExclamation'``  | Exclamation                            |
   +--------------------------+----------------------------------------+
   | ``'SystemExit'``         | Exit Windows                           |
   +--------------------------+----------------------------------------+
   | ``'SystemHand'``         | Critical Stop                          |
   +--------------------------+----------------------------------------+
   | ``'SystemQuestion'``     | Question                               |
   +--------------------------+----------------------------------------+

   For example::

      import winsound
      # Play Windows exit sound.
      winsound.PlaySound("SystemExit", winsound.SND_ALIAS)

      # Probably play Windows default sound, if any is registered (because
      # "*" probably isn't the registered name of any sound).
      winsound.PlaySound("*", winsound.SND_ALIAS)


.. data:: SND_LOOP

   Play the sound repeatedly.  The :const:`SND_ASYNC` flag must also be used to
   avoid blocking.  Cannot be used with :const:`SND_MEMORY`.


.. data:: SND_MEMORY

   The *sound* parameter to :func:`PlaySound` is a memory image of a WAV file, as a
   string.

   .. note::

      This module does not support playing from a memory image asynchronously, so a
      combination of this flag and :const:`SND_ASYNC` will raise :exc:`RuntimeError`.


.. data:: SND_PURGE

   Stop playing all instances of the specified sound.

   .. note::

      This flag is not supported on modern Windows platforms.


.. data:: SND_ASYNC

   Return immediately, allowing sounds to play asynchronously.


.. data:: SND_NODEFAULT

   If the specified sound cannot be found, do not play the system default sound.


.. data:: SND_NOSTOP

   Do not interrupt sounds currently playing.


.. data:: SND_NOWAIT

   Return immediately if the sound driver is busy.

   .. note::

      This flag is not supported on modern Windows platforms.


.. data:: MB_ICONASTERISK

   Play the ``SystemDefault`` sound.


.. data:: MB_ICONEXCLAMATION

   Play the ``SystemExclamation`` sound.


.. data:: MB_ICONHAND

   Play the ``SystemHand`` sound.


.. data:: MB_ICONQUESTION

   Play the ``SystemQuestion`` sound.


.. data:: MB_OK

   Play the ``SystemDefault`` sound.

PK
%�\y��mgwgw%html/_sources/library/wsgiref.rst.txtnu�[���:mod:`wsgiref` --- WSGI Utilities and Reference Implementation
==============================================================

.. module:: wsgiref
   :synopsis: WSGI Utilities and Reference Implementation.
.. moduleauthor:: Phillip J. Eby <pje@telecommunity.com>
.. sectionauthor:: Phillip J. Eby <pje@telecommunity.com>


.. versionadded:: 2.5

The Web Server Gateway Interface (WSGI) is a standard interface between web
server software and web applications written in Python. Having a standard
interface makes it easy to use an application that supports WSGI with a number
of different web servers.

Only authors of web servers and programming frameworks need to know every detail
and corner case of the WSGI design.  You don't need to understand every detail
of WSGI just to install a WSGI application or to write a web application using
an existing framework.

:mod:`wsgiref` is a reference implementation of the WSGI specification that can
be used to add WSGI support to a web server or framework.  It provides utilities
for manipulating WSGI environment variables and response headers, base classes
for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
and a validation tool that checks WSGI servers and applications for conformance
to the WSGI specification (:pep:`333`).

See https://wsgi.readthedocs.org/ for more information about WSGI, and links to
tutorials and other resources.

.. XXX If you're just trying to write a web application...


:mod:`wsgiref.util` -- WSGI environment utilities
-------------------------------------------------

.. module:: wsgiref.util
   :synopsis: WSGI environment utilities.


This module provides a variety of utility functions for working with WSGI
environments.  A WSGI environment is a dictionary containing HTTP request
variables as described in :pep:`333`.  All of the functions taking an *environ*
parameter expect a WSGI-compliant dictionary to be supplied; please see
:pep:`333` for a detailed specification.


.. function:: guess_scheme(environ)

   Return a guess for whether ``wsgi.url_scheme`` should be "http" or "https", by
   checking for a ``HTTPS`` environment variable in the *environ* dictionary.  The
   return value is a string.

   This function is useful when creating a gateway that wraps CGI or a CGI-like
   protocol such as FastCGI.  Typically, servers providing such protocols will
   include a ``HTTPS`` variable with a value of "1" "yes", or "on" when a request
   is received via SSL.  So, this function returns "https" if such a value is
   found, and "http" otherwise.


.. function:: request_uri(environ, include_query=1)

   Return the full request URI, optionally including the query string, using the
   algorithm found in the "URL Reconstruction" section of :pep:`333`.  If
   *include_query* is false, the query string is not included in the resulting URI.


.. function:: application_uri(environ)

   Similar to :func:`request_uri`, except that the ``PATH_INFO`` and
   ``QUERY_STRING`` variables are ignored.  The result is the base URI of the
   application object addressed by the request.


.. function:: shift_path_info(environ)

   Shift a single name from ``PATH_INFO`` to ``SCRIPT_NAME`` and return the name.
   The *environ* dictionary is *modified* in-place; use a copy if you need to keep
   the original ``PATH_INFO`` or ``SCRIPT_NAME`` intact.

   If there are no remaining path segments in ``PATH_INFO``, ``None`` is returned.

   Typically, this routine is used to process each portion of a request URI path,
   for example to treat the path as a series of dictionary keys. This routine
   modifies the passed-in environment to make it suitable for invoking another WSGI
   application that is located at the target URI. For example, if there is a WSGI
   application at ``/foo``, and the request URI path is ``/foo/bar/baz``, and the
   WSGI application at ``/foo`` calls :func:`shift_path_info`, it will receive the
   string "bar", and the environment will be updated to be suitable for passing to
   a WSGI application at ``/foo/bar``.  That is, ``SCRIPT_NAME`` will change from
   ``/foo`` to ``/foo/bar``, and ``PATH_INFO`` will change from ``/bar/baz`` to
   ``/baz``.

   When ``PATH_INFO`` is just a "/", this routine returns an empty string and
   appends a trailing slash to ``SCRIPT_NAME``, even though empty path segments are
   normally ignored, and ``SCRIPT_NAME`` doesn't normally end in a slash.  This is
   intentional behavior, to ensure that an application can tell the difference
   between URIs ending in ``/x`` from ones ending in ``/x/`` when using this
   routine to do object traversal.


.. function:: setup_testing_defaults(environ)

   Update *environ* with trivial defaults for testing purposes.

   This routine adds various parameters required for WSGI, including ``HTTP_HOST``,
   ``SERVER_NAME``, ``SERVER_PORT``, ``REQUEST_METHOD``, ``SCRIPT_NAME``,
   ``PATH_INFO``, and all of the :pep:`333`\ -defined ``wsgi.*`` variables.  It
   only supplies default values, and does not replace any existing settings for
   these variables.

   This routine is intended to make it easier for unit tests of WSGI servers and
   applications to set up dummy environments.  It should NOT be used by actual WSGI
   servers or applications, since the data is fake!

   Example usage::

      from wsgiref.util import setup_testing_defaults
      from wsgiref.simple_server import make_server

      # A relatively simple WSGI application. It's going to print out the
      # environment dictionary after being updated by setup_testing_defaults
      def simple_app(environ, start_response):
          setup_testing_defaults(environ)

          status = '200 OK'
          headers = [('Content-type', 'text/plain')]

          start_response(status, headers)

          ret = ["%s: %s\n" % (key, value)
                 for key, value in environ.iteritems()]
          return ret

      httpd = make_server('', 8000, simple_app)
      print "Serving on port 8000..."
      httpd.serve_forever()


In addition to the environment functions above, the :mod:`wsgiref.util` module
also provides these miscellaneous utilities:


.. function:: is_hop_by_hop(header_name)

   Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header, as defined by
   :rfc:`2616`.


.. class:: FileWrapper(filelike, blksize=8192)

   A wrapper to convert a file-like object to an :term:`iterator`.  The resulting objects
   support both :meth:`__getitem__` and :meth:`__iter__` iteration styles, for
   compatibility with Python 2.1 and Jython. As the object is iterated over, the
   optional *blksize* parameter will be repeatedly passed to the *filelike*
   object's :meth:`read` method to obtain strings to yield.  When :meth:`read`
   returns an empty string, iteration is ended and is not resumable.

   If *filelike* has a :meth:`close` method, the returned object will also have a
   :meth:`close` method, and it will invoke the *filelike* object's :meth:`close`
   method when called.

   Example usage::

      from StringIO import StringIO
      from wsgiref.util import FileWrapper

      # We're using a StringIO-buffer for as the file-like object
      filelike = StringIO("This is an example file-like object"*10)
      wrapper = FileWrapper(filelike, blksize=5)

      for chunk in wrapper:
          print chunk



:mod:`wsgiref.headers` -- WSGI response header tools
----------------------------------------------------

.. module:: wsgiref.headers
   :synopsis: WSGI response header tools.


This module provides a single class, :class:`Headers`, for convenient
manipulation of WSGI response headers using a mapping-like interface.


.. class:: Headers(headers)

   Create a mapping-like object wrapping *headers*, which must be a list of header
   name/value tuples as described in :pep:`333`.  Any changes made to the new
   :class:`Headers` object will directly update the *headers* list it was created
   with.

   :class:`Headers` objects support typical mapping operations including
   :meth:`__getitem__`, :meth:`get`, :meth:`__setitem__`, :meth:`setdefault`,
   :meth:`__delitem__`, :meth:`__contains__` and :meth:`has_key`.  For each of
   these methods, the key is the header name (treated case-insensitively), and the
   value is the first value associated with that header name.  Setting a header
   deletes any existing values for that header, then adds a new value at the end of
   the wrapped header list.  Headers' existing order is generally maintained, with
   new headers added to the end of the wrapped list.

   Unlike a dictionary, :class:`Headers` objects do not raise an error when you try
   to get or delete a key that isn't in the wrapped header list. Getting a
   nonexistent header just returns ``None``, and deleting a nonexistent header does
   nothing.

   :class:`Headers` objects also support :meth:`keys`, :meth:`values`, and
   :meth:`items` methods.  The lists returned by :meth:`keys` and :meth:`items` can
   include the same key more than once if there is a multi-valued header.  The
   ``len()`` of a :class:`Headers` object is the same as the length of its
   :meth:`items`, which is the same as the length of the wrapped header list.  In
   fact, the :meth:`items` method just returns a copy of the wrapped header list.

   Calling ``str()`` on a :class:`Headers` object returns a formatted string
   suitable for transmission as HTTP response headers.  Each header is placed on a
   line with its value, separated by a colon and a space. Each line is terminated
   by a carriage return and line feed, and the string is terminated with a blank
   line.

   In addition to their mapping interface and formatting features, :class:`Headers`
   objects also have the following methods for querying and adding multi-valued
   headers, and for adding headers with MIME parameters:


   .. method:: Headers.get_all(name)

      Return a list of all the values for the named header.

      The returned list will be sorted in the order they appeared in the original
      header list or were added to this instance, and may contain duplicates.  Any
      fields deleted and re-inserted are always appended to the header list.  If no
      fields exist with the given name, returns an empty list.


   .. method:: Headers.add_header(name, value, **_params)

      Add a (possibly multi-valued) header, with optional MIME parameters specified
      via keyword arguments.

      *name* is the header field to add.  Keyword arguments can be used to set MIME
      parameters for the header field.  Each parameter must be a string or ``None``.
      Underscores in parameter names are converted to dashes, since dashes are illegal
      in Python identifiers, but many MIME parameter names include dashes.  If the
      parameter value is a string, it is added to the header value parameters in the
      form ``name="value"``. If it is ``None``, only the parameter name is added.
      (This is used for MIME parameters without a value.)  Example usage::

         h.add_header('content-disposition', 'attachment', filename='bud.gif')

      The above will add a header that looks like this::

         Content-Disposition: attachment; filename="bud.gif"


:mod:`wsgiref.simple_server` -- a simple WSGI HTTP server
---------------------------------------------------------

.. module:: wsgiref.simple_server
   :synopsis: A simple WSGI HTTP server.


This module implements a simple HTTP server (based on :mod:`BaseHTTPServer`)
that serves WSGI applications.  Each server instance serves a single WSGI
application on a given host and port.  If you want to serve multiple
applications on a single host and port, you should create a WSGI application
that parses ``PATH_INFO`` to select which application to invoke for each
request.  (E.g., using the :func:`shift_path_info` function from
:mod:`wsgiref.util`.)


.. function:: make_server(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)

   Create a new WSGI server listening on *host* and *port*, accepting connections
   for *app*.  The return value is an instance of the supplied *server_class*, and
   will process requests using the specified *handler_class*.  *app* must be a WSGI
   application object, as defined by :pep:`333`.

   Example usage::

      from wsgiref.simple_server import make_server, demo_app

      httpd = make_server('', 8000, demo_app)
      print "Serving HTTP on port 8000..."

      # Respond to requests until process is killed
      httpd.serve_forever()

      # Alternative: serve one request, then exit
      httpd.handle_request()


.. function:: demo_app(environ, start_response)

   This function is a small but complete WSGI application that returns a text page
   containing the message "Hello world!" and a list of the key/value pairs provided
   in the *environ* parameter.  It's useful for verifying that a WSGI server (such
   as :mod:`wsgiref.simple_server`) is able to run a simple WSGI application
   correctly.


.. class:: WSGIServer(server_address, RequestHandlerClass)

   Create a :class:`WSGIServer` instance.  *server_address* should be a
   ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of
   :class:`BaseHTTPServer.BaseHTTPRequestHandler` that will be used to process
   requests.

   You do not normally need to call this constructor, as the :func:`make_server`
   function can handle all the details for you.

   :class:`WSGIServer` is a subclass of :class:`BaseHTTPServer.HTTPServer`, so all
   of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are
   available. :class:`WSGIServer` also provides these WSGI-specific methods:


   .. method:: WSGIServer.set_app(application)

      Sets the callable *application* as the WSGI application that will receive
      requests.


   .. method:: WSGIServer.get_app()

      Returns the currently-set application callable.

   Normally, however, you do not need to use these additional methods, as
   :meth:`set_app` is normally called by :func:`make_server`, and the
   :meth:`get_app` exists mainly for the benefit of request handler instances.


.. class:: WSGIRequestHandler(request, client_address, server)

   Create an HTTP handler for the given *request* (i.e. a socket), *client_address*
   (a ``(host,port)`` tuple), and *server* (:class:`WSGIServer` instance).

   You do not need to create instances of this class directly; they are
   automatically created as needed by :class:`WSGIServer` objects.  You can,
   however, subclass this class and supply it as a *handler_class* to the
   :func:`make_server` function.  Some possibly relevant methods for overriding in
   subclasses:


   .. method:: WSGIRequestHandler.get_environ()

      Returns a dictionary containing the WSGI environment for a request.  The default
      implementation copies the contents of the :class:`WSGIServer` object's
      :attr:`base_environ` dictionary attribute and then adds various headers derived
      from the HTTP request.  Each call to this method should return a new dictionary
      containing all of the relevant CGI environment variables as specified in
      :pep:`333`.


   .. method:: WSGIRequestHandler.get_stderr()

      Return the object that should be used as the ``wsgi.errors`` stream. The default
      implementation just returns ``sys.stderr``.


   .. method:: WSGIRequestHandler.handle()

      Process the HTTP request.  The default implementation creates a handler instance
      using a :mod:`wsgiref.handlers` class to implement the actual WSGI application
      interface.


:mod:`wsgiref.validate` --- WSGI conformance checker
----------------------------------------------------

.. module:: wsgiref.validate
   :synopsis: WSGI conformance checker.


When creating new WSGI application objects, frameworks, servers, or middleware,
it can be useful to validate the new code's conformance using
:mod:`wsgiref.validate`.  This module provides a function that creates WSGI
application objects that validate communications between a WSGI server or
gateway and a WSGI application object, to check both sides for protocol
conformance.

Note that this utility does not guarantee complete :pep:`333` compliance; an
absence of errors from this module does not necessarily mean that errors do not
exist.  However, if this module does produce an error, then it is virtually
certain that either the server or application is not 100% compliant.

This module is based on the :mod:`paste.lint` module from Ian Bicking's "Python
Paste" library.


.. function:: validator(application)

   Wrap *application* and return a new WSGI application object.  The returned
   application will forward all requests to the original *application*, and will
   check that both the *application* and the server invoking it are conforming to
   the WSGI specification and to RFC 2616.

   Any detected nonconformance results in an :exc:`AssertionError` being raised;
   note, however, that how these errors are handled is server-dependent.  For
   example, :mod:`wsgiref.simple_server` and other servers based on
   :mod:`wsgiref.handlers` (that don't override the error handling methods to do
   something else) will simply output a message that an error has occurred, and
   dump the traceback to ``sys.stderr`` or some other error stream.

   This wrapper may also generate output using the :mod:`warnings` module to
   indicate behaviors that are questionable but which may not actually be
   prohibited by :pep:`333`.  Unless they are suppressed using Python command-line
   options or the :mod:`warnings` API, any such warnings will be written to
   ``sys.stderr`` (*not* ``wsgi.errors``, unless they happen to be the same
   object).

   Example usage::

      from wsgiref.validate import validator
      from wsgiref.simple_server import make_server

      # Our callable object which is intentionally not compliant to the
      # standard, so the validator is going to break
      def simple_app(environ, start_response):
          status = '200 OK'  # HTTP Status
          headers = [('Content-type', 'text/plain')]  # HTTP Headers
          start_response(status, headers)

          # This is going to break because we need to return a list, and
          # the validator is going to inform us
          return "Hello World"

      # This is the application wrapped in a validator
      validator_app = validator(simple_app)

      httpd = make_server('', 8000, validator_app)
      print "Listening on port 8000...."
      httpd.serve_forever()


:mod:`wsgiref.handlers` -- server/gateway base classes
------------------------------------------------------

.. module:: wsgiref.handlers
   :synopsis: WSGI server/gateway base classes.


This module provides base handler classes for implementing WSGI servers and
gateways.  These base classes handle most of the work of communicating with a
WSGI application, as long as they are given a CGI-like environment, along with
input, output, and error streams.


.. class:: CGIHandler()

   CGI-based invocation via ``sys.stdin``, ``sys.stdout``, ``sys.stderr`` and
   ``os.environ``.  This is useful when you have a WSGI application and want to run
   it as a CGI script.  Simply invoke ``CGIHandler().run(app)``, where ``app`` is
   the WSGI application object you wish to invoke.

   This class is a subclass of :class:`BaseCGIHandler` that sets ``wsgi.run_once``
   to true, ``wsgi.multithread`` to false, and ``wsgi.multiprocess`` to true, and
   always uses :mod:`sys` and :mod:`os` to obtain the necessary CGI streams and
   environment.


.. class:: BaseCGIHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

   Similar to :class:`CGIHandler`, but instead of using the :mod:`sys` and
   :mod:`os` modules, the CGI environment and I/O streams are specified explicitly.
   The *multithread* and *multiprocess* values are used to set the
   ``wsgi.multithread`` and ``wsgi.multiprocess`` flags for any applications run by
   the handler instance.

   This class is a subclass of :class:`SimpleHandler` intended for use with
   software other than HTTP "origin servers".  If you are writing a gateway
   protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a
   ``Status:`` header to send an HTTP status, you probably want to subclass this
   instead of :class:`SimpleHandler`.


.. class:: SimpleHandler(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)

   Similar to :class:`BaseCGIHandler`, but designed for use with HTTP origin
   servers.  If you are writing an HTTP server implementation, you will probably
   want to subclass this instead of :class:`BaseCGIHandler`.

   This class is a subclass of :class:`BaseHandler`.  It overrides the
   :meth:`__init__`, :meth:`get_stdin`, :meth:`get_stderr`, :meth:`add_cgi_vars`,
   :meth:`_write`, and :meth:`_flush` methods to support explicitly setting the
   environment and streams via the constructor.  The supplied environment and
   streams are stored in the :attr:`stdin`, :attr:`stdout`, :attr:`stderr`, and
   :attr:`environ` attributes.


.. class:: BaseHandler()

   This is an abstract base class for running WSGI applications.  Each instance
   will handle a single HTTP request, although in principle you could create a
   subclass that was reusable for multiple requests.

   :class:`BaseHandler` instances have only one method intended for external use:


   .. method:: BaseHandler.run(app)

      Run the specified WSGI application, *app*.

   All of the other :class:`BaseHandler` methods are invoked by this method in the
   process of running the application, and thus exist primarily to allow
   customizing the process.

   The following methods MUST be overridden in a subclass:


   .. method:: BaseHandler._write(data)

      Buffer the string *data* for transmission to the client.  It's okay if this
      method actually transmits the data; :class:`BaseHandler` just separates write
      and flush operations for greater efficiency when the underlying system actually
      has such a distinction.


   .. method:: BaseHandler._flush()

      Force buffered data to be transmitted to the client.  It's okay if this method
      is a no-op (i.e., if :meth:`_write` actually sends the data).


   .. method:: BaseHandler.get_stdin()

      Return an input stream object suitable for use as the ``wsgi.input`` of the
      request currently being processed.


   .. method:: BaseHandler.get_stderr()

      Return an output stream object suitable for use as the ``wsgi.errors`` of the
      request currently being processed.


   .. method:: BaseHandler.add_cgi_vars()

      Insert CGI variables for the current request into the :attr:`environ` attribute.

   Here are some other methods and attributes you may wish to override. This list
   is only a summary, however, and does not include every method that can be
   overridden.  You should consult the docstrings and source code for additional
   information before attempting to create a customized :class:`BaseHandler`
   subclass.

   Attributes and methods for customizing the WSGI environment:


   .. attribute:: BaseHandler.wsgi_multithread

      The value to be used for the ``wsgi.multithread`` environment variable.  It
      defaults to true in :class:`BaseHandler`, but may have a different default (or
      be set by the constructor) in the other subclasses.


   .. attribute:: BaseHandler.wsgi_multiprocess

      The value to be used for the ``wsgi.multiprocess`` environment variable.  It
      defaults to true in :class:`BaseHandler`, but may have a different default (or
      be set by the constructor) in the other subclasses.


   .. attribute:: BaseHandler.wsgi_run_once

      The value to be used for the ``wsgi.run_once`` environment variable.  It
      defaults to false in :class:`BaseHandler`, but :class:`CGIHandler` sets it to
      true by default.


   .. attribute:: BaseHandler.os_environ

      The default environment variables to be included in every request's WSGI
      environment.  By default, this is a copy of ``os.environ`` at the time that
      :mod:`wsgiref.handlers` was imported, but subclasses can either create their own
      at the class or instance level.  Note that the dictionary should be considered
      read-only, since the default value is shared between multiple classes and
      instances.


   .. attribute:: BaseHandler.server_software

      If the :attr:`origin_server` attribute is set, this attribute's value is used to
      set the default ``SERVER_SOFTWARE`` WSGI environment variable, and also to set a
      default ``Server:`` header in HTTP responses.  It is ignored for handlers (such
      as :class:`BaseCGIHandler` and :class:`CGIHandler`) that are not HTTP origin
      servers.


   .. method:: BaseHandler.get_scheme()

      Return the URL scheme being used for the current request.  The default
      implementation uses the :func:`guess_scheme` function from :mod:`wsgiref.util`
      to guess whether the scheme should be "http" or "https", based on the current
      request's :attr:`environ` variables.


   .. method:: BaseHandler.setup_environ()

      Set the :attr:`environ` attribute to a fully-populated WSGI environment.  The
      default implementation uses all of the above methods and attributes, plus the
      :meth:`get_stdin`, :meth:`get_stderr`, and :meth:`add_cgi_vars` methods and the
      :attr:`wsgi_file_wrapper` attribute.  It also inserts a ``SERVER_SOFTWARE`` key
      if not present, as long as the :attr:`origin_server` attribute is a true value
      and the :attr:`server_software` attribute is set.

   Methods and attributes for customizing exception handling:


   .. method:: BaseHandler.log_exception(exc_info)

      Log the *exc_info* tuple in the server log.  *exc_info* is a ``(type, value,
      traceback)`` tuple.  The default implementation simply writes the traceback to
      the request's ``wsgi.errors`` stream and flushes it.  Subclasses can override
      this method to change the format or retarget the output, mail the traceback to
      an administrator, or whatever other action may be deemed suitable.


   .. attribute:: BaseHandler.traceback_limit

      The maximum number of frames to include in tracebacks output by the default
      :meth:`log_exception` method.  If ``None``, all frames are included.


   .. method:: BaseHandler.error_output(environ, start_response)

      This method is a WSGI application to generate an error page for the user.  It is
      only invoked if an error occurs before headers are sent to the client.

      This method can access the current error information using ``sys.exc_info()``,
      and should pass that information to *start_response* when calling it (as
      described in the "Error Handling" section of :pep:`333`).

      The default implementation just uses the :attr:`error_status`,
      :attr:`error_headers`, and :attr:`error_body` attributes to generate an output
      page.  Subclasses can override this to produce more dynamic error output.

      Note, however, that it's not recommended from a security perspective to spit out
      diagnostics to any old user; ideally, you should have to do something special to
      enable diagnostic output, which is why the default implementation doesn't
      include any.


   .. attribute:: BaseHandler.error_status

      The HTTP status used for error responses.  This should be a status string as
      defined in :pep:`333`; it defaults to a 500 code and message.


   .. attribute:: BaseHandler.error_headers

      The HTTP headers used for error responses.  This should be a list of WSGI
      response headers (``(name, value)`` tuples), as described in :pep:`333`.  The
      default list just sets the content type to ``text/plain``.


   .. attribute:: BaseHandler.error_body

      The error response body.  This should be an HTTP response body string. It
      defaults to the plain text, "A server error occurred.  Please contact the
      administrator."

   Methods and attributes for :pep:`333`'s "Optional Platform-Specific File
   Handling" feature:


   .. attribute:: BaseHandler.wsgi_file_wrapper

      A ``wsgi.file_wrapper`` factory, or ``None``.  The default value of this
      attribute is the :class:`FileWrapper` class from :mod:`wsgiref.util`.


   .. method:: BaseHandler.sendfile()

      Override to implement platform-specific file transmission.  This method is
      called only if the application's return value is an instance of the class
      specified by the :attr:`wsgi_file_wrapper` attribute.  It should return a true
      value if it was able to successfully transmit the file, so that the default
      transmission code will not be executed. The default implementation of this
      method just returns a false value.

   Miscellaneous methods and attributes:


   .. attribute:: BaseHandler.origin_server

      This attribute should be set to a true value if the handler's :meth:`_write` and
      :meth:`_flush` are being used to communicate directly to the client, rather than
      via a CGI-like gateway protocol that wants the HTTP status in a special
      ``Status:`` header.

      This attribute's default value is true in :class:`BaseHandler`, but false in
      :class:`BaseCGIHandler` and :class:`CGIHandler`.


   .. attribute:: BaseHandler.http_version

      If :attr:`origin_server` is true, this string attribute is used to set the HTTP
      version of the response set to the client.  It defaults to ``"1.0"``.


Examples
--------

This is a working "Hello World" WSGI application::

   from wsgiref.simple_server import make_server

   # Every WSGI application must have an application object - a callable
   # object that accepts two arguments. For that purpose, we're going to
   # use a function (note that you're not limited to a function, you can
   # use a class for example). The first argument passed to the function
   # is a dictionary containing CGI-style environment variables and the
   # second variable is the callable object (see PEP 333).
   def hello_world_app(environ, start_response):
       status = '200 OK'  # HTTP Status
       headers = [('Content-type', 'text/plain')]  # HTTP Headers
       start_response(status, headers)

       # The returned object is going to be printed
       return ["Hello World"]

   httpd = make_server('', 8000, hello_world_app)
   print "Serving on port 8000..."

   # Serve until process is killed
   httpd.serve_forever()
PK
%�\�>�[��$html/_sources/library/xdrlib.rst.txtnu�[���:mod:`xdrlib` --- Encode and decode XDR data
============================================

.. module:: xdrlib
   :synopsis: Encoders and decoders for the External Data Representation (XDR).


.. index::
   single: XDR
   single: External Data Representation

**Source code:** :source:`Lib/xdrlib.py`

--------------

The :mod:`xdrlib` module supports the External Data Representation Standard as
described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987.  It
supports most of the data types described in the RFC.

The :mod:`xdrlib` module defines two classes, one for packing variables into XDR
representation, and another for unpacking from XDR representation.  There are
also two exception classes.


.. class:: Packer()

   :class:`Packer` is the class for packing data into XDR representation. The
   :class:`Packer` class is instantiated with no arguments.


.. class:: Unpacker(data)

   ``Unpacker`` is the complementary class which unpacks XDR data values from a
   string buffer.  The input buffer is given as *data*.


.. seealso::

   :rfc:`1014` - XDR: External Data Representation Standard
      This RFC defined the encoding of data which was XDR at the time this module was
      originally written.  It has apparently been obsoleted by :rfc:`1832`.

   :rfc:`1832` - XDR: External Data Representation Standard
      Newer RFC that provides a revised definition of XDR.


.. _xdr-packer-objects:

Packer Objects
--------------

:class:`Packer` instances have the following methods:


.. method:: Packer.get_buffer()

   Returns the current pack buffer as a string.


.. method:: Packer.reset()

   Resets the pack buffer to the empty string.

In general, you can pack any of the most common XDR data types by calling the
appropriate ``pack_type()`` method.  Each method takes a single argument, the
value to pack.  The following simple data type packing methods are supported:
:meth:`pack_uint`, :meth:`pack_int`, :meth:`pack_enum`, :meth:`pack_bool`,
:meth:`pack_uhyper`, and :meth:`pack_hyper`.


.. method:: Packer.pack_float(value)

   Packs the single-precision floating point number *value*.


.. method:: Packer.pack_double(value)

   Packs the double-precision floating point number *value*.

The following methods support packing strings, bytes, and opaque data:


.. method:: Packer.pack_fstring(n, s)

   Packs a fixed length string, *s*.  *n* is the length of the string but it is
   *not* packed into the data buffer.  The string is padded with null bytes if
   necessary to guaranteed 4 byte alignment.


.. method:: Packer.pack_fopaque(n, data)

   Packs a fixed length opaque data stream, similarly to :meth:`pack_fstring`.


.. method:: Packer.pack_string(s)

   Packs a variable length string, *s*.  The length of the string is first packed
   as an unsigned integer, then the string data is packed with
   :meth:`pack_fstring`.


.. method:: Packer.pack_opaque(data)

   Packs a variable length opaque data string, similarly to :meth:`pack_string`.


.. method:: Packer.pack_bytes(bytes)

   Packs a variable length byte stream, similarly to :meth:`pack_string`.

The following methods support packing arrays and lists:


.. method:: Packer.pack_list(list, pack_item)

   Packs a *list* of homogeneous items.  This method is useful for lists with an
   indeterminate size; i.e. the size is not available until the entire list has
   been walked.  For each item in the list, an unsigned integer ``1`` is packed
   first, followed by the data value from the list.  *pack_item* is the function
   that is called to pack the individual item.  At the end of the list, an unsigned
   integer ``0`` is packed.

   For example, to pack a list of integers, the code might appear like this::

      import xdrlib
      p = xdrlib.Packer()
      p.pack_list([1, 2, 3], p.pack_int)


.. method:: Packer.pack_farray(n, array, pack_item)

   Packs a fixed length list (*array*) of homogeneous items.  *n* is the length of
   the list; it is *not* packed into the buffer, but a :exc:`ValueError` exception
   is raised if ``len(array)`` is not equal to *n*.  As above, *pack_item* is the
   function used to pack each element.


.. method:: Packer.pack_array(list, pack_item)

   Packs a variable length *list* of homogeneous items.  First, the length of the
   list is packed as an unsigned integer, then each element is packed as in
   :meth:`pack_farray` above.


.. _xdr-unpacker-objects:

Unpacker Objects
----------------

The :class:`Unpacker` class offers the following methods:


.. method:: Unpacker.reset(data)

   Resets the string buffer with the given *data*.


.. method:: Unpacker.get_position()

   Returns the current unpack position in the data buffer.


.. method:: Unpacker.set_position(position)

   Sets the data buffer unpack position to *position*.  You should be careful about
   using :meth:`get_position` and :meth:`set_position`.


.. method:: Unpacker.get_buffer()

   Returns the current unpack data buffer as a string.


.. method:: Unpacker.done()

   Indicates unpack completion.  Raises an :exc:`Error` exception if all of the
   data has not been unpacked.

In addition, every data type that can be packed with a :class:`Packer`, can be
unpacked with an :class:`Unpacker`.  Unpacking methods are of the form
``unpack_type()``, and take no arguments.  They return the unpacked object.


.. method:: Unpacker.unpack_float()

   Unpacks a single-precision floating point number.


.. method:: Unpacker.unpack_double()

   Unpacks a double-precision floating point number, similarly to
   :meth:`unpack_float`.

In addition, the following methods unpack strings, bytes, and opaque data:


.. method:: Unpacker.unpack_fstring(n)

   Unpacks and returns a fixed length string.  *n* is the number of characters
   expected.  Padding with null bytes to guaranteed 4 byte alignment is assumed.


.. method:: Unpacker.unpack_fopaque(n)

   Unpacks and returns a fixed length opaque data stream, similarly to
   :meth:`unpack_fstring`.


.. method:: Unpacker.unpack_string()

   Unpacks and returns a variable length string.  The length of the string is first
   unpacked as an unsigned integer, then the string data is unpacked with
   :meth:`unpack_fstring`.


.. method:: Unpacker.unpack_opaque()

   Unpacks and returns a variable length opaque data string, similarly to
   :meth:`unpack_string`.


.. method:: Unpacker.unpack_bytes()

   Unpacks and returns a variable length byte stream, similarly to
   :meth:`unpack_string`.

The following methods support unpacking arrays and lists:


.. method:: Unpacker.unpack_list(unpack_item)

   Unpacks and returns a list of homogeneous items.  The list is unpacked one
   element at a time by first unpacking an unsigned integer flag.  If the flag is
   ``1``, then the item is unpacked and appended to the list.  A flag of ``0``
   indicates the end of the list.  *unpack_item* is the function that is called to
   unpack the items.


.. method:: Unpacker.unpack_farray(n, unpack_item)

   Unpacks and returns (as a list) a fixed length array of homogeneous items.  *n*
   is number of list elements to expect in the buffer. As above, *unpack_item* is
   the function used to unpack each element.


.. method:: Unpacker.unpack_array(unpack_item)

   Unpacks and returns a variable length *list* of homogeneous items. First, the
   length of the list is unpacked as an unsigned integer, then each element is
   unpacked as in :meth:`unpack_farray` above.


.. _xdr-exceptions:

Exceptions
----------

Exceptions in this module are coded as class instances:


.. exception:: Error

   The base exception class.  :exc:`Error` has a single public attribute
   :attr:`msg` containing the description of the error.


.. exception:: ConversionError

   Class derived from :exc:`Error`.  Contains no additional instance variables.

Here is an example of how you would catch one of these exceptions::

   import xdrlib
   p = xdrlib.Packer()
   try:
       p.pack_double(8.01)
   except xdrlib.ConversionError as instance:
       print 'packing the double failed:', instance.msg
PK
%�\)v���+�+-html/_sources/library/xml.dom.minidom.rst.txtnu�[���:mod:`xml.dom.minidom` --- Minimal DOM implementation
=====================================================

.. module:: xml.dom.minidom
   :synopsis: Minimal Document Object Model (DOM) implementation.
.. moduleauthor:: Paul Prescod <paul@prescod.net>
.. sectionauthor:: Paul Prescod <paul@prescod.net>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

**Source code:** :source:`Lib/xml/dom/minidom.py`

--------------

:mod:`xml.dom.minidom` is a minimal implementation of the Document Object
Model interface, with an API similar to that in other languages.  It is intended
to be simpler than the full DOM and also significantly smaller.  Users who are
not already proficient with the DOM should consider using the
:mod:`xml.etree.ElementTree` module for their XML processing instead.


.. warning::

   The :mod:`xml.dom.minidom` module is not secure against
   maliciously constructed data.  If you need to parse untrusted or
   unauthenticated data see :ref:`xml-vulnerabilities`.


DOM applications typically start by parsing some XML into a DOM.  With
:mod:`xml.dom.minidom`, this is done through the parse functions::

   from xml.dom.minidom import parse, parseString

   dom1 = parse('c:\\temp\\mydata.xml')  # parse an XML file by name

   datasource = open('c:\\temp\\mydata.xml')
   dom2 = parse(datasource)  # parse an open file

   dom3 = parseString('<myxml>Some data<empty/> some more data</myxml>')

The :func:`parse` function can take either a filename or an open file object.


.. function:: parse(filename_or_file[, parser[, bufsize]])

   Return a :class:`Document` from the given input. *filename_or_file* may be
   either a file name, or a file-like object. *parser*, if given, must be a SAX2
   parser object. This function will change the document handler of the parser and
   activate namespace support; other parser configuration (like setting an entity
   resolver) must have been done in advance.

If you have XML in a string, you can use the :func:`parseString` function
instead:


.. function:: parseString(string[, parser])

   Return a :class:`Document` that represents the *string*. This method creates a
   :class:`~StringIO.StringIO` object for the string and passes that on to :func:`parse`.

Both functions return a :class:`Document` object representing the content of the
document.

What the :func:`parse` and :func:`parseString` functions do is connect an XML
parser with a "DOM builder" that can accept parse events from any SAX parser and
convert them into a DOM tree.  The name of the functions are perhaps misleading,
but are easy to grasp when learning the interfaces.  The parsing of the document
will be completed before these functions return; it's simply that these
functions do not provide a parser implementation themselves.

You can also create a :class:`Document` by calling a method on a "DOM
Implementation" object.  You can get this object either by calling the
:func:`getDOMImplementation` function in the :mod:`xml.dom` package or the
:mod:`xml.dom.minidom` module. Using the implementation from the
:mod:`xml.dom.minidom` module will always return a :class:`Document` instance
from the minidom implementation, while the version from :mod:`xml.dom` may
provide an alternate implementation (this is likely if you have the `PyXML
package <http://pyxml.sourceforge.net/>`_ installed).  Once you have a
:class:`Document`, you can add child nodes to it to populate the DOM::

   from xml.dom.minidom import getDOMImplementation

   impl = getDOMImplementation()

   newdoc = impl.createDocument(None, "some_tag", None)
   top_element = newdoc.documentElement
   text = newdoc.createTextNode('Some textual content.')
   top_element.appendChild(text)

Once you have a DOM document object, you can access the parts of your XML
document through its properties and methods.  These properties are defined in
the DOM specification.  The main property of the document object is the
:attr:`documentElement` property.  It gives you the main element in the XML
document: the one that holds all others.  Here is an example program::

   dom3 = parseString("<myxml>Some data</myxml>")
   assert dom3.documentElement.tagName == "myxml"

When you are finished with a DOM tree, you may optionally call the
:meth:`unlink` method to encourage early cleanup of the now-unneeded
objects.  :meth:`unlink` is an :mod:`xml.dom.minidom`\ -specific
extension to the DOM API that renders the node and its descendants are
essentially useless.  Otherwise, Python's garbage collector will
eventually take care of the objects in the tree.

.. seealso::

   `Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_
      The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.


.. _minidom-objects:

DOM Objects
-----------

The definition of the DOM API for Python is given as part of the :mod:`xml.dom`
module documentation.  This section lists the differences between the API and
:mod:`xml.dom.minidom`.


.. method:: Node.unlink()

   Break internal references within the DOM so that it will be garbage collected on
   versions of Python without cyclic GC.  Even when cyclic GC is available, using
   this can make large amounts of memory available sooner, so calling this on DOM
   objects as soon as they are no longer needed is good practice.  This only needs
   to be called on the :class:`Document` object, but may be called on child nodes
   to discard children of that node.


.. method:: Node.writexml(writer, indent="", addindent="", newl="")

   Write XML to the writer object.  The writer should have a :meth:`write` method
   which matches that of the file object interface.  The *indent* parameter is the
   indentation of the current node.  The *addindent* parameter is the incremental
   indentation to use for subnodes of the current one.  The *newl* parameter
   specifies the string to use to terminate newlines.

   For the :class:`Document` node, an additional keyword argument *encoding* can
   be used to specify the encoding field of the XML header.

   .. versionchanged:: 2.1
      The optional keyword parameters *indent*, *addindent*, and *newl* were added to
      support pretty output.

   .. versionchanged:: 2.3
      For the :class:`Document` node, an additional keyword argument
      *encoding* can be used to specify the encoding field of the XML header.


.. method:: Node.toxml([encoding])

   Return the XML that the DOM represents as a string.

   With no argument, the XML header does not specify an encoding, and the result is
   Unicode string if the default encoding cannot represent all characters in the
   document. Encoding this string in an encoding other than UTF-8 is likely
   incorrect, since UTF-8 is the default encoding of XML.

   With an explicit *encoding* [1]_ argument, the result is a byte string in the
   specified encoding. It is recommended that this argument is always specified. To
   avoid :exc:`UnicodeError` exceptions in case of unrepresentable text data, the
   encoding argument should be specified as "utf-8".

   .. versionchanged:: 2.3
      the *encoding* argument was introduced; see :meth:`writexml`.


.. method:: Node.toprettyxml(indent="\\t", newl="\\n", encoding=None)

   Return a pretty-printed version of the document. *indent* specifies the
   indentation string and defaults to a tabulator; *newl* specifies the string
   emitted at the end of each line and defaults to ``\n``.

   .. versionadded:: 2.1

   .. versionchanged:: 2.3
      the encoding argument was introduced; see :meth:`writexml`.

The following standard DOM methods have special considerations with
:mod:`xml.dom.minidom`:


.. method:: Node.cloneNode(deep)

   Although this method was present in the version of :mod:`xml.dom.minidom`
   packaged with Python 2.0, it was seriously broken.  This has been corrected for
   subsequent releases.


.. _dom-example:

DOM Example
-----------

This example program is a fairly realistic example of a simple program. In this
particular case, we do not take much advantage of the flexibility of the DOM.

.. literalinclude:: ../includes/minidom-example.py


.. _minidom-and-dom:

minidom and the DOM standard
----------------------------

The :mod:`xml.dom.minidom` module is essentially a DOM 1.0-compatible DOM with
some DOM 2 features (primarily namespace features).

Usage of the DOM interface in Python is straight-forward.  The following mapping
rules apply:

* Interfaces are accessed through instance objects. Applications should not
  instantiate the classes themselves; they should use the creator functions
  available on the :class:`Document` object. Derived interfaces support all
  operations (and attributes) from the base interfaces, plus any new operations.

* Operations are used as methods. Since the DOM uses only :keyword:`in`
  parameters, the arguments are passed in normal order (from left to right).
  There are no optional arguments. ``void`` operations return ``None``.

* IDL attributes map to instance attributes. For compatibility with the OMG IDL
  language mapping for Python, an attribute ``foo`` can also be accessed through
  accessor methods :meth:`_get_foo` and :meth:`_set_foo`.  ``readonly``
  attributes must not be changed; this is not enforced at runtime.

* The types ``short int``, ``unsigned int``, ``unsigned long long``, and
  ``boolean`` all map to Python integer objects.

* The type ``DOMString`` maps to Python strings. :mod:`xml.dom.minidom` supports
  either byte or Unicode strings, but will normally produce Unicode strings.
  Values of type ``DOMString`` may also be ``None`` where allowed to have the IDL
  ``null`` value by the DOM specification from the W3C.

* ``const`` declarations map to variables in their respective scope (e.g.
  ``xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE``); they must not be changed.

* ``DOMException`` is currently not supported in :mod:`xml.dom.minidom`.
  Instead, :mod:`xml.dom.minidom` uses standard Python exceptions such as
  :exc:`TypeError` and :exc:`AttributeError`.

* :class:`NodeList` objects are implemented using Python's built-in list type.
  Starting with Python 2.2, these objects provide the interface defined in the DOM
  specification, but with earlier versions of Python they do not support the
  official API.  They are, however, much more "Pythonic" than the interface
  defined in the W3C recommendations.

The following interfaces have no implementation in :mod:`xml.dom.minidom`:

* :class:`DOMTimeStamp`

* :class:`DocumentType` (added in Python 2.1)

* :class:`DOMImplementation` (added in Python 2.1)

* :class:`CharacterData`

* :class:`CDATASection`

* :class:`Notation`

* :class:`Entity`

* :class:`EntityReference`

* :class:`DocumentFragment`

Most of these reflect information in the XML document that is not of general
utility to most DOM users.

.. rubric:: Footnotes

.. [1] The encoding string included in XML output should conform to the
   appropriate standards. For example, "UTF-8" is valid, but "UTF8" is
   not. See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
PK
%�\��##-html/_sources/library/xml.dom.pulldom.rst.txtnu�[���:mod:`xml.dom.pulldom` --- Support for building partial DOM trees
=================================================================

.. module:: xml.dom.pulldom
   :synopsis: Support for building partial DOM trees from SAX events.
.. moduleauthor:: Paul Prescod <paul@prescod.net>


.. versionadded:: 2.0

**Source code:** :source:`Lib/xml/dom/pulldom.py`

--------------

:mod:`xml.dom.pulldom` allows building only selected portions of a Document
Object Model representation of a document from SAX events.


.. warning::

   The :mod:`xml.dom.pulldom` module is not secure against
   maliciously constructed data.  If you need to parse untrusted or
   unauthenticated data see :ref:`xml-vulnerabilities`.


.. class:: PullDOM([documentFactory])

   :class:`xml.sax.handler.ContentHandler` implementation that ...


.. class:: DOMEventStream(stream, parser, bufsize)

   ...


.. class:: SAX2DOM([documentFactory])

   :class:`xml.sax.handler.ContentHandler` implementation that ...


.. function:: parse(stream_or_string[, parser[, bufsize]])

   ...


.. function:: parseString(string[, parser])

   ...


.. data:: default_bufsize

   Default value for the *bufsize* parameter to :func:`parse`.

   .. versionchanged:: 2.1
      The value of this variable can be changed before calling :func:`parse` and the
      new value will take effect.


.. _domeventstream-objects:

DOMEventStream Objects
----------------------


.. method:: DOMEventStream.getEvent()

   ...


.. method:: DOMEventStream.expandNode(node)

   ...


.. method:: DOMEventStream.reset()

   ...

PK
%�\ծ����%html/_sources/library/xml.dom.rst.txtnu�[���
:mod:`xml.dom` --- The Document Object Model API
================================================

.. module:: xml.dom
   :synopsis: Document Object Model API for Python.
.. sectionauthor:: Paul Prescod <paul@prescod.net>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

The Document Object Model, or "DOM," is a cross-language API from the World Wide
Web Consortium (W3C) for accessing and modifying XML documents.  A DOM
implementation presents an XML document as a tree structure, or allows client
code to build such a structure from scratch.  It then gives access to the
structure through a set of objects which provided well-known interfaces.

The DOM is extremely useful for random-access applications.  SAX only allows you
a view of one bit of the document at a time.  If you are looking at one SAX
element, you have no access to another.  If you are looking at a text node, you
have no access to a containing element. When you write a SAX application, you
need to keep track of your program's position in the document somewhere in your
own code.  SAX does not do it for you.  Also, if you need to look ahead in the
XML document, you are just out of luck.

Some applications are simply impossible in an event driven model with no access
to a tree.  Of course you could build some sort of tree yourself in SAX events,
but the DOM allows you to avoid writing that code.  The DOM is a standard tree
representation for XML data.

The Document Object Model is being defined by the W3C in stages, or "levels" in
their terminology.  The Python mapping of the API is substantially based on the
DOM Level 2 recommendation.

.. XXX PyXML is dead...
.. The mapping of the Level 3 specification, currently
   only available in draft form, is being developed by the `Python XML Special
   Interest Group <https://www.python.org/sigs/xml-sig/>`_ as part of the `PyXML
   package <http://pyxml.sourceforge.net/>`_.  Refer to the documentation bundled
   with that package for information on the current state of DOM Level 3 support.

.. What if your needs are somewhere between SAX and the DOM?  Perhaps
   you cannot afford to load the entire tree in memory but you find the
   SAX model somewhat cumbersome and low-level.  There is also a module
   called xml.dom.pulldom that allows you to build trees of only the
   parts of a document that you need structured access to.  It also has
   features that allow you to find your way around the DOM.
   See http://www.prescod.net/python/pulldom

DOM applications typically start by parsing some XML into a DOM.  How this is
accomplished is not covered at all by DOM Level 1, and Level 2 provides only
limited improvements: There is a :class:`DOMImplementation` object class which
provides access to :class:`Document` creation methods, but no way to access an
XML reader/parser/Document builder in an implementation-independent way. There
is also no well-defined way to access these methods without an existing
:class:`Document` object.  In Python, each DOM implementation will provide a
function :func:`getDOMImplementation`. DOM Level 3 adds a Load/Store
specification, which defines an interface to the reader, but this is not yet
available in the Python standard library.

Once you have a DOM document object, you can access the parts of your XML
document through its properties and methods.  These properties are defined in
the DOM specification; this portion of the reference manual describes the
interpretation of the specification in Python.

The specification provided by the W3C defines the DOM API for Java, ECMAScript,
and OMG IDL.  The Python mapping defined here is based in large part on the IDL
version of the specification, but strict compliance is not required (though
implementations are free to support the strict mapping from IDL).  See section
:ref:`dom-conformance` for a detailed discussion of mapping requirements.


.. seealso::

   `Document Object Model (DOM) Level 2 Specification <https://www.w3.org/TR/DOM-Level-2-Core/>`_
      The W3C recommendation upon which the Python DOM API is based.

   `Document Object Model (DOM) Level 1 Specification <https://www.w3.org/TR/REC-DOM-Level-1/>`_
      The W3C recommendation for the DOM supported by :mod:`xml.dom.minidom`.

   `Python Language Mapping Specification <http://www.omg.org/spec/PYTH/1.2/PDF>`_
      This specifies the mapping from OMG IDL to Python.


Module Contents
---------------

The :mod:`xml.dom` contains the following functions:


.. function:: registerDOMImplementation(name, factory)

   Register the *factory* function with the name *name*.  The factory function
   should return an object which implements the :class:`DOMImplementation`
   interface.  The factory function can return the same object every time, or a new
   one for each call, as appropriate for the specific implementation (e.g. if that
   implementation supports some customization).


.. function:: getDOMImplementation([name[, features]])

   Return a suitable DOM implementation. The *name* is either well-known, the
   module name of a DOM implementation, or ``None``. If it is not ``None``, imports
   the corresponding module and returns a :class:`DOMImplementation` object if the
   import succeeds.  If no name is given, and if the environment variable
   :envvar:`PYTHON_DOM` is set, this variable is used to find the implementation.

   If name is not given, this examines the available implementations to find one
   with the required feature set.  If no implementation can be found, raise an
   :exc:`ImportError`.  The features list must be a sequence of ``(feature,
   version)`` pairs which are passed to the :meth:`hasFeature` method on available
   :class:`DOMImplementation` objects.

Some convenience constants are also provided:


.. data:: EMPTY_NAMESPACE

   The value used to indicate that no namespace is associated with a node in the
   DOM.  This is typically found as the :attr:`namespaceURI` of a node, or used as
   the *namespaceURI* parameter to a namespaces-specific method.

   .. versionadded:: 2.2


.. data:: XML_NAMESPACE

   The namespace URI associated with the reserved prefix ``xml``, as defined by
   `Namespaces in XML <https://www.w3.org/TR/REC-xml-names/>`_ (section 4).

   .. versionadded:: 2.2


.. data:: XMLNS_NAMESPACE

   The namespace URI for namespace declarations, as defined by `Document Object
   Model (DOM) Level 2 Core Specification
   <https://www.w3.org/TR/DOM-Level-2-Core/core.html>`_ (section 1.1.8).

   .. versionadded:: 2.2


.. data:: XHTML_NAMESPACE

   The URI of the XHTML namespace as defined by `XHTML 1.0: The Extensible
   HyperText Markup Language <https://www.w3.org/TR/xhtml1/>`_ (section 3.1.1).

   .. versionadded:: 2.2

In addition, :mod:`xml.dom` contains a base :class:`Node` class and the DOM
exception classes.  The :class:`Node` class provided by this module does not
implement any of the methods or attributes defined by the DOM specification;
concrete DOM implementations must provide those.  The :class:`Node` class
provided as part of this module does provide the constants used for the
:attr:`nodeType` attribute on concrete :class:`Node` objects; they are located
within the class rather than at the module level to conform with the DOM
specifications.

.. Should the Node documentation go here?


.. _dom-objects:

Objects in the DOM
------------------

The definitive documentation for the DOM is the DOM specification from the W3C.

Note that DOM attributes may also be manipulated as nodes instead of as simple
strings.  It is fairly rare that you must do this, however, so this usage is not
yet documented.

+--------------------------------+-----------------------------------+---------------------------------+
| Interface                      | Section                           | Purpose                         |
+================================+===================================+=================================+
| :class:`DOMImplementation`     | :ref:`dom-implementation-objects` | Interface to the underlying     |
|                                |                                   | implementation.                 |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Node`                  | :ref:`dom-node-objects`           | Base interface for most objects |
|                                |                                   | in a document.                  |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`NodeList`              | :ref:`dom-nodelist-objects`       | Interface for a sequence of     |
|                                |                                   | nodes.                          |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`DocumentType`          | :ref:`dom-documenttype-objects`   | Information about the           |
|                                |                                   | declarations needed to process  |
|                                |                                   | a document.                     |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Document`              | :ref:`dom-document-objects`       | Object which represents an      |
|                                |                                   | entire document.                |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Element`               | :ref:`dom-element-objects`        | Element nodes in the document   |
|                                |                                   | hierarchy.                      |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Attr`                  | :ref:`dom-attr-objects`           | Attribute value nodes on        |
|                                |                                   | element nodes.                  |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Comment`               | :ref:`dom-comment-objects`        | Representation of comments in   |
|                                |                                   | the source document.            |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`Text`                  | :ref:`dom-text-objects`           | Nodes containing textual        |
|                                |                                   | content from the document.      |
+--------------------------------+-----------------------------------+---------------------------------+
| :class:`ProcessingInstruction` | :ref:`dom-pi-objects`             | Processing instruction          |
|                                |                                   | representation.                 |
+--------------------------------+-----------------------------------+---------------------------------+

An additional section describes the exceptions defined for working with the DOM
in Python.


.. _dom-implementation-objects:

DOMImplementation Objects
^^^^^^^^^^^^^^^^^^^^^^^^^

The :class:`DOMImplementation` interface provides a way for applications to
determine the availability of particular features in the DOM they are using.
DOM Level 2 added the ability to create new :class:`Document` and
:class:`DocumentType` objects using the :class:`DOMImplementation` as well.


.. method:: DOMImplementation.hasFeature(feature, version)

   Return true if the feature identified by the pair of strings *feature* and
   *version* is implemented.


.. method:: DOMImplementation.createDocument(namespaceUri, qualifiedName, doctype)

   Return a new :class:`Document` object (the root of the DOM), with a child
   :class:`Element` object having the given *namespaceUri* and *qualifiedName*. The
   *doctype* must be a :class:`DocumentType` object created by
   :meth:`createDocumentType`, or ``None``. In the Python DOM API, the first two
   arguments can also be ``None`` in order to indicate that no :class:`Element`
   child is to be created.


.. method:: DOMImplementation.createDocumentType(qualifiedName, publicId, systemId)

   Return a new :class:`DocumentType` object that encapsulates the given
   *qualifiedName*, *publicId*, and *systemId* strings, representing the
   information contained in an XML document type declaration.


.. _dom-node-objects:

Node Objects
^^^^^^^^^^^^

All of the components of an XML document are subclasses of :class:`Node`.


.. attribute:: Node.nodeType

   An integer representing the node type.  Symbolic constants for the types are on
   the :class:`Node` object: :const:`ELEMENT_NODE`, :const:`ATTRIBUTE_NODE`,
   :const:`TEXT_NODE`, :const:`CDATA_SECTION_NODE`, :const:`ENTITY_NODE`,
   :const:`PROCESSING_INSTRUCTION_NODE`, :const:`COMMENT_NODE`,
   :const:`DOCUMENT_NODE`, :const:`DOCUMENT_TYPE_NODE`, :const:`NOTATION_NODE`.
   This is a read-only attribute.


.. attribute:: Node.parentNode

   The parent of the current node, or ``None`` for the document node. The value is
   always a :class:`Node` object or ``None``.  For :class:`Element` nodes, this
   will be the parent element, except for the root element, in which case it will
   be the :class:`Document` object. For :class:`Attr` nodes, this is always
   ``None``. This is a read-only attribute.


.. attribute:: Node.attributes

   A :class:`NamedNodeMap` of attribute objects.  Only elements have actual values
   for this; others provide ``None`` for this attribute. This is a read-only
   attribute.


.. attribute:: Node.previousSibling

   The node that immediately precedes this one with the same parent.  For
   instance the element with an end-tag that comes just before the *self*
   element's start-tag.  Of course, XML documents are made up of more than just
   elements so the previous sibling could be text, a comment, or something else.
   If this node is the first child of the parent, this attribute will be
   ``None``. This is a read-only attribute.


.. attribute:: Node.nextSibling

   The node that immediately follows this one with the same parent.  See also
   :attr:`previousSibling`.  If this is the last child of the parent, this
   attribute will be ``None``. This is a read-only attribute.


.. attribute:: Node.childNodes

   A list of nodes contained within this node. This is a read-only attribute.


.. attribute:: Node.firstChild

   The first child of the node, if there are any, or ``None``. This is a read-only
   attribute.


.. attribute:: Node.lastChild

   The last child of the node, if there are any, or ``None``. This is a read-only
   attribute.


.. attribute:: Node.localName

   The part of the :attr:`tagName` following the colon if there is one, else the
   entire :attr:`tagName`.  The value is a string.


.. attribute:: Node.prefix

   The part of the :attr:`tagName` preceding the colon if there is one, else the
   empty string.  The value is a string, or ``None``.


.. attribute:: Node.namespaceURI

   The namespace associated with the element name.  This will be a string or
   ``None``.  This is a read-only attribute.


.. attribute:: Node.nodeName

   This has a different meaning for each node type; see the DOM specification for
   details.  You can always get the information you would get here from another
   property such as the :attr:`tagName` property for elements or the :attr:`name`
   property for attributes. For all node types, the value of this attribute will be
   either a string or ``None``.  This is a read-only attribute.


.. attribute:: Node.nodeValue

   This has a different meaning for each node type; see the DOM specification for
   details.  The situation is similar to that with :attr:`nodeName`.  The value is
   a string or ``None``.


.. method:: Node.hasAttributes()

   Returns true if the node has any attributes.


.. method:: Node.hasChildNodes()

   Returns true if the node has any child nodes.


.. method:: Node.isSameNode(other)

   Returns true if *other* refers to the same node as this node. This is especially
   useful for DOM implementations which use any sort of proxy architecture (because
   more than one object can refer to the same node).

   .. note::

      This is based on a proposed DOM Level 3 API which is still in the "working
      draft" stage, but this particular interface appears uncontroversial.  Changes
      from the W3C will not necessarily affect this method in the Python DOM interface
      (though any new W3C API for this would also be supported).


.. method:: Node.appendChild(newChild)

   Add a new child node to this node at the end of the list of
   children, returning *newChild*. If the node was already in
   the tree, it is removed first.


.. method:: Node.insertBefore(newChild, refChild)

   Insert a new child node before an existing child.  It must be the case that
   *refChild* is a child of this node; if not, :exc:`ValueError` is raised.
   *newChild* is returned. If *refChild* is ``None``, it inserts *newChild* at the
   end of the children's list.


.. method:: Node.removeChild(oldChild)

   Remove a child node.  *oldChild* must be a child of this node; if not,
   :exc:`ValueError` is raised.  *oldChild* is returned on success.  If *oldChild*
   will not be used further, its :meth:`unlink` method should be called.


.. method:: Node.replaceChild(newChild, oldChild)

   Replace an existing node with a new node. It must be the case that  *oldChild*
   is a child of this node; if not, :exc:`ValueError` is raised.


.. method:: Node.normalize()

   Join adjacent text nodes so that all stretches of text are stored as single
   :class:`Text` instances.  This simplifies processing text from a DOM tree for
   many applications.

   .. versionadded:: 2.1


.. method:: Node.cloneNode(deep)

   Clone this node.  Setting *deep* means to clone all child nodes as well.  This
   returns the clone.


.. _dom-nodelist-objects:

NodeList Objects
^^^^^^^^^^^^^^^^

A :class:`NodeList` represents a sequence of nodes.  These objects are used in
two ways in the DOM Core recommendation:  an :class:`Element` object provides
one as its list of child nodes, and the :meth:`getElementsByTagName` and
:meth:`getElementsByTagNameNS` methods of :class:`Node` return objects with this
interface to represent query results.

The DOM Level 2 recommendation defines one method and one attribute for these
objects:


.. method:: NodeList.item(i)

   Return the *i*'th item from the sequence, if there is one, or ``None``.  The
   index *i* is not allowed to be less than zero or greater than or equal to the
   length of the sequence.


.. attribute:: NodeList.length

   The number of nodes in the sequence.

In addition, the Python DOM interface requires that some additional support is
provided to allow :class:`NodeList` objects to be used as Python sequences.  All
:class:`NodeList` implementations must include support for
:meth:`~object.__len__` and
:meth:`~object.__getitem__`; this allows iteration over the :class:`NodeList` in
:keyword:`for` statements and proper support for the :func:`len` built-in
function.

If a DOM implementation supports modification of the document, the
:class:`NodeList` implementation must also support the
:meth:`~object.__setitem__` and :meth:`~object.__delitem__` methods.


.. _dom-documenttype-objects:

DocumentType Objects
^^^^^^^^^^^^^^^^^^^^

Information about the notations and entities declared by a document (including
the external subset if the parser uses it and can provide the information) is
available from a :class:`DocumentType` object.  The :class:`DocumentType` for a
document is available from the :class:`Document` object's :attr:`doctype`
attribute; if there is no ``DOCTYPE`` declaration for the document, the
document's :attr:`doctype` attribute will be set to ``None`` instead of an
instance of this interface.

:class:`DocumentType` is a specialization of :class:`Node`, and adds the
following attributes:


.. attribute:: DocumentType.publicId

   The public identifier for the external subset of the document type definition.
   This will be a string or ``None``.


.. attribute:: DocumentType.systemId

   The system identifier for the external subset of the document type definition.
   This will be a URI as a string, or ``None``.


.. attribute:: DocumentType.internalSubset

   A string giving the complete internal subset from the document. This does not
   include the brackets which enclose the subset.  If the document has no internal
   subset, this should be ``None``.


.. attribute:: DocumentType.name

   The name of the root element as given in the ``DOCTYPE`` declaration, if
   present.


.. attribute:: DocumentType.entities

   This is a :class:`NamedNodeMap` giving the definitions of external entities.
   For entity names defined more than once, only the first definition is provided
   (others are ignored as required by the XML recommendation).  This may be
   ``None`` if the information is not provided by the parser, or if no entities are
   defined.


.. attribute:: DocumentType.notations

   This is a :class:`NamedNodeMap` giving the definitions of notations. For
   notation names defined more than once, only the first definition is provided
   (others are ignored as required by the XML recommendation).  This may be
   ``None`` if the information is not provided by the parser, or if no notations
   are defined.


.. _dom-document-objects:

Document Objects
^^^^^^^^^^^^^^^^

A :class:`Document` represents an entire XML document, including its constituent
elements, attributes, processing instructions, comments etc.  Remember that it
inherits properties from :class:`Node`.


.. attribute:: Document.documentElement

   The one and only root element of the document.


.. method:: Document.createElement(tagName)

   Create and return a new element node.  The element is not inserted into the
   document when it is created.  You need to explicitly insert it with one of the
   other methods such as :meth:`insertBefore` or :meth:`appendChild`.


.. method:: Document.createElementNS(namespaceURI, tagName)

   Create and return a new element with a namespace.  The *tagName* may have a
   prefix.  The element is not inserted into the document when it is created.  You
   need to explicitly insert it with one of the other methods such as
   :meth:`insertBefore` or :meth:`appendChild`.


.. method:: Document.createTextNode(data)

   Create and return a text node containing the data passed as a parameter.  As
   with the other creation methods, this one does not insert the node into the
   tree.


.. method:: Document.createComment(data)

   Create and return a comment node containing the data passed as a parameter.  As
   with the other creation methods, this one does not insert the node into the
   tree.


.. method:: Document.createProcessingInstruction(target, data)

   Create and return a processing instruction node containing the *target* and
   *data* passed as parameters.  As with the other creation methods, this one does
   not insert the node into the tree.


.. method:: Document.createAttribute(name)

   Create and return an attribute node.  This method does not associate the
   attribute node with any particular element.  You must use
   :meth:`setAttributeNode` on the appropriate :class:`Element` object to use the
   newly created attribute instance.


.. method:: Document.createAttributeNS(namespaceURI, qualifiedName)

   Create and return an attribute node with a namespace.  The *tagName* may have a
   prefix.  This method does not associate the attribute node with any particular
   element.  You must use :meth:`setAttributeNode` on the appropriate
   :class:`Element` object to use the newly created attribute instance.


.. method:: Document.getElementsByTagName(tagName)

   Search for all descendants (direct children, children's children, etc.) with a
   particular element type name.


.. method:: Document.getElementsByTagNameNS(namespaceURI, localName)

   Search for all descendants (direct children, children's children, etc.) with a
   particular namespace URI and localname.  The localname is the part of the
   namespace after the prefix.


.. _dom-element-objects:

Element Objects
^^^^^^^^^^^^^^^

:class:`Element` is a subclass of :class:`Node`, so inherits all the attributes
of that class.


.. attribute:: Element.tagName

   The element type name.  In a namespace-using document it may have colons in it.
   The value is a string.


.. method:: Element.getElementsByTagName(tagName)

   Same as equivalent method in the :class:`Document` class.


.. method:: Element.getElementsByTagNameNS(namespaceURI, localName)

   Same as equivalent method in the :class:`Document` class.


.. method:: Element.hasAttribute(name)

   Returns true if the element has an attribute named by *name*.


.. method:: Element.hasAttributeNS(namespaceURI, localName)

   Returns true if the element has an attribute named by *namespaceURI* and
   *localName*.


.. method:: Element.getAttribute(name)

   Return the value of the attribute named by *name* as a string. If no such
   attribute exists, an empty string is returned, as if the attribute had no value.


.. method:: Element.getAttributeNode(attrname)

   Return the :class:`Attr` node for the attribute named by *attrname*.


.. method:: Element.getAttributeNS(namespaceURI, localName)

   Return the value of the attribute named by *namespaceURI* and *localName* as a
   string. If no such attribute exists, an empty string is returned, as if the
   attribute had no value.


.. method:: Element.getAttributeNodeNS(namespaceURI, localName)

   Return an attribute value as a node, given a *namespaceURI* and *localName*.


.. method:: Element.removeAttribute(name)

   Remove an attribute by name.  If there is no matching attribute, a
   :exc:`NotFoundErr` is raised.


.. method:: Element.removeAttributeNode(oldAttr)

   Remove and return *oldAttr* from the attribute list, if present. If *oldAttr* is
   not present, :exc:`NotFoundErr` is raised.


.. method:: Element.removeAttributeNS(namespaceURI, localName)

   Remove an attribute by name.  Note that it uses a localName, not a qname.  No
   exception is raised if there is no matching attribute.


.. method:: Element.setAttribute(name, value)

   Set an attribute value from a string.


.. method:: Element.setAttributeNode(newAttr)

   Add a new attribute node to the element, replacing an existing attribute if
   necessary if the :attr:`name` attribute matches.  If a replacement occurs, the
   old attribute node will be returned.  If *newAttr* is already in use,
   :exc:`InuseAttributeErr` will be raised.


.. method:: Element.setAttributeNodeNS(newAttr)

   Add a new attribute node to the element, replacing an existing attribute if
   necessary if the :attr:`namespaceURI` and :attr:`localName` attributes match.
   If a replacement occurs, the old attribute node will be returned.  If *newAttr*
   is already in use, :exc:`InuseAttributeErr` will be raised.


.. method:: Element.setAttributeNS(namespaceURI, qname, value)

   Set an attribute value from a string, given a *namespaceURI* and a *qname*.
   Note that a qname is the whole attribute name.  This is different than above.


.. _dom-attr-objects:

Attr Objects
^^^^^^^^^^^^

:class:`Attr` inherits from :class:`Node`, so inherits all its attributes.


.. attribute:: Attr.name

   The attribute name.
   In a namespace-using document it may include a colon.


.. attribute:: Attr.localName

   The part of the name following the colon if there is one, else the
   entire name.
   This is a read-only attribute.


.. attribute:: Attr.prefix

   The part of the name preceding the colon if there is one, else the
   empty string.


.. attribute:: Attr.value

   The text value of the attribute.  This is a synonym for the
   :attr:`nodeValue` attribute.


.. _dom-attributelist-objects:

NamedNodeMap Objects
^^^^^^^^^^^^^^^^^^^^

:class:`NamedNodeMap` does *not* inherit from :class:`Node`.


.. attribute:: NamedNodeMap.length

   The length of the attribute list.


.. method:: NamedNodeMap.item(index)

   Return an attribute with a particular index.  The order you get the attributes
   in is arbitrary but will be consistent for the life of a DOM.  Each item is an
   attribute node.  Get its value with the :attr:`value` attribute.

There are also experimental methods that give this class more mapping behavior.
You can use them or you can use the standardized :meth:`getAttribute\*` family
of methods on the :class:`Element` objects.


.. _dom-comment-objects:

Comment Objects
^^^^^^^^^^^^^^^

:class:`Comment` represents a comment in the XML document.  It is a subclass of
:class:`Node`, but cannot have child nodes.


.. attribute:: Comment.data

   The content of the comment as a string.  The attribute contains all characters
   between the leading ``<!-``\ ``-`` and trailing ``-``\ ``->``, but does not
   include them.


.. _dom-text-objects:

Text and CDATASection Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The :class:`Text` interface represents text in the XML document.  If the parser
and DOM implementation support the DOM's XML extension, portions of the text
enclosed in CDATA marked sections are stored in :class:`CDATASection` objects.
These two interfaces are identical, but provide different values for the
:attr:`nodeType` attribute.

These interfaces extend the :class:`Node` interface.  They cannot have child
nodes.


.. attribute:: Text.data

   The content of the text node as a string.

.. note::

   The use of a :class:`CDATASection` node does not indicate that the node
   represents a complete CDATA marked section, only that the content of the node
   was part of a CDATA section.  A single CDATA section may be represented by more
   than one node in the document tree.  There is no way to determine whether two
   adjacent :class:`CDATASection` nodes represent different CDATA marked sections.


.. _dom-pi-objects:

ProcessingInstruction Objects
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Represents a processing instruction in the XML document; this inherits from the
:class:`Node` interface and cannot have child nodes.


.. attribute:: ProcessingInstruction.target

   The content of the processing instruction up to the first whitespace character.
   This is a read-only attribute.


.. attribute:: ProcessingInstruction.data

   The content of the processing instruction following the first whitespace
   character.


.. _dom-exceptions:

Exceptions
^^^^^^^^^^

.. versionadded:: 2.1

The DOM Level 2 recommendation defines a single exception, :exc:`DOMException`,
and a number of constants that allow applications to determine what sort of
error occurred. :exc:`DOMException` instances carry a :attr:`code` attribute
that provides the appropriate value for the specific exception.

The Python DOM interface provides the constants, but also expands the set of
exceptions so that a specific exception exists for each of the exception codes
defined by the DOM.  The implementations must raise the appropriate specific
exception, each of which carries the appropriate value for the :attr:`code`
attribute.


.. exception:: DOMException

   Base exception class used for all specific DOM exceptions.  This exception class
   cannot be directly instantiated.


.. exception:: DomstringSizeErr

   Raised when a specified range of text does not fit into a string. This is not
   known to be used in the Python DOM implementations, but may be received from DOM
   implementations not written in Python.


.. exception:: HierarchyRequestErr

   Raised when an attempt is made to insert a node where the node type is not
   allowed.


.. exception:: IndexSizeErr

   Raised when an index or size parameter to a method is negative or exceeds the
   allowed values.


.. exception:: InuseAttributeErr

   Raised when an attempt is made to insert an :class:`Attr` node that is already
   present elsewhere in the document.


.. exception:: InvalidAccessErr

   Raised if a parameter or an operation is not supported on the underlying object.


.. exception:: InvalidCharacterErr

   This exception is raised when a string parameter contains a character that is
   not permitted in the context it's being used in by the XML 1.0 recommendation.
   For example, attempting to create an :class:`Element` node with a space in the
   element type name will cause this error to be raised.


.. exception:: InvalidModificationErr

   Raised when an attempt is made to modify the type of a node.


.. exception:: InvalidStateErr

   Raised when an attempt is made to use an object that is not defined or is no
   longer usable.


.. exception:: NamespaceErr

   If an attempt is made to change any object in a way that is not permitted with
   regard to the `Namespaces in XML <https://www.w3.org/TR/REC-xml-names/>`_
   recommendation, this exception is raised.


.. exception:: NotFoundErr

   Exception when a node does not exist in the referenced context.  For example,
   :meth:`NamedNodeMap.removeNamedItem` will raise this if the node passed in does
   not exist in the map.


.. exception:: NotSupportedErr

   Raised when the implementation does not support the requested type of object or
   operation.


.. exception:: NoDataAllowedErr

   This is raised if data is specified for a node which does not support data.

   .. XXX  a better explanation is needed!


.. exception:: NoModificationAllowedErr

   Raised on attempts to modify an object where modifications are not allowed (such
   as for read-only nodes).


.. exception:: SyntaxErr

   Raised when an invalid or illegal string is specified.

   .. XXX  how is this different from InvalidCharacterErr?


.. exception:: WrongDocumentErr

   Raised when a node is inserted in a different document than it currently belongs
   to, and the implementation does not support migrating the node from one document
   to the other.

The exception codes defined in the DOM recommendation map to the exceptions
described above according to this table:

+--------------------------------------+---------------------------------+
| Constant                             | Exception                       |
+======================================+=================================+
| :const:`DOMSTRING_SIZE_ERR`          | :exc:`DomstringSizeErr`         |
+--------------------------------------+---------------------------------+
| :const:`HIERARCHY_REQUEST_ERR`       | :exc:`HierarchyRequestErr`      |
+--------------------------------------+---------------------------------+
| :const:`INDEX_SIZE_ERR`              | :exc:`IndexSizeErr`             |
+--------------------------------------+---------------------------------+
| :const:`INUSE_ATTRIBUTE_ERR`         | :exc:`InuseAttributeErr`        |
+--------------------------------------+---------------------------------+
| :const:`INVALID_ACCESS_ERR`          | :exc:`InvalidAccessErr`         |
+--------------------------------------+---------------------------------+
| :const:`INVALID_CHARACTER_ERR`       | :exc:`InvalidCharacterErr`      |
+--------------------------------------+---------------------------------+
| :const:`INVALID_MODIFICATION_ERR`    | :exc:`InvalidModificationErr`   |
+--------------------------------------+---------------------------------+
| :const:`INVALID_STATE_ERR`           | :exc:`InvalidStateErr`          |
+--------------------------------------+---------------------------------+
| :const:`NAMESPACE_ERR`               | :exc:`NamespaceErr`             |
+--------------------------------------+---------------------------------+
| :const:`NOT_FOUND_ERR`               | :exc:`NotFoundErr`              |
+--------------------------------------+---------------------------------+
| :const:`NOT_SUPPORTED_ERR`           | :exc:`NotSupportedErr`          |
+--------------------------------------+---------------------------------+
| :const:`NO_DATA_ALLOWED_ERR`         | :exc:`NoDataAllowedErr`         |
+--------------------------------------+---------------------------------+
| :const:`NO_MODIFICATION_ALLOWED_ERR` | :exc:`NoModificationAllowedErr` |
+--------------------------------------+---------------------------------+
| :const:`SYNTAX_ERR`                  | :exc:`SyntaxErr`                |
+--------------------------------------+---------------------------------+
| :const:`WRONG_DOCUMENT_ERR`          | :exc:`WrongDocumentErr`         |
+--------------------------------------+---------------------------------+


.. _dom-conformance:

Conformance
-----------

This section describes the conformance requirements and relationships between
the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for
Python.


.. _dom-type-mapping:

Type Mapping
^^^^^^^^^^^^

The primitive IDL types used in the DOM specification are mapped to Python types
according to the following table.

+------------------+-------------------------------------------+
| IDL Type         | Python Type                               |
+==================+===========================================+
| ``boolean``      | ``IntegerType`` (with a value of ``0`` or |
|                  | ``1``)                                    |
+------------------+-------------------------------------------+
| ``int``          | ``IntegerType``                           |
+------------------+-------------------------------------------+
| ``long int``     | ``IntegerType``                           |
+------------------+-------------------------------------------+
| ``unsigned int`` | ``IntegerType``                           |
+------------------+-------------------------------------------+

Additionally, the :class:`DOMString` defined in the recommendation is mapped to
a Python string or Unicode string.  Applications should be able to handle
Unicode whenever a string is returned from the DOM.

The IDL ``null`` value is mapped to ``None``, which may be accepted or
provided by the implementation whenever ``null`` is allowed by the API.


.. _dom-accessor-methods:

Accessor Methods
^^^^^^^^^^^^^^^^

The mapping from OMG IDL to Python defines accessor functions for IDL
``attribute`` declarations in much the way the Java mapping does.
Mapping the IDL declarations ::

   readonly attribute string someValue;
            attribute string anotherValue;

yields three accessor functions:  a "get" method for :attr:`someValue`
(:meth:`_get_someValue`), and "get" and "set" methods for :attr:`anotherValue`
(:meth:`_get_anotherValue` and :meth:`_set_anotherValue`).  The mapping, in
particular, does not require that the IDL attributes are accessible as normal
Python attributes:  ``object.someValue`` is *not* required to work, and may
raise an :exc:`AttributeError`.

The Python DOM API, however, *does* require that normal attribute access work.
This means that the typical surrogates generated by Python IDL compilers are not
likely to work, and wrapper objects may be needed on the client if the DOM
objects are accessed via CORBA. While this does require some additional
consideration for CORBA DOM clients, the implementers with experience using DOM
over CORBA from Python do not consider this a problem.  Attributes that are
declared ``readonly`` may not restrict write access in all DOM
implementations.

In the Python DOM API, accessor functions are not required.  If provided, they
should take the form defined by the Python IDL mapping, but these methods are
considered unnecessary since the attributes are accessible directly from Python.
"Set" accessors should never be provided for ``readonly`` attributes.

The IDL definitions do not fully embody the requirements of the W3C DOM API,
such as the notion of certain objects, such as the return value of
:meth:`getElementsByTagName`, being "live".  The Python DOM API does not require
implementations to enforce such requirements.

PK
%�\b�~�{�{�3html/_sources/library/xml.etree.elementtree.rst.txtnu�[���:mod:`xml.etree.ElementTree` --- The ElementTree XML API
========================================================

.. module:: xml.etree.ElementTree
   :synopsis: Implementation of the ElementTree API.
.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>


.. versionadded:: 2.5

**Source code:** :source:`Lib/xml/etree/ElementTree.py`

--------------

The :class:`Element` type is a flexible container object, designed to store
hierarchical data structures in memory.  The type can be described as a cross
between a list and a dictionary.


.. warning::

   The :mod:`xml.etree.ElementTree` module is not secure against
   maliciously constructed data.  If you need to parse untrusted or
   unauthenticated data see :ref:`xml-vulnerabilities`.


Each element has a number of properties associated with it:

* a tag which is a string identifying what kind of data this element represents
  (the element type, in other words).

* a number of attributes, stored in a Python dictionary.

* a text string.

* an optional tail string.

* a number of child elements, stored in a Python sequence

To create an element instance, use the :class:`Element` constructor or the
:func:`SubElement` factory function.

The :class:`ElementTree` class can be used to wrap an element structure, and
convert it from and to XML.

A C implementation of this API is available as :mod:`xml.etree.cElementTree`.

See http://effbot.org/zone/element-index.htm for tutorials and links to other
docs.  Fredrik Lundh's page is also the location of the development version of
the xml.etree.ElementTree.

.. versionchanged:: 2.7
   The ElementTree API is updated to 1.3.  For more information, see
   `Introducing ElementTree 1.3
   <http://effbot.org/zone/elementtree-13-intro.htm>`_.

Tutorial
--------

This is a short tutorial for using :mod:`xml.etree.ElementTree` (``ET`` in
short).  The goal is to demonstrate some of the building blocks and basic
concepts of the module.

XML tree and elements
^^^^^^^^^^^^^^^^^^^^^

XML is an inherently hierarchical data format, and the most natural way to
represent it is with a tree.  ``ET`` has two classes for this purpose -
:class:`ElementTree` represents the whole XML document as a tree, and
:class:`Element` represents a single node in this tree.  Interactions with
the whole document (reading and writing to/from files) are usually done
on the :class:`ElementTree` level.  Interactions with a single XML element
and its sub-elements are done on the :class:`Element` level.

.. _elementtree-parsing-xml:

Parsing XML
^^^^^^^^^^^

We'll be using the following XML document as the sample data for this section:

.. code-block:: xml

   <?xml version="1.0"?>
   <data>
       <country name="Liechtenstein">
           <rank>1</rank>
           <year>2008</year>
           <gdppc>141100</gdppc>
           <neighbor name="Austria" direction="E"/>
           <neighbor name="Switzerland" direction="W"/>
       </country>
       <country name="Singapore">
           <rank>4</rank>
           <year>2011</year>
           <gdppc>59900</gdppc>
           <neighbor name="Malaysia" direction="N"/>
       </country>
       <country name="Panama">
           <rank>68</rank>
           <year>2011</year>
           <gdppc>13600</gdppc>
           <neighbor name="Costa Rica" direction="W"/>
           <neighbor name="Colombia" direction="E"/>
       </country>
   </data>

We have a number of ways to import the data.  Reading the file from disk::

   import xml.etree.ElementTree as ET
   tree = ET.parse('country_data.xml')
   root = tree.getroot()

Reading the data from a string::

   root = ET.fromstring(country_data_as_string)

:func:`fromstring` parses XML from a string directly into an :class:`Element`,
which is the root element of the parsed tree.  Other parsing functions may
create an :class:`ElementTree`.  Check the documentation to be sure.

As an :class:`Element`, ``root`` has a tag and a dictionary of attributes::

   >>> root.tag
   'data'
   >>> root.attrib
   {}

It also has children nodes over which we can iterate::

   >>> for child in root:
   ...     print child.tag, child.attrib
   ...
   country {'name': 'Liechtenstein'}
   country {'name': 'Singapore'}
   country {'name': 'Panama'}

Children are nested, and we can access specific child nodes by index::

   >>> root[0][1].text
   '2008'

Finding interesting elements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

:class:`Element` has some useful methods that help iterate recursively over all
the sub-tree below it (its children, their children, and so on).  For example,
:meth:`Element.iter`::

   >>> for neighbor in root.iter('neighbor'):
   ...     print neighbor.attrib
   ...
   {'name': 'Austria', 'direction': 'E'}
   {'name': 'Switzerland', 'direction': 'W'}
   {'name': 'Malaysia', 'direction': 'N'}
   {'name': 'Costa Rica', 'direction': 'W'}
   {'name': 'Colombia', 'direction': 'E'}

:meth:`Element.findall` finds only elements with a tag which are direct
children of the current element.  :meth:`Element.find` finds the *first* child
with a particular tag, and :attr:`Element.text` accesses the element's text
content.  :meth:`Element.get` accesses the element's attributes::

   >>> for country in root.findall('country'):
   ...     rank = country.find('rank').text
   ...     name = country.get('name')
   ...     print name, rank
   ...
   Liechtenstein 1
   Singapore 4
   Panama 68

More sophisticated specification of which elements to look for is possible by
using :ref:`XPath <elementtree-xpath>`.

Modifying an XML File
^^^^^^^^^^^^^^^^^^^^^

:class:`ElementTree` provides a simple way to build XML documents and write them to files.
The :meth:`ElementTree.write` method serves this purpose.

Once created, an :class:`Element` object may be manipulated by directly changing
its fields (such as :attr:`Element.text`), adding and modifying attributes
(:meth:`Element.set` method), as well as adding new children (for example
with :meth:`Element.append`).

Let's say we want to add one to each country's rank, and add an ``updated``
attribute to the rank element::

   >>> for rank in root.iter('rank'):
   ...     new_rank = int(rank.text) + 1
   ...     rank.text = str(new_rank)
   ...     rank.set('updated', 'yes')
   ...
   >>> tree.write('output.xml')

Our XML now looks like this:

.. code-block:: xml

   <?xml version="1.0"?>
   <data>
       <country name="Liechtenstein">
           <rank updated="yes">2</rank>
           <year>2008</year>
           <gdppc>141100</gdppc>
           <neighbor name="Austria" direction="E"/>
           <neighbor name="Switzerland" direction="W"/>
       </country>
       <country name="Singapore">
           <rank updated="yes">5</rank>
           <year>2011</year>
           <gdppc>59900</gdppc>
           <neighbor name="Malaysia" direction="N"/>
       </country>
       <country name="Panama">
           <rank updated="yes">69</rank>
           <year>2011</year>
           <gdppc>13600</gdppc>
           <neighbor name="Costa Rica" direction="W"/>
           <neighbor name="Colombia" direction="E"/>
       </country>
   </data>

We can remove elements using :meth:`Element.remove`.  Let's say we want to
remove all countries with a rank higher than 50::

   >>> for country in root.findall('country'):
   ...     rank = int(country.find('rank').text)
   ...     if rank > 50:
   ...         root.remove(country)
   ...
   >>> tree.write('output.xml')

Our XML now looks like this:

.. code-block:: xml

   <?xml version="1.0"?>
   <data>
       <country name="Liechtenstein">
           <rank updated="yes">2</rank>
           <year>2008</year>
           <gdppc>141100</gdppc>
           <neighbor name="Austria" direction="E"/>
           <neighbor name="Switzerland" direction="W"/>
       </country>
       <country name="Singapore">
           <rank updated="yes">5</rank>
           <year>2011</year>
           <gdppc>59900</gdppc>
           <neighbor name="Malaysia" direction="N"/>
       </country>
   </data>

Building XML documents
^^^^^^^^^^^^^^^^^^^^^^

The :func:`SubElement` function also provides a convenient way to create new
sub-elements for a given element::

   >>> a = ET.Element('a')
   >>> b = ET.SubElement(a, 'b')
   >>> c = ET.SubElement(a, 'c')
   >>> d = ET.SubElement(c, 'd')
   >>> ET.dump(a)
   <a><b /><c><d /></c></a>

Parsing XML with Namespaces
^^^^^^^^^^^^^^^^^^^^^^^^^^^

If the XML input has `namespaces
<https://en.wikipedia.org/wiki/XML_namespace>`__, tags and attributes
with prefixes in the form ``prefix:sometag`` get expanded to
``{uri}sometag`` where the *prefix* is replaced by the full *URI*.
Also, if there is a `default namespace
<https://www.w3.org/TR/xml-names/#defaulting>`__,
that full URI gets prepended to all of the non-prefixed tags.

Here is an XML example that incorporates two namespaces, one with the
prefix "fictional" and the other serving as the default namespace:

.. code-block:: xml

    <?xml version="1.0"?>
    <actors xmlns:fictional="http://characters.example.com"
            xmlns="http://people.example.com">
        <actor>
            <name>John Cleese</name>
            <fictional:character>Lancelot</fictional:character>
            <fictional:character>Archie Leach</fictional:character>
        </actor>
        <actor>
            <name>Eric Idle</name>
            <fictional:character>Sir Robin</fictional:character>
            <fictional:character>Gunther</fictional:character>
            <fictional:character>Commander Clement</fictional:character>
        </actor>
    </actors>

One way to search and explore this XML example is to manually add the
URI to every tag or attribute in the xpath of a
:meth:`~Element.find` or :meth:`~Element.findall`::

    root = fromstring(xml_text)
    for actor in root.findall('{http://people.example.com}actor'):
        name = actor.find('{http://people.example.com}name')
        print name.text
        for char in actor.findall('{http://characters.example.com}character'):
            print ' |-->', char.text


A better way to search the namespaced XML example is to create a
dictionary with your own prefixes and use those in the search functions::

    ns = {'real_person': 'http://people.example.com',
          'role': 'http://characters.example.com'}

    for actor in root.findall('real_person:actor', ns):
        name = actor.find('real_person:name', ns)
        print name.text
        for char in actor.findall('role:character', ns):
            print ' |-->', char.text

These two approaches both output::

    John Cleese
     |--> Lancelot
     |--> Archie Leach
    Eric Idle
     |--> Sir Robin
     |--> Gunther
     |--> Commander Clement


Additional resources
^^^^^^^^^^^^^^^^^^^^

See http://effbot.org/zone/element-index.htm for tutorials and links to other
docs.

.. _elementtree-xpath:

XPath support
-------------

This module provides limited support for
`XPath expressions <https://www.w3.org/TR/xpath>`_ for locating elements in a
tree.  The goal is to support a small subset of the abbreviated syntax; a full
XPath engine is outside the scope of the module.

Example
^^^^^^^

Here's an example that demonstrates some of the XPath capabilities of the
module.  We'll be using the ``countrydata`` XML document from the
:ref:`Parsing XML <elementtree-parsing-xml>` section::

   import xml.etree.ElementTree as ET

   root = ET.fromstring(countrydata)

   # Top-level elements
   root.findall(".")

   # All 'neighbor' grand-children of 'country' children of the top-level
   # elements
   root.findall("./country/neighbor")

   # Nodes with name='Singapore' that have a 'year' child
   root.findall(".//year/..[@name='Singapore']")

   # 'year' nodes that are children of nodes with name='Singapore'
   root.findall(".//*[@name='Singapore']/year")

   # All 'neighbor' nodes that are the second child of their parent
   root.findall(".//neighbor[2]")

Supported XPath syntax
^^^^^^^^^^^^^^^^^^^^^^

.. tabularcolumns:: |l|L|

+-----------------------+------------------------------------------------------+
| Syntax                | Meaning                                              |
+=======================+======================================================+
| ``tag``               | Selects all child elements with the given tag.       |
|                       | For example, ``spam`` selects all child elements     |
|                       | named ``spam``, and ``spam/egg`` selects all         |
|                       | grandchildren named ``egg`` in all children named    |
|                       | ``spam``.                                            |
+-----------------------+------------------------------------------------------+
| ``*``                 | Selects all child elements.  For example, ``*/egg``  |
|                       | selects all grandchildren named ``egg``.             |
+-----------------------+------------------------------------------------------+
| ``.``                 | Selects the current node.  This is mostly useful     |
|                       | at the beginning of the path, to indicate that it's  |
|                       | a relative path.                                     |
+-----------------------+------------------------------------------------------+
| ``//``                | Selects all subelements, on all levels beneath the   |
|                       | current  element.  For example, ``.//egg`` selects   |
|                       | all ``egg`` elements in the entire tree.             |
+-----------------------+------------------------------------------------------+
| ``..``                | Selects the parent element.                          |
+-----------------------+------------------------------------------------------+
| ``[@attrib]``         | Selects all elements that have the given attribute.  |
+-----------------------+------------------------------------------------------+
| ``[@attrib='value']`` | Selects all elements for which the given attribute   |
|                       | has the given value.  The value cannot contain       |
|                       | quotes.                                              |
+-----------------------+------------------------------------------------------+
| ``[tag]``             | Selects all elements that have a child named         |
|                       | ``tag``.  Only immediate children are supported.     |
+-----------------------+------------------------------------------------------+
| ``[tag='text']``      | Selects all elements that have a child named         |
|                       | ``tag`` whose complete text content, including       |
|                       | descendants, equals the given ``text``.              |
+-----------------------+------------------------------------------------------+
| ``[position]``        | Selects all elements that are located at the given   |
|                       | position.  The position can be either an integer     |
|                       | (1 is the first position), the expression ``last()`` |
|                       | (for the last position), or a position relative to   |
|                       | the last position (e.g. ``last()-1``).               |
+-----------------------+------------------------------------------------------+

Predicates (expressions within square brackets) must be preceded by a tag
name, an asterisk, or another predicate.  ``position`` predicates must be
preceded by a tag name.

Reference
---------

.. _elementtree-functions:

Functions
^^^^^^^^^


.. function:: Comment(text=None)

   Comment element factory.  This factory function creates a special element
   that will be serialized as an XML comment by the standard serializer.  The
   comment string can be either a bytestring or a Unicode string.  *text* is a
   string containing the comment string.  Returns an element instance
   representing a comment.


.. function:: dump(elem)

   Writes an element tree or element structure to sys.stdout.  This function
   should be used for debugging only.

   The exact output format is implementation dependent.  In this version, it's
   written as an ordinary XML file.

   *elem* is an element tree or an individual element.


.. function:: fromstring(text)

   Parses an XML section from a string constant.  Same as :func:`XML`.  *text*
   is a string containing XML data.  Returns an :class:`Element` instance.


.. function:: fromstringlist(sequence, parser=None)

   Parses an XML document from a sequence of string fragments.  *sequence* is a
   list or other sequence containing XML data fragments.  *parser* is an
   optional parser instance.  If not given, the standard :class:`XMLParser`
   parser is used.  Returns an :class:`Element` instance.

   .. versionadded:: 2.7


.. function:: iselement(element)

   Checks if an object appears to be a valid element object.  *element* is an
   element instance.  Returns a true value if this is an element object.


.. function:: iterparse(source, events=None, parser=None)

   Parses an XML section into an element tree incrementally, and reports what's
   going on to the user.  *source* is a filename or file object containing XML
   data.  *events* is a list of events to report back.  If omitted, only "end"
   events are reported.  *parser* is an optional parser instance.  If not
   given, the standard :class:`XMLParser` parser is used.  *parser* is not
   supported by ``cElementTree``. Returns an :term:`iterator` providing
   ``(event, elem)`` pairs.

   .. note::

      :func:`iterparse` only guarantees that it has seen the ">"
      character of a starting tag when it emits a "start" event, so the
      attributes are defined, but the contents of the text and tail attributes
      are undefined at that point.  The same applies to the element children;
      they may or may not be present.

      If you need a fully populated element, look for "end" events instead.


.. function:: parse(source, parser=None)

   Parses an XML section into an element tree.  *source* is a filename or file
   object containing XML data.  *parser* is an optional parser instance.  If
   not given, the standard :class:`XMLParser` parser is used.  Returns an
   :class:`ElementTree` instance.


.. function:: ProcessingInstruction(target, text=None)

   PI element factory.  This factory function creates a special element that
   will be serialized as an XML processing instruction.  *target* is a string
   containing the PI target.  *text* is a string containing the PI contents, if
   given.  Returns an element instance, representing a processing instruction.


.. function:: register_namespace(prefix, uri)

   Registers a namespace prefix.  The registry is global, and any existing
   mapping for either the given prefix or the namespace URI will be removed.
   *prefix* is a namespace prefix.  *uri* is a namespace uri.  Tags and
   attributes in this namespace will be serialized with the given prefix, if at
   all possible.

   .. versionadded:: 2.7


.. function:: SubElement(parent, tag, attrib={}, **extra)

   Subelement factory.  This function creates an element instance, and appends
   it to an existing element.

   The element name, attribute names, and attribute values can be either
   bytestrings or Unicode strings.  *parent* is the parent element.  *tag* is
   the subelement name.  *attrib* is an optional dictionary, containing element
   attributes.  *extra* contains additional attributes, given as keyword
   arguments.  Returns an element instance.


.. function:: tostring(element, encoding="us-ascii", method="xml")

   Generates a string representation of an XML element, including all
   subelements.  *element* is an :class:`Element` instance.  *encoding* [1]_ is
   the output encoding (default is US-ASCII).  *method* is either ``"xml"``,
   ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns an encoded string
   containing the XML data.


.. function:: tostringlist(element, encoding="us-ascii", method="xml")

   Generates a string representation of an XML element, including all
   subelements.  *element* is an :class:`Element` instance.  *encoding* [1]_ is
   the output encoding (default is US-ASCII).   *method* is either ``"xml"``,
   ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns a list of encoded
   strings containing the XML data.  It does not guarantee any specific
   sequence, except that ``"".join(tostringlist(element)) ==
   tostring(element)``.

   .. versionadded:: 2.7


.. function:: XML(text, parser=None)

   Parses an XML section from a string constant.  This function can be used to
   embed "XML literals" in Python code.  *text* is a string containing XML
   data.  *parser* is an optional parser instance.  If not given, the standard
   :class:`XMLParser` parser is used.  Returns an :class:`Element` instance.


.. function:: XMLID(text, parser=None)

   Parses an XML section from a string constant, and also returns a dictionary
   which maps from element id:s to elements.  *text* is a string containing XML
   data.  *parser* is an optional parser instance.  If not given, the standard
   :class:`XMLParser` parser is used.  Returns a tuple containing an
   :class:`Element` instance and a dictionary.


.. _elementtree-element-objects:

Element Objects
^^^^^^^^^^^^^^^

.. class:: Element(tag, attrib={}, **extra)

   Element class.  This class defines the Element interface, and provides a
   reference implementation of this interface.

   The element name, attribute names, and attribute values can be either
   bytestrings or Unicode strings.  *tag* is the element name.  *attrib* is
   an optional dictionary, containing element attributes.  *extra* contains
   additional attributes, given as keyword arguments.


   .. attribute:: tag

      A string identifying what kind of data this element represents (the
      element type, in other words).


   .. attribute:: text
                  tail

      These attributes can be used to hold additional data associated with
      the element.  Their values are usually strings but may be any
      application-specific object.  If the element is created from
      an XML file, the *text* attribute holds either the text between
      the element's start tag and its first child or end tag, or ``None``, and
      the *tail* attribute holds either the text between the element's
      end tag and the next tag, or ``None``.  For the XML data

      .. code-block:: xml

         <a><b>1<c>2<d/>3</c></b>4</a>

      the *a* element has ``None`` for both *text* and *tail* attributes,
      the *b* element has *text* ``"1"`` and *tail* ``"4"``,
      the *c* element has *text* ``"2"`` and *tail* ``None``,
      and the *d* element has *text* ``None`` and *tail* ``"3"``.

      To collect the inner text of an element, see :meth:`itertext`, for
      example ``"".join(element.itertext())``.

      Applications may store arbitrary objects in these attributes.


   .. attribute:: attrib

      A dictionary containing the element's attributes.  Note that while the
      *attrib* value is always a real mutable Python dictionary, an ElementTree
      implementation may choose to use another internal representation, and
      create the dictionary only if someone asks for it.  To take advantage of
      such implementations, use the dictionary methods below whenever possible.

   The following dictionary-like methods work on the element attributes.


   .. method:: clear()

      Resets an element.  This function removes all subelements, clears all
      attributes, and sets the text and tail attributes to ``None``.


   .. method:: get(key, default=None)

      Gets the element attribute named *key*.

      Returns the attribute value, or *default* if the attribute was not found.


   .. method:: items()

      Returns the element attributes as a sequence of (name, value) pairs.  The
      attributes are returned in an arbitrary order.


   .. method:: keys()

      Returns the elements attribute names as a list.  The names are returned
      in an arbitrary order.


   .. method:: set(key, value)

      Set the attribute *key* on the element to *value*.

   The following methods work on the element's children (subelements).


   .. method:: append(subelement)

      Adds the element *subelement* to the end of this elements internal list
      of subelements.


   .. method:: extend(subelements)

      Appends *subelements* from a sequence object with zero or more elements.
      Raises :exc:`AssertionError` if a subelement is not a valid object.

      .. versionadded:: 2.7


   .. method:: find(match)

      Finds the first subelement matching *match*.  *match* may be a tag name
      or path.  Returns an element instance or ``None``.


   .. method:: findall(match)

      Finds all matching subelements, by tag name or path.  Returns a list
      containing all matching elements in document order.


   .. method:: findtext(match, default=None)

      Finds text for the first subelement matching *match*.  *match* may be
      a tag name or path.  Returns the text content of the first matching
      element, or *default* if no element was found.  Note that if the matching
      element has no text content an empty string is returned.


   .. method:: getchildren()

      .. deprecated:: 2.7
         Use ``list(elem)`` or iteration.


   .. method:: getiterator(tag=None)

      .. deprecated:: 2.7
         Use method :meth:`Element.iter` instead.


   .. method:: insert(index, element)

      Inserts a subelement at the given position in this element.


   .. method:: iter(tag=None)

      Creates a tree :term:`iterator` with the current element as the root.
      The iterator iterates over this element and all elements below it, in
      document (depth first) order.  If *tag* is not ``None`` or ``'*'``, only
      elements whose tag equals *tag* are returned from the iterator.  If the
      tree structure is modified during iteration, the result is undefined.

      .. versionadded:: 2.7


   .. method:: iterfind(match)

      Finds all matching subelements, by tag name or path.  Returns an iterable
      yielding all matching elements in document order.

      .. versionadded:: 2.7


   .. method:: itertext()

      Creates a text iterator.  The iterator loops over this element and all
      subelements, in document order, and returns all inner text.

      .. versionadded:: 2.7


   .. method:: makeelement(tag, attrib)

      Creates a new element object of the same type as this element.  Do not
      call this method, use the :func:`SubElement` factory function instead.


   .. method:: remove(subelement)

      Removes *subelement* from the element.  Unlike the find\* methods this
      method compares elements based on the instance identity, not on tag value
      or contents.

   :class:`Element` objects also support the following sequence type methods
   for working with subelements: :meth:`~object.__delitem__`,
   :meth:`~object.__getitem__`, :meth:`~object.__setitem__`,
   :meth:`~object.__len__`.

   Caution: Elements with no subelements will test as ``False``.  This behavior
   will change in future versions.  Use specific ``len(elem)`` or ``elem is
   None`` test instead. ::

     element = root.find('foo')

     if not element:  # careful!
         print "element not found, or element has no subelements"

     if element is None:
         print "element not found"


.. _elementtree-elementtree-objects:

ElementTree Objects
^^^^^^^^^^^^^^^^^^^


.. class:: ElementTree(element=None, file=None)

   ElementTree wrapper class.  This class represents an entire element
   hierarchy, and adds some extra support for serialization to and from
   standard XML.

   *element* is the root element.  The tree is initialized with the contents
   of the XML *file* if given.


   .. method:: _setroot(element)

      Replaces the root element for this tree.  This discards the current
      contents of the tree, and replaces it with the given element.  Use with
      care.  *element* is an element instance.


   .. method:: find(match)

      Same as :meth:`Element.find`, starting at the root of the tree.


   .. method:: findall(match)

      Same as :meth:`Element.findall`, starting at the root of the tree.


   .. method:: findtext(match, default=None)

      Same as :meth:`Element.findtext`, starting at the root of the tree.


   .. method:: getiterator(tag=None)

      .. deprecated:: 2.7
         Use method :meth:`ElementTree.iter` instead.


   .. method:: getroot()

      Returns the root element for this tree.


   .. method:: iter(tag=None)

      Creates and returns a tree iterator for the root element.  The iterator
      loops over all elements in this tree, in section order.  *tag* is the tag
      to look for (default is to return all elements).


   .. method:: iterfind(match)

      Finds all matching subelements, by tag name or path.  Same as
      getroot().iterfind(match). Returns an iterable yielding all matching
      elements in document order.

      .. versionadded:: 2.7


   .. method:: parse(source, parser=None)

      Loads an external XML section into this element tree.  *source* is a file
      name or file object.  *parser* is an optional parser instance.  If not
      given, the standard XMLParser parser is used.  Returns the section
      root element.


   .. method:: write(file, encoding="us-ascii", xml_declaration=None, \
                     default_namespace=None, method="xml")

      Writes the element tree to a file, as XML.  *file* is a file name, or a
      file object opened for writing.  *encoding* [1]_ is the output encoding
      (default is US-ASCII).  *xml_declaration* controls if an XML declaration
      should be added to the file.  Use ``False`` for never, ``True`` for always, ``None``
      for only if not US-ASCII or UTF-8 (default is ``None``).  *default_namespace*
      sets the default XML namespace (for "xmlns").  *method* is either
      ``"xml"``, ``"html"`` or ``"text"`` (default is ``"xml"``).  Returns an
      encoded string.

This is the XML file that is going to be manipulated::

    <html>
        <head>
            <title>Example page</title>
        </head>
        <body>
            <p>Moved to <a href="http://example.org/">example.org</a>
            or <a href="http://example.com/">example.com</a>.</p>
        </body>
    </html>

Example of changing the attribute "target" of every link in first paragraph::

    >>> from xml.etree.ElementTree import ElementTree
    >>> tree = ElementTree()
    >>> tree.parse("index.xhtml")
    <Element 'html' at 0xb77e6fac>
    >>> p = tree.find("body/p")     # Finds first occurrence of tag p in body
    >>> p
    <Element 'p' at 0xb77ec26c>
    >>> links = list(p.iter("a"))   # Returns list of all links
    >>> links
    [<Element 'a' at 0xb77ec2ac>, <Element 'a' at 0xb77ec1cc>]
    >>> for i in links:             # Iterates through all found links
    ...     i.attrib["target"] = "blank"
    ...
    >>> tree.write("output.xhtml")

.. _elementtree-qname-objects:

QName Objects
^^^^^^^^^^^^^


.. class:: QName(text_or_uri, tag=None)

   QName wrapper.  This can be used to wrap a QName attribute value, in order
   to get proper namespace handling on output.  *text_or_uri* is a string
   containing the QName value, in the form {uri}local, or, if the tag argument
   is given, the URI part of a QName.  If *tag* is given, the first argument is
   interpreted as a URI, and this argument is interpreted as a local name.
   :class:`QName` instances are opaque.


.. _elementtree-treebuilder-objects:

TreeBuilder Objects
^^^^^^^^^^^^^^^^^^^


.. class:: TreeBuilder(element_factory=None)

   Generic element structure builder.  This builder converts a sequence of
   start, data, and end method calls to a well-formed element structure.  You
   can use this class to build an element structure using a custom XML parser,
   or a parser for some other XML-like format.  The *element_factory* is called
   to create new :class:`Element` instances when given.


   .. method:: close()

      Flushes the builder buffers, and returns the toplevel document
      element.  Returns an :class:`Element` instance.


   .. method:: data(data)

      Adds text to the current element.  *data* is a string.  This should be
      either a bytestring, or a Unicode string.


   .. method:: end(tag)

      Closes the current element.  *tag* is the element name.  Returns the
      closed element.


   .. method:: start(tag, attrs)

      Opens a new element.  *tag* is the element name.  *attrs* is a dictionary
      containing element attributes.  Returns the opened element.


   In addition, a custom :class:`TreeBuilder` object can provide the
   following method:

   .. method:: doctype(name, pubid, system)

      Handles a doctype declaration.  *name* is the doctype name.  *pubid* is
      the public identifier.  *system* is the system identifier.  This method
      does not exist on the default :class:`TreeBuilder` class.

      .. versionadded:: 2.7


.. _elementtree-xmlparser-objects:

XMLParser Objects
^^^^^^^^^^^^^^^^^


.. class:: XMLParser(html=0, target=None, encoding=None)

   :class:`Element` structure builder for XML source data, based on the expat
   parser.  *html* are predefined HTML entities.  This flag is not supported by
   the current implementation.  *target* is the target object.  If omitted, the
   builder uses an instance of the standard TreeBuilder class.  *encoding* [1]_
   is optional.  If given, the value overrides the encoding specified in the
   XML file.


   .. method:: close()

      Finishes feeding data to the parser.  Returns an element structure.


   .. method:: doctype(name, pubid, system)

      .. deprecated:: 2.7
         Define the :meth:`TreeBuilder.doctype` method on a custom TreeBuilder
         target.


   .. method:: feed(data)

      Feeds data to the parser.  *data* is encoded data.

:meth:`XMLParser.feed` calls *target*\'s :meth:`start` method
for each opening tag, its :meth:`end` method for each closing tag,
and data is processed by method :meth:`data`.  :meth:`XMLParser.close`
calls *target*\'s method :meth:`close`.
:class:`XMLParser` can be used not only for building a tree structure.
This is an example of counting the maximum depth of an XML file::

    >>> from xml.etree.ElementTree import XMLParser
    >>> class MaxDepth:                     # The target object of the parser
    ...     maxDepth = 0
    ...     depth = 0
    ...     def start(self, tag, attrib):   # Called for each opening tag.
    ...         self.depth += 1
    ...         if self.depth > self.maxDepth:
    ...             self.maxDepth = self.depth
    ...     def end(self, tag):             # Called for each closing tag.
    ...         self.depth -= 1
    ...     def data(self, data):
    ...         pass            # We do not need to do anything with data.
    ...     def close(self):    # Called when all data has been parsed.
    ...         return self.maxDepth
    ...
    >>> target = MaxDepth()
    >>> parser = XMLParser(target=target)
    >>> exampleXml = """
    ... <a>
    ...   <b>
    ...   </b>
    ...   <b>
    ...     <c>
    ...       <d>
    ...       </d>
    ...     </c>
    ...   </b>
    ... </a>"""
    >>> parser.feed(exampleXml)
    >>> parser.close()
    4


.. rubric:: Footnotes

.. [1] The encoding string included in XML output should conform to the
   appropriate standards.  For example, "UTF-8" is valid, but "UTF8" is
   not.  See https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl
   and https://www.iana.org/assignments/character-sets/character-sets.xhtml.
PK
%�\~E�x��!html/_sources/library/xml.rst.txtnu�[���.. _xml:

XML Processing Modules
======================

.. module:: xml
   :synopsis: Package containing XML processing modules
.. sectionauthor:: Christian Heimes <christian@python.org>
.. sectionauthor:: Georg Brandl <georg@python.org>


Python's interfaces for processing XML are grouped in the ``xml`` package.

.. warning::

   The XML modules are not secure against erroneous or maliciously
   constructed data.  If you need to parse untrusted or unauthenticated data see
   :ref:`xml-vulnerabilities`.

It is important to note that modules in the :mod:`xml` package require that
there be at least one SAX-compliant XML parser available. The Expat parser is
included with Python, so the :mod:`xml.parsers.expat` module will always be
available.

The documentation for the :mod:`xml.dom` and :mod:`xml.sax` packages are the
definition of the Python bindings for the DOM and SAX interfaces.

The XML handling submodules are:

* :mod:`xml.etree.ElementTree`: the ElementTree API, a simple and lightweight
  XML processor

..

* :mod:`xml.dom`: the DOM API definition
* :mod:`xml.dom.minidom`: a minimal DOM implementation
* :mod:`xml.dom.pulldom`: support for building partial DOM trees

..

* :mod:`xml.sax`: SAX2 base classes and convenience functions
* :mod:`xml.parsers.expat`: the Expat parser binding


.. _xml-vulnerabilities:

XML vulnerabilities
===================

The XML processing modules are not secure against maliciously constructed data.
An attacker can abuse vulnerabilities for e.g. denial of service attacks, to
access local files, to generate network connections to other machines, or
to or circumvent firewalls. The attacks on XML abuse unfamiliar features
like inline `DTD`_ (document type definition) with entities.

The following table gives an overview of the known attacks and if the various
modules are vulnerable to them.

=========================  ==============   ===============   ==============   ==============   ==============
kind                       sax              etree             minidom          pulldom          xmlrpc
=========================  ==============   ===============   ==============   ==============   ==============
billion laughs             **Vulnerable**   **Vulnerable**    **Vulnerable**   **Vulnerable**   **Vulnerable**
quadratic blowup           **Vulnerable**   **Vulnerable**    **Vulnerable**   **Vulnerable**   **Vulnerable**
external entity expansion  **Vulnerable**   Safe    (1)       Safe    (2)      **Vulnerable**   Safe    (3)
`DTD`_ retrieval           **Vulnerable**   Safe              Safe             **Vulnerable**   Safe
decompression bomb         Safe             Safe              Safe             Safe             **Vulnerable**
=========================  ==============   ===============   ==============   ==============   ==============

1. :mod:`xml.etree.ElementTree` doesn't expand external entities and raises a
   ParserError when an entity occurs.
2. :mod:`xml.dom.minidom` doesn't expand external entities and simply returns
   the unexpanded entity verbatim.
3. :mod:`xmlrpclib` doesn't expand external entities and omits them.


billion laughs / exponential entity expansion
  The `Billion Laughs`_ attack -- also known as exponential entity expansion --
  uses multiple levels of nested entities. Each entity refers to another entity
  several times, the final entity definition contains a small string. Eventually
  the small string is expanded to several gigabytes. The exponential expansion
  consumes lots of CPU time, too.

quadratic blowup entity expansion
  A quadratic blowup attack is similar to a `Billion Laughs`_ attack; it abuses
  entity expansion, too. Instead of nested entities it repeats one large entity
  with a couple of thousand chars over and over again. The attack isn't as
  efficient as the exponential case but it avoids triggering countermeasures of
  parsers against heavily nested entities.

external entity expansion
  Entity declarations can contain more than just text for replacement. They can
  also point to external resources by public identifiers or system identifiers.
  System identifiers are standard URIs or can refer to local files. The XML
  parser retrieves the resource with e.g. HTTP or FTP requests and embeds the
  content into the XML document.

`DTD`_ retrieval
  Some XML libraries like Python's :mod:`xml.dom.pulldom` retrieve document type
  definitions from remote or local locations. The feature has similar
  implications as the external entity expansion issue.

decompression bomb
  The issue of decompression bombs (aka `ZIP bomb`_) apply to all XML libraries
  that can parse compressed XML stream like gzipped HTTP streams or LZMA-ed
  files. For an attacker it can reduce the amount of transmitted data by three
  magnitudes or more.

The documentation of `defusedxml`_ on PyPI has further information about
all known attack vectors with examples and references.

defused packages
----------------

These external packages are recommended for any code that parses
untrusted XML data.

`defusedxml`_ is a pure Python package with modified subclasses of all stdlib
XML parsers that prevent any potentially malicious operation. The
package also ships with example exploits and extended documentation on more
XML exploits like xpath injection.

`defusedexpat`_ provides a modified libexpat and patched replacement
:mod:`pyexpat` extension module with countermeasures against entity expansion
DoS attacks. Defusedexpat still allows a sane and configurable amount of entity
expansions. The modifications will be merged into future releases of Python.

The workarounds and modifications are not included in patch releases as they
break backward compatibility. After all inline DTD and entity expansion are
well-defined XML features.


.. _defusedxml: https://pypi.org/project/defusedxml/
.. _defusedexpat: https://pypi.org/project/defusedexpat/
.. _Billion Laughs: https://en.wikipedia.org/wiki/Billion_laughs
.. _ZIP bomb: https://en.wikipedia.org/wiki/Zip_bomb
.. _DTD: https://en.wikipedia.org/wiki/Document_type_definition
PK
%�\Xm�o<<-html/_sources/library/xml.sax.handler.rst.txtnu�[���
:mod:`xml.sax.handler` --- Base classes for SAX handlers
========================================================

.. module:: xml.sax.handler
   :synopsis: Base classes for SAX event handlers.
.. moduleauthor:: Lars Marius Garshol <larsga@garshol.priv.no>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

The SAX API defines four kinds of handlers: content handlers, DTD handlers,
error handlers, and entity resolvers. Applications normally only need to
implement those interfaces whose events they are interested in; they can
implement the interfaces in a single object or in multiple objects. Handler
implementations should inherit from the base classes provided in the module
:mod:`xml.sax.handler`, so that all methods get default implementations.


.. class:: ContentHandler

   This is the main callback interface in SAX, and the one most important to
   applications. The order of events in this interface mirrors the order of the
   information in the document.


.. class:: DTDHandler

   Handle DTD events.

   This interface specifies only those DTD events required for basic parsing
   (unparsed entities and attributes).


.. class:: EntityResolver

   Basic interface for resolving entities. If you create an object implementing
   this interface, then register the object with your Parser, the parser will call
   the method in your object to resolve all external entities.


.. class:: ErrorHandler

   Interface used by the parser to present error and warning messages to the
   application.  The methods of this object control whether errors are immediately
   converted to exceptions or are handled in some other way.

In addition to these classes, :mod:`xml.sax.handler` provides symbolic constants
for the feature and property names.


.. data:: feature_namespaces

   | value: ``"http://xml.org/sax/features/namespaces"``
   | true: Perform Namespace processing.
   | false: Optionally do not perform Namespace processing (implies
     namespace-prefixes; default).
   | access: (parsing) read-only; (not parsing) read/write


.. data:: feature_namespace_prefixes

   | value: ``"http://xml.org/sax/features/namespace-prefixes"``
   | true: Report the original prefixed names and attributes used for Namespace
     declarations.
   | false: Do not report attributes used for Namespace declarations, and
     optionally do not report original prefixed names (default).
   | access: (parsing) read-only; (not parsing) read/write


.. data:: feature_string_interning

   | value: ``"http://xml.org/sax/features/string-interning"``
   | true: All element names, prefixes, attribute names, Namespace URIs, and
     local names are interned using the built-in intern function.
   | false: Names are not necessarily interned, although they may be (default).
   | access: (parsing) read-only; (not parsing) read/write


.. data:: feature_validation

   | value: ``"http://xml.org/sax/features/validation"``
   | true: Report all validation errors (implies external-general-entities and
     external-parameter-entities).
   | false: Do not report validation errors.
   | access: (parsing) read-only; (not parsing) read/write


.. data:: feature_external_ges

   | value: ``"http://xml.org/sax/features/external-general-entities"``
   | true: Include all external general (text) entities.
   | false: Do not include external general entities.
   | access: (parsing) read-only; (not parsing) read/write


.. data:: feature_external_pes

   | value: ``"http://xml.org/sax/features/external-parameter-entities"``
   | true: Include all external parameter entities, including the external DTD
     subset.
   | false: Do not include any external parameter entities, even the external
     DTD subset.
   | access: (parsing) read-only; (not parsing) read/write


.. data:: all_features

   List of all features.


.. data:: property_lexical_handler

   | value: ``"http://xml.org/sax/properties/lexical-handler"``
   | data type: xml.sax.sax2lib.LexicalHandler (not supported in Python 2)
   | description: An optional extension handler for lexical events like
     comments.
   | access: read/write


.. data:: property_declaration_handler

   | value: ``"http://xml.org/sax/properties/declaration-handler"``
   | data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2)
   | description: An optional extension handler for DTD-related events other
     than notations and unparsed entities.
   | access: read/write


.. data:: property_dom_node

   | value: ``"http://xml.org/sax/properties/dom-node"``
   | data type: org.w3c.dom.Node (not supported in Python 2)
   | description: When parsing, the current DOM node being visited if this is
     a DOM iterator; when not parsing, the root DOM node for iteration.
   | access: (parsing) read-only; (not parsing) read/write


.. data:: property_xml_string

   | value: ``"http://xml.org/sax/properties/xml-string"``
   | data type: String
   | description: The literal string of characters that was the source for the
     current event.
   | access: read-only


.. data:: all_properties

   List of all known property names.


.. _content-handler-objects:

ContentHandler Objects
----------------------

Users are expected to subclass :class:`ContentHandler` to support their
application.  The following methods are called by the parser on the appropriate
events in the input document:


.. method:: ContentHandler.setDocumentLocator(locator)

   Called by the parser to give the application a locator for locating the origin
   of document events.

   SAX parsers are strongly encouraged (though not absolutely required) to supply a
   locator: if it does so, it must supply the locator to the application by
   invoking this method before invoking any of the other methods in the
   DocumentHandler interface.

   The locator allows the application to determine the end position of any
   document-related event, even if the parser is not reporting an error. Typically,
   the application will use this information for reporting its own errors (such as
   character content that does not match an application's business rules). The
   information returned by the locator is probably not sufficient for use with a
   search engine.

   Note that the locator will return correct information only during the invocation
   of the events in this interface. The application should not attempt to use it at
   any other time.


.. method:: ContentHandler.startDocument()

   Receive notification of the beginning of a document.

   The SAX parser will invoke this method only once, before any other methods in
   this interface or in DTDHandler (except for :meth:`setDocumentLocator`).


.. method:: ContentHandler.endDocument()

   Receive notification of the end of a document.

   The SAX parser will invoke this method only once, and it will be the last method
   invoked during the parse. The parser shall not invoke this method until it has
   either abandoned parsing (because of an unrecoverable error) or reached the end
   of input.


.. method:: ContentHandler.startPrefixMapping(prefix, uri)

   Begin the scope of a prefix-URI Namespace mapping.

   The information from this event is not necessary for normal Namespace
   processing: the SAX XML reader will automatically replace prefixes for element
   and attribute names when the ``feature_namespaces`` feature is enabled (the
   default).

   There are cases, however, when applications need to use prefixes in character
   data or in attribute values, where they cannot safely be expanded automatically;
   the :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events supply the
   information to the application to expand prefixes in those contexts itself, if
   necessary.

   .. XXX This is not really the default, is it? MvL

   Note that :meth:`startPrefixMapping` and :meth:`endPrefixMapping` events are not
   guaranteed to be properly nested relative to each-other: all
   :meth:`startPrefixMapping` events will occur before the corresponding
   :meth:`startElement` event, and all :meth:`endPrefixMapping` events will occur
   after the corresponding :meth:`endElement` event, but their order is not
   guaranteed.


.. method:: ContentHandler.endPrefixMapping(prefix)

   End the scope of a prefix-URI mapping.

   See :meth:`startPrefixMapping` for details. This event will always occur after
   the corresponding :meth:`endElement` event, but the order of
   :meth:`endPrefixMapping` events is not otherwise guaranteed.


.. method:: ContentHandler.startElement(name, attrs)

   Signals the start of an element in non-namespace mode.

   The *name* parameter contains the raw XML 1.0 name of the element type as a
   string and the *attrs* parameter holds an object of the
   :class:`~xml.sax.xmlreader.Attributes`
   interface (see :ref:`attributes-objects`) containing the attributes of
   the element.  The object passed as *attrs* may be re-used by the parser; holding
   on to a reference to it is not a reliable way to keep a copy of the attributes.
   To keep a copy of the attributes, use the :meth:`copy` method of the *attrs*
   object.


.. method:: ContentHandler.endElement(name)

   Signals the end of an element in non-namespace mode.

   The *name* parameter contains the name of the element type, just as with the
   :meth:`startElement` event.


.. method:: ContentHandler.startElementNS(name, qname, attrs)

   Signals the start of an element in namespace mode.

   The *name* parameter contains the name of the element type as a ``(uri,
   localname)`` tuple, the *qname* parameter contains the raw XML 1.0 name used in
   the source document, and the *attrs* parameter holds an instance of the
   :class:`~xml.sax.xmlreader.AttributesNS` interface (see
   :ref:`attributes-ns-objects`)
   containing the attributes of the element.  If no namespace is associated with
   the element, the *uri* component of *name* will be ``None``.  The object passed
   as *attrs* may be re-used by the parser; holding on to a reference to it is not
   a reliable way to keep a copy of the attributes.  To keep a copy of the
   attributes, use the :meth:`copy` method of the *attrs* object.

   Parsers may set the *qname* parameter to ``None``, unless the
   ``feature_namespace_prefixes`` feature is activated.


.. method:: ContentHandler.endElementNS(name, qname)

   Signals the end of an element in namespace mode.

   The *name* parameter contains the name of the element type, just as with the
   :meth:`startElementNS` method, likewise the *qname* parameter.


.. method:: ContentHandler.characters(content)

   Receive notification of character data.

   The Parser will call this method to report each chunk of character data. SAX
   parsers may return all contiguous character data in a single chunk, or they may
   split it into several chunks; however, all of the characters in any single event
   must come from the same external entity so that the Locator provides useful
   information.

   *content* may be a Unicode string or a byte string; the ``expat`` reader module
   produces always Unicode strings.

   .. note::

      The earlier SAX 1 interface provided by the Python XML Special Interest Group
      used a more Java-like interface for this method.  Since most parsers used from
      Python did not take advantage of the older interface, the simpler signature was
      chosen to replace it.  To convert old code to the new interface, use *content*
      instead of slicing content with the old *offset* and *length* parameters.


.. method:: ContentHandler.ignorableWhitespace(whitespace)

   Receive notification of ignorable whitespace in element content.

   Validating Parsers must use this method to report each chunk of ignorable
   whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating
   parsers may also use this method if they are capable of parsing and using
   content models.

   SAX parsers may return all contiguous whitespace in a single chunk, or they may
   split it into several chunks; however, all of the characters in any single event
   must come from the same external entity, so that the Locator provides useful
   information.


.. method:: ContentHandler.processingInstruction(target, data)

   Receive notification of a processing instruction.

   The Parser will invoke this method once for each processing instruction found:
   note that processing instructions may occur before or after the main document
   element.

   A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a
   text declaration (XML 1.0, section 4.3.1) using this method.


.. method:: ContentHandler.skippedEntity(name)

   Receive notification of a skipped entity.

   The Parser will invoke this method once for each entity skipped. Non-validating
   processors may skip entities if they have not seen the declarations (because,
   for example, the entity was declared in an external DTD subset). All processors
   may skip external entities, depending on the values of the
   ``feature_external_ges`` and the ``feature_external_pes`` properties.


.. _dtd-handler-objects:

DTDHandler Objects
------------------

:class:`DTDHandler` instances provide the following methods:


.. method:: DTDHandler.notationDecl(name, publicId, systemId)

   Handle a notation declaration event.


.. method:: DTDHandler.unparsedEntityDecl(name, publicId, systemId, ndata)

   Handle an unparsed entity declaration event.


.. _entity-resolver-objects:

EntityResolver Objects
----------------------


.. method:: EntityResolver.resolveEntity(publicId, systemId)

   Resolve the system identifier of an entity and return either the system
   identifier to read from as a string, or an InputSource to read from. The default
   implementation returns *systemId*.


.. _sax-error-handler:

ErrorHandler Objects
--------------------

Objects with this interface are used to receive error and warning information
from the :class:`~xml.sax.xmlreader.XMLReader`.  If you create an object that
implements this interface, then register the object with your
:class:`~xml.sax.xmlreader.XMLReader`, the parser
will call the methods in your object to report all warnings and errors. There
are three levels of errors available: warnings, (possibly) recoverable errors,
and unrecoverable errors.  All methods take a :exc:`SAXParseException` as the
only parameter.  Errors and warnings may be converted to an exception by raising
the passed-in exception object.


.. method:: ErrorHandler.error(exception)

   Called when the parser encounters a recoverable error.  If this method does not
   raise an exception, parsing may continue, but further document information
   should not be expected by the application.  Allowing the parser to continue may
   allow additional errors to be discovered in the input document.


.. method:: ErrorHandler.fatalError(exception)

   Called when the parser encounters an error it cannot recover from; parsing is
   expected to terminate when this method returns.


.. method:: ErrorHandler.warning(exception)

   Called when the parser presents minor warning information to the application.
   Parsing is expected to continue when this method returns, and document
   information will continue to be passed to the application. Raising an exception
   in this method will cause parsing to end.

PK
%�\�I��/�/,html/_sources/library/xml.sax.reader.rst.txtnu�[���
:mod:`xml.sax.xmlreader` --- Interface for XML parsers
======================================================

.. module:: xml.sax.xmlreader
   :synopsis: Interface which SAX-compliant XML parsers must implement.
.. moduleauthor:: Lars Marius Garshol <larsga@garshol.priv.no>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

SAX parsers implement the :class:`XMLReader` interface. They are implemented in
a Python module, which must provide a function :func:`create_parser`. This
function is invoked by  :func:`xml.sax.make_parser` with no arguments to create
a new  parser object.


.. class:: XMLReader()

   Base class which can be inherited by SAX parsers.


.. class:: IncrementalParser()

   In some cases, it is desirable not to parse an input source at once, but to feed
   chunks of the document as they get available. Note that the reader will normally
   not read the entire file, but read it in chunks as well; still :meth:`parse`
   won't return until the entire document is processed. So these interfaces should
   be used if the blocking behaviour of :meth:`parse` is not desirable.

   When the parser is instantiated it is ready to begin accepting data from the
   feed method immediately. After parsing has been finished with a call to close
   the reset method must be called to make the parser ready to accept new data,
   either from feed or using the parse method.

   Note that these methods must *not* be called during parsing, that is, after
   parse has been called and before it returns.

   By default, the class also implements the parse method of the XMLReader
   interface using the feed, close and reset methods of the IncrementalParser
   interface as a convenience to SAX 2.0 driver writers.


.. class:: Locator()

   Interface for associating a SAX event with a document location. A locator object
   will return valid results only during calls to DocumentHandler methods; at any
   other time, the results are unpredictable. If information is not available,
   methods may return ``None``.


.. class:: InputSource([systemId])

   Encapsulation of the information needed by the :class:`XMLReader` to read
   entities.

   This class may include information about the public identifier, system
   identifier, byte stream (possibly with character encoding information) and/or
   the character stream of an entity.

   Applications will create objects of this class for use in the
   :meth:`XMLReader.parse` method and for returning from
   EntityResolver.resolveEntity.

   An :class:`InputSource` belongs to the application, the :class:`XMLReader` is
   not allowed to modify :class:`InputSource` objects passed to it from the
   application, although it may make copies and modify those.


.. class:: AttributesImpl(attrs)

   This is an implementation of the :class:`Attributes` interface (see section
   :ref:`attributes-objects`).  This is a dictionary-like object which
   represents the element attributes in a :meth:`startElement` call. In addition
   to the most useful dictionary operations, it supports a number of other
   methods as described by the interface. Objects of this class should be
   instantiated by readers; *attrs* must be a dictionary-like object containing
   a mapping from attribute names to attribute values.


.. class:: AttributesNSImpl(attrs, qnames)

   Namespace-aware variant of :class:`AttributesImpl`, which will be passed to
   :meth:`startElementNS`. It is derived from :class:`AttributesImpl`, but
   understands attribute names as two-tuples of *namespaceURI* and
   *localname*. In addition, it provides a number of methods expecting qualified
   names as they appear in the original document.  This class implements the
   :class:`AttributesNS` interface (see section :ref:`attributes-ns-objects`).


.. _xmlreader-objects:

XMLReader Objects
-----------------

The :class:`XMLReader` interface supports the following methods:


.. method:: XMLReader.parse(source)

   Process an input source, producing SAX events. The *source* object can be a
   system identifier (a string identifying the input source -- typically a file
   name or a URL), a file-like object, or an :class:`InputSource` object. When
   :meth:`parse` returns, the input is completely processed, and the parser object
   can be discarded or reset. As a limitation, the current implementation only
   accepts byte streams; processing of character streams is for further study.


.. method:: XMLReader.getContentHandler()

   Return the current :class:`~xml.sax.handler.ContentHandler`.


.. method:: XMLReader.setContentHandler(handler)

   Set the current :class:`~xml.sax.handler.ContentHandler`.  If no
   :class:`~xml.sax.handler.ContentHandler` is set, content events will be
   discarded.


.. method:: XMLReader.getDTDHandler()

   Return the current :class:`~xml.sax.handler.DTDHandler`.


.. method:: XMLReader.setDTDHandler(handler)

   Set the current :class:`~xml.sax.handler.DTDHandler`.  If no
   :class:`~xml.sax.handler.DTDHandler` is set, DTD
   events will be discarded.


.. method:: XMLReader.getEntityResolver()

   Return the current :class:`~xml.sax.handler.EntityResolver`.


.. method:: XMLReader.setEntityResolver(handler)

   Set the current :class:`~xml.sax.handler.EntityResolver`.  If no
   :class:`~xml.sax.handler.EntityResolver` is set,
   attempts to resolve an external entity will result in opening the system
   identifier for the entity, and fail if it is not available.


.. method:: XMLReader.getErrorHandler()

   Return the current :class:`~xml.sax.handler.ErrorHandler`.


.. method:: XMLReader.setErrorHandler(handler)

   Set the current error handler.  If no :class:`~xml.sax.handler.ErrorHandler`
   is set, errors will be raised as exceptions, and warnings will be printed.


.. method:: XMLReader.setLocale(locale)

   Allow an application to set the locale for errors and warnings.

   SAX parsers are not required to provide localization for errors and warnings; if
   they cannot support the requested locale, however, they must raise a SAX
   exception.  Applications may request a locale change in the middle of a parse.


.. method:: XMLReader.getFeature(featurename)

   Return the current setting for feature *featurename*.  If the feature is not
   recognized, :exc:`SAXNotRecognizedException` is raised. The well-known
   featurenames are listed in the module :mod:`xml.sax.handler`.


.. method:: XMLReader.setFeature(featurename, value)

   Set the *featurename* to *value*. If the feature is not recognized,
   :exc:`SAXNotRecognizedException` is raised. If the feature or its setting is not
   supported by the parser, *SAXNotSupportedException* is raised.


.. method:: XMLReader.getProperty(propertyname)

   Return the current setting for property *propertyname*. If the property is not
   recognized, a :exc:`SAXNotRecognizedException` is raised. The well-known
   propertynames are listed in the module :mod:`xml.sax.handler`.


.. method:: XMLReader.setProperty(propertyname, value)

   Set the *propertyname* to *value*. If the property is not recognized,
   :exc:`SAXNotRecognizedException` is raised. If the property or its setting is
   not supported by the parser, *SAXNotSupportedException* is raised.


.. _incremental-parser-objects:

IncrementalParser Objects
-------------------------

Instances of :class:`IncrementalParser` offer the following additional methods:


.. method:: IncrementalParser.feed(data)

   Process a chunk of *data*.


.. method:: IncrementalParser.close()

   Assume the end of the document. That will check well-formedness conditions that
   can be checked only at the end, invoke handlers, and may clean up resources
   allocated during parsing.


.. method:: IncrementalParser.reset()

   This method is called after close has been called to reset the parser so that it
   is ready to parse new documents. The results of calling parse or feed after
   close without calling reset are undefined.


.. _locator-objects:

Locator Objects
---------------

Instances of :class:`Locator` provide these methods:


.. method:: Locator.getColumnNumber()

   Return the column number where the current event begins.


.. method:: Locator.getLineNumber()

   Return the line number where the current event begins.


.. method:: Locator.getPublicId()

   Return the public identifier for the current event.


.. method:: Locator.getSystemId()

   Return the system identifier for the current event.


.. _input-source-objects:

InputSource Objects
-------------------


.. method:: InputSource.setPublicId(id)

   Sets the public identifier of this :class:`InputSource`.


.. method:: InputSource.getPublicId()

   Returns the public identifier of this :class:`InputSource`.


.. method:: InputSource.setSystemId(id)

   Sets the system identifier of this :class:`InputSource`.


.. method:: InputSource.getSystemId()

   Returns the system identifier of this :class:`InputSource`.


.. method:: InputSource.setEncoding(encoding)

   Sets the character encoding of this :class:`InputSource`.

   The encoding must be a string acceptable for an XML encoding declaration (see
   section 4.3.3 of the XML recommendation).

   The encoding attribute of the :class:`InputSource` is ignored if the
   :class:`InputSource` also contains a character stream.


.. method:: InputSource.getEncoding()

   Get the character encoding of this InputSource.


.. method:: InputSource.setByteStream(bytefile)

   Set the byte stream (a Python file-like object which does not perform
   byte-to-character conversion) for this input source.

   The SAX parser will ignore this if there is also a character stream specified,
   but it will use a byte stream in preference to opening a URI connection itself.

   If the application knows the character encoding of the byte stream, it should
   set it with the setEncoding method.


.. method:: InputSource.getByteStream()

   Get the byte stream for this input source.

   The getEncoding method will return the character encoding for this byte stream,
   or ``None`` if unknown.


.. method:: InputSource.setCharacterStream(charfile)

   Set the character stream for this input source. (The stream must be a Python 1.6
   Unicode-wrapped file-like that performs conversion to Unicode strings.)

   If there is a character stream specified, the SAX parser will ignore any byte
   stream and will not attempt to open a URI connection to the system identifier.


.. method:: InputSource.getCharacterStream()

   Get the character stream for this input source.


.. _attributes-objects:

The :class:`Attributes` Interface
---------------------------------

:class:`Attributes` objects implement a portion of the mapping protocol,
including the methods :meth:`~collections.Mapping.copy`,
:meth:`~collections.Mapping.get`,
:meth:`~collections.Mapping.has_key`,
:meth:`~collections.Mapping.items`,
:meth:`~collections.Mapping.keys`,
and :meth:`~collections.Mapping.values`.  The following methods
are also provided:


.. method:: Attributes.getLength()

   Return the number of attributes.


.. method:: Attributes.getNames()

   Return the names of the attributes.


.. method:: Attributes.getType(name)

   Returns the type of the attribute *name*, which is normally ``'CDATA'``.


.. method:: Attributes.getValue(name)

   Return the value of attribute *name*.

.. getValueByQName, getNameByQName, getQNameByName, getQNames available
.. here already, but documented only for derived class.


.. _attributes-ns-objects:

The :class:`AttributesNS` Interface
-----------------------------------

This interface is a subtype of the :class:`Attributes` interface (see section
:ref:`attributes-objects`).  All methods supported by that interface are also
available on :class:`AttributesNS` objects.

The following methods are also available:


.. method:: AttributesNS.getValueByQName(name)

   Return the value for a qualified name.


.. method:: AttributesNS.getNameByQName(name)

   Return the ``(namespace, localname)`` pair for a qualified *name*.


.. method:: AttributesNS.getQNameByName(name)

   Return the qualified name for a ``(namespace, localname)`` pair.


.. method:: AttributesNS.getQNames()

   Return the qualified names of all attributes.

PK
%�\��p<<%html/_sources/library/xml.sax.rst.txtnu�[���
:mod:`xml.sax` --- Support for SAX2 parsers
===========================================

.. module:: xml.sax
   :synopsis: Package containing SAX2 base classes and convenience functions.
.. moduleauthor:: Lars Marius Garshol <larsga@garshol.priv.no>
.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

The :mod:`xml.sax` package provides a number of modules which implement the
Simple API for XML (SAX) interface for Python.  The package itself provides the
SAX exceptions and the convenience functions which will be most used by users of
the SAX API.


.. warning::

   The :mod:`xml.sax` module is not secure against maliciously
   constructed data.  If you need to parse untrusted or unauthenticated data see
   :ref:`xml-vulnerabilities`.


The convenience functions are:


.. function:: make_parser([parser_list])

   Create and return a SAX :class:`~xml.sax.xmlreader.XMLReader` object.  The
   first parser found will
   be used.  If *parser_list* is provided, it must be a list of strings which
   name modules that have a function named :func:`create_parser`.  Modules listed
   in *parser_list* will be used before modules in the default list of parsers.


.. function:: parse(filename_or_stream, handler[, error_handler])

   Create a SAX parser and use it to parse a document.  The document, passed in as
   *filename_or_stream*, can be a filename or a file object.  The *handler*
   parameter needs to be a SAX :class:`~handler.ContentHandler` instance.  If
   *error_handler* is given, it must be a SAX :class:`~handler.ErrorHandler`
   instance; if
   omitted,  :exc:`SAXParseException` will be raised on all errors.  There is no
   return value; all work must be done by the *handler* passed in.


.. function:: parseString(string, handler[, error_handler])

   Similar to :func:`parse`, but parses from a buffer *string* received as a
   parameter.

A typical SAX application uses three kinds of objects: readers, handlers and
input sources.  "Reader" in this context is another term for parser, i.e. some
piece of code that reads the bytes or characters from the input source, and
produces a sequence of events. The events then get distributed to the handler
objects, i.e. the reader invokes a method on the handler.  A SAX application
must therefore obtain a reader object, create or open the input sources, create
the handlers, and connect these objects all together.  As the final step of
preparation, the reader is called to parse the input. During parsing, methods on
the handler objects are called based on structural and syntactic events from the
input data.

For these objects, only the interfaces are relevant; they are normally not
instantiated by the application itself.  Since Python does not have an explicit
notion of interface, they are formally introduced as classes, but applications
may use implementations which do not inherit from the provided classes.  The
:class:`~xml.sax.xmlreader.InputSource`, :class:`~xml.sax.xmlreader.Locator`,
:class:`~xml.sax.xmlreader.Attributes`, :class:`~xml.sax.xmlreader.AttributesNS`,
and :class:`~xml.sax.xmlreader.XMLReader` interfaces are defined in the
module :mod:`xml.sax.xmlreader`.  The handler interfaces are defined in
:mod:`xml.sax.handler`.  For convenience,
:class:`~xml.sax.xmlreader.InputSource` (which is often
instantiated directly) and the handler classes are also available from
:mod:`xml.sax`.  These interfaces are described below.

In addition to these classes, :mod:`xml.sax` provides the following exception
classes.


.. exception:: SAXException(msg[, exception])

   Encapsulate an XML error or warning.  This class can contain basic error or
   warning information from either the XML parser or the application: it can be
   subclassed to provide additional functionality or to add localization.  Note
   that although the handlers defined in the
   :class:`~xml.sax.handler.ErrorHandler` interface
   receive instances of this exception, it is not required to actually raise the
   exception --- it is also useful as a container for information.

   When instantiated, *msg* should be a human-readable description of the error.
   The optional *exception* parameter, if given, should be ``None`` or an exception
   that was caught by the parsing code and is being passed along as information.

   This is the base class for the other SAX exception classes.


.. exception:: SAXParseException(msg, exception, locator)

   Subclass of :exc:`SAXException` raised on parse errors. Instances of this
   class are passed to the methods of the SAX
   :class:`~xml.sax.handler.ErrorHandler` interface to provide information
   about the parse error.  This class supports the SAX
   :class:`~xml.sax.xmlreader.Locator` interface as well as the
   :class:`SAXException` interface.


.. exception:: SAXNotRecognizedException(msg[, exception])

   Subclass of :exc:`SAXException` raised when a SAX
   :class:`~xml.sax.xmlreader.XMLReader` is
   confronted with an unrecognized feature or property.  SAX applications and
   extensions may use this class for similar purposes.


.. exception:: SAXNotSupportedException(msg[, exception])

   Subclass of :exc:`SAXException` raised when a SAX
   :class:`~xml.sax.xmlreader.XMLReader` is asked to
   enable a feature that is not supported, or to set a property to a value that the
   implementation does not support.  SAX applications and extensions may use this
   class for similar purposes.


.. seealso::

   `SAX: The Simple API for XML <http://www.saxproject.org/>`_
      This site is the focal point for the definition of the SAX API.  It provides a
      Java implementation and online documentation.  Links to implementations and
      historical information are also available.

   Module :mod:`xml.sax.handler`
      Definitions of the interfaces for application-provided objects.

   Module :mod:`xml.sax.saxutils`
      Convenience functions for use in SAX applications.

   Module :mod:`xml.sax.xmlreader`
      Definitions of the interfaces for parser-provided objects.


.. _sax-exception-objects:

SAXException Objects
--------------------

The :class:`SAXException` exception class supports the following methods:


.. method:: SAXException.getMessage()

   Return a human-readable message describing the error condition.


.. method:: SAXException.getException()

   Return an encapsulated exception object, or ``None``.

PK
%�\M����
�
+html/_sources/library/xml.sax.utils.rst.txtnu�[���
:mod:`xml.sax.saxutils` --- SAX Utilities
=========================================

.. module:: xml.sax.saxutils
   :synopsis: Convenience functions and classes for use with SAX.
.. moduleauthor:: Lars Marius Garshol <larsga@garshol.priv.no>
.. sectionauthor:: Martin v. Löwis <martin@v.loewis.de>


.. versionadded:: 2.0

The module :mod:`xml.sax.saxutils` contains a number of classes and functions
that are commonly useful when creating SAX applications, either in direct use,
or as base classes.


.. function:: escape(data[, entities])

   Escape ``'&'``, ``'<'``, and ``'>'`` in a string of data.

   You can escape other strings of data by passing a dictionary as the optional
   *entities* parameter.  The keys and values must all be strings; each key will be
   replaced with its corresponding value.  The characters ``'&'``, ``'<'`` and
   ``'>'`` are always escaped, even if *entities* is provided.


.. function:: unescape(data[, entities])

   Unescape ``'&amp;'``, ``'&lt;'``, and ``'&gt;'`` in a string of data.

   You can unescape other strings of data by passing a dictionary as the optional
   *entities* parameter.  The keys and values must all be strings; each key will be
   replaced with its corresponding value.  ``'&amp'``, ``'&lt;'``, and ``'&gt;'``
   are always unescaped, even if *entities* is provided.

   .. versionadded:: 2.3


.. function:: quoteattr(data[, entities])

   Similar to :func:`escape`, but also prepares *data* to be used as an
   attribute value.  The return value is a quoted version of *data* with any
   additional required replacements. :func:`quoteattr` will select a quote
   character based on the content of *data*, attempting to avoid encoding any
   quote characters in the string.  If both single- and double-quote characters
   are already in *data*, the double-quote characters will be encoded and *data*
   will be wrapped in double-quotes.  The resulting string can be used directly
   as an attribute value::

      >>> print "<element attr=%s>" % quoteattr("ab ' cd \" ef")
      <element attr="ab ' cd &quot; ef">

   This function is useful when generating attribute values for HTML or any SGML
   using the reference concrete syntax.

   .. versionadded:: 2.2


.. class:: XMLGenerator([out[, encoding]])

   This class implements the :class:`~xml.sax.handler.ContentHandler` interface
   by writing SAX
   events back into an XML document. In other words, using an :class:`XMLGenerator`
   as the content handler will reproduce the original document being parsed. *out*
   should be a file-like object which will default to *sys.stdout*. *encoding* is
   the encoding of the output stream which defaults to ``'iso-8859-1'``.


.. class:: XMLFilterBase(base)

   This class is designed to sit between an
   :class:`~xml.sax.xmlreader.XMLReader` and the client
   application's event handlers.  By default, it does nothing but pass requests up
   to the reader and events on to the handlers unmodified, but subclasses can
   override specific methods to modify the event stream or the configuration
   requests as they pass through.


.. function:: prepare_input_source(source[, base])

   This function takes an input source and an optional base URL and returns a
   fully resolved :class:`~xml.sax.xmlreader.InputSource` object ready for
   reading.  The input source can be given as a string, a file-like object, or
   an :class:`~xml.sax.xmlreader.InputSource` object; parsers will use this
   function to implement the polymorphic *source* argument to their
   :meth:`parse` method.

PK
%�\�w�%XX'html/_sources/library/xmlrpclib.rst.txtnu�[���:mod:`xmlrpclib` --- XML-RPC client access
==========================================

.. module:: xmlrpclib
   :synopsis: XML-RPC client access.
.. moduleauthor:: Fredrik Lundh <fredrik@pythonware.com>
.. sectionauthor:: Eric S. Raymond <esr@snark.thyrsus.com>

.. note::
   The :mod:`xmlrpclib` module has been renamed to :mod:`xmlrpc.client` in
   Python 3.  The :term:`2to3` tool will automatically adapt imports when
   converting your sources to Python 3.


.. XXX Not everything is documented yet.  It might be good to describe
   Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.

.. versionadded:: 2.2

**Source code:** :source:`Lib/xmlrpclib.py`

--------------

XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a
transport.  With it, a client can call methods with parameters on a remote
server (the server is named by a URI) and get back structured data.  This module
supports writing XML-RPC client code; it handles all the details of translating
between conformable Python objects and XML on the wire.


.. warning::

   The :mod:`xmlrpclib` module is not secure against maliciously
   constructed data.  If you need to parse untrusted or unauthenticated data see
   :ref:`xml-vulnerabilities`.

.. versionchanged:: 2.7.9

   For HTTPS URIs, :mod:`xmlrpclib` now performs all the necessary certificate
   and hostname checks by default.

.. class:: ServerProxy(uri[, transport[, encoding[, verbose[, allow_none[, use_datetime[, context]]]]]])

   A :class:`ServerProxy` instance is an object that manages communication with a
   remote XML-RPC server.  The required first argument is a URI (Uniform Resource
   Indicator), and will normally be the URL of the server.  The optional second
   argument is a transport factory instance; by default it is an internal
   :class:`SafeTransport` instance for https: URLs and an internal HTTP
   :class:`Transport` instance otherwise.  The optional third argument is an
   encoding, by default UTF-8. The optional fourth argument is a debugging flag.

   The following parameters govern the use of the returned proxy instance.
   If *allow_none* is true,  the Python constant ``None`` will be translated into
   XML; the default behaviour is for ``None`` to raise a :exc:`TypeError`. This is
   a commonly-used extension to the XML-RPC specification, but isn't supported by
   all clients and servers; see `http://ontosys.com/xml-rpc/extensions.php
   <https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php>`_
   for a description.
   The *use_datetime* flag can be used to cause date/time values to
   be presented as :class:`datetime.datetime` objects; this is false by default.
   :class:`datetime.datetime` objects may be passed to calls.

   Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
   Basic Authentication: ``http://user:pass@host:port/path``.  The ``user:pass``
   portion will be base64-encoded as an HTTP 'Authorization' header, and sent to
   the remote server as part of the connection process when invoking an XML-RPC
   method.  You only need to use this if the remote server requires a Basic
   Authentication user and password. If an HTTPS URL is provided, *context* may
   be :class:`ssl.SSLContext` and configures the SSL settings of the underlying
   HTTPS connection.

   The returned instance is a proxy object with methods that can be used to invoke
   corresponding RPC calls on the remote server.  If the remote server supports the
   introspection API, the proxy can also be used to query the remote server for the
   methods it supports (service discovery) and fetch other server-associated
   metadata.

   Types that are conformable (e.g. that can be marshalled through XML),
   include the following (and except where noted, they are unmarshalled
   as the same Python type):

   .. tabularcolumns:: |l|L|

   +----------------------+-------------------------------------------------------+
   | XML-RPC type         | Python type                                           |
   +======================+=======================================================+
   | ``boolean``          | :class:`bool`                                         |
   +----------------------+-------------------------------------------------------+
   | ``int`` or ``i4``    | :class:`int` or :class:`long` in range from           |
   |                      | -2147483648 to 2147483647.                            |
   +----------------------+-------------------------------------------------------+
   | ``double``           | :class:`float`                                        |
   +----------------------+-------------------------------------------------------+
   | ``string``           | :class:`str` or :class:`unicode`                      |
   +----------------------+-------------------------------------------------------+
   | ``array``            | :class:`list` or :class:`tuple` containing            |
   |                      | conformable elements.  Arrays are returned as         |
   |                      | :class:`lists <list>`.                                |
   +----------------------+-------------------------------------------------------+
   | ``struct``           | :class:`dict`.  Keys must be strings, values may be   |
   |                      | any conformable type.  Objects of user-defined        |
   |                      | classes can be passed in; only their                  |
   |                      | :attr:`~object.__dict__` attribute is transmitted.    |
   +----------------------+-------------------------------------------------------+
   | ``dateTime.iso8601`` | :class:`DateTime` or :class:`datetime.datetime`.      |
   |                      | Returned type depends on values of the *use_datetime* |
   |                      | flags.                                                |
   +----------------------+-------------------------------------------------------+
   | ``base64``           | :class:`Binary`                                       |
   +----------------------+-------------------------------------------------------+
   | ``nil``              | The ``None`` constant.  Passing is allowed only if    |
   |                      | *allow_none* is true.                                 |
   +----------------------+-------------------------------------------------------+

   This is the full set of data types supported by XML-RPC.  Method calls may also
   raise a special :exc:`Fault` instance, used to signal XML-RPC server errors, or
   :exc:`ProtocolError` used to signal an error in the HTTP/HTTPS transport layer.
   Both :exc:`Fault` and :exc:`ProtocolError` derive from a base class called
   :exc:`Error`.  Note that even though starting with Python 2.2 you can subclass
   built-in types, the xmlrpclib module currently does not marshal instances of such
   subclasses.

   When passing strings, characters special to XML such as ``<``, ``>``, and ``&``
   will be automatically escaped.  However, it's the caller's responsibility to
   ensure that the string is free of characters that aren't allowed in XML, such as
   the control characters with ASCII values between 0 and 31 (except, of course,
   tab, newline and carriage return); failing to do this will result in an XML-RPC
   request that isn't well-formed XML.  If you have to pass arbitrary strings via
   XML-RPC, use the :class:`Binary` wrapper class described below.

   :class:`Server` is retained as an alias for :class:`ServerProxy` for backwards
   compatibility.  New code should use :class:`ServerProxy`.

   .. versionchanged:: 2.5
      The *use_datetime* flag was added.

   .. versionchanged:: 2.6
      Instances of :term:`new-style class`\es can be passed in if they have an
      *__dict__* attribute and don't have a base class that is marshalled in a
      special way.

   .. versionchanged:: 2.7.9
      Added the *context* argument.


.. seealso::

   `XML-RPC HOWTO <http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html>`_
      A good description of XML-RPC operation and client software in several languages.
      Contains pretty much everything an XML-RPC client developer needs to know.

   `XML-RPC Introspection <http://xmlrpc-c.sourceforge.net/introspection.html>`_
      Describes the XML-RPC protocol extension for introspection.

   `XML-RPC Specification <http://www.xmlrpc.com/spec>`_
      The official specification.

   `Unofficial XML-RPC Errata <http://effbot.org/zone/xmlrpc-errata.htm>`_
      Fredrik Lundh's "unofficial errata, intended to clarify certain
      details in the XML-RPC specification, as well as hint at
      'best practices' to use when designing your own XML-RPC
      implementations."

.. _serverproxy-objects:

ServerProxy Objects
-------------------

A :class:`ServerProxy` instance has a method corresponding to each remote
procedure call accepted by the XML-RPC server.  Calling the method performs an
RPC, dispatched by both name and argument signature (e.g. the same method name
can be overloaded with multiple argument signatures).  The RPC finishes by
returning a value, which may be either returned data in a conformant type or a
:class:`Fault` or :class:`ProtocolError` object indicating an error.

Servers that support the XML introspection API support some common methods
grouped under the reserved :attr:`~ServerProxy.system` attribute:


.. method:: ServerProxy.system.listMethods()

   This method returns a list of strings, one for each (non-system) method
   supported by the XML-RPC server.


.. method:: ServerProxy.system.methodSignature(name)

   This method takes one parameter, the name of a method implemented by the XML-RPC
   server. It returns an array of possible signatures for this method. A signature
   is an array of types. The first of these types is the return type of the method,
   the rest are parameters.

   Because multiple signatures (ie. overloading) is permitted, this method returns
   a list of signatures rather than a singleton.

   Signatures themselves are restricted to the top level parameters expected by a
   method. For instance if a method expects one array of structs as a parameter,
   and it returns a string, its signature is simply "string, array". If it expects
   three integers and returns a string, its signature is "string, int, int, int".

   If no signature is defined for the method, a non-array value is returned. In
   Python this means that the type of the returned  value will be something other
   than list.


.. method:: ServerProxy.system.methodHelp(name)

   This method takes one parameter, the name of a method implemented by the XML-RPC
   server.  It returns a documentation string describing the use of that method. If
   no such string is available, an empty string is returned. The documentation
   string may contain HTML markup.


.. _boolean-objects:

Boolean Objects
---------------

This class may be initialized from any Python value; the instance returned
depends only on its truth value.  It supports various Python operators through
:meth:`__cmp__`, :meth:`__repr__`, :meth:`__int__`, and :meth:`__nonzero__`
methods, all implemented in the obvious ways.

It also has the following method, supported mainly for internal use by the
unmarshalling code:


.. method:: Boolean.encode(out)

   Write the XML-RPC encoding of this Boolean item to the out stream object.

A working example follows. The server code::

   import xmlrpclib
   from SimpleXMLRPCServer import SimpleXMLRPCServer

   def is_even(n):
       return n % 2 == 0

   server = SimpleXMLRPCServer(("localhost", 8000))
   print "Listening on port 8000..."
   server.register_function(is_even, "is_even")
   server.serve_forever()

The client code for the preceding server::

   import xmlrpclib

   proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
   print "3 is even: %s" % str(proxy.is_even(3))
   print "100 is even: %s" % str(proxy.is_even(100))

.. _datetime-objects:

DateTime Objects
----------------

.. class:: DateTime

   This class may be initialized with seconds since the epoch, a time
   tuple, an ISO 8601 time/date string, or a :class:`datetime.datetime`
   instance.  It has the following methods, supported mainly for internal
   use by the marshalling/unmarshalling code:


   .. method:: decode(string)

      Accept a string as the instance's new time value.


   .. method:: encode(out)

      Write the XML-RPC encoding of this :class:`DateTime` item to the *out* stream
      object.

   It also supports certain of Python's built-in operators through :meth:`__cmp__`
   and :meth:`__repr__` methods.

A working example follows. The server code::

   import datetime
   from SimpleXMLRPCServer import SimpleXMLRPCServer
   import xmlrpclib

   def today():
       today = datetime.datetime.today()
       return xmlrpclib.DateTime(today)

   server = SimpleXMLRPCServer(("localhost", 8000))
   print "Listening on port 8000..."
   server.register_function(today, "today")
   server.serve_forever()

The client code for the preceding server::

   import xmlrpclib
   import datetime

   proxy = xmlrpclib.ServerProxy("http://localhost:8000/")

   today = proxy.today()
   # convert the ISO8601 string to a datetime object
   converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
   print "Today: %s" % converted.strftime("%d.%m.%Y, %H:%M")

.. _binary-objects:

Binary Objects
--------------

.. class:: Binary

   This class may be initialized from string data (which may include NULs). The
   primary access to the content of a :class:`Binary` object is provided by an
   attribute:


   .. attribute:: data

      The binary data encapsulated by the :class:`Binary` instance.  The data is
      provided as an 8-bit string.

   :class:`Binary` objects have the following methods, supported mainly for
   internal use by the marshalling/unmarshalling code:


   .. method:: decode(string)

      Accept a base64 string and decode it as the instance's new data.


   .. method:: encode(out)

      Write the XML-RPC base 64 encoding of this binary item to the *out* stream object.

      The encoded data will have newlines every 76 characters as per
      `RFC 2045 section 6.8 <https://tools.ietf.org/html/rfc2045#section-6.8>`_,
      which was the de facto standard base64 specification when the
      XML-RPC spec was written.

   It also supports certain of Python's built-in operators through a
   :meth:`__cmp__` method.

Example usage of the binary objects.  We're going to transfer an image over
XMLRPC::

   from SimpleXMLRPCServer import SimpleXMLRPCServer
   import xmlrpclib

   def python_logo():
        with open("python_logo.jpg", "rb") as handle:
            return xmlrpclib.Binary(handle.read())

   server = SimpleXMLRPCServer(("localhost", 8000))
   print "Listening on port 8000..."
   server.register_function(python_logo, 'python_logo')

   server.serve_forever()

The client gets the image and saves it to a file::

   import xmlrpclib

   proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
   with open("fetched_python_logo.jpg", "wb") as handle:
       handle.write(proxy.python_logo().data)

.. _fault-objects:

Fault Objects
-------------

.. class:: Fault

   A :class:`Fault` object encapsulates the content of an XML-RPC fault tag. Fault
   objects have the following attributes:


   .. attribute:: faultCode

      A string indicating the fault type.


   .. attribute:: faultString

      A string containing a diagnostic message associated with the fault.

In the following example we're going to intentionally cause a :exc:`Fault` by
returning a complex type object.  The server code::

   from SimpleXMLRPCServer import SimpleXMLRPCServer

   # A marshalling error is going to occur because we're returning a
   # complex number
   def add(x, y):
       return x+y+0j

   server = SimpleXMLRPCServer(("localhost", 8000))
   print "Listening on port 8000..."
   server.register_function(add, 'add')

   server.serve_forever()

The client code for the preceding server::

   import xmlrpclib

   proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
   try:
       proxy.add(2, 5)
   except xmlrpclib.Fault as err:
       print "A fault occurred"
       print "Fault code: %d" % err.faultCode
       print "Fault string: %s" % err.faultString



.. _protocol-error-objects:

ProtocolError Objects
---------------------

.. class:: ProtocolError

   A :class:`ProtocolError` object describes a protocol error in the underlying
   transport layer (such as a 404 'not found' error if the server named by the URI
   does not exist).  It has the following attributes:


   .. attribute:: url

      The URI or URL that triggered the error.


   .. attribute:: errcode

      The error code.


   .. attribute:: errmsg

      The error message or diagnostic string.


   .. attribute:: headers

      A string containing the headers of the HTTP/HTTPS request that triggered the
      error.

In the following example we're going to intentionally cause a :exc:`ProtocolError`
by providing a URI that doesn't point to an XMLRPC server::

   import xmlrpclib

   # create a ServerProxy with a URI that doesn't respond to XMLRPC requests
   proxy = xmlrpclib.ServerProxy("http://www.google.com/")

   try:
       proxy.some_method()
   except xmlrpclib.ProtocolError as err:
       print "A protocol error occurred"
       print "URL: %s" % err.url
       print "HTTP/HTTPS headers: %s" % err.headers
       print "Error code: %d" % err.errcode
       print "Error message: %s" % err.errmsg

MultiCall Objects
-----------------

.. versionadded:: 2.4

The :class:`MultiCall` object provides a way to encapsulate multiple calls to a
remote server into a single request [#]_.


.. class:: MultiCall(server)

   Create an object used to boxcar method calls. *server* is the eventual target of
   the call. Calls can be made to the result object, but they will immediately
   return ``None``, and only store the call name and parameters in the
   :class:`MultiCall` object. Calling the object itself causes all stored calls to
   be transmitted as a single ``system.multicall`` request. The result of this call
   is a :term:`generator`; iterating over this generator yields the individual
   results.

A usage example of this class follows.  The server code ::

   from SimpleXMLRPCServer import SimpleXMLRPCServer

   def add(x,y):
       return x+y

   def subtract(x, y):
       return x-y

   def multiply(x, y):
       return x*y

   def divide(x, y):
       return x/y

   # A simple server with simple arithmetic functions
   server = SimpleXMLRPCServer(("localhost", 8000))
   print "Listening on port 8000..."
   server.register_multicall_functions()
   server.register_function(add, 'add')
   server.register_function(subtract, 'subtract')
   server.register_function(multiply, 'multiply')
   server.register_function(divide, 'divide')
   server.serve_forever()

The client code for the preceding server::

   import xmlrpclib

   proxy = xmlrpclib.ServerProxy("http://localhost:8000/")
   multicall = xmlrpclib.MultiCall(proxy)
   multicall.add(7,3)
   multicall.subtract(7,3)
   multicall.multiply(7,3)
   multicall.divide(7,3)
   result = multicall()

   print "7+3=%d, 7-3=%d, 7*3=%d, 7/3=%d" % tuple(result)


Convenience Functions
---------------------


.. function:: boolean(value)

   Convert any Python value to one of the XML-RPC Boolean constants, ``True`` or
   ``False``.


.. function:: dumps(params[, methodname[,  methodresponse[, encoding[, allow_none]]]])

   Convert *params* into an XML-RPC request. or into a response if *methodresponse*
   is true. *params* can be either a tuple of arguments or an instance of the
   :exc:`Fault` exception class.  If *methodresponse* is true, only a single value
   can be returned, meaning that *params* must be of length 1. *encoding*, if
   supplied, is the encoding to use in the generated XML; the default is UTF-8.
   Python's :const:`None` value cannot be used in standard XML-RPC; to allow using
   it via an extension,  provide a true value for *allow_none*.


.. function:: loads(data[, use_datetime])

   Convert an XML-RPC request or response into Python objects, a ``(params,
   methodname)``.  *params* is a tuple of argument; *methodname* is a string, or
   ``None`` if no method name is present in the packet. If the XML-RPC packet
   represents a fault condition, this function will raise a :exc:`Fault` exception.
   The *use_datetime* flag can be used to cause date/time values to be presented as
   :class:`datetime.datetime` objects; this is false by default.

   .. versionchanged:: 2.5
      The *use_datetime* flag was added.


.. _xmlrpc-client-example:

Example of Client Usage
-----------------------

::

   # simple test program (from the XML-RPC specification)
   from xmlrpclib import ServerProxy, Error

   # server = ServerProxy("http://localhost:8000") # local server
   server = ServerProxy("http://betty.userland.com")

   print server

   try:
       print server.examples.getStateName(41)
   except Error as v:
       print "ERROR", v

To access an XML-RPC server through a HTTP proxy, you need to define a custom
transport.  The following example shows how:

.. Example taken from http://lowlife.jp/nobonobo/wiki/xmlrpcwithproxy.html

::

   import xmlrpclib, httplib

   class ProxiedTransport(xmlrpclib.Transport):
       def set_proxy(self, proxy):
           self.proxy = proxy

       def make_connection(self, host):
           self.realhost = host
           h = httplib.HTTPConnection(self.proxy)
           return h

       def send_request(self, connection, handler, request_body):
           connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler))

       def send_host(self, connection, host):
           connection.putheader('Host', self.realhost)

   p = ProxiedTransport()
   p.set_proxy('proxy-server:8080')
   server = xmlrpclib.ServerProxy('http://time.xmlrpc.com/RPC2', transport=p)
   print server.currentTime.getCurrentTime()


Example of Client and Server Usage
----------------------------------

See :ref:`simplexmlrpcserver-example`.


.. rubric:: Footnotes

.. [#] This approach has been first presented in `a discussion on xmlrpc.com
   <https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic>`_.
.. the link now points to webarchive since the one at
.. http://www.xmlrpc.com/discuss/msgReader%241208 is broken (and webadmin
.. doesn't reply)
PK
%�\�U�p�I�I%html/_sources/library/zipfile.rst.txtnu�[���:mod:`zipfile` --- Work with ZIP archives
=========================================

.. module:: zipfile
   :synopsis: Read and write ZIP-format archive files.
.. moduleauthor:: James C. Ahlstrom <jim@interet.com>
.. sectionauthor:: James C. Ahlstrom <jim@interet.com>

.. versionadded:: 1.6

**Source code:** :source:`Lib/zipfile.py`

--------------

The ZIP file format is a common archive and compression standard. This module
provides tools to create, read, write, append, and list a ZIP file.  Any
advanced use of this module will require an understanding of the format, as
defined in `PKZIP Application Note`_.

This module does not currently handle multi-disk ZIP files.
It can handle ZIP files that use the ZIP64 extensions
(that is ZIP files that are more than 4 GByte in size).  It supports
decryption of encrypted files in ZIP archives, but it currently cannot
create an encrypted file.  Decryption is extremely slow as it is
implemented in native Python rather than C.

The module defines the following items:

.. exception:: BadZipfile

   The error raised for bad ZIP files (old name: ``zipfile.error``).


.. exception:: LargeZipFile

   The error raised when a ZIP file would require ZIP64 functionality but that has
   not been enabled.


.. class:: ZipFile
   :noindex:

   The class for reading and writing ZIP files.  See section
   :ref:`zipfile-objects` for constructor details.


.. class:: PyZipFile

   Class for creating ZIP archives containing Python libraries.


.. class:: ZipInfo([filename[, date_time]])

   Class used to represent information about a member of an archive. Instances
   of this class are returned by the :meth:`.getinfo` and :meth:`.infolist`
   methods of :class:`ZipFile` objects.  Most users of the :mod:`zipfile` module
   will not need to create these, but only use those created by this
   module. *filename* should be the full name of the archive member, and
   *date_time* should be a tuple containing six fields which describe the time
   of the last modification to the file; the fields are described in section
   :ref:`zipinfo-objects`.


.. function:: is_zipfile(filename)

   Returns ``True`` if *filename* is a valid ZIP file based on its magic number,
   otherwise returns ``False``.  *filename* may be a file or file-like object too.

   .. versionchanged:: 2.7
      Support for file and file-like objects.

.. data:: ZIP_STORED

   The numeric constant for an uncompressed archive member.


.. data:: ZIP_DEFLATED

   The numeric constant for the usual ZIP compression method.  This requires the
   :mod:`zlib` module.  No other compression methods are currently supported.


.. seealso::

   `PKZIP Application Note`_
      Documentation on the ZIP file format by Phil Katz, the creator of the format and
      algorithms used.

   `Info-ZIP Home Page <http://www.info-zip.org/>`_
      Information about the Info-ZIP project's ZIP archive programs and development
      libraries.


.. _zipfile-objects:

ZipFile Objects
---------------


.. class:: ZipFile(file[, mode[, compression[, allowZip64]]])

   Open a ZIP file, where *file* can be either a path to a file (a string) or a
   file-like object.  The *mode* parameter should be ``'r'`` to read an existing
   file, ``'w'`` to truncate and write a new file, or ``'a'`` to append to an
   existing file.  If *mode* is ``'a'`` and *file* refers to an existing ZIP
   file, then additional files are added to it.  If *file* does not refer to a
   ZIP file, then a new ZIP archive is appended to the file.  This is meant for
   adding a ZIP archive to another file (such as :file:`python.exe`).

   .. versionchanged:: 2.6
      If *mode* is ``a`` and the file does not exist at all, it is created.

   *compression* is the ZIP compression method to use when writing the archive,
   and should be :const:`ZIP_STORED` or :const:`ZIP_DEFLATED`; unrecognized
   values will cause :exc:`RuntimeError` to be raised.  If :const:`ZIP_DEFLATED`
   is specified but the :mod:`zlib` module is not available, :exc:`RuntimeError`
   is also raised. The default is :const:`ZIP_STORED`.  If *allowZip64* is
   ``True`` zipfile will create ZIP files that use the ZIP64 extensions when
   the zipfile is larger than 2 GB. If it is  false (the default) :mod:`zipfile`
   will raise an exception when the ZIP file would require ZIP64 extensions.
   ZIP64 extensions are disabled by default because the default :program:`zip`
   and :program:`unzip` commands on Unix (the InfoZIP utilities) don't support
   these extensions.

   .. versionchanged:: 2.7.1
      If the file is created with mode ``'a'`` or ``'w'`` and then
      :meth:`closed <close>` without adding any files to the archive, the appropriate
      ZIP structures for an empty archive will be written to the file.

   ZipFile is also a context manager and therefore supports the
   :keyword:`with` statement.  In the example, *myzip* is closed after the
   :keyword:`with` statement's suite is finished---even if an exception occurs::

      with ZipFile('spam.zip', 'w') as myzip:
          myzip.write('eggs.txt')

   .. versionadded:: 2.7
      Added the ability to use :class:`ZipFile` as a context manager.


.. method:: ZipFile.close()

   Close the archive file.  You must call :meth:`close` before exiting your program
   or essential records will not be written.


.. method:: ZipFile.getinfo(name)

   Return a :class:`ZipInfo` object with information about the archive member
   *name*.  Calling :meth:`getinfo` for a name not currently contained in the
   archive will raise a :exc:`KeyError`.


.. method:: ZipFile.infolist()

   Return a list containing a :class:`ZipInfo` object for each member of the
   archive.  The objects are in the same order as their entries in the actual ZIP
   file on disk if an existing archive was opened.


.. method:: ZipFile.namelist()

   Return a list of archive members by name.

   .. index::
      single: universal newlines; zipfile.ZipFile.open method


.. method:: ZipFile.open(name[, mode[, pwd]])

   Extract a member from the archive as a file-like object (ZipExtFile). *name* is
   the name of the file in the archive, or a :class:`ZipInfo` object. The *mode*
   parameter, if included, must be one of the following: ``'r'`` (the default),
   ``'U'``, or ``'rU'``. Choosing ``'U'`` or  ``'rU'`` will enable
   :term:`universal newline <universal newlines>`
   support in the read-only object. *pwd* is the password used for encrypted files.
   Calling  :meth:`.open` on a closed ZipFile will raise a  :exc:`RuntimeError`.

   .. note::

      The file-like object is read-only and provides the following methods:
      :meth:`~file.read`, :meth:`~file.readline`,
      :meth:`~file.readlines`, :meth:`__iter__`,
      :meth:`~object.next`.

   .. note::

      If the ZipFile was created by passing in a file-like object as the  first
      argument to the constructor, then the object returned by :meth:`.open` shares the
      ZipFile's file pointer.  Under these  circumstances, the object returned by
      :meth:`.open` should not  be used after any additional operations are performed
      on the  ZipFile object.  If the ZipFile was created by passing in a string (the
      filename) as the first argument to the constructor, then  :meth:`.open` will
      create a new file object that will be held by the ZipExtFile, allowing it to
      operate independently of the  ZipFile.

   .. note::

      The :meth:`.open`, :meth:`read` and :meth:`extract` methods can take a filename
      or a :class:`ZipInfo` object.  You will appreciate this when trying to read a
      ZIP file that contains members with duplicate names.

   .. versionadded:: 2.6


.. method:: ZipFile.extract(member[, path[, pwd]])

   Extract a member from the archive to the current working directory; *member*
   must be its full name or a :class:`ZipInfo` object).  Its file information is
   extracted as accurately as possible.  *path* specifies a different directory
   to extract to.  *member* can be a filename or a :class:`ZipInfo` object.
   *pwd* is the password used for encrypted files.

   Returns the normalized path created (a directory or new file).

   .. versionadded:: 2.6

   .. note::

      If a member filename is an absolute path, a drive/UNC sharepoint and
      leading (back)slashes will be stripped, e.g.: ``///foo/bar`` becomes
      ``foo/bar`` on Unix, and ``C:\foo\bar`` becomes ``foo\bar`` on Windows.
      And all ``".."`` components in a member filename will be removed, e.g.:
      ``../../foo../../ba..r`` becomes ``foo../ba..r``.  On Windows illegal
      characters (``:``, ``<``, ``>``, ``|``, ``"``, ``?``, and ``*``)
      replaced by underscore (``_``).


.. method:: ZipFile.extractall([path[, members[, pwd]]])

   Extract all members from the archive to the current working directory.  *path*
   specifies a different directory to extract to.  *members* is optional and must
   be a subset of the list returned by :meth:`namelist`.  *pwd* is the password
   used for encrypted files.

   .. warning::

      Never extract archives from untrusted sources without prior inspection.
      It is possible that files are created outside of *path*, e.g. members
      that have absolute filenames starting with ``"/"`` or filenames with two
      dots ``".."``.

   .. versionchanged:: 2.7.4
      The zipfile module attempts to prevent that.  See :meth:`extract` note.

   .. versionadded:: 2.6


.. method:: ZipFile.printdir()

   Print a table of contents for the archive to ``sys.stdout``.


.. method:: ZipFile.setpassword(pwd)

   Set *pwd* as default password to extract encrypted files.

   .. versionadded:: 2.6


.. method:: ZipFile.read(name[, pwd])

   Return the bytes of the file *name* in the archive.  *name* is the name of the
   file in the archive, or a :class:`ZipInfo` object.  The archive must be open for
   read or append. *pwd* is the password used for encrypted  files and, if specified,
   it will override the default password set with :meth:`setpassword`.  Calling
   :meth:`read` on a closed ZipFile  will raise a :exc:`RuntimeError`.

   .. versionchanged:: 2.6
      *pwd* was added, and *name* can now be a :class:`ZipInfo` object.


.. method:: ZipFile.testzip()

   Read all the files in the archive and check their CRC's and file headers.
   Return the name of the first bad file, or else return ``None``. Calling
   :meth:`testzip` on a closed ZipFile will raise a :exc:`RuntimeError`.


.. method:: ZipFile.write(filename[, arcname[, compress_type]])

   Write the file named *filename* to the archive, giving it the archive name
   *arcname* (by default, this will be the same as *filename*, but without a drive
   letter and with leading path separators removed).  If given, *compress_type*
   overrides the value given for the *compression* parameter to the constructor for
   the new entry.  The archive must be open with mode ``'w'`` or ``'a'`` -- calling
   :meth:`write` on a ZipFile created with mode ``'r'`` will raise a
   :exc:`RuntimeError`.  Calling  :meth:`write` on a closed ZipFile will raise a
   :exc:`RuntimeError`.

   .. note::

      There is no official file name encoding for ZIP files. If you have unicode file
      names, you must convert them to byte strings in your desired encoding before
      passing them to :meth:`write`. WinZip interprets all file names as encoded in
      CP437, also known as DOS Latin.

   .. note::

      Archive names should be relative to the archive root, that is, they should not
      start with a path separator.

   .. note::

      If ``arcname`` (or ``filename``, if ``arcname`` is  not given) contains a null
      byte, the name of the file in the archive will be truncated at the null byte.


.. method:: ZipFile.writestr(zinfo_or_arcname, bytes[, compress_type])

   Write the string *bytes* to the archive; *zinfo_or_arcname* is either the file
   name it will be given in the archive, or a :class:`ZipInfo` instance.  If it's
   an instance, at least the filename, date, and time must be given.  If it's a
   name, the date and time is set to the current date and time. The archive must be
   opened with mode ``'w'`` or ``'a'`` -- calling  :meth:`writestr` on a ZipFile
   created with mode ``'r'``  will raise a :exc:`RuntimeError`.  Calling
   :meth:`writestr` on a closed ZipFile will raise a :exc:`RuntimeError`.

   If given, *compress_type* overrides the value given for the *compression*
   parameter to the constructor for the new entry, or in the *zinfo_or_arcname*
   (if that is a :class:`ZipInfo` instance).

   .. note::

      When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* parameter,
      the compression method used will be that specified in the *compress_type*
      member of the given :class:`ZipInfo` instance.  By default, the
      :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.

   .. versionchanged:: 2.7
      The *compress_type* argument.

The following data attributes are also available:


.. attribute:: ZipFile.debug

   The level of debug output to use.  This may be set from ``0`` (the default, no
   output) to ``3`` (the most output).  Debugging information is written to
   ``sys.stdout``.

.. attribute:: ZipFile.comment

   The comment text associated with the ZIP file.  If assigning a comment to a
   :class:`ZipFile` instance created with mode 'a' or 'w', this should be a
   string no longer than 65535 bytes.  Comments longer than this will be
   truncated in the written archive when :meth:`.close` is called.

.. _pyzipfile-objects:

PyZipFile Objects
-----------------

The :class:`PyZipFile` constructor takes the same parameters as the
:class:`ZipFile` constructor.  Instances have one method in addition to those of
:class:`ZipFile` objects.


.. method:: PyZipFile.writepy(pathname[, basename])

   Search for files :file:`\*.py` and add the corresponding file to the archive.
   The corresponding file is a :file:`\*.pyo` file if available, else a
   :file:`\*.pyc` file, compiling if necessary.  If the pathname is a file, the
   filename must end with :file:`.py`, and just the (corresponding
   :file:`\*.py[co]`) file is added at the top level (no path information).  If the
   pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
   will be raised.  If it is a directory, and the directory is not a package
   directory, then all the files :file:`\*.py[co]` are added at the top level.  If
   the directory is a package directory, then all :file:`\*.py[co]` are added under
   the package name as a file path, and if any subdirectories are package
   directories, all of these are added recursively.  *basename* is intended for
   internal use only.  The :meth:`writepy` method makes archives with file names
   like this::

      string.pyc                                # Top level name
      test/__init__.pyc                         # Package directory
      test/test_support.pyc                          # Module test.test_support
      test/bogus/__init__.pyc                   # Subpackage directory
      test/bogus/myfile.pyc                     # Submodule test.bogus.myfile


.. _zipinfo-objects:

ZipInfo Objects
---------------

Instances of the :class:`ZipInfo` class are returned by the :meth:`.getinfo` and
:meth:`.infolist` methods of :class:`ZipFile` objects.  Each object stores
information about a single member of the ZIP archive.

Instances have the following attributes:


.. attribute:: ZipInfo.filename

   Name of the file in the archive.


.. attribute:: ZipInfo.date_time

   The time and date of the last modification to the archive member.  This is a
   tuple of six values:

   +-------+--------------------------+
   | Index | Value                    |
   +=======+==========================+
   | ``0`` | Year (>= 1980)           |
   +-------+--------------------------+
   | ``1`` | Month (one-based)        |
   +-------+--------------------------+
   | ``2`` | Day of month (one-based) |
   +-------+--------------------------+
   | ``3`` | Hours (zero-based)       |
   +-------+--------------------------+
   | ``4`` | Minutes (zero-based)     |
   +-------+--------------------------+
   | ``5`` | Seconds (zero-based)     |
   +-------+--------------------------+

   .. note::

      The ZIP file format does not support timestamps before 1980.


.. attribute:: ZipInfo.compress_type

   Type of compression for the archive member.


.. attribute:: ZipInfo.comment

   Comment for the individual archive member.


.. attribute:: ZipInfo.extra

   Expansion field data.  The `PKZIP Application Note`_ contains
   some comments on the internal structure of the data contained in this string.


.. attribute:: ZipInfo.create_system

   System which created ZIP archive.


.. attribute:: ZipInfo.create_version

   PKZIP version which created ZIP archive.


.. attribute:: ZipInfo.extract_version

   PKZIP version needed to extract archive.


.. attribute:: ZipInfo.reserved

   Must be zero.


.. attribute:: ZipInfo.flag_bits

   ZIP flag bits.


.. attribute:: ZipInfo.volume

   Volume number of file header.


.. attribute:: ZipInfo.internal_attr

   Internal attributes.


.. attribute:: ZipInfo.external_attr

   External file attributes.


.. attribute:: ZipInfo.header_offset

   Byte offset to the file header.


.. attribute:: ZipInfo.CRC

   CRC-32 of the uncompressed file.


.. attribute:: ZipInfo.compress_size

   Size of the compressed data.


.. attribute:: ZipInfo.file_size

   Size of the uncompressed file.


.. _zipfile-commandline:
.. program:: zipfile

Command-Line Interface
----------------------

The :mod:`zipfile` module provides a simple command-line interface to interact
with ZIP archives.

If you want to create a new ZIP archive, specify its name after the :option:`-c`
option and then list the filename(s) that should be included:

.. code-block:: shell-session

    $ python -m zipfile -c monty.zip spam.txt eggs.txt

Passing a directory is also acceptable:

.. code-block:: shell-session

    $ python -m zipfile -c monty.zip life-of-brian_1979/

If you want to extract a ZIP archive into the specified directory, use
the :option:`-e` option:

.. code-block:: shell-session

    $ python -m zipfile -e monty.zip target-dir/

For a list of the files in a ZIP archive, use the :option:`-l` option:

.. code-block:: shell-session

    $ python -m zipfile -l monty.zip


Command-line options
~~~~~~~~~~~~~~~~~~~~

.. cmdoption:: -l <zipfile>

   List files in a zipfile.

.. cmdoption:: -c <zipfile> <source1> ... <sourceN>

   Create zipfile from source files.

.. cmdoption:: -e <zipfile> <output_dir>

   Extract zipfile into target directory.

.. cmdoption:: -t <zipfile>

   Test whether the zipfile is valid or not.


.. _PKZIP Application Note: https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
PK
%�\6a��EE'html/_sources/library/zipimport.rst.txtnu�[���
:mod:`zipimport` --- Import modules from Zip archives
=====================================================

.. module:: zipimport
   :synopsis: support for importing Python modules from ZIP archives.
.. moduleauthor:: Just van Rossum <just@letterror.com>


.. versionadded:: 2.3

This module adds the ability to import Python modules (:file:`\*.py`,
:file:`\*.py[co]`) and packages from ZIP-format archives. It is usually not
needed to use the :mod:`zipimport` module explicitly; it is automatically used
by the built-in :keyword:`import` mechanism for :data:`sys.path` items that are paths
to ZIP archives.

Typically, :data:`sys.path` is a list of directory names as strings.  This module
also allows an item of :data:`sys.path` to be a string naming a ZIP file archive.
The ZIP archive can contain a subdirectory structure to support package imports,
and a path within the archive can be specified to only import from a
subdirectory.  For example, the path :file:`example.zip/lib/` would only
import from the :file:`lib/` subdirectory within the archive.

Any files may be present in the ZIP archive, but only files :file:`.py` and
:file:`.py[co]` are available for import.  ZIP import of dynamic modules
(:file:`.pyd`, :file:`.so`) is disallowed. Note that if an archive only contains
:file:`.py` files, Python will not attempt to modify the archive by adding the
corresponding :file:`.pyc` or :file:`.pyo` file, meaning that if a ZIP archive
doesn't contain :file:`.pyc` files, importing may be rather slow.

Using the built-in :func:`reload` function will fail if called on a module
loaded from a ZIP archive; it is unlikely that :func:`reload` would be needed,
since this would imply that the ZIP has been altered during runtime.

ZIP archives with an archive comment are currently not supported.

.. seealso::

   `PKZIP Application Note <https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT>`_
      Documentation on the ZIP file format by Phil Katz, the creator of the format and
      algorithms used.

   :pep:`273` - Import Modules from Zip Archives
      Written by James C. Ahlstrom, who also provided an implementation. Python 2.3
      follows the specification in PEP 273, but uses an implementation written by Just
      van Rossum that uses the import hooks described in PEP 302.

   :pep:`302` - New Import Hooks
      The PEP to add the import hooks that help this module work.


This module defines an exception:

.. exception:: ZipImportError

   Exception raised by zipimporter objects. It's a subclass of :exc:`ImportError`,
   so it can be caught as :exc:`ImportError`, too.


.. _zipimporter-objects:

zipimporter Objects
-------------------

:class:`zipimporter` is the class for importing ZIP files.

.. class:: zipimporter(archivepath)

   Create a new zipimporter instance. *archivepath* must be a path to a ZIP
   file, or to a specific path within a ZIP file.  For example, an *archivepath*
   of :file:`foo/bar.zip/lib` will look for modules in the :file:`lib` directory
   inside the ZIP file :file:`foo/bar.zip` (provided that it exists).

   :exc:`ZipImportError` is raised if *archivepath* doesn't point to a valid ZIP
   archive.

   .. method:: find_module(fullname[, path])

      Search for a module specified by *fullname*. *fullname* must be the fully
      qualified (dotted) module name. It returns the zipimporter instance itself
      if the module was found, or :const:`None` if it wasn't. The optional
      *path* argument is ignored---it's there for compatibility with the
      importer protocol.


   .. method:: get_code(fullname)

      Return the code object for the specified module. Raise
      :exc:`ZipImportError` if the module couldn't be found.


   .. method:: get_data(pathname)

      Return the data associated with *pathname*. Raise :exc:`IOError` if the
      file wasn't found.


   .. method:: get_filename(fullname)

      Return the value ``__file__`` would be set to if the specified module
      was imported. Raise :exc:`ZipImportError` if the module couldn't be
      found.

   .. versionadded:: 2.7


   .. method:: get_source(fullname)

      Return the source code for the specified module. Raise
      :exc:`ZipImportError` if the module couldn't be found, return
      :const:`None` if the archive does contain the module, but has no source
      for it.


   .. method:: is_package(fullname)

      Return ``True`` if the module specified by *fullname* is a package. Raise
      :exc:`ZipImportError` if the module couldn't be found.


   .. method:: load_module(fullname)

      Load the module specified by *fullname*. *fullname* must be the fully
      qualified (dotted) module name. It returns the imported module, or raises
      :exc:`ZipImportError` if it wasn't found.


   .. attribute:: archive

      The file name of the importer's associated ZIP file, without a possible
      subpath.


   .. attribute:: prefix

      The subpath within the ZIP file where modules are searched.  This is the
      empty string for zipimporter objects which point to the root of the ZIP
      file.

   The :attr:`archive` and :attr:`prefix` attributes, when combined with a
   slash, equal the original *archivepath* argument given to the
   :class:`zipimporter` constructor.


.. _zipimport-examples:

Examples
--------

Here is an example that imports a module from a ZIP archive - note that the
:mod:`zipimport` module is not explicitly used.

.. code-block:: shell-session

   $ unzip -l example.zip
   Archive:  example.zip
     Length     Date   Time    Name
    --------    ----   ----    ----
        8467  11-26-02 22:30   jwzthreading.py
    --------                   -------
        8467                   1 file
   $ ./python
   Python 2.3 (#1, Aug 1 2003, 19:54:32)
   >>> import sys
   >>> sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
   >>> import jwzthreading
   >>> jwzthreading.__file__
   'example.zip/jwzthreading.py'

PK
%�\lZݦ�1�1"html/_sources/library/zlib.rst.txtnu�[���
:mod:`zlib` --- Compression compatible with :program:`gzip`
===========================================================

.. module:: zlib
   :synopsis: Low-level interface to compression and decompression routines compatible with
              gzip.


For applications that require data compression, the functions in this module
allow compression and decompression, using the zlib library. The zlib library
has its own home page at http://www.zlib.net.   There are known
incompatibilities between the Python module and versions of the zlib library
earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using
1.1.4 or later.

zlib's functions have many options and often need to be used in a particular
order.  This documentation doesn't attempt to cover all of the permutations;
consult the zlib manual at http://www.zlib.net/manual.html for authoritative
information.

For reading and writing ``.gz`` files see the :mod:`gzip` module.

The available exception and functions in this module are:


.. exception:: error

   Exception raised on compression and decompression errors.


.. function:: adler32(data[, value])

   Computes an Adler-32 checksum of *data*.  (An Adler-32 checksum is almost as
   reliable as a CRC32 but can be computed much more quickly.)  If *value* is
   present, it is used as the starting value of the checksum; otherwise, a fixed
   default value is used.  This allows computing a running checksum over the
   concatenation of several inputs.  The algorithm is not cryptographically
   strong, and should not be used for authentication or digital signatures.  Since
   the algorithm is designed for use as a checksum algorithm, it is not suitable
   for use as a general hash algorithm.

   This function always returns an integer object.

.. note::
   To generate the same numeric value across all Python versions and
   platforms use adler32(data) & 0xffffffff.  If you are only using
   the checksum in packed binary format this is not necessary as the
   return value is the correct 32bit binary representation
   regardless of sign.

.. versionchanged:: 2.6
   The return value is in the range [-2**31, 2**31-1]
   regardless of platform.  In older versions the value is
   signed on some platforms and unsigned on others.

.. versionchanged:: 3.0
   The return value is unsigned and in the range [0, 2**32-1]
   regardless of platform.


.. function:: compress(string[, level])

   Compresses the data in *string*, returning a string contained compressed data.
   *level* is an integer from ``0`` to ``9`` controlling the level of compression;
   ``1`` is fastest and produces the least compression, ``9`` is slowest and
   produces the most.  ``0`` is no compression.  The default value is ``6``.
   Raises the :exc:`error` exception if any error occurs.


.. function:: compressobj([level[, method[, wbits[, memlevel[, strategy]]]]])

   Returns a compression object, to be used for compressing data streams that won't
   fit into memory at once.  *level* is an integer from
   ``0`` to ``9`` or ``-1``, controlling
   the level of compression; ``1`` is fastest and produces the least compression,
   ``9`` is slowest and produces the most.  ``0`` is no compression.  The default
   value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default
   compromise between speed and compression (currently equivalent to level 6).

   *method* is the compression algorithm. Currently, the only supported value is
   ``DEFLATED``.

   The *wbits* argument controls the size of the history buffer (or the
   "window size") used when compressing data, and whether a header and
   trailer is included in the output.  It can take several ranges of values.
   The default is 15.

   * +9 to +15: The base-two logarithm of the window size, which
     therefore ranges between 512 and 32768.  Larger values produce
     better compression at the expense of greater memory usage.  The
     resulting output will include a zlib-specific header and trailer.

   * −9 to −15: Uses the absolute value of *wbits* as the
     window size logarithm, while producing a raw output stream with no
     header or trailing checksum.

   * +25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the
     window size logarithm, while including a basic :program:`gzip` header
     and trailing checksum in the output.

   *memlevel* controls the amount of memory used for internal compression state.
   Valid values range from ``1`` to ``9``. Higher values using more memory,
   but are faster and produce smaller output. The default is 8.

   *strategy* is used to tune the compression algorithm. Possible values are
   ``Z_DEFAULT_STRATEGY``, ``Z_FILTERED``, and ``Z_HUFFMAN_ONLY``. The default
   is ``Z_DEFAULT_STRATEGY``.


.. function:: crc32(data[, value])

   .. index::
      single: Cyclic Redundancy Check
      single: checksum; Cyclic Redundancy Check

   Computes a CRC (Cyclic Redundancy Check)  checksum of *data*. If *value* is
   present, it is used as the starting value of the checksum; otherwise, a fixed
   default value is used.  This allows computing a running checksum over the
   concatenation of several inputs.  The algorithm is not cryptographically
   strong, and should not be used for authentication or digital signatures.  Since
   the algorithm is designed for use as a checksum algorithm, it is not suitable
   for use as a general hash algorithm.

   This function always returns an integer object.

.. note::
   To generate the same numeric value across all Python versions and
   platforms use crc32(data) & 0xffffffff.  If you are only using
   the checksum in packed binary format this is not necessary as the
   return value is the correct 32bit binary representation
   regardless of sign.

.. versionchanged:: 2.6
   The return value is in the range [-2**31, 2**31-1]
   regardless of platform.  In older versions the value would be
   signed on some platforms and unsigned on others.

.. versionchanged:: 3.0
   The return value is unsigned and in the range [0, 2**32-1]
   regardless of platform.


.. function:: decompress(string[, wbits[, bufsize]])

   Decompresses the data in *string*, returning a string containing the
   uncompressed data.  The *wbits* parameter depends on
   the format of *string*, and is discussed further below.
   If *bufsize* is given, it is used as the initial size of the output
   buffer.  Raises the :exc:`error` exception if any error occurs.

   .. _decompress-wbits:

   The *wbits* parameter controls the size of the history buffer
   (or "window size"), and what header and trailer format is expected.
   It is similar to the parameter for :func:`compressobj`, but accepts
   more ranges of values:

   * +8 to +15: The base-two logarithm of the window size.  The input
     must include a zlib header and trailer.

   * 0: Automatically determine the window size from the zlib header.
     Only supported since zlib 1.2.3.5.

   * −8 to −15: Uses the absolute value of *wbits* as the window size
     logarithm.  The input must be a raw stream with no header or trailer.

   * +24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as
     the window size logarithm.  The input must include a gzip header and
     trailer.

   * +40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as
     the window size logarithm, and automatically accepts either
     the zlib or gzip format.

   When decompressing a stream, the window size must not be smaller
   than the size originally used to compress the stream; using a too-small
   value may result in an :exc:`error` exception. The default *wbits* value
   is 15, which corresponds to the largest window size and requires a zlib
   header and trailer to be included.

   *bufsize* is the initial size of the buffer used to hold decompressed data.  If
   more space is required, the buffer size will be increased as needed, so you
   don't have to get this value exactly right; tuning it will only save a few calls
   to :c:func:`malloc`.  The default size is 16384.


.. function:: decompressobj([wbits])

   Returns a decompression object, to be used for decompressing data streams that
   won't fit into memory at once.

   The *wbits* parameter controls the size of the history buffer (or the
   "window size"), and what header and trailer format is expected.  It has
   the same meaning as `described for decompress() <#decompress-wbits>`__.

Compression objects support the following methods:


.. method:: Compress.compress(string)

   Compress *string*, returning a string containing compressed data for at least
   part of the data in *string*.  This data should be concatenated to the output
   produced by any preceding calls to the :meth:`compress` method.  Some input may
   be kept in internal buffers for later processing.


.. method:: Compress.flush([mode])

   All pending input is processed, and a string containing the remaining compressed
   output is returned.  *mode* can be selected from the constants
   :const:`Z_SYNC_FLUSH`,  :const:`Z_FULL_FLUSH`,  or  :const:`Z_FINISH`,
   defaulting to :const:`Z_FINISH`.  :const:`Z_SYNC_FLUSH` and
   :const:`Z_FULL_FLUSH` allow compressing further strings of data, while
   :const:`Z_FINISH` finishes the compressed stream and  prevents compressing any
   more data.  After calling :meth:`flush` with *mode* set to :const:`Z_FINISH`,
   the :meth:`compress` method cannot be called again; the only realistic action is
   to delete the object.


.. method:: Compress.copy()

   Returns a copy of the compression object.  This can be used to efficiently
   compress a set of data that share a common initial prefix.

   .. versionadded:: 2.5

Decompression objects support the following methods, and two attributes:


.. attribute:: Decompress.unused_data

   A string which contains any bytes past the end of the compressed data. That is,
   this remains ``""`` until the last byte that contains compression data is
   available.  If the whole string turned out to contain compressed data, this is
   ``""``, the empty string.

   The only way to determine where a string of compressed data ends is by actually
   decompressing it.  This means that when compressed data is contained part of a
   larger file, you can only find the end of it by reading data and feeding it
   followed by some non-empty string into a decompression object's
   :meth:`decompress` method until the :attr:`unused_data` attribute is no longer
   the empty string.


.. attribute:: Decompress.unconsumed_tail

   A string that contains any data that was not consumed by the last
   :meth:`decompress` call because it exceeded the limit for the uncompressed data
   buffer.  This data has not yet been seen by the zlib machinery, so you must feed
   it (possibly with further data concatenated to it) back to a subsequent
   :meth:`decompress` method call in order to get correct output.


.. method:: Decompress.decompress(string[, max_length])

   Decompress *string*, returning a string containing the uncompressed data
   corresponding to at least part of the data in *string*.  This data should be
   concatenated to the output produced by any preceding calls to the
   :meth:`decompress` method.  Some of the input data may be preserved in internal
   buffers for later processing.

   If the optional parameter *max_length* is non-zero then the return value will be
   no longer than *max_length*. This may mean that not all of the compressed input
   can be processed; and unconsumed data will be stored in the attribute
   :attr:`unconsumed_tail`. This string must be passed to a subsequent call to
   :meth:`decompress` if decompression is to continue.  If *max_length* is not
   supplied then the whole input is decompressed, and :attr:`unconsumed_tail` is an
   empty string.


.. method:: Decompress.flush([length])

   All pending input is processed, and a string containing the remaining
   uncompressed output is returned.  After calling :meth:`flush`, the
   :meth:`decompress` method cannot be called again; the only realistic action is
   to delete the object.

   The optional parameter *length* sets the initial size of the output buffer.


.. method:: Decompress.copy()

   Returns a copy of the decompression object.  This can be used to save the state
   of the decompressor midway through the data stream in order to speed up random
   seeks into the stream at a future point.

   .. versionadded:: 2.5


.. seealso::

   Module :mod:`gzip`
      Reading and writing :program:`gzip`\ -format files.

   http://www.zlib.net
      The zlib library home page.

   http://www.zlib.net/manual.html
      The zlib manual explains  the semantics and usage of the library's many
      functions.

PK
%�\[���\\.html/_sources/reference/compound_stmts.rst.txtnu�[���.. _compound:

*******************
Compound statements
*******************

.. index:: pair: compound; statement

Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way.  In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.

The :keyword:`if`, :keyword:`while` and :keyword:`for` statements implement
traditional control flow constructs.  :keyword:`try` specifies exception
handlers and/or cleanup code for a group of statements.  Function and class
definitions are also syntactically compound statements.

.. index::
   single: clause
   single: suite

Compound statements consist of one or more 'clauses.'  A clause consists of a
header and a 'suite.'  The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon.  A suite is a group of statements
controlled by a clause.  A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header's colon, or it
can be one or more indented statements on subsequent lines.  Only the latter
form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn't be clear to which :keyword:`if` clause a following
:keyword:`else` clause would belong:   ::

   if test1: if test2: print x

Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the :keyword:`print`
statements are executed::

   if x < y < z: print x; print y; print z

Summarizing:

.. productionlist::
   compound_stmt: `if_stmt`
                : | `while_stmt`
                : | `for_stmt`
                : | `try_stmt`
                : | `with_stmt`
                : | `funcdef`
                : | `classdef`
                : | `decorated`
   suite: `stmt_list` NEWLINE | NEWLINE INDENT `statement`+ DEDENT
   statement: `stmt_list` NEWLINE | `compound_stmt`
   stmt_list: `simple_stmt` (";" `simple_stmt`)* [";"]

.. index::
   single: NEWLINE token
   single: DEDENT token
   pair: dangling; else

Note that statements always end in a ``NEWLINE`` possibly followed by a
``DEDENT``. Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
'dangling :keyword:`else`' problem is solved in Python by requiring nested
:keyword:`if` statements to be indented).

The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.


.. _if:
.. _elif:
.. _else:

The :keyword:`if` statement
===========================

.. index::
   statement: if
   keyword: elif
   keyword: else

The :keyword:`if` statement is used for conditional execution:

.. productionlist::
   if_stmt: "if" `expression` ":" `suite`
          : ( "elif" `expression` ":" `suite` )*
          : ["else" ":" `suite`]

It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section :ref:`booleans` for the definition of
true and false); then that suite is executed (and no other part of the
:keyword:`if` statement is executed or evaluated).  If all expressions are
false, the suite of the :keyword:`else` clause, if present, is executed.


.. _while:

The :keyword:`while` statement
==============================

.. index::
   statement: while
   pair: loop; statement
   keyword: else

The :keyword:`while` statement is used for repeated execution as long as an
expression is true:

.. productionlist::
   while_stmt: "while" `expression` ":" `suite`
             : ["else" ":" `suite`]

This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the :keyword:`else` clause, if present, is executed and the loop
terminates.

.. index::
   statement: break
   statement: continue

A :keyword:`break` statement executed in the first suite terminates the loop
without executing the :keyword:`else` clause's suite.  A :keyword:`continue`
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.


.. _for:

The :keyword:`for` statement
============================

.. index::
   statement: for
   pair: loop; statement
   keyword: in
   keyword: else
   pair: target; list
   object: sequence

The :keyword:`for` statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

.. productionlist::
   for_stmt: "for" `target_list` "in" `expression_list` ":" `suite`
           : ["else" ":" `suite`]

The expression list is evaluated once; it should yield an iterable object.  An
iterator is created for the result of the ``expression_list``.  The suite is
then executed once for each item provided by the iterator, in the order of
ascending indices.  Each item in turn is assigned to the target list using the
standard rules for assignments, and then the suite is executed.  When the items
are exhausted (which is immediately when the sequence is empty), the suite in
the :keyword:`else` clause, if present, is executed, and the loop terminates.

.. index::
   statement: break
   statement: continue

A :keyword:`break` statement executed in the first suite terminates the loop
without executing the :keyword:`else` clause's suite.  A :keyword:`continue`
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the :keyword:`else` clause if there was no next
item.

The suite may assign to the variable(s) in the target list; this does not affect
the next item assigned to it.

.. index::
   builtin: range
   pair: Pascal; language

The target list is not deleted when the loop is finished, but if the sequence is
empty, it will not have been assigned to at all by the loop.  Hint: the built-in
function :func:`range` returns a sequence of integers suitable to emulate the
effect of Pascal's ``for i := a to b do``; e.g., ``range(3)`` returns the list
``[0, 1, 2]``.

.. note::

   .. index::
      single: loop; over mutable sequence
      single: mutable sequence; loop over

   There is a subtlety when the sequence is being modified by the loop (this can
   only occur for mutable sequences, e.g. lists). An internal counter is used to
   keep track of which item is used next, and this is incremented on each
   iteration.  When this counter has reached the length of the sequence the loop
   terminates.  This means that if the suite deletes the current (or a previous)
   item from the sequence, the next item will be skipped (since it gets the index
   of the current item which has already been treated).  Likewise, if the suite
   inserts an item in the sequence before the current item, the current item will
   be treated again the next time through the loop. This can lead to nasty bugs
   that can be avoided by making a temporary copy using a slice of the whole
   sequence, e.g., ::

      for x in a[:]:
          if x < 0: a.remove(x)


.. _try:
.. _except:
.. _finally:

The :keyword:`try` statement
============================

.. index::
   statement: try
   keyword: except
   keyword: finally

The :keyword:`try` statement specifies exception handlers and/or cleanup code
for a group of statements:

.. productionlist::
   try_stmt: try1_stmt | try2_stmt
   try1_stmt: "try" ":" `suite`
            : ("except" [`expression` [("as" | ",") `identifier`]] ":" `suite`)+
            : ["else" ":" `suite`]
            : ["finally" ":" `suite`]
   try2_stmt: "try" ":" `suite`
            : "finally" ":" `suite`

.. versionchanged:: 2.5
   In previous versions of Python, :keyword:`try`...\ :keyword:`except`...\
   :keyword:`finally` did not work. :keyword:`try`...\ :keyword:`except` had to be
   nested in :keyword:`try`...\ :keyword:`finally`.

The :keyword:`except` clause(s) specify one or more exception handlers. When no
exception occurs in the :keyword:`try` clause, no exception handler is executed.
When an exception occurs in the :keyword:`try` suite, a search for an exception
handler is started.  This search inspects the except clauses in turn until one
is found that matches the exception.  An expression-less except clause, if
present, must be last; it matches any exception.  For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is "compatible" with the exception.  An object is
compatible with an exception if it is the class or a base class of the exception
object, or a tuple containing an item compatible with the exception.

If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack.  [#]_

If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire :keyword:`try` statement raised the exception).

When a matching except clause is found, the exception is assigned to the target
specified in that except clause, if present, and the except clause's suite is
executed.  All except clauses must have an executable block.  When the end of
this block is reached, execution continues normally after the entire try
statement.  (This means that if two nested handlers exist for the same
exception, and the exception occurs in the try clause of the inner handler, the
outer handler will not handle the exception.)

.. index::
   module: sys
   object: traceback
   single: exc_type (in module sys)
   single: exc_value (in module sys)
   single: exc_traceback (in module sys)

Before an except clause's suite is executed, details about the exception are
assigned to three variables in the :mod:`sys` module: ``sys.exc_type`` receives
the object identifying the exception; ``sys.exc_value`` receives the exception's
parameter; ``sys.exc_traceback`` receives a traceback object (see section
:ref:`types`) identifying the point in the program where the exception
occurred. These details are also available through the :func:`sys.exc_info`
function, which returns a tuple ``(exc_type, exc_value, exc_traceback)``.  Use
of the corresponding variables is deprecated in favor of this function, since
their use is unsafe in a threaded program.  As of Python 1.5, the variables are
restored to their previous values (before the call) when returning from a
function that handled an exception.

.. index::
   keyword: else
   statement: return
   statement: break
   statement: continue

The optional :keyword:`else` clause is executed if the control flow leaves the
:keyword:`try` suite, no exception was raised, and no :keyword:`return`,
:keyword:`continue`, or :keyword:`break` statement was executed.  Exceptions in
the :keyword:`else` clause are not handled by the preceding :keyword:`except`
clauses.

.. index:: keyword: finally

If :keyword:`finally` is present, it specifies a 'cleanup' handler.  The
:keyword:`try` clause is executed, including any :keyword:`except` and
:keyword:`else` clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The :keyword:`finally` clause
is executed.  If there is a saved exception, it is re-raised at the end of the
:keyword:`finally` clause. If the :keyword:`finally` clause raises another
exception or executes a :keyword:`return` or :keyword:`break` statement, the
saved exception is discarded::

   >>> def f():
   ...     try:
   ...         1/0
   ...     finally:
   ...         return 42
   ...
   >>> f()
   42

The exception information is not available to the program during execution of
the :keyword:`finally` clause.

.. index::
   statement: return
   statement: break
   statement: continue

When a :keyword:`return`, :keyword:`break` or :keyword:`continue` statement is
executed in the :keyword:`try` suite of a :keyword:`try`...\ :keyword:`finally`
statement, the :keyword:`finally` clause is also executed 'on the way out.' A
:keyword:`continue` statement is illegal in the :keyword:`finally` clause. (The
reason is a problem with the current implementation --- this restriction may be
lifted in the future).

The return value of a function is determined by the last :keyword:`return`
statement executed.  Since the :keyword:`finally` clause always executes, a
:keyword:`return` statement executed in the :keyword:`finally` clause will
always be the last one executed::

   >>> def foo():
   ...     try:
   ...         return 'try'
   ...     finally:
   ...         return 'finally'
   ...
   >>> foo()
   'finally'

Additional information on exceptions can be found in section :ref:`exceptions`,
and information on using the :keyword:`raise` statement to generate exceptions
may be found in section :ref:`raise`.


.. _with:
.. _as:

The :keyword:`with` statement
=============================

.. index::
    statement: with
    single: as; with statement

.. versionadded:: 2.5

The :keyword:`with` statement is used to wrap the execution of a block with
methods defined by a context manager (see section :ref:`context-managers`). This
allows common :keyword:`try`...\ :keyword:`except`...\ :keyword:`finally` usage
patterns to be encapsulated for convenient reuse.

.. productionlist::
   with_stmt: "with" with_item ("," with_item)* ":" `suite`
   with_item: `expression` ["as" `target`]

The execution of the :keyword:`with` statement with one "item" proceeds as follows:

#. The context expression (the expression given in the :token:`with_item`) is
   evaluated to obtain a context manager.

#. The context manager's :meth:`__exit__` is loaded for later use.

#. The context manager's :meth:`__enter__` method is invoked.

#. If a target was included in the :keyword:`with` statement, the return value
   from :meth:`__enter__` is assigned to it.

   .. note::

      The :keyword:`with` statement guarantees that if the :meth:`__enter__` method
      returns without an error, then :meth:`__exit__` will always be called. Thus, if
      an error occurs during the assignment to the target list, it will be treated the
      same as an error occurring within the suite would be. See step 6 below.

#. The suite is executed.

#. The context manager's :meth:`__exit__` method is invoked. If an exception
   caused the suite to be exited, its type, value, and traceback are passed as
   arguments to :meth:`__exit__`. Otherwise, three :const:`None` arguments are
   supplied.

   If the suite was exited due to an exception, and the return value from the
   :meth:`__exit__` method was false, the exception is reraised. If the return
   value was true, the exception is suppressed, and execution continues with the
   statement following the :keyword:`with` statement.

   If the suite was exited for any reason other than an exception, the return value
   from :meth:`__exit__` is ignored, and execution proceeds at the normal location
   for the kind of exit that was taken.

With more than one item, the context managers are processed as if multiple
:keyword:`with` statements were nested::

   with A() as a, B() as b:
       suite

is equivalent to ::

   with A() as a:
       with B() as b:
           suite

.. note::

   In Python 2.5, the :keyword:`with` statement is only allowed when the
   ``with_statement`` feature has been enabled.  It is always enabled in
   Python 2.6.

.. versionchanged:: 2.7
   Support for multiple context expressions.

.. seealso::

   :pep:`343` - The "with" statement
      The specification, background, and examples for the Python :keyword:`with`
      statement.


.. index::
   single: parameter; function definition

.. _function:
.. _def:

Function definitions
====================

.. index::
   statement: def
   pair: function; definition
   pair: function; name
   pair: name; binding
   object: user-defined function
   object: function

A function definition defines a user-defined function object (see section
:ref:`types`):

.. productionlist::
   decorated: decorators (classdef | funcdef)
   decorators: `decorator`+
   decorator: "@" `dotted_name` ["(" [`argument_list` [","]] ")"] NEWLINE
   funcdef: "def" `funcname` "(" [`parameter_list`] ")" ":" `suite`
   dotted_name: `identifier` ("." `identifier`)*
   parameter_list: (`defparameter` ",")*
                 : (  "*" `identifier` ["," "**" `identifier`]
                 : | "**" `identifier`
                 : | `defparameter` [","] )
   defparameter: `parameter` ["=" `expression`]
   sublist: `parameter` ("," `parameter`)* [","]
   parameter: `identifier` | "(" `sublist` ")"
   funcname: `identifier`

A function definition is an executable statement.  Its execution binds the
function name in the current local namespace to a function object (a wrapper
around the executable code for the function).  This function object contains a
reference to the current global namespace as the global namespace to be used
when the function is called.

The function definition does not execute the function body; this gets executed
only when the function is called. [#]_

.. index::
  statement: @

A function definition may be wrapped by one or more :term:`decorator` expressions.
Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition.  The result must be a callable, which is
invoked with the function object as the only argument. The returned value is
bound to the function name instead of the function object.  Multiple decorators
are applied in nested fashion. For example, the following code::

   @f1(arg)
   @f2
   def func(): pass

is equivalent to::

   def func(): pass
   func = f1(arg)(f2(func))

.. index::
   triple: default; parameter; value
   single: argument; function definition

When one or more top-level :term:`parameters <parameter>` have the form
*parameter* ``=`` *expression*, the function is said to have "default parameter
values."  For a parameter with a default value, the corresponding
:term:`argument` may be omitted from a call, in which
case the parameter's default value is substituted.  If a
parameter has a default value, all following parameters must also have a default
value --- this is a syntactic restriction that is not expressed by the grammar.

**Default parameter values are evaluated when the function definition is
executed.**  This means that the expression is evaluated once, when the function
is defined, and that the same "pre-computed" value is used for each call.  This
is especially important to understand when a default parameter is a mutable
object, such as a list or a dictionary: if the function modifies the object
(e.g. by appending an item to a list), the default value is in effect modified.
This is generally not what was intended.  A way around this  is to use ``None``
as the default, and explicitly test for it in the body of the function, e.g.::

   def whats_on_the_telly(penguin=None):
       if penguin is None:
           penguin = []
       penguin.append("property of the zoo")
       return penguin

.. index::
  statement: *
  statement: **

Function call semantics are described in more detail in section :ref:`calls`. A
function call always assigns values to all parameters mentioned in the parameter
list, either from position arguments, from keyword arguments, or from default
values.  If the form "``*identifier``" is present, it is initialized to a tuple
receiving any excess positional parameters, defaulting to the empty tuple.  If
the form "``**identifier``" is present, it is initialized to a new dictionary
receiving any excess keyword arguments, defaulting to a new empty dictionary.

.. index:: pair: lambda; expression

It is also possible to create anonymous functions (functions not bound to a
name), for immediate use in expressions.  This uses lambda expressions, described in
section :ref:`lambda`.  Note that the lambda expression is merely a shorthand for a
simplified function definition; a function defined in a ":keyword:`def`"
statement can be passed around or assigned to another name just like a function
defined by a lambda expression.  The ":keyword:`def`" form is actually more powerful
since it allows the execution of multiple statements.

**Programmer's note:** Functions are first-class objects.  A "``def``" form
executed inside a function definition defines a local function that can be
returned or passed around.  Free variables used in the nested function can
access the local variables of the function containing the def.  See section
:ref:`naming` for details.


.. _class:

Class definitions
=================

.. index::
   object: class
   statement: class
   pair: class; definition
   pair: class; name
   pair: name; binding
   pair: execution; frame
   single: inheritance
   single: docstring

A class definition defines a class object (see section :ref:`types`):

.. productionlist::
   classdef: "class" `classname` [`inheritance`] ":" `suite`
   inheritance: "(" [`expression_list`] ")"
   classname: `identifier`

A class definition is an executable statement.  It first evaluates the
inheritance list, if present.  Each item in the inheritance list should evaluate
to a class object or class type which allows subclassing.  The class's suite is
then executed in a new execution frame (see section :ref:`naming`), using a
newly created local namespace and the original global namespace. (Usually, the
suite contains only function definitions.)  When the class's suite finishes
execution, its execution frame is discarded but its local namespace is
saved. [#]_ A class object is then created using the inheritance list for the
base classes and the saved local namespace for the attribute dictionary.  The
class name is bound to this class object in the original local namespace.

**Programmer's note:** Variables defined in the class definition are class
variables; they are shared by all instances.  To create instance variables, they
can be set in a method with ``self.name = value``.  Both class and instance
variables are accessible through the notation "``self.name``", and an instance
variable hides a class variable with the same name when accessed in this way.
Class variables can be used as defaults for instance variables, but using
mutable values there can lead to unexpected results.  For :term:`new-style
class`\es, descriptors can be used to create instance variables with different
implementation details.

Class definitions, like function definitions, may be wrapped by one or more
:term:`decorator` expressions.  The evaluation rules for the decorator
expressions are the same as for functions.  The result must be a class object,
which is then bound to the class name.

.. rubric:: Footnotes

.. [#] The exception is propagated to the invocation stack unless
   there is a :keyword:`finally` clause which happens to raise another
   exception. That new exception causes the old one to be lost.

.. [#] A string literal appearing as the first statement in the function body is
   transformed into the function's ``__doc__`` attribute and therefore the
   function's :term:`docstring`.

.. [#] A string literal appearing as the first statement in the class body is
   transformed into the namespace's ``__doc__`` item and therefore the class's
   :term:`docstring`.
PK
%�\��J�����)html/_sources/reference/datamodel.rst.txtnu�[���
.. _datamodel:

**********
Data model
**********


.. _objects:

Objects, values and types
=========================

.. index::
   single: object
   single: data

:dfn:`Objects` are Python's abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann's model of a "stored program computer," code is also
represented by objects.)

.. index::
   builtin: id
   builtin: type
   single: identity of an object
   single: value of an object
   single: type of an object
   single: mutable object
   single: immutable object

Every object has an identity, a type and a value.  An object's *identity* never
changes once it has been created; you may think of it as the object's address in
memory.  The ':keyword:`is`' operator compares the identity of two objects; the
:func:`id` function returns an integer representing its identity (currently
implemented as its address). An object's :dfn:`type` is also unchangeable. [#]_
An object's type determines the operations that the object supports (e.g., "does
it have a length?") and also defines the possible values for objects of that
type.  The :func:`type` function returns an object's type (which is an object
itself).  The *value* of some objects can change.  Objects whose value can
change are said to be *mutable*; objects whose value is unchangeable once they
are created are called *immutable*. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter's value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object's mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.

.. index::
   single: garbage collection
   single: reference counting
   single: unreachable object

Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected.  An implementation is allowed to postpone garbage
collection or omit it altogether --- it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.

.. impl-detail::

   CPython currently uses a reference-counting scheme with (optional) delayed
   detection of cyclically linked garbage, which collects most objects as soon
   as they become unreachable, but is not guaranteed to collect garbage
   containing circular references.  See the documentation of the :mod:`gc`
   module for information on controlling the collection of cyclic garbage.
   Other implementations act differently and CPython may change.
   Do not depend on immediate finalization of objects when they become
   unreachable (ex: always close files).

Note that the use of the implementation's tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a ':keyword:`try`...\ :keyword:`except`' statement may keep
objects alive.

Some objects contain references to "external" resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a :meth:`close` method. Programs are strongly recommended to explicitly
close such objects.  The ':keyword:`try`...\ :keyword:`finally`' statement
provides a convenient way to do this.

.. index:: single: container

Some objects contain references to other objects; these are called *containers*.
Examples of containers are tuples, lists and dictionaries.  The references are
part of a container's value.  In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied.  So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.

Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.  E.g.,
after ``a = 1; b = 1``, ``a`` and ``b`` may or may not refer to the same object
with the value one, depending on the implementation, but after ``c = []; d =
[]``, ``c`` and ``d`` are guaranteed to refer to two different, unique, newly
created empty lists. (Note that ``c = d = []`` assigns the same object to both
``c`` and ``d``.)


.. _types:

The standard type hierarchy
===========================

.. index::
   single: type
   pair: data; type
   pair: type; hierarchy
   pair: extension; module
   pair: C; language

Below is a list of the types that are built into Python.  Extension modules
(written in C, Java, or other languages, depending on the implementation) can
define additional types.  Future versions of Python may add types to the type
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).

.. index::
   single: attribute
   pair: special; attribute
   triple: generic; special; attribute

Some of the type descriptions below contain a paragraph listing 'special
attributes.'  These are attributes that provide access to the implementation and
are not intended for general use.  Their definition may change in the future.

None
   .. index:: object: None

   This type has a single value.  There is a single object with this value. This
   object is accessed through the built-in name ``None``. It is used to signify the
   absence of a value in many situations, e.g., it is returned from functions that
   don't explicitly return anything. Its truth value is false.

NotImplemented
   .. index:: object: NotImplemented

   This type has a single value.  There is a single object with this value. This
   object is accessed through the built-in name ``NotImplemented``. Numeric methods
   and rich comparison methods may return this value if they do not implement the
   operation for the operands provided.  (The interpreter will then try the
   reflected operation, or some other fallback, depending on the operator.)  Its
   truth value is true.

Ellipsis
   .. index:: object: Ellipsis

   This type has a single value.  There is a single object with this value. This
   object is accessed through the built-in name ``Ellipsis``. It is used to
   indicate the presence of the ``...`` syntax in a slice.  Its truth value is
   true.

:class:`numbers.Number`
   .. index:: object: numeric

   These are created by numeric literals and returned as results by arithmetic
   operators and arithmetic built-in functions.  Numeric objects are immutable;
   once created their value never changes.  Python numbers are of course strongly
   related to mathematical numbers, but subject to the limitations of numerical
   representation in computers.

   Python distinguishes between integers, floating point numbers, and complex
   numbers:

   :class:`numbers.Integral`
      .. index:: object: integer

      These represent elements from the mathematical set of integers (positive and
      negative).

      There are three types of integers:

      Plain integers
         .. index::
            object: plain integer
            single: OverflowError (built-in exception)

         These represent numbers in the range -2147483648 through 2147483647.
         (The range may be larger on machines with a larger natural word size,
         but not smaller.)  When the result of an operation would fall outside
         this range, the result is normally returned as a long integer (in some
         cases, the exception :exc:`OverflowError` is raised instead).  For the
         purpose of shift and mask operations, integers are assumed to have a
         binary, 2's complement notation using 32 or more bits, and hiding no
         bits from the user (i.e., all 4294967296 different bit patterns
         correspond to different values).

      Long integers
         .. index:: object: long integer

         These represent numbers in an unlimited range, subject to available
         (virtual) memory only.  For the purpose of shift and mask operations, a
         binary representation is assumed, and negative numbers are represented
         in a variant of 2's complement which gives the illusion of an infinite
         string of sign bits extending to the left.

      Booleans
         .. index::
            object: Boolean
            single: False
            single: True

         These represent the truth values False and True.  The two objects
         representing the values ``False`` and ``True`` are the only Boolean objects.
         The Boolean type is a subtype of plain integers, and Boolean values
         behave like the values 0 and 1, respectively, in almost all contexts,
         the exception being that when converted to a string, the strings
         ``"False"`` or ``"True"`` are returned, respectively.

      .. index:: pair: integer; representation

      The rules for integer representation are intended to give the most
      meaningful interpretation of shift and mask operations involving negative
      integers and the least surprises when switching between the plain and long
      integer domains.  Any operation, if it yields a result in the plain
      integer domain, will yield the same result in the long integer domain or
      when using mixed operands.  The switch between domains is transparent to
      the programmer.

   :class:`numbers.Real` (:class:`float`)
      .. index::
         object: floating point
         pair: floating point; number
         pair: C; language
         pair: Java; language

      These represent machine-level double precision floating point numbers. You are
      at the mercy of the underlying machine architecture (and C or Java
      implementation) for the accepted range and handling of overflow. Python does not
      support single-precision floating point numbers; the savings in processor and
      memory usage that are usually the reason for using these are dwarfed by the
      overhead of using objects in Python, so there is no reason to complicate the
      language with two kinds of floating point numbers.

   :class:`numbers.Complex`
      .. index::
         object: complex
         pair: complex; number

      These represent complex numbers as a pair of machine-level double precision
      floating point numbers.  The same caveats apply as for floating point numbers.
      The real and imaginary parts of a complex number ``z`` can be retrieved through
      the read-only attributes ``z.real`` and ``z.imag``.

Sequences
   .. index::
      builtin: len
      object: sequence
      single: index operation
      single: item selection
      single: subscription

   These represent finite ordered sets indexed by non-negative numbers. The
   built-in function :func:`len` returns the number of items of a sequence. When
   the length of a sequence is *n*, the index set contains the numbers 0, 1,
   ..., *n*-1.  Item *i* of sequence *a* is selected by ``a[i]``.

   .. index:: single: slicing

   Sequences also support slicing: ``a[i:j]`` selects all items with index *k* such
   that *i* ``<=`` *k* ``<`` *j*.  When used as an expression, a slice is a
   sequence of the same type.  This implies that the index set is renumbered so
   that it starts at 0.

   .. index:: single: extended slicing

   Some sequences also support "extended slicing" with a third "step" parameter:
   ``a[i:j:k]`` selects all items of *a* with index *x* where ``x = i + n*k``, *n*
   ``>=`` ``0`` and *i* ``<=`` *x* ``<`` *j*.

   Sequences are distinguished according to their mutability:

   Immutable sequences
      .. index::
         object: immutable sequence
         object: immutable

      An object of an immutable sequence type cannot change once it is created.  (If
      the object contains references to other objects, these other objects may be
      mutable and may be changed; however, the collection of objects directly
      referenced by an immutable object cannot change.)

      The following types are immutable sequences:

      Strings
         .. index::
            builtin: chr
            builtin: ord
            object: string
            single: character
            single: byte
            single: ASCII@ASCII

         The items of a string are characters.  There is no separate character type; a
         character is represented by a string of one item. Characters represent (at
         least) 8-bit bytes.  The built-in functions :func:`chr` and :func:`ord` convert
         between characters and nonnegative integers representing the byte values.  Bytes
         with the values 0--127 usually represent the corresponding ASCII values, but the
         interpretation of values is up to the program.  The string data type is also
         used to represent arrays of bytes, e.g., to hold data read from a file.

         .. index::
            single: ASCII@ASCII
            single: EBCDIC
            single: character set
            pair: string; comparison
            builtin: chr
            builtin: ord

         (On systems whose native character set is not ASCII, strings may use EBCDIC in
         their internal representation, provided the functions :func:`chr` and
         :func:`ord` implement a mapping between ASCII and EBCDIC, and string comparison
         preserves the ASCII order. Or perhaps someone can propose a better rule?)

      Unicode
         .. index::
            builtin: unichr
            builtin: ord
            builtin: unicode
            object: unicode
            single: character
            single: integer
            single: Unicode

         The items of a Unicode object are Unicode code units.  A Unicode code unit is
         represented by a Unicode object of one item and can hold either a 16-bit or
         32-bit value representing a Unicode ordinal (the maximum value for the ordinal
         is given in ``sys.maxunicode``, and depends on how Python is configured at
         compile time).  Surrogate pairs may be present in the Unicode object, and will
         be reported as two separate items.  The built-in functions :func:`unichr` and
         :func:`ord` convert between code units and nonnegative integers representing the
         Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to
         other encodings are possible through the Unicode method :meth:`encode` and the
         built-in function :func:`unicode`.

      Tuples
         .. index::
            object: tuple
            pair: singleton; tuple
            pair: empty; tuple

         The items of a tuple are arbitrary Python objects. Tuples of two or more items
         are formed by comma-separated lists of expressions.  A tuple of one item (a
         'singleton') can be formed by affixing a comma to an expression (an expression
         by itself does not create a tuple, since parentheses must be usable for grouping
         of expressions).  An empty tuple can be formed by an empty pair of parentheses.

   Mutable sequences
      .. index::
         object: mutable sequence
         object: mutable
         pair: assignment; statement
         single: subscription
         single: slicing

      Mutable sequences can be changed after they are created.  The subscription and
      slicing notations can be used as the target of assignment and :keyword:`del`
      (delete) statements.

      There are currently two intrinsic mutable sequence types:

      Lists
         .. index:: object: list

         The items of a list are arbitrary Python objects.  Lists are formed by placing a
         comma-separated list of expressions in square brackets. (Note that there are no
         special cases needed to form lists of length 0 or 1.)

      Byte Arrays
         .. index:: bytearray

         A bytearray object is a mutable array. They are created by the built-in
         :func:`bytearray` constructor.  Aside from being mutable (and hence
         unhashable), byte arrays otherwise provide the same interface and
         functionality as immutable bytes objects.

      .. index:: module: array

      The extension module :mod:`array` provides an additional example of a mutable
      sequence type.

Set types
   .. index::
      builtin: len
      object: set type

   These represent unordered, finite sets of unique, immutable objects. As such,
   they cannot be indexed by any subscript. However, they can be iterated over, and
   the built-in function :func:`len` returns the number of items in a set. Common
   uses for sets are fast membership testing, removing duplicates from a sequence,
   and computing mathematical operations such as intersection, union, difference,
   and symmetric difference.

   For set elements, the same immutability rules apply as for dictionary keys. Note
   that numeric types obey the normal rules for numeric comparison: if two numbers
   compare equal (e.g., ``1`` and ``1.0``), only one of them can be contained in a
   set.

   There are currently two intrinsic set types:

   Sets
      .. index:: object: set

      These represent a mutable set. They are created by the built-in :func:`set`
      constructor and can be modified afterwards by several methods, such as
      :meth:`~set.add`.

   Frozen sets
      .. index:: object: frozenset

      These represent an immutable set.  They are created by the built-in
      :func:`frozenset` constructor.  As a frozenset is immutable and
      :term:`hashable`, it can be used again as an element of another set, or as
      a dictionary key.

Mappings
   .. index::
      builtin: len
      single: subscription
      object: mapping

   These represent finite sets of objects indexed by arbitrary index sets. The
   subscript notation ``a[k]`` selects the item indexed by ``k`` from the mapping
   ``a``; this can be used in expressions and as the target of assignments or
   :keyword:`del` statements. The built-in function :func:`len` returns the number
   of items in a mapping.

   There is currently a single intrinsic mapping type:

   Dictionaries
      .. index:: object: dictionary

      These represent finite sets of objects indexed by nearly arbitrary values.  The
      only types of values not acceptable as keys are values containing lists or
      dictionaries or other mutable types that are compared by value rather than by
      object identity, the reason being that the efficient implementation of
      dictionaries requires a key's hash value to remain constant. Numeric types used
      for keys obey the normal rules for numeric comparison: if two numbers compare
      equal (e.g., ``1`` and ``1.0``) then they can be used interchangeably to index
      the same dictionary entry.

      Dictionaries are mutable; they can be created by the ``{...}`` notation (see
      section :ref:`dict`).

      .. index::
         module: dbm
         module: gdbm
         module: bsddb

      The extension modules :mod:`dbm`, :mod:`gdbm`, and :mod:`bsddb` provide
      additional examples of mapping types.

Callable types
   .. index::
      object: callable
      pair: function; call
      single: invocation
      pair: function; argument

   These are the types to which the function call operation (see section
   :ref:`calls`) can be applied:

   User-defined functions
      .. index::
         pair: user-defined; function
         object: function
         object: user-defined function

      A user-defined function object is created by a function definition (see
      section :ref:`function`).  It should be called with an argument list
      containing the same number of items as the function's formal parameter
      list.

      Special attributes:

      .. tabularcolumns:: |l|L|l|

      .. index::
         single: __doc__ (function attribute)
         single: __name__ (function attribute)
         single: __module__ (function attribute)
         single: __dict__ (function attribute)
         single: __defaults__ (function attribute)
         single: __code__ (function attribute)
         single: __globals__ (function attribute)
         single: __closure__ (function attribute)
         single: func_doc (function attribute)
         single: func_name (function attribute)
         single: func_dict (function attribute)
         single: func_defaults (function attribute)
         single: func_code (function attribute)
         single: func_globals (function attribute)
         single: func_closure (function attribute)
         pair: global; namespace

      +-----------------------+-------------------------------+-----------+
      | Attribute             | Meaning                       |           |
      +=======================+===============================+===========+
      | :attr:`__doc__`       | The function's documentation  | Writable  |
      | :attr:`func_doc`      | string, or ``None`` if        |           |
      |                       | unavailable.                  |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`~definition.\  | The function's name           | Writable  |
      | __name__`             |                               |           |
      | :attr:`func_name`     |                               |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`__module__`    | The name of the module the    | Writable  |
      |                       | function was defined in, or   |           |
      |                       | ``None`` if unavailable.      |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`__defaults__`  | A tuple containing default    | Writable  |
      | :attr:`func_defaults` | argument values for those     |           |
      |                       | arguments that have defaults, |           |
      |                       | or ``None`` if no arguments   |           |
      |                       | have a default value.         |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`__code__`      | The code object representing  | Writable  |
      | :attr:`func_code`     | the compiled function body.   |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`__globals__`   | A reference to the dictionary | Read-only |
      | :attr:`func_globals`  | that holds the function's     |           |
      |                       | global variables --- the      |           |
      |                       | global namespace of the       |           |
      |                       | module in which the function  |           |
      |                       | was defined.                  |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`~object.\      | The namespace supporting      | Writable  |
      | __dict__`             | arbitrary function            |           |
      | :attr:`func_dict`     | attributes.                   |           |
      +-----------------------+-------------------------------+-----------+
      | :attr:`__closure__`   | ``None`` or a tuple of cells  | Read-only |
      | :attr:`func_closure`  | that contain bindings for the |           |
      |                       | function's free variables.    |           |
      +-----------------------+-------------------------------+-----------+

      Most of the attributes labelled "Writable" check the type of the assigned value.

      .. versionchanged:: 2.4
         ``func_name`` is now writable.

      .. versionchanged:: 2.6
         The double-underscore attributes ``__closure__``, ``__code__``,
         ``__defaults__``, and ``__globals__`` were introduced as aliases for
         the corresponding ``func_*`` attributes for forwards compatibility
         with Python 3.

      Function objects also support getting and setting arbitrary attributes, which
      can be used, for example, to attach metadata to functions.  Regular attribute
      dot-notation is used to get and set such attributes. *Note that the current
      implementation only supports function attributes on user-defined functions.
      Function attributes on built-in functions may be supported in the future.*

      Additional information about a function's definition can be retrieved from its
      code object; see the description of internal types below.

   User-defined methods
      .. index::
         object: method
         object: user-defined method
         pair: user-defined; method

      A user-defined method object combines a class, a class instance (or ``None``)
      and any callable object (normally a user-defined function).

      Special read-only attributes: :attr:`im_self` is the class instance object,
      :attr:`im_func` is the function object; :attr:`im_class` is the class of
      :attr:`im_self` for bound methods or the class that asked for the method for
      unbound methods; :attr:`__doc__` is the method's documentation (same as
      ``im_func.__doc__``); :attr:`~definition.__name__` is the method name (same as
      ``im_func.__name__``); :attr:`__module__` is the name of the module the method
      was defined in, or ``None`` if unavailable.

      .. versionchanged:: 2.2
         :attr:`im_self` used to refer to the class that defined the method.

      .. versionchanged:: 2.6
         For Python 3 forward-compatibility, :attr:`im_func` is also available as
         :attr:`__func__`, and :attr:`im_self` as :attr:`__self__`.

      .. index::
         single: __doc__ (method attribute)
         single: __name__ (method attribute)
         single: __module__ (method attribute)
         single: im_func (method attribute)
         single: im_self (method attribute)

      Methods also support accessing (but not setting) the arbitrary function
      attributes on the underlying function object.

      User-defined method objects may be created when getting an attribute of a class
      (perhaps via an instance of that class), if that attribute is a user-defined
      function object, an unbound user-defined method object, or a class method
      object. When the attribute is a user-defined method object, a new method object
      is only created if the class from which it is being retrieved is the same as, or
      a derived class of, the class stored in the original method object; otherwise,
      the original method object is used as it is.

      .. index::
         single: im_class (method attribute)
         single: im_func (method attribute)
         single: im_self (method attribute)

      When a user-defined method object is created by retrieving a user-defined
      function object from a class, its :attr:`im_self` attribute is ``None``
      and the method object is said to be unbound. When one is created by
      retrieving a user-defined function object from a class via one of its
      instances, its :attr:`im_self` attribute is the instance, and the method
      object is said to be bound. In either case, the new method's
      :attr:`im_class` attribute is the class from which the retrieval takes
      place, and its :attr:`im_func` attribute is the original function object.

      .. index:: single: im_func (method attribute)

      When a user-defined method object is created by retrieving another method object
      from a class or instance, the behaviour is the same as for a function object,
      except that the :attr:`im_func` attribute of the new instance is not the
      original method object but its :attr:`im_func` attribute.

      .. index::
         single: im_class (method attribute)
         single: im_func (method attribute)
         single: im_self (method attribute)

      When a user-defined method object is created by retrieving a class method object
      from a class or instance, its :attr:`im_self` attribute is the class itself, and
      its :attr:`im_func` attribute is the function object underlying the class method.

      When an unbound user-defined method object is called, the underlying function
      (:attr:`im_func`) is called, with the restriction that the first argument must
      be an instance of the proper class (:attr:`im_class`) or of a derived class
      thereof.

      When a bound user-defined method object is called, the underlying function
      (:attr:`im_func`) is called, inserting the class instance (:attr:`im_self`) in
      front of the argument list.  For instance, when :class:`C` is a class which
      contains a definition for a function :meth:`f`, and ``x`` is an instance of
      :class:`C`, calling ``x.f(1)`` is equivalent to calling ``C.f(x, 1)``.

      When a user-defined method object is derived from a class method object, the
      "class instance" stored in :attr:`im_self` will actually be the class itself, so
      that calling either ``x.f(1)`` or ``C.f(1)`` is equivalent to calling ``f(C,1)``
      where ``f`` is the underlying function.

      Note that the transformation from function object to (unbound or bound) method
      object happens each time the attribute is retrieved from the class or instance.
      In some cases, a fruitful optimization is to assign the attribute to a local
      variable and call that local variable. Also notice that this transformation only
      happens for user-defined functions; other callable objects (and all non-callable
      objects) are retrieved without transformation.  It is also important to note
      that user-defined functions which are attributes of a class instance are not
      converted to bound methods; this *only* happens when the function is an
      attribute of the class.

   Generator functions
      .. index::
         single: generator; function
         single: generator; iterator

      A function or method which uses the :keyword:`yield` statement (see section
      :ref:`yield`) is called a :dfn:`generator
      function`.  Such a function, when called, always returns an iterator object
      which can be used to execute the body of the function:  calling the iterator's
      :meth:`~iterator.next` method will cause the function to execute until
      it provides a value
      using the :keyword:`yield` statement.  When the function executes a
      :keyword:`return` statement or falls off the end, a :exc:`StopIteration`
      exception is raised and the iterator will have reached the end of the set of
      values to be returned.

   Built-in functions
      .. index::
         object: built-in function
         object: function
         pair: C; language

      A built-in function object is a wrapper around a C function.  Examples of
      built-in functions are :func:`len` and :func:`math.sin` (:mod:`math` is a
      standard built-in module). The number and type of the arguments are
      determined by the C function. Special read-only attributes:
      :attr:`__doc__` is the function's documentation string, or ``None`` if
      unavailable; :attr:`~definition.__name__` is the function's name; :attr:`__self__` is
      set to ``None`` (but see the next item); :attr:`__module__` is the name of
      the module the function was defined in or ``None`` if unavailable.

   Built-in methods
      .. index::
         object: built-in method
         object: method
         pair: built-in; method

      This is really a different disguise of a built-in function, this time containing
      an object passed to the C function as an implicit extra argument.  An example of
      a built-in method is ``alist.append()``, assuming *alist* is a list object. In
      this case, the special read-only attribute :attr:`__self__` is set to the object
      denoted by *alist*.

   Class Types
      Class types, or "new-style classes," are callable.  These objects normally act
      as factories for new instances of themselves, but variations are possible for
      class types that override :meth:`__new__`.  The arguments of the call are passed
      to :meth:`__new__` and, in the typical case, to :meth:`__init__` to initialize
      the new instance.

   Classic Classes
      .. index::
         single: __init__() (object method)
         object: class
         object: class instance
         object: instance
         pair: class object; call

      Class objects are described below.  When a class object is called, a new class
      instance (also described below) is created and returned.  This implies a call to
      the class's :meth:`__init__` method if it has one.  Any arguments are passed on
      to the :meth:`__init__` method.  If there is no :meth:`__init__` method, the
      class must be called without arguments.

   Class instances
      Class instances are described below.  Class instances are callable only when the
      class has a :meth:`__call__` method; ``x(arguments)`` is a shorthand for
      ``x.__call__(arguments)``.

Modules
   .. index::
      statement: import
      object: module

   Modules are imported by the :keyword:`import` statement (see section
   :ref:`import`). A module object has a
   namespace implemented by a dictionary object (this is the dictionary referenced
   by the func_globals attribute of functions defined in the module).  Attribute
   references are translated to lookups in this dictionary, e.g., ``m.x`` is
   equivalent to ``m.__dict__["x"]``. A module object does not contain the code
   object used to initialize the module (since it isn't needed once the
   initialization is done).

   Attribute assignment updates the module's namespace dictionary, e.g., ``m.x =
   1`` is equivalent to ``m.__dict__["x"] = 1``.

   .. index:: single: __dict__ (module attribute)

   Special read-only attribute: :attr:`~object.__dict__` is the module's namespace as a
   dictionary object.

   .. impl-detail::

      Because of the way CPython clears module dictionaries, the module
      dictionary will be cleared when the module falls out of scope even if the
      dictionary still has live references.  To avoid this, copy the dictionary
      or keep the module around while using its dictionary directly.

   .. index::
      single: __name__ (module attribute)
      single: __doc__ (module attribute)
      single: __file__ (module attribute)
      pair: module; namespace

   Predefined (writable) attributes: :attr:`__name__` is the module's name;
   :attr:`__doc__` is the module's documentation string, or ``None`` if
   unavailable; :attr:`__file__` is the pathname of the file from which the module
   was loaded, if it was loaded from a file. The :attr:`__file__` attribute is not
   present for C modules that are statically linked into the interpreter; for
   extension modules loaded dynamically from a shared library, it is the pathname
   of the shared library file.

Classes
   Both class types (new-style classes) and class objects (old-style/classic
   classes) are typically created by class definitions (see section
   :ref:`class`).  A class has a namespace implemented by a dictionary object.
   Class attribute references are translated to lookups in this dictionary, e.g.,
   ``C.x`` is translated to ``C.__dict__["x"]`` (although for new-style classes
   in particular there are a number of hooks which allow for other means of
   locating attributes). When the attribute name is not found there, the
   attribute search continues in the base classes.  For old-style classes, the
   search is depth-first, left-to-right in the order of occurrence in the base
   class list. New-style classes use the more complex C3 method resolution
   order which behaves correctly even in the presence of 'diamond'
   inheritance structures where there are multiple inheritance paths
   leading back to a common ancestor. Additional details on the C3 MRO used by
   new-style classes can be found in the documentation accompanying the
   2.3 release at https://www.python.org/download/releases/2.3/mro/.

   .. XXX: Could we add that MRO doc as an appendix to the language ref?

   .. index::
      object: class
      object: class instance
      object: instance
      pair: class object; call
      single: container
      object: dictionary
      pair: class; attribute

   When a class attribute reference (for class :class:`C`, say) would yield a
   user-defined function object or an unbound user-defined method object whose
   associated class is either :class:`C` or one of its base classes, it is
   transformed into an unbound user-defined method object whose :attr:`im_class`
   attribute is :class:`C`. When it would yield a class method object, it is
   transformed into a bound user-defined method object whose
   :attr:`im_self` attribute is :class:`C`.  When it would yield a
   static method object, it is transformed into the object wrapped by the static
   method object. See section :ref:`descriptors` for another way in which
   attributes retrieved from a class may differ from those actually contained in
   its :attr:`~object.__dict__` (note that only new-style classes support descriptors).

   .. index:: triple: class; attribute; assignment

   Class attribute assignments update the class's dictionary, never the dictionary
   of a base class.

   .. index:: pair: class object; call

   A class object can be called (see above) to yield a class instance (see below).

   .. index::
      single: __name__ (class attribute)
      single: __module__ (class attribute)
      single: __dict__ (class attribute)
      single: __bases__ (class attribute)
      single: __doc__ (class attribute)

   Special attributes: :attr:`~definition.__name__` is the class name; :attr:`__module__` is
   the module name in which the class was defined; :attr:`~object.__dict__` is the
   dictionary containing the class's namespace; :attr:`~class.__bases__` is a
   tuple (possibly empty or a singleton) containing the base classes, in the
   order of their occurrence in the base class list; :attr:`__doc__` is the
   class's documentation string, or ``None`` if undefined.

Class instances
   .. index::
      object: class instance
      object: instance
      pair: class; instance
      pair: class instance; attribute

   A class instance is created by calling a class object (see above). A class
   instance has a namespace implemented as a dictionary which is the first place in
   which attribute references are searched.  When an attribute is not found there,
   and the instance's class has an attribute by that name, the search continues
   with the class attributes.  If a class attribute is found that is a user-defined
   function object or an unbound user-defined method object whose associated class
   is the class (call it :class:`C`) of the instance for which the attribute
   reference was initiated or one of its bases, it is transformed into a bound
   user-defined method object whose :attr:`im_class` attribute is :class:`C` and
   whose :attr:`im_self` attribute is the instance. Static method and class method
   objects are also transformed, as if they had been retrieved from class
   :class:`C`; see above under "Classes". See section :ref:`descriptors` for
   another way in which attributes of a class retrieved via its instances may
   differ from the objects actually stored in the class's :attr:`~object.__dict__`. If no
   class attribute is found, and the object's class has a :meth:`__getattr__`
   method, that is called to satisfy the lookup.

   .. index:: triple: class instance; attribute; assignment

   Attribute assignments and deletions update the instance's dictionary, never a
   class's dictionary.  If the class has a :meth:`__setattr__` or
   :meth:`__delattr__` method, this is called instead of updating the instance
   dictionary directly.

   .. index::
      object: numeric
      object: sequence
      object: mapping

   Class instances can pretend to be numbers, sequences, or mappings if they have
   methods with certain special names.  See section :ref:`specialnames`.

   .. index::
      single: __dict__ (instance attribute)
      single: __class__ (instance attribute)

   Special attributes: :attr:`~object.__dict__` is the attribute dictionary;
   :attr:`~instance.__class__` is the instance's class.

Files
   .. index::
      object: file
      builtin: open
      single: popen() (in module os)
      single: makefile() (socket method)
      single: sys.stdin
      single: sys.stdout
      single: sys.stderr
      single: stdio
      single: stdin (in module sys)
      single: stdout (in module sys)
      single: stderr (in module sys)

   A file object represents an open file.  File objects are created by the
   :func:`open` built-in function, and also by :func:`os.popen`,
   :func:`os.fdopen`, and the :meth:`makefile` method of socket objects (and
   perhaps by other functions or methods provided by extension modules).  The
   objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are initialized to
   file objects corresponding to the interpreter's standard input, output and
   error streams.  See :ref:`bltin-file-objects` for complete documentation of
   file objects.

Internal types
   .. index::
      single: internal type
      single: types, internal

   A few types used internally by the interpreter are exposed to the user. Their
   definitions may change with future versions of the interpreter, but they are
   mentioned here for completeness.

   .. index:: bytecode, object; code, code object

   Code objects
      Code objects represent *byte-compiled* executable Python code, or :term:`bytecode`.
      The difference between a code object and a function object is that the function
      object contains an explicit reference to the function's globals (the module in
      which it was defined), while a code object contains no context; also the default
      argument values are stored in the function object, not in the code object
      (because they represent values calculated at run-time).  Unlike function
      objects, code objects are immutable and contain no references (directly or
      indirectly) to mutable objects.

      .. index::
         single: co_argcount (code object attribute)
         single: co_code (code object attribute)
         single: co_consts (code object attribute)
         single: co_filename (code object attribute)
         single: co_firstlineno (code object attribute)
         single: co_flags (code object attribute)
         single: co_lnotab (code object attribute)
         single: co_name (code object attribute)
         single: co_names (code object attribute)
         single: co_nlocals (code object attribute)
         single: co_stacksize (code object attribute)
         single: co_varnames (code object attribute)
         single: co_cellvars (code object attribute)
         single: co_freevars (code object attribute)

      Special read-only attributes: :attr:`co_name` gives the function name;
      :attr:`co_argcount` is the number of positional arguments (including arguments
      with default values); :attr:`co_nlocals` is the number of local variables used
      by the function (including arguments); :attr:`co_varnames` is a tuple containing
      the names of the local variables (starting with the argument names);
      :attr:`co_cellvars` is a tuple containing the names of local variables that are
      referenced by nested functions; :attr:`co_freevars` is a tuple containing the
      names of free variables; :attr:`co_code` is a string representing the sequence
      of bytecode instructions; :attr:`co_consts` is a tuple containing the literals
      used by the bytecode; :attr:`co_names` is a tuple containing the names used by
      the bytecode; :attr:`co_filename` is the filename from which the code was
      compiled; :attr:`co_firstlineno` is the first line number of the function;
      :attr:`co_lnotab` is a string encoding the mapping from bytecode offsets to
      line numbers (for details see the source code of the interpreter);
      :attr:`co_stacksize` is the required stack size (including local variables);
      :attr:`co_flags` is an integer encoding a number of flags for the interpreter.

      .. index:: object: generator

      The following flag bits are defined for :attr:`co_flags`: bit ``0x04`` is set if
      the function uses the ``*arguments`` syntax to accept an arbitrary number of
      positional arguments; bit ``0x08`` is set if the function uses the
      ``**keywords`` syntax to accept arbitrary keyword arguments; bit ``0x20`` is set
      if the function is a generator.

      Future feature declarations (``from __future__ import division``) also use bits
      in :attr:`co_flags` to indicate whether a code object was compiled with a
      particular feature enabled: bit ``0x2000`` is set if the function was compiled
      with future division enabled; bits ``0x10`` and ``0x1000`` were used in earlier
      versions of Python.

      Other bits in :attr:`co_flags` are reserved for internal use.

      .. index:: single: documentation string

      If a code object represents a function, the first item in :attr:`co_consts` is
      the documentation string of the function, or ``None`` if undefined.

   .. _frame-objects:

   Frame objects
      .. index:: object: frame

      Frame objects represent execution frames.  They may occur in traceback objects
      (see below).

      .. index::
         single: f_back (frame attribute)
         single: f_code (frame attribute)
         single: f_globals (frame attribute)
         single: f_locals (frame attribute)
         single: f_lasti (frame attribute)
         single: f_builtins (frame attribute)
         single: f_restricted (frame attribute)

      Special read-only attributes: :attr:`f_back` is to the previous stack frame
      (towards the caller), or ``None`` if this is the bottom stack frame;
      :attr:`f_code` is the code object being executed in this frame; :attr:`f_locals`
      is the dictionary used to look up local variables; :attr:`f_globals` is used for
      global variables; :attr:`f_builtins` is used for built-in (intrinsic) names;
      :attr:`f_restricted` is a flag indicating whether the function is executing in
      restricted execution mode; :attr:`f_lasti` gives the precise instruction (this
      is an index into the bytecode string of the code object).

      .. index::
         single: f_trace (frame attribute)
         single: f_exc_type (frame attribute)
         single: f_exc_value (frame attribute)
         single: f_exc_traceback (frame attribute)
         single: f_lineno (frame attribute)

      Special writable attributes: :attr:`f_trace`, if not ``None``, is a function
      called at the start of each source code line (this is used by the debugger);
      :attr:`f_exc_type`, :attr:`f_exc_value`, :attr:`f_exc_traceback` represent the
      last exception raised in the parent frame provided another exception was ever
      raised in the current frame (in all other cases they are ``None``); :attr:`f_lineno`
      is the current line number of the frame --- writing to this from within a trace
      function jumps to the given line (only for the bottom-most frame).  A debugger
      can implement a Jump command (aka Set Next Statement) by writing to f_lineno.

   Traceback objects
      .. index::
         object: traceback
         pair: stack; trace
         pair: exception; handler
         pair: execution; stack
         single: exc_info (in module sys)
         single: exc_traceback (in module sys)
         single: last_traceback (in module sys)
         single: sys.exc_info
         single: sys.exc_traceback
         single: sys.last_traceback

      Traceback objects represent a stack trace of an exception.  A traceback object
      is created when an exception occurs.  When the search for an exception handler
      unwinds the execution stack, at each unwound level a traceback object is
      inserted in front of the current traceback.  When an exception handler is
      entered, the stack trace is made available to the program. (See section
      :ref:`try`.) It is accessible as ``sys.exc_traceback``,
      and also as the third item of the tuple returned by ``sys.exc_info()``.  The
      latter is the preferred interface, since it works correctly when the program is
      using multiple threads. When the program contains no suitable handler, the stack
      trace is written (nicely formatted) to the standard error stream; if the
      interpreter is interactive, it is also made available to the user as
      ``sys.last_traceback``.

      .. index::
         single: tb_next (traceback attribute)
         single: tb_frame (traceback attribute)
         single: tb_lineno (traceback attribute)
         single: tb_lasti (traceback attribute)
         statement: try

      Special read-only attributes: :attr:`tb_next` is the next level in the stack
      trace (towards the frame where the exception occurred), or ``None`` if there is
      no next level; :attr:`tb_frame` points to the execution frame of the current
      level; :attr:`tb_lineno` gives the line number where the exception occurred;
      :attr:`tb_lasti` indicates the precise instruction.  The line number and last
      instruction in the traceback may differ from the line number of its frame object
      if the exception occurred in a :keyword:`try` statement with no matching except
      clause or with a finally clause.

   Slice objects
      .. index:: builtin: slice

      Slice objects are used to represent slices when *extended slice syntax* is used.
      This is a slice using two colons, or multiple slices or ellipses separated by
      commas, e.g., ``a[i:j:step]``, ``a[i:j, k:l]``, or ``a[..., i:j]``.  They are
      also created by the built-in :func:`slice` function.

      .. index::
         single: start (slice object attribute)
         single: stop (slice object attribute)
         single: step (slice object attribute)

      Special read-only attributes: :attr:`~slice.start` is the lower bound;
      :attr:`~slice.stop` is the upper bound; :attr:`~slice.step` is the step
      value; each is ``None`` if omitted.  These attributes can have any type.

      Slice objects support one method:


      .. method:: slice.indices(self, length)

         This method takes a single integer argument *length* and computes information
         about the extended slice that the slice object would describe if applied to a
         sequence of *length* items.  It returns a tuple of three integers; respectively
         these are the *start* and *stop* indices and the *step* or stride length of the
         slice. Missing or out-of-bounds indices are handled in a manner consistent with
         regular slices.

         .. versionadded:: 2.3

   Static method objects
      Static method objects provide a way of defeating the transformation of function
      objects to method objects described above. A static method object is a wrapper
      around any other object, usually a user-defined method object. When a static
      method object is retrieved from a class or a class instance, the object actually
      returned is the wrapped object, which is not subject to any further
      transformation. Static method objects are not themselves callable, although the
      objects they wrap usually are. Static method objects are created by the built-in
      :func:`staticmethod` constructor.

   Class method objects
      A class method object, like a static method object, is a wrapper around another
      object that alters the way in which that object is retrieved from classes and
      class instances. The behaviour of class method objects upon such retrieval is
      described above, under "User-defined methods". Class method objects are created
      by the built-in :func:`classmethod` constructor.


.. _newstyle:

New-style and classic classes
=============================

Classes and instances come in two flavors: old-style (or classic) and new-style.

Up to Python 2.1 the concept of ``class`` was unrelated to the concept of
``type``, and old-style classes were the only flavor available.  For an
old-style class, the statement ``x.__class__`` provides the class of *x*, but
``type(x)`` is always ``<type 'instance'>``.  This reflects the fact that all
old-style instances, independent of their class, are implemented with a single
built-in type, called ``instance``.

New-style classes were introduced in Python 2.2 to unify the concepts of
``class`` and ``type``.  A new-style class is simply a user-defined type,
no more, no less.  If *x* is an instance of a new-style class, then ``type(x)``
is typically the same as ``x.__class__`` (although this is not guaranteed -- a
new-style class instance is permitted to override the value returned for
``x.__class__``).

The major motivation for introducing new-style classes is to provide a unified
object model with a full meta-model.  It also has a number of practical
benefits, like the ability to subclass most built-in types, or the introduction
of "descriptors", which enable computed properties.

For compatibility reasons, classes are still old-style by default.  New-style
classes are created by specifying another new-style class (i.e. a type) as a
parent class, or the "top-level type" :class:`object` if no other parent is
needed.  The behaviour of new-style classes differs from that of old-style
classes in a number of important details in addition to what :func:`type`
returns.  Some of these changes are fundamental to the new object model, like
the way special methods are invoked.  Others are "fixes" that could not be
implemented before for compatibility concerns, like the method resolution order
in case of multiple inheritance.

While this manual aims to provide comprehensive coverage of Python's class
mechanics, it may still be lacking in some areas when it comes to its coverage
of new-style classes. Please see https://www.python.org/doc/newstyle/ for
sources of additional information.

.. index::
   single: class; new-style
   single: class; classic
   single: class; old-style

Old-style classes are removed in Python 3, leaving only new-style classes.


.. _specialnames:

Special method names
====================

.. index::
   pair: operator; overloading
   single: __getitem__() (mapping object method)

A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python's approach to :dfn:`operator overloading`,
allowing classes to define their own behavior with respect to language
operators.  For instance, if a class defines a method named :meth:`__getitem__`,
and ``x`` is an instance of this class, then ``x[i]`` is roughly equivalent
to ``x.__getitem__(i)`` for old-style classes and ``type(x).__getitem__(x, i)``
for new-style classes.  Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
:exc:`AttributeError` or :exc:`TypeError`).

When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.  (One example
of this is the :class:`~xml.dom.NodeList` interface in the W3C's Document
Object Model.)


.. _customization:

Basic customization
-------------------

.. method:: object.__new__(cls[, ...])

   .. index:: pair: subclassing; immutable types

   Called to create a new instance of class *cls*.  :meth:`__new__` is a static
   method (special-cased so you need not declare it as such) that takes the class
   of which an instance was requested as its first argument.  The remaining
   arguments are those passed to the object constructor expression (the call to the
   class).  The return value of :meth:`__new__` should be the new object instance
   (usually an instance of *cls*).

   Typical implementations create a new instance of the class by invoking the
   superclass's :meth:`__new__` method using ``super(currentclass,
   cls).__new__(cls[, ...])`` with appropriate arguments and then modifying the
   newly-created instance as necessary before returning it.

   If :meth:`__new__` returns an instance of *cls*, then the new instance's
   :meth:`__init__` method will be invoked like ``__init__(self[, ...])``, where
   *self* is the new instance and the remaining arguments are the same as were
   passed to :meth:`__new__`.

   If :meth:`__new__` does not return an instance of *cls*, then the new instance's
   :meth:`__init__` method will not be invoked.

   :meth:`__new__` is intended mainly to allow subclasses of immutable types (like
   int, str, or tuple) to customize instance creation.  It is also commonly
   overridden in custom metaclasses in order to customize class creation.


.. method:: object.__init__(self[, ...])

   .. index:: pair: class; constructor

   Called after the instance has been created (by :meth:`__new__`), but before
   it is returned to the caller.  The arguments are those passed to the
   class constructor expression.  If a base class has an :meth:`__init__` method,
   the derived class's :meth:`__init__` method, if any, must explicitly call it to
   ensure proper initialization of the base class part of the instance; for
   example: ``BaseClass.__init__(self, [args...])``.

   Because :meth:`__new__` and :meth:`__init__` work together in constructing
   objects (:meth:`__new__` to create it, and :meth:`__init__` to customise it),
   no non-``None`` value may be returned by :meth:`__init__`; doing so will
   cause a :exc:`TypeError` to be raised at runtime.


.. method:: object.__del__(self)

   .. index::
      single: destructor
      statement: del

   Called when the instance is about to be destroyed.  This is also called a
   destructor.  If a base class has a :meth:`__del__` method, the derived class's
   :meth:`__del__` method, if any, must explicitly call it to ensure proper
   deletion of the base class part of the instance.  Note that it is possible
   (though not recommended!) for the :meth:`__del__` method to postpone destruction
   of the instance by creating a new reference to it.  It may then be called at a
   later time when this new reference is deleted.  It is not guaranteed that
   :meth:`__del__` methods are called for objects that still exist when the
   interpreter exits.

   .. note::

      ``del x`` doesn't directly call ``x.__del__()`` --- the former decrements
      the reference count for ``x`` by one, and the latter is only called when
      ``x``'s reference count reaches zero.  Some common situations that may
      prevent the reference count of an object from going to zero include:
      circular references between objects (e.g., a doubly-linked list or a tree
      data structure with parent and child pointers); a reference to the object
      on the stack frame of a function that caught an exception (the traceback
      stored in ``sys.exc_traceback`` keeps the stack frame alive); or a
      reference to the object on the stack frame that raised an unhandled
      exception in interactive mode (the traceback stored in
      ``sys.last_traceback`` keeps the stack frame alive).  The first situation
      can only be remedied by explicitly breaking the cycles; the latter two
      situations can be resolved by storing ``None`` in ``sys.exc_traceback`` or
      ``sys.last_traceback``.  Circular references which are garbage are
      detected when the option cycle detector is enabled (it's on by default),
      but can only be cleaned up if there are no Python-level :meth:`__del__`
      methods involved. Refer to the documentation for the :mod:`gc` module for
      more information about how :meth:`__del__` methods are handled by the
      cycle detector, particularly the description of the ``garbage`` value.

   .. warning::

      Due to the precarious circumstances under which :meth:`__del__` methods are
      invoked, exceptions that occur during their execution are ignored, and a warning
      is printed to ``sys.stderr`` instead.  Also, when :meth:`__del__` is invoked in
      response to a module being deleted (e.g., when execution of the program is
      done), other globals referenced by the :meth:`__del__` method may already have
      been deleted or in the process of being torn down (e.g. the import
      machinery shutting down).  For this reason, :meth:`__del__` methods
      should do the absolute
      minimum needed to maintain external invariants.  Starting with version 1.5,
      Python guarantees that globals whose name begins with a single underscore are
      deleted from their module before other globals are deleted; if no other
      references to such globals exist, this may help in assuring that imported
      modules are still available at the time when the :meth:`__del__` method is
      called.

   See also the :option:`-R` command-line option.


.. method:: object.__repr__(self)

   .. index:: builtin: repr

   Called by the :func:`repr` built-in function and by string conversions (reverse
   quotes) to compute the "official" string representation of an object.  If at all
   possible, this should look like a valid Python expression that could be used to
   recreate an object with the same value (given an appropriate environment).  If
   this is not possible, a string of the form ``<...some useful description...>``
   should be returned.  The return value must be a string object. If a class
   defines :meth:`__repr__` but not :meth:`__str__`, then :meth:`__repr__` is also
   used when an "informal" string representation of instances of that class is
   required.

   .. index::
      pair: string; conversion
      pair: reverse; quotes
      pair: backward; quotes
      single: back-quotes

   This is typically used for debugging, so it is important that the representation
   is information-rich and unambiguous.


.. method:: object.__str__(self)

   .. index::
      builtin: str
      statement: print

   Called by the :func:`str` built-in function and by the :keyword:`print`
   statement to compute the "informal" string representation of an object.  This
   differs from :meth:`__repr__` in that it does not have to be a valid Python
   expression: a more convenient or concise representation may be used instead.
   The return value must be a string object.


.. method:: object.__lt__(self, other)
            object.__le__(self, other)
            object.__eq__(self, other)
            object.__ne__(self, other)
            object.__gt__(self, other)
            object.__ge__(self, other)

   .. versionadded:: 2.1

   .. index::
      single: comparisons

   These are the so-called "rich comparison" methods, and are called for comparison
   operators in preference to :meth:`__cmp__` below. The correspondence between
   operator symbols and method names is as follows: ``x<y`` calls ``x.__lt__(y)``,
   ``x<=y`` calls ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` and
   ``x<>y`` call ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls
   ``x.__ge__(y)``.

   A rich comparison method may return the singleton ``NotImplemented`` if it does
   not implement the operation for a given pair of arguments. By convention,
   ``False`` and ``True`` are returned for a successful comparison. However, these
   methods can return any value, so if the comparison operator is used in a Boolean
   context (e.g., in the condition of an ``if`` statement), Python will call
   :func:`bool` on the value to determine if the result is true or false.

   There are no implied relationships among the comparison operators. The truth
   of ``x==y`` does not imply that ``x!=y`` is false.  Accordingly, when
   defining :meth:`__eq__`, one should also define :meth:`__ne__` so that the
   operators will behave as expected.  See the paragraph on :meth:`__hash__` for
   some important notes on creating :term:`hashable` objects which support
   custom comparison operations and are usable as dictionary keys.

   There are no swapped-argument versions of these methods (to be used when the
   left argument does not support the operation but the right argument does);
   rather, :meth:`__lt__` and :meth:`__gt__` are each other's reflection,
   :meth:`__le__` and :meth:`__ge__` are each other's reflection, and
   :meth:`__eq__` and :meth:`__ne__` are their own reflection.

   Arguments to rich comparison methods are never coerced.

   To automatically generate ordering operations from a single root operation,
   see :func:`functools.total_ordering`.

.. method:: object.__cmp__(self, other)

   .. index::
      builtin: cmp
      single: comparisons

   Called by comparison operations if rich comparison (see above) is not
   defined.  Should return a negative integer if ``self < other``, zero if
   ``self == other``, a positive integer if ``self > other``.  If no
   :meth:`__cmp__`, :meth:`__eq__` or :meth:`__ne__` operation is defined, class
   instances are compared by object identity ("address").  See also the
   description of :meth:`__hash__` for some important notes on creating
   :term:`hashable` objects which support custom comparison operations and are
   usable as dictionary keys. (Note: the restriction that exceptions are not
   propagated by :meth:`__cmp__` has been removed since Python 1.5.)


.. method:: object.__rcmp__(self, other)

   .. versionchanged:: 2.1
      No longer supported.


.. method:: object.__hash__(self)

   .. index::
      object: dictionary
      builtin: hash

   Called by built-in function :func:`hash` and for operations on members of
   hashed collections including :class:`set`, :class:`frozenset`, and
   :class:`dict`.  :meth:`__hash__` should return an integer.  The only required
   property is that objects which compare equal have the same hash value; it is
   advised to mix together the hash values of the components of the object that
   also play a part in comparison of objects by packing them into a tuple and
   hashing the tuple. Example::

       def __hash__(self):
           return hash((self.name, self.nick, self.color))

   If a class does not define a :meth:`__cmp__` or :meth:`__eq__` method it
   should not define a :meth:`__hash__` operation either; if it defines
   :meth:`__cmp__` or :meth:`__eq__` but not :meth:`__hash__`, its instances
   will not be usable in hashed collections.  If a class defines mutable objects
   and implements a :meth:`__cmp__` or :meth:`__eq__` method, it should not
   implement :meth:`__hash__`, since hashable collection implementations require
   that an object's hash value is immutable (if the object's hash value changes,
   it will be in the wrong hash bucket).

   User-defined classes have :meth:`__cmp__` and :meth:`__hash__` methods
   by default; with them, all objects compare unequal (except with themselves)
   and ``x.__hash__()`` returns a result derived from ``id(x)``.

   Classes which inherit a :meth:`__hash__` method from a parent class but
   change the meaning of :meth:`__cmp__` or :meth:`__eq__` such that the hash
   value returned is no longer appropriate (e.g. by switching to a value-based
   concept of equality instead of the default identity based equality) can
   explicitly flag themselves as being unhashable by setting ``__hash__ = None``
   in the class definition. Doing so means that not only will instances of the
   class raise an appropriate :exc:`TypeError` when a program attempts to
   retrieve their hash value, but they will also be correctly identified as
   unhashable when checking ``isinstance(obj, collections.Hashable)`` (unlike
   classes which define their own :meth:`__hash__` to explicitly raise
   :exc:`TypeError`).

   .. versionchanged:: 2.5
      :meth:`__hash__` may now also return a long integer object; the 32-bit
      integer is then derived from the hash of that object.

   .. versionchanged:: 2.6
      :attr:`__hash__` may now be set to :const:`None` to explicitly flag
      instances of a class as unhashable.


.. method:: object.__nonzero__(self)

   .. index:: single: __len__() (mapping object method)

   Called to implement truth value testing and the built-in operation ``bool()``;
   should return ``False`` or ``True``, or their integer equivalents ``0`` or
   ``1``.  When this method is not defined, :meth:`__len__` is called, if it is
   defined, and the object is considered true if its result is nonzero.
   If a class defines neither :meth:`__len__` nor :meth:`__nonzero__`, all its
   instances are considered true.


.. method:: object.__unicode__(self)

   .. index:: builtin: unicode

   Called to implement :func:`unicode` built-in; should return a Unicode object.
   When this method is not defined, string conversion is attempted, and the result
   of string conversion is converted to Unicode using the system default encoding.


.. _attribute-access:

Customizing attribute access
----------------------------

The following methods can be defined to customize the meaning of attribute
access (use of, assignment to, or deletion of ``x.name``) for class instances.


.. method:: object.__getattr__(self, name)

   Called when an attribute lookup has not found the attribute in the usual places
   (i.e. it is not an instance attribute nor is it found in the class tree for
   ``self``).  ``name`` is the attribute name. This method should return the
   (computed) attribute value or raise an :exc:`AttributeError` exception.

   .. index:: single: __setattr__() (object method)

   Note that if the attribute is found through the normal mechanism,
   :meth:`__getattr__` is not called.  (This is an intentional asymmetry between
   :meth:`__getattr__` and :meth:`__setattr__`.) This is done both for efficiency
   reasons and because otherwise :meth:`__getattr__` would have no way to access
   other attributes of the instance.  Note that at least for instance variables,
   you can fake total control by not inserting any values in the instance attribute
   dictionary (but instead inserting them in another object).  See the
   :meth:`__getattribute__` method below for a way to actually get total control in
   new-style classes.


.. method:: object.__setattr__(self, name, value)

   Called when an attribute assignment is attempted.  This is called instead of the
   normal mechanism (i.e. store the value in the instance dictionary).  *name* is
   the attribute name, *value* is the value to be assigned to it.

   .. index:: single: __dict__ (instance attribute)

   If :meth:`__setattr__` wants to assign to an instance attribute, it should not
   simply execute ``self.name = value`` --- this would cause a recursive call to
   itself.  Instead, it should insert the value in the dictionary of instance
   attributes, e.g., ``self.__dict__[name] = value``.  For new-style classes,
   rather than accessing the instance dictionary, it should call the base class
   method with the same name, for example, ``object.__setattr__(self, name,
   value)``.


.. method:: object.__delattr__(self, name)

   Like :meth:`__setattr__` but for attribute deletion instead of assignment.  This
   should only be implemented if ``del obj.name`` is meaningful for the object.


.. _new-style-attribute-access:

More attribute access for new-style classes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The following methods only apply to new-style classes.


.. method:: object.__getattribute__(self, name)

   Called unconditionally to implement attribute accesses for instances of the
   class. If the class also defines :meth:`__getattr__`, the latter will not be
   called unless :meth:`__getattribute__` either calls it explicitly or raises an
   :exc:`AttributeError`. This method should return the (computed) attribute value
   or raise an :exc:`AttributeError` exception. In order to avoid infinite
   recursion in this method, its implementation should always call the base class
   method with the same name to access any attributes it needs, for example,
   ``object.__getattribute__(self, name)``.

   .. note::

      This method may still be bypassed when looking up special methods as the
      result of implicit invocation via language syntax or built-in functions.
      See :ref:`new-style-special-lookup`.


.. _descriptors:

Implementing Descriptors
^^^^^^^^^^^^^^^^^^^^^^^^

The following methods only apply when an instance of the class containing the
method (a so-called *descriptor* class) appears in an *owner* class (the
descriptor must be in either the owner's class dictionary or in the class
dictionary for one of its parents).  In the examples below, "the attribute"
refers to the attribute whose name is the key of the property in the owner
class' :attr:`~object.__dict__`.


.. method:: object.__get__(self, instance, owner)

   Called to get the attribute of the owner class (class attribute access) or of an
   instance of that class (instance attribute access). *owner* is always the owner
   class, while *instance* is the instance that the attribute was accessed through,
   or ``None`` when the attribute is accessed through the *owner*.  This method
   should return the (computed) attribute value or raise an :exc:`AttributeError`
   exception.


.. method:: object.__set__(self, instance, value)

   Called to set the attribute on an instance *instance* of the owner class to a
   new value, *value*.


.. method:: object.__delete__(self, instance)

   Called to delete the attribute on an instance *instance* of the owner class.


.. _descriptor-invocation:

Invoking Descriptors
^^^^^^^^^^^^^^^^^^^^

In general, a descriptor is an object attribute with "binding behavior", one
whose attribute access has been overridden by methods in the descriptor
protocol:  :meth:`__get__`, :meth:`__set__`, and :meth:`__delete__`. If any of
those methods are defined for an object, it is said to be a descriptor.

The default behavior for attribute access is to get, set, or delete the
attribute from an object's dictionary. For instance, ``a.x`` has a lookup chain
starting with ``a.__dict__['x']``, then ``type(a).__dict__['x']``, and
continuing through the base classes of ``type(a)`` excluding metaclasses.

However, if the looked-up value is an object defining one of the descriptor
methods, then Python may override the default behavior and invoke the descriptor
method instead.  Where this occurs in the precedence chain depends on which
descriptor methods were defined and how they were called.  Note that descriptors
are only invoked for new style objects or classes (ones that subclass
:class:`object()` or :class:`type()`).

The starting point for descriptor invocation is a binding, ``a.x``. How the
arguments are assembled depends on ``a``:

Direct Call
   The simplest and least common call is when user code directly invokes a
   descriptor method:    ``x.__get__(a)``.

Instance Binding
   If binding to a new-style object instance, ``a.x`` is transformed into the call:
   ``type(a).__dict__['x'].__get__(a, type(a))``.

Class Binding
   If binding to a new-style class, ``A.x`` is transformed into the call:
   ``A.__dict__['x'].__get__(None, A)``.

Super Binding
   If ``a`` is an instance of :class:`super`, then the binding ``super(B,
   obj).m()`` searches ``obj.__class__.__mro__`` for the base class ``A``
   immediately preceding ``B`` and then invokes the descriptor with the call:
   ``A.__dict__['m'].__get__(obj, obj.__class__)``.

For instance bindings, the precedence of descriptor invocation depends on the
which descriptor methods are defined.  A descriptor can define any combination
of :meth:`__get__`, :meth:`__set__` and :meth:`__delete__`.  If it does not
define :meth:`__get__`, then accessing the attribute will return the descriptor
object itself unless there is a value in the object's instance dictionary.  If
the descriptor defines :meth:`__set__` and/or :meth:`__delete__`, it is a data
descriptor; if it defines neither, it is a non-data descriptor.  Normally, data
descriptors define both :meth:`__get__` and :meth:`__set__`, while non-data
descriptors have just the :meth:`__get__` method.  Data descriptors with
:meth:`__set__` and :meth:`__get__` defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be overridden by
instances.

Python methods (including :func:`staticmethod` and :func:`classmethod`) are
implemented as non-data descriptors.  Accordingly, instances can redefine and
override methods.  This allows individual instances to acquire behaviors that
differ from other instances of the same class.

The :func:`property` function is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.


.. _slots:

__slots__
^^^^^^^^^

By default, instances of both old and new-style classes have a dictionary for
attribute storage.  This wastes space for objects having very few instance
variables.  The space consumption can become acute when creating large numbers
of instances.

The default can be overridden by defining *__slots__* in a new-style class
definition.  The *__slots__* declaration takes a sequence of instance variables
and reserves just enough space in each instance to hold a value for each
variable.  Space is saved because *__dict__* is not created for each instance.


.. data:: __slots__

   This class variable can be assigned a string, iterable, or sequence of strings
   with variable names used by instances.  If defined in a new-style class,
   *__slots__* reserves space for the declared variables and prevents the automatic
   creation of *__dict__* and *__weakref__* for each instance.

   .. versionadded:: 2.2

Notes on using *__slots__*

* When inheriting from a class without *__slots__*, the *__dict__* attribute of
  that class will always be accessible, so a *__slots__* definition in the
  subclass is meaningless.

* Without a *__dict__* variable, instances cannot be assigned new variables not
  listed in the *__slots__* definition.  Attempts to assign to an unlisted
  variable name raises :exc:`AttributeError`. If dynamic assignment of new
  variables is desired, then add ``'__dict__'`` to the sequence of strings in the
  *__slots__* declaration.

  .. versionchanged:: 2.3
     Previously, adding ``'__dict__'`` to the *__slots__* declaration would not
     enable the assignment of new attributes not specifically listed in the sequence
     of instance variable names.

* Without a *__weakref__* variable for each instance, classes defining
  *__slots__* do not support weak references to its instances. If weak reference
  support is needed, then add ``'__weakref__'`` to the sequence of strings in the
  *__slots__* declaration.

  .. versionchanged:: 2.3
     Previously, adding ``'__weakref__'`` to the *__slots__* declaration would not
     enable support for weak references.

* *__slots__* are implemented at the class level by creating descriptors
  (:ref:`descriptors`) for each variable name.  As a result, class attributes
  cannot be used to set default values for instance variables defined by
  *__slots__*; otherwise, the class attribute would overwrite the descriptor
  assignment.

* The action of a *__slots__* declaration is limited to the class where it is
  defined.  As a result, subclasses will have a *__dict__* unless they also define
  *__slots__* (which must only contain names of any *additional* slots).

* If a class defines a slot also defined in a base class, the instance variable
  defined by the base class slot is inaccessible (except by retrieving its
  descriptor directly from the base class). This renders the meaning of the
  program undefined.  In the future, a check may be added to prevent this.

* Nonempty *__slots__* does not work for classes derived from "variable-length"
  built-in types such as :class:`long`, :class:`str` and :class:`tuple`.

* Any non-string iterable may be assigned to *__slots__*. Mappings may also be
  used; however, in the future, special meaning may be assigned to the values
  corresponding to each key.

* *__class__* assignment works only if both classes have the same *__slots__*.

  .. versionchanged:: 2.6
     Previously, *__class__* assignment raised an error if either new or old class
     had *__slots__*.


.. _metaclasses:

Customizing class creation
--------------------------

By default, new-style classes are constructed using :func:`type`. A class
definition is read into a separate namespace and the value of class name is
bound to the result of ``type(name, bases, dict)``.

When the class definition is read, if *__metaclass__* is defined then the
callable assigned to it will be called instead of :func:`type`. This allows
classes or functions to be written which monitor or alter the class creation
process:

* Modifying the class dictionary prior to the class being created.

* Returning an instance of another class -- essentially performing the role of a
  factory function.

These steps will have to be performed in the metaclass's :meth:`__new__` method
-- :meth:`type.__new__` can then be called from this method to create a class
with different properties.  This example adds a new element to the class
dictionary before creating the class::

  class metacls(type):
      def __new__(mcs, name, bases, dict):
          dict['foo'] = 'metacls was here'
          return type.__new__(mcs, name, bases, dict)

You can of course also override other class methods (or add new methods); for
example defining a custom :meth:`__call__` method in the metaclass allows custom
behavior when the class is called, e.g. not always creating a new instance.


.. data:: __metaclass__

   This variable can be any callable accepting arguments for ``name``, ``bases``,
   and ``dict``.  Upon class creation, the callable is used instead of the built-in
   :func:`type`.

   .. versionadded:: 2.2

The appropriate metaclass is determined by the following precedence rules:

* If ``dict['__metaclass__']`` exists, it is used.

* Otherwise, if there is at least one base class, its metaclass is used (this
  looks for a *__class__* attribute first and if not found, uses its type).

* Otherwise, if a global variable named __metaclass__ exists, it is used.

* Otherwise, the old-style, classic metaclass (types.ClassType) is used.

The potential uses for metaclasses are boundless. Some ideas that have been
explored including logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.


Customizing instance and subclass checks
----------------------------------------

.. versionadded:: 2.6

The following methods are used to override the default behavior of the
:func:`isinstance` and :func:`issubclass` built-in functions.

In particular, the metaclass :class:`abc.ABCMeta` implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as "virtual base
classes" to any class or type (including built-in types), including other
ABCs.

.. method:: class.__instancecheck__(self, instance)

   Return true if *instance* should be considered a (direct or indirect)
   instance of *class*. If defined, called to implement ``isinstance(instance,
   class)``.


.. method:: class.__subclasscheck__(self, subclass)

   Return true if *subclass* should be considered a (direct or indirect)
   subclass of *class*.  If defined, called to implement ``issubclass(subclass,
   class)``.


Note that these methods are looked up on the type (metaclass) of a class.  They
cannot be defined as class methods in the actual class.  This is consistent with
the lookup of special methods that are called on instances, only in this
case the instance is itself a class.

.. seealso::

   :pep:`3119` - Introducing Abstract Base Classes
      Includes the specification for customizing :func:`isinstance` and
      :func:`issubclass` behavior through :meth:`~class.__instancecheck__` and
      :meth:`~class.__subclasscheck__`, with motivation for this functionality
      in the context of adding Abstract Base Classes (see the :mod:`abc`
      module) to the language.


.. _callable-types:

Emulating callable objects
--------------------------


.. method:: object.__call__(self[, args...])

   .. index:: pair: call; instance

   Called when the instance is "called" as a function; if this method is defined,
   ``x(arg1, arg2, ...)`` is a shorthand for ``x.__call__(arg1, arg2, ...)``.


.. _sequence-types:

Emulating container types
-------------------------

The following methods can be defined to implement container objects.  Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well.  The first set of methods is used
either to emulate a sequence or to emulate a mapping; the difference is that for
a sequence, the allowable keys should be the integers *k* for which ``0 <= k <
N`` where *N* is the length of the sequence, or slice objects, which define a
range of items. (For backwards compatibility, the method :meth:`__getslice__`
(see below) can also be defined to handle simple, but not extended slices.) It
is also recommended that mappings provide the methods :meth:`keys`,
:meth:`values`, :meth:`items`, :meth:`has_key`, :meth:`get`, :meth:`clear`,
:meth:`setdefault`, :meth:`iterkeys`, :meth:`itervalues`, :meth:`iteritems`,
:meth:`pop`, :meth:`popitem`, :meth:`!copy`, and :meth:`update` behaving similar
to those for Python's standard dictionary objects.  The :mod:`UserDict` module
provides a :class:`DictMixin` class to help create those methods from a base set
of :meth:`__getitem__`, :meth:`__setitem__`, :meth:`__delitem__`, and
:meth:`keys`. Mutable sequences should provide methods :meth:`append`,
:meth:`count`, :meth:`index`, :meth:`extend`, :meth:`insert`, :meth:`pop`,
:meth:`remove`, :meth:`reverse` and :meth:`sort`, like Python standard list
objects.  Finally, sequence types should implement addition (meaning
concatenation) and multiplication (meaning repetition) by defining the methods
:meth:`__add__`, :meth:`__radd__`, :meth:`__iadd__`, :meth:`__mul__`,
:meth:`__rmul__` and :meth:`__imul__` described below; they should not define
:meth:`__coerce__` or other numerical operators.  It is recommended that both
mappings and sequences implement the :meth:`__contains__` method to allow
efficient use of the ``in`` operator; for mappings, ``in`` should be equivalent
of :meth:`has_key`; for sequences, it should search through the values.  It is
further recommended that both mappings and sequences implement the
:meth:`__iter__` method to allow efficient iteration through the container; for
mappings, :meth:`__iter__` should be the same as :meth:`iterkeys`; for
sequences, it should iterate through the values.


.. method:: object.__len__(self)

   .. index::
      builtin: len
      single: __nonzero__() (object method)

   Called to implement the built-in function :func:`len`.  Should return the length
   of the object, an integer ``>=`` 0.  Also, an object that doesn't define a
   :meth:`__nonzero__` method and whose :meth:`__len__` method returns zero is
   considered to be false in a Boolean context.

   .. impl-detail::

      In CPython, the length is required to be at most :attr:`sys.maxsize`.
      If the length is larger than :attr:`!sys.maxsize` some features (such as
      :func:`len`) may raise :exc:`OverflowError`.  To prevent raising
      :exc:`!OverflowError` by truth value testing, an object must define a
      :meth:`__nonzero__` method.


.. method:: object.__getitem__(self, key)

   .. index:: object: slice

   Called to implement evaluation of ``self[key]``. For sequence types, the
   accepted keys should be integers and slice objects.  Note that the special
   interpretation of negative indexes (if the class wishes to emulate a sequence
   type) is up to the :meth:`__getitem__` method. If *key* is of an inappropriate
   type, :exc:`TypeError` may be raised; if of a value outside the set of indexes
   for the sequence (after any special interpretation of negative values),
   :exc:`IndexError` should be raised. For mapping types, if *key* is missing (not
   in the container), :exc:`KeyError` should be raised.

   .. note::

      :keyword:`for` loops expect that an :exc:`IndexError` will be raised for illegal
      indexes to allow proper detection of the end of the sequence.


.. method:: object.__setitem__(self, key, value)

   Called to implement assignment to ``self[key]``.  Same note as for
   :meth:`__getitem__`.  This should only be implemented for mappings if the
   objects support changes to the values for keys, or if new keys can be added, or
   for sequences if elements can be replaced.  The same exceptions should be raised
   for improper *key* values as for the :meth:`__getitem__` method.


.. method:: object.__delitem__(self, key)

   Called to implement deletion of ``self[key]``.  Same note as for
   :meth:`__getitem__`.  This should only be implemented for mappings if the
   objects support removal of keys, or for sequences if elements can be removed
   from the sequence.  The same exceptions should be raised for improper *key*
   values as for the :meth:`__getitem__` method.


.. method:: object.__missing__(self, key)

   Called by :class:`dict`\ .\ :meth:`__getitem__` to implement ``self[key]`` for dict subclasses
   when key is not in the dictionary.


.. method:: object.__iter__(self)

   This method is called when an iterator is required for a container. This method
   should return a new iterator object that can iterate over all the objects in the
   container.  For mappings, it should iterate over the keys of the container, and
   should also be made available as the method :meth:`iterkeys`.

   Iterator objects also need to implement this method; they are required to return
   themselves.  For more information on iterator objects, see :ref:`typeiter`.


.. method:: object.__reversed__(self)

   Called (if present) by the :func:`reversed` built-in to implement
   reverse iteration.  It should return a new iterator object that iterates
   over all the objects in the container in reverse order.

   If the :meth:`__reversed__` method is not provided, the :func:`reversed`
   built-in will fall back to using the sequence protocol (:meth:`__len__` and
   :meth:`__getitem__`).  Objects that support the sequence protocol should
   only provide :meth:`__reversed__` if they can provide an implementation
   that is more efficient than the one provided by :func:`reversed`.

   .. versionadded:: 2.6


The membership test operators (:keyword:`in` and :keyword:`not in`) are normally
implemented as an iteration through a sequence.  However, container objects can
supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.

.. method:: object.__contains__(self, item)

   Called to implement membership test operators.  Should return true if *item*
   is in *self*, false otherwise.  For mapping objects, this should consider the
   keys of the mapping rather than the values or the key-item pairs.

   For objects that don't define :meth:`__contains__`, the membership test first
   tries iteration via :meth:`__iter__`, then the old sequence iteration
   protocol via :meth:`__getitem__`, see :ref:`this section in the language
   reference <membership-test-details>`.


.. _sequence-methods:

Additional methods for emulation of sequence types
--------------------------------------------------

The following optional methods can be defined to further emulate sequence
objects.  Immutable sequences methods should at most only define
:meth:`__getslice__`; mutable sequences might define all three methods.


.. method:: object.__getslice__(self, i, j)

   .. deprecated:: 2.0
      Support slice objects as parameters to the :meth:`__getitem__` method.
      (However, built-in types in CPython currently still implement
      :meth:`__getslice__`.  Therefore, you have to override it in derived
      classes when implementing slicing.)

   Called to implement evaluation of ``self[i:j]``. The returned object should
   be of the same type as *self*.  Note that missing *i* or *j* in the slice
   expression are replaced by zero or :attr:`sys.maxsize`, respectively.  If
   negative indexes are used in the slice, the length of the sequence is added
   to that index. If the instance does not implement the :meth:`__len__` method,
   an :exc:`AttributeError` is raised. No guarantee is made that indexes
   adjusted this way are not still negative.  Indexes which are greater than the
   length of the sequence are not modified. If no :meth:`__getslice__` is found,
   a slice object is created instead, and passed to :meth:`__getitem__` instead.


.. method:: object.__setslice__(self, i, j, sequence)

   Called to implement assignment to ``self[i:j]``. Same notes for *i* and *j* as
   for :meth:`__getslice__`.

   This method is deprecated. If no :meth:`__setslice__` is found, or for extended
   slicing of the form ``self[i:j:k]``, a slice object is created, and passed to
   :meth:`__setitem__`, instead of :meth:`__setslice__` being called.


.. method:: object.__delslice__(self, i, j)

   Called to implement deletion of ``self[i:j]``. Same notes for *i* and *j* as for
   :meth:`__getslice__`. This method is deprecated. If no :meth:`__delslice__` is
   found, or for extended slicing of the form ``self[i:j:k]``, a slice object is
   created, and passed to :meth:`__delitem__`, instead of :meth:`__delslice__`
   being called.

Notice that these methods are only invoked when a single slice with a single
colon is used, and the slice method is available.  For slice operations
involving extended slice notation, or in absence of the slice methods,
:meth:`__getitem__`, :meth:`__setitem__` or :meth:`__delitem__` is called with a
slice object as argument.

The following example demonstrate how to make your program or module compatible
with earlier versions of Python (assuming that methods :meth:`__getitem__`,
:meth:`__setitem__` and :meth:`__delitem__` support slice objects as
arguments)::

   class MyClass:
       ...
       def __getitem__(self, index):
           ...
       def __setitem__(self, index, value):
           ...
       def __delitem__(self, index):
           ...

       if sys.version_info < (2, 0):
           # They won't be defined if version is at least 2.0 final

           def __getslice__(self, i, j):
               return self[max(0, i):max(0, j):]
           def __setslice__(self, i, j, seq):
               self[max(0, i):max(0, j):] = seq
           def __delslice__(self, i, j):
               del self[max(0, i):max(0, j):]
       ...

Note the calls to :func:`max`; these are necessary because of the handling of
negative indices before the :meth:`__\*slice__` methods are called.  When
negative indexes are used, the :meth:`__\*item__` methods receive them as
provided, but the :meth:`__\*slice__` methods get a "cooked" form of the index
values.  For each negative index value, the length of the sequence is added to
the index before calling the method (which may still result in a negative
index); this is the customary handling of negative indexes by the built-in
sequence types, and the :meth:`__\*item__` methods are expected to do this as
well.  However, since they should already be doing that, negative indexes cannot
be passed in; they must be constrained to the bounds of the sequence before
being passed to the :meth:`__\*item__` methods. Calling ``max(0, i)``
conveniently returns the proper value.


.. _numeric-types:

Emulating numeric types
-----------------------

The following methods can be defined to emulate numeric objects. Methods
corresponding to operations that are not supported by the particular kind of
number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.


.. method:: object.__add__(self, other)
            object.__sub__(self, other)
            object.__mul__(self, other)
            object.__floordiv__(self, other)
            object.__mod__(self, other)
            object.__divmod__(self, other)
            object.__pow__(self, other[, modulo])
            object.__lshift__(self, other)
            object.__rshift__(self, other)
            object.__and__(self, other)
            object.__xor__(self, other)
            object.__or__(self, other)

   .. index::
      builtin: divmod
      builtin: pow
      builtin: pow

   These methods are called to implement the binary arithmetic operations (``+``,
   ``-``, ``*``, ``//``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``,
   ``>>``, ``&``, ``^``, ``|``).  For instance, to evaluate the expression
   ``x + y``, where *x* is an instance of a class that has an :meth:`__add__`
   method, ``x.__add__(y)`` is called.  The :meth:`__divmod__` method should be the
   equivalent to using :meth:`__floordiv__` and :meth:`__mod__`; it should not be
   related to :meth:`__truediv__` (described below).  Note that :meth:`__pow__`
   should be defined to accept an optional third argument if the ternary version of
   the built-in :func:`pow` function is to be supported.

   If one of those methods does not support the operation with the supplied
   arguments, it should return ``NotImplemented``.


.. method:: object.__div__(self, other)
            object.__truediv__(self, other)

   The division operator (``/``) is implemented by these methods.  The
   :meth:`__truediv__` method is used when ``__future__.division`` is in effect,
   otherwise :meth:`__div__` is used.  If only one of these two methods is defined,
   the object will not support division in the alternate context; :exc:`TypeError`
   will be raised instead.


.. method:: object.__radd__(self, other)
            object.__rsub__(self, other)
            object.__rmul__(self, other)
            object.__rdiv__(self, other)
            object.__rtruediv__(self, other)
            object.__rfloordiv__(self, other)
            object.__rmod__(self, other)
            object.__rdivmod__(self, other)
            object.__rpow__(self, other)
            object.__rlshift__(self, other)
            object.__rrshift__(self, other)
            object.__rand__(self, other)
            object.__rxor__(self, other)
            object.__ror__(self, other)

   .. index::
      builtin: divmod
      builtin: pow

   These methods are called to implement the binary arithmetic operations (``+``,
   ``-``, ``*``, ``/``, ``%``, :func:`divmod`, :func:`pow`, ``**``, ``<<``, ``>>``,
   ``&``, ``^``, ``|``) with reflected (swapped) operands.  These functions are
   only called if the left operand does not support the corresponding operation and
   the operands are of different types. [#]_ For instance, to evaluate the
   expression ``x - y``, where *y* is an instance of a class that has an
   :meth:`__rsub__` method, ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns
   *NotImplemented*.

   .. index:: builtin: pow

   Note that ternary :func:`pow` will not try calling :meth:`__rpow__` (the
   coercion rules would become too complicated).

   .. note::

      If the right operand's type is a subclass of the left operand's type and that
      subclass provides the reflected method for the operation, this method will be
      called before the left operand's non-reflected method.  This behavior allows
      subclasses to override their ancestors' operations.


.. method:: object.__iadd__(self, other)
            object.__isub__(self, other)
            object.__imul__(self, other)
            object.__idiv__(self, other)
            object.__itruediv__(self, other)
            object.__ifloordiv__(self, other)
            object.__imod__(self, other)
            object.__ipow__(self, other[, modulo])
            object.__ilshift__(self, other)
            object.__irshift__(self, other)
            object.__iand__(self, other)
            object.__ixor__(self, other)
            object.__ior__(self, other)

   These methods are called to implement the augmented arithmetic assignments
   (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``, ``**=``, ``<<=``, ``>>=``,
   ``&=``, ``^=``, ``|=``).  These methods should attempt to do the operation
   in-place (modifying *self*) and return the result (which could be, but does
   not have to be, *self*).  If a specific method is not defined, the augmented
   assignment falls back to the normal methods.  For instance, to execute the
   statement ``x += y``, where *x* is an instance of a class that has an
   :meth:`__iadd__` method, ``x.__iadd__(y)`` is called.  If *x* is an instance
   of a class that does not define a :meth:`__iadd__` method, ``x.__add__(y)``
   and ``y.__radd__(x)`` are considered, as with the evaluation of ``x + y``.


.. method:: object.__neg__(self)
            object.__pos__(self)
            object.__abs__(self)
            object.__invert__(self)

   .. index:: builtin: abs

   Called to implement the unary arithmetic operations (``-``, ``+``, :func:`abs`
   and ``~``).


.. method:: object.__complex__(self)
            object.__int__(self)
            object.__long__(self)
            object.__float__(self)

   .. index::
      builtin: complex
      builtin: int
      builtin: long
      builtin: float

   Called to implement the built-in functions :func:`complex`, :func:`int`,
   :func:`long`, and :func:`float`.  Should return a value of the appropriate type.


.. method:: object.__oct__(self)
            object.__hex__(self)

   .. index::
      builtin: oct
      builtin: hex

   Called to implement the built-in functions :func:`oct` and :func:`hex`.  Should
   return a string value.


.. method:: object.__index__(self)

   Called to implement :func:`operator.index`.  Also called whenever Python needs
   an integer object (such as in slicing).  Must return an integer (int or long).

   .. versionadded:: 2.5


.. method:: object.__coerce__(self, other)

   Called to implement "mixed-mode" numeric arithmetic.  Should either return a
   2-tuple containing *self* and *other* converted to a common numeric type, or
   ``None`` if conversion is impossible.  When the common type would be the type of
   ``other``, it is sufficient to return ``None``, since the interpreter will also
   ask the other object to attempt a coercion (but sometimes, if the implementation
   of the other type cannot be changed, it is useful to do the conversion to the
   other type here).  A return value of ``NotImplemented`` is equivalent to
   returning ``None``.


.. _coercion-rules:

Coercion rules
--------------

This section used to document the rules for coercion.  As the language has
evolved, the coercion rules have become hard to document precisely; documenting
what one version of one particular implementation does is undesirable.  Instead,
here are some informal guidelines regarding coercion.  In Python 3, coercion
will not be supported.

*

  If the left operand of a % operator is a string or Unicode object, no coercion
  takes place and the string formatting operation is invoked instead.

*

  It is no longer recommended to define a coercion operation. Mixed-mode
  operations on types that don't define coercion pass the original arguments to
  the operation.

*

  New-style classes (those derived from :class:`object`) never invoke the
  :meth:`__coerce__` method in response to a binary operator; the only time
  :meth:`__coerce__` is invoked is when the built-in function :func:`coerce` is
  called.

*

  For most intents and purposes, an operator that returns ``NotImplemented`` is
  treated the same as one that is not implemented at all.

*

  Below, :meth:`__op__` and :meth:`__rop__` are used to signify the generic method
  names corresponding to an operator; :meth:`__iop__` is used for the
  corresponding in-place operator.  For example, for the operator '``+``',
  :meth:`__add__` and :meth:`__radd__` are used for the left and right variant of
  the binary operator, and :meth:`__iadd__` for the in-place variant.

*

  For objects *x* and *y*, first ``x.__op__(y)`` is tried.  If this is not
  implemented or returns ``NotImplemented``, ``y.__rop__(x)`` is tried.  If this
  is also not implemented or returns ``NotImplemented``, a :exc:`TypeError`
  exception is raised.  But see the following exception:

*

  Exception to the previous item: if the left operand is an instance of a built-in
  type or a new-style class, and the right operand is an instance of a proper
  subclass of that type or class and overrides the base's :meth:`__rop__` method,
  the right operand's :meth:`__rop__` method is tried *before* the left operand's
  :meth:`__op__` method.

  This is done so that a subclass can completely override binary operators.
  Otherwise, the left operand's :meth:`__op__` method would always accept the
  right operand: when an instance of a given class is expected, an instance of a
  subclass of that class is always acceptable.

*

  When either operand type defines a coercion, this coercion is called before that
  type's :meth:`__op__` or :meth:`__rop__` method is called, but no sooner.  If
  the coercion returns an object of a different type for the operand whose
  coercion is invoked, part of the process is redone using the new object.

*

  When an in-place operator (like '``+=``') is used, if the left operand
  implements :meth:`__iop__`, it is invoked without any coercion.  When the
  operation falls back to :meth:`__op__` and/or :meth:`__rop__`, the normal
  coercion rules apply.

*

  In ``x + y``, if *x* is a sequence that implements sequence concatenation,
  sequence concatenation is invoked.

*

  In ``x * y``, if one operand is a sequence that implements sequence
  repetition, and the other is an integer (:class:`int` or :class:`long`),
  sequence repetition is invoked.

*

  Rich comparisons (implemented by methods :meth:`__eq__` and so on) never use
  coercion.  Three-way comparison (implemented by :meth:`__cmp__`) does use
  coercion under the same conditions as other binary operations use it.

*

  In the current implementation, the built-in numeric types :class:`int`,
  :class:`long`, :class:`float`, and :class:`complex` do not use coercion.
  All these types implement a :meth:`__coerce__` method, for use by the built-in
  :func:`coerce` function.

  .. versionchanged:: 2.7

     The complex type no longer makes implicit calls to the :meth:`__coerce__`
     method for mixed-type binary arithmetic operations.


.. _context-managers:

With Statement Context Managers
-------------------------------

.. versionadded:: 2.5

A :dfn:`context manager` is an object that defines the runtime context to be
established when executing a :keyword:`with` statement. The context manager
handles the entry into, and the exit from, the desired runtime context for the
execution of the block of code.  Context managers are normally invoked using the
:keyword:`with` statement (described in section :ref:`with`), but can also be
used by directly invoking their methods.

.. index::
   statement: with
   single: context manager

Typical uses of context managers include saving and restoring various kinds of
global state, locking and unlocking resources, closing opened files, etc.

For more information on context managers, see :ref:`typecontextmanager`.


.. method:: object.__enter__(self)

   Enter the runtime context related to this object. The :keyword:`with` statement
   will bind this method's return value to the target(s) specified in the
   :keyword:`as` clause of the statement, if any.


.. method:: object.__exit__(self, exc_type, exc_value, traceback)

   Exit the runtime context related to this object. The parameters describe the
   exception that caused the context to be exited. If the context was exited
   without an exception, all three arguments will be :const:`None`.

   If an exception is supplied, and the method wishes to suppress the exception
   (i.e., prevent it from being propagated), it should return a true value.
   Otherwise, the exception will be processed normally upon exit from this method.

   Note that :meth:`__exit__` methods should not reraise the passed-in exception;
   this is the caller's responsibility.


.. seealso::

   :pep:`343` - The "with" statement
      The specification, background, and examples for the Python :keyword:`with`
      statement.


.. _old-style-special-lookup:

Special method lookup for old-style classes
-------------------------------------------

For old-style classes, special methods are always looked up in exactly the
same way as any other method or attribute. This is the case regardless of
whether the method is being looked up explicitly as in ``x.__getitem__(i)``
or implicitly as in ``x[i]``.

This behaviour means that special methods may exhibit different behaviour
for different instances of a single old-style class if the appropriate
special attributes are set differently::

   >>> class C:
   ...     pass
   ...
   >>> c1 = C()
   >>> c2 = C()
   >>> c1.__len__ = lambda: 5
   >>> c2.__len__ = lambda: 9
   >>> len(c1)
   5
   >>> len(c2)
   9


.. _new-style-special-lookup:

Special method lookup for new-style classes
-------------------------------------------

For new-style classes, implicit invocations of special methods are only guaranteed
to work correctly if defined on an object's type, not in the object's instance
dictionary.  That behaviour is the reason why the following code raises an
exception (unlike the equivalent example with old-style classes)::

   >>> class C(object):
   ...     pass
   ...
   >>> c = C()
   >>> c.__len__ = lambda: 5
   >>> len(c)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: object of type 'C' has no len()

The rationale behind this behaviour lies with a number of special methods such
as :meth:`__hash__` and :meth:`__repr__` that are implemented by all objects,
including type objects. If the implicit lookup of these methods used the
conventional lookup process, they would fail when invoked on the type object
itself::

   >>> 1 .__hash__() == hash(1)
   True
   >>> int.__hash__() == hash(int)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: descriptor '__hash__' of 'int' object needs an argument

Incorrectly attempting to invoke an unbound method of a class in this way is
sometimes referred to as 'metaclass confusion', and is avoided by bypassing
the instance when looking up special methods::

   >>> type(1).__hash__(1) == hash(1)
   True
   >>> type(int).__hash__(int) == hash(int)
   True

In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
:meth:`__getattribute__` method even of the object's metaclass::

   >>> class Meta(type):
   ...    def __getattribute__(*args):
   ...       print "Metaclass getattribute invoked"
   ...       return type.__getattribute__(*args)
   ...
   >>> class C(object):
   ...     __metaclass__ = Meta
   ...     def __len__(self):
   ...         return 10
   ...     def __getattribute__(*args):
   ...         print "Class getattribute invoked"
   ...         return object.__getattribute__(*args)
   ...
   >>> c = C()
   >>> c.__len__()                 # Explicit lookup via instance
   Class getattribute invoked
   10
   >>> type(c).__len__(c)          # Explicit lookup via type
   Metaclass getattribute invoked
   10
   >>> len(c)                      # Implicit lookup
   10

Bypassing the :meth:`__getattribute__` machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of
special methods (the special method *must* be set on the class
object itself in order to be consistently invoked by the interpreter).


.. rubric:: Footnotes

.. [#] It *is* possible in some cases to change an object's type, under certain
   controlled conditions. It generally isn't a good idea though, since it can
   lead to some very strange behaviour if it is handled incorrectly.

.. [#] For operands of the same type, it is assumed that if the non-reflected method
   (such as :meth:`__add__`) fails the operation is not supported, which is why the
   reflected method is not called.

PK
%�\��{��*�*.html/_sources/reference/executionmodel.rst.txtnu�[���
.. _execmodel:

***************
Execution model
***************

.. index:: single: execution model


.. _naming:

Naming and binding
==================

.. index::
   pair: code; block
   single: namespace
   single: scope

.. index::
   single: name
   pair: binding; name

:dfn:`Names` refer to objects.  Names are introduced by name binding operations.
Each occurrence of a name in the program text refers to the :dfn:`binding` of
that name established in the innermost function block containing the use.

.. index:: single: block

A :dfn:`block` is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block.  A script file (a file given as
standard input to the interpreter or specified on the interpreter command line
the first argument) is a code block.  A script command (a command specified on
the interpreter command line with the '**-c**' option) is a code block.  The
file read by the built-in function :func:`execfile` is a code block.  The string
argument passed to the built-in function :func:`eval` and to the :keyword:`exec`
statement is a code block. The expression read and evaluated by the built-in
function :func:`input` is a code block.

.. index:: pair: execution; frame

A code block is executed in an :dfn:`execution frame`.  A frame contains some
administrative information (used for debugging) and determines where and how
execution continues after the code block's execution has completed.

.. index:: single: scope

A :dfn:`scope` defines the visibility of a name within a block.  If a local
variable is defined in a block, its scope includes that block.  If the
definition occurs in a function block, the scope extends to any blocks contained
within the defining one, unless a contained block introduces a different binding
for the name.  The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods -- this includes
generator expressions since they are implemented using a function scope.  This
means that the following will fail::

   class A:
       a = 42
       b = list(a + i for i in range(10))

.. index:: single: environment

When a name is used in a code block, it is resolved using the nearest enclosing
scope.  The set of all such scopes visible to a code block is called the block's
:dfn:`environment`.

.. index:: pair: free; variable

If a name is bound in a block, it is a local variable of that block. If a name
is bound at the module level, it is a global variable.  (The variables of the
module code block are local and global.)  If a variable is used in a code block
but not defined there, it is a :dfn:`free variable`.

.. index::
   single: NameError (built-in exception)
   single: UnboundLocalError

When a name is not found at all, a :exc:`NameError` exception is raised.  If the
name refers to a local variable that has not been bound, a
:exc:`UnboundLocalError` exception is raised.  :exc:`UnboundLocalError` is a
subclass of :exc:`NameError`.

.. index:: statement: from

The following constructs bind names: formal parameters to functions,
:keyword:`import` statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are identifiers
if occurring in an assignment, :keyword:`for` loop header, in the second
position of an :keyword:`except` clause header or after :keyword:`as` in a
:keyword:`with` statement.  The :keyword:`import` statement
of the form ``from ... import *`` binds all names defined in the imported
module, except those beginning with an underscore.  This form may only be used
at the module level.

A target occurring in a :keyword:`del` statement is also considered bound for
this purpose (though the actual semantics are to unbind the name).  It is
illegal to unbind a name that is referenced by an enclosing scope; the compiler
will report a :exc:`SyntaxError`.

Each assignment or import statement occurs within a block defined by a class or
function definition or at the module level (the top-level code block).

If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block.  This can
lead to errors when a name is used within a block before it is bound. This rule
is subtle.  Python lacks declarations and allows name binding operations to
occur anywhere within a code block.  The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.

If the global statement occurs within a block, all uses of the name specified in
the statement refer to the binding of that name in the top-level namespace.
Names are resolved in the top-level namespace by searching the global namespace,
i.e. the namespace of the module containing the code block, and the builtins
namespace, the namespace of the module :mod:`__builtin__`.  The global namespace
is searched first.  If the name is not found there, the builtins namespace is
searched.  The global statement must precede all uses of the name.

.. index:: pair: restricted; execution

The builtins namespace associated with the execution of a code block is actually
found by looking up the name ``__builtins__`` in its global namespace; this
should be a dictionary or a module (in the latter case the module's dictionary
is used).  By default, when in the :mod:`__main__` module, ``__builtins__`` is
the built-in module :mod:`__builtin__` (note: no 's'); when in any other module,
``__builtins__`` is an alias for the dictionary of the :mod:`__builtin__` module
itself.  ``__builtins__`` can be set to a user-created dictionary to create a
weak form of restricted execution.

.. impl-detail::

   Users should not touch ``__builtins__``; it is strictly an implementation
   detail.  Users wanting to override values in the builtins namespace should
   :keyword:`import` the :mod:`__builtin__` (no 's') module and modify its
   attributes appropriately.

.. index:: module: __main__

The namespace for a module is automatically created the first time a module is
imported.  The main module for a script is always called :mod:`__main__`.

The :keyword:`global` statement has the same scope as a name binding operation
in the same block.  If the nearest enclosing scope for a free variable contains
a global statement, the free variable is treated as a global.

A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution. The namespace of
the class definition becomes the attribute dictionary of the class.  Names
defined at the class scope are not visible in methods.


.. _dynamic-features:

Interaction with dynamic features
---------------------------------

There are several cases where Python statements are illegal when used in
conjunction with nested scopes that contain free variables.

If a variable is referenced in an enclosing scope, it is illegal to delete the
name.  An error will be reported at compile time.

If the wild card form of import --- ``import *`` --- is used in a function and
the function contains or is a nested block with free variables, the compiler
will raise a :exc:`SyntaxError`.

If :keyword:`exec` is used in a function and the function contains or is a
nested block with free variables, the compiler will raise a :exc:`SyntaxError`
unless the exec explicitly specifies the local namespace for the
:keyword:`exec`.  (In other words, ``exec obj`` would be illegal, but ``exec obj
in ns`` would be legal.)

The :func:`eval`, :func:`execfile`, and :func:`input` functions and the
:keyword:`exec` statement do not have access to the full environment for
resolving names.  Names may be resolved in the local and global namespaces of
the caller.  Free variables are not resolved in the nearest enclosing namespace,
but in the global namespace. [#]_ The :keyword:`exec` statement and the
:func:`eval` and :func:`execfile` functions have optional arguments to override
the global and local namespace.  If only one namespace is specified, it is used
for both.


.. _exceptions:

Exceptions
==========

.. index:: single: exception

.. index::
   single: raise an exception
   single: handle an exception
   single: exception handler
   single: errors
   single: error handling

Exceptions are a means of breaking out of the normal flow of control of a code
block in order to handle errors or other exceptional conditions.  An exception
is *raised* at the point where the error is detected; it may be *handled* by the
surrounding code block or by any code block that directly or indirectly invoked
the code block where the error occurred.

The Python interpreter raises an exception when it detects a run-time error
(such as division by zero).  A Python program can also explicitly raise an
exception with the :keyword:`raise` statement. Exception handlers are specified
with the :keyword:`try` ... :keyword:`except` statement.  The :keyword:`finally`
clause of such a statement can be used to specify cleanup code which does not
handle the exception, but is executed whether an exception occurred or not in
the preceding code.

.. index:: single: termination model

Python uses the "termination" model of error handling: an exception handler can
find out what happened and continue execution at an outer level, but it cannot
repair the cause of the error and retry the failing operation (except by
re-entering the offending piece of code from the top).

.. index:: single: SystemExit (built-in exception)

When an exception is not handled at all, the interpreter terminates execution of
the program, or returns to its interactive main loop.  In either case, it prints
a stack backtrace, except when the exception is  :exc:`SystemExit`.

Exceptions are identified by class instances.  The :keyword:`except` clause is
selected depending on the class of the instance: it must reference the class of
the instance or a base class thereof.  The instance can be received by the
handler and can carry additional information about the exceptional condition.

Exceptions can also be identified by strings, in which case the
:keyword:`except` clause is selected by object identity.  An arbitrary value can
be raised along with the identifying string which can be passed to the handler.

.. note::

   Messages to exceptions are not part of the Python API.  Their contents may
   change from one version of Python to the next without warning and should not be
   relied on by code which will run under multiple versions of the interpreter.

See also the description of the :keyword:`try` statement in section :ref:`try`
and :keyword:`raise` statement in section :ref:`raise`.

.. rubric:: Footnotes

.. [#] This limitation occurs because the code that is executed by these operations is
   not available at the time the module is compiled.

PK
%�\�mW&]�]�+html/_sources/reference/expressions.rst.txtnu�[���
.. _expressions:

***********
Expressions
***********

.. index:: single: expression

This chapter explains the meaning of the elements of expressions in Python.

.. index:: single: BNF

**Syntax Notes:** In this and the following chapters, extended BNF notation will
be used to describe syntax, not lexical analysis.  When (one alternative of) a
syntax rule has the form

.. productionlist:: *
   name: `othername`

.. index:: single: syntax

and no semantics are given, the semantics of this form of ``name`` are the same
as for ``othername``.


.. _conversions:

Arithmetic conversions
======================

.. index:: pair: arithmetic; conversion

When a description of an arithmetic operator below uses the phrase "the numeric
arguments are converted to a common type," the arguments are coerced using the
coercion rules listed at  :ref:`coercion-rules`.  If both arguments are standard
numeric types, the following coercions are applied:

* If either argument is a complex number, the other is converted to complex;

* otherwise, if either argument is a floating point number, the other is
  converted to floating point;

* otherwise, if either argument is a long integer, the other is converted to
  long integer;

* otherwise, both must be plain integers and no conversion is necessary.

Some additional rules apply for certain operators (e.g., a string left argument
to the '%' operator). Extensions can define their own coercions.


.. _atoms:

Atoms
=====

.. index:: single: atom

Atoms are the most basic elements of expressions.  The simplest atoms are
identifiers or literals.  Forms enclosed in reverse quotes or in parentheses,
brackets or braces are also categorized syntactically as atoms.  The syntax for
atoms is:

.. productionlist::
   atom: `identifier` | `literal` | `enclosure`
   enclosure: `parenth_form` | `list_display`
            : | `generator_expression` | `dict_display` | `set_display`
            : | `string_conversion` | `yield_atom`


.. _atom-identifiers:

Identifiers (Names)
-------------------

.. index::
   single: name
   single: identifier

An identifier occurring as an atom is a name.  See section :ref:`identifiers`
for lexical definition and section :ref:`naming` for documentation of naming and
binding.

.. index:: exception: NameError

When the name is bound to an object, evaluation of the atom yields that object.
When a name is not bound, an attempt to evaluate it raises a :exc:`NameError`
exception.

.. index::
   pair: name; mangling
   pair: private; names

**Private name mangling:** When an identifier that textually occurs in a class
definition begins with two or more underscore characters and does not end in two
or more underscores, it is considered a :dfn:`private name` of that class.
Private names are transformed to a longer form before code is generated for
them.  The transformation inserts the class name, with leading underscores
removed and a single underscore inserted, in front of the name.  For example,
the identifier ``__spam`` occurring in a class named ``Ham`` will be transformed
to ``_Ham__spam``.  This transformation is independent of the syntactical
context in which the identifier is used.  If the transformed name is extremely
long (longer than 255 characters), implementation defined truncation may happen.
If the class name consists only of underscores, no transformation is done.



.. _atom-literals:

Literals
--------

.. index:: single: literal

Python supports string literals and various numeric literals:

.. productionlist::
   literal: `stringliteral` | `integer` | `longinteger`
          : | `floatnumber` | `imagnumber`

Evaluation of a literal yields an object of the given type (string, integer,
long integer, floating point number, complex number) with the given value.  The
value may be approximated in the case of floating point and imaginary (complex)
literals.  See section :ref:`literals` for details.

.. index::
   triple: immutable; data; type
   pair: immutable; object

All literals correspond to immutable data types, and hence the object's identity
is less important than its value.  Multiple evaluations of literals with the
same value (either the same occurrence in the program text or a different
occurrence) may obtain the same object or a different object with the same
value.


.. _parenthesized:

Parenthesized forms
-------------------

.. index:: single: parenthesized form

A parenthesized form is an optional expression list enclosed in parentheses:

.. productionlist::
   parenth_form: "(" [`expression_list`] ")"

A parenthesized expression list yields whatever that expression list yields: if
the list contains at least one comma, it yields a tuple; otherwise, it yields
the single expression that makes up the expression list.

.. index:: pair: empty; tuple

An empty pair of parentheses yields an empty tuple object.  Since tuples are
immutable, the rules for literals apply (i.e., two occurrences of the empty
tuple may or may not yield the same object).

.. index::
   single: comma
   pair: tuple; display

Note that tuples are not formed by the parentheses, but rather by use of the
comma operator.  The exception is the empty tuple, for which parentheses *are*
required --- allowing unparenthesized "nothing" in expressions would cause
ambiguities and allow common typos to pass uncaught.


.. _lists:

List displays
-------------

.. index::
   pair: list; display
   pair: list; comprehensions

A list display is a possibly empty series of expressions enclosed in square
brackets:

.. productionlist::
   list_display: "[" [`expression_list` | `list_comprehension`] "]"
   list_comprehension: `expression` `list_for`
   list_for: "for" `target_list` "in" `old_expression_list` [`list_iter`]
   old_expression_list: `old_expression` [("," `old_expression`)+ [","]]
   old_expression: `or_test` | `old_lambda_expr`
   list_iter: `list_for` | `list_if`
   list_if: "if" `old_expression` [`list_iter`]

.. index::
   pair: list; comprehensions
   object: list
   pair: empty; list

A list display yields a new list object.  Its contents are specified by
providing either a list of expressions or a list comprehension.  When a
comma-separated list of expressions is supplied, its elements are evaluated from
left to right and placed into the list object in that order.  When a list
comprehension is supplied, it consists of a single expression followed by at
least one :keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if`
clauses.  In this case, the elements of the new list are those that would be
produced by considering each of the :keyword:`for` or :keyword:`if` clauses a
block, nesting from left to right, and evaluating the expression to produce a
list element each time the innermost block is reached [#]_.


.. _comprehensions:

Displays for sets and dictionaries
----------------------------------

For constructing a set or a dictionary Python provides special syntax
called "displays", each of them in two flavors:

* either the container contents are listed explicitly, or

* they are computed via a set of looping and filtering instructions, called a
  :dfn:`comprehension`.

Common syntax elements for comprehensions are:

.. productionlist::
   comprehension: `expression` `comp_for`
   comp_for: "for" `target_list` "in" `or_test` [`comp_iter`]
   comp_iter: `comp_for` | `comp_if`
   comp_if: "if" `expression_nocond` [`comp_iter`]

The comprehension consists of a single expression followed by at least one
:keyword:`for` clause and zero or more :keyword:`for` or :keyword:`if` clauses.
In this case, the elements of the new container are those that would be produced
by considering each of the :keyword:`for` or :keyword:`if` clauses a block,
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.

Note that the comprehension is executed in a separate scope, so names assigned
to in the target list don't "leak" in the enclosing scope.


.. _genexpr:

Generator expressions
---------------------

.. index:: pair: generator; expression
           object: generator

A generator expression is a compact generator notation in parentheses:

.. productionlist::
   generator_expression: "(" `expression` `comp_for` ")"

A generator expression yields a new generator object.  Its syntax is the same as
for comprehensions, except that it is enclosed in parentheses instead of
brackets or curly braces.

Variables used in the generator expression are evaluated lazily when the
:meth:`__next__` method is called for generator object (in the same fashion as
normal generators).  However, the leftmost :keyword:`for` clause is immediately
evaluated, so that an error produced by it can be seen before any other possible
error in the code that handles the generator expression.  Subsequent
:keyword:`for` clauses cannot be evaluated immediately since they may depend on
the previous :keyword:`for` loop. For example: ``(x*y for x in range(10) for y
in bar(x))``.

The parentheses can be omitted on calls with only one argument.  See section
:ref:`calls` for the detail.

.. _dict:

Dictionary displays
-------------------

.. index:: pair: dictionary; display
           key, datum, key/datum pair
           object: dictionary

A dictionary display is a possibly empty series of key/datum pairs enclosed in
curly braces:

.. productionlist::
   dict_display: "{" [`key_datum_list` | `dict_comprehension`] "}"
   key_datum_list: `key_datum` ("," `key_datum`)* [","]
   key_datum: `expression` ":" `expression`
   dict_comprehension: `expression` ":" `expression` `comp_for`

A dictionary display yields a new dictionary object.

If a comma-separated sequence of key/datum pairs is given, they are evaluated
from left to right to define the entries of the dictionary: each key object is
used as a key into the dictionary to store the corresponding datum.  This means
that you can specify the same key multiple times in the key/datum list, and the
final dictionary's value for that key will be the last one given.

A dict comprehension, in contrast to list and set comprehensions, needs two
expressions separated with a colon followed by the usual "for" and "if" clauses.
When the comprehension is run, the resulting key and value elements are inserted
in the new dictionary in the order they are produced.

.. index:: pair: immutable; object
           hashable

Restrictions on the types of the key values are listed earlier in section
:ref:`types`.  (To summarize, the key type should be :term:`hashable`, which excludes
all mutable objects.)  Clashes between duplicate keys are not detected; the last
datum (textually rightmost in the display) stored for a given key value
prevails.


.. _set:

Set displays
------------

.. index:: pair: set; display
           object: set

A set display is denoted by curly braces and distinguishable from dictionary
displays by the lack of colons separating keys and values:

.. productionlist::
   set_display: "{" (`expression_list` | `comprehension`) "}"

A set display yields a new mutable set object, the contents being specified by
either a sequence of expressions or a comprehension.  When a comma-separated
list of expressions is supplied, its elements are evaluated from left to right
and added to the set object.  When a comprehension is supplied, the set is
constructed from the elements resulting from the comprehension.

An empty set cannot be constructed with ``{}``; this literal constructs an empty
dictionary.


.. _string-conversions:

String conversions
------------------

.. index::
   pair: string; conversion
   pair: reverse; quotes
   pair: backward; quotes
   single: back-quotes

A string conversion is an expression list enclosed in reverse (a.k.a. backward)
quotes:

.. productionlist::
   string_conversion: "`" `expression_list` "`"

A string conversion evaluates the contained expression list and converts the
resulting object into a string according to rules specific to its type.

If the object is a string, a number, ``None``, or a tuple, list or dictionary
containing only objects whose type is one of these, the resulting string is a
valid Python expression which can be passed to the built-in function
:func:`eval` to yield an expression with the same value (or an approximation, if
floating point numbers are involved).

(In particular, converting a string adds quotes around it and converts "funny"
characters to escape sequences that are safe to print.)

.. index:: object: recursive

Recursive objects (for example, lists or dictionaries that contain a reference
to themselves, directly or indirectly) use ``...`` to indicate a recursive
reference, and the result cannot be passed to :func:`eval` to get an equal value
(:exc:`SyntaxError` will be raised instead).

.. index::
   builtin: repr
   builtin: str

The built-in function :func:`repr` performs exactly the same conversion in its
argument as enclosing it in parentheses and reverse quotes does.  The built-in
function :func:`str` performs a similar but more user-friendly conversion.


.. _yieldexpr:

Yield expressions
-----------------

.. index::
   keyword: yield
   pair: yield; expression
   pair: generator; function

.. productionlist::
   yield_atom: "(" `yield_expression` ")"
   yield_expression: "yield" [`expression_list`]

.. versionadded:: 2.5

The :keyword:`yield` expression is only used when defining a generator function,
and can only be used in the body of a function definition. Using a
:keyword:`yield` expression in a function definition is sufficient to cause that
definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a
generator.  That generator then controls the execution of a generator function.
The execution starts when one of the generator's methods is called.  At that
time, the execution proceeds to the first :keyword:`yield` expression, where it
is suspended again, returning the value of :token:`expression_list` to
generator's caller.  By suspended we mean that all local state is retained,
including the current bindings of local variables, the instruction pointer, and
the internal evaluation stack.  When the execution is resumed by calling one of
the generator's methods, the function can proceed exactly as if the
:keyword:`yield` expression was just another external call. The value of the
:keyword:`yield` expression after resuming depends on the method which resumed
the execution.

.. index:: single: coroutine

All of this makes generator functions quite similar to coroutines; they yield
multiple times, they have more than one entry point and their execution can be
suspended.  The only difference is that a generator function cannot control
where should the execution continue after it yields; the control is always
transferred to the generator's caller.

.. index:: object: generator


Generator-iterator methods
^^^^^^^^^^^^^^^^^^^^^^^^^^

This subsection describes the methods of a generator iterator.  They can
be used to control the execution of a generator function.

Note that calling any of the generator methods below when the generator
is already executing raises a :exc:`ValueError` exception.

.. index:: exception: StopIteration


.. method:: generator.next()

   Starts the execution of a generator function or resumes it at the last executed
   :keyword:`yield` expression.  When a generator function is resumed with a
   :meth:`~generator.next` method, the current :keyword:`yield` expression
   always evaluates to
   :const:`None`.  The execution then continues to the next :keyword:`yield`
   expression, where the generator is suspended again, and the value of the
   :token:`expression_list` is returned to :meth:`~generator.next`'s caller.
   If the generator
   exits without yielding another value, a :exc:`StopIteration` exception is
   raised.

.. method:: generator.send(value)

   Resumes the execution and "sends" a value into the generator function.  The
   ``value`` argument becomes the result of the current :keyword:`yield`
   expression.  The :meth:`send` method returns the next value yielded by the
   generator, or raises :exc:`StopIteration` if the generator exits without
   yielding another value. When :meth:`send` is called to start the generator, it
   must be called with :const:`None` as the argument, because there is no
   :keyword:`yield` expression that could receive the value.


.. method:: generator.throw(type[, value[, traceback]])

   Raises an exception of type ``type`` at the point where generator was paused,
   and returns the next value yielded by the generator function.  If the generator
   exits without yielding another value, a :exc:`StopIteration` exception is
   raised.  If the generator function does not catch the passed-in exception, or
   raises a different exception, then that exception propagates to the caller.

.. index:: exception: GeneratorExit


.. method:: generator.close()

   Raises a :exc:`GeneratorExit` at the point where the generator function was
   paused.  If the generator function then raises :exc:`StopIteration` (by exiting
   normally, or due to already being closed) or :exc:`GeneratorExit` (by not
   catching the exception), close returns to its caller.  If the generator yields a
   value, a :exc:`RuntimeError` is raised.  If the generator raises any other
   exception, it is propagated to the caller.  :meth:`close` does nothing if the
   generator has already exited due to an exception or normal exit.

Here is a simple example that demonstrates the behavior of generators and
generator functions::

   >>> def echo(value=None):
   ...     print "Execution starts when 'next()' is called for the first time."
   ...     try:
   ...         while True:
   ...             try:
   ...                 value = (yield value)
   ...             except Exception, e:
   ...                 value = e
   ...     finally:
   ...         print "Don't forget to clean up when 'close()' is called."
   ...
   >>> generator = echo(1)
   >>> print generator.next()
   Execution starts when 'next()' is called for the first time.
   1
   >>> print generator.next()
   None
   >>> print generator.send(2)
   2
   >>> generator.throw(TypeError, "spam")
   TypeError('spam',)
   >>> generator.close()
   Don't forget to clean up when 'close()' is called.


.. seealso::

   :pep:`342` - Coroutines via Enhanced Generators
      The proposal to enhance the API and syntax of generators, making them usable as
      simple coroutines.


.. _primaries:

Primaries
=========

.. index:: single: primary

Primaries represent the most tightly bound operations of the language. Their
syntax is:

.. productionlist::
   primary: `atom` | `attributeref` | `subscription` | `slicing` | `call`


.. _attribute-references:

Attribute references
--------------------

.. index:: pair: attribute; reference

An attribute reference is a primary followed by a period and a name:

.. productionlist::
   attributeref: `primary` "." `identifier`

.. index::
   exception: AttributeError
   object: module
   object: list

The primary must evaluate to an object of a type that supports attribute
references, e.g., a module, list, or an instance.  This object is then asked to
produce the attribute whose name is the identifier.  If this attribute is not
available, the exception :exc:`AttributeError` is raised. Otherwise, the type
and value of the object produced is determined by the object.  Multiple
evaluations of the same attribute reference may yield different objects.


.. _subscriptions:

Subscriptions
-------------

.. index:: single: subscription

.. index::
   object: sequence
   object: mapping
   object: string
   object: tuple
   object: list
   object: dictionary
   pair: sequence; item

A subscription selects an item of a sequence (string, tuple or list) or mapping
(dictionary) object:

.. productionlist::
   subscription: `primary` "[" `expression_list` "]"

The primary must evaluate to an object of a sequence or mapping type.

If the primary is a mapping, the expression list must evaluate to an object
whose value is one of the keys of the mapping, and the subscription selects the
value in the mapping that corresponds to that key.  (The expression list is a
tuple except if it has exactly one item.)

If the primary is a sequence, the expression list must evaluate to a plain
integer.  If this value is negative, the length of the sequence is added to it
(so that, e.g., ``x[-1]`` selects the last item of ``x``.)  The resulting value
must be a nonnegative integer less than the number of items in the sequence, and
the subscription selects the item whose index is that value (counting from
zero).

.. index::
   single: character
   pair: string; item

A string's items are characters.  A character is not a separate data type but a
string of exactly one character.


.. _slicings:

Slicings
--------

.. index::
   single: slicing
   single: slice

.. index::
   object: sequence
   object: string
   object: tuple
   object: list

A slicing selects a range of items in a sequence object (e.g., a string, tuple
or list).  Slicings may be used as expressions or as targets in assignment or
:keyword:`del` statements.  The syntax for a slicing:

.. productionlist::
   slicing: `simple_slicing` | `extended_slicing`
   simple_slicing: `primary` "[" `short_slice` "]"
   extended_slicing: `primary` "[" `slice_list` "]"
   slice_list: `slice_item` ("," `slice_item`)* [","]
   slice_item: `expression` | `proper_slice` | `ellipsis`
   proper_slice: `short_slice` | `long_slice`
   short_slice: [`lower_bound`] ":" [`upper_bound`]
   long_slice: `short_slice` ":" [`stride`]
   lower_bound: `expression`
   upper_bound: `expression`
   stride: `expression`
   ellipsis: "..."

.. index:: pair: extended; slicing

There is ambiguity in the formal syntax here: anything that looks like an
expression list also looks like a slice list, so any subscription can be
interpreted as a slicing.  Rather than further complicating the syntax, this is
disambiguated by defining that in this case the interpretation as a subscription
takes priority over the interpretation as a slicing (this is the case if the
slice list contains no proper slice nor ellipses).  Similarly, when the slice
list has exactly one short slice and no trailing comma, the interpretation as a
simple slicing takes priority over that as an extended slicing.

The semantics for a simple slicing are as follows.  The primary must evaluate to
a sequence object.  The lower and upper bound expressions, if present, must
evaluate to plain integers; defaults are zero and the ``sys.maxint``,
respectively.  If either bound is negative, the sequence's length is added to
it.  The slicing now selects all items with index *k* such that ``i <= k < j``
where *i* and *j* are the specified lower and upper bounds.  This may be an
empty sequence.  It is not an error if *i* or *j* lie outside the range of valid
indexes (such items don't exist so they aren't selected).

.. index::
   single: start (slice object attribute)
   single: stop (slice object attribute)
   single: step (slice object attribute)

The semantics for an extended slicing are as follows.  The primary must evaluate
to a mapping object, and it is indexed with a key that is constructed from the
slice list, as follows.  If the slice list contains at least one comma, the key
is a tuple containing the conversion of the slice items; otherwise, the
conversion of the lone slice item is the key.  The conversion of a slice item
that is an expression is that expression.  The conversion of an ellipsis slice
item is the built-in ``Ellipsis`` object.  The conversion of a proper slice is a
slice object (see section :ref:`types`) whose :attr:`~slice.start`,
:attr:`~slice.stop` and :attr:`~slice.step` attributes are the values of the
expressions given as lower bound, upper bound and stride, respectively,
substituting ``None`` for missing expressions.


.. index::
   object: callable
   single: call
   single: argument; call semantics

.. _calls:

Calls
-----

A call calls a callable object (e.g., a :term:`function`) with a possibly empty
series of :term:`arguments <argument>`:

.. productionlist::
   call: `primary` "(" [`argument_list` [","]
       : | `expression` `genexpr_for`] ")"
   argument_list: `positional_arguments` ["," `keyword_arguments`]
                :   ["," "*" `expression`] ["," `keyword_arguments`]
                :   ["," "**" `expression`]
                : | `keyword_arguments` ["," "*" `expression`]
                :   ["," "**" `expression`]
                : | "*" `expression` ["," `keyword_arguments`] ["," "**" `expression`]
                : | "**" `expression`
   positional_arguments: `expression` ("," `expression`)*
   keyword_arguments: `keyword_item` ("," `keyword_item`)*
   keyword_item: `identifier` "=" `expression`

A trailing comma may be present after the positional and keyword arguments but
does not affect the semantics.

.. index::
   single: parameter; call semantics

The primary must evaluate to a callable object (user-defined functions, built-in
functions, methods of built-in objects, class objects, methods of class
instances, and certain class instances themselves are callable; extensions may
define additional callable object types).  All argument expressions are
evaluated before the call is attempted.  Please refer to section :ref:`function`
for the syntax of formal :term:`parameter` lists.

If keyword arguments are present, they are first converted to positional
arguments, as follows.  First, a list of unfilled slots is created for the
formal parameters.  If there are N positional arguments, they are placed in the
first N slots.  Next, for each keyword argument, the identifier is used to
determine the corresponding slot (if the identifier is the same as the first
formal parameter name, the first slot is used, and so on).  If the slot is
already filled, a :exc:`TypeError` exception is raised. Otherwise, the value of
the argument is placed in the slot, filling it (even if the expression is
``None``, it fills the slot).  When all arguments have been processed, the slots
that are still unfilled are filled with the corresponding default value from the
function definition.  (Default values are calculated, once, when the function is
defined; thus, a mutable object such as a list or dictionary used as default
value will be shared by all calls that don't specify an argument value for the
corresponding slot; this should usually be avoided.)  If there are any unfilled
slots for which no default value is specified, a :exc:`TypeError` exception is
raised.  Otherwise, the list of filled slots is used as the argument list for
the call.

.. impl-detail::

   An implementation may provide built-in functions whose positional parameters
   do not have names, even if they are 'named' for the purpose of documentation,
   and which therefore cannot be supplied by keyword.  In CPython, this is the
   case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to
   parse their arguments.

If there are more positional arguments than there are formal parameter slots, a
:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
``*identifier`` is present; in this case, that formal parameter receives a tuple
containing the excess positional arguments (or an empty tuple if there were no
excess positional arguments).

If any keyword argument does not correspond to a formal parameter name, a
:exc:`TypeError` exception is raised, unless a formal parameter using the syntax
``**identifier`` is present; in this case, that formal parameter receives a
dictionary containing the excess keyword arguments (using the keywords as keys
and the argument values as corresponding values), or a (new) empty dictionary if
there were no excess keyword arguments.

.. index::
   single: *; in function calls

If the syntax ``*expression`` appears in the function call, ``expression`` must
evaluate to an iterable.  Elements from this iterable are treated as if they
were additional positional arguments; if there are positional arguments
*x1*, ..., *xN*, and ``expression`` evaluates to a sequence *y1*, ..., *yM*, this
is equivalent to a call with M+N positional arguments *x1*, ..., *xN*, *y1*,
..., *yM*.

A consequence of this is that although the ``*expression`` syntax may appear
*after* some keyword arguments, it is processed *before* the keyword arguments
(and the ``**expression`` argument, if any -- see below).  So::

   >>> def f(a, b):
   ...     print a, b
   ...
   >>> f(b=1, *(2,))
   2 1
   >>> f(a=1, *(2,))
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: f() got multiple values for keyword argument 'a'
   >>> f(1, *(2,))
   1 2

It is unusual for both keyword arguments and the ``*expression`` syntax to be
used in the same call, so in practice this confusion does not arise.

.. index::
   single: **; in function calls

If the syntax ``**expression`` appears in the function call, ``expression`` must
evaluate to a mapping, the contents of which are treated as additional keyword
arguments.  In the case of a keyword appearing in both ``expression`` and as an
explicit keyword argument, a :exc:`TypeError` exception is raised.

Formal parameters using the syntax ``*identifier`` or ``**identifier`` cannot be
used as positional argument slots or as keyword argument names.  Formal
parameters using the syntax ``(sublist)`` cannot be used as keyword argument
names; the outermost sublist corresponds to a single unnamed argument slot, and
the argument value is assigned to the sublist using the usual tuple assignment
rules after all other parameter processing is done.

A call always returns some value, possibly ``None``, unless it raises an
exception.  How this value is computed depends on the type of the callable
object.

If it is---

a user-defined function:
   .. index::
      pair: function; call
      triple: user-defined; function; call
      object: user-defined function
      object: function

   The code block for the function is executed, passing it the argument list.  The
   first thing the code block will do is bind the formal parameters to the
   arguments; this is described in section :ref:`function`.  When the code block
   executes a :keyword:`return` statement, this specifies the return value of the
   function call.

a built-in function or method:
   .. index::
      pair: function; call
      pair: built-in function; call
      pair: method; call
      pair: built-in method; call
      object: built-in method
      object: built-in function
      object: method
      object: function

   The result is up to the interpreter; see :ref:`built-in-funcs` for the
   descriptions of built-in functions and methods.

a class object:
   .. index::
      object: class
      pair: class object; call

   A new instance of that class is returned.

a class instance method:
   .. index::
      object: class instance
      object: instance
      pair: class instance; call

   The corresponding user-defined function is called, with an argument list that is
   one longer than the argument list of the call: the instance becomes the first
   argument.

a class instance:
   .. index::
      pair: instance; call
      single: __call__() (object method)

   The class must define a :meth:`__call__` method; the effect is then the same as
   if that method was called.


.. _power:

The power operator
==================

The power operator binds more tightly than unary operators on its left; it binds
less tightly than unary operators on its right.  The syntax is:

.. productionlist::
   power: `primary` ["**" `u_expr`]

Thus, in an unparenthesized sequence of power and unary operators, the operators
are evaluated from right to left (this does not constrain the evaluation order
for the operands): ``-1**2`` results in ``-1``.

The power operator has the same semantics as the built-in :func:`pow` function,
when called with two arguments: it yields its left argument raised to the power
of its right argument.  The numeric arguments are first converted to a common
type.  The result type is that of the arguments after coercion.

With mixed operand types, the coercion rules for binary arithmetic operators
apply. For int and long int operands, the result has the same type as the
operands (after coercion) unless the second argument is negative; in that case,
all arguments are converted to float and a float result is delivered. For
example, ``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``. (This last
feature was added in Python 2.2. In Python 2.1 and before, if both arguments
were of integer types and the second argument was negative, an exception was
raised).

Raising ``0.0`` to a negative power results in a :exc:`ZeroDivisionError`.
Raising a negative number to a fractional power results in a :exc:`ValueError`.


.. _unary:

Unary arithmetic and bitwise operations
=======================================

.. index::
   triple: unary; arithmetic; operation
   triple: unary; bitwise; operation

All unary arithmetic and bitwise operations have the same priority:

.. productionlist::
   u_expr: `power` | "-" `u_expr` | "+" `u_expr` | "~" `u_expr`

.. index::
   single: negation
   single: minus

The unary ``-`` (minus) operator yields the negation of its numeric argument.

.. index:: single: plus

The unary ``+`` (plus) operator yields its numeric argument unchanged.

.. index:: single: inversion

The unary ``~`` (invert) operator yields the bitwise inversion of its plain or
long integer argument.  The bitwise inversion of ``x`` is defined as
``-(x+1)``.  It only applies to integral numbers.

.. index:: exception: TypeError

In all three cases, if the argument does not have the proper type, a
:exc:`TypeError` exception is raised.


.. _binary:

Binary arithmetic operations
============================

.. index:: triple: binary; arithmetic; operation

The binary arithmetic operations have the conventional priority levels.  Note
that some of these operations also apply to certain non-numeric types.  Apart
from the power operator, there are only two levels, one for multiplicative
operators and one for additive operators:

.. productionlist::
   m_expr: `u_expr` | `m_expr` "*" `u_expr` | `m_expr` "//" `u_expr` | `m_expr` "/" `u_expr`
         : | `m_expr` "%" `u_expr`
   a_expr: `m_expr` | `a_expr` "+" `m_expr` | `a_expr` "-" `m_expr`

.. index:: single: multiplication

The ``*`` (multiplication) operator yields the product of its arguments.  The
arguments must either both be numbers, or one argument must be an integer (plain
or long) and the other must be a sequence. In the former case, the numbers are
converted to a common type and then multiplied together.  In the latter case,
sequence repetition is performed; a negative repetition factor yields an empty
sequence.

.. index::
   exception: ZeroDivisionError
   single: division

The ``/`` (division) and ``//`` (floor division) operators yield the quotient of
their arguments.  The numeric arguments are first converted to a common type.
Plain or long integer division yields an integer of the same type; the result is
that of mathematical division with the 'floor' function applied to the result.
Division by zero raises the :exc:`ZeroDivisionError` exception.

.. index:: single: modulo

The ``%`` (modulo) operator yields the remainder from the division of the first
argument by the second.  The numeric arguments are first converted to a common
type.  A zero right argument raises the :exc:`ZeroDivisionError` exception.  The
arguments may be floating point numbers, e.g., ``3.14%0.7`` equals ``0.34``
(since ``3.14`` equals ``4*0.7 + 0.34``.)  The modulo operator always yields a
result with the same sign as its second operand (or zero); the absolute value of
the result is strictly smaller than the absolute value of the second operand
[#]_.

The integer division and modulo operators are connected by the following
identity: ``x == (x/y)*y + (x%y)``.  Integer division and modulo are also
connected with the built-in function :func:`divmod`: ``divmod(x, y) == (x/y,
x%y)``.  These identities don't hold for floating point numbers; there similar
identities hold approximately where ``x/y`` is replaced by ``floor(x/y)`` or
``floor(x/y) - 1`` [#]_.

In addition to performing the modulo operation on numbers, the ``%`` operator is
also overloaded by string and unicode objects to perform string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section :ref:`string-formatting`.

.. deprecated:: 2.3
   The floor division operator, the modulo operator, and the :func:`divmod`
   function are no longer defined for complex numbers.  Instead, convert to a
   floating point number using the :func:`abs` function if appropriate.

.. index:: single: addition

The ``+`` (addition) operator yields the sum of its arguments. The arguments
must either both be numbers or both sequences of the same type.  In the former
case, the numbers are converted to a common type and then added together.  In
the latter case, the sequences are concatenated.

.. index:: single: subtraction

The ``-`` (subtraction) operator yields the difference of its arguments.  The
numeric arguments are first converted to a common type.


.. _shifting:

Shifting operations
===================

.. index:: pair: shifting; operation

The shifting operations have lower priority than the arithmetic operations:

.. productionlist::
   shift_expr: `a_expr` | `shift_expr` ( "<<" | ">>" ) `a_expr`

These operators accept plain or long integers as arguments.  The arguments are
converted to a common type.  They shift the first argument to the left or right
by the number of bits given by the second argument.

.. index:: exception: ValueError

A right shift by *n* bits is defined as division by ``pow(2, n)``.  A left shift
by *n* bits is defined as multiplication with ``pow(2, n)``.  Negative shift
counts raise a :exc:`ValueError` exception.

.. note::

   In the current implementation, the right-hand operand is required
   to be at most :attr:`sys.maxsize`.  If the right-hand operand is larger than
   :attr:`sys.maxsize` an :exc:`OverflowError` exception is raised.

.. _bitwise:

Binary bitwise operations
=========================

.. index:: triple: binary; bitwise; operation

Each of the three bitwise operations has a different priority level:

.. productionlist::
   and_expr: `shift_expr` | `and_expr` "&" `shift_expr`
   xor_expr: `and_expr` | `xor_expr` "^" `and_expr`
   or_expr: `xor_expr` | `or_expr` "|" `xor_expr`

.. index:: pair: bitwise; and

The ``&`` operator yields the bitwise AND of its arguments, which must be plain
or long integers.  The arguments are converted to a common type.

.. index::
   pair: bitwise; xor
   pair: exclusive; or

The ``^`` operator yields the bitwise XOR (exclusive OR) of its arguments, which
must be plain or long integers.  The arguments are converted to a common type.

.. index::
   pair: bitwise; or
   pair: inclusive; or

The ``|`` operator yields the bitwise (inclusive) OR of its arguments, which
must be plain or long integers.  The arguments are converted to a common type.


.. _comparisons:

Comparisons
===========

.. index:: single: comparison

.. index:: pair: C; language

Unlike C, all comparison operations in Python have the same priority, which is
lower than that of any arithmetic, shifting or bitwise operation.  Also unlike
C, expressions like ``a < b < c`` have the interpretation that is conventional
in mathematics:

.. productionlist::
   comparison: `or_expr` ( `comp_operator` `or_expr` )*
   comp_operator: "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
                : | "is" ["not"] | ["not"] "in"

Comparisons yield boolean values: ``True`` or ``False``.

.. index:: pair: chaining; comparisons

Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to
``x < y and y <= z``, except that ``y`` is evaluated only once (but in both
cases ``z`` is not evaluated at all when ``x < y`` is found to be false).

Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ...,
*opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent
to ``a op1 b and b op2 c and ... y opN z``, except that each expression is
evaluated at most once.

Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and
*c*, so that, e.g., ``x < y > z`` is perfectly legal (though perhaps not
pretty).

The forms ``<>`` and ``!=`` are equivalent; for consistency with C, ``!=`` is
preferred; where ``!=`` is mentioned below ``<>`` is also accepted.  The ``<>``
spelling is considered obsolescent.

Value comparisons
-----------------

The operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare the
values of two objects.  The objects do not need to have the same type.

Chapter :ref:`objects` states that objects have a value (in addition to type
and identity).  The value of an object is a rather abstract notion in Python:
For example, there is no canonical access method for an object's value.  Also,
there is no requirement that the value of an object should be constructed in a
particular way, e.g. comprised of all its data attributes. Comparison operators
implement a particular notion of what the value of an object is.  One can think
of them as defining the value of an object indirectly, by means of their
comparison implementation.

Types can customize their comparison behavior by implementing
a :meth:`__cmp__` method or
:dfn:`rich comparison methods` like :meth:`__lt__`, described in
:ref:`customization`.

The default behavior for equality comparison (``==`` and ``!=``) is based on
the identity of the objects.  Hence, equality comparison of instances with the
same identity results in equality, and equality comparison of instances with
different identities results in inequality.  A motivation for this default
behavior is the desire that all objects should be reflexive (i.e. ``x is y``
implies ``x == y``).

The default order comparison (``<``, ``>``, ``<=``, and ``>=``) gives a
consistent but arbitrary order.

(This unusual definition of comparison was used to simplify the definition of
operations like sorting and the :keyword:`in` and :keyword:`not in` operators.
In the future, the comparison rules for objects of different types are likely to
change.)

The behavior of the default equality comparison, that instances with different
identities are always unequal, may be in contrast to what types will need that
have a sensible definition of object value and value-based equality.  Such
types will need to customize their comparison behavior, and in fact, a number
of built-in types have done that.

The following list describes the comparison behavior of the most important
built-in types.

* Numbers of built-in numeric types (:ref:`typesnumeric`) and of the standard
  library types :class:`fractions.Fraction` and :class:`decimal.Decimal` can be
  compared within and across their types, with the restriction that complex
  numbers do not support order comparison.  Within the limits of the types
  involved, they compare mathematically (algorithmically) correct without loss
  of precision.

* Strings (instances of :class:`str` or :class:`unicode`)
  compare lexicographically using the numeric equivalents (the
  result of the built-in function :func:`ord`) of their characters. [#]_
  When comparing an 8-bit string and a Unicode string, the 8-bit string
  is converted to Unicode.  If the conversion fails, the strings
  are considered unequal.

* Instances of :class:`tuple` or :class:`list` can be compared only
  within each of their types.  Equality comparison across these types
  results in unequality, and ordering comparison across these types
  gives an arbitrary order.

  These sequences compare lexicographically using comparison of corresponding
  elements, whereby reflexivity of the elements is enforced.

  In enforcing reflexivity of elements, the comparison of collections assumes
  that for a collection element ``x``, ``x == x`` is always true.  Based on
  that assumption, element identity is compared first, and element comparison
  is performed only for distinct elements.  This approach yields the same
  result as a strict element comparison would, if the compared elements are
  reflexive.  For non-reflexive elements, the result is different than for
  strict element comparison.

  Lexicographical comparison between built-in collections works as follows:

  - For two collections to compare equal, they must be of the same type, have
    the same length, and each pair of corresponding elements must compare
    equal (for example, ``[1,2] == (1,2)`` is false because the type is not the
    same).

  - Collections are ordered the same as their
    first unequal elements (for example, ``cmp([1,2,x], [1,2,y])`` returns the
    same as ``cmp(x,y)``).  If a corresponding element does not exist, the
    shorter collection is ordered first (for example, ``[1,2] < [1,2,3]`` is
    true).

* Mappings (instances of :class:`dict`) compare equal if and only if they have
  equal `(key, value)` pairs. Equality comparison of the keys and values
  enforces reflexivity.

  Outcomes other than equality are resolved
  consistently, but are not otherwise defined. [#]_

* Most other objects of built-in types compare unequal unless they are the same
  object; the choice whether one object is considered smaller or larger than
  another one is made arbitrarily but consistently within one execution of a
  program.

User-defined classes that customize their comparison behavior should follow
some consistency rules, if possible:

* Equality comparison should be reflexive.
  In other words, identical objects should compare equal:

    ``x is y`` implies ``x == y``

* Comparison should be symmetric.
  In other words, the following expressions should have the same result:

    ``x == y`` and ``y == x``

    ``x != y`` and ``y != x``

    ``x < y`` and ``y > x``

    ``x <= y`` and ``y >= x``

* Comparison should be transitive.
  The following (non-exhaustive) examples illustrate that:

    ``x > y and y > z`` implies ``x > z``

    ``x < y and y <= z`` implies ``x < z``

* Inverse comparison should result in the boolean negation.
  In other words, the following expressions should have the same result:

    ``x == y`` and ``not x != y``

    ``x < y`` and ``not x >= y`` (for total ordering)

    ``x > y`` and ``not x <= y`` (for total ordering)

  The last two expressions apply to totally ordered collections (e.g. to
  sequences, but not to sets or mappings). See also the
  :func:`~functools.total_ordering` decorator.

* The :func:`hash` result should be consistent with equality.
  Objects that are equal should either have the same hash value,
  or be marked as unhashable.

Python does not enforce these consistency rules.


.. _in:
.. _not in:
.. _membership-test-details:

Membership test operations
--------------------------

The operators :keyword:`in` and :keyword:`not in` test for membership.  ``x in
s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise.
``x not in s`` returns the negation of ``x in s``.  All built-in sequences and
set types support this as well as dictionary, for which :keyword:`in` tests
whether the dictionary has a given key. For container types such as list, tuple,
set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent
to ``any(x is e or x == e for e in y)``.

For the string and bytes types, ``x in y`` is ``True`` if and only if *x* is a
substring of *y*.  An equivalent test is ``y.find(x) != -1``.  Empty strings are
always considered to be a substring of any other string, so ``"" in "abc"`` will
return ``True``.

For user-defined classes which define the :meth:`__contains__` method, ``x in
y`` returns ``True`` if ``y.__contains__(x)`` returns a true value, and
``False`` otherwise.

For user-defined classes which do not define :meth:`__contains__` but do define
:meth:`__iter__`, ``x in y`` is ``True`` if some value ``z`` with ``x == z`` is
produced while iterating over ``y``.  If an exception is raised during the
iteration, it is as if :keyword:`in` raised that exception.

Lastly, the old-style iteration protocol is tried: if a class defines
:meth:`__getitem__`, ``x in y`` is ``True`` if and only if there is a non-negative
integer index *i* such that ``x == y[i]``, and all lower integer indices do not
raise :exc:`IndexError` exception. (If any other exception is raised, it is as
if :keyword:`in` raised that exception).

.. index::
   operator: in
   operator: not in
   pair: membership; test
   object: sequence

The operator :keyword:`not in` is defined to have the inverse true value of
:keyword:`in`.

.. index::
   operator: is
   operator: is not
   pair: identity; test


.. _is:
.. _is not:

Identity comparisons
--------------------

The operators :keyword:`is` and :keyword:`is not` test for object identity: ``x
is y`` is true if and only if *x* and *y* are the same object.  ``x is not y``
yields the inverse truth value. [#]_


.. _booleans:
.. _and:
.. _or:
.. _not:

Boolean operations
==================

.. index::
   pair: Conditional; expression
   pair: Boolean; operation

.. productionlist::
   or_test: `and_test` | `or_test` "or" `and_test`
   and_test: `not_test` | `and_test` "and" `not_test`
   not_test: `comparison` | "not" `not_test`

In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
``False``, ``None``, numeric zero of all types, and empty strings and containers
(including strings, tuples, lists, dictionaries, sets and frozensets).  All
other values are interpreted as true.  (See the :meth:`~object.__nonzero__`
special method for a way to change this.)

.. index:: operator: not

The operator :keyword:`not` yields ``True`` if its argument is false, ``False``
otherwise.

.. index:: operator: and

The expression ``x and y`` first evaluates *x*; if *x* is false, its value is
returned; otherwise, *y* is evaluated and the resulting value is returned.

.. index:: operator: or

The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
returned; otherwise, *y* is evaluated and the resulting value is returned.

(Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
they return to ``False`` and ``True``, but rather return the last evaluated
argument. This is sometimes useful, e.g., if ``s`` is a string that should be
replaced by a default value if it is empty, the expression ``s or 'foo'`` yields
the desired value.  Because :keyword:`not` has to invent a value anyway, it does
not bother to return a value of the same type as its argument, so e.g., ``not
'foo'`` yields ``False``, not ``''``.)


Conditional Expressions
=======================

.. versionadded:: 2.5

.. index::
   pair: conditional; expression
   pair: ternary; operator

.. productionlist::
   conditional_expression: `or_test` ["if" `or_test` "else" `expression`]
   expression: `conditional_expression` | `lambda_expr`

Conditional expressions (sometimes called a "ternary operator") have the lowest
priority of all Python operations.

The expression ``x if C else y`` first evaluates the condition, *C* (*not* *x*);
if *C* is true, *x* is evaluated and its value is returned; otherwise, *y* is
evaluated and its value is returned.

See :pep:`308` for more details about conditional expressions.


.. _lambdas:
.. _lambda:

Lambdas
=======

.. index::
   pair: lambda; expression
   pair: anonymous; function

.. productionlist::
   lambda_expr: "lambda" [`parameter_list`]: `expression`
   old_lambda_expr: "lambda" [`parameter_list`]: `old_expression`

Lambda expressions (sometimes called lambda forms) have the same syntactic position as
expressions.  They are a shorthand to create anonymous functions; the expression
``lambda parameters: expression`` yields a function object.  The unnamed object
behaves like a function object defined with ::

   def <lambda>(parameters):
       return expression

See section :ref:`function` for the syntax of parameter lists.  Note that
functions created with lambda expressions cannot contain statements.


.. _exprlists:

Expression lists
================

.. index:: pair: expression; list

.. productionlist::
   expression_list: `expression` ( "," `expression` )* [","]

.. index:: object: tuple

An expression list containing at least one comma yields a tuple.  The length of
the tuple is the number of expressions in the list.  The expressions are
evaluated from left to right.

.. index:: pair: trailing; comma

The trailing comma is required only to create a single tuple (a.k.a. a
*singleton*); it is optional in all other cases.  A single expression without a
trailing comma doesn't create a tuple, but rather yields the value of that
expression. (To create an empty tuple, use an empty pair of parentheses:
``()``.)


.. _evalorder:

Evaluation order
================

.. index:: pair: evaluation; order

Python evaluates expressions from left to right. Notice that while evaluating an
assignment, the right-hand side is evaluated before the left-hand side.

In the following lines, expressions will be evaluated in the arithmetic order of
their suffixes::

   expr1, expr2, expr3, expr4
   (expr1, expr2, expr3, expr4)
   {expr1: expr2, expr3: expr4}
   expr1 + expr2 * (expr3 - expr4)
   expr1(expr2, expr3, *expr4, **expr5)
   expr3, expr4 = expr1, expr2


.. _operator-summary:

Operator precedence
===================

.. index:: pair: operator; precedence

The following table summarizes the operator precedences in Python, from lowest
precedence (least binding) to highest precedence (most binding). Operators in
the same box have the same precedence.  Unless the syntax is explicitly given,
operators are binary.  Operators in the same box group left to right (except for
comparisons, including tests, which all have the same precedence and chain from
left to right --- see section :ref:`comparisons` --- and exponentiation, which
groups from right to left).

+-----------------------------------------------+-------------------------------------+
| Operator                                      | Description                         |
+===============================================+=====================================+
| :keyword:`lambda`                             | Lambda expression                   |
+-----------------------------------------------+-------------------------------------+
| :keyword:`if` -- :keyword:`else`              | Conditional expression              |
+-----------------------------------------------+-------------------------------------+
| :keyword:`or`                                 | Boolean OR                          |
+-----------------------------------------------+-------------------------------------+
| :keyword:`and`                                | Boolean AND                         |
+-----------------------------------------------+-------------------------------------+
| :keyword:`not` ``x``                          | Boolean NOT                         |
+-----------------------------------------------+-------------------------------------+
| :keyword:`in`, :keyword:`not in`,             | Comparisons, including membership   |
| :keyword:`is`, :keyword:`is not`, ``<``,      | tests and identity tests            |
| ``<=``, ``>``, ``>=``, ``<>``, ``!=``, ``==`` |                                     |
+-----------------------------------------------+-------------------------------------+
| ``|``                                         | Bitwise OR                          |
+-----------------------------------------------+-------------------------------------+
| ``^``                                         | Bitwise XOR                         |
+-----------------------------------------------+-------------------------------------+
| ``&``                                         | Bitwise AND                         |
+-----------------------------------------------+-------------------------------------+
| ``<<``, ``>>``                                | Shifts                              |
+-----------------------------------------------+-------------------------------------+
| ``+``, ``-``                                  | Addition and subtraction            |
+-----------------------------------------------+-------------------------------------+
| ``*``, ``/``, ``//``, ``%``                   | Multiplication, division, remainder |
|                                               | [#]_                                |
+-----------------------------------------------+-------------------------------------+
| ``+x``, ``-x``, ``~x``                        | Positive, negative, bitwise NOT     |
+-----------------------------------------------+-------------------------------------+
| ``**``                                        | Exponentiation [#]_                 |
+-----------------------------------------------+-------------------------------------+
| ``x[index]``, ``x[index:index]``,             | Subscription, slicing,              |
| ``x(arguments...)``, ``x.attribute``          | call, attribute reference           |
+-----------------------------------------------+-------------------------------------+
| ``(expressions...)``,                         | Binding or tuple display,           |
| ``[expressions...]``,                         | list display,                       |
| ``{key: value...}``,                          | dictionary display,                 |
| ```expressions...```                          | string conversion                   |
+-----------------------------------------------+-------------------------------------+

.. rubric:: Footnotes

.. [#] In Python 2.3 and later releases, a list comprehension "leaks" the control
   variables of each ``for`` it contains into the containing scope.  However, this
   behavior is deprecated, and relying on it will not work in Python 3.

.. [#] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it may not be
   true numerically due to roundoff.  For example, and assuming a platform on which
   a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
   1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
   1e100``, which is numerically exactly equal to ``1e100``.  The function
   :func:`math.fmod` returns a result whose sign matches the sign of the
   first argument instead, and so returns ``-1e-100`` in this case. Which approach
   is more appropriate depends on the application.

.. [#] If x is very close to an exact integer multiple of y, it's possible for
   ``floor(x/y)`` to be one larger than ``(x-x%y)/y`` due to rounding.  In such
   cases, Python returns the latter result, in order to preserve that
   ``divmod(x,y)[0] * y + x % y`` be very close to ``x``.

.. [#] The Unicode standard distinguishes between :dfn:`code points`
   (e.g. U+0041) and :dfn:`abstract characters` (e.g. "LATIN CAPITAL LETTER A").
   While most abstract characters in Unicode are only represented using one
   code point, there is a number of abstract characters that can in addition be
   represented using a sequence of more than one code point.  For example, the
   abstract character "LATIN CAPITAL LETTER C WITH CEDILLA" can be represented
   as a single :dfn:`precomposed character` at code position U+00C7, or as a
   sequence of a :dfn:`base character` at code position U+0043 (LATIN CAPITAL
   LETTER C), followed by a :dfn:`combining character` at code position U+0327
   (COMBINING CEDILLA).

   The comparison operators on unicode strings compare at the level of Unicode code
   points. This may be counter-intuitive to humans.  For example,
   ``u"\u00C7" == u"\u0043\u0327"`` is ``False``, even though both strings
   represent the same abstract character "LATIN CAPITAL LETTER C WITH CEDILLA".

   To compare strings at the level of abstract characters (that is, in a way
   intuitive to humans), use :func:`unicodedata.normalize`.

.. [#] Earlier versions of Python used lexicographic comparison of the sorted (key,
   value) lists, but this was very expensive for the common case of comparing for
   equality.  An even earlier version of Python compared dictionaries by identity
   only, but this caused surprises because people expected to be able to test a
   dictionary for emptiness by comparing it to ``{}``.

.. [#] Due to automatic garbage-collection, free lists, and the dynamic nature of
   descriptors, you may notice seemingly unusual behaviour in certain uses of
   the :keyword:`is` operator, like those involving comparisons between instance
   methods, or constants.  Check their documentation for more info.

.. [#] The ``%`` operator is also used for string formatting; the same
   precedence applies.

.. [#] The power operator ``**`` binds less tightly than an arithmetic or
   bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.
PK
%�\6�� ��'html/_sources/reference/grammar.rst.txtnu�[���Full Grammar specification
==========================

This is the full Python grammar, as it is read by the parser generator and used
to parse Python source files:

.. literalinclude:: ../../Grammar/Grammar
PK
%�\]lh_��%html/_sources/reference/index.rst.txtnu�[���.. _reference-index:

#################################
  The Python Language Reference
#################################

This reference manual describes the syntax and "core semantics" of the
language. It is terse, but attempts to be exact and complete. The semantics of
non-essential built-in object types and of the built-in functions and modules
are described in :ref:`library-index`. For an informal introduction to the
language, see :ref:`tutorial-index`. For C or C++ programmers, two additional
manuals exist: :ref:`extending-index` describes the high-level picture of how to
write a Python extension module, and the :ref:`c-api-index` describes the
interfaces available to C/C++ programmers in detail.

.. toctree::
   :maxdepth: 2
   :numbered:

   introduction.rst
   lexical_analysis.rst
   datamodel.rst
   executionmodel.rst
   expressions.rst
   simple_stmts.rst
   compound_stmts.rst
   toplevel_components.rst
   grammar.rst
PK
%�\�)�1��,html/_sources/reference/introduction.rst.txtnu�[���
.. _introduction:

************
Introduction
************

This reference manual describes the Python programming language. It is not
intended as a tutorial.

While I am trying to be as precise as possible, I chose to use English rather
than formal specifications for everything except syntax and lexical analysis.
This should make the document more understandable to the average reader, but
will leave room for ambiguities. Consequently, if you were coming from Mars and
tried to re-implement Python from this document alone, you might have to guess
things and in fact you would probably end up implementing quite a different
language. On the other hand, if you are using Python and wonder what the precise
rules about a particular area of the language are, you should definitely be able
to find them here. If you would like to see a more formal definition of the
language, maybe you could volunteer your time --- or invent a cloning machine
:-).

It is dangerous to add too many implementation details to a language reference
document --- the implementation may change, and other implementations of the
same language may work differently.  On the other hand, there is currently only
one Python implementation in widespread use (although alternate implementations
exist), and its particular quirks are sometimes worth being mentioned,
especially where the implementation imposes additional limitations.  Therefore,
you'll find short "implementation notes" sprinkled throughout the text.

Every Python implementation comes with a number of built-in and standard
modules.  These are documented in :ref:`library-index`.  A few built-in modules
are mentioned when they interact in a significant way with the language
definition.


.. _implementations:

Alternate Implementations
=========================

Though there is one Python implementation which is by far the most popular,
there are some alternate implementations which are of particular interest to
different audiences.

Known implementations include:

CPython
   This is the original and most-maintained implementation of Python, written in C.
   New language features generally appear here first.

Jython
   Python implemented in Java.  This implementation can be used as a scripting
   language for Java applications, or can be used to create applications using the
   Java class libraries.  It is also often used to create tests for Java libraries.
   More information can be found at `the Jython website <http://www.jython.org/>`_.

Python for .NET
   This implementation actually uses the CPython implementation, but is a managed
   .NET application and makes .NET libraries available.  It was created by Brian
   Lloyd.  For more information, see the `Python for .NET home page
   <https://pythonnet.github.io/>`_.

IronPython
   An alternate Python for .NET.  Unlike Python.NET, this is a complete Python
   implementation that generates IL, and compiles Python code directly to .NET
   assemblies.  It was created by Jim Hugunin, the original creator of Jython.  For
   more information, see `the IronPython website <http://ironpython.net/>`_.

PyPy
   An implementation of Python written completely in Python. It supports several
   advanced features not found in other implementations like stackless support
   and a Just in Time compiler. One of the goals of the project is to encourage
   experimentation with the language itself by making it easier to modify the
   interpreter (since it is written in Python).  Additional information is
   available on `the PyPy project's home page <http://pypy.org/>`_.

Each of these implementations varies in some way from the language as documented
in this manual, or introduces specific information beyond what's covered in the
standard Python documentation.  Please refer to the implementation-specific
documentation to determine what else you need to know about the specific
implementation you're using.


.. _notation:

Notation
========

.. index::
   single: BNF
   single: grammar
   single: syntax
   single: notation

The descriptions of lexical analysis and syntax use a modified BNF grammar
notation.  This uses the following style of definition:

.. productionlist:: *
   name: `lc_letter` (`lc_letter` | "_")*
   lc_letter: "a"..."z"

The first line says that a ``name`` is an ``lc_letter`` followed by a sequence
of zero or more ``lc_letter``\ s and underscores.  An ``lc_letter`` in turn is
any of the single characters ``'a'`` through ``'z'``.  (This rule is actually
adhered to for the names defined in lexical and grammar rules in this document.)

Each rule begins with a name (which is the name defined by the rule) and
``::=``.  A vertical bar (``|``) is used to separate alternatives; it is the
least binding operator in this notation.  A star (``*``) means zero or more
repetitions of the preceding item; likewise, a plus (``+``) means one or more
repetitions, and a phrase enclosed in square brackets (``[ ]``) means zero or
one occurrences (in other words, the enclosed phrase is optional).  The ``*``
and ``+`` operators bind as tightly as possible; parentheses are used for
grouping.  Literal strings are enclosed in quotes.  White space is only
meaningful to separate tokens. Rules are normally contained on a single line;
rules with many alternatives may be formatted alternatively with each line after
the first beginning with a vertical bar.

.. index::
   single: lexical definitions
   single: ASCII@ASCII

In lexical definitions (as the example above), two more conventions are used:
Two literal characters separated by three dots mean a choice of any single
character in the given (inclusive) range of ASCII characters.  A phrase between
angular brackets (``<...>``) gives an informal description of the symbol
defined; e.g., this could be used to describe the notion of 'control character'
if needed.

Even though the notation used is almost the same, there is a big difference
between the meaning of lexical and syntactic definitions: a lexical definition
operates on the individual characters of the input source, while a syntax
definition operates on the stream of tokens generated by the lexical analysis.
All uses of BNF in the next chapter ("Lexical Analysis") are lexical
definitions; uses in subsequent chapters are syntactic definitions.

PK
%�\�F~`�q�q0html/_sources/reference/lexical_analysis.rst.txtnu�[���
.. _lexical:

****************
Lexical analysis
****************

.. index::
   single: lexical analysis
   single: parser
   single: token

A Python program is read by a *parser*.  Input to the parser is a stream of
*tokens*, generated by the *lexical analyzer*.  This chapter describes how the
lexical analyzer breaks a file into tokens.

Python uses the 7-bit ASCII character set for program text.

.. versionadded:: 2.3
   An encoding declaration can be used to indicate that  string literals and
   comments use an encoding different from ASCII.

For compatibility with older versions, Python only warns if it finds 8-bit
characters; those warnings should be corrected by either declaring an explicit
encoding, or using escape sequences if those bytes are binary data, instead of
characters.

The run-time character set depends on the I/O devices connected to the program
but is generally a superset of ASCII.

**Future compatibility note:** It may be tempting to assume that the character
set for 8-bit characters is ISO Latin-1 (an ASCII superset that covers most
western languages that use the Latin alphabet), but it is possible that in the
future Unicode text editors will become common.  These generally use the UTF-8
encoding, which is also an ASCII superset, but with very different use for the
characters with ordinals 128-255.  While there is no consensus on this subject
yet, it is unwise to assume either Latin-1 or UTF-8, even though the current
implementation appears to favor Latin-1.  This applies both to the source
character set and the run-time character set.


.. _line-structure:

Line structure
==============

.. index:: single: line structure

A Python program is divided into a number of *logical lines*.


.. _logical:

Logical lines
-------------

.. index::
   single: logical line
   single: physical line
   single: line joining
   single: NEWLINE token

The end of a logical line is represented by the token NEWLINE.  Statements
cannot cross logical line boundaries except where NEWLINE is allowed by the
syntax (e.g., between statements in compound statements). A logical line is
constructed from one or more *physical lines* by following the explicit or
implicit *line joining* rules.


.. _physical:

Physical lines
--------------

A physical line is a sequence of characters terminated by an end-of-line
sequence.  In source files and strings, any of the standard platform line
termination sequences can be used - the Unix form using ASCII LF (linefeed),
the Windows form using the ASCII sequence CR LF (return followed by linefeed),
or the old Macintosh form using the ASCII CR (return) character.  All of these
forms can be used equally, regardless of platform. The end of input also serves
as an implicit terminator for the final physical line.

When embedding Python, source code strings should be passed to Python APIs using
the standard C conventions for newline characters (the ``\n`` character,
representing ASCII LF, is the line terminator).


.. _comments:

Comments
--------

.. index::
   single: comment
   single: hash character

A comment starts with a hash character (``#``) that is not part of a string
literal, and ends at the end of the physical line.  A comment signifies the end
of the logical line unless the implicit line joining rules are invoked. Comments
are ignored by the syntax; they are not tokens.


.. _encodings:

Encoding declarations
---------------------

.. index:: source character set, encoding declarations (source file)

If a comment in the first or second line of the Python script matches the
regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
encoding declaration; the first group of this expression names the encoding of
the source code file. The encoding declaration must appear on a line of its
own. If it is the second line, the first line must also be a comment-only line.
The recommended forms of an encoding expression are ::

   # -*- coding: <encoding-name> -*-

which is recognized also by GNU Emacs, and ::

   # vim:fileencoding=<encoding-name>

which is recognized by Bram Moolenaar's VIM. In addition, if the first bytes of
the file are the UTF-8 byte-order mark (``'\xef\xbb\xbf'``), the declared file
encoding is UTF-8 (this is supported, among others, by Microsoft's
:program:`notepad`).

If an encoding is declared, the encoding name must be recognized by Python. The
encoding is used for all lexical analysis, in particular to find the end of a
string, and to interpret the contents of Unicode literals. String literals are
converted to Unicode for syntactical analysis, then converted back to their
original encoding before interpretation starts.

.. XXX there should be a list of supported encodings.


.. _explicit-joining:

Explicit line joining
---------------------

.. index::
   single: physical line
   single: line joining
   single: line continuation
   single: backslash character

Two or more physical lines may be joined into logical lines using backslash
characters (``\``), as follows: when a physical line ends in a backslash that is
not part of a string literal or comment, it is joined with the following forming
a single logical line, deleting the backslash and the following end-of-line
character.  For example::

   if 1900 < year < 2100 and 1 <= month <= 12 \
      and 1 <= day <= 31 and 0 <= hour < 24 \
      and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
           return 1

A line ending in a backslash cannot carry a comment.  A backslash does not
continue a comment.  A backslash does not continue a token except for string
literals (i.e., tokens other than string literals cannot be split across
physical lines using a backslash).  A backslash is illegal elsewhere on a line
outside a string literal.


.. _implicit-joining:

Implicit line joining
---------------------

Expressions in parentheses, square brackets or curly braces can be split over
more than one physical line without using backslashes. For example::

   month_names = ['Januari', 'Februari', 'Maart',      # These are the
                  'April',   'Mei',      'Juni',       # Dutch names
                  'Juli',    'Augustus', 'September',  # for the months
                  'Oktober', 'November', 'December']   # of the year

Implicitly continued lines can carry comments.  The indentation of the
continuation lines is not important.  Blank continuation lines are allowed.
There is no NEWLINE token between implicit continuation lines.  Implicitly
continued lines can also occur within triple-quoted strings (see below); in that
case they cannot carry comments.


.. _blank-lines:

Blank lines
-----------

.. index:: single: blank line

A logical line that contains only spaces, tabs, formfeeds and possibly a
comment, is ignored (i.e., no NEWLINE token is generated).  During interactive
input of statements, handling of a blank line may differ depending on the
implementation of the read-eval-print loop.  In the standard implementation, an
entirely blank logical line (i.e. one containing not even whitespace or a
comment) terminates a multi-line statement.


.. _indentation:

Indentation
-----------

.. index::
   single: indentation
   single: whitespace
   single: leading whitespace
   single: space
   single: tab
   single: grouping
   single: statement grouping

Leading whitespace (spaces and tabs) at the beginning of a logical line is used
to compute the indentation level of the line, which in turn is used to determine
the grouping of statements.

First, tabs are replaced (from left to right) by one to eight spaces such that
the total number of characters up to and including the replacement is a multiple
of eight (this is intended to be the same rule as used by Unix).  The total
number of spaces preceding the first non-blank character then determines the
line's indentation.  Indentation cannot be split over multiple physical lines
using backslashes; the whitespace up to the first backslash determines the
indentation.

**Cross-platform compatibility note:** because of the nature of text editors on
non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
indentation in a single source file.  It should also be noted that different
platforms may explicitly limit the maximum indentation level.

A formfeed character may be present at the start of the line; it will be ignored
for the indentation calculations above.  Formfeed characters occurring elsewhere
in the leading whitespace have an undefined effect (for instance, they may reset
the space count to zero).

.. index::
   single: INDENT token
   single: DEDENT token

The indentation levels of consecutive lines are used to generate INDENT and
DEDENT tokens, using a stack, as follows.

Before the first line of the file is read, a single zero is pushed on the stack;
this will never be popped off again.  The numbers pushed on the stack will
always be strictly increasing from bottom to top.  At the beginning of each
logical line, the line's indentation level is compared to the top of the stack.
If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
one INDENT token is generated.  If it is smaller, it *must* be one of the
numbers occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a DEDENT token is generated.  At the
end of the file, a DEDENT token is generated for each number remaining on the
stack that is larger than zero.

Here is an example of a correctly (though confusingly) indented piece of Python
code::

   def perm(l):
           # Compute the list of all permutations of l
       if len(l) <= 1:
                     return [l]
       r = []
       for i in range(len(l)):
                s = l[:i] + l[i+1:]
                p = perm(s)
                for x in p:
                 r.append(l[i:i+1] + x)
       return r

The following example shows various indentation errors::

    def perm(l):                       # error: first line indented
   for i in range(len(l)):             # error: not indented
       s = l[:i] + l[i+1:]
           p = perm(l[:i] + l[i+1:])   # error: unexpected indent
           for x in p:
                   r.append(l[i:i+1] + x)
               return r                # error: inconsistent dedent

(Actually, the first three errors are detected by the parser; only the last
error is found by the lexical analyzer --- the indentation of ``return r`` does
not match a level popped off the stack.)


.. _whitespace:

Whitespace between tokens
-------------------------

Except at the beginning of a logical line or in string literals, the whitespace
characters space, tab and formfeed can be used interchangeably to separate
tokens.  Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token (e.g., ab is one token, but
a b is two tokens).


.. _other-tokens:

Other tokens
============

Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
characters (other than line terminators, discussed earlier) are not tokens, but
serve to delimit tokens. Where ambiguity exists, a token comprises the longest
possible string that forms a legal token, when read from left to right.


.. _identifiers:

Identifiers and keywords
========================

.. index::
   single: identifier
   single: name

Identifiers (also referred to as *names*) are described by the following lexical
definitions:

.. productionlist::
   identifier: (`letter`|"_") (`letter` | `digit` | "_")*
   letter: `lowercase` | `uppercase`
   lowercase: "a"..."z"
   uppercase: "A"..."Z"
   digit: "0"..."9"

Identifiers are unlimited in length.  Case is significant.


.. _keywords:

Keywords
--------

.. index::
   single: keyword
   single: reserved word

The following identifiers are used as reserved words, or *keywords* of the
language, and cannot be used as ordinary identifiers.  They must be spelled
exactly as written here:

.. sourcecode:: text

   and       del       from      not       while
   as        elif      global    or        with
   assert    else      if        pass      yield
   break     except    import    print
   class     exec      in        raise
   continue  finally   is        return
   def       for       lambda    try

.. versionchanged:: 2.4
   :const:`None` became a constant and is now recognized by the compiler as a name
   for the built-in object :const:`None`.  Although it is not a keyword, you cannot
   assign a different object to it.

.. versionchanged:: 2.5
   Using :keyword:`as` and :keyword:`with` as identifiers triggers a warning.  To
   use them as keywords, enable the ``with_statement`` future feature .

.. versionchanged:: 2.6
    :keyword:`as` and :keyword:`with` are full keywords.


.. _id-classes:

Reserved classes of identifiers
-------------------------------

Certain classes of identifiers (besides keywords) have special meanings.  These
classes are identified by the patterns of leading and trailing underscore
characters:

``_*``
   Not imported by ``from module import *``.  The special identifier ``_`` is used
   in the interactive interpreter to store the result of the last evaluation; it is
   stored in the :mod:`__builtin__` module.  When not in interactive mode, ``_``
   has no special meaning and is not defined. See section :ref:`import`.

   .. note::

      The name ``_`` is often used in conjunction with internationalization;
      refer to the documentation for the :mod:`gettext` module for more
      information on this convention.

``__*__``
   System-defined names. These names are defined by the interpreter and its
   implementation (including the standard library).  Current system names are
   discussed in the :ref:`specialnames` section and elsewhere.  More will likely
   be defined in future versions of Python.  *Any* use of ``__*__`` names, in
   any context, that does not follow explicitly documented use, is subject to
   breakage without warning.

``__*``
   Class-private names.  Names in this category, when used within the context of a
   class definition, are re-written to use a mangled form to help avoid name
   clashes between "private" attributes of base and derived classes. See section
   :ref:`atom-identifiers`.


.. _literals:

Literals
========

.. index::
   single: literal
   single: constant

Literals are notations for constant values of some built-in types.


.. _strings:

String literals
---------------

.. index:: single: string literal

String literals are described by the following lexical definitions:

.. index:: single: ASCII@ASCII

.. productionlist::
   stringliteral: [`stringprefix`](`shortstring` | `longstring`)
   stringprefix: "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"
               : | "b" | "B" | "br" | "Br" | "bR" | "BR"
   shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
   longstring: "'''" `longstringitem`* "'''"
             : | '"""' `longstringitem`* '"""'
   shortstringitem: `shortstringchar` | `escapeseq`
   longstringitem: `longstringchar` | `escapeseq`
   shortstringchar: <any source character except "\" or newline or the quote>
   longstringchar: <any source character except "\">
   escapeseq: "\" <any ASCII character>

One syntactic restriction not indicated by these productions is that whitespace
is not allowed between the :token:`stringprefix` and the rest of the string
literal. The source character set is defined by the encoding declaration; it is
ASCII if no encoding declaration is given in the source file; see section
:ref:`encodings`.

.. index::
   single: triple-quoted string
   single: Unicode Consortium
   single: string; Unicode
   single: raw string

In plain English: String literals can be enclosed in matching single quotes
(``'``) or double quotes (``"``).  They can also be enclosed in matching groups
of three single or double quotes (these are generally referred to as
*triple-quoted strings*).  The backslash (``\``) character is used to escape
characters that otherwise have a special meaning, such as newline, backslash
itself, or the quote character.  String literals may optionally be prefixed with
a letter ``'r'`` or ``'R'``; such strings are called :dfn:`raw strings` and use
different rules for interpreting backslash escape sequences.  A prefix of
``'u'`` or ``'U'`` makes the string a Unicode string.  Unicode strings use the
Unicode character set as defined by the Unicode Consortium and ISO 10646.  Some
additional escape sequences, described below, are available in Unicode strings.
A prefix of ``'b'`` or ``'B'`` is ignored in Python 2; it indicates that the
literal should become a bytes literal in Python 3 (e.g. when code is
automatically converted with 2to3).  A ``'u'`` or ``'b'`` prefix may be followed
by an ``'r'`` prefix.

In triple-quoted strings, unescaped newlines and quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the string.  (A
"quote" is the character used to open the string, i.e. either ``'`` or ``"``.)

.. index::
   single: physical line
   single: escape sequence
   single: Standard C
   single: C

Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in strings are
interpreted according to rules similar to those used by Standard C.  The
recognized escape sequences are:

+-----------------+---------------------------------+-------+
| Escape Sequence | Meaning                         | Notes |
+=================+=================================+=======+
| ``\newline``    | Ignored                         |       |
+-----------------+---------------------------------+-------+
| ``\\``          | Backslash (``\``)               |       |
+-----------------+---------------------------------+-------+
| ``\'``          | Single quote (``'``)            |       |
+-----------------+---------------------------------+-------+
| ``\"``          | Double quote (``"``)            |       |
+-----------------+---------------------------------+-------+
| ``\a``          | ASCII Bell (BEL)                |       |
+-----------------+---------------------------------+-------+
| ``\b``          | ASCII Backspace (BS)            |       |
+-----------------+---------------------------------+-------+
| ``\f``          | ASCII Formfeed (FF)             |       |
+-----------------+---------------------------------+-------+
| ``\n``          | ASCII Linefeed (LF)             |       |
+-----------------+---------------------------------+-------+
| ``\N{name}``    | Character named *name* in the   |       |
|                 | Unicode database (Unicode only) |       |
+-----------------+---------------------------------+-------+
| ``\r``          | ASCII Carriage Return (CR)      |       |
+-----------------+---------------------------------+-------+
| ``\t``          | ASCII Horizontal Tab (TAB)      |       |
+-----------------+---------------------------------+-------+
| ``\uxxxx``      | Character with 16-bit hex value | \(1)  |
|                 | *xxxx* (Unicode only)           |       |
+-----------------+---------------------------------+-------+
| ``\Uxxxxxxxx``  | Character with 32-bit hex value | \(2)  |
|                 | *xxxxxxxx* (Unicode only)       |       |
+-----------------+---------------------------------+-------+
| ``\v``          | ASCII Vertical Tab (VT)         |       |
+-----------------+---------------------------------+-------+
| ``\ooo``        | Character with octal value      | (3,5) |
|                 | *ooo*                           |       |
+-----------------+---------------------------------+-------+
| ``\xhh``        | Character with hex value *hh*   | (4,5) |
+-----------------+---------------------------------+-------+

.. index:: single: ASCII@ASCII

Notes:

(1)
   Individual code units which form parts of a surrogate pair can be encoded using
   this escape sequence.

(2)
   Any Unicode character can be encoded this way, but characters outside the Basic
   Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is
   compiled to use 16-bit code units (the default).

(3)
   As in Standard C, up to three octal digits are accepted.

(4)
   Unlike in Standard C, exactly two hex digits are required.

(5)
   In a string literal, hexadecimal and octal escapes denote the byte with the
   given value; it is not necessary that the byte encodes a character in the source
   character set. In a Unicode literal, these escapes denote a Unicode character
   with the given value.

.. index:: single: unrecognized escape sequence

Unlike Standard C, all unrecognized escape sequences are left in the string
unchanged, i.e., *the backslash is left in the string*.  (This behavior is
useful when debugging: if an escape sequence is mistyped, the resulting output
is more easily recognized as broken.)  It is also important to note that the
escape sequences marked as "(Unicode only)" in the table above fall into the
category of unrecognized escapes for non-Unicode string literals.

When an ``'r'`` or ``'R'`` prefix is present, a character following a backslash
is included in the string without change, and *all backslashes are left in the
string*.  For example, the string literal ``r"\n"`` consists of two characters:
a backslash and a lowercase ``'n'``.  String quotes can be escaped with a
backslash, but the backslash remains in the string; for example, ``r"\""`` is a
valid string literal consisting of two characters: a backslash and a double
quote; ``r"\"`` is not a valid string literal (even a raw string cannot end in
an odd number of backslashes).  Specifically, *a raw string cannot end in a
single backslash* (since the backslash would escape the following quote
character).  Note also that a single backslash followed by a newline is
interpreted as those two characters as part of the string, *not* as a line
continuation.

When an ``'r'`` or ``'R'`` prefix is used in conjunction with a ``'u'`` or
``'U'`` prefix, then the ``\uXXXX`` and ``\UXXXXXXXX`` escape sequences are
processed while  *all other backslashes are left in the string*. For example,
the string literal ``ur"\u0062\n"`` consists of three Unicode characters: 'LATIN
SMALL LETTER B', 'REVERSE SOLIDUS', and 'LATIN SMALL LETTER N'. Backslashes can
be escaped with a preceding backslash; however, both remain in the string.  As a
result, ``\uXXXX`` escape sequences are only recognized when there are an odd
number of backslashes.


.. _string-catenation:

String literal concatenation
----------------------------

Multiple adjacent string literals (delimited by whitespace), possibly using
different quoting conventions, are allowed, and their meaning is the same as
their concatenation.  Thus, ``"hello" 'world'`` is equivalent to
``"helloworld"``.  This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings, for example::

   re.compile("[A-Za-z_]"       # letter or underscore
              "[A-Za-z0-9_]*"   # letter, digit or underscore
             )

Note that this feature is defined at the syntactical level, but implemented at
compile time.  The '+' operator must be used to concatenate string expressions
at run time.  Also note that literal concatenation can use different quoting
styles for each component (even mixing raw strings and triple quoted strings).


.. _numbers:

Numeric literals
----------------

.. index::
   single: number
   single: numeric literal
   single: integer literal
   single: plain integer literal
   single: long integer literal
   single: floating point literal
   single: hexadecimal literal
   single: binary literal
   single: octal literal
   single: decimal literal
   single: imaginary literal
   single: complex; literal

There are four types of numeric literals: plain integers, long integers,
floating point numbers, and imaginary numbers.  There are no complex literals
(complex numbers can be formed by adding a real number and an imaginary number).

Note that numeric literals do not include a sign; a phrase like ``-1`` is
actually an expression composed of the unary operator '``-``' and the literal
``1``.


.. _integers:

Integer and long integer literals
---------------------------------

Integer and long integer literals are described by the following lexical
definitions:

.. productionlist::
   longinteger: `integer` ("l" | "L")
   integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger`
   decimalinteger: `nonzerodigit` `digit`* | "0"
   octinteger: "0" ("o" | "O") `octdigit`+ | "0" `octdigit`+
   hexinteger: "0" ("x" | "X") `hexdigit`+
   bininteger: "0" ("b" | "B") `bindigit`+
   nonzerodigit: "1"..."9"
   octdigit: "0"..."7"
   bindigit: "0" | "1"
   hexdigit: `digit` | "a"..."f" | "A"..."F"

Although both lower case ``'l'`` and upper case ``'L'`` are allowed as suffix
for long integers, it is strongly recommended to always use ``'L'``, since the
letter ``'l'`` looks too much like the digit ``'1'``.

Plain integer literals that are above the largest representable plain integer
(e.g., 2147483647 when using 32-bit arithmetic) are accepted as if they were
long integers instead. [#]_  There is no limit for long integer literals apart
from what can be stored in available memory.

Some examples of plain integer literals (first row) and long integer literals
(second and third rows)::

   7     2147483647                        0177
   3L    79228162514264337593543950336L    0377L   0x100000000L
         79228162514264337593543950336             0xdeadbeef


.. _floating:

Floating point literals
-----------------------

Floating point literals are described by the following lexical definitions:

.. productionlist::
   floatnumber: `pointfloat` | `exponentfloat`
   pointfloat: [`intpart`] `fraction` | `intpart` "."
   exponentfloat: (`intpart` | `pointfloat`) `exponent`
   intpart: `digit`+
   fraction: "." `digit`+
   exponent: ("e" | "E") ["+" | "-"] `digit`+

Note that the integer and exponent parts of floating point numbers can look like
octal integers, but are interpreted using radix 10.  For example, ``077e010`` is
legal, and denotes the same number as ``77e10``. The allowed range of floating
point literals is implementation-dependent. Some examples of floating point
literals::

   3.14    10.    .001    1e100    3.14e-10    0e0

Note that numeric literals do not include a sign; a phrase like ``-1`` is
actually an expression composed of the unary operator ``-`` and the literal
``1``.


.. _imaginary:

Imaginary literals
------------------

Imaginary literals are described by the following lexical definitions:

.. productionlist::
   imagnumber: (`floatnumber` | `intpart`) ("j" | "J")

An imaginary literal yields a complex number with a real part of 0.0.  Complex
numbers are represented as a pair of floating point numbers and have the same
restrictions on their range.  To create a complex number with a nonzero real
part, add a floating point number to it, e.g., ``(3+4j)``.  Some examples of
imaginary literals::

   3.14j   10.j    10j     .001j   1e100j  3.14e-10j


.. _operators:

Operators
=========

.. index:: single: operators

The following tokens are operators:

.. code-block:: none


   +       -       *       **      /       //      %
   <<      >>      &       |       ^       ~
   <       >       <=      >=      ==      !=      <>

The comparison operators ``<>`` and ``!=`` are alternate spellings of the same
operator.  ``!=`` is the preferred spelling; ``<>`` is obsolescent.


.. _delimiters:

Delimiters
==========

.. index:: single: delimiters

The following tokens serve as delimiters in the grammar:

.. code-block:: none

   (       )       [       ]       {       }      @
   ,       :       .       `       =       ;
   +=      -=      *=      /=      //=     %=
   &=      |=      ^=      >>=     <<=     **=

The period can also occur in floating-point and imaginary literals.  A sequence
of three periods has a special meaning as an ellipsis in slices. The second half
of the list, the augmented assignment operators, serve lexically as delimiters,
but also perform an operation.

The following printing ASCII characters have special meaning as part of other
tokens or are otherwise significant to the lexical analyzer:

.. code-block:: none

   '       "       #       \

.. index:: single: ASCII@ASCII

The following printing ASCII characters are not used in Python.  Their
occurrence outside string literals and comments is an unconditional error:

.. code-block:: none

   $       ?

.. rubric:: Footnotes

.. [#] In versions of Python prior to 2.4, octal and hexadecimal literals in the range
   just above the largest representable plain integer but below the largest
   unsigned 32-bit number (on a machine using 32-bit arithmetic), 4294967296, were
   taken as the negative plain integer obtained by subtracting 4294967296 from
   their unsigned value.

PK
%�\|l5�5�,html/_sources/reference/simple_stmts.rst.txtnu�[���
.. _simple:

*****************
Simple statements
*****************

.. index:: pair: simple; statement

Simple statements are comprised within a single logical line. Several simple
statements may occur on a single line separated by semicolons.  The syntax for
simple statements is:

.. productionlist::
   simple_stmt: `expression_stmt`
              : | `assert_stmt`
              : | `assignment_stmt`
              : | `augmented_assignment_stmt`
              : | `pass_stmt`
              : | `del_stmt`
              : | `print_stmt`
              : | `return_stmt`
              : | `yield_stmt`
              : | `raise_stmt`
              : | `break_stmt`
              : | `continue_stmt`
              : | `import_stmt`
              : | `future_stmt`
              : | `global_stmt`
              : | `exec_stmt`


.. _exprstmts:

Expression statements
=====================

.. index::
   pair: expression; statement
   pair: expression; list

Expression statements are used (mostly interactively) to compute and write a
value, or (usually) to call a procedure (a function that returns no meaningful
result; in Python, procedures return the value ``None``).  Other uses of
expression statements are allowed and occasionally useful.  The syntax for an
expression statement is:

.. productionlist::
   expression_stmt: `expression_list`

An expression statement evaluates the expression list (which may be a single
expression).

.. index::
   builtin: repr
   object: None
   pair: string; conversion
   single: output
   pair: standard; output
   pair: writing; values
   pair: procedure; call

In interactive mode, if the value is not ``None``, it is converted to a string
using the built-in :func:`repr` function and the resulting string is written to
standard output (see section :ref:`print`) on a line by itself.  (Expression
statements yielding ``None`` are not written, so that procedure calls do not
cause any output.)


.. _assignment:

Assignment statements
=====================

.. index::
   single: =; assignment statement
   pair: assignment; statement
   pair: binding; name
   pair: rebinding; name
   object: mutable
   pair: attribute; assignment

Assignment statements are used to (re)bind names to values and to modify
attributes or items of mutable objects:

.. productionlist::
   assignment_stmt: (`target_list` "=")+ (`expression_list` | `yield_expression`)
   target_list: `target` ("," `target`)* [","]
   target: `identifier`
         : | "(" `target_list` ")"
         : | "[" [`target_list`] "]"
         : | `attributeref`
         : | `subscription`
         : | `slicing`

(See section :ref:`primaries` for the syntax definitions for the last three
symbols.)

.. index:: pair: expression; list

An assignment statement evaluates the expression list (remember that this can be
a single expression or a comma-separated list, the latter yielding a tuple) and
assigns the single resulting object to each of the target lists, from left to
right.

.. index::
   single: target
   pair: target; list

Assignment is defined recursively depending on the form of the target (list).
When a target is part of a mutable object (an attribute reference, subscription
or slicing), the mutable object must ultimately perform the assignment and
decide about its validity, and may raise an exception if the assignment is
unacceptable.  The rules observed by various types and the exceptions raised are
given with the definition of the object types (see section :ref:`types`).

.. index:: triple: target; list; assignment

Assignment of an object to a target list is recursively defined as follows.

* If the target list is a single target: The object is assigned to that target.

* If the target list is a comma-separated list of targets: The object must be an
  iterable with the same number of items as there are targets in the target list,
  and the items are assigned, from left to right, to the corresponding targets.

Assignment of an object to a single target is recursively defined as follows.

* If the target is an identifier (name):

    .. index:: statement: global

  * If the name does not occur in a :keyword:`global` statement in the current
    code block: the name is bound to the object in the current local namespace.

  * Otherwise: the name is bound to the object in the current global namespace.

  .. index:: single: destructor

  The name is rebound if it was already bound.  This may cause the reference count
  for the object previously bound to the name to reach zero, causing the object to
  be deallocated and its destructor (if it has one) to be called.

* If the target is a target list enclosed in parentheses or in square brackets:
  The object must be an iterable with the same number of items as there are
  targets in the target list, and its items are assigned, from left to right,
  to the corresponding targets.

  .. index:: pair: attribute; assignment

* If the target is an attribute reference: The primary expression in the
  reference is evaluated.  It should yield an object with assignable attributes;
  if this is not the case, :exc:`TypeError` is raised.  That object is then
  asked to assign the assigned object to the given attribute; if it cannot
  perform the assignment, it raises an exception (usually but not necessarily
  :exc:`AttributeError`).

  .. _attr-target-note:

  Note: If the object is a class instance and the attribute reference occurs on
  both sides of the assignment operator, the RHS expression, ``a.x`` can access
  either an instance attribute or (if no instance attribute exists) a class
  attribute.  The LHS target ``a.x`` is always set as an instance attribute,
  creating it if necessary.  Thus, the two occurrences of ``a.x`` do not
  necessarily refer to the same attribute: if the RHS expression refers to a
  class attribute, the LHS creates a new instance attribute as the target of the
  assignment::

     class Cls:
         x = 3             # class variable
     inst = Cls()
     inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3

  This description does not necessarily apply to descriptor attributes, such as
  properties created with :func:`property`.

  .. index::
     pair: subscription; assignment
     object: mutable

* If the target is a subscription: The primary expression in the reference is
  evaluated.  It should yield either a mutable sequence object (such as a list) or
  a mapping object (such as a dictionary). Next, the subscript expression is
  evaluated.

  .. index::
     object: sequence
     object: list

  If the primary is a mutable sequence object (such as a list), the subscript must
  yield a plain integer.  If it is negative, the sequence's length is added to it.
  The resulting value must be a nonnegative integer less than the sequence's
  length, and the sequence is asked to assign the assigned object to its item with
  that index.  If the index is out of range, :exc:`IndexError` is raised
  (assignment to a subscripted sequence cannot add new items to a list).

  .. index::
     object: mapping
     object: dictionary

  If the primary is a mapping object (such as a dictionary), the subscript must
  have a type compatible with the mapping's key type, and the mapping is then
  asked to create a key/datum pair which maps the subscript to the assigned
  object.  This can either replace an existing key/value pair with the same key
  value, or insert a new key/value pair (if no key with the same value existed).

  .. index:: pair: slicing; assignment

* If the target is a slicing: The primary expression in the reference is
  evaluated.  It should yield a mutable sequence object (such as a list).  The
  assigned object should be a sequence object of the same type.  Next, the lower
  and upper bound expressions are evaluated, insofar they are present; defaults
  are zero and the sequence's length.  The bounds should evaluate to (small)
  integers.  If either bound is negative, the sequence's length is added to it.
  The resulting bounds are clipped to lie between zero and the sequence's length,
  inclusive.  Finally, the sequence object is asked to replace the slice with the
  items of the assigned sequence.  The length of the slice may be different from
  the length of the assigned sequence, thus changing the length of the target
  sequence, if the object allows it.

.. impl-detail::

   In the current implementation, the syntax for targets is taken to be the same
   as for expressions, and invalid syntax is rejected during the code generation
   phase, causing less detailed error messages.

WARNING: Although the definition of assignment implies that overlaps between the
left-hand side and the right-hand side are 'safe' (for example ``a, b = b, a``
swaps two variables), overlaps *within* the collection of assigned-to variables
are not safe!  For instance, the following program prints ``[0, 2]``::

   x = [0, 1]
   i = 0
   i, x[i] = 1, 2
   print x


.. _augassign:

Augmented assignment statements
-------------------------------

.. index::
   pair: augmented; assignment
   single: statement; assignment, augmented
   single: +=; augmented assignment
   single: -=; augmented assignment
   single: *=; augmented assignment
   single: /=; augmented assignment
   single: %=; augmented assignment
   single: &=; augmented assignment
   single: ^=; augmented assignment
   single: |=; augmented assignment
   single: **=; augmented assignment
   single: //=; augmented assignment
   single: >>=; augmented assignment
   single: <<=; augmented assignment

Augmented assignment is the combination, in a single statement, of a binary
operation and an assignment statement:

.. productionlist::
   augmented_assignment_stmt: `augtarget` `augop` (`expression_list` | `yield_expression`)
   augtarget: `identifier` | `attributeref` | `subscription` | `slicing`
   augop: "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="
        : | ">>=" | "<<=" | "&=" | "^=" | "|="

(See section :ref:`primaries` for the syntax definitions for the last three
symbols.)

An augmented assignment evaluates the target (which, unlike normal assignment
statements, cannot be an unpacking) and the expression list, performs the binary
operation specific to the type of assignment on the two operands, and assigns
the result to the original target.  The target is only evaluated once.

An augmented assignment expression like ``x += 1`` can be rewritten as ``x = x +
1`` to achieve a similar, but not exactly equal effect. In the augmented
version, ``x`` is only evaluated once. Also, when possible, the actual operation
is performed *in-place*, meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead.

With the exception of assigning to tuples and multiple targets in a single
statement, the assignment done by augmented assignment statements is handled the
same way as normal assignments. Similarly, with the exception of the possible
*in-place* behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations.

For targets which are attribute references, the same :ref:`caveat about class
and instance attributes <attr-target-note>` applies as for regular assignments.


.. _assert:

The :keyword:`assert` statement
===============================

.. index::
   statement: assert
   pair: debugging; assertions

Assert statements are a convenient way to insert debugging assertions into a
program:

.. productionlist::
   assert_stmt: "assert" `expression` ["," `expression`]

The simple form, ``assert expression``, is equivalent to ::

   if __debug__:
       if not expression: raise AssertionError

The extended form, ``assert expression1, expression2``, is equivalent to ::

   if __debug__:
       if not expression1: raise AssertionError(expression2)

.. index::
   single: __debug__
   exception: AssertionError

These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
the built-in variables with those names.  In the current implementation, the
built-in variable :const:`__debug__` is ``True`` under normal circumstances,
``False`` when optimization is requested (command line option -O).  The current
code generator emits no code for an assert statement when optimization is
requested at compile time.  Note that it is unnecessary to include the source
code for the expression that failed in the error message; it will be displayed
as part of the stack trace.

Assignments to :const:`__debug__` are illegal.  The value for the built-in variable
is determined when the interpreter starts.


.. _pass:

The :keyword:`pass` statement
=============================

.. index::
   statement: pass
   pair: null; operation

.. productionlist::
   pass_stmt: "pass"

:keyword:`pass` is a null operation --- when it is executed, nothing happens.
It is useful as a placeholder when a statement is required syntactically, but no
code needs to be executed, for example::

   def f(arg): pass    # a function that does nothing (yet)

   class C: pass       # a class with no methods (yet)


.. _del:

The :keyword:`del` statement
============================

.. index::
   statement: del
   pair: deletion; target
   triple: deletion; target; list

.. productionlist::
   del_stmt: "del" `target_list`

Deletion is recursively defined very similar to the way assignment is defined.
Rather than spelling it out in full details, here are some hints.

Deletion of a target list recursively deletes each target, from left to right.

.. index::
   statement: global
   pair: unbinding; name

Deletion of a name removes the binding of that name  from the local or global
namespace, depending on whether the name occurs in a :keyword:`global` statement
in the same code block.  If the name is unbound, a :exc:`NameError` exception
will be raised.

.. index:: pair: free; variable

It is illegal to delete a name from the local namespace if it occurs as a free
variable in a nested block.

.. index:: pair: attribute; deletion

Deletion of attribute references, subscriptions and slicings is passed to the
primary object involved; deletion of a slicing is in general equivalent to
assignment of an empty slice of the right type (but even this is determined by
the sliced object).


.. _print:

The :keyword:`print` statement
==============================

.. index:: statement: print

.. productionlist::
   print_stmt: "print" ([`expression` ("," `expression`)* [","]]
             : | ">>" `expression` [("," `expression`)+ [","]])

:keyword:`print` evaluates each expression in turn and writes the resulting
object to standard output (see below).  If an object is not a string, it is
first converted to a string using the rules for string conversions.  The
(resulting or original) string is then written.  A space is written before each
object is (converted and) written, unless the output system believes it is
positioned at the beginning of a line.  This is the case (1) when no characters
have yet been written to standard output, (2) when the last character written to
standard output is a whitespace character except ``' '``, or (3) when the last
write operation on standard output was not a :keyword:`print` statement.
(In some cases it may be functional to write an empty string to standard output
for this reason.)

.. note::

   Objects which act like file objects but which are not the built-in file objects
   often do not properly emulate this aspect of the file object's behavior, so it
   is best not to rely on this.

.. index::
   single: output
   pair: writing; values
   pair: trailing; comma
   pair: newline; suppression

A ``'\n'`` character is written at the end, unless the :keyword:`print`
statement ends with a comma.  This is the only action if the statement contains
just the keyword :keyword:`print`.

.. index::
   pair: standard; output
   module: sys
   single: stdout (in module sys)
   exception: RuntimeError

Standard output is defined as the file object named ``stdout`` in the built-in
module :mod:`sys`.  If no such object exists, or if it does not have a
:meth:`write` method, a :exc:`RuntimeError` exception is raised.

.. index:: single: extended print statement

:keyword:`print` also has an extended form, defined by the second portion of the
syntax described above. This form is sometimes referred to as ":keyword:`print`
chevron." In this form, the first expression after the ``>>`` must evaluate to a
"file-like" object, specifically an object that has a :meth:`write` method as
described above.  With this extended form, the subsequent expressions are
printed to this file object.  If the first expression evaluates to ``None``,
then ``sys.stdout`` is used as the file for output.


.. _return:

The :keyword:`return` statement
===============================

.. index::
   statement: return
   pair: function; definition
   pair: class; definition

.. productionlist::
   return_stmt: "return" [`expression_list`]

:keyword:`return` may only occur syntactically nested in a function definition,
not within a nested class definition.

If an expression list is present, it is evaluated, else ``None`` is substituted.

:keyword:`return` leaves the current function call with the expression list (or
``None``) as return value.

.. index:: keyword: finally

When :keyword:`return` passes control out of a :keyword:`try` statement with a
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
really leaving the function.

In a generator function, the :keyword:`return` statement is not allowed to
include an :token:`expression_list`.  In that context, a bare :keyword:`return`
indicates that the generator is done and will cause :exc:`StopIteration` to be
raised.


.. _yield:

The :keyword:`yield` statement
==============================

.. index::
   statement: yield
   single: generator; function
   single: generator; iterator
   single: function; generator
   exception: StopIteration

.. productionlist::
   yield_stmt: `yield_expression`

The :keyword:`yield` statement is only used when defining a generator function,
and is only used in the body of the generator function. Using a :keyword:`yield`
statement in a function definition is sufficient to cause that definition to
create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator
iterator, or more commonly, a generator.  The body of the generator function is
executed by calling the generator's :meth:`~generator.next` method repeatedly
until it raises an exception.

When a :keyword:`yield` statement is executed, the state of the generator is
frozen and the value of :token:`expression_list` is returned to
:meth:`~generator.next`'s caller.  By "frozen" we mean that all local state is
retained, including the current bindings of local variables, the instruction
pointer, and the internal evaluation stack: enough information is saved so that
the next time :meth:`~generator.next` is invoked, the function can proceed
exactly as if the :keyword:`yield` statement were just another external call.

As of Python version 2.5, the :keyword:`yield` statement is now allowed in the
:keyword:`try` clause of a :keyword:`try` ...  :keyword:`finally` construct.  If
the generator is not resumed before it is finalized (by reaching a zero
reference count or by being garbage collected), the generator-iterator's
:meth:`close` method will be called, allowing any pending :keyword:`finally`
clauses to execute.

For full details of :keyword:`yield` semantics, refer to the :ref:`yieldexpr`
section.

.. note::

   In Python 2.2, the :keyword:`yield` statement was only allowed when the
   ``generators`` feature has been enabled.  This ``__future__``
   import statement was used to enable the feature::

      from __future__ import generators


.. seealso::

   :pep:`255` - Simple Generators
      The proposal for adding generators and the :keyword:`yield` statement to Python.

   :pep:`342` - Coroutines via Enhanced Generators
      The proposal that, among other generator enhancements, proposed allowing
      :keyword:`yield` to appear inside a :keyword:`try` ... :keyword:`finally` block.


.. _raise:

The :keyword:`raise` statement
==============================

.. index::
   statement: raise
   single: exception
   pair: raising; exception

.. productionlist::
   raise_stmt: "raise" [`expression` ["," `expression` ["," `expression`]]]

If no expressions are present, :keyword:`raise` re-raises the last exception
that was active in the current scope.  If no exception is active in the current
scope, a :exc:`TypeError` exception is raised indicating that this is an error
(if running under IDLE, a :exc:`Queue.Empty` exception is raised instead).

Otherwise, :keyword:`raise` evaluates the expressions to get three objects,
using ``None`` as the value of omitted expressions.  The first two objects are
used to determine the *type* and *value* of the exception.

If the first object is an instance, the type of the exception is the class of
the instance, the instance itself is the value, and the second object must be
``None``.

If the first object is a class, it becomes the type of the exception. The second
object is used to determine the exception value: If it is an instance of the
class, the instance becomes the exception value. If the second object is a
tuple, it is used as the argument list for the class constructor; if it is
``None``, an empty argument list is used, and any other object is treated as a
single argument to the constructor.  The instance so created by calling the
constructor is used as the exception value.

.. index:: object: traceback

If a third object is present and not ``None``, it must be a traceback object
(see section :ref:`types`), and it is substituted instead of the current
location as the place where the exception occurred.  If the third object is
present and not a traceback object or ``None``, a :exc:`TypeError` exception is
raised.  The three-expression form of :keyword:`raise` is useful to re-raise an
exception transparently in an except clause, but :keyword:`raise` with no
expressions should be preferred if the exception to be re-raised was the most
recently active exception in the current scope.

Additional information on exceptions can be found in section :ref:`exceptions`,
and information about handling exceptions is in section :ref:`try`.


.. _break:

The :keyword:`break` statement
==============================

.. index::
   statement: break
   statement: for
   statement: while
   pair: loop; statement

.. productionlist::
   break_stmt: "break"

:keyword:`break` may only occur syntactically nested in a :keyword:`for` or
:keyword:`while` loop, but not nested in a function or class definition within
that loop.

.. index:: keyword: else

It terminates the nearest enclosing loop, skipping the optional :keyword:`else`
clause if the loop has one.

.. index:: pair: loop control; target

If a :keyword:`for` loop is terminated by :keyword:`break`, the loop control
target keeps its current value.

.. index:: keyword: finally

When :keyword:`break` passes control out of a :keyword:`try` statement with a
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
really leaving the loop.


.. _continue:

The :keyword:`continue` statement
=================================

.. index::
   statement: continue
   statement: for
   statement: while
   pair: loop; statement
   keyword: finally

.. productionlist::
   continue_stmt: "continue"

:keyword:`continue` may only occur syntactically nested in a :keyword:`for` or
:keyword:`while` loop, but not nested in a function or class definition or
:keyword:`finally` clause within that loop.  It continues with the next
cycle of the nearest enclosing loop.

When :keyword:`continue` passes control out of a :keyword:`try` statement with a
:keyword:`finally` clause, that :keyword:`finally` clause is executed before
really starting the next loop cycle.


.. _import:
.. _from:

The :keyword:`import` statement
===============================

.. index::
   statement: import
   single: module; importing
   pair: name; binding
   keyword: from
   single: as; import statement

.. productionlist::
   import_stmt: "import" `module` ["as" `name`] ( "," `module` ["as" `name`] )*
              : | "from" `relative_module` "import" `identifier` ["as" `name`]
              : ( "," `identifier` ["as" `name`] )*
              : | "from" `relative_module` "import" "(" `identifier` ["as" `name`]
              : ( "," `identifier` ["as" `name`] )* [","] ")"
              : | "from" `module` "import" "*"
   module: (`identifier` ".")* `identifier`
   relative_module: "."* `module` | "."+
   name: `identifier`

Import statements are executed in two steps: (1) find a module, and initialize
it if necessary; (2) define a name or names in the local namespace (of the scope
where the :keyword:`import` statement occurs). The statement comes in two
forms differing on whether it uses the :keyword:`from` keyword. The first form
(without :keyword:`from`) repeats these steps for each identifier in the list.
The form with :keyword:`from` performs step (1) once, and then performs step
(2) repeatedly.

.. index::
    single: package

To understand how step (1) occurs, one must first understand how Python handles
hierarchical naming of modules. To help organize modules and provide a
hierarchy in naming, Python has a concept of packages. A package can contain
other packages and modules while modules cannot contain other modules or
packages. From a file system perspective, packages are directories and modules
are files.

.. index::
    single: sys.modules

Once the name of the module is known (unless otherwise specified, the term
"module" will refer to both packages and modules), searching
for the module or package can begin. The first place checked is
:data:`sys.modules`, the cache of all modules that have been imported
previously. If the module is found there then it is used in step (2) of import.

.. index::
    single: sys.meta_path
    single: finder
    pair: finder; find_module
    single: __path__

If the module is not found in the cache, then :data:`sys.meta_path` is searched
(the specification for :data:`sys.meta_path` can be found in :pep:`302`).
The object is a list of :term:`finder` objects which are queried in order as to
whether they know how to load the module by calling their :meth:`find_module`
method with the name of the module. If the module happens to be contained
within a package (as denoted by the existence of a dot in the name), then a
second argument to :meth:`find_module` is given as the value of the
:attr:`__path__` attribute from the parent package (everything up to the last
dot in the name of the module being imported). If a finder can find the module
it returns a :term:`loader` (discussed later) or returns ``None``.

.. index::
    single: sys.path_hooks
    single: sys.path_importer_cache
    single: sys.path

If none of the finders on :data:`sys.meta_path` are able to find the module
then some implicitly defined finders are queried. Implementations of Python
vary in what implicit meta path finders are defined. The one they all do
define, though, is one that handles :data:`sys.path_hooks`,
:data:`sys.path_importer_cache`, and :data:`sys.path`.

The implicit finder searches for the requested module in the "paths" specified
in one of two places ("paths" do not have to be file system paths). If the
module being imported is supposed to be contained within a package then the
second argument passed to :meth:`find_module`, :attr:`__path__` on the parent
package, is used as the source of paths. If the module is not contained in a
package then :data:`sys.path` is used as the source of paths.

Once the source of paths is chosen it is iterated over to find a finder that
can handle that path. The dict at :data:`sys.path_importer_cache` caches
finders for paths and is checked for a finder. If the path does not have a
finder cached then :data:`sys.path_hooks` is searched by calling each object in
the list with a single argument of the path, returning a finder or raises
:exc:`ImportError`. If a finder is returned then it is cached in
:data:`sys.path_importer_cache` and then used for that path entry. If no finder
can be found but the path exists then a value of ``None`` is
stored in :data:`sys.path_importer_cache` to signify that an implicit,
file-based finder that handles modules stored as individual files should be
used for that path. If the path does not exist then a finder which always
returns ``None`` is placed in the cache for the path.

.. index::
    single: loader
    pair: loader; load_module
    exception: ImportError

If no finder can find the module then :exc:`ImportError` is raised. Otherwise
some finder returned a loader whose :meth:`load_module` method is called with
the name of the module to load (see :pep:`302` for the original definition of
loaders). A loader has several responsibilities to perform on a module it
loads. First, if the module already exists in :data:`sys.modules` (a
possibility if the loader is called outside of the import machinery) then it
is to use that module for initialization and not a new module. But if the
module does not exist in :data:`sys.modules` then it is to be added to that
dict before initialization begins. If an error occurs during loading of the
module and it was added to :data:`sys.modules` it is to be removed from the
dict. If an error occurs but the module was already in :data:`sys.modules` it
is left in the dict.

.. index::
    single: __name__
    single: __file__
    single: __path__
    single: __package__
    single: __loader__

The loader must set several attributes on the module. :data:`__name__` is to be
set to the name of the module. :data:`__file__` is to be the "path" to the file
unless the module is built-in (and thus listed in
:data:`sys.builtin_module_names`) in which case the attribute is not set.
If what is being imported is a package then :data:`__path__` is to be set to a
list of paths to be searched when looking for modules and packages contained
within the package being imported. :data:`__package__` is optional but should
be set to the name of package that contains the module or package (the empty
string is used for module not contained in a package). :data:`__loader__` is
also optional but should be set to the loader object that is loading the
module.

.. index::
    exception: ImportError

If an error occurs during loading then the loader raises :exc:`ImportError` if
some other exception is not already being propagated. Otherwise the loader
returns the module that was loaded and initialized.

When step (1) finishes without raising an exception, step (2) can begin.

The first form of :keyword:`import` statement binds the module name in the local
namespace to the module object, and then goes on to import the next identifier,
if any.  If the module name is followed by :keyword:`as`, the name following
:keyword:`as` is used as the local name for the module.

.. index::
   pair: name; binding
   exception: ImportError

The :keyword:`from` form does not bind the module name: it goes through the list
of identifiers, looks each one of them up in the module found in step (1), and
binds the name in the local namespace to the object thus found.  As with the
first form of :keyword:`import`, an alternate local name can be supplied by
specifying ":keyword:`as` localname".  If a name is not found,
:exc:`ImportError` is raised.  If the list of identifiers is replaced by a star
(``'*'``), all public names defined in the module are bound in the local
namespace of the :keyword:`import` statement..

.. index:: single: __all__ (optional module attribute)

The *public names* defined by a module are determined by checking the module's
namespace for a variable named ``__all__``; if defined, it must be a sequence of
strings which are names defined or imported by that module.  The names given in
``__all__`` are all considered public and are required to exist.  If ``__all__``
is not defined, the set of public names includes all names found in the module's
namespace which do not begin with an underscore character (``'_'``).
``__all__`` should contain the entire public API. It is intended to avoid
accidentally exporting items that are not part of the API (such as library
modules which were imported and used within the module).

The :keyword:`from` form with ``*`` may only occur in a module scope.  If the
wild card form of import --- ``import *`` --- is used in a function and the
function contains or is a nested block with free variables, the compiler will
raise a :exc:`SyntaxError`.

.. index::
    single: relative; import

When specifying what module to import you do not have to specify the absolute
name of the module. When a module or package is contained within another
package it is possible to make a relative import within the same top package
without having to mention the package name. By using leading dots in the
specified module or package after :keyword:`from` you can specify how high to
traverse up the current package hierarchy without specifying exact names. One
leading dot means the current package where the module making the import
exists. Two dots means up one package level. Three dots is up two levels, etc.
So if you execute ``from . import mod`` from a module in the ``pkg`` package
then you will end up importing ``pkg.mod``. If you execute ``from ..subpkg2
import mod`` from within ``pkg.subpkg1`` you will import ``pkg.subpkg2.mod``.
The specification for relative imports is contained within :pep:`328`.

:func:`importlib.import_module` is provided to support applications that
determine which modules need to be loaded dynamically.


.. _future:

Future statements
-----------------

.. index:: pair: future; statement

A :dfn:`future statement` is a directive to the compiler that a particular
module should be compiled using syntax or semantics that will be available in a
specified future release of Python.  The future statement is intended to ease
migration to future versions of Python that introduce incompatible changes to
the language.  It allows use of the new features on a per-module basis before
the release in which the feature becomes standard.

.. productionlist:: *
   future_statement: "from" "__future__" "import" feature ["as" name]
                   : ("," feature ["as" name])*
                   : | "from" "__future__" "import" "(" feature ["as" name]
                   : ("," feature ["as" name])* [","] ")"
   feature: identifier
   name: identifier

A future statement must appear near the top of the module.  The only lines that
can appear before a future statement are:

* the module docstring (if any),
* comments,
* blank lines, and
* other future statements.

The features recognized by Python 2.6 are ``unicode_literals``,
``print_function``, ``absolute_import``, ``division``, ``generators``,
``nested_scopes`` and ``with_statement``.  ``generators``, ``with_statement``,
``nested_scopes`` are redundant in Python version 2.6 and above because they are
always enabled.

A future statement is recognized and treated specially at compile time: Changes
to the semantics of core constructs are often implemented by generating
different code.  It may even be the case that a new feature introduces new
incompatible syntax (such as a new reserved word), in which case the compiler
may need to parse the module differently.  Such decisions cannot be pushed off
until runtime.

For any given release, the compiler knows which feature names have been defined,
and raises a compile-time error if a future statement contains a feature not
known to it.

The direct runtime semantics are the same as for any import statement: there is
a standard module :mod:`__future__`, described later, and it will be imported in
the usual way at the time the future statement is executed.

The interesting runtime semantics depend on the specific feature enabled by the
future statement.

Note that there is nothing special about the statement::

   import __future__ [as name]

That is not a future statement; it's an ordinary import statement with no
special semantics or syntax restrictions.

Code compiled by an :keyword:`exec` statement or calls to the built-in functions
:func:`compile` and :func:`execfile` that occur in a module :mod:`M` containing
a future statement will, by default, use the new  syntax or semantics associated
with the future statement.  This can, starting with Python 2.2 be controlled by
optional arguments to :func:`compile` --- see the documentation of that function
for details.

A future statement typed at an interactive interpreter prompt will take effect
for the rest of the interpreter session.  If an interpreter is started with the
:option:`-i` option, is passed a script name to execute, and the script includes
a future statement, it will be in effect in the interactive session started
after the script is executed.

.. seealso::

   :pep:`236` - Back to the __future__
      The original proposal for the __future__ mechanism.


.. _global:

The :keyword:`global` statement
===============================

.. index::
   statement: global
   triple: global; name; binding

.. productionlist::
   global_stmt: "global" `identifier` ("," `identifier`)*

The :keyword:`global` statement is a declaration which holds for the entire
current code block.  It means that the listed identifiers are to be interpreted
as globals.  It would be impossible to assign to a global variable without
:keyword:`global`, although free variables may refer to globals without being
declared global.

Names listed in a :keyword:`global` statement must not be used in the same code
block textually preceding that :keyword:`global` statement.

Names listed in a :keyword:`global` statement must not be defined as formal
parameters or in a :keyword:`for` loop control target, :keyword:`class`
definition, function definition, or :keyword:`import` statement.

.. impl-detail::

   The current implementation does not enforce the latter two restrictions, but
   programs should not abuse this freedom, as future implementations may enforce
   them or silently change the meaning of the program.

.. index::
   statement: exec
   builtin: eval
   builtin: execfile
   builtin: compile

**Programmer's note:** :keyword:`global` is a directive to the parser.  It
applies only to code parsed at the same time as the :keyword:`global` statement.
In particular, a :keyword:`global` statement contained in an :keyword:`exec`
statement does not affect the code block *containing* the :keyword:`exec`
statement, and code contained in an :keyword:`exec` statement is unaffected by
:keyword:`global` statements in the code containing the :keyword:`exec`
statement.  The same applies to the :func:`eval`, :func:`execfile` and
:func:`compile` functions.


.. _exec:

The :keyword:`exec` statement
=============================

.. index:: statement: exec

.. productionlist::
   exec_stmt: "exec" `or_expr` ["in" `expression` ["," `expression`]]

This statement supports dynamic execution of Python code.  The first expression
should evaluate to either a Unicode string, a *Latin-1* encoded string, an open
file object, a code object, or a tuple.  If it is a string, the string is parsed
as a suite of Python statements which is then executed (unless a syntax error
occurs). [#]_ If it is an open file, the file is parsed until EOF and executed.
If it is a code object, it is simply executed.  For the interpretation of a
tuple, see below.  In all cases, the code that's executed is expected to be
valid as file input (see section :ref:`file-input`).  Be aware that the
:keyword:`return` and :keyword:`yield` statements may not be used outside of
function definitions even within the context of code passed to the
:keyword:`exec` statement.

In all cases, if the optional parts are omitted, the code is executed in the
current scope.  If only the first expression after ``in`` is specified,
it should be a dictionary, which will be used for both the global and the local
variables.  If two expressions are given, they are used for the global and local
variables, respectively. If provided, *locals* can be any mapping object.
Remember that at module level, globals and locals are the same dictionary. If
two separate objects are given as *globals* and *locals*, the code will be
executed as if it were embedded in a class definition.

The first expression may also be a tuple of length 2 or 3.  In this case, the
optional parts must be omitted.  The form ``exec(expr, globals)`` is equivalent
to ``exec expr in globals``, while the form ``exec(expr, globals, locals)`` is
equivalent to ``exec expr in globals, locals``.  The tuple form of ``exec``
provides compatibility with Python 3, where ``exec`` is a function rather than
a statement.

.. versionchanged:: 2.4
   Formerly, *locals* was required to be a dictionary.

.. index::
   single: __builtins__
   module: __builtin__

As a side effect, an implementation may insert additional keys into the
dictionaries given besides those corresponding to variable names set by the
executed code.  For example, the current implementation may add a reference to
the dictionary of the built-in module :mod:`__builtin__` under the key
``__builtins__`` (!).

.. index::
   builtin: eval
   builtin: globals
   builtin: locals

**Programmer's hints:** dynamic evaluation of expressions is supported by the
built-in function :func:`eval`.  The built-in functions :func:`globals` and
:func:`locals` return the current global and local dictionary, respectively,
which may be useful to pass around for use by :keyword:`exec`.


.. rubric:: Footnotes

.. [#] Note that the parser only accepts the Unix-style end of line convention.
       If you are reading the code from a file, make sure to use
       :term:`universal newlines` mode to convert Windows or Mac-style newlines.
PK
%�\0�pI�
�
3html/_sources/reference/toplevel_components.rst.txtnu�[���
.. _top-level:

********************
Top-level components
********************

.. index:: single: interpreter

The Python interpreter can get its input from a number of sources: from a script
passed to it as standard input or as program argument, typed in interactively,
from a module source file, etc.  This chapter gives the syntax used in these
cases.


.. _programs:

Complete Python programs
========================

.. index:: single: program

.. index::
   module: sys
   module: __main__
   module: __builtin__

While a language specification need not prescribe how the language interpreter
is invoked, it is useful to have a notion of a complete Python program.  A
complete Python program is executed in a minimally initialized environment: all
built-in and standard modules are available, but none have been initialized,
except for :mod:`sys` (various system services), :mod:`__builtin__` (built-in
functions, exceptions and ``None``) and :mod:`__main__`.  The latter is used to
provide the local and global namespace for execution of the complete program.

The syntax for a complete Python program is that for file input, described in
the next section.

.. index::
   single: interactive mode
   module: __main__

The interpreter may also be invoked in interactive mode; in this case, it does
not read and execute a complete program but reads and executes one statement
(possibly compound) at a time.  The initial environment is identical to that of
a complete program; each statement is executed in the namespace of
:mod:`__main__`.

.. index::
   single: UNIX
   single: command line
   single: standard input

A complete program can be passed to the interpreter
in three forms: with the :option:`-c` *string* command line option, as a file
passed as the first command line argument, or as standard input. If the file
or standard input is a tty device, the interpreter enters interactive mode;
otherwise, it executes the file as a complete program.


.. _file-input:

File input
==========

All input read from non-interactive files has the same form:

.. productionlist::
   file_input: (NEWLINE | `statement`)*

This syntax is used in the following situations:

* when parsing a complete Python program (from a file or from a string);

* when parsing a module;

* when parsing a string passed to the :keyword:`exec` statement;


.. _interactive:

Interactive input
=================

Input in interactive mode is parsed using the following grammar:

.. productionlist::
   interactive_input: [`stmt_list`] NEWLINE | `compound_stmt` NEWLINE

Note that a (top-level) compound statement must be followed by a blank line in
interactive mode; this is needed to help the parser detect the end of the input.


.. _expression-input:

Expression input
================

.. index:: single: input

.. index:: builtin: eval

There are two forms of expression input.  Both ignore leading whitespace. The
string argument to :func:`eval` must have the following form:

.. productionlist::
   eval_input: `expression_list` NEWLINE*

.. index:: builtin: input

The input line read by :func:`input` must have the following form:

.. productionlist::
   input_input: `expression_list` NEWLINE

.. index::
   object: file
   single: input; raw
   single: raw input
   builtin: raw_input
   single: readline() (file method)

Note: to read 'raw' input line without interpretation, you can use the built-in
function :func:`raw_input` or the :meth:`readline` method of file objects.

PK
%�\���'html/_sources/tutorial/appendix.rst.txtnu�[���.. _tut-appendix:

********
Appendix
********


.. _tut-interac:

Interactive Mode
================

.. _tut-error:

Error Handling
--------------

When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement
are not errors in this context.)  Some errors are unconditionally fatal and
cause an exit with a nonzero exit; this applies to internal inconsistencies and
some cases of running out of memory.  All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.

Typing the interrupt character (usually :kbd:`Control-C` or :kbd:`Delete`) to the primary or
secondary prompt cancels the input and returns to the primary prompt. [#]_
Typing an interrupt while a command is executing raises the
:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try`
statement.


.. _tut-scripts:

Executable Python Scripts
-------------------------

On BSD'ish Unix systems, Python scripts can be made directly executable, like
shell scripts, by putting the line ::

   #!/usr/bin/env python

(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
of the script and giving the file an executable mode.  The ``#!`` must be the
first two characters of the file.  On some platforms, this first line must end
with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line
ending.  Note that the hash, or pound, character, ``'#'``, is used to start a
comment in Python.

The script can be given an executable mode, or permission, using the
:program:`chmod` command.

.. code-block:: bash

   $ chmod +x myscript.py

On Windows systems, there is no notion of an "executable mode".  The Python
installer automatically associates ``.py`` files with ``python.exe`` so that
a double-click on a Python file will run it as a script.  The extension can
also be ``.pyw``, in that case, the console window that normally appears is
suppressed.


.. _tut-startup:

The Interactive Startup File
----------------------------

When you use Python interactively, it is frequently handy to have some standard
commands executed every time the interpreter is started.  You can do this by
setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a
file containing your start-up commands.  This is similar to the :file:`.profile`
feature of the Unix shells.

This file is only read in interactive sessions, not when Python reads commands
from a script, and not when :file:`/dev/tty` is given as the explicit source of
commands (which otherwise behaves like an interactive session).  It is executed
in the same namespace where interactive commands are executed, so that objects
that it defines or imports can be used without qualification in the interactive
session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this
file.

If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like ``if
os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
If you want to use the startup file in a script, you must do this explicitly
in the script::

   import os
   filename = os.environ.get('PYTHONSTARTUP')
   if filename and os.path.isfile(filename):
       with open(filename) as fobj:
           startup_file = fobj.read()
       exec(startup_file)


.. _tut-customize:

The Customization Modules
-------------------------

Python provides two hooks to let you customize it: :mod:`sitecustomize` and
:mod:`usercustomize`.  To see how it works, you need first to find the location
of your user site-packages directory.  Start Python and run this code::

   >>> import site
   >>> site.getusersitepackages()
   '/home/user/.local/lib/python2.7/site-packages'

Now you can create a file named :file:`usercustomize.py` in that directory and
put anything you want in it.  It will affect every invocation of Python, unless
it is started with the :option:`-s` option to disable the automatic import.

:mod:`sitecustomize` works in the same way, but is typically created by an
administrator of the computer in the global site-packages directory, and is
imported before :mod:`usercustomize`.  See the documentation of the :mod:`site`
module for more details.


.. rubric:: Footnotes

.. [#] A problem with the GNU Readline package may prevent this.
PK
%�\�
����'html/_sources/tutorial/appetite.rst.txtnu�[���.. _tut-intro:

**********************
Whetting Your Appetite
**********************

If you do much work on computers, eventually you find that there's some task
you'd like to automate.  For example, you may wish to perform a
search-and-replace over a large number of text files, or rename and rearrange a
bunch of photo files in a complicated way. Perhaps you'd like to write a small
custom database, or a specialized GUI application, or a simple game.

If you're a professional software developer, you may have to work with several
C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is
too slow.  Perhaps you're writing a test suite for such a library and find
writing the testing code a tedious task.  Or maybe you've written a program that
could use an extension language, and you don't want to design and implement a
whole new language for your application.

Python is just the language for you.

You could write a Unix shell script or Windows batch files for some of these
tasks, but shell scripts are best at moving around files and changing text data,
not well-suited for GUI applications or games. You could write a C/C++/Java
program, but it can take a lot of development time to get even a first-draft
program.  Python is simpler to use, available on Windows, Mac OS X, and Unix
operating systems, and will help you get the job done more quickly.

Python is simple to use, but it is a real programming language, offering much
more structure and support for large programs than shell scripts or batch files
can offer.  On the other hand, Python also offers much more error checking than
C, and, being a *very-high-level language*, it has high-level data types built
in, such as flexible arrays and dictionaries.  Because of its more general data
types Python is applicable to a much larger problem domain than Awk or even
Perl, yet many things are at least as easy in Python as in those languages.

Python allows you to split your program into modules that can be reused in other
Python programs.  It comes with a large collection of standard modules that you
can use as the basis of your programs --- or as examples to start learning to
program in Python.  Some of these modules provide things like file I/O, system
calls, sockets, and even interfaces to graphical user interface toolkits like
Tk.

Python is an interpreted language, which can save you considerable time during
program development because no compilation and linking is necessary.  The
interpreter can be used interactively, which makes it easy to experiment with
features of the language, to write throw-away programs, or to test functions
during bottom-up program development. It is also a handy desk calculator.

Python enables programs to be written compactly and readably.  Programs written
in Python are typically much shorter than equivalent C,  C++, or Java programs,
for several reasons:

* the high-level data types allow you to express complex operations in a single
  statement;

* statement grouping is done by indentation instead of beginning and ending
  brackets;

* no variable or argument declarations are necessary.

Python is *extensible*: if you know how to program in C it is easy to add a new
built-in function or module to the interpreter, either to perform critical
operations at maximum speed, or to link Python programs to libraries that may
only be available in binary form (such as a vendor-specific graphics library).
Once you are really hooked, you can link the Python interpreter into an
application written in C and use it as an extension or command language for that
application.

By the way, the language is named after the BBC show "Monty Python's Flying
Circus" and has nothing to do with reptiles.  Making references to Monty
Python skits in documentation is not only allowed, it is encouraged!

Now that you are all excited about Python, you'll want to examine it in some
more detail.  Since the best way to learn a language is to use it, the tutorial
invites you to play with the Python interpreter as you read.

In the next chapter, the mechanics of using the interpreter are explained.  This
is rather mundane information, but essential for trying out the examples shown
later.

The rest of the tutorial introduces various features of the Python language and
system through examples, beginning with simple expressions, statements and data
types, through functions and modules, and finally touching upon advanced
concepts like exceptions and user-defined classes.


PK
%�\ߞ�l��&html/_sources/tutorial/classes.rst.txtnu�[���.. _tut-classes:

*******
Classes
*******

Compared with other programming languages, Python's class mechanism adds classes
with a minimum of new syntax and semantics.  It is a mixture of the class
mechanisms found in C++ and Modula-3.  Python classes provide all the standard
features of Object Oriented Programming: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
name.  Objects can contain arbitrary amounts and kinds of data.  As is true for
modules, classes partake of the dynamic nature of Python: they are created at
runtime, and can be modified further after creation.

In C++ terminology, normally class members (including the data members) are
*public* (except see below :ref:`tut-private`), and all member functions are
*virtual*.  As in Modula-3, there are no shorthands for referencing the object's
members from its methods: the method function is declared with an explicit first
argument representing the object, which is provided implicitly by the call.  As
in Smalltalk, classes themselves are objects.  This provides semantics for
importing and renaming.  Unlike C++ and Modula-3, built-in types can be used as
base classes for extension by the user.  Also, like in C++, most built-in
operators with special syntax (arithmetic operators, subscripting etc.) can be
redefined for class instances.

(Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms.  I would use Modula-3 terms, since
its object-oriented semantics are closer to those of Python than C++, but I
expect that few readers have heard of it.)


.. _tut-object:

A Word About Names and Objects
==============================

Objects have individuality, and multiple names (in multiple scopes) can be bound
to the same object.  This is known as aliasing in other languages.  This is
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples).  However,
aliasing has a possibly surprising effect on the semantics of Python code
involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like
pointers in some respects.  For example, passing an object is cheap since only a
pointer is passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change --- this eliminates the
need for two different argument passing mechanisms as in Pascal.


.. _tut-scopes:

Python Scopes and Namespaces
============================

Before introducing classes, I first have to tell you something about Python's
scope rules.  Class definitions play some neat tricks with namespaces, and you
need to know how scopes and namespaces work to fully understand what's going on.
Incidentally, knowledge about this subject is useful for any advanced Python
programmer.

Let's begin with some definitions.

A *namespace* is a mapping from names to objects.  Most namespaces are currently
implemented as Python dictionaries, but that's normally not noticeable in any
way (except for performance), and it may change in the future.  Examples of
namespaces are: the set of built-in names (containing functions such as :func:`abs`, and
built-in exception names); the global names in a module; and the local names in
a function invocation.  In a sense the set of attributes of an object also form
a namespace.  The important thing to know about namespaces is that there is
absolutely no relation between names in different namespaces; for instance, two
different modules may both define a function ``maximize`` without confusion ---
users of the modules must prefix it with the module name.

By the way, I use the word *attribute* for any name following a dot --- for
example, in the expression ``z.real``, ``real`` is an attribute of the object
``z``.  Strictly speaking, references to names in modules are attribute
references: in the expression ``modname.funcname``, ``modname`` is a module
object and ``funcname`` is an attribute of it.  In this case there happens to be
a straightforward mapping between the module's attributes and the global names
defined in the module: they share the same namespace!  [#]_

Attributes may be read-only or writable.  In the latter case, assignment to
attributes is possible.  Module attributes are writable: you can write
``modname.the_answer = 42``.  Writable attributes may also be deleted with the
:keyword:`del` statement.  For example, ``del modname.the_answer`` will remove
the attribute :attr:`the_answer` from the object named by ``modname``.

Namespaces are created at different moments and have different lifetimes.  The
namespace containing the built-in names is created when the Python interpreter
starts up, and is never deleted.  The global namespace for a module is created
when the module definition is read in; normally, module namespaces also last
until the interpreter quits.  The statements executed by the top-level
invocation of the interpreter, either read from a script file or interactively,
are considered part of a module called :mod:`__main__`, so they have their own
global namespace.  (The built-in names actually also live in a module; this is
called :mod:`__builtin__`.)

The local namespace for a function is created when the function is called, and
deleted when the function returns or raises an exception that is not handled
within the function.  (Actually, forgetting would be a better way to describe
what actually happens.)  Of course, recursive invocations each have their own
local namespace.

A *scope* is a textual region of a Python program where a namespace is directly
accessible.  "Directly accessible" here means that an unqualified reference to a
name attempts to find the name in the namespace.

Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
are directly accessible:

* the innermost scope, which is searched first, contains the local names
* the scopes of any enclosing functions, which are searched starting with the
  nearest enclosing scope, contains non-local, but also non-global names
* the next-to-last scope contains the current module's global names
* the outermost scope (searched last) is the namespace containing built-in names

If a name is declared global, then all references and assignments go directly to
the middle scope containing the module's global names. Otherwise, all variables
found outside of the innermost scope are read-only (an attempt to write to such
a variable will simply create a *new* local variable in the innermost scope,
leaving the identically named outer variable unchanged).

Usually, the local scope references the local names of the (textually) current
function.  Outside functions, the local scope references the same namespace as
the global scope: the module's namespace. Class definitions place yet another
namespace in the local scope.

It is important to realize that scopes are determined textually: the global
scope of a function defined in a module is that module's namespace, no matter
from where or by what alias the function is called.  On the other hand, the
actual search for names is done dynamically, at run time --- however, the
language definition is evolving towards static name resolution, at "compile"
time, so don't rely on dynamic name resolution!  (In fact, local variables are
already determined statically.)

A special quirk of Python is that -- if no :keyword:`global` statement is in
effect -- assignments to names always go into the innermost scope.  Assignments
do not copy data --- they just bind names to objects.  The same is true for
deletions: the statement ``del x`` removes the binding of ``x`` from the
namespace referenced by the local scope.  In fact, all operations that introduce
new names use the local scope: in particular, :keyword:`import` statements and
function definitions bind the module or function name in the local scope.  (The
:keyword:`global` statement can be used to indicate that particular variables
live in the global scope.)


.. _tut-firstclasses:

A First Look at Classes
=======================

Classes introduce a little bit of new syntax, three new object types, and some
new semantics.


.. _tut-classdefinition:

Class Definition Syntax
-----------------------

The simplest form of class definition looks like this::

   class ClassName:
       <statement-1>
       .
       .
       .
       <statement-N>

Class definitions, like function definitions (:keyword:`def` statements) must be
executed before they have any effect.  (You could conceivably place a class
definition in a branch of an :keyword:`if` statement, or inside a function.)

In practice, the statements inside a class definition will usually be function
definitions, but other statements are allowed, and sometimes useful --- we'll
come back to this later.  The function definitions inside a class normally have
a peculiar form of argument list, dictated by the calling conventions for
methods --- again, this is explained later.

When a class definition is entered, a new namespace is created, and used as the
local scope --- thus, all assignments to local variables go into this new
namespace.  In particular, function definitions bind the name of the new
function here.

When a class definition is left normally (via the end), a *class object* is
created.  This is basically a wrapper around the contents of the namespace
created by the class definition; we'll learn more about class objects in the
next section.  The original local scope (the one in effect just before the class
definition was entered) is reinstated, and the class object is bound here to the
class name given in the class definition header (:class:`ClassName` in the
example).


.. _tut-classobjects:

Class Objects
-------------

Class objects support two kinds of operations: attribute references and
instantiation.

*Attribute references* use the standard syntax used for all attribute references
in Python: ``obj.name``.  Valid attribute names are all the names that were in
the class's namespace when the class object was created.  So, if the class
definition looked like this::

   class MyClass:
       """A simple example class"""
       i = 12345

       def f(self):
           return 'hello world'

then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, returning
an integer and a function object, respectively. Class attributes can also be
assigned to, so you can change the value of ``MyClass.i`` by assignment.
:attr:`__doc__` is also a valid attribute, returning the docstring belonging to
the class: ``"A simple example class"``.

Class *instantiation* uses function notation.  Just pretend that the class
object is a parameterless function that returns a new instance of the class.
For example (assuming the above class)::

   x = MyClass()

creates a new *instance* of the class and assigns this object to the local
variable ``x``.

The instantiation operation ("calling" a class object) creates an empty object.
Many classes like to create objects with instances customized to a specific
initial state. Therefore a class may define a special method named
:meth:`__init__`, like this::

   def __init__(self):
       self.data = []

When a class defines an :meth:`__init__` method, class instantiation
automatically invokes :meth:`__init__` for the newly-created class instance.  So
in this example, a new, initialized instance can be obtained by::

   x = MyClass()

Of course, the :meth:`__init__` method may have arguments for greater
flexibility.  In that case, arguments given to the class instantiation operator
are passed on to :meth:`__init__`.  For example, ::

   >>> class Complex:
   ...     def __init__(self, realpart, imagpart):
   ...         self.r = realpart
   ...         self.i = imagpart
   ...
   >>> x = Complex(3.0, -4.5)
   >>> x.r, x.i
   (3.0, -4.5)


.. _tut-instanceobjects:

Instance Objects
----------------

Now what can we do with instance objects?  The only operations understood by
instance objects are attribute references.  There are two kinds of valid
attribute names, data attributes and methods.

*data attributes* correspond to "instance variables" in Smalltalk, and to "data
members" in C++.  Data attributes need not be declared; like local variables,
they spring into existence when they are first assigned to.  For example, if
``x`` is the instance of :class:`MyClass` created above, the following piece of
code will print the value ``16``, without leaving a trace::

   x.counter = 1
   while x.counter < 10:
       x.counter = x.counter * 2
   print x.counter
   del x.counter

The other kind of instance attribute reference is a *method*. A method is a
function that "belongs to" an object.  (In Python, the term method is not unique
to class instances: other object types can have methods as well.  For example,
list objects have methods called append, insert, remove, sort, and so on.
However, in the following discussion, we'll use the term method exclusively to
mean methods of class instance objects, unless explicitly stated otherwise.)

.. index:: object: method

Valid method names of an instance object depend on its class.  By definition,
all attributes of a class that are function  objects define corresponding
methods of its instances.  So in our example, ``x.f`` is a valid method
reference, since ``MyClass.f`` is a function, but ``x.i`` is not, since
``MyClass.i`` is not.  But ``x.f`` is not the same thing as ``MyClass.f`` --- it
is a *method object*, not a function object.


.. _tut-methodobjects:

Method Objects
--------------

Usually, a method is called right after it is bound::

   x.f()

In the :class:`MyClass` example, this will return the string ``'hello world'``.
However, it is not necessary to call a method right away: ``x.f`` is a method
object, and can be stored away and called at a later time.  For example::

   xf = x.f
   while True:
       print xf()

will continue to print ``hello world`` until the end of time.

What exactly happens when a method is called?  You may have noticed that
``x.f()`` was called without an argument above, even though the function
definition for :meth:`f` specified an argument.  What happened to the argument?
Surely Python raises an exception when a function that requires an argument is
called without any --- even if the argument isn't actually used...

Actually, you may have guessed the answer: the special thing about methods is
that the object is passed as the first argument of the function.  In our
example, the call ``x.f()`` is exactly equivalent to ``MyClass.f(x)``.  In
general, calling a method with a list of *n* arguments is equivalent to calling
the corresponding function with an argument list that is created by inserting
the method's object before the first argument.

If you still don't understand how methods work, a look at the implementation can
perhaps clarify matters.  When a non-data attribute of an instance is
referenced, the instance's class is searched.  If the name denotes a valid class
attribute that is a function object, a method object is created by packing
(pointers to) the instance object and the function object just found together in
an abstract object: this is the method object.  When the method object is called
with an argument list, a new argument list is constructed from the instance
object and the argument list, and the function object is called with this new
argument list.


.. _tut-class-and-instance-variables:

Class and Instance Variables
----------------------------

Generally speaking, instance variables are for data unique to each instance
and class variables are for attributes and methods shared by all instances
of the class::

    class Dog:

        kind = 'canine'         # class variable shared by all instances

        def __init__(self, name):
            self.name = name    # instance variable unique to each instance

    >>> d = Dog('Fido')
    >>> e = Dog('Buddy')
    >>> d.kind                  # shared by all dogs
    'canine'
    >>> e.kind                  # shared by all dogs
    'canine'
    >>> d.name                  # unique to d
    'Fido'
    >>> e.name                  # unique to e
    'Buddy'

As discussed in :ref:`tut-object`, shared data can have possibly surprising
effects with involving :term:`mutable` objects such as lists and dictionaries.
For example, the *tricks* list in the following code should not be used as a
class variable because just a single list would be shared by all *Dog*
instances::

    class Dog:

        tricks = []             # mistaken use of a class variable

        def __init__(self, name):
            self.name = name

        def add_trick(self, trick):
            self.tricks.append(trick)

    >>> d = Dog('Fido')
    >>> e = Dog('Buddy')
    >>> d.add_trick('roll over')
    >>> e.add_trick('play dead')
    >>> d.tricks                # unexpectedly shared by all dogs
    ['roll over', 'play dead']

Correct design of the class should use an instance variable instead::

    class Dog:

        def __init__(self, name):
            self.name = name
            self.tricks = []    # creates a new empty list for each dog

        def add_trick(self, trick):
            self.tricks.append(trick)

    >>> d = Dog('Fido')
    >>> e = Dog('Buddy')
    >>> d.add_trick('roll over')
    >>> e.add_trick('play dead')
    >>> d.tricks
    ['roll over']
    >>> e.tricks
    ['play dead']


.. _tut-remarks:

Random Remarks
==============

.. These should perhaps be placed more carefully...

Data attributes override method attributes with the same name; to avoid
accidental name conflicts, which may cause hard-to-find bugs in large programs,
it is wise to use some kind of convention that minimizes the chance of
conflicts.  Possible conventions include capitalizing method names, prefixing
data attribute names with a small unique string (perhaps just an underscore), or
using verbs for methods and nouns for data attributes.

Data attributes may be referenced by methods as well as by ordinary users
("clients") of an object.  In other words, classes are not usable to implement
pure abstract data types.  In fact, nothing in Python makes it possible to
enforce data hiding --- it is all based upon convention.  (On the other hand,
the Python implementation, written in C, can completely hide implementation
details and control access to an object if necessary; this can be used by
extensions to Python written in C.)

Clients should use data attributes with care --- clients may mess up invariants
maintained by the methods by stamping on their data attributes.  Note that
clients may add data attributes of their own to an instance object without
affecting the validity of the methods, as long as name conflicts are avoided ---
again, a naming convention can save a lot of headaches here.

There is no shorthand for referencing data attributes (or other methods!) from
within methods.  I find that this actually increases the readability of methods:
there is no chance of confusing local variables and instance variables when
glancing through a method.

Often, the first argument of a method is called ``self``.  This is nothing more
than a convention: the name ``self`` has absolutely no special meaning to
Python.  Note, however, that by not following the convention your code may be
less readable to other Python programmers, and it is also conceivable that a
*class browser* program might be written that relies upon such a convention.

Any function object that is a class attribute defines a method for instances of
that class.  It is not necessary that the function definition is textually
enclosed in the class definition: assigning a function object to a local
variable in the class is also ok.  For example::

   # Function defined outside the class
   def f1(self, x, y):
       return min(x, x+y)

   class C:
       f = f1

       def g(self):
           return 'hello world'

       h = g

Now ``f``, ``g`` and ``h`` are all attributes of class :class:`C` that refer to
function objects, and consequently they are all methods of instances of
:class:`C` --- ``h`` being exactly equivalent to ``g``.  Note that this practice
usually only serves to confuse the reader of a program.

Methods may call other methods by using method attributes of the ``self``
argument::

   class Bag:
       def __init__(self):
           self.data = []

       def add(self, x):
           self.data.append(x)

       def addtwice(self, x):
           self.add(x)
           self.add(x)

Methods may reference global names in the same way as ordinary functions.  The
global scope associated with a method is the module containing its
definition.  (A class is never used as a global scope.)  While one
rarely encounters a good reason for using global data in a method, there are
many legitimate uses of the global scope: for one thing, functions and modules
imported into the global scope can be used by methods, as well as functions and
classes defined in it.  Usually, the class containing the method is itself
defined in this global scope, and in the next section we'll find some good
reasons why a method would want to reference its own class.

Each value is an object, and therefore has a *class* (also called its *type*).
It is stored as ``object.__class__``.


.. _tut-inheritance:

Inheritance
===========

Of course, a language feature would not be worthy of the name "class" without
supporting inheritance.  The syntax for a derived class definition looks like
this::

   class DerivedClassName(BaseClassName):
       <statement-1>
       .
       .
       .
       <statement-N>

The name :class:`BaseClassName` must be defined in a scope containing the
derived class definition.  In place of a base class name, other arbitrary
expressions are also allowed.  This can be useful, for example, when the base
class is defined in another module::

   class DerivedClassName(modname.BaseClassName):

Execution of a derived class definition proceeds the same as for a base class.
When the class object is constructed, the base class is remembered.  This is
used for resolving attribute references: if a requested attribute is not found
in the class, the search proceeds to look in the base class.  This rule is
applied recursively if the base class itself is derived from some other class.

There's nothing special about instantiation of derived classes:
``DerivedClassName()`` creates a new instance of the class.  Method references
are resolved as follows: the corresponding class attribute is searched,
descending down the chain of base classes if necessary, and the method reference
is valid if this yields a function object.

Derived classes may override methods of their base classes.  Because methods
have no special privileges when calling other methods of the same object, a
method of a base class that calls another method defined in the same base class
may end up calling a method of a derived class that overrides it.  (For C++
programmers: all methods in Python are effectively ``virtual``.)

An overriding method in a derived class may in fact want to extend rather than
simply replace the base class method of the same name. There is a simple way to
call the base class method directly: just call ``BaseClassName.methodname(self,
arguments)``.  This is occasionally useful to clients as well.  (Note that this
only works if the base class is accessible as ``BaseClassName`` in the global
scope.)

Python has two built-in functions that work with inheritance:

* Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)``
  will be ``True`` only if ``obj.__class__`` is :class:`int` or some class
  derived from :class:`int`.

* Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)``
  is ``True`` since :class:`bool` is a subclass of :class:`int`.  However,
  ``issubclass(unicode, str)`` is ``False`` since :class:`unicode` is not a
  subclass of :class:`str` (they only share a common ancestor,
  :class:`basestring`).



.. _tut-multiple:

Multiple Inheritance
--------------------

Python supports a limited form of multiple inheritance as well.  A class
definition with multiple base classes looks like this::

   class DerivedClassName(Base1, Base2, Base3):
       <statement-1>
       .
       .
       .
       <statement-N>

For old-style classes, the only rule is depth-first, left-to-right.  Thus, if an
attribute is not found in :class:`DerivedClassName`, it is searched in
:class:`Base1`, then (recursively) in the base classes of :class:`Base1`, and
only if it is not found there, it is searched in :class:`Base2`, and so on.

(To some people breadth first --- searching :class:`Base2` and :class:`Base3`
before the base classes of :class:`Base1` --- looks more natural.  However, this
would require you to know whether a particular attribute of :class:`Base1` is
actually defined in :class:`Base1` or in one of its base classes before you can
figure out the consequences of a name conflict with an attribute of
:class:`Base2`.  The depth-first rule makes no differences between direct and
inherited attributes of :class:`Base1`.)

For :term:`new-style class`\es, the method resolution order changes dynamically
to support cooperative calls to :func:`super`.  This approach is known in some
other multiple-inheritance languages as call-next-method and is more powerful
than the super call found in single-inheritance languages.

With new-style classes, dynamic ordering is necessary because all  cases of
multiple inheritance exhibit one or more diamond relationships (where at
least one of the parent classes can be accessed through multiple paths from the
bottommost class).  For example, all new-style classes inherit from
:class:`object`, so any case of multiple inheritance provides more than one path
to reach :class:`object`.  To keep the base classes from being accessed more
than once, the dynamic algorithm linearizes the search order in a way that
preserves the left-to-right ordering specified in each class, that calls each
parent only once, and that is monotonic (meaning that a class can be subclassed
without affecting the precedence order of its parents).  Taken together, these
properties make it possible to design reliable and extensible classes with
multiple inheritance.  For more detail, see
https://www.python.org/download/releases/2.3/mro/.


.. _tut-private:

Private Variables and Class-local References
============================================

"Private" instance variables that cannot be accessed except from inside an
object don't exist in Python.  However, there is a convention that is followed
by most Python code: a name prefixed with an underscore (e.g. ``_spam``) should
be treated as a non-public part of the API (whether it is a function, a method
or a data member).  It should be considered an implementation detail and subject
to change without notice.

.. index::
   pair: name; mangling

Since there is a valid use-case for class-private members (namely to avoid name
clashes of names with names defined by subclasses), there is limited support for
such a mechanism, called :dfn:`name mangling`.  Any identifier of the form
``__spam`` (at least two leading underscores, at most one trailing underscore)
is textually replaced with ``_classname__spam``, where ``classname`` is the
current class name with leading underscore(s) stripped.  This mangling is done
without regard to the syntactic position of the identifier, as long as it
occurs within the definition of a class.

Name mangling is helpful for letting subclasses override methods without
breaking intraclass method calls.  For example::

   class Mapping:
       def __init__(self, iterable):
           self.items_list = []
           self.__update(iterable)

       def update(self, iterable):
           for item in iterable:
               self.items_list.append(item)

       __update = update   # private copy of original update() method

   class MappingSubclass(Mapping):

       def update(self, keys, values):
           # provides new signature for update()
           # but does not break __init__()
           for item in zip(keys, values):
               self.items_list.append(item)

The above example would work even if ``MappingSubclass`` were to introduce a
``__update`` identifier since it is replaced with ``_Mapping__update`` in the
``Mapping`` class  and ``_MappingSubclass__update`` in the ``MappingSubclass``
class respectively.

Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private.  This can
even be useful in special circumstances, such as in the debugger.

Notice that code passed to ``exec``, ``eval()`` or ``execfile()`` does not
consider the classname of the invoking  class to be the current class; this is
similar to the effect of the  ``global`` statement, the effect of which is
likewise restricted to  code that is byte-compiled together.  The same
restriction applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well
as when referencing ``__dict__`` directly.


.. _tut-odds:

Odds and Ends
=============

Sometimes it is useful to have a data type similar to the Pascal "record" or C
"struct", bundling together a few named data items.  An empty class definition
will do nicely::

   class Employee:
       pass

   john = Employee()  # Create an empty employee record

   # Fill the fields of the record
   john.name = 'John Doe'
   john.dept = 'computer lab'
   john.salary = 1000

A piece of Python code that expects a particular abstract data type can often be
passed a class that emulates the methods of that data type instead.  For
instance, if you have a function that formats some data from a file object, you
can define a class with methods :meth:`read` and :meth:`!readline` that get the
data from a string buffer instead, and pass it as an argument.

.. (Unfortunately, this technique has its limitations: a class can't define
   operations that are accessed by special syntax such as sequence subscripting
   or arithmetic operators, and assigning such a "pseudo-file" to sys.stdin will
   not cause the interpreter to read further input from it.)

Instance method objects have attributes, too: ``m.im_self`` is the instance
object with the method :meth:`m`, and ``m.im_func`` is the function object
corresponding to the method.


.. _tut-exceptionclasses:

Exceptions Are Classes Too
==========================

User-defined exceptions are identified by classes as well.  Using this mechanism
it is possible to create extensible hierarchies of exceptions.

There are two new valid (semantic) forms for the :keyword:`raise` statement::

   raise Class, instance

   raise instance

In the first form, ``instance`` must be an instance of :class:`Class` or of a
class derived from it.  The second form is a shorthand for::

   raise instance.__class__, instance

A class in an :keyword:`except` clause is compatible with an exception if it is
the same class or a base class thereof (but not the other way around --- an
except clause listing a derived class is not compatible with a base class).  For
example, the following code will print B, C, D in that order::

   class B:
       pass
   class C(B):
       pass
   class D(C):
       pass

   for c in [B, C, D]:
       try:
           raise c()
       except D:
           print "D"
       except C:
           print "C"
       except B:
           print "B"

Note that if the except clauses were reversed (with ``except B`` first), it
would have printed B, B, B --- the first matching except clause is triggered.

When an error message is printed for an unhandled exception, the exception's
class name is printed, then a colon and a space, and finally the instance
converted to a string using the built-in function :func:`str`.


.. _tut-iterators:

Iterators
=========

By now you have probably noticed that most container objects can be looped over
using a :keyword:`for` statement::

   for element in [1, 2, 3]:
       print element
   for element in (1, 2, 3):
       print element
   for key in {'one':1, 'two':2}:
       print key
   for char in "123":
       print char
   for line in open("myfile.txt"):
       print line,

This style of access is clear, concise, and convenient.  The use of iterators
pervades and unifies Python.  Behind the scenes, the :keyword:`for` statement
calls :func:`iter` on the container object.  The function returns an iterator
object that defines the method :meth:`~iterator.next` which accesses elements
in the container one at a time.  When there are no more elements,
:meth:`~iterator.next` raises a :exc:`StopIteration` exception which tells the
:keyword:`for` loop to terminate.
This example shows how it all works::

   >>> s = 'abc'
   >>> it = iter(s)
   >>> it
   <iterator object at 0x00A1DB50>
   >>> it.next()
   'a'
   >>> it.next()
   'b'
   >>> it.next()
   'c'
   >>> it.next()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
       it.next()
   StopIteration

Having seen the mechanics behind the iterator protocol, it is easy to add
iterator behavior to your classes.  Define an :meth:`__iter__` method which
returns an object with a :meth:`~iterator.next` method.  If the class
defines :meth:`~iterator.next`, then :meth:`__iter__` can just return ``self``::

   class Reverse:
       """Iterator for looping over a sequence backwards."""
       def __init__(self, data):
           self.data = data
           self.index = len(data)

       def __iter__(self):
           return self

       def next(self):
           if self.index == 0:
               raise StopIteration
           self.index = self.index - 1
           return self.data[self.index]

::

   >>> rev = Reverse('spam')
   >>> iter(rev)
   <__main__.Reverse object at 0x00A1DB50>
   >>> for char in rev:
   ...     print char
   ...
   m
   a
   p
   s


.. _tut-generators:

Generators
==========

:term:`Generator`\s are a simple and powerful tool for creating iterators.  They
are written like regular functions but use the :keyword:`yield` statement
whenever they want to return data.  Each time :func:`next` is called on it, the
generator resumes where it left off (it remembers all the data values and which
statement was last executed).  An example shows that generators can be trivially
easy to create::

   def reverse(data):
       for index in range(len(data)-1, -1, -1):
           yield data[index]

::

   >>> for char in reverse('golf'):
   ...     print char
   ...
   f
   l
   o
   g

Anything that can be done with generators can also be done with class-based
iterators as described in the previous section.  What makes generators so
compact is that the :meth:`__iter__` and :meth:`~generator.next` methods
are created automatically.

Another key feature is that the local variables and execution state are
automatically saved between calls.  This made the function easier to write and
much more clear than an approach using instance variables like ``self.index``
and ``self.data``.

In addition to automatic method creation and saving program state, when
generators terminate, they automatically raise :exc:`StopIteration`. In
combination, these features make it easy to create iterators with no more effort
than writing a regular function.


.. _tut-genexps:

Generator Expressions
=====================

Some simple generators can be coded succinctly as expressions using a syntax
similar to list comprehensions but with parentheses instead of square brackets.
These expressions are designed for situations where the generator is used right
away by an enclosing function.  Generator expressions are more compact but less
versatile than full generator definitions and tend to be more memory friendly
than equivalent list comprehensions.

Examples::

   >>> sum(i*i for i in range(10))                 # sum of squares
   285

   >>> xvec = [10, 20, 30]
   >>> yvec = [7, 5, 3]
   >>> sum(x*y for x,y in zip(xvec, yvec))         # dot product
   260

   >>> from math import pi, sin
   >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91))

   >>> unique_words = set(word  for line in page  for word in line.split())

   >>> valedictorian = max((student.gpa, student.name) for student in graduates)

   >>> data = 'golf'
   >>> list(data[i] for i in range(len(data)-1,-1,-1))
   ['f', 'l', 'o', 'g']



.. rubric:: Footnotes

.. [#] Except for one thing.  Module objects have a secret read-only attribute called
   :attr:`~object.__dict__` which returns the dictionary used to implement the module's
   namespace; the name :attr:`~object.__dict__` is an attribute but not a global name.
   Obviously, using this violates the abstraction of namespace implementation, and
   should be restricted to things like post-mortem debuggers.

PK
%�\�9'm�\�\*html/_sources/tutorial/controlflow.rst.txtnu�[���.. _tut-morecontrol:

***********************
More Control Flow Tools
***********************

Besides the :keyword:`while` statement just introduced, Python knows the usual
control flow statements known from other languages, with some twists.


.. _tut-if:

:keyword:`if` Statements
========================

Perhaps the most well-known statement type is the :keyword:`if` statement.  For
example::

   >>> x = int(raw_input("Please enter an integer: "))
   Please enter an integer: 42
   >>> if x < 0:
   ...     x = 0
   ...     print 'Negative changed to zero'
   ... elif x == 0:
   ...     print 'Zero'
   ... elif x == 1:
   ...     print 'Single'
   ... else:
   ...     print 'More'
   ...
   More

There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
optional.  The keyword ':keyword:`elif`' is short for 'else if', and is useful
to avoid excessive indentation.  An  :keyword:`if` ... :keyword:`elif` ...
:keyword:`elif` ... sequence is a substitute for the ``switch`` or
``case`` statements found in other languages.


.. _tut-for:

:keyword:`for` Statements
=========================

.. index::
   statement: for
   statement: for

The :keyword:`for` statement in Python differs a bit from what you may be used
to in C or Pascal.  Rather than always iterating over an arithmetic progression
of numbers (like in Pascal), or giving the user the ability to define both the
iteration step and halting condition (as C), Python's :keyword:`for` statement
iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence.  For example (no pun intended):

.. One suggestion was to give a real C example here, but that may only serve to
   confuse non-C programmers.

::

   >>> # Measure some strings:
   ... words = ['cat', 'window', 'defenestrate']
   >>> for w in words:
   ...     print w, len(w)
   ...
   cat 3
   window 6
   defenestrate 12

If you need to modify the sequence you are iterating over while inside the loop
(for example to duplicate selected items), it is recommended that you first
make a copy.  Iterating over a sequence does not implicitly make a copy.  The
slice notation makes this especially convenient::

   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
   ...     if len(w) > 6:
   ...         words.insert(0, w)
   ...
   >>> words
   ['defenestrate', 'cat', 'window', 'defenestrate']


.. _tut-range:

The :func:`range` Function
==========================

If you do need to iterate over a sequence of numbers, the built-in function
:func:`range` comes in handy.  It generates lists containing arithmetic
progressions::

   >>> range(10)
   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The given end point is never part of the generated list; ``range(10)`` generates
a list of 10 values, the legal indices for items of a sequence of length 10.  It
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the 'step')::

   >>> range(5, 10)
   [5, 6, 7, 8, 9]
   >>> range(0, 10, 3)
   [0, 3, 6, 9]
   >>> range(-10, -100, -30)
   [-10, -40, -70]

To iterate over the indices of a sequence, you can combine :func:`range` and
:func:`len` as follows::

   >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
   >>> for i in range(len(a)):
   ...     print i, a[i]
   ...
   0 Mary
   1 had
   2 a
   3 little
   4 lamb

In most such cases, however, it is convenient to use the :func:`enumerate`
function, see :ref:`tut-loopidioms`.


.. _tut-break:

:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
=========================================================================================

The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
:keyword:`for` or :keyword:`while` loop.

Loop statements may have an ``else`` clause; it is executed when the loop
terminates through exhaustion of the list (with :keyword:`for`) or when the
condition becomes false (with :keyword:`while`), but not when the loop is
terminated by a :keyword:`break` statement.  This is exemplified by the
following loop, which searches for prime numbers::

   >>> for n in range(2, 10):
   ...     for x in range(2, n):
   ...         if n % x == 0:
   ...             print n, 'equals', x, '*', n/x
   ...             break
   ...     else:
   ...         # loop fell through without finding a factor
   ...         print n, 'is a prime number'
   ...
   2 is a prime number
   3 is a prime number
   4 equals 2 * 2
   5 is a prime number
   6 equals 2 * 3
   7 is a prime number
   8 equals 2 * 4
   9 equals 3 * 3

(Yes, this is the correct code.  Look closely: the ``else`` clause belongs to
the :keyword:`for` loop, **not** the :keyword:`if` statement.)

When used with a loop, the ``else`` clause has more in common with the
``else`` clause of a :keyword:`try` statement than it does that of
:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
when no exception occurs, and a loop's ``else`` clause runs when no ``break``
occurs. For more on the :keyword:`try` statement and exceptions, see
:ref:`tut-handling`.

The :keyword:`continue` statement, also borrowed from C, continues with the next
iteration of the loop::

    >>> for num in range(2, 10):
    ...     if num % 2 == 0:
    ...         print "Found an even number", num
    ...         continue
    ...     print "Found a number", num
    Found an even number 2
    Found a number 3
    Found an even number 4
    Found a number 5
    Found an even number 6
    Found a number 7
    Found an even number 8
    Found a number 9


.. _tut-pass:

:keyword:`pass` Statements
==========================

The :keyword:`pass` statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example::

   >>> while True:
   ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
   ...

This is commonly used for creating minimal classes::

   >>> class MyEmptyClass:
   ...     pass
   ...

Another place :keyword:`pass` can be used is as a place-holder for a function or
conditional body when you are working on new code, allowing you to keep thinking
at a more abstract level.  The :keyword:`pass` is silently ignored::

   >>> def initlog(*args):
   ...     pass   # Remember to implement this!
   ...

.. _tut-functions:

Defining Functions
==================

We can create a function that writes the Fibonacci series to an arbitrary
boundary::

   >>> def fib(n):    # write Fibonacci series up to n
   ...     """Print a Fibonacci series up to n."""
   ...     a, b = 0, 1
   ...     while a < n:
   ...         print a,
   ...         a, b = b, a+b
   ...
   >>> # Now call the function we just defined:
   ... fib(2000)
   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

.. index::
   single: documentation strings
   single: docstrings
   single: strings, documentation

The keyword :keyword:`def` introduces a function *definition*.  It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.

The first statement of the function body can optionally be a string literal;
this string literal is the function's documentation string, or :dfn:`docstring`.
(More about docstrings can be found in the section :ref:`tut-docstrings`.)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it's good
practice to include docstrings in code that you write, so make a habit of it.

The *execution* of a function introduces a new symbol table used for the local
variables of the function.  More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a :keyword:`global` statement), although they
may be referenced.

The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using *call by value* (where the *value* is always an object *reference*,
not the value of the object). [#]_ When a function calls another function, a new
local symbol table is created for that call.

A function definition introduces the function name in the current symbol table.
The value of the function name has a type that is recognized by the interpreter
as a user-defined function.  This value can be assigned to another name which
can then also be used as a function.  This serves as a general renaming
mechanism::

   >>> fib
   <function fib at 10042ed0>
   >>> f = fib
   >>> f(100)
   0 1 1 2 3 5 8 13 21 34 55 89

Coming from other languages, you might object that ``fib`` is not a function but
a procedure since it doesn't return a value.  In fact, even functions without a
:keyword:`return` statement do return a value, albeit a rather boring one.  This
value is called ``None`` (it's a built-in name).  Writing the value ``None`` is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using :keyword:`print`::

   >>> fib(0)
   >>> print fib(0)
   None

It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it::

   >>> def fib2(n):  # return Fibonacci series up to n
   ...     """Return a list containing the Fibonacci series up to n."""
   ...     result = []
   ...     a, b = 0, 1
   ...     while a < n:
   ...         result.append(a)    # see below
   ...         a, b = b, a+b
   ...     return result
   ...
   >>> f100 = fib2(100)    # call it
   >>> f100                # write the result
   [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

This example, as usual, demonstrates some new Python features:

* The :keyword:`return` statement returns with a value from a function.
  :keyword:`return` without an expression argument returns ``None``. Falling off
  the end of a function also returns ``None``.

* The statement ``result.append(a)`` calls a *method* of the list object
  ``result``.  A method is a function that 'belongs' to an object and is named
  ``obj.methodname``, where ``obj`` is some object (this may be an expression),
  and ``methodname`` is the name of a method that is defined by the object's type.
  Different types define different methods.  Methods of different types may have
  the same name without causing ambiguity.  (It is possible to define your own
  object types and methods, using *classes*, see :ref:`tut-classes`)
  The method :meth:`append` shown in the example is defined for list objects; it
  adds a new element at the end of the list.  In this example it is equivalent to
  ``result = result + [a]``, but more efficient.


.. _tut-defining:

More on Defining Functions
==========================

It is also possible to define functions with a variable number of arguments.
There are three forms, which can be combined.


.. _tut-defaultargs:

Default Argument Values
-----------------------

The most useful form is to specify a default value for one or more arguments.
This creates a function that can be called with fewer arguments than it is
defined to allow.  For example::

   def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
       while True:
           ok = raw_input(prompt)
           if ok in ('y', 'ye', 'yes'):
               return True
           if ok in ('n', 'no', 'nop', 'nope'):
               return False
           retries = retries - 1
           if retries < 0:
               raise IOError('refusenik user')
           print complaint

This function can be called in several ways:

* giving only the mandatory argument:
  ``ask_ok('Do you really want to quit?')``
* giving one of the optional arguments:
  ``ask_ok('OK to overwrite the file?', 2)``
* or even giving all arguments:
  ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``

This example also introduces the :keyword:`in` keyword. This tests whether or
not a sequence contains a certain value.

The default values are evaluated at the point of function definition in the
*defining* scope, so that ::

   i = 5

   def f(arg=i):
       print arg

   i = 6
   f()

will print ``5``.

**Important warning:**  The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary, or
instances of most classes.  For example, the following function accumulates the
arguments passed to it on subsequent calls::

   def f(a, L=[]):
       L.append(a)
       return L

   print f(1)
   print f(2)
   print f(3)

This will print ::

   [1]
   [1, 2]
   [1, 2, 3]

If you don't want the default to be shared between subsequent calls, you can
write the function like this instead::

   def f(a, L=None):
       if L is None:
           L = []
       L.append(a)
       return L


.. _tut-keywordargs:

Keyword Arguments
-----------------

Functions can also be called using :term:`keyword arguments <keyword argument>`
of the form ``kwarg=value``.  For instance, the following function::

   def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
       print "-- This parrot wouldn't", action,
       print "if you put", voltage, "volts through it."
       print "-- Lovely plumage, the", type
       print "-- It's", state, "!"

accepts one required argument (``voltage``) and three optional arguments
(``state``, ``action``, and ``type``).  This function can be called in any
of the following ways::

   parrot(1000)                                          # 1 positional argument
   parrot(voltage=1000)                                  # 1 keyword argument
   parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
   parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
   parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
   parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

but all the following calls would be invalid::

   parrot()                     # required argument missing
   parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
   parrot(110, voltage=220)     # duplicate value for the same argument
   parrot(actor='John Cleese')  # unknown keyword argument

In a function call, keyword arguments must follow positional arguments.
All the keyword arguments passed must match one of the arguments
accepted by the function (e.g. ``actor`` is not a valid argument for the
``parrot`` function), and their order is not important.  This also includes
non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
No argument may receive a value more than once.
Here's an example that fails due to this restriction::

   >>> def function(a):
   ...     pass
   ...
   >>> function(0, a=0)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: function() got multiple values for keyword argument 'a'

When a final formal parameter of the form ``**name`` is present, it receives a
dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
those corresponding to a formal parameter.  This may be combined with a formal
parameter of the form ``*name`` (described in the next subsection) which
receives a tuple containing the positional arguments beyond the formal parameter
list.  (``*name`` must occur before ``**name``.) For example, if we define a
function like this::

   def cheeseshop(kind, *arguments, **keywords):
       print "-- Do you have any", kind, "?"
       print "-- I'm sorry, we're all out of", kind
       for arg in arguments:
           print arg
       print "-" * 40
       keys = sorted(keywords.keys())
       for kw in keys:
           print kw, ":", keywords[kw]

It could be called like this::

   cheeseshop("Limburger", "It's very runny, sir.",
              "It's really very, VERY runny, sir.",
              shopkeeper='Michael Palin',
              client="John Cleese",
              sketch="Cheese Shop Sketch")

and of course it would print:

.. code-block:: none

   -- Do you have any Limburger ?
   -- I'm sorry, we're all out of Limburger
   It's very runny, sir.
   It's really very, VERY runny, sir.
   ----------------------------------------
   client : John Cleese
   shopkeeper : Michael Palin
   sketch : Cheese Shop Sketch

Note that the list of keyword argument names is created by sorting the result
of the keywords dictionary's ``keys()`` method before printing its contents;
if this is not done, the order in which the arguments are printed is undefined.

.. _tut-arbitraryargs:

Arbitrary Argument Lists
------------------------

.. index::
  statement: *

Finally, the least frequently used option is to specify that a function can be
called with an arbitrary number of arguments.  These arguments will be wrapped
up in a tuple (see :ref:`tut-tuples`).  Before the variable number of arguments,
zero or more normal arguments may occur. ::

   def write_multiple_items(file, separator, *args):
       file.write(separator.join(args))


.. _tut-unpacking-arguments:

Unpacking Argument Lists
------------------------

The reverse situation occurs when the arguments are already in a list or tuple
but need to be unpacked for a function call requiring separate positional
arguments.  For instance, the built-in :func:`range` function expects separate
*start* and *stop* arguments.  If they are not available separately, write the
function call with the  ``*``\ -operator to unpack the arguments out of a list
or tuple::

   >>> range(3, 6)             # normal call with separate arguments
   [3, 4, 5]
   >>> args = [3, 6]
   >>> range(*args)            # call with arguments unpacked from a list
   [3, 4, 5]

.. index::
  statement: **

In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
-operator::

   >>> def parrot(voltage, state='a stiff', action='voom'):
   ...     print "-- This parrot wouldn't", action,
   ...     print "if you put", voltage, "volts through it.",
   ...     print "E's", state, "!"
   ...
   >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
   >>> parrot(**d)
   -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !


.. _tut-lambda:

Lambda Expressions
------------------

Small anonymous functions can be created with the :keyword:`lambda` keyword.
This function returns the sum of its two arguments: ``lambda a, b: a+b``.
Lambda functions can be used wherever function objects are required.  They are
syntactically restricted to a single expression.  Semantically, they are just
syntactic sugar for a normal function definition.  Like nested function
definitions, lambda functions can reference variables from the containing
scope::

   >>> def make_incrementor(n):
   ...     return lambda x: x + n
   ...
   >>> f = make_incrementor(42)
   >>> f(0)
   42
   >>> f(1)
   43

The above example uses a lambda expression to return a function.  Another use
is to pass a small function as an argument::

   >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
   >>> pairs.sort(key=lambda pair: pair[1])
   >>> pairs
   [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]


.. _tut-docstrings:

Documentation Strings
---------------------

.. index::
   single: docstrings
   single: documentation strings
   single: strings, documentation

There are emerging conventions about the content and formatting of documentation
strings.

The first line should always be a short, concise summary of the object's
purpose.  For brevity, it should not explicitly state the object's name or type,
since these are available by other means (except if the name happens to be a
verb describing a function's operation).  This line should begin with a capital
letter and end with a period.

If there are more lines in the documentation string, the second line should be
blank, visually separating the summary from the rest of the description.  The
following lines should be one or more paragraphs describing the object's calling
conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals in
Python, so tools that process documentation have to strip indentation if
desired.  This is done using the following convention. The first non-blank line
*after* the first line of the string determines the amount of indentation for
the entire documentation string.  (We can't use the first line since it is
generally adjacent to the string's opening quotes so its indentation is not
apparent in the string literal.)  Whitespace "equivalent" to this indentation is
then stripped from the start of all lines of the string.  Lines that are
indented less should not occur, but if they occur all their leading whitespace
should be stripped.  Equivalence of whitespace should be tested after expansion
of tabs (to 8 spaces, normally).

Here is an example of a multi-line docstring::

   >>> def my_function():
   ...     """Do nothing, but document it.
   ...
   ...     No, really, it doesn't do anything.
   ...     """
   ...     pass
   ...
   >>> print my_function.__doc__
   Do nothing, but document it.

       No, really, it doesn't do anything.


.. _tut-codingstyle:

Intermezzo: Coding Style
========================

.. sectionauthor:: Georg Brandl <georg@python.org>
.. index:: pair: coding; style

Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about *coding style*.  Most languages can be written (or more
concise, *formatted*) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.

For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style.  Every Python
developer should read it at some point; here are the most important points
extracted for you:

* Use 4-space indentation, and no tabs.

  4 spaces are a good compromise between small indentation (allows greater
  nesting depth) and large indentation (easier to read).  Tabs introduce
  confusion, and are best left out.

* Wrap lines so that they don't exceed 79 characters.

  This helps users with small displays and makes it possible to have several
  code files side-by-side on larger displays.

* Use blank lines to separate functions and classes, and larger blocks of
  code inside functions.

* When possible, put comments on a line of their own.

* Use docstrings.

* Use spaces around operators and after commas, but not directly inside
  bracketing constructs: ``a = f(1, 2) + g(3, 4)``.

* Name your classes and functions consistently; the convention is to use
  ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
  and methods.  Always use ``self`` as the name for the first method argument
  (see :ref:`tut-firstclasses` for more on classes and methods).

* Don't use fancy encodings if your code is meant to be used in international
  environments.  Plain ASCII works best in any case.


.. rubric:: Footnotes

.. [#] Actually, *call by object reference* would be a better description,
   since if a mutable object is passed, the caller will see any changes the
   callee makes to it (items inserted into a list).

PK
%�\��ڷ�c�c-html/_sources/tutorial/datastructures.rst.txtnu�[���.. _tut-structures:

***************
Data Structures
***************

This chapter describes some things you've learned about already in more detail,
and adds some new things as well.


.. _tut-morelists:

More on Lists
=============

The list data type has some more methods.  Here are all of the methods of list
objects:


.. method:: list.append(x)
   :noindex:

   Add an item to the end of the list; equivalent to ``a[len(a):] = [x]``.


.. method:: list.extend(L)
   :noindex:

   Extend the list by appending all the items in the given list; equivalent to
   ``a[len(a):] = L``.


.. method:: list.insert(i, x)
   :noindex:

   Insert an item at a given position.  The first argument is the index of the
   element before which to insert, so ``a.insert(0, x)`` inserts at the front of
   the list, and ``a.insert(len(a), x)`` is equivalent to ``a.append(x)``.


.. method:: list.remove(x)
   :noindex:

   Remove the first item from the list whose value is *x*. It is an error if there
   is no such item.


.. method:: list.pop([i])
   :noindex:

   Remove the item at the given position in the list, and return it.  If no index
   is specified, ``a.pop()`` removes and returns the last item in the list.  (The
   square brackets around the *i* in the method signature denote that the parameter
   is optional, not that you should type square brackets at that position.  You
   will see this notation frequently in the Python Library Reference.)


.. method:: list.index(x)
   :noindex:

   Return the index in the list of the first item whose value is *x*. It is an
   error if there is no such item.


.. method:: list.count(x)
   :noindex:

   Return the number of times *x* appears in the list.


.. method:: list.sort(cmp=None, key=None, reverse=False)
   :noindex:

   Sort the items of the list in place (the arguments can be used for sort
   customization, see :func:`sorted` for their explanation).


.. method:: list.reverse()
   :noindex:

   Reverse the elements of the list, in place.

An example that uses most of the list methods::

   >>> a = [66.25, 333, 333, 1, 1234.5]
   >>> print a.count(333), a.count(66.25), a.count('x')
   2 1 0
   >>> a.insert(2, -1)
   >>> a.append(333)
   >>> a
   [66.25, 333, -1, 333, 1, 1234.5, 333]
   >>> a.index(333)
   1
   >>> a.remove(333)
   >>> a
   [66.25, -1, 333, 1, 1234.5, 333]
   >>> a.reverse()
   >>> a
   [333, 1234.5, 1, 333, -1, 66.25]
   >>> a.sort()
   >>> a
   [-1, 1, 66.25, 333, 333, 1234.5]
   >>> a.pop()
   1234.5
   >>> a
   [-1, 1, 66.25, 333, 333]

You might have noticed that methods like ``insert``, ``remove`` or ``sort`` that
only modify the list have no return value printed -- they return the default
``None``.  This is a design principle for all mutable data structures in
Python.


.. _tut-lists-as-stacks:

Using Lists as Stacks
---------------------

.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>


The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved ("last-in, first-out").  To add an
item to the top of the stack, use :meth:`append`.  To retrieve an item from the
top of the stack, use :meth:`pop` without an explicit index.  For example::

   >>> stack = [3, 4, 5]
   >>> stack.append(6)
   >>> stack.append(7)
   >>> stack
   [3, 4, 5, 6, 7]
   >>> stack.pop()
   7
   >>> stack
   [3, 4, 5, 6]
   >>> stack.pop()
   6
   >>> stack.pop()
   5
   >>> stack
   [3, 4]


.. _tut-lists-as-queues:

Using Lists as Queues
---------------------

.. sectionauthor:: Ka-Ping Yee <ping@lfw.org>

It is also possible to use a list as a queue, where the first element added is
the first element retrieved ("first-in, first-out"); however, lists are not
efficient for this purpose.  While appends and pops from the end of list are
fast, doing inserts or pops from the beginning of a list is slow (because all
of the other elements have to be shifted by one).

To implement a queue, use :class:`collections.deque` which was designed to
have fast appends and pops from both ends.  For example::

   >>> from collections import deque
   >>> queue = deque(["Eric", "John", "Michael"])
   >>> queue.append("Terry")           # Terry arrives
   >>> queue.append("Graham")          # Graham arrives
   >>> queue.popleft()                 # The first to arrive now leaves
   'Eric'
   >>> queue.popleft()                 # The second to arrive now leaves
   'John'
   >>> queue                           # Remaining queue in order of arrival
   deque(['Michael', 'Terry', 'Graham'])


.. _tut-functional:

Functional Programming Tools
----------------------------

There are three built-in functions that are very useful when used with lists:
:func:`filter`, :func:`map`, and :func:`reduce`.

``filter(function, sequence)`` returns a sequence consisting of those items from
the sequence for which ``function(item)`` is true. If *sequence* is a
:class:`str`, :class:`unicode` or :class:`tuple`, the result will be of the
same type; otherwise, it is always a :class:`list`.  For example, to compute a
sequence of numbers divisible by 3 or 5::

   >>> def f(x): return x % 3 == 0 or x % 5 == 0
   ...
   >>> filter(f, range(2, 25))
   [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]

``map(function, sequence)`` calls ``function(item)`` for each of the sequence's
items and returns a list of the return values.  For example, to compute some
cubes::

   >>> def cube(x): return x*x*x
   ...
   >>> map(cube, range(1, 11))
   [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence may be passed; the function must then have as many
arguments as there are sequences and is called with the corresponding item from
each sequence (or ``None`` if some sequence is shorter than another).  For
example::

   >>> seq = range(8)
   >>> def add(x, y): return x+y
   ...
   >>> map(add, seq, seq)
   [0, 2, 4, 6, 8, 10, 12, 14]

``reduce(function, sequence)`` returns a single value constructed by calling the
binary function *function* on the first two items of the sequence, then on the
result and the next item, and so on.  For example, to compute the sum of the
numbers 1 through 10::

   >>> def add(x,y): return x+y
   ...
   >>> reduce(add, range(1, 11))
   55

If there's only one item in the sequence, its value is returned; if the sequence
is empty, an exception is raised.

A third argument can be passed to indicate the starting value.  In this case the
starting value is returned for an empty sequence, and the function is first
applied to the starting value and the first sequence item, then to the result
and the next item, and so on.  For example, ::

   >>> def sum(seq):
   ...     def add(x,y): return x+y
   ...     return reduce(add, seq, 0)
   ...
   >>> sum(range(1, 11))
   55
   >>> sum([])
   0

Don't use this example's definition of :func:`sum`: since summing numbers is
such a common need, a built-in function ``sum(sequence)`` is already provided,
and works exactly like this.

.. _tut-listcomps:

List Comprehensions
-------------------

List comprehensions provide a concise way to create lists.
Common applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or iterable, or to
create a subsequence of those elements that satisfy a certain condition.

For example, assume we want to create a list of squares, like::

   >>> squares = []
   >>> for x in range(10):
   ...     squares.append(x**2)
   ...
   >>> squares
   [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

We can obtain the same result with::

   squares = [x**2 for x in range(10)]

This is also equivalent to ``squares = map(lambda x: x**2, range(10))``,
but it's more concise and readable.

A list comprehension consists of brackets containing an expression followed
by a :keyword:`for` clause, then zero or more :keyword:`for` or :keyword:`if`
clauses.  The result will be a new list resulting from evaluating the expression
in the context of the :keyword:`for` and :keyword:`if` clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not
equal::

   >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

and it's equivalent to:

   >>> combs = []
   >>> for x in [1,2,3]:
   ...     for y in [3,1,4]:
   ...         if x != y:
   ...             combs.append((x, y))
   ...
   >>> combs
   [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Note how the order of the :keyword:`for` and :keyword:`if` statements is the
same in both these snippets.

If the expression is a tuple (e.g. the ``(x, y)`` in the previous example),
it must be parenthesized. ::

   >>> vec = [-4, -2, 0, 2, 4]
   >>> # create a new list with the values doubled
   >>> [x*2 for x in vec]
   [-8, -4, 0, 4, 8]
   >>> # filter the list to exclude negative numbers
   >>> [x for x in vec if x >= 0]
   [0, 2, 4]
   >>> # apply a function to all the elements
   >>> [abs(x) for x in vec]
   [4, 2, 0, 2, 4]
   >>> # call a method on each element
   >>> freshfruit = ['  banana', '  loganberry ', 'passion fruit  ']
   >>> [weapon.strip() for weapon in freshfruit]
   ['banana', 'loganberry', 'passion fruit']
   >>> # create a list of 2-tuples like (number, square)
   >>> [(x, x**2) for x in range(6)]
   [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
   >>> # the tuple must be parenthesized, otherwise an error is raised
   >>> [x, x**2 for x in range(6)]
     File "<stdin>", line 1, in <module>
       [x, x**2 for x in range(6)]
                  ^
   SyntaxError: invalid syntax
   >>> # flatten a list using a listcomp with two 'for'
   >>> vec = [[1,2,3], [4,5,6], [7,8,9]]
   >>> [num for elem in vec for num in elem]
   [1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can contain complex expressions and nested functions::

   >>> from math import pi
   >>> [str(round(pi, i)) for i in range(1, 6)]
   ['3.1', '3.14', '3.142', '3.1416', '3.14159']


Nested List Comprehensions
''''''''''''''''''''''''''

The initial expression in a list comprehension can be any arbitrary expression,
including another list comprehension.

Consider the following example of a 3x4 matrix implemented as a list of
3 lists of length 4::

   >>> matrix = [
   ...     [1, 2, 3, 4],
   ...     [5, 6, 7, 8],
   ...     [9, 10, 11, 12],
   ... ]

The following list comprehension will transpose rows and columns::

   >>> [[row[i] for row in matrix] for i in range(4)]
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in
the context of the :keyword:`for` that follows it, so this example is
equivalent to::

   >>> transposed = []
   >>> for i in range(4):
   ...     transposed.append([row[i] for row in matrix])
   ...
   >>> transposed
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as::

   >>> transposed = []
   >>> for i in range(4):
   ...     # the following 3 lines implement the nested listcomp
   ...     transposed_row = []
   ...     for row in matrix:
   ...         transposed_row.append(row[i])
   ...     transposed.append(transposed_row)
   ...
   >>> transposed
   [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]


In the real world, you should prefer built-in functions to complex flow statements.
The :func:`zip` function would do a great job for this use case::

   >>> zip(*matrix)
   [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.

.. _tut-del:

The :keyword:`del` statement
============================

There is a way to remove an item from a list given its index instead of its
value: the :keyword:`del` statement.  This differs from the :meth:`pop` method
which returns a value.  The :keyword:`del` statement can also be used to remove
slices from a list or clear the entire list (which we did earlier by assignment
of an empty list to the slice).  For example::

   >>> a = [-1, 1, 66.25, 333, 333, 1234.5]
   >>> del a[0]
   >>> a
   [1, 66.25, 333, 333, 1234.5]
   >>> del a[2:4]
   >>> a
   [1, 66.25, 1234.5]
   >>> del a[:]
   >>> a
   []

:keyword:`del` can also be used to delete entire variables::

   >>> del a

Referencing the name ``a`` hereafter is an error (at least until another value
is assigned to it).  We'll find other uses for :keyword:`del` later.


.. _tut-tuples:

Tuples and Sequences
====================

We saw that lists and strings have many common properties, such as indexing and
slicing operations.  They are two examples of *sequence* data types (see
:ref:`typesseq`).  Since Python is an evolving language, other sequence data
types may be added.  There is also another standard sequence data type: the
*tuple*.

A tuple consists of a number of values separated by commas, for instance::

   >>> t = 12345, 54321, 'hello!'
   >>> t[0]
   12345
   >>> t
   (12345, 54321, 'hello!')
   >>> # Tuples may be nested:
   ... u = t, (1, 2, 3, 4, 5)
   >>> u
   ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
   >>> # Tuples are immutable:
   ... t[0] = 88888
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: 'tuple' object does not support item assignment
   >>> # but they can contain mutable objects:
   ... v = ([1, 2, 3], [3, 2, 1])
   >>> v
   ([1, 2, 3], [3, 2, 1])


As you see, on output tuples are always enclosed in parentheses, so that nested
tuples are interpreted correctly; they may be input with or without surrounding
parentheses, although often parentheses are necessary anyway (if the tuple is
part of a larger expression).  It is not possible to assign to the individual
items of a tuple, however it is possible to create tuples which contain mutable
objects, such as lists.

Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
Tuples are :term:`immutable`, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking (see later in this section) or indexing
(or even by attribute in the case of :func:`namedtuples <collections.namedtuple>`).
Lists are :term:`mutable`, and their elements are usually homogeneous and are
accessed by iterating over the list.

A special problem is the construction of tuples containing 0 or 1 items: the
syntax has some extra quirks to accommodate these.  Empty tuples are constructed
by an empty pair of parentheses; a tuple with one item is constructed by
following a value with a comma (it is not sufficient to enclose a single value
in parentheses). Ugly, but effective.  For example::

   >>> empty = ()
   >>> singleton = 'hello',    # <-- note trailing comma
   >>> len(empty)
   0
   >>> len(singleton)
   1
   >>> singleton
   ('hello',)

The statement ``t = 12345, 54321, 'hello!'`` is an example of *tuple packing*:
the values ``12345``, ``54321`` and ``'hello!'`` are packed together in a tuple.
The reverse operation is also possible::

   >>> x, y, z = t

This is called, appropriately enough, *sequence unpacking* and works for any
sequence on the right-hand side.  Sequence unpacking requires the list of
variables on the left to have the same number of elements as the length of the
sequence.  Note that multiple assignment is really just a combination of tuple
packing and sequence unpacking.


.. _tut-sets:

Sets
====

Python also includes a data type for *sets*.  A set is an unordered collection
with no duplicate elements.  Basic uses include membership testing and
eliminating duplicate entries.  Set objects also support mathematical operations
like union, intersection, difference, and symmetric difference.

Curly braces or the :func:`set` function can be used to create sets.  Note: to
create an empty set you have to use ``set()``, not ``{}``; the latter creates an
empty dictionary, a data structure that we discuss in the next section.

Here is a brief demonstration::

   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
   >>> fruit = set(basket)               # create a set without duplicates
   >>> fruit
   set(['orange', 'pear', 'apple', 'banana'])
   >>> 'orange' in fruit                 # fast membership testing
   True
   >>> 'crabgrass' in fruit
   False

   >>> # Demonstrate set operations on unique letters from two words
   ...
   >>> a = set('abracadabra')
   >>> b = set('alacazam')
   >>> a                                  # unique letters in a
   set(['a', 'r', 'b', 'c', 'd'])
   >>> a - b                              # letters in a but not in b
   set(['r', 'd', 'b'])
   >>> a | b                              # letters in either a or b
   set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
   >>> a & b                              # letters in both a and b
   set(['a', 'c'])
   >>> a ^ b                              # letters in a or b but not both
   set(['r', 'd', 'b', 'm', 'z', 'l'])

Similarly to :ref:`list comprehensions <tut-listcomps>`, set comprehensions
are also supported::

   >>> a = {x for x in 'abracadabra' if x not in 'abc'}
   >>> a
   set(['r', 'd'])


.. _tut-dictionaries:

Dictionaries
============

Another useful data type built into Python is the *dictionary* (see
:ref:`typesmapping`). Dictionaries are sometimes found in other languages as
"associative memories" or "associative arrays".  Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by *keys*, which can be
any immutable type; strings and numbers can always be keys.  Tuples can be used
as keys if they contain only strings, numbers, or tuples; if a tuple contains
any mutable object either directly or indirectly, it cannot be used as a key.
You can't use lists as keys, since lists can be modified in place using index
assignments, slice assignments, or methods like :meth:`append` and
:meth:`extend`.

It is best to think of a dictionary as an unordered set of *key: value* pairs,
with the requirement that the keys are unique (within one dictionary). A pair of
braces creates an empty dictionary: ``{}``. Placing a comma-separated list of
key:value pairs within the braces adds initial key:value pairs to the
dictionary; this is also the way dictionaries are written on output.

The main operations on a dictionary are storing a value with some key and
extracting the value given the key.  It is also possible to delete a key:value
pair with ``del``. If you store using a key that is already in use, the old
value associated with that key is forgotten.  It is an error to extract a value
using a non-existent key.

The :meth:`keys` method of a dictionary object returns a list of all the keys
used in the dictionary, in arbitrary order (if you want it sorted, just apply
the :func:`sorted` function to it).  To check whether a single key is in the
dictionary, use the :keyword:`in` keyword.

Here is a small example using a dictionary::

   >>> tel = {'jack': 4098, 'sape': 4139}
   >>> tel['guido'] = 4127
   >>> tel
   {'sape': 4139, 'guido': 4127, 'jack': 4098}
   >>> tel['jack']
   4098
   >>> del tel['sape']
   >>> tel['irv'] = 4127
   >>> tel
   {'guido': 4127, 'irv': 4127, 'jack': 4098}
   >>> tel.keys()
   ['guido', 'irv', 'jack']
   >>> 'guido' in tel
   True

The :func:`dict` constructor builds dictionaries directly from sequences of
key-value pairs::

   >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
   {'sape': 4139, 'jack': 4098, 'guido': 4127}

In addition, dict comprehensions can be used to create dictionaries from
arbitrary key and value expressions::

   >>> {x: x**2 for x in (2, 4, 6)}
   {2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using
keyword arguments::

   >>> dict(sape=4139, guido=4127, jack=4098)
   {'sape': 4139, 'jack': 4098, 'guido': 4127}


.. _tut-loopidioms:

Looping Techniques
==================

When looping through a sequence, the position index and corresponding value can
be retrieved at the same time using the :func:`enumerate` function. ::

   >>> for i, v in enumerate(['tic', 'tac', 'toe']):
   ...     print i, v
   ...
   0 tic
   1 tac
   2 toe

To loop over two or more sequences at the same time, the entries can be paired
with the :func:`zip` function. ::

   >>> questions = ['name', 'quest', 'favorite color']
   >>> answers = ['lancelot', 'the holy grail', 'blue']
   >>> for q, a in zip(questions, answers):
   ...     print 'What is your {0}?  It is {1}.'.format(q, a)
   ...
   What is your name?  It is lancelot.
   What is your quest?  It is the holy grail.
   What is your favorite color?  It is blue.

To loop over a sequence in reverse, first specify the sequence in a forward
direction and then call the :func:`reversed` function. ::

   >>> for i in reversed(xrange(1,10,2)):
   ...     print i
   ...
   9
   7
   5
   3
   1

To loop over a sequence in sorted order, use the :func:`sorted` function which
returns a new sorted list while leaving the source unaltered. ::

   >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
   >>> for f in sorted(set(basket)):
   ...     print f
   ...
   apple
   banana
   orange
   pear

When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the :meth:`iteritems` method. ::

   >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
   >>> for k, v in knights.iteritems():
   ...     print k, v
   ...
   gallahad the pure
   robin the brave

It is sometimes tempting to change a list while you are looping over it;
however, it is often simpler and safer to create a new list instead. ::

   >>> import math
   >>> raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
   >>> filtered_data = []
   >>> for value in raw_data:
   ...     if not math.isnan(value):
   ...         filtered_data.append(value)
   ...
   >>> filtered_data
   [56.2, 51.7, 55.3, 52.5, 47.8]


.. _tut-conditions:

More on Conditions
==================

The conditions used in ``while`` and ``if`` statements can contain any
operators, not just comparisons.

The comparison operators ``in`` and ``not in`` check whether a value occurs
(does not occur) in a sequence.  The operators ``is`` and ``is not`` compare
whether two objects are really the same object; this only matters for mutable
objects like lists.  All comparison operators have the same priority, which is
lower than that of all numerical operators.

Comparisons can be chained.  For example, ``a < b == c`` tests whether ``a`` is
less than ``b`` and moreover ``b`` equals ``c``.

Comparisons may be combined using the Boolean operators ``and`` and ``or``, and
the outcome of a comparison (or of any other Boolean expression) may be negated
with ``not``.  These have lower priorities than comparison operators; between
them, ``not`` has the highest priority and ``or`` the lowest, so that ``A and
not B or C`` is equivalent to ``(A and (not B)) or C``. As always, parentheses
can be used to express the desired composition.

The Boolean operators ``and`` and ``or`` are so-called *short-circuit*
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined.  For example, if ``A`` and ``C`` are
true but ``B`` is false, ``A and B and C`` does not evaluate the expression
``C``.  When used as a general value and not as a Boolean, the return value of a
short-circuit operator is the last evaluated argument.

It is possible to assign the result of a comparison or other Boolean expression
to a variable.  For example, ::

   >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
   >>> non_null = string1 or string2 or string3
   >>> non_null
   'Trondheim'

Note that in Python, unlike C, assignment cannot occur inside expressions. C
programmers may grumble about this, but it avoids a common class of problems
encountered in C programs: typing ``=`` in an expression when ``==`` was
intended.


.. _tut-comparing:

Comparing Sequences and Other Types
===================================

Sequence objects may be compared to other objects with the same sequence type.
The comparison uses *lexicographical* ordering: first the first two items are
compared, and if they differ this determines the outcome of the comparison; if
they are equal, the next two items are compared, and so on, until either
sequence is exhausted. If two items to be compared are themselves sequences of
the same type, the lexicographical comparison is carried out recursively.  If
all items of two sequences compare equal, the sequences are considered equal.
If one sequence is an initial sub-sequence of the other, the shorter sequence is
the smaller (lesser) one.  Lexicographical ordering for strings uses the ASCII
ordering for individual characters.  Some examples of comparisons between
sequences of the same type::

   (1, 2, 3)              < (1, 2, 4)
   [1, 2, 3]              < [1, 2, 4]
   'ABC' < 'C' < 'Pascal' < 'Python'
   (1, 2, 3, 4)           < (1, 2, 4)
   (1, 2)                 < (1, 2, -1)
   (1, 2, 3)             == (1.0, 2.0, 3.0)
   (1, 2, ('aa', 'ab'))   < (1, 2, ('abc', 'a'), 4)

Note that comparing objects of different types is legal.  The outcome is
deterministic but arbitrary: the types are ordered by their name. Thus, a list
is always smaller than a string, a string is always smaller than a tuple, etc.
[#]_ Mixed numeric types are compared according to their numeric value, so 0
equals 0.0, etc.


.. rubric:: Footnotes

.. [#] The rules for comparing objects of different types should not be relied upon;
   they may change in a future version of the language.

PK
%�\?po��;�;%html/_sources/tutorial/errors.rst.txtnu�[���.. _tut-errors:

*********************
Errors and Exceptions
*********************

Until now error messages haven't been more than mentioned, but if you have tried
out the examples you have probably seen some.  There are (at least) two
distinguishable kinds of errors: *syntax errors* and *exceptions*.


.. _tut-syntaxerrors:

Syntax Errors
=============

Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python::

   >>> while True print 'Hello world'
     File "<stdin>", line 1
       while True print 'Hello world'
                      ^
   SyntaxError: invalid syntax

The parser repeats the offending line and displays a little 'arrow' pointing at
the earliest point in the line where the error was detected.  The error is
caused by (or at least detected at) the token *preceding* the arrow: in the
example, the error is detected at the keyword :keyword:`print`, since a colon
(``':'``) is missing before it.  File name and line number are printed so you
know where to look in case the input came from a script.


.. _tut-exceptions:

Exceptions
==========

Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called *exceptions* and are not unconditionally fatal: you will soon learn
how to handle them in Python programs.  Most exceptions are not handled by
programs, however, and result in error messages as shown here::

   >>> 10 * (1/0)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ZeroDivisionError: integer division or modulo by zero
   >>> 4 + spam*3
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   NameError: name 'spam' is not defined
   >>> '2' + 2
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: cannot concatenate 'str' and 'int' objects

The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are :exc:`ZeroDivisionError`, :exc:`NameError` and :exc:`TypeError`.
The string printed as the exception type is the name of the built-in exception
that occurred.  This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what
caused it.

The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.

:ref:`bltin-exceptions` lists the built-in exceptions and their meanings.


.. _tut-handling:

Handling Exceptions
===================

It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using :kbd:`Control-C` or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the :exc:`KeyboardInterrupt` exception. ::

   >>> while True:
   ...     try:
   ...         x = int(raw_input("Please enter a number: "))
   ...         break
   ...     except ValueError:
   ...         print "Oops!  That was no valid number.  Try again..."
   ...

The :keyword:`try` statement works as follows.

* First, the *try clause* (the statement(s) between the :keyword:`try` and
  :keyword:`except` keywords) is executed.

* If no exception occurs, the *except clause* is skipped and execution of the
  :keyword:`try` statement is finished.

* If an exception occurs during execution of the try clause, the rest of the
  clause is skipped.  Then if its type matches the exception named after the
  :keyword:`except` keyword, the except clause is executed, and then execution
  continues after the :keyword:`try` statement.

* If an exception occurs which does not match the exception named in the except
  clause, it is passed on to outer :keyword:`try` statements; if no handler is
  found, it is an *unhandled exception* and execution stops with a message as
  shown above.

A :keyword:`try` statement may have more than one except clause, to specify
handlers for different exceptions.  At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same :keyword:`try` statement.  An except clause may
name multiple exceptions as a parenthesized tuple, for example::

   ... except (RuntimeError, TypeError, NameError):
   ...     pass

Note that the parentheses around this tuple are required, because
``except ValueError, e:`` was the syntax used for what is normally
written as ``except ValueError as e:`` in modern Python (described
below). The old syntax is still supported for backwards compatibility.
This means ``except RuntimeError, TypeError`` is not equivalent to
``except (RuntimeError, TypeError):`` but to ``except RuntimeError as
TypeError:`` which is not what you want.

The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way!  It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well)::

   import sys

   try:
       f = open('myfile.txt')
       s = f.readline()
       i = int(s.strip())
   except IOError as e:
       print "I/O error({0}): {1}".format(e.errno, e.strerror)
   except ValueError:
       print "Could not convert data to an integer."
   except:
       print "Unexpected error:", sys.exc_info()[0]
       raise

The :keyword:`try` ... :keyword:`except` statement has an optional *else
clause*, which, when present, must follow all except clauses.  It is useful for
code that must be executed if the try clause does not raise an exception.  For
example::

   for arg in sys.argv[1:]:
       try:
           f = open(arg, 'r')
       except IOError:
           print 'cannot open', arg
       else:
           print arg, 'has', len(f.readlines()), 'lines'
           f.close()

The use of the :keyword:`else` clause is better than adding additional code to
the :keyword:`try` clause because it avoids accidentally catching an exception
that wasn't raised by the code being protected by the :keyword:`try` ...
:keyword:`except` statement.

When an exception occurs, it may have an associated value, also known as the
exception's *argument*. The presence and type of the argument depend on the
exception type.

The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
``instance.args``.  For convenience, the exception instance defines
:meth:`__str__` so the arguments can be printed directly without having to
reference ``.args``.

One may also instantiate an exception first before raising it and add any
attributes to it as desired. ::

   >>> try:
   ...     raise Exception('spam', 'eggs')
   ... except Exception as inst:
   ...     print type(inst)     # the exception instance
   ...     print inst.args      # arguments stored in .args
   ...     print inst           # __str__ allows args to be printed directly
   ...     x, y = inst.args
   ...     print 'x =', x
   ...     print 'y =', y
   ...
   <type 'exceptions.Exception'>
   ('spam', 'eggs')
   ('spam', 'eggs')
   x = spam
   y = eggs

If an exception has an argument, it is printed as the last part ('detail') of
the message for unhandled exceptions.

Exception handlers don't just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example::

   >>> def this_fails():
   ...     x = 1/0
   ...
   >>> try:
   ...     this_fails()
   ... except ZeroDivisionError as detail:
   ...     print 'Handling run-time error:', detail
   ...
   Handling run-time error: integer division or modulo by zero


.. _tut-raising:

Raising Exceptions
==================

The :keyword:`raise` statement allows the programmer to force a specified
exception to occur. For example::

   >>> raise NameError('HiThere')
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   NameError: HiThere

The sole argument to :keyword:`raise` indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from :class:`Exception`).

If you need to determine whether an exception was raised but don't intend to
handle it, a simpler form of the :keyword:`raise` statement allows you to
re-raise the exception::

   >>> try:
   ...     raise NameError('HiThere')
   ... except NameError:
   ...     print 'An exception flew by!'
   ...     raise
   ...
   An exception flew by!
   Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
   NameError: HiThere


.. _tut-userexceptions:

User-defined Exceptions
=======================

Programs may name their own exceptions by creating a new exception class (see
:ref:`tut-classes` for more about Python classes).  Exceptions should typically
be derived from the :exc:`Exception` class, either directly or indirectly.  For
example::

   >>> class MyError(Exception):
   ...     def __init__(self, value):
   ...         self.value = value
   ...     def __str__(self):
   ...         return repr(self.value)
   ...
   >>> try:
   ...     raise MyError(2*2)
   ... except MyError as e:
   ...     print 'My exception occurred, value:', e.value
   ...
   My exception occurred, value: 4
   >>> raise MyError('oops!')
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   __main__.MyError: 'oops!'

In this example, the default :meth:`__init__` of :class:`Exception` has been
overridden.  The new behavior simply creates the *value* attribute.  This
replaces the default behavior of creating the *args* attribute.

Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception.  When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions::

   class Error(Exception):
       """Base class for exceptions in this module."""
       pass

   class InputError(Error):
       """Exception raised for errors in the input.

       Attributes:
           expr -- input expression in which the error occurred
           msg  -- explanation of the error
       """

       def __init__(self, expr, msg):
           self.expr = expr
           self.msg = msg

   class TransitionError(Error):
       """Raised when an operation attempts a state transition that's not
       allowed.

       Attributes:
           prev -- state at beginning of transition
           next -- attempted new state
           msg  -- explanation of why the specific transition is not allowed
       """

       def __init__(self, prev, next, msg):
           self.prev = prev
           self.next = next
           self.msg = msg

Most exceptions are defined with names that end in "Error", similar to the
naming of the standard exceptions.

Many standard modules define their own exceptions to report errors that may
occur in functions they define.  More information on classes is presented in
chapter :ref:`tut-classes`.


.. _tut-cleanup:

Defining Clean-up Actions
=========================

The :keyword:`try` statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances.  For
example::

   >>> try:
   ...     raise KeyboardInterrupt
   ... finally:
   ...     print 'Goodbye, world!'
   ...
   Goodbye, world!
   Traceback (most recent call last):
     File "<stdin>", line 2, in <module>
   KeyboardInterrupt

A *finally clause* is always executed before leaving the :keyword:`try`
statement, whether an exception has occurred or not. When an exception has
occurred in the :keyword:`try` clause and has not been handled by an
:keyword:`except` clause (or it has occurred in an :keyword:`except` or
:keyword:`else` clause), it is re-raised after the :keyword:`finally` clause has
been executed.  The :keyword:`finally` clause is also executed "on the way out"
when any other clause of the :keyword:`try` statement is left via a
:keyword:`break`, :keyword:`continue` or :keyword:`return` statement.  A more
complicated example (having :keyword:`except` and :keyword:`finally` clauses in
the same :keyword:`try` statement works as of Python 2.5)::

   >>> def divide(x, y):
   ...     try:
   ...         result = x / y
   ...     except ZeroDivisionError:
   ...         print "division by zero!"
   ...     else:
   ...         print "result is", result
   ...     finally:
   ...         print "executing finally clause"
   ...
   >>> divide(2, 1)
   result is 2
   executing finally clause
   >>> divide(2, 0)
   division by zero!
   executing finally clause
   >>> divide("2", "1")
   executing finally clause
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
     File "<stdin>", line 3, in divide
   TypeError: unsupported operand type(s) for /: 'str' and 'str'

As you can see, the :keyword:`finally` clause is executed in any event.  The
:exc:`TypeError` raised by dividing two strings is not handled by the
:keyword:`except` clause and therefore re-raised after the :keyword:`finally`
clause has been executed.

In real world applications, the :keyword:`finally` clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.


.. _tut-cleanup-with:

Predefined Clean-up Actions
===========================

Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen. ::

   for line in open("myfile.txt"):
       print line,

The problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. This is not an issue in
simple scripts, but can be a problem for larger applications. The
:keyword:`with` statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly. ::

   with open("myfile.txt") as f:
       for line in f:
           print line,

After the statement is executed, the file *f* is always closed, even if a
problem was encountered while processing the lines. Other objects which provide
predefined clean-up actions will indicate this in their documentation.


PK
%�\�Egm!!,html/_sources/tutorial/floatingpoint.rst.txtnu�[���.. _tut-fp-issues:

**************************************************
Floating Point Arithmetic:  Issues and Limitations
**************************************************

.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>


Floating-point numbers are represented in computer hardware as base 2 (binary)
fractions.  For example, the decimal fraction ::

   0.125

has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction ::

   0.001

has value 0/2 + 0/4 + 1/8.  These two fractions have identical values, the only
real difference being that the first is written in base 10 fractional notation,
and the second in base 2.

Unfortunately, most decimal fractions cannot be represented exactly as binary
fractions.  A consequence is that, in general, the decimal floating-point
numbers you enter are only approximated by the binary floating-point numbers
actually stored in the machine.

The problem is easier to understand at first in base 10.  Consider the fraction
1/3.  You can approximate that as a base 10 fraction::

   0.3

or, better, ::

   0.33

or, better, ::

   0.333

and so on.  No matter how many digits you're willing to write down, the result
will never be exactly 1/3, but will be an increasingly better approximation of
1/3.

In the same way, no matter how many base 2 digits you're willing to use, the
decimal value 0.1 cannot be represented exactly as a base 2 fraction.  In base
2, 1/10 is the infinitely repeating fraction ::

   0.0001100110011001100110011001100110011001100110011...

Stop at any finite number of bits, and you get an approximation.

On a typical machine running Python, there are 53 bits of precision available
for a Python float, so the value stored internally when you enter the decimal
number ``0.1`` is the binary fraction ::

   0.00011001100110011001100110011001100110011001100110011010

which is close to, but not exactly equal to, 1/10.

It's easy to forget that the stored value is an approximation to the original
decimal fraction, because of the way that floats are displayed at the
interpreter prompt.  Python only prints a decimal approximation to the true
decimal value of the binary approximation stored by the machine.  If Python
were to print the true decimal value of the binary approximation stored for
0.1, it would have to display ::

   >>> 0.1
   0.1000000000000000055511151231257827021181583404541015625

That is more digits than most people find useful, so Python keeps the number
of digits manageable by displaying a rounded value instead ::

   >>> 0.1
   0.1

It's important to realize that this is, in a real sense, an illusion: the value
in the machine is not exactly 1/10, you're simply rounding the *display* of the
true machine value.  This fact becomes apparent as soon as you try to do
arithmetic with these values ::

   >>> 0.1 + 0.2
   0.30000000000000004

Note that this is in the very nature of binary floating-point: this is not a
bug in Python, and it is not a bug in your code either.  You'll see the same
kind of thing in all languages that support your hardware's floating-point
arithmetic (although some languages may not *display* the difference by
default, or in all output modes).

Other surprises follow from this one.  For example, if you try to round the
value 2.675 to two decimal places, you get this ::

   >>> round(2.675, 2)
   2.67

The documentation for the built-in :func:`round` function says that it rounds
to the nearest value, rounding ties away from zero.  Since the decimal fraction
2.675 is exactly halfway between 2.67 and 2.68, you might expect the result
here to be (a binary approximation to) 2.68.  It's not, because when the
decimal string ``2.675`` is converted to a binary floating-point number, it's
again replaced with a binary approximation, whose exact value is ::

   2.67499999999999982236431605997495353221893310546875

Since this approximation is slightly closer to 2.67 than to 2.68, it's rounded
down.

If you're in a situation where you care which way your decimal halfway-cases
are rounded, you should consider using the :mod:`decimal` module.
Incidentally, the :mod:`decimal` module also provides a nice way to "see" the
exact value that's stored in any particular Python float ::

   >>> from decimal import Decimal
   >>> Decimal(2.675)
   Decimal('2.67499999999999982236431605997495353221893310546875')

Another consequence is that since 0.1 is not exactly 1/10, summing ten values
of 0.1 may not yield exactly 1.0, either::

   >>> sum = 0.0
   >>> for i in range(10):
   ...     sum += 0.1
   ...
   >>> sum
   0.9999999999999999

Binary floating-point arithmetic holds many surprises like this.  The problem
with "0.1" is explained in precise detail below, in the "Representation Error"
section.  See `The Perils of Floating Point <http://www.lahey.com/float.htm>`_
for a more complete account of other common surprises.

As that says near the end, "there are no easy answers."  Still, don't be unduly
wary of floating-point!  The errors in Python float operations are inherited
from the floating-point hardware, and on most machines are on the order of no
more than 1 part in 2\*\*53 per operation.  That's more than adequate for most
tasks, but you do need to keep in mind that it's not decimal arithmetic, and
that every float operation can suffer a new rounding error.

While pathological cases do exist, for most casual use of floating-point
arithmetic you'll see the result you expect in the end if you simply round the
display of your final results to the number of decimal digits you expect.  For
fine control over how a float is displayed see the :meth:`str.format` method's
format specifiers in :ref:`formatstrings`.


.. _tut-fp-error:

Representation Error
====================

This section explains the "0.1" example in detail, and shows how you can
perform an exact analysis of cases like this yourself.  Basic familiarity with
binary floating-point representation is assumed.

:dfn:`Representation error` refers to the fact that some (most, actually)
decimal fractions cannot be represented exactly as binary (base 2) fractions.
This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many
others) often won't display the exact decimal number you expect::

   >>> 0.1 + 0.2
   0.30000000000000004

Why is that?  1/10 and 2/10 are not exactly representable as a binary
fraction. Almost all machines today (July 2010) use IEEE-754 floating point
arithmetic, and almost all platforms map Python floats to IEEE-754 "double
precision".  754 doubles contain 53 bits of precision, so on input the computer
strives to convert 0.1 to the closest fraction it can of the form *J*/2**\ *N*
where *J* is an integer containing exactly 53 bits.  Rewriting ::

   1 / 10 ~= J / (2**N)

as ::

   J ~= 2**N / 10

and recalling that *J* has exactly 53 bits (is ``>= 2**52`` but ``< 2**53``),
the best value for *N* is 56::

   >>> 2**52
   4503599627370496
   >>> 2**53
   9007199254740992
   >>> 2**56/10
   7205759403792793

That is, 56 is the only value for *N* that leaves *J* with exactly 53 bits.
The best possible value for *J* is then that quotient rounded::

   >>> q, r = divmod(2**56, 10)
   >>> r
   6

Since the remainder is more than half of 10, the best approximation is obtained
by rounding up::

   >>> q+1
   7205759403792794

Therefore the best possible approximation to 1/10 in 754 double precision is
that over 2\*\*56, or ::

   7205759403792794 / 72057594037927936

Note that since we rounded up, this is actually a little bit larger than 1/10;
if we had not rounded up, the quotient would have been a little bit smaller
than 1/10.  But in no case can it be *exactly* 1/10!

So the computer never "sees" 1/10:  what it sees is the exact fraction given
above, the best 754 double approximation it can get::

   >>> .1 * 2**56
   7205759403792794.0

If we multiply that fraction by 10\*\*30, we can see the (truncated) value of
its 30 most significant decimal digits::

   >>> 7205759403792794 * 10**30 // 2**56
   100000000000000005551115123125L

meaning that the exact number stored in the computer is approximately equal to
the decimal value 0.100000000000000005551115123125.  In versions prior to
Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits,
giving '0.10000000000000001'.  In current versions, Python displays a value
based on the shortest decimal fraction that rounds correctly back to the true
binary value, resulting simply in '0.1'.
PK
%�\Kͧ�F	F	$html/_sources/tutorial/index.rst.txtnu�[���.. _tutorial-index:

######################
  The Python Tutorial
######################

Python is an easy to learn, powerful programming language. It has efficient
high-level data structures and a simple but effective approach to
object-oriented programming. Python's elegant syntax and dynamic typing,
together with its interpreted nature, make it an ideal language for scripting
and rapid application development in many areas on most platforms.

The Python interpreter and the extensive standard library are freely available
in source or binary form for all major platforms from the Python Web site,
https://www.python.org/, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.

The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also
suitable as an extension language for customizable applications.

This tutorial introduces the reader informally to the basic concepts and
features of the Python language and system. It helps to have a Python
interpreter handy for hands-on experience, but all examples are self-contained,
so the tutorial can be read off-line as well.

For a description of standard objects and modules, see :ref:`library-index`.
:ref:`reference-index` gives a more formal definition of the language.  To write
extensions in C or C++, read :ref:`extending-index` and
:ref:`c-api-index`. There are also several books covering Python in depth.

This tutorial does not attempt to be comprehensive and cover every single
feature, or even every commonly used feature. Instead, it introduces many of
Python's most noteworthy features, and will give you a good idea of the
language's flavor and style. After reading it, you will be able to read and
write Python modules and programs, and you will be ready to learn more about the
various Python library modules described in :ref:`library-index`.

The :ref:`glossary` is also worth going through.

.. toctree::
   :numbered:

   appetite.rst
   interpreter.rst
   introduction.rst
   controlflow.rst
   datastructures.rst
   modules.rst
   inputoutput.rst
   errors.rst
   classes.rst
   stdlib.rst
   stdlib2.rst
   whatnow.rst
   interactive.rst
   floatingpoint.rst
   appendix.rst
PK
%�\��>�>*html/_sources/tutorial/inputoutput.rst.txtnu�[���.. _tut-io:

****************
Input and Output
****************

There are several ways to present the output of a program; data can be printed
in a human-readable form, or written to a file for future use. This chapter will
discuss some of the possibilities.


.. _tut-formatting:

Fancier Output Formatting
=========================

So far we've encountered two ways of writing values: *expression statements* and
the :keyword:`print` statement.  (A third way is using the :meth:`write` method
of file objects; the standard output file can be referenced as ``sys.stdout``.
See the Library Reference for more information on this.)

Often you'll want more control over the formatting of your output than simply
printing space-separated values.  There are two ways to format your output; the
first way is to do all the string handling yourself; using string slicing and
concatenation operations you can create any layout you can imagine.  The
string types have some methods that perform useful operations for padding
strings to a given column width; these will be discussed shortly.  The second
way is to use the :meth:`str.format` method.

The :mod:`string` module contains a :class:`~string.Template` class which offers
yet another way to substitute values into strings.

One question remains, of course: how do you convert values to strings? Luckily,
Python has ways to convert any value to a string: pass it to the :func:`repr`
or :func:`str` functions.

The :func:`str` function is meant to return representations of values which are
fairly human-readable, while :func:`repr` is meant to generate representations
which can be read by the interpreter (or will force a :exc:`SyntaxError` if
there is no equivalent syntax).  For objects which don't have a particular
representation for human consumption, :func:`str` will return the same value as
:func:`repr`.  Many values, such as numbers or structures like lists and
dictionaries, have the same representation using either function.  Strings and
floating point numbers, in particular, have two distinct representations.

Some examples::

   >>> s = 'Hello, world.'
   >>> str(s)
   'Hello, world.'
   >>> repr(s)
   "'Hello, world.'"
   >>> str(1.0/7.0)
   '0.142857142857'
   >>> repr(1.0/7.0)
   '0.14285714285714285'
   >>> x = 10 * 3.25
   >>> y = 200 * 200
   >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
   >>> print s
   The value of x is 32.5, and y is 40000...
   >>> # The repr() of a string adds string quotes and backslashes:
   ... hello = 'hello, world\n'
   >>> hellos = repr(hello)
   >>> print hellos
   'hello, world\n'
   >>> # The argument to repr() may be any Python object:
   ... repr((x, y, ('spam', 'eggs')))
   "(32.5, 40000, ('spam', 'eggs'))"

Here are two ways to write a table of squares and cubes::

   >>> for x in range(1, 11):
   ...     print repr(x).rjust(2), repr(x*x).rjust(3),
   ...     # Note trailing comma on previous line
   ...     print repr(x*x*x).rjust(4)
   ...
    1   1    1
    2   4    8
    3   9   27
    4  16   64
    5  25  125
    6  36  216
    7  49  343
    8  64  512
    9  81  729
   10 100 1000

   >>> for x in range(1,11):
   ...     print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)
   ...
    1   1    1
    2   4    8
    3   9   27
    4  16   64
    5  25  125
    6  36  216
    7  49  343
    8  64  512
    9  81  729
   10 100 1000

(Note that in the first example, one space between each column was added by the
way :keyword:`print` works: by default it adds spaces between its arguments.)

This example demonstrates the :meth:`str.rjust` method of string
objects, which right-justifies a string in a field of a given width by padding
it with spaces on the left.  There are similar methods :meth:`str.ljust` and
:meth:`str.center`.  These methods do not write anything, they just return a
new string.  If the input string is too long, they don't truncate it, but
return it unchanged; this will mess up your column lay-out but that's usually
better than the alternative, which would be lying about a value.  (If you
really want truncation you can always add a slice operation, as in
``x.ljust(n)[:n]``.)

There is another method, :meth:`str.zfill`, which pads a numeric string on the
left with zeros.  It understands about plus and minus signs::

   >>> '12'.zfill(5)
   '00012'
   >>> '-3.14'.zfill(7)
   '-003.14'
   >>> '3.14159265359'.zfill(5)
   '3.14159265359'

Basic usage of the :meth:`str.format` method looks like this::

   >>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
   We are the knights who say "Ni!"

The brackets and characters within them (called format fields) are replaced with
the objects passed into the :meth:`str.format` method.  A number in the
brackets refers to the position of the object passed into the
:meth:`str.format` method. ::

   >>> print '{0} and {1}'.format('spam', 'eggs')
   spam and eggs
   >>> print '{1} and {0}'.format('spam', 'eggs')
   eggs and spam

If keyword arguments are used in the :meth:`str.format` method, their values
are referred to by using the name of the argument. ::

   >>> print 'This {food} is {adjective}.'.format(
   ...       food='spam', adjective='absolutely horrible')
   This spam is absolutely horrible.

Positional and keyword arguments can be arbitrarily combined::

   >>> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
   ...                                                    other='Georg')
   The story of Bill, Manfred, and Georg.

``'!s'`` (apply :func:`str`) and ``'!r'`` (apply :func:`repr`) can be used to
convert the value before it is formatted. ::

   >>> import math
   >>> print 'The value of PI is approximately {}.'.format(math.pi)
   The value of PI is approximately 3.14159265359.
   >>> print 'The value of PI is approximately {!r}.'.format(math.pi)
   The value of PI is approximately 3.141592653589793.

An optional ``':'`` and format specifier can follow the field name. This allows
greater control over how the value is formatted.  The following example
rounds Pi to three places after the decimal.

   >>> import math
   >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
   The value of PI is approximately 3.142.

Passing an integer after the ``':'`` will cause that field to be a minimum
number of characters wide.  This is useful for making tables pretty. ::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
   >>> for name, phone in table.items():
   ...     print '{0:10} ==> {1:10d}'.format(name, phone)
   ...
   Jack       ==>       4098
   Dcab       ==>       7678
   Sjoerd     ==>       4127

If you have a really long format string that you don't want to split up, it
would be nice if you could reference the variables to be formatted by name
instead of by position.  This can be done by simply passing the dict and using
square brackets ``'[]'`` to access the keys ::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
   >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
   ...        'Dcab: {0[Dcab]:d}'.format(table))
   Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This could also be done by passing the table as keyword arguments with the '**'
notation. ::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
   >>> print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)
   Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful in combination with the built-in function
:func:`vars`, which returns a dictionary containing all local variables.

For a complete overview of string formatting with :meth:`str.format`, see
:ref:`formatstrings`.


Old string formatting
---------------------

The ``%`` operator can also be used for string formatting. It interprets the
left argument much like a :c:func:`sprintf`\ -style format string to be applied
to the right argument, and returns the string resulting from this formatting
operation. For example::

   >>> import math
   >>> print 'The value of PI is approximately %5.3f.' % math.pi
   The value of PI is approximately 3.142.

More information can be found in the :ref:`string-formatting` section.


.. _tut-files:

Reading and Writing Files
=========================

.. index::
   builtin: open
   object: file

:func:`open` returns a file object, and is most commonly used with two
arguments: ``open(filename, mode)``.

::

   >>> f = open('workfile', 'w')
   >>> print f
   <open file 'workfile', mode 'w' at 80a0960>

The first argument is a string containing the filename.  The second argument is
another string containing a few characters describing the way in which the file
will be used.  *mode* can be ``'r'`` when the file will only be read, ``'w'``
for only writing (an existing file with the same name will be erased), and
``'a'`` opens the file for appending; any data written to the file is
automatically added to the end.  ``'r+'`` opens the file for both reading and
writing. The *mode* argument is optional; ``'r'`` will be assumed if it's
omitted.

On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there
are also modes like ``'rb'``, ``'wb'``, and ``'r+b'``.  Python on Windows makes
a distinction between text and binary files; the end-of-line characters in text
files are automatically altered slightly when data is read or written.  This
behind-the-scenes modification to file data is fine for ASCII text files, but
it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files.  Be
very careful to use binary mode when reading and writing such files.  On Unix,
it doesn't hurt to append a ``'b'`` to the mode, so you can use it
platform-independently for all binary files.


.. _tut-filemethods:

Methods of File Objects
-----------------------

The rest of the examples in this section will assume that a file object called
``f`` has already been created.

To read a file's contents, call ``f.read(size)``, which reads some quantity of
data and returns it as a string.  *size* is an optional numeric argument.  When
*size* is omitted or negative, the entire contents of the file will be read and
returned; it's your problem if the file is twice as large as your machine's
memory. Otherwise, at most *size* bytes are read and returned.  If the end of
the file has been reached, ``f.read()`` will return an empty string (``""``).
::

   >>> f.read()
   'This is the entire file.\n'
   >>> f.read()
   ''

``f.readline()`` reads a single line from the file; a newline character (``\n``)
is left at the end of the string, and is only omitted on the last line of the
file if the file doesn't end in a newline.  This makes the return value
unambiguous; if ``f.readline()`` returns an empty string, the end of the file
has been reached, while a blank line is represented by ``'\n'``, a string
containing only a single newline.   ::

   >>> f.readline()
   'This is the first line of the file.\n'
   >>> f.readline()
   'Second line of the file\n'
   >>> f.readline()
   ''

For reading lines from a file, you can loop over the file object. This is memory
efficient, fast, and leads to simple code::

   >>> for line in f:
           print line,

   This is the first line of the file.
   Second line of the file

If you want to read all the lines of a file in a list you can also use
``list(f)`` or ``f.readlines()``.

``f.write(string)`` writes the contents of *string* to the file, returning
``None``.   ::

   >>> f.write('This is a test\n')

To write something other than a string, it needs to be converted to a string
first::

   >>> value = ('the answer', 42)
   >>> s = str(value)
   >>> f.write(s)

``f.tell()`` returns an integer giving the file object's current position in the
file, measured in bytes from the beginning of the file.  To change the file
object's position, use ``f.seek(offset, from_what)``.  The position is computed
from adding *offset* to a reference point; the reference point is selected by
the *from_what* argument.  A *from_what* value of 0 measures from the beginning
of the file, 1 uses the current file position, and 2 uses the end of the file as
the reference point.  *from_what* can be omitted and defaults to 0, using the
beginning of the file as the reference point. ::

   >>> f = open('workfile', 'r+')
   >>> f.write('0123456789abcdef')
   >>> f.seek(5)      # Go to the 6th byte in the file
   >>> f.read(1)
   '5'
   >>> f.seek(-3, 2)  # Go to the 3rd byte before the end
   >>> f.read(1)
   'd'

When you're done with a file, call ``f.close()`` to close it and free up any
system resources taken up by the open file.  After calling ``f.close()``,
attempts to use the file object will automatically fail. ::

   >>> f.close()
   >>> f.read()
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   ValueError: I/O operation on closed file

It is good practice to use the :keyword:`with` keyword when dealing with file
objects.  This has the advantage that the file is properly closed after its
suite finishes, even if an exception is raised on the way.  It is also much
shorter than writing equivalent :keyword:`try`\ -\ :keyword:`finally` blocks::

    >>> with open('workfile', 'r') as f:
    ...     read_data = f.read()
    >>> f.closed
    True

File objects have some additional methods, such as :meth:`~file.isatty` and
:meth:`~file.truncate` which are less frequently used; consult the Library
Reference for a complete guide to file objects.


.. _tut-json:

Saving structured data with :mod:`json`
---------------------------------------

.. index:: module: json

Strings can easily be written to and read from a file.  Numbers take a bit more
effort, since the :meth:`read` method only returns strings, which will have to
be passed to a function like :func:`int`, which takes a string like ``'123'``
and returns its numeric value 123.  When you want to save more complex data
types like nested lists and dictionaries, parsing and serializing by hand
becomes complicated.

Rather than having users constantly writing and debugging code to save
complicated data types to files, Python allows you to use the popular data
interchange format called `JSON (JavaScript Object Notation)
<http://json.org>`_.  The standard module called :mod:`json` can take Python
data hierarchies, and convert them to string representations; this process is
called :dfn:`serializing`.  Reconstructing the data from the string representation
is called :dfn:`deserializing`.  Between serializing and deserializing, the
string representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.

.. note::
   The JSON format is commonly used by modern applications to allow for data
   exchange.  Many programmers are already familiar with it, which makes
   it a good choice for interoperability.

If you have an object ``x``, you can view its JSON string representation with a
simple line of code::

   >>> import json
   >>> json.dumps([1, 'simple', 'list'])
   '[1, "simple", "list"]'

Another variant of the :func:`~json.dumps` function, called :func:`~json.dump`,
simply serializes the object to a file.  So if ``f`` is a :term:`file object`
opened for writing, we can do this::

   json.dump(x, f)

To decode the object again, if ``f`` is a :term:`file object` which has
been opened for reading::

   x = json.load(f)

This simple serialization technique can handle lists and dictionaries, but
serializing arbitrary class instances in JSON requires a bit of extra effort.
The reference for the :mod:`json` module contains an explanation of this.

.. seealso::

   :mod:`pickle` - the pickle module

   Contrary to :ref:`JSON <tut-json>`, *pickle* is a protocol which allows
   the serialization of arbitrarily complex Python objects.  As such, it is
   specific to Python and cannot be used to communicate with applications
   written in other languages.  It is also insecure by default:
   deserializing pickle data coming from an untrusted source can execute
   arbitrary code, if the data was crafted by a skilled attacker.

PK
%�\A��)__*html/_sources/tutorial/interactive.rst.txtnu�[���.. _tut-interacting:

**************************************************
Interactive Input Editing and History Substitution
**************************************************

Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell.  This is implemented using the `GNU Readline`_ library,
which supports Emacs-style and vi-style editing.  This library has its own
documentation which I won't duplicate here; however, the basics are easily
explained.  The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter.

This chapter does *not* document the editing facilities of Mark Hammond's
PythonWin package or the Tk-based environment, IDLE, distributed with Python.
The command line history recall which operates within DOS boxes on NT and some
other DOS and Windows flavors  is yet another beast.


.. _tut-lineediting:

Line Editing
============

If supported, input line editing is active whenever the interpreter prints a
primary or secondary prompt.  The current line can be edited using the
conventional Emacs control characters.  The most important of these are:
:kbd:`C-A` (Control-A) moves the cursor to the beginning of the line, :kbd:`C-E`
to the end, :kbd:`C-B` moves it one position to the left, :kbd:`C-F` to the
right.  Backspace erases the character to the left of the cursor, :kbd:`C-D` the
character to its right. :kbd:`C-K` kills (erases) the rest of the line to the
right of the cursor, :kbd:`C-Y` yanks back the last killed string.
:kbd:`C-underscore` undoes the last change you made; it can be repeated for
cumulative effect.


.. _tut-history:

History Substitution
====================

History substitution works as follows.  All non-empty input lines issued are
saved in a history buffer, and when a new prompt is given you are positioned on
a new line at the bottom of this buffer. :kbd:`C-P` moves one line up (back) in
the history buffer, :kbd:`C-N` moves one down.  Any line in the history buffer
can be edited; an asterisk appears in front of the prompt to mark a line as
modified.  Pressing the :kbd:`Return` key passes the current line to the
interpreter.  :kbd:`C-R` starts an incremental reverse search; :kbd:`C-S` starts
a forward search.


.. _tut-keybindings:

Key Bindings
============

The key bindings and some other parameters of the Readline library can be
customized by placing commands in an initialization file called
:file:`~/.inputrc`.  Key bindings have the form ::

   key-name: function-name

or ::

   "string": function-name

and options can be set with ::

   set option-name value

For example::

   # I prefer vi-style editing:
   set editing-mode vi

   # Edit using a single line:
   set horizontal-scroll-mode On

   # Rebind some keys:
   Meta-h: backward-kill-word
   "\C-u": universal-argument
   "\C-x\C-r": re-read-init-file

Note that the default binding for :kbd:`Tab` in Python is to insert a :kbd:`Tab`
character instead of Readline's default filename completion function.  If you
insist, you can override this by putting ::

   Tab: complete

in your :file:`~/.inputrc`.  (Of course, this makes it harder to type indented
continuation lines if you're accustomed to using :kbd:`Tab` for that purpose.)

.. index::
   module: rlcompleter
   module: readline

Automatic completion of variable and module names is optionally available.  To
enable it in the interpreter's interactive mode, add the following to your
startup file: [#]_  ::

   import rlcompleter, readline
   readline.parse_and_bind('tab: complete')

This binds the :kbd:`Tab` key to the completion function, so hitting the
:kbd:`Tab` key twice suggests completions; it looks at Python statement names,
the current local variables, and the available module names.  For dotted
expressions such as ``string.a``, it will evaluate the expression up to the
final ``'.'`` and then suggest completions from the attributes of the resulting
object.  Note that this may execute application-defined code if an object with a
:meth:`__getattr__` method is part of the expression.

A more capable startup file might look like this example.  Note that this
deletes the names it creates once they are no longer needed; this is done since
the startup file is executed in the same namespace as the interactive commands,
and removing the names avoids creating side effects in the interactive
environment.  You may find it convenient to keep some of the imported modules,
such as :mod:`os`, which turn out to be needed in most sessions with the
interpreter. ::

   # Add auto-completion and a stored history file of commands to your Python
   # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
   # bound to the Esc key by default (you can change it - see readline docs).
   #
   # Store the file in ~/.pystartup, and set an environment variable to point
   # to it:  "export PYTHONSTARTUP=~/.pystartup" in bash.

   import atexit
   import os
   import readline
   import rlcompleter

   historyPath = os.path.expanduser("~/.pyhistory")

   def save_history(historyPath=historyPath):
       import readline
       readline.write_history_file(historyPath)

   if os.path.exists(historyPath):
       readline.read_history_file(historyPath)

   atexit.register(save_history)
   del os, atexit, readline, rlcompleter, save_history, historyPath


.. _tut-commentary:

Alternatives to the Interactive Interpreter
===========================================

This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper
indentation were suggested on continuation lines (the parser knows if an indent
token is required next).  The completion mechanism might use the interpreter's
symbol table.  A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.

One alternative enhanced interactive interpreter that has been around for quite
some time is IPython_, which features tab completion, object exploration and
advanced history management.  It can also be thoroughly customized and embedded
into other applications.  Another similar enhanced interactive environment is
bpython_.


.. rubric:: Footnotes

.. [#] Python will execute the contents of a file identified by the
   :envvar:`PYTHONSTARTUP` environment variable when you start an interactive
   interpreter.  To customize Python even for non-interactive mode, see
   :ref:`tut-customize`.


.. _GNU Readline: https://tiswww.case.edu/php/chet/readline/rltop.html
.. _IPython: http://ipython.scipy.org/
.. _bpython: http://www.bpython-interpreter.org/
PK
%�\�~+��*html/_sources/tutorial/interpreter.rst.txtnu�[���.. _tut-using:

****************************
Using the Python Interpreter
****************************


.. _tut-invoking:

Invoking the Interpreter
========================

The Python interpreter is usually installed as :file:`/usr/local/bin/python` on
those machines where it is available; putting :file:`/usr/local/bin` in your
Unix shell's search path makes it possible to start it by typing the command ::

   python

to the shell.  Since the choice of the directory where the interpreter lives is
an installation option, other places are possible; check with your local Python
guru or system administrator.  (E.g., :file:`/usr/local/python` is a popular
alternative location.)

On Windows machines, the Python installation is usually placed in
:file:`C:\\Python27`, though you can change this when you're running the
installer.  To add this directory to your path,  you can type the following
command into the command prompt in a DOS box::

   set path=%path%;C:\python27

Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status.  If that doesn't work, you can exit the interpreter by typing the
following command: ``quit()``.

The interpreter's line-editing features usually aren't very sophisticated.  On
Unix, whoever installed the interpreter may have enabled support for the GNU
readline library, which adds more elaborate interactive editing and history
features. Perhaps the quickest check to see whether command line editing is
supported is typing :kbd:`Control-P` to the first Python prompt you get.  If it beeps,
you have command line editing; see Appendix :ref:`tut-interacting` for an
introduction to the keys.  If nothing appears to happen, or if ``^P`` is echoed,
command line editing isn't available; you'll only be able to use backspace to
remove characters from the current line.

The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a *script* from that file.

A second way of starting the interpreter is ``python -c command [arg] ...``,
which executes the statement(s) in *command*, analogous to the shell's
:option:`-c` option.  Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
*command* in its entirety with single quotes.

Some Python modules are also useful as scripts.  These can be invoked using
``python -m module [arg] ...``, which executes the source file for *module* as
if you had spelled out its full name on the command line.

When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards.  This can be done by passing :option:`-i`
before the script.

All command-line options are described in :ref:`using-on-general`.


.. _tut-argpassing:

Argument Passing
----------------

When known to the interpreter, the script name and additional arguments
thereafter are turned into a list of strings and assigned to the ``argv``
variable in the ``sys`` module.  You can access this list by executing ``import
sys``.  The length of the list is at least one; when no script and no arguments
are given, ``sys.argv[0]`` is an empty string.  When the script name is given as
``'-'`` (meaning  standard input), ``sys.argv[0]`` is set to ``'-'``.  When
:option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``.  When
:option:`-m` *module* is used, ``sys.argv[0]``  is set to the full name of the
located module.  Options found after  :option:`-c` *command* or :option:`-m`
*module* are not consumed  by the Python interpreter's option processing but
left in ``sys.argv`` for  the command or module to handle.


.. _tut-interactive:

Interactive Mode
----------------

When commands are read from a tty, the interpreter is said to be in *interactive
mode*.  In this mode it prompts for the next command with the *primary prompt*,
usually three greater-than signs (``>>>``); for continuation lines it prompts
with the *secondary prompt*, by default three dots (``...``). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:

.. code-block:: shell-session

   python
   Python 2.7 (#1, Feb 28 2010, 00:02:06)
   Type "help", "copyright", "credits" or "license" for more information.
   >>>

Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this :keyword:`if` statement::

   >>> the_world_is_flat = 1
   >>> if the_world_is_flat:
   ...     print "Be careful not to fall off!"
   ...
   Be careful not to fall off!


For more on interactive mode, see :ref:`tut-interac`.


.. _tut-interp:

The Interpreter and Its Environment
===================================


.. _tut-source-encoding:

Source Code Encoding
--------------------

By default, Python source files are treated as encoded in ASCII.
To declare an encoding other than the default one, a special comment line
should be added as the *first* line of the file.  The syntax is as follows::

   # -*- coding: encoding -*-

where *encoding* is one of the valid :mod:`codecs` supported by Python.

For example, to declare that Windows-1252 encoding is to be used, the first
line of your source code file should be::

   # -*- coding: cp1252 -*-

One exception to the *first line* rule is when the source code starts with a
:ref:`UNIX "shebang" line <tut-scripts>`.  In this case, the encoding
declaration should be added as the second line of the file.  For example::

   #!/usr/bin/env python
   # -*- coding: cp1252 -*-

PK
%�\g�J�OUOU+html/_sources/tutorial/introduction.rst.txtnu�[���.. _tut-informal:

**********************************
An Informal Introduction to Python
**********************************

In the following examples, input and output are distinguished by the presence or
absence of prompts (:term:`>>>` and :term:`...`): to repeat the example, you must type
everything after the prompt, when the prompt appears; lines that do not begin
with a prompt are output from the interpreter. Note that a secondary prompt on a
line by itself in an example means you must type a blank line; this is used to
end a multi-line command.

Many of the examples in this manual, even those entered at the interactive
prompt, include comments.  Comments in Python start with the hash character,
``#``, and extend to the end of the physical line.  A comment may appear at the
start of a line or following whitespace or code, but not within a string
literal.  A hash character within a string literal is just a hash character.
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.

Some examples::

   # this is the first comment
   spam = 1  # and this is the second comment
             # ... and now a third!
   text = "# This is not a comment because it's inside quotes."


.. _tut-calculator:

Using Python as a Calculator
============================

Let's try some simple Python commands.  Start the interpreter and wait for the
primary prompt, ``>>>``.  (It shouldn't take long.)


.. _tut-numbers:

Numbers
-------

The interpreter acts as a simple calculator: you can type an expression at it
and it will write the value.  Expression syntax is straightforward: the
operators ``+``, ``-``, ``*`` and ``/`` work just like in most other languages
(for example, Pascal or C); parentheses (``()``) can be used for grouping.
For example::

   >>> 2 + 2
   4
   >>> 50 - 5*6
   20
   >>> (50 - 5.0*6) / 4
   5.0
   >>> 8 / 5.0
   1.6

The integer numbers (e.g. ``2``, ``4``, ``20``) have type :class:`int`,
the ones with a fractional part (e.g. ``5.0``, ``1.6``) have type
:class:`float`.  We will see more about numeric types later in the tutorial.

The return type of a division (``/``) operation depends on its operands.  If
both operands are of type :class:`int`, :term:`floor division` is performed
and an :class:`int` is returned.  If either operand is a :class:`float`,
classic division is performed and a :class:`float` is returned.  The ``//``
operator is also provided for doing floor division no matter what the
operands are.  The remainder can be calculated with the ``%`` operator::

   >>> 17 / 3  # int / int -> int
   5
   >>> 17 / 3.0  # int / float -> float
   5.666666666666667
   >>> 17 // 3.0  # explicit floor division discards the fractional part
   5.0
   >>> 17 % 3  # the % operator returns the remainder of the division
   2
   >>> 5 * 3 + 2  # result * divisor + remainder
   17

With Python, it is possible to use the ``**`` operator to calculate powers [#]_::

   >>> 5 ** 2  # 5 squared
   25
   >>> 2 ** 7  # 2 to the power of 7
   128

The equal sign (``=``) is used to assign a value to a variable. Afterwards, no
result is displayed before the next interactive prompt::

   >>> width = 20
   >>> height = 5 * 9
   >>> width * height
   900

If a variable is not "defined" (assigned a value), trying to use it will
give you an error::

   >>> n  # try to access an undefined variable
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   NameError: name 'n' is not defined

There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point::

   >>> 3 * 3.75 / 1.5
   7.5
   >>> 7.0 / 2
   3.5

In interactive mode, the last printed expression is assigned to the variable
``_``.  This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example::

   >>> tax = 12.5 / 100
   >>> price = 100.50
   >>> price * tax
   12.5625
   >>> price + _
   113.0625
   >>> round(_, 2)
   113.06

This variable should be treated as read-only by the user.  Don't explicitly
assign a value to it --- you would create an independent local variable with the
same name masking the built-in variable with its magic behavior.

In addition to :class:`int` and :class:`float`, Python supports other types of
numbers, such as :class:`~decimal.Decimal` and :class:`~fractions.Fraction`.
Python also has built-in support for :ref:`complex numbers <typesnumeric>`,
and uses the ``j`` or ``J`` suffix to indicate the imaginary part
(e.g. ``3+5j``).


.. _tut-strings:

Strings
-------

Besides numbers, Python can also manipulate strings, which can be expressed
in several ways.  They can be enclosed in single quotes (``'...'``) or
double quotes (``"..."``) with the same result [#]_.  ``\`` can be used
to escape quotes::

   >>> 'spam eggs'  # single quotes
   'spam eggs'
   >>> 'doesn\'t'  # use \' to escape the single quote...
   "doesn't"
   >>> "doesn't"  # ...or use double quotes instead
   "doesn't"
   >>> '"Yes," they said.'
   '"Yes," they said.'
   >>> "\"Yes,\" they said."
   '"Yes," they said.'
   >>> '"Isn\'t," they said.'
   '"Isn\'t," they said.'

In the interactive interpreter, the output string is enclosed in quotes and
special characters are escaped with backslashes.  While this might sometimes
look different from the input (the enclosing quotes could change), the two
strings are equivalent.  The string is enclosed in double quotes if
the string contains a single quote and no double quotes, otherwise it is
enclosed in single quotes.  The :keyword:`print` statement produces a more
readable output, by omitting the enclosing quotes and by printing escaped
and special characters::

   >>> '"Isn\'t," they said.'
   '"Isn\'t," they said.'
   >>> print '"Isn\'t," they said.'
   "Isn't," they said.
   >>> s = 'First line.\nSecond line.'  # \n means newline
   >>> s  # without print, \n is included in the output
   'First line.\nSecond line.'
   >>> print s  # with print, \n produces a new line
   First line.
   Second line.

If you don't want characters prefaced by ``\`` to be interpreted as
special characters, you can use *raw strings* by adding an ``r`` before
the first quote::

   >>> print 'C:\some\name'  # here \n means newline!
   C:\some
   ame
   >>> print r'C:\some\name'  # note the r before the quote
   C:\some\name

String literals can span multiple lines.  One way is using triple-quotes:
``"""..."""`` or ``'''...'''``.  End of lines are automatically
included in the string, but it's possible to prevent this by adding a ``\`` at
the end of the line.  The following example::

   print """\
   Usage: thingy [OPTIONS]
        -h                        Display this usage message
        -H hostname               Hostname to connect to
   """

produces the following output (note that the initial newline is not included):

.. code-block:: text

   Usage: thingy [OPTIONS]
        -h                        Display this usage message
        -H hostname               Hostname to connect to

Strings can be concatenated (glued together) with the ``+`` operator, and
repeated with ``*``::

   >>> # 3 times 'un', followed by 'ium'
   >>> 3 * 'un' + 'ium'
   'unununium'

Two or more *string literals* (i.e. the ones enclosed between quotes) next
to each other are automatically concatenated. ::

   >>> 'Py' 'thon'
   'Python'

This feature is particularly useful when you want to break long strings::

   >>> text = ('Put several strings within parentheses '
   ...         'to have them joined together.')
   >>> text
   'Put several strings within parentheses to have them joined together.'

This only works with two literals though, not with variables or expressions::

   >>> prefix = 'Py'
   >>> prefix 'thon'  # can't concatenate a variable and a string literal
     ...
   SyntaxError: invalid syntax
   >>> ('un' * 3) 'ium'
     ...
   SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use ``+``::

   >>> prefix + 'thon'
   'Python'

Strings can be *indexed* (subscripted), with the first character having index 0.
There is no separate character type; a character is simply a string of size
one::

   >>> word = 'Python'
   >>> word[0]  # character in position 0
   'P'
   >>> word[5]  # character in position 5
   'n'

Indices may also be negative numbers, to start counting from the right::

   >>> word[-1]  # last character
   'n'
   >>> word[-2]  # second-last character
   'o'
   >>> word[-6]
   'P'

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, *slicing* is also supported.  While indexing is used
to obtain individual characters, *slicing* allows you to obtain a substring::

   >>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
   'Py'
   >>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
   'tho'

Note how the start is always included, and the end always excluded.  This
makes sure that ``s[:i] + s[i:]`` is always equal to ``s``::

   >>> word[:2] + word[2:]
   'Python'
   >>> word[:4] + word[4:]
   'Python'

Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced. ::

   >>> word[:2]   # character from the beginning to position 2 (excluded)
   'Py'
   >>> word[4:]   # characters from position 4 (included) to the end
   'on'
   >>> word[-2:]  # characters from the second-last (included) to the end
   'on'

One way to remember how slices work is to think of the indices as pointing
*between* characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of *n* characters has
index *n*, for example::

    +---+---+---+---+---+---+
    | P | y | t | h | o | n |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
   -6  -5  -4  -3  -2  -1

The first row of numbers gives the position of the indices 0...6 in the string;
the second row gives the corresponding negative indices. The slice from *i* to
*j* consists of all characters between the edges labeled *i* and *j*,
respectively.

For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds.  For example, the length of ``word[1:3]`` is
2.

Attempting to use an index that is too large will result in an error::

   >>> word[42]  # the word only has 6 characters
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for
slicing::

   >>> word[4:42]
   'on'
   >>> word[42:]
   ''

Python strings cannot be changed --- they are :term:`immutable`.
Therefore, assigning to an indexed position in the string results in an error::

   >>> word[0] = 'J'
     ...
   TypeError: 'str' object does not support item assignment
   >>> word[2:] = 'py'
     ...
   TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one::

   >>> 'J' + word[1:]
   'Jython'
   >>> word[:2] + 'py'
   'Pypy'

The built-in function :func:`len` returns the length of a string::

   >>> s = 'supercalifragilisticexpialidocious'
   >>> len(s)
   34


.. seealso::

   :ref:`typesseq`
      Strings, and the Unicode strings described in the next section, are
      examples of *sequence types*, and support the common operations supported
      by such types.

   :ref:`string-methods`
      Both strings and Unicode strings support a large number of methods for
      basic transformations and searching.

   :ref:`formatstrings`
      Information about string formatting with :meth:`str.format`.

   :ref:`string-formatting`
      The old formatting operations invoked when strings and Unicode strings are
      the left operand of the ``%`` operator are described in more detail here.


.. _tut-unicodestrings:

Unicode Strings
---------------

.. sectionauthor:: Marc-Andre Lemburg <mal@lemburg.com>


Starting with Python 2.0 a new data type for storing text data is available to
the programmer: the Unicode object. It can be used to store and manipulate
Unicode data (see http://www.unicode.org/) and integrates well with the existing
string objects, providing auto-conversions where necessary.

Unicode has the advantage of providing one ordinal for every character in every
script used in modern and ancient texts. Previously, there were only 256
possible ordinals for script characters. Texts were typically bound to a code
page which mapped the ordinals to script characters. This lead to very much
confusion especially with respect to internationalization (usually written as
``i18n`` --- ``'i'`` + 18 characters + ``'n'``) of software.  Unicode solves
these problems by defining one code page for all scripts.

Creating Unicode strings in Python is just as simple as creating normal
strings::

   >>> u'Hello World !'
   u'Hello World !'

The small ``'u'`` in front of the quote indicates that a Unicode string is
supposed to be created. If you want to include special characters in the string,
you can do so by using the Python *Unicode-Escape* encoding. The following
example shows how::

   >>> u'Hello\u0020World !'
   u'Hello World !'

The escape sequence ``\u0020`` indicates to insert the Unicode character with
the ordinal value 0x0020 (the space character) at the given position.

Other characters are interpreted by using their respective ordinal values
directly as Unicode ordinals.  If you have literal strings in the standard
Latin-1 encoding that is used in many Western countries, you will find it
convenient that the lower 256 characters of Unicode are the same as the 256
characters of Latin-1.

For experts, there is also a raw mode just like the one for normal strings. You
have to prefix the opening quote with 'ur' to have Python use the
*Raw-Unicode-Escape* encoding. It will only apply the above ``\uXXXX``
conversion if there is an uneven number of backslashes in front of the small
'u'. ::

   >>> ur'Hello\u0020World !'
   u'Hello World !'
   >>> ur'Hello\\u0020World !'
   u'Hello\\\\u0020World !'

The raw mode is most useful when you have to enter lots of backslashes, as can
be necessary in regular expressions.

Apart from these standard encodings, Python provides a whole set of other ways
of creating Unicode strings on the basis of a known encoding.

.. index:: builtin: unicode

The built-in function :func:`unicode` provides access to all registered Unicode
codecs (COders and DECoders). Some of the more well known encodings which these
codecs can convert are *Latin-1*, *ASCII*, *UTF-8*, and *UTF-16*. The latter two
are variable-length encodings that store each Unicode character in one or more
bytes. The default encoding is normally set to ASCII, which passes through
characters in the range 0 to 127 and rejects any other characters with an error.
When a Unicode string is printed, written to a file, or converted with
:func:`str`, conversion takes place using this default encoding. ::

   >>> u"abc"
   u'abc'
   >>> str(u"abc")
   'abc'
   >>> u"äöü"
   u'\xe4\xf6\xfc'
   >>> str(u"äöü")
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

To convert a Unicode string into an 8-bit string using a specific encoding,
Unicode objects provide an :func:`encode` method that takes one argument, the
name of the encoding.  Lowercase names for encodings are preferred. ::

   >>> u"äöü".encode('utf-8')
   '\xc3\xa4\xc3\xb6\xc3\xbc'

If you have data in a specific encoding and want to produce a corresponding
Unicode string from it, you can use the :func:`unicode` function with the
encoding name as the second argument. ::

   >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
   u'\xe4\xf6\xfc'


.. _tut-lists:

Lists
-----

Python knows a number of *compound* data types, used to group together other
values.  The most versatile is the *list*, which can be written as a list of
comma-separated values (items) between square brackets.  Lists might contain
items of different types, but usually the items all have the same type. ::

   >>> squares = [1, 4, 9, 16, 25]
   >>> squares
   [1, 4, 9, 16, 25]

Like strings (and all other built-in :term:`sequence` type), lists can be
indexed and sliced::

   >>> squares[0]  # indexing returns the item
   1
   >>> squares[-1]
   25
   >>> squares[-3:]  # slicing returns a new list
   [9, 16, 25]

All slice operations return a new list containing the requested elements.  This
means that the following slice returns a new (shallow) copy of the list::

   >>> squares[:]
   [1, 4, 9, 16, 25]

Lists also supports operations like concatenation::

   >>> squares + [36, 49, 64, 81, 100]
   [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike strings, which are :term:`immutable`, lists are a :term:`mutable`
type, i.e. it is possible to change their content::

    >>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
    >>> 4 ** 3  # the cube of 4 is 64, not 65!
    64
    >>> cubes[3] = 64  # replace the wrong value
    >>> cubes
    [1, 8, 27, 64, 125]

You can also add new items at the end of the list, by using
the :meth:`~list.append` *method* (we will see more about methods later)::

   >>> cubes.append(216)  # add the cube of 6
   >>> cubes.append(7 ** 3)  # and the cube of 7
   >>> cubes
   [1, 8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely::

   >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
   >>> letters
   ['a', 'b', 'c', 'd', 'e', 'f', 'g']
   >>> # replace some values
   >>> letters[2:5] = ['C', 'D', 'E']
   >>> letters
   ['a', 'b', 'C', 'D', 'E', 'f', 'g']
   >>> # now remove them
   >>> letters[2:5] = []
   >>> letters
   ['a', 'b', 'f', 'g']
   >>> # clear the list by replacing all the elements with an empty list
   >>> letters[:] = []
   >>> letters
   []

The built-in function :func:`len` also applies to lists::

   >>> letters = ['a', 'b', 'c', 'd']
   >>> len(letters)
   4

It is possible to nest lists (create lists containing other lists), for
example::

   >>> a = ['a', 'b', 'c']
   >>> n = [1, 2, 3]
   >>> x = [a, n]
   >>> x
   [['a', 'b', 'c'], [1, 2, 3]]
   >>> x[0]
   ['a', 'b', 'c']
   >>> x[0][1]
   'b'

.. _tut-firststeps:

First Steps Towards Programming
===============================

Of course, we can use Python for more complicated tasks than adding two and two
together.  For instance, we can write an initial sub-sequence of the *Fibonacci*
series as follows::

   >>> # Fibonacci series:
   ... # the sum of two elements defines the next
   ... a, b = 0, 1
   >>> while b < 10:
   ...     print b
   ...     a, b = b, a+b
   ...
   1
   1
   2
   3
   5
   8

This example introduces several new features.

* The first line contains a *multiple assignment*: the variables ``a`` and ``b``
  simultaneously get the new values 0 and 1.  On the last line this is used again,
  demonstrating that the expressions on the right-hand side are all evaluated
  first before any of the assignments take place.  The right-hand side expressions
  are evaluated  from the left to the right.

* The :keyword:`while` loop executes as long as the condition (here: ``b < 10``)
  remains true.  In Python, like in C, any non-zero integer value is true; zero is
  false.  The condition may also be a string or list value, in fact any sequence;
  anything with a non-zero length is true, empty sequences are false.  The test
  used in the example is a simple comparison.  The standard comparison operators
  are written the same as in C: ``<`` (less than), ``>`` (greater than), ``==``
  (equal to), ``<=`` (less than or equal to), ``>=`` (greater than or equal to)
  and ``!=`` (not equal to).

* The *body* of the loop is *indented*: indentation is Python's way of grouping
  statements.  At the interactive prompt, you have to type a tab or space(s) for
  each indented line.  In practice you will prepare more complicated input
  for Python with a text editor; all decent text editors have an auto-indent
  facility.  When a compound statement is entered interactively, it must be
  followed by a blank line to indicate completion (since the parser cannot
  guess when you have typed the last line).  Note that each line within a basic
  block must be indented by the same amount.

* The :keyword:`print` statement writes the value of the expression(s) it is
  given.  It differs from just writing the expression you want to write (as we did
  earlier in the calculator examples) in the way it handles multiple expressions
  and strings.  Strings are printed without quotes, and a space is inserted
  between items, so you can format things nicely, like this::

     >>> i = 256*256
     >>> print 'The value of i is', i
     The value of i is 65536

  A trailing comma avoids the newline after the output::

     >>> a, b = 0, 1
     >>> while b < 1000:
     ...     print b,
     ...     a, b = b, a+b
     ...
     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

  Note that the interpreter inserts a newline before it prints the next prompt if
  the last line was not completed.

.. rubric:: Footnotes

.. [#] Since ``**`` has higher precedence than ``-``, ``-3**2`` will be
   interpreted as ``-(3**2)`` and thus result in ``-9``.  To avoid this
   and get ``9``, you can use ``(-3)**2``.

.. [#] Unlike other languages, special characters such as ``\n`` have the
   same meaning with both single (``'...'``) and double (``"..."``) quotes.
   The only difference between the two is that within single quotes you don't
   need to escape ``"`` (but you have to escape ``\'``) and vice versa.
PK
%�\���+W`W`&html/_sources/tutorial/modules.rst.txtnu�[���.. _tut-modules:

*******
Modules
*******

If you quit from the Python interpreter and enter it again, the definitions you
have made (functions and variables) are lost. Therefore, if you want to write a
somewhat longer program, you are better off using a text editor to prepare the
input for the interpreter and running it with that file as input instead.  This
is known as creating a *script*.  As your program gets longer, you may want to
split it into several files for easier maintenance.  You may also want to use a
handy function that you've written in several programs without copying its
definition into each program.

To support this, Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is called a
*module*; definitions from a module can be *imported* into other modules or into
the *main* module (the collection of variables that you have access to in a
script executed at the top level and in calculator mode).

A module is a file containing Python definitions and statements.  The file name
is the module name with the suffix :file:`.py` appended.  Within a module, the
module's name (as a string) is available as the value of the global variable
``__name__``.  For instance, use your favorite text editor to create a file
called :file:`fibo.py` in the current directory with the following contents::

   # Fibonacci numbers module

   def fib(n):    # write Fibonacci series up to n
       a, b = 0, 1
       while b < n:
           print b,
           a, b = b, a+b

   def fib2(n):   # return Fibonacci series up to n
       result = []
       a, b = 0, 1
       while b < n:
           result.append(b)
           a, b = b, a+b
       return result

Now enter the Python interpreter and import this module with the following
command::

   >>> import fibo

This does not enter the names of the functions defined in ``fibo``  directly in
the current symbol table; it only enters the module name ``fibo`` there. Using
the module name you can access the functions::

   >>> fibo.fib(1000)
   1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
   >>> fibo.fib2(100)
   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
   >>> fibo.__name__
   'fibo'

If you intend to use a function often you can assign it to a local name::

   >>> fib = fibo.fib
   >>> fib(500)
   1 1 2 3 5 8 13 21 34 55 89 144 233 377


.. _tut-moremodules:

More on Modules
===============

A module can contain executable statements as well as function definitions.
These statements are intended to initialize the module. They are executed only
the *first* time the module name is encountered in an import statement. [#]_
(They are also run if the file is executed as a script.)

Each module has its own private symbol table, which is used as the global symbol
table by all functions defined in the module. Thus, the author of a module can
use global variables in the module without worrying about accidental clashes
with a user's global variables. On the other hand, if you know what you are
doing you can touch a module's global variables with the same notation used to
refer to its functions, ``modname.itemname``.

Modules can import other modules.  It is customary but not required to place all
:keyword:`import` statements at the beginning of a module (or script, for that
matter).  The imported module names are placed in the importing module's global
symbol table.

There is a variant of the :keyword:`import` statement that imports names from a
module directly into the importing module's symbol table.  For example::

   >>> from fibo import fib, fib2
   >>> fib(500)
   1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the
local symbol table (so in the example, ``fibo`` is not defined).

There is even a variant to import all names that a module defines::

   >>> from fibo import *
   >>> fib(500)
   1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (``_``).

Note that in general the practice of importing ``*`` from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to
use it to save typing in interactive sessions.

If the module name is followed by :keyword:`as`, then the name
following :keyword:`as` is bound directly to the imported module.

::

   >>> import fibo as fib
   >>> fib.fib(500)
   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This is effectively importing the module in the same way that ``import fibo``
will do, with the only difference of it being available as ``fib``.

It can also be used when utilising :keyword:`from` with similar effects::

   >>> from fibo import fib as fibonacci
   >>> fibonacci(500)
   0 1 1 2 3 5 8 13 21 34 55 89 144 233 377


.. note::

   For efficiency reasons, each module is only imported once per interpreter
   session.  Therefore, if you change your modules, you must restart the
   interpreter -- or, if it's just one module you want to test interactively,
   use :func:`reload`, e.g. ``reload(modulename)``.


.. _tut-modulesasscripts:

Executing modules as scripts
----------------------------

When you run a Python module with ::

   python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with
the ``__name__`` set to ``"__main__"``.  That means that by adding this code at
the end of your module::

   if __name__ == "__main__":
       import sys
       fib(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module,
because the code that parses the command line only runs if the module is
executed as the "main" file:

.. code-block:: shell-session

   $ python fibo.py 50
   1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run::

   >>> import fibo
   >>>

This is often used either to provide a convenient user interface to a module, or
for testing purposes (running the module as a script executes a test suite).


.. _tut-searchpath:

The Module Search Path
----------------------

.. index:: triple: module; search; path

When a module named :mod:`spam` is imported, the interpreter first searches for
a built-in module with that name. If not found, it then searches for a file
named :file:`spam.py` in a list of directories given by the variable
:data:`sys.path`.  :data:`sys.path` is initialized from these locations:

* the directory containing the input script (or the current directory).
* :envvar:`PYTHONPATH` (a list of directory names, with the same syntax as the
  shell variable :envvar:`PATH`).
* the installation-dependent default.

After initialization, Python programs can modify :data:`sys.path`.  The
directory containing the script being run is placed at the beginning of the
search path, ahead of the standard library path. This means that scripts in that
directory will be loaded instead of modules of the same name in the library
directory. This is an error unless the replacement is intended.  See section
:ref:`tut-standardmodules` for more information.


"Compiled" Python files
-----------------------

As an important speed-up of the start-up time for short programs that use a lot
of standard modules, if a file called :file:`spam.pyc` exists in the directory
where :file:`spam.py` is found, this is assumed to contain an
already-"byte-compiled" version of the module :mod:`spam`. The modification time
of the version of :file:`spam.py` used to create :file:`spam.pyc` is recorded in
:file:`spam.pyc`, and the :file:`.pyc` file is ignored if these don't match.

Normally, you don't need to do anything to create the :file:`spam.pyc` file.
Whenever :file:`spam.py` is successfully compiled, an attempt is made to write
the compiled version to :file:`spam.pyc`.  It is not an error if this attempt
fails; if for any reason the file is not written completely, the resulting
:file:`spam.pyc` file will be recognized as invalid and thus ignored later.  The
contents of the :file:`spam.pyc` file are platform independent, so a Python
module directory can be shared by machines of different architectures.

Some tips for experts:

* When the Python interpreter is invoked with the :option:`-O` flag, optimized
  code is generated and stored in :file:`.pyo` files.  The optimizer currently
  doesn't help much; it only removes :keyword:`assert` statements.  When
  :option:`-O` is used, *all* :term:`bytecode` is optimized; ``.pyc`` files are
  ignored and ``.py`` files are compiled to optimized bytecode.

* Passing two :option:`-O` flags to the Python interpreter (:option:`-OO`) will
  cause the bytecode compiler to perform optimizations that could in some rare
  cases result in malfunctioning programs.  Currently only ``__doc__`` strings are
  removed from the bytecode, resulting in more compact :file:`.pyo` files.  Since
  some programs may rely on having these available, you should only use this
  option if you know what you're doing.

* A program doesn't run any faster when it is read from a :file:`.pyc` or
  :file:`.pyo` file than when it is read from a :file:`.py` file; the only thing
  that's faster about :file:`.pyc` or :file:`.pyo` files is the speed with which
  they are loaded.

* When a script is run by giving its name on the command line, the bytecode for
  the script is never written to a :file:`.pyc` or :file:`.pyo` file.  Thus, the
  startup time of a script may be reduced by moving most of its code to a module
  and having a small bootstrap script that imports that module.  It is also
  possible to name a :file:`.pyc` or :file:`.pyo` file directly on the command
  line.

* It is possible to have a file called :file:`spam.pyc` (or :file:`spam.pyo`
  when :option:`-O` is used) without a file :file:`spam.py` for the same module.
  This can be used to distribute a library of Python code in a form that is
  moderately hard to reverse engineer.

  .. index:: module: compileall

* The module :mod:`compileall` can create :file:`.pyc` files (or :file:`.pyo`
  files when :option:`-O` is used) for all modules in a directory.


.. _tut-standardmodules:

Standard Modules
================

.. index:: module: sys

Python comes with a library of standard modules, described in a separate
document, the Python Library Reference ("Library Reference" hereafter).  Some
modules are built into the interpreter; these provide access to operations that
are not part of the core of the language but are nevertheless built in, either
for efficiency or to provide access to operating system primitives such as
system calls.  The set of such modules is a configuration option which also
depends on the underlying platform.  For example, the :mod:`winreg` module is only
provided on Windows systems. One particular module deserves some attention:
:mod:`sys`, which is built into every Python interpreter.  The variables
``sys.ps1`` and ``sys.ps2`` define the strings used as primary and secondary
prompts::

   >>> import sys
   >>> sys.ps1
   '>>> '
   >>> sys.ps2
   '... '
   >>> sys.ps1 = 'C> '
   C> print 'Yuck!'
   Yuck!
   C>


These two variables are only defined if the interpreter is in interactive mode.

The variable ``sys.path`` is a list of strings that determines the interpreter's
search path for modules. It is initialized to a default path taken from the
environment variable :envvar:`PYTHONPATH`, or from a built-in default if
:envvar:`PYTHONPATH` is not set.  You can modify it using standard list
operations::

   >>> import sys
   >>> sys.path.append('/ufs/guido/lib/python')


.. _tut-dir:

The :func:`dir` Function
========================

The built-in function :func:`dir` is used to find out which names a module
defines.  It returns a sorted list of strings::

   >>> import fibo, sys
   >>> dir(fibo)
   ['__name__', 'fib', 'fib2']
   >>> dir(sys)  # doctest: +NORMALIZE_WHITESPACE
   ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__',
    '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache',
    '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv',
    'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
    'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info',
    'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix',
    'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
    'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
    'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
    'getrefcount', 'getsizeof', 'gettotalrefcount', 'gettrace', 'hexversion',
    'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules',
    'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
    'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile',
    'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion',
    'version', 'version_info', 'warnoptions']

Without arguments, :func:`dir` lists the names you have defined currently::

   >>> a = [1, 2, 3, 4, 5]
   >>> import fibo
   >>> fib = fibo.fib
   >>> dir()
   ['__builtins__', '__name__', '__package__', 'a', 'fib', 'fibo', 'sys']

Note that it lists all types of names: variables, modules, functions, etc.

.. index:: module: __builtin__

:func:`dir` does not list the names of built-in functions and variables.  If you
want a list of those, they are defined in the standard module
:mod:`__builtin__`::

   >>> import __builtin__
   >>> dir(__builtin__)  # doctest: +NORMALIZE_WHITESPACE
   ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
    'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError',
    'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError',
    'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning',
    'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
    'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
    'NotImplementedError', 'OSError', 'OverflowError',
    'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
    'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
    'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
    'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
    'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
    'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning',
    'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
    '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring',
    'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr',
    'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright',
    'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval',
    'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset',
    'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input',
    'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license',
    'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next',
    'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit',
    'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round',
    'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
    'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']


.. _tut-packages:

Packages
========

Packages are a way of structuring Python's module namespace by using "dotted
module names".  For example, the module name :mod:`A.B` designates a submodule
named ``B`` in a package named ``A``.  Just like the use of modules saves the
authors of different modules from having to worry about each other's global
variable names, the use of dotted module names saves the authors of multi-module
packages like NumPy or Pillow from having to worry about
each other's module names.

Suppose you want to design a collection of modules (a "package") for the uniform
handling of sound files and sound data.  There are many different sound file
formats (usually recognized by their extension, for example: :file:`.wav`,
:file:`.aiff`, :file:`.au`), so you may need to create and maintain a growing
collection of modules for the conversion between the various file formats.
There are also many different operations you might want to perform on sound data
(such as mixing, adding echo, applying an equalizer function, creating an
artificial stereo effect), so in addition you will be writing a never-ending
stream of modules to perform these operations.  Here's a possible structure for
your package (expressed in terms of a hierarchical filesystem):

.. code-block:: text

   sound/                          Top-level package
         __init__.py               Initialize the sound package
         formats/                  Subpackage for file format conversions
                 __init__.py
                 wavread.py
                 wavwrite.py
                 aiffread.py
                 aiffwrite.py
                 auread.py
                 auwrite.py
                 ...
         effects/                  Subpackage for sound effects
                 __init__.py
                 echo.py
                 surround.py
                 reverse.py
                 ...
         filters/                  Subpackage for filters
                 __init__.py
                 equalizer.py
                 vocoder.py
                 karaoke.py
                 ...

When importing the package, Python searches through the directories on
``sys.path`` looking for the package subdirectory.

The :file:`__init__.py` files are required to make Python treat the directories
as containing packages; this is done to prevent directories with a common name,
such as ``string``, from unintentionally hiding valid modules that occur later
on the module search path. In the simplest case, :file:`__init__.py` can just be
an empty file, but it can also execute initialization code for the package or
set the ``__all__`` variable, described later.

Users of the package can import individual modules from the package, for
example::

   import sound.effects.echo

This loads the submodule :mod:`sound.effects.echo`.  It must be referenced with
its full name. ::

   sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is::

   from sound.effects import echo

This also loads the submodule :mod:`echo`, and makes it available without its
package prefix, so it can be used as follows::

   echo.echofilter(input, output, delay=0.7, atten=4)

Yet another variation is to import the desired function or variable directly::

   from sound.effects.echo import echofilter

Again, this loads the submodule :mod:`echo`, but this makes its function
:func:`echofilter` directly available::

   echofilter(input, output, delay=0.7, atten=4)

Note that when using ``from package import item``, the item can be either a
submodule (or subpackage) of the package, or some  other name defined in the
package, like a function, class or variable.  The ``import`` statement first
tests whether the item is defined in the package; if not, it assumes it is a
module and attempts to load it.  If it fails to find it, an :exc:`ImportError`
exception is raised.

Contrarily, when using syntax like ``import item.subitem.subsubitem``, each item
except for the last must be a package; the last item can be a module or a
package but can't be a class or function or variable defined in the previous
item.


.. _tut-pkg-import-star:

Importing \* From a Package
---------------------------

.. index:: single: __all__

Now what happens when the user writes ``from sound.effects import *``?  Ideally,
one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all.  This could take a
long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported.

The only solution is for the package author to provide an explicit index of the
package.  The :keyword:`import` statement uses the following convention: if a package's
:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the
list of module names that should be imported when ``from package import *`` is
encountered.  It is up to the package author to keep this list up-to-date when a
new version of the package is released.  Package authors may also decide not to
support it, if they don't see a use for importing \* from their package.  For
example, the file :file:`sound/effects/__init__.py` could contain the following
code::

   __all__ = ["echo", "surround", "reverse"]

This would mean that ``from sound.effects import *`` would import the three
named submodules of the :mod:`sound` package.

If ``__all__`` is not defined, the statement ``from sound.effects import *``
does *not* import all submodules from the package :mod:`sound.effects` into the
current namespace; it only ensures that the package :mod:`sound.effects` has
been imported (possibly running any initialization code in :file:`__init__.py`)
and then imports whatever names are defined in the package.  This includes any
names defined (and submodules explicitly loaded) by :file:`__init__.py`.  It
also includes any submodules of the package that were explicitly loaded by
previous :keyword:`import` statements.  Consider this code::

   import sound.effects.echo
   import sound.effects.surround
   from sound.effects import *

In this example, the :mod:`echo` and :mod:`surround` modules are imported in the
current namespace because they are defined in the :mod:`sound.effects` package
when the ``from...import`` statement is executed.  (This also works when
``__all__`` is defined.)

Although certain modules are designed to export only names that follow certain
patterns when you use ``import *``, it is still considered bad practice in
production code.

Remember, there is nothing wrong with using ``from Package import
specific_submodule``!  In fact, this is the recommended notation unless the
importing module needs to use submodules with the same name from different
packages.


Intra-package References
------------------------

The submodules often need to refer to each other.  For example, the
:mod:`surround` module might use the :mod:`echo` module.  In fact, such
references are so common that the :keyword:`import` statement first looks in the
containing package before looking in the standard module search path. Thus, the
:mod:`surround` module can simply use ``import echo`` or ``from echo import
echofilter``.  If the imported module is not found in the current package (the
package of which the current module is a submodule), the :keyword:`import`
statement looks for a top-level module with the given name.

When packages are structured into subpackages (as with the :mod:`sound` package
in the example), you can use absolute imports to refer to submodules of siblings
packages.  For example, if the module :mod:`sound.filters.vocoder` needs to use
the :mod:`echo` module in the :mod:`sound.effects` package, it can use ``from
sound.effects import echo``.

Starting with Python 2.5, in addition to the implicit relative imports described
above, you can write explicit relative imports with the ``from module import
name`` form of import statement. These explicit relative imports use leading
dots to indicate the current and parent packages involved in the relative
import. From the :mod:`surround` module for example, you might use::

   from . import echo
   from .. import formats
   from ..filters import equalizer

Note that both explicit and implicit relative imports are based on the name of
the current module. Since the name of the main module is always ``"__main__"``,
modules intended for use as the main module of a Python application should
always use absolute imports.


Packages in Multiple Directories
--------------------------------

Packages support one more special attribute, :attr:`__path__`.  This is
initialized to be a list containing the name of the directory holding the
package's :file:`__init__.py` before the code in that file is executed.  This
variable can be modified; doing so affects future searches for modules and
subpackages contained in the package.

While this feature is not often needed, it can be used to extend the set of
modules found in a package.


.. rubric:: Footnotes

.. [#] In fact function definitions are also 'statements' that are 'executed'; the
   execution of a module-level function definition enters the function name in
   the module's global symbol table.

PK
%�\�@"Ά&�&%html/_sources/tutorial/stdlib.rst.txtnu�[���.. _tut-brieftour:

**********************************
Brief Tour of the Standard Library
**********************************


.. _tut-os-interface:

Operating System Interface
==========================

The :mod:`os` module provides dozens of functions for interacting with the
operating system::

   >>> import os
   >>> os.getcwd()      # Return the current working directory
   'C:\\Python26'
   >>> os.chdir('/server/accesslogs')   # Change current working directory
   >>> os.system('mkdir today')   # Run the command mkdir in the system shell
   0

Be sure to use the ``import os`` style instead of ``from os import *``.  This
will keep :func:`os.open` from shadowing the built-in :func:`open` function which
operates much differently.

.. index:: builtin: help

The built-in :func:`dir` and :func:`help` functions are useful as interactive
aids for working with large modules like :mod:`os`::

   >>> import os
   >>> dir(os)
   <returns a list of all module functions>
   >>> help(os)
   <returns an extensive manual page created from the module's docstrings>

For daily file and directory management tasks, the :mod:`shutil` module provides
a higher level interface that is easier to use::

   >>> import shutil
   >>> shutil.copyfile('data.db', 'archive.db')
   >>> shutil.move('/build/executables', 'installdir')


.. _tut-file-wildcards:

File Wildcards
==============

The :mod:`glob` module provides a function for making file lists from directory
wildcard searches::

   >>> import glob
   >>> glob.glob('*.py')
   ['primes.py', 'random.py', 'quote.py']


.. _tut-command-line-arguments:

Command Line Arguments
======================

Common utility scripts often need to process command line arguments. These
arguments are stored in the :mod:`sys` module's *argv* attribute as a list.  For
instance the following output results from running ``python demo.py one two
three`` at the command line::

   >>> import sys
   >>> print sys.argv
   ['demo.py', 'one', 'two', 'three']

The :mod:`getopt` module processes *sys.argv* using the conventions of the Unix
:func:`getopt` function.  More powerful and flexible command line processing is
provided by the :mod:`argparse` module.


.. _tut-stderr:

Error Output Redirection and Program Termination
================================================

The :mod:`sys` module also has attributes for *stdin*, *stdout*, and *stderr*.
The latter is useful for emitting warnings and error messages to make them
visible even when *stdout* has been redirected::

   >>> sys.stderr.write('Warning, log file not found starting a new one\n')
   Warning, log file not found starting a new one

The most direct way to terminate a script is to use ``sys.exit()``.


.. _tut-string-pattern-matching:

String Pattern Matching
=======================

The :mod:`re` module provides regular expression tools for advanced string
processing. For complex matching and manipulation, regular expressions offer
succinct, optimized solutions::

   >>> import re
   >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
   ['foot', 'fell', 'fastest']
   >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
   'cat in the hat'

When only simple capabilities are needed, string methods are preferred because
they are easier to read and debug::

   >>> 'tea for too'.replace('too', 'two')
   'tea for two'


.. _tut-mathematics:

Mathematics
===========

The :mod:`math` module gives access to the underlying C library functions for
floating point math::

   >>> import math
   >>> math.cos(math.pi / 4.0)
   0.70710678118654757
   >>> math.log(1024, 2)
   10.0

The :mod:`random` module provides tools for making random selections::

   >>> import random
   >>> random.choice(['apple', 'pear', 'banana'])
   'apple'
   >>> random.sample(xrange(100), 10)   # sampling without replacement
   [30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
   >>> random.random()    # random float
   0.17970987693706186
   >>> random.randrange(6)    # random integer chosen from range(6)
   4


.. _tut-internet-access:

Internet Access
===============

There are a number of modules for accessing the internet and processing internet
protocols. Two of the simplest are :mod:`urllib2` for retrieving data from URLs
and :mod:`smtplib` for sending mail::

   >>> import urllib2
   >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
   ...     if 'EST' in line or 'EDT' in line:  # look for Eastern Time
   ...         print line

   <BR>Nov. 25, 09:43:32 PM EST

   >>> import smtplib
   >>> server = smtplib.SMTP('localhost')
   >>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
   ... """To: jcaesar@example.org
   ... From: soothsayer@example.org
   ...
   ... Beware the Ides of March.
   ... """)
   >>> server.quit()

(Note that the second example needs a mailserver running on localhost.)


.. _tut-dates-and-times:

Dates and Times
===============

The :mod:`datetime` module supplies classes for manipulating dates and times in
both simple and complex ways. While date and time arithmetic is supported, the
focus of the implementation is on efficient member extraction for output
formatting and manipulation.  The module also supports objects that are timezone
aware. ::

   >>> # dates are easily constructed and formatted
   >>> from datetime import date
   >>> now = date.today()
   >>> now
   datetime.date(2003, 12, 2)
   >>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
   '12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

   >>> # dates support calendar arithmetic
   >>> birthday = date(1964, 7, 31)
   >>> age = now - birthday
   >>> age.days
   14368


.. _tut-data-compression:

Data Compression
================

Common data archiving and compression formats are directly supported by modules
including: :mod:`zlib`, :mod:`gzip`, :mod:`bz2`, :mod:`zipfile` and
:mod:`tarfile`. ::

   >>> import zlib
   >>> s = 'witch which has which witches wrist watch'
   >>> len(s)
   41
   >>> t = zlib.compress(s)
   >>> len(t)
   37
   >>> zlib.decompress(t)
   'witch which has which witches wrist watch'
   >>> zlib.crc32(s)
   226805979


.. _tut-performance-measurement:

Performance Measurement
=======================

Some Python users develop a deep interest in knowing the relative performance of
different approaches to the same problem. Python provides a measurement tool
that answers those questions immediately.

For example, it may be tempting to use the tuple packing and unpacking feature
instead of the traditional approach to swapping arguments. The :mod:`timeit`
module quickly demonstrates a modest performance advantage::

   >>> from timeit import Timer
   >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
   0.57535828626024577
   >>> Timer('a,b = b,a', 'a=1; b=2').timeit()
   0.54962537085770791

In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and
:mod:`pstats` modules provide tools for identifying time critical sections in
larger blocks of code.


.. _tut-quality-control:

Quality Control
===============

One approach for developing high quality software is to write tests for each
function as it is developed and to run those tests frequently during the
development process.

The :mod:`doctest` module provides a tool for scanning a module and validating
tests embedded in a program's docstrings.  Test construction is as simple as
cutting-and-pasting a typical call along with its results into the docstring.
This improves the documentation by providing the user with an example and it
allows the doctest module to make sure the code remains true to the
documentation::

   def average(values):
       """Computes the arithmetic mean of a list of numbers.

       >>> print average([20, 30, 70])
       40.0
       """
       return sum(values, 0.0) / len(values)

   import doctest
   doctest.testmod()   # automatically validate the embedded tests

The :mod:`unittest` module is not as effortless as the :mod:`doctest` module,
but it allows a more comprehensive set of tests to be maintained in a separate
file::

   import unittest

   class TestStatisticalFunctions(unittest.TestCase):

       def test_average(self):
           self.assertEqual(average([20, 30, 70]), 40.0)
           self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
           with self.assertRaises(ZeroDivisionError):
               average([])
           with self.assertRaises(TypeError):
               average(20, 30, 70)

   unittest.main()  # Calling from the command line invokes all tests


.. _tut-batteries-included:

Batteries Included
==================

Python has a "batteries included" philosophy.  This is best seen through the
sophisticated and robust capabilities of its larger packages. For example:

* The :mod:`xmlrpclib` and :mod:`SimpleXMLRPCServer` modules make implementing
  remote procedure calls into an almost trivial task.  Despite the modules
  names, no direct knowledge or handling of XML is needed.

* The :mod:`email` package is a library for managing email messages, including
  MIME and other RFC 2822-based message documents. Unlike :mod:`smtplib` and
  :mod:`poplib` which actually send and receive messages, the email package has
  a complete toolset for building or decoding complex message structures
  (including attachments) and for implementing internet encoding and header
  protocols.

* The :mod:`xml.dom` and :mod:`xml.sax` packages provide robust support for
  parsing this popular data interchange format. Likewise, the :mod:`csv` module
  supports direct reads and writes in a common database format. Together, these
  modules and packages greatly simplify data interchange between Python
  applications and other tools.

* Internationalization is supported by a number of modules including
  :mod:`gettext`, :mod:`locale`, and the :mod:`codecs` package.


PK
%�\���_�;�;&html/_sources/tutorial/stdlib2.rst.txtnu�[���.. _tut-brieftourtwo:

**********************************************
Brief Tour of the Standard Library --- Part II
**********************************************

This second tour covers more advanced modules that support professional
programming needs.  These modules rarely occur in small scripts.


.. _tut-output-formatting:

Output Formatting
=================

The :mod:`repr` module provides a version of :func:`repr` customized for
abbreviated displays of large or deeply nested containers::

   >>> import repr
   >>> repr.repr(set('supercalifragilisticexpialidocious'))
   "set(['a', 'c', 'd', 'e', 'f', 'g', ...])"

The :mod:`pprint` module offers more sophisticated control over printing both
built-in and user defined objects in a way that is readable by the interpreter.
When the result is longer than one line, the "pretty printer" adds line breaks
and indentation to more clearly reveal data structure::

   >>> import pprint
   >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
   ...     'yellow'], 'blue']]]
   ...
   >>> pprint.pprint(t, width=30)
   [[[['black', 'cyan'],
      'white',
      ['green', 'red']],
     [['magenta', 'yellow'],
      'blue']]]

The :mod:`textwrap` module formats paragraphs of text to fit a given screen
width::

   >>> import textwrap
   >>> doc = """The wrap() method is just like fill() except that it returns
   ... a list of strings instead of one big string with newlines to separate
   ... the wrapped lines."""
   ...
   >>> print textwrap.fill(doc, width=40)
   The wrap() method is just like fill()
   except that it returns a list of strings
   instead of one big string with newlines
   to separate the wrapped lines.

The :mod:`locale` module accesses a database of culture specific data formats.
The grouping attribute of locale's format function provides a direct way of
formatting numbers with group separators::

   >>> import locale
   >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
   'English_United States.1252'
   >>> conv = locale.localeconv()          # get a mapping of conventions
   >>> x = 1234567.8
   >>> locale.format("%d", x, grouping=True)
   '1,234,567'
   >>> locale.format_string("%s%.*f", (conv['currency_symbol'],
   ...                      conv['frac_digits'], x), grouping=True)
   '$1,234,567.80'


.. _tut-templating:

Templating
==========

The :mod:`string` module includes a versatile :class:`~string.Template` class
with a simplified syntax suitable for editing by end-users.  This allows users
to customize their applications without having to alter the application.

The format uses placeholder names formed by ``$`` with valid Python identifiers
(alphanumeric characters and underscores).  Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening
spaces.  Writing ``$$`` creates a single escaped ``$``::

   >>> from string import Template
   >>> t = Template('${village}folk send $$10 to $cause.')
   >>> t.substitute(village='Nottingham', cause='the ditch fund')
   'Nottinghamfolk send $10 to the ditch fund.'

The :meth:`~string.Template.substitute` method raises a :exc:`KeyError` when a
placeholder is not supplied in a dictionary or a keyword argument.  For
mail-merge style applications, user supplied data may be incomplete and the
:meth:`~string.Template.safe_substitute` method may be more appropriate ---
it will leave placeholders unchanged if data is missing::

   >>> t = Template('Return the $item to $owner.')
   >>> d = dict(item='unladen swallow')
   >>> t.substitute(d)
   Traceback (most recent call last):
     ...
   KeyError: 'owner'
   >>> t.safe_substitute(d)
   'Return the unladen swallow to $owner.'

Template subclasses can specify a custom delimiter.  For example, a batch
renaming utility for a photo browser may elect to use percent signs for
placeholders such as the current date, image sequence number, or file format::

   >>> import time, os.path
   >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
   >>> class BatchRename(Template):
   ...     delimiter = '%'
   >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format):  ')
   Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f

   >>> t = BatchRename(fmt)
   >>> date = time.strftime('%d%b%y')
   >>> for i, filename in enumerate(photofiles):
   ...     base, ext = os.path.splitext(filename)
   ...     newname = t.substitute(d=date, n=i, f=ext)
   ...     print '{0} --> {1}'.format(filename, newname)

   img_1074.jpg --> Ashley_0.jpg
   img_1076.jpg --> Ashley_1.jpg
   img_1077.jpg --> Ashley_2.jpg

Another application for templating is separating program logic from the details
of multiple output formats.  This makes it possible to substitute custom
templates for XML files, plain text reports, and HTML web reports.


.. _tut-binary-formats:

Working with Binary Data Record Layouts
=======================================

The :mod:`struct` module provides :func:`~struct.pack` and
:func:`~struct.unpack` functions for working with variable length binary
record formats.  The following example shows
how to loop through header information in a ZIP file without using the
:mod:`zipfile` module.  Pack codes ``"H"`` and ``"I"`` represent two and four
byte unsigned numbers respectively.  The ``"<"`` indicates that they are
standard size and in little-endian byte order::

   import struct

   data = open('myfile.zip', 'rb').read()
   start = 0
   for i in range(3):                      # show the first 3 file headers
       start += 14
       fields = struct.unpack('<IIIHH', data[start:start+16])
       crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

       start += 16
       filename = data[start:start+filenamesize]
       start += filenamesize
       extra = data[start:start+extra_size]
       print filename, hex(crc32), comp_size, uncomp_size

       start += extra_size + comp_size     # skip to the next header


.. _tut-multi-threading:

Multi-threading
===============

Threading is a technique for decoupling tasks which are not sequentially
dependent.  Threads can be used to improve the responsiveness of applications
that accept user input while other tasks run in the background.  A related use
case is running I/O in parallel with computations in another thread.

The following code shows how the high level :mod:`threading` module can run
tasks in background while the main program continues to run::

   import threading, zipfile

   class AsyncZip(threading.Thread):
       def __init__(self, infile, outfile):
           threading.Thread.__init__(self)
           self.infile = infile
           self.outfile = outfile

       def run(self):
           f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
           f.write(self.infile)
           f.close()
           print 'Finished background zip of: ', self.infile

   background = AsyncZip('mydata.txt', 'myarchive.zip')
   background.start()
   print 'The main program continues to run in foreground.'

   background.join()    # Wait for the background task to finish
   print 'Main program waited until background was done.'

The principal challenge of multi-threaded applications is coordinating threads
that share data or other resources.  To that end, the threading module provides
a number of synchronization primitives including locks, events, condition
variables, and semaphores.

While those tools are powerful, minor design errors can result in problems that
are difficult to reproduce.  So, the preferred approach to task coordination is
to concentrate all access to a resource in a single thread and then use the
:mod:`Queue` module to feed that thread with requests from other threads.
Applications using :class:`Queue.Queue` objects for inter-thread communication
and coordination are easier to design, more readable, and more reliable.


.. _tut-logging:

Logging
=======

The :mod:`logging` module offers a full featured and flexible logging system.
At its simplest, log messages are sent to a file or to ``sys.stderr``::

   import logging
   logging.debug('Debugging information')
   logging.info('Informational message')
   logging.warning('Warning:config file %s not found', 'server.conf')
   logging.error('Error occurred')
   logging.critical('Critical error -- shutting down')

This produces the following output:

.. code-block:: none

   WARNING:root:Warning:config file server.conf not found
   ERROR:root:Error occurred
   CRITICAL:root:Critical error -- shutting down

By default, informational and debugging messages are suppressed and the output
is sent to standard error.  Other output options include routing messages
through email, datagrams, sockets, or to an HTTP Server.  New filters can select
different routing based on message priority: :const:`~logging.DEBUG`,
:const:`~logging.INFO`, :const:`~logging.WARNING`, :const:`~logging.ERROR`,
and :const:`~logging.CRITICAL`.

The logging system can be configured directly from Python or can be loaded from
a user editable configuration file for customized logging without altering the
application.


.. _tut-weak-references:

Weak References
===============

Python does automatic memory management (reference counting for most objects and
:term:`garbage collection` to eliminate cycles).  The memory is freed shortly
after the last reference to it has been eliminated.

This approach works fine for most applications but occasionally there is a need
to track objects only as long as they are being used by something else.
Unfortunately, just tracking them creates a reference that makes them permanent.
The :mod:`weakref` module provides tools for tracking objects without creating a
reference.  When the object is no longer needed, it is automatically removed
from a weakref table and a callback is triggered for weakref objects.  Typical
applications include caching objects that are expensive to create::

   >>> import weakref, gc
   >>> class A:
   ...     def __init__(self, value):
   ...         self.value = value
   ...     def __repr__(self):
   ...         return str(self.value)
   ...
   >>> a = A(10)                   # create a reference
   >>> d = weakref.WeakValueDictionary()
   >>> d['primary'] = a            # does not create a reference
   >>> d['primary']                # fetch the object if it is still alive
   10
   >>> del a                       # remove the one reference
   >>> gc.collect()                # run garbage collection right away
   0
   >>> d['primary']                # entry was automatically removed
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
       d['primary']                # entry was automatically removed
     File "C:/python26/lib/weakref.py", line 46, in __getitem__
       o = self.data[key]()
   KeyError: 'primary'


.. _tut-list-tools:

Tools for Working with Lists
============================

Many data structure needs can be met with the built-in list type. However,
sometimes there is a need for alternative implementations with different
performance trade-offs.

The :mod:`array` module provides an :class:`~array.array()` object that is like
a list that stores only homogeneous data and stores it more compactly.  The
following example shows an array of numbers stored as two byte unsigned binary
numbers (typecode ``"H"``) rather than the usual 16 bytes per entry for regular
lists of Python int objects::

   >>> from array import array
   >>> a = array('H', [4000, 10, 700, 22222])
   >>> sum(a)
   26932
   >>> a[1:3]
   array('H', [10, 700])

The :mod:`collections` module provides a :class:`~collections.deque()` object
that is like a list with faster appends and pops from the left side but slower
lookups in the middle. These objects are well suited for implementing queues
and breadth first tree searches::

   >>> from collections import deque
   >>> d = deque(["task1", "task2", "task3"])
   >>> d.append("task4")
   >>> print "Handling", d.popleft()
   Handling task1

::

   unsearched = deque([starting_node])
   def breadth_first_search(unsearched):
       node = unsearched.popleft()
       for m in gen_moves(node):
           if is_goal(m):
               return m
           unsearched.append(m)

In addition to alternative list implementations, the library also offers other
tools such as the :mod:`bisect` module with functions for manipulating sorted
lists::

   >>> import bisect
   >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
   >>> bisect.insort(scores, (300, 'ruby'))
   >>> scores
   [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

The :mod:`heapq` module provides functions for implementing heaps based on
regular lists.  The lowest valued entry is always kept at position zero.  This
is useful for applications which repeatedly access the smallest element but do
not want to run a full list sort::

   >>> from heapq import heapify, heappop, heappush
   >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
   >>> heapify(data)                      # rearrange the list into heap order
   >>> heappush(data, -5)                 # add a new entry
   >>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
   [-5, 0, 1]


.. _tut-decimal-fp:

Decimal Floating Point Arithmetic
=================================

The :mod:`decimal` module offers a :class:`~decimal.Decimal` datatype for
decimal floating point arithmetic.  Compared to the built-in :class:`float`
implementation of binary floating point, the class is especially helpful for

* financial applications and other uses which require exact decimal
  representation,
* control over precision,
* control over rounding to meet legal or regulatory requirements,
* tracking of significant decimal places, or
* applications where the user expects the results to match calculations done by
  hand.

For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference
becomes significant if the results are rounded to the nearest cent::

   >>> from decimal import *
   >>> x = Decimal('0.70') * Decimal('1.05')
   >>> x
   Decimal('0.7350')
   >>> x.quantize(Decimal('0.01'))  # round to nearest cent
   Decimal('0.74')
   >>> round(.70 * 1.05, 2)         # same calculation with floats
   0.73

The :class:`~decimal.Decimal` result keeps a trailing zero, automatically
inferring four place significance from multiplicands with two place
significance.  Decimal reproduces mathematics as done by hand and avoids
issues that can arise when binary floating point cannot exactly represent
decimal quantities.

Exact representation enables the :class:`~decimal.Decimal` class to perform
modulo calculations and equality tests that are unsuitable for binary floating
point::

   >>> Decimal('1.00') % Decimal('.10')
   Decimal('0.00')
   >>> 1.00 % 0.10
   0.09999999999999995

   >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
   True
   >>> sum([0.1]*10) == 1.0
   False

The :mod:`decimal` module provides arithmetic with as much precision as needed::

   >>> getcontext().prec = 36
   >>> Decimal(1) / Decimal(7)
   Decimal('0.142857142857142857142857142857142857')


PK
%�\�ٗ�&html/_sources/tutorial/whatnow.rst.txtnu�[���.. _tut-whatnow:

*********
What Now?
*********

Reading this tutorial has probably reinforced your interest in using Python ---
you should be eager to apply Python to solving your real-world problems. Where
should you go to learn more?

This tutorial is part of Python's documentation set.   Some other documents in
the set are:

* :ref:`library-index`:

  You should browse through this manual, which gives complete (though terse)
  reference material about types, functions, and the modules in the standard
  library.  The standard Python distribution includes a *lot* of additional code.
  There are modules to read Unix mailboxes, retrieve documents via HTTP, generate
  random numbers, parse command-line options, write CGI programs, compress data,
  and many other tasks. Skimming through the Library Reference will give you an
  idea of what's available.

* :ref:`install-index` explains how to install external modules written by other
  Python users.

* :ref:`reference-index`: A detailed explanation of Python's syntax and
  semantics.  It's heavy reading, but is useful as a complete guide to the
  language itself.

More Python resources:

* https://www.python.org:  The major Python Web site.  It contains code,
  documentation, and pointers to Python-related pages around the Web.  This Web
  site is mirrored in various places around the world, such as Europe, Japan, and
  Australia; a mirror may be faster than the main site, depending on your
  geographical location.

* https://docs.python.org:  Fast access to Python's  documentation.

* https://pypi.org: The Python Package Index, previously also nicknamed
  the Cheese Shop, is an index of user-created Python modules that are available
  for download.  Once you begin releasing code, you can register it here so that
  others can find it.

* https://code.activestate.com/recipes/langs/python/: The Python Cookbook is a
  sizable collection of code examples, larger modules, and useful scripts.
  Particularly notable contributions are collected in a book also titled Python
  Cookbook (O'Reilly & Associates, ISBN 0-596-00797-3.)

For Python-related questions and problem reports, you can post to the newsgroup
:newsgroup:`comp.lang.python`, or send them to the mailing list at
python-list@python.org.  The newsgroup and mailing list are gatewayed, so
messages posted to one will automatically be forwarded to the other.  There are
around 120 postings a day (with peaks up to several hundred), asking (and
answering) questions, suggesting new features, and announcing new modules.
Before posting, be sure to check the list of :ref:`Frequently Asked Questions
<faq-index>` (also called the FAQ).  Mailing list
archives are available at https://mail.python.org/pipermail/. The FAQ answers
many of the questions that come up again and again, and may already contain the
solution for your problem.

.. Postings figure based on average of last six months activity as
   reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
   days = 116.9 msgs / day and steadily increasing. (XXX up to date figures?)


PK
%�\��ęW�W#html/_sources/using/cmdline.rst.txtnu�[���.. highlightlang:: sh

.. ATTENTION: You probably should update Misc/python.man, too, if you modify
   this file.

.. _using-on-general:

Command line and environment
============================

The CPython interpreter scans the command line and the environment for various
settings.

.. impl-detail::

   Other implementations' command line schemes may differ.  See
   :ref:`implementations` for further resources.


.. _using-on-cmdline:

Command line
------------

When invoking Python, you may specify any of these options::

    python [-bBdEiOQsRStuUvVWxX3?] [-c command | -m module-name | script | - ] [args]

The most common use case is, of course, a simple invocation of a script::

    python myscript.py


.. _using-on-interface-options:

Interface options
~~~~~~~~~~~~~~~~~

The interpreter interface resembles that of the UNIX shell, but provides some
additional methods of invocation:

* When called with standard input connected to a tty device, it prompts for
  commands and executes them until an EOF (an end-of-file character, you can
  produce that with :kbd:`Ctrl-D` on UNIX or :kbd:`Ctrl-Z, Enter` on Windows) is read.
* When called with a file name argument or with a file as standard input, it
  reads and executes a script from that file.
* When called with a directory name argument, it reads and executes an
  appropriately named script from that directory.
* When called with ``-c command``, it executes the Python statement(s) given as
  *command*.  Here *command* may contain multiple statements separated by
  newlines. Leading whitespace is significant in Python statements!
* When called with ``-m module-name``, the given module is located on the
  Python module path and executed as a script.

In non-interactive mode, the entire input is parsed before it is executed.

An interface option terminates the list of options consumed by the interpreter,
all consecutive arguments will end up in :data:`sys.argv` -- note that the first
element, subscript zero (``sys.argv[0]``), is a string reflecting the program's
source.

.. cmdoption:: -c <command>

   Execute the Python code in *command*.  *command* can be one or more
   statements separated by newlines, with significant leading whitespace as in
   normal module code.

   If this option is given, the first element of :data:`sys.argv` will be
   ``"-c"`` and the current directory will be added to the start of
   :data:`sys.path` (allowing modules in that directory to be imported as top
   level modules).


.. cmdoption:: -m <module-name>

   Search :data:`sys.path` for the named module and execute its contents as
   the :mod:`__main__` module.

   Since the argument is a *module* name, you must not give a file extension
   (``.py``).  The ``module-name`` should be a valid Python module name, but
   the implementation may not always enforce this (e.g. it may allow you to
   use a name that includes a hyphen).

   Package names are also permitted. When a package name is supplied instead
   of a normal module, the interpreter will execute ``<pkg>.__main__`` as
   the main module. This behaviour is deliberately similar to the handling
   of directories and zipfiles that are passed to the interpreter as the
   script argument.

   .. note::

      This option cannot be used with built-in modules and extension modules
      written in C, since they do not have Python module files. However, it
      can still be used for precompiled modules, even if the original source
      file is not available.

   If this option is given, the first element of :data:`sys.argv` will be the
   full path to the module file. As with the :option:`-c` option, the current
   directory will be added to the start of :data:`sys.path`.

   Many standard library modules contain code that is invoked on their execution
   as a script.  An example is the :mod:`timeit` module::

       python -mtimeit -s 'setup here' 'benchmarked code here'
       python -mtimeit -h # for details

   .. seealso::
      :func:`runpy.run_module`
         Equivalent functionality directly available to Python code

      :pep:`338` -- Executing modules as scripts

   .. versionadded:: 2.4

   .. versionchanged:: 2.5
      The named module can now be located inside a package.

   .. versionchanged:: 2.7
      Supply the package name to run a ``__main__`` submodule.
      sys.argv[0] is now set to ``"-m"`` while searching for the module
      (it was previously incorrectly set to ``"-c"``)


.. describe:: -

   Read commands from standard input (:data:`sys.stdin`).  If standard input is
   a terminal, :option:`-i` is implied.

   If this option is given, the first element of :data:`sys.argv` will be
   ``"-"`` and the current directory will be added to the start of
   :data:`sys.path`.

   .. seealso::
      :func:`runpy.run_path`
         Equivalent functionality directly available to Python code


.. describe:: <script>

   Execute the Python code contained in *script*, which must be a filesystem
   path (absolute or relative) referring to either a Python file, a directory
   containing a ``__main__.py`` file, or a zipfile containing a
   ``__main__.py`` file.

   If this option is given, the first element of :data:`sys.argv` will be the
   script name as given on the command line.

   If the script name refers directly to a Python file, the directory
   containing that file is added to the start of :data:`sys.path`, and the
   file is executed as the :mod:`__main__` module.

   If the script name refers to a directory or zipfile, the script name is
   added to the start of :data:`sys.path` and the ``__main__.py`` file in
   that location is executed as the :mod:`__main__` module.

   .. versionchanged:: 2.5
      Directories and zipfiles containing a ``__main__.py`` file at the top
      level are now considered valid Python scripts.

If no interface option is given, :option:`-i` is implied, ``sys.argv[0]`` is
an empty string (``""``) and the current directory will be added to the
start of :data:`sys.path`.

.. seealso::  :ref:`tut-invoking`


Generic options
~~~~~~~~~~~~~~~

.. cmdoption:: -?
               -h
               --help

   Print a short description of all command line options.

   .. versionchanged:: 2.5
      The ``--help`` variant.


.. cmdoption:: -V
               --version

   Print the Python version number and exit.  Example output could be::

       Python 2.5.1

   .. versionchanged:: 2.5
      The ``--version`` variant.


Miscellaneous options
~~~~~~~~~~~~~~~~~~~~~

.. cmdoption:: -b

   Issue a warning when comparing :class:`unicode` with :class:`bytearray`.
   Issue an error when the option is given twice (:option:`!-bb`).

   Note that, unlike the corresponding Python 3.x flag, this will **not** emit
   warnings for comparisons between :class:`str` and :class:`unicode`.
   Instead, the ``str`` instance will be implicitly decoded to ``unicode`` and
   Unicode comparison used.

   .. versionadded:: 2.6


.. cmdoption:: -B

   If given, Python won't try to write ``.pyc`` or ``.pyo`` files on the
   import of source modules.  See also :envvar:`PYTHONDONTWRITEBYTECODE`.

   .. versionadded:: 2.6


.. cmdoption:: -d

   Turn on parser debugging output (for wizards only, depending on compilation
   options).  See also :envvar:`PYTHONDEBUG`.


.. cmdoption:: -E

   Ignore all :envvar:`PYTHON*` environment variables, e.g.
   :envvar:`PYTHONPATH` and :envvar:`PYTHONHOME`, that might be set.

   .. versionadded:: 2.2


.. cmdoption:: -i

   When a script is passed as first argument or the :option:`-c` option is used,
   enter interactive mode after executing the script or the command, even when
   :data:`sys.stdin` does not appear to be a terminal.  The
   :envvar:`PYTHONSTARTUP` file is not read.

   This can be useful to inspect global variables or a stack trace when a script
   raises an exception.  See also :envvar:`PYTHONINSPECT`.


.. _using-on-optimizations:
.. cmdoption:: -O

   Turn on basic optimizations.  This changes the filename extension for
   compiled (:term:`bytecode`) files from ``.pyc`` to ``.pyo``.  See also
   :envvar:`PYTHONOPTIMIZE`.


.. cmdoption:: -OO

   Discard docstrings in addition to the :option:`-O` optimizations.


.. cmdoption:: -Q <arg>

   Division control. The argument must be one of the following:

   ``old``
     division of int/int and long/long return an int or long (*default*)
   ``new``
     new division semantics, i.e. division of int/int and long/long returns a
     float
   ``warn``
     old division semantics with a warning for int/int and long/long
   ``warnall``
     old division semantics with a warning for all uses of the division operator

   .. seealso::
      :file:`Tools/scripts/fixdiv.py`
         for a use of ``warnall``

      :pep:`238` -- Changing the division operator


.. cmdoption:: -R

   Turn on hash randomization, so that the :meth:`__hash__` values of str,
   bytes and datetime objects are "salted" with an unpredictable random value.
   Although they remain constant within an individual Python process, they are
   not predictable between repeated invocations of Python.

   This is intended to provide protection against a denial-of-service caused by
   carefully-chosen inputs that exploit the worst case performance of a dict
   construction, O(n^2) complexity.  See
   http://www.ocert.org/advisories/ocert-2011-003.html for details.

   Changing hash values affects the order in which keys are retrieved from a
   dict.  Although Python has never made guarantees about this ordering (and it
   typically varies between 32-bit and 64-bit builds), enough real-world code
   implicitly relies on this non-guaranteed behavior that the randomization is
   disabled by default.

   See also :envvar:`PYTHONHASHSEED`.

   .. versionadded:: 2.6.8


.. cmdoption:: -s

   Don't add the :data:`user site-packages directory <site.USER_SITE>` to
   :data:`sys.path`.

   .. versionadded:: 2.6

   .. seealso::

      :pep:`370` -- Per user site-packages directory


.. cmdoption:: -S

   Disable the import of the module :mod:`site` and the site-dependent
   manipulations of :data:`sys.path` that it entails.


.. cmdoption:: -t

   Issue a warning when a source file mixes tabs and spaces for indentation in a
   way that makes it depend on the worth of a tab expressed in spaces.  Issue an
   error when the option is given twice (:option:`!-tt`).


.. cmdoption:: -u

   Force stdin, stdout and stderr to be totally unbuffered.  On systems where it
   matters, also put stdin, stdout and stderr in binary mode.

   Note that there is internal buffering in :meth:`file.readlines` and
   :ref:`bltin-file-objects` (``for line in sys.stdin``) which is not influenced
   by this option.  To work around this, you will want to use
   :meth:`file.readline` inside a ``while 1:`` loop.

   See also :envvar:`PYTHONUNBUFFERED`.


.. cmdoption:: -v

   Print a message each time a module is initialized, showing the place
   (filename or built-in module) from which it is loaded.  When given twice
   (:option:`!-vv`), print a message for each file that is checked for when
   searching for a module.  Also provides information on module cleanup at exit.
   See also :envvar:`PYTHONVERBOSE`.


.. cmdoption:: -W arg

   Warning control.  Python's warning machinery by default prints warning
   messages to :data:`sys.stderr`.  A typical warning message has the following
   form::

       file:line: category: message

   By default, each warning is printed once for each source line where it
   occurs.  This option controls how often warnings are printed.

   Multiple :option:`-W` options may be given; when a warning matches more than
   one option, the action for the last matching option is performed.  Invalid
   :option:`-W` options are ignored (though, a warning message is printed about
   invalid options when the first warning is issued).

   Starting from Python 2.7, :exc:`DeprecationWarning` and its descendants
   are ignored by default.  The :option:`!-Wd` option can be used to re-enable
   them.

   Warnings can also be controlled from within a Python program using the
   :mod:`warnings` module.

   The simplest form of argument is one of the following action strings (or a
   unique abbreviation) by themselves:

   ``ignore``
      Ignore all warnings.
   ``default``
      Explicitly request the default behavior (printing each warning once per
      source line).
   ``all``
      Print a warning each time it occurs (this may generate many messages if a
      warning is triggered repeatedly for the same source line, such as inside a
      loop).
   ``module``
      Print each warning only the first time it occurs in each module.
   ``once``
      Print each warning only the first time it occurs in the program.
   ``error``
      Raise an exception instead of printing a warning message.

   The full form of argument is::

       action:message:category:module:line

   Here, *action* is as explained above but only applies to messages that match
   the remaining fields.  Empty fields match all values; trailing empty fields
   may be omitted.  The *message* field matches the start of the warning message
   printed; this match is case-insensitive.  The *category* field matches the
   warning category.  This must be a class name; the match tests whether the
   actual warning category of the message is a subclass of the specified warning
   category.  The full class name must be given.  The *module* field matches the
   (fully-qualified) module name; this match is case-sensitive.  The *line*
   field matches the line number, where zero matches all line numbers and is
   thus equivalent to an omitted line number.

   .. seealso::
      :mod:`warnings` -- the warnings module

      :pep:`230` -- Warning framework

      :envvar:`PYTHONWARNINGS`


.. cmdoption:: -x

   Skip the first line of the source, allowing use of non-Unix forms of
   ``#!cmd``.  This is intended for a DOS specific hack only.

.. cmdoption:: -3

   Warn about Python 3.x possible incompatibilities by emitting a
   :exc:`DeprecationWarning` for features that are removed or significantly
   changed in Python 3 and can't be detected using static code analysis.

   .. versionadded:: 2.6

   See :doc:`/howto/pyporting` for more details.

Options you shouldn't use
~~~~~~~~~~~~~~~~~~~~~~~~~

.. cmdoption:: -J

   Reserved for use by Jython_.

.. _Jython: http://www.jython.org/

.. cmdoption:: -U

   Turns all string literals into unicodes globally.  Do not be tempted to use
   this option as it will probably break your world.  It also produces
   ``.pyc`` files with a different magic number than normal.  Instead, you can
   enable unicode literals on a per-module basis by using::

        from __future__ import unicode_literals

   at the top of the file.  See :mod:`__future__` for details.

.. cmdoption:: -X

    Reserved for alternative implementations of Python to use for their own
    purposes.

.. _using-on-envvars:

Environment variables
---------------------

These environment variables influence Python's behavior, they are processed
before the command-line switches other than -E.  It is customary that
command-line switches override environmental variables where there is a
conflict.

.. envvar:: PYTHONHOME

   Change the location of the standard Python libraries.  By default, the
   libraries are searched in :file:`{prefix}/lib/python{version}` and
   :file:`{exec_prefix}/lib/python{version}`, where :file:`{prefix}` and
   :file:`{exec_prefix}` are installation-dependent directories, both defaulting
   to :file:`/usr/local`.

   When :envvar:`PYTHONHOME` is set to a single directory, its value replaces
   both :file:`{prefix}` and :file:`{exec_prefix}`.  To specify different values
   for these, set :envvar:`PYTHONHOME` to :file:`{prefix}:{exec_prefix}`.


.. envvar:: PYTHONPATH

   Augment the default search path for module files.  The format is the same as
   the shell's :envvar:`PATH`: one or more directory pathnames separated by
   :data:`os.pathsep` (e.g. colons on Unix or semicolons on Windows).
   Non-existent directories are silently ignored.

   In addition to normal directories, individual :envvar:`PYTHONPATH` entries
   may refer to zipfiles containing pure Python modules (in either source or
   compiled form). Extension modules cannot be imported from zipfiles.

   The default search path is installation dependent, but generally begins with
   :file:`{prefix}/lib/python{version}` (see :envvar:`PYTHONHOME` above).  It
   is *always* appended to :envvar:`PYTHONPATH`.

   An additional directory will be inserted in the search path in front of
   :envvar:`PYTHONPATH` as described above under
   :ref:`using-on-interface-options`. The search path can be manipulated from
   within a Python program as the variable :data:`sys.path`.


.. envvar:: PYTHONSTARTUP

   If this is the name of a readable file, the Python commands in that file are
   executed before the first prompt is displayed in interactive mode.  The file
   is executed in the same namespace where interactive commands are executed so
   that objects defined or imported in it can be used without qualification in
   the interactive session.  You can also change the prompts :data:`sys.ps1` and
   :data:`sys.ps2` in this file.


.. envvar:: PYTHONY2K

   Set this to a non-empty string to cause the :mod:`time` module to require
   dates specified as strings to include 4-digit years, otherwise 2-digit years
   are converted based on rules described in the :mod:`time` module
   documentation.


.. envvar:: PYTHONOPTIMIZE

   If this is set to a non-empty string it is equivalent to specifying the
   :option:`-O` option.  If set to an integer, it is equivalent to specifying
   :option:`-O` multiple times.


.. envvar:: PYTHONDEBUG

   If this is set to a non-empty string it is equivalent to specifying the
   :option:`-d` option.  If set to an integer, it is equivalent to specifying
   :option:`-d` multiple times.


.. envvar:: PYTHONINSPECT

   If this is set to a non-empty string it is equivalent to specifying the
   :option:`-i` option.

   This variable can also be modified by Python code using :data:`os.environ`
   to force inspect mode on program termination.


.. envvar:: PYTHONUNBUFFERED

   If this is set to a non-empty string it is equivalent to specifying the
   :option:`-u` option.


.. envvar:: PYTHONVERBOSE

   If this is set to a non-empty string it is equivalent to specifying the
   :option:`-v` option.  If set to an integer, it is equivalent to specifying
   :option:`-v` multiple times.


.. envvar:: PYTHONCASEOK

   If this is set, Python ignores case in :keyword:`import` statements.  This
   only works on Windows, OS X, OS/2, and RiscOS.


.. envvar:: PYTHONDONTWRITEBYTECODE

   If this is set, Python won't try to write ``.pyc`` or ``.pyo`` files on the
   import of source modules.  This is equivalent to specifying the :option:`-B`
   option.

   .. versionadded:: 2.6

.. envvar:: PYTHONHASHSEED

   If this variable is set to ``random``, the effect is the same as specifying
   the :option:`-R` option: a random value is used to seed the hashes of str,
   bytes and datetime objects.

   If :envvar:`PYTHONHASHSEED` is set to an integer value, it is used as a
   fixed seed for generating the hash() of the types covered by the hash
   randomization.

   Its purpose is to allow repeatable hashing, such as for selftests for the
   interpreter itself, or to allow a cluster of python processes to share hash
   values.

   The integer must be a decimal number in the range [0,4294967295].
   Specifying the value 0 will lead to the same hash values as when hash
   randomization is disabled.

   .. versionadded:: 2.6.8


.. envvar:: PYTHONIOENCODING

   Overrides the encoding used for stdin/stdout/stderr, in the syntax
   ``encodingname:errorhandler``.  The ``:errorhandler`` part is optional and
   has the same meaning as in :func:`str.encode`.

   .. versionadded:: 2.6


.. envvar:: PYTHONNOUSERSITE

   If this is set, Python won't add the :data:`user site-packages directory
   <site.USER_SITE>` to :data:`sys.path`.

   .. versionadded:: 2.6

   .. seealso::

      :pep:`370` -- Per user site-packages directory


.. envvar:: PYTHONUSERBASE

   Defines the :data:`user base directory <site.USER_BASE>`, which is used to
   compute the path of the :data:`user site-packages directory <site.USER_SITE>`
   and :ref:`Distutils installation paths <inst-alt-install-user>` for ``python
   setup.py install --user``.

   .. versionadded:: 2.6

   .. seealso::

      :pep:`370` -- Per user site-packages directory


.. envvar:: PYTHONEXECUTABLE

   If this environment variable is set, ``sys.argv[0]`` will be set to its
   value instead of the value got through the C runtime.  Only works on
   Mac OS X.

.. envvar:: PYTHONWARNINGS

   This is equivalent to the :option:`-W` option. If set to a comma
   separated string, it is equivalent to specifying :option:`-W` multiple
   times.


.. envvar:: PYTHONHTTPSVERIFY

   If this environment variable is set specifically to ``0``, then it is
   equivalent to implicitly calling :func:`ssl._https_verify_certificates` with
   ``enable=False`` when :mod:`ssl` is first imported.

   Refer to the documentation of :func:`ssl._https_verify_certificates` for
   details.

   .. versionadded:: 2.7.12

Debug-mode variables
~~~~~~~~~~~~~~~~~~~~

Setting these variables only has an effect in a debug build of Python, that is,
if Python was configured with the ``--with-pydebug`` build option.

.. envvar:: PYTHONTHREADDEBUG

   If set, Python will print threading debug info.

   .. versionchanged:: 2.6
      Previously, this variable was called ``THREADDEBUG``.

.. envvar:: PYTHONDUMPREFS

   If set, Python will dump objects and reference counts still alive after
   shutting down the interpreter.


.. envvar:: PYTHONMALLOCSTATS

   If set, Python will print memory allocation statistics every time a new
   object arena is created, and on shutdown.

.. envvar:: PYTHONSHOWALLOCCOUNT

   If set and Python was compiled with ``COUNT_ALLOCS`` defined, Python will
   dump allocations counts into stderr on shutdown.

   .. versionadded:: 2.7.15

.. envvar:: PYTHONSHOWREFCOUNT

   If set, Python will print the total reference count when the program
   finishes or after each statement in the interactive interpreter.

   .. versionadded:: 2.7.15
PK
%�\SϤ��!html/_sources/using/index.rst.txtnu�[���.. _using-index:

##########################
  Python Setup and Usage
##########################


This part of the documentation is devoted to general information on the setup
of the Python environment on different platforms, the invocation of the
interpreter and things that make working with Python easier.


.. toctree::
   :numbered:

   cmdline.rst
   unix.rst
   windows.rst
   mac.rst

PK
%�\/r��aahtml/_sources/using/mac.rst.txtnu�[���
.. _using-on-mac:

***************************
Using Python on a Macintosh
***************************

:Author: Bob Savage <bobsavage@mac.com>


Python on a Macintosh running Mac OS X is in principle very similar to Python on
any other Unix platform, but there are a number of additional features such as
the IDE and the Package Manager that are worth pointing out.

The Mac-specific modules are documented in :ref:`mac-specific-services`.

Python on Mac OS 9 or earlier can be quite different from Python on Unix or
Windows, but is beyond the scope of this manual, as that platform is no longer
supported, starting with Python 2.4. See http://www.cwi.nl/~jack/macpython for
installers for the latest 2.3 release for Mac OS 9 and related documentation.


.. _getting-osx:

Getting and Installing MacPython
================================

Mac OS X 10.8 comes with Python 2.7 pre-installed by Apple.  If you wish, you
are invited to install the most recent version of Python from the Python website
(https://www.python.org).  A current "universal binary" build of Python, which
runs natively on the Mac's new Intel and legacy PPC CPU's, is available there.

What you get after installing is a number of things:

* A :file:`MacPython 2.7` folder in your :file:`Applications` folder. In here
  you find IDLE, the development environment that is a standard part of official
  Python distributions; PythonLauncher, which handles double-clicking Python
  scripts from the Finder; and the "Build Applet" tool, which allows you to
  package Python scripts as standalone applications on your system.

* A framework :file:`/Library/Frameworks/Python.framework`, which includes the
  Python executable and libraries. The installer adds this location to your shell
  path. To uninstall MacPython, you can simply remove these three things. A
  symlink to the Python executable is placed in /usr/local/bin/.

The Apple-provided build of Python is installed in
:file:`/System/Library/Frameworks/Python.framework` and :file:`/usr/bin/python`,
respectively. You should never modify or delete these, as they are
Apple-controlled and are used by Apple- or third-party software.  Remember that
if you choose to install a newer Python version from python.org, you will have
two different but functional Python installations on your computer, so it will
be important that your paths and usages are consistent with what you want to do.

IDLE includes a help menu that allows you to access Python documentation. If you
are completely new to Python you should start reading the tutorial introduction
in that document.

If you are familiar with Python on other Unix platforms you should read the
section on running Python scripts from the Unix shell.


How to run a Python script
--------------------------

Your best way to get started with Python on Mac OS X is through the IDLE
integrated development environment, see section :ref:`ide` and use the Help menu
when the IDE is running.

If you want to run Python scripts from the Terminal window command line or from
the Finder you first need an editor to create your script. Mac OS X comes with a
number of standard Unix command line editors, :program:`vim` and
:program:`emacs` among them. If you want a more Mac-like editor,
:program:`BBEdit` or :program:`TextWrangler` from Bare Bones Software (see
http://www.barebones.com/products/bbedit/index.html) are good choices, as is
:program:`TextMate` (see https://macromates.com/). Other editors include
:program:`Gvim` (http://macvim.org) and :program:`Aquamacs`
(http://aquamacs.org/).

To run your script from the Terminal window you must make sure that
:file:`/usr/local/bin` is in your shell search path.

To run your script from the Finder you have two options:

* Drag it to :program:`PythonLauncher`

* Select :program:`PythonLauncher` as the default application to open your
  script (or any .py script) through the finder Info window and double-click it.
  :program:`PythonLauncher` has various preferences to control how your script is
  launched. Option-dragging allows you to change these for one invocation, or use
  its Preferences menu to change things globally.


.. _osx-gui-scripts:

Running scripts with a GUI
--------------------------

With older versions of Python, there is one Mac OS X quirk that you need to be
aware of: programs that talk to the Aqua window manager (in other words,
anything that has a GUI) need to be run in a special way. Use :program:`pythonw`
instead of :program:`python` to start such scripts.

With Python 2.7, you can use either :program:`python` or :program:`pythonw`.


Configuration
-------------

Python on OS X honors all standard Unix environment variables such as
:envvar:`PYTHONPATH`, but setting these variables for programs started from the
Finder is non-standard as the Finder does not read your :file:`.profile` or
:file:`.cshrc` at startup. You need to create a file
:file:`~/.MacOSX/environment.plist`. See Apple's Technical Document QA1067 for
details.

For more information on installation Python packages in MacPython, see section
:ref:`mac-package-manager`.


.. _ide:

The IDE
=======

MacPython ships with the standard IDLE development environment. A good
introduction to using IDLE can be found at
https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html.


.. _mac-package-manager:

Installing Additional Python Packages
=====================================

There are several methods to install additional Python packages:

* Packages can be installed via the standard Python distutils mode (``python
  setup.py install``).

* Many packages can also be installed via the :program:`setuptools` extension
  or :program:`pip` wrapper, see https://pip.pypa.io/.


GUI Programming on the Mac
==========================

There are several options for building GUI applications on the Mac with Python.

*PyObjC* is a Python binding to Apple's Objective-C/Cocoa framework, which is
the foundation of most modern Mac development. Information on PyObjC is
available from https://pythonhosted.org/pyobjc/.

The standard Python GUI toolkit is :mod:`Tkinter`, based on the cross-platform
Tk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is bundled with OS
X by Apple, and the latest version can be downloaded and installed from
https://www.activestate.com; it can also be built from source.

*wxPython* is another popular cross-platform GUI toolkit that runs natively on
Mac OS X. Packages and documentation are available from http://www.wxpython.org.

*PyQt* is another popular cross-platform GUI toolkit that runs natively on Mac
OS X. More information can be found at
https://riverbankcomputing.com/software/pyqt/intro.


Distributing Python Applications on the Mac
===========================================

The "Build Applet" tool that is placed in the MacPython 2.7 folder is fine for
packaging small Python scripts on your own machine to run as a standard Mac
application. This tool, however, is not robust enough to distribute Python
applications to other users.

The standard tool for deploying standalone Python applications on the Mac is
:program:`py2app`. More information on installing and using py2app can be found
at http://undefined.org/python/#py2app.


Other Resources
===============

The MacPython mailing list is an excellent support resource for Python users and
developers on the Mac:

https://www.python.org/community/sigs/current/pythonmac-sig/

Another useful resource is the MacPython wiki:

https://wiki.python.org/moin/MacPython

PK
%�\�<� html/_sources/using/unix.rst.txtnu�[���.. highlightlang:: sh

.. _using-on-unix:

********************************
 Using Python on Unix platforms
********************************

.. sectionauthor:: Shriphani Palakodety


Getting and installing the latest version of Python
===================================================

On Linux
--------

Python comes preinstalled on most Linux distributions, and is available as a
package on all others.  However there are certain features you might want to use
that are not available on your distro's package.  You can easily compile the
latest version of Python from source.

In the event that Python doesn't come preinstalled and isn't in the repositories as
well, you can easily make packages for your own distro.  Have a look at the
following links:

.. seealso::

   https://www.debian.org/doc/manuals/maint-guide/first.en.html
      for Debian users
   https://en.opensuse.org/Portal:Packaging
      for OpenSuse users
   https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html
      for Fedora users
   http://www.slackbook.org/html/package-management-making-packages.html
      for Slackware users


On FreeBSD and OpenBSD
----------------------

* FreeBSD users, to add the package use::

     pkg install python3

* OpenBSD users, to add the package use::

     pkg_add -r python

     pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/<insert your architecture here>/python-<version>.tgz

  For example i386 users get the 2.5.1 version of Python using::

     pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz


On OpenSolaris
--------------

You can get Python from `OpenCSW <https://www.opencsw.org/>`_.  Various versions
of Python are available and can be installed with e.g. ``pkgutil -i python27``.


.. _building-python-on-unix:

Building Python
===============

If you want to compile CPython yourself, first thing you should do is get the
`source <https://www.python.org/downloads/source/>`_. You can download either the
latest release's source or just grab a fresh `clone
<https://docs.python.org/devguide/setup.html#getting-the-source-code>`_.  (If you want
to contribute patches, you will need a clone.)

The build process consists in the usual ::

   ./configure
   make
   make install

invocations. Configuration options and caveats for specific Unix platforms are
extensively documented in the :source:`README` file in the root of the Python
source tree.

.. warning::

   ``make install`` can overwrite or masquerade the :file:`python` binary.
   ``make altinstall`` is therefore recommended instead of ``make install``
   since it only installs :file:`{exec_prefix}/bin/python{version}`.


Python-related paths and files
==============================

These are subject to difference depending on local installation conventions;
:envvar:`prefix` (``${prefix}``) and :envvar:`exec_prefix` (``${exec_prefix}``)
are installation-dependent and should be interpreted as for GNU software; they
may be the same.

For example, on most Linux systems, the default for both is :file:`/usr`.

+-----------------------------------------------+------------------------------------------+
| File/directory                                | Meaning                                  |
+===============================================+==========================================+
| :file:`{exec_prefix}/bin/python`              | Recommended location of the interpreter. |
+-----------------------------------------------+------------------------------------------+
| :file:`{prefix}/lib/python{version}`,         | Recommended locations of the directories |
| :file:`{exec_prefix}/lib/python{version}`     | containing the standard modules.         |
+-----------------------------------------------+------------------------------------------+
| :file:`{prefix}/include/python{version}`,     | Recommended locations of the directories |
| :file:`{exec_prefix}/include/python{version}` | containing the include files needed for  |
|                                               | developing Python extensions and         |
|                                               | embedding the interpreter.               |
+-----------------------------------------------+------------------------------------------+
| :file:`~/.pythonrc.py`                        | User-specific initialization file loaded |
|                                               | by the user module; not used by default  |
|                                               | or by most applications.                 |
+-----------------------------------------------+------------------------------------------+


Miscellaneous
=============

To easily use Python scripts on Unix, you need to make them executable,
e.g. with ::

   $ chmod +x script

and put an appropriate Shebang line at the top of the script.  A good choice is
usually ::

   #!/usr/bin/env python

which searches for the Python interpreter in the whole :envvar:`PATH`.  However,
some Unices may not have the :program:`env` command, so you may need to hardcode
``/usr/bin/python`` as the interpreter path.

To use shell commands in your Python scripts, look at the :mod:`subprocess` module.


Editors and IDEs
================

There are a number of IDEs that support Python programming language.
Many editors and IDEs provide syntax highlighting, debugging tools, and :pep:`8` checks.

Please go to `Python Editors <https://wiki.python.org/moin/PythonEditors>`_ and
`Integrated Development Environments <https://wiki.python.org/moin/IntegratedDevelopmentEnvironments>`_
for a comprehensive list.PK
%�\?���3�3#html/_sources/using/windows.rst.txtnu�[���.. highlightlang:: none

.. _using-on-windows:

*************************
 Using Python on Windows
*************************

.. sectionauthor:: Robert Lehmann <lehmannro@gmail.com>

This document aims to give an overview of Windows-specific behaviour you should
know about when using Python on Microsoft Windows.


Installing Python
=================

Unlike most Unix systems and services, Windows does not require Python natively
and thus does not pre-install a version of Python.  However, the CPython team
has compiled Windows installers (MSI packages) with every `release
<https://www.python.org/download/releases/>`_ for many years.

With ongoing development of Python, some platforms that used to be supported
earlier are no longer supported (due to the lack of users or developers).
Check :pep:`11` for details on all unsupported platforms.

* DOS and Windows 3.x are deprecated since Python 2.0 and code specific to these
  systems was removed in Python 2.1.
* Up to 2.5, Python was still compatible with Windows 95, 98 and ME (but already
  raised a deprecation warning on installation).  For Python 2.6 (and all
  following releases), this support was dropped and new releases are just
  expected to work on the Windows NT family.
* `Windows CE <http://pythonce.sourceforge.net/>`_ is still supported.
* The `Cygwin <https://cygwin.com/>`_ installer offers to install the Python
  interpreter as well (cf. `Cygwin package source
  <ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/
  release/python>`_, `Maintainer releases
  <http://www.tishler.net/jason/software/python/>`_)

See `Python for Windows (and DOS) <https://www.python.org/download/windows/>`_
for detailed information about platforms with precompiled installers.

.. seealso::

   `Python on XP <http://dooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/>`_
      "7 Minutes to "Hello World!""
      by Richard Dooling, 2006

   `Installing on Windows <http://www.diveintopython.net/installing_python/windows.html>`_
      in "`Dive into Python: Python from novice to pro
      <http://www.diveintopython.net/>`_"
      by Mark Pilgrim, 2004,
      ISBN 1-59059-356-1

   `For Windows users <http://python.swaroopch.com/installation.html#installation-on-windows>`_
      in "Installing Python"
      in "`A Byte of Python <http://python.swaroopch.com/>`_"
      by Swaroop C H, 2003


Alternative bundles
===================

Besides the standard CPython distribution, there are modified packages including
additional functionality.  The following is a list of popular versions and their
key features:

`ActivePython <https://www.activestate.com/activepython/>`_
    Installer with multi-platform compatibility, documentation, PyWin32

`Enthought Python Distribution <https://www.enthought.com/products/epd/>`_
    Popular modules (such as PyWin32) with their respective documentation, tool
    suite for building extensible Python applications

Notice that these packages are likely to install *older* versions of Python.



Configuring Python
==================

In order to run Python flawlessly, you might have to change certain environment
settings in Windows.


.. _setting-envvars:

Excursus: Setting environment variables
---------------------------------------

Windows has a built-in dialog for changing environment variables (following
guide applies to XP classical view): Right-click the icon for your machine
(usually located on your Desktop and called "My Computer") and choose
:menuselection:`Properties` there.  Then, open the :guilabel:`Advanced` tab
and click the :guilabel:`Environment Variables` button.

In short, your path is:

    :menuselection:`My Computer
    --> Properties
    --> Advanced
    --> Environment Variables`

In this dialog, you can add or modify User and System variables. To change
System variables, you need non-restricted access to your machine
(i.e. Administrator rights).

Another way of adding variables to your environment is using the :command:`set`
command::

    set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib

To make this setting permanent, you could add the corresponding command line to
your :file:`autoexec.bat`. :program:`msconfig` is a graphical interface to this
file.

Viewing environment variables can also be done more straight-forward: The
command prompt will expand strings wrapped into percent signs automatically::

    echo %PATH%

Consult :command:`set /?` for details on this behaviour.

.. seealso::

   https://support.microsoft.com/kb/100843
      Environment variables in Windows NT

   https://support.microsoft.com/kb/310519
      How To Manage Environment Variables in Windows XP

   https://www.chem.gla.ac.uk/~louis/software/faq/q1.html
      Setting Environment variables, Louis J. Farrugia


Finding the Python executable
-----------------------------

Besides using the automatically created start menu entry for the Python
interpreter, you might want to start Python in the DOS prompt.  To make this
work, you need to set your :envvar:`%PATH%` environment variable to include the
directory of your Python distribution, delimited by a semicolon from other
entries.  An example variable could look like this (assuming the first two
entries are Windows' default)::

    C:\WINDOWS\system32;C:\WINDOWS;C:\Python25

Typing :command:`python` on your command prompt will now fire up the Python
interpreter.  Thus, you can also execute your scripts with command line options,
see :ref:`using-on-cmdline` documentation.


Finding modules
---------------

Python usually stores its library (and thereby your site-packages folder) in the
installation directory.  So, if you had installed Python to
:file:`C:\\Python\\`, the default library would reside in
:file:`C:\\Python\\Lib\\` and third-party modules should be stored in
:file:`C:\\Python\\Lib\\site-packages\\`.

This is how :data:`sys.path` is populated on Windows:

* An empty entry is added at the start, which corresponds to the current
  directory.

* If the environment variable :envvar:`PYTHONPATH` exists, as described in
  :ref:`using-on-envvars`, its entries are added next.  Note that on Windows,
  paths in this variable must be separated by semicolons, to distinguish them
  from the colon used in drive identifiers (``C:\`` etc.).

* Additional "application paths" can be added in the registry as subkeys of
  :samp:`\\SOFTWARE\\Python\\PythonCore\\{version}\\PythonPath` under both the
  ``HKEY_CURRENT_USER`` and ``HKEY_LOCAL_MACHINE`` hives.  Subkeys which have
  semicolon-delimited path strings as their default value will cause each path
  to be added to :data:`sys.path`.  (Note that all known installers only use
  HKLM, so HKCU is typically empty.)

* If the environment variable :envvar:`PYTHONHOME` is set, it is assumed as
  "Python Home".  Otherwise, the path of the main Python executable is used to
  locate a "landmark file" (``Lib\os.py``) to deduce the "Python Home".  If a
  Python home is found, the relevant sub-directories added to :data:`sys.path`
  (``Lib``, ``plat-win``, etc) are based on that folder.  Otherwise, the core
  Python path is constructed from the PythonPath stored in the registry.

* If the Python Home cannot be located, no :envvar:`PYTHONPATH` is specified in
  the environment, and no registry entries can be found, a default path with
  relative entries is used (e.g. ``.\Lib;.\plat-win``, etc).

The end result of all this is:

* When running :file:`python.exe`, or any other .exe in the main Python
  directory (either an installed version, or directly from the PCbuild
  directory), the core path is deduced, and the core paths in the registry are
  ignored.  Other "application paths" in the registry are always read.

* When Python is hosted in another .exe (different directory, embedded via COM,
  etc), the "Python Home" will not be deduced, so the core path from the
  registry is used.  Other "application paths" in the registry are always read.

* If Python can't find its home and there is no registry (eg, frozen .exe, some
  very strange installation setup) you get a path with some default, but
  relative, paths.


Executing scripts
-----------------

Python scripts (files with the extension ``.py``) will be executed by
:program:`python.exe` by default.  This executable opens a terminal, which stays
open even if the program uses a GUI.  If you do not want this to happen, use the
extension ``.pyw`` which will cause the script to be executed by
:program:`pythonw.exe` by default (both executables are located in the top-level
of your Python installation directory).  This suppresses the terminal window on
startup.

You can also make all ``.py`` scripts execute with :program:`pythonw.exe`,
setting this through the usual facilities, for example (might require
administrative rights):

#. Launch a command prompt.
#. Associate the correct file group with ``.py`` scripts::

      assoc .py=Python.File

#. Redirect all Python files to the new executable::

      ftype Python.File=C:\Path\to\pythonw.exe "%1" %*


Additional modules
==================

Even though Python aims to be portable among all platforms, there are features
that are unique to Windows.  A couple of modules, both in the standard library
and external, and snippets exist to use these features.

The Windows-specific standard modules are documented in
:ref:`mswin-specific-services`.


PyWin32
-------

The `PyWin32 <https://pypi.org/project/pywin32>`_ module by Mark Hammond
is a collection of modules for advanced Windows-specific support.  This includes
utilities for:

* `Component Object Model <https://www.microsoft.com/com/>`_ (COM)
* Win32 API calls
* Registry
* Event log
* `Microsoft Foundation Classes <https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx>`_ (MFC)
  user interfaces

`PythonWin <https://web.archive.org/web/20060524042422/
https://www.python.org/windows/pythonwin/>`_ is a sample MFC application
shipped with PyWin32.  It is an embeddable IDE with a built-in debugger.

.. seealso::

   `Win32 How Do I...? <http://timgolden.me.uk/python/win32_how_do_i.html>`_
      by Tim Golden

   `Python and COM <http://www.boddie.org.uk/python/COM.html>`_
      by David and Paul Boddie


Py2exe
------

`Py2exe <http://www.py2exe.org/>`_ is a :mod:`distutils` extension (see
:ref:`extending-distutils`) which wraps Python scripts into executable Windows
programs (:file:`{*}.exe` files).  When you have done this, you can distribute
your application without requiring your users to install Python.


WConio
------

Since Python's advanced terminal handling layer, :mod:`curses`, is restricted to
Unix-like systems, there is a library exclusive to Windows as well: Windows
Console I/O for Python.

`WConio <http://newcenturycomputers.net/projects/wconio.html>`_ is a wrapper for
Turbo-C's :file:`CONIO.H`, used to create text user interfaces.



Compiling Python on Windows
===========================

If you want to compile CPython yourself, first thing you should do is get the
`source <https://www.python.org/downloads/source/>`_. You can download either the
latest release's source or just grab a fresh `checkout
<https://docs.python.org/devguide/setup.html#getting-the-source-code>`_.

For Microsoft Visual C++, which is the compiler with which official Python
releases are built, the source tree contains solutions/project files.  View the
:file:`readme.txt` in their respective directories:

+--------------------+--------------+-----------------------+
| Directory          | MSVC version | Visual Studio version |
+====================+==============+=======================+
| :file:`PC/VC6/`    | 6.0          | 97                    |
+--------------------+--------------+-----------------------+
| :file:`PC/VS7.1/`  | 7.1          | 2003                  |
+--------------------+--------------+-----------------------+
| :file:`PC/VS8.0/`  | 8.0          | 2005                  |
+--------------------+--------------+-----------------------+
| :file:`PCbuild/`   | 9.0          | 2008                  |
+--------------------+--------------+-----------------------+

Note that not all of these build directories are fully supported.  Read the
release notes to see which compiler version the official releases for your
version are built with.

Check :file:`PC/readme.txt` for general information on the build process.


For extension modules, consult :ref:`building-on-windows`.

.. seealso::

   `Python + Windows + distutils + SWIG + gcc MinGW <http://sebsauvage.net/python/mingw.html>`_
      or "Creating Python extensions in C/C++ with SWIG and compiling them with
      MinGW gcc under Windows" or "Installing Python extension with distutils
      and without Microsoft Visual C++" by Sébastien Sauvage, 2003

   `MingW -- Python extensions <http://oldwiki.mingw.org/index.php/Python%20extensions>`_
      by Trent Apted et al, 2007


Other resources
===============

.. seealso::

   `Python Programming On Win32 <http://shop.oreilly.com/product/9781565926219.do>`_
      "Help for Windows Programmers"
      by Mark Hammond and Andy Robinson, O'Reilly Media, 2000,
      ISBN 1-56592-621-8

   `A Python for Windows Tutorial <http://www.imladris.com/Scripts/PythonForWindows.html>`_
      by Amanda Birmingham, 2004

PK
%�\5nBfJ�J�"html/_sources/whatsnew/2.0.rst.txtnu�[���****************************
  What's New in Python 2.0
****************************

:Author: A.M. Kuchling and Moshe Zadka

.. |release| replace:: 1.02

.. $Id: whatsnew20.tex 50964 2006-07-30 03:03:43Z fred.drake $


Introduction
============

A new release of Python, version 2.0, was released on October 16, 2000. This
article covers the exciting new features in 2.0, highlights some other useful
changes, and points out a few incompatible changes that may require rewriting
code.

Python's development never completely stops between releases, and a steady flow
of bug fixes and improvements are always being submitted. A host of minor fixes,
a few optimizations, additional docstrings, and better error messages went into
2.0; to list them all would be impossible, but they're certainly significant.
Consult the publicly-available CVS logs if you want to see the full list.  This
progress is due to the five developers working for  PythonLabs are now getting
paid to spend their days fixing bugs, and also due to the improved communication
resulting  from moving to SourceForge.

.. ======================================================================


What About Python 1.6?
======================

Python 1.6 can be thought of as the Contractual Obligations Python release.
After the core development team left CNRI in May 2000, CNRI requested that a 1.6
release be created, containing all the work on Python that had been performed at
CNRI.  Python 1.6 therefore represents the state of the CVS tree as of May 2000,
with the most significant new feature being Unicode support.  Development
continued after May, of course, so the 1.6 tree received a few fixes to ensure
that it's forward-compatible with Python 2.0.  1.6 is therefore part of Python's
evolution, and not a side branch.

So, should you take much interest in Python 1.6?  Probably not.  The 1.6final
and 2.0beta1 releases were made on the same day (September 5, 2000), the plan
being to finalize Python 2.0 within a month or so.  If you have applications to
maintain, there seems little point in breaking things by moving to 1.6, fixing
them, and then having another round of breakage within a month by moving to 2.0;
you're better off just going straight to 2.0.  Most of the really interesting
features described in this document are only in 2.0, because a lot of work was
done between May and September.

.. ======================================================================


New Development Process
=======================

The most important change in Python 2.0 may not be to the code at all, but to
how Python is developed: in May 2000 the Python developers began using the tools
made available by SourceForge for storing  source code, tracking bug reports,
and managing the queue of patch submissions.  To report bugs or submit patches
for Python 2.0, use the bug tracking and patch manager tools available from
Python's project page, located at https://sourceforge.net/projects/python/.

The most important of the services now hosted at SourceForge is the Python CVS
tree, the version-controlled repository containing the source code for Python.
Previously, there were roughly 7 or so people who had write access to the CVS
tree, and all patches had to be inspected and checked in by one of the people on
this short list. Obviously, this wasn't very scalable.  By moving the CVS tree
to SourceForge, it became possible to grant write access to more people; as of
September 2000 there were 27 people able to check in changes, a fourfold
increase.  This makes possible large-scale changes that wouldn't be attempted if
they'd have to be filtered through the small group of core developers.  For
example, one day Peter Schneider-Kamp took it into his head to drop K&R C
compatibility and convert the C source for Python to ANSI C. After getting
approval on the python-dev mailing list, he launched into a flurry of checkins
that lasted about a week, other developers joined in to help, and the job was
done.  If there were only 5 people with write access, probably that task would
have been viewed as "nice, but not worth the time and effort needed" and it
would never have gotten done.

The shift to using SourceForge's services has resulted in a remarkable increase
in the speed of development.  Patches now get submitted, commented on, revised
by people other than the original submitter, and bounced back and forth between
people until the patch is deemed worth checking in.  Bugs are tracked in one
central location and can be assigned to a specific person for fixing, and we can
count the number of open bugs to measure progress.  This didn't come without a
cost: developers now have more e-mail to deal with, more mailing lists to
follow, and special tools had to be written for the new environment. For
example, SourceForge sends default patch and bug notification e-mail messages
that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that
sends more useful messages.

The ease of adding code caused a few initial growing pains, such as code was
checked in before it was ready or without getting clear agreement from the
developer group.  The approval process that has emerged is somewhat similar to
that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch;
+1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is
mostly indifferent to the change, though with a slight positive or negative
slant.  The most significant change from the Apache model is that the voting is
essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For
Life status, know what the general opinion is. He can still ignore the result of
a vote, and approve or reject a change even if the community disagrees with him.

Producing an actual patch is the last step in adding a new feature, and is
usually easy compared to the earlier task of coming up with a good design.
Discussions of new features can often explode into lengthy mailing list threads,
making the discussion hard to follow, and no one can read every posting to
python-dev.  Therefore, a relatively formal process has been set up to write
Python Enhancement Proposals (PEPs), modelled on the Internet RFC process.  PEPs
are draft documents that describe a proposed new feature, and are continually
revised until the community reaches a consensus, either accepting or rejecting
the proposal.  Quoting from the introduction to PEP 1, "PEP Purpose and
Guidelines":


.. epigraph::

   PEP stands for Python Enhancement Proposal.  A PEP is a design document
   providing information to the Python community, or describing a new feature for
   Python.  The PEP should provide a concise technical specification of the feature
   and a rationale for the feature.

   We intend PEPs to be the primary mechanisms for proposing new features, for
   collecting community input on an issue, and for documenting the design decisions
   that have gone into Python.  The PEP author is responsible for building
   consensus within the community and documenting dissenting opinions.

Read the rest of PEP 1 for the details of the PEP editorial process, style, and
format.  PEPs are kept in the Python CVS tree on SourceForge, though they're not
part of the Python 2.0 distribution, and are also available in HTML form from
https://www.python.org/dev/peps/.  As of September 2000, there are 25 PEPS, ranging
from PEP 201, "Lockstep Iteration", to PEP 225, "Elementwise/Objectwise
Operators".

.. ======================================================================


Unicode
=======

The largest new feature in Python 2.0 is a new fundamental data type: Unicode
strings.  Unicode uses 16-bit numbers to represent characters instead of the
8-bit number used by ASCII, meaning that 65,536 distinct characters can be
supported.

The final interface for Unicode support was arrived at through countless
often-stormy discussions on the python-dev mailing list, and mostly implemented by
Marc-André Lemburg, based on a Unicode string type implementation by Fredrik
Lundh.  A detailed explanation of the interface was written up as :pep:`100`,
"Python Unicode Integration". This article will simply cover the most
significant points about the Unicode interfaces.

In Python source code, Unicode strings are written as ``u"string"``.  Arbitrary
Unicode characters can be written using a new escape sequence, ``\uHHHH``, where
*HHHH* is a 4-digit hexadecimal number from 0000 to FFFF.  The existing
``\xHHHH`` escape sequence can also be used, and octal escapes can be used for
characters up to U+01FF, which is represented by ``\777``.

Unicode strings, just like regular strings, are an immutable sequence type.
They can be indexed and sliced, but not modified in place. Unicode strings have
an ``encode( [encoding] )`` method that returns an 8-bit string in the desired
encoding.  Encodings are named by strings, such as ``'ascii'``, ``'utf-8'``,
``'iso-8859-1'``, or whatever.  A codec API is defined for implementing and
registering new encodings that are then available throughout a Python program.
If an encoding isn't specified, the default encoding is usually 7-bit ASCII,
though it can be changed for your Python installation by calling the
``sys.setdefaultencoding(encoding)`` function in a customised version of
:file:`site.py`.

Combining 8-bit and Unicode strings always coerces to Unicode, using the default
ASCII encoding; the result of ``'a' + u'bc'`` is ``u'abc'``.

New built-in functions have been added, and existing built-ins modified to
support Unicode:

* ``unichr(ch)`` returns a Unicode string 1 character long, containing the
  character *ch*.

* ``ord(u)``, where *u* is a 1-character regular or Unicode string, returns the
  number of the character as an integer.

* ``unicode(string [, encoding]  [, errors] )`` creates a Unicode string
  from an 8-bit string.  ``encoding`` is a string naming the encoding to use. The
  ``errors`` parameter specifies the treatment of characters that are invalid for
  the current encoding; passing ``'strict'`` as the value causes an exception to
  be raised on any encoding error, while ``'ignore'`` causes errors to be silently
  ignored and ``'replace'`` uses U+FFFD, the official replacement character, in
  case of any problems.

* The :keyword:`exec` statement, and various built-ins such as ``eval()``,
  ``getattr()``, and ``setattr()`` will also accept Unicode strings as well as
  regular strings.  (It's possible that the process of fixing this missed some
  built-ins; if you find a built-in function that accepts strings but doesn't
  accept Unicode strings at all, please report it as a bug.)

A new module, :mod:`unicodedata`, provides an interface to Unicode character
properties.  For example, ``unicodedata.category(u'A')`` returns the 2-character
string 'Lu', the 'L' denoting it's a letter, and 'u' meaning that it's
uppercase. ``unicodedata.bidirectional(u'\u0660')`` returns 'AN', meaning that
U+0660 is an Arabic number.

The :mod:`codecs` module contains functions to look up existing encodings and
register new ones.  Unless you want to implement a new encoding, you'll most
often use the ``codecs.lookup(encoding)`` function, which returns a
4-element tuple: ``(encode_func, decode_func, stream_reader, stream_writer)``.

* *encode_func* is a function that takes a Unicode string, and returns a 2-tuple
  ``(string, length)``.  *string* is an 8-bit string containing a portion (perhaps
  all) of the Unicode string converted into the given encoding, and *length* tells
  you how much of the Unicode string was converted.

* *decode_func* is the opposite of *encode_func*, taking an 8-bit string and
  returning a 2-tuple ``(ustring, length)``, consisting of the resulting Unicode
  string *ustring* and the integer *length* telling how much of the 8-bit string
  was consumed.

* *stream_reader* is a class that supports decoding input from a stream.
  *stream_reader(file_obj)* returns an object that supports the :meth:`read`,
  :meth:`readline`, and :meth:`readlines` methods.  These methods will all
  translate from the given encoding and return Unicode strings.

* *stream_writer*, similarly, is a class that supports encoding output to a
  stream.  *stream_writer(file_obj)* returns an object that supports the
  :meth:`write` and :meth:`writelines` methods.  These methods expect Unicode
  strings, translating them to the given encoding on output.

For example, the following code writes a Unicode string into a file,  encoding
it as UTF-8::

   import codecs

   unistr = u'\u0660\u2000ab ...'

   (UTF8_encode, UTF8_decode,
    UTF8_streamreader, UTF8_streamwriter) = codecs.lookup('UTF-8')

   output = UTF8_streamwriter( open( '/tmp/output', 'wb') )
   output.write( unistr )
   output.close()

The following code would then read UTF-8 input from the file::

   input = UTF8_streamreader( open( '/tmp/output', 'rb') )
   print repr(input.read())
   input.close()

Unicode-aware regular expressions are available through the :mod:`re` module,
which has a new underlying implementation called SRE written by Fredrik Lundh of
Secret Labs AB.

A ``-U`` command line option was added which causes the Python compiler to
interpret all string literals as Unicode string literals. This is intended to be
used in testing and future-proofing your Python code, since some future version
of Python may drop support for 8-bit strings and provide only Unicode strings.

.. ======================================================================


List Comprehensions
===================

Lists are a workhorse data type in Python, and many programs manipulate a list
at some point.  Two common operations on lists are to loop over them, and either
pick out the elements that meet a certain criterion, or apply some function to
each element.  For example, given a list of strings, you might want to pull out
all the strings containing a given substring, or strip off trailing whitespace
from each line.

The existing :func:`map` and :func:`filter` functions can be used for this
purpose, but they require a function as one of their arguments.  This is fine if
there's an existing built-in function that can be passed directly, but if there
isn't, you have to create a little function to do the required work, and
Python's scoping rules make the result ugly if the little function needs
additional information.  Take the first example in the previous paragraph,
finding all the strings in the list containing a given substring.  You could
write the following to do it::

   # Given the list L, make a list of all strings
   # containing the substring S.
   sublist = filter( lambda s, substring=S:
                        string.find(s, substring) != -1,
                     L)

Because of Python's scoping rules, a default argument is used so that the
anonymous function created by the :keyword:`lambda` statement knows what
substring is being searched for.  List comprehensions make this cleaner::

   sublist = [ s for s in L if string.find(s, S) != -1 ]

List comprehensions have the form::

   [ expression for expr in sequence1
                for expr2 in sequence2 ...
                for exprN in sequenceN
                if condition ]

The :keyword:`for`...\ :keyword:`in` clauses contain the sequences to be
iterated over.  The sequences do not have to be the same length, because they
are *not* iterated over in parallel, but from left to right; this is explained
more clearly in the following paragraphs.  The elements of the generated list
will be the successive values of *expression*.  The final :keyword:`if` clause
is optional; if present, *expression* is only evaluated and added to the result
if *condition* is true.

To make the semantics very clear, a list comprehension is equivalent to the
following Python code::

   for expr1 in sequence1:
       for expr2 in sequence2:
       ...
           for exprN in sequenceN:
                if (condition):
                     # Append the value of
                     # the expression to the
                     # resulting list.

This means that when there are multiple :keyword:`for`...\ :keyword:`in`
clauses, the resulting list will be equal to the product of the lengths of all
the sequences.  If you have two lists of length 3, the output list is 9 elements
long::

   seq1 = 'abc'
   seq2 = (1,2,3)
   >>> [ (x,y) for x in seq1 for y in seq2]
   [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1),
   ('c', 2), ('c', 3)]

To avoid introducing an ambiguity into Python's grammar, if *expression* is
creating a tuple, it must be surrounded with parentheses.  The first list
comprehension below is a syntax error, while the second one is correct::

   # Syntax error
   [ x,y for x in seq1 for y in seq2]
   # Correct
   [ (x,y) for x in seq1 for y in seq2]

The idea of list comprehensions originally comes from the functional programming
language Haskell (https://www.haskell.org).  Greg Ewing argued most effectively
for adding them to Python and wrote the initial list comprehension patch, which
was then discussed for a seemingly endless time on the python-dev mailing list
and kept up-to-date by Skip Montanaro.

.. ======================================================================


Augmented Assignment
====================

Augmented assignment operators, another long-requested feature, have been added
to Python 2.0.  Augmented assignment operators include ``+=``, ``-=``, ``*=``,
and so forth.  For example, the statement ``a += 2`` increments the value of the
variable  ``a`` by 2, equivalent to the slightly lengthier ``a = a + 2``.

The full list of supported assignment operators is ``+=``, ``-=``, ``*=``,
``/=``, ``%=``, ``**=``, ``&=``, ``|=``, ``^=``, ``>>=``, and ``<<=``.  Python
classes can override the augmented assignment operators by defining methods
named :meth:`__iadd__`, :meth:`__isub__`, etc.  For example, the following
:class:`Number` class stores a number and supports using += to create a new
instance with an incremented value.

.. The empty groups below prevent conversion to guillemets.

::

   class Number:
       def __init__(self, value):
           self.value = value
       def __iadd__(self, increment):
           return Number( self.value + increment)

   n = Number(5)
   n += 3
   print n.value

The :meth:`__iadd__` special method is called with the value of the increment,
and should return a new instance with an appropriately modified value; this
return value is bound as the new value of the variable on the left-hand side.

Augmented assignment operators were first introduced in the C programming
language, and most C-derived languages, such as :program:`awk`, C++, Java, Perl,
and PHP also support them.  The augmented assignment patch was implemented by
Thomas Wouters.

.. ======================================================================


String Methods
==============

Until now string-manipulation functionality was in the :mod:`string` module,
which was usually a front-end for the :mod:`strop` module written in C.  The
addition of Unicode posed a difficulty for the :mod:`strop` module, because the
functions would all need to be rewritten in order to accept either 8-bit or
Unicode strings.  For functions such as :func:`string.replace`, which takes 3
string arguments, that means eight possible permutations, and correspondingly
complicated code.

Instead, Python 2.0 pushes the problem onto the string type, making string
manipulation functionality available through methods on both 8-bit strings and
Unicode strings.   ::

   >>> 'andrew'.capitalize()
   'Andrew'
   >>> 'hostname'.replace('os', 'linux')
   'hlinuxtname'
   >>> 'moshe'.find('sh')
   2

One thing that hasn't changed, a noteworthy April Fools' joke notwithstanding,
is that Python strings are immutable. Thus, the string methods return new
strings, and do not modify the string on which they operate.

The old :mod:`string` module is still around for backwards compatibility, but it
mostly acts as a front-end to the new string methods.

Two methods which have no parallel in pre-2.0 versions, although they did exist
in JPython for quite some time, are :meth:`startswith` and :meth:`endswith`.
``s.startswith(t)`` is equivalent to ``s[:len(t)] == t``, while
``s.endswith(t)`` is equivalent to ``s[-len(t):] == t``.

One other method which deserves special mention is :meth:`join`.  The
:meth:`join` method of a string receives one parameter, a sequence of strings,
and is equivalent to the :func:`string.join` function from the old :mod:`string`
module, with the arguments reversed. In other words, ``s.join(seq)`` is
equivalent to the old ``string.join(seq, s)``.

.. ======================================================================


Garbage Collection of Cycles
============================

The C implementation of Python uses reference counting to implement garbage
collection.  Every Python object maintains a count of the number of references
pointing to itself, and adjusts the count as references are created or
destroyed.  Once the reference count reaches zero, the object is no longer
accessible, since you need to have a reference to an object to access it, and if
the count is zero, no references exist any longer.

Reference counting has some pleasant properties: it's easy to understand and
implement, and the resulting implementation is portable, fairly fast, and reacts
well with other libraries that implement their own memory handling schemes.  The
major problem with reference counting is that it sometimes doesn't realise that
objects are no longer accessible, resulting in a memory leak.  This happens when
there are cycles of references.

Consider the simplest possible cycle,  a class instance which has a reference to
itself::

   instance = SomeClass()
   instance.myself = instance

After the above two lines of code have been executed, the reference count of
``instance`` is 2; one reference is from the variable named ``'instance'``, and
the other is from the ``myself`` attribute of the instance.

If the next line of code is ``del instance``, what happens?  The reference count
of ``instance`` is decreased by 1, so it has a reference count of 1; the
reference in the ``myself`` attribute still exists.  Yet the instance is no
longer accessible through Python code, and it could be deleted.  Several objects
can participate in a cycle if they have references to each other, causing all of
the objects to be leaked.

Python 2.0 fixes this problem by periodically executing a cycle detection
algorithm which looks for inaccessible cycles and deletes the objects involved.
A new :mod:`gc` module provides functions to perform a garbage collection,
obtain debugging statistics, and tuning the collector's parameters.

Running the cycle detection algorithm takes some time, and therefore will result
in some additional overhead.  It is hoped that after we've gotten experience
with the cycle collection from using 2.0, Python 2.1 will be able to minimize
the overhead with careful tuning.  It's not yet obvious how much performance is
lost, because benchmarking this is tricky and depends crucially on how often the
program creates and destroys objects.  The detection of cycles can be disabled
when Python is compiled, if you can't afford even a tiny speed penalty or
suspect that the cycle collection is buggy, by specifying the
:option:`!--without-cycle-gc` switch when running the :program:`configure`
script.

Several people tackled this problem and contributed to a solution.  An early
implementation of the cycle detection approach was written by Toby Kelsey.  The
current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and
Guido van Rossum and Neil Schemenauer wrote two different implementations, which
were later integrated by Neil.  Lots of other people offered suggestions along
the way; the March 2000 archives of the python-dev mailing list contain most of
the relevant discussion, especially in the threads titled "Reference cycle
collection for Python" and "Finalization again".

.. ======================================================================


Other Core Changes
==================

Various minor changes have been made to Python's syntax and built-in functions.
None of the changes are very far-reaching, but they're handy conveniences.


Minor Language Changes
----------------------

A new syntax makes it more convenient to call a given function with a tuple of
arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
you'd use the :func:`apply` built-in function: ``apply(f, args, kw)`` calls the
function :func:`f` with the argument tuple *args* and the keyword arguments in
the dictionary *kw*.  :func:`apply`  is the same in 2.0, but thanks to a patch
from Greg Ewing, ``f(*args, **kw)`` is a shorter and clearer way to achieve the
same effect.  This syntax is symmetrical with the syntax for defining
functions::

   def f(*args, **kw):
       # args is a tuple of positional args,
       # kw is a dictionary of keyword args
       ...

The :keyword:`print` statement can now have its output directed to a file-like
object by following the :keyword:`print` with  ``>> file``, similar to the
redirection operator in Unix shells. Previously you'd either have to use the
:meth:`write` method of the file-like object, which lacks the convenience and
simplicity of :keyword:`print`, or you could assign a new value to
``sys.stdout`` and then restore the old value.  For sending output to standard
error, it's much easier to write this::

   print >> sys.stderr, "Warning: action field not supplied"

Modules can now be renamed on importing them, using the syntax ``import module
as name`` or ``from module import name as othername``.  The patch was submitted
by Thomas Wouters.

A new format style is available when using the ``%`` operator; '%r' will insert
the :func:`repr` of its argument.  This was also added from symmetry
considerations, this time for symmetry with the existing '%s' format style,
which inserts the :func:`str` of its argument.  For example, ``'%r %s' % ('abc',
'abc')`` returns a string containing ``'abc' abc``.

Previously there was no way to implement a class that overrode Python's built-in
:keyword:`in` operator and implemented a custom version.  ``obj in seq`` returns
true if *obj* is present in the sequence *seq*; Python computes this by simply
trying every index of the sequence until either *obj* is found or an
:exc:`IndexError` is encountered.  Moshe Zadka contributed a patch which adds a
:meth:`__contains__` magic method for providing a custom implementation for
:keyword:`in`. Additionally, new built-in objects written in C can define what
:keyword:`in` means for them via a new slot in the sequence protocol.

Earlier versions of Python used a recursive algorithm for deleting objects.
Deeply nested data structures could cause the interpreter to fill up the C stack
and crash; Christian Tismer rewrote the deletion logic to fix this problem.  On
a related note, comparing recursive objects recursed infinitely and crashed;
Jeremy Hylton rewrote the code to no longer crash, producing a useful result
instead.  For example, after this code::

   a = []
   b = []
   a.append(a)
   b.append(b)

The comparison ``a==b`` returns true, because the two recursive data structures
are isomorphic. See the thread "trashcan and PR#7" in the April 2000 archives of
the python-dev mailing list for the discussion leading up to this
implementation, and some useful relevant links.    Note that comparisons can now
also raise exceptions. In earlier versions of Python, a comparison operation
such as ``cmp(a,b)`` would always produce an answer, even if a user-defined
:meth:`__cmp__` method encountered an error, since the resulting exception would
simply be silently swallowed.

.. Starting URL:
.. https://www.python.org/pipermail/python-dev/2000-April/004834.html

Work has been done on porting Python to 64-bit Windows on the Itanium processor,
mostly by Trent Mick of ActiveState.  (Confusingly, ``sys.platform`` is still
``'win32'`` on Win64 because it seems that for ease of porting, MS Visual C++
treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the
Python CE page at http://pythonce.sourceforge.net/ for more information.

Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0.
Dynamic loading works, if you specify "configure --with-dyld --with-suffix=.x".
Consult the README in the Python source distribution for more instructions.

An attempt has been made to alleviate one of Python's warts, the often-confusing
:exc:`NameError` exception when code refers to a local variable before the
variable has been assigned a value.  For example, the following code raises an
exception on the :keyword:`print` statement in both 1.5.2 and 2.0; in 1.5.2 a
:exc:`NameError` exception is raised, while 2.0 raises a new
:exc:`UnboundLocalError` exception. :exc:`UnboundLocalError` is a subclass of
:exc:`NameError`, so any existing code that expects :exc:`NameError` to be
raised should still work. ::

   def f():
       print "i=",i
       i = i + 1
   f()

Two new exceptions, :exc:`TabError` and :exc:`IndentationError`, have been
introduced.  They're both subclasses of :exc:`SyntaxError`, and are raised when
Python code is found to be improperly indented.


Changes to Built-in Functions
-----------------------------

A new built-in, ``zip(seq1, seq2, ...)``, has been added.  :func:`zip`
returns a list of tuples where each tuple contains the i-th element from each of
the argument sequences.  The difference between :func:`zip` and ``map(None,
seq1, seq2)`` is that :func:`map` pads the sequences with ``None`` if the
sequences aren't all of the same length, while :func:`zip` truncates the
returned list to the length of the shortest argument sequence.

The :func:`int` and :func:`long` functions now accept an optional "base"
parameter when the first argument is a string. ``int('123', 10)`` returns 123,
while ``int('123', 16)`` returns 291.  ``int(123, 16)`` raises a
:exc:`TypeError` exception with the message "can't convert non-string with
explicit base".

A new variable holding more detailed version information has been added to the
:mod:`sys` module.  ``sys.version_info`` is a tuple ``(major, minor, micro,
level, serial)`` For example, in a hypothetical 2.0.1beta1, ``sys.version_info``
would be ``(2, 0, 1, 'beta', 1)``. *level* is a string such as ``"alpha"``,
``"beta"``, or ``"final"`` for a final release.

Dictionaries have an odd new method, ``setdefault(key, default)``, which
behaves similarly to the existing :meth:`get` method.  However, if the key is
missing, :meth:`setdefault` both returns the value of *default* as :meth:`get`
would do, and also inserts it into the dictionary as the value for *key*.  Thus,
the following lines of code::

   if dict.has_key( key ): return dict[key]
   else:
       dict[key] = []
       return dict[key]

can be reduced to a single ``return dict.setdefault(key, [])`` statement.

The interpreter sets a maximum recursion depth in order to catch runaway
recursion before filling the C stack and causing a core dump or GPF..
Previously this limit was fixed when you compiled Python, but in 2.0 the maximum
recursion depth can be read and modified using :func:`sys.getrecursionlimit` and
:func:`sys.setrecursionlimit`. The default value is 1000, and a rough maximum
value for a given platform can be found by running a new script,
:file:`Misc/find_recursionlimit.py`.

.. ======================================================================


Porting to 2.0
==============

New Python releases try hard to be compatible with previous releases, and the
record has been pretty good.  However, some changes are considered useful
enough, usually because they fix initial design decisions that turned out to be
actively mistaken, that breaking backward compatibility can't always be avoided.
This section lists the changes in Python 2.0 that may cause old Python code to
break.

The change which will probably break the most code is tightening up the
arguments accepted by some methods.  Some methods would take multiple arguments
and treat them as a tuple, particularly various list methods such as
:meth:`append` and :meth:`insert`. In earlier versions of Python, if ``L`` is
a list, ``L.append( 1,2 )`` appends the tuple ``(1,2)`` to the list.  In Python
2.0 this causes a :exc:`TypeError` exception to be raised, with the message:
'append requires exactly 1 argument; 2 given'.  The fix is to simply add an
extra set of parentheses to pass both values as a tuple:  ``L.append( (1,2) )``.

The earlier versions of these methods were more forgiving because they used an
old function in Python's C interface to parse their arguments; 2.0 modernizes
them to use :func:`PyArg_ParseTuple`, the current argument parsing function,
which provides more helpful error messages and treats multi-argument calls as
errors.  If you absolutely must use 2.0 but can't fix your code, you can edit
:file:`Objects/listobject.c` and define the preprocessor symbol
``NO_STRICT_LIST_APPEND`` to preserve the old behaviour; this isn't recommended.

Some of the functions in the :mod:`socket` module are still forgiving in this
way.  For example, :func:`socket.connect( ('hostname', 25) )` is the correct
form, passing a tuple representing an IP address, but :func:`socket.connect(
'hostname', 25 )` also works. :func:`socket.connect_ex` and :func:`socket.bind`
are similarly easy-going.  2.0alpha1 tightened these functions up, but because
the documentation actually used the erroneous multiple argument form, many
people wrote code which would break with the stricter checking.  GvR backed out
the changes in the face of public reaction, so for the :mod:`socket` module, the
documentation was fixed and the multiple argument form is simply marked as
deprecated; it *will* be tightened up again in a future Python version.

The ``\x`` escape in string literals now takes exactly 2 hex digits.  Previously
it would consume all the hex digits following the 'x' and take the lowest 8 bits
of the result, so ``\x123456`` was equivalent to ``\x56``.

The :exc:`AttributeError` and :exc:`NameError` exceptions have a more friendly
error message, whose text will be something like ``'Spam' instance has no
attribute 'eggs'`` or ``name 'eggs' is not defined``.  Previously the error
message was just the missing attribute name ``eggs``, and code written to take
advantage of this fact will break in 2.0.

Some work has been done to make integers and long integers a bit more
interchangeable.  In 1.5.2, large-file support was added for Solaris, to allow
reading files larger than 2 GiB; this made the :meth:`tell` method of file
objects return a long integer instead of a regular integer.  Some code would
subtract two file offsets and attempt to use the result to multiply a sequence
or slice a string, but this raised a :exc:`TypeError`.  In 2.0, long integers
can be used to multiply or slice a sequence, and it'll behave as you'd
intuitively expect it to; ``3L * 'abc'`` produces 'abcabcabc', and
``(0,1,2,3)[2L:4L]`` produces (2,3). Long integers can also be used in various
contexts where previously only integers were accepted, such as in the
:meth:`seek` method of file objects, and in the formats supported by the ``%``
operator (``%d``, ``%i``, ``%x``, etc.).  For example, ``"%d" % 2L**64`` will
produce the string ``18446744073709551616``.

The subtlest long integer change of all is that the :func:`str` of a long
integer no longer has a trailing 'L' character, though :func:`repr` still
includes it.  The 'L' annoyed many people who wanted to print long integers that
looked just like regular integers, since they had to go out of their way to chop
off the character.  This is no longer a problem in 2.0, but code which does
``str(longval)[:-1]`` and assumes the 'L' is there, will now lose the final
digit.

Taking the :func:`repr` of a float now uses a different formatting precision
than :func:`str`.  :func:`repr` uses ``%.17g`` format string for C's
:func:`sprintf`, while :func:`str` uses ``%.12g`` as before.  The effect is that
:func:`repr` may occasionally show more decimal places than  :func:`str`, for
certain numbers.  For example, the number 8.1 can't be represented exactly in
binary, so ``repr(8.1)`` is ``'8.0999999999999996'``, while str(8.1) is
``'8.1'``.

The ``-X`` command-line option, which turned all standard exceptions into
strings instead of classes, has been removed; the standard exceptions will now
always be classes.  The :mod:`exceptions` module containing the standard
exceptions was translated from Python to a built-in C module, written by Barry
Warsaw and Fredrik Lundh.

.. Commented out for now -- I don't think anyone will care.
   The pattern and match objects provided by SRE are C types, not Python
   class instances as in 1.5.  This means you can no longer inherit from
   \class{RegexObject} or \class{MatchObject}, but that shouldn't be much
   of a problem since no one should have been doing that in the first
   place.
.. ======================================================================


Extending/Embedding Changes
===========================

Some of the changes are under the covers, and will only be apparent to people
writing C extension modules or embedding a Python interpreter in a larger
application.  If you aren't dealing with Python's C API, you can safely skip
this section.

The version number of the Python C API was incremented, so C extensions compiled
for 1.5.2 must be recompiled in order to work with 2.0.  On Windows, it's not
possible for Python 2.0 to import a third party extension built for Python 1.5.x
due to how Windows DLLs work, so Python will raise an exception and the import
will fail.

Users of Jim Fulton's ExtensionClass module will be pleased to find out that
hooks have been added so that ExtensionClasses are now supported by
:func:`isinstance` and :func:`issubclass`. This means you no longer have to
remember to write code such as ``if type(obj) == myExtensionClass``, but can use
the more natural ``if isinstance(obj, myExtensionClass)``.

The :file:`Python/importdl.c` file, which was a mass of #ifdefs to support
dynamic loading on many different platforms, was cleaned up and reorganised by
Greg Stein.  :file:`importdl.c` is now quite small, and platform-specific code
has been moved into a bunch of :file:`Python/dynload_\*.c` files.  Another
cleanup: there were also a number of :file:`my\*.h` files in the Include/
directory that held various portability hacks; they've been merged into a single
file, :file:`Include/pyport.h`.

Vladimir Marangozov's long-awaited malloc restructuring was completed, to make
it easy to have the Python interpreter use a custom allocator instead of C's
standard :func:`malloc`.  For documentation, read the comments in
:file:`Include/pymem.h` and :file:`Include/objimpl.h`.  For the lengthy
discussions during which the interface was hammered out, see the Web archives of
the 'patches' and 'python-dev' lists at python.org.

Recent versions of the GUSI development environment for MacOS support POSIX
threads.  Therefore, Python's POSIX threading support now works on the
Macintosh.  Threading support using the user-space GNU ``pth`` library was also
contributed.

Threading support on Windows was enhanced, too.  Windows supports thread locks
that use kernel objects only in case of contention; in the common case when
there's no contention, they use simpler functions which are an order of
magnitude faster.  A threaded version of Python 1.5.2 on NT is twice as slow as
an unthreaded version; with the 2.0 changes, the difference is only 10%.  These
improvements were contributed by Yakov Markovitch.

Python 2.0's source now uses only ANSI C prototypes, so compiling Python now
requires an ANSI C compiler, and can no longer be done using a compiler that
only supports K&R C.

Previously the Python virtual machine used 16-bit numbers in its bytecode,
limiting the size of source files.  In particular, this affected the maximum
size of literal lists and dictionaries in Python source; occasionally people who
are generating Python code would run into this limit.  A patch by Charles G.
Waldman raises the limit from ``2^16`` to ``2^{32}``.

Three new convenience functions intended for adding constants to a module's
dictionary at module initialization time were added: :func:`PyModule_AddObject`,
:func:`PyModule_AddIntConstant`, and :func:`PyModule_AddStringConstant`.  Each
of these functions takes a module object, a null-terminated C string containing
the name to be added, and a third argument for the value to be assigned to the
name.  This third argument is, respectively, a Python object, a C long, or a C
string.

A wrapper API was added for Unix-style signal handlers. :func:`PyOS_getsig` gets
a signal handler and :func:`PyOS_setsig` will set a new handler.

.. ======================================================================


Distutils: Making Modules Easy to Install
=========================================

Before Python 2.0, installing modules was a tedious affair -- there was no way
to figure out automatically where Python is installed, or what compiler options
to use for extension modules.  Software authors had to go through an arduous
ritual of editing Makefiles and configuration files, which only really work on
Unix and leave Windows and MacOS unsupported.  Python users faced wildly
differing installation instructions which varied between different extension
packages, which made administering a Python installation something of  a chore.

The SIG for distribution utilities, shepherded by Greg Ward, has created the
Distutils, a system to make package installation much easier.  They form the
:mod:`distutils` package, a new part of Python's standard library. In the best
case, installing a Python module from source will require the same steps: first
you simply mean unpack the tarball or zip archive, and the run "``python
setup.py install``".  The platform will be automatically detected, the compiler
will be recognized, C extension modules will be compiled, and the distribution
installed into the proper directory.  Optional command-line arguments provide
more control over the installation process, the distutils package offers many
places to override defaults -- separating the build from the install, building
or installing in non-default directories, and more.

In order to use the Distutils, you need to write a :file:`setup.py` script.  For
the simple case, when the software contains only .py files, a minimal
:file:`setup.py` can be just a few lines long::

   from distutils.core import setup
   setup (name = "foo", version = "1.0",
          py_modules = ["module1", "module2"])

The :file:`setup.py` file isn't much more complicated if the software consists
of a few packages::

   from distutils.core import setup
   setup (name = "foo", version = "1.0",
          packages = ["package", "package.subpackage"])

A C extension can be the most complicated case; here's an example taken from
the PyXML package::

   from distutils.core import setup, Extension

   expat_extension = Extension('xml.parsers.pyexpat',
        define_macros = [('XML_NS', None)],
        include_dirs = [ 'extensions/expat/xmltok',
                         'extensions/expat/xmlparse' ],
        sources = [ 'extensions/pyexpat.c',
                    'extensions/expat/xmltok/xmltok.c',
                    'extensions/expat/xmltok/xmlrole.c', ]
          )
   setup (name = "PyXML", version = "0.5.4",
          ext_modules =[ expat_extension ] )

The Distutils can also take care of creating source and binary distributions.
The "sdist" command, run by "``python setup.py sdist``', builds a source
distribution such as :file:`foo-1.0.tar.gz`. Adding new commands isn't
difficult, "bdist_rpm" and "bdist_wininst" commands have already been
contributed to create an RPM distribution and a Windows installer for the
software, respectively.  Commands to create other distribution formats such as
Debian packages and Solaris :file:`.pkg` files are in various stages of
development.

All this is documented in a new manual, *Distributing Python Modules*, that
joins the basic set of Python documentation.

.. ======================================================================


XML Modules
===========

Python 1.5.2 included a simple XML parser in the form of the :mod:`xmllib`
module, contributed by Sjoerd Mullender.  Since 1.5.2's release, two different
interfaces for processing XML have become common: SAX2 (version 2 of the Simple
API for XML) provides an event-driven interface with some similarities to
:mod:`xmllib`, and the DOM (Document Object Model) provides a tree-based
interface, transforming an XML document into a tree of nodes that can be
traversed and modified.  Python 2.0 includes a SAX2 interface and a stripped-down
DOM interface as part of the :mod:`xml` package. Here we will give a brief
overview of these new interfaces; consult the Python documentation or the source
code for complete details. The Python XML SIG is also working on improved
documentation.


SAX2 Support
------------

SAX defines an event-driven interface for parsing XML.  To use SAX, you must
write a SAX handler class.  Handler classes inherit from various classes
provided by SAX, and override various methods that will then be called by the
XML parser.  For example, the :meth:`startElement` and :meth:`endElement`
methods are called for every starting and end tag encountered by the parser, the
:meth:`characters` method is called for every chunk of character data, and so
forth.

The advantage of the event-driven approach is that the whole document doesn't
have to be resident in memory at any one time, which matters if you are
processing really huge documents.  However, writing the SAX handler class can
get very complicated if you're trying to modify the document structure in some
elaborate way.

For example, this little example program defines a handler that prints a message
for every starting and ending tag, and then parses the file :file:`hamlet.xml`
using it::

   from xml import sax

   class SimpleHandler(sax.ContentHandler):
       def startElement(self, name, attrs):
           print 'Start of element:', name, attrs.keys()

       def endElement(self, name):
           print 'End of element:', name

   # Create a parser object
   parser = sax.make_parser()

   # Tell it what handler to use
   handler = SimpleHandler()
   parser.setContentHandler( handler )

   # Parse a file!
   parser.parse( 'hamlet.xml' )

For more information, consult the Python documentation, or the XML HOWTO at
http://pyxml.sourceforge.net/topics/howto/xml-howto.html.


DOM Support
-----------

The Document Object Model is a tree-based representation for an XML document.  A
top-level :class:`Document` instance is the root of the tree, and has a single
child which is the top-level :class:`Element` instance. This :class:`Element`
has children nodes representing character data and any sub-elements, which may
have further children of their own, and so forth.  Using the DOM you can
traverse the resulting tree any way you like, access element and attribute
values, insert and delete nodes, and convert the tree back into XML.

The DOM is useful for modifying XML documents, because you can create a DOM
tree, modify it by adding new nodes or rearranging subtrees, and then produce a
new XML document as output.  You can also construct a DOM tree manually and
convert it to XML, which can be a more flexible way of producing XML output than
simply writing ``<tag1>``...\ ``</tag1>`` to a file.

The DOM implementation included with Python lives in the :mod:`xml.dom.minidom`
module.  It's a lightweight implementation of the Level 1 DOM with support for
XML namespaces.  The  :func:`parse` and :func:`parseString` convenience
functions are provided for generating a DOM tree::

   from xml.dom import minidom
   doc = minidom.parse('hamlet.xml')

``doc`` is a :class:`Document` instance.  :class:`Document`, like all the other
DOM classes such as :class:`Element` and :class:`Text`, is a subclass of the
:class:`Node` base class.  All the nodes in a DOM tree therefore support certain
common methods, such as :meth:`toxml` which returns a string containing the XML
representation of the node and its children.  Each class also has special
methods of its own; for example, :class:`Element` and :class:`Document`
instances have a method to find all child elements with a given tag name.
Continuing from the previous 2-line example::

   perslist = doc.getElementsByTagName( 'PERSONA' )
   print perslist[0].toxml()
   print perslist[1].toxml()

For the *Hamlet* XML file, the above few lines output::

   <PERSONA>CLAUDIUS, king of Denmark. </PERSONA>
   <PERSONA>HAMLET, son to the late, and nephew to the present king.</PERSONA>

The root element of the document is available as ``doc.documentElement``, and
its children can be easily modified by deleting, adding, or removing nodes::

   root = doc.documentElement

   # Remove the first child
   root.removeChild( root.childNodes[0] )

   # Move the new first child to the end
   root.appendChild( root.childNodes[0] )

   # Insert the new first child (originally,
   # the third child) before the 20th child.
   root.insertBefore( root.childNodes[0], root.childNodes[20] )

Again, I will refer you to the Python documentation for a complete listing of
the different :class:`Node` classes and their various methods.


Relationship to PyXML
---------------------

The XML Special Interest Group has been working on XML-related Python code for a
while.  Its code distribution, called PyXML, is available from the SIG's Web
pages at https://www.python.org/community/sigs/current/xml-sig. The PyXML distribution also used
the package name ``xml``.  If you've written programs that used PyXML, you're
probably wondering about its compatibility with the 2.0 :mod:`xml` package.

The answer is that Python 2.0's :mod:`xml` package isn't compatible with PyXML,
but can be made compatible by installing a recent version PyXML.  Many
applications can get by with the XML support that is included with Python 2.0,
but more complicated applications will require that the full PyXML package will
be installed.  When installed, PyXML versions 0.6.0 or greater will replace the
:mod:`xml` package shipped with Python, and will be a strict superset of the
standard package, adding a bunch of additional features.  Some of the additional
features in PyXML include:

* 4DOM, a full DOM implementation from FourThought, Inc.

* The xmlproc validating parser, written by Lars Marius Garshol.

* The :mod:`sgmlop` parser accelerator module, written by Fredrik Lundh.

.. ======================================================================


Module changes
==============

Lots of improvements and bugfixes were made to Python's extensive standard
library; some of the affected modules include :mod:`readline`,
:mod:`ConfigParser`, :mod:`cgi`, :mod:`calendar`, :mod:`posix`, :mod:`readline`,
:mod:`xmllib`, :mod:`aifc`, :mod:`chunk, wave`, :mod:`random`, :mod:`shelve`,
and :mod:`nntplib`.  Consult the CVS logs for the exact patch-by-patch details.

Brian Gallew contributed OpenSSL support for the :mod:`socket` module.  OpenSSL
is an implementation of the Secure Socket Layer, which encrypts the data being
sent over a socket.  When compiling Python, you can edit :file:`Modules/Setup`
to include SSL support, which adds an additional function to the :mod:`socket`
module: ``socket.ssl(socket, keyfile, certfile)``, which takes a socket
object and returns an SSL socket.  The :mod:`httplib` and :mod:`urllib` modules
were also changed to support ``https://`` URLs, though no one has implemented
FTP or SMTP over SSL.

The :mod:`httplib` module has been rewritten by Greg Stein to support HTTP/1.1.
Backward compatibility with the 1.5 version of :mod:`httplib` is provided,
though using HTTP/1.1 features such as pipelining will require rewriting code to
use a different set of interfaces.

The :mod:`Tkinter` module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
support for the older 7.x versions has been dropped.  The Tkinter module now
supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh
contributed an optimization which makes operations like ``create_line`` and
``create_polygon`` much faster, especially when using lots of coordinates.

The :mod:`curses` module has been greatly extended, starting from Oliver
Andrich's enhanced version, to provide many additional functions from ncurses
and SYSV curses, such as colour, alternative character set support, pads, and
mouse support.  This means the module is no longer compatible with operating
systems that only have BSD curses, but there don't seem to be any currently
maintained OSes that fall into this category.

As mentioned in the earlier discussion of 2.0's Unicode support, the underlying
implementation of the regular expressions provided by the :mod:`re` module has
been changed.  SRE, a new regular expression engine written by Fredrik Lundh and
partially funded by Hewlett Packard, supports matching against both 8-bit
strings and Unicode strings.

.. ======================================================================


New modules
===========

A number of new modules were added.  We'll simply list them with brief
descriptions; consult the 2.0 documentation for the details of a particular
module.

* :mod:`atexit`:  For registering functions to be called before the Python
  interpreter exits. Code that currently sets ``sys.exitfunc`` directly should be
  changed to  use the :mod:`atexit` module instead, importing :mod:`atexit` and
  calling :func:`atexit.register` with  the function to be called on exit.
  (Contributed by Skip Montanaro.)

* :mod:`codecs`, :mod:`encodings`, :mod:`unicodedata`:  Added as part of the new
  Unicode support.

* :mod:`filecmp`: Supersedes the old :mod:`cmp`, :mod:`cmpcache` and
  :mod:`dircmp` modules, which have now become deprecated. (Contributed by Gordon
  MacMillan and Moshe Zadka.)

* :mod:`gettext`: This module provides internationalization (I18N) and
  localization (L10N) support for Python programs by providing an interface to the
  GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate
  contributions by Martin  von Löwis, Peter Funk, and James Henstridge.)

* :mod:`linuxaudiodev`: Support for the :file:`/dev/audio` device on Linux, a
  twin to the existing :mod:`sunaudiodev` module. (Contributed by Peter Bosch,
  with fixes by Jeremy Hylton.)

* :mod:`mmap`: An interface to memory-mapped files on both Windows and Unix.  A
  file's contents can be mapped directly into memory, at which point it behaves
  like a mutable string, so its contents can be read and modified.  They can even
  be passed to functions that expect ordinary strings, such as the :mod:`re`
  module. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)

* :mod:`pyexpat`: An interface to the Expat XML parser. (Contributed by Paul
  Prescod.)

* :mod:`robotparser`: Parse a :file:`robots.txt` file, which is used for writing
  Web spiders that politely avoid certain areas of a Web site.  The parser accepts
  the contents of a :file:`robots.txt` file, builds a set of rules from it, and
  can then answer questions about the fetchability of a given URL.  (Contributed
  by Skip Montanaro.)

* :mod:`tabnanny`: A module/script to  check Python source code for ambiguous
  indentation. (Contributed by Tim Peters.)

* :mod:`UserString`: A base class useful for deriving objects that behave like
  strings.

* :mod:`webbrowser`: A module that provides a platform independent way to launch
  a web browser on a specific URL. For each platform, various browsers are tried
  in a specific order. The user can alter which browser is launched by setting the
  *BROWSER* environment variable.  (Originally inspired by Eric S. Raymond's patch
  to :mod:`urllib` which added similar functionality, but the final module comes
  from code originally  implemented by Fred Drake as
  :file:`Tools/idle/BrowserControl.py`, and adapted for the standard library by
  Fred.)

* :mod:`_winreg`: An interface to the Windows registry.  :mod:`_winreg` is an
  adaptation of functions that have been part of PythonWin since 1995, but has now
  been added to the core  distribution, and enhanced to support Unicode.
  :mod:`_winreg` was written by Bill Tutt and Mark Hammond.

* :mod:`zipfile`: A module for reading and writing ZIP-format archives.  These
  are archives produced by :program:`PKZIP` on DOS/Windows or :program:`zip` on
  Unix, not to be confused with :program:`gzip`\ -format files (which are
  supported by the :mod:`gzip` module) (Contributed by James C. Ahlstrom.)

* :mod:`imputil`: A module that provides a simpler way for writing customised
  import hooks, in comparison to the existing :mod:`ihooks` module.  (Implemented
  by Greg Stein, with much discussion on python-dev along the way.)

.. ======================================================================


IDLE Improvements
=================

IDLE is the official Python cross-platform IDE, written using Tkinter. Python
2.0 includes IDLE 0.6, which adds a number of new features and improvements.  A
partial list:

* UI improvements and optimizations, especially in the area of syntax
  highlighting and auto-indentation.

* The class browser now shows more information, such as the top level functions
  in a module.

* Tab width is now a user settable option. When opening an existing Python file,
  IDLE automatically detects the indentation conventions, and adapts.

* There is now support for calling browsers on various platforms, used to open
  the Python documentation in a browser.

* IDLE now has a command line, which is largely similar to  the vanilla Python
  interpreter.

* Call tips were added in many places.

* IDLE can now be installed as a package.

* In the editor window, there is now a line/column bar at the bottom.

* Three new keystroke commands: Check module (:kbd:`Alt-F5`), Import module (:kbd:`F5`) and
  Run script (:kbd:`Ctrl-F5`).

.. ======================================================================


Deleted and Deprecated Modules
==============================

A few modules have been dropped because they're obsolete, or because there are
now better ways to do the same thing.  The :mod:`stdwin` module is gone; it was
for a platform-independent windowing toolkit that's no longer developed.

A number of modules have been moved to the :file:`lib-old` subdirectory:
:mod:`cmp`, :mod:`cmpcache`, :mod:`dircmp`, :mod:`dump`,  :mod:`find`,
:mod:`grep`, :mod:`packmail`,  :mod:`poly`, :mod:`util`, :mod:`whatsound`,
:mod:`zmod`.  If you have code which relies on a module  that's been moved to
:file:`lib-old`, you can simply add that directory to ``sys.path``   to get them
back, but you're encouraged to update any code that uses these modules.


Acknowledgements
================

The authors would like to thank the following people for offering suggestions on
various drafts of this article: David Bolen, Mark Hammond, Gregg Hauser, Jeremy
Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir
Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.

PK
%�\��VR����"html/_sources/whatsnew/2.1.rst.txtnu�[���****************************
  What's New in Python 2.1
****************************

:Author: A.M. Kuchling

.. |release| replace:: 1.01

.. $Id: whatsnew21.tex 50964 2006-07-30 03:03:43Z fred.drake $


Introduction
============

This article explains the new features in Python 2.1.  While there aren't as
many changes in 2.1 as there were in Python 2.0, there are still some pleasant
surprises in store.  2.1 is the first release to be steered through the use of
Python Enhancement Proposals, or PEPs, so most of the sizable changes have
accompanying PEPs that provide more complete documentation and a design
rationale for the change.  This article doesn't attempt to document the new
features completely, but simply provides an overview of the new features for
Python programmers. Refer to the Python 2.1 documentation, or to the specific
PEP, for more details about any new feature that particularly interests you.

One recent goal of the Python development team has been to accelerate the pace
of new releases, with a new release coming every 6 to 9 months. 2.1 is the first
release to come out at this faster pace, with the first alpha appearing in
January, 3 months after the final version of 2.0 was released.

The final release of Python 2.1 was made on April 17, 2001.

.. ======================================================================


PEP 227: Nested Scopes
======================

The largest change in Python 2.1 is to Python's scoping rules.  In Python 2.0,
at any given time there are at most three namespaces used to look up variable
names: local, module-level, and the built-in namespace.  This often surprised
people because it didn't match their intuitive expectations.  For example, a
nested recursive function definition doesn't work::

   def f():
       ...
       def g(value):
           ...
           return g(value-1) + 1
       ...

The function :func:`g` will always raise a :exc:`NameError` exception, because
the binding of the name ``g`` isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the :keyword:`lambda` statement clumsier, and this was a problem in practice.
In code which uses :keyword:`lambda` you can often find local variables being
copied by passing them as the default values of arguments. ::

   def find(self, name):
       "Return list of any entries equal to 'name'"
       L = filter(lambda x, name=name: x == name,
                  self.list_attribute)
       return L

The readability of Python code written in a strongly functional style suffers
greatly as a result.

The most significant change to Python 2.1 is that static scoping has been added
to the language to fix this problem.  As a first effect, the ``name=name``
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the :keyword:`def`, :keyword:`class`, or :keyword:`import` statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.

One side effect of the change is that the ``from module import *`` and
:keyword:`exec` statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that ``from
module import *`` is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  ``from
module import *`` and :keyword:`exec` make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or :keyword:`lambda` expressions with free variables, the compiler
will flag this by raising a :exc:`SyntaxError` exception.

To make the preceding explanation a bit clearer, here's an example::

   x = 1
   def f():
       # The next line is a syntax error
       exec 'x=2'
       def g():
           return x

Line 4 containing the :keyword:`exec` statement is a syntax error, since
:keyword:`exec` would define a new local variable named ``x`` whose value should
be accessed by :func:`g`.

This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
most Python code (and when it is used, it's often a sign of a poor design
anyway).

Compatibility concerns have led to nested scopes being introduced gradually; in
Python 2.1, they aren't enabled by default, but can be turned on within a module
by using a future statement as described in PEP 236.  (See the following section
for further discussion of PEP 236.)  In Python 2.2, nested scopes will become
the default and there will be no way to turn them off, but users will have had
all of 2.1's lifetime to fix any breakage resulting from their introduction.


.. seealso::

   :pep:`227` - Statically Nested Scopes
      Written and implemented by Jeremy Hylton.

.. ======================================================================


PEP 236: __future__ Directives
==============================

The reaction to nested scopes was widespread concern about the dangers of
breaking code with the 2.1 release, and it was strong enough to make the
Pythoneers take a more conservative approach.  This approach consists of
introducing a convention for enabling optional functionality in release N that
will become compulsory in release N+1.

The syntax uses a ``from...import`` statement using the reserved module name
:mod:`__future__`.  Nested scopes can be enabled by the following statement::

   from __future__ import nested_scopes

While it looks like a normal :keyword:`import` statement, it's not; there are
strict rules on where such a future statement can be put. They can only be at
the top of a module, and must precede any Python code or regular
:keyword:`import` statements.  This is because such statements can affect how
the Python bytecode compiler parses code and generates bytecode, so they must
precede any statement that will result in bytecodes being produced.


.. seealso::

   :pep:`236` - Back to the :mod:`__future__`
      Written by Tim Peters, and primarily implemented by Jeremy Hylton.

.. ======================================================================


PEP 207: Rich Comparisons
=========================

In earlier versions, Python's support for implementing comparisons on user-defined
classes and extension types was quite simple. Classes could implement a
:meth:`__cmp__` method that was given two instances of a class, and could only
return 0 if they were equal or +1 or -1 if they weren't; the method couldn't
raise an exception or return anything other than a Boolean value.  Users of
Numeric Python often found this model too weak and restrictive, because in the
number-crunching programs that numeric Python is used for, it would be more
useful to be able to perform elementwise comparisons of two matrices, returning
a matrix containing the results of a given comparison for each element.  If the
two matrices are of different sizes, then the compare has to be able to raise an
exception to signal the error.

In Python 2.1, rich comparisons were added in order to support this need.
Python classes can now individually overload each of the ``<``, ``<=``, ``>``,
``>=``, ``==``, and ``!=`` operations.  The new magic method names are:

+-----------+----------------+
| Operation | Method name    |
+===========+================+
| ``<``     | :meth:`__lt__` |
+-----------+----------------+
| ``<=``    | :meth:`__le__` |
+-----------+----------------+
| ``>``     | :meth:`__gt__` |
+-----------+----------------+
| ``>=``    | :meth:`__ge__` |
+-----------+----------------+
| ``==``    | :meth:`__eq__` |
+-----------+----------------+
| ``!=``    | :meth:`__ne__` |
+-----------+----------------+

(The magic methods are named after the corresponding Fortran operators ``.LT.``.
``.LE.``, &c.  Numeric programmers are almost certainly quite familiar with
these names and will find them easy to remember.)

Each of these magic methods is of the form ``method(self, other)``, where
``self`` will be the object on the left-hand side of the operator, while
``other`` will be the object on the right-hand side.  For example, the
expression ``A < B`` will cause ``A.__lt__(B)`` to be called.

Each of these magic methods can return anything at all: a Boolean, a matrix, a
list, or any other Python object.  Alternatively they can raise an exception if
the comparison is impossible, inconsistent, or otherwise meaningless.

The built-in ``cmp(A,B)`` function can use the rich comparison machinery,
and now accepts an optional argument specifying which comparison operation to
use; this is given as one of the strings ``"<"``, ``"<="``, ``">"``, ``">="``,
``"=="``, or ``"!="``.  If called without the optional third argument,
:func:`cmp` will only return -1, 0, or +1 as in previous versions of Python;
otherwise it will call the appropriate method and can return any Python object.

There are also corresponding changes of interest to C programmers; there's a new
slot ``tp_richcmp`` in type objects and an API for performing a given rich
comparison.  I won't cover the C API here, but will refer you to PEP 207, or to
2.1's C API documentation, for the full list of related functions.


.. seealso::

   :pep:`207` - Rich Comparisons
      Written by Guido van Rossum, heavily based on earlier work by David Ascher, and
      implemented by Guido van Rossum.

.. ======================================================================


PEP 230: Warning Framework
==========================

Over its 10 years of existence, Python has accumulated a certain number of
obsolete modules and features along the way.  It's difficult to know when a
feature is safe to remove, since there's no way of knowing how much code uses it
--- perhaps no programs depend on the feature, or perhaps many do.  To enable
removing old features in a more structured way, a warning framework was added.
When the Python developers want to get rid of a feature, it will first trigger a
warning in the next version of Python.  The following Python version can then
drop the feature, and users will have had a full release cycle to remove uses of
the old feature.

Python 2.1 adds the warning framework to be used in this scheme.  It adds a
:mod:`warnings` module that provide functions to issue warnings, and to filter
out warnings that you don't want to be displayed. Third-party modules can also
use this framework to deprecate old features that they no longer wish to
support.

For example, in Python 2.1 the :mod:`regex` module is deprecated, so importing
it causes a warning to be printed::

   >>> import regex
   __main__:1: DeprecationWarning: the regex module
            is deprecated; please use the re module
   >>>

Warnings can be issued by calling the :func:`warnings.warn` function::

   warnings.warn("feature X no longer supported")

The first parameter is the warning message; an additional optional parameters
can be used to specify a particular warning category.

Filters can be added to disable certain warnings; a regular expression pattern
can be applied to the message or to the module name in order to suppress a
warning.  For example, you may have a program that uses the :mod:`regex` module
and not want to spare the time to convert it to use the :mod:`re` module right
now.  The warning can be suppressed by calling ::

   import warnings
   warnings.filterwarnings(action = 'ignore',
                           message='.*regex module is deprecated',
                           category=DeprecationWarning,
                           module = '__main__')

This adds a filter that will apply only to warnings of the class
:class:`DeprecationWarning` triggered in the :mod:`__main__` module, and applies
a regular expression to only match the message about the :mod:`regex` module
being deprecated, and will cause such warnings to be ignored.  Warnings can also
be printed only once, printed every time the offending code is executed, or
turned into exceptions that will cause the program to stop (unless the
exceptions are caught in the usual way, of course).

Functions were also added to Python's C API for issuing warnings; refer to PEP
230 or to Python's API documentation for the details.


.. seealso::

   :pep:`5` - Guidelines for Language Evolution
      Written by Paul Prescod, to specify procedures to be followed when removing old
      features from Python.  The policy described in this PEP hasn't been officially
      adopted, but the eventual policy probably won't be too different from Prescod's
      proposal.

   :pep:`230` - Warning Framework
      Written and implemented by Guido van Rossum.

.. ======================================================================


PEP 229: New Build System
=========================

When compiling Python, the user had to go in and edit the :file:`Modules/Setup`
file in order to enable various additional modules; the default set is
relatively small and limited to modules that compile on most Unix platforms.
This means that on Unix platforms with many more features, most notably Linux,
Python installations often don't contain all useful modules they could.

Python 2.0 added the Distutils, a set of modules for distributing and installing
extensions.  In Python 2.1, the Distutils are used to compile much of the
standard library of extension modules, autodetecting which ones are supported on
the current machine.  It's hoped that this will make Python installations easier
and more featureful.

Instead of having to edit the :file:`Modules/Setup` file in order to enable
modules, a :file:`setup.py` script in the top directory of the Python source
distribution is run at build time, and attempts to discover which modules can be
enabled by examining the modules and header files on the system.  If a module is
configured in :file:`Modules/Setup`, the :file:`setup.py` script won't attempt
to compile that module and will defer to the :file:`Modules/Setup` file's
contents.  This provides a way to specific any strange command-line flags or
libraries that are required for a specific platform.

In another far-reaching change to the build mechanism, Neil Schemenauer
restructured things so Python now uses a single makefile that isn't recursive,
instead of makefiles in the top directory and in each of the :file:`Python/`,
:file:`Parser/`, :file:`Objects/`, and :file:`Modules/` subdirectories.  This
makes building Python faster and also makes hacking the Makefiles clearer and
simpler.


.. seealso::

   :pep:`229` - Using Distutils to Build Python
      Written and implemented by A.M. Kuchling.

.. ======================================================================


PEP 205: Weak References
========================

Weak references, available through the :mod:`weakref` module, are a minor but
useful new data type in the Python programmer's toolbox.

Storing a reference to an object (say, in a dictionary or a list) has the side
effect of keeping that object alive forever.  There are a few specific cases
where this behaviour is undesirable, object caches being the most common one,
and another being circular references in data structures such as trees.

For example, consider a memoizing function that caches the results of another
function ``f(x)`` by storing the function's argument and its result in a
dictionary::

   _cache = {}
   def memoize(x):
       if _cache.has_key(x):
           return _cache[x]

       retval = f(x)

       # Cache the returned object
       _cache[x] = retval

       return retval

This version works for simple things such as integers, but it has a side effect;
the ``_cache`` dictionary holds a reference to the return values, so they'll
never be deallocated until the Python process exits and cleans up This isn't
very noticeable for integers, but if :func:`f` returns an object, or a data
structure that takes up a lot of memory, this can be a problem.

Weak references provide a way to implement a cache that won't keep objects alive
beyond their time.  If an object is only accessible through weak references, the
object will be deallocated and the weak references will now indicate that the
object it referred to no longer exists.  A weak reference to an object *obj* is
created by calling ``wr = weakref.ref(obj)``.  The object being referred to is
returned by calling the weak reference as if it were a function: ``wr()``.  It
will return the referenced object, or ``None`` if the object no longer exists.

This makes it possible to write a :func:`memoize` function whose cache doesn't
keep objects alive, by storing weak references in the cache. ::

   _cache = {}
   def memoize(x):
       if _cache.has_key(x):
           obj = _cache[x]()
           # If weak reference object still exists,
           # return it
           if obj is not None: return obj

       retval = f(x)

       # Cache a weak reference
       _cache[x] = weakref.ref(retval)

       return retval

The :mod:`weakref` module also allows creating proxy objects which behave like
weak references --- an object referenced only by proxy objects is deallocated --
but instead of requiring an explicit call to retrieve the object, the proxy
transparently forwards all operations to the object as long as the object still
exists.  If the object is deallocated, attempting to use a proxy will cause a
:exc:`weakref.ReferenceError` exception to be raised. ::

   proxy = weakref.proxy(obj)
   proxy.attr   # Equivalent to obj.attr
   proxy.meth() # Equivalent to obj.meth()
   del obj
   proxy.attr   # raises weakref.ReferenceError


.. seealso::

   :pep:`205` - Weak References
      Written and implemented by Fred L. Drake, Jr.

.. ======================================================================


PEP 232: Function Attributes
============================

In Python 2.1, functions can now have arbitrary information attached to them.
People were often using docstrings to hold information about functions and
methods, because the ``__doc__`` attribute was the only way of attaching any
information to a function.  For example, in the Zope Web application server,
functions are marked as safe for public access by having a docstring, and in
John Aycock's SPARK parsing framework, docstrings hold parts of the BNF grammar
to be parsed.  This overloading is unfortunate, since docstrings are really
intended to hold a function's documentation; for example, it means you can't
properly document functions intended for private use in Zope.

Arbitrary attributes can now be set and retrieved on functions using the regular
Python syntax::

   def f(): pass

   f.publish = 1
   f.secure = 1
   f.grammar = "A ::= B (C D)*"

The dictionary containing attributes can be accessed as the function's
:attr:`~object.__dict__`. Unlike the :attr:`~object.__dict__` attribute of class instances, in
functions you can actually assign a new dictionary to :attr:`~object.__dict__`, though
the new value is restricted to a regular Python dictionary; you *can't* be
tricky and set it to a :class:`~UserDict.UserDict` instance, or any other random object
that behaves like a mapping.


.. seealso::

   :pep:`232` - Function Attributes
      Written and implemented by Barry Warsaw.

.. ======================================================================


PEP 235: Importing Modules on Case-Insensitive Platforms
========================================================

Some operating systems have filesystems that are case-insensitive, MacOS and
Windows being the primary examples; on these systems, it's impossible to
distinguish the filenames ``FILE.PY`` and ``file.py``, even though they do store
the file's name  in its original case (they're case-preserving, too).

In Python 2.1, the :keyword:`import` statement will work to simulate case-sensitivity
on case-insensitive platforms.  Python will now search for the first
case-sensitive match by default, raising an :exc:`ImportError` if no such file
is found, so ``import file`` will not import a module named ``FILE.PY``.
Case-insensitive matching can be requested by setting the :envvar:`PYTHONCASEOK`
environment variable before starting the Python interpreter.

.. ======================================================================


PEP 217: Interactive Display Hook
=================================

When using the Python interpreter interactively, the output of commands is
displayed using the built-in :func:`repr` function. In Python 2.1, the variable
:func:`sys.displayhook` can be set to a callable object which will be called
instead of :func:`repr`. For example, you can set it to a special
pretty-printing function::

   >>> # Create a recursive data structure
   ... L = [1,2,3]
   >>> L.append(L)
   >>> L # Show Python's default output
   [1, 2, 3, [...]]
   >>> # Use pprint.pprint() as the display function
   ... import sys, pprint
   >>> sys.displayhook = pprint.pprint
   >>> L
   [1, 2, 3,  <Recursion on list with id=135143996>]
   >>>


.. seealso::

   :pep:`217` - Display Hook for Interactive Use
      Written and implemented by Moshe Zadka.

.. ======================================================================


PEP 208: New Coercion Model
===========================

How numeric coercion is done at the C level was significantly modified.  This
will only affect the authors of C extensions to Python, allowing them more
flexibility in writing extension types that support numeric operations.

Extension types can now set the type flag ``Py_TPFLAGS_CHECKTYPES`` in their
``PyTypeObject`` structure to indicate that they support the new coercion model.
In such extension types, the numeric slot functions can no longer assume that
they'll be passed two arguments of the same type; instead they may be passed two
arguments of differing types, and can then perform their own internal coercion.
If the slot function is passed a type it can't handle, it can indicate the
failure by returning a reference to the ``Py_NotImplemented`` singleton value.
The numeric functions of the other type will then be tried, and perhaps they can
handle the operation; if the other type also returns ``Py_NotImplemented``, then
a :exc:`TypeError` will be raised.  Numeric methods written in Python can also
return ``Py_NotImplemented``, causing the interpreter to act as if the method
did not exist (perhaps raising a :exc:`TypeError`, perhaps trying another
object's numeric methods).


.. seealso::

   :pep:`208` - Reworking the Coercion Model
      Written and implemented by Neil Schemenauer, heavily based upon earlier work by
      Marc-André Lemburg.  Read this to understand the fine points of how numeric
      operations will now be processed at the C level.

.. ======================================================================


PEP 241: Metadata in Python Packages
====================================

A common complaint from Python users is that there's no single catalog of all
the Python modules in existence.  T. Middleton's Vaults of Parnassus at
http://www.vex.net/parnassus/ are the largest catalog of Python modules, but
registering software at the Vaults is optional, and many people don't bother.

As a first small step toward fixing the problem, Python software packaged using
the Distutils :command:`sdist` command will include a file named
:file:`PKG-INFO` containing information about the package such as its name,
version, and author (metadata, in cataloguing terminology).  PEP 241 contains
the full list of fields that can be present in the :file:`PKG-INFO` file.  As
people began to package their software using Python 2.1, more and more packages
will include metadata, making it possible to build automated cataloguing systems
and experiment with them.  With the result experience, perhaps it'll be possible
to design a really good catalog and then build support for it into Python 2.2.
For example, the Distutils :command:`sdist` and :command:`bdist_\*` commands
could support an ``upload`` option that would automatically upload your
package to a catalog server.

You can start creating packages containing :file:`PKG-INFO` even if you're not
using Python 2.1, since a new release of the Distutils will be made for users of
earlier Python versions.  Version 1.0.2 of the Distutils includes the changes
described in PEP 241, as well as various bugfixes and enhancements.  It will be
available from the Distutils SIG at https://www.python.org/community/sigs/current/distutils-sig/.


.. seealso::

   :pep:`241` - Metadata for Python Software Packages
      Written and implemented by A.M. Kuchling.

   :pep:`243` - Module Repository Upload Mechanism
      Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for
      uploading  Python packages to a central server.

.. ======================================================================


New and Improved Modules
========================

* Ka-Ping Yee contributed two new modules: :mod:`inspect.py`, a module for
  getting information about live Python code, and :mod:`pydoc.py`, a module for
  interactively converting docstrings to HTML or text.  As a bonus,
  :file:`Tools/scripts/pydoc`, which is now automatically installed, uses
  :mod:`pydoc.py` to display documentation given a Python module, package, or
  class name.  For example, ``pydoc xml.dom`` displays the following::

     Python Library Documentation: package xml.dom in xml

     NAME
         xml.dom - W3C Document Object Model implementation for Python.

     FILE
         /usr/local/lib/python2.1/xml/dom/__init__.pyc

     DESCRIPTION
         The Python mapping of the Document Object Model is documented in the
         Python Library Reference in the section on the xml.dom package.

         This package contains the following modules:
           ...

  :file:`pydoc` also includes a Tk-based interactive help browser.   :file:`pydoc`
  quickly becomes addictive; try it out!

* Two different modules for unit testing were added to the standard library.
  The :mod:`doctest` module, contributed by Tim Peters, provides a testing
  framework based on running embedded examples in docstrings and comparing the
  results against the expected output.  PyUnit, contributed by Steve Purcell, is a
  unit testing framework inspired by JUnit, which was in turn an adaptation of
  Kent Beck's Smalltalk testing framework.  See http://pyunit.sourceforge.net/ for
  more information about PyUnit.

* The :mod:`difflib` module contains a class, :class:`SequenceMatcher`, which
  compares two sequences and computes the changes required to transform one
  sequence into the other.  For example, this module can be used to write a tool
  similar to the Unix :program:`diff` program, and in fact the sample program
  :file:`Tools/scripts/ndiff.py` demonstrates how to write such a script.

* :mod:`curses.panel`, a wrapper for the panel library, part of ncurses and of
  SYSV curses, was contributed by Thomas Gellekum.  The panel library provides
  windows with the additional feature of depth. Windows can be moved higher or
  lower in the depth ordering, and the panel library figures out where panels
  overlap and which sections are visible.

* The PyXML package has gone through a few releases since Python 2.0, and Python
  2.1 includes an updated version of the :mod:`xml` package.  Some of the
  noteworthy changes include support for Expat 1.2 and later versions, the ability
  for Expat parsers to handle files in any encoding supported by Python, and
  various bugfixes for SAX, DOM, and the :mod:`minidom` module.

* Ping also contributed another hook for handling uncaught exceptions.
  :func:`sys.excepthook` can be set to a callable object.  When an exception isn't
  caught by any :keyword:`try`...\ :keyword:`except` blocks, the exception will be
  passed to :func:`sys.excepthook`, which can then do whatever it likes.  At the
  Ninth Python Conference, Ping demonstrated an application for this hook:
  printing an extended traceback that not only lists the stack frames, but also
  lists the function arguments and the local variables for each frame.

* Various functions in the :mod:`time` module, such as :func:`asctime` and
  :func:`localtime`, require a floating point argument containing the time in
  seconds since the epoch.  The most common use of these functions is to work with
  the current time, so the floating point argument has been made optional; when a
  value isn't provided, the current time will be used.  For example, log file
  entries usually need a string containing the current time; in Python 2.1,
  ``time.asctime()`` can be used, instead of the lengthier
  ``time.asctime(time.localtime(time.time()))`` that was previously required.

  This change was proposed and implemented by Thomas Wouters.

* The :mod:`ftplib` module now defaults to retrieving files in passive mode,
  because passive mode is more likely to work from behind a firewall.  This
  request came from the Debian bug tracking system, since other Debian packages
  use :mod:`ftplib` to retrieve files and then don't work from behind a firewall.
  It's deemed unlikely that this will cause problems for anyone, because Netscape
  defaults to passive mode and few people complain, but if passive mode is
  unsuitable for your application or network setup, call ``set_pasv(0)`` on
  FTP objects to disable passive mode.

* Support for raw socket access has been added to the :mod:`socket` module,
  contributed by Grant Edwards.

* The :mod:`pstats` module now contains a simple interactive statistics browser
  for displaying timing profiles for Python programs, invoked when the module is
  run as a script.  Contributed by  Eric S. Raymond.

* A new implementation-dependent function, ``sys._getframe([depth])``, has
  been added to return a given frame object from the current call stack.
  :func:`sys._getframe` returns the frame at the top of the call stack;  if the
  optional integer argument *depth* is supplied, the function returns the frame
  that is *depth* calls below the top of the stack.  For example,
  ``sys._getframe(1)`` returns the caller's frame object.

  This function is only present in CPython, not in Jython or the .NET
  implementation.  Use it for debugging, and resist the temptation to put it into
  production code.

.. ======================================================================


Other Changes and Fixes
=======================

There were relatively few smaller changes made in Python 2.1 due to the shorter
release cycle.  A search through the CVS change logs turns up 117 patches
applied, and 136 bugs fixed; both figures are likely to be underestimates.  Some
of the more notable changes are:

* A specialized object allocator is now optionally available, that should be
  faster than the system :func:`malloc` and have less memory overhead.  The
  allocator uses C's :func:`malloc` function to get large pools of memory, and
  then fulfills smaller memory requests from these pools.  It can be enabled by
  providing the :option:`!--with-pymalloc` option to the :program:`configure`
  script; see :file:`Objects/obmalloc.c` for the implementation details.

  Authors of C extension modules should test their code with the object allocator
  enabled, because some incorrect code may break, causing core dumps at runtime.
  There are a bunch of memory allocation functions in Python's C API that have
  previously been just aliases for the C library's :func:`malloc` and
  :func:`free`, meaning that if you accidentally called mismatched functions, the
  error wouldn't be noticeable.  When the object allocator is enabled, these
  functions aren't aliases of :func:`malloc` and :func:`free` any more, and
  calling the wrong function to free memory will get you a core dump.  For
  example, if memory was allocated using :func:`PyMem_New`, it has to be freed
  using :func:`PyMem_Del`, not :func:`free`.  A few modules included with Python
  fell afoul of this and had to be fixed; doubtless there are more third-party
  modules that will have the same problem.

  The object allocator was contributed by Vladimir Marangozov.

* The speed of line-oriented file I/O has been improved because people often
  complain about its lack of speed, and because it's often been used as a naïve
  benchmark.  The :meth:`readline` method of file objects has therefore been
  rewritten to be much faster.  The exact amount of the speedup will vary from
  platform to platform depending on how slow the C library's :func:`getc` was, but
  is around 66%, and potentially much faster on some particular operating systems.
  Tim Peters did much of the benchmarking and coding for this change, motivated by
  a discussion in comp.lang.python.

  A new module and method for file objects was also added, contributed by Jeff
  Epler. The new method, :meth:`xreadlines`, is similar to the existing
  :func:`xrange` built-in.  :func:`xreadlines` returns an opaque sequence object
  that only supports being iterated over, reading a line on every iteration but
  not reading the entire file into memory as the existing :meth:`readlines` method
  does. You'd use it like this::

     for line in sys.stdin.xreadlines():
         # ... do something for each line ...
         ...

  For a fuller discussion of the line I/O changes, see the python-dev summary for
  January 1--15, 2001 at https://mail.python.org/pipermail/python-dev/2001-January/.

* A new method, :meth:`popitem`, was added to dictionaries to enable
  destructively iterating through the contents of a dictionary; this can be faster
  for large dictionaries because there's no need to construct a list containing
  all the keys or values. ``D.popitem()`` removes a random ``(key, value)`` pair
  from the dictionary ``D`` and returns it as a 2-tuple.  This was implemented
  mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary
  patch by Moshe Zadka.

* Modules can now control which names are imported when ``from module import *``
  is used, by defining an ``__all__`` attribute containing a list of names that
  will be imported.  One common complaint is that if the module imports other
  modules such as :mod:`sys` or :mod:`string`, ``from module import *`` will add
  them to the importing module's namespace.  To fix this, simply list the public
  names in ``__all__``::

     # List public names
     __all__ = ['Database', 'open']

  A stricter version of this patch was first suggested and implemented by Ben
  Wolfson, but after some python-dev discussion, a weaker final version was
  checked in.

* Applying :func:`repr` to strings previously used octal escapes for
  non-printable characters; for example, a newline was ``'\012'``.  This was a
  vestigial trace of Python's C ancestry, but today octal is of very little
  practical use.  Ka-Ping Yee suggested using hex escapes instead of octal ones,
  and using the ``\n``, ``\t``, ``\r`` escapes for the appropriate characters,
  and implemented this new formatting.

* Syntax errors detected at compile-time can now raise exceptions containing the
  filename and line number of the error, a pleasant side effect of the compiler
  reorganization done by Jeremy Hylton.

* C extensions which import other modules have been changed to use
  :func:`PyImport_ImportModule`, which means that they will use any import hooks
  that have been installed.  This is also encouraged for third-party extensions
  that need to import some other module from C code.

* The size of the Unicode character database was shrunk by another 340K thanks
  to Fredrik Lundh.

* Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by
  Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7  (by Billy G.
  Allie).

And there's the usual list of minor bugfixes, minor memory leaks, docstring
edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for
the full details if you want them.

.. ======================================================================


Acknowledgements
================

The author would like to thank the following people for offering suggestions on
various drafts of this article: Graeme Cross, David Goodger, Jay Graves, Michael
Hudson, Marc-André Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.

PK
%�\�Ҫ:����"html/_sources/whatsnew/2.2.rst.txtnu�[���****************************
  What's New in Python 2.2
****************************

:Author: A.M. Kuchling

.. |release| replace:: 1.02

.. $Id: whatsnew22.tex 37315 2004-09-10 19:33:00Z akuchling $


Introduction
============

This article explains the new features in Python 2.2.2, released on October 14,
2002.  Python 2.2.2 is a bugfix release of Python 2.2, originally released on
December 21, 2001.

Python 2.2 can be thought of as the "cleanup release".  There are some features
such as generators and iterators that are completely new, but most of the
changes, significant and far-reaching though they may be, are aimed at cleaning
up irregularities and dark corners of the language design.

This article doesn't attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.2, such as the `Python Library
Reference <https://docs.python.org/2.2/lib/lib.html>`_ and the `Python
Reference Manual <https://docs.python.org/2.2/ref/ref.html>`_.  If you want to
understand the complete implementation and design rationale for a change, refer
to the PEP for a particular new feature.


.. see also, now defunct

   http://www.unixreview.com/documents/s=1356/urm0109h/0109h.htm
      "What's So Special About Python 2.2?" is also about the new 2.2 features, and
      was written by Cameron Laird and Kathryn Soraiz.

.. ======================================================================


PEPs 252 and 253: Type and Class Changes
========================================

The largest and most far-reaching changes in Python 2.2 are to Python's model of
objects and classes.  The changes should be backward compatible, so it's likely
that your code will continue to run unchanged, but the changes provide some
amazing new capabilities. Before beginning this, the longest and most
complicated section of this article, I'll provide an overview of the changes and
offer some comments.

A long time ago I wrote a Web page listing flaws in Python's design.  One of the
most significant flaws was that it's impossible to subclass Python types
implemented in C.  In particular, it's not possible to subclass built-in types,
so you can't just subclass, say, lists in order to add a single useful method to
them. The :mod:`UserList` module provides a class that supports all of the
methods of lists and that can be subclassed further, but there's lots of C code
that expects a regular Python list and won't accept a :class:`~UserList.UserList`
instance.

Python 2.2 fixes this, and in the process adds some exciting new capabilities.
A brief summary:

* You can subclass built-in types such as lists and even integers, and your
  subclasses should work in every place that requires the original type.

* It's now possible to define static and class methods, in addition to the
  instance methods available in previous versions of Python.

* It's also possible to automatically call methods on accessing or setting an
  instance attribute by using a new mechanism called :dfn:`properties`.  Many uses
  of :meth:`__getattr__` can be rewritten to use properties instead, making the
  resulting code simpler and faster.  As a small side benefit, attributes can now
  have docstrings, too.

* The list of legal attributes for an instance can be limited to a particular
  set using :dfn:`slots`, making it possible to safeguard against typos and
  perhaps make more optimizations possible in future versions of Python.

Some users have voiced concern about all these changes.  Sure, they say, the new
features are neat and lend themselves to all sorts of tricks that weren't
possible in previous versions of Python, but they also make the language more
complicated.  Some people have said that they've always recommended Python for
its simplicity, and feel that its simplicity is being lost.

Personally, I think there's no need to worry.  Many of the new features are
quite esoteric, and you can write a lot of Python code without ever needed to be
aware of them.  Writing a simple class is no more difficult than it ever was, so
you don't need to bother learning or teaching them unless they're actually
needed.  Some very complicated tasks that were previously only possible from C
will now be possible in pure Python, and to my mind that's all for the better.

I'm not going to attempt to cover every single corner case and small change that
were required to make the new features work.  Instead this section will paint
only the broad strokes.  See section :ref:`sect-rellinks`, "Related Links", for
further sources of information about Python 2.2's new object model.


Old and New Classes
-------------------

First, you should know that Python 2.2 really has two kinds of classes: classic
or old-style classes, and new-style classes.  The old-style class model is
exactly the same as the class model in earlier versions of Python.  All the new
features described in this section apply only to new-style classes. This
divergence isn't intended to last forever; eventually old-style classes will be
dropped, possibly in Python 3.0.

So how do you define a new-style class?  You do it by subclassing an existing
new-style class.  Most of Python's built-in types, such as integers, lists,
dictionaries, and even files, are new-style classes now.  A new-style class
named :class:`object`, the base class for all built-in types, has also been
added so if no built-in type is suitable, you can just subclass
:class:`object`::

   class C(object):
       def __init__ (self):
           ...
       ...

This means that :keyword:`class` statements that don't have any base classes are
always classic classes in Python 2.2.  (Actually you can also change this by
setting a module-level variable named :attr:`__metaclass__` --- see :pep:`253`
for the details --- but it's easier to just subclass :keyword:`object`.)

The type objects for the built-in types are available as built-ins, named using
a clever trick.  Python has always had built-in functions named :func:`int`,
:func:`float`, and :func:`str`.  In 2.2, they aren't functions any more, but
type objects that behave as factories when called. ::

   >>> int
   <type 'int'>
   >>> int('123')
   123

To make the set of types complete, new type objects such as :func:`dict` and
:func:`file` have been added.  Here's a more interesting example, adding a
:meth:`lock` method to file objects::

   class LockableFile(file):
       def lock (self, operation, length=0, start=0, whence=0):
           import fcntl
           return fcntl.lockf(self.fileno(), operation,
                              length, start, whence)

The now-obsolete :mod:`posixfile` module contained a class that emulated all of
a file object's methods and also added a :meth:`lock` method, but this class
couldn't be passed to internal functions that expected a built-in file,
something which is possible with our new :class:`LockableFile`.


Descriptors
-----------

In previous versions of Python, there was no consistent way to discover what
attributes and methods were supported by an object. There were some informal
conventions, such as defining :attr:`__members__` and :attr:`__methods__`
attributes that were lists of names, but often the author of an extension type
or a class wouldn't bother to define them.  You could fall back on inspecting
the :attr:`~object.__dict__` of an object, but when class inheritance or an arbitrary
:meth:`__getattr__` hook were in use this could still be inaccurate.

The one big idea underlying the new class model is that an API for describing
the attributes of an object using :dfn:`descriptors` has been formalized.
Descriptors specify the value of an attribute, stating whether it's a method or
a field.  With the descriptor API, static methods and class methods become
possible, as well as more exotic constructs.

Attribute descriptors are objects that live inside class objects, and have a few
attributes of their own:

* :attr:`~definition.__name__` is the attribute's name.

* :attr:`__doc__` is the attribute's docstring.

* ``__get__(object)`` is a method that retrieves the attribute value from
  *object*.

* ``__set__(object, value)`` sets the attribute on *object* to *value*.

* ``__delete__(object, value)`` deletes the *value*  attribute of *object*.

For example, when you write ``obj.x``, the steps that Python actually performs
are::

   descriptor = obj.__class__.x
   descriptor.__get__(obj)

For methods, :meth:`descriptor.__get__` returns a temporary object that's
callable, and wraps up the instance and the method to be called on it. This is
also why static methods and class methods are now possible; they have
descriptors that wrap up just the method, or the method and the class.  As a
brief explanation of these new kinds of methods, static methods aren't passed
the instance, and therefore resemble regular functions.  Class methods are
passed the class of the object, but not the object itself.  Static and class
methods are defined like this::

   class C(object):
       def f(arg1, arg2):
           ...
       f = staticmethod(f)

       def g(cls, arg1, arg2):
           ...
       g = classmethod(g)

The :func:`staticmethod` function takes the function :func:`f`, and returns it
wrapped up in a descriptor so it can be stored in the class object.  You might
expect there to be special syntax for creating such methods (``def static f``,
``defstatic f()``, or something like that) but no such syntax has been defined
yet; that's been left for future versions of Python.

More new features, such as slots and properties, are also implemented as new
kinds of descriptors, and it's not difficult to write a descriptor class that
does something novel.  For example, it would be possible to write a descriptor
class that made it possible to write Eiffel-style preconditions and
postconditions for a method.  A class that used this feature might be defined
like this::

   from eiffel import eiffelmethod

   class C(object):
       def f(self, arg1, arg2):
           # The actual function
           ...
       def pre_f(self):
           # Check preconditions
           ...
       def post_f(self):
           # Check postconditions
           ...

       f = eiffelmethod(f, pre_f, post_f)

Note that a person using the new :func:`eiffelmethod` doesn't have to understand
anything about descriptors.  This is why I think the new features don't increase
the basic complexity of the language. There will be a few wizards who need to
know about it in order to write :func:`eiffelmethod` or the ZODB or whatever,
but most users will just write code on top of the resulting libraries and ignore
the implementation details.


Multiple Inheritance: The Diamond Rule
--------------------------------------

Multiple inheritance has also been made more useful through changing the rules
under which names are resolved.  Consider this set of classes (diagram taken
from :pep:`253` by Guido van Rossum)::

         class A:
           ^ ^  def save(self): ...
          /   \
         /     \
        /       \
       /         \
   class B     class C:
       ^         ^  def save(self): ...
        \       /
         \     /
          \   /
           \ /
         class D

The lookup rule for classic classes is simple but not very smart; the base
classes are searched depth-first, going from left to right.  A reference to
:meth:`D.save` will search the classes :class:`D`, :class:`B`, and then
:class:`A`, where :meth:`save` would be found and returned.  :meth:`C.save`
would never be found at all.  This is bad, because if :class:`C`'s :meth:`save`
method is saving some internal state specific to :class:`C`, not calling it will
result in that state never getting saved.

New-style classes follow a different algorithm that's a bit more complicated to
explain, but does the right thing in this situation. (Note that Python 2.3
changes this algorithm to one that produces the same results in most cases, but
produces more useful results for really complicated inheritance graphs.)

#. List all the base classes, following the classic lookup rule and include a
   class multiple times if it's visited repeatedly.  In the above example, the list
   of visited classes is [:class:`D`, :class:`B`, :class:`A`, :class:`C`,
   :class:`A`].

#. Scan the list for duplicated classes.  If any are found, remove all but one
   occurrence, leaving the *last* one in the list.  In the above example, the list
   becomes [:class:`D`, :class:`B`, :class:`C`, :class:`A`] after dropping
   duplicates.

Following this rule, referring to :meth:`D.save` will return :meth:`C.save`,
which is the behaviour we're after.  This lookup rule is the same as the one
followed by Common Lisp.  A new built-in function, :func:`super`, provides a way
to get at a class's superclasses without having to reimplement Python's
algorithm. The most commonly used form will be  ``super(class, obj)``, which
returns  a bound superclass object (not the actual class object).  This form
will be used in methods to call a method in the superclass; for example,
:class:`D`'s :meth:`save` method would look like this::

   class D (B,C):
       def save (self):
           # Call superclass .save()
           super(D, self).save()
           # Save D's private information here
           ...

:func:`super` can also return unbound superclass objects when called as
``super(class)`` or ``super(class1, class2)``, but this probably won't
often be useful.


Attribute Access
----------------

A fair number of sophisticated Python classes define hooks for attribute access
using :meth:`__getattr__`; most commonly this is done for convenience, to make
code more readable by automatically mapping an attribute access such as
``obj.parent`` into a method call such as ``obj.get_parent``.  Python 2.2 adds
some new ways of controlling attribute access.

First, ``__getattr__(attr_name)`` is still supported by new-style classes,
and nothing about it has changed.  As before, it will be called when an attempt
is made to access ``obj.foo`` and no attribute named ``foo`` is found in the
instance's dictionary.

New-style classes also support a new method,
``__getattribute__(attr_name)``.  The difference between the two methods is
that :meth:`__getattribute__` is *always* called whenever any attribute is
accessed, while the old :meth:`__getattr__` is only called if ``foo`` isn't
found in the instance's dictionary.

However, Python 2.2's support for :dfn:`properties` will often be a simpler way
to trap attribute references.  Writing a :meth:`__getattr__` method is
complicated because to avoid recursion you can't use regular attribute accesses
inside them, and instead have to mess around with the contents of
:attr:`~object.__dict__`. :meth:`__getattr__` methods also end up being called by Python
when it checks for other methods such as :meth:`__repr__` or :meth:`__coerce__`,
and so have to be written with this in mind. Finally, calling a function on
every attribute access results in a sizable performance loss.

:class:`property` is a new built-in type that packages up three functions that
get, set, or delete an attribute, and a docstring.  For example, if you want to
define a :attr:`size` attribute that's computed, but also settable, you could
write::

   class C(object):
       def get_size (self):
           result = ... computation ...
           return result
       def set_size (self, size):
           ... compute something based on the size
           and set internal state appropriately ...

       # Define a property.  The 'delete this attribute'
       # method is defined as None, so the attribute
       # can't be deleted.
       size = property(get_size, set_size,
                       None,
                       "Storage size of this instance")

That is certainly clearer and easier to write than a pair of
:meth:`__getattr__`/:meth:`__setattr__` methods that check for the :attr:`size`
attribute and handle it specially while retrieving all other attributes from the
instance's :attr:`~object.__dict__`.  Accesses to :attr:`size` are also the only ones
which have to perform the work of calling a function, so references to other
attributes run at their usual speed.

Finally, it's possible to constrain the list of attributes that can be
referenced on an object using the new :attr:`~object.__slots__` class attribute. Python
objects are usually very dynamic; at any time it's possible to define a new
attribute on an instance by just doing ``obj.new_attr=1``.   A new-style class
can define a class attribute named :attr:`~object.__slots__` to limit the legal
attributes  to a particular set of names.  An example will make this clear::

   >>> class C(object):
   ...     __slots__ = ('template', 'name')
   ...
   >>> obj = C()
   >>> print obj.template
   None
   >>> obj.template = 'Test'
   >>> print obj.template
   Test
   >>> obj.newattr = None
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   AttributeError: 'C' object has no attribute 'newattr'

Note how you get an :exc:`AttributeError` on the attempt to assign to an
attribute not listed in :attr:`~object.__slots__`.


.. _sect-rellinks:

Related Links
-------------

This section has just been a quick overview of the new features, giving enough
of an explanation to start you programming, but many details have been
simplified or ignored.  Where should you go to get a more complete picture?

https://docs.python.org/dev/howto/descriptor.html is a lengthy tutorial introduction to
the descriptor features, written by Guido van Rossum. If my description has
whetted your appetite, go read this tutorial next, because it goes into much
more detail about the new features while still remaining quite easy to read.

Next, there are two relevant PEPs, :pep:`252` and :pep:`253`.  :pep:`252` is
titled "Making Types Look More Like Classes", and covers the descriptor API.
:pep:`253` is titled "Subtyping Built-in Types", and describes the changes to
type objects that make it possible to subtype built-in objects.  :pep:`253` is
the more complicated PEP of the two, and at a few points the necessary
explanations of types and meta-types may cause your head to explode.  Both PEPs
were written and implemented by Guido van Rossum, with substantial assistance
from the rest of the Zope Corp. team.

Finally, there's the ultimate authority: the source code.  Most of the machinery
for the type handling is in :file:`Objects/typeobject.c`, but you should only
resort to it after all other avenues have been exhausted, including posting a
question to python-list or python-dev.

.. ======================================================================


PEP 234: Iterators
==================

Another significant addition to 2.2 is an iteration interface at both the C and
Python levels.  Objects can define how they can be looped over by callers.

In Python versions up to 2.1, the usual way to make ``for item in obj`` work is
to define a :meth:`__getitem__` method that looks something like this::

   def __getitem__(self, index):
       return <next item>

:meth:`__getitem__` is more properly used to define an indexing operation on an
object so that you can write ``obj[5]`` to retrieve the sixth element.  It's a
bit misleading when you're using this only to support :keyword:`for` loops.
Consider some file-like object that wants to be looped over; the *index*
parameter is essentially meaningless, as the class probably assumes that a
series of :meth:`__getitem__` calls will be made with *index* incrementing by
one each time.  In other words, the presence of the :meth:`__getitem__` method
doesn't mean that using ``file[5]``  to randomly access the sixth element will
work, though it really should.

In Python 2.2, iteration can be implemented separately, and :meth:`__getitem__`
methods can be limited to classes that really do support random access.  The
basic idea of iterators is  simple.  A new built-in function, ``iter(obj)``
or ``iter(C, sentinel)``, is used to get an iterator. ``iter(obj)`` returns
an iterator for the object *obj*, while ``iter(C, sentinel)`` returns an
iterator that will invoke the callable object *C* until it returns *sentinel* to
signal that the iterator is done.

Python classes can define an :meth:`__iter__` method, which should create and
return a new iterator for the object; if the object is its own iterator, this
method can just return ``self``.  In particular, iterators will usually be their
own iterators.  Extension types implemented in C can implement a :c:member:`~PyTypeObject.tp_iter`
function in order to return an iterator, and extension types that want to behave
as iterators can define a :c:member:`~PyTypeObject.tp_iternext` function.

So, after all this, what do iterators actually do?  They have one required
method, :meth:`next`, which takes no arguments and returns the next value.  When
there are no more values to be returned, calling :meth:`next` should raise the
:exc:`StopIteration` exception. ::

   >>> L = [1,2,3]
   >>> i = iter(L)
   >>> print i
   <iterator object at 0x8116870>
   >>> i.next()
   1
   >>> i.next()
   2
   >>> i.next()
   3
   >>> i.next()
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   StopIteration
   >>>

In 2.2, Python's :keyword:`for` statement no longer expects a sequence; it
expects something for which :func:`iter` will return an iterator. For backward
compatibility and convenience, an iterator is automatically constructed for
sequences that don't implement :meth:`__iter__` or a :c:member:`~PyTypeObject.tp_iter` slot, so
``for i in [1,2,3]`` will still work.  Wherever the Python interpreter loops
over a sequence, it's been changed to use the iterator protocol.  This means you
can do things like this::

   >>> L = [1,2,3]
   >>> i = iter(L)
   >>> a,b,c = i
   >>> a,b,c
   (1, 2, 3)

Iterator support has been added to some of Python's basic types.   Calling
:func:`iter` on a dictionary will return an iterator which loops over its keys::

   >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
   ...      'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
   >>> for key in m: print key, m[key]
   ...
   Mar 3
   Feb 2
   Aug 8
   Sep 9
   May 5
   Jun 6
   Jul 7
   Jan 1
   Apr 4
   Nov 11
   Dec 12
   Oct 10

That's just the default behaviour.  If you want to iterate over keys, values, or
key/value pairs, you can explicitly call the :meth:`iterkeys`,
:meth:`itervalues`, or :meth:`iteritems` methods to get an appropriate iterator.
In a minor related change, the :keyword:`in` operator now works on dictionaries,
so ``key in dict`` is now equivalent to ``dict.has_key(key)``.

Files also provide an iterator, which calls the :meth:`readline` method until
there are no more lines in the file.  This means you can now read each line of a
file using code like this::

   for line in file:
       # do something for each line
       ...

Note that you can only go forward in an iterator; there's no way to get the
previous element, reset the iterator, or make a copy of it. An iterator object
could provide such additional capabilities, but the iterator protocol only
requires a :meth:`next` method.


.. seealso::

   :pep:`234` - Iterators
      Written by Ka-Ping Yee and GvR; implemented  by the Python Labs crew, mostly by
      GvR and Tim Peters.

.. ======================================================================


PEP 255: Simple Generators
==========================

Generators are another new feature, one that interacts with the introduction of
iterators.

You're doubtless familiar with how function calls work in Python or C.  When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a :keyword:`return` statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren't thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.

Here's the simplest example of a generator function::

   def generate_ints(N):
       for i in range(N):
           yield i

A new keyword, :keyword:`yield`, was introduced for generators.  Any function
containing a :keyword:`yield` statement is a generator function; this is
detected by Python's bytecode compiler which compiles the function specially as
a result.  Because a new keyword was introduced, generators must be explicitly
enabled in a module by including a ``from __future__ import generators``
statement near the top of the module's source code.  In Python 2.3 this
statement will become unnecessary.

When you call a generator function, it doesn't return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the :keyword:`yield` statement, the generator outputs the value of ``i``,
similar to a :keyword:`return` statement.  The big difference between
:keyword:`yield` and a :keyword:`return` statement is that on reaching a
:keyword:`yield` the generator's state of execution is suspended and local
variables are preserved.  On the next call to the generator's ``next()`` method,
the function will resume executing immediately after the :keyword:`yield`
statement.  (For complicated reasons, the :keyword:`yield` statement isn't
allowed inside the :keyword:`try` block of a :keyword:`try`...\
:keyword:`finally` statement; read :pep:`255` for a full explanation of the
interaction between :keyword:`yield` and exceptions.)

Here's a sample usage of the :func:`generate_ints` generator::

   >>> gen = generate_ints(3)
   >>> gen
   <generator object at 0x8117f90>
   >>> gen.next()
   0
   >>> gen.next()
   1
   >>> gen.next()
   2
   >>> gen.next()
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
     File "<stdin>", line 2, in generate_ints
   StopIteration

You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
generate_ints(3)``.

Inside a generator function, the :keyword:`return` statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. :keyword:`return` with a value, such
as ``return 5``, is a syntax error inside a generator function.  The end of the
generator's results can also be indicated by raising :exc:`StopIteration`
manually, or by just letting the flow of execution fall off the bottom of the
function.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting ``self.count`` to
0, and having the :meth:`next` method increment ``self.count`` and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. :file:`Lib/test/test_generators.py` contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively. ::

   # A recursive generator that generates Tree leaves in in-order.
   def inorder(t):
       if t:
           for x in inorder(t.left):
               yield x
           yield t.label
           for x in inorder(t.right):
               yield x

Two other examples in :file:`Lib/test/test_generators.py` produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight's Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon
(https://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from "An Overview of the Icon Programming Language" at
https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
like::

   sentence := "Store it in the neighboring harbor"
   if (i := find("or", sentence)) > 5 then write(i)

In Icon the :func:`find` function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the :keyword:`if` statement, ``i`` is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.

Python doesn't go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered a new part of the core Python language, but
learning or using them isn't compulsory; if they don't solve any problems that
you have, feel free to ignore them. One novel feature of Python's interface as
compared to Icon's is that a generator's state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.


.. seealso::

   :pep:`255` - Simple Generators
      Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
      by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.

.. ======================================================================


PEP 237: Unifying Long Integers and Integers
============================================

In recent versions, the distinction between regular integers, which are 32-bit
values on most machines, and long integers, which can be of arbitrary size, was
becoming an annoyance.  For example, on platforms that support files larger than
``2**32`` bytes, the :meth:`tell` method of file objects has to return a long
integer. However, there were various bits of Python that expected plain integers
and would raise an error if a long integer was provided instead.  For example,
in Python 1.5, only regular integers could be used as a slice index, and
``'abc'[1L:]`` would raise a :exc:`TypeError` exception with the message 'slice
index must be int'.

Python 2.2 will shift values from short to long integers as required. The 'L'
suffix is no longer needed to indicate a long integer literal, as now the
compiler will choose the appropriate type.  (Using the 'L' suffix will be
discouraged in future 2.x versions of Python, triggering a warning in Python
2.4, and probably dropped in Python 3.0.)  Many operations that used to raise an
:exc:`OverflowError` will now return a long integer as their result.  For
example::

   >>> 1234567890123
   1234567890123L
   >>> 2 ** 64
   18446744073709551616L

In most cases, integers and long integers will now be treated identically.  You
can still distinguish them with the :func:`type` built-in function, but that's
rarely needed.


.. seealso::

   :pep:`237` - Unifying Long Integers and Integers
      Written by Moshe Zadka and Guido van Rossum.  Implemented mostly by Guido van
      Rossum.

.. ======================================================================


PEP 238: Changing the Division Operator
=======================================

The most controversial change in Python 2.2 heralds the start of an effort to
fix an old design flaw that's been in Python from the beginning. Currently
Python's division operator, ``/``, behaves like C's division operator when
presented with two integer arguments: it returns an integer result that's
truncated down when there would be a fractional part.  For example, ``3/2`` is
1, not 1.5, and ``(-1)/2`` is -1, not -0.5.  This means that the results of
division can vary unexpectedly depending on the type of the two operands and
because Python is dynamically typed, it can be difficult to determine the
possible types of the operands.

(The controversy is over whether this is *really* a design flaw, and whether
it's worth breaking existing code to fix this.  It's caused endless discussions
on python-dev, and in July 2001 erupted into a storm of acidly sarcastic
postings on :newsgroup:`comp.lang.python`. I won't argue for either side here
and will stick to describing what's  implemented in 2.2.  Read :pep:`238` for a
summary of arguments and counter-arguments.)

Because this change might break code, it's being introduced very gradually.
Python 2.2 begins the transition, but the switch won't be complete until Python
3.0.

First, I'll borrow some terminology from :pep:`238`.  "True division" is the
division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is 0.25,
and so forth.  "Floor division" is what Python's ``/`` operator currently does
when given integer operands; the result is the floor of the value returned by
true division.  "Classic division" is the current mixed behaviour of ``/``; it
returns the result of floor division when the operands are integers, and returns
the result of true division when one of the operands is a floating-point number.

Here are the changes 2.2 introduces:

* A new operator, ``//``, is the floor division operator. (Yes, we know it looks
  like C++'s comment symbol.)  ``//`` *always* performs floor division no matter
  what the types of its operands are, so ``1 // 2`` is 0 and ``1.0 // 2.0`` is
  also 0.0.

  ``//`` is always available in Python 2.2; you don't need to enable it using a
  ``__future__`` statement.

* By including a ``from __future__ import division`` in a module, the ``/``
  operator will be changed to return the result of true division, so ``1/2`` is
  0.5.  Without the ``__future__`` statement, ``/`` still means classic division.
  The default meaning of ``/`` will not change until Python 3.0.

* Classes can define methods called :meth:`__truediv__` and :meth:`__floordiv__`
  to overload the two division operators.  At the C level, there are also slots in
  the :c:type:`PyNumberMethods` structure so extension types can define the two
  operators.

* Python 2.2 supports some command-line arguments for testing whether code will
  work with the changed division semantics.  Running python with :option:`-Q
  warn <-Q>` will cause a warning to be issued whenever division is applied to two
  integers.  You can use this to find code that's affected by the change and fix
  it.  By default, Python 2.2 will simply perform classic division without a
  warning; the warning will be turned on by default in Python 2.3.


.. seealso::

   :pep:`238` - Changing the Division Operator
      Written by Moshe Zadka and  Guido van Rossum.  Implemented by Guido van Rossum..

.. ======================================================================


Unicode Changes
===============

Python's Unicode support has been enhanced a bit in 2.2.  Unicode strings are
usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be
compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by
supplying :option:`!--enable-unicode=ucs4` to the configure script.   (It's also
possible to specify :option:`!--disable-unicode` to completely disable Unicode
support.)

When built to use UCS-4 (a "wide Python"), the interpreter can natively handle
Unicode characters from U+000000 to U+110000, so the range of legal values for
the :func:`unichr` function is expanded accordingly.  Using an interpreter
compiled to use UCS-2 (a "narrow Python"), values greater than 65535 will still
cause :func:`unichr` to raise a :exc:`ValueError` exception. This is all
described in :pep:`261`, "Support for 'wide' Unicode characters"; consult it for
further details.

Another change is simpler to explain. Since their introduction, Unicode strings
have supported an :meth:`encode` method to convert the string to a selected
encoding such as UTF-8 or Latin-1.  A symmetric ``decode([*encoding*])``
method has been added to 8-bit strings (though not to Unicode strings) in 2.2.
:meth:`decode` assumes that the string is in the specified encoding and decodes
it, returning whatever is returned by the codec.

Using this new feature, codecs have been added for tasks not directly related to
Unicode.  For example, codecs have been added for uu-encoding, MIME's base64
encoding, and compression with the :mod:`zlib` module::

   >>> s = """Here is a lengthy piece of redundant, overly verbose,
   ... and repetitive text.
   ... """
   >>> data = s.encode('zlib')
   >>> data
   'x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...'
   >>> data.decode('zlib')
   'Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n'
   >>> print s.encode('uu')
   begin 666 <data>
   M2&5R92!I<R!A(&QE;F=T:'D@<&EE8V4@;V8@<F5D=6YD86YT+"!O=F5R;'D@
   >=F5R8F]S92P*86YD(')E<&5T:71I=F4@=&5X="X*

   end
   >>> "sheesh".encode('rot-13')
   'furrfu'

To convert a class instance to Unicode, a :meth:`__unicode__` method can be
defined by a class, analogous to :meth:`__str__`.

:meth:`encode`, :meth:`decode`, and :meth:`__unicode__` were implemented by
Marc-André Lemburg.  The changes to support using UCS-4 internally were
implemented by Fredrik Lundh and Martin von Löwis.


.. seealso::

   :pep:`261` - Support for 'wide' Unicode characters
      Written by Paul Prescod.

.. ======================================================================


PEP 227: Nested Scopes
======================

In Python 2.1, statically nested scopes were added as an optional feature, to be
enabled by a ``from __future__ import nested_scopes`` directive.  In 2.2 nested
scopes no longer need to be specially enabled, and are now always present.  The
rest of this section is a copy of the description of nested scopes from my
"What's New in Python 2.1" document; if you read it when 2.1 came out, you can
skip the rest of this section.

The largest change introduced in Python 2.1, and made complete in 2.2, is to
Python's scoping rules.  In Python 2.0, at any given time there are at most
three namespaces used to look up variable names: local, module-level, and the
built-in namespace.  This often surprised people because it didn't match their
intuitive expectations.  For example, a nested recursive function definition
doesn't work::

   def f():
       ...
       def g(value):
           ...
           return g(value-1) + 1
       ...

The function :func:`g` will always raise a :exc:`NameError` exception, because
the binding of the name ``g`` isn't in either its local namespace or in the
module-level namespace.  This isn't much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the :keyword:`lambda` statement clumsier, and this was a problem in practice.
In code which uses :keyword:`lambda` you can often find local variables being
copied by passing them as the default values of arguments. ::

   def find(self, name):
       "Return list of any entries equal to 'name'"
       L = filter(lambda x, name=name: x == name,
                  self.list_attribute)
       return L

The readability of Python code written in a strongly functional style suffers
greatly as a result.

The most significant change to Python 2.2 is that static scoping has been added
to the language to fix this problem.  As a first effect, the ``name=name``
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the :keyword:`def`, :keyword:`class`, or :keyword:`import` statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.

This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.

One side effect of the change is that the ``from module import *`` and
:keyword:`exec` statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that ``from
module import *`` is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  ``from
module import *`` and :keyword:`exec` make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or :keyword:`lambda` expressions with free variables, the compiler
will flag this by raising a :exc:`SyntaxError` exception.

To make the preceding explanation a bit clearer, here's an example::

   x = 1
   def f():
       # The next line is a syntax error
       exec 'x=2'
       def g():
           return x

Line 4 containing the :keyword:`exec` statement is a syntax error, since
:keyword:`exec` would define a new local variable named ``x`` whose value should
be accessed by :func:`g`.

This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
most Python code (and when it is used, it's often a sign of a poor design
anyway).


.. seealso::

   :pep:`227` - Statically Nested Scopes
      Written and implemented by Jeremy Hylton.

.. ======================================================================


New and Improved Modules
========================

* The :mod:`xmlrpclib` module was contributed to the standard library by Fredrik
  Lundh, providing support for writing XML-RPC clients.  XML-RPC is a simple
  remote procedure call protocol built on top of HTTP and XML. For example, the
  following snippet retrieves a list of RSS channels from the O'Reilly Network,
  and then  lists the recent headlines for one channel::

     import xmlrpclib
     s = xmlrpclib.Server(
           'http://www.oreillynet.com/meerkat/xml-rpc/server.php')
     channels = s.meerkat.getChannels()
     # channels is a list of dictionaries, like this:
     # [{'id': 4, 'title': 'Freshmeat Daily News'}
     #  {'id': 190, 'title': '32Bits Online'},
     #  {'id': 4549, 'title': '3DGamers'}, ... ]

     # Get the items for one channel
     items = s.meerkat.getItems( {'channel': 4} )

     # 'items' is another list of dictionaries, like this:
     # [{'link': 'http://freshmeat.net/releases/52719/',
     #   'description': 'A utility which converts HTML to XSL FO.',
     #   'title': 'html2fo 0.3 (Default)'}, ... ]

  The :mod:`SimpleXMLRPCServer` module makes it easy to create straightforward
  XML-RPC servers.  See http://www.xmlrpc.com/ for more information about XML-RPC.

* The new :mod:`hmac` module implements the HMAC algorithm described by
  :rfc:`2104`. (Contributed by Gerhard Häring.)

* Several functions that originally returned lengthy tuples now return
  pseudo-sequences that still behave like tuples but also have mnemonic attributes such
  as memberst_mtime or :attr:`tm_year`. The enhanced functions include
  :func:`stat`, :func:`fstat`, :func:`statvfs`, and :func:`fstatvfs` in the
  :mod:`os` module, and :func:`localtime`, :func:`gmtime`, and :func:`strptime` in
  the :mod:`time` module.

  For example, to obtain a file's size using the old tuples, you'd end up writing
  something like ``file_size = os.stat(filename)[stat.ST_SIZE]``, but now this can
  be written more clearly as ``file_size = os.stat(filename).st_size``.

  The original patch for this feature was contributed by Nick Mathewson.

* The Python profiler has been extensively reworked and various errors in its
  output have been corrected.  (Contributed by Fred L. Drake, Jr. and Tim Peters.)

* The :mod:`socket` module can be compiled to support IPv6; specify the
  :option:`!--enable-ipv6` option to Python's configure script.  (Contributed by
  Jun-ichiro "itojun" Hagino.)

* Two new format characters were added to the :mod:`struct` module for 64-bit
  integers on platforms that support the C :c:type:`long long` type.  ``q`` is for
  a signed 64-bit integer, and ``Q`` is for an unsigned one.  The value is
  returned in Python's long integer type.  (Contributed by Tim Peters.)

* In the interpreter's interactive mode, there's a new built-in function
  :func:`help` that uses the :mod:`pydoc` module introduced in Python 2.1 to
  provide interactive help. ``help(object)`` displays any available help text
  about *object*.  :func:`help` with no argument puts you in an online help
  utility, where you can enter the names of functions, classes, or modules to read
  their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee's
  :mod:`pydoc` module.)

* Various bugfixes and performance improvements have been made to the SRE engine
  underlying the :mod:`re` module.  For example, the :func:`re.sub` and
  :func:`re.split` functions have been rewritten in C.  Another contributed patch
  speeds up certain Unicode character ranges by a factor of two, and a new
  :meth:`finditer`  method that returns an iterator over all the non-overlapping
  matches in  a given string.  (SRE is maintained by Fredrik Lundh.  The
  BIGCHARSET patch was contributed by Martin von Löwis.)

* The :mod:`smtplib` module now supports :rfc:`2487`, "Secure SMTP over TLS", so
  it's now possible to encrypt the SMTP traffic between a Python program and the
  mail transport agent being handed a message.  :mod:`smtplib` also supports SMTP
  authentication.  (Contributed by Gerhard Häring.)

* The :mod:`imaplib` module, maintained by Piers Lauder, has support for several
  new extensions: the NAMESPACE extension defined in :rfc:`2342`, SORT, GETACL and
  SETACL.  (Contributed by Anthony Baxter and Michel Pelletier.)

* The :mod:`rfc822` module's parsing of email addresses is now compliant with
  :rfc:`2822`, an update to :rfc:`822`.  (The module's name is *not* going to be
  changed to ``rfc2822``.)  A new package, :mod:`email`, has also been added for
  parsing and generating e-mail messages.  (Contributed by Barry Warsaw, and
  arising out of his work on Mailman.)

* The :mod:`difflib` module now contains a new :class:`Differ` class for
  producing human-readable lists of changes (a "delta") between two sequences of
  lines of text.  There are also two generator functions, :func:`ndiff` and
  :func:`restore`, which respectively return a delta from two sequences, or one of
  the original sequences from a delta. (Grunt work contributed by David Goodger,
  from ndiff.py code by Tim Peters who then did the generatorization.)

* New constants :const:`ascii_letters`, :const:`ascii_lowercase`, and
  :const:`ascii_uppercase` were added to the :mod:`string` module.  There were
  several modules in the standard library that used :const:`string.letters` to
  mean the ranges A-Za-z, but that assumption is incorrect when locales are in
  use, because :const:`string.letters` varies depending on the set of legal
  characters defined by the current locale.  The buggy modules have all been fixed
  to use :const:`ascii_letters` instead. (Reported by an unknown person; fixed by
  Fred L. Drake, Jr.)

* The :mod:`mimetypes` module now makes it easier to use alternative MIME-type
  databases by the addition of a :class:`MimeTypes` class, which takes a list of
  filenames to be parsed.  (Contributed by Fred L. Drake, Jr.)

* A :class:`Timer` class was added to the :mod:`threading` module that allows
  scheduling an activity to happen at some future time.  (Contributed by Itamar
  Shtull-Trauring.)

.. ======================================================================


Interpreter Changes and Fixes
=============================

Some of the changes only affect people who deal with the Python interpreter at
the C level because they're writing Python extension modules, embedding the
interpreter, or just hacking on the interpreter itself. If you only write Python
code, none of the changes described here will affect you very much.

* Profiling and tracing functions can now be implemented in C, which can operate
  at much higher speeds than Python-based functions and should reduce the overhead
  of profiling and tracing.  This  will be of interest to authors of development
  environments for Python.  Two new C functions were added to Python's API,
  :c:func:`PyEval_SetProfile` and :c:func:`PyEval_SetTrace`. The existing
  :func:`sys.setprofile` and :func:`sys.settrace` functions still exist, and have
  simply been changed to use the new C-level interface.  (Contributed by Fred L.
  Drake, Jr.)

* Another low-level API, primarily of interest to implementors of Python
  debuggers and development tools, was added. :c:func:`PyInterpreterState_Head` and
  :c:func:`PyInterpreterState_Next` let a caller walk through all the existing
  interpreter objects; :c:func:`PyInterpreterState_ThreadHead` and
  :c:func:`PyThreadState_Next` allow looping over all the thread states for a given
  interpreter.  (Contributed by David Beazley.)

* The C-level interface to the garbage collector has been changed to make it
  easier to write extension types that support garbage collection and to debug
  misuses of the functions. Various functions have slightly different semantics,
  so a bunch of functions had to be renamed.  Extensions that use the old API will
  still compile but will *not* participate in garbage collection, so updating them
  for 2.2 should be considered fairly high priority.

  To upgrade an extension module to the new API, perform the following steps:

* Rename :c:func:`Py_TPFLAGS_GC` to :c:func:`PyTPFLAGS_HAVE_GC`.

* Use :c:func:`PyObject_GC_New` or :c:func:`PyObject_GC_NewVar` to allocate
    objects, and :c:func:`PyObject_GC_Del` to deallocate them.

* Rename :c:func:`PyObject_GC_Init` to :c:func:`PyObject_GC_Track` and
    :c:func:`PyObject_GC_Fini` to :c:func:`PyObject_GC_UnTrack`.

* Remove :c:func:`PyGC_HEAD_SIZE` from object size calculations.

* Remove calls to :c:func:`PyObject_AS_GC` and :c:func:`PyObject_FROM_GC`.

* A new ``et`` format sequence was added to :c:func:`PyArg_ParseTuple`; ``et``
  takes both a parameter and an encoding name, and converts the parameter to the
  given encoding if the parameter turns out to be a Unicode string, or leaves it
  alone if it's an 8-bit string, assuming it to already be in the desired
  encoding.  This differs from the ``es`` format character, which assumes that
  8-bit strings are in Python's default ASCII encoding and converts them to the
  specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS
  support on Windows described in the following section.)

* A different argument parsing function, :c:func:`PyArg_UnpackTuple`, has been
  added that's simpler and presumably faster.  Instead of specifying a format
  string, the caller simply gives the minimum and maximum number of arguments
  expected, and a set of pointers to :c:type:`PyObject\*` variables that will be
  filled in with argument values.

* Two new flags :const:`METH_NOARGS` and :const:`METH_O` are available in method
  definition tables to simplify implementation of methods with no arguments or a
  single untyped argument. Calling such methods is more efficient than calling a
  corresponding method that uses :const:`METH_VARARGS`.  Also, the old
  :const:`METH_OLDARGS` style of writing C methods is  now officially deprecated.

* Two new wrapper functions, :c:func:`PyOS_snprintf` and :c:func:`PyOS_vsnprintf`
  were added to provide  cross-platform implementations for the relatively new
  :c:func:`snprintf` and :c:func:`vsnprintf` C lib APIs. In contrast to the standard
  :c:func:`sprintf` and :c:func:`vsprintf` functions, the Python versions check the
  bounds of the buffer used to protect against buffer overruns. (Contributed by
  M.-A. Lemburg.)

* The :c:func:`_PyTuple_Resize` function has lost an unused parameter, so now it
  takes 2 parameters instead of 3.  The third argument was never used, and can
  simply be discarded when porting code from earlier versions to Python 2.2.

.. ======================================================================


Other Changes and Fixes
=======================

As usual there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1
applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches and fixed 82
bugs.  These figures are likely to be underestimates.

Some of the more notable changes are:

* The code for the MacOS port for Python, maintained by Jack Jansen, is now kept
  in the main Python CVS tree, and many changes have been made to support MacOS X.

  The most significant change is the ability to build Python as a framework,
  enabled by supplying the :option:`!--enable-framework` option to the configure
  script when compiling Python.  According to Jack Jansen, "This installs a
  self-contained Python installation plus the OS X framework "glue" into
  :file:`/Library/Frameworks/Python.framework` (or another location of choice).
  For now there is little immediate added benefit to this (actually, there is the
  disadvantage that you have to change your PATH to be able to find Python), but
  it is the basis for creating a full-blown Python application, porting the
  MacPython IDE, possibly using Python as a standard OSA scripting language and
  much more."

  Most of the MacPython toolbox modules, which interface to MacOS APIs such as
  windowing, QuickTime, scripting, etc. have been ported to OS X, but they've been
  left commented out in :file:`setup.py`.  People who want to experiment with
  these modules can uncomment them manually.

  .. Jack's original comments:
     The main change is the possibility to build Python as a
     framework. This installs a self-contained Python installation plus the
     OSX framework "glue" into /Library/Frameworks/Python.framework (or
     another location of choice). For now there is little immediate added
     benefit to this (actually, there is the disadvantage that you have to
     change your PATH to be able to find Python), but it is the basis for
     creating a fullblown Python application, porting the MacPython IDE,
     possibly using Python as a standard OSA scripting language and much
     more. You enable this with "configure --enable-framework".
     The other change is that most MacPython toolbox modules, which
     interface to all the MacOS APIs such as windowing, quicktime,
     scripting, etc. have been ported. Again, most of these are not of
     immediate use, as they need a full application to be really useful, so
     they have been commented out in setup.py. People wanting to experiment
     can uncomment them. Gestalt and Internet Config modules are enabled by
     default.

* Keyword arguments passed to built-in functions that don't take them now cause a
  :exc:`TypeError` exception to be raised, with the message "*function* takes no
  keyword arguments".

* Weak references, added in Python 2.1 as an extension module, are now part of
  the core because they're used in the implementation of new-style classes.  The
  :exc:`ReferenceError` exception has therefore moved from the :mod:`weakref`
  module to become a built-in exception.

* A new script, :file:`Tools/scripts/cleanfuture.py` by Tim Peters,
  automatically removes obsolete ``__future__`` statements from Python source
  code.

* An additional *flags* argument has been added to the built-in function
  :func:`compile`, so the behaviour of ``__future__`` statements can now be
  correctly observed in simulated shells, such as those presented by IDLE and
  other development environments.  This is described in :pep:`264`. (Contributed
  by Michael Hudson.)

* The new license introduced with Python 1.6 wasn't GPL-compatible.  This is
  fixed by some minor textual changes to the 2.2 license, so it's now legal to
  embed Python inside a GPLed program again.  Note that Python itself is not
  GPLed, but instead is under a license that's essentially equivalent to the BSD
  license, same as it always was.  The license changes were also applied to the
  Python 2.0.1 and 2.1.1 releases.

* When presented with a Unicode filename on Windows, Python will now convert it
  to an MBCS encoded string, as used by the Microsoft file APIs.  As MBCS is
  explicitly used by the file APIs, Python's choice of ASCII as the default
  encoding turns out to be an annoyance.  On Unix, the locale's character set is
  used if ``locale.nl_langinfo(CODESET)`` is available.  (Windows support was
  contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix
  support was added by Martin von Löwis.)

* Large file support is now enabled on Windows.  (Contributed by Tim Peters.)

* The :file:`Tools/scripts/ftpmirror.py` script now parses a :file:`.netrc`
  file, if you have one. (Contributed by Mike Romberg.)

* Some features of the object returned by the :func:`xrange` function are now
  deprecated, and trigger warnings when they're accessed; they'll disappear in
  Python 2.3. :class:`xrange` objects tried to pretend they were full sequence
  types by supporting slicing, sequence multiplication, and the :keyword:`in`
  operator, but these features were rarely used and therefore buggy.  The
  :meth:`tolist` method and the :attr:`start`, :attr:`stop`, and :attr:`step`
  attributes are also being deprecated.  At the C level, the fourth argument to
  the :c:func:`PyRange_New` function, ``repeat``, has also been deprecated.

* There were a bunch of patches to the dictionary implementation, mostly to fix
  potential core dumps if a dictionary contains objects that sneakily changed
  their hash value, or mutated the dictionary they were contained in. For a while
  python-dev fell into a gentle rhythm of Michael Hudson finding a case that
  dumped core, Tim Peters fixing the bug, Michael finding another case, and round
  and round it went.

* On Windows, Python can now be compiled with Borland C thanks to a number of
  patches contributed by Stephen Hansen, though the result isn't fully functional
  yet.  (But this *is* progress...)

* Another Windows enhancement: Wise Solutions generously offered PythonLabs use
  of their InstallerMaster 8.1 system.  Earlier PythonLabs Windows installers used
  Wise 5.0a, which was beginning to show its age.  (Packaged up by Tim Peters.)

* Files ending in ``.pyw`` can now be imported on Windows. ``.pyw`` is a
  Windows-only thing, used to indicate that a script needs to be run using
  PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS console from popping
  up to display the output.  This patch makes it possible to import such scripts,
  in case they're also usable as modules.  (Implemented by David Bolen.)

* On platforms where Python uses the C :c:func:`dlopen` function  to load
  extension modules, it's now possible to set the flags used  by :c:func:`dlopen`
  using the :func:`sys.getdlopenflags` and :func:`sys.setdlopenflags` functions.
  (Contributed by Bram Stolk.)

* The :func:`pow` built-in function no longer supports 3 arguments when
  floating-point numbers are supplied. ``pow(x, y, z)`` returns ``(x**y) % z``,
  but this is never useful for floating point numbers, and the final result varies
  unpredictably depending on the platform.  A call such as ``pow(2.0, 8.0, 7.0)``
  will now raise a :exc:`TypeError` exception.

.. ======================================================================


Acknowledgements
================

The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Fred Bremmer,
Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger,
Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen, Marc-André Lemburg,
Martin von Löwis, Fredrik Lundh, Michael McLay, Nick Mathewson, Paul Moore,
Gustavo Niemeyer, Don O'Donnell, Joonas Paalasma, Tim Peters, Jens Quade, Tom
Reinhardt, Neil Schemenauer, Guido van Rossum, Greg Ward, Edward Welbourne.

PK
%�\���?^?^"html/_sources/whatsnew/2.3.rst.txtnu�[���****************************
  What's New in Python 2.3
****************************

:Author: A.M. Kuchling

.. |release| replace:: 1.01

.. $Id: whatsnew23.tex 54631 2007-03-31 11:58:36Z georg.brandl $

This article explains the new features in Python 2.3.  Python 2.3 was released
on July 29, 2003.

The main themes for Python 2.3 are polishing some of the features added in 2.2,
adding various small but useful enhancements to the core language, and expanding
the standard library.  The new object model introduced in the previous version
has benefited from 18 months of bugfixes and from optimization efforts that have
improved the performance of new-style classes.  A few new built-in functions
have been added such as :func:`sum` and :func:`enumerate`.  The :keyword:`in`
operator can now be used for substring searches (e.g. ``"ab" in "abc"`` returns
:const:`True`).

Some of the many new library features include Boolean, set, heap, and date/time
data types, the ability to import modules from ZIP-format archives, metadata
support for the long-awaited Python catalog, an updated version of IDLE, and
modules for logging messages, wrapping text, parsing CSV files, processing
command-line options, using BerkeleyDB databases...  the list of new and
enhanced modules is lengthy.

This article doesn't attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.3, such as the Python Library
Reference and the Python Reference Manual.  If you want to understand the
complete implementation and design rationale, refer to the PEP for a particular
new feature.

.. ======================================================================


PEP 218: A Standard Set Datatype
================================

The new :mod:`sets` module contains an implementation of a set datatype.  The
:class:`Set` class is for mutable sets, sets that can have members added and
removed.  The :class:`ImmutableSet` class is for sets that can't be modified,
and instances of :class:`ImmutableSet` can therefore be used as dictionary keys.
Sets are built on top of dictionaries, so the elements within a set must be
hashable.

Here's a simple example::

   >>> import sets
   >>> S = sets.Set([1,2,3])
   >>> S
   Set([1, 2, 3])
   >>> 1 in S
   True
   >>> 0 in S
   False
   >>> S.add(5)
   >>> S.remove(3)
   >>> S
   Set([1, 2, 5])
   >>>

The union and intersection of sets can be computed with the :meth:`union` and
:meth:`intersection` methods; an alternative notation uses the bitwise operators
``&`` and ``|``. Mutable sets also have in-place versions of these methods,
:meth:`union_update` and :meth:`intersection_update`. ::

   >>> S1 = sets.Set([1,2,3])
   >>> S2 = sets.Set([4,5,6])
   >>> S1.union(S2)
   Set([1, 2, 3, 4, 5, 6])
   >>> S1 | S2                  # Alternative notation
   Set([1, 2, 3, 4, 5, 6])
   >>> S1.intersection(S2)
   Set([])
   >>> S1 & S2                  # Alternative notation
   Set([])
   >>> S1.union_update(S2)
   >>> S1
   Set([1, 2, 3, 4, 5, 6])
   >>>

It's also possible to take the symmetric difference of two sets.  This is the
set of all elements in the union that aren't in the intersection.  Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set.  Again, there's an alternative notation (``^``), and an
in-place version with the ungainly name :meth:`symmetric_difference_update`. ::

   >>> S1 = sets.Set([1,2,3,4])
   >>> S2 = sets.Set([3,4,5,6])
   >>> S1.symmetric_difference(S2)
   Set([1, 2, 5, 6])
   >>> S1 ^ S2
   Set([1, 2, 5, 6])
   >>>

There are also :meth:`issubset` and :meth:`issuperset` methods for checking
whether one set is a subset or superset of another::

   >>> S1 = sets.Set([1,2,3])
   >>> S2 = sets.Set([2,3])
   >>> S2.issubset(S1)
   True
   >>> S1.issubset(S2)
   False
   >>> S1.issuperset(S2)
   True
   >>>


.. seealso::

   :pep:`218` - Adding a Built-In Set Object Type
      PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and
      GvR.

.. ======================================================================


.. _section-generators:

PEP 255: Simple Generators
==========================

In Python 2.2, generators were added as an optional feature, to be enabled by a
``from __future__ import generators`` directive.  In 2.3 generators no longer
need to be specially enabled, and are now always present; this means that
:keyword:`yield` is now always a keyword.  The rest of this section is a copy of
the description of generators from the "What's New in Python 2.2" document; if
you read it back when Python 2.2 came out, you can skip the rest of this
section.

You're doubtless familiar with how function calls work in Python or C. When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a :keyword:`return` statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren't thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.

Here's the simplest example of a generator function::

   def generate_ints(N):
       for i in range(N):
           yield i

A new keyword, :keyword:`yield`, was introduced for generators.  Any function
containing a :keyword:`yield` statement is a generator function; this is
detected by Python's bytecode compiler which compiles the function specially as
a result.

When you call a generator function, it doesn't return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the :keyword:`yield` statement, the generator outputs the value of ``i``,
similar to a :keyword:`return` statement.  The big difference between
:keyword:`yield` and a :keyword:`return` statement is that on reaching a
:keyword:`yield` the generator's state of execution is suspended and local
variables are preserved.  On the next call to the generator's ``.next()``
method, the function will resume executing immediately after the
:keyword:`yield` statement.  (For complicated reasons, the :keyword:`yield`
statement isn't allowed inside the :keyword:`try` block of a :keyword:`try`...\
:keyword:`finally` statement; read :pep:`255` for a full explanation of the
interaction between :keyword:`yield` and exceptions.)

Here's a sample usage of the :func:`generate_ints` generator::

   >>> gen = generate_ints(3)
   >>> gen
   <generator object at 0x8117f90>
   >>> gen.next()
   0
   >>> gen.next()
   1
   >>> gen.next()
   2
   >>> gen.next()
   Traceback (most recent call last):
     File "stdin", line 1, in ?
     File "stdin", line 2, in generate_ints
   StopIteration

You could equally write ``for i in generate_ints(5)``, or ``a,b,c =
generate_ints(3)``.

Inside a generator function, the :keyword:`return` statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. :keyword:`return` with a value, such
as ``return 5``, is a syntax error inside a generator function.  The end of the
generator's results can also be indicated by raising :exc:`StopIteration`
manually, or by just letting the flow of execution fall off the bottom of the
function.

You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting ``self.count`` to
0, and having the :meth:`next` method increment ``self.count`` and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. :file:`Lib/test/test_generators.py` contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively. ::

   # A recursive generator that generates Tree leaves in in-order.
   def inorder(t):
       if t:
           for x in inorder(t.left):
               yield x
           yield t.label
           for x in inorder(t.right):
               yield x

Two other examples in :file:`Lib/test/test_generators.py` produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight's Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).

The idea of generators comes from other programming languages, especially Icon
(https://www.cs.arizona.edu/icon/), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from "An Overview of the Icon Programming Language" at
https://www.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what this looks
like::

   sentence := "Store it in the neighboring harbor"
   if (i := find("or", sentence)) > 5 then write(i)

In Icon the :func:`find` function returns the indexes at which the substring
"or" is found: 3, 23, 33.  In the :keyword:`if` statement, ``i`` is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.

Python doesn't go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered part of the core Python language, but
learning or using them isn't compulsory; if they don't solve any problems that
you have, feel free to ignore them. One novel feature of Python's interface as
compared to Icon's is that a generator's state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.


.. seealso::

   :pep:`255` - Simple Generators
      Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
      by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.

.. ======================================================================


.. _section-encodings:

PEP 263: Source Code Encodings
==============================

Python source files can now be declared as being in different character set
encodings.  Encodings are declared by including a specially formatted comment in
the first or second line of the source file.  For example, a UTF-8 file can be
declared with::

   #!/usr/bin/env python
   # -*- coding: UTF-8 -*-

Without such an encoding declaration, the default encoding used is 7-bit ASCII.
Executing or importing modules that contain string literals with 8-bit
characters and have no encoding declaration will result in a
:exc:`DeprecationWarning` being signalled by Python 2.3; in 2.4 this will be a
syntax error.

The encoding declaration only affects Unicode string literals, which will be
converted to Unicode using the specified encoding.  Note that Python identifiers
are still restricted to ASCII characters, so you can't have variable names that
use characters outside of the usual alphanumerics.


.. seealso::

   :pep:`263` - Defining Python Source Code Encodings
      Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao
      and Martin von Löwis.

.. ======================================================================


PEP 273: Importing Modules from ZIP Archives
============================================

The new :mod:`zipimport` module adds support for importing modules from a
ZIP-format archive.  You don't need to import the module explicitly; it will be
automatically imported if a ZIP archive's filename is added to ``sys.path``.
For example:

.. code-block:: shell-session

   amk@nyman:~/src/python$ unzip -l /tmp/example.zip
   Archive:  /tmp/example.zip
     Length     Date   Time    Name
    --------    ----   ----    ----
        8467  11-26-02 22:30   jwzthreading.py
    --------                   -------
        8467                   1 file
   amk@nyman:~/src/python$ ./python
   Python 2.3 (#1, Aug 1 2003, 19:54:32)
   >>> import sys
   >>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
   >>> import jwzthreading
   >>> jwzthreading.__file__
   '/tmp/example.zip/jwzthreading.py'
   >>>

An entry in ``sys.path`` can now be the filename of a ZIP archive. The ZIP
archive can contain any kind of files, but only files named :file:`\*.py`,
:file:`\*.pyc`, or :file:`\*.pyo` can be imported.  If an archive only contains
:file:`\*.py` files, Python will not attempt to modify the archive by adding the
corresponding :file:`\*.pyc` file, meaning that if a ZIP archive doesn't contain
:file:`\*.pyc` files, importing may be rather slow.

A path within the archive can also be specified to only import from a
subdirectory; for example, the path :file:`/tmp/example.zip/lib/` would only
import from the :file:`lib/` subdirectory within the archive.


.. seealso::

   :pep:`273` - Import Modules from Zip Archives
      Written by James C. Ahlstrom,  who also provided an implementation. Python 2.3
      follows the specification in :pep:`273`,  but uses an implementation written by
      Just van Rossum  that uses the import hooks described in :pep:`302`. See section
      :ref:`section-pep302` for a description of the new import hooks.

.. ======================================================================


PEP 277: Unicode file name support for Windows NT
=================================================

On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
Traditionally, Python has represented file names as byte strings, which is
inadequate because it renders some file names inaccessible.

Python now allows using arbitrary Unicode strings (within the limitations of the
file system) for all functions that expect file names, most notably the
:func:`open` built-in function. If a Unicode string is passed to
:func:`os.listdir`, Python now returns a list of Unicode strings.  A new
function, :func:`os.getcwdu`, returns the current directory as a Unicode string.

Byte strings still work as file names, and on Windows Python will transparently
convert them to Unicode using the ``mbcs`` encoding.

Other systems also allow Unicode strings as file names but convert them to byte
strings before passing them to the system, which can cause a :exc:`UnicodeError`
to be raised. Applications can test whether arbitrary Unicode strings are
supported as file names by checking :attr:`os.path.supports_unicode_filenames`,
a Boolean value.

Under MacOS, :func:`os.listdir` may now return Unicode filenames.


.. seealso::

   :pep:`277` - Unicode file name support for Windows NT
      Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark
      Hammond.

.. ======================================================================


.. index::
   single: universal newlines; What's new

PEP 278: Universal Newline Support
==================================

The three major operating systems used today are Microsoft Windows, Apple's
Macintosh OS, and the various Unix derivatives.  A minor irritation of
cross-platform work  is that these three platforms all use different characters to
mark the ends of lines in text files.  Unix uses the linefeed (ASCII character
10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
two-character sequence of a carriage return plus a newline.

Python's file objects can now support end of line conventions other than the
one followed by the platform on which Python is running. Opening a file with
the mode ``'U'`` or ``'rU'`` will open a file for reading in :term:`universal
newlines` mode.  All three line ending conventions will be translated to a
``'\n'`` in the strings returned by the various file methods such as
:meth:`read` and :meth:`readline`.

Universal newline support is also used when importing modules and when executing
a file with the :func:`execfile` function.  This means that Python modules can
be shared between all three operating systems without needing to convert the
line-endings.

This feature can be disabled when compiling Python by specifying the
:option:`!--without-universal-newlines` switch when running Python's
:program:`configure` script.


.. seealso::

   :pep:`278` - Universal Newline Support
      Written and implemented by Jack Jansen.

.. ======================================================================


.. _section-enumerate:

PEP 279: enumerate()
====================

A new built-in function, :func:`enumerate`, will make certain loops a bit
clearer.  ``enumerate(thing)``, where *thing* is either an iterator or a
sequence, returns an iterator that will return ``(0, thing[0])``, ``(1,
thing[1])``, ``(2, thing[2])``, and so forth.

A common idiom to change every element of a list looks like this::

   for i in range(len(L)):
       item = L[i]
       # ... compute some result based on item ...
       L[i] = result

This can be rewritten using :func:`enumerate` as::

   for i, item in enumerate(L):
       # ... compute some result based on item ...
       L[i] = result


.. seealso::

   :pep:`279` - The enumerate() built-in function
      Written and implemented by Raymond D. Hettinger.

.. ======================================================================


PEP 282: The logging Package
============================

A standard package for writing logs, :mod:`logging`, has been added to Python
2.3.  It provides a powerful and flexible mechanism for generating logging
output which can then be filtered and processed in various ways.  A
configuration file written in a standard format can be used to control the
logging behavior of a program.  Python includes handlers that will write log
records to standard error or to a file or socket, send them to the system log,
or even e-mail them to a particular address; of course, it's also possible to
write your own handler classes.

The :class:`Logger` class is the primary class. Most application code will deal
with one or more :class:`Logger` objects, each one used by a particular
subsystem of the application. Each :class:`Logger` is identified by a name, and
names are organized into a hierarchy using ``.``  as the component separator.
For example, you might have :class:`Logger` instances named ``server``,
``server.auth`` and ``server.network``.  The latter two instances are below
``server`` in the hierarchy.  This means that if you turn up the verbosity for
``server`` or direct ``server`` messages to a different handler, the changes
will also apply to records logged to ``server.auth`` and ``server.network``.
There's also a root :class:`Logger` that's the parent of all other loggers.

For simple uses, the :mod:`logging` package contains some convenience functions
that always use the root log::

   import logging

   logging.debug('Debugging information')
   logging.info('Informational message')
   logging.warning('Warning:config file %s not found', 'server.conf')
   logging.error('Error occurred')
   logging.critical('Critical error -- shutting down')

This produces the following output::

   WARNING:root:Warning:config file server.conf not found
   ERROR:root:Error occurred
   CRITICAL:root:Critical error -- shutting down

In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable the display
of informational and debugging messages by calling the :meth:`setLevel` method
on the root logger.

Notice the :func:`warning` call's use of string formatting operators; all of the
functions for logging messages take the arguments ``(msg, arg1, arg2, ...)`` and
log the string resulting from ``msg % (arg1, arg2, ...)``.

There's also an :func:`exception` function that records the most recent
traceback.  Any of the other functions will also record the traceback if you
specify a true value for the keyword argument *exc_info*. ::

   def f():
       try:    1/0
       except: logging.exception('Problem recorded')

   f()

This produces the following output::

   ERROR:root:Problem recorded
   Traceback (most recent call last):
     File "t.py", line 6, in f
       1/0
   ZeroDivisionError: integer division or modulo by zero

Slightly more advanced programs will use a logger other than the root logger.
The ``getLogger(name)`` function is used to get a particular log, creating
it if it doesn't exist yet. ``getLogger(None)`` returns the root logger. ::

   log = logging.getLogger('server')
    ...
   log.info('Listening on port %i', port)
    ...
   log.critical('Disk full')
    ...

Log records are usually propagated up the hierarchy, so a message logged to
``server.auth`` is also seen by ``server`` and ``root``, but a :class:`Logger`
can prevent this by setting its :attr:`propagate` attribute to :const:`False`.

There are more classes provided by the :mod:`logging` package that can be
customized.  When a :class:`Logger` instance is told to log a message, it
creates a :class:`LogRecord` instance that is sent to any number of different
:class:`Handler` instances.  Loggers and handlers can also have an attached list
of filters, and each filter can cause the :class:`LogRecord` to be ignored or
can modify the record before passing it along.  When they're finally output,
:class:`LogRecord` instances are converted to text by a :class:`Formatter`
class.  All of these classes can be replaced by your own specially-written
classes.

With all of these features the :mod:`logging` package should provide enough
flexibility for even the most complicated applications.  This is only an
incomplete overview of its features, so please see the package's reference
documentation for all of the details.  Reading :pep:`282` will also be helpful.


.. seealso::

   :pep:`282` - A Logging System
      Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.

.. ======================================================================


.. _section-bool:

PEP 285: A Boolean Type
=======================

A Boolean type was added to Python 2.3.  Two new constants were added to the
:mod:`__builtin__` module, :const:`True` and :const:`False`.  (:const:`True` and
:const:`False` constants were added to the built-ins in Python 2.2.1, but the
2.2.1 versions are simply set to integer values of 1 and 0 and aren't a
different type.)

The type object for this new type is named :class:`bool`; the constructor for it
takes any Python value and converts it to :const:`True` or :const:`False`. ::

   >>> bool(1)
   True
   >>> bool(0)
   False
   >>> bool([])
   False
   >>> bool( (1,) )
   True

Most of the standard library modules and built-in functions have been changed to
return Booleans. ::

   >>> obj = []
   >>> hasattr(obj, 'append')
   True
   >>> isinstance(obj, list)
   True
   >>> isinstance(obj, tuple)
   False

Python's Booleans were added with the primary goal of making code clearer.  For
example, if you're reading a function and encounter the statement ``return 1``,
you might wonder whether the ``1`` represents a Boolean truth value, an index,
or a coefficient that multiplies some other quantity.  If the statement is
``return True``, however, the meaning of the return value is quite clear.

Python's Booleans were *not* added for the sake of strict type-checking.  A very
strict language such as Pascal would also prevent you performing arithmetic with
Booleans, and would require that the expression in an :keyword:`if` statement
always evaluate to a Boolean result.  Python is not this strict and never will
be, as :pep:`285` explicitly says.  This means you can still use any expression
in an :keyword:`if` statement, even ones that evaluate to a list or tuple or
some random object.  The Boolean type is a subclass of the :class:`int` class so
that arithmetic using a Boolean still works. ::

   >>> True + 1
   2
   >>> False + 1
   1
   >>> False * 75
   0
   >>> True * 75
   75

To sum up :const:`True` and :const:`False` in a sentence: they're alternative
ways to spell the integer values 1 and 0, with the single difference that
:func:`str` and :func:`repr` return the strings ``'True'`` and ``'False'``
instead of ``'1'`` and ``'0'``.


.. seealso::

   :pep:`285` - Adding a bool type
      Written and implemented by GvR.

.. ======================================================================


PEP 293: Codec Error Handling Callbacks
=======================================

When encoding a Unicode string into a byte string, unencodable characters may be
encountered.  So far, Python has allowed specifying the error processing as
either "strict" (raising :exc:`UnicodeError`), "ignore" (skipping the
character), or "replace" (using a question mark in the output string), with
"strict" being the default behavior. It may be desirable to specify alternative
processing of such errors, such as inserting an XML character reference or HTML
entity reference into the converted string.

Python now has a flexible framework to add different processing strategies.  New
error handlers can be added with :func:`codecs.register_error`, and codecs then
can access the error handler with :func:`codecs.lookup_error`. An equivalent C
API has been added for codecs written in C. The error handler gets the necessary
state information such as the string being converted, the position in the string
where the error was detected, and the target encoding.  The handler can then
either raise an exception or return a replacement string.

Two additional error handlers have been implemented using this framework:
"backslashreplace" uses Python backslash quoting to represent unencodable
characters and "xmlcharrefreplace" emits XML character references.


.. seealso::

   :pep:`293` - Codec Error Handling Callbacks
      Written and implemented by Walter Dörwald.

.. ======================================================================


.. _section-pep301:

PEP 301: Package Index and Metadata for Distutils
=================================================

Support for the long-requested Python catalog makes its first appearance in 2.3.

The heart of the catalog is the new Distutils :command:`register` command.
Running ``python setup.py register`` will collect the metadata describing a
package, such as its name, version, maintainer, description, &c., and send it to
a central catalog server.  The resulting catalog is available from
https://pypi.org.

To make the catalog a bit more useful, a new optional *classifiers* keyword
argument has been added to the Distutils :func:`setup` function.  A list of
`Trove <http://catb.org/~esr/trove/>`_-style strings can be supplied to help
classify the software.

Here's an example :file:`setup.py` with classifiers, written to be compatible
with older versions of the Distutils::

   from distutils import core
   kw = {'name': "Quixote",
         'version': "0.5.1",
         'description': "A highly Pythonic Web application framework",
         # ...
         }

   if (hasattr(core, 'setup_keywords') and
       'classifiers' in core.setup_keywords):
       kw['classifiers'] = \
           ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
            'Environment :: No Input/Output (Daemon)',
            'Intended Audience :: Developers'],

   core.setup(**kw)

The full list of classifiers can be obtained by running  ``python setup.py
register --list-classifiers``.


.. seealso::

   :pep:`301` - Package Index and Metadata for Distutils
      Written and implemented by Richard Jones.

.. ======================================================================


.. _section-pep302:

PEP 302: New Import Hooks
=========================

While it's been possible to write custom import hooks ever since the
:mod:`ihooks` module was introduced in Python 1.3, no one has ever been really
happy with it because writing new import hooks is difficult and messy.  There
have been various proposed alternatives such as the :mod:`imputil` and :mod:`iu`
modules, but none of them has ever gained much acceptance, and none of them were
easily usable from C code.

:pep:`302` borrows ideas from its predecessors, especially from Gordon
McMillan's :mod:`iu` module.  Three new items  are added to the :mod:`sys`
module:

* ``sys.path_hooks`` is a list of callable objects; most  often they'll be
  classes.  Each callable takes a string containing a path and either returns an
  importer object that will handle imports from this path or raises an
  :exc:`ImportError` exception if it can't handle this path.

* ``sys.path_importer_cache`` caches importer objects for each path, so
  ``sys.path_hooks`` will only need to be traversed once for each path.

* ``sys.meta_path`` is a list of importer objects that will be traversed before
  ``sys.path`` is checked.  This list is initially empty, but user code can add
  objects to it.  Additional built-in and frozen modules can be imported by an
  object added to this list.

Importer objects must have a single method, ``find_module(fullname,
path=None)``.  *fullname* will be a module or package name, e.g. ``string`` or
``distutils.core``.  :meth:`find_module` must return a loader object that has a
single method, ``load_module(fullname)``, that creates and returns the
corresponding module object.

Pseudo-code for Python's new import logic, therefore, looks something like this
(simplified a bit; see :pep:`302` for the full details)::

   for mp in sys.meta_path:
       loader = mp(fullname)
       if loader is not None:
           <module> = loader.load_module(fullname)

   for path in sys.path:
       for hook in sys.path_hooks:
           try:
               importer = hook(path)
           except ImportError:
               # ImportError, so try the other path hooks
               pass
           else:
               loader = importer.find_module(fullname)
               <module> = loader.load_module(fullname)

   # Not found!
   raise ImportError


.. seealso::

   :pep:`302` - New Import Hooks
      Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.

.. ======================================================================


.. _section-pep305:

PEP 305: Comma-separated Files
==============================

Comma-separated files are a format frequently used for exporting data from
databases and spreadsheets.  Python 2.3 adds a parser for comma-separated files.

Comma-separated format is deceptively simple at first glance::

   Costs,150,200,3.95

Read a line and call ``line.split(',')``: what could be simpler? But toss in
string data that can contain commas, and things get more complicated::

   "Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"

A big ugly regular expression can parse this, but using the new  :mod:`csv`
package is much simpler::

   import csv

   input = open('datafile', 'rb')
   reader = csv.reader(input)
   for line in reader:
       print line

The :func:`reader` function takes a number of different options. The field
separator isn't limited to the comma and can be changed to any character, and so
can the quoting and line-ending characters.

Different dialects of comma-separated files can be defined and registered;
currently there are two dialects, both used by Microsoft Excel. A separate
:class:`csv.writer` class will generate comma-separated files from a succession
of tuples or lists, quoting strings that contain the delimiter.


.. seealso::

   :pep:`305` - CSV File API
      Written and implemented  by Kevin Altis, Dave Cole, Andrew McNamara, Skip
      Montanaro, Cliff Wells.

.. ======================================================================


.. _section-pep307:

PEP 307: Pickle Enhancements
============================

The :mod:`pickle` and :mod:`cPickle` modules received some attention during the
2.3 development cycle.  In 2.2, new-style classes could be pickled without
difficulty, but they weren't pickled very compactly; :pep:`307` quotes a trivial
example where a new-style class results in a pickled string three times longer
than that for a classic class.

The solution was to invent a new pickle protocol.  The :func:`pickle.dumps`
function has supported a text-or-binary flag  for a long time.  In 2.3, this
flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
format, 1 is the old binary format, and now 2 is a new 2.3-specific format.  A
new constant, :const:`pickle.HIGHEST_PROTOCOL`, can be used to select the
fanciest protocol available.

Unpickling is no longer considered a safe operation.  2.2's :mod:`pickle`
provided hooks for trying to prevent unsafe classes from being unpickled
(specifically, a :attr:`__safe_for_unpickling__` attribute), but none of this
code was ever audited and therefore it's all been ripped out in 2.3.  You should
not unpickle untrusted data in any version of Python.

To reduce the pickling overhead for new-style classes, a new interface for
customizing pickling was added using three special methods:
:meth:`__getstate__`, :meth:`__setstate__`, and :meth:`__getnewargs__`.  Consult
:pep:`307` for the full semantics  of these methods.

As a way to compress pickles yet further, it's now possible to use integer codes
instead of long strings to identify pickled classes. The Python Software
Foundation will maintain a list of standardized codes; there's also a range of
codes for private use.  Currently no codes have been specified.


.. seealso::

   :pep:`307` - Extensions to the pickle protocol
      Written and implemented  by Guido van Rossum and Tim Peters.

.. ======================================================================


.. _section-slices:

Extended Slices
===============

Ever since Python 1.4, the slicing syntax has supported an optional third "step"
or "stride" argument.  For example, these are all legal Python syntax:
``L[1:10:2]``, ``L[:-1:1]``, ``L[::-1]``.  This was added to Python at the
request of the developers of Numerical Python, which uses the third argument
extensively.  However, Python's built-in list, tuple, and string sequence types
have never supported this feature, raising a :exc:`TypeError` if you tried it.
Michael Hudson contributed a patch to fix this shortcoming.

For example, you can now easily extract the elements of a list that have even
indexes::

   >>> L = range(10)
   >>> L[::2]
   [0, 2, 4, 6, 8]

Negative values also work to make a copy of the same list in reverse order::

   >>> L[::-1]
   [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

This also works for tuples, arrays, and strings::

   >>> s='abcd'
   >>> s[::2]
   'ac'
   >>> s[::-1]
   'dcba'

If you have a mutable sequence such as a list or an array you can assign to or
delete an extended slice, but there are some differences between assignment to
extended and regular slices.  Assignment to a regular slice can be used to
change the length of the sequence::

   >>> a = range(3)
   >>> a
   [0, 1, 2]
   >>> a[1:3] = [4, 5, 6]
   >>> a
   [0, 4, 5, 6]

Extended slices aren't this flexible.  When assigning to an extended slice, the
list on the right hand side of the statement must contain the same number of
items as the slice it is replacing::

   >>> a = range(4)
   >>> a
   [0, 1, 2, 3]
   >>> a[::2]
   [0, 2]
   >>> a[::2] = [0, -1]
   >>> a
   [0, 1, -1, 3]
   >>> a[::2] = [0,1,2]
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   ValueError: attempt to assign sequence of size 3 to extended slice of size 2

Deletion is more straightforward::

   >>> a = range(4)
   >>> a
   [0, 1, 2, 3]
   >>> a[::2]
   [0, 2]
   >>> del a[::2]
   >>> a
   [1, 3]

One can also now pass slice objects to the :meth:`__getitem__` methods of the
built-in sequences::

   >>> range(10).__getitem__(slice(0, 5, 2))
   [0, 2, 4]

Or use slice objects directly in subscripts::

   >>> range(10)[slice(0, 5, 2)]
   [0, 2, 4]

To simplify implementing sequences that support extended slicing, slice objects
now have a method ``indices(length)`` which, given the length of a sequence,
returns a ``(start, stop, step)`` tuple that can be passed directly to
:func:`range`. :meth:`indices` handles omitted and out-of-bounds indices in a
manner consistent with regular slices (and this innocuous phrase hides a welter
of confusing details!).  The method is intended to be used like this::

   class FakeSeq:
       ...
       def calc_item(self, i):
           ...
       def __getitem__(self, item):
           if isinstance(item, slice):
               indices = item.indices(len(self))
               return FakeSeq([self.calc_item(i) for i in range(*indices)])
           else:
               return self.calc_item(i)

From this example you can also see that the built-in :class:`slice` object is
now the type object for the slice type, and is no longer a function.  This is
consistent with Python 2.2, where :class:`int`, :class:`str`, etc., underwent
the same change.

.. ======================================================================


Other Language Changes
======================

Here are all of the changes that Python 2.3 makes to the core Python language.

* The :keyword:`yield` statement is now always a keyword, as described in
  section :ref:`section-generators` of this document.

* A new built-in function :func:`enumerate` was added, as described in section
  :ref:`section-enumerate` of this document.

* Two new constants, :const:`True` and :const:`False` were added along with the
  built-in :class:`bool` type, as described in section :ref:`section-bool` of this
  document.

* The :func:`int` type constructor will now return a long integer instead of
  raising an :exc:`OverflowError` when a string or floating-point number is too
  large to fit into an integer.  This can lead to the paradoxical result that
  ``isinstance(int(expression), int)`` is false, but that seems unlikely to cause
  problems in practice.

* Built-in types now support the extended slicing syntax, as described in
  section :ref:`section-slices` of this document.

* A new built-in function, ``sum(iterable, start=0)``,  adds up the numeric
  items in the iterable object and returns their sum.  :func:`sum` only accepts
  numbers, meaning that you can't use it to concatenate a bunch of strings.
  (Contributed by Alex Martelli.)

* ``list.insert(pos, value)`` used to  insert *value* at the front of the list
  when *pos* was negative.  The behaviour has now been changed to be consistent
  with slice indexing, so when *pos* is -1 the value will be inserted before the
  last element, and so forth.

* ``list.index(value)``, which searches for *value*  within the list and returns
  its index, now takes optional  *start* and *stop* arguments to limit the search
  to  only part of the list.

* Dictionaries have a new method, ``pop(key[, *default*])``, that returns
  the value corresponding to *key* and removes that key/value pair from the
  dictionary.  If the requested key isn't present in the dictionary, *default* is
  returned if it's specified and :exc:`KeyError` raised if it isn't. ::

     >>> d = {1:2}
     >>> d
     {1: 2}
     >>> d.pop(4)
     Traceback (most recent call last):
       File "stdin", line 1, in ?
     KeyError: 4
     >>> d.pop(1)
     2
     >>> d.pop(1)
     Traceback (most recent call last):
       File "stdin", line 1, in ?
     KeyError: 'pop(): dictionary is empty'
     >>> d
     {}
     >>>

  There's also a new class method,  ``dict.fromkeys(iterable, value)``, that
  creates a dictionary with keys taken from the supplied iterator *iterable* and
  all values set to *value*, defaulting to ``None``.

  (Patches contributed by Raymond Hettinger.)

  Also, the :func:`dict` constructor now accepts keyword arguments to simplify
  creating small dictionaries::

     >>> dict(red=1, blue=2, green=3, black=4)
     {'blue': 2, 'black': 4, 'green': 3, 'red': 1}

  (Contributed by Just van Rossum.)

* The :keyword:`assert` statement no longer checks the ``__debug__`` flag, so
  you can no longer disable assertions by assigning to ``__debug__``. Running
  Python with the :option:`-O` switch will still generate code that doesn't
  execute any assertions.

* Most type objects are now callable, so you can use them to create new objects
  such as functions, classes, and modules.  (This means that the :mod:`new` module
  can be deprecated in a future Python version, because you can now use the type
  objects available in the :mod:`types` module.) For example, you can create a new
  module object with the following code:

  ::

     >>> import types
     >>> m = types.ModuleType('abc','docstring')
     >>> m
     <module 'abc' (built-in)>
     >>> m.__doc__
     'docstring'

* A new warning, :exc:`PendingDeprecationWarning` was added to indicate features
  which are in the process of being deprecated.  The warning will *not* be printed
  by default.  To check for use of features that will be deprecated in the future,
  supply :option:`-Walways::PendingDeprecationWarning:: <-W>` on the command line or
  use :func:`warnings.filterwarnings`.

* The process of deprecating string-based exceptions, as in ``raise "Error
  occurred"``, has begun.  Raising a string will now trigger
  :exc:`PendingDeprecationWarning`.

* Using ``None`` as a variable name will now result in a :exc:`SyntaxWarning`
  warning.  In a future version of Python, ``None`` may finally become a keyword.

* The :meth:`xreadlines` method of file objects, introduced in Python 2.1, is no
  longer necessary because files now behave as their own iterator.
  :meth:`xreadlines` was originally introduced as a faster way to loop over all
  the lines in a file, but now you can simply write ``for line in file_obj``.
  File objects also have a new read-only :attr:`encoding` attribute that gives the
  encoding used by the file; Unicode strings written to the file will be
  automatically  converted to bytes using the given encoding.

* The method resolution order used by new-style classes has changed, though
  you'll only notice the difference if you have a really complicated inheritance
  hierarchy.  Classic classes are unaffected by this change.  Python 2.2
  originally used a topological sort of a class's ancestors, but 2.3 now uses the
  C3 algorithm as described in the paper `"A Monotonic Superclass Linearization
  for Dylan" <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910>`_. To
  understand the motivation for this change,  read Michele Simionato's article
  `"Python 2.3 Method Resolution Order" <http://www.phyast.pitt.edu/~micheles/mro.html>`_, or
  read the thread on python-dev starting with the message at
  https://mail.python.org/pipermail/python-dev/2002-October/029035.html. Samuele
  Pedroni first pointed out the problem and also implemented the fix by coding the
  C3 algorithm.

* Python runs multithreaded programs by switching between threads after
  executing N bytecodes.  The default value for N has been increased from 10 to
  100 bytecodes, speeding up single-threaded applications by reducing the
  switching overhead.  Some multithreaded applications may suffer slower response
  time, but that's easily fixed by setting the limit back to a lower number using
  ``sys.setcheckinterval(N)``. The limit can be retrieved with the new
  :func:`sys.getcheckinterval` function.

* One minor but far-reaching change is that the names of extension types defined
  by the modules included with Python now contain the module and a ``'.'`` in
  front of the type name.  For example, in Python 2.2, if you created a socket and
  printed its :attr:`__class__`, you'd get this output::

     >>> s = socket.socket()
     >>> s.__class__
     <type 'socket'>

  In 2.3, you get this::

     >>> s.__class__
     <type '_socket.socket'>

* One of the noted incompatibilities between old- and new-style classes has been
  removed: you can now assign to the :attr:`~definition.__name__` and :attr:`~class.__bases__`
  attributes of new-style classes.  There are some restrictions on what can be
  assigned to :attr:`~class.__bases__` along the lines of those relating to assigning to
  an instance's :attr:`~instance.__class__` attribute.

.. ======================================================================


String Changes
--------------

* The :keyword:`in` operator now works differently for strings. Previously, when
  evaluating ``X in Y`` where *X* and *Y* are strings, *X* could only be a single
  character. That's now changed; *X* can be a string of any length, and ``X in Y``
  will return :const:`True` if *X* is a substring of *Y*.  If *X* is the empty
  string, the result is always :const:`True`. ::

     >>> 'ab' in 'abcd'
     True
     >>> 'ad' in 'abcd'
     False
     >>> '' in 'abcd'
     True

  Note that this doesn't tell you where the substring starts; if you need that
  information, use the :meth:`find` string method.

* The :meth:`strip`, :meth:`lstrip`, and :meth:`rstrip` string methods now have
  an optional argument for specifying the characters to strip.  The default is
  still to remove all whitespace characters::

     >>> '   abc '.strip()
     'abc'
     >>> '><><abc<><><>'.strip('<>')
     'abc'
     >>> '><><abc<><><>\n'.strip('<>')
     'abc<><><>\n'
     >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
     u'\u4001abc'
     >>>

  (Suggested by Simon Brunning and implemented by Walter Dörwald.)

* The :meth:`startswith` and :meth:`endswith` string methods now accept negative
  numbers for the *start* and *end* parameters.

* Another new string method is :meth:`zfill`, originally a function in the
  :mod:`string` module.  :meth:`zfill` pads a numeric string with zeros on the
  left until it's the specified width. Note that the ``%`` operator is still more
  flexible and powerful than :meth:`zfill`. ::

     >>> '45'.zfill(4)
     '0045'
     >>> '12345'.zfill(4)
     '12345'
     >>> 'goofy'.zfill(6)
     '0goofy'

  (Contributed by Walter Dörwald.)

* A new type object, :class:`basestring`, has been added. Both 8-bit strings and
  Unicode strings inherit from this type, so ``isinstance(obj, basestring)`` will
  return :const:`True` for either kind of string.  It's a completely abstract
  type, so you can't create :class:`basestring` instances.

* Interned strings are no longer immortal and will now be garbage-collected in
  the usual way when the only reference to them is from the internal dictionary of
  interned strings.  (Implemented by Oren Tirosh.)

.. ======================================================================


Optimizations
-------------

* The creation of new-style class instances has been made much faster; they're
  now faster than classic classes!

* The :meth:`sort` method of list objects has been extensively rewritten by Tim
  Peters, and the implementation is significantly faster.

* Multiplication of large long integers is now much faster thanks to an
  implementation of Karatsuba multiplication, an algorithm that scales better than
  the O(n\*n) required for the grade-school multiplication algorithm.  (Original
  patch by Christopher A. Craig, and significantly reworked by Tim Peters.)

* The ``SET_LINENO`` opcode is now gone.  This may provide a small speed
  increase, depending on your compiler's idiosyncrasies. See section
  :ref:`section-other` for a longer explanation. (Removed by Michael Hudson.)

* :func:`xrange` objects now have their own iterator, making ``for i in
  xrange(n)`` slightly faster than ``for i in range(n)``.  (Patch by Raymond
  Hettinger.)

* A number of small rearrangements have been made in various hotspots to improve
  performance, such as inlining a function or removing some code.  (Implemented
  mostly by GvR, but lots of people have contributed single changes.)

The net result of the 2.3 optimizations is that Python 2.3 runs the  pystone
benchmark around 25% faster than Python 2.2.

.. ======================================================================


New, Improved, and Deprecated Modules
=====================================

As usual, Python's standard library received a number of enhancements and bug
fixes.  Here's a partial list of the most notable changes, sorted alphabetically
by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.

* The :mod:`array` module now supports arrays of Unicode characters using the
  ``'u'`` format character.  Arrays also now support using the ``+=`` assignment
  operator to add another array's contents, and the ``*=`` assignment operator to
  repeat an array. (Contributed by Jason Orendorff.)

* The :mod:`bsddb` module has been replaced by version 4.1.6 of the `PyBSDDB
  <http://pybsddb.sourceforge.net>`_ package, providing a more complete interface
  to the transactional features of the BerkeleyDB library.

  The old version of the module has been renamed to  :mod:`bsddb185` and is no
  longer built automatically; you'll  have to edit :file:`Modules/Setup` to enable
  it.  Note that the new :mod:`bsddb` package is intended to be compatible with
  the  old module, so be sure to file bugs if you discover any incompatibilities.
  When upgrading to Python 2.3, if the new interpreter is compiled with a new
  version of  the underlying BerkeleyDB library, you will almost certainly have to
  convert your database files to the new version.  You can do this fairly easily
  with the new scripts :file:`db2pickle.py` and :file:`pickle2db.py` which you
  will find in the distribution's :file:`Tools/scripts` directory.  If you've
  already been using the PyBSDDB package and importing it as :mod:`bsddb3`, you
  will have to change your ``import`` statements to import it as :mod:`bsddb`.

* The new :mod:`bz2` module is an interface to the bz2 data compression library.
  bz2-compressed data is usually smaller than  corresponding :mod:`zlib`\
  -compressed data. (Contributed by Gustavo Niemeyer.)

* A set of standard date/time types has been added in the new :mod:`datetime`
  module.  See the following section for more details.

* The Distutils :class:`Extension` class now supports an extra constructor
  argument named *depends* for listing additional source files that an extension
  depends on.  This lets Distutils recompile the module if any of the dependency
  files are modified.  For example, if :file:`sampmodule.c` includes the header
  file :file:`sample.h`, you would create the :class:`Extension` object like
  this::

     ext = Extension("samp",
                     sources=["sampmodule.c"],
                     depends=["sample.h"])

  Modifying :file:`sample.h` would then cause the module to be recompiled.
  (Contributed by Jeremy Hylton.)

* Other minor changes to Distutils: it now checks for the :envvar:`CC`,
  :envvar:`CFLAGS`, :envvar:`CPP`, :envvar:`LDFLAGS`, and :envvar:`CPPFLAGS`
  environment variables, using them to override the settings in Python's
  configuration (contributed by Robert Weber).

* Previously the :mod:`doctest` module would only search the docstrings of
  public methods and functions for test cases, but it now also examines private
  ones as well.  The :func:`DocTestSuite` function creates a
  :class:`unittest.TestSuite` object from a set of :mod:`doctest` tests.

* The new ``gc.get_referents(object)`` function returns a list of all the
  objects referenced by *object*.

* The :mod:`getopt` module gained a new function, :func:`gnu_getopt`, that
  supports the same arguments as the existing :func:`getopt` function but uses
  GNU-style scanning mode. The existing :func:`getopt` stops processing options as
  soon as a non-option argument is encountered, but in GNU-style mode processing
  continues, meaning that options and arguments can be mixed.  For example::

     >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
     ([('-f', 'filename')], ['output', '-v'])
     >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
     ([('-f', 'filename'), ('-v', '')], ['output'])

  (Contributed by Peter Åstrand.)

* The :mod:`grp`, :mod:`pwd`, and :mod:`resource` modules now return enhanced
  tuples::

     >>> import grp
     >>> g = grp.getgrnam('amk')
     >>> g.gr_name, g.gr_gid
     ('amk', 500)

* The :mod:`gzip` module can now handle files exceeding 2 GiB.

* The new :mod:`heapq` module contains an implementation of a heap queue
  algorithm.  A heap is an array-like data structure that keeps items in a
  partially sorted order such that, for every index *k*, ``heap[k] <=
  heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]``.  This makes it quick to remove the
  smallest item, and inserting a new item while maintaining the heap property is
  O(lg n).  (See https://xlinux.nist.gov/dads//HTML/priorityque.html for more
  information about the priority queue data structure.)

  The :mod:`heapq` module provides :func:`heappush` and :func:`heappop` functions
  for adding and removing items while maintaining the heap property on top of some
  other mutable Python sequence type.  Here's an example that uses a Python list::

     >>> import heapq
     >>> heap = []
     >>> for item in [3, 7, 5, 11, 1]:
     ...    heapq.heappush(heap, item)
     ...
     >>> heap
     [1, 3, 5, 11, 7]
     >>> heapq.heappop(heap)
     1
     >>> heapq.heappop(heap)
     3
     >>> heap
     [5, 7, 11]

  (Contributed by Kevin O'Connor.)

* The IDLE integrated development environment has been updated using the code
  from the IDLEfork project (http://idlefork.sourceforge.net).  The most notable feature is
  that the code being developed is now executed in a subprocess, meaning that
  there's no longer any need for manual ``reload()`` operations. IDLE's core code
  has been incorporated into the standard library as the :mod:`idlelib` package.

* The :mod:`imaplib` module now supports IMAP over SSL. (Contributed by Piers
  Lauder and Tino Lange.)

* The :mod:`itertools` contains a number of useful functions for use with
  iterators, inspired by various functions provided by the ML and Haskell
  languages.  For example, ``itertools.ifilter(predicate, iterator)`` returns all
  elements in the iterator for which the function :func:`predicate` returns
  :const:`True`, and ``itertools.repeat(obj, N)`` returns ``obj`` *N* times.
  There are a number of other functions in the module; see the package's reference
  documentation for details.
  (Contributed by Raymond Hettinger.)

* Two new functions in the :mod:`math` module, ``degrees(rads)`` and
  ``radians(degs)``, convert between radians and degrees.  Other functions in
  the :mod:`math` module such as :func:`math.sin` and :func:`math.cos` have always
  required input values measured in radians.  Also, an optional *base* argument
  was added to :func:`math.log` to make it easier to compute logarithms for bases
  other than ``e`` and ``10``.  (Contributed by Raymond Hettinger.)

* Several new POSIX functions (:func:`getpgid`, :func:`killpg`, :func:`lchown`,
  :func:`loadavg`, :func:`major`, :func:`makedev`, :func:`minor`, and
  :func:`mknod`) were added to the :mod:`posix` module that underlies the
  :mod:`os` module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
  Otkidach.)

* In the :mod:`os` module, the :func:`\*stat` family of functions can now report
  fractions of a second in a timestamp.  Such time stamps are represented as
  floats, similar to the value returned by :func:`time.time`.

  During testing, it was found that some applications will break if time stamps
  are floats.  For compatibility, when using the tuple interface of the
  :class:`stat_result` time stamps will be represented as integers. When using
  named fields (a feature first introduced in Python 2.2), time stamps are still
  represented as integers, unless :func:`os.stat_float_times` is invoked to enable
  float return values::

     >>> os.stat("/tmp").st_mtime
     1034791200
     >>> os.stat_float_times(True)
     >>> os.stat("/tmp").st_mtime
     1034791200.6335014

  In Python 2.4, the default will change to always returning floats.

  Application developers should enable this feature only if all their libraries
  work properly when confronted with floating point time stamps, or if they use
  the tuple API. If used, the feature should be activated on an application level
  instead of trying to enable it on a per-use basis.

* The :mod:`optparse` module contains a new parser for command-line arguments
  that can convert option values to a particular Python type  and will
  automatically generate a usage message.  See the following section for  more
  details.

* The old and never-documented :mod:`linuxaudiodev` module has been deprecated,
  and a new version named :mod:`ossaudiodev` has been added.  The module was
  renamed because the OSS sound drivers can be used on platforms other than Linux,
  and the interface has also been tidied and brought up to date in various ways.
  (Contributed by Greg Ward and Nicholas FitzRoy-Dale.)

* The new :mod:`platform` module contains a number of functions that try to
  determine various properties of the platform you're running on.  There are
  functions for getting the architecture, CPU type, the Windows OS version, and
  even the Linux distribution version. (Contributed by Marc-André Lemburg.)

* The parser objects provided by the :mod:`pyexpat` module can now optionally
  buffer character data, resulting in fewer calls to your character data handler
  and therefore faster performance.  Setting the parser object's
  :attr:`buffer_text` attribute to :const:`True` will enable buffering.

* The ``sample(population, k)`` function was added to the :mod:`random`
  module.  *population* is a sequence or :class:`xrange` object containing the
  elements of a population, and :func:`sample` chooses *k* elements from the
  population without replacing chosen elements.  *k* can be any value up to
  ``len(population)``. For example::

     >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
     >>> random.sample(days, 3)      # Choose 3 elements
     ['St', 'Sn', 'Th']
     >>> random.sample(days, 7)      # Choose 7 elements
     ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
     >>> random.sample(days, 7)      # Choose 7 again
     ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
     >>> random.sample(days, 8)      # Can't choose eight
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "random.py", line 414, in sample
           raise ValueError, "sample larger than population"
     ValueError: sample larger than population
     >>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
     [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]

  The :mod:`random` module now uses a new algorithm, the Mersenne Twister,
  implemented in C.  It's faster and more extensively studied than the previous
  algorithm.

  (All changes contributed by Raymond Hettinger.)

* The :mod:`readline` module also gained a number of new functions:
  :func:`get_history_item`, :func:`get_current_history_length`, and
  :func:`redisplay`.

* The :mod:`rexec` and :mod:`Bastion` modules have been declared dead, and
  attempts to import them will fail with a :exc:`RuntimeError`.  New-style classes
  provide new ways to break out of the restricted execution environment provided
  by :mod:`rexec`, and no one has interest in fixing them or time to do so.  If
  you have applications using :mod:`rexec`, rewrite them to use something else.

  (Sticking with Python 2.2 or 2.1 will not make your applications any safer
  because there are known bugs in the :mod:`rexec` module in those versions.  To
  repeat: if you're using :mod:`rexec`, stop using it immediately.)

* The :mod:`rotor` module has been deprecated because the  algorithm it uses for
  encryption is not believed to be secure.  If you need encryption, use one of the
  several AES Python modules that are available separately.

* The :mod:`shutil` module gained a ``move(src, dest)`` function that
  recursively moves a file or directory to a new location.

* Support for more advanced POSIX signal handling was added to the :mod:`signal`
  but then removed again as it proved impossible to make it work reliably across
  platforms.

* The :mod:`socket` module now supports timeouts.  You can call the
  ``settimeout(t)`` method on a socket object to set a timeout of *t* seconds.
  Subsequent socket operations that take longer than *t* seconds to complete will
  abort and raise a :exc:`socket.timeout` exception.

  The original timeout implementation was by Tim O'Malley.  Michael Gilfix
  integrated it into the Python :mod:`socket` module and shepherded it through a
  lengthy review.  After the code was checked in, Guido van Rossum rewrote parts
  of it.  (This is a good example of a collaborative development process in
  action.)

* On Windows, the :mod:`socket` module now ships with Secure  Sockets Layer
  (SSL) support.

* The value of the C :const:`PYTHON_API_VERSION` macro is now exposed at the
  Python level as ``sys.api_version``.  The current exception can be cleared by
  calling the new :func:`sys.exc_clear` function.

* The new :mod:`tarfile` module  allows reading from and writing to
  :program:`tar`\ -format archive files. (Contributed by Lars Gustäbel.)

* The new :mod:`textwrap` module contains functions for wrapping strings
  containing paragraphs of text.  The ``wrap(text, width)`` function takes a
  string and returns a list containing the text split into lines of no more than
  the chosen width.  The ``fill(text, width)`` function returns a single
  string, reformatted to fit into lines no longer than the chosen width. (As you
  can guess, :func:`fill` is built on top of :func:`wrap`.  For example::

     >>> import textwrap
     >>> paragraph = "Not a whit, we defy augury: ... more text ..."
     >>> textwrap.wrap(paragraph, 60)
     ["Not a whit, we defy augury: there's a special providence in",
      "the fall of a sparrow. If it be now, 'tis not to come; if it",
      ...]
     >>> print textwrap.fill(paragraph, 35)
     Not a whit, we defy augury: there's
     a special providence in the fall of
     a sparrow. If it be now, 'tis not
     to come; if it be not to come, it
     will be now; if it be not now, yet
     it will come: the readiness is all.
     >>>

  The module also contains a :class:`TextWrapper` class that actually implements
  the text wrapping strategy.   Both the :class:`TextWrapper` class and the
  :func:`wrap` and :func:`fill` functions support a number of additional keyword
  arguments for fine-tuning the formatting; consult the module's documentation
  for details. (Contributed by Greg Ward.)

* The :mod:`thread` and :mod:`threading` modules now have companion modules,
  :mod:`dummy_thread` and :mod:`dummy_threading`, that provide a do-nothing
  implementation of the :mod:`thread` module's interface for platforms where
  threads are not supported.  The intention is to simplify thread-aware modules
  (ones that *don't* rely on threads to run) by putting the following code at the
  top::

     try:
         import threading as _threading
     except ImportError:
         import dummy_threading as _threading

  In this example, :mod:`_threading` is used as the module name to make it clear
  that the module being used is not necessarily the actual :mod:`threading`
  module. Code can call functions and use classes in :mod:`_threading` whether or
  not threads are supported, avoiding an :keyword:`if` statement and making the
  code slightly clearer.  This module will not magically make multithreaded code
  run without threads; code that waits for another thread to return or to do
  something will simply hang forever.

* The :mod:`time` module's :func:`strptime` function has long been an annoyance
  because it uses the platform C library's :func:`strptime` implementation, and
  different platforms sometimes have odd bugs.  Brett Cannon contributed a
  portable implementation that's written in pure Python and should behave
  identically on all platforms.

* The new :mod:`timeit` module helps measure how long snippets of Python code
  take to execute.  The :file:`timeit.py` file can be run directly from the
  command line, or the module's :class:`Timer` class can be imported and used
  directly.  Here's a short example that figures out whether it's faster to
  convert an 8-bit string to Unicode by appending an empty Unicode string to it or
  by using the :func:`unicode` function::

     import timeit

     timer1 = timeit.Timer('unicode("abc")')
     timer2 = timeit.Timer('"abc" + u""')

     # Run three trials
     print timer1.repeat(repeat=3, number=100000)
     print timer2.repeat(repeat=3, number=100000)

     # On my laptop this outputs:
     # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
     # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]

* The :mod:`Tix` module has received various bug fixes and updates for the
  current version of the Tix package.

* The :mod:`Tkinter` module now works with a thread-enabled  version of Tcl.
  Tcl's threading model requires that widgets only be accessed from the thread in
  which they're created; accesses from another thread can cause Tcl to panic.  For
  certain Tcl interfaces, :mod:`Tkinter` will now automatically avoid this  when a
  widget is accessed from a different thread by marshalling a command, passing it
  to the correct thread, and waiting for the results.  Other interfaces can't be
  handled automatically but :mod:`Tkinter` will now raise an exception on such an
  access so that you can at least find out about the problem.  See
  https://mail.python.org/pipermail/python-dev/2002-December/031107.html for a more
  detailed explanation of this change.  (Implemented by Martin von Löwis.)

* Calling Tcl methods through :mod:`_tkinter` no longer  returns only strings.
  Instead, if Tcl returns other objects those objects are converted to their
  Python equivalent, if one exists, or wrapped with a :class:`_tkinter.Tcl_Obj`
  object if no Python equivalent exists. This behavior can be controlled through
  the :meth:`wantobjects` method of :class:`tkapp` objects.

  When using :mod:`_tkinter` through the :mod:`Tkinter` module (as most Tkinter
  applications will), this feature is always activated. It should not cause
  compatibility problems, since Tkinter would always convert string results to
  Python types where possible.

  If any incompatibilities are found, the old behavior can be restored by setting
  the :attr:`wantobjects` variable in the :mod:`Tkinter` module to false before
  creating the first :class:`tkapp` object. ::

     import Tkinter
     Tkinter.wantobjects = 0

  Any breakage caused by this change should be reported as a bug.

* The :mod:`UserDict` module has a new :class:`DictMixin` class which defines
  all dictionary methods for classes that already have a minimum mapping
  interface.  This greatly simplifies writing classes that need to be
  substitutable for dictionaries, such as the classes in  the :mod:`shelve`
  module.

  Adding the mix-in as a superclass provides the full dictionary interface
  whenever the class defines :meth:`__getitem__`, :meth:`__setitem__`,
  :meth:`__delitem__`, and :meth:`keys`. For example::

     >>> import UserDict
     >>> class SeqDict(UserDict.DictMixin):
     ...     """Dictionary lookalike implemented with lists."""
     ...     def __init__(self):
     ...         self.keylist = []
     ...         self.valuelist = []
     ...     def __getitem__(self, key):
     ...         try:
     ...             i = self.keylist.index(key)
     ...         except ValueError:
     ...             raise KeyError
     ...         return self.valuelist[i]
     ...     def __setitem__(self, key, value):
     ...         try:
     ...             i = self.keylist.index(key)
     ...             self.valuelist[i] = value
     ...         except ValueError:
     ...             self.keylist.append(key)
     ...             self.valuelist.append(value)
     ...     def __delitem__(self, key):
     ...         try:
     ...             i = self.keylist.index(key)
     ...         except ValueError:
     ...             raise KeyError
     ...         self.keylist.pop(i)
     ...         self.valuelist.pop(i)
     ...     def keys(self):
     ...         return list(self.keylist)
     ...
     >>> s = SeqDict()
     >>> dir(s)      # See that other dictionary methods are implemented
     ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
      '__init__', '__iter__', '__len__', '__module__', '__repr__',
      '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
      'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
      'setdefault', 'update', 'valuelist', 'values']

  (Contributed by Raymond Hettinger.)

* The DOM implementation in :mod:`xml.dom.minidom` can now generate XML output
  in a particular encoding by providing an optional encoding argument to the
  :meth:`toxml` and :meth:`toprettyxml` methods of DOM nodes.

* The :mod:`xmlrpclib` module now supports an XML-RPC extension for handling nil
  data values such as Python's ``None``.  Nil values are always supported on
  unmarshalling an XML-RPC response.  To generate requests containing ``None``,
  you must supply a true value for the *allow_none* parameter when creating a
  :class:`Marshaller` instance.

* The new :mod:`DocXMLRPCServer` module allows writing self-documenting XML-RPC
  servers. Run it in demo mode (as a program) to see it in action.   Pointing the
  Web browser to the RPC server produces pydoc-style documentation; pointing
  xmlrpclib to the server allows invoking the actual methods. (Contributed by
  Brian Quinlan.)

* Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
  has been added. The "idna" encoding can be used to convert between a Unicode
  domain name and the ASCII-compatible encoding (ACE) of that name. ::

     >{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
     'www.xn--alliancefranaise-npb.nu'

  The :mod:`socket` module has also been extended to transparently convert
  Unicode hostnames to the ACE version before passing them to the C library.
  Modules that deal with hostnames such as :mod:`httplib` and :mod:`ftplib`)
  also support Unicode host names; :mod:`httplib` also sends HTTP ``Host``
  headers using the ACE version of the domain name.  :mod:`urllib` supports
  Unicode URLs with non-ASCII host names as long as the ``path`` part of the URL
  is ASCII only.

  To implement this change, the :mod:`stringprep` module, the  ``mkstringprep``
  tool and the ``punycode`` encoding have been added.

.. ======================================================================


Date/Time Type
--------------

Date and time types suitable for expressing timestamps were added as the
:mod:`datetime` module.  The types don't support different calendars or many
fancy features, and just stick to the basics of representing time.

The three primary types are: :class:`date`, representing a day, month, and year;
:class:`~datetime.time`, consisting of hour, minute, and second; and :class:`~datetime.datetime`,
which contains all the attributes of both :class:`date` and :class:`~datetime.time`.
There's also a :class:`timedelta` class representing differences between two
points in time, and time zone logic is implemented by classes inheriting from
the abstract :class:`tzinfo` class.

You can create instances of :class:`date` and :class:`~datetime.time` by either supplying
keyword arguments to the appropriate constructor, e.g.
``datetime.date(year=1972, month=10, day=15)``, or by using one of a number of
class methods.  For example, the :meth:`date.today` class method returns the
current local date.

Once created, instances of the date/time classes are all immutable. There are a
number of methods for producing formatted strings from objects::

   >>> import datetime
   >>> now = datetime.datetime.now()
   >>> now.isoformat()
   '2002-12-30T21:27:03.994956'
   >>> now.ctime()  # Only available on date, datetime
   'Mon Dec 30 21:27:03 2002'
   >>> now.strftime('%Y %d %b')
   '2002 30 Dec'

The :meth:`replace` method allows modifying one or more fields  of a
:class:`date` or :class:`~datetime.datetime` instance, returning a new instance::

   >>> d = datetime.datetime.now()
   >>> d
   datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
   >>> d.replace(year=2001, hour = 12)
   datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
   >>>

Instances can be compared, hashed, and converted to strings (the result is the
same as that of :meth:`isoformat`).  :class:`date` and :class:`~datetime.datetime`
instances can be subtracted from each other, and added to :class:`timedelta`
instances.  The largest missing feature is that there's no standard library
support for parsing strings and getting back a :class:`date` or
:class:`~datetime.datetime`.

For more information, refer to the module's reference documentation.
(Contributed by Tim Peters.)

.. ======================================================================


The optparse Module
-------------------

The :mod:`getopt` module provides simple parsing of command-line arguments.  The
new :mod:`optparse` module (originally named Optik) provides more elaborate
command-line parsing that follows the Unix conventions, automatically creates
the output for :option:`!--help`, and can perform different actions for different
options.

You start by creating an instance of :class:`OptionParser` and telling it what
your program's options are. ::

   import sys
   from optparse import OptionParser

   op = OptionParser()
   op.add_option('-i', '--input',
                 action='store', type='string', dest='input',
                 help='set input filename')
   op.add_option('-l', '--length',
                 action='store', type='int', dest='length',
                 help='set maximum length of output')

Parsing a command line is then done by calling the :meth:`parse_args` method. ::

   options, args = op.parse_args(sys.argv[1:])
   print options
   print args

This returns an object containing all of the option values, and a list of
strings containing the remaining arguments.

Invoking the script with the various arguments now works as you'd expect it to.
Note that the length argument is automatically converted to an integer.

.. code-block:: shell-session

   $ ./python opt.py -i data arg1
   <Values at 0x400cad4c: {'input': 'data', 'length': None}>
   ['arg1']
   $ ./python opt.py --input=data --length=4
   <Values at 0x400cad2c: {'input': 'data', 'length': 4}>
   []
   $

The help message is automatically generated for you:

.. code-block:: shell-session

   $ ./python opt.py --help
   usage: opt.py [options]

   options:
     -h, --help            show this help message and exit
     -iINPUT, --input=INPUT
                           set input filename
     -lLENGTH, --length=LENGTH
                           set maximum length of output
   $

See the module's documentation for more details.


Optik was written by Greg Ward, with suggestions from the readers of the Getopt
SIG.

.. ======================================================================


.. _section-pymalloc:

Pymalloc: A Specialized Object Allocator
========================================

Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
feature added to Python 2.1.  Pymalloc is intended to be faster than the system
:c:func:`malloc` and to have less memory overhead for allocation patterns typical
of Python programs. The allocator uses C's :c:func:`malloc` function to get large
pools of memory and then fulfills smaller memory requests from these pools.

In 2.1 and 2.2, pymalloc was an experimental feature and wasn't enabled by
default; you had to explicitly enable it when compiling Python by providing the
:option:`!--with-pymalloc` option to the :program:`configure` script.  In 2.3,
pymalloc has had further enhancements and is now enabled by default; you'll have
to supply :option:`!--without-pymalloc` to disable it.

This change is transparent to code written in Python; however, pymalloc may
expose bugs in C extensions.  Authors of C extension modules should test their
code with pymalloc enabled, because some incorrect code may cause core dumps at
runtime.

There's one particularly common error that causes problems.  There are a number
of memory allocation functions in Python's C API that have previously just been
aliases for the C library's :c:func:`malloc` and :c:func:`free`, meaning that if
you accidentally called mismatched functions the error wouldn't be noticeable.
When the object allocator is enabled, these functions aren't aliases of
:c:func:`malloc` and :c:func:`free` any more, and calling the wrong function to
free memory may get you a core dump.  For example, if memory was allocated using
:c:func:`PyObject_Malloc`, it has to be freed using :c:func:`PyObject_Free`, not
:c:func:`free`.  A few modules included with Python fell afoul of this and had to
be fixed; doubtless there are more third-party modules that will have the same
problem.

As part of this change, the confusing multiple interfaces for allocating memory
have been consolidated down into two API families. Memory allocated with one
family must not be manipulated with functions from the other family.  There is
one family for allocating chunks of memory and another family of functions
specifically for allocating Python objects.

* To allocate and free an undistinguished chunk of memory use the "raw memory"
  family: :c:func:`PyMem_Malloc`, :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free`.

* The "object memory" family is the interface to the pymalloc facility described
  above and is biased towards a large number of "small" allocations:
  :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and :c:func:`PyObject_Free`.

* To allocate and free Python objects, use the "object" family
  :c:func:`PyObject_New`, :c:func:`PyObject_NewVar`, and :c:func:`PyObject_Del`.

Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
features to catch memory overwrites and doubled frees in both extension modules
and in the interpreter itself.  To enable this support, compile a debugging
version of the Python interpreter by running :program:`configure` with
:option:`!--with-pydebug`.

To aid extension writers, a header file :file:`Misc/pymemcompat.h` is
distributed with the source to Python 2.3 that allows Python extensions to use
the 2.3 interfaces to memory allocation while compiling against any version of
Python since 1.5.2.  You would copy the file from Python's source distribution
and bundle it with the source of your extension.


.. seealso::

   https://hg.python.org/cpython/file/default/Objects/obmalloc.c
      For the full details of the pymalloc implementation, see the comments at
      the top of the file :file:`Objects/obmalloc.c` in the Python source code.
      The above link points to the file within the python.org SVN browser.

.. ======================================================================


Build and C API Changes
=======================

Changes to Python's build process and to the C API include:

* The cycle detection implementation used by the garbage collection has proven
  to be stable, so it's now been made mandatory.  You can no longer compile Python
  without it, and the :option:`!--with-cycle-gc` switch to :program:`configure` has
  been removed.

* Python can now optionally be built as a shared library
  (:file:`libpython2.3.so`) by supplying :option:`!--enable-shared` when running
  Python's :program:`configure` script.  (Contributed by Ondrej Palkovsky.)

* The :c:macro:`DL_EXPORT` and :c:macro:`DL_IMPORT` macros are now deprecated.
  Initialization functions for Python extension modules should now be declared
  using the new macro :c:macro:`PyMODINIT_FUNC`, while the Python core will
  generally use the :c:macro:`PyAPI_FUNC` and :c:macro:`PyAPI_DATA` macros.

* The interpreter can be compiled without any docstrings for the built-in
  functions and modules by supplying :option:`!--without-doc-strings` to the
  :program:`configure` script. This makes the Python executable about 10% smaller,
  but will also mean that you can't get help for Python's built-ins.  (Contributed
  by Gustavo Niemeyer.)

* The :c:func:`PyArg_NoArgs` macro is now deprecated, and code that uses it
  should be changed.  For Python 2.2 and later, the method definition table can
  specify the :const:`METH_NOARGS` flag, signalling that there are no arguments,
  and the argument checking can then be removed.  If compatibility with pre-2.2
  versions of Python is important, the code could use ``PyArg_ParseTuple(args,
  "")`` instead, but this will be slower than using :const:`METH_NOARGS`.

* :c:func:`PyArg_ParseTuple` accepts new format characters for various sizes of
  unsigned integers: ``B`` for :c:type:`unsigned char`, ``H`` for :c:type:`unsigned
  short int`,  ``I`` for :c:type:`unsigned int`,  and ``K`` for :c:type:`unsigned
  long long`.

* A new function, ``PyObject_DelItemString(mapping, char *key)`` was added
  as shorthand for ``PyObject_DelItem(mapping, PyString_New(key))``.

* File objects now manage their internal string buffer differently, increasing
  it exponentially when needed.  This results in the benchmark tests in
  :file:`Lib/test/test_bufio.py` speeding up considerably (from 57 seconds to 1.7
  seconds, according to one measurement).

* It's now possible to define class and static methods for a C extension type by
  setting either the :const:`METH_CLASS` or :const:`METH_STATIC` flags in a
  method's :c:type:`PyMethodDef` structure.

* Python now includes a copy of the Expat XML parser's source code, removing any
  dependence on a system version or local installation of Expat.

* If you dynamically allocate type objects in your extension, you should be
  aware of a change in the rules relating to the :attr:`__module__` and
  :attr:`~definition.__name__` attributes.  In summary, you will want to ensure the type's
  dictionary contains a ``'__module__'`` key; making the module name the part of
  the type name leading up to the final period will no longer have the desired
  effect.  For more detail, read the API reference documentation or the  source.

.. ======================================================================


Port-Specific Changes
---------------------

Support for a port to IBM's OS/2 using the EMX runtime environment was merged
into the main Python source tree.  EMX is a POSIX emulation layer over the OS/2
system APIs.  The Python port for EMX tries to support all the POSIX-like
capability exposed by the EMX runtime, and mostly succeeds; :func:`fork` and
:func:`fcntl` are restricted by the limitations of the underlying emulation
layer.  The standard OS/2 port, which uses IBM's Visual Age compiler, also
gained support for case-sensitive import semantics as part of the integration of
the EMX port into CVS.  (Contributed by Andrew MacIntyre.)

On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility.  This means that modules will no longer fail to load if a single
routine is missing on the current OS version. Instead calling the missing
routine will raise an exception. (Contributed by Jack Jansen.)

The RPM spec files, found in the :file:`Misc/RPM/` directory in the Python
source distribution, were updated for 2.3.  (Contributed by Sean Reifschneider.)

Other new platforms now supported by Python include AtheOS
(http://atheos.cx/), GNU/Hurd, and OpenVMS.

.. ======================================================================


.. _section-other:

Other Changes and Fixes
=======================

As usual, there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3.  Both
figures are likely to be underestimates.

Some of the more notable changes are:

* If the :envvar:`PYTHONINSPECT` environment variable is set, the Python
  interpreter will enter the interactive prompt after running a Python program, as
  if Python had been invoked with the :option:`-i` option. The environment
  variable can be set before running the Python interpreter, or it can be set by
  the Python program as part of its execution.

* The :file:`regrtest.py` script now provides a way to allow "all resources
  except *foo*."  A resource name passed to the :option:`!-u` option can now be
  prefixed with a hyphen (``'-'``) to mean "remove this resource."  For example,
  the option '``-uall,-bsddb``' could be used to enable the use of all resources
  except ``bsddb``.

* The tools used to build the documentation now work under Cygwin as well as
  Unix.

* The ``SET_LINENO`` opcode has been removed.  Back in the mists of time, this
  opcode was needed to produce line numbers in tracebacks and support trace
  functions (for, e.g., :mod:`pdb`). Since Python 1.5, the line numbers in
  tracebacks have been computed using a different mechanism that works with
  "python -O".  For Python 2.3 Michael Hudson implemented a similar scheme to
  determine when to call the trace function, removing the need for ``SET_LINENO``
  entirely.

  It would be difficult to detect any resulting difference from Python code, apart
  from a slight speed up when Python is run without :option:`-O`.

  C extensions that access the :attr:`f_lineno` field of frame objects should
  instead call ``PyCode_Addr2Line(f->f_code, f->f_lasti)``. This will have the
  added effect of making the code work as desired under "python -O" in earlier
  versions of Python.

  A nifty new feature is that trace functions can now assign to the
  :attr:`f_lineno` attribute of frame objects, changing the line that will be
  executed next.  A ``jump`` command has been added to the :mod:`pdb` debugger
  taking advantage of this new feature. (Implemented by Richie Hindle.)

.. ======================================================================


Porting to Python 2.3
=====================

This section lists previously described changes that may require changes to your
code:

* :keyword:`yield` is now always a keyword; if it's used as a variable name in
  your code, a different name must be chosen.

* For strings *X* and *Y*, ``X in Y`` now works if *X* is more than one
  character long.

* The :func:`int` type constructor will now return a long integer instead of
  raising an :exc:`OverflowError` when a string or floating-point number is too
  large to fit into an integer.

* If you have Unicode strings that contain 8-bit characters, you must declare
  the file's encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
  of the file.  See section :ref:`section-encodings` for more information.

* Calling Tcl methods through :mod:`_tkinter` no longer  returns only strings.
  Instead, if Tcl returns other objects those objects are converted to their
  Python equivalent, if one exists, or wrapped with a :class:`_tkinter.Tcl_Obj`
  object if no Python equivalent exists.

* Large octal and hex literals such as ``0xffffffff`` now trigger a
  :exc:`FutureWarning`. Currently they're stored as 32-bit numbers and result in a
  negative value, but in Python 2.4 they'll become positive long integers.

  There are a few ways to fix this warning.  If you really need a positive number,
  just add an ``L`` to the end of the literal.  If you're trying to get a 32-bit
  integer with low bits set and have previously used an expression such as ``~(1
  << 31)``, it's probably clearest to start with all bits set and clear the
  desired upper bits. For example, to clear just the top bit (bit 31), you could
  write ``0xffffffffL &~(1L<<31)``.

* You can no longer disable assertions by assigning to ``__debug__``.

* The Distutils :func:`setup` function has gained various new keyword arguments
  such as *depends*.  Old versions of the Distutils will abort if passed unknown
  keywords.  A solution is to check for the presence of the new
  :func:`get_distutil_options` function in your :file:`setup.py` and only uses the
  new keywords with a version of the Distutils that supports them::

     from distutils import core

     kw = {'sources': 'foo.c', ...}
     if hasattr(core, 'get_distutil_options'):
         kw['depends'] = ['foo.h']
     ext = Extension(**kw)

* Using ``None`` as a variable name will now result in a :exc:`SyntaxWarning`
  warning.

* Names of extension types defined by the modules included with Python now
  contain the module and a ``'.'`` in front of the type name.

.. ======================================================================


.. _23acks:

Acknowledgements
================

The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Jeff Bauer,
Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
Daniels, Fred L. Drake, Jr., David Fraser,  Kelly Gerber, Raymond Hettinger,
Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
Suzi, Jason Tishler, Just van Rossum.
PK
%�\;�]��"html/_sources/whatsnew/2.4.rst.txtnu�[���****************************
  What's New in Python 2.4
****************************

:Author: A.M. Kuchling

.. |release| replace:: 1.02

.. $Id: whatsnew24.tex 54632 2007-03-31 11:59:54Z georg.brandl $
.. Don't write extensive text for new sections; I'll do that.
.. Feel free to add commented-out reminders of things that need
.. to be covered.  --amk

This article explains the new features in Python 2.4.1, released on March 30,
2005.

Python 2.4 is a medium-sized release.  It doesn't introduce as many changes as
the radical Python 2.2, but introduces more features than the conservative 2.3
release.  The most significant new language features are function decorators and
generator expressions; most other changes are to the standard library.

According to the CVS change logs, there were 481 patches applied and 502 bugs
fixed between Python 2.3 and 2.4.  Both figures are likely to be underestimates.

This article doesn't attempt to provide a complete specification of every single
new feature, but instead provides a brief introduction to each feature.  For
full details, you should refer to the documentation for Python 2.4, such as the
Python Library Reference and the Python Reference Manual.  Often you will be
referred to the PEP for a particular new feature for explanations of the
implementation and design rationale.

.. ======================================================================


PEP 218: Built-In Set Objects
=============================

Python 2.3 introduced the :mod:`sets` module.  C implementations of set data
types have now been added to the Python core as two new built-in types,
``set(iterable)`` and ``frozenset(iterable)``.  They provide high speed
operations for membership testing, for eliminating duplicates from sequences,
and for mathematical operations like unions, intersections, differences, and
symmetric differences. ::

   >>> a = set('abracadabra')              # form a set from a string
   >>> 'z' in a                            # fast membership testing
   False
   >>> a                                   # unique letters in a
   set(['a', 'r', 'b', 'c', 'd'])
   >>> ''.join(a)                          # convert back into a string
   'arbcd'

   >>> b = set('alacazam')                 # form a second set
   >>> a - b                               # letters in a but not in b
   set(['r', 'd', 'b'])
   >>> a | b                               # letters in either a or b
   set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
   >>> a & b                               # letters in both a and b
   set(['a', 'c'])
   >>> a ^ b                               # letters in a or b but not both
   set(['r', 'd', 'b', 'm', 'z', 'l'])

   >>> a.add('z')                          # add a new element
   >>> a.update('wxy')                     # add multiple new elements
   >>> a
   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'x', 'z'])
   >>> a.remove('x')                       # take one element out
   >>> a
   set(['a', 'c', 'b', 'd', 'r', 'w', 'y', 'z'])

The :func:`frozenset` type is an immutable version of :func:`set`. Since it is
immutable and hashable, it may be used as a dictionary key or as a member of
another set.

The :mod:`sets` module remains in the standard library, and may be useful if you
wish to subclass the :class:`Set` or :class:`ImmutableSet` classes.  There are
currently no plans to deprecate the module.


.. seealso::

   :pep:`218` - Adding a Built-In Set Object Type
      Originally proposed by Greg Wilson and ultimately implemented by Raymond
      Hettinger.

.. ======================================================================


PEP 237: Unifying Long Integers and Integers
============================================

The lengthy transition process for this PEP, begun in Python 2.2, takes another
step forward in Python 2.4.  In 2.3, certain integer operations that would
behave differently after int/long unification triggered :exc:`FutureWarning`
warnings and returned values limited to 32 or 64 bits (depending on your
platform).  In 2.4, these expressions no longer produce a warning and instead
produce a different result that's usually a long integer.

The problematic expressions are primarily left shifts and lengthy hexadecimal
and octal constants.  For example, ``2 << 32`` results in a warning in 2.3,
evaluating to 0 on 32-bit platforms.  In Python 2.4, this expression now returns
the correct answer, 8589934592.


.. seealso::

   :pep:`237` - Unifying Long Integers and Integers
      Original PEP written by Moshe Zadka and GvR.  The changes for 2.4 were
      implemented by  Kalle Svensson.

.. ======================================================================


PEP 289: Generator Expressions
==============================

The iterator feature introduced in Python 2.2 and the :mod:`itertools` module
make it easier to write programs that loop through large data sets without
having the entire data set in memory at one time.  List comprehensions don't fit
into this picture very well because they produce a Python list object containing
all of the items.  This unavoidably pulls all of the objects into memory, which
can be a problem if your data set is very large.  When trying to write a
functionally-styled program, it would be natural to write something like::

   links = [link for link in get_all_links() if not link.followed]
   for link in links:
       ...

instead of  ::

   for link in get_all_links():
       if link.followed:
           continue
       ...

The first form is more concise and perhaps more readable, but if you're dealing
with a large number of link objects you'd have to write the second form to avoid
having all link objects in memory at the same time.

Generator expressions work similarly to list comprehensions but don't
materialize the entire list; instead they create a generator that will return
elements one by one.  The above example could be written as::

   links = (link for link in get_all_links() if not link.followed)
   for link in links:
       ...

Generator expressions always have to be written inside parentheses, as in the
above example.  The parentheses signalling a function call also count, so if you
want to create an iterator that will be immediately passed to a function you
could write::

   print sum(obj.count for obj in list_all_objects())

Generator expressions differ from list comprehensions in various small ways.
Most notably, the loop variable (*obj* in the above example) is not accessible
outside of the generator expression.  List comprehensions leave the variable
assigned to its last value; future versions of Python will change this, making
list comprehensions match generator expressions in this respect.


.. seealso::

   :pep:`289` - Generator Expressions
      Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts
      steered by Hye-Shik Chang.

.. ======================================================================


PEP 292: Simpler String Substitutions
=====================================

Some new classes in the standard library provide an alternative mechanism for
substituting variables into strings; this style of substitution may be better
for applications where untrained users need to edit templates.

The usual way of substituting variables by name is the ``%`` operator::

   >>> '%(page)i: %(title)s' % {'page':2, 'title': 'The Best of Times'}
   '2: The Best of Times'

When writing the template string, it can be easy to forget the ``i`` or ``s``
after the closing parenthesis.  This isn't a big problem if the template is in a
Python module, because you run the code, get an "Unsupported format character"
:exc:`ValueError`, and fix the problem.  However, consider an application such
as Mailman where template strings or translations are being edited by users who
aren't aware of the Python language.  The format string's syntax is complicated
to explain to such users, and if they make a mistake, it's difficult to provide
helpful feedback to them.

PEP 292 adds a :class:`Template` class to the :mod:`string` module that uses
``$`` to indicate a substitution::

   >>> import string
   >>> t = string.Template('$page: $title')
   >>> t.substitute({'page':2, 'title': 'The Best of Times'})
   '2: The Best of Times'

If a key is missing from the dictionary, the :meth:`substitute` method will
raise a :exc:`KeyError`.  There's also a :meth:`safe_substitute` method that
ignores missing keys::

   >>> t = string.Template('$page: $title')
   >>> t.safe_substitute({'page':3})
   '3: $title'


.. seealso::

   :pep:`292` - Simpler String Substitutions
      Written and implemented  by Barry Warsaw.

.. ======================================================================


PEP 318: Decorators for Functions and Methods
=============================================

Python 2.2 extended Python's object model by adding static methods and class
methods, but it didn't extend Python's syntax to provide any new way of defining
static or class methods.  Instead, you had to write a :keyword:`def` statement
in the usual way, and pass the resulting method to a :func:`staticmethod` or
:func:`classmethod` function that would wrap up the function as a method of the
new type. Your code would look like this::

   class C:
      def meth (cls):
          ...

      meth = classmethod(meth)   # Rebind name to wrapped-up class method

If the method was very long, it would be easy to miss or forget the
:func:`classmethod` invocation after the function body.

The intention was always to add some syntax to make such definitions more
readable, but at the time of 2.2's release a good syntax was not obvious.  Today
a good syntax *still* isn't obvious but users are asking for easier access to
the feature; a new syntactic feature has been added to meet this need.

The new feature is called "function decorators".  The name comes from the idea
that :func:`classmethod`, :func:`staticmethod`, and friends are storing
additional information on a function object; they're *decorating* functions with
more details.

The notation borrows from Java and uses the ``'@'`` character as an indicator.
Using the new syntax, the example above would be written::

   class C:

      @classmethod
      def meth (cls):
          ...


The ``@classmethod`` is shorthand for the ``meth=classmethod(meth)`` assignment.
More generally, if you have the following::

   @A
   @B
   @C
   def f ():
       ...

It's equivalent to the following pre-decorator code::

   def f(): ...
   f = A(B(C(f)))

Decorators must come on the line before a function definition, one decorator per
line, and can't be on the same line as the def statement, meaning that ``@A def
f(): ...`` is illegal.  You can only decorate function definitions, either at
the module level or inside a class; you can't decorate class definitions.

A decorator is just a function that takes the function to be decorated as an
argument and returns either the same function or some new object.  The return
value of the decorator need not be callable (though it typically is), unless
further decorators will be applied to the result.  It's easy to write your own
decorators.  The following simple example just sets an attribute on the function
object::

   >>> def deco(func):
   ...    func.attr = 'decorated'
   ...    return func
   ...
   >>> @deco
   ... def f(): pass
   ...
   >>> f
   <function f at 0x402ef0d4>
   >>> f.attr
   'decorated'
   >>>

As a slightly more realistic example, the following decorator checks that the
supplied argument is an integer::

   def require_int (func):
       def wrapper (arg):
           assert isinstance(arg, int)
           return func(arg)

       return wrapper

   @require_int
   def p1 (arg):
       print arg

   @require_int
   def p2(arg):
       print arg*2

An example in :pep:`318` contains a fancier version of this idea that lets you
both specify the required type and check the returned type.

Decorator functions can take arguments.  If arguments are supplied, your
decorator function is called with only those arguments and must return a new
decorator function; this function must take a single function and return a
function, as previously described.  In other words, ``@A @B @C(args)`` becomes::

   def f(): ...
   _deco = C(args)
   f = A(B(_deco(f)))

Getting this right can be slightly brain-bending, but it's not too difficult.

A small related change makes the :attr:`func_name` attribute of functions
writable.  This attribute is used to display function names in tracebacks, so
decorators should change the name of any new function that's constructed and
returned.


.. seealso::

   :pep:`318` - Decorators for Functions, Methods and Classes
      Written  by Kevin D. Smith, Jim Jewett, and Skip Montanaro.  Several people
      wrote patches implementing function decorators, but the one that was actually
      checked in was patch #979728, written by Mark Russell.

   https://wiki.python.org/moin/PythonDecoratorLibrary
      This Wiki page contains several examples of decorators.

.. ======================================================================


PEP 322: Reverse Iteration
==========================

A new built-in function, ``reversed(seq)``, takes a sequence and returns an
iterator that loops over the elements of the sequence  in reverse order.   ::

   >>> for i in reversed(xrange(1,4)):
   ...    print i
   ...
   3
   2
   1

Compared to extended slicing, such as ``range(1,4)[::-1]``, :func:`reversed` is
easier to read, runs faster, and uses substantially less memory.

Note that :func:`reversed` only accepts sequences, not arbitrary iterators.  If
you want to reverse an iterator, first convert it to  a list with :func:`list`.
::

   >>> input = open('/etc/passwd', 'r')
   >>> for line in reversed(list(input)):
   ...   print line
   ...
   root:*:0:0:System Administrator:/var/root:/bin/tcsh
     ...


.. seealso::

   :pep:`322` - Reverse Iteration
      Written and implemented by Raymond Hettinger.

.. ======================================================================


PEP 324: New subprocess Module
==============================

The standard library provides a number of ways to execute a subprocess, offering
different features and different levels of complexity.
``os.system(command)`` is easy to use, but slow (it runs a shell process
which executes the command) and dangerous (you have to be careful about escaping
the shell's metacharacters).  The :mod:`popen2` module offers classes that can
capture standard output and standard error from the subprocess, but the naming
is confusing.  The :mod:`subprocess` module cleans  this up, providing a unified
interface that offers all the features you might need.

Instead of :mod:`popen2`'s collection of classes, :mod:`subprocess` contains a
single class called :class:`Popen`  whose constructor supports a number of
different keyword arguments. ::

   class Popen(args, bufsize=0, executable=None,
               stdin=None, stdout=None, stderr=None,
               preexec_fn=None, close_fds=False, shell=False,
               cwd=None, env=None, universal_newlines=False,
               startupinfo=None, creationflags=0):

*args* is commonly a sequence of strings that will be the arguments to the
program executed as the subprocess.  (If the *shell* argument is true, *args*
can be a string which will then be passed on to the shell for interpretation,
just as :func:`os.system` does.)

*stdin*, *stdout*, and *stderr* specify what the subprocess's input, output, and
error streams will be.  You can provide a file object or a file descriptor, or
you can use the constant ``subprocess.PIPE`` to create a pipe between the
subprocess and the parent.

.. index::
   single: universal newlines; What's new

The constructor has a number of handy options:

* *close_fds* requests that all file descriptors be closed before running the
  subprocess.

* *cwd* specifies the working directory in which the subprocess will be executed
  (defaulting to whatever the parent's working directory is).

* *env* is a dictionary specifying environment variables.

* *preexec_fn* is a function that gets called before the child is started.

* *universal_newlines* opens the child's input and output using Python's
  :term:`universal newlines` feature.

Once you've created the :class:`Popen` instance,  you can call its :meth:`wait`
method to pause until the subprocess has exited, :meth:`poll` to check if it's
exited without pausing,  or ``communicate(data)`` to send the string *data*
to the subprocess's standard input.   ``communicate(data)``  then reads any
data that the subprocess has sent to its standard output  or standard error,
returning a tuple ``(stdout_data, stderr_data)``.

:func:`call` is a shortcut that passes its arguments along to the :class:`Popen`
constructor, waits for the command to complete, and returns the status code of
the subprocess.  It can serve as a safer analog to :func:`os.system`::

   sts = subprocess.call(['dpkg', '-i', '/tmp/new-package.deb'])
   if sts == 0:
       # Success
       ...
   else:
       # dpkg returned an error
       ...

The command is invoked without use of the shell.  If you really do want to  use
the shell, you can add ``shell=True`` as a keyword argument and provide a string
instead of a sequence::

   sts = subprocess.call('dpkg -i /tmp/new-package.deb', shell=True)

The PEP takes various examples of shell and Python code and shows how they'd be
translated into Python code that uses :mod:`subprocess`.  Reading this section
of the PEP is highly recommended.


.. seealso::

   :pep:`324` - subprocess - New process module
      Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and
      others.

.. ======================================================================


PEP 327: Decimal Data Type
==========================

Python has always supported floating-point (FP) numbers, based on the underlying
C :c:type:`double` type, as a data type.  However, while most programming
languages provide a floating-point type, many people (even programmers) are
unaware that floating-point numbers don't represent certain decimal fractions
accurately.  The new :class:`Decimal` type can represent these fractions
accurately, up to a user-specified precision limit.


Why is Decimal needed?
----------------------

The limitations arise from the representation used for floating-point numbers.
FP numbers are made up of three components:

* The sign, which is positive or negative.

* The mantissa, which is a single-digit binary number   followed by a fractional
  part.  For example, ``1.01`` in base-2 notation is ``1 + 0/2 + 1/4``, or 1.25 in
  decimal notation.

* The exponent, which tells where the decimal point is located in the number
  represented.

For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in
binary), and an exponent of 0 (the decimal point doesn't need to be shifted).
The number 5 has the same sign and mantissa, but the exponent is 2 because the
mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 \* 4 equals
5.

Modern systems usually provide floating-point support that conforms to a
standard called IEEE 754.  C's :c:type:`double` type is usually implemented as a
64-bit IEEE 754 number, which uses 52 bits of space for the mantissa.  This
means that numbers can only be specified to 52 bits of precision.  If you're
trying to represent numbers whose expansion repeats endlessly, the expansion is
cut off after 52 bits. Unfortunately, most software needs to produce output in
base 10, and common fractions in base 10 are often repeating decimals in binary.
For example, 1.1 decimal is binary ``1.0001100110011 ...``; .1 = 1/16 + 1/32 +
1/256 plus an infinite number of additional terms.  IEEE 754 has to chop off
that infinitely repeated decimal after 52 digits, so the representation is
slightly inaccurate.

Sometimes you can see this inaccuracy when the number is printed::

   >>> 1.1
   1.1000000000000001

The inaccuracy isn't always visible when you print the number because the
FP-to-decimal-string conversion is provided by the C library, and most C libraries try
to produce sensible output.  Even if it's not displayed, however, the inaccuracy
is still there and subsequent operations can magnify the error.

For many applications this doesn't matter.  If I'm plotting points and
displaying them on my monitor, the difference between 1.1 and 1.1000000000000001
is too small to be visible.  Reports often limit output to a certain number of
decimal places, and if you round the number to two or three or even eight
decimal places, the error is never apparent.  However, for applications where it
does matter,  it's a lot of work to implement your own custom arithmetic
routines.

Hence, the :class:`Decimal` type was created.


The :class:`Decimal` type
-------------------------

A new module, :mod:`decimal`, was added to Python's standard library.  It
contains two classes, :class:`Decimal` and :class:`Context`.  :class:`Decimal`
instances represent numbers, and :class:`Context` instances are used to wrap up
various settings such as the precision and default rounding mode.

:class:`Decimal` instances are immutable, like regular Python integers and FP
numbers; once it's been created, you can't change the value an instance
represents.  :class:`Decimal` instances can be created from integers or
strings::

   >>> import decimal
   >>> decimal.Decimal(1972)
   Decimal("1972")
   >>> decimal.Decimal("1.1")
   Decimal("1.1")

You can also provide tuples containing the sign, the mantissa represented  as a
tuple of decimal digits, and the exponent::

   >>> decimal.Decimal((1, (1, 4, 7, 5), -2))
   Decimal("-14.75")

Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is
negative.

Converting from floating-point numbers poses a bit of a problem: should the FP
number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1
plus whatever inaccuracies are introduced? The decision was to dodge the issue
and leave such a conversion out of the API.  Instead, you should convert the
floating-point number into a string using the desired precision and pass the
string to the :class:`Decimal` constructor::

   >>> f = 1.1
   >>> decimal.Decimal(str(f))
   Decimal("1.1")
   >>> decimal.Decimal('%.12f' % f)
   Decimal("1.100000000000")

Once you have :class:`Decimal` instances, you can perform the usual mathematical
operations on them.  One limitation: exponentiation requires an integer
exponent::

   >>> a = decimal.Decimal('35.72')
   >>> b = decimal.Decimal('1.73')
   >>> a+b
   Decimal("37.45")
   >>> a-b
   Decimal("33.99")
   >>> a*b
   Decimal("61.7956")
   >>> a/b
   Decimal("20.64739884393063583815028902")
   >>> a ** 2
   Decimal("1275.9184")
   >>> a**b
   Traceback (most recent call last):
     ...
   decimal.InvalidOperation: x ** (non-integer)

You can combine :class:`Decimal` instances with integers, but not with
floating-point numbers::

   >>> a + 4
   Decimal("39.72")
   >>> a + 4.5
   Traceback (most recent call last):
     ...
   TypeError: You can interact Decimal only with int, long or Decimal data types.
   >>>

:class:`Decimal` numbers can be used with the :mod:`math` and :mod:`cmath`
modules, but note that they'll be immediately converted to  floating-point
numbers before the operation is performed, resulting in a possible loss of
precision and accuracy.  You'll also get back a regular floating-point number
and not a :class:`Decimal`.   ::

   >>> import math, cmath
   >>> d = decimal.Decimal('123456789012.345')
   >>> math.sqrt(d)
   351364.18288201344
   >>> cmath.sqrt(-d)
   351364.18288201344j

:class:`Decimal` instances have a :meth:`sqrt` method that returns a
:class:`Decimal`, but if you need other things such as trigonometric functions
you'll have to implement them. ::

   >>> d.sqrt()
   Decimal("351364.1828820134592177245001")


The :class:`Context` type
-------------------------

Instances of the :class:`Context` class encapsulate several settings for
decimal operations:

* :attr:`prec` is the precision, the number of decimal places.

* :attr:`rounding` specifies the rounding mode.  The :mod:`decimal` module has
  constants for the various possibilities: :const:`ROUND_DOWN`,
  :const:`ROUND_CEILING`,  :const:`ROUND_HALF_EVEN`, and various others.

* :attr:`traps` is a dictionary specifying what happens on encountering certain
  error conditions: either  an exception is raised or  a value is returned.  Some
  examples of error conditions are division by zero, loss of precision, and
  overflow.

There's a thread-local default context available by calling :func:`getcontext`;
you can change the properties of this context to alter the default precision,
rounding, or trap handling.  The following example shows the effect of changing
the precision of the default context::

   >>> decimal.getcontext().prec
   28
   >>> decimal.Decimal(1) / decimal.Decimal(7)
   Decimal("0.1428571428571428571428571429")
   >>> decimal.getcontext().prec = 9
   >>> decimal.Decimal(1) / decimal.Decimal(7)
   Decimal("0.142857143")

The default action for error conditions is selectable; the module can either
return a special value such as infinity or not-a-number, or exceptions can be
raised::

   >>> decimal.Decimal(1) / decimal.Decimal(0)
   Traceback (most recent call last):
     ...
   decimal.DivisionByZero: x / 0
   >>> decimal.getcontext().traps[decimal.DivisionByZero] = False
   >>> decimal.Decimal(1) / decimal.Decimal(0)
   Decimal("Infinity")
   >>>

The :class:`Context` instance also has various methods for formatting  numbers
such as :meth:`to_eng_string` and :meth:`to_sci_string`.

For more information, see the documentation for the :mod:`decimal` module, which
includes a quick-start tutorial and a reference.


.. seealso::

   :pep:`327` - Decimal Data Type
      Written by Facundo Batista and implemented by Facundo Batista, Eric Price,
      Raymond Hettinger, Aahz, and Tim Peters.

   http://www.lahey.com/float.htm
      The article uses Fortran code to illustrate many of the problems that
      floating-point inaccuracy can cause.

   http://speleotrove.com/decimal/
      A description of a decimal-based representation.  This representation is being
      proposed as a standard, and underlies the new Python decimal type.  Much of this
      material was written by Mike Cowlishaw, designer of the Rexx language.

.. ======================================================================


PEP 328: Multi-line Imports
===========================

One language change is a small syntactic tweak aimed at making it easier to
import many names from a module.  In a ``from module import names`` statement,
*names* is a sequence of names separated by commas.  If the sequence is  very
long, you can either write multiple imports from the same module, or you can use
backslashes to escape the line endings like this::

   from SimpleXMLRPCServer import SimpleXMLRPCServer,\
               SimpleXMLRPCRequestHandler,\
               CGIXMLRPCRequestHandler,\
               resolve_dotted_attribute

The syntactic change in Python 2.4 simply allows putting the names within
parentheses.  Python ignores newlines within a parenthesized expression, so the
backslashes are no longer needed::

   from SimpleXMLRPCServer import (SimpleXMLRPCServer,
                                   SimpleXMLRPCRequestHandler,
                                   CGIXMLRPCRequestHandler,
                                   resolve_dotted_attribute)

The PEP also proposes that all :keyword:`import` statements be absolute imports,
with a leading ``.`` character to indicate a relative import.  This part of the
PEP was not implemented for Python 2.4, but was completed for Python 2.5.


.. seealso::

   :pep:`328` - Imports: Multi-Line and Absolute/Relative
      Written by Aahz.  Multi-line imports were implemented by Dima Dorfman.

.. ======================================================================


PEP 331: Locale-Independent Float/String Conversions
====================================================

The :mod:`locale` modules lets Python software select various conversions and
display conventions that are localized to a particular country or language.
However, the module was careful to not change the numeric locale because various
functions in Python's implementation required that the numeric locale remain set
to the ``'C'`` locale.  Often this was because the code was using the C
library's :c:func:`atof` function.

Not setting the numeric locale caused trouble for extensions that used third-party
C libraries, however, because they wouldn't have the correct locale set.
The motivating example was GTK+, whose user interface widgets weren't displaying
numbers in the current locale.

The solution described in the PEP is to add three new functions to the Python
API that perform ASCII-only conversions, ignoring the locale setting:

* ``PyOS_ascii_strtod(str, ptr)``  and ``PyOS_ascii_atof(str, ptr)``
  both convert a string to a C :c:type:`double`.

* ``PyOS_ascii_formatd(buffer, buf_len, format, d)`` converts a
  :c:type:`double` to an ASCII string.

The code for these functions came from the GLib library
(https://developer.gnome.org/glib/stable/), whose developers kindly
relicensed the relevant functions and donated them to the Python Software
Foundation.  The :mod:`locale` module  can now change the numeric locale,
letting extensions such as GTK+  produce the correct results.


.. seealso::

   :pep:`331` - Locale-Independent Float/String Conversions
      Written by Christian R. Reis, and implemented by Gustavo Carneiro.

.. ======================================================================


Other Language Changes
======================

Here are all of the changes that Python 2.4 makes to the core Python language.

* Decorators for functions and methods were added (:pep:`318`).

* Built-in :func:`set` and :func:`frozenset` types were  added (:pep:`218`).
  Other new built-ins include the ``reversed(seq)`` function (:pep:`322`).

* Generator expressions were added (:pep:`289`).

* Certain numeric expressions no longer return values restricted to 32 or 64
  bits (:pep:`237`).

* You can now put parentheses around the list of names in a ``from module import
  names`` statement (:pep:`328`).

* The :meth:`dict.update` method now accepts the same argument forms as the
  :class:`dict` constructor.  This includes any mapping, any iterable of key/value
  pairs, and keyword arguments. (Contributed by Raymond Hettinger.)

* The string methods :meth:`ljust`, :meth:`rjust`, and :meth:`center` now take
  an optional argument for specifying a fill character other than a space.
  (Contributed by Raymond Hettinger.)

* Strings also gained an :meth:`rsplit` method that works like the :meth:`split`
  method but splits from the end of the string.   (Contributed by Sean
  Reifschneider.) ::

     >>> 'www.python.org'.split('.', 1)
     ['www', 'python.org']
     'www.python.org'.rsplit('.', 1)
     ['www.python', 'org']

* Three keyword parameters, *cmp*, *key*, and *reverse*, were added to the
  :meth:`sort` method of lists. These parameters make some common usages of
  :meth:`sort` simpler. All of these parameters are optional.

  For the *cmp* parameter, the value should be a comparison function that takes
  two parameters and returns -1, 0, or +1 depending on how the parameters compare.
  This function will then be used to sort the list.  Previously this was the only
  parameter that could be provided to :meth:`sort`.

  *key* should be a single-parameter function that takes a list element and
  returns a comparison key for the element.  The list is then sorted using the
  comparison keys.  The following example sorts a list case-insensitively::

     >>> L = ['A', 'b', 'c', 'D']
     >>> L.sort()                 # Case-sensitive sort
     >>> L
     ['A', 'D', 'b', 'c']
     >>> # Using 'key' parameter to sort list
     >>> L.sort(key=lambda x: x.lower())
     >>> L
     ['A', 'b', 'c', 'D']
     >>> # Old-fashioned way
     >>> L.sort(cmp=lambda x,y: cmp(x.lower(), y.lower()))
     >>> L
     ['A', 'b', 'c', 'D']

  The last example, which uses the *cmp* parameter, is the old way to perform a
  case-insensitive sort.  It works but is slower than using a *key* parameter.
  Using *key* calls :meth:`lower` method once for each element in the list while
  using *cmp* will call it twice for each comparison, so using *key* saves on
  invocations of the :meth:`lower` method.

  For simple key functions and comparison functions, it is often possible to avoid
  a :keyword:`lambda` expression by using an unbound method instead.  For example,
  the above case-insensitive sort is best written as::

     >>> L.sort(key=str.lower)
     >>> L
     ['A', 'b', 'c', 'D']

  Finally, the *reverse* parameter takes a Boolean value.  If the value is true,
  the list will be sorted into reverse order. Instead of ``L.sort();
  L.reverse()``, you can now write ``L.sort(reverse=True)``.

  The results of sorting are now guaranteed to be stable.  This means that two
  entries with equal keys will be returned in the same order as they were input.
  For example, you can sort a list of people by name, and then sort the list by
  age, resulting in a list sorted by age where people with the same age are in
  name-sorted order.

  (All changes to :meth:`sort` contributed by Raymond Hettinger.)

* There is a new built-in function ``sorted(iterable)`` that works like the
  in-place :meth:`list.sort` method but can be used in expressions.  The
  differences are:

* the input may be any iterable;

* a newly formed copy is sorted, leaving the original intact; and

* the expression returns the new sorted copy

  ::

     >>> L = [9,7,8,3,2,4,1,6,5]
     >>> [10+i for i in sorted(L)]       # usable in a list comprehension
     [11, 12, 13, 14, 15, 16, 17, 18, 19]
     >>> L                               # original is left unchanged
     [9,7,8,3,2,4,1,6,5]
     >>> sorted('Monty Python')          # any iterable may be an input
     [' ', 'M', 'P', 'h', 'n', 'n', 'o', 'o', 't', 't', 'y', 'y']

     >>> # List the contents of a dict sorted by key values
     >>> colormap = dict(red=1, blue=2, green=3, black=4, yellow=5)
     >>> for k, v in sorted(colormap.iteritems()):
     ...     print k, v
     ...
     black 4
     blue 2
     green 3
     red 1
     yellow 5

  (Contributed by Raymond Hettinger.)

* Integer operations will no longer trigger an :exc:`OverflowWarning`. The
  :exc:`OverflowWarning` warning will disappear in Python 2.5.

* The interpreter gained a new switch, :option:`-m`, that takes a name, searches
  for the corresponding  module on ``sys.path``, and runs the module as a script.
  For example,  you can now run the Python profiler with ``python -m profile``.
  (Contributed by Nick Coghlan.)

* The ``eval(expr, globals, locals)`` and ``execfile(filename, globals,
  locals)`` functions and the :keyword:`exec` statement now accept any mapping type
  for the *locals* parameter.  Previously this had to be a regular Python
  dictionary.  (Contributed by Raymond Hettinger.)

* The :func:`zip` built-in function and :func:`itertools.izip` now return an
  empty list if called with no arguments. Previously they raised a
  :exc:`TypeError` exception.  This makes them more suitable for use with variable
  length argument lists::

     >>> def transpose(array):
     ...    return zip(*array)
     ...
     >>> transpose([(1,2,3), (4,5,6)])
     [(1, 4), (2, 5), (3, 6)]
     >>> transpose([])
     []

  (Contributed by Raymond Hettinger.)

* Encountering a failure while importing a module no longer leaves a partially-initialized
  module object in ``sys.modules``.  The incomplete module object left
  behind would fool further imports of the same module into succeeding, leading to
  confusing errors.   (Fixed by Tim Peters.)

* :const:`None` is now a constant; code that binds a new value to  the name
  ``None`` is now a syntax error. (Contributed by Raymond Hettinger.)

.. ======================================================================


Optimizations
-------------

* The inner loops for list and tuple slicing were optimized and now run about
  one-third faster.  The inner loops for dictionaries were also optimized,
  resulting in performance boosts for :meth:`keys`, :meth:`values`, :meth:`items`,
  :meth:`iterkeys`, :meth:`itervalues`, and :meth:`iteritems`. (Contributed by
  Raymond Hettinger.)

* The machinery for growing and shrinking lists was optimized for speed and for
  space efficiency.  Appending and popping from lists now runs faster due to more
  efficient code paths and less frequent use of the underlying system
  :c:func:`realloc`.  List comprehensions also benefit.   :meth:`list.extend` was
  also optimized and no longer converts its argument into a temporary list before
  extending the base list.  (Contributed by Raymond Hettinger.)

* :func:`list`, :func:`tuple`, :func:`map`, :func:`filter`, and :func:`zip` now
  run several times faster with non-sequence arguments that supply a
  :meth:`__len__` method.  (Contributed by Raymond Hettinger.)

* The methods :meth:`list.__getitem__`, :meth:`dict.__getitem__`, and
  :meth:`dict.__contains__` are now implemented as :class:`method_descriptor`
  objects rather than :class:`wrapper_descriptor` objects.  This form of  access
  doubles their performance and makes them more suitable for use as arguments to
  functionals: ``map(mydict.__getitem__, keylist)``. (Contributed by Raymond
  Hettinger.)

* Added a new opcode, ``LIST_APPEND``, that simplifies the generated bytecode
  for list comprehensions and speeds them up by about a third.  (Contributed by
  Raymond Hettinger.)

* The peephole bytecode optimizer has been improved to  produce shorter, faster
  bytecode; remarkably, the resulting bytecode is  more readable.  (Enhanced by
  Raymond Hettinger.)

* String concatenations in statements of the form ``s = s + "abc"`` and ``s +=
  "abc"`` are now performed more efficiently in certain circumstances.  This
  optimization won't be present in other Python implementations such as Jython, so
  you shouldn't rely on it; using the :meth:`join` method of strings is still
  recommended when you want to efficiently glue a large number of strings
  together. (Contributed by Armin Rigo.)

The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
(pystone is not a particularly good benchmark, but it's the most commonly used
measurement of Python's performance.  Your own applications may show greater or
smaller benefits from Python 2.4.)

.. pystone is almost useless for comparing different versions of Python;
   instead, it excels at predicting relative Python performance on different
   machines.  So, this section would be more informative if it used other tools
   such as pybench and parrotbench.  For a more application oriented benchmark,
   try comparing the timings of test_decimal.py under 2.3 and 2.4.

.. ======================================================================


New, Improved, and Deprecated Modules
=====================================

As usual, Python's standard library received a number of enhancements and bug
fixes.  Here's a partial list of the most notable changes, sorted alphabetically
by module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.

* The :mod:`asyncore` module's :func:`loop` function now has a *count* parameter
  that lets you perform a limited number of passes through the polling loop.  The
  default is still to loop forever.

* The :mod:`base64` module now has more complete RFC 3548 support for Base64,
  Base32, and Base16 encoding and decoding, including optional case folding and
  optional alternative alphabets. (Contributed by Barry Warsaw.)

* The :mod:`bisect` module now has an underlying C implementation for improved
  performance. (Contributed by Dmitry Vasiliev.)

* The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang,
  was integrated into 2.4.   The new encodings are:

* Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz

* Chinese (ROC): big5, cp950

* Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,
    iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
    shift-jis, shift-jisx0213, shift-jis-2004

* Korean: cp949, euc-kr, johab, iso-2022-kr

* Some other new encodings were added: HP Roman8,  ISO_8859-11, ISO_8859-16,
  PCTP-154, and TIS-620.

* The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
  Previously the :class:`StreamReader` class would try to read more data, making
  it impossible to resume decoding from the stream.  The :meth:`read` method will
  now return as much data as it can and future calls will resume decoding where
  previous ones left off.  (Implemented by Walter Dörwald.)

* There is a new :mod:`collections` module for  various specialized collection
  datatypes.  Currently it contains just one type, :class:`deque`, a double-ended
  queue that supports efficiently adding and removing elements from either
  end::

     >>> from collections import deque
     >>> d = deque('ghi')        # make a new deque with three items
     >>> d.append('j')           # add a new entry to the right side
     >>> d.appendleft('f')       # add a new entry to the left side
     >>> d                       # show the representation of the deque
     deque(['f', 'g', 'h', 'i', 'j'])
     >>> d.pop()                 # return and remove the rightmost item
     'j'
     >>> d.popleft()             # return and remove the leftmost item
     'f'
     >>> list(d)                 # list the contents of the deque
     ['g', 'h', 'i']
     >>> 'h' in d                # search the deque
     True

  Several modules, such as the :mod:`Queue` and :mod:`threading` modules, now take
  advantage of :class:`collections.deque` for improved performance.  (Contributed
  by Raymond Hettinger.)

* The :mod:`ConfigParser` classes have been enhanced slightly. The :meth:`read`
  method now returns a list of the files that were successfully parsed, and the
  :meth:`set` method raises :exc:`TypeError` if passed a *value* argument that
  isn't a string.   (Contributed by John Belmonte and David Goodger.)

* The :mod:`curses` module now supports the ncurses extension
  :func:`use_default_colors`.  On platforms where the terminal supports
  transparency, this makes it possible to use a transparent background.
  (Contributed by Jörg Lehmann.)

* The :mod:`difflib` module now includes an :class:`HtmlDiff` class that creates
  an HTML table showing a side by side comparison of two versions of a text.
  (Contributed by Dan Gass.)

* The :mod:`email` package was updated to version 3.0,  which dropped various
  deprecated APIs and removes support for Python versions earlier than 2.3.  The
  3.0 version of the package uses a new incremental parser for MIME messages,
  available in the :mod:`email.FeedParser` module.  The new parser doesn't require
  reading the entire message into memory, and doesn't raise exceptions if a
  message is malformed; instead it records any problems in the  :attr:`defect`
  attribute of the message.  (Developed by Anthony Baxter, Barry Warsaw, Thomas
  Wouters, and others.)

* The :mod:`heapq` module has been converted to C.  The resulting tenfold
  improvement in speed makes the module suitable for handling high volumes of
  data.  In addition, the module has two new functions :func:`nlargest` and
  :func:`nsmallest` that use heaps to find the N largest or smallest values in a
  dataset without the expense of a full sort.  (Contributed by Raymond Hettinger.)

* The :mod:`httplib` module now contains constants for HTTP status codes defined
  in various HTTP-related RFC documents.  Constants have names such as
  :const:`OK`, :const:`CREATED`, :const:`CONTINUE`, and
  :const:`MOVED_PERMANENTLY`; use pydoc to get a full list.  (Contributed by
  Andrew Eland.)

* The :mod:`imaplib` module now supports IMAP's THREAD command (contributed by
  Yves Dionne) and new :meth:`deleteacl` and :meth:`myrights` methods (contributed
  by Arnaud Mazin).

* The :mod:`itertools` module gained a ``groupby(iterable[, *func*])``
  function. *iterable* is something that can be iterated over to return a stream
  of elements, and the optional *func* parameter is a function that takes an
  element and returns a key value; if omitted, the key is simply the element
  itself.  :func:`groupby` then groups the elements into subsequences which have
  matching values of the key, and returns a series of 2-tuples containing the key
  value and an iterator over the subsequence.

  Here's an example to make this clearer.  The *key* function simply returns
  whether a number is even or odd, so the result of :func:`groupby` is to return
  consecutive runs of odd or even numbers. ::

     >>> import itertools
     >>> L = [2, 4, 6, 7, 8, 9, 11, 12, 14]
     >>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
     ...    print key_val, list(it)
     ...
     0 [2, 4, 6]
     1 [7]
     0 [8]
     1 [9, 11]
     0 [12, 14]
     >>>

  :func:`groupby` is typically used with sorted input.  The logic for
  :func:`groupby` is similar to the Unix ``uniq`` filter which makes it handy for
  eliminating, counting, or identifying duplicate elements::

     >>> word = 'abracadabra'
     >>> letters = sorted(word)   # Turn string into a sorted list of letters
     >>> letters
     ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'c', 'd', 'r', 'r']
     >>> for k, g in itertools.groupby(letters):
     ...    print k, list(g)
     ...
     a ['a', 'a', 'a', 'a', 'a']
     b ['b', 'b']
     c ['c']
     d ['d']
     r ['r', 'r']
     >>> # List unique letters
     >>> [k for k, g in groupby(letters)]
     ['a', 'b', 'c', 'd', 'r']
     >>> # Count letter occurrences
     >>> [(k, len(list(g))) for k, g in groupby(letters)]
     [('a', 5), ('b', 2), ('c', 1), ('d', 1), ('r', 2)]

  (Contributed by Hye-Shik Chang.)

* :mod:`itertools` also gained a function named ``tee(iterator, N)`` that
  returns *N* independent iterators that replicate *iterator*.  If *N* is omitted,
  the default is 2. ::

     >>> L = [1,2,3]
     >>> i1, i2 = itertools.tee(L)
     >>> i1,i2
     (<itertools.tee object at 0x402c2080>, <itertools.tee object at 0x402c2090>)
     >>> list(i1)               # Run the first iterator to exhaustion
     [1, 2, 3]
     >>> list(i2)               # Run the second iterator to exhaustion
     [1, 2, 3]

  Note that :func:`tee` has to keep copies of the values returned  by the
  iterator; in the worst case, it may need to keep all of them.   This should
  therefore be used carefully if the leading iterator can run far ahead of the
  trailing iterator in a long stream of inputs. If the separation is large, then
  you might as well use  :func:`list` instead.  When the iterators track closely
  with one another, :func:`tee` is ideal.  Possible applications include
  bookmarking, windowing, or lookahead iterators. (Contributed by Raymond
  Hettinger.)

* A number of functions were added to the :mod:`locale`  module, such as
  :func:`bind_textdomain_codeset` to specify a particular encoding and a family of
  :func:`l\*gettext` functions that return messages in the chosen encoding.
  (Contributed by Gustavo Niemeyer.)

* Some keyword arguments were added to the :mod:`logging` package's
  :func:`basicConfig` function to simplify log configuration.  The default
  behavior is to log messages to standard error, but various keyword arguments can
  be specified to log to a particular file, change the logging format, or set the
  logging level. For example::

     import logging
     logging.basicConfig(filename='/var/log/application.log',
         level=0,  # Log all messages
         format='%(levelname):%(process):%(thread):%(message)')

  Other additions to the :mod:`logging` package include a ``log(level, msg)``
  convenience method, as well as a :class:`TimedRotatingFileHandler` class that
  rotates its log files at a timed interval.  The module already had
  :class:`RotatingFileHandler`, which rotated logs once the file exceeded a
  certain size.  Both classes derive from a new :class:`BaseRotatingHandler` class
  that can be used to implement other rotating handlers.

  (Changes implemented by Vinay Sajip.)

* The :mod:`marshal` module now shares interned strings on unpacking a  data
  structure.  This may shrink the size of certain pickle strings, but the primary
  effect is to make :file:`.pyc` files significantly smaller. (Contributed by
  Martin von Löwis.)

* The :mod:`nntplib` module's :class:`NNTP` class gained :meth:`description` and
  :meth:`descriptions` methods to retrieve  newsgroup descriptions for a single
  group or for a range of groups. (Contributed by Jürgen A. Erhard.)

* Two new functions were added to the :mod:`operator` module,
  ``attrgetter(attr)`` and ``itemgetter(index)``. Both functions return
  callables that take a single argument and return the corresponding attribute or
  item; these callables make excellent data extractors when used with :func:`map`
  or :func:`sorted`.  For example::

     >>> L = [('c', 2), ('d', 1), ('a', 4), ('b', 3)]
     >>> map(operator.itemgetter(0), L)
     ['c', 'd', 'a', 'b']
     >>> map(operator.itemgetter(1), L)
     [2, 1, 4, 3]
     >>> sorted(L, key=operator.itemgetter(1)) # Sort list by second tuple item
     [('d', 1), ('c', 2), ('b', 3), ('a', 4)]

  (Contributed by Raymond Hettinger.)

* The :mod:`optparse` module was updated in various ways.  The module now passes
  its messages through :func:`gettext.gettext`, making it possible to
  internationalize Optik's help and error messages.  Help messages for options can
  now include the string ``'%default'``, which will be replaced by the option's
  default value.  (Contributed by Greg Ward.)

* The long-term plan is to deprecate the :mod:`rfc822` module in some future
  Python release in favor of the :mod:`email` package. To this end, the
  :func:`email.Utils.formatdate` function has been changed to make it usable as a
  replacement for :func:`rfc822.formatdate`.  You may want to write new e-mail
  processing code with this in mind.  (Change implemented by Anthony Baxter.)

* A new ``urandom(n)`` function was added to the :mod:`os` module, returning
  a string containing *n* bytes of random data.  This function provides access to
  platform-specific sources of randomness such as :file:`/dev/urandom` on Linux or
  the Windows CryptoAPI.  (Contributed by Trevor Perrin.)

* Another new function: ``os.path.lexists(path)``  returns true if the file
  specified by *path* exists, whether or not it's a symbolic link.  This differs
  from the existing ``os.path.exists(path)`` function, which returns false if
  *path* is a symlink that points to a destination that doesn't exist.
  (Contributed by Beni Cherniavsky.)

* A new :func:`getsid` function was added to the :mod:`posix` module that
  underlies the :mod:`os` module. (Contributed by J. Raynor.)

* The :mod:`poplib` module now supports POP over SSL.  (Contributed by Hector
  Urtubia.)

* The :mod:`profile` module can now profile C extension functions. (Contributed
  by Nick Bastin.)

* The :mod:`random` module has a new method called ``getrandbits(N)`` that
  returns a long integer *N* bits in length.  The existing :meth:`randrange`
  method now uses :meth:`getrandbits` where appropriate, making generation of
  arbitrarily large random numbers more efficient.  (Contributed by Raymond
  Hettinger.)

* The regular expression language accepted by the :mod:`re` module was extended
  with simple conditional expressions, written as ``(?(group)A|B)``.  *group* is
  either a numeric group ID or a group name defined with ``(?P<group>...)``
  earlier in the expression.  If the specified group matched, the regular
  expression pattern *A* will be tested against the string; if the group didn't
  match, the pattern *B* will be used instead. (Contributed by Gustavo Niemeyer.)

* The :mod:`re` module is also no longer recursive, thanks to a massive amount
  of work by Gustavo Niemeyer.  In a recursive regular expression engine, certain
  patterns result in a large amount of C stack space being consumed, and it was
  possible to overflow the stack. For example, if you matched a 30000-byte string
  of ``a`` characters against the expression ``(a|b)+``, one stack frame was
  consumed per character.  Python 2.3 tried to check for stack overflow and raise
  a :exc:`RuntimeError` exception, but certain patterns could sidestep the
  checking and if you were unlucky Python could segfault. Python 2.4's regular
  expression engine can match this pattern without problems.

* The :mod:`signal` module now performs tighter error-checking on the parameters
  to the :func:`signal.signal` function.  For example, you can't set a handler on
  the :const:`SIGKILL` signal; previous versions of Python would quietly accept
  this, but 2.4 will raise a :exc:`RuntimeError` exception.

* Two new functions were added to the :mod:`socket` module. :func:`socketpair`
  returns a pair of connected sockets and ``getservbyport(port)`` looks up the
  service name for a given port number. (Contributed by Dave Cole and Barry
  Warsaw.)

* The :func:`sys.exitfunc` function has been deprecated.  Code should be using
  the existing :mod:`atexit` module, which correctly handles calling multiple exit
  functions.  Eventually :func:`sys.exitfunc` will become a purely internal
  interface, accessed only by :mod:`atexit`.

* The :mod:`tarfile` module now generates GNU-format tar files by default.
  (Contributed by Lars Gustaebel.)

* The :mod:`threading` module now has an elegantly simple way to support
  thread-local data.  The module contains a :class:`local` class whose attribute
  values are local to different threads. ::

     import threading

     data = threading.local()
     data.number = 42
     data.url = ('www.python.org', 80)

  Other threads can assign and retrieve their own values for the :attr:`number`
  and :attr:`url` attributes.  You can subclass :class:`local` to initialize
  attributes or to add methods. (Contributed by Jim Fulton.)

* The :mod:`timeit` module now automatically disables periodic garbage
  collection during the timing loop.  This change makes consecutive timings more
  comparable.  (Contributed by Raymond Hettinger.)

* The :mod:`weakref` module now supports a wider variety of objects including
  Python functions, class instances, sets, frozensets, deques, arrays, files,
  sockets, and regular expression pattern objects. (Contributed by Raymond
  Hettinger.)

* The :mod:`xmlrpclib` module now supports a multi-call extension for
  transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
  Brian Quinlan.)

* The :mod:`mpz`, :mod:`rotor`, and :mod:`xreadlines` modules have  been
  removed.

.. ======================================================================
.. whole new modules get described in subsections here
.. =====================


cookielib
---------

The :mod:`cookielib` library supports client-side handling for HTTP cookies,
mirroring the :mod:`Cookie` module's server-side cookie support. Cookies are
stored in cookie jars; the library transparently stores cookies offered by the
web server in the cookie jar, and fetches the cookie from the jar when
connecting to the server. As in web browsers, policy objects control whether
cookies are accepted or not.

In order to store cookies across sessions, two implementations of cookie jars
are provided: one that stores cookies in the Netscape format so applications can
use the Mozilla or Lynx cookie files, and one that stores cookies in the same
format as the Perl libwww library.

:mod:`urllib2` has been changed to interact with :mod:`cookielib`:
:class:`HTTPCookieProcessor` manages a cookie jar that is used when accessing
URLs.

This module was contributed by John J. Lee.

.. ==================


doctest
-------

The :mod:`doctest` module underwent considerable refactoring thanks to Edward
Loper and Tim Peters.  Testing can still be as simple as running
:func:`doctest.testmod`, but the refactorings allow customizing the module's
operation in various ways

The new :class:`DocTestFinder` class extracts the tests from a given  object's
docstrings::

   def f (x, y):
       """>>> f(2,2)
   4
   >>> f(3,2)
   6
       """
       return x*y

   finder = doctest.DocTestFinder()

   # Get list of DocTest instances
   tests = finder.find(f)

The new :class:`DocTestRunner` class then runs individual tests and can produce
a summary of the results::

   runner = doctest.DocTestRunner()
   for t in tests:
       tried, failed = runner.run(t)

   runner.summarize(verbose=1)

The above example produces the following output::

   1 items passed all tests:
      2 tests in f
   2 tests in 1 items.
   2 passed and 0 failed.
   Test passed.

:class:`DocTestRunner` uses an instance of the :class:`OutputChecker` class to
compare the expected output with the actual output.  This class takes a number
of different flags that customize its behaviour; ambitious users can also write
a completely new subclass of :class:`OutputChecker`.

The default output checker provides a number of handy features. For example,
with the :const:`doctest.ELLIPSIS` option flag, an ellipsis (``...``) in the
expected output matches any substring,  making it easier to accommodate outputs
that vary in minor ways::

   def o (n):
       """>>> o(1)
   <__main__.C instance at 0x...>
   >>>
   """

Another special string, ``<BLANKLINE>``, matches a blank line::

   def p (n):
       """>>> p(1)
   <BLANKLINE>
   >>>
   """

Another new capability is producing a diff-style display of the output by
specifying the :const:`doctest.REPORT_UDIFF` (unified diffs),
:const:`doctest.REPORT_CDIFF` (context diffs), or :const:`doctest.REPORT_NDIFF`
(delta-style) option flags.  For example::

   def g (n):
       """>>> g(4)
   here
   is
   a
   lengthy
   >>>"""
       L = 'here is a rather lengthy list of words'.split()
       for word in L[:n]:
           print word

Running the above function's tests with :const:`doctest.REPORT_UDIFF` specified,
you get the following output:

.. code-block:: none

   **********************************************************************
   File "t.py", line 15, in g
   Failed example:
       g(4)
   Differences (unified diff with -expected +actual):
       @@ -2,3 +2,3 @@
        is
        a
       -lengthy
       +rather
   **********************************************************************

.. ======================================================================


Build and C API Changes
=======================

Some of the changes to Python's build process and to the C API are:

* Three new convenience macros were added for common return values from
  extension functions: :c:macro:`Py_RETURN_NONE`, :c:macro:`Py_RETURN_TRUE`, and
  :c:macro:`Py_RETURN_FALSE`. (Contributed by Brett Cannon.)

* Another new macro, :c:macro:`Py_CLEAR(obj)`,  decreases the reference count of
  *obj* and sets *obj* to the null pointer.  (Contributed by Jim Fulton.)

* A new function, ``PyTuple_Pack(N, obj1, obj2, ..., objN)``, constructs
  tuples from a variable length argument list of Python objects.  (Contributed by
  Raymond Hettinger.)

* A new function, ``PyDict_Contains(d, k)``, implements fast dictionary
  lookups without masking exceptions raised during the look-up process.
  (Contributed by Raymond Hettinger.)

* The :c:macro:`Py_IS_NAN(X)` macro returns 1 if  its float or double argument
  *X* is a NaN.   (Contributed by Tim Peters.)

* C code can avoid unnecessary locking by using the new
  :c:func:`PyEval_ThreadsInitialized` function to tell  if any thread operations
  have been performed.  If this function  returns false, no lock operations are
  needed. (Contributed by Nick Coghlan.)

* A new function, :c:func:`PyArg_VaParseTupleAndKeywords`, is the same as
  :c:func:`PyArg_ParseTupleAndKeywords` but takes a  :c:type:`va_list` instead of a
  number of arguments. (Contributed by Greg Chapman.)

* A new method flag, :const:`METH_COEXISTS`, allows a function defined in slots
  to co-exist with a :c:type:`PyCFunction` having the same name.  This can halve
  the access time for a method such as :meth:`set.__contains__`.  (Contributed by
  Raymond Hettinger.)

* Python can now be built with additional profiling for the interpreter itself,
  intended as an aid to people developing the Python core.  Providing
  :option:`!--enable-profiling` to the :program:`configure` script will let you
  profile the interpreter with :program:`gprof`, and providing the
  :option:`!--with-tsc` switch enables profiling using the Pentium's
  Time-Stamp-Counter register.  Note that the :option:`!--with-tsc` switch is slightly
  misnamed, because the profiling feature also works on the PowerPC platform,
  though that processor architecture doesn't call that register "the TSC
  register".  (Contributed by Jeremy Hylton.)

* The :c:type:`tracebackobject` type has been renamed to
  :c:type:`PyTracebackObject`.

.. ======================================================================


Port-Specific Changes
---------------------

* The Windows port now builds under MSVC++ 7.1 as well as version 6.
  (Contributed by Martin von Löwis.)

.. ======================================================================


Porting to Python 2.4
=====================

This section lists previously described changes that may require changes to your
code:

* Left shifts and hexadecimal/octal constants that are too  large no longer
  trigger a :exc:`FutureWarning` and return  a value limited to 32 or 64 bits;
  instead they return a long integer.

* Integer operations will no longer trigger an :exc:`OverflowWarning`. The
  :exc:`OverflowWarning` warning will disappear in Python 2.5.

* The :func:`zip` built-in function and :func:`itertools.izip` now return  an
  empty list instead of raising a :exc:`TypeError` exception if called with no
  arguments.

* You can no longer compare the :class:`date` and :class:`~datetime.datetime` instances
  provided by the :mod:`datetime` module.  Two  instances of different classes
  will now always be unequal, and  relative comparisons (``<``, ``>``) will raise
  a :exc:`TypeError`.

* :func:`dircache.listdir` now passes exceptions to the caller instead of
  returning empty lists.

* :func:`LexicalHandler.startDTD` used to receive the public and system IDs in
  the wrong order.  This has been corrected; applications relying on the wrong
  order need to be fixed.

* :func:`fcntl.ioctl` now warns if the *mutate*  argument is omitted and
  relevant.

* The :mod:`tarfile` module now generates GNU-format tar files by default.

* Encountering a failure while importing a module no longer leaves a
  partially-initialized module object in ``sys.modules``.

* :const:`None` is now a constant; code that binds a new value to  the name
  ``None`` is now a syntax error.

* The :func:`signals.signal` function now raises a :exc:`RuntimeError` exception
  for certain illegal values; previously these errors would pass silently.  For
  example, you can no longer set a handler on the :const:`SIGKILL` signal.

.. ======================================================================


.. _24acks:

Acknowledgements
================

The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Koray Can,
Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson,
Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.

PK
%�\(QK�,�,�"html/_sources/whatsnew/2.5.rst.txtnu�[���****************************
  What's New in Python 2.5
****************************

:Author: A.M. Kuchling

.. |release| replace:: 1.01

.. $Id: whatsnew25.tex 56611 2007-07-29 08:26:10Z georg.brandl $
.. Fix XXX comments

This article explains the new features in Python 2.5.  The final release of
Python 2.5 is scheduled for August 2006; :pep:`356` describes the planned
release schedule.

The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python's user
community, I think, because several widely-useful packages were added.  New
modules include ElementTree for XML processing (:mod:`xml.etree`),
the SQLite database module (:mod:`sqlite`), and the :mod:`ctypes`
module for calling C functions.

The language changes are of middling significance.  Some pleasant new features
were added, but most of them aren't features that you'll use every day.
Conditional expressions were finally added to the language using a novel syntax;
see section :ref:`pep-308`.  The new ':keyword:`with`' statement will make
writing cleanup code easier (section :ref:`pep-343`).  Values can now be passed
into generators (section :ref:`pep-342`).  Imports are now visible as either
absolute or relative (section :ref:`pep-328`).  Some corner cases of exception
handling are handled better (section :ref:`pep-341`).  All these improvements
are worthwhile, but they're improvements to one specific language feature or
another; none of them are broad modifications to Python's semantics.

As well as the language and library additions, other improvements and bugfixes
were made throughout the source tree.  A search through the SVN change logs
finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
2.5.  (Both figures are likely to be underestimates.)

This article doesn't try to be a complete specification of the new features;
instead changes are briefly introduced using helpful examples.  For full
details, you should always refer to the documentation for Python 2.5 at
https://docs.python.org. If you want to understand the complete implementation
and design rationale, refer to the PEP for a particular new feature.

Comments, suggestions, and error reports for this document are welcome; please
e-mail them to the author or open a bug in the Python bug tracker.

.. ======================================================================


.. _pep-308:

PEP 308: Conditional Expressions
================================

For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B depending on
whether a Boolean value is true or false.  A conditional expression lets you
write a single assignment statement that has the same effect as the following::

   if condition:
       x = true_value
   else:
       x = false_value

There have been endless tedious discussions of syntax on both python-dev and
comp.lang.python.  A vote was even held that found the majority of voters wanted
conditional expressions in some form, but there was no syntax that was preferred
by a clear majority. Candidates included C's ``cond ? true_v : false_v``, ``if
cond then true_v else false_v``, and 16 other variations.

Guido van Rossum eventually chose a surprising syntax::

   x = true_value if condition else false_value

Evaluation is still lazy as in existing Boolean expressions, so the order of
evaluation jumps around a bit.  The *condition* expression in the middle is
evaluated first, and the *true_value* expression is evaluated only if the
condition was true.  Similarly, the *false_value* expression is only evaluated
when the condition is false.

This syntax may seem strange and backwards; why does the condition go in the
*middle* of the expression, and not in the front as in C's ``c ? x : y``?  The
decision was checked by applying the new syntax to the modules in the standard
library and seeing how the resulting code read.  In many cases where a
conditional expression is used, one value seems to be the 'common case' and one
value is an 'exceptional case', used only on rarer occasions when the condition
isn't met.  The conditional syntax makes this pattern a bit more obvious::

   contents = ((doc + '\n') if doc else '')

I read the above statement as meaning "here *contents* is  usually assigned a
value of ``doc+'\n'``; sometimes  *doc* is empty, in which special case an empty
string is returned."   I doubt I will use conditional expressions very often
where there  isn't a clear common and uncommon case.

There was some discussion of whether the language should require surrounding
conditional expressions with parentheses.  The decision was made to *not*
require parentheses in the Python language's grammar, but as a matter of style I
think you should always use them. Consider these two statements::

   # First version -- no parens
   level = 1 if logging else 0

   # Second version -- with parens
   level = (1 if logging else 0)

In the first version, I think a reader's eye might group the statement into
'level = 1', 'if logging', 'else 0', and think that the condition decides
whether the assignment to *level* is performed.  The second version reads
better, in my opinion, because it makes it clear that the assignment is always
performed and the choice is being made between two values.

Another reason for including the brackets: a few odd combinations of list
comprehensions and lambdas could look like incorrect conditional expressions.
See :pep:`308` for some examples.  If you put parentheses around your
conditional expressions, you won't run into this case.


.. seealso::

   :pep:`308` - Conditional Expressions
      PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
      Wouters.

.. ======================================================================


.. _pep-309:

PEP 309: Partial Function Application
=====================================

The :mod:`functools` module is intended to contain tools for functional-style
programming.

One useful tool in this module is the :func:`partial` function. For programs
written in a functional style, you'll sometimes want to construct variants of
existing functions that have some of the parameters filled in.  Consider a
Python function ``f(a, b, c)``; you could create a new function ``g(b, c)`` that
was equivalent to ``f(1, b, c)``.  This is called "partial function
application".

:func:`partial` takes the arguments ``(function, arg1, arg2, ... kwarg1=value1,
kwarg2=value2)``.  The resulting object is callable, so you can just call it to
invoke *function* with the filled-in arguments.

Here's a small but realistic example::

   import functools

   def log (message, subsystem):
       "Write the contents of 'message' to the specified subsystem."
       print '%s: %s' % (subsystem, message)
       ...

   server_log = functools.partial(log, subsystem='server')
   server_log('Unable to open socket')

Here's another example, from a program that uses PyGTK.  Here a context-sensitive
pop-up menu is being constructed dynamically.  The callback provided
for the menu option is a partially applied version of the :meth:`open_item`
method, where the first argument has been provided. ::

   ...
   class Application:
       def open_item(self, path):
          ...
       def init (self):
           open_func = functools.partial(self.open_item, item_path)
           popup_menu.append( ("Open", open_func, 1) )

Another function in the :mod:`functools` module is the
``update_wrapper(wrapper, wrapped)`` function that helps you write
well-behaved decorators.  :func:`update_wrapper` copies the name, module, and
docstring attribute to a wrapper function so that tracebacks inside the wrapped
function are easier to understand.  For example, you might write::

   def my_decorator(f):
       def wrapper(*args, **kwds):
           print 'Calling decorated function'
           return f(*args, **kwds)
       functools.update_wrapper(wrapper, f)
       return wrapper

:func:`wraps` is a decorator that can be used inside your own decorators to copy
the wrapped function's information.  An alternate  version of the previous
example would be::

   def my_decorator(f):
       @functools.wraps(f)
       def wrapper(*args, **kwds):
           print 'Calling decorated function'
           return f(*args, **kwds)
       return wrapper


.. seealso::

   :pep:`309` - Partial Function Application
      PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick
      Coghlan, with adaptations by Raymond Hettinger.

.. ======================================================================


.. _pep-314:

PEP 314: Metadata for Python Software Packages v1.1
===================================================

Some simple dependency support was added to Distutils.  The :func:`setup`
function now has ``requires``, ``provides``, and ``obsoletes`` keyword
parameters.  When you build a source distribution using the ``sdist`` command,
the dependency information will be recorded in the :file:`PKG-INFO` file.

Another new keyword parameter is ``download_url``, which should be set to a URL
for the package's source code.  This means it's now possible to look up an entry
in the package index, determine the dependencies for a package, and download the
required packages. ::

   VERSION = '1.0'
   setup(name='PyPackage',
         version=VERSION,
         requires=['numarray', 'zlib (>=1.1.4)'],
         obsoletes=['OldPackage']
         download_url=('http://www.example.com/pypackage/dist/pkg-%s.tar.gz'
                       % VERSION),
        )

Another new enhancement to the Python package index at
https://pypi.org is storing source and binary archives for a
package.  The new :command:`upload` Distutils command will upload a package to
the repository.

Before a package can be uploaded, you must be able to build a distribution using
the :command:`sdist` Distutils command.  Once that works, you can run ``python
setup.py upload`` to add your package to the PyPI archive.  Optionally you can
GPG-sign the package by supplying the :option:`!--sign` and :option:`!--identity`
options.

Package uploading was implemented by Martin von Löwis and Richard Jones.


.. seealso::

   :pep:`314` - Metadata for Python Software Packages v1.1
      PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake;
      implemented by Richard Jones and Fred Drake.

.. ======================================================================


.. _pep-328:

PEP 328: Absolute and Relative Imports
======================================

The simpler part of PEP 328 was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the ``from ... import
...`` statement, making it easier to import many different names.

The more complicated part has been implemented in Python 2.5: importing a module
can be specified to use absolute or package-relative imports.  The plan is to
move toward making absolute imports the default in future versions of Python.

Let's say you have a package directory like this::

   pkg/
   pkg/__init__.py
   pkg/main.py
   pkg/string.py

This defines a package named :mod:`pkg` containing the :mod:`pkg.main` and
:mod:`pkg.string` submodules.

Consider the code in the :file:`main.py` module.  What happens if it executes
the statement ``import string``?  In Python 2.4 and earlier, it will first look
in the package's directory to perform a relative import, finds
:file:`pkg/string.py`, imports the contents of that file as the
:mod:`pkg.string` module, and that module is bound to the name ``string`` in the
:mod:`pkg.main` module's namespace.

That's fine if :mod:`pkg.string` was what you wanted.  But what if you wanted
Python's standard :mod:`string` module?  There's no clean way to ignore
:mod:`pkg.string` and look for the standard module; generally you had to look at
the contents of ``sys.modules``, which is slightly unclean.    Holger Krekel's
:mod:`py.std` package provides a tidier way to perform imports from the standard
library, ``import py; py.std.string.join()``, but that package isn't available
on all Python installations.

Reading code which relies on relative imports is also less clear, because a
reader may be confused about which module, :mod:`string` or :mod:`pkg.string`,
is intended to be used.  Python users soon learned not to duplicate the names of
standard library modules in the names of their packages' submodules, but you
can't protect against having your submodule's name being used for a new module
added in a future version of Python.

In Python 2.5, you can switch :keyword:`import`'s behaviour to  absolute imports
using a ``from __future__ import absolute_import`` directive.  This absolute-import
behaviour will become the default in a future version (probably Python
2.7).  Once absolute imports  are the default, ``import string`` will always
find the standard library's version. It's suggested that users should begin
using absolute imports as much as possible, so it's preferable to begin writing
``from pkg import string`` in your code.

Relative imports are still possible by adding a leading period  to the module
name when using the ``from ... import`` form::

   # Import names from pkg.string
   from .string import name1, name2
   # Import pkg.string
   from . import string

This imports the :mod:`string` module relative to the current package, so in
:mod:`pkg.main` this will import *name1* and *name2* from :mod:`pkg.string`.
Additional leading periods perform the relative import starting from the parent
of the current package.  For example, code in the :mod:`A.B.C` module can do::

   from . import D                 # Imports A.B.D
   from .. import E                # Imports A.E
   from ..F import G               # Imports A.F.G

Leading periods cannot be used with the ``import modname``  form of the import
statement, only the ``from ... import`` form.


.. seealso::

   :pep:`328` - Imports: Multi-Line and Absolute/Relative
      PEP written by Aahz; implemented by Thomas Wouters.

   https://pylib.readthedocs.org/
      The py library by Holger Krekel, which contains the :mod:`py.std` package.

.. ======================================================================


.. _pep-338:

PEP 338: Executing Modules as Scripts
=====================================

The :option:`-m` switch added in Python 2.4 to execute a module as a script
gained a few more abilities.  Instead of being implemented in C code inside the
Python interpreter, the switch now uses an implementation in a new module,
:mod:`runpy`.

The :mod:`runpy` module implements a more sophisticated import mechanism so that
it's now possible to run modules in a package such as :mod:`pychecker.checker`.
The module also supports alternative import mechanisms such as the
:mod:`zipimport` module.  This means you can add a .zip archive's path to
``sys.path`` and then use the :option:`-m` switch to execute code from the
archive.


.. seealso::

   :pep:`338` - Executing modules as scripts
      PEP written and  implemented by Nick Coghlan.

.. ======================================================================


.. _pep-341:

PEP 341: Unified try/except/finally
===================================

Until Python 2.5, the :keyword:`try` statement came in two flavours. You could
use a :keyword:`finally` block to ensure that code is always executed, or one or
more :keyword:`except` blocks to catch  specific exceptions.  You couldn't
combine both :keyword:`except` blocks and a :keyword:`finally` block, because
generating the right bytecode for the combined version was complicated and it
wasn't clear what the semantics of the combined statement should be.

Guido van Rossum spent some time working with Java, which does support the
equivalent of combining :keyword:`except` blocks and a :keyword:`finally` block,
and this clarified what the statement should mean.  In Python 2.5, you can now
write::

   try:
       block-1 ...
   except Exception1:
       handler-1 ...
   except Exception2:
       handler-2 ...
   else:
       else-block
   finally:
       final-block

The code in *block-1* is executed.  If the code raises an exception, the various
:keyword:`except` blocks are tested: if the exception is of class
:class:`Exception1`, *handler-1* is executed; otherwise if it's of class
:class:`Exception2`, *handler-2* is executed, and so forth.  If no exception is
raised, the *else-block* is executed.

No matter what happened previously, the *final-block* is executed once the code
block is complete and any raised exceptions handled. Even if there's an error in
an exception handler or the *else-block* and a new exception is raised, the code
in the *final-block* is still run.


.. seealso::

   :pep:`341` - Unifying try-except and try-finally
      PEP written by Georg Brandl;  implementation by Thomas Lee.

.. ======================================================================


.. _pep-342:

PEP 342: New Generator Features
===============================

Python 2.5 adds a simple way to pass values *into* a generator. As introduced in
Python 2.3, generators only produce output; once a generator's code was invoked
to create an iterator, there was no way to pass any new information into the
function when its execution is resumed.  Sometimes the ability to pass in some
information would be useful.  Hackish solutions to this include making the
generator's code look at a global variable and then changing the global
variable's value, or passing in some mutable object that callers then modify.

To refresh your memory of basic generators, here's a simple example::

   def counter (maximum):
       i = 0
       while i < maximum:
           yield i
           i += 1

When you call ``counter(10)``, the result is an iterator that returns the values
from 0 up to 9.  On encountering the :keyword:`yield` statement, the iterator
returns the provided value and suspends the function's execution, preserving the
local variables. Execution resumes on the following call to the iterator's
:meth:`next` method, picking up after the :keyword:`yield` statement.

In Python 2.3, :keyword:`yield` was a statement; it didn't return any value.  In
2.5, :keyword:`yield` is now an expression, returning a value that can be
assigned to a variable or otherwise operated on::

   val = (yield i)

I recommend that you always put parentheses around a :keyword:`yield` expression
when you're doing something with the returned value, as in the above example.
The parentheses aren't always necessary, but it's easier to always add them
instead of having to remember when they're needed.

(:pep:`342` explains the exact rules, which are that a :keyword:`yield`\
-expression must always be parenthesized except when it occurs at the top-level
expression on the right-hand side of an assignment.  This means you can write
``val = yield i`` but have to use parentheses when there's an operation, as in
``val = (yield i) + 12``.)

Values are sent into a generator by calling its ``send(value)`` method.  The
generator's code is then resumed and the :keyword:`yield` expression returns the
specified *value*.  If the regular :meth:`next` method is called, the
:keyword:`yield` returns :const:`None`.

Here's the previous example, modified to allow changing the value of the
internal counter. ::

   def counter (maximum):
       i = 0
       while i < maximum:
           val = (yield i)
           # If value provided, change counter
           if val is not None:
               i = val
           else:
               i += 1

And here's an example of changing the counter::

   >>> it = counter(10)
   >>> print it.next()
   0
   >>> print it.next()
   1
   >>> print it.send(8)
   8
   >>> print it.next()
   9
   >>> print it.next()
   Traceback (most recent call last):
     File "t.py", line 15, in ?
       print it.next()
   StopIteration

:keyword:`yield` will usually return :const:`None`, so you should always check
for this case.  Don't just use its value in expressions unless you're sure that
the :meth:`send` method will be the only method used to resume your generator
function.

In addition to :meth:`send`, there are two other new methods on generators:

* ``throw(type, value=None, traceback=None)`` is used to raise an exception
  inside the generator; the exception is raised by the :keyword:`yield` expression
  where the generator's execution is paused.

* :meth:`close` raises a new :exc:`GeneratorExit` exception inside the generator
  to terminate the iteration.  On receiving this exception, the generator's code
  must either raise :exc:`GeneratorExit` or :exc:`StopIteration`.  Catching the
  :exc:`GeneratorExit` exception and returning a value is illegal and will trigger
  a :exc:`RuntimeError`; if the function raises some other exception, that
  exception is propagated to the caller.  :meth:`close` will also be called by
  Python's garbage collector when the generator is garbage-collected.

  If you need to run cleanup code when a :exc:`GeneratorExit` occurs, I suggest
  using a ``try: ... finally:`` suite instead of  catching :exc:`GeneratorExit`.

The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.

Generators also become *coroutines*, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a :keyword:`return` statement), but coroutines can be entered,
exited, and resumed at many different points (the :keyword:`yield` statements).
We'll have to figure out patterns for using coroutines effectively in Python.

The addition of the :meth:`close` method has one side effect that isn't obvious.
:meth:`close` is called when a generator is garbage-collected, so this means the
generator's code gets one last chance to run before the generator is destroyed.
This last chance means that ``try...finally`` statements in generators can now
be guaranteed to work; the :keyword:`finally` clause will now always get a
chance to run.  The syntactic restriction that you couldn't mix :keyword:`yield`
statements with a ``try...finally`` suite has therefore been removed.  This
seems like a minor bit of language trivia, but using generators and
``try...finally`` is actually necessary in order to implement the
:keyword:`with` statement described by PEP 343.  I'll look at this new statement
in the following  section.

Another even more esoteric effect of this change: previously, the
:attr:`gi_frame` attribute of a generator was always a frame object. It's now
possible for :attr:`gi_frame` to be ``None`` once the generator has been
exhausted.


.. seealso::

   :pep:`342` - Coroutines via Enhanced Generators
      PEP written by  Guido van Rossum and Phillip J. Eby; implemented by Phillip J.
      Eby.  Includes examples of  some fancier uses of generators as coroutines.

      Earlier versions of these features were proposed in  :pep:`288` by Raymond
      Hettinger and :pep:`325` by Samuele Pedroni.

   https://en.wikipedia.org/wiki/Coroutine
      The Wikipedia entry for  coroutines.

   http://www.sidhe.org/~dan/blog/archives/000178.html
      An explanation of coroutines from a Perl point of view, written by Dan Sugalski.

.. ======================================================================


.. _pep-343:

PEP 343: The 'with' statement
=============================

The ':keyword:`with`' statement clarifies code that previously would use
``try...finally`` blocks to ensure that clean-up code is executed.  In this
section, I'll discuss the statement as it will commonly be used.  In the next
section, I'll examine the implementation details and show how to write objects
for use with this statement.

The ':keyword:`with`' statement is a new control-flow structure whose basic
structure is::

   with expression [as variable]:
       with-block

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
methods.

The object's :meth:`__enter__` is called before *with-block* is executed and
therefore can run set-up code. It also may return a value that is bound to the
name *variable*, if given.  (Note carefully that *variable* is *not* assigned
the result of *expression*.)

After execution of the *with-block* is finished, the object's :meth:`__exit__`
method is called, even if the block raised an exception, and can therefore run
clean-up code.

To enable the statement in Python 2.5, you need to add the following directive
to your module::

   from __future__ import with_statement

The statement will always be enabled in Python 2.6.

Some standard Python objects now support the context management protocol and can
be used with the ':keyword:`with`' statement. File objects are one example::

   with open('/etc/passwd', 'r') as f:
       for line in f:
           print line
           ... more processing code ...

After this statement has executed, the file object in *f* will have been
automatically closed, even if the :keyword:`for` loop raised an exception
part-way through the block.

.. note::

   In this case, *f* is the same object created by :func:`open`, because
   :meth:`file.__enter__` returns *self*.

The :mod:`threading` module's locks and condition variables  also support the
':keyword:`with`' statement::

   lock = threading.Lock()
   with lock:
       # Critical section of code
       ...

The lock is acquired before the block is executed and always released once  the
block is complete.

The new :func:`localcontext` function in the :mod:`decimal` module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations::

   from decimal import Decimal, Context, localcontext

   # Displays with default precision of 28 digits
   v = Decimal('578')
   print v.sqrt()

   with localcontext(Context(prec=16)):
       # All code in this block uses a precision of 16 digits.
       # The original context is restored on exiting the block.
       print v.sqrt()


.. _new-25-context-managers:

Writing Context Managers
------------------------

Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
people will only use ':keyword:`with`' in company with existing objects and
don't need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

* The expression is evaluated and should result in an object called a "context
  manager".  The context manager must have :meth:`__enter__` and :meth:`__exit__`
  methods.

* The context manager's :meth:`__enter__` method is called.  The value returned
  is assigned to *VAR*.  If no ``'as VAR'`` clause is present, the value is simply
  discarded.

* The code in *BLOCK* is executed.

* If *BLOCK* raises an exception, the ``__exit__(type, value, traceback)``
  is called with the exception details, the same values returned by
  :func:`sys.exc_info`.  The method's return value controls whether the exception
  is re-raised: any false value re-raises the exception, and ``True`` will result
  in suppressing it.  You'll only rarely want to suppress the exception, because
  if you do the author of the code containing the ':keyword:`with`' statement will
  never realize anything went wrong.

* If *BLOCK* didn't raise an exception,  the :meth:`__exit__` method is still
  called, but *type*, *value*, and *traceback* are all ``None``.

Let's think through an example.  I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)

Let's assume there's an object representing a database connection. Our goal will
be to let the user write code like this::

   db_connection = DatabaseConnection()
   with db_connection as cursor:
       cursor.execute('insert into ...')
       cursor.execute('delete from ...')
       # ... more operations ...

The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
:class:`DatabaseConnection` that I'll assume::

   class DatabaseConnection:
       # Database interface
       def cursor (self):
           "Returns a cursor object and starts a new transaction"
       def commit (self):
           "Commits current transaction"
       def rollback (self):
           "Rolls back current transaction"

The :meth:`__enter__` method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add ``as cursor`` to
their ':keyword:`with`' statement to bind the cursor to a variable name. ::

   class DatabaseConnection:
       ...
       def __enter__ (self):
           # Code to start a new transaction
           cursor = self.cursor()
           return cursor

The :meth:`__exit__` method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of ``None``.  ``None`` is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a :keyword:`return` statement at the marked location. ::

   class DatabaseConnection:
       ...
       def __exit__ (self, type, value, tb):
           if tb is None:
               # No exception, so commit
               self.commit()
           else:
               # Exception occurred, so rollback.
               self.rollback()
               # return False


.. _contextlibmod:

The contextlib module
---------------------

The new :mod:`contextlib` module provides some functions and a decorator that
are useful for writing objects for use with the ':keyword:`with`' statement.

The decorator is called :func:`contextmanager`, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the :keyword:`yield` will be executed as the
:meth:`__enter__` method, and the value yielded will be the method's return
value that will get bound to the variable in the ':keyword:`with`' statement's
:keyword:`as` clause, if any.  The code after the :keyword:`yield` will be
executed in the :meth:`__exit__` method.  Any exception raised in the block will
be raised by the :keyword:`yield` statement.

Our database example from the previous section could be written  using this
decorator as::

   from contextlib import contextmanager

   @contextmanager
   def db_transaction (connection):
       cursor = connection.cursor()
       try:
           yield cursor
       except:
           connection.rollback()
           raise
       else:
           connection.commit()

   db = DatabaseConnection()
   with db_transaction(db) as cursor:
       ...

The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
that combines a number of context managers so you don't need to write nested
':keyword:`with`' statements.  In this example, the single ':keyword:`with`'
statement both starts a database transaction and acquires a thread lock::

   lock = threading.Lock()
   with nested (db_transaction(db), lock) as (cursor, locked):
       ...

Finally, the ``closing(object)`` function returns *object* so that it can be
bound to a variable, and calls ``object.close`` at the end of the block. ::

   import urllib, sys
   from contextlib import closing

   with closing(urllib.urlopen('http://www.yahoo.com')) as f:
       for line in f:
           sys.stdout.write(line)


.. seealso::

   :pep:`343` - The "with" statement
      PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
      Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
      ':keyword:`with`' statement, which can be helpful in learning how the statement
      works.

   The documentation  for the :mod:`contextlib` module.

.. ======================================================================


.. _pep-352:

PEP 352: Exceptions as New-Style Classes
========================================

Exception classes can now be new-style classes, not just classic classes, and
the built-in :exc:`Exception` class and all the standard built-in exceptions
(:exc:`NameError`, :exc:`ValueError`, etc.) are now new-style classes.

The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
inheritance relationships are::

   BaseException       # New in Python 2.5
   |- KeyboardInterrupt
   |- SystemExit
   |- Exception
      |- (all other current built-in exceptions)

This rearrangement was done because people often want to catch all exceptions
that indicate program errors.  :exc:`KeyboardInterrupt` and :exc:`SystemExit`
aren't errors, though, and usually represent an explicit action such as the user
hitting :kbd:`Control-C` or code calling :func:`sys.exit`.  A bare ``except:`` will
catch all exceptions, so you commonly need to list :exc:`KeyboardInterrupt` and
:exc:`SystemExit` in order to re-raise them.  The usual pattern is::

   try:
       ...
   except (KeyboardInterrupt, SystemExit):
       raise
   except:
       # Log error...
       # Continue running program...

In Python 2.5, you can now write ``except Exception`` to achieve the same
result, catching all the exceptions that usually indicate errors  but leaving
:exc:`KeyboardInterrupt` and :exc:`SystemExit` alone.  As in previous versions,
a bare ``except:`` still catches all exceptions.

The goal for Python 3.0 is to require any class raised as an exception to derive
from :exc:`BaseException` or some descendant of :exc:`BaseException`, and future
releases in the Python 2.x series may begin to enforce this constraint.
Therefore, I suggest you begin making all your exception classes derive from
:exc:`Exception` now.  It's been suggested that the bare ``except:`` form should
be removed in Python 3.0, but Guido van Rossum hasn't decided whether to do this
or not.

Raising of strings as exceptions, as in the statement ``raise "Error
occurred"``, is deprecated in Python 2.5 and will trigger a warning.  The aim is
to be able to remove the string-exception feature in a few releases.


.. seealso::

   :pep:`352` - Required Superclass for Exceptions
      PEP written by  Brett Cannon and Guido van Rossum; implemented by Brett Cannon.

.. ======================================================================


.. _pep-353:

PEP 353: Using ssize_t as the index type
========================================

A wide-ranging change to Python's C API, using a new  :c:type:`Py_ssize_t` type
definition instead of :c:type:`int`,  will permit the interpreter to handle more
data on 64-bit platforms. This change doesn't affect Python's capacity on 32-bit
platforms.

Various pieces of the Python interpreter used C's :c:type:`int` type to store
sizes or counts; for example, the number of items in a list or tuple were stored
in an :c:type:`int`.  The C compilers for most 64-bit platforms still define
:c:type:`int` as a 32-bit type, so that meant that lists could only hold up to
``2**31 - 1`` = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use -- see
http://www.unix.org/version2/whatsnew/lp64_wp.html for a discussion -- but the
most commonly available model leaves :c:type:`int` as 32 bits.)

A limit of 2147483647 items doesn't really matter on a 32-bit platform because
you'll run out of memory before hitting the length limit. Each list item
requires space for a pointer, which is 4 bytes, plus space for a
:c:type:`PyObject` representing the item.  2147483647\*4 is already more bytes
than a 32-bit address space can contain.

It's possible to address that much memory on a 64-bit platform, however.  The
pointers for a list that size would only require 16 GiB of space, so it's not
unreasonable that Python programmers might construct lists that large.
Therefore, the Python interpreter had to be changed to use some type other than
:c:type:`int`, and this will be a 64-bit type on 64-bit platforms.  The change
will cause incompatibilities on 64-bit machines, so it was deemed worth making
the transition now, while the number of 64-bit users is still relatively small.
(In 5 or 10 years, we may *all* be on 64-bit machines, and the transition would
be more painful then.)

This change most strongly affects authors of C extension modules.   Python
strings and container types such as lists and tuples  now use
:c:type:`Py_ssize_t` to store their size.   Functions such as
:c:func:`PyList_Size`  now return :c:type:`Py_ssize_t`.  Code in extension modules
may therefore need to have some variables changed to :c:type:`Py_ssize_t`.

The :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` functions have a new
conversion code, ``n``, for :c:type:`Py_ssize_t`.   :c:func:`PyArg_ParseTuple`'s
``s#`` and ``t#`` still output :c:type:`int` by default, but you can define the
macro  :c:macro:`PY_SSIZE_T_CLEAN` before including :file:`Python.h`  to make
them return :c:type:`Py_ssize_t`.

:pep:`353` has a section on conversion guidelines that  extension authors should
read to learn about supporting 64-bit platforms.


.. seealso::

   :pep:`353` - Using ssize_t as the index type
      PEP written and implemented by Martin von Löwis.

.. ======================================================================


.. _pep-357:

PEP 357: The '__index__' method
===============================

The NumPy developers had a problem that could only be solved by adding a new
special method, :meth:`__index__`.  When using slice notation, as in
``[start:stop:step]``, the values of the *start*, *stop*, and *step* indexes
must all be either integers or long integers.  NumPy defines a variety of
specialized integer types corresponding to unsigned and signed integers of 8,
16, 32, and 64 bits, but there was no way to signal that these types could be
used as slice indexes.

Slicing can't just use the existing :meth:`__int__` method because that method
is also used to implement coercion to integers.  If slicing used
:meth:`__int__`, floating-point numbers would also become legal slice indexes
and that's clearly an undesirable behaviour.

Instead, a new special method called :meth:`__index__` was added.  It takes no
arguments and returns an integer giving the slice index to use.  For example::

   class C:
       def __index__ (self):
           return self.value

The return value must be either a Python integer or long integer. The
interpreter will check that the type returned is correct, and raises a
:exc:`TypeError` if this requirement isn't met.

A corresponding :attr:`nb_index` slot was added to the C-level
:c:type:`PyNumberMethods` structure to let C extensions implement this protocol.
``PyNumber_Index(obj)`` can be used in extension code to call the
:meth:`__index__` function and retrieve its result.


.. seealso::

   :pep:`357` - Allowing Any Object to be Used for Slicing
      PEP written  and implemented by Travis Oliphant.

.. ======================================================================


.. _other-lang:

Other Language Changes
======================

Here are all of the changes that Python 2.5 makes to the core Python language.

* The :class:`dict` type has a new hook for letting subclasses provide a default
  value when a key isn't contained in the dictionary. When a key isn't found, the
  dictionary's ``__missing__(key)`` method will be called.  This hook is used
  to implement the new :class:`defaultdict` class in the :mod:`collections`
  module.  The following example defines a dictionary  that returns zero for any
  missing key::

     class zerodict (dict):
         def __missing__ (self, key):
             return 0

     d = zerodict({1:1, 2:2})
     print d[1], d[2]   # Prints 1, 2
     print d[3], d[4]   # Prints 0, 0

* Both 8-bit and Unicode strings have new ``partition(sep)``  and
  ``rpartition(sep)`` methods that simplify a common use case.

  The ``find(S)`` method is often used to get an index which is then used to
  slice the string and obtain the pieces that are before and after the separator.
  ``partition(sep)`` condenses this pattern into a single method call that
  returns a 3-tuple containing the substring before the separator, the separator
  itself, and the substring after the separator.  If the separator isn't found,
  the first element of the tuple is the entire string and the other two elements
  are empty.  ``rpartition(sep)`` also returns a 3-tuple but starts searching
  from the end of the string; the ``r`` stands for 'reverse'.

  Some examples::

     >>> ('http://www.python.org').partition('://')
     ('http', '://', 'www.python.org')
     >>> ('file:/usr/share/doc/index.html').partition('://')
     ('file:/usr/share/doc/index.html', '', '')
     >>> (u'Subject: a quick question').partition(':')
     (u'Subject', u':', u' a quick question')
     >>> 'www.python.org'.rpartition('.')
     ('www.python', '.', 'org')
     >>> 'www.python.org'.rpartition(':')
     ('', '', 'www.python.org')

  (Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)

* The :meth:`startswith` and :meth:`endswith` methods of string types now accept
  tuples of strings to check for. ::

     def is_image_file (filename):
         return filename.endswith(('.gif', '.jpg', '.tiff'))

  (Implemented by Georg Brandl following a suggestion by Tom Lynn.)

  .. RFE #1491485

* The :func:`min` and :func:`max` built-in functions gained a ``key`` keyword
  parameter analogous to the ``key`` argument for :meth:`sort`.  This parameter
  supplies a function that takes a single argument and is called for every value
  in the list; :func:`min`/:func:`max` will return the element with the
  smallest/largest return value from this function. For example, to find the
  longest string in a list, you can do::

     L = ['medium', 'longest', 'short']
     # Prints 'longest'
     print max(L, key=len)
     # Prints 'short', because lexicographically 'short' has the largest value
     print max(L)

  (Contributed by Steven Bethard and Raymond Hettinger.)

* Two new built-in functions, :func:`any` and :func:`all`, evaluate whether an
  iterator contains any true or false values.  :func:`any` returns :const:`True`
  if any value returned by the iterator is true; otherwise it will return
  :const:`False`.  :func:`all` returns :const:`True` only if all of the values
  returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and
  implemented by Raymond Hettinger.)

* The result of a class's :meth:`__hash__` method can now be either a long
  integer or a regular integer.  If a long integer is returned, the hash of that
  value is taken.  In earlier versions the hash value was required to be a
  regular integer, but in 2.5 the :func:`id` built-in was changed to always
  return non-negative numbers, and users often seem to use ``id(self)`` in
  :meth:`__hash__` methods (though this is discouraged).

  .. Bug #1536021

* ASCII is now the default encoding for modules.  It's now  a syntax error if a
  module contains string literals with 8-bit characters but doesn't have an
  encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
  error.  See :pep:`263`  for how to declare a module's encoding; for example, you
  might add  a line like this near the top of the source file::

     # -*- coding: latin1 -*-

* A new warning, :class:`UnicodeWarning`, is triggered when  you attempt to
  compare a Unicode string and an 8-bit string  that can't be converted to Unicode
  using the default ASCII encoding.   The result of the comparison is false::

     >>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
     __main__:1: UnicodeWarning: Unicode equal comparison failed
       to convert both arguments to Unicode - interpreting them
       as being unequal
     False
     >>> chr(127) == unichr(127)   # chr(127) can be converted
     True

  Previously this would raise a :class:`UnicodeDecodeError` exception, but in 2.5
  this could result in puzzling problems when accessing a dictionary.  If you
  looked up ``unichr(128)`` and ``chr(128)`` was being used as a key, you'd get a
  :class:`UnicodeDecodeError` exception.  Other changes in 2.5 resulted in this
  exception being raised instead of suppressed by the code in :file:`dictobject.c`
  that implements dictionaries.

  Raising an exception for such a comparison is strictly correct, but the change
  might have broken code, so instead  :class:`UnicodeWarning` was introduced.

  (Implemented by Marc-André Lemburg.)

* One error that Python programmers sometimes make is forgetting to include an
  :file:`__init__.py` module in a package directory. Debugging this mistake can be
  confusing, and usually requires running Python with the :option:`-v` switch to
  log all the paths searched. In Python 2.5, a new :exc:`ImportWarning` warning is
  triggered when an import would have picked up a directory as a package but no
  :file:`__init__.py` was found.  This warning is silently ignored by default;
  provide the :option:`-Wd <-W>` option when running the Python executable to display
  the warning message. (Implemented by Thomas Wouters.)

* The list of base classes in a class definition can now be empty.   As an
  example, this is now legal::

     class C():
         pass

  (Implemented by Brett Cannon.)

.. ======================================================================


.. _25interactive:

Interactive Interpreter Changes
-------------------------------

In the interactive interpreter, ``quit`` and ``exit``  have long been strings so
that new users get a somewhat helpful message when they try to quit::

   >>> quit
   'Use Ctrl-D (i.e. EOF) to exit.'

In Python 2.5, ``quit`` and ``exit`` are now objects that still produce string
representations of themselves, but are also callable. Newbies who try ``quit()``
or ``exit()`` will now exit the interpreter as they expect.  (Implemented by
Georg Brandl.)

The Python executable now accepts the standard long options  :option:`--help`
and :option:`--version`; on Windows,  it also accepts the :option:`/? <-?>` option
for displaying a help message. (Implemented by Georg Brandl.)

.. ======================================================================


.. _opts:

Optimizations
-------------

Several of the optimizations were developed at the NeedForSpeed sprint, an event
held in Reykjavik, Iceland, from May 21--28 2006. The sprint focused on speed
enhancements to the CPython implementation and was funded by EWT LLC with local
support from CCP Games.  Those optimizations added at this sprint are specially
marked in the following list.

* When they were introduced  in Python 2.4, the built-in :class:`set` and
  :class:`frozenset` types were built on top of Python's dictionary type.   In 2.5
  the internal data structure has been customized for implementing sets, and as a
  result sets will use a third less memory and are somewhat faster. (Implemented
  by Raymond Hettinger.)

* The speed of some Unicode operations, such as finding substrings, string
  splitting, and character map encoding and decoding, has been improved.
  (Substring search and splitting improvements were added by Fredrik Lundh and
  Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter
  Dörwald and Martin von Löwis.)

  .. Patch 1313939, 1359618

* The ``long(str, base)`` function is now faster on long digit strings
  because fewer intermediate results are calculated.  The peak is for strings of
  around 800--1000 digits where  the function is 6 times faster. (Contributed by
  Alan McIntyre and committed at the NeedForSpeed sprint.)

  .. Patch 1442927

* It's now illegal to mix iterating over a file  with ``for line in file`` and
  calling  the file object's :meth:`read`/:meth:`readline`/:meth:`readlines`
  methods.  Iteration uses an internal buffer and the  :meth:`read\*` methods
  don't use that buffer.   Instead they would return the data following the
  buffer, causing the data to appear out of order.  Mixing iteration and these
  methods will now trigger a :exc:`ValueError` from the :meth:`read\*` method.
  (Implemented by Thomas Wouters.)

  .. Patch 1397960

* The :mod:`struct` module now compiles structure format  strings into an
  internal representation and caches this representation, yielding a 20% speedup.
  (Contributed by Bob Ippolito at the NeedForSpeed sprint.)

* The :mod:`re` module got a 1 or 2% speedup by switching to  Python's allocator
  functions instead of the system's  :c:func:`malloc` and :c:func:`free`.
  (Contributed by Jack Diederich at the NeedForSpeed sprint.)

* The code generator's peephole optimizer now performs simple constant folding
  in expressions.  If you write something like ``a = 2+3``, the code generator
  will do the arithmetic and produce code corresponding to ``a = 5``.  (Proposed
  and implemented  by Raymond Hettinger.)

* Function calls are now faster because code objects now keep  the most recently
  finished frame (a "zombie frame") in an internal field of the code object,
  reusing it the next time the code object is invoked.  (Original patch by Michael
  Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
  sprint.)  Frame objects are also slightly smaller, which may improve cache
  locality and reduce memory usage a bit.  (Contributed by Neal Norwitz.)

  .. Patch 876206
  .. Patch 1337051

* Python's built-in exceptions are now new-style classes, a change that speeds
  up instantiation considerably.  Exception handling in Python 2.5 is therefore
  about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
  Sean Reifschneider at the NeedForSpeed sprint.)

* Importing now caches the paths tried, recording whether  they exist or not so
  that the interpreter makes fewer  :c:func:`open` and :c:func:`stat` calls on
  startup. (Contributed by Martin von Löwis and Georg Brandl.)

  .. Patch 921466

.. ======================================================================


.. _25modules:

New, Improved, and Removed Modules
==================================

The standard library received many enhancements and bug fixes in Python 2.5.
Here's a partial list of the most notable changes, sorted alphabetically by
module name. Consult the :file:`Misc/NEWS` file in the source tree for a more
complete list of changes, or look through the SVN logs for all the details.

* The :mod:`audioop` module now supports the a-LAW encoding, and the code for
  u-LAW encoding has been improved.  (Contributed by Lars Immisch.)

* The :mod:`codecs` module gained support for incremental codecs.  The
  :func:`codec.lookup` function now returns a :class:`CodecInfo` instance instead
  of a tuple. :class:`CodecInfo` instances behave like a 4-tuple to preserve
  backward compatibility but also have the attributes :attr:`encode`,
  :attr:`decode`, :attr:`incrementalencoder`, :attr:`incrementaldecoder`,
  :attr:`streamwriter`, and :attr:`streamreader`.  Incremental codecs  can receive
  input and produce output in multiple chunks; the output is the same as if the
  entire input was fed to the non-incremental codec. See the :mod:`codecs` module
  documentation for details. (Designed and implemented by Walter Dörwald.)

  .. Patch  1436130

* The :mod:`collections` module gained a new type, :class:`defaultdict`, that
  subclasses the standard :class:`dict` type.  The new type mostly behaves like a
  dictionary but constructs a default value when a key isn't present,
  automatically adding it to the dictionary for the requested key value.

  The first argument to :class:`defaultdict`'s constructor is a factory function
  that gets called whenever a key is requested but not found. This factory
  function receives no arguments, so you can use built-in type constructors such
  as :func:`list` or :func:`int`.  For example,  you can make an index of words
  based on their initial letter like this::

     words = """Nel mezzo del cammin di nostra vita
     mi ritrovai per una selva oscura
     che la diritta via era smarrita""".lower().split()

     index = defaultdict(list)

     for w in words:
         init_letter = w[0]
         index[init_letter].append(w)

  Printing ``index`` results in the following output::

     defaultdict(<type 'list'>, {'c': ['cammin', 'che'], 'e': ['era'],
             'd': ['del', 'di', 'diritta'], 'm': ['mezzo', 'mi'],
             'l': ['la'], 'o': ['oscura'], 'n': ['nel', 'nostra'],
             'p': ['per'], 's': ['selva', 'smarrita'],
             'r': ['ritrovai'], 'u': ['una'], 'v': ['vita', 'via']}

  (Contributed by Guido van Rossum.)

* The :class:`deque` double-ended queue type supplied by the :mod:`collections`
  module now has a ``remove(value)`` method that removes the first occurrence
  of *value* in the queue, raising :exc:`ValueError` if the value isn't found.
  (Contributed by Raymond Hettinger.)

* New module: The :mod:`contextlib` module contains helper functions for use
  with the new ':keyword:`with`' statement.  See section :ref:`contextlibmod`
  for more about this module.

* New module: The :mod:`cProfile` module is a C implementation of  the existing
  :mod:`profile` module that has much lower overhead. The module's interface is
  the same as :mod:`profile`: you run ``cProfile.run('main()')`` to profile a
  function, can save profile data to a file, etc.  It's not yet known if the
  Hotshot profiler, which is also written in C but doesn't match the
  :mod:`profile` module's interface, will continue to be maintained in future
  versions of Python.  (Contributed by Armin Rigo.)

  Also, the :mod:`pstats` module for analyzing the data measured by the profiler
  now supports directing the output to any file object by supplying a *stream*
  argument to the :class:`Stats` constructor. (Contributed by Skip Montanaro.)

* The :mod:`csv` module, which parses files in comma-separated value format,
  received several enhancements and a number of bugfixes.  You can now set the
  maximum size in bytes of a field by calling the
  ``csv.field_size_limit(new_limit)`` function; omitting the *new_limit*
  argument will return the currently-set limit.  The :class:`reader` class now has
  a :attr:`line_num` attribute that counts the number of physical lines read from
  the source; records can span multiple physical lines, so :attr:`line_num` is not
  the same as the number of records read.

  The CSV parser is now stricter about multi-line quoted fields. Previously, if a
  line ended within a quoted field without a terminating newline character, a
  newline would be inserted into the returned field. This behavior caused problems
  when reading files that contained carriage return characters within fields, so
  the code was changed to return the field without inserting newlines. As a
  consequence, if newlines embedded within fields are important, the input should
  be split into lines in a manner that preserves the newline characters.

  (Contributed by Skip Montanaro and Andrew McNamara.)

* The :class:`~datetime.datetime` class in the :mod:`datetime`  module now has a
  ``strptime(string, format)``  method for parsing date strings, contributed
  by Josh Spoerri. It uses the same format characters as :func:`time.strptime` and
  :func:`time.strftime`::

     from datetime import datetime

     ts = datetime.strptime('10:13:15 2006-03-07',
                            '%H:%M:%S %Y-%m-%d')

* The :meth:`SequenceMatcher.get_matching_blocks` method in the :mod:`difflib`
  module now guarantees to return a minimal list of blocks describing matching
  subsequences.  Previously, the algorithm would occasionally break a block of
  matching elements into two list entries. (Enhancement by Tim Peters.)

* The :mod:`doctest` module gained a ``SKIP`` option that keeps an example from
  being executed at all.  This is intended for code snippets that are usage
  examples intended for the reader and aren't actually test cases.

  An *encoding* parameter was added to the :func:`testfile` function and the
  :class:`DocFileSuite` class to specify the file's encoding.  This makes it
  easier to use non-ASCII characters in  tests contained within a docstring.
  (Contributed by Bjorn Tillenius.)

  .. Patch 1080727

* The :mod:`email` package has been updated to version 4.0. (Contributed by
  Barry Warsaw.)

  .. XXX need to provide some more detail here

  .. index::
     single: universal newlines; What's new

* The :mod:`fileinput` module was made more flexible. Unicode filenames are now
  supported, and a *mode* parameter that defaults to ``"r"`` was added to the
  :func:`input` function to allow opening files in binary or :term:`universal
  newlines` mode.  Another new parameter, *openhook*, lets you use a function
  other than :func:`open`  to open the input files.  Once you're iterating over
  the set of files, the :class:`FileInput` object's new :meth:`fileno` returns
  the file descriptor for the currently opened file. (Contributed by Georg
  Brandl.)

* In the :mod:`gc` module, the new :func:`get_count` function returns a 3-tuple
  containing the current collection counts for the three GC generations.  This is
  accounting information for the garbage collector; when these counts reach a
  specified threshold, a garbage collection sweep will be made.  The existing
  :func:`gc.collect` function now takes an optional *generation* argument of 0, 1,
  or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)

* The :func:`nsmallest` and  :func:`nlargest` functions in the :mod:`heapq`
  module  now support a ``key`` keyword parameter similar to the one provided by
  the :func:`min`/:func:`max` functions and the :meth:`sort` methods.  For
  example::

     >>> import heapq
     >>> L = ["short", 'medium', 'longest', 'longer still']
     >>> heapq.nsmallest(2, L)  # Return two lowest elements, lexicographically
     ['longer still', 'longest']
     >>> heapq.nsmallest(2, L, key=len)   # Return two shortest elements
     ['short', 'medium']

  (Contributed by Raymond Hettinger.)

* The :func:`itertools.islice` function now accepts ``None`` for the start and
  step arguments.  This makes it more compatible with the attributes of slice
  objects, so that you can now write the following::

     s = slice(5)     # Create slice object
     itertools.islice(iterable, s.start, s.stop, s.step)

  (Contributed by Raymond Hettinger.)

* The :func:`format` function in the :mod:`locale` module has been modified and
  two new functions were added, :func:`format_string` and :func:`currency`.

  The :func:`format` function's *val* parameter could previously be a string as
  long as no more than one %char specifier appeared; now the parameter must be
  exactly one %char specifier with no surrounding text.  An optional *monetary*
  parameter was also added which, if ``True``, will use the locale's rules for
  formatting currency in placing a separator between groups of three digits.

  To format strings with multiple %char specifiers, use the new
  :func:`format_string` function that works like :func:`format` but also supports
  mixing %char specifiers with arbitrary text.

  A new :func:`currency` function was also added that formats a number according
  to the current locale's settings.

  (Contributed by Georg Brandl.)

  .. Patch 1180296

* The :mod:`mailbox` module underwent a massive rewrite to add the capability to
  modify mailboxes in addition to reading them.  A new set of classes that include
  :class:`mbox`, :class:`MH`, and :class:`Maildir` are used to read mailboxes, and
  have an ``add(message)`` method to add messages, ``remove(key)`` to
  remove messages, and :meth:`lock`/:meth:`unlock` to lock/unlock the mailbox.
  The following example converts a maildir-format mailbox into an mbox-format
  one::

     import mailbox

     # 'factory=None' uses email.Message.Message as the class representing
     # individual messages.
     src = mailbox.Maildir('maildir', factory=None)
     dest = mailbox.mbox('/tmp/mbox')

     for msg in src:
         dest.add(msg)

  (Contributed by Gregory K. Johnson.  Funding was provided by Google's 2005
  Summer of Code.)

* New module: the :mod:`msilib` module allows creating Microsoft Installer
  :file:`.msi` files and CAB files.  Some support for reading the :file:`.msi`
  database is also included. (Contributed by Martin von Löwis.)

* The :mod:`nis` module now supports accessing domains other than the system
  default domain by supplying a *domain* argument to the :func:`nis.match` and
  :func:`nis.maps` functions. (Contributed by Ben Bell.)

* The :mod:`operator` module's :func:`itemgetter`  and :func:`attrgetter`
  functions now support multiple fields.   A call such as
  ``operator.attrgetter('a', 'b')`` will return a function  that retrieves the
  :attr:`a` and :attr:`b` attributes.  Combining  this new feature with the
  :meth:`sort` method's ``key`` parameter  lets you easily sort lists using
  multiple fields. (Contributed by Raymond Hettinger.)

* The :mod:`optparse` module was updated to version 1.5.1 of the Optik library.
  The :class:`OptionParser` class gained an :attr:`epilog` attribute, a string
  that will be printed after the help message, and a :meth:`destroy` method to
  break reference cycles created by the object. (Contributed by Greg Ward.)

* The :mod:`os` module underwent several changes.  The :attr:`stat_float_times`
  variable now defaults to true, meaning that :func:`os.stat` will now return time
  values as floats.  (This doesn't necessarily mean that :func:`os.stat` will
  return times that are precise to fractions of a second; not all systems support
  such precision.)

  Constants named :attr:`os.SEEK_SET`, :attr:`os.SEEK_CUR`, and
  :attr:`os.SEEK_END` have been added; these are the parameters to the
  :func:`os.lseek` function.  Two new constants for locking are
  :attr:`os.O_SHLOCK` and :attr:`os.O_EXLOCK`.

  Two new functions, :func:`wait3` and :func:`wait4`, were added.  They're similar
  the :func:`waitpid` function which waits for a child process to exit and returns
  a tuple of the process ID and its exit status, but :func:`wait3` and
  :func:`wait4` return additional information.  :func:`wait3` doesn't take a
  process ID as input, so it waits for any child process to exit and returns a
  3-tuple of *process-id*, *exit-status*, *resource-usage* as returned from the
  :func:`resource.getrusage` function. ``wait4(pid)`` does take a process ID.
  (Contributed by Chad J. Schroeder.)

  On FreeBSD, the :func:`os.stat` function now returns  times with nanosecond
  resolution, and the returned object now has :attr:`st_gen` and
  :attr:`st_birthtime`. The :attr:`st_flags` attribute is also available, if the
  platform supports it. (Contributed by Antti Louko and  Diego Pettenò.)

  .. (Patch 1180695, 1212117)

* The Python debugger provided by the :mod:`pdb` module can now store lists of
  commands to execute when a breakpoint is reached and execution stops.  Once
  breakpoint #1 has been created, enter ``commands 1`` and enter a series of
  commands to be executed, finishing the list with ``end``.  The command list can
  include commands that resume execution, such as ``continue`` or ``next``.
  (Contributed by Grégoire Dooms.)

  .. Patch 790710

* The :mod:`pickle` and :mod:`cPickle` modules no longer accept a return value
  of ``None`` from the :meth:`__reduce__` method; the method must return a tuple
  of arguments instead.  The ability to return ``None`` was deprecated in Python
  2.4, so this completes the removal of the feature.

* The :mod:`pkgutil` module, containing various utility functions for finding
  packages, was enhanced to support PEP 302's import hooks and now also works for
  packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)

* The pybench benchmark suite by Marc-André Lemburg is now included in the
  :file:`Tools/pybench` directory.  The pybench suite is an improvement on the
  commonly used :file:`pystone.py` program because pybench provides a more
  detailed measurement of the interpreter's speed.  It times particular operations
  such as function calls, tuple slicing, method lookups, and numeric operations,
  instead of performing many different operations and reducing the result to a
  single number as :file:`pystone.py` does.

* The :mod:`pyexpat` module now uses version 2.0 of the Expat parser.
  (Contributed by Trent Mick.)

* The :class:`~Queue.Queue` class provided by the :mod:`Queue` module gained two new
  methods.  :meth:`join` blocks until all items in the queue have been retrieved
  and all processing work on the items  have been completed.  Worker threads call
  the other new method,  :meth:`task_done`, to signal that processing for an item
  has been completed.  (Contributed by Raymond Hettinger.)

* The old :mod:`regex` and :mod:`regsub` modules, which have been  deprecated
  ever since Python 2.0, have finally been deleted.   Other deleted modules:
  :mod:`statcache`, :mod:`tzparse`, :mod:`whrandom`.

* Also deleted: the :file:`lib-old` directory, which includes ancient modules
  such as :mod:`dircmp` and :mod:`ni`, was removed.  :file:`lib-old` wasn't on the
  default ``sys.path``, so unless your programs explicitly added the directory to
  ``sys.path``, this removal shouldn't affect your code.

* The :mod:`rlcompleter` module is no longer  dependent on importing the
  :mod:`readline` module and therefore now works on non-Unix platforms. (Patch
  from Robert Kiendl.)

  .. Patch #1472854

* The :mod:`SimpleXMLRPCServer` and :mod:`DocXMLRPCServer`  classes now have a
  :attr:`rpc_paths` attribute that constrains XML-RPC operations to a limited set
  of URL paths; the default is to allow only ``'/'`` and ``'/RPC2'``.  Setting
  :attr:`rpc_paths` to ``None`` or an empty tuple disables  this path checking.

  .. Bug #1473048

* The :mod:`socket` module now supports :const:`AF_NETLINK` sockets on Linux,
  thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
  mechanism for communications between a user-space process and kernel code; an
  introductory  article about them is at https://www.linuxjournal.com/article/7356.
  In Python code, netlink addresses are represented as a tuple of 2 integers,
  ``(pid, group_mask)``.

  Two new methods on socket objects, ``recv_into(buffer)`` and
  ``recvfrom_into(buffer)``, store the received data in an object  that
  supports the buffer protocol instead of returning the data as a string.  This
  means you can put the data directly into an array or a memory-mapped file.

  Socket objects also gained :meth:`getfamily`, :meth:`gettype`, and
  :meth:`getproto` accessor methods to retrieve the family, type, and protocol
  values for the socket.

* New module: the :mod:`spwd` module provides functions for accessing the shadow
  password database on systems that support  shadow passwords.

* The :mod:`struct` is now faster because it  compiles format strings into
  :class:`Struct` objects with :meth:`pack` and :meth:`unpack` methods.  This is
  similar to how the :mod:`re` module lets you create compiled regular expression
  objects.  You can still use the module-level  :func:`pack` and :func:`unpack`
  functions; they'll create  :class:`Struct` objects and cache them.  Or you can
  use  :class:`Struct` instances directly::

     s = struct.Struct('ih3s')

     data = s.pack(1972, 187, 'abc')
     year, number, name = s.unpack(data)

  You can also pack and unpack data to and from buffer objects directly using the
  ``pack_into(buffer, offset, v1, v2, ...)`` and ``unpack_from(buffer,
  offset)`` methods.  This lets you store data directly into an array or a
  memory-mapped file.

  (:class:`Struct` objects were implemented by Bob Ippolito at the NeedForSpeed
  sprint.  Support for buffer objects was added by Martin Blais, also at the
  NeedForSpeed sprint.)

* The Python developers switched from CVS to Subversion during the 2.5
  development process.  Information about the exact build version is available as
  the ``sys.subversion`` variable, a 3-tuple of ``(interpreter-name, branch-name,
  revision-range)``.  For example, at the time of writing my copy of 2.5 was
  reporting ``('CPython', 'trunk', '45313:45315')``.

  This information is also available to C extensions via the
  :c:func:`Py_GetBuildInfo` function that returns a  string of build information
  like this: ``"trunk:45355:45356M, Apr 13 2006, 07:42:19"``.   (Contributed by
  Barry Warsaw.)

* Another new function, :func:`sys._current_frames`, returns the current stack
  frames for all running threads as a dictionary mapping thread identifiers to the
  topmost stack frame currently active in that thread at the time the function is
  called.  (Contributed by Tim Peters.)

* The :class:`TarFile` class in the :mod:`tarfile` module now has an
  :meth:`extractall` method that extracts all members from the archive into the
  current working directory.  It's also possible to set a different directory as
  the extraction target, and to unpack only a subset of the archive's members.

  The compression used for a tarfile opened in stream mode can now be autodetected
  using the mode ``'r|*'``. (Contributed by Lars Gustäbel.)

  .. patch 918101

* The :mod:`threading` module now lets you set the stack size used when new
  threads are created. The ``stack_size([*size*])`` function returns the
  currently configured stack size, and supplying the optional *size* parameter
  sets a new value.  Not all platforms support changing the stack size, but
  Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)

  .. Patch 1454481

* The :mod:`unicodedata` module has been updated to use version 4.1.0 of the
  Unicode character database.  Version 3.2.0 is required  by some specifications,
  so it's still available as  :attr:`unicodedata.ucd_3_2_0`.

* New module: the  :mod:`uuid` module generates  universally unique identifiers
  (UUIDs) according to :rfc:`4122`.  The RFC defines several different UUID
  versions that are generated from a starting string, from system properties, or
  purely randomly.  This module contains a :class:`UUID` class and  functions
  named :func:`uuid1`, :func:`uuid3`, :func:`uuid4`,  and  :func:`uuid5` to
  generate different versions of UUID.  (Version 2 UUIDs  are not specified in
  :rfc:`4122` and are not supported by this module.) ::

     >>> import uuid
     >>> # make a UUID based on the host ID and current time
     >>> uuid.uuid1()
     UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

     >>> # make a UUID using an MD5 hash of a namespace UUID and a name
     >>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
     UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

     >>> # make a random UUID
     >>> uuid.uuid4()
     UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

     >>> # make a UUID using a SHA-1 hash of a namespace UUID and a name
     >>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
     UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

  (Contributed by Ka-Ping Yee.)

* The :mod:`weakref` module's :class:`WeakKeyDictionary` and
  :class:`WeakValueDictionary` types gained new methods for iterating over the
  weak references contained in the dictionary.  :meth:`iterkeyrefs` and
  :meth:`keyrefs` methods were added to :class:`WeakKeyDictionary`, and
  :meth:`itervaluerefs` and :meth:`valuerefs` were added to
  :class:`WeakValueDictionary`.  (Contributed by Fred L. Drake, Jr.)

* The :mod:`webbrowser` module received a number of enhancements. It's now
  usable as a script with ``python -m webbrowser``, taking a URL as the argument;
  there are a number of switches  to control the behaviour (:option:`!-n` for a new
  browser window,  :option:`!-t` for a new tab).  New module-level functions,
  :func:`open_new` and :func:`open_new_tab`, were added  to support this.  The
  module's :func:`open` function supports an additional feature, an *autoraise*
  parameter that signals whether to raise the open window when possible. A number
  of additional browsers were added to the supported list such as Firefox, Opera,
  Konqueror, and elinks.  (Contributed by Oleg Broytmann and Georg Brandl.)

  .. Patch #754022

* The :mod:`xmlrpclib` module now supports returning  :class:`~datetime.datetime` objects
  for the XML-RPC date type.  Supply  ``use_datetime=True`` to the :func:`loads`
  function or the :class:`Unmarshaller` class to enable this feature. (Contributed
  by Skip Montanaro.)

  .. Patch 1120353

* The :mod:`zipfile` module now supports the ZIP64 version of the  format,
  meaning that a .zip archive can now be larger than 4 GiB and can contain
  individual files larger than 4 GiB.  (Contributed by Ronald Oussoren.)

  .. Patch 1446489

* The :mod:`zlib` module's :class:`Compress` and :class:`Decompress` objects now
  support a :meth:`copy` method that makes a copy of the  object's internal state
  and returns a new  :class:`Compress` or :class:`Decompress` object.
  (Contributed by Chris AtLee.)

  .. Patch 1435422

.. ======================================================================


.. _module-ctypes:

The ctypes package
------------------

The :mod:`ctypes` package, written by Thomas Heller, has been added  to the
standard library.  :mod:`ctypes` lets you call arbitrary functions  in shared
libraries or DLLs.  Long-time users may remember the :mod:`dl` module, which
provides functions for loading shared libraries and calling functions in them.
The :mod:`ctypes` package is much fancier.

To load a shared library or DLL, you must create an instance of the
:class:`CDLL` class and provide the name or path of the shared library or DLL.
Once that's done, you can call arbitrary functions by accessing them as
attributes of the :class:`CDLL` object.   ::

   import ctypes

   libc = ctypes.CDLL('libc.so.6')
   result = libc.printf("Line of output\n")

Type constructors for the various C types are provided: :func:`c_int`,
:func:`c_float`, :func:`c_double`, :func:`c_char_p` (equivalent to :c:type:`char
\*`), and so forth.  Unlike Python's types, the C versions are all mutable; you
can assign to their :attr:`value` attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the corresponding C
types, but for other types you  must call the correct type constructor.  (And I
mean *must*;  getting it wrong will often result in the interpreter crashing
with a segmentation fault.)

You shouldn't use :func:`c_char_p` with a Python string when the C function will
be modifying the memory area, because Python strings are  supposed to be
immutable; breaking this rule will cause puzzling bugs.  When you need a
modifiable memory area, use :func:`create_string_buffer`::

   s = "this is a string"
   buf = ctypes.create_string_buffer(s)
   libc.strfry(buf)

C functions are assumed to return integers, but you can set the :attr:`restype`
attribute of the function object to  change this::

   >>> libc.atof('2.71828')
   -1783957616
   >>> libc.atof.restype = ctypes.c_double
   >>> libc.atof('2.71828')
   2.71828

:mod:`ctypes` also provides a wrapper for Python's C API  as the
``ctypes.pythonapi`` object.  This object does *not*  release the global
interpreter lock before calling a function, because the lock must be held when
calling into the interpreter's code.   There's a :class:`py_object()` type
constructor that will create a  :c:type:`PyObject \*` pointer.  A simple usage::

   import ctypes

   d = {}
   ctypes.pythonapi.PyObject_SetItem(ctypes.py_object(d),
             ctypes.py_object("abc"),  ctypes.py_object(1))
   # d is now {'abc', 1}.

Don't forget to use :class:`py_object()`; if it's omitted you end  up with a
segmentation fault.

:mod:`ctypes` has been around for a while, but people still write  and
distribution hand-coded extension modules because you can't rely on
:mod:`ctypes` being present. Perhaps developers will begin to write  Python
wrappers atop a library accessed through :mod:`ctypes` instead of extension
modules, now that :mod:`ctypes` is included with core Python.


.. seealso::

   http://starship.python.net/crew/theller/ctypes/
      The ctypes web page, with a tutorial, reference, and FAQ.

   The documentation  for the :mod:`ctypes` module.

.. ======================================================================


.. _module-etree:

The ElementTree package
-----------------------

A subset of Fredrik Lundh's ElementTree library for processing XML has been
added to the standard library as :mod:`xml.etree`.  The available modules are
:mod:`ElementTree`, :mod:`ElementPath`, and :mod:`ElementInclude` from
ElementTree 1.2.6.    The :mod:`cElementTree` accelerator module is also
included.

The rest of this section will provide a brief overview of using ElementTree.
Full documentation for ElementTree is available at
http://effbot.org/zone/element-index.htm.

ElementTree represents an XML document as a tree of element nodes. The text
content of the document is stored as the :attr:`text` and :attr:`tail`
attributes of  (This is one of the major differences between ElementTree and
the Document Object Model; in the DOM there are many different types of node,
including :class:`TextNode`.)

The most commonly used parsing function is :func:`parse`, that takes either a
string (assumed to contain a filename) or a file-like object and returns an
:class:`ElementTree` instance::

   from xml.etree import ElementTree as ET

   tree = ET.parse('ex-1.xml')

   feed = urllib.urlopen(
             'http://planet.python.org/rss10.xml')
   tree = ET.parse(feed)

Once you have an :class:`ElementTree` instance, you can call its :meth:`getroot`
method to get the root :class:`Element` node.

There's also an :func:`XML` function that takes a string literal and returns an
:class:`Element` node (not an :class:`ElementTree`).   This function provides a
tidy way to incorporate XML fragments, approaching the convenience of an XML
literal::

   svg = ET.XML("""<svg width="10px" version="1.0">
                </svg>""")
   svg.set('height', '320px')
   svg.append(elem1)

Each XML element supports some dictionary-like and some list-like access
methods.  Dictionary-like operations are used to access attribute values, and
list-like operations are used to access child nodes.

+-------------------------------+--------------------------------------------+
| Operation                     | Result                                     |
+===============================+============================================+
| ``elem[n]``                   | Returns n'th child element.                |
+-------------------------------+--------------------------------------------+
| ``elem[m:n]``                 | Returns list of m'th through n'th child    |
|                               | elements.                                  |
+-------------------------------+--------------------------------------------+
| ``len(elem)``                 | Returns number of child elements.          |
+-------------------------------+--------------------------------------------+
| ``list(elem)``                | Returns list of child elements.            |
+-------------------------------+--------------------------------------------+
| ``elem.append(elem2)``        | Adds *elem2* as a child.                   |
+-------------------------------+--------------------------------------------+
| ``elem.insert(index, elem2)`` | Inserts *elem2* at the specified location. |
+-------------------------------+--------------------------------------------+
| ``del elem[n]``               | Deletes n'th child element.                |
+-------------------------------+--------------------------------------------+
| ``elem.keys()``               | Returns list of attribute names.           |
+-------------------------------+--------------------------------------------+
| ``elem.get(name)``            | Returns value of attribute *name*.         |
+-------------------------------+--------------------------------------------+
| ``elem.set(name, value)``     | Sets new value for attribute *name*.       |
+-------------------------------+--------------------------------------------+
| ``elem.attrib``               | Retrieves the dictionary containing        |
|                               | attributes.                                |
+-------------------------------+--------------------------------------------+
| ``del elem.attrib[name]``     | Deletes attribute *name*.                  |
+-------------------------------+--------------------------------------------+

Comments and processing instructions are also represented as :class:`Element`
nodes.  To check if a node is a comment or processing instructions::

   if elem.tag is ET.Comment:
       ...
   elif elem.tag is ET.ProcessingInstruction:
       ...

To generate XML output, you should call the :meth:`ElementTree.write` method.
Like :func:`parse`, it can take either a string or a file-like object::

   # Encoding is US-ASCII
   tree.write('output.xml')

   # Encoding is UTF-8
   f = open('output.xml', 'w')
   tree.write(f, encoding='utf-8')

(Caution: the default encoding used for output is ASCII.  For general XML work,
where an element's name may contain arbitrary Unicode characters, ASCII isn't a
very useful encoding because it will raise an exception if an element's name
contains any characters with values greater than 127.  Therefore, it's best to
specify a different encoding such as UTF-8 that can handle any Unicode
character.)

This section is only a partial description of the ElementTree interfaces. Please
read the package's official documentation for more details.


.. seealso::

   http://effbot.org/zone/element-index.htm
      Official documentation for ElementTree.

.. ======================================================================


.. _module-hashlib:

The hashlib package
-------------------

A new :mod:`hashlib` module, written by Gregory P. Smith,  has been added to
replace the :mod:`md5` and :mod:`sha` modules.  :mod:`hashlib` adds support for
additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
available, the module uses OpenSSL for fast platform optimized implementations
of algorithms.

The old :mod:`md5` and :mod:`sha` modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module's interface is very close
to that of the old modules, but not identical. The most significant difference
is that the constructor functions for creating new hashing objects are named
differently. ::

   # Old versions
   h = md5.md5()
   h = md5.new()

   # New version
   h = hashlib.md5()

   # Old versions
   h = sha.sha()
   h = sha.new()

   # New version
   h = hashlib.sha1()

   # Hash that weren't previously available
   h = hashlib.sha224()
   h = hashlib.sha256()
   h = hashlib.sha384()
   h = hashlib.sha512()

   # Alternative form
   h = hashlib.new('md5')          # Provide algorithm as a string

Once a hash object has been created, its methods are the same as before:
``update(string)`` hashes the specified string into the  current digest
state, :meth:`digest` and :meth:`hexdigest` return the digest value as a binary
string or a string of hex digits, and :meth:`copy` returns a new hashing object
with the same digest state.


.. seealso::

   The documentation  for the :mod:`hashlib` module.

.. ======================================================================


.. _module-sqlite:

The sqlite3 package
-------------------

The pysqlite module (http://www.pysqlite.org), a wrapper for the SQLite embedded
database, has been added to the standard library under the package name
:mod:`sqlite3`.

SQLite is a C library that provides a lightweight disk-based database that
doesn't require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage.  It's also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.

pysqlite was written by Gerhard Häring and provides a SQL interface compliant
with the DB-API 2.0 specification described by :pep:`249`.

If you're compiling the Python source yourself, note that the source tree
doesn't include the SQLite code, only the wrapper module. You'll need to have
the SQLite libraries and headers installed before compiling Python, and the
build process will compile the module when the necessary headers are available.

To use the module, you must first create a :class:`Connection` object that
represents the database.  Here the data will be stored in the
:file:`/tmp/example` file::

   conn = sqlite3.connect('/tmp/example')

You can also supply the special name ``:memory:`` to create a database in RAM.

Once you have a :class:`Connection`, you can create a :class:`Cursor`  object
and call its :meth:`execute` method to perform SQL commands::

   c = conn.cursor()

   # Create table
   c.execute('''create table stocks
   (date text, trans text, symbol text,
    qty real, price real)''')

   # Insert a row of data
   c.execute("""insert into stocks
             values ('2006-01-05','BUY','RHAT',100,35.14)""")

Usually your SQL operations will need to use values from Python variables.  You
shouldn't assemble your query using Python's string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack.

Instead, use the DB-API's parameter substitution.  Put ``?`` as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor's :meth:`execute` method.  (Other database modules
may use a different placeholder, such as ``%s`` or ``:1``.) For example::

   # Never do this -- insecure!
   symbol = 'IBM'
   c.execute("... where symbol = '%s'" % symbol)

   # Do this instead
   t = (symbol,)
   c.execute('select * from stocks where symbol=?', t)

   # Larger example
   for t in (('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
             ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
             ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
            ):
       c.execute('insert into stocks values (?,?,?,?,?)', t)

To retrieve data after executing a SELECT statement, you can either  treat the
cursor as an iterator, call the cursor's :meth:`fetchone` method to retrieve a
single matching row,  or call :meth:`fetchall` to get a list of the matching
rows.

This example uses the iterator form::

   >>> c = conn.cursor()
   >>> c.execute('select * from stocks order by price')
   >>> for row in c:
   ...    print row
   ...
   (u'2006-01-05', u'BUY', u'RHAT', 100, 35.140000000000001)
   (u'2006-03-28', u'BUY', u'IBM', 1000, 45.0)
   (u'2006-04-06', u'SELL', u'IBM', 500, 53.0)
   (u'2006-04-05', u'BUY', u'MSOFT', 1000, 72.0)
   >>>

For more information about the SQL dialect supported by SQLite, see
https://www.sqlite.org.


.. seealso::

   http://www.pysqlite.org
      The pysqlite web page.

   https://www.sqlite.org
      The SQLite web page; the documentation describes the syntax and the available
      data types for the supported SQL dialect.

   The documentation  for the :mod:`sqlite3` module.

   :pep:`249` - Database API Specification 2.0
      PEP written by Marc-André Lemburg.

.. ======================================================================


.. _module-wsgiref:

The wsgiref package
-------------------

The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface
between web servers and Python web applications and is described in :pep:`333`.
The :mod:`wsgiref` package is a reference implementation of the WSGI
specification.

.. XXX should this be in a PEP 333 section instead?

The package includes a basic HTTP server that will run a WSGI application; this
server is useful for debugging but isn't intended for  production use.  Setting
up a server takes only a few lines of code::

   from wsgiref import simple_server

   wsgi_app = ...

   host = ''
   port = 8000
   httpd = simple_server.make_server(host, port, wsgi_app)
   httpd.serve_forever()

.. XXX discuss structure of WSGI applications?
.. XXX provide an example using Django or some other framework?


.. seealso::

   http://www.wsgi.org
      A central web site for WSGI-related resources.

   :pep:`333` - Python Web Server Gateway Interface v1.0
      PEP written by Phillip J. Eby.

.. ======================================================================


.. _build-api:

Build and C API Changes
=======================

Changes to Python's build process and to the C API include:

* The Python source tree was converted from CVS to Subversion,  in a complex
  migration procedure that was supervised and flawlessly carried out by Martin von
  Löwis.  The procedure was developed as :pep:`347`.

* Coverity, a company that markets a source code analysis tool called Prevent,
  provided the results of their examination of the Python source code.  The
  analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
  refcounting problems, often occurring in error-handling code.  See
  https://scan.coverity.com for the statistics.

* The largest change to the C API came from :pep:`353`, which modifies the
  interpreter to use a :c:type:`Py_ssize_t` type definition instead of
  :c:type:`int`.  See the earlier section :ref:`pep-353` for a discussion of this
  change.

* The design of the bytecode compiler has changed a great deal,  no longer
  generating bytecode by traversing the parse tree.  Instead the parse tree is
  converted to an abstract syntax tree (or AST), and it is  the abstract syntax
  tree that's traversed to produce the bytecode.

  It's possible for Python code to obtain AST objects by using the
  :func:`compile` built-in and specifying ``_ast.PyCF_ONLY_AST`` as the value of
  the  *flags* parameter::

     from _ast import PyCF_ONLY_AST
     ast = compile("""a=0
     for i in range(10):
         a += i
     """, "<string>", 'exec', PyCF_ONLY_AST)

     assignment = ast.body[0]
     for_loop = ast.body[1]

  No official documentation has been written for the AST code yet, but :pep:`339`
  discusses the design.  To start learning about the code, read the definition of
  the various AST nodes in :file:`Parser/Python.asdl`.  A Python script reads this
  file and generates a set of C structure definitions in
  :file:`Include/Python-ast.h`.  The :c:func:`PyParser_ASTFromString` and
  :c:func:`PyParser_ASTFromFile`, defined in :file:`Include/pythonrun.h`, take
  Python source as input and return the root of an AST representing the contents.
  This AST can then be turned into a code object by :c:func:`PyAST_Compile`.  For
  more information, read the source code, and then ask questions on python-dev.

  The AST code was developed under Jeremy Hylton's management, and implemented by
  (in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
  Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
  Schemenauer, plus the participants in a number of AST sprints at conferences
  such as PyCon.

  .. List of names taken from Jeremy's python-dev post at
  .. https://mail.python.org/pipermail/python-dev/2005-October/057500.html

* Evan Jones's patch to obmalloc, first described in a talk at PyCon DC 2005,
  was applied.  Python 2.4 allocated small objects in 256K-sized arenas, but never
  freed arenas.  With this patch, Python will free arenas when they're empty.  The
  net effect is that on some platforms, when you allocate many objects, Python's
  memory usage may actually drop when you delete them and the memory may be
  returned to the operating system.  (Implemented by Evan Jones, and reworked by
  Tim Peters.)

  Note that this change means extension modules must be more careful when
  allocating memory.  Python's API has many different functions for allocating
  memory that are grouped into families.  For example, :c:func:`PyMem_Malloc`,
  :c:func:`PyMem_Realloc`, and :c:func:`PyMem_Free` are one family that allocates
  raw memory, while :c:func:`PyObject_Malloc`, :c:func:`PyObject_Realloc`, and
  :c:func:`PyObject_Free` are another family that's supposed to be used for
  creating Python objects.

  Previously these different families all reduced to the platform's
  :c:func:`malloc` and :c:func:`free` functions.  This meant  it didn't matter if
  you got things wrong and allocated memory with the :c:func:`PyMem` function but
  freed it with the :c:func:`PyObject` function.  With 2.5's changes to obmalloc,
  these families now do different things and mismatches will probably result in a
  segfault.  You should carefully test your C extension modules with Python 2.5.

* The built-in set types now have an official C API.  Call :c:func:`PySet_New`
  and :c:func:`PyFrozenSet_New` to create a new set, :c:func:`PySet_Add` and
  :c:func:`PySet_Discard` to add and remove elements, and :c:func:`PySet_Contains`
  and :c:func:`PySet_Size` to examine the set's state. (Contributed by Raymond
  Hettinger.)

* C code can now obtain information about the exact revision of the Python
  interpreter by calling the  :c:func:`Py_GetBuildInfo` function that returns a
  string of build information like this: ``"trunk:45355:45356M, Apr 13 2006,
  07:42:19"``.   (Contributed by Barry Warsaw.)

* Two new macros can be used to indicate C functions that are local to the
  current file so that a faster calling convention can be used.
  ``Py_LOCAL(type)`` declares the function as returning a value of the
  specified *type* and uses a fast-calling qualifier.
  ``Py_LOCAL_INLINE(type)`` does the same thing and also requests the
  function be inlined.  If :c:func:`PY_LOCAL_AGGRESSIVE` is defined before
  :file:`python.h` is included, a set of more aggressive optimizations are enabled
  for the module; you should benchmark the results to find out if these
  optimizations actually make the code faster.  (Contributed by Fredrik Lundh at
  the NeedForSpeed sprint.)

* ``PyErr_NewException(name, base, dict)`` can now accept a tuple of base
  classes as its *base* argument.  (Contributed by Georg Brandl.)

* The :c:func:`PyErr_Warn` function for issuing warnings is now deprecated in
  favour of ``PyErr_WarnEx(category, message, stacklevel)`` which lets you
  specify the number of stack frames separating this function and the caller.  A
  *stacklevel* of 1 is the function calling :c:func:`PyErr_WarnEx`, 2 is the
  function above that, and so forth.  (Added by Neal Norwitz.)

* The CPython interpreter is still written in C, but  the code can now be
  compiled with a C++ compiler without errors.   (Implemented by Anthony Baxter,
  Martin von Löwis, Skip Montanaro.)

* The :c:func:`PyRange_New` function was removed.  It was never documented, never
  used in the core code, and had dangerously lax error checking.  In the unlikely
  case that your extensions were using it, you can replace it by something like
  the following::

     range = PyObject_CallFunction((PyObject*) &PyRange_Type, "lll",
                                   start, stop, step);

.. ======================================================================


.. _ports:

Port-Specific Changes
---------------------

* MacOS X (10.3 and higher): dynamic loading of modules now uses the
  :c:func:`dlopen` function instead of MacOS-specific functions.

* MacOS X: an :option:`!--enable-universalsdk` switch was added to the
  :program:`configure` script that compiles the interpreter as a universal binary
  able to run on both PowerPC and Intel processors. (Contributed by Ronald
  Oussoren; :issue:`2573`.)

* Windows: :file:`.dll` is no longer supported as a filename extension for
  extension modules.  :file:`.pyd` is now the only filename extension that will be
  searched for.

.. ======================================================================


.. _porting:

Porting to Python 2.5
=====================

This section lists previously described changes that may require changes to your
code:

* ASCII is now the default encoding for modules.  It's now  a syntax error if a
  module contains string literals with 8-bit characters but doesn't have an
  encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
  error.

* Previously, the :attr:`gi_frame` attribute of a generator was always a frame
  object.  Because of the :pep:`342` changes described in section :ref:`pep-342`,
  it's now possible for :attr:`gi_frame` to be ``None``.

* A new warning, :class:`UnicodeWarning`, is triggered when  you attempt to
  compare a Unicode string and an 8-bit string that can't be converted to Unicode
  using the default ASCII encoding.  Previously such comparisons would raise a
  :class:`UnicodeDecodeError` exception.

* Library: the :mod:`csv` module is now stricter about multi-line quoted fields.
  If your files contain newlines embedded within fields, the input should be split
  into lines in a manner which preserves the newline characters.

* Library: the :mod:`locale` module's  :func:`format` function's would
  previously  accept any string as long as no more than one %char specifier
  appeared.  In Python 2.5, the argument must be exactly one %char specifier with
  no surrounding text.

* Library: The :mod:`pickle` and :mod:`cPickle` modules no longer accept a
  return value of ``None`` from the :meth:`__reduce__` method; the method must
  return a tuple of arguments instead.  The modules also no longer accept the
  deprecated *bin* keyword parameter.

* Library: The :mod:`SimpleXMLRPCServer` and :mod:`DocXMLRPCServer`  classes now
  have a :attr:`rpc_paths` attribute that constrains XML-RPC operations to a
  limited set of URL paths; the default is to allow only ``'/'`` and ``'/RPC2'``.
  Setting  :attr:`rpc_paths` to ``None`` or an empty tuple disables  this path
  checking.

* C API: Many functions now use :c:type:`Py_ssize_t`  instead of :c:type:`int` to
  allow processing more data on 64-bit machines.  Extension code may need to make
  the same change to avoid warnings and to support 64-bit machines.  See the
  earlier section :ref:`pep-353` for a discussion of this change.

* C API:  The obmalloc changes mean that  you must be careful to not mix usage
  of the :c:func:`PyMem_\*` and :c:func:`PyObject_\*` families of functions. Memory
  allocated with  one family's :c:func:`\*_Malloc` must be  freed with the
  corresponding family's :c:func:`\*_Free` function.

.. ======================================================================


Acknowledgements
================

The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Georg Brandl,
Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W.
Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew
McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike
Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.

PK
%�\@��y��"html/_sources/whatsnew/2.6.rst.txtnu�[���****************************
  What's New in Python 2.6
****************************

.. XXX add trademark info for Apple, Microsoft, SourceForge.

:Author: A.M. Kuchling (amk at amk.ca)

.. $Id$
   Rules for maintenance:

   * Anyone can add text to this document.  Do not spend very much time
   on the wording of your changes, because your text will probably
   get rewritten to some degree.

   * The maintainer will go through Misc/NEWS periodically and add
   changes; it's therefore more important to add your changes to
   Misc/NEWS than to this file.

   * This is not a complete list of every single change; completeness
   is the purpose of Misc/NEWS.  Some changes I consider too small
   or esoteric to include.  If such a change is added to the text,
   I'll just remove it.  (This is another reason you shouldn't spend
   too much time on writing your addition.)

   * If you want to draw your new text to the attention of the
   maintainer, add 'XXX' to the beginning of the paragraph or
   section.

   * It's OK to just add a fragmentary note about a change.  For
   example: "XXX Describe the transmogrify() function added to the
   socket module."  The maintainer will research the change and
   write the necessary text.

   * You can comment out your additions if you like, but it's not
   necessary (especially when a final release is some months away).

   * Credit the author of a patch or bugfix.   Just the name is
   sufficient; the e-mail address isn't necessary.

   * It's helpful to add the bug/patch number in a parenthetical comment.

   XXX Describe the transmogrify() function added to the socket
   module.
   (Contributed by P.Y. Developer; :issue:`12345`.)

   This saves the maintainer some effort going through the SVN logs
   when researching a change.

This article explains the new features in Python 2.6, released on October 1
2008.  The release schedule is described in :pep:`361`.

The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it's not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
:mod:`future_builtins` module and a :option:`-3` switch to warn about
usages that will become unsupported in 3.0.

Some significant new packages have been added to the standard library,
such as the :mod:`multiprocessing` and :mod:`json` modules, but
there aren't many new features that aren't related to Python 3.0 in
some way.

Python 2.6 also sees a number of improvements and bugfixes throughout
the source.  A search through the change logs finds there were 259
patches applied and 612 bugs fixed between Python 2.5 and 2.6.  Both
figures are likely to be underestimates.

This article doesn't attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.6. If
you want to understand the rationale for the design and
implementation, refer to the PEP for a particular new feature.
Whenever possible, "What's New in Python" links to the bug/patch item
for each change.

.. Compare with previous release in 2 - 3 sentences here.
   add hyperlink when the documentation becomes available online.

.. ========================================================================
.. Large, PEP-level features and changes should be described here.
.. ========================================================================

Python 3.0
================

The development cycle for Python versions 2.6 and 3.0 was
synchronized, with the alpha and beta releases for both versions being
made on the same days.  The development of 3.0 has influenced many
features in 2.6.

Python 3.0 is a far-ranging redesign of Python that breaks
compatibility with the 2.x series.  This means that existing Python
code will need some conversion in order to run on
Python 3.0.  However, not all the changes in 3.0 necessarily break
compatibility.  In cases where new features won't cause existing code
to break, they've been backported to 2.6 and are described in this
document in the appropriate place.  Some of the 3.0-derived features
are:

* A :meth:`__complex__` method for converting objects to a complex number.
* Alternate syntax for catching exceptions: ``except TypeError as exc``.
* The addition of :func:`functools.reduce` as a synonym for the built-in
  :func:`reduce` function.

Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as :func:`bin` have simply been added to Python 2.6, but existing
builtins haven't been changed; instead, the :mod:`future_builtins`
module has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do ``from future_builtins import hex, map`` as
necessary.

A new command-line switch, :option:`-3`, enables warnings
about features that will be removed in Python 3.0.  You can run code
with this switch to see how much work will be necessary to port
code to 3.0.  The value of this switch is available
to Python code as the boolean variable :data:`sys.py3kwarning`,
and to C extension code as :c:data:`Py_Py3kWarningFlag`.

.. seealso::

   The 3xxx series of PEPs, which contains proposals for Python 3.0.
   :pep:`3000` describes the development process for Python 3.0.
   Start with :pep:`3100` that describes the general goals for Python
   3.0, and then explore the higher-numbered PEPS that propose
   specific features.


Changes to the Development Process
==================================================

While 2.6 was being developed, the Python development process
underwent two significant changes: we switched from SourceForge's
issue tracker to a customized Roundup installation, and the
documentation was converted from LaTeX to reStructuredText.


New Issue Tracker: Roundup
--------------------------------------------------

For a long time, the Python developers had been growing increasingly
annoyed by SourceForge's bug tracker.  SourceForge's hosted solution
doesn't permit much customization; for example, it wasn't possible to
customize the life cycle of issues.

The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: `Jira
<https://www.atlassian.com/software/jira/>`__,
`Launchpad <https://launchpad.net/>`__,
`Roundup <http://roundup.sourceforge.net/>`__, and
`Trac <https://trac.edgewall.org/>`__.
The committee eventually settled on Jira
and Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.

After posting a call for volunteers, a new Roundup installation was
set up at https://bugs.python.org.  One installation of Roundup can
host multiple trackers, and this server now also hosts issue trackers
for Jython and for the Python web site.  It will surely find
other uses in the future.  Where possible,
this edition of "What's New in Python" links to the bug/patch
item for each change.

Hosting of the Python bug tracker is kindly provided by
`Upfront Systems <http://www.upfrontsystems.co.za/>`__
of Stellenbosch, South Africa.  Martin von Loewis put a
lot of effort into importing existing bugs and patches from
SourceForge; his scripts for this import operation are at
http://svn.python.org/view/tracker/importer/ and may be useful to
other projects wishing to move from SourceForge to Roundup.

.. seealso::

  https://bugs.python.org
    The Python bug tracker.

  http://bugs.jython.org:
    The Jython bug tracker.

  http://roundup.sourceforge.net/
    Roundup downloads and documentation.

  http://svn.python.org/view/tracker/importer/
    Martin von Loewis's conversion scripts.

New Documentation Format: reStructuredText Using Sphinx
-----------------------------------------------------------

The Python documentation was written using LaTeX since the project
started around 1989.  In the 1980s and early 1990s, most documentation
was printed out for later study, not viewed online. LaTeX was widely
used because it provided attractive printed output while remaining
straightforward to write once the basic rules of the markup were
learned.

Today LaTeX is still used for writing publications destined for
printing, but the landscape for programming tools has shifted.  We no
longer print out reams of documentation; instead, we browse through it
online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
L. Drake Jr., the long-time Python documentation editor, spent a lot
of time maintaining the conversion process.  Occasionally people would
suggest converting the documentation into SGML and later XML, but
performing a good conversion is a major task and no one ever committed
the time required to finish the job.

During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
http://sphinx-doc.org/.

Sphinx concentrates on HTML output, producing attractively styled and
modern HTML; printed output is still supported through conversion to
LaTeX.  The input format is reStructuredText, a markup syntax
supporting custom extensions and directives that is commonly used in
the Python community.

Sphinx is a standalone package that can be used for writing, and
almost two dozen other projects
(`listed on the Sphinx web site <http://sphinx-doc.org/examples.html>`__)
have adopted Sphinx as their documentation tool.

.. seealso::

   `Documenting Python <https://docs.python.org/devguide/documenting.html>`__
       Describes how to write for Python's documentation.

   `Sphinx <http://sphinx-doc.org/>`__
     Documentation and code for the Sphinx toolchain.

   `Docutils <http://docutils.sourceforge.net>`__
     The underlying reStructuredText parser and toolset.


PEP 343: The 'with' statement
=============================

The previous version, Python 2.5, added the ':keyword:`with`'
statement as an optional feature, to be enabled by a ``from __future__
import with_statement`` directive.  In 2.6 the statement no longer needs to
be specially enabled; this means that :keyword:`with` is now always a
keyword.  The rest of this section is a copy of the corresponding
section from the "What's New in Python 2.5" document; if you're
familiar with the ':keyword:`with`' statement
from Python 2.5, you can skip this section.

The ':keyword:`with`' statement clarifies code that previously would use
``try...finally`` blocks to ensure that clean-up code is executed.  In this
section, I'll discuss the statement as it will commonly be used.  In the next
section, I'll examine the implementation details and show how to write objects
for use with this statement.

The ':keyword:`with`' statement is a control-flow structure whose basic
structure is::

   with expression [as variable]:
       with-block

The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has :meth:`__enter__` and :meth:`__exit__`
methods).

The object's :meth:`__enter__` is called before *with-block* is executed and
therefore can run set-up code. It also may return a value that is bound to the
name *variable*, if given.  (Note carefully that *variable* is *not* assigned
the result of *expression*.)

After execution of the *with-block* is finished, the object's :meth:`__exit__`
method is called, even if the block raised an exception, and can therefore run
clean-up code.

Some standard Python objects now support the context management protocol and can
be used with the ':keyword:`with`' statement. File objects are one example::

   with open('/etc/passwd', 'r') as f:
       for line in f:
           print line
           ... more processing code ...

After this statement has executed, the file object in *f* will have been
automatically closed, even if the :keyword:`for` loop raised an exception
part-way through the block.

.. note::

   In this case, *f* is the same object created by :func:`open`, because
   :meth:`file.__enter__` returns *self*.

The :mod:`threading` module's locks and condition variables  also support the
':keyword:`with`' statement::

   lock = threading.Lock()
   with lock:
       # Critical section of code
       ...

The lock is acquired before the block is executed and always released once  the
block is complete.

The :func:`localcontext` function in the :mod:`decimal` module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations::

   from decimal import Decimal, Context, localcontext

   # Displays with default precision of 28 digits
   v = Decimal('578')
   print v.sqrt()

   with localcontext(Context(prec=16)):
       # All code in this block uses a precision of 16 digits.
       # The original context is restored on exiting the block.
       print v.sqrt()


.. _new-26-context-managers:

Writing Context Managers
------------------------

Under the hood, the ':keyword:`with`' statement is fairly complicated. Most
people will only use ':keyword:`with`' in company with existing objects and
don't need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.

A high-level explanation of the context management protocol is:

* The expression is evaluated and should result in an object called a "context
  manager".  The context manager must have :meth:`__enter__` and :meth:`__exit__`
  methods.

* The context manager's :meth:`__enter__` method is called.  The value returned
  is assigned to *VAR*.  If no ``as VAR`` clause is present, the value is simply
  discarded.

* The code in *BLOCK* is executed.

* If *BLOCK* raises an exception, the context manager's :meth:`__exit__` method
  is called with three arguments, the exception details (``type, value, traceback``,
  the same values returned by :func:`sys.exc_info`, which can also be ``None``
  if no exception occurred).  The method's return value controls whether an exception
  is re-raised: any false value re-raises the exception, and ``True`` will result
  in suppressing it.  You'll only rarely want to suppress the exception, because
  if you do the author of the code containing the ':keyword:`with`' statement will
  never realize anything went wrong.

* If *BLOCK* didn't raise an exception,  the :meth:`__exit__` method is still
  called, but *type*, *value*, and *traceback* are all ``None``.

Let's think through an example.  I won't present detailed code but will only
sketch the methods necessary for a database that supports transactions.

(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)

Let's assume there's an object representing a database connection. Our goal will
be to let the user write code like this::

   db_connection = DatabaseConnection()
   with db_connection as cursor:
       cursor.execute('insert into ...')
       cursor.execute('delete from ...')
       # ... more operations ...

The transaction should be committed if the code in the block runs flawlessly or
rolled back if there's an exception. Here's the basic interface for
:class:`DatabaseConnection` that I'll assume::

   class DatabaseConnection:
       # Database interface
       def cursor(self):
           "Returns a cursor object and starts a new transaction"
       def commit(self):
           "Commits current transaction"
       def rollback(self):
           "Rolls back current transaction"

The :meth:`__enter__` method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add ``as cursor`` to
their ':keyword:`with`' statement to bind the cursor to a variable name. ::

   class DatabaseConnection:
       ...
       def __enter__(self):
           # Code to start a new transaction
           cursor = self.cursor()
           return cursor

The :meth:`__exit__` method is the most complicated because it's where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.

In the code below, execution will just fall off the end of the function,
returning the default value of ``None``.  ``None`` is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a :keyword:`return` statement at the marked location. ::

   class DatabaseConnection:
       ...
       def __exit__(self, type, value, tb):
           if tb is None:
               # No exception, so commit
               self.commit()
           else:
               # Exception occurred, so rollback.
               self.rollback()
               # return False


.. _module-contextlib:

The contextlib module
---------------------

The :mod:`contextlib` module provides some functions and a decorator that
are useful when writing objects for use with the ':keyword:`with`' statement.

The decorator is called :func:`contextmanager`, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the :keyword:`yield` will be executed as the
:meth:`__enter__` method, and the value yielded will be the method's return
value that will get bound to the variable in the ':keyword:`with`' statement's
:keyword:`as` clause, if any.  The code after the :keyword:`yield` will be
executed in the :meth:`__exit__` method.  Any exception raised in the block will
be raised by the :keyword:`yield` statement.

Using this decorator, our database example from the previous section
could be written as::

   from contextlib import contextmanager

   @contextmanager
   def db_transaction(connection):
       cursor = connection.cursor()
       try:
           yield cursor
       except:
           connection.rollback()
           raise
       else:
           connection.commit()

   db = DatabaseConnection()
   with db_transaction(db) as cursor:
       ...

The :mod:`contextlib` module also has a ``nested(mgr1, mgr2, ...)`` function
that combines a number of context managers so you don't need to write nested
':keyword:`with`' statements.  In this example, the single ':keyword:`with`'
statement both starts a database transaction and acquires a thread lock::

   lock = threading.Lock()
   with nested (db_transaction(db), lock) as (cursor, locked):
       ...

Finally, the :func:`closing` function returns its argument so that it can be
bound to a variable, and calls the argument's ``.close()`` method at the end
of the block. ::

   import urllib, sys
   from contextlib import closing

   with closing(urllib.urlopen('http://www.yahoo.com')) as f:
       for line in f:
           sys.stdout.write(line)


.. seealso::

   :pep:`343` - The "with" statement
      PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
      Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
      ':keyword:`with`' statement, which can be helpful in learning how the statement
      works.

   The documentation  for the :mod:`contextlib` module.

.. ======================================================================

.. _pep-0366:

PEP 366: Explicit Relative Imports From a Main Module
============================================================

Python's :option:`-m` switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn't work correctly.

The fix for Python 2.6 adds a :attr:`__package__` attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the
:attr:`__name__` attribute.

PEP 302-style importers can then set :attr:`__package__` as necessary.
The :mod:`runpy` module that implements the :option:`-m` switch now
does this, so relative imports will now work correctly in scripts
running from inside a package.

.. ======================================================================

.. _pep-0370:

PEP 370: Per-user ``site-packages`` Directory
=====================================================

When you run Python, the module search path ``sys.path`` usually
includes a directory whose path ends in ``"site-packages"``.  This
directory is intended to hold locally-installed packages available to
all users using a machine or a particular site installation.

Python 2.6 introduces a convention for user-specific site directories.
The directory varies depending on the platform:

* Unix and Mac OS X: :file:`~/.local/`
* Windows: :file:`%APPDATA%/Python`

Within this directory, there will be version-specific subdirectories,
such as :file:`lib/python2.6/site-packages` on Unix/Mac OS and
:file:`Python26/site-packages` on Windows.

If you don't like the default directory, it can be overridden by an
environment variable.  :envvar:`PYTHONUSERBASE` sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the :envvar:`APPDATA` environment variable.  You can also
modify the :file:`site.py` file for your Python installation.

The feature can be disabled entirely by running Python with the
:option:`-s` option or setting the :envvar:`PYTHONNOUSERSITE`
environment variable.

.. seealso::

   :pep:`370` - Per-user ``site-packages`` Directory
     PEP written and implemented by Christian Heimes.


.. ======================================================================

.. _pep-0371:

PEP 371: The ``multiprocessing`` Package
=====================================================

The new :mod:`multiprocessing` package lets Python programs create new
processes that will perform a computation and return a result to the
parent.  The parent and child processes can communicate using queues
and pipes, synchronize their operations using locks and semaphores,
and can share simple arrays of data.

The :mod:`multiprocessing` module started out as an exact emulation of
the :mod:`threading` module using processes instead of threads.  That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class
is the :class:`Process`, which is passed a callable object and
a collection of arguments.  The :meth:`start` method
sets the callable running in a subprocess, after which you can call
the :meth:`is_alive` method to check whether the subprocess is still running
and the :meth:`join` method to wait for the process to exit.

Here's a simple example where the subprocess will calculate a
factorial.  The function doing the calculation is written strangely so
that it takes significantly longer when the input argument is a
multiple of 4.

::

    import time
    from multiprocessing import Process, Queue


    def factorial(queue, N):
        "Compute a factorial."
        # If N is a multiple of 4, this function will take much longer.
        if (N % 4) == 0:
            time.sleep(.05 * N/4)

        # Calculate the result
        fact = 1L
        for i in range(1, N+1):
            fact = fact * i

        # Put the result on the queue
        queue.put(fact)

    if __name__ == '__main__':
        queue = Queue()

        N = 5

        p = Process(target=factorial, args=(queue, N))
        p.start()
        p.join()

        result = queue.get()
        print 'Factorial', N, '=', result

A :class:`~Queue.Queue` is used to communicate the result of the factorial.
The :class:`~Queue.Queue` object is stored in a global variable.
The child process will use the value of the variable when the child
was created; because it's a :class:`~Queue.Queue`, parent and child can use
the object to communicate.  (If the parent were to change the value of
the global variable, the child's value would be unaffected, and vice
versa.)

Two other classes, :class:`Pool` and :class:`Manager`, provide
higher-level interfaces.  :class:`Pool` will create a fixed number of
worker processes, and requests can then be distributed to the workers
by calling :meth:`apply` or :meth:`apply_async` to add a single request,
and :meth:`map` or :meth:`map_async` to add a number of
requests.  The following code uses a :class:`Pool` to spread requests
across 5 worker processes and retrieve a list of results::

    from multiprocessing import Pool

    def factorial(N, dictionary):
        "Compute a factorial."
        ...
    p = Pool(5)
    result = p.map(factorial, range(1, 1000, 10))
    for v in result:
        print v

This produces the following output::

    1
    39916800
    51090942171709440000
    8222838654177922817725562880000000
    33452526613163807108170062053440751665152000000000
    ...

The other high-level interface, the :class:`Manager` class, creates a
separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the :meth:`dict` method; the worker
processes then insert values into the dictionary.  (Locking is not
done for you automatically, which doesn't matter in this example.
:class:`Manager`'s methods also include :meth:`Lock`, :meth:`RLock`,
and :meth:`Semaphore` to create shared locks.)

::

    import time
    from multiprocessing import Pool, Manager

    def factorial(N, dictionary):
        "Compute a factorial."
        # Calculate the result
        fact = 1L
        for i in range(1, N+1):
            fact = fact * i

        # Store result in dictionary
        dictionary[N] = fact

    if __name__ == '__main__':
        p = Pool(5)
        mgr = Manager()
        d = mgr.dict()         # Create shared dictionary

        # Run tasks using the pool
        for N in range(1, 1000, 10):
            p.apply_async(factorial, (N, d))

        # Mark pool as closed -- no more tasks can be added.
        p.close()

        # Wait for tasks to exit
        p.join()

        # Output results
        for k, v in sorted(d.items()):
            print k, v

This will produce the output::

    1 1
    11 39916800
    21 51090942171709440000
    31 8222838654177922817725562880000000
    41 33452526613163807108170062053440751665152000000000
    51 15511187532873822802242430164693032110632597200169861120000...

.. seealso::

   The documentation for the :mod:`multiprocessing` module.

   :pep:`371` - Addition of the multiprocessing package
     PEP written by Jesse Noller and Richard Oudkerk;
     implemented by Richard Oudkerk and Jesse Noller.


.. ======================================================================

.. _pep-3101:

PEP 3101: Advanced String Formatting
=====================================================

In Python 3.0, the `%` operator is supplemented by a more powerful string
formatting method, :meth:`format`.  Support for the :meth:`str.format` method
has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a `.format()` method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (`{`, `}`) as special characters::

     >>> # Substitute positional argument 0 into the string.
     >>> "User ID: {0}".format("root")
     'User ID: root'
     >>> # Use the named keyword arguments
     >>> "User ID: {uid}   Last seen: {last_login}".format(
     ...    uid="root",
     ...    last_login = "5 Mar 2008 07:20")
     'User ID: root   Last seen: 5 Mar 2008 07:20'

Curly brackets can be escaped by doubling them::

     >>> "Empty dict: {{}}".format()
     "Empty dict: {}"

Field names can be integers indicating positional arguments, such as
``{0}``, ``{1}``, etc. or names of keyword arguments.  You can also
supply compound field names that read attributes or access dictionary keys::

    >>> import sys
    >>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
    Platform: darwin
    Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
    [GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

    >>> import mimetypes
    >>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
    'Content-type: video/mp4'

Note that when using dictionary-style notation such as ``[.mp4]``, you
don't need to put any quotation marks around the string; it will look
up the value using ``.mp4`` as the key.  Strings beginning with a
number will be converted to an integer.  You can't write more
complicated expressions inside a format string.

So far we've shown how to specify which field to substitute into the
resulting string.  The precise formatting used is also controllable by
adding a colon followed by a format specifier.  For example::

     >>> # Field 0: left justify, pad to 15 characters
     >>> # Field 1: right justify, pad to 6 characters
     >>> fmt = '{0:15} ${1:>6}'
     >>> fmt.format('Registration', 35)
     'Registration    $    35'
     >>> fmt.format('Tutorial', 50)
     'Tutorial        $    50'
     >>> fmt.format('Banquet', 125)
     'Banquet         $   125'

Format specifiers can reference other fields through nesting::

    >>> fmt = '{0:{1}}'
    >>> width = 15
    >>> fmt.format('Invoice #1234', width)
    'Invoice #1234  '
    >>> width = 35
    >>> fmt.format('Invoice #1234', width)
    'Invoice #1234                      '

The alignment of a field within the desired width can be specified:

================ ============================================
Character        Effect
================ ============================================
< (default)      Left-align
>                Right-align
^                Center
=                (For numeric types only) Pad after the sign.
================ ============================================

Format specifiers can also include a presentation type, which
controls how the value is formatted.  For example, floating-point numbers
can be formatted as a general number or in exponential notation::

    >>> '{0:g}'.format(3.75)
    '3.75'
    >>> '{0:e}'.format(3.75)
    '3.750000e+00'

A variety of presentation types are available.  Consult the 2.6
documentation for a :ref:`complete list <formatstrings>`; here's a sample:

===== ========================================================================
``b`` Binary. Outputs the number in base 2.
``c`` Character. Converts the integer to the corresponding Unicode character
      before printing.
``d`` Decimal Integer. Outputs the number in base 10.
``o`` Octal format. Outputs the number in base 8.
``x`` Hex format. Outputs the number in base 16, using lower-case letters for
      the digits above 9.
``e`` Exponent notation. Prints the number in scientific notation using the
      letter 'e' to indicate the exponent.
``g`` General format. This prints the number as a fixed-point number, unless
      the number is too large, in which case it switches to 'e' exponent
      notation.
``n`` Number. This is the same as 'g' (for floats) or 'd' (for integers),
      except that it uses the current locale setting to insert the appropriate
      number separator characters.
``%`` Percentage. Multiplies the number by 100 and displays in fixed ('f')
      format, followed by a percent sign.
===== ========================================================================

Classes and types can define a :meth:`__format__` method to control how they're
formatted.  It receives a single argument, the format specifier::

   def __format__(self, format_spec):
       if isinstance(format_spec, unicode):
           return unicode(str(self))
       else:
           return str(self)

There's also a :func:`format` builtin that will format a single
value.  It calls the type's :meth:`__format__` method with the
provided specifier::

    >>> format(75.6564, '.2f')
    '75.66'


.. seealso::

   :ref:`formatstrings`
      The reference documentation for format fields.

   :pep:`3101` - Advanced String Formatting
      PEP written by Talin. Implemented by Eric Smith.

.. ======================================================================

.. _pep-3105:

PEP 3105: ``print`` As a Function
=====================================================

The ``print`` statement becomes the :func:`print` function in Python 3.0.
Making :func:`print` a function makes it possible to replace the function
by doing ``def print(...)`` or importing a new function from somewhere else.

Python 2.6 has a ``__future__`` import that removes ``print`` as language
syntax, letting you use the functional form instead.  For example::

    >>> from __future__ import print_function
    >>> print('# of entries', len(dictionary), file=sys.stderr)

The signature of the new function is::

    def print(*args, sep=' ', end='\n', file=None)


The parameters are:

 * *args*: positional arguments whose values will be printed out.
 * *sep*: the separator, which will be printed between arguments.
 * *end*: the ending text, which will be printed after all of the
   arguments have been output.
 * *file*: the file object to which the output will be sent.

.. seealso::

   :pep:`3105` - Make print a function
      PEP written by Georg Brandl.

.. ======================================================================

.. _pep-3110:

PEP 3110: Exception-Handling Changes
=====================================================

One error that Python programmers occasionally make
is writing the following code::

    try:
        ...
    except TypeError, ValueError:  # Wrong!
        ...

The author is probably trying to catch both :exc:`TypeError` and
:exc:`ValueError` exceptions, but this code actually does something
different: it will catch :exc:`TypeError` and bind the resulting
exception object to the local name ``"ValueError"``.  The
:exc:`ValueError` exception will not be caught at all.  The correct
code specifies a tuple of exceptions::

    try:
        ...
    except (TypeError, ValueError):
        ...

This error happens because the use of the comma here is ambiguous:
does it indicate two different nodes in the parse tree, or a single
node that's a tuple?

Python 3.0 makes this unambiguous by replacing the comma with the word
"as".  To catch an exception and store the exception object in the
variable ``exc``, you must write::

    try:
        ...
    except TypeError as exc:
        ...

Python 3.0 will only support the use of "as", and therefore interprets
the first example as catching two different exceptions.  Python 2.6
supports both the comma and "as", so existing code will continue to
work.  We therefore suggest using "as" when writing new Python code
that will only be executed with 2.6.

.. seealso::

   :pep:`3110` - Catching Exceptions in Python 3000
      PEP written and implemented by Collin Winter.

.. ======================================================================

.. _pep-3112:

PEP 3112: Byte Literals
=====================================================

Python 3.0 adopts Unicode as the language's fundamental string type and
denotes 8-bit literals differently, either as ``b'string'``
or using a :class:`bytes` constructor.  For future compatibility,
Python 2.6 adds :class:`bytes` as a synonym for the :class:`str` type,
and it also supports the ``b''`` notation.


The 2.6 :class:`str` differs from 3.0's :class:`bytes` type in various
ways; most notably, the constructor is completely different.  In 3.0,
``bytes([65, 66, 67])`` is 3 elements long, containing the bytes
representing ``ABC``; in 2.6, ``bytes([65, 66, 67])`` returns the
12-byte string representing the :func:`str` of the list.

The primary use of :class:`bytes` in 2.6 will be to write tests of
object type such as ``isinstance(x, bytes)``.  This will help the 2to3
converter, which can't tell whether 2.x code intends strings to
contain either characters or 8-bit bytes; you can now
use either :class:`bytes` or :class:`str` to represent your intention
exactly, and the resulting code will also be correct in Python 3.0.

There's also a ``__future__`` import that causes all string literals
to become Unicode strings.  This means that ``\u`` escape sequences
can be used to include Unicode characters::


    from __future__ import unicode_literals

    s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
         '\u3081\u3000\u751f\u305f\u307e\u3054')

    print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit
string type, called :c:type:`PyStringObject` in Python 2.x,
to :c:type:`PyBytesObject`.  Python 2.6 uses ``#define``
to support using the names :c:func:`PyBytesObject`,
:c:func:`PyBytes_Check`, :c:func:`PyBytes_FromStringAndSize`,
and all the other functions and macros used with strings.

Instances of the :class:`bytes` type are immutable just
as strings are.  A new :class:`bytearray` type stores a mutable
sequence of bytes::

    >>> bytearray([65, 66, 67])
    bytearray(b'ABC')
    >>> b = bytearray(u'\u21ef\u3244', 'utf-8')
    >>> b
    bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
    >>> b[0] = '\xe3'
    >>> b
    bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
    >>> unicode(str(b), 'utf-8')
    u'\u31ef \u3244'

Byte arrays support most of the methods of string types, such as
:meth:`startswith`/:meth:`endswith`, :meth:`find`/:meth:`rfind`,
and some of the methods of lists, such as :meth:`append`,
:meth:`pop`,  and :meth:`reverse`.

::

    >>> b = bytearray('ABC')
    >>> b.append('d')
    >>> b.append(ord('e'))
    >>> b
    bytearray(b'ABCde')

There's also a corresponding C API, with
:c:func:`PyByteArray_FromObject`,
:c:func:`PyByteArray_FromStringAndSize`,
and various other functions.

.. seealso::

   :pep:`3112` - Bytes literals in Python 3000
      PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.

.. ======================================================================

.. _pep-3116:

PEP 3116: New I/O Library
=====================================================

Python's built-in file objects support a number of methods, but
file-like objects don't necessarily support all of them.  Objects that
imitate files usually support :meth:`read` and :meth:`write`, but they
may not support :meth:`readline`, for example.  Python 3.0 introduces
a layered I/O library in the :mod:`io` module that separates buffering
and text-handling features from the fundamental read and write
operations.

There are three levels of abstract base classes provided by
the :mod:`io` module:

* :class:`RawIOBase` defines raw I/O operations: :meth:`read`,
  :meth:`readinto`,
  :meth:`write`, :meth:`seek`, :meth:`tell`, :meth:`truncate`,
  and :meth:`close`.
  Most of the methods of this class will often map to a single system call.
  There are also :meth:`readable`, :meth:`writable`, and :meth:`seekable`
  methods for determining what operations a given object will allow.

  Python 3.0 has concrete implementations of this class for files and
  sockets, but Python 2.6 hasn't restructured its file and socket objects
  in this way.

  .. XXX should 2.6 register them in io.py?

* :class:`BufferedIOBase` is an abstract base class that
  buffers data in memory to reduce the number of
  system calls used, making I/O processing more efficient.
  It supports all of the methods of :class:`RawIOBase`,
  and adds a :attr:`raw` attribute holding the underlying raw object.

  There are five concrete classes implementing this ABC.
  :class:`BufferedWriter` and :class:`BufferedReader` are for objects
  that support write-only or read-only usage that have a :meth:`seek`
  method for random access.  :class:`BufferedRandom` objects support
  read and write access upon the same underlying stream, and
  :class:`BufferedRWPair` is for objects such as TTYs that have both
  read and write operations acting upon unconnected streams of data.
  The :class:`BytesIO` class supports reading, writing, and seeking
  over an in-memory buffer.

  .. index::
     single: universal newlines; What's new

* :class:`TextIOBase`: Provides functions for reading and writing
  strings (remember, strings will be Unicode in Python 3.0),
  and supporting :term:`universal newlines`.  :class:`TextIOBase` defines
  the :meth:`readline` method and supports iteration upon
  objects.

  There are two concrete implementations.  :class:`TextIOWrapper`
  wraps a buffered I/O object, supporting all of the methods for
  text I/O and adding a :attr:`buffer` attribute for access
  to the underlying object.  :class:`~StringIO.StringIO` simply buffers
  everything in memory without ever writing anything to disk.

  (In Python 2.6, :class:`io.StringIO` is implemented in
  pure Python, so it's pretty slow.   You should therefore stick with the
  existing :mod:`StringIO` module or :mod:`cStringIO` for now.  At some
  point Python 3.0's :mod:`io` module will be rewritten into C for speed,
  and perhaps the C implementation will be  backported to the 2.x releases.)

In Python 2.6, the underlying implementations haven't been
restructured to build on top of the :mod:`io` module's classes.  The
module is being provided to make it easier to write code that's
forward-compatible with 3.0, and to save developers the effort of writing
their own implementations of buffering and text I/O.

.. seealso::

   :pep:`3116` - New I/O
      PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
      Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
      Jeremy Hylton, Martin von Loewis, Tony Lownds, and others.

.. ======================================================================

.. _pep-3118:

PEP 3118: Revised Buffer Protocol
=====================================================

The buffer protocol is a C-level API that lets Python types
exchange pointers into their internal representations.  A
memory-mapped file can be viewed as a buffer of characters, for
example, and this lets another module such as :mod:`re`
treat memory-mapped files as a string of characters to be searched.

The primary users of the buffer protocol are numeric-processing
packages such as NumPy, which expose the internal representation
of arrays so that callers can write data directly into an array instead
of going through a slower API.  This PEP updates the buffer protocol in light of experience
from NumPy development, adding a number of new features
such as indicating the shape of an array or locking a memory region.

The most important new C API function is
``PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)``, which
takes an object and a set of flags, and fills in the
``Py_buffer`` structure with information
about the object's memory representation.  Objects
can use this operation to lock memory in place
while an external caller could be modifying the contents,
so there's a corresponding ``PyBuffer_Release(Py_buffer *view)`` to
indicate that the external caller is done.

.. XXX PyObject_GetBuffer not documented in c-api

The *flags* argument to :c:func:`PyObject_GetBuffer` specifies
constraints upon the memory returned.  Some examples are:

 * :const:`PyBUF_WRITABLE` indicates that the memory must be writable.

 * :const:`PyBUF_LOCK` requests a read-only or exclusive lock on the memory.

 * :const:`PyBUF_C_CONTIGUOUS` and :const:`PyBUF_F_CONTIGUOUS`
   requests a C-contiguous (last dimension varies the fastest) or
   Fortran-contiguous (first dimension varies the fastest) array layout.

Two new argument codes for :c:func:`PyArg_ParseTuple`,
``s*`` and ``z*``, return locked buffer objects for a parameter.

.. seealso::

   :pep:`3118` - Revising the buffer protocol
      PEP written by Travis Oliphant and Carl Banks; implemented by
      Travis Oliphant.


.. ======================================================================

.. _pep-3119:

PEP 3119: Abstract Base Classes
=====================================================

Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an :mod:`abc` module
containing a metaclass called :class:`ABCMeta`, special handling of
this metaclass by the :func:`isinstance` and :func:`issubclass`
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful.  Future versions of Python will probably
add more ABCs.

Let's say you have a particular class and wish to know whether it supports
dictionary-style access.  The phrase "dictionary-style" is vague, however.
It probably means that accessing items with ``obj[1]`` works.
Does it imply that setting items with ``obj[2] = value`` works?
Or that the object will have :meth:`keys`, :meth:`values`, and :meth:`items`
methods?  What about the iterative variants  such as :meth:`iterkeys`?  :meth:`copy`
and :meth:`update`?  Iterating over the object with :func:`iter`?

The Python 2.6 :mod:`collections` module includes a number of
different ABCs that represent these distinctions.  :class:`Iterable`
indicates that a class defines :meth:`__iter__`, and
:class:`Container` means the class defines a :meth:`__contains__`
method and therefore supports ``x in y`` expressions.  The basic
dictionary interface of getting items, setting items, and
:meth:`keys`, :meth:`values`, and :meth:`items`, is defined by the
:class:`MutableMapping` ABC.

You can derive your own classes from a particular ABC
to indicate they support that ABC's interface::

    import collections

    class Storage(collections.MutableMapping):
        ...


Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
calling the ABC's :meth:`register` method::

    import collections

    class Storage:
        ...

    collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer.
The :meth:`register`  method is useful when you've written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
For example, if you defined a :class:`PrintableType` ABC,
it's legal to do::

  # Register Python's types
  PrintableType.register(int)
  PrintableType.register(float)
  PrintableType.register(str)

Classes should obey the semantics specified by an ABC, but
Python can't check this; it's up to the class author to
understand the ABC's requirements and to implement the code accordingly.

To check whether an object supports a particular interface, you can
now write::

    def func(d):
        if not isinstance(d, collections.MutableMapping):
            raise ValueError("Mapping object expected, not %r" % d)

Don't feel that you must now begin writing lots of checks as in the
above example.  Python has a strong tradition of duck-typing, where
explicit type-checking is never done and code simply calls methods on
an object, trusting that those methods will be there and raising an
exception if they aren't.  Be judicious in checking for ABCs and only
do it where it's absolutely necessary.

You can write your own ABCs by using ``abc.ABCMeta`` as the
metaclass in a class definition::

    from abc import ABCMeta, abstractmethod

    class Drawable():
        __metaclass__ = ABCMeta

        @abstractmethod
        def draw(self, x, y, scale=1.0):
            pass

        def draw_doubled(self, x, y):
            self.draw(x, y, scale=2.0)


    class Square(Drawable):
        def draw(self, x, y, scale):
            ...


In the :class:`Drawable` ABC above, the :meth:`draw_doubled` method
renders the object at twice its size and can be implemented in terms
of other methods described in :class:`Drawable`.  Classes implementing
this ABC therefore don't need to provide their own implementation
of :meth:`draw_doubled`, though they can do so.  An implementation
of :meth:`draw` is necessary, though; the ABC can't provide
a useful generic implementation.

You can apply the ``@abstractmethod`` decorator to methods such as
:meth:`draw` that must be implemented; Python will then raise an
exception for classes that don't define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method::

    >>> class Circle(Drawable):
    ...     pass
    ...
    >>> c = Circle()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Can't instantiate abstract class Circle with abstract methods draw
    >>>

Abstract data attributes can be declared using the
``@abstractproperty`` decorator::

    from abc import abstractproperty
    ...

    @abstractproperty
    def readonly(self):
       return self._x

Subclasses must then define a :meth:`readonly` property.

.. seealso::

   :pep:`3119` - Introducing Abstract Base Classes
      PEP written by Guido van Rossum and Talin.
      Implemented by Guido van Rossum.
      Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.

.. ======================================================================

.. _pep-3127:

PEP 3127: Integer Literal Support and Syntax
=====================================================

Python 3.0 changes the syntax for octal (base-8) integer literals,
prefixing them with "0o" or "0O" instead of a leading zero, and adds
support for binary (base-2) integer literals, signalled by a "0b" or
"0B" prefix.

Python 2.6 doesn't drop support for a leading 0 signalling
an octal number, but it does add support for "0o" and "0b"::

    >>> 0o21, 2*8 + 1
    (17, 17)
    >>> 0b101111
    47

The :func:`oct` builtin still returns numbers
prefixed with a leading zero, and a new :func:`bin`
builtin returns the binary representation for a number::

    >>> oct(42)
    '052'
    >>> future_builtins.oct(42)
    '0o52'
    >>> bin(173)
    '0b10101101'

The :func:`int` and :func:`long` builtins will now accept the "0o"
and "0b" prefixes when base-8 or base-2 are requested, or when the
*base* argument is zero (signalling that the base used should be
determined from the string)::

    >>> int ('0o52', 0)
    42
    >>> int('1101', 2)
    13
    >>> int('0b1101', 2)
    13
    >>> int('0b1101', 0)
    13


.. seealso::

   :pep:`3127` - Integer Literal Support and Syntax
      PEP written by Patrick Maupin; backported to 2.6 by
      Eric Smith.

.. ======================================================================

.. _pep-3129:

PEP 3129: Class Decorators
=====================================================

Decorators have been extended from functions to classes.  It's now legal to
write::

  @foo
  @bar
  class A:
    pass

This is equivalent to::

  class A:
    pass

  A = foo(bar(A))

.. seealso::

   :pep:`3129` - Class Decorators
      PEP written by Collin Winter.

.. ======================================================================

.. _pep-3141:

PEP 3141: A Type Hierarchy for Numbers
=====================================================

Python 3.0 adds several abstract base classes for numeric types
inspired by Scheme's numeric tower.  These classes were backported to
2.6 as the :mod:`numbers` module.

The most general ABC is :class:`Number`.  It defines no operations at
all, and only exists to allow checking if an object is a number by
doing ``isinstance(obj, Number)``.

:class:`Complex` is a subclass of :class:`Number`.  Complex numbers
can undergo the basic operations of addition, subtraction,
multiplication, division, and exponentiation, and you can retrieve the
real and imaginary parts and obtain a number's conjugate.  Python's built-in
complex type is an implementation of :class:`Complex`.

:class:`Real` further derives from :class:`Complex`, and adds
operations that only work on real numbers: :func:`floor`, :func:`trunc`,
rounding, taking the remainder mod N, floor division,
and comparisons.

:class:`Rational` numbers derive from :class:`Real`, have
:attr:`numerator` and :attr:`denominator` properties, and can be
converted to floats.  Python 2.6 adds a simple rational-number class,
:class:`Fraction`, in the :mod:`fractions` module.  (It's called
:class:`Fraction` instead of :class:`Rational` to avoid
a name clash with :class:`numbers.Rational`.)

:class:`Integral` numbers derive from :class:`Rational`, and
can be shifted left and right with ``<<`` and ``>>``,
combined using bitwise operations such as ``&`` and ``|``,
and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins
:func:`round`, :func:`math.floor`, :func:`math.ceil`, and adds a new
one, :func:`math.trunc`, that's been backported to Python 2.6.
:func:`math.trunc` rounds toward zero, returning the closest
:class:`Integral` that's between the function's argument and zero.

.. seealso::

   :pep:`3141` - A Type Hierarchy for Numbers
      PEP written by Jeffrey Yasskin.

   `Scheme's numerical tower <https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower>`__, from the Guile manual.

   `Scheme's number datatypes <http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2>`__ from the R5RS Scheme specification.


The :mod:`fractions` Module
--------------------------------------------------

To fill out the hierarchy of numeric types, the :mod:`fractions`
module provides a rational-number class.  Rational numbers store their
values as a numerator and denominator forming a fraction, and can
exactly represent numbers such as ``2/3`` that floating-point numbers
can only approximate.

The :class:`Fraction` constructor takes two :class:`Integral` values
that will be the numerator and denominator of the resulting fraction. ::

    >>> from fractions import Fraction
    >>> a = Fraction(2, 3)
    >>> b = Fraction(2, 5)
    >>> float(a), float(b)
    (0.66666666666666663, 0.40000000000000002)
    >>> a+b
    Fraction(16, 15)
    >>> a/b
    Fraction(5, 3)

For converting floating-point numbers to rationals,
the float type now has an :meth:`as_integer_ratio()` method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value::

    >>> (2.5) .as_integer_ratio()
    (5, 2)
    >>> (3.1415) .as_integer_ratio()
    (7074029114692207L, 2251799813685248L)
    >>> (1./3) .as_integer_ratio()
    (6004799503160661L, 18014398509481984L)

Note that values that can only be approximated by floating-point
numbers, such as 1./3, are not simplified to the number being
approximated; the fraction attempts to match the floating-point value
**exactly**.

The :mod:`fractions` module is based upon an implementation by Sjoerd
Mullender that was in Python's :file:`Demo/classes/` directory for a
long time.  This implementation was significantly updated by Jeffrey
Yasskin.


Other Language Changes
======================

Some smaller changes made to the core Python language are:

* Directories and zip archives containing a :file:`__main__.py` file
  can now be executed directly by passing their name to the
  interpreter. The directory or zip archive is automatically inserted
  as the first entry in sys.path.  (Suggestion and initial patch by
  Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
  :issue:`1739468`.)

* The :func:`hasattr` function was catching and ignoring all errors,
  under the assumption that they meant a :meth:`__getattr__` method
  was failing somehow and the return value of :func:`hasattr` would
  therefore be ``False``.  This logic shouldn't be applied to
  :exc:`KeyboardInterrupt` and :exc:`SystemExit`, however; Python 2.6
  will no longer discard such exceptions when :func:`hasattr`
  encounters them.  (Fixed by Benjamin Peterson; :issue:`2196`.)

* When calling a function using the ``**`` syntax to provide keyword
  arguments, you are no longer required to use a Python dictionary;
  any mapping will now work::

    >>> def f(**kw):
    ...    print sorted(kw)
    ...
    >>> ud=UserDict.UserDict()
    >>> ud['a'] = 1
    >>> ud['b'] = 'string'
    >>> f(**ud)
    ['a', 'b']

  (Contributed by Alexander Belopolsky; :issue:`1686487`.)

  It's also become legal to provide keyword arguments after a ``*args`` argument
  to a function call. ::

    >>> def f(*args, **kw):
    ...     print args, kw
    ...
    >>> f(1,2,3, *(4,5,6), keyword=13)
    (1, 2, 3, 4, 5, 6) {'keyword': 13}

  Previously this would have been a syntax error.
  (Contributed by Amaury Forgeot d'Arc; :issue:`3473`.)

* A new builtin, ``next(iterator, [default])`` returns the next item
  from the specified iterator.  If the *default* argument is supplied,
  it will be returned if *iterator* has been exhausted; otherwise,
  the :exc:`StopIteration` exception will be raised.  (Backported
  in :issue:`2719`.)

* Tuples now have :meth:`index` and :meth:`count` methods matching the
  list type's :meth:`index` and :meth:`count` methods::

    >>> t = (0,1,2,3,4,0,1,2)
    >>> t.index(3)
    3
    >>> t.count(0)
    2

  (Contributed by Raymond Hettinger)

* The built-in types now have improved support for extended slicing syntax,
  accepting various combinations of ``(start, stop, step)``.
  Previously, the support was partial and certain corner cases wouldn't work.
  (Implemented by Thomas Wouters.)

  .. Revision 57619

* Properties now have three attributes, :attr:`getter`, :attr:`setter`
  and :attr:`deleter`, that are decorators providing useful shortcuts
  for adding a getter, setter or deleter function to an existing
  property. You would use them like this::

    class C(object):
        @property
        def x(self):
            return self._x

        @x.setter
        def x(self, value):
            self._x = value

        @x.deleter
        def x(self):
            del self._x

    class D(C):
        @C.x.getter
        def x(self):
            return self._x * 2

        @x.setter
        def x(self, value):
            self._x = value / 2

* Several methods of the built-in set types now accept multiple iterables:
  :meth:`intersection`,
  :meth:`intersection_update`,
  :meth:`union`, :meth:`update`,
  :meth:`difference` and :meth:`difference_update`.

  ::

    >>> s=set('1234567890')
    >>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
    set(['2'])
    >>> s.difference('246', '789')
    set(['1', '0', '3', '5'])

  (Contributed by Raymond Hettinger.)

* Many floating-point features were added.  The :func:`float` function
  will now turn the string ``nan`` into an
  IEEE 754 Not A Number value, and ``+inf`` and ``-inf`` into
  positive or negative infinity.  This works on any platform with
  IEEE 754 semantics.  (Contributed by Christian Heimes; :issue:`1635`.)

  Other functions in the :mod:`math` module, :func:`isinf` and
  :func:`isnan`, return true if their floating-point argument is
  infinite or Not A Number.  (:issue:`1640`)

  Conversion functions were added to convert floating-point numbers
  into hexadecimal strings (:issue:`3008`).  These functions
  convert floats to and from a string representation without
  introducing rounding errors from the conversion between decimal and
  binary.  Floats have a :meth:`hex` method that returns a string
  representation, and the ``float.fromhex()`` method converts a string
  back into a number::

      >>> a = 3.75
      >>> a.hex()
      '0x1.e000000000000p+1'
      >>> float.fromhex('0x1.e000000000000p+1')
      3.75
      >>> b=1./3
      >>> b.hex()
      '0x1.5555555555555p-2'

* A numerical nicety: when creating a complex number from two floats
  on systems that support signed zeros (-0 and +0), the
  :func:`complex` constructor will now preserve the sign
  of the zero.  (Fixed by Mark T. Dickinson; :issue:`1507`.)

* Classes that inherit a :meth:`__hash__` method from a parent class
  can set ``__hash__ = None`` to indicate that the class isn't
  hashable.  This will make ``hash(obj)`` raise a :exc:`TypeError`
  and the class will not be indicated as implementing the
  :class:`Hashable` ABC.

  You should do this when you've defined a :meth:`__cmp__` or
  :meth:`__eq__` method that compares objects by their value rather
  than by identity.  All objects have a default hash method that uses
  ``id(obj)`` as the hash value.  There's no tidy way to remove the
  :meth:`__hash__` method inherited from a parent class, so
  assigning ``None`` was implemented as an override.  At the
  C level, extensions can set ``tp_hash`` to
  :c:func:`PyObject_HashNotImplemented`.
  (Fixed by Nick Coghlan and Amaury Forgeot d'Arc; :issue:`2235`.)

* The :exc:`GeneratorExit` exception now subclasses
  :exc:`BaseException` instead of :exc:`Exception`.  This means
  that an exception handler that does ``except Exception:``
  will not inadvertently catch :exc:`GeneratorExit`.
  (Contributed by Chad Austin; :issue:`1537`.)

* Generator objects now have a :attr:`gi_code` attribute that refers to
  the original code object backing the generator.
  (Contributed by Collin Winter; :issue:`1473257`.)

* The :func:`compile` built-in function now accepts keyword arguments
  as well as positional parameters.  (Contributed by Thomas Wouters;
  :issue:`1444529`.)

* The :func:`complex` constructor now accepts strings containing
  parenthesized complex numbers, meaning that ``complex(repr(cplx))``
  will now round-trip values.  For example, ``complex('(3+4j)')``
  now returns the value (3+4j).  (:issue:`1491866`)

* The string :meth:`translate` method now accepts ``None`` as the
  translation table parameter, which is treated as the identity
  transformation.   This makes it easier to carry out operations
  that only delete characters.  (Contributed by Bengt Richter and
  implemented by Raymond Hettinger; :issue:`1193128`.)

* The built-in :func:`dir` function now checks for a :meth:`__dir__`
  method on the objects it receives.  This method must return a list
  of strings containing the names of valid attributes for the object,
  and lets the object control the value that :func:`dir` produces.
  Objects that have :meth:`__getattr__` or :meth:`__getattribute__`
  methods can use this to advertise pseudo-attributes they will honor.
  (:issue:`1591665`)

* Instance method objects have new attributes for the object and function
  comprising the method; the new synonym for :attr:`im_self` is
  :attr:`__self__`, and :attr:`im_func` is also available as :attr:`__func__`.
  The old names are still supported in Python 2.6, but are gone in 3.0.

* An obscure change: when you use the :func:`locals` function inside a
  :keyword:`class` statement, the resulting dictionary no longer returns free
  variables.  (Free variables, in this case, are variables referenced in the
  :keyword:`class` statement  that aren't attributes of the class.)

.. ======================================================================


Optimizations
-------------

* The :mod:`warnings` module has been rewritten in C.  This makes
  it possible to invoke warnings from the parser, and may also
  make the interpreter's startup faster.
  (Contributed by Neal Norwitz and Brett Cannon; :issue:`1631171`.)

* Type objects now have a cache of methods that can reduce
  the work required to find the correct method implementation
  for a particular class; once cached, the interpreter doesn't need to
  traverse base classes to figure out the right method to call.
  The cache is cleared if a base class or the class itself is modified,
  so the cache should remain correct even in the face of Python's dynamic
  nature.
  (Original optimization implemented by Armin Rigo, updated for
  Python 2.6 by Kevin Jacobs; :issue:`1700288`.)

  By default, this change is only applied to types that are included with
  the Python core.  Extension modules may not necessarily be compatible with
  this cache,
  so they must explicitly add :c:macro:`Py_TPFLAGS_HAVE_VERSION_TAG`
  to the module's ``tp_flags`` field to enable the method cache.
  (To be compatible with the method cache, the extension module's code
  must not directly access and modify the ``tp_dict`` member of
  any of the types it implements.  Most modules don't do this,
  but it's impossible for the Python interpreter to determine that.
  See :issue:`1878` for some discussion.)

* Function calls that use keyword arguments are significantly faster
  by doing a quick pointer comparison, usually saving the time of a
  full string comparison.  (Contributed by Raymond Hettinger, after an
  initial implementation by Antoine Pitrou; :issue:`1819`.)

* All of the functions in the :mod:`struct` module have been rewritten in
  C, thanks to work at the Need For Speed sprint.
  (Contributed by Raymond Hettinger.)

* Some of the standard built-in types now set a bit in their type
  objects.  This speeds up checking whether an object is a subclass of
  one of these types.  (Contributed by Neal Norwitz.)

* Unicode strings now use faster code for detecting
  whitespace and line breaks; this speeds up the :meth:`split` method
  by about 25% and :meth:`splitlines` by 35%.
  (Contributed by Antoine Pitrou.)  Memory usage is reduced
  by using pymalloc for the Unicode string's data.

* The ``with`` statement now stores the :meth:`__exit__` method on the stack,
  producing a small speedup.  (Implemented by Jeffrey Yasskin.)

* To reduce memory usage, the garbage collector will now clear internal
  free lists when garbage-collecting the highest generation of objects.
  This may return memory to the operating system sooner.

.. ======================================================================

.. _new-26-interpreter:

Interpreter Changes
-------------------------------

Two command-line options have been reserved for use by other Python
implementations.  The :option:`-J` switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM.  :option:`-X` has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython.  If either option is used with Python 2.6, the
interpreter will report that the option isn't currently used.

Python can now be prevented from writing :file:`.pyc` or :file:`.pyo`
files by supplying the :option:`-B` switch to the Python interpreter,
or by setting the :envvar:`PYTHONDONTWRITEBYTECODE` environment
variable before running the interpreter.  This setting is available to
Python programs as the ``sys.dont_write_bytecode`` variable, and
Python code can change the value to modify the interpreter's
behaviour.  (Contributed by Neal Norwitz and Georg Brandl.)

The encoding used for standard input, output, and standard error can
be specified by setting the :envvar:`PYTHONIOENCODING` environment
variable before running the interpreter.  The value should be a string
in the form ``<encoding>`` or ``<encoding>:<errorhandler>``.
The *encoding* part specifies the encoding's name, e.g. ``utf-8`` or
``latin-1``; the optional *errorhandler* part specifies
what to do with characters that can't be handled by the encoding,
and  should be one of "error", "ignore", or "replace".   (Contributed
by Martin von Loewis.)

.. ======================================================================

New and Improved Modules
========================

As in every release, Python's standard library received a number of
enhancements and bug fixes.  Here's a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
:file:`Misc/NEWS` file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.

* The :mod:`asyncore` and :mod:`asynchat` modules are
  being actively maintained again, and a number of patches and bugfixes
  were applied.  (Maintained by Josiah Carlson; see :issue:`1736190` for
  one patch.)

* The :mod:`bsddb` module also has a new maintainer, Jesús Cea Avion, and the package
  is now available as a standalone package.  The web page for the package is
  `www.jcea.es/programacion/pybsddb.htm
  <https://www.jcea.es/programacion/pybsddb.htm>`__.
  The plan is to remove the package from the standard library
  in Python 3.0, because its pace of releases is much more frequent than
  Python's.

  The :mod:`bsddb.dbshelve` module now uses the highest pickling protocol
  available, instead of restricting itself to protocol 1.
  (Contributed by W. Barnes.)

* The :mod:`cgi` module will now read variables from the query string
  of an HTTP POST request.  This makes it possible to use form actions
  with URLs that include query strings such as
  "/cgi-bin/add.py?category=1".  (Contributed by Alexandre Fiori and
  Nubis; :issue:`1817`.)

  The :func:`parse_qs` and :func:`parse_qsl` functions have been
  relocated from the :mod:`cgi` module to the :mod:`urlparse` module.
  The versions still available in the :mod:`cgi` module will
  trigger :exc:`PendingDeprecationWarning` messages in 2.6
  (:issue:`600362`).

* The :mod:`cmath` module underwent extensive revision,
  contributed by Mark Dickinson and Christian Heimes.
  Five new functions were added:

  * :func:`polar` converts a complex number to polar form, returning
    the modulus and argument of the complex number.

  * :func:`rect` does the opposite, turning a modulus, argument pair
    back into the corresponding complex number.

  * :func:`phase` returns the argument (also called the angle) of a complex
    number.

  * :func:`isnan` returns True if either
    the real or imaginary part of its argument is a NaN.

  * :func:`isinf` returns True if either the real or imaginary part of
    its argument is infinite.

  The revisions also improved the numerical soundness of the
  :mod:`cmath` module.  For all functions, the real and imaginary
  parts of the results are accurate to within a few units of least
  precision (ulps) whenever possible.  See :issue:`1381` for the
  details.  The branch cuts for :func:`asinh`, :func:`atanh`: and
  :func:`atan` have also been corrected.

  The tests for the module have been greatly expanded; nearly 2000 new
  test cases exercise the algebraic functions.

  On IEEE 754 platforms, the :mod:`cmath` module now handles IEEE 754
  special values and floating-point exceptions in a manner consistent
  with Annex 'G' of the C99 standard.

* A new data type in the :mod:`collections` module: :class:`namedtuple(typename,
  fieldnames)` is a factory function that creates subclasses of the standard tuple
  whose fields are accessible by name as well as index.  For example::

     >>> var_type = collections.namedtuple('variable',
     ...             'id name type size')
     >>> # Names are separated by spaces or commas.
     >>> # 'id, name, type, size' would also work.
     >>> var_type._fields
     ('id', 'name', 'type', 'size')

     >>> var = var_type(1, 'frequency', 'int', 4)
     >>> print var[0], var.id    # Equivalent
     1 1
     >>> print var[2], var.type  # Equivalent
     int int
     >>> var._asdict()
     {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
     >>> v2 = var._replace(name='amplitude')
     >>> v2
     variable(id=1, name='amplitude', type='int', size=4)

  Several places in the standard library that returned tuples have
  been modified to return :class:`namedtuple` instances.  For example,
  the :meth:`Decimal.as_tuple` method now returns a named tuple with
  :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.

  (Contributed by Raymond Hettinger.)

* Another change to the :mod:`collections` module is that the
  :class:`deque` type now supports an optional *maxlen* parameter;
  if supplied, the deque's size will be restricted to no more
  than *maxlen* items.  Adding more items to a full deque causes
  old items to be discarded.

  ::

    >>> from collections import deque
    >>> dq=deque(maxlen=3)
    >>> dq
    deque([], maxlen=3)
    >>> dq.append(1); dq.append(2); dq.append(3)
    >>> dq
    deque([1, 2, 3], maxlen=3)
    >>> dq.append(4)
    >>> dq
    deque([2, 3, 4], maxlen=3)

  (Contributed by Raymond Hettinger.)

* The :mod:`Cookie` module's :class:`Morsel` objects now support an
  :attr:`httponly` attribute.  In some browsers. cookies with this attribute
  set cannot be accessed or manipulated by JavaScript code.
  (Contributed by Arvin Schnell; :issue:`1638033`.)

* A new window method in the :mod:`curses` module,
  :meth:`chgat`, changes the display attributes for a certain number of
  characters on a single line.  (Contributed by Fabian Kreutz.)

  ::

     # Boldface text starting at y=0,x=21
     # and affecting the rest of the line.
     stdscr.chgat(0, 21, curses.A_BOLD)

  The :class:`Textbox` class in the :mod:`curses.textpad` module
  now supports editing in insert mode as well as overwrite mode.
  Insert mode is enabled by supplying a true value for the *insert_mode*
  parameter when creating the :class:`Textbox` instance.

* The :mod:`datetime` module's :meth:`strftime` methods now support a
  ``%f`` format code that expands to the number of microseconds in the
  object, zero-padded on
  the left to six places.  (Contributed by Skip Montanaro; :issue:`1158`.)

* The :mod:`decimal` module was updated to version 1.66 of
  `the General Decimal Specification <http://speleotrove.com/decimal/decarith.html>`__.  New features
  include some methods for some basic mathematical functions such as
  :meth:`exp` and :meth:`log10`::

    >>> Decimal(1).exp()
    Decimal("2.718281828459045235360287471")
    >>> Decimal("2.7182818").ln()
    Decimal("0.9999999895305022877376682436")
    >>> Decimal(1000).log10()
    Decimal("3")

  The :meth:`as_tuple` method of :class:`Decimal` objects now returns a
  named tuple with :attr:`sign`, :attr:`digits`, and :attr:`exponent` fields.

  (Implemented by Facundo Batista and Mark Dickinson.  Named tuple
  support added by Raymond Hettinger.)

* The :mod:`difflib` module's :class:`SequenceMatcher` class
  now returns named tuples representing matches,
  with :attr:`a`, :attr:`b`, and :attr:`size` attributes.
  (Contributed by Raymond Hettinger.)

* An optional ``timeout`` parameter, specifying a timeout measured in
  seconds, was added to the :class:`ftplib.FTP` class constructor as
  well as the :meth:`connect` method.  (Added by Facundo Batista.)
  Also, the :class:`FTP` class's :meth:`storbinary` and
  :meth:`storlines` now take an optional *callback* parameter that
  will be called with each block of data after the data has been sent.
  (Contributed by Phil Schwartz; :issue:`1221598`.)

* The :func:`reduce` built-in function is also available in the
  :mod:`functools` module.  In Python 3.0, the builtin has been
  dropped and :func:`reduce` is only available from :mod:`functools`;
  currently there are no plans to drop the builtin in the 2.x series.
  (Patched by Christian Heimes; :issue:`1739906`.)

* When possible, the :mod:`getpass` module will now use
  :file:`/dev/tty` to print a prompt message and read the password,
  falling back to standard error and standard input.  If the
  password may be echoed to the terminal, a warning is printed before
  the prompt is displayed.  (Contributed by Gregory P. Smith.)

* The :func:`glob.glob` function can now return Unicode filenames if
  a Unicode path was used and Unicode filenames are matched within the
  directory.  (:issue:`1001604`)

* A new function in the :mod:`heapq` module, ``merge(iter1, iter2, ...)``,
  takes any number of iterables returning data in sorted
  order, and returns a new generator that returns the contents of all
  the iterators, also in sorted order.  For example::

      >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
      [1, 2, 3, 5, 8, 9, 16]

  Another new function, ``heappushpop(heap, item)``,
  pushes *item* onto *heap*, then pops off and returns the smallest item.
  This is more efficient than making a call to :func:`heappush` and then
  :func:`heappop`.

  :mod:`heapq` is now implemented to only use less-than comparison,
  instead of the less-than-or-equal comparison it previously used.
  This makes :mod:`heapq`'s usage of a type match the
  :meth:`list.sort` method.
  (Contributed by Raymond Hettinger.)

* An optional ``timeout`` parameter, specifying a timeout measured in
  seconds, was added to the :class:`httplib.HTTPConnection` and
  :class:`HTTPSConnection` class constructors.  (Added by Facundo
  Batista.)

* Most of the :mod:`inspect` module's functions, such as
  :func:`getmoduleinfo` and :func:`getargs`, now return named tuples.
  In addition to behaving like tuples, the elements of the  return value
  can also be accessed as attributes.
  (Contributed by Raymond Hettinger.)

  Some new functions in the module include
  :func:`isgenerator`, :func:`isgeneratorfunction`,
  and :func:`isabstract`.

* The :mod:`itertools` module gained several new functions.

  ``izip_longest(iter1, iter2, ...[, fillvalue])`` makes tuples from
  each of the elements; if some of the iterables are shorter than
  others, the missing values are set to *fillvalue*.  For example::

     >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
     ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))

  ``product(iter1, iter2, ..., [repeat=N])`` returns the Cartesian product
  of the supplied iterables, a set of tuples containing
  every possible combination of the elements returned from each iterable. ::

     >>> list(itertools.product([1,2,3], [4,5,6]))
     [(1, 4), (1, 5), (1, 6),
      (2, 4), (2, 5), (2, 6),
      (3, 4), (3, 5), (3, 6)]

  The optional *repeat* keyword argument is used for taking the
  product of an iterable or a set of iterables with themselves,
  repeated *N* times.  With a single iterable argument, *N*-tuples
  are returned::

     >>> list(itertools.product([1,2], repeat=3))
     [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
      (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

  With two iterables, *2N*-tuples are returned. ::

     >>> list(itertools.product([1,2], [3,4], repeat=2))
     [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
      (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
      (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
      (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]

  ``combinations(iterable, r)`` returns sub-sequences of length *r* from
  the elements of *iterable*. ::

    >>> list(itertools.combinations('123', 2))
    [('1', '2'), ('1', '3'), ('2', '3')]
    >>> list(itertools.combinations('123', 3))
    [('1', '2', '3')]
    >>> list(itertools.combinations('1234', 3))
    [('1', '2', '3'), ('1', '2', '4'),
     ('1', '3', '4'), ('2', '3', '4')]

  ``permutations(iter[, r])`` returns all the permutations of length *r* of
  the iterable's elements.  If *r* is not specified, it will default to the
  number of elements produced by the iterable. ::

    >>> list(itertools.permutations([1,2,3,4], 2))
    [(1, 2), (1, 3), (1, 4),
     (2, 1), (2, 3), (2, 4),
     (3, 1), (3, 2), (3, 4),
     (4, 1), (4, 2), (4, 3)]

  ``itertools.chain(*iterables)`` is an existing function in
  :mod:`itertools` that gained a new constructor in Python 2.6.
  ``itertools.chain.from_iterable(iterable)`` takes a single
  iterable that should return other iterables.  :func:`chain` will
  then return all the elements of the first iterable, then
  all the elements of the second, and so on. ::

    >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
    [1, 2, 3, 4, 5, 6]

  (All contributed by Raymond Hettinger.)

* The :mod:`logging` module's :class:`FileHandler` class
  and its subclasses :class:`WatchedFileHandler`, :class:`RotatingFileHandler`,
  and :class:`TimedRotatingFileHandler` now
  have an optional *delay* parameter to their constructors.  If *delay*
  is true, opening of the log file is deferred until the first
  :meth:`emit` call is made.  (Contributed by Vinay Sajip.)

  :class:`TimedRotatingFileHandler` also has a *utc* constructor
  parameter.  If the argument is true, UTC time will be used
  in determining when midnight occurs and in generating filenames;
  otherwise local time will be used.

* Several new functions were added to the :mod:`math` module:

  * :func:`~math.isinf` and :func:`~math.isnan` determine whether a given float
    is a (positive or negative) infinity or a NaN (Not a Number), respectively.

  * :func:`~math.copysign` copies the sign bit of an IEEE 754 number,
    returning the absolute value of *x* combined with the sign bit of
    *y*.  For example, ``math.copysign(1, -0.0)`` returns -1.0.
    (Contributed by Christian Heimes.)

  * :func:`~math.factorial` computes the factorial of a number.
    (Contributed by Raymond Hettinger; :issue:`2138`.)

  * :func:`~math.fsum` adds up the stream of numbers from an iterable,
    and is careful to avoid loss of precision through using partial sums.
    (Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
    :issue:`2819`.)

  * :func:`~math.acosh`, :func:`~math.asinh`
    and :func:`~math.atanh` compute the inverse hyperbolic functions.

  * :func:`~math.log1p` returns the natural logarithm of *1+x*
    (base *e*).

  * :func:`trunc` rounds a number toward zero, returning the closest
    :class:`Integral` that's between the function's argument and zero.
    Added as part of the backport of
    `PEP 3141's type hierarchy for numbers <#pep-3141>`__.

* The :mod:`math` module has been improved to give more consistent
  behaviour across platforms, especially with respect to handling of
  floating-point exceptions and IEEE 754 special values.

  Whenever possible, the module follows the recommendations of the C99
  standard about 754's special values.  For example, ``sqrt(-1.)``
  should now give a :exc:`ValueError` across almost all platforms,
  while ``sqrt(float('NaN'))`` should return a NaN on all IEEE 754
  platforms.  Where Annex 'F' of the C99 standard recommends signaling
  'divide-by-zero' or 'invalid', Python will raise :exc:`ValueError`.
  Where Annex 'F' of the C99 standard recommends signaling 'overflow',
  Python will raise :exc:`OverflowError`.  (See :issue:`711019` and
  :issue:`1640`.)

  (Contributed by Christian Heimes and Mark Dickinson.)

* :class:`~mmap.mmap` objects now have a :meth:`rfind` method that searches for a
  substring beginning at the end of the string and searching
  backwards.  The :meth:`find` method also gained an *end* parameter
  giving an index at which to stop searching.
  (Contributed by John Lenton.)

* The :mod:`operator` module gained a
  :func:`methodcaller` function that takes a name and an optional
  set of arguments, returning a callable that will call
  the named function on any arguments passed to it.  For example::

    >>> # Equivalent to lambda s: s.replace('old', 'new')
    >>> replacer = operator.methodcaller('replace', 'old', 'new')
    >>> replacer('old wine in old bottles')
    'new wine in new bottles'

  (Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)

  The :func:`attrgetter` function now accepts dotted names and performs
  the corresponding attribute lookups::

    >>> inst_name = operator.attrgetter(
    ...        '__class__.__name__')
    >>> inst_name('')
    'str'
    >>> inst_name(help)
    '_Helper'

  (Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)

* The :mod:`os` module now wraps several new system calls.
  ``fchmod(fd, mode)`` and ``fchown(fd, uid, gid)`` change the mode
  and ownership of an opened file, and ``lchmod(path, mode)`` changes
  the mode of a symlink.  (Contributed by Georg Brandl and Christian
  Heimes.)

  :func:`chflags` and :func:`lchflags` are wrappers for the
  corresponding system calls (where they're available), changing the
  flags set on a file.  Constants for the flag values are defined in
  the :mod:`stat` module; some possible values include
  :const:`UF_IMMUTABLE` to signal the file may not be changed and
  :const:`UF_APPEND` to indicate that data can only be appended to the
  file.  (Contributed by M. Levinson.)

  ``os.closerange(low, high)`` efficiently closes all file descriptors
  from *low* to *high*, ignoring any errors and not including *high* itself.
  This function is now used by the :mod:`subprocess` module to make starting
  processes faster.  (Contributed by Georg Brandl; :issue:`1663329`.)

* The ``os.environ`` object's :meth:`clear` method will now unset the
  environment variables using :func:`os.unsetenv` in addition to clearing
  the object's keys.  (Contributed by Martin Horcicka; :issue:`1181`.)

* The :func:`os.walk` function now has a ``followlinks`` parameter. If
  set to True, it will follow symlinks pointing to directories and
  visit the directory's contents.  For backward compatibility, the
  parameter's default value is false.  Note that the function can fall
  into an infinite recursion if there's a symlink that points to a
  parent directory.  (:issue:`1273829`)

* In the :mod:`os.path` module, the :func:`splitext` function
  has been changed to not split on leading period characters.
  This produces better results when operating on Unix's dot-files.
  For example, ``os.path.splitext('.ipython')``
  now returns ``('.ipython', '')`` instead of ``('', '.ipython')``.
  (:issue:`1115886`)

  A new function, ``os.path.relpath(path, start='.')``, returns a relative path
  from the ``start`` path, if it's supplied, or from the current
  working directory to the destination ``path``.  (Contributed by
  Richard Barran; :issue:`1339796`.)

  On Windows, :func:`os.path.expandvars` will now expand environment variables
  given in the form "%var%", and "~user" will be expanded into the
  user's home directory path.  (Contributed by Josiah Carlson;
  :issue:`957650`.)

* The Python debugger provided by the :mod:`pdb` module
  gained a new command: "run" restarts the Python program being debugged
  and can optionally take new command-line arguments for the program.
  (Contributed by Rocky Bernstein; :issue:`1393667`.)

* The :func:`pdb.post_mortem` function, used to begin debugging a
  traceback, will now use the traceback returned by :func:`sys.exc_info`
  if no traceback is supplied.   (Contributed by Facundo Batista;
  :issue:`1106316`.)

* The :mod:`pickletools` module now has an :func:`optimize` function
  that takes a string containing a pickle and removes some unused
  opcodes, returning a shorter pickle that contains the same data structure.
  (Contributed by Raymond Hettinger.)

* A :func:`get_data` function was added to the :mod:`pkgutil`
  module that returns the contents of resource files included
  with an installed Python package.  For example::

    >>> import pkgutil
    >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
          +-- StopIteration
          +-- StandardError
     ...

  (Contributed by Paul Moore; :issue:`2439`.)

* The :mod:`pyexpat` module's :class:`Parser` objects now allow setting
  their :attr:`buffer_size` attribute to change the size of the buffer
  used to hold character data.
  (Contributed by Achim Gaedke; :issue:`1137`.)

* The :mod:`Queue` module now provides queue variants that retrieve entries
  in different orders.  The :class:`PriorityQueue` class stores
  queued items in a heap and retrieves them in priority order,
  and :class:`LifoQueue` retrieves the most recently added entries first,
  meaning that it behaves like a stack.
  (Contributed by Raymond Hettinger.)

* The :mod:`random` module's :class:`Random` objects can
  now be pickled on a 32-bit system and unpickled on a 64-bit
  system, and vice versa.  Unfortunately, this change also means
  that Python 2.6's :class:`Random` objects can't be unpickled correctly
  on earlier versions of Python.
  (Contributed by Shawn Ligocki; :issue:`1727780`.)

  The new ``triangular(low, high, mode)`` function returns random
  numbers following a triangular distribution.   The returned values
  are between *low* and *high*, not including *high* itself, and
  with *mode* as the most frequently occurring value
  in the distribution.  (Contributed by Wladmir van der Laan and
  Raymond Hettinger; :issue:`1681432`.)

* Long regular expression searches carried out by the  :mod:`re`
  module will check for signals being delivered, so
  time-consuming searches can now be interrupted.
  (Contributed by Josh Hoyt and Ralf Schmitt; :issue:`846388`.)

  The regular expression module is implemented by compiling bytecodes
  for a tiny regex-specific virtual machine.  Untrusted code
  could create malicious strings of bytecode directly and cause crashes,
  so Python 2.6 includes a verifier for the regex bytecode.
  (Contributed by Guido van Rossum from work for Google App Engine;
  :issue:`3487`.)

* The :mod:`rlcompleter` module's :meth:`Completer.complete()` method
  will now ignore exceptions triggered while evaluating a name.
  (Fixed by Lorenz Quack; :issue:`2250`.)

* The :mod:`sched` module's :class:`scheduler` instances now
  have a read-only :attr:`queue` attribute that returns the
  contents of the scheduler's queue, represented as a list of
  named tuples with the fields ``(time, priority, action, argument)``.
  (Contributed by Raymond Hettinger; :issue:`1861`.)

* The :mod:`select` module now has wrapper functions
  for the Linux :c:func:`epoll` and BSD :c:func:`kqueue` system calls.
  :meth:`modify` method was added to the existing :class:`poll`
  objects; ``pollobj.modify(fd, eventmask)`` takes a file descriptor
  or file object and an event mask, modifying the recorded event mask
  for that file.
  (Contributed by Christian Heimes; :issue:`1657`.)

* The :func:`shutil.copytree` function now has an optional *ignore* argument
  that takes a callable object.  This callable will receive each directory path
  and a list of the directory's contents, and returns a list of names that
  will be ignored, not copied.

  The :mod:`shutil` module also provides an :func:`ignore_patterns`
  function for use with this new parameter.  :func:`ignore_patterns`
  takes an arbitrary number of glob-style patterns and returns a
  callable that will ignore any files and directories that match any
  of these patterns.  The following example copies a directory tree,
  but skips both :file:`.svn` directories and Emacs backup files,
  which have names ending with '~'::

      shutil.copytree('Doc/library', '/tmp/library',
                      ignore=shutil.ignore_patterns('*~', '.svn'))

  (Contributed by Tarek Ziadé; :issue:`2663`.)

* Integrating signal handling with GUI handling event loops
  like those used by Tkinter or GTk+ has long been a problem; most
  software ends up polling, waking up every fraction of a second to check
  if any GUI events have occurred.
  The :mod:`signal` module can now make this more efficient.
  Calling ``signal.set_wakeup_fd(fd)`` sets a file descriptor
  to be used; when a signal is received, a byte is written to that
  file descriptor.  There's also a C-level function,
  :c:func:`PySignal_SetWakeupFd`, for setting the descriptor.

  Event loops will use this by opening a pipe to create two descriptors,
  one for reading and one for writing.  The writable descriptor
  will be passed to :func:`set_wakeup_fd`, and the readable descriptor
  will be added to the list of descriptors monitored by the event loop via
  :c:func:`select` or :c:func:`poll`.
  On receiving a signal, a byte will be written and the main event loop
  will be woken up, avoiding the need to poll.

  (Contributed by Adam Olsen; :issue:`1583`.)

  The :func:`siginterrupt` function is now available from Python code,
  and allows changing whether signals can interrupt system calls or not.
  (Contributed by Ralf Schmitt.)

  The :func:`setitimer` and :func:`getitimer` functions have also been
  added (where they're available).  :func:`setitimer`
  allows setting interval timers that will cause a signal to be
  delivered to the process after a specified time, measured in
  wall-clock time, consumed process time, or combined process+system
  time.  (Contributed by Guilherme Polo; :issue:`2240`.)

* The :mod:`smtplib` module now supports SMTP over SSL thanks to the
  addition of the :class:`SMTP_SSL` class. This class supports an
  interface identical to the existing :class:`SMTP` class.
  (Contributed by Monty Taylor.)  Both class constructors also have an
  optional ``timeout`` parameter that specifies a timeout for the
  initial connection attempt, measured in seconds.  (Contributed by
  Facundo Batista.)

  An implementation of the LMTP protocol (:rfc:`2033`) was also added
  to the module.  LMTP is used in place of SMTP when transferring
  e-mail between agents that don't manage a mail queue.  (LMTP
  implemented by Leif Hedstrom; :issue:`957003`.)

  :meth:`SMTP.starttls` now complies with :rfc:`3207` and forgets any
  knowledge obtained from the server not obtained from the TLS
  negotiation itself.  (Patch contributed by Bill Fenner;
  :issue:`829951`.)

* The :mod:`socket` module now supports TIPC (http://tipc.sourceforge.net/),
  a high-performance non-IP-based protocol designed for use in clustered
  environments.  TIPC addresses are 4- or 5-tuples.
  (Contributed by Alberto Bertogli; :issue:`1646`.)

  A new function, :func:`create_connection`, takes an address and
  connects to it using an optional timeout value, returning the
  connected socket object.  This function also looks up the address's
  type and connects to it using IPv4 or IPv6 as appropriate.  Changing
  your code to use :func:`create_connection` instead of
  ``socket(socket.AF_INET, ...)`` may be all that's required to make
  your code work with IPv6.

* The base classes in the :mod:`SocketServer` module now support
  calling a :meth:`handle_timeout` method after a span of inactivity
  specified by the server's :attr:`timeout` attribute.  (Contributed
  by Michael Pomraning.)  The :meth:`serve_forever` method
  now takes an optional poll interval measured in seconds,
  controlling how often the server will check for a shutdown request.
  (Contributed by Pedro Werneck and Jeffrey Yasskin;
  :issue:`742598`, :issue:`1193577`.)

* The :mod:`sqlite3` module, maintained by Gerhard Haering,
  has been updated from version 2.3.2 in Python 2.5 to
  version 2.4.1.

* The :mod:`struct` module now supports the C99 :c:type:`_Bool` type,
  using the format character ``'?'``.
  (Contributed by David Remahl.)

* The :class:`Popen` objects provided by the :mod:`subprocess` module
  now have :meth:`terminate`, :meth:`kill`, and :meth:`send_signal` methods.
  On Windows, :meth:`send_signal` only supports the :const:`SIGTERM`
  signal, and all these methods are aliases for the Win32 API function
  :c:func:`TerminateProcess`.
  (Contributed by Christian Heimes.)

* A new variable in the :mod:`sys` module, :attr:`float_info`, is an
  object containing information derived from the :file:`float.h` file
  about the platform's floating-point support.  Attributes of this
  object include :attr:`mant_dig` (number of digits in the mantissa),
  :attr:`epsilon` (smallest difference between 1.0 and the next
  largest value representable), and several others.  (Contributed by
  Christian Heimes; :issue:`1534`.)

  Another new variable, :attr:`dont_write_bytecode`, controls whether Python
  writes any :file:`.pyc` or :file:`.pyo` files on importing a module.
  If this variable is true, the compiled files are not written.  The
  variable is initially set on start-up by supplying the :option:`-B`
  switch to the Python interpreter, or by setting the
  :envvar:`PYTHONDONTWRITEBYTECODE` environment variable before
  running the interpreter.  Python code can subsequently
  change the value of this variable to control whether bytecode files
  are written or not.
  (Contributed by Neal Norwitz and Georg Brandl.)

  Information about the command-line arguments supplied to the Python
  interpreter is available by reading attributes of a named
  tuple available as ``sys.flags``.  For example, the :attr:`verbose`
  attribute is true if Python
  was executed in verbose mode, :attr:`debug` is true in debugging mode, etc.
  These attributes are all read-only.
  (Contributed by Christian Heimes.)

  A new function, :func:`getsizeof`, takes a Python object and returns
  the amount of memory used by the object, measured in bytes.  Built-in
  objects return correct results; third-party extensions may not,
  but can define a :meth:`__sizeof__` method to return the
  object's size.
  (Contributed by Robert Schuppenies; :issue:`2898`.)

  It's now possible to determine the current profiler and tracer functions
  by calling :func:`sys.getprofile` and :func:`sys.gettrace`.
  (Contributed by Georg Brandl; :issue:`1648`.)

* The :mod:`tarfile` module now supports POSIX.1-2001 (pax) tarfiles in
  addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
  already supported.  The default format is GNU tar; specify the
  ``format`` parameter to open a file using a different format::

    tar = tarfile.open("output.tar", "w",
                       format=tarfile.PAX_FORMAT)

  The new ``encoding`` and ``errors`` parameters specify an encoding and
  an error handling scheme for character conversions.  ``'strict'``,
  ``'ignore'``, and ``'replace'`` are the three standard ways Python can
  handle errors,;
  ``'utf-8'`` is a special value that replaces bad characters with
  their UTF-8 representation.  (Character conversions occur because the
  PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)

  The :meth:`TarFile.add` method now accepts an ``exclude`` argument that's
  a function that can be used to exclude certain filenames from
  an archive.
  The function must take a filename and return true if the file
  should be excluded or false if it should be archived.
  The function is applied to both the name initially passed to :meth:`add`
  and to the names of files in recursively-added directories.

  (All changes contributed by Lars Gustäbel).

* An optional ``timeout`` parameter was added to the
  :class:`telnetlib.Telnet` class constructor, specifying a timeout
  measured in seconds.  (Added by Facundo Batista.)

* The :class:`tempfile.NamedTemporaryFile` class usually deletes
  the temporary file it created when the file is closed.  This
  behaviour can now be changed by passing ``delete=False`` to the
  constructor.  (Contributed by Damien Miller; :issue:`1537850`.)

  A new class, :class:`SpooledTemporaryFile`, behaves like
  a temporary file but stores its data in memory until a maximum size is
  exceeded.  On reaching that limit, the contents will be written to
  an on-disk temporary file.  (Contributed by Dustin J. Mitchell.)

  The :class:`NamedTemporaryFile` and :class:`SpooledTemporaryFile` classes
  both work as context managers, so you can write
  ``with tempfile.NamedTemporaryFile() as tmp: ...``.
  (Contributed by Alexander Belopolsky; :issue:`2021`.)

* The :mod:`test.test_support` module gained a number
  of context managers useful for writing tests.
  :func:`EnvironmentVarGuard` is a
  context manager that temporarily changes environment variables and
  automatically restores them to their old values.

  Another context manager, :class:`TransientResource`, can surround calls
  to resources that may or may not be available; it will catch and
  ignore a specified list of exceptions.  For example,
  a network test may ignore certain failures when connecting to an
  external web site::

      with test_support.TransientResource(IOError,
                                      errno=errno.ETIMEDOUT):
          f = urllib.urlopen('https://sf.net')
          ...

  Finally, :func:`check_warnings` resets the :mod:`warning` module's
  warning filters and returns an object that will record all warning
  messages triggered (:issue:`3781`)::

      with test_support.check_warnings() as wrec:
          warnings.simplefilter("always")
          # ... code that triggers a warning ...
          assert str(wrec.message) == "function is outdated"
          assert len(wrec.warnings) == 1, "Multiple warnings raised"

  (Contributed by Brett Cannon.)

* The :mod:`textwrap` module can now preserve existing whitespace
  at the beginnings and ends of the newly-created lines
  by specifying ``drop_whitespace=False``
  as an argument::

    >>> S = """This  sentence  has a bunch   of
    ...   extra   whitespace."""
    >>> print textwrap.fill(S, width=15)
    This  sentence
    has a bunch
    of    extra
    whitespace.
    >>> print textwrap.fill(S, drop_whitespace=False, width=15)
    This  sentence
      has a bunch
       of    extra
       whitespace.
    >>>

  (Contributed by Dwayne Bailey; :issue:`1581073`.)

* The :mod:`threading` module API is being changed to use properties
  such as :attr:`daemon` instead of :meth:`setDaemon` and
  :meth:`isDaemon` methods, and some methods have been renamed to use
  underscores instead of camel-case; for example, the
  :meth:`activeCount` method is renamed to :meth:`active_count`.  Both
  the 2.6 and 3.0 versions of the module support the same properties
  and renamed methods, but don't remove the old methods.  No date has been set
  for the deprecation of the old APIs in Python 3.x; the old APIs won't
  be removed in any 2.x version.
  (Carried out by several people, most notably Benjamin Peterson.)

  The :mod:`threading` module's :class:`Thread` objects
  gained an :attr:`ident` property that returns the thread's
  identifier, a nonzero integer.  (Contributed by Gregory P. Smith;
  :issue:`2871`.)

* The :mod:`timeit` module now accepts callables as well as strings
  for the statement being timed and for the setup code.
  Two convenience functions were added for creating
  :class:`Timer` instances:
  ``repeat(stmt, setup, time, repeat, number)`` and
  ``timeit(stmt, setup, time, number)`` create an instance and call
  the corresponding method. (Contributed by Erik Demaine;
  :issue:`1533909`.)

* The :mod:`Tkinter` module now accepts lists and tuples for options,
  separating the elements by spaces before passing the resulting value to
  Tcl/Tk.
  (Contributed by Guilherme Polo; :issue:`2906`.)

* The :mod:`turtle` module for turtle graphics was greatly enhanced by
  Gregor Lingl.  New features in the module include:

  * Better animation of turtle movement and rotation.
  * Control over turtle movement using the new :meth:`delay`,
    :meth:`tracer`, and :meth:`speed` methods.
  * The ability to set new shapes for the turtle, and to
    define a new coordinate system.
  * Turtles now have an :meth:`undo()` method that can roll back actions.
  * Simple support for reacting to input events such as mouse and keyboard
    activity, making it possible to write simple games.
  * A :file:`turtle.cfg` file can be used to customize the starting appearance
    of the turtle's screen.
  * The module's docstrings can be replaced by new docstrings that have been
    translated into another language.

  (:issue:`1513695`)

* An optional ``timeout`` parameter was added to the
  :func:`urllib.urlopen` function and the
  :class:`urllib.ftpwrapper` class constructor, as well as the
  :func:`urllib2.urlopen` function.  The parameter specifies a timeout
  measured in seconds.   For example::

     >>> u = urllib2.urlopen("http://slow.example.com",
                             timeout=3)
     Traceback (most recent call last):
       ...
     urllib2.URLError: <urlopen error timed out>
     >>>

  (Added by Facundo Batista.)

* The Unicode database provided by the :mod:`unicodedata` module
  has been updated to version 5.1.0.  (Updated by
  Martin von Loewis; :issue:`3811`.)

* The :mod:`warnings` module's :func:`formatwarning` and :func:`showwarning`
  gained an optional *line* argument that can be used to supply the
  line of source code.  (Added as part of :issue:`1631171`, which re-implemented
  part of the :mod:`warnings` module in C code.)

  A new function, :func:`catch_warnings`, is a context manager
  intended for testing purposes that lets you temporarily modify the
  warning filters and then restore their original values (:issue:`3781`).

* The XML-RPC :class:`~SimpleXMLRPCServer.SimpleXMLRPCServer` and :class:`~DocXMLRPCServer.DocXMLRPCServer`
  classes can now be prevented from immediately opening and binding to
  their socket by passing ``False`` as the *bind_and_activate*
  constructor parameter.  This can be used to modify the instance's
  :attr:`allow_reuse_address` attribute before calling the
  :meth:`server_bind` and :meth:`server_activate` methods to
  open the socket and begin listening for connections.
  (Contributed by Peter Parente; :issue:`1599845`.)

  :class:`~SimpleXMLRPCServer.SimpleXMLRPCServer` also has a :attr:`_send_traceback_header`
  attribute; if true, the exception and formatted traceback are returned
  as HTTP headers "X-Exception" and "X-Traceback".  This feature is
  for debugging purposes only and should not be used on production servers
  because the tracebacks might reveal passwords or other sensitive
  information.  (Contributed by Alan McIntyre as part of his
  project for Google's Summer of Code 2007.)

* The :mod:`xmlrpclib` module no longer automatically converts
  :class:`datetime.date` and :class:`datetime.time` to the
  :class:`xmlrpclib.DateTime` type; the conversion semantics were
  not necessarily correct for all applications.  Code using
  :mod:`xmlrpclib` should convert :class:`date` and :class:`~datetime.time`
  instances. (:issue:`1330538`)  The code can also handle
  dates before 1900 (contributed by Ralf Schmitt; :issue:`2014`)
  and 64-bit integers represented by using ``<i8>`` in XML-RPC responses
  (contributed by Riku Lindblad; :issue:`2985`).

* The :mod:`zipfile` module's :class:`ZipFile` class now has
  :meth:`extract` and :meth:`extractall` methods that will unpack
  a single file or all the files in the archive to the current directory, or
  to a specified directory::

    z = zipfile.ZipFile('python-251.zip')

    # Unpack a single file, writing it relative
    # to the /tmp directory.
    z.extract('Python/sysmodule.c', '/tmp')

    # Unpack all the files in the archive.
    z.extractall()

  (Contributed by Alan McIntyre; :issue:`467924`.)

  The :meth:`open`, :meth:`read` and :meth:`extract` methods can now
  take either a filename or a :class:`ZipInfo` object.  This is useful when an
  archive accidentally contains a duplicated filename.
  (Contributed by Graham Horler; :issue:`1775025`.)

  Finally, :mod:`zipfile` now supports using Unicode filenames
  for archived files.  (Contributed by Alexey Borzenkov; :issue:`1734346`.)

.. ======================================================================
.. whole new modules get described in subsections here

The :mod:`ast` module
----------------------

The :mod:`ast` module provides an Abstract Syntax Tree
representation of Python code, and Armin Ronacher
contributed a set of helper functions that perform a variety of
common tasks.  These will be useful for HTML templating
packages, code analyzers, and similar tools that process
Python code.

The :func:`parse` function takes an expression and returns an AST.
The :func:`dump` function outputs a representation of a tree, suitable
for debugging::

    import ast

    t = ast.parse("""
    d = {}
    for i in 'abcdefghijklm':
        d[i + i] = ord(i) - ord('a') + 1
    print d
    """)
    print ast.dump(t)

This outputs a deeply nested tree::

    Module(body=[
      Assign(targets=[
        Name(id='d', ctx=Store())
       ], value=Dict(keys=[], values=[]))
      For(target=Name(id='i', ctx=Store()),
          iter=Str(s='abcdefghijklm'), body=[
        Assign(targets=[
          Subscript(value=
            Name(id='d', ctx=Load()),
              slice=
              Index(value=
                BinOp(left=Name(id='i', ctx=Load()), op=Add(),
                 right=Name(id='i', ctx=Load()))), ctx=Store())
         ], value=
         BinOp(left=
          BinOp(left=
           Call(func=
            Name(id='ord', ctx=Load()), args=[
              Name(id='i', ctx=Load())
             ], keywords=[], starargs=None, kwargs=None),
           op=Sub(), right=Call(func=
            Name(id='ord', ctx=Load()), args=[
              Str(s='a')
             ], keywords=[], starargs=None, kwargs=None)),
           op=Add(), right=Num(n=1)))
        ], orelse=[])
       Print(dest=None, values=[
         Name(id='d', ctx=Load())
       ], nl=True)
     ])

The :func:`literal_eval` method takes a string or an AST
representing a literal expression, parses and evaluates it, and
returns the resulting value.  A literal expression is a Python
expression containing only strings, numbers, dictionaries,
etc. but no statements or function calls.  If you need to
evaluate an expression but cannot accept the security risk of using an
:func:`eval` call, :func:`literal_eval` will handle it safely::

    >>> literal = '("a", "b", {2:4, 3:8, 1:2})'
    >>> print ast.literal_eval(literal)
    ('a', 'b', {1: 2, 2: 4, 3: 8})
    >>> print ast.literal_eval('"a" + "b"')
    Traceback (most recent call last):
      ...
    ValueError: malformed string

The module also includes :class:`NodeVisitor` and
:class:`NodeTransformer` classes for traversing and modifying an AST,
and functions for common transformations such as changing line
numbers.

.. ======================================================================

The :mod:`future_builtins` module
--------------------------------------

Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can't be introduced in the Python
2.x series because they would break compatibility.
The :mod:`future_builtins` module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.

The functions in this module currently include:

* ``ascii(obj)``: equivalent to :func:`repr`.  In Python 3.0,
  :func:`repr` will return a Unicode string, while :func:`ascii` will
  return a pure ASCII bytestring.

* ``filter(predicate, iterable)``,
  ``map(func, iterable1, ...)``: the 3.0 versions
  return iterators, unlike the 2.x builtins which return lists.

* ``hex(value)``, ``oct(value)``: instead of calling the
  :meth:`__hex__` or :meth:`__oct__` methods, these versions will
  call the :meth:`__index__` method and convert the result to hexadecimal
  or octal.  :func:`oct` will use the new ``0o`` notation for its
  result.

.. ======================================================================

The :mod:`json` module: JavaScript Object Notation
--------------------------------------------------------------------

The new :mod:`json` module supports the encoding and decoding of Python types in
JSON (Javascript Object Notation). JSON is a lightweight interchange format
often used in web applications. For more information about JSON, see
http://www.json.org.

:mod:`json` comes with support for decoding and encoding most built-in Python
types. The following example encodes and decodes a dictionary::

       >>> import json
       >>> data = {"spam": "foo", "parrot": 42}
       >>> in_json = json.dumps(data) # Encode the data
       >>> in_json
       '{"parrot": 42, "spam": "foo"}'
       >>> json.loads(in_json) # Decode into a Python object
       {"spam": "foo", "parrot": 42}

It's also possible to write your own decoders and encoders to support
more types. Pretty-printing of the JSON strings is also supported.

:mod:`json` (originally called simplejson) was written by Bob
Ippolito.


.. ======================================================================

The :mod:`plistlib` module: A Property-List Parser
--------------------------------------------------

The ``.plist`` format is commonly used on Mac OS X to
store basic data types (numbers, strings, lists,
and dictionaries) by serializing them into an XML-based format.
It resembles the XML-RPC serialization of data types.

Despite being primarily used on Mac OS X, the format
has nothing Mac-specific about it and the Python implementation works
on any platform that Python supports, so the :mod:`plistlib` module
has been promoted to the standard library.

Using the module is simple::

    import sys
    import plistlib
    import datetime

    # Create data structure
    data_struct = dict(lastAccessed=datetime.datetime.now(),
                       version=1,
                       categories=('Personal','Shared','Private'))

    # Create string containing XML.
    plist_str = plistlib.writePlistToString(data_struct)
    new_struct = plistlib.readPlistFromString(plist_str)
    print data_struct
    print new_struct

    # Write data structure to a file and read it back.
    plistlib.writePlist(data_struct, '/tmp/customizations.plist')
    new_struct = plistlib.readPlist('/tmp/customizations.plist')

    # read/writePlist accepts file-like objects as well as paths.
    plistlib.writePlist(data_struct, sys.stdout)

.. ======================================================================

ctypes Enhancements
--------------------------------------------------

Thomas Heller continued to maintain and enhance the
:mod:`ctypes` module.

:mod:`ctypes` now supports a :class:`c_bool` datatype
that represents the C99 ``bool`` type.  (Contributed by David Remahl;
:issue:`1649190`.)

The :mod:`ctypes` string, buffer and array types have improved
support for extended slicing syntax,
where various combinations of ``(start, stop, step)`` are supplied.
(Implemented by Thomas Wouters.)

.. Revision 57769

All :mod:`ctypes` data types now support
:meth:`from_buffer` and :meth:`from_buffer_copy`
methods that create a ctypes instance based on a
provided buffer object.  :meth:`from_buffer_copy` copies
the contents of the object,
while :meth:`from_buffer` will share the same memory area.

A new calling convention tells :mod:`ctypes` to clear the ``errno`` or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; :issue:`1798`.)

You can now retrieve the Unix ``errno`` variable after a function
call.  When creating a wrapped function, you can supply
``use_errno=True`` as a keyword parameter to the :func:`DLL` function
and then call the module-level methods :meth:`set_errno` and
:meth:`get_errno` to set and retrieve the error value.

The Win32 LastError variable is similarly supported by
the :func:`DLL`, :func:`OleDLL`, and :func:`WinDLL` functions.
You supply ``use_last_error=True`` as a keyword parameter
and then call the module-level methods :meth:`set_last_error`
and :meth:`get_last_error`.

The :func:`byref` function, used to retrieve a pointer to a ctypes
instance, now has an optional *offset* parameter that is a byte
count that will be added to the returned pointer.

.. ======================================================================

Improved SSL Support
--------------------------------------------------

Bill Janssen made extensive improvements to Python 2.6's support for
the Secure Sockets Layer by adding a new module, :mod:`ssl`, that's
built atop the `OpenSSL <https://www.openssl.org/>`__ library.
This new module provides more control over the protocol negotiated,
the X.509 certificates used, and has better support for writing SSL
servers (as opposed to clients) in Python.  The existing SSL support
in the :mod:`socket` module hasn't been removed and continues to work,
though it will be removed in Python 3.0.

To use the new module, you must first create a TCP connection in the
usual way and then pass it to the :func:`ssl.wrap_socket` function.
It's possible to specify whether a certificate is required, and to
obtain certificate info by calling the :meth:`getpeercert` method.

.. seealso::

   The documentation for the :mod:`ssl` module.

.. ======================================================================

Deprecations and Removals
=========================

* String exceptions have been removed.  Attempting to use them raises a
  :exc:`TypeError`.

* Changes to the :class:`Exception` interface
  as dictated by :pep:`352` continue to be made.  For 2.6,
  the :attr:`message` attribute is being deprecated in favor of the
  :attr:`args` attribute.

* (3.0-warning mode) Python 3.0 will feature a reorganized standard
  library that will drop many outdated modules and rename others.
  Python 2.6 running in 3.0-warning mode will warn about these modules
  when they are imported.

  The list of deprecated modules is:
  :mod:`audiodev`,
  :mod:`bgenlocations`,
  :mod:`buildtools`,
  :mod:`bundlebuilder`,
  :mod:`Canvas`,
  :mod:`compiler`,
  :mod:`dircache`,
  :mod:`dl`,
  :mod:`fpformat`,
  :mod:`gensuitemodule`,
  :mod:`ihooks`,
  :mod:`imageop`,
  :mod:`imgfile`,
  :mod:`linuxaudiodev`,
  :mod:`mhlib`,
  :mod:`mimetools`,
  :mod:`multifile`,
  :mod:`new`,
  :mod:`pure`,
  :mod:`statvfs`,
  :mod:`sunaudiodev`,
  :mod:`test.testall`, and
  :mod:`toaiff`.

* The :mod:`gopherlib` module has been removed.

* The :mod:`MimeWriter` module and :mod:`mimify` module
  have been deprecated; use the :mod:`email`
  package instead.

* The :mod:`md5` module has been deprecated; use the :mod:`hashlib` module
  instead.

* The :mod:`posixfile` module has been deprecated; :func:`fcntl.lockf`
  provides better locking.

* The :mod:`popen2` module has been deprecated; use the :mod:`subprocess`
  module.

* The :mod:`rgbimg` module has been removed.

* The :mod:`sets` module has been deprecated; it's better to
  use the built-in :class:`set` and :class:`frozenset` types.

* The :mod:`sha` module has been deprecated; use the :mod:`hashlib` module
  instead.


.. ======================================================================


Build and C API Changes
=======================

Changes to Python's build process and to the C API include:

* Python now must be compiled with C89 compilers (after 19
  years!).  This means that the Python source tree has dropped its
  own implementations of :c:func:`memmove` and :c:func:`strerror`, which
  are in the C89 standard library.

* Python 2.6 can be built with Microsoft Visual Studio 2008 (version
  9.0), and this is the new default compiler.  See the
  :file:`PCbuild` directory for the build files.  (Implemented by
  Christian Heimes.)

* On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
  The :program:`configure` script
  can take a :option:`!--with-universal-archs=[32-bit|64-bit|all]`
  switch, controlling whether the binaries are built for 32-bit
  architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
  (Contributed by Ronald Oussoren.)

* The BerkeleyDB module now has a C API object, available as
  ``bsddb.db.api``.   This object can be used by other C extensions
  that wish to use the :mod:`bsddb` module for their own purposes.
  (Contributed by Duncan Grisby.)

* The new buffer interface, previously described in
  `the PEP 3118 section <#pep-3118-revised-buffer-protocol>`__,
  adds :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release`,
  as well as a few other functions.

* Python's use of the C stdio library is now thread-safe, or at least
  as thread-safe as the underlying library is.  A long-standing potential
  bug occurred if one thread closed a file object while another thread
  was reading from or writing to the object.  In 2.6 file objects
  have a reference count, manipulated by the
  :c:func:`PyFile_IncUseCount` and :c:func:`PyFile_DecUseCount`
  functions.  File objects can't be closed unless the reference count
  is zero.  :c:func:`PyFile_IncUseCount` should be called while the GIL
  is still held, before carrying out an I/O operation using the
  ``FILE *`` pointer, and :c:func:`PyFile_DecUseCount` should be called
  immediately after the GIL is re-acquired.
  (Contributed by Antoine Pitrou and Gregory P. Smith.)

* Importing modules simultaneously in two different threads no longer
  deadlocks; it will now raise an :exc:`ImportError`.  A new API
  function, :c:func:`PyImport_ImportModuleNoBlock`, will look for a
  module in ``sys.modules`` first, then try to import it after
  acquiring an import lock.  If the import lock is held by another
  thread, an :exc:`ImportError` is raised.
  (Contributed by Christian Heimes.)

* Several functions return information about the platform's
  floating-point support.  :c:func:`PyFloat_GetMax` returns
  the maximum representable floating point value,
  and :c:func:`PyFloat_GetMin` returns the minimum
  positive value.  :c:func:`PyFloat_GetInfo` returns an object
  containing more information from the :file:`float.h` file, such as
  ``"mant_dig"`` (number of digits in the mantissa), ``"epsilon"``
  (smallest difference between 1.0 and the next largest value
  representable), and several others.
  (Contributed by Christian Heimes; :issue:`1534`.)

* C functions and methods that use
  :c:func:`PyComplex_AsCComplex` will now accept arguments that
  have a :meth:`__complex__` method.  In particular, the functions in the
  :mod:`cmath` module will now accept objects with this method.
  This is a backport of a Python 3.0 change.
  (Contributed by Mark Dickinson; :issue:`1675423`.)

* Python's C API now includes two functions for case-insensitive string
  comparisons, ``PyOS_stricmp(char*, char*)``
  and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.
  (Contributed by Christian Heimes; :issue:`1635`.)

* Many C extensions define their own little macro for adding
  integers and strings to the module's dictionary in the
  ``init*`` function.  Python 2.6 finally defines standard macros
  for adding values to a module, :c:macro:`PyModule_AddStringMacro`
  and :c:macro:`PyModule_AddIntMacro()`.  (Contributed by
  Christian Heimes.)

* Some macros were renamed in both 3.0 and 2.6 to make it clearer that
  they are macros,
  not functions.  :c:macro:`Py_Size()` became :c:macro:`Py_SIZE()`,
  :c:macro:`Py_Type()` became :c:macro:`Py_TYPE()`, and
  :c:macro:`Py_Refcnt()` became :c:macro:`Py_REFCNT()`.
  The mixed-case macros are still available
  in Python 2.6 for backward compatibility.
  (:issue:`1629`)

* Distutils now places C extensions it builds in a
  different directory when running on a debug version of Python.
  (Contributed by Collin Winter; :issue:`1530959`.)

* Several basic data types, such as integers and strings, maintain
  internal free lists of objects that can be re-used.  The data
  structures for these free lists now follow a naming convention: the
  variable is always named ``free_list``, the counter is always named
  ``numfree``, and a macro ``Py<typename>_MAXFREELIST`` is
  always defined.

* A new Makefile target, "make patchcheck", prepares the Python source tree
  for making a patch: it fixes trailing whitespace in all modified
  ``.py`` files, checks whether the documentation has been changed,
  and reports whether the :file:`Misc/ACKS` and :file:`Misc/NEWS` files
  have been updated.
  (Contributed by Brett Cannon.)

  Another new target, "make profile-opt", compiles a Python binary
  using GCC's profile-guided optimization.  It compiles Python with
  profiling enabled, runs the test suite to obtain a set of profiling
  results, and then compiles using these results for optimization.
  (Contributed by Gregory P. Smith.)

.. ======================================================================

Port-Specific Changes: Windows
-----------------------------------

* The support for Windows 95, 98, ME and NT4 has been dropped.
  Python 2.6 requires at least Windows 2000 SP4.

* The new default compiler on Windows is Visual Studio 2008 (version
  9.0). The build directories for Visual Studio 2003 (version 7.1) and
  2005 (version 8.0) were moved into the PC/ directory. The new
  :file:`PCbuild` directory supports cross compilation for X64, debug
  builds and Profile Guided Optimization (PGO). PGO builds are roughly
  10% faster than normal builds.  (Contributed by Christian Heimes
  with help from Amaury Forgeot d'Arc and Martin von Loewis.)

* The :mod:`msvcrt` module now supports
  both the normal and wide char variants of the console I/O
  API.  The :func:`getwch` function reads a keypress and returns a Unicode
  value, as does the :func:`getwche` function.  The :func:`putwch` function
  takes a Unicode character and writes it to the console.
  (Contributed by Christian Heimes.)

* :func:`os.path.expandvars` will now expand environment variables in
  the form "%var%", and "~user" will be expanded into the user's home
  directory path.  (Contributed by Josiah Carlson; :issue:`957650`.)

* The :mod:`socket` module's socket objects now have an
  :meth:`ioctl` method that provides a limited interface to the
  :c:func:`WSAIoctl` system interface.

* The :mod:`_winreg` module now has a function,
  :func:`ExpandEnvironmentStrings`,
  that expands environment variable references such as ``%NAME%``
  in an input string.  The handle objects provided by this
  module now support the context protocol, so they can be used
  in :keyword:`with` statements. (Contributed by Christian Heimes.)

  :mod:`_winreg` also has better support for x64 systems,
  exposing the :func:`DisableReflectionKey`, :func:`EnableReflectionKey`,
  and :func:`QueryReflectionKey` functions, which enable and disable
  registry reflection for 32-bit processes running on 64-bit systems.
  (:issue:`1753245`)

* The :mod:`msilib` module's :class:`Record` object
  gained :meth:`GetInteger` and :meth:`GetString` methods that
  return field values as an integer or a string.
  (Contributed by Floris Bruynooghe; :issue:`2125`.)

.. ======================================================================

Port-Specific Changes: Mac OS X
-----------------------------------

* When compiling a framework build of Python, you can now specify the
  framework name to be used by providing the
  :option:`!--with-framework-name=` option to the
  :program:`configure` script.

* The :mod:`macfs` module has been removed.  This in turn required the
  :func:`macostools.touched` function to be removed because it depended on the
  :mod:`macfs` module.  (:issue:`1490190`)

* Many other Mac OS modules have been deprecated and will be removed in
  Python 3.0:
  :mod:`_builtinSuites`,
  :mod:`aepack`,
  :mod:`aetools`,
  :mod:`aetypes`,
  :mod:`applesingle`,
  :mod:`appletrawmain`,
  :mod:`appletrunner`,
  :mod:`argvemulator`,
  :mod:`Audio_mac`,
  :mod:`autoGIL`,
  :mod:`Carbon`,
  :mod:`cfmfile`,
  :mod:`CodeWarrior`,
  :mod:`ColorPicker`,
  :mod:`EasyDialogs`,
  :mod:`Explorer`,
  :mod:`Finder`,
  :mod:`FrameWork`,
  :mod:`findertools`,
  :mod:`ic`,
  :mod:`icglue`,
  :mod:`icopen`,
  :mod:`macerrors`,
  :mod:`MacOS`,
  :mod:`macfs`,
  :mod:`macostools`,
  :mod:`macresource`,
  :mod:`MiniAEFrame`,
  :mod:`Nav`,
  :mod:`Netscape`,
  :mod:`OSATerminology`,
  :mod:`pimp`,
  :mod:`PixMapWrapper`,
  :mod:`StdSuites`,
  :mod:`SystemEvents`,
  :mod:`Terminal`, and
  :mod:`terminalcommand`.

.. ======================================================================

Port-Specific Changes: IRIX
-----------------------------------

A number of old IRIX-specific modules were deprecated and will
be removed in Python 3.0:
:mod:`al` and :mod:`AL`,
:mod:`cd`,
:mod:`cddb`,
:mod:`cdplayer`,
:mod:`CL` and :mod:`cl`,
:mod:`DEVICE`,
:mod:`ERRNO`,
:mod:`FILE`,
:mod:`FL` and :mod:`fl`,
:mod:`flp`,
:mod:`fm`,
:mod:`GET`,
:mod:`GLWS`,
:mod:`GL` and :mod:`gl`,
:mod:`IN`,
:mod:`IOCTL`,
:mod:`jpeg`,
:mod:`panelparser`,
:mod:`readcd`,
:mod:`SV` and :mod:`sv`,
:mod:`torgb`,
:mod:`videoreader`, and
:mod:`WAIT`.

.. ======================================================================


Porting to Python 2.6
=====================

This section lists previously described changes and other bugfixes
that may require changes to your code:

* Classes that aren't supposed to be hashable should
  set ``__hash__ = None`` in their definitions to indicate
  the fact.

* String exceptions have been removed.  Attempting to use them raises a
  :exc:`TypeError`.

* The :meth:`__init__` method of :class:`collections.deque`
  now clears any existing contents of the deque
  before adding elements from the iterable.  This change makes the
  behavior match ``list.__init__()``.

* :meth:`object.__init__` previously accepted arbitrary arguments and
  keyword arguments, ignoring them.  In Python 2.6, this is no longer
  allowed and will result in a :exc:`TypeError`.  This will affect
  :meth:`__init__` methods that end up calling the corresponding
  method on :class:`object` (perhaps through using :func:`super`).
  See :issue:`1683368` for discussion.

* The :class:`Decimal` constructor now accepts leading and trailing
  whitespace when passed a string.  Previously it would raise an
  :exc:`InvalidOperation` exception.  On the other hand, the
  :meth:`create_decimal` method of :class:`Context` objects now
  explicitly disallows extra whitespace, raising a
  :exc:`ConversionSyntax` exception.

* Due to an implementation accident, if you passed a file path to
  the built-in  :func:`__import__` function, it would actually import
  the specified file.  This was never intended to work, however, and
  the implementation now explicitly checks for this case and raises
  an :exc:`ImportError`.

* C API: the :c:func:`PyImport_Import` and :c:func:`PyImport_ImportModule`
  functions now default to absolute imports, not relative imports.
  This will affect C extensions that import other modules.

* C API: extension data types that shouldn't be hashable
  should define their ``tp_hash`` slot to
  :c:func:`PyObject_HashNotImplemented`.

* The :mod:`socket` module exception :exc:`socket.error` now inherits
  from :exc:`IOError`.  Previously it wasn't a subclass of
  :exc:`StandardError` but now it is, through :exc:`IOError`.
  (Implemented by Gregory P. Smith; :issue:`1706815`.)

* The :mod:`xmlrpclib` module no longer automatically converts
  :class:`datetime.date` and :class:`datetime.time` to the
  :class:`xmlrpclib.DateTime` type; the conversion semantics were
  not necessarily correct for all applications.  Code using
  :mod:`xmlrpclib` should convert :class:`date` and :class:`~datetime.time`
  instances. (:issue:`1330538`)

* (3.0-warning mode) The :class:`Exception` class now warns
  when accessed using slicing or index access; having
  :class:`Exception` behave like a tuple is being phased out.

* (3.0-warning mode) inequality comparisons between two dictionaries
  or two objects that don't implement comparison methods are reported
  as warnings.  ``dict1 == dict2`` still works, but ``dict1 < dict2``
  is being phased out.

  Comparisons between cells, which are an implementation detail of Python's
  scoping rules, also cause warnings because such comparisons are forbidden
  entirely in 3.0.

.. ======================================================================


.. _26acks:

Acknowledgements
================

The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,
Jim Jewett, Kent Johnson, Chris Lambacher,  Martin Michlmayr,
Antoine Pitrou, Brian Warner.

PK
%�\l>�����"html/_sources/whatsnew/2.7.rst.txtnu�[���****************************
  What's New in Python 2.7
****************************

:Author: A.M. Kuchling (amk at amk.ca)

..  hyperlink all the methods & functions.

.. T_STRING_INPLACE not described in main docs

.. $Id$
   Rules for maintenance:

   * Anyone can add text to this document.  Do not spend very much time
   on the wording of your changes, because your text will probably
   get rewritten to some degree.

   * The maintainer will go through Misc/NEWS periodically and add
   changes; it's therefore more important to add your changes to
   Misc/NEWS than to this file.

   * This is not a complete list of every single change; completeness
   is the purpose of Misc/NEWS.  Some changes I consider too small
   or esoteric to include.  If such a change is added to the text,
   I'll just remove it.  (This is another reason you shouldn't spend
   too much time on writing your addition.)

   * If you want to draw your new text to the attention of the
   maintainer, add 'XXX' to the beginning of the paragraph or
   section.

   * It's OK to just add a fragmentary note about a change.  For
   example: "XXX Describe the transmogrify() function added to the
   socket module."  The maintainer will research the change and
   write the necessary text.

   * You can comment out your additions if you like, but it's not
   necessary (especially when a final release is some months away).

   * Credit the author of a patch or bugfix.  Just the name is
   sufficient; the e-mail address isn't necessary.

   * It's helpful to add the bug/patch number in a parenthetical comment.

   XXX Describe the transmogrify() function added to the socket
   module.
   (Contributed by P.Y. Developer; :issue:`12345`.)

   This saves the maintainer some effort going through the SVN logs
   when researching a change.

This article explains the new features in Python 2.7.  Python 2.7 was released
on July 3, 2010.

Numeric handling has been improved in many ways, for both
floating-point numbers and for the :class:`~decimal.Decimal` class.
There are some useful additions to the standard library, such as a
greatly enhanced :mod:`unittest` module, the :mod:`argparse` module
for parsing command-line options, convenient :class:`~collections.OrderedDict`
and :class:`~collections.Counter` classes in the :mod:`collections` module,
and many other improvements.

Python 2.7 is planned to be the last of the 2.x releases, so we worked
on making it a good release for the long term.  To help with porting
to Python 3, several new features from the Python 3.x series have been
included in 2.7.

This article doesn't attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.7 at
https://docs.python.org. If you want to understand the rationale for
the design and implementation, refer to the PEP for a particular new
feature or the issue on https://bugs.python.org in which a change was
discussed.  Whenever possible, "What's New in Python" links to the
bug/patch item for each change.

.. _whatsnew27-python31:

The Future for Python 2.x
=========================

Python 2.7 is the last major release in the 2.x series, as the Python
maintainers have shifted the focus of their new feature development efforts
to the Python 3.x series. This means that while Python 2 continues to
receive bug fixes, and to be updated to build correctly on new hardware and
versions of supported operated systems, there will be no new full feature
releases for the language or standard library.

However, while there is a large common subset between Python 2.7 and Python
3, and many of the changes involved in migrating to that common subset, or
directly to Python 3, can be safely automated, some other changes (notably
those associated with Unicode handling) may require careful consideration,
and preferably robust automated regression test suites, to migrate
effectively.

This means that Python 2.7 will remain in place for a long time, providing a
stable and supported base platform for production systems that have not yet
been ported to Python 3. The full expected lifecycle of the Python 2.7
series is detailed in :pep:`373`.

Some key consequences of the long-term significance of 2.7 are:

* As noted above, the 2.7 release has a much longer period of maintenance
  when compared to earlier 2.x versions. Python 2.7 is currently expected to
  remain supported by the core development team (receiving security updates
  and other bug fixes) until at least 2020 (10 years after its initial
  release, compared to the more typical support period of 18--24 months).

* As the Python 2.7 standard library ages, making effective use of the
  Python Package Index (either directly or via a redistributor) becomes
  more important for Python 2 users. In addition to a wide variety of third
  party packages for various tasks, the available packages include backports
  of new modules and features from the Python 3 standard library that are
  compatible with Python 2, as well as various tools and libraries that can
  make it easier to migrate to Python 3. The `Python Packaging User Guide
  <https://packaging.python.org>`__ provides guidance on downloading and
  installing software from the Python Package Index.

* While the preferred approach to enhancing Python 2 is now the publication
  of new packages on the Python Package Index, this approach doesn't
  necessarily work in all cases, especially those related to network
  security. In exceptional cases that cannot be handled adequately by
  publishing new or updated packages on PyPI, the Python Enhancement
  Proposal process may be used to make the case for adding new features
  directly to the Python 2 standard library. Any such additions, and the
  maintenance releases where they were added, will be noted in the
  :ref:`py27-maintenance-enhancements` section below.

For projects wishing to migrate from Python 2 to Python 3, or for library
and framework developers wishing to support users on both Python 2 and
Python 3, there are a variety of tools and guides available to help decide
on a suitable approach and manage some of the technical details involved.
The recommended starting point is the :ref:`pyporting-howto` HOWTO guide.


Changes to the Handling of Deprecation Warnings
===============================================

For Python 2.7, a policy decision was made to silence warnings only of
interest to developers by default.  :exc:`DeprecationWarning` and its
descendants are now ignored unless otherwise requested, preventing
users from seeing warnings triggered by an application.  This change
was also made in the branch that became Python 3.2. (Discussed
on stdlib-sig and carried out in :issue:`7319`.)

In previous releases, :exc:`DeprecationWarning` messages were
enabled by default, providing Python developers with a clear
indication of where their code may break in a future major version
of Python.

However, there are increasingly many users of Python-based
applications who are not directly involved in the development of
those applications.  :exc:`DeprecationWarning` messages are
irrelevant to such users, making them worry about an application
that's actually working correctly and burdening application developers
with responding to these concerns.

You can re-enable display of :exc:`DeprecationWarning` messages by
running Python with the :option:`-Wdefault <-W>` (short form:
:option:`-Wd <-W>`) switch, or by setting the :envvar:`PYTHONWARNINGS`
environment variable to ``"default"`` (or ``"d"``) before running
Python.  Python code can also re-enable them
by calling ``warnings.simplefilter('default')``.

The ``unittest`` module also automatically reenables deprecation warnings
when running tests.


Python 3.1 Features
=======================

Much as Python 2.6 incorporated features from Python 3.0,
version 2.7 incorporates some of the new features
in Python 3.1.  The 2.x series continues to provide tools
for migrating to the 3.x series.

A partial list of 3.1 features that were backported to 2.7:

* The syntax for set literals (``{1,2,3}`` is a mutable set).
* Dictionary and set comprehensions (``{i: i*2 for i in range(3)}``).
* Multiple context managers in a single :keyword:`with` statement.
* A new version of the :mod:`io` library, rewritten in C for performance.
* The ordered-dictionary type described in :ref:`pep-0372`.
* The new ``","`` format specifier described in :ref:`pep-0378`.
* The :class:`memoryview` object.
* A small subset of the :mod:`importlib` module,
  `described below <#importlib-section>`__.
* The :func:`repr` of a float ``x`` is shorter in many cases: it's now
  based on the shortest decimal string that's guaranteed to round back
  to ``x``.  As in previous versions of Python, it's guaranteed that
  ``float(repr(x))`` recovers ``x``.
* Float-to-string and string-to-float conversions are correctly rounded.
  The :func:`round` function is also now correctly rounded.
* The :c:type:`PyCapsule` type, used to provide a C API for extension modules.
* The :c:func:`PyLong_AsLongAndOverflow` C API function.

Other new Python3-mode warnings include:

* :func:`operator.isCallable` and :func:`operator.sequenceIncludes`,
  which are not supported in 3.x, now trigger warnings.
* The :option:`-3` switch now automatically
  enables the :option:`-Qwarn <-Q>` switch that causes warnings
  about using classic division with integers and long integers.



.. ========================================================================
.. Large, PEP-level features and changes should be described here.
.. ========================================================================

.. _pep-0372:

PEP 372: Adding an Ordered Dictionary to collections
====================================================

Regular Python dictionaries iterate over key/value pairs in arbitrary order.
Over the years, a number of authors have written alternative implementations
that remember the order that the keys were originally inserted.  Based on
the experiences from those implementations, 2.7 introduces a new
:class:`~collections.OrderedDict` class in the :mod:`collections` module.

The :class:`~collections.OrderedDict` API provides the same interface as regular
dictionaries but iterates over keys and values in a guaranteed order
depending on when a key was first inserted::

    >>> from collections import OrderedDict
    >>> d = OrderedDict([('first', 1),
    ...                  ('second', 2),
    ...                  ('third', 3)])
    >>> d.items()
    [('first', 1), ('second', 2), ('third', 3)]

If a new entry overwrites an existing entry, the original insertion
position is left unchanged::

    >>> d['second'] = 4
    >>> d.items()
    [('first', 1), ('second', 4), ('third', 3)]

Deleting an entry and reinserting it will move it to the end::

    >>> del d['second']
    >>> d['second'] = 5
    >>> d.items()
    [('first', 1), ('third', 3), ('second', 5)]

The :meth:`~collections.OrderedDict.popitem` method has an optional *last*
argument that defaults to ``True``.  If *last* is true, the most recently
added key is returned and removed; if it's false, the
oldest key is selected::

    >>> od = OrderedDict([(x,0) for x in range(20)])
    >>> od.popitem()
    (19, 0)
    >>> od.popitem()
    (18, 0)
    >>> od.popitem(last=False)
    (0, 0)
    >>> od.popitem(last=False)
    (1, 0)

Comparing two ordered dictionaries checks both the keys and values,
and requires that the insertion order was the same::

    >>> od1 = OrderedDict([('first', 1),
    ...                    ('second', 2),
    ...                    ('third', 3)])
    >>> od2 = OrderedDict([('third', 3),
    ...                    ('first', 1),
    ...                    ('second', 2)])
    >>> od1 == od2
    False
    >>> # Move 'third' key to the end
    >>> del od2['third']; od2['third'] = 3
    >>> od1 == od2
    True

Comparing an :class:`~collections.OrderedDict` with a regular dictionary
ignores the insertion order and just compares the keys and values.

How does the :class:`~collections.OrderedDict` work?  It maintains a
doubly-linked list of keys, appending new keys to the list as they're inserted.
A secondary dictionary maps keys to their corresponding list node, so
deletion doesn't have to traverse the entire linked list and therefore
remains O(1).

The standard library now supports use of ordered dictionaries in several
modules.

* The :mod:`ConfigParser` module uses them by default, meaning that
  configuration files can now be read, modified, and then written back
  in their original order.

* The :meth:`~collections.somenamedtuple._asdict()` method for
  :func:`collections.namedtuple` now returns an ordered dictionary with the
  values appearing in the same order as the underlying tuple indices.

* The :mod:`json` module's :class:`~json.JSONDecoder` class
  constructor was extended with an *object_pairs_hook* parameter to
  allow :class:`OrderedDict` instances to be built by the decoder.
  Support was also added for third-party tools like
  `PyYAML <http://pyyaml.org/>`_.

.. seealso::

   :pep:`372` - Adding an ordered dictionary to collections
     PEP written by Armin Ronacher and Raymond Hettinger;
     implemented by Raymond Hettinger.

.. _pep-0378:

PEP 378: Format Specifier for Thousands Separator
=================================================

To make program output more readable, it can be useful to add
separators to large numbers, rendering them as
18,446,744,073,709,551,616 instead of 18446744073709551616.

The fully general solution for doing this is the :mod:`locale` module,
which can use different separators ("," in North America, "." in
Europe) and different grouping sizes, but :mod:`locale` is complicated
to use and unsuitable for multi-threaded applications where different
threads are producing output for different locales.

Therefore, a simple comma-grouping mechanism has been added to the
mini-language used by the :meth:`str.format` method.  When
formatting a floating-point number, simply include a comma between the
width and the precision::

   >>> '{:20,.2f}'.format(18446744073709551616.0)
   '18,446,744,073,709,551,616.00'

When formatting an integer, include the comma after the width:

   >>> '{:20,d}'.format(18446744073709551616)
   '18,446,744,073,709,551,616'

This mechanism is not adaptable at all; commas are always used as the
separator and the grouping is always into three-digit groups.  The
comma-formatting mechanism isn't as general as the :mod:`locale`
module, but it's easier to use.

.. seealso::

   :pep:`378` - Format Specifier for Thousands Separator
     PEP written by Raymond Hettinger; implemented by Eric Smith.

PEP 389: The argparse Module for Parsing Command Lines
======================================================

The :mod:`argparse` module for parsing command-line arguments was
added as a more powerful replacement for the
:mod:`optparse` module.

This means Python now supports three different modules for parsing
command-line arguments: :mod:`getopt`, :mod:`optparse`, and
:mod:`argparse`.  The :mod:`getopt` module closely resembles the C
library's :c:func:`getopt` function, so it remains useful if you're writing a
Python prototype that will eventually be rewritten in C.
:mod:`optparse` becomes redundant, but there are no plans to remove it
because there are many scripts still using it, and there's no
automated way to update these scripts.  (Making the :mod:`argparse`
API consistent with :mod:`optparse`'s interface was discussed but
rejected as too messy and difficult.)

In short, if you're writing a new script and don't need to worry
about compatibility with earlier versions of Python, use
:mod:`argparse` instead of :mod:`optparse`.

Here's an example::

    import argparse

    parser = argparse.ArgumentParser(description='Command-line example.')

    # Add optional switches
    parser.add_argument('-v', action='store_true', dest='is_verbose',
                        help='produce verbose output')
    parser.add_argument('-o', action='store', dest='output',
                        metavar='FILE',
                        help='direct output to FILE instead of stdout')
    parser.add_argument('-C', action='store', type=int, dest='context',
                        metavar='NUM', default=0,
                        help='display NUM lines of added context')

    # Allow any number of additional arguments.
    parser.add_argument(nargs='*', action='store', dest='inputs',
                        help='input filenames (default is stdin)')

    args = parser.parse_args()
    print args.__dict__

Unless you override it, :option:`!-h` and :option:`!--help` switches
are automatically added, and produce neatly formatted output::

    -> ./python.exe argparse-example.py --help
    usage: argparse-example.py [-h] [-v] [-o FILE] [-C NUM] [inputs [inputs ...]]

    Command-line example.

    positional arguments:
      inputs      input filenames (default is stdin)

    optional arguments:
      -h, --help  show this help message and exit
      -v          produce verbose output
      -o FILE     direct output to FILE instead of stdout
      -C NUM      display NUM lines of added context

As with :mod:`optparse`, the command-line switches and arguments
are returned as an object with attributes named by the *dest* parameters::

    -> ./python.exe argparse-example.py -v
    {'output': None,
     'is_verbose': True,
     'context': 0,
     'inputs': []}

    -> ./python.exe argparse-example.py -v -o /tmp/output -C 4 file1 file2
    {'output': '/tmp/output',
     'is_verbose': True,
     'context': 4,
     'inputs': ['file1', 'file2']}

:mod:`argparse` has much fancier validation than :mod:`optparse`; you
can specify an exact number of arguments as an integer, 0 or more
arguments by passing ``'*'``, 1 or more by passing ``'+'``, or an
optional argument with ``'?'``.  A top-level parser can contain
sub-parsers to define subcommands that have different sets of
switches, as in ``svn commit``, ``svn checkout``, etc.  You can
specify an argument's type as :class:`~argparse.FileType`, which will
automatically open files for you and understands that ``'-'`` means
standard input or output.

.. seealso::

   :mod:`argparse` documentation
     The documentation page of the argparse module.

   :ref:`argparse-from-optparse`
     Part of the Python documentation, describing how to convert
     code that uses :mod:`optparse`.

   :pep:`389` - argparse - New Command Line Parsing Module
     PEP written and implemented by Steven Bethard.

PEP 391: Dictionary-Based Configuration For Logging
====================================================

The :mod:`logging` module is very flexible; applications can define
a tree of logging subsystems, and each logger in this tree can filter
out certain messages, format them differently, and direct messages to
a varying number of handlers.

All this flexibility can require a lot of configuration.  You can
write Python statements to create objects and set their properties,
but a complex set-up requires verbose but boring code.
:mod:`logging` also supports a :func:`~logging.fileConfig`
function that parses a file, but the file format doesn't support
configuring filters, and it's messier to generate programmatically.

Python 2.7 adds a :func:`~logging.dictConfig` function that
uses a dictionary to configure logging.  There are many ways to
produce a dictionary from different sources: construct one with code;
parse a file containing JSON; or use a YAML parsing library if one is
installed.  For more information see :ref:`logging-config-api`.

The following example configures two loggers, the root logger and a
logger named "network".  Messages sent to the root logger will be
sent to the system log using the syslog protocol, and messages
to the "network" logger will be written to a :file:`network.log` file
that will be rotated once the log reaches 1MB.

::

    import logging
    import logging.config

    configdict = {
     'version': 1,    # Configuration schema in use; must be 1 for now
     'formatters': {
         'standard': {
             'format': ('%(asctime)s %(name)-15s '
                        '%(levelname)-8s %(message)s')}},

     'handlers': {'netlog': {'backupCount': 10,
                         'class': 'logging.handlers.RotatingFileHandler',
                         'filename': '/logs/network.log',
                         'formatter': 'standard',
                         'level': 'INFO',
                         'maxBytes': 1000000},
                  'syslog': {'class': 'logging.handlers.SysLogHandler',
                             'formatter': 'standard',
                             'level': 'ERROR'}},

     # Specify all the subordinate loggers
     'loggers': {
                 'network': {
                             'handlers': ['netlog']
                 }
     },
     # Specify properties of the root logger
     'root': {
              'handlers': ['syslog']
     },
    }

    # Set up configuration
    logging.config.dictConfig(configdict)

    # As an example, log two error messages
    logger = logging.getLogger('/')
    logger.error('Database not found')

    netlogger = logging.getLogger('network')
    netlogger.error('Connection failed')

Three smaller enhancements to the :mod:`logging` module, all
implemented by Vinay Sajip, are:

.. rev79293

* The :class:`~logging.handlers.SysLogHandler` class now supports
  syslogging over TCP.  The constructor has a *socktype* parameter
  giving the type of socket to use, either :const:`socket.SOCK_DGRAM`
  for UDP or :const:`socket.SOCK_STREAM` for TCP.  The default
  protocol remains UDP.

* :class:`~logging.Logger` instances gained a :meth:`~logging.Logger.getChild`
  method that retrieves a descendant logger using a relative path.
  For example, once you retrieve a logger by doing ``log = getLogger('app')``,
  calling ``log.getChild('network.listen')`` is equivalent to
  ``getLogger('app.network.listen')``.

* The :class:`~logging.LoggerAdapter` class gained an
  :meth:`~logging.LoggerAdapter.isEnabledFor` method that takes a
  *level* and returns whether the underlying logger would
  process a message of that level of importance.

.. XXX: Logger objects don't have a class declaration so the link don't work

.. seealso::

   :pep:`391` - Dictionary-Based Configuration For Logging
     PEP written and implemented by Vinay Sajip.

PEP 3106: Dictionary Views
====================================================

The dictionary methods :meth:`~dict.keys`, :meth:`~dict.values`, and
:meth:`~dict.items` are different in Python 3.x.  They return an object
called a :dfn:`view` instead of a fully materialized list.

It's not possible to change the return values of :meth:`~dict.keys`,
:meth:`~dict.values`, and :meth:`~dict.items` in Python 2.7 because
too much code would break.  Instead the 3.x versions were added
under the new names :meth:`~dict.viewkeys`, :meth:`~dict.viewvalues`,
and :meth:`~dict.viewitems`.

::

    >>> d = dict((i*10, chr(65+i)) for i in range(26))
    >>> d
    {0: 'A', 130: 'N', 10: 'B', 140: 'O', 20: ..., 250: 'Z'}
    >>> d.viewkeys()
    dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])

Views can be iterated over, but the key and item views also behave
like sets.  The ``&`` operator performs intersection, and ``|``
performs a union::

    >>> d1 = dict((i*10, chr(65+i)) for i in range(26))
    >>> d2 = dict((i**.5, i) for i in range(1000))
    >>> d1.viewkeys() & d2.viewkeys()
    set([0.0, 10.0, 20.0, 30.0])
    >>> d1.viewkeys() | range(0, 30)
    set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])

The view keeps track of the dictionary and its contents change as the
dictionary is modified::

    >>> vk = d.viewkeys()
    >>> vk
    dict_keys([0, 130, 10, ..., 250])
    >>> d[260] = '&'
    >>> vk
    dict_keys([0, 130, 260, 10, ..., 250])

However, note that you can't add or remove keys while you're iterating
over the view::

    >>> for k in vk:
    ...     d[k*2] = k
    ...
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    RuntimeError: dictionary changed size during iteration

You can use the view methods in Python 2.x code, and the 2to3
converter will change them to the standard :meth:`~dict.keys`,
:meth:`~dict.values`, and :meth:`~dict.items` methods.

.. seealso::

   :pep:`3106` - Revamping dict.keys(), .values() and .items()
     PEP written by Guido van Rossum.
     Backported to 2.7 by Alexandre Vassalotti; :issue:`1967`.


PEP 3137: The memoryview Object
====================================================

The :class:`memoryview` object provides a view of another object's
memory content that matches the :class:`bytes` type's interface.

    >>> import string
    >>> m = memoryview(string.letters)
    >>> m
    <memory at 0x37f850>
    >>> len(m)           # Returns length of underlying object
    52
    >>> m[0], m[25], m[26]   # Indexing returns one byte
    ('a', 'z', 'A')
    >>> m2 = m[0:26]         # Slicing returns another memoryview
    >>> m2
    <memory at 0x37f080>

The content of the view can be converted to a string of bytes or
a list of integers:

    >>> m2.tobytes()
    'abcdefghijklmnopqrstuvwxyz'
    >>> m2.tolist()
    [97, 98, 99, 100, 101, 102, 103, ... 121, 122]
    >>>

:class:`memoryview` objects allow modifying the underlying object if
it's a mutable object.

    >>> m2[0] = 75
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: cannot modify read-only memory
    >>> b = bytearray(string.letters)  # Creating a mutable object
    >>> b
    bytearray(b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
    >>> mb = memoryview(b)
    >>> mb[0] = '*'         # Assign to view, changing the bytearray.
    >>> b[0:5]              # The bytearray has been changed.
    bytearray(b'*bcde')
    >>>

.. seealso::

   :pep:`3137` - Immutable Bytes and Mutable Buffer
     PEP written by Guido van Rossum.
     Implemented by Travis Oliphant, Antoine Pitrou and others.
     Backported to 2.7 by Antoine Pitrou; :issue:`2396`.



Other Language Changes
======================

Some smaller changes made to the core Python language are:

* The syntax for set literals has been backported from Python 3.x.
  Curly brackets are used to surround the contents of the resulting
  mutable set; set literals are
  distinguished from dictionaries by not containing colons and values.
  ``{}`` continues to represent an empty dictionary; use
  ``set()`` for an empty set.

    >>> {1, 2, 3, 4, 5}
    set([1, 2, 3, 4, 5])
    >>> set() # empty set
    set([])
    >>> {}    # empty dict
    {}

  Backported by Alexandre Vassalotti; :issue:`2335`.

* Dictionary and set comprehensions are another feature backported from
  3.x, generalizing list/generator comprehensions to use
  the literal syntax for sets and dictionaries.

    >>> {x: x*x for x in range(6)}
    {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
    >>> {('a'*x) for x in range(6)}
    set(['', 'a', 'aa', 'aaa', 'aaaa', 'aaaaa'])

  Backported by Alexandre Vassalotti; :issue:`2333`.

* The :keyword:`with` statement can now use multiple context managers
  in one statement.  Context managers are processed from left to right
  and each one is treated as beginning a new :keyword:`with` statement.
  This means that::

   with A() as a, B() as b:
       ... suite of statements ...

  is equivalent to::

   with A() as a:
       with B() as b:
           ... suite of statements ...

  The :func:`contextlib.nested` function provides a very similar
  function, so it's no longer necessary and has been deprecated.

  (Proposed in https://codereview.appspot.com/53094; implemented by
  Georg Brandl.)

* Conversions between floating-point numbers and strings are
  now correctly rounded on most platforms.  These conversions occur
  in many different places: :func:`str` on
  floats and complex numbers; the :class:`float` and :class:`complex`
  constructors;
  numeric formatting; serializing and
  deserializing floats and complex numbers using the
  :mod:`marshal`, :mod:`pickle`
  and :mod:`json` modules;
  parsing of float and imaginary literals in Python code;
  and :class:`~decimal.Decimal`-to-float conversion.

  Related to this, the :func:`repr` of a floating-point number *x*
  now returns a result based on the shortest decimal string that's
  guaranteed to round back to *x* under correct rounding (with
  round-half-to-even rounding mode).  Previously it gave a string
  based on rounding x to 17 decimal digits.

  .. maybe add an example?

  The rounding library responsible for this improvement works on
  Windows and on Unix platforms using the gcc, icc, or suncc
  compilers.  There may be a small number of platforms where correct
  operation of this code cannot be guaranteed, so the code is not
  used on such systems.  You can find out which code is being used
  by checking :data:`sys.float_repr_style`,  which will be ``short``
  if the new code is in use and ``legacy`` if it isn't.

  Implemented by Eric Smith and Mark Dickinson, using David Gay's
  :file:`dtoa.c` library; :issue:`7117`.

* Conversions from long integers and regular integers to floating
  point now round differently, returning the floating-point number
  closest to the number.  This doesn't matter for small integers that
  can be converted exactly, but for large numbers that will
  unavoidably lose precision, Python 2.7 now approximates more
  closely.  For example, Python 2.6 computed the following::

    >>> n = 295147905179352891391
    >>> float(n)
    2.9514790517935283e+20
    >>> n - long(float(n))
    65535L

  Python 2.7's floating-point result is larger, but much closer to the
  true value::

    >>> n = 295147905179352891391
    >>> float(n)
    2.9514790517935289e+20
    >>> n - long(float(n))
    -1L

  (Implemented by Mark Dickinson; :issue:`3166`.)

  Integer division is also more accurate in its rounding behaviours.  (Also
  implemented by Mark Dickinson; :issue:`1811`.)

* Implicit coercion for complex numbers has been removed; the interpreter
  will no longer ever attempt to call a :meth:`__coerce__` method on complex
  objects.  (Removed by Meador Inge and Mark Dickinson; :issue:`5211`.)

* The :meth:`str.format` method now supports automatic numbering of the replacement
  fields.  This makes using :meth:`str.format` more closely resemble using
  ``%s`` formatting::

    >>> '{}:{}:{}'.format(2009, 04, 'Sunday')
    '2009:4:Sunday'
    >>> '{}:{}:{day}'.format(2009, 4, day='Sunday')
    '2009:4:Sunday'

  The auto-numbering takes the fields from left to right, so the first ``{...}``
  specifier will use the first argument to :meth:`str.format`, the next
  specifier will use the next argument, and so on.  You can't mix auto-numbering
  and explicit numbering -- either number all of your specifier fields or none
  of them -- but you can mix auto-numbering and named fields, as in the second
  example above.  (Contributed by Eric Smith; :issue:`5237`.)

  Complex numbers now correctly support usage with :func:`format`,
  and default to being right-aligned.
  Specifying a precision or comma-separation applies to both the real
  and imaginary parts of the number, but a specified field width and
  alignment is applied to the whole of the resulting ``1.5+3j``
  output.  (Contributed by Eric Smith; :issue:`1588` and :issue:`7988`.)

  The 'F' format code now always formats its output using uppercase characters,
  so it will now produce 'INF' and 'NAN'.
  (Contributed by Eric Smith; :issue:`3382`.)

  A low-level change: the :meth:`object.__format__` method now triggers
  a :exc:`PendingDeprecationWarning` if it's passed a format string,
  because the :meth:`__format__` method for :class:`object` converts
  the object to a string representation and formats that.  Previously
  the method silently applied the format string to the string
  representation, but that could hide mistakes in Python code.  If
  you're supplying formatting information such as an alignment or
  precision, presumably you're expecting the formatting to be applied
  in some object-specific way.  (Fixed by Eric Smith; :issue:`7994`.)

* The :func:`int` and :func:`long` types gained a ``bit_length``
  method that returns the number of bits necessary to represent
  its argument in binary::

      >>> n = 37
      >>> bin(n)
      '0b100101'
      >>> n.bit_length()
      6
      >>> n = 2**123-1
      >>> n.bit_length()
      123
      >>> (n+1).bit_length()
      124

  (Contributed by Fredrik Johansson and Victor Stinner; :issue:`3439`.)

* The :keyword:`import` statement will no longer try an absolute import
  if a relative import (e.g. ``from .os import sep``) fails.  This
  fixes a bug, but could possibly break certain :keyword:`import`
  statements that were only working by accident.  (Fixed by Meador Inge;
  :issue:`7902`.)

* It's now possible for a subclass of the built-in :class:`unicode` type
  to override the :meth:`__unicode__` method.  (Implemented by
  Victor Stinner; :issue:`1583863`.)

* The :class:`bytearray` type's :meth:`~bytearray.translate` method now accepts
  ``None`` as its first argument.  (Fixed by Georg Brandl;
  :issue:`4759`.)

  .. XXX bytearray doesn't seem to be documented

* When using ``@classmethod`` and ``@staticmethod`` to wrap
  methods as class or static methods, the wrapper object now
  exposes the wrapped function as their :attr:`__func__` attribute.
  (Contributed by Amaury Forgeot d'Arc, after a suggestion by
  George Sakkis; :issue:`5982`.)

* When a restricted set of attributes were set using ``__slots__``,
  deleting an unset attribute would not raise :exc:`AttributeError`
  as you would expect.  Fixed by Benjamin Peterson; :issue:`7604`.)

* Two new encodings are now supported: "cp720", used primarily for
  Arabic text; and "cp858", a variant of CP 850 that adds the euro
  symbol.  (CP720 contributed by Alexander Belchenko and Amaury
  Forgeot d'Arc in :issue:`1616979`; CP858 contributed by Tim Hatch in
  :issue:`8016`.)

* The :class:`file` object will now set the :attr:`filename` attribute
  on the :exc:`IOError` exception when trying to open a directory
  on POSIX platforms (noted by Jan Kaliszewski; :issue:`4764`), and
  now explicitly checks for and forbids writing to read-only file objects
  instead of trusting the C library to catch and report the error
  (fixed by Stefan Krah; :issue:`5677`).

* The Python tokenizer now translates line endings itself, so the
  :func:`compile` built-in function now accepts code using any
  line-ending convention.  Additionally, it no longer requires that the
  code end in a newline.

* Extra parentheses in function definitions are illegal in Python 3.x,
  meaning that you get a syntax error from ``def f((x)): pass``.  In
  Python3-warning mode, Python 2.7 will now warn about this odd usage.
  (Noted by James Lingard; :issue:`7362`.)

* It's now possible to create weak references to old-style class
  objects.  New-style classes were always weak-referenceable.  (Fixed
  by Antoine Pitrou; :issue:`8268`.)

* When a module object is garbage-collected, the module's dictionary is
  now only cleared if no one else is holding a reference to the
  dictionary (:issue:`7140`).

.. ======================================================================

.. _new-27-interpreter:

Interpreter Changes
-------------------------------

A new environment variable, :envvar:`PYTHONWARNINGS`,
allows controlling warnings.  It should be set to a string
containing warning settings, equivalent to those
used with the :option:`-W` switch, separated by commas.
(Contributed by Brian Curtin; :issue:`7301`.)

For example, the following setting will print warnings every time
they occur, but turn warnings from the :mod:`Cookie` module into an
error.  (The exact syntax for setting an environment variable varies
across operating systems and shells.)

::

  export PYTHONWARNINGS=all,error:::Cookie:0

.. ======================================================================


Optimizations
-------------

Several performance enhancements have been added:

* A new opcode was added to perform the initial setup for
  :keyword:`with` statements, looking up the :meth:`__enter__` and
  :meth:`__exit__` methods.  (Contributed by Benjamin Peterson.)

* The garbage collector now performs better for one common usage
  pattern: when many objects are being allocated without deallocating
  any of them.  This would previously take quadratic
  time for garbage collection, but now the number of full garbage collections
  is reduced as the number of objects on the heap grows.
  The new logic only performs a full garbage collection pass when
  the middle generation has been collected 10 times and when the
  number of survivor objects from the middle generation exceeds 10% of
  the number of objects in the oldest generation.  (Suggested by Martin
  von Löwis and implemented by Antoine Pitrou; :issue:`4074`.)

* The garbage collector tries to avoid tracking simple containers
  which can't be part of a cycle. In Python 2.7, this is now true for
  tuples and dicts containing atomic types (such as ints, strings,
  etc.). Transitively, a dict containing tuples of atomic types won't
  be tracked either. This helps reduce the cost of each
  garbage collection by decreasing the number of objects to be
  considered and traversed by the collector.
  (Contributed by Antoine Pitrou; :issue:`4688`.)

* Long integers are now stored internally either in base 2**15 or in base
  2**30, the base being determined at build time.  Previously, they
  were always stored in base 2**15.  Using base 2**30 gives
  significant performance improvements on 64-bit machines, but
  benchmark results on 32-bit machines have been mixed.  Therefore,
  the default is to use base 2**30 on 64-bit machines and base 2**15
  on 32-bit machines; on Unix, there's a new configure option
  :option:`!--enable-big-digits` that can be used to override this default.

  Apart from the performance improvements this change should be
  invisible to end users, with one exception: for testing and
  debugging purposes there's a new structseq :data:`sys.long_info` that
  provides information about the internal format, giving the number of
  bits per digit and the size in bytes of the C type used to store
  each digit::

     >>> import sys
     >>> sys.long_info
     sys.long_info(bits_per_digit=30, sizeof_digit=4)

  (Contributed by Mark Dickinson; :issue:`4258`.)

  Another set of changes made long objects a few bytes smaller: 2 bytes
  smaller on 32-bit systems and 6 bytes on 64-bit.
  (Contributed by Mark Dickinson; :issue:`5260`.)

* The division algorithm for long integers has been made faster
  by tightening the inner loop, doing shifts instead of multiplications,
  and fixing an unnecessary extra iteration.
  Various benchmarks show speedups of between 50% and 150% for long
  integer divisions and modulo operations.
  (Contributed by Mark Dickinson; :issue:`5512`.)
  Bitwise operations are also significantly faster (initial patch by
  Gregory Smith; :issue:`1087418`).

* The implementation of ``%`` checks for the left-side operand being
  a Python string and special-cases it; this results in a 1--3%
  performance increase for applications that frequently use ``%``
  with strings, such as templating libraries.
  (Implemented by Collin Winter; :issue:`5176`.)

* List comprehensions with an ``if`` condition are compiled into
  faster bytecode.  (Patch by Antoine Pitrou, back-ported to 2.7
  by Jeffrey Yasskin; :issue:`4715`.)

* Converting an integer or long integer to a decimal string was made
  faster by special-casing base 10 instead of using a generalized
  conversion function that supports arbitrary bases.
  (Patch by Gawain Bolton; :issue:`6713`.)

* The :meth:`split`, :meth:`replace`, :meth:`rindex`,
  :meth:`rpartition`, and :meth:`rsplit` methods of string-like types
  (strings, Unicode strings, and :class:`bytearray` objects) now use a
  fast reverse-search algorithm instead of a character-by-character
  scan.  This is sometimes faster by a factor of 10.  (Added by
  Florent Xicluna; :issue:`7462` and :issue:`7622`.)

* The :mod:`pickle` and :mod:`cPickle` modules now automatically
  intern the strings used for attribute names, reducing memory usage
  of the objects resulting from unpickling.  (Contributed by Jake
  McGuire; :issue:`5084`.)

* The :mod:`cPickle` module now special-cases dictionaries,
  nearly halving the time required to pickle them.
  (Contributed by Collin Winter; :issue:`5670`.)

.. ======================================================================

New and Improved Modules
========================

As in every release, Python's standard library received a number of
enhancements and bug fixes.  Here's a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
:file:`Misc/NEWS` file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.

* The :mod:`bdb` module's base debugging class :class:`~bdb.Bdb`
  gained a feature for skipping modules.  The constructor
  now takes an iterable containing glob-style patterns such as
  ``django.*``; the debugger will not step into stack frames
  from a module that matches one of these patterns.
  (Contributed by Maru Newby after a suggestion by
  Senthil Kumaran; :issue:`5142`.)

* The :mod:`binascii` module now supports the buffer API, so it can be
  used with :class:`memoryview` instances and other similar buffer objects.
  (Backported from 3.x by Florent Xicluna; :issue:`7703`.)

* Updated module: the :mod:`bsddb` module has been updated from 4.7.2devel9
  to version 4.8.4 of
  `the pybsddb package <https://www.jcea.es/programacion/pybsddb.htm>`__.
  The new version features better Python 3.x compatibility, various bug fixes,
  and adds several new BerkeleyDB flags and methods.
  (Updated by Jesús Cea Avión; :issue:`8156`.  The pybsddb
  changelog can be read at http://hg.jcea.es/pybsddb/file/tip/ChangeLog.)

* The :mod:`bz2` module's :class:`~bz2.BZ2File` now supports the context
  management protocol, so you can write ``with bz2.BZ2File(...) as f:``.
  (Contributed by Hagen Fürstenau; :issue:`3860`.)

* New class: the :class:`~collections.Counter` class in the :mod:`collections`
  module is useful for tallying data.  :class:`~collections.Counter` instances
  behave mostly like dictionaries but return zero for missing keys instead of
  raising a :exc:`KeyError`:

  .. doctest::
     :options: +NORMALIZE_WHITESPACE

     >>> from collections import Counter
     >>> c = Counter()
     >>> for letter in 'here is a sample of english text':
     ...   c[letter] += 1
     ...
     >>> c
     Counter({' ': 6, 'e': 5, 's': 3, 'a': 2, 'i': 2, 'h': 2,
     'l': 2, 't': 2, 'g': 1, 'f': 1, 'm': 1, 'o': 1, 'n': 1,
     'p': 1, 'r': 1, 'x': 1})
     >>> c['e']
     5
     >>> c['z']
     0

  There are three additional :class:`~collections.Counter` methods.
  :meth:`~collections.Counter.most_common` returns the N most common
  elements and their counts.  :meth:`~collections.Counter.elements`
  returns an iterator over the contained elements, repeating each
  element as many times as its count.
  :meth:`~collections.Counter.subtract` takes an iterable and
  subtracts one for each element instead of adding; if the argument is
  a dictionary or another :class:`Counter`, the counts are
  subtracted. ::

    >>> c.most_common(5)
    [(' ', 6), ('e', 5), ('s', 3), ('a', 2), ('i', 2)]
    >>> c.elements() ->
       'a', 'a', ' ', ' ', ' ', ' ', ' ', ' ',
       'e', 'e', 'e', 'e', 'e', 'g', 'f', 'i', 'i',
       'h', 'h', 'm', 'l', 'l', 'o', 'n', 'p', 's',
       's', 's', 'r', 't', 't', 'x'
    >>> c['e']
    5
    >>> c.subtract('very heavy on the letter e')
    >>> c['e']    # Count is now lower
    -1

  Contributed by Raymond Hettinger; :issue:`1696199`.

  .. revision 79660

  New class: :class:`~collections.OrderedDict` is described in the earlier
  section :ref:`pep-0372`.

  New method: The :class:`~collections.deque` data type now has a
  :meth:`~collections.deque.count` method that returns the number of
  contained elements equal to the supplied argument *x*, and a
  :meth:`~collections.deque.reverse` method that reverses the elements
  of the deque in-place.  :class:`~collections.deque` also exposes its maximum
  length as the read-only :attr:`~collections.deque.maxlen` attribute.
  (Both features added by Raymond Hettinger.)

  The :class:`~collections.namedtuple` class now has an optional *rename* parameter.
  If *rename* is true, field names that are invalid because they've
  been repeated or aren't legal Python identifiers will be
  renamed to legal names that are derived from the field's
  position within the list of fields:

     >>> from collections import namedtuple
     >>> T = namedtuple('T', ['field1', '$illegal', 'for', 'field2'], rename=True)
     >>> T._fields
     ('field1', '_1', '_2', 'field2')

  (Added by Raymond Hettinger; :issue:`1818`.)

  Finally, the :class:`~collections.Mapping` abstract base class now
  returns :const:`NotImplemented` if a mapping is compared to
  another type that isn't a :class:`Mapping`.
  (Fixed by Daniel Stutzbach; :issue:`8729`.)

* Constructors for the parsing classes in the :mod:`ConfigParser` module now
  take an *allow_no_value* parameter, defaulting to false; if true,
  options without values will be allowed.  For example::

    >>> import ConfigParser, StringIO
    >>> sample_config = """
    ... [mysqld]
    ... user = mysql
    ... pid-file = /var/run/mysqld/mysqld.pid
    ... skip-bdb
    ... """
    >>> config = ConfigParser.RawConfigParser(allow_no_value=True)
    >>> config.readfp(StringIO.StringIO(sample_config))
    >>> config.get('mysqld', 'user')
    'mysql'
    >>> print config.get('mysqld', 'skip-bdb')
    None
    >>> print config.get('mysqld', 'unknown')
    Traceback (most recent call last):
      ...
    NoOptionError: No option 'unknown' in section: 'mysqld'

  (Contributed by Mats Kindahl; :issue:`7005`.)

* Deprecated function: :func:`contextlib.nested`, which allows
  handling more than one context manager with a single :keyword:`with`
  statement, has been deprecated, because the :keyword:`with` statement
  now supports multiple context managers.

* The :mod:`cookielib` module now ignores cookies that have an invalid
  version field, one that doesn't contain an integer value.  (Fixed by
  John J. Lee; :issue:`3924`.)

* The :mod:`copy` module's :func:`~copy.deepcopy` function will now
  correctly copy bound instance methods.  (Implemented by
  Robert Collins; :issue:`1515`.)

* The :mod:`ctypes` module now always converts ``None`` to a C NULL
  pointer for arguments declared as pointers.  (Changed by Thomas
  Heller; :issue:`4606`.)  The underlying `libffi library
  <https://sourceware.org/libffi/>`__ has been updated to version
  3.0.9, containing various fixes for different platforms.  (Updated
  by Matthias Klose; :issue:`8142`.)

* New method: the :mod:`datetime` module's :class:`~datetime.timedelta` class
  gained a :meth:`~datetime.timedelta.total_seconds` method that returns the
  number of seconds in the duration.  (Contributed by Brian Quinlan; :issue:`5788`.)

* New method: the :class:`~decimal.Decimal` class gained a
  :meth:`~decimal.Decimal.from_float` class method that performs an exact
  conversion of a floating-point number to a :class:`~decimal.Decimal`.
  This exact conversion strives for the
  closest decimal approximation to the floating-point representation's value;
  the resulting decimal value will therefore still include the inaccuracy,
  if any.
  For example, ``Decimal.from_float(0.1)`` returns
  ``Decimal('0.1000000000000000055511151231257827021181583404541015625')``.
  (Implemented by Raymond Hettinger; :issue:`4796`.)

  Comparing instances of :class:`~decimal.Decimal` with floating-point
  numbers now produces sensible results based on the numeric values
  of the operands.  Previously such comparisons would fall back to
  Python's default rules for comparing objects, which produced arbitrary
  results based on their type.  Note that you still cannot combine
  :class:`Decimal` and floating-point in other operations such as addition,
  since you should be explicitly choosing how to convert between float and
  :class:`~decimal.Decimal`.  (Fixed by Mark Dickinson; :issue:`2531`.)

  The constructor for :class:`~decimal.Decimal` now accepts
  floating-point numbers (added by Raymond Hettinger; :issue:`8257`)
  and non-European Unicode characters such as Arabic-Indic digits
  (contributed by Mark Dickinson; :issue:`6595`).

  Most of the methods of the :class:`~decimal.Context` class now accept integers
  as well as :class:`~decimal.Decimal` instances; the only exceptions are the
  :meth:`~decimal.Context.canonical` and :meth:`~decimal.Context.is_canonical`
  methods.  (Patch by Juan José Conti; :issue:`7633`.)

  When using :class:`~decimal.Decimal` instances with a string's
  :meth:`~str.format` method, the default alignment was previously
  left-alignment.  This has been changed to right-alignment, which is
  more sensible for numeric types.  (Changed by Mark Dickinson; :issue:`6857`.)

  Comparisons involving a signaling NaN value (or ``sNAN``) now signal
  :const:`InvalidOperation` instead of silently returning a true or
  false value depending on the comparison operator.  Quiet NaN values
  (or ``NaN``) are now hashable.  (Fixed by Mark Dickinson;
  :issue:`7279`.)

* The :mod:`difflib` module now produces output that is more
  compatible with modern :command:`diff`/:command:`patch` tools
  through one small change, using a tab character instead of spaces as
  a separator in the header giving the filename.  (Fixed by Anatoly
  Techtonik; :issue:`7585`.)

* The Distutils ``sdist`` command now always regenerates the
  :file:`MANIFEST` file, since even if the :file:`MANIFEST.in` or
  :file:`setup.py` files haven't been modified, the user might have
  created some new files that should be included.
  (Fixed by Tarek Ziadé; :issue:`8688`.)

* The :mod:`doctest` module's :const:`IGNORE_EXCEPTION_DETAIL` flag
  will now ignore the name of the module containing the exception
  being tested.  (Patch by Lennart Regebro; :issue:`7490`.)

* The :mod:`email` module's :class:`~email.message.Message` class will
  now accept a Unicode-valued payload, automatically converting the
  payload to the encoding specified by :attr:`output_charset`.
  (Added by R. David Murray; :issue:`1368247`.)

* The :class:`~fractions.Fraction` class now accepts a single float or
  :class:`~decimal.Decimal` instance, or two rational numbers, as
  arguments to its constructor.  (Implemented by Mark Dickinson;
  rationals added in :issue:`5812`, and float/decimal in
  :issue:`8294`.)

  Ordering comparisons (``<``, ``<=``, ``>``, ``>=``) between
  fractions and complex numbers now raise a :exc:`TypeError`.
  This fixes an oversight, making the :class:`~fractions.Fraction`
  match the other numeric types.

  .. revision 79455

* New class: :class:`~ftplib.FTP_TLS` in
  the :mod:`ftplib` module provides secure FTP
  connections using TLS encapsulation of authentication as well as
  subsequent control and data transfers.
  (Contributed by Giampaolo Rodola; :issue:`2054`.)

  The :meth:`~ftplib.FTP.storbinary` method for binary uploads can now restart
  uploads thanks to an added *rest* parameter (patch by Pablo Mouzo;
  :issue:`6845`.)

* New class decorator: :func:`~functools.total_ordering` in the :mod:`functools`
  module takes a class that defines an :meth:`__eq__` method and one of
  :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`,
  and generates the missing comparison methods.  Since the
  :meth:`__cmp__` method is being deprecated in Python 3.x,
  this decorator makes it easier to define ordered classes.
  (Added by Raymond Hettinger; :issue:`5479`.)

  New function: :func:`~functools.cmp_to_key` will take an old-style comparison
  function that expects two arguments and return a new callable that
  can be used as the *key* parameter to functions such as
  :func:`sorted`, :func:`min` and :func:`max`, etc.  The primary
  intended use is to help with making code compatible with Python 3.x.
  (Added by Raymond Hettinger.)

* New function: the :mod:`gc` module's :func:`~gc.is_tracked` returns
  true if a given instance is tracked by the garbage collector, false
  otherwise. (Contributed by Antoine Pitrou; :issue:`4688`.)

* The :mod:`gzip` module's :class:`~gzip.GzipFile` now supports the context
  management protocol, so you can write ``with gzip.GzipFile(...) as f:``
  (contributed by Hagen Fürstenau; :issue:`3860`), and it now implements
  the :class:`io.BufferedIOBase` ABC, so you can wrap it with
  :class:`io.BufferedReader` for faster processing
  (contributed by Nir Aides; :issue:`7471`).
  It's also now possible to override the modification time
  recorded in a gzipped file by providing an optional timestamp to
  the constructor.  (Contributed by Jacques Frechet; :issue:`4272`.)

  Files in gzip format can be padded with trailing zero bytes; the
  :mod:`gzip` module will now consume these trailing bytes.  (Fixed by
  Tadek Pietraszek and Brian Curtin; :issue:`2846`.)

* New attribute: the :mod:`hashlib` module now has an :attr:`~hashlib.hashlib.algorithms`
  attribute containing a tuple naming the supported algorithms.
  In Python 2.7, ``hashlib.algorithms`` contains
  ``('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')``.
  (Contributed by Carl Chenet; :issue:`7418`.)

* The default :class:`~httplib.HTTPResponse` class used by the :mod:`httplib` module now
  supports buffering, resulting in much faster reading of HTTP responses.
  (Contributed by Kristján Valur Jónsson; :issue:`4879`.)

  The :class:`~httplib.HTTPConnection` and :class:`~httplib.HTTPSConnection` classes
  now support a *source_address* parameter, a ``(host, port)`` 2-tuple
  giving the source address that will be used for the connection.
  (Contributed by Eldon Ziegler; :issue:`3972`.)

* The :mod:`ihooks` module now supports relative imports.  Note that
  :mod:`ihooks` is an older module for customizing imports,
  superseded by the :mod:`imputil` module added in Python 2.0.
  (Relative import support added by Neil Schemenauer.)

  .. revision 75423

* The :mod:`imaplib` module now supports IPv6 addresses.
  (Contributed by Derek Morr; :issue:`1655`.)

* New function: the :mod:`inspect` module's :func:`~inspect.getcallargs`
  takes a callable and its positional and keyword arguments,
  and figures out which of the callable's parameters will receive each argument,
  returning a dictionary mapping argument names to their values.  For example::

    >>> from inspect import getcallargs
    >>> def f(a, b=1, *pos, **named):
    ...     pass
    >>> getcallargs(f, 1, 2, 3)
    {'a': 1, 'b': 2, 'pos': (3,), 'named': {}}
    >>> getcallargs(f, a=2, x=4)
    {'a': 2, 'b': 1, 'pos': (), 'named': {'x': 4}}
    >>> getcallargs(f)
    Traceback (most recent call last):
    ...
    TypeError: f() takes at least 1 argument (0 given)

  Contributed by George Sakkis; :issue:`3135`.

* Updated module: The :mod:`io` library has been upgraded to the version shipped with
  Python 3.1.  For 3.1, the I/O library was entirely rewritten in C
  and is 2 to 20 times faster depending on the task being performed.  The
  original Python version was renamed to the :mod:`_pyio` module.

  One minor resulting change: the :class:`io.TextIOBase` class now
  has an :attr:`errors` attribute giving the error setting
  used for encoding and decoding errors (one of ``'strict'``, ``'replace'``,
  ``'ignore'``).

  The :class:`io.FileIO` class now raises an :exc:`OSError` when passed
  an invalid file descriptor.  (Implemented by Benjamin Peterson;
  :issue:`4991`.)  The :meth:`~io.IOBase.truncate` method now preserves the
  file position; previously it would change the file position to the
  end of the new file.  (Fixed by Pascal Chambon; :issue:`6939`.)

* New function: ``itertools.compress(data, selectors)`` takes two
  iterators.  Elements of *data* are returned if the corresponding
  value in *selectors* is true::

    itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
      A, C, E, F

  .. maybe here is better to use >>> list(itertools.compress(...)) instead

  New function: ``itertools.combinations_with_replacement(iter, r)``
  returns all the possible *r*-length combinations of elements from the
  iterable *iter*.  Unlike :func:`~itertools.combinations`, individual elements
  can be repeated in the generated combinations::

    itertools.combinations_with_replacement('abc', 2) =>
      ('a', 'a'), ('a', 'b'), ('a', 'c'),
      ('b', 'b'), ('b', 'c'), ('c', 'c')

  Note that elements are treated as unique depending on their position
  in the input, not their actual values.

  The :func:`itertools.count` function now has a *step* argument that
  allows incrementing by values other than 1.  :func:`~itertools.count` also
  now allows keyword arguments, and using non-integer values such as
  floats or :class:`~decimal.Decimal` instances.  (Implemented by Raymond
  Hettinger; :issue:`5032`.)

  :func:`itertools.combinations` and :func:`itertools.product`
  previously raised :exc:`ValueError` for values of *r* larger than
  the input iterable.  This was deemed a specification error, so they
  now return an empty iterator.  (Fixed by Raymond Hettinger; :issue:`4816`.)

* Updated module: The :mod:`json` module was upgraded to version 2.0.9 of the
  simplejson package, which includes a C extension that makes
  encoding and decoding faster.
  (Contributed by Bob Ippolito; :issue:`4136`.)

  To support the new :class:`collections.OrderedDict` type, :func:`json.load`
  now has an optional *object_pairs_hook* parameter that will be called
  with any object literal that decodes to a list of pairs.
  (Contributed by Raymond Hettinger; :issue:`5381`.)

* The :mod:`mailbox` module's :class:`~mailbox.Maildir` class now records the
  timestamp on the directories it reads, and only re-reads them if the
  modification time has subsequently changed.  This improves
  performance by avoiding unneeded directory scans.  (Fixed by
  A.M. Kuchling and Antoine Pitrou; :issue:`1607951`, :issue:`6896`.)

* New functions: the :mod:`math` module gained
  :func:`~math.erf` and :func:`~math.erfc` for the error function and the complementary error function,
  :func:`~math.expm1` which computes ``e**x - 1`` with more precision than
  using :func:`~math.exp` and subtracting 1,
  :func:`~math.gamma` for the Gamma function, and
  :func:`~math.lgamma` for the natural log of the Gamma function.
  (Contributed by Mark Dickinson and nirinA raseliarison; :issue:`3366`.)

* The :mod:`multiprocessing` module's :class:`Manager*` classes
  can now be passed a callable that will be called whenever
  a subprocess is started, along with a set of arguments that will be
  passed to the callable.
  (Contributed by lekma; :issue:`5585`.)

  The :class:`~multiprocessing.Pool` class, which controls a pool of worker processes,
  now has an optional *maxtasksperchild* parameter.  Worker processes
  will perform the specified number of tasks and then exit, causing the
  :class:`~multiprocessing.Pool` to start a new worker.  This is useful if tasks may leak
  memory or other resources, or if some tasks will cause the worker to
  become very large.
  (Contributed by Charles Cazabon; :issue:`6963`.)

* The :mod:`nntplib` module now supports IPv6 addresses.
  (Contributed by Derek Morr; :issue:`1664`.)

* New functions: the :mod:`os` module wraps the following POSIX system
  calls: :func:`~os.getresgid` and :func:`~os.getresuid`, which return the
  real, effective, and saved GIDs and UIDs;
  :func:`~os.setresgid` and :func:`~os.setresuid`, which set
  real, effective, and saved GIDs and UIDs to new values;
  :func:`~os.initgroups`, which initialize the group access list
  for the current process.  (GID/UID functions
  contributed by Travis H.; :issue:`6508`.  Support for initgroups added
  by Jean-Paul Calderone; :issue:`7333`.)

  The :func:`os.fork` function now re-initializes the import lock in
  the child process; this fixes problems on Solaris when :func:`~os.fork`
  is called from a thread.  (Fixed by Zsolt Cserna; :issue:`7242`.)

* In the :mod:`os.path` module, the :func:`~os.path.normpath` and
  :func:`~os.path.abspath` functions now preserve Unicode; if their input path
  is a Unicode string, the return value is also a Unicode string.
  (:meth:`~os.path.normpath` fixed by Matt Giuca in :issue:`5827`;
  :meth:`~os.path.abspath` fixed by Ezio Melotti in :issue:`3426`.)

* The :mod:`pydoc` module now has help for the various symbols that Python
  uses.  You can now do ``help('<<')`` or ``help('@')``, for example.
  (Contributed by David Laban; :issue:`4739`.)

* The :mod:`re` module's :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn`
  now accept an optional *flags* argument, for consistency with the
  other functions in the module.  (Added by Gregory P. Smith.)

* New function: :func:`~runpy.run_path` in the :mod:`runpy` module
  will execute the code at a provided *path* argument.  *path* can be
  the path of a Python source file (:file:`example.py`), a compiled
  bytecode file (:file:`example.pyc`), a directory
  (:file:`./package/`), or a zip archive (:file:`example.zip`).  If a
  directory or zip path is provided, it will be added to the front of
  ``sys.path`` and the module :mod:`__main__` will be imported.  It's
  expected that the directory or zip contains a :file:`__main__.py`;
  if it doesn't, some other :file:`__main__.py` might be imported from
  a location later in ``sys.path``.  This makes more of the machinery
  of :mod:`runpy` available to scripts that want to mimic the way
  Python's command line processes an explicit path name.
  (Added by Nick Coghlan; :issue:`6816`.)

* New function: in the :mod:`shutil` module, :func:`~shutil.make_archive`
  takes a filename, archive type (zip or tar-format), and a directory
  path, and creates an archive containing the directory's contents.
  (Added by Tarek Ziadé.)

  :mod:`shutil`'s :func:`~shutil.copyfile` and :func:`~shutil.copytree`
  functions now raise a :exc:`~shutil.SpecialFileError` exception when
  asked to copy a named pipe.  Previously the code would treat
  named pipes like a regular file by opening them for reading, and
  this would block indefinitely.  (Fixed by Antoine Pitrou; :issue:`3002`.)

* The :mod:`signal` module no longer re-installs the signal handler
  unless this is truly necessary, which fixes a bug that could make it
  impossible to catch the EINTR signal robustly.  (Fixed by
  Charles-Francois Natali; :issue:`8354`.)

* New functions: in the :mod:`site` module, three new functions
  return various site- and user-specific paths.
  :func:`~site.getsitepackages` returns a list containing all
  global site-packages directories,
  :func:`~site.getusersitepackages` returns the path of the user's
  site-packages directory, and
  :func:`~site.getuserbase` returns the value of the :envvar:`USER_BASE`
  environment variable, giving the path to a directory that can be used
  to store data.
  (Contributed by Tarek Ziadé; :issue:`6693`.)

  The :mod:`site` module now reports exceptions occurring
  when the :mod:`sitecustomize` module is imported, and will no longer
  catch and swallow the :exc:`KeyboardInterrupt` exception.  (Fixed by
  Victor Stinner; :issue:`3137`.)

* The :func:`~socket.create_connection` function
  gained a *source_address* parameter, a ``(host, port)`` 2-tuple
  giving the source address that will be used for the connection.
  (Contributed by Eldon Ziegler; :issue:`3972`.)

  The :meth:`~socket.socket.recv_into` and :meth:`~socket.socket.recvfrom_into`
  methods will now write into objects that support the buffer API, most usefully
  the :class:`bytearray` and :class:`memoryview` objects.  (Implemented by
  Antoine Pitrou; :issue:`8104`.)

* The :mod:`SocketServer` module's :class:`~SocketServer.TCPServer` class now
  supports socket timeouts and disabling the Nagle algorithm.
  The :attr:`~SocketServer.TCPServer.disable_nagle_algorithm` class attribute
  defaults to ``False``; if overridden to be true,
  new request connections will have the TCP_NODELAY option set to
  prevent buffering many small sends into a single TCP packet.
  The :attr:`~SocketServer.BaseServer.timeout` class attribute can hold
  a timeout in seconds that will be applied to the request socket; if
  no request is received within that time, :meth:`~SocketServer.BaseServer.handle_timeout`
  will be called and :meth:`~SocketServer.BaseServer.handle_request` will return.
  (Contributed by Kristján Valur Jónsson; :issue:`6192` and :issue:`6267`.)

* Updated module: the :mod:`sqlite3` module has been updated to
  version 2.6.0 of the `pysqlite package <https://github.com/ghaering/pysqlite>`__. Version 2.6.0 includes a number of bugfixes, and adds
  the ability to load SQLite extensions from shared libraries.
  Call the ``enable_load_extension(True)`` method to enable extensions,
  and then call :meth:`~sqlite3.Connection.load_extension` to load a particular shared library.
  (Updated by Gerhard Häring.)

* The :mod:`ssl` module's :class:`~ssl.SSLSocket` objects now support the
  buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
  :issue:`7133`) and automatically set
  OpenSSL's :c:macro:`SSL_MODE_AUTO_RETRY`, which will prevent an error
  code being returned from :meth:`recv` operations that trigger an SSL
  renegotiation (fix by Antoine Pitrou; :issue:`8222`).

  The :func:`ssl.wrap_socket` constructor function now takes a
  *ciphers* argument that's a string listing the encryption algorithms
  to be allowed; the format of the string is described
  `in the OpenSSL documentation
  <https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT>`__.
  (Added by Antoine Pitrou; :issue:`8322`.)

  Another change makes the extension load all of OpenSSL's ciphers and
  digest algorithms so that they're all available.  Some SSL
  certificates couldn't be verified, reporting an "unknown algorithm"
  error.  (Reported by Beda Kosata, and fixed by Antoine Pitrou;
  :issue:`8484`.)

  The version of OpenSSL being used is now available as the module
  attributes :data:`ssl.OPENSSL_VERSION` (a string),
  :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
  :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer).  (Added by Antoine
  Pitrou; :issue:`8321`.)

* The :mod:`struct` module will no longer silently ignore overflow
  errors when a value is too large for a particular integer format
  code (one of ``bBhHiIlLqQ``); it now always raises a
  :exc:`struct.error` exception.  (Changed by Mark Dickinson;
  :issue:`1523`.)  The :func:`~struct.pack` function will also
  attempt to use :meth:`__index__` to convert and pack non-integers
  before trying the :meth:`__int__` method or reporting an error.
  (Changed by Mark Dickinson; :issue:`8300`.)

* New function: the :mod:`subprocess` module's
  :func:`~subprocess.check_output` runs a command with a specified set of arguments
  and returns the command's output as a string when the command runs without
  error, or raises a :exc:`~subprocess.CalledProcessError` exception otherwise.

  ::

    >>> subprocess.check_output(['df', '-h', '.'])
    'Filesystem     Size   Used  Avail Capacity  Mounted on\n
    /dev/disk0s2    52G    49G   3.0G    94%    /\n'

    >>> subprocess.check_output(['df', '-h', '/bogus'])
      ...
    subprocess.CalledProcessError: Command '['df', '-h', '/bogus']' returned non-zero exit status 1

  (Contributed by Gregory P. Smith.)

  The :mod:`subprocess` module will now retry its internal system calls
  on receiving an :const:`EINTR` signal.  (Reported by several people; final
  patch by Gregory P. Smith in :issue:`1068268`.)

* New function: :func:`~symtable.Symbol.is_declared_global` in the :mod:`symtable` module
  returns true for variables that are explicitly declared to be global,
  false for ones that are implicitly global.
  (Contributed by Jeremy Hylton.)

* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
  identifier instead of the previous default value of ``'python'``.
  (Changed by Sean Reifschneider; :issue:`8451`.)

* The ``sys.version_info`` value is now a named tuple, with attributes
  named :attr:`major`, :attr:`minor`, :attr:`micro`,
  :attr:`releaselevel`, and :attr:`serial`.  (Contributed by Ross
  Light; :issue:`4285`.)

  :func:`sys.getwindowsversion` also returns a named tuple,
  with attributes named :attr:`major`, :attr:`minor`, :attr:`build`,
  :attr:`platform`, :attr:`service_pack`, :attr:`service_pack_major`,
  :attr:`service_pack_minor`, :attr:`suite_mask`, and
  :attr:`product_type`.  (Contributed by Brian Curtin; :issue:`7766`.)

* The :mod:`tarfile` module's default error handling has changed, to
  no longer suppress fatal errors.  The default error level was previously 0,
  which meant that errors would only result in a message being written to the
  debug log, but because the debug log is not activated by default,
  these errors go unnoticed.  The default error level is now 1,
  which raises an exception if there's an error.
  (Changed by Lars Gustäbel; :issue:`7357`.)

  :mod:`tarfile` now supports filtering the :class:`~tarfile.TarInfo`
  objects being added to a tar file.  When you call :meth:`~tarfile.TarFile.add`,
  you may supply an optional *filter* argument
  that's a callable.  The *filter* callable will be passed the
  :class:`~tarfile.TarInfo` for every file being added, and can modify and return it.
  If the callable returns ``None``, the file will be excluded from the
  resulting archive.  This is more powerful than the existing
  *exclude* argument, which has therefore been deprecated.
  (Added by Lars Gustäbel; :issue:`6856`.)
  The :class:`~tarfile.TarFile` class also now supports the context management protocol.
  (Added by Lars Gustäbel; :issue:`7232`.)

* The :meth:`~threading.Event.wait` method of the :class:`threading.Event` class
  now returns the internal flag on exit.  This means the method will usually
  return true because :meth:`~threading.Event.wait` is supposed to block until the
  internal flag becomes true.  The return value will only be false if
  a timeout was provided and the operation timed out.
  (Contributed by Tim Lesher; :issue:`1674032`.)

* The Unicode database provided by the :mod:`unicodedata` module is
  now used internally to determine which characters are numeric,
  whitespace, or represent line breaks.  The database also
  includes information from the :file:`Unihan.txt` data file (patch
  by Anders Chrigström and Amaury Forgeot d'Arc; :issue:`1571184`)
  and has been updated to version 5.2.0 (updated by
  Florent Xicluna; :issue:`8024`).

* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
  unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
  URL is of the form ``"<something>://..."``, the text before the
  ``://`` is treated as the scheme, even if it's a made-up scheme that
  the module doesn't know about.  This change may break code that
  worked around the old behaviour.  For example, Python 2.6.4 or 2.5
  will return the following:

    >>> import urlparse
    >>> urlparse.urlsplit('invented://host/filename?query')
    ('invented', '', '//host/filename?query', '', '')

  Python 2.7 (and Python 2.6.5) will return:

    >>> import urlparse
    >>> urlparse.urlsplit('invented://host/filename?query')
    ('invented', 'host', '/filename?query', '', '')

  (Python 2.7 actually produces slightly different output, since it
  returns a named tuple instead of a standard tuple.)

  The :mod:`urlparse` module also supports IPv6 literal addresses as defined by
  :rfc:`2732` (contributed by Senthil Kumaran; :issue:`2987`). ::

    >>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
    ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',
                path='/foo', params='', query='', fragment='')

* New class: the :class:`~weakref.WeakSet` class in the :mod:`weakref`
  module is a set that only holds weak references to its elements; elements
  will be removed once there are no references pointing to them.
  (Originally implemented in Python 3.x by Raymond Hettinger, and backported
  to 2.7 by Michael Foord.)

* The ElementTree library, :mod:`xml.etree`, no longer escapes
  ampersands and angle brackets when outputting an XML processing
  instruction (which looks like ``<?xml-stylesheet href="#style1"?>``)
  or comment (which looks like ``<!-- comment -->``).
  (Patch by Neil Muller; :issue:`2746`.)

* The XML-RPC client and server, provided by the :mod:`xmlrpclib` and
  :mod:`SimpleXMLRPCServer` modules, have improved performance by
  supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
  to compress the XML being exchanged.  The gzip compression is
  controlled by the :attr:`encode_threshold` attribute of
  :class:`SimpleXMLRPCRequestHandler`, which contains a size in bytes;
  responses larger than this will be compressed.
  (Contributed by Kristján Valur Jónsson; :issue:`6267`.)

* The :mod:`zipfile` module's :class:`~zipfile.ZipFile` now supports the context
  management protocol, so you can write ``with zipfile.ZipFile(...) as f:``.
  (Contributed by Brian Curtin; :issue:`5511`.)

  :mod:`zipfile` now also supports archiving empty directories and
  extracts them correctly.  (Fixed by Kuba Wieczorek; :issue:`4710`.)
  Reading files out of an archive is faster, and interleaving
  :meth:`~zipfile.ZipFile.read` and :meth:`~zipfile.ZipFile.readline` now works correctly.
  (Contributed by Nir Aides; :issue:`7610`.)

  The :func:`~zipfile.is_zipfile` function now
  accepts a file object, in addition to the path names accepted in earlier
  versions.  (Contributed by Gabriel Genellina; :issue:`4756`.)

  The :meth:`~zipfile.ZipFile.writestr` method now has an optional *compress_type* parameter
  that lets you override the default compression method specified in the
  :class:`~zipfile.ZipFile` constructor.  (Contributed by Ronald Oussoren;
  :issue:`6003`.)


.. ======================================================================
.. whole new modules get described in subsections here


.. _importlib-section:

New module: importlib
------------------------------

Python 3.1 includes the :mod:`importlib` package, a re-implementation
of the logic underlying Python's :keyword:`import` statement.
:mod:`importlib` is useful for implementors of Python interpreters and
to users who wish to write new importers that can participate in the
import process.  Python 2.7 doesn't contain the complete
:mod:`importlib` package, but instead has a tiny subset that contains
a single function, :func:`~importlib.import_module`.

``import_module(name, package=None)`` imports a module.  *name* is
a string containing the module or package's name.  It's possible to do
relative imports by providing a string that begins with a ``.``
character, such as ``..utils.errors``.  For relative imports, the
*package* argument must be provided and is the name of the package that
will be used as the anchor for
the relative import.  :func:`~importlib.import_module` both inserts the imported
module into ``sys.modules`` and returns the module object.

Here are some examples::

    >>> from importlib import import_module
    >>> anydbm = import_module('anydbm')  # Standard absolute import
    >>> anydbm
    <module 'anydbm' from '/p/python/Lib/anydbm.py'>
    >>> # Relative import
    >>> file_util = import_module('..file_util', 'distutils.command')
    >>> file_util
    <module 'distutils.file_util' from '/python/Lib/distutils/file_util.pyc'>

:mod:`importlib` was implemented by Brett Cannon and introduced in
Python 3.1.


New module: sysconfig
---------------------------------

The :mod:`sysconfig` module has been pulled out of the Distutils
package, becoming a new top-level module in its own right.
:mod:`sysconfig` provides functions for getting information about
Python's build process: compiler switches, installation paths, the
platform name, and whether Python is running from its source
directory.

Some of the functions in the module are:

* :func:`~sysconfig.get_config_var` returns variables from Python's
  Makefile and the :file:`pyconfig.h` file.
* :func:`~sysconfig.get_config_vars` returns a dictionary containing
  all of the configuration variables.
* :func:`~sysconfig.get_path` returns the configured path for
  a particular type of module: the standard library,
  site-specific modules, platform-specific modules, etc.
* :func:`~sysconfig.is_python_build` returns true if you're running a
  binary from a Python source tree, and false otherwise.

Consult the :mod:`sysconfig` documentation for more details and for
a complete list of functions.

The Distutils package and :mod:`sysconfig` are now maintained by Tarek
Ziadé, who has also started a Distutils2 package (source repository at
https://hg.python.org/distutils2/) for developing a next-generation
version of Distutils.


ttk: Themed Widgets for Tk
--------------------------

Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
widgets but have a more customizable appearance and can therefore more
closely resemble the native platform's widgets.  This widget
set was originally called Tile, but was renamed to Ttk (for "themed Tk")
on being added to Tcl/Tck release 8.5.

To learn more, read the :mod:`ttk` module documentation.  You may also
wish to read the Tcl/Tk manual page describing the
Ttk theme engine, available at
https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm. Some
screenshots of the Python/Ttk code in use are at
https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki.

The :mod:`ttk` module was written by Guilherme Polo and added in
:issue:`2983`.  An alternate version called ``Tile.py``, written by
Martin Franklin and maintained by Kevin Walzer, was proposed for
inclusion in :issue:`2618`, but the authors argued that Guilherme
Polo's work was more comprehensive.


.. _unittest-section:

Updated module: unittest
---------------------------------

The :mod:`unittest` module was greatly enhanced; many
new features were added.  Most of these features were implemented
by Michael Foord, unless otherwise noted.  The enhanced version of
the module is downloadable separately for use with Python versions 2.4 to 2.6,
packaged as the :mod:`unittest2` package, from
https://pypi.org/project/unittest2.

When used from the command line, the module can automatically discover
tests.  It's not as fancy as `py.test <http://pytest.org>`__ or
`nose <https://nose.readthedocs.io/>`__, but provides a
simple way to run tests kept within a set of package directories.  For example,
the following command will search the :file:`test/` subdirectory for
any importable test files named ``test*.py``::

   python -m unittest discover -s test

Consult the :mod:`unittest` module documentation for more details.
(Developed in :issue:`6001`.)

The :func:`~unittest.main` function supports some other new options:

* :option:`-b <unittest -b>` or :option:`!--buffer` will buffer the standard output
  and standard error streams during each test.  If the test passes,
  any resulting output will be discarded; on failure, the buffered
  output will be displayed.

* :option:`-c <unittest -c>` or :option:`!--catch` will cause the control-C interrupt
  to be handled more gracefully.  Instead of interrupting the test
  process immediately, the currently running test will be completed
  and then the partial results up to the interruption will be reported.
  If you're impatient, a second press of control-C will cause an immediate
  interruption.

  This control-C handler tries to avoid causing problems when the code
  being tested or the tests being run have defined a signal handler of
  their own, by noticing that a signal handler was already set and
  calling it.  If this doesn't work for you, there's a
  :func:`~unittest.removeHandler` decorator that can be used to mark tests that
  should have the control-C handling disabled.

* :option:`-f <unittest -f>` or :option:`!--failfast` makes
  test execution stop immediately when a test fails instead of
  continuing to execute further tests.  (Suggested by Cliff Dyer and
  implemented by Michael Foord; :issue:`8074`.)

The progress messages now show 'x' for expected failures
and 'u' for unexpected successes when run in verbose mode.
(Contributed by Benjamin Peterson.)

Test cases can raise the :exc:`~unittest.SkipTest` exception to skip a
test (:issue:`1034053`).

The error messages for :meth:`~unittest.TestCase.assertEqual`,
:meth:`~unittest.TestCase.assertTrue`, and :meth:`~unittest.TestCase.assertFalse`
failures now provide more information.  If you set the
:attr:`~unittest.TestCase.longMessage` attribute of your :class:`~unittest.TestCase` classes to
true, both the standard error message and any additional message you
provide will be printed for failures.  (Added by Michael Foord; :issue:`5663`.)

The :meth:`~unittest.TestCase.assertRaises` method now
returns a context handler when called without providing a callable
object to run.  For example, you can write this::

  with self.assertRaises(KeyError):
      {}['foo']

(Implemented by Antoine Pitrou; :issue:`4444`.)

.. rev 78774

Module- and class-level setup and teardown fixtures are now supported.
Modules can contain :func:`~unittest.setUpModule` and :func:`~unittest.tearDownModule`
functions.  Classes can have :meth:`~unittest.TestCase.setUpClass` and
:meth:`~unittest.TestCase.tearDownClass` methods that must be defined as class methods
(using ``@classmethod`` or equivalent).  These functions and
methods are invoked when the test runner switches to a test case in a
different module or class.

The methods :meth:`~unittest.TestCase.addCleanup` and
:meth:`~unittest.TestCase.doCleanups` were added.
:meth:`~unittest.TestCase.addCleanup` lets you add cleanup functions that
will be called unconditionally (after :meth:`~unittest.TestCase.setUp` if
:meth:`~unittest.TestCase.setUp` fails, otherwise after :meth:`~unittest.TestCase.tearDown`). This allows
for much simpler resource allocation and deallocation during tests
(:issue:`5679`).

A number of new methods were added that provide more specialized
tests.  Many of these methods were written by Google engineers
for use in their test suites; Gregory P. Smith, Michael Foord, and
GvR worked on merging them into Python's version of :mod:`unittest`.

* :meth:`~unittest.TestCase.assertIsNone` and :meth:`~unittest.TestCase.assertIsNotNone` take one
  expression and verify that the result is or is not ``None``.

* :meth:`~unittest.TestCase.assertIs` and :meth:`~unittest.TestCase.assertIsNot`
  take two values and check whether the two values evaluate to the same object or not.
  (Added by Michael Foord; :issue:`2578`.)

* :meth:`~unittest.TestCase.assertIsInstance` and
  :meth:`~unittest.TestCase.assertNotIsInstance` check whether
  the resulting object is an instance of a particular class, or of
  one of a tuple of classes.  (Added by Georg Brandl; :issue:`7031`.)

* :meth:`~unittest.TestCase.assertGreater`, :meth:`~unittest.TestCase.assertGreaterEqual`,
  :meth:`~unittest.TestCase.assertLess`, and :meth:`~unittest.TestCase.assertLessEqual` compare
  two quantities.

* :meth:`~unittest.TestCase.assertMultiLineEqual` compares two strings, and if they're
  not equal, displays a helpful comparison that highlights the
  differences in the two strings.  This comparison is now used by
  default when Unicode strings are compared with :meth:`~unittest.TestCase.assertEqual`.

* :meth:`~unittest.TestCase.assertRegexpMatches` and
  :meth:`~unittest.TestCase.assertNotRegexpMatches` checks whether the
  first argument is a string matching or not matching the regular
  expression provided as the second argument (:issue:`8038`).

* :meth:`~unittest.TestCase.assertRaisesRegexp` checks whether a particular exception
  is raised, and then also checks that the string representation of
  the exception matches the provided regular expression.

* :meth:`~unittest.TestCase.assertIn` and :meth:`~unittest.TestCase.assertNotIn`
  tests whether *first* is or is not in  *second*.

* :meth:`~unittest.TestCase.assertItemsEqual` tests whether two provided sequences
  contain the same elements.

* :meth:`~unittest.TestCase.assertSetEqual` compares whether two sets are equal, and
  only reports the differences between the sets in case of error.

* Similarly, :meth:`~unittest.TestCase.assertListEqual` and :meth:`~unittest.TestCase.assertTupleEqual`
  compare the specified types and explain any differences without necessarily
  printing their full values; these methods are now used by default
  when comparing lists and tuples using :meth:`~unittest.TestCase.assertEqual`.
  More generally, :meth:`~unittest.TestCase.assertSequenceEqual` compares two sequences
  and can optionally check whether both sequences are of a
  particular type.

* :meth:`~unittest.TestCase.assertDictEqual` compares two dictionaries and reports the
  differences; it's now used by default when you compare two dictionaries
  using :meth:`~unittest.TestCase.assertEqual`.  :meth:`~unittest.TestCase.assertDictContainsSubset` checks whether
  all of the key/value pairs in *first* are found in *second*.

* :meth:`~unittest.TestCase.assertAlmostEqual` and :meth:`~unittest.TestCase.assertNotAlmostEqual` test
  whether *first* and *second* are approximately equal.  This method
  can either round their difference to an optionally-specified number
  of *places* (the default is 7) and compare it to zero, or require
  the difference to be smaller than a supplied *delta* value.

* :meth:`~unittest.TestLoader.loadTestsFromName` properly honors the
  :attr:`~unittest.TestLoader.suiteClass` attribute of
  the :class:`~unittest.TestLoader`. (Fixed by Mark Roddy; :issue:`6866`.)

* A new hook lets you extend the :meth:`~unittest.TestCase.assertEqual` method to handle
  new data types.  The :meth:`~unittest.TestCase.addTypeEqualityFunc` method takes a type
  object and a function. The function will be used when both of the
  objects being compared are of the specified type.  This function
  should compare the two objects and raise an exception if they don't
  match; it's a good idea for the function to provide additional
  information about why the two objects aren't matching, much as the new
  sequence comparison methods do.

:func:`unittest.main` now takes an optional ``exit`` argument.  If
false, :func:`~unittest.main` doesn't call :func:`sys.exit`, allowing
:func:`~unittest.main` to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; :issue:`3379`.)

:class:`~unittest.TestResult` has new :meth:`~unittest.TestResult.startTestRun` and
:meth:`~unittest.TestResult.stopTestRun` methods that are called immediately before
and after a test run.  (Contributed by Robert Collins; :issue:`5728`.)

With all these changes, the :file:`unittest.py` was becoming awkwardly
large, so the module was turned into a package and the code split into
several files (by Benjamin Peterson).  This doesn't affect how the
module is imported or used.

.. seealso::

  http://www.voidspace.org.uk/python/articles/unittest2.shtml
    Describes the new features, how to use them, and the
    rationale for various design decisions.  (By Michael Foord.)

.. _elementtree-section:

Updated module: ElementTree 1.3
---------------------------------

The version of the ElementTree library included with Python was updated to
version 1.3.  Some of the new features are:

* The various parsing functions now take a *parser* keyword argument
  giving an :class:`~xml.etree.ElementTree.XMLParser` instance that will
  be used.  This makes it possible to override the file's internal encoding::

    p = ET.XMLParser(encoding='utf-8')
    t = ET.XML("""<root/>""", parser=p)

  Errors in parsing XML now raise a :exc:`ParseError` exception, whose
  instances have a :attr:`position` attribute
  containing a (*line*, *column*) tuple giving the location of the problem.

* ElementTree's code for converting trees to a string has been
  significantly reworked, making it roughly twice as fast in many
  cases.  The :meth:`ElementTree.write() <xml.etree.ElementTree.ElementTree.write>`
  and :meth:`Element.write` methods now have a *method* parameter that can be
  "xml" (the default), "html", or "text".  HTML mode will output empty
  elements as ``<empty></empty>`` instead of ``<empty/>``, and text
  mode will skip over elements and only output the text chunks.  If
  you set the :attr:`tag` attribute of an element to ``None`` but
  leave its children in place, the element will be omitted when the
  tree is written out, so you don't need to do more extensive rearrangement
  to remove a single element.

  Namespace handling has also been improved.  All ``xmlns:<whatever>``
  declarations are now output on the root element, not scattered throughout
  the resulting XML.  You can set the default namespace for a tree
  by setting the :attr:`default_namespace` attribute and can
  register new prefixes with :meth:`~xml.etree.ElementTree.register_namespace`.  In XML mode,
  you can use the true/false *xml_declaration* parameter to suppress the
  XML declaration.

* New :class:`~xml.etree.ElementTree.Element` method:
  :meth:`~xml.etree.ElementTree.Element.extend` appends the items from a
  sequence to the element's children.  Elements themselves behave like
  sequences, so it's easy to move children from one element to
  another::

    from xml.etree import ElementTree as ET

    t = ET.XML("""<list>
      <item>1</item> <item>2</item>  <item>3</item>
    </list>""")
    new = ET.XML('<root/>')
    new.extend(t)

    # Outputs <root><item>1</item>...</root>
    print ET.tostring(new)

* New :class:`Element` method:
  :meth:`~xml.etree.ElementTree.Element.iter` yields the children of the
  element as a generator.  It's also possible to write ``for child in
  elem:`` to loop over an element's children.  The existing method
  :meth:`getiterator` is now deprecated, as is :meth:`getchildren`
  which constructs and returns a list of children.

* New :class:`Element` method:
  :meth:`~xml.etree.ElementTree.Element.itertext` yields all chunks of
  text that are descendants of the element.  For example::

    t = ET.XML("""<list>
      <item>1</item> <item>2</item>  <item>3</item>
    </list>""")

    # Outputs ['\n  ', '1', ' ', '2', '  ', '3', '\n']
    print list(t.itertext())

* Deprecated: using an element as a Boolean (i.e., ``if elem:``) would
  return true if the element had any children, or false if there were
  no children.  This behaviour is confusing -- ``None`` is false, but
  so is a childless element? -- so it will now trigger a
  :exc:`FutureWarning`.  In your code, you should be explicit: write
  ``len(elem) != 0`` if you're interested in the number of children,
  or ``elem is not None``.

Fredrik Lundh develops ElementTree and produced the 1.3 version;
you can read his article describing 1.3 at
http://effbot.org/zone/elementtree-13-intro.htm.
Florent Xicluna updated the version included with
Python, after discussions on python-dev and in :issue:`6472`.)

.. ======================================================================


Build and C API Changes
=======================

Changes to Python's build process and to the C API include:

* The latest release of the GNU Debugger, GDB 7, can be `scripted
  using Python
  <https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html>`__.
  When you begin debugging an executable program P, GDB will look for
  a file named ``P-gdb.py`` and automatically read it.  Dave Malcolm
  contributed a :file:`python-gdb.py` that adds a number of
  commands useful when debugging Python itself.  For example,
  ``py-up`` and ``py-down`` go up or down one Python stack frame,
  which usually corresponds to several C stack frames.  ``py-print``
  prints the value of a Python variable, and ``py-bt`` prints the
  Python stack trace.  (Added as a result of :issue:`8032`.)

* If you use the :file:`.gdbinit` file provided with Python,
  the "pyo" macro in the 2.7 version now works correctly when the thread being
  debugged doesn't hold the GIL; the macro now acquires it before printing.
  (Contributed by Victor Stinner; :issue:`3632`.)

* :c:func:`Py_AddPendingCall` is now thread-safe, letting any
  worker thread submit notifications to the main Python thread.  This
  is particularly useful for asynchronous IO operations.
  (Contributed by Kristján Valur Jónsson; :issue:`4293`.)

* New function: :c:func:`PyCode_NewEmpty` creates an empty code object;
  only the filename, function name, and first line number are required.
  This is useful for extension modules that are attempting to
  construct a more useful traceback stack.  Previously such
  extensions needed to call :c:func:`PyCode_New`, which had many
  more arguments.  (Added by Jeffrey Yasskin.)

* New function: :c:func:`PyErr_NewExceptionWithDoc` creates a new
  exception class, just as the existing :c:func:`PyErr_NewException` does,
  but takes an extra ``char *`` argument containing the docstring for the
  new exception class.  (Added by 'lekma' on the Python bug tracker;
  :issue:`7033`.)

* New function: :c:func:`PyFrame_GetLineNumber` takes a frame object
  and returns the line number that the frame is currently executing.
  Previously code would need to get the index of the bytecode
  instruction currently executing, and then look up the line number
  corresponding to that address.  (Added by Jeffrey Yasskin.)

* New functions: :c:func:`PyLong_AsLongAndOverflow` and
  :c:func:`PyLong_AsLongLongAndOverflow`  approximates a Python long
  integer as a C :c:type:`long` or :c:type:`long long`.
  If the number is too large to fit into
  the output type, an *overflow* flag is set and returned to the caller.
  (Contributed by Case Van Horsen; :issue:`7528` and :issue:`7767`.)

* New function: stemming from the rewrite of string-to-float conversion,
  a new :c:func:`PyOS_string_to_double` function was added.  The old
  :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions
  are now deprecated.

* New function: :c:func:`PySys_SetArgvEx` sets the value of
  ``sys.argv`` and can optionally update ``sys.path`` to include the
  directory containing the script named by ``sys.argv[0]`` depending
  on the value of an *updatepath* parameter.

  This function was added to close a security hole for applications
  that embed Python.  The old function, :c:func:`PySys_SetArgv`, would
  always update ``sys.path``, and sometimes it would add the current
  directory.  This meant that, if you ran an application embedding
  Python in a directory controlled by someone else, attackers could
  put a Trojan-horse module in the directory (say, a file named
  :file:`os.py`) that your application would then import and run.

  If you maintain a C/C++ application that embeds Python, check
  whether you're calling :c:func:`PySys_SetArgv` and carefully consider
  whether the application should be using :c:func:`PySys_SetArgvEx`
  with *updatepath* set to false.

  Security issue reported as `CVE-2008-5983
  <https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_;
  discussed in :issue:`5753`, and fixed by Antoine Pitrou.

* New macros: the Python header files now define the following macros:
  :c:macro:`Py_ISALNUM`,
  :c:macro:`Py_ISALPHA`,
  :c:macro:`Py_ISDIGIT`,
  :c:macro:`Py_ISLOWER`,
  :c:macro:`Py_ISSPACE`,
  :c:macro:`Py_ISUPPER`,
  :c:macro:`Py_ISXDIGIT`,
  :c:macro:`Py_TOLOWER`, and :c:macro:`Py_TOUPPER`.
  All of these functions are analogous to the C
  standard macros for classifying characters, but ignore the current
  locale setting, because in
  several places Python needs to analyze characters in a
  locale-independent way.  (Added by Eric Smith;
  :issue:`5793`.)

  .. XXX these macros don't seem to be described in the c-api docs.

* Removed function: :c:macro:`PyEval_CallObject` is now only available
  as a macro.  A function version was being kept around to preserve
  ABI linking compatibility, but that was in 1997; it can certainly be
  deleted by now.  (Removed by Antoine Pitrou; :issue:`8276`.)

* New format codes: the :c:func:`PyFormat_FromString`,
  :c:func:`PyFormat_FromStringV`, and :c:func:`PyErr_Format` functions now
  accept ``%lld`` and ``%llu`` format codes for displaying
  C's :c:type:`long long` types.
  (Contributed by Mark Dickinson; :issue:`7228`.)

* The complicated interaction between threads and process forking has
  been changed.  Previously, the child process created by
  :func:`os.fork` might fail because the child is created with only a
  single thread running, the thread performing the :func:`os.fork`.
  If other threads were holding a lock, such as Python's import lock,
  when the fork was performed, the lock would still be marked as
  "held" in the new process.  But in the child process nothing would
  ever release the lock, since the other threads weren't replicated,
  and the child process would no longer be able to perform imports.

  Python 2.7 acquires the import lock before performing an
  :func:`os.fork`, and will also clean up any locks created using the
  :mod:`threading` module.  C extension modules that have internal
  locks, or that call :c:func:`fork()` themselves, will not benefit
  from this clean-up.

  (Fixed by Thomas Wouters; :issue:`1590864`.)

* The :c:func:`Py_Finalize` function now calls the internal
  :func:`threading._shutdown` function; this prevents some exceptions from
  being raised when an interpreter shuts down.
  (Patch by Adam Olsen; :issue:`1722344`.)

* When using the :c:type:`PyMemberDef` structure to define attributes
  of a type, Python will no longer let you try to delete or set a
  :const:`T_STRING_INPLACE` attribute.

  .. rev 79644

* Global symbols defined by the :mod:`ctypes` module are now prefixed
  with ``Py``, or with ``_ctypes``.  (Implemented by Thomas
  Heller; :issue:`3102`.)

* New configure option: the :option:`!--with-system-expat` switch allows
  building the :mod:`pyexpat` module to use the system Expat library.
  (Contributed by Arfrever Frehtes Taifersar Arahesis; :issue:`7609`.)

* New configure option: the
  :option:`!--with-valgrind` option will now disable the pymalloc
  allocator, which is difficult for the Valgrind memory-error detector
  to analyze correctly.
  Valgrind will therefore be better at detecting memory leaks and
  overruns. (Contributed by James Henstridge; :issue:`2422`.)

* New configure option: you can now supply an empty string to
  :option:`!--with-dbmliborder=` in order to disable all of the various
  DBM modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
  :issue:`6491`.)

* The :program:`configure` script now checks for floating-point rounding bugs
  on certain 32-bit Intel chips and defines a :c:macro:`X87_DOUBLE_ROUNDING`
  preprocessor definition.  No code currently uses this definition,
  but it's available if anyone wishes to use it.
  (Added by Mark Dickinson; :issue:`2937`.)

  :program:`configure` also now sets a :envvar:`LDCXXSHARED` Makefile
  variable for supporting C++ linking.  (Contributed by Arfrever
  Frehtes Taifersar Arahesis; :issue:`1222585`.)

* The build process now creates the necessary files for pkg-config
  support.  (Contributed by Clinton Roy; :issue:`3585`.)

* The build process now supports Subversion 1.7.  (Contributed by
  Arfrever Frehtes Taifersar Arahesis; :issue:`6094`.)


.. _whatsnew27-capsules:

Capsules
-------------------

Python 3.1 adds a new C datatype, :c:type:`PyCapsule`, for providing a
C API to an extension module.  A capsule is essentially the holder of
a C ``void *`` pointer, and is made available as a module attribute; for
example, the :mod:`socket` module's API is exposed as ``socket.CAPI``,
and :mod:`unicodedata` exposes ``ucnhash_CAPI``.  Other extensions
can import the module, access its dictionary to get the capsule
object, and then get the ``void *`` pointer, which will usually point
to an array of pointers to the module's various API functions.

There is an existing data type already used for this,
:c:type:`PyCObject`, but it doesn't provide type safety.  Evil code
written in pure Python could cause a segmentation fault by taking a
:c:type:`PyCObject` from module A and somehow substituting it for the
:c:type:`PyCObject` in module B.   Capsules know their own name,
and getting the pointer requires providing the name:

.. code-block:: c

   void *vtable;

   if (!PyCapsule_IsValid(capsule, "mymodule.CAPI") {
           PyErr_SetString(PyExc_ValueError, "argument type invalid");
           return NULL;
   }

   vtable = PyCapsule_GetPointer(capsule, "mymodule.CAPI");

You are assured that ``vtable`` points to whatever you're expecting.
If a different capsule was passed in, :c:func:`PyCapsule_IsValid` would
detect the mismatched name and return false.  Refer to
:ref:`using-capsules` for more information on using these objects.

Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the :c:func:`PyCObject_AsVoidPtr` was
modified to handle capsules, preserving compile-time compatibility
with the :c:type:`CObject` interface.  Use of
:c:func:`PyCObject_AsVoidPtr` will signal a
:exc:`PendingDeprecationWarning`, which is silent by default.

Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in :issue:`5630`.


.. ======================================================================

Port-Specific Changes: Windows
-----------------------------------

* The :mod:`msvcrt` module now contains some constants from
  the :file:`crtassem.h` header file:
  :data:`CRT_ASSEMBLY_VERSION`,
  :data:`VC_ASSEMBLY_PUBLICKEYTOKEN`,
  and :data:`LIBRARIES_ASSEMBLY_NAME_PREFIX`.
  (Contributed by David Cournapeau; :issue:`4365`.)

* The :mod:`_winreg` module for accessing the registry now implements
  the :func:`~_winreg.CreateKeyEx` and :func:`~_winreg.DeleteKeyEx`
  functions, extended versions of previously-supported functions that
  take several extra arguments.  The :func:`~_winreg.DisableReflectionKey`,
  :func:`~_winreg.EnableReflectionKey`, and :func:`~_winreg.QueryReflectionKey`
  were also tested and documented.
  (Implemented by Brian Curtin: :issue:`7347`.)

* The new :c:func:`_beginthreadex` API is used to start threads, and
  the native thread-local storage functions are now used.
  (Contributed by Kristján Valur Jónsson; :issue:`3582`.)

* The :func:`os.kill` function now works on Windows.  The signal value
  can be the constants :const:`CTRL_C_EVENT`,
  :const:`CTRL_BREAK_EVENT`, or any integer.  The first two constants
  will send :kbd:`Control-C` and :kbd:`Control-Break` keystroke events to
  subprocesses; any other value will use the :c:func:`TerminateProcess`
  API.  (Contributed by Miki Tebeka; :issue:`1220212`.)

* The :func:`os.listdir` function now correctly fails
  for an empty path.  (Fixed by Hirokazu Yamamoto; :issue:`5913`.)

* The :mod:`mimelib` module will now read the MIME database from
  the Windows registry when initializing.
  (Patch by Gabriel Genellina; :issue:`4969`.)

.. ======================================================================

Port-Specific Changes: Mac OS X
-----------------------------------

* The path ``/Library/Python/2.7/site-packages`` is now appended to
  ``sys.path``, in order to share added packages between the system
  installation and a user-installed copy of the same version.
  (Changed by Ronald Oussoren; :issue:`4865`.)

   .. versionchanged:: 2.7.13

     As of 2.7.13, this change was removed.
     ``/Library/Python/2.7/site-packages``, the site-packages directory
     used by the Apple-supplied system Python 2.7 is no longer appended to
     ``sys.path`` for user-installed Pythons such as from the python.org
     installers.  As of macOS 10.12, Apple changed how the system
     site-packages directory is configured, which could cause installation
     of pip components, like setuptools, to fail.  Packages installed for
     the system Python will no longer be shared with user-installed
     Pythons. (:issue:`28440`)

Port-Specific Changes: FreeBSD
-----------------------------------

* FreeBSD 7.1's :const:`SO_SETFIB` constant, used with
  :func:`~socket.getsockopt`/:func:`~socket.setsockopt` to select an
  alternate routing table, is now available in the :mod:`socket`
  module.  (Added by Kyle VanderBeek; :issue:`8235`.)

Other Changes and Fixes
=======================

* Two benchmark scripts, :file:`iobench` and :file:`ccbench`, were
  added to the :file:`Tools` directory.  :file:`iobench` measures the
  speed of the built-in file I/O objects returned by :func:`open`
  while performing various operations, and :file:`ccbench` is a
  concurrency benchmark that tries to measure computing throughput,
  thread switching latency, and IO processing bandwidth when
  performing several tasks using a varying number of threads.

* The :file:`Tools/i18n/msgfmt.py` script now understands plural
  forms in :file:`.po` files.  (Fixed by Martin von Löwis;
  :issue:`5464`.)

* When importing a module from a :file:`.pyc` or :file:`.pyo` file
  with an existing :file:`.py` counterpart, the :attr:`co_filename`
  attributes of the resulting code objects are overwritten when the
  original filename is obsolete.  This can happen if the file has been
  renamed, moved, or is accessed through different paths.  (Patch by
  Ziga Seilnacht and Jean-Paul Calderone; :issue:`1180193`.)

* The :file:`regrtest.py` script now takes a :option:`!--randseed=`
  switch that takes an integer that will be used as the random seed
  for the :option:`!-r` option that executes tests in random order.
  The :option:`!-r` option also reports the seed that was used
  (Added by Collin Winter.)

* Another :file:`regrtest.py` switch is :option:`!-j`, which
  takes an integer specifying how many tests run in parallel. This
  allows reducing the total runtime on multi-core machines.
  This option is compatible with several other options, including the
  :option:`!-R` switch which is known to produce long runtimes.
  (Added by Antoine Pitrou, :issue:`6152`.)  This can also be used
  with a new :option:`!-F` switch that runs selected tests in a loop
  until they fail.  (Added by Antoine Pitrou; :issue:`7312`.)

* When executed as a script, the :file:`py_compile.py` module now
  accepts ``'-'`` as an argument, which will read standard input for
  the list of filenames to be compiled.  (Contributed by Piotr
  Ożarowski; :issue:`8233`.)

.. ======================================================================

Porting to Python 2.7
=====================

This section lists previously described changes and other bugfixes
that may require changes to your code:

* The :func:`range` function processes its arguments more
  consistently; it will now call :meth:`__int__` on non-float,
  non-integer arguments that are supplied to it.  (Fixed by Alexander
  Belopolsky; :issue:`1533`.)

* The string :meth:`format` method changed the default precision used
  for floating-point and complex numbers from 6 decimal
  places to 12, which matches the precision used by :func:`str`.
  (Changed by Eric Smith; :issue:`5920`.)

* Because of an optimization for the :keyword:`with` statement, the special
  methods :meth:`__enter__` and :meth:`__exit__` must belong to the object's
  type, and cannot be directly attached to the object's instance.  This
  affects new-style classes (derived from :class:`object`) and C extension
  types.  (:issue:`6101`.)

* Due to a bug in Python 2.6, the *exc_value* parameter to
  :meth:`__exit__` methods was often the string representation of the
  exception, not an instance.  This was fixed in 2.7, so *exc_value*
  will be an instance as expected.  (Fixed by Florent Xicluna;
  :issue:`7853`.)

* When a restricted set of attributes were set using ``__slots__``,
  deleting an unset attribute would not raise :exc:`AttributeError`
  as you would expect.  Fixed by Benjamin Peterson; :issue:`7604`.)

In the standard library:

* Operations with :class:`~datetime.datetime` instances that resulted in a year
  falling outside the supported range didn't always raise
  :exc:`OverflowError`.  Such errors are now checked more carefully
  and will now raise the exception. (Reported by Mark Leander, patch
  by Anand B. Pillai and Alexander Belopolsky; :issue:`7150`.)

* When using :class:`~decimal.Decimal` instances with a string's
  :meth:`format` method, the default alignment was previously
  left-alignment.  This has been changed to right-alignment, which might
  change the output of your programs.
  (Changed by Mark Dickinson; :issue:`6857`.)

  Comparisons involving a signaling NaN value (or ``sNAN``) now signal
  :const:`~decimal.InvalidOperation` instead of silently returning a true or
  false value depending on the comparison operator.  Quiet NaN values
  (or ``NaN``) are now hashable.  (Fixed by Mark Dickinson;
  :issue:`7279`.)

* The ElementTree library, :mod:`xml.etree`, no longer escapes
  ampersands and angle brackets when outputting an XML processing
  instruction (which looks like `<?xml-stylesheet href="#style1"?>`)
  or comment (which looks like `<!-- comment -->`).
  (Patch by Neil Muller; :issue:`2746`.)

* The :meth:`~StringIO.StringIO.readline` method of :class:`~StringIO.StringIO` objects now does
  nothing when a negative length is requested, as other file-like
  objects do.  (:issue:`7348`).

* The :mod:`syslog` module will now use the value of ``sys.argv[0]`` as the
  identifier instead of the previous default value of ``'python'``.
  (Changed by Sean Reifschneider; :issue:`8451`.)

* The :mod:`tarfile` module's default error handling has changed, to
  no longer suppress fatal errors.  The default error level was previously 0,
  which meant that errors would only result in a message being written to the
  debug log, but because the debug log is not activated by default,
  these errors go unnoticed.  The default error level is now 1,
  which raises an exception if there's an error.
  (Changed by Lars Gustäbel; :issue:`7357`.)

* The :mod:`urlparse` module's :func:`~urlparse.urlsplit` now handles
  unknown URL schemes in a fashion compliant with :rfc:`3986`: if the
  URL is of the form ``"<something>://..."``, the text before the
  ``://`` is treated as the scheme, even if it's a made-up scheme that
  the module doesn't know about.  This change may break code that
  worked around the old behaviour.  For example, Python 2.6.4 or 2.5
  will return the following:

    >>> import urlparse
    >>> urlparse.urlsplit('invented://host/filename?query')
    ('invented', '', '//host/filename?query', '', '')

  Python 2.7 (and Python 2.6.5) will return:

    >>> import urlparse
    >>> urlparse.urlsplit('invented://host/filename?query')
    ('invented', 'host', '/filename?query', '', '')

  (Python 2.7 actually produces slightly different output, since it
  returns a named tuple instead of a standard tuple.)

For C extensions:

* C extensions that use integer format codes with the ``PyArg_Parse*``
  family of functions will now raise a :exc:`TypeError` exception
  instead of triggering a :exc:`DeprecationWarning` (:issue:`5080`).

* Use the new :c:func:`PyOS_string_to_double` function instead of the old
  :c:func:`PyOS_ascii_strtod` and :c:func:`PyOS_ascii_atof` functions,
  which are now deprecated.

For applications that embed Python:

* The :c:func:`PySys_SetArgvEx` function was added, letting
  applications close a security hole when the existing
  :c:func:`PySys_SetArgv` function was used.  Check whether you're
  calling :c:func:`PySys_SetArgv` and carefully consider whether the
  application should be using :c:func:`PySys_SetArgvEx` with
  *updatepath* set to false.

.. ======================================================================


.. _py27-maintenance-enhancements:

New Features Added to Python 2.7 Maintenance Releases
=====================================================

New features may be added to Python 2.7 maintenance releases when the
situation genuinely calls for it. Any such additions must go through
the Python Enhancement Proposal process, and make a compelling case for why
they can't be adequately addressed by either adding the new feature solely to
Python 3, or else by publishing it on the Python Package Index.

In addition to the specific proposals listed below, there is a general
exemption allowing new ``-3`` warnings to be added in any Python 2.7
maintenance release.


Two new environment variables for debug mode
--------------------------------------------

In debug mode, the ``[xxx refs]`` statistic is not written by default, the
:envvar:`PYTHONSHOWREFCOUNT` environment variable now must also be set.
(Contributed by Victor Stinner; :issue:`31733`.)

When Python is compiled with ``COUNT_ALLOC`` defined, allocation counts are no
longer dumped by default anymore: the :envvar:`PYTHONSHOWALLOCCOUNT` environment
variable must now also be set. Moreover, allocation counts are now dumped into
stderr, rather than stdout. (Contributed by Victor Stinner; :issue:`31692`.)

.. versionadded:: 2.7.15


PEP 434: IDLE Enhancement Exception for All Branches
----------------------------------------------------

:pep:`434` describes a general exemption for changes made to the IDLE
development environment shipped along with Python. This exemption makes it
possible for the IDLE developers to provide a more consistent user
experience across all supported versions of Python 2 and 3.

For details of any IDLE changes, refer to the NEWS file for the specific
release.


PEP 466: Network Security Enhancements for Python 2.7
-----------------------------------------------------

:pep:`466` describes a number of network security enhancement proposals
that have been approved for inclusion in Python 2.7 maintenance releases,
with the first of those changes appearing in the Python 2.7.7 release.

:pep:`466` related features added in Python 2.7.7:

* :func:`hmac.compare_digest` was backported from Python 3 to make a timing
  attack resistant comparison operation available to Python 2 applications.
  (Contributed by Alex Gaynor; :issue:`21306`.)

* OpenSSL 1.0.1g was upgraded in the official Windows installers published on
  python.org. (Contributed by Zachary Ware; :issue:`21462`.)

:pep:`466` related features added in Python 2.7.8:

* :func:`hashlib.pbkdf2_hmac` was backported from Python 3 to make a hashing
  algorithm suitable for secure password storage broadly available to Python
  2 applications. (Contributed by Alex Gaynor; :issue:`21304`.)

* OpenSSL 1.0.1h was upgraded for the official Windows installers published on
  python.org. (contributed by Zachary Ware in :issue:`21671` for CVE-2014-0224)

:pep:`466` related features added in Python 2.7.9:

* Most of Python 3.4's :mod:`ssl` module was backported. This means :mod:`ssl`
  now supports Server Name Indication, TLS1.x settings, access to the platform
  certificate store, the :class:`~ssl.SSLContext` class, and other
  features. (Contributed by Alex Gaynor and David Reid; :issue:`21308`.)

  Refer to the "Version added: 2.7.9" notes in the module documentation for
  specific details.

* :func:`os.urandom` was changed to cache a file descriptor to ``/dev/urandom``
  instead of reopening ``/dev/urandom`` on every call. (Contributed by Alex
  Gaynor; :issue:`21305`.)

* :data:`hashlib.algorithms_guaranteed` and
  :data:`hashlib.algorithms_available` were backported from Python 3 to make
  it easier for Python 2 applications to select the strongest available hash
  algorithm. (Contributed by Alex Gaynor in :issue:`21307`)


PEP 477: Backport ensurepip (PEP 453) to Python 2.7
---------------------------------------------------

:pep:`477` approves the inclusion of the :pep:`453` ensurepip module and the
improved documentation that was enabled by it in the Python 2.7 maintenance
releases, appearing first in the Python 2.7.9 release.


Bootstrapping pip By Default
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The new :mod:`ensurepip` module (defined in :pep:`453`) provides a standard
cross-platform mechanism to bootstrap the pip installer into Python
installations. The version of ``pip`` included with Python 2.7.9 is ``pip``
1.5.6, and future 2.7.x maintenance releases will update the bundled version to
the latest version of ``pip`` that is available at the time of creating the
release candidate.

By default, the commands ``pip``, ``pipX`` and ``pipX.Y`` will be installed on
all platforms (where X.Y stands for the version of the Python installation),
along with the ``pip`` Python package and its dependencies.

For CPython :ref:`source builds on POSIX systems <building-python-on-unix>`,
the ``make install`` and ``make altinstall`` commands do not bootstrap ``pip``
by default.  This behaviour can be controlled through configure options, and
overridden through Makefile options.

On Windows and Mac OS X, the CPython installers now default to installing
``pip`` along with CPython itself (users may opt out of installing it
during the installation process). Window users will need to opt in to the
automatic ``PATH`` modifications to have ``pip`` available from the command
line by default, otherwise it can still be accessed through the Python
launcher for Windows as ``py -m pip``.

As `discussed in the PEP`__, platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).

__ https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors


Documentation Changes
~~~~~~~~~~~~~~~~~~~~~

As part of this change, the :ref:`installing-index` and
:ref:`distributing-index` sections of the documentation have been
completely redesigned as short getting started and FAQ documents. Most
packaging documentation has now been moved out to the Python Packaging
Authority maintained `Python Packaging User Guide
<http://packaging.python.org>`__ and the documentation of the individual
projects.

However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as :ref:`install-index`
and :ref:`distutils-index`.

.. seealso::

   :pep:`453` -- Explicit bootstrapping of pip in Python installations
      PEP written by Donald Stufft and Nick Coghlan, implemented by
      Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.

PEP 476: Enabling certificate verification by default for stdlib http clients
-----------------------------------------------------------------------------

:pep:`476` updated :mod:`httplib` and modules which use it, such as
:mod:`urllib2` and :mod:`xmlrpclib`, to now verify that the server
presents a certificate which is signed by a Certificate Authority in the
platform trust store and whose hostname matches the hostname being requested
by default, significantly improving security for many applications. This
change was made in the Python 2.7.9 release.

For applications which require the old previous behavior, they can pass an
alternate context::

    import urllib2
    import ssl

    # This disables all verification
    context = ssl._create_unverified_context()

    # This allows using a specific certificate for the host, which doesn't need
    # to be in the trust store
    context = ssl.create_default_context(cafile="/path/to/file.crt")

    urllib2.urlopen("https://invalid-cert", context=context)


PEP 493: HTTPS verification migration tools for Python 2.7
----------------------------------------------------------

:pep:`493` provides additional migration tools to support a more incremental
infrastructure upgrade process for environments containing applications and
services relying on the historically permissive processing of server
certificates when establishing client HTTPS connections.  These additions were
made in the Python 2.7.12 release.

These tools are intended for use in cases where affected applications and
services can't be modified to explicitly pass a more permissive SSL context
when establishing the connection.

For applications and services which can't be modified at all, the new
``PYTHONHTTPSVERIFY`` environment variable may be set to ``0`` to revert an
entire Python process back to the default permissive behaviour of Python 2.7.8
and earlier.

For cases where the connection establishment code can't be modified, but the
overall application can be, the new :func:`ssl._https_verify_certificates`
function can be used to adjust the default behaviour at runtime.


New ``make regen-all`` build target
-----------------------------------

To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.

Instead, a new ``make regen-all`` command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).

More selective regeneration targets are also defined - see
:source:`Makefile.pre.in` for details.

(Contributed by Victor Stinner in :issue:`23404`.)

.. versionadded:: 2.7.14


Removal of ``make touch`` build target
--------------------------------------

The ``make touch`` build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.

It has been replaced by the new ``make regen-all`` target.

(Contributed by Victor Stinner in :issue:`23404`.)

.. versionchanged:: 2.7.14

.. ======================================================================

.. _acks27:

Acknowledgements
================

The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
Hugh Secker-Walker.
PK
%�\U����$html/_sources/whatsnew/index.rst.txtnu�[���.. _whatsnew-index:

######################
 What's New in Python
######################

The "What's New in Python" series of essays takes tours through the most
important changes between major Python versions.  They are a "must read" for
anyone wishing to stay up-to-date after a new release.

.. toctree::
   :maxdepth: 2

   2.7.rst
   2.6.rst
   2.5.rst
   2.4.rst
   2.3.rst
   2.2.rst
   2.1.rst
   2.0.rst
PK
%�\~7����html/_sources/about.rst.txtnu�[���=====================
About these documents
=====================


These documents are generated from `reStructuredText`_ sources by `Sphinx`_, a
document processor specifically written for the Python documentation.

.. _reStructuredText: http://docutils.sourceforge.net/rst.html
.. _Sphinx: http://sphinx-doc.org/

.. In the online version of these documents, you can submit comments and suggest
   changes directly on the documentation pages.

Development of the documentation and its toolchain is an entirely volunteer
effort, just like Python itself.  If you want to contribute, please take a
look at the :ref:`reporting-bugs` page for information on how to do so.  New
volunteers are always welcome!

Many thanks go to:

* Fred L. Drake, Jr., the creator of the original Python documentation toolset
  and writer of much of the content;
* the `Docutils <http://docutils.sourceforge.net/>`_ project for creating
  reStructuredText and the Docutils suite;
* Fredrik Lundh for his `Alternative Python Reference
  <http://effbot.org/zone/pyref.htm>`_ project from which Sphinx got many good
  ideas.


Contributors to the Python Documentation
----------------------------------------

Many people have contributed to the Python language, the Python standard
library, and the Python documentation.  See :source:`Misc/ACKS` in the Python
source distribution for a partial list of contributors.

It is only with the input and contributions of the Python community
that Python has such wonderful documentation -- Thank You!
PK
%�\ �@�html/_sources/bugs.rst.txtnu�[���.. _reporting-bugs:

**************
Reporting Bugs
**************

Python is a mature programming language which has established a reputation for
stability.  In order to maintain this reputation, the developers would like to
know of any deficiencies you find in Python.


Documentation bugs
==================

If you find a bug in this documentation or would like to propose an improvement,
please submit a bug report on the :ref:`tracker <using-the-tracker>`.  If you
have a suggestion on how to fix it, include that as well.

If you're short on time, you can also email documentation bug reports to
docs@python.org (behavioral bugs can be sent to python-list@python.org).
'docs@' is a mailing list run by volunteers; your request will be noticed,
though it may take a while to be processed.

.. seealso::
   `Documentation bugs`_ on the Python issue tracker

.. _using-the-tracker:

Using the Python issue tracker
==============================

Bug reports for Python itself should be submitted via the Python Bug Tracker
(https://bugs.python.org/).  The bug tracker offers a Web form which allows
pertinent information to be entered and submitted to the developers.

The first step in filing a report is to determine whether the problem has
already been reported.  The advantage in doing so, aside from saving the
developers time, is that you learn what has been done to fix it; it may be that
the problem has already been fixed for the next release, or additional
information is needed (in which case you are welcome to provide it if you can!).
To do this, search the bug database using the search box on the top of the page.

If the problem you're reporting is not already in the bug tracker, go back to
the Python Bug Tracker and log in.  If you don't already have a tracker account,
select the "Register" link or, if you use OpenID, one of the OpenID provider
logos in the sidebar.  It is not possible to submit a bug report anonymously.

Being now logged in, you can submit a bug.  Select the "Create New" link in the
sidebar to open the bug reporting form.

The submission form has a number of fields.  For the "Title" field, enter a
*very* short description of the problem; less than ten words is good.  In the
"Type" field, select the type of your problem; also select the "Component" and
"Versions" to which the bug relates.

In the "Comment" field, describe the problem in detail, including what you
expected to happen and what did happen.  Be sure to include whether any
extension modules were involved, and what hardware and software platform you
were using (including version information as appropriate).

Each bug report will be assigned to a developer who will determine what needs to
be done to correct the problem.  You will receive an update each time action is
taken on the bug.


.. seealso::

   `How to Report Bugs Effectively <http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>`_
      Article which goes into some detail about how to create a useful bug report.
      This describes what kind of information is useful and why it is useful.

   `Bug Writing Guidelines <https://developer.mozilla.org/en-US/docs/Mozilla/QA/Bug_writing_guidelines>`_
      Information about writing a good bug report.  Some of this is specific to the
      Mozilla project, but describes general good practices.


Getting started contributing to Python yourself
===============================================

Beyond just reporting bugs that you find, you are also welcome to submit
patches to fix them.  You can find more information on how to get started
patching Python in the `Python Developer's Guide`_.  If you have questions,
the `core-mentorship mailing list`_ is a friendly place to get answers to
any and all questions pertaining to the process of fixing issues in Python.

.. _Documentation bugs: https://bugs.python.org/issue?@filter=status&@filter=components&components=4&status=1&@columns=id,activity,title,status&@sort=-activity
.. _Python Developer's Guide: https://devguide.python.org/
.. _core-mentorship mailing list: https://mail.python.org/mailman3/lists/core-mentorship.python.org/
PK
%�\�oLhtml/_sources/contents.rst.txtnu�[���%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 Python Documentation contents
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

.. toctree::

   whatsnew/index.rst
   tutorial/index.rst
   using/index.rst
   reference/index.rst
   library/index.rst
   extending/index.rst
   c-api/index.rst
   distributing/index.rst
   installing/index.rst
   howto/index.rst
   faq/index.rst
   glossary.rst

   about.rst
   bugs.rst
   copyright.rst
   license.rst

.. to include legacy packaging docs in build

.. toctree::
   :hidden:

   distutils/index.rst
   install/index.rst
PK
%�\˗���html/_sources/copyright.rst.txtnu�[���*********
Copyright
*********

Python and this documentation is:

Copyright © 2001-2019 Python Software Foundation. All rights reserved.

Copyright © 2000 BeOpen.com. All rights reserved.

Copyright © 1995-2000 Corporation for National Research Initiatives. All rights
reserved.

Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.

-------

See :ref:`history-and-license` for complete license and permissions information.

PK
%�\�WV���html/_sources/glossary.rst.txtnu�[���.. _glossary:

********
Glossary
********

.. if you add new entries, keep the alphabetical sorting!

.. glossary::

   ``>>>``
      The default Python prompt of the interactive shell.  Often seen for code
      examples which can be executed interactively in the interpreter.

   ``...``
      The default Python prompt of the interactive shell when entering code for
      an indented code block, when within a pair of matching left and right
      delimiters (parentheses, square brackets, curly braces or triple quotes),
      or after specifying a decorator.

   2to3
      A tool that tries to convert Python 2.x code to Python 3.x code by
      handling most of the incompatibilities which can be detected by parsing the
      source and traversing the parse tree.

      2to3 is available in the standard library as :mod:`lib2to3`; a standalone
      entry point is provided as :file:`Tools/scripts/2to3`.  See
      :ref:`2to3-reference`.

   abstract base class
      Abstract base classes complement :term:`duck-typing` by
      providing a way to define interfaces when other techniques like
      :func:`hasattr` would be clumsy or subtly wrong (for example with
      :ref:`magic methods <new-style-special-lookup>`).  ABCs introduce virtual
      subclasses, which are classes that don't inherit from a class but are
      still recognized by :func:`isinstance` and :func:`issubclass`; see the
      :mod:`abc` module documentation.  Python comes with many built-in ABCs for
      data structures (in the :mod:`collections` module), numbers (in the
      :mod:`numbers` module), and streams (in the :mod:`io` module). You can
      create your own ABCs with the :mod:`abc` module.

   argument
      A value passed to a :term:`function` (or :term:`method`) when calling the
      function.  There are two types of arguments:

      * :dfn:`keyword argument`: an argument preceded by an identifier (e.g.
        ``name=``) in a function call or passed as a value in a dictionary
        preceded by ``**``.  For example, ``3`` and ``5`` are both keyword
        arguments in the following calls to :func:`complex`::

           complex(real=3, imag=5)
           complex(**{'real': 3, 'imag': 5})

      * :dfn:`positional argument`: an argument that is not a keyword argument.
        Positional arguments can appear at the beginning of an argument list
        and/or be passed as elements of an :term:`iterable` preceded by ``*``.
        For example, ``3`` and ``5`` are both positional arguments in the
        following calls::

           complex(3, 5)
           complex(*(3, 5))

      Arguments are assigned to the named local variables in a function body.
      See the :ref:`calls` section for the rules governing this assignment.
      Syntactically, any expression can be used to represent an argument; the
      evaluated value is assigned to the local variable.

      See also the :term:`parameter` glossary entry and the FAQ question on
      :ref:`the difference between arguments and parameters
      <faq-argument-vs-parameter>`.

   attribute
      A value associated with an object which is referenced by name using
      dotted expressions.  For example, if an object *o* has an attribute
      *a* it would be referenced as *o.a*.

   BDFL
      Benevolent Dictator For Life, a.k.a. `Guido van Rossum
      <https://www.python.org/~guido/>`_, Python's creator.

   bytes-like object
      An object that supports the :ref:`buffer protocol <bufferobjects>`,
      like :class:`str`, :class:`bytearray` or :class:`memoryview`.
      Bytes-like objects can be used for various operations that expect
      binary data, such as compression, saving to a binary file or sending
      over a socket. Some operations need the binary data to be mutable,
      in which case not all bytes-like objects can apply.

   bytecode
      Python source code is compiled into bytecode, the internal representation
      of a Python program in the CPython interpreter.  The bytecode is also
      cached in ``.pyc`` and ``.pyo`` files so that executing the same file is
      faster the second time (recompilation from source to bytecode can be
      avoided).  This "intermediate language" is said to run on a
      :term:`virtual machine` that executes the machine code corresponding to
      each bytecode. Do note that bytecodes are not expected to work between
      different Python virtual machines, nor to be stable between Python
      releases.

      A list of bytecode instructions can be found in the documentation for
      :ref:`the dis module <bytecodes>`.

   class
      A template for creating user-defined objects. Class definitions
      normally contain method definitions which operate on instances of the
      class.

   classic class
      Any class which does not inherit from :class:`object`.  See
      :term:`new-style class`.  Classic classes have been removed in Python 3.

   coercion
      The implicit conversion of an instance of one type to another during an
      operation which involves two arguments of the same type.  For example,
      ``int(3.15)`` converts the floating point number to the integer ``3``, but
      in ``3+4.5``, each argument is of a different type (one int, one float),
      and both must be converted to the same type before they can be added or it
      will raise a ``TypeError``.  Coercion between two operands can be
      performed with the ``coerce`` built-in function; thus, ``3+4.5`` is
      equivalent to calling ``operator.add(*coerce(3, 4.5))`` and results in
      ``operator.add(3.0, 4.5)``.  Without coercion, all arguments of even
      compatible types would have to be normalized to the same value by the
      programmer, e.g., ``float(3)+4.5`` rather than just ``3+4.5``.

   complex number
      An extension of the familiar real number system in which all numbers are
      expressed as a sum of a real part and an imaginary part.  Imaginary
      numbers are real multiples of the imaginary unit (the square root of
      ``-1``), often written ``i`` in mathematics or ``j`` in
      engineering.  Python has built-in support for complex numbers, which are
      written with this latter notation; the imaginary part is written with a
      ``j`` suffix, e.g., ``3+1j``.  To get access to complex equivalents of the
      :mod:`math` module, use :mod:`cmath`.  Use of complex numbers is a fairly
      advanced mathematical feature.  If you're not aware of a need for them,
      it's almost certain you can safely ignore them.

   context manager
      An object which controls the environment seen in a :keyword:`with`
      statement by defining :meth:`__enter__` and :meth:`__exit__` methods.
      See :pep:`343`.

   CPython
      The canonical implementation of the Python programming language, as
      distributed on `python.org <https://www.python.org>`_.  The term "CPython"
      is used when necessary to distinguish this implementation from others
      such as Jython or IronPython.

   decorator
      A function returning another function, usually applied as a function
      transformation using the ``@wrapper`` syntax.  Common examples for
      decorators are :func:`classmethod` and :func:`staticmethod`.

      The decorator syntax is merely syntactic sugar, the following two
      function definitions are semantically equivalent::

         def f(...):
             ...
         f = staticmethod(f)

         @staticmethod
         def f(...):
             ...

      The same concept exists for classes, but is less commonly used there.  See
      the documentation for :ref:`function definitions <function>` and
      :ref:`class definitions <class>` for more about decorators.

   descriptor
      Any *new-style* object which defines the methods :meth:`__get__`,
      :meth:`__set__`, or :meth:`__delete__`.  When a class attribute is a
      descriptor, its special binding behavior is triggered upon attribute
      lookup.  Normally, using *a.b* to get, set or delete an attribute looks up
      the object named *b* in the class dictionary for *a*, but if *b* is a
      descriptor, the respective descriptor method gets called.  Understanding
      descriptors is a key to a deep understanding of Python because they are
      the basis for many features including functions, methods, properties,
      class methods, static methods, and reference to super classes.

      For more information about descriptors' methods, see :ref:`descriptors`.

   dictionary
      An associative array, where arbitrary keys are mapped to values.  The
      keys can be any object with :meth:`__hash__`  and :meth:`__eq__` methods.
      Called a hash in Perl.

   dictionary view
      The objects returned from :meth:`dict.viewkeys`, :meth:`dict.viewvalues`,
      and :meth:`dict.viewitems` are called dictionary views. They provide a dynamic
      view on the dictionary’s entries, which means that when the dictionary
      changes, the view reflects these changes. To force the
      dictionary view to become a full list use ``list(dictview)``.  See
      :ref:`dict-views`.

   docstring
      A string literal which appears as the first expression in a class,
      function or module.  While ignored when the suite is executed, it is
      recognized by the compiler and put into the :attr:`__doc__` attribute
      of the enclosing class, function or module.  Since it is available via
      introspection, it is the canonical place for documentation of the
      object.

   duck-typing
      A programming style which does not look at an object's type to determine
      if it has the right interface; instead, the method or attribute is simply
      called or used ("If it looks like a duck and quacks like a duck, it
      must be a duck.")  By emphasizing interfaces rather than specific types,
      well-designed code improves its flexibility by allowing polymorphic
      substitution.  Duck-typing avoids tests using :func:`type` or
      :func:`isinstance`.  (Note, however, that duck-typing can be complemented
      with :term:`abstract base classes <abstract base class>`.)  Instead, it
      typically employs :func:`hasattr` tests or :term:`EAFP` programming.

   EAFP
      Easier to ask for forgiveness than permission.  This common Python coding
      style assumes the existence of valid keys or attributes and catches
      exceptions if the assumption proves false.  This clean and fast style is
      characterized by the presence of many :keyword:`try` and :keyword:`except`
      statements.  The technique contrasts with the :term:`LBYL` style
      common to many other languages such as C.

   expression
      A piece of syntax which can be evaluated to some value.  In other words,
      an expression is an accumulation of expression elements like literals,
      names, attribute access, operators or function calls which all return a
      value.  In contrast to many other languages, not all language constructs
      are expressions.  There are also :term:`statement`\s which cannot be used
      as expressions, such as :keyword:`print` or :keyword:`if`.  Assignments
      are also statements, not expressions.

   extension module
      A module written in C or C++, using Python's C API to interact with the
      core and with user code.

   file object
      An object exposing a file-oriented API (with methods such as
      :meth:`read()` or :meth:`write()`) to an underlying resource.  Depending
      on the way it was created, a file object can mediate access to a real
      on-disk file or to another type of storage or communication device
      (for example standard input/output, in-memory buffers, sockets, pipes,
      etc.).  File objects are also called :dfn:`file-like objects` or
      :dfn:`streams`.

      There are actually three categories of file objects: raw binary files,
      buffered binary files and text files.  Their interfaces are defined in the
      :mod:`io` module.  The canonical way to create a file object is by using
      the :func:`open` function.

   file-like object
      A synonym for :term:`file object`.

   finder
      An object that tries to find the :term:`loader` for a module. It must
      implement a method named :meth:`find_module`. See :pep:`302` for
      details.

   floor division
      Mathematical division that rounds down to nearest integer.  The floor
      division operator is ``//``.  For example, the expression ``11 // 4``
      evaluates to ``2`` in contrast to the ``2.75`` returned by float true
      division.  Note that ``(-11) // 4`` is ``-3`` because that is ``-2.75``
      rounded *downward*. See :pep:`238`.

   function
      A series of statements which returns some value to a caller. It can also
      be passed zero or more :term:`arguments <argument>` which may be used in
      the execution of the body. See also :term:`parameter`, :term:`method`,
      and the :ref:`function` section.

   __future__
      A pseudo-module which programmers can use to enable new language features
      which are not compatible with the current interpreter.  For example, the
      expression ``11/4`` currently evaluates to ``2``. If the module in which
      it is executed had enabled *true division* by executing::

         from __future__ import division

      the expression ``11/4`` would evaluate to ``2.75``.  By importing the
      :mod:`__future__` module and evaluating its variables, you can see when a
      new feature was first added to the language and when it will become the
      default::

         >>> import __future__
         >>> __future__.division
         _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)

   garbage collection
      The process of freeing memory when it is not used anymore.  Python
      performs garbage collection via reference counting and a cyclic garbage
      collector that is able to detect and break reference cycles.

      .. index:: single: generator

   generator
      A function which returns an iterator.  It looks like a normal function
      except that it contains :keyword:`yield` statements for producing a series
      of values usable in a for-loop or that can be retrieved one at a time with
      the :func:`next` function. Each :keyword:`yield` temporarily suspends
      processing, remembering the location execution state (including local
      variables and pending try-statements).  When the generator resumes, it
      picks up where it left off (in contrast to functions which start fresh on
      every invocation).

      .. index:: single: generator expression

   generator expression
      An expression that returns an iterator.  It looks like a normal expression
      followed by a :keyword:`for` expression defining a loop variable, range,
      and an optional :keyword:`if` expression.  The combined expression
      generates values for an enclosing function::

         >>> sum(i*i for i in range(10))         # sum of squares 0, 1, 4, ... 81
         285

   GIL
      See :term:`global interpreter lock`.

   global interpreter lock
      The mechanism used by the :term:`CPython` interpreter to assure that
      only one thread executes Python :term:`bytecode` at a time.
      This simplifies the CPython implementation by making the object model
      (including critical built-in types such as :class:`dict`) implicitly
      safe against concurrent access.  Locking the entire interpreter
      makes it easier for the interpreter to be multi-threaded, at the
      expense of much of the parallelism afforded by multi-processor
      machines.

      However, some extension modules, either standard or third-party,
      are designed so as to release the GIL when doing computationally-intensive
      tasks such as compression or hashing.  Also, the GIL is always released
      when doing I/O.

      Past efforts to create a "free-threaded" interpreter (one which locks
      shared data at a much finer granularity) have not been successful
      because performance suffered in the common single-processor case. It
      is believed that overcoming this performance issue would make the
      implementation much more complicated and therefore costlier to maintain.

   hashable
      An object is *hashable* if it has a hash value which never changes during
      its lifetime (it needs a :meth:`__hash__` method), and can be compared to
      other objects (it needs an :meth:`__eq__` or :meth:`__cmp__` method).
      Hashable objects which compare equal must have the same hash value.

      Hashability makes an object usable as a dictionary key and a set member,
      because these data structures use the hash value internally.

      All of Python's immutable built-in objects are hashable, while no mutable
      containers (such as lists or dictionaries) are.  Objects which are
      instances of user-defined classes are hashable by default; they all
      compare unequal (except with themselves), and their hash value is derived
      from their :func:`id`.

   IDLE
      An Integrated Development Environment for Python.  IDLE is a basic editor
      and interpreter environment which ships with the standard distribution of
      Python.

   immutable
      An object with a fixed value.  Immutable objects include numbers, strings and
      tuples.  Such an object cannot be altered.  A new object has to
      be created if a different value has to be stored.  They play an important
      role in places where a constant hash value is needed, for example as a key
      in a dictionary.

   integer division
      Mathematical division discarding any remainder.  For example, the
      expression ``11/4`` currently evaluates to ``2`` in contrast to the
      ``2.75`` returned by float division.  Also called *floor division*.
      When dividing two integers the outcome will always be another integer
      (having the floor function applied to it). However, if one of the operands
      is another numeric type (such as a :class:`float`), the result will be
      coerced (see :term:`coercion`) to a common type.  For example, an integer
      divided by a float will result in a float value, possibly with a decimal
      fraction.  Integer division can be forced by using the ``//`` operator
      instead of the ``/`` operator.  See also :term:`__future__`.

   importing
      The process by which Python code in one module is made available to
      Python code in another module.

   importer
      An object that both finds and loads a module; both a
      :term:`finder` and :term:`loader` object.

   interactive
      Python has an interactive interpreter which means you can enter
      statements and expressions at the interpreter prompt, immediately
      execute them and see their results.  Just launch ``python`` with no
      arguments (possibly by selecting it from your computer's main
      menu). It is a very powerful way to test out new ideas or inspect
      modules and packages (remember ``help(x)``).

   interpreted
      Python is an interpreted language, as opposed to a compiled one,
      though the distinction can be blurry because of the presence of the
      bytecode compiler.  This means that source files can be run directly
      without explicitly creating an executable which is then run.
      Interpreted languages typically have a shorter development/debug cycle
      than compiled ones, though their programs generally also run more
      slowly.  See also :term:`interactive`.

   iterable
      An object capable of returning its members one at a time. Examples of
      iterables include all sequence types (such as :class:`list`, :class:`str`,
      and :class:`tuple`) and some non-sequence types like :class:`dict`
      and :class:`file` and objects of any classes you define
      with an :meth:`__iter__` or :meth:`__getitem__` method.  Iterables can be
      used in a :keyword:`for` loop and in many other places where a sequence is
      needed (:func:`zip`, :func:`map`, ...).  When an iterable object is passed
      as an argument to the built-in function :func:`iter`, it returns an
      iterator for the object.  This iterator is good for one pass over the set
      of values.  When using iterables, it is usually not necessary to call
      :func:`iter` or deal with iterator objects yourself.  The ``for``
      statement does that automatically for you, creating a temporary unnamed
      variable to hold the iterator for the duration of the loop.  See also
      :term:`iterator`, :term:`sequence`, and :term:`generator`.

   iterator
      An object representing a stream of data.  Repeated calls to the iterator's
      :meth:`~generator.next` method return successive items in the stream.  When no more
      data are available a :exc:`StopIteration` exception is raised instead.  At
      this point, the iterator object is exhausted and any further calls to its
      :meth:`~generator.next` method just raise :exc:`StopIteration` again.  Iterators are
      required to have an :meth:`__iter__` method that returns the iterator
      object itself so every iterator is also iterable and may be used in most
      places where other iterables are accepted.  One notable exception is code
      which attempts multiple iteration passes.  A container object (such as a
      :class:`list`) produces a fresh new iterator each time you pass it to the
      :func:`iter` function or use it in a :keyword:`for` loop.  Attempting this
      with an iterator will just return the same exhausted iterator object used
      in the previous iteration pass, making it appear like an empty container.

      More information can be found in :ref:`typeiter`.

   key function
      A key function or collation function is a callable that returns a value
      used for sorting or ordering.  For example, :func:`locale.strxfrm` is
      used to produce a sort key that is aware of locale specific sort
      conventions.

      A number of tools in Python accept key functions to control how elements
      are ordered or grouped.  They include :func:`min`, :func:`max`,
      :func:`sorted`, :meth:`list.sort`, :func:`heapq.nsmallest`,
      :func:`heapq.nlargest`, and :func:`itertools.groupby`.

      There are several ways to create a key function.  For example. the
      :meth:`str.lower` method can serve as a key function for case insensitive
      sorts.  Alternatively, an ad-hoc key function can be built from a
      :keyword:`lambda` expression such as ``lambda r: (r[0], r[2])``.  Also,
      the :mod:`operator` module provides three key function constructors:
      :func:`~operator.attrgetter`, :func:`~operator.itemgetter`, and
      :func:`~operator.methodcaller`.  See the :ref:`Sorting HOW TO
      <sortinghowto>` for examples of how to create and use key functions.

   keyword argument
      See :term:`argument`.

   lambda
      An anonymous inline function consisting of a single :term:`expression`
      which is evaluated when the function is called.  The syntax to create
      a lambda function is ``lambda [parameters]: expression``

   LBYL
      Look before you leap.  This coding style explicitly tests for
      pre-conditions before making calls or lookups.  This style contrasts with
      the :term:`EAFP` approach and is characterized by the presence of many
      :keyword:`if` statements.

      In a multi-threaded environment, the LBYL approach can risk introducing a
      race condition between "the looking" and "the leaping".  For example, the
      code, ``if key in mapping: return mapping[key]`` can fail if another
      thread removes *key* from *mapping* after the test, but before the lookup.
      This issue can be solved with locks or by using the EAFP approach.

   list
      A built-in Python :term:`sequence`.  Despite its name it is more akin
      to an array in other languages than to a linked list since access to
      elements is O(1).

   list comprehension
      A compact way to process all or part of the elements in a sequence and
      return a list with the results.  ``result = ["0x%02x" % x for x in
      range(256) if x % 2 == 0]`` generates a list of strings containing
      even hex numbers (0x..) in the range from 0 to 255. The :keyword:`if`
      clause is optional.  If omitted, all elements in ``range(256)`` are
      processed.

   loader
      An object that loads a module. It must define a method named
      :meth:`load_module`. A loader is typically returned by a
      :term:`finder`. See :pep:`302` for details.

   mapping
      A container object that supports arbitrary key lookups and implements the
      methods specified in the :class:`~collections.Mapping` or
      :class:`~collections.MutableMapping`
      :ref:`abstract base classes <collections-abstract-base-classes>`.  Examples
      include :class:`dict`, :class:`collections.defaultdict`,
      :class:`collections.OrderedDict` and :class:`collections.Counter`.

   metaclass
      The class of a class.  Class definitions create a class name, a class
      dictionary, and a list of base classes.  The metaclass is responsible for
      taking those three arguments and creating the class.  Most object oriented
      programming languages provide a default implementation.  What makes Python
      special is that it is possible to create custom metaclasses.  Most users
      never need this tool, but when the need arises, metaclasses can provide
      powerful, elegant solutions.  They have been used for logging attribute
      access, adding thread-safety, tracking object creation, implementing
      singletons, and many other tasks.

      More information can be found in :ref:`metaclasses`.

   method
      A function which is defined inside a class body.  If called as an attribute
      of an instance of that class, the method will get the instance object as
      its first :term:`argument` (which is usually called ``self``).
      See :term:`function` and :term:`nested scope`.

   method resolution order
      Method Resolution Order is the order in which base classes are searched
      for a member during lookup. See `The Python 2.3 Method Resolution Order
      <https://www.python.org/download/releases/2.3/mro/>`_ for details of the
      algorithm used by the Python interpreter since the 2.3 release.

   module
      An object that serves as an organizational unit of Python code.  Modules
      have a namespace containing arbitrary Python objects.  Modules are loaded
      into Python by the process of :term:`importing`.

      See also :term:`package`.

   MRO
      See :term:`method resolution order`.

   mutable
      Mutable objects can change their value but keep their :func:`id`.  See
      also :term:`immutable`.

   named tuple
      Any tuple-like class whose indexable elements are also accessible using
      named attributes (for example, :func:`time.localtime` returns a
      tuple-like object where the *year* is accessible either with an
      index such as ``t[0]`` or with a named attribute like ``t.tm_year``).

      A named tuple can be a built-in type such as :class:`time.struct_time`,
      or it can be created with a regular class definition.  A full featured
      named tuple can also be created with the factory function
      :func:`collections.namedtuple`.  The latter approach automatically
      provides extra features such as a self-documenting representation like
      ``Employee(name='jones', title='programmer')``.

   namespace
      The place where a variable is stored.  Namespaces are implemented as
      dictionaries.  There are the local, global and built-in namespaces as well
      as nested namespaces in objects (in methods).  Namespaces support
      modularity by preventing naming conflicts.  For instance, the functions
      :func:`__builtin__.open` and :func:`os.open` are distinguished by their
      namespaces.  Namespaces also aid readability and maintainability by making
      it clear which module implements a function.  For instance, writing
      :func:`random.seed` or :func:`itertools.izip` makes it clear that those
      functions are implemented by the :mod:`random` and :mod:`itertools`
      modules, respectively.

   nested scope
      The ability to refer to a variable in an enclosing definition.  For
      instance, a function defined inside another function can refer to
      variables in the outer function.  Note that nested scopes work only for
      reference and not for assignment which will always write to the innermost
      scope.  In contrast, local variables both read and write in the innermost
      scope.  Likewise, global variables read and write to the global namespace.

   new-style class
      Any class which inherits from :class:`object`.  This includes all built-in
      types like :class:`list` and :class:`dict`.  Only new-style classes can
      use Python's newer, versatile features like :attr:`~object.__slots__`,
      descriptors, properties, and :meth:`__getattribute__`.

      More information can be found in :ref:`newstyle`.

   object
      Any data with state (attributes or value) and defined behavior
      (methods).  Also the ultimate base class of any :term:`new-style
      class`.

   package
      A Python :term:`module` which can contain submodules or recursively,
      subpackages.  Technically, a package is a Python module with an
      ``__path__`` attribute.

   parameter
      A named entity in a :term:`function` (or method) definition that
      specifies an :term:`argument` (or in some cases, arguments) that the
      function can accept.  There are four types of parameters:

      * :dfn:`positional-or-keyword`: specifies an argument that can be passed
        either :term:`positionally <argument>` or as a :term:`keyword argument
        <argument>`.  This is the default kind of parameter, for example *foo*
        and *bar* in the following::

           def func(foo, bar=None): ...

      * :dfn:`positional-only`: specifies an argument that can be supplied only
        by position.  Python has no syntax for defining positional-only
        parameters.  However, some built-in functions have positional-only
        parameters (e.g. :func:`abs`).

      * :dfn:`var-positional`: specifies that an arbitrary sequence of
        positional arguments can be provided (in addition to any positional
        arguments already accepted by other parameters).  Such a parameter can
        be defined by prepending the parameter name with ``*``, for example
        *args* in the following::

           def func(*args, **kwargs): ...

      * :dfn:`var-keyword`: specifies that arbitrarily many keyword arguments
        can be provided (in addition to any keyword arguments already accepted
        by other parameters).  Such a parameter can be defined by prepending
        the parameter name with ``**``, for example *kwargs* in the example
        above.

      Parameters can specify both optional and required arguments, as well as
      default values for some optional arguments.

      See also the :term:`argument` glossary entry, the FAQ question on
      :ref:`the difference between arguments and parameters
      <faq-argument-vs-parameter>`, and the :ref:`function` section.

   PEP
      Python Enhancement Proposal. A PEP is a design document
      providing information to the Python community, or describing a new
      feature for Python or its processes or environment. PEPs should
      provide a concise technical specification and a rationale for proposed
      features.

      PEPs are intended to be the primary mechanisms for proposing major new
      features, for collecting community input on an issue, and for documenting
      the design decisions that have gone into Python. The PEP author is
      responsible for building consensus within the community and documenting
      dissenting opinions.

      See :pep:`1`.

   positional argument
      See :term:`argument`.

   Python 3000
      Nickname for the Python 3.x release line (coined long ago when the release
      of version 3 was something in the distant future.)  This is also
      abbreviated "Py3k".

   Pythonic
      An idea or piece of code which closely follows the most common idioms
      of the Python language, rather than implementing code using concepts
      common to other languages.  For example, a common idiom in Python is
      to loop over all elements of an iterable using a :keyword:`for`
      statement.  Many other languages don't have this type of construct, so
      people unfamiliar with Python sometimes use a numerical counter instead::

          for i in range(len(food)):
              print food[i]

      As opposed to the cleaner, Pythonic method::

         for piece in food:
             print piece

   reference count
      The number of references to an object.  When the reference count of an
      object drops to zero, it is deallocated.  Reference counting is
      generally not visible to Python code, but it is a key element of the
      :term:`CPython` implementation.  The :mod:`sys` module defines a
      :func:`~sys.getrefcount` function that programmers can call to return the
      reference count for a particular object.

   __slots__
      A declaration inside a :term:`new-style class` that saves memory by
      pre-declaring space for instance attributes and eliminating instance
      dictionaries.  Though popular, the technique is somewhat tricky to get
      right and is best reserved for rare cases where there are large numbers of
      instances in a memory-critical application.

   sequence
      An :term:`iterable` which supports efficient element access using integer
      indices via the :meth:`__getitem__` special method and defines a
      :meth:`len` method that returns the length of the sequence.
      Some built-in sequence types are :class:`list`, :class:`str`,
      :class:`tuple`, and :class:`unicode`. Note that :class:`dict` also
      supports :meth:`__getitem__` and :meth:`__len__`, but is considered a
      mapping rather than a sequence because the lookups use arbitrary
      :term:`immutable` keys rather than integers.

   slice
      An object usually containing a portion of a :term:`sequence`.  A slice is
      created using the subscript notation, ``[]`` with colons between numbers
      when several are given, such as in ``variable_name[1:3:5]``.  The bracket
      (subscript) notation uses :class:`slice` objects internally (or in older
      versions, :meth:`__getslice__` and :meth:`__setslice__`).

   special method
      A method that is called implicitly by Python to execute a certain
      operation on a type, such as addition.  Such methods have names starting
      and ending with double underscores.  Special methods are documented in
      :ref:`specialnames`.

   statement
      A statement is part of a suite (a "block" of code).  A statement is either
      an :term:`expression` or one of several constructs with a keyword, such
      as :keyword:`if`, :keyword:`while` or :keyword:`for`.

   struct sequence
      A tuple with named elements. Struct sequences expose an interface similiar
      to :term:`named tuple` in that elements can be accessed either by
      index or as an attribute. However, they do not have any of the named tuple
      methods like :meth:`~collections.somenamedtuple._make` or
      :meth:`~collections.somenamedtuple._asdict`. Examples of struct sequences
      include :data:`sys.float_info` and the return value of :func:`os.stat`.

   triple-quoted string
      A string which is bound by three instances of either a quotation mark
      (") or an apostrophe (').  While they don't provide any functionality
      not available with single-quoted strings, they are useful for a number
      of reasons.  They allow you to include unescaped single and double
      quotes within a string and they can span multiple lines without the
      use of the continuation character, making them especially useful when
      writing docstrings.

   type
      The type of a Python object determines what kind of object it is; every
      object has a type.  An object's type is accessible as its
      :attr:`~instance.__class__` attribute or can be retrieved with
      ``type(obj)``.

   universal newlines
      A manner of interpreting text streams in which all of the following are
      recognized as ending a line: the Unix end-of-line convention ``'\n'``,
      the Windows convention ``'\r\n'``, and the old Macintosh convention
      ``'\r'``.  See :pep:`278` and :pep:`3116`, as well as
      :func:`str.splitlines` for an additional use.

   virtual environment
      A cooperatively isolated runtime environment that allows Python users
      and applications to install and upgrade Python distribution packages
      without interfering with the behaviour of other Python applications
      running on the same system.

   virtual machine
      A computer defined entirely in software.  Python's virtual machine
      executes the :term:`bytecode` emitted by the bytecode compiler.

   Zen of Python
      Listing of Python design principles and philosophies that are helpful in
      understanding and using the language.  The listing can be found by typing
      "``import this``" at the interactive prompt.
PK
%�\>�(L�L�html/_sources/license.rst.txtnu�[���.. highlightlang:: none

.. _history-and-license:

*******************
History and License
*******************


History of the software
=======================

Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see https://www.cwi.nl/) in the Netherlands as a
successor of a language called ABC.  Guido remains Python's principal author,
although it includes many contributions from others.

In 1995, Guido continued his work on Python at the Corporation for National
Research Initiatives (CNRI, see https://www.cnri.reston.va.us/) in Reston,
Virginia where he released several versions of the software.

In May 2000, Guido and the Python core development team moved to BeOpen.com to
form the BeOpen PythonLabs team.  In October of the same year, the PythonLabs
team moved to Digital Creations (now Zope Corporation; see
http://www.zope.com/).  In 2001, the Python Software Foundation (PSF, see
https://www.python.org/psf/) was formed, a non-profit organization created
specifically to own Python-related Intellectual Property.  Zope Corporation is a
sponsoring member of the PSF.

All Python releases are Open Source (see https://opensource.org/ for the Open
Source Definition). Historically, most, but not all, Python releases have also
been GPL-compatible; the table below summarizes the various releases.

+----------------+--------------+-----------+------------+-----------------+
| Release        | Derived from | Year      | Owner      | GPL compatible? |
+================+==============+===========+============+=================+
| 0.9.0 thru 1.2 | n/a          | 1991-1995 | CWI        | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 1.3 thru 1.5.2 | 1.2          | 1995-1999 | CNRI       | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 1.6            | 1.5.2        | 2000      | CNRI       | no              |
+----------------+--------------+-----------+------------+-----------------+
| 2.0            | 1.6          | 2000      | BeOpen.com | no              |
+----------------+--------------+-----------+------------+-----------------+
| 1.6.1          | 1.6          | 2001      | CNRI       | no              |
+----------------+--------------+-----------+------------+-----------------+
| 2.1            | 2.0+1.6.1    | 2001      | PSF        | no              |
+----------------+--------------+-----------+------------+-----------------+
| 2.0.1          | 2.0+1.6.1    | 2001      | PSF        | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 2.1.1          | 2.1+2.0.1    | 2001      | PSF        | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 2.1.2          | 2.1.1        | 2002      | PSF        | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 2.1.3          | 2.1.2        | 2002      | PSF        | yes             |
+----------------+--------------+-----------+------------+-----------------+
| 2.2 and above  | 2.1.1        | 2001-now  | PSF        | yes             |
+----------------+--------------+-----------+------------+-----------------+

.. note::

   GPL-compatible doesn't mean that we're distributing Python under the GPL.  All
   Python licenses, unlike the GPL, let you distribute a modified version without
   making your changes open source. The GPL-compatible licenses make it possible to
   combine Python with other software that is released under the GPL; the others
   don't.

Thanks to the many outside volunteers who have worked under Guido's direction to
make these releases possible.


Terms and conditions for accessing or otherwise using Python
============================================================


PSF LICENSE AGREEMENT FOR PYTHON |release|
------------------------------------------

.. parsed-literal::

   1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
      the Individual or Organization ("Licensee") accessing and otherwise using Python
      |release| software in source or binary form and its associated documentation.

   2. Subject to the terms and conditions of this License Agreement, PSF hereby
      grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
      analyze, test, perform and/or display publicly, prepare derivative works,
      distribute, and otherwise use Python |release| alone or in any derivative
      version, provided, however, that PSF's License Agreement and PSF's notice of
      copyright, i.e., "Copyright © 2001-2019 Python Software Foundation; All Rights
      Reserved" are retained in Python |release| alone or in any derivative version
      prepared by Licensee.

   3. In the event Licensee prepares a derivative work that is based on or
      incorporates Python |release| or any part thereof, and wants to make the
      derivative work available to others as provided herein, then Licensee hereby
      agrees to include in any such work a brief summary of the changes made to Python
      |release|.

   4. PSF is making Python |release| available to Licensee on an "AS IS" basis.
      PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
      EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
      WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
      USE OF PYTHON |release| WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

   5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON |release|
      FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
      MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON |release|, OR ANY DERIVATIVE
      THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

   6. This License Agreement will automatically terminate upon a material breach of
      its terms and conditions.

   7. Nothing in this License Agreement shall be deemed to create any relationship
      of agency, partnership, or joint venture between PSF and Licensee.  This License
      Agreement does not grant permission to use PSF trademarks or trade name in a
      trademark sense to endorse or promote products or services of Licensee, or any
      third party.

   8. By copying, installing or otherwise using Python |release|, Licensee agrees
      to be bound by the terms and conditions of this License Agreement.


BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
-------------------------------------------

BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1

.. parsed-literal::

   1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at
      160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
      ("Licensee") accessing and otherwise using this software in source or binary
      form and its associated documentation ("the Software").

   2. Subject to the terms and conditions of this BeOpen Python License Agreement,
      BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
      to reproduce, analyze, test, perform and/or display publicly, prepare derivative
      works, distribute, and otherwise use the Software alone or in any derivative
      version, provided, however, that the BeOpen Python License is retained in the
      Software, alone or in any derivative version prepared by Licensee.

   3. BeOpen is making the Software available to Licensee on an "AS IS" basis.
      BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
      EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
      WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
      USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

   4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
      ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
      MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
      ADVISED OF THE POSSIBILITY THEREOF.

   5. This License Agreement will automatically terminate upon a material breach of
      its terms and conditions.

   6. This License Agreement shall be governed by and interpreted in all respects
      by the law of the State of California, excluding conflict of law provisions.
      Nothing in this License Agreement shall be deemed to create any relationship of
      agency, partnership, or joint venture between BeOpen and Licensee.  This License
      Agreement does not grant permission to use BeOpen trademarks or trade names in a
      trademark sense to endorse or promote products or services of Licensee, or any
      third party.  As an exception, the "BeOpen Python" logos available at
      http://www.pythonlabs.com/logos.html may be used according to the permissions
      granted on that web page.

   7. By copying, installing or otherwise using the software, Licensee agrees to be
      bound by the terms and conditions of this License Agreement.


CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
---------------------------------------

.. parsed-literal::

   1. This LICENSE AGREEMENT is between the Corporation for National Research
      Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
      ("CNRI"), and the Individual or Organization ("Licensee") accessing and
      otherwise using Python 1.6.1 software in source or binary form and its
      associated documentation.

   2. Subject to the terms and conditions of this License Agreement, CNRI hereby
      grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
      analyze, test, perform and/or display publicly, prepare derivative works,
      distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
      provided, however, that CNRI's License Agreement and CNRI's notice of copyright,
      i.e., "Copyright © 1995-2001 Corporation for National Research Initiatives; All
      Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version
      prepared by Licensee.  Alternately, in lieu of CNRI's License Agreement,
      Licensee may substitute the following text (omitting the quotes): "Python 1.6.1
      is made available subject to the terms and conditions in CNRI's License
      Agreement.  This Agreement together with Python 1.6.1 may be located on the
      Internet using the following unique, persistent identifier (known as a handle):
      1895.22/1013.  This Agreement may also be obtained from a proxy server on the
      Internet using the following URL: http://hdl.handle.net/1895.22/1013."

   3. In the event Licensee prepares a derivative work that is based on or
      incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
      work available to others as provided herein, then Licensee hereby agrees to
      include in any such work a brief summary of the changes made to Python 1.6.1.

   4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis.  CNRI
      MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
      BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
      OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
      PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

   5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
      ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
      MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
      THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

   6. This License Agreement will automatically terminate upon a material breach of
      its terms and conditions.

   7. This License Agreement shall be governed by the federal intellectual property
      law of the United States, including without limitation the federal copyright
      law, and, to the extent such U.S. federal law does not apply, by the law of the
      Commonwealth of Virginia, excluding Virginia's conflict of law provisions.
      Notwithstanding the foregoing, with regard to derivative works based on Python
      1.6.1 that incorporate non-separable material that was previously distributed
      under the GNU General Public License (GPL), the law of the Commonwealth of
      Virginia shall govern this License Agreement only as to issues arising under or
      with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
      this License Agreement shall be deemed to create any relationship of agency,
      partnership, or joint venture between CNRI and Licensee.  This License Agreement
      does not grant permission to use CNRI trademarks or trade name in a trademark
      sense to endorse or promote products or services of Licensee, or any third
      party.

   8. By clicking on the "ACCEPT" button where indicated, or by copying, installing
      or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
      conditions of this License Agreement.


CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
--------------------------------------------------

.. parsed-literal::

   Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
   Netherlands.  All rights reserved.

   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted, provided that
   the above copyright notice appear in all copies and that both that copyright
   notice and this permission notice appear in supporting documentation, and that
   the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
   publicity pertaining to distribution of the software without specific, written
   prior permission.

   STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
   SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
   EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
   OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
   DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
   ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
   SOFTWARE.


Licenses and Acknowledgements for Incorporated Software
=======================================================

This section is an incomplete, but growing list of licenses and acknowledgements
for third-party software incorporated in the Python distribution.


Mersenne Twister
----------------

The :mod:`_random` module includes code based on a download from
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html. The following are
the verbatim comments from the original code::

   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    3. The names of its contributors may not be used to endorse or promote
       products derived from this software without specific prior written
       permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)


Sockets
-------

The :mod:`socket` module uses the functions, :func:`getaddrinfo`, and
:func:`getnameinfo`, which are coded in separate source files from the WIDE
Project, http://www.wide.ad.jp/. ::

   Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:
   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
   2. Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
   3. Neither the name of the project nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
   FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   SUCH DAMAGE.

Floating point exception control
--------------------------------

The source for the :mod:`fpectl` module includes the following notice::

     ---------------------------------------------------------------------
    /                       Copyright (c) 1996.                           \
   |          The Regents of the University of California.                 |
   |                        All rights reserved.                           |
   |                                                                       |
   |   Permission to use, copy, modify, and distribute this software for   |
   |   any purpose without fee is hereby granted, provided that this en-   |
   |   tire notice is included in all copies of any software which is or   |
   |   includes  a  copy  or  modification  of  this software and in all   |
   |   copies of the supporting documentation for such software.           |
   |                                                                       |
   |   This  work was produced at the University of California, Lawrence   |
   |   Livermore National Laboratory under  contract  no.  W-7405-ENG-48   |
   |   between  the  U.S.  Department  of  Energy and The Regents of the   |
   |   University of California for the operation of UC LLNL.              |
   |                                                                       |
   |                              DISCLAIMER                               |
   |                                                                       |
   |   This  software was prepared as an account of work sponsored by an   |
   |   agency of the United States Government. Neither the United States   |
   |   Government  nor the University of California nor any of their em-   |
   |   ployees, makes any warranty, express or implied, or  assumes  any   |
   |   liability  or  responsibility  for the accuracy, completeness, or   |
   |   usefulness of any information,  apparatus,  product,  or  process   |
   |   disclosed,   or  represents  that  its  use  would  not  infringe   |
   |   privately-owned rights. Reference herein to any specific  commer-   |
   |   cial  products,  process,  or  service  by trade name, trademark,   |
   |   manufacturer, or otherwise, does not  necessarily  constitute  or   |
   |   imply  its endorsement, recommendation, or favoring by the United   |
   |   States Government or the University of California. The views  and   |
   |   opinions  of authors expressed herein do not necessarily state or   |
   |   reflect those of the United States Government or  the  University   |
   |   of  California,  and shall not be used for advertising or product   |
    \  endorsement purposes.                                              /
     ---------------------------------------------------------------------


MD5 message digest algorithm
----------------------------

The source code for the :mod:`md5` module contains the following notice::

     Copyright (C) 1999, 2002 Aladdin Enterprises.  All rights reserved.

     This software is provided 'as-is', without any express or implied
     warranty.  In no event will the authors be held liable for any damages
     arising from the use of this software.

     Permission is granted to anyone to use this software for any purpose,
     including commercial applications, and to alter it and redistribute it
     freely, subject to the following restrictions:

     1. The origin of this software must not be misrepresented; you must not
        claim that you wrote the original software. If you use this software
        in a product, an acknowledgment in the product documentation would be
        appreciated but is not required.
     2. Altered source versions must be plainly marked as such, and must not be
        misrepresented as being the original software.
     3. This notice may not be removed or altered from any source distribution.

     L. Peter Deutsch
     ghost@aladdin.com

     Independent implementation of MD5 (RFC 1321).

     This code implements the MD5 Algorithm defined in RFC 1321, whose
     text is available at
           http://www.ietf.org/rfc/rfc1321.txt
     The code is derived from the text of the RFC, including the test suite
     (section A.5) but excluding the rest of Appendix A.  It does not include
     any code or documentation that is identified in the RFC as being
     copyrighted.

     The original and principal author of md5.h is L. Peter Deutsch
     <ghost@aladdin.com>.  Other authors are noted in the change history
     that follows (in reverse chronological order):

     2002-04-13 lpd Removed support for non-ANSI compilers; removed
           references to Ghostscript; clarified derivation from RFC 1321;
           now handles byte order either statically or dynamically.
     1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
     1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
           added conditionalization for C++ compilation from Martin
           Purschke <purschke@bnl.gov>.
     1999-05-03 lpd Original version.


Asynchronous socket services
----------------------------

The :mod:`asynchat` and :mod:`asyncore` modules contain the following notice::

   Copyright 1996 by Sam Rushing

                           All Rights Reserved

   Permission to use, copy, modify, and distribute this software and
   its documentation for any purpose and without fee is hereby
   granted, provided that the above copyright notice appear in all
   copies and that both that copyright notice and this permission
   notice appear in supporting documentation, and that the name of Sam
   Rushing not be used in advertising or publicity pertaining to
   distribution of the software without specific, written prior
   permission.

   SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
   INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
   NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
   CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
   OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
   NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
   CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.


Cookie management
-----------------

The :mod:`Cookie` module contains the following notice::

   Copyright 2000 by Timothy O'Malley <timo@alum.mit.edu>

                  All Rights Reserved

   Permission to use, copy, modify, and distribute this software
   and its documentation for any purpose and without fee is hereby
   granted, provided that the above copyright notice appear in all
   copies and that both that copyright notice and this permission
   notice appear in supporting documentation, and that the name of
   Timothy O'Malley  not be used in advertising or publicity
   pertaining to distribution of the software without specific, written
   prior permission.

   Timothy O'Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
   SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
   AND FITNESS, IN NO EVENT SHALL Timothy O'Malley BE LIABLE FOR
   ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
   WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
   ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
   PERFORMANCE OF THIS SOFTWARE.


Execution tracing
-----------------

The :mod:`trace` module contains the following notice::

   portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
   err...  reserved and offered to the public under the terms of the
   Python 2.2 license.
   Author: Zooko O'Whielacronx
   http://zooko.com/
   mailto:zooko@zooko.com

   Copyright 2000, Mojam Media, Inc., all rights reserved.
   Author: Skip Montanaro

   Copyright 1999, Bioreason, Inc., all rights reserved.
   Author: Andrew Dalke

   Copyright 1995-1997, Automatrix, Inc., all rights reserved.
   Author: Skip Montanaro

   Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.


   Permission to use, copy, modify, and distribute this Python software and
   its associated documentation for any purpose without fee is hereby
   granted, provided that the above copyright notice appears in all copies,
   and that both that copyright notice and this permission notice appear in
   supporting documentation, and that the name of neither Automatrix,
   Bioreason or Mojam Media be used in advertising or publicity pertaining to
   distribution of the software without specific, written prior permission.


UUencode and UUdecode functions
-------------------------------

The :mod:`uu` module contains the following notice::

   Copyright 1994 by Lance Ellinghouse
   Cathedral City, California Republic, United States of America.
                          All Rights Reserved
   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted,
   provided that the above copyright notice appear in all copies and that
   both that copyright notice and this permission notice appear in
   supporting documentation, and that the name of Lance Ellinghouse
   not be used in advertising or publicity pertaining to distribution
   of the software without specific, written prior permission.
   LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
   THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
   FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
   FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
   WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
   ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
   OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

   Modified by Jack Jansen, CWI, July 1995:
   - Use binascii module to do the actual line-by-line conversion
     between ascii and binary. This results in a 1000-fold speedup. The C
     version is still 5 times faster, though.
   - Arguments more compliant with Python standard


XML Remote Procedure Calls
--------------------------

The :mod:`xmlrpclib` module contains the following notice::

       The XML-RPC client interface is

   Copyright (c) 1999-2002 by Secret Labs AB
   Copyright (c) 1999-2002 by Fredrik Lundh

   By obtaining, using, and/or copying this software and/or its
   associated documentation, you agree that you have read, understood,
   and will comply with the following terms and conditions:

   Permission to use, copy, modify, and distribute this software and
   its associated documentation for any purpose and without fee is
   hereby granted, provided that the above copyright notice appears in
   all copies, and that both that copyright notice and this permission
   notice appear in supporting documentation, and that the name of
   Secret Labs AB or the author not be used in advertising or publicity
   pertaining to distribution of the software without specific, written
   prior permission.

   SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
   TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
   ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
   BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
   DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
   WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
   ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
   OF THIS SOFTWARE.


test_epoll
----------

The :mod:`test_epoll` contains the following notice::

  Copyright (c) 2001-2006 Twisted Matrix Laboratories.

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Select kqueue
-------------

The :mod:`select` and contains the following notice for the kqueue interface::

  Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
  All rights reserved.

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions
  are met:
  1. Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  SUCH DAMAGE.


strtod and dtoa
---------------

The file :file:`Python/dtoa.c`, which supplies C functions dtoa and
strtod for conversion of C doubles to and from strings, is derived
from the file of the same name by David M. Gay, currently available
from http://www.netlib.org/fp/.  The original file, as retrieved on
March 16, 2009, contains the following copyright and licensing
notice::

   /****************************************************************
    *
    * The author of this software is David M. Gay.
    *
    * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
    *
    * Permission to use, copy, modify, and distribute this software for any
    * purpose without fee is hereby granted, provided that this entire notice
    * is included in all copies of any software which is or includes a copy
    * or modification of this software and in all copies of the supporting
    * documentation for such software.
    *
    * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
    * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
    * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
    * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
    *
    ***************************************************************/


OpenSSL
-------

The modules :mod:`hashlib`, :mod:`posix`, :mod:`ssl`, :mod:`crypt` use
the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and Mac OS X installers for
Python may include a copy of the OpenSSL libraries, so we include a copy
of the OpenSSL license here::


  LICENSE ISSUES
  ==============

  The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
  the OpenSSL License and the original SSLeay license apply to the toolkit.
  See below for the actual license texts. Actually both licenses are BSD-style
  Open Source licenses. In case of any license issues related to OpenSSL
  please contact openssl-core@openssl.org.

  OpenSSL License
  ---------------

    /* ====================================================================
     * Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in
     *    the documentation and/or other materials provided with the
     *    distribution.
     *
     * 3. All advertising materials mentioning features or use of this
     *    software must display the following acknowledgment:
     *    "This product includes software developed by the OpenSSL Project
     *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
     *
     * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     *    endorse or promote products derived from this software without
     *    prior written permission. For written permission, please contact
     *    openssl-core@openssl.org.
     *
     * 5. Products derived from this software may not be called "OpenSSL"
     *    nor may "OpenSSL" appear in their names without prior written
     *    permission of the OpenSSL Project.
     *
     * 6. Redistributions of any form whatsoever must retain the following
     *    acknowledgment:
     *    "This product includes software developed by the OpenSSL Project
     *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
     *
     * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
     * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
     * OF THE POSSIBILITY OF SUCH DAMAGE.
     * ====================================================================
     *
     * This product includes cryptographic software written by Eric Young
     * (eay@cryptsoft.com).  This product includes software written by Tim
     * Hudson (tjh@cryptsoft.com).
     *
     */

  Original SSLeay License
  -----------------------

    /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
     * All rights reserved.
     *
     * This package is an SSL implementation written
     * by Eric Young (eay@cryptsoft.com).
     * The implementation was written so as to conform with Netscapes SSL.
     *
     * This library is free for commercial and non-commercial use as long as
     * the following conditions are aheared to.  The following conditions
     * apply to all code found in this distribution, be it the RC4, RSA,
     * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     * included with this distribution is covered by the same copyright terms
     * except that the holder is Tim Hudson (tjh@cryptsoft.com).
     *
     * Copyright remains Eric Young's, and as such any Copyright notices in
     * the code are not to be removed.
     * If this package is used in a product, Eric Young should be given attribution
     * as the author of the parts of the library used.
     * This can be in the form of a textual message at program startup or
     * in documentation (online or textual) provided with the package.
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     * 1. Redistributions of source code must retain the copyright
     *    notice, this list of conditions and the following disclaimer.
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     * 3. All advertising materials mentioning features or use of this software
     *    must display the following acknowledgement:
     *    "This product includes cryptographic software written by
     *     Eric Young (eay@cryptsoft.com)"
     *    The word 'cryptographic' can be left out if the rouines from the library
     *    being used are not cryptographic related :-).
     * 4. If you include any Windows specific code (or a derivative thereof) from
     *    the apps directory (application code) you must include an acknowledgement:
     *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
     *
     * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     * SUCH DAMAGE.
     *
     * The licence and distribution terms for any publically available version or
     * derivative of this code cannot be changed.  i.e. this code cannot simply be
     * copied and put under another distribution licence
     * [including the GNU Public Licence.]
     */


expat
-----

The :mod:`pyexpat` extension is built using an included copy of the expat
sources unless the build is configured ``--with-system-expat``::

  Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                                 and Clark Cooper

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be included
  in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


libffi
------

The :mod:`_ctypes` extension is built using an included copy of the libffi
sources unless the build is configured ``--with-system-libffi``::

   Copyright (c) 1996-2008  Red Hat, Inc and others.

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   ``Software''), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.


zlib
----

The :mod:`zlib` extension is built using an included copy of the zlib
sources if the zlib version found on the system is too old to be
used for the build::

  Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler

  This software is provided 'as-is', without any express or implied
  warranty.  In no event will the authors be held liable for any damages
  arising from the use of this software.

  Permission is granted to anyone to use this software for any purpose,
  including commercial applications, and to alter it and redistribute it
  freely, subject to the following restrictions:

  1. The origin of this software must not be misrepresented; you must not
     claim that you wrote the original software. If you use this software
     in a product, an acknowledgment in the product documentation would be
     appreciated but is not required.

  2. Altered source versions must be plainly marked as such, and must not be
     misrepresented as being the original software.

  3. This notice may not be removed or altered from any source distribution.

  Jean-loup Gailly        Mark Adler
  jloup@gzip.org          madler@alumni.caltech.edu
PK
%�\<>��html/_static/ajax-loader.gifnu�[���GIF89a����U|���N��U|l��������!�Created with ajaxload.info!�
!�NETSCAPE2.0,3��0�Ikc:�N�f	E�1º���.`��q�-[9ݦ9Jk�H!�
,4��N�! ����DqBQT`1 `LE[�|�u��a� ��C�%$*!�
,6�2#+�AȐ̔V/�c�N�IBa��p�
̳�ƨ+Y����2�d��!�
,3�b%+�2���V_���	�!1D�a�F���bR]�=08,�Ȥr9L!�
,2�r'+J�d��L�&v�`\bT����hYB)��@�<�&,�ȤR�!�
,3� 9�t�ڞ0��!.B���W��1sa��5���0�	���m)J!�
,2���	ٜU]���qp�`��a��4��AF�0�`��
�@�1���Α!�
,2��0�I�eBԜ)�� ��q10�ʰ�P�aVڥ ub��[�;PK
%�\�o�Ŭ�html/_static/basic.cssnu�[���/**
 * Sphinx stylesheet -- basic theme
 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 */

/* -- main layout ----------------------------------------------------------- */

div.clearer {
    clear: both;
}

/* -- relbar ---------------------------------------------------------------- */

div.related {
    width: 100%;
    font-size: 90%;
}

div.related h3 {
    display: none;
}

div.related ul {
    margin: 0;
    padding: 0 0 0 10px;
    list-style: none;
}

div.related li {
    display: inline;
}

div.related li.right {
    float: right;
    margin-right: 5px;
}

/* -- sidebar --------------------------------------------------------------- */

div.sphinxsidebarwrapper {
    position: relative;
    top: 0;
    padding: 10px 5px 0 10px;
    word-wrap: break-word;
}

div.sphinxsidebar {
    float: left;
    width: 230px;
    margin-left: -100%;
    font-size: 90%;
}

div.sphinxsidebar ul {
    list-style: none;
}

div.sphinxsidebar ul ul,
div.sphinxsidebar ul.want-points {
    margin-left: 20px;
    list-style: square;
}

div.sphinxsidebar ul ul {
    margin-top: 0;
    margin-bottom: 0;
}

div.sphinxsidebar form {
    margin-top: 10px;
}

div.sphinxsidebar input {
    border: 1px solid #98dbcc;
    font-family: sans-serif;
    font-size: 1em;
}

img {
    border: 0;
}

/* -- search page ----------------------------------------------------------- */

ul.search {
    margin: 10px 0 0 20px;
    padding: 0;
}

ul.search li {
    padding: 5px 0 5px 20px;
    background-image: url(file.png);
    background-repeat: no-repeat;
    background-position: 0 7px;
}

ul.search li a {
    font-weight: bold;
}

ul.search li div.context {
    color: #888;
    margin: 2px 0 0 30px;
    text-align: left;
}

ul.keywordmatches li.goodmatch a {
    font-weight: bold;
}

/* -- index page ------------------------------------------------------------ */

table.contentstable {
    width: 90%;
}

table.contentstable p.biglink {
    line-height: 150%;
}

a.biglink {
    font-size: 1.3em;
}

span.linkdescr {
    font-style: italic;
    padding-top: 5px;
    font-size: 90%;
}

/* -- general index --------------------------------------------------------- */

table.indextable td {
    text-align: left;
    vertical-align: top;
}

table.indextable dl, table.indextable dd {
    margin-top: 0;
    margin-bottom: 0;
}

table.indextable tr.pcap {
    height: 10px;
}

table.indextable tr.cap {
    margin-top: 10px;
    background-color: #f2f2f2;
}

img.toggler {
    margin-right: 3px;
    margin-top: 3px;
    cursor: pointer;
}

/* -- general body styles --------------------------------------------------- */

a.headerlink {
    visibility: hidden;
}

h1:hover > a.headerlink,
h2:hover > a.headerlink,
h3:hover > a.headerlink,
h4:hover > a.headerlink,
h5:hover > a.headerlink,
h6:hover > a.headerlink,
dt:hover > a.headerlink {
    visibility: visible;
}

div.body p.caption {
    text-align: inherit;
}

div.body td {
    text-align: left;
}

.field-list ul {
    padding-left: 1em;
}

.first {
    margin-top: 0 !important;
}

p.rubric {
    margin-top: 30px;
    font-weight: bold;
}

/* -- sidebars -------------------------------------------------------------- */

div.sidebar {
    margin: 0 0 0.5em 1em;
    border: 1px solid #ddb;
    padding: 7px 7px 0 7px;
    background-color: #ffe;
    width: 40%;
    float: right;
}

p.sidebar-title {
    font-weight: bold;
}

/* -- topics ---------------------------------------------------------------- */

div.topic {
    border: 1px solid #ccc;
    padding: 7px 7px 0 7px;
    margin: 10px 0 10px 0;
}

p.topic-title {
    font-size: 1.1em;
    font-weight: bold;
    margin-top: 10px;
}

/* -- admonitions ----------------------------------------------------------- */

div.admonition {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 7px;
}

div.admonition dt {
    font-weight: bold;
}

div.admonition dl {
    margin-bottom: 0;
}

p.admonition-title {
    margin: 0px 10px 5px 0px;
    font-weight: bold;
}

div.body p.centered {
    text-align: center;
    margin-top: 25px;
}

/* -- tables ---------------------------------------------------------------- */

table.docutils {
    border: 0 solid #dce;
    border-collapse: collapse;
}

table.docutils td, table.docutils th {
    padding: 2px 5px 2px 5px;
    border-left: 0;
    background-color: #eef;
}

table.docutils td p.last, table.docutils th p.last {
    margin-bottom: 0;
}

table.field-list td, table.field-list th {
    border: 0 !important;
}

table.footnote td, table.footnote th {
    border: 0 !important;
}

table.docutils th {
    border-top: 1px solid #cac;
    background-color: #ede;
}

th {
    text-align: left;
    padding-right: 5px;
}

th.head {
    text-align: center;
}

/* -- other body styles ----------------------------------------------------- */

dl {
    margin-bottom: 15px;
}

dd p {
    margin-top: 0px;
}

dd ul, dd table {
    margin-bottom: 10px;
}

dd {
    margin-top: 3px;
    margin-bottom: 10px;
    margin-left: 30px;
}

dt:target, .highlighted {
    background-color: #fbe54e;
}

dl.glossary dt {
    font-weight: bold;
    font-size: 1.1em;
}

.field-list ul {
    margin: 0;
    padding-left: 1em;
}

.field-list p {
    margin: 0;
}

.refcount {
    color: #060;
}

.optional {
    font-size: 1.3em;
}

.versionmodified {
    font-style: italic;
}

.deprecated {
    background-color: #ffe4e4;
    border: 1px solid #f66;
    padding: 7px;
}

div.deprecated p {
    margin-bottom: 0;
}

.system-message {
    background-color: #fda;
    padding: 5px;
    border: 3px solid red;
}

.footnote:target  {
    background-color: #ffa;
}

.impl-detail {
    margin-top: 10px;
    margin-bottom: 10px;
    padding: 7px;
    border: 1px solid #ccc;
}

.impl-detail .compound-first {
    margin-top: 0;
}

.impl-detail .compound-last {
    margin-bottom: 0;
}

/* -- code displays --------------------------------------------------------- */

pre {
    overflow: auto;
    overflow-y: hidden;
}

td.linenos pre {
    padding: 5px 0px;
    border: 0;
    background-color: transparent;
    color: #aaa;
}

table.highlighttable {
    margin-left: 0.5em;
}

table.highlighttable td {
    padding: 0 0.5em 0 0.5em;
}

code.descname {
    background-color: transparent;
    font-weight: bold;
    font-size: 1.2em;
}

code.descclassname {
    background-color: transparent;
}

code.xref, a code {
    background-color: transparent;
    font-weight: bold;
}

h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
    background-color: transparent;
}

.highlight {
    background: none !important;
}


/* -- math display ---------------------------------------------------------- */

img.math {
    vertical-align: middle;
}

div.body div.math p {
    text-align: center;
}

span.eqno {
    float: right;
}

/* -- printout stylesheet --------------------------------------------------- */

@media print {
    div.document,
    div.documentwrapper,
    div.bodywrapper {
        margin: 0 !important;
        width: 100%;
    }

    div.sphinxsidebar,
    div.related,
    div.footer,
    #top-link {
        display: none;
    }
}
PK
%�\`A�?��html/_static/classic.cssnu�[���/*
 * classic.css_t
 * ~~~~~~~~~~~~~
 *
 * Sphinx stylesheet -- classic theme.
 *
 * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */

@import url("basic.css");

/* -- page layout ----------------------------------------------------------- */

body {
    font-family: sans-serif;
    font-size: 100%;
    background-color: #11303d;
    color: #000;
    margin: 0;
    padding: 0;
}

div.document {
    background-color: #1c4e63;
}

div.documentwrapper {
    float: left;
    width: 100%;
}

div.bodywrapper {
    margin: 0 0 0 230px;
}

div.body {
    background-color: #ffffff;
    color: #000000;
    padding: 0 20px 30px 20px;
}

div.footer {
    color: #ffffff;
    width: 100%;
    padding: 9px 0 9px 0;
    text-align: center;
    font-size: 75%;
}

div.footer a {
    color: #ffffff;
    text-decoration: underline;
}

div.related {
    background-color: #133f52;
    line-height: 30px;
    color: #ffffff;
}

div.related a {
    color: #ffffff;
}

div.sphinxsidebar {
}

div.sphinxsidebar h3 {
    font-family: 'Trebuchet MS', sans-serif;
    color: #ffffff;
    font-size: 1.4em;
    font-weight: normal;
    margin: 0;
    padding: 0;
}

div.sphinxsidebar h3 a {
    color: #ffffff;
}

div.sphinxsidebar h4 {
    font-family: 'Trebuchet MS', sans-serif;
    color: #ffffff;
    font-size: 1.3em;
    font-weight: normal;
    margin: 5px 0 0 0;
    padding: 0;
}

div.sphinxsidebar p {
    color: #ffffff;
}

div.sphinxsidebar p.topless {
    margin: 5px 10px 10px 10px;
}

div.sphinxsidebar ul {
    margin: 10px;
    padding: 0;
    color: #ffffff;
}

div.sphinxsidebar a {
    color: #98dbcc;
}

div.sphinxsidebar input {
    border: 1px solid #98dbcc;
    font-family: sans-serif;
    font-size: 1em;
}


/* for collapsible sidebar */
div#sidebarbutton {
    background-color: #3c6e83;
}


/* -- hyperlink styles ------------------------------------------------------ */

a {
    color: #355f7c;
    text-decoration: none;
}

a:visited {
    color: #355f7c;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}



/* -- body styles ----------------------------------------------------------- */

div.body h1,
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
    font-family: 'Trebuchet MS', sans-serif;
    background-color: #f2f2f2;
    font-weight: normal;
    color: #20435c;
    border-bottom: 1px solid #ccc;
    margin: 20px -20px 10px -20px;
    padding: 3px 0 3px 10px;
}

div.body h1 { margin-top: 0; font-size: 200%; }
div.body h2 { font-size: 160%; }
div.body h3 { font-size: 140%; }
div.body h4 { font-size: 120%; }
div.body h5 { font-size: 110%; }
div.body h6 { font-size: 100%; }

a.headerlink {
    color: #c60f0f;
    font-size: 0.8em;
    padding: 0 4px 0 4px;
    text-decoration: none;
}

a.headerlink:hover {
    background-color: #c60f0f;
    color: white;
}

div.body p, div.body dd, div.body li, div.body blockquote {
    text-align: justify;
    line-height: 130%;
}

div.admonition p.admonition-title + p {
    display: inline;
}

div.admonition p {
    margin-bottom: 5px;
}

div.admonition pre {
    margin-bottom: 5px;
}

div.admonition ul, div.admonition ol {
    margin-bottom: 5px;
}

div.note {
    background-color: #eee;
    border: 1px solid #ccc;
}

div.seealso {
    background-color: #ffc;
    border: 1px solid #ff6;
}

div.topic {
    background-color: #eee;
}

div.warning {
    background-color: #ffe4e4;
    border: 1px solid #f66;
}

p.admonition-title {
    display: inline;
}

p.admonition-title:after {
    content: ":";
}

pre {
    padding: 5px;
    background-color: #eeffcc;
    color: #333333;
    line-height: 120%;
    border: 1px solid #ac9;
    border-left: none;
    border-right: none;
}

code {
    background-color: #ecf0f3;
    padding: 0 1px 0 1px;
    font-size: 0.95em;
}

th {
    background-color: #ede;
}

.warning code {
    background: #efc2c2;
}

.note code {
    background: #d6d6d6;
}

.viewcode-back {
    font-family: sans-serif;
}

div.viewcode-block:target {
    background-color: #f4debf;
    border-top: 1px solid #ac9;
    border-bottom: 1px solid #ac9;
}

div.code-block-caption {
    color: #efefef;
    background-color: #1c4e63;
}PK
%�\x,���html/_static/comment-bright.pngnu�[����PNG


IHDR�a�IDATx����<�ߙ��m۶m۶q�m۶m۶m��M�=����D��8���tٍ�\{������56��j���>Qn�~3����s�D�{��o��S+ٻ�؀=���n���n���W�?��Xum���A��H�I�%p<Vr��{�̮7.�%���u�'�v�+�t�#?��%ߵ�e��/|��\8��Z�[�xgQ��o	Dq��X�	
ȄF���ޟgU�j+���t�%�7�;*"�Ii�b��[����	e[�[��n�r�7����6_w�9�֭�5S�҄4�,�,�C�"cp�]w\s5����ta(��ch��:��{[/��pŭ������:34��H�E	��?n�<�EZ�(b�F���Z�xb$E�޵�lK�<O���i�~����0EQ��q"	��ޝ����/]�nź�
�W V����ܸ�$Ϸ�Ώ/�ȭ3�򈖭Ϝ4�ԍ�x_Ϸ�6m	
-\�&0@��s��A+���Xl_����ņ	�T�����?ڴ6��۲���C ��v�����B���s�����>Hs�c���Yo�o���_{���Z)48s�ڳ��ۗ���8Y�üYs��j3��4�s^�#ǒ��tˋq�kZ�ܜw�ݿ�ߵ>��!���8��pVn�{�շ�=�n$��p\�^;=��;��wPIEND�B`�PK
%�\5��==html/_static/comment-close.pngnu�[����PNG


IHDR�aIDATxm���8��$�k�m۶m۶m۶m۶�A�M�fp���:�O�'e�$Q�q�
���a��O[��B�3�U�9�O��g+ł-�81d��w=7����q�����1�����C�K�a�~
�ʏ���<��e͛��g�'�y�{�r�Gn���_���.|�5�խ̄Y�<m�x��%޹�U� �����
Z
���P��U �*�#�v�S���~'at5c���~�8"3[��% �2W�0A��|m'x�u�yV���~�	^8�G�Y�X
Ђ���
��L��K����,%�ۏ.�I[��%,�,	V���O��Z�c�� ?p�1��q��m*X��
���/`ـ��J�%�}�5�?��=
{�j��`�2�݂t�յ޾W/�J;DV�m3� �-��$Ƿ���@Z���x�'	�|��7s�=�`{]K<�q���я��	IRJ���Ip�Jm�I�ʲ�ս�(>��l�ϕ���]�����������O�4���l�!A�@@�w���n����y��^���xa*��;1�u�S��W�ݦO<�*�7�g>b�~�yޞ�� mN���\�(�t��:+�tU&>9Z}��O�k=���wԈ=��e��hjo
�O���Sd̳m#�(�2�ڮ�����&�!Q&��<���i�_~�� Y���=����K�eߨO���� �)�\�/&��f������d�����U���@�w��yq�#�9�IEND�B`�PK
%�\4����html/_static/comment.pngnu�[����PNG


IHDR�aHIDATx���_���VT�Vܰ�Qǵ�FT7�m�]��<��M���=�>$�|��~\>&nM����K�<+W	��7�����zɫ����?�w��!���8_�O�
��ާ4�&�
�M�S�'���/қ��=rּ`��V�0!��?t'$�#�'��P`��iawP��������?Dãqف�.`Ž �lZ%9A�{EҺ !;e�`f�T]�P]ZCD���X�2e)ן��r�y�OZs߂Ј
{�1<���*�Bx�����
�`�����(�B4��2|��k@���=�P�A���Țe;�
Hͭ�U���`�B������@(��I��ϚR�
��F�"�a�(.� |R*w���ZB/bZ�	f��M�Q+��d!���!06���5.���9Eq+@3�ى��VSË��d8���;��&KpHh0�f;���h�Y�,]|�Lcne!��f�KcJ�Fiy����S��O�h�מ%ws
���va��J{���ڣ;/S3��?q��c�C��\�q�H���x���sem���k2n<O�
9z��9�ѣ�l�t*�3�IEND�B`�PK
%�\��`x
x
html/_static/copybutton.jsnu�[���$(document).ready(function() {
    /* Add a [>>>] button on the top-right corner of code samples to hide
     * the >>> and ... prompts and the output and thus make the code
     * copyable. */
    var div = $('.highlight-python .highlight,' +
                '.highlight-python3 .highlight')
    var pre = div.find('pre');

    // get the styles from the current theme
    pre.parent().parent().css('position', 'relative');
    var hide_text = 'Hide the prompts and output';
    var show_text = 'Show the prompts and output';
    var border_width = pre.css('border-top-width');
    var border_style = pre.css('border-top-style');
    var border_color = pre.css('border-top-color');
    var button_styles = {
        'cursor':'pointer', 'position': 'absolute', 'top': '0', 'right': '0',
        'border-color': border_color, 'border-style': border_style,
        'border-width': border_width, 'color': border_color, 'text-size': '75%',
        'font-family': 'monospace', 'padding-left': '0.2em', 'padding-right': '0.2em'
    }

    // create and add the button to all the code blocks that contain >>>
    div.each(function(index) {
        var jthis = $(this);
        if (jthis.find('.gp').length > 0) {
            var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
            button.css(button_styles)
            button.attr('title', hide_text);
            button.data('hidden', 'false');
            jthis.prepend(button);
        }
        // tracebacks (.gt) contain bare text elements that need to be
        // wrapped in a span to work with .nextUntil() (see later)
        jthis.find('pre:has(.gt)').contents().filter(function() {
            return ((this.nodeType == 3) && (this.data.trim().length > 0));
        }).wrap('<span>');
    });

    // define the behavior of the button when it's clicked
    $('.copybutton').click(function(e){
        e.preventDefault();
        var button = $(this);
        if (button.data('hidden') === 'false') {
            // hide the code output
            button.parent().find('.go, .gp, .gt').hide();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
            button.css('text-decoration', 'line-through');
            button.attr('title', show_text);
            button.data('hidden', 'true');
        } else {
            // show the code output
            button.parent().find('.go, .gp, .gt').show();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
            button.css('text-decoration', 'none');
            button.attr('title', hide_text);
            button.data('hidden', 'false');
        }
    });
});

PK
%�\_��html/_static/default.cssnu�[���@import url("classic.css");
PK
%�\JO�S$$html/_static/doctools.jsnu�[���/*
 * doctools.js
 * ~~~~~~~~~~~
 *
 * Sphinx JavaScript utilities for all documentation.
 *
 * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */

/**
 * select a different prefix for underscore
 */
$u = _.noConflict();

/**
 * make the code below compatible with browsers without
 * an installed firebug like debugger
if (!window.console || !console.firebug) {
  var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
    "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
    "profile", "profileEnd"];
  window.console = {};
  for (var i = 0; i < names.length; ++i)
    window.console[names[i]] = function() {};
}
 */

/**
 * small helper function to urldecode strings
 */
jQuery.urldecode = function(x) {
  return decodeURIComponent(x).replace(/\+/g, ' ');
};

/**
 * small helper function to urlencode strings
 */
jQuery.urlencode = encodeURIComponent;

/**
 * This function returns the parsed url parameters of the
 * current request. Multiple values per key are supported,
 * it will always return arrays of strings for the value parts.
 */
jQuery.getQueryParameters = function(s) {
  if (typeof s === 'undefined')
    s = document.location.search;
  var parts = s.substr(s.indexOf('?') + 1).split('&');
  var result = {};
  for (var i = 0; i < parts.length; i++) {
    var tmp = parts[i].split('=', 2);
    var key = jQuery.urldecode(tmp[0]);
    var value = jQuery.urldecode(tmp[1]);
    if (key in result)
      result[key].push(value);
    else
      result[key] = [value];
  }
  return result;
};

/**
 * highlight a given string on a jquery object by wrapping it in
 * span elements with the given class name.
 */
jQuery.fn.highlightText = function(text, className) {
  function highlight(node, addItems) {
    if (node.nodeType === 3) {
      var val = node.nodeValue;
      var pos = val.toLowerCase().indexOf(text);
      if (pos >= 0 &&
          !jQuery(node.parentNode).hasClass(className) &&
          !jQuery(node.parentNode).hasClass("nohighlight")) {
        var span;
        var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg");
        if (isInSVG) {
          span = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
        } else {
          span = document.createElement("span");
          span.className = className;
        }
        span.appendChild(document.createTextNode(val.substr(pos, text.length)));
        node.parentNode.insertBefore(span, node.parentNode.insertBefore(
          document.createTextNode(val.substr(pos + text.length)),
          node.nextSibling));
        node.nodeValue = val.substr(0, pos);
        if (isInSVG) {
          var bbox = span.getBBox();
          var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
       	  rect.x.baseVal.value = bbox.x;
          rect.y.baseVal.value = bbox.y;
          rect.width.baseVal.value = bbox.width;
          rect.height.baseVal.value = bbox.height;
          rect.setAttribute('class', className);
          var parentOfText = node.parentNode.parentNode;
          addItems.push({
              "parent": node.parentNode,
              "target": rect});
        }
      }
    }
    else if (!jQuery(node).is("button, select, textarea")) {
      jQuery.each(node.childNodes, function() {
        highlight(this, addItems);
      });
    }
  }
  var addItems = [];
  var result = this.each(function() {
    highlight(this, addItems);
  });
  for (var i = 0; i < addItems.length; ++i) {
    jQuery(addItems[i].parent).before(addItems[i].target);
  }
  return result;
};

/*
 * backward compatibility for jQuery.browser
 * This will be supported until firefox bug is fixed.
 */
if (!jQuery.browser) {
  jQuery.uaMatch = function(ua) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
      /(webkit)[ \/]([\w.]+)/.exec(ua) ||
      /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
      /(msie) ([\w.]+)/.exec(ua) ||
      ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
      [];

    return {
      browser: match[ 1 ] || "",
      version: match[ 2 ] || "0"
    };
  };
  jQuery.browser = {};
  jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
}

/**
 * Small JavaScript module for the documentation.
 */
var Documentation = {

  init : function() {
    this.fixFirefoxAnchorBug();
    this.highlightSearchWords();
    this.initIndexTable();
    
  },

  /**
   * i18n support
   */
  TRANSLATIONS : {},
  PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; },
  LOCALE : 'unknown',

  // gettext and ngettext don't access this so that the functions
  // can safely bound to a different name (_ = Documentation.gettext)
  gettext : function(string) {
    var translated = Documentation.TRANSLATIONS[string];
    if (typeof translated === 'undefined')
      return string;
    return (typeof translated === 'string') ? translated : translated[0];
  },

  ngettext : function(singular, plural, n) {
    var translated = Documentation.TRANSLATIONS[singular];
    if (typeof translated === 'undefined')
      return (n == 1) ? singular : plural;
    return translated[Documentation.PLURALEXPR(n)];
  },

  addTranslations : function(catalog) {
    for (var key in catalog.messages)
      this.TRANSLATIONS[key] = catalog.messages[key];
    this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
    this.LOCALE = catalog.locale;
  },

  /**
   * add context elements like header anchor links
   */
  addContextElements : function() {
    $('div[id] > :header:first').each(function() {
      $('<a class="headerlink">\u00B6</a>').
      attr('href', '#' + this.id).
      attr('title', _('Permalink to this headline')).
      appendTo(this);
    });
    $('dt[id]').each(function() {
      $('<a class="headerlink">\u00B6</a>').
      attr('href', '#' + this.id).
      attr('title', _('Permalink to this definition')).
      appendTo(this);
    });
  },

  /**
   * workaround a firefox stupidity
   * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
   */
  fixFirefoxAnchorBug : function() {
    if (document.location.hash && $.browser.mozilla)
      window.setTimeout(function() {
        document.location.href += '';
      }, 10);
  },

  /**
   * highlight the search words provided in the url in the text
   */
  highlightSearchWords : function() {
    var params = $.getQueryParameters();
    var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
    if (terms.length) {
      var body = $('div.body');
      if (!body.length) {
        body = $('body');
      }
      window.setTimeout(function() {
        $.each(terms, function() {
          body.highlightText(this.toLowerCase(), 'highlighted');
        });
      }, 10);
      $('<p class="highlight-link"><a href="javascript:Documentation.' +
        'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
          .appendTo($('#searchbox'));
    }
  },

  /**
   * init the domain index toggle buttons
   */
  initIndexTable : function() {
    var togglers = $('img.toggler').click(function() {
      var src = $(this).attr('src');
      var idnum = $(this).attr('id').substr(7);
      $('tr.cg-' + idnum).toggle();
      if (src.substr(-9) === 'minus.png')
        $(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
      else
        $(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
    }).css('display', '');
    if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
        togglers.click();
    }
  },

  /**
   * helper function to hide the search marks again
   */
  hideSearchWords : function() {
    $('#searchbox .highlight-link').fadeOut(300);
    $('span.highlighted').removeClass('highlighted');
  },

  /**
   * make the url absolute
   */
  makeURL : function(relativeURL) {
    return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
  },

  /**
   * get the current relative url
   */
  getCurrentURL : function() {
    var path = document.location.pathname;
    var parts = path.split(/\//);
    $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
      if (this === '..')
        parts.pop();
    });
    var url = parts.join('/');
    return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
  },

  initOnKeyListeners: function() {
    $(document).keyup(function(event) {
      var activeElementType = document.activeElement.tagName;
      // don't navigate when in search box or textarea
      if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
        switch (event.keyCode) {
          case 37: // left
            var prevHref = $('link[rel="prev"]').prop('href');
            if (prevHref) {
              window.location.href = prevHref;
              return false;
            }
          case 39: // right
            var nextHref = $('link[rel="next"]').prop('href');
            if (nextHref) {
              window.location.href = nextHref;
              return false;
            }
        }
      }
    });
  }
};

// quick alias for translations
_ = Documentation.gettext;

$(document).ready(function() {
  Documentation.init();
});PK
%�\N�9�%html/_static/documentation_options.jsnu�[���var DOCUMENTATION_OPTIONS = {
    URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'),
    VERSION: '2.7.16',
    LANGUAGE: 'None',
    COLLAPSE_INDEX: false,
    FILE_SUFFIX: '.html',
    HAS_SOURCE: true,
    SOURCELINK_SUFFIX: '.txt'
};PK
%�\�'���html/_static/down-pressed.pngnu�[����PNG


IHDR�a�IDATxc���@�J@lK�f[�^g%_� ����
H��K �Ŀ���D ���A��b3���C�G�hr.��x����/`X��W��ʱ
�2� �e�F�+,.xEJ����lAR�
$�W��T?�0i��)1�m����aU�IEND�B`�PK
%�\9.����html/_static/down.pngnu�[����PNG


IHDR��7��IDATx�����P@��
�@I�ߗ`&�"z6xK@kbϢx�s]��M	�:���/�+�g�Pd�2G�eÐ~�߸J�_�cS_��
S%exdU��]�(UH���>�&����;4�i��$�n�3�>	�y�c��d��IEND�B`�PK
%�\S[�Shtml/_static/file.pngnu�[����PNG


IHDR�a�IDATx���R��){�l� ۶�f�=@���:���3�~箄������rX$A�X-�D	~�
����lj(�P%���8<<9::
��P��O&�$���l~�X����&���EW�^4�wQ}����^���ͣ�
��i���0/H/�@F)�Dzq+��j��[�SU5����h��/�oY�	G&Lfs|�����{����3%�U+S��`AF�IEND�B`�PK
%�\����html/_static/jquery-3.2.1.jsnu�[���/*!
 * jQuery JavaScript Library v3.2.1
 * https://jquery.com/
 *
 * Includes Sizzle.js
 * https://sizzlejs.com/
 *
 * Copyright JS Foundation and other contributors
 * Released under the MIT license
 * https://jquery.org/license
 *
 * Date: 2017-03-20T18:59Z
 */
( function( global, factory ) {

	"use strict";

	if ( typeof module === "object" && typeof module.exports === "object" ) {

		// For CommonJS and CommonJS-like environments where a proper `window`
		// is present, execute the factory and get jQuery.
		// For environments that do not have a `window` with a `document`
		// (such as Node.js), expose a factory as module.exports.
		// This accentuates the need for the creation of a real `window`.
		// e.g. var jQuery = require("jquery")(window);
		// See ticket #14549 for more info.
		module.exports = global.document ?
			factory( global, true ) :
			function( w ) {
				if ( !w.document ) {
					throw new Error( "jQuery requires a window with a document" );
				}
				return factory( w );
			};
	} else {
		factory( global );
	}

// Pass this if window is not defined yet
} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {

// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";

var arr = [];

var document = window.document;

var getProto = Object.getPrototypeOf;

var slice = arr.slice;

var concat = arr.concat;

var push = arr.push;

var indexOf = arr.indexOf;

var class2type = {};

var toString = class2type.toString;

var hasOwn = class2type.hasOwnProperty;

var fnToString = hasOwn.toString;

var ObjectFunctionString = fnToString.call( Object );

var support = {};



	function DOMEval( code, doc ) {
		doc = doc || document;

		var script = doc.createElement( "script" );

		script.text = code;
		doc.head.appendChild( script ).parentNode.removeChild( script );
	}
/* global Symbol */
// Defining this global in .eslintrc.json would create a danger of using the global
// unguarded in another place, it seems safer to define global only for this module



var
	version = "3.2.1",

	// Define a local copy of jQuery
	jQuery = function( selector, context ) {

		// The jQuery object is actually just the init constructor 'enhanced'
		// Need init if jQuery is called (just allow error to be thrown if not included)
		return new jQuery.fn.init( selector, context );
	},

	// Support: Android <=4.0 only
	// Make sure we trim BOM and NBSP
	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

	// Matches dashed string for camelizing
	rmsPrefix = /^-ms-/,
	rdashAlpha = /-([a-z])/g,

	// Used by jQuery.camelCase as callback to replace()
	fcamelCase = function( all, letter ) {
		return letter.toUpperCase();
	};

jQuery.fn = jQuery.prototype = {

	// The current version of jQuery being used
	jquery: version,

	constructor: jQuery,

	// The default length of a jQuery object is 0
	length: 0,

	toArray: function() {
		return slice.call( this );
	},

	// Get the Nth element in the matched element set OR
	// Get the whole matched element set as a clean array
	get: function( num ) {

		// Return all the elements in a clean array
		if ( num == null ) {
			return slice.call( this );
		}

		// Return just the one element from the set
		return num < 0 ? this[ num + this.length ] : this[ num ];
	},

	// Take an array of elements and push it onto the stack
	// (returning the new matched element set)
	pushStack: function( elems ) {

		// Build a new jQuery matched element set
		var ret = jQuery.merge( this.constructor(), elems );

		// Add the old object onto the stack (as a reference)
		ret.prevObject = this;

		// Return the newly-formed element set
		return ret;
	},

	// Execute a callback for every element in the matched set.
	each: function( callback ) {
		return jQuery.each( this, callback );
	},

	map: function( callback ) {
		return this.pushStack( jQuery.map( this, function( elem, i ) {
			return callback.call( elem, i, elem );
		} ) );
	},

	slice: function() {
		return this.pushStack( slice.apply( this, arguments ) );
	},

	first: function() {
		return this.eq( 0 );
	},

	last: function() {
		return this.eq( -1 );
	},

	eq: function( i ) {
		var len = this.length,
			j = +i + ( i < 0 ? len : 0 );
		return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
	},

	end: function() {
		return this.prevObject || this.constructor();
	},

	// For internal use only.
	// Behaves like an Array's method, not like a jQuery method.
	push: push,
	sort: arr.sort,
	splice: arr.splice
};

jQuery.extend = jQuery.fn.extend = function() {
	var options, name, src, copy, copyIsArray, clone,
		target = arguments[ 0 ] || {},
		i = 1,
		length = arguments.length,
		deep = false;

	// Handle a deep copy situation
	if ( typeof target === "boolean" ) {
		deep = target;

		// Skip the boolean and the target
		target = arguments[ i ] || {};
		i++;
	}

	// Handle case when target is a string or something (possible in deep copy)
	if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
		target = {};
	}

	// Extend jQuery itself if only one argument is passed
	if ( i === length ) {
		target = this;
		i--;
	}

	for ( ; i < length; i++ ) {

		// Only deal with non-null/undefined values
		if ( ( options = arguments[ i ] ) != null ) {

			// Extend the base object
			for ( name in options ) {
				src = target[ name ];
				copy = options[ name ];

				// Prevent never-ending loop
				if ( target === copy ) {
					continue;
				}

				// Recurse if we're merging plain objects or arrays
				if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
					( copyIsArray = Array.isArray( copy ) ) ) ) {

					if ( copyIsArray ) {
						copyIsArray = false;
						clone = src && Array.isArray( src ) ? src : [];

					} else {
						clone = src && jQuery.isPlainObject( src ) ? src : {};
					}

					// Never move original objects, clone them
					target[ name ] = jQuery.extend( deep, clone, copy );

				// Don't bring in undefined values
				} else if ( copy !== undefined ) {
					target[ name ] = copy;
				}
			}
		}
	}

	// Return the modified object
	return target;
};

jQuery.extend( {

	// Unique for each copy of jQuery on the page
	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),

	// Assume jQuery is ready without the ready module
	isReady: true,

	error: function( msg ) {
		throw new Error( msg );
	},

	noop: function() {},

	isFunction: function( obj ) {
		return jQuery.type( obj ) === "function";
	},

	isWindow: function( obj ) {
		return obj != null && obj === obj.window;
	},

	isNumeric: function( obj ) {

		// As of jQuery 3.0, isNumeric is limited to
		// strings and numbers (primitives or objects)
		// that can be coerced to finite numbers (gh-2662)
		var type = jQuery.type( obj );
		return ( type === "number" || type === "string" ) &&

			// parseFloat NaNs numeric-cast false positives ("")
			// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
			// subtraction forces infinities to NaN
			!isNaN( obj - parseFloat( obj ) );
	},

	isPlainObject: function( obj ) {
		var proto, Ctor;

		// Detect obvious negatives
		// Use toString instead of jQuery.type to catch host objects
		if ( !obj || toString.call( obj ) !== "[object Object]" ) {
			return false;
		}

		proto = getProto( obj );

		// Objects with no prototype (e.g., `Object.create( null )`) are plain
		if ( !proto ) {
			return true;
		}

		// Objects with prototype are plain iff they were constructed by a global Object function
		Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
		return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
	},

	isEmptyObject: function( obj ) {

		/* eslint-disable no-unused-vars */
		// See https://github.com/eslint/eslint/issues/6125
		var name;

		for ( name in obj ) {
			return false;
		}
		return true;
	},

	type: function( obj ) {
		if ( obj == null ) {
			return obj + "";
		}

		// Support: Android <=2.3 only (functionish RegExp)
		return typeof obj === "object" || typeof obj === "function" ?
			class2type[ toString.call( obj ) ] || "object" :
			typeof obj;
	},

	// Evaluates a script in a global context
	globalEval: function( code ) {
		DOMEval( code );
	},

	// Convert dashed to camelCase; used by the css and data modules
	// Support: IE <=9 - 11, Edge 12 - 13
	// Microsoft forgot to hump their vendor prefix (#9572)
	camelCase: function( string ) {
		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
	},

	each: function( obj, callback ) {
		var length, i = 0;

		if ( isArrayLike( obj ) ) {
			length = obj.length;
			for ( ; i < length; i++ ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		} else {
			for ( i in obj ) {
				if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
					break;
				}
			}
		}

		return obj;
	},

	// Support: Android <=4.0 only
	trim: function( text ) {
		return text == null ?
			"" :
			( text + "" ).replace( rtrim, "" );
	},

	// results is for internal usage only
	makeArray: function( arr, results ) {
		var ret = results || [];

		if ( arr != null ) {
			if ( isArrayLike( Object( arr ) ) ) {
				jQuery.merge( ret,
					typeof arr === "string" ?
					[ arr ] : arr
				);
			} else {
				push.call( ret, arr );
			}
		}

		return ret;
	},

	inArray: function( elem, arr, i ) {
		return arr == null ? -1 : indexOf.call( arr, elem, i );
	},

	// Support: Android <=4.0 only, PhantomJS 1 only
	// push.apply(_, arraylike) throws on ancient WebKit
	merge: function( first, second ) {
		var len = +second.length,
			j = 0,
			i = first.length;

		for ( ; j < len; j++ ) {
			first[ i++ ] = second[ j ];
		}

		first.length = i;

		return first;
	},

	grep: function( elems, callback, invert ) {
		var callbackInverse,
			matches = [],
			i = 0,
			length = elems.length,
			callbackExpect = !invert;

		// Go through the array, only saving the items
		// that pass the validator function
		for ( ; i < length; i++ ) {
			callbackInverse = !callback( elems[ i ], i );
			if ( callbackInverse !== callbackExpect ) {
				matches.push( elems[ i ] );
			}
		}

		return matches;
	},

	// arg is for internal usage only
	map: function( elems, callback, arg ) {
		var length, value,
			i = 0,
			ret = [];

		// Go through the array, translating each of the items to their new values
		if ( isArrayLike( elems ) ) {
			length = elems.length;
			for ( ; i < length; i++ ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}

		// Go through every key on the object,
		} else {
			for ( i in elems ) {
				value = callback( elems[ i ], i, arg );

				if ( value != null ) {
					ret.push( value );
				}
			}
		}

		// Flatten any nested arrays
		return concat.apply( [], ret );
	},

	// A global GUID counter for objects
	guid: 1,

	// Bind a function to a context, optionally partially applying any
	// arguments.
	proxy: function( fn, context ) {
		var tmp, args, proxy;

		if ( typeof context === "string" ) {
			tmp = fn[ context ];
			context = fn;
			fn = tmp;
		}

		// Quick check to determine if target is callable, in the spec
		// this throws a TypeError, but we will just return undefined.
		if ( !jQuery.isFunction( fn ) ) {
			return undefined;
		}

		// Simulated bind
		args = slice.call( arguments, 2 );
		proxy = function() {
			return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
		};

		// Set the guid of unique handler to the same of original handler, so it can be removed
		proxy.guid = fn.guid = fn.guid || jQuery.guid++;

		return proxy;
	},

	now: Date.now,

	// jQuery.support is not used in Core but other projects attach their
	// properties to it so it needs to exist.
	support: support
} );

if ( typeof Symbol === "function" ) {
	jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}

// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
	class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );

function isArrayLike( obj ) {

	// Support: real iOS 8.2 only (not reproducible in simulator)
	// `in` check used to prevent JIT error (gh-2145)
	// hasOwn isn't used here due to false negatives
	// regarding Nodelist length in IE
	var length = !!obj && "length" in obj && obj.length,
		type = jQuery.type( obj );

	if ( type === "function" || jQuery.isWindow( obj ) ) {
		return false;
	}

	return type === "array" || length === 0 ||
		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
 * Sizzle CSS Selector Engine v2.3.3
 * https://sizzlejs.com/
 *
 * Copyright jQuery Foundation and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2016-08-08
 */
(function( window ) {

var i,
	support,
	Expr,
	getText,
	isXML,
	tokenize,
	compile,
	select,
	outermostContext,
	sortInput,
	hasDuplicate,

	// Local document vars
	setDocument,
	document,
	docElem,
	documentIsHTML,
	rbuggyQSA,
	rbuggyMatches,
	matches,
	contains,

	// Instance-specific data
	expando = "sizzle" + 1 * new Date(),
	preferredDoc = window.document,
	dirruns = 0,
	done = 0,
	classCache = createCache(),
	tokenCache = createCache(),
	compilerCache = createCache(),
	sortOrder = function( a, b ) {
		if ( a === b ) {
			hasDuplicate = true;
		}
		return 0;
	},

	// Instance methods
	hasOwn = ({}).hasOwnProperty,
	arr = [],
	pop = arr.pop,
	push_native = arr.push,
	push = arr.push,
	slice = arr.slice,
	// Use a stripped-down indexOf as it's faster than native
	// https://jsperf.com/thor-indexof-vs-for/5
	indexOf = function( list, elem ) {
		var i = 0,
			len = list.length;
		for ( ; i < len; i++ ) {
			if ( list[i] === elem ) {
				return i;
			}
		}
		return -1;
	},

	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",

	// Regular expressions

	// http://www.w3.org/TR/css3-selectors/#whitespace
	whitespace = "[\\x20\\t\\r\\n\\f]",

	// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
	identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",

	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
	attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
		// Operator (capture 2)
		"*([*^$|!~]?=)" + whitespace +
		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
		"*\\]",

	pseudos = ":(" + identifier + ")(?:\\((" +
		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
		// 1. quoted (capture 3; capture 4 or capture 5)
		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
		// 2. simple (capture 6)
		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
		// 3. anything else (capture 2)
		".*" +
		")\\)|)",

	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
	rwhitespace = new RegExp( whitespace + "+", "g" ),
	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),

	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),

	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),

	rpseudo = new RegExp( pseudos ),
	ridentifier = new RegExp( "^" + identifier + "$" ),

	matchExpr = {
		"ID": new RegExp( "^#(" + identifier + ")" ),
		"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
		"TAG": new RegExp( "^(" + identifier + "|[*])" ),
		"ATTR": new RegExp( "^" + attributes ),
		"PSEUDO": new RegExp( "^" + pseudos ),
		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
		// For use in libraries implementing .is()
		// We use this for POS matching in `select`
		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
	},

	rinputs = /^(?:input|select|textarea|button)$/i,
	rheader = /^h\d$/i,

	rnative = /^[^{]+\{\s*\[native \w/,

	// Easily-parseable/retrievable ID or TAG or CLASS selectors
	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,

	rsibling = /[+~]/,

	// CSS escapes
	// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
	funescape = function( _, escaped, escapedWhitespace ) {
		var high = "0x" + escaped - 0x10000;
		// NaN means non-codepoint
		// Support: Firefox<24
		// Workaround erroneous numeric interpretation of +"0x"
		return high !== high || escapedWhitespace ?
			escaped :
			high < 0 ?
				// BMP codepoint
				String.fromCharCode( high + 0x10000 ) :
				// Supplemental Plane codepoint (surrogate pair)
				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
	},

	// CSS string/identifier serialization
	// https://drafts.csswg.org/cssom/#common-serializing-idioms
	rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
	fcssescape = function( ch, asCodePoint ) {
		if ( asCodePoint ) {

			// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
			if ( ch === "\0" ) {
				return "\uFFFD";
			}

			// Control characters and (dependent upon position) numbers get escaped as code points
			return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
		}

		// Other potentially-special ASCII characters get backslash-escaped
		return "\\" + ch;
	},

	// Used for iframes
	// See setDocument()
	// Removing the function wrapper causes a "Permission Denied"
	// error in IE
	unloadHandler = function() {
		setDocument();
	},

	disabledAncestor = addCombinator(
		function( elem ) {
			return elem.disabled === true && ("form" in elem || "label" in elem);
		},
		{ dir: "parentNode", next: "legend" }
	);

// Optimize for push.apply( _, NodeList )
try {
	push.apply(
		(arr = slice.call( preferredDoc.childNodes )),
		preferredDoc.childNodes
	);
	// Support: Android<4.0
	// Detect silently failing push.apply
	arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
	push = { apply: arr.length ?

		// Leverage slice if possible
		function( target, els ) {
			push_native.apply( target, slice.call(els) );
		} :

		// Support: IE<9
		// Otherwise append directly
		function( target, els ) {
			var j = target.length,
				i = 0;
			// Can't trust NodeList.length
			while ( (target[j++] = els[i++]) ) {}
			target.length = j - 1;
		}
	};
}

function Sizzle( selector, context, results, seed ) {
	var m, i, elem, nid, match, groups, newSelector,
		newContext = context && context.ownerDocument,

		// nodeType defaults to 9, since context defaults to document
		nodeType = context ? context.nodeType : 9;

	results = results || [];

	// Return early from calls with invalid selector or context
	if ( typeof selector !== "string" || !selector ||
		nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {

		return results;
	}

	// Try to shortcut find operations (as opposed to filters) in HTML documents
	if ( !seed ) {

		if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
			setDocument( context );
		}
		context = context || document;

		if ( documentIsHTML ) {

			// If the selector is sufficiently simple, try using a "get*By*" DOM method
			// (excepting DocumentFragment context, where the methods don't exist)
			if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {

				// ID selector
				if ( (m = match[1]) ) {

					// Document context
					if ( nodeType === 9 ) {
						if ( (elem = context.getElementById( m )) ) {

							// Support: IE, Opera, Webkit
							// TODO: identify versions
							// getElementById can match elements by name instead of ID
							if ( elem.id === m ) {
								results.push( elem );
								return results;
							}
						} else {
							return results;
						}

					// Element context
					} else {

						// Support: IE, Opera, Webkit
						// TODO: identify versions
						// getElementById can match elements by name instead of ID
						if ( newContext && (elem = newContext.getElementById( m )) &&
							contains( context, elem ) &&
							elem.id === m ) {

							results.push( elem );
							return results;
						}
					}

				// Type selector
				} else if ( match[2] ) {
					push.apply( results, context.getElementsByTagName( selector ) );
					return results;

				// Class selector
				} else if ( (m = match[3]) && support.getElementsByClassName &&
					context.getElementsByClassName ) {

					push.apply( results, context.getElementsByClassName( m ) );
					return results;
				}
			}

			// Take advantage of querySelectorAll
			if ( support.qsa &&
				!compilerCache[ selector + " " ] &&
				(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {

				if ( nodeType !== 1 ) {
					newContext = context;
					newSelector = selector;

				// qSA looks outside Element context, which is not what we want
				// Thanks to Andrew Dupont for this workaround technique
				// Support: IE <=8
				// Exclude object elements
				} else if ( context.nodeName.toLowerCase() !== "object" ) {

					// Capture the context ID, setting it first if necessary
					if ( (nid = context.getAttribute( "id" )) ) {
						nid = nid.replace( rcssescape, fcssescape );
					} else {
						context.setAttribute( "id", (nid = expando) );
					}

					// Prefix every selector in the list
					groups = tokenize( selector );
					i = groups.length;
					while ( i-- ) {
						groups[i] = "#" + nid + " " + toSelector( groups[i] );
					}
					newSelector = groups.join( "," );

					// Expand context for sibling selectors
					newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
						context;
				}

				if ( newSelector ) {
					try {
						push.apply( results,
							newContext.querySelectorAll( newSelector )
						);
						return results;
					} catch ( qsaError ) {
					} finally {
						if ( nid === expando ) {
							context.removeAttribute( "id" );
						}
					}
				}
			}
		}
	}

	// All others
	return select( selector.replace( rtrim, "$1" ), context, results, seed );
}

/**
 * Create key-value caches of limited size
 * @returns {function(string, object)} Returns the Object data after storing it on itself with
 *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
 *	deleting the oldest entry
 */
function createCache() {
	var keys = [];

	function cache( key, value ) {
		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
		if ( keys.push( key + " " ) > Expr.cacheLength ) {
			// Only keep the most recent entries
			delete cache[ keys.shift() ];
		}
		return (cache[ key + " " ] = value);
	}
	return cache;
}

/**
 * Mark a function for special use by Sizzle
 * @param {Function} fn The function to mark
 */
function markFunction( fn ) {
	fn[ expando ] = true;
	return fn;
}

/**
 * Support testing using an element
 * @param {Function} fn Passed the created element and returns a boolean result
 */
function assert( fn ) {
	var el = document.createElement("fieldset");

	try {
		return !!fn( el );
	} catch (e) {
		return false;
	} finally {
		// Remove from its parent by default
		if ( el.parentNode ) {
			el.parentNode.removeChild( el );
		}
		// release memory in IE
		el = null;
	}
}

/**
 * Adds the same handler for all of the specified attrs
 * @param {String} attrs Pipe-separated list of attributes
 * @param {Function} handler The method that will be applied
 */
function addHandle( attrs, handler ) {
	var arr = attrs.split("|"),
		i = arr.length;

	while ( i-- ) {
		Expr.attrHandle[ arr[i] ] = handler;
	}
}

/**
 * Checks document order of two siblings
 * @param {Element} a
 * @param {Element} b
 * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
 */
function siblingCheck( a, b ) {
	var cur = b && a,
		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
			a.sourceIndex - b.sourceIndex;

	// Use IE sourceIndex if available on both nodes
	if ( diff ) {
		return diff;
	}

	// Check if b follows a
	if ( cur ) {
		while ( (cur = cur.nextSibling) ) {
			if ( cur === b ) {
				return -1;
			}
		}
	}

	return a ? 1 : -1;
}

/**
 * Returns a function to use in pseudos for input types
 * @param {String} type
 */
function createInputPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return name === "input" && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for buttons
 * @param {String} type
 */
function createButtonPseudo( type ) {
	return function( elem ) {
		var name = elem.nodeName.toLowerCase();
		return (name === "input" || name === "button") && elem.type === type;
	};
}

/**
 * Returns a function to use in pseudos for :enabled/:disabled
 * @param {Boolean} disabled true for :disabled; false for :enabled
 */
function createDisabledPseudo( disabled ) {

	// Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
	return function( elem ) {

		// Only certain elements can match :enabled or :disabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
		// https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
		if ( "form" in elem ) {

			// Check for inherited disabledness on relevant non-disabled elements:
			// * listed form-associated elements in a disabled fieldset
			//   https://html.spec.whatwg.org/multipage/forms.html#category-listed
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
			// * option elements in a disabled optgroup
			//   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
			// All such elements have a "form" property.
			if ( elem.parentNode && elem.disabled === false ) {

				// Option elements defer to a parent optgroup if present
				if ( "label" in elem ) {
					if ( "label" in elem.parentNode ) {
						return elem.parentNode.disabled === disabled;
					} else {
						return elem.disabled === disabled;
					}
				}

				// Support: IE 6 - 11
				// Use the isDisabled shortcut property to check for disabled fieldset ancestors
				return elem.isDisabled === disabled ||

					// Where there is no isDisabled, check manually
					/* jshint -W018 */
					elem.isDisabled !== !disabled &&
						disabledAncestor( elem ) === disabled;
			}

			return elem.disabled === disabled;

		// Try to winnow out elements that can't be disabled before trusting the disabled property.
		// Some victims get caught in our net (label, legend, menu, track), but it shouldn't
		// even exist on them, let alone have a boolean value.
		} else if ( "label" in elem ) {
			return elem.disabled === disabled;
		}

		// Remaining elements are neither :enabled nor :disabled
		return false;
	};
}

/**
 * Returns a function to use in pseudos for positionals
 * @param {Function} fn
 */
function createPositionalPseudo( fn ) {
	return markFunction(function( argument ) {
		argument = +argument;
		return markFunction(function( seed, matches ) {
			var j,
				matchIndexes = fn( [], seed.length, argument ),
				i = matchIndexes.length;

			// Match elements found at the specified indexes
			while ( i-- ) {
				if ( seed[ (j = matchIndexes[i]) ] ) {
					seed[j] = !(matches[j] = seed[j]);
				}
			}
		});
	});
}

/**
 * Checks a node for validity as a Sizzle context
 * @param {Element|Object=} context
 * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
 */
function testContext( context ) {
	return context && typeof context.getElementsByTagName !== "undefined" && context;
}

// Expose support vars for convenience
support = Sizzle.support = {};

/**
 * Detects XML nodes
 * @param {Element|Object} elem An element or a document
 * @returns {Boolean} True iff elem is a non-HTML XML node
 */
isXML = Sizzle.isXML = function( elem ) {
	// documentElement is verified for cases where it doesn't yet exist
	// (such as loading iframes in IE - #4833)
	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
	return documentElement ? documentElement.nodeName !== "HTML" : false;
};

/**
 * Sets document-related variables once based on the current document
 * @param {Element|Object} [doc] An element or document object to use to set the document
 * @returns {Object} Returns the current document
 */
setDocument = Sizzle.setDocument = function( node ) {
	var hasCompare, subWindow,
		doc = node ? node.ownerDocument || node : preferredDoc;

	// Return early if doc is invalid or already selected
	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
		return document;
	}

	// Update global variables
	document = doc;
	docElem = document.documentElement;
	documentIsHTML = !isXML( document );

	// Support: IE 9-11, Edge
	// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
	if ( preferredDoc !== document &&
		(subWindow = document.defaultView) && subWindow.top !== subWindow ) {

		// Support: IE 11, Edge
		if ( subWindow.addEventListener ) {
			subWindow.addEventListener( "unload", unloadHandler, false );

		// Support: IE 9 - 10 only
		} else if ( subWindow.attachEvent ) {
			subWindow.attachEvent( "onunload", unloadHandler );
		}
	}

	/* Attributes
	---------------------------------------------------------------------- */

	// Support: IE<8
	// Verify that getAttribute really returns attributes and not properties
	// (excepting IE8 booleans)
	support.attributes = assert(function( el ) {
		el.className = "i";
		return !el.getAttribute("className");
	});

	/* getElement(s)By*
	---------------------------------------------------------------------- */

	// Check if getElementsByTagName("*") returns only elements
	support.getElementsByTagName = assert(function( el ) {
		el.appendChild( document.createComment("") );
		return !el.getElementsByTagName("*").length;
	});

	// Support: IE<9
	support.getElementsByClassName = rnative.test( document.getElementsByClassName );

	// Support: IE<10
	// Check if getElementById returns elements by name
	// The broken getElementById methods don't pick up programmatically-set names,
	// so use a roundabout getElementsByName test
	support.getById = assert(function( el ) {
		docElem.appendChild( el ).id = expando;
		return !document.getElementsByName || !document.getElementsByName( expando ).length;
	});

	// ID filter and find
	if ( support.getById ) {
		Expr.filter["ID"] = function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				return elem.getAttribute("id") === attrId;
			};
		};
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var elem = context.getElementById( id );
				return elem ? [ elem ] : [];
			}
		};
	} else {
		Expr.filter["ID"] =  function( id ) {
			var attrId = id.replace( runescape, funescape );
			return function( elem ) {
				var node = typeof elem.getAttributeNode !== "undefined" &&
					elem.getAttributeNode("id");
				return node && node.value === attrId;
			};
		};

		// Support: IE 6 - 7 only
		// getElementById is not reliable as a find shortcut
		Expr.find["ID"] = function( id, context ) {
			if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
				var node, i, elems,
					elem = context.getElementById( id );

				if ( elem ) {

					// Verify the id attribute
					node = elem.getAttributeNode("id");
					if ( node && node.value === id ) {
						return [ elem ];
					}

					// Fall back on getElementsByName
					elems = context.getElementsByName( id );
					i = 0;
					while ( (elem = elems[i++]) ) {
						node = elem.getAttributeNode("id");
						if ( node && node.value === id ) {
							return [ elem ];
						}
					}
				}

				return [];
			}
		};
	}

	// Tag
	Expr.find["TAG"] = support.getElementsByTagName ?
		function( tag, context ) {
			if ( typeof context.getElementsByTagName !== "undefined" ) {
				return context.getElementsByTagName( tag );

			// DocumentFragment nodes don't have gEBTN
			} else if ( support.qsa ) {
				return context.querySelectorAll( tag );
			}
		} :

		function( tag, context ) {
			var elem,
				tmp = [],
				i = 0,
				// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
				results = context.getElementsByTagName( tag );

			// Filter out possible comments
			if ( tag === "*" ) {
				while ( (elem = results[i++]) ) {
					if ( elem.nodeType === 1 ) {
						tmp.push( elem );
					}
				}

				return tmp;
			}
			return results;
		};

	// Class
	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
		if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
			return context.getElementsByClassName( className );
		}
	};

	/* QSA/matchesSelector
	---------------------------------------------------------------------- */

	// QSA and matchesSelector support

	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
	rbuggyMatches = [];

	// qSa(:focus) reports false when true (Chrome 21)
	// We allow this because of a bug in IE8/9 that throws an error
	// whenever `document.activeElement` is accessed on an iframe
	// So, we allow :focus to pass through QSA all the time to avoid the IE error
	// See https://bugs.jquery.com/ticket/13378
	rbuggyQSA = [];

	if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
		// Build QSA regex
		// Regex strategy adopted from Diego Perini
		assert(function( el ) {
			// Select is set to empty string on purpose
			// This is to test IE's treatment of not explicitly
			// setting a boolean content attribute,
			// since its presence should be enough
			// https://bugs.jquery.com/ticket/12359
			docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
				"<select id='" + expando + "-\r\\' msallowcapture=''>" +
				"<option selected=''></option></select>";

			// Support: IE8, Opera 11-12.16
			// Nothing should be selected when empty strings follow ^= or $= or *=
			// The test attribute must be unknown in Opera but "safe" for WinRT
			// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
			if ( el.querySelectorAll("[msallowcapture^='']").length ) {
				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
			}

			// Support: IE8
			// Boolean attributes and "value" are not treated correctly
			if ( !el.querySelectorAll("[selected]").length ) {
				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
			}

			// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
			if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
				rbuggyQSA.push("~=");
			}

			// Webkit/Opera - :checked should return selected option elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			// IE8 throws error here and will not see later tests
			if ( !el.querySelectorAll(":checked").length ) {
				rbuggyQSA.push(":checked");
			}

			// Support: Safari 8+, iOS 8+
			// https://bugs.webkit.org/show_bug.cgi?id=136851
			// In-page `selector#id sibling-combinator selector` fails
			if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
				rbuggyQSA.push(".#.+[+~]");
			}
		});

		assert(function( el ) {
			el.innerHTML = "<a href='' disabled='disabled'></a>" +
				"<select disabled='disabled'><option/></select>";

			// Support: Windows 8 Native Apps
			// The type and name attributes are restricted during .innerHTML assignment
			var input = document.createElement("input");
			input.setAttribute( "type", "hidden" );
			el.appendChild( input ).setAttribute( "name", "D" );

			// Support: IE8
			// Enforce case-sensitivity of name attribute
			if ( el.querySelectorAll("[name=d]").length ) {
				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
			}

			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
			// IE8 throws error here and will not see later tests
			if ( el.querySelectorAll(":enabled").length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Support: IE9-11+
			// IE's :disabled selector does not pick up the children of disabled fieldsets
			docElem.appendChild( el ).disabled = true;
			if ( el.querySelectorAll(":disabled").length !== 2 ) {
				rbuggyQSA.push( ":enabled", ":disabled" );
			}

			// Opera 10-11 does not throw on post-comma invalid pseudos
			el.querySelectorAll("*,:x");
			rbuggyQSA.push(",.*:");
		});
	}

	if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
		docElem.webkitMatchesSelector ||
		docElem.mozMatchesSelector ||
		docElem.oMatchesSelector ||
		docElem.msMatchesSelector) )) ) {

		assert(function( el ) {
			// Check to see if it's possible to do matchesSelector
			// on a disconnected node (IE 9)
			support.disconnectedMatch = matches.call( el, "*" );

			// This should fail with an exception
			// Gecko does not error, returns false instead
			matches.call( el, "[s!='']:x" );
			rbuggyMatches.push( "!=", pseudos );
		});
	}

	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );

	/* Contains
	---------------------------------------------------------------------- */
	hasCompare = rnative.test( docElem.compareDocumentPosition );

	// Element contains another
	// Purposefully self-exclusive
	// As in, an element does not contain itself
	contains = hasCompare || rnative.test( docElem.contains ) ?
		function( a, b ) {
			var adown = a.nodeType === 9 ? a.documentElement : a,
				bup = b && b.parentNode;
			return a === bup || !!( bup && bup.nodeType === 1 && (
				adown.contains ?
					adown.contains( bup ) :
					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
			));
		} :
		function( a, b ) {
			if ( b ) {
				while ( (b = b.parentNode) ) {
					if ( b === a ) {
						return true;
					}
				}
			}
			return false;
		};

	/* Sorting
	---------------------------------------------------------------------- */

	// Document order sorting
	sortOrder = hasCompare ?
	function( a, b ) {

		// Flag for duplicate removal
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		// Sort on method existence if only one input has compareDocumentPosition
		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
		if ( compare ) {
			return compare;
		}

		// Calculate position if both inputs belong to the same document
		compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
			a.compareDocumentPosition( b ) :

			// Otherwise we know they are disconnected
			1;

		// Disconnected nodes
		if ( compare & 1 ||
			(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {

			// Choose the first element that is related to our preferred document
			if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
				return -1;
			}
			if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
				return 1;
			}

			// Maintain original order
			return sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;
		}

		return compare & 4 ? -1 : 1;
	} :
	function( a, b ) {
		// Exit early if the nodes are identical
		if ( a === b ) {
			hasDuplicate = true;
			return 0;
		}

		var cur,
			i = 0,
			aup = a.parentNode,
			bup = b.parentNode,
			ap = [ a ],
			bp = [ b ];

		// Parentless nodes are either documents or disconnected
		if ( !aup || !bup ) {
			return a === document ? -1 :
				b === document ? 1 :
				aup ? -1 :
				bup ? 1 :
				sortInput ?
				( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
				0;

		// If the nodes are siblings, we can do a quick check
		} else if ( aup === bup ) {
			return siblingCheck( a, b );
		}

		// Otherwise we need full lists of their ancestors for comparison
		cur = a;
		while ( (cur = cur.parentNode) ) {
			ap.unshift( cur );
		}
		cur = b;
		while ( (cur = cur.parentNode) ) {
			bp.unshift( cur );
		}

		// Walk down the tree looking for a discrepancy
		while ( ap[i] === bp[i] ) {
			i++;
		}

		return i ?
			// Do a sibling check if the nodes have a common ancestor
			siblingCheck( ap[i], bp[i] ) :

			// Otherwise nodes in our document sort first
			ap[i] === preferredDoc ? -1 :
			bp[i] === preferredDoc ? 1 :
			0;
	};

	return document;
};

Sizzle.matches = function( expr, elements ) {
	return Sizzle( expr, null, null, elements );
};

Sizzle.matchesSelector = function( elem, expr ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	// Make sure that attribute selectors are quoted
	expr = expr.replace( rattributeQuotes, "='$1']" );

	if ( support.matchesSelector && documentIsHTML &&
		!compilerCache[ expr + " " ] &&
		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {

		try {
			var ret = matches.call( elem, expr );

			// IE 9's matchesSelector returns false on disconnected nodes
			if ( ret || support.disconnectedMatch ||
					// As well, disconnected nodes are said to be in a document
					// fragment in IE 9
					elem.document && elem.document.nodeType !== 11 ) {
				return ret;
			}
		} catch (e) {}
	}

	return Sizzle( expr, document, null, [ elem ] ).length > 0;
};

Sizzle.contains = function( context, elem ) {
	// Set document vars if needed
	if ( ( context.ownerDocument || context ) !== document ) {
		setDocument( context );
	}
	return contains( context, elem );
};

Sizzle.attr = function( elem, name ) {
	// Set document vars if needed
	if ( ( elem.ownerDocument || elem ) !== document ) {
		setDocument( elem );
	}

	var fn = Expr.attrHandle[ name.toLowerCase() ],
		// Don't get fooled by Object.prototype properties (jQuery #13807)
		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
			fn( elem, name, !documentIsHTML ) :
			undefined;

	return val !== undefined ?
		val :
		support.attributes || !documentIsHTML ?
			elem.getAttribute( name ) :
			(val = elem.getAttributeNode(name)) && val.specified ?
				val.value :
				null;
};

Sizzle.escape = function( sel ) {
	return (sel + "").replace( rcssescape, fcssescape );
};

Sizzle.error = function( msg ) {
	throw new Error( "Syntax error, unrecognized expression: " + msg );
};

/**
 * Document sorting and removing duplicates
 * @param {ArrayLike} results
 */
Sizzle.uniqueSort = function( results ) {
	var elem,
		duplicates = [],
		j = 0,
		i = 0;

	// Unless we *know* we can detect duplicates, assume their presence
	hasDuplicate = !support.detectDuplicates;
	sortInput = !support.sortStable && results.slice( 0 );
	results.sort( sortOrder );

	if ( hasDuplicate ) {
		while ( (elem = results[i++]) ) {
			if ( elem === results[ i ] ) {
				j = duplicates.push( i );
			}
		}
		while ( j-- ) {
			results.splice( duplicates[ j ], 1 );
		}
	}

	// Clear input after sorting to release objects
	// See https://github.com/jquery/sizzle/pull/225
	sortInput = null;

	return results;
};

/**
 * Utility function for retrieving the text value of an array of DOM nodes
 * @param {Array|Element} elem
 */
getText = Sizzle.getText = function( elem ) {
	var node,
		ret = "",
		i = 0,
		nodeType = elem.nodeType;

	if ( !nodeType ) {
		// If no nodeType, this is expected to be an array
		while ( (node = elem[i++]) ) {
			// Do not traverse comment nodes
			ret += getText( node );
		}
	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
		// Use textContent for elements
		// innerText usage removed for consistency of new lines (jQuery #11153)
		if ( typeof elem.textContent === "string" ) {
			return elem.textContent;
		} else {
			// Traverse its children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				ret += getText( elem );
			}
		}
	} else if ( nodeType === 3 || nodeType === 4 ) {
		return elem.nodeValue;
	}
	// Do not include comment or processing instruction nodes

	return ret;
};

Expr = Sizzle.selectors = {

	// Can be adjusted by the user
	cacheLength: 50,

	createPseudo: markFunction,

	match: matchExpr,

	attrHandle: {},

	find: {},

	relative: {
		">": { dir: "parentNode", first: true },
		" ": { dir: "parentNode" },
		"+": { dir: "previousSibling", first: true },
		"~": { dir: "previousSibling" }
	},

	preFilter: {
		"ATTR": function( match ) {
			match[1] = match[1].replace( runescape, funescape );

			// Move the given value to match[3] whether quoted or unquoted
			match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );

			if ( match[2] === "~=" ) {
				match[3] = " " + match[3] + " ";
			}

			return match.slice( 0, 4 );
		},

		"CHILD": function( match ) {
			/* matches from matchExpr["CHILD"]
				1 type (only|nth|...)
				2 what (child|of-type)
				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
				4 xn-component of xn+y argument ([+-]?\d*n|)
				5 sign of xn-component
				6 x of xn-component
				7 sign of y-component
				8 y of y-component
			*/
			match[1] = match[1].toLowerCase();

			if ( match[1].slice( 0, 3 ) === "nth" ) {
				// nth-* requires argument
				if ( !match[3] ) {
					Sizzle.error( match[0] );
				}

				// numeric x and y parameters for Expr.filter.CHILD
				// remember that false/true cast respectively to 0/1
				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );

			// other types prohibit arguments
			} else if ( match[3] ) {
				Sizzle.error( match[0] );
			}

			return match;
		},

		"PSEUDO": function( match ) {
			var excess,
				unquoted = !match[6] && match[2];

			if ( matchExpr["CHILD"].test( match[0] ) ) {
				return null;
			}

			// Accept quoted arguments as-is
			if ( match[3] ) {
				match[2] = match[4] || match[5] || "";

			// Strip excess characters from unquoted arguments
			} else if ( unquoted && rpseudo.test( unquoted ) &&
				// Get excess from tokenize (recursively)
				(excess = tokenize( unquoted, true )) &&
				// advance to the next closing parenthesis
				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {

				// excess is a negative index
				match[0] = match[0].slice( 0, excess );
				match[2] = unquoted.slice( 0, excess );
			}

			// Return only captures needed by the pseudo filter method (type and argument)
			return match.slice( 0, 3 );
		}
	},

	filter: {

		"TAG": function( nodeNameSelector ) {
			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
			return nodeNameSelector === "*" ?
				function() { return true; } :
				function( elem ) {
					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
				};
		},

		"CLASS": function( className ) {
			var pattern = classCache[ className + " " ];

			return pattern ||
				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
				classCache( className, function( elem ) {
					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
				});
		},

		"ATTR": function( name, operator, check ) {
			return function( elem ) {
				var result = Sizzle.attr( elem, name );

				if ( result == null ) {
					return operator === "!=";
				}
				if ( !operator ) {
					return true;
				}

				result += "";

				return operator === "=" ? result === check :
					operator === "!=" ? result !== check :
					operator === "^=" ? check && result.indexOf( check ) === 0 :
					operator === "*=" ? check && result.indexOf( check ) > -1 :
					operator === "$=" ? check && result.slice( -check.length ) === check :
					operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
					false;
			};
		},

		"CHILD": function( type, what, argument, first, last ) {
			var simple = type.slice( 0, 3 ) !== "nth",
				forward = type.slice( -4 ) !== "last",
				ofType = what === "of-type";

			return first === 1 && last === 0 ?

				// Shortcut for :nth-*(n)
				function( elem ) {
					return !!elem.parentNode;
				} :

				function( elem, context, xml ) {
					var cache, uniqueCache, outerCache, node, nodeIndex, start,
						dir = simple !== forward ? "nextSibling" : "previousSibling",
						parent = elem.parentNode,
						name = ofType && elem.nodeName.toLowerCase(),
						useCache = !xml && !ofType,
						diff = false;

					if ( parent ) {

						// :(first|last|only)-(child|of-type)
						if ( simple ) {
							while ( dir ) {
								node = elem;
								while ( (node = node[ dir ]) ) {
									if ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) {

										return false;
									}
								}
								// Reverse direction for :only-* (if we haven't yet done so)
								start = dir = type === "only" && !start && "nextSibling";
							}
							return true;
						}

						start = [ forward ? parent.firstChild : parent.lastChild ];

						// non-xml :nth-child(...) stores cache data on `parent`
						if ( forward && useCache ) {

							// Seek `elem` from a previously-cached index

							// ...in a gzip-friendly way
							node = parent;
							outerCache = node[ expando ] || (node[ expando ] = {});

							// Support: IE <9 only
							// Defend against cloned attroperties (jQuery gh-1709)
							uniqueCache = outerCache[ node.uniqueID ] ||
								(outerCache[ node.uniqueID ] = {});

							cache = uniqueCache[ type ] || [];
							nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
							diff = nodeIndex && cache[ 2 ];
							node = nodeIndex && parent.childNodes[ nodeIndex ];

							while ( (node = ++nodeIndex && node && node[ dir ] ||

								// Fallback to seeking `elem` from the start
								(diff = nodeIndex = 0) || start.pop()) ) {

								// When found, cache indexes on `parent` and break
								if ( node.nodeType === 1 && ++diff && node === elem ) {
									uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
									break;
								}
							}

						} else {
							// Use previously-cached element index if available
							if ( useCache ) {
								// ...in a gzip-friendly way
								node = elem;
								outerCache = node[ expando ] || (node[ expando ] = {});

								// Support: IE <9 only
								// Defend against cloned attroperties (jQuery gh-1709)
								uniqueCache = outerCache[ node.uniqueID ] ||
									(outerCache[ node.uniqueID ] = {});

								cache = uniqueCache[ type ] || [];
								nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
								diff = nodeIndex;
							}

							// xml :nth-child(...)
							// or :nth-last-child(...) or :nth(-last)?-of-type(...)
							if ( diff === false ) {
								// Use the same loop as above to seek `elem` from the start
								while ( (node = ++nodeIndex && node && node[ dir ] ||
									(diff = nodeIndex = 0) || start.pop()) ) {

									if ( ( ofType ?
										node.nodeName.toLowerCase() === name :
										node.nodeType === 1 ) &&
										++diff ) {

										// Cache the index of each encountered element
										if ( useCache ) {
											outerCache = node[ expando ] || (node[ expando ] = {});

											// Support: IE <9 only
											// Defend against cloned attroperties (jQuery gh-1709)
											uniqueCache = outerCache[ node.uniqueID ] ||
												(outerCache[ node.uniqueID ] = {});

											uniqueCache[ type ] = [ dirruns, diff ];
										}

										if ( node === elem ) {
											break;
										}
									}
								}
							}
						}

						// Incorporate the offset, then check against cycle size
						diff -= last;
						return diff === first || ( diff % first === 0 && diff / first >= 0 );
					}
				};
		},

		"PSEUDO": function( pseudo, argument ) {
			// pseudo-class names are case-insensitive
			// http://www.w3.org/TR/selectors/#pseudo-classes
			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
			// Remember that setFilters inherits from pseudos
			var args,
				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
					Sizzle.error( "unsupported pseudo: " + pseudo );

			// The user may use createPseudo to indicate that
			// arguments are needed to create the filter function
			// just as Sizzle does
			if ( fn[ expando ] ) {
				return fn( argument );
			}

			// But maintain support for old signatures
			if ( fn.length > 1 ) {
				args = [ pseudo, pseudo, "", argument ];
				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
					markFunction(function( seed, matches ) {
						var idx,
							matched = fn( seed, argument ),
							i = matched.length;
						while ( i-- ) {
							idx = indexOf( seed, matched[i] );
							seed[ idx ] = !( matches[ idx ] = matched[i] );
						}
					}) :
					function( elem ) {
						return fn( elem, 0, args );
					};
			}

			return fn;
		}
	},

	pseudos: {
		// Potentially complex pseudos
		"not": markFunction(function( selector ) {
			// Trim the selector passed to compile
			// to avoid treating leading and trailing
			// spaces as combinators
			var input = [],
				results = [],
				matcher = compile( selector.replace( rtrim, "$1" ) );

			return matcher[ expando ] ?
				markFunction(function( seed, matches, context, xml ) {
					var elem,
						unmatched = matcher( seed, null, xml, [] ),
						i = seed.length;

					// Match elements unmatched by `matcher`
					while ( i-- ) {
						if ( (elem = unmatched[i]) ) {
							seed[i] = !(matches[i] = elem);
						}
					}
				}) :
				function( elem, context, xml ) {
					input[0] = elem;
					matcher( input, null, xml, results );
					// Don't keep the element (issue #299)
					input[0] = null;
					return !results.pop();
				};
		}),

		"has": markFunction(function( selector ) {
			return function( elem ) {
				return Sizzle( selector, elem ).length > 0;
			};
		}),

		"contains": markFunction(function( text ) {
			text = text.replace( runescape, funescape );
			return function( elem ) {
				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
			};
		}),

		// "Whether an element is represented by a :lang() selector
		// is based solely on the element's language value
		// being equal to the identifier C,
		// or beginning with the identifier C immediately followed by "-".
		// The matching of C against the element's language value is performed case-insensitively.
		// The identifier C does not have to be a valid language name."
		// http://www.w3.org/TR/selectors/#lang-pseudo
		"lang": markFunction( function( lang ) {
			// lang value must be a valid identifier
			if ( !ridentifier.test(lang || "") ) {
				Sizzle.error( "unsupported lang: " + lang );
			}
			lang = lang.replace( runescape, funescape ).toLowerCase();
			return function( elem ) {
				var elemLang;
				do {
					if ( (elemLang = documentIsHTML ?
						elem.lang :
						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {

						elemLang = elemLang.toLowerCase();
						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
					}
				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
				return false;
			};
		}),

		// Miscellaneous
		"target": function( elem ) {
			var hash = window.location && window.location.hash;
			return hash && hash.slice( 1 ) === elem.id;
		},

		"root": function( elem ) {
			return elem === docElem;
		},

		"focus": function( elem ) {
			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
		},

		// Boolean properties
		"enabled": createDisabledPseudo( false ),
		"disabled": createDisabledPseudo( true ),

		"checked": function( elem ) {
			// In CSS3, :checked should return both checked and selected elements
			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
			var nodeName = elem.nodeName.toLowerCase();
			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
		},

		"selected": function( elem ) {
			// Accessing this property makes selected-by-default
			// options in Safari work properly
			if ( elem.parentNode ) {
				elem.parentNode.selectedIndex;
			}

			return elem.selected === true;
		},

		// Contents
		"empty": function( elem ) {
			// http://www.w3.org/TR/selectors/#empty-pseudo
			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
			//   but not by others (comment: 8; processing instruction: 7; etc.)
			// nodeType < 6 works because attributes (2) do not appear as children
			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
				if ( elem.nodeType < 6 ) {
					return false;
				}
			}
			return true;
		},

		"parent": function( elem ) {
			return !Expr.pseudos["empty"]( elem );
		},

		// Element/input types
		"header": function( elem ) {
			return rheader.test( elem.nodeName );
		},

		"input": function( elem ) {
			return rinputs.test( elem.nodeName );
		},

		"button": function( elem ) {
			var name = elem.nodeName.toLowerCase();
			return name === "input" && elem.type === "button" || name === "button";
		},

		"text": function( elem ) {
			var attr;
			return elem.nodeName.toLowerCase() === "input" &&
				elem.type === "text" &&

				// Support: IE<8
				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
		},

		// Position-in-collection
		"first": createPositionalPseudo(function() {
			return [ 0 ];
		}),

		"last": createPositionalPseudo(function( matchIndexes, length ) {
			return [ length - 1 ];
		}),

		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
			return [ argument < 0 ? argument + length : argument ];
		}),

		"even": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 0;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"odd": createPositionalPseudo(function( matchIndexes, length ) {
			var i = 1;
			for ( ; i < length; i += 2 ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; --i >= 0; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		}),

		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
			var i = argument < 0 ? argument + length : argument;
			for ( ; ++i < length; ) {
				matchIndexes.push( i );
			}
			return matchIndexes;
		})
	}
};

Expr.pseudos["nth"] = Expr.pseudos["eq"];

// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
	Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
	Expr.pseudos[ i ] = createButtonPseudo( i );
}

// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();

tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
	var matched, match, tokens, type,
		soFar, groups, preFilters,
		cached = tokenCache[ selector + " " ];

	if ( cached ) {
		return parseOnly ? 0 : cached.slice( 0 );
	}

	soFar = selector;
	groups = [];
	preFilters = Expr.preFilter;

	while ( soFar ) {

		// Comma and first run
		if ( !matched || (match = rcomma.exec( soFar )) ) {
			if ( match ) {
				// Don't consume trailing commas as valid
				soFar = soFar.slice( match[0].length ) || soFar;
			}
			groups.push( (tokens = []) );
		}

		matched = false;

		// Combinators
		if ( (match = rcombinators.exec( soFar )) ) {
			matched = match.shift();
			tokens.push({
				value: matched,
				// Cast descendant combinators to space
				type: match[0].replace( rtrim, " " )
			});
			soFar = soFar.slice( matched.length );
		}

		// Filters
		for ( type in Expr.filter ) {
			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
				(match = preFilters[ type ]( match ))) ) {
				matched = match.shift();
				tokens.push({
					value: matched,
					type: type,
					matches: match
				});
				soFar = soFar.slice( matched.length );
			}
		}

		if ( !matched ) {
			break;
		}
	}

	// Return the length of the invalid excess
	// if we're just parsing
	// Otherwise, throw an error or return tokens
	return parseOnly ?
		soFar.length :
		soFar ?
			Sizzle.error( selector ) :
			// Cache the tokens
			tokenCache( selector, groups ).slice( 0 );
};

function toSelector( tokens ) {
	var i = 0,
		len = tokens.length,
		selector = "";
	for ( ; i < len; i++ ) {
		selector += tokens[i].value;
	}
	return selector;
}

function addCombinator( matcher, combinator, base ) {
	var dir = combinator.dir,
		skip = combinator.next,
		key = skip || dir,
		checkNonElements = base && key === "parentNode",
		doneName = done++;

	return combinator.first ?
		// Check against closest ancestor/preceding element
		function( elem, context, xml ) {
			while ( (elem = elem[ dir ]) ) {
				if ( elem.nodeType === 1 || checkNonElements ) {
					return matcher( elem, context, xml );
				}
			}
			return false;
		} :

		// Check against all ancestor/preceding elements
		function( elem, context, xml ) {
			var oldCache, uniqueCache, outerCache,
				newCache = [ dirruns, doneName ];

			// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
			if ( xml ) {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						if ( matcher( elem, context, xml ) ) {
							return true;
						}
					}
				}
			} else {
				while ( (elem = elem[ dir ]) ) {
					if ( elem.nodeType === 1 || checkNonElements ) {
						outerCache = elem[ expando ] || (elem[ expando ] = {});

						// Support: IE <9 only
						// Defend against cloned attroperties (jQuery gh-1709)
						uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});

						if ( skip && skip === elem.nodeName.toLowerCase() ) {
							elem = elem[ dir ] || elem;
						} else if ( (oldCache = uniqueCache[ key ]) &&
							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {

							// Assign to newCache so results back-propagate to previous elements
							return (newCache[ 2 ] = oldCache[ 2 ]);
						} else {
							// Reuse newcache so results back-propagate to previous elements
							uniqueCache[ key ] = newCache;

							// A match means we're done; a fail means we have to keep checking
							if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
								return true;
							}
						}
					}
				}
			}
			return false;
		};
}

function elementMatcher( matchers ) {
	return matchers.length > 1 ?
		function( elem, context, xml ) {
			var i = matchers.length;
			while ( i-- ) {
				if ( !matchers[i]( elem, context, xml ) ) {
					return false;
				}
			}
			return true;
		} :
		matchers[0];
}

function multipleContexts( selector, contexts, results ) {
	var i = 0,
		len = contexts.length;
	for ( ; i < len; i++ ) {
		Sizzle( selector, contexts[i], results );
	}
	return results;
}

function condense( unmatched, map, filter, context, xml ) {
	var elem,
		newUnmatched = [],
		i = 0,
		len = unmatched.length,
		mapped = map != null;

	for ( ; i < len; i++ ) {
		if ( (elem = unmatched[i]) ) {
			if ( !filter || filter( elem, context, xml ) ) {
				newUnmatched.push( elem );
				if ( mapped ) {
					map.push( i );
				}
			}
		}
	}

	return newUnmatched;
}

function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
	if ( postFilter && !postFilter[ expando ] ) {
		postFilter = setMatcher( postFilter );
	}
	if ( postFinder && !postFinder[ expando ] ) {
		postFinder = setMatcher( postFinder, postSelector );
	}
	return markFunction(function( seed, results, context, xml ) {
		var temp, i, elem,
			preMap = [],
			postMap = [],
			preexisting = results.length,

			// Get initial elements from seed or context
			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),

			// Prefilter to get matcher input, preserving a map for seed-results synchronization
			matcherIn = preFilter && ( seed || !selector ) ?
				condense( elems, preMap, preFilter, context, xml ) :
				elems,

			matcherOut = matcher ?
				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?

					// ...intermediate processing is necessary
					[] :

					// ...otherwise use results directly
					results :
				matcherIn;

		// Find primary matches
		if ( matcher ) {
			matcher( matcherIn, matcherOut, context, xml );
		}

		// Apply postFilter
		if ( postFilter ) {
			temp = condense( matcherOut, postMap );
			postFilter( temp, [], context, xml );

			// Un-match failing elements by moving them back to matcherIn
			i = temp.length;
			while ( i-- ) {
				if ( (elem = temp[i]) ) {
					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
				}
			}
		}

		if ( seed ) {
			if ( postFinder || preFilter ) {
				if ( postFinder ) {
					// Get the final matcherOut by condensing this intermediate into postFinder contexts
					temp = [];
					i = matcherOut.length;
					while ( i-- ) {
						if ( (elem = matcherOut[i]) ) {
							// Restore matcherIn since elem is not yet a final match
							temp.push( (matcherIn[i] = elem) );
						}
					}
					postFinder( null, (matcherOut = []), temp, xml );
				}

				// Move matched elements from seed to results to keep them synchronized
				i = matcherOut.length;
				while ( i-- ) {
					if ( (elem = matcherOut[i]) &&
						(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {

						seed[temp] = !(results[temp] = elem);
					}
				}
			}

		// Add elements to results, through postFinder if defined
		} else {
			matcherOut = condense(
				matcherOut === results ?
					matcherOut.splice( preexisting, matcherOut.length ) :
					matcherOut
			);
			if ( postFinder ) {
				postFinder( null, results, matcherOut, xml );
			} else {
				push.apply( results, matcherOut );
			}
		}
	});
}

function matcherFromTokens( tokens ) {
	var checkContext, matcher, j,
		len = tokens.length,
		leadingRelative = Expr.relative[ tokens[0].type ],
		implicitRelative = leadingRelative || Expr.relative[" "],
		i = leadingRelative ? 1 : 0,

		// The foundational matcher ensures that elements are reachable from top-level context(s)
		matchContext = addCombinator( function( elem ) {
			return elem === checkContext;
		}, implicitRelative, true ),
		matchAnyContext = addCombinator( function( elem ) {
			return indexOf( checkContext, elem ) > -1;
		}, implicitRelative, true ),
		matchers = [ function( elem, context, xml ) {
			var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
				(checkContext = context).nodeType ?
					matchContext( elem, context, xml ) :
					matchAnyContext( elem, context, xml ) );
			// Avoid hanging onto element (issue #299)
			checkContext = null;
			return ret;
		} ];

	for ( ; i < len; i++ ) {
		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
		} else {
			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );

			// Return special upon seeing a positional matcher
			if ( matcher[ expando ] ) {
				// Find the next relative operator (if any) for proper handling
				j = ++i;
				for ( ; j < len; j++ ) {
					if ( Expr.relative[ tokens[j].type ] ) {
						break;
					}
				}
				return setMatcher(
					i > 1 && elementMatcher( matchers ),
					i > 1 && toSelector(
						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
					).replace( rtrim, "$1" ),
					matcher,
					i < j && matcherFromTokens( tokens.slice( i, j ) ),
					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
					j < len && toSelector( tokens )
				);
			}
			matchers.push( matcher );
		}
	}

	return elementMatcher( matchers );
}

function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
	var bySet = setMatchers.length > 0,
		byElement = elementMatchers.length > 0,
		superMatcher = function( seed, context, xml, results, outermost ) {
			var elem, j, matcher,
				matchedCount = 0,
				i = "0",
				unmatched = seed && [],
				setMatched = [],
				contextBackup = outermostContext,
				// We must always have either seed elements or outermost context
				elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
				// Use integer dirruns iff this is the outermost matcher
				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
				len = elems.length;

			if ( outermost ) {
				outermostContext = context === document || context || outermost;
			}

			// Add elements passing elementMatchers directly to results
			// Support: IE<9, Safari
			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
			for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
				if ( byElement && elem ) {
					j = 0;
					if ( !context && elem.ownerDocument !== document ) {
						setDocument( elem );
						xml = !documentIsHTML;
					}
					while ( (matcher = elementMatchers[j++]) ) {
						if ( matcher( elem, context || document, xml) ) {
							results.push( elem );
							break;
						}
					}
					if ( outermost ) {
						dirruns = dirrunsUnique;
					}
				}

				// Track unmatched elements for set filters
				if ( bySet ) {
					// They will have gone through all possible matchers
					if ( (elem = !matcher && elem) ) {
						matchedCount--;
					}

					// Lengthen the array for every element, matched or not
					if ( seed ) {
						unmatched.push( elem );
					}
				}
			}

			// `i` is now the count of elements visited above, and adding it to `matchedCount`
			// makes the latter nonnegative.
			matchedCount += i;

			// Apply set filters to unmatched elements
			// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
			// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
			// no element matchers and no seed.
			// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
			// case, which will result in a "00" `matchedCount` that differs from `i` but is also
			// numerically zero.
			if ( bySet && i !== matchedCount ) {
				j = 0;
				while ( (matcher = setMatchers[j++]) ) {
					matcher( unmatched, setMatched, context, xml );
				}

				if ( seed ) {
					// Reintegrate element matches to eliminate the need for sorting
					if ( matchedCount > 0 ) {
						while ( i-- ) {
							if ( !(unmatched[i] || setMatched[i]) ) {
								setMatched[i] = pop.call( results );
							}
						}
					}

					// Discard index placeholder values to get only actual matches
					setMatched = condense( setMatched );
				}

				// Add matches to results
				push.apply( results, setMatched );

				// Seedless set matches succeeding multiple successful matchers stipulate sorting
				if ( outermost && !seed && setMatched.length > 0 &&
					( matchedCount + setMatchers.length ) > 1 ) {

					Sizzle.uniqueSort( results );
				}
			}

			// Override manipulation of globals by nested matchers
			if ( outermost ) {
				dirruns = dirrunsUnique;
				outermostContext = contextBackup;
			}

			return unmatched;
		};

	return bySet ?
		markFunction( superMatcher ) :
		superMatcher;
}

compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
	var i,
		setMatchers = [],
		elementMatchers = [],
		cached = compilerCache[ selector + " " ];

	if ( !cached ) {
		// Generate a function of recursive functions that can be used to check each element
		if ( !match ) {
			match = tokenize( selector );
		}
		i = match.length;
		while ( i-- ) {
			cached = matcherFromTokens( match[i] );
			if ( cached[ expando ] ) {
				setMatchers.push( cached );
			} else {
				elementMatchers.push( cached );
			}
		}

		// Cache the compiled function
		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );

		// Save selector and tokenization
		cached.selector = selector;
	}
	return cached;
};

/**
 * A low-level selection function that works with Sizzle's compiled
 *  selector functions
 * @param {String|Function} selector A selector or a pre-compiled
 *  selector function built with Sizzle.compile
 * @param {Element} context
 * @param {Array} [results]
 * @param {Array} [seed] A set of elements to match against
 */
select = Sizzle.select = function( selector, context, results, seed ) {
	var i, tokens, token, type, find,
		compiled = typeof selector === "function" && selector,
		match = !seed && tokenize( (selector = compiled.selector || selector) );

	results = results || [];

	// Try to minimize operations if there is only one selector in the list and no seed
	// (the latter of which guarantees us context)
	if ( match.length === 1 ) {

		// Reduce context if the leading compound selector is an ID
		tokens = match[0] = match[0].slice( 0 );
		if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
				context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) {

			context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
			if ( !context ) {
				return results;

			// Precompiled matchers will still verify ancestry, so step up a level
			} else if ( compiled ) {
				context = context.parentNode;
			}

			selector = selector.slice( tokens.shift().value.length );
		}

		// Fetch a seed set for right-to-left matching
		i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
		while ( i-- ) {
			token = tokens[i];

			// Abort if we hit a combinator
			if ( Expr.relative[ (type = token.type) ] ) {
				break;
			}
			if ( (find = Expr.find[ type ]) ) {
				// Search, expanding context for leading sibling combinators
				if ( (seed = find(
					token.matches[0].replace( runescape, funescape ),
					rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
				)) ) {

					// If seed is empty or no tokens remain, we can return early
					tokens.splice( i, 1 );
					selector = seed.length && toSelector( tokens );
					if ( !selector ) {
						push.apply( results, seed );
						return results;
					}

					break;
				}
			}
		}
	}

	// Compile and execute a filtering function if one is not provided
	// Provide `match` to avoid retokenization if we modified the selector above
	( compiled || compile( selector, match ) )(
		seed,
		context,
		!documentIsHTML,
		results,
		!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
	);
	return results;
};

// One-time assignments

// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;

// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;

// Initialize against the default document
setDocument();

// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( el ) {
	// Should return 1, but returns 4 (following)
	return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});

// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
	el.innerHTML = "<a href='#'></a>";
	return el.firstChild.getAttribute("href") === "#" ;
}) ) {
	addHandle( "type|href|height|width", function( elem, name, isXML ) {
		if ( !isXML ) {
			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
		}
	});
}

// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( el ) {
	el.innerHTML = "<input/>";
	el.firstChild.setAttribute( "value", "" );
	return el.firstChild.getAttribute( "value" ) === "";
}) ) {
	addHandle( "value", function( elem, name, isXML ) {
		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
			return elem.defaultValue;
		}
	});
}

// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( el ) {
	return el.getAttribute("disabled") == null;
}) ) {
	addHandle( booleans, function( elem, name, isXML ) {
		var val;
		if ( !isXML ) {
			return elem[ name ] === true ? name.toLowerCase() :
					(val = elem.getAttributeNode( name )) && val.specified ?
					val.value :
				null;
		}
	});
}

return Sizzle;

})( window );



jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;

// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;




var dir = function( elem, dir, until ) {
	var matched = [],
		truncate = until !== undefined;

	while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
		if ( elem.nodeType === 1 ) {
			if ( truncate && jQuery( elem ).is( until ) ) {
				break;
			}
			matched.push( elem );
		}
	}
	return matched;
};


var siblings = function( n, elem ) {
	var matched = [];

	for ( ; n; n = n.nextSibling ) {
		if ( n.nodeType === 1 && n !== elem ) {
			matched.push( n );
		}
	}

	return matched;
};


var rneedsContext = jQuery.expr.match.needsContext;



function nodeName( elem, name ) {

  return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();

};
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );



var risSimple = /^.[^:#\[\.,]*$/;

// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
	if ( jQuery.isFunction( qualifier ) ) {
		return jQuery.grep( elements, function( elem, i ) {
			return !!qualifier.call( elem, i, elem ) !== not;
		} );
	}

	// Single element
	if ( qualifier.nodeType ) {
		return jQuery.grep( elements, function( elem ) {
			return ( elem === qualifier ) !== not;
		} );
	}

	// Arraylike of elements (jQuery, arguments, Array)
	if ( typeof qualifier !== "string" ) {
		return jQuery.grep( elements, function( elem ) {
			return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
		} );
	}

	// Simple selector that can be filtered directly, removing non-Elements
	if ( risSimple.test( qualifier ) ) {
		return jQuery.filter( qualifier, elements, not );
	}

	// Complex selector, compare the two sets, removing non-Elements
	qualifier = jQuery.filter( qualifier, elements );
	return jQuery.grep( elements, function( elem ) {
		return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
	} );
}

jQuery.filter = function( expr, elems, not ) {
	var elem = elems[ 0 ];

	if ( not ) {
		expr = ":not(" + expr + ")";
	}

	if ( elems.length === 1 && elem.nodeType === 1 ) {
		return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
	}

	return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
		return elem.nodeType === 1;
	} ) );
};

jQuery.fn.extend( {
	find: function( selector ) {
		var i, ret,
			len = this.length,
			self = this;

		if ( typeof selector !== "string" ) {
			return this.pushStack( jQuery( selector ).filter( function() {
				for ( i = 0; i < len; i++ ) {
					if ( jQuery.contains( self[ i ], this ) ) {
						return true;
					}
				}
			} ) );
		}

		ret = this.pushStack( [] );

		for ( i = 0; i < len; i++ ) {
			jQuery.find( selector, self[ i ], ret );
		}

		return len > 1 ? jQuery.uniqueSort( ret ) : ret;
	},
	filter: function( selector ) {
		return this.pushStack( winnow( this, selector || [], false ) );
	},
	not: function( selector ) {
		return this.pushStack( winnow( this, selector || [], true ) );
	},
	is: function( selector ) {
		return !!winnow(
			this,

			// If this is a positional/relative selector, check membership in the returned set
			// so $("p:first").is("p:last") won't return true for a doc with two "p".
			typeof selector === "string" && rneedsContext.test( selector ) ?
				jQuery( selector ) :
				selector || [],
			false
		).length;
	}
} );


// Initialize a jQuery object


// A central reference to the root jQuery(document)
var rootjQuery,

	// A simple way to check for HTML strings
	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
	// Strict HTML recognition (#11290: must start with <)
	// Shortcut simple #id case for speed
	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,

	init = jQuery.fn.init = function( selector, context, root ) {
		var match, elem;

		// HANDLE: $(""), $(null), $(undefined), $(false)
		if ( !selector ) {
			return this;
		}

		// Method init() accepts an alternate rootjQuery
		// so migrate can support jQuery.sub (gh-2101)
		root = root || rootjQuery;

		// Handle HTML strings
		if ( typeof selector === "string" ) {
			if ( selector[ 0 ] === "<" &&
				selector[ selector.length - 1 ] === ">" &&
				selector.length >= 3 ) {

				// Assume that strings that start and end with <> are HTML and skip the regex check
				match = [ null, selector, null ];

			} else {
				match = rquickExpr.exec( selector );
			}

			// Match html or make sure no context is specified for #id
			if ( match && ( match[ 1 ] || !context ) ) {

				// HANDLE: $(html) -> $(array)
				if ( match[ 1 ] ) {
					context = context instanceof jQuery ? context[ 0 ] : context;

					// Option to run scripts is true for back-compat
					// Intentionally let the error be thrown if parseHTML is not present
					jQuery.merge( this, jQuery.parseHTML(
						match[ 1 ],
						context && context.nodeType ? context.ownerDocument || context : document,
						true
					) );

					// HANDLE: $(html, props)
					if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
						for ( match in context ) {

							// Properties of context are called as methods if possible
							if ( jQuery.isFunction( this[ match ] ) ) {
								this[ match ]( context[ match ] );

							// ...and otherwise set as attributes
							} else {
								this.attr( match, context[ match ] );
							}
						}
					}

					return this;

				// HANDLE: $(#id)
				} else {
					elem = document.getElementById( match[ 2 ] );

					if ( elem ) {

						// Inject the element directly into the jQuery object
						this[ 0 ] = elem;
						this.length = 1;
					}
					return this;
				}

			// HANDLE: $(expr, $(...))
			} else if ( !context || context.jquery ) {
				return ( context || root ).find( selector );

			// HANDLE: $(expr, context)
			// (which is just equivalent to: $(context).find(expr)
			} else {
				return this.constructor( context ).find( selector );
			}

		// HANDLE: $(DOMElement)
		} else if ( selector.nodeType ) {
			this[ 0 ] = selector;
			this.length = 1;
			return this;

		// HANDLE: $(function)
		// Shortcut for document ready
		} else if ( jQuery.isFunction( selector ) ) {
			return root.ready !== undefined ?
				root.ready( selector ) :

				// Execute immediately if ready is not present
				selector( jQuery );
		}

		return jQuery.makeArray( selector, this );
	};

// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;

// Initialize central reference
rootjQuery = jQuery( document );


var rparentsprev = /^(?:parents|prev(?:Until|All))/,

	// Methods guaranteed to produce a unique set when starting from a unique set
	guaranteedUnique = {
		children: true,
		contents: true,
		next: true,
		prev: true
	};

jQuery.fn.extend( {
	has: function( target ) {
		var targets = jQuery( target, this ),
			l = targets.length;

		return this.filter( function() {
			var i = 0;
			for ( ; i < l; i++ ) {
				if ( jQuery.contains( this, targets[ i ] ) ) {
					return true;
				}
			}
		} );
	},

	closest: function( selectors, context ) {
		var cur,
			i = 0,
			l = this.length,
			matched = [],
			targets = typeof selectors !== "string" && jQuery( selectors );

		// Positional selectors never match, since there's no _selection_ context
		if ( !rneedsContext.test( selectors ) ) {
			for ( ; i < l; i++ ) {
				for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {

					// Always skip document fragments
					if ( cur.nodeType < 11 && ( targets ?
						targets.index( cur ) > -1 :

						// Don't pass non-elements to Sizzle
						cur.nodeType === 1 &&
							jQuery.find.matchesSelector( cur, selectors ) ) ) {

						matched.push( cur );
						break;
					}
				}
			}
		}

		return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
	},

	// Determine the position of an element within the set
	index: function( elem ) {

		// No argument, return index in parent
		if ( !elem ) {
			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
		}

		// Index in selector
		if ( typeof elem === "string" ) {
			return indexOf.call( jQuery( elem ), this[ 0 ] );
		}

		// Locate the position of the desired element
		return indexOf.call( this,

			// If it receives a jQuery object, the first element is used
			elem.jquery ? elem[ 0 ] : elem
		);
	},

	add: function( selector, context ) {
		return this.pushStack(
			jQuery.uniqueSort(
				jQuery.merge( this.get(), jQuery( selector, context ) )
			)
		);
	},

	addBack: function( selector ) {
		return this.add( selector == null ?
			this.prevObject : this.prevObject.filter( selector )
		);
	}
} );

function sibling( cur, dir ) {
	while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
	return cur;
}

jQuery.each( {
	parent: function( elem ) {
		var parent = elem.parentNode;
		return parent && parent.nodeType !== 11 ? parent : null;
	},
	parents: function( elem ) {
		return dir( elem, "parentNode" );
	},
	parentsUntil: function( elem, i, until ) {
		return dir( elem, "parentNode", until );
	},
	next: function( elem ) {
		return sibling( elem, "nextSibling" );
	},
	prev: function( elem ) {
		return sibling( elem, "previousSibling" );
	},
	nextAll: function( elem ) {
		return dir( elem, "nextSibling" );
	},
	prevAll: function( elem ) {
		return dir( elem, "previousSibling" );
	},
	nextUntil: function( elem, i, until ) {
		return dir( elem, "nextSibling", until );
	},
	prevUntil: function( elem, i, until ) {
		return dir( elem, "previousSibling", until );
	},
	siblings: function( elem ) {
		return siblings( ( elem.parentNode || {} ).firstChild, elem );
	},
	children: function( elem ) {
		return siblings( elem.firstChild );
	},
	contents: function( elem ) {
        if ( nodeName( elem, "iframe" ) ) {
            return elem.contentDocument;
        }

        // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
        // Treat the template element as a regular one in browsers that
        // don't support it.
        if ( nodeName( elem, "template" ) ) {
            elem = elem.content || elem;
        }

        return jQuery.merge( [], elem.childNodes );
	}
}, function( name, fn ) {
	jQuery.fn[ name ] = function( until, selector ) {
		var matched = jQuery.map( this, fn, until );

		if ( name.slice( -5 ) !== "Until" ) {
			selector = until;
		}

		if ( selector && typeof selector === "string" ) {
			matched = jQuery.filter( selector, matched );
		}

		if ( this.length > 1 ) {

			// Remove duplicates
			if ( !guaranteedUnique[ name ] ) {
				jQuery.uniqueSort( matched );
			}

			// Reverse order for parents* and prev-derivatives
			if ( rparentsprev.test( name ) ) {
				matched.reverse();
			}
		}

		return this.pushStack( matched );
	};
} );
var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );



// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
	var object = {};
	jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
		object[ flag ] = true;
	} );
	return object;
}

/*
 * Create a callback list using the following parameters:
 *
 *	options: an optional list of space-separated options that will change how
 *			the callback list behaves or a more traditional option object
 *
 * By default a callback list will act like an event callback list and can be
 * "fired" multiple times.
 *
 * Possible options:
 *
 *	once:			will ensure the callback list can only be fired once (like a Deferred)
 *
 *	memory:			will keep track of previous values and will call any callback added
 *					after the list has been fired right away with the latest "memorized"
 *					values (like a Deferred)
 *
 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
 *
 *	stopOnFalse:	interrupt callings when a callback returns false
 *
 */
jQuery.Callbacks = function( options ) {

	// Convert options from String-formatted to Object-formatted if needed
	// (we check in cache first)
	options = typeof options === "string" ?
		createOptions( options ) :
		jQuery.extend( {}, options );

	var // Flag to know if list is currently firing
		firing,

		// Last fire value for non-forgettable lists
		memory,

		// Flag to know if list was already fired
		fired,

		// Flag to prevent firing
		locked,

		// Actual callback list
		list = [],

		// Queue of execution data for repeatable lists
		queue = [],

		// Index of currently firing callback (modified by add/remove as needed)
		firingIndex = -1,

		// Fire callbacks
		fire = function() {

			// Enforce single-firing
			locked = locked || options.once;

			// Execute callbacks for all pending executions,
			// respecting firingIndex overrides and runtime changes
			fired = firing = true;
			for ( ; queue.length; firingIndex = -1 ) {
				memory = queue.shift();
				while ( ++firingIndex < list.length ) {

					// Run callback and check for early termination
					if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
						options.stopOnFalse ) {

						// Jump to end and forget the data so .add doesn't re-fire
						firingIndex = list.length;
						memory = false;
					}
				}
			}

			// Forget the data if we're done with it
			if ( !options.memory ) {
				memory = false;
			}

			firing = false;

			// Clean up if we're done firing for good
			if ( locked ) {

				// Keep an empty list if we have data for future add calls
				if ( memory ) {
					list = [];

				// Otherwise, this object is spent
				} else {
					list = "";
				}
			}
		},

		// Actual Callbacks object
		self = {

			// Add a callback or a collection of callbacks to the list
			add: function() {
				if ( list ) {

					// If we have memory from a past run, we should fire after adding
					if ( memory && !firing ) {
						firingIndex = list.length - 1;
						queue.push( memory );
					}

					( function add( args ) {
						jQuery.each( args, function( _, arg ) {
							if ( jQuery.isFunction( arg ) ) {
								if ( !options.unique || !self.has( arg ) ) {
									list.push( arg );
								}
							} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {

								// Inspect recursively
								add( arg );
							}
						} );
					} )( arguments );

					if ( memory && !firing ) {
						fire();
					}
				}
				return this;
			},

			// Remove a callback from the list
			remove: function() {
				jQuery.each( arguments, function( _, arg ) {
					var index;
					while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
						list.splice( index, 1 );

						// Handle firing indexes
						if ( index <= firingIndex ) {
							firingIndex--;
						}
					}
				} );
				return this;
			},

			// Check if a given callback is in the list.
			// If no argument is given, return whether or not list has callbacks attached.
			has: function( fn ) {
				return fn ?
					jQuery.inArray( fn, list ) > -1 :
					list.length > 0;
			},

			// Remove all callbacks from the list
			empty: function() {
				if ( list ) {
					list = [];
				}
				return this;
			},

			// Disable .fire and .add
			// Abort any current/pending executions
			// Clear all callbacks and values
			disable: function() {
				locked = queue = [];
				list = memory = "";
				return this;
			},
			disabled: function() {
				return !list;
			},

			// Disable .fire
			// Also disable .add unless we have memory (since it would have no effect)
			// Abort any pending executions
			lock: function() {
				locked = queue = [];
				if ( !memory && !firing ) {
					list = memory = "";
				}
				return this;
			},
			locked: function() {
				return !!locked;
			},

			// Call all callbacks with the given context and arguments
			fireWith: function( context, args ) {
				if ( !locked ) {
					args = args || [];
					args = [ context, args.slice ? args.slice() : args ];
					queue.push( args );
					if ( !firing ) {
						fire();
					}
				}
				return this;
			},

			// Call all the callbacks with the given arguments
			fire: function() {
				self.fireWith( this, arguments );
				return this;
			},

			// To know if the callbacks have already been called at least once
			fired: function() {
				return !!fired;
			}
		};

	return self;
};


function Identity( v ) {
	return v;
}
function Thrower( ex ) {
	throw ex;
}

function adoptValue( value, resolve, reject, noValue ) {
	var method;

	try {

		// Check for promise aspect first to privilege synchronous behavior
		if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
			method.call( value ).done( resolve ).fail( reject );

		// Other thenables
		} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
			method.call( value, resolve, reject );

		// Other non-thenables
		} else {

			// Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
			// * false: [ value ].slice( 0 ) => resolve( value )
			// * true: [ value ].slice( 1 ) => resolve()
			resolve.apply( undefined, [ value ].slice( noValue ) );
		}

	// For Promises/A+, convert exceptions into rejections
	// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
	// Deferred#then to conditionally suppress rejection.
	} catch ( value ) {

		// Support: Android 4.0 only
		// Strict mode functions invoked without .call/.apply get global-object context
		reject.apply( undefined, [ value ] );
	}
}

jQuery.extend( {

	Deferred: function( func ) {
		var tuples = [

				// action, add listener, callbacks,
				// ... .then handlers, argument index, [final state]
				[ "notify", "progress", jQuery.Callbacks( "memory" ),
					jQuery.Callbacks( "memory" ), 2 ],
				[ "resolve", "done", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 0, "resolved" ],
				[ "reject", "fail", jQuery.Callbacks( "once memory" ),
					jQuery.Callbacks( "once memory" ), 1, "rejected" ]
			],
			state = "pending",
			promise = {
				state: function() {
					return state;
				},
				always: function() {
					deferred.done( arguments ).fail( arguments );
					return this;
				},
				"catch": function( fn ) {
					return promise.then( null, fn );
				},

				// Keep pipe for back-compat
				pipe: function( /* fnDone, fnFail, fnProgress */ ) {
					var fns = arguments;

					return jQuery.Deferred( function( newDefer ) {
						jQuery.each( tuples, function( i, tuple ) {

							// Map tuples (progress, done, fail) to arguments (done, fail, progress)
							var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];

							// deferred.progress(function() { bind to newDefer or newDefer.notify })
							// deferred.done(function() { bind to newDefer or newDefer.resolve })
							// deferred.fail(function() { bind to newDefer or newDefer.reject })
							deferred[ tuple[ 1 ] ]( function() {
								var returned = fn && fn.apply( this, arguments );
								if ( returned && jQuery.isFunction( returned.promise ) ) {
									returned.promise()
										.progress( newDefer.notify )
										.done( newDefer.resolve )
										.fail( newDefer.reject );
								} else {
									newDefer[ tuple[ 0 ] + "With" ](
										this,
										fn ? [ returned ] : arguments
									);
								}
							} );
						} );
						fns = null;
					} ).promise();
				},
				then: function( onFulfilled, onRejected, onProgress ) {
					var maxDepth = 0;
					function resolve( depth, deferred, handler, special ) {
						return function() {
							var that = this,
								args = arguments,
								mightThrow = function() {
									var returned, then;

									// Support: Promises/A+ section 2.3.3.3.3
									// https://promisesaplus.com/#point-59
									// Ignore double-resolution attempts
									if ( depth < maxDepth ) {
										return;
									}

									returned = handler.apply( that, args );

									// Support: Promises/A+ section 2.3.1
									// https://promisesaplus.com/#point-48
									if ( returned === deferred.promise() ) {
										throw new TypeError( "Thenable self-resolution" );
									}

									// Support: Promises/A+ sections 2.3.3.1, 3.5
									// https://promisesaplus.com/#point-54
									// https://promisesaplus.com/#point-75
									// Retrieve `then` only once
									then = returned &&

										// Support: Promises/A+ section 2.3.4
										// https://promisesaplus.com/#point-64
										// Only check objects and functions for thenability
										( typeof returned === "object" ||
											typeof returned === "function" ) &&
										returned.then;

									// Handle a returned thenable
									if ( jQuery.isFunction( then ) ) {

										// Special processors (notify) just wait for resolution
										if ( special ) {
											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special )
											);

										// Normal processors (resolve) also hook into progress
										} else {

											// ...and disregard older resolution values
											maxDepth++;

											then.call(
												returned,
												resolve( maxDepth, deferred, Identity, special ),
												resolve( maxDepth, deferred, Thrower, special ),
												resolve( maxDepth, deferred, Identity,
													deferred.notifyWith )
											);
										}

									// Handle all other returned values
									} else {

										// Only substitute handlers pass on context
										// and multiple values (non-spec behavior)
										if ( handler !== Identity ) {
											that = undefined;
											args = [ returned ];
										}

										// Process the value(s)
										// Default process is resolve
										( special || deferred.resolveWith )( that, args );
									}
								},

								// Only normal processors (resolve) catch and reject exceptions
								process = special ?
									mightThrow :
									function() {
										try {
											mightThrow();
										} catch ( e ) {

											if ( jQuery.Deferred.exceptionHook ) {
												jQuery.Deferred.exceptionHook( e,
													process.stackTrace );
											}

											// Support: Promises/A+ section 2.3.3.3.4.1
											// https://promisesaplus.com/#point-61
											// Ignore post-resolution exceptions
											if ( depth + 1 >= maxDepth ) {

												// Only substitute handlers pass on context
												// and multiple values (non-spec behavior)
												if ( handler !== Thrower ) {
													that = undefined;
													args = [ e ];
												}

												deferred.rejectWith( that, args );
											}
										}
									};

							// Support: Promises/A+ section 2.3.3.3.1
							// https://promisesaplus.com/#point-57
							// Re-resolve promises immediately to dodge false rejection from
							// subsequent errors
							if ( depth ) {
								process();
							} else {

								// Call an optional hook to record the stack, in case of exception
								// since it's otherwise lost when execution goes async
								if ( jQuery.Deferred.getStackHook ) {
									process.stackTrace = jQuery.Deferred.getStackHook();
								}
								window.setTimeout( process );
							}
						};
					}

					return jQuery.Deferred( function( newDefer ) {

						// progress_handlers.add( ... )
						tuples[ 0 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								jQuery.isFunction( onProgress ) ?
									onProgress :
									Identity,
								newDefer.notifyWith
							)
						);

						// fulfilled_handlers.add( ... )
						tuples[ 1 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								jQuery.isFunction( onFulfilled ) ?
									onFulfilled :
									Identity
							)
						);

						// rejected_handlers.add( ... )
						tuples[ 2 ][ 3 ].add(
							resolve(
								0,
								newDefer,
								jQuery.isFunction( onRejected ) ?
									onRejected :
									Thrower
							)
						);
					} ).promise();
				},

				// Get a promise for this deferred
				// If obj is provided, the promise aspect is added to the object
				promise: function( obj ) {
					return obj != null ? jQuery.extend( obj, promise ) : promise;
				}
			},
			deferred = {};

		// Add list-specific methods
		jQuery.each( tuples, function( i, tuple ) {
			var list = tuple[ 2 ],
				stateString = tuple[ 5 ];

			// promise.progress = list.add
			// promise.done = list.add
			// promise.fail = list.add
			promise[ tuple[ 1 ] ] = list.add;

			// Handle state
			if ( stateString ) {
				list.add(
					function() {

						// state = "resolved" (i.e., fulfilled)
						// state = "rejected"
						state = stateString;
					},

					// rejected_callbacks.disable
					// fulfilled_callbacks.disable
					tuples[ 3 - i ][ 2 ].disable,

					// progress_callbacks.lock
					tuples[ 0 ][ 2 ].lock
				);
			}

			// progress_handlers.fire
			// fulfilled_handlers.fire
			// rejected_handlers.fire
			list.add( tuple[ 3 ].fire );

			// deferred.notify = function() { deferred.notifyWith(...) }
			// deferred.resolve = function() { deferred.resolveWith(...) }
			// deferred.reject = function() { deferred.rejectWith(...) }
			deferred[ tuple[ 0 ] ] = function() {
				deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
				return this;
			};

			// deferred.notifyWith = list.fireWith
			// deferred.resolveWith = list.fireWith
			// deferred.rejectWith = list.fireWith
			deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
		} );

		// Make the deferred a promise
		promise.promise( deferred );

		// Call given func if any
		if ( func ) {
			func.call( deferred, deferred );
		}

		// All done!
		return deferred;
	},

	// Deferred helper
	when: function( singleValue ) {
		var

			// count of uncompleted subordinates
			remaining = arguments.length,

			// count of unprocessed arguments
			i = remaining,

			// subordinate fulfillment data
			resolveContexts = Array( i ),
			resolveValues = slice.call( arguments ),

			// the master Deferred
			master = jQuery.Deferred(),

			// subordinate callback factory
			updateFunc = function( i ) {
				return function( value ) {
					resolveContexts[ i ] = this;
					resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
					if ( !( --remaining ) ) {
						master.resolveWith( resolveContexts, resolveValues );
					}
				};
			};

		// Single- and empty arguments are adopted like Promise.resolve
		if ( remaining <= 1 ) {
			adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject,
				!remaining );

			// Use .then() to unwrap secondary thenables (cf. gh-3000)
			if ( master.state() === "pending" ||
				jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {

				return master.then();
			}
		}

		// Multiple arguments are aggregated like Promise.all array elements
		while ( i-- ) {
			adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
		}

		return master.promise();
	}
} );


// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;

jQuery.Deferred.exceptionHook = function( error, stack ) {

	// Support: IE 8 - 9 only
	// Console exists when dev tools are open, which can happen at any time
	if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
		window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
	}
};




jQuery.readyException = function( error ) {
	window.setTimeout( function() {
		throw error;
	} );
};




// The deferred used on DOM ready
var readyList = jQuery.Deferred();

jQuery.fn.ready = function( fn ) {

	readyList
		.then( fn )

		// Wrap jQuery.readyException in a function so that the lookup
		// happens at the time of error handling instead of callback
		// registration.
		.catch( function( error ) {
			jQuery.readyException( error );
		} );

	return this;
};

jQuery.extend( {

	// Is the DOM ready to be used? Set to true once it occurs.
	isReady: false,

	// A counter to track how many items to wait for before
	// the ready event fires. See #6781
	readyWait: 1,

	// Handle when the DOM is ready
	ready: function( wait ) {

		// Abort if there are pending holds or we're already ready
		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
			return;
		}

		// Remember that the DOM is ready
		jQuery.isReady = true;

		// If a normal DOM Ready event fired, decrement, and wait if need be
		if ( wait !== true && --jQuery.readyWait > 0 ) {
			return;
		}

		// If there are functions bound, to execute
		readyList.resolveWith( document, [ jQuery ] );
	}
} );

jQuery.ready.then = readyList.then;

// The ready event handler and self cleanup method
function completed() {
	document.removeEventListener( "DOMContentLoaded", completed );
	window.removeEventListener( "load", completed );
	jQuery.ready();
}

// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
	( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {

	// Handle it asynchronously to allow scripts the opportunity to delay ready
	window.setTimeout( jQuery.ready );

} else {

	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", completed );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", completed );
}




// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,
		len = elems.length,
		bulk = key == null;

	// Sets many values
	if ( jQuery.type( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			access( elems, fn, i, key[ i ], true, emptyGet, raw );
		}

	// Sets one value
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !jQuery.isFunction( value ) ) {
			raw = true;
		}

		if ( bulk ) {

			// Bulk operations run against the entire set
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			} else {
				bulk = fn;
				fn = function( elem, key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {
			for ( ; i < len; i++ ) {
				fn(
					elems[ i ], key, raw ?
					value :
					value.call( elems[ i ], i, fn( elems[ i ], key ) )
				);
			}
		}
	}

	if ( chainable ) {
		return elems;
	}

	// Gets
	if ( bulk ) {
		return fn.call( elems );
	}

	return len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {

	// Accepts only:
	//  - Node
	//    - Node.ELEMENT_NODE
	//    - Node.DOCUMENT_NODE
	//  - Object
	//    - Any
	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};




function Data() {
	this.expando = jQuery.expando + Data.uid++;
}

Data.uid = 1;

Data.prototype = {

	cache: function( owner ) {

		// Check if the owner object already has a cache
		var value = owner[ this.expando ];

		// If not, create one
		if ( !value ) {
			value = {};

			// We can accept data for non-element nodes in modern browsers,
			// but we should not, see #8335.
			// Always return an empty object.
			if ( acceptData( owner ) ) {

				// If it is a node unlikely to be stringify-ed or looped over
				// use plain assignment
				if ( owner.nodeType ) {
					owner[ this.expando ] = value;

				// Otherwise secure it in a non-enumerable property
				// configurable must be true to allow the property to be
				// deleted when data is removed
				} else {
					Object.defineProperty( owner, this.expando, {
						value: value,
						configurable: true
					} );
				}
			}
		}

		return value;
	},
	set: function( owner, data, value ) {
		var prop,
			cache = this.cache( owner );

		// Handle: [ owner, key, value ] args
		// Always use camelCase key (gh-2257)
		if ( typeof data === "string" ) {
			cache[ jQuery.camelCase( data ) ] = value;

		// Handle: [ owner, { properties } ] args
		} else {

			// Copy the properties one-by-one to the cache object
			for ( prop in data ) {
				cache[ jQuery.camelCase( prop ) ] = data[ prop ];
			}
		}
		return cache;
	},
	get: function( owner, key ) {
		return key === undefined ?
			this.cache( owner ) :

			// Always use camelCase key (gh-2257)
			owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
	},
	access: function( owner, key, value ) {

		// In cases where either:
		//
		//   1. No key was specified
		//   2. A string key was specified, but no value provided
		//
		// Take the "read" path and allow the get method to determine
		// which value to return, respectively either:
		//
		//   1. The entire cache object
		//   2. The data stored at the key
		//
		if ( key === undefined ||
				( ( key && typeof key === "string" ) && value === undefined ) ) {

			return this.get( owner, key );
		}

		// When the key is not a string, or both a key and value
		// are specified, set or extend (existing objects) with either:
		//
		//   1. An object of properties
		//   2. A key and value
		//
		this.set( owner, key, value );

		// Since the "set" path can have two possible entry points
		// return the expected data based on which path was taken[*]
		return value !== undefined ? value : key;
	},
	remove: function( owner, key ) {
		var i,
			cache = owner[ this.expando ];

		if ( cache === undefined ) {
			return;
		}

		if ( key !== undefined ) {

			// Support array or space separated string of keys
			if ( Array.isArray( key ) ) {

				// If key is an array of keys...
				// We always set camelCase keys, so remove that.
				key = key.map( jQuery.camelCase );
			} else {
				key = jQuery.camelCase( key );

				// If a key with the spaces exists, use it.
				// Otherwise, create an array by matching non-whitespace
				key = key in cache ?
					[ key ] :
					( key.match( rnothtmlwhite ) || [] );
			}

			i = key.length;

			while ( i-- ) {
				delete cache[ key[ i ] ];
			}
		}

		// Remove the expando if there's no more data
		if ( key === undefined || jQuery.isEmptyObject( cache ) ) {

			// Support: Chrome <=35 - 45
			// Webkit & Blink performance suffers when deleting properties
			// from DOM nodes, so set to undefined instead
			// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
			if ( owner.nodeType ) {
				owner[ this.expando ] = undefined;
			} else {
				delete owner[ this.expando ];
			}
		}
	},
	hasData: function( owner ) {
		var cache = owner[ this.expando ];
		return cache !== undefined && !jQuery.isEmptyObject( cache );
	}
};
var dataPriv = new Data();

var dataUser = new Data();



//	Implementation Summary
//
//	1. Enforce API surface and semantic compatibility with 1.9.x branch
//	2. Improve the module's maintainability by reducing the storage
//		paths to a single mechanism.
//	3. Use the same single mechanism to support "private" and "user" data.
//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
//	5. Avoid exposing implementation details on user objects (eg. expando properties)
//	6. Provide a clear path for implementation upgrade to WeakMap in 2014

var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
	rmultiDash = /[A-Z]/g;

function getData( data ) {
	if ( data === "true" ) {
		return true;
	}

	if ( data === "false" ) {
		return false;
	}

	if ( data === "null" ) {
		return null;
	}

	// Only convert to a number if it doesn't change the string
	if ( data === +data + "" ) {
		return +data;
	}

	if ( rbrace.test( data ) ) {
		return JSON.parse( data );
	}

	return data;
}

function dataAttr( elem, key, data ) {
	var name;

	// If nothing was found internally, try to fetch any
	// data from the HTML5 data-* attribute
	if ( data === undefined && elem.nodeType === 1 ) {
		name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
		data = elem.getAttribute( name );

		if ( typeof data === "string" ) {
			try {
				data = getData( data );
			} catch ( e ) {}

			// Make sure we set the data so it isn't changed later
			dataUser.set( elem, key, data );
		} else {
			data = undefined;
		}
	}
	return data;
}

jQuery.extend( {
	hasData: function( elem ) {
		return dataUser.hasData( elem ) || dataPriv.hasData( elem );
	},

	data: function( elem, name, data ) {
		return dataUser.access( elem, name, data );
	},

	removeData: function( elem, name ) {
		dataUser.remove( elem, name );
	},

	// TODO: Now that all calls to _data and _removeData have been replaced
	// with direct calls to dataPriv methods, these can be deprecated.
	_data: function( elem, name, data ) {
		return dataPriv.access( elem, name, data );
	},

	_removeData: function( elem, name ) {
		dataPriv.remove( elem, name );
	}
} );

jQuery.fn.extend( {
	data: function( key, value ) {
		var i, name, data,
			elem = this[ 0 ],
			attrs = elem && elem.attributes;

		// Gets all values
		if ( key === undefined ) {
			if ( this.length ) {
				data = dataUser.get( elem );

				if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
					i = attrs.length;
					while ( i-- ) {

						// Support: IE 11 only
						// The attrs elements can be null (#14894)
						if ( attrs[ i ] ) {
							name = attrs[ i ].name;
							if ( name.indexOf( "data-" ) === 0 ) {
								name = jQuery.camelCase( name.slice( 5 ) );
								dataAttr( elem, name, data[ name ] );
							}
						}
					}
					dataPriv.set( elem, "hasDataAttrs", true );
				}
			}

			return data;
		}

		// Sets multiple values
		if ( typeof key === "object" ) {
			return this.each( function() {
				dataUser.set( this, key );
			} );
		}

		return access( this, function( value ) {
			var data;

			// The calling jQuery object (element matches) is not empty
			// (and therefore has an element appears at this[ 0 ]) and the
			// `value` parameter was not undefined. An empty jQuery object
			// will result in `undefined` for elem = this[ 0 ] which will
			// throw an exception if an attempt to read a data cache is made.
			if ( elem && value === undefined ) {

				// Attempt to get data from the cache
				// The key will always be camelCased in Data
				data = dataUser.get( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// Attempt to "discover" the data in
				// HTML5 custom data-* attrs
				data = dataAttr( elem, key );
				if ( data !== undefined ) {
					return data;
				}

				// We tried really hard, but the data doesn't exist.
				return;
			}

			// Set the data...
			this.each( function() {

				// We always store the camelCased key
				dataUser.set( this, key, value );
			} );
		}, null, value, arguments.length > 1, null, true );
	},

	removeData: function( key ) {
		return this.each( function() {
			dataUser.remove( this, key );
		} );
	}
} );


jQuery.extend( {
	queue: function( elem, type, data ) {
		var queue;

		if ( elem ) {
			type = ( type || "fx" ) + "queue";
			queue = dataPriv.get( elem, type );

			// Speed up dequeue by getting out quickly if this is just a lookup
			if ( data ) {
				if ( !queue || Array.isArray( data ) ) {
					queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
				} else {
					queue.push( data );
				}
			}
			return queue || [];
		}
	},

	dequeue: function( elem, type ) {
		type = type || "fx";

		var queue = jQuery.queue( elem, type ),
			startLength = queue.length,
			fn = queue.shift(),
			hooks = jQuery._queueHooks( elem, type ),
			next = function() {
				jQuery.dequeue( elem, type );
			};

		// If the fx queue is dequeued, always remove the progress sentinel
		if ( fn === "inprogress" ) {
			fn = queue.shift();
			startLength--;
		}

		if ( fn ) {

			// Add a progress sentinel to prevent the fx queue from being
			// automatically dequeued
			if ( type === "fx" ) {
				queue.unshift( "inprogress" );
			}

			// Clear up the last queue stop function
			delete hooks.stop;
			fn.call( elem, next, hooks );
		}

		if ( !startLength && hooks ) {
			hooks.empty.fire();
		}
	},

	// Not public - generate a queueHooks object, or return the current one
	_queueHooks: function( elem, type ) {
		var key = type + "queueHooks";
		return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
			empty: jQuery.Callbacks( "once memory" ).add( function() {
				dataPriv.remove( elem, [ type + "queue", key ] );
			} )
		} );
	}
} );

jQuery.fn.extend( {
	queue: function( type, data ) {
		var setter = 2;

		if ( typeof type !== "string" ) {
			data = type;
			type = "fx";
			setter--;
		}

		if ( arguments.length < setter ) {
			return jQuery.queue( this[ 0 ], type );
		}

		return data === undefined ?
			this :
			this.each( function() {
				var queue = jQuery.queue( this, type, data );

				// Ensure a hooks for this queue
				jQuery._queueHooks( this, type );

				if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
					jQuery.dequeue( this, type );
				}
			} );
	},
	dequeue: function( type ) {
		return this.each( function() {
			jQuery.dequeue( this, type );
		} );
	},
	clearQueue: function( type ) {
		return this.queue( type || "fx", [] );
	},

	// Get a promise resolved when queues of a certain type
	// are emptied (fx is the type by default)
	promise: function( type, obj ) {
		var tmp,
			count = 1,
			defer = jQuery.Deferred(),
			elements = this,
			i = this.length,
			resolve = function() {
				if ( !( --count ) ) {
					defer.resolveWith( elements, [ elements ] );
				}
			};

		if ( typeof type !== "string" ) {
			obj = type;
			type = undefined;
		}
		type = type || "fx";

		while ( i-- ) {
			tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
			if ( tmp && tmp.empty ) {
				count++;
				tmp.empty.add( resolve );
			}
		}
		resolve();
		return defer.promise( obj );
	}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;

var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );


var cssExpand = [ "Top", "Right", "Bottom", "Left" ];

var isHiddenWithinTree = function( elem, el ) {

		// isHiddenWithinTree might be called from jQuery#filter function;
		// in that case, element will be second argument
		elem = el || elem;

		// Inline style trumps all
		return elem.style.display === "none" ||
			elem.style.display === "" &&

			// Otherwise, check computed style
			// Support: Firefox <=43 - 45
			// Disconnected elements can have computed display: none, so first confirm that elem is
			// in the document.
			jQuery.contains( elem.ownerDocument, elem ) &&

			jQuery.css( elem, "display" ) === "none";
	};

var swap = function( elem, options, callback, args ) {
	var ret, name,
		old = {};

	// Remember the old values, and insert the new ones
	for ( name in options ) {
		old[ name ] = elem.style[ name ];
		elem.style[ name ] = options[ name ];
	}

	ret = callback.apply( elem, args || [] );

	// Revert the old values
	for ( name in options ) {
		elem.style[ name ] = old[ name ];
	}

	return ret;
};




function adjustCSS( elem, prop, valueParts, tween ) {
	var adjusted,
		scale = 1,
		maxIterations = 20,
		currentValue = tween ?
			function() {
				return tween.cur();
			} :
			function() {
				return jQuery.css( elem, prop, "" );
			},
		initial = currentValue(),
		unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),

		// Starting value computation is required for potential unit mismatches
		initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
			rcssNum.exec( jQuery.css( elem, prop ) );

	if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {

		// Trust units reported by jQuery.css
		unit = unit || initialInUnit[ 3 ];

		// Make sure we update the tween properties later on
		valueParts = valueParts || [];

		// Iteratively approximate from a nonzero starting point
		initialInUnit = +initial || 1;

		do {

			// If previous iteration zeroed out, double until we get *something*.
			// Use string for doubling so we don't accidentally see scale as unchanged below
			scale = scale || ".5";

			// Adjust and apply
			initialInUnit = initialInUnit / scale;
			jQuery.style( elem, prop, initialInUnit + unit );

		// Update scale, tolerating zero or NaN from tween.cur()
		// Break the loop if scale is unchanged or perfect, or if we've just had enough.
		} while (
			scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
		);
	}

	if ( valueParts ) {
		initialInUnit = +initialInUnit || +initial || 0;

		// Apply relative offset (+=/-=) if specified
		adjusted = valueParts[ 1 ] ?
			initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
			+valueParts[ 2 ];
		if ( tween ) {
			tween.unit = unit;
			tween.start = initialInUnit;
			tween.end = adjusted;
		}
	}
	return adjusted;
}


var defaultDisplayMap = {};

function getDefaultDisplay( elem ) {
	var temp,
		doc = elem.ownerDocument,
		nodeName = elem.nodeName,
		display = defaultDisplayMap[ nodeName ];

	if ( display ) {
		return display;
	}

	temp = doc.body.appendChild( doc.createElement( nodeName ) );
	display = jQuery.css( temp, "display" );

	temp.parentNode.removeChild( temp );

	if ( display === "none" ) {
		display = "block";
	}
	defaultDisplayMap[ nodeName ] = display;

	return display;
}

function showHide( elements, show ) {
	var display, elem,
		values = [],
		index = 0,
		length = elements.length;

	// Determine new display value for elements that need to change
	for ( ; index < length; index++ ) {
		elem = elements[ index ];
		if ( !elem.style ) {
			continue;
		}

		display = elem.style.display;
		if ( show ) {

			// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
			// check is required in this first loop unless we have a nonempty display value (either
			// inline or about-to-be-restored)
			if ( display === "none" ) {
				values[ index ] = dataPriv.get( elem, "display" ) || null;
				if ( !values[ index ] ) {
					elem.style.display = "";
				}
			}
			if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
				values[ index ] = getDefaultDisplay( elem );
			}
		} else {
			if ( display !== "none" ) {
				values[ index ] = "none";

				// Remember what we're overwriting
				dataPriv.set( elem, "display", display );
			}
		}
	}

	// Set the display of the elements in a second loop to avoid constant reflow
	for ( index = 0; index < length; index++ ) {
		if ( values[ index ] != null ) {
			elements[ index ].style.display = values[ index ];
		}
	}

	return elements;
}

jQuery.fn.extend( {
	show: function() {
		return showHide( this, true );
	},
	hide: function() {
		return showHide( this );
	},
	toggle: function( state ) {
		if ( typeof state === "boolean" ) {
			return state ? this.show() : this.hide();
		}

		return this.each( function() {
			if ( isHiddenWithinTree( this ) ) {
				jQuery( this ).show();
			} else {
				jQuery( this ).hide();
			}
		} );
	}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );

var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );

var rscriptType = ( /^$|\/(?:java|ecma)script/i );



// We have to close these tags to support XHTML (#13200)
var wrapMap = {

	// Support: IE <=9 only
	option: [ 1, "<select multiple='multiple'>", "</select>" ],

	// XHTML parsers do not magically insert elements in the
	// same way that tag soup parsers do. So we cannot shorten
	// this by omitting <tbody> or other required elements.
	thead: [ 1, "<table>", "</table>" ],
	col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
	tr: [ 2, "<table><tbody>", "</tbody></table>" ],
	td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],

	_default: [ 0, "", "" ]
};

// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;

wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;


function getAll( context, tag ) {

	// Support: IE <=9 - 11 only
	// Use typeof to avoid zero-argument method invocation on host objects (#15151)
	var ret;

	if ( typeof context.getElementsByTagName !== "undefined" ) {
		ret = context.getElementsByTagName( tag || "*" );

	} else if ( typeof context.querySelectorAll !== "undefined" ) {
		ret = context.querySelectorAll( tag || "*" );

	} else {
		ret = [];
	}

	if ( tag === undefined || tag && nodeName( context, tag ) ) {
		return jQuery.merge( [ context ], ret );
	}

	return ret;
}


// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
	var i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		dataPriv.set(
			elems[ i ],
			"globalEval",
			!refElements || dataPriv.get( refElements[ i ], "globalEval" )
		);
	}
}


var rhtml = /<|&#?\w+;/;

function buildFragment( elems, context, scripts, selection, ignored ) {
	var elem, tmp, tag, wrap, contains, j,
		fragment = context.createDocumentFragment(),
		nodes = [],
		i = 0,
		l = elems.length;

	for ( ; i < l; i++ ) {
		elem = elems[ i ];

		if ( elem || elem === 0 ) {

			// Add nodes directly
			if ( jQuery.type( elem ) === "object" ) {

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );

			// Convert non-html into a text node
			} else if ( !rhtml.test( elem ) ) {
				nodes.push( context.createTextNode( elem ) );

			// Convert html into DOM nodes
			} else {
				tmp = tmp || fragment.appendChild( context.createElement( "div" ) );

				// Deserialize a standard representation
				tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
				wrap = wrapMap[ tag ] || wrapMap._default;
				tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];

				// Descend through wrappers to the right content
				j = wrap[ 0 ];
				while ( j-- ) {
					tmp = tmp.lastChild;
				}

				// Support: Android <=4.0 only, PhantomJS 1 only
				// push.apply(_, arraylike) throws on ancient WebKit
				jQuery.merge( nodes, tmp.childNodes );

				// Remember the top-level container
				tmp = fragment.firstChild;

				// Ensure the created nodes are orphaned (#12392)
				tmp.textContent = "";
			}
		}
	}

	// Remove wrapper from fragment
	fragment.textContent = "";

	i = 0;
	while ( ( elem = nodes[ i++ ] ) ) {

		// Skip elements already in the context collection (trac-4087)
		if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
			if ( ignored ) {
				ignored.push( elem );
			}
			continue;
		}

		contains = jQuery.contains( elem.ownerDocument, elem );

		// Append to fragment
		tmp = getAll( fragment.appendChild( elem ), "script" );

		// Preserve script evaluation history
		if ( contains ) {
			setGlobalEval( tmp );
		}

		// Capture executables
		if ( scripts ) {
			j = 0;
			while ( ( elem = tmp[ j++ ] ) ) {
				if ( rscriptType.test( elem.type || "" ) ) {
					scripts.push( elem );
				}
			}
		}
	}

	return fragment;
}


( function() {
	var fragment = document.createDocumentFragment(),
		div = fragment.appendChild( document.createElement( "div" ) ),
		input = document.createElement( "input" );

	// Support: Android 4.0 - 4.3 only
	// Check state lost if the name is set (#11217)
	// Support: Windows Web Apps (WWA)
	// `name` and `type` must use .setAttribute for WWA (#14901)
	input.setAttribute( "type", "radio" );
	input.setAttribute( "checked", "checked" );
	input.setAttribute( "name", "t" );

	div.appendChild( input );

	// Support: Android <=4.1 only
	// Older WebKit doesn't clone checked state correctly in fragments
	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;

	// Support: IE <=11 only
	// Make sure textarea (and checkbox) defaultValue is properly cloned
	div.innerHTML = "<textarea>x</textarea>";
	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;



var
	rkeyEvent = /^key/,
	rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
	rtypenamespace = /^([^.]*)(?:\.(.+)|)/;

function returnTrue() {
	return true;
}

function returnFalse() {
	return false;
}

// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
	try {
		return document.activeElement;
	} catch ( err ) { }
}

function on( elem, types, selector, data, fn, one ) {
	var origFn, type;

	// Types can be a map of types/handlers
	if ( typeof types === "object" ) {

		// ( types-Object, selector, data )
		if ( typeof selector !== "string" ) {

			// ( types-Object, data )
			data = data || selector;
			selector = undefined;
		}
		for ( type in types ) {
			on( elem, type, selector, data, types[ type ], one );
		}
		return elem;
	}

	if ( data == null && fn == null ) {

		// ( types, fn )
		fn = selector;
		data = selector = undefined;
	} else if ( fn == null ) {
		if ( typeof selector === "string" ) {

			// ( types, selector, fn )
			fn = data;
			data = undefined;
		} else {

			// ( types, data, fn )
			fn = data;
			data = selector;
			selector = undefined;
		}
	}
	if ( fn === false ) {
		fn = returnFalse;
	} else if ( !fn ) {
		return elem;
	}

	if ( one === 1 ) {
		origFn = fn;
		fn = function( event ) {

			// Can use an empty set, since event contains the info
			jQuery().off( event );
			return origFn.apply( this, arguments );
		};

		// Use same guid so caller can remove using origFn
		fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
	}
	return elem.each( function() {
		jQuery.event.add( this, types, fn, data, selector );
	} );
}

/*
 * Helper functions for managing events -- not part of the public interface.
 * Props to Dean Edwards' addEvent library for many of the ideas.
 */
jQuery.event = {

	global: {},

	add: function( elem, types, handler, data, selector ) {

		var handleObjIn, eventHandle, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.get( elem );

		// Don't attach events to noData or text/comment nodes (but allow plain objects)
		if ( !elemData ) {
			return;
		}

		// Caller can pass in an object of custom data in lieu of the handler
		if ( handler.handler ) {
			handleObjIn = handler;
			handler = handleObjIn.handler;
			selector = handleObjIn.selector;
		}

		// Ensure that invalid selectors throw exceptions at attach time
		// Evaluate against documentElement in case elem is a non-element node (e.g., document)
		if ( selector ) {
			jQuery.find.matchesSelector( documentElement, selector );
		}

		// Make sure that the handler has a unique ID, used to find/remove it later
		if ( !handler.guid ) {
			handler.guid = jQuery.guid++;
		}

		// Init the element's event structure and main handler, if this is the first
		if ( !( events = elemData.events ) ) {
			events = elemData.events = {};
		}
		if ( !( eventHandle = elemData.handle ) ) {
			eventHandle = elemData.handle = function( e ) {

				// Discard the second event of a jQuery.event.trigger() and
				// when an event is called after a page has unloaded
				return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
			};
		}

		// Handle multiple events separated by a space
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// There *must* be a type, no attaching namespace-only handlers
			if ( !type ) {
				continue;
			}

			// If event changes its type, use the special event handlers for the changed type
			special = jQuery.event.special[ type ] || {};

			// If selector defined, determine special event api type, otherwise given type
			type = ( selector ? special.delegateType : special.bindType ) || type;

			// Update special based on newly reset type
			special = jQuery.event.special[ type ] || {};

			// handleObj is passed to all event handlers
			handleObj = jQuery.extend( {
				type: type,
				origType: origType,
				data: data,
				handler: handler,
				guid: handler.guid,
				selector: selector,
				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
				namespace: namespaces.join( "." )
			}, handleObjIn );

			// Init the event handler queue if we're the first
			if ( !( handlers = events[ type ] ) ) {
				handlers = events[ type ] = [];
				handlers.delegateCount = 0;

				// Only use addEventListener if the special events handler returns false
				if ( !special.setup ||
					special.setup.call( elem, data, namespaces, eventHandle ) === false ) {

					if ( elem.addEventListener ) {
						elem.addEventListener( type, eventHandle );
					}
				}
			}

			if ( special.add ) {
				special.add.call( elem, handleObj );

				if ( !handleObj.handler.guid ) {
					handleObj.handler.guid = handler.guid;
				}
			}

			// Add to the element's handler list, delegates in front
			if ( selector ) {
				handlers.splice( handlers.delegateCount++, 0, handleObj );
			} else {
				handlers.push( handleObj );
			}

			// Keep track of which events have ever been used, for event optimization
			jQuery.event.global[ type ] = true;
		}

	},

	// Detach an event or set of events from an element
	remove: function( elem, types, handler, selector, mappedTypes ) {

		var j, origCount, tmp,
			events, t, handleObj,
			special, handlers, type, namespaces, origType,
			elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );

		if ( !elemData || !( events = elemData.events ) ) {
			return;
		}

		// Once for each type.namespace in types; type may be omitted
		types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
		t = types.length;
		while ( t-- ) {
			tmp = rtypenamespace.exec( types[ t ] ) || [];
			type = origType = tmp[ 1 ];
			namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();

			// Unbind all events (on this namespace, if provided) for the element
			if ( !type ) {
				for ( type in events ) {
					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
				}
				continue;
			}

			special = jQuery.event.special[ type ] || {};
			type = ( selector ? special.delegateType : special.bindType ) || type;
			handlers = events[ type ] || [];
			tmp = tmp[ 2 ] &&
				new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );

			// Remove matching events
			origCount = j = handlers.length;
			while ( j-- ) {
				handleObj = handlers[ j ];

				if ( ( mappedTypes || origType === handleObj.origType ) &&
					( !handler || handler.guid === handleObj.guid ) &&
					( !tmp || tmp.test( handleObj.namespace ) ) &&
					( !selector || selector === handleObj.selector ||
						selector === "**" && handleObj.selector ) ) {
					handlers.splice( j, 1 );

					if ( handleObj.selector ) {
						handlers.delegateCount--;
					}
					if ( special.remove ) {
						special.remove.call( elem, handleObj );
					}
				}
			}

			// Remove generic event handler if we removed something and no more handlers exist
			// (avoids potential for endless recursion during removal of special event handlers)
			if ( origCount && !handlers.length ) {
				if ( !special.teardown ||
					special.teardown.call( elem, namespaces, elemData.handle ) === false ) {

					jQuery.removeEvent( elem, type, elemData.handle );
				}

				delete events[ type ];
			}
		}

		// Remove data and the expando if it's no longer used
		if ( jQuery.isEmptyObject( events ) ) {
			dataPriv.remove( elem, "handle events" );
		}
	},

	dispatch: function( nativeEvent ) {

		// Make a writable jQuery.Event from the native event object
		var event = jQuery.event.fix( nativeEvent );

		var i, j, ret, matched, handleObj, handlerQueue,
			args = new Array( arguments.length ),
			handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
			special = jQuery.event.special[ event.type ] || {};

		// Use the fix-ed jQuery.Event rather than the (read-only) native event
		args[ 0 ] = event;

		for ( i = 1; i < arguments.length; i++ ) {
			args[ i ] = arguments[ i ];
		}

		event.delegateTarget = this;

		// Call the preDispatch hook for the mapped type, and let it bail if desired
		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
			return;
		}

		// Determine handlers
		handlerQueue = jQuery.event.handlers.call( this, event, handlers );

		// Run delegates first; they may want to stop propagation beneath us
		i = 0;
		while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
			event.currentTarget = matched.elem;

			j = 0;
			while ( ( handleObj = matched.handlers[ j++ ] ) &&
				!event.isImmediatePropagationStopped() ) {

				// Triggered event must either 1) have no namespace, or 2) have namespace(s)
				// a subset or equal to those in the bound event (both can have no namespace).
				if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {

					event.handleObj = handleObj;
					event.data = handleObj.data;

					ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
						handleObj.handler ).apply( matched.elem, args );

					if ( ret !== undefined ) {
						if ( ( event.result = ret ) === false ) {
							event.preventDefault();
							event.stopPropagation();
						}
					}
				}
			}
		}

		// Call the postDispatch hook for the mapped type
		if ( special.postDispatch ) {
			special.postDispatch.call( this, event );
		}

		return event.result;
	},

	handlers: function( event, handlers ) {
		var i, handleObj, sel, matchedHandlers, matchedSelectors,
			handlerQueue = [],
			delegateCount = handlers.delegateCount,
			cur = event.target;

		// Find delegate handlers
		if ( delegateCount &&

			// Support: IE <=9
			// Black-hole SVG <use> instance trees (trac-13180)
			cur.nodeType &&

			// Support: Firefox <=42
			// Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
			// https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
			// Support: IE 11 only
			// ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
			!( event.type === "click" && event.button >= 1 ) ) {

			for ( ; cur !== this; cur = cur.parentNode || this ) {

				// Don't check non-elements (#13208)
				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
				if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
					matchedHandlers = [];
					matchedSelectors = {};
					for ( i = 0; i < delegateCount; i++ ) {
						handleObj = handlers[ i ];

						// Don't conflict with Object.prototype properties (#13203)
						sel = handleObj.selector + " ";

						if ( matchedSelectors[ sel ] === undefined ) {
							matchedSelectors[ sel ] = handleObj.needsContext ?
								jQuery( sel, this ).index( cur ) > -1 :
								jQuery.find( sel, this, null, [ cur ] ).length;
						}
						if ( matchedSelectors[ sel ] ) {
							matchedHandlers.push( handleObj );
						}
					}
					if ( matchedHandlers.length ) {
						handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
					}
				}
			}
		}

		// Add the remaining (directly-bound) handlers
		cur = this;
		if ( delegateCount < handlers.length ) {
			handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
		}

		return handlerQueue;
	},

	addProp: function( name, hook ) {
		Object.defineProperty( jQuery.Event.prototype, name, {
			enumerable: true,
			configurable: true,

			get: jQuery.isFunction( hook ) ?
				function() {
					if ( this.originalEvent ) {
							return hook( this.originalEvent );
					}
				} :
				function() {
					if ( this.originalEvent ) {
							return this.originalEvent[ name ];
					}
				},

			set: function( value ) {
				Object.defineProperty( this, name, {
					enumerable: true,
					configurable: true,
					writable: true,
					value: value
				} );
			}
		} );
	},

	fix: function( originalEvent ) {
		return originalEvent[ jQuery.expando ] ?
			originalEvent :
			new jQuery.Event( originalEvent );
	},

	special: {
		load: {

			// Prevent triggered image.load events from bubbling to window.load
			noBubble: true
		},
		focus: {

			// Fire native event if possible so blur/focus sequence is correct
			trigger: function() {
				if ( this !== safeActiveElement() && this.focus ) {
					this.focus();
					return false;
				}
			},
			delegateType: "focusin"
		},
		blur: {
			trigger: function() {
				if ( this === safeActiveElement() && this.blur ) {
					this.blur();
					return false;
				}
			},
			delegateType: "focusout"
		},
		click: {

			// For checkbox, fire native event so checked state will be right
			trigger: function() {
				if ( this.type === "checkbox" && this.click && nodeName( this, "input" ) ) {
					this.click();
					return false;
				}
			},

			// For cross-browser consistency, don't fire native .click() on links
			_default: function( event ) {
				return nodeName( event.target, "a" );
			}
		},

		beforeunload: {
			postDispatch: function( event ) {

				// Support: Firefox 20+
				// Firefox doesn't alert if the returnValue field is not set.
				if ( event.result !== undefined && event.originalEvent ) {
					event.originalEvent.returnValue = event.result;
				}
			}
		}
	}
};

jQuery.removeEvent = function( elem, type, handle ) {

	// This "if" is needed for plain objects
	if ( elem.removeEventListener ) {
		elem.removeEventListener( type, handle );
	}
};

jQuery.Event = function( src, props ) {

	// Allow instantiation without the 'new' keyword
	if ( !( this instanceof jQuery.Event ) ) {
		return new jQuery.Event( src, props );
	}

	// Event object
	if ( src && src.type ) {
		this.originalEvent = src;
		this.type = src.type;

		// Events bubbling up the document may have been marked as prevented
		// by a handler lower down the tree; reflect the correct value.
		this.isDefaultPrevented = src.defaultPrevented ||
				src.defaultPrevented === undefined &&

				// Support: Android <=2.3 only
				src.returnValue === false ?
			returnTrue :
			returnFalse;

		// Create target properties
		// Support: Safari <=6 - 7 only
		// Target should not be a text node (#504, #13143)
		this.target = ( src.target && src.target.nodeType === 3 ) ?
			src.target.parentNode :
			src.target;

		this.currentTarget = src.currentTarget;
		this.relatedTarget = src.relatedTarget;

	// Event type
	} else {
		this.type = src;
	}

	// Put explicitly provided properties onto the event object
	if ( props ) {
		jQuery.extend( this, props );
	}

	// Create a timestamp if incoming event doesn't have one
	this.timeStamp = src && src.timeStamp || jQuery.now();

	// Mark it as fixed
	this[ jQuery.expando ] = true;
};

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
	constructor: jQuery.Event,
	isDefaultPrevented: returnFalse,
	isPropagationStopped: returnFalse,
	isImmediatePropagationStopped: returnFalse,
	isSimulated: false,

	preventDefault: function() {
		var e = this.originalEvent;

		this.isDefaultPrevented = returnTrue;

		if ( e && !this.isSimulated ) {
			e.preventDefault();
		}
	},
	stopPropagation: function() {
		var e = this.originalEvent;

		this.isPropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopPropagation();
		}
	},
	stopImmediatePropagation: function() {
		var e = this.originalEvent;

		this.isImmediatePropagationStopped = returnTrue;

		if ( e && !this.isSimulated ) {
			e.stopImmediatePropagation();
		}

		this.stopPropagation();
	}
};

// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
	altKey: true,
	bubbles: true,
	cancelable: true,
	changedTouches: true,
	ctrlKey: true,
	detail: true,
	eventPhase: true,
	metaKey: true,
	pageX: true,
	pageY: true,
	shiftKey: true,
	view: true,
	"char": true,
	charCode: true,
	key: true,
	keyCode: true,
	button: true,
	buttons: true,
	clientX: true,
	clientY: true,
	offsetX: true,
	offsetY: true,
	pointerId: true,
	pointerType: true,
	screenX: true,
	screenY: true,
	targetTouches: true,
	toElement: true,
	touches: true,

	which: function( event ) {
		var button = event.button;

		// Add which for key events
		if ( event.which == null && rkeyEvent.test( event.type ) ) {
			return event.charCode != null ? event.charCode : event.keyCode;
		}

		// Add which for click: 1 === left; 2 === middle; 3 === right
		if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
			if ( button & 1 ) {
				return 1;
			}

			if ( button & 2 ) {
				return 3;
			}

			if ( button & 4 ) {
				return 2;
			}

			return 0;
		}

		return event.which;
	}
}, jQuery.event.addProp );

// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
	mouseenter: "mouseover",
	mouseleave: "mouseout",
	pointerenter: "pointerover",
	pointerleave: "pointerout"
}, function( orig, fix ) {
	jQuery.event.special[ orig ] = {
		delegateType: fix,
		bindType: fix,

		handle: function( event ) {
			var ret,
				target = this,
				related = event.relatedTarget,
				handleObj = event.handleObj;

			// For mouseenter/leave call the handler if related is outside the target.
			// NB: No relatedTarget if the mouse left/entered the browser window
			if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
				event.type = handleObj.origType;
				ret = handleObj.handler.apply( this, arguments );
				event.type = fix;
			}
			return ret;
		}
	};
} );

jQuery.fn.extend( {

	on: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn );
	},
	one: function( types, selector, data, fn ) {
		return on( this, types, selector, data, fn, 1 );
	},
	off: function( types, selector, fn ) {
		var handleObj, type;
		if ( types && types.preventDefault && types.handleObj ) {

			// ( event )  dispatched jQuery.Event
			handleObj = types.handleObj;
			jQuery( types.delegateTarget ).off(
				handleObj.namespace ?
					handleObj.origType + "." + handleObj.namespace :
					handleObj.origType,
				handleObj.selector,
				handleObj.handler
			);
			return this;
		}
		if ( typeof types === "object" ) {

			// ( types-object [, selector] )
			for ( type in types ) {
				this.off( type, selector, types[ type ] );
			}
			return this;
		}
		if ( selector === false || typeof selector === "function" ) {

			// ( types [, fn] )
			fn = selector;
			selector = undefined;
		}
		if ( fn === false ) {
			fn = returnFalse;
		}
		return this.each( function() {
			jQuery.event.remove( this, types, fn, selector );
		} );
	}
} );


var

	/* eslint-disable max-len */

	// See https://github.com/eslint/eslint/issues/3229
	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,

	/* eslint-enable */

	// Support: IE <=10 - 11, Edge 12 - 13
	// In IE/Edge using regex groups here causes severe slowdowns.
	// See https://connect.microsoft.com/IE/feedback/details/1736512/
	rnoInnerhtml = /<script|<style|<link/i,

	// checked="checked" or checked
	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
	rscriptTypeMasked = /^true\/(.*)/,
	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;

// Prefer a tbody over its parent table for containing new rows
function manipulationTarget( elem, content ) {
	if ( nodeName( elem, "table" ) &&
		nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {

		return jQuery( ">tbody", elem )[ 0 ] || elem;
	}

	return elem;
}

// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
	elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
	return elem;
}
function restoreScript( elem ) {
	var match = rscriptTypeMasked.exec( elem.type );

	if ( match ) {
		elem.type = match[ 1 ];
	} else {
		elem.removeAttribute( "type" );
	}

	return elem;
}

function cloneCopyEvent( src, dest ) {
	var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;

	if ( dest.nodeType !== 1 ) {
		return;
	}

	// 1. Copy private data: events, handlers, etc.
	if ( dataPriv.hasData( src ) ) {
		pdataOld = dataPriv.access( src );
		pdataCur = dataPriv.set( dest, pdataOld );
		events = pdataOld.events;

		if ( events ) {
			delete pdataCur.handle;
			pdataCur.events = {};

			for ( type in events ) {
				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
					jQuery.event.add( dest, type, events[ type ][ i ] );
				}
			}
		}
	}

	// 2. Copy user data
	if ( dataUser.hasData( src ) ) {
		udataOld = dataUser.access( src );
		udataCur = jQuery.extend( {}, udataOld );

		dataUser.set( dest, udataCur );
	}
}

// Fix IE bugs, see support tests
function fixInput( src, dest ) {
	var nodeName = dest.nodeName.toLowerCase();

	// Fails to persist the checked state of a cloned checkbox or radio button.
	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
		dest.checked = src.checked;

	// Fails to return the selected option to the default selected state when cloning options
	} else if ( nodeName === "input" || nodeName === "textarea" ) {
		dest.defaultValue = src.defaultValue;
	}
}

function domManip( collection, args, callback, ignored ) {

	// Flatten any nested arrays
	args = concat.apply( [], args );

	var fragment, first, scripts, hasScripts, node, doc,
		i = 0,
		l = collection.length,
		iNoClone = l - 1,
		value = args[ 0 ],
		isFunction = jQuery.isFunction( value );

	// We can't cloneNode fragments that contain checked, in WebKit
	if ( isFunction ||
			( l > 1 && typeof value === "string" &&
				!support.checkClone && rchecked.test( value ) ) ) {
		return collection.each( function( index ) {
			var self = collection.eq( index );
			if ( isFunction ) {
				args[ 0 ] = value.call( this, index, self.html() );
			}
			domManip( self, args, callback, ignored );
		} );
	}

	if ( l ) {
		fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
		first = fragment.firstChild;

		if ( fragment.childNodes.length === 1 ) {
			fragment = first;
		}

		// Require either new content or an interest in ignored elements to invoke the callback
		if ( first || ignored ) {
			scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
			hasScripts = scripts.length;

			// Use the original fragment for the last item
			// instead of the first because it can end up
			// being emptied incorrectly in certain situations (#8070).
			for ( ; i < l; i++ ) {
				node = fragment;

				if ( i !== iNoClone ) {
					node = jQuery.clone( node, true, true );

					// Keep references to cloned scripts for later restoration
					if ( hasScripts ) {

						// Support: Android <=4.0 only, PhantomJS 1 only
						// push.apply(_, arraylike) throws on ancient WebKit
						jQuery.merge( scripts, getAll( node, "script" ) );
					}
				}

				callback.call( collection[ i ], node, i );
			}

			if ( hasScripts ) {
				doc = scripts[ scripts.length - 1 ].ownerDocument;

				// Reenable scripts
				jQuery.map( scripts, restoreScript );

				// Evaluate executable scripts on first document insertion
				for ( i = 0; i < hasScripts; i++ ) {
					node = scripts[ i ];
					if ( rscriptType.test( node.type || "" ) &&
						!dataPriv.access( node, "globalEval" ) &&
						jQuery.contains( doc, node ) ) {

						if ( node.src ) {

							// Optional AJAX dependency, but won't run scripts if not present
							if ( jQuery._evalUrl ) {
								jQuery._evalUrl( node.src );
							}
						} else {
							DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
						}
					}
				}
			}
		}
	}

	return collection;
}

function remove( elem, selector, keepData ) {
	var node,
		nodes = selector ? jQuery.filter( selector, elem ) : elem,
		i = 0;

	for ( ; ( node = nodes[ i ] ) != null; i++ ) {
		if ( !keepData && node.nodeType === 1 ) {
			jQuery.cleanData( getAll( node ) );
		}

		if ( node.parentNode ) {
			if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
				setGlobalEval( getAll( node, "script" ) );
			}
			node.parentNode.removeChild( node );
		}
	}

	return elem;
}

jQuery.extend( {
	htmlPrefilter: function( html ) {
		return html.replace( rxhtmlTag, "<$1></$2>" );
	},

	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
		var i, l, srcElements, destElements,
			clone = elem.cloneNode( true ),
			inPage = jQuery.contains( elem.ownerDocument, elem );

		// Fix IE cloning issues
		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
				!jQuery.isXMLDoc( elem ) ) {

			// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
			destElements = getAll( clone );
			srcElements = getAll( elem );

			for ( i = 0, l = srcElements.length; i < l; i++ ) {
				fixInput( srcElements[ i ], destElements[ i ] );
			}
		}

		// Copy the events from the original to the clone
		if ( dataAndEvents ) {
			if ( deepDataAndEvents ) {
				srcElements = srcElements || getAll( elem );
				destElements = destElements || getAll( clone );

				for ( i = 0, l = srcElements.length; i < l; i++ ) {
					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
				}
			} else {
				cloneCopyEvent( elem, clone );
			}
		}

		// Preserve script evaluation history
		destElements = getAll( clone, "script" );
		if ( destElements.length > 0 ) {
			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
		}

		// Return the cloned set
		return clone;
	},

	cleanData: function( elems ) {
		var data, elem, type,
			special = jQuery.event.special,
			i = 0;

		for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
			if ( acceptData( elem ) ) {
				if ( ( data = elem[ dataPriv.expando ] ) ) {
					if ( data.events ) {
						for ( type in data.events ) {
							if ( special[ type ] ) {
								jQuery.event.remove( elem, type );

							// This is a shortcut to avoid jQuery.event.remove's overhead
							} else {
								jQuery.removeEvent( elem, type, data.handle );
							}
						}
					}

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataPriv.expando ] = undefined;
				}
				if ( elem[ dataUser.expando ] ) {

					// Support: Chrome <=35 - 45+
					// Assign undefined instead of using delete, see Data#remove
					elem[ dataUser.expando ] = undefined;
				}
			}
		}
	}
} );

jQuery.fn.extend( {
	detach: function( selector ) {
		return remove( this, selector, true );
	},

	remove: function( selector ) {
		return remove( this, selector );
	},

	text: function( value ) {
		return access( this, function( value ) {
			return value === undefined ?
				jQuery.text( this ) :
				this.empty().each( function() {
					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
						this.textContent = value;
					}
				} );
		}, null, value, arguments.length );
	},

	append: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.appendChild( elem );
			}
		} );
	},

	prepend: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
				var target = manipulationTarget( this, elem );
				target.insertBefore( elem, target.firstChild );
			}
		} );
	},

	before: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this );
			}
		} );
	},

	after: function() {
		return domManip( this, arguments, function( elem ) {
			if ( this.parentNode ) {
				this.parentNode.insertBefore( elem, this.nextSibling );
			}
		} );
	},

	empty: function() {
		var elem,
			i = 0;

		for ( ; ( elem = this[ i ] ) != null; i++ ) {
			if ( elem.nodeType === 1 ) {

				// Prevent memory leaks
				jQuery.cleanData( getAll( elem, false ) );

				// Remove any remaining nodes
				elem.textContent = "";
			}
		}

		return this;
	},

	clone: function( dataAndEvents, deepDataAndEvents ) {
		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

		return this.map( function() {
			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
		} );
	},

	html: function( value ) {
		return access( this, function( value ) {
			var elem = this[ 0 ] || {},
				i = 0,
				l = this.length;

			if ( value === undefined && elem.nodeType === 1 ) {
				return elem.innerHTML;
			}

			// See if we can take a shortcut and just use innerHTML
			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {

				value = jQuery.htmlPrefilter( value );

				try {
					for ( ; i < l; i++ ) {
						elem = this[ i ] || {};

						// Remove element nodes and prevent memory leaks
						if ( elem.nodeType === 1 ) {
							jQuery.cleanData( getAll( elem, false ) );
							elem.innerHTML = value;
						}
					}

					elem = 0;

				// If using innerHTML throws an exception, use the fallback method
				} catch ( e ) {}
			}

			if ( elem ) {
				this.empty().append( value );
			}
		}, null, value, arguments.length );
	},

	replaceWith: function() {
		var ignored = [];

		// Make the changes, replacing each non-ignored context element with the new content
		return domManip( this, arguments, function( elem ) {
			var parent = this.parentNode;

			if ( jQuery.inArray( this, ignored ) < 0 ) {
				jQuery.cleanData( getAll( this ) );
				if ( parent ) {
					parent.replaceChild( elem, this );
				}
			}

		// Force callback invocation
		}, ignored );
	}
} );

jQuery.each( {
	appendTo: "append",
	prependTo: "prepend",
	insertBefore: "before",
	insertAfter: "after",
	replaceAll: "replaceWith"
}, function( name, original ) {
	jQuery.fn[ name ] = function( selector ) {
		var elems,
			ret = [],
			insert = jQuery( selector ),
			last = insert.length - 1,
			i = 0;

		for ( ; i <= last; i++ ) {
			elems = i === last ? this : this.clone( true );
			jQuery( insert[ i ] )[ original ]( elems );

			// Support: Android <=4.0 only, PhantomJS 1 only
			// .get() because push.apply(_, arraylike) throws on ancient WebKit
			push.apply( ret, elems.get() );
		}

		return this.pushStack( ret );
	};
} );
var rmargin = ( /^margin/ );

var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );

var getStyles = function( elem ) {

		// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
		// IE throws on elements created in popups
		// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
		var view = elem.ownerDocument.defaultView;

		if ( !view || !view.opener ) {
			view = window;
		}

		return view.getComputedStyle( elem );
	};



( function() {

	// Executing both pixelPosition & boxSizingReliable tests require only one layout
	// so they're executed at the same time to save the second computation.
	function computeStyleTests() {

		// This is a singleton, we need to execute it only once
		if ( !div ) {
			return;
		}

		div.style.cssText =
			"box-sizing:border-box;" +
			"position:relative;display:block;" +
			"margin:auto;border:1px;padding:1px;" +
			"top:1%;width:50%";
		div.innerHTML = "";
		documentElement.appendChild( container );

		var divStyle = window.getComputedStyle( div );
		pixelPositionVal = divStyle.top !== "1%";

		// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
		reliableMarginLeftVal = divStyle.marginLeft === "2px";
		boxSizingReliableVal = divStyle.width === "4px";

		// Support: Android 4.0 - 4.3 only
		// Some styles come back with percentage values, even though they shouldn't
		div.style.marginRight = "50%";
		pixelMarginRightVal = divStyle.marginRight === "4px";

		documentElement.removeChild( container );

		// Nullify the div so it wouldn't be stored in the memory and
		// it will also be a sign that checks already performed
		div = null;
	}

	var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
		container = document.createElement( "div" ),
		div = document.createElement( "div" );

	// Finish early in limited (non-browser) environments
	if ( !div.style ) {
		return;
	}

	// Support: IE <=9 - 11 only
	// Style of cloned element affects source element cloned (#8908)
	div.style.backgroundClip = "content-box";
	div.cloneNode( true ).style.backgroundClip = "";
	support.clearCloneStyle = div.style.backgroundClip === "content-box";

	container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
		"padding:0;margin-top:1px;position:absolute";
	container.appendChild( div );

	jQuery.extend( support, {
		pixelPosition: function() {
			computeStyleTests();
			return pixelPositionVal;
		},
		boxSizingReliable: function() {
			computeStyleTests();
			return boxSizingReliableVal;
		},
		pixelMarginRight: function() {
			computeStyleTests();
			return pixelMarginRightVal;
		},
		reliableMarginLeft: function() {
			computeStyleTests();
			return reliableMarginLeftVal;
		}
	} );
} )();


function curCSS( elem, name, computed ) {
	var width, minWidth, maxWidth, ret,

		// Support: Firefox 51+
		// Retrieving style before computed somehow
		// fixes an issue with getting wrong values
		// on detached elements
		style = elem.style;

	computed = computed || getStyles( elem );

	// getPropertyValue is needed for:
	//   .css('filter') (IE 9 only, #12537)
	//   .css('--customProperty) (#3144)
	if ( computed ) {
		ret = computed.getPropertyValue( name ) || computed[ name ];

		if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
			ret = jQuery.style( elem, name );
		}

		// A tribute to the "awesome hack by Dean Edwards"
		// Android Browser returns percentage for some values,
		// but width seems to be reliably pixels.
		// This is against the CSSOM draft spec:
		// https://drafts.csswg.org/cssom/#resolved-values
		if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {

			// Remember the original values
			width = style.width;
			minWidth = style.minWidth;
			maxWidth = style.maxWidth;

			// Put in the new values to get a computed value out
			style.minWidth = style.maxWidth = style.width = ret;
			ret = computed.width;

			// Revert the changed values
			style.width = width;
			style.minWidth = minWidth;
			style.maxWidth = maxWidth;
		}
	}

	return ret !== undefined ?

		// Support: IE <=9 - 11 only
		// IE returns zIndex value as an integer.
		ret + "" :
		ret;
}


function addGetHookIf( conditionFn, hookFn ) {

	// Define the hook, we'll check on the first run if it's really needed.
	return {
		get: function() {
			if ( conditionFn() ) {

				// Hook not needed (or it's not possible to use it due
				// to missing dependency), remove it.
				delete this.get;
				return;
			}

			// Hook needed; redefine it so that the support test is not executed again.
			return ( this.get = hookFn ).apply( this, arguments );
		}
	};
}


var

	// Swappable if display is none or starts with table
	// except "table", "table-cell", or "table-caption"
	// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
	rcustomProp = /^--/,
	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
	cssNormalTransform = {
		letterSpacing: "0",
		fontWeight: "400"
	},

	cssPrefixes = [ "Webkit", "Moz", "ms" ],
	emptyStyle = document.createElement( "div" ).style;

// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {

	// Shortcut for names that are not vendor prefixed
	if ( name in emptyStyle ) {
		return name;
	}

	// Check for vendor prefixed names
	var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
		i = cssPrefixes.length;

	while ( i-- ) {
		name = cssPrefixes[ i ] + capName;
		if ( name in emptyStyle ) {
			return name;
		}
	}
}

// Return a property mapped along what jQuery.cssProps suggests or to
// a vendor prefixed property.
function finalPropName( name ) {
	var ret = jQuery.cssProps[ name ];
	if ( !ret ) {
		ret = jQuery.cssProps[ name ] = vendorPropName( name ) || name;
	}
	return ret;
}

function setPositiveNumber( elem, value, subtract ) {

	// Any relative (+/-) values have already been
	// normalized at this point
	var matches = rcssNum.exec( value );
	return matches ?

		// Guard against undefined "subtract", e.g., when used as in cssHooks
		Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
		value;
}

function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
	var i,
		val = 0;

	// If we already have the right measurement, avoid augmentation
	if ( extra === ( isBorderBox ? "border" : "content" ) ) {
		i = 4;

	// Otherwise initialize for horizontal or vertical properties
	} else {
		i = name === "width" ? 1 : 0;
	}

	for ( ; i < 4; i += 2 ) {

		// Both box models exclude margin, so add it if we want it
		if ( extra === "margin" ) {
			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
		}

		if ( isBorderBox ) {

			// border-box includes padding, so remove it if we want content
			if ( extra === "content" ) {
				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
			}

			// At this point, extra isn't border nor margin, so remove border
			if ( extra !== "margin" ) {
				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		} else {

			// At this point, extra isn't content, so add padding
			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );

			// At this point, extra isn't content nor padding, so add border
			if ( extra !== "padding" ) {
				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
			}
		}
	}

	return val;
}

function getWidthOrHeight( elem, name, extra ) {

	// Start with computed style
	var valueIsBorderBox,
		styles = getStyles( elem ),
		val = curCSS( elem, name, styles ),
		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";

	// Computed unit is not pixels. Stop here and return.
	if ( rnumnonpx.test( val ) ) {
		return val;
	}

	// Check for style in case a browser which returns unreliable values
	// for getComputedStyle silently falls back to the reliable elem.style
	valueIsBorderBox = isBorderBox &&
		( support.boxSizingReliable() || val === elem.style[ name ] );

	// Fall back to offsetWidth/Height when value is "auto"
	// This happens for inline elements with no explicit setting (gh-3571)
	if ( val === "auto" ) {
		val = elem[ "offset" + name[ 0 ].toUpperCase() + name.slice( 1 ) ];
	}

	// Normalize "", auto, and prepare for extra
	val = parseFloat( val ) || 0;

	// Use the active box-sizing model to add/subtract irrelevant styles
	return ( val +
		augmentWidthOrHeight(
			elem,
			name,
			extra || ( isBorderBox ? "border" : "content" ),
			valueIsBorderBox,
			styles
		)
	) + "px";
}

jQuery.extend( {

	// Add in style property hooks for overriding the default
	// behavior of getting and setting a style property
	cssHooks: {
		opacity: {
			get: function( elem, computed ) {
				if ( computed ) {

					// We should always get a number back from opacity
					var ret = curCSS( elem, "opacity" );
					return ret === "" ? "1" : ret;
				}
			}
		}
	},

	// Don't automatically add "px" to these possibly-unitless properties
	cssNumber: {
		"animationIterationCount": true,
		"columnCount": true,
		"fillOpacity": true,
		"flexGrow": true,
		"flexShrink": true,
		"fontWeight": true,
		"lineHeight": true,
		"opacity": true,
		"order": true,
		"orphans": true,
		"widows": true,
		"zIndex": true,
		"zoom": true
	},

	// Add in properties whose names you wish to fix before
	// setting or getting the value
	cssProps: {
		"float": "cssFloat"
	},

	// Get and set the style property on a DOM Node
	style: function( elem, name, value, extra ) {

		// Don't set styles on text and comment nodes
		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
			return;
		}

		// Make sure that we're working with the right name
		var ret, type, hooks,
			origName = jQuery.camelCase( name ),
			isCustomProp = rcustomProp.test( name ),
			style = elem.style;

		// Make sure that we're working with the right name. We don't
		// want to query the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Gets hook for the prefixed version, then unprefixed version
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// Check if we're setting a value
		if ( value !== undefined ) {
			type = typeof value;

			// Convert "+=" or "-=" to relative numbers (#7345)
			if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
				value = adjustCSS( elem, name, ret );

				// Fixes bug #9237
				type = "number";
			}

			// Make sure that null and NaN values aren't set (#7116)
			if ( value == null || value !== value ) {
				return;
			}

			// If a number was passed in, add the unit (except for certain CSS properties)
			if ( type === "number" ) {
				value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
			}

			// background-* props affect original clone's values
			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
				style[ name ] = "inherit";
			}

			// If a hook was provided, use that value, otherwise just set the specified value
			if ( !hooks || !( "set" in hooks ) ||
				( value = hooks.set( elem, value, extra ) ) !== undefined ) {

				if ( isCustomProp ) {
					style.setProperty( name, value );
				} else {
					style[ name ] = value;
				}
			}

		} else {

			// If a hook was provided get the non-computed value from there
			if ( hooks && "get" in hooks &&
				( ret = hooks.get( elem, false, extra ) ) !== undefined ) {

				return ret;
			}

			// Otherwise just get the value from the style object
			return style[ name ];
		}
	},

	css: function( elem, name, extra, styles ) {
		var val, num, hooks,
			origName = jQuery.camelCase( name ),
			isCustomProp = rcustomProp.test( name );

		// Make sure that we're working with the right name. We don't
		// want to modify the value if it is a CSS custom property
		// since they are user-defined.
		if ( !isCustomProp ) {
			name = finalPropName( origName );
		}

		// Try prefixed name followed by the unprefixed name
		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];

		// If a hook was provided get the computed value from there
		if ( hooks && "get" in hooks ) {
			val = hooks.get( elem, true, extra );
		}

		// Otherwise, if a way to get the computed value exists, use that
		if ( val === undefined ) {
			val = curCSS( elem, name, styles );
		}

		// Convert "normal" to computed value
		if ( val === "normal" && name in cssNormalTransform ) {
			val = cssNormalTransform[ name ];
		}

		// Make numeric if forced or a qualifier was provided and val looks numeric
		if ( extra === "" || extra ) {
			num = parseFloat( val );
			return extra === true || isFinite( num ) ? num || 0 : val;
		}

		return val;
	}
} );

jQuery.each( [ "height", "width" ], function( i, name ) {
	jQuery.cssHooks[ name ] = {
		get: function( elem, computed, extra ) {
			if ( computed ) {

				// Certain elements can have dimension info if we invisibly show them
				// but it must have a current display style that would benefit
				return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&

					// Support: Safari 8+
					// Table columns in Safari have non-zero offsetWidth & zero
					// getBoundingClientRect().width unless display is changed.
					// Support: IE <=11 only
					// Running getBoundingClientRect on a disconnected node
					// in IE throws an error.
					( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
						swap( elem, cssShow, function() {
							return getWidthOrHeight( elem, name, extra );
						} ) :
						getWidthOrHeight( elem, name, extra );
			}
		},

		set: function( elem, value, extra ) {
			var matches,
				styles = extra && getStyles( elem ),
				subtract = extra && augmentWidthOrHeight(
					elem,
					name,
					extra,
					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
					styles
				);

			// Convert to pixels if value adjustment is needed
			if ( subtract && ( matches = rcssNum.exec( value ) ) &&
				( matches[ 3 ] || "px" ) !== "px" ) {

				elem.style[ name ] = value;
				value = jQuery.css( elem, name );
			}

			return setPositiveNumber( elem, value, subtract );
		}
	};
} );

jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
	function( elem, computed ) {
		if ( computed ) {
			return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
				elem.getBoundingClientRect().left -
					swap( elem, { marginLeft: 0 }, function() {
						return elem.getBoundingClientRect().left;
					} )
				) + "px";
		}
	}
);

// These hooks are used by animate to expand properties
jQuery.each( {
	margin: "",
	padding: "",
	border: "Width"
}, function( prefix, suffix ) {
	jQuery.cssHooks[ prefix + suffix ] = {
		expand: function( value ) {
			var i = 0,
				expanded = {},

				// Assumes a single number if not a string
				parts = typeof value === "string" ? value.split( " " ) : [ value ];

			for ( ; i < 4; i++ ) {
				expanded[ prefix + cssExpand[ i ] + suffix ] =
					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
			}

			return expanded;
		}
	};

	if ( !rmargin.test( prefix ) ) {
		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
	}
} );

jQuery.fn.extend( {
	css: function( name, value ) {
		return access( this, function( elem, name, value ) {
			var styles, len,
				map = {},
				i = 0;

			if ( Array.isArray( name ) ) {
				styles = getStyles( elem );
				len = name.length;

				for ( ; i < len; i++ ) {
					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
				}

				return map;
			}

			return value !== undefined ?
				jQuery.style( elem, name, value ) :
				jQuery.css( elem, name );
		}, name, value, arguments.length > 1 );
	}
} );


function Tween( elem, options, prop, end, easing ) {
	return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;

Tween.prototype = {
	constructor: Tween,
	init: function( elem, options, prop, end, easing, unit ) {
		this.elem = elem;
		this.prop = prop;
		this.easing = easing || jQuery.easing._default;
		this.options = options;
		this.start = this.now = this.cur();
		this.end = end;
		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
	},
	cur: function() {
		var hooks = Tween.propHooks[ this.prop ];

		return hooks && hooks.get ?
			hooks.get( this ) :
			Tween.propHooks._default.get( this );
	},
	run: function( percent ) {
		var eased,
			hooks = Tween.propHooks[ this.prop ];

		if ( this.options.duration ) {
			this.pos = eased = jQuery.easing[ this.easing ](
				percent, this.options.duration * percent, 0, 1, this.options.duration
			);
		} else {
			this.pos = eased = percent;
		}
		this.now = ( this.end - this.start ) * eased + this.start;

		if ( this.options.step ) {
			this.options.step.call( this.elem, this.now, this );
		}

		if ( hooks && hooks.set ) {
			hooks.set( this );
		} else {
			Tween.propHooks._default.set( this );
		}
		return this;
	}
};

Tween.prototype.init.prototype = Tween.prototype;

Tween.propHooks = {
	_default: {
		get: function( tween ) {
			var result;

			// Use a property on the element directly when it is not a DOM element,
			// or when there is no matching style property that exists.
			if ( tween.elem.nodeType !== 1 ||
				tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
				return tween.elem[ tween.prop ];
			}

			// Passing an empty string as a 3rd parameter to .css will automatically
			// attempt a parseFloat and fallback to a string if the parse fails.
			// Simple values such as "10px" are parsed to Float;
			// complex values such as "rotate(1rad)" are returned as-is.
			result = jQuery.css( tween.elem, tween.prop, "" );

			// Empty strings, null, undefined and "auto" are converted to 0.
			return !result || result === "auto" ? 0 : result;
		},
		set: function( tween ) {

			// Use step hook for back compat.
			// Use cssHook if its there.
			// Use .style if available and use plain properties where available.
			if ( jQuery.fx.step[ tween.prop ] ) {
				jQuery.fx.step[ tween.prop ]( tween );
			} else if ( tween.elem.nodeType === 1 &&
				( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
					jQuery.cssHooks[ tween.prop ] ) ) {
				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
			} else {
				tween.elem[ tween.prop ] = tween.now;
			}
		}
	}
};

// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
	set: function( tween ) {
		if ( tween.elem.nodeType && tween.elem.parentNode ) {
			tween.elem[ tween.prop ] = tween.now;
		}
	}
};

jQuery.easing = {
	linear: function( p ) {
		return p;
	},
	swing: function( p ) {
		return 0.5 - Math.cos( p * Math.PI ) / 2;
	},
	_default: "swing"
};

jQuery.fx = Tween.prototype.init;

// Back compat <1.8 extension point
jQuery.fx.step = {};




var
	fxNow, inProgress,
	rfxtypes = /^(?:toggle|show|hide)$/,
	rrun = /queueHooks$/;

function schedule() {
	if ( inProgress ) {
		if ( document.hidden === false && window.requestAnimationFrame ) {
			window.requestAnimationFrame( schedule );
		} else {
			window.setTimeout( schedule, jQuery.fx.interval );
		}

		jQuery.fx.tick();
	}
}

// Animations created synchronously will run synchronously
function createFxNow() {
	window.setTimeout( function() {
		fxNow = undefined;
	} );
	return ( fxNow = jQuery.now() );
}

// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
	var which,
		i = 0,
		attrs = { height: type };

	// If we include width, step value is 1 to do all cssExpand values,
	// otherwise step value is 2 to skip over Left and Right
	includeWidth = includeWidth ? 1 : 0;
	for ( ; i < 4; i += 2 - includeWidth ) {
		which = cssExpand[ i ];
		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
	}

	if ( includeWidth ) {
		attrs.opacity = attrs.width = type;
	}

	return attrs;
}

function createTween( value, prop, animation ) {
	var tween,
		collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
		index = 0,
		length = collection.length;
	for ( ; index < length; index++ ) {
		if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {

			// We're done with this property
			return tween;
		}
	}
}

function defaultPrefilter( elem, props, opts ) {
	var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
		isBox = "width" in props || "height" in props,
		anim = this,
		orig = {},
		style = elem.style,
		hidden = elem.nodeType && isHiddenWithinTree( elem ),
		dataShow = dataPriv.get( elem, "fxshow" );

	// Queue-skipping animations hijack the fx hooks
	if ( !opts.queue ) {
		hooks = jQuery._queueHooks( elem, "fx" );
		if ( hooks.unqueued == null ) {
			hooks.unqueued = 0;
			oldfire = hooks.empty.fire;
			hooks.empty.fire = function() {
				if ( !hooks.unqueued ) {
					oldfire();
				}
			};
		}
		hooks.unqueued++;

		anim.always( function() {

			// Ensure the complete handler is called before this completes
			anim.always( function() {
				hooks.unqueued--;
				if ( !jQuery.queue( elem, "fx" ).length ) {
					hooks.empty.fire();
				}
			} );
		} );
	}

	// Detect show/hide animations
	for ( prop in props ) {
		value = props[ prop ];
		if ( rfxtypes.test( value ) ) {
			delete props[ prop ];
			toggle = toggle || value === "toggle";
			if ( value === ( hidden ? "hide" : "show" ) ) {

				// Pretend to be hidden if this is a "show" and
				// there is still data from a stopped show/hide
				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
					hidden = true;

				// Ignore all other no-op show/hide data
				} else {
					continue;
				}
			}
			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
		}
	}

	// Bail out if this is a no-op like .hide().hide()
	propTween = !jQuery.isEmptyObject( props );
	if ( !propTween && jQuery.isEmptyObject( orig ) ) {
		return;
	}

	// Restrict "overflow" and "display" styles during box animations
	if ( isBox && elem.nodeType === 1 ) {

		// Support: IE <=9 - 11, Edge 12 - 13
		// Record all 3 overflow attributes because IE does not infer the shorthand
		// from identically-valued overflowX and overflowY
		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];

		// Identify a display type, preferring old show/hide data over the CSS cascade
		restoreDisplay = dataShow && dataShow.display;
		if ( restoreDisplay == null ) {
			restoreDisplay = dataPriv.get( elem, "display" );
		}
		display = jQuery.css( elem, "display" );
		if ( display === "none" ) {
			if ( restoreDisplay ) {
				display = restoreDisplay;
			} else {

				// Get nonempty value(s) by temporarily forcing visibility
				showHide( [ elem ], true );
				restoreDisplay = elem.style.display || restoreDisplay;
				display = jQuery.css( elem, "display" );
				showHide( [ elem ] );
			}
		}

		// Animate inline elements as inline-block
		if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
			if ( jQuery.css( elem, "float" ) === "none" ) {

				// Restore the original display value at the end of pure show/hide animations
				if ( !propTween ) {
					anim.done( function() {
						style.display = restoreDisplay;
					} );
					if ( restoreDisplay == null ) {
						display = style.display;
						restoreDisplay = display === "none" ? "" : display;
					}
				}
				style.display = "inline-block";
			}
		}
	}

	if ( opts.overflow ) {
		style.overflow = "hidden";
		anim.always( function() {
			style.overflow = opts.overflow[ 0 ];
			style.overflowX = opts.overflow[ 1 ];
			style.overflowY = opts.overflow[ 2 ];
		} );
	}

	// Implement show/hide animations
	propTween = false;
	for ( prop in orig ) {

		// General show/hide setup for this element animation
		if ( !propTween ) {
			if ( dataShow ) {
				if ( "hidden" in dataShow ) {
					hidden = dataShow.hidden;
				}
			} else {
				dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
			}

			// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
			if ( toggle ) {
				dataShow.hidden = !hidden;
			}

			// Show elements before animating them
			if ( hidden ) {
				showHide( [ elem ], true );
			}

			/* eslint-disable no-loop-func */

			anim.done( function() {

			/* eslint-enable no-loop-func */

				// The final step of a "hide" animation is actually hiding the element
				if ( !hidden ) {
					showHide( [ elem ] );
				}
				dataPriv.remove( elem, "fxshow" );
				for ( prop in orig ) {
					jQuery.style( elem, prop, orig[ prop ] );
				}
			} );
		}

		// Per-property setup
		propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
		if ( !( prop in dataShow ) ) {
			dataShow[ prop ] = propTween.start;
			if ( hidden ) {
				propTween.end = propTween.start;
				propTween.start = 0;
			}
		}
	}
}

function propFilter( props, specialEasing ) {
	var index, name, easing, value, hooks;

	// camelCase, specialEasing and expand cssHook pass
	for ( index in props ) {
		name = jQuery.camelCase( index );
		easing = specialEasing[ name ];
		value = props[ index ];
		if ( Array.isArray( value ) ) {
			easing = value[ 1 ];
			value = props[ index ] = value[ 0 ];
		}

		if ( index !== name ) {
			props[ name ] = value;
			delete props[ index ];
		}

		hooks = jQuery.cssHooks[ name ];
		if ( hooks && "expand" in hooks ) {
			value = hooks.expand( value );
			delete props[ name ];

			// Not quite $.extend, this won't overwrite existing keys.
			// Reusing 'index' because we have the correct "name"
			for ( index in value ) {
				if ( !( index in props ) ) {
					props[ index ] = value[ index ];
					specialEasing[ index ] = easing;
				}
			}
		} else {
			specialEasing[ name ] = easing;
		}
	}
}

function Animation( elem, properties, options ) {
	var result,
		stopped,
		index = 0,
		length = Animation.prefilters.length,
		deferred = jQuery.Deferred().always( function() {

			// Don't match elem in the :animated selector
			delete tick.elem;
		} ),
		tick = function() {
			if ( stopped ) {
				return false;
			}
			var currentTime = fxNow || createFxNow(),
				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),

				// Support: Android 2.3 only
				// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
				temp = remaining / animation.duration || 0,
				percent = 1 - temp,
				index = 0,
				length = animation.tweens.length;

			for ( ; index < length; index++ ) {
				animation.tweens[ index ].run( percent );
			}

			deferred.notifyWith( elem, [ animation, percent, remaining ] );

			// If there's more to do, yield
			if ( percent < 1 && length ) {
				return remaining;
			}

			// If this was an empty animation, synthesize a final progress notification
			if ( !length ) {
				deferred.notifyWith( elem, [ animation, 1, 0 ] );
			}

			// Resolve the animation and report its conclusion
			deferred.resolveWith( elem, [ animation ] );
			return false;
		},
		animation = deferred.promise( {
			elem: elem,
			props: jQuery.extend( {}, properties ),
			opts: jQuery.extend( true, {
				specialEasing: {},
				easing: jQuery.easing._default
			}, options ),
			originalProperties: properties,
			originalOptions: options,
			startTime: fxNow || createFxNow(),
			duration: options.duration,
			tweens: [],
			createTween: function( prop, end ) {
				var tween = jQuery.Tween( elem, animation.opts, prop, end,
						animation.opts.specialEasing[ prop ] || animation.opts.easing );
				animation.tweens.push( tween );
				return tween;
			},
			stop: function( gotoEnd ) {
				var index = 0,

					// If we are going to the end, we want to run all the tweens
					// otherwise we skip this part
					length = gotoEnd ? animation.tweens.length : 0;
				if ( stopped ) {
					return this;
				}
				stopped = true;
				for ( ; index < length; index++ ) {
					animation.tweens[ index ].run( 1 );
				}

				// Resolve when we played the last frame; otherwise, reject
				if ( gotoEnd ) {
					deferred.notifyWith( elem, [ animation, 1, 0 ] );
					deferred.resolveWith( elem, [ animation, gotoEnd ] );
				} else {
					deferred.rejectWith( elem, [ animation, gotoEnd ] );
				}
				return this;
			}
		} ),
		props = animation.props;

	propFilter( props, animation.opts.specialEasing );

	for ( ; index < length; index++ ) {
		result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
		if ( result ) {
			if ( jQuery.isFunction( result.stop ) ) {
				jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
					jQuery.proxy( result.stop, result );
			}
			return result;
		}
	}

	jQuery.map( props, createTween, animation );

	if ( jQuery.isFunction( animation.opts.start ) ) {
		animation.opts.start.call( elem, animation );
	}

	// Attach callbacks from options
	animation
		.progress( animation.opts.progress )
		.done( animation.opts.done, animation.opts.complete )
		.fail( animation.opts.fail )
		.always( animation.opts.always );

	jQuery.fx.timer(
		jQuery.extend( tick, {
			elem: elem,
			anim: animation,
			queue: animation.opts.queue
		} )
	);

	return animation;
}

jQuery.Animation = jQuery.extend( Animation, {

	tweeners: {
		"*": [ function( prop, value ) {
			var tween = this.createTween( prop, value );
			adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
			return tween;
		} ]
	},

	tweener: function( props, callback ) {
		if ( jQuery.isFunction( props ) ) {
			callback = props;
			props = [ "*" ];
		} else {
			props = props.match( rnothtmlwhite );
		}

		var prop,
			index = 0,
			length = props.length;

		for ( ; index < length; index++ ) {
			prop = props[ index ];
			Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
			Animation.tweeners[ prop ].unshift( callback );
		}
	},

	prefilters: [ defaultPrefilter ],

	prefilter: function( callback, prepend ) {
		if ( prepend ) {
			Animation.prefilters.unshift( callback );
		} else {
			Animation.prefilters.push( callback );
		}
	}
} );

jQuery.speed = function( speed, easing, fn ) {
	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
		complete: fn || !fn && easing ||
			jQuery.isFunction( speed ) && speed,
		duration: speed,
		easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
	};

	// Go to the end state if fx are off
	if ( jQuery.fx.off ) {
		opt.duration = 0;

	} else {
		if ( typeof opt.duration !== "number" ) {
			if ( opt.duration in jQuery.fx.speeds ) {
				opt.duration = jQuery.fx.speeds[ opt.duration ];

			} else {
				opt.duration = jQuery.fx.speeds._default;
			}
		}
	}

	// Normalize opt.queue - true/undefined/null -> "fx"
	if ( opt.queue == null || opt.queue === true ) {
		opt.queue = "fx";
	}

	// Queueing
	opt.old = opt.complete;

	opt.complete = function() {
		if ( jQuery.isFunction( opt.old ) ) {
			opt.old.call( this );
		}

		if ( opt.queue ) {
			jQuery.dequeue( this, opt.queue );
		}
	};

	return opt;
};

jQuery.fn.extend( {
	fadeTo: function( speed, to, easing, callback ) {

		// Show any hidden elements after setting opacity to 0
		return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()

			// Animate to the value specified
			.end().animate( { opacity: to }, speed, easing, callback );
	},
	animate: function( prop, speed, easing, callback ) {
		var empty = jQuery.isEmptyObject( prop ),
			optall = jQuery.speed( speed, easing, callback ),
			doAnimation = function() {

				// Operate on a copy of prop so per-property easing won't be lost
				var anim = Animation( this, jQuery.extend( {}, prop ), optall );

				// Empty animations, or finishing resolves immediately
				if ( empty || dataPriv.get( this, "finish" ) ) {
					anim.stop( true );
				}
			};
			doAnimation.finish = doAnimation;

		return empty || optall.queue === false ?
			this.each( doAnimation ) :
			this.queue( optall.queue, doAnimation );
	},
	stop: function( type, clearQueue, gotoEnd ) {
		var stopQueue = function( hooks ) {
			var stop = hooks.stop;
			delete hooks.stop;
			stop( gotoEnd );
		};

		if ( typeof type !== "string" ) {
			gotoEnd = clearQueue;
			clearQueue = type;
			type = undefined;
		}
		if ( clearQueue && type !== false ) {
			this.queue( type || "fx", [] );
		}

		return this.each( function() {
			var dequeue = true,
				index = type != null && type + "queueHooks",
				timers = jQuery.timers,
				data = dataPriv.get( this );

			if ( index ) {
				if ( data[ index ] && data[ index ].stop ) {
					stopQueue( data[ index ] );
				}
			} else {
				for ( index in data ) {
					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
						stopQueue( data[ index ] );
					}
				}
			}

			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this &&
					( type == null || timers[ index ].queue === type ) ) {

					timers[ index ].anim.stop( gotoEnd );
					dequeue = false;
					timers.splice( index, 1 );
				}
			}

			// Start the next in the queue if the last step wasn't forced.
			// Timers currently will call their complete callbacks, which
			// will dequeue but only if they were gotoEnd.
			if ( dequeue || !gotoEnd ) {
				jQuery.dequeue( this, type );
			}
		} );
	},
	finish: function( type ) {
		if ( type !== false ) {
			type = type || "fx";
		}
		return this.each( function() {
			var index,
				data = dataPriv.get( this ),
				queue = data[ type + "queue" ],
				hooks = data[ type + "queueHooks" ],
				timers = jQuery.timers,
				length = queue ? queue.length : 0;

			// Enable finishing flag on private data
			data.finish = true;

			// Empty the queue first
			jQuery.queue( this, type, [] );

			if ( hooks && hooks.stop ) {
				hooks.stop.call( this, true );
			}

			// Look for any active animations, and finish them
			for ( index = timers.length; index--; ) {
				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
					timers[ index ].anim.stop( true );
					timers.splice( index, 1 );
				}
			}

			// Look for any animations in the old queue and finish them
			for ( index = 0; index < length; index++ ) {
				if ( queue[ index ] && queue[ index ].finish ) {
					queue[ index ].finish.call( this );
				}
			}

			// Turn off finishing flag
			delete data.finish;
		} );
	}
} );

jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
	var cssFn = jQuery.fn[ name ];
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return speed == null || typeof speed === "boolean" ?
			cssFn.apply( this, arguments ) :
			this.animate( genFx( name, true ), speed, easing, callback );
	};
} );

// Generate shortcuts for custom animations
jQuery.each( {
	slideDown: genFx( "show" ),
	slideUp: genFx( "hide" ),
	slideToggle: genFx( "toggle" ),
	fadeIn: { opacity: "show" },
	fadeOut: { opacity: "hide" },
	fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
	jQuery.fn[ name ] = function( speed, easing, callback ) {
		return this.animate( props, speed, easing, callback );
	};
} );

jQuery.timers = [];
jQuery.fx.tick = function() {
	var timer,
		i = 0,
		timers = jQuery.timers;

	fxNow = jQuery.now();

	for ( ; i < timers.length; i++ ) {
		timer = timers[ i ];

		// Run the timer and safely remove it when done (allowing for external removal)
		if ( !timer() && timers[ i ] === timer ) {
			timers.splice( i--, 1 );
		}
	}

	if ( !timers.length ) {
		jQuery.fx.stop();
	}
	fxNow = undefined;
};

jQuery.fx.timer = function( timer ) {
	jQuery.timers.push( timer );
	jQuery.fx.start();
};

jQuery.fx.interval = 13;
jQuery.fx.start = function() {
	if ( inProgress ) {
		return;
	}

	inProgress = true;
	schedule();
};

jQuery.fx.stop = function() {
	inProgress = null;
};

jQuery.fx.speeds = {
	slow: 600,
	fast: 200,

	// Default speed
	_default: 400
};


// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
	type = type || "fx";

	return this.queue( type, function( next, hooks ) {
		var timeout = window.setTimeout( next, time );
		hooks.stop = function() {
			window.clearTimeout( timeout );
		};
	} );
};


( function() {
	var input = document.createElement( "input" ),
		select = document.createElement( "select" ),
		opt = select.appendChild( document.createElement( "option" ) );

	input.type = "checkbox";

	// Support: Android <=4.3 only
	// Default value for a checkbox should be "on"
	support.checkOn = input.value !== "";

	// Support: IE <=11 only
	// Must access selectedIndex to make default options select
	support.optSelected = opt.selected;

	// Support: IE <=11 only
	// An input loses its value after becoming a radio
	input = document.createElement( "input" );
	input.value = "t";
	input.type = "radio";
	support.radioValue = input.value === "t";
} )();


var boolHook,
	attrHandle = jQuery.expr.attrHandle;

jQuery.fn.extend( {
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},

	removeAttr: function( name ) {
		return this.each( function() {
			jQuery.removeAttr( this, name );
		} );
	}
} );

jQuery.extend( {
	attr: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set attributes on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// Fallback to prop when attributes are not supported
		if ( typeof elem.getAttribute === "undefined" ) {
			return jQuery.prop( elem, name, value );
		}

		// Attribute hooks are determined by the lowercase version
		// Grab necessary hook if one is defined
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
		}

		if ( value !== undefined ) {
			if ( value === null ) {
				jQuery.removeAttr( elem, name );
				return;
			}

			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			elem.setAttribute( name, value + "" );
			return value;
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		ret = jQuery.find.attr( elem, name );

		// Non-existent attributes return null, we normalize to undefined
		return ret == null ? undefined : ret;
	},

	attrHooks: {
		type: {
			set: function( elem, value ) {
				if ( !support.radioValue && value === "radio" &&
					nodeName( elem, "input" ) ) {
					var val = elem.value;
					elem.setAttribute( "type", value );
					if ( val ) {
						elem.value = val;
					}
					return value;
				}
			}
		}
	},

	removeAttr: function( elem, value ) {
		var name,
			i = 0,

			// Attribute names can contain non-HTML whitespace characters
			// https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
			attrNames = value && value.match( rnothtmlwhite );

		if ( attrNames && elem.nodeType === 1 ) {
			while ( ( name = attrNames[ i++ ] ) ) {
				elem.removeAttribute( name );
			}
		}
	}
} );

// Hooks for boolean attributes
boolHook = {
	set: function( elem, value, name ) {
		if ( value === false ) {

			// Remove boolean attributes when set to false
			jQuery.removeAttr( elem, name );
		} else {
			elem.setAttribute( name, name );
		}
		return name;
	}
};

jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
	var getter = attrHandle[ name ] || jQuery.find.attr;

	attrHandle[ name ] = function( elem, name, isXML ) {
		var ret, handle,
			lowercaseName = name.toLowerCase();

		if ( !isXML ) {

			// Avoid an infinite loop by temporarily removing this function from the getter
			handle = attrHandle[ lowercaseName ];
			attrHandle[ lowercaseName ] = ret;
			ret = getter( elem, name, isXML ) != null ?
				lowercaseName :
				null;
			attrHandle[ lowercaseName ] = handle;
		}
		return ret;
	};
} );




var rfocusable = /^(?:input|select|textarea|button)$/i,
	rclickable = /^(?:a|area)$/i;

jQuery.fn.extend( {
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},

	removeProp: function( name ) {
		return this.each( function() {
			delete this[ jQuery.propFix[ name ] || name ];
		} );
	}
} );

jQuery.extend( {
	prop: function( elem, name, value ) {
		var ret, hooks,
			nType = elem.nodeType;

		// Don't get/set properties on text, comment and attribute nodes
		if ( nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {

			// Fix name and attach hooks
			name = jQuery.propFix[ name ] || name;
			hooks = jQuery.propHooks[ name ];
		}

		if ( value !== undefined ) {
			if ( hooks && "set" in hooks &&
				( ret = hooks.set( elem, value, name ) ) !== undefined ) {
				return ret;
			}

			return ( elem[ name ] = value );
		}

		if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
			return ret;
		}

		return elem[ name ];
	},

	propHooks: {
		tabIndex: {
			get: function( elem ) {

				// Support: IE <=9 - 11 only
				// elem.tabIndex doesn't always return the
				// correct value when it hasn't been explicitly set
				// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
				// Use proper attribute retrieval(#12072)
				var tabindex = jQuery.find.attr( elem, "tabindex" );

				if ( tabindex ) {
					return parseInt( tabindex, 10 );
				}

				if (
					rfocusable.test( elem.nodeName ) ||
					rclickable.test( elem.nodeName ) &&
					elem.href
				) {
					return 0;
				}

				return -1;
			}
		}
	},

	propFix: {
		"for": "htmlFor",
		"class": "className"
	}
} );

// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
// eslint rule "no-unused-expressions" is disabled for this code
// since it considers such accessions noop
if ( !support.optSelected ) {
	jQuery.propHooks.selected = {
		get: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent && parent.parentNode ) {
				parent.parentNode.selectedIndex;
			}
			return null;
		},
		set: function( elem ) {

			/* eslint no-unused-expressions: "off" */

			var parent = elem.parentNode;
			if ( parent ) {
				parent.selectedIndex;

				if ( parent.parentNode ) {
					parent.parentNode.selectedIndex;
				}
			}
		}
	};
}

jQuery.each( [
	"tabIndex",
	"readOnly",
	"maxLength",
	"cellSpacing",
	"cellPadding",
	"rowSpan",
	"colSpan",
	"useMap",
	"frameBorder",
	"contentEditable"
], function() {
	jQuery.propFix[ this.toLowerCase() ] = this;
} );




	// Strip and collapse whitespace according to HTML spec
	// https://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace
	function stripAndCollapse( value ) {
		var tokens = value.match( rnothtmlwhite ) || [];
		return tokens.join( " " );
	}


function getClass( elem ) {
	return elem.getAttribute && elem.getAttribute( "class" ) || "";
}

jQuery.fn.extend( {
	addClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnothtmlwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {
						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
							cur += clazz + " ";
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	removeClass: function( value ) {
		var classes, elem, cur, curValue, clazz, j, finalValue,
			i = 0;

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( j ) {
				jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
			} );
		}

		if ( !arguments.length ) {
			return this.attr( "class", "" );
		}

		if ( typeof value === "string" && value ) {
			classes = value.match( rnothtmlwhite ) || [];

			while ( ( elem = this[ i++ ] ) ) {
				curValue = getClass( elem );

				// This expression is here for better compressibility (see addClass)
				cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );

				if ( cur ) {
					j = 0;
					while ( ( clazz = classes[ j++ ] ) ) {

						// Remove *all* instances
						while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
							cur = cur.replace( " " + clazz + " ", " " );
						}
					}

					// Only assign if different to avoid unneeded rendering.
					finalValue = stripAndCollapse( cur );
					if ( curValue !== finalValue ) {
						elem.setAttribute( "class", finalValue );
					}
				}
			}
		}

		return this;
	},

	toggleClass: function( value, stateVal ) {
		var type = typeof value;

		if ( typeof stateVal === "boolean" && type === "string" ) {
			return stateVal ? this.addClass( value ) : this.removeClass( value );
		}

		if ( jQuery.isFunction( value ) ) {
			return this.each( function( i ) {
				jQuery( this ).toggleClass(
					value.call( this, i, getClass( this ), stateVal ),
					stateVal
				);
			} );
		}

		return this.each( function() {
			var className, i, self, classNames;

			if ( type === "string" ) {

				// Toggle individual class names
				i = 0;
				self = jQuery( this );
				classNames = value.match( rnothtmlwhite ) || [];

				while ( ( className = classNames[ i++ ] ) ) {

					// Check each className given, space separated list
					if ( self.hasClass( className ) ) {
						self.removeClass( className );
					} else {
						self.addClass( className );
					}
				}

			// Toggle whole class name
			} else if ( value === undefined || type === "boolean" ) {
				className = getClass( this );
				if ( className ) {

					// Store className if set
					dataPriv.set( this, "__className__", className );
				}

				// If the element has a class name or if we're passed `false`,
				// then remove the whole classname (if there was one, the above saved it).
				// Otherwise bring back whatever was previously saved (if anything),
				// falling back to the empty string if nothing was stored.
				if ( this.setAttribute ) {
					this.setAttribute( "class",
						className || value === false ?
						"" :
						dataPriv.get( this, "__className__" ) || ""
					);
				}
			}
		} );
	},

	hasClass: function( selector ) {
		var className, elem,
			i = 0;

		className = " " + selector + " ";
		while ( ( elem = this[ i++ ] ) ) {
			if ( elem.nodeType === 1 &&
				( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
					return true;
			}
		}

		return false;
	}
} );




var rreturn = /\r/g;

jQuery.fn.extend( {
	val: function( value ) {
		var hooks, ret, isFunction,
			elem = this[ 0 ];

		if ( !arguments.length ) {
			if ( elem ) {
				hooks = jQuery.valHooks[ elem.type ] ||
					jQuery.valHooks[ elem.nodeName.toLowerCase() ];

				if ( hooks &&
					"get" in hooks &&
					( ret = hooks.get( elem, "value" ) ) !== undefined
				) {
					return ret;
				}

				ret = elem.value;

				// Handle most common string cases
				if ( typeof ret === "string" ) {
					return ret.replace( rreturn, "" );
				}

				// Handle cases where value is null/undef or number
				return ret == null ? "" : ret;
			}

			return;
		}

		isFunction = jQuery.isFunction( value );

		return this.each( function( i ) {
			var val;

			if ( this.nodeType !== 1 ) {
				return;
			}

			if ( isFunction ) {
				val = value.call( this, i, jQuery( this ).val() );
			} else {
				val = value;
			}

			// Treat null/undefined as ""; convert numbers to string
			if ( val == null ) {
				val = "";

			} else if ( typeof val === "number" ) {
				val += "";

			} else if ( Array.isArray( val ) ) {
				val = jQuery.map( val, function( value ) {
					return value == null ? "" : value + "";
				} );
			}

			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

			// If set returns undefined, fall back to normal setting
			if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
				this.value = val;
			}
		} );
	}
} );

jQuery.extend( {
	valHooks: {
		option: {
			get: function( elem ) {

				var val = jQuery.find.attr( elem, "value" );
				return val != null ?
					val :

					// Support: IE <=10 - 11 only
					// option.text throws exceptions (#14686, #14858)
					// Strip and collapse whitespace
					// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
					stripAndCollapse( jQuery.text( elem ) );
			}
		},
		select: {
			get: function( elem ) {
				var value, option, i,
					options = elem.options,
					index = elem.selectedIndex,
					one = elem.type === "select-one",
					values = one ? null : [],
					max = one ? index + 1 : options.length;

				if ( index < 0 ) {
					i = max;

				} else {
					i = one ? index : 0;
				}

				// Loop through all the selected options
				for ( ; i < max; i++ ) {
					option = options[ i ];

					// Support: IE <=9 only
					// IE8-9 doesn't update selected after form reset (#2551)
					if ( ( option.selected || i === index ) &&

							// Don't return options that are disabled or in a disabled optgroup
							!option.disabled &&
							( !option.parentNode.disabled ||
								!nodeName( option.parentNode, "optgroup" ) ) ) {

						// Get the specific value for the option
						value = jQuery( option ).val();

						// We don't need an array for one selects
						if ( one ) {
							return value;
						}

						// Multi-Selects return an array
						values.push( value );
					}
				}

				return values;
			},

			set: function( elem, value ) {
				var optionSet, option,
					options = elem.options,
					values = jQuery.makeArray( value ),
					i = options.length;

				while ( i-- ) {
					option = options[ i ];

					/* eslint-disable no-cond-assign */

					if ( option.selected =
						jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
					) {
						optionSet = true;
					}

					/* eslint-enable no-cond-assign */
				}

				// Force browsers to behave consistently when non-matching value is set
				if ( !optionSet ) {
					elem.selectedIndex = -1;
				}
				return values;
			}
		}
	}
} );

// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
	jQuery.valHooks[ this ] = {
		set: function( elem, value ) {
			if ( Array.isArray( value ) ) {
				return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
			}
		}
	};
	if ( !support.checkOn ) {
		jQuery.valHooks[ this ].get = function( elem ) {
			return elem.getAttribute( "value" ) === null ? "on" : elem.value;
		};
	}
} );




// Return jQuery for attributes-only inclusion


var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;

jQuery.extend( jQuery.event, {

	trigger: function( event, data, elem, onlyHandlers ) {

		var i, cur, tmp, bubbleType, ontype, handle, special,
			eventPath = [ elem || document ],
			type = hasOwn.call( event, "type" ) ? event.type : event,
			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];

		cur = tmp = elem = elem || document;

		// Don't do events on text and comment nodes
		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
			return;
		}

		// focus/blur morphs to focusin/out; ensure we're not firing them right now
		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
			return;
		}

		if ( type.indexOf( "." ) > -1 ) {

			// Namespaced trigger; create a regexp to match event type in handle()
			namespaces = type.split( "." );
			type = namespaces.shift();
			namespaces.sort();
		}
		ontype = type.indexOf( ":" ) < 0 && "on" + type;

		// Caller can pass in a jQuery.Event object, Object, or just an event type string
		event = event[ jQuery.expando ] ?
			event :
			new jQuery.Event( type, typeof event === "object" && event );

		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
		event.isTrigger = onlyHandlers ? 2 : 3;
		event.namespace = namespaces.join( "." );
		event.rnamespace = event.namespace ?
			new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
			null;

		// Clean up the event in case it is being reused
		event.result = undefined;
		if ( !event.target ) {
			event.target = elem;
		}

		// Clone any incoming data and prepend the event, creating the handler arg list
		data = data == null ?
			[ event ] :
			jQuery.makeArray( data, [ event ] );

		// Allow special events to draw outside the lines
		special = jQuery.event.special[ type ] || {};
		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
			return;
		}

		// Determine event propagation path in advance, per W3C events spec (#9951)
		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {

			bubbleType = special.delegateType || type;
			if ( !rfocusMorph.test( bubbleType + type ) ) {
				cur = cur.parentNode;
			}
			for ( ; cur; cur = cur.parentNode ) {
				eventPath.push( cur );
				tmp = cur;
			}

			// Only add window if we got to document (e.g., not plain obj or detached DOM)
			if ( tmp === ( elem.ownerDocument || document ) ) {
				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
			}
		}

		// Fire handlers on the event path
		i = 0;
		while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {

			event.type = i > 1 ?
				bubbleType :
				special.bindType || type;

			// jQuery handler
			handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
				dataPriv.get( cur, "handle" );
			if ( handle ) {
				handle.apply( cur, data );
			}

			// Native handler
			handle = ontype && cur[ ontype ];
			if ( handle && handle.apply && acceptData( cur ) ) {
				event.result = handle.apply( cur, data );
				if ( event.result === false ) {
					event.preventDefault();
				}
			}
		}
		event.type = type;

		// If nobody prevented the default action, do it now
		if ( !onlyHandlers && !event.isDefaultPrevented() ) {

			if ( ( !special._default ||
				special._default.apply( eventPath.pop(), data ) === false ) &&
				acceptData( elem ) ) {

				// Call a native DOM method on the target with the same name as the event.
				// Don't do default actions on window, that's where global variables be (#6170)
				if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {

					// Don't re-trigger an onFOO event when we call its FOO() method
					tmp = elem[ ontype ];

					if ( tmp ) {
						elem[ ontype ] = null;
					}

					// Prevent re-triggering of the same event, since we already bubbled it above
					jQuery.event.triggered = type;
					elem[ type ]();
					jQuery.event.triggered = undefined;

					if ( tmp ) {
						elem[ ontype ] = tmp;
					}
				}
			}
		}

		return event.result;
	},

	// Piggyback on a donor event to simulate a different one
	// Used only for `focus(in | out)` events
	simulate: function( type, elem, event ) {
		var e = jQuery.extend(
			new jQuery.Event(),
			event,
			{
				type: type,
				isSimulated: true
			}
		);

		jQuery.event.trigger( e, null, elem );
	}

} );

jQuery.fn.extend( {

	trigger: function( type, data ) {
		return this.each( function() {
			jQuery.event.trigger( type, data, this );
		} );
	},
	triggerHandler: function( type, data ) {
		var elem = this[ 0 ];
		if ( elem ) {
			return jQuery.event.trigger( type, data, elem, true );
		}
	}
} );


jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup contextmenu" ).split( " " ),
	function( i, name ) {

	// Handle event binding
	jQuery.fn[ name ] = function( data, fn ) {
		return arguments.length > 0 ?
			this.on( name, null, data, fn ) :
			this.trigger( name );
	};
} );

jQuery.fn.extend( {
	hover: function( fnOver, fnOut ) {
		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
	}
} );




support.focusin = "onfocusin" in window;


// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
	jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {

		// Attach a single capturing handler on the document while someone wants focusin/focusout
		var handler = function( event ) {
			jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
		};

		jQuery.event.special[ fix ] = {
			setup: function() {
				var doc = this.ownerDocument || this,
					attaches = dataPriv.access( doc, fix );

				if ( !attaches ) {
					doc.addEventListener( orig, handler, true );
				}
				dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
			},
			teardown: function() {
				var doc = this.ownerDocument || this,
					attaches = dataPriv.access( doc, fix ) - 1;

				if ( !attaches ) {
					doc.removeEventListener( orig, handler, true );
					dataPriv.remove( doc, fix );

				} else {
					dataPriv.access( doc, fix, attaches );
				}
			}
		};
	} );
}
var location = window.location;

var nonce = jQuery.now();

var rquery = ( /\?/ );



// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
	var xml;
	if ( !data || typeof data !== "string" ) {
		return null;
	}

	// Support: IE 9 - 11 only
	// IE throws on parseFromString with invalid input.
	try {
		xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
	} catch ( e ) {
		xml = undefined;
	}

	if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
		jQuery.error( "Invalid XML: " + data );
	}
	return xml;
};


var
	rbracket = /\[\]$/,
	rCRLF = /\r?\n/g,
	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
	rsubmittable = /^(?:input|select|textarea|keygen)/i;

function buildParams( prefix, obj, traditional, add ) {
	var name;

	if ( Array.isArray( obj ) ) {

		// Serialize array item.
		jQuery.each( obj, function( i, v ) {
			if ( traditional || rbracket.test( prefix ) ) {

				// Treat each array item as a scalar.
				add( prefix, v );

			} else {

				// Item is non-scalar (array or object), encode its numeric index.
				buildParams(
					prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
					v,
					traditional,
					add
				);
			}
		} );

	} else if ( !traditional && jQuery.type( obj ) === "object" ) {

		// Serialize object item.
		for ( name in obj ) {
			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
		}

	} else {

		// Serialize scalar item.
		add( prefix, obj );
	}
}

// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
	var prefix,
		s = [],
		add = function( key, valueOrFunction ) {

			// If value is a function, invoke it and use its return value
			var value = jQuery.isFunction( valueOrFunction ) ?
				valueOrFunction() :
				valueOrFunction;

			s[ s.length ] = encodeURIComponent( key ) + "=" +
				encodeURIComponent( value == null ? "" : value );
		};

	// If an array was passed in, assume that it is an array of form elements.
	if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {

		// Serialize the form elements
		jQuery.each( a, function() {
			add( this.name, this.value );
		} );

	} else {

		// If traditional, encode the "old" way (the way 1.3.2 or older
		// did it), otherwise encode params recursively.
		for ( prefix in a ) {
			buildParams( prefix, a[ prefix ], traditional, add );
		}
	}

	// Return the resulting serialization
	return s.join( "&" );
};

jQuery.fn.extend( {
	serialize: function() {
		return jQuery.param( this.serializeArray() );
	},
	serializeArray: function() {
		return this.map( function() {

			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} )
		.filter( function() {
			var type = this.type;

			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} )
		.map( function( i, elem ) {
			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}

			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}

			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
} );


var
	r20 = /%20/g,
	rhash = /#.*$/,
	rantiCache = /([?&])_=[^&]*/,
	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,

	// #7653, #8125, #8152: local protocol detection
	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
	rnoContent = /^(?:GET|HEAD)$/,
	rprotocol = /^\/\//,

	/* Prefilters
	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
	 * 2) These are called:
	 *    - BEFORE asking for a transport
	 *    - AFTER param serialization (s.data is a string if s.processData is true)
	 * 3) key is the dataType
	 * 4) the catchall symbol "*" can be used
	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
	 */
	prefilters = {},

	/* Transports bindings
	 * 1) key is the dataType
	 * 2) the catchall symbol "*" can be used
	 * 3) selection will start with transport dataType and THEN go to "*" if needed
	 */
	transports = {},

	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
	allTypes = "*/".concat( "*" ),

	// Anchor tag for parsing the document origin
	originAnchor = document.createElement( "a" );
	originAnchor.href = location.href;

// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {

	// dataTypeExpression is optional and defaults to "*"
	return function( dataTypeExpression, func ) {

		if ( typeof dataTypeExpression !== "string" ) {
			func = dataTypeExpression;
			dataTypeExpression = "*";
		}

		var dataType,
			i = 0,
			dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];

		if ( jQuery.isFunction( func ) ) {

			// For each dataType in the dataTypeExpression
			while ( ( dataType = dataTypes[ i++ ] ) ) {

				// Prepend if requested
				if ( dataType[ 0 ] === "+" ) {
					dataType = dataType.slice( 1 ) || "*";
					( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );

				// Otherwise append
				} else {
					( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
				}
			}
		}
	};
}

// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {

	var inspected = {},
		seekingTransport = ( structure === transports );

	function inspect( dataType ) {
		var selected;
		inspected[ dataType ] = true;
		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
			if ( typeof dataTypeOrTransport === "string" &&
				!seekingTransport && !inspected[ dataTypeOrTransport ] ) {

				options.dataTypes.unshift( dataTypeOrTransport );
				inspect( dataTypeOrTransport );
				return false;
			} else if ( seekingTransport ) {
				return !( selected = dataTypeOrTransport );
			}
		} );
		return selected;
	}

	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}

// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
	var key, deep,
		flatOptions = jQuery.ajaxSettings.flatOptions || {};

	for ( key in src ) {
		if ( src[ key ] !== undefined ) {
			( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
		}
	}
	if ( deep ) {
		jQuery.extend( true, target, deep );
	}

	return target;
}

/* Handles responses to an ajax request:
 * - finds the right dataType (mediates between content-type and expected dataType)
 * - returns the corresponding response
 */
function ajaxHandleResponses( s, jqXHR, responses ) {

	var ct, type, finalDataType, firstDataType,
		contents = s.contents,
		dataTypes = s.dataTypes;

	// Remove auto dataType and get content-type in the process
	while ( dataTypes[ 0 ] === "*" ) {
		dataTypes.shift();
		if ( ct === undefined ) {
			ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
		}
	}

	// Check if we're dealing with a known content-type
	if ( ct ) {
		for ( type in contents ) {
			if ( contents[ type ] && contents[ type ].test( ct ) ) {
				dataTypes.unshift( type );
				break;
			}
		}
	}

	// Check to see if we have a response for the expected dataType
	if ( dataTypes[ 0 ] in responses ) {
		finalDataType = dataTypes[ 0 ];
	} else {

		// Try convertible dataTypes
		for ( type in responses ) {
			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
				finalDataType = type;
				break;
			}
			if ( !firstDataType ) {
				firstDataType = type;
			}
		}

		// Or just use first one
		finalDataType = finalDataType || firstDataType;
	}

	// If we found a dataType
	// We add the dataType to the list if needed
	// and return the corresponding response
	if ( finalDataType ) {
		if ( finalDataType !== dataTypes[ 0 ] ) {
			dataTypes.unshift( finalDataType );
		}
		return responses[ finalDataType ];
	}
}

/* Chain conversions given the request and the original response
 * Also sets the responseXXX fields on the jqXHR instance
 */
function ajaxConvert( s, response, jqXHR, isSuccess ) {
	var conv2, current, conv, tmp, prev,
		converters = {},

		// Work with a copy of dataTypes in case we need to modify it for conversion
		dataTypes = s.dataTypes.slice();

	// Create converters map with lowercased keys
	if ( dataTypes[ 1 ] ) {
		for ( conv in s.converters ) {
			converters[ conv.toLowerCase() ] = s.converters[ conv ];
		}
	}

	current = dataTypes.shift();

	// Convert to each sequential dataType
	while ( current ) {

		if ( s.responseFields[ current ] ) {
			jqXHR[ s.responseFields[ current ] ] = response;
		}

		// Apply the dataFilter if provided
		if ( !prev && isSuccess && s.dataFilter ) {
			response = s.dataFilter( response, s.dataType );
		}

		prev = current;
		current = dataTypes.shift();

		if ( current ) {

			// There's only work to do if current dataType is non-auto
			if ( current === "*" ) {

				current = prev;

			// Convert response if prev dataType is non-auto and differs from current
			} else if ( prev !== "*" && prev !== current ) {

				// Seek a direct converter
				conv = converters[ prev + " " + current ] || converters[ "* " + current ];

				// If none found, seek a pair
				if ( !conv ) {
					for ( conv2 in converters ) {

						// If conv2 outputs current
						tmp = conv2.split( " " );
						if ( tmp[ 1 ] === current ) {

							// If prev can be converted to accepted input
							conv = converters[ prev + " " + tmp[ 0 ] ] ||
								converters[ "* " + tmp[ 0 ] ];
							if ( conv ) {

								// Condense equivalence converters
								if ( conv === true ) {
									conv = converters[ conv2 ];

								// Otherwise, insert the intermediate dataType
								} else if ( converters[ conv2 ] !== true ) {
									current = tmp[ 0 ];
									dataTypes.unshift( tmp[ 1 ] );
								}
								break;
							}
						}
					}
				}

				// Apply converter (if not an equivalence)
				if ( conv !== true ) {

					// Unless errors are allowed to bubble, catch and return them
					if ( conv && s.throws ) {
						response = conv( response );
					} else {
						try {
							response = conv( response );
						} catch ( e ) {
							return {
								state: "parsererror",
								error: conv ? e : "No conversion from " + prev + " to " + current
							};
						}
					}
				}
			}
		}
	}

	return { state: "success", data: response };
}

jQuery.extend( {

	// Counter for holding the number of active queries
	active: 0,

	// Last-Modified header cache for next request
	lastModified: {},
	etag: {},

	ajaxSettings: {
		url: location.href,
		type: "GET",
		isLocal: rlocalProtocol.test( location.protocol ),
		global: true,
		processData: true,
		async: true,
		contentType: "application/x-www-form-urlencoded; charset=UTF-8",

		/*
		timeout: 0,
		data: null,
		dataType: null,
		username: null,
		password: null,
		cache: null,
		throws: false,
		traditional: false,
		headers: {},
		*/

		accepts: {
			"*": allTypes,
			text: "text/plain",
			html: "text/html",
			xml: "application/xml, text/xml",
			json: "application/json, text/javascript"
		},

		contents: {
			xml: /\bxml\b/,
			html: /\bhtml/,
			json: /\bjson\b/
		},

		responseFields: {
			xml: "responseXML",
			text: "responseText",
			json: "responseJSON"
		},

		// Data converters
		// Keys separate source (or catchall "*") and destination types with a single space
		converters: {

			// Convert anything to text
			"* text": String,

			// Text to html (true = no transformation)
			"text html": true,

			// Evaluate text as a json expression
			"text json": JSON.parse,

			// Parse text as xml
			"text xml": jQuery.parseXML
		},

		// For options that shouldn't be deep extended:
		// you can add your own custom options here if
		// and when you create one that shouldn't be
		// deep extended (see ajaxExtend)
		flatOptions: {
			url: true,
			context: true
		}
	},

	// Creates a full fledged settings object into target
	// with both ajaxSettings and settings fields.
	// If target is omitted, writes into ajaxSettings.
	ajaxSetup: function( target, settings ) {
		return settings ?

			// Building a settings object
			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :

			// Extending ajaxSettings
			ajaxExtend( jQuery.ajaxSettings, target );
	},

	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
	ajaxTransport: addToPrefiltersOrTransports( transports ),

	// Main method
	ajax: function( url, options ) {

		// If url is an object, simulate pre-1.5 signature
		if ( typeof url === "object" ) {
			options = url;
			url = undefined;
		}

		// Force options to be an object
		options = options || {};

		var transport,

			// URL without anti-cache param
			cacheURL,

			// Response headers
			responseHeadersString,
			responseHeaders,

			// timeout handle
			timeoutTimer,

			// Url cleanup var
			urlAnchor,

			// Request state (becomes false upon send and true upon completion)
			completed,

			// To know if global events are to be dispatched
			fireGlobals,

			// Loop variable
			i,

			// uncached part of the url
			uncached,

			// Create the final options object
			s = jQuery.ajaxSetup( {}, options ),

			// Callbacks context
			callbackContext = s.context || s,

			// Context for global events is callbackContext if it is a DOM node or jQuery collection
			globalEventContext = s.context &&
				( callbackContext.nodeType || callbackContext.jquery ) ?
					jQuery( callbackContext ) :
					jQuery.event,

			// Deferreds
			deferred = jQuery.Deferred(),
			completeDeferred = jQuery.Callbacks( "once memory" ),

			// Status-dependent callbacks
			statusCode = s.statusCode || {},

			// Headers (they are sent all at once)
			requestHeaders = {},
			requestHeadersNames = {},

			// Default abort message
			strAbort = "canceled",

			// Fake xhr
			jqXHR = {
				readyState: 0,

				// Builds headers hashtable if needed
				getResponseHeader: function( key ) {
					var match;
					if ( completed ) {
						if ( !responseHeaders ) {
							responseHeaders = {};
							while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
								responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
							}
						}
						match = responseHeaders[ key.toLowerCase() ];
					}
					return match == null ? null : match;
				},

				// Raw string
				getAllResponseHeaders: function() {
					return completed ? responseHeadersString : null;
				},

				// Caches the header
				setRequestHeader: function( name, value ) {
					if ( completed == null ) {
						name = requestHeadersNames[ name.toLowerCase() ] =
							requestHeadersNames[ name.toLowerCase() ] || name;
						requestHeaders[ name ] = value;
					}
					return this;
				},

				// Overrides response content-type header
				overrideMimeType: function( type ) {
					if ( completed == null ) {
						s.mimeType = type;
					}
					return this;
				},

				// Status-dependent callbacks
				statusCode: function( map ) {
					var code;
					if ( map ) {
						if ( completed ) {

							// Execute the appropriate callbacks
							jqXHR.always( map[ jqXHR.status ] );
						} else {

							// Lazy-add the new callbacks in a way that preserves old ones
							for ( code in map ) {
								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
							}
						}
					}
					return this;
				},

				// Cancel the request
				abort: function( statusText ) {
					var finalText = statusText || strAbort;
					if ( transport ) {
						transport.abort( finalText );
					}
					done( 0, finalText );
					return this;
				}
			};

		// Attach deferreds
		deferred.promise( jqXHR );

		// Add protocol if not provided (prefilters might expect it)
		// Handle falsy url in the settings object (#10093: consistency with old signature)
		// We also use the url parameter if available
		s.url = ( ( url || s.url || location.href ) + "" )
			.replace( rprotocol, location.protocol + "//" );

		// Alias method option to type as per ticket #12004
		s.type = options.method || options.type || s.method || s.type;

		// Extract dataTypes list
		s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];

		// A cross-domain request is in order when the origin doesn't match the current origin.
		if ( s.crossDomain == null ) {
			urlAnchor = document.createElement( "a" );

			// Support: IE <=8 - 11, Edge 12 - 13
			// IE throws exception on accessing the href property if url is malformed,
			// e.g. http://example.com:80x/
			try {
				urlAnchor.href = s.url;

				// Support: IE <=8 - 11 only
				// Anchor's host property isn't correctly set when s.url is relative
				urlAnchor.href = urlAnchor.href;
				s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
					urlAnchor.protocol + "//" + urlAnchor.host;
			} catch ( e ) {

				// If there is an error parsing the URL, assume it is crossDomain,
				// it can be rejected by the transport if it is invalid
				s.crossDomain = true;
			}
		}

		// Convert data if not already a string
		if ( s.data && s.processData && typeof s.data !== "string" ) {
			s.data = jQuery.param( s.data, s.traditional );
		}

		// Apply prefilters
		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );

		// If request was aborted inside a prefilter, stop there
		if ( completed ) {
			return jqXHR;
		}

		// We can fire global events as of now if asked to
		// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
		fireGlobals = jQuery.event && s.global;

		// Watch for a new set of requests
		if ( fireGlobals && jQuery.active++ === 0 ) {
			jQuery.event.trigger( "ajaxStart" );
		}

		// Uppercase the type
		s.type = s.type.toUpperCase();

		// Determine if request has content
		s.hasContent = !rnoContent.test( s.type );

		// Save the URL in case we're toying with the If-Modified-Since
		// and/or If-None-Match header later on
		// Remove hash to simplify url manipulation
		cacheURL = s.url.replace( rhash, "" );

		// More options handling for requests with no content
		if ( !s.hasContent ) {

			// Remember the hash so we can put it back
			uncached = s.url.slice( cacheURL.length );

			// If data is available, append data to url
			if ( s.data ) {
				cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;

				// #9682: remove data so that it's not used in an eventual retry
				delete s.data;
			}

			// Add or update anti-cache param if needed
			if ( s.cache === false ) {
				cacheURL = cacheURL.replace( rantiCache, "$1" );
				uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
			}

			// Put hash and anti-cache on the URL that will be requested (gh-1732)
			s.url = cacheURL + uncached;

		// Change '%20' to '+' if this is encoded form body content (gh-2658)
		} else if ( s.data && s.processData &&
			( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
			s.data = s.data.replace( r20, "+" );
		}

		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
		if ( s.ifModified ) {
			if ( jQuery.lastModified[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
			}
			if ( jQuery.etag[ cacheURL ] ) {
				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
			}
		}

		// Set the correct header, if data is being sent
		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
			jqXHR.setRequestHeader( "Content-Type", s.contentType );
		}

		// Set the Accepts header for the server, depending on the dataType
		jqXHR.setRequestHeader(
			"Accept",
			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
				s.accepts[ s.dataTypes[ 0 ] ] +
					( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
				s.accepts[ "*" ]
		);

		// Check for headers option
		for ( i in s.headers ) {
			jqXHR.setRequestHeader( i, s.headers[ i ] );
		}

		// Allow custom headers/mimetypes and early abort
		if ( s.beforeSend &&
			( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {

			// Abort if not done already and return
			return jqXHR.abort();
		}

		// Aborting is no longer a cancellation
		strAbort = "abort";

		// Install callbacks on deferreds
		completeDeferred.add( s.complete );
		jqXHR.done( s.success );
		jqXHR.fail( s.error );

		// Get transport
		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );

		// If no transport, we auto-abort
		if ( !transport ) {
			done( -1, "No Transport" );
		} else {
			jqXHR.readyState = 1;

			// Send global event
			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
			}

			// If request was aborted inside ajaxSend, stop there
			if ( completed ) {
				return jqXHR;
			}

			// Timeout
			if ( s.async && s.timeout > 0 ) {
				timeoutTimer = window.setTimeout( function() {
					jqXHR.abort( "timeout" );
				}, s.timeout );
			}

			try {
				completed = false;
				transport.send( requestHeaders, done );
			} catch ( e ) {

				// Rethrow post-completion exceptions
				if ( completed ) {
					throw e;
				}

				// Propagate others as results
				done( -1, e );
			}
		}

		// Callback for when everything is done
		function done( status, nativeStatusText, responses, headers ) {
			var isSuccess, success, error, response, modified,
				statusText = nativeStatusText;

			// Ignore repeat invocations
			if ( completed ) {
				return;
			}

			completed = true;

			// Clear timeout if it exists
			if ( timeoutTimer ) {
				window.clearTimeout( timeoutTimer );
			}

			// Dereference transport for early garbage collection
			// (no matter how long the jqXHR object will be used)
			transport = undefined;

			// Cache response headers
			responseHeadersString = headers || "";

			// Set readyState
			jqXHR.readyState = status > 0 ? 4 : 0;

			// Determine if successful
			isSuccess = status >= 200 && status < 300 || status === 304;

			// Get response data
			if ( responses ) {
				response = ajaxHandleResponses( s, jqXHR, responses );
			}

			// Convert no matter what (that way responseXXX fields are always set)
			response = ajaxConvert( s, response, jqXHR, isSuccess );

			// If successful, handle type chaining
			if ( isSuccess ) {

				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
				if ( s.ifModified ) {
					modified = jqXHR.getResponseHeader( "Last-Modified" );
					if ( modified ) {
						jQuery.lastModified[ cacheURL ] = modified;
					}
					modified = jqXHR.getResponseHeader( "etag" );
					if ( modified ) {
						jQuery.etag[ cacheURL ] = modified;
					}
				}

				// if no content
				if ( status === 204 || s.type === "HEAD" ) {
					statusText = "nocontent";

				// if not modified
				} else if ( status === 304 ) {
					statusText = "notmodified";

				// If we have data, let's convert it
				} else {
					statusText = response.state;
					success = response.data;
					error = response.error;
					isSuccess = !error;
				}
			} else {

				// Extract error from statusText and normalize for non-aborts
				error = statusText;
				if ( status || !statusText ) {
					statusText = "error";
					if ( status < 0 ) {
						status = 0;
					}
				}
			}

			// Set data for the fake xhr object
			jqXHR.status = status;
			jqXHR.statusText = ( nativeStatusText || statusText ) + "";

			// Success/Error
			if ( isSuccess ) {
				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
			} else {
				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
			}

			// Status-dependent callbacks
			jqXHR.statusCode( statusCode );
			statusCode = undefined;

			if ( fireGlobals ) {
				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
					[ jqXHR, s, isSuccess ? success : error ] );
			}

			// Complete
			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );

			if ( fireGlobals ) {
				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );

				// Handle the global AJAX counter
				if ( !( --jQuery.active ) ) {
					jQuery.event.trigger( "ajaxStop" );
				}
			}
		}

		return jqXHR;
	},

	getJSON: function( url, data, callback ) {
		return jQuery.get( url, data, callback, "json" );
	},

	getScript: function( url, callback ) {
		return jQuery.get( url, undefined, callback, "script" );
	}
} );

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( jQuery.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );


jQuery._evalUrl = function( url ) {
	return jQuery.ajax( {
		url: url,

		// Make this explicit, since user can override this through ajaxSetup (#11264)
		type: "GET",
		dataType: "script",
		cache: true,
		async: false,
		global: false,
		"throws": true
	} );
};


jQuery.fn.extend( {
	wrapAll: function( html ) {
		var wrap;

		if ( this[ 0 ] ) {
			if ( jQuery.isFunction( html ) ) {
				html = html.call( this[ 0 ] );
			}

			// The elements to wrap the target around
			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );

			if ( this[ 0 ].parentNode ) {
				wrap.insertBefore( this[ 0 ] );
			}

			wrap.map( function() {
				var elem = this;

				while ( elem.firstElementChild ) {
					elem = elem.firstElementChild;
				}

				return elem;
			} ).append( this );
		}

		return this;
	},

	wrapInner: function( html ) {
		if ( jQuery.isFunction( html ) ) {
			return this.each( function( i ) {
				jQuery( this ).wrapInner( html.call( this, i ) );
			} );
		}

		return this.each( function() {
			var self = jQuery( this ),
				contents = self.contents();

			if ( contents.length ) {
				contents.wrapAll( html );

			} else {
				self.append( html );
			}
		} );
	},

	wrap: function( html ) {
		var isFunction = jQuery.isFunction( html );

		return this.each( function( i ) {
			jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
		} );
	},

	unwrap: function( selector ) {
		this.parent( selector ).not( "body" ).each( function() {
			jQuery( this ).replaceWith( this.childNodes );
		} );
		return this;
	}
} );


jQuery.expr.pseudos.hidden = function( elem ) {
	return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
	return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};




jQuery.ajaxSettings.xhr = function() {
	try {
		return new window.XMLHttpRequest();
	} catch ( e ) {}
};

var xhrSuccessStatus = {

		// File protocol always yields status code 0, assume 200
		0: 200,

		// Support: IE <=9 only
		// #1450: sometimes IE returns 1223 when it should be 204
		1223: 204
	},
	xhrSupported = jQuery.ajaxSettings.xhr();

support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;

jQuery.ajaxTransport( function( options ) {
	var callback, errorCallback;

	// Cross domain only allowed if supported through XMLHttpRequest
	if ( support.cors || xhrSupported && !options.crossDomain ) {
		return {
			send: function( headers, complete ) {
				var i,
					xhr = options.xhr();

				xhr.open(
					options.type,
					options.url,
					options.async,
					options.username,
					options.password
				);

				// Apply custom fields if provided
				if ( options.xhrFields ) {
					for ( i in options.xhrFields ) {
						xhr[ i ] = options.xhrFields[ i ];
					}
				}

				// Override mime type if needed
				if ( options.mimeType && xhr.overrideMimeType ) {
					xhr.overrideMimeType( options.mimeType );
				}

				// X-Requested-With header
				// For cross-domain requests, seeing as conditions for a preflight are
				// akin to a jigsaw puzzle, we simply never set it to be sure.
				// (it can always be set on a per-request basis or even using ajaxSetup)
				// For same-domain requests, won't change header if already provided.
				if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
					headers[ "X-Requested-With" ] = "XMLHttpRequest";
				}

				// Set headers
				for ( i in headers ) {
					xhr.setRequestHeader( i, headers[ i ] );
				}

				// Callback
				callback = function( type ) {
					return function() {
						if ( callback ) {
							callback = errorCallback = xhr.onload =
								xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;

							if ( type === "abort" ) {
								xhr.abort();
							} else if ( type === "error" ) {

								// Support: IE <=9 only
								// On a manual native abort, IE9 throws
								// errors on any property access that is not readyState
								if ( typeof xhr.status !== "number" ) {
									complete( 0, "error" );
								} else {
									complete(

										// File: protocol always yields status 0; see #8605, #14207
										xhr.status,
										xhr.statusText
									);
								}
							} else {
								complete(
									xhrSuccessStatus[ xhr.status ] || xhr.status,
									xhr.statusText,

									// Support: IE <=9 only
									// IE9 has no XHR2 but throws on binary (trac-11426)
									// For XHR2 non-text, let the caller handle it (gh-2498)
									( xhr.responseType || "text" ) !== "text"  ||
									typeof xhr.responseText !== "string" ?
										{ binary: xhr.response } :
										{ text: xhr.responseText },
									xhr.getAllResponseHeaders()
								);
							}
						}
					};
				};

				// Listen to events
				xhr.onload = callback();
				errorCallback = xhr.onerror = callback( "error" );

				// Support: IE 9 only
				// Use onreadystatechange to replace onabort
				// to handle uncaught aborts
				if ( xhr.onabort !== undefined ) {
					xhr.onabort = errorCallback;
				} else {
					xhr.onreadystatechange = function() {

						// Check readyState before timeout as it changes
						if ( xhr.readyState === 4 ) {

							// Allow onerror to be called first,
							// but that will not handle a native abort
							// Also, save errorCallback to a variable
							// as xhr.onerror cannot be accessed
							window.setTimeout( function() {
								if ( callback ) {
									errorCallback();
								}
							} );
						}
					};
				}

				// Create the abort callback
				callback = callback( "abort" );

				try {

					// Do send the request (this may raise an exception)
					xhr.send( options.hasContent && options.data || null );
				} catch ( e ) {

					// #14683: Only rethrow if this hasn't been notified as an error yet
					if ( callback ) {
						throw e;
					}
				}
			},

			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
	if ( s.crossDomain ) {
		s.contents.script = false;
	}
} );

// Install script dataType
jQuery.ajaxSetup( {
	accepts: {
		script: "text/javascript, application/javascript, " +
			"application/ecmascript, application/x-ecmascript"
	},
	contents: {
		script: /\b(?:java|ecma)script\b/
	},
	converters: {
		"text script": function( text ) {
			jQuery.globalEval( text );
			return text;
		}
	}
} );

// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
	if ( s.cache === undefined ) {
		s.cache = false;
	}
	if ( s.crossDomain ) {
		s.type = "GET";
	}
} );

// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {

	// This transport only deals with cross domain requests
	if ( s.crossDomain ) {
		var script, callback;
		return {
			send: function( _, complete ) {
				script = jQuery( "<script>" ).prop( {
					charset: s.scriptCharset,
					src: s.url
				} ).on(
					"load error",
					callback = function( evt ) {
						script.remove();
						callback = null;
						if ( evt ) {
							complete( evt.type === "error" ? 404 : 200, evt.type );
						}
					}
				);

				// Use native DOM manipulation to avoid our domManip AJAX trickery
				document.head.appendChild( script[ 0 ] );
			},
			abort: function() {
				if ( callback ) {
					callback();
				}
			}
		};
	}
} );




var oldCallbacks = [],
	rjsonp = /(=)\?(?=&|$)|\?\?/;

// Default jsonp settings
jQuery.ajaxSetup( {
	jsonp: "callback",
	jsonpCallback: function() {
		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
		this[ callback ] = true;
		return callback;
	}
} );

// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {

	var callbackName, overwritten, responseContainer,
		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
			"url" :
			typeof s.data === "string" &&
				( s.contentType || "" )
					.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
				rjsonp.test( s.data ) && "data"
		);

	// Handle iff the expected data type is "jsonp" or we have a parameter to set
	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {

		// Get callback name, remembering preexisting value associated with it
		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
			s.jsonpCallback() :
			s.jsonpCallback;

		// Insert callback into url or form data
		if ( jsonProp ) {
			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
		} else if ( s.jsonp !== false ) {
			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
		}

		// Use data converter to retrieve json after script execution
		s.converters[ "script json" ] = function() {
			if ( !responseContainer ) {
				jQuery.error( callbackName + " was not called" );
			}
			return responseContainer[ 0 ];
		};

		// Force json dataType
		s.dataTypes[ 0 ] = "json";

		// Install callback
		overwritten = window[ callbackName ];
		window[ callbackName ] = function() {
			responseContainer = arguments;
		};

		// Clean-up function (fires after converters)
		jqXHR.always( function() {

			// If previous value didn't exist - remove it
			if ( overwritten === undefined ) {
				jQuery( window ).removeProp( callbackName );

			// Otherwise restore preexisting value
			} else {
				window[ callbackName ] = overwritten;
			}

			// Save back as free
			if ( s[ callbackName ] ) {

				// Make sure that re-using the options doesn't screw things around
				s.jsonpCallback = originalSettings.jsonpCallback;

				// Save the callback name for future use
				oldCallbacks.push( callbackName );
			}

			// Call if it was a function and we have a response
			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
				overwritten( responseContainer[ 0 ] );
			}

			responseContainer = overwritten = undefined;
		} );

		// Delegate to script
		return "script";
	}
} );




// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
	var body = document.implementation.createHTMLDocument( "" ).body;
	body.innerHTML = "<form></form><form></form>";
	return body.childNodes.length === 2;
} )();


// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
	if ( typeof data !== "string" ) {
		return [];
	}
	if ( typeof context === "boolean" ) {
		keepScripts = context;
		context = false;
	}

	var base, parsed, scripts;

	if ( !context ) {

		// Stop scripts or inline event handlers from being executed immediately
		// by using document.implementation
		if ( support.createHTMLDocument ) {
			context = document.implementation.createHTMLDocument( "" );

			// Set the base href for the created document
			// so any parsed elements with URLs
			// are based on the document's URL (gh-2965)
			base = context.createElement( "base" );
			base.href = document.location.href;
			context.head.appendChild( base );
		} else {
			context = document;
		}
	}

	parsed = rsingleTag.exec( data );
	scripts = !keepScripts && [];

	// Single tag
	if ( parsed ) {
		return [ context.createElement( parsed[ 1 ] ) ];
	}

	parsed = buildFragment( [ data ], context, scripts );

	if ( scripts && scripts.length ) {
		jQuery( scripts ).remove();
	}

	return jQuery.merge( [], parsed.childNodes );
};


/**
 * Load a url into a page
 */
jQuery.fn.load = function( url, params, callback ) {
	var selector, type, response,
		self = this,
		off = url.indexOf( " " );

	if ( off > -1 ) {
		selector = stripAndCollapse( url.slice( off ) );
		url = url.slice( 0, off );
	}

	// If it's a function
	if ( jQuery.isFunction( params ) ) {

		// We assume that it's the callback
		callback = params;
		params = undefined;

	// Otherwise, build a param string
	} else if ( params && typeof params === "object" ) {
		type = "POST";
	}

	// If we have elements to modify, make the request
	if ( self.length > 0 ) {
		jQuery.ajax( {
			url: url,

			// If "type" variable is undefined, then "GET" method will be used.
			// Make value of this field explicit since
			// user can override it through ajaxSetup method
			type: type || "GET",
			dataType: "html",
			data: params
		} ).done( function( responseText ) {

			// Save response for use in complete callback
			response = arguments;

			self.html( selector ?

				// If a selector was specified, locate the right elements in a dummy div
				// Exclude scripts to avoid IE 'Permission Denied' errors
				jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :

				// Otherwise use the full result
				responseText );

		// If the request succeeds, this function gets "data", "status", "jqXHR"
		// but they are ignored because response was set above.
		// If it fails, this function gets "jqXHR", "status", "error"
		} ).always( callback && function( jqXHR, status ) {
			self.each( function() {
				callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
			} );
		} );
	}

	return this;
};




// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
	"ajaxStart",
	"ajaxStop",
	"ajaxComplete",
	"ajaxError",
	"ajaxSuccess",
	"ajaxSend"
], function( i, type ) {
	jQuery.fn[ type ] = function( fn ) {
		return this.on( type, fn );
	};
} );




jQuery.expr.pseudos.animated = function( elem ) {
	return jQuery.grep( jQuery.timers, function( fn ) {
		return elem === fn.elem;
	} ).length;
};




jQuery.offset = {
	setOffset: function( elem, options, i ) {
		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
			position = jQuery.css( elem, "position" ),
			curElem = jQuery( elem ),
			props = {};

		// Set position first, in-case top/left are set even on static elem
		if ( position === "static" ) {
			elem.style.position = "relative";
		}

		curOffset = curElem.offset();
		curCSSTop = jQuery.css( elem, "top" );
		curCSSLeft = jQuery.css( elem, "left" );
		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
			( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;

		// Need to be able to calculate position if either
		// top or left is auto and position is either absolute or fixed
		if ( calculatePosition ) {
			curPosition = curElem.position();
			curTop = curPosition.top;
			curLeft = curPosition.left;

		} else {
			curTop = parseFloat( curCSSTop ) || 0;
			curLeft = parseFloat( curCSSLeft ) || 0;
		}

		if ( jQuery.isFunction( options ) ) {

			// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
			options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
		}

		if ( options.top != null ) {
			props.top = ( options.top - curOffset.top ) + curTop;
		}
		if ( options.left != null ) {
			props.left = ( options.left - curOffset.left ) + curLeft;
		}

		if ( "using" in options ) {
			options.using.call( elem, props );

		} else {
			curElem.css( props );
		}
	}
};

jQuery.fn.extend( {
	offset: function( options ) {

		// Preserve chaining for setter
		if ( arguments.length ) {
			return options === undefined ?
				this :
				this.each( function( i ) {
					jQuery.offset.setOffset( this, options, i );
				} );
		}

		var doc, docElem, rect, win,
			elem = this[ 0 ];

		if ( !elem ) {
			return;
		}

		// Return zeros for disconnected and hidden (display: none) elements (gh-2310)
		// Support: IE <=11 only
		// Running getBoundingClientRect on a
		// disconnected node in IE throws an error
		if ( !elem.getClientRects().length ) {
			return { top: 0, left: 0 };
		}

		rect = elem.getBoundingClientRect();

		doc = elem.ownerDocument;
		docElem = doc.documentElement;
		win = doc.defaultView;

		return {
			top: rect.top + win.pageYOffset - docElem.clientTop,
			left: rect.left + win.pageXOffset - docElem.clientLeft
		};
	},

	position: function() {
		if ( !this[ 0 ] ) {
			return;
		}

		var offsetParent, offset,
			elem = this[ 0 ],
			parentOffset = { top: 0, left: 0 };

		// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
		// because it is its only offset parent
		if ( jQuery.css( elem, "position" ) === "fixed" ) {

			// Assume getBoundingClientRect is there when computed position is fixed
			offset = elem.getBoundingClientRect();

		} else {

			// Get *real* offsetParent
			offsetParent = this.offsetParent();

			// Get correct offsets
			offset = this.offset();
			if ( !nodeName( offsetParent[ 0 ], "html" ) ) {
				parentOffset = offsetParent.offset();
			}

			// Add offsetParent borders
			parentOffset = {
				top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
				left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
			};
		}

		// Subtract parent offsets and element margins
		return {
			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
		};
	},

	// This method will return documentElement in the following cases:
	// 1) For the element inside the iframe without offsetParent, this method will return
	//    documentElement of the parent window
	// 2) For the hidden or detached element
	// 3) For body or html element, i.e. in case of the html node - it will return itself
	//
	// but those exceptions were never presented as a real life use-cases
	// and might be considered as more preferable results.
	//
	// This logic, however, is not guaranteed and can change at any point in the future
	offsetParent: function() {
		return this.map( function() {
			var offsetParent = this.offsetParent;

			while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
				offsetParent = offsetParent.offsetParent;
			}

			return offsetParent || documentElement;
		} );
	}
} );

// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
	var top = "pageYOffset" === prop;

	jQuery.fn[ method ] = function( val ) {
		return access( this, function( elem, method, val ) {

			// Coalesce documents and windows
			var win;
			if ( jQuery.isWindow( elem ) ) {
				win = elem;
			} else if ( elem.nodeType === 9 ) {
				win = elem.defaultView;
			}

			if ( val === undefined ) {
				return win ? win[ prop ] : elem[ method ];
			}

			if ( win ) {
				win.scrollTo(
					!top ? val : win.pageXOffset,
					top ? val : win.pageYOffset
				);

			} else {
				elem[ method ] = val;
			}
		}, method, val, arguments.length );
	};
} );

// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
		function( elem, computed ) {
			if ( computed ) {
				computed = curCSS( elem, prop );

				// If curCSS returns percentage, fallback to offset
				return rnumnonpx.test( computed ) ?
					jQuery( elem ).position()[ prop ] + "px" :
					computed;
			}
		}
	);
} );


// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
		function( defaultExtra, funcName ) {

		// Margin is only for outerHeight, outerWidth
		jQuery.fn[ funcName ] = function( margin, value ) {
			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );

			return access( this, function( elem, type, value ) {
				var doc;

				if ( jQuery.isWindow( elem ) ) {

					// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
					return funcName.indexOf( "outer" ) === 0 ?
						elem[ "inner" + name ] :
						elem.document.documentElement[ "client" + name ];
				}

				// Get document width or height
				if ( elem.nodeType === 9 ) {
					doc = elem.documentElement;

					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
					// whichever is greatest
					return Math.max(
						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
						elem.body[ "offset" + name ], doc[ "offset" + name ],
						doc[ "client" + name ]
					);
				}

				return value === undefined ?

					// Get width or height on the element, requesting but not forcing parseFloat
					jQuery.css( elem, type, extra ) :

					// Set width or height on the element
					jQuery.style( elem, type, value, extra );
			}, type, chainable ? margin : undefined, chainable );
		};
	} );
} );


jQuery.fn.extend( {

	bind: function( types, data, fn ) {
		return this.on( types, null, data, fn );
	},
	unbind: function( types, fn ) {
		return this.off( types, null, fn );
	},

	delegate: function( selector, types, data, fn ) {
		return this.on( types, selector, data, fn );
	},
	undelegate: function( selector, types, fn ) {

		// ( namespace ) or ( selector, types [, fn] )
		return arguments.length === 1 ?
			this.off( selector, "**" ) :
			this.off( types, selector || "**", fn );
	}
} );

jQuery.holdReady = function( hold ) {
	if ( hold ) {
		jQuery.readyWait++;
	} else {
		jQuery.ready( true );
	}
};
jQuery.isArray = Array.isArray;
jQuery.parseJSON = JSON.parse;
jQuery.nodeName = nodeName;




// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.

// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon

if ( typeof define === "function" && define.amd ) {
	define( "jquery", [], function() {
		return jQuery;
	} );
}




var

	// Map over jQuery in case of overwrite
	_jQuery = window.jQuery,

	// Map over the $ in case of overwrite
	_$ = window.$;

jQuery.noConflict = function( deep ) {
	if ( window.$ === jQuery ) {
		window.$ = _$;
	}

	if ( deep && window.jQuery === jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
	window.jQuery = window.$ = jQuery;
}




return jQuery;
} );
PK
%�\)��R�Rhtml/_static/jquery.jsnu�[���/*! jQuery v3.2.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.2.1",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null==a?f.call(this):a<0?this[a+this.length]:this[a]},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=Array.isArray(d)))?(e?(e=!1,f=c&&Array.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0&&("form"in a||"label"in a)},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"form"in b?b.parentNode&&b.disabled===!1?"label"in b?"label"in b.parentNode?b.parentNode.disabled===a:b.disabled===a:b.isDisabled===a||b.isDisabled!==!a&&ea(b)===a:b.disabled===a:"label"in b&&b.disabled===a}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}}):(d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}},d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c,d,e,f=b.getElementById(a);if(f){if(c=f.getAttributeNode("id"),c&&c.value===a)return[f];e=b.getElementsByName(a),d=0;while(f=e[d++])if(c=f.getAttributeNode("id"),c&&c.value===a)return[f]}return[]}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function ra(){}ra.prototype=d.filters=d.pseudos,d.setFilters=new ra,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=Q.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function sa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e);return!1}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}return!1}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d<e;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i<f;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i<e&&ya(a.slice(i,e)),e<f&&ya(a=a.slice(e)),e<f&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,c,e){var f,i,j,k,l,m="function"==typeof a&&a,n=!e&&g(a=m.selector||a);if(c=c||[],1===n.length){if(i=n[0]=n[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&9===b.nodeType&&p&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(_,aa),b)||[])[0],!b)return c;m&&(b=b.parentNode),a=a.slice(i.shift().value.length)}f=V.needsContext.test(a)?0:i.length;while(f--){if(j=i[f],d.relative[k=j.type])break;if((l=d.find[k])&&(e=l(j.matches[0].replace(_,aa),$.test(i[0].type)&&qa(b.parentNode)||b))){if(i.splice(f,1),a=e.length&&sa(i),!a)return G.apply(c,e),c;break}}}return(m||h(a,n))(e,b,!p,c,!b||$.test(a)&&qa(b.parentNode)||b),c},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext;function B(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()}var C=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,D=/^.[^:#\[\.,]*$/;function E(a,b,c){return r.isFunction(b)?r.grep(a,function(a,d){return!!b.call(a,d,a)!==c}):b.nodeType?r.grep(a,function(a){return a===b!==c}):"string"!=typeof b?r.grep(a,function(a){return i.call(b,a)>-1!==c}):D.test(b)?r.filter(b,a,c):(b=r.filter(b,a),r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType}))}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b<d;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;b<d;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(E(this,a||[],!1))},not:function(a){return this.pushStack(E(this,a||[],!0))},is:function(a){return!!E(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var F,G=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,H=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||F,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:G.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),C.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};H.prototype=r.fn,F=r(d);var I=/^(?:parents|prev(?:Until|All))/,J={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function K(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return K(a,"nextSibling")},prev:function(a){return K(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return B(a,"iframe")?a.contentDocument:(B(a,"template")&&(a=a.content||a),r.merge([],a.childNodes))}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(J[a]||r.uniqueSort(e),I.test(a)&&e.reverse()),this.pushStack(e)}});var L=/[^\x20\t\r\n\f]+/g;function M(a){var b={};return r.each(a.match(L)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?M(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=e||a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){r.each(b,function(b,c){r.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==r.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return r.each(arguments,function(a,b){var c;while((c=r.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function N(a){return a}function O(a){throw a}function P(a,b,c,d){var e;try{a&&r.isFunction(e=a.promise)?e.call(a).done(b).fail(c):a&&r.isFunction(e=a.then)?e.call(a,b,c):b.apply(void 0,[a].slice(d))}catch(a){c.apply(void 0,[a])}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b<f)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,N,e),g(f,c,O,e)):(f++,j.call(a,g(f,c,N,e),g(f,c,O,e),g(f,c,N,c.notifyWith))):(d!==N&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==O&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:N,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:N)),c[2][3].add(g(0,a,r.isFunction(d)?d:O))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(P(a,g.done(h(c)).resolve,g.reject,!b),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)P(e[c],h(c),g.reject);return g.promise()}});var Q=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&Q.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var R=r.Deferred();r.fn.ready=function(a){return R.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||R.resolveWith(d,[r]))}}),r.ready.then=R.then;function S(){d.removeEventListener("DOMContentLoaded",S),
a.removeEventListener("load",S),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",S),a.addEventListener("load",S));var T=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)T(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},U=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function V(){this.expando=r.expando+V.uid++}V.uid=1,V.prototype={cache:function(a){var b=a[this.expando];return b||(b={},U(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){Array.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(L)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var W=new V,X=new V,Y=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Z=/[A-Z]/g;function $(a){return"true"===a||"false"!==a&&("null"===a?null:a===+a+""?+a:Y.test(a)?JSON.parse(a):a)}function _(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Z,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c=$(c)}catch(e){}X.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return X.hasData(a)||W.hasData(a)},data:function(a,b,c){return X.access(a,b,c)},removeData:function(a,b){X.remove(a,b)},_data:function(a,b,c){return W.access(a,b,c)},_removeData:function(a,b){W.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=X.get(f),1===f.nodeType&&!W.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),_(f,d,e[d])));W.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){X.set(this,a)}):T(this,function(b){var c;if(f&&void 0===b){if(c=X.get(f,a),void 0!==c)return c;if(c=_(f,a),void 0!==c)return c}else this.each(function(){X.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){X.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=W.get(a,b),c&&(!d||Array.isArray(c)?d=W.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return W.get(a,c)||W.access(a,c,{empty:r.Callbacks("once memory").add(function(){W.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=W.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var aa=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,ba=new RegExp("^(?:([+-])=|)("+aa+")([a-z%]*)$","i"),ca=["Top","Right","Bottom","Left"],da=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},ea=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function fa(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&ba.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var ga={};function ha(a){var b,c=a.ownerDocument,d=a.nodeName,e=ga[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),ga[d]=e,e)}function ia(a,b){for(var c,d,e=[],f=0,g=a.length;f<g;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=W.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&da(d)&&(e[f]=ha(d))):"none"!==c&&(e[f]="none",W.set(d,"display",c)));for(f=0;f<g;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ia(this,!0)},hide:function(){return ia(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){da(this)?r(this).show():r(this).hide()})}});var ja=/^(?:checkbox|radio)$/i,ka=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,la=/^$|\/(?:java|ecma)script/i,ma={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ma.optgroup=ma.option,ma.tbody=ma.tfoot=ma.colgroup=ma.caption=ma.thead,ma.th=ma.td;function na(a,b){var c;return c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[],void 0===b||b&&B(a,b)?r.merge([a],c):c}function oa(a,b){for(var c=0,d=a.length;c<d;c++)W.set(a[c],"globalEval",!b||W.get(b[c],"globalEval"))}var pa=/<|&#?\w+;/;function qa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;n<o;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(pa.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ka.exec(f)||["",""])[1].toLowerCase(),i=ma[h]||ma._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=na(l.appendChild(f),"script"),j&&oa(g),c){k=0;while(f=g[k++])la.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var ra=d.documentElement,sa=/^key/,ta=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,ua=/^([^.]*)(?:\.(.+)|)/;function va(){return!0}function wa(){return!1}function xa(){try{return d.activeElement}catch(a){}}function ya(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)ya(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=wa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(ra,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(L)||[""],j=b.length;while(j--)h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=W.hasData(a)&&W.get(a);if(q&&(i=q.events)){b=(b||"").match(L)||[""],j=b.length;while(j--)if(h=ua.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&W.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(W.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c<arguments.length;c++)i[c]=arguments[c];if(b.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,b)!==!1){h=r.event.handlers.call(this,b,j),c=0;while((f=h[c++])&&!b.isPropagationStopped()){b.currentTarget=f.elem,d=0;while((g=f.handlers[d++])&&!b.isImmediatePropagationStopped())b.rnamespace&&!b.rnamespace.test(g.namespace)||(b.handleObj=g,b.data=g.data,e=((r.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(b.result=e)===!1&&(b.preventDefault(),b.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,b),b.result}},handlers:function(a,b){var c,d,e,f,g,h=[],i=b.delegateCount,j=a.target;if(i&&j.nodeType&&!("click"===a.type&&a.button>=1))for(;j!==this;j=j.parentNode||this)if(1===j.nodeType&&("click"!==a.type||j.disabled!==!0)){for(f=[],g={},c=0;c<i;c++)d=b[c],e=d.selector+" ",void 0===g[e]&&(g[e]=d.needsContext?r(e,this).index(j)>-1:r.find(e,this,null,[j]).length),g[e]&&f.push(d);f.length&&h.push({elem:j,handlers:f})}return j=this,i<b.length&&h.push({elem:j,handlers:b.slice(i)}),h},addProp:function(a,b){Object.defineProperty(r.Event.prototype,a,{enumerable:!0,configurable:!0,get:r.isFunction(b)?function(){if(this.originalEvent)return b(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[a]},set:function(b){Object.defineProperty(this,a,{enumerable:!0,configurable:!0,writable:!0,value:b})}})},fix:function(a){return a[r.expando]?a:new r.Event(a)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==xa()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===xa()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&B(this,"input"))return this.click(),!1},_default:function(a){return B(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},r.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},r.Event=function(a,b){return this instanceof r.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?va:wa,this.target=a.target&&3===a.target.nodeType?a.target.parentNode:a.target,this.currentTarget=a.currentTarget,this.relatedTarget=a.relatedTarget):this.type=a,b&&r.extend(this,b),this.timeStamp=a&&a.timeStamp||r.now(),void(this[r.expando]=!0)):new r.Event(a,b)},r.Event.prototype={constructor:r.Event,isDefaultPrevented:wa,isPropagationStopped:wa,isImmediatePropagationStopped:wa,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=va,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=va,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=va,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},r.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(a){var b=a.button;return null==a.which&&sa.test(a.type)?null!=a.charCode?a.charCode:a.keyCode:!a.which&&void 0!==b&&ta.test(a.type)?1&b?1:2&b?3:4&b?2:0:a.which}},r.event.addProp),r.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){r.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||r.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),r.fn.extend({on:function(a,b,c,d){return ya(this,a,b,c,d)},one:function(a,b,c,d){return ya(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,r(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=wa),this.each(function(){r.event.remove(this,a,c,b)})}});var za=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,Aa=/<script|<style|<link/i,Ba=/checked\s*(?:[^=]|=\s*.checked.)/i,Ca=/^true\/(.*)/,Da=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Ea(a,b){return B(a,"table")&&B(11!==b.nodeType?b:b.firstChild,"tr")?r(">tbody",a)[0]||a:a}function Fa(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ga(a){var b=Ca.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ha(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(W.hasData(a)&&(f=W.access(a),g=W.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)r.event.add(b,e,j[e][c])}X.hasData(a)&&(h=X.access(a),i=r.extend({},h),X.set(b,i))}}function Ia(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ja.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ja(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&Ba.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ja(f,b,c,d)});if(m&&(e=qa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(na(e,"script"),Fa),i=h.length;l<m;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,na(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Ga),l=0;l<i;l++)j=h[l],la.test(j.type||"")&&!W.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Da,""),k))}return a}function Ka(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(na(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&oa(na(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(za,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=na(h),f=na(a),d=0,e=f.length;d<e;d++)Ia(f[d],g[d]);if(b)if(c)for(f=f||na(a),g=g||na(h),d=0,e=f.length;d<e;d++)Ha(f[d],g[d]);else Ha(a,h);return g=na(h,"script"),g.length>0&&oa(g,!i&&na(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(U(c)){if(b=c[W.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[W.expando]=void 0}c[X.expando]&&(c[X.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ka(this,a,!0)},remove:function(a){return Ka(this,a)},text:function(a){return T(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.appendChild(a)}})},prepend:function(){return Ja(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ea(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ja(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(na(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return T(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!Aa.test(a)&&!ma[(ka.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(na(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ja(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(na(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;g<=f;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var La=/^margin/,Ma=new RegExp("^("+aa+")(?!px)[a-z%]+$","i"),Na=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",ra.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,ra.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Oa(a,b,c){var d,e,f,g,h=a.style;return c=c||Na(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&Ma.test(g)&&La.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Pa(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Qa=/^(none|table(?!-c[ea]).+)/,Ra=/^--/,Sa={position:"absolute",visibility:"hidden",display:"block"},Ta={letterSpacing:"0",fontWeight:"400"},Ua=["Webkit","Moz","ms"],Va=d.createElement("div").style;function Wa(a){if(a in Va)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ua.length;while(c--)if(a=Ua[c]+b,a in Va)return a}function Xa(a){var b=r.cssProps[a];return b||(b=r.cssProps[a]=Wa(a)||a),b}function Ya(a,b,c){var d=ba.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Za(a,b,c,d,e){var f,g=0;for(f=c===(d?"border":"content")?4:"width"===b?1:0;f<4;f+=2)"margin"===c&&(g+=r.css(a,c+ca[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+ca[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+ca[f]+"Width",!0,e))):(g+=r.css(a,"padding"+ca[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+ca[f]+"Width",!0,e)));return g}function $a(a,b,c){var d,e=Na(a),f=Oa(a,b,e),g="border-box"===r.css(a,"boxSizing",!1,e);return Ma.test(f)?f:(d=g&&(o.boxSizingReliable()||f===a.style[b]),"auto"===f&&(f=a["offset"+b[0].toUpperCase()+b.slice(1)]),f=parseFloat(f)||0,f+Za(a,b,c||(g?"border":"content"),d,e)+"px")}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Oa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=Ra.test(b),j=a.style;return i||(b=Xa(h)),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:j[b]:(f=typeof c,"string"===f&&(e=ba.exec(c))&&e[1]&&(c=fa(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(j[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i?j.setProperty(b,c):j[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b),i=Ra.test(b);return i||(b=Xa(h)),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Oa(a,b,d)),"normal"===e&&b in Ta&&(e=Ta[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){if(c)return!Qa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?$a(a,b,d):ea(a,Sa,function(){return $a(a,b,d)})},set:function(a,c,d){var e,f=d&&Na(a),g=d&&Za(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=ba.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Ya(a,c,g)}}}),r.cssHooks.marginLeft=Pa(o.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Oa(a,"marginLeft"))||a.getBoundingClientRect().left-ea(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+ca[d]+b]=f[d]||f[d-2]||f[0];return e}},La.test(a)||(r.cssHooks[a+b].set=Ya)}),r.fn.extend({css:function(a,b){return T(this,function(a,b,c){var d,e,f={},g=0;if(Array.isArray(b)){for(d=Na(a),e=b.length;g<e;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function _a(a,b,c,d,e){return new _a.prototype.init(a,b,c,d,e)}r.Tween=_a,_a.prototype={constructor:_a,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=_a.propHooks[this.prop];return a&&a.get?a.get(this):_a.propHooks._default.get(this)},run:function(a){var b,c=_a.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):_a.propHooks._default.set(this),this}},_a.prototype.init.prototype=_a.prototype,_a.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},_a.propHooks.scrollTop=_a.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=_a.prototype.init,r.fx.step={};var ab,bb,cb=/^(?:toggle|show|hide)$/,db=/queueHooks$/;function eb(){bb&&(d.hidden===!1&&a.requestAnimationFrame?a.requestAnimationFrame(eb):a.setTimeout(eb,r.fx.interval),r.fx.tick())}function fb(){return a.setTimeout(function(){ab=void 0}),ab=r.now()}function gb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=ca[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function hb(a,b,c){for(var d,e=(kb.tweeners[b]||[]).concat(kb.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function ib(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&da(a),q=W.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],cb.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=W.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ia([a],!0),j=a.style.display||j,k=r.css(a,"display"),ia([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=W.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ia([a],!0),m.done(function(){p||ia([a]),W.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=hb(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function jb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],Array.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function kb(a,b,c){var d,e,f=0,g=kb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=ab||fb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(i||h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:ab||fb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(jb(k,j.opts.specialEasing);f<g;f++)if(d=kb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,hb,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j}r.Animation=r.extend(kb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return fa(c.elem,a,ba.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(L);for(var c,d=0,e=a.length;d<e;d++)c=a[d],kb.tweeners[c]=kb.tweeners[c]||[],kb.tweeners[c].unshift(b)},prefilters:[ib],prefilter:function(a,b){b?kb.prefilters.unshift(a):kb.prefilters.push(a)}}),r.speed=function(a,b,c){var d=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off?d.duration=0:"number"!=typeof d.duration&&(d.duration in r.fx.speeds?d.duration=r.fx.speeds[d.duration]:d.duration=r.fx.speeds._default),null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){r.isFunction(d.old)&&d.old.call(this),d.queue&&r.dequeue(this,d.queue)},d},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(da).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=kb(this,r.extend({},a),f);(e||W.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=W.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&db.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=W.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(gb(b,!0),a,d,e)}}),r.each({slideDown:gb("show"),slideUp:gb("hide"),slideToggle:gb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(ab=r.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||r.fx.stop(),ab=void 0},r.fx.timer=function(a){r.timers.push(a),r.fx.start()},r.fx.interval=13,r.fx.start=function(){bb||(bb=!0,eb())},r.fx.stop=function(){bb=null},r.fx.speeds={slow:600,fast:200,_default:400},r.fn.delay=function(b,c){return b=r.fx?r.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",o.checkOn=""!==a.value,o.optSelected=c.selected,a=d.createElement("input"),a.value="t",a.type="radio",o.radioValue="t"===a.value}();var lb,mb=r.expr.attrHandle;r.fn.extend({attr:function(a,b){return T(this,r.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?lb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),
null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&B(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(L);if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),lb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=mb[b]||r.find.attr;mb[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=mb[g],mb[g]=e,e=null!=c(a,b,d)?g:null,mb[g]=f),e}});var nb=/^(?:input|select|textarea|button)$/i,ob=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return T(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):nb.test(a.nodeName)||ob.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});function pb(a){var b=a.match(L)||[];return b.join(" ")}function qb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,qb(this)))});if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,qb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(L)||[];while(c=this[i++])if(e=qb(c),d=1===c.nodeType&&" "+pb(e)+" "){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=pb(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,qb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(L)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=qb(this),b&&W.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":W.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+pb(qb(c))+" ").indexOf(b)>-1)return!0;return!1}});var rb=/\r/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":Array.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:pb(r.text(a))}},select:{get:function(a){var b,c,d,e=a.options,f=a.selectedIndex,g="select-one"===a.type,h=g?null:[],i=g?f+1:e.length;for(d=f<0?i:g?f:0;d<i;d++)if(c=e[d],(c.selected||d===f)&&!c.disabled&&(!c.parentNode.disabled||!B(c.parentNode,"optgroup"))){if(b=r(c).val(),g)return b;h.push(b)}return h},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(Array.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var sb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!sb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,sb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(W.get(h,"events")||{})[b.type]&&W.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&U(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!U(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=W.access(d,b);e||d.addEventListener(a,c,!0),W.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=W.access(d,b)-1;e?W.access(d,b,e):(d.removeEventListener(a,c,!0),W.remove(d,b))}}});var tb=a.location,ub=r.now(),vb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var wb=/\[\]$/,xb=/\r?\n/g,yb=/^(?:submit|button|image|reset|file)$/i,zb=/^(?:input|select|textarea|keygen)/i;function Ab(a,b,c,d){var e;if(Array.isArray(b))r.each(b,function(b,e){c||wb.test(a)?d(a,e):Ab(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)Ab(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(Array.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)Ab(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&zb.test(this.nodeName)&&!yb.test(a)&&(this.checked||!ja.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:Array.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(xb,"\r\n")}}):{name:b.name,value:c.replace(xb,"\r\n")}}).get()}});var Bb=/%20/g,Cb=/#.*$/,Db=/([?&])_=[^&]*/,Eb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Gb=/^(?:GET|HEAD)$/,Hb=/^\/\//,Ib={},Jb={},Kb="*/".concat("*"),Lb=d.createElement("a");Lb.href=tb.href;function Mb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(L)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nb(a,b,c,d){var e={},f=a===Jb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Ob(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Pb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Qb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:tb.href,type:"GET",isLocal:Fb.test(tb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Ob(Ob(a,r.ajaxSettings),b):Ob(r.ajaxSettings,a)},ajaxPrefilter:Mb(Ib),ajaxTransport:Mb(Jb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Eb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||tb.href)+"").replace(Hb,tb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(L)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Lb.protocol+"//"+Lb.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Nb(Ib,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Gb.test(o.type),f=o.url.replace(Cb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(Bb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(vb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Db,"$1"),n=(vb.test(f)?"&":"?")+"_="+ub++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Kb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Nb(Jb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Pb(o,y,d)),v=Qb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Rb={0:200,1223:204},Sb=r.ajaxSettings.xhr();o.cors=!!Sb&&"withCredentials"in Sb,o.ajax=Sb=!!Sb,r.ajaxTransport(function(b){var c,d;if(o.cors||Sb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Rb[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Tb=[],Ub=/(=)\?(?=&|$)|\?\?/;r.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Tb.pop()||r.expando+"_"+ub++;return this[a]=!0,a}}),r.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Ub.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ub.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=r.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Ub,"$1"+e):b.jsonp!==!1&&(b.url+=(vb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||r.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?r(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Tb.push(e)),g&&r.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),o.createHTMLDocument=function(){var a=d.implementation.createHTMLDocument("").body;return a.innerHTML="<form></form><form></form>",2===a.childNodes.length}(),r.parseHTML=function(a,b,c){if("string"!=typeof a)return[];"boolean"==typeof b&&(c=b,b=!1);var e,f,g;return b||(o.createHTMLDocument?(b=d.implementation.createHTMLDocument(""),e=b.createElement("base"),e.href=d.location.href,b.head.appendChild(e)):b=d),f=C.exec(a),g=!c&&[],f?[b.createElement(f[1])]:(f=qa([a],b,g),g&&g.length&&r(g).remove(),r.merge([],f.childNodes))},r.fn.load=function(a,b,c){var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=pb(a.slice(h)),a=a.slice(0,h)),r.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&r.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?r("<div>").append(r.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},r.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){r.fn[b]=function(a){return this.on(b,a)}}),r.expr.pseudos.animated=function(a){return r.grep(r.timers,function(b){return a===b.elem}).length},r.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=r.css(a,"position"),l=r(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=r.css(a,"top"),i=r.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),r.isFunction(b)&&(b=b.call(a,c,r.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},r.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){r.offset.setOffset(this,a,b)});var b,c,d,e,f=this[0];if(f)return f.getClientRects().length?(d=f.getBoundingClientRect(),b=f.ownerDocument,c=b.documentElement,e=b.defaultView,{top:d.top+e.pageYOffset-c.clientTop,left:d.left+e.pageXOffset-c.clientLeft}):{top:0,left:0}},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===r.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),B(a[0],"html")||(d=a.offset()),d={top:d.top+r.css(a[0],"borderTopWidth",!0),left:d.left+r.css(a[0],"borderLeftWidth",!0)}),{top:b.top-d.top-r.css(c,"marginTop",!0),left:b.left-d.left-r.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===r.css(a,"position"))a=a.offsetParent;return a||ra})}}),r.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;r.fn[a]=function(d){return T(this,function(a,d,e){var f;return r.isWindow(a)?f=a:9===a.nodeType&&(f=a.defaultView),void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),r.each(["top","left"],function(a,b){r.cssHooks[b]=Pa(o.pixelPosition,function(a,c){if(c)return c=Oa(a,b),Ma.test(c)?r(a).position()[b]+"px":c})}),r.each({Height:"height",Width:"width"},function(a,b){r.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){r.fn[d]=function(e,f){var g=arguments.length&&(c||"boolean"!=typeof e),h=c||(e===!0||f===!0?"margin":"border");return T(this,function(b,c,e){var f;return r.isWindow(b)?0===d.indexOf("outer")?b["inner"+a]:b.document.documentElement["client"+a]:9===b.nodeType?(f=b.documentElement,Math.max(b.body["scroll"+a],f["scroll"+a],b.body["offset"+a],f["offset"+a],f["client"+a])):void 0===e?r.css(b,c,h):r.style(b,c,e,h)},b,g?e:void 0,g)}})}),r.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),r.holdReady=function(a){a?r.readyWait++:r.ready(!0)},r.isArray=Array.isArray,r.parseJSON=JSON.parse,r.nodeName=B,"function"==typeof define&&define.amd&&define("jquery",[],function(){return r});var Vb=a.jQuery,Wb=a.$;return r.noConflict=function(b){return a.$===r&&(a.$=Wb),b&&a.jQuery===r&&(a.jQuery=Vb),r},b||(a.jQuery=a.$=r),r});
PK
%�\���ZZhtml/_static/minus.pngnu�[����PNG


IHDR��(�!IDATxc8�g>@�;(�!�&����]�f2n�NIEND�B`�PK
%�\�]l�==html/_static/opensearch.xmlnu�[���<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>Python</ShortName>
  <Description>Search Python 2.7.16 documentation</Description>
  <InputEncoding>utf-8</InputEncoding>
  <Url type="text/html" method="get"
       template="https://docs.python.org//search.html?q={searchTerms}&amp;check_keywords=yes&amp;area=default"/>
  <LongName>Python 2.7.16 documentation</LongName>
<Image height="16" width="16" type="image/x-icon">https://www.python.org/images/favicon16x16.ico</Image>
</OpenSearchDescription>PK
%�\��%ZZZhtml/_static/plus.pngnu�[����PNG


IHDR��(�!IDATxc8�g>@�;([�[�U�
@l-!a���@IEND�B`�PK
%�\��
ͷ�html/_static/py.pngnu�[����PNG


IHDR�asRGB���bKGD�������	pHYs��tIME�8!3'^7IDAT8�e�OHUA��{߳w{"���&hS�6�Z�mB*xP�MQ��A� "�)mZH� FEF������2���y3g��޼���;�7̜�]���3i�sޙv�M����U����}�\·�x'G�j�N,�Z�X�wQ���1 *�{
8k9g'v;�͏;�j�/t?|�[{\�
�N�j�E�%g�J=M}�W�Ҏ�}x��v�^�{�Tn�J�N���\}��X�nܯ�zw/��umY5;mg����Q�"	�SQ}�,�/�|��i���'}�S��@B�ځ�����������Wk�)`��j'�J/N�K@��e1M��FN,j}yhb�wp��+�щK�S�Xb��‹�@:����ɗ��_�=mU5�EqR'�4I�N&t:�c��祝�j�.l
��`zF�6��guG�f�pm"�����J��(p
�o���ٞ�q�G0�"���n��:"�,�%8��4��+!್`��DoY-��4�ً,߳5�3������gob�;��3c��]�I��i�ވ�C��
h�\nf]����������IEND�B`�PK
%�\�PlS++html/_static/pygments.cssnu�[���.highlight .hll { background-color: #ffffcc }
.highlight  { background: #eeffcc; }
.highlight .c { color: #408090; font-style: italic } /* Comment */
.highlight .err { border: 1px solid #FF0000 } /* Error */
.highlight .k { color: #007020; font-weight: bold } /* Keyword */
.highlight .o { color: #666666 } /* Operator */
.highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */
.highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */
.highlight .cp { color: #007020 } /* Comment.Preproc */
.highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */
.highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */
.highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #A00000 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #FF0000 } /* Generic.Error */
.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight .gi { color: #00A000 } /* Generic.Inserted */
.highlight .go { color: #333333 } /* Generic.Output */
.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight .gt { color: #0044DD } /* Generic.Traceback */
.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #007020 } /* Keyword.Pseudo */
.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #902000 } /* Keyword.Type */
.highlight .m { color: #208050 } /* Literal.Number */
.highlight .s { color: #4070a0 } /* Literal.String */
.highlight .na { color: #4070a0 } /* Name.Attribute */
.highlight .nb { color: #007020 } /* Name.Builtin */
.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */
.highlight .no { color: #60add5 } /* Name.Constant */
.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */
.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */
.highlight .ne { color: #007020 } /* Name.Exception */
.highlight .nf { color: #06287e } /* Name.Function */
.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */
.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #bb60d5 } /* Name.Variable */
.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #208050 } /* Literal.Number.Bin */
.highlight .mf { color: #208050 } /* Literal.Number.Float */
.highlight .mh { color: #208050 } /* Literal.Number.Hex */
.highlight .mi { color: #208050 } /* Literal.Number.Integer */
.highlight .mo { color: #208050 } /* Literal.Number.Oct */
.highlight .sa { color: #4070a0 } /* Literal.String.Affix */
.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */
.highlight .sc { color: #4070a0 } /* Literal.String.Char */
.highlight .dl { color: #4070a0 } /* Literal.String.Delimiter */
.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */
.highlight .s2 { color: #4070a0 } /* Literal.String.Double */
.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */
.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */
.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
.highlight .sx { color: #c65d09 } /* Literal.String.Other */
.highlight .sr { color: #235388 } /* Literal.String.Regex */
.highlight .s1 { color: #4070a0 } /* Literal.String.Single */
.highlight .ss { color: #517918 } /* Literal.String.Symbol */
.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #06287e } /* Name.Function.Magic */
.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */
.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */
.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */
.highlight .vm { color: #bb60d5 } /* Name.Variable.Magic */
.highlight .il { color: #208050 } /* Literal.Number.Integer.Long */PK
%�\����icichtml/_static/searchtools.jsnu�[���/*
 * searchtools.js_t
 * ~~~~~~~~~~~~~~~~
 *
 * Sphinx JavaScript utilities for the full-text search.
 *
 * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */


/* Non-minified version JS is _stemmer.js if file is provided */ 
/**
 * Porter Stemmer
 */
var Stemmer = function() {

  var step2list = {
    ational: 'ate',
    tional: 'tion',
    enci: 'ence',
    anci: 'ance',
    izer: 'ize',
    bli: 'ble',
    alli: 'al',
    entli: 'ent',
    eli: 'e',
    ousli: 'ous',
    ization: 'ize',
    ation: 'ate',
    ator: 'ate',
    alism: 'al',
    iveness: 'ive',
    fulness: 'ful',
    ousness: 'ous',
    aliti: 'al',
    iviti: 'ive',
    biliti: 'ble',
    logi: 'log'
  };

  var step3list = {
    icate: 'ic',
    ative: '',
    alize: 'al',
    iciti: 'ic',
    ical: 'ic',
    ful: '',
    ness: ''
  };

  var c = "[^aeiou]";          // consonant
  var v = "[aeiouy]";          // vowel
  var C = c + "[^aeiouy]*";    // consonant sequence
  var V = v + "[aeiou]*";      // vowel sequence

  var mgr0 = "^(" + C + ")?" + V + C;                      // [C]VC... is m>0
  var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$";    // [C]VC[V] is m=1
  var mgr1 = "^(" + C + ")?" + V + C + V + C;              // [C]VCVC... is m>1
  var s_v   = "^(" + C + ")?" + v;                         // vowel in stem

  this.stemWord = function (w) {
    var stem;
    var suffix;
    var firstch;
    var origword = w;

    if (w.length < 3)
      return w;

    var re;
    var re2;
    var re3;
    var re4;

    firstch = w.substr(0,1);
    if (firstch == "y")
      w = firstch.toUpperCase() + w.substr(1);

    // Step 1a
    re = /^(.+?)(ss|i)es$/;
    re2 = /^(.+?)([^s])s$/;

    if (re.test(w))
      w = w.replace(re,"$1$2");
    else if (re2.test(w))
      w = w.replace(re2,"$1$2");

    // Step 1b
    re = /^(.+?)eed$/;
    re2 = /^(.+?)(ed|ing)$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      re = new RegExp(mgr0);
      if (re.test(fp[1])) {
        re = /.$/;
        w = w.replace(re,"");
      }
    }
    else if (re2.test(w)) {
      var fp = re2.exec(w);
      stem = fp[1];
      re2 = new RegExp(s_v);
      if (re2.test(stem)) {
        w = stem;
        re2 = /(at|bl|iz)$/;
        re3 = new RegExp("([^aeiouylsz])\\1$");
        re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
        if (re2.test(w))
          w = w + "e";
        else if (re3.test(w)) {
          re = /.$/;
          w = w.replace(re,"");
        }
        else if (re4.test(w))
          w = w + "e";
      }
    }

    // Step 1c
    re = /^(.+?)y$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      re = new RegExp(s_v);
      if (re.test(stem))
        w = stem + "i";
    }

    // Step 2
    re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      suffix = fp[2];
      re = new RegExp(mgr0);
      if (re.test(stem))
        w = stem + step2list[suffix];
    }

    // Step 3
    re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      suffix = fp[2];
      re = new RegExp(mgr0);
      if (re.test(stem))
        w = stem + step3list[suffix];
    }

    // Step 4
    re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
    re2 = /^(.+?)(s|t)(ion)$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      re = new RegExp(mgr1);
      if (re.test(stem))
        w = stem;
    }
    else if (re2.test(w)) {
      var fp = re2.exec(w);
      stem = fp[1] + fp[2];
      re2 = new RegExp(mgr1);
      if (re2.test(stem))
        w = stem;
    }

    // Step 5
    re = /^(.+?)e$/;
    if (re.test(w)) {
      var fp = re.exec(w);
      stem = fp[1];
      re = new RegExp(mgr1);
      re2 = new RegExp(meq1);
      re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
      if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
        w = stem;
    }
    re = /ll$/;
    re2 = new RegExp(mgr1);
    if (re.test(w) && re2.test(w)) {
      re = /.$/;
      w = w.replace(re,"");
    }

    // and turn initial Y back to y
    if (firstch == "y")
      w = firstch.toLowerCase() + w.substr(1);
    return w;
  }
}



/**
 * Simple result scoring code.
 */
var Scorer = {
  // Implement the following function to further tweak the score for each result
  // The function takes a result array [filename, title, anchor, descr, score]
  // and returns the new score.
  /*
  score: function(result) {
    return result[4];
  },
  */

  // query matches the full name of an object
  objNameMatch: 11,
  // or matches in the last dotted part of the object name
  objPartialMatch: 6,
  // Additive scores depending on the priority of the object
  objPrio: {0:  15,   // used to be importantResults
            1:  5,   // used to be objectResults
            2: -5},  // used to be unimportantResults
  //  Used when the priority is not in the mapping.
  objPrioDefault: 0,

  // query found in title
  title: 15,
  // query found in terms
  term: 5
};





var splitChars = (function() {
    var result = {};
    var singles = [96, 180, 187, 191, 215, 247, 749, 885, 903, 907, 909, 930, 1014, 1648,
         1748, 1809, 2416, 2473, 2481, 2526, 2601, 2609, 2612, 2615, 2653, 2702,
         2706, 2729, 2737, 2740, 2857, 2865, 2868, 2910, 2928, 2948, 2961, 2971,
         2973, 3085, 3089, 3113, 3124, 3213, 3217, 3241, 3252, 3295, 3341, 3345,
         3369, 3506, 3516, 3633, 3715, 3721, 3736, 3744, 3748, 3750, 3756, 3761,
         3781, 3912, 4239, 4347, 4681, 4695, 4697, 4745, 4785, 4799, 4801, 4823,
         4881, 5760, 5901, 5997, 6313, 7405, 8024, 8026, 8028, 8030, 8117, 8125,
         8133, 8181, 8468, 8485, 8487, 8489, 8494, 8527, 11311, 11359, 11687, 11695,
         11703, 11711, 11719, 11727, 11735, 12448, 12539, 43010, 43014, 43019, 43587,
         43696, 43713, 64286, 64297, 64311, 64317, 64319, 64322, 64325, 65141];
    var i, j, start, end;
    for (i = 0; i < singles.length; i++) {
        result[singles[i]] = true;
    }
    var ranges = [[0, 47], [58, 64], [91, 94], [123, 169], [171, 177], [182, 184], [706, 709],
         [722, 735], [741, 747], [751, 879], [888, 889], [894, 901], [1154, 1161],
         [1318, 1328], [1367, 1368], [1370, 1376], [1416, 1487], [1515, 1519], [1523, 1568],
         [1611, 1631], [1642, 1645], [1750, 1764], [1767, 1773], [1789, 1790], [1792, 1807],
         [1840, 1868], [1958, 1968], [1970, 1983], [2027, 2035], [2038, 2041], [2043, 2047],
         [2070, 2073], [2075, 2083], [2085, 2087], [2089, 2307], [2362, 2364], [2366, 2383],
         [2385, 2391], [2402, 2405], [2419, 2424], [2432, 2436], [2445, 2446], [2449, 2450],
         [2483, 2485], [2490, 2492], [2494, 2509], [2511, 2523], [2530, 2533], [2546, 2547],
         [2554, 2564], [2571, 2574], [2577, 2578], [2618, 2648], [2655, 2661], [2672, 2673],
         [2677, 2692], [2746, 2748], [2750, 2767], [2769, 2783], [2786, 2789], [2800, 2820],
         [2829, 2830], [2833, 2834], [2874, 2876], [2878, 2907], [2914, 2917], [2930, 2946],
         [2955, 2957], [2966, 2968], [2976, 2978], [2981, 2983], [2987, 2989], [3002, 3023],
         [3025, 3045], [3059, 3076], [3130, 3132], [3134, 3159], [3162, 3167], [3170, 3173],
         [3184, 3191], [3199, 3204], [3258, 3260], [3262, 3293], [3298, 3301], [3312, 3332],
         [3386, 3388], [3390, 3423], [3426, 3429], [3446, 3449], [3456, 3460], [3479, 3481],
         [3518, 3519], [3527, 3584], [3636, 3647], [3655, 3663], [3674, 3712], [3717, 3718],
         [3723, 3724], [3726, 3731], [3752, 3753], [3764, 3772], [3774, 3775], [3783, 3791],
         [3802, 3803], [3806, 3839], [3841, 3871], [3892, 3903], [3949, 3975], [3980, 4095],
         [4139, 4158], [4170, 4175], [4182, 4185], [4190, 4192], [4194, 4196], [4199, 4205],
         [4209, 4212], [4226, 4237], [4250, 4255], [4294, 4303], [4349, 4351], [4686, 4687],
         [4702, 4703], [4750, 4751], [4790, 4791], [4806, 4807], [4886, 4887], [4955, 4968],
         [4989, 4991], [5008, 5023], [5109, 5120], [5741, 5742], [5787, 5791], [5867, 5869],
         [5873, 5887], [5906, 5919], [5938, 5951], [5970, 5983], [6001, 6015], [6068, 6102],
         [6104, 6107], [6109, 6111], [6122, 6127], [6138, 6159], [6170, 6175], [6264, 6271],
         [6315, 6319], [6390, 6399], [6429, 6469], [6510, 6511], [6517, 6527], [6572, 6592],
         [6600, 6607], [6619, 6655], [6679, 6687], [6741, 6783], [6794, 6799], [6810, 6822],
         [6824, 6916], [6964, 6980], [6988, 6991], [7002, 7042], [7073, 7085], [7098, 7167],
         [7204, 7231], [7242, 7244], [7294, 7400], [7410, 7423], [7616, 7679], [7958, 7959],
         [7966, 7967], [8006, 8007], [8014, 8015], [8062, 8063], [8127, 8129], [8141, 8143],
         [8148, 8149], [8156, 8159], [8173, 8177], [8189, 8303], [8306, 8307], [8314, 8318],
         [8330, 8335], [8341, 8449], [8451, 8454], [8456, 8457], [8470, 8472], [8478, 8483],
         [8506, 8507], [8512, 8516], [8522, 8525], [8586, 9311], [9372, 9449], [9472, 10101],
         [10132, 11263], [11493, 11498], [11503, 11516], [11518, 11519], [11558, 11567],
         [11622, 11630], [11632, 11647], [11671, 11679], [11743, 11822], [11824, 12292],
         [12296, 12320], [12330, 12336], [12342, 12343], [12349, 12352], [12439, 12444],
         [12544, 12548], [12590, 12592], [12687, 12689], [12694, 12703], [12728, 12783],
         [12800, 12831], [12842, 12880], [12896, 12927], [12938, 12976], [12992, 13311],
         [19894, 19967], [40908, 40959], [42125, 42191], [42238, 42239], [42509, 42511],
         [42540, 42559], [42592, 42593], [42607, 42622], [42648, 42655], [42736, 42774],
         [42784, 42785], [42889, 42890], [42893, 43002], [43043, 43055], [43062, 43071],
         [43124, 43137], [43188, 43215], [43226, 43249], [43256, 43258], [43260, 43263],
         [43302, 43311], [43335, 43359], [43389, 43395], [43443, 43470], [43482, 43519],
         [43561, 43583], [43596, 43599], [43610, 43615], [43639, 43641], [43643, 43647],
         [43698, 43700], [43703, 43704], [43710, 43711], [43715, 43738], [43742, 43967],
         [44003, 44015], [44026, 44031], [55204, 55215], [55239, 55242], [55292, 55295],
         [57344, 63743], [64046, 64047], [64110, 64111], [64218, 64255], [64263, 64274],
         [64280, 64284], [64434, 64466], [64830, 64847], [64912, 64913], [64968, 65007],
         [65020, 65135], [65277, 65295], [65306, 65312], [65339, 65344], [65371, 65381],
         [65471, 65473], [65480, 65481], [65488, 65489], [65496, 65497]];
    for (i = 0; i < ranges.length; i++) {
        start = ranges[i][0];
        end = ranges[i][1];
        for (j = start; j <= end; j++) {
            result[j] = true;
        }
    }
    return result;
})();

function splitQuery(query) {
    var result = [];
    var start = -1;
    for (var i = 0; i < query.length; i++) {
        if (splitChars[query.charCodeAt(i)]) {
            if (start !== -1) {
                result.push(query.slice(start, i));
                start = -1;
            }
        } else if (start === -1) {
            start = i;
        }
    }
    if (start !== -1) {
        result.push(query.slice(start));
    }
    return result;
}




/**
 * Search Module
 */
var Search = {

  _index : null,
  _queued_query : null,
  _pulse_status : -1,

  init : function() {
      var params = $.getQueryParameters();
      if (params.q) {
          var query = params.q[0];
          $('input[name="q"]')[0].value = query;
          this.performSearch(query);
      }
  },

  loadIndex : function(url) {
    $.ajax({type: "GET", url: url, data: null,
            dataType: "script", cache: true,
            complete: function(jqxhr, textstatus) {
              if (textstatus != "success") {
                document.getElementById("searchindexloader").src = url;
              }
            }});
  },

  setIndex : function(index) {
    var q;
    this._index = index;
    if ((q = this._queued_query) !== null) {
      this._queued_query = null;
      Search.query(q);
    }
  },

  hasIndex : function() {
      return this._index !== null;
  },

  deferQuery : function(query) {
      this._queued_query = query;
  },

  stopPulse : function() {
      this._pulse_status = 0;
  },

  startPulse : function() {
    if (this._pulse_status >= 0)
        return;
    function pulse() {
      var i;
      Search._pulse_status = (Search._pulse_status + 1) % 4;
      var dotString = '';
      for (i = 0; i < Search._pulse_status; i++)
        dotString += '.';
      Search.dots.text(dotString);
      if (Search._pulse_status > -1)
        window.setTimeout(pulse, 500);
    }
    pulse();
  },

  /**
   * perform a search for something (or wait until index is loaded)
   */
  performSearch : function(query) {
    // create the required interface elements
    this.out = $('#search-results');
    this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
    this.dots = $('<span></span>').appendTo(this.title);
    this.status = $('<p style="display: none"></p>').appendTo(this.out);
    this.output = $('<ul class="search"/>').appendTo(this.out);

    $('#search-progress').text(_('Preparing search...'));
    this.startPulse();

    // index already loaded, the browser was quick!
    if (this.hasIndex())
      this.query(query);
    else
      this.deferQuery(query);
  },

  /**
   * execute search (requires search index to be loaded)
   */
  query : function(query) {
    var i;
    var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];

    // stem the searchterms and add them to the correct list
    var stemmer = new Stemmer();
    var searchterms = [];
    var excluded = [];
    var hlterms = [];
    var tmp = splitQuery(query);
    var objectterms = [];
    for (i = 0; i < tmp.length; i++) {
      if (tmp[i] !== "") {
          objectterms.push(tmp[i].toLowerCase());
      }

      if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
          tmp[i] === "") {
        // skip this "word"
        continue;
      }
      // stem the word
      var word = stemmer.stemWord(tmp[i].toLowerCase());
      // prevent stemmer from cutting word smaller than two chars
      if(word.length < 3 && tmp[i].length >= 3) {
        word = tmp[i];
      }
      var toAppend;
      // select the correct list
      if (word[0] == '-') {
        toAppend = excluded;
        word = word.substr(1);
      }
      else {
        toAppend = searchterms;
        hlterms.push(tmp[i].toLowerCase());
      }
      // only add if not already in the list
      if (!$u.contains(toAppend, word))
        toAppend.push(word);
    }
    var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));

    // console.debug('SEARCH: searching for:');
    // console.info('required: ', searchterms);
    // console.info('excluded: ', excluded);

    // prepare search
    var terms = this._index.terms;
    var titleterms = this._index.titleterms;

    // array of [filename, title, anchor, descr, score]
    var results = [];
    $('#search-progress').empty();

    // lookup as object
    for (i = 0; i < objectterms.length; i++) {
      var others = [].concat(objectterms.slice(0, i),
                             objectterms.slice(i+1, objectterms.length));
      results = results.concat(this.performObjectSearch(objectterms[i], others));
    }

    // lookup as search terms in fulltext
    results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));

    // let the scorer override scores with a custom scoring function
    if (Scorer.score) {
      for (i = 0; i < results.length; i++)
        results[i][4] = Scorer.score(results[i]);
    }

    // now sort the results by score (in opposite order of appearance, since the
    // display function below uses pop() to retrieve items) and then
    // alphabetically
    results.sort(function(a, b) {
      var left = a[4];
      var right = b[4];
      if (left > right) {
        return 1;
      } else if (left < right) {
        return -1;
      } else {
        // same score: sort alphabetically
        left = a[1].toLowerCase();
        right = b[1].toLowerCase();
        return (left > right) ? -1 : ((left < right) ? 1 : 0);
      }
    });

    // for debugging
    //Search.lastresults = results.slice();  // a copy
    //console.info('search results:', Search.lastresults);

    // print the results
    var resultCount = results.length;
    function displayNextItem() {
      // results left, load the summary and display it
      if (results.length) {
        var item = results.pop();
        var listItem = $('<li style="display:none"></li>');
        if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
          // dirhtml builder
          var dirname = item[0] + '/';
          if (dirname.match(/\/index\/$/)) {
            dirname = dirname.substring(0, dirname.length-6);
          } else if (dirname == 'index/') {
            dirname = '';
          }
          listItem.append($('<a/>').attr('href',
            DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
            highlightstring + item[2]).html(item[1]));
        } else {
          // normal html builders
          listItem.append($('<a/>').attr('href',
            item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
            highlightstring + item[2]).html(item[1]));
        }
        if (item[3]) {
          listItem.append($('<span> (' + item[3] + ')</span>'));
          Search.output.append(listItem);
          listItem.slideDown(5, function() {
            displayNextItem();
          });
        } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
          var suffix = DOCUMENTATION_OPTIONS.SOURCELINK_SUFFIX;
          if (suffix === undefined) {
            suffix = '.txt';
          }
          $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[5] + (item[5].slice(-suffix.length) === suffix ? '' : suffix),
                  dataType: "text",
                  complete: function(jqxhr, textstatus) {
                    var data = jqxhr.responseText;
                    if (data !== '' && data !== undefined) {
                      listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
                    }
                    Search.output.append(listItem);
                    listItem.slideDown(5, function() {
                      displayNextItem();
                    });
                  }});
        } else {
          // no source available, just display title
          Search.output.append(listItem);
          listItem.slideDown(5, function() {
            displayNextItem();
          });
        }
      }
      // search finished, update title and status message
      else {
        Search.stopPulse();
        Search.title.text(_('Search Results'));
        if (!resultCount)
          Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
        else
            Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
        Search.status.fadeIn(500);
      }
    }
    displayNextItem();
  },

  /**
   * search for object names
   */
  performObjectSearch : function(object, otherterms) {
    var filenames = this._index.filenames;
    var docnames = this._index.docnames;
    var objects = this._index.objects;
    var objnames = this._index.objnames;
    var titles = this._index.titles;

    var i;
    var results = [];

    for (var prefix in objects) {
      for (var name in objects[prefix]) {
        var fullname = (prefix ? prefix + '.' : '') + name;
        if (fullname.toLowerCase().indexOf(object) > -1) {
          var score = 0;
          var parts = fullname.split('.');
          // check for different match types: exact matches of full name or
          // "last name" (i.e. last dotted part)
          if (fullname == object || parts[parts.length - 1] == object) {
            score += Scorer.objNameMatch;
          // matches in last name
          } else if (parts[parts.length - 1].indexOf(object) > -1) {
            score += Scorer.objPartialMatch;
          }
          var match = objects[prefix][name];
          var objname = objnames[match[1]][2];
          var title = titles[match[0]];
          // If more than one term searched for, we require other words to be
          // found in the name/title/description
          if (otherterms.length > 0) {
            var haystack = (prefix + ' ' + name + ' ' +
                            objname + ' ' + title).toLowerCase();
            var allfound = true;
            for (i = 0; i < otherterms.length; i++) {
              if (haystack.indexOf(otherterms[i]) == -1) {
                allfound = false;
                break;
              }
            }
            if (!allfound) {
              continue;
            }
          }
          var descr = objname + _(', in ') + title;

          var anchor = match[3];
          if (anchor === '')
            anchor = fullname;
          else if (anchor == '-')
            anchor = objnames[match[1]][1] + '-' + fullname;
          // add custom score for some objects according to scorer
          if (Scorer.objPrio.hasOwnProperty(match[2])) {
            score += Scorer.objPrio[match[2]];
          } else {
            score += Scorer.objPrioDefault;
          }
          results.push([docnames[match[0]], fullname, '#'+anchor, descr, score, filenames[match[0]]]);
        }
      }
    }

    return results;
  },

  /**
   * search for full-text terms in the index
   */
  performTermsSearch : function(searchterms, excluded, terms, titleterms) {
    var docnames = this._index.docnames;
    var filenames = this._index.filenames;
    var titles = this._index.titles;

    var i, j, file;
    var fileMap = {};
    var scoreMap = {};
    var results = [];

    // perform the search on the required terms
    for (i = 0; i < searchterms.length; i++) {
      var word = searchterms[i];
      var files = [];
      var _o = [
        {files: terms[word], score: Scorer.term},
        {files: titleterms[word], score: Scorer.title}
      ];

      // no match but word was a required one
      if ($u.every(_o, function(o){return o.files === undefined;})) {
        break;
      }
      // found search word in contents
      $u.each(_o, function(o) {
        var _files = o.files;
        if (_files === undefined)
          return

        if (_files.length === undefined)
          _files = [_files];
        files = files.concat(_files);

        // set score for the word in each file to Scorer.term
        for (j = 0; j < _files.length; j++) {
          file = _files[j];
          if (!(file in scoreMap))
            scoreMap[file] = {}
          scoreMap[file][word] = o.score;
        }
      });

      // create the mapping
      for (j = 0; j < files.length; j++) {
        file = files[j];
        if (file in fileMap)
          fileMap[file].push(word);
        else
          fileMap[file] = [word];
      }
    }

    // now check if the files don't contain excluded terms
    for (file in fileMap) {
      var valid = true;

      // check if all requirements are matched
      if (fileMap[file].length != searchterms.length)
          continue;

      // ensure that none of the excluded terms is in the search result
      for (i = 0; i < excluded.length; i++) {
        if (terms[excluded[i]] == file ||
            titleterms[excluded[i]] == file ||
            $u.contains(terms[excluded[i]] || [], file) ||
            $u.contains(titleterms[excluded[i]] || [], file)) {
          valid = false;
          break;
        }
      }

      // if we have still a valid result we can add it to the result list
      if (valid) {
        // select one (max) score for the file.
        // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
        var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
        results.push([docnames[file], titles[file], '', null, score, filenames[file]]);
      }
    }
    return results;
  },

  /**
   * helper function to return a node containing the
   * search summary for a given text. keywords is a list
   * of stemmed words, hlwords is the list of normal, unstemmed
   * words. the first one is used to find the occurrence, the
   * latter for highlighting it.
   */
  makeSearchSummary : function(text, keywords, hlwords) {
    var textLower = text.toLowerCase();
    var start = 0;
    $.each(keywords, function() {
      var i = textLower.indexOf(this.toLowerCase());
      if (i > -1)
        start = i;
    });
    start = Math.max(start - 120, 0);
    var excerpt = ((start > 0) ? '...' : '') +
      $.trim(text.substr(start, 240)) +
      ((start + 240 - text.length) ? '...' : '');
    var rv = $('<div class="context"></div>').text(excerpt);
    $.each(hlwords, function() {
      rv = rv.highlightText(this, 'highlighted');
    });
    return rv;
  }
};

$(document).ready(function() {
  Search.init();
});PK
%�\�y��pphtml/_static/sidebar.jsnu�[���/*
 * sidebar.js
 * ~~~~~~~~~~
 *
 * This script makes the Sphinx sidebar collapsible and implements
 * intelligent scrolling.
 *
 * .sphinxsidebar contains .sphinxsidebarwrapper.  This script adds
 * in .sphixsidebar, after .sphinxsidebarwrapper, the #sidebarbutton
 * used to collapse and expand the sidebar.
 *
 * When the sidebar is collapsed the .sphinxsidebarwrapper is hidden
 * and the width of the sidebar and the margin-left of the document
 * are decreased. When the sidebar is expanded the opposite happens.
 * This script saves a per-browser/per-session cookie used to
 * remember the position of the sidebar among the pages.
 * Once the browser is closed the cookie is deleted and the position
 * reset to the default (expanded).
 *
 * :copyright: Copyright 2007-2011 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */

$(function() {
  // global elements used by the functions.
  // the 'sidebarbutton' element is defined as global after its
  // creation, in the add_sidebar_button function
  var jwindow = $(window);
  var jdocument = $(document);
  var bodywrapper = $('.bodywrapper');
  var sidebar = $('.sphinxsidebar');
  var sidebarwrapper = $('.sphinxsidebarwrapper');

  // original margin-left of the bodywrapper and width of the sidebar
  // with the sidebar expanded
  var bw_margin_expanded = bodywrapper.css('margin-left');
  var ssb_width_expanded = sidebar.width();

  // margin-left of the bodywrapper and width of the sidebar
  // with the sidebar collapsed
  var bw_margin_collapsed = '.8em';
  var ssb_width_collapsed = '.8em';

  // colors used by the current theme
  var dark_color = $('.related').css('background-color');
  var light_color = $('.document').css('background-color');

  function get_viewport_height() {
    if (window.innerHeight)
      return window.innerHeight;
    else
      return jwindow.height();
  }

  function sidebar_is_collapsed() {
    return sidebarwrapper.is(':not(:visible)');
  }

  function toggle_sidebar() {
    if (sidebar_is_collapsed())
      expand_sidebar();
    else
      collapse_sidebar();
    // adjust the scrolling of the sidebar
    scroll_sidebar();
  }

  function collapse_sidebar() {
    sidebarwrapper.hide();
    sidebar.css('width', ssb_width_collapsed);
    bodywrapper.css('margin-left', bw_margin_collapsed);
    sidebarbutton.css({
        'margin-left': '0',
        'height': bodywrapper.height()
    });
    sidebarbutton.find('span').text('»');
    sidebarbutton.attr('title', _('Expand sidebar'));
    document.cookie = 'sidebar=collapsed';
  }

  function expand_sidebar() {
    bodywrapper.css('margin-left', bw_margin_expanded);
    sidebar.css('width', ssb_width_expanded);
    sidebarwrapper.show();
    sidebarbutton.css({
        'margin-left': ssb_width_expanded-12,
        'height': bodywrapper.height()
    });
    sidebarbutton.find('span').text('«');
    sidebarbutton.attr('title', _('Collapse sidebar'));
    document.cookie = 'sidebar=expanded';
  }

  function add_sidebar_button() {
    sidebarwrapper.css({
        'float': 'left',
        'margin-right': '0',
        'width': ssb_width_expanded - 28
    });
    // create the button
    sidebar.append(
        '<div id="sidebarbutton"><span>&laquo;</span></div>'
    );
    var sidebarbutton = $('#sidebarbutton');
    light_color = sidebarbutton.css('background-color');
    // find the height of the viewport to center the '<<' in the page
    var viewport_height = get_viewport_height();
    sidebarbutton.find('span').css({
        'display': 'block',
        'margin-top': (viewport_height - sidebar.position().top - 20) / 2
    });

    sidebarbutton.click(toggle_sidebar);
    sidebarbutton.attr('title', _('Collapse sidebar'));
    sidebarbutton.css({
        'color': '#FFFFFF',
        'border-left': '1px solid ' + dark_color,
        'font-size': '1.2em',
        'cursor': 'pointer',
        'height': bodywrapper.height(),
        'padding-top': '1px',
        'margin-left': ssb_width_expanded - 12
    });

    sidebarbutton.hover(
      function () {
          $(this).css('background-color', dark_color);
      },
      function () {
          $(this).css('background-color', light_color);
      }
    );
  }

  function set_position_from_cookie() {
    if (!document.cookie)
      return;
    var items = document.cookie.split(';');
    for(var k=0; k<items.length; k++) {
      var key_val = items[k].split('=');
      var key = key_val[0];
      if (key == 'sidebar') {
        var value = key_val[1];
        if ((value == 'collapsed') && (!sidebar_is_collapsed()))
          collapse_sidebar();
        else if ((value == 'expanded') && (sidebar_is_collapsed()))
          expand_sidebar();
      }
    }
  }

  add_sidebar_button();
  var sidebarbutton = $('#sidebarbutton');
  set_position_from_cookie();


  /* intelligent scrolling */
  function scroll_sidebar() {
    var sidebar_height = sidebarwrapper.height();
    var viewport_height = get_viewport_height();
    var offset = sidebar.position()['top'];
    var wintop = jwindow.scrollTop();
    var winbot = wintop + viewport_height;
    var curtop = sidebarwrapper.position()['top'];
    var curbot = curtop + sidebar_height;
    // does sidebar fit in window?
    if (sidebar_height < viewport_height) {
      // yes: easy case -- always keep at the top
      sidebarwrapper.css('top', $u.min([$u.max([0, wintop - offset - 10]),
                            jdocument.height() - sidebar_height - 200]));
    }
    else {
      // no: only scroll if top/bottom edge of sidebar is at
      // top/bottom edge of window
      if (curtop > wintop && curbot > winbot) {
        sidebarwrapper.css('top', $u.max([wintop - offset - 10, 0]));
      }
      else if (curtop < wintop && curbot < winbot) {
        sidebarwrapper.css('top', $u.min([winbot - sidebar_height - offset - 20,
                              jdocument.height() - sidebar_height - 200]));
      }
    }
  }
  jwindow.scroll(scroll_sidebar);
});
PK
%�\F@��html/_static/switchers.jsnu�[���(function() {
  'use strict';

  // Parses versions in URL segments like:
  // "3", "dev", "release/2.7" or "3.6rc2"
  var version_regexs = [
    '(?:\\d)',
    '(?:\\d\\.\\d[\\w\\d\\.]*)',
    '(?:dev)',
    '(?:release/\\d.\\d[\\x\\d\\.]*)'];

  var all_versions = {
    '3.8': 'dev (3.8)',
    '3.7': '3.7',
    '3.6': '3.6',
    '3.5': '3.5',
    '2.7': '2.7',
  };

  var all_languages = {
      'en': 'English',
      'fr': 'French',
      'ja': 'Japanese',
  };

  function build_version_select(current_version, current_release) {
    var buf = ['<select>'];

    $.each(all_versions, function(version, title) {
      buf.push('<option value="' + version + '"');
      if (version == current_version)
        buf.push(' selected="selected">' + current_release + '</option>');
      else
        buf.push('>' + title + '</option>');
    });

    buf.push('</select>');
    return buf.join('');
  }

  function build_language_select(current_language) {
    var buf = ['<select>'];

    $.each(all_languages, function(language, title) {
      if (language == current_language)
        buf.push('<option value="' + language + '" selected="selected">' +
                 all_languages[current_language] + '</option>');
      else
        buf.push('<option value="' + language + '">' + title + '</option>');
    });
    if (!(current_language in all_languages)) {
        // In case we're browsing a language that is not yet in all_languages.
        buf.push('<option value="' + current_language + '" selected="selected">' +
                 current_language + '</option>');
        all_languages[current_language] = current_language;
    }
    buf.push('</select>');
    return buf.join('');
  }

  function navigate_to_first_existing(urls) {
    // Navigate to the first existing URL in urls.
    var url = urls.shift();
    if (urls.length == 0) {
      window.location.href = url;
      return;
    }
    $.ajax({
      url: url,
      success: function() {
        window.location.href = url;
      },
      error: function() {
        navigate_to_first_existing(urls);
      }
    });
  }

  function on_version_switch() {
    var selected_version = $(this).children('option:selected').attr('value') + '/';
    var url = window.location.href;
    var current_language = language_segment_from_url(url);
    var current_version = version_segment_in_url(url);
    var new_url = url.replace('.org/' + current_language + current_version,
                              '.org/' + current_language + selected_version);
    if (new_url != url) {
      navigate_to_first_existing([
        new_url,
        url.replace('.org/' + current_language + current_version,
                    '.org/' + selected_version),
        'https://docs.python.org/' + current_language + selected_version,
        'https://docs.python.org/' + selected_version,
        'https://docs.python.org/'
      ]);
    }
  }

  function on_language_switch() {
    var selected_language = $(this).children('option:selected').attr('value') + '/';
    var url = window.location.href;
    var current_language = language_segment_from_url(url);
    var current_version = version_segment_in_url(url);
    if (selected_language == 'en/') // Special 'default' case for english.
      selected_language = '';
    var new_url = url.replace('.org/' + current_language + current_version,
                              '.org/' + selected_language + current_version);
    if (new_url != url) {
      navigate_to_first_existing([
        new_url,
        'https://docs.python.org/'
      ]);
    }
  }

  // Returns the path segment of the language as a string, like 'fr/'
  // or '' if not found.
  function language_segment_from_url(url) {
    var language_regexp = '\.org/([a-z]{2}(?:-[a-z]{2})?/)';
    var match = url.match(language_regexp);
    if (match !== null)
        return match[1];
    return '';
  }

  // Returns the path segment of the version as a string, like '3.6/'
  // or '' if not found.
  function version_segment_in_url(url) {
    var language_segment = '(?:[a-z]{2}(?:-[a-z]{2})?/)';
    var version_segment = '(?:(?:' + version_regexs.join('|') + ')/)';
    var version_regexp = '\\.org/' + language_segment + '?(' + version_segment + ')';
    var match = url.match(version_regexp);
    if (match !== null)
      return match[1];
    return ''
  }

  $(document).ready(function() {
    var release = DOCUMENTATION_OPTIONS.VERSION;
    var language_segment = language_segment_from_url(window.location.href);
    var current_language = language_segment.replace(/\/+$/g, '') || 'en';
    var version = release.substr(0, 3);
    var version_select = build_version_select(version, release);

    $('.version_switcher_placeholder').html(version_select);
    $('.version_switcher_placeholder select').bind('change', on_version_switch);

    var language_select = build_language_select(current_language);

    $('.language_switcher_placeholder').html(language_select);
    $('.language_switcher_placeholder select').bind('change', on_language_switch);
  });
})();
PK
%�\��`�`� html/_static/underscore-1.3.1.jsnu�[���//     Underscore.js 1.3.1
//     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
//     Underscore is freely distributable under the MIT license.
//     Portions of Underscore are inspired or borrowed from Prototype,
//     Oliver Steele's Functional, and John Resig's Micro-Templating.
//     For all details and documentation:
//     http://documentcloud.github.com/underscore

(function() {

  // Baseline setup
  // --------------

  // Establish the root object, `window` in the browser, or `global` on the server.
  var root = this;

  // Save the previous value of the `_` variable.
  var previousUnderscore = root._;

  // Establish the object that gets returned to break out of a loop iteration.
  var breaker = {};

  // Save bytes in the minified (but not gzipped) version:
  var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;

  // Create quick reference variables for speed access to core prototypes.
  var slice            = ArrayProto.slice,
      unshift          = ArrayProto.unshift,
      toString         = ObjProto.toString,
      hasOwnProperty   = ObjProto.hasOwnProperty;

  // All **ECMAScript 5** native function implementations that we hope to use
  // are declared here.
  var
    nativeForEach      = ArrayProto.forEach,
    nativeMap          = ArrayProto.map,
    nativeReduce       = ArrayProto.reduce,
    nativeReduceRight  = ArrayProto.reduceRight,
    nativeFilter       = ArrayProto.filter,
    nativeEvery        = ArrayProto.every,
    nativeSome         = ArrayProto.some,
    nativeIndexOf      = ArrayProto.indexOf,
    nativeLastIndexOf  = ArrayProto.lastIndexOf,
    nativeIsArray      = Array.isArray,
    nativeKeys         = Object.keys,
    nativeBind         = FuncProto.bind;

  // Create a safe reference to the Underscore object for use below.
  var _ = function(obj) { return new wrapper(obj); };

  // Export the Underscore object for **Node.js**, with
  // backwards-compatibility for the old `require()` API. If we're in
  // the browser, add `_` as a global object via a string identifier,
  // for Closure Compiler "advanced" mode.
  if (typeof exports !== 'undefined') {
    if (typeof module !== 'undefined' && module.exports) {
      exports = module.exports = _;
    }
    exports._ = _;
  } else {
    root['_'] = _;
  }

  // Current version.
  _.VERSION = '1.3.1';

  // Collection Functions
  // --------------------

  // The cornerstone, an `each` implementation, aka `forEach`.
  // Handles objects with the built-in `forEach`, arrays, and raw objects.
  // Delegates to **ECMAScript 5**'s native `forEach` if available.
  var each = _.each = _.forEach = function(obj, iterator, context) {
    if (obj == null) return;
    if (nativeForEach && obj.forEach === nativeForEach) {
      obj.forEach(iterator, context);
    } else if (obj.length === +obj.length) {
      for (var i = 0, l = obj.length; i < l; i++) {
        if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
      }
    } else {
      for (var key in obj) {
        if (_.has(obj, key)) {
          if (iterator.call(context, obj[key], key, obj) === breaker) return;
        }
      }
    }
  };

  // Return the results of applying the iterator to each element.
  // Delegates to **ECMAScript 5**'s native `map` if available.
  _.map = _.collect = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
    each(obj, function(value, index, list) {
      results[results.length] = iterator.call(context, value, index, list);
    });
    if (obj.length === +obj.length) results.length = obj.length;
    return results;
  };

  // **Reduce** builds up a single result from a list of values, aka `inject`,
  // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
  _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduce && obj.reduce === nativeReduce) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
    }
    each(obj, function(value, index, list) {
      if (!initial) {
        memo = value;
        initial = true;
      } else {
        memo = iterator.call(context, memo, value, index, list);
      }
    });
    if (!initial) throw new TypeError('Reduce of empty array with no initial value');
    return memo;
  };

  // The right-associative version of reduce, also known as `foldr`.
  // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
  _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
    var initial = arguments.length > 2;
    if (obj == null) obj = [];
    if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
      if (context) iterator = _.bind(iterator, context);
      return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
    }
    var reversed = _.toArray(obj).reverse();
    if (context && !initial) iterator = _.bind(iterator, context);
    return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
  };

  // Return the first value which passes a truth test. Aliased as `detect`.
  _.find = _.detect = function(obj, iterator, context) {
    var result;
    any(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) {
        result = value;
        return true;
      }
    });
    return result;
  };

  // Return all the elements that pass a truth test.
  // Delegates to **ECMAScript 5**'s native `filter` if available.
  // Aliased as `select`.
  _.filter = _.select = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
    each(obj, function(value, index, list) {
      if (iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Return all the elements for which a truth test fails.
  _.reject = function(obj, iterator, context) {
    var results = [];
    if (obj == null) return results;
    each(obj, function(value, index, list) {
      if (!iterator.call(context, value, index, list)) results[results.length] = value;
    });
    return results;
  };

  // Determine whether all of the elements match a truth test.
  // Delegates to **ECMAScript 5**'s native `every` if available.
  // Aliased as `all`.
  _.every = _.all = function(obj, iterator, context) {
    var result = true;
    if (obj == null) return result;
    if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
    each(obj, function(value, index, list) {
      if (!(result = result && iterator.call(context, value, index, list))) return breaker;
    });
    return result;
  };

  // Determine if at least one element in the object matches a truth test.
  // Delegates to **ECMAScript 5**'s native `some` if available.
  // Aliased as `any`.
  var any = _.some = _.any = function(obj, iterator, context) {
    iterator || (iterator = _.identity);
    var result = false;
    if (obj == null) return result;
    if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
    each(obj, function(value, index, list) {
      if (result || (result = iterator.call(context, value, index, list))) return breaker;
    });
    return !!result;
  };

  // Determine if a given value is included in the array or object using `===`.
  // Aliased as `contains`.
  _.include = _.contains = function(obj, target) {
    var found = false;
    if (obj == null) return found;
    if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
    found = any(obj, function(value) {
      return value === target;
    });
    return found;
  };

  // Invoke a method (with arguments) on every item in a collection.
  _.invoke = function(obj, method) {
    var args = slice.call(arguments, 2);
    return _.map(obj, function(value) {
      return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
    });
  };

  // Convenience version of a common use case of `map`: fetching a property.
  _.pluck = function(obj, key) {
    return _.map(obj, function(value){ return value[key]; });
  };

  // Return the maximum element or (element-based computation).
  _.max = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return -Infinity;
    var result = {computed : -Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed >= result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Return the minimum element (or element-based computation).
  _.min = function(obj, iterator, context) {
    if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
    if (!iterator && _.isEmpty(obj)) return Infinity;
    var result = {computed : Infinity};
    each(obj, function(value, index, list) {
      var computed = iterator ? iterator.call(context, value, index, list) : value;
      computed < result.computed && (result = {value : value, computed : computed});
    });
    return result.value;
  };

  // Shuffle an array.
  _.shuffle = function(obj) {
    var shuffled = [], rand;
    each(obj, function(value, index, list) {
      if (index == 0) {
        shuffled[0] = value;
      } else {
        rand = Math.floor(Math.random() * (index + 1));
        shuffled[index] = shuffled[rand];
        shuffled[rand] = value;
      }
    });
    return shuffled;
  };

  // Sort the object's values by a criterion produced by an iterator.
  _.sortBy = function(obj, iterator, context) {
    return _.pluck(_.map(obj, function(value, index, list) {
      return {
        value : value,
        criteria : iterator.call(context, value, index, list)
      };
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }), 'value');
  };

  // Groups the object's values by a criterion. Pass either a string attribute
  // to group by, or a function that returns the criterion.
  _.groupBy = function(obj, val) {
    var result = {};
    var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
    each(obj, function(value, index) {
      var key = iterator(value, index);
      (result[key] || (result[key] = [])).push(value);
    });
    return result;
  };

  // Use a comparator function to figure out at what index an object should
  // be inserted so as to maintain order. Uses binary search.
  _.sortedIndex = function(array, obj, iterator) {
    iterator || (iterator = _.identity);
    var low = 0, high = array.length;
    while (low < high) {
      var mid = (low + high) >> 1;
      iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
    }
    return low;
  };

  // Safely convert anything iterable into a real, live array.
  _.toArray = function(iterable) {
    if (!iterable)                return [];
    if (iterable.toArray)         return iterable.toArray();
    if (_.isArray(iterable))      return slice.call(iterable);
    if (_.isArguments(iterable))  return slice.call(iterable);
    return _.values(iterable);
  };

  // Return the number of elements in an object.
  _.size = function(obj) {
    return _.toArray(obj).length;
  };

  // Array Functions
  // ---------------

  // Get the first element of an array. Passing **n** will return the first N
  // values in the array. Aliased as `head`. The **guard** check allows it to work
  // with `_.map`.
  _.first = _.head = function(array, n, guard) {
    return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
  };

  // Returns everything but the last entry of the array. Especcialy useful on
  // the arguments object. Passing **n** will return all the values in
  // the array, excluding the last N. The **guard** check allows it to work with
  // `_.map`.
  _.initial = function(array, n, guard) {
    return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
  };

  // Get the last element of an array. Passing **n** will return the last N
  // values in the array. The **guard** check allows it to work with `_.map`.
  _.last = function(array, n, guard) {
    if ((n != null) && !guard) {
      return slice.call(array, Math.max(array.length - n, 0));
    } else {
      return array[array.length - 1];
    }
  };

  // Returns everything but the first entry of the array. Aliased as `tail`.
  // Especially useful on the arguments object. Passing an **index** will return
  // the rest of the values in the array from that index onward. The **guard**
  // check allows it to work with `_.map`.
  _.rest = _.tail = function(array, index, guard) {
    return slice.call(array, (index == null) || guard ? 1 : index);
  };

  // Trim out all falsy values from an array.
  _.compact = function(array) {
    return _.filter(array, function(value){ return !!value; });
  };

  // Return a completely flattened version of an array.
  _.flatten = function(array, shallow) {
    return _.reduce(array, function(memo, value) {
      if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
      memo[memo.length] = value;
      return memo;
    }, []);
  };

  // Return a version of the array that does not contain the specified value(s).
  _.without = function(array) {
    return _.difference(array, slice.call(arguments, 1));
  };

  // Produce a duplicate-free version of the array. If the array has already
  // been sorted, you have the option of using a faster algorithm.
  // Aliased as `unique`.
  _.uniq = _.unique = function(array, isSorted, iterator) {
    var initial = iterator ? _.map(array, iterator) : array;
    var result = [];
    _.reduce(initial, function(memo, el, i) {
      if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
        memo[memo.length] = el;
        result[result.length] = array[i];
      }
      return memo;
    }, []);
    return result;
  };

  // Produce an array that contains the union: each distinct element from all of
  // the passed-in arrays.
  _.union = function() {
    return _.uniq(_.flatten(arguments, true));
  };

  // Produce an array that contains every item shared between all the
  // passed-in arrays. (Aliased as "intersect" for back-compat.)
  _.intersection = _.intersect = function(array) {
    var rest = slice.call(arguments, 1);
    return _.filter(_.uniq(array), function(item) {
      return _.every(rest, function(other) {
        return _.indexOf(other, item) >= 0;
      });
    });
  };

  // Take the difference between one array and a number of other arrays.
  // Only the elements present in just the first array will remain.
  _.difference = function(array) {
    var rest = _.flatten(slice.call(arguments, 1));
    return _.filter(array, function(value){ return !_.include(rest, value); });
  };

  // Zip together multiple lists into a single array -- elements that share
  // an index go together.
  _.zip = function() {
    var args = slice.call(arguments);
    var length = _.max(_.pluck(args, 'length'));
    var results = new Array(length);
    for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
    return results;
  };

  // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
  // we need this function. Return the position of the first occurrence of an
  // item in an array, or -1 if the item is not included in the array.
  // Delegates to **ECMAScript 5**'s native `indexOf` if available.
  // If the array is large and already in sort order, pass `true`
  // for **isSorted** to use binary search.
  _.indexOf = function(array, item, isSorted) {
    if (array == null) return -1;
    var i, l;
    if (isSorted) {
      i = _.sortedIndex(array, item);
      return array[i] === item ? i : -1;
    }
    if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
    for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
  _.lastIndexOf = function(array, item) {
    if (array == null) return -1;
    if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
    var i = array.length;
    while (i--) if (i in array && array[i] === item) return i;
    return -1;
  };

  // Generate an integer Array containing an arithmetic progression. A port of
  // the native Python `range()` function. See
  // [the Python documentation](http://docs.python.org/library/functions.html#range).
  _.range = function(start, stop, step) {
    if (arguments.length <= 1) {
      stop = start || 0;
      start = 0;
    }
    step = arguments[2] || 1;

    var len = Math.max(Math.ceil((stop - start) / step), 0);
    var idx = 0;
    var range = new Array(len);

    while(idx < len) {
      range[idx++] = start;
      start += step;
    }

    return range;
  };

  // Function (ahem) Functions
  // ------------------

  // Reusable constructor function for prototype setting.
  var ctor = function(){};

  // Create a function bound to a given object (assigning `this`, and arguments,
  // optionally). Binding with arguments is also known as `curry`.
  // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
  // We check for `func.bind` first, to fail fast when `func` is undefined.
  _.bind = function bind(func, context) {
    var bound, args;
    if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
    if (!_.isFunction(func)) throw new TypeError;
    args = slice.call(arguments, 2);
    return bound = function() {
      if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
      ctor.prototype = func.prototype;
      var self = new ctor;
      var result = func.apply(self, args.concat(slice.call(arguments)));
      if (Object(result) === result) return result;
      return self;
    };
  };

  // Bind all of an object's methods to that object. Useful for ensuring that
  // all callbacks defined on an object belong to it.
  _.bindAll = function(obj) {
    var funcs = slice.call(arguments, 1);
    if (funcs.length == 0) funcs = _.functions(obj);
    each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
    return obj;
  };

  // Memoize an expensive function by storing its results.
  _.memoize = function(func, hasher) {
    var memo = {};
    hasher || (hasher = _.identity);
    return function() {
      var key = hasher.apply(this, arguments);
      return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
    };
  };

  // Delays a function for the given number of milliseconds, and then calls
  // it with the arguments supplied.
  _.delay = function(func, wait) {
    var args = slice.call(arguments, 2);
    return setTimeout(function(){ return func.apply(func, args); }, wait);
  };

  // Defers a function, scheduling it to run after the current call stack has
  // cleared.
  _.defer = function(func) {
    return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
  };

  // Returns a function, that, when invoked, will only be triggered at most once
  // during a given window of time.
  _.throttle = function(func, wait) {
    var context, args, timeout, throttling, more;
    var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
    return function() {
      context = this; args = arguments;
      var later = function() {
        timeout = null;
        if (more) func.apply(context, args);
        whenDone();
      };
      if (!timeout) timeout = setTimeout(later, wait);
      if (throttling) {
        more = true;
      } else {
        func.apply(context, args);
      }
      whenDone();
      throttling = true;
    };
  };

  // Returns a function, that, as long as it continues to be invoked, will not
  // be triggered. The function will be called after it stops being called for
  // N milliseconds.
  _.debounce = function(func, wait) {
    var timeout;
    return function() {
      var context = this, args = arguments;
      var later = function() {
        timeout = null;
        func.apply(context, args);
      };
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
    };
  };

  // Returns a function that will be executed at most one time, no matter how
  // often you call it. Useful for lazy initialization.
  _.once = function(func) {
    var ran = false, memo;
    return function() {
      if (ran) return memo;
      ran = true;
      return memo = func.apply(this, arguments);
    };
  };

  // Returns the first function passed as an argument to the second,
  // allowing you to adjust arguments, run code before and after, and
  // conditionally execute the original function.
  _.wrap = function(func, wrapper) {
    return function() {
      var args = [func].concat(slice.call(arguments, 0));
      return wrapper.apply(this, args);
    };
  };

  // Returns a function that is the composition of a list of functions, each
  // consuming the return value of the function that follows.
  _.compose = function() {
    var funcs = arguments;
    return function() {
      var args = arguments;
      for (var i = funcs.length - 1; i >= 0; i--) {
        args = [funcs[i].apply(this, args)];
      }
      return args[0];
    };
  };

  // Returns a function that will only be executed after being called N times.
  _.after = function(times, func) {
    if (times <= 0) return func();
    return function() {
      if (--times < 1) { return func.apply(this, arguments); }
    };
  };

  // Object Functions
  // ----------------

  // Retrieve the names of an object's properties.
  // Delegates to **ECMAScript 5**'s native `Object.keys`
  _.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
    return keys;
  };

  // Retrieve the values of an object's properties.
  _.values = function(obj) {
    return _.map(obj, _.identity);
  };

  // Return a sorted list of the function names available on the object.
  // Aliased as `methods`
  _.functions = _.methods = function(obj) {
    var names = [];
    for (var key in obj) {
      if (_.isFunction(obj[key])) names.push(key);
    }
    return names.sort();
  };

  // Extend a given object with all the properties in passed-in object(s).
  _.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Fill in a given object with default properties.
  _.defaults = function(obj) {
    each(slice.call(arguments, 1), function(source) {
      for (var prop in source) {
        if (obj[prop] == null) obj[prop] = source[prop];
      }
    });
    return obj;
  };

  // Create a (shallow-cloned) duplicate of an object.
  _.clone = function(obj) {
    if (!_.isObject(obj)) return obj;
    return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
  };

  // Invokes interceptor with the obj, and then returns obj.
  // The primary purpose of this method is to "tap into" a method chain, in
  // order to perform operations on intermediate results within the chain.
  _.tap = function(obj, interceptor) {
    interceptor(obj);
    return obj;
  };

  // Internal recursive comparison function.
  function eq(a, b, stack) {
    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
    if (a === b) return a !== 0 || 1 / a == 1 / b;
    // A strict comparison is necessary because `null == undefined`.
    if (a == null || b == null) return a === b;
    // Unwrap any wrapped objects.
    if (a._chain) a = a._wrapped;
    if (b._chain) b = b._wrapped;
    // Invoke a custom `isEqual` method if one is provided.
    if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
    if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
    // Compare `[[Class]]` names.
    var className = toString.call(a);
    if (className != toString.call(b)) return false;
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b);
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b;
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
               a.global == b.global &&
               a.multiline == b.multiline &&
               a.ignoreCase == b.ignoreCase;
    }
    if (typeof a != 'object' || typeof b != 'object') return false;
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = stack.length;
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (stack[length] == a) return true;
    }
    // Add the first object to the stack of traversed objects.
    stack.push(a);
    var size = 0, result = true;
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length;
      result = size == b.length;
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          // Ensure commutative equality for sparse arrays.
          if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
        }
      }
    } else {
      // Objects with different constructors are not equivalent.
      if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
      // Deep compare objects.
      for (var key in a) {
        if (_.has(a, key)) {
          // Count the expected number of properties.
          size++;
          // Deep compare each member.
          if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (_.has(b, key) && !(size--)) break;
        }
        result = !size;
      }
    }
    // Remove the first object from the stack of traversed objects.
    stack.pop();
    return result;
  }

  // Perform a deep comparison to check if two objects are equal.
  _.isEqual = function(a, b) {
    return eq(a, b, []);
  };

  // Is a given array, string, or object empty?
  // An "empty" object has no enumerable own-properties.
  _.isEmpty = function(obj) {
    if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
    for (var key in obj) if (_.has(obj, key)) return false;
    return true;
  };

  // Is a given value a DOM element?
  _.isElement = function(obj) {
    return !!(obj && obj.nodeType == 1);
  };

  // Is a given value an array?
  // Delegates to ECMA5's native Array.isArray
  _.isArray = nativeIsArray || function(obj) {
    return toString.call(obj) == '[object Array]';
  };

  // Is a given variable an object?
  _.isObject = function(obj) {
    return obj === Object(obj);
  };

  // Is a given variable an arguments object?
  _.isArguments = function(obj) {
    return toString.call(obj) == '[object Arguments]';
  };
  if (!_.isArguments(arguments)) {
    _.isArguments = function(obj) {
      return !!(obj && _.has(obj, 'callee'));
    };
  }

  // Is a given value a function?
  _.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

  // Is a given value a string?
  _.isString = function(obj) {
    return toString.call(obj) == '[object String]';
  };

  // Is a given value a number?
  _.isNumber = function(obj) {
    return toString.call(obj) == '[object Number]';
  };

  // Is the given value `NaN`?
  _.isNaN = function(obj) {
    // `NaN` is the only value for which `===` is not reflexive.
    return obj !== obj;
  };

  // Is a given value a boolean?
  _.isBoolean = function(obj) {
    return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
  };

  // Is a given value a date?
  _.isDate = function(obj) {
    return toString.call(obj) == '[object Date]';
  };

  // Is the given value a regular expression?
  _.isRegExp = function(obj) {
    return toString.call(obj) == '[object RegExp]';
  };

  // Is a given value equal to null?
  _.isNull = function(obj) {
    return obj === null;
  };

  // Is a given variable undefined?
  _.isUndefined = function(obj) {
    return obj === void 0;
  };

  // Has own property?
  _.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
  };

  // Utility Functions
  // -----------------

  // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
  // previous owner. Returns a reference to the Underscore object.
  _.noConflict = function() {
    root._ = previousUnderscore;
    return this;
  };

  // Keep the identity function around for default iterators.
  _.identity = function(value) {
    return value;
  };

  // Run a function **n** times.
  _.times = function (n, iterator, context) {
    for (var i = 0; i < n; i++) iterator.call(context, i);
  };

  // Escape a string for HTML interpolation.
  _.escape = function(string) {
    return (''+string).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#x27;').replace(/\//g,'&#x2F;');
  };

  // Add your own custom functions to the Underscore object, ensuring that
  // they're correctly added to the OOP wrapper as well.
  _.mixin = function(obj) {
    each(_.functions(obj), function(name){
      addToWrapper(name, _[name] = obj[name]);
    });
  };

  // Generate a unique integer id (unique within the entire client session).
  // Useful for temporary DOM ids.
  var idCounter = 0;
  _.uniqueId = function(prefix) {
    var id = idCounter++;
    return prefix ? prefix + id : id;
  };

  // By default, Underscore uses ERB-style template delimiters, change the
  // following template settings to use alternative delimiters.
  _.templateSettings = {
    evaluate    : /<%([\s\S]+?)%>/g,
    interpolate : /<%=([\s\S]+?)%>/g,
    escape      : /<%-([\s\S]+?)%>/g
  };

  // When customizing `templateSettings`, if you don't want to define an
  // interpolation, evaluation or escaping regex, we need one that is
  // guaranteed not to match.
  var noMatch = /.^/;

  // Within an interpolation, evaluation, or escaping, remove HTML escaping
  // that had been previously added.
  var unescape = function(code) {
    return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
  };

  // JavaScript micro-templating, similar to John Resig's implementation.
  // Underscore templating handles arbitrary delimiters, preserves whitespace,
  // and correctly escapes quotes within interpolated code.
  _.template = function(str, data) {
    var c  = _.templateSettings;
    var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
      'with(obj||{}){__p.push(\'' +
      str.replace(/\\/g, '\\\\')
         .replace(/'/g, "\\'")
         .replace(c.escape || noMatch, function(match, code) {
           return "',_.escape(" + unescape(code) + "),'";
         })
         .replace(c.interpolate || noMatch, function(match, code) {
           return "'," + unescape(code) + ",'";
         })
         .replace(c.evaluate || noMatch, function(match, code) {
           return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
         })
         .replace(/\r/g, '\\r')
         .replace(/\n/g, '\\n')
         .replace(/\t/g, '\\t')
         + "');}return __p.join('');";
    var func = new Function('obj', '_', tmpl);
    if (data) return func(data, _);
    return function(data) {
      return func.call(this, data, _);
    };
  };

  // Add a "chain" function, which will delegate to the wrapper.
  _.chain = function(obj) {
    return _(obj).chain();
  };

  // The OOP Wrapper
  // ---------------

  // If Underscore is called as a function, it returns a wrapped object that
  // can be used OO-style. This wrapper holds altered versions of all the
  // underscore functions. Wrapped objects may be chained.
  var wrapper = function(obj) { this._wrapped = obj; };

  // Expose `wrapper.prototype` as `_.prototype`
  _.prototype = wrapper.prototype;

  // Helper function to continue chaining intermediate results.
  var result = function(obj, chain) {
    return chain ? _(obj).chain() : obj;
  };

  // A method to easily add functions to the OOP wrapper.
  var addToWrapper = function(name, func) {
    wrapper.prototype[name] = function() {
      var args = slice.call(arguments);
      unshift.call(args, this._wrapped);
      return result(func.apply(_, args), this._chain);
    };
  };

  // Add all of the Underscore functions to the wrapper object.
  _.mixin(_);

  // Add all mutator Array functions to the wrapper.
  each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      var wrapped = this._wrapped;
      method.apply(wrapped, arguments);
      var length = wrapped.length;
      if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
      return result(wrapped, this._chain);
    };
  });

  // Add all accessor Array functions to the wrapper.
  each(['concat', 'join', 'slice'], function(name) {
    var method = ArrayProto[name];
    wrapper.prototype[name] = function() {
      return result(method.apply(this._wrapped, arguments), this._chain);
    };
  });

  // Start chaining a wrapped Underscore object.
  wrapper.prototype.chain = function() {
    this._chain = true;
    return this;
  };

  // Extracts the result from a wrapped and chained object.
  wrapper.prototype.value = function() {
    return this._wrapped;
  };

}).call(this);
PK
%�\��;�l/l/html/_static/underscore.jsnu�[���// Underscore.js 1.3.1
// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source==
c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h in c)if(b.has(c,
h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var j=b.each=
b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.length>2;a==
null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=
function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=
e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=
function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a,computed:b})});
return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,
c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length-1]};b.rest=
b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];return d},[]);
return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=function(a,c,
d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d;return g};
var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.memoize=function(a,
c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c));g?h=true:
a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)];return b[0]}};
b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function(a){j(i.call(arguments,
1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){return a===Object(a)};
b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a)=="[object Date]"};
b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;").replace(/\//g,"&#x2F;")};b.mixin=function(a){j(b.functions(a),
function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return"',_.escape("+
u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=function(a,c){m.prototype[a]=
function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.chain=function(){this._chain=
true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
PK
%�\���H��html/_static/up-pressed.pngnu�[����PNG


IHDR�a�IDATxc� �o+Sb�)Sb�G&W�
 ��+H�,���Cق��
n;�"VsT�?��.#&ھ�jF�c�g��b�
.�.�NG`49l��*�
Ŀ��'q<��*��]�J��c���y�j�����ؖ��f�b0S�ԙ�µ���|IEND�B`�PK
%�\>u���html/_static/up.pngnu�[����PNG


IHDR��7��IDATx�����@��e�z $���&�	�8�:�& :Kpw�n}���O�����<��:!!��{�G@�Dz?�"̧���	�S��{g�<�ݢ� lMQw�y�|�?�
0	pq8q`�	��p�L-'��SBNA��wT���ń�|UVIEND�B`�PK
%�\Fo,�cchtml/_static/websupport.jsnu�[���/*
 * websupport.js
 * ~~~~~~~~~~~~~
 *
 * sphinx.websupport utilities for all documentation.
 *
 * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
 * :license: BSD, see LICENSE for details.
 *
 */

(function($) {
  $.fn.autogrow = function() {
    return this.each(function() {
    var textarea = this;

    $.fn.autogrow.resize(textarea);

    $(textarea)
      .focus(function() {
        textarea.interval = setInterval(function() {
          $.fn.autogrow.resize(textarea);
        }, 500);
      })
      .blur(function() {
        clearInterval(textarea.interval);
      });
    });
  };

  $.fn.autogrow.resize = function(textarea) {
    var lineHeight = parseInt($(textarea).css('line-height'), 10);
    var lines = textarea.value.split('\n');
    var columns = textarea.cols;
    var lineCount = 0;
    $.each(lines, function() {
      lineCount += Math.ceil(this.length / columns) || 1;
    });
    var height = lineHeight * (lineCount + 1);
    $(textarea).css('height', height);
  };
})(jQuery);

(function($) {
  var comp, by;

  function init() {
    initEvents();
    initComparator();
  }

  function initEvents() {
    $(document).on("click", 'a.comment-close', function(event) {
      event.preventDefault();
      hide($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.vote', function(event) {
      event.preventDefault();
      handleVote($(this));
    });
    $(document).on("click", 'a.reply', function(event) {
      event.preventDefault();
      openReply($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.close-reply', function(event) {
      event.preventDefault();
      closeReply($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.sort-option', function(event) {
      event.preventDefault();
      handleReSort($(this));
    });
    $(document).on("click", 'a.show-proposal', function(event) {
      event.preventDefault();
      showProposal($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.hide-proposal', function(event) {
      event.preventDefault();
      hideProposal($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.show-propose-change', function(event) {
      event.preventDefault();
      showProposeChange($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.hide-propose-change', function(event) {
      event.preventDefault();
      hideProposeChange($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.accept-comment', function(event) {
      event.preventDefault();
      acceptComment($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.delete-comment', function(event) {
      event.preventDefault();
      deleteComment($(this).attr('id').substring(2));
    });
    $(document).on("click", 'a.comment-markup', function(event) {
      event.preventDefault();
      toggleCommentMarkupBox($(this).attr('id').substring(2));
    });
  }

  /**
   * Set comp, which is a comparator function used for sorting and
   * inserting comments into the list.
   */
  function setComparator() {
    // If the first three letters are "asc", sort in ascending order
    // and remove the prefix.
    if (by.substring(0,3) == 'asc') {
      var i = by.substring(3);
      comp = function(a, b) { return a[i] - b[i]; };
    } else {
      // Otherwise sort in descending order.
      comp = function(a, b) { return b[by] - a[by]; };
    }

    // Reset link styles and format the selected sort option.
    $('a.sel').attr('href', '#').removeClass('sel');
    $('a.by' + by).removeAttr('href').addClass('sel');
  }

  /**
   * Create a comp function. If the user has preferences stored in
   * the sortBy cookie, use those, otherwise use the default.
   */
  function initComparator() {
    by = 'rating'; // Default to sort by rating.
    // If the sortBy cookie is set, use that instead.
    if (document.cookie.length > 0) {
      var start = document.cookie.indexOf('sortBy=');
      if (start != -1) {
        start = start + 7;
        var end = document.cookie.indexOf(";", start);
        if (end == -1) {
          end = document.cookie.length;
          by = unescape(document.cookie.substring(start, end));
        }
      }
    }
    setComparator();
  }

  /**
   * Show a comment div.
   */
  function show(id) {
    $('#ao' + id).hide();
    $('#ah' + id).show();
    var context = $.extend({id: id}, opts);
    var popup = $(renderTemplate(popupTemplate, context)).hide();
    popup.find('textarea[name="proposal"]').hide();
    popup.find('a.by' + by).addClass('sel');
    var form = popup.find('#cf' + id);
    form.submit(function(event) {
      event.preventDefault();
      addComment(form);
    });
    $('#s' + id).after(popup);
    popup.slideDown('fast', function() {
      getComments(id);
    });
  }

  /**
   * Hide a comment div.
   */
  function hide(id) {
    $('#ah' + id).hide();
    $('#ao' + id).show();
    var div = $('#sc' + id);
    div.slideUp('fast', function() {
      div.remove();
    });
  }

  /**
   * Perform an ajax request to get comments for a node
   * and insert the comments into the comments tree.
   */
  function getComments(id) {
    $.ajax({
     type: 'GET',
     url: opts.getCommentsURL,
     data: {node: id},
     success: function(data, textStatus, request) {
       var ul = $('#cl' + id);
       var speed = 100;
       $('#cf' + id)
         .find('textarea[name="proposal"]')
         .data('source', data.source);

       if (data.comments.length === 0) {
         ul.html('<li>No comments yet.</li>');
         ul.data('empty', true);
       } else {
         // If there are comments, sort them and put them in the list.
         var comments = sortComments(data.comments);
         speed = data.comments.length * 100;
         appendComments(comments, ul);
         ul.data('empty', false);
       }
       $('#cn' + id).slideUp(speed + 200);
       ul.slideDown(speed);
     },
     error: function(request, textStatus, error) {
       showError('Oops, there was a problem retrieving the comments.');
     },
     dataType: 'json'
    });
  }

  /**
   * Add a comment via ajax and insert the comment into the comment tree.
   */
  function addComment(form) {
    var node_id = form.find('input[name="node"]').val();
    var parent_id = form.find('input[name="parent"]').val();
    var text = form.find('textarea[name="comment"]').val();
    var proposal = form.find('textarea[name="proposal"]').val();

    if (text == '') {
      showError('Please enter a comment.');
      return;
    }

    // Disable the form that is being submitted.
    form.find('textarea,input').attr('disabled', 'disabled');

    // Send the comment to the server.
    $.ajax({
      type: "POST",
      url: opts.addCommentURL,
      dataType: 'json',
      data: {
        node: node_id,
        parent: parent_id,
        text: text,
        proposal: proposal
      },
      success: function(data, textStatus, error) {
        // Reset the form.
        if (node_id) {
          hideProposeChange(node_id);
        }
        form.find('textarea')
          .val('')
          .add(form.find('input'))
          .removeAttr('disabled');
	var ul = $('#cl' + (node_id || parent_id));
        if (ul.data('empty')) {
          $(ul).empty();
          ul.data('empty', false);
        }
        insertComment(data.comment);
        var ao = $('#ao' + node_id);
        ao.find('img').attr({'src': opts.commentBrightImage});
        if (node_id) {
          // if this was a "root" comment, remove the commenting box
          // (the user can get it back by reopening the comment popup)
          $('#ca' + node_id).slideUp();
        }
      },
      error: function(request, textStatus, error) {
        form.find('textarea,input').removeAttr('disabled');
        showError('Oops, there was a problem adding the comment.');
      }
    });
  }

  /**
   * Recursively append comments to the main comment list and children
   * lists, creating the comment tree.
   */
  function appendComments(comments, ul) {
    $.each(comments, function() {
      var div = createCommentDiv(this);
      ul.append($(document.createElement('li')).html(div));
      appendComments(this.children, div.find('ul.comment-children'));
      // To avoid stagnating data, don't store the comments children in data.
      this.children = null;
      div.data('comment', this);
    });
  }

  /**
   * After adding a new comment, it must be inserted in the correct
   * location in the comment tree.
   */
  function insertComment(comment) {
    var div = createCommentDiv(comment);

    // To avoid stagnating data, don't store the comments children in data.
    comment.children = null;
    div.data('comment', comment);

    var ul = $('#cl' + (comment.node || comment.parent));
    var siblings = getChildren(ul);

    var li = $(document.createElement('li'));
    li.hide();

    // Determine where in the parents children list to insert this comment.
    for(var i=0; i < siblings.length; i++) {
      if (comp(comment, siblings[i]) <= 0) {
        $('#cd' + siblings[i].id)
          .parent()
          .before(li.html(div));
        li.slideDown('fast');
        return;
      }
    }

    // If we get here, this comment rates lower than all the others,
    // or it is the only comment in the list.
    ul.append(li.html(div));
    li.slideDown('fast');
  }

  function acceptComment(id) {
    $.ajax({
      type: 'POST',
      url: opts.acceptCommentURL,
      data: {id: id},
      success: function(data, textStatus, request) {
        $('#cm' + id).fadeOut('fast');
        $('#cd' + id).removeClass('moderate');
      },
      error: function(request, textStatus, error) {
        showError('Oops, there was a problem accepting the comment.');
      }
    });
  }

  function deleteComment(id) {
    $.ajax({
      type: 'POST',
      url: opts.deleteCommentURL,
      data: {id: id},
      success: function(data, textStatus, request) {
        var div = $('#cd' + id);
        if (data == 'delete') {
          // Moderator mode: remove the comment and all children immediately
          div.slideUp('fast', function() {
            div.remove();
          });
          return;
        }
        // User mode: only mark the comment as deleted
        div
          .find('span.user-id:first')
          .text('[deleted]').end()
          .find('div.comment-text:first')
          .text('[deleted]').end()
          .find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id +
                ', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id)
          .remove();
        var comment = div.data('comment');
        comment.username = '[deleted]';
        comment.text = '[deleted]';
        div.data('comment', comment);
      },
      error: function(request, textStatus, error) {
        showError('Oops, there was a problem deleting the comment.');
      }
    });
  }

  function showProposal(id) {
    $('#sp' + id).hide();
    $('#hp' + id).show();
    $('#pr' + id).slideDown('fast');
  }

  function hideProposal(id) {
    $('#hp' + id).hide();
    $('#sp' + id).show();
    $('#pr' + id).slideUp('fast');
  }

  function showProposeChange(id) {
    $('#pc' + id).hide();
    $('#hc' + id).show();
    var textarea = $('#pt' + id);
    textarea.val(textarea.data('source'));
    $.fn.autogrow.resize(textarea[0]);
    textarea.slideDown('fast');
  }

  function hideProposeChange(id) {
    $('#hc' + id).hide();
    $('#pc' + id).show();
    var textarea = $('#pt' + id);
    textarea.val('').removeAttr('disabled');
    textarea.slideUp('fast');
  }

  function toggleCommentMarkupBox(id) {
    $('#mb' + id).toggle();
  }

  /** Handle when the user clicks on a sort by link. */
  function handleReSort(link) {
    var classes = link.attr('class').split(/\s+/);
    for (var i=0; i<classes.length; i++) {
      if (classes[i] != 'sort-option') {
	by = classes[i].substring(2);
      }
    }
    setComparator();
    // Save/update the sortBy cookie.
    var expiration = new Date();
    expiration.setDate(expiration.getDate() + 365);
    document.cookie= 'sortBy=' + escape(by) +
                     ';expires=' + expiration.toUTCString();
    $('ul.comment-ul').each(function(index, ul) {
      var comments = getChildren($(ul), true);
      comments = sortComments(comments);
      appendComments(comments, $(ul).empty());
    });
  }

  /**
   * Function to process a vote when a user clicks an arrow.
   */
  function handleVote(link) {
    if (!opts.voting) {
      showError("You'll need to login to vote.");
      return;
    }

    var id = link.attr('id');
    if (!id) {
      // Didn't click on one of the voting arrows.
      return;
    }
    // If it is an unvote, the new vote value is 0,
    // Otherwise it's 1 for an upvote, or -1 for a downvote.
    var value = 0;
    if (id.charAt(1) != 'u') {
      value = id.charAt(0) == 'u' ? 1 : -1;
    }
    // The data to be sent to the server.
    var d = {
      comment_id: id.substring(2),
      value: value
    };

    // Swap the vote and unvote links.
    link.hide();
    $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
      .show();

    // The div the comment is displayed in.
    var div = $('div#cd' + d.comment_id);
    var data = div.data('comment');

    // If this is not an unvote, and the other vote arrow has
    // already been pressed, unpress it.
    if ((d.value !== 0) && (data.vote === d.value * -1)) {
      $('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
      $('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
    }

    // Update the comments rating in the local data.
    data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
    data.vote = d.value;
    div.data('comment', data);

    // Change the rating text.
    div.find('.rating:first')
      .text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));

    // Send the vote information to the server.
    $.ajax({
      type: "POST",
      url: opts.processVoteURL,
      data: d,
      error: function(request, textStatus, error) {
        showError('Oops, there was a problem casting that vote.');
      }
    });
  }

  /**
   * Open a reply form used to reply to an existing comment.
   */
  function openReply(id) {
    // Swap out the reply link for the hide link
    $('#rl' + id).hide();
    $('#cr' + id).show();

    // Add the reply li to the children ul.
    var div = $(renderTemplate(replyTemplate, {id: id})).hide();
    $('#cl' + id)
      .prepend(div)
      // Setup the submit handler for the reply form.
      .find('#rf' + id)
      .submit(function(event) {
        event.preventDefault();
        addComment($('#rf' + id));
        closeReply(id);
      })
      .find('input[type=button]')
      .click(function() {
        closeReply(id);
      });
    div.slideDown('fast', function() {
      $('#rf' + id).find('textarea').focus();
    });
  }

  /**
   * Close the reply form opened with openReply.
   */
  function closeReply(id) {
    // Remove the reply div from the DOM.
    $('#rd' + id).slideUp('fast', function() {
      $(this).remove();
    });

    // Swap out the hide link for the reply link
    $('#cr' + id).hide();
    $('#rl' + id).show();
  }

  /**
   * Recursively sort a tree of comments using the comp comparator.
   */
  function sortComments(comments) {
    comments.sort(comp);
    $.each(comments, function() {
      this.children = sortComments(this.children);
    });
    return comments;
  }

  /**
   * Get the children comments from a ul. If recursive is true,
   * recursively include childrens' children.
   */
  function getChildren(ul, recursive) {
    var children = [];
    ul.children().children("[id^='cd']")
      .each(function() {
        var comment = $(this).data('comment');
        if (recursive)
          comment.children = getChildren($(this).find('#cl' + comment.id), true);
        children.push(comment);
      });
    return children;
  }

  /** Create a div to display a comment in. */
  function createCommentDiv(comment) {
    if (!comment.displayed && !opts.moderator) {
      return $('<div class="moderate">Thank you!  Your comment will show up '
               + 'once it is has been approved by a moderator.</div>');
    }
    // Prettify the comment rating.
    comment.pretty_rating = comment.rating + ' point' +
      (comment.rating == 1 ? '' : 's');
    // Make a class (for displaying not yet moderated comments differently)
    comment.css_class = comment.displayed ? '' : ' moderate';
    // Create a div for this comment.
    var context = $.extend({}, opts, comment);
    var div = $(renderTemplate(commentTemplate, context));

    // If the user has voted on this comment, highlight the correct arrow.
    if (comment.vote) {
      var direction = (comment.vote == 1) ? 'u' : 'd';
      div.find('#' + direction + 'v' + comment.id).hide();
      div.find('#' + direction + 'u' + comment.id).show();
    }

    if (opts.moderator || comment.text != '[deleted]') {
      div.find('a.reply').show();
      if (comment.proposal_diff)
        div.find('#sp' + comment.id).show();
      if (opts.moderator && !comment.displayed)
        div.find('#cm' + comment.id).show();
      if (opts.moderator || (opts.username == comment.username))
        div.find('#dc' + comment.id).show();
    }
    return div;
  }

  /**
   * A simple template renderer. Placeholders such as <%id%> are replaced
   * by context['id'] with items being escaped. Placeholders such as <#id#>
   * are not escaped.
   */
  function renderTemplate(template, context) {
    var esc = $(document.createElement('div'));

    function handle(ph, escape) {
      var cur = context;
      $.each(ph.split('.'), function() {
        cur = cur[this];
      });
      return escape ? esc.text(cur || "").html() : cur;
    }

    return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
      return handle(arguments[2], arguments[1] == '%' ? true : false);
    });
  }

  /** Flash an error message briefly. */
  function showError(message) {
    $(document.createElement('div')).attr({'class': 'popup-error'})
      .append($(document.createElement('div'))
               .attr({'class': 'error-message'}).text(message))
      .appendTo('body')
      .fadeIn("slow")
      .delay(2000)
      .fadeOut("slow");
  }

  /** Add a link the user uses to open the comments popup. */
  $.fn.comment = function() {
    return this.each(function() {
      var id = $(this).attr('id').substring(1);
      var count = COMMENT_METADATA[id];
      var title = count + ' comment' + (count == 1 ? '' : 's');
      var image = count > 0 ? opts.commentBrightImage : opts.commentImage;
      var addcls = count == 0 ? ' nocomment' : '';
      $(this)
        .append(
          $(document.createElement('a')).attr({
            href: '#',
            'class': 'sphinx-comment-open' + addcls,
            id: 'ao' + id
          })
            .append($(document.createElement('img')).attr({
              src: image,
              alt: 'comment',
              title: title
            }))
            .click(function(event) {
              event.preventDefault();
              show($(this).attr('id').substring(2));
            })
        )
        .append(
          $(document.createElement('a')).attr({
            href: '#',
            'class': 'sphinx-comment-close hidden',
            id: 'ah' + id
          })
            .append($(document.createElement('img')).attr({
              src: opts.closeCommentImage,
              alt: 'close',
              title: 'close'
            }))
            .click(function(event) {
              event.preventDefault();
              hide($(this).attr('id').substring(2));
            })
        );
    });
  };

  var opts = {
    processVoteURL: '/_process_vote',
    addCommentURL: '/_add_comment',
    getCommentsURL: '/_get_comments',
    acceptCommentURL: '/_accept_comment',
    deleteCommentURL: '/_delete_comment',
    commentImage: '/static/_static/comment.png',
    closeCommentImage: '/static/_static/comment-close.png',
    loadingImage: '/static/_static/ajax-loader.gif',
    commentBrightImage: '/static/_static/comment-bright.png',
    upArrow: '/static/_static/up.png',
    downArrow: '/static/_static/down.png',
    upArrowPressed: '/static/_static/up-pressed.png',
    downArrowPressed: '/static/_static/down-pressed.png',
    voting: false,
    moderator: false
  };

  if (typeof COMMENT_OPTIONS != "undefined") {
    opts = jQuery.extend(opts, COMMENT_OPTIONS);
  }

  var popupTemplate = '\
    <div class="sphinx-comments" id="sc<%id%>">\
      <p class="sort-options">\
        Sort by:\
        <a href="#" class="sort-option byrating">best rated</a>\
        <a href="#" class="sort-option byascage">newest</a>\
        <a href="#" class="sort-option byage">oldest</a>\
      </p>\
      <div class="comment-header">Comments</div>\
      <div class="comment-loading" id="cn<%id%>">\
        loading comments... <img src="<%loadingImage%>" alt="" /></div>\
      <ul id="cl<%id%>" class="comment-ul"></ul>\
      <div id="ca<%id%>">\
      <p class="add-a-comment">Add a comment\
        (<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\
      <div class="comment-markup-box" id="mb<%id%>">\
        reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \
        <code>``code``</code>, \
        code blocks: <code>::</code> and an indented block after blank line</div>\
      <form method="post" id="cf<%id%>" class="comment-form" action="">\
        <textarea name="comment" cols="80"></textarea>\
        <p class="propose-button">\
          <a href="#" id="pc<%id%>" class="show-propose-change">\
            Propose a change &#9657;\
          </a>\
          <a href="#" id="hc<%id%>" class="hide-propose-change">\
            Propose a change &#9663;\
          </a>\
        </p>\
        <textarea name="proposal" id="pt<%id%>" cols="80"\
                  spellcheck="false"></textarea>\
        <input type="submit" value="Add comment" />\
        <input type="hidden" name="node" value="<%id%>" />\
        <input type="hidden" name="parent" value="" />\
      </form>\
      </div>\
    </div>';

  var commentTemplate = '\
    <div id="cd<%id%>" class="sphinx-comment<%css_class%>">\
      <div class="vote">\
        <div class="arrow">\
          <a href="#" id="uv<%id%>" class="vote" title="vote up">\
            <img src="<%upArrow%>" />\
          </a>\
          <a href="#" id="uu<%id%>" class="un vote" title="vote up">\
            <img src="<%upArrowPressed%>" />\
          </a>\
        </div>\
        <div class="arrow">\
          <a href="#" id="dv<%id%>" class="vote" title="vote down">\
            <img src="<%downArrow%>" id="da<%id%>" />\
          </a>\
          <a href="#" id="du<%id%>" class="un vote" title="vote down">\
            <img src="<%downArrowPressed%>" />\
          </a>\
        </div>\
      </div>\
      <div class="comment-content">\
        <p class="tagline comment">\
          <span class="user-id"><%username%></span>\
          <span class="rating"><%pretty_rating%></span>\
          <span class="delta"><%time.delta%></span>\
        </p>\
        <div class="comment-text comment"><#text#></div>\
        <p class="comment-opts comment">\
          <a href="#" class="reply hidden" id="rl<%id%>">reply &#9657;</a>\
          <a href="#" class="close-reply" id="cr<%id%>">reply &#9663;</a>\
          <a href="#" id="sp<%id%>" class="show-proposal">proposal &#9657;</a>\
          <a href="#" id="hp<%id%>" class="hide-proposal">proposal &#9663;</a>\
          <a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\
          <span id="cm<%id%>" class="moderation hidden">\
            <a href="#" id="ac<%id%>" class="accept-comment">accept</a>\
          </span>\
        </p>\
        <pre class="proposal" id="pr<%id%>">\
<#proposal_diff#>\
        </pre>\
          <ul class="comment-children" id="cl<%id%>"></ul>\
        </div>\
        <div class="clearleft"></div>\
      </div>\
    </div>';

  var replyTemplate = '\
    <li>\
      <div class="reply-div" id="rd<%id%>">\
        <form id="rf<%id%>">\
          <textarea name="comment" cols="80"></textarea>\
          <input type="submit" value="Add reply" />\
          <input type="button" value="Cancel" />\
          <input type="hidden" name="parent" value="<%id%>" />\
          <input type="hidden" name="node" value="" />\
        </form>\
      </div>\
    </li>';

  $(document).ready(function() {
    init();
  });
})(jQuery);

$(document).ready(function() {
  // add comment anchors for all paragraphs that are commentable
  $('.sphinx-has-comment').comment();

  // highlight search words in search results
  $("div.context").each(function() {
    var params = $.getQueryParameters();
    var terms = (params.q) ? params.q[0].split(/\s+/) : [];
    var result = $(this);
    $.each(terms, function() {
      result.highlightText(this.toLowerCase(), 'highlighted');
    });
  });

  // directly open comment window if requested
  var anchor = document.location.hash;
  if (anchor.substring(0, 9) == '#comment-') {
    $('#ao' + anchor.substring(9)).click();
    document.location.hash = '#s' + anchor.substring(9);
  }
});
PK
%�\�NC�L!L!html/c-api/gen.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Generator Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="DateTime Objects" href="datetime.html" />
    <link rel="prev" title="Cell Objects" href="cell.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/gen.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="DateTime Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cell.html" title="Cell Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="generator-objects">
<span id="gen-objects"></span><h1>Generator Objects<a class="headerlink" href="#generator-objects" title="Permalink to this headline">¶</a></h1>
<p>Generator objects are what Python uses to implement generator iterators. They
are normally created by iterating over a function that yields values, rather
than explicitly calling <a class="reference internal" href="#c.PyGen_New" title="PyGen_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGen_New()</span></code></a>.</p>
<dl class="type">
<dt id="c.PyGenObject">
<code class="descname">PyGenObject</code><a class="headerlink" href="#c.PyGenObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure used for generator objects.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyGen_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyGen_Type</code><a class="headerlink" href="#c.PyGen_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object corresponding to generator objects.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyGen_Check">
int <code class="descname">PyGen_Check</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyGen_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is a generator object; <em>ob</em> must not be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyGen_CheckExact">
int <code class="descname">PyGen_CheckExact</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyGen_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em>’s type is <em>PyGen_Type</em> is a generator object; <em>ob</em> must not
be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyGen_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyGen_New</code><span class="sig-paren">(</span>PyFrameObject<em>&nbsp;*frame</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyGen_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create and return a new generator object based on the <em>frame</em> object. A
reference to <em>frame</em> is stolen by this function. The parameter must not be
<em>NULL</em>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="cell.html"
                        title="previous chapter">Cell Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datetime.html"
                        title="next chapter">DateTime Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/gen.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="DateTime Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="cell.html" title="Cell Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\+�����html/c-api/import.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Importing Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Data marshalling support" href="marshal.html" />
    <link rel="prev" title="Operating System Utilities" href="sys.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/import.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="Data marshalling support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sys.html" title="Operating System Utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="importing-modules">
<span id="importing"></span><h1>Importing Modules<a class="headerlink" href="#importing-modules" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyImport_ImportModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ImportModule</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ImportModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-0">This is a simplified interface to <a class="reference internal" href="#c.PyImport_ImportModuleEx" title="PyImport_ImportModuleEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleEx()</span></code></a> below,
leaving the <em>globals</em> and <em>locals</em> arguments set to <em>NULL</em> and <em>level</em> set
to 0.  When the <em>name</em>
argument contains a dot (when it specifies a submodule of a package), the
<em>fromlist</em> argument is set to the list <code class="docutils literal notranslate"><span class="pre">['*']</span></code> so that the return value is the
named module rather than the top-level package containing it as would otherwise
be the case.  (Unfortunately, this has an additional side effect when <em>name</em> in
fact specifies a subpackage instead of a submodule: the submodules specified in
the package’s <code class="docutils literal notranslate"><span class="pre">__all__</span></code> variable are  loaded.)  Return a new reference to the
imported module, or <em>NULL</em> with an exception set on failure.  Before Python 2.4,
the module may still be created in the failure case — examine <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>
to find out.  Starting with Python 2.4, a failing import of a module no longer
leaves the module in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Failing imports remove incomplete module objects.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Always uses absolute imports.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ImportModuleNoBlock">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ImportModuleNoBlock</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ImportModuleNoBlock" title="Permalink to this definition">¶</a></dt>
<dd><p>This version of <a class="reference internal" href="#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a> does not block. It’s intended
to be used in C functions that import other modules to execute a function.
The import may block if another thread holds the import lock. The function
<a class="reference internal" href="#c.PyImport_ImportModuleNoBlock" title="PyImport_ImportModuleNoBlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleNoBlock()</span></code></a> never blocks. It first tries to fetch
the module from sys.modules and falls back to <a class="reference internal" href="#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>
unless the lock is held, in which case the function will raise an
<a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ImportModuleEx">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ImportModuleEx</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*fromlist</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ImportModuleEx" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-1">Import a module.  This is best described by referring to the built-in Python
function <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>, as the standard <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function calls
this function directly.</p>
<p>The return value is a new reference to the imported module or top-level package,
or <em>NULL</em> with an exception set on failure (before Python 2.4, the module may
still be created in this case).  Like for <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>, the return value
when a submodule of a package was requested is normally the top-level package,
unless a non-empty <em>fromlist</em> was given.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Failing imports remove incomplete module objects.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The function is an alias for <a class="reference internal" href="#c.PyImport_ImportModuleLevel" title="PyImport_ImportModuleLevel"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleLevel()</span></code></a> with
<code class="docutils literal notranslate"><span class="pre">-1</span></code> as level, meaning relative import.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ImportModuleLevel">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ImportModuleLevel</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*fromlist</em>, int<em>&nbsp;level</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ImportModuleLevel" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Import a module.  This is best described by referring to the built-in Python
function <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>, as the standard <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function calls
this function directly.</p>
<p>The return value is a new reference to the imported module or top-level package,
or <em>NULL</em> with an exception set on failure.  Like for <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>,
the return value when a submodule of a package was requested is normally the
top-level package, unless a non-empty <em>fromlist</em> was given.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_Import">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_Import</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_Import" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">This is a higher-level interface that calls the current “import hook function”.
It invokes the <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function from the <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> of the
current globals.  This means that the import is done using whatever import hooks
are installed in the current environment, e.g. by <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Always uses absolute imports.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ReloadModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ReloadModule</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*m</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ReloadModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-3">Reload a module.  This is best described by referring to the built-in Python
function <a class="reference internal" href="../library/functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a>, as the standard <a class="reference internal" href="../library/functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> function calls this
function directly.  Return a new reference to the reloaded module, or <em>NULL</em>
with an exception set on failure (the module still exists in this case).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_AddModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_AddModule</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_AddModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the module object corresponding to a module name.  The <em>name</em> argument
may be of the form <code class="docutils literal notranslate"><span class="pre">package.module</span></code>. First check the modules dictionary if
there’s one there, and if not, create a new one and insert it in the modules
dictionary. Return <em>NULL</em> with an exception set on failure.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function does not load or import the module; if the module wasn’t already
loaded, you will get an empty module object. Use <a class="reference internal" href="#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>
or one of its variants to import a module.  Package structures implied by a
dotted name for <em>name</em> are not created if not already present.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ExecCodeModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ExecCodeModule</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*co</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ExecCodeModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-4">Given a module name (possibly of the form <code class="docutils literal notranslate"><span class="pre">package.module</span></code>) and a code object
read from a Python bytecode file or obtained from the built-in function
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>, load the module.  Return a new reference to the module object,
or <em>NULL</em> with an exception set if an error occurred.  Before Python 2.4, the
module could still be created in error cases.  Starting with Python 2.4, <em>name</em>
is removed from <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.modules</span></code></a> in error cases, and even if <em>name</em> was already
in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.modules</span></code></a> on entry to <a class="reference internal" href="#c.PyImport_ExecCodeModule" title="PyImport_ExecCodeModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ExecCodeModule()</span></code></a>.  Leaving
incompletely initialized modules in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.modules</span></code></a> is dangerous, as imports of
such modules have no way to know that the module object is an unknown (and
probably damaged with respect to the module author’s intents) state.</p>
<p>The module’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> attribute will be set to the code object’s
<code class="xref c c-member docutils literal notranslate"><span class="pre">co_filename</span></code>.</p>
<p>This function will reload the module if it was already imported.  See
<a class="reference internal" href="#c.PyImport_ReloadModule" title="PyImport_ReloadModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ReloadModule()</span></code></a> for the intended way to reload a module.</p>
<p>If <em>name</em> points to a dotted name of the form <code class="docutils literal notranslate"><span class="pre">package.module</span></code>, any package
structures not already created will still not be created.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>name</em> is removed from <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.modules</span></code></a> in error cases.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ExecCodeModuleEx">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_ExecCodeModuleEx</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*co</em>, char<em>&nbsp;*pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ExecCodeModuleEx" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Like <a class="reference internal" href="#c.PyImport_ExecCodeModule" title="PyImport_ExecCodeModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ExecCodeModule()</span></code></a>, but the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> attribute of
the module object is set to <em>pathname</em> if it is non-<code class="docutils literal notranslate"><span class="pre">NULL</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_GetMagicNumber">
long <code class="descname">PyImport_GetMagicNumber</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_GetMagicNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the magic number for Python bytecode files (a.k.a. <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> and
<code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files).  The magic number should be present in the first four bytes
of the bytecode file, in little-endian byte order.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_GetModuleDict">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_GetModuleDict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_GetModuleDict" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the dictionary used for the module administration (a.k.a.
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>).  Note that this is a per-interpreter variable.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_GetImporter">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyImport_GetImporter</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*path</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_GetImporter" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an importer object for a <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>/<code class="xref py py-attr docutils literal notranslate"><span class="pre">pkg.__path__</span></code> item
<em>path</em>, possibly by fetching it from the <a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a>
dict.  If it wasn’t yet cached, traverse <a class="reference internal" href="../library/sys.html#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a> until a hook
is found that can handle the path item.  Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no hook could;
this tells our caller it should fall back to the built-in import mechanism.
Cache the result in <a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a>.  Return a new reference
to the importer object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c._PyImport_Init">
void <code class="descname">_PyImport_Init</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c._PyImport_Init" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the import mechanism.  For internal use only.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_Cleanup">
void <code class="descname">PyImport_Cleanup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_Cleanup" title="Permalink to this definition">¶</a></dt>
<dd><p>Empty the module table.  For internal use only.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyImport_Fini">
void <code class="descname">_PyImport_Fini</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c._PyImport_Fini" title="Permalink to this definition">¶</a></dt>
<dd><p>Finalize the import mechanism.  For internal use only.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyImport_FindExtension">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">_PyImport_FindExtension</code><span class="sig-paren">(</span>char<em>&nbsp;*</em>, char<em>&nbsp;*</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyImport_FindExtension" title="Permalink to this definition">¶</a></dt>
<dd><p>For internal use only.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyImport_FixupExtension">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">_PyImport_FixupExtension</code><span class="sig-paren">(</span>char<em>&nbsp;*</em>, char<em>&nbsp;*</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyImport_FixupExtension" title="Permalink to this definition">¶</a></dt>
<dd><p>For internal use only.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ImportFrozenModule">
int <code class="descname">PyImport_ImportFrozenModule</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ImportFrozenModule" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a frozen module named <em>name</em>.  Return <code class="docutils literal notranslate"><span class="pre">1</span></code> for success, <code class="docutils literal notranslate"><span class="pre">0</span></code> if the
module is not found, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> with an exception set if the initialization
failed.  To access the imported module on a successful load, use
<a class="reference internal" href="#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>.  (Note the misnomer — this function would
reload the module if it was already imported.)</p>
</dd></dl>

<dl class="type">
<dt id="c._frozen">
struct <code class="descname">_frozen</code><a class="headerlink" href="#c._frozen" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">This is the structure type definition for frozen module descriptors, as
generated by the <strong class="program">freeze</strong> utility (see <code class="file docutils literal notranslate"><span class="pre">Tools/freeze/</span></code> in the
Python source distribution).  Its definition, found in <code class="file docutils literal notranslate"><span class="pre">Include/import.h</span></code>,
is:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">struct</span> <span class="n">_frozen</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">;</span>
    <span class="kt">unsigned</span> <span class="kt">char</span> <span class="o">*</span><span class="n">code</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">size</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
</div>
</dd></dl>

<dl class="var">
<dt id="c.PyImport_FrozenModules">
struct <a class="reference internal" href="#c._frozen" title="_frozen">_frozen</a>* <code class="descname">PyImport_FrozenModules</code><a class="headerlink" href="#c.PyImport_FrozenModules" title="Permalink to this definition">¶</a></dt>
<dd><p>This pointer is initialized to point to an array of <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">_frozen</span></code>
records, terminated by one whose members are all <em>NULL</em> or zero.  When a frozen
module is imported, it is searched in this table.  Third-party code could play
tricks with this to provide a dynamically created collection of frozen modules.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_AppendInittab">
int <code class="descname">PyImport_AppendInittab</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em>, void (<em>*initfunc</em>)(void)<span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_AppendInittab" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a single module to the existing table of built-in modules.  This is a
convenience wrapper around <a class="reference internal" href="#c.PyImport_ExtendInittab" title="PyImport_ExtendInittab"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ExtendInittab()</span></code></a>, returning <code class="docutils literal notranslate"><span class="pre">-1</span></code> if
the table could not be extended.  The new module can be imported by the name
<em>name</em>, and uses the function <em>initfunc</em> as the initialization function called
on the first attempted import.  This should be called before
<a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.</p>
</dd></dl>

<dl class="type">
<dt id="c._inittab">
struct <code class="descname">_inittab</code><a class="headerlink" href="#c._inittab" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure describing a single entry in the list of built-in modules.  Each of
these structures gives the name and initialization function for a module built
into the interpreter.  Programs which embed Python may use an array of these
structures in conjunction with <a class="reference internal" href="#c.PyImport_ExtendInittab" title="PyImport_ExtendInittab"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ExtendInittab()</span></code></a> to provide
additional built-in modules.  The structure is defined in
<code class="file docutils literal notranslate"><span class="pre">Include/import.h</span></code> as:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">struct</span> <span class="n">_inittab</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">;</span>
    <span class="kt">void</span> <span class="p">(</span><span class="o">*</span><span class="n">initfunc</span><span class="p">)(</span><span class="kt">void</span><span class="p">);</span>
<span class="p">};</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyImport_ExtendInittab">
int <code class="descname">PyImport_ExtendInittab</code><span class="sig-paren">(</span>struct <a class="reference internal" href="#c._inittab" title="_inittab">_inittab</a><em>&nbsp;*newtab</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyImport_ExtendInittab" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a collection of modules to the table of built-in modules.  The <em>newtab</em>
array must end with a sentinel entry which contains <em>NULL</em> for the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code>
field; failure to provide the sentinel value can result in a memory fault.
Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if insufficient memory could be allocated to
extend the internal table.  In the event of failure, no modules are added to the
internal table.  This should be called before <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="sys.html"
                        title="previous chapter">Operating System Utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="marshal.html"
                        title="next chapter">Data marshalling support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/import.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="Data marshalling support"
             >next</a> |</li>
        <li class="right" >
          <a href="sys.html" title="Operating System Utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\G0P�4�4html/c-api/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python/C API Reference Manual &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Introduction" href="intro.html" />
    <link rel="prev" title="5. Embedding Python in Another Application" href="../extending/embedding.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="intro.html" title="Introduction"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../extending/embedding.html" title="5. Embedding Python in Another Application"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-c-api-reference-manual">
<span id="c-api-index"></span><h1>Python/C API Reference Manual<a class="headerlink" href="#python-c-api-reference-manual" title="Permalink to this headline">¶</a></h1>
<p>This manual documents the API used by C and C++ programmers who want to write
extension modules or embed Python.  It is a companion to <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a>,
which describes the general principles of extension writing but does not
document the API functions in detail.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro.html">Introduction</a><ul>
<li class="toctree-l2"><a class="reference internal" href="intro.html#include-files">Include Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="intro.html#objects-types-and-reference-counts">Objects, Types and Reference Counts</a></li>
<li class="toctree-l2"><a class="reference internal" href="intro.html#exceptions">Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="intro.html#embedding-python">Embedding Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="intro.html#debugging-builds">Debugging Builds</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="veryhigh.html">The Very High Level Layer</a></li>
<li class="toctree-l1"><a class="reference internal" href="refcounting.html">Reference Counting</a></li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">Exception Handling</a><ul>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#unicode-exception-objects">Unicode Exception Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#recursion-control">Recursion Control</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#standard-exceptions">Standard Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#standard-warning-categories">Standard Warning Categories</a></li>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#string-exceptions">String Exceptions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="utilities.html">Utilities</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sys.html">Operating System Utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="sys.html#system-functions">System Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="sys.html#process-control">Process Control</a></li>
<li class="toctree-l2"><a class="reference internal" href="import.html">Importing Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="marshal.html">Data marshalling support</a></li>
<li class="toctree-l2"><a class="reference internal" href="arg.html">Parsing arguments and building values</a></li>
<li class="toctree-l2"><a class="reference internal" href="conversion.html">String conversion and formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="reflection.html">Reflection</a></li>
<li class="toctree-l2"><a class="reference internal" href="codec.html">Codec registry and support functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="abstract.html">Abstract Objects Layer</a><ul>
<li class="toctree-l2"><a class="reference internal" href="object.html">Object Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="number.html">Number Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="sequence.html">Sequence Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="mapping.html">Mapping Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="iter.html">Iterator Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="objbuffer.html">Old Buffer Protocol</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="concrete.html">Concrete Objects Layer</a><ul>
<li class="toctree-l2"><a class="reference internal" href="concrete.html#fundamental-objects">Fundamental Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="concrete.html#numeric-objects">Numeric Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="concrete.html#sequence-objects">Sequence Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="concrete.html#mapping-objects">Mapping Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="concrete.html#other-objects">Other Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="init.html">Initialization, Finalization, and Threads</a><ul>
<li class="toctree-l2"><a class="reference internal" href="init.html#initializing-and-finalizing-the-interpreter">Initializing and finalizing the interpreter</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#process-wide-parameters">Process-wide parameters</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#thread-state-and-the-global-interpreter-lock">Thread State and the Global Interpreter Lock</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#sub-interpreter-support">Sub-interpreter support</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#asynchronous-notifications">Asynchronous Notifications</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#profiling-and-tracing">Profiling and Tracing</a></li>
<li class="toctree-l2"><a class="reference internal" href="init.html#advanced-debugger-support">Advanced Debugger Support</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="memory.html">Memory Management</a><ul>
<li class="toctree-l2"><a class="reference internal" href="memory.html#overview">Overview</a></li>
<li class="toctree-l2"><a class="reference internal" href="memory.html#memory-interface">Memory Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="memory.html#object-allocators">Object allocators</a></li>
<li class="toctree-l2"><a class="reference internal" href="memory.html#the-pymalloc-allocator">The pymalloc allocator</a></li>
<li class="toctree-l2"><a class="reference internal" href="memory.html#examples">Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="objimpl.html">Object Implementation Support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="allocation.html">Allocating Objects on the Heap</a></li>
<li class="toctree-l2"><a class="reference internal" href="structures.html">Common Object Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="typeobj.html">Type Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="typeobj.html#number-object-structures">Number Object Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="typeobj.html#mapping-object-structures">Mapping Object Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="typeobj.html#sequence-object-structures">Sequence Object Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="typeobj.html#buffer-object-structures">Buffer Object Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="gcsupport.html">Supporting Cyclic Garbage Collection</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../extending/embedding.html"
                        title="previous chapter">5. Embedding Python in Another Application</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="intro.html"
                        title="next chapter">Introduction</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="intro.html" title="Introduction"
             >next</a> |</li>
        <li class="right" >
          <a href="../extending/embedding.html" title="5. Embedding Python in Another Application"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��n-�-�html/c-api/init.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Initialization, Finalization, and Threads &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Memory Management" href="memory.html" />
    <link rel="prev" title="Code Objects" href="code.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/init.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="memory.html" title="Memory Management"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="code.html" title="Code Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="initialization-finalization-and-threads">
<span id="initialization"></span><h1>Initialization, Finalization, and Threads<a class="headerlink" href="#initialization-finalization-and-threads" title="Permalink to this headline">¶</a></h1>
<div class="section" id="initializing-and-finalizing-the-interpreter">
<h2>Initializing and finalizing the interpreter<a class="headerlink" href="#initializing-and-finalizing-the-interpreter" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.Py_Initialize">
void <code class="descname">Py_Initialize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_Initialize" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Initialize the Python interpreter.  In an application embedding  Python, this
should be called before using any other Python/C API functions; with the
exception of <a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a>, <a class="reference internal" href="#c.Py_SetPythonHome" title="Py_SetPythonHome"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetPythonHome()</span></code></a>, <a class="reference internal" href="#c.PyEval_InitThreads" title="PyEval_InitThreads"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_InitThreads()</span></code></a>,
<a class="reference internal" href="#c.PyEval_ReleaseLock" title="PyEval_ReleaseLock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_ReleaseLock()</span></code></a>, and <a class="reference internal" href="#c.PyEval_AcquireLock" title="PyEval_AcquireLock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_AcquireLock()</span></code></a>. This initializes
the table of loaded modules (<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>), and creates the fundamental
modules <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a>, <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> and <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>.  It also initializes
the module search path (<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>). It does not set <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>; use
<a class="reference internal" href="#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a> for that.  This is a no-op when called for a second time
(without calling <a class="reference internal" href="#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> first).  There is no return value; it is a
fatal error if the initialization fails.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_InitializeEx">
void <code class="descname">Py_InitializeEx</code><span class="sig-paren">(</span>int<em>&nbsp;initsigs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_InitializeEx" title="Permalink to this definition">¶</a></dt>
<dd><p>This function works like <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> if <em>initsigs</em> is <code class="docutils literal notranslate"><span class="pre">1</span></code>. If
<em>initsigs</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, it skips initialization registration of signal handlers, which
might be useful when Python is embedded.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.Py_IsInitialized">
int <code class="descname">Py_IsInitialized</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_IsInitialized" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true (nonzero) when the Python interpreter has been initialized, false
(zero) if not.  After <a class="reference internal" href="#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> is called, this returns false until
<a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> is called again.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_Finalize">
void <code class="descname">Py_Finalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_Finalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Undo all initializations made by <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> and subsequent use of
Python/C API functions, and destroy all sub-interpreters (see
<a class="reference internal" href="#c.Py_NewInterpreter" title="Py_NewInterpreter"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_NewInterpreter()</span></code></a> below) that were created and not yet destroyed since
the last call to <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.  Ideally, this frees all memory
allocated by the Python interpreter.  This is a no-op when called for a second
time (without calling <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> again first).  There is no return
value; errors during finalization are ignored.</p>
<p>This function is provided for a number of reasons.  An embedding application
might want to restart Python without having to restart the application itself.
An application that has loaded the Python interpreter from a dynamically
loadable library (or DLL) might want to free all memory allocated by Python
before unloading the DLL. During a hunt for memory leaks in an application a
developer might want to free all memory allocated by Python before exiting from
the application.</p>
<p><strong>Bugs and caveats:</strong> The destruction of modules and objects in modules is done
in random order; this may cause destructors (<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods) to fail
when they depend on other objects (even functions) or modules.  Dynamically
loaded extension modules loaded by Python are not unloaded.  Small amounts of
memory allocated by the Python interpreter may not be freed (if you find a leak,
please report it).  Memory tied up in circular references between objects is not
freed.  Some memory allocated by extension modules may not be freed.  Some
extensions may not work properly if their initialization routine is called more
than once; this can happen if an application calls <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> and
<a class="reference internal" href="#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> more than once.</p>
</dd></dl>

</div>
<div class="section" id="process-wide-parameters">
<h2>Process-wide parameters<a class="headerlink" href="#process-wide-parameters" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.Py_SetProgramName">
void <code class="descname">Py_SetProgramName</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_SetProgramName" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This function should be called before <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> is called for
the first time, if it is called at all.  It tells the interpreter the value
of the <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code> argument to the <code class="xref c c-func docutils literal notranslate"><span class="pre">main()</span></code> function of the program.
This is used by <a class="reference internal" href="#c.Py_GetPath" title="Py_GetPath"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetPath()</span></code></a> and some other functions below to find
the Python run-time libraries relative to the interpreter executable.  The
default value is <code class="docutils literal notranslate"><span class="pre">'python'</span></code>.  The argument should point to a
zero-terminated character string in static storage whose contents will not
change for the duration of the program’s execution.  No code in the Python
interpreter will change the contents of this storage.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetProgramName">
char* <code class="descname">Py_GetProgramName</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetProgramName" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Return the program name set with <a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a>, or the default.
The returned string points into static storage; the caller should not modify its
value.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetPrefix">
char* <code class="descname">Py_GetPrefix</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetPrefix" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>prefix</em> for installed platform-independent files. This is derived
through a number of complicated rules from the program name set with
<a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a> and some environment variables; for example, if the
program name is <code class="docutils literal notranslate"><span class="pre">'/usr/local/bin/python'</span></code>, the prefix is <code class="docutils literal notranslate"><span class="pre">'/usr/local'</span></code>. The
returned string points into static storage; the caller should not modify its
value.  This corresponds to the <strong class="makevar">prefix</strong> variable in the top-level
<code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> and the <code class="docutils literal notranslate"><span class="pre">--prefix</span></code> argument to the <strong class="program">configure</strong>
script at build time.  The value is available to Python code as <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code>.
It is only useful on Unix.  See also the next function.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetExecPrefix">
char* <code class="descname">Py_GetExecPrefix</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetExecPrefix" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>exec-prefix</em> for installed platform-<em>dependent</em> files.  This is
derived through a number of complicated rules from the program name set with
<a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a> and some environment variables; for example, if the
program name is <code class="docutils literal notranslate"><span class="pre">'/usr/local/bin/python'</span></code>, the exec-prefix is
<code class="docutils literal notranslate"><span class="pre">'/usr/local'</span></code>.  The returned string points into static storage; the caller
should not modify its value.  This corresponds to the <strong class="makevar">exec_prefix</strong>
variable in the top-level <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> and the <code class="docutils literal notranslate"><span class="pre">--exec-prefix</span></code>
argument to the <strong class="program">configure</strong> script at build  time.  The value is
available to Python code as <code class="docutils literal notranslate"><span class="pre">sys.exec_prefix</span></code>.  It is only useful on Unix.</p>
<p>Background: The exec-prefix differs from the prefix when platform dependent
files (such as executables and shared libraries) are installed in a different
directory tree.  In a typical installation, platform dependent files may be
installed in the <code class="file docutils literal notranslate"><span class="pre">/usr/local/plat</span></code> subtree while platform independent may
be installed in <code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code>.</p>
<p>Generally speaking, a platform is a combination of hardware and software
families, e.g.  Sparc machines running the Solaris 2.x operating system are
considered the same platform, but Intel machines running Solaris 2.x are another
platform, and Intel machines running Linux are yet another platform.  Different
major revisions of the same operating system generally also form different
platforms.  Non-Unix operating systems are a different story; the installation
strategies on those systems are so different that the prefix and exec-prefix are
meaningless, and set to the empty string. Note that compiled Python bytecode
files are platform independent (but not independent from the Python version by
which they were compiled!).</p>
<p>System administrators will know how to configure the <strong class="program">mount</strong> or
<strong class="program">automount</strong> programs to share <code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code> between platforms
while having <code class="file docutils literal notranslate"><span class="pre">/usr/local/plat</span></code> be a different filesystem for each
platform.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetProgramFullPath">
char* <code class="descname">Py_GetProgramFullPath</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetProgramFullPath" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Return the full program name of the Python executable; this is  computed as a
side-effect of deriving the default module search path  from the program name
(set by <a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a> above). The returned string points into
static storage; the caller should not modify its value.  The value is available
to Python code as <code class="docutils literal notranslate"><span class="pre">sys.executable</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetPath">
char* <code class="descname">Py_GetPath</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetPath" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Return the default module search path; this is computed from the program name
(set by <a class="reference internal" href="#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a> above) and some environment variables.
The returned string consists of a series of directory names separated by a
platform dependent delimiter character.  The delimiter character is <code class="docutils literal notranslate"><span class="pre">':'</span></code>
on Unix and Mac OS X, <code class="docutils literal notranslate"><span class="pre">';'</span></code> on Windows.  The returned string points into
static storage; the caller should not modify its value.  The list
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is initialized with this value on interpreter startup; it
can be (and usually is) modified later to change the search path for loading
modules.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetVersion">
const char* <code class="descname">Py_GetVersion</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetVersion" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the version of this Python interpreter.  This is a string that looks
something like</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="s">&quot;1.5 (#67, Dec 31 1997, 22:34:28) [GCC 2.7.2.2]&quot;</span>
</pre></div>
</div>
<p id="index-5">The first word (up to the first space character) is the current Python version;
the first three characters are the major and minor version separated by a
period.  The returned string points into static storage; the caller should not
modify its value.  The value is available to Python code as <code class="docutils literal notranslate"><span class="pre">sys.version</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetPlatform">
const char* <code class="descname">Py_GetPlatform</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetPlatform" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">Return the platform identifier for the current platform.  On Unix, this is
formed from the “official” name of the operating system, converted to lower
case, followed by the major revision number; e.g., for Solaris 2.x, which is
also known as SunOS 5.x, the value is <code class="docutils literal notranslate"><span class="pre">'sunos5'</span></code>.  On Mac OS X, it is
<code class="docutils literal notranslate"><span class="pre">'darwin'</span></code>.  On Windows, it is <code class="docutils literal notranslate"><span class="pre">'win'</span></code>.  The returned string points into
static storage; the caller should not modify its value.  The value is available
to Python code as <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetCopyright">
const char* <code class="descname">Py_GetCopyright</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetCopyright" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the official copyright string for the current Python version, for example</p>
<p><code class="docutils literal notranslate"><span class="pre">'Copyright</span> <span class="pre">1991-1995</span> <span class="pre">Stichting</span> <span class="pre">Mathematisch</span> <span class="pre">Centrum,</span> <span class="pre">Amsterdam'</span></code></p>
<p id="index-7">The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as <code class="docutils literal notranslate"><span class="pre">sys.copyright</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetCompiler">
const char* <code class="descname">Py_GetCompiler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetCompiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an indication of the compiler used to build the current Python version,
in square brackets, for example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="s">&quot;[GCC 2.7.2.2]&quot;</span>
</pre></div>
</div>
<p id="index-8">The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as part of the variable
<code class="docutils literal notranslate"><span class="pre">sys.version</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetBuildInfo">
const char* <code class="descname">Py_GetBuildInfo</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetBuildInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return information about the sequence number and build date and time  of the
current Python interpreter instance, for example</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="s">&quot;#67, Aug  1 1997, 22:34:28&quot;</span>
</pre></div>
</div>
<p id="index-9">The returned string points into static storage; the caller should not modify its
value.  The value is available to Python code as part of the variable
<code class="docutils literal notranslate"><span class="pre">sys.version</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_SetArgvEx">
void <code class="descname">PySys_SetArgvEx</code><span class="sig-paren">(</span>int<em>&nbsp;argc</em>, char<em>&nbsp;**argv</em>, int<em>&nbsp;updatepath</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_SetArgvEx" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-10">Set <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> based on <em>argc</em> and <em>argv</em>.  These parameters are
similar to those passed to the program’s <code class="xref c c-func docutils literal notranslate"><span class="pre">main()</span></code> function with the
difference that the first entry should refer to the script file to be
executed rather than the executable hosting the Python interpreter.  If there
isn’t a script that will be run, the first entry in <em>argv</em> can be an empty
string.  If this function fails to initialize <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a>, a fatal
condition is signalled using <a class="reference internal" href="sys.html#c.Py_FatalError" title="Py_FatalError"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_FatalError()</span></code></a>.</p>
<p>If <em>updatepath</em> is zero, this is all the function does.  If <em>updatepath</em>
is non-zero, the function also modifies <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> according to the
following algorithm:</p>
<ul class="simple">
<li>If the name of an existing script is passed in <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code>, the absolute
path of the directory where the script is located is prepended to
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</li>
<li>Otherwise (that is, if <em>argc</em> is 0 or <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code> doesn’t point
to an existing file name), an empty string is prepended to
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, which is the same as prepending the current working
directory (<code class="docutils literal notranslate"><span class="pre">&quot;.&quot;</span></code>).</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>It is recommended that applications embedding the Python interpreter
for purposes other than executing a single script pass <code class="docutils literal notranslate"><span class="pre">0</span></code> as <em>updatepath</em>,
and update <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> themselves if desired.
See <a class="reference external" href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983">CVE-2008-5983</a>.</p>
<p>On versions before 2.6.6, you can achieve the same effect by manually
popping the first <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> element after having called
<a class="reference internal" href="#c.PySys_SetArgv" title="PySys_SetArgv"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code></a>, for example using:</p>
<div class="last highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyRun_SimpleString</span><span class="p">(</span><span class="s">&quot;import sys; sys.path.pop(0)</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySys_SetArgv">
void <code class="descname">PySys_SetArgv</code><span class="sig-paren">(</span>int<em>&nbsp;argc</em>, char<em>&nbsp;**argv</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_SetArgv" title="Permalink to this definition">¶</a></dt>
<dd><p>This function works like <a class="reference internal" href="#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a> with <em>updatepath</em> set to <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_SetPythonHome">
void <code class="descname">Py_SetPythonHome</code><span class="sig-paren">(</span>char<em>&nbsp;*home</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_SetPythonHome" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the default “home” directory, that is, the location of the standard
Python libraries.  See <span class="target" id="index-11"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> for the meaning of the
argument string.</p>
<p>The argument should point to a zero-terminated character string in static
storage whose contents will not change for the duration of the program’s
execution.  No code in the Python interpreter will change the contents of
this storage.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_GetPythonHome">
char* <code class="descname">Py_GetPythonHome</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_GetPythonHome" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the default “home”, that is, the value set by a previous call to
<a class="reference internal" href="#c.Py_SetPythonHome" title="Py_SetPythonHome"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetPythonHome()</span></code></a>, or the value of the <span class="target" id="index-12"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a>
environment variable if it is set.</p>
</dd></dl>

</div>
<div class="section" id="thread-state-and-the-global-interpreter-lock">
<span id="threads"></span><h2>Thread State and the Global Interpreter Lock<a class="headerlink" href="#thread-state-and-the-global-interpreter-lock" title="Permalink to this headline">¶</a></h2>
<p id="index-13">The Python interpreter is not fully thread-safe.  In order to support
multi-threaded Python programs, there’s a global lock, called the <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global
interpreter lock</span></a> or <a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a>, that must be held by the current thread before
it can safely access Python objects. Without the lock, even the simplest
operations could cause problems in a multi-threaded program: for example, when
two threads simultaneously increment the reference count of the same object, the
reference count could end up being incremented only once instead of twice.</p>
<p id="index-14">Therefore, the rule exists that only the thread that has acquired the
<a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a> may operate on Python objects or call Python/C API functions.
In order to emulate concurrency of execution, the interpreter regularly
tries to switch threads (see <a class="reference internal" href="../library/sys.html#sys.setcheckinterval" title="sys.setcheckinterval"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setcheckinterval()</span></code></a>).  The lock is also
released around potentially blocking I/O operations like reading or writing
a file, so that other Python threads can run in the meantime.</p>
<p id="index-15">The Python interpreter keeps some thread-specific bookkeeping information
inside a data structure called <a class="reference internal" href="#c.PyThreadState" title="PyThreadState"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyThreadState</span></code></a>.  There’s also one
global variable pointing to the current <a class="reference internal" href="#c.PyThreadState" title="PyThreadState"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyThreadState</span></code></a>: it can
be retrieved using <a class="reference internal" href="#c.PyThreadState_Get" title="PyThreadState_Get"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyThreadState_Get()</span></code></a>.</p>
<div class="section" id="releasing-the-gil-from-extension-code">
<h3>Releasing the GIL from extension code<a class="headerlink" href="#releasing-the-gil-from-extension-code" title="Permalink to this headline">¶</a></h3>
<p>Most extension code manipulating the <a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a> has the following simple
structure:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Save</span> <span class="n">the</span> <span class="kr">thread</span> <span class="n">state</span> <span class="n">in</span> <span class="n">a</span> <span class="n">local</span> <span class="n">variable</span><span class="p">.</span>
<span class="n">Release</span> <span class="n">the</span> <span class="n">global</span> <span class="n">interpreter</span> <span class="n">lock</span><span class="p">.</span>
<span class="p">...</span> <span class="n">Do</span> <span class="n">some</span> <span class="n">blocking</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">operation</span> <span class="p">...</span>
<span class="n">Reacquire</span> <span class="n">the</span> <span class="n">global</span> <span class="n">interpreter</span> <span class="n">lock</span><span class="p">.</span>
<span class="n">Restore</span> <span class="n">the</span> <span class="kr">thread</span> <span class="n">state</span> <span class="n">from</span> <span class="n">the</span> <span class="n">local</span> <span class="n">variable</span><span class="p">.</span>
</pre></div>
</div>
<p>This is so common that a pair of macros exists to simplify it:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_BEGIN_ALLOW_THREADS</span>
<span class="p">...</span> <span class="n">Do</span> <span class="n">some</span> <span class="n">blocking</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">operation</span> <span class="p">...</span>
<span class="n">Py_END_ALLOW_THREADS</span>
</pre></div>
</div>
<p id="index-16">The <a class="reference internal" href="#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a> macro opens a new block and declares a
hidden local variable; the <a class="reference internal" href="#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a> macro closes the
block.  These two macros are still available when Python is compiled without
thread support (they simply have an empty expansion).</p>
<p>When thread support is enabled, the block above expands to the following code:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyThreadState</span> <span class="o">*</span><span class="n">_save</span><span class="p">;</span>

<span class="n">_save</span> <span class="o">=</span> <span class="n">PyEval_SaveThread</span><span class="p">();</span>
<span class="p">...</span><span class="n">Do</span> <span class="n">some</span> <span class="n">blocking</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">operation</span><span class="p">...</span>
<span class="n">PyEval_RestoreThread</span><span class="p">(</span><span class="n">_save</span><span class="p">);</span>
</pre></div>
</div>
<p id="index-17">Here is how these functions work: the global interpreter lock is used to protect the pointer to the
current thread state.  When releasing the lock and saving the thread state,
the current thread state pointer must be retrieved before the lock is released
(since another thread could immediately acquire the lock and store its own thread
state in the global variable). Conversely, when acquiring the lock and restoring
the thread state, the lock must be acquired before storing the thread state
pointer.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Calling system I/O functions is the most common use case for releasing
the GIL, but it can also be useful before calling long-running computations
which don’t need access to Python objects, such as compression or
cryptographic functions operating over memory buffers.  For example, the
standard <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> and <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> modules release the GIL when
compressing or hashing data.</p>
</div>
</div>
<div class="section" id="non-python-created-threads">
<span id="gilstate"></span><h3>Non-Python created threads<a class="headerlink" href="#non-python-created-threads" title="Permalink to this headline">¶</a></h3>
<p>When threads are created using the dedicated Python APIs (such as the
<a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module), a thread state is automatically associated to them
and the code showed above is therefore correct.  However, when threads are
created from C (for example by a third-party library with its own thread
management), they don’t hold the GIL, nor is there a thread state structure
for them.</p>
<p>If you need to call Python code from these threads (often this will be part
of a callback API provided by the aforementioned third-party library),
you must first register these threads with the interpreter by
creating a thread state data structure, then acquiring the GIL, and finally
storing their thread state pointer, before you can start using the Python/C
API.  When you are done, you should reset the thread state pointer, release
the GIL, and finally free the thread state data structure.</p>
<p>The <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> and <a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a> functions do
all of the above automatically.  The typical idiom for calling into Python
from a C thread is:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyGILState_STATE</span> <span class="n">gstate</span><span class="p">;</span>
<span class="n">gstate</span> <span class="o">=</span> <span class="n">PyGILState_Ensure</span><span class="p">();</span>

<span class="cm">/* Perform Python actions here. */</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">CallSomeFunction</span><span class="p">();</span>
<span class="cm">/* evaluate result or handle exception */</span>

<span class="cm">/* Release the thread. No Python API allowed beyond this point. */</span>
<span class="n">PyGILState_Release</span><span class="p">(</span><span class="n">gstate</span><span class="p">);</span>
</pre></div>
</div>
<p>Note that the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_*()</span></code> functions assume there is only one global
interpreter (created automatically by <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>).  Python
supports the creation of additional interpreters (using
<a class="reference internal" href="#c.Py_NewInterpreter" title="Py_NewInterpreter"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_NewInterpreter()</span></code></a>), but mixing multiple interpreters and the
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_*()</span></code> API is unsupported.</p>
<p>Another important thing to note about threads is their behaviour in the face
of the C <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code> call. On most systems with <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code>, after a
process forks only the thread that issued the fork will exist. That also
means any locks held by other threads will never be released. Python solves
this for <a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a> by acquiring the locks it uses internally before
the fork, and releasing them afterwards. In addition, it resets any
<a class="reference internal" href="../library/threading.html#lock-objects"><span class="std std-ref">Lock Objects</span></a> in the child. When extending or embedding Python, there
is no way to inform Python of additional (non-Python) locks that need to be
acquired before or reset after a fork. OS facilities such as
<code class="xref c c-func docutils literal notranslate"><span class="pre">pthread_atfork()</span></code> would need to be used to accomplish the same thing.
Additionally, when extending or embedding Python, calling <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code>
directly rather than through <a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a> (and returning to or calling
into Python) may result in a deadlock by one of Python’s internal locks
being held by a thread that is defunct after the fork.
<a class="reference internal" href="sys.html#c.PyOS_AfterFork" title="PyOS_AfterFork"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_AfterFork()</span></code></a> tries to reset the necessary locks, but is not
always able to.</p>
</div>
<div class="section" id="high-level-api">
<h3>High-level API<a class="headerlink" href="#high-level-api" title="Permalink to this headline">¶</a></h3>
<p>These are the most commonly used types and functions when writing C extension
code, or when embedding the Python interpreter:</p>
<dl class="type">
<dt id="c.PyInterpreterState">
<code class="descname">PyInterpreterState</code><a class="headerlink" href="#c.PyInterpreterState" title="Permalink to this definition">¶</a></dt>
<dd><p>This data structure represents the state shared by a number of cooperating
threads.  Threads belonging to the same interpreter share their module
administration and a few other internal items. There are no public members in
this structure.</p>
<p>Threads belonging to different interpreters initially share nothing, except
process state like available memory, open file descriptors and such.  The global
interpreter lock is also shared by all threads, regardless of to which
interpreter they belong.</p>
</dd></dl>

<dl class="type">
<dt id="c.PyThreadState">
<code class="descname">PyThreadState</code><a class="headerlink" href="#c.PyThreadState" title="Permalink to this definition">¶</a></dt>
<dd><p>This data structure represents the state of a single thread.  The only public
data member is <a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyInterpreterState</span> <span class="pre">*</span></code></a><code class="xref py py-attr docutils literal notranslate"><span class="pre">interp</span></code>, which points to
this thread’s interpreter state.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_InitThreads">
void <code class="descname">PyEval_InitThreads</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_InitThreads" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-18">Initialize and acquire the global interpreter lock.  It should be called in the
main thread before creating a second thread or engaging in any other thread
operations such as <a class="reference internal" href="#c.PyEval_ReleaseLock" title="PyEval_ReleaseLock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_ReleaseLock()</span></code></a> or
<code class="docutils literal notranslate"><span class="pre">PyEval_ReleaseThread(tstate)</span></code>. It is not needed before calling
<a class="reference internal" href="#c.PyEval_SaveThread" title="PyEval_SaveThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SaveThread()</span></code></a> or <a class="reference internal" href="#c.PyEval_RestoreThread" title="PyEval_RestoreThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_RestoreThread()</span></code></a>.</p>
<p id="index-19">This is a no-op when called for a second time.  It is safe to call this function
before calling <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.</p>
<div class="admonition note" id="index-20">
<p class="first admonition-title">Note</p>
<p>When only the main thread exists, no GIL operations are needed. This is a
common situation (most Python programs do not use threads), and the lock
operations slow the interpreter down a bit. Therefore, the lock is not
created initially.  This situation is equivalent to having acquired the lock:
when there is only a single thread, all object accesses are safe.  Therefore,
when this function initializes the global interpreter lock, it also acquires
it.  Before the Python <code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> module creates a new thread, knowing
that either it has the lock or the lock hasn’t been created yet, it calls
<a class="reference internal" href="#c.PyEval_InitThreads" title="PyEval_InitThreads"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_InitThreads()</span></code></a>.  When this call returns, it is guaranteed that
the lock has been created and that the calling thread has acquired it.</p>
<p>It is <strong>not</strong> safe to call this function when it is unknown which thread (if
any) currently has the global interpreter lock.</p>
<p class="last">This function is not available when thread support is disabled at compile time.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_ThreadsInitialized">
int <code class="descname">PyEval_ThreadsInitialized</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_ThreadsInitialized" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a non-zero value if <a class="reference internal" href="#c.PyEval_InitThreads" title="PyEval_InitThreads"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_InitThreads()</span></code></a> has been called.  This
function can be called without holding the GIL, and therefore can be used to
avoid calls to the locking API when running single-threaded.  This function is
not available when thread support is disabled at compile time.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_SaveThread">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyEval_SaveThread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_SaveThread" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the global interpreter lock (if it has been created and thread
support is enabled) and reset the thread state to <em>NULL</em>, returning the
previous thread state (which is not <em>NULL</em>).  If the lock has been created,
the current thread must have acquired it.  (This function is available even
when thread support is disabled at compile time.)</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_RestoreThread">
void <code class="descname">PyEval_RestoreThread</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_RestoreThread" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the global interpreter lock (if it has been created and thread
support is enabled) and set the thread state to <em>tstate</em>, which must not be
<em>NULL</em>.  If the lock has been created, the current thread must not have
acquired it, otherwise deadlock ensues.  (This function is available even
when thread support is disabled at compile time.)</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_Get">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyThreadState_Get</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_Get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current thread state.  The global interpreter lock must be held.
When the current thread state is <em>NULL</em>, this issues a fatal error (so that
the caller needn’t check for <em>NULL</em>).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_Swap">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyThreadState_Swap</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_Swap" title="Permalink to this definition">¶</a></dt>
<dd><p>Swap the current thread state with the thread state given by the argument
<em>tstate</em>, which may be <em>NULL</em>.  The global interpreter lock must be held
and is not released.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_ReInitThreads">
void <code class="descname">PyEval_ReInitThreads</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_ReInitThreads" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is called from <a class="reference internal" href="sys.html#c.PyOS_AfterFork" title="PyOS_AfterFork"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_AfterFork()</span></code></a> to ensure that newly
created child processes don’t hold locks referring to threads which
are not running in the child process.</p>
</dd></dl>

<p>The following functions use thread-local storage, and are not compatible
with sub-interpreters:</p>
<dl class="function">
<dt id="c.PyGILState_Ensure">
PyGILState_STATE <code class="descname">PyGILState_Ensure</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyGILState_Ensure" title="Permalink to this definition">¶</a></dt>
<dd><p>Ensure that the current thread is ready to call the Python C API regardless
of the current state of Python, or of the global interpreter lock. This may
be called as many times as desired by a thread as long as each call is
matched with a call to <a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a>. In general, other
thread-related APIs may be used between <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> and
<a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a> calls as long as the thread state is restored to
its previous state before the Release().  For example, normal usage of the
<a class="reference internal" href="#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a> and <a class="reference internal" href="#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a> macros is
acceptable.</p>
<p>The return value is an opaque “handle” to the thread state when
<a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> was called, and must be passed to
<a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a> to ensure Python is left in the same state. Even
though recursive calls are allowed, these handles <em>cannot</em> be shared - each
unique call to <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> must save the handle for its call
to <a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a>.</p>
<p>When the function returns, the current thread will hold the GIL and be able
to call arbitrary Python code.  Failure is a fatal error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyGILState_Release">
void <code class="descname">PyGILState_Release</code><span class="sig-paren">(</span>PyGILState_STATE<span class="sig-paren">)</span><a class="headerlink" href="#c.PyGILState_Release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release any resources previously acquired.  After this call, Python’s state will
be the same as it was prior to the corresponding <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> call
(but generally this state will be unknown to the caller, hence the use of the
GILState API).</p>
<p>Every call to <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> must be matched by a call to
<a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a> on the same thread.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyGILState_GetThisThreadState">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyGILState_GetThisThreadState</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyGILState_GetThisThreadState" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the current thread state for this thread.  May return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> if no
GILState API has been used on the current thread.  Note that the main thread
always has such a thread-state, even if no auto-thread-state call has been
made on the main thread.  This is mainly a helper/diagnostic function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>The following macros are normally used without a trailing semicolon; look for
example usage in the Python source distribution.</p>
<dl class="macro">
<dt id="c.Py_BEGIN_ALLOW_THREADS">
<code class="descname">Py_BEGIN_ALLOW_THREADS</code><a class="headerlink" href="#c.Py_BEGIN_ALLOW_THREADS" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro expands to <code class="docutils literal notranslate"><span class="pre">{</span> <span class="pre">PyThreadState</span> <span class="pre">*_save;</span> <span class="pre">_save</span> <span class="pre">=</span> <span class="pre">PyEval_SaveThread();</span></code>.
Note that it contains an opening brace; it must be matched with a following
<a class="reference internal" href="#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a> macro.  See above for further discussion of this
macro.  It is a no-op when thread support is disabled at compile time.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_END_ALLOW_THREADS">
<code class="descname">Py_END_ALLOW_THREADS</code><a class="headerlink" href="#c.Py_END_ALLOW_THREADS" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro expands to <code class="docutils literal notranslate"><span class="pre">PyEval_RestoreThread(_save);</span> <span class="pre">}</span></code>. Note that it contains
a closing brace; it must be matched with an earlier
<a class="reference internal" href="#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a> macro.  See above for further discussion of
this macro.  It is a no-op when thread support is disabled at compile time.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_BLOCK_THREADS">
<code class="descname">Py_BLOCK_THREADS</code><a class="headerlink" href="#c.Py_BLOCK_THREADS" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro expands to <code class="docutils literal notranslate"><span class="pre">PyEval_RestoreThread(_save);</span></code>: it is equivalent to
<a class="reference internal" href="#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a> without the closing brace.  It is a no-op when
thread support is disabled at compile time.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_UNBLOCK_THREADS">
<code class="descname">Py_UNBLOCK_THREADS</code><a class="headerlink" href="#c.Py_UNBLOCK_THREADS" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro expands to <code class="docutils literal notranslate"><span class="pre">_save</span> <span class="pre">=</span> <span class="pre">PyEval_SaveThread();</span></code>: it is equivalent to
<a class="reference internal" href="#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a> without the opening brace and variable
declaration.  It is a no-op when thread support is disabled at compile time.</p>
</dd></dl>

</div>
<div class="section" id="low-level-api">
<h3>Low-level API<a class="headerlink" href="#low-level-api" title="Permalink to this headline">¶</a></h3>
<p>All of the following functions are only available when thread support is enabled
at compile time, and must be called only when the global interpreter lock has
been created.</p>
<dl class="function">
<dt id="c.PyInterpreterState_New">
<a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a>* <code class="descname">PyInterpreterState_New</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_New" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new interpreter state object.  The global interpreter lock need not
be held, but may be held if it is necessary to serialize calls to this
function.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInterpreterState_Clear">
void <code class="descname">PyInterpreterState_Clear</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a><em>&nbsp;*interp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_Clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset all information in an interpreter state object.  The global interpreter
lock must be held.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInterpreterState_Delete">
void <code class="descname">PyInterpreterState_Delete</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a><em>&nbsp;*interp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_Delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Destroy an interpreter state object.  The global interpreter lock need not be
held.  The interpreter state must have been reset with a previous call to
<a class="reference internal" href="#c.PyInterpreterState_Clear" title="PyInterpreterState_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInterpreterState_Clear()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_New">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyThreadState_New</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a><em>&nbsp;*interp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_New" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new thread state object belonging to the given interpreter object.
The global interpreter lock need not be held, but may be held if it is
necessary to serialize calls to this function.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_Clear">
void <code class="descname">PyThreadState_Clear</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_Clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset all information in a thread state object.  The global interpreter lock
must be held.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_Delete">
void <code class="descname">PyThreadState_Delete</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_Delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Destroy a thread state object.  The global interpreter lock need not be held.
The thread state must have been reset with a previous call to
<a class="reference internal" href="#c.PyThreadState_Clear" title="PyThreadState_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyThreadState_Clear()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_GetDict">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyThreadState_GetDict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_GetDict" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return a dictionary in which extensions can store thread-specific state
information.  Each extension should use a unique key to use to store state in
the dictionary.  It is okay to call this function when no current thread state
is available. If this function returns <em>NULL</em>, no exception has been raised and
the caller should assume no current thread state is available.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Previously this could only be called when a current thread is active, and <em>NULL</em>
meant that an exception was raised.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_SetAsyncExc">
int <code class="descname">PyThreadState_SetAsyncExc</code><span class="sig-paren">(</span>long<em>&nbsp;id</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_SetAsyncExc" title="Permalink to this definition">¶</a></dt>
<dd><p>Asynchronously raise an exception in a thread. The <em>id</em> argument is the thread
id of the target thread; <em>exc</em> is the exception object to be raised. This
function does not steal any references to <em>exc</em>. To prevent naive misuse, you
must write your own C extension to call this.  Must be called with the GIL held.
Returns the number of thread states modified; this is normally one, but will be
zero if the thread id isn’t found.  If <em>exc</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">NULL</span></code>, the pending
exception (if any) for the thread is cleared. This raises no exceptions.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_AcquireThread">
void <code class="descname">PyEval_AcquireThread</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_AcquireThread" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the global interpreter lock and set the current thread state to
<em>tstate</em>, which should not be <em>NULL</em>.  The lock must have been created earlier.
If this thread already has the lock, deadlock ensues.</p>
<p><a class="reference internal" href="#c.PyEval_RestoreThread" title="PyEval_RestoreThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_RestoreThread()</span></code></a> is a higher-level function which is always
available (even when thread support isn’t enabled or when threads have
not been initialized).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_ReleaseThread">
void <code class="descname">PyEval_ReleaseThread</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_ReleaseThread" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the current thread state to <em>NULL</em> and release the global interpreter
lock.  The lock must have been created earlier and must be held by the current
thread.  The <em>tstate</em> argument, which must not be <em>NULL</em>, is only used to check
that it represents the current thread state — if it isn’t, a fatal error is
reported.</p>
<p><a class="reference internal" href="#c.PyEval_SaveThread" title="PyEval_SaveThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SaveThread()</span></code></a> is a higher-level function which is always
available (even when thread support isn’t enabled or when threads have
not been initialized).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_AcquireLock">
void <code class="descname">PyEval_AcquireLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_AcquireLock" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the global interpreter lock.  The lock must have been created earlier.
If this thread already has the lock, a deadlock ensues.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This function does not change the current thread state.  Please use
<a class="reference internal" href="#c.PyEval_RestoreThread" title="PyEval_RestoreThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_RestoreThread()</span></code></a> or <a class="reference internal" href="#c.PyEval_AcquireThread" title="PyEval_AcquireThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_AcquireThread()</span></code></a>
instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_ReleaseLock">
void <code class="descname">PyEval_ReleaseLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_ReleaseLock" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the global interpreter lock.  The lock must have been created earlier.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This function does not change the current thread state.  Please use
<a class="reference internal" href="#c.PyEval_SaveThread" title="PyEval_SaveThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SaveThread()</span></code></a> or <a class="reference internal" href="#c.PyEval_ReleaseThread" title="PyEval_ReleaseThread"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_ReleaseThread()</span></code></a>
instead.</p>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="sub-interpreter-support">
<h2>Sub-interpreter support<a class="headerlink" href="#sub-interpreter-support" title="Permalink to this headline">¶</a></h2>
<p>While in most uses, you will only embed a single Python interpreter, there
are cases where you need to create several independent interpreters in the
same process and perhaps even in the same thread.  Sub-interpreters allow
you to do that.  You can switch between sub-interpreters using the
<a class="reference internal" href="#c.PyThreadState_Swap" title="PyThreadState_Swap"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyThreadState_Swap()</span></code></a> function.  You can create and destroy them
using the following functions:</p>
<dl class="function">
<dt id="c.Py_NewInterpreter">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">Py_NewInterpreter</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_NewInterpreter" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-21">Create a new sub-interpreter.  This is an (almost) totally separate environment
for the execution of Python code.  In particular, the new interpreter has
separate, independent versions of all imported modules, including the
fundamental modules <code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code>, <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> and <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>.  The
table of loaded modules (<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>) and the module search path
(<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>) are also separate.  The new environment has no <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>
variable.  It has new standard I/O stream file objects <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>,
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> (however these refer to the same underlying
file descriptors).</p>
<p>The return value points to the first thread state created in the new
sub-interpreter.  This thread state is made in the current thread state.
Note that no actual thread is created; see the discussion of thread states
below.  If creation of the new interpreter is unsuccessful, <em>NULL</em> is
returned; no exception is set since the exception state is stored in the
current thread state and there may not be a current thread state.  (Like all
other Python/C API functions, the global interpreter lock must be held before
calling this function and is still held when it returns; however, unlike most
other Python/C API functions, there needn’t be a current thread state on
entry.)</p>
<p id="index-22">Extension modules are shared between (sub-)interpreters as follows: the first
time a particular extension is imported, it is initialized normally, and a
(shallow) copy of its module’s dictionary is squirreled away.  When the same
extension is imported by another (sub-)interpreter, a new module is initialized
and filled with the contents of this copy; the extension’s <code class="docutils literal notranslate"><span class="pre">init</span></code> function is
not called.  Note that this is different from what happens when an extension is
imported after the interpreter has been completely re-initialized by calling
<a class="reference internal" href="#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> and <a class="reference internal" href="#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>; in that case, the extension’s
<code class="docutils literal notranslate"><span class="pre">initmodule</span></code> function <em>is</em> called again.</p>
<span class="target" id="index-23"></span></dd></dl>

<dl class="function">
<dt id="c.Py_EndInterpreter">
void <code class="descname">Py_EndInterpreter</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_EndInterpreter" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-24">Destroy the (sub-)interpreter represented by the given thread state. The given
thread state must be the current thread state.  See the discussion of thread
states below.  When the call returns, the current thread state is <em>NULL</em>.  All
thread states associated with this interpreter are destroyed.  (The global
interpreter lock must be held before calling this function and is still held
when it returns.)  <a class="reference internal" href="#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> will destroy all sub-interpreters that
haven’t been explicitly destroyed at that point.</p>
</dd></dl>

<div class="section" id="bugs-and-caveats">
<h3>Bugs and caveats<a class="headerlink" href="#bugs-and-caveats" title="Permalink to this headline">¶</a></h3>
<p>Because sub-interpreters (and the main interpreter) are part of the same
process, the insulation between them isn’t perfect — for example, using
low-level file operations like  <a class="reference internal" href="../library/os.html#os.close" title="os.close"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.close()</span></code></a> they can
(accidentally or maliciously) affect each other’s open files.  Because of the
way extensions are shared between (sub-)interpreters, some extensions may not
work properly; this is especially likely when the extension makes use of
(static) global variables, or when the extension manipulates its module’s
dictionary after its initialization.  It is possible to insert objects created
in one sub-interpreter into a namespace of another sub-interpreter; this should
be done with great care to avoid sharing user-defined functions, methods,
instances or classes between sub-interpreters, since import operations executed
by such objects may affect the wrong (sub-)interpreter’s dictionary of loaded
modules.</p>
<p>Also note that combining this functionality with <code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_*()</span></code> APIs
is delicate, because these APIs assume a bijection between Python thread states
and OS-level threads, an assumption broken by the presence of sub-interpreters.
It is highly recommended that you don’t switch sub-interpreters between a pair
of matching <a class="reference internal" href="#c.PyGILState_Ensure" title="PyGILState_Ensure"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Ensure()</span></code></a> and <a class="reference internal" href="#c.PyGILState_Release" title="PyGILState_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyGILState_Release()</span></code></a> calls.
Furthermore, extensions (such as <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>) using these APIs to allow calling
of Python code from non-Python created threads will probably be broken when using
sub-interpreters.</p>
</div>
</div>
<div class="section" id="asynchronous-notifications">
<h2>Asynchronous Notifications<a class="headerlink" href="#asynchronous-notifications" title="Permalink to this headline">¶</a></h2>
<p>A mechanism is provided to make asynchronous notifications to the main
interpreter thread.  These notifications take the form of a function
pointer and a void pointer argument.</p>
<dl class="function">
<dt id="c.Py_AddPendingCall">
int <code class="descname">Py_AddPendingCall</code><span class="sig-paren">(</span>int (<em>*func</em>)(void *), void<em>&nbsp;*arg</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_AddPendingCall" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-25">Schedule a function to be called from the main interpreter thread.  On
success, <code class="docutils literal notranslate"><span class="pre">0</span></code> is returned and <em>func</em> is queued for being called in the
main thread.  On failure, <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned without setting any exception.</p>
<p>When successfully queued, <em>func</em> will be <em>eventually</em> called from the
main interpreter thread with the argument <em>arg</em>.  It will be called
asynchronously with respect to normally running Python code, but with
both these conditions met:</p>
<ul class="simple">
<li>on a <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> boundary;</li>
<li>with the main thread holding the <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a>
(<em>func</em> can therefore use the full C API).</li>
</ul>
<p><em>func</em> must return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure with an exception
set.  <em>func</em> won’t be interrupted to perform another asynchronous
notification recursively, but it can still be interrupted to switch
threads if the global interpreter lock is released.</p>
<p>This function doesn’t need a current thread state to run, and it doesn’t
need the global interpreter lock.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This is a low-level function, only useful for very special cases.
There is no guarantee that <em>func</em> will be called as quick as
possible.  If the main thread is busy executing a system call,
<em>func</em> won’t be called before the system call returns.  This
function is generally <strong>not</strong> suitable for calling Python code from
arbitrary C threads.  Instead, use the <a class="reference internal" href="#gilstate"><span class="std std-ref">PyGILState API</span></a>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="profiling-and-tracing">
<span id="profiling"></span><h2>Profiling and Tracing<a class="headerlink" href="#profiling-and-tracing" title="Permalink to this headline">¶</a></h2>
<p>The Python interpreter provides some low-level support for attaching profiling
and execution tracing facilities.  These are used for profiling, debugging, and
coverage analysis tools.</p>
<p>Starting with Python 2.2, the implementation of this facility was substantially
revised, and an interface from C was added.  This C interface allows the
profiling or tracing code to avoid the overhead of calling through Python-level
callable objects, making a direct C function call instead.  The essential
attributes of the facility have not changed; the interface allows trace
functions to be installed per-thread, and the basic events reported to the trace
function are the same as had been reported to the Python-level trace functions
in previous versions.</p>
<dl class="type">
<dt id="c.Py_tracefunc">
int <code class="descname">(*Py_tracefunc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, PyFrameObject<em>&nbsp;*frame</em>, int<em>&nbsp;what</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*arg</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_tracefunc" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of the trace function registered using <a class="reference internal" href="#c.PyEval_SetProfile" title="PyEval_SetProfile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetProfile()</span></code></a> and
<a class="reference internal" href="#c.PyEval_SetTrace" title="PyEval_SetTrace"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetTrace()</span></code></a>. The first parameter is the object passed to the
registration function as <em>obj</em>, <em>frame</em> is the frame object to which the event
pertains, <em>what</em> is one of the constants <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_CALL</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_EXCEPTION</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_LINE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_RETURN</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_CALL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_EXCEPTION</span></code>, or
<code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_RETURN</span></code>, and <em>arg</em> depends on the value of <em>what</em>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="44%" />
<col width="56%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value of <em>what</em></th>
<th class="head">Meaning of <em>arg</em></th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_CALL</span></code></td>
<td>Always <a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_EXCEPTION</span></code></td>
<td>Exception information as returned by
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_LINE</span></code></td>
<td>Always <a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_RETURN</span></code></td>
<td>Value being returned to the caller,
or <em>NULL</em> if caused by an exception.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_CALL</span></code></td>
<td>Function object being called.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_EXCEPTION</span></code></td>
<td>Function object being called.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_RETURN</span></code></td>
<td>Function object being called.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_CALL">
int <code class="descname">PyTrace_CALL</code><a class="headerlink" href="#c.PyTrace_CALL" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of the <em>what</em> parameter to a <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> function when a new
call to a function or method is being reported, or a new entry into a generator.
Note that the creation of the iterator for a generator function is not reported
as there is no control transfer to the Python bytecode in the corresponding
frame.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_EXCEPTION">
int <code class="descname">PyTrace_EXCEPTION</code><a class="headerlink" href="#c.PyTrace_EXCEPTION" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of the <em>what</em> parameter to a <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> function when an
exception has been raised.  The callback function is called with this value for
<em>what</em> when after any bytecode is processed after which the exception becomes
set within the frame being executed.  The effect of this is that as exception
propagation causes the Python stack to unwind, the callback is called upon
return to each frame as the exception propagates.  Only trace functions receives
these events; they are not needed by the profiler.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_LINE">
int <code class="descname">PyTrace_LINE</code><a class="headerlink" href="#c.PyTrace_LINE" title="Permalink to this definition">¶</a></dt>
<dd><p>The value passed as the <em>what</em> parameter to a trace function (but not a
profiling function) when a line-number event is being reported.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_RETURN">
int <code class="descname">PyTrace_RETURN</code><a class="headerlink" href="#c.PyTrace_RETURN" title="Permalink to this definition">¶</a></dt>
<dd><p>The value for the <em>what</em> parameter to <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> functions when a
call is about to return.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_C_CALL">
int <code class="descname">PyTrace_C_CALL</code><a class="headerlink" href="#c.PyTrace_C_CALL" title="Permalink to this definition">¶</a></dt>
<dd><p>The value for the <em>what</em> parameter to <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> functions when a C
function is about to be called.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_C_EXCEPTION">
int <code class="descname">PyTrace_C_EXCEPTION</code><a class="headerlink" href="#c.PyTrace_C_EXCEPTION" title="Permalink to this definition">¶</a></dt>
<dd><p>The value for the <em>what</em> parameter to <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> functions when a C
function has raised an exception.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTrace_C_RETURN">
int <code class="descname">PyTrace_C_RETURN</code><a class="headerlink" href="#c.PyTrace_C_RETURN" title="Permalink to this definition">¶</a></dt>
<dd><p>The value for the <em>what</em> parameter to <a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_tracefunc</span></code></a> functions when a C
function has returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_SetProfile">
void <code class="descname">PyEval_SetProfile</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc">Py_tracefunc</a><em>&nbsp;func</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_SetProfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the profiler function to <em>func</em>.  The <em>obj</em> parameter is passed to the
function as its first parameter, and may be any Python object, or <em>NULL</em>.  If
the profile function needs to maintain state, using a different value for <em>obj</em>
for each thread provides a convenient and thread-safe place to store it.  The
profile function is called for all monitored events except <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_LINE</span></code>
and <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_EXCEPTION</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_SetTrace">
void <code class="descname">PyEval_SetTrace</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_tracefunc" title="Py_tracefunc">Py_tracefunc</a><em>&nbsp;func</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_SetTrace" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the tracing function to <em>func</em>.  This is similar to
<a class="reference internal" href="#c.PyEval_SetProfile" title="PyEval_SetProfile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetProfile()</span></code></a>, except the tracing function does receive line-number
events and does not receive any event related to C function objects being called. Any
trace function registered using <a class="reference internal" href="#c.PyEval_SetTrace" title="PyEval_SetTrace"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetTrace()</span></code></a> will not receive
<code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_CALL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_EXCEPTION</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">PyTrace_C_RETURN</span></code>
as a value for the <em>what</em> parameter.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetCallStats">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_GetCallStats</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetCallStats" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple of function call counts.  There are constants defined for the
positions within the tuple:</p>
<table border="1" class="docutils">
<colgroup>
<col width="82%" />
<col width="18%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name</th>
<th class="head">Value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_ALL</span></code></td>
<td>0</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_FUNCTION</span></code></td>
<td>1</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_FAST_FUNCTION</span></code></td>
<td>2</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_FASTER_FUNCTION</span></code></td>
<td>3</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_METHOD</span></code></td>
<td>4</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_BOUND_METHOD</span></code></td>
<td>5</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_CFUNCTION</span></code></td>
<td>6</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_TYPE</span></code></td>
<td>7</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_GENERATOR</span></code></td>
<td>8</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_OTHER</span></code></td>
<td>9</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_POP</span></code></td>
<td>10</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_FAST_FUNCTION</span></code> means no argument tuple needs to be created.
<code class="xref py py-const docutils literal notranslate"><span class="pre">PCALL_FASTER_FUNCTION</span></code> means that the fast-path frame setup code is used.</p>
<p>If there is a method call where the call can be optimized by changing
the argument tuple and calling the function directly, it gets recorded
twice.</p>
<p>This function is only present if Python is compiled with <code class="xref py py-const docutils literal notranslate"><span class="pre">CALL_PROFILE</span></code>
defined.</p>
</dd></dl>

</div>
<div class="section" id="advanced-debugger-support">
<span id="advanced-debugging"></span><h2>Advanced Debugger Support<a class="headerlink" href="#advanced-debugger-support" title="Permalink to this headline">¶</a></h2>
<p>These functions are only intended to be used by advanced debugging tools.</p>
<dl class="function">
<dt id="c.PyInterpreterState_Head">
<a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a>* <code class="descname">PyInterpreterState_Head</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_Head" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the interpreter state object at the head of the list of all such objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInterpreterState_Next">
<a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a>* <code class="descname">PyInterpreterState_Next</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a><em>&nbsp;*interp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_Next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next interpreter state object after <em>interp</em> from the list of all
such objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInterpreterState_ThreadHead">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a> * <code class="descname">PyInterpreterState_ThreadHead</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState">PyInterpreterState</a><em>&nbsp;*interp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInterpreterState_ThreadHead" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the pointer to the first <a class="reference internal" href="#c.PyThreadState" title="PyThreadState"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyThreadState</span></code></a> object in the list of
threads associated with the interpreter <em>interp</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyThreadState_Next">
<a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a>* <code class="descname">PyThreadState_Next</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyThreadState" title="PyThreadState">PyThreadState</a><em>&nbsp;*tstate</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyThreadState_Next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next thread state object after <em>tstate</em> from the list of all such
objects belonging to the same <a class="reference internal" href="#c.PyInterpreterState" title="PyInterpreterState"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyInterpreterState</span></code></a> object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Initialization, Finalization, and Threads</a><ul>
<li><a class="reference internal" href="#initializing-and-finalizing-the-interpreter">Initializing and finalizing the interpreter</a></li>
<li><a class="reference internal" href="#process-wide-parameters">Process-wide parameters</a></li>
<li><a class="reference internal" href="#thread-state-and-the-global-interpreter-lock">Thread State and the Global Interpreter Lock</a><ul>
<li><a class="reference internal" href="#releasing-the-gil-from-extension-code">Releasing the GIL from extension code</a></li>
<li><a class="reference internal" href="#non-python-created-threads">Non-Python created threads</a></li>
<li><a class="reference internal" href="#high-level-api">High-level API</a></li>
<li><a class="reference internal" href="#low-level-api">Low-level API</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sub-interpreter-support">Sub-interpreter support</a><ul>
<li><a class="reference internal" href="#bugs-and-caveats">Bugs and caveats</a></li>
</ul>
</li>
<li><a class="reference internal" href="#asynchronous-notifications">Asynchronous Notifications</a></li>
<li><a class="reference internal" href="#profiling-and-tracing">Profiling and Tracing</a></li>
<li><a class="reference internal" href="#advanced-debugger-support">Advanced Debugger Support</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="code.html"
                        title="previous chapter">Code Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="memory.html"
                        title="next chapter">Memory Management</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/init.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="memory.html" title="Memory Management"
             >next</a> |</li>
        <li class="right" >
          <a href="code.html" title="Code Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\#*9l0P0Phtml/c-api/int.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Plain Integer Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Boolean Objects" href="bool.html" />
    <link rel="prev" title="The None Object" href="none.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/int.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bool.html" title="Boolean Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="none.html" title="The None Object"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="plain-integer-objects">
<span id="intobjects"></span><h1>Plain Integer Objects<a class="headerlink" href="#plain-integer-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyIntObject">
<code class="descname">PyIntObject</code><a class="headerlink" href="#c.PyIntObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python integer object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyInt_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyInt_Type</code><a class="headerlink" href="#c.PyInt_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python plain integer type.
This is the same object as <code class="docutils literal notranslate"><span class="pre">int</span></code> and <code class="docutils literal notranslate"><span class="pre">types.IntType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_Check">
int <code class="descname">PyInt_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>o</em> is of type <a class="reference internal" href="#c.PyInt_Type" title="PyInt_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyInt_Type</span></code></a> or a subtype of
<a class="reference internal" href="#c.PyInt_Type" title="PyInt_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyInt_Type</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_CheckExact">
int <code class="descname">PyInt_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>o</em> is of type <a class="reference internal" href="#c.PyInt_Type" title="PyInt_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyInt_Type</span></code></a>, but not a subtype of
<a class="reference internal" href="#c.PyInt_Type" title="PyInt_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyInt_Type</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInt_FromString</code><span class="sig-paren">(</span>char<em>&nbsp;*str</em>, char<em>&nbsp;**pend</em>, int<em>&nbsp;base</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyIntObject" title="PyIntObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyIntObject</span></code></a> or <a class="reference internal" href="long.html#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> based on the string
value in <em>str</em>, which is interpreted according to the radix in <em>base</em>.  If
<em>pend</em> is non-<em>NULL</em>, <code class="docutils literal notranslate"><span class="pre">*pend</span></code> will point to the first character in <em>str</em> which
follows the representation of the number.  If <em>base</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the radix will be
determined based on the leading characters of <em>str</em>: if <em>str</em> starts with
<code class="docutils literal notranslate"><span class="pre">'0x'</span></code> or <code class="docutils literal notranslate"><span class="pre">'0X'</span></code>, radix 16 will be used; if <em>str</em> starts with <code class="docutils literal notranslate"><span class="pre">'0'</span></code>, radix
8 will be used; otherwise radix 10 will be used.  If <em>base</em> is not <code class="docutils literal notranslate"><span class="pre">0</span></code>, it
must be between <code class="docutils literal notranslate"><span class="pre">2</span></code> and <code class="docutils literal notranslate"><span class="pre">36</span></code>, inclusive.  Leading spaces are ignored.  If
there are no digits, <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised.  If the string represents
a number too large to be contained within the machine’s <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code> type
and overflow warnings are being suppressed, a <a class="reference internal" href="long.html#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> will be
returned.  If overflow warnings are not being suppressed, <em>NULL</em> will be
returned in this case.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_FromLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInt_FromLong</code><span class="sig-paren">(</span>long<em>&nbsp;ival</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_FromLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new integer object with a value of <em>ival</em>.</p>
<p>The current implementation keeps an array of integer objects for all integers
between <code class="docutils literal notranslate"><span class="pre">-5</span></code> and <code class="docutils literal notranslate"><span class="pre">256</span></code>, when you create an int in that range you actually
just get back a reference to the existing object. So it should be possible to
change the value of <code class="docutils literal notranslate"><span class="pre">1</span></code>.  I suspect the behaviour of Python in this case is
undefined. :-)</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_FromSsize_t">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInt_FromSsize_t</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;ival</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_FromSsize_t" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new integer object with a value of <em>ival</em>. If the value is larger
than <code class="docutils literal notranslate"><span class="pre">LONG_MAX</span></code> or smaller than <code class="docutils literal notranslate"><span class="pre">LONG_MIN</span></code>, a long integer object is
returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_FromSize_t">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInt_FromSize_t</code><span class="sig-paren">(</span>size_t<em>&nbsp;ival</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_FromSize_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new integer object with a value of <em>ival</em>. If the value exceeds
<code class="docutils literal notranslate"><span class="pre">LONG_MAX</span></code>, a long integer object is returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_AsLong">
long <code class="descname">PyInt_AsLong</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_AsLong" title="Permalink to this definition">¶</a></dt>
<dd><p>Will first attempt to cast the object to a <a class="reference internal" href="#c.PyIntObject" title="PyIntObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyIntObject</span></code></a>, if it is not
already one, and then return its value. If there is an error, <code class="docutils literal notranslate"><span class="pre">-1</span></code> is
returned, and the caller should check <code class="docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code> to find out whether
there was an error, or whether the value just happened to be <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_AS_LONG">
long <code class="descname">PyInt_AS_LONG</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_AS_LONG" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the object <em>io</em>.  No error checking is performed.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_AsUnsignedLongMask">
unsigned long <code class="descname">PyInt_AsUnsignedLongMask</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_AsUnsignedLongMask" title="Permalink to this definition">¶</a></dt>
<dd><p>Will first attempt to cast the object to a <a class="reference internal" href="#c.PyIntObject" title="PyIntObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyIntObject</span></code></a> or
<a class="reference internal" href="long.html#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>, if it is not already one, and then return its value as
unsigned long.  This function does not check for overflow.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_AsUnsignedLongLongMask">
unsigned PY_LONG_LONG <code class="descname">PyInt_AsUnsignedLongLongMask</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_AsUnsignedLongLongMask" title="Permalink to this definition">¶</a></dt>
<dd><p>Will first attempt to cast the object to a <a class="reference internal" href="#c.PyIntObject" title="PyIntObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyIntObject</span></code></a> or
<a class="reference internal" href="long.html#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>, if it is not already one, and then return its value as
unsigned long long, without checking for overflow.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_AsSsize_t">
Py_ssize_t <code class="descname">PyInt_AsSsize_t</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_AsSsize_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Will first attempt to cast the object to a <a class="reference internal" href="#c.PyIntObject" title="PyIntObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyIntObject</span></code></a> or
<a class="reference internal" href="long.html#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>, if it is not already one, and then return its value as
<code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_GetMax">
long <code class="descname">PyInt_GetMax</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_GetMax" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Return the system’s idea of the largest integer it can handle
(<code class="xref py py-const docutils literal notranslate"><span class="pre">LONG_MAX</span></code>, as defined in the system header files).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInt_ClearFreeList">
int <code class="descname">PyInt_ClearFreeList</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInt_ClearFreeList" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the integer free list. Return the number of items that could not
be freed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="none.html"
                        title="previous chapter">The <code class="docutils literal notranslate"><span class="pre">None</span></code> Object</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bool.html"
                        title="next chapter">Boolean Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/int.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bool.html" title="Boolean Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="none.html" title="The None Object"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��A���html/c-api/intro.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Introduction &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="The Very High Level Layer" href="veryhigh.html" />
    <link rel="prev" title="Python/C API Reference Manual" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/intro.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="veryhigh.html" title="The Very High Level Layer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python/C API Reference Manual"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="introduction">
<span id="api-intro"></span><h1>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h1>
<p>The Application Programmer’s Interface to Python gives C and C++ programmers
access to the Python interpreter at a variety of levels.  The API is equally
usable from C++, but for brevity it is generally referred to as the Python/C
API.  There are two fundamentally different reasons for using the Python/C API.
The first reason is to write <em>extension modules</em> for specific purposes; these
are C modules that extend the Python interpreter.  This is probably the most
common use.  The second reason is to use Python as a component in a larger
application; this technique is generally referred to as <em class="dfn">embedding</em> Python
in an application.</p>
<p>Writing an extension module is a relatively well-understood process,  where a
“cookbook” approach works well.  There are several tools  that automate the
process to some extent.  While people have embedded  Python in other
applications since its early existence, the process of  embedding Python is less
straightforward than writing an extension.</p>
<p>Many API functions are useful independent of whether you’re embedding  or
extending Python; moreover, most applications that embed Python  will need to
provide a custom extension as well, so it’s probably a  good idea to become
familiar with writing an extension before  attempting to embed Python in a real
application.</p>
<div class="section" id="include-files">
<span id="api-includes"></span><h2>Include Files<a class="headerlink" href="#include-files" title="Permalink to this headline">¶</a></h2>
<p>All function, type and macro definitions needed to use the Python/C API are
included in your code by the following line:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;Python.h&quot;</span><span class="cp"></span>
</pre></div>
</div>
<p>This implies inclusion of the following standard headers: <code class="docutils literal notranslate"><span class="pre">&lt;stdio.h&gt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;string.h&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;errno.h&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;limits.h&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;assert.h&gt;</span></code> and <code class="docutils literal notranslate"><span class="pre">&lt;stdlib.h&gt;</span></code>
(if available).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since Python may define some pre-processor definitions which affect the standard
headers on some systems, you <em>must</em> include <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> before any standard
headers are included.</p>
</div>
<p>All user visible names defined by Python.h (except those defined by the included
standard headers) have one of the prefixes <code class="docutils literal notranslate"><span class="pre">Py</span></code> or <code class="docutils literal notranslate"><span class="pre">_Py</span></code>.  Names beginning
with <code class="docutils literal notranslate"><span class="pre">_Py</span></code> are for internal use by the Python implementation and should not be
used by extension writers. Structure member names do not have a reserved prefix.</p>
<p><strong>Important:</strong> user code should never define names that begin with <code class="docutils literal notranslate"><span class="pre">Py</span></code> or
<code class="docutils literal notranslate"><span class="pre">_Py</span></code>.  This confuses the reader, and jeopardizes the portability of the user
code to future Python versions, which may define additional names beginning with
one of these prefixes.</p>
<p>The header files are typically installed with Python.  On Unix, these  are
located in the directories <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include/pythonversion/</span></code> and
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/include/pythonversion/</span></code>, where <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> and
<span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">exec_prefix</span></code> are defined by the corresponding parameters to Python’s
<strong class="program">configure</strong> script and <em>version</em> is <code class="docutils literal notranslate"><span class="pre">sys.version[:3]</span></code>.  On Windows,
the headers are installed in <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include</span></code>, where <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> is
the installation directory specified to the installer.</p>
<p>To include the headers, place both directories (if different) on your compiler’s
search path for includes.  Do <em>not</em> place the parent directories on the search
path and then use <code class="docutils literal notranslate"><span class="pre">#include</span> <span class="pre">&lt;pythonX.Y/Python.h&gt;</span></code>; this will break on
multi-platform builds since the platform independent headers under
<span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> include the platform specific headers from
<span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">exec_prefix</span></code>.</p>
<p>C++ users should note that though the API is defined entirely using C, the
header files do properly declare the entry points to be <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>, so there
is no need to do anything special to use the API from C++.</p>
</div>
<div class="section" id="objects-types-and-reference-counts">
<span id="api-objects"></span><h2>Objects, Types and Reference Counts<a class="headerlink" href="#objects-types-and-reference-counts" title="Permalink to this headline">¶</a></h2>
<p id="index-5">Most Python/C API functions have one or more arguments as well as a return value
of type <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.  This type is a pointer to an opaque data type
representing an arbitrary Python object.  Since all Python object types are
treated the same way by the Python language in most situations (e.g.,
assignments, scope rules, and argument passing), it is only fitting that they
should be represented by a single C type.  Almost all Python objects live on the
heap: you never declare an automatic or static variable of type
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a>, only pointer variables of type <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> can  be
declared.  The sole exception are the type objects; since these must never be
deallocated, they are typically static <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> objects.</p>
<p>All Python objects (even Python integers) have a <em class="dfn">type</em> and a
<em class="dfn">reference count</em>.  An object’s type determines what kind of object it is
(e.g., an integer, a list, or a user-defined function; there are many more as
explained in <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>).  For each of the well-known types there is a macro
to check whether an object is of that type; for instance, <code class="docutils literal notranslate"><span class="pre">PyList_Check(a)</span></code> is
true if (and only if) the object pointed to by <em>a</em> is a Python list.</p>
<div class="section" id="reference-counts">
<span id="api-refcounts"></span><h3>Reference Counts<a class="headerlink" href="#reference-counts" title="Permalink to this headline">¶</a></h3>
<p>The reference count is important because today’s computers have a  finite (and
often severely limited) memory size; it counts how many  different places there
are that have a reference to an object.  Such a  place could be another object,
or a global (or static) C variable, or  a local variable in some C function.
When an object’s reference count  becomes zero, the object is deallocated.  If
it contains references to  other objects, their reference count is decremented.
Those other  objects may be deallocated in turn, if this decrement makes their
reference count become zero, and so on.  (There’s an obvious problem  with
objects that reference each other here; for now, the solution is  “don’t do
that.”)</p>
<p id="index-6">Reference counts are always manipulated explicitly.  The normal way is  to use
the macro <a class="reference internal" href="refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to increment an object’s reference count by one,
and <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> to decrement it by   one.  The <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> macro
is considerably more complex than the incref one, since it must check whether
the reference count becomes zero and then cause the object’s deallocator to be
called. The deallocator is a function pointer contained in the object’s type
structure.  The type-specific deallocator takes care of decrementing the
reference counts for other objects contained in the object if this is a compound
object type, such as a list, as well as performing any additional finalization
that’s needed.  There’s no chance that the reference count can overflow; at
least as many bits are used to hold the reference count as there are distinct
memory locations in virtual memory (assuming <code class="docutils literal notranslate"><span class="pre">sizeof(Py_ssize_t)</span> <span class="pre">&gt;=</span> <span class="pre">sizeof(void*)</span></code>).
Thus, the reference count increment is a simple operation.</p>
<p>It is not necessary to increment an object’s reference count for every  local
variable that contains a pointer to an object.  In theory, the  object’s
reference count goes up by one when the variable is made to  point to it and it
goes down by one when the variable goes out of  scope.  However, these two
cancel each other out, so at the end the  reference count hasn’t changed.  The
only real reason to use the  reference count is to prevent the object from being
deallocated as  long as our variable is pointing to it.  If we know that there
is at  least one other reference to the object that lives at least as long as
our variable, there is no need to increment the reference count  temporarily.
An important situation where this arises is in objects  that are passed as
arguments to C functions in an extension module  that are called from Python;
the call mechanism guarantees to hold a  reference to every argument for the
duration of the call.</p>
<p>However, a common pitfall is to extract an object from a list and hold on to it
for a while without incrementing its reference count. Some other operation might
conceivably remove the object from the list, decrementing its reference count
and possible deallocating it. The real danger is that innocent-looking
operations may invoke arbitrary Python code which could do this; there is a code
path which allows control to flow back to the user from a <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>, so
almost any operation is potentially dangerous.</p>
<p>A safe approach is to always use the generic operations (functions  whose name
begins with <code class="docutils literal notranslate"><span class="pre">PyObject_</span></code>, <code class="docutils literal notranslate"><span class="pre">PyNumber_</span></code>, <code class="docutils literal notranslate"><span class="pre">PySequence_</span></code> or <code class="docutils literal notranslate"><span class="pre">PyMapping_</span></code>).
These operations always increment the reference count of the object they return.
This leaves the caller with the responsibility to call <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> when
they are done with the result; this soon becomes second nature.</p>
<div class="section" id="reference-count-details">
<span id="api-refcountdetails"></span><h4>Reference Count Details<a class="headerlink" href="#reference-count-details" title="Permalink to this headline">¶</a></h4>
<p>The reference count behavior of functions in the Python/C API is best  explained
in terms of <em>ownership of references</em>.  Ownership pertains to references, never
to objects (objects are not owned: they are always shared).  “Owning a
reference” means being responsible for calling Py_DECREF on it when the
reference is no longer needed.  Ownership can also be transferred, meaning that
the code that receives ownership of the reference then becomes responsible for
eventually decref’ing it by calling <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> or <a class="reference internal" href="refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>
when it’s no longer needed—or passing on this responsibility (usually to its
caller). When a function passes ownership of a reference on to its caller, the
caller is said to receive a <em>new</em> reference.  When no ownership is transferred,
the caller is said to <em>borrow</em> the reference. Nothing needs to be done for a
borrowed reference.</p>
<p>Conversely, when a calling function passes in a reference to an  object, there
are two possibilities: the function <em>steals</em> a  reference to the object, or it
does not.  <em>Stealing a reference</em> means that when you pass a reference to a
function, that function assumes that it now owns that reference, and you are not
responsible for it any longer.</p>
<p id="index-7">Few functions steal references; the two notable exceptions are
<a class="reference internal" href="list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a> and <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a>, which  steal a reference
to the item (but not to the tuple or list into which the item is put!).  These
functions were designed to steal a reference because of a common idiom for
populating a tuple or list with newly created objects; for example, the code to
create the tuple <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">&quot;three&quot;)</span></code> could look like this (forgetting about
error handling for the moment; a better way to code this is shown below):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">t</span><span class="p">;</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">PyTuple_New</span><span class="p">(</span><span class="mi">3</span><span class="p">);</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">1L</span><span class="p">));</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">2L</span><span class="p">));</span>
<span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;three&quot;</span><span class="p">));</span>
</pre></div>
</div>
<p>Here, <a class="reference internal" href="int.html#c.PyInt_FromLong" title="PyInt_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInt_FromLong()</span></code></a> returns a new reference which is immediately
stolen by <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a>.  When you want to keep using an object
although the reference to it will be stolen, use <a class="reference internal" href="refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to grab
another reference before calling the reference-stealing function.</p>
<p>Incidentally, <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> is the <em>only</em> way to set tuple items;
<a class="reference internal" href="sequence.html#c.PySequence_SetItem" title="PySequence_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_SetItem()</span></code></a> and <a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a> refuse to do this
since tuples are an immutable data type.  You should only use
<a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> for tuples that you are creating yourself.</p>
<p>Equivalent code for populating a list can be written using <a class="reference internal" href="list.html#c.PyList_New" title="PyList_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_New()</span></code></a>
and <a class="reference internal" href="list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>.</p>
<p>However, in practice, you will rarely use these ways of creating and populating
a tuple or list.  There’s a generic function, <a class="reference internal" href="arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, that can
create most common objects from C values, directed by a <em class="dfn">format string</em>.
For example, the above two blocks of code could be replaced by the following
(which also takes care of the error checking):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">tuple</span><span class="p">,</span> <span class="o">*</span><span class="n">list</span><span class="p">;</span>

<span class="n">tuple</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(iis)&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&quot;three&quot;</span><span class="p">);</span>
<span class="n">list</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;[iis]&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s">&quot;three&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>It is much more common to use <a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a> and friends with items
whose references you are only borrowing, like arguments that were passed in to
the function you are writing.  In that case, their behaviour regarding reference
counts is much saner, since you don’t have to increment a reference count so you
can give a reference away (“have it be stolen”).  For example, this function
sets all items of a list (actually, any mutable sequence) to a given item:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">set_all</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">target</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">PyObject_Length</span><span class="p">(</span><span class="n">target</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyObject</span> <span class="o">*</span><span class="n">index</span> <span class="o">=</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">index</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">target</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">index</span><span class="p">);</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">index</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p id="index-8">The situation is slightly different for function return values.   While passing
a reference to most functions does not change your  ownership responsibilities
for that reference, many functions that  return a reference to an object give
you ownership of the reference. The reason is simple: in many cases, the
returned object is created  on the fly, and the reference you get is the only
reference to the  object.  Therefore, the generic functions that return object
references, like <a class="reference internal" href="object.html#c.PyObject_GetItem" title="PyObject_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetItem()</span></code></a> and  <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>,
always return a new reference (the caller becomes the owner of the reference).</p>
<p>It is important to realize that whether you own a reference returned  by a
function depends on which function you call only — <em>the plumage</em> (the type of
the object passed as an argument to the function) <em>doesn’t enter into it!</em>
Thus, if you  extract an item from a list using <a class="reference internal" href="list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, you
don’t own the reference — but if you obtain the same item from the same list
using <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a> (which happens to take exactly the same
arguments), you do own a reference to the returned object.</p>
<p id="index-9">Here is an example of how you could write a function that computes the sum of
the items in a list of integers; once using  <a class="reference internal" href="list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, and once
using <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">long</span>
<span class="nf">sum_list</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">;</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">PyList_Size</span><span class="p">(</span><span class="n">list</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Not a list */</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span> <span class="cm">/* Can&#39;t fail */</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyInt_Check</span><span class="p">(</span><span class="n">item</span><span class="p">))</span> <span class="k">continue</span><span class="p">;</span> <span class="cm">/* Skip non-integers */</span>
        <span class="n">total</span> <span class="o">+=</span> <span class="n">PyInt_AsLong</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">total</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate" id="index-10"><div class="highlight"><pre><span></span><span class="kt">long</span>
<span class="nf">sum_sequence</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">sequence</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">total</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">;</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">PySequence_Length</span><span class="p">(</span><span class="n">sequence</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Has no length */</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PySequence_GetItem</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Not a sequence, or other failure */</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PyInt_Check</span><span class="p">(</span><span class="n">item</span><span class="p">))</span>
            <span class="n">total</span> <span class="o">+=</span> <span class="n">PyInt_AsLong</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span> <span class="cm">/* Discard reference ownership */</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">total</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="types">
<span id="api-types"></span><span id="index-11"></span><h3>Types<a class="headerlink" href="#types" title="Permalink to this headline">¶</a></h3>
<p>There are few other data types that play a significant role in  the Python/C
API; most are simple C types such as <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>,  <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code>,
<code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> and <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>.  A few structure types  are used to
describe static tables used to list the functions exported  by a module or the
data attributes of a new object type, and another is used to describe the value
of a complex number.  These will  be discussed together with the functions that
use them.</p>
</div>
</div>
<div class="section" id="exceptions">
<span id="api-exceptions"></span><h2>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>The Python programmer only needs to deal with exceptions if specific  error
handling is required; unhandled exceptions are automatically  propagated to the
caller, then to the caller’s caller, and so on, until they reach the top-level
interpreter, where they are reported to the  user accompanied by a stack
traceback.</p>
<p id="index-12">For C programmers, however, error checking always has to be explicit.  All
functions in the Python/C API can raise exceptions, unless an explicit claim is
made otherwise in a function’s documentation.  In general, when a function
encounters an error, it sets an exception, discards any object references that
it owns, and returns an error indicator.  If not documented otherwise, this
indicator is either <em>NULL</em> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>, depending on the function’s return type.
A few functions return a Boolean true/false result, with false indicating an
error.  Very few functions return no explicit error indicator or have an
ambiguous return value, and require explicit testing for errors with
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>.  These exceptions are always explicitly documented.</p>
<p id="index-13">Exception state is maintained in per-thread storage (this is  equivalent to
using global storage in an unthreaded application).  A  thread can be in one of
two states: an exception has occurred, or not. The function
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> can be used to check for this: it returns a borrowed
reference to the exception type object when an exception has occurred, and
<em>NULL</em> otherwise.  There are a number of functions to set the exception state:
<a class="reference internal" href="exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> is the most common (though not the most general)
function to set the exception state, and <a class="reference internal" href="exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> clears the
exception state.</p>
<p id="index-14">The full exception state consists of three objects (all of which can  be
<em>NULL</em>): the exception type, the corresponding exception  value, and the
traceback.  These have the same meanings as the Python   objects
<code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.exc_value</span></code>, and <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code>; however, they
are not the same: the Python objects represent the last exception being handled
by a Python  <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement, while the C level
exception state only exists while an exception is being passed on between C
functions until it reaches the Python bytecode interpreter’s  main loop, which
takes care of transferring it to <code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code> and friends.</p>
<p id="index-15">Note that starting with Python 1.5, the preferred, thread-safe way to access the
exception state from Python code is to call the function <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>,
which returns the per-thread exception state for Python code.  Also, the
semantics of both ways to access the exception state have changed so that a
function which catches an exception will save and restore its thread’s exception
state so as to preserve the exception state of its caller.  This prevents common
bugs in exception handling code caused by an innocent-looking function
overwriting the exception being handled; it also reduces the often unwanted
lifetime extension for objects that are referenced by the stack frames in the
traceback.</p>
<p>As a general principle, a function that calls another function to  perform some
task should check whether the called function raised an  exception, and if so,
pass the exception state on to its caller.  It  should discard any object
references that it owns, and return an  error indicator, but it should <em>not</em> set
another exception — that would overwrite the exception that was just raised,
and lose important information about the exact cause of the error.</p>
<p id="index-16">A simple example of detecting exceptions and passing them on is shown in the
<code class="xref c c-func docutils literal notranslate"><span class="pre">sum_sequence()</span></code> example above.  It so happens that this example doesn’t
need to clean up any owned references when it detects an error.  The following
example function shows some error cleanup.  First, to remind you why you like
Python, we show the equivalent Python code:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">def</span> <span class="n">incr_item</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span><span class="o">:</span>
    <span class="nl">try</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
    <span class="n">except</span> <span class="nl">KeyError</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">item</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p id="index-17">Here is the corresponding C code, in all its glory:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">incr_item</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dict</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">key</span><span class="p">)</span>
<span class="p">{</span>
    <span class="cm">/* Objects all initialized to NULL for Py_XDECREF */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">const_one</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">incremented_item</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">rv</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span> <span class="cm">/* Return value initialized to -1 (failure) */</span>

    <span class="n">item</span> <span class="o">=</span> <span class="n">PyObject_GetItem</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="cm">/* Handle KeyError only: */</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyErr_ExceptionMatches</span><span class="p">(</span><span class="n">PyExc_KeyError</span><span class="p">))</span>
            <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

        <span class="cm">/* Clear the error and use zero: */</span>
        <span class="n">PyErr_Clear</span><span class="p">();</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">const_one</span> <span class="o">=</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">1L</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">const_one</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

    <span class="n">incremented_item</span> <span class="o">=</span> <span class="n">PyNumber_Add</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">const_one</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">incremented_item</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">incremented_item</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">goto</span> <span class="n">error</span><span class="p">;</span>
    <span class="n">rv</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="cm">/* Success */</span>
    <span class="cm">/* Continue with cleanup code */</span>

 <span class="nl">error</span><span class="p">:</span>
    <span class="cm">/* Cleanup code, shared by success and failure path */</span>

    <span class="cm">/* Use Py_XDECREF() to ignore NULL references */</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">const_one</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">incremented_item</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">rv</span><span class="p">;</span> <span class="cm">/* -1 for error, 0 for success */</span>
<span class="p">}</span>
</pre></div>
</div>
<span class="target" id="index-18"></span><p id="index-19">This example represents an endorsed use of the <code class="docutils literal notranslate"><span class="pre">goto</span></code> statement  in C!
It illustrates the use of <a class="reference internal" href="exceptions.html#c.PyErr_ExceptionMatches" title="PyErr_ExceptionMatches"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_ExceptionMatches()</span></code></a> and
<a class="reference internal" href="exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> to handle specific exceptions, and the use of
<a class="reference internal" href="refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> to dispose of owned references that may be <em>NULL</em> (note the
<code class="docutils literal notranslate"><span class="pre">'X'</span></code> in the name; <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> would crash when confronted with a
<em>NULL</em> reference).  It is important that the variables used to hold owned
references are initialized to <em>NULL</em> for this to work; likewise, the proposed
return value is initialized to <code class="docutils literal notranslate"><span class="pre">-1</span></code> (failure) and only set to success after
the final call made is successful.</p>
</div>
<div class="section" id="embedding-python">
<span id="api-embedding"></span><h2>Embedding Python<a class="headerlink" href="#embedding-python" title="Permalink to this headline">¶</a></h2>
<p>The one important task that only embedders (as opposed to extension writers) of
the Python interpreter have to worry about is the initialization, and possibly
the finalization, of the Python interpreter.  Most functionality of the
interpreter can only be used after the interpreter has been initialized.</p>
<p id="index-20">The basic initialization function is <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>. This initializes
the table of loaded modules, and creates the fundamental modules
<a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a>, <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, and <a class="reference internal" href="../library/exceptions.html#module-exceptions" title="exceptions: Standard exception classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">exceptions</span></code></a>.  It also
initializes the module search path (<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>).</p>
<p id="index-21"><a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> does not set the “script argument list”  (<code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>).
If this variable is needed by Python code that will be executed later, it must
be set explicitly with a call to  <code class="docutils literal notranslate"><span class="pre">PySys_SetArgvEx(argc,</span> <span class="pre">argv,</span> <span class="pre">updatepath)</span></code>
after the call to <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.</p>
<p>On most systems (in particular, on Unix and Windows, although the details are
slightly different), <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> calculates the module search path
based upon its best guess for the location of the standard Python interpreter
executable, assuming that the Python library is found in a fixed location
relative to the Python interpreter executable.  In particular, it looks for a
directory named <code class="file docutils literal notranslate"><span class="pre">lib/python</span><em><span class="pre">X.Y</span></em></code> relative to the parent directory
where the executable named <code class="file docutils literal notranslate"><span class="pre">python</span></code> is found on the shell command search
path (the environment variable <span class="target" id="index-22"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>).</p>
<p>For instance, if the Python executable is found in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/bin/python</span></code>, it will assume that the libraries are in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em></code>.  (In fact, this particular path is also
the “fallback” location, used when no executable file named <code class="file docutils literal notranslate"><span class="pre">python</span></code> is
found along <span class="target" id="index-23"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>.)  The user can override this behavior by setting the
environment variable <span class="target" id="index-24"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a>, or insert additional directories in
front of the standard path by setting <span class="target" id="index-25"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>.</p>
<p id="index-26">The embedding application can steer the search by calling
<code class="docutils literal notranslate"><span class="pre">Py_SetProgramName(file)</span></code> <em>before</em> calling  <a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.  Note that
<span class="target" id="index-27"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> still overrides this and <span class="target" id="index-28"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is still
inserted in front of the standard path.  An application that requires total
control has to provide its own implementation of <a class="reference internal" href="init.html#c.Py_GetPath" title="Py_GetPath"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetPath()</span></code></a>,
<a class="reference internal" href="init.html#c.Py_GetPrefix" title="Py_GetPrefix"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetPrefix()</span></code></a>, <a class="reference internal" href="init.html#c.Py_GetExecPrefix" title="Py_GetExecPrefix"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetExecPrefix()</span></code></a>, and
<a class="reference internal" href="init.html#c.Py_GetProgramFullPath" title="Py_GetProgramFullPath"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetProgramFullPath()</span></code></a> (all defined in <code class="file docutils literal notranslate"><span class="pre">Modules/getpath.c</span></code>).</p>
<p id="index-29">Sometimes, it is desirable to “uninitialize” Python.  For instance,  the
application may want to start over (make another call to
<a class="reference internal" href="init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>) or the application is simply done with its  use of
Python and wants to free memory allocated by Python.  This can be accomplished
by calling <a class="reference internal" href="init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a>.  The function <a class="reference internal" href="init.html#c.Py_IsInitialized" title="Py_IsInitialized"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_IsInitialized()</span></code></a> returns
true if Python is currently in the initialized state.  More information about
these functions is given in a later chapter. Notice that <a class="reference internal" href="init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a>
does <em>not</em> free all memory allocated by the Python interpreter, e.g. memory
allocated by extension modules currently cannot be released.</p>
</div>
<div class="section" id="debugging-builds">
<span id="api-debugging"></span><h2>Debugging Builds<a class="headerlink" href="#debugging-builds" title="Permalink to this headline">¶</a></h2>
<p>Python can be built with several macros to enable extra checks of the
interpreter and extension modules.  These checks tend to add a large amount of
overhead to the runtime so they are not enabled by default.</p>
<p>A full list of the various types of debugging builds is in the file
<code class="file docutils literal notranslate"><span class="pre">Misc/SpecialBuilds.txt</span></code> in the Python source distribution. Builds are
available that support tracing of reference counts, debugging the memory
allocator, or low-level profiling of the main interpreter loop.  Only the most
frequently-used builds will be described in the remainder of this section.</p>
<p>Compiling the interpreter with the <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> macro defined produces
what is generally meant by “a debug build” of Python. <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> is
enabled in the Unix build by adding <code class="docutils literal notranslate"><span class="pre">--with-pydebug</span></code> to the
<code class="file docutils literal notranslate"><span class="pre">./configure</span></code> command.  It is also implied by the presence of the
not-Python-specific <code class="xref c c-macro docutils literal notranslate"><span class="pre">_DEBUG</span></code> macro.  When <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code> is enabled
in the Unix build, compiler optimization is disabled.</p>
<p>In addition to the reference count debugging described below, the following
extra checks are performed:</p>
<ul class="simple">
<li>Extra checks are added to the object allocator.</li>
<li>Extra checks are added to the parser and compiler.</li>
<li>Downcasts from wide types to narrow types are checked for loss of information.</li>
<li>A number of assertions are added to the dictionary and set implementations.
In addition, the set object acquires a <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_c_api()</span></code> method.</li>
<li>Sanity checks of the input arguments are added to frame creation.</li>
<li>The storage for long ints is initialized with a known invalid pattern to catch
reference to uninitialized digits.</li>
<li>Low-level tracing and extra exception checking are added to the runtime
virtual machine.</li>
<li>Extra checks are added to the memory arena implementation.</li>
<li>Extra debugging is added to the thread module.</li>
</ul>
<p>There may be additional checks not mentioned here.</p>
<p>Defining <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code> enables reference tracing.  When defined, a
circular doubly linked list of active objects is maintained by adding two extra
fields to every <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a>.  Total allocations are tracked as well.  Upon
exit, all existing references are printed.  (In interactive mode this happens
after every statement run by the interpreter.)  Implied by <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_DEBUG</span></code>.</p>
<p>Please refer to <code class="file docutils literal notranslate"><span class="pre">Misc/SpecialBuilds.txt</span></code> in the Python source distribution
for more detailed information.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Introduction</a><ul>
<li><a class="reference internal" href="#include-files">Include Files</a></li>
<li><a class="reference internal" href="#objects-types-and-reference-counts">Objects, Types and Reference Counts</a><ul>
<li><a class="reference internal" href="#reference-counts">Reference Counts</a><ul>
<li><a class="reference internal" href="#reference-count-details">Reference Count Details</a></li>
</ul>
</li>
<li><a class="reference internal" href="#types">Types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">Exceptions</a></li>
<li><a class="reference internal" href="#embedding-python">Embedding Python</a></li>
<li><a class="reference internal" href="#debugging-builds">Debugging Builds</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Python/C API Reference Manual</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="veryhigh.html"
                        title="next chapter">The Very High Level Layer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/intro.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="veryhigh.html" title="The Very High Level Layer"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python/C API Reference Manual"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�g}��'�'html/c-api/iter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Iterator Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Old Buffer Protocol" href="objbuffer.html" />
    <link rel="prev" title="Mapping Protocol" href="mapping.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/iter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="objbuffer.html" title="Old Buffer Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mapping.html" title="Mapping Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="iterator-protocol">
<span id="iterator"></span><h1>Iterator Protocol<a class="headerlink" href="#iterator-protocol" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>There are two functions specifically for working with iterators.</p>
<dl class="function">
<dt id="c.PyIter_Check">
int <code class="descname">PyIter_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyIter_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> supports the iterator protocol.</p>
<p>This function can return a false positive in the case of old-style
classes because those classes always define a <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iternext</span></code>
slot with logic that either invokes a <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method or raises
a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyIter_Next">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyIter_Next</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyIter_Next" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the next value from the iteration <em>o</em>.  The object must be an iterator
(it is up to the caller to check this).  If there are no remaining values,
returns <em>NULL</em> with no exception set.  If an error occurs while retrieving
the item, returns <em>NULL</em> and passes along the exception.</p>
</dd></dl>

<p>To write a loop which iterates over an iterator, the C code should look
something like this:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">iterator</span> <span class="o">=</span> <span class="n">PyObject_GetIter</span><span class="p">(</span><span class="n">obj</span><span class="p">);</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span><span class="p">;</span>

<span class="k">if</span> <span class="p">(</span><span class="n">iterator</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
    <span class="cm">/* propagate error */</span>
<span class="p">}</span>

<span class="k">while</span> <span class="p">(</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyIter_Next</span><span class="p">(</span><span class="n">iterator</span><span class="p">))</span> <span class="p">{</span>
    <span class="cm">/* do something with item */</span>
    <span class="p">...</span>
    <span class="cm">/* release reference when done */</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
<span class="p">}</span>

<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">iterator</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">PyErr_Occurred</span><span class="p">())</span> <span class="p">{</span>
    <span class="cm">/* propagate error */</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
    <span class="cm">/* continue doing useful work */</span>
<span class="p">}</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="mapping.html"
                        title="previous chapter">Mapping Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="objbuffer.html"
                        title="next chapter">Old Buffer Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/iter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="objbuffer.html" title="Old Buffer Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="mapping.html" title="Mapping Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���6.6.html/c-api/iterator.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Iterator Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Descriptor Objects" href="descriptor.html" />
    <link rel="prev" title="Module Objects" href="module.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/iterator.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="module.html" title="Module Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="iterator-objects">
<span id="id1"></span><h1>Iterator Objects<a class="headerlink" href="#iterator-objects" title="Permalink to this headline">¶</a></h1>
<p>Python provides two general-purpose iterator objects.  The first, a sequence
iterator, works with an arbitrary sequence supporting the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
method.  The second works with a callable object and a sentinel value, calling
the callable for each item in the sequence, and ending the iteration when the
sentinel value is returned.</p>
<dl class="var">
<dt id="c.PySeqIter_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PySeqIter_Type</code><a class="headerlink" href="#c.PySeqIter_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>Type object for iterator objects returned by <a class="reference internal" href="#c.PySeqIter_New" title="PySeqIter_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySeqIter_New()</span></code></a> and the
one-argument form of the <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> built-in function for built-in sequence
types.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySeqIter_Check">
int <code class="descname">PySeqIter_Check</code><span class="sig-paren">(</span>op<span class="sig-paren">)</span><a class="headerlink" href="#c.PySeqIter_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the type of <em>op</em> is <a class="reference internal" href="#c.PySeqIter_Type" title="PySeqIter_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PySeqIter_Type</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySeqIter_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySeqIter_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*seq</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySeqIter_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return an iterator that works with a general sequence object, <em>seq</em>.  The
iteration ends when the sequence raises <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> for the subscripting
operation.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="var">
<dt id="c.PyCallIter_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyCallIter_Type</code><a class="headerlink" href="#c.PyCallIter_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>Type object for iterator objects returned by <a class="reference internal" href="#c.PyCallIter_New" title="PyCallIter_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCallIter_New()</span></code></a> and the
two-argument form of the <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> built-in function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyCallIter_Check">
int <code class="descname">PyCallIter_Check</code><span class="sig-paren">(</span>op<span class="sig-paren">)</span><a class="headerlink" href="#c.PyCallIter_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the type of <em>op</em> is <a class="reference internal" href="#c.PyCallIter_Type" title="PyCallIter_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyCallIter_Type</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyCallIter_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCallIter_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callable</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*sentinel</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCallIter_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new iterator.  The first parameter, <em>callable</em>, can be any Python
callable object that can be called with no parameters; each call to it should
return the next item in the iteration.  When <em>callable</em> returns a value equal to
<em>sentinel</em>, the iteration will be terminated.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="module.html"
                        title="previous chapter">Module Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="descriptor.html"
                        title="next chapter">Descriptor Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/iterator.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="module.html" title="Module Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�L>�^`^`html/c-api/list.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>List Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Dictionary Objects" href="dict.html" />
    <link rel="prev" title="Tuple Objects" href="tuple.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/list.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dict.html" title="Dictionary Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tuple.html" title="Tuple Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="list-objects">
<span id="listobjects"></span><h1>List Objects<a class="headerlink" href="#list-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyListObject">
<code class="descname">PyListObject</code><a class="headerlink" href="#c.PyListObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python list object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyList_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyList_Type</code><a class="headerlink" href="#c.PyList_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python list type.  This
is the same object as <code class="docutils literal notranslate"><span class="pre">list</span></code> in the Python layer.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Check">
int <code class="descname">PyList_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a list object or an instance of a subtype of the list
type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_CheckExact">
int <code class="descname">PyList_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a list object, but not an instance of a subtype of
the list type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyList_New</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new list of length <em>len</em> on success, or <em>NULL</em> on failure.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <em>len</em> is greater than zero, the returned list object’s items are
set to <code class="docutils literal notranslate"><span class="pre">NULL</span></code>.  Thus you cannot use abstract API functions such as
<a class="reference internal" href="sequence.html#c.PySequence_SetItem" title="PySequence_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_SetItem()</span></code></a>  or expose the object to Python code before
setting all items to a real object with <a class="reference internal" href="#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Size">
Py_ssize_t <code class="descname">PyList_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Size" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Return the length of the list object in <em>list</em>; this is equivalent to
<code class="docutils literal notranslate"><span class="pre">len(list)</span></code> on a list object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>. This might require changes in
your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_GET_SIZE">
Py_ssize_t <code class="descname">PyList_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro form of <a class="reference internal" href="#c.PyList_Size" title="PyList_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Size()</span></code></a> without error checking.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This macro returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>. This might require changes in your
code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_GetItem">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyList_GetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;index</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_GetItem" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the object at position <em>index</em> in the list pointed to by <em>list</em>.  The
position must be positive, indexing from the end of the list is not
supported.  If <em>index</em> is out of bounds, return <em>NULL</em> and set an
<a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>index</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_GET_ITEM">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyList_GET_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_GET_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Macro form of <a class="reference internal" href="#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a> without error checking.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This macro used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>i</em>. This might require changes in
your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_SetItem">
int <code class="descname">PyList_SetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;index</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*item</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_SetItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the item at index <em>index</em> in list to <em>item</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success
or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function “steals” a reference to <em>item</em> and discards a reference to
an item already in the list at the affected position.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>index</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_SET_ITEM">
void <code class="descname">PyList_SET_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;i</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_SET_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro form of <a class="reference internal" href="#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a> without error checking. This is
normally only used to fill in new lists where there is no previous content.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This macro “steals” a reference to <em>item</em>, and, unlike
<a class="reference internal" href="#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>, does <em>not</em> discard a reference to any item that
it being replaced; any reference in <em>list</em> at position <em>i</em> will be
leaked.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This macro used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Insert">
int <code class="descname">PyList_Insert</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;index</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*item</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Insert" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert the item <em>item</em> into list <em>list</em> in front of index <em>index</em>.  Return
<code class="docutils literal notranslate"><span class="pre">0</span></code> if successful; return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and set an exception if unsuccessful.
Analogous to <code class="docutils literal notranslate"><span class="pre">list.insert(index,</span> <span class="pre">item)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>index</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Append">
int <code class="descname">PyList_Append</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*item</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Append" title="Permalink to this definition">¶</a></dt>
<dd><p>Append the object <em>item</em> at the end of list <em>list</em>. Return <code class="docutils literal notranslate"><span class="pre">0</span></code> if
successful; return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and set an exception if unsuccessful.  Analogous
to <code class="docutils literal notranslate"><span class="pre">list.append(item)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyList_GetSlice">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyList_GetSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;low</em>, Py_ssize_t<em>&nbsp;high</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_GetSlice" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a list of the objects in <em>list</em> containing the objects <em>between</em> <em>low</em>
and <em>high</em>.  Return <em>NULL</em> and set an exception if unsuccessful.  Analogous
to <code class="docutils literal notranslate"><span class="pre">list[low:high]</span></code>.  Negative indices, as when slicing from Python, are not
supported.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>low</em> and <em>high</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_SetSlice">
int <code class="descname">PyList_SetSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em>, Py_ssize_t<em>&nbsp;low</em>, Py_ssize_t<em>&nbsp;high</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*itemlist</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_SetSlice" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the slice of <em>list</em> between <em>low</em> and <em>high</em> to the contents of
<em>itemlist</em>.  Analogous to <code class="docutils literal notranslate"><span class="pre">list[low:high]</span> <span class="pre">=</span> <span class="pre">itemlist</span></code>. The <em>itemlist</em> may
be <em>NULL</em>, indicating the assignment of an empty list (slice deletion).
Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.  Negative indices, as when
slicing from Python, are not supported.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>low</em> and <em>high</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Sort">
int <code class="descname">PyList_Sort</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Sort" title="Permalink to this definition">¶</a></dt>
<dd><p>Sort the items of <em>list</em> in place.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">list.sort()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyList_Reverse">
int <code class="descname">PyList_Reverse</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_Reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the items of <em>list</em> in place.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is the equivalent of <code class="docutils literal notranslate"><span class="pre">list.reverse()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyList_AsTuple">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyList_AsTuple</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*list</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyList_AsTuple" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">Return a new tuple object containing the contents of <em>list</em>; equivalent to
<code class="docutils literal notranslate"><span class="pre">tuple(list)</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tuple.html"
                        title="previous chapter">Tuple Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dict.html"
                        title="next chapter">Dictionary Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/list.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dict.html" title="Dictionary Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="tuple.html" title="Tuple Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��7f����html/c-api/long.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Long Integer Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Floating Point Objects" href="float.html" />
    <link rel="prev" title="Boolean Objects" href="bool.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/long.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="float.html" title="Floating Point Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bool.html" title="Boolean Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="long-integer-objects">
<span id="longobjects"></span><h1>Long Integer Objects<a class="headerlink" href="#long-integer-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyLongObject">
<code class="descname">PyLongObject</code><a class="headerlink" href="#c.PyLongObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python long integer object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyLong_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyLong_Type</code><a class="headerlink" href="#c.PyLong_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python long integer type.
This is the same object as <code class="docutils literal notranslate"><span class="pre">long</span></code> and <code class="docutils literal notranslate"><span class="pre">types.LongType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_Check">
int <code class="descname">PyLong_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> or a subtype of
<a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_CheckExact">
int <code class="descname">PyLong_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>, but not a subtype of
<a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromLong</code><span class="sig-paren">(</span>long<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from <em>v</em>, or <em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromUnsignedLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromUnsignedLong</code><span class="sig-paren">(</span>unsigned long<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromUnsignedLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code>, or
<em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromSsize_t">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromSsize_t</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromSsize_t" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from a C <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>, or
<em>NULL</em> on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromSize_t">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromSize_t</code><span class="sig-paren">(</span>size_t<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromSize_t" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from a C <code class="xref c c-type docutils literal notranslate"><span class="pre">size_t</span></code>, or
<em>NULL</em> on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromLongLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromLongLong</code><span class="sig-paren">(</span>PY_LONG_LONG<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromLongLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>, or <em>NULL</em>
on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromUnsignedLongLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromUnsignedLongLong</code><span class="sig-paren">(</span>unsigned PY_LONG_LONG<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromUnsignedLongLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code>,
or <em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromDouble">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromDouble</code><span class="sig-paren">(</span>double<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromDouble" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> object from the integer part of <em>v</em>, or
<em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromString</code><span class="sig-paren">(</span>char<em>&nbsp;*str</em>, char<em>&nbsp;**pend</em>, int<em>&nbsp;base</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyLongObject" title="PyLongObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyLongObject</span></code></a> based on the string value in <em>str</em>, which is
interpreted according to the radix in <em>base</em>.  If <em>pend</em> is non-<em>NULL</em>,
<em>*pend</em> will point to the first character in <em>str</em> which follows the
representation of the number.  If <em>base</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the radix will be determined
based on the leading characters of <em>str</em>: if <em>str</em> starts with <code class="docutils literal notranslate"><span class="pre">'0x'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'0X'</span></code>, radix 16 will be used; if <em>str</em> starts with <code class="docutils literal notranslate"><span class="pre">'0'</span></code>, radix 8 will be
used; otherwise radix 10 will be used.  If <em>base</em> is not <code class="docutils literal notranslate"><span class="pre">0</span></code>, it must be
between <code class="docutils literal notranslate"><span class="pre">2</span></code> and <code class="docutils literal notranslate"><span class="pre">36</span></code>, inclusive.  Leading spaces are ignored.  If there are
no digits, <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromUnicode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromUnicode</code><span class="sig-paren">(</span><a class="reference internal" href="unicode.html#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*u</em>, Py_ssize_t<em>&nbsp;length</em>, int<em>&nbsp;base</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromUnicode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Convert a sequence of Unicode digits to a Python long integer value.  The first
parameter, <em>u</em>, points to the first character of the Unicode string, <em>length</em>
gives the number of characters, and <em>base</em> is the radix for the conversion.  The
radix must be in the range [2, 36]; if it is out of range, <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
will be raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> for <em>length</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_FromVoidPtr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyLong_FromVoidPtr</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_FromVoidPtr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Python integer or long integer from the pointer <em>p</em>. The pointer value
can be retrieved from the resulting value using <a class="reference internal" href="#c.PyLong_AsVoidPtr" title="PyLong_AsVoidPtr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_AsVoidPtr()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>If the integer is larger than LONG_MAX, a positive long integer is returned.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsLong">
long <code class="descname">PyLong_AsLong</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsLong" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> representation of the contents of <em>pylong</em>.  If
<em>pylong</em> is greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">LONG_MAX</span></code>, an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised
and <code class="docutils literal notranslate"><span class="pre">-1</span></code> will be returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsLongAndOverflow">
long <code class="descname">PyLong_AsLongAndOverflow</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em>, int<em>&nbsp;*overflow</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsLongAndOverflow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> representation of the contents of
<em>pylong</em>.  If <em>pylong</em> is greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">LONG_MAX</span></code> or less
than <code class="xref py py-const docutils literal notranslate"><span class="pre">LONG_MIN</span></code>, set <em>*overflow</em> to <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>,
respectively, and return <code class="docutils literal notranslate"><span class="pre">-1</span></code>; otherwise, set <em>*overflow</em> to
<code class="docutils literal notranslate"><span class="pre">0</span></code>.  If any other exception occurs (for example a TypeError or
MemoryError), then <code class="docutils literal notranslate"><span class="pre">-1</span></code> will be returned and <em>*overflow</em> will
be <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsLongLongAndOverflow">
PY_LONG_LONG <code class="descname">PyLong_AsLongLongAndOverflow</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em>, int<em>&nbsp;*overflow</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsLongLongAndOverflow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> representation of the contents of
<em>pylong</em>.  If <em>pylong</em> is greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">PY_LLONG_MAX</span></code> or less
than <code class="xref py py-const docutils literal notranslate"><span class="pre">PY_LLONG_MIN</span></code>, set <em>*overflow</em> to <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>,
respectively, and return <code class="docutils literal notranslate"><span class="pre">-1</span></code>; otherwise, set <em>*overflow</em> to
<code class="docutils literal notranslate"><span class="pre">0</span></code>.  If any other exception occurs (for example a TypeError or
MemoryError), then <code class="docutils literal notranslate"><span class="pre">-1</span></code> will be returned and <em>*overflow</em> will
be <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsSsize_t">
Py_ssize_t <code class="descname">PyLong_AsSsize_t</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsSsize_t" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> representation of the contents of <em>pylong</em>.  If
<em>pylong</em> is greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">PY_SSIZE_T_MAX</span></code>, an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised
and <code class="docutils literal notranslate"><span class="pre">-1</span></code> will be returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsUnsignedLong">
unsigned long <code class="descname">PyLong_AsUnsignedLong</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsUnsignedLong" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code> representation of the contents of <em>pylong</em>.
If <em>pylong</em> is greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">ULONG_MAX</span></code>, an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is
raised.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsLongLong">
PY_LONG_LONG <code class="descname">PyLong_AsLongLong</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsLongLong" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> from a Python long integer.  If
<em>pylong</em> cannot be represented as a <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>, an
<a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised and <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsUnsignedLongLong">
unsigned PY_LONG_LONG <code class="descname">PyLong_AsUnsignedLongLong</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsUnsignedLongLong" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code> from a Python long integer. If
<em>pylong</em> cannot be represented as an <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code>, an
<a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised and <code class="docutils literal notranslate"><span class="pre">(unsigned</span> <span class="pre">long</span> <span class="pre">long)-1</span></code> is
returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>A negative <em>pylong</em> now raises <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>, not
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsUnsignedLongMask">
unsigned long <code class="descname">PyLong_AsUnsignedLongMask</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsUnsignedLongMask" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code> from a Python long integer, without checking
for overflow.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsUnsignedLongLongMask">
unsigned PY_LONG_LONG <code class="descname">PyLong_AsUnsignedLongLongMask</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*io</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsUnsignedLongLongMask" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code> from a Python long integer, without
checking for overflow.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsDouble">
double <code class="descname">PyLong_AsDouble</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsDouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> representation of the contents of <em>pylong</em>.  If
<em>pylong</em> cannot be approximately represented as a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>, an
<a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> exception is raised and <code class="docutils literal notranslate"><span class="pre">-1.0</span></code> will be returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyLong_AsVoidPtr">
void* <code class="descname">PyLong_AsVoidPtr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pylong</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyLong_AsVoidPtr" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a Python integer or long integer <em>pylong</em> to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code> pointer.
If <em>pylong</em> cannot be converted, an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> will be raised.  This
is only assured to produce a usable <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code> pointer for values created
with <a class="reference internal" href="#c.PyLong_FromVoidPtr" title="PyLong_FromVoidPtr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_FromVoidPtr()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>For values outside 0..LONG_MAX, both signed and unsigned integers are accepted.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="bool.html"
                        title="previous chapter">Boolean Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="float.html"
                        title="next chapter">Floating Point Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/long.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="float.html" title="Floating Point Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="bool.html" title="Boolean Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\S�f�>�>html/c-api/mapping.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Mapping Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Iterator Protocol" href="iter.html" />
    <link rel="prev" title="Sequence Protocol" href="sequence.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/mapping.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="iter.html" title="Iterator Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sequence.html" title="Sequence Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="mapping-protocol">
<span id="mapping"></span><h1>Mapping Protocol<a class="headerlink" href="#mapping-protocol" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyMapping_Check">
int <code class="descname">PyMapping_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the object provides mapping protocol, and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.  This
function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_Size">
Py_ssize_t <code class="descname">PyMapping_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Size" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyMapping_Length">
Py_ssize_t <code class="descname">PyMapping_Length</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Length" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Returns the number of keys in object <em>o</em> on success, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.  For
objects that do not provide mapping protocol, this is equivalent to the Python
expression <code class="docutils literal notranslate"><span class="pre">len(o)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>These functions returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_DelItemString">
int <code class="descname">PyMapping_DelItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, char<em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_DelItemString" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the mapping for object <em>key</em> from the object <em>o</em>. Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is equivalent to the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o[key]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_DelItem">
int <code class="descname">PyMapping_DelItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_DelItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the mapping for object <em>key</em> from the object <em>o</em>. Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is equivalent to the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o[key]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_HasKeyString">
int <code class="descname">PyMapping_HasKeyString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, char<em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_HasKeyString" title="Permalink to this definition">¶</a></dt>
<dd><p>On success, return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the mapping object has the key <em>key</em> and <code class="docutils literal notranslate"><span class="pre">0</span></code>
otherwise.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">o[key]</span></code>, returning <code class="docutils literal notranslate"><span class="pre">True</span></code> on success
and <code class="docutils literal notranslate"><span class="pre">False</span></code> on an exception.  This function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_HasKey">
int <code class="descname">PyMapping_HasKey</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_HasKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the mapping object has the key <em>key</em> and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.
This is equivalent to <code class="docutils literal notranslate"><span class="pre">o[key]</span></code>, returning <code class="docutils literal notranslate"><span class="pre">True</span></code> on success and <code class="docutils literal notranslate"><span class="pre">False</span></code>
on an exception.  This function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_Keys">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMapping_Keys</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Keys" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>On success, return a list of the keys in object <em>o</em>.  On failure, return <em>NULL</em>.
This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">o.keys()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_Values">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMapping_Values</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Values" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>On success, return a list of the values in object <em>o</em>.  On failure, return
<em>NULL</em>. This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">o.values()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_Items">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMapping_Items</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_Items" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>On success, return a list of the items in object <em>o</em>, where each item is a tuple
containing a key-value pair.  On failure, return <em>NULL</em>. This is equivalent to
the Python expression <code class="docutils literal notranslate"><span class="pre">o.items()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_GetItemString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMapping_GetItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, char<em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_GetItemString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return element of <em>o</em> corresponding to the object <em>key</em> or <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o[key]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMapping_SetItemString">
int <code class="descname">PyMapping_SetItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, char<em>&nbsp;*key</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMapping_SetItemString" title="Permalink to this definition">¶</a></dt>
<dd><p>Map the object <em>key</em> to the value <em>v</em> in object <em>o</em>. Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.
This is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o[key]</span> <span class="pre">=</span> <span class="pre">v</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="sequence.html"
                        title="previous chapter">Sequence Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="iter.html"
                        title="next chapter">Iterator Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/mapping.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="iter.html" title="Iterator Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="sequence.html" title="Sequence Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\	�c�?�?html/c-api/marshal.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Data marshalling support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Parsing arguments and building values" href="arg.html" />
    <link rel="prev" title="Importing Modules" href="import.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/marshal.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="arg.html" title="Parsing arguments and building values"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="import.html" title="Importing Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-marshalling-support">
<span id="marshalling-utils"></span><h1>Data marshalling support<a class="headerlink" href="#data-marshalling-support" title="Permalink to this headline">¶</a></h1>
<p>These routines allow C code to work with serialized objects using the same
data format as the <a class="reference internal" href="../library/marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module.  There are functions to write data
into the serialization format, and additional functions that can be used to
read the data back.  Files used to store marshalled data must be opened in
binary mode.</p>
<p>Numeric values are stored with the least significant byte first.</p>
<p>The module supports two versions of the data format: version <code class="docutils literal notranslate"><span class="pre">0</span></code> is the
historical version, version <code class="docutils literal notranslate"><span class="pre">1</span></code> (new in Python 2.4) shares interned strings in
the file, and upon unmarshalling.  Version 2 (new in Python 2.5) uses a binary
format for floating point numbers.  <em>Py_MARSHAL_VERSION</em> indicates the current
file format (currently 2).</p>
<dl class="function">
<dt id="c.PyMarshal_WriteLongToFile">
void <code class="descname">PyMarshal_WriteLongToFile</code><span class="sig-paren">(</span>long<em>&nbsp;value</em>, FILE<em>&nbsp;*file</em>, int<em>&nbsp;version</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_WriteLongToFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Marshal a <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> integer, <em>value</em>, to <em>file</em>.  This will only write
the least-significant 32 bits of <em>value</em>; regardless of the size of the
native <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>version</em> indicates the file format.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_WriteObjectToFile">
void <code class="descname">PyMarshal_WriteObjectToFile</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em>, FILE<em>&nbsp;*file</em>, int<em>&nbsp;version</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_WriteObjectToFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Marshal a Python object, <em>value</em>, to <em>file</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>version</em> indicates the file format.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_WriteObjectToString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMarshal_WriteObjectToString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em>, int<em>&nbsp;version</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_WriteObjectToString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a string object containing the marshalled representation of <em>value</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>version</em> indicates the file format.</p>
</div>
</dd></dl>

<p>The following functions allow marshalled values to be read back in.</p>
<p>XXX What about error detection?  It appears that reading past the end of the
file will always result in a negative numeric value (where that’s relevant),
but it’s not clear that negative values won’t be handled properly when there’s
no error.  What’s the right way to tell? Should only non-negative values be
written using these routines?</p>
<dl class="function">
<dt id="c.PyMarshal_ReadLongFromFile">
long <code class="descname">PyMarshal_ReadLongFromFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*file</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_ReadLongFromFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> from the data stream in a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> opened
for reading.  Only a 32-bit value can be read in using this function,
regardless of the native size of <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_ReadShortFromFile">
int <code class="descname">PyMarshal_ReadShortFromFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*file</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_ReadShortFromFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">short</span></code> from the data stream in a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> opened
for reading.  Only a 16-bit value can be read in using this function,
regardless of the native size of <code class="xref c c-type docutils literal notranslate"><span class="pre">short</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_ReadObjectFromFile">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMarshal_ReadObjectFromFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*file</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_ReadObjectFromFile" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a Python object from the data stream in a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> opened for
reading.  On error, sets the appropriate exception (<a class="reference internal" href="../library/exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> or
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>) and returns <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_ReadLastObjectFromFile">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMarshal_ReadLastObjectFromFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*file</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_ReadLastObjectFromFile" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a Python object from the data stream in a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> opened for
reading.  Unlike <a class="reference internal" href="#c.PyMarshal_ReadObjectFromFile" title="PyMarshal_ReadObjectFromFile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMarshal_ReadObjectFromFile()</span></code></a>, this function
assumes that no further objects will be read from the file, allowing it to
aggressively load file data into memory so that the de-serialization can
operate from data in memory rather than reading a byte at a time from the
file.  Only use these variant if you are certain that you won’t be reading
anything else from the file.  On error, sets the appropriate exception
(<a class="reference internal" href="../library/exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>) and returns <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMarshal_ReadObjectFromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMarshal_ReadObjectFromString</code><span class="sig-paren">(</span>char<em>&nbsp;*string</em>, Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMarshal_ReadObjectFromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a Python object from the data stream in a character buffer
containing <em>len</em> bytes pointed to by <em>string</em>.  On error, sets the
appropriate exception (<a class="reference internal" href="../library/exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>) and returns
<em>NULL</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>len</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="import.html"
                        title="previous chapter">Importing Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="arg.html"
                        title="next chapter">Parsing arguments and building values</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/marshal.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="arg.html" title="Parsing arguments and building values"
             >next</a> |</li>
        <li class="right" >
          <a href="import.html" title="Importing Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\UV� ÀÀhtml/c-api/memory.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Memory Management &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Object Implementation Support" href="objimpl.html" />
    <link rel="prev" title="Initialization, Finalization, and Threads" href="init.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/memory.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="objimpl.html" title="Object Implementation Support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="init.html" title="Initialization, Finalization, and Threads"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="memory-management">
<span id="memory"></span><h1>Memory Management<a class="headerlink" href="#memory-management" title="Permalink to this headline">¶</a></h1>
<div class="section" id="overview">
<span id="memoryoverview"></span><h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2>
<p>Memory management in Python involves a private heap containing all Python
objects and data structures. The management of this private heap is ensured
internally by the <em>Python memory manager</em>.  The Python memory manager has
different components which deal with various dynamic storage management aspects,
like sharing, segmentation, preallocation or caching.</p>
<p>At the lowest level, a raw memory allocator ensures that there is enough room in
the private heap for storing all Python-related data by interacting with the
memory manager of the operating system. On top of the raw memory allocator,
several object-specific allocators operate on the same heap and implement
distinct memory management policies adapted to the peculiarities of every object
type. For example, integer objects are managed differently within the heap than
strings, tuples or dictionaries because integers imply different storage
requirements and speed/space tradeoffs. The Python memory manager thus delegates
some of the work to the object-specific allocators, but ensures that the latter
operate within the bounds of the private heap.</p>
<p>It is important to understand that the management of the Python heap is
performed by the interpreter itself and that the user has no control over it,
even if they regularly manipulate object pointers to memory blocks inside that
heap.  The allocation of heap space for Python objects and other internal
buffers is performed on demand by the Python memory manager through the Python/C
API functions listed in this document.</p>
<p id="index-0">To avoid memory corruption, extension writers should never try to operate on
Python objects with the functions exported by the C library: <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>,
<code class="xref c c-func docutils literal notranslate"><span class="pre">calloc()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.  This will result in  mixed
calls between the C allocator and the Python memory manager with fatal
consequences, because they implement different algorithms and operate on
different heaps.  However, one may safely allocate and release memory blocks
with the C library allocator for individual purposes, as shown in the following
example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">res</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">buf</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span> <span class="n">malloc</span><span class="p">(</span><span class="n">BUFSIZ</span><span class="p">);</span> <span class="cm">/* for I/O */</span>

<span class="k">if</span> <span class="p">(</span><span class="n">buf</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">PyErr_NoMemory</span><span class="p">();</span>
<span class="p">...</span><span class="n">Do</span> <span class="n">some</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">operation</span> <span class="n">involving</span> <span class="n">buf</span><span class="p">...</span>
<span class="n">res</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span>
<span class="n">free</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span> <span class="cm">/* malloc&#39;ed */</span>
<span class="k">return</span> <span class="n">res</span><span class="p">;</span>
</pre></div>
</div>
<p>In this example, the memory request for the I/O buffer is handled by the C
library allocator. The Python memory manager is involved only in the allocation
of the string object returned as a result.</p>
<p>In most situations, however, it is recommended to allocate memory from the
Python heap specifically because the latter is under control of the Python
memory manager. For example, this is required when the interpreter is extended
with new object types written in C. Another reason for using the Python heap is
the desire to <em>inform</em> the Python memory manager about the memory needs of the
extension module. Even when the requested memory is used exclusively for
internal, highly-specific purposes, delegating all memory requests to the Python
memory manager causes the interpreter to have a more accurate image of its
memory footprint as a whole. Consequently, under certain circumstances, the
Python memory manager may or may not trigger appropriate actions, like garbage
collection, memory compaction or other preventive procedures. Note that by using
the C library allocator as shown in the previous example, the allocated memory
for the I/O buffer escapes completely the Python memory manager.</p>
</div>
<div class="section" id="memory-interface">
<span id="memoryinterface"></span><h2>Memory Interface<a class="headerlink" href="#memory-interface" title="Permalink to this headline">¶</a></h2>
<p>The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap:</p>
<dl class="function">
<dt id="c.PyMem_Malloc">
void* <code class="descname">PyMem_Malloc</code><span class="sig-paren">(</span>size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_Malloc" title="Permalink to this definition">¶</a></dt>
<dd><p>Allocates <em>n</em> bytes and returns a pointer of type <code class="xref c c-type docutils literal notranslate"><span class="pre">void*</span></code> to the
allocated memory, or <em>NULL</em> if the request fails. Requesting zero bytes returns
a distinct non-<em>NULL</em> pointer if possible, as if <code class="docutils literal notranslate"><span class="pre">PyMem_Malloc(1)</span></code> had
been called instead. The memory will not have been initialized in any way.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMem_Realloc">
void* <code class="descname">PyMem_Realloc</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em>, size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_Realloc" title="Permalink to this definition">¶</a></dt>
<dd><p>Resizes the memory block pointed to by <em>p</em> to <em>n</em> bytes. The contents will be
unchanged to the minimum of the old and the new sizes. If <em>p</em> is <em>NULL</em>, the
call is equivalent to <code class="docutils literal notranslate"><span class="pre">PyMem_Malloc(n)</span></code>; else if <em>n</em> is equal to zero,
the memory block is resized but is not freed, and the returned pointer is
non-<em>NULL</em>.  Unless <em>p</em> is <em>NULL</em>, it must have been returned by a previous call
to <a class="reference internal" href="#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a> or <a class="reference internal" href="#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>. If the request fails,
<a class="reference internal" href="#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a> returns <em>NULL</em> and <em>p</em> remains a valid pointer to the
previous memory area.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMem_Free">
void <code class="descname">PyMem_Free</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_Free" title="Permalink to this definition">¶</a></dt>
<dd><p>Frees the memory block pointed to by <em>p</em>, which must have been returned by a
previous call to <a class="reference internal" href="#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a> or <a class="reference internal" href="#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>.  Otherwise, or
if <code class="docutils literal notranslate"><span class="pre">PyMem_Free(p)</span></code> has been called before, undefined behavior occurs. If
<em>p</em> is <em>NULL</em>, no operation is performed.</p>
</dd></dl>

<p>The following type-oriented macros are provided for convenience.  Note  that
<em>TYPE</em> refers to any C type.</p>
<dl class="function">
<dt id="c.PyMem_New">
TYPE* <code class="descname">PyMem_New</code><span class="sig-paren">(</span>TYPE, size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_New" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a>, but allocates <code class="docutils literal notranslate"><span class="pre">(n</span> <span class="pre">*</span> <span class="pre">sizeof(TYPE))</span></code> bytes of
memory.  Returns a pointer cast to <code class="xref c c-type docutils literal notranslate"><span class="pre">TYPE*</span></code>.  The memory will not have
been initialized in any way.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMem_Resize">
TYPE* <code class="descname">PyMem_Resize</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em>, TYPE, size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_Resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>, but the memory block is resized to <code class="docutils literal notranslate"><span class="pre">(n</span> <span class="pre">*</span>
<span class="pre">sizeof(TYPE))</span></code> bytes.  Returns a pointer cast to <code class="xref c c-type docutils literal notranslate"><span class="pre">TYPE*</span></code>. On return,
<em>p</em> will be a pointer to the new memory area, or <em>NULL</em> in the event of
failure.  This is a C preprocessor macro; p is always reassigned.  Save
the original value of p to avoid losing memory when handling errors.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMem_Del">
void <code class="descname">PyMem_Del</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMem_Del" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a>.</p>
</dd></dl>

<p>In addition, the following macro sets are provided for calling the Python memory
allocator directly, without involving the C API functions listed above. However,
note that their use does not preserve binary compatibility across Python
versions and is therefore deprecated in extension modules.</p>
<p><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_MALLOC()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_REALLOC()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_FREE()</span></code>.</p>
<p><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_NEW()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_RESIZE()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_DEL()</span></code>.</p>
</div>
<div class="section" id="object-allocators">
<h2>Object allocators<a class="headerlink" href="#object-allocators" title="Permalink to this headline">¶</a></h2>
<p>The following function sets, modeled after the ANSI C standard, but specifying
behavior when requesting zero bytes, are available for allocating and releasing
memory from the Python heap.</p>
<p>By default, these functions use <a class="reference internal" href="#pymalloc"><span class="std std-ref">pymalloc memory allocator</span></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">GIL</span></a> must be held when using these
functions.</p>
</div>
<dl class="function">
<dt id="c.PyObject_Malloc">
void* <code class="descname">PyObject_Malloc</code><span class="sig-paren">(</span>size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Malloc" title="Permalink to this definition">¶</a></dt>
<dd><p>Allocates <em>n</em> bytes and returns a pointer of type <code class="xref c c-type docutils literal notranslate"><span class="pre">void*</span></code> to the
allocated memory, or <em>NULL</em> if the request fails.</p>
<p>Requesting zero bytes returns a distinct non-<em>NULL</em> pointer if possible, as
if <code class="docutils literal notranslate"><span class="pre">PyObject_Malloc(1)</span></code> had been called instead. The memory will not have
been initialized in any way.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Realloc">
void* <code class="descname">PyObject_Realloc</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em>, size_t<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Realloc" title="Permalink to this definition">¶</a></dt>
<dd><p>Resizes the memory block pointed to by <em>p</em> to <em>n</em> bytes. The contents will be
unchanged to the minimum of the old and the new sizes.</p>
<p>If <em>p</em> is <em>NULL</em>, the call is equivalent to <code class="docutils literal notranslate"><span class="pre">PyObject_Malloc(n)</span></code>; else if <em>n</em>
is equal to zero, the memory block is resized but is not freed, and the
returned pointer is non-<em>NULL</em>.</p>
<p>Unless <em>p</em> is <em>NULL</em>, it must have been returned by a previous call to
<a class="reference internal" href="#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a> or <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Calloc()</span></code>.</p>
<p>If the request fails, <a class="reference internal" href="#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a> returns <em>NULL</em> and <em>p</em> remains
a valid pointer to the previous memory area.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Free">
void <code class="descname">PyObject_Free</code><span class="sig-paren">(</span>void<em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Free" title="Permalink to this definition">¶</a></dt>
<dd><p>Frees the memory block pointed to by <em>p</em>, which must have been returned by a
previous call to <a class="reference internal" href="#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a> or
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Calloc()</span></code>.  Otherwise, or if <code class="docutils literal notranslate"><span class="pre">PyObject_Free(p)</span></code> has been called
before, undefined behavior occurs.</p>
<p>If <em>p</em> is <em>NULL</em>, no operation is performed.</p>
</dd></dl>

<p>In addition, the following macro sets are provided:</p>
<ul class="simple">
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_MALLOC()</span></code>: alias to <a class="reference internal" href="#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a></li>
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_REALLOC()</span></code>: alias to <a class="reference internal" href="#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a></li>
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_FREE()</span></code>: alias to <a class="reference internal" href="#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a></li>
<li><a class="reference internal" href="allocation.html#c.PyObject_Del" title="PyObject_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Del()</span></code></a>: alias to <a class="reference internal" href="#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a></li>
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_DEL()</span></code>: alias to <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_FREE()</span></code> (so finally an alias
to <a class="reference internal" href="#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a>)</li>
</ul>
</div>
<div class="section" id="the-pymalloc-allocator">
<span id="pymalloc"></span><h2>The pymalloc allocator<a class="headerlink" href="#the-pymalloc-allocator" title="Permalink to this headline">¶</a></h2>
<p>Python has a <em>pymalloc</em> allocator optimized for small objects (smaller or equal
to 512 bytes) with a short lifetime. It uses memory mappings called “arenas”
with a fixed size of 256 KiB. It falls back to <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and
<code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code> for allocations larger than 512 bytes.</p>
<p><em>pymalloc</em> is the default allocator of <a class="reference internal" href="#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>.</p>
<p>The arena allocator uses the following functions:</p>
<ul class="simple">
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">mmap()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">munmap()</span></code> if available,</li>
<li><code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> otherwise.</li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.7: </span>The threshold changed from 256 to 512 bytes. The arena allocator now
uses <code class="xref c c-func docutils literal notranslate"><span class="pre">mmap()</span></code> if available.</p>
</div>
</div>
<div class="section" id="examples">
<span id="memoryexamples"></span><h2>Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Here is the example from section <a class="reference internal" href="#memoryoverview"><span class="std std-ref">Overview</span></a>, rewritten so that the
I/O buffer is allocated from the Python heap by using the first function set:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">res</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">buf</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span> <span class="n">PyMem_Malloc</span><span class="p">(</span><span class="n">BUFSIZ</span><span class="p">);</span> <span class="cm">/* for I/O */</span>

<span class="k">if</span> <span class="p">(</span><span class="n">buf</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">PyErr_NoMemory</span><span class="p">();</span>
<span class="cm">/* ...Do some I/O operation involving buf... */</span>
<span class="n">res</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span>
<span class="n">PyMem_Free</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span> <span class="cm">/* allocated with PyMem_Malloc */</span>
<span class="k">return</span> <span class="n">res</span><span class="p">;</span>
</pre></div>
</div>
<p>The same code using the type-oriented function set:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">res</span><span class="p">;</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">buf</span> <span class="o">=</span> <span class="n">PyMem_New</span><span class="p">(</span><span class="kt">char</span><span class="p">,</span> <span class="n">BUFSIZ</span><span class="p">);</span> <span class="cm">/* for I/O */</span>

<span class="k">if</span> <span class="p">(</span><span class="n">buf</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">PyErr_NoMemory</span><span class="p">();</span>
<span class="cm">/* ...Do some I/O operation involving buf... */</span>
<span class="n">res</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span>
<span class="n">PyMem_Del</span><span class="p">(</span><span class="n">buf</span><span class="p">);</span> <span class="cm">/* allocated with PyMem_New */</span>
<span class="k">return</span> <span class="n">res</span><span class="p">;</span>
</pre></div>
</div>
<p>Note that in the two examples above, the buffer is always manipulated via
functions belonging to the same set. Indeed, it is required to use the same
memory API family for a given memory block, so that the risk of mixing different
allocators is reduced to a minimum. The following code sequence contains two
errors, one of which is labeled as <em>fatal</em> because it mixes two different
allocators operating on different heaps.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">char</span> <span class="o">*</span><span class="n">buf1</span> <span class="o">=</span> <span class="n">PyMem_New</span><span class="p">(</span><span class="kt">char</span><span class="p">,</span> <span class="n">BUFSIZ</span><span class="p">);</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">buf2</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span> <span class="n">malloc</span><span class="p">(</span><span class="n">BUFSIZ</span><span class="p">);</span>
<span class="kt">char</span> <span class="o">*</span><span class="n">buf3</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span> <span class="n">PyMem_Malloc</span><span class="p">(</span><span class="n">BUFSIZ</span><span class="p">);</span>
<span class="p">...</span>
<span class="n">PyMem_Del</span><span class="p">(</span><span class="n">buf3</span><span class="p">);</span>  <span class="cm">/* Wrong -- should be PyMem_Free() */</span>
<span class="n">free</span><span class="p">(</span><span class="n">buf2</span><span class="p">);</span>       <span class="cm">/* Right -- allocated via malloc() */</span>
<span class="n">free</span><span class="p">(</span><span class="n">buf1</span><span class="p">);</span>       <span class="cm">/* Fatal -- should be PyMem_Del()  */</span>
</pre></div>
</div>
<p>In addition to the functions aimed at handling raw memory blocks from the Python
heap, objects in Python are allocated and released with <a class="reference internal" href="allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a>,
<a class="reference internal" href="allocation.html#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_NewVar()</span></code></a> and <a class="reference internal" href="allocation.html#c.PyObject_Del" title="PyObject_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Del()</span></code></a>.</p>
<p>These will be explained in the next chapter on defining and implementing new
object types in C.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Memory Management</a><ul>
<li><a class="reference internal" href="#overview">Overview</a></li>
<li><a class="reference internal" href="#memory-interface">Memory Interface</a></li>
<li><a class="reference internal" href="#object-allocators">Object allocators</a></li>
<li><a class="reference internal" href="#the-pymalloc-allocator">The pymalloc allocator</a></li>
<li><a class="reference internal" href="#examples">Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="init.html"
                        title="previous chapter">Initialization, Finalization, and Threads</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="objimpl.html"
                        title="next chapter">Object Implementation Support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/memory.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="objimpl.html" title="Object Implementation Support"
             >next</a> |</li>
        <li class="right" >
          <a href="init.html" title="Initialization, Finalization, and Threads"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ۏ�
&5&5html/c-api/method.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Method Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="File Objects" href="file.html" />
    <link rel="prev" title="Function Objects" href="function.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/method.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="file.html" title="File Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="function.html" title="Function Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="method-objects">
<span id="id1"></span><h1>Method Objects<a class="headerlink" href="#method-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">There are some useful functions that are useful for working with method objects.</p>
<dl class="var">
<dt id="c.PyMethod_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyMethod_Type</code><a class="headerlink" href="#c.PyMethod_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python method type.  This
is exposed to Python programs as <code class="docutils literal notranslate"><span class="pre">types.MethodType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_Check">
int <code class="descname">PyMethod_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>o</em> is a method object (has type <a class="reference internal" href="#c.PyMethod_Type" title="PyMethod_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyMethod_Type</span></code></a>).  The
parameter must not be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*func</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*class</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new method object, with <em>func</em> being any callable object; this is the
function that will be called when the method is called.  If this method should
be bound to an instance, <em>self</em> should be the instance and <em>class</em> should be the
class of <em>self</em>, otherwise <em>self</em> should be <em>NULL</em> and <em>class</em> should be the
class which provides the unbound method..</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_Class">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_Class</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_Class" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the class object from which the method <em>meth</em> was created; if this was
created from an instance, it will be the class of the instance.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_GET_CLASS">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_GET_CLASS</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_GET_CLASS" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Macro version of <a class="reference internal" href="#c.PyMethod_Class" title="PyMethod_Class"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMethod_Class()</span></code></a> which avoids error checking.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_Function">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_Function</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_Function" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the function object associated with the method <em>meth</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_GET_FUNCTION">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_GET_FUNCTION</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_GET_FUNCTION" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Macro version of <a class="reference internal" href="#c.PyMethod_Function" title="PyMethod_Function"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMethod_Function()</span></code></a> which avoids error checking.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_Self">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_Self</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_Self" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the instance associated with the method <em>meth</em> if it is bound, otherwise
return <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_GET_SELF">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyMethod_GET_SELF</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_GET_SELF" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Macro version of <a class="reference internal" href="#c.PyMethod_Self" title="PyMethod_Self"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMethod_Self()</span></code></a> which avoids error checking.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMethod_ClearFreeList">
int <code class="descname">PyMethod_ClearFreeList</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMethod_ClearFreeList" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the free list. Return the total number of freed items.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="function.html"
                        title="previous chapter">Function Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="file.html"
                        title="next chapter">File Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/method.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="file.html" title="File Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="function.html" title="Function Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�	@��B�Bhtml/c-api/module.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Module Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Iterator Objects" href="iterator.html" />
    <link rel="prev" title="File Objects" href="file.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/module.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="iterator.html" title="Iterator Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="file.html" title="File Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-objects">
<span id="moduleobjects"></span><h1>Module Objects<a class="headerlink" href="#module-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">There are only a few functions special to module objects.</p>
<dl class="var">
<dt id="c.PyModule_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyModule_Type</code><a class="headerlink" href="#c.PyModule_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python module type.  This
is exposed to Python programs as <code class="docutils literal notranslate"><span class="pre">types.ModuleType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_Check">
int <code class="descname">PyModule_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a module object, or a subtype of a module object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_CheckExact">
int <code class="descname">PyModule_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a module object, but not a subtype of
<a class="reference internal" href="#c.PyModule_Type" title="PyModule_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyModule_Type</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyModule_New</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">Return a new module object with the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> attribute set to <em>name</em>.
Only the module’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> attributes are filled in;
the caller is responsible for providing a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> attribute.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_GetDict">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyModule_GetDict</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_GetDict" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p id="index-3">Return the dictionary object that implements <em>module</em>’s namespace; this object
is the same as the <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute of the module object.  This
function never fails.  It is recommended extensions use other
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyModule_*()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_*()</span></code> functions rather than directly
manipulate a module’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_GetName">
char* <code class="descname">PyModule_GetName</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_GetName" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Return <em>module</em>’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> value.  If the module does not provide one,
or if it is not a string, <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> is raised and <em>NULL</em> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_GetFilename">
char* <code class="descname">PyModule_GetFilename</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_GetFilename" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">Return the name of the file from which <em>module</em> was loaded using <em>module</em>’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> attribute.  If this is not defined, or if it is not a string,
raise <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> and return <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_AddObject">
int <code class="descname">PyModule_AddObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em>, const char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_AddObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an object to <em>module</em> as <em>name</em>.  This is a convenience function which can
be used from the module’s initialization function.  This steals a reference to
<em>value</em>.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error, <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_AddIntConstant">
int <code class="descname">PyModule_AddIntConstant</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em>, const char<em>&nbsp;*name</em>, long<em>&nbsp;value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_AddIntConstant" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an integer constant to <em>module</em> as <em>name</em>.  This convenience function can be
used from the module’s initialization function. Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error, <code class="docutils literal notranslate"><span class="pre">0</span></code> on
success.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_AddStringConstant">
int <code class="descname">PyModule_AddStringConstant</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em>, const char<em>&nbsp;*name</em>, const char<em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_AddStringConstant" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a string constant to <em>module</em> as <em>name</em>.  This convenience function can be
used from the module’s initialization function.  The string <em>value</em> must be
null-terminated.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error, <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_AddIntMacro">
int <code class="descname">PyModule_AddIntMacro</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em>, macro<span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_AddIntMacro" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an int constant to <em>module</em>. The name and the value are taken from
<em>macro</em>. For example <code class="docutils literal notranslate"><span class="pre">PyModule_AddIntMacro(module,</span> <span class="pre">AF_INET)</span></code> adds the int
constant <em>AF_INET</em> with the value of <em>AF_INET</em> to <em>module</em>.
Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error, <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyModule_AddStringMacro">
int <code class="descname">PyModule_AddStringMacro</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*module</em>, macro<span class="sig-paren">)</span><a class="headerlink" href="#c.PyModule_AddStringMacro" title="Permalink to this definition">¶</a></dt>
<dd><blockquote>
<div>Add a string constant to <em>module</em>.</div></blockquote>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="file.html"
                        title="previous chapter">File Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="iterator.html"
                        title="next chapter">Iterator Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/module.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="iterator.html" title="Iterator Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="file.html" title="File Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��s�[[html/c-api/none.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>The None Object &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Plain Integer Objects" href="int.html" />
    <link rel="prev" title="Type Objects" href="type.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/none.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="int.html" title="Plain Integer Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="type.html" title="Type Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-none-object">
<span id="noneobject"></span><h1>The <code class="docutils literal notranslate"><span class="pre">None</span></code> Object<a class="headerlink" href="#the-none-object" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Note that the <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> for <code class="docutils literal notranslate"><span class="pre">None</span></code> is not directly exposed in the
Python/C API.  Since <code class="docutils literal notranslate"><span class="pre">None</span></code> is a singleton, testing for object identity (using
<code class="docutils literal notranslate"><span class="pre">==</span></code> in C) is sufficient. There is no <code class="xref c c-func docutils literal notranslate"><span class="pre">PyNone_Check()</span></code> function for the
same reason.</p>
<dl class="var">
<dt id="c.Py_None">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_None</code><a class="headerlink" href="#c.Py_None" title="Permalink to this definition">¶</a></dt>
<dd><p>The Python <code class="docutils literal notranslate"><span class="pre">None</span></code> object, denoting lack of value.  This object has no methods.
It needs to be treated just like any other object with respect to reference
counts.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_RETURN_NONE">
<code class="descname">Py_RETURN_NONE</code><a class="headerlink" href="#c.Py_RETURN_NONE" title="Permalink to this definition">¶</a></dt>
<dd><p>Properly handle returning <a class="reference internal" href="#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> from within a C function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="type.html"
                        title="previous chapter">Type Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="int.html"
                        title="next chapter">Plain Integer Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/none.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="int.html" title="Plain Integer Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="type.html" title="Type Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�9�½½html/c-api/number.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Number Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Sequence Protocol" href="sequence.html" />
    <link rel="prev" title="Object Protocol" href="object.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/number.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sequence.html" title="Sequence Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="object.html" title="Object Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="number-protocol">
<span id="number"></span><h1>Number Protocol<a class="headerlink" href="#number-protocol" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyNumber_Check">
int <code class="descname">PyNumber_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if the object <em>o</em> provides numeric protocols, and false otherwise.
This function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Add">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Add</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Add" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of adding <em>o1</em> and <em>o2</em>, or <em>NULL</em> on failure.  This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">+</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Subtract">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Subtract</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Subtract" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of subtracting <em>o2</em> from <em>o1</em>, or <em>NULL</em> on failure.  This is
the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">-</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Multiply">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Multiply</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Multiply" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of multiplying <em>o1</em> and <em>o2</em>, or <em>NULL</em> on failure.  This is
the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">*</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Divide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Divide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Divide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of dividing <em>o1</em> by <em>o2</em>, or <em>NULL</em> on failure.  This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">/</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_FloorDivide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_FloorDivide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_FloorDivide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the floor of <em>o1</em> divided by <em>o2</em>, or <em>NULL</em> on failure.  This is
equivalent to the “classic” division of integers.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_TrueDivide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_TrueDivide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_TrueDivide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a reasonable approximation for the mathematical value of <em>o1</em> divided by
<em>o2</em>, or <em>NULL</em> on failure.  The return value is “approximate” because binary
floating point numbers are approximate; it is not possible to represent all real
numbers in base two.  This function can return a floating point value when
passed two integers.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Remainder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Remainder</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Remainder" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the remainder of dividing <em>o1</em> by <em>o2</em>, or <em>NULL</em> on failure.  This is
the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">%</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Divmod">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Divmod</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Divmod" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-0">See the built-in function <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>. Returns <em>NULL</em> on failure.  This is
the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">divmod(o1,</span> <span class="pre">o2)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Power">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Power</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o3</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Power" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-1">See the built-in function <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>. Returns <em>NULL</em> on failure.  This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">pow(o1,</span> <span class="pre">o2,</span> <span class="pre">o3)</span></code>, where <em>o3</em> is optional.
If <em>o3</em> is to be ignored, pass <a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> in its place (passing <em>NULL</em> for
<em>o3</em> would cause an illegal memory access).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Negative">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Negative</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Negative" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the negation of <em>o</em> on success, or <em>NULL</em> on failure. This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">-o</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Positive">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Positive</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Positive" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns <em>o</em> on success, or <em>NULL</em> on failure.  This is the equivalent of the
Python expression <code class="docutils literal notranslate"><span class="pre">+o</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Absolute">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Absolute</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Absolute" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">Returns the absolute value of <em>o</em>, or <em>NULL</em> on failure.  This is the equivalent
of the Python expression <code class="docutils literal notranslate"><span class="pre">abs(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Invert">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Invert</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Invert" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the bitwise negation of <em>o</em> on success, or <em>NULL</em> on failure.  This is
the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">~o</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Lshift">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Lshift</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Lshift" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of left shifting <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&lt;&lt;</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Rshift">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Rshift</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Rshift" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of right shifting <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&gt;&gt;</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_And">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_And</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_And" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise and” of <em>o1</em> and <em>o2</em> on success and <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&amp;</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Xor">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Xor</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Xor" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise exclusive or” of <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">^</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Or">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Or</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Or" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise or” of <em>o1</em> and <em>o2</em> on success, or <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">|</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceAdd">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceAdd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceAdd" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of adding <em>o1</em> and <em>o2</em>, or <em>NULL</em> on failure.  The operation
is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of the Python
statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">+=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceSubtract">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceSubtract</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceSubtract" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of subtracting <em>o2</em> from <em>o1</em>, or <em>NULL</em> on failure.  The
operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">-=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceMultiply">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceMultiply</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceMultiply" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of multiplying <em>o1</em> and <em>o2</em>, or <em>NULL</em> on failure.  The
operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">*=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceDivide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceDivide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceDivide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of dividing <em>o1</em> by <em>o2</em>, or <em>NULL</em> on failure.  The
operation is done <em>in-place</em> when <em>o1</em> supports it. This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">/=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceFloorDivide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceFloorDivide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceFloorDivide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the mathematical floor of dividing <em>o1</em> by <em>o2</em>, or <em>NULL</em> on failure.
The operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent
of the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">//=</span> <span class="pre">o2</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceTrueDivide">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceTrueDivide</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceTrueDivide" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a reasonable approximation for the mathematical value of <em>o1</em> divided by
<em>o2</em>, or <em>NULL</em> on failure.  The return value is “approximate” because binary
floating point numbers are approximate; it is not possible to represent all real
numbers in base two.  This function can return a floating point value when
passed two integers.  The operation is done <em>in-place</em> when <em>o1</em> supports it.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceRemainder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceRemainder</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceRemainder" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the remainder of dividing <em>o1</em> by <em>o2</em>, or <em>NULL</em> on failure.  The
operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">%=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlacePower">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlacePower</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o3</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlacePower" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-3">See the built-in function <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>. Returns <em>NULL</em> on failure.  The operation
is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of the Python
statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">**=</span> <span class="pre">o2</span></code> when o3 is <a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a>, or an in-place variant of
<code class="docutils literal notranslate"><span class="pre">pow(o1,</span> <span class="pre">o2,</span> <span class="pre">o3)</span></code> otherwise. If <em>o3</em> is to be ignored, pass <a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a>
in its place (passing <em>NULL</em> for <em>o3</em> would cause an illegal memory access).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceLshift">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceLshift</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceLshift" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of left shifting <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  The operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&lt;&lt;=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceRshift">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceRshift</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceRshift" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the result of right shifting <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  The operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&gt;&gt;=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceAnd">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceAnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceAnd" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise and” of <em>o1</em> and <em>o2</em> on success and <em>NULL</em> on failure. The
operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">&amp;=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceXor">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceXor</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceXor" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise exclusive or” of <em>o1</em> by <em>o2</em> on success, or <em>NULL</em> on
failure.  The operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">^=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_InPlaceOr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_InPlaceOr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_InPlaceOr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Returns the “bitwise or” of <em>o1</em> and <em>o2</em> on success, or <em>NULL</em> on failure.  The
operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">|=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Coerce">
int <code class="descname">PyNumber_Coerce</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**p1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**p2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Coerce" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">This function takes the addresses of two variables of type <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.
If the objects pointed to by <code class="docutils literal notranslate"><span class="pre">*p1</span></code> and <code class="docutils literal notranslate"><span class="pre">*p2</span></code> have the same type, increment
their reference count and return <code class="docutils literal notranslate"><span class="pre">0</span></code> (success). If the objects can be
converted to a common numeric type, replace <code class="docutils literal notranslate"><span class="pre">*p1</span></code> and <code class="docutils literal notranslate"><span class="pre">*p2</span></code> by their
converted value (with ‘new’ reference counts), and return <code class="docutils literal notranslate"><span class="pre">0</span></code>. If no
conversion is possible, or if some other error occurs, return <code class="docutils literal notranslate"><span class="pre">-1</span></code> (failure)
and don’t increment the reference counts.  The call <code class="docutils literal notranslate"><span class="pre">PyNumber_Coerce(&amp;o1,</span>
<span class="pre">&amp;o2)</span></code> is equivalent to the Python statement <code class="docutils literal notranslate"><span class="pre">o1,</span> <span class="pre">o2</span> <span class="pre">=</span> <span class="pre">coerce(o1,</span> <span class="pre">o2)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_CoerceEx">
int <code class="descname">PyNumber_CoerceEx</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**p1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**p2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_CoerceEx" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to <a class="reference internal" href="#c.PyNumber_Coerce" title="PyNumber_Coerce"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Coerce()</span></code></a>, except that it returns
<code class="docutils literal notranslate"><span class="pre">1</span></code> when the conversion is not possible and when no error is raised.
Reference counts are still not increased in this case.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Int">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Int</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Int" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-5">Returns the <em>o</em> converted to an integer object on success, or <em>NULL</em> on failure.
If the argument is outside the integer range a long object will be returned
instead. This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">int(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Long">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Long</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Long" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-6">Returns the <em>o</em> converted to a long integer object on success, or <em>NULL</em> on
failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">long(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Float">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Float</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Float" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-7">Returns the <em>o</em> converted to a float object on success, or <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">float(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_Index">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_Index</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_Index" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the <em>o</em> converted to a Python int or long on success or <em>NULL</em> with a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception raised on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_ToBase">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyNumber_ToBase</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*n</em>, int<em>&nbsp;base</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_ToBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the integer <em>n</em> converted to <em>base</em> as a string with a base
marker of <code class="docutils literal notranslate"><span class="pre">'0b'</span></code>, <code class="docutils literal notranslate"><span class="pre">'0o'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'0x'</span></code> if applicable.  When
<em>base</em> is not 2, 8, 10, or 16, the format is <code class="docutils literal notranslate"><span class="pre">'x#num'</span></code> where x is the
base. If <em>n</em> is not an int object, it is converted with
<a class="reference internal" href="#c.PyNumber_Index" title="PyNumber_Index"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Index()</span></code></a> first.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyNumber_AsSsize_t">
Py_ssize_t <code class="descname">PyNumber_AsSsize_t</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyNumber_AsSsize_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <em>o</em> converted to a Py_ssize_t value if <em>o</em> can be interpreted as an
integer. If <em>o</em> can be converted to a Python int or long but the attempt to
convert to a Py_ssize_t value would raise an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>, then the
<em>exc</em> argument is the type of exception that will be raised (usually
<a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>).  If <em>exc</em> is <em>NULL</em>, then the
exception is cleared and the value is clipped to <em>PY_SSIZE_T_MIN</em> for a negative
integer or <em>PY_SSIZE_T_MAX</em> for a positive integer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyIndex_Check">
int <code class="descname">PyIndex_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyIndex_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>o</em> is an index integer (has the nb_index slot of  the
tp_as_number structure filled in), and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="object.html"
                        title="previous chapter">Object Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sequence.html"
                        title="next chapter">Sequence Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/number.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sequence.html" title="Sequence Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="object.html" title="Object Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\?�q00html/c-api/objbuffer.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Old Buffer Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Concrete Objects Layer" href="concrete.html" />
    <link rel="prev" title="Iterator Protocol" href="iter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/objbuffer.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="concrete.html" title="Concrete Objects Layer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="iter.html" title="Iterator Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="old-buffer-protocol">
<span id="abstract-buffer"></span><h1>Old Buffer Protocol<a class="headerlink" href="#old-buffer-protocol" title="Permalink to this headline">¶</a></h1>
<p>This section describes the legacy buffer protocol, which has been introduced
in Python 1.6. It is still supported but deprecated in the Python 2.x series.
Python 3 introduces a new buffer protocol which fixes weaknesses and
shortcomings of the protocol, and has been backported to Python 2.6.  See
<a class="reference internal" href="buffer.html#bufferobjects"><span class="std std-ref">Buffers and Memoryview Objects</span></a> for more information.</p>
<dl class="function">
<dt id="c.PyObject_AsCharBuffer">
int <code class="descname">PyObject_AsCharBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, const char<em>&nbsp;**buffer</em>, Py_ssize_t<em>&nbsp;*buffer_len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_AsCharBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a pointer to a read-only memory location usable as character-based
input.  The <em>obj</em> argument must support the single-segment character buffer
interface.  On success, returns <code class="docutils literal notranslate"><span class="pre">0</span></code>, sets <em>buffer</em> to the memory location
and <em>buffer_len</em> to the buffer length.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> on error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>buffer_len</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_AsReadBuffer">
int <code class="descname">PyObject_AsReadBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, const void<em>&nbsp;**buffer</em>, Py_ssize_t<em>&nbsp;*buffer_len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_AsReadBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a pointer to a read-only memory location containing arbitrary data.
The <em>obj</em> argument must support the single-segment readable buffer
interface.  On success, returns <code class="docutils literal notranslate"><span class="pre">0</span></code>, sets <em>buffer</em> to the memory location
and <em>buffer_len</em> to the buffer length.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> on error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>buffer_len</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CheckReadBuffer">
int <code class="descname">PyObject_CheckReadBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CheckReadBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>o</em> supports the single-segment readable buffer interface.
Otherwise returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_AsWriteBuffer">
int <code class="descname">PyObject_AsWriteBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, void<em>&nbsp;**buffer</em>, Py_ssize_t<em>&nbsp;*buffer_len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_AsWriteBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a pointer to a writeable memory location.  The <em>obj</em> argument must
support the single-segment, character buffer interface.  On success,
returns <code class="docutils literal notranslate"><span class="pre">0</span></code>, sets <em>buffer</em> to the memory location and <em>buffer_len</em> to the
buffer length.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> on error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>buffer_len</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="iter.html"
                        title="previous chapter">Iterator Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="concrete.html"
                        title="next chapter">Concrete Objects Layer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/objbuffer.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="concrete.html" title="Concrete Objects Layer"
             >next</a> |</li>
        <li class="right" >
          <a href="iter.html" title="Iterator Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���c����html/c-api/object.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Object Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Number Protocol" href="number.html" />
    <link rel="prev" title="Abstract Objects Layer" href="abstract.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/object.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="number.html" title="Number Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="abstract.html" title="Abstract Objects Layer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="object-protocol">
<span id="object"></span><h1>Object Protocol<a class="headerlink" href="#object-protocol" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyObject_Print">
int <code class="descname">PyObject_Print</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, FILE<em>&nbsp;*fp</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Print" title="Permalink to this definition">¶</a></dt>
<dd><p>Print an object <em>o</em>, on file <em>fp</em>.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error.  The flags argument
is used to enable certain printing options.  The only option currently supported
is <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code>; if given, the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the object is written
instead of the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_HasAttr">
int <code class="descname">PyObject_HasAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_HasAttr" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>o</em> has the attribute <em>attr_name</em>, and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.  This
is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">hasattr(o,</span> <span class="pre">attr_name)</span></code>.  This function
always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_HasAttrString">
int <code class="descname">PyObject_HasAttrString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, const char<em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_HasAttrString" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>o</em> has the attribute <em>attr_name</em>, and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.  This
is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">hasattr(o,</span> <span class="pre">attr_name)</span></code>.  This function
always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GetAttr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_GetAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GetAttr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Retrieve an attribute named <em>attr_name</em> from object <em>o</em>. Returns the attribute
value on success, or <em>NULL</em> on failure.  This is the equivalent of the Python
expression <code class="docutils literal notranslate"><span class="pre">o.attr_name</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GetAttrString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_GetAttrString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, const char<em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GetAttrString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Retrieve an attribute named <em>attr_name</em> from object <em>o</em>. Returns the attribute
value on success, or <em>NULL</em> on failure. This is the equivalent of the Python
expression <code class="docutils literal notranslate"><span class="pre">o.attr_name</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GenericGetAttr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_GenericGetAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GenericGetAttr" title="Permalink to this definition">¶</a></dt>
<dd><p>Generic attribute getter function that is meant to be put into a type
object’s <code class="docutils literal notranslate"><span class="pre">tp_getattro</span></code> slot.  It looks for a descriptor in the dictionary
of classes in the object’s MRO as well as an attribute in the object’s
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (if present).  As outlined in <a class="reference internal" href="../reference/datamodel.html#descriptors"><span class="std std-ref">Implementing Descriptors</span></a>,
data descriptors take preference over instance attributes, while non-data
descriptors don’t.  Otherwise, an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_SetAttr">
int <code class="descname">PyObject_SetAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*attr_name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_SetAttr" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of the attribute named <em>attr_name</em>, for object <em>o</em>, to the value
<em>v</em>. Raise an exception and return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure;
return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  This is the equivalent of the Python statement
<code class="docutils literal notranslate"><span class="pre">o.attr_name</span> <span class="pre">=</span> <span class="pre">v</span></code>.</p>
<p>If <em>v</em> is <em>NULL</em>, the attribute is deleted, however this feature is
deprecated in favour of using <a class="reference internal" href="#c.PyObject_DelAttr" title="PyObject_DelAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_DelAttr()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_SetAttrString">
int <code class="descname">PyObject_SetAttrString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, const char<em>&nbsp;*attr_name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_SetAttrString" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of the attribute named <em>attr_name</em>, for object <em>o</em>, to the value
<em>v</em>. Raise an exception and return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure;
return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  This is the equivalent of the Python statement
<code class="docutils literal notranslate"><span class="pre">o.attr_name</span> <span class="pre">=</span> <span class="pre">v</span></code>.</p>
<p>If <em>v</em> is <em>NULL</em>, the attribute is deleted, however this feature is
deprecated in favour of using <a class="reference internal" href="#c.PyObject_DelAttrString" title="PyObject_DelAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_DelAttrString()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GenericSetAttr">
int <code class="descname">PyObject_GenericSetAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GenericSetAttr" title="Permalink to this definition">¶</a></dt>
<dd><p>Generic attribute setter and deleter function that is meant
to be put into a type object’s <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a>
slot.  It looks for a data descriptor in the
dictionary of classes in the object’s MRO, and if found it takes preference
over setting or deleting the attribute in the instance dictionary. Otherwise, the
attribute is set or deleted in the object’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (if present).
On success, <code class="docutils literal notranslate"><span class="pre">0</span></code> is returned, otherwise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>
is raised and <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_DelAttr">
int <code class="descname">PyObject_DelAttr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_DelAttr" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete attribute named <em>attr_name</em>, for object <em>o</em>. Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.
This is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o.attr_name</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_DelAttrString">
int <code class="descname">PyObject_DelAttrString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, const char<em>&nbsp;*attr_name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_DelAttrString" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete attribute named <em>attr_name</em>, for object <em>o</em>. Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.
This is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o.attr_name</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_RichCompare">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_RichCompare</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em>, int<em>&nbsp;opid</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_RichCompare" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Compare the values of <em>o1</em> and <em>o2</em> using the operation specified by <em>opid</em>,
which must be one of <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GT</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GE</span></code>, corresponding to <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> respectively. This is the equivalent of
the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">op</span> <span class="pre">o2</span></code>, where <code class="docutils literal notranslate"><span class="pre">op</span></code> is the operator corresponding
to <em>opid</em>. Returns the value of the comparison on success, or <em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_RichCompareBool">
int <code class="descname">PyObject_RichCompareBool</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em>, int<em>&nbsp;opid</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_RichCompareBool" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare the values of <em>o1</em> and <em>o2</em> using the operation specified by <em>opid</em>,
which must be one of <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GT</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GE</span></code>, corresponding to <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> respectively. Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error,
<code class="docutils literal notranslate"><span class="pre">0</span></code> if the result is false, <code class="docutils literal notranslate"><span class="pre">1</span></code> otherwise. This is the equivalent of the
Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">op</span> <span class="pre">o2</span></code>, where <code class="docutils literal notranslate"><span class="pre">op</span></code> is the operator corresponding to
<em>opid</em>.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <em>o1</em> and <em>o2</em> are the same object, <a class="reference internal" href="#c.PyObject_RichCompareBool" title="PyObject_RichCompareBool"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_RichCompareBool()</span></code></a>
will always return <code class="docutils literal notranslate"><span class="pre">1</span></code> for <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code> and <code class="docutils literal notranslate"><span class="pre">0</span></code> for <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code>.</p>
</div>
<dl class="function">
<dt id="c.PyObject_Cmp">
int <code class="descname">PyObject_Cmp</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em>, int<em>&nbsp;*result</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Cmp" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Compare the values of <em>o1</em> and <em>o2</em> using a routine provided by <em>o1</em>, if one
exists, otherwise with a routine provided by <em>o2</em>.  The result of the comparison
is returned in <em>result</em>.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.  This is the equivalent of
the Python statement <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">cmp(o1,</span> <span class="pre">o2)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Compare">
int <code class="descname">PyObject_Compare</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Compare" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Compare the values of <em>o1</em> and <em>o2</em> using a routine provided by <em>o1</em>, if one
exists, otherwise with a routine provided by <em>o2</em>.  Returns the result of the
comparison on success.  On error, the value returned is undefined; use
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to detect an error.  This is equivalent to the Python
expression <code class="docutils literal notranslate"><span class="pre">cmp(o1,</span> <span class="pre">o2)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Repr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Repr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Repr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">Compute a string representation of object <em>o</em>.  Returns the string
representation on success, <em>NULL</em> on failure.  This is the equivalent of the
Python expression <code class="docutils literal notranslate"><span class="pre">repr(o)</span></code>.  Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> built-in function and
by reverse quotes.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Str">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Str</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Str" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-3">Compute a string representation of object <em>o</em>.  Returns the string
representation on success, <em>NULL</em> on failure.  This is the equivalent of the
Python expression <code class="docutils literal notranslate"><span class="pre">str(o)</span></code>.  Called by the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> built-in function and
by the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Bytes">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Bytes</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Bytes" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Compute a bytes representation of object <em>o</em>.  In 2.x, this is just an alias
for <a class="reference internal" href="#c.PyObject_Str" title="PyObject_Str"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Str()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Unicode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Unicode</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Unicode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-5">Compute a Unicode string representation of object <em>o</em>.  Returns the Unicode
string representation on success, <em>NULL</em> on failure. This is the equivalent of
the Python expression <code class="docutils literal notranslate"><span class="pre">unicode(o)</span></code>.  Called by the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> built-in
function.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_IsInstance">
int <code class="descname">PyObject_IsInstance</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*inst</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cls</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_IsInstance" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>inst</em> is an instance of the class <em>cls</em> or a subclass of
<em>cls</em>, or <code class="docutils literal notranslate"><span class="pre">0</span></code> if not.  On error, returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets an exception.  If
<em>cls</em> is a type object rather than a class object, <a class="reference internal" href="#c.PyObject_IsInstance" title="PyObject_IsInstance"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_IsInstance()</span></code></a>
returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>inst</em> is of type <em>cls</em>.  If <em>cls</em> is a tuple, the check will
be done against every entry in <em>cls</em>. The result will be <code class="docutils literal notranslate"><span class="pre">1</span></code> when at least one
of the checks returns <code class="docutils literal notranslate"><span class="pre">1</span></code>, otherwise it will be <code class="docutils literal notranslate"><span class="pre">0</span></code>. If <em>inst</em> is not a
class instance and <em>cls</em> is neither a type object, nor a class object, nor a
tuple, <em>inst</em> must have a <a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> attribute — the
class relationship of the value of that attribute with <em>cls</em> will be used
to determine the result of this function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Support for a tuple as the second argument added.</p>
</div>
</dd></dl>

<p>Subclass determination is done in a fairly straightforward way, but includes a
wrinkle that implementors of extensions to the class system may want to be aware
of.  If <code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">B</span></code> are class objects, <code class="xref py py-class docutils literal notranslate"><span class="pre">B</span></code> is a subclass of
<code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code> if it inherits from <code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code> either directly or indirectly.  If
either is not a class object, a more general mechanism is used to determine the
class relationship of the two objects.  When testing if <em>B</em> is a subclass of
<em>A</em>, if <em>A</em> is <em>B</em>, <a class="reference internal" href="#c.PyObject_IsSubclass" title="PyObject_IsSubclass"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_IsSubclass()</span></code></a> returns true.  If <em>A</em> and <em>B</em>
are different objects, <em>B</em>’s <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> attribute is searched in
a depth-first fashion for <em>A</em> — the presence of the <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a>
attribute is considered sufficient for this determination.</p>
<dl class="function">
<dt id="c.PyObject_IsSubclass">
int <code class="descname">PyObject_IsSubclass</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*derived</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cls</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_IsSubclass" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if the class <em>derived</em> is identical to or derived from the class
<em>cls</em>, otherwise returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.  In case of an error, returns <code class="docutils literal notranslate"><span class="pre">-1</span></code>. If <em>cls</em>
is a tuple, the check will be done against every entry in <em>cls</em>. The result will
be <code class="docutils literal notranslate"><span class="pre">1</span></code> when at least one of the checks returns <code class="docutils literal notranslate"><span class="pre">1</span></code>, otherwise it will be
<code class="docutils literal notranslate"><span class="pre">0</span></code>. If either <em>derived</em> or <em>cls</em> is not an actual class object (or tuple),
this function uses the generic algorithm described above.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Older versions of Python did not support a tuple as the second argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyCallable_Check">
int <code class="descname">PyCallable_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCallable_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if the object <em>o</em> is callable.  Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the object is callable
and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.  This function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Call">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Call</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callable_object</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*kw</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Call" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-6">Call a callable Python object <em>callable_object</em>, with arguments given by the
tuple <em>args</em>, and named arguments given by the dictionary <em>kw</em>. If no named
arguments are needed, <em>kw</em> may be <em>NULL</em>. <em>args</em> must not be <em>NULL</em>, use an
empty tuple if no arguments are needed. Returns the result of the call on
success, or <em>NULL</em> on failure.  This is the equivalent of the Python expression
<code class="docutils literal notranslate"><span class="pre">apply(callable_object,</span> <span class="pre">args,</span> <span class="pre">kw)</span></code> or <code class="docutils literal notranslate"><span class="pre">callable_object(*args,</span> <span class="pre">**kw)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CallObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_CallObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callable_object</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CallObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-7">Call a callable Python object <em>callable_object</em>, with arguments given by the
tuple <em>args</em>.  If no arguments are needed, then <em>args</em> may be <em>NULL</em>.  Returns
the result of the call on success, or <em>NULL</em> on failure.  This is the equivalent
of the Python expression <code class="docutils literal notranslate"><span class="pre">apply(callable_object,</span> <span class="pre">args)</span></code> or
<code class="docutils literal notranslate"><span class="pre">callable_object(*args)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CallFunction">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_CallFunction</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callable</em>, char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CallFunction" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-8">Call a callable Python object <em>callable</em>, with a variable number of C arguments.
The C arguments are described using a <a class="reference internal" href="arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> style format
string.  The format may be <em>NULL</em>, indicating that no arguments are provided.
Returns the result of the call on success, or <em>NULL</em> on failure.  This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">apply(callable,</span> <span class="pre">args)</span></code> or
<code class="docutils literal notranslate"><span class="pre">callable(*args)</span></code>. Note that if you only pass <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code></a> args,
<a class="reference internal" href="#c.PyObject_CallFunctionObjArgs" title="PyObject_CallFunctionObjArgs"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallFunctionObjArgs()</span></code></a> is a faster alternative.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CallMethod">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_CallMethod</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, char<em>&nbsp;*method</em>, char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CallMethod" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Call the method named <em>method</em> of object <em>o</em> with a variable number of C
arguments.  The C arguments are described by a <a class="reference internal" href="arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> format
string that should  produce a tuple.  The format may be <em>NULL</em>, indicating that
no arguments are provided. Returns the result of the call on success, or <em>NULL</em>
on failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o.method(args)</span></code>.
Note that if you only pass <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code></a> args,
<a class="reference internal" href="#c.PyObject_CallMethodObjArgs" title="PyObject_CallMethodObjArgs"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallMethodObjArgs()</span></code></a> is a faster alternative.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CallFunctionObjArgs">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_CallFunctionObjArgs</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callable</em>, ..., NULL<span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CallFunctionObjArgs" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Call a callable Python object <em>callable</em>, with a variable number of
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> arguments.  The arguments are provided as a variable number
of parameters followed by <em>NULL</em>. Returns the result of the call on success, or
<em>NULL</em> on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_CallMethodObjArgs">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_CallMethodObjArgs</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*name</em>, ..., NULL<span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CallMethodObjArgs" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Calls a method of the object <em>o</em>, where the name of the method is given as a
Python string object in <em>name</em>.  It is called with a variable number of
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> arguments.  The arguments are provided as a variable number
of parameters followed by <em>NULL</em>. Returns the result of the call on success, or
<em>NULL</em> on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Hash">
long <code class="descname">PyObject_Hash</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Hash" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-9">Compute and return the hash value of an object <em>o</em>.  On failure, return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">hash(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_HashNotImplemented">
long <code class="descname">PyObject_HashNotImplemented</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_HashNotImplemented" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> indicating that <code class="docutils literal notranslate"><span class="pre">type(o)</span></code> is not hashable and return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.
This function receives special treatment when stored in a <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> slot,
allowing a type to explicitly indicate to the interpreter that it is not
hashable.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_IsTrue">
int <code class="descname">PyObject_IsTrue</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_IsTrue" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if the object <em>o</em> is considered to be true, and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.
This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">not</span> <span class="pre">o</span></code>.  On failure, return
<code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Not">
int <code class="descname">PyObject_Not</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Not" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> if the object <em>o</em> is considered to be true, and <code class="docutils literal notranslate"><span class="pre">1</span></code> otherwise.
This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">o</span></code>.  On failure, return
<code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Type">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Type</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Type" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-10">When <em>o</em> is non-<em>NULL</em>, returns a type object corresponding to the object type
of object <em>o</em>. On failure, raises <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> and returns <em>NULL</em>.  This
is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">type(o)</span></code>. This function increments the
reference count of the return value. There’s really no reason to use this
function instead of the common expression <code class="docutils literal notranslate"><span class="pre">o-&gt;ob_type</span></code>, which returns a
pointer of type <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject*</span></code></a>, except when the incremented reference
count is needed.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_TypeCheck">
int <code class="descname">PyObject_TypeCheck</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_TypeCheck" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is of type <em>type</em> or a subtype of <em>type</em>.  Both
parameters must be non-<em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Length">
Py_ssize_t <code class="descname">PyObject_Length</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Length" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyObject_Size">
Py_ssize_t <code class="descname">PyObject_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Size" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-11">Return the length of object <em>o</em>.  If the object <em>o</em> provides either the sequence
and mapping protocols, the sequence length is returned.  On error, <code class="docutils literal notranslate"><span class="pre">-1</span></code> is
returned.  This is the equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">len(o)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>These functions returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GetItem">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_GetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GetItem" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return element of <em>o</em> corresponding to the object <em>key</em> or <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o[key]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_SetItem">
int <code class="descname">PyObject_SetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_SetItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Map the object <em>key</em> to the value <em>v</em>.  Raise an exception and
return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure; return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o[key]</span> <span class="pre">=</span> <span class="pre">v</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_DelItem">
int <code class="descname">PyObject_DelItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_DelItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the mapping for <em>key</em> from <em>o</em>.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure. This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o[key]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_AsFileDescriptor">
int <code class="descname">PyObject_AsFileDescriptor</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_AsFileDescriptor" title="Permalink to this definition">¶</a></dt>
<dd><p>Derives a file descriptor from a Python object.  If the object is an integer or
long integer, its value is returned.  If not, the object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> method
is called if it exists; the method must return an integer or long integer, which
is returned as the file descriptor value.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Dir">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Dir</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Dir" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">dir(o)</span></code>, returning a (possibly
empty) list of strings appropriate for the object argument, or <em>NULL</em> if there
was an error.  If the argument is <em>NULL</em>, this is like the Python <code class="docutils literal notranslate"><span class="pre">dir()</span></code>,
returning the names of the current locals; in this case, if no execution frame
is active then <em>NULL</em> is returned but <a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> will return false.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GetIter">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_GetIter</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GetIter" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">iter(o)</span></code>. It returns a new
iterator for the object argument, or the object  itself if the object is already
an iterator.  Raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and returns <em>NULL</em> if the object cannot be
iterated.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="abstract.html"
                        title="previous chapter">Abstract Objects Layer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="number.html"
                        title="next chapter">Number Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/object.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="number.html" title="Number Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="abstract.html" title="Abstract Objects Layer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��
QQhtml/c-api/objimpl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Object Implementation Support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Allocating Objects on the Heap" href="allocation.html" />
    <link rel="prev" title="Memory Management" href="memory.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/objimpl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="allocation.html" title="Allocating Objects on the Heap"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="memory.html" title="Memory Management"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="object-implementation-support">
<span id="newtypes"></span><h1>Object Implementation Support<a class="headerlink" href="#object-implementation-support" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes the functions, types, and macros used when defining new
object types.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="allocation.html">Allocating Objects on the Heap</a></li>
<li class="toctree-l1"><a class="reference internal" href="structures.html">Common Object Structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="typeobj.html">Type Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="typeobj.html#number-object-structures">Number Object Structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="typeobj.html#mapping-object-structures">Mapping Object Structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="typeobj.html#sequence-object-structures">Sequence Object Structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="typeobj.html#buffer-object-structures">Buffer Object Structures</a></li>
<li class="toctree-l1"><a class="reference internal" href="gcsupport.html">Supporting Cyclic Garbage Collection</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="memory.html"
                        title="previous chapter">Memory Management</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="allocation.html"
                        title="next chapter">Allocating Objects on the Heap</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/objimpl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="allocation.html" title="Allocating Objects on the Heap"
             >next</a> |</li>
        <li class="right" >
          <a href="memory.html" title="Memory Management"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\'S�Z,2,2html/c-api/refcounting.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Reference Counting &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Exception Handling" href="exceptions.html" />
    <link rel="prev" title="The Very High Level Layer" href="veryhigh.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/refcounting.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="Exception Handling"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="veryhigh.html" title="The Very High Level Layer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="reference-counting">
<span id="countingrefs"></span><h1>Reference Counting<a class="headerlink" href="#reference-counting" title="Permalink to this headline">¶</a></h1>
<p>The macros in this section are used for managing reference counts of Python
objects.</p>
<dl class="function">
<dt id="c.Py_INCREF">
void <code class="descname">Py_INCREF</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_INCREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Increment the reference count for object <em>o</em>.  The object must not be <em>NULL</em>; if
you aren’t sure that it isn’t <em>NULL</em>, use <a class="reference internal" href="#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_XINCREF">
void <code class="descname">Py_XINCREF</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_XINCREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Increment the reference count for object <em>o</em>.  The object may be <em>NULL</em>, in
which case the macro has no effect.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_DECREF">
void <code class="descname">Py_DECREF</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_DECREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrement the reference count for object <em>o</em>.  The object must not be <em>NULL</em>; if
you aren’t sure that it isn’t <em>NULL</em>, use <a class="reference internal" href="#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>.  If the reference
count reaches zero, the object’s type’s deallocation function (which must not be
<em>NULL</em>) is invoked.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The deallocation function can cause arbitrary Python code to be invoked (e.g.
when a class instance with a <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method is deallocated).  While
exceptions in such code are not propagated, the executed code has free access to
all Python global variables.  This means that any object that is reachable from
a global variable should be in a consistent state before <a class="reference internal" href="#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> is
invoked.  For example, code to delete an object from a list should copy a
reference to the deleted object in a temporary variable, update the list data
structure, and then call <a class="reference internal" href="#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> for the temporary variable.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.Py_XDECREF">
void <code class="descname">Py_XDECREF</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_XDECREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrement the reference count for object <em>o</em>.  The object may be <em>NULL</em>, in
which case the macro has no effect; otherwise the effect is the same as for
<a class="reference internal" href="#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>, and the same warning applies.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_CLEAR">
void <code class="descname">Py_CLEAR</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_CLEAR" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrement the reference count for object <em>o</em>.  The object may be <em>NULL</em>, in
which case the macro has no effect; otherwise the effect is the same as for
<a class="reference internal" href="#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>, except that the argument is also set to <em>NULL</em>.  The warning
for <a class="reference internal" href="#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> does not apply with respect to the object passed because
the macro carefully uses a temporary variable and sets the argument to <em>NULL</em>
before decrementing its reference count.</p>
<p>It is a good idea to use this macro whenever decrementing the value of a
variable that might be traversed during garbage collection.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>The following functions are for runtime dynamic embedding of Python:
<code class="docutils literal notranslate"><span class="pre">Py_IncRef(PyObject</span> <span class="pre">*o)</span></code>, <code class="docutils literal notranslate"><span class="pre">Py_DecRef(PyObject</span> <span class="pre">*o)</span></code>. They are
simply exported function versions of <a class="reference internal" href="#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and
<a class="reference internal" href="#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>, respectively.</p>
<p>The following functions or macros are only for use within the interpreter core:
<code class="xref c c-func docutils literal notranslate"><span class="pre">_Py_Dealloc()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">_Py_ForgetReference()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">_Py_NewReference()</span></code>,
as well as the global variable <code class="xref c c-data docutils literal notranslate"><span class="pre">_Py_RefTotal</span></code>.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="veryhigh.html"
                        title="previous chapter">The Very High Level Layer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="exceptions.html"
                        title="next chapter">Exception Handling</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/refcounting.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="Exception Handling"
             >next</a> |</li>
        <li class="right" >
          <a href="veryhigh.html" title="The Very High Level Layer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\_dz��)�)html/c-api/reflection.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Reflection &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Codec registry and support functions" href="codec.html" />
    <link rel="prev" title="String conversion and formatting" href="conversion.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/reflection.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codec.html" title="Codec registry and support functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="conversion.html" title="String conversion and formatting"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="reflection">
<span id="id1"></span><h1>Reflection<a class="headerlink" href="#reflection" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyEval_GetBuiltins">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_GetBuiltins</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetBuiltins" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return a dictionary of the builtins in the current execution frame,
or the interpreter of the thread state if no frame is currently executing.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetLocals">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_GetLocals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetLocals" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return a dictionary of the local variables in the current execution frame,
or <em>NULL</em> if no frame is currently executing.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetGlobals">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_GetGlobals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetGlobals" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return a dictionary of the global variables in the current execution frame,
or <em>NULL</em> if no frame is currently executing.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetFrame">
PyFrameObject* <code class="descname">PyEval_GetFrame</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetFrame" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the current thread state’s frame, which is <em>NULL</em> if no frame is
currently executing.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFrame_GetLineNumber">
int <code class="descname">PyFrame_GetLineNumber</code><span class="sig-paren">(</span>PyFrameObject<em>&nbsp;*frame</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFrame_GetLineNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the line number that <em>frame</em> is currently executing.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetRestricted">
int <code class="descname">PyEval_GetRestricted</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetRestricted" title="Permalink to this definition">¶</a></dt>
<dd><p>If there is a current frame and it is executing in restricted mode, return true,
otherwise false.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetFuncName">
const char* <code class="descname">PyEval_GetFuncName</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*func</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetFuncName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of <em>func</em> if it is a function, class or instance object, else the
name of <em>func</em>s type.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_GetFuncDesc">
const char* <code class="descname">PyEval_GetFuncDesc</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*func</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_GetFuncDesc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a description string, depending on the type of <em>func</em>.
Return values include “()” for functions and methods, ” constructor”,
” instance”, and ” object”.  Concatenated with the result of
<a class="reference internal" href="#c.PyEval_GetFuncName" title="PyEval_GetFuncName"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_GetFuncName()</span></code></a>, the result will be a description of
<em>func</em>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="conversion.html"
                        title="previous chapter">String conversion and formatting</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="codec.html"
                        title="next chapter">Codec registry and support functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/reflection.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codec.html" title="Codec registry and support functions"
             >next</a> |</li>
        <li class="right" >
          <a href="conversion.html" title="String conversion and formatting"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�c$D~D~html/c-api/sequence.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sequence Protocol &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Mapping Protocol" href="mapping.html" />
    <link rel="prev" title="Number Protocol" href="number.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/sequence.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mapping.html" title="Mapping Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="number.html" title="Number Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" accesskey="U">Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="sequence-protocol">
<span id="sequence"></span><h1>Sequence Protocol<a class="headerlink" href="#sequence-protocol" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PySequence_Check">
int <code class="descname">PySequence_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the object provides sequence protocol, and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.
This function always succeeds.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Size">
Py_ssize_t <code class="descname">PySequence_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Size" title="Permalink to this definition">¶</a></dt>
<dt id="c.PySequence_Length">
Py_ssize_t <code class="descname">PySequence_Length</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Length" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Returns the number of objects in sequence <em>o</em> on success, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">len(o)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>These functions returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Concat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_Concat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Concat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the concatenation of <em>o1</em> and <em>o2</em> on success, and <em>NULL</em> on failure.
This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">+</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Repeat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_Repeat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;count</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Repeat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the result of repeating sequence object <em>o</em> <em>count</em> times, or <em>NULL</em> on
failure.  This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o</span> <span class="pre">*</span> <span class="pre">count</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>count</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_InPlaceConcat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_InPlaceConcat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o1</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_InPlaceConcat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the concatenation of <em>o1</em> and <em>o2</em> on success, and <em>NULL</em> on failure.
The operation is done <em>in-place</em> when <em>o1</em> supports it.  This is the equivalent
of the Python expression <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">+=</span> <span class="pre">o2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_InPlaceRepeat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_InPlaceRepeat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;count</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_InPlaceRepeat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the result of repeating sequence object <em>o</em> <em>count</em> times, or <em>NULL</em> on
failure.  The operation is done <em>in-place</em> when <em>o</em> supports it.  This is the
equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o</span> <span class="pre">*=</span> <span class="pre">count</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>count</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_GetItem">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_GetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_GetItem" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the <em>i</em>th element of <em>o</em>, or <em>NULL</em> on failure. This is the equivalent of
the Python expression <code class="docutils literal notranslate"><span class="pre">o[i]</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_GetSlice">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_GetSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i1</em>, Py_ssize_t<em>&nbsp;i2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_GetSlice" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the slice of sequence object <em>o</em> between <em>i1</em> and <em>i2</em>, or <em>NULL</em> on
failure. This is the equivalent of the Python expression <code class="docutils literal notranslate"><span class="pre">o[i1:i2]</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i1</em> and <em>i2</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_SetItem">
int <code class="descname">PySequence_SetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_SetItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign object <em>v</em> to the <em>i</em>th element of <em>o</em>.  Raise an exception
and return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure; return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  This
is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o[i]</span> <span class="pre">=</span> <span class="pre">v</span></code>.  This function <em>does
not</em> steal a reference to <em>v</em>.</p>
<p>If <em>v</em> is <em>NULL</em>, the element is deleted, however this feature is
deprecated in favour of using <a class="reference internal" href="#c.PySequence_DelItem" title="PySequence_DelItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_DelItem()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_DelItem">
int <code class="descname">PySequence_DelItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_DelItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the <em>i</em>th element of object <em>o</em>.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.  This is the
equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o[i]</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_SetSlice">
int <code class="descname">PySequence_SetSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i1</em>, Py_ssize_t<em>&nbsp;i2</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_SetSlice" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign the sequence object <em>v</em> to the slice in sequence object <em>o</em> from <em>i1</em> to
<em>i2</em>.  Raise an exception and return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure; return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.
This is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">o[i1:i2]</span> <span class="pre">=</span> <span class="pre">v</span></code>.</p>
<p>If <em>v</em> is <em>NULL</em>, the slice is deleted, however this feature is
deprecated in favour of using <a class="reference internal" href="#c.PySequence_DelSlice" title="PySequence_DelSlice"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_DelSlice()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i1</em> and <em>i2</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_DelSlice">
int <code class="descname">PySequence_DelSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i1</em>, Py_ssize_t<em>&nbsp;i2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_DelSlice" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the slice in sequence object <em>o</em> from <em>i1</em> to <em>i2</em>.  Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.  This is the equivalent of the Python statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">o[i1:i2]</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i1</em> and <em>i2</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Count">
Py_ssize_t <code class="descname">PySequence_Count</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of occurrences of <em>value</em> in <em>o</em>, that is, return the number
of keys for which <code class="docutils literal notranslate"><span class="pre">o[key]</span> <span class="pre">==</span> <span class="pre">value</span></code>.  On failure, return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.  This is
equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">o.count(value)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Contains">
int <code class="descname">PySequence_Contains</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Contains" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if <em>o</em> contains <em>value</em>.  If an item in <em>o</em> is equal to <em>value</em>,
return <code class="docutils literal notranslate"><span class="pre">1</span></code>, otherwise return <code class="docutils literal notranslate"><span class="pre">0</span></code>. On error, return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.  This is
equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">value</span> <span class="pre">in</span> <span class="pre">o</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Index">
Py_ssize_t <code class="descname">PySequence_Index</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Index" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the first index <em>i</em> for which <code class="docutils literal notranslate"><span class="pre">o[i]</span> <span class="pre">==</span> <span class="pre">value</span></code>.  On error, return
<code class="docutils literal notranslate"><span class="pre">-1</span></code>.    This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">o.index(value)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_List">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_List</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_List" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a list object with the same contents as the arbitrary sequence <em>o</em>.  The
returned list is guaranteed to be new.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Tuple">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_Tuple</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Tuple" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-1">Return a tuple object with the same contents as the arbitrary sequence <em>o</em> or
<em>NULL</em> on failure.  If <em>o</em> is a tuple, a new reference will be returned,
otherwise a tuple will be constructed with the appropriate contents.  This is
equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">tuple(o)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Fast">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_Fast</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, const char<em>&nbsp;*m</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Fast" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the sequence <em>o</em> as a list, unless it is already a tuple or list, in
which case <em>o</em> is returned.  Use <a class="reference internal" href="#c.PySequence_Fast_GET_ITEM" title="PySequence_Fast_GET_ITEM"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Fast_GET_ITEM()</span></code></a> to access
the members of the result.  Returns <em>NULL</em> on failure.  If the object is not
a sequence, raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> with <em>m</em> as the message text.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Fast_GET_ITEM">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_Fast_GET_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Fast_GET_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the <em>i</em>th element of <em>o</em>, assuming that <em>o</em> was returned by
<a class="reference internal" href="#c.PySequence_Fast" title="PySequence_Fast"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Fast()</span></code></a>, <em>o</em> is not <em>NULL</em>, and that <em>i</em> is within bounds.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Fast_ITEMS">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>** <code class="descname">PySequence_Fast_ITEMS</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Fast_ITEMS" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the underlying array of PyObject pointers.  Assumes that <em>o</em> was returned
by <a class="reference internal" href="#c.PySequence_Fast" title="PySequence_Fast"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Fast()</span></code></a> and <em>o</em> is not <em>NULL</em>.</p>
<p>Note, if a list gets resized, the reallocation may relocate the items array.
So, only use the underlying array pointer in contexts where the sequence
cannot change.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_ITEM">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySequence_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, Py_ssize_t<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the <em>i</em>th element of <em>o</em> or <em>NULL</em> on failure. Macro form of
<a class="reference internal" href="#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a> but without checking that
<a class="reference internal" href="#c.PySequence_Check" title="PySequence_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Check()</span></code></a> on <em>o</em> is true and without adjustment for negative
indices.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>i</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySequence_Fast_GET_SIZE">
Py_ssize_t <code class="descname">PySequence_Fast_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySequence_Fast_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the length of <em>o</em>, assuming that <em>o</em> was returned by
<a class="reference internal" href="#c.PySequence_Fast" title="PySequence_Fast"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Fast()</span></code></a> and that <em>o</em> is not <em>NULL</em>.  The size can also be
gotten by calling <a class="reference internal" href="#c.PySequence_Size" title="PySequence_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Size()</span></code></a> on <em>o</em>, but
<a class="reference internal" href="#c.PySequence_Fast_GET_SIZE" title="PySequence_Fast_GET_SIZE"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Fast_GET_SIZE()</span></code></a> is faster because it can assume <em>o</em> is a list
or tuple.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="number.html"
                        title="previous chapter">Number Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mapping.html"
                        title="next chapter">Mapping Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/sequence.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mapping.html" title="Mapping Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="number.html" title="Number Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="abstract.html" >Abstract Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����{�{html/c-api/set.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Set Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Code Objects" href="code.html" />
    <link rel="prev" title="DateTime Objects" href="datetime.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/set.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="code.html" title="Code Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="DateTime Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="set-objects">
<span id="setobjects"></span><h1>Set Objects<a class="headerlink" href="#set-objects" title="Permalink to this headline">¶</a></h1>
<div class="versionadded" id="index-0">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>This section details the public API for <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>
objects.  Any functionality not listed below is best accessed using the either
the abstract object protocol (including <a class="reference internal" href="object.html#c.PyObject_CallMethod" title="PyObject_CallMethod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallMethod()</span></code></a>,
<a class="reference internal" href="object.html#c.PyObject_RichCompareBool" title="PyObject_RichCompareBool"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_RichCompareBool()</span></code></a>, <a class="reference internal" href="object.html#c.PyObject_Hash" title="PyObject_Hash"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Hash()</span></code></a>,
<a class="reference internal" href="object.html#c.PyObject_Repr" title="PyObject_Repr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Repr()</span></code></a>, <a class="reference internal" href="object.html#c.PyObject_IsTrue" title="PyObject_IsTrue"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_IsTrue()</span></code></a>, <a class="reference internal" href="object.html#c.PyObject_Print" title="PyObject_Print"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Print()</span></code></a>, and
<a class="reference internal" href="object.html#c.PyObject_GetIter" title="PyObject_GetIter"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetIter()</span></code></a>) or the abstract number protocol (including
<a class="reference internal" href="number.html#c.PyNumber_And" title="PyNumber_And"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_And()</span></code></a>, <a class="reference internal" href="number.html#c.PyNumber_Subtract" title="PyNumber_Subtract"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Subtract()</span></code></a>, <a class="reference internal" href="number.html#c.PyNumber_Or" title="PyNumber_Or"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Or()</span></code></a>,
<a class="reference internal" href="number.html#c.PyNumber_Xor" title="PyNumber_Xor"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_Xor()</span></code></a>, <a class="reference internal" href="number.html#c.PyNumber_InPlaceAnd" title="PyNumber_InPlaceAnd"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_InPlaceAnd()</span></code></a>,
<a class="reference internal" href="number.html#c.PyNumber_InPlaceSubtract" title="PyNumber_InPlaceSubtract"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_InPlaceSubtract()</span></code></a>, <a class="reference internal" href="number.html#c.PyNumber_InPlaceOr" title="PyNumber_InPlaceOr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_InPlaceOr()</span></code></a>, and
<a class="reference internal" href="number.html#c.PyNumber_InPlaceXor" title="PyNumber_InPlaceXor"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_InPlaceXor()</span></code></a>).</p>
<dl class="type">
<dt id="c.PySetObject">
<code class="descname">PySetObject</code><a class="headerlink" href="#c.PySetObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> is used to hold the internal data for both
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> objects.  It is like a <a class="reference internal" href="dict.html#c.PyDictObject" title="PyDictObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyDictObject</span></code></a>
in that it is a fixed size for small sets (much like tuple storage) and will
point to a separate, variable sized block of memory for medium and large sized
sets (much like list storage). None of the fields of this structure should be
considered public and are subject to change.  All access should be done through
the documented API rather than by manipulating the values in the structure.</p>
</dd></dl>

<dl class="var">
<dt id="c.PySet_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PySet_Type</code><a class="headerlink" href="#c.PySet_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> representing the Python
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> type.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyFrozenSet_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyFrozenSet_Type</code><a class="headerlink" href="#c.PyFrozenSet_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> representing the Python
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> type.</p>
</dd></dl>

<p>The following type check macros work on pointers to any Python object. Likewise,
the constructor functions work with any iterable Python object.</p>
<dl class="function">
<dt id="c.PySet_Check">
int <code class="descname">PySet_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> object or an instance of a subtype.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFrozenSet_Check">
int <code class="descname">PyFrozenSet_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFrozenSet_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object or an instance of a
subtype.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyAnySet_Check">
int <code class="descname">PyAnySet_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyAnySet_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> object, a <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object, or an
instance of a subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyAnySet_CheckExact">
int <code class="descname">PyAnySet_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyAnySet_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> object or a <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object but
not an instance of a subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFrozenSet_CheckExact">
int <code class="descname">PyFrozenSet_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFrozenSet_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object but not an instance of a
subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySet_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySet_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> containing objects returned by the <em>iterable</em>.  The
<em>iterable</em> may be <em>NULL</em> to create a new empty set.  Return the new set on
success or <em>NULL</em> on failure.  Raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if <em>iterable</em> is not
actually iterable.  The constructor is also useful for copying a set
(<code class="docutils literal notranslate"><span class="pre">c=set(s)</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFrozenSet_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFrozenSet_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFrozenSet_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> containing objects returned by the <em>iterable</em>.
The <em>iterable</em> may be <em>NULL</em> to create a new empty frozenset.  Return the new
set on success or <em>NULL</em> on failure.  Raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if <em>iterable</em> is
not actually iterable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Now guaranteed to return a brand-new <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>.  Formerly,
frozensets of zero-length were a singleton.  This got in the way of
building-up new frozensets with <code class="xref py py-meth docutils literal notranslate"><span class="pre">PySet_Add()</span></code>.</p>
</div>
</dd></dl>

<p>The following functions and macros are available for instances of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>
or <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> or instances of their subtypes.</p>
<dl class="function">
<dt id="c.PySet_Size">
Py_ssize_t <code class="descname">PySet_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*anyset</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Size" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Return the length of a <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object. Equivalent to
<code class="docutils literal notranslate"><span class="pre">len(anyset)</span></code>.  Raises a <code class="xref py py-exc docutils literal notranslate"><span class="pre">PyExc_SystemError</span></code> if <em>anyset</em> is not a
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, or an instance of a subtype.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>. This might require changes in
your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySet_GET_SIZE">
Py_ssize_t <code class="descname">PySet_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*anyset</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro form of <a class="reference internal" href="#c.PySet_Size" title="PySet_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Size()</span></code></a> without error checking.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySet_Contains">
int <code class="descname">PySet_Contains</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*anyset</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Contains" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if found, <code class="docutils literal notranslate"><span class="pre">0</span></code> if not found, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an error is encountered.  Unlike
the Python <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method, this function does not automatically
convert unhashable sets into temporary frozensets.  Raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if
the <em>key</em> is unhashable. Raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">PyExc_SystemError</span></code> if <em>anyset</em> is not a
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, or an instance of a subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySet_Add">
int <code class="descname">PySet_Add</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*set</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>key</em> to a <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> instance.  Does not apply to <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>
instances.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure. Raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if
the <em>key</em> is unhashable. Raise a <a class="reference internal" href="../library/exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> if there is no room to grow.
Raise a <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> if <em>set</em> is not an instance of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or its
subtype.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Now works with instances of <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> or its subtypes.
Like <a class="reference internal" href="tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> in that it can be used to fill-in the
values of brand new frozensets before they are exposed to other code.</p>
</div>
</dd></dl>

<p>The following functions are available for instances of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or its
subtypes but not for instances of <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> or its subtypes.</p>
<dl class="function">
<dt id="c.PySet_Discard">
int <code class="descname">PySet_Discard</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*set</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Discard" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if found and removed, <code class="docutils literal notranslate"><span class="pre">0</span></code> if not found (no action taken), and <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an
error is encountered.  Does not raise <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> for missing keys.  Raise a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the <em>key</em> is unhashable.  Unlike the Python <code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code>
method, this function does not automatically convert unhashable sets into
temporary frozensets. Raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">PyExc_SystemError</span></code> if <em>set</em> is not an
instance of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or its subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySet_Pop">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySet_Pop</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*set</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Pop" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new reference to an arbitrary object in the <em>set</em>, and removes the
object from the <em>set</em>.  Return <em>NULL</em> on failure.  Raise <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if the
set is empty. Raise a <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> if <em>set</em> is not an instance of
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> or its subtype.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySet_Clear">
int <code class="descname">PySet_Clear</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*set</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySet_Clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Empty an existing set of all elements.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="datetime.html"
                        title="previous chapter">DateTime Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="code.html"
                        title="next chapter">Code Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/set.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="code.html" title="Code Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="DateTime Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\^��55html/c-api/slice.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Slice Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Weak Reference Objects" href="weakref.html" />
    <link rel="prev" title="Descriptor Objects" href="descriptor.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/slice.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="Weak Reference Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="slice-objects">
<span id="id1"></span><h1>Slice Objects<a class="headerlink" href="#slice-objects" title="Permalink to this headline">¶</a></h1>
<dl class="var">
<dt id="c.PySlice_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PySlice_Type</code><a class="headerlink" href="#c.PySlice_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">The type object for slice objects.  This is the same as <code class="docutils literal notranslate"><span class="pre">slice</span></code> and
<code class="docutils literal notranslate"><span class="pre">types.SliceType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySlice_Check">
int <code class="descname">PySlice_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySlice_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is a slice object; <em>ob</em> must not be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySlice_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PySlice_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*stop</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*step</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySlice_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new slice object with the given values.  The <em>start</em>, <em>stop</em>, and
<em>step</em> parameters are used as the values of the slice object attributes of
the same names.  Any of the values may be <em>NULL</em>, in which case the
<code class="docutils literal notranslate"><span class="pre">None</span></code> will be used for the corresponding attribute.  Return <em>NULL</em> if
the new object could not be allocated.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySlice_GetIndices">
int <code class="descname">PySlice_GetIndices</code><span class="sig-paren">(</span>PySliceObject<em>&nbsp;*slice</em>, Py_ssize_t<em>&nbsp;length</em>, Py_ssize_t<em>&nbsp;*start</em>, Py_ssize_t<em>&nbsp;*stop</em>, Py_ssize_t<em>&nbsp;*step</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySlice_GetIndices" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the start, stop and step indices from the slice object <em>slice</em>,
assuming a sequence of length <em>length</em>. Treats indices greater than
<em>length</em> as errors.</p>
<p>Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error with no exception set (unless one of
the indices was not <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and failed to be converted to an integer,
in which case <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned with an exception set).</p>
<p>You probably do not want to use this function.  If you want to use slice
objects in versions of Python prior to 2.3, you would probably do well to
incorporate the source of <a class="reference internal" href="#c.PySlice_GetIndicesEx" title="PySlice_GetIndicesEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySlice_GetIndicesEx()</span></code></a>, suitably renamed,
in the source of your extension.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>length</em> and an
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>start</em>, <em>stop</em>, and <em>step</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PySlice_GetIndicesEx">
int <code class="descname">PySlice_GetIndicesEx</code><span class="sig-paren">(</span>PySliceObject<em>&nbsp;*slice</em>, Py_ssize_t<em>&nbsp;length</em>, Py_ssize_t<em>&nbsp;*start</em>, Py_ssize_t<em>&nbsp;*stop</em>, Py_ssize_t<em>&nbsp;*step</em>, Py_ssize_t<em>&nbsp;*slicelength</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySlice_GetIndicesEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Usable replacement for <a class="reference internal" href="#c.PySlice_GetIndices" title="PySlice_GetIndices"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySlice_GetIndices()</span></code></a>.  Retrieve the start,
stop, and step indices from the slice object <em>slice</em> assuming a sequence of
length <em>length</em>, and store the length of the slice in <em>slicelength</em>.  Out
of bounds indices are clipped in a manner consistent with the handling of
normal slices.</p>
<p>Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error with exception set.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>length</em> and an
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>start</em>, <em>stop</em>, <em>step</em>, and <em>slicelength</em>. This
might require changes in your code for properly supporting 64-bit
systems.</p>
</div>
</dd></dl>

</div>
<div class="section" id="ellipsis-object">
<h1>Ellipsis Object<a class="headerlink" href="#ellipsis-object" title="Permalink to this headline">¶</a></h1>
<dl class="var">
<dt id="c.Py_Ellipsis">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">Py_Ellipsis</code><a class="headerlink" href="#c.Py_Ellipsis" title="Permalink to this definition">¶</a></dt>
<dd><p>The Python <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code> object.  This object has no methods.  It needs to be
treated just like any other object with respect to reference counts.  Like
<a class="reference internal" href="none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> it is a singleton object.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Slice Objects</a></li>
<li><a class="reference internal" href="#ellipsis-object">Ellipsis Object</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="descriptor.html"
                        title="previous chapter">Descriptor Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="weakref.html"
                        title="next chapter">Weak Reference Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/slice.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="Weak Reference Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���]����html/c-api/string.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>String/Bytes Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Unicode Objects and Codecs" href="unicode.html" />
    <link rel="prev" title="Byte Array Objects" href="bytearray.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/string.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode Objects and Codecs"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bytearray.html" title="Byte Array Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="string-bytes-objects">
<span id="stringobjects"></span><h1>String/Bytes Objects<a class="headerlink" href="#string-bytes-objects" title="Permalink to this headline">¶</a></h1>
<p>These functions raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> when expecting a string parameter and are
called with a non-string parameter.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">These functions have been renamed to PyBytes_* in Python 3.x. Unless
otherwise noted, the PyBytes functions available in 3.x are aliased to their
PyString_* equivalents to help porting.</p>
</div>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyStringObject">
<code class="descname">PyStringObject</code><a class="headerlink" href="#c.PyStringObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python string object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyString_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyString_Type</code><a class="headerlink" href="#c.PyString_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python string type; it is
the same object as <code class="docutils literal notranslate"><span class="pre">str</span></code> and <code class="docutils literal notranslate"><span class="pre">types.StringType</span></code> in the Python layer. .</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Check">
int <code class="descname">PyString_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a string object or an instance of a subtype of
the string type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_CheckExact">
int <code class="descname">PyString_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a string object, but not an instance of a
subtype of the string type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_FromString</code><span class="sig-paren">(</span>const char<em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new string object with a copy of the string <em>v</em> as value on success,
and <em>NULL</em> on failure.  The parameter <em>v</em> must not be <em>NULL</em>; it will not be
checked.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_FromStringAndSize">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_FromStringAndSize</code><span class="sig-paren">(</span>const char<em>&nbsp;*v</em>, Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_FromStringAndSize" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new string object with a copy of the string <em>v</em> as value and length
<em>len</em> on success, and <em>NULL</em> on failure.  If <em>v</em> is <em>NULL</em>, the contents of the
string are uninitialized.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>len</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_FromFormat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_FromFormat</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_FromFormat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Take a C <code class="xref c c-func docutils literal notranslate"><span class="pre">printf()</span></code>-style <em>format</em> string and a variable number of
arguments, calculate the size of the resulting Python string and return a string
with the values formatted into it.  The variable arguments must be C types and
must correspond exactly to the format characters in the <em>format</em> string.  The
following format characters are allowed:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="23%" />
<col width="48%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format Characters</th>
<th class="head">Type</th>
<th class="head">Comment</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%%</span></code></td>
<td><em>n/a</em></td>
<td>The literal % character.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%c</span></code></td>
<td>int</td>
<td>A single character,
represented as a C int.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%d</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%d&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%u</span></code></td>
<td>unsigned int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%u&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%ld</span></code></td>
<td>long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%ld&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%lu</span></code></td>
<td>unsigned long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%lu&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%lld</span></code></td>
<td>long long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%lld&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%llu</span></code></td>
<td>unsigned
long long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%llu&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%zd</span></code></td>
<td>Py_ssize_t</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%zd&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%zu</span></code></td>
<td>size_t</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%zu&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%i</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%i&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%x</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%x&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%s</span></code></td>
<td>char*</td>
<td>A null-terminated C character
array.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%p</span></code></td>
<td>void*</td>
<td>The hex representation of a C
pointer. Mostly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%p&quot;)</span></code> except that
it is guaranteed to start with
the literal <code class="docutils literal notranslate"><span class="pre">0x</span></code> regardless
of what the platform’s
<code class="docutils literal notranslate"><span class="pre">printf</span></code> yields.</td>
</tr>
</tbody>
</table>
<p>An unrecognized format character causes all the rest of the format string to be
copied as-is to the result string, and any extra arguments discarded.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <cite>“%lld”</cite> and <cite>“%llu”</cite> format specifiers are only available
when <code class="xref py py-const docutils literal notranslate"><span class="pre">HAVE_LONG_LONG</span></code> is defined.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for <cite>“%lld”</cite> and <cite>“%llu”</cite> added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_FromFormatV">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_FromFormatV</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, va_list<em>&nbsp;vargs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_FromFormatV" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Identical to <a class="reference internal" href="#c.PyString_FromFormat" title="PyString_FromFormat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_FromFormat()</span></code></a> except that it takes exactly two
arguments.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Size">
Py_ssize_t <code class="descname">PyString_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*string</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the length of the string in string object <em>string</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_GET_SIZE">
Py_ssize_t <code class="descname">PyString_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*string</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro form of <a class="reference internal" href="#c.PyString_Size" title="PyString_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_Size()</span></code></a> but without error checking.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This macro returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes in
your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_AsString">
char* <code class="descname">PyString_AsString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*string</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_AsString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a NUL-terminated representation of the contents of <em>string</em>.  The pointer
refers to the internal buffer of <em>string</em>, not a copy.  The data must not be
modified in any way, unless the string was just created using
<code class="docutils literal notranslate"><span class="pre">PyString_FromStringAndSize(NULL,</span> <span class="pre">size)</span></code>. It must not be deallocated.  If
<em>string</em> is a Unicode object, this function computes the default encoding of
<em>string</em> and operates on that.  If <em>string</em> is not a string object at all,
<a class="reference internal" href="#c.PyString_AsString" title="PyString_AsString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_AsString()</span></code></a> returns <em>NULL</em> and raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_AS_STRING">
char* <code class="descname">PyString_AS_STRING</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*string</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_AS_STRING" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro form of <a class="reference internal" href="#c.PyString_AsString" title="PyString_AsString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_AsString()</span></code></a> but without error checking.  Only
string objects are supported; no Unicode objects should be passed.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_AsStringAndSize">
int <code class="descname">PyString_AsStringAndSize</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, char<em>&nbsp;**buffer</em>, Py_ssize_t<em>&nbsp;*length</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_AsStringAndSize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a NUL-terminated representation of the contents of the object <em>obj</em>
through the output variables <em>buffer</em> and <em>length</em>.</p>
<p>The function accepts both string and Unicode objects as input. For Unicode
objects it returns the default encoded version of the object.  If <em>length</em> is
<em>NULL</em>, the resulting buffer may not contain NUL characters; if it does, the
function returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>The buffer refers to an internal string buffer of <em>obj</em>, not a copy. The data
must not be modified in any way, unless the string was just created using
<code class="docutils literal notranslate"><span class="pre">PyString_FromStringAndSize(NULL,</span> <span class="pre">size)</span></code>.  It must not be deallocated.  If
<em>string</em> is a Unicode object, this function computes the default encoding of
<em>string</em> and operates on that.  If <em>string</em> is not a string object at all,
<a class="reference internal" href="#c.PyString_AsStringAndSize" title="PyString_AsStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_AsStringAndSize()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>length</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Concat">
void <code class="descname">PyString_Concat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**string</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*newpart</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Concat" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new string object in <em>*string</em> containing the contents of <em>newpart</em>
appended to <em>string</em>; the caller will own the new reference.  The reference to
the old value of <em>string</em> will be stolen.  If the new string cannot be created,
the old reference to <em>string</em> will still be discarded and the value of
<em>*string</em> will be set to <em>NULL</em>; the appropriate exception will be set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_ConcatAndDel">
void <code class="descname">PyString_ConcatAndDel</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**string</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*newpart</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_ConcatAndDel" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new string object in <em>*string</em> containing the contents of <em>newpart</em>
appended to <em>string</em>.  This version decrements the reference count of <em>newpart</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyString_Resize">
int <code class="descname">_PyString_Resize</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**string</em>, Py_ssize_t<em>&nbsp;newsize</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyString_Resize" title="Permalink to this definition">¶</a></dt>
<dd><p>A way to resize a string object even though it is “immutable”. Only use this to
build up a brand new string object; don’t use this if the string may already be
known in other parts of the code.  It is an error to call this function if the
refcount on the input string object is not one. Pass the address of an existing
string object as an lvalue (it may be written into), and the new size desired.
On success, <em>*string</em> holds the resized string object and <code class="docutils literal notranslate"><span class="pre">0</span></code> is returned;
the address in <em>*string</em> may differ from its input value.  If the reallocation
fails, the original string object at <em>*string</em> is deallocated, <em>*string</em> is
set to <em>NULL</em>, a memory exception is set, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>newsize</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Format">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_Format</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*format</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Format" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new string object from <em>format</em> and <em>args</em>. Analogous to <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span>
<span class="pre">args</span></code>.  The <em>args</em> argument must be a tuple or dict.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyString_InternInPlace">
void <code class="descname">PyString_InternInPlace</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**string</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_InternInPlace" title="Permalink to this definition">¶</a></dt>
<dd><p>Intern the argument <em>*string</em> in place.  The argument must be the address of a
pointer variable pointing to a Python string object.  If there is an existing
interned string that is the same as <em>*string</em>, it sets <em>*string</em> to it
(decrementing the reference count of the old string object and incrementing the
reference count of the interned string object), otherwise it leaves <em>*string</em>
alone and interns it (incrementing its reference count).  (Clarification: even
though there is a lot of talk about reference counts, think of this function as
reference-count-neutral; you own the object after the call if and only if you
owned it before the call.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_InternFromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_InternFromString</code><span class="sig-paren">(</span>const char<em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_InternFromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>A combination of <a class="reference internal" href="#c.PyString_FromString" title="PyString_FromString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_FromString()</span></code></a> and
<a class="reference internal" href="#c.PyString_InternInPlace" title="PyString_InternInPlace"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_InternInPlace()</span></code></a>, returning either a new string object that has
been interned, or a new (“owned”) reference to an earlier interned string object
with the same value.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Decode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_Decode</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Decode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create an object by decoding <em>size</em> bytes of the encoded buffer <em>s</em> using the
codec registered for <em>encoding</em>.  <em>encoding</em> and <em>errors</em> have the same meaning
as the parameters of the same name in the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> built-in function.
The codec to be used is looked up using the Python codec registry.  Return
<em>NULL</em> if an exception was raised by the codec.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_AsDecodedObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_AsDecodedObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_AsDecodedObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Decode a string object by passing it to the codec registered for <em>encoding</em> and
return the result as Python object. <em>encoding</em> and <em>errors</em> have the same
meaning as the parameters of the same name in the string <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method.
The codec to be used is looked up using the Python codec registry. Return <em>NULL</em>
if an exception was raised by the codec.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_Encode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_Encode</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_Encode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code> buffer of the given size by passing it to the codec
registered for <em>encoding</em> and return a Python object. <em>encoding</em> and <em>errors</em>
have the same meaning as the parameters of the same name in the string
<code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method. The codec to be used is looked up using the Python codec
registry.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyString_AsEncodedObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyString_AsEncodedObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyString_AsEncodedObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a string object using the codec registered for <em>encoding</em> and return the
result as Python object. <em>encoding</em> and <em>errors</em> have the same meaning as the
parameters of the same name in the string <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method. The codec to be
used is looked up using the Python codec registry. Return <em>NULL</em> if an exception
was raised by the codec.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available in 3.x and does not have a PyBytes alias.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="bytearray.html"
                        title="previous chapter">Byte Array Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unicode.html"
                        title="next chapter">Unicode Objects and Codecs</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/string.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode Objects and Codecs"
             >next</a> |</li>
        <li class="right" >
          <a href="bytearray.html" title="Byte Array Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\-�D�����html/c-api/structures.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Common Object Structures &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Type Objects" href="typeobj.html" />
    <link rel="prev" title="Allocating Objects on the Heap" href="allocation.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/structures.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="typeobj.html" title="Type Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="allocation.html" title="Allocating Objects on the Heap"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" accesskey="U">Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="common-object-structures">
<span id="common-structs"></span><h1>Common Object Structures<a class="headerlink" href="#common-object-structures" title="Permalink to this headline">¶</a></h1>
<p>There are a large number of structures which are used in the definition of
object types for Python.  This section describes these structures and how they
are used.</p>
<p>All Python objects ultimately share a small number of fields at the beginning
of the object’s representation in memory.  These are represented by the
<a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> and <a class="reference internal" href="#c.PyVarObject" title="PyVarObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyVarObject</span></code></a> types, which are defined, in turn,
by the expansions of some macros also used, whether directly or indirectly, in
the definition of all other Python objects.</p>
<dl class="type">
<dt id="c.PyObject">
<code class="descname">PyObject</code><a class="headerlink" href="#c.PyObject" title="Permalink to this definition">¶</a></dt>
<dd><p>All object types are extensions of this type.  This is a type which
contains the information Python needs to treat a pointer to an object as an
object.  In a normal “release” build, it contains only the object’s
reference count and a pointer to the corresponding type object.  It
corresponds to the fields defined by the expansion of the <code class="docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code>
macro.</p>
</dd></dl>

<dl class="type">
<dt id="c.PyVarObject">
<code class="descname">PyVarObject</code><a class="headerlink" href="#c.PyVarObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an extension of <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> that adds the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code>
field.  This is only used for objects that have some notion of <em>length</em>.
This type does not often appear in the Python/C API.  It corresponds to the
fields defined by the expansion of the <code class="docutils literal notranslate"><span class="pre">PyObject_VAR_HEAD</span></code> macro.</p>
</dd></dl>

<p>These macros are used in the definition of <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> and
<a class="reference internal" href="#c.PyVarObject" title="PyVarObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyVarObject</span></code></a>:</p>
<dl class="macro">
<dt id="c.PyObject_HEAD">
<code class="descname">PyObject_HEAD</code><a class="headerlink" href="#c.PyObject_HEAD" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a macro which expands to the declarations of the fields of the
<a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> type; it is used when declaring new types which represent
objects without a varying length.  The specific fields it expands to depend
on the definition of <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code>.  By default, that macro is
not defined, and <a class="reference internal" href="#c.PyObject_HEAD" title="PyObject_HEAD"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code></a> expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_ssize_t</span> <span class="n">ob_refcnt</span><span class="p">;</span>
<span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">ob_type</span><span class="p">;</span>
</pre></div>
</div>
<p>When <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code> is defined, it expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">_ob_next</span><span class="p">,</span> <span class="o">*</span><span class="n">_ob_prev</span><span class="p">;</span>
<span class="n">Py_ssize_t</span> <span class="n">ob_refcnt</span><span class="p">;</span>
<span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">ob_type</span><span class="p">;</span>
</pre></div>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.PyObject_VAR_HEAD">
<code class="descname">PyObject_VAR_HEAD</code><a class="headerlink" href="#c.PyObject_VAR_HEAD" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a macro which expands to the declarations of the fields of the
<a class="reference internal" href="#c.PyVarObject" title="PyVarObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyVarObject</span></code></a> type; it is used when declaring new types which
represent objects with a length that varies from instance to instance.
This macro always expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject_HEAD</span>
<span class="n">Py_ssize_t</span> <span class="n">ob_size</span><span class="p">;</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#c.PyObject_HEAD" title="PyObject_HEAD"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code></a> is part of the expansion, and that its own
expansion varies depending on the definition of <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code>.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_TYPE">
<code class="descname">Py_TYPE</code><span class="sig-paren">(</span>o<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_TYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro is used to access the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> member of a Python object.
It expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">(((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)(</span><span class="n">o</span><span class="p">))</span><span class="o">-&gt;</span><span class="n">ob_type</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_REFCNT">
<code class="descname">Py_REFCNT</code><span class="sig-paren">(</span>o<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_REFCNT" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro is used to access the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_refcnt</span></code> member of a Python
object.
It expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">(((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)(</span><span class="n">o</span><span class="p">))</span><span class="o">-&gt;</span><span class="n">ob_refcnt</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_SIZE">
<code class="descname">Py_SIZE</code><span class="sig-paren">(</span>o<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>This macro is used to access the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> member of a Python object.
It expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">(((</span><span class="n">PyVarObject</span><span class="o">*</span><span class="p">)(</span><span class="n">o</span><span class="p">))</span><span class="o">-&gt;</span><span class="n">ob_size</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.PyObject_HEAD_INIT">
<code class="descname">PyObject_HEAD_INIT</code><span class="sig-paren">(</span>type<span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_HEAD_INIT" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a macro which expands to initialization values for a new
<a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> type.  This macro expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">_PyObject_EXTRA_INIT</span>
<span class="mi">1</span><span class="p">,</span> <span class="n">type</span><span class="p">,</span>
</pre></div>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.PyVarObject_HEAD_INIT">
<code class="descname">PyVarObject_HEAD_INIT</code><span class="sig-paren">(</span>type, size<span class="sig-paren">)</span><a class="headerlink" href="#c.PyVarObject_HEAD_INIT" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a macro which expands to initialization values for a new
<a class="reference internal" href="#c.PyVarObject" title="PyVarObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyVarObject</span></code></a> type, including the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field.
This macro expands to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">_PyObject_EXTRA_INIT</span>
<span class="mi">1</span><span class="p">,</span> <span class="n">type</span><span class="p">,</span> <span class="n">size</span><span class="p">,</span>
</pre></div>
</div>
</dd></dl>

<dl class="type">
<dt id="c.PyCFunction">
<code class="descname">PyCFunction</code><a class="headerlink" href="#c.PyCFunction" title="Permalink to this definition">¶</a></dt>
<dd><p>Type of the functions used to implement most Python callables in C.
Functions of this type take two <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> parameters and return
one such value.  If the return value is <em>NULL</em>, an exception shall have
been set.  If not <em>NULL</em>, the return value is interpreted as the return
value of the function as exposed in Python.  The function must return a new
reference.</p>
</dd></dl>

<dl class="type">
<dt id="c.PyMethodDef">
<code class="descname">PyMethodDef</code><a class="headerlink" href="#c.PyMethodDef" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure used to describe a method of an extension type.  This structure has
four fields:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="21%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">C Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_name</span></code></td>
<td>char *</td>
<td>name of the method</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_meth</span></code></td>
<td>PyCFunction</td>
<td>pointer to the C
implementation</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_flags</span></code></td>
<td>int</td>
<td>flag bits indicating how the
call should be constructed</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_doc</span></code></td>
<td>char *</td>
<td>points to the contents of the
docstring</td>
</tr>
</tbody>
</table>
</dd></dl>

<p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_meth</span></code> is a C function pointer.  The functions may be of different
types, but they always return <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.  If the function is not of
the <a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a>, the compiler will require a cast in the method table.
Even though <a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a> defines the first parameter as
<a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>, it is common that the method implementation uses the
specific C type of the <em>self</em> object.</p>
<p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_flags</span></code> field is a bitfield which can include the following flags.
The individual flags indicate either a calling convention or a binding
convention.  Of the calling convention flags, only <a class="reference internal" href="#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a> and
<a class="reference internal" href="#METH_KEYWORDS" title="METH_KEYWORDS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_KEYWORDS</span></code></a> can be combined. Any of the calling convention flags
can be combined with a binding flag.</p>
<dl class="data">
<dt id="METH_VARARGS">
<code class="descname">METH_VARARGS</code><a class="headerlink" href="#METH_VARARGS" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the typical calling convention, where the methods have the type
<a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a>. The function expects two <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> values.
The first one is the <em>self</em> object for methods; for module functions, it is
the module object.  The second parameter (often called <em>args</em>) is a tuple
object representing all arguments.  This parameter is typically processed
using <a class="reference internal" href="arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> or <a class="reference internal" href="arg.html#c.PyArg_UnpackTuple" title="PyArg_UnpackTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_UnpackTuple()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="METH_KEYWORDS">
<code class="descname">METH_KEYWORDS</code><a class="headerlink" href="#METH_KEYWORDS" title="Permalink to this definition">¶</a></dt>
<dd><p>Methods with these flags must be of type <code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunctionWithKeywords</span></code>.
The function expects three parameters: <em>self</em>, <em>args</em>, and a dictionary of
all the keyword arguments.  The flag is typically combined with
<a class="reference internal" href="#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a>, and the parameters are typically processed using
<a class="reference internal" href="arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="METH_NOARGS">
<code class="descname">METH_NOARGS</code><a class="headerlink" href="#METH_NOARGS" title="Permalink to this definition">¶</a></dt>
<dd><p>Methods without parameters don’t need to check whether arguments are given if
they are listed with the <a class="reference internal" href="#METH_NOARGS" title="METH_NOARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a> flag.  They need to be of type
<a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a>.  The first parameter is typically named <code class="docutils literal notranslate"><span class="pre">self</span></code> and
will hold a reference to the module or object instance.  In all cases the
second parameter will be <em>NULL</em>.</p>
</dd></dl>

<dl class="data">
<dt id="METH_O">
<code class="descname">METH_O</code><a class="headerlink" href="#METH_O" title="Permalink to this definition">¶</a></dt>
<dd><p>Methods with a single object argument can be listed with the <a class="reference internal" href="#METH_O" title="METH_O"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_O</span></code></a>
flag, instead of invoking <a class="reference internal" href="arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> with a <code class="docutils literal notranslate"><span class="pre">&quot;O&quot;</span></code> argument.
They have the type <a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a>, with the <em>self</em> parameter, and a
<a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> parameter representing the single argument.</p>
</dd></dl>

<dl class="data">
<dt id="METH_OLDARGS">
<code class="descname">METH_OLDARGS</code><a class="headerlink" href="#METH_OLDARGS" title="Permalink to this definition">¶</a></dt>
<dd><p>This calling convention is deprecated.  The method must be of type
<a class="reference internal" href="#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a>.  The second argument is <em>NULL</em> if no arguments are
given, a single object if exactly one argument is given, and a tuple of
objects if more than one argument is given.  There is no way for a function
using this convention to distinguish between a call with multiple arguments
and a call with a tuple as the only argument.</p>
</dd></dl>

<p>These two constants are not used to indicate the calling convention but the
binding when use with methods of classes.  These may not be used for functions
defined for modules.  At most one of these flags may be set for any given
method.</p>
<dl class="data">
<dt id="METH_CLASS">
<code class="descname">METH_CLASS</code><a class="headerlink" href="#METH_CLASS" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">The method will be passed the type object as the first parameter rather
than an instance of the type.  This is used to create <em>class methods</em>,
similar to what is created when using the <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> built-in
function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="METH_STATIC">
<code class="descname">METH_STATIC</code><a class="headerlink" href="#METH_STATIC" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">The method will be passed <em>NULL</em> as the first parameter rather than an
instance of the type.  This is used to create <em>static methods</em>, similar to
what is created when using the <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> built-in function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>One other constant controls whether a method is loaded in place of another
definition with the same method name.</p>
<dl class="data">
<dt id="METH_COEXIST">
<code class="descname">METH_COEXIST</code><a class="headerlink" href="#METH_COEXIST" title="Permalink to this definition">¶</a></dt>
<dd><p>The method will be loaded in place of existing definitions.  Without
<em>METH_COEXIST</em>, the default is to skip repeated definitions.  Since slot
wrappers are loaded before the method table, the existence of a
<em>sq_contains</em> slot, for example, would generate a wrapped method named
<a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> and preclude the loading of a corresponding
PyCFunction with the same name.  With the flag defined, the PyCFunction
will be loaded in place of the wrapper object and will co-exist with the
slot.  This is helpful because calls to PyCFunctions are optimized more
than wrapper object calls.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="type">
<dt id="c.PyMemberDef">
<code class="descname">PyMemberDef</code><a class="headerlink" href="#c.PyMemberDef" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure which describes an attribute of a type which corresponds to a C
struct member.  Its fields are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="21%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">C Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>char *</td>
<td>name of the member</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></td>
<td>int</td>
<td>the type of the member in the
C struct</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">offset</span></code></td>
<td>Py_ssize_t</td>
<td>the offset in bytes that the
member is located on the
type’s object struct</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>int</td>
<td>flag bits indicating if the
field should be read-only or
writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">doc</span></code></td>
<td>char *</td>
<td>points to the contents of the
docstring</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code> can be one of many <code class="docutils literal notranslate"><span class="pre">T_</span></code> macros corresponding to various C
types.  When the member is accessed in Python, it will be converted to the
equivalent Python type.</p>
<table border="1" class="docutils">
<colgroup>
<col width="45%" />
<col width="55%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Macro name</th>
<th class="head">C type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>T_SHORT</td>
<td>short</td>
</tr>
<tr class="row-odd"><td>T_INT</td>
<td>int</td>
</tr>
<tr class="row-even"><td>T_LONG</td>
<td>long</td>
</tr>
<tr class="row-odd"><td>T_FLOAT</td>
<td>float</td>
</tr>
<tr class="row-even"><td>T_DOUBLE</td>
<td>double</td>
</tr>
<tr class="row-odd"><td>T_STRING</td>
<td>char *</td>
</tr>
<tr class="row-even"><td>T_OBJECT</td>
<td>PyObject *</td>
</tr>
<tr class="row-odd"><td>T_OBJECT_EX</td>
<td>PyObject *</td>
</tr>
<tr class="row-even"><td>T_CHAR</td>
<td>char</td>
</tr>
<tr class="row-odd"><td>T_BYTE</td>
<td>char</td>
</tr>
<tr class="row-even"><td>T_UBYTE</td>
<td>unsigned char</td>
</tr>
<tr class="row-odd"><td>T_UINT</td>
<td>unsigned int</td>
</tr>
<tr class="row-even"><td>T_USHORT</td>
<td>unsigned short</td>
</tr>
<tr class="row-odd"><td>T_ULONG</td>
<td>unsigned long</td>
</tr>
<tr class="row-even"><td>T_BOOL</td>
<td>char</td>
</tr>
<tr class="row-odd"><td>T_LONGLONG</td>
<td>long long</td>
</tr>
<tr class="row-even"><td>T_ULONGLONG</td>
<td>unsigned long long</td>
</tr>
<tr class="row-odd"><td>T_PYSSIZET</td>
<td>Py_ssize_t</td>
</tr>
</tbody>
</table>
<p><code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT_EX</span></code> differ in that
<code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT</span></code> returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if the member is <em>NULL</em> and
<code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT_EX</span></code> raises an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.  Try to use
<code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT_EX</span></code> over <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT</span></code> because <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT_EX</span></code>
handles use of the <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement on that attribute more correctly
than <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT</span></code>.</p>
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code> can be <code class="docutils literal notranslate"><span class="pre">0</span></code> for write and read access or <code class="xref c c-macro docutils literal notranslate"><span class="pre">READONLY</span></code> for
read-only access.  Using <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_STRING</span></code> for <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> implies
<code class="xref c c-macro docutils literal notranslate"><span class="pre">READONLY</span></code>.  Only <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">T_OBJECT_EX</span></code>
members can be deleted.  (They are set to <em>NULL</em>).</p>
</dd></dl>

<dl class="type">
<dt id="c.PyGetSetDef">
<code class="descname">PyGetSetDef</code><a class="headerlink" href="#c.PyGetSetDef" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure to define property-like access for a type. See also description of
the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_getset" title="PyTypeObject.tp_getset"><code class="xref c c-member docutils literal notranslate"><span class="pre">PyTypeObject.tp_getset</span></code></a> slot.</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="27%" />
<col width="53%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">C Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>name</td>
<td>char *</td>
<td>attribute name</td>
</tr>
<tr class="row-odd"><td>get</td>
<td>getter</td>
<td>C Function to get the attribute</td>
</tr>
<tr class="row-even"><td>set</td>
<td>setter</td>
<td>optional C function to set or
delete the attribute, if omitted
the attribute is readonly</td>
</tr>
<tr class="row-odd"><td>doc</td>
<td>char *</td>
<td>optional docstring</td>
</tr>
<tr class="row-even"><td>closure</td>
<td>void *</td>
<td>optional function pointer,
providing additional data for
getter and setter</td>
</tr>
</tbody>
</table>
<p>The <code class="docutils literal notranslate"><span class="pre">get</span></code> function takes one <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> parameter (the
instance) and a function pointer (the associated <code class="docutils literal notranslate"><span class="pre">closure</span></code>):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="n">PyObject</span> <span class="o">*</span><span class="p">(</span><span class="o">*</span><span class="n">getter</span><span class="p">)(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="p">);</span>
</pre></div>
</div>
<p>It should return a new reference on success or <em>NULL</em> with a set exception
on failure.</p>
<p><code class="docutils literal notranslate"><span class="pre">set</span></code> functions take two <a class="reference internal" href="#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> parameters (the instance and
the value to be set) and a function pointer (the associated <code class="docutils literal notranslate"><span class="pre">closure</span></code>):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="nf">int</span> <span class="p">(</span><span class="o">*</span><span class="n">setter</span><span class="p">)(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="p">);</span>
</pre></div>
</div>
<p>In case the attribute should be deleted the second parameter is <em>NULL</em>.
Should return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> with a set exception on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_FindMethod">
<a class="reference internal" href="#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_FindMethod</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;table[]</em>, <a class="reference internal" href="#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em>, char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_FindMethod" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a bound method object for an extension type implemented in C.  This
can be useful in the implementation of a <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> or
<a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> handler that does not use the
<a class="reference internal" href="object.html#c.PyObject_GenericGetAttr" title="PyObject_GenericGetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GenericGetAttr()</span></code></a> function.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="allocation.html"
                        title="previous chapter">Allocating Objects on the Heap</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="typeobj.html"
                        title="next chapter">Type Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/structures.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="typeobj.html" title="Type Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="allocation.html" title="Allocating Objects on the Heap"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" >Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\O+��R�Rhtml/c-api/sys.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Operating System Utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Importing Modules" href="import.html" />
    <link rel="prev" title="Utilities" href="utilities.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/sys.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="import.html" title="Importing Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="utilities.html" title="Utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="operating-system-utilities">
<span id="os"></span><h1>Operating System Utilities<a class="headerlink" href="#operating-system-utilities" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.Py_FdIsInteractive">
int <code class="descname">Py_FdIsInteractive</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_FdIsInteractive" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true (nonzero) if the standard I/O file <em>fp</em> with name <em>filename</em> is
deemed interactive.  This is the case for files for which <code class="docutils literal notranslate"><span class="pre">isatty(fileno(fp))</span></code>
is true.  If the global flag <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_InteractiveFlag</span></code> is true, this function
also returns true if the <em>filename</em> pointer is <em>NULL</em> or if the name is equal to
one of the strings <code class="docutils literal notranslate"><span class="pre">'&lt;stdin&gt;'</span></code> or <code class="docutils literal notranslate"><span class="pre">'???'</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_AfterFork">
void <code class="descname">PyOS_AfterFork</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_AfterFork" title="Permalink to this definition">¶</a></dt>
<dd><p>Function to update some internal state after a process fork; this should be
called in the new process if the Python interpreter will continue to be used.
If a new executable is loaded into the new process, this function does not need
to be called.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_CheckStack">
int <code class="descname">PyOS_CheckStack</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_CheckStack" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true when the interpreter runs out of stack space.  This is a reliable
check, but is only available when <code class="xref py py-const docutils literal notranslate"><span class="pre">USE_STACKCHECK</span></code> is defined (currently
on Windows using the Microsoft Visual C++ compiler).  <code class="xref py py-const docutils literal notranslate"><span class="pre">USE_STACKCHECK</span></code>
will be defined automatically; you should never change the definition in your
own code.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_getsig">
PyOS_sighandler_t <code class="descname">PyOS_getsig</code><span class="sig-paren">(</span>int<em>&nbsp;i</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_getsig" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current signal handler for signal <em>i</em>.  This is a thin wrapper around
either <code class="xref c c-func docutils literal notranslate"><span class="pre">sigaction()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">signal()</span></code>.  Do not call those functions
directly! <code class="xref c c-type docutils literal notranslate"><span class="pre">PyOS_sighandler_t</span></code> is a typedef alias for <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span>
<span class="pre">(*)(int)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_setsig">
PyOS_sighandler_t <code class="descname">PyOS_setsig</code><span class="sig-paren">(</span>int<em>&nbsp;i</em>, PyOS_sighandler_t<em>&nbsp;h</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_setsig" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the signal handler for signal <em>i</em> to be <em>h</em>; return the old signal handler.
This is a thin wrapper around either <code class="xref c c-func docutils literal notranslate"><span class="pre">sigaction()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">signal()</span></code>.  Do
not call those functions directly!  <code class="xref c c-type docutils literal notranslate"><span class="pre">PyOS_sighandler_t</span></code> is a typedef
alias for <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">(*)(int)</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="system-functions">
<span id="systemfunctions"></span><h1>System Functions<a class="headerlink" href="#system-functions" title="Permalink to this headline">¶</a></h1>
<p>These are utility functions that make functionality from the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module
accessible to C code.  They all work with the current interpreter thread’s
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module’s dict, which is contained in the internal thread state structure.</p>
<dl class="function">
<dt id="c.PySys_GetObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">PySys_GetObject</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_GetObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the object <em>name</em> from the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module or <em>NULL</em> if it does
not exist, without setting an exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_GetFile">
FILE *<code class="descname">PySys_GetFile</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, FILE<em>&nbsp;*def</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_GetFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> associated with the object <em>name</em> in the
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, or <em>def</em> if <em>name</em> is not in the module or is not associated
with a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_SetObject">
int <code class="descname">PySys_SetObject</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_SetObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>name</em> in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module to <em>v</em> unless <em>v</em> is <em>NULL</em>, in which
case <em>name</em> is deleted from the sys module. Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code>
on error.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_ResetWarnOptions">
void <code class="descname">PySys_ResetWarnOptions</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_ResetWarnOptions" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset <a class="reference internal" href="../library/sys.html#sys.warnoptions" title="sys.warnoptions"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.warnoptions</span></code></a> to an empty list.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_AddWarnOption">
void <code class="descname">PySys_AddWarnOption</code><span class="sig-paren">(</span>char<em>&nbsp;*s</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_AddWarnOption" title="Permalink to this definition">¶</a></dt>
<dd><p>Append <em>s</em> to <a class="reference internal" href="../library/sys.html#sys.warnoptions" title="sys.warnoptions"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.warnoptions</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_SetPath">
void <code class="descname">PySys_SetPath</code><span class="sig-paren">(</span>char<em>&nbsp;*path</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_SetPath" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> to a list object of paths found in <em>path</em> which should
be a list of paths separated with the platform’s search path delimiter
(<code class="docutils literal notranslate"><span class="pre">:</span></code> on Unix, <code class="docutils literal notranslate"><span class="pre">;</span></code> on Windows).</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_WriteStdout">
void <code class="descname">PySys_WriteStdout</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_WriteStdout" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the output string described by <em>format</em> to <a class="reference internal" href="../library/sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>.  No
exceptions are raised, even if truncation occurs (see below).</p>
<p><em>format</em> should limit the total size of the formatted output string to
1000 bytes or less – after 1000 bytes, the output string is truncated.
In particular, this means that no unrestricted “%s” formats should occur;
these should be limited using “%.&lt;N&gt;s” where &lt;N&gt; is a decimal number
calculated so that &lt;N&gt; plus the maximum size of other formatted text does not
exceed 1000 bytes.  Also watch out for “%f”, which can print hundreds of
digits for very large numbers.</p>
<p>If a problem occurs, or <a class="reference internal" href="../library/sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> is unset, the formatted message
is written to the real (C level) <em>stdout</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySys_WriteStderr">
void <code class="descname">PySys_WriteStderr</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PySys_WriteStderr" title="Permalink to this definition">¶</a></dt>
<dd><p>As above, but write to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a> or <em>stderr</em> instead.</p>
</dd></dl>

</div>
<div class="section" id="process-control">
<span id="processcontrol"></span><h1>Process Control<a class="headerlink" href="#process-control" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.Py_FatalError">
void <code class="descname">Py_FatalError</code><span class="sig-paren">(</span>const char<em>&nbsp;*message</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_FatalError" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Print a fatal error message and kill the process.  No cleanup is performed.
This function should only be invoked when a condition is detected that would
make it dangerous to continue using the Python interpreter; e.g., when the
object administration appears to be corrupted.  On Unix, the standard C library
function <code class="xref c c-func docutils literal notranslate"><span class="pre">abort()</span></code> is called which will attempt to produce a <code class="file docutils literal notranslate"><span class="pre">core</span></code>
file.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_Exit">
void <code class="descname">Py_Exit</code><span class="sig-paren">(</span>int<em>&nbsp;status</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_Exit" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Exit the current process.  This calls <a class="reference internal" href="init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> and then calls the
standard C library function <code class="docutils literal notranslate"><span class="pre">exit(status)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_AtExit">
int <code class="descname">Py_AtExit</code><span class="sig-paren">(</span>void (<em>*func</em>)()<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_AtExit" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Register a cleanup function to be called by <a class="reference internal" href="init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a>.  The cleanup
function will be called with no arguments and should return no value.  At most
32 cleanup functions can be registered.  When the registration is successful,
<a class="reference internal" href="#c.Py_AtExit" title="Py_AtExit"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_AtExit()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">0</span></code>; on failure, it returns <code class="docutils literal notranslate"><span class="pre">-1</span></code>.  The cleanup
function registered last is called first. Each cleanup function will be called
at most once.  Since Python’s internal finalization will have completed before
the cleanup function, no Python APIs should be called by <em>func</em>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Operating System Utilities</a></li>
<li><a class="reference internal" href="#system-functions">System Functions</a></li>
<li><a class="reference internal" href="#process-control">Process Control</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="utilities.html"
                        title="previous chapter">Utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="import.html"
                        title="next chapter">Importing Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/sys.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="import.html" title="Importing Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="utilities.html" title="Utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����S�Shtml/c-api/tuple.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Tuple Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="List Objects" href="list.html" />
    <link rel="prev" title="Buffers and Memoryview Objects" href="buffer.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/tuple.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="list.html" title="List Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="buffer.html" title="Buffers and Memoryview Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="tuple-objects">
<span id="tupleobjects"></span><h1>Tuple Objects<a class="headerlink" href="#tuple-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyTupleObject">
<code class="descname">PyTupleObject</code><a class="headerlink" href="#c.PyTupleObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python tuple object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyTuple_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyTuple_Type</code><a class="headerlink" href="#c.PyTuple_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python tuple type; it is
the same object as <code class="docutils literal notranslate"><span class="pre">tuple</span></code> and <code class="docutils literal notranslate"><span class="pre">types.TupleType</span></code> in the Python layer..</p>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_Check">
int <code class="descname">PyTuple_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a tuple object or an instance of a subtype of the tuple
type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_CheckExact">
int <code class="descname">PyTuple_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a tuple object, but not an instance of a subtype of the
tuple type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTuple_New</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new tuple object of size <em>len</em>, or <em>NULL</em> on failure.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>len</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_Pack">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTuple_Pack</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;n</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_Pack" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new tuple object of size <em>n</em>, or <em>NULL</em> on failure. The tuple values
are initialized to the subsequent <em>n</em> C arguments pointing to Python objects.
<code class="docutils literal notranslate"><span class="pre">PyTuple_Pack(2,</span> <span class="pre">a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">Py_BuildValue(&quot;(OO)&quot;,</span> <span class="pre">a,</span> <span class="pre">b)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>n</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_Size">
Py_ssize_t <code class="descname">PyTuple_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_Size" title="Permalink to this definition">¶</a></dt>
<dd><p>Take a pointer to a tuple object, and return the size of that tuple.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_GET_SIZE">
Py_ssize_t <code class="descname">PyTuple_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of the tuple <em>p</em>, which must be non-<em>NULL</em> and point to a tuple;
no error checking is performed.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_GetItem">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTuple_GetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;pos</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_GetItem" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the object at position <em>pos</em> in the tuple pointed to by <em>p</em>.  If <em>pos</em> is
out of bounds, return <em>NULL</em> and sets an <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>pos</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_GET_ITEM">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTuple_GET_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;pos</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_GET_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Like <a class="reference internal" href="#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a>, but does no checking of its arguments.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>pos</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_GetSlice">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTuple_GetSlice</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;low</em>, Py_ssize_t<em>&nbsp;high</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_GetSlice" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Take a slice of the tuple pointed to by <em>p</em> from <em>low</em> to <em>high</em> and return it
as a new tuple.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>low</em> and <em>high</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_SetItem">
int <code class="descname">PyTuple_SetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;pos</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_SetItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a reference to object <em>o</em> at position <em>pos</em> of the tuple pointed to by
<em>p</em>. Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function “steals” a reference to <em>o</em>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>pos</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_SET_ITEM">
void <code class="descname">PyTuple_SET_ITEM</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;pos</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_SET_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a>, but does no error checking, and should <em>only</em> be
used to fill in brand new tuples.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function “steals” a reference to <em>o</em>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>pos</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c._PyTuple_Resize">
int <code class="descname">_PyTuple_Resize</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**p</em>, Py_ssize_t<em>&nbsp;newsize</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyTuple_Resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Can be used to resize a tuple.  <em>newsize</em> will be the new length of the tuple.
Because tuples are <em>supposed</em> to be immutable, this should only be used if there
is only one reference to the object.  Do <em>not</em> use this if the tuple may already
be known to some other part of the code.  The tuple will always grow or shrink
at the end.  Think of this as destroying the old tuple and creating a new one,
only more efficiently.  Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success. Client code should never
assume that the resulting value of <code class="docutils literal notranslate"><span class="pre">*p</span></code> will be the same as before calling
this function. If the object referenced by <code class="docutils literal notranslate"><span class="pre">*p</span></code> is replaced, the original
<code class="docutils literal notranslate"><span class="pre">*p</span></code> is destroyed.  On failure, returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets <code class="docutils literal notranslate"><span class="pre">*p</span></code> to <em>NULL</em>, and
raises <a class="reference internal" href="../library/exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Removed unused third parameter, <em>last_is_sticky</em>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>newsize</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTuple_ClearFreeList">
int <code class="descname">PyTuple_ClearFreeList</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTuple_ClearFreeList" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the free list. Return the total number of freed items.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="buffer.html"
                        title="previous chapter">Buffers and Memoryview Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="list.html"
                        title="next chapter">List Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/tuple.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="list.html" title="List Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="buffer.html" title="Buffers and Memoryview Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�h���:�:html/c-api/type.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Type Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="The None Object" href="none.html" />
    <link rel="prev" title="Concrete Objects Layer" href="concrete.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/type.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="none.html" title="The None Object"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="concrete.html" title="Concrete Objects Layer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="type-objects">
<span id="typeobjects"></span><h1>Type Objects<a class="headerlink" href="#type-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyTypeObject">
<code class="descname">PyTypeObject</code><a class="headerlink" href="#c.PyTypeObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure of the objects used to describe built-in types.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyType_Type">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyType_Type</code><a class="headerlink" href="#c.PyType_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This is the type object for type objects; it is the same object as <code class="docutils literal notranslate"><span class="pre">type</span></code> and
<code class="docutils literal notranslate"><span class="pre">types.TypeType</span></code> in the Python layer.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyType_Check">
int <code class="descname">PyType_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a type object, including instances of types
derived from the standard type object.  Return false in all other cases.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyType_CheckExact">
int <code class="descname">PyType_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a type object, but not a subtype of the
standard type object.  Return false in all other cases.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_ClearCache">
unsigned int <code class="descname">PyType_ClearCache</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_ClearCache" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the internal lookup cache. Return the current version tag.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_Modified">
void <code class="descname">PyType_Modified</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_Modified" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalidate the internal lookup cache for the type and all of its
subtypes.  This function must be called after any manual
modification of the attributes or base classes of the type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_HasFeature">
int <code class="descname">PyType_HasFeature</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em>, int<em>&nbsp;feature</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_HasFeature" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the type object <em>o</em> sets the feature <em>feature</em>.  Type features
are denoted by single bit flags.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyType_IS_GC">
int <code class="descname">PyType_IS_GC</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_IS_GC" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the type object includes support for the cycle detector; this
tests the type flag <a class="reference internal" href="typeobj.html#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_IsSubtype">
int <code class="descname">PyType_IsSubtype</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*a</em>, <a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*b</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_IsSubtype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>a</em> is a subtype of <em>b</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>This function only checks for actual subtypes, which means that
<a class="reference internal" href="../reference/datamodel.html#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a> is not called on <em>b</em>.  Call
<a class="reference internal" href="object.html#c.PyObject_IsSubclass" title="PyObject_IsSubclass"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_IsSubclass()</span></code></a> to do the same check that <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>
would do.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyType_GenericAlloc">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyType_GenericAlloc</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, Py_ssize_t<em>&nbsp;nitems</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_GenericAlloc" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>nitems</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_GenericNew">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyType_GenericNew</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_GenericNew" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyType_Ready">
int <code class="descname">PyType_Ready</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyType_Ready" title="Permalink to this definition">¶</a></dt>
<dd><p>Finalize a type object.  This should be called on all type objects to finish
their initialization.  This function is responsible for adding inherited slots
from a type’s base class.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, or return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and sets an
exception on error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="concrete.html"
                        title="previous chapter">Concrete Objects Layer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="none.html"
                        title="next chapter">The <code class="docutils literal notranslate"><span class="pre">None</span></code> Object</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/type.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="none.html" title="The None Object"
             >next</a> |</li>
        <li class="right" >
          <a href="concrete.html" title="Concrete Objects Layer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\K�Yi����html/c-api/typeobj.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Type Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Supporting Cyclic Garbage Collection" href="gcsupport.html" />
    <link rel="prev" title="Common Object Structures" href="structures.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/typeobj.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gcsupport.html" title="Supporting Cyclic Garbage Collection"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="structures.html" title="Common Object Structures"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" accesskey="U">Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="type-objects">
<span id="type-structs"></span><h1>Type Objects<a class="headerlink" href="#type-objects" title="Permalink to this headline">¶</a></h1>
<p>Perhaps one of the most important structures of the Python object system is the
structure that defines a new type: the <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> structure.  Type
objects can be handled using any of the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_*()</span></code> or
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_*()</span></code> functions, but do not offer much that’s interesting to most
Python applications. These objects are fundamental to how objects behave, so
they are very important to the interpreter itself and to any extension module
that implements new types.</p>
<p>Type objects are fairly large compared to most of the standard types. The reason
for the size is that each type object stores a large number of values, mostly C
function pointers, each of which implements a small part of the type’s
functionality.  The fields of the type object are examined in detail in this
section.  The fields will be described in the order in which they occur in the
structure.</p>
<p>Typedefs: unaryfunc, binaryfunc, ternaryfunc, inquiry, coercion, intargfunc,
intintargfunc, intobjargproc, intintobjargproc, objobjargproc, destructor,
freefunc, printfunc, getattrfunc, getattrofunc, setattrfunc, setattrofunc,
cmpfunc, reprfunc, hashfunc</p>
<p>The structure definition for <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> can be found in
<code class="file docutils literal notranslate"><span class="pre">Include/object.h</span></code>.  For convenience of reference, this repeats the
definition found there:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="n">_typeobject</span> <span class="p">{</span>
    <span class="n">PyObject_VAR_HEAD</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">tp_name</span><span class="p">;</span> <span class="cm">/* For printing, in format &quot;&lt;module&gt;.&lt;name&gt;&quot; */</span>
    <span class="kt">int</span> <span class="n">tp_basicsize</span><span class="p">,</span> <span class="n">tp_itemsize</span><span class="p">;</span> <span class="cm">/* For allocation */</span>

    <span class="cm">/* Methods to implement standard operations */</span>

    <span class="n">destructor</span> <span class="n">tp_dealloc</span><span class="p">;</span>
    <span class="n">printfunc</span> <span class="n">tp_print</span><span class="p">;</span>
    <span class="n">getattrfunc</span> <span class="n">tp_getattr</span><span class="p">;</span>
    <span class="n">setattrfunc</span> <span class="n">tp_setattr</span><span class="p">;</span>
    <span class="n">cmpfunc</span> <span class="n">tp_compare</span><span class="p">;</span>
    <span class="n">reprfunc</span> <span class="n">tp_repr</span><span class="p">;</span>

    <span class="cm">/* Method suites for standard classes */</span>

    <span class="n">PyNumberMethods</span> <span class="o">*</span><span class="n">tp_as_number</span><span class="p">;</span>
    <span class="n">PySequenceMethods</span> <span class="o">*</span><span class="n">tp_as_sequence</span><span class="p">;</span>
    <span class="n">PyMappingMethods</span> <span class="o">*</span><span class="n">tp_as_mapping</span><span class="p">;</span>

    <span class="cm">/* More standard operations (here for binary compatibility) */</span>

    <span class="n">hashfunc</span> <span class="n">tp_hash</span><span class="p">;</span>
    <span class="n">ternaryfunc</span> <span class="n">tp_call</span><span class="p">;</span>
    <span class="n">reprfunc</span> <span class="n">tp_str</span><span class="p">;</span>
    <span class="n">getattrofunc</span> <span class="n">tp_getattro</span><span class="p">;</span>
    <span class="n">setattrofunc</span> <span class="n">tp_setattro</span><span class="p">;</span>

    <span class="cm">/* Functions to access object as input/output buffer */</span>
    <span class="n">PyBufferProcs</span> <span class="o">*</span><span class="n">tp_as_buffer</span><span class="p">;</span>

    <span class="cm">/* Flags to define presence of optional/expanded features */</span>
    <span class="kt">long</span> <span class="n">tp_flags</span><span class="p">;</span>

    <span class="kt">char</span> <span class="o">*</span><span class="n">tp_doc</span><span class="p">;</span> <span class="cm">/* Documentation string */</span>

    <span class="cm">/* Assigned meaning in release 2.0 */</span>
    <span class="cm">/* call function for all accessible objects */</span>
    <span class="n">traverseproc</span> <span class="n">tp_traverse</span><span class="p">;</span>

    <span class="cm">/* delete references to contained objects */</span>
    <span class="n">inquiry</span> <span class="n">tp_clear</span><span class="p">;</span>

    <span class="cm">/* Assigned meaning in release 2.1 */</span>
    <span class="cm">/* rich comparisons */</span>
    <span class="n">richcmpfunc</span> <span class="n">tp_richcompare</span><span class="p">;</span>

    <span class="cm">/* weak reference enabler */</span>
    <span class="kt">long</span> <span class="n">tp_weaklistoffset</span><span class="p">;</span>

    <span class="cm">/* Added in release 2.2 */</span>
    <span class="cm">/* Iterators */</span>
    <span class="n">getiterfunc</span> <span class="n">tp_iter</span><span class="p">;</span>
    <span class="n">iternextfunc</span> <span class="n">tp_iternext</span><span class="p">;</span>

    <span class="cm">/* Attribute descriptor and subclassing stuff */</span>
    <span class="k">struct</span> <span class="n">PyMethodDef</span> <span class="o">*</span><span class="n">tp_methods</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">PyMemberDef</span> <span class="o">*</span><span class="n">tp_members</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">PyGetSetDef</span> <span class="o">*</span><span class="n">tp_getset</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">_typeobject</span> <span class="o">*</span><span class="n">tp_base</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_dict</span><span class="p">;</span>
    <span class="n">descrgetfunc</span> <span class="n">tp_descr_get</span><span class="p">;</span>
    <span class="n">descrsetfunc</span> <span class="n">tp_descr_set</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">tp_dictoffset</span><span class="p">;</span>
    <span class="n">initproc</span> <span class="n">tp_init</span><span class="p">;</span>
    <span class="n">allocfunc</span> <span class="n">tp_alloc</span><span class="p">;</span>
    <span class="n">newfunc</span> <span class="n">tp_new</span><span class="p">;</span>
    <span class="n">freefunc</span> <span class="n">tp_free</span><span class="p">;</span> <span class="cm">/* Low-level free-memory routine */</span>
    <span class="n">inquiry</span> <span class="n">tp_is_gc</span><span class="p">;</span> <span class="cm">/* For PyObject_IS_GC */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_bases</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_mro</span><span class="p">;</span> <span class="cm">/* method resolution order */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_cache</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_subclasses</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_weaklist</span><span class="p">;</span>

<span class="p">}</span> <span class="n">PyTypeObject</span><span class="p">;</span>
</pre></div>
</div>
<p>The type object structure extends the <a class="reference internal" href="structures.html#c.PyVarObject" title="PyVarObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyVarObject</span></code></a> structure. The
<code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field is used for dynamic types (created by  <code class="xref py py-func docutils literal notranslate"><span class="pre">type_new()</span></code>,
usually called from a class statement). Note that <a class="reference internal" href="type.html#c.PyType_Type" title="PyType_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyType_Type</span></code></a> (the
metatype) initializes <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a>, which means that its instances (i.e.
type objects) <em>must</em> have the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field.</p>
<dl class="member">
<dt id="c.PyObject._ob_next">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject._ob_next</code><a class="headerlink" href="#c.PyObject._ob_next" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyObject._ob_prev">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject._ob_prev</code><a class="headerlink" href="#c.PyObject._ob_prev" title="Permalink to this definition">¶</a></dt>
<dd><p>These fields are only present when the macro <code class="docutils literal notranslate"><span class="pre">Py_TRACE_REFS</span></code> is defined.
Their initialization to <em>NULL</em> is taken care of by the <code class="docutils literal notranslate"><span class="pre">PyObject_HEAD_INIT</span></code>
macro.  For statically allocated objects, these fields always remain <em>NULL</em>.
For dynamically allocated objects, these two fields are used to link the object
into a doubly-linked list of <em>all</em> live objects on the heap.  This could be used
for various debugging purposes; currently the only use is to print the objects
that are still alive at the end of a run when the environment variable
<span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDUMPREFS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDUMPREFS</span></code></a> is set.</p>
<p>These fields are not inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyObject.ob_refcnt">
Py_ssize_t <code class="descname">PyObject.ob_refcnt</code><a class="headerlink" href="#c.PyObject.ob_refcnt" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the type object’s reference count, initialized to <code class="docutils literal notranslate"><span class="pre">1</span></code> by the
<code class="docutils literal notranslate"><span class="pre">PyObject_HEAD_INIT</span></code> macro.  Note that for statically allocated type objects,
the type’s instances (objects whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> points back to the type) do
<em>not</em> count as references.  But for dynamically allocated type objects, the
instances <em>do</em> count as references.</p>
<p>This field is not inherited by subtypes.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This field used to be an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="member">
<dt id="c.PyObject.ob_type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a>* <code class="descname">PyObject.ob_type</code><a class="headerlink" href="#c.PyObject.ob_type" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the type’s type, in other words its metatype.  It is initialized by the
argument to the <code class="docutils literal notranslate"><span class="pre">PyObject_HEAD_INIT</span></code> macro, and its value should normally be
<code class="docutils literal notranslate"><span class="pre">&amp;PyType_Type</span></code>.  However, for dynamically loadable extension modules that must
be usable on Windows (at least), the compiler complains that this is not a valid
initializer.  Therefore, the convention is to pass <em>NULL</em> to the
<code class="docutils literal notranslate"><span class="pre">PyObject_HEAD_INIT</span></code> macro and to initialize this field explicitly at the
start of the module’s initialization function, before doing anything else.  This
is typically done like this:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Foo_Type</span><span class="p">.</span><span class="n">ob_type</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">PyType_Type</span><span class="p">;</span>
</pre></div>
</div>
<p>This should be done before any instances of the type are created.
<a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> checks if <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> is <em>NULL</em>, and if so,
initializes it: in Python 2.2, it is set to <code class="docutils literal notranslate"><span class="pre">&amp;PyType_Type</span></code>; in Python 2.2.1
and later it is initialized to the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> field of the base class.
<a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> will not change this field if it is non-zero.</p>
<p>In Python 2.2, this field is not inherited by subtypes.  In 2.2.1, and in 2.3
and beyond, it is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyVarObject.ob_size">
Py_ssize_t <code class="descname">PyVarObject.ob_size</code><a class="headerlink" href="#c.PyVarObject.ob_size" title="Permalink to this definition">¶</a></dt>
<dd><p>For statically allocated type objects, this should be initialized to zero.  For
dynamically allocated type objects, this field has a special internal meaning.</p>
<p>This field is not inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_name">
char* <code class="descname">PyTypeObject.tp_name</code><a class="headerlink" href="#c.PyTypeObject.tp_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to a NUL-terminated string containing the name of the type. For types
that are accessible as module globals, the string should be the full module
name, followed by a dot, followed by the type name; for built-in types, it
should be just the type name.  If the module is a submodule of a package, the
full package name is part of the full module name.  For example, a type named
<code class="xref py py-class docutils literal notranslate"><span class="pre">T</span></code> defined in module <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code> in subpackage <code class="xref py py-mod docutils literal notranslate"><span class="pre">Q</span></code> in package <code class="xref py py-mod docutils literal notranslate"><span class="pre">P</span></code>
should have the <a class="reference internal" href="#c.PyTypeObject.tp_name" title="PyTypeObject.tp_name"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_name</span></code></a> initializer <code class="docutils literal notranslate"><span class="pre">&quot;P.Q.M.T&quot;</span></code>.</p>
<p>For dynamically allocated type objects, this should just be the type name, and
the module name explicitly stored in the type dict as the value for key
<code class="docutils literal notranslate"><span class="pre">'__module__'</span></code>.</p>
<p>For statically allocated type objects, the tp_name field should contain a dot.
Everything before the last dot is made accessible as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code>
attribute, and everything after the last dot is made accessible as the
<a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute.</p>
<p>If no dot is present, the entire <a class="reference internal" href="#c.PyTypeObject.tp_name" title="PyTypeObject.tp_name"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_name</span></code></a> field is made accessible as the
<a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute, and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> attribute is undefined
(unless explicitly set in the dictionary, as explained above).  This means your
type will be impossible to pickle.  Additionally, it will not be listed in
module documentations created with pydoc.</p>
<p>This field is not inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_basicsize">
Py_ssize_t <code class="descname">PyTypeObject.tp_basicsize</code><a class="headerlink" href="#c.PyTypeObject.tp_basicsize" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyTypeObject.tp_itemsize">
Py_ssize_t <code class="descname">PyTypeObject.tp_itemsize</code><a class="headerlink" href="#c.PyTypeObject.tp_itemsize" title="Permalink to this definition">¶</a></dt>
<dd><p>These fields allow calculating the size in bytes of instances of the type.</p>
<p>There are two kinds of types: types with fixed-length instances have a zero
<a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> field, types with variable-length instances have a non-zero
<a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> field.  For a type with fixed-length instances, all
instances have the same size, given in <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a>.</p>
<p>For a type with variable-length instances, the instances must have an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field, and the instance size is <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> plus N
times <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a>, where N is the “length” of the object.  The value of
N is typically stored in the instance’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field.  There are
exceptions:  for example, long ints use a negative <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> to indicate a
negative number, and N is <code class="docutils literal notranslate"><span class="pre">abs(ob_size)</span></code> there.  Also, the presence of an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field in the instance layout doesn’t mean that the instance
structure is variable-length (for example, the structure for the list type has
fixed-length instances, yet those instances have a meaningful <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code>
field).</p>
<p>The basic size includes the fields in the instance declared by the macro
<a class="reference internal" href="structures.html#c.PyObject_HEAD" title="PyObject_HEAD"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code></a> or <a class="reference internal" href="structures.html#c.PyObject_VAR_HEAD" title="PyObject_VAR_HEAD"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyObject_VAR_HEAD</span></code></a> (whichever is used to
declare the instance struct) and this in turn includes the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_ob_prev</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">_ob_next</span></code> fields if they are present.  This means that the only correct
way to get an initializer for the <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> is to use the
<code class="docutils literal notranslate"><span class="pre">sizeof</span></code> operator on the struct used to declare the instance layout.
The basic size does not include the GC header size (this is new in Python 2.2;
in 2.1 and 2.0, the GC header size was included in <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a>).</p>
<p>These fields are inherited separately by subtypes.  If the base type has a
non-zero <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a>, it is generally not safe to set
<a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> to a different non-zero value in a subtype (though this
depends on the implementation of the base type).</p>
<p>A note about alignment: if the variable items require a particular alignment,
this should be taken care of by the value of <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a>.  Example:
suppose a type implements an array of <code class="docutils literal notranslate"><span class="pre">double</span></code>. <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> is
<code class="docutils literal notranslate"><span class="pre">sizeof(double)</span></code>. It is the programmer’s responsibility that
<a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> is a multiple of <code class="docutils literal notranslate"><span class="pre">sizeof(double)</span></code> (assuming this is the
alignment requirement for <code class="docutils literal notranslate"><span class="pre">double</span></code>).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_dealloc">
destructor <code class="descname">PyTypeObject.tp_dealloc</code><a class="headerlink" href="#c.PyTypeObject.tp_dealloc" title="Permalink to this definition">¶</a></dt>
<dd><p>A pointer to the instance destructor function.  This function must be defined
unless the type guarantees that its instances will never be deallocated (as is
the case for the singletons <code class="docutils literal notranslate"><span class="pre">None</span></code> and <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>).</p>
<p>The destructor function is called by the <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> and
<a class="reference internal" href="refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> macros when the new reference count is zero.  At this point,
the instance is still in existence, but there are no references to it.  The
destructor function should free all references which the instance owns, free all
memory buffers owned by the instance (using the freeing function corresponding
to the allocation function used to allocate the buffer), and finally (as its
last action) call the type’s <a class="reference internal" href="#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_free</span></code></a> function.  If the type is not
subtypable (doesn’t have the <a class="reference internal" href="#Py_TPFLAGS_BASETYPE" title="Py_TPFLAGS_BASETYPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_BASETYPE</span></code></a> flag bit set), it is
permissible to call the object deallocator directly instead of via
<a class="reference internal" href="#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_free</span></code></a>.  The object deallocator should be the one used to allocate the
instance; this is normally <a class="reference internal" href="allocation.html#c.PyObject_Del" title="PyObject_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Del()</span></code></a> if the instance was allocated
using <a class="reference internal" href="allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a> or <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_VarNew()</span></code>, or
<a class="reference internal" href="gcsupport.html#c.PyObject_GC_Del" title="PyObject_GC_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Del()</span></code></a> if the instance was allocated using
<a class="reference internal" href="gcsupport.html#c.PyObject_GC_New" title="PyObject_GC_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_New()</span></code></a> or <a class="reference internal" href="gcsupport.html#c.PyObject_GC_NewVar" title="PyObject_GC_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_NewVar()</span></code></a>.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_print">
printfunc <code class="descname">PyTypeObject.tp_print</code><a class="headerlink" href="#c.PyTypeObject.tp_print" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the instance print function.</p>
<p>The print function is only called when the instance is printed to a <em>real</em> file;
when it is printed to a pseudo-file (like a <a class="reference internal" href="../library/stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> instance), the
instance’s <a class="reference internal" href="#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> or <a class="reference internal" href="#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> function is called to convert it to
a string.  These are also called when the type’s <a class="reference internal" href="#c.PyTypeObject.tp_print" title="PyTypeObject.tp_print"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_print</span></code></a> field is
<em>NULL</em>.  A type should never implement <a class="reference internal" href="#c.PyTypeObject.tp_print" title="PyTypeObject.tp_print"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_print</span></code></a> in a way that produces
different output than <a class="reference internal" href="#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> or <a class="reference internal" href="#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> would.</p>
<p>The print function is called with the same signature as <a class="reference internal" href="object.html#c.PyObject_Print" title="PyObject_Print"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Print()</span></code></a>:
<code class="docutils literal notranslate"><span class="pre">int</span> <span class="pre">tp_print(PyObject</span> <span class="pre">*self,</span> <span class="pre">FILE</span> <span class="pre">*file,</span> <span class="pre">int</span> <span class="pre">flags)</span></code>.  The <em>self</em> argument is
the instance to be printed.  The <em>file</em> argument is the stdio file to which it
is to be printed.  The <em>flags</em> argument is composed of flag bits. The only flag
bit currently defined is <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code>. When the <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code>
flag bit is set, the instance should be printed the same way as <a class="reference internal" href="#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a>
would format it; when the <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code> flag bit is clear, the instance
should be printed the same was as <a class="reference internal" href="#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> would format it. It should
return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and set an exception condition when an error occurred during the
comparison.</p>
<p>It is possible that the <a class="reference internal" href="#c.PyTypeObject.tp_print" title="PyTypeObject.tp_print"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_print</span></code></a> field will be deprecated. In any case,
it is recommended not to define <a class="reference internal" href="#c.PyTypeObject.tp_print" title="PyTypeObject.tp_print"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_print</span></code></a>, but instead to rely on
<a class="reference internal" href="#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> for printing.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_getattr">
getattrfunc <code class="descname">PyTypeObject.tp_getattr</code><a class="headerlink" href="#c.PyTypeObject.tp_getattr" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the get-attribute-string function.</p>
<p>This field is deprecated.  When it is defined, it should point to a function
that acts the same as the <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> function, but taking a C string
instead of a Python string object to give the attribute name.  The signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span> <span class="nf">tp_getattr</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">o</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">attr_name</span><span class="p">);</span>
</pre></div>
</div>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a>: a subtype
inherits both <a class="reference internal" href="#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> from its base type when
the subtype’s <a class="reference internal" href="#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> are both <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_setattr">
setattrfunc <code class="descname">PyTypeObject.tp_setattr</code><a class="headerlink" href="#c.PyTypeObject.tp_setattr" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the function for setting and deleting attributes.</p>
<p>This field is deprecated.  When it is defined, it should point to a function
that acts the same as the <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> function, but taking a C string
instead of a Python string object to give the attribute name.  The signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span> <span class="nf">tp_setattr</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">o</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">attr_name</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
</pre></div>
</div>
<p>The <em>v</em> argument is set to <em>NULL</em> to delete the attribute.
This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a>: a subtype
inherits both <a class="reference internal" href="#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> from its base type when
the subtype’s <a class="reference internal" href="#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> are both <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_compare">
cmpfunc <code class="descname">PyTypeObject.tp_compare</code><a class="headerlink" href="#c.PyTypeObject.tp_compare" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the three-way comparison function.</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_Compare" title="PyObject_Compare"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Compare()</span></code></a>. The function should
return <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>self</em> greater than <em>other</em>, <code class="docutils literal notranslate"><span class="pre">0</span></code> if <em>self</em> is equal to
<em>other</em>, and <code class="docutils literal notranslate"><span class="pre">-1</span></code> if <em>self</em> less than <em>other</em>.  It should return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and
set an exception condition when an error occurred during the comparison.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> and
<a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a>: a subtypes inherits all three of <a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a> when the subtype’s
<a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a> are all <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_repr">
reprfunc <code class="descname">PyTypeObject.tp_repr</code><a class="headerlink" href="#c.PyTypeObject.tp_repr" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">An optional pointer to a function that implements the built-in function
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_Repr" title="PyObject_Repr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Repr()</span></code></a>; it must return a string
or a Unicode object.  Ideally, this function should return a string that, when
passed to <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, given a suitable environment, returns an object with the
same value.  If this is not feasible, it should return a string starting with
<code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and ending with <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> from which both the type and the value of the
object can be deduced.</p>
<p>When this field is not set, a string of the form <code class="docutils literal notranslate"><span class="pre">&lt;%s</span> <span class="pre">object</span> <span class="pre">at</span> <span class="pre">%p&gt;</span></code> is
returned, where <code class="docutils literal notranslate"><span class="pre">%s</span></code> is replaced by the type name, and <code class="docutils literal notranslate"><span class="pre">%p</span></code> by the object’s
memory address.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.tp_as_number">
<a class="reference internal" href="#c.PyNumberMethods" title="PyNumberMethods">PyNumberMethods</a>* <code class="descname">tp_as_number</code><a class="headerlink" href="#c.tp_as_number" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to an additional structure that contains fields relevant only to
objects which implement the number protocol.  These fields are documented in
<a class="reference internal" href="#number-structs"><span class="std std-ref">Number Object Structures</span></a>.</p>
<p>The <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_number</span></code> field is not inherited, but the contained fields are
inherited individually.</p>
</dd></dl>

<dl class="member">
<dt id="c.tp_as_sequence">
<a class="reference internal" href="#c.PySequenceMethods" title="PySequenceMethods">PySequenceMethods</a>* <code class="descname">tp_as_sequence</code><a class="headerlink" href="#c.tp_as_sequence" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to an additional structure that contains fields relevant only to
objects which implement the sequence protocol.  These fields are documented
in <a class="reference internal" href="#sequence-structs"><span class="std std-ref">Sequence Object Structures</span></a>.</p>
<p>The <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_sequence</span></code> field is not inherited, but the contained fields
are inherited individually.</p>
</dd></dl>

<dl class="member">
<dt id="c.tp_as_mapping">
<a class="reference internal" href="#c.PyMappingMethods" title="PyMappingMethods">PyMappingMethods</a>* <code class="descname">tp_as_mapping</code><a class="headerlink" href="#c.tp_as_mapping" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to an additional structure that contains fields relevant only to
objects which implement the mapping protocol.  These fields are documented in
<a class="reference internal" href="#mapping-structs"><span class="std std-ref">Mapping Object Structures</span></a>.</p>
<p>The <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_mapping</span></code> field is not inherited, but the contained fields
are inherited individually.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_hash">
hashfunc <code class="descname">PyTypeObject.tp_hash</code><a class="headerlink" href="#c.PyTypeObject.tp_hash" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">An optional pointer to a function that implements the built-in function
<a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a>.</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_Hash" title="PyObject_Hash"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Hash()</span></code></a>; it must return a C
long.  The value <code class="docutils literal notranslate"><span class="pre">-1</span></code> should not be returned as a normal return value; when an
error occurs during the computation of the hash value, the function should set
an exception and return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
<p>This field can be set explicitly to <a class="reference internal" href="object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a> to
block inheritance of the hash method from a parent type. This is interpreted
as the equivalent of <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> at the Python level, causing
<code class="docutils literal notranslate"><span class="pre">isinstance(o,</span> <span class="pre">collections.Hashable)</span></code> to correctly return <code class="docutils literal notranslate"><span class="pre">False</span></code>. Note
that the converse is also true - setting <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> on a class at
the Python level will result in the <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> slot being set to
<a class="reference internal" href="object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.</p>
<p>When this field is not set, two possibilities exist: if the <a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>
and <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> fields are both <em>NULL</em>, a default hash value based on
the object’s address is returned; otherwise, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> and
<a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>: a subtypes inherits all three of <a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a>, when the subtype’s
<a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a> are all <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_call">
ternaryfunc <code class="descname">PyTypeObject.tp_call</code><a class="headerlink" href="#c.PyTypeObject.tp_call" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function that implements calling the object.  This
should be <em>NULL</em> if the object is not callable.  The signature is the same as
for <a class="reference internal" href="object.html#c.PyObject_Call" title="PyObject_Call"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Call()</span></code></a>.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_str">
reprfunc <code class="descname">PyTypeObject.tp_str</code><a class="headerlink" href="#c.PyTypeObject.tp_str" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function that implements the built-in operation
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.  (Note that <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> is a type now, and <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> calls the
constructor for that type.  This constructor calls <a class="reference internal" href="object.html#c.PyObject_Str" title="PyObject_Str"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Str()</span></code></a> to do
the actual work, and <a class="reference internal" href="object.html#c.PyObject_Str" title="PyObject_Str"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Str()</span></code></a> will call this handler.)</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_Str" title="PyObject_Str"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Str()</span></code></a>; it must return a string
or a Unicode object.  This function should return a “friendly” string
representation of the object, as this is the representation that will be used by
the print statement.</p>
<p>When this field is not set, <a class="reference internal" href="object.html#c.PyObject_Repr" title="PyObject_Repr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Repr()</span></code></a> is called to return a string
representation.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_getattro">
getattrofunc <code class="descname">PyTypeObject.tp_getattro</code><a class="headerlink" href="#c.PyTypeObject.tp_getattro" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the get-attribute function.</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_GetAttr" title="PyObject_GetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetAttr()</span></code></a>.  It is usually
convenient to set this field to <a class="reference internal" href="object.html#c.PyObject_GenericGetAttr" title="PyObject_GenericGetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GenericGetAttr()</span></code></a>, which
implements the normal way of looking for object attributes.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a>: a subtype
inherits both <a class="reference internal" href="#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> from its base type when
the subtype’s <a class="reference internal" href="#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> are both <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_setattro">
setattrofunc <code class="descname">PyTypeObject.tp_setattro</code><a class="headerlink" href="#c.PyTypeObject.tp_setattro" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the function for setting and deleting attributes.</p>
<p>The signature is the same as for <a class="reference internal" href="object.html#c.PyObject_SetAttr" title="PyObject_SetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetAttr()</span></code></a>, but setting
<em>v</em> to <em>NULL</em> to delete an attribute must be supported.  It is usually
convenient to set this field to <a class="reference internal" href="object.html#c.PyObject_GenericSetAttr" title="PyObject_GenericSetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GenericSetAttr()</span></code></a>, which
implements the normal way of setting object attributes.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a>: a subtype
inherits both <a class="reference internal" href="#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> from its base type when
the subtype’s <a class="reference internal" href="#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> are both <em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_as_buffer">
<a class="reference internal" href="#c.PyBufferProcs" title="PyBufferProcs">PyBufferProcs</a>* <code class="descname">PyTypeObject.tp_as_buffer</code><a class="headerlink" href="#c.PyTypeObject.tp_as_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to an additional structure that contains fields relevant only to objects
which implement the buffer interface.  These fields are documented in
<a class="reference internal" href="#buffer-structs"><span class="std std-ref">Buffer Object Structures</span></a>.</p>
<p>The <a class="reference internal" href="#c.PyTypeObject.tp_as_buffer" title="PyTypeObject.tp_as_buffer"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_buffer</span></code></a> field is not inherited, but the contained fields are
inherited individually.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_flags">
long <code class="descname">PyTypeObject.tp_flags</code><a class="headerlink" href="#c.PyTypeObject.tp_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>This field is a bit mask of various flags.  Some flags indicate variant
semantics for certain situations; others are used to indicate that certain
fields in the type object (or in the extension structures referenced via
<code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_number</span></code>, <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_sequence</span></code>, <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_mapping</span></code>, and
<a class="reference internal" href="#c.PyTypeObject.tp_as_buffer" title="PyTypeObject.tp_as_buffer"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_buffer</span></code></a>) that were historically not always present are valid; if
such a flag bit is clear, the type fields it guards must not be accessed and
must be considered to have a zero or <em>NULL</em> value instead.</p>
<p>Inheritance of this field is complicated.  Most flag bits are inherited
individually, i.e. if the base type has a flag bit set, the subtype inherits
this flag bit.  The flag bits that pertain to extension structures are strictly
inherited if the extension structure is inherited, i.e. the base type’s value of
the flag bit is copied into the subtype together with a pointer to the extension
structure.  The <a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit is inherited together with
the <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> fields, i.e. if the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit is clear in the subtype and the
<a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> fields in the subtype exist (as
indicated by the <a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a> flag bit) and have <em>NULL</em>
values.</p>
<p>The following bit masks are currently defined; these can be ORed together using
the <code class="docutils literal notranslate"><span class="pre">|</span></code> operator to form the value of the <a class="reference internal" href="#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_flags</span></code></a> field.  The macro
<a class="reference internal" href="type.html#c.PyType_HasFeature" title="PyType_HasFeature"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_HasFeature()</span></code></a> takes a type and a flags value, <em>tp</em> and <em>f</em>, and
checks whether <code class="docutils literal notranslate"><span class="pre">tp-&gt;tp_flags</span> <span class="pre">&amp;</span> <span class="pre">f</span></code> is non-zero.</p>
<dl class="data">
<dt id="Py_TPFLAGS_HAVE_GETCHARBUFFER">
<code class="descname">Py_TPFLAGS_HAVE_GETCHARBUFFER</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_GETCHARBUFFER" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the <a class="reference internal" href="#c.PyBufferProcs" title="PyBufferProcs"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBufferProcs</span></code></a> struct referenced by
<a class="reference internal" href="#c.PyTypeObject.tp_as_buffer" title="PyTypeObject.tp_as_buffer"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_buffer</span></code></a> has the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code> field.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_SEQUENCE_IN">
<code class="descname">Py_TPFLAGS_HAVE_SEQUENCE_IN</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_SEQUENCE_IN" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the <a class="reference internal" href="#c.PySequenceMethods" title="PySequenceMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PySequenceMethods</span></code></a> struct referenced by
<code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_sequence</span></code> has the <code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_contains</span></code> field.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_GC">
<code class="descname">Py_TPFLAGS_GC</code><a class="headerlink" href="#Py_TPFLAGS_GC" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is obsolete.  The bit it used to name is no longer in use.  The symbol
is now defined as zero.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_INPLACEOPS">
<code class="descname">Py_TPFLAGS_HAVE_INPLACEOPS</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_INPLACEOPS" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the <a class="reference internal" href="#c.PySequenceMethods" title="PySequenceMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PySequenceMethods</span></code></a> struct referenced by
<code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_sequence</span></code> and the <a class="reference internal" href="#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure referenced by
<code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_number</span></code> contain the fields for in-place operators. In particular,
this means that the <a class="reference internal" href="#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure has the fields
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_add</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_subtract</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_multiply</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_divide</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_remainder</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_power</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_lshift</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_rshift</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_and</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_xor</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_inplace_or</span></code>; and the
<a class="reference internal" href="#c.PySequenceMethods" title="PySequenceMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PySequenceMethods</span></code></a> struct has the fields <code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_inplace_concat</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_inplace_repeat</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_CHECKTYPES">
<code class="descname">Py_TPFLAGS_CHECKTYPES</code><a class="headerlink" href="#Py_TPFLAGS_CHECKTYPES" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the binary and ternary operations in the
<a class="reference internal" href="#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure referenced by <code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_number</span></code> accept
arguments of arbitrary object types, and do their own type conversions if
needed.  If this bit is clear, those operations require that all arguments have
the current type as their type, and the caller is supposed to perform a coercion
operation first.  This applies to <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_add</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_subtract</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_multiply</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_divide</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_remainder</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_divmod</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_power</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_lshift</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_rshift</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_and</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_xor</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_or</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_RICHCOMPARE">
<code class="descname">Py_TPFLAGS_HAVE_RICHCOMPARE</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the type object has the <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> field, as
well as the <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> and the <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> fields.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_WEAKREFS">
<code class="descname">Py_TPFLAGS_HAVE_WEAKREFS</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_WEAKREFS" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the <a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a> field is defined.  Instances
of a type are weakly referenceable if the type’s <a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a> field
has a value greater than zero.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_ITER">
<code class="descname">Py_TPFLAGS_HAVE_ITER</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_ITER" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the type object has the <a class="reference internal" href="#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> and
<a class="reference internal" href="#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iternext</span></code></a> fields.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_CLASS">
<code class="descname">Py_TPFLAGS_HAVE_CLASS</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_CLASS" title="Permalink to this definition">¶</a></dt>
<dd><p>If this bit is set, the type object has several new fields defined starting in
Python 2.2: <a class="reference internal" href="#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_methods</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_members" title="PyTypeObject.tp_members"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_members</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_getset" title="PyTypeObject.tp_getset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getset</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_base" title="PyTypeObject.tp_base"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_base</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_dict" title="PyTypeObject.tp_dict"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dict</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_descr_get" title="PyTypeObject.tp_descr_get"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_descr_get</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_descr_set" title="PyTypeObject.tp_descr_set"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_descr_set</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_alloc</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_free</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_is_gc" title="PyTypeObject.tp_is_gc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_is_gc</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_bases" title="PyTypeObject.tp_bases"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_bases</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_mro" title="PyTypeObject.tp_mro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_mro</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_cache" title="PyTypeObject.tp_cache"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_cache</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_subclasses" title="PyTypeObject.tp_subclasses"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_subclasses</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_weaklist" title="PyTypeObject.tp_weaklist"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklist</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HEAPTYPE">
<code class="descname">Py_TPFLAGS_HEAPTYPE</code><a class="headerlink" href="#Py_TPFLAGS_HEAPTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is set when the type object itself is allocated on the heap.  In this
case, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> field of its instances is considered a reference to
the type, and the type object is INCREF’ed when a new instance is created, and
DECREF’ed when an instance is destroyed (this does not apply to instances of
subtypes; only the type referenced by the instance’s ob_type gets INCREF’ed or
DECREF’ed).</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_BASETYPE">
<code class="descname">Py_TPFLAGS_BASETYPE</code><a class="headerlink" href="#Py_TPFLAGS_BASETYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is set when the type can be used as the base type of another type.  If
this bit is clear, the type cannot be subtyped (similar to a “final” class in
Java).</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_READY">
<code class="descname">Py_TPFLAGS_READY</code><a class="headerlink" href="#Py_TPFLAGS_READY" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is set when the type object has been fully initialized by
<a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_READYING">
<code class="descname">Py_TPFLAGS_READYING</code><a class="headerlink" href="#Py_TPFLAGS_READYING" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is set while <a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> is in the process of initializing
the type object.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_HAVE_GC">
<code class="descname">Py_TPFLAGS_HAVE_GC</code><a class="headerlink" href="#Py_TPFLAGS_HAVE_GC" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit is set when the object supports garbage collection.  If this bit
is set, instances must be created using <a class="reference internal" href="gcsupport.html#c.PyObject_GC_New" title="PyObject_GC_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_New()</span></code></a> and
destroyed using <a class="reference internal" href="gcsupport.html#c.PyObject_GC_Del" title="PyObject_GC_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Del()</span></code></a>.  More information in section
<a class="reference internal" href="gcsupport.html#supporting-cycle-detection"><span class="std std-ref">Supporting Cyclic Garbage Collection</span></a>.  This bit also implies that the
GC-related fields <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> are present in
the type object; but those fields also exist when
<a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> is clear but
<a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a> is set.</p>
</dd></dl>

<dl class="data">
<dt id="Py_TPFLAGS_DEFAULT">
<code class="descname">Py_TPFLAGS_DEFAULT</code><a class="headerlink" href="#Py_TPFLAGS_DEFAULT" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a bitmask of all the bits that pertain to the existence of certain
fields in the type object and its extension structures. Currently, it includes
the following bits: <a class="reference internal" href="#Py_TPFLAGS_HAVE_GETCHARBUFFER" title="Py_TPFLAGS_HAVE_GETCHARBUFFER"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GETCHARBUFFER</span></code></a>,
<a class="reference internal" href="#Py_TPFLAGS_HAVE_SEQUENCE_IN" title="Py_TPFLAGS_HAVE_SEQUENCE_IN"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_SEQUENCE_IN</span></code></a>, <a class="reference internal" href="#Py_TPFLAGS_HAVE_INPLACEOPS" title="Py_TPFLAGS_HAVE_INPLACEOPS"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_INPLACEOPS</span></code></a>,
<a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a>, <a class="reference internal" href="#Py_TPFLAGS_HAVE_WEAKREFS" title="Py_TPFLAGS_HAVE_WEAKREFS"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_WEAKREFS</span></code></a>,
<a class="reference internal" href="#Py_TPFLAGS_HAVE_ITER" title="Py_TPFLAGS_HAVE_ITER"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_ITER</span></code></a>, and <a class="reference internal" href="#Py_TPFLAGS_HAVE_CLASS" title="Py_TPFLAGS_HAVE_CLASS"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_CLASS</span></code></a>.</p>
</dd></dl>

</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_doc">
char* <code class="descname">PyTypeObject.tp_doc</code><a class="headerlink" href="#c.PyTypeObject.tp_doc" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a NUL-terminated C string giving the docstring for this
type object.  This is exposed as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attribute on the type and
instances of the type.</p>
<p>This field is <em>not</em> inherited by subtypes.</p>
</dd></dl>

<p>The following three fields only exist if the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a> flag bit is set.</p>
<dl class="member">
<dt id="c.PyTypeObject.tp_traverse">
<a class="reference internal" href="gcsupport.html#c.traverseproc" title="traverseproc">traverseproc</a> <code class="descname">PyTypeObject.tp_traverse</code><a class="headerlink" href="#c.PyTypeObject.tp_traverse" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a traversal function for the garbage collector.  This is
only used if the <a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit is set.  More information
about Python’s garbage collection scheme can be found in section
<a class="reference internal" href="gcsupport.html#supporting-cycle-detection"><span class="std std-ref">Supporting Cyclic Garbage Collection</span></a>.</p>
<p>The <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> pointer is used by the garbage collector to detect
reference cycles. A typical implementation of a <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> function
simply calls <a class="reference internal" href="gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a> on each of the instance’s members that are Python
objects.  For example, this is function <code class="xref c c-func docutils literal notranslate"><span class="pre">local_traverse()</span></code> from the
<a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> extension module:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">local_traverse</span><span class="p">(</span><span class="n">localobject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">);</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">kw</span><span class="p">);</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">dict</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a> is called only on those members that can participate
in reference cycles.  Although there is also a <code class="docutils literal notranslate"><span class="pre">self-&gt;key</span></code> member, it can only
be <em>NULL</em> or a Python string and therefore cannot be part of a reference cycle.</p>
<p>On the other hand, even if you know a member can never be part of a cycle, as a
debugging aid you may want to visit it anyway just so the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module’s
<a class="reference internal" href="../library/gc.html#gc.get_referents" title="gc.get_referents"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_referents()</span></code></a> function will include it.</p>
<p>Note that <a class="reference internal" href="gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a> requires the <em>visit</em> and <em>arg</em> parameters to
<code class="xref c c-func docutils literal notranslate"><span class="pre">local_traverse()</span></code> to have these specific names; don’t name them just
anything.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> and the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit: the flag bit, <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a>, and
<a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> are all inherited from the base type if they are all zero in
the subtype <em>and</em> the subtype has the <a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a> flag
bit set.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_clear">
<a class="reference internal" href="gcsupport.html#c.inquiry" title="inquiry">inquiry</a> <code class="descname">PyTypeObject.tp_clear</code><a class="headerlink" href="#c.PyTypeObject.tp_clear" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a clear function for the garbage collector. This is only
used if the <a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit is set.</p>
<p>The <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> member function is used to break reference cycles in cyclic
garbage detected by the garbage collector.  Taken together, all <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a>
functions in the system must combine to break all reference cycles.  This is
subtle, and if in any doubt supply a <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> function.  For example,
the tuple type does not implement a <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> function, because it’s
possible to prove that no reference cycle can be composed entirely of tuples.
Therefore the <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> functions of other types must be sufficient to
break any cycle containing a tuple.  This isn’t immediately obvious, and there’s
rarely a good reason to avoid implementing <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a>.</p>
<p>Implementations of <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> should drop the instance’s references to
those of its members that may be Python objects, and set its pointers to those
members to <em>NULL</em>, as in the following example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">local_clear</span><span class="p">(</span><span class="n">localobject</span> <span class="o">*</span><span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">key</span><span class="p">);</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">args</span><span class="p">);</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">kw</span><span class="p">);</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">dict</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="refcounting.html#c.Py_CLEAR" title="Py_CLEAR"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CLEAR()</span></code></a> macro should be used, because clearing references is
delicate:  the reference to the contained object must not be decremented until
after the pointer to the contained object is set to <em>NULL</em>.  This is because
decrementing the reference count may cause the contained object to become trash,
triggering a chain of reclamation activity that may include invoking arbitrary
Python code (due to finalizers, or weakref callbacks, associated with the
contained object). If it’s possible for such code to reference <em>self</em> again,
it’s important that the pointer to the contained object be <em>NULL</em> at that time,
so that <em>self</em> knows the contained object can no longer be used.  The
<a class="reference internal" href="refcounting.html#c.Py_CLEAR" title="Py_CLEAR"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CLEAR()</span></code></a> macro performs the operations in a safe order.</p>
<p>Because the goal of <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> functions is to break reference cycles,
it’s not necessary to clear contained objects like Python strings or Python
integers, which can’t participate in reference cycles. On the other hand, it may
be convenient to clear all contained Python objects, and write the type’s
<a class="reference internal" href="#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> function to invoke <a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a>.</p>
<p>More information about Python’s garbage collection scheme can be found in
section <a class="reference internal" href="gcsupport.html#supporting-cycle-detection"><span class="std std-ref">Supporting Cyclic Garbage Collection</span></a>.</p>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> and the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit: the flag bit, <a class="reference internal" href="#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a>, and
<a class="reference internal" href="#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> are all inherited from the base type if they are all zero in
the subtype <em>and</em> the subtype has the <a class="reference internal" href="#Py_TPFLAGS_HAVE_RICHCOMPARE" title="Py_TPFLAGS_HAVE_RICHCOMPARE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_RICHCOMPARE</span></code></a> flag
bit set.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_richcompare">
richcmpfunc <code class="descname">PyTypeObject.tp_richcompare</code><a class="headerlink" href="#c.PyTypeObject.tp_richcompare" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to the rich comparison function, whose signature is
<code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*tp_richcompare(PyObject</span> <span class="pre">*a,</span> <span class="pre">PyObject</span> <span class="pre">*b,</span> <span class="pre">int</span> <span class="pre">op)</span></code>.</p>
<p>The function should return the result of the comparison (usually <code class="docutils literal notranslate"><span class="pre">Py_True</span></code>
or <code class="docutils literal notranslate"><span class="pre">Py_False</span></code>).  If the comparison is undefined, it must return
<code class="docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code>, if another error occurred it must return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> and
set an exception condition.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you want to implement a type for which only a limited set of
comparisons makes sense (e.g. <code class="docutils literal notranslate"><span class="pre">==</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code>, but not <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> and
friends), directly raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> in the rich comparison function.</p>
</div>
<p>This field is inherited by subtypes together with <a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a> and
<a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a>: a subtype inherits all three of <a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>,
<a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a>, when the subtype’s
<a class="reference internal" href="#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a>, and <a class="reference internal" href="#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_hash</span></code></a> are all <em>NULL</em>.</p>
<p>The following constants are defined to be used as the third argument for
<a class="reference internal" href="#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_richcompare</span></code></a> and for <a class="reference internal" href="object.html#c.PyObject_RichCompare" title="PyObject_RichCompare"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_RichCompare()</span></code></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="57%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Comparison</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">&lt;</span></code></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">&lt;=</span></code></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">==</span></code></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">!=</span></code></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">&gt;</span></code></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">&gt;=</span></code></td>
</tr>
</tbody>
</table>
</dd></dl>

<p>The next field only exists if the <a class="reference internal" href="#Py_TPFLAGS_HAVE_WEAKREFS" title="Py_TPFLAGS_HAVE_WEAKREFS"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_WEAKREFS</span></code></a> flag bit is
set.</p>
<dl class="member">
<dt id="c.PyTypeObject.tp_weaklistoffset">
long <code class="descname">PyTypeObject.tp_weaklistoffset</code><a class="headerlink" href="#c.PyTypeObject.tp_weaklistoffset" title="Permalink to this definition">¶</a></dt>
<dd><p>If the instances of this type are weakly referenceable, this field is greater
than zero and contains the offset in the instance structure of the weak
reference list head (ignoring the GC header, if present); this offset is used by
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_ClearWeakRefs()</span></code> and the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyWeakref_*()</span></code> functions.  The
instance structure needs to include a field of type <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> which is
initialized to <em>NULL</em>.</p>
<p>Do not confuse this field with <a class="reference internal" href="#c.PyTypeObject.tp_weaklist" title="PyTypeObject.tp_weaklist"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklist</span></code></a>; that is the list head for
weak references to the type object itself.</p>
<p>This field is inherited by subtypes, but see the rules listed below. A subtype
may override this offset; this means that the subtype uses a different weak
reference list head than the base type.  Since the list head is always found via
<a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a>, this should not be a problem.</p>
<p>When a type defined by a class statement has no <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code> declaration,
and none of its base types are weakly referenceable, the type is made weakly
referenceable by adding a weak reference list head slot to the instance layout
and setting the <a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a> of that slot’s offset.</p>
<p>When a type’s <a class="reference internal" href="../reference/datamodel.html#__slots__" title="__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a> declaration contains a slot named
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__weakref__</span></code>, that slot becomes the weak reference list head for
instances of the type, and the slot’s offset is stored in the type’s
<a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a>.</p>
<p>When a type’s <a class="reference internal" href="../reference/datamodel.html#__slots__" title="__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a> declaration does not contain a slot named
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__weakref__</span></code>, the type inherits its <a class="reference internal" href="#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a> from its
base type.</p>
</dd></dl>

<p>The next two fields only exist if the <a class="reference internal" href="#Py_TPFLAGS_HAVE_ITER" title="Py_TPFLAGS_HAVE_ITER"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_ITER</span></code></a> flag bit is
set.</p>
<dl class="member">
<dt id="c.PyTypeObject.tp_iter">
getiterfunc <code class="descname">PyTypeObject.tp_iter</code><a class="headerlink" href="#c.PyTypeObject.tp_iter" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function that returns an iterator for the object.  Its
presence normally signals that the instances of this type are iterable (although
sequences may be iterable without this function, and classic instances always
have this function, even if they don’t define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method).</p>
<p>This function has the same signature as <a class="reference internal" href="object.html#c.PyObject_GetIter" title="PyObject_GetIter"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetIter()</span></code></a>.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_iternext">
iternextfunc <code class="descname">PyTypeObject.tp_iternext</code><a class="headerlink" href="#c.PyTypeObject.tp_iternext" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function that returns the next item in an iterator.
When the iterator is exhausted, it must return <em>NULL</em>; a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
exception may or may not be set.  When another error occurs, it must return
<em>NULL</em> too.  Its presence normally signals that the instances of this type
are iterators (although classic instances always have this function, even if
they don’t define a <a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method).</p>
<p>Iterator types should also define the <a class="reference internal" href="#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> function, and that
function should return the iterator instance itself (not a new iterator
instance).</p>
<p>This function has the same signature as <a class="reference internal" href="iter.html#c.PyIter_Next" title="PyIter_Next"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyIter_Next()</span></code></a>.</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<p>The next fields, up to and including <a class="reference internal" href="#c.PyTypeObject.tp_weaklist" title="PyTypeObject.tp_weaklist"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklist</span></code></a>, only exist if the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_CLASS" title="Py_TPFLAGS_HAVE_CLASS"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_CLASS</span></code></a> flag bit is set.</p>
<dl class="member">
<dt id="c.PyTypeObject.tp_methods">
struct <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a>* <code class="descname">PyTypeObject.tp_methods</code><a class="headerlink" href="#c.PyTypeObject.tp_methods" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a static <em>NULL</em>-terminated array of <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a>
structures, declaring regular methods of this type.</p>
<p>For each entry in the array, an entry is added to the type’s dictionary (see
<a class="reference internal" href="#c.PyTypeObject.tp_dict" title="PyTypeObject.tp_dict"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dict</span></code></a> below) containing a method descriptor.</p>
<p>This field is not inherited by subtypes (methods are inherited through a
different mechanism).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_members">
struct <a class="reference internal" href="structures.html#c.PyMemberDef" title="PyMemberDef">PyMemberDef</a>* <code class="descname">PyTypeObject.tp_members</code><a class="headerlink" href="#c.PyTypeObject.tp_members" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a static <em>NULL</em>-terminated array of <a class="reference internal" href="structures.html#c.PyMemberDef" title="PyMemberDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMemberDef</span></code></a>
structures, declaring regular data members (fields or slots) of instances of
this type.</p>
<p>For each entry in the array, an entry is added to the type’s dictionary (see
<a class="reference internal" href="#c.PyTypeObject.tp_dict" title="PyTypeObject.tp_dict"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dict</span></code></a> below) containing a member descriptor.</p>
<p>This field is not inherited by subtypes (members are inherited through a
different mechanism).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_getset">
struct <a class="reference internal" href="structures.html#c.PyGetSetDef" title="PyGetSetDef">PyGetSetDef</a>* <code class="descname">PyTypeObject.tp_getset</code><a class="headerlink" href="#c.PyTypeObject.tp_getset" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a static <em>NULL</em>-terminated array of <a class="reference internal" href="structures.html#c.PyGetSetDef" title="PyGetSetDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyGetSetDef</span></code></a>
structures, declaring computed attributes of instances of this type.</p>
<p>For each entry in the array, an entry is added to the type’s dictionary (see
<a class="reference internal" href="#c.PyTypeObject.tp_dict" title="PyTypeObject.tp_dict"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dict</span></code></a> below) containing a getset descriptor.</p>
<p>This field is not inherited by subtypes (computed attributes are inherited
through a different mechanism).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_base">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a>* <code class="descname">PyTypeObject.tp_base</code><a class="headerlink" href="#c.PyTypeObject.tp_base" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a base type from which type properties are inherited.  At
this level, only single inheritance is supported; multiple inheritance require
dynamically creating a type object by calling the metatype.</p>
<p>This field is not inherited by subtypes (obviously), but it defaults to
<code class="docutils literal notranslate"><span class="pre">&amp;PyBaseObject_Type</span></code> (which to Python programmers is known as the type
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_dict">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_dict</code><a class="headerlink" href="#c.PyTypeObject.tp_dict" title="Permalink to this definition">¶</a></dt>
<dd><p>The type’s dictionary is stored here by <a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>.</p>
<p>This field should normally be initialized to <em>NULL</em> before PyType_Ready is
called; it may also be initialized to a dictionary containing initial attributes
for the type.  Once <a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> has initialized the type, extra
attributes for the type may be added to this dictionary only if they don’t
correspond to overloaded operations (like <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>).</p>
<p>This field is not inherited by subtypes (though the attributes defined in here
are inherited through a different mechanism).</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_descr_get">
descrgetfunc <code class="descname">PyTypeObject.tp_descr_get</code><a class="headerlink" href="#c.PyTypeObject.tp_descr_get" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a “descriptor get” function.</p>
<p>The function signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span> <span class="nf">tp_descr_get</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">type</span><span class="p">);</span>
</pre></div>
</div>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_descr_set">
descrsetfunc <code class="descname">PyTypeObject.tp_descr_set</code><a class="headerlink" href="#c.PyTypeObject.tp_descr_set" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function for setting and deleting
a descriptor’s value.</p>
<p>The function signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="nf">tp_descr_set</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">value</span><span class="p">);</span>
</pre></div>
</div>
<p>The <em>value</em> argument is set to <em>NULL</em> to delete the value.
This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_dictoffset">
long <code class="descname">PyTypeObject.tp_dictoffset</code><a class="headerlink" href="#c.PyTypeObject.tp_dictoffset" title="Permalink to this definition">¶</a></dt>
<dd><p>If the instances of this type have a dictionary containing instance variables,
this field is non-zero and contains the offset in the instances of the type of
the instance variable dictionary; this offset is used by
<a class="reference internal" href="object.html#c.PyObject_GenericGetAttr" title="PyObject_GenericGetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GenericGetAttr()</span></code></a>.</p>
<p>Do not confuse this field with <a class="reference internal" href="#c.PyTypeObject.tp_dict" title="PyTypeObject.tp_dict"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dict</span></code></a>; that is the dictionary for
attributes of the type object itself.</p>
<p>If the value of this field is greater than zero, it specifies the offset from
the start of the instance structure.  If the value is less than zero, it
specifies the offset from the <em>end</em> of the instance structure.  A negative
offset is more expensive to use, and should only be used when the instance
structure contains a variable-length part.  This is used for example to add an
instance variable dictionary to subtypes of <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>. Note
that the <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> field should account for the dictionary added to
the end in that case, even though the dictionary is not included in the basic
object layout.  On a system with a pointer size of 4 bytes,
<a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a> should be set to <code class="docutils literal notranslate"><span class="pre">-4</span></code> to indicate that the dictionary is
at the very end of the structure.</p>
<p>The real dictionary offset in an instance can be computed from a negative
<a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a> as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">dictoffset</span> <span class="o">=</span> <span class="n">tp_basicsize</span> <span class="o">+</span> <span class="n">abs</span><span class="p">(</span><span class="n">ob_size</span><span class="p">)</span><span class="o">*</span><span class="n">tp_itemsize</span> <span class="o">+</span> <span class="n">tp_dictoffset</span>
<span class="k">if</span> <span class="n">dictoffset</span> <span class="n">is</span> <span class="n">not</span> <span class="n">aligned</span> <span class="n">on</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)</span><span class="o">:</span>
    <span class="n">round</span> <span class="n">up</span> <span class="n">to</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)</span>
</pre></div>
</div>
<p>where <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a>, <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> and <a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a> are
taken from the type object, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> is taken from the instance.  The
absolute value is taken because long ints use the sign of <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> to
store the sign of the number.  (There’s never a need to do this calculation
yourself; it is done for you by <code class="xref c c-func docutils literal notranslate"><span class="pre">_PyObject_GetDictPtr()</span></code>.)</p>
<p>This field is inherited by subtypes, but see the rules listed below. A subtype
may override this offset; this means that the subtype instances store the
dictionary at a difference offset than the base type.  Since the dictionary is
always found via <a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a>, this should not be a problem.</p>
<p>When a type defined by a class statement has no <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code> declaration,
and none of its base types has an instance variable dictionary, a dictionary
slot is added to the instance layout and the <a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a> is set to
that slot’s offset.</p>
<p>When a type defined by a class statement has a <a class="reference internal" href="../reference/datamodel.html#__slots__" title="__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a> declaration,
the type inherits its <a class="reference internal" href="#c.PyTypeObject.tp_dictoffset" title="PyTypeObject.tp_dictoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dictoffset</span></code></a> from its base type.</p>
<p>(Adding a slot named <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> to the <a class="reference internal" href="../reference/datamodel.html#__slots__" title="__slots__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code></a> declaration does
not have the expected effect, it just causes confusion.  Maybe this should be
added as a feature just like <code class="xref py py-attr docutils literal notranslate"><span class="pre">__weakref__</span></code> though.)</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_init">
initproc <code class="descname">PyTypeObject.tp_init</code><a class="headerlink" href="#c.PyTypeObject.tp_init" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to an instance initialization function.</p>
<p>This function corresponds to the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method of classes.  Like
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, it is possible to create an instance without calling
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, and it is possible to reinitialize an instance by calling its
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method again.</p>
<p>The function signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">tp_init</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
</pre></div>
</div>
<p>The self argument is the instance to be initialized; the <em>args</em> and <em>kwds</em>
arguments represent positional and keyword arguments of the call to
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>.</p>
<p>The <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> function, if not <em>NULL</em>, is called when an instance is
created normally by calling its type, after the type’s <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> function
has returned an instance of the type.  If the <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> function returns an
instance of some other type that is not a subtype of the original type, no
<a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> function is called; if <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> returns an instance of a
subtype of the original type, the subtype’s <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> is called.  (VERSION
NOTE: described here is what is implemented in Python 2.2.1 and later.  In
Python 2.2, the <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> of the type of the object returned by
<a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> was always called, if not <em>NULL</em>.)</p>
<p>This field is inherited by subtypes.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_alloc">
allocfunc <code class="descname">PyTypeObject.tp_alloc</code><a class="headerlink" href="#c.PyTypeObject.tp_alloc" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to an instance allocation function.</p>
<p>The function signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_alloc</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">Py_ssize_t</span> <span class="n">nitems</span><span class="p">)</span>
</pre></div>
</div>
<p>The purpose of this function is to separate memory allocation from memory
initialization.  It should return a pointer to a block of memory of adequate
length for the instance, suitably aligned, and initialized to zeros, but with
<code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_refcnt</span></code> set to <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> set to the type argument.  If
the type’s <a class="reference internal" href="#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> is non-zero, the object’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_size</span></code> field
should be initialized to <em>nitems</em> and the length of the allocated memory block
should be <code class="docutils literal notranslate"><span class="pre">tp_basicsize</span> <span class="pre">+</span> <span class="pre">nitems*tp_itemsize</span></code>, rounded up to a multiple of
<code class="docutils literal notranslate"><span class="pre">sizeof(void*)</span></code>; otherwise, <em>nitems</em> is not used and the length of the block
should be <a class="reference internal" href="#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a>.</p>
<p>Do not use this function to do any other instance initialization, not even to
allocate additional memory; that should be done by <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a>.</p>
<p>This field is inherited by static subtypes, but not by dynamic subtypes
(subtypes created by a class statement); in the latter, this field is always set
to <a class="reference internal" href="type.html#c.PyType_GenericAlloc" title="PyType_GenericAlloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericAlloc()</span></code></a>, to force a standard heap allocation strategy.
That is also the recommended value for statically defined types.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_new">
newfunc <code class="descname">PyTypeObject.tp_new</code><a class="headerlink" href="#c.PyTypeObject.tp_new" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to an instance creation function.</p>
<p>If this function is <em>NULL</em> for a particular type, that type cannot be called to
create new instances; presumably there is some other way to create instances,
like a factory function.</p>
<p>The function signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_new</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">subtype</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
</pre></div>
</div>
<p>The subtype argument is the type of the object being created; the <em>args</em> and
<em>kwds</em> arguments represent positional and keyword arguments of the call to the
type.  Note that subtype doesn’t have to equal the type whose <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a>
function is called; it may be a subtype of that type (but not an unrelated
type).</p>
<p>The <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> function should call <code class="docutils literal notranslate"><span class="pre">subtype-&gt;tp_alloc(subtype,</span> <span class="pre">nitems)</span></code>
to allocate space for the object, and then do only as much further
initialization as is absolutely necessary.  Initialization that can safely be
ignored or repeated should be placed in the <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> handler.  A good
rule of thumb is that for immutable types, all initialization should take place
in <a class="reference internal" href="#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a>, while for mutable types, most initialization should be
deferred to <a class="reference internal" href="#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a>.</p>
<p>This field is inherited by subtypes, except it is not inherited by static types
whose <a class="reference internal" href="#c.PyTypeObject.tp_base" title="PyTypeObject.tp_base"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_base</span></code></a> is <em>NULL</em> or <code class="docutils literal notranslate"><span class="pre">&amp;PyBaseObject_Type</span></code>.  The latter exception
is a precaution so that old extension types don’t become callable simply by
being linked with Python 2.2.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_free">
destructor <code class="descname">PyTypeObject.tp_free</code><a class="headerlink" href="#c.PyTypeObject.tp_free" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to an instance deallocation function.</p>
<p>The signature of this function has changed slightly: in Python 2.2 and 2.2.1,
its signature is <code class="xref c c-type docutils literal notranslate"><span class="pre">destructor</span></code>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="n">tp_free</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span>
</pre></div>
</div>
<p>In Python 2.3 and beyond, its signature is <code class="xref c c-type docutils literal notranslate"><span class="pre">freefunc</span></code>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="n">tp_free</span><span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span>
</pre></div>
</div>
<p>The only initializer that is compatible with both versions is <code class="docutils literal notranslate"><span class="pre">_PyObject_Del</span></code>,
whose definition has suitably adapted in Python 2.3.</p>
<p>This field is inherited by static subtypes, but not by dynamic subtypes
(subtypes created by a class statement); in the latter, this field is set to a
deallocator suitable to match <a class="reference internal" href="type.html#c.PyType_GenericAlloc" title="PyType_GenericAlloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericAlloc()</span></code></a> and the value of the
<a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_is_gc">
<a class="reference internal" href="gcsupport.html#c.inquiry" title="inquiry">inquiry</a> <code class="descname">PyTypeObject.tp_is_gc</code><a class="headerlink" href="#c.PyTypeObject.tp_is_gc" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional pointer to a function called by the garbage collector.</p>
<p>The garbage collector needs to know whether a particular object is collectible
or not.  Normally, it is sufficient to look at the object’s type’s
<a class="reference internal" href="#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_flags</span></code></a> field, and check the <a class="reference internal" href="#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag bit.  But
some types have a mixture of statically and dynamically allocated instances, and
the statically allocated instances are not collectible.  Such types should
define this function; it should return <code class="docutils literal notranslate"><span class="pre">1</span></code> for a collectible instance, and
<code class="docutils literal notranslate"><span class="pre">0</span></code> for a non-collectible instance. The signature is</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">tp_is_gc</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">)</span>
</pre></div>
</div>
<p>(The only example of this are types themselves.  The metatype,
<a class="reference internal" href="type.html#c.PyType_Type" title="PyType_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyType_Type</span></code></a>, defines this function to distinguish between statically
and dynamically allocated types.)</p>
<p>This field is inherited by subtypes.  (VERSION NOTE: in Python 2.2, it was not
inherited.  It is inherited in 2.2.1 and later versions.)</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_bases">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_bases</code><a class="headerlink" href="#c.PyTypeObject.tp_bases" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple of base types.</p>
<p>This is set for types created by a class statement.  It should be <em>NULL</em> for
statically defined types.</p>
<p>This field is not inherited.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_mro">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_mro</code><a class="headerlink" href="#c.PyTypeObject.tp_mro" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple containing the expanded set of base types, starting with the type itself
and ending with <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, in Method Resolution Order.</p>
<p>This field is not inherited; it is calculated fresh by <a class="reference internal" href="type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_cache">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_cache</code><a class="headerlink" href="#c.PyTypeObject.tp_cache" title="Permalink to this definition">¶</a></dt>
<dd><p>Unused.  Not inherited.  Internal use only.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_subclasses">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_subclasses</code><a class="headerlink" href="#c.PyTypeObject.tp_subclasses" title="Permalink to this definition">¶</a></dt>
<dd><p>List of weak references to subclasses.  Not inherited.  Internal use only.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_weaklist">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTypeObject.tp_weaklist</code><a class="headerlink" href="#c.PyTypeObject.tp_weaklist" title="Permalink to this definition">¶</a></dt>
<dd><p>Weak reference list head, for weak references to this type object.  Not
inherited.  Internal use only.</p>
</dd></dl>

<p>The remaining fields are only defined if the feature test macro
<code class="xref py py-const docutils literal notranslate"><span class="pre">COUNT_ALLOCS</span></code> is defined, and are for internal use only. They are
documented here for completeness.  None of these fields are inherited by
subtypes. See the <span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSHOWALLOCCOUNT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSHOWALLOCCOUNT</span></code></a> environment variable.</p>
<dl class="member">
<dt id="c.PyTypeObject.tp_allocs">
Py_ssize_t <code class="descname">PyTypeObject.tp_allocs</code><a class="headerlink" href="#c.PyTypeObject.tp_allocs" title="Permalink to this definition">¶</a></dt>
<dd><p>Number of allocations.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_frees">
Py_ssize_t <code class="descname">PyTypeObject.tp_frees</code><a class="headerlink" href="#c.PyTypeObject.tp_frees" title="Permalink to this definition">¶</a></dt>
<dd><p>Number of frees.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_maxalloc">
Py_ssize_t <code class="descname">PyTypeObject.tp_maxalloc</code><a class="headerlink" href="#c.PyTypeObject.tp_maxalloc" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum simultaneously allocated objects.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyTypeObject.tp_next">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a>* <code class="descname">PyTypeObject.tp_next</code><a class="headerlink" href="#c.PyTypeObject.tp_next" title="Permalink to this definition">¶</a></dt>
<dd><p>Pointer to the next type object with a non-zero <a class="reference internal" href="#c.PyTypeObject.tp_allocs" title="PyTypeObject.tp_allocs"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_allocs</span></code></a> field.</p>
</dd></dl>

<p>Also, note that, in a garbage collected Python, tp_dealloc may be called from
any Python thread, not just the thread which created the object (if the object
becomes part of a refcount cycle, that cycle might be collected by a garbage
collection on any thread).  This is not a problem for Python API calls, since
the thread on which tp_dealloc is called will own the Global Interpreter Lock
(GIL). However, if the object being destroyed in turn destroys objects from some
other C or C++ library, care should be taken to ensure that destroying those
objects on the thread which called tp_dealloc will not violate any assumptions
of the library.</p>
</div>
<div class="section" id="number-object-structures">
<span id="number-structs"></span><h1>Number Object Structures<a class="headerlink" href="#number-object-structures" title="Permalink to this headline">¶</a></h1>
<dl class="type">
<dt id="c.PyNumberMethods">
<code class="descname">PyNumberMethods</code><a class="headerlink" href="#c.PyNumberMethods" title="Permalink to this definition">¶</a></dt>
<dd><p>This structure holds pointers to the functions which an object uses to
implement the number protocol.  Almost every function below is used by the
function of similar name documented in the <a class="reference internal" href="number.html#number"><span class="std std-ref">Number Protocol</span></a> section.</p>
<p>Here is the structure definition:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
     <span class="n">binaryfunc</span> <span class="n">nb_add</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_subtract</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_multiply</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_divide</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_remainder</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_divmod</span><span class="p">;</span>
     <span class="n">ternaryfunc</span> <span class="n">nb_power</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_negative</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_positive</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_absolute</span><span class="p">;</span>
     <span class="n">inquiry</span> <span class="n">nb_nonzero</span><span class="p">;</span>       <span class="cm">/* Used by PyObject_IsTrue */</span>
     <span class="n">unaryfunc</span> <span class="n">nb_invert</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_lshift</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_rshift</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_and</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_xor</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_or</span><span class="p">;</span>
     <span class="n">coercion</span> <span class="n">nb_coerce</span><span class="p">;</span>       <span class="cm">/* Used by the coerce() function */</span>
     <span class="n">unaryfunc</span> <span class="n">nb_int</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_long</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_float</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_oct</span><span class="p">;</span>
     <span class="n">unaryfunc</span> <span class="n">nb_hex</span><span class="p">;</span>

     <span class="cm">/* Added in release 2.0 */</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_add</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_subtract</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_multiply</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_divide</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_remainder</span><span class="p">;</span>
     <span class="n">ternaryfunc</span> <span class="n">nb_inplace_power</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_lshift</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_rshift</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_and</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_xor</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_or</span><span class="p">;</span>

     <span class="cm">/* Added in release 2.2 */</span>
     <span class="n">binaryfunc</span> <span class="n">nb_floor_divide</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_true_divide</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_floor_divide</span><span class="p">;</span>
     <span class="n">binaryfunc</span> <span class="n">nb_inplace_true_divide</span><span class="p">;</span>

     <span class="cm">/* Added in release 2.5 */</span>
     <span class="n">unaryfunc</span> <span class="n">nb_index</span><span class="p">;</span>
<span class="p">}</span> <span class="n">PyNumberMethods</span><span class="p">;</span>
</pre></div>
</div>
</dd></dl>

<p>Binary and ternary functions may receive different kinds of arguments, depending
on the flag bit <a class="reference internal" href="#Py_TPFLAGS_CHECKTYPES" title="Py_TPFLAGS_CHECKTYPES"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_CHECKTYPES</span></code></a>:</p>
<ul>
<li><p class="first">If <a class="reference internal" href="#Py_TPFLAGS_CHECKTYPES" title="Py_TPFLAGS_CHECKTYPES"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_CHECKTYPES</span></code></a> is not set, the function arguments are
guaranteed to be of the object’s type; the caller is responsible for calling
the coercion method specified by the <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_coerce</span></code> member to convert the
arguments:</p>
<dl class="member">
<dt id="c.PyNumberMethods.nb_coerce">
coercion <code class="descname">PyNumberMethods.nb_coerce</code><a class="headerlink" href="#c.PyNumberMethods.nb_coerce" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="number.html#c.PyNumber_CoerceEx" title="PyNumber_CoerceEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyNumber_CoerceEx()</span></code></a> and has the same
signature.  The first argument is always a pointer to an object of the
defined type.  If the conversion to a common “larger” type is possible, the
function replaces the pointers with new references to the converted objects
and returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.  If the conversion is not possible, the function returns
<code class="docutils literal notranslate"><span class="pre">1</span></code>.  If an error condition is set, it will return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
</dd></dl>

</li>
<li><p class="first">If the <a class="reference internal" href="#Py_TPFLAGS_CHECKTYPES" title="Py_TPFLAGS_CHECKTYPES"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_CHECKTYPES</span></code></a> flag is set, binary and ternary
functions must check the type of all their operands, and implement the
necessary conversions (at least one of the operands is an instance of the
defined type).  This is the recommended way; with Python 3 coercion will
disappear completely.</p>
</li>
</ul>
<p>If the operation is not defined for the given operands, binary and ternary
functions must return <code class="docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code>, if another error occurred they must
return <code class="docutils literal notranslate"><span class="pre">NULL</span></code> and set an exception.</p>
</div>
<div class="section" id="mapping-object-structures">
<span id="mapping-structs"></span><h1>Mapping Object Structures<a class="headerlink" href="#mapping-object-structures" title="Permalink to this headline">¶</a></h1>
<dl class="type">
<dt id="c.PyMappingMethods">
<code class="descname">PyMappingMethods</code><a class="headerlink" href="#c.PyMappingMethods" title="Permalink to this definition">¶</a></dt>
<dd><p>This structure holds pointers to the functions which an object uses to
implement the mapping protocol.  It has three members:</p>
</dd></dl>

<dl class="member">
<dt id="c.PyMappingMethods.mp_length">
lenfunc <code class="descname">PyMappingMethods.mp_length</code><a class="headerlink" href="#c.PyMappingMethods.mp_length" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="mapping.html#c.PyMapping_Length" title="PyMapping_Length"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMapping_Length()</span></code></a> and
<a class="reference internal" href="object.html#c.PyObject_Size" title="PyObject_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Size()</span></code></a>, and has the same signature.  This slot may be set to
<em>NULL</em> if the object has no defined length.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyMappingMethods.mp_subscript">
binaryfunc <code class="descname">PyMappingMethods.mp_subscript</code><a class="headerlink" href="#c.PyMappingMethods.mp_subscript" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="object.html#c.PyObject_GetItem" title="PyObject_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetItem()</span></code></a> and has the same
signature.  This slot must be filled for the <a class="reference internal" href="mapping.html#c.PyMapping_Check" title="PyMapping_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMapping_Check()</span></code></a>
function to return <code class="docutils literal notranslate"><span class="pre">1</span></code>, it can be <em>NULL</em> otherwise.</p>
</dd></dl>

<dl class="member">
<dt id="c.PyMappingMethods.mp_ass_subscript">
objobjargproc <code class="descname">PyMappingMethods.mp_ass_subscript</code><a class="headerlink" href="#c.PyMappingMethods.mp_ass_subscript" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a> and
<a class="reference internal" href="object.html#c.PyObject_DelItem" title="PyObject_DelItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_DelItem()</span></code></a>.  It has the same signature as
<a class="reference internal" href="object.html#c.PyObject_SetItem" title="PyObject_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetItem()</span></code></a>, but <em>v</em> can also be set to <em>NULL</em> to delete
an item.  If this slot is <em>NULL</em>, the object does not support item
assignment and deletion.</p>
</dd></dl>

</div>
<div class="section" id="sequence-object-structures">
<span id="sequence-structs"></span><h1>Sequence Object Structures<a class="headerlink" href="#sequence-object-structures" title="Permalink to this headline">¶</a></h1>
<dl class="type">
<dt id="c.PySequenceMethods">
<code class="descname">PySequenceMethods</code><a class="headerlink" href="#c.PySequenceMethods" title="Permalink to this definition">¶</a></dt>
<dd><p>This structure holds pointers to the functions which an object uses to
implement the sequence protocol.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_length">
lenfunc <code class="descname">PySequenceMethods.sq_length</code><a class="headerlink" href="#c.PySequenceMethods.sq_length" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_Size" title="PySequence_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Size()</span></code></a> and <a class="reference internal" href="object.html#c.PyObject_Size" title="PyObject_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Size()</span></code></a>,
and has the same signature.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_concat">
binaryfunc <code class="descname">PySequenceMethods.sq_concat</code><a class="headerlink" href="#c.PySequenceMethods.sq_concat" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_Concat" title="PySequence_Concat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Concat()</span></code></a> and has the same
signature.  It is also used by the <code class="docutils literal notranslate"><span class="pre">+</span></code> operator, after trying the numeric
addition via the <code class="xref c c-member docutils literal notranslate"><span class="pre">nb_add</span></code> slot.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_repeat">
ssizeargfunc <code class="descname">PySequenceMethods.sq_repeat</code><a class="headerlink" href="#c.PySequenceMethods.sq_repeat" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_Repeat" title="PySequence_Repeat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Repeat()</span></code></a> and has the same
signature.  It is also used by the <code class="docutils literal notranslate"><span class="pre">*</span></code> operator, after trying numeric
multiplication via the <code class="xref c c-member docutils literal notranslate"><span class="pre">nb_multiply</span></code>
slot.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_item">
ssizeargfunc <code class="descname">PySequenceMethods.sq_item</code><a class="headerlink" href="#c.PySequenceMethods.sq_item" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a> and has the same
signature.  This slot must be filled for the <a class="reference internal" href="sequence.html#c.PySequence_Check" title="PySequence_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Check()</span></code></a>
function to return <code class="docutils literal notranslate"><span class="pre">1</span></code>, it can be <em>NULL</em> otherwise.</p>
<p>Negative indexes are handled as follows: if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_length</span></code> slot is
filled, it is called and the sequence length is used to compute a positive
index which is passed to <code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_item</span></code>.  If <code class="xref py py-attr docutils literal notranslate"><span class="pre">sq_length</span></code> is <em>NULL</em>,
the index is passed as is to the function.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_ass_item">
ssizeobjargproc <code class="descname">PySequenceMethods.sq_ass_item</code><a class="headerlink" href="#c.PySequenceMethods.sq_ass_item" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_SetItem" title="PySequence_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_SetItem()</span></code></a> and has the same
signature.  This slot may be left to <em>NULL</em> if the object does not support
item assignment and deletion.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_contains">
objobjproc <code class="descname">PySequenceMethods.sq_contains</code><a class="headerlink" href="#c.PySequenceMethods.sq_contains" title="Permalink to this definition">¶</a></dt>
<dd><p>This function may be used by <a class="reference internal" href="sequence.html#c.PySequence_Contains" title="PySequence_Contains"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Contains()</span></code></a> and has the same
signature.  This slot may be left to <em>NULL</em>, in this case
<a class="reference internal" href="sequence.html#c.PySequence_Contains" title="PySequence_Contains"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Contains()</span></code></a> simply traverses the sequence until it finds a
match.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_inplace_concat">
binaryfunc <code class="descname">PySequenceMethods.sq_inplace_concat</code><a class="headerlink" href="#c.PySequenceMethods.sq_inplace_concat" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_InPlaceConcat" title="PySequence_InPlaceConcat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_InPlaceConcat()</span></code></a> and has the same
signature.  It should modify its first operand, and return it.</p>
</dd></dl>

<dl class="member">
<dt id="c.PySequenceMethods.sq_inplace_repeat">
ssizeargfunc <code class="descname">PySequenceMethods.sq_inplace_repeat</code><a class="headerlink" href="#c.PySequenceMethods.sq_inplace_repeat" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="sequence.html#c.PySequence_InPlaceRepeat" title="PySequence_InPlaceRepeat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_InPlaceRepeat()</span></code></a> and has the same
signature.  It should modify its first operand, and return it.</p>
</dd></dl>

</div>
<div class="section" id="buffer-object-structures">
<span id="buffer-structs"></span><h1>Buffer Object Structures<a class="headerlink" href="#buffer-object-structures" title="Permalink to this headline">¶</a></h1>
<p>The buffer interface exports a model where an object can expose its internal
data as a set of chunks of data, where each chunk is specified as a
pointer/length pair.  These chunks are called <em class="dfn">segments</em> and are presumed
to be non-contiguous in memory.</p>
<p>If an object does not export the buffer interface, then its <a class="reference internal" href="#c.PyTypeObject.tp_as_buffer" title="PyTypeObject.tp_as_buffer"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_buffer</span></code></a>
member in the <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> structure should be <em>NULL</em>.  Otherwise, the
<a class="reference internal" href="#c.PyTypeObject.tp_as_buffer" title="PyTypeObject.tp_as_buffer"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_as_buffer</span></code></a> will point to a <a class="reference internal" href="#c.PyBufferProcs" title="PyBufferProcs"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBufferProcs</span></code></a> structure.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is very important that your <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> structure uses
<a class="reference internal" href="#Py_TPFLAGS_DEFAULT" title="Py_TPFLAGS_DEFAULT"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_DEFAULT</span></code></a> for the value of the <a class="reference internal" href="#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_flags</span></code></a> member rather
than <code class="docutils literal notranslate"><span class="pre">0</span></code>.  This tells the Python runtime that your <a class="reference internal" href="#c.PyBufferProcs" title="PyBufferProcs"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBufferProcs</span></code></a>
structure contains the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code> slot. Older versions of Python
did not have this member, so a new Python interpreter using an old extension
needs to be able to test for its presence before using it.</p>
</div>
<dl class="type">
<dt id="c.PyBufferProcs">
<code class="descname">PyBufferProcs</code><a class="headerlink" href="#c.PyBufferProcs" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure used to hold the function pointers which define an implementation of
the buffer protocol.</p>
<p>The first slot is <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getreadbuffer</span></code>, of type <a class="reference internal" href="#c.readbufferproc" title="readbufferproc"><code class="xref c c-type docutils literal notranslate"><span class="pre">readbufferproc</span></code></a>.
If this slot is <em>NULL</em>, then the object does not support reading from the
internal data.  This is non-sensical, so implementors should fill this in, but
callers should test that the slot contains a non-<em>NULL</em> value.</p>
<p>The next slot is <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getwritebuffer</span></code> having type
<a class="reference internal" href="#c.writebufferproc" title="writebufferproc"><code class="xref c c-type docutils literal notranslate"><span class="pre">writebufferproc</span></code></a>.  This slot may be <em>NULL</em> if the object does not
allow writing into its returned buffers.</p>
<p>The third slot is <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getsegcount</span></code>, with type <a class="reference internal" href="#c.segcountproc" title="segcountproc"><code class="xref c c-type docutils literal notranslate"><span class="pre">segcountproc</span></code></a>.
This slot must not be <em>NULL</em> and is used to inform the caller how many segments
the object contains.  Simple objects such as <a class="reference internal" href="string.html#c.PyString_Type" title="PyString_Type"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyString_Type</span></code></a> and
<a class="reference internal" href="buffer.html#c.PyBuffer_Type" title="PyBuffer_Type"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBuffer_Type</span></code></a> objects contain a single segment.</p>
<p id="index-4">The last slot is <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code>, of type <a class="reference internal" href="#c.charbufferproc" title="charbufferproc"><code class="xref c c-type docutils literal notranslate"><span class="pre">charbufferproc</span></code></a>.
This slot will only be present if the <a class="reference internal" href="#Py_TPFLAGS_HAVE_GETCHARBUFFER" title="Py_TPFLAGS_HAVE_GETCHARBUFFER"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GETCHARBUFFER</span></code></a>
flag is present in the <a class="reference internal" href="#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_flags</span></code></a> field of the object’s
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a>. Before using this slot, the caller should test whether it
is present by using the <a class="reference internal" href="type.html#c.PyType_HasFeature" title="PyType_HasFeature"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_HasFeature()</span></code></a> function.  If the flag is
present, <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code> may be <em>NULL</em>, indicating that the object’s
contents cannot be used as <em>8-bit characters</em>. The slot function may also raise
an error if the object’s contents cannot be interpreted as 8-bit characters.
For example, if the object is an array which is configured to hold floating
point values, an exception may be raised if a caller attempts to use
<code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code> to fetch a sequence of 8-bit characters. This notion of
exporting the internal buffers as “text” is used to distinguish between objects
that are binary in nature, and those which have character-based content.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The current policy seems to state that these characters may be multi-byte
characters. This implies that a buffer size of <em>N</em> does not mean there are <em>N</em>
characters present.</p>
</div>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">Py_TPFLAGS_HAVE_GETCHARBUFFER</code></dt>
<dd><p>Flag bit set in the type structure to indicate that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code>
slot is known.  This being set does not indicate that the object supports the
buffer interface or that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getcharbuffer</span></code> slot is non-<em>NULL</em>.</p>
</dd></dl>

<dl class="type">
<dt id="c.readbufferproc">
Py_ssize_t <code class="descname">(*readbufferproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, Py_ssize_t<em>&nbsp;segment</em>, void<em>&nbsp;**ptrptr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.readbufferproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pointer to a readable segment of the buffer in <code class="docutils literal notranslate"><span class="pre">*ptrptr</span></code>.  This
function is allowed to raise an exception, in which case it must return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.
The <em>segment</em> which is specified must be zero or positive, and strictly less
than the number of segments returned by the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bf_getsegcount</span></code> slot
function.  On success, it returns the length of the segment, and sets
<code class="docutils literal notranslate"><span class="pre">*ptrptr</span></code> to a pointer to that memory.</p>
</dd></dl>

<dl class="type">
<dt id="c.writebufferproc">
Py_ssize_t <code class="descname">(*writebufferproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, Py_ssize_t<em>&nbsp;segment</em>, void<em>&nbsp;**ptrptr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.writebufferproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pointer to a writable memory buffer in <code class="docutils literal notranslate"><span class="pre">*ptrptr</span></code>, and the length of
that segment as the function return value.  The memory buffer must correspond to
buffer segment <em>segment</em>.  Must return <code class="docutils literal notranslate"><span class="pre">-1</span></code> and set an exception on error.
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> should be raised if the object only supports read-only buffers,
and <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> should be raised when <em>segment</em> specifies a segment that
doesn’t exist.</p>
</dd></dl>

<dl class="type">
<dt id="c.segcountproc">
Py_ssize_t <code class="descname">(*segcountproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, Py_ssize_t<em>&nbsp;*lenp</em><span class="sig-paren">)</span><a class="headerlink" href="#c.segcountproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of memory segments which comprise the buffer.  If <em>lenp</em> is
not <em>NULL</em>, the implementation must report the sum of the sizes (in bytes) of
all segments in <code class="docutils literal notranslate"><span class="pre">*lenp</span></code>. The function cannot fail.</p>
</dd></dl>

<dl class="type">
<dt id="c.charbufferproc">
Py_ssize_t <code class="descname">(*charbufferproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, Py_ssize_t<em>&nbsp;segment</em>, char<em>&nbsp;**ptrptr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.charbufferproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of the segment <em>segment</em> that <em>ptrptr</em>  is set to.  <code class="docutils literal notranslate"><span class="pre">*ptrptr</span></code>
is set to the memory buffer. Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Type Objects</a></li>
<li><a class="reference internal" href="#number-object-structures">Number Object Structures</a></li>
<li><a class="reference internal" href="#mapping-object-structures">Mapping Object Structures</a></li>
<li><a class="reference internal" href="#sequence-object-structures">Sequence Object Structures</a></li>
<li><a class="reference internal" href="#buffer-object-structures">Buffer Object Structures</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="structures.html"
                        title="previous chapter">Common Object Structures</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gcsupport.html"
                        title="next chapter">Supporting Cyclic Garbage Collection</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/typeobj.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gcsupport.html" title="Supporting Cyclic Garbage Collection"
             >next</a> |</li>
        <li class="right" >
          <a href="structures.html" title="Common Object Structures"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" >Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\)�i�i�i�html/c-api/unicode.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Unicode Objects and Codecs &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Buffers and Memoryview Objects" href="buffer.html" />
    <link rel="prev" title="String/Bytes Objects" href="string.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/unicode.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="buffer.html" title="Buffers and Memoryview Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="string.html" title="String/Bytes Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="unicode-objects-and-codecs">
<span id="unicodeobjects"></span><h1>Unicode Objects and Codecs<a class="headerlink" href="#unicode-objects-and-codecs" title="Permalink to this headline">¶</a></h1>
<div class="section" id="unicode-objects">
<h2>Unicode Objects<a class="headerlink" href="#unicode-objects" title="Permalink to this headline">¶</a></h2>
<div class="section" id="unicode-type">
<h3>Unicode Type<a class="headerlink" href="#unicode-type" title="Permalink to this headline">¶</a></h3>
<p>These are the basic Unicode object types used for the Unicode implementation in
Python:</p>
<dl class="type">
<dt id="c.Py_UNICODE">
<code class="descname">Py_UNICODE</code><a class="headerlink" href="#c.Py_UNICODE" title="Permalink to this definition">¶</a></dt>
<dd><p>This type represents the storage type which is used by Python internally as
basis for holding Unicode ordinals.  Python’s default builds use a 16-bit type
for <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> and store Unicode values internally as UCS2. It is also
possible to build a UCS4 version of Python (most recent Linux distributions come
with UCS4 builds of Python). These builds then use a 32-bit type for
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> and store Unicode data internally as UCS4. On platforms
where <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> is available and compatible with the chosen Python
Unicode build variant, <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> is a typedef alias for
<code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> to enhance native platform compatibility. On all other
platforms, <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> is a typedef alias for either <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span>
<span class="pre">short</span></code> (UCS2) or <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code> (UCS4).</p>
</dd></dl>

<p>Note that UCS2 and UCS4 Python builds are not binary compatible. Please keep
this in mind when writing extensions or interfaces.</p>
<dl class="type">
<dt id="c.PyUnicodeObject">
<code class="descname">PyUnicodeObject</code><a class="headerlink" href="#c.PyUnicodeObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python Unicode object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyUnicode_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyUnicode_Type</code><a class="headerlink" href="#c.PyUnicode_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python Unicode type.  It
is exposed to Python code as <code class="docutils literal notranslate"><span class="pre">unicode</span></code> and <code class="docutils literal notranslate"><span class="pre">types.UnicodeType</span></code>.</p>
</dd></dl>

<p>The following APIs are really C macros and can be used to do fast checks and to
access internal read-only data of Unicode objects:</p>
<dl class="function">
<dt id="c.PyUnicode_Check">
int <code class="descname">PyUnicode_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a Unicode object or an instance of a Unicode
subtype.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_CheckExact">
int <code class="descname">PyUnicode_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a Unicode object, but not an instance of a
subtype.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_GET_SIZE">
Py_ssize_t <code class="descname">PyUnicode_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of the object.  <em>o</em> has to be a <a class="reference internal" href="#c.PyUnicodeObject" title="PyUnicodeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicodeObject</span></code></a> (not
checked).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_GET_DATA_SIZE">
Py_ssize_t <code class="descname">PyUnicode_GET_DATA_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_GET_DATA_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of the object’s internal buffer in bytes.  <em>o</em> has to be a
<a class="reference internal" href="#c.PyUnicodeObject" title="PyUnicodeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicodeObject</span></code></a> (not checked).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AS_UNICODE">
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a>* <code class="descname">PyUnicode_AS_UNICODE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AS_UNICODE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pointer to the internal <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the object.  <em>o</em>
has to be a <a class="reference internal" href="#c.PyUnicodeObject" title="PyUnicodeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicodeObject</span></code></a> (not checked).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AS_DATA">
const char* <code class="descname">PyUnicode_AS_DATA</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AS_DATA" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pointer to the internal buffer of the object. <em>o</em> has to be a
<a class="reference internal" href="#c.PyUnicodeObject" title="PyUnicodeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicodeObject</span></code></a> (not checked).</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_ClearFreeList">
int <code class="descname">PyUnicode_ClearFreeList</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_ClearFreeList" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the free list. Return the total number of freed items.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="unicode-character-properties">
<h3>Unicode Character Properties<a class="headerlink" href="#unicode-character-properties" title="Permalink to this headline">¶</a></h3>
<p>Unicode provides many different character properties. The most often needed ones
are available through these macros which are mapped to C functions depending on
the Python configuration.</p>
<dl class="function">
<dt id="c.Py_UNICODE_ISSPACE">
int <code class="descname">Py_UNICODE_ISSPACE</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISSPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a whitespace character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISLOWER">
int <code class="descname">Py_UNICODE_ISLOWER</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISLOWER" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a lowercase character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISUPPER">
int <code class="descname">Py_UNICODE_ISUPPER</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISUPPER" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is an uppercase character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISTITLE">
int <code class="descname">Py_UNICODE_ISTITLE</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISTITLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a titlecase character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISLINEBREAK">
int <code class="descname">Py_UNICODE_ISLINEBREAK</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISLINEBREAK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a linebreak character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISDECIMAL">
int <code class="descname">Py_UNICODE_ISDECIMAL</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISDECIMAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a decimal character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISDIGIT">
int <code class="descname">Py_UNICODE_ISDIGIT</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISDIGIT" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a digit character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISNUMERIC">
int <code class="descname">Py_UNICODE_ISNUMERIC</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISNUMERIC" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is a numeric character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISALPHA">
int <code class="descname">Py_UNICODE_ISALPHA</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISALPHA" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is an alphabetic character.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_ISALNUM">
int <code class="descname">Py_UNICODE_ISALNUM</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_ISALNUM" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether <em>ch</em> is an alphanumeric character.</p>
</dd></dl>

<p>These APIs can be used for fast direct character conversions:</p>
<dl class="function">
<dt id="c.Py_UNICODE_TOLOWER">
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a> <code class="descname">Py_UNICODE_TOLOWER</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TOLOWER" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to lower case.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_TOUPPER">
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a> <code class="descname">Py_UNICODE_TOUPPER</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TOUPPER" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to upper case.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_TOTITLE">
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a> <code class="descname">Py_UNICODE_TOTITLE</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TOTITLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to title case.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_TODECIMAL">
int <code class="descname">Py_UNICODE_TODECIMAL</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TODECIMAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to a decimal positive integer.  Return
<code class="docutils literal notranslate"><span class="pre">-1</span></code> if this is not possible.  This macro does not raise exceptions.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_TODIGIT">
int <code class="descname">Py_UNICODE_TODIGIT</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TODIGIT" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to a single digit integer. Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if
this is not possible.  This macro does not raise exceptions.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_UNICODE_TONUMERIC">
double <code class="descname">Py_UNICODE_TONUMERIC</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;ch</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_UNICODE_TONUMERIC" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character <em>ch</em> converted to a double. Return <code class="docutils literal notranslate"><span class="pre">-1.0</span></code> if this is not
possible.  This macro does not raise exceptions.</p>
</dd></dl>

</div>
<div class="section" id="plain-py-unicode">
<h3>Plain Py_UNICODE<a class="headerlink" href="#plain-py-unicode" title="Permalink to this headline">¶</a></h3>
<p>To create Unicode objects and access their basic sequence properties, use these
APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_FromUnicode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromUnicode</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*u</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromUnicode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object from the Py_UNICODE buffer <em>u</em> of the given size. <em>u</em>
may be <em>NULL</em> which causes the contents to be undefined. It is the user’s
responsibility to fill in the needed data.  The buffer is copied into the new
object. If the buffer is not <em>NULL</em>, the return value might be a shared object.
Therefore, modification of the resulting Unicode object is only allowed when <em>u</em>
is <em>NULL</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromStringAndSize">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromStringAndSize</code><span class="sig-paren">(</span>const char<em>&nbsp;*u</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromStringAndSize" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object from the char buffer <em>u</em>.  The bytes will be interpreted
as being UTF-8 encoded.  <em>u</em> may also be <em>NULL</em> which
causes the contents to be undefined. It is the user’s responsibility to fill in
the needed data.  The buffer is copied into the new object. If the buffer is not
<em>NULL</em>, the return value might be a shared object. Therefore, modification of
the resulting Unicode object is only allowed when <em>u</em> is <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">PyUnicode_FromString</code><span class="sig-paren">(</span>const char<em>&nbsp;*u</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object from a UTF-8 encoded null-terminated char buffer
<em>u</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromFormat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromFormat</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromFormat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Take a C <code class="xref c c-func docutils literal notranslate"><span class="pre">printf()</span></code>-style <em>format</em> string and a variable number of
arguments, calculate the size of the resulting Python unicode string and return
a string with the values formatted into it.  The variable arguments must be C
types and must correspond exactly to the format characters in the <em>format</em>
string.  The following format characters are allowed:</p>
<table border="1" class="docutils">
<colgroup>
<col width="26%" />
<col width="29%" />
<col width="44%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format Characters</th>
<th class="head">Type</th>
<th class="head">Comment</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%%</span></code></td>
<td><em>n/a</em></td>
<td>The literal % character.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%c</span></code></td>
<td>int</td>
<td>A single character,
represented as a C int.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%d</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%d&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%u</span></code></td>
<td>unsigned int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%u&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%ld</span></code></td>
<td>long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%ld&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%lu</span></code></td>
<td>unsigned long</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%lu&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%zd</span></code></td>
<td>Py_ssize_t</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%zd&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%zu</span></code></td>
<td>size_t</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%zu&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%i</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%i&quot;)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%x</span></code></td>
<td>int</td>
<td>Exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%x&quot;)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%s</span></code></td>
<td>char*</td>
<td>A null-terminated C character
array.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%p</span></code></td>
<td>void*</td>
<td>The hex representation of a C
pointer. Mostly equivalent to
<code class="docutils literal notranslate"><span class="pre">printf(&quot;%p&quot;)</span></code> except that
it is guaranteed to start with
the literal <code class="docutils literal notranslate"><span class="pre">0x</span></code> regardless
of what the platform’s
<code class="docutils literal notranslate"><span class="pre">printf</span></code> yields.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%U</span></code></td>
<td>PyObject*</td>
<td>A unicode object.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%V</span></code></td>
<td>PyObject*, char *</td>
<td>A unicode object (which may be
<em>NULL</em>) and a null-terminated
C character array as a second
parameter (which will be used,
if the first parameter is
<em>NULL</em>).</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%S</span></code></td>
<td>PyObject*</td>
<td>The result of calling
<code class="xref py py-func docutils literal notranslate"><span class="pre">PyObject_Unicode()</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">%R</span></code></td>
<td>PyObject*</td>
<td>The result of calling
<code class="xref py py-func docutils literal notranslate"><span class="pre">PyObject_Repr()</span></code>.</td>
</tr>
</tbody>
</table>
<p>An unrecognized format character causes all the rest of the format string to be
copied as-is to the result string, and any extra arguments discarded.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromFormatV">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromFormatV</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, va_list<em>&nbsp;vargs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromFormatV" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Identical to <code class="xref py py-func docutils literal notranslate"><span class="pre">PyUnicode_FromFormat()</span></code> except that it takes exactly two
arguments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsUnicode">
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a>* <code class="descname">PyUnicode_AsUnicode</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsUnicode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a read-only pointer to the Unicode object’s internal
<a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer, <em>NULL</em> if <em>unicode</em> is not a Unicode object.
Note that the resulting <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE*</span></code></a> string may contain embedded
null characters, which would cause the string to be truncated when used in
most C functions.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_GetSize">
Py_ssize_t <code class="descname">PyUnicode_GetSize</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_GetSize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the length of the Unicode object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type. This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromEncodedObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromEncodedObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromEncodedObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Coerce an encoded object <em>obj</em> to a Unicode object and return a reference with
incremented refcount.</p>
<p>String and other char buffer compatible objects are decoded according to the
given encoding and using the error handling defined by errors.  Both can be
<em>NULL</em> to have the interface use the default values (see the next section for
details).</p>
<p>All other objects, including Unicode objects, cause a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to be
set.</p>
<p>The API returns <em>NULL</em> if there was an error.  The caller is responsible for
decref’ing the returned objects.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_FromObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Shortcut for <code class="docutils literal notranslate"><span class="pre">PyUnicode_FromEncodedObject(obj,</span> <span class="pre">NULL,</span> <span class="pre">&quot;strict&quot;)</span></code> which is used
throughout the interpreter whenever coercion to Unicode is needed.</p>
</dd></dl>

<p>If the platform supports <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> and provides a header file wchar.h,
Python can interface directly to this type using the following functions.
Support is optimized if Python’s own <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> type is identical to
the system’s <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code>.</p>
</div>
<div class="section" id="wchar-t-support">
<h3>wchar_t Support<a class="headerlink" href="#wchar-t-support" title="Permalink to this headline">¶</a></h3>
<p><code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> support for platforms which support it:</p>
<dl class="function">
<dt id="c.PyUnicode_FromWideChar">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_FromWideChar</code><span class="sig-paren">(</span>const wchar_t<em>&nbsp;*w</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_FromWideChar" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object from the <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> buffer <em>w</em> of the given <em>size</em>.
Return <em>NULL</em> on failure.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsWideChar">
Py_ssize_t <code class="descname">PyUnicode_AsWideChar</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyUnicodeObject" title="PyUnicodeObject">PyUnicodeObject</a><em>&nbsp;*unicode</em>, wchar_t<em>&nbsp;*w</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsWideChar" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the Unicode object contents into the <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> buffer <em>w</em>.  At most
<em>size</em> <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> characters are copied (excluding a possibly trailing
0-termination character).  Return the number of <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> characters
copied or <code class="docutils literal notranslate"><span class="pre">-1</span></code> in case of an error.  Note that the resulting <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code>
string may or may not be 0-terminated.  It is the responsibility of the caller
to make sure that the <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> string is 0-terminated in case this is
required by the application. Also, note that the <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t*</span></code> string
might contain null characters, which would cause the string to be truncated
when used with most C functions.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type and used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>
type for <em>size</em>. This might require changes in your code for properly
supporting 64-bit systems.</p>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="built-in-codecs">
<span id="builtincodecs"></span><h2>Built-in Codecs<a class="headerlink" href="#built-in-codecs" title="Permalink to this headline">¶</a></h2>
<p>Python provides a set of built-in codecs which are written in C for speed. All of
these codecs are directly usable via the following functions.</p>
<p>Many of the following APIs take two arguments encoding and errors, and they
have the same semantics as the ones of the built-in <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> Unicode
object constructor.</p>
<p>Setting encoding to <em>NULL</em> causes the default encoding to be used which is
ASCII.  The file system calls should use <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_FileSystemDefaultEncoding</span></code>
as the encoding for file names. This variable should be treated as read-only: on
some systems, it will be a pointer to a static string, on others, it will change
at run-time (such as when the application invokes setlocale).</p>
<p>Error handling is set by errors which may also be set to <em>NULL</em> meaning to use
the default handling defined for the codec.  Default error handling for all
built-in codecs is “strict” (<a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised).</p>
<p>The codecs all use a similar interface.  Only deviation from the following
generic ones are documented for simplicity.</p>
<div class="section" id="generic-codecs">
<h3>Generic Codecs<a class="headerlink" href="#generic-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the generic codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_Decode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Decode</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Decode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the encoded string <em>s</em>.
<em>encoding</em> and <em>errors</em> have the same meaning as the parameters of the same name
in the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> built-in function.  The codec to be used is looked up
using the Python codec registry.  Return <em>NULL</em> if an exception was raised by
the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Encode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Encode</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Encode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer <em>s</em> of the given <em>size</em> and return a Python
string object.  <em>encoding</em> and <em>errors</em> have the same meaning as the parameters
of the same name in the Unicode <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method.  The codec
to be used is looked up using the Python codec registry.  Return <em>NULL</em> if
an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsEncodedString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsEncodedString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsEncodedString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object and return the result as Python string object.
<em>encoding</em> and <em>errors</em> have the same meaning as the parameters of the same name
in the Unicode <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method. The codec to be used is looked up using
the Python codec registry. Return <em>NULL</em> if an exception was raised by the
codec.</p>
</dd></dl>

</div>
<div class="section" id="utf-8-codecs">
<h3>UTF-8 Codecs<a class="headerlink" href="#utf-8-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the UTF-8 codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeUTF8">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF8</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF8" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the UTF-8 encoded string
<em>s</em>. Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_DecodeUTF8Stateful">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF8Stateful</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, Py_ssize_t<em>&nbsp;*consumed</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF8Stateful" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>If <em>consumed</em> is <em>NULL</em>, behave like <a class="reference internal" href="#c.PyUnicode_DecodeUTF8" title="PyUnicode_DecodeUTF8"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF8()</span></code></a>. If
<em>consumed</em> is not <em>NULL</em>, trailing incomplete UTF-8 byte sequences will not be
treated as an error. Those bytes will not be decoded and the number of bytes
that have been decoded will be stored in <em>consumed</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeUTF8">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeUTF8</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeUTF8" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer <em>s</em> of the given <em>size</em> using UTF-8 and return a
Python string object.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsUTF8String">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsUTF8String</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsUTF8String" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using UTF-8 and return the result as Python string
object.  Error handling is “strict”.  Return <em>NULL</em> if an exception was raised
by the codec.</p>
</dd></dl>

</div>
<div class="section" id="utf-32-codecs">
<h3>UTF-32 Codecs<a class="headerlink" href="#utf-32-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the UTF-32 codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeUTF32">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF32</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;*byteorder</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF32" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode <em>size</em> bytes from a UTF-32 encoded buffer string and return the
corresponding Unicode object.  <em>errors</em> (if non-<em>NULL</em>) defines the error
handling. It defaults to “strict”.</p>
<p>If <em>byteorder</em> is non-<em>NULL</em>, the decoder starts decoding using the given byte
order:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="o">:</span> <span class="n">little</span> <span class="n">endian</span>
<span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="mi">0</span><span class="o">:</span>  <span class="n">native</span> <span class="n">order</span>
<span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="mi">1</span><span class="o">:</span>  <span class="n">big</span> <span class="n">endian</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">*byteorder</span></code> is zero, and the first four bytes of the input data are a
byte order mark (BOM), the decoder switches to this byte order and the BOM is
not copied into the resulting Unicode string.  If <code class="docutils literal notranslate"><span class="pre">*byteorder</span></code> is <code class="docutils literal notranslate"><span class="pre">-1</span></code> or
<code class="docutils literal notranslate"><span class="pre">1</span></code>, any byte order mark is copied to the output.</p>
<p>After completion, <em>*byteorder</em> is set to the current byte order at the end
of input data.</p>
<p>In a narrow build code points outside the BMP will be decoded as surrogate pairs.</p>
<p>If <em>byteorder</em> is <em>NULL</em>, the codec starts in native order mode.</p>
<p>Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_DecodeUTF32Stateful">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF32Stateful</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;*byteorder</em>, Py_ssize_t<em>&nbsp;*consumed</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF32Stateful" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>consumed</em> is <em>NULL</em>, behave like <a class="reference internal" href="#c.PyUnicode_DecodeUTF32" title="PyUnicode_DecodeUTF32"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF32()</span></code></a>. If
<em>consumed</em> is not <em>NULL</em>, <a class="reference internal" href="#c.PyUnicode_DecodeUTF32Stateful" title="PyUnicode_DecodeUTF32Stateful"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF32Stateful()</span></code></a> will not treat
trailing incomplete UTF-32 byte sequences (such as a number of bytes not divisible
by four) as an error. Those bytes will not be decoded and the number of bytes
that have been decoded will be stored in <em>consumed</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeUTF32">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeUTF32</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;byteorder</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeUTF32" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a Python bytes object holding the UTF-32 encoded value of the Unicode
data in <em>s</em>.  Output is written according to the following byte order:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">byteorder</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="o">:</span> <span class="n">little</span> <span class="n">endian</span>
<span class="n">byteorder</span> <span class="o">==</span> <span class="mi">0</span><span class="o">:</span>  <span class="n">native</span> <span class="n">byte</span> <span class="n">order</span> <span class="p">(</span><span class="n">writes</span> <span class="n">a</span> <span class="n">BOM</span> <span class="n">mark</span><span class="p">)</span>
<span class="n">byteorder</span> <span class="o">==</span> <span class="mi">1</span><span class="o">:</span>  <span class="n">big</span> <span class="n">endian</span>
</pre></div>
</div>
<p>If byteorder is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the output string will always start with the Unicode BOM
mark (U+FEFF). In the other two modes, no BOM mark is prepended.</p>
<p>If <em>Py_UNICODE_WIDE</em> is not defined, surrogate pairs will be output
as a single code point.</p>
<p>Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsUTF32String">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsUTF32String</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsUTF32String" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a Python string using the UTF-32 encoding in native byte order. The
string always starts with a BOM mark.  Error handling is “strict”.  Return
<em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="utf-16-codecs">
<h3>UTF-16 Codecs<a class="headerlink" href="#utf-16-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the UTF-16 codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeUTF16">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF16</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;*byteorder</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF16" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Decode <em>size</em> bytes from a UTF-16 encoded buffer string and return the
corresponding Unicode object.  <em>errors</em> (if non-<em>NULL</em>) defines the error
handling. It defaults to “strict”.</p>
<p>If <em>byteorder</em> is non-<em>NULL</em>, the decoder starts decoding using the given byte
order:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="o">:</span> <span class="n">little</span> <span class="n">endian</span>
<span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="mi">0</span><span class="o">:</span>  <span class="n">native</span> <span class="n">order</span>
<span class="o">*</span><span class="n">byteorder</span> <span class="o">==</span> <span class="mi">1</span><span class="o">:</span>  <span class="n">big</span> <span class="n">endian</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">*byteorder</span></code> is zero, and the first two bytes of the input data are a
byte order mark (BOM), the decoder switches to this byte order and the BOM is
not copied into the resulting Unicode string.  If <code class="docutils literal notranslate"><span class="pre">*byteorder</span></code> is <code class="docutils literal notranslate"><span class="pre">-1</span></code> or
<code class="docutils literal notranslate"><span class="pre">1</span></code>, any byte order mark is copied to the output (where it will result in
either a <code class="docutils literal notranslate"><span class="pre">\ufeff</span></code> or a <code class="docutils literal notranslate"><span class="pre">\ufffe</span></code> character).</p>
<p>After completion, <em>*byteorder</em> is set to the current byte order at the end
of input data.</p>
<p>If <em>byteorder</em> is <em>NULL</em>, the codec starts in native order mode.</p>
<p>Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_DecodeUTF16Stateful">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF16Stateful</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;*byteorder</em>, Py_ssize_t<em>&nbsp;*consumed</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF16Stateful" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>If <em>consumed</em> is <em>NULL</em>, behave like <a class="reference internal" href="#c.PyUnicode_DecodeUTF16" title="PyUnicode_DecodeUTF16"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF16()</span></code></a>. If
<em>consumed</em> is not <em>NULL</em>, <a class="reference internal" href="#c.PyUnicode_DecodeUTF16Stateful" title="PyUnicode_DecodeUTF16Stateful"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF16Stateful()</span></code></a> will not treat
trailing incomplete UTF-16 byte sequences (such as an odd number of bytes or a
split surrogate pair) as an error. Those bytes will not be decoded and the
number of bytes that have been decoded will be stored in <em>consumed</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em> and an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code>
type for <em>consumed</em>. This might require changes in your code for
properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeUTF16">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeUTF16</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;byteorder</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeUTF16" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a Python string object holding the UTF-16 encoded value of the Unicode
data in <em>s</em>.  Output is written according to the following byte order:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">byteorder</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="o">:</span> <span class="n">little</span> <span class="n">endian</span>
<span class="n">byteorder</span> <span class="o">==</span> <span class="mi">0</span><span class="o">:</span>  <span class="n">native</span> <span class="n">byte</span> <span class="n">order</span> <span class="p">(</span><span class="n">writes</span> <span class="n">a</span> <span class="n">BOM</span> <span class="n">mark</span><span class="p">)</span>
<span class="n">byteorder</span> <span class="o">==</span> <span class="mi">1</span><span class="o">:</span>  <span class="n">big</span> <span class="n">endian</span>
</pre></div>
</div>
<p>If byteorder is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the output string will always start with the Unicode BOM
mark (U+FEFF). In the other two modes, no BOM mark is prepended.</p>
<p>If <em>Py_UNICODE_WIDE</em> is defined, a single <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> value may get
represented as a surrogate pair. If it is not defined, each <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a>
values is interpreted as a UCS-2 character.</p>
<p>Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsUTF16String">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsUTF16String</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsUTF16String" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a Python string using the UTF-16 encoding in native byte order. The
string always starts with a BOM mark.  Error handling is “strict”.  Return
<em>NULL</em> if an exception was raised by the codec.</p>
</dd></dl>

</div>
<div class="section" id="utf-7-codecs">
<h3>UTF-7 Codecs<a class="headerlink" href="#utf-7-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the UTF-7 codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeUTF7">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF7</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF7" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a Unicode object by decoding <em>size</em> bytes of the UTF-7 encoded string
<em>s</em>.  Return <em>NULL</em> if an exception was raised by the codec.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_DecodeUTF7Stateful">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUTF7Stateful</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, Py_ssize_t<em>&nbsp;*consumed</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUTF7Stateful" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>consumed</em> is <em>NULL</em>, behave like <a class="reference internal" href="#c.PyUnicode_DecodeUTF7" title="PyUnicode_DecodeUTF7"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeUTF7()</span></code></a>.  If
<em>consumed</em> is not <em>NULL</em>, trailing incomplete UTF-7 base-64 sections will not
be treated as an error.  Those bytes will not be decoded and the number of
bytes that have been decoded will be stored in <em>consumed</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeUTF7">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeUTF7</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, int<em>&nbsp;base64SetO</em>, int<em>&nbsp;base64WhiteSpace</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeUTF7" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given size using UTF-7 and
return a Python bytes object.  Return <em>NULL</em> if an exception was raised by
the codec.</p>
<p>If <em>base64SetO</em> is nonzero, “Set O” (punctuation that has no otherwise
special meaning) will be encoded in base-64.  If <em>base64WhiteSpace</em> is
nonzero, whitespace will be encoded in base-64.  Both are set to zero for the
Python “utf-7” codec.</p>
</dd></dl>

</div>
<div class="section" id="unicode-escape-codecs">
<h3>Unicode-Escape Codecs<a class="headerlink" href="#unicode-escape-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the “Unicode Escape” codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeUnicodeEscape">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeUnicodeEscape</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeUnicodeEscape" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the Unicode-Escape encoded
string <em>s</em>.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeUnicodeEscape">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeUnicodeEscape</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeUnicodeEscape" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using Unicode-Escape and
return a Python string object.  Return <em>NULL</em> if an exception was raised by the
codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsUnicodeEscapeString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsUnicodeEscapeString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsUnicodeEscapeString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using Unicode-Escape and return the result as Python
string object.  Error handling is “strict”. Return <em>NULL</em> if an exception was
raised by the codec.</p>
</dd></dl>

</div>
<div class="section" id="raw-unicode-escape-codecs">
<h3>Raw-Unicode-Escape Codecs<a class="headerlink" href="#raw-unicode-escape-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the “Raw Unicode Escape” codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeRawUnicodeEscape">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeRawUnicodeEscape</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeRawUnicodeEscape" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the Raw-Unicode-Escape
encoded string <em>s</em>.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeRawUnicodeEscape">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeRawUnicodeEscape</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeRawUnicodeEscape" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using Raw-Unicode-Escape
and return a Python string object.  Return <em>NULL</em> if an exception was raised by
the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsRawUnicodeEscapeString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsRawUnicodeEscapeString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsRawUnicodeEscapeString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using Raw-Unicode-Escape and return the result as
Python string object. Error handling is “strict”. Return <em>NULL</em> if an exception
was raised by the codec.</p>
</dd></dl>

</div>
<div class="section" id="latin-1-codecs">
<h3>Latin-1 Codecs<a class="headerlink" href="#latin-1-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the Latin-1 codec APIs: Latin-1 corresponds to the first 256 Unicode
ordinals and only these are accepted by the codecs during encoding.</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeLatin1">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeLatin1</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeLatin1" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the Latin-1 encoded string
<em>s</em>.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeLatin1">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeLatin1</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeLatin1" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using Latin-1 and return
a Python string object.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsLatin1String">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsLatin1String</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsLatin1String" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using Latin-1 and return the result as Python string
object.  Error handling is “strict”.  Return <em>NULL</em> if an exception was raised
by the codec.</p>
</dd></dl>

</div>
<div class="section" id="ascii-codecs">
<h3>ASCII Codecs<a class="headerlink" href="#ascii-codecs" title="Permalink to this headline">¶</a></h3>
<p>These are the ASCII codec APIs.  Only 7-bit ASCII data is accepted. All other
codes generate errors.</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeASCII">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeASCII</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeASCII" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the ASCII encoded string
<em>s</em>.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeASCII">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeASCII</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeASCII" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using ASCII and return a
Python string object.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsASCIIString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsASCIIString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsASCIIString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using ASCII and return the result as Python string
object.  Error handling is “strict”.  Return <em>NULL</em> if an exception was raised
by the codec.</p>
</dd></dl>

</div>
<div class="section" id="character-map-codecs">
<h3>Character Map Codecs<a class="headerlink" href="#character-map-codecs" title="Permalink to this headline">¶</a></h3>
<p>This codec is special in that it can be used to implement many different codecs
(and this is in fact what was done to obtain most of the standard codecs
included in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings</span></code> package). The codec uses mapping to encode and
decode characters.</p>
<p>Decoding mappings must map single string characters to single Unicode
characters, integers (which are then interpreted as Unicode ordinals) or <code class="docutils literal notranslate"><span class="pre">None</span></code>
(meaning “undefined mapping” and causing an error).</p>
<p>Encoding mappings must map single Unicode characters to single string
characters, integers (which are then interpreted as Latin-1 ordinals) or <code class="docutils literal notranslate"><span class="pre">None</span></code>
(meaning “undefined mapping” and causing an error).</p>
<p>The mapping objects provided must only support the __getitem__ mapping
interface.</p>
<p>If a character lookup fails with a LookupError, the character is copied as-is
meaning that its ordinal value will be interpreted as Unicode or Latin-1 ordinal
resp. Because of this, mappings only need to contain those mappings which map
characters to different code points.</p>
<p>These are the mapping codec APIs:</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeCharmap">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeCharmap</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*mapping</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeCharmap" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the encoded string <em>s</em> using
the given <em>mapping</em> object.  Return <em>NULL</em> if an exception was raised by the
codec. If <em>mapping</em> is <em>NULL</em> latin-1 decoding will be done. Else it can be a
dictionary mapping byte or a unicode string, which is treated as a lookup table.
Byte values greater that the length of the string and U+FFFE “characters” are
treated as “undefined mapping”.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Allowed unicode string as mapping argument.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeCharmap">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeCharmap</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*mapping</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeCharmap" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using the given
<em>mapping</em> object and return a Python string object. Return <em>NULL</em> if an
exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsCharmapString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsCharmapString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*mapping</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsCharmapString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using the given <em>mapping</em> object and return the result
as Python string object.  Error handling is “strict”.  Return <em>NULL</em> if an
exception was raised by the codec.</p>
</dd></dl>

<p>The following codec API is special in that maps Unicode to Unicode.</p>
<dl class="function">
<dt id="c.PyUnicode_TranslateCharmap">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_TranslateCharmap</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*table</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_TranslateCharmap" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Translate a <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> by applying a
character mapping <em>table</em> to it and return the resulting Unicode object.  Return
<em>NULL</em> when an exception was raised by the codec.</p>
<p>The <em>mapping</em> table must map Unicode ordinal integers to Unicode ordinal
integers or <code class="docutils literal notranslate"><span class="pre">None</span></code> (causing deletion of the character).</p>
<p>Mapping tables need only provide the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> interface; dictionaries
and sequences work well.  Unmapped character ordinals (ones which cause a
<a class="reference internal" href="../library/exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a>) are left untouched and are copied as-is.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

</div>
<div class="section" id="mbcs-codecs-for-windows">
<h3>MBCS codecs for Windows<a class="headerlink" href="#mbcs-codecs-for-windows" title="Permalink to this headline">¶</a></h3>
<p>These are the MBCS codec APIs. They are currently only available on Windows and
use the Win32 MBCS converters to implement the conversions.  Note that MBCS (or
DBCS) is a class of encodings, not just one.  The target encoding is defined by
the user settings on the machine running the codec.</p>
<dl class="function">
<dt id="c.PyUnicode_DecodeMBCS">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeMBCS</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeMBCS" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a Unicode object by decoding <em>size</em> bytes of the MBCS encoded string <em>s</em>.
Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_DecodeMBCSStateful">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_DecodeMBCSStateful</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, int<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em>, int<em>&nbsp;*consumed</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_DecodeMBCSStateful" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>consumed</em> is <em>NULL</em>, behave like <a class="reference internal" href="#c.PyUnicode_DecodeMBCS" title="PyUnicode_DecodeMBCS"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeMBCS()</span></code></a>. If
<em>consumed</em> is not <em>NULL</em>, <a class="reference internal" href="#c.PyUnicode_DecodeMBCSStateful" title="PyUnicode_DecodeMBCSStateful"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyUnicode_DecodeMBCSStateful()</span></code></a> will not decode
trailing lead byte and the number of bytes that have been decoded will be stored
in <em>consumed</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_EncodeMBCS">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_EncodeMBCS</code><span class="sig-paren">(</span>const <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*s</em>, Py_ssize_t<em>&nbsp;size</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_EncodeMBCS" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode the <a class="reference internal" href="#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> buffer of the given <em>size</em> using MBCS and return a
Python string object.  Return <em>NULL</em> if an exception was raised by the codec.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_AsMBCSString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_AsMBCSString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_AsMBCSString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Encode a Unicode object using MBCS and return the result as Python string
object.  Error handling is “strict”.  Return <em>NULL</em> if an exception was raised
by the codec.</p>
</dd></dl>

</div>
<div class="section" id="methods-slots">
<h3>Methods &amp; Slots<a class="headerlink" href="#methods-slots" title="Permalink to this headline">¶</a></h3>
</div>
</div>
<div class="section" id="methods-and-slot-functions">
<span id="unicodemethodsandslots"></span><h2>Methods and Slot Functions<a class="headerlink" href="#methods-and-slot-functions" title="Permalink to this headline">¶</a></h2>
<p>The following APIs are capable of handling Unicode objects and strings on input
(we refer to them as strings in the descriptions) and return Unicode objects or
integers as appropriate.</p>
<p>They all return <em>NULL</em> or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an exception occurs.</p>
<dl class="function">
<dt id="c.PyUnicode_Concat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Concat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*left</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*right</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Concat" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Concat two strings giving a new Unicode string.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Split">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Split</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*s</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*sep</em>, Py_ssize_t<em>&nbsp;maxsplit</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Split" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Split a string giving a list of Unicode strings.  If <em>sep</em> is <em>NULL</em>, splitting
will be done at all whitespace substrings.  Otherwise, splits occur at the given
separator.  At most <em>maxsplit</em> splits will be done.  If negative, no limit is
set.  Separators are not included in the resulting list.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>maxsplit</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Splitlines">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Splitlines</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*s</em>, int<em>&nbsp;keepend</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Splitlines" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Split a Unicode string at line breaks, returning a list of Unicode strings.
CRLF is considered to be one line break.  If <em>keepend</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the Line break
characters are not included in the resulting strings.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Translate">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Translate</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*table</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Translate" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Translate a string by applying a character mapping table to it and return the
resulting Unicode object.</p>
<p>The mapping table must map Unicode ordinal integers to Unicode ordinal integers
or <code class="docutils literal notranslate"><span class="pre">None</span></code> (causing deletion of the character).</p>
<p>Mapping tables need only provide the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> interface; dictionaries
and sequences work well.  Unmapped character ordinals (ones which cause a
<a class="reference internal" href="../library/exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a>) are left untouched and are copied as-is.</p>
<p><em>errors</em> has the usual meaning for codecs. It may be <em>NULL</em> which indicates to
use the default error handling.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Join">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Join</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*separator</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*seq</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Join" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Join a sequence of strings using the given <em>separator</em> and return the resulting
Unicode string.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Tailmatch">
Py_ssize_t <code class="descname">PyUnicode_Tailmatch</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*substr</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em>, int<em>&nbsp;direction</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Tailmatch" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>substr</em> matches <code class="docutils literal notranslate"><span class="pre">str[start:end]</span></code> at the given tail end
(<em>direction</em> == <code class="docutils literal notranslate"><span class="pre">-1</span></code> means to do a prefix match, <em>direction</em> == <code class="docutils literal notranslate"><span class="pre">1</span></code> a suffix match),
<code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise. Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an error occurred.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>start</em> and <em>end</em>. This
might require changes in your code for properly supporting 64-bit
systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Find">
Py_ssize_t <code class="descname">PyUnicode_Find</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*substr</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em>, int<em>&nbsp;direction</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Find" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the first position of <em>substr</em> in <code class="docutils literal notranslate"><span class="pre">str[start:end]</span></code> using the given
<em>direction</em> (<em>direction</em> == <code class="docutils literal notranslate"><span class="pre">1</span></code> means to do a forward search, <em>direction</em> == <code class="docutils literal notranslate"><span class="pre">-1</span></code> a
backward search).  The return value is the index of the first match; a value of
<code class="docutils literal notranslate"><span class="pre">-1</span></code> indicates that no match was found, and <code class="docutils literal notranslate"><span class="pre">-2</span></code> indicates that an error
occurred and an exception has been set.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>start</em> and <em>end</em>. This
might require changes in your code for properly supporting 64-bit
systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Count">
Py_ssize_t <code class="descname">PyUnicode_Count</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*substr</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of non-overlapping occurrences of <em>substr</em> in
<code class="docutils literal notranslate"><span class="pre">str[start:end]</span></code>.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an error occurred.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type and used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>
type for <em>start</em> and <em>end</em>. This might require changes in your code for
properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Replace">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Replace</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*substr</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*replstr</em>, Py_ssize_t<em>&nbsp;maxcount</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Replace" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Replace at most <em>maxcount</em> occurrences of <em>substr</em> in <em>str</em> with <em>replstr</em> and
return the resulting Unicode object. <em>maxcount</em> == <code class="docutils literal notranslate"><span class="pre">-1</span></code> means replace all
occurrences.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>maxcount</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Compare">
int <code class="descname">PyUnicode_Compare</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*left</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*right</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Compare" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare two strings and return <code class="docutils literal notranslate"><span class="pre">-1</span></code>, <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">1</span></code> for less than, equal, and greater than,
respectively.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_RichCompare">
int <code class="descname">PyUnicode_RichCompare</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*left</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*right</em>, int<em>&nbsp;op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_RichCompare" title="Permalink to this definition">¶</a></dt>
<dd><p>Rich compare two unicode strings and return one of the following:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">NULL</span></code> in case an exception was raised</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_True</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_False</span></code> for successful comparisons</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code> in case the type combination is unknown</li>
</ul>
<p>Note that <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code> comparisons can cause a
<a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeWarning" title="exceptions.UnicodeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a> in case the conversion of the arguments to Unicode fails
with a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a>.</p>
<p>Possible values for <em>op</em> are <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_GE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_EQ</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_NE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LT</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_LE</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Format">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicode_Format</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*format</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Format" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new string object from <em>format</em> and <em>args</em>; this is analogous to
<code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">args</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicode_Contains">
int <code class="descname">PyUnicode_Contains</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*container</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*element</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicode_Contains" title="Permalink to this definition">¶</a></dt>
<dd><p>Check whether <em>element</em> is contained in <em>container</em> and return true or false
accordingly.</p>
<p><em>element</em> has to coerce to a one element Unicode string. <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned if
there was an error.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Unicode Objects and Codecs</a><ul>
<li><a class="reference internal" href="#unicode-objects">Unicode Objects</a><ul>
<li><a class="reference internal" href="#unicode-type">Unicode Type</a></li>
<li><a class="reference internal" href="#unicode-character-properties">Unicode Character Properties</a></li>
<li><a class="reference internal" href="#plain-py-unicode">Plain Py_UNICODE</a></li>
<li><a class="reference internal" href="#wchar-t-support">wchar_t Support</a></li>
</ul>
</li>
<li><a class="reference internal" href="#built-in-codecs">Built-in Codecs</a><ul>
<li><a class="reference internal" href="#generic-codecs">Generic Codecs</a></li>
<li><a class="reference internal" href="#utf-8-codecs">UTF-8 Codecs</a></li>
<li><a class="reference internal" href="#utf-32-codecs">UTF-32 Codecs</a></li>
<li><a class="reference internal" href="#utf-16-codecs">UTF-16 Codecs</a></li>
<li><a class="reference internal" href="#utf-7-codecs">UTF-7 Codecs</a></li>
<li><a class="reference internal" href="#unicode-escape-codecs">Unicode-Escape Codecs</a></li>
<li><a class="reference internal" href="#raw-unicode-escape-codecs">Raw-Unicode-Escape Codecs</a></li>
<li><a class="reference internal" href="#latin-1-codecs">Latin-1 Codecs</a></li>
<li><a class="reference internal" href="#ascii-codecs">ASCII Codecs</a></li>
<li><a class="reference internal" href="#character-map-codecs">Character Map Codecs</a></li>
<li><a class="reference internal" href="#mbcs-codecs-for-windows">MBCS codecs for Windows</a></li>
<li><a class="reference internal" href="#methods-slots">Methods &amp; Slots</a></li>
</ul>
</li>
<li><a class="reference internal" href="#methods-and-slot-functions">Methods and Slot Functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="string.html"
                        title="previous chapter">String/Bytes Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="buffer.html"
                        title="next chapter">Buffers and Memoryview Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/unicode.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="buffer.html" title="Buffers and Memoryview Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="string.html" title="String/Bytes Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���ɤ�html/c-api/utilities.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Operating System Utilities" href="sys.html" />
    <link rel="prev" title="Exception Handling" href="exceptions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/utilities.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sys.html" title="Operating System Utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="Exception Handling"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="utilities">
<span id="id1"></span><h1>Utilities<a class="headerlink" href="#utilities" title="Permalink to this headline">¶</a></h1>
<p>The functions in this chapter perform various utility tasks, ranging from
helping C code be more portable across platforms, using Python modules from C,
and parsing function arguments and constructing Python values from C values.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="sys.html">Operating System Utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="sys.html#system-functions">System Functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="sys.html#process-control">Process Control</a></li>
<li class="toctree-l1"><a class="reference internal" href="import.html">Importing Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="marshal.html">Data marshalling support</a></li>
<li class="toctree-l1"><a class="reference internal" href="arg.html">Parsing arguments and building values</a></li>
<li class="toctree-l1"><a class="reference internal" href="conversion.html">String conversion and formatting</a></li>
<li class="toctree-l1"><a class="reference internal" href="reflection.html">Reflection</a></li>
<li class="toctree-l1"><a class="reference internal" href="codec.html">Codec registry and support functions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="codec.html#codec-lookup-api">Codec lookup API</a></li>
<li class="toctree-l2"><a class="reference internal" href="codec.html#registry-api-for-unicode-encoding-error-handlers">Registry API for Unicode encoding error handlers</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="exceptions.html"
                        title="previous chapter">Exception Handling</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sys.html"
                        title="next chapter">Operating System Utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/utilities.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sys.html" title="Operating System Utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="Exception Handling"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\<��ޭޭhtml/c-api/veryhigh.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>The Very High Level Layer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Reference Counting" href="refcounting.html" />
    <link rel="prev" title="Introduction" href="intro.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/veryhigh.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="refcounting.html" title="Reference Counting"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="intro.html" title="Introduction"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-very-high-level-layer">
<span id="veryhigh"></span><h1>The Very High Level Layer<a class="headerlink" href="#the-very-high-level-layer" title="Permalink to this headline">¶</a></h1>
<p>The functions in this chapter will let you execute Python source code given in a
file or a buffer, but they will not let you interact in a more detailed way with
the interpreter.</p>
<p>Several of these functions accept a start symbol from the grammar as a
parameter.  The available start symbols are <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_eval_input</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_file_input</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_single_input</span></code>.  These are described
following the functions which accept them as parameters.</p>
<p>Note also that several of these functions take <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> parameters.  One
particular issue which needs to be handled carefully is that the <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE</span></code>
structure for different C libraries can be different and incompatible.  Under
Windows (at least), it is possible for dynamically linked extensions to actually
use different libraries, so care should be taken that <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> parameters
are only passed to these functions if it is certain that they were created by
the same library that the Python runtime is using.</p>
<dl class="function">
<dt id="c.Py_Main">
int <code class="descname">Py_Main</code><span class="sig-paren">(</span>int<em>&nbsp;argc</em>, char<em>&nbsp;**argv</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_Main" title="Permalink to this definition">¶</a></dt>
<dd><p>The main program for the standard interpreter.  This is made available for
programs which embed Python.  The <em>argc</em> and <em>argv</em> parameters should be
prepared exactly as those which are passed to a C program’s <code class="xref c c-func docutils literal notranslate"><span class="pre">main()</span></code>
function.  It is important to note that the argument list may be modified (but
the contents of the strings pointed to by the argument list are not). The return
value will be <code class="docutils literal notranslate"><span class="pre">0</span></code> if the interpreter exits normally (ie, without an
exception), <code class="docutils literal notranslate"><span class="pre">1</span></code> if the interpreter exits due to an exception, or <code class="docutils literal notranslate"><span class="pre">2</span></code>
if the parameter list does not represent a valid Python command line.</p>
<p>Note that if an otherwise unhandled <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> is raised, this
function will not return <code class="docutils literal notranslate"><span class="pre">1</span></code>, but exit the process, as long as
<code class="docutils literal notranslate"><span class="pre">Py_InspectFlag</span></code> is not set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_AnyFile">
int <code class="descname">PyRun_AnyFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_AnyFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_AnyFileExFlags" title="PyRun_AnyFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_AnyFileExFlags()</span></code></a> below, leaving
<em>closeit</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_AnyFileFlags">
int <code class="descname">PyRun_AnyFileFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_AnyFileFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_AnyFileExFlags" title="PyRun_AnyFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_AnyFileExFlags()</span></code></a> below, leaving
the <em>closeit</em> argument set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_AnyFileEx">
int <code class="descname">PyRun_AnyFileEx</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;closeit</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_AnyFileEx" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_AnyFileExFlags" title="PyRun_AnyFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_AnyFileExFlags()</span></code></a> below, leaving
the <em>flags</em> argument set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_AnyFileExFlags">
int <code class="descname">PyRun_AnyFileExFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;closeit</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_AnyFileExFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>fp</em> refers to a file associated with an interactive device (console or
terminal input or Unix pseudo-terminal), return the value of
<a class="reference internal" href="#c.PyRun_InteractiveLoop" title="PyRun_InteractiveLoop"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveLoop()</span></code></a>, otherwise return the result of
<a class="reference internal" href="#c.PyRun_SimpleFile" title="PyRun_SimpleFile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFile()</span></code></a>.  If <em>filename</em> is <em>NULL</em>, this function uses
<code class="docutils literal notranslate"><span class="pre">&quot;???&quot;</span></code> as the filename.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleString">
int <code class="descname">PyRun_SimpleString</code><span class="sig-paren">(</span>const char<em>&nbsp;*command</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleString" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_SimpleStringFlags" title="PyRun_SimpleStringFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleStringFlags()</span></code></a> below,
leaving the <em>PyCompilerFlags*</em> argument set to NULL.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleStringFlags">
int <code class="descname">PyRun_SimpleStringFlags</code><span class="sig-paren">(</span>const char<em>&nbsp;*command</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleStringFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes the Python source code from <em>command</em> in the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module
according to the <em>flags</em> argument. If <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> does not already exist, it
is created.  Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an exception was raised.  If
there was an error, there is no way to get the exception information. For the
meaning of <em>flags</em>, see below.</p>
<p>Note that if an otherwise unhandled <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> is raised, this
function will not return <code class="docutils literal notranslate"><span class="pre">-1</span></code>, but exit the process, as long as
<code class="docutils literal notranslate"><span class="pre">Py_InspectFlag</span></code> is not set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleFile">
int <code class="descname">PyRun_SimpleFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_SimpleFileExFlags" title="PyRun_SimpleFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFileExFlags()</span></code></a> below,
leaving <em>closeit</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleFileFlags">
int <code class="descname">PyRun_SimpleFileFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleFileFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_SimpleFileExFlags" title="PyRun_SimpleFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFileExFlags()</span></code></a> below,
leaving <em>closeit</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleFileEx">
int <code class="descname">PyRun_SimpleFileEx</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;closeit</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleFileEx" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_SimpleFileExFlags" title="PyRun_SimpleFileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFileExFlags()</span></code></a> below,
leaving <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_SimpleFileExFlags">
int <code class="descname">PyRun_SimpleFileExFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;closeit</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_SimpleFileExFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#c.PyRun_SimpleStringFlags" title="PyRun_SimpleStringFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleStringFlags()</span></code></a>, but the Python source code is read
from <em>fp</em> instead of an in-memory string. <em>filename</em> should be the name of the
file.  If <em>closeit</em> is true, the file is closed before PyRun_SimpleFileExFlags
returns.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_InteractiveOne">
int <code class="descname">PyRun_InteractiveOne</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_InteractiveOne" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_InteractiveOneFlags" title="PyRun_InteractiveOneFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveOneFlags()</span></code></a> below,
leaving <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_InteractiveOneFlags">
int <code class="descname">PyRun_InteractiveOneFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_InteractiveOneFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and execute a single statement from a file associated with an
interactive device according to the <em>flags</em> argument.  The user will be
prompted using <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>.  Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> when the input was
executed successfully, <code class="docutils literal notranslate"><span class="pre">-1</span></code> if there was an exception, or an error code
from the <code class="file docutils literal notranslate"><span class="pre">errcode.h</span></code> include file distributed as part of Python if
there was a parse error.  (Note that <code class="file docutils literal notranslate"><span class="pre">errcode.h</span></code> is not included by
<code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>, so must be included specifically if needed.)</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_InteractiveLoop">
int <code class="descname">PyRun_InteractiveLoop</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_InteractiveLoop" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_InteractiveLoopFlags" title="PyRun_InteractiveLoopFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveLoopFlags()</span></code></a> below,
leaving <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_InteractiveLoopFlags">
int <code class="descname">PyRun_InteractiveLoopFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_InteractiveLoopFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and execute statements from a file associated with an interactive device
until EOF is reached.  The user will be prompted using <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and
<code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>.  Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> at EOF.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyParser_SimpleParseString">
struct _node* <code class="descname">PyParser_SimpleParseString</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, int<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyParser_SimpleParseString" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to
<a class="reference internal" href="#c.PyParser_SimpleParseStringFlagsFilename" title="PyParser_SimpleParseStringFlagsFilename"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_SimpleParseStringFlagsFilename()</span></code></a> below, leaving  <em>filename</em> set
to <em>NULL</em> and <em>flags</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyParser_SimpleParseStringFlags">
struct _node* <code class="descname">PyParser_SimpleParseStringFlags</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, int<em>&nbsp;start</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyParser_SimpleParseStringFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to
<a class="reference internal" href="#c.PyParser_SimpleParseStringFlagsFilename" title="PyParser_SimpleParseStringFlagsFilename"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_SimpleParseStringFlagsFilename()</span></code></a> below, leaving  <em>filename</em> set
to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyParser_SimpleParseStringFlagsFilename">
struct _node* <code class="descname">PyParser_SimpleParseStringFlagsFilename</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyParser_SimpleParseStringFlagsFilename" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse Python source code from <em>str</em> using the start token <em>start</em> according to
the <em>flags</em> argument.  The result can be used to create a code object which can
be evaluated efficiently. This is useful if a code fragment must be evaluated
many times.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyParser_SimpleParseFile">
struct _node* <code class="descname">PyParser_SimpleParseFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyParser_SimpleParseFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a simplified interface to <a class="reference internal" href="#c.PyParser_SimpleParseFileFlags" title="PyParser_SimpleParseFileFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_SimpleParseFileFlags()</span></code></a> below,
leaving <em>flags</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyParser_SimpleParseFileFlags">
struct _node* <code class="descname">PyParser_SimpleParseFileFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyParser_SimpleParseFileFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#c.PyParser_SimpleParseStringFlagsFilename" title="PyParser_SimpleParseStringFlagsFilename"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_SimpleParseStringFlagsFilename()</span></code></a>, but the Python
source code is read from <em>fp</em> instead of an in-memory string.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_String">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_String</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_String" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_StringFlags" title="PyRun_StringFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_StringFlags()</span></code></a> below, leaving
<em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_StringFlags">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_StringFlags</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_StringFlags" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Execute Python source code from <em>str</em> in the context specified by the
dictionaries <em>globals</em> and <em>locals</em> with the compiler flags specified by
<em>flags</em>.  The parameter <em>start</em> specifies the start token that should be used to
parse the source code.</p>
<p>Returns the result of executing the code as a Python object, or <em>NULL</em> if an
exception was raised.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_File">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_File</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_File" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_FileExFlags" title="PyRun_FileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_FileExFlags()</span></code></a> below, leaving
<em>closeit</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_FileEx">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_FileEx</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, int<em>&nbsp;closeit</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_FileEx" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_FileExFlags" title="PyRun_FileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_FileExFlags()</span></code></a> below, leaving
<em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_FileFlags">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_FileFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_FileFlags" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.PyRun_FileExFlags" title="PyRun_FileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_FileExFlags()</span></code></a> below, leaving
<em>closeit</em> set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyRun_FileExFlags">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyRun_FileExFlags</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, int<em>&nbsp;closeit</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyRun_FileExFlags" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Similar to <a class="reference internal" href="#c.PyRun_StringFlags" title="PyRun_StringFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_StringFlags()</span></code></a>, but the Python source code is read from
<em>fp</em> instead of an in-memory string. <em>filename</em> should be the name of the file.
If <em>closeit</em> is true, the file is closed before <a class="reference internal" href="#c.PyRun_FileExFlags" title="PyRun_FileExFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_FileExFlags()</span></code></a>
returns.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_CompileString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_CompileString</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_CompileString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.Py_CompileStringFlags" title="Py_CompileStringFlags"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CompileStringFlags()</span></code></a> below, leaving
<em>flags</em> set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_CompileStringFlags">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_CompileStringFlags</code><span class="sig-paren">(</span>const char<em>&nbsp;*str</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;start</em>, <a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_CompileStringFlags" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Parse and compile the Python source code in <em>str</em>, returning the resulting code
object.  The start token is given by <em>start</em>; this can be used to constrain the
code which can be compiled and should be <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_eval_input</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_file_input</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_single_input</span></code>.  The filename specified by
<em>filename</em> is used to construct the code object and may appear in tracebacks or
<a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> exception messages.  This returns <em>NULL</em> if the code cannot
be parsed or compiled.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_EvalCode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_EvalCode</code><span class="sig-paren">(</span><a class="reference internal" href="code.html#c.PyCodeObject" title="PyCodeObject">PyCodeObject</a><em>&nbsp;*co</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_EvalCode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This is a simplified interface to <a class="reference internal" href="#c.PyEval_EvalCodeEx" title="PyEval_EvalCodeEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_EvalCodeEx()</span></code></a>, with just
the code object, and the dictionaries of global and local variables.
The other arguments are set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_EvalCodeEx">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_EvalCodeEx</code><span class="sig-paren">(</span><a class="reference internal" href="code.html#c.PyCodeObject" title="PyCodeObject">PyCodeObject</a><em>&nbsp;*co</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*locals</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**args</em>, int<em>&nbsp;argcount</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**kws</em>, int<em>&nbsp;kwcount</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**defs</em>, int<em>&nbsp;defcount</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*closure</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_EvalCodeEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Evaluate a precompiled code object, given a particular environment for its
evaluation.  This environment consists of dictionaries of global and local
variables, arrays of arguments, keywords and defaults, and a closure tuple of
cells.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_EvalFrame">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_EvalFrame</code><span class="sig-paren">(</span>PyFrameObject<em>&nbsp;*f</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_EvalFrame" title="Permalink to this definition">¶</a></dt>
<dd><p>Evaluate an execution frame.  This is a simplified interface to
PyEval_EvalFrameEx, for backward compatibility.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_EvalFrameEx">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyEval_EvalFrameEx</code><span class="sig-paren">(</span>PyFrameObject<em>&nbsp;*f</em>, int<em>&nbsp;throwflag</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_EvalFrameEx" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the main, unvarnished function of Python interpretation.  It is
literally 2000 lines long.  The code object associated with the execution
frame <em>f</em> is executed, interpreting bytecode and executing calls as needed.
The additional <em>throwflag</em> parameter can mostly be ignored - if true, then
it causes an exception to immediately be thrown; this is used for the
<a class="reference internal" href="../reference/expressions.html#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> methods of generator objects.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyEval_MergeCompilerFlags">
int <code class="descname">PyEval_MergeCompilerFlags</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyCompilerFlags" title="PyCompilerFlags">PyCompilerFlags</a><em>&nbsp;*cf</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyEval_MergeCompilerFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>This function changes the flags of the current evaluation frame, and returns
true on success, false on failure.</p>
</dd></dl>

<dl class="var">
<dt id="c.Py_eval_input">
int <code class="descname">Py_eval_input</code><a class="headerlink" href="#c.Py_eval_input" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">The start symbol from the Python grammar for isolated expressions; for use with
<a class="reference internal" href="#c.Py_CompileString" title="Py_CompileString"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CompileString()</span></code></a>.</p>
</dd></dl>

<dl class="var">
<dt id="c.Py_file_input">
int <code class="descname">Py_file_input</code><a class="headerlink" href="#c.Py_file_input" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">The start symbol from the Python grammar for sequences of statements as read
from a file or other source; for use with <a class="reference internal" href="#c.Py_CompileString" title="Py_CompileString"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CompileString()</span></code></a>.  This is
the symbol to use when compiling arbitrarily long Python source code.</p>
</dd></dl>

<dl class="var">
<dt id="c.Py_single_input">
int <code class="descname">Py_single_input</code><a class="headerlink" href="#c.Py_single_input" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">The start symbol from the Python grammar for a single statement; for use with
<a class="reference internal" href="#c.Py_CompileString" title="Py_CompileString"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CompileString()</span></code></a>. This is the symbol used for the interactive
interpreter loop.</p>
</dd></dl>

<dl class="type">
<dt id="c.PyCompilerFlags">
struct <code class="descname">PyCompilerFlags</code><a class="headerlink" href="#c.PyCompilerFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the structure used to hold compiler flags.  In cases where code is only
being compiled, it is passed as <code class="docutils literal notranslate"><span class="pre">int</span> <span class="pre">flags</span></code>, and in cases where code is being
executed, it is passed as <code class="docutils literal notranslate"><span class="pre">PyCompilerFlags</span> <span class="pre">*flags</span></code>.  In this case, <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">__future__</span> <span class="pre">import</span></code> can modify <em>flags</em>.</p>
<p>Whenever <code class="docutils literal notranslate"><span class="pre">PyCompilerFlags</span> <span class="pre">*flags</span></code> is <em>NULL</em>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">cf_flags</span></code> is treated as
equal to <code class="docutils literal notranslate"><span class="pre">0</span></code>, and any modification due to <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span></code> is
discarded.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">struct</span> <span class="n">PyCompilerFlags</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">cf_flags</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</dd></dl>

<dl class="var">
<dt id="c.CO_FUTURE_DIVISION">
int <code class="descname">CO_FUTURE_DIVISION</code><a class="headerlink" href="#c.CO_FUTURE_DIVISION" title="Permalink to this definition">¶</a></dt>
<dd><p>This bit can be set in <em>flags</em> to cause division operator <code class="docutils literal notranslate"><span class="pre">/</span></code> to be
interpreted as “true division” according to <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="intro.html"
                        title="previous chapter">Introduction</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="refcounting.html"
                        title="next chapter">Reference Counting</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/veryhigh.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="refcounting.html" title="Reference Counting"
             >next</a> |</li>
        <li class="right" >
          <a href="intro.html" title="Introduction"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��ۄ#5#5html/c-api/weakref.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Weak Reference Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Capsules" href="capsule.html" />
    <link rel="prev" title="Slice Objects" href="slice.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/weakref.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="capsule.html" title="Capsules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="slice.html" title="Slice Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="weak-reference-objects">
<span id="weakrefobjects"></span><h1>Weak Reference Objects<a class="headerlink" href="#weak-reference-objects" title="Permalink to this headline">¶</a></h1>
<p>Python supports <em>weak references</em> as first-class objects.  There are two
specific object types which directly implement weak references.  The first is a
simple reference object, and the second acts as a proxy for the original object
as much as it can.</p>
<dl class="function">
<dt id="c.PyWeakref_Check">
int <code class="descname">PyWeakref_Check</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is either a reference or proxy object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_CheckRef">
int <code class="descname">PyWeakref_CheckRef</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_CheckRef" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is a reference object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_CheckProxy">
int <code class="descname">PyWeakref_CheckProxy</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_CheckProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is a proxy object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_NewRef">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyWeakref_NewRef</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callback</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_NewRef" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a weak reference object for the object <em>ob</em>.  This will always return
a new reference, but is not guaranteed to create a new object; an existing
reference object may be returned.  The second parameter, <em>callback</em>, can be a
callable object that receives notification when <em>ob</em> is garbage collected; it
should accept a single parameter, which will be the weak reference object
itself. <em>callback</em> may also be <code class="docutils literal notranslate"><span class="pre">None</span></code> or <em>NULL</em>.  If <em>ob</em> is not a
weakly-referencable object, or if <em>callback</em> is not callable, <code class="docutils literal notranslate"><span class="pre">None</span></code>, or
<em>NULL</em>, this will return <em>NULL</em> and raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_NewProxy">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyWeakref_NewProxy</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*callback</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_NewProxy" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a weak reference proxy object for the object <em>ob</em>.  This will always
return a new reference, but is not guaranteed to create a new object; an
existing proxy object may be returned.  The second parameter, <em>callback</em>, can
be a callable object that receives notification when <em>ob</em> is garbage
collected; it should accept a single parameter, which will be the weak
reference object itself. <em>callback</em> may also be <code class="docutils literal notranslate"><span class="pre">None</span></code> or <em>NULL</em>.  If <em>ob</em>
is not a weakly-referencable object, or if <em>callback</em> is not callable,
<code class="docutils literal notranslate"><span class="pre">None</span></code>, or <em>NULL</em>, this will return <em>NULL</em> and raise <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_GetObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyWeakref_GetObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ref</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_GetObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the referenced object from a weak reference, <em>ref</em>.  If the referent is
no longer live, returns <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This function returns a <strong>borrowed reference</strong> to the referenced object.
This means that you should always call <a class="reference internal" href="refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> on the object
except if you know that it cannot be destroyed while you are still
using it.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWeakref_GET_OBJECT">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyWeakref_GET_OBJECT</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ref</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyWeakref_GET_OBJECT" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Similar to <a class="reference internal" href="#c.PyWeakref_GetObject" title="PyWeakref_GetObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyWeakref_GetObject()</span></code></a>, but implemented as a macro that does no
error checking.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="slice.html"
                        title="previous chapter">Slice Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="capsule.html"
                        title="next chapter">Capsules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/weakref.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="capsule.html" title="Capsules"
             >next</a> |</li>
        <li class="right" >
          <a href="slice.html" title="Slice Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�HĴ33html/c-api/abstract.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Abstract Objects Layer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Object Protocol" href="object.html" />
    <link rel="prev" title="Codec registry and support functions" href="codec.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/abstract.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="object.html" title="Object Protocol"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="codec.html" title="Codec registry and support functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="abstract-objects-layer">
<span id="abstract"></span><h1>Abstract Objects Layer<a class="headerlink" href="#abstract-objects-layer" title="Permalink to this headline">¶</a></h1>
<p>The functions in this chapter interact with Python objects regardless of their
type, or with wide classes of object types (e.g. all numerical types, or all
sequence types).  When used on object types for which they do not apply, they
will raise a Python exception.</p>
<p>It is not possible to use these functions on objects that are not properly
initialized, such as a list object that has been created by <a class="reference internal" href="list.html#c.PyList_New" title="PyList_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_New()</span></code></a>,
but whose items have not been set to some non-<code class="docutils literal notranslate"><span class="pre">NULL</span></code> value yet.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="object.html">Object Protocol</a></li>
<li class="toctree-l1"><a class="reference internal" href="number.html">Number Protocol</a></li>
<li class="toctree-l1"><a class="reference internal" href="sequence.html">Sequence Protocol</a></li>
<li class="toctree-l1"><a class="reference internal" href="mapping.html">Mapping Protocol</a></li>
<li class="toctree-l1"><a class="reference internal" href="iter.html">Iterator Protocol</a></li>
<li class="toctree-l1"><a class="reference internal" href="objbuffer.html">Old Buffer Protocol</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="codec.html"
                        title="previous chapter">Codec registry and support functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="object.html"
                        title="next chapter">Object Protocol</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/abstract.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="object.html" title="Object Protocol"
             >next</a> |</li>
        <li class="right" >
          <a href="codec.html" title="Codec registry and support functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\"8t_I_Ihtml/c-api/allocation.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Allocating Objects on the Heap &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Common Object Structures" href="structures.html" />
    <link rel="prev" title="Object Implementation Support" href="objimpl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/allocation.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="structures.html" title="Common Object Structures"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="objimpl.html" title="Object Implementation Support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" accesskey="U">Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="allocating-objects-on-the-heap">
<span id="allocating-objects"></span><h1>Allocating Objects on the Heap<a class="headerlink" href="#allocating-objects-on-the-heap" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c._PyObject_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">_PyObject_New</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyObject_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em></dd></dl>

<dl class="function">
<dt id="c._PyObject_NewVar">
<a class="reference internal" href="structures.html#c.PyVarObject" title="PyVarObject">PyVarObject</a>* <code class="descname">_PyObject_NewVar</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyObject_NewVar" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c._PyObject_Del">
void <code class="descname">_PyObject_Del</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyObject_Del" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="c.PyObject_Init">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyObject_Init</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em>, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Init" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Initialize a newly-allocated object <em>op</em> with its type and initial
reference.  Returns the initialized object.  If <em>type</em> indicates that the
object participates in the cyclic garbage detector, it is added to the
detector’s set of observed objects. Other fields of the object are not
affected.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_InitVar">
<a class="reference internal" href="structures.html#c.PyVarObject" title="PyVarObject">PyVarObject</a>* <code class="descname">PyObject_InitVar</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyVarObject" title="PyVarObject">PyVarObject</a><em>&nbsp;*op</em>, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_InitVar" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>This does everything <a class="reference internal" href="#c.PyObject_Init" title="PyObject_Init"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Init()</span></code></a> does, and also initializes the
length information for a variable-size object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_New">
TYPE* <code class="descname">PyObject_New</code><span class="sig-paren">(</span>TYPE, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Allocate a new Python object using the C structure type <em>TYPE</em> and the
Python type object <em>type</em>.  Fields not defined by the Python object header
are not initialized; the object’s reference count will be one.  The size of
the memory allocation is determined from the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> field of
the type object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_NewVar">
TYPE* <code class="descname">PyObject_NewVar</code><span class="sig-paren">(</span>TYPE, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_NewVar" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Allocate a new Python object using the C structure type <em>TYPE</em> and the
Python type object <em>type</em>.  Fields not defined by the Python object header
are not initialized.  The allocated memory allows for the <em>TYPE</em> structure
plus <em>size</em> fields of the size given by the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> field of
<em>type</em>.  This is useful for implementing objects like tuples, which are
able to determine their size at construction time.  Embedding the array of
fields into the same allocation decreases the number of allocations,
improving the memory management efficiency.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_Del">
void <code class="descname">PyObject_Del</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_Del" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases memory allocated to an object using <a class="reference internal" href="#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a> or
<a class="reference internal" href="#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_NewVar()</span></code></a>.  This is normally called from the
<a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> handler specified in the object’s type.  The fields of
the object should not be accessed after this call as the memory is no
longer a valid Python object.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_InitModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_InitModule</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;*methods</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_InitModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Create a new module object based on a name and table of functions,
returning the new module object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Older versions of Python did not support <em>NULL</em> as the value for the
<em>methods</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.Py_InitModule3">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_InitModule3</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;*methods</em>, char<em>&nbsp;*doc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_InitModule3" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Create a new module object based on a name and table of functions,
returning the new module object.  If <em>doc</em> is non-<em>NULL</em>, it will be used
to define the docstring for the module.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Older versions of Python did not support <em>NULL</em> as the value for the
<em>methods</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.Py_InitModule4">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_InitModule4</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;*methods</em>, char<em>&nbsp;*doc</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, int<em>&nbsp;apiver</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_InitModule4" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Create a new module object based on a name and table of functions,
returning the new module object.  If <em>doc</em> is non-<em>NULL</em>, it will be used
to define the docstring for the module.  If <em>self</em> is non-<em>NULL</em>, it will
be passed to the functions of the module as their (otherwise <em>NULL</em>) first
parameter.  (This was added as an experimental feature, and there are no
known uses in the current version of Python.)  For <em>apiver</em>, the only value
which should be passed is defined by the constant
<code class="xref py py-const docutils literal notranslate"><span class="pre">PYTHON_API_VERSION</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Most uses of this function should probably be using the
<a class="reference internal" href="#c.Py_InitModule3" title="Py_InitModule3"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitModule3()</span></code></a> instead; only use this if you are sure you need
it.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Older versions of Python did not support <em>NULL</em> as the value for the
<em>methods</em> argument.</p>
</div>
</dd></dl>

<dl class="var">
<dt id="c._Py_NoneStruct">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> <code class="descname">_Py_NoneStruct</code><a class="headerlink" href="#c._Py_NoneStruct" title="Permalink to this definition">¶</a></dt>
<dd><p>Object which is visible in Python as <code class="docutils literal notranslate"><span class="pre">None</span></code>.  This should only be
accessed using the <code class="docutils literal notranslate"><span class="pre">Py_None</span></code> macro, which evaluates to a pointer to this
object.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="objimpl.html"
                        title="previous chapter">Object Implementation Support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="structures.html"
                        title="next chapter">Common Object Structures</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/allocation.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="structures.html" title="Common Object Structures"
             >next</a> |</li>
        <li class="right" >
          <a href="objimpl.html" title="Object Implementation Support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" >Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Q���2�2�html/c-api/arg.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Parsing arguments and building values &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="String conversion and formatting" href="conversion.html" />
    <link rel="prev" title="Data marshalling support" href="marshal.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/arg.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="conversion.html" title="String conversion and formatting"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="Data marshalling support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="parsing-arguments-and-building-values">
<span id="arg-parsing"></span><h1>Parsing arguments and building values<a class="headerlink" href="#parsing-arguments-and-building-values" title="Permalink to this headline">¶</a></h1>
<p>These functions are useful when creating your own extensions functions and
methods.  Additional information and examples are available in
<a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a>.</p>
<p>The first three of these functions described, <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>,
<a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a>, and <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_Parse()</span></code></a>, all use
<em>format strings</em> which are used to tell the function about the expected
arguments.  The format strings use the same syntax for each of these
functions.</p>
<p>A format string consists of zero or more “format units.”  A format unit
describes one Python object; it is usually a single character or a
parenthesized sequence of format units.  With a few exceptions, a format unit
that is not a parenthesized sequence normally corresponds to a single address
argument to these functions.  In the following description, the quoted form is
the format unit; the entry in (round) parentheses is the Python object type
that matches the format unit; and the entry in [square] brackets is the type
of the C variable(s) whose address should be passed.</p>
<p>These formats allow accessing an object as a contiguous chunk of memory.
You don’t have to provide raw storage for the returned unicode or bytes
area.  Also, you won’t have to release any memory yourself, except with the
<code class="docutils literal notranslate"><span class="pre">es</span></code>, <code class="docutils literal notranslate"><span class="pre">es#</span></code>, <code class="docutils literal notranslate"><span class="pre">et</span></code> and <code class="docutils literal notranslate"><span class="pre">et#</span></code> formats.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">s</span></code> (string or Unicode) [const char *]</dt>
<dd>Convert a Python string or Unicode object to a C pointer to a character
string.  You must not provide storage for the string itself; a pointer to
an existing string is stored into the character pointer variable whose
address you pass.  The C string is NUL-terminated.  The Python string must
not contain embedded NUL bytes; if it does, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is
raised. Unicode objects are converted to C strings using the default
encoding.  If this conversion fails, a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> is raised.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">s#</span></code> (string, Unicode or any read buffer compatible object) [const char *, int (or <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>, see below)]</dt>
<dd><p class="first">This variant on <code class="docutils literal notranslate"><span class="pre">s</span></code> stores into two C variables, the first one a pointer
to a character string, the second one its length.  In this case the Python
string may contain embedded null bytes.  Unicode objects pass back a
pointer to the default encoded string version of the object if such a
conversion is possible.  All other read-buffer compatible objects pass back
a reference to the raw internal data representation.</p>
<p class="last">Starting with Python 2.5 the type of the length argument can be controlled
by defining the macro <code class="xref c c-macro docutils literal notranslate"><span class="pre">PY_SSIZE_T_CLEAN</span></code> before including
<code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>.  If the macro is defined, length is a <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>
rather than an int.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">s*</span></code> (string, Unicode, or any buffer compatible object) [Py_buffer]</dt>
<dd><p class="first">Similar to <code class="docutils literal notranslate"><span class="pre">s#</span></code>, this code fills a Py_buffer structure provided by the
caller.  The buffer gets locked, so that the caller can subsequently use
the buffer even inside a <code class="docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code> block; the caller is
responsible for calling <code class="docutils literal notranslate"><span class="pre">PyBuffer_Release</span></code> with the structure after it
has processed the data.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">z</span></code> (string, Unicode  or <code class="docutils literal notranslate"><span class="pre">None</span></code>) [const char *]</dt>
<dd>Like <code class="docutils literal notranslate"><span class="pre">s</span></code>, but the Python object may also be <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case the C
pointer is set to <em>NULL</em>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">z#</span></code> (string, Unicode, <code class="docutils literal notranslate"><span class="pre">None</span></code> or any read buffer compatible object) [const char *, int]</dt>
<dd>This is to <code class="docutils literal notranslate"><span class="pre">s#</span></code> as <code class="docutils literal notranslate"><span class="pre">z</span></code> is to <code class="docutils literal notranslate"><span class="pre">s</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">z*</span></code> (string, Unicode, <code class="docutils literal notranslate"><span class="pre">None</span></code> or any buffer compatible object) [Py_buffer]</dt>
<dd><p class="first">This is to <code class="docutils literal notranslate"><span class="pre">s*</span></code> as <code class="docutils literal notranslate"><span class="pre">z</span></code> is to <code class="docutils literal notranslate"><span class="pre">s</span></code>.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">u</span></code> (Unicode) [Py_UNICODE *]</dt>
<dd>Convert a Python Unicode object to a C pointer to a NUL-terminated buffer
of 16-bit Unicode (UTF-16) data.  As with <code class="docutils literal notranslate"><span class="pre">s</span></code>, there is no need to
provide storage for the Unicode data buffer; a pointer to the existing
Unicode data is stored into the <a class="reference internal" href="unicode.html#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> pointer variable whose
address you pass.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">u#</span></code> (Unicode) [Py_UNICODE *, int]</dt>
<dd>This variant on <code class="docutils literal notranslate"><span class="pre">u</span></code> stores into two C variables, the first one a pointer
to a Unicode data buffer, the second one its length. Non-Unicode objects
are handled by interpreting their read-buffer pointer as pointer to a
<a class="reference internal" href="unicode.html#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> array.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">es</span></code> (string, Unicode or character buffer compatible object) [const char *encoding, char **buffer]</dt>
<dd><p class="first">This variant on <code class="docutils literal notranslate"><span class="pre">s</span></code> is used for encoding Unicode and objects convertible
to Unicode into a character buffer. It only works for encoded data without
embedded NUL bytes.</p>
<p>This format requires two arguments.  The first is only used as input, and
must be a <code class="xref c c-type docutils literal notranslate"><span class="pre">const</span> <span class="pre">char*</span></code> which points to the name of an encoding as
a NUL-terminated string, or <em>NULL</em>, in which case the default encoding is
used.  An exception is raised if the named encoding is not known to Python.
The second argument must be a <code class="xref c c-type docutils literal notranslate"><span class="pre">char**</span></code>; the value of the pointer
it references will be set to a buffer with the contents of the argument
text.  The text will be encoded in the encoding specified by the first
argument.</p>
<p class="last"><a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> will allocate a buffer of the needed size, copy
the encoded data into this buffer and adjust <em>*buffer</em> to reference the
newly allocated storage.  The caller is responsible for calling
<a class="reference internal" href="memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a> to free the allocated buffer after use.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">et</span></code> (string, Unicode or character buffer compatible object) [const char *encoding, char **buffer]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">es</span></code> except that 8-bit string objects are passed through without
recoding them.  Instead, the implementation assumes that the string object
uses the encoding passed in as parameter.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">es#</span></code> (string, Unicode or character buffer compatible object) [const char *encoding, char **buffer, int *buffer_length]</dt>
<dd><p class="first">This variant on <code class="docutils literal notranslate"><span class="pre">s#</span></code> is used for encoding Unicode and objects convertible
to Unicode into a character buffer.  Unlike the <code class="docutils literal notranslate"><span class="pre">es</span></code> format, this variant
allows input data which contains NUL characters.</p>
<p>It requires three arguments.  The first is only used as input, and must be
a <code class="xref c c-type docutils literal notranslate"><span class="pre">const</span> <span class="pre">char*</span></code> which points to the name of an encoding as a
NUL-terminated string, or <em>NULL</em>, in which case the default encoding is
used.  An exception is raised if the named encoding is not known to Python.
The second argument must be a <code class="xref c c-type docutils literal notranslate"><span class="pre">char**</span></code>; the value of the pointer
it references will be set to a buffer with the contents of the argument
text.  The text will be encoded in the encoding specified by the first
argument.  The third argument must be a pointer to an integer; the
referenced integer will be set to the number of bytes in the output buffer.</p>
<p>There are two modes of operation:</p>
<p>If <em>*buffer</em> points a <em>NULL</em> pointer, the function will allocate a buffer
of the needed size, copy the encoded data into this buffer and set
<em>*buffer</em> to reference the newly allocated storage.  The caller is
responsible for calling <a class="reference internal" href="memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a> to free the allocated buffer
after usage.</p>
<p>If <em>*buffer</em> points to a non-<em>NULL</em> pointer (an already allocated buffer),
<a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> will use this location as the buffer and
interpret the initial value of <em>*buffer_length</em> as the buffer size.  It
will then copy the encoded data into the buffer and NUL-terminate it.  If
the buffer is not large enough, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be set.
Note: starting from Python 3.6 a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be set.</p>
<p class="last">In both cases, <em>*buffer_length</em> is set to the length of the encoded data
without the trailing NUL byte.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">et#</span></code> (string, Unicode or character buffer compatible object) [const char *encoding, char **buffer, int *buffer_length]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">es#</span></code> except that string objects are passed through without
recoding them. Instead, the implementation assumes that the string object
uses the encoding passed in as parameter.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">b</span></code> (integer) [unsigned char]</dt>
<dd>Convert a nonnegative Python integer to an unsigned tiny int, stored in a C
<code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">B</span></code> (integer) [unsigned char]</dt>
<dd><p class="first">Convert a Python integer to a tiny int without overflow checking, stored in
a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code>.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">h</span></code> (integer) [short int]</dt>
<dd>Convert a Python integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">short</span> <span class="pre">int</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">H</span></code> (integer) [unsigned short int]</dt>
<dd><p class="first">Convert a Python integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">short</span> <span class="pre">int</span></code>, without
overflow checking.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">i</span></code> (integer) [int]</dt>
<dd>Convert a Python integer to a plain C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">I</span></code> (integer) [unsigned int]</dt>
<dd><p class="first">Convert a Python integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code>, without overflow
checking.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">l</span></code> (integer) [long int]</dt>
<dd>Convert a Python integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">k</span></code> (integer) [unsigned long]</dt>
<dd><p class="first">Convert a Python integer or long integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code>
without overflow checking.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">L</span></code> (integer) [PY_LONG_LONG]</dt>
<dd>Convert a Python integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>.  This format is only
available on platforms that support <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> (or <code class="xref c c-type docutils literal notranslate"><span class="pre">_int64</span></code>
on Windows).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">K</span></code> (integer) [unsigned PY_LONG_LONG]</dt>
<dd><p class="first">Convert a Python integer or long integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code>
without overflow checking.  This format is only available on platforms that
support <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code> (or <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">_int64</span></code> on
Windows).</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">n</span></code> (integer) [Py_ssize_t]</dt>
<dd><p class="first">Convert a Python integer or long integer to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">c</span></code> (string of length 1) [char]</dt>
<dd>Convert a Python character, represented as a string of length 1, to a C
<code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">f</span></code> (float) [float]</dt>
<dd>Convert a Python floating point number to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">float</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">d</span></code> (float) [double]</dt>
<dd>Convert a Python floating point number to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">D</span></code> (complex) [Py_complex]</dt>
<dd>Convert a Python complex number to a C <a class="reference internal" href="complex.html#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> structure.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">O</span></code> (object) [PyObject *]</dt>
<dd>Store a Python object (without any conversion) in a C object pointer.  The
C program thus receives the actual object that was passed.  The object’s
reference count is not increased.  The pointer stored is not <em>NULL</em>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">O!</span></code> (object) [<em>typeobject</em>, PyObject *]</dt>
<dd>Store a Python object in a C object pointer.  This is similar to <code class="docutils literal notranslate"><span class="pre">O</span></code>, but
takes two C arguments: the first is the address of a Python type object,
the second is the address of the C variable (of type <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>)
into which the object pointer is stored.  If the Python object does not
have the required type, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">O&amp;</span></code> (object) [<em>converter</em>, <em>anything</em>]</dt>
<dd><p class="first">Convert a Python object to a C variable through a <em>converter</em> function.
This takes two arguments: the first is a function, the second is the
address of a C variable (of arbitrary type), converted to <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code>.
The <em>converter</em> function in turn is called as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">status</span> <span class="o">=</span> <span class="n">converter</span><span class="p">(</span><span class="n">object</span><span class="p">,</span> <span class="n">address</span><span class="p">);</span>
</pre></div>
</div>
<p class="last">where <em>object</em> is the Python object to be converted and <em>address</em> is the
<code class="xref c c-type docutils literal notranslate"><span class="pre">void*</span></code> argument that was passed to the <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_Parse*()</span></code></a>
function.  The returned <em>status</em> should be <code class="docutils literal notranslate"><span class="pre">1</span></code> for a successful
conversion and <code class="docutils literal notranslate"><span class="pre">0</span></code> if the conversion has failed.  When the conversion
fails, the <em>converter</em> function should raise an exception and leave the
content of <em>address</em> unmodified.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">S</span></code> (string) [PyStringObject *]</dt>
<dd>Like <code class="docutils literal notranslate"><span class="pre">O</span></code> but requires that the Python object is a string object.  Raises
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the object is not a string object.  The C variable may
also be declared as <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">U</span></code> (Unicode string) [PyUnicodeObject *]</dt>
<dd>Like <code class="docutils literal notranslate"><span class="pre">O</span></code> but requires that the Python object is a Unicode object.  Raises
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the object is not a Unicode object.  The C variable may
also be declared as <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">t#</span></code> (read-only character buffer) [char *, int]</dt>
<dd>Like <code class="docutils literal notranslate"><span class="pre">s#</span></code>, but accepts any object which implements the read-only buffer
interface.  The <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code> variable is set to point to the first byte
of the buffer, and the <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> is set to the length of the buffer.
Only single-segment buffer objects are accepted; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised
for all others.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">w</span></code> (read-write character buffer) [char *]</dt>
<dd>Similar to <code class="docutils literal notranslate"><span class="pre">s</span></code>, but accepts any object which implements the read-write
buffer interface.  The caller must determine the length of the buffer by
other means, or use <code class="docutils literal notranslate"><span class="pre">w#</span></code> instead.  Only single-segment buffer objects are
accepted; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised for all others.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">w#</span></code> (read-write character buffer) [char *, Py_ssize_t]</dt>
<dd>Like <code class="docutils literal notranslate"><span class="pre">s#</span></code>, but accepts any object which implements the read-write buffer
interface.  The <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span> <span class="pre">*</span></code> variable is set to point to the first byte
of the buffer, and the <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> is set to the length of the
buffer.  Only single-segment buffer objects are accepted; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
is raised for all others.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">w*</span></code> (read-write byte-oriented buffer) [Py_buffer]</dt>
<dd><p class="first">This is to <code class="docutils literal notranslate"><span class="pre">w</span></code> what <code class="docutils literal notranslate"><span class="pre">s*</span></code> is to <code class="docutils literal notranslate"><span class="pre">s</span></code>.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(items)</span></code> (tuple) [<em>matching-items</em>]</dt>
<dd><p class="first">The object must be a Python sequence whose length is the number of format
units in <em>items</em>.  The C arguments must correspond to the individual format
units in <em>items</em>.  Format units for sequences may be nested.</p>
<div class="last admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Prior to Python version 1.5.2, this format specifier only accepted a
tuple containing the individual parameters, not an arbitrary sequence.
Code which previously caused <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to be raised here may now
proceed without an exception.  This is not expected to be a problem for
existing code.</p>
</div>
</dd>
</dl>
<p>It is possible to pass Python long integers where integers are requested;
however no proper range checking is done — the most significant bits are
silently truncated when the receiving field is too small to receive the value
(actually, the semantics are inherited from downcasts in C — your mileage
may vary).</p>
<p>A few other characters have a meaning in a format string.  These may not occur
inside nested parentheses.  They are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">|</span></code></dt>
<dd>Indicates that the remaining arguments in the Python argument list are
optional.  The C variables corresponding to optional arguments should be
initialized to their default value — when an optional argument is not
specified, <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> does not touch the contents of the
corresponding C variable(s).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">:</span></code></dt>
<dd>The list of format units ends here; the string after the colon is used as
the function name in error messages (the “associated value” of the
exception that <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> raises).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">;</span></code></dt>
<dd>The list of format units ends here; the string after the semicolon is used
as the error message <em>instead</em> of the default error message.  <code class="docutils literal notranslate"><span class="pre">:</span></code> and
<code class="docutils literal notranslate"><span class="pre">;</span></code> mutually exclude each other.</dd>
</dl>
<p>Note that any Python object references which are provided to the caller are
<em>borrowed</em> references; do not decrement their reference count!</p>
<p>Additional arguments passed to these functions must be addresses of variables
whose type is determined by the format string; these are used to store values
from the input tuple.  There are a few cases, as described in the list of
format units above, where these parameters are used as input values; they
should match what is specified for the corresponding format unit in that case.</p>
<p>For the conversion to succeed, the <em>arg</em> object must match the format and the
format must be exhausted.  On success, the <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_Parse*()</span></code></a> functions
return true, otherwise they return false and raise an appropriate exception.
When the <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_Parse*()</span></code></a> functions fail due to conversion failure in
one of the format units, the variables at the addresses corresponding to that
and the following format units are left untouched.</p>
<dl class="function">
<dt id="c.PyArg_ParseTuple">
int <code class="descname">PyArg_ParseTuple</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_ParseTuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse the parameters of a function that takes only positional parameters
into local variables.  Returns true on success; on failure, it returns
false and raises the appropriate exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyArg_VaParse">
int <code class="descname">PyArg_VaParse</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, const char<em>&nbsp;*format</em>, va_list<em>&nbsp;vargs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_VaParse" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>, except that it accepts a va_list
rather than a variable number of arguments.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyArg_ParseTupleAndKeywords">
int <code class="descname">PyArg_ParseTupleAndKeywords</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*kw</em>, const char<em>&nbsp;*format</em>, char<em>&nbsp;*keywords[]</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_ParseTupleAndKeywords" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse the parameters of a function that takes both positional and keyword
parameters into local variables.  Returns true on success; on failure, it
returns false and raises the appropriate exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyArg_VaParseTupleAndKeywords">
int <code class="descname">PyArg_VaParseTupleAndKeywords</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*kw</em>, const char<em>&nbsp;*format</em>, char<em>&nbsp;*keywords[]</em>, va_list<em>&nbsp;vargs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_VaParseTupleAndKeywords" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to <a class="reference internal" href="#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a>, except that it accepts a
va_list rather than a variable number of arguments.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyArg_Parse">
int <code class="descname">PyArg_Parse</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_Parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Function used to deconstruct the argument lists of “old-style” functions
— these are functions which use the <a class="reference internal" href="structures.html#METH_OLDARGS" title="METH_OLDARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_OLDARGS</span></code></a> parameter
parsing method.  This is not recommended for use in parameter parsing in
new code, and most code in the standard interpreter has been modified to no
longer use this for that purpose.  It does remain a convenient way to
decompose other tuples, however, and may continue to be used for that
purpose.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyArg_UnpackTuple">
int <code class="descname">PyArg_UnpackTuple</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em>, const char<em>&nbsp;*name</em>, Py_ssize_t<em>&nbsp;min</em>, Py_ssize_t<em>&nbsp;max</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyArg_UnpackTuple" title="Permalink to this definition">¶</a></dt>
<dd><p>A simpler form of parameter retrieval which does not use a format string to
specify the types of the arguments.  Functions which use this method to
retrieve their parameters should be declared as <a class="reference internal" href="structures.html#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a> in
function or method tables.  The tuple containing the actual parameters
should be passed as <em>args</em>; it must actually be a tuple.  The length of the
tuple must be at least <em>min</em> and no more than <em>max</em>; <em>min</em> and <em>max</em> may be
equal.  Additional arguments must be passed to the function, each of which
should be a pointer to a <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> variable; these will be filled
in with the values from <em>args</em>; they will contain borrowed references.  The
variables which correspond to optional parameters not given by <em>args</em> will
not be filled in; these should be initialized by the caller. This function
returns true on success and false if <em>args</em> is not a tuple or contains the
wrong number of elements; an exception will be set if there was a failure.</p>
<p>This is an example of the use of this function, taken from the sources for
the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_weakref</span></code> helper module for weak references:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">weakref_ref</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">object</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">callback</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyArg_UnpackTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;ref&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">object</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">callback</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">PyWeakref_NewRef</span><span class="p">(</span><span class="n">object</span><span class="p">,</span> <span class="n">callback</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The call to <a class="reference internal" href="#c.PyArg_UnpackTuple" title="PyArg_UnpackTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_UnpackTuple()</span></code></a> in this example is entirely
equivalent to this call to <a class="reference internal" href="#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;O|O:ref&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">object</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">callback</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>min</em> and <em>max</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.Py_BuildValue">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_BuildValue</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.Py_BuildValue" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new value based on a format string similar to those accepted by
the <a class="reference internal" href="#c.PyArg_Parse" title="PyArg_Parse"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_Parse*()</span></code></a> family of functions and a sequence of values.
Returns the value or <em>NULL</em> in the case of an error; an exception will be
raised if <em>NULL</em> is returned.</p>
<p><a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> does not always build a tuple.  It builds a tuple
only if its format string contains two or more format units.  If the format
string is empty, it returns <code class="docutils literal notranslate"><span class="pre">None</span></code>; if it contains exactly one format
unit, it returns whatever object is described by that format unit.  To
force it to return a tuple of size <code class="docutils literal notranslate"><span class="pre">0</span></code> or one, parenthesize the format
string.</p>
<p>When memory buffers are passed as parameters to supply data to build
objects, as for the <code class="docutils literal notranslate"><span class="pre">s</span></code> and <code class="docutils literal notranslate"><span class="pre">s#</span></code> formats, the required data is copied.
Buffers provided by the caller are never referenced by the objects created
by <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>.  In other words, if your code invokes
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and passes the allocated memory to <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>,
your code is responsible for calling <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> for that memory once
<a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> returns.</p>
<p>In the following description, the quoted form is the format unit; the entry
in (round) parentheses is the Python object type that the format unit will
return; and the entry in [square] brackets is the type of the C value(s) to
be passed.</p>
<p>The characters space, tab, colon and comma are ignored in format strings
(but not within format units such as <code class="docutils literal notranslate"><span class="pre">s#</span></code>).  This can be used to make
long format strings a tad more readable.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">s</span></code> (string) [char *]</dt>
<dd>Convert a null-terminated C string to a Python object.  If the C string
pointer is <em>NULL</em>, <code class="docutils literal notranslate"><span class="pre">None</span></code> is used.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">s#</span></code> (string) [char *, int]</dt>
<dd>Convert a C string and its length to a Python object.  If the C string
pointer is <em>NULL</em>, the length is ignored and <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">z</span></code> (string or <code class="docutils literal notranslate"><span class="pre">None</span></code>) [char *]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">s</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">z#</span></code> (string or <code class="docutils literal notranslate"><span class="pre">None</span></code>) [char *, int]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">s#</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">u</span></code> (Unicode string) [Py_UNICODE *]</dt>
<dd>Convert a null-terminated buffer of Unicode (UCS-2 or UCS-4) data to a
Python Unicode object.  If the Unicode buffer pointer is <em>NULL</em>,
<code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">u#</span></code> (Unicode string) [Py_UNICODE *, int]</dt>
<dd>Convert a Unicode (UCS-2 or UCS-4) data buffer and its length to a
Python Unicode object.   If the Unicode buffer pointer is <em>NULL</em>, the
length is ignored and <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">i</span></code> (integer) [int]</dt>
<dd>Convert a plain C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">b</span></code> (integer) [char]</dt>
<dd>Convert a plain C <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">h</span></code> (integer) [short int]</dt>
<dd>Convert a plain C <code class="xref c c-type docutils literal notranslate"><span class="pre">short</span> <span class="pre">int</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">l</span></code> (integer) [long int]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">B</span></code> (integer) [unsigned char]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">H</span></code> (integer) [unsigned short int]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">short</span> <span class="pre">int</span></code> to a Python integer object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">I</span></code> (integer/long) [unsigned int]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> to a Python integer object or a Python
long integer object, if it is larger than <code class="docutils literal notranslate"><span class="pre">sys.maxint</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">k</span></code> (integer/long) [unsigned long]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code> to a Python integer object or a
Python long integer object, if it is larger than <code class="docutils literal notranslate"><span class="pre">sys.maxint</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">L</span></code> (long) [PY_LONG_LONG]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> to a Python long integer object. Only
available on platforms that support <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">K</span></code> (long) [unsigned PY_LONG_LONG]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code> to a Python long integer object.
Only available on platforms that support <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">n</span></code> (int) [Py_ssize_t]</dt>
<dd><p class="first">Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> to a Python integer or long integer.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">c</span></code> (string of length 1) [char]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> representing a character to a Python string of
length 1.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">d</span></code> (float) [double]</dt>
<dd>Convert a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> to a Python floating point number.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">f</span></code> (float) [float]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">d</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">D</span></code> (complex) [Py_complex *]</dt>
<dd>Convert a C <a class="reference internal" href="complex.html#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> structure to a Python complex number.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">O</span></code> (object) [PyObject *]</dt>
<dd>Pass a Python object untouched (except for its reference count, which is
incremented by one).  If the object passed in is a <em>NULL</em> pointer, it is
assumed that this was caused because the call producing the argument
found an error and set an exception. Therefore, <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>
will return <em>NULL</em> but won’t raise an exception.  If no exception has
been raised yet, <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> is set.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">S</span></code> (object) [PyObject *]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">O</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">N</span></code> (object) [PyObject *]</dt>
<dd>Same as <code class="docutils literal notranslate"><span class="pre">O</span></code>, except it doesn’t increment the reference count on the
object.  Useful when the object is created by a call to an object
constructor in the argument list.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">O&amp;</span></code> (object) [<em>converter</em>, <em>anything</em>]</dt>
<dd>Convert <em>anything</em> to a Python object through a <em>converter</em> function.
The function is called with <em>anything</em> (which should be compatible with
<code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code>) as its argument and should return a “new” Python
object, or <em>NULL</em> if an error occurred.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(items)</span></code> (tuple) [<em>matching-items</em>]</dt>
<dd>Convert a sequence of C values to a Python tuple with the same number of
items.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">[items]</span></code> (list) [<em>matching-items</em>]</dt>
<dd>Convert a sequence of C values to a Python list with the same number of
items.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">{items}</span></code> (dictionary) [<em>matching-items</em>]</dt>
<dd>Convert a sequence of C values to a Python dictionary.  Each pair of
consecutive C values adds one item to the dictionary, serving as key and
value, respectively.</dd>
</dl>
<p>If there is an error in the format string, the <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> exception
is set and <em>NULL</em> returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_VaBuildValue">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_VaBuildValue</code><span class="sig-paren">(</span>const char<em>&nbsp;*format</em>, va_list<em>&nbsp;vargs</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_VaBuildValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to <a class="reference internal" href="#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, except that it accepts a va_list
rather than a variable number of arguments.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="marshal.html"
                        title="previous chapter">Data marshalling support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="conversion.html"
                        title="next chapter">String conversion and formatting</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/arg.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="conversion.html" title="String conversion and formatting"
             >next</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="Data marshalling support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Tn�8)')'html/c-api/bool.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Boolean Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Long Integer Objects" href="long.html" />
    <link rel="prev" title="Plain Integer Objects" href="int.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/bool.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="long.html" title="Long Integer Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="int.html" title="Plain Integer Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="boolean-objects">
<span id="boolobjects"></span><h1>Boolean Objects<a class="headerlink" href="#boolean-objects" title="Permalink to this headline">¶</a></h1>
<p>Booleans in Python are implemented as a subclass of integers.  There are only
two booleans, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_False</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_True</span></code>.  As such, the normal
creation and deletion functions don’t apply to booleans.  The following macros
are available, however.</p>
<dl class="function">
<dt id="c.PyBool_Check">
int <code class="descname">PyBool_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBool_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>o</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyBool_Type</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="var">
<dt id="c.Py_False">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_False</code><a class="headerlink" href="#c.Py_False" title="Permalink to this definition">¶</a></dt>
<dd><p>The Python <code class="docutils literal notranslate"><span class="pre">False</span></code> object.  This object has no methods.  It needs to be
treated just like any other object with respect to reference counts.</p>
</dd></dl>

<dl class="var">
<dt id="c.Py_True">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">Py_True</code><a class="headerlink" href="#c.Py_True" title="Permalink to this definition">¶</a></dt>
<dd><p>The Python <code class="docutils literal notranslate"><span class="pre">True</span></code> object.  This object has no methods.  It needs to be treated
just like any other object with respect to reference counts.</p>
</dd></dl>

<dl class="macro">
<dt id="c.Py_RETURN_FALSE">
<code class="descname">Py_RETURN_FALSE</code><a class="headerlink" href="#c.Py_RETURN_FALSE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_False</span></code> from a function, properly incrementing its reference
count.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="macro">
<dt id="c.Py_RETURN_TRUE">
<code class="descname">Py_RETURN_TRUE</code><a class="headerlink" href="#c.Py_RETURN_TRUE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_True</span></code> from a function, properly incrementing its reference
count.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyBool_FromLong">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBool_FromLong</code><span class="sig-paren">(</span>long<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBool_FromLong" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new reference to <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_True</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_False</span></code> depending on the
truth value of <em>v</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="int.html"
                        title="previous chapter">Plain Integer Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="long.html"
                        title="next chapter">Long Integer Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/bool.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="long.html" title="Long Integer Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="int.html" title="Plain Integer Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\y���g�g�html/c-api/buffer.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Buffers and Memoryview Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Tuple Objects" href="tuple.html" />
    <link rel="prev" title="Unicode Objects and Codecs" href="unicode.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/buffer.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tuple.html" title="Tuple Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode Objects and Codecs"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="buffers-and-memoryview-objects">
<span id="bufferobjects"></span><h1>Buffers and Memoryview Objects<a class="headerlink" href="#buffers-and-memoryview-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Python objects implemented in C can export a group of functions called the
“buffer interface.”  These functions can be used by an object to expose its
data in a raw, byte-oriented format. Clients of the object can use the buffer
interface to access the object data directly, without needing to copy it
first.</p>
<p>Two examples of objects that support the buffer interface are strings and
arrays. The string object exposes the character contents in the buffer
interface’s byte-oriented form. An array can only expose its contents via the
old-style buffer interface. This limitation does not apply to Python 3,
where <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> objects can be constructed from arrays, too.
Array elements may be multi-byte values.</p>
<p>An example user of the buffer interface is the file object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>
method. Any object that can export a series of bytes through the buffer
interface can be written to a file. There are a number of format codes to
<a class="reference internal" href="arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> that operate against an object’s buffer interface,
returning data from the target object.</p>
<p>Starting from version 1.6, Python has been providing Python-level buffer
objects and a C-level buffer API so that any built-in or used-defined type can
expose its characteristics. Both, however, have been deprecated because of
various shortcomings, and have been officially removed in Python 3 in favour
of a new C-level buffer API and a new Python-level object named
<a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.</p>
<p>The new buffer API has been backported to Python 2.6, and the
<a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object has been backported to Python 2.7. It is strongly
advised to use them rather than the old APIs, unless you are blocked from
doing so for compatibility reasons.</p>
<div class="section" id="the-new-style-py-buffer-struct">
<h2>The new-style Py_buffer struct<a class="headerlink" href="#the-new-style-py-buffer-struct" title="Permalink to this headline">¶</a></h2>
<dl class="type">
<dt id="c.Py_buffer">
<code class="descname">Py_buffer</code><a class="headerlink" href="#c.Py_buffer" title="Permalink to this definition">¶</a></dt>
<dd><dl class="member">
<dt id="c.Py_buffer.buf">
void *<code class="descname">buf</code><a class="headerlink" href="#c.Py_buffer.buf" title="Permalink to this definition">¶</a></dt>
<dd><p>A pointer to the start of the memory for the object.</p>
</dd></dl>

<dl class="member">
<dt>
Py_ssize_t <code class="descname">len</code></dt>
<dd><p>The total length of the memory in bytes.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.readonly">
int <code class="descname">readonly</code><a class="headerlink" href="#c.Py_buffer.readonly" title="Permalink to this definition">¶</a></dt>
<dd><p>An indicator of whether the buffer is read only.</p>
</dd></dl>

<dl class="member">
<dt>
const char *<code class="descname">format</code></dt>
<dd><p>A <em>NULL</em> terminated string in <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module style syntax giving
the contents of the elements available through the buffer.  If this is
<em>NULL</em>, <code class="docutils literal notranslate"><span class="pre">&quot;B&quot;</span></code> (unsigned bytes) is assumed.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.ndim">
int <code class="descname">ndim</code><a class="headerlink" href="#c.Py_buffer.ndim" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of dimensions the memory represents as a multi-dimensional
array.  If it is <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="xref c c-data docutils literal notranslate"><span class="pre">strides</span></code> and <code class="xref c c-data docutils literal notranslate"><span class="pre">suboffsets</span></code> must be
<em>NULL</em>.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.shape">
Py_ssize_t *<code class="descname">shape</code><a class="headerlink" href="#c.Py_buffer.shape" title="Permalink to this definition">¶</a></dt>
<dd><p>An array of <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>s the length of <code class="xref c c-data docutils literal notranslate"><span class="pre">ndim</span></code> giving the
shape of the memory as a multi-dimensional array.  Note that
<code class="docutils literal notranslate"><span class="pre">((*shape)[0]</span> <span class="pre">*</span> <span class="pre">...</span> <span class="pre">*</span> <span class="pre">(*shape)[ndims-1])*itemsize</span></code> should be equal to
<code class="xref c c-data docutils literal notranslate"><span class="pre">len</span></code>.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.strides">
Py_ssize_t *<code class="descname">strides</code><a class="headerlink" href="#c.Py_buffer.strides" title="Permalink to this definition">¶</a></dt>
<dd><p>An array of <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>s the length of <code class="xref c c-data docutils literal notranslate"><span class="pre">ndim</span></code> giving the
number of bytes to skip to get to a new element in each dimension.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.suboffsets">
Py_ssize_t *<code class="descname">suboffsets</code><a class="headerlink" href="#c.Py_buffer.suboffsets" title="Permalink to this definition">¶</a></dt>
<dd><p>An array of <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>s the length of <code class="xref c c-data docutils literal notranslate"><span class="pre">ndim</span></code>.  If these
suboffset numbers are greater than or equal to 0, then the value stored
along the indicated dimension is a pointer and the suboffset value
dictates how many bytes to add to the pointer after de-referencing. A
suboffset value that it negative indicates that no de-referencing should
occur (striding in a contiguous memory block).</p>
<p>If all suboffsets are negative (i.e. no de-referencing is needed), then
this field must be NULL (the default value).</p>
<p>Here is a function that returns a pointer to the element in an N-D array
pointed to by an N-dimensional index when there are both non-NULL strides
and suboffsets:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="o">*</span><span class="nf">get_item_pointer</span><span class="p">(</span><span class="kt">int</span> <span class="n">ndim</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">buf</span><span class="p">,</span> <span class="n">Py_ssize_t</span> <span class="o">*</span><span class="n">strides</span><span class="p">,</span>
    <span class="n">Py_ssize_t</span> <span class="o">*</span><span class="n">suboffsets</span><span class="p">,</span> <span class="n">Py_ssize_t</span> <span class="o">*</span><span class="n">indices</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">pointer</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span><span class="o">*</span><span class="p">)</span><span class="n">buf</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">;</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">ndim</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">pointer</span> <span class="o">+=</span> <span class="n">strides</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">*</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">suboffsets</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">&gt;=</span><span class="mi">0</span> <span class="p">)</span> <span class="p">{</span>
            <span class="n">pointer</span> <span class="o">=</span> <span class="o">*</span><span class="p">((</span><span class="kt">char</span><span class="o">**</span><span class="p">)</span><span class="n">pointer</span><span class="p">)</span> <span class="o">+</span> <span class="n">suboffsets</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>
        <span class="p">}</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="p">(</span><span class="kt">void</span><span class="o">*</span><span class="p">)</span><span class="n">pointer</span><span class="p">;</span>
 <span class="p">}</span>
</pre></div>
</div>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.itemsize">
Py_ssize_t <code class="descname">itemsize</code><a class="headerlink" href="#c.Py_buffer.itemsize" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a storage for the itemsize (in bytes) of each element of the
shared memory. It is technically un-necessary as it can be obtained
using <a class="reference internal" href="#c.PyBuffer_SizeFromFormat" title="PyBuffer_SizeFromFormat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_SizeFromFormat()</span></code></a>, however an exporter may know
this information without parsing the format string and it is necessary
to know the itemsize for proper interpretation of striding. Therefore,
storing it is more convenient and faster.</p>
</dd></dl>

<dl class="member">
<dt id="c.Py_buffer.internal">
void *<code class="descname">internal</code><a class="headerlink" href="#c.Py_buffer.internal" title="Permalink to this definition">¶</a></dt>
<dd><p>This is for use internally by the exporting object. For example, this
might be re-cast as an integer by the exporter and used to store flags
about whether or not the shape, strides, and suboffsets arrays must be
freed when the buffer is released. The consumer should never alter this
value.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="buffer-related-functions">
<h2>Buffer related functions<a class="headerlink" href="#buffer-related-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.PyObject_CheckBuffer">
int <code class="descname">PyObject_CheckBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_CheckBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>obj</em> supports the buffer interface otherwise <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GetBuffer">
int <code class="descname">PyObject_GetBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, <a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a><em>&nbsp;*view</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GetBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Export <em>obj</em> into a <a class="reference internal" href="#c.Py_buffer" title="Py_buffer"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_buffer</span></code></a>, <em>view</em>.  These arguments must
never be <em>NULL</em>.  The <em>flags</em> argument is a bit field indicating what
kind of buffer the caller is prepared to deal with and therefore what
kind of buffer the exporter is allowed to return.  The buffer interface
allows for complicated memory sharing possibilities, but some caller may
not be able to handle all the complexity but may want to see if the
exporter will let them take a simpler view to its memory.</p>
<p>Some exporters may not be able to share memory in every possible way and
may need to raise errors to signal to some consumers that something is
just not possible. These errors should be a <a class="reference internal" href="../library/exceptions.html#exceptions.BufferError" title="exceptions.BufferError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BufferError</span></code></a> unless
there is another error that is actually causing the problem. The
exporter can use flags information to simplify how much of the
<a class="reference internal" href="#c.Py_buffer" title="Py_buffer"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_buffer</span></code></a> structure is filled in with non-default values and/or
raise an error if the object can’t support a simpler view of its memory.</p>
<p><code class="docutils literal notranslate"><span class="pre">0</span></code> is returned on success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error.</p>
<p>The following table gives possible values to the <em>flags</em> arguments.</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="62%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_SIMPLE</span></code></td>
<td>This is the default flag state.  The returned
buffer may or may not have writable memory.  The
format of the data will be assumed to be unsigned
bytes.  This is a “stand-alone” flag constant. It
never needs to be ‘|’d to the others. The exporter
will raise an error if it cannot provide such a
contiguous buffer of bytes.</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_WRITABLE</span></code></td>
<td>The returned buffer must be writable.  If it is
not writable, then raise an error.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_STRIDES</span></code></td>
<td>This implies <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_ND</span></code>. The returned
buffer must provide strides information (i.e. the
strides cannot be NULL). This would be used when
the consumer can handle strided, discontiguous
arrays.  Handling strides automatically assumes
you can handle shape.  The exporter can raise an
error if a strided representation of the data is
not possible (i.e. without the suboffsets).</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_ND</span></code></td>
<td>The returned buffer must provide shape
information. The memory will be assumed C-style
contiguous (last dimension varies the
fastest). The exporter may raise an error if it
cannot provide this kind of contiguous buffer. If
this is not given then shape will be <em>NULL</em>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_C_CONTIGUOUS</span></code>
<code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_F_CONTIGUOUS</span></code>
<code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_ANY_CONTIGUOUS</span></code></td>
<td>These flags indicate that the contiguity returned
buffer must be respectively, C-contiguous (last
dimension varies the fastest), Fortran contiguous
(first dimension varies the fastest) or either
one.  All of these flags imply
<code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_STRIDES</span></code> and guarantee that the
strides buffer info structure will be filled in
correctly.</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_INDIRECT</span></code></td>
<td>This flag indicates the returned buffer must have
suboffsets information (which can be NULL if no
suboffsets are needed).  This can be used when
the consumer can handle indirect array
referencing implied by these suboffsets. This
implies <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_STRIDES</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_FORMAT</span></code></td>
<td>The returned buffer must have true format
information if this flag is provided. This would
be used when the consumer is going to be checking
for what ‘kind’ of data is actually stored. An
exporter should always be able to provide this
information if requested. If format is not
explicitly requested then the format must be
returned as <em>NULL</em> (which means <code class="docutils literal notranslate"><span class="pre">'B'</span></code>, or
unsigned bytes)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_STRIDED</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_STRIDES</span> <span class="pre">|</span>
<span class="pre">PyBUF_WRITABLE)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_STRIDED_RO</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_STRIDES)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_RECORDS</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_STRIDES</span> <span class="pre">|</span>
<span class="pre">PyBUF_FORMAT</span> <span class="pre">|</span> <span class="pre">PyBUF_WRITABLE)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_RECORDS_RO</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_STRIDES</span> <span class="pre">|</span>
<span class="pre">PyBUF_FORMAT)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_FULL</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_INDIRECT</span> <span class="pre">|</span>
<span class="pre">PyBUF_FORMAT</span> <span class="pre">|</span> <span class="pre">PyBUF_WRITABLE)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_FULL_RO</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_INDIRECT</span> <span class="pre">|</span>
<span class="pre">PyBUF_FORMAT)</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_CONTIG</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_ND</span> <span class="pre">|</span>
<span class="pre">PyBUF_WRITABLE)</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyBUF_CONTIG_RO</span></code></td>
<td>This is equivalent to <code class="docutils literal notranslate"><span class="pre">(PyBUF_ND)</span></code>.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_Release">
void <code class="descname">PyBuffer_Release</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a><em>&nbsp;*view</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_Release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the buffer <em>view</em>.  This should be called when the buffer
is no longer being used as it may free memory from it.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_SizeFromFormat">
Py_ssize_t <code class="descname">PyBuffer_SizeFromFormat</code><span class="sig-paren">(</span>const char<em>&nbsp;*</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_SizeFromFormat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the implied <a class="reference internal" href="#c.Py_buffer.itemsize" title="Py_buffer.itemsize"><code class="xref c c-data docutils literal notranslate"><span class="pre">itemsize</span></code></a> from the struct-stype
<code class="xref c c-data docutils literal notranslate"><span class="pre">format</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_IsContiguous">
int <code class="descname">PyBuffer_IsContiguous</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a><em>&nbsp;*view</em>, char<em>&nbsp;fortran</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_IsContiguous" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the memory defined by the <em>view</em> is C-style (<em>fortran</em> is
<code class="docutils literal notranslate"><span class="pre">'C'</span></code>) or Fortran-style (<em>fortran</em> is <code class="docutils literal notranslate"><span class="pre">'F'</span></code>) contiguous or either one
(<em>fortran</em> is <code class="docutils literal notranslate"><span class="pre">'A'</span></code>).  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FillContiguousStrides">
void <code class="descname">PyBuffer_FillContiguousStrides</code><span class="sig-paren">(</span>int<em>&nbsp;ndims</em>, Py_ssize_t<em>&nbsp;*shape</em>, Py_ssize_t<em>&nbsp;*strides</em>, int<em>&nbsp;itemsize</em>, char<em>&nbsp;fortran</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FillContiguousStrides" title="Permalink to this definition">¶</a></dt>
<dd><p>Fill the <em>strides</em> array with byte-strides of a contiguous (C-style if
<em>fortran</em> is <code class="docutils literal notranslate"><span class="pre">'C'</span></code> or Fortran-style if <em>fortran</em> is <code class="docutils literal notranslate"><span class="pre">'F'</span></code>) array of the
given shape with the given number of bytes per element.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FillInfo">
int <code class="descname">PyBuffer_FillInfo</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a><em>&nbsp;*view</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, void<em>&nbsp;*buf</em>, Py_ssize_t<em>&nbsp;len</em>, int<em>&nbsp;readonly</em>, int<em>&nbsp;infoflags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FillInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Fill in a buffer-info structure, <em>view</em>, correctly for an exporter that can
only share a contiguous chunk of memory of “unsigned bytes” of the given
length.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> (with raising an error) on error.</p>
</dd></dl>

</div>
<div class="section" id="memoryview-objects">
<h2>MemoryView objects<a class="headerlink" href="#memoryview-objects" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>A <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object exposes the new C level buffer interface as a
Python object which can then be passed around like any other object.</p>
<dl class="function">
<dt id="c.PyMemoryView_FromObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">PyMemoryView_FromObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMemoryView_FromObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a memoryview object from an object that defines the new buffer
interface.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMemoryView_FromBuffer">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">PyMemoryView_FromBuffer</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a><em>&nbsp;*view</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMemoryView_FromBuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a memoryview object wrapping the given buffer-info structure <em>view</em>.
The memoryview object then owns the buffer, which means you shouldn’t
try to release it yourself: it will be released on deallocation of the
memoryview object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMemoryView_GetContiguous">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a> *<code class="descname">PyMemoryView_GetContiguous</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, int<em>&nbsp;buffertype</em>, char<em>&nbsp;order</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMemoryView_GetContiguous" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a memoryview object to a contiguous chunk of memory (in either
‘C’ or ‘F’ortran <em>order</em>) from an object that defines the buffer
interface. If memory is contiguous, the memoryview object points to the
original memory. Otherwise copy is made and the memoryview points to a
new bytes object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMemoryView_Check">
int <code class="descname">PyMemoryView_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMemoryView_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>obj</em> is a memoryview object.  It is not
currently allowed to create subclasses of <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyMemoryView_GET_BUFFER">
<a class="reference internal" href="#c.Py_buffer" title="Py_buffer">Py_buffer</a> *<code class="descname">PyMemoryView_GET_BUFFER</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyMemoryView_GET_BUFFER" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pointer to the buffer-info structure wrapped by the given
object.  The object <strong>must</strong> be a memoryview instance; this macro doesn’t
check its type, you must do it yourself or you will risk crashes.</p>
</dd></dl>

</div>
<div class="section" id="old-style-buffer-objects">
<h2>Old-style buffer objects<a class="headerlink" href="#old-style-buffer-objects" title="Permalink to this headline">¶</a></h2>
<p id="index-1">More information on the old buffer interface is provided in the section
<a class="reference internal" href="typeobj.html#buffer-structs"><span class="std std-ref">Buffer Object Structures</span></a>, under the description for <a class="reference internal" href="typeobj.html#c.PyBufferProcs" title="PyBufferProcs"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBufferProcs</span></code></a>.</p>
<p>A “buffer object” is defined in the <code class="file docutils literal notranslate"><span class="pre">bufferobject.h</span></code> header (included by
<code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>). These objects look very similar to string objects at the
Python programming level: they support slicing, indexing, concatenation, and
some other standard string operations. However, their data can come from one
of two sources: from a block of memory, or from another object which exports
the buffer interface.</p>
<p>Buffer objects are useful as a way to expose the data from another object’s
buffer interface to the Python programmer. They can also be used as a
zero-copy slicing mechanism. Using their ability to reference a block of
memory, it is possible to expose any data to the Python programmer quite
easily. The memory could be a large, constant array in a C extension, it could
be a raw block of memory for manipulation before passing to an operating
system library, or it could be used to pass around structured data in its
native, in-memory format.</p>
<dl class="type">
<dt id="c.PyBufferObject">
<code class="descname">PyBufferObject</code><a class="headerlink" href="#c.PyBufferObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a buffer object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyBuffer_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyBuffer_Type</code><a class="headerlink" href="#c.PyBuffer_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">The instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> which represents the Python buffer type;
it is the same object as <code class="docutils literal notranslate"><span class="pre">buffer</span></code> and  <code class="docutils literal notranslate"><span class="pre">types.BufferType</span></code> in the Python
layer. .</p>
</dd></dl>

<dl class="var">
<dt id="c.Py_END_OF_BUFFER">
int <code class="descname">Py_END_OF_BUFFER</code><a class="headerlink" href="#c.Py_END_OF_BUFFER" title="Permalink to this definition">¶</a></dt>
<dd><p>This constant may be passed as the <em>size</em> parameter to
<a class="reference internal" href="#c.PyBuffer_FromObject" title="PyBuffer_FromObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_FromObject()</span></code></a> or <a class="reference internal" href="#c.PyBuffer_FromReadWriteObject" title="PyBuffer_FromReadWriteObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_FromReadWriteObject()</span></code></a>.  It
indicates that the new <a class="reference internal" href="#c.PyBufferObject" title="PyBufferObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyBufferObject</span></code></a> should refer to <em>base</em>
object from the specified <em>offset</em> to the end of its exported buffer.
Using this enables the caller to avoid querying the <em>base</em> object for its
length.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_Check">
int <code class="descname">PyBuffer_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the argument has type <a class="reference internal" href="#c.PyBuffer_Type" title="PyBuffer_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyBuffer_Type</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FromObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBuffer_FromObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*base</em>, Py_ssize_t<em>&nbsp;offset</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FromObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new read-only buffer object.  This raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if
<em>base</em> doesn’t support the read-only buffer protocol or doesn’t provide
exactly one buffer segment, or it raises <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>offset</em> is
less than zero.  The buffer will hold a reference to the <em>base</em> object, and
the buffer’s contents will refer to the <em>base</em> object’s buffer interface,
starting as position <em>offset</em> and extending for <em>size</em> bytes. If <em>size</em> is
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_END_OF_BUFFER</span></code>, then the new buffer’s contents extend to the
length of the <em>base</em> object’s exported buffer data.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>offset</em> and <em>size</em>. This
might require changes in your code for properly supporting 64-bit
systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FromReadWriteObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBuffer_FromReadWriteObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*base</em>, Py_ssize_t<em>&nbsp;offset</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FromReadWriteObject" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new writable buffer object.  Parameters and exceptions are similar
to those for <a class="reference internal" href="#c.PyBuffer_FromObject" title="PyBuffer_FromObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_FromObject()</span></code></a>.  If the <em>base</em> object does not
export the writeable buffer protocol, then <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>offset</em> and <em>size</em>. This
might require changes in your code for properly supporting 64-bit
systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FromMemory">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBuffer_FromMemory</code><span class="sig-paren">(</span>void<em>&nbsp;*ptr</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FromMemory" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new read-only buffer object that reads from a specified location
in memory, with a specified size.  The caller is responsible for ensuring
that the memory buffer, passed in as <em>ptr</em>, is not deallocated while the
returned buffer object exists.  Raises <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>size</em> is less
than zero.  Note that <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_END_OF_BUFFER</span></code> may <em>not</em> be passed for the
<em>size</em> parameter; <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised in that case.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_FromReadWriteMemory">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBuffer_FromReadWriteMemory</code><span class="sig-paren">(</span>void<em>&nbsp;*ptr</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_FromReadWriteMemory" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Similar to <a class="reference internal" href="#c.PyBuffer_FromMemory" title="PyBuffer_FromMemory"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_FromMemory()</span></code></a>, but the returned buffer is
writable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyBuffer_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyBuffer_New</code><span class="sig-paren">(</span>Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyBuffer_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new writable buffer object that maintains its own memory buffer of
<em>size</em> bytes.  <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is returned if <em>size</em> is not zero or
positive.  Note that the memory buffer (as returned by
<a class="reference internal" href="objbuffer.html#c.PyObject_AsWriteBuffer" title="PyObject_AsWriteBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_AsWriteBuffer()</span></code></a>) is not specifically aligned.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Buffers and Memoryview Objects</a><ul>
<li><a class="reference internal" href="#the-new-style-py-buffer-struct">The new-style Py_buffer struct</a></li>
<li><a class="reference internal" href="#buffer-related-functions">Buffer related functions</a></li>
<li><a class="reference internal" href="#memoryview-objects">MemoryView objects</a></li>
<li><a class="reference internal" href="#old-style-buffer-objects">Old-style buffer objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="unicode.html"
                        title="previous chapter">Unicode Objects and Codecs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tuple.html"
                        title="next chapter">Tuple Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/buffer.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tuple.html" title="Tuple Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode Objects and Codecs"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��1�}7}7html/c-api/bytearray.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Byte Array Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="String/Bytes Objects" href="string.html" />
    <link rel="prev" title="Complex Number Objects" href="complex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/bytearray.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="string.html" title="String/Bytes Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="complex.html" title="Complex Number Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="byte-array-objects">
<span id="bytearrayobjects"></span><h1>Byte Array Objects<a class="headerlink" href="#byte-array-objects" title="Permalink to this headline">¶</a></h1>
<div class="versionadded" id="index-0">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<dl class="type">
<dt id="c.PyByteArrayObject">
<code class="descname">PyByteArrayObject</code><a class="headerlink" href="#c.PyByteArrayObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python bytearray object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyByteArray_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyByteArray_Type</code><a class="headerlink" href="#c.PyByteArray_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python bytearray type;
it is the same object as <code class="docutils literal notranslate"><span class="pre">bytearray</span></code> in the Python layer.</p>
</dd></dl>

<div class="section" id="type-check-macros">
<h2>Type check macros<a class="headerlink" href="#type-check-macros" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.PyByteArray_Check">
int <code class="descname">PyByteArray_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a bytearray object or an instance of a
subtype of the bytearray type.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_CheckExact">
int <code class="descname">PyByteArray_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a bytearray object, but not an instance of a
subtype of the bytearray type.</p>
</dd></dl>

</div>
<div class="section" id="direct-api-functions">
<h2>Direct API functions<a class="headerlink" href="#direct-api-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.PyByteArray_FromObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyByteArray_FromObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_FromObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new bytearray object from any object, <em>o</em>, that implements the
buffer protocol.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_FromStringAndSize">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyByteArray_FromStringAndSize</code><span class="sig-paren">(</span>const char<em>&nbsp;*string</em>, Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_FromStringAndSize" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new bytearray object from <em>string</em> and its length, <em>len</em>.  On
failure, <em>NULL</em> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_Concat">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyByteArray_Concat</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*a</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*b</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_Concat" title="Permalink to this definition">¶</a></dt>
<dd><p>Concat bytearrays <em>a</em> and <em>b</em> and return a new bytearray with the result.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_Size">
Py_ssize_t <code class="descname">PyByteArray_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*bytearray</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_Size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of <em>bytearray</em> after checking for a <em>NULL</em> pointer.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_AsString">
char* <code class="descname">PyByteArray_AsString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*bytearray</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_AsString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the contents of <em>bytearray</em> as a char array after checking for a
<em>NULL</em> pointer.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_Resize">
int <code class="descname">PyByteArray_Resize</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*bytearray</em>, Py_ssize_t<em>&nbsp;len</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_Resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Resize the internal buffer of <em>bytearray</em> to <em>len</em>.</p>
</dd></dl>

</div>
<div class="section" id="macros">
<h2>Macros<a class="headerlink" href="#macros" title="Permalink to this headline">¶</a></h2>
<p>These macros trade safety for speed and they don’t check pointers.</p>
<dl class="function">
<dt id="c.PyByteArray_AS_STRING">
char* <code class="descname">PyByteArray_AS_STRING</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*bytearray</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_AS_STRING" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro version of <a class="reference internal" href="#c.PyByteArray_AsString" title="PyByteArray_AsString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_AsString()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyByteArray_GET_SIZE">
Py_ssize_t <code class="descname">PyByteArray_GET_SIZE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*bytearray</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyByteArray_GET_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Macro version of <a class="reference internal" href="#c.PyByteArray_Size" title="PyByteArray_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_Size()</span></code></a>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Byte Array Objects</a><ul>
<li><a class="reference internal" href="#type-check-macros">Type check macros</a></li>
<li><a class="reference internal" href="#direct-api-functions">Direct API functions</a></li>
<li><a class="reference internal" href="#macros">Macros</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="complex.html"
                        title="previous chapter">Complex Number Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="string.html"
                        title="next chapter">String/Bytes Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/bytearray.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="string.html" title="String/Bytes Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="complex.html" title="Complex Number Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��o�Q�Qhtml/c-api/capsule.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Capsules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="CObjects" href="cobject.html" />
    <link rel="prev" title="Weak Reference Objects" href="weakref.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/capsule.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cobject.html" title="CObjects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="Weak Reference Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="capsules">
<span id="id1"></span><h1>Capsules<a class="headerlink" href="#capsules" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Refer to <a class="reference internal" href="../extending/extending.html#using-capsules"><span class="std std-ref">Providing a C API for an Extension Module</span></a> for more information on using these objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<dl class="type">
<dt id="c.PyCapsule">
<code class="descname">PyCapsule</code><a class="headerlink" href="#c.PyCapsule" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents an opaque value, useful for C
extension modules who need to pass an opaque value (as a <code class="xref c c-type docutils literal notranslate"><span class="pre">void*</span></code>
pointer) through Python code to other C code.  It is often used to make a C
function pointer defined in one module available to other modules, so the
regular import mechanism can be used to access C APIs defined in dynamically
loaded modules.</p>
</dd></dl>

<dl class="type">
<dt id="c.PyCapsule_Destructor">
<code class="descname">PyCapsule_Destructor</code><a class="headerlink" href="#c.PyCapsule_Destructor" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of a destructor callback for a capsule.  Defined as:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="nf">void</span> <span class="p">(</span><span class="o">*</span><span class="n">PyCapsule_Destructor</span><span class="p">)(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">);</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#c.PyCapsule_New" title="PyCapsule_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_New()</span></code></a> for the semantics of PyCapsule_Destructor
callbacks.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_CheckExact">
int <code class="descname">PyCapsule_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyCapsule" title="PyCapsule"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCapsule</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCapsule_New</code><span class="sig-paren">(</span>void<em>&nbsp;*pointer</em>, const char<em>&nbsp;*name</em>, <a class="reference internal" href="#c.PyCapsule_Destructor" title="PyCapsule_Destructor">PyCapsule_Destructor</a><em>&nbsp;destructor</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a <a class="reference internal" href="#c.PyCapsule" title="PyCapsule"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCapsule</span></code></a> encapsulating the <em>pointer</em>.  The <em>pointer</em>
argument may not be <em>NULL</em>.</p>
<p>On failure, set an exception and return <em>NULL</em>.</p>
<p>The <em>name</em> string may either be <em>NULL</em> or a pointer to a valid C string.  If
non-<em>NULL</em>, this string must outlive the capsule.  (Though it is permitted to
free it inside the <em>destructor</em>.)</p>
<p>If the <em>destructor</em> argument is not <em>NULL</em>, it will be called with the
capsule as its argument when it is destroyed.</p>
<p>If this capsule will be stored as an attribute of a module, the <em>name</em> should
be specified as <code class="docutils literal notranslate"><span class="pre">modulename.attributename</span></code>.  This will enable other modules
to import the capsule using <a class="reference internal" href="#c.PyCapsule_Import" title="PyCapsule_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_Import()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_GetPointer">
void* <code class="descname">PyCapsule_GetPointer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_GetPointer" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the <em>pointer</em> stored in the capsule.  On failure, set an exception
and return <em>NULL</em>.</p>
<p>The <em>name</em> parameter must compare exactly to the name stored in the capsule.
If the name stored in the capsule is <em>NULL</em>, the <em>name</em> passed in must also
be <em>NULL</em>.  Python uses the C function <code class="xref c c-func docutils literal notranslate"><span class="pre">strcmp()</span></code> to compare capsule
names.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_GetDestructor">
<a class="reference internal" href="#c.PyCapsule_Destructor" title="PyCapsule_Destructor">PyCapsule_Destructor</a> <code class="descname">PyCapsule_GetDestructor</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_GetDestructor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current destructor stored in the capsule.  On failure, set an
exception and return <em>NULL</em>.</p>
<p>It is legal for a capsule to have a <em>NULL</em> destructor.  This makes a <em>NULL</em>
return code somewhat ambiguous; use <a class="reference internal" href="#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> or
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to disambiguate.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_GetContext">
void* <code class="descname">PyCapsule_GetContext</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_GetContext" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current context stored in the capsule.  On failure, set an
exception and return <em>NULL</em>.</p>
<p>It is legal for a capsule to have a <em>NULL</em> context.  This makes a <em>NULL</em>
return code somewhat ambiguous; use <a class="reference internal" href="#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> or
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to disambiguate.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_GetName">
const char* <code class="descname">PyCapsule_GetName</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_GetName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current name stored in the capsule.  On failure, set an exception
and return <em>NULL</em>.</p>
<p>It is legal for a capsule to have a <em>NULL</em> name.  This makes a <em>NULL</em> return
code somewhat ambiguous; use <a class="reference internal" href="#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> or
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to disambiguate.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_Import">
void* <code class="descname">PyCapsule_Import</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em>, int<em>&nbsp;no_block</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_Import" title="Permalink to this definition">¶</a></dt>
<dd><p>Import a pointer to a C object from a capsule attribute in a module.  The
<em>name</em> parameter should specify the full name to the attribute, as in
<code class="docutils literal notranslate"><span class="pre">module.attribute</span></code>.  The <em>name</em> stored in the capsule must match this
string exactly.  If <em>no_block</em> is true, import the module without blocking
(using <a class="reference internal" href="import.html#c.PyImport_ImportModuleNoBlock" title="PyImport_ImportModuleNoBlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleNoBlock()</span></code></a>).  If <em>no_block</em> is false,
import the module conventionally (using <a class="reference internal" href="import.html#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>).</p>
<p>Return the capsule’s internal <em>pointer</em> on success.  On failure, set an
exception and return <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_IsValid">
int <code class="descname">PyCapsule_IsValid</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_IsValid" title="Permalink to this definition">¶</a></dt>
<dd><p>Determines whether or not <em>capsule</em> is a valid capsule.  A valid capsule is
non-<em>NULL</em>, passes <a class="reference internal" href="#c.PyCapsule_CheckExact" title="PyCapsule_CheckExact"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_CheckExact()</span></code></a>, has a non-<em>NULL</em> pointer
stored in it, and its internal name matches the <em>name</em> parameter.  (See
<a class="reference internal" href="#c.PyCapsule_GetPointer" title="PyCapsule_GetPointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_GetPointer()</span></code></a> for information on how capsule names are
compared.)</p>
<p>In other words, if <a class="reference internal" href="#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> returns a true value, calls to
any of the accessors (any function starting with <code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_Get()</span></code>) are
guaranteed to succeed.</p>
<p>Return a nonzero value if the object is valid and matches the name passed in.
Return <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.  This function will not fail.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_SetContext">
int <code class="descname">PyCapsule_SetContext</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, void<em>&nbsp;*context</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_SetContext" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the context pointer inside <em>capsule</em> to <em>context</em>.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  Return nonzero and set an exception on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_SetDestructor">
int <code class="descname">PyCapsule_SetDestructor</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, <a class="reference internal" href="#c.PyCapsule_Destructor" title="PyCapsule_Destructor">PyCapsule_Destructor</a><em>&nbsp;destructor</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_SetDestructor" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the destructor inside <em>capsule</em> to <em>destructor</em>.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  Return nonzero and set an exception on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_SetName">
int <code class="descname">PyCapsule_SetName</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_SetName" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the name inside <em>capsule</em> to <em>name</em>.  If non-<em>NULL</em>, the name must
outlive the capsule.  If the previous <em>name</em> stored in the capsule was not
<em>NULL</em>, no attempt is made to free it.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  Return nonzero and set an exception on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCapsule_SetPointer">
int <code class="descname">PyCapsule_SetPointer</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*capsule</em>, void<em>&nbsp;*pointer</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCapsule_SetPointer" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the void pointer inside <em>capsule</em> to <em>pointer</em>.  The pointer may not be
<em>NULL</em>.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success.  Return nonzero and set an exception on failure.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="weakref.html"
                        title="previous chapter">Weak Reference Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cobject.html"
                        title="next chapter">CObjects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/capsule.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cobject.html" title="CObjects"
             >next</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="Weak Reference Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���+�+html/c-api/cell.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Cell Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Generator Objects" href="gen.html" />
    <link rel="prev" title="CObjects" href="cobject.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/cell.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gen.html" title="Generator Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cobject.html" title="CObjects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="cell-objects">
<span id="id1"></span><h1>Cell Objects<a class="headerlink" href="#cell-objects" title="Permalink to this headline">¶</a></h1>
<p>“Cell” objects are used to implement variables referenced by multiple scopes.
For each such variable, a cell object is created to store the value; the local
variables of each stack frame that references the value contains a reference to
the cells from outer scopes which also use that variable.  When the value is
accessed, the value contained in the cell is used instead of the cell object
itself.  This de-referencing of the cell object requires support from the
generated byte-code; these are not automatically de-referenced when accessed.
Cell objects are not likely to be useful elsewhere.</p>
<dl class="type">
<dt id="c.PyCellObject">
<code class="descname">PyCellObject</code><a class="headerlink" href="#c.PyCellObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure used for cell objects.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyCell_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyCell_Type</code><a class="headerlink" href="#c.PyCell_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object corresponding to cell objects.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_Check">
int <code class="descname">PyCell_Check</code><span class="sig-paren">(</span>ob<span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is a cell object; <em>ob</em> must not be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCell_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create and return a new cell object containing the value <em>ob</em>. The parameter may
be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_Get">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCell_Get</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cell</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_Get" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return the contents of the cell <em>cell</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_GET">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCell_GET</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cell</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_GET" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the contents of the cell <em>cell</em>, but without checking that <em>cell</em> is
non-<em>NULL</em> and a cell object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_Set">
int <code class="descname">PyCell_Set</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cell</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_Set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the contents of the cell object <em>cell</em> to <em>value</em>.  This releases the
reference to any current content of the cell. <em>value</em> may be <em>NULL</em>.  <em>cell</em>
must be non-<em>NULL</em>; if it is not a cell object, <code class="docutils literal notranslate"><span class="pre">-1</span></code> will be returned.  On
success, <code class="docutils literal notranslate"><span class="pre">0</span></code> will be returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCell_SET">
void <code class="descname">PyCell_SET</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cell</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCell_SET" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the value of the cell object <em>cell</em> to <em>value</em>.  No reference counts are
adjusted, and no checks are made for safety; <em>cell</em> must be non-<em>NULL</em> and must
be a cell object.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="cobject.html"
                        title="previous chapter">CObjects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gen.html"
                        title="next chapter">Generator Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/cell.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gen.html" title="Generator Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="cobject.html" title="CObjects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\
�N&�,�,html/c-api/class.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Class and Instance Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Function Objects" href="function.html" />
    <link rel="prev" title="Dictionary Objects" href="dict.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/class.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="function.html" title="Function Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dict.html" title="Dictionary Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="class-and-instance-objects">
<span id="classobjects"></span><h1>Class and Instance Objects<a class="headerlink" href="#class-and-instance-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Note that the class objects described here represent old-style classes, which
will go away in Python 3. When creating new types for extension modules, you
will want to work with type objects (section <a class="reference internal" href="type.html#typeobjects"><span class="std std-ref">Type Objects</span></a>).</p>
<dl class="type">
<dt id="c.PyClassObject">
<code class="descname">PyClassObject</code><a class="headerlink" href="#c.PyClassObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure of the objects used to describe built-in classes.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyClass_Type">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyClass_Type</code><a class="headerlink" href="#c.PyClass_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This is the type object for class objects; it is the same object as
<code class="docutils literal notranslate"><span class="pre">types.ClassType</span></code> in the Python layer.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyClass_Check">
int <code class="descname">PyClass_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyClass_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object <em>o</em> is a class object, including instances of types
derived from the standard class object.  Return false in all other cases.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyClass_IsSubclass">
int <code class="descname">PyClass_IsSubclass</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*klass</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*base</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyClass_IsSubclass" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>klass</em> is a subclass of <em>base</em>. Return false in all other cases.</p>
</dd></dl>

<p id="index-2">There are very few functions specific to instance objects.</p>
<dl class="var">
<dt id="c.PyInstance_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyInstance_Type</code><a class="headerlink" href="#c.PyInstance_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>Type object for class instances.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInstance_Check">
int <code class="descname">PyInstance_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInstance_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>obj</em> is an instance.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInstance_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInstance_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*class</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*arg</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*kw</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInstance_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new instance of a specific class.  The parameters <em>arg</em> and <em>kw</em> are
used as the positional and keyword parameters to the object’s constructor.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyInstance_NewRaw">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyInstance_NewRaw</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*class</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*dict</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyInstance_NewRaw" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new instance of a specific class without calling its constructor.
<em>class</em> is the class of new object.  The <em>dict</em> parameter will be used as the
object’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>; if <em>NULL</em>, a new dictionary will be created for the
instance.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="dict.html"
                        title="previous chapter">Dictionary Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="function.html"
                        title="next chapter">Function Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/class.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="function.html" title="Function Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="dict.html" title="Dictionary Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\m��2/2/html/c-api/cobject.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>CObjects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Cell Objects" href="cell.html" />
    <link rel="prev" title="Capsules" href="capsule.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/cobject.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cell.html" title="Cell Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="capsule.html" title="Capsules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="cobjects">
<span id="id1"></span><h1>CObjects<a class="headerlink" href="#cobjects" title="Permalink to this headline">¶</a></h1>
<div class="admonition warning" id="index-0">
<p class="first admonition-title">Warning</p>
<p class="last">The CObject API is deprecated as of Python 2.7.  Please switch to the new
<a class="reference internal" href="capsule.html#capsules"><span class="std std-ref">Capsules</span></a> API.</p>
</div>
<dl class="type">
<dt id="c.PyCObject">
<code class="descname">PyCObject</code><a class="headerlink" href="#c.PyCObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents an opaque value, useful for C
extension modules who need to pass an opaque value (as a <code class="xref c c-type docutils literal notranslate"><span class="pre">void*</span></code>
pointer) through Python code to other C code.  It is often used to make a C
function pointer defined in one module available to other modules, so the
regular import mechanism can be used to access C APIs defined in dynamically
loaded modules.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_Check">
int <code class="descname">PyCObject_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_FromVoidPtr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCObject_FromVoidPtr</code><span class="sig-paren">(</span>void*<em>&nbsp;cobj</em>, void (<em>*destr</em>)(void *)<span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_FromVoidPtr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> from the <code class="docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> <em>cobj</em>.  The <em>destr</em> function
will be called when the object is reclaimed, unless it is <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_FromVoidPtrAndDesc">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCObject_FromVoidPtrAndDesc</code><span class="sig-paren">(</span>void*<em>&nbsp;cobj</em>, void*<em>&nbsp;desc</em>, void (<em>*destr</em>)(void *, void *)<span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_FromVoidPtrAndDesc" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> from the <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> <em>cobj</em>.  The <em>destr</em>
function will be called when the object is reclaimed. The <em>desc</em> argument can
be used to pass extra callback data for the destructor function.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_AsVoidPtr">
void* <code class="descname">PyCObject_AsVoidPtr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>*<em>&nbsp;self</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_AsVoidPtr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the object <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> that the <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> <em>self</em> was
created with.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_GetDesc">
void* <code class="descname">PyCObject_GetDesc</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>*<em>&nbsp;self</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_GetDesc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the description <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> that the <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> <em>self</em> was
created with.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCObject_SetVoidPtr">
int <code class="descname">PyCObject_SetVoidPtr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>*<em>&nbsp;self</em>, void*<em>&nbsp;cobj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCObject_SetVoidPtr" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the void pointer inside <em>self</em> to <em>cobj</em>. The <a class="reference internal" href="#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> must not
have an associated destructor. Return true on success, false on failure.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="capsule.html"
                        title="previous chapter">Capsules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cell.html"
                        title="next chapter">Cell Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/cobject.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cell.html" title="Cell Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="capsule.html" title="Capsules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����-�-html/c-api/code.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Code Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Initialization, Finalization, and Threads" href="init.html" />
    <link rel="prev" title="Set Objects" href="set.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/code.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="init.html" title="Initialization, Finalization, and Threads"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="set.html" title="Set Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <span class="target" id="codeobjects"></span><div class="section" id="code-objects">
<span id="index-0"></span><h1>Code Objects<a class="headerlink" href="#code-objects" title="Permalink to this headline">¶</a></h1>
<p>Code objects are a low-level detail of the CPython implementation.
Each one represents a chunk of executable code that hasn’t yet been
bound into a function.</p>
<dl class="type">
<dt id="c.PyCodeObject">
<code class="descname">PyCodeObject</code><a class="headerlink" href="#c.PyCodeObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure of the objects used to describe code objects.  The
fields of this type are subject to change at any time.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyCode_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyCode_Type</code><a class="headerlink" href="#c.PyCode_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> representing the Python
<a class="reference internal" href="../library/code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-class docutils literal notranslate"><span class="pre">code</span></code></a> type.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCode_Check">
int <code class="descname">PyCode_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*co</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCode_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>co</em> is a <a class="reference internal" href="../library/code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-class docutils literal notranslate"><span class="pre">code</span></code></a> object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCode_GetNumFree">
int <code class="descname">PyCode_GetNumFree</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*co</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCode_GetNumFree" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of free variables in <em>co</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCode_New">
<a class="reference internal" href="#c.PyCodeObject" title="PyCodeObject">PyCodeObject</a> *<code class="descname">PyCode_New</code><span class="sig-paren">(</span>int<em>&nbsp;argcount</em>, int<em>&nbsp;nlocals</em>, int<em>&nbsp;stacksize</em>, int<em>&nbsp;flags</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*code</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*consts</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*names</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*varnames</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*freevars</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*cellvars</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*filename</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*name</em>, int<em>&nbsp;firstlineno</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*lnotab</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCode_New" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new code object.  If you need a dummy code object to
create a frame, use <a class="reference internal" href="#c.PyCode_NewEmpty" title="PyCode_NewEmpty"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCode_NewEmpty()</span></code></a> instead.  Calling
<a class="reference internal" href="#c.PyCode_New" title="PyCode_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCode_New()</span></code></a> directly can bind you to a precise Python
version since the definition of the bytecode changes often.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCode_NewEmpty">
int <code class="descname">PyCode_NewEmpty</code><span class="sig-paren">(</span>const char<em>&nbsp;*filename</em>, const char<em>&nbsp;*funcname</em>, int<em>&nbsp;firstlineno</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCode_NewEmpty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new empty code object with the specified filename,
function name, and first line number.  It is illegal to
<a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> or <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> the resulting code object.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="set.html"
                        title="previous chapter">Set Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="init.html"
                        title="next chapter">Initialization, Finalization, and Threads</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/code.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="init.html" title="Initialization, Finalization, and Threads"
             >next</a> |</li>
        <li class="right" >
          <a href="set.html" title="Set Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�R<ISIShtml/c-api/codec.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Codec registry and support functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Abstract Objects Layer" href="abstract.html" />
    <link rel="prev" title="Reflection" href="reflection.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/codec.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="abstract.html" title="Abstract Objects Layer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="reflection.html" title="Reflection"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="codec-registry-and-support-functions">
<span id="codec-registry"></span><h1>Codec registry and support functions<a class="headerlink" href="#codec-registry-and-support-functions" title="Permalink to this headline">¶</a></h1>
<dl class="function">
<dt id="c.PyCodec_Register">
int <code class="descname">PyCodec_Register</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*search_function</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_Register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a new codec search function.</p>
<p>As side effect, this tries to load the <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings</span></code> package, if not yet
done, to make sure that it is always first in the list of search functions.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_KnownEncoding">
int <code class="descname">PyCodec_KnownEncoding</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_KnownEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> depending on whether there is a registered codec for
the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_Encode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_Encode</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*object</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_Encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Generic codec based encoding API.</p>
<p><em>object</em> is passed through the encoder function found for the given
<em>encoding</em> using the error handling method defined by <em>errors</em>.  <em>errors</em> may
be <em>NULL</em> to use the default method defined for the codec.  Raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> if no encoder can be found.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_Decode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_Decode</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*object</em>, const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_Decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Generic codec based decoding API.</p>
<p><em>object</em> is passed through the decoder function found for the given
<em>encoding</em> using the error handling method defined by <em>errors</em>.  <em>errors</em> may
be <em>NULL</em> to use the default method defined for the codec.  Raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> if no encoder can be found.</p>
</dd></dl>

<div class="section" id="codec-lookup-api">
<h2>Codec lookup API<a class="headerlink" href="#codec-lookup-api" title="Permalink to this headline">¶</a></h2>
<p>In the following functions, the <em>encoding</em> string is looked up converted to all
lower-case characters, which makes encodings looked up through this mechanism
effectively case-insensitive.  If no codec is found, a <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is set
and <em>NULL</em> returned.</p>
<dl class="function">
<dt id="c.PyCodec_Encoder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_Encoder</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_Encoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Get an encoder function for the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_Decoder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_Decoder</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_Decoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a decoder function for the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_IncrementalEncoder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_IncrementalEncoder</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_IncrementalEncoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Get an <a class="reference internal" href="../library/codecs.html#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> object for the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_IncrementalDecoder">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_IncrementalDecoder</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_IncrementalDecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Get an <a class="reference internal" href="../library/codecs.html#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> object for the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_StreamReader">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_StreamReader</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*stream</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_StreamReader" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a <a class="reference internal" href="../library/codecs.html#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> factory function for the given <em>encoding</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_StreamWriter">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_StreamWriter</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*stream</em>, const char<em>&nbsp;*errors</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_StreamWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a <a class="reference internal" href="../library/codecs.html#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> factory function for the given <em>encoding</em>.</p>
</dd></dl>

</div>
<div class="section" id="registry-api-for-unicode-encoding-error-handlers">
<h2>Registry API for Unicode encoding error handlers<a class="headerlink" href="#registry-api-for-unicode-encoding-error-handlers" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="c.PyCodec_RegisterError">
int <code class="descname">PyCodec_RegisterError</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*error</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_RegisterError" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the error handling callback function <em>error</em> under the given <em>name</em>.
This callback function will be called by a codec when it encounters
unencodable characters/undecodable bytes and <em>name</em> is specified as the error
parameter in the call to the encode/decode function.</p>
<p>The callback gets a single argument, an instance of
<a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> or
<a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeTranslateError" title="exceptions.UnicodeTranslateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeTranslateError</span></code></a> that holds information about the problematic
sequence of characters or bytes and their offset in the original string (see
<a class="reference internal" href="exceptions.html#unicodeexceptions"><span class="std std-ref">Unicode Exception Objects</span></a> for functions to extract this information).  The
callback must either raise the given exception, or return a two-item tuple
containing the replacement for the problematic sequence, and an integer
giving the offset in the original string at which encoding/decoding should be
resumed.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on error.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_LookupError">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_LookupError</code><span class="sig-paren">(</span>const char<em>&nbsp;*name</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_LookupError" title="Permalink to this definition">¶</a></dt>
<dd><p>Lookup the error handling callback function registered under <em>name</em>.  As a
special case <em>NULL</em> can be passed, in which case the error handling callback
for “strict” will be returned.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_StrictErrors">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_StrictErrors</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_StrictErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise <em>exc</em> as an exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_IgnoreErrors">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_IgnoreErrors</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_IgnoreErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Ignore the unicode error, skipping the faulty input.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_ReplaceErrors">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_ReplaceErrors</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_ReplaceErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace the unicode encode error with <code class="docutils literal notranslate"><span class="pre">?</span></code> or <code class="docutils literal notranslate"><span class="pre">U+FFFD</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_XMLCharRefReplaceErrors">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_XMLCharRefReplaceErrors</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_XMLCharRefReplaceErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace the unicode encode error with XML character references.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyCodec_BackslashReplaceErrors">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyCodec_BackslashReplaceErrors</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyCodec_BackslashReplaceErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace the unicode encode error with backslash escapes (<code class="docutils literal notranslate"><span class="pre">\x</span></code>, <code class="docutils literal notranslate"><span class="pre">\u</span></code> and
<code class="docutils literal notranslate"><span class="pre">\U</span></code>).</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Codec registry and support functions</a><ul>
<li><a class="reference internal" href="#codec-lookup-api">Codec lookup API</a></li>
<li><a class="reference internal" href="#registry-api-for-unicode-encoding-error-handlers">Registry API for Unicode encoding error handlers</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="reflection.html"
                        title="previous chapter">Reflection</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="abstract.html"
                        title="next chapter">Abstract Objects Layer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/codec.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="abstract.html" title="Abstract Objects Layer"
             >next</a> |</li>
        <li class="right" >
          <a href="reflection.html" title="Reflection"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��9�Q�Qhtml/c-api/complex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Complex Number Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Byte Array Objects" href="bytearray.html" />
    <link rel="prev" title="Floating Point Objects" href="float.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/complex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bytearray.html" title="Byte Array Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="float.html" title="Floating Point Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="complex-number-objects">
<span id="complexobjects"></span><h1>Complex Number Objects<a class="headerlink" href="#complex-number-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Python’s complex number objects are implemented as two distinct types when
viewed from the C API:  one is the Python object exposed to Python programs, and
the other is a C structure which represents the actual complex number value.
The API provides functions for working with both.</p>
<div class="section" id="complex-numbers-as-c-structures">
<h2>Complex Numbers as C Structures<a class="headerlink" href="#complex-numbers-as-c-structures" title="Permalink to this headline">¶</a></h2>
<p>Note that the functions which accept these structures as parameters and return
them as results do so <em>by value</em> rather than dereferencing them through
pointers.  This is consistent throughout the API.</p>
<dl class="type">
<dt id="c.Py_complex">
<code class="descname">Py_complex</code><a class="headerlink" href="#c.Py_complex" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure which corresponds to the value portion of a Python complex
number object.  Most of the functions for dealing with complex number objects
use structures of this type as input or output values, as appropriate.  It is
defined as:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
   <span class="kt">double</span> <span class="n">real</span><span class="p">;</span>
   <span class="kt">double</span> <span class="n">imag</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Py_complex</span><span class="p">;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_sum">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_sum</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;left</em>, <a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;right</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_sum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sum of two complex numbers, using the C <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a>
representation.</p>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_diff">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_diff</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;left</em>, <a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;right</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_diff" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the difference between two complex numbers, using the C
<a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> representation.</p>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_neg">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_neg</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;complex</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_neg" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the negation of the complex number <em>complex</em>, using the C
<a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> representation.</p>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_prod">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_prod</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;left</em>, <a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;right</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_prod" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the product of two complex numbers, using the C <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a>
representation.</p>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_quot">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_quot</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;dividend</em>, <a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;divisor</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_quot" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the quotient of two complex numbers, using the C <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a>
representation.</p>
<p>If <em>divisor</em> is null, this method returns zero and sets
<code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> to <code class="xref c c-data docutils literal notranslate"><span class="pre">EDOM</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c._Py_c_pow">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">_Py_c_pow</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;num</em>, <a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;exp</em><span class="sig-paren">)</span><a class="headerlink" href="#c._Py_c_pow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the exponentiation of <em>num</em> by <em>exp</em>, using the C <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a>
representation.</p>
<p>If <em>num</em> is null and <em>exp</em> is not a positive real number,
this method returns zero and sets <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> to <code class="xref c c-data docutils literal notranslate"><span class="pre">EDOM</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="complex-numbers-as-python-objects">
<h2>Complex Numbers as Python Objects<a class="headerlink" href="#complex-numbers-as-python-objects" title="Permalink to this headline">¶</a></h2>
<dl class="type">
<dt id="c.PyComplexObject">
<code class="descname">PyComplexObject</code><a class="headerlink" href="#c.PyComplexObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python complex number object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyComplex_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyComplex_Type</code><a class="headerlink" href="#c.PyComplex_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python complex number
type. It is the same object as <code class="docutils literal notranslate"><span class="pre">complex</span></code> and <code class="docutils literal notranslate"><span class="pre">types.ComplexType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_Check">
int <code class="descname">PyComplex_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyComplexObject" title="PyComplexObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyComplexObject</span></code></a> or a subtype of
<a class="reference internal" href="#c.PyComplexObject" title="PyComplexObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyComplexObject</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_CheckExact">
int <code class="descname">PyComplex_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyComplexObject" title="PyComplexObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyComplexObject</span></code></a>, but not a subtype of
<a class="reference internal" href="#c.PyComplexObject" title="PyComplexObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyComplexObject</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_FromCComplex">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyComplex_FromCComplex</code><span class="sig-paren">(</span><a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a><em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_FromCComplex" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new Python complex number object from a C <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> value.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_FromDoubles">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyComplex_FromDoubles</code><span class="sig-paren">(</span>double<em>&nbsp;real</em>, double<em>&nbsp;imag</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_FromDoubles" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new <a class="reference internal" href="#c.PyComplexObject" title="PyComplexObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyComplexObject</span></code></a> object from <em>real</em> and <em>imag</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_RealAsDouble">
double <code class="descname">PyComplex_RealAsDouble</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_RealAsDouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the real part of <em>op</em> as a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_ImagAsDouble">
double <code class="descname">PyComplex_ImagAsDouble</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_ImagAsDouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the imaginary part of <em>op</em> as a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyComplex_AsCComplex">
<a class="reference internal" href="#c.Py_complex" title="Py_complex">Py_complex</a> <code class="descname">PyComplex_AsCComplex</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyComplex_AsCComplex" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="#c.Py_complex" title="Py_complex"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_complex</span></code></a> value of the complex number <em>op</em>.
Upon failure, this method returns <code class="docutils literal notranslate"><span class="pre">-1.0</span></code> as a real value.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>If <em>op</em> is not a Python complex number object but has a <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a>
method, this method will first be called to convert <em>op</em> to a Python complex
number object.</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Complex Number Objects</a><ul>
<li><a class="reference internal" href="#complex-numbers-as-c-structures">Complex Numbers as C Structures</a></li>
<li><a class="reference internal" href="#complex-numbers-as-python-objects">Complex Numbers as Python Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="float.html"
                        title="previous chapter">Floating Point Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bytearray.html"
                        title="next chapter">Byte Array Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/complex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bytearray.html" title="Byte Array Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="float.html" title="Floating Point Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�;�=�=html/c-api/concrete.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Concrete Objects Layer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Type Objects" href="type.html" />
    <link rel="prev" title="Old Buffer Protocol" href="objbuffer.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/concrete.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="type.html" title="Type Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="objbuffer.html" title="Old Buffer Protocol"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="concrete-objects-layer">
<span id="concrete"></span><h1>Concrete Objects Layer<a class="headerlink" href="#concrete-objects-layer" title="Permalink to this headline">¶</a></h1>
<p>The functions in this chapter are specific to certain Python object types.
Passing them an object of the wrong type is not a good idea; if you receive an
object from a Python program and you are not sure that it has the right type,
you must perform a type check first; for example, to check that an object is a
dictionary, use <a class="reference internal" href="dict.html#c.PyDict_Check" title="PyDict_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_Check()</span></code></a>.  The chapter is structured like the
“family tree” of Python object types.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">While the functions described in this chapter carefully check the type of the
objects which are passed in, many of them do not check for <em>NULL</em> being passed
instead of a valid object.  Allowing <em>NULL</em> to be passed in can cause memory
access violations and immediate termination of the interpreter.</p>
</div>
<div class="section" id="fundamental-objects">
<span id="fundamental"></span><h2>Fundamental Objects<a class="headerlink" href="#fundamental-objects" title="Permalink to this headline">¶</a></h2>
<p>This section describes Python type objects and the singleton object <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="type.html">Type Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="none.html">The <code class="docutils literal notranslate"><span class="pre">None</span></code> Object</a></li>
</ul>
</div>
</div>
<div class="section" id="numeric-objects">
<span id="numericobjects"></span><h2>Numeric Objects<a class="headerlink" href="#numeric-objects" title="Permalink to this headline">¶</a></h2>
<div class="toctree-wrapper compound" id="index-0">
<ul>
<li class="toctree-l1"><a class="reference internal" href="int.html">Plain Integer Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="bool.html">Boolean Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="long.html">Long Integer Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="float.html">Floating Point Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="complex.html">Complex Number Objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="complex.html#complex-numbers-as-c-structures">Complex Numbers as C Structures</a></li>
<li class="toctree-l2"><a class="reference internal" href="complex.html#complex-numbers-as-python-objects">Complex Numbers as Python Objects</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div class="section" id="sequence-objects">
<span id="sequenceobjects"></span><h2>Sequence Objects<a class="headerlink" href="#sequence-objects" title="Permalink to this headline">¶</a></h2>
<p id="index-1">Generic operations on sequence objects were discussed in the previous chapter;
this section deals with the specific kinds of sequence objects that are
intrinsic to the Python language.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="bytearray.html">Byte Array Objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="bytearray.html#type-check-macros">Type check macros</a></li>
<li class="toctree-l2"><a class="reference internal" href="bytearray.html#direct-api-functions">Direct API functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="bytearray.html#macros">Macros</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="string.html">String/Bytes Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="unicode.html">Unicode Objects and Codecs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="unicode.html#unicode-objects">Unicode Objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#unicode-type">Unicode Type</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#unicode-character-properties">Unicode Character Properties</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#plain-py-unicode">Plain Py_UNICODE</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#wchar-t-support">wchar_t Support</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unicode.html#built-in-codecs">Built-in Codecs</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#generic-codecs">Generic Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#utf-8-codecs">UTF-8 Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#utf-32-codecs">UTF-32 Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#utf-16-codecs">UTF-16 Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#utf-7-codecs">UTF-7 Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#unicode-escape-codecs">Unicode-Escape Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#raw-unicode-escape-codecs">Raw-Unicode-Escape Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#latin-1-codecs">Latin-1 Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#ascii-codecs">ASCII Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#character-map-codecs">Character Map Codecs</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#mbcs-codecs-for-windows">MBCS codecs for Windows</a></li>
<li class="toctree-l3"><a class="reference internal" href="unicode.html#methods-slots">Methods &amp; Slots</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unicode.html#methods-and-slot-functions">Methods and Slot Functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="buffer.html">Buffers and Memoryview Objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="buffer.html#the-new-style-py-buffer-struct">The new-style Py_buffer struct</a></li>
<li class="toctree-l2"><a class="reference internal" href="buffer.html#buffer-related-functions">Buffer related functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="buffer.html#memoryview-objects">MemoryView objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="buffer.html#old-style-buffer-objects">Old-style buffer objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tuple.html">Tuple Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="list.html">List Objects</a></li>
</ul>
</div>
</div>
<div class="section" id="mapping-objects">
<span id="mapobjects"></span><h2>Mapping Objects<a class="headerlink" href="#mapping-objects" title="Permalink to this headline">¶</a></h2>
<div class="toctree-wrapper compound" id="index-2">
<ul>
<li class="toctree-l1"><a class="reference internal" href="dict.html">Dictionary Objects</a></li>
</ul>
</div>
</div>
<div class="section" id="other-objects">
<span id="otherobjects"></span><h2>Other Objects<a class="headerlink" href="#other-objects" title="Permalink to this headline">¶</a></h2>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="class.html">Class and Instance Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="function.html">Function Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="method.html">Method Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="file.html">File Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="module.html">Module Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="iterator.html">Iterator Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="descriptor.html">Descriptor Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="slice.html">Slice Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="slice.html#ellipsis-object">Ellipsis Object</a></li>
<li class="toctree-l1"><a class="reference internal" href="weakref.html">Weak Reference Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="capsule.html">Capsules</a></li>
<li class="toctree-l1"><a class="reference internal" href="cobject.html">CObjects</a></li>
<li class="toctree-l1"><a class="reference internal" href="cell.html">Cell Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="gen.html">Generator Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="datetime.html">DateTime Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="set.html">Set Objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="code.html">Code Objects</a></li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Concrete Objects Layer</a><ul>
<li><a class="reference internal" href="#fundamental-objects">Fundamental Objects</a></li>
<li><a class="reference internal" href="#numeric-objects">Numeric Objects</a></li>
<li><a class="reference internal" href="#sequence-objects">Sequence Objects</a></li>
<li><a class="reference internal" href="#mapping-objects">Mapping Objects</a></li>
<li><a class="reference internal" href="#other-objects">Other Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="objbuffer.html"
                        title="previous chapter">Old Buffer Protocol</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="type.html"
                        title="next chapter">Type Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/concrete.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="type.html" title="Type Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="objbuffer.html" title="Old Buffer Protocol"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\&cn[n[html/c-api/conversion.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>String conversion and formatting &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Reflection" href="reflection.html" />
    <link rel="prev" title="Parsing arguments and building values" href="arg.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/conversion.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="reflection.html" title="Reflection"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="arg.html" title="Parsing arguments and building values"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" accesskey="U">Utilities</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="string-conversion-and-formatting">
<span id="string-conversion"></span><h1>String conversion and formatting<a class="headerlink" href="#string-conversion-and-formatting" title="Permalink to this headline">¶</a></h1>
<p>Functions for number conversion and formatted string output.</p>
<dl class="function">
<dt id="c.PyOS_snprintf">
int <code class="descname">PyOS_snprintf</code><span class="sig-paren">(</span>char<em>&nbsp;*str</em>, size_t<em>&nbsp;size</em>, const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_snprintf" title="Permalink to this definition">¶</a></dt>
<dd><p>Output not more than <em>size</em> bytes to <em>str</em> according to the format string
<em>format</em> and the extra arguments. See the Unix man page <em class="manpage">snprintf(2)</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_vsnprintf">
int <code class="descname">PyOS_vsnprintf</code><span class="sig-paren">(</span>char<em>&nbsp;*str</em>, size_t<em>&nbsp;size</em>, const char<em>&nbsp;*format</em>, va_list<em>&nbsp;va</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_vsnprintf" title="Permalink to this definition">¶</a></dt>
<dd><p>Output not more than <em>size</em> bytes to <em>str</em> according to the format string
<em>format</em> and the variable argument list <em>va</em>. Unix man page
<em class="manpage">vsnprintf(2)</em>.</p>
</dd></dl>

<p><a class="reference internal" href="#c.PyOS_snprintf" title="PyOS_snprintf"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_snprintf()</span></code></a> and <a class="reference internal" href="#c.PyOS_vsnprintf" title="PyOS_vsnprintf"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_vsnprintf()</span></code></a> wrap the Standard C library
functions <code class="xref c c-func docutils literal notranslate"><span class="pre">snprintf()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">vsnprintf()</span></code>. Their purpose is to
guarantee consistent behavior in corner cases, which the Standard C functions do
not.</p>
<p>The wrappers ensure that <em>str*[*size</em>-1] is always <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> upon return. They
never write more than <em>size</em> bytes (including the trailing <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> into str.
Both functions require that <code class="docutils literal notranslate"><span class="pre">str</span> <span class="pre">!=</span> <span class="pre">NULL</span></code>, <code class="docutils literal notranslate"><span class="pre">size</span> <span class="pre">&gt;</span> <span class="pre">0</span></code> and <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">!=</span>
<span class="pre">NULL</span></code>.</p>
<p>If the platform doesn’t have <code class="xref c c-func docutils literal notranslate"><span class="pre">vsnprintf()</span></code> and the buffer size needed to
avoid truncation exceeds <em>size</em> by more than 512 bytes, Python aborts with a
<em>Py_FatalError</em>.</p>
<p>The return value (<em>rv</em>) for these functions should be interpreted as follows:</p>
<ul class="simple">
<li>When <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">rv</span> <span class="pre">&lt;</span> <span class="pre">size</span></code>, the output conversion was successful and <em>rv</em>
characters were written to <em>str</em> (excluding the trailing <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> byte at
<em>str*[*rv</em>]).</li>
<li>When <code class="docutils literal notranslate"><span class="pre">rv</span> <span class="pre">&gt;=</span> <span class="pre">size</span></code>, the output conversion was truncated and a buffer with
<code class="docutils literal notranslate"><span class="pre">rv</span> <span class="pre">+</span> <span class="pre">1</span></code> bytes would have been needed to succeed. <em>str*[*size</em>-1] is <code class="docutils literal notranslate"><span class="pre">'\0'</span></code>
in this case.</li>
<li>When <code class="docutils literal notranslate"><span class="pre">rv</span> <span class="pre">&lt;</span> <span class="pre">0</span></code>, “something bad happened.” <em>str*[*size</em>-1] is <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> in
this case too, but the rest of <em>str</em> is undefined. The exact cause of the error
depends on the underlying platform.</li>
</ul>
<p>The following functions provide locale-independent string to number conversions.</p>
<dl class="function">
<dt id="c.PyOS_string_to_double">
double <code class="descname">PyOS_string_to_double</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, char<em>&nbsp;**endptr</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*overflow_exception</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_string_to_double" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a string <code class="docutils literal notranslate"><span class="pre">s</span></code> to a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>, raising a Python
exception on failure.  The set of accepted strings corresponds to
the set of strings accepted by Python’s <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> constructor,
except that <code class="docutils literal notranslate"><span class="pre">s</span></code> must not have leading or trailing whitespace.
The conversion is independent of the current locale.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">endptr</span></code> is <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, convert the whole string.  Raise
ValueError and return <code class="docutils literal notranslate"><span class="pre">-1.0</span></code> if the string is not a valid
representation of a floating-point number.</p>
<p>If endptr is not <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, convert as much of the string as
possible and set <code class="docutils literal notranslate"><span class="pre">*endptr</span></code> to point to the first unconverted
character.  If no initial segment of the string is the valid
representation of a floating-point number, set <code class="docutils literal notranslate"><span class="pre">*endptr</span></code> to point
to the beginning of the string, raise ValueError, and return
<code class="docutils literal notranslate"><span class="pre">-1.0</span></code>.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">s</span></code> represents a value that is too large to store in a float
(for example, <code class="docutils literal notranslate"><span class="pre">&quot;1e500&quot;</span></code> is such a string on many platforms) then
if <code class="docutils literal notranslate"><span class="pre">overflow_exception</span></code> is <code class="docutils literal notranslate"><span class="pre">NULL</span></code> return <code class="docutils literal notranslate"><span class="pre">Py_HUGE_VAL</span></code> (with
an appropriate sign) and don’t set any exception.  Otherwise,
<code class="docutils literal notranslate"><span class="pre">overflow_exception</span></code> must point to a Python exception object;
raise that exception and return <code class="docutils literal notranslate"><span class="pre">-1.0</span></code>.  In both cases, set
<code class="docutils literal notranslate"><span class="pre">*endptr</span></code> to point to the first character after the converted value.</p>
<p>If any other error occurs during the conversion (for example an
out-of-memory error), set the appropriate Python exception and
return <code class="docutils literal notranslate"><span class="pre">-1.0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_ascii_strtod">
double <code class="descname">PyOS_ascii_strtod</code><span class="sig-paren">(</span>const char<em>&nbsp;*nptr</em>, char<em>&nbsp;**endptr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_ascii_strtod" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a string to a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>. This function behaves like the Standard C
function <code class="xref c c-func docutils literal notranslate"><span class="pre">strtod()</span></code> does in the C locale. It does this without changing the
current locale, since that would not be thread-safe.</p>
<p><a class="reference internal" href="#c.PyOS_ascii_strtod" title="PyOS_ascii_strtod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ascii_strtod()</span></code></a> should typically be used for reading configuration
files or other non-user input that should be locale independent.</p>
<p>See the Unix man page <em class="manpage">strtod(2)</em> for details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <a class="reference internal" href="#c.PyOS_string_to_double" title="PyOS_string_to_double"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_string_to_double()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_ascii_formatd">
char* <code class="descname">PyOS_ascii_formatd</code><span class="sig-paren">(</span>char<em>&nbsp;*buffer</em>, size_t<em>&nbsp;buf_len</em>, const char<em>&nbsp;*format</em>, double<em>&nbsp;d</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_ascii_formatd" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> to a string using the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> as the decimal
separator. <em>format</em> is a <code class="xref c c-func docutils literal notranslate"><span class="pre">printf()</span></code>-style format string specifying the
number format. Allowed conversion characters are <code class="docutils literal notranslate"><span class="pre">'e'</span></code>, <code class="docutils literal notranslate"><span class="pre">'E'</span></code>, <code class="docutils literal notranslate"><span class="pre">'f'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'F'</span></code>, <code class="docutils literal notranslate"><span class="pre">'g'</span></code> and <code class="docutils literal notranslate"><span class="pre">'G'</span></code>.</p>
<p>The return value is a pointer to <em>buffer</em> with the converted string or NULL if
the conversion failed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>This function is removed in Python 2.7 and 3.1.  Use <code class="xref py py-func docutils literal notranslate"><span class="pre">PyOS_double_to_string()</span></code>
instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_double_to_string">
char* <code class="descname">PyOS_double_to_string</code><span class="sig-paren">(</span>double<em>&nbsp;val</em>, char<em>&nbsp;format_code</em>, int<em>&nbsp;precision</em>, int<em>&nbsp;flags</em>, int<em>&nbsp;*ptype</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_double_to_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> <em>val</em> to a string using supplied
<em>format_code</em>, <em>precision</em>, and <em>flags</em>.</p>
<p><em>format_code</em> must be one of <code class="docutils literal notranslate"><span class="pre">'e'</span></code>, <code class="docutils literal notranslate"><span class="pre">'E'</span></code>, <code class="docutils literal notranslate"><span class="pre">'f'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'g'</span></code>, <code class="docutils literal notranslate"><span class="pre">'G'</span></code> or <code class="docutils literal notranslate"><span class="pre">'r'</span></code>.  For <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, the supplied <em>precision</em>
must be <code class="docutils literal notranslate"><span class="pre">0</span></code> and is ignored.  The <code class="docutils literal notranslate"><span class="pre">'r'</span></code> format code specifies the
standard <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> format.</p>
<p><em>flags</em> can be zero or more of the values <em>Py_DTSF_SIGN</em>,
<em>Py_DTSF_ADD_DOT_0</em>, or <em>Py_DTSF_ALT</em>, or-ed together:</p>
<ul class="simple">
<li><em>Py_DTSF_SIGN</em> means to always precede the returned string with a sign
character, even if <em>val</em> is non-negative.</li>
<li><em>Py_DTSF_ADD_DOT_0</em> means to ensure that the returned string will not look
like an integer.</li>
<li><em>Py_DTSF_ALT</em> means to apply “alternate” formatting rules.  See the
documentation for the <a class="reference internal" href="#c.PyOS_snprintf" title="PyOS_snprintf"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_snprintf()</span></code></a> <code class="docutils literal notranslate"><span class="pre">'#'</span></code> specifier for
details.</li>
</ul>
<p>If <em>ptype</em> is non-NULL, then the value it points to will be set to one of
<em>Py_DTST_FINITE</em>, <em>Py_DTST_INFINITE</em>, or <em>Py_DTST_NAN</em>, signifying that
<em>val</em> is a finite number, an infinite number, or not a number, respectively.</p>
<p>The return value is a pointer to <em>buffer</em> with the converted string or
<em>NULL</em> if the conversion failed. The caller is responsible for freeing the
returned string by calling <a class="reference internal" href="memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_ascii_atof">
double <code class="descname">PyOS_ascii_atof</code><span class="sig-paren">(</span>const char<em>&nbsp;*nptr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_ascii_atof" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a string to a <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> in a locale-independent way.</p>
<p>See the Unix man page <em class="manpage">atof(2)</em> for details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 3.1: </span>Use <a class="reference internal" href="#c.PyOS_string_to_double" title="PyOS_string_to_double"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_string_to_double()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_stricmp">
char* <code class="descname">PyOS_stricmp</code><span class="sig-paren">(</span>char<em>&nbsp;*s1</em>, char<em>&nbsp;*s2</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_stricmp" title="Permalink to this definition">¶</a></dt>
<dd><p>Case insensitive comparison of strings. The function works almost
identically to <code class="xref c c-func docutils literal notranslate"><span class="pre">strcmp()</span></code> except that it ignores the case.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyOS_strnicmp">
char* <code class="descname">PyOS_strnicmp</code><span class="sig-paren">(</span>char<em>&nbsp;*s1</em>, char<em>&nbsp;*s2</em>, Py_ssize_t <em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyOS_strnicmp" title="Permalink to this definition">¶</a></dt>
<dd><p>Case insensitive comparison of strings. The function works almost
identically to <code class="xref c c-func docutils literal notranslate"><span class="pre">strncmp()</span></code> except that it ignores the case.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="arg.html"
                        title="previous chapter">Parsing arguments and building values</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="reflection.html"
                        title="next chapter">Reflection</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/conversion.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="reflection.html" title="Reflection"
             >next</a> |</li>
        <li class="right" >
          <a href="arg.html" title="Parsing arguments and building values"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="utilities.html" >Utilities</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�g��egeghtml/c-api/datetime.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>DateTime Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Set Objects" href="set.html" />
    <link rel="prev" title="Generator Objects" href="gen.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/datetime.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="set.html" title="Set Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gen.html" title="Generator Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="datetime-objects">
<span id="datetimeobjects"></span><h1>DateTime Objects<a class="headerlink" href="#datetime-objects" title="Permalink to this headline">¶</a></h1>
<p>Various date and time objects are supplied by the <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module.
Before using any of these functions, the header file <code class="file docutils literal notranslate"><span class="pre">datetime.h</span></code> must be
included in your source (note that this is not included by <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>),
and the macro <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyDateTime_IMPORT</span></code> must be invoked, usually as part of
the module initialisation function.  The macro puts a pointer to a C structure
into a static variable, <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTimeAPI</span></code>, that is used by the following
macros.</p>
<p>Type-check macros:</p>
<dl class="function">
<dt id="c.PyDate_Check">
int <code class="descname">PyDate_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDate_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateType</span></code> or a subtype of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateType</span></code>.  <em>ob</em> must not be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDate_CheckExact">
int <code class="descname">PyDate_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDate_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateType</span></code>. <em>ob</em> must not be
<em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_Check">
int <code class="descname">PyDateTime_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateTimeType</span></code> or a subtype of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateTimeType</span></code>.  <em>ob</em> must not be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_CheckExact">
int <code class="descname">PyDateTime_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateTimeType</span></code>. <em>ob</em> must not
be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTime_Check">
int <code class="descname">PyTime_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTime_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TimeType</span></code> or a subtype of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TimeType</span></code>.  <em>ob</em> must not be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTime_CheckExact">
int <code class="descname">PyTime_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTime_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TimeType</span></code>. <em>ob</em> must not be
<em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDelta_Check">
int <code class="descname">PyDelta_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDelta_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DeltaType</span></code> or a subtype of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DeltaType</span></code>.  <em>ob</em> must not be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDelta_CheckExact">
int <code class="descname">PyDelta_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDelta_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DeltaType</span></code>. <em>ob</em> must not be
<em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTZInfo_Check">
int <code class="descname">PyTZInfo_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTZInfo_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TZInfoType</span></code> or a subtype of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TZInfoType</span></code>.  <em>ob</em> must not be <em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTZInfo_CheckExact">
int <code class="descname">PyTZInfo_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*ob</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTZInfo_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>ob</em> is of type <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_TZInfoType</span></code>. <em>ob</em> must not be
<em>NULL</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Macros to create objects:</p>
<dl class="function">
<dt id="c.PyDate_FromDate">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDate_FromDate</code><span class="sig-paren">(</span>int<em>&nbsp;year</em>, int<em>&nbsp;month</em>, int<em>&nbsp;day</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDate_FromDate" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> object with the specified year, month and day.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_FromDateAndTime">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDateTime_FromDateAndTime</code><span class="sig-paren">(</span>int<em>&nbsp;year</em>, int<em>&nbsp;month</em>, int<em>&nbsp;day</em>, int<em>&nbsp;hour</em>, int<em>&nbsp;minute</em>, int<em>&nbsp;second</em>, int<em>&nbsp;usecond</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_FromDateAndTime" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> object with the specified year, month, day, hour,
minute, second and microsecond.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyTime_FromTime">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyTime_FromTime</code><span class="sig-paren">(</span>int<em>&nbsp;hour</em>, int<em>&nbsp;minute</em>, int<em>&nbsp;second</em>, int<em>&nbsp;usecond</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyTime_FromTime" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <code class="docutils literal notranslate"><span class="pre">datetime.time</span></code> object with the specified hour, minute, second and
microsecond.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDelta_FromDSU">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDelta_FromDSU</code><span class="sig-paren">(</span>int<em>&nbsp;days</em>, int<em>&nbsp;seconds</em>, int<em>&nbsp;useconds</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDelta_FromDSU" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <code class="docutils literal notranslate"><span class="pre">datetime.timedelta</span></code> object representing the given number of days,
seconds and microseconds.  Normalization is performed so that the resulting
number of microseconds and seconds lie in the ranges documented for
<code class="docutils literal notranslate"><span class="pre">datetime.timedelta</span></code> objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Macros to extract fields from date objects.  The argument must be an instance of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_Date</span></code>, including subclasses (such as
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateTime</span></code>).  The argument must not be <em>NULL</em>, and the type is
not checked:</p>
<dl class="function">
<dt id="c.PyDateTime_GET_YEAR">
int <code class="descname">PyDateTime_GET_YEAR</code><span class="sig-paren">(</span>PyDateTime_Date<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_GET_YEAR" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the year, as a positive int.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_GET_MONTH">
int <code class="descname">PyDateTime_GET_MONTH</code><span class="sig-paren">(</span>PyDateTime_Date<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_GET_MONTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the month, as an int from 1 through 12.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_GET_DAY">
int <code class="descname">PyDateTime_GET_DAY</code><span class="sig-paren">(</span>PyDateTime_Date<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_GET_DAY" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the day, as an int from 1 through 31.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Macros to extract fields from datetime objects.  The argument must be an
instance of <code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_DateTime</span></code>, including subclasses. The argument
must not be <em>NULL</em>, and the type is not checked:</p>
<dl class="function">
<dt id="c.PyDateTime_DATE_GET_HOUR">
int <code class="descname">PyDateTime_DATE_GET_HOUR</code><span class="sig-paren">(</span>PyDateTime_DateTime<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_DATE_GET_HOUR" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hour, as an int from 0 through 23.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_DATE_GET_MINUTE">
int <code class="descname">PyDateTime_DATE_GET_MINUTE</code><span class="sig-paren">(</span>PyDateTime_DateTime<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_DATE_GET_MINUTE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the minute, as an int from 0 through 59.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_DATE_GET_SECOND">
int <code class="descname">PyDateTime_DATE_GET_SECOND</code><span class="sig-paren">(</span>PyDateTime_DateTime<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_DATE_GET_SECOND" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the second, as an int from 0 through 59.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_DATE_GET_MICROSECOND">
int <code class="descname">PyDateTime_DATE_GET_MICROSECOND</code><span class="sig-paren">(</span>PyDateTime_DateTime<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_DATE_GET_MICROSECOND" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the microsecond, as an int from 0 through 999999.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Macros to extract fields from time objects.  The argument must be an instance of
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyDateTime_Time</span></code>, including subclasses. The argument must not be <em>NULL</em>,
and the type is not checked:</p>
<dl class="function">
<dt id="c.PyDateTime_TIME_GET_HOUR">
int <code class="descname">PyDateTime_TIME_GET_HOUR</code><span class="sig-paren">(</span>PyDateTime_Time<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_TIME_GET_HOUR" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hour, as an int from 0 through 23.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_TIME_GET_MINUTE">
int <code class="descname">PyDateTime_TIME_GET_MINUTE</code><span class="sig-paren">(</span>PyDateTime_Time<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_TIME_GET_MINUTE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the minute, as an int from 0 through 59.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_TIME_GET_SECOND">
int <code class="descname">PyDateTime_TIME_GET_SECOND</code><span class="sig-paren">(</span>PyDateTime_Time<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_TIME_GET_SECOND" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the second, as an int from 0 through 59.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDateTime_TIME_GET_MICROSECOND">
int <code class="descname">PyDateTime_TIME_GET_MICROSECOND</code><span class="sig-paren">(</span>PyDateTime_Time<em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_TIME_GET_MICROSECOND" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the microsecond, as an int from 0 through 999999.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Macros for the convenience of modules implementing the DB API:</p>
<dl class="function">
<dt id="c.PyDateTime_FromTimestamp">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDateTime_FromTimestamp</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDateTime_FromTimestamp" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create and return a new <code class="docutils literal notranslate"><span class="pre">datetime.datetime</span></code> object given an argument tuple
suitable for passing to <code class="docutils literal notranslate"><span class="pre">datetime.datetime.fromtimestamp()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDate_FromTimestamp">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDate_FromTimestamp</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*args</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDate_FromTimestamp" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create and return a new <code class="docutils literal notranslate"><span class="pre">datetime.date</span></code> object given an argument tuple
suitable for passing to <code class="docutils literal notranslate"><span class="pre">datetime.date.fromtimestamp()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="gen.html"
                        title="previous chapter">Generator Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="set.html"
                        title="next chapter">Set Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/datetime.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="set.html" title="Set Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="gen.html" title="Generator Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\
kc//html/c-api/descriptor.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Descriptor Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Slice Objects" href="slice.html" />
    <link rel="prev" title="Iterator Objects" href="iterator.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/descriptor.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="slice.html" title="Slice Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="iterator.html" title="Iterator Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="descriptor-objects">
<span id="id1"></span><h1>Descriptor Objects<a class="headerlink" href="#descriptor-objects" title="Permalink to this headline">¶</a></h1>
<p>“Descriptors” are objects that describe some attribute of an object. They are
found in the dictionary of type objects.</p>
<dl class="var">
<dt id="c.PyProperty_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyProperty_Type</code><a class="headerlink" href="#c.PyProperty_Type" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for the built-in descriptor types.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_NewGetSet">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDescr_NewGetSet</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, struct <a class="reference internal" href="structures.html#c.PyGetSetDef" title="PyGetSetDef">PyGetSetDef</a><em>&nbsp;*getset</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_NewGetSet" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_NewMember">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDescr_NewMember</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, struct <a class="reference internal" href="structures.html#c.PyMemberDef" title="PyMemberDef">PyMemberDef</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_NewMember" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_NewMethod">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDescr_NewMethod</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, struct <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;*meth</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_NewMethod" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_NewWrapper">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDescr_NewWrapper</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, struct wrapperbase<em>&nbsp;*wrapper</em>, void<em>&nbsp;*wrapped</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_NewWrapper" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_NewClassMethod">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDescr_NewClassMethod</code><span class="sig-paren">(</span><a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, <a class="reference internal" href="structures.html#c.PyMethodDef" title="PyMethodDef">PyMethodDef</a><em>&nbsp;*method</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_NewClassMethod" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDescr_IsData">
int <code class="descname">PyDescr_IsData</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*descr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDescr_IsData" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the descriptor objects <em>descr</em> describes a data attribute, or
false if it describes a method.  <em>descr</em> must be a descriptor object; there is
no error checking.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyWrapper_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyWrapper_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyWrapper_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="iterator.html"
                        title="previous chapter">Iterator Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="slice.html"
                        title="next chapter">Slice Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/descriptor.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="slice.html" title="Slice Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="iterator.html" title="Iterator Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��ƁƁhtml/c-api/dict.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Dictionary Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Class and Instance Objects" href="class.html" />
    <link rel="prev" title="List Objects" href="list.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/dict.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="class.html" title="Class and Instance Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="list.html" title="List Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="dictionary-objects">
<span id="dictobjects"></span><h1>Dictionary Objects<a class="headerlink" href="#dictionary-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyDictObject">
<code class="descname">PyDictObject</code><a class="headerlink" href="#c.PyDictObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python dictionary object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyDict_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyDict_Type</code><a class="headerlink" href="#c.PyDict_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python dictionary
type.  This is exposed to Python programs as <code class="docutils literal notranslate"><span class="pre">dict</span></code> and
<code class="docutils literal notranslate"><span class="pre">types.DictType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Check">
int <code class="descname">PyDict_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a dict object or an instance of a subtype of the dict
type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_CheckExact">
int <code class="descname">PyDict_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>p</em> is a dict object, but not an instance of a subtype of
the dict type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_New</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new empty dictionary, or <em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDictProxy_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDictProxy_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*dict</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDictProxy_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a proxy object for a mapping which enforces read-only behavior.
This is normally used to create a proxy to prevent modification of the
dictionary for non-dynamic class types.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Clear">
void <code class="descname">PyDict_Clear</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Empty an existing dictionary of all key-value pairs.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Contains">
int <code class="descname">PyDict_Contains</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Contains" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if dictionary <em>p</em> contains <em>key</em>.  If an item in <em>p</em> is matches
<em>key</em>, return <code class="docutils literal notranslate"><span class="pre">1</span></code>, otherwise return <code class="docutils literal notranslate"><span class="pre">0</span></code>.  On error, return <code class="docutils literal notranslate"><span class="pre">-1</span></code>.
This is equivalent to the Python expression <code class="docutils literal notranslate"><span class="pre">key</span> <span class="pre">in</span> <span class="pre">p</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Copy">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_Copy</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Copy" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new dictionary that contains the same key-value pairs as <em>p</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_SetItem">
int <code class="descname">PyDict_SetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*val</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_SetItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert <em>value</em> into the dictionary <em>p</em> with a key of <em>key</em>.  <em>key</em> must be
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>; if it isn’t, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised. Return
<code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_SetItemString">
int <code class="descname">PyDict_SetItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, const char<em>&nbsp;*key</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*val</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_SetItemString" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Insert <em>value</em> into the dictionary <em>p</em> using <em>key</em> as a key. <em>key</em> should
be a <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>.  The key object is created using
<code class="docutils literal notranslate"><span class="pre">PyString_FromString(key)</span></code>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_DelItem">
int <code class="descname">PyDict_DelItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_DelItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the entry in dictionary <em>p</em> with key <em>key</em>. <em>key</em> must be hashable;
if it isn’t, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code>
on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_DelItemString">
int <code class="descname">PyDict_DelItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, char<em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_DelItemString" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the entry in dictionary <em>p</em> which has a key specified by the string
<em>key</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_GetItem">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_GetItem</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_GetItem" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the object from dictionary <em>p</em> which has a key <em>key</em>.  Return <em>NULL</em>
if the key <em>key</em> is not present, but <em>without</em> setting an exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_GetItemString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_GetItemString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, const char<em>&nbsp;*key</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_GetItemString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>This is the same as <a class="reference internal" href="#c.PyDict_GetItem" title="PyDict_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItem()</span></code></a>, but <em>key</em> is specified as a
<code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>, rather than a <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Items">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_Items</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Items" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <a class="reference internal" href="list.html#c.PyListObject" title="PyListObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyListObject</span></code></a> containing all the items from the
dictionary, as in the dictionary method <a class="reference internal" href="../library/stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Keys">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_Keys</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Keys" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <a class="reference internal" href="list.html#c.PyListObject" title="PyListObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyListObject</span></code></a> containing all the keys from the dictionary,
as in the dictionary method <a class="reference internal" href="../library/stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.keys()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Values">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyDict_Values</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Values" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a <a class="reference internal" href="list.html#c.PyListObject" title="PyListObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyListObject</span></code></a> containing all the values from the
dictionary <em>p</em>, as in the dictionary method <a class="reference internal" href="../library/stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.values()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Size">
Py_ssize_t <code class="descname">PyDict_Size</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Size" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Return the number of items in the dictionary.  This is equivalent to
<code class="docutils literal notranslate"><span class="pre">len(p)</span></code> on a dictionary.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function returned an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type.  This might require changes
in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Next">
int <code class="descname">PyDict_Next</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, Py_ssize_t<em>&nbsp;*ppos</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**pkey</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**pvalue</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Next" title="Permalink to this definition">¶</a></dt>
<dd><p>Iterate over all key-value pairs in the dictionary <em>p</em>.  The
<code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> referred to by <em>ppos</em> must be initialized to <code class="docutils literal notranslate"><span class="pre">0</span></code>
prior to the first call to this function to start the iteration; the
function returns true for each pair in the dictionary, and false once all
pairs have been reported.  The parameters <em>pkey</em> and <em>pvalue</em> should either
point to <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> variables that will be filled in with each key
and value, respectively, or may be <em>NULL</em>.  Any references returned through
them are borrowed.  <em>ppos</em> should not be altered during iteration. Its
value represents offsets within the internal dictionary structure, and
since the structure is sparse, the offsets are not consecutive.</p>
<p>For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">key</span><span class="p">,</span> <span class="o">*</span><span class="n">value</span><span class="p">;</span>
<span class="n">Py_ssize_t</span> <span class="n">pos</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

<span class="k">while</span> <span class="p">(</span><span class="n">PyDict_Next</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">dict</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">pos</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">key</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">value</span><span class="p">))</span> <span class="p">{</span>
    <span class="cm">/* do something interesting with the values... */</span>
    <span class="p">...</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The dictionary <em>p</em> should not be mutated during iteration.  It is safe
(since Python 2.1) to modify the values of the keys as you iterate over the
dictionary, but only so long as the set of keys does not change.  For
example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">key</span><span class="p">,</span> <span class="o">*</span><span class="n">value</span><span class="p">;</span>
<span class="n">Py_ssize_t</span> <span class="n">pos</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

<span class="k">while</span> <span class="p">(</span><span class="n">PyDict_Next</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">dict</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">pos</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">key</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">value</span><span class="p">))</span> <span class="p">{</span>
    <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="n">PyInt_AS_LONG</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">o</span> <span class="o">=</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">o</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyDict_SetItem</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">dict</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">o</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">o</span><span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">o</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span> <span class="pre">*</span></code> type for <em>ppos</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Merge">
int <code class="descname">PyDict_Merge</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*a</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*b</em>, int<em>&nbsp;override</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Merge" title="Permalink to this definition">¶</a></dt>
<dd><p>Iterate over mapping object <em>b</em> adding key-value pairs to dictionary <em>a</em>.
<em>b</em> may be a dictionary, or any object supporting <a class="reference internal" href="mapping.html#c.PyMapping_Keys" title="PyMapping_Keys"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMapping_Keys()</span></code></a>
and <a class="reference internal" href="object.html#c.PyObject_GetItem" title="PyObject_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetItem()</span></code></a>. If <em>override</em> is true, existing pairs in <em>a</em>
will be replaced if a matching key is found in <em>b</em>, otherwise pairs will
only be added if there is not a matching key in <em>a</em>. Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on
success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an exception was raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_Update">
int <code class="descname">PyDict_Update</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*a</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*b</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_Update" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the same as <code class="docutils literal notranslate"><span class="pre">PyDict_Merge(a,</span> <span class="pre">b,</span> <span class="pre">1)</span></code> in C, and is similar to
<code class="docutils literal notranslate"><span class="pre">a.update(b)</span></code> in Python except that <a class="reference internal" href="#c.PyDict_Update" title="PyDict_Update"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_Update()</span></code></a> doesn’t fall
back to the iterating over a sequence of key value pairs if the second
argument has no “keys” attribute.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an
exception was raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyDict_MergeFromSeq2">
int <code class="descname">PyDict_MergeFromSeq2</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*a</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*seq2</em>, int<em>&nbsp;override</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyDict_MergeFromSeq2" title="Permalink to this definition">¶</a></dt>
<dd><p>Update or merge into dictionary <em>a</em>, from the key-value pairs in <em>seq2</em>.
<em>seq2</em> must be an iterable object producing iterable objects of length 2,
viewed as key-value pairs.  In case of duplicate keys, the last wins if
<em>override</em> is true, else the first wins. Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code>
if an exception was raised. Equivalent Python (except for the return
value):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">def</span> <span class="n">PyDict_MergeFromSeq2</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">seq2</span><span class="p">,</span> <span class="n">override</span><span class="p">)</span><span class="o">:</span>
    <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="n">in</span> <span class="nl">seq2</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">override</span> <span class="n">or</span> <span class="n">key</span> <span class="n">not</span> <span class="n">in</span> <span class="nl">a</span><span class="p">:</span>
            <span class="n">a</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="list.html"
                        title="previous chapter">List Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="class.html"
                        title="next chapter">Class and Instance Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/dict.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="class.html" title="Class and Instance Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="list.html" title="List Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Q\tGkGkhtml/c-api/exceptions.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Exception Handling &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Utilities" href="utilities.html" />
    <link rel="prev" title="Reference Counting" href="refcounting.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/exceptions.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="utilities.html" title="Utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="refcounting.html" title="Reference Counting"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="exception-handling">
<span id="exceptionhandling"></span><h1>Exception Handling<a class="headerlink" href="#exception-handling" title="Permalink to this headline">¶</a></h1>
<p>The functions described in this chapter will let you handle and raise Python
exceptions.  It is important to understand some of the basics of Python
exception handling.  It works somewhat like the Unix <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> variable:
there is a global indicator (per thread) of the last error that occurred.  Most
functions don’t clear this on success, but will set it to indicate the cause of
the error on failure.  Most functions also return an error indicator, usually
<em>NULL</em> if they are supposed to return a pointer, or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if they return an
integer (exception: the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_*()</span></code> functions return <code class="docutils literal notranslate"><span class="pre">1</span></code> for success and
<code class="docutils literal notranslate"><span class="pre">0</span></code> for failure).</p>
<p>When a function must fail because some function it called failed, it generally
doesn’t set the error indicator; the function it called already set it.  It is
responsible for either handling the error and clearing the exception or
returning after cleaning up any resources it holds (such as object references or
memory allocations); it should <em>not</em> continue normally if it is not prepared to
handle the error.  If returning due to an error, it is important to indicate to
the caller that an error has been set.  If the error is not handled or carefully
propagated, additional calls into the Python/C API may not behave as intended
and may fail in mysterious ways.</p>
<p id="index-0">The error indicator consists of three Python objects corresponding to   the
Python variables <code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.exc_value</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code>.
API functions exist to interact with the error indicator in various ways.  There
is a separate error indicator for each thread.</p>
<dl class="function">
<dt id="c.PyErr_PrintEx">
void <code class="descname">PyErr_PrintEx</code><span class="sig-paren">(</span>int<em>&nbsp;set_sys_last_vars</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_PrintEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a standard traceback to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> and clear the error indicator.
Call this function only when the error indicator is set.  (Otherwise it will
cause a fatal error!)</p>
<p>If <em>set_sys_last_vars</em> is nonzero, the variables <a class="reference internal" href="../library/sys.html#sys.last_type" title="sys.last_type"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_type</span></code></a>,
<a class="reference internal" href="../library/sys.html#sys.last_value" title="sys.last_value"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_value</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.last_traceback" title="sys.last_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_traceback</span></code></a> will be set to the
type, value and traceback of the printed exception, respectively.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Print">
void <code class="descname">PyErr_Print</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Print" title="Permalink to this definition">¶</a></dt>
<dd><p>Alias for <code class="docutils literal notranslate"><span class="pre">PyErr_PrintEx(1)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Occurred">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_Occurred</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Occurred" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Test whether the error indicator is set.  If set, return the exception <em>type</em>
(the first argument to the last call to one of the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Set*()</span></code>
functions or to <a class="reference internal" href="#c.PyErr_Restore" title="PyErr_Restore"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Restore()</span></code></a>).  If not set, return <em>NULL</em>.  You do not
own a reference to the return value, so you do not need to <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>
it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Do not compare the return value to a specific exception; use
<a class="reference internal" href="#c.PyErr_ExceptionMatches" title="PyErr_ExceptionMatches"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_ExceptionMatches()</span></code></a> instead, shown below.  (The comparison could
easily fail since the exception may be an instance instead of a class, in the
case of a class exception, or it may be a subclass of the expected exception.)</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_ExceptionMatches">
int <code class="descname">PyErr_ExceptionMatches</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_ExceptionMatches" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">PyErr_GivenExceptionMatches(PyErr_Occurred(),</span> <span class="pre">exc)</span></code>.  This
should only be called when an exception is actually set; a memory access
violation will occur if no exception has been raised.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_GivenExceptionMatches">
int <code class="descname">PyErr_GivenExceptionMatches</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*given</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_GivenExceptionMatches" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the <em>given</em> exception matches the exception in <em>exc</em>.  If
<em>exc</em> is a class object, this also returns true when <em>given</em> is an instance
of a subclass.  If <em>exc</em> is a tuple, all exceptions in the tuple (and
recursively in subtuples) are searched for a match.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_NormalizeException">
void <code class="descname">PyErr_NormalizeException</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>**exc, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>**val, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>**tb<span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_NormalizeException" title="Permalink to this definition">¶</a></dt>
<dd><p>Under certain circumstances, the values returned by <a class="reference internal" href="#c.PyErr_Fetch" title="PyErr_Fetch"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Fetch()</span></code></a> below
can be “unnormalized”, meaning that <code class="docutils literal notranslate"><span class="pre">*exc</span></code> is a class object but <code class="docutils literal notranslate"><span class="pre">*val</span></code> is
not an instance of the  same class.  This function can be used to instantiate
the class in that case.  If the values are already normalized, nothing happens.
The delayed normalization is implemented to improve performance.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Clear">
void <code class="descname">PyErr_Clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the error indicator.  If the error indicator is not set, there is no
effect.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Fetch">
void <code class="descname">PyErr_Fetch</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**ptype</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**pvalue</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;**ptraceback</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Fetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the error indicator into three variables whose addresses are passed.
If the error indicator is not set, set all three variables to <em>NULL</em>.  If it is
set, it will be cleared and you own a reference to each object retrieved.  The
value and traceback object may be <em>NULL</em> even when the type object is not.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is normally only used by code that needs to handle exceptions or
by code that needs to save and restore the error indicator temporarily.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Restore">
void <code class="descname">PyErr_Restore</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Restore" title="Permalink to this definition">¶</a></dt>
<dd><p>Set  the error indicator from the three objects.  If the error indicator is
already set, it is cleared first.  If the objects are <em>NULL</em>, the error
indicator is cleared.  Do not pass a <em>NULL</em> type and non-<em>NULL</em> value or
traceback.  The exception type should be a class.  Do not pass an invalid
exception type or value. (Violating these rules will cause subtle problems
later.)  This call takes away a reference to each object: you must own a
reference to each object before the call and after the call you no longer own
these references.  (If you don’t understand this, don’t use this function.  I
warned you.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is normally only used by code that needs to save and restore the
error indicator temporarily; use <a class="reference internal" href="#c.PyErr_Fetch" title="PyErr_Fetch"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Fetch()</span></code></a> to save the current
exception state.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetString">
void <code class="descname">PyErr_SetString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, const char<em>&nbsp;*message</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetString" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the most common way to set the error indicator.  The first argument
specifies the exception type; it is normally one of the standard exceptions,
e.g. <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_RuntimeError</span></code>.  You need not increment its reference count.
The second argument is an error message; it is converted to a string object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetObject">
void <code class="descname">PyErr_SetObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*value</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to <a class="reference internal" href="#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> but lets you specify an
arbitrary Python object for the “value” of the exception.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Format">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_Format</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exception</em>, const char<em>&nbsp;*format</em>, ...<span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Format" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>This function sets the error indicator and returns <em>NULL</em>.  <em>exception</em>
should be a Python exception class.  The <em>format</em> and subsequent
parameters help format the error message; they have the same meaning and
values as in <a class="reference internal" href="string.html#c.PyString_FromFormat" title="PyString_FromFormat"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_FromFormat()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetNone">
void <code class="descname">PyErr_SetNone</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetNone" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">PyErr_SetObject(type,</span> <span class="pre">Py_None)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_BadArgument">
int <code class="descname">PyErr_BadArgument</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_BadArgument" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">PyErr_SetString(PyExc_TypeError,</span> <span class="pre">message)</span></code>, where
<em>message</em> indicates that a built-in operation was invoked with an illegal
argument.  It is mostly for internal use.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_NoMemory">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_NoMemory</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_NoMemory" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">PyErr_SetNone(PyExc_MemoryError)</span></code>; it returns <em>NULL</em>
so an object allocation function can write <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">PyErr_NoMemory();</span></code> when it
runs out of memory.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromErrno">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromErrno</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromErrno" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p id="index-1">This is a convenience function to raise an exception when a C library function
has returned an error and set the C variable <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code>.  It constructs a
tuple object whose first item is the integer <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> value and whose
second item is the corresponding error message (gotten from <code class="xref c c-func docutils literal notranslate"><span class="pre">strerror()</span></code>),
and then calls <code class="docutils literal notranslate"><span class="pre">PyErr_SetObject(type,</span> <span class="pre">object)</span></code>.  On Unix, when the
<code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> value is <code class="xref py py-const docutils literal notranslate"><span class="pre">EINTR</span></code>, indicating an interrupted system call,
this calls <a class="reference internal" href="#c.PyErr_CheckSignals" title="PyErr_CheckSignals"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_CheckSignals()</span></code></a>, and if that set the error indicator,
leaves it set to that.  The function always returns <em>NULL</em>, so a wrapper
function around a system call can write <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">PyErr_SetFromErrno(type);</span></code>
when the system call returns an error.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromErrnoWithFilenameObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromErrnoWithFilenameObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*filenameObject</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromErrnoWithFilenameObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromErrno" title="PyErr_SetFromErrno"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromErrno()</span></code></a>, with the additional behavior that if
<em>filenameObject</em> is not <em>NULL</em>, it is passed to the constructor of <em>type</em> as
a third parameter.  In the case of exceptions such as <a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> and
<a class="reference internal" href="../library/exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>, this is used to define the <code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attribute of the
exception instance.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromErrnoWithFilename">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromErrnoWithFilename</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromErrnoWithFilename" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromErrnoWithFilenameObject" title="PyErr_SetFromErrnoWithFilenameObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromErrnoWithFilenameObject()</span></code></a>, but the filename
is given as a C string.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromWindowsErr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromWindowsErr</code><span class="sig-paren">(</span>int<em>&nbsp;ierr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromWindowsErr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>This is a convenience function to raise <a class="reference internal" href="../library/exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a>. If called with
<em>ierr</em> of <code class="xref c c-data docutils literal notranslate"><span class="pre">0</span></code>, the error code returned by a call to <code class="xref c c-func docutils literal notranslate"><span class="pre">GetLastError()</span></code>
is used instead.  It calls the Win32 function <code class="xref c c-func docutils literal notranslate"><span class="pre">FormatMessage()</span></code> to retrieve
the Windows description of error code given by <em>ierr</em> or <code class="xref c c-func docutils literal notranslate"><span class="pre">GetLastError()</span></code>,
then it constructs a tuple object whose first item is the <em>ierr</em> value and whose
second item is the corresponding error message (gotten from
<code class="xref c c-func docutils literal notranslate"><span class="pre">FormatMessage()</span></code>), and then calls <code class="docutils literal notranslate"><span class="pre">PyErr_SetObject(PyExc_WindowsError,</span>
<span class="pre">object)</span></code>. This function always returns <em>NULL</em>. Availability: Windows.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetExcFromWindowsErr">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetExcFromWindowsErr</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, int<em>&nbsp;ierr</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetExcFromWindowsErr" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromWindowsErr" title="PyErr_SetFromWindowsErr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromWindowsErr()</span></code></a>, with an additional parameter
specifying the exception type to be raised. Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromWindowsErrWithFilenameObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromWindowsErrWithFilenameObject</code><span class="sig-paren">(</span>int<em>&nbsp;ierr</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*filenameObject</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromWindowsErrWithFilenameObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromWindowsErr" title="PyErr_SetFromWindowsErr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromWindowsErr()</span></code></a>, with the additional behavior that
if <em>filenameObject</em> is not <em>NULL</em>, it is passed to the constructor of
<a class="reference internal" href="../library/exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> as a third parameter. Availability: Windows.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetFromWindowsErrWithFilename">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetFromWindowsErrWithFilename</code><span class="sig-paren">(</span>int<em>&nbsp;ierr</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetFromWindowsErrWithFilename" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromWindowsErrWithFilenameObject" title="PyErr_SetFromWindowsErrWithFilenameObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromWindowsErrWithFilenameObject()</span></code></a>, but the
filename is given as a C string. Availability: Windows.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetExcFromWindowsErrWithFilenameObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetExcFromWindowsErrWithFilenameObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, int<em>&nbsp;ierr</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetExcFromWindowsErrWithFilenameObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromWindowsErrWithFilenameObject" title="PyErr_SetFromWindowsErrWithFilenameObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromWindowsErrWithFilenameObject()</span></code></a>, with an
additional parameter specifying the exception type to be raised.
Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetExcFromWindowsErrWithFilename">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_SetExcFromWindowsErrWithFilename</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*type</em>, int<em>&nbsp;ierr</em>, const char<em>&nbsp;*filename</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetExcFromWindowsErrWithFilename" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Always NULL.</em><p>Similar to <a class="reference internal" href="#c.PyErr_SetFromWindowsErrWithFilename" title="PyErr_SetFromWindowsErrWithFilename"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromWindowsErrWithFilename()</span></code></a>, with an additional
parameter specifying the exception type to be raised. Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_BadInternalCall">
void <code class="descname">PyErr_BadInternalCall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_BadInternalCall" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">PyErr_SetString(PyExc_SystemError,</span> <span class="pre">message)</span></code>,
where <em>message</em> indicates that an internal operation (e.g. a Python/C API
function) was invoked with an illegal argument.  It is mostly for internal
use.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_WarnEx">
int <code class="descname">PyErr_WarnEx</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*category</em>, char<em>&nbsp;*message</em>, int<em>&nbsp;stacklevel</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_WarnEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning message.  The <em>category</em> argument is a warning category (see
below) or <em>NULL</em>; the <em>message</em> argument is a message string.  <em>stacklevel</em> is a
positive number giving a number of stack frames; the warning will be issued from
the  currently executing line of code in that stack frame.  A <em>stacklevel</em> of 1
is the function calling <a class="reference internal" href="#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a>, 2 is  the function above that,
and so forth.</p>
<p>This function normally prints a warning message to <em>sys.stderr</em>; however, it is
also possible that the user has specified that warnings are to be turned into
errors, and in that case this will raise an exception.  It is also possible that
the function raises an exception because of a problem with the warning machinery
(the implementation imports the <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module to do the heavy lifting).
The return value is <code class="docutils literal notranslate"><span class="pre">0</span></code> if no exception is raised, or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if an exception
is raised.  (It is not possible to determine whether a warning message is
actually printed, nor what the reason is for the exception; this is
intentional.)  If an exception is raised, the caller should do its normal
exception handling (for example, <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> owned references and return
an error value).</p>
<p>Warning categories must be subclasses of <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Warning</span></code>;
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Warning</span></code> is a subclass of <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Exception</span></code>;
the default warning category is <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_RuntimeWarning</span></code>. The standard
Python warning categories are available as global variables whose names are
enumerated at <a class="reference internal" href="#standardwarningcategories"><span class="std std-ref">Standard Warning Categories</span></a>.</p>
<p>For information about warning control, see the documentation for the
<a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module and the <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> option in the command line
documentation.  There is no C API for warning control.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_Warn">
int <code class="descname">PyErr_Warn</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*category</em>, char<em>&nbsp;*message</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_Warn" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning message.  The <em>category</em> argument is a warning category (see
below) or <em>NULL</em>; the <em>message</em> argument is a message string.  The warning will
appear to be issued from the function calling <a class="reference internal" href="#c.PyErr_Warn" title="PyErr_Warn"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Warn()</span></code></a>, equivalent to
calling <a class="reference internal" href="#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a> with a <em>stacklevel</em> of 1.</p>
<p>Deprecated; use <a class="reference internal" href="#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a> instead.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_WarnExplicit">
int <code class="descname">PyErr_WarnExplicit</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*category</em>, const char<em>&nbsp;*message</em>, const char<em>&nbsp;*filename</em>, int<em>&nbsp;lineno</em>, const char<em>&nbsp;*module</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*registry</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_WarnExplicit" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning message with explicit control over all warning attributes.  This
is a straightforward wrapper around the Python function
<a class="reference internal" href="../library/warnings.html#warnings.warn_explicit" title="warnings.warn_explicit"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.warn_explicit()</span></code></a>, see there for more information.  The <em>module</em>
and <em>registry</em> arguments may be set to <em>NULL</em> to get the default effect
described there.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_WarnPy3k">
int <code class="descname">PyErr_WarnPy3k</code><span class="sig-paren">(</span>char<em>&nbsp;*message</em>, int<em>&nbsp;stacklevel</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_WarnPy3k" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> with the given <em>message</em> and <em>stacklevel</em>
if the <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_Py3kWarningFlag</span></code> flag is enabled.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_CheckSignals">
int <code class="descname">PyErr_CheckSignals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_CheckSignals" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">This function interacts with Python’s signal handling.  It checks whether a
signal has been sent to the processes and if so, invokes the corresponding
signal handler.  If the <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module is supported, this can invoke a
signal handler written in Python.  In all cases, the default effect for
<code class="xref py py-const docutils literal notranslate"><span class="pre">SIGINT</span></code> is to raise the  <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.  If an
exception is raised the error indicator is set and the function returns <code class="docutils literal notranslate"><span class="pre">-1</span></code>;
otherwise the function returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.  The error indicator may or may not be
cleared if it was previously set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_SetInterrupt">
void <code class="descname">PyErr_SetInterrupt</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_SetInterrupt" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">This function simulates the effect of a <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGINT</span></code> signal arriving — the
next time <a class="reference internal" href="#c.PyErr_CheckSignals" title="PyErr_CheckSignals"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_CheckSignals()</span></code></a> is called,  <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> will
be raised.  It may be called without holding the interpreter lock.</p>
</dd></dl>

<dl class="function">
<dt id="c.PySignal_SetWakeupFd">
int <code class="descname">PySignal_SetWakeupFd</code><span class="sig-paren">(</span>int<em>&nbsp;fd</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PySignal_SetWakeupFd" title="Permalink to this definition">¶</a></dt>
<dd><p>This utility function specifies a file descriptor to which a <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> byte will
be written whenever a signal is received.  It returns the previous such file
descriptor.  The value <code class="docutils literal notranslate"><span class="pre">-1</span></code> disables the feature; this is the initial state.
This is equivalent to <a class="reference internal" href="../library/signal.html#signal.set_wakeup_fd" title="signal.set_wakeup_fd"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.set_wakeup_fd()</span></code></a> in Python, but without any
error checking.  <em>fd</em> should be a valid file descriptor.  The function should
only be called from the main thread.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_NewException">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_NewException</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*base</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*dict</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_NewException" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>This utility function creates and returns a new exception class. The <em>name</em>
argument must be the name of the new exception, a C string of the form
<code class="docutils literal notranslate"><span class="pre">module.classname</span></code>.  The <em>base</em> and <em>dict</em> arguments are normally <em>NULL</em>.
This creates a class object derived from <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> (accessible in C as
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Exception</span></code>).</p>
<p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> attribute of the new class is set to the first part (up
to the last dot) of the <em>name</em> argument, and the class name is set to the last
part (after the last dot).  The <em>base</em> argument can be used to specify alternate
base classes; it can either be only one class or a tuple of classes. The <em>dict</em>
argument can be used to specify a dictionary of class variables and methods.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_NewExceptionWithDoc">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyErr_NewExceptionWithDoc</code><span class="sig-paren">(</span>char<em>&nbsp;*name</em>, char<em>&nbsp;*doc</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*base</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*dict</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_NewExceptionWithDoc" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Same as <a class="reference internal" href="#c.PyErr_NewException" title="PyErr_NewException"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewException()</span></code></a>, except that the new exception class can
easily be given a docstring: If <em>doc</em> is non-<em>NULL</em>, it will be used as the
docstring for the exception class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyErr_WriteUnraisable">
void <code class="descname">PyErr_WriteUnraisable</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyErr_WriteUnraisable" title="Permalink to this definition">¶</a></dt>
<dd><p>This utility function prints a warning message to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> when an
exception has been set but it is impossible for the interpreter to actually
raise the exception.  It is used, for example, when an exception occurs in an
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.</p>
<p>The function is called with a single argument <em>obj</em> that identifies the context
in which the unraisable exception occurred. If possible,
the repr of <em>obj</em> will be printed in the warning message.</p>
</dd></dl>

<div class="section" id="unicode-exception-objects">
<span id="unicodeexceptions"></span><h2>Unicode Exception Objects<a class="headerlink" href="#unicode-exception-objects" title="Permalink to this headline">¶</a></h2>
<p>The following functions are used to create and modify Unicode exceptions from C.</p>
<dl class="function">
<dt id="c.PyUnicodeDecodeError_Create">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeDecodeError_Create</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, const char<em>&nbsp;*object</em>, Py_ssize_t<em>&nbsp;length</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_Create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code> object with the attributes <em>encoding</em>,
<em>object</em>, <em>length</em>, <em>start</em>, <em>end</em> and <em>reason</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeEncodeError_Create">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeEncodeError_Create</code><span class="sig-paren">(</span>const char<em>&nbsp;*encoding</em>, const <a class="reference internal" href="unicode.html#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*object</em>, Py_ssize_t<em>&nbsp;length</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_Create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code> object with the attributes <em>encoding</em>,
<em>object</em>, <em>length</em>, <em>start</em>, <em>end</em> and <em>reason</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeTranslateError_Create">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeTranslateError_Create</code><span class="sig-paren">(</span>const <a class="reference internal" href="unicode.html#c.Py_UNICODE" title="Py_UNICODE">Py_UNICODE</a><em>&nbsp;*object</em>, Py_ssize_t<em>&nbsp;length</em>, Py_ssize_t<em>&nbsp;start</em>, Py_ssize_t<em>&nbsp;end</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_Create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeTranslateError</span></code> object with the attributes <em>object</em>,
<em>length</em>, <em>start</em>, <em>end</em> and <em>reason</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_GetEncoding">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeDecodeError_GetEncoding</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_GetEncoding" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_GetEncoding">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeEncodeError_GetEncoding</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_GetEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>encoding</em> attribute of the given exception object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_GetObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeDecodeError_GetObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_GetObject" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_GetObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeEncodeError_GetObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_GetObject" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_GetObject">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeTranslateError_GetObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_GetObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>object</em> attribute of the given exception object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_GetStart">
int <code class="descname">PyUnicodeDecodeError_GetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_GetStart" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_GetStart">
int <code class="descname">PyUnicodeEncodeError_GetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_GetStart" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_GetStart">
int <code class="descname">PyUnicodeTranslateError_GetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_GetStart" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the <em>start</em> attribute of the given exception object and place it into
<em>*start</em>.  <em>start</em> must not be <em>NULL</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_SetStart">
int <code class="descname">PyUnicodeDecodeError_SetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_SetStart" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_SetStart">
int <code class="descname">PyUnicodeEncodeError_SetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_SetStart" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_SetStart">
int <code class="descname">PyUnicodeTranslateError_SetStart</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;start</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_SetStart" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>start</em> attribute of the given exception object to <em>start</em>.  Return
<code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_GetEnd">
int <code class="descname">PyUnicodeDecodeError_GetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_GetEnd" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_GetEnd">
int <code class="descname">PyUnicodeEncodeError_GetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_GetEnd" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_GetEnd">
int <code class="descname">PyUnicodeTranslateError_GetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;*end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_GetEnd" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the <em>end</em> attribute of the given exception object and place it into
<em>*end</em>.  <em>end</em> must not be <em>NULL</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_SetEnd">
int <code class="descname">PyUnicodeDecodeError_SetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_SetEnd" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_SetEnd">
int <code class="descname">PyUnicodeEncodeError_SetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_SetEnd" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_SetEnd">
int <code class="descname">PyUnicodeTranslateError_SetEnd</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, Py_ssize_t<em>&nbsp;end</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_SetEnd" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>end</em> attribute of the given exception object to <em>end</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code>
on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_GetReason">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeDecodeError_GetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_GetReason" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_GetReason">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeEncodeError_GetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_GetReason" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_GetReason">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyUnicodeTranslateError_GetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_GetReason" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>reason</em> attribute of the given exception object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyUnicodeDecodeError_SetReason">
int <code class="descname">PyUnicodeDecodeError_SetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeDecodeError_SetReason" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeEncodeError_SetReason">
int <code class="descname">PyUnicodeEncodeError_SetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeEncodeError_SetReason" title="Permalink to this definition">¶</a></dt>
<dt id="c.PyUnicodeTranslateError_SetReason">
int <code class="descname">PyUnicodeTranslateError_SetReason</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*exc</em>, const char<em>&nbsp;*reason</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyUnicodeTranslateError_SetReason" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>reason</em> attribute of the given exception object to <em>reason</em>.  Return
<code class="docutils literal notranslate"><span class="pre">0</span></code> on success, <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

</div>
<div class="section" id="recursion-control">
<h2>Recursion Control<a class="headerlink" href="#recursion-control" title="Permalink to this headline">¶</a></h2>
<p>These two functions provide a way to perform safe recursive calls at the C
level, both in the core and in extension modules.  They are needed if the
recursive code does not necessarily invoke Python code (which tracks its
recursion depth automatically).</p>
<dl class="function">
<dt id="c.Py_EnterRecursiveCall">
int <code class="descname">Py_EnterRecursiveCall</code><span class="sig-paren">(</span>const char<em>&nbsp;*where</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_EnterRecursiveCall" title="Permalink to this definition">¶</a></dt>
<dd><p>Marks a point where a recursive C-level call is about to be performed.</p>
<p>If <code class="xref py py-const docutils literal notranslate"><span class="pre">USE_STACKCHECK</span></code> is defined, this function checks if the OS
stack overflowed using <a class="reference internal" href="sys.html#c.PyOS_CheckStack" title="PyOS_CheckStack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_CheckStack()</span></code></a>.  In this is the case, it
sets a <a class="reference internal" href="../library/exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> and returns a nonzero value.</p>
<p>The function then checks if the recursion limit is reached.  If this is the
case, a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is set and a nonzero value is returned.
Otherwise, zero is returned.</p>
<p><em>where</em> should be a string such as <code class="docutils literal notranslate"><span class="pre">&quot;</span> <span class="pre">in</span> <span class="pre">instance</span> <span class="pre">check&quot;</span></code> to be
concatenated to the <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> message caused by the recursion depth
limit.</p>
</dd></dl>

<dl class="function">
<dt id="c.Py_LeaveRecursiveCall">
void <code class="descname">Py_LeaveRecursiveCall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_LeaveRecursiveCall" title="Permalink to this definition">¶</a></dt>
<dd><p>Ends a <a class="reference internal" href="#c.Py_EnterRecursiveCall" title="Py_EnterRecursiveCall"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_EnterRecursiveCall()</span></code></a>.  Must be called once for each
<em>successful</em> invocation of <a class="reference internal" href="#c.Py_EnterRecursiveCall" title="Py_EnterRecursiveCall"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_EnterRecursiveCall()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="standard-exceptions">
<span id="standardexceptions"></span><h2>Standard Exceptions<a class="headerlink" href="#standard-exceptions" title="Permalink to this headline">¶</a></h2>
<p>All standard Python exceptions are available as global variables whose names are
<code class="docutils literal notranslate"><span class="pre">PyExc_</span></code> followed by the Python exception name.  These have the type
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>; they are all class objects.  For completeness, here are all
the variables:</p>
<table border="1" class="docutils" id="index-4">
<colgroup>
<col width="49%" />
<col width="39%" />
<col width="12%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">C Name</th>
<th class="head">Python Name</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_BaseException</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a></td>
<td>(1), (4)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Exception</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_StandardError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ArithmeticError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ArithmeticError" title="exceptions.ArithmeticError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ArithmeticError</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_AssertionError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_AttributeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_BufferError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.BufferError" title="exceptions.BufferError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BufferError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_EnvironmentError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.EnvironmentError" title="exceptions.EnvironmentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EnvironmentError</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_EOFError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_FloatingPointError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.FloatingPointError" title="exceptions.FloatingPointError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FloatingPointError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_GeneratorExit</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ImportError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_IndentationError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.IndentationError" title="exceptions.IndentationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndentationError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_IndexError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_IOError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_KeyError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_KeyboardInterrupt</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_LookupError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_MemoryError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_NameError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_NotImplementedError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_OSError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_OverflowError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ReferenceError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ReferenceError" title="exceptions.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ReferenceError</span></code></a></td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_RuntimeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_StopIteration</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_SyntaxError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_SystemError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_SystemExit</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TabError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.TabError" title="exceptions.TabError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TabError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnboundLocalError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnboundLocalError" title="exceptions.UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnicodeDecodeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnicodeEncodeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnicodeError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnicodeTranslateError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeTranslateError" title="exceptions.UnicodeTranslateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeTranslateError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_VMSError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.VMSError" title="exceptions.VMSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">VMSError</span></code></a></td>
<td>(5)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ValueError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_WindowsError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">This is a base class for other standard exceptions.</p>
</li>
<li><p class="first">This is the same as <a class="reference internal" href="../library/weakref.html#weakref.ReferenceError" title="weakref.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">weakref.ReferenceError</span></code></a>.</p>
</li>
<li><p class="first">Only defined on Windows; protect code that uses this by testing that the
preprocessor macro <code class="docutils literal notranslate"><span class="pre">MS_WINDOWS</span></code> is defined.</p>
</li>
<li><div class="first versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</li>
<li><p class="first">Only defined on VMS; protect code that uses this by testing that the
preprocessor macro <code class="docutils literal notranslate"><span class="pre">__VMS</span></code> is defined.</p>
</li>
</ol>
</div>
<div class="section" id="standard-warning-categories">
<span id="standardwarningcategories"></span><h2>Standard Warning Categories<a class="headerlink" href="#standard-warning-categories" title="Permalink to this headline">¶</a></h2>
<p>All standard Python warning categories are available as global variables whose
names are <code class="docutils literal notranslate"><span class="pre">PyExc_</span></code> followed by the Python exception name. These have the type
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>; they are all class objects. For completeness, here are all
the variables:</p>
<table border="1" class="docutils" id="index-5">
<colgroup>
<col width="49%" />
<col width="39%" />
<col width="12%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">C Name</th>
<th class="head">Python Name</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_Warning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_BytesWarning</span></code></td>
<td><code class="xref py py-exc docutils literal notranslate"><span class="pre">BytesWarning</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_DeprecationWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_FutureWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ImportWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.ImportWarning" title="exceptions.ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_PendingDeprecationWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_RuntimeWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeWarning" title="exceptions.RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_SyntaxWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UnicodeWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeWarning" title="exceptions.UnicodeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_UserWarning</span></code></td>
<td><a class="reference internal" href="../library/exceptions.html#exceptions.UserWarning" title="exceptions.UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>This is a base class for other standard warning categories.</li>
</ol>
</div>
<div class="section" id="string-exceptions">
<h2>String Exceptions<a class="headerlink" href="#string-exceptions" title="Permalink to this headline">¶</a></h2>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>All exceptions to be raised or caught must be derived from <a class="reference internal" href="../library/exceptions.html#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.
Trying to raise a string exception now raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Exception Handling</a><ul>
<li><a class="reference internal" href="#unicode-exception-objects">Unicode Exception Objects</a></li>
<li><a class="reference internal" href="#recursion-control">Recursion Control</a></li>
<li><a class="reference internal" href="#standard-exceptions">Standard Exceptions</a></li>
<li><a class="reference internal" href="#standard-warning-categories">Standard Warning Categories</a></li>
<li><a class="reference internal" href="#string-exceptions">String Exceptions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="refcounting.html"
                        title="previous chapter">Reference Counting</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="utilities.html"
                        title="next chapter">Utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/exceptions.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="utilities.html" title="Utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="refcounting.html" title="Reference Counting"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\'��^�^html/c-api/file.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>File Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Module Objects" href="module.html" />
    <link rel="prev" title="Method Objects" href="method.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/file.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="module.html" title="Module Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="method.html" title="Method Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="file-objects">
<span id="fileobjects"></span><h1>File Objects<a class="headerlink" href="#file-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Python’s built-in file objects are implemented entirely on the <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code>
support from the C standard library.  This is an implementation detail and may
change in future releases of Python.</p>
<dl class="type">
<dt id="c.PyFileObject">
<code class="descname">PyFileObject</code><a class="headerlink" href="#c.PyFileObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python file object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyFile_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyFile_Type</code><a class="headerlink" href="#c.PyFile_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python file type.  This is
exposed to Python programs as <code class="docutils literal notranslate"><span class="pre">file</span></code> and <code class="docutils literal notranslate"><span class="pre">types.FileType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_Check">
int <code class="descname">PyFile_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyFileObject" title="PyFileObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFileObject</span></code></a> or a subtype of
<a class="reference internal" href="#c.PyFileObject" title="PyFileObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFileObject</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_CheckExact">
int <code class="descname">PyFile_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyFileObject" title="PyFileObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFileObject</span></code></a>, but not a subtype of
<a class="reference internal" href="#c.PyFileObject" title="PyFileObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFileObject</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFile_FromString</code><span class="sig-paren">(</span>char<em>&nbsp;*filename</em>, char<em>&nbsp;*mode</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-2">On success, return a new file object that is opened on the file given by
<em>filename</em>, with a file mode given by <em>mode</em>, where <em>mode</em> has the same
semantics as the standard C routine <code class="xref c c-func docutils literal notranslate"><span class="pre">fopen()</span></code>.  On failure, return <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_FromFile">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFile_FromFile</code><span class="sig-paren">(</span>FILE<em>&nbsp;*fp</em>, char<em>&nbsp;*name</em>, char<em>&nbsp;*mode</em>, int (<em>*close</em>)(FILE*)<span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_FromFile" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a new <a class="reference internal" href="#c.PyFileObject" title="PyFileObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFileObject</span></code></a> from the already-open standard C file
pointer, <em>fp</em>.  The function <em>close</em> will be called when the file should be
closed.  Return <em>NULL</em> and close the file using <em>close</em> on failure.
<em>close</em> is optional and can be set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_AsFile">
FILE* <code class="descname">PyFile_AsFile</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_AsFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file object associated with <em>p</em> as a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code>.</p>
<p>If the caller will ever use the returned <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> object while
the <a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a> is released it must also call the <a class="reference internal" href="#c.PyFile_IncUseCount" title="PyFile_IncUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code></a> and
<a class="reference internal" href="#c.PyFile_DecUseCount" title="PyFile_DecUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code></a> functions described below as appropriate.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_IncUseCount">
void <code class="descname">PyFile_IncUseCount</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyFileObject" title="PyFileObject">PyFileObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_IncUseCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Increments the PyFileObject’s internal use count to indicate
that the underlying <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> is being used.
This prevents Python from calling f_close() on it from another thread.
Callers of this must call <a class="reference internal" href="#c.PyFile_DecUseCount" title="PyFile_DecUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code></a> when they are
finished with the <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code>.  Otherwise the file object will
never be closed by Python.</p>
<p>The <a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a> must be held while calling this function.</p>
<p>The suggested use is to call this after <a class="reference internal" href="#c.PyFile_AsFile" title="PyFile_AsFile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_AsFile()</span></code></a> and before
you release the GIL:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span> <span class="o">=</span> <span class="n">PyFile_AsFile</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
<span class="n">PyFile_IncUseCount</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
<span class="cm">/* ... */</span>
<span class="n">Py_BEGIN_ALLOW_THREADS</span>
<span class="nf">do_something</span><span class="p">(</span><span class="n">fp</span><span class="p">);</span>
<span class="n">Py_END_ALLOW_THREADS</span>
<span class="cm">/* ... */</span>
<span class="n">PyFile_DecUseCount</span><span class="p">(</span><span class="n">p</span><span class="p">);</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_DecUseCount">
void <code class="descname">PyFile_DecUseCount</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyFileObject" title="PyFileObject">PyFileObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_DecUseCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrements the PyFileObject’s internal unlocked_count member to
indicate that the caller is done with its own use of the <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code>.
This may only be called to undo a prior call to <a class="reference internal" href="#c.PyFile_IncUseCount" title="PyFile_IncUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code></a>.</p>
<p>The <a class="reference internal" href="../glossary.html#term-gil"><span class="xref std std-term">GIL</span></a> must be held while calling this function (see the example
above).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_GetLine">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFile_GetLine</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, int<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_GetLine" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p id="index-3">Equivalent to <code class="docutils literal notranslate"><span class="pre">p.readline([n])</span></code>, this function reads one line from the
object <em>p</em>.  <em>p</em> may be a file object or any object with a
<a class="reference internal" href="../library/io.html#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>
method.  If <em>n</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, exactly one line is read, regardless of the length of
the line.  If <em>n</em> is greater than <code class="docutils literal notranslate"><span class="pre">0</span></code>, no more than <em>n</em> bytes will be read
from the file; a partial line can be returned.  In both cases, an empty string
is returned if the end of the file is reached immediately.  If <em>n</em> is less than
<code class="docutils literal notranslate"><span class="pre">0</span></code>, however, one line is read regardless of length, but <a class="reference internal" href="../library/exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is
raised if the end of the file is reached immediately.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_Name">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFile_Name</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_Name" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the name of the file specified by <em>p</em> as a string object.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_SetBufSize">
void <code class="descname">PyFile_SetBufSize</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyFileObject" title="PyFileObject">PyFileObject</a><em>&nbsp;*p</em>, int<em>&nbsp;n</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_SetBufSize" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Available on systems with <code class="xref c c-func docutils literal notranslate"><span class="pre">setvbuf()</span></code> only.  This should only be called
immediately after file object creation.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_SetEncoding">
int <code class="descname">PyFile_SetEncoding</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyFileObject" title="PyFileObject">PyFileObject</a><em>&nbsp;*p</em>, const char<em>&nbsp;*enc</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_SetEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file’s encoding for Unicode output to <em>enc</em>. Return <code class="docutils literal notranslate"><span class="pre">1</span></code> on success and <code class="docutils literal notranslate"><span class="pre">0</span></code>
on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_SetEncodingAndErrors">
int <code class="descname">PyFile_SetEncodingAndErrors</code><span class="sig-paren">(</span><a class="reference internal" href="#c.PyFileObject" title="PyFileObject">PyFileObject</a><em>&nbsp;*p</em>, const char<em>&nbsp;*enc</em>, *errors<span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_SetEncodingAndErrors" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file’s encoding for Unicode output to <em>enc</em>, and its error
mode to <em>err</em>. Return <code class="docutils literal notranslate"><span class="pre">1</span></code> on success and <code class="docutils literal notranslate"><span class="pre">0</span></code> on failure.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_SoftSpace">
int <code class="descname">PyFile_SoftSpace</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, int<em>&nbsp;newflag</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_SoftSpace" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">This function exists for internal use by the interpreter.  Set the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">softspace</span></code> attribute of <em>p</em> to <em>newflag</em> and return the previous value.
<em>p</em> does not have to be a file object for this function to work properly; any
object is supported (thought its only interesting if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">softspace</span></code>
attribute can be set).  This function clears any errors, and will return <code class="docutils literal notranslate"><span class="pre">0</span></code>
as the previous value if the attribute either does not exist or if there were
errors in retrieving it.  There is no way to detect errors from this function,
but doing so should not be needed.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_WriteObject">
int <code class="descname">PyFile_WriteObject</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*obj</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em>, int<em>&nbsp;flags</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_WriteObject" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">Write object <em>obj</em> to file object <em>p</em>.  The only supported flag for <em>flags</em> is
<code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code>; if given, the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the object is written
instead of the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure; the
appropriate exception will be set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFile_WriteString">
int <code class="descname">PyFile_WriteString</code><span class="sig-paren">(</span>const char<em>&nbsp;*s</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFile_WriteString" title="Permalink to this definition">¶</a></dt>
<dd><p>Write string <em>s</em> to file object <em>p</em>.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> on success or <code class="docutils literal notranslate"><span class="pre">-1</span></code> on
failure; the appropriate exception will be set.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="method.html"
                        title="previous chapter">Method Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="module.html"
                        title="next chapter">Module Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/file.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="module.html" title="Module Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="method.html" title="Method Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\"�:�vDvDhtml/c-api/float.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Floating Point Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Complex Number Objects" href="complex.html" />
    <link rel="prev" title="Long Integer Objects" href="long.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/float.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="complex.html" title="Complex Number Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="long.html" title="Long Integer Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="floating-point-objects">
<span id="floatobjects"></span><h1>Floating Point Objects<a class="headerlink" href="#floating-point-objects" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><dl class="type">
<dt id="c.PyFloatObject">
<code class="descname">PyFloatObject</code><a class="headerlink" href="#c.PyFloatObject" title="Permalink to this definition">¶</a></dt>
<dd><p>This subtype of <a class="reference internal" href="structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> represents a Python floating point object.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyFloat_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyFloat_Type</code><a class="headerlink" href="#c.PyFloat_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> represents the Python floating point
type.  This is the same object as <code class="docutils literal notranslate"><span class="pre">float</span></code> and <code class="docutils literal notranslate"><span class="pre">types.FloatType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_Check">
int <code class="descname">PyFloat_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a> or a subtype of
<a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Allowed subtypes to be accepted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_CheckExact">
int <code class="descname">PyFloat_CheckExact</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*p</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_CheckExact" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if its argument is a <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a>, but not a subtype of
<a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_FromString">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFloat_FromString</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*str</em>, char<em>&nbsp;**pend</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_FromString" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a> object based on the string value in <em>str</em>, or
<em>NULL</em> on failure.  The <em>pend</em> argument is ignored.  It remains only for
backward compatibility.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_FromDouble">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFloat_FromDouble</code><span class="sig-paren">(</span>double<em>&nbsp;v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_FromDouble" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Create a <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyFloatObject</span></code></a> object from <em>v</em>, or <em>NULL</em> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_AsDouble">
double <code class="descname">PyFloat_AsDouble</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pyfloat</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_AsDouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> representation of the contents of <em>pyfloat</em>.  If
<em>pyfloat</em> is not a Python floating point object but has a <a class="reference internal" href="../reference/datamodel.html#object.__float__" title="object.__float__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__float__()</span></code></a>
method, this method will first be called to convert <em>pyfloat</em> into a float.
This method returns <code class="docutils literal notranslate"><span class="pre">-1.0</span></code> upon failure, so one should call
<a class="reference internal" href="exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to check for errors.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_AS_DOUBLE">
double <code class="descname">PyFloat_AS_DOUBLE</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*pyfloat</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_AS_DOUBLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> representation of the contents of <em>pyfloat</em>, but
without error checking.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_GetInfo">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFloat_GetInfo</code><span class="sig-paren">(</span>void<span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_GetInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a structseq instance which contains information about the
precision, minimum and maximum values of a float. It’s a thin wrapper
around the header file <code class="file docutils literal notranslate"><span class="pre">float.h</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_GetMax">
double <code class="descname">PyFloat_GetMax</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_GetMax" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the maximum representable finite float <em>DBL_MAX</em> as C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_GetMin">
double <code class="descname">PyFloat_GetMin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_GetMin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the minimum normalized positive float <em>DBL_MIN</em> as C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_ClearFreeList">
int <code class="descname">PyFloat_ClearFreeList</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_ClearFreeList" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the float free list. Return the number of items that could not
be freed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_AsString">
void <code class="descname">PyFloat_AsString</code><span class="sig-paren">(</span>char<em>&nbsp;*buf</em>, <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject">PyFloatObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_AsString" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the argument <em>v</em> to a string, using the same rules as
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>. The length of <em>buf</em> should be at least 100.</p>
<p>This function is unsafe to call because it writes to a buffer whose
length it does not know.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="xref py py-func docutils literal notranslate"><span class="pre">PyObject_Str()</span></code> or <code class="xref py py-func docutils literal notranslate"><span class="pre">PyOS_double_to_string()</span></code> instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyFloat_AsReprString">
void <code class="descname">PyFloat_AsReprString</code><span class="sig-paren">(</span>char<em>&nbsp;*buf</em>, <a class="reference internal" href="#c.PyFloatObject" title="PyFloatObject">PyFloatObject</a><em>&nbsp;*v</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFloat_AsReprString" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as PyFloat_AsString, except uses the same rules as
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  The length of <em>buf</em> should be at least 100.</p>
<p>This function is unsafe to call because it writes to a buffer whose
length it does not know.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="xref py py-func docutils literal notranslate"><span class="pre">PyObject_Repr()</span></code> or <code class="xref py py-func docutils literal notranslate"><span class="pre">PyOS_double_to_string()</span></code> instead.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="long.html"
                        title="previous chapter">Long Integer Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="complex.html"
                        title="next chapter">Complex Number Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/float.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="complex.html" title="Complex Number Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="long.html" title="Long Integer Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\I;sy�7�7html/c-api/function.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Function Objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Method Objects" href="method.html" />
    <link rel="prev" title="Class and Instance Objects" href="class.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/function.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="method.html" title="Method Objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="class.html" title="Class and Instance Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" accesskey="U">Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="function-objects">
<span id="id1"></span><h1>Function Objects<a class="headerlink" href="#function-objects" title="Permalink to this headline">¶</a></h1>
<p id="index-0">There are a few functions specific to Python functions.</p>
<dl class="type">
<dt id="c.PyFunctionObject">
<code class="descname">PyFunctionObject</code><a class="headerlink" href="#c.PyFunctionObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The C structure used for functions.</p>
</dd></dl>

<dl class="var">
<dt id="c.PyFunction_Type">
<a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a> <code class="descname">PyFunction_Type</code><a class="headerlink" href="#c.PyFunction_Type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This is an instance of <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> and represents the Python function
type.  It is exposed to Python programmers as <code class="docutils literal notranslate"><span class="pre">types.FunctionType</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_Check">
int <code class="descname">PyFunction_Check</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_Check" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>o</em> is a function object (has type <a class="reference internal" href="#c.PyFunction_Type" title="PyFunction_Type"><code class="xref c c-data docutils literal notranslate"><span class="pre">PyFunction_Type</span></code></a>).
The parameter must not be <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_New">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_New</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*code</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*globals</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_New" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: New reference.</em><p>Return a new function object associated with the code object <em>code</em>. <em>globals</em>
must be a dictionary with the global variables accessible to the function.</p>
<p>The function’s docstring, name and <em>__module__</em> are retrieved from the code
object, the argument defaults and closure are set to <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_GetCode">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_GetCode</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_GetCode" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the code object associated with the function object <em>op</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_GetGlobals">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_GetGlobals</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_GetGlobals" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the globals dictionary associated with the function object <em>op</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_GetModule">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_GetModule</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_GetModule" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the <em>__module__</em> attribute of the function object <em>op</em>. This is normally
a string containing the module name, but can be set to any other object by
Python code.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_GetDefaults">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_GetDefaults</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_GetDefaults" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the argument default values of the function object <em>op</em>. This can be a
tuple of arguments or <em>NULL</em>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_SetDefaults">
int <code class="descname">PyFunction_SetDefaults</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*defaults</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_SetDefaults" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the argument default values for the function object <em>op</em>. <em>defaults</em> must be
<em>Py_None</em> or a tuple.</p>
<p>Raises <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> and returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_GetClosure">
<a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a>* <code class="descname">PyFunction_GetClosure</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_GetClosure" title="Permalink to this definition">¶</a></dt>
<dd><em class="refcount">Return value: Borrowed reference.</em><p>Return the closure associated with the function object <em>op</em>. This can be <em>NULL</em>
or a tuple of cell objects.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyFunction_SetClosure">
int <code class="descname">PyFunction_SetClosure</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em>, <a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*closure</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyFunction_SetClosure" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the closure associated with the function object <em>op</em>. <em>closure</em> must be
<em>Py_None</em> or a tuple of cell objects.</p>
<p>Raises <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> and returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="class.html"
                        title="previous chapter">Class and Instance Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="method.html"
                        title="next chapter">Method Objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/function.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="method.html" title="Method Objects"
             >next</a> |</li>
        <li class="right" >
          <a href="class.html" title="Class and Instance Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="concrete.html" >Concrete Objects Layer</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��z�F]F]html/c-api/gcsupport.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Supporting Cyclic Garbage Collection &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Distributing Python Modules" href="../distributing/index.html" />
    <link rel="prev" title="Type Objects" href="typeobj.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/c-api/gcsupport.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../distributing/index.html" title="Distributing Python Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="typeobj.html" title="Type Objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" accesskey="U">Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="supporting-cyclic-garbage-collection">
<span id="supporting-cycle-detection"></span><h1>Supporting Cyclic Garbage Collection<a class="headerlink" href="#supporting-cyclic-garbage-collection" title="Permalink to this headline">¶</a></h1>
<p>Python’s support for detecting and collecting garbage which involves circular
references requires support from object types which are “containers” for other
objects which may also be containers.  Types which do not store references to
other objects, or which only store references to atomic types (such as numbers
or strings), do not need to provide any explicit support for garbage
collection.</p>
<p>To create a container type, the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_flags</span></code></a> field of the type object must
include the <a class="reference internal" href="typeobj.html#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> and provide an implementation of the
<a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler.  If instances of the type are mutable, a
<a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> implementation must also be provided.</p>
<dl class="data">
<dt>
<code class="descname">Py_TPFLAGS_HAVE_GC</code></dt>
<dd><p>Objects with a type with this flag set must conform with the rules
documented here.  For convenience these objects will be referred to as
container objects.</p>
</dd></dl>

<p>Constructors for container types must conform to two rules:</p>
<ol class="arabic simple">
<li>The memory for the object must be allocated using <a class="reference internal" href="#c.PyObject_GC_New" title="PyObject_GC_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_New()</span></code></a>
or <a class="reference internal" href="#c.PyObject_GC_NewVar" title="PyObject_GC_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_NewVar()</span></code></a>.</li>
<li>Once all the fields which may contain references to other containers are
initialized, it must call <a class="reference internal" href="#c.PyObject_GC_Track" title="PyObject_GC_Track"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Track()</span></code></a>.</li>
</ol>
<dl class="function">
<dt id="c.PyObject_GC_New">
TYPE* <code class="descname">PyObject_GC_New</code><span class="sig-paren">(</span>TYPE, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_New" title="Permalink to this definition">¶</a></dt>
<dd><p>Analogous to <a class="reference internal" href="allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a> but for container objects with the
<a class="reference internal" href="typeobj.html#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag set.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GC_NewVar">
TYPE* <code class="descname">PyObject_GC_NewVar</code><span class="sig-paren">(</span>TYPE, <a class="reference internal" href="type.html#c.PyTypeObject" title="PyTypeObject">PyTypeObject</a><em>&nbsp;*type</em>, Py_ssize_t<em>&nbsp;size</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_NewVar" title="Permalink to this definition">¶</a></dt>
<dd><p>Analogous to <a class="reference internal" href="allocation.html#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_NewVar()</span></code></a> but for container objects with the
<a class="reference internal" href="typeobj.html#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag set.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>size</em>. This might require
changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GC_Resize">
TYPE* <code class="descname">PyObject_GC_Resize</code><span class="sig-paren">(</span>TYPE, <a class="reference internal" href="structures.html#c.PyVarObject" title="PyVarObject">PyVarObject</a><em>&nbsp;*op</em>, Py_ssize_t<em>&nbsp;newsize</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_Resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Resize an object allocated by <a class="reference internal" href="allocation.html#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_NewVar()</span></code></a>.  Returns the
resized object or <em>NULL</em> on failure.  <em>op</em> must not be tracked by the collector yet.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function used an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type for <em>newsize</em>. This might
require changes in your code for properly supporting 64-bit systems.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GC_Track">
void <code class="descname">PyObject_GC_Track</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_Track" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the object <em>op</em> to the set of container objects tracked by the
collector.  The collector can run at unexpected times so objects must be
valid while being tracked.  This should be called once all the fields
followed by the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler become valid, usually near the
end of the constructor.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyObject_GC_TRACK">
void <code class="descname">_PyObject_GC_TRACK</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyObject_GC_TRACK" title="Permalink to this definition">¶</a></dt>
<dd><p>A macro version of <a class="reference internal" href="#c.PyObject_GC_Track" title="PyObject_GC_Track"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Track()</span></code></a>.  It should not be used for
extension modules.</p>
</dd></dl>

<p>Similarly, the deallocator for the object must conform to a similar pair of
rules:</p>
<ol class="arabic simple">
<li>Before fields which refer to other containers are invalidated,
<a class="reference internal" href="#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_UnTrack()</span></code></a> must be called.</li>
<li>The object’s memory must be deallocated using <a class="reference internal" href="#c.PyObject_GC_Del" title="PyObject_GC_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Del()</span></code></a>.</li>
</ol>
<dl class="function">
<dt id="c.PyObject_GC_Del">
void <code class="descname">PyObject_GC_Del</code><span class="sig-paren">(</span>void<em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_Del" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases memory allocated to an object using <a class="reference internal" href="#c.PyObject_GC_New" title="PyObject_GC_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_New()</span></code></a> or
<a class="reference internal" href="#c.PyObject_GC_NewVar" title="PyObject_GC_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_NewVar()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="c.PyObject_GC_UnTrack">
void <code class="descname">PyObject_GC_UnTrack</code><span class="sig-paren">(</span>void<em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c.PyObject_GC_UnTrack" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the object <em>op</em> from the set of container objects tracked by the
collector.  Note that <a class="reference internal" href="#c.PyObject_GC_Track" title="PyObject_GC_Track"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Track()</span></code></a> can be called again on
this object to add it back to the set of tracked objects.  The deallocator
(<a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> handler) should call this for the object before any of
the fields used by the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler become invalid.</p>
</dd></dl>

<dl class="function">
<dt id="c._PyObject_GC_UNTRACK">
void <code class="descname">_PyObject_GC_UNTRACK</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*op</em><span class="sig-paren">)</span><a class="headerlink" href="#c._PyObject_GC_UNTRACK" title="Permalink to this definition">¶</a></dt>
<dd><p>A macro version of <a class="reference internal" href="#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_UnTrack()</span></code></a>.  It should not be used for
extension modules.</p>
</dd></dl>

<p>The <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler accepts a function parameter of this type:</p>
<dl class="type">
<dt id="c.visitproc">
int <code class="descname">(*visitproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*object</em>, void<em>&nbsp;*arg</em><span class="sig-paren">)</span><a class="headerlink" href="#c.visitproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Type of the visitor function passed to the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler.
The function should be called with an object to traverse as <em>object</em> and
the third parameter to the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler as <em>arg</em>.  The
Python core uses several visitor functions to implement cyclic garbage
detection; it’s not expected that users will need to write their own
visitor functions.</p>
</dd></dl>

<p>The <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler must have the following type:</p>
<dl class="type">
<dt id="c.traverseproc">
int <code class="descname">(*traverseproc)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em>, <a class="reference internal" href="#c.visitproc" title="visitproc">visitproc</a><em>&nbsp;visit</em>, void<em>&nbsp;*arg</em><span class="sig-paren">)</span><a class="headerlink" href="#c.traverseproc" title="Permalink to this definition">¶</a></dt>
<dd><p>Traversal function for a container object.  Implementations must call the
<em>visit</em> function for each object directly contained by <em>self</em>, with the
parameters to <em>visit</em> being the contained object and the <em>arg</em> value passed
to the handler.  The <em>visit</em> function must not be called with a <em>NULL</em>
object argument.  If <em>visit</em> returns a non-zero value that value should be
returned immediately.</p>
</dd></dl>

<p>To simplify writing <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handlers, a <a class="reference internal" href="#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a> macro is
provided.  In order to use this macro, the <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> implementation
must name its arguments exactly <em>visit</em> and <em>arg</em>:</p>
<dl class="function">
<dt id="c.Py_VISIT">
void <code class="descname">Py_VISIT</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*o</em><span class="sig-paren">)</span><a class="headerlink" href="#c.Py_VISIT" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>o</em> is not <em>NULL</em>, call the <em>visit</em> callback, with arguments <em>o</em>
and <em>arg</em>.  If <em>visit</em> returns a non-zero value, then return it.
Using this macro, <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handlers
look like:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">my_traverse</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">foo</span><span class="p">);</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">bar</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="typeobj.html#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_clear</span></code></a> handler must be of the <a class="reference internal" href="#c.inquiry" title="inquiry"><code class="xref c c-type docutils literal notranslate"><span class="pre">inquiry</span></code></a> type, or <em>NULL</em>
if the object is immutable.</p>
<dl class="type">
<dt id="c.inquiry">
int <code class="descname">(*inquiry)</code><span class="sig-paren">(</span><a class="reference internal" href="structures.html#c.PyObject" title="PyObject">PyObject</a><em>&nbsp;*self</em><span class="sig-paren">)</span><a class="headerlink" href="#c.inquiry" title="Permalink to this definition">¶</a></dt>
<dd><p>Drop references that may have created reference cycles.  Immutable objects
do not have to define this method since they can never directly create
reference cycles.  Note that the object must still be valid after calling
this method (don’t just call <a class="reference internal" href="refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> on a reference).  The
collector will call this method if it detects that this object is involved
in a reference cycle.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="typeobj.html"
                        title="previous chapter">Type Objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../distributing/index.html"
                        title="next chapter">Distributing Python Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/c-api/gcsupport.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../distributing/index.html" title="Distributing Python Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="typeobj.html" title="Type Objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python/C API Reference Manual</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="objimpl.html" >Object Implementation Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\,�~!F!Fhtml/distributing/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Distributing Python Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Installing Python Modules" href="../installing/index.html" />
    <link rel="prev" title="Supporting Cyclic Garbage Collection" href="../c-api/gcsupport.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distributing/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../installing/index.html" title="Installing Python Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../c-api/gcsupport.html" title="Supporting Cyclic Garbage Collection"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="distributing-python-modules">
<span id="distributing-index"></span><h1>Distributing Python Modules<a class="headerlink" href="#distributing-python-modules" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Email:</th><td class="field-body"><a class="reference external" href="mailto:distutils-sig&#37;&#52;&#48;python&#46;org">distutils-sig<span>&#64;</span>python<span>&#46;</span>org</a></td>
</tr>
</tbody>
</table>
<p>As a popular open source development project, Python has an active
supporting community of contributors and users that also make their software
available for other Python developers to use under open source license terms.</p>
<p>This allows Python users to share and collaborate effectively, benefiting
from the solutions others have already created to common (and sometimes
even rare!) problems, as well as potentially contributing their own
solutions to the common pool.</p>
<p>This guide covers the distribution part of the process. For a guide to
installing other Python projects, refer to the
<a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">installation guide</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For corporate and other institutional users, be aware that many
organisations have their own policies around using and contributing to
open source software. Please take such policies into account when making
use of the distribution and installation tools provided with Python.</p>
</div>
<div class="section" id="key-terms">
<h2>Key terms<a class="headerlink" href="#key-terms" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>the <a class="reference external" href="https://pypi.org">Python Packaging Index</a> is a public
repository of open source licensed packages made available for use by
other Python users</li>
<li>the <a class="reference external" href="https://www.pypa.io/">Python Packaging Authority</a> are the group of
developers and documentation authors responsible for the maintenance and
evolution of the standard packaging tools and the associated metadata and
file format standards. They maintain a variety of tools, documentation
and issue trackers on both <a class="reference external" href="https://github.com/pypa">GitHub</a> and
<a class="reference external" href="https://bitbucket.org/pypa/">BitBucket</a>.</li>
<li><a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> is the original build and distribution system first added
to the Python standard library in 1998. While direct use of <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a>
is being phased out, it still laid the foundation for the current packaging
and distribution infrastructure, and it not only remains part of the
standard library, but its name lives on in other ways (such as the name
of the mailing list used to coordinate Python packaging standards
development).</li>
<li><a class="reference external" href="https://setuptools.readthedocs.io/en/latest/">setuptools</a> is a (largely) drop-in replacement for <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> first
published in 2004. Its most notable addition over the unmodified
<a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> tools was the ability to declare dependencies on other
packages. It is currently recommended as a more regularly updated
alternative to <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> that offers consistent support for more
recent packaging standards across a wide range of Python versions.</li>
<li><a class="reference external" href="https://wheel.readthedocs.org">wheel</a> (in this context) is a project that adds the <code class="docutils literal notranslate"><span class="pre">bdist_wheel</span></code>
command to <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a>/<a class="reference external" href="https://setuptools.readthedocs.io/en/latest/">setuptools</a>. This produces a cross platform
binary packaging format (called “wheels” or “wheel files” and defined in
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0427"><strong>PEP 427</strong></a>) that allows Python libraries, even those including binary
extensions, to be installed on a system without needing to be built
locally.</li>
</ul>
</div>
<div class="section" id="open-source-licensing-and-collaboration">
<h2>Open source licensing and collaboration<a class="headerlink" href="#open-source-licensing-and-collaboration" title="Permalink to this headline">¶</a></h2>
<p>In most parts of the world, software is automatically covered by copyright.
This means that other developers require explicit permission to copy, use,
modify and redistribute the software.</p>
<p>Open source licensing is a way of explicitly granting such permission in a
relatively consistent way, allowing developers to share and collaborate
efficiently by making common solutions to various problems freely available.
This leaves many developers free to spend more time focusing on the problems
that are relatively unique to their specific situation.</p>
<p>The distribution tools provided with Python are designed to make it
reasonably straightforward for developers to make their own contributions
back to that common pool of software if they choose to do so.</p>
<p>The same distribution tools can also be used to distribute software within
an organisation, regardless of whether that software is published as open
source software or not.</p>
</div>
<div class="section" id="installing-the-tools">
<h2>Installing the tools<a class="headerlink" href="#installing-the-tools" title="Permalink to this headline">¶</a></h2>
<p>The standard library does not include build tools that support modern
Python packaging standards, as the core development team has found that it
is important to have standard tools that work consistently, even on older
versions of Python.</p>
<p>The currently recommended build and distribution tools can be installed
by invoking the <code class="docutils literal notranslate"><span class="pre">pip</span></code> module at the command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">pip</span> <span class="n">install</span> <span class="n">setuptools</span> <span class="n">wheel</span> <span class="n">twine</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>For POSIX users (including Mac OS X and Linux users), these instructions
assume the use of a <a class="reference internal" href="../glossary.html#term-virtual-environment"><span class="xref std std-term">virtual environment</span></a>.</p>
<p class="last">For Windows users, these instructions assume that the option to
adjust the system PATH environment variable was selected when installing
Python.</p>
</div>
<p>The Python Packaging User Guide includes more details on the <a class="reference external" href="https://packaging.python.org/en/latest/current/#packaging-tool-recommendations">currently
recommended tools</a>.</p>
</div>
<div class="section" id="reading-the-guide">
<h2>Reading the guide<a class="headerlink" href="#reading-the-guide" title="Permalink to this headline">¶</a></h2>
<p>The Python Packaging User Guide covers the various key steps and elements
involved in creating a project:</p>
<ul class="simple">
<li><a class="reference external" href=" https://packaging.python.org/en/latest/distributing/">Project structure</a></li>
<li><a class="reference external" href=" https://packaging.python.org/en/latest/distributing/#packaging-your-project">Building and packaging the project</a></li>
<li><a class="reference external" href=" https://packaging.python.org/en/latest/distributing/#uploading-your-project-to-pypi">Uploading the project to the Python Packaging Index</a></li>
</ul>
</div>
<div class="section" id="how-do-i">
<h2>How do I…?<a class="headerlink" href="#how-do-i" title="Permalink to this headline">¶</a></h2>
<p>These are quick answers or links for some common tasks.</p>
<div class="section" id="choose-a-name-for-my-project">
<h3>… choose a name for my project?<a class="headerlink" href="#choose-a-name-for-my-project" title="Permalink to this headline">¶</a></h3>
<p>This isn’t an easy topic, but here are a few tips:</p>
<ul class="simple">
<li>check the Python Packaging Index to see if the name is already in use</li>
<li>check popular hosting sites like GitHub, BitBucket, etc to see if there
is already a project with that name</li>
<li>check what comes up in a web search for the name you’re considering</li>
<li>avoid particularly common words, especially ones with multiple meanings,
as they can make it difficult for users to find your software when
searching for it</li>
</ul>
</div>
<div class="section" id="create-and-distribute-binary-extensions">
<h3>… create and distribute binary extensions?<a class="headerlink" href="#create-and-distribute-binary-extensions" title="Permalink to this headline">¶</a></h3>
<p>This is actually quite a complex topic, with a variety of alternatives
available depending on exactly what you’re aiming to achieve. See the
Python Packaging User Guide for more information and recommendations.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://packaging.python.org/en/latest/extensions">Python Packaging User Guide: Binary Extensions</a></p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Distributing Python Modules</a><ul>
<li><a class="reference internal" href="#key-terms">Key terms</a></li>
<li><a class="reference internal" href="#open-source-licensing-and-collaboration">Open source licensing and collaboration</a></li>
<li><a class="reference internal" href="#installing-the-tools">Installing the tools</a></li>
<li><a class="reference internal" href="#reading-the-guide">Reading the guide</a></li>
<li><a class="reference internal" href="#how-do-i">How do I…?</a><ul>
<li><a class="reference internal" href="#choose-a-name-for-my-project">… choose a name for my project?</a></li>
<li><a class="reference internal" href="#create-and-distribute-binary-extensions">… create and distribute binary extensions?</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="../c-api/gcsupport.html"
                        title="previous chapter">Supporting Cyclic Garbage Collection</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../installing/index.html"
                        title="next chapter">Installing Python Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distributing/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../installing/index.html" title="Installing Python Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="../c-api/gcsupport.html" title="Supporting Cyclic Garbage Collection"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\)��b�b�html/distutils/apiref.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10. API Reference &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Installing Python Modules (Legacy version)" href="../install/index.html" />
    <link rel="prev" title="9. Command Reference" href="commandref.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/apiref.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../install/index.html" title="Installing Python Modules (Legacy version)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="commandref.html" title="9. Command Reference"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="api-reference">
<span id="id1"></span><h1>10. API Reference<a class="headerlink" href="#api-reference" title="Permalink to this headline">¶</a></h1>
<div class="section" id="module-distutils.core">
<span id="distutils-core-core-distutils-functionality"></span><h2>10.1. <a class="reference internal" href="#module-distutils.core" title="distutils.core: The core Distutils functionality"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.core</span></code></a> — Core Distutils functionality<a class="headerlink" href="#module-distutils.core" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-distutils.core" title="distutils.core: The core Distutils functionality"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.core</span></code></a> module is the only module that needs to be installed
to use the Distutils. It provides the <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a> (which is called from the
setup script). Indirectly provides the  <code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.dist.Distribution</span></code> and
<a class="reference internal" href="#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.cmd.Command</span></code></a> class.</p>
<dl class="function">
<dt id="distutils.core.setup">
<code class="descclassname">distutils.core.</code><code class="descname">setup</code><span class="sig-paren">(</span><em>arguments</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.core.setup" title="Permalink to this definition">¶</a></dt>
<dd><p>The basic do-everything function that does most everything you could ever ask
for from a Distutils method.</p>
<p>The setup function takes a large number of arguments. These are laid out in the
following table.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="28%" />
<col width="54%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">argument name</th>
<th class="head">value</th>
<th class="head">type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>name</em></td>
<td>The name of the package</td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>version</em></td>
<td>The version number of the
package; see
<a class="reference internal" href="#module-distutils.version" title="distutils.version: implements classes that represent module version numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.version</span></code></a></td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>description</em></td>
<td>A single line describing the
package</td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>long_description</em></td>
<td>Longer description of the
package</td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>author</em></td>
<td>The name of the package author</td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>author_email</em></td>
<td>The email address of the
package author</td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>maintainer</em></td>
<td>The name of the current
maintainer, if different from
the author. Note that if
the maintainer is provided,
distutils will use it as the
author in <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code></td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>maintainer_email</em></td>
<td>The email address of the
current maintainer, if
different from the author</td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>url</em></td>
<td>A URL for the package
(homepage)</td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>download_url</em></td>
<td>A URL to download the package</td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>packages</em></td>
<td>A list of Python packages that
distutils will manipulate</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>py_modules</em></td>
<td>A list of Python modules that
distutils will manipulate</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>scripts</em></td>
<td>A list of standalone script
files to be built and
installed</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>ext_modules</em></td>
<td>A list of Python extensions to
be built</td>
<td>a list of instances of
<a class="reference internal" href="#distutils.core.Extension" title="distutils.core.Extension"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.core.Extension</span></code></a></td>
</tr>
<tr class="row-even"><td><em>classifiers</em></td>
<td>A list of categories for the
package</td>
<td>a list of strings; valid classifiers are listed on <a class="reference external" href="https://pypi.org/classifiers">PyPI</a>.</td>
</tr>
<tr class="row-odd"><td><em>distclass</em></td>
<td>the <a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a>
class to use</td>
<td>a subclass of
<a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.core.Distribution</span></code></a></td>
</tr>
<tr class="row-even"><td><em>script_name</em></td>
<td>The name of the setup.py
script - defaults to
<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code></td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>script_args</em></td>
<td>Arguments to supply to the
setup script</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>options</em></td>
<td>default options for the setup
script</td>
<td>a dictionary</td>
</tr>
<tr class="row-odd"><td><em>license</em></td>
<td>The license for the package</td>
<td>a string</td>
</tr>
<tr class="row-even"><td><em>keywords</em></td>
<td>Descriptive meta-data, see
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0314"><strong>PEP 314</strong></a></td>
<td>a list of strings or a comma-separated string</td>
</tr>
<tr class="row-odd"><td><em>platforms</em></td>
<td>&#160;</td>
<td>a list of strings or a comma-separated string</td>
</tr>
<tr class="row-even"><td><em>cmdclass</em></td>
<td>A mapping of command names to
<a class="reference internal" href="#distutils.core.Command" title="distutils.core.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code></a> subclasses</td>
<td>a dictionary</td>
</tr>
<tr class="row-odd"><td><em>data_files</em></td>
<td>A list of data files to
install</td>
<td>a list</td>
</tr>
<tr class="row-even"><td><em>package_dir</em></td>
<td>A mapping of package to
directory names</td>
<td>a dictionary</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="distutils.core.run_setup">
<code class="descclassname">distutils.core.</code><code class="descname">run_setup</code><span class="sig-paren">(</span><em>script_name</em><span class="optional">[</span>, <em>script_args=None</em>, <em>stop_after='run'</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.core.run_setup" title="Permalink to this definition">¶</a></dt>
<dd><p>Run a setup script in a somewhat controlled environment, and return  the
<code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.dist.Distribution</span></code> instance that drives things.   This is
useful if you need to find out the distribution meta-data  (passed as keyword
args from <em>script</em> to <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a>), or  the contents of the config files or
command-line.</p>
<p><em>script_name</em> is a file that will be run with <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>
will be replaced with <em>script</em> for the duration of the call.  <em>script_args</em> is a
list of strings; if supplied, <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code> will be replaced by <em>script_args</em>
for the duration  of the call.</p>
<p><em>stop_after</em> tells <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a> when to stop processing; possible  values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">value</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>init</em></td>
<td>Stop after the <a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a>
instance has been created  and populated
with the keyword arguments to <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a></td>
</tr>
<tr class="row-odd"><td><em>config</em></td>
<td>Stop after config files have been parsed
(and their data stored in the
<a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a> instance)</td>
</tr>
<tr class="row-even"><td><em>commandline</em></td>
<td>Stop after the command-line
(<code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code> or  <em>script_args</em>) have
been parsed (and the data stored in the
<a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a> instance.)</td>
</tr>
<tr class="row-odd"><td><em>run</em></td>
<td>Stop after all commands have been run (the
same as  if <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a> had been called
in the usual way). This is the default
value.</td>
</tr>
</tbody>
</table>
</dd></dl>

<p>In addition, the <a class="reference internal" href="#module-distutils.core" title="distutils.core: The core Distutils functionality"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.core</span></code></a> module exposed a number of  classes that
live elsewhere.</p>
<ul class="simple">
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> from <a class="reference internal" href="#module-distutils.extension" title="distutils.extension: Provides the Extension class, used to describe C/C++ extension modules in setup scripts"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.extension</span></code></a></li>
<li><a class="reference internal" href="#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code></a> from <a class="reference internal" href="#module-distutils.cmd" title="distutils.cmd: This module provides the abstract base class Command. This class is subclassed by the modules in the distutils.command subpackage."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.cmd</span></code></a></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code> from <a class="reference internal" href="#module-distutils.dist" title="distutils.dist: Provides the Distribution class, which represents the module distribution being built/installed/distributed"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.dist</span></code></a></li>
</ul>
<p>A short description of each of these follows, but see the relevant module for
the full reference.</p>
<dl class="class">
<dt id="distutils.core.Extension">
<em class="property">class </em><code class="descclassname">distutils.core.</code><code class="descname">Extension</code><a class="headerlink" href="#distutils.core.Extension" title="Permalink to this definition">¶</a></dt>
<dd><p>The Extension class describes a single C or C++ extension module in a setup
script. It accepts the following keyword arguments in its constructor</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="39%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">argument name</th>
<th class="head">value</th>
<th class="head">type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>name</em></td>
<td>the full name of the
extension, including any
packages — ie. <em>not</em> a
filename or pathname, but
Python dotted name</td>
<td>a string</td>
</tr>
<tr class="row-odd"><td><em>sources</em></td>
<td>list of source filenames,
relative to the distribution
root (where the setup script
lives), in Unix form (slash-
separated) for portability.
Source files may be C, C++,
SWIG (.i), platform-specific
resource files, or whatever
else is recognized by the
<strong class="command">build_ext</strong> command
as source for a Python
extension.</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>include_dirs</em></td>
<td>list of directories to search
for C/C++ header files (in
Unix form for portability)</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>define_macros</em></td>
<td>list of macros to define; each
macro is defined using a
2-tuple <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code>,
where <em>value</em> is
either the string to define it
to or <code class="docutils literal notranslate"><span class="pre">None</span></code> to define it
without a particular value
(equivalent of <code class="docutils literal notranslate"><span class="pre">#define</span> <span class="pre">FOO</span></code>
in source or <code class="xref std std-option docutils literal notranslate"><span class="pre">-DFOO</span></code>
on Unix C compiler command
line)</td>
<td>a list of tuples</td>
</tr>
<tr class="row-even"><td><em>undef_macros</em></td>
<td>list of macros to undefine
explicitly</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>library_dirs</em></td>
<td>list of directories to search
for C/C++ libraries at link
time</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>libraries</em></td>
<td>list of library names (not
filenames or paths) to link
against</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>runtime_library_dirs</em></td>
<td>list of directories to search
for C/C++ libraries at run
time (for shared extensions,
this is when the extension is
loaded)</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>extra_objects</em></td>
<td>list of extra files to link
with (eg. object files not
implied by ‘sources’, static
library that must be
explicitly specified, binary
resource files, etc.)</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>extra_compile_args</em></td>
<td>any extra platform- and
compiler-specific information
to use when compiling the
source files in ‘sources’. For
platforms and compilers where
a command line makes sense,
this is typically a list of
command-line arguments, but
for other platforms it could
be anything.</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>extra_link_args</em></td>
<td>any extra platform- and
compiler-specific information
to use when linking object
files together to create the
extension (or to create a new
static Python interpreter).
Similar interpretation as for
‘extra_compile_args’.</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>export_symbols</em></td>
<td>list of symbols to be exported
from a shared extension. Not
used on all platforms, and not
generally necessary for Python
extensions, which typically
export exactly one symbol:
<code class="docutils literal notranslate"><span class="pre">init</span></code> + extension_name.</td>
<td>a list of strings</td>
</tr>
<tr class="row-even"><td><em>depends</em></td>
<td>list of files that the
extension depends on</td>
<td>a list of strings</td>
</tr>
<tr class="row-odd"><td><em>language</em></td>
<td>extension language (i.e.
<code class="docutils literal notranslate"><span class="pre">'c'</span></code>, <code class="docutils literal notranslate"><span class="pre">'c++'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'objc'</span></code>). Will be detected
from the source extensions if
not provided.</td>
<td>a string</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="class">
<dt id="distutils.core.Distribution">
<em class="property">class </em><code class="descclassname">distutils.core.</code><code class="descname">Distribution</code><a class="headerlink" href="#distutils.core.Distribution" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a> describes how to build, install and package up a Python
software package.</p>
<p>See the <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a> function for a list of keyword arguments accepted  by the
Distribution constructor. <a class="reference internal" href="#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a> creates a Distribution instance.</p>
</dd></dl>

<dl class="class">
<dt id="distutils.core.Command">
<em class="property">class </em><code class="descclassname">distutils.core.</code><code class="descname">Command</code><a class="headerlink" href="#distutils.core.Command" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#distutils.core.Command" title="distutils.core.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code></a> class (or rather, an instance of one of its subclasses)
implement a single distutils command.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.ccompiler">
<span id="distutils-ccompiler-ccompiler-base-class"></span><h2>10.2. <a class="reference internal" href="#module-distutils.ccompiler" title="distutils.ccompiler: Abstract CCompiler class"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.ccompiler</span></code></a> — CCompiler base class<a class="headerlink" href="#module-distutils.ccompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides the abstract base class for the <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a>
classes.  A <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a> instance can be used for all the compile  and
link steps needed to build a single project. Methods are provided to  set
options for the compiler — macro definitions, include directories,  link path,
libraries and the like.</p>
<p>This module provides the following functions.</p>
<dl class="function">
<dt id="distutils.ccompiler.gen_lib_options">
<code class="descclassname">distutils.ccompiler.</code><code class="descname">gen_lib_options</code><span class="sig-paren">(</span><em>compiler</em>, <em>library_dirs</em>, <em>runtime_library_dirs</em>, <em>libraries</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.gen_lib_options" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate linker options for searching library directories and linking with
specific libraries.  <em>libraries</em> and <em>library_dirs</em> are, respectively, lists of
library names (not filenames!) and search directories.  Returns a list of
command-line options suitable for use with some compiler (depending on the two
format strings passed in).</p>
</dd></dl>

<dl class="function">
<dt id="distutils.ccompiler.gen_preprocess_options">
<code class="descclassname">distutils.ccompiler.</code><code class="descname">gen_preprocess_options</code><span class="sig-paren">(</span><em>macros</em>, <em>include_dirs</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.gen_preprocess_options" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate C pre-processor options (<code class="xref std std-option docutils literal notranslate"><span class="pre">-D</span></code>, <code class="xref std std-option docutils literal notranslate"><span class="pre">-U</span></code>, <code class="xref std std-option docutils literal notranslate"><span class="pre">-I</span></code>) as
used by at least two types of compilers: the typical Unix compiler and Visual
C++. <em>macros</em> is the usual thing, a list of 1- or 2-tuples, where <code class="docutils literal notranslate"><span class="pre">(name,)</span></code>
means undefine (<code class="xref std std-option docutils literal notranslate"><span class="pre">-U</span></code>) macro <em>name</em>, and <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> means define
(<code class="xref std std-option docutils literal notranslate"><span class="pre">-D</span></code>) macro <em>name</em> to <em>value</em>.  <em>include_dirs</em> is just a list of
directory names to be added to the header file search path (<code class="xref std std-option docutils literal notranslate"><span class="pre">-I</span></code>).
Returns a list of command-line options suitable for either Unix compilers or
Visual C++.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.ccompiler.get_default_compiler">
<code class="descclassname">distutils.ccompiler.</code><code class="descname">get_default_compiler</code><span class="sig-paren">(</span><em>osname</em>, <em>platform</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.get_default_compiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine the default compiler to use for the given platform.</p>
<p><em>osname</em> should be one of the standard Python OS names (i.e. the ones returned
by <code class="docutils literal notranslate"><span class="pre">os.name</span></code>) and <em>platform</em> the common value returned by <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code> for
the platform in question.</p>
<p>The default values are <code class="docutils literal notranslate"><span class="pre">os.name</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code> in case the parameters
are not given.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.ccompiler.new_compiler">
<code class="descclassname">distutils.ccompiler.</code><code class="descname">new_compiler</code><span class="sig-paren">(</span><em>plat=None</em>, <em>compiler=None</em>, <em>verbose=0</em>, <em>dry_run=0</em>, <em>force=0</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.new_compiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Factory function to generate an instance of some CCompiler subclass for the
supplied platform/compiler combination. <em>plat</em> defaults to <code class="docutils literal notranslate"><span class="pre">os.name</span></code> (eg.
<code class="docutils literal notranslate"><span class="pre">'posix'</span></code>, <code class="docutils literal notranslate"><span class="pre">'nt'</span></code>), and <em>compiler</em>  defaults to the default compiler for
that platform. Currently only <code class="docutils literal notranslate"><span class="pre">'posix'</span></code> and <code class="docutils literal notranslate"><span class="pre">'nt'</span></code> are supported, and the
default compilers are “traditional Unix interface” (<code class="xref py py-class docutils literal notranslate"><span class="pre">UnixCCompiler</span></code>
class) and Visual C++ (<code class="xref py py-class docutils literal notranslate"><span class="pre">MSVCCompiler</span></code> class).  Note that it’s perfectly
possible to ask for a Unix compiler object under Windows, and a Microsoft
compiler object under Unix—if you supply a value for <em>compiler</em>, <em>plat</em> is
ignored.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.ccompiler.show_compilers">
<code class="descclassname">distutils.ccompiler.</code><code class="descname">show_compilers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.show_compilers" title="Permalink to this definition">¶</a></dt>
<dd><p>Print list of available compilers (used by the <code class="xref std std-option docutils literal notranslate"><span class="pre">--help-compiler</span></code> options
to <strong class="command">build</strong>, <strong class="command">build_ext</strong>, <strong class="command">build_clib</strong>).</p>
</dd></dl>

<dl class="class">
<dt id="distutils.ccompiler.CCompiler">
<em class="property">class </em><code class="descclassname">distutils.ccompiler.</code><code class="descname">CCompiler</code><span class="sig-paren">(</span><span class="optional">[</span><em>verbose=0</em>, <em>dry_run=0</em>, <em>force=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler" title="Permalink to this definition">¶</a></dt>
<dd><p>The abstract base class <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a> defines the interface that  must be
implemented by real compiler classes.  The class also has  some utility methods
used by several compiler classes.</p>
<p>The basic idea behind a compiler abstraction class is that each instance can be
used for all the compile/link steps in building a single project.  Thus,
attributes common to all of those compile and link steps — include
directories, macros to define, libraries to link against, etc. — are
attributes of the compiler instance.  To allow for variability in how individual
files are treated, most of those attributes may be varied on a per-compilation
or per-link basis.</p>
<p>The constructor for each subclass creates an instance of the Compiler object.
Flags are <em>verbose</em> (show verbose output), <em>dry_run</em> (don’t actually execute the
steps) and <em>force</em> (rebuild everything, regardless of dependencies). All of
these flags default to <code class="docutils literal notranslate"><span class="pre">0</span></code> (off). Note that you probably don’t want to
instantiate <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a> or one of its subclasses directly - use the
<code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.CCompiler.new_compiler()</span></code> factory function instead.</p>
<p>The following methods allow you to manually alter compiler options for  the
instance of the Compiler class.</p>
<dl class="method">
<dt id="distutils.ccompiler.CCompiler.add_include_dir">
<code class="descname">add_include_dir</code><span class="sig-paren">(</span><em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.add_include_dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>dir</em> to the list of directories that will be searched for header files.
The compiler is instructed to search directories in the order in which they are
supplied by successive calls to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_include_dir" title="distutils.ccompiler.CCompiler.add_include_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_include_dir()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_include_dirs">
<code class="descname">set_include_dirs</code><span class="sig-paren">(</span><em>dirs</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_include_dirs" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of directories that will be searched to <em>dirs</em> (a list of strings).
Overrides any preceding calls to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_include_dir" title="distutils.ccompiler.CCompiler.add_include_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_include_dir()</span></code></a>; subsequent calls to
<a class="reference internal" href="#distutils.ccompiler.CCompiler.add_include_dir" title="distutils.ccompiler.CCompiler.add_include_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_include_dir()</span></code></a> add to the list passed to <a class="reference internal" href="#distutils.ccompiler.CCompiler.set_include_dirs" title="distutils.ccompiler.CCompiler.set_include_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_include_dirs()</span></code></a>.
This does not affect any list of standard include directories that the compiler
may search by default.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.add_library">
<code class="descname">add_library</code><span class="sig-paren">(</span><em>libname</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.add_library" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>libname</em> to the list of libraries that will be included in all links driven
by this compiler object.  Note that <em>libname</em> should *not* be the name of a
file containing a library, but the name of the library itself: the actual
filename will be inferred by the linker, the compiler, or the compiler class
(depending on the platform).</p>
<p>The linker will be instructed to link against libraries in the order they were
supplied to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_library" title="distutils.ccompiler.CCompiler.add_library"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_library()</span></code></a> and/or <a class="reference internal" href="#distutils.ccompiler.CCompiler.set_libraries" title="distutils.ccompiler.CCompiler.set_libraries"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_libraries()</span></code></a>.  It is perfectly
valid to duplicate library names; the linker will be instructed to link against
libraries as many times as they are mentioned.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_libraries">
<code class="descname">set_libraries</code><span class="sig-paren">(</span><em>libnames</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_libraries" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of libraries to be included in all links driven by this compiler
object to <em>libnames</em> (a list of strings).  This does not affect any standard
system libraries that the linker may include by default.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.add_library_dir">
<code class="descname">add_library_dir</code><span class="sig-paren">(</span><em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.add_library_dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>dir</em> to the list of directories that will be searched for libraries
specified to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_library" title="distutils.ccompiler.CCompiler.add_library"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_library()</span></code></a> and <a class="reference internal" href="#distutils.ccompiler.CCompiler.set_libraries" title="distutils.ccompiler.CCompiler.set_libraries"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_libraries()</span></code></a>.  The linker will be
instructed to search for libraries in the order they are supplied to
<a class="reference internal" href="#distutils.ccompiler.CCompiler.add_library_dir" title="distutils.ccompiler.CCompiler.add_library_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_library_dir()</span></code></a> and/or <a class="reference internal" href="#distutils.ccompiler.CCompiler.set_library_dirs" title="distutils.ccompiler.CCompiler.set_library_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_library_dirs()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_library_dirs">
<code class="descname">set_library_dirs</code><span class="sig-paren">(</span><em>dirs</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_library_dirs" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of library search directories to <em>dirs</em> (a list of strings).  This
does not affect any standard library search path that the linker may search by
default.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.add_runtime_library_dir">
<code class="descname">add_runtime_library_dir</code><span class="sig-paren">(</span><em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.add_runtime_library_dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>dir</em> to the list of directories that will be searched for shared libraries
at runtime.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_runtime_library_dirs">
<code class="descname">set_runtime_library_dirs</code><span class="sig-paren">(</span><em>dirs</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_runtime_library_dirs" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of directories to search for shared libraries at runtime to <em>dirs</em>
(a list of strings).  This does not affect any standard search path that the
runtime linker may search by default.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.define_macro">
<code class="descname">define_macro</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>value=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.define_macro" title="Permalink to this definition">¶</a></dt>
<dd><p>Define a preprocessor macro for all compilations driven by this compiler object.
The optional parameter <em>value</em> should be a string; if it is not supplied, then
the macro will be defined without an explicit value and the exact outcome
depends on the compiler used.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.undefine_macro">
<code class="descname">undefine_macro</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.undefine_macro" title="Permalink to this definition">¶</a></dt>
<dd><p>Undefine a preprocessor macro for all compilations driven by this compiler
object.  If the same macro is defined by <a class="reference internal" href="#distutils.ccompiler.CCompiler.define_macro" title="distutils.ccompiler.CCompiler.define_macro"><code class="xref py py-meth docutils literal notranslate"><span class="pre">define_macro()</span></code></a> and
undefined by <a class="reference internal" href="#distutils.ccompiler.CCompiler.undefine_macro" title="distutils.ccompiler.CCompiler.undefine_macro"><code class="xref py py-meth docutils literal notranslate"><span class="pre">undefine_macro()</span></code></a> the last call takes precedence
(including multiple redefinitions or undefinitions).  If the macro is
redefined/undefined on a per-compilation basis (ie. in the call to
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compile()</span></code></a>), then that takes precedence.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.add_link_object">
<code class="descname">add_link_object</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.add_link_object" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>object</em> to the list of object files (or analogues, such as explicitly named
library files or the output of “resource compilers”) to be included in every
link driven by this compiler object.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_link_objects">
<code class="descname">set_link_objects</code><span class="sig-paren">(</span><em>objects</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_link_objects" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of object files (or analogues) to be included in every link to
<em>objects</em>.  This does not affect any standard object files that the linker may
include by default (such as system libraries).</p>
</dd></dl>

<p>The following methods implement methods for autodetection of compiler  options,
providing some functionality similar to GNU <strong class="program">autoconf</strong>.</p>
<dl class="method">
<dt id="distutils.ccompiler.CCompiler.detect_language">
<code class="descname">detect_language</code><span class="sig-paren">(</span><em>sources</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.detect_language" title="Permalink to this definition">¶</a></dt>
<dd><p>Detect the language of a given file, or list of files. Uses the  instance
attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">language_map</span></code> (a dictionary), and  <code class="xref py py-attr docutils literal notranslate"><span class="pre">language_order</span></code> (a
list) to do the job.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.find_library_file">
<code class="descname">find_library_file</code><span class="sig-paren">(</span><em>dirs</em>, <em>lib</em><span class="optional">[</span>, <em>debug=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.find_library_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Search the specified list of directories for a static or shared library file
<em>lib</em> and return the full path to that file.  If <em>debug</em> is true, look for a
debugging version (if that makes sense on the current platform).  Return
<code class="docutils literal notranslate"><span class="pre">None</span></code> if <em>lib</em> wasn’t found in any of the specified directories.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.has_function">
<code class="descname">has_function</code><span class="sig-paren">(</span><em>funcname</em><span class="optional">[</span>, <em>includes=None</em>, <em>include_dirs=None</em>, <em>libraries=None</em>, <em>library_dirs=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.has_function" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a boolean indicating whether <em>funcname</em> is supported on the current
platform.  The optional arguments can be used to augment the compilation
environment by providing additional include files and paths and libraries and
paths.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.library_dir_option">
<code class="descname">library_dir_option</code><span class="sig-paren">(</span><em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.library_dir_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the compiler option to add <em>dir</em> to the list of directories searched for
libraries.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.library_option">
<code class="descname">library_option</code><span class="sig-paren">(</span><em>lib</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.library_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the compiler option to add <em>lib</em> to the list of libraries linked into the
shared library or executable.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.runtime_library_dir_option">
<code class="descname">runtime_library_dir_option</code><span class="sig-paren">(</span><em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.runtime_library_dir_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the compiler option to add <em>dir</em> to the list of directories searched for
runtime libraries.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.set_executables">
<code class="descname">set_executables</code><span class="sig-paren">(</span><em>**args</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.set_executables" title="Permalink to this definition">¶</a></dt>
<dd><p>Define the executables (and options for them) that will be run to perform the
various stages of compilation.  The exact set of executables that may be
specified here depends on the compiler class (via the ‘executables’ class
attribute), but most will have:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">attribute</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>compiler</em></td>
<td>the C/C++ compiler</td>
</tr>
<tr class="row-odd"><td><em>linker_so</em></td>
<td>linker used to create shared objects and
libraries</td>
</tr>
<tr class="row-even"><td><em>linker_exe</em></td>
<td>linker used to create binary executables</td>
</tr>
<tr class="row-odd"><td><em>archiver</em></td>
<td>static library creator</td>
</tr>
</tbody>
</table>
<p>On platforms with a command-line (Unix, DOS/Windows), each of these is a string
that will be split into executable name and (optional) list of arguments.
(Splitting the string is done similarly to how Unix shells operate: words are
delimited by spaces, but quotes and backslashes can override this.  See
<a class="reference internal" href="#distutils.util.split_quoted" title="distutils.util.split_quoted"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.util.split_quoted()</span></code></a>.)</p>
</dd></dl>

<p>The following methods invoke stages in the build process.</p>
<dl class="method">
<dt id="distutils.ccompiler.CCompiler.compile">
<code class="descname">compile</code><span class="sig-paren">(</span><em>sources</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>macros=None</em>, <em>include_dirs=None</em>, <em>debug=0</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em>, <em>depends=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile one or more source files. Generates object files (e.g.  transforms a
<code class="file docutils literal notranslate"><span class="pre">.c</span></code> file to a <code class="file docutils literal notranslate"><span class="pre">.o</span></code> file.)</p>
<p><em>sources</em> must be a list of filenames, most likely C/C++ files, but in reality
anything that can be handled by a particular compiler and compiler class (eg.
<code class="xref py py-class docutils literal notranslate"><span class="pre">MSVCCompiler</span></code> can handle resource files in <em>sources</em>).  Return a list of
object filenames, one per source filename in <em>sources</em>.  Depending on the
implementation, not all source files will necessarily be compiled, but all
corresponding object filenames will be returned.</p>
<p>If <em>output_dir</em> is given, object files will be put under it, while retaining
their original path component.  That is, <code class="file docutils literal notranslate"><span class="pre">foo/bar.c</span></code> normally compiles to
<code class="file docutils literal notranslate"><span class="pre">foo/bar.o</span></code> (for a Unix implementation); if <em>output_dir</em> is <em>build</em>, then
it would compile to <code class="file docutils literal notranslate"><span class="pre">build/foo/bar.o</span></code>.</p>
<p><em>macros</em>, if given, must be a list of macro definitions.  A macro definition is
either a <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> 2-tuple or a <code class="docutils literal notranslate"><span class="pre">(name,)</span></code> 1-tuple. The former defines
a macro; if the value is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the macro is defined without an explicit
value.  The 1-tuple case undefines a macro.  Later
definitions/redefinitions/undefinitions take precedence.</p>
<p><em>include_dirs</em>, if given, must be a list of strings, the directories to add to
the default include file search path for this compilation only.</p>
<p><em>debug</em> is a boolean; if true, the compiler will be instructed to output debug
symbols in (or alongside) the object file(s).</p>
<p><em>extra_preargs</em> and <em>extra_postargs</em> are implementation-dependent. On platforms
that have the notion of a command-line (e.g. Unix, DOS/Windows), they are most
likely lists of strings: extra command-line arguments to prepend/append to the
compiler command line.  On other platforms, consult the implementation class
documentation.  In any event, they are intended as an escape hatch for those
occasions when the abstract compiler framework doesn’t cut the mustard.</p>
<p><em>depends</em>, if given, is a list of filenames that all targets depend on.  If a
source file is older than any file in depends, then the source file will be
recompiled.  This supports dependency tracking, but only at a coarse
granularity.</p>
<p>Raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">CompileError</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.create_static_lib">
<code class="descname">create_static_lib</code><span class="sig-paren">(</span><em>objects</em>, <em>output_libname</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>debug=0</em>, <em>target_lang=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.create_static_lib" title="Permalink to this definition">¶</a></dt>
<dd><p>Link a bunch of stuff together to create a static library file. The “bunch of
stuff” consists of the list of object files supplied as <em>objects</em>, the extra
object files supplied to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_link_object" title="distutils.ccompiler.CCompiler.add_link_object"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_link_object()</span></code></a> and/or
<a class="reference internal" href="#distutils.ccompiler.CCompiler.set_link_objects" title="distutils.ccompiler.CCompiler.set_link_objects"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_link_objects()</span></code></a>, the libraries supplied to <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_library" title="distutils.ccompiler.CCompiler.add_library"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_library()</span></code></a> and/or
<a class="reference internal" href="#distutils.ccompiler.CCompiler.set_libraries" title="distutils.ccompiler.CCompiler.set_libraries"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_libraries()</span></code></a>, and the libraries supplied as <em>libraries</em> (if any).</p>
<p><em>output_libname</em> should be a library name, not a filename; the filename will be
inferred from the library name.  <em>output_dir</em> is the directory where the library
file will be put.</p>
<p><em>debug</em> is a boolean; if true, debugging information will be included in the
library (note that on most platforms, it is the compile step where this matters:
the <em>debug</em> flag is included here just for consistency).</p>
<p><em>target_lang</em> is the target language for which the given objects are being
compiled. This allows specific linkage time treatment of certain languages.</p>
<p>Raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">LibError</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.link">
<code class="descname">link</code><span class="sig-paren">(</span><em>target_desc</em>, <em>objects</em>, <em>output_filename</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>libraries=None</em>, <em>library_dirs=None</em>, <em>runtime_library_dirs=None</em>, <em>export_symbols=None</em>, <em>debug=0</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em>, <em>build_temp=None</em>, <em>target_lang=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.link" title="Permalink to this definition">¶</a></dt>
<dd><p>Link a bunch of stuff together to create an executable or shared library file.</p>
<p>The “bunch of stuff” consists of the list of object files supplied as <em>objects</em>.
<em>output_filename</em> should be a filename.  If <em>output_dir</em> is supplied,
<em>output_filename</em> is relative to it (i.e. <em>output_filename</em> can provide
directory components if needed).</p>
<p><em>libraries</em> is a list of libraries to link against.  These are library names,
not filenames, since they’re translated into filenames in a platform-specific
way (eg. <em>foo</em> becomes <code class="file docutils literal notranslate"><span class="pre">libfoo.a</span></code> on Unix and <code class="file docutils literal notranslate"><span class="pre">foo.lib</span></code> on
DOS/Windows).  However, they can include a directory component, which means the
linker will look in that specific directory rather than searching all the normal
locations.</p>
<p><em>library_dirs</em>, if supplied, should be a list of directories to search for
libraries that were specified as bare library names (ie. no directory
component).  These are on top of the system default and those supplied to
<a class="reference internal" href="#distutils.ccompiler.CCompiler.add_library_dir" title="distutils.ccompiler.CCompiler.add_library_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_library_dir()</span></code></a> and/or <a class="reference internal" href="#distutils.ccompiler.CCompiler.set_library_dirs" title="distutils.ccompiler.CCompiler.set_library_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_library_dirs()</span></code></a>.  <em>runtime_library_dirs</em>
is a list of directories that will be embedded into the shared library and used
to search for other shared libraries that *it* depends on at run-time.  (This
may only be relevant on Unix.)</p>
<p><em>export_symbols</em> is a list of symbols that the shared library will export.
(This appears to be relevant only on Windows.)</p>
<p><em>debug</em> is as for <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compile()</span></code></a> and <a class="reference internal" href="#distutils.ccompiler.CCompiler.create_static_lib" title="distutils.ccompiler.CCompiler.create_static_lib"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_static_lib()</span></code></a>,  with the
slight distinction that it actually matters on most platforms (as opposed to
<a class="reference internal" href="#distutils.ccompiler.CCompiler.create_static_lib" title="distutils.ccompiler.CCompiler.create_static_lib"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_static_lib()</span></code></a>, which includes a <em>debug</em> flag mostly for form’s
sake).</p>
<p><em>extra_preargs</em> and <em>extra_postargs</em> are as for <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compile()</span></code></a>  (except of
course that they supply command-line arguments for the particular linker being
used).</p>
<p><em>target_lang</em> is the target language for which the given objects are being
compiled. This allows specific linkage time treatment of certain languages.</p>
<p>Raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">LinkError</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.link_executable">
<code class="descname">link_executable</code><span class="sig-paren">(</span><em>objects</em>, <em>output_progname</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>libraries=None</em>, <em>library_dirs=None</em>, <em>runtime_library_dirs=None</em>, <em>debug=0</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em>, <em>target_lang=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.link_executable" title="Permalink to this definition">¶</a></dt>
<dd><p>Link an executable.  <em>output_progname</em> is the name of the file executable, while
<em>objects</em> are a list of object filenames to link in. Other arguments  are as for
the <a class="reference internal" href="#distutils.ccompiler.CCompiler.link" title="distutils.ccompiler.CCompiler.link"><code class="xref py py-meth docutils literal notranslate"><span class="pre">link()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.link_shared_lib">
<code class="descname">link_shared_lib</code><span class="sig-paren">(</span><em>objects</em>, <em>output_libname</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>libraries=None</em>, <em>library_dirs=None</em>, <em>runtime_library_dirs=None</em>, <em>export_symbols=None</em>, <em>debug=0</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em>, <em>build_temp=None</em>, <em>target_lang=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.link_shared_lib" title="Permalink to this definition">¶</a></dt>
<dd><p>Link a shared library. <em>output_libname</em> is the name of the output  library,
while <em>objects</em> is a list of object filenames to link in.  Other arguments are
as for the <a class="reference internal" href="#distutils.ccompiler.CCompiler.link" title="distutils.ccompiler.CCompiler.link"><code class="xref py py-meth docutils literal notranslate"><span class="pre">link()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.link_shared_object">
<code class="descname">link_shared_object</code><span class="sig-paren">(</span><em>objects</em>, <em>output_filename</em><span class="optional">[</span>, <em>output_dir=None</em>, <em>libraries=None</em>, <em>library_dirs=None</em>, <em>runtime_library_dirs=None</em>, <em>export_symbols=None</em>, <em>debug=0</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em>, <em>build_temp=None</em>, <em>target_lang=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.link_shared_object" title="Permalink to this definition">¶</a></dt>
<dd><p>Link a shared object. <em>output_filename</em> is the name of the shared object that
will be created, while <em>objects</em> is a list of object filenames  to link in.
Other arguments are as for the <a class="reference internal" href="#distutils.ccompiler.CCompiler.link" title="distutils.ccompiler.CCompiler.link"><code class="xref py py-meth docutils literal notranslate"><span class="pre">link()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.preprocess">
<code class="descname">preprocess</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>output_file=None</em>, <em>macros=None</em>, <em>include_dirs=None</em>, <em>extra_preargs=None</em>, <em>extra_postargs=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.preprocess" title="Permalink to this definition">¶</a></dt>
<dd><p>Preprocess a single C/C++ source file, named in <em>source</em>. Output will be written
to file named <em>output_file</em>, or <em>stdout</em> if <em>output_file</em> not supplied.
<em>macros</em> is a list of macro definitions as for <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compile()</span></code></a>, which will
augment the macros set with <a class="reference internal" href="#distutils.ccompiler.CCompiler.define_macro" title="distutils.ccompiler.CCompiler.define_macro"><code class="xref py py-meth docutils literal notranslate"><span class="pre">define_macro()</span></code></a> and <a class="reference internal" href="#distutils.ccompiler.CCompiler.undefine_macro" title="distutils.ccompiler.CCompiler.undefine_macro"><code class="xref py py-meth docutils literal notranslate"><span class="pre">undefine_macro()</span></code></a>.
<em>include_dirs</em> is a list of directory names that will be added to the  default
list, in the same way as <a class="reference internal" href="#distutils.ccompiler.CCompiler.add_include_dir" title="distutils.ccompiler.CCompiler.add_include_dir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_include_dir()</span></code></a>.</p>
<p>Raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">PreprocessError</span></code> on failure.</p>
</dd></dl>

<p>The following utility methods are defined by the <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a> class, for
use by the various concrete subclasses.</p>
<dl class="method">
<dt id="distutils.ccompiler.CCompiler.executable_filename">
<code class="descname">executable_filename</code><span class="sig-paren">(</span><em>basename</em><span class="optional">[</span>, <em>strip_dir=0</em>, <em>output_dir=''</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.executable_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the filename of the executable for the given <em>basename</em>.  Typically for
non-Windows platforms this is the same as the basename,  while Windows will get
a <code class="file docutils literal notranslate"><span class="pre">.exe</span></code> added.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.library_filename">
<code class="descname">library_filename</code><span class="sig-paren">(</span><em>libname</em><span class="optional">[</span>, <em>lib_type='static'</em>, <em>strip_dir=0</em>, <em>output_dir=''</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.library_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the filename for the given library name on the current platform. On Unix
a library with <em>lib_type</em> of <code class="docutils literal notranslate"><span class="pre">'static'</span></code> will typically  be of the form
<code class="file docutils literal notranslate"><span class="pre">liblibname.a</span></code>, while a <em>lib_type</em> of <code class="docutils literal notranslate"><span class="pre">'dynamic'</span></code>  will be of the form
<code class="file docutils literal notranslate"><span class="pre">liblibname.so</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.object_filenames">
<code class="descname">object_filenames</code><span class="sig-paren">(</span><em>source_filenames</em><span class="optional">[</span>, <em>strip_dir=0</em>, <em>output_dir=''</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.object_filenames" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name of the object files for the given source files.
<em>source_filenames</em> should be a list of filenames.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.shared_object_filename">
<code class="descname">shared_object_filename</code><span class="sig-paren">(</span><em>basename</em><span class="optional">[</span>, <em>strip_dir=0</em>, <em>output_dir=''</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.shared_object_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name of a shared object file for the given file name <em>basename</em>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.execute">
<code class="descname">execute</code><span class="sig-paren">(</span><em>func</em>, <em>args</em><span class="optional">[</span>, <em>msg=None</em>, <em>level=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.execute" title="Permalink to this definition">¶</a></dt>
<dd><p>Invokes <a class="reference internal" href="#distutils.util.execute" title="distutils.util.execute"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.util.execute()</span></code></a>. This method invokes a  Python function
<em>func</em> with the given arguments <em>args</em>, after  logging and taking into account
the <em>dry_run</em> flag.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.spawn">
<code class="descname">spawn</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.spawn" title="Permalink to this definition">¶</a></dt>
<dd><p>Invokes <code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.util.spawn()</span></code>. This invokes an external  process to run
the given command.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.mkpath">
<code class="descname">mkpath</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode=511</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.mkpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Invokes <a class="reference internal" href="#distutils.dir_util.mkpath" title="distutils.dir_util.mkpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.dir_util.mkpath()</span></code></a>. This creates a directory  and any
missing ancestor directories.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.move_file">
<code class="descname">move_file</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.move_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Invokes <a class="reference internal" href="#distutils.file_util.move_file" title="distutils.file_util.move_file"><code class="xref py py-meth docutils literal notranslate"><span class="pre">distutils.file_util.move_file()</span></code></a>. Renames <em>src</em> to  <em>dst</em>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.announce">
<code class="descname">announce</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>level=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.announce" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a message using <code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.log.debug()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.warn">
<code class="descname">warn</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.warn" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a warning message <em>msg</em> to standard error.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.ccompiler.CCompiler.debug_print">
<code class="descname">debug_print</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.ccompiler.CCompiler.debug_print" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>debug</em> flag is set on this <a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code></a> instance, print  <em>msg</em> to
standard output, otherwise do nothing.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="module-distutils.unixccompiler">
<span id="distutils-unixccompiler-unix-c-compiler"></span><h2>10.3. <a class="reference internal" href="#module-distutils.unixccompiler" title="distutils.unixccompiler: UNIX C Compiler"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.unixccompiler</span></code></a> — Unix C Compiler<a class="headerlink" href="#module-distutils.unixccompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <code class="xref py py-class docutils literal notranslate"><span class="pre">UnixCCompiler</span></code> class, a subclass of
<code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code> that handles the typical Unix-style command-line  C compiler:</p>
<ul class="simple">
<li>macros defined with <code class="xref std std-option docutils literal notranslate"><span class="pre">-Dname[=value]</span></code></li>
<li>macros undefined with <code class="xref std std-option docutils literal notranslate"><span class="pre">-Uname</span></code></li>
<li>include search directories specified with <code class="xref std std-option docutils literal notranslate"><span class="pre">-Idir</span></code></li>
<li>libraries specified with <code class="xref std std-option docutils literal notranslate"><span class="pre">-llib</span></code></li>
<li>library search directories specified with <code class="xref std std-option docutils literal notranslate"><span class="pre">-Ldir</span></code></li>
<li>compile handled by <strong class="program">cc</strong> (or similar) executable with <code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code>
option: compiles <code class="file docutils literal notranslate"><span class="pre">.c</span></code> to <code class="file docutils literal notranslate"><span class="pre">.o</span></code></li>
<li>link static library handled by <strong class="program">ar</strong> command (possibly with
<strong class="program">ranlib</strong>)</li>
<li>link shared library handled by <strong class="program">cc</strong> <code class="xref std std-option docutils literal notranslate"><span class="pre">-shared</span></code></li>
</ul>
</div>
<div class="section" id="module-distutils.msvccompiler">
<span id="distutils-msvccompiler-microsoft-compiler"></span><h2>10.4. <a class="reference internal" href="#module-distutils.msvccompiler" title="distutils.msvccompiler: Microsoft Compiler"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.msvccompiler</span></code></a> — Microsoft Compiler<a class="headerlink" href="#module-distutils.msvccompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides <code class="xref py py-class docutils literal notranslate"><span class="pre">MSVCCompiler</span></code>, an implementation of the abstract
<code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code> class for Microsoft Visual Studio. Typically, extension
modules need to be compiled with the same compiler that was used to compile
Python. For Python 2.3 and earlier, the compiler was Visual Studio 6. For Python
2.4 and 2.5, the compiler is Visual Studio .NET 2003. The AMD64 and Itanium
binaries are created using the Platform SDK.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">MSVCCompiler</span></code> will normally choose the right compiler, linker etc. on
its own. To override this choice, the environment variables <em>DISTUTILS_USE_SDK</em>
and <em>MSSdk</em> must be both set. <em>MSSdk</em> indicates that the current environment has
been setup by the SDK’s <code class="docutils literal notranslate"><span class="pre">SetEnv.Cmd</span></code> script, or that the environment variables
had been registered when the SDK was installed; <em>DISTUTILS_USE_SDK</em> indicates
that the distutils user has made an explicit choice to override the compiler
selection by <code class="xref py py-class docutils literal notranslate"><span class="pre">MSVCCompiler</span></code>.</p>
</div>
<div class="section" id="module-distutils.bcppcompiler">
<span id="distutils-bcppcompiler-borland-compiler"></span><h2>10.5. <a class="reference internal" href="#module-distutils.bcppcompiler" title="distutils.bcppcompiler"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.bcppcompiler</span></code></a> — Borland Compiler<a class="headerlink" href="#module-distutils.bcppcompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides <code class="xref py py-class docutils literal notranslate"><span class="pre">BorlandCCompiler</span></code>, a subclass of the abstract
<code class="xref py py-class docutils literal notranslate"><span class="pre">CCompiler</span></code> class for the Borland C++ compiler.</p>
</div>
<div class="section" id="module-distutils.cygwinccompiler">
<span id="distutils-cygwincompiler-cygwin-compiler"></span><h2>10.6. <code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.cygwincompiler</span></code> — Cygwin Compiler<a class="headerlink" href="#module-distutils.cygwinccompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <code class="xref py py-class docutils literal notranslate"><span class="pre">CygwinCCompiler</span></code> class, a subclass of
<code class="xref py py-class docutils literal notranslate"><span class="pre">UnixCCompiler</span></code> that handles the Cygwin port of the GNU C compiler to
Windows.  It also contains the Mingw32CCompiler class which handles the mingw32
port of GCC (same as cygwin in no-cygwin mode).</p>
</div>
<div class="section" id="module-distutils.emxccompiler">
<span id="distutils-emxccompiler-os-2-emx-compiler"></span><h2>10.7. <a class="reference internal" href="#module-distutils.emxccompiler" title="distutils.emxccompiler: OS/2 EMX Compiler support"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.emxccompiler</span></code></a> — OS/2 EMX Compiler<a class="headerlink" href="#module-distutils.emxccompiler" title="Permalink to this headline">¶</a></h2>
<p>This module provides the EMXCCompiler class, a subclass of
<code class="xref py py-class docutils literal notranslate"><span class="pre">UnixCCompiler</span></code> that handles the EMX port of the GNU C compiler to OS/2.</p>
</div>
<div class="section" id="module-distutils.archive_util">
<span id="distutils-archive-util-archiving-utilities"></span><h2>10.8. <a class="reference internal" href="#module-distutils.archive_util" title="distutils.archive_util: Utility functions for creating archive files (tarballs, zip files, ...)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.archive_util</span></code></a> —  Archiving utilities<a class="headerlink" href="#module-distutils.archive_util" title="Permalink to this headline">¶</a></h2>
<p>This module provides a few functions for creating archive files, such as
tarballs or zipfiles.</p>
<dl class="function">
<dt id="distutils.archive_util.make_archive">
<code class="descclassname">distutils.archive_util.</code><code class="descname">make_archive</code><span class="sig-paren">(</span><em>base_name</em>, <em>format</em><span class="optional">[</span>, <em>root_dir=None</em>, <em>base_dir=None</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.archive_util.make_archive" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an archive file (eg. <code class="docutils literal notranslate"><span class="pre">zip</span></code> or <code class="docutils literal notranslate"><span class="pre">tar</span></code>).  <em>base_name</em>  is the name of
the file to create, minus any format-specific extension;  <em>format</em> is the
archive format: one of <code class="docutils literal notranslate"><span class="pre">zip</span></code>, <code class="docutils literal notranslate"><span class="pre">tar</span></code>,  <code class="docutils literal notranslate"><span class="pre">ztar</span></code>, or <code class="docutils literal notranslate"><span class="pre">gztar</span></code>. <em>root_dir</em> is
a directory that will be the root directory of the archive; ie. we typically
<code class="docutils literal notranslate"><span class="pre">chdir</span></code> into <em>root_dir</em> before  creating the archive.  <em>base_dir</em> is the
directory where we start  archiving from; ie. <em>base_dir</em> will be the common
prefix of all files and directories in the archive.  <em>root_dir</em> and <em>base_dir</em>
both default to the current directory.  Returns the name of the archive file.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.archive_util.make_tarball">
<code class="descclassname">distutils.archive_util.</code><code class="descname">make_tarball</code><span class="sig-paren">(</span><em>base_name</em>, <em>base_dir</em><span class="optional">[</span>, <em>compress='gzip'</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.archive_util.make_tarball" title="Permalink to this definition">¶</a></dt>
<dd><p>‘Create an (optional compressed) archive as a tar file from all files in and
under <em>base_dir</em>. <em>compress</em> must be <code class="docutils literal notranslate"><span class="pre">'gzip'</span></code> (the default),  <code class="docutils literal notranslate"><span class="pre">'compress'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'bzip2'</span></code>, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Both <strong class="program">tar</strong> and the compression utility named
by <em>compress</em> must be on the  default program search path, so this is probably
Unix-specific.  The  output tar file will be named <code class="file docutils literal notranslate"><span class="pre">base_dir.tar</span></code>,
possibly plus the appropriate compression extension (<code class="file docutils literal notranslate"><span class="pre">.gz</span></code>, <code class="file docutils literal notranslate"><span class="pre">.bz2</span></code>
or <code class="file docutils literal notranslate"><span class="pre">.Z</span></code>).  Return the output filename.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.archive_util.make_zipfile">
<code class="descclassname">distutils.archive_util.</code><code class="descname">make_zipfile</code><span class="sig-paren">(</span><em>base_name</em>, <em>base_dir</em><span class="optional">[</span>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.archive_util.make_zipfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a zip file from all files in and under <em>base_dir</em>.  The output zip file
will be named <em>base_name</em> + <code class="file docutils literal notranslate"><span class="pre">.zip</span></code>.  Uses either the  <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> Python
module (if available) or the InfoZIP <code class="file docutils literal notranslate"><span class="pre">zip</span></code>  utility (if installed and
found on the default search path).  If neither  tool is available, raises
<code class="xref py py-exc docutils literal notranslate"><span class="pre">DistutilsExecError</span></code>.   Returns the name of the output zip file.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.dep_util">
<span id="distutils-dep-util-dependency-checking"></span><h2>10.9. <a class="reference internal" href="#module-distutils.dep_util" title="distutils.dep_util: Utility functions for simple dependency checking"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.dep_util</span></code></a> — Dependency checking<a class="headerlink" href="#module-distutils.dep_util" title="Permalink to this headline">¶</a></h2>
<p>This module provides functions for performing simple, timestamp-based
dependency of files and groups of files; also, functions based entirely  on such
timestamp dependency analysis.</p>
<dl class="function">
<dt id="distutils.dep_util.newer">
<code class="descclassname">distutils.dep_util.</code><code class="descname">newer</code><span class="sig-paren">(</span><em>source</em>, <em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dep_util.newer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>source</em> exists and is more recently modified than <em>target</em>, or
if <em>source</em> exists and <em>target</em> doesn’t. Return false if both exist and <em>target</em>
is the same age or newer  than <em>source</em>. Raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">DistutilsFileError</span></code> if
<em>source</em> does not exist.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.dep_util.newer_pairwise">
<code class="descclassname">distutils.dep_util.</code><code class="descname">newer_pairwise</code><span class="sig-paren">(</span><em>sources</em>, <em>targets</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dep_util.newer_pairwise" title="Permalink to this definition">¶</a></dt>
<dd><p>Walk two filename lists in parallel, testing if each source is newer than its
corresponding target.  Return a pair of lists (<em>sources</em>, <em>targets</em>) where
source is newer than target, according to the semantics of <a class="reference internal" href="#distutils.dep_util.newer" title="distutils.dep_util.newer"><code class="xref py py-func docutils literal notranslate"><span class="pre">newer()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.dep_util.newer_group">
<code class="descclassname">distutils.dep_util.</code><code class="descname">newer_group</code><span class="sig-paren">(</span><em>sources</em>, <em>target</em><span class="optional">[</span>, <em>missing='error'</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dep_util.newer_group" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>target</em> is out-of-date with respect to any file listed in
<em>sources</em>.  In other words, if <em>target</em> exists and is newer than every file in
<em>sources</em>, return false; otherwise return true. <em>missing</em> controls what we do
when a source file is missing; the default (<code class="docutils literal notranslate"><span class="pre">'error'</span></code>) is to blow up with an
<a class="reference internal" href="../library/exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> from  inside <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>; if it is <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, we silently
drop any missing source files; if it is <code class="docutils literal notranslate"><span class="pre">'newer'</span></code>, any missing source files
make us assume that <em>target</em> is out-of-date (this is handy in “dry-run” mode:
it’ll make you pretend to carry out commands that wouldn’t work because inputs
are missing, but that doesn’t matter because you’re not actually going to run
the commands).</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.dir_util">
<span id="distutils-dir-util-directory-tree-operations"></span><h2>10.10. <a class="reference internal" href="#module-distutils.dir_util" title="distutils.dir_util: Utility functions for operating on directories and directory trees"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.dir_util</span></code></a> — Directory tree operations<a class="headerlink" href="#module-distutils.dir_util" title="Permalink to this headline">¶</a></h2>
<p>This module provides functions for operating on directories and trees of
directories.</p>
<dl class="function">
<dt id="distutils.dir_util.mkpath">
<code class="descclassname">distutils.dir_util.</code><code class="descname">mkpath</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode=0777</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dir_util.mkpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a directory and any missing ancestor directories.  If the directory
already exists (or if <em>name</em> is the empty string, which means the current
directory, which of course exists), then do nothing.  Raise
<code class="xref py py-exc docutils literal notranslate"><span class="pre">DistutilsFileError</span></code> if unable to create some directory along the way (eg.
some sub-path exists, but is a file rather than a directory).  If <em>verbose</em> is
true, print a one-line summary of each mkdir to stdout.  Return the list of
directories actually created.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.dir_util.create_tree">
<code class="descclassname">distutils.dir_util.</code><code class="descname">create_tree</code><span class="sig-paren">(</span><em>base_dir</em>, <em>files</em><span class="optional">[</span>, <em>mode=0777</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dir_util.create_tree" title="Permalink to this definition">¶</a></dt>
<dd><p>Create all the empty directories under <em>base_dir</em> needed to put <em>files</em> there.
<em>base_dir</em> is just the name of a directory which doesn’t necessarily exist
yet; <em>files</em> is a list of filenames to be interpreted relative to <em>base_dir</em>.
<em>base_dir</em> + the directory portion of every file in <em>files</em> will be created if
it doesn’t already exist.  <em>mode</em>, <em>verbose</em> and <em>dry_run</em> flags  are as for
<a class="reference internal" href="#distutils.dir_util.mkpath" title="distutils.dir_util.mkpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkpath()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.dir_util.copy_tree">
<code class="descclassname">distutils.dir_util.</code><code class="descname">copy_tree</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="optional">[</span>, <em>preserve_mode=1</em>, <em>preserve_times=1</em>, <em>preserve_symlinks=0</em>, <em>update=0</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dir_util.copy_tree" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy an entire directory tree <em>src</em> to a new location <em>dst</em>.  Both <em>src</em> and
<em>dst</em> must be directory names.  If <em>src</em> is not a directory, raise
<code class="xref py py-exc docutils literal notranslate"><span class="pre">DistutilsFileError</span></code>.  If <em>dst</em> does  not exist, it is created with
<a class="reference internal" href="#distutils.dir_util.mkpath" title="distutils.dir_util.mkpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkpath()</span></code></a>.  The end result of the copy is that every file in <em>src</em> is
copied to <em>dst</em>, and directories under <em>src</em> are recursively copied to <em>dst</em>.
Return the list of files that were copied or might have been copied, using their
output name. The return value is unaffected by <em>update</em> or <em>dry_run</em>: it is
simply the list of all files under <em>src</em>, with the names changed to be under
<em>dst</em>.</p>
<p><em>preserve_mode</em> and <em>preserve_times</em> are the same as for
<a class="reference internal" href="#distutils.file_util.copy_file" title="distutils.file_util.copy_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.file_util.copy_file()</span></code></a>; note that they only apply to
regular files, not to
directories.  If <em>preserve_symlinks</em> is true, symlinks will be copied as
symlinks (on platforms that support them!); otherwise (the default), the
destination of the symlink will be copied.  <em>update</em> and <em>verbose</em> are the same
as for <code class="xref py py-func docutils literal notranslate"><span class="pre">copy_file()</span></code>.</p>
<p>Files in <em>src</em> that begin with <code class="file docutils literal notranslate"><span class="pre">.nfs</span></code> are skipped (more information on
these files is available in answer D2 of the <a class="reference external" href="http://nfs.sourceforge.net/#section_d">NFS FAQ page</a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.4: </span>NFS files are ignored.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="distutils.dir_util.remove_tree">
<code class="descclassname">distutils.dir_util.</code><code class="descname">remove_tree</code><span class="sig-paren">(</span><em>directory</em><span class="optional">[</span>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.dir_util.remove_tree" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively remove <em>directory</em> and all files and directories underneath it. Any
errors are ignored (apart from being reported to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> if <em>verbose</em> is
true).</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.file_util">
<span id="distutils-file-util-single-file-operations"></span><h2>10.11. <a class="reference internal" href="#module-distutils.file_util" title="distutils.file_util: Utility functions for operating on single files"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.file_util</span></code></a> — Single file operations<a class="headerlink" href="#module-distutils.file_util" title="Permalink to this headline">¶</a></h2>
<p>This module contains some utility functions for operating on individual files.</p>
<dl class="function">
<dt id="distutils.file_util.copy_file">
<code class="descclassname">distutils.file_util.</code><code class="descname">copy_file</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="optional">[</span>, <em>preserve_mode=1</em>, <em>preserve_times=1</em>, <em>update=0</em>, <em>link=None</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.file_util.copy_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy file <em>src</em> to <em>dst</em>. If <em>dst</em> is a directory, then <em>src</em> is copied there
with the same name; otherwise, it must be a filename. (If the file exists, it
will be ruthlessly clobbered.) If <em>preserve_mode</em> is true (the default), the
file’s mode (type and permission bits, or whatever is analogous on the
current platform) is copied. If <em>preserve_times</em> is true (the default), the
last-modified and last-access times are copied as well. If <em>update</em> is true,
<em>src</em> will only be copied if <em>dst</em> does not exist, or if <em>dst</em> does exist but
is older than <em>src</em>.</p>
<p><em>link</em> allows you to make hard links (using <a class="reference internal" href="../library/os.html#os.link" title="os.link"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.link()</span></code></a>) or symbolic links
(using <a class="reference internal" href="../library/os.html#os.symlink" title="os.symlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.symlink()</span></code></a>) instead of copying: set it to <code class="docutils literal notranslate"><span class="pre">'hard'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'sym'</span></code>; if it is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), files are copied. Don’t set <em>link</em>
on systems that don’t support it: <a class="reference internal" href="#distutils.file_util.copy_file" title="distutils.file_util.copy_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy_file()</span></code></a> doesn’t check if hard or
symbolic linking is available.  It uses <code class="xref py py-func docutils literal notranslate"><span class="pre">_copy_file_contents()</span></code> to copy file
contents.</p>
<p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(dest_name,</span> <span class="pre">copied)</span></code>: <em>dest_name</em> is the actual  name of the
output file, and <em>copied</em> is true if the file was copied  (or would have been
copied, if <em>dry_run</em> true).</p>
</dd></dl>

<dl class="function">
<dt id="distutils.file_util.move_file">
<code class="descclassname">distutils.file_util.</code><code class="descname">move_file</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="optional">[</span>, <em>verbose</em>, <em>dry_run</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.file_util.move_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Move file <em>src</em> to <em>dst</em>. If <em>dst</em> is a directory, the file will be moved into
it with the same name; otherwise, <em>src</em> is just renamed to <em>dst</em>.  Returns the
new full name of the file.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Handles cross-device moves on Unix using <a class="reference internal" href="#distutils.file_util.copy_file" title="distutils.file_util.copy_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy_file()</span></code></a>.  What about
other systems?</p>
</div>
</dd></dl>

<dl class="function">
<dt id="distutils.file_util.write_file">
<code class="descclassname">distutils.file_util.</code><code class="descname">write_file</code><span class="sig-paren">(</span><em>filename</em>, <em>contents</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.file_util.write_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a file called <em>filename</em> and write <em>contents</em> (a sequence of strings
without line terminators) to it.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.util">
<span id="distutils-util-miscellaneous-other-utility-functions"></span><h2>10.12. <a class="reference internal" href="#module-distutils.util" title="distutils.util: Miscellaneous other utility functions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.util</span></code></a> — Miscellaneous other utility functions<a class="headerlink" href="#module-distutils.util" title="Permalink to this headline">¶</a></h2>
<p>This module contains other assorted bits and pieces that don’t fit into  any
other utility module.</p>
<dl class="function">
<dt id="distutils.util.get_platform">
<code class="descclassname">distutils.util.</code><code class="descname">get_platform</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.get_platform" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string that identifies the current platform.  This is used mainly to
distinguish platform-specific build directories and platform-specific built
distributions.  Typically includes the OS name and version and the architecture
(as supplied by ‘os.uname()’), although the exact information included depends
on the OS; eg. for IRIX the architecture isn’t particularly important (IRIX only
runs on SGI hardware), but for Linux the kernel version isn’t particularly
important.</p>
<p>Examples of returned values:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">linux-i586</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">linux-alpha</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">solaris-2.6-sun4u</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">irix-5.3</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">irix64-6.2</span></code></li>
</ul>
<p>For non-POSIX platforms, currently just returns <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code>.</p>
<p>For Mac OS X systems the OS version reflects the minimal version on which
binaries will run (that is, the value of <code class="docutils literal notranslate"><span class="pre">MACOSX_DEPLOYMENT_TARGET</span></code>
during the build of Python), not the OS version of the current system.</p>
<p>For universal binary builds on Mac OS X the architecture value reflects
the universal binary status instead of the architecture of the current
processor. For 32-bit universal binaries the architecture is <code class="docutils literal notranslate"><span class="pre">fat</span></code>,
for 64-bit universal binaries the architecture is <code class="docutils literal notranslate"><span class="pre">fat64</span></code>, and
for 4-way universal binaries the architecture is <code class="docutils literal notranslate"><span class="pre">universal</span></code>. Starting
from Python 2.7 and Python 3.2 the architecture <code class="docutils literal notranslate"><span class="pre">fat3</span></code> is used for
a 3-way universal build (ppc, i386, x86_64) and <code class="docutils literal notranslate"><span class="pre">intel</span></code> is used for
a universal build with the i386 and x86_64 architectures</p>
<p>Examples of returned values on Mac OS X:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">macosx-10.3-ppc</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">macosx-10.3-fat</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">macosx-10.5-universal</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">macosx-10.6-intel</span></code></li>
</ul>
</dd></dl>

<dl class="function">
<dt id="distutils.util.convert_path">
<code class="descclassname">distutils.util.</code><code class="descname">convert_path</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.convert_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Return ‘pathname’ as a name that will work on the native filesystem, i.e. split
it on ‘/’ and put it back together again using the current directory separator.
Needed because filenames in the setup script are always supplied in Unix style,
and have to be converted to the local convention before we can actually use them
in the filesystem.  Raises <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> on non-Unix-ish systems if
<em>pathname</em> either  starts or ends with a slash.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.change_root">
<code class="descclassname">distutils.util.</code><code class="descname">change_root</code><span class="sig-paren">(</span><em>new_root</em>, <em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.change_root" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>pathname</em> with <em>new_root</em> prepended.  If <em>pathname</em> is relative, this is
equivalent to <code class="docutils literal notranslate"><span class="pre">os.path.join(new_root,pathname)</span></code> Otherwise, it requires making
<em>pathname</em> relative and then joining the two, which is tricky on DOS/Windows.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.check_environ">
<code class="descclassname">distutils.util.</code><code class="descname">check_environ</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.check_environ" title="Permalink to this definition">¶</a></dt>
<dd><p>Ensure that ‘os.environ’ has all the environment variables we guarantee that
users can use in config files, command-line options, etc.  Currently this
includes:</p>
<ul class="simple">
<li><span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code> - user’s home directory (Unix only)</li>
<li><span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PLAT</span></code> - description of the current platform, including hardware and
OS (see <a class="reference internal" href="#distutils.util.get_platform" title="distutils.util.get_platform"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_platform()</span></code></a>)</li>
</ul>
</dd></dl>

<dl class="function">
<dt id="distutils.util.subst_vars">
<code class="descclassname">distutils.util.</code><code class="descname">subst_vars</code><span class="sig-paren">(</span><em>s</em>, <em>local_vars</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.subst_vars" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform shell/Perl-style variable substitution on <em>s</em>.  Every occurrence of
<code class="docutils literal notranslate"><span class="pre">$</span></code> followed by a name is considered a variable, and variable is substituted
by the value found in the <em>local_vars</em> dictionary, or in <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> if it’s
not in <em>local_vars</em>. <em>os.environ</em> is first checked/augmented to guarantee that
it contains certain values: see <a class="reference internal" href="#distutils.util.check_environ" title="distutils.util.check_environ"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_environ()</span></code></a>.  Raise <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
for any variables not found in either <em>local_vars</em> or <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>.</p>
<p>Note that this is not a fully-fledged string interpolation function. A valid
<code class="docutils literal notranslate"><span class="pre">$variable</span></code> can consist only of upper and lower case letters, numbers and an
underscore. No { } or ( ) style quoting is available.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.split_quoted">
<code class="descclassname">distutils.util.</code><code class="descname">split_quoted</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.split_quoted" title="Permalink to this definition">¶</a></dt>
<dd><p>Split a string up according to Unix shell-like rules for quotes and backslashes.
In short: words are delimited by spaces, as long as those spaces are not escaped
by a backslash, or inside a quoted string. Single and double quotes are
equivalent, and the quote characters can be backslash-escaped.  The backslash is
stripped from any two-character escape sequence, leaving only the escaped
character.  The quote characters are stripped from any quoted string.  Returns a
list of words.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.execute">
<code class="descclassname">distutils.util.</code><code class="descname">execute</code><span class="sig-paren">(</span><em>func</em>, <em>args</em><span class="optional">[</span>, <em>msg=None</em>, <em>verbose=0</em>, <em>dry_run=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.execute" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform some action that affects the outside world (for instance, writing to the
filesystem).  Such actions are special because they are disabled by the
<em>dry_run</em> flag.  This method takes  care of all that bureaucracy for you; all
you have to do is supply the function to call and an argument tuple for it (to
embody the “external action” being performed), and an optional message to print.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.strtobool">
<code class="descclassname">distutils.util.</code><code class="descname">strtobool</code><span class="sig-paren">(</span><em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.strtobool" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a string representation of truth to true (1) or false (0).</p>
<p>True values are <code class="docutils literal notranslate"><span class="pre">y</span></code>, <code class="docutils literal notranslate"><span class="pre">yes</span></code>, <code class="docutils literal notranslate"><span class="pre">t</span></code>, <code class="docutils literal notranslate"><span class="pre">true</span></code>, <code class="docutils literal notranslate"><span class="pre">on</span></code>  and <code class="docutils literal notranslate"><span class="pre">1</span></code>; false values
are <code class="docutils literal notranslate"><span class="pre">n</span></code>, <code class="docutils literal notranslate"><span class="pre">no</span></code>, <code class="docutils literal notranslate"><span class="pre">f</span></code>, <code class="docutils literal notranslate"><span class="pre">false</span></code>,  <code class="docutils literal notranslate"><span class="pre">off</span></code> and <code class="docutils literal notranslate"><span class="pre">0</span></code>.  Raises
<a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>val</em>  is anything else.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.byte_compile">
<code class="descclassname">distutils.util.</code><code class="descname">byte_compile</code><span class="sig-paren">(</span><em>py_files</em><span class="optional">[</span>, <em>optimize=0</em>, <em>force=0</em>, <em>prefix=None</em>, <em>base_dir=None</em>, <em>verbose=1</em>, <em>dry_run=0</em>, <em>direct=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.byte_compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Byte-compile a collection of Python source files to either <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or
<code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files in the same directory.  <em>py_files</em> is a list of files to
compile; any files that don’t end in <code class="file docutils literal notranslate"><span class="pre">.py</span></code> are silently skipped.
<em>optimize</em> must be one of the following:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">0</span></code> - don’t optimize (generate <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code>)</li>
<li><code class="docutils literal notranslate"><span class="pre">1</span></code> - normal optimization (like <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-O</span></code>)</li>
<li><code class="docutils literal notranslate"><span class="pre">2</span></code> - extra optimization (like <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-OO</span></code>)</li>
</ul>
<p>If <em>force</em> is true, all files are recompiled regardless of timestamps.</p>
<p>The source filename encoded in each <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> file defaults to the filenames
listed in <em>py_files</em>; you can modify these with <em>prefix</em> and <em>basedir</em>.
<em>prefix</em> is a string that will be stripped off of each source filename, and
<em>base_dir</em> is a directory name that will be prepended (after <em>prefix</em> is
stripped).  You can supply either or both (or neither) of <em>prefix</em> and
<em>base_dir</em>, as you wish.</p>
<p>If <em>dry_run</em> is true, doesn’t actually do anything that would affect the
filesystem.</p>
<p>Byte-compilation is either done directly in this interpreter process with the
standard <a class="reference internal" href="../library/py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> module, or indirectly by writing a temporary script
and executing it.  Normally, you should let <a class="reference internal" href="#distutils.util.byte_compile" title="distutils.util.byte_compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">byte_compile()</span></code></a> figure out to
use direct compilation or not (see the source for details).  The <em>direct</em> flag
is used by the script generated in indirect mode; unless you know what you’re
doing, leave it set to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.util.rfc822_escape">
<code class="descclassname">distutils.util.</code><code class="descname">rfc822_escape</code><span class="sig-paren">(</span><em>header</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.util.rfc822_escape" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a version of <em>header</em> escaped for inclusion in an <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> header, by
ensuring there are 8 spaces space after each newline. Note that it does no other
modification of the string.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.dist">
<span id="distutils-dist-the-distribution-class"></span><h2>10.13. <a class="reference internal" href="#module-distutils.dist" title="distutils.dist: Provides the Distribution class, which represents the module distribution being built/installed/distributed"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.dist</span></code></a> — The Distribution class<a class="headerlink" href="#module-distutils.dist" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a> class, which
represents the module distribution being built/installed/distributed.</p>
</div>
<div class="section" id="module-distutils.extension">
<span id="distutils-extension-the-extension-class"></span><h2>10.14. <a class="reference internal" href="#module-distutils.extension" title="distutils.extension: Provides the Extension class, used to describe C/C++ extension modules in setup scripts"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.extension</span></code></a> — The Extension class<a class="headerlink" href="#module-distutils.extension" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> class, used to describe C/C++
extension modules in setup scripts.</p>
</div>
<div class="section" id="module-distutils.debug">
<span id="distutils-debug-distutils-debug-mode"></span><h2>10.15. <a class="reference internal" href="#module-distutils.debug" title="distutils.debug: Provides the debug flag for distutils"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.debug</span></code></a> — Distutils debug mode<a class="headerlink" href="#module-distutils.debug" title="Permalink to this headline">¶</a></h2>
<p>This module provides the DEBUG flag.</p>
</div>
<div class="section" id="module-distutils.errors">
<span id="distutils-errors-distutils-exceptions"></span><h2>10.16. <a class="reference internal" href="#module-distutils.errors" title="distutils.errors: Provides standard distutils exceptions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.errors</span></code></a> — Distutils exceptions<a class="headerlink" href="#module-distutils.errors" title="Permalink to this headline">¶</a></h2>
<p>Provides exceptions used by the Distutils modules.  Note that Distutils modules
may raise standard exceptions; in particular, SystemExit is usually raised for
errors that are obviously the end-user’s fault (eg. bad command-line arguments).</p>
<p>This module is safe to use in <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span> <span class="pre">*</span></code> mode; it only exports
symbols whose names start with <code class="docutils literal notranslate"><span class="pre">Distutils</span></code> and end with <code class="docutils literal notranslate"><span class="pre">Error</span></code>.</p>
</div>
<div class="section" id="module-distutils.fancy_getopt">
<span id="distutils-fancy-getopt-wrapper-around-the-standard-getopt-module"></span><h2>10.17. <a class="reference internal" href="#module-distutils.fancy_getopt" title="distutils.fancy_getopt: Additional getopt functionality"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.fancy_getopt</span></code></a> — Wrapper around the standard getopt module<a class="headerlink" href="#module-distutils.fancy_getopt" title="Permalink to this headline">¶</a></h2>
<p>This module provides a wrapper around the standard <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a>  module that
provides the following additional features:</p>
<ul class="simple">
<li>short and long options are tied together</li>
<li>options have help strings, so <a class="reference internal" href="#distutils.fancy_getopt.fancy_getopt" title="distutils.fancy_getopt.fancy_getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">fancy_getopt()</span></code></a> could potentially  create a
complete usage summary</li>
<li>options set attributes of a passed-in object</li>
<li>boolean options can have “negative aliases” — eg. if <code class="xref std std-option docutils literal notranslate"><span class="pre">--quiet</span></code> is
the “negative alias” of <code class="xref std std-option docutils literal notranslate"><span class="pre">--verbose</span></code>, then <code class="xref std std-option docutils literal notranslate"><span class="pre">--quiet</span></code> on the
command line sets <em>verbose</em> to false.</li>
</ul>
<dl class="function">
<dt id="distutils.fancy_getopt.fancy_getopt">
<code class="descclassname">distutils.fancy_getopt.</code><code class="descname">fancy_getopt</code><span class="sig-paren">(</span><em>options</em>, <em>negative_opt</em>, <em>object</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.fancy_getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>Wrapper function. <em>options</em> is a list of <code class="docutils literal notranslate"><span class="pre">(long_option,</span> <span class="pre">short_option,</span>
<span class="pre">help_string)</span></code> 3-tuples as described in the constructor for
<a class="reference internal" href="#distutils.fancy_getopt.FancyGetopt" title="distutils.fancy_getopt.FancyGetopt"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyGetopt</span></code></a>. <em>negative_opt</em> should be a dictionary mapping option names
to option names, both the key and value should be in the <em>options</em> list.
<em>object</em> is an object which will be used to store values (see the <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-meth docutils literal notranslate"><span class="pre">getopt()</span></code></a>
method of the <a class="reference internal" href="#distutils.fancy_getopt.FancyGetopt" title="distutils.fancy_getopt.FancyGetopt"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyGetopt</span></code></a> class). <em>args</em> is the argument list. Will use
<code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code> if you  pass <code class="docutils literal notranslate"><span class="pre">None</span></code> as <em>args</em>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.fancy_getopt.wrap_text">
<code class="descclassname">distutils.fancy_getopt.</code><code class="descname">wrap_text</code><span class="sig-paren">(</span><em>text</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.wrap_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps <em>text</em> to less than <em>width</em> wide.</p>
</dd></dl>

<dl class="class">
<dt id="distutils.fancy_getopt.FancyGetopt">
<em class="property">class </em><code class="descclassname">distutils.fancy_getopt.</code><code class="descname">FancyGetopt</code><span class="sig-paren">(</span><span class="optional">[</span><em>option_table=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.FancyGetopt" title="Permalink to this definition">¶</a></dt>
<dd><p>The option_table is a list of 3-tuples: <code class="docutils literal notranslate"><span class="pre">(long_option,</span> <span class="pre">short_option,</span>
<span class="pre">help_string)</span></code></p>
<p>If an option takes an argument, its <em>long_option</em> should have <code class="docutils literal notranslate"><span class="pre">'='</span></code> appended;
<em>short_option</em> should just be a single character, no <code class="docutils literal notranslate"><span class="pre">':'</span></code> in any case.
<em>short_option</em> should be <code class="docutils literal notranslate"><span class="pre">None</span></code> if a <em>long_option</em>  doesn’t have a
corresponding <em>short_option</em>. All option tuples must have long options.</p>
</dd></dl>

<p>The <a class="reference internal" href="#distutils.fancy_getopt.FancyGetopt" title="distutils.fancy_getopt.FancyGetopt"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyGetopt</span></code></a> class provides the following methods:</p>
<dl class="method">
<dt id="distutils.fancy_getopt.FancyGetopt.getopt">
<code class="descclassname">FancyGetopt.</code><code class="descname">getopt</code><span class="sig-paren">(</span><span class="optional">[</span><em>args=None</em>, <em>object=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.FancyGetopt.getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse command-line options in args. Store as attributes on <em>object</em>.</p>
<p>If <em>args</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> or not supplied, uses <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>.  If <em>object</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code> or not supplied, creates a new <code class="xref py py-class docutils literal notranslate"><span class="pre">OptionDummy</span></code> instance, stores
option values there, and returns a tuple <code class="docutils literal notranslate"><span class="pre">(args,</span> <span class="pre">object)</span></code>.  If <em>object</em> is
supplied, it is modified in place and <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> just returns <em>args</em>; in
both cases, the returned <em>args</em> is a modified copy of the passed-in <em>args</em> list,
which is left untouched.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.fancy_getopt.FancyGetopt.get_option_order">
<code class="descclassname">FancyGetopt.</code><code class="descname">get_option_order</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.FancyGetopt.get_option_order" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the list of <code class="docutils literal notranslate"><span class="pre">(option,</span> <span class="pre">value)</span></code> tuples processed by the previous run of
<a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-meth docutils literal notranslate"><span class="pre">getopt()</span></code></a>  Raises <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-meth docutils literal notranslate"><span class="pre">getopt()</span></code></a> hasn’t been called
yet.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.fancy_getopt.FancyGetopt.generate_help">
<code class="descclassname">FancyGetopt.</code><code class="descname">generate_help</code><span class="sig-paren">(</span><span class="optional">[</span><em>header=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.fancy_getopt.FancyGetopt.generate_help" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate help text (a list of strings, one per suggested line of output) from
the option table for this <a class="reference internal" href="#distutils.fancy_getopt.FancyGetopt" title="distutils.fancy_getopt.FancyGetopt"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyGetopt</span></code></a> object.</p>
<p>If supplied, prints the supplied <em>header</em> at the top of the help.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.filelist">
<span id="distutils-filelist-the-filelist-class"></span><h2>10.18. <a class="reference internal" href="#module-distutils.filelist" title="distutils.filelist: The FileList class, used for poking about the file system and building lists of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.filelist</span></code></a> — The FileList class<a class="headerlink" href="#module-distutils.filelist" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <code class="xref py py-class docutils literal notranslate"><span class="pre">FileList</span></code> class, used for poking about the
filesystem and building lists of files.</p>
</div>
<div class="section" id="module-distutils.log">
<span id="distutils-log-simple-pep-282-style-logging"></span><h2>10.19. <a class="reference internal" href="#module-distutils.log" title="distutils.log: A simple logging mechanism, 282-style"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.log</span></code></a> — Simple PEP 282-style logging<a class="headerlink" href="#module-distutils.log" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.spawn">
<span id="distutils-spawn-spawn-a-sub-process"></span><h2>10.20. <a class="reference internal" href="#module-distutils.spawn" title="distutils.spawn: Provides the spawn() function"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.spawn</span></code></a> — Spawn a sub-process<a class="headerlink" href="#module-distutils.spawn" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn()</span></code> function, a front-end to  various
platform-specific functions for launching another program in a  sub-process.
Also provides <code class="xref py py-func docutils literal notranslate"><span class="pre">find_executable()</span></code> to search the path for a given executable
name.</p>
</div>
<div class="section" id="module-distutils.sysconfig">
<span id="distutils-sysconfig-system-configuration-information"></span><h2>10.21. <a class="reference internal" href="#module-distutils.sysconfig" title="distutils.sysconfig: Low-level access to configuration information of the Python interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code></a> — System configuration information<a class="headerlink" href="#module-distutils.sysconfig" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-distutils.sysconfig" title="distutils.sysconfig: Low-level access to configuration information of the Python interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code></a> module provides access to Python’s low-level
configuration information.  The specific configuration variables available
depend heavily on the platform and configuration. The specific variables depend
on the build process for the specific version of Python being run; the variables
are those found in the <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> and configuration header that are
installed with Python on Unix systems.  The configuration header is called
<code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code> for Python versions starting with 2.2, and <code class="file docutils literal notranslate"><span class="pre">config.h</span></code>
for earlier versions of Python.</p>
<p>Some additional functions are provided which perform some useful manipulations
for other parts of the <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> package.</p>
<dl class="data">
<dt id="distutils.sysconfig.PREFIX">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">PREFIX</code><a class="headerlink" href="#distutils.sysconfig.PREFIX" title="Permalink to this definition">¶</a></dt>
<dd><p>The result of <code class="docutils literal notranslate"><span class="pre">os.path.normpath(sys.prefix)</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="distutils.sysconfig.EXEC_PREFIX">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">EXEC_PREFIX</code><a class="headerlink" href="#distutils.sysconfig.EXEC_PREFIX" title="Permalink to this definition">¶</a></dt>
<dd><p>The result of <code class="docutils literal notranslate"><span class="pre">os.path.normpath(sys.exec_prefix)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_config_var">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_config_var</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_config_var" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of a single variable.  This is equivalent to
<code class="docutils literal notranslate"><span class="pre">get_config_vars().get(name)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_config_vars">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_config_vars</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_config_vars" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a set of variable definitions.  If there are no arguments, this returns a
dictionary mapping names of configuration variables to values.  If arguments are
provided, they should be strings, and the return value will be a sequence giving
the associated values. If a given name does not have a corresponding value,
<code class="docutils literal notranslate"><span class="pre">None</span></code> will be included for that variable.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_config_h_filename">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_config_h_filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_config_h_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the full path name of the configuration header.  For Unix, this will be
the header generated by the <strong class="program">configure</strong> script; for other platforms the
header will have been supplied directly by the Python source distribution.  The
file is a platform-specific text file.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_makefile_filename">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_makefile_filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_makefile_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the full path name of the <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> used to build Python.  For
Unix, this will be a file generated by the <strong class="program">configure</strong> script; the
meaning for other platforms will vary.  The file is a platform-specific text
file, if it exists. This function is only useful on POSIX platforms.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_python_inc">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_python_inc</code><span class="sig-paren">(</span><span class="optional">[</span><em>plat_specific</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_python_inc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the directory for either the general or platform-dependent C include
files.  If <em>plat_specific</em> is true, the platform-dependent include directory is
returned; if false or omitted, the platform-independent directory is returned.
If <em>prefix</em> is given, it is used as either the prefix instead of
<a class="reference internal" href="#distutils.sysconfig.PREFIX" title="distutils.sysconfig.PREFIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">PREFIX</span></code></a>, or as the exec-prefix instead of <a class="reference internal" href="#distutils.sysconfig.EXEC_PREFIX" title="distutils.sysconfig.EXEC_PREFIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">EXEC_PREFIX</span></code></a> if
<em>plat_specific</em> is true.</p>
</dd></dl>

<dl class="function">
<dt id="distutils.sysconfig.get_python_lib">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">get_python_lib</code><span class="sig-paren">(</span><span class="optional">[</span><em>plat_specific</em><span class="optional">[</span>, <em>standard_lib</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.get_python_lib" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the directory for either the general or platform-dependent library
installation.  If <em>plat_specific</em> is true, the platform-dependent include
directory is returned; if false or omitted, the platform-independent directory
is returned.  If <em>prefix</em> is given, it is used as either the prefix instead of
<a class="reference internal" href="#distutils.sysconfig.PREFIX" title="distutils.sysconfig.PREFIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">PREFIX</span></code></a>, or as the exec-prefix instead of <a class="reference internal" href="#distutils.sysconfig.EXEC_PREFIX" title="distutils.sysconfig.EXEC_PREFIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">EXEC_PREFIX</span></code></a> if
<em>plat_specific</em> is true.  If <em>standard_lib</em> is true, the directory for the
standard library is returned rather than the directory for the installation of
third-party extensions.</p>
</dd></dl>

<p>The following function is only intended for use within the <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a>
package.</p>
<dl class="function">
<dt id="distutils.sysconfig.customize_compiler">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">customize_compiler</code><span class="sig-paren">(</span><em>compiler</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.customize_compiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Do any platform-specific customization of a
<a class="reference internal" href="#distutils.ccompiler.CCompiler" title="distutils.ccompiler.CCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.ccompiler.CCompiler</span></code></a> instance.</p>
<p>This function is only needed on Unix at this time, but should be called
consistently to support forward-compatibility.  It inserts the information that
varies across Unix flavors and is stored in Python’s <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code>.  This
information includes the selected compiler, compiler and linker options, and the
extension used by the linker for shared objects.</p>
</dd></dl>

<p>This function is even more special-purpose, and should only be used from
Python’s own build procedures.</p>
<dl class="function">
<dt id="distutils.sysconfig.set_python_build">
<code class="descclassname">distutils.sysconfig.</code><code class="descname">set_python_build</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.sysconfig.set_python_build" title="Permalink to this definition">¶</a></dt>
<dd><p>Inform the <a class="reference internal" href="#module-distutils.sysconfig" title="distutils.sysconfig: Low-level access to configuration information of the Python interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code></a> module that it is being used as part of
the build process for Python.  This changes a lot of relative locations for
files, allowing them to be located in the build area rather than in an installed
Python.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.text_file">
<span id="distutils-text-file-the-textfile-class"></span><h2>10.22. <a class="reference internal" href="#module-distutils.text_file" title="distutils.text_file: provides the TextFile class, a simple interface to text files"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.text_file</span></code></a> — The TextFile class<a class="headerlink" href="#module-distutils.text_file" title="Permalink to this headline">¶</a></h2>
<p>This module provides the <a class="reference internal" href="#distutils.text_file.TextFile" title="distutils.text_file.TextFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextFile</span></code></a> class, which gives an interface  to
text files that (optionally) takes care of stripping comments, ignoring  blank
lines, and joining lines with backslashes.</p>
<dl class="class">
<dt id="distutils.text_file.TextFile">
<em class="property">class </em><code class="descclassname">distutils.text_file.</code><code class="descname">TextFile</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename=None</em>, <em>file=None</em>, <em>**options</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This class provides a file-like object that takes care of all  the things you
commonly want to do when processing a text file  that has some line-by-line
syntax: strip comments (as long as <code class="docutils literal notranslate"><span class="pre">#</span></code>  is your comment character), skip blank
lines, join adjacent lines by escaping the newline (ie. backslash at end of
line), strip leading and/or trailing whitespace.  All of these are optional and
independently controllable.</p>
<p>The class provides a <a class="reference internal" href="#distutils.text_file.TextFile.warn" title="distutils.text_file.TextFile.warn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">warn()</span></code></a> method so you can generate  warning messages
that report physical line number, even if the  logical line in question spans
multiple physical lines.  Also  provides <a class="reference internal" href="#distutils.text_file.TextFile.unreadline" title="distutils.text_file.TextFile.unreadline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unreadline()</span></code></a> for implementing
line-at-a-time lookahead.</p>
<p><a class="reference internal" href="#distutils.text_file.TextFile" title="distutils.text_file.TextFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextFile</span></code></a> instances are create with either <em>filename</em>, <em>file</em>, or both.
<a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if both are <code class="docutils literal notranslate"><span class="pre">None</span></code>. <em>filename</em> should be a
string, and <em>file</em> a file object (or something that provides <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>
and <a class="reference internal" href="#distutils.text_file.TextFile.close" title="distutils.text_file.TextFile.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>  methods).  It is recommended that you supply at least
<em>filename</em>,  so that <a class="reference internal" href="#distutils.text_file.TextFile" title="distutils.text_file.TextFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextFile</span></code></a> can include it in warning messages.  If
<em>file</em> is not supplied, <a class="reference internal" href="#distutils.text_file.TextFile" title="distutils.text_file.TextFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextFile</span></code></a> creates its own using the
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function.</p>
<p>The options are all boolean, and affect the values returned by <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a></p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="54%" />
<col width="15%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option name</th>
<th class="head">description</th>
<th class="head">default</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>strip_comments</em></td>
<td>strip from <code class="docutils literal notranslate"><span class="pre">'#'</span></code> to end-of-
line, as well as any
whitespace leading up to the
<code class="docutils literal notranslate"><span class="pre">'#'</span></code>—unless it is
escaped by a backslash</td>
<td>true</td>
</tr>
<tr class="row-odd"><td><em>lstrip_ws</em></td>
<td>strip leading whitespace from
each line before returning it</td>
<td>false</td>
</tr>
<tr class="row-even"><td><em>rstrip_ws</em></td>
<td>strip trailing whitespace
(including line terminator!)
from each line before
returning it.</td>
<td>true</td>
</tr>
<tr class="row-odd"><td><em>skip_blanks</em></td>
<td>skip lines that are empty
*after* stripping comments
and whitespace.  (If both
lstrip_ws and rstrip_ws are
false, then some lines may
consist of solely whitespace:
these will *not* be skipped,
even if <em>skip_blanks</em> is
true.)</td>
<td>true</td>
</tr>
<tr class="row-even"><td><em>join_lines</em></td>
<td>if a backslash is the last
non-newline character on a
line after stripping comments
and whitespace, join the
following line to it to form
one logical line; if N
consecutive lines end with a
backslash, then N+1 physical
lines will be joined to form
one logical line.</td>
<td>false</td>
</tr>
<tr class="row-odd"><td><em>collapse_join</em></td>
<td>strip leading whitespace from
lines that are joined to their
predecessor; only matters if
<code class="docutils literal notranslate"><span class="pre">(join_lines</span> <span class="pre">and</span> <span class="pre">not</span>
<span class="pre">lstrip_ws)</span></code></td>
<td>false</td>
</tr>
</tbody>
</table>
<p>Note that since <em>rstrip_ws</em> can strip the trailing newline, the semantics of
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> must differ from those of the built-in file object’s
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method!  In particular, <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>  returns <code class="docutils literal notranslate"><span class="pre">None</span></code> for
end-of-file: an empty string might just be a  blank line (or an all-whitespace
line), if <em>rstrip_ws</em> is true  but <em>skip_blanks</em> is not.</p>
<dl class="method">
<dt id="distutils.text_file.TextFile.open">
<code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a new file <em>filename</em>.  This overrides any <em>file</em> or <em>filename</em>
constructor arguments.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.text_file.TextFile.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the current file and forget everything we know about it (including the
filename and the current line number).</p>
</dd></dl>

<dl class="method">
<dt id="distutils.text_file.TextFile.warn">
<code class="descname">warn</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>line=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.warn" title="Permalink to this definition">¶</a></dt>
<dd><p>Print (to stderr) a warning message tied to the current logical line in the
current file.  If the current logical line in the file spans multiple physical
lines, the warning refers to the whole range, such as <code class="docutils literal notranslate"><span class="pre">&quot;lines</span> <span class="pre">3-5&quot;</span></code>.  If
<em>line</em> is supplied,  it overrides the current line number; it may be a list or
tuple  to indicate a range of physical lines, or an integer for a  single
physical line.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.text_file.TextFile.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return a single logical line from the current file (or from an internal
buffer if lines have previously been “unread” with <a class="reference internal" href="#distutils.text_file.TextFile.unreadline" title="distutils.text_file.TextFile.unreadline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unreadline()</span></code></a>).  If the
<em>join_lines</em> option  is true, this may involve reading multiple physical lines
concatenated into a single string.  Updates the current line number,  so calling
<a class="reference internal" href="#distutils.text_file.TextFile.warn" title="distutils.text_file.TextFile.warn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">warn()</span></code></a> after <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> emits a warning  about the physical line(s)
just read.  Returns <code class="docutils literal notranslate"><span class="pre">None</span></code> on end-of-file,  since the empty string can occur
if <em>rstrip_ws</em> is true but  <em>strip_blanks</em> is not.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.text_file.TextFile.readlines">
<code class="descname">readlines</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return the list of all logical lines remaining in the current file.
This updates the current line number to the last line of the file.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.text_file.TextFile.unreadline">
<code class="descname">unreadline</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.text_file.TextFile.unreadline" title="Permalink to this definition">¶</a></dt>
<dd><p>Push <em>line</em> (a string) onto an internal buffer that will be checked by future
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> calls.  Handy for implementing a parser with line-at-a-time
lookahead. Note that lines that are “unread” with <a class="reference internal" href="#distutils.text_file.TextFile.unreadline" title="distutils.text_file.TextFile.unreadline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unreadline()</span></code></a> are not
subsequently re-cleansed (whitespace  stripped, or whatever) when read with
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>. If multiple calls are made to <a class="reference internal" href="#distutils.text_file.TextFile.unreadline" title="distutils.text_file.TextFile.unreadline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unreadline()</span></code></a> before a call
to <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, the lines will be returned most in most recent first order.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="module-distutils.version">
<span id="distutils-version-version-number-classes"></span><h2>10.23. <a class="reference internal" href="#module-distutils.version" title="distutils.version: implements classes that represent module version numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.version</span></code></a> — Version number classes<a class="headerlink" href="#module-distutils.version" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.cmd">
<span id="distutils-cmd-abstract-base-class-for-distutils-commands"></span><h2>10.24. <a class="reference internal" href="#module-distutils.cmd" title="distutils.cmd: This module provides the abstract base class Command. This class is subclassed by the modules in the distutils.command subpackage."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.cmd</span></code></a> — Abstract base class for Distutils commands<a class="headerlink" href="#module-distutils.cmd" title="Permalink to this headline">¶</a></h2>
<p>This module supplies the abstract base class <a class="reference internal" href="#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code></a>.</p>
<dl class="class">
<dt id="distutils.cmd.Command">
<em class="property">class </em><code class="descclassname">distutils.cmd.</code><code class="descname">Command</code><span class="sig-paren">(</span><em>dist</em><span class="sig-paren">)</span><a class="headerlink" href="#distutils.cmd.Command" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for defining command classes, the “worker bees” of the
Distutils.  A useful analogy for command classes is to think of them as
subroutines with local variables called <em>options</em>.  The options are declared
in <a class="reference internal" href="#distutils.cmd.Command.initialize_options" title="distutils.cmd.Command.initialize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">initialize_options()</span></code></a> and defined (given their final values) in
<a class="reference internal" href="#distutils.cmd.Command.finalize_options" title="distutils.cmd.Command.finalize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finalize_options()</span></code></a>, both of which must be defined by every command
class.  The distinction between the two is necessary because option values
might come from the outside world (command line, config file, …), and any
options dependent on other options must be computed after these outside
influences have been processed — hence <a class="reference internal" href="#distutils.cmd.Command.finalize_options" title="distutils.cmd.Command.finalize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finalize_options()</span></code></a>.  The body
of the subroutine, where it does all its work based on the values of its
options, is the <a class="reference internal" href="#distutils.cmd.Command.run" title="distutils.cmd.Command.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method, which must also be implemented by every
command class.</p>
<p>The class constructor takes a single argument <em>dist</em>, a
<a class="reference internal" href="#distutils.core.Distribution" title="distutils.core.Distribution"><code class="xref py py-class docutils literal notranslate"><span class="pre">Distribution</span></code></a> instance.</p>
</dd></dl>

</div>
<div class="section" id="creating-a-new-distutils-command">
<h2>10.25. Creating a new Distutils command<a class="headerlink" href="#creating-a-new-distutils-command" title="Permalink to this headline">¶</a></h2>
<p>This section outlines the steps to create a new Distutils command.</p>
<p>A new command lives in a module in the <a class="reference internal" href="#module-distutils.command" title="distutils.command: This subpackage contains one module for each standard Distutils command."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command</span></code></a> package. There
is a sample template in that directory called <code class="file docutils literal notranslate"><span class="pre">command_template</span></code>.  Copy
this file to a new module with the same name as the new command you’re
implementing.  This module should implement a class with the same name as the
module (and the command).  So, for instance, to create the command
<code class="docutils literal notranslate"><span class="pre">peel_banana</span></code> (so that users can run <code class="docutils literal notranslate"><span class="pre">setup.py</span> <span class="pre">peel_banana</span></code>), you’d copy
<code class="file docutils literal notranslate"><span class="pre">command_template</span></code> to <code class="file docutils literal notranslate"><span class="pre">distutils/command/peel_banana.py</span></code>, then edit
it so that it’s implementing the class <code class="xref py py-class docutils literal notranslate"><span class="pre">peel_banana</span></code>, a subclass of
<a class="reference internal" href="#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.cmd.Command</span></code></a>.</p>
<p>Subclasses of <a class="reference internal" href="#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code></a> must define the following methods.</p>
<dl class="method">
<dt id="distutils.cmd.Command.initialize_options">
<code class="descclassname">Command.</code><code class="descname">initialize_options</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.cmd.Command.initialize_options" title="Permalink to this definition">¶</a></dt>
<dd><p>Set default values for all the options that this command supports.  Note that
these defaults may be overridden by other commands, by the setup script, by
config files, or by the command-line.  Thus, this is not the place to code
dependencies between options; generally, <a class="reference internal" href="#distutils.cmd.Command.initialize_options" title="distutils.cmd.Command.initialize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">initialize_options()</span></code></a>
implementations are just a bunch of <code class="docutils literal notranslate"><span class="pre">self.foo</span> <span class="pre">=</span> <span class="pre">None</span></code> assignments.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.cmd.Command.finalize_options">
<code class="descclassname">Command.</code><code class="descname">finalize_options</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.cmd.Command.finalize_options" title="Permalink to this definition">¶</a></dt>
<dd><p>Set final values for all the options that this command supports. This is
always called as late as possible, ie.  after any option assignments from the
command-line or from other commands have been done.  Thus, this is the place
to code option dependencies: if <em>foo</em> depends on <em>bar</em>, then it is safe to
set <em>foo</em> from <em>bar</em> as long as <em>foo</em> still has the same value it was
assigned in <a class="reference internal" href="#distutils.cmd.Command.initialize_options" title="distutils.cmd.Command.initialize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">initialize_options()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="distutils.cmd.Command.run">
<code class="descclassname">Command.</code><code class="descname">run</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#distutils.cmd.Command.run" title="Permalink to this definition">¶</a></dt>
<dd><p>A command’s raison d’etre: carry out the action it exists to perform, controlled
by the options initialized in <a class="reference internal" href="#distutils.cmd.Command.initialize_options" title="distutils.cmd.Command.initialize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">initialize_options()</span></code></a>, customized by other
commands, the setup script, the command-line, and config files, and finalized in
<a class="reference internal" href="#distutils.cmd.Command.finalize_options" title="distutils.cmd.Command.finalize_options"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finalize_options()</span></code></a>.  All terminal output and filesystem interaction should
be done by <a class="reference internal" href="#distutils.cmd.Command.run" title="distutils.cmd.Command.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="distutils.cmd.Command.sub_commands">
<code class="descclassname">Command.</code><code class="descname">sub_commands</code><a class="headerlink" href="#distutils.cmd.Command.sub_commands" title="Permalink to this definition">¶</a></dt>
<dd><p><em>sub_commands</em> formalizes the notion of a “family” of commands,
e.g. <code class="docutils literal notranslate"><span class="pre">install</span></code> as the parent with sub-commands <code class="docutils literal notranslate"><span class="pre">install_lib</span></code>,
<code class="docutils literal notranslate"><span class="pre">install_headers</span></code>, etc.  The parent of a family of commands defines
<em>sub_commands</em> as a class attribute; it’s a list of 2-tuples <code class="docutils literal notranslate"><span class="pre">(command_name,</span>
<span class="pre">predicate)</span></code>, with <em>command_name</em> a string and <em>predicate</em> a function, a
string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <em>predicate</em> is a method of the parent command that
determines whether the corresponding command is applicable in the current
situation.  (E.g. <code class="docutils literal notranslate"><span class="pre">install_headers</span></code> is only applicable if we have any C
header files to install.)  If <em>predicate</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, that command is always
applicable.</p>
<p><em>sub_commands</em> is usually defined at the <em>end</em> of a class, because
predicates can be methods of the class, so they must already have been
defined.  The canonical example is the <strong class="command">install</strong> command.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.command">
<span id="distutils-command-individual-distutils-commands"></span><h2>10.26. <a class="reference internal" href="#module-distutils.command" title="distutils.command: This subpackage contains one module for each standard Distutils command."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command</span></code></a> — Individual Distutils commands<a class="headerlink" href="#module-distutils.command" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.bdist">
<span id="distutils-command-bdist-build-a-binary-installer"></span><h2>10.27. <a class="reference internal" href="#module-distutils.command.bdist" title="distutils.command.bdist: Build a binary installer for a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist</span></code></a> — Build a binary installer<a class="headerlink" href="#module-distutils.command.bdist" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.bdist_packager">
<span id="distutils-command-bdist-packager-abstract-base-class-for-packagers"></span><h2>10.28. <a class="reference internal" href="#module-distutils.command.bdist_packager" title="distutils.command.bdist_packager: Abstract base class for packagers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist_packager</span></code></a> — Abstract base class for packagers<a class="headerlink" href="#module-distutils.command.bdist_packager" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.bdist_dumb">
<span id="distutils-command-bdist-dumb-build-a-dumb-installer"></span><h2>10.29. <a class="reference internal" href="#module-distutils.command.bdist_dumb" title="distutils.command.bdist_dumb: Build a &quot;dumb&quot; installer - a simple archive of files"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist_dumb</span></code></a> — Build a “dumb” installer<a class="headerlink" href="#module-distutils.command.bdist_dumb" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.bdist_msi">
<span id="distutils-command-bdist-msi-build-a-microsoft-installer-binary-package"></span><h2>10.30. <a class="reference internal" href="#module-distutils.command.bdist_msi" title="distutils.command.bdist_msi: Build a binary distribution as a Windows MSI file"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist_msi</span></code></a> — Build a Microsoft Installer binary package<a class="headerlink" href="#module-distutils.command.bdist_msi" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="distutils.command.bdist_msi.bdist_msi">
<em class="property">class </em><code class="descclassname">distutils.command.bdist_msi.</code><code class="descname">bdist_msi</code><a class="headerlink" href="#distutils.command.bdist_msi.bdist_msi" title="Permalink to this definition">¶</a></dt>
<dd><p>Builds a <a class="reference external" href="https://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx">Windows Installer</a> (.msi) binary package.</p>
<p>In most cases, the <code class="docutils literal notranslate"><span class="pre">bdist_msi</span></code> installer is a better choice than the
<code class="docutils literal notranslate"><span class="pre">bdist_wininst</span></code> installer, because it provides better support for
Win64 platforms, allows administrators to perform non-interactive
installations, and allows installation through group policies.</p>
</dd></dl>

</div>
<div class="section" id="module-distutils.command.bdist_rpm">
<span id="distutils-command-bdist-rpm-build-a-binary-distribution-as-a-redhat-rpm-and-srpm"></span><h2>10.31. <a class="reference internal" href="#module-distutils.command.bdist_rpm" title="distutils.command.bdist_rpm: Build a binary distribution as a Redhat RPM and SRPM"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist_rpm</span></code></a> — Build a binary distribution as a Redhat RPM and SRPM<a class="headerlink" href="#module-distutils.command.bdist_rpm" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.bdist_wininst">
<span id="distutils-command-bdist-wininst-build-a-windows-installer"></span><h2>10.32. <a class="reference internal" href="#module-distutils.command.bdist_wininst" title="distutils.command.bdist_wininst: Build a Windows installer"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.bdist_wininst</span></code></a> — Build a Windows installer<a class="headerlink" href="#module-distutils.command.bdist_wininst" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.sdist">
<span id="distutils-command-sdist-build-a-source-distribution"></span><h2>10.33. <a class="reference internal" href="#module-distutils.command.sdist" title="distutils.command.sdist: Build a source distribution"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.sdist</span></code></a> — Build a source distribution<a class="headerlink" href="#module-distutils.command.sdist" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.build">
<span id="distutils-command-build-build-all-files-of-a-package"></span><h2>10.34. <a class="reference internal" href="#module-distutils.command.build" title="distutils.command.build: Build all files of a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.build</span></code></a> — Build all files of a package<a class="headerlink" href="#module-distutils.command.build" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.build_clib">
<span id="distutils-command-build-clib-build-any-c-libraries-in-a-package"></span><h2>10.35. <a class="reference internal" href="#module-distutils.command.build_clib" title="distutils.command.build_clib: Build any C libraries in a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.build_clib</span></code></a> — Build any C libraries in a package<a class="headerlink" href="#module-distutils.command.build_clib" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.build_ext">
<span id="distutils-command-build-ext-build-any-extensions-in-a-package"></span><h2>10.36. <a class="reference internal" href="#module-distutils.command.build_ext" title="distutils.command.build_ext: Build any extensions in a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.build_ext</span></code></a> — Build any extensions in a package<a class="headerlink" href="#module-distutils.command.build_ext" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.build_py">
<span id="distutils-command-build-py-build-the-py-pyc-files-of-a-package"></span><h2>10.37. <a class="reference internal" href="#module-distutils.command.build_py" title="distutils.command.build_py: Build the .py/.pyc files of a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.build_py</span></code></a> — Build the .py/.pyc files of a package<a class="headerlink" href="#module-distutils.command.build_py" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.build_scripts">
<span id="distutils-command-build-scripts-build-the-scripts-of-a-package"></span><h2>10.38. <a class="reference internal" href="#module-distutils.command.build_scripts" title="distutils.command.build_scripts: Build the scripts of a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.build_scripts</span></code></a> — Build the scripts of a package<a class="headerlink" href="#module-distutils.command.build_scripts" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.clean">
<span id="distutils-command-clean-clean-a-package-build-area"></span><h2>10.39. <a class="reference internal" href="#module-distutils.command.clean" title="distutils.command.clean: Clean a package build area"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.clean</span></code></a> — Clean a package build area<a class="headerlink" href="#module-distutils.command.clean" title="Permalink to this headline">¶</a></h2>
<p>This command removes the temporary files created by <strong class="command">build</strong>
and its subcommands, like intermediary compiled object files.  With
the <code class="docutils literal notranslate"><span class="pre">--all</span></code> option, the complete build directory will be removed.</p>
<p>Extension modules built <a class="reference internal" href="configfile.html#distutils-build-ext-inplace"><span class="std std-ref">in place</span></a>
will not be cleaned, as they are not in the build directory.</p>
</div>
<div class="section" id="module-distutils.command.config">
<span id="distutils-command-config-perform-package-configuration"></span><h2>10.40. <a class="reference internal" href="#module-distutils.command.config" title="distutils.command.config: Perform package configuration"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.config</span></code></a> — Perform package configuration<a class="headerlink" href="#module-distutils.command.config" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.install">
<span id="distutils-command-install-install-a-package"></span><h2>10.41. <a class="reference internal" href="#module-distutils.command.install" title="distutils.command.install: Install a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.install</span></code></a> — Install a package<a class="headerlink" href="#module-distutils.command.install" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.install_data">
<span id="distutils-command-install-data-install-data-files-from-a-package"></span><h2>10.42. <a class="reference internal" href="#module-distutils.command.install_data" title="distutils.command.install_data: Install data files from a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.install_data</span></code></a> — Install data files from a package<a class="headerlink" href="#module-distutils.command.install_data" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.install_headers">
<span id="distutils-command-install-headers-install-c-c-header-files-from-a-package"></span><h2>10.43. <a class="reference internal" href="#module-distutils.command.install_headers" title="distutils.command.install_headers: Install C/C++ header files from a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.install_headers</span></code></a> — Install C/C++ header files from a package<a class="headerlink" href="#module-distutils.command.install_headers" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.install_lib">
<span id="distutils-command-install-lib-install-library-files-from-a-package"></span><h2>10.44. <a class="reference internal" href="#module-distutils.command.install_lib" title="distutils.command.install_lib: Install library files from a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.install_lib</span></code></a> — Install library files from a package<a class="headerlink" href="#module-distutils.command.install_lib" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.install_scripts">
<span id="distutils-command-install-scripts-install-script-files-from-a-package"></span><h2>10.45. <a class="reference internal" href="#module-distutils.command.install_scripts" title="distutils.command.install_scripts: Install script files from a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.install_scripts</span></code></a> — Install script files from a package<a class="headerlink" href="#module-distutils.command.install_scripts" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-distutils.command.register">
<span id="distutils-command-register-register-a-module-with-the-python-package-index"></span><h2>10.46. <a class="reference internal" href="#module-distutils.command.register" title="distutils.command.register: Register a module with the Python Package Index"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.register</span></code></a> — Register a module with the Python Package Index<a class="headerlink" href="#module-distutils.command.register" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">register</span></code> command registers the package with the Python Package  Index.
This is described in more detail in <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0301"><strong>PEP 301</strong></a>.</p>
</div>
<div class="section" id="module-distutils.command.check">
<span id="distutils-command-check-check-the-meta-data-of-a-package"></span><h2>10.47. <a class="reference internal" href="#module-distutils.command.check" title="distutils.command.check: Check the metadata of a package"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command.check</span></code></a> — Check the meta-data of a package<a class="headerlink" href="#module-distutils.command.check" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">check</span></code> command performs some tests on the meta-data of a package.
For example, it verifies that all required meta-data are provided as
the arguments passed to the <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">10. API Reference</a><ul>
<li><a class="reference internal" href="#module-distutils.core">10.1. <code class="docutils literal notranslate"><span class="pre">distutils.core</span></code> — Core Distutils functionality</a></li>
<li><a class="reference internal" href="#module-distutils.ccompiler">10.2. <code class="docutils literal notranslate"><span class="pre">distutils.ccompiler</span></code> — CCompiler base class</a></li>
<li><a class="reference internal" href="#module-distutils.unixccompiler">10.3. <code class="docutils literal notranslate"><span class="pre">distutils.unixccompiler</span></code> — Unix C Compiler</a></li>
<li><a class="reference internal" href="#module-distutils.msvccompiler">10.4. <code class="docutils literal notranslate"><span class="pre">distutils.msvccompiler</span></code> — Microsoft Compiler</a></li>
<li><a class="reference internal" href="#module-distutils.bcppcompiler">10.5. <code class="docutils literal notranslate"><span class="pre">distutils.bcppcompiler</span></code> — Borland Compiler</a></li>
<li><a class="reference internal" href="#module-distutils.cygwinccompiler">10.6. <code class="docutils literal notranslate"><span class="pre">distutils.cygwincompiler</span></code> — Cygwin Compiler</a></li>
<li><a class="reference internal" href="#module-distutils.emxccompiler">10.7. <code class="docutils literal notranslate"><span class="pre">distutils.emxccompiler</span></code> — OS/2 EMX Compiler</a></li>
<li><a class="reference internal" href="#module-distutils.archive_util">10.8. <code class="docutils literal notranslate"><span class="pre">distutils.archive_util</span></code> —  Archiving utilities</a></li>
<li><a class="reference internal" href="#module-distutils.dep_util">10.9. <code class="docutils literal notranslate"><span class="pre">distutils.dep_util</span></code> — Dependency checking</a></li>
<li><a class="reference internal" href="#module-distutils.dir_util">10.10. <code class="docutils literal notranslate"><span class="pre">distutils.dir_util</span></code> — Directory tree operations</a></li>
<li><a class="reference internal" href="#module-distutils.file_util">10.11. <code class="docutils literal notranslate"><span class="pre">distutils.file_util</span></code> — Single file operations</a></li>
<li><a class="reference internal" href="#module-distutils.util">10.12. <code class="docutils literal notranslate"><span class="pre">distutils.util</span></code> — Miscellaneous other utility functions</a></li>
<li><a class="reference internal" href="#module-distutils.dist">10.13. <code class="docutils literal notranslate"><span class="pre">distutils.dist</span></code> — The Distribution class</a></li>
<li><a class="reference internal" href="#module-distutils.extension">10.14. <code class="docutils literal notranslate"><span class="pre">distutils.extension</span></code> — The Extension class</a></li>
<li><a class="reference internal" href="#module-distutils.debug">10.15. <code class="docutils literal notranslate"><span class="pre">distutils.debug</span></code> — Distutils debug mode</a></li>
<li><a class="reference internal" href="#module-distutils.errors">10.16. <code class="docutils literal notranslate"><span class="pre">distutils.errors</span></code> — Distutils exceptions</a></li>
<li><a class="reference internal" href="#module-distutils.fancy_getopt">10.17. <code class="docutils literal notranslate"><span class="pre">distutils.fancy_getopt</span></code> — Wrapper around the standard getopt module</a></li>
<li><a class="reference internal" href="#module-distutils.filelist">10.18. <code class="docutils literal notranslate"><span class="pre">distutils.filelist</span></code> — The FileList class</a></li>
<li><a class="reference internal" href="#module-distutils.log">10.19. <code class="docutils literal notranslate"><span class="pre">distutils.log</span></code> — Simple PEP 282-style logging</a></li>
<li><a class="reference internal" href="#module-distutils.spawn">10.20. <code class="docutils literal notranslate"><span class="pre">distutils.spawn</span></code> — Spawn a sub-process</a></li>
<li><a class="reference internal" href="#module-distutils.sysconfig">10.21. <code class="docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code> — System configuration information</a></li>
<li><a class="reference internal" href="#module-distutils.text_file">10.22. <code class="docutils literal notranslate"><span class="pre">distutils.text_file</span></code> — The TextFile class</a></li>
<li><a class="reference internal" href="#module-distutils.version">10.23. <code class="docutils literal notranslate"><span class="pre">distutils.version</span></code> — Version number classes</a></li>
<li><a class="reference internal" href="#module-distutils.cmd">10.24. <code class="docutils literal notranslate"><span class="pre">distutils.cmd</span></code> — Abstract base class for Distutils commands</a></li>
<li><a class="reference internal" href="#creating-a-new-distutils-command">10.25. Creating a new Distutils command</a></li>
<li><a class="reference internal" href="#module-distutils.command">10.26. <code class="docutils literal notranslate"><span class="pre">distutils.command</span></code> — Individual Distutils commands</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist">10.27. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist</span></code> — Build a binary installer</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist_packager">10.28. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_packager</span></code> — Abstract base class for packagers</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist_dumb">10.29. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_dumb</span></code> — Build a “dumb” installer</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist_msi">10.30. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_msi</span></code> — Build a Microsoft Installer binary package</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist_rpm">10.31. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_rpm</span></code> — Build a binary distribution as a Redhat RPM and SRPM</a></li>
<li><a class="reference internal" href="#module-distutils.command.bdist_wininst">10.32. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_wininst</span></code> — Build a Windows installer</a></li>
<li><a class="reference internal" href="#module-distutils.command.sdist">10.33. <code class="docutils literal notranslate"><span class="pre">distutils.command.sdist</span></code> — Build a source distribution</a></li>
<li><a class="reference internal" href="#module-distutils.command.build">10.34. <code class="docutils literal notranslate"><span class="pre">distutils.command.build</span></code> — Build all files of a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.build_clib">10.35. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_clib</span></code> — Build any C libraries in a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.build_ext">10.36. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_ext</span></code> — Build any extensions in a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.build_py">10.37. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_py</span></code> — Build the .py/.pyc files of a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.build_scripts">10.38. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_scripts</span></code> — Build the scripts of a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.clean">10.39. <code class="docutils literal notranslate"><span class="pre">distutils.command.clean</span></code> — Clean a package build area</a></li>
<li><a class="reference internal" href="#module-distutils.command.config">10.40. <code class="docutils literal notranslate"><span class="pre">distutils.command.config</span></code> — Perform package configuration</a></li>
<li><a class="reference internal" href="#module-distutils.command.install">10.41. <code class="docutils literal notranslate"><span class="pre">distutils.command.install</span></code> — Install a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.install_data">10.42. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_data</span></code> — Install data files from a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.install_headers">10.43. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_headers</span></code> — Install C/C++ header files from a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.install_lib">10.44. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_lib</span></code> — Install library files from a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.install_scripts">10.45. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_scripts</span></code> — Install script files from a package</a></li>
<li><a class="reference internal" href="#module-distutils.command.register">10.46. <code class="docutils literal notranslate"><span class="pre">distutils.command.register</span></code> — Register a module with the Python Package Index</a></li>
<li><a class="reference internal" href="#module-distutils.command.check">10.47. <code class="docutils literal notranslate"><span class="pre">distutils.command.check</span></code> — Check the meta-data of a package</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="commandref.html"
                        title="previous chapter">9. Command Reference</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../install/index.html"
                        title="next chapter">Installing Python Modules (Legacy version)</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/apiref.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../install/index.html" title="Installing Python Modules (Legacy version)"
             >next</a> |</li>
        <li class="right" >
          <a href="commandref.html" title="9. Command Reference"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�5�S��html/distutils/builtdist.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>5. Creating Built Distributions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="6. The Python Package Index (PyPI)" href="packageindex.html" />
    <link rel="prev" title="4. Creating a Source Distribution" href="sourcedist.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/builtdist.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="packageindex.html" title="6. The Python Package Index (PyPI)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sourcedist.html" title="4. Creating a Source Distribution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="creating-built-distributions">
<span id="built-dist"></span><h1>5. Creating Built Distributions<a class="headerlink" href="#creating-built-distributions" title="Permalink to this headline">¶</a></h1>
<p>A “built distribution” is what you’re probably used to thinking of either as a
“binary package” or an “installer” (depending on your background).  It’s not
necessarily binary, though, because it might contain only Python source code
and/or byte-code; and we don’t call it a package, because that word is already
spoken for in Python.  (And “installer” is a term specific to the world of
mainstream desktop systems.)</p>
<p>A built distribution is how you make life as easy as possible for installers of
your module distribution: for users of RPM-based Linux systems, it’s a binary
RPM; for Windows users, it’s an executable installer; for Debian-based Linux
users, it’s a Debian package; and so forth.  Obviously, no one person will be
able to create built distributions for every platform under the sun, so the
Distutils are designed to enable module developers to concentrate on their
specialty—writing code and creating source distributions—while an
intermediary species called <em>packagers</em> springs up to turn source distributions
into built distributions for as many platforms as there are packagers.</p>
<p>Of course, the module developer could be their own packager; or the packager could
be a volunteer “out there” somewhere who has access to a platform which the
original developer does not; or it could be software periodically grabbing new
source distributions and turning them into built distributions for as many
platforms as the software has access to.  Regardless of who they are, a packager
uses the setup script and the <strong class="command">bdist</strong> command family to generate built
distributions.</p>
<p>As a simple example, if I run the following command in the Distutils source
tree:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist</span>
</pre></div>
</div>
<p>then the Distutils builds my module distribution (the Distutils itself in this
case), does a “fake” installation (also in the <code class="file docutils literal notranslate"><span class="pre">build</span></code> directory), and
creates the default type of built distribution for my platform.  The default
format for built distributions is a “dumb” tar file on Unix, and a simple
executable installer on Windows.  (That tar file is considered “dumb” because it
has to be unpacked in a specific location to work.)</p>
<p>Thus, the above command on a Unix system creates
<code class="file docutils literal notranslate"><span class="pre">Distutils-1.0.</span><em><span class="pre">plat</span></em><span class="pre">.tar.gz</span></code>; unpacking this tarball from the right place
installs the Distutils just as though you had downloaded the source distribution
and run <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">install</span></code>.  (The “right place” is either the root of
the filesystem or  Python’s <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> directory, depending on the options
given to the <strong class="command">bdist_dumb</strong> command; the default is to make dumb
distributions relative to <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code>.)</p>
<p>Obviously, for pure Python distributions, this isn’t any simpler than just
running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">install</span></code>—but for non-pure distributions, which
include extensions that would need to be compiled, it can mean the difference
between someone being able to use your extensions or not.  And creating “smart”
built distributions, such as an RPM package or an executable installer for
Windows, is far more convenient for users even if your distribution doesn’t
include any extensions.</p>
<p>The <strong class="command">bdist</strong> command has a <code class="xref std std-option docutils literal notranslate"><span class="pre">--formats</span></code> option, similar to the
<strong class="command">sdist</strong> command, which you can use to select the types of built
distribution to generate: for example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist</span> <span class="o">--</span><span class="nb">format</span><span class="o">=</span><span class="nb">zip</span>
</pre></div>
</div>
<p>would, when run on a Unix system, create <code class="file docutils literal notranslate"><span class="pre">Distutils-1.0.</span><em><span class="pre">plat</span></em><span class="pre">.zip</span></code>—again, this archive would be unpacked from the root directory to install the
Distutils.</p>
<p>The available formats for built distributions are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="58%" />
<col width="17%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Description</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">gztar</span></code></td>
<td>gzipped tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.gz</span></code>)</td>
<td>(1),(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ztar</span></code></td>
<td>compressed tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.Z</span></code>)</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">tar</span></code></td>
<td>tar file (<code class="file docutils literal notranslate"><span class="pre">.tar</span></code>)</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">zip</span></code></td>
<td>zip file (<code class="file docutils literal notranslate"><span class="pre">.zip</span></code>)</td>
<td>(2),(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">rpm</span></code></td>
<td>RPM</td>
<td>(5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">pkgtool</span></code></td>
<td>Solaris <strong class="program">pkgtool</strong></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">sdux</span></code></td>
<td>HP-UX <strong class="program">swinstall</strong></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">wininst</span></code></td>
<td>self-extracting ZIP file for
Windows</td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">msi</span></code></td>
<td>Microsoft Installer.</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>default on Unix</li>
<li>default on Windows</li>
<li>requires external utilities: <strong class="program">tar</strong> and possibly one of <strong class="program">gzip</strong>,
<strong class="program">bzip2</strong>, or <strong class="program">compress</strong></li>
<li>requires either external <strong class="program">zip</strong> utility or <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module (part
of the standard Python library since Python 1.6)</li>
<li>requires external <strong class="program">rpm</strong> utility, version 3.0.4 or better (use <code class="docutils literal notranslate"><span class="pre">rpm</span>
<span class="pre">--version</span></code> to find out which version you have)</li>
</ol>
<p>You don’t have to use the <strong class="command">bdist</strong> command with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--formats</span></code>
option; you can also use the command that directly implements the format you’re
interested in.  Some of these <strong class="command">bdist</strong> “sub-commands” actually generate
several similar formats; for instance, the <strong class="command">bdist_dumb</strong> command
generates all the “dumb” archive formats (<code class="docutils literal notranslate"><span class="pre">tar</span></code>, <code class="docutils literal notranslate"><span class="pre">ztar</span></code>, <code class="docutils literal notranslate"><span class="pre">gztar</span></code>, and
<code class="docutils literal notranslate"><span class="pre">zip</span></code>), and <strong class="command">bdist_rpm</strong> generates both binary and source RPMs.  The
<strong class="command">bdist</strong> sub-commands, and the formats generated by each, are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="53%" />
<col width="47%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Command</th>
<th class="head">Formats</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><strong class="command">bdist_dumb</strong></td>
<td>tar, ztar, gztar, zip</td>
</tr>
<tr class="row-odd"><td><strong class="command">bdist_rpm</strong></td>
<td>rpm, srpm</td>
</tr>
<tr class="row-even"><td><strong class="command">bdist_wininst</strong></td>
<td>wininst</td>
</tr>
<tr class="row-odd"><td><strong class="command">bdist_msi</strong></td>
<td>msi</td>
</tr>
</tbody>
</table>
<p>The following sections give details on the individual <strong class="command">bdist_*</strong>
commands.</p>
<div class="section" id="creating-dumb-built-distributions">
<span id="creating-dumb"></span><h2>5.1. Creating dumb built distributions<a class="headerlink" href="#creating-dumb-built-distributions" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="creating-rpm-packages">
<span id="creating-rpms"></span><h2>5.2. Creating RPM packages<a class="headerlink" href="#creating-rpm-packages" title="Permalink to this headline">¶</a></h2>
<p>The RPM format is used by many popular Linux distributions, including Red Hat,
SuSE, and Mandrake.  If one of these (or any of the other RPM-based Linux
distributions) is your usual environment, creating RPM packages for other users
of that same distribution is trivial. Depending on the complexity of your module
distribution and differences between Linux distributions, you may also be able
to create RPMs that work on different RPM-based distributions.</p>
<p>The usual way to create an RPM of your module distribution is to run the
<strong class="command">bdist_rpm</strong> command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist_rpm</span>
</pre></div>
</div>
<p>or the <strong class="command">bdist</strong> command with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--format</span></code> option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist</span> <span class="o">--</span><span class="n">formats</span><span class="o">=</span><span class="n">rpm</span>
</pre></div>
</div>
<p>The former allows you to specify RPM-specific options; the latter allows  you to
easily specify multiple formats in one run.  If you need to do both, you can
explicitly specify multiple <strong class="command">bdist_*</strong> commands and their options:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist_rpm</span> <span class="o">--</span><span class="n">packager</span><span class="o">=</span><span class="s2">&quot;John Doe &lt;jdoe@example.org&gt;&quot;</span> \
                <span class="n">bdist_wininst</span> <span class="o">--</span><span class="n">target</span><span class="o">-</span><span class="n">version</span><span class="o">=</span><span class="s2">&quot;2.0&quot;</span>
</pre></div>
</div>
<p>Creating RPM packages is driven by a <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file, much as using the
Distutils is driven by the setup script.  To make your life easier, the
<strong class="command">bdist_rpm</strong> command normally creates a <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file based on the
information you supply in the setup script, on the command line, and in any
Distutils configuration files.  Various options and sections in the
<code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file are derived from options in the setup script as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">RPM <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file option or section</th>
<th class="head">Distutils setup script option</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Name</td>
<td><code class="docutils literal notranslate"><span class="pre">name</span></code></td>
</tr>
<tr class="row-odd"><td>Summary (in preamble)</td>
<td><code class="docutils literal notranslate"><span class="pre">description</span></code></td>
</tr>
<tr class="row-even"><td>Version</td>
<td><code class="docutils literal notranslate"><span class="pre">version</span></code></td>
</tr>
<tr class="row-odd"><td>Vendor</td>
<td><code class="docutils literal notranslate"><span class="pre">author</span></code> and <code class="docutils literal notranslate"><span class="pre">author_email</span></code>,
or  — &amp; <code class="docutils literal notranslate"><span class="pre">maintainer</span></code> and
<code class="docutils literal notranslate"><span class="pre">maintainer_email</span></code></td>
</tr>
<tr class="row-even"><td>Copyright</td>
<td><code class="docutils literal notranslate"><span class="pre">license</span></code></td>
</tr>
<tr class="row-odd"><td>Url</td>
<td><code class="docutils literal notranslate"><span class="pre">url</span></code></td>
</tr>
<tr class="row-even"><td>%description (section)</td>
<td><code class="docutils literal notranslate"><span class="pre">long_description</span></code></td>
</tr>
</tbody>
</table>
<p>Additionally, there are many options in <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> files that don’t have
corresponding options in the setup script.  Most of these are handled through
options to the <strong class="command">bdist_rpm</strong> command as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="36%" />
<col width="34%" />
<col width="29%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">RPM <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file option
or section</th>
<th class="head"><strong class="command">bdist_rpm</strong> option</th>
<th class="head">default value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Release</td>
<td><code class="docutils literal notranslate"><span class="pre">release</span></code></td>
<td>“1”</td>
</tr>
<tr class="row-odd"><td>Group</td>
<td><code class="docutils literal notranslate"><span class="pre">group</span></code></td>
<td>“Development/Libraries”</td>
</tr>
<tr class="row-even"><td>Vendor</td>
<td><code class="docutils literal notranslate"><span class="pre">vendor</span></code></td>
<td>(see above)</td>
</tr>
<tr class="row-odd"><td>Packager</td>
<td><code class="docutils literal notranslate"><span class="pre">packager</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-even"><td>Provides</td>
<td><code class="docutils literal notranslate"><span class="pre">provides</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-odd"><td>Requires</td>
<td><code class="docutils literal notranslate"><span class="pre">requires</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-even"><td>Conflicts</td>
<td><code class="docutils literal notranslate"><span class="pre">conflicts</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-odd"><td>Obsoletes</td>
<td><code class="docutils literal notranslate"><span class="pre">obsoletes</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-even"><td>Distribution</td>
<td><code class="docutils literal notranslate"><span class="pre">distribution_name</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-odd"><td>BuildRequires</td>
<td><code class="docutils literal notranslate"><span class="pre">build_requires</span></code></td>
<td>(none)</td>
</tr>
<tr class="row-even"><td>Icon</td>
<td><code class="docutils literal notranslate"><span class="pre">icon</span></code></td>
<td>(none)</td>
</tr>
</tbody>
</table>
<p>Obviously, supplying even a few of these options on the command-line would be
tedious and error-prone, so it’s usually best to put them in the setup
configuration file, <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code>—see section <a class="reference internal" href="configfile.html#setup-config"><span class="std std-ref">Writing the Setup Configuration File</span></a>.  If
you distribute or package many Python module distributions, you might want to
put options that apply to all of them in your personal Distutils configuration
file (<code class="file docutils literal notranslate"><span class="pre">~/.pydistutils.cfg</span></code>).  If you want to temporarily disable
this file, you can pass the –no-user-cfg option to setup.py.</p>
<p>There are three steps to building a binary RPM package, all of which are
handled automatically by the Distutils:</p>
<ol class="arabic simple">
<li>create a <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file, which describes the package (analogous  to the
Distutils setup script; in fact, much of the information in the  setup script
winds up in the <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file)</li>
<li>create the source RPM</li>
<li>create the “binary” RPM (which may or may not contain binary code, depending
on whether your module distribution contains Python extensions)</li>
</ol>
<p>Normally, RPM bundles the last two steps together; when you use the Distutils,
all three steps are typically bundled together.</p>
<p>If you wish, you can separate these three steps.  You can use the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--spec-only</span></code> option to make <strong class="command">bdist_rpm</strong> just create the
<code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file and exit; in this case, the <code class="file docutils literal notranslate"><span class="pre">.spec</span></code> file will be
written to the “distribution directory”—normally <code class="file docutils literal notranslate"><span class="pre">dist/</span></code>, but
customizable with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--dist-dir</span></code> option.  (Normally, the <code class="file docutils literal notranslate"><span class="pre">.spec</span></code>
file winds up deep in the “build tree,” in a temporary directory created by
<strong class="command">bdist_rpm</strong>.)</p>
</div>
<div class="section" id="creating-windows-installers">
<span id="creating-wininst"></span><h2>5.3. Creating Windows Installers<a class="headerlink" href="#creating-windows-installers" title="Permalink to this headline">¶</a></h2>
<p>Executable installers are the natural format for binary distributions on
Windows.  They display a nice graphical user interface, display some information
about the module distribution to be installed taken from the metadata in the
setup script, let the user select a few options, and start or cancel the
installation.</p>
<p>Since the metadata is taken from the setup script, creating Windows installers
is usually as easy as running:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist_wininst</span>
</pre></div>
</div>
<p>or the <strong class="command">bdist</strong> command with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--formats</span></code> option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist</span> <span class="o">--</span><span class="n">formats</span><span class="o">=</span><span class="n">wininst</span>
</pre></div>
</div>
<p>If you have a pure module distribution (only containing pure Python modules and
packages), the resulting installer will be version independent and have a name
like <code class="file docutils literal notranslate"><span class="pre">foo-1.0.win32.exe</span></code>.  These installers can even be created on Unix
platforms or Mac OS X.</p>
<p>If you have a non-pure distribution, the extensions can only be created on a
Windows platform, and will be Python version dependent. The installer filename
will reflect this and now has the form <code class="file docutils literal notranslate"><span class="pre">foo-1.0.win32-py2.0.exe</span></code>.  You
have to create a separate installer for every Python version you want to
support.</p>
<p>The installer will try to compile pure modules into <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> after installation
on the target system in normal and optimizing mode.  If you don’t want this to
happen for some reason, you can run the <strong class="command">bdist_wininst</strong> command with
the <code class="xref std std-option docutils literal notranslate"><span class="pre">--no-target-compile</span></code> and/or the <code class="xref std std-option docutils literal notranslate"><span class="pre">--no-target-optimize</span></code>
option.</p>
<p>By default the installer will display the cool “Python Powered” logo when it is
run, but you can also supply your own 152x261 bitmap which must be a Windows
<code class="file docutils literal notranslate"><span class="pre">.bmp</span></code> file with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--bitmap</span></code> option.</p>
<p>The installer will also display a large title on the desktop background window
when it is run, which is constructed from the name of your distribution and the
version number.  This can be changed to another text by using the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--title</span></code> option.</p>
<p>The installer file will be written to the “distribution directory” — normally
<code class="file docutils literal notranslate"><span class="pre">dist/</span></code>, but customizable with the <code class="xref std std-option docutils literal notranslate"><span class="pre">--dist-dir</span></code> option.</p>
</div>
<div class="section" id="cross-compiling-on-windows">
<span id="cross-compile-windows"></span><h2>5.4. Cross-compiling on Windows<a class="headerlink" href="#cross-compiling-on-windows" title="Permalink to this headline">¶</a></h2>
<p>Starting with Python 2.6, distutils is capable of cross-compiling between
Windows platforms.  In practice, this means that with the correct tools
installed, you can use a 32bit version of Windows to create 64bit extensions
and vice-versa.</p>
<p>To build for an alternate platform, specify the <code class="xref std std-option docutils literal notranslate"><span class="pre">--plat-name</span></code> option
to the build command.  Valid values are currently ‘win32’, ‘win-amd64’ and
‘win-ia64’.  For example, on a 32bit version of Windows, you could execute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">build</span> <span class="o">--</span><span class="n">plat</span><span class="o">-</span><span class="n">name</span><span class="o">=</span><span class="n">win</span><span class="o">-</span><span class="n">amd64</span>
</pre></div>
</div>
<p>to build a 64bit version of your extension.  The Windows Installers also
support this option, so the command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">build</span> <span class="o">--</span><span class="n">plat</span><span class="o">-</span><span class="n">name</span><span class="o">=</span><span class="n">win</span><span class="o">-</span><span class="n">amd64</span> <span class="n">bdist_wininst</span>
</pre></div>
</div>
<p>would create a 64bit installation executable on your 32bit version of Windows.</p>
<p>To cross-compile, you must download the Python source code and cross-compile
Python itself for the platform you are targeting - it is not possible from a
binary installation of Python (as the .lib etc file for other platforms are
not included.)  In practice, this means the user of a 32 bit operating
system will need to use Visual Studio 2008 to open the
<code class="file docutils literal notranslate"><span class="pre">PCBuild/PCbuild.sln</span></code> solution in the Python source tree and build the
“x64” configuration of the ‘pythoncore’ project before cross-compiling
extensions is possible.</p>
<p>Note that by default, Visual Studio 2008 does not install 64bit compilers or
tools.  You may need to reexecute the Visual Studio setup process and select
these tools (using Control Panel-&gt;[Add/Remove] Programs is a convenient way to
check or modify your existing install.)</p>
<div class="section" id="the-postinstallation-script">
<span id="postinstallation-script"></span><h3>5.4.1. The Postinstallation script<a class="headerlink" href="#the-postinstallation-script" title="Permalink to this headline">¶</a></h3>
<p>Starting with Python 2.3, a postinstallation script can be specified with the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--install-script</span></code> option.  The basename of the script must be
specified, and the script filename must also be listed in the scripts argument
to the setup function.</p>
<p>This script will be run at installation time on the target system after all the
files have been copied, with <code class="docutils literal notranslate"><span class="pre">argv[1]</span></code> set to <code class="xref std std-option docutils literal notranslate"><span class="pre">-install</span></code>, and again at
uninstallation time before the files are removed with <code class="docutils literal notranslate"><span class="pre">argv[1]</span></code> set to
<code class="xref std std-option docutils literal notranslate"><span class="pre">-remove</span></code>.</p>
<p>The installation script runs embedded in the windows installer, every output
(<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>) is redirected into a buffer and will be
displayed in the GUI after the script has finished.</p>
<p>Some functions especially useful in this context are available as additional
built-in functions in the installation script.</p>
<dl class="function">
<dt id="directory_created">
<code class="descname">directory_created</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#directory_created" title="Permalink to this definition">¶</a></dt>
<dt id="file_created">
<code class="descname">file_created</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#file_created" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions should be called when a directory or file is created by the
postinstall script at installation time.  It will register <em>path</em> with the
uninstaller, so that it will be removed when the distribution is uninstalled.
To be safe, directories are only removed if they are empty.</p>
</dd></dl>

<dl class="function">
<dt id="get_special_folder_path">
<code class="descname">get_special_folder_path</code><span class="sig-paren">(</span><em>csidl_string</em><span class="sig-paren">)</span><a class="headerlink" href="#get_special_folder_path" title="Permalink to this definition">¶</a></dt>
<dd><p>This function can be used to retrieve special folder locations on Windows like
the Start Menu or the Desktop.  It returns the full path to the folder.
<em>csidl_string</em> must be one of the following strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;CSIDL_APPDATA&quot;</span>

<span class="s2">&quot;CSIDL_COMMON_STARTMENU&quot;</span>
<span class="s2">&quot;CSIDL_STARTMENU&quot;</span>

<span class="s2">&quot;CSIDL_COMMON_DESKTOPDIRECTORY&quot;</span>
<span class="s2">&quot;CSIDL_DESKTOPDIRECTORY&quot;</span>

<span class="s2">&quot;CSIDL_COMMON_STARTUP&quot;</span>
<span class="s2">&quot;CSIDL_STARTUP&quot;</span>

<span class="s2">&quot;CSIDL_COMMON_PROGRAMS&quot;</span>
<span class="s2">&quot;CSIDL_PROGRAMS&quot;</span>

<span class="s2">&quot;CSIDL_FONTS&quot;</span>
</pre></div>
</div>
<p>If the folder cannot be retrieved, <a class="reference internal" href="../library/exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised.</p>
<p>Which folders are available depends on the exact Windows version, and probably
also the configuration.  For details refer to Microsoft’s documentation of the
<code class="xref c c-func docutils literal notranslate"><span class="pre">SHGetSpecialFolderPath()</span></code> function.</p>
</dd></dl>

<dl class="function">
<dt id="create_shortcut">
<code class="descname">create_shortcut</code><span class="sig-paren">(</span><em>target</em>, <em>description</em>, <em>filename</em><span class="optional">[</span>, <em>arguments</em><span class="optional">[</span>, <em>workdir</em><span class="optional">[</span>, <em>iconpath</em><span class="optional">[</span>, <em>iconindex</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#create_shortcut" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a shortcut. <em>target</em> is the path to the program to be
started by the shortcut. <em>description</em> is the description of the shortcut.
<em>filename</em> is the title of the shortcut that the user will see. <em>arguments</em>
specifies the command line arguments, if any. <em>workdir</em> is the working directory
for the program. <em>iconpath</em> is the file containing the icon for the shortcut,
and <em>iconindex</em> is the index of the icon in the file <em>iconpath</em>.  Again, for
details consult the Microsoft documentation for the <code class="xref py py-class docutils literal notranslate"><span class="pre">IShellLink</span></code>
interface.</p>
</dd></dl>

</div>
</div>
<div class="section" id="vista-user-access-control-uac">
<h2>5.5. Vista User Access Control (UAC)<a class="headerlink" href="#vista-user-access-control-uac" title="Permalink to this headline">¶</a></h2>
<p>Starting with Python 2.6, bdist_wininst supports a <code class="xref std std-option docutils literal notranslate"><span class="pre">--user-access-control</span></code>
option.  The default is ‘none’ (meaning no UAC handling is done), and other
valid values are ‘auto’ (meaning prompt for UAC elevation if Python was
installed for all users) and ‘force’ (meaning always prompt for elevation).</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">5. Creating Built Distributions</a><ul>
<li><a class="reference internal" href="#creating-dumb-built-distributions">5.1. Creating dumb built distributions</a></li>
<li><a class="reference internal" href="#creating-rpm-packages">5.2. Creating RPM packages</a></li>
<li><a class="reference internal" href="#creating-windows-installers">5.3. Creating Windows Installers</a></li>
<li><a class="reference internal" href="#cross-compiling-on-windows">5.4. Cross-compiling on Windows</a><ul>
<li><a class="reference internal" href="#the-postinstallation-script">5.4.1. The Postinstallation script</a></li>
</ul>
</li>
<li><a class="reference internal" href="#vista-user-access-control-uac">5.5. Vista User Access Control (UAC)</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sourcedist.html"
                        title="previous chapter">4. Creating a Source Distribution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="packageindex.html"
                        title="next chapter">6. The Python Package Index (PyPI)</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/builtdist.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="packageindex.html" title="6. The Python Package Index (PyPI)"
             >next</a> |</li>
        <li class="right" >
          <a href="sourcedist.html" title="4. Creating a Source Distribution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Kg���html/distutils/commandref.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9. Command Reference &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10. API Reference" href="apiref.html" />
    <link rel="prev" title="8. Extending Distutils" href="extending.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/commandref.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="apiref.html" title="10. API Reference"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="8. Extending Distutils"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="command-reference">
<span id="reference"></span><h1>9. Command Reference<a class="headerlink" href="#command-reference" title="Permalink to this headline">¶</a></h1>
<div class="section" id="installing-modules-the-install-command-family">
<span id="install-cmd"></span><h2>9.1. Installing modules: the <strong class="command">install</strong> command family<a class="headerlink" href="#installing-modules-the-install-command-family" title="Permalink to this headline">¶</a></h2>
<p>The install command ensures that the build commands have been run and then runs
the subcommands <strong class="command">install_lib</strong>, <strong class="command">install_data</strong> and
<strong class="command">install_scripts</strong>.</p>
<div class="section" id="install-data">
<span id="install-data-cmd"></span><h3>9.1.1. <strong class="command">install_data</strong><a class="headerlink" href="#install-data" title="Permalink to this headline">¶</a></h3>
<p>This command installs all data files provided with the distribution.</p>
</div>
<div class="section" id="install-scripts">
<span id="install-scripts-cmd"></span><h3>9.1.2. <strong class="command">install_scripts</strong><a class="headerlink" href="#install-scripts" title="Permalink to this headline">¶</a></h3>
<p>This command installs all (Python) scripts in the distribution.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9. Command Reference</a><ul>
<li><a class="reference internal" href="#installing-modules-the-install-command-family">9.1. Installing modules: the <strong class="command">install</strong> command family</a><ul>
<li><a class="reference internal" href="#install-data">9.1.1. <strong class="command">install_data</strong></a></li>
<li><a class="reference internal" href="#install-scripts">9.1.2. <strong class="command">install_scripts</strong></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="extending.html"
                        title="previous chapter">8. Extending Distutils</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="apiref.html"
                        title="next chapter">10. API Reference</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/commandref.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="apiref.html" title="10. API Reference"
             >next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="8. Extending Distutils"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\i�>H>Hhtml/distutils/configfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>3. Writing the Setup Configuration File &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. Creating a Source Distribution" href="sourcedist.html" />
    <link rel="prev" title="2. Writing the Setup Script" href="setupscript.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/configfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sourcedist.html" title="4. Creating a Source Distribution"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="setupscript.html" title="2. Writing the Setup Script"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="writing-the-setup-configuration-file">
<span id="setup-config"></span><h1>3. Writing the Setup Configuration File<a class="headerlink" href="#writing-the-setup-configuration-file" title="Permalink to this headline">¶</a></h1>
<p>Often, it’s not possible to write down everything needed to build a distribution
<em>a priori</em>: you may need to get some information from the user, or from the
user’s system, in order to proceed.  As long as that information is fairly
simple—a list of directories to search for C header files or libraries, for
example—then providing a configuration file, <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code>, for users to
edit is a cheap and easy way to solicit it.  Configuration files also let you
provide default values for any command option, which the installer can then
override either on the command-line or by editing the config file.</p>
<p>The setup configuration file is a useful middle-ground between the setup script
—which, ideally, would be opaque to installers <a class="footnote-reference" href="#id2" id="id1">[1]</a>—and the command-line to
the setup script, which is outside of your control and entirely up to the
installer.  In fact, <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code> (and any other Distutils configuration
files present on the target system) are processed after the contents of the
setup script, but before the command-line.  This has  several useful
consequences:</p>
<ul class="simple">
<li>installers can override some of what you put in <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> by editing
<code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code></li>
<li>you can provide non-standard defaults for options that are not easily set in
<code class="file docutils literal notranslate"><span class="pre">setup.py</span></code></li>
<li>installers can override anything in <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code> using the command-line
options to <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code></li>
</ul>
<p>The basic syntax of the configuration file is simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">command</span><span class="p">]</span>
<span class="n">option</span><span class="o">=</span><span class="n">value</span>
<span class="o">...</span>
</pre></div>
</div>
<p>where <em>command</em> is one of the Distutils commands (e.g. <strong class="command">build_py</strong>,
<strong class="command">install</strong>), and <em>option</em> is one of the options that command supports.
Any number of options can be supplied for each command, and any number of
command sections can be included in the file.  Blank lines are ignored, as are
comments, which run from a <code class="docutils literal notranslate"><span class="pre">'#'</span></code> character until the end of the line.  Long
option values can be split across multiple lines simply by indenting the
continuation lines.</p>
<p>You can find out the list of options supported by a particular command with the
universal <code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code> option, e.g.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;</span> <span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="o">--</span><span class="n">help</span> <span class="n">build_ext</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
<span class="n">Options</span> <span class="k">for</span> <span class="s1">&#39;build_ext&#39;</span> <span class="n">command</span><span class="p">:</span>
  <span class="o">--</span><span class="n">build</span><span class="o">-</span><span class="n">lib</span> <span class="p">(</span><span class="o">-</span><span class="n">b</span><span class="p">)</span>     <span class="n">directory</span> <span class="k">for</span> <span class="n">compiled</span> <span class="n">extension</span> <span class="n">modules</span>
  <span class="o">--</span><span class="n">build</span><span class="o">-</span><span class="n">temp</span> <span class="p">(</span><span class="o">-</span><span class="n">t</span><span class="p">)</span>    <span class="n">directory</span> <span class="k">for</span> <span class="n">temporary</span> <span class="n">files</span> <span class="p">(</span><span class="n">build</span> <span class="n">by</span><span class="o">-</span><span class="n">products</span><span class="p">)</span>
  <span class="o">--</span><span class="n">inplace</span> <span class="p">(</span><span class="o">-</span><span class="n">i</span><span class="p">)</span>       <span class="n">ignore</span> <span class="n">build</span><span class="o">-</span><span class="n">lib</span> <span class="ow">and</span> <span class="n">put</span> <span class="n">compiled</span> <span class="n">extensions</span> <span class="n">into</span> <span class="n">the</span>
                       <span class="n">source</span> <span class="n">directory</span> <span class="n">alongside</span> <span class="n">your</span> <span class="n">pure</span> <span class="n">Python</span> <span class="n">modules</span>
  <span class="o">--</span><span class="n">include</span><span class="o">-</span><span class="n">dirs</span> <span class="p">(</span><span class="o">-</span><span class="n">I</span><span class="p">)</span>  <span class="nb">list</span> <span class="n">of</span> <span class="n">directories</span> <span class="n">to</span> <span class="n">search</span> <span class="k">for</span> <span class="n">header</span> <span class="n">files</span>
  <span class="o">--</span><span class="n">define</span> <span class="p">(</span><span class="o">-</span><span class="n">D</span><span class="p">)</span>        <span class="n">C</span> <span class="n">preprocessor</span> <span class="n">macros</span> <span class="n">to</span> <span class="n">define</span>
  <span class="o">--</span><span class="n">undef</span> <span class="p">(</span><span class="o">-</span><span class="n">U</span><span class="p">)</span>         <span class="n">C</span> <span class="n">preprocessor</span> <span class="n">macros</span> <span class="n">to</span> <span class="n">undefine</span>
  <span class="o">--</span><span class="n">swig</span><span class="o">-</span><span class="n">opts</span>          <span class="nb">list</span> <span class="n">of</span> <span class="n">SWIG</span> <span class="n">command</span> <span class="n">line</span> <span class="n">options</span>
<span class="p">[</span><span class="o">...</span><span class="p">]</span>
</pre></div>
</div>
<p>Note that an option spelled <code class="xref std std-option docutils literal notranslate"><span class="pre">--foo-bar</span></code> on the command-line  is spelled
<code class="docutils literal notranslate"><span class="pre">foo_bar</span></code> in configuration files.</p>
<p id="distutils-build-ext-inplace">For example, say you want your extensions to be built “in-place”—that is, you
have an extension <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.ext</span></code>, and you want the compiled extension file
(<code class="file docutils literal notranslate"><span class="pre">ext.so</span></code> on Unix, say) to be put in the same source directory as your
pure Python modules <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.mod1</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.mod2</span></code>.  You can always use the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--inplace</span></code> option on the command-line to ensure this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">build_ext</span> <span class="o">--</span><span class="n">inplace</span>
</pre></div>
</div>
<p>But this requires that you always specify the <strong class="command">build_ext</strong> command
explicitly, and remember to provide <code class="xref std std-option docutils literal notranslate"><span class="pre">--inplace</span></code>. An easier way is to
“set and forget” this option, by encoding it in <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code>, the
configuration file for this distribution:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">build_ext</span><span class="p">]</span>
<span class="n">inplace</span><span class="o">=</span><span class="mi">1</span>
</pre></div>
</div>
<p>This will affect all builds of this module distribution, whether or not you
explicitly specify <strong class="command">build_ext</strong>.  If you include <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code> in
your source distribution, it will also affect end-user builds—which is
probably a bad idea for this option, since always building extensions in-place
would break installation of the module distribution.  In certain peculiar cases,
though, modules are built right in their installation directory, so this is
conceivably a useful ability.  (Distributing extensions that expect to be built
in their installation directory is almost always a bad idea, though.)</p>
<p>Another example: certain commands take a lot of options that don’t change from
run to run; for example, <strong class="command">bdist_rpm</strong> needs to know everything required
to generate a “spec” file for creating an RPM distribution.  Some of this
information comes from the setup script, and some is automatically generated by
the Distutils (such as the list of files installed).  But some of it has to be
supplied as options to <strong class="command">bdist_rpm</strong>, which would be very tedious to do
on the command-line for every run.  Hence, here is a snippet from the Distutils’
own <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">bdist_rpm</span><span class="p">]</span>
<span class="n">release</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">packager</span> <span class="o">=</span> <span class="n">Greg</span> <span class="n">Ward</span> <span class="o">&lt;</span><span class="n">gward</span><span class="nd">@python</span><span class="o">.</span><span class="n">net</span><span class="o">&gt;</span>
<span class="n">doc_files</span> <span class="o">=</span> <span class="n">CHANGES</span><span class="o">.</span><span class="n">txt</span>
            <span class="n">README</span><span class="o">.</span><span class="n">txt</span>
            <span class="n">USAGE</span><span class="o">.</span><span class="n">txt</span>
            <span class="n">doc</span><span class="o">/</span>
            <span class="n">examples</span><span class="o">/</span>
</pre></div>
</div>
<p>Note that the <code class="docutils literal notranslate"><span class="pre">doc_files</span></code> option is simply a whitespace-separated string
split across multiple lines for readability.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../install/index.html#inst-config-syntax"><span class="std std-ref">Syntax of config files</span></a> in “Installing Python Modules”</dt>
<dd>More information on the configuration files is available in the manual for
system administrators.</dd>
</dl>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This ideal probably won’t be achieved until auto-configuration is fully
supported by the Distutils.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="setupscript.html"
                        title="previous chapter">2. Writing the Setup Script</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sourcedist.html"
                        title="next chapter">4. Creating a Source Distribution</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/configfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sourcedist.html" title="4. Creating a Source Distribution"
             >next</a> |</li>
        <li class="right" >
          <a href="setupscript.html" title="2. Writing the Setup Script"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�2�JfJfhtml/distutils/examples.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7. Examples &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8. Extending Distutils" href="extending.html" />
    <link rel="prev" title="6. The Python Package Index (PyPI)" href="packageindex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/examples.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="8. Extending Distutils"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="packageindex.html" title="6. The Python Package Index (PyPI)"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="examples">
<span id="id1"></span><h1>7. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h1>
<p>This chapter provides a number of basic examples to help get started with
distutils.  Additional information about using distutils can be found in the
Distutils Cookbook.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://wiki.python.org/moin/Distutils/Cookbook">Distutils Cookbook</a></dt>
<dd>Collection of recipes showing how to achieve more control over distutils.</dd>
</dl>
</div>
<div class="section" id="pure-python-distribution-by-module">
<span id="pure-mod"></span><h2>7.1. Pure Python distribution (by module)<a class="headerlink" href="#pure-python-distribution-by-module" title="Permalink to this headline">¶</a></h2>
<p>If you’re just distributing a couple of modules, especially if they don’t live
in a particular package, you can specify them individually using the
<code class="docutils literal notranslate"><span class="pre">py_modules</span></code> option in the setup script.</p>
<p>In the simplest case, you’ll have two files to worry about: a setup script and
the single module you’re distributing, <code class="file docutils literal notranslate"><span class="pre">foo.py</span></code> in this example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>(In all diagrams in this section, <em>&lt;root&gt;</em> will refer to the distribution root
directory.)  A minimal setup script to describe this situation would be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">py_modules</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>Note that the name of the distribution is specified independently with the
<code class="docutils literal notranslate"><span class="pre">name</span></code> option, and there’s no rule that says it has to be the same as
the name of the sole module in the distribution (although that’s probably a good
convention to follow).  However, the distribution name is used to generate
filenames, so you should stick to letters, digits, underscores, and hyphens.</p>
<p>Since <code class="docutils literal notranslate"><span class="pre">py_modules</span></code> is a list, you can of course specify multiple
modules, eg. if you’re distributing modules <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">bar</span></code>, your
setup might look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
        <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>and the setup script might be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">py_modules</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>You can put module source files into another directory, but if you have enough
modules to do that, it’s probably easier to specify modules by package rather
than listing them individually.</p>
</div>
<div class="section" id="pure-python-distribution-by-package">
<span id="pure-pkg"></span><h2>7.2. Pure Python distribution (by package)<a class="headerlink" href="#pure-python-distribution-by-package" title="Permalink to this headline">¶</a></h2>
<p>If you have more than a couple of modules to distribute, especially if they are
in multiple packages, it’s probably easier to specify whole packages rather than
individual modules.  This works even if your modules are not in a package; you
can just tell the Distutils to process modules from the root package, and that
works the same as any other package (except that you don’t have to have an
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> file).</p>
<p>The setup script from the last example could also be written as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>(The empty string stands for the root package.)</p>
<p>If those two files are moved into a subdirectory, but remain in the root
package, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">src</span><span class="o">/</span>      <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
                  <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>then you would still specify the root package, but you have to tell the
Distutils where source files in the root package live:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">package_dir</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;&#39;</span><span class="p">:</span> <span class="s1">&#39;src&#39;</span><span class="p">},</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>More typically, though, you will want to distribute multiple modules in the same
package (or in sub-packages).  For example, if the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code>  and <code class="xref py py-mod docutils literal notranslate"><span class="pre">bar</span></code>
modules belong in package <code class="xref py py-mod docutils literal notranslate"><span class="pre">foobar</span></code>, one way to layout your source tree is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foobar</span><span class="o">/</span>
                 <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This is in fact the default layout expected by the Distutils, and the one that
requires the least work to describe in your setup script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foobar&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>If you want to put modules in directories not named for their package, then you
need to use the <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> option again.  For example, if the
<code class="file docutils literal notranslate"><span class="pre">src</span></code> directory holds modules in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foobar</span></code> package:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">src</span><span class="o">/</span>
                 <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>an appropriate setup script would be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">package_dir</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;foobar&#39;</span><span class="p">:</span> <span class="s1">&#39;src&#39;</span><span class="p">},</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foobar&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>Or, you might put modules from your main package right in the distribution
root:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
        <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>in which case your setup script would be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">package_dir</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;foobar&#39;</span><span class="p">:</span> <span class="s1">&#39;&#39;</span><span class="p">},</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foobar&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>(The empty string also stands for the current directory.)</p>
<p>If you have sub-packages, they must be explicitly listed in <code class="docutils literal notranslate"><span class="pre">packages</span></code>,
but any entries in <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> automatically extend to sub-packages.
(In other words, the Distutils does <em>not</em> scan your source tree, trying to
figure out which directories correspond to Python packages by looking for
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> files.)  Thus, if the default layout grows a sub-package:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foobar</span><span class="o">/</span>
                 <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">foo</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">bar</span><span class="o">.</span><span class="n">py</span>
                 <span class="n">subfoo</span><span class="o">/</span>
                           <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
                           <span class="n">blah</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>then the corresponding setup script would be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span> <span class="s1">&#39;foobar.subfoo&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="single-extension-module">
<span id="single-ext"></span><h2>7.3. Single extension module<a class="headerlink" href="#single-extension-module" title="Permalink to this headline">¶</a></h2>
<p>Extension modules are specified using the <code class="docutils literal notranslate"><span class="pre">ext_modules</span></code> option.
<code class="docutils literal notranslate"><span class="pre">package_dir</span></code> has no effect on where extension source files are found;
it only affects the source for pure Python modules.  The simplest  case, a
single extension module in a single C source file, is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">root</span><span class="o">&gt;/</span>
        <span class="n">setup</span><span class="o">.</span><span class="n">py</span>
        <span class="n">foo</span><span class="o">.</span><span class="n">c</span>
</pre></div>
</div>
<p>If the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> extension belongs in the root package, the setup script for
this could be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="kn">from</span> <span class="nn">distutils.extension</span> <span class="k">import</span> <span class="n">Extension</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">])],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>If the extension actually belongs in a package, say <code class="xref py py-mod docutils literal notranslate"><span class="pre">foopkg</span></code>, then</p>
<p>With exactly the same source tree layout, this extension can be put in the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">foopkg</span></code> package simply by changing the name of the extension:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="kn">from</span> <span class="nn">distutils.extension</span> <span class="k">import</span> <span class="n">Extension</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foobar&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foopkg.foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">])],</span>
      <span class="p">)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. Examples</a><ul>
<li><a class="reference internal" href="#pure-python-distribution-by-module">7.1. Pure Python distribution (by module)</a></li>
<li><a class="reference internal" href="#pure-python-distribution-by-package">7.2. Pure Python distribution (by package)</a></li>
<li><a class="reference internal" href="#single-extension-module">7.3. Single extension module</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="packageindex.html"
                        title="previous chapter">6. The Python Package Index (PyPI)</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="extending.html"
                        title="next chapter">8. Extending Distutils</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/examples.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="8. Extending Distutils"
             >next</a> |</li>
        <li class="right" >
          <a href="packageindex.html" title="6. The Python Package Index (PyPI)"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\9�x�7�7html/distutils/extending.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8. Extending Distutils &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9. Command Reference" href="commandref.html" />
    <link rel="prev" title="7. Examples" href="examples.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/extending.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="commandref.html" title="9. Command Reference"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="examples.html" title="7. Examples"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="extending-distutils">
<span id="id1"></span><h1>8. Extending Distutils<a class="headerlink" href="#extending-distutils" title="Permalink to this headline">¶</a></h1>
<p>Distutils can be extended in various ways.  Most extensions take the form of new
commands or replacements for existing commands.  New commands may be written to
support new types of platform-specific packaging, for example, while
replacements for existing commands may be made to modify details of how the
command operates on a package.</p>
<p>Most extensions of the distutils are made within <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> scripts that
want to modify existing commands; many simply add a few file extensions that
should be copied into packages in addition to <code class="file docutils literal notranslate"><span class="pre">.py</span></code> files as a
convenience.</p>
<p>Most distutils command implementations are subclasses of the
<a class="reference internal" href="apiref.html#distutils.cmd.Command" title="distutils.cmd.Command"><code class="xref py py-class docutils literal notranslate"><span class="pre">distutils.cmd.Command</span></code></a> class.  New commands may directly inherit from
<code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code>, while replacements often derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code>
indirectly, directly subclassing the command they are replacing.  Commands are
required to derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Command</span></code>.</p>
<div class="section" id="integrating-new-commands">
<h2>8.1. Integrating new commands<a class="headerlink" href="#integrating-new-commands" title="Permalink to this headline">¶</a></h2>
<p>There are different ways to integrate new command implementations into
distutils.  The most difficult is to lobby for the inclusion of the new features
in distutils itself, and wait for (and require) a version of Python that
provides that support.  This is really hard for many reasons.</p>
<p>The most common, and possibly the most reasonable for most needs, is to include
the new implementations with your <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script, and cause the
<a class="reference internal" href="apiref.html#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.core.setup()</span></code></a> function use them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.command.build_py</span> <span class="k">import</span> <span class="n">build_py</span> <span class="k">as</span> <span class="n">_build_py</span>
<span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>

<span class="k">class</span> <span class="nc">build_py</span><span class="p">(</span><span class="n">_build_py</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Specialized Python source builder.&quot;&quot;&quot;</span>

    <span class="c1"># implement whatever needs to be different...</span>

<span class="n">setup</span><span class="p">(</span><span class="n">cmdclass</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;build_py&#39;</span><span class="p">:</span> <span class="n">build_py</span><span class="p">},</span>
      <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>This approach is most valuable if the new implementations must be used to use a
particular package, as everyone interested in the package will need to have the
new command implementation.</p>
<p>Beginning with Python 2.4, a third option is available, intended to allow new
commands to be added which can support existing <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> scripts without
requiring modifications to the Python installation.  This is expected to allow
third-party extensions to provide support for additional packaging systems, but
the commands can be used for anything distutils commands can be used for.  A new
configuration option, <code class="docutils literal notranslate"><span class="pre">command_packages</span></code> (command-line option
<code class="xref std std-option docutils literal notranslate"><span class="pre">--command-packages</span></code>), can be used to specify additional packages to be
searched for modules implementing commands.  Like all distutils options, this
can be specified on the command line or in a configuration file.  This option
can only be set in the <code class="docutils literal notranslate"><span class="pre">[global]</span></code> section of a configuration file, or before
any commands on the command line.  If set in a configuration file, it can be
overridden from the command line; setting it to an empty string on the command
line causes the default to be used.  This should never be set in a configuration
file provided with a package.</p>
<p>This new option can be used to add any number of packages to the list of
packages searched for command implementations; multiple package names should be
separated by commas.  When not specified, the search is only performed in the
<a class="reference internal" href="apiref.html#module-distutils.command" title="distutils.command: This subpackage contains one module for each standard Distutils command."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command</span></code></a> package.  When <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> is run with the option
<code class="docutils literal notranslate"><span class="pre">--command-packages</span> <span class="pre">distcmds,buildcmds</span></code>, however, the packages
<a class="reference internal" href="apiref.html#module-distutils.command" title="distutils.command: This subpackage contains one module for each standard Distutils command."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.command</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">distcmds</span></code>, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">buildcmds</span></code> will be searched
in that order.  New commands are expected to be implemented in modules of the
same name as the command by classes sharing the same name.  Given the example
command line option above, the command <strong class="command">bdist_openpkg</strong> could be
implemented by the class <code class="xref py py-class docutils literal notranslate"><span class="pre">distcmds.bdist_openpkg.bdist_openpkg</span></code> or
<code class="xref py py-class docutils literal notranslate"><span class="pre">buildcmds.bdist_openpkg.bdist_openpkg</span></code>.</p>
</div>
<div class="section" id="adding-new-distribution-types">
<h2>8.2. Adding new distribution types<a class="headerlink" href="#adding-new-distribution-types" title="Permalink to this headline">¶</a></h2>
<p>Commands that create distributions (files in the <code class="file docutils literal notranslate"><span class="pre">dist/</span></code> directory) need
to add <code class="docutils literal notranslate"><span class="pre">(command,</span> <span class="pre">filename)</span></code> pairs to <code class="docutils literal notranslate"><span class="pre">self.distribution.dist_files</span></code> so that
<strong class="command">upload</strong> can upload it to PyPI.  The <em>filename</em> in the pair contains no
path information, only the name of the file itself.  In dry-run mode, pairs
should still be added to represent what would have been created.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8. Extending Distutils</a><ul>
<li><a class="reference internal" href="#integrating-new-commands">8.1. Integrating new commands</a></li>
<li><a class="reference internal" href="#adding-new-distribution-types">8.2. Adding new distribution types</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="examples.html"
                        title="previous chapter">7. Examples</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="commandref.html"
                        title="next chapter">9. Command Reference</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/extending.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="commandref.html" title="9. Command Reference"
             >next</a> |</li>
        <li class="right" >
          <a href="examples.html" title="7. Examples"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\9�0([a[ahtml/distutils/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Distributing Python Modules (Legacy version) &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. An Introduction to Distutils" href="introduction.html" />
    <link rel="prev" title="History and License" href="../license.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. An Introduction to Distutils"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../license.html" title="History and License"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="distributing-python-modules-legacy-version">
<span id="distutils-index"></span><h1>Distributing Python Modules (Legacy version)<a class="headerlink" href="#distributing-python-modules-legacy-version" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Authors:</th><td class="field-body">Greg Ward, Anthony Baxter</td>
</tr>
<tr class="field-even field"><th class="field-name">Email:</th><td class="field-body"><a class="reference external" href="mailto:distutils-sig&#37;&#52;&#48;python&#46;org">distutils-sig<span>&#64;</span>python<span>&#46;</span>org</a></td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../distributing/index.html#distributing-index"><span class="std std-ref">Distributing Python Modules</span></a></dt>
<dd>The up to date module distribution documentations</dd>
</dl>
</div>
<p>This document describes the Python Distribution Utilities (“Distutils”) from
the module developer’s point of view, describing how to use the Distutils to
make Python modules and extensions easily available to a wider audience with
very little overhead for build/release/install mechanics.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This guide only covers the basic tools for building and distributing
extensions that are provided as part of this version of Python. Third party
tools offer easier to use and more secure alternatives. Refer to the <a class="reference external" href="https://packaging.python.org/en/latest/current/">quick
recommendations section</a>
in the Python Packaging User Guide for more information.</p>
</div>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="introduction.html">1. An Introduction to Distutils</a><ul>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#concepts-terminology">1.1. Concepts &amp; Terminology</a></li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#a-simple-example">1.2. A Simple Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#general-python-terminology">1.3. General Python terminology</a></li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#distutils-specific-terminology">1.4. Distutils-specific terminology</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="setupscript.html">2. Writing the Setup Script</a><ul>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#listing-whole-packages">2.1. Listing whole packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#listing-individual-modules">2.2. Listing individual modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#describing-extension-modules">2.3. Describing extension modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#relationships-between-distributions-and-packages">2.4. Relationships between Distributions and Packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#installing-scripts">2.5. Installing Scripts</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#installing-package-data">2.6. Installing Package Data</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#installing-additional-files">2.7. Installing Additional Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#additional-meta-data">2.8. Additional meta-data</a></li>
<li class="toctree-l2"><a class="reference internal" href="setupscript.html#debugging-the-setup-script">2.9. Debugging the setup script</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="configfile.html">3. Writing the Setup Configuration File</a></li>
<li class="toctree-l1"><a class="reference internal" href="sourcedist.html">4. Creating a Source Distribution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sourcedist.html#specifying-the-files-to-distribute">4.1. Specifying the files to distribute</a></li>
<li class="toctree-l2"><a class="reference internal" href="sourcedist.html#manifest-related-options">4.2. Manifest-related options</a></li>
<li class="toctree-l2"><a class="reference internal" href="sourcedist.html#the-manifest-in-template">4.3. The MANIFEST.in template</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="builtdist.html">5. Creating Built Distributions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="builtdist.html#creating-dumb-built-distributions">5.1. Creating dumb built distributions</a></li>
<li class="toctree-l2"><a class="reference internal" href="builtdist.html#creating-rpm-packages">5.2. Creating RPM packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="builtdist.html#creating-windows-installers">5.3. Creating Windows Installers</a></li>
<li class="toctree-l2"><a class="reference internal" href="builtdist.html#cross-compiling-on-windows">5.4. Cross-compiling on Windows</a></li>
<li class="toctree-l2"><a class="reference internal" href="builtdist.html#vista-user-access-control-uac">5.5. Vista User Access Control (UAC)</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="packageindex.html">6. The Python Package Index (PyPI)</a><ul>
<li class="toctree-l2"><a class="reference internal" href="packageindex.html#pypi-overview">6.1. PyPI overview</a></li>
<li class="toctree-l2"><a class="reference internal" href="packageindex.html#distutils-commands">6.2. Distutils commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="packageindex.html#pypi-package-display">6.3. PyPI package display</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="examples.html">7. Examples</a><ul>
<li class="toctree-l2"><a class="reference internal" href="examples.html#pure-python-distribution-by-module">7.1. Pure Python distribution (by module)</a></li>
<li class="toctree-l2"><a class="reference internal" href="examples.html#pure-python-distribution-by-package">7.2. Pure Python distribution (by package)</a></li>
<li class="toctree-l2"><a class="reference internal" href="examples.html#single-extension-module">7.3. Single extension module</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="extending.html">8. Extending Distutils</a><ul>
<li class="toctree-l2"><a class="reference internal" href="extending.html#integrating-new-commands">8.1. Integrating new commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#adding-new-distribution-types">8.2. Adding new distribution types</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="commandref.html">9. Command Reference</a><ul>
<li class="toctree-l2"><a class="reference internal" href="commandref.html#installing-modules-the-install-command-family">9.1. Installing modules: the <strong class="command">install</strong> command family</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="apiref.html">10. API Reference</a><ul>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.core">10.1. <code class="docutils literal notranslate"><span class="pre">distutils.core</span></code> — Core Distutils functionality</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.ccompiler">10.2. <code class="docutils literal notranslate"><span class="pre">distutils.ccompiler</span></code> — CCompiler base class</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.unixccompiler">10.3. <code class="docutils literal notranslate"><span class="pre">distutils.unixccompiler</span></code> — Unix C Compiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.msvccompiler">10.4. <code class="docutils literal notranslate"><span class="pre">distutils.msvccompiler</span></code> — Microsoft Compiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.bcppcompiler">10.5. <code class="docutils literal notranslate"><span class="pre">distutils.bcppcompiler</span></code> — Borland Compiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.cygwinccompiler">10.6. <code class="docutils literal notranslate"><span class="pre">distutils.cygwincompiler</span></code> — Cygwin Compiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.emxccompiler">10.7. <code class="docutils literal notranslate"><span class="pre">distutils.emxccompiler</span></code> — OS/2 EMX Compiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.archive_util">10.8. <code class="docutils literal notranslate"><span class="pre">distutils.archive_util</span></code> —  Archiving utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.dep_util">10.9. <code class="docutils literal notranslate"><span class="pre">distutils.dep_util</span></code> — Dependency checking</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.dir_util">10.10. <code class="docutils literal notranslate"><span class="pre">distutils.dir_util</span></code> — Directory tree operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.file_util">10.11. <code class="docutils literal notranslate"><span class="pre">distutils.file_util</span></code> — Single file operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.util">10.12. <code class="docutils literal notranslate"><span class="pre">distutils.util</span></code> — Miscellaneous other utility functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.dist">10.13. <code class="docutils literal notranslate"><span class="pre">distutils.dist</span></code> — The Distribution class</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.extension">10.14. <code class="docutils literal notranslate"><span class="pre">distutils.extension</span></code> — The Extension class</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.debug">10.15. <code class="docutils literal notranslate"><span class="pre">distutils.debug</span></code> — Distutils debug mode</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.errors">10.16. <code class="docutils literal notranslate"><span class="pre">distutils.errors</span></code> — Distutils exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.fancy_getopt">10.17. <code class="docutils literal notranslate"><span class="pre">distutils.fancy_getopt</span></code> — Wrapper around the standard getopt module</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.filelist">10.18. <code class="docutils literal notranslate"><span class="pre">distutils.filelist</span></code> — The FileList class</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.log">10.19. <code class="docutils literal notranslate"><span class="pre">distutils.log</span></code> — Simple PEP 282-style logging</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.spawn">10.20. <code class="docutils literal notranslate"><span class="pre">distutils.spawn</span></code> — Spawn a sub-process</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.sysconfig">10.21. <code class="docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code> — System configuration information</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.text_file">10.22. <code class="docutils literal notranslate"><span class="pre">distutils.text_file</span></code> — The TextFile class</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.version">10.23. <code class="docutils literal notranslate"><span class="pre">distutils.version</span></code> — Version number classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.cmd">10.24. <code class="docutils literal notranslate"><span class="pre">distutils.cmd</span></code> — Abstract base class for Distutils commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#creating-a-new-distutils-command">10.25. Creating a new Distutils command</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command">10.26. <code class="docutils literal notranslate"><span class="pre">distutils.command</span></code> — Individual Distutils commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist">10.27. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist</span></code> — Build a binary installer</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist_packager">10.28. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_packager</span></code> — Abstract base class for packagers</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist_dumb">10.29. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_dumb</span></code> — Build a “dumb” installer</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist_msi">10.30. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_msi</span></code> — Build a Microsoft Installer binary package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist_rpm">10.31. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_rpm</span></code> — Build a binary distribution as a Redhat RPM and SRPM</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.bdist_wininst">10.32. <code class="docutils literal notranslate"><span class="pre">distutils.command.bdist_wininst</span></code> — Build a Windows installer</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.sdist">10.33. <code class="docutils literal notranslate"><span class="pre">distutils.command.sdist</span></code> — Build a source distribution</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.build">10.34. <code class="docutils literal notranslate"><span class="pre">distutils.command.build</span></code> — Build all files of a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.build_clib">10.35. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_clib</span></code> — Build any C libraries in a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.build_ext">10.36. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_ext</span></code> — Build any extensions in a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.build_py">10.37. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_py</span></code> — Build the .py/.pyc files of a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.build_scripts">10.38. <code class="docutils literal notranslate"><span class="pre">distutils.command.build_scripts</span></code> — Build the scripts of a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.clean">10.39. <code class="docutils literal notranslate"><span class="pre">distutils.command.clean</span></code> — Clean a package build area</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.config">10.40. <code class="docutils literal notranslate"><span class="pre">distutils.command.config</span></code> — Perform package configuration</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.install">10.41. <code class="docutils literal notranslate"><span class="pre">distutils.command.install</span></code> — Install a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.install_data">10.42. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_data</span></code> — Install data files from a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.install_headers">10.43. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_headers</span></code> — Install C/C++ header files from a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.install_lib">10.44. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_lib</span></code> — Install library files from a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.install_scripts">10.45. <code class="docutils literal notranslate"><span class="pre">distutils.command.install_scripts</span></code> — Install script files from a package</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.register">10.46. <code class="docutils literal notranslate"><span class="pre">distutils.command.register</span></code> — Register a module with the Python Package Index</a></li>
<li class="toctree-l2"><a class="reference internal" href="apiref.html#module-distutils.command.check">10.47. <code class="docutils literal notranslate"><span class="pre">distutils.command.check</span></code> — Check the meta-data of a package</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../license.html"
                        title="previous chapter">History and License</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="next chapter">1. An Introduction to Distutils</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. An Introduction to Distutils"
             >next</a> |</li>
        <li class="right" >
          <a href="../license.html" title="History and License"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\49�P�P html/distutils/introduction.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. An Introduction to Distutils &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Writing the Setup Script" href="setupscript.html" />
    <link rel="prev" title="Distributing Python Modules (Legacy version)" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/introduction.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="setupscript.html" title="2. Writing the Setup Script"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Distributing Python Modules (Legacy version)"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="an-introduction-to-distutils">
<span id="distutils-intro"></span><h1>1. An Introduction to Distutils<a class="headerlink" href="#an-introduction-to-distutils" title="Permalink to this headline">¶</a></h1>
<p>This document covers using the Distutils to distribute your Python modules,
concentrating on the role of developer/distributor: if you’re looking for
information on installing Python modules, you should refer to the
<a class="reference internal" href="../install/index.html#install-index"><span class="std std-ref">Installing Python Modules (Legacy version)</span></a> chapter.</p>
<div class="section" id="concepts-terminology">
<span id="distutils-concepts"></span><h2>1.1. Concepts &amp; Terminology<a class="headerlink" href="#concepts-terminology" title="Permalink to this headline">¶</a></h2>
<p>Using the Distutils is quite simple, both for module developers and for
users/administrators installing third-party modules.  As a developer, your
responsibilities (apart from writing solid, well-documented and well-tested
code, of course!) are:</p>
<ul class="simple">
<li>write a setup script (<code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> by convention)</li>
<li>(optional) write a setup configuration file</li>
<li>create a source distribution</li>
<li>(optional) create one or more built (binary) distributions</li>
</ul>
<p>Each of these tasks is covered in this document.</p>
<p>Not all module developers have access to a multitude of platforms, so it’s not
always feasible to expect them to create a multitude of built distributions.  It
is hoped that a class of intermediaries, called <em>packagers</em>, will arise to
address this need.  Packagers will take source distributions released by module
developers, build them on one or more platforms, and release the resulting built
distributions.  Thus, users on the most popular platforms will be able to
install most popular Python module distributions in the most natural way for
their platform, without having to run a single setup script or compile a line of
code.</p>
</div>
<div class="section" id="a-simple-example">
<span id="distutils-simple-example"></span><h2>1.2. A Simple Example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h2>
<p>The setup script is usually quite simple, although since it’s written in Python,
there are no arbitrary limits to what you can do with it, though you should be
careful about putting arbitrarily expensive operations in your setup script.
Unlike, say, Autoconf-style configure scripts, the setup script may be run
multiple times in the course of building and installing your module
distribution.</p>
<p>If all you want to do is distribute a module called <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code>, contained in a
file <code class="file docutils literal notranslate"><span class="pre">foo.py</span></code>, then your setup script can be as simple as this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">py_modules</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>Some observations:</p>
<ul class="simple">
<li>most information that you supply to the Distutils is supplied as keyword
arguments to the <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function</li>
<li>those keyword arguments fall into two categories: package metadata (name,
version number) and information about what’s in the package (a list of pure
Python modules, in this case)</li>
<li>modules are specified by module name, not filename (the same will hold true
for packages and extensions)</li>
<li>it’s recommended that you supply a little more metadata, in particular your
name, email address and a URL for the project (see section <a class="reference internal" href="setupscript.html#setup-script"><span class="std std-ref">Writing the Setup Script</span></a>
for an example)</li>
</ul>
<p>To create a source distribution for this module, you would create a setup
script, <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, containing the above code, and run this command from a
terminal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span>
</pre></div>
</div>
<p>For Windows, open a command prompt windows (<span class="menuselection">Start ‣
Accessories</span>) and change the command to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span>
</pre></div>
</div>
<p><strong class="command">sdist</strong> will create an archive file (e.g., tarball on Unix, ZIP file on Windows)
containing your setup script <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, and your module <code class="file docutils literal notranslate"><span class="pre">foo.py</span></code>.
The archive file will be named <code class="file docutils literal notranslate"><span class="pre">foo-1.0.tar.gz</span></code> (or <code class="file docutils literal notranslate"><span class="pre">.zip</span></code>), and
will unpack into a directory <code class="file docutils literal notranslate"><span class="pre">foo-1.0</span></code>.</p>
<p>If an end-user wishes to install your <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> module, all they have to do is
download <code class="file docutils literal notranslate"><span class="pre">foo-1.0.tar.gz</span></code> (or <code class="file docutils literal notranslate"><span class="pre">.zip</span></code>), unpack it, and—from the
<code class="file docutils literal notranslate"><span class="pre">foo-1.0</span></code> directory—run</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">install</span>
</pre></div>
</div>
<p>which will ultimately copy <code class="file docutils literal notranslate"><span class="pre">foo.py</span></code> to the appropriate directory for
third-party modules in their Python installation.</p>
<p>This simple example demonstrates some fundamental concepts of the Distutils.
First, both developers and installers have the same basic user interface, i.e.
the setup script.  The difference is which Distutils <em>commands</em> they use: the
<strong class="command">sdist</strong> command is almost exclusively for module developers, while
<strong class="command">install</strong> is more often for installers (although most developers will
want to install their own code occasionally).</p>
<p>If you want to make things really easy for your users, you can create one or
more built distributions for them.  For instance, if you are running on a
Windows machine, and want to make things easy for other Windows users, you can
create an executable installer (the most appropriate type of built distribution
for this platform) with the <strong class="command">bdist_wininst</strong> command.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist_wininst</span>
</pre></div>
</div>
<p>will create an executable installer, <code class="file docutils literal notranslate"><span class="pre">foo-1.0.win32.exe</span></code>, in the current
directory.</p>
<p>Other useful built distribution formats are RPM, implemented by the
<strong class="command">bdist_rpm</strong> command, Solaris <strong class="program">pkgtool</strong>
(<strong class="command">bdist_pkgtool</strong>), and HP-UX <strong class="program">swinstall</strong>
(<strong class="command">bdist_sdux</strong>).  For example, the following command will create an RPM
file called <code class="file docutils literal notranslate"><span class="pre">foo-1.0.noarch.rpm</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist_rpm</span>
</pre></div>
</div>
<p>(The <strong class="command">bdist_rpm</strong> command uses the <strong class="command">rpm</strong> executable, therefore
this has to be run on an RPM-based system such as Red Hat Linux, SuSE Linux, or
Mandrake Linux.)</p>
<p>You can find out what distribution formats are available at any time by running</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">bdist</span> <span class="o">--</span><span class="n">help</span><span class="o">-</span><span class="n">formats</span>
</pre></div>
</div>
</div>
<div class="section" id="general-python-terminology">
<span id="python-terms"></span><h2>1.3. General Python terminology<a class="headerlink" href="#general-python-terminology" title="Permalink to this headline">¶</a></h2>
<p>If you’re reading this document, you probably have a good idea of what modules,
extensions, and so forth are.  Nevertheless, just to be sure that everyone is
operating from a common starting point, we offer the following glossary of
common Python terms:</p>
<dl class="docutils">
<dt>module</dt>
<dd>the basic unit of code reusability in Python: a block of code imported by some
other code.  Three types of modules concern us here: pure Python modules,
extension modules, and packages.</dd>
<dt>pure Python module</dt>
<dd>a module written in Python and contained in a single <code class="file docutils literal notranslate"><span class="pre">.py</span></code> file (and
possibly associated <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> and/or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files).  Sometimes referred
to as a “pure module.”</dd>
<dt>extension module</dt>
<dd>a module written in the low-level language of the Python implementation: C/C++
for Python, Java for Jython. Typically contained in a single dynamically
loadable pre-compiled file, e.g. a shared object (<code class="file docutils literal notranslate"><span class="pre">.so</span></code>) file for Python
extensions on Unix, a DLL (given the <code class="file docutils literal notranslate"><span class="pre">.pyd</span></code> extension) for Python
extensions on Windows, or a Java class file for Jython extensions.  (Note that
currently, the Distutils only handles C/C++ extensions for Python.)</dd>
<dt>package</dt>
<dd>a module that contains other modules; typically contained in a directory in the
filesystem and distinguished from other directories by the presence of a file
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>.</dd>
<dt>root package</dt>
<dd>the root of the hierarchy of packages.  (This isn’t really a package, since it
doesn’t have an <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> file.  But we have to call it something.)
The vast majority of the standard library is in the root package, as are many
small, standalone third-party modules that don’t belong to a larger module
collection. Unlike regular packages, modules in the root package can be found in
many directories: in fact, every directory listed in <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> contributes
modules to the root package.</dd>
</dl>
</div>
<div class="section" id="distutils-specific-terminology">
<span id="distutils-term"></span><h2>1.4. Distutils-specific terminology<a class="headerlink" href="#distutils-specific-terminology" title="Permalink to this headline">¶</a></h2>
<p>The following terms apply more specifically to the domain of distributing Python
modules using the Distutils:</p>
<dl class="docutils">
<dt>module distribution</dt>
<dd>a collection of Python modules distributed together as a single downloadable
resource and meant to be installed <em>en masse</em>.  Examples of some well-known
module distributions are Numeric Python, PyXML, Pillow,
or mxBase.  (This would be called a <em>package</em>, except that term is
already taken in the Python context: a single module distribution may contain
zero, one, or many Python packages.)</dd>
<dt>pure module distribution</dt>
<dd>a module distribution that contains only pure Python modules and packages.
Sometimes referred to as a “pure distribution.”</dd>
<dt>non-pure module distribution</dt>
<dd>a module distribution that contains at least one extension module.  Sometimes
referred to as a “non-pure distribution.”</dd>
<dt>distribution root</dt>
<dd>the top-level directory of your source tree (or  source distribution); the
directory where <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> exists.  Generally  <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> will be
run from this directory.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">1. An Introduction to Distutils</a><ul>
<li><a class="reference internal" href="#concepts-terminology">1.1. Concepts &amp; Terminology</a></li>
<li><a class="reference internal" href="#a-simple-example">1.2. A Simple Example</a></li>
<li><a class="reference internal" href="#general-python-terminology">1.3. General Python terminology</a></li>
<li><a class="reference internal" href="#distutils-specific-terminology">1.4. Distutils-specific terminology</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Distributing Python Modules (Legacy version)</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="setupscript.html"
                        title="next chapter">2. Writing the Setup Script</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/introduction.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="setupscript.html" title="2. Writing the Setup Script"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Distributing Python Modules (Legacy version)"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\>$�f�f html/distutils/packageindex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>6. The Python Package Index (PyPI) &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7. Examples" href="examples.html" />
    <link rel="prev" title="5. Creating Built Distributions" href="builtdist.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/packageindex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="examples.html" title="7. Examples"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="builtdist.html" title="5. Creating Built Distributions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-python-package-index-pypi">
<span id="package-index"></span><span id="index-0"></span><h1>6. The Python Package Index (PyPI)<a class="headerlink" href="#the-python-package-index-pypi" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference external" href="https://pypi.org">Python Package Index (PyPI)</a> stores <a class="reference internal" href="setupscript.html#meta-data"><span class="std std-ref">meta-data</span></a>
describing distributions packaged with distutils, as well as package data like
distribution files if a package author wishes.</p>
<p>Distutils provides the <strong class="command">register</strong> and <strong class="command">upload</strong> commands for
pushing meta-data and distribution files to PyPI, respectively.  See
<a class="reference internal" href="#package-commands"><span class="std std-ref">Distutils commands</span></a> for information on these commands.</p>
<div class="section" id="pypi-overview">
<h2>6.1. PyPI overview<a class="headerlink" href="#pypi-overview" title="Permalink to this headline">¶</a></h2>
<p>PyPI lets you submit any number of versions of your distribution to the index.
If you alter the meta-data for a particular version, you can submit it again
and the index will be updated.</p>
<p>PyPI holds a record for each (name, version) combination submitted.  The first
user to submit information for a given name is designated the Owner of that
name.  Changes can be submitted through the <strong class="command">register</strong> command or
through the web interface.  Owners can designate other users as Owners or
Maintainers.  Maintainers can edit the package information, but not designate
new Owners or Maintainers.</p>
<p>By default PyPI displays only the newest version of a given package.  The web
interface lets one change this default behavior and manually select which
versions to display and hide.</p>
<p>For each version, PyPI displays a home page.  The home page is created from
the <code class="docutils literal notranslate"><span class="pre">long_description</span></code> which can be submitted via the <strong class="command">register</strong>
command.  See <a class="reference internal" href="#package-display"><span class="std std-ref">PyPI package display</span></a> for more information.</p>
</div>
<div class="section" id="distutils-commands">
<span id="package-commands"></span><h2>6.2. Distutils commands<a class="headerlink" href="#distutils-commands" title="Permalink to this headline">¶</a></h2>
<p>Distutils exposes two commands for submitting package data to PyPI: the
<a class="reference internal" href="#package-register"><span class="std std-ref">register</span></a> command for submitting meta-data to PyPI
and the <a class="reference internal" href="#package-upload"><span class="std std-ref">upload</span></a> command for submitting distribution
files.  Both commands read configuration data from a special file called a
<a class="reference internal" href="#pypirc"><span class="std std-ref">.pypirc file</span></a>.</p>
<div class="section" id="the-register-command">
<span id="package-register"></span><h3>6.2.1. The <code class="docutils literal notranslate"><span class="pre">register</span></code> command<a class="headerlink" href="#the-register-command" title="Permalink to this headline">¶</a></h3>
<p>The distutils command <strong class="command">register</strong> is used to submit your distribution’s
meta-data to an index server. It is invoked as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">register</span>
</pre></div>
</div>
<p>Distutils will respond with the following prompt:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">running</span> <span class="n">register</span>
<span class="n">We</span> <span class="n">need</span> <span class="n">to</span> <span class="n">know</span> <span class="n">who</span> <span class="n">you</span> <span class="n">are</span><span class="p">,</span> <span class="n">so</span> <span class="n">please</span> <span class="n">choose</span> <span class="n">either</span><span class="p">:</span>
    <span class="mf">1.</span> <span class="n">use</span> <span class="n">your</span> <span class="n">existing</span> <span class="n">login</span><span class="p">,</span>
    <span class="mf">2.</span> <span class="n">register</span> <span class="k">as</span> <span class="n">a</span> <span class="n">new</span> <span class="n">user</span><span class="p">,</span>
    <span class="mf">3.</span> <span class="n">have</span> <span class="n">the</span> <span class="n">server</span> <span class="n">generate</span> <span class="n">a</span> <span class="n">new</span> <span class="n">password</span> <span class="k">for</span> <span class="n">you</span> <span class="p">(</span><span class="ow">and</span> <span class="n">email</span> <span class="n">it</span> <span class="n">to</span> <span class="n">you</span><span class="p">),</span> <span class="ow">or</span>
    <span class="mf">4.</span> <span class="n">quit</span>
<span class="n">Your</span> <span class="n">selection</span> <span class="p">[</span><span class="n">default</span> <span class="mi">1</span><span class="p">]:</span>
</pre></div>
</div>
<p>Note: if your username and password are saved locally, you will not see this
menu.  Also, refer to <a class="reference internal" href="#pypirc"><span class="std std-ref">The .pypirc file</span></a> for how to store your credentials in a
<code class="file docutils literal notranslate"><span class="pre">.pypirc</span></code> file.</p>
<p>If you have not registered with PyPI, then you will need to do so now. You
should choose option 2, and enter your details as required. Soon after
submitting your details, you will receive an email which will be used to confirm
your registration.</p>
<p>Once you are registered, you may choose option 1 from the menu. You will be
prompted for your PyPI username and password, and <strong class="command">register</strong> will then
submit your meta-data to the index.</p>
<p>See <a class="reference internal" href="#package-cmdoptions"><span class="std std-ref">Additional command options</span></a> for options to the <strong class="command">register</strong> command.</p>
</div>
<div class="section" id="the-upload-command">
<span id="package-upload"></span><h3>6.2.2. The <code class="docutils literal notranslate"><span class="pre">upload</span></code> command<a class="headerlink" href="#the-upload-command" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The distutils command <strong class="command">upload</strong> pushes the distribution files to PyPI.</p>
<p>The command is invoked immediately after building one or more distribution
files.  For example, the command</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span> <span class="n">bdist_wininst</span> <span class="n">upload</span>
</pre></div>
</div>
<p>will cause the source distribution and the Windows installer to be uploaded to
PyPI.  Note that these will be uploaded even if they are built using an earlier
invocation of <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, but that only distributions named on the command
line for the invocation including the <strong class="command">upload</strong> command are uploaded.</p>
<p>If a <strong class="command">register</strong> command was previously called in the same command,
and if the password was entered in the prompt, <strong class="command">upload</strong> will reuse the
entered password.  This is useful if you do not want to store a password in
clear text in a <code class="file docutils literal notranslate"><span class="pre">.pypirc</span></code> file.</p>
<p>You can use the <code class="docutils literal notranslate"><span class="pre">--sign</span></code> option to tell <strong class="command">upload</strong> to sign each
uploaded file using GPG (GNU Privacy Guard).  The  <strong class="program">gpg</strong> program must
be available for execution on the system <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>.  You can also specify
which key to use for signing using the <code class="docutils literal notranslate"><span class="pre">--identity=name</span></code> option.</p>
<p>See <a class="reference internal" href="#package-cmdoptions"><span class="std std-ref">Additional command options</span></a> for additional options to the <strong class="command">upload</strong>
command.</p>
</div>
<div class="section" id="additional-command-options">
<span id="package-cmdoptions"></span><h3>6.2.3. Additional command options<a class="headerlink" href="#additional-command-options" title="Permalink to this headline">¶</a></h3>
<p>This section describes options common to both the <strong class="command">register</strong> and
<strong class="command">upload</strong> commands.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">--repository</span></code> or <code class="docutils literal notranslate"><span class="pre">-r</span></code> option lets you specify a PyPI server
different from the default.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span> <span class="n">bdist_wininst</span> <span class="n">upload</span> <span class="o">-</span><span class="n">r</span> <span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">/</span><span class="n">pypi</span>
</pre></div>
</div>
<p>For convenience, a name can be used in place of the URL when the
<code class="file docutils literal notranslate"><span class="pre">.pypirc</span></code> file is configured to do so.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">register</span> <span class="o">-</span><span class="n">r</span> <span class="n">other</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#pypirc"><span class="std std-ref">The .pypirc file</span></a> for more information on defining alternate servers.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">--show-response</span></code> option displays the full response text from the PyPI
server, which is useful when debugging problems with registering and uploading.</p>
</div>
<div class="section" id="the-pypirc-file">
<span id="pypirc"></span><span id="index-2"></span><h3>6.2.4. The <code class="docutils literal notranslate"><span class="pre">.pypirc</span></code> file<a class="headerlink" href="#the-pypirc-file" title="Permalink to this headline">¶</a></h3>
<p>The <strong class="command">register</strong> and <strong class="command">upload</strong> commands both check for the
existence of a <code class="file docutils literal notranslate"><span class="pre">.pypirc</span></code> file at the location <code class="file docutils literal notranslate"><span class="pre">$HOME/.pypirc</span></code>.
If this file exists, the command uses the username, password, and repository
URL configured in the file.  The format of a <code class="file docutils literal notranslate"><span class="pre">.pypirc</span></code> file is as
follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">distutils</span><span class="p">]</span>
<span class="n">index</span><span class="o">-</span><span class="n">servers</span> <span class="o">=</span>
    <span class="n">pypi</span>

<span class="p">[</span><span class="n">pypi</span><span class="p">]</span>
<span class="n">repository</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">repository</span><span class="o">-</span><span class="n">url</span><span class="o">&gt;</span>
<span class="n">username</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">username</span><span class="o">&gt;</span>
<span class="n">password</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">password</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>The <em>distutils</em> section defines an <em>index-servers</em> variable that lists the
name of all sections describing a repository.</p>
<p>Each section describing a repository defines three variables:</p>
<ul class="simple">
<li><dl class="first docutils">
<dt><em>repository</em>, that defines the url of the PyPI server. Defaults to</dt>
<dd><code class="docutils literal notranslate"><span class="pre">https://www.python.org/pypi</span></code>.</dd>
</dl>
</li>
<li><em>username</em>, which is the registered username on the PyPI server.</li>
<li><dl class="first docutils">
<dt><em>password</em>, that will be used to authenticate. If omitted the user</dt>
<dd>will be prompt to type it when needed.</dd>
</dl>
</li>
</ul>
<p>If you want to define another server a new section can be created and
listed in the <em>index-servers</em> variable:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">distutils</span><span class="p">]</span>
<span class="n">index</span><span class="o">-</span><span class="n">servers</span> <span class="o">=</span>
    <span class="n">pypi</span>
    <span class="n">other</span>

<span class="p">[</span><span class="n">pypi</span><span class="p">]</span>
<span class="n">repository</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">repository</span><span class="o">-</span><span class="n">url</span><span class="o">&gt;</span>
<span class="n">username</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">username</span><span class="o">&gt;</span>
<span class="n">password</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">password</span><span class="o">&gt;</span>

<span class="p">[</span><span class="n">other</span><span class="p">]</span>
<span class="n">repository</span><span class="p">:</span> <span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">/</span><span class="n">pypi</span>
<span class="n">username</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">username</span><span class="o">&gt;</span>
<span class="n">password</span><span class="p">:</span> <span class="o">&lt;</span><span class="n">password</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>This allows the <strong class="command">register</strong> and <strong class="command">upload</strong> commands to be
called with the <code class="docutils literal notranslate"><span class="pre">--repository</span></code> option as described in
<a class="reference internal" href="#package-cmdoptions"><span class="std std-ref">Additional command options</span></a>.</p>
<p>Specifically, you might want to add the <a class="reference external" href="https://wiki.python.org/moin/TestPyPI">PyPI Test Repository</a> to your <code class="docutils literal notranslate"><span class="pre">.pypirc</span></code> to facilitate
testing before doing your first upload to <code class="docutils literal notranslate"><span class="pre">PyPI</span></code> itself.</p>
</div>
</div>
<div class="section" id="pypi-package-display">
<span id="package-display"></span><h2>6.3. PyPI package display<a class="headerlink" href="#pypi-package-display" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">long_description</span></code> field plays a special role at PyPI. It is used by
the server to display a home page for the registered package.</p>
<p>If you use the <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a>
syntax for this field, PyPI will parse it and display an HTML output for
the package home page.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">long_description</span></code> field can be attached to a text file located
in the package:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;README.txt&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">file</span><span class="p">:</span>
    <span class="n">long_description</span> <span class="o">=</span> <span class="n">file</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Distutils&#39;</span><span class="p">,</span>
      <span class="n">long_description</span><span class="o">=</span><span class="n">long_description</span><span class="p">)</span>
</pre></div>
</div>
<p>In that case, <code class="file docutils literal notranslate"><span class="pre">README.txt</span></code> is a regular reStructuredText text file located
in the root of the package besides <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>.</p>
<p>To prevent registering broken reStructuredText content, you can use the
<strong class="program">rst2html</strong> program that is provided by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">docutils</span></code> package and
check the <code class="docutils literal notranslate"><span class="pre">long_description</span></code> from the command line:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python setup.py --long-description <span class="p">|</span> rst2html.py &gt; output.html
</pre></div>
</div>
<p><code class="xref py py-mod docutils literal notranslate"><span class="pre">docutils</span></code> will display a warning if there’s something wrong with your
syntax.  Because PyPI applies additional checks (e.g. by passing <code class="docutils literal notranslate"><span class="pre">--no-raw</span></code>
to <code class="docutils literal notranslate"><span class="pre">rst2html.py</span></code> in the command above), being able to run the command above
without warnings does not guarantee that PyPI will convert the content
successfully.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">6. The Python Package Index (PyPI)</a><ul>
<li><a class="reference internal" href="#pypi-overview">6.1. PyPI overview</a></li>
<li><a class="reference internal" href="#distutils-commands">6.2. Distutils commands</a><ul>
<li><a class="reference internal" href="#the-register-command">6.2.1. The <code class="docutils literal notranslate"><span class="pre">register</span></code> command</a></li>
<li><a class="reference internal" href="#the-upload-command">6.2.2. The <code class="docutils literal notranslate"><span class="pre">upload</span></code> command</a></li>
<li><a class="reference internal" href="#additional-command-options">6.2.3. Additional command options</a></li>
<li><a class="reference internal" href="#the-pypirc-file">6.2.4. The <code class="docutils literal notranslate"><span class="pre">.pypirc</span></code> file</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pypi-package-display">6.3. PyPI package display</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="builtdist.html"
                        title="previous chapter">5. Creating Built Distributions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="examples.html"
                        title="next chapter">7. Examples</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/packageindex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="examples.html" title="7. Examples"
             >next</a> |</li>
        <li class="right" >
          <a href="builtdist.html" title="5. Creating Built Distributions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����
�
html/distutils/setupscript.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Writing the Setup Script &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="3. Writing the Setup Configuration File" href="configfile.html" />
    <link rel="prev" title="1. An Introduction to Distutils" href="introduction.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/setupscript.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="configfile.html" title="3. Writing the Setup Configuration File"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. An Introduction to Distutils"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="writing-the-setup-script">
<span id="setup-script"></span><h1>2. Writing the Setup Script<a class="headerlink" href="#writing-the-setup-script" title="Permalink to this headline">¶</a></h1>
<p>The setup script is the centre of all activity in building, distributing, and
installing modules using the Distutils.  The main purpose of the setup script is
to describe your module distribution to the Distutils, so that the various
commands that operate on your modules do the right thing.  As we saw in section
<a class="reference internal" href="introduction.html#distutils-simple-example"><span class="std std-ref">A Simple Example</span></a> above, the setup script consists mainly of a call to
<code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>, and most information supplied to the Distutils by the module
developer is supplied as keyword arguments to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>.</p>
<p>Here’s a slightly more involved example, which we’ll follow for the next couple
of sections: the Distutils’ own setup script.  (Keep in mind that although the
Distutils are included with Python 1.6 and later, they also have an independent
existence so that Python 1.5.2 users can use them to install other module
distributions.  The Distutils’ own setup script, shown here, is used to install
the package into Python 1.5.2.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>

<span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>

<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Distutils&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">description</span><span class="o">=</span><span class="s1">&#39;Python Distribution Utilities&#39;</span><span class="p">,</span>
      <span class="n">author</span><span class="o">=</span><span class="s1">&#39;Greg Ward&#39;</span><span class="p">,</span>
      <span class="n">author_email</span><span class="o">=</span><span class="s1">&#39;gward@python.net&#39;</span><span class="p">,</span>
      <span class="n">url</span><span class="o">=</span><span class="s1">&#39;https://www.python.org/sigs/distutils-sig/&#39;</span><span class="p">,</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;distutils&#39;</span><span class="p">,</span> <span class="s1">&#39;distutils.command&#39;</span><span class="p">],</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>There are only two differences between this and the trivial one-file
distribution presented in section <a class="reference internal" href="introduction.html#distutils-simple-example"><span class="std std-ref">A Simple Example</span></a>: more metadata, and the
specification of pure Python modules by package, rather than by module.  This is
important since the Distutils consist of a couple of dozen modules split into
(so far) two packages; an explicit list of every module would be tedious to
generate and difficult to maintain.  For more information on the additional
meta-data, see section <a class="reference internal" href="#meta-data"><span class="std std-ref">Additional meta-data</span></a>.</p>
<p>Note that any pathnames (files or directories) supplied in the setup script
should be written using the Unix convention, i.e. slash-separated.  The
Distutils will take care of converting this platform-neutral representation into
whatever is appropriate on your current platform before actually using the
pathname.  This makes your setup script portable across operating systems, which
of course is one of the major goals of the Distutils.  In this spirit, all
pathnames in this document are slash-separated.</p>
<p>This, of course, only applies to pathnames given to Distutils functions.  If
you, for example, use standard Python functions such as <a class="reference internal" href="../library/glob.html#glob.glob" title="glob.glob"><code class="xref py py-func docutils literal notranslate"><span class="pre">glob.glob()</span></code></a> or
<a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> to specify files, you should be careful to write portable
code instead of hardcoding path separators:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;mydir&#39;</span><span class="p">,</span> <span class="s1">&#39;subdir&#39;</span><span class="p">,</span> <span class="s1">&#39;*.html&#39;</span><span class="p">))</span>
<span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;mydir&#39;</span><span class="p">,</span> <span class="s1">&#39;subdir&#39;</span><span class="p">))</span>
</pre></div>
</div>
<div class="section" id="listing-whole-packages">
<span id="listing-packages"></span><h2>2.1. Listing whole packages<a class="headerlink" href="#listing-whole-packages" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">packages</span></code> option tells the Distutils to process (build, distribute,
install, etc.) all pure Python modules found in each package mentioned in the
<code class="docutils literal notranslate"><span class="pre">packages</span></code> list.  In order to do this, of course, there has to be a
correspondence between package names and directories in the filesystem.  The
default correspondence is the most obvious one, i.e. package <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> is
found in the directory <code class="file docutils literal notranslate"><span class="pre">distutils</span></code> relative to the distribution root.
Thus, when you say <code class="docutils literal notranslate"><span class="pre">packages</span> <span class="pre">=</span> <span class="pre">['foo']</span></code> in your setup script, you are
promising that the Distutils will find a file <code class="file docutils literal notranslate"><span class="pre">foo/__init__.py</span></code> (which
might be spelled differently on your system, but you get the idea) relative to
the directory where your setup script lives.  If you break this promise, the
Distutils will issue a warning but still process the broken package anyway.</p>
<p>If you use a different convention to lay out your source directory, that’s no
problem: you just have to supply the <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> option to tell the
Distutils about your convention.  For example, say you keep all Python source
under <code class="file docutils literal notranslate"><span class="pre">lib</span></code>, so that modules in the “root package” (i.e., not in any
package at all) are in <code class="file docutils literal notranslate"><span class="pre">lib</span></code>, modules in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> package are in
<code class="file docutils literal notranslate"><span class="pre">lib/foo</span></code>, and so forth.  Then you would put</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">package_dir</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;&#39;</span><span class="p">:</span> <span class="s1">&#39;lib&#39;</span><span class="p">}</span>
</pre></div>
</div>
<p>in your setup script.  The keys to this dictionary are package names, and an
empty package name stands for the root package.  The values are directory names
relative to your distribution root.  In this case, when you say <code class="docutils literal notranslate"><span class="pre">packages</span> <span class="pre">=</span>
<span class="pre">['foo']</span></code>, you are promising that the file <code class="file docutils literal notranslate"><span class="pre">lib/foo/__init__.py</span></code> exists.</p>
<p>Another possible convention is to put the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> package right in
<code class="file docutils literal notranslate"><span class="pre">lib</span></code>, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo.bar</span></code> package in <code class="file docutils literal notranslate"><span class="pre">lib/bar</span></code>, etc.  This would be
written in the setup script as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">package_dir</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;foo&#39;</span><span class="p">:</span> <span class="s1">&#39;lib&#39;</span><span class="p">}</span>
</pre></div>
</div>
<p>A <code class="docutils literal notranslate"><span class="pre">package:</span> <span class="pre">dir</span></code> entry in the <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> dictionary implicitly
applies to all packages below <em>package</em>, so the <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo.bar</span></code> case is
automatically handled here.  In this example, having <code class="docutils literal notranslate"><span class="pre">packages</span> <span class="pre">=</span> <span class="pre">['foo',</span>
<span class="pre">'foo.bar']</span></code> tells the Distutils to look for <code class="file docutils literal notranslate"><span class="pre">lib/__init__.py</span></code> and
<code class="file docutils literal notranslate"><span class="pre">lib/bar/__init__.py</span></code>.  (Keep in mind that although <code class="docutils literal notranslate"><span class="pre">package_dir</span></code>
applies recursively, you must explicitly list all packages in
<code class="docutils literal notranslate"><span class="pre">packages</span></code>: the Distutils will <em>not</em> recursively scan your source tree
looking for any directory with an <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> file.)</p>
</div>
<div class="section" id="listing-individual-modules">
<span id="listing-modules"></span><h2>2.2. Listing individual modules<a class="headerlink" href="#listing-individual-modules" title="Permalink to this headline">¶</a></h2>
<p>For a small module distribution, you might prefer to list all modules rather
than listing packages—especially the case of a single module that goes in the
“root package” (i.e., no package at all).  This simplest case was shown in
section <a class="reference internal" href="introduction.html#distutils-simple-example"><span class="std std-ref">A Simple Example</span></a>; here is a slightly more involved example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">py_modules</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;mod1&#39;</span><span class="p">,</span> <span class="s1">&#39;pkg.mod2&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>This describes two modules, one of them in the “root” package, the other in the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg</span></code> package.  Again, the default package/directory layout implies that
these two modules can be found in <code class="file docutils literal notranslate"><span class="pre">mod1.py</span></code> and <code class="file docutils literal notranslate"><span class="pre">pkg/mod2.py</span></code>, and
that <code class="file docutils literal notranslate"><span class="pre">pkg/__init__.py</span></code> exists as well. And again, you can override the
package/directory correspondence using the <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> option.</p>
</div>
<div class="section" id="describing-extension-modules">
<span id="describing-extensions"></span><h2>2.3. Describing extension modules<a class="headerlink" href="#describing-extension-modules" title="Permalink to this headline">¶</a></h2>
<p>Just as writing Python extension modules is a bit more complicated than writing
pure Python modules, describing them to the Distutils is a bit more complicated.
Unlike pure modules, it’s not enough just to list modules or packages and expect
the Distutils to go out and find the right files; you have to specify the
extension name, source file(s), and any compile/link requirements (include
directories, libraries to link with, etc.).</p>
<p>All of this is done through another keyword argument to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>, the
<code class="docutils literal notranslate"><span class="pre">ext_modules</span></code> option.  <code class="docutils literal notranslate"><span class="pre">ext_modules</span></code> is just a list of
<a class="reference internal" href="apiref.html#distutils.core.Extension" title="distutils.core.Extension"><code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code></a> instances, each of which describes a
single extension module.
Suppose your distribution includes a single extension, called <code class="xref py py-mod docutils literal notranslate"><span class="pre">foo</span></code> and
implemented by <code class="file docutils literal notranslate"><span class="pre">foo.c</span></code>.  If no additional instructions to the
compiler/linker are needed, describing this extension is quite simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> class can be imported from <a class="reference internal" href="apiref.html#module-distutils.core" title="distutils.core: The core Distutils functionality"><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.core</span></code></a> along
with <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>.  Thus, the setup script for a module distribution that
contains only this one extension and nothing else might be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">])],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> class (actually, the underlying extension-building
machinery implemented by the <strong class="command">build_ext</strong> command) supports a great deal
of flexibility in describing Python extensions, which is explained in the
following sections.</p>
<div class="section" id="extension-names-and-packages">
<h3>2.3.1. Extension names and packages<a class="headerlink" href="#extension-names-and-packages" title="Permalink to this headline">¶</a></h3>
<p>The first argument to the <a class="reference internal" href="apiref.html#distutils.core.Extension" title="distutils.core.Extension"><code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code></a> constructor is
always the name of the extension, including any package names.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;src/foo1.c&#39;</span><span class="p">,</span> <span class="s1">&#39;src/foo2.c&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>describes an extension that lives in the root package, while</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;pkg.foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;src/foo1.c&#39;</span><span class="p">,</span> <span class="s1">&#39;src/foo2.c&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>describes the same extension in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg</span></code> package.  The source files and
resulting object code are identical in both cases; the only difference is where
in the filesystem (and therefore where in Python’s namespace hierarchy) the
resulting extension lives.</p>
<p>If you have a number of extensions all in the same package (or all under the
same base package), use the <code class="docutils literal notranslate"><span class="pre">ext_package</span></code> keyword argument to
<code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">ext_package</span><span class="o">=</span><span class="s1">&#39;pkg&#39;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">]),</span>
                   <span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;subpkg.bar&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;bar.c&#39;</span><span class="p">])],</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>will compile <code class="file docutils literal notranslate"><span class="pre">foo.c</span></code> to the extension <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.foo</span></code>, and <code class="file docutils literal notranslate"><span class="pre">bar.c</span></code> to
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.subpkg.bar</span></code>.</p>
</div>
<div class="section" id="extension-source-files">
<h3>2.3.2. Extension source files<a class="headerlink" href="#extension-source-files" title="Permalink to this headline">¶</a></h3>
<p>The second argument to the <a class="reference internal" href="apiref.html#distutils.core.Extension" title="distutils.core.Extension"><code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code></a> constructor is
a list of source
files.  Since the Distutils currently only support C, C++, and Objective-C
extensions, these are normally C/C++/Objective-C source files.  (Be sure to use
appropriate extensions to distinguish C++ source files: <code class="file docutils literal notranslate"><span class="pre">.cc</span></code> and
<code class="file docutils literal notranslate"><span class="pre">.cpp</span></code> seem to be recognized by both Unix and Windows compilers.)</p>
<p>However, you can also include SWIG interface (<code class="file docutils literal notranslate"><span class="pre">.i</span></code>) files in the list; the
<strong class="command">build_ext</strong> command knows how to deal with SWIG extensions: it will run
SWIG on the interface file and compile the resulting C/C++ file into your
extension.</p>
<p>This warning notwithstanding, options to SWIG can be currently passed like
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;_foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.i&#39;</span><span class="p">],</span>
                             <span class="n">swig_opts</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;-modern&#39;</span><span class="p">,</span> <span class="s1">&#39;-I../include&#39;</span><span class="p">])],</span>
      <span class="n">py_modules</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">],</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>Or on the commandline like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;</span> <span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">build_ext</span> <span class="o">--</span><span class="n">swig</span><span class="o">-</span><span class="n">opts</span><span class="o">=</span><span class="s2">&quot;-modern -I../include&quot;</span>
</pre></div>
</div>
<p>On some platforms, you can include non-source files that are processed by the
compiler and included in your extension.  Currently, this just means Windows
message text (<code class="file docutils literal notranslate"><span class="pre">.mc</span></code>) files and resource definition (<code class="file docutils literal notranslate"><span class="pre">.rc</span></code>) files for
Visual C++. These will be compiled to binary resource (<code class="file docutils literal notranslate"><span class="pre">.res</span></code>) files and
linked into the executable.</p>
</div>
<div class="section" id="preprocessor-options">
<h3>2.3.3. Preprocessor options<a class="headerlink" href="#preprocessor-options" title="Permalink to this headline">¶</a></h3>
<p>Three optional arguments to <a class="reference internal" href="apiref.html#distutils.core.Extension" title="distutils.core.Extension"><code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code></a> will help if
you need to specify include directories to search or preprocessor macros to
define/undefine: <code class="docutils literal notranslate"><span class="pre">include_dirs</span></code>, <code class="docutils literal notranslate"><span class="pre">define_macros</span></code>, and <code class="docutils literal notranslate"><span class="pre">undef_macros</span></code>.</p>
<p>For example, if your extension requires header files in the <code class="file docutils literal notranslate"><span class="pre">include</span></code>
directory under your distribution root, use the <code class="docutils literal notranslate"><span class="pre">include_dirs</span></code> option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">],</span> <span class="n">include_dirs</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;include&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>You can specify absolute directories there; if you know that your extension will
only be built on Unix systems with X11R6 installed to <code class="file docutils literal notranslate"><span class="pre">/usr</span></code>, you can get
away with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;foo.c&#39;</span><span class="p">],</span> <span class="n">include_dirs</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;/usr/include/X11&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>You should avoid this sort of non-portable usage if you plan to distribute your
code: it’s probably better to write C code like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#include &lt;X11/Xlib.h&gt;</span>
</pre></div>
</div>
<p>If you need to include header files from some other Python extension, you can
take advantage of the fact that header files are installed in a consistent way
by the Distutils <strong class="command">install_headers</strong> command.  For example, the Numerical
Python header files are installed (on a standard Unix installation) to
<code class="file docutils literal notranslate"><span class="pre">/usr/local/include/python1.5/Numerical</span></code>. (The exact location will differ
according to your platform and Python installation.)  Since the Python include
directory—<code class="file docutils literal notranslate"><span class="pre">/usr/local/include/python1.5</span></code> in this case—is always
included in the search path when building Python extensions, the best approach
is to write C code like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#include &lt;Numerical/arrayobject.h&gt;</span>
</pre></div>
</div>
<p>If you must put the <code class="file docutils literal notranslate"><span class="pre">Numerical</span></code> include directory right into your header
search path, though, you can find that directory using the Distutils
<a class="reference internal" href="apiref.html#module-distutils.sysconfig" title="distutils.sysconfig: Low-level access to configuration information of the Python interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils.sysconfig</span></code></a> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.sysconfig</span> <span class="k">import</span> <span class="n">get_python_inc</span>
<span class="n">incdir</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">get_python_inc</span><span class="p">(</span><span class="n">plat_specific</span><span class="o">=</span><span class="mi">1</span><span class="p">),</span> <span class="s1">&#39;Numerical&#39;</span><span class="p">)</span>
<span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">Extension</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="n">include_dirs</span><span class="o">=</span><span class="p">[</span><span class="n">incdir</span><span class="p">]),</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>Even though this is quite portable—it will work on any Python installation,
regardless of platform—it’s probably easier to just write your C code in the
sensible way.</p>
<p>You can define and undefine pre-processor macros with the <code class="docutils literal notranslate"><span class="pre">define_macros</span></code> and
<code class="docutils literal notranslate"><span class="pre">undef_macros</span></code> options. <code class="docutils literal notranslate"><span class="pre">define_macros</span></code> takes a list of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code>
tuples, where <code class="docutils literal notranslate"><span class="pre">name</span></code> is the name of the macro to define (a string) and
<code class="docutils literal notranslate"><span class="pre">value</span></code> is its value: either a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  (Defining a macro <code class="docutils literal notranslate"><span class="pre">FOO</span></code>
to <code class="docutils literal notranslate"><span class="pre">None</span></code> is the equivalent of a bare <code class="docutils literal notranslate"><span class="pre">#define</span> <span class="pre">FOO</span></code> in your C source: with
most compilers, this sets <code class="docutils literal notranslate"><span class="pre">FOO</span></code> to the string <code class="docutils literal notranslate"><span class="pre">1</span></code>.)  <code class="docutils literal notranslate"><span class="pre">undef_macros</span></code> is
just a list of macros to undefine.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
          <span class="n">define_macros</span><span class="o">=</span><span class="p">[(</span><span class="s1">&#39;NDEBUG&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">),</span>
                         <span class="p">(</span><span class="s1">&#39;HAVE_STRFTIME&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)],</span>
          <span class="n">undef_macros</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;HAVE_FOO&#39;</span><span class="p">,</span> <span class="s1">&#39;HAVE_BAR&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>is the equivalent of having this at the top of every C source file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#define NDEBUG 1</span>
<span class="c1">#define HAVE_STRFTIME</span>
<span class="c1">#undef HAVE_FOO</span>
<span class="c1">#undef HAVE_BAR</span>
</pre></div>
</div>
</div>
<div class="section" id="library-options">
<h3>2.3.4. Library options<a class="headerlink" href="#library-options" title="Permalink to this headline">¶</a></h3>
<p>You can also specify the libraries to link against when building your extension,
and the directories to search for those libraries.  The <code class="docutils literal notranslate"><span class="pre">libraries</span></code> option is
a list of libraries to link against, <code class="docutils literal notranslate"><span class="pre">library_dirs</span></code> is a list of directories
to search for libraries at  link-time, and <code class="docutils literal notranslate"><span class="pre">runtime_library_dirs</span></code> is a list of
directories to  search for shared (dynamically loaded) libraries at run-time.</p>
<p>For example, if you need to link against libraries known to be in the standard
library search path on target systems</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
          <span class="n">libraries</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;gdbm&#39;</span><span class="p">,</span> <span class="s1">&#39;readline&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>If you need to link with libraries in a non-standard location, you’ll have to
include the location in <code class="docutils literal notranslate"><span class="pre">library_dirs</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Extension</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
          <span class="n">library_dirs</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;/usr/X11R6/lib&#39;</span><span class="p">],</span>
          <span class="n">libraries</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;X11&#39;</span><span class="p">,</span> <span class="s1">&#39;Xt&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>(Again, this sort of non-portable construct should be avoided if you intend to
distribute your code.)</p>
</div>
<div class="section" id="other-options">
<h3>2.3.5. Other options<a class="headerlink" href="#other-options" title="Permalink to this headline">¶</a></h3>
<p>There are still some other options which can be used to handle special cases.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">extra_objects</span></code> option is a list of object files to be passed to the
linker. These files must not have extensions, as the default extension for the
compiler is used.</p>
<p><code class="docutils literal notranslate"><span class="pre">extra_compile_args</span></code> and <code class="docutils literal notranslate"><span class="pre">extra_link_args</span></code> can be used to
specify additional command line options for the respective compiler and linker
command lines.</p>
<p><code class="docutils literal notranslate"><span class="pre">export_symbols</span></code> is only useful on Windows.  It can contain a list of
symbols (functions or variables) to be exported. This option is not needed when
building compiled extensions: Distutils  will automatically add <code class="docutils literal notranslate"><span class="pre">initmodule</span></code>
to the list of exported symbols.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">depends</span></code> option is a list of files that the extension depends on
(for example header files). The build command will call the compiler on the
sources to rebuild extension if any on this files has been modified since the
previous build.</p>
</div>
</div>
<div class="section" id="relationships-between-distributions-and-packages">
<h2>2.4. Relationships between Distributions and Packages<a class="headerlink" href="#relationships-between-distributions-and-packages" title="Permalink to this headline">¶</a></h2>
<p>A distribution may relate to packages in three specific ways:</p>
<ol class="arabic simple">
<li>It can require packages or modules.</li>
<li>It can provide packages or modules.</li>
<li>It can obsolete packages or modules.</li>
</ol>
<p>These relationships can be specified using keyword arguments to the
<a class="reference internal" href="apiref.html#distutils.core.setup" title="distutils.core.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">distutils.core.setup()</span></code></a> function.</p>
<p>Dependencies on other Python modules and packages can be specified by supplying
the <em>requires</em> keyword argument to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>. The value must be a list of
strings.  Each string specifies a package that is required, and optionally what
versions are sufficient.</p>
<p>To specify that any version of a module or package is required, the string
should consist entirely of the module or package name. Examples include
<code class="docutils literal notranslate"><span class="pre">'mymodule'</span></code> and <code class="docutils literal notranslate"><span class="pre">'xml.parsers.expat'</span></code>.</p>
<p>If specific versions are required, a sequence of qualifiers can be supplied in
parentheses.  Each qualifier may consist of a comparison operator and a version
number.  The accepted comparison operators are:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span>    <span class="o">&gt;</span>    <span class="o">==</span>
<span class="o">&lt;=</span>   <span class="o">&gt;=</span>   <span class="o">!=</span>
</pre></div>
</div>
<p>These can be combined by using multiple qualifiers separated by commas (and
optional whitespace).  In this case, all of the qualifiers must be matched; a
logical AND is used to combine the evaluations.</p>
<p>Let’s look at a bunch of examples:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Requires Expression</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">==1.0</span></code></td>
<td>Only version <code class="docutils literal notranslate"><span class="pre">1.0</span></code> is compatible</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&gt;1.0,</span> <span class="pre">!=1.5.1,</span> <span class="pre">&lt;2.0</span></code></td>
<td>Any version after <code class="docutils literal notranslate"><span class="pre">1.0</span></code> and before <code class="docutils literal notranslate"><span class="pre">2.0</span></code>
is compatible, except <code class="docutils literal notranslate"><span class="pre">1.5.1</span></code></td>
</tr>
</tbody>
</table>
<p>Now that we can specify dependencies, we also need to be able to specify what we
provide that other distributions can require.  This is done using the <em>provides</em>
keyword argument to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>. The value for this keyword is a list of
strings, each of which names a Python module or package, and optionally
identifies the version.  If the version is not specified, it is assumed to match
that of the distribution.</p>
<p>Some examples:</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Provides Expression</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">mypkg</span></code></td>
<td>Provide <code class="docutils literal notranslate"><span class="pre">mypkg</span></code>, using the distribution
version</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">mypkg</span> <span class="pre">(1.1)</span></code></td>
<td>Provide <code class="docutils literal notranslate"><span class="pre">mypkg</span></code> version 1.1, regardless of
the distribution version</td>
</tr>
</tbody>
</table>
<p>A package can declare that it obsoletes other packages using the <em>obsoletes</em>
keyword argument.  The value for this is similar to that of the <em>requires</em>
keyword: a list of strings giving module or package specifiers.  Each specifier
consists of a module or package name optionally followed by one or more version
qualifiers.  Version qualifiers are given in parentheses after the module or
package name.</p>
<p>The versions identified by the qualifiers are those that are obsoleted by the
distribution being described.  If no qualifiers are given, all versions of the
named module or package are understood to be obsoleted.</p>
</div>
<div class="section" id="installing-scripts">
<span id="distutils-installing-scripts"></span><h2>2.5. Installing Scripts<a class="headerlink" href="#installing-scripts" title="Permalink to this headline">¶</a></h2>
<p>So far we have been dealing with pure and non-pure Python modules, which are
usually not run by themselves but imported by scripts.</p>
<p>Scripts are files containing Python source code, intended to be started from the
command line.  Scripts don’t require Distutils to do anything very complicated.
The only clever feature is that if the first line of the script starts with
<code class="docutils literal notranslate"><span class="pre">#!</span></code> and contains the word “python”, the Distutils will adjust the first line
to refer to the current interpreter location. By default, it is replaced with
the current interpreter location.  The <code class="xref std std-option docutils literal notranslate"><span class="pre">--executable</span></code> (or <code class="xref std std-option docutils literal notranslate"><span class="pre">-e</span></code>)
option will allow the interpreter path to be explicitly overridden.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">scripts</span></code> option simply is a list of files to be handled in this
way.  From the PyXML setup script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">scripts</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;scripts/xmlproc_parse&#39;</span><span class="p">,</span> <span class="s1">&#39;scripts/xmlproc_val&#39;</span><span class="p">]</span>
      <span class="p">)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>All the scripts will also be added to the <code class="docutils literal notranslate"><span class="pre">MANIFEST</span></code>
file if no template is provided. See <a class="reference internal" href="sourcedist.html#manifest"><span class="std std-ref">Specifying the files to distribute</span></a>.</p>
</div>
</div>
<div class="section" id="installing-package-data">
<span id="distutils-installing-package-data"></span><h2>2.6. Installing Package Data<a class="headerlink" href="#installing-package-data" title="Permalink to this headline">¶</a></h2>
<p>Often, additional files need to be installed into a package.  These files are
often data that’s closely related to the package’s implementation, or text files
containing documentation that might be of interest to programmers using the
package.  These files are called <em class="dfn">package data</em>.</p>
<p>Package data can be added to packages using the <code class="docutils literal notranslate"><span class="pre">package_data</span></code> keyword
argument to the <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function.  The value must be a mapping from
package name to a list of relative path names that should be copied into the
package.  The paths are interpreted as relative to the directory containing the
package (information from the <code class="docutils literal notranslate"><span class="pre">package_dir</span></code> mapping is used if appropriate);
that is, the files are expected to be part of the package in the source
directories. They may contain glob patterns as well.</p>
<p>The path names may contain directory portions; any necessary directories will be
created in the installation.</p>
<p>For example, if a package should contain a subdirectory with several data files,
the files can be arranged like this in the source tree:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="o">.</span><span class="n">py</span>
<span class="n">src</span><span class="o">/</span>
    <span class="n">mypkg</span><span class="o">/</span>
        <span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
        <span class="n">module</span><span class="o">.</span><span class="n">py</span>
        <span class="n">data</span><span class="o">/</span>
            <span class="n">tables</span><span class="o">.</span><span class="n">dat</span>
            <span class="n">spoons</span><span class="o">.</span><span class="n">dat</span>
            <span class="n">forks</span><span class="o">.</span><span class="n">dat</span>
</pre></div>
</div>
<p>The corresponding call to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> might be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">packages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;mypkg&#39;</span><span class="p">],</span>
      <span class="n">package_dir</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;mypkg&#39;</span><span class="p">:</span> <span class="s1">&#39;src/mypkg&#39;</span><span class="p">},</span>
      <span class="n">package_data</span><span class="o">=</span><span class="p">{</span><span class="s1">&#39;mypkg&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;data/*.dat&#39;</span><span class="p">]},</span>
      <span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>All the files that match <code class="docutils literal notranslate"><span class="pre">package_data</span></code> will be added to the <code class="docutils literal notranslate"><span class="pre">MANIFEST</span></code>
file if no template is provided. See <a class="reference internal" href="sourcedist.html#manifest"><span class="std std-ref">Specifying the files to distribute</span></a>.</p>
</div>
</div>
<div class="section" id="installing-additional-files">
<span id="distutils-additional-files"></span><h2>2.7. Installing Additional Files<a class="headerlink" href="#installing-additional-files" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">data_files</span></code> option can be used to specify additional files needed
by the module distribution: configuration files, message catalogs, data files,
anything which doesn’t fit in the previous categories.</p>
<p><code class="docutils literal notranslate"><span class="pre">data_files</span></code> specifies a sequence of (<em>directory</em>, <em>files</em>) pairs in the
following way:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">data_files</span><span class="o">=</span><span class="p">[(</span><span class="s1">&#39;bitmaps&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;bm/b1.gif&#39;</span><span class="p">,</span> <span class="s1">&#39;bm/b2.gif&#39;</span><span class="p">]),</span>
                  <span class="p">(</span><span class="s1">&#39;config&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;cfg/data.cfg&#39;</span><span class="p">]),</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>Each (<em>directory</em>, <em>files</em>) pair in the sequence specifies the installation
directory and the files to install there.</p>
<p>Each file name in <em>files</em> is interpreted relative to the <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>
script at the top of the package source distribution. Note that you can
specify the directory where the data files will be installed, but you cannot
rename the data files themselves.</p>
<p>The <em>directory</em> should be a relative path. It is interpreted relative to the
installation prefix (Python’s <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code> for system installations;
<code class="docutils literal notranslate"><span class="pre">site.USER_BASE</span></code> for user installations). Distutils allows <em>directory</em> to be
an absolute installation path, but this is discouraged since it is
incompatible with the wheel packaging format. No directory information from
<em>files</em> is used to determine the final location of the installed file; only
the name of the file is used.</p>
<p>You can specify the <code class="docutils literal notranslate"><span class="pre">data_files</span></code> options as a simple sequence of files
without specifying a target directory, but this is not recommended, and the
<strong class="command">install</strong> command will print a warning in this case. To install data
files directly in the target directory, an empty string should be given as the
directory.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>All the files that match <code class="docutils literal notranslate"><span class="pre">data_files</span></code> will be added to the <code class="docutils literal notranslate"><span class="pre">MANIFEST</span></code>
file if no template is provided. See <a class="reference internal" href="sourcedist.html#manifest"><span class="std std-ref">Specifying the files to distribute</span></a>.</p>
</div>
</div>
<div class="section" id="additional-meta-data">
<span id="meta-data"></span><h2>2.8. Additional meta-data<a class="headerlink" href="#additional-meta-data" title="Permalink to this headline">¶</a></h2>
<p>The setup script may include additional meta-data beyond the name and version.
This information includes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="36%" />
<col width="23%" />
<col width="11%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Meta-Data</th>
<th class="head">Description</th>
<th class="head">Value</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">name</span></code></td>
<td>name of the package</td>
<td>short string</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">version</span></code></td>
<td>version of this release</td>
<td>short string</td>
<td>(1)(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">author</span></code></td>
<td>package author’s name</td>
<td>short string</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">author_email</span></code></td>
<td>email address of the
package author</td>
<td>email address</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">maintainer</span></code></td>
<td>package maintainer’s name</td>
<td>short string</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">maintainer_email</span></code></td>
<td>email address of the
package maintainer</td>
<td>email address</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">url</span></code></td>
<td>home page for the package</td>
<td>URL</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">description</span></code></td>
<td>short, summary
description of the
package</td>
<td>short string</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">long_description</span></code></td>
<td>longer description of the
package</td>
<td>long string</td>
<td>(5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">download_url</span></code></td>
<td>location where the
package may be downloaded</td>
<td>URL</td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">classifiers</span></code></td>
<td>a list of classifiers</td>
<td>list of strings</td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">platforms</span></code></td>
<td>a list of platforms</td>
<td>list of strings</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">license</span></code></td>
<td>license for the package</td>
<td>short string</td>
<td>(6)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>These fields are required.</li>
<li>It is recommended that versions take the form <em>major.minor[.patch[.sub]]</em>.</li>
<li>Either the author or the maintainer must be identified. If maintainer is
provided, distutils lists it as the author in <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code>.</li>
<li>These fields should not be used if your package is to be compatible with Python
versions prior to 2.2.3 or 2.3.  The list is available from the <a class="reference external" href="https://pypi.org">PyPI website</a>.</li>
<li>The <code class="docutils literal notranslate"><span class="pre">long_description</span></code> field is used by PyPI when you are
<a class="reference internal" href="packageindex.html#package-register"><span class="std std-ref">registering</span></a> a package, to
<a class="reference internal" href="packageindex.html#package-display"><span class="std std-ref">build its home page</span></a>.</li>
<li>The <code class="docutils literal notranslate"><span class="pre">license</span></code> field is a text indicating the license covering the
package where the license is not a selection from the “License” Trove
classifiers. See the <code class="docutils literal notranslate"><span class="pre">Classifier</span></code> field. Notice that
there’s a <code class="docutils literal notranslate"><span class="pre">licence</span></code> distribution option which is deprecated but still
acts as an alias for <code class="docutils literal notranslate"><span class="pre">license</span></code>.</li>
</ol>
<dl class="docutils">
<dt>‘short string’</dt>
<dd>A single line of text, not more than 200 characters.</dd>
<dt>‘long string’</dt>
<dd>Multiple lines of plain text in reStructuredText format (see
<a class="reference external" href="http://docutils.sourceforge.net/">http://docutils.sourceforge.net/</a>).</dd>
<dt>‘list of strings’</dt>
<dd>See below.</dd>
</dl>
<p>None of the string values may be Unicode.</p>
<p>Encoding the version information is an art in itself. Python packages generally
adhere to the version format <em>major.minor[.patch][sub]</em>. The major number is 0
for initial, experimental releases of software. It is incremented for releases
that represent major milestones in a package. The minor number is incremented
when important new features are added to the package. The patch number
increments when bug-fix releases are made. Additional trailing version
information is sometimes used to indicate sub-releases.  These are
“a1,a2,…,aN” (for alpha releases, where functionality and API may change),
“b1,b2,…,bN” (for beta releases, which only fix bugs) and “pr1,pr2,…,prN”
(for final pre-release release testing). Some examples:</p>
<dl class="docutils">
<dt>0.1.0</dt>
<dd>the first, experimental release of a package</dd>
<dt>1.0.1a2</dt>
<dd>the second alpha release of the first patch version of 1.0</dd>
</dl>
<p><code class="docutils literal notranslate"><span class="pre">classifiers</span></code> are specified in a Python list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">setup</span><span class="p">(</span><span class="o">...</span><span class="p">,</span>
      <span class="n">classifiers</span><span class="o">=</span><span class="p">[</span>
          <span class="s1">&#39;Development Status :: 4 - Beta&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Environment :: Console&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Environment :: Web Environment&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Intended Audience :: End Users/Desktop&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Intended Audience :: Developers&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Intended Audience :: System Administrators&#39;</span><span class="p">,</span>
          <span class="s1">&#39;License :: OSI Approved :: Python Software Foundation License&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Operating System :: MacOS :: MacOS X&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Operating System :: Microsoft :: Windows&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Operating System :: POSIX&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Programming Language :: Python&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Topic :: Communications :: Email&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Topic :: Office/Business&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Topic :: Software Development :: Bug Tracking&#39;</span><span class="p">,</span>
          <span class="p">],</span>
      <span class="p">)</span>
</pre></div>
</div>
<p>If you wish to include classifiers in your <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> file and also wish
to remain backwards-compatible with Python releases prior to 2.2.3, then you can
include the following code fragment in your <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> before the
<code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> call.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># patch distutils if it can&#39;t cope with the &quot;classifiers&quot; or</span>
<span class="c1"># &quot;download_url&quot; keywords</span>
<span class="kn">from</span> <span class="nn">sys</span> <span class="k">import</span> <span class="n">version</span>
<span class="k">if</span> <span class="n">version</span> <span class="o">&lt;</span> <span class="s1">&#39;2.2.3&#39;</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">distutils.dist</span> <span class="k">import</span> <span class="n">DistributionMetadata</span>
    <span class="n">DistributionMetadata</span><span class="o">.</span><span class="n">classifiers</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">DistributionMetadata</span><span class="o">.</span><span class="n">download_url</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
</div>
<div class="section" id="debugging-the-setup-script">
<span id="debug-setup-script"></span><h2>2.9. Debugging the setup script<a class="headerlink" href="#debugging-the-setup-script" title="Permalink to this headline">¶</a></h2>
<p>Sometimes things go wrong, and the setup script doesn’t do what the developer
wants.</p>
<p>Distutils catches any exceptions when running the setup script, and print a
simple error message before the script is terminated.  The motivation for this
behaviour is to not confuse administrators who don’t know much about Python and
are trying to install a package.  If they get a big long traceback from deep
inside the guts of Distutils, they may think the package or the Python
installation is broken because they don’t read all the way down to the bottom
and see that it’s a permission problem.</p>
<p>On the other hand, this doesn’t help the developer to find the cause of the
failure. For this purpose, the <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">DISTUTILS_DEBUG</span></code> environment variable can be set
to anything except an empty string, and distutils will now print detailed
information about what it is doing, dump the full traceback when an exception
occurs, and print the whole command line when an external program (like a C
compiler) fails.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Writing the Setup Script</a><ul>
<li><a class="reference internal" href="#listing-whole-packages">2.1. Listing whole packages</a></li>
<li><a class="reference internal" href="#listing-individual-modules">2.2. Listing individual modules</a></li>
<li><a class="reference internal" href="#describing-extension-modules">2.3. Describing extension modules</a><ul>
<li><a class="reference internal" href="#extension-names-and-packages">2.3.1. Extension names and packages</a></li>
<li><a class="reference internal" href="#extension-source-files">2.3.2. Extension source files</a></li>
<li><a class="reference internal" href="#preprocessor-options">2.3.3. Preprocessor options</a></li>
<li><a class="reference internal" href="#library-options">2.3.4. Library options</a></li>
<li><a class="reference internal" href="#other-options">2.3.5. Other options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#relationships-between-distributions-and-packages">2.4. Relationships between Distributions and Packages</a></li>
<li><a class="reference internal" href="#installing-scripts">2.5. Installing Scripts</a></li>
<li><a class="reference internal" href="#installing-package-data">2.6. Installing Package Data</a></li>
<li><a class="reference internal" href="#installing-additional-files">2.7. Installing Additional Files</a></li>
<li><a class="reference internal" href="#additional-meta-data">2.8. Additional meta-data</a></li>
<li><a class="reference internal" href="#debugging-the-setup-script">2.9. Debugging the setup script</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="previous chapter">1. An Introduction to Distutils</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="configfile.html"
                        title="next chapter">3. Writing the Setup Configuration File</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/setupscript.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="configfile.html" title="3. Writing the Setup Configuration File"
             >next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. An Introduction to Distutils"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��]s]shtml/distutils/sourcedist.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. Creating a Source Distribution &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="5. Creating Built Distributions" href="builtdist.html" />
    <link rel="prev" title="3. Writing the Setup Configuration File" href="configfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/sourcedist.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="builtdist.html" title="5. Creating Built Distributions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="configfile.html" title="3. Writing the Setup Configuration File"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="creating-a-source-distribution">
<span id="source-dist"></span><h1>4. Creating a Source Distribution<a class="headerlink" href="#creating-a-source-distribution" title="Permalink to this headline">¶</a></h1>
<p>As shown in section <a class="reference internal" href="introduction.html#distutils-simple-example"><span class="std std-ref">A Simple Example</span></a>, you use the <strong class="command">sdist</strong> command
to create a source distribution.  In the simplest case,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span>
</pre></div>
</div>
<p>(assuming you haven’t specified any <strong class="command">sdist</strong> options in the setup script
or config file), <strong class="command">sdist</strong> creates the archive of the default format for
the current platform.  The default format is a gzip’ed tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.gz</span></code>) on Unix, and ZIP file on Windows.</p>
<p>You can specify as many formats as you like using the <code class="xref std std-option docutils literal notranslate"><span class="pre">--formats</span></code>
option, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span> <span class="o">--</span><span class="n">formats</span><span class="o">=</span><span class="n">gztar</span><span class="p">,</span><span class="nb">zip</span>
</pre></div>
</div>
<p>to create a gzipped tarball and a zip file.  The available formats are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="56%" />
<col width="20%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Description</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">zip</span></code></td>
<td>zip file (<code class="file docutils literal notranslate"><span class="pre">.zip</span></code>)</td>
<td>(1),(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">gztar</span></code></td>
<td>gzip’ed tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.gz</span></code>)</td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">bztar</span></code></td>
<td>bzip2’ed tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.bz2</span></code>)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ztar</span></code></td>
<td>compressed tar file
(<code class="file docutils literal notranslate"><span class="pre">.tar.Z</span></code>)</td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">tar</span></code></td>
<td>tar file (<code class="file docutils literal notranslate"><span class="pre">.tar</span></code>)</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>default on Windows</li>
<li>default on Unix</li>
<li>requires either external <strong class="program">zip</strong> utility or <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module (part
of the standard Python library since Python 1.6)</li>
<li>requires the <strong class="program">compress</strong> program.</li>
</ol>
<p>When using any <code class="docutils literal notranslate"><span class="pre">tar</span></code> format (<code class="docutils literal notranslate"><span class="pre">gztar</span></code>, <code class="docutils literal notranslate"><span class="pre">bztar</span></code>, <code class="docutils literal notranslate"><span class="pre">ztar</span></code> or
<code class="docutils literal notranslate"><span class="pre">tar</span></code>) under Unix, you can specify the <code class="docutils literal notranslate"><span class="pre">owner</span></code> and <code class="docutils literal notranslate"><span class="pre">group</span></code> names
that will be set for each member of the archive.</p>
<p>For example, if you want all files of the archive to be owned by root:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span> <span class="o">--</span><span class="n">owner</span><span class="o">=</span><span class="n">root</span> <span class="o">--</span><span class="n">group</span><span class="o">=</span><span class="n">root</span>
</pre></div>
</div>
<div class="section" id="specifying-the-files-to-distribute">
<span id="manifest"></span><h2>4.1. Specifying the files to distribute<a class="headerlink" href="#specifying-the-files-to-distribute" title="Permalink to this headline">¶</a></h2>
<p>If you don’t supply an explicit list of files (or instructions on how to
generate one), the <strong class="command">sdist</strong> command puts a minimal default set into the
source distribution:</p>
<ul class="simple">
<li>all Python source files implied by the <code class="docutils literal notranslate"><span class="pre">py_modules</span></code> and
<code class="docutils literal notranslate"><span class="pre">packages</span></code> options</li>
<li>all C source files mentioned in the <code class="docutils literal notranslate"><span class="pre">ext_modules</span></code> or
<code class="docutils literal notranslate"><span class="pre">libraries</span></code> options</li>
<li>scripts identified by the <code class="docutils literal notranslate"><span class="pre">scripts</span></code> option
See <a class="reference internal" href="setupscript.html#distutils-installing-scripts"><span class="std std-ref">Installing Scripts</span></a>.</li>
<li>anything that looks like a test script: <code class="file docutils literal notranslate"><span class="pre">test/test*.py</span></code> (currently, the
Distutils don’t do anything with test scripts except include them in source
distributions, but in the future there will be a standard for testing Python
module distributions)</li>
<li><code class="file docutils literal notranslate"><span class="pre">README.txt</span></code> (or <code class="file docutils literal notranslate"><span class="pre">README</span></code>), <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> (or whatever  you
called your setup script), and <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code></li>
<li>all files that matches the <code class="docutils literal notranslate"><span class="pre">package_data</span></code> metadata.
See <a class="reference internal" href="setupscript.html#distutils-installing-package-data"><span class="std std-ref">Installing Package Data</span></a>.</li>
<li>all files that matches the <code class="docutils literal notranslate"><span class="pre">data_files</span></code> metadata.
See <a class="reference internal" href="setupscript.html#distutils-additional-files"><span class="std std-ref">Installing Additional Files</span></a>.</li>
</ul>
<p>Sometimes this is enough, but usually you will want to specify additional files
to distribute.  The typical way to do this is to write a <em>manifest template</em>,
called <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> by default.  The manifest template is just a list of
instructions for how to generate your manifest file, <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code>, which is
the exact list of files to include in your source distribution.  The
<strong class="command">sdist</strong> command processes this template and generates a manifest based
on its instructions and what it finds in the filesystem.</p>
<p>If you prefer to roll your own manifest file, the format is simple: one filename
per line, regular files (or symlinks to them) only.  If you do supply your own
<code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code>, you must specify everything: the default set of files
described above does not apply in this case.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>An existing generated <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> will be regenerated without
<strong class="command">sdist</strong> comparing its modification time to the one of
<code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> or <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.1: </span><code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> files start with a comment indicating they are generated.
Files without this comment are not overwritten or removed.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.3: </span><strong class="command">sdist</strong> will read a <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> file if no <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code>
exists, like it did before 2.7.</p>
</div>
<p>See <a class="reference internal" href="#manifest-template"><span class="std std-ref">The MANIFEST.in template</span></a> section for a syntax reference.</p>
</div>
<div class="section" id="manifest-related-options">
<span id="manifest-options"></span><h2>4.2. Manifest-related options<a class="headerlink" href="#manifest-related-options" title="Permalink to this headline">¶</a></h2>
<p>The normal course of operations for the <strong class="command">sdist</strong> command is as follows:</p>
<ul class="simple">
<li>if the manifest file (<code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> by default) exists and the first line
does not have a comment indicating it is generated from <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code>,
then it is used as is, unaltered</li>
<li>if the manifest file doesn’t exist or has been previously automatically
generated, read <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> and create the manifest</li>
<li>if neither <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> nor <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> exist, create a manifest
with just the default file set</li>
<li>use the list of files now in <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> (either just generated or read
in) to create the source distribution archive(s)</li>
</ul>
<p>There are a couple of options that modify this behaviour.  First, use the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--no-defaults</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--no-prune</span></code> to disable the standard
“include” and “exclude” sets.</p>
<p>Second, you might just want to (re)generate the manifest, but not create a
source distribution:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">sdist</span> <span class="o">--</span><span class="n">manifest</span><span class="o">-</span><span class="n">only</span>
</pre></div>
</div>
<p><code class="xref std std-option docutils literal notranslate"><span class="pre">-o</span></code> is a shortcut for <code class="xref std std-option docutils literal notranslate"><span class="pre">--manifest-only</span></code>.</p>
</div>
<div class="section" id="the-manifest-in-template">
<span id="manifest-template"></span><h2>4.3. The MANIFEST.in template<a class="headerlink" href="#the-manifest-in-template" title="Permalink to this headline">¶</a></h2>
<p>A <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> file can be added in a project to define the list of
files to include in the distribution built by the <strong class="command">sdist</strong> command.</p>
<p>When <strong class="command">sdist</strong> is run, it will look for the <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> file
and interpret it to generate the <code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> file that contains the
list of files that will be included in the package.</p>
<p>This mechanism can be used when the default list of files is not enough.
(See <a class="reference internal" href="#manifest"><span class="std std-ref">Specifying the files to distribute</span></a>).</p>
<div class="section" id="principle">
<h3>4.3.1. Principle<a class="headerlink" href="#principle" title="Permalink to this headline">¶</a></h3>
<p>The manifest template has one command per line, where each command specifies a
set of files to include or exclude from the source distribution.  For an
example, let’s look at the Distutils’ own manifest template:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>include *.txt
recursive-include examples *.txt *.py
prune examples/sample?/build
</pre></div>
</div>
<p>The meanings should be fairly clear: include all files in the distribution root
matching <code class="file docutils literal notranslate"><span class="pre">*.txt</span></code>, all files anywhere under the <code class="file docutils literal notranslate"><span class="pre">examples</span></code> directory
matching <code class="file docutils literal notranslate"><span class="pre">*.txt</span></code> or <code class="file docutils literal notranslate"><span class="pre">*.py</span></code>, and exclude all directories matching
<code class="file docutils literal notranslate"><span class="pre">examples/sample?/build</span></code>.  All of this is done <em>after</em> the standard
include set, so you can exclude files from the standard set with explicit
instructions in the manifest template.  (Or, you can use the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--no-defaults</span></code> option to disable the standard set entirely.)</p>
<p>The order of commands in the manifest template matters: initially, we have the
list of default files as described above, and each command in the template adds
to or removes from that list of files.  Once we have fully processed the
manifest template, we remove files that should not be included in the source
distribution:</p>
<ul class="simple">
<li>all files in the Distutils “build” tree (default <code class="file docutils literal notranslate"><span class="pre">build/</span></code>)</li>
<li>all files in directories named <code class="file docutils literal notranslate"><span class="pre">RCS</span></code>, <code class="file docutils literal notranslate"><span class="pre">CVS</span></code>, <code class="file docutils literal notranslate"><span class="pre">.svn</span></code>,
<code class="file docutils literal notranslate"><span class="pre">.hg</span></code>, <code class="file docutils literal notranslate"><span class="pre">.git</span></code>, <code class="file docutils literal notranslate"><span class="pre">.bzr</span></code> or <code class="file docutils literal notranslate"><span class="pre">_darcs</span></code></li>
</ul>
<p>Now we have our complete list of files, which is written to the manifest for
future reference, and then used to build the source distribution archive(s).</p>
<p>You can disable the default set of included files with the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--no-defaults</span></code> option, and you can disable the standard exclude set
with <code class="xref std std-option docutils literal notranslate"><span class="pre">--no-prune</span></code>.</p>
<p>Following the Distutils’ own manifest template, let’s trace how the
<strong class="command">sdist</strong> command builds the list of files to include in the Distutils
source distribution:</p>
<ol class="arabic simple">
<li>include all Python source files in the <code class="file docutils literal notranslate"><span class="pre">distutils</span></code> and
<code class="file docutils literal notranslate"><span class="pre">distutils/command</span></code> subdirectories (because packages corresponding to
those two directories were mentioned in the <code class="docutils literal notranslate"><span class="pre">packages</span></code> option in the
setup script—see section <a class="reference internal" href="setupscript.html#setup-script"><span class="std std-ref">Writing the Setup Script</span></a>)</li>
<li>include <code class="file docutils literal notranslate"><span class="pre">README.txt</span></code>, <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, and <code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code> (standard
files)</li>
<li>include <code class="file docutils literal notranslate"><span class="pre">test/test*.py</span></code> (standard files)</li>
<li>include <code class="file docutils literal notranslate"><span class="pre">*.txt</span></code> in the distribution root (this will find
<code class="file docutils literal notranslate"><span class="pre">README.txt</span></code> a second time, but such redundancies are weeded out later)</li>
<li>include anything matching <code class="file docutils literal notranslate"><span class="pre">*.txt</span></code> or <code class="file docutils literal notranslate"><span class="pre">*.py</span></code> in the sub-tree
under <code class="file docutils literal notranslate"><span class="pre">examples</span></code>,</li>
<li>exclude all files in the sub-trees starting at directories matching
<code class="file docutils literal notranslate"><span class="pre">examples/sample?/build</span></code>—this may exclude files included by the
previous two steps, so it’s important that the <code class="docutils literal notranslate"><span class="pre">prune</span></code> command in the manifest
template comes after the <code class="docutils literal notranslate"><span class="pre">recursive-include</span></code> command</li>
<li>exclude the entire <code class="file docutils literal notranslate"><span class="pre">build</span></code> tree, and any <code class="file docutils literal notranslate"><span class="pre">RCS</span></code>, <code class="file docutils literal notranslate"><span class="pre">CVS</span></code>,
<code class="file docutils literal notranslate"><span class="pre">.svn</span></code>, <code class="file docutils literal notranslate"><span class="pre">.hg</span></code>, <code class="file docutils literal notranslate"><span class="pre">.git</span></code>, <code class="file docutils literal notranslate"><span class="pre">.bzr</span></code> and <code class="file docutils literal notranslate"><span class="pre">_darcs</span></code>
directories</li>
</ol>
<p>Just like in the setup script, file and directory names in the manifest template
should always be slash-separated; the Distutils will take care of converting
them to the standard representation on your platform. That way, the manifest
template is portable across operating systems.</p>
</div>
<div class="section" id="commands">
<h3>4.3.2. Commands<a class="headerlink" href="#commands" title="Permalink to this headline">¶</a></h3>
<p>The manifest template commands are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Command</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><strong class="command">include pat1 pat2 ...</strong></td>
<td>include all files matching any of the listed
patterns</td>
</tr>
<tr class="row-odd"><td><strong class="command">exclude pat1 pat2 ...</strong></td>
<td>exclude all files matching any of the listed
patterns</td>
</tr>
<tr class="row-even"><td><strong class="command">recursive-include dir pat1 pat2
...</strong></td>
<td>include all files under <em>dir</em> matching any of
the listed patterns</td>
</tr>
<tr class="row-odd"><td><strong class="command">recursive-exclude dir pat1 pat2
...</strong></td>
<td>exclude all files under <em>dir</em> matching any of
the listed patterns</td>
</tr>
<tr class="row-even"><td><strong class="command">global-include pat1 pat2 ...</strong></td>
<td>include all files anywhere in the source tree
matching — &amp; any of the listed patterns</td>
</tr>
<tr class="row-odd"><td><strong class="command">global-exclude pat1 pat2 ...</strong></td>
<td>exclude all files anywhere in the source tree
matching — &amp; any of the listed patterns</td>
</tr>
<tr class="row-even"><td><strong class="command">prune dir</strong></td>
<td>exclude all files under <em>dir</em></td>
</tr>
<tr class="row-odd"><td><strong class="command">graft dir</strong></td>
<td>include all files under <em>dir</em></td>
</tr>
</tbody>
</table>
<p>The patterns here are Unix-style “glob” patterns: <code class="docutils literal notranslate"><span class="pre">*</span></code> matches any sequence of
regular filename characters, <code class="docutils literal notranslate"><span class="pre">?</span></code> matches any single regular filename
character, and <code class="docutils literal notranslate"><span class="pre">[range]</span></code> matches any of the characters in <em>range</em> (e.g.,
<code class="docutils literal notranslate"><span class="pre">a-z</span></code>, <code class="docutils literal notranslate"><span class="pre">a-zA-Z</span></code>, <code class="docutils literal notranslate"><span class="pre">a-f0-9_.</span></code>).  The definition of “regular filename
character” is platform-specific: on Unix it is anything except slash; on Windows
anything except backslash or colon.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Creating a Source Distribution</a><ul>
<li><a class="reference internal" href="#specifying-the-files-to-distribute">4.1. Specifying the files to distribute</a></li>
<li><a class="reference internal" href="#manifest-related-options">4.2. Manifest-related options</a></li>
<li><a class="reference internal" href="#the-manifest-in-template">4.3. The MANIFEST.in template</a><ul>
<li><a class="reference internal" href="#principle">4.3.1. Principle</a></li>
<li><a class="reference internal" href="#commands">4.3.2. Commands</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="configfile.html"
                        title="previous chapter">3. Writing the Setup Configuration File</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="builtdist.html"
                        title="next chapter">5. Creating Built Distributions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/sourcedist.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="builtdist.html" title="5. Creating Built Distributions"
             >next</a> |</li>
        <li class="right" >
          <a href="configfile.html" title="3. Writing the Setup Configuration File"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Distributing Python Modules (Legacy version)</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�r��html/distutils/uploading.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Uploading Packages to the Package Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/distutils/uploading.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="uploading-packages-to-the-package-index">
<h1>Uploading Packages to the Package Index<a class="headerlink" href="#uploading-packages-to-the-package-index" title="Permalink to this headline">¶</a></h1>
<p>The contents of this page have moved to the section <a class="reference internal" href="packageindex.html#package-index"><span class="std std-ref">The Python Package Index (PyPI)</span></a>.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/distutils/uploading.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\j�$KNKNhtml/extending/building.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>3. Building C and C++ Extensions with distutils &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. Building C and C++ Extensions on Windows" href="windows.html" />
    <link rel="prev" title="2. Defining New Types" href="newtypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/building.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="4. Building C and C++ Extensions on Windows"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="newtypes.html" title="2. Defining New Types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="building-c-and-c-extensions-with-distutils">
<span id="building"></span><h1>3. Building C and C++ Extensions with distutils<a class="headerlink" href="#building-c-and-c-extensions-with-distutils" title="Permalink to this headline">¶</a></h1>
<p>Starting in Python 1.4, Python provides, on Unix, a special make file for
building make files for building dynamically-linked extensions and custom
interpreters.  Starting with Python 2.0, this mechanism (known as related to
Makefile.pre.in, and Setup files) is no longer supported. Building custom
interpreters was rarely used, and extension modules can be built using
distutils.</p>
<p>Building an extension module using distutils requires that distutils is
installed on the build machine, which is included in Python 2.x and available
separately for Python 1.5. Since distutils also supports creation of binary
packages, users don’t necessarily need a compiler and distutils to install the
extension.</p>
<p>A distutils package contains a driver script, <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>. This is a plain
Python file, which, in the most simple case, could look like this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="kn">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>

<span class="n">module1</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;demo&#39;</span><span class="p">,</span>
                    <span class="n">sources</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;demo.c&#39;</span><span class="p">])</span>

<span class="n">setup</span> <span class="p">(</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;PackageName&#39;</span><span class="p">,</span>
       <span class="n">version</span> <span class="o">=</span> <span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
       <span class="n">description</span> <span class="o">=</span> <span class="s1">&#39;This is a demo package&#39;</span><span class="p">,</span>
       <span class="n">ext_modules</span> <span class="o">=</span> <span class="p">[</span><span class="n">module1</span><span class="p">])</span>
</pre></div>
</div>
<p>With this <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, and a file <code class="file docutils literal notranslate"><span class="pre">demo.c</span></code>, running</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">build</span>
</pre></div>
</div>
<p>will compile <code class="file docutils literal notranslate"><span class="pre">demo.c</span></code>, and produce an extension module named <code class="docutils literal notranslate"><span class="pre">demo</span></code> in
the <code class="file docutils literal notranslate"><span class="pre">build</span></code> directory. Depending on the system, the module file will end
up in a subdirectory <code class="file docutils literal notranslate"><span class="pre">build/lib.system</span></code>, and may have a name like
<code class="file docutils literal notranslate"><span class="pre">demo.so</span></code> or <code class="file docutils literal notranslate"><span class="pre">demo.pyd</span></code>.</p>
<p>In the <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, all execution is performed by calling the <code class="docutils literal notranslate"><span class="pre">setup</span></code>
function. This takes a variable number of keyword arguments, of which the
example above uses only a subset. Specifically, the example specifies
meta-information to build packages, and it specifies the contents of the
package.  Normally, a package will contain of addition modules, like Python
source modules, documentation, subpackages, etc. Please refer to the distutils
documentation in <a class="reference internal" href="../distutils/index.html#distutils-index"><span class="std std-ref">Distributing Python Modules (Legacy version)</span></a> to learn more about the features of
distutils; this section explains building extension modules only.</p>
<p>It is common to pre-compute arguments to <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>, to better structure the
driver script. In the example above, the <code class="docutils literal notranslate"><span class="pre">ext_modules</span></code> argument to
<code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> is a list of extension modules, each of which is an instance of
the <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code>. In the example, the instance
defines an extension named <code class="docutils literal notranslate"><span class="pre">demo</span></code> which is build by compiling a single source
file, <code class="file docutils literal notranslate"><span class="pre">demo.c</span></code>.</p>
<p>In many cases, building an extension is more complex, since additional
preprocessor defines and libraries may be needed. This is demonstrated in the
example below.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="kn">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>

<span class="n">module1</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;demo&#39;</span><span class="p">,</span>
                    <span class="n">define_macros</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;MAJOR_VERSION&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">),</span>
                                     <span class="p">(</span><span class="s1">&#39;MINOR_VERSION&#39;</span><span class="p">,</span> <span class="s1">&#39;0&#39;</span><span class="p">)],</span>
                    <span class="n">include_dirs</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;/usr/local/include&#39;</span><span class="p">],</span>
                    <span class="n">libraries</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;tcl83&#39;</span><span class="p">],</span>
                    <span class="n">library_dirs</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;/usr/local/lib&#39;</span><span class="p">],</span>
                    <span class="n">sources</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;demo.c&#39;</span><span class="p">])</span>

<span class="n">setup</span> <span class="p">(</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;PackageName&#39;</span><span class="p">,</span>
       <span class="n">version</span> <span class="o">=</span> <span class="s1">&#39;1.0&#39;</span><span class="p">,</span>
       <span class="n">description</span> <span class="o">=</span> <span class="s1">&#39;This is a demo package&#39;</span><span class="p">,</span>
       <span class="n">author</span> <span class="o">=</span> <span class="s1">&#39;Martin v. Loewis&#39;</span><span class="p">,</span>
       <span class="n">author_email</span> <span class="o">=</span> <span class="s1">&#39;martin@v.loewis.de&#39;</span><span class="p">,</span>
       <span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;https://docs.python.org/extending/building&#39;</span><span class="p">,</span>
       <span class="n">long_description</span> <span class="o">=</span> <span class="s1">&#39;&#39;&#39;</span>
<span class="s1">This is really just a demo package.</span>
<span class="s1">&#39;&#39;&#39;</span><span class="p">,</span>
       <span class="n">ext_modules</span> <span class="o">=</span> <span class="p">[</span><span class="n">module1</span><span class="p">])</span>
</pre></div>
</div>
<p>In this example, <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> is called with additional meta-information, which
is recommended when distribution packages have to be built. For the extension
itself, it specifies preprocessor defines, include directories, library
directories, and libraries. Depending on the compiler, distutils passes this
information in different ways to the compiler. For example, on Unix, this may
result in the compilation commands</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">gcc</span> <span class="o">-</span><span class="n">DNDEBUG</span> <span class="o">-</span><span class="n">g</span> <span class="o">-</span><span class="n">O3</span> <span class="o">-</span><span class="n">Wall</span> <span class="o">-</span><span class="n">Wstrict</span><span class="o">-</span><span class="n">prototypes</span> <span class="o">-</span><span class="n">fPIC</span> <span class="o">-</span><span class="n">DMAJOR_VERSION</span><span class="o">=</span><span class="mi">1</span> <span class="o">-</span><span class="n">DMINOR_VERSION</span><span class="o">=</span><span class="mi">0</span> <span class="o">-</span><span class="n">I</span><span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">local</span><span class="o">/</span><span class="n">include</span> <span class="o">-</span><span class="n">I</span><span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">local</span><span class="o">/</span><span class="n">include</span><span class="o">/</span><span class="n">python2</span><span class="mf">.2</span> <span class="o">-</span><span class="n">c</span> <span class="n">demo</span><span class="p">.</span><span class="n">c</span> <span class="o">-</span><span class="n">o</span> <span class="n">build</span><span class="o">/</span><span class="n">temp</span><span class="p">.</span><span class="n">linux</span><span class="o">-</span><span class="n">i686</span><span class="o">-</span><span class="mf">2.2</span><span class="o">/</span><span class="n">demo</span><span class="p">.</span><span class="n">o</span>

<span class="n">gcc</span> <span class="o">-</span><span class="n">shared</span> <span class="n">build</span><span class="o">/</span><span class="n">temp</span><span class="p">.</span><span class="n">linux</span><span class="o">-</span><span class="n">i686</span><span class="o">-</span><span class="mf">2.2</span><span class="o">/</span><span class="n">demo</span><span class="p">.</span><span class="n">o</span> <span class="o">-</span><span class="n">L</span><span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">local</span><span class="o">/</span><span class="n">lib</span> <span class="o">-</span><span class="n">ltcl83</span> <span class="o">-</span><span class="n">o</span> <span class="n">build</span><span class="o">/</span><span class="n">lib</span><span class="p">.</span><span class="n">linux</span><span class="o">-</span><span class="n">i686</span><span class="o">-</span><span class="mf">2.2</span><span class="o">/</span><span class="n">demo</span><span class="p">.</span><span class="n">so</span>
</pre></div>
</div>
<p>These lines are for demonstration purposes only; distutils users should trust
that distutils gets the invocations right.</p>
<div class="section" id="distributing-your-extension-modules">
<span id="distributing"></span><h2>3.1. Distributing your extension modules<a class="headerlink" href="#distributing-your-extension-modules" title="Permalink to this headline">¶</a></h2>
<p>When an extension has been successfully build, there are three ways to use it.</p>
<p>End-users will typically want to install the module, they do so by running</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">install</span>
</pre></div>
</div>
<p>Module maintainers should produce source packages; to do so, they run</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">sdist</span>
</pre></div>
</div>
<p>In some cases, additional files need to be included in a source distribution;
this is done through a <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> file; see the distutils documentation
for details.</p>
<p>If the source distribution has been build successfully, maintainers can also
create binary distributions. Depending on the platform, one of the following
commands can be used to do so.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">bdist_wininst</span>
<span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">bdist_rpm</span>
<span class="n">python</span> <span class="n">setup</span><span class="p">.</span><span class="n">py</span> <span class="n">bdist_dumb</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. Building C and C++ Extensions with distutils</a><ul>
<li><a class="reference internal" href="#distributing-your-extension-modules">3.1. Distributing your extension modules</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="newtypes.html"
                        title="previous chapter">2. Defining New Types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="windows.html"
                        title="next chapter">4. Building C and C++ Extensions on Windows</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/building.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="4. Building C and C++ Extensions on Windows"
             >next</a> |</li>
        <li class="right" >
          <a href="newtypes.html" title="2. Defining New Types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��D<�<�html/extending/embedding.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>5. Embedding Python in Another Application &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python/C API Reference Manual" href="../c-api/index.html" />
    <link rel="prev" title="4. Building C and C++ Extensions on Windows" href="windows.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/embedding.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../c-api/index.html" title="Python/C API Reference Manual"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="4. Building C and C++ Extensions on Windows"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="embedding-python-in-another-application">
<span id="embedding"></span><h1>5. Embedding Python in Another Application<a class="headerlink" href="#embedding-python-in-another-application" title="Permalink to this headline">¶</a></h1>
<p>The previous chapters discussed how to extend Python, that is, how to extend the
functionality of Python by attaching a library of C functions to it.  It is also
possible to do it the other way around: enrich your C/C++ application by
embedding Python in it.  Embedding provides your application with the ability to
implement some of the functionality of your application in Python rather than C
or C++. This can be used for many purposes; one example would be to allow users
to tailor the application to their needs by writing some scripts in Python.  You
can also use it yourself if some of the functionality can be written in Python
more easily.</p>
<p>Embedding Python is similar to extending it, but not quite.  The difference is
that when you extend Python, the main program of the application is still the
Python interpreter, while if you embed Python, the main program may have nothing
to do with Python — instead, some parts of the application occasionally call
the Python interpreter to run some Python code.</p>
<p>So if you are embedding Python, you are providing your own main program.  One of
the things this main program has to do is initialize the Python interpreter.  At
the very least, you have to call the function <a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>.  There are
optional calls to pass command line arguments to Python.  Then later you can
call the interpreter from any part of the application.</p>
<p>There are several different ways to call the interpreter: you can pass a string
containing Python statements to <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleString()</span></code></a>, or you can pass a
stdio file pointer and a file name (for identification in error messages only)
to <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleFile" title="PyRun_SimpleFile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFile()</span></code></a>.  You can also call the lower-level operations
described in the previous chapters to construct and use Python objects.</p>
<p>A simple demo of embedding Python can be found in the directory
<code class="file docutils literal notranslate"><span class="pre">Demo/embed/</span></code> of the source distribution.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a></dt>
<dd>The details of Python’s C interface are given in this manual. A great deal of
necessary information can be found here.</dd>
</dl>
</div>
<div class="section" id="very-high-level-embedding">
<span id="high-level-embedding"></span><h2>5.1. Very High Level Embedding<a class="headerlink" href="#very-high-level-embedding" title="Permalink to this headline">¶</a></h2>
<p>The simplest form of embedding Python is the use of the very high level
interface. This interface is intended to execute a Python script without needing
to interact with the application directly. This can for example be used to
perform some operation on a file.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>

<span class="kt">int</span>
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
<span class="p">{</span>
  <span class="n">Py_SetProgramName</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span>  <span class="cm">/* optional but recommended */</span>
  <span class="n">Py_Initialize</span><span class="p">();</span>
  <span class="n">PyRun_SimpleString</span><span class="p">(</span><span class="s">&quot;from time import time,ctime</span><span class="se">\n</span><span class="s">&quot;</span>
                     <span class="s">&quot;print &#39;Today is&#39;,ctime(time())</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
  <span class="n">Py_Finalize</span><span class="p">();</span>
  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../c-api/init.html#c.Py_SetProgramName" title="Py_SetProgramName"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_SetProgramName()</span></code></a> function should be called before
<a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a> to inform the interpreter about paths to Python run-time
libraries.  Next, the Python interpreter is initialized with
<a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>, followed by the execution of a hard-coded Python script
that prints the date and time.  Afterwards, the <a class="reference internal" href="../c-api/init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> call shuts
the interpreter down, followed by the end of the program.  In a real program,
you may want to get the Python script from another source, perhaps a text-editor
routine, a file, or a database.  Getting the Python code from a file can better
be done by using the <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleFile" title="PyRun_SimpleFile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleFile()</span></code></a> function, which saves you the
trouble of allocating memory space and loading the file contents.</p>
</div>
<div class="section" id="beyond-very-high-level-embedding-an-overview">
<span id="lower-level-embedding"></span><h2>5.2. Beyond Very High Level Embedding: An overview<a class="headerlink" href="#beyond-very-high-level-embedding-an-overview" title="Permalink to this headline">¶</a></h2>
<p>The high level interface gives you the ability to execute arbitrary pieces of
Python code from your application, but exchanging data values is quite
cumbersome to say the least. If you want that, you should use lower level calls.
At the cost of having to write more C code, you can achieve almost anything.</p>
<p>It should be noted that extending Python and embedding Python is quite the same
activity, despite the different intent. Most topics discussed in the previous
chapters are still valid. To show this, consider what the extension code from
Python to C really does:</p>
<ol class="arabic simple">
<li>Convert data values from Python to C,</li>
<li>Perform a function call to a C routine using the converted values, and</li>
<li>Convert the data values from the call from C to Python.</li>
</ol>
<p>When embedding Python, the interface code does:</p>
<ol class="arabic simple">
<li>Convert data values from C to Python,</li>
<li>Perform a function call to a Python interface routine using the converted
values, and</li>
<li>Convert the data values from the call from Python to C.</li>
</ol>
<p>As you can see, the data conversion steps are simply swapped to accommodate the
different direction of the cross-language transfer. The only difference is the
routine that you call between both data conversions. When extending, you call a
C routine, when embedding, you call a Python routine.</p>
<p>This chapter will not discuss how to convert data from Python to C and vice
versa.  Also, proper use of references and dealing with errors is assumed to be
understood.  Since these aspects do not differ from extending the interpreter,
you can refer to earlier chapters for the required information.</p>
</div>
<div class="section" id="pure-embedding">
<span id="id1"></span><h2>5.3. Pure Embedding<a class="headerlink" href="#pure-embedding" title="Permalink to this headline">¶</a></h2>
<p>The first program aims to execute a function in a Python script. Like in the
section about the very high level interface, the Python interpreter does not
directly interact with the application (but that will change in the next
section).</p>
<p>The code to run a function defined in a Python script is:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>

<span class="kt">int</span>
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">pName</span><span class="p">,</span> <span class="o">*</span><span class="n">pModule</span><span class="p">,</span> <span class="o">*</span><span class="n">pFunc</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">pArgs</span><span class="p">,</span> <span class="o">*</span><span class="n">pValue</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">i</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">argc</span> <span class="o">&lt;</span> <span class="mi">3</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="s">&quot;Usage: call pythonfile funcname [args]</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">Py_Initialize</span><span class="p">();</span>
    <span class="n">pName</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
    <span class="cm">/* Error checking of pName left out */</span>

    <span class="n">pModule</span> <span class="o">=</span> <span class="n">PyImport_Import</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">pModule</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">pFunc</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">pModule</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
        <span class="cm">/* pFunc is a new reference */</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">pFunc</span> <span class="o">&amp;&amp;</span> <span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">pFunc</span><span class="p">))</span> <span class="p">{</span>
            <span class="n">pArgs</span> <span class="o">=</span> <span class="n">PyTuple_New</span><span class="p">(</span><span class="n">argc</span> <span class="o">-</span> <span class="mi">3</span><span class="p">);</span>
            <span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">argc</span> <span class="o">-</span> <span class="mi">3</span><span class="p">;</span> <span class="o">++</span><span class="n">i</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">pValue</span> <span class="o">=</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="n">atoi</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="mi">3</span><span class="p">]));</span>
                <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">pValue</span><span class="p">)</span> <span class="p">{</span>
                    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pArgs</span><span class="p">);</span>
                    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
                    <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Cannot convert argument</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
                    <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="cm">/* pValue reference stolen here: */</span>
                <span class="n">PyTuple_SetItem</span><span class="p">(</span><span class="n">pArgs</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">pValue</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="n">pValue</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">pFunc</span><span class="p">,</span> <span class="n">pArgs</span><span class="p">);</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pArgs</span><span class="p">);</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">pValue</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">printf</span><span class="p">(</span><span class="s">&quot;Result of call: %ld</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">PyInt_AsLong</span><span class="p">(</span><span class="n">pValue</span><span class="p">));</span>
                <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pValue</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">else</span> <span class="p">{</span>
                <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
                <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
                <span class="n">PyErr_Print</span><span class="p">();</span>
                <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span><span class="s">&quot;Call failed</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">);</span>
                <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">}</span>
        <span class="k">else</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">PyErr_Occurred</span><span class="p">())</span>
                <span class="n">PyErr_Print</span><span class="p">();</span>
            <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Cannot find function </span><span class="se">\&quot;</span><span class="s">%s</span><span class="se">\&quot;\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
        <span class="p">}</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">pModule</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span> <span class="p">{</span>
        <span class="n">PyErr_Print</span><span class="p">();</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">stderr</span><span class="p">,</span> <span class="s">&quot;Failed to load </span><span class="se">\&quot;</span><span class="s">%s</span><span class="se">\&quot;\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
        <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">Py_Finalize</span><span class="p">();</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This code loads a Python script using <code class="docutils literal notranslate"><span class="pre">argv[1]</span></code>, and calls the function named
in <code class="docutils literal notranslate"><span class="pre">argv[2]</span></code>.  Its integer arguments are the other values of the <code class="docutils literal notranslate"><span class="pre">argv</span></code>
array.  If you compile and link this program (let’s call the finished executable
<strong class="program">call</strong>), and use it to execute a Python script, such as:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">multiply</span><span class="p">(</span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">):</span>
    <span class="k">print</span> <span class="s2">&quot;Will compute&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="s2">&quot;times&quot;</span><span class="p">,</span> <span class="n">b</span>
    <span class="n">c</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">):</span>
        <span class="n">c</span> <span class="o">=</span> <span class="n">c</span> <span class="o">+</span> <span class="n">b</span>
    <span class="k">return</span> <span class="n">c</span>
</pre></div>
</div>
<p>then the result should be:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> call multiply multiply <span class="m">3</span> <span class="m">2</span>
<span class="go">Will compute 3 times 2</span>
<span class="go">Result of call: 6</span>
</pre></div>
</div>
<p>Although the program is quite large for its functionality, most of the code is
for data conversion between Python and C, and for error reporting.  The
interesting part with respect to embedding Python starts with</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_Initialize</span><span class="p">();</span>
<span class="n">pName</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]);</span>
<span class="cm">/* Error checking of pName left out */</span>
<span class="n">pModule</span> <span class="o">=</span> <span class="n">PyImport_Import</span><span class="p">(</span><span class="n">pName</span><span class="p">);</span>
</pre></div>
</div>
<p>After initializing the interpreter, the script is loaded using
<a class="reference internal" href="../c-api/import.html#c.PyImport_Import" title="PyImport_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_Import()</span></code></a>.  This routine needs a Python string as its argument,
which is constructed using the <a class="reference internal" href="../c-api/string.html#c.PyString_FromString" title="PyString_FromString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_FromString()</span></code></a> data conversion
routine.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">pFunc</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">pModule</span><span class="p">,</span> <span class="n">argv</span><span class="p">[</span><span class="mi">2</span><span class="p">]);</span>
<span class="cm">/* pFunc is a new reference */</span>

<span class="k">if</span> <span class="p">(</span><span class="n">pFunc</span> <span class="o">&amp;&amp;</span> <span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">pFunc</span><span class="p">))</span> <span class="p">{</span>
    <span class="p">...</span>
<span class="p">}</span>
<span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">pFunc</span><span class="p">);</span>
</pre></div>
</div>
<p>Once the script is loaded, the name we’re looking for is retrieved using
<a class="reference internal" href="../c-api/object.html#c.PyObject_GetAttrString" title="PyObject_GetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetAttrString()</span></code></a>.  If the name exists, and the object returned is
callable, you can safely assume that it is a function.  The program then
proceeds by constructing a tuple of arguments as normal.  The call to the Python
function is then made with:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">pValue</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">pFunc</span><span class="p">,</span> <span class="n">pArgs</span><span class="p">);</span>
</pre></div>
</div>
<p>Upon return of the function, <code class="docutils literal notranslate"><span class="pre">pValue</span></code> is either <em>NULL</em> or it contains a
reference to the return value of the function.  Be sure to release the reference
after examining the value.</p>
</div>
<div class="section" id="extending-embedded-python">
<span id="extending-with-embedding"></span><h2>5.4. Extending Embedded Python<a class="headerlink" href="#extending-embedded-python" title="Permalink to this headline">¶</a></h2>
<p>Until now, the embedded Python interpreter had no access to functionality from
the application itself.  The Python API allows this by extending the embedded
interpreter.  That is, the embedded interpreter gets extended with routines
provided by the application. While it sounds complex, it is not so bad.  Simply
forget for a while that the application starts the Python interpreter.  Instead,
consider the application to be a set of subroutines, and write some glue code
that gives Python access to those routines, just like you would write a normal
Python extension.  For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span> <span class="n">numargs</span><span class="o">=</span><span class="mi">0</span><span class="p">;</span>

<span class="cm">/* Return the number of arguments of the application command line */</span>
<span class="k">static</span> <span class="n">PyObject</span><span class="o">*</span>
<span class="nf">emb_numargs</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;:numargs&quot;</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;i&quot;</span><span class="p">,</span> <span class="n">numargs</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">EmbMethods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;numargs&quot;</span><span class="p">,</span> <span class="n">emb_numargs</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the number of arguments received by the process.&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>
<span class="p">};</span>
</pre></div>
</div>
<p>Insert the above code just above the <code class="xref c c-func docutils literal notranslate"><span class="pre">main()</span></code> function. Also, insert the
following two statements directly after <a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">numargs</span> <span class="o">=</span> <span class="n">argc</span><span class="p">;</span>
<span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;emb&quot;</span><span class="p">,</span> <span class="n">EmbMethods</span><span class="p">);</span>
</pre></div>
</div>
<p>These two lines initialize the <code class="docutils literal notranslate"><span class="pre">numargs</span></code> variable, and make the
<code class="xref py py-func docutils literal notranslate"><span class="pre">emb.numargs()</span></code> function accessible to the embedded Python interpreter.
With these extensions, the Python script can do things like</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">emb</span>
<span class="k">print</span> <span class="s2">&quot;Number of arguments&quot;</span><span class="p">,</span> <span class="n">emb</span><span class="o">.</span><span class="n">numargs</span><span class="p">()</span>
</pre></div>
</div>
<p>In a real application, the methods will expose an API of the application to
Python.</p>
</div>
<div class="section" id="embedding-python-in-c">
<span id="embeddingincplusplus"></span><h2>5.5. Embedding Python in C++<a class="headerlink" href="#embedding-python-in-c" title="Permalink to this headline">¶</a></h2>
<p>It is also possible to embed Python in a C++ program; precisely how this is done
will depend on the details of the C++ system used; in general you will need to
write the main program in C++, and use the C++ compiler to compile and link your
program.  There is no need to recompile Python itself using C++.</p>
</div>
<div class="section" id="compiling-and-linking-under-unix-like-systems">
<span id="link-reqs"></span><h2>5.6. Compiling and Linking under Unix-like systems<a class="headerlink" href="#compiling-and-linking-under-unix-like-systems" title="Permalink to this headline">¶</a></h2>
<p>It is not necessarily trivial to find the right flags to pass to your
compiler (and linker) in order to embed the Python interpreter into your
application, particularly because Python needs to load library modules
implemented as C dynamic extensions (<code class="file docutils literal notranslate"><span class="pre">.so</span></code> files) linked against
it.</p>
<p>To find out the required compiler and linker flags, you can execute the
<code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">X.Y</span></em><span class="pre">-config</span></code> script which is generated as part of the
installation process (a <code class="file docutils literal notranslate"><span class="pre">python-config</span></code> script may also be
available).  This script has several options, of which the following will
be directly useful to you:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">pythonX.Y-config</span> <span class="pre">--cflags</span></code> will give you the recommended flags when
compiling:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> /opt/bin/python2.7-config --cflags
<span class="go">-I/opt/include/python2.7 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">pythonX.Y-config</span> <span class="pre">--ldflags</span></code> will give you the recommended flags when
linking:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> /opt/bin/python2.7-config --ldflags
<span class="go">-L/opt/lib/python2.7/config -lpthread -ldl -lutil -lm -lpython2.7 -Xlinker -export-dynamic</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To avoid confusion between several Python installations (and especially
between the system Python and your own compiled Python), it is recommended
that you use the absolute path to <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">X.Y</span></em><span class="pre">-config</span></code>, as in the above
example.</p>
</div>
<p>If this procedure doesn’t work for you (it is not guaranteed to work for
all Unix-like platforms; however, we welcome <a class="reference internal" href="../bugs.html#reporting-bugs"><span class="std std-ref">bug reports</span></a>)
you will have to read your system’s documentation about dynamic linking and/or
examine Python’s <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> (use <a class="reference internal" href="../library/sysconfig.html#sysconfig.get_makefile_filename" title="sysconfig.get_makefile_filename"><code class="xref py py-func docutils literal notranslate"><span class="pre">sysconfig.get_makefile_filename()</span></code></a>
to find its location) and compilation
options.  In this case, the <a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> module is a useful tool to
programmatically extract the configuration values that you will want to
combine together.  For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sysconfig</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">&#39;LIBS&#39;</span><span class="p">)</span>
<span class="go">&#39;-lpthread -ldl  -lutil&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">&#39;LINKFORSHARED&#39;</span><span class="p">)</span>
<span class="go">&#39;-Xlinker -export-dynamic&#39;</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">5. Embedding Python in Another Application</a><ul>
<li><a class="reference internal" href="#very-high-level-embedding">5.1. Very High Level Embedding</a></li>
<li><a class="reference internal" href="#beyond-very-high-level-embedding-an-overview">5.2. Beyond Very High Level Embedding: An overview</a></li>
<li><a class="reference internal" href="#pure-embedding">5.3. Pure Embedding</a></li>
<li><a class="reference internal" href="#extending-embedded-python">5.4. Extending Embedded Python</a></li>
<li><a class="reference internal" href="#embedding-python-in-c">5.5. Embedding Python in C++</a></li>
<li><a class="reference internal" href="#compiling-and-linking-under-unix-like-systems">5.6. Compiling and Linking under Unix-like systems</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="windows.html"
                        title="previous chapter">4. Building C and C++ Extensions on Windows</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../c-api/index.html"
                        title="next chapter">Python/C API Reference Manual</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/embedding.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../c-api/index.html" title="Python/C API Reference Manual"
             >next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="4. Building C and C++ Extensions on Windows"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�6�html/extending/extending.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. Extending Python with C or C++ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Defining New Types" href="newtypes.html" />
    <link rel="prev" title="Extending and Embedding the Python Interpreter" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/extending.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="newtypes.html" title="2. Defining New Types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Extending and Embedding the Python Interpreter"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="extending-python-with-c-or-c">
<span id="extending-intro"></span><h1>1. Extending Python with C or C++<a class="headerlink" href="#extending-python-with-c-or-c" title="Permalink to this headline">¶</a></h1>
<p>It is quite easy to add new built-in modules to Python, if you know how to
program in C.  Such <em class="dfn">extension modules</em> can do two things that can’t be
done directly in Python: they can implement new built-in object types, and they
can call C library functions and system calls.</p>
<p>To support extensions, the Python API (Application Programmers Interface)
defines a set of functions, macros and variables that provide access to most
aspects of the Python run-time system.  The Python API is incorporated in a C
source file by including the header <code class="docutils literal notranslate"><span class="pre">&quot;Python.h&quot;</span></code>.</p>
<p>The compilation of an extension module depends on its intended use as well as on
your system setup; details are given in later chapters.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The C extension interface is specific to CPython, and extension modules do
not work on other Python implementations.  In many cases, it is possible to
avoid writing C extensions and preserve portability to other implementations.
For example, if your use case is calling C library functions or system calls,
you should consider using the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module or the <a class="reference external" href="https://cffi.readthedocs.org">cffi</a> library rather than writing custom C code.
These modules let you write Python code to interface with C code and are more
portable between implementations of Python than writing and compiling a C
extension module.</p>
</div>
<div class="section" id="a-simple-example">
<span id="extending-simpleexample"></span><h2>1.1. A Simple Example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h2>
<p>Let’s create an extension module called <code class="docutils literal notranslate"><span class="pre">spam</span></code> (the favorite food of Monty
Python fans…) and let’s say we want to create a Python interface to the C
library function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> <a class="footnote-reference" href="#id5" id="id1">[1]</a>. This function takes a null-terminated
character string as argument and returns an integer.  We want this function to
be callable from Python as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="n">import</span> <span class="n">spam</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">status</span> <span class="o">=</span> <span class="n">spam</span><span class="p">.</span><span class="n">system</span><span class="p">(</span><span class="s">&quot;ls -l&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Begin by creating a file <code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>.  (Historically, if a module is
called <code class="docutils literal notranslate"><span class="pre">spam</span></code>, the C file containing its implementation is called
<code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code>; if the module name is very long, like <code class="docutils literal notranslate"><span class="pre">spammify</span></code>, the
module name can be just <code class="file docutils literal notranslate"><span class="pre">spammify.c</span></code>.)</p>
<p>The first line of our file can be:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
</pre></div>
</div>
<p>which pulls in the Python API (you can add a comment describing the purpose of
the module and a copyright notice if you like).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since Python may define some pre-processor definitions which affect the standard
headers on some systems, you <em>must</em> include <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> before any standard
headers are included.</p>
</div>
<p>All user-visible symbols defined by <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> have a prefix of <code class="docutils literal notranslate"><span class="pre">Py</span></code> or
<code class="docutils literal notranslate"><span class="pre">PY</span></code>, except those defined in standard header files. For convenience, and
since they are used extensively by the Python interpreter, <code class="docutils literal notranslate"><span class="pre">&quot;Python.h&quot;</span></code>
includes a few standard header files: <code class="docutils literal notranslate"><span class="pre">&lt;stdio.h&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;string.h&gt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;errno.h&gt;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&lt;stdlib.h&gt;</span></code>.  If the latter header file does not exist on
your system, it declares the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> and
<code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code> directly.</p>
<p>The next thing we add to our module file is the C function that will be called
when the Python expression <code class="docutils literal notranslate"><span class="pre">spam.system(string)</span></code> is evaluated (we’ll see
shortly how it ends up being called):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">sts</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;i&quot;</span><span class="p">,</span> <span class="n">sts</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There is a straightforward translation from the argument list in Python (for
example, the single expression <code class="docutils literal notranslate"><span class="pre">&quot;ls</span> <span class="pre">-l&quot;</span></code>) to the arguments passed to the C
function.  The C function always has two arguments, conventionally named <em>self</em>
and <em>args</em>.</p>
<p>For module functions, the <em>self</em> argument is <em>NULL</em> or a pointer selected while
initializing the module (see <a class="reference internal" href="../c-api/allocation.html#c.Py_InitModule4" title="Py_InitModule4"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitModule4()</span></code></a>).  For a method, it would
point to the object instance.</p>
<p>The <em>args</em> argument will be a pointer to a Python tuple object containing the
arguments.  Each item of the tuple corresponds to an argument in the call’s
argument list.  The arguments are Python objects — in order to do anything
with them in our C function we have to convert them to C values.  The function
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> in the Python API checks the argument types and
converts them to C values.  It uses a template string to determine the required
types of the arguments as well as the types of the C variables into which to
store the converted values.  More about this later.</p>
<p><a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> returns true (nonzero) if all arguments have the right
type and its components have been stored in the variables whose addresses are
passed.  It returns false (zero) if an invalid argument list was passed.  In the
latter case it also raises an appropriate exception so the calling function can
return <em>NULL</em> immediately (as we saw in the example).</p>
</div>
<div class="section" id="intermezzo-errors-and-exceptions">
<span id="extending-errors"></span><h2>1.2. Intermezzo: Errors and Exceptions<a class="headerlink" href="#intermezzo-errors-and-exceptions" title="Permalink to this headline">¶</a></h2>
<p>An important convention throughout the Python interpreter is the following: when
a function fails, it should set an exception condition and return an error value
(usually a <em>NULL</em> pointer).  Exceptions are stored in a static global variable
inside the interpreter; if this variable is <em>NULL</em> no exception has occurred.  A
second global variable stores the “associated value” of the exception (the
second argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a>).  A third variable contains the stack
traceback in case the error originated in Python code.  These three variables
are the C equivalents of the Python variables <code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code>,
<code class="docutils literal notranslate"><span class="pre">sys.exc_value</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code> (see the section on module
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> in the Python Library Reference).  It is important to know about them
to understand how errors are passed around.</p>
<p>The Python API defines a number of functions to set various types of exceptions.</p>
<p>The most common one is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a>.  Its arguments are an exception
object and a C string.  The exception object is usually a predefined object like
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>.  The C string indicates the cause of the error
and is converted to a Python string object and stored as the “associated value”
of the exception.</p>
<p>Another useful function is <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetFromErrno" title="PyErr_SetFromErrno"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetFromErrno()</span></code></a>, which only takes an
exception argument and constructs the associated value by inspection of the
global variable <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code>.  The most general function is
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetObject" title="PyErr_SetObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetObject()</span></code></a>, which takes two object arguments, the exception and
its associated value.  You don’t need to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> the objects passed
to any of these functions.</p>
<p>You can test non-destructively whether an exception has been set with
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>.  This returns the current exception object, or <em>NULL</em>
if no exception has occurred.  You normally don’t need to call
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a> to see whether an error occurred in a function call,
since you should be able to tell from the return value.</p>
<p>When a function <em>f</em> that calls another function <em>g</em> detects that the latter
fails, <em>f</em> should itself return an error value (usually <em>NULL</em> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>).  It
should <em>not</em> call one of the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code> functions — one has already
been called by <em>g</em>. <em>f</em>’s caller is then supposed to also return an error
indication to <em>its</em> caller, again <em>without</em> calling <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code>, and so on
— the most detailed cause of the error was already reported by the function
that first detected it.  Once the error reaches the Python interpreter’s main
loop, this aborts the currently executing Python code and tries to find an
exception handler specified by the Python programmer.</p>
<p>(There are situations where a module can actually give a more detailed error
message by calling another <code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_*()</span></code> function, and in such cases it is
fine to do so.  As a general rule, however, this is not necessary, and can cause
information about the cause of the error to be lost: most operations can fail
for a variety of reasons.)</p>
<p>To ignore an exception set by a function call that failed, the exception
condition must be cleared explicitly by calling <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>.  The only
time C code should call <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a> is if it doesn’t want to pass the
error on to the interpreter but wants to handle it completely by itself
(possibly by trying something else, or pretending nothing went wrong).</p>
<p>Every failing <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call must be turned into an exception — the
direct caller of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> (or <code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code>) must call
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NoMemory" title="PyErr_NoMemory"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NoMemory()</span></code></a> and return a failure indicator itself.  All the
object-creating functions (for example, <a class="reference internal" href="../c-api/int.html#c.PyInt_FromLong" title="PyInt_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInt_FromLong()</span></code></a>) already do
this, so this note is only relevant to those who call <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> directly.</p>
<p>Also note that, with the important exception of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> and
friends, functions that return an integer status usually return a positive value
or zero for success and <code class="docutils literal notranslate"><span class="pre">-1</span></code> for failure, like Unix system calls.</p>
<p>Finally, be careful to clean up garbage (by making <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> or
<a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> calls for objects you have already created) when you return
an error indicator!</p>
<p>The choice of which exception to raise is entirely yours.  There are predeclared
C objects corresponding to all built-in Python exceptions, such as
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ZeroDivisionError</span></code>, which you can use directly. Of course, you
should choose exceptions wisely — don’t use <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code> to mean
that a file couldn’t be opened (that should probably be <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_IOError</span></code>).
If something’s wrong with the argument list, the <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>
function usually raises <code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_TypeError</span></code>.  If you have an argument whose
value must be in a particular range or must satisfy other conditions,
<code class="xref c c-data docutils literal notranslate"><span class="pre">PyExc_ValueError</span></code> is appropriate.</p>
<p>You can also define a new exception that is unique to your module. For this, you
usually declare a static object variable at the beginning of your file:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">SpamError</span><span class="p">;</span>
</pre></div>
</div>
<p>and initialize it in your module’s initialization function (<code class="xref c c-func docutils literal notranslate"><span class="pre">initspam()</span></code>)
with an exception object (leaving out the error checking for now):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">initspam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;spam&quot;</span><span class="p">,</span> <span class="n">SpamMethods</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">SpamError</span> <span class="o">=</span> <span class="n">PyErr_NewException</span><span class="p">(</span><span class="s">&quot;spam.error&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">SpamError</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;error&quot;</span><span class="p">,</span> <span class="n">SpamError</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that the Python name for the exception object is <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code>.  The
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NewException" title="PyErr_NewException"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewException()</span></code></a> function may create a class with the base class
being <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> (unless another class is passed in instead of <em>NULL</em>),
described in <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a>.</p>
<p>Note also that the <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> variable retains a reference to the newly
created exception class; this is intentional!  Since the exception could be
removed from the module by external code, an owned reference to the class is
needed to ensure that it will not be discarded, causing <code class="xref c c-data docutils literal notranslate"><span class="pre">SpamError</span></code> to
become a dangling pointer. Should it become a dangling pointer, C code which
raises the exception could cause a core dump or other unintended side effects.</p>
<p>We discuss the use of <code class="docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code> as a function return type later in this
sample.</p>
<p>The <code class="xref py py-exc docutils literal notranslate"><span class="pre">spam.error</span></code> exception can be raised in your extension module using a
call to <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_SetString" title="PyErr_SetString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_SetString()</span></code></a> as shown below:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">sts</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">sts</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">SpamError</span><span class="p">,</span> <span class="s">&quot;System command failed&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">PyLong_FromLong</span><span class="p">(</span><span class="n">sts</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="back-to-the-example">
<span id="backtoexample"></span><h2>1.3. Back to the Example<a class="headerlink" href="#back-to-the-example" title="Permalink to this headline">¶</a></h2>
<p>Going back to our example function, you should now be able to understand this
statement:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
</pre></div>
</div>
<p>It returns <em>NULL</em> (the error indicator for functions returning object pointers)
if an error is detected in the argument list, relying on the exception set by
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>.  Otherwise the string value of the argument has been
copied to the local variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code>.  This is a pointer assignment and
you are not supposed to modify the string to which it points (so in Standard C,
the variable <code class="xref c c-data docutils literal notranslate"><span class="pre">command</span></code> should properly be declared as <code class="docutils literal notranslate"><span class="pre">const</span> <span class="pre">char</span>
<span class="pre">*command</span></code>).</p>
<p>The next statement is a call to the Unix function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code>, passing it
the string we just got from <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">sts</span> <span class="o">=</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
</pre></div>
</div>
<p>Our <code class="xref py py-func docutils literal notranslate"><span class="pre">spam.system()</span></code> function must return the value of <code class="xref c c-data docutils literal notranslate"><span class="pre">sts</span></code> as a
Python object.  This is done using the function <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, which is
something like the inverse of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>: it takes a format
string and an arbitrary number of C values, and returns a new Python object.
More info on <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> is given later.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">return</span> <span class="nf">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;i&quot;</span><span class="p">,</span> <span class="n">sts</span><span class="p">);</span>
</pre></div>
</div>
<p>In this case, it will return an integer object.  (Yes, even integers are objects
on the heap in Python!)</p>
<p>If you have a C function that returns no useful argument (a function returning
<code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code>), the corresponding Python function must return <code class="docutils literal notranslate"><span class="pre">None</span></code>.   You
need this idiom to do so (which is implemented by the <a class="reference internal" href="../c-api/none.html#c.Py_RETURN_NONE" title="Py_RETURN_NONE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_NONE</span></code></a>
macro):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
<span class="k">return</span> <span class="n">Py_None</span><span class="p">;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../c-api/none.html#c.Py_None" title="Py_None"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_None</span></code></a> is the C name for the special Python object <code class="docutils literal notranslate"><span class="pre">None</span></code>.  It is a
genuine Python object rather than a <em>NULL</em> pointer, which means “error” in most
contexts, as we have seen.</p>
</div>
<div class="section" id="the-module-s-method-table-and-initialization-function">
<span id="methodtable"></span><h2>1.4. The Module’s Method Table and Initialization Function<a class="headerlink" href="#the-module-s-method-table-and-initialization-function" title="Permalink to this headline">¶</a></h2>
<p>I promised to show how <code class="xref c c-func docutils literal notranslate"><span class="pre">spam_system()</span></code> is called from Python programs.
First, we need to list its name and address in a “method table”:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">SpamMethods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">...</span>
    <span class="p">{</span><span class="s">&quot;system&quot;</span><span class="p">,</span>  <span class="n">spam_system</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
     <span class="s">&quot;Execute a shell command.&quot;</span><span class="p">},</span>
    <span class="p">...</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>        <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>Note the third entry (<code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>).  This is a flag telling the interpreter
the calling convention to be used for the C function.  It should normally always
be <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code> or <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span> <span class="pre">|</span> <span class="pre">METH_KEYWORDS</span></code>; a value of <code class="docutils literal notranslate"><span class="pre">0</span></code> means
that an obsolete variant of <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> is used.</p>
<p>When using only <code class="docutils literal notranslate"><span class="pre">METH_VARARGS</span></code>, the function should expect the Python-level
parameters to be passed in as a tuple acceptable for parsing via
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>; more information on this function is provided below.</p>
<p>The <a class="reference internal" href="../c-api/structures.html#METH_KEYWORDS" title="METH_KEYWORDS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_KEYWORDS</span></code></a> bit may be set in the third field if keyword
arguments should be passed to the function.  In this case, the C function should
accept a third <code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code> parameter which will be a dictionary of keywords.
Use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> to parse the arguments to such a
function.</p>
<p>The method table must be passed to the interpreter in the module’s
initialization function.  The initialization function must be named
<code class="xref c c-func docutils literal notranslate"><span class="pre">initname()</span></code>, where <em>name</em> is the name of the module, and should be the
only non-<code class="docutils literal notranslate"><span class="pre">static</span></code> item defined in the module file:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">initspam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;spam&quot;</span><span class="p">,</span> <span class="n">SpamMethods</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that PyMODINIT_FUNC declares the function as <code class="docutils literal notranslate"><span class="pre">void</span></code> return type,
declares any special linkage declarations required by the platform, and for  C++
declares the function as <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>.</p>
<p>When the Python program imports module <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> for the first time,
<code class="xref c c-func docutils literal notranslate"><span class="pre">initspam()</span></code> is called. (See below for comments about embedding Python.)
It calls <a class="reference internal" href="../c-api/allocation.html#c.Py_InitModule" title="Py_InitModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitModule()</span></code></a>, which creates a “module object” (which is
inserted in the dictionary <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> under the key <code class="docutils literal notranslate"><span class="pre">&quot;spam&quot;</span></code>), and
inserts built-in function objects into the newly created module based upon the
table (an array of <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structures) that was passed as its
second argument. <a class="reference internal" href="../c-api/allocation.html#c.Py_InitModule" title="Py_InitModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitModule()</span></code></a> returns a pointer to the module object
that it creates (which is unused here).  It may abort with a fatal error for
certain errors, or return <em>NULL</em> if the module could not be initialized
satisfactorily.</p>
<p>When embedding Python, the <code class="xref c c-func docutils literal notranslate"><span class="pre">initspam()</span></code> function is not called
automatically unless there’s an entry in the <code class="xref c c-data docutils literal notranslate"><span class="pre">_PyImport_Inittab</span></code> table.
The easiest way to handle this is to statically initialize your
statically-linked modules by directly calling <code class="xref c c-func docutils literal notranslate"><span class="pre">initspam()</span></code> after the call
to <a class="reference internal" href="../c-api/init.html#c.Py_Initialize" title="Py_Initialize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Initialize()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span>
<span class="nf">main</span><span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">argv</span><span class="p">[])</span>
<span class="p">{</span>
    <span class="cm">/* Pass argv[0] to the Python interpreter */</span>
    <span class="n">Py_SetProgramName</span><span class="p">(</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span>

    <span class="cm">/* Initialize the Python interpreter.  Required. */</span>
    <span class="n">Py_Initialize</span><span class="p">();</span>

    <span class="cm">/* Add a static module */</span>
    <span class="n">initspam</span><span class="p">();</span>

    <span class="p">...</span>
</pre></div>
</div>
<p>An example may be found in the file <code class="file docutils literal notranslate"><span class="pre">Demo/embed/demo.c</span></code> in the Python
source distribution.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Removing entries from <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> or importing compiled modules into
multiple interpreters within a process (or following a <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code> without an
intervening <code class="xref c c-func docutils literal notranslate"><span class="pre">exec()</span></code>) can create problems for some extension modules.
Extension module authors should exercise caution when initializing internal data
structures. Note also that the <a class="reference internal" href="../library/functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> function can be used with
extension modules, and will call the module initialization function
(<code class="xref c c-func docutils literal notranslate"><span class="pre">initspam()</span></code> in the example), but will not load the module again if it was
loaded from a dynamically loadable object file (<code class="file docutils literal notranslate"><span class="pre">.so</span></code> on Unix,
<code class="file docutils literal notranslate"><span class="pre">.dll</span></code> on Windows).</p>
</div>
<p>A more substantial example module is included in the Python source distribution
as <code class="file docutils literal notranslate"><span class="pre">Modules/xxmodule.c</span></code>.  This file may be used as a  template or simply
read as an example.</p>
</div>
<div class="section" id="compilation-and-linkage">
<span id="compilation"></span><h2>1.5. Compilation and Linkage<a class="headerlink" href="#compilation-and-linkage" title="Permalink to this headline">¶</a></h2>
<p>There are two more things to do before you can use your new extension: compiling
and linking it with the Python system.  If you use dynamic loading, the details
may depend on the style of dynamic loading your system uses; see the chapters
about building extension modules (chapter <a class="reference internal" href="building.html#building"><span class="std std-ref">Building C and C++ Extensions with distutils</span></a>) and additional
information that pertains only to building on Windows (chapter
<a class="reference internal" href="windows.html#building-on-windows"><span class="std std-ref">Building C and C++ Extensions on Windows</span></a>) for more information about this.</p>
<p>If you can’t use dynamic loading, or if you want to make your module a permanent
part of the Python interpreter, you will have to change the configuration setup
and rebuild the interpreter.  Luckily, this is very simple on Unix: just place
your file (<code class="file docutils literal notranslate"><span class="pre">spammodule.c</span></code> for example) in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code> directory
of an unpacked source distribution, add a line to the file
<code class="file docutils literal notranslate"><span class="pre">Modules/Setup.local</span></code> describing your file:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">spam</span> <span class="n">spammodule</span><span class="p">.</span><span class="n">o</span>
</pre></div>
</div>
<p>and rebuild the interpreter by running <strong class="program">make</strong> in the toplevel
directory.  You can also run <strong class="program">make</strong> in the <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code>
subdirectory, but then you must first rebuild <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> there by running
‘<strong class="program">make</strong> Makefile’.  (This is necessary each time you change the
<code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file.)</p>
<p>If your module requires additional libraries to link with, these can be listed
on the line in the configuration file as well, for instance:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">spam</span> <span class="n">spammodule</span><span class="p">.</span><span class="n">o</span> <span class="o">-</span><span class="n">lX11</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-python-functions-from-c">
<span id="callingpython"></span><h2>1.6. Calling Python Functions from C<a class="headerlink" href="#calling-python-functions-from-c" title="Permalink to this headline">¶</a></h2>
<p>So far we have concentrated on making C functions callable from Python.  The
reverse is also useful: calling Python functions from C. This is especially the
case for libraries that support so-called “callback” functions.  If a C
interface makes use of callbacks, the equivalent Python often needs to provide a
callback mechanism to the Python programmer; the implementation will require
calling the Python callback functions from a C callback.  Other uses are also
imaginable.</p>
<p>Fortunately, the Python interpreter is easily called recursively, and there is a
standard interface to call a Python function.  (I won’t dwell on how to call the
Python parser with a particular string as input — if you’re interested, have a
look at the implementation of the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> command line option in
<code class="file docutils literal notranslate"><span class="pre">Modules/main.c</span></code> from the Python source code.)</p>
<p>Calling a Python function is easy.  First, the Python program must somehow pass
you the Python function object.  You should provide a function (or some other
interface) to do this.  When this function is called, save a pointer to the
Python function object (be careful to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> it!) in a global
variable — or wherever you see fit. For example, the following function might
be part of a module definition:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">my_callback</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">my_set_callback</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dummy</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">temp</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;O:set_callback&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">temp</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyCallable_Check</span><span class="p">(</span><span class="n">temp</span><span class="p">))</span> <span class="p">{</span>
            <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">&quot;parameter must be callable&quot;</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="n">Py_XINCREF</span><span class="p">(</span><span class="n">temp</span><span class="p">);</span>         <span class="cm">/* Add a reference to new callback */</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">my_callback</span><span class="p">);</span>  <span class="cm">/* Dispose of previous callback */</span>
        <span class="n">my_callback</span> <span class="o">=</span> <span class="n">temp</span><span class="p">;</span>       <span class="cm">/* Remember new callback */</span>
        <span class="cm">/* Boilerplate to return &quot;None&quot; */</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">Py_None</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This function must be registered with the interpreter using the
<a class="reference internal" href="../c-api/structures.html#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a> flag; this is described in section <a class="reference internal" href="#methodtable"><span class="std std-ref">The Module’s Method Table and Initialization Function</span></a>.  The
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function and its arguments are documented in section
<a class="reference internal" href="#parsetuple"><span class="std std-ref">Extracting Parameters in Extension Functions</span></a>.</p>
<p>The macros <a class="reference internal" href="../c-api/refcounting.html#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> increment/decrement the
reference count of an object and are safe in the presence of <em>NULL</em> pointers
(but note that <em>temp</em> will not be  <em>NULL</em> in this context).  More info on them
in section <a class="reference internal" href="#refcounts"><span class="std std-ref">Reference Counts</span></a>.</p>
<p id="index-0">Later, when it is time to call the function, you call the C function
<a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>.  This function has two arguments, both pointers to
arbitrary Python objects: the Python function, and the argument list.  The
argument list must always be a tuple object, whose length is the number of
arguments.  To call the Python function with no arguments, pass in NULL, or
an empty tuple; to call it with one argument, pass a singleton tuple.
<a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> returns a tuple when its format string consists of zero
or more format codes between parentheses.  For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">arg</span><span class="p">;</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
<span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">arg</span> <span class="o">=</span> <span class="mi">123</span><span class="p">;</span>
<span class="p">...</span>
<span class="cm">/* Time to call the callback */</span>
<span class="n">arglist</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(i)&quot;</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="n">arglist</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
</pre></div>
</div>
<p><a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> returns a Python object pointer: this is the return
value of the Python function.  <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is
“reference-count-neutral” with respect to its arguments.  In the example a new
tuple was created to serve as the argument list, which is <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>-ed immediately after the <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> call.</p>
<p>The return value of <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is “new”: either it is a brand
new object, or it is an existing object whose reference count has been
incremented.  So, unless you want to save it in a global variable, you should
somehow <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> the result, even (especially!) if you are not
interested in its value.</p>
<p>Before you do this, however, it is important to check that the return value
isn’t <em>NULL</em>.  If it is, the Python function terminated by raising an exception.
If the C code that called <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> is called from Python, it
should now return an error indication to its Python caller, so the interpreter
can print a stack trace, or the calling Python code can handle the exception.
If this is not possible or desirable, the exception should be cleared by calling
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Clear" title="PyErr_Clear"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Clear()</span></code></a>.  For example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="p">...</span><span class="n">use</span> <span class="n">result</span><span class="p">...</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
<p>Depending on the desired interface to the Python callback function, you may also
have to provide an argument list to <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a>.  In some cases
the argument list is also provided by the Python program, through the same
interface that specified the callback function.  It can then be saved and used
in the same manner as the function object.  In other cases, you may have to
construct a new tuple to pass as the argument list.  The simplest way to do this
is to call <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>.  For example, if you want to pass an integral
event code, you might use the following code:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arglist</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">arglist</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;(l)&quot;</span><span class="p">,</span> <span class="n">eventcode</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="n">arglist</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">arglist</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="cm">/* Here maybe use the result */</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
<p>Note the placement of <code class="docutils literal notranslate"><span class="pre">Py_DECREF(arglist)</span></code> immediately after the call, before
the error check!  Also note that strictly speaking this code is not complete:
<a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> may run out of memory, and this should be checked.</p>
<p>You may also call a function with keyword arguments by using
<a class="reference internal" href="../c-api/object.html#c.PyObject_Call" title="PyObject_Call"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Call()</span></code></a>, which supports arguments and keyword arguments.  As in
the above example, we use <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> to construct the dictionary.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="n">dict</span><span class="p">;</span>
<span class="p">...</span>
<span class="n">dict</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;{s:i}&quot;</span><span class="p">,</span> <span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="n">val</span><span class="p">);</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">PyObject_Call</span><span class="p">(</span><span class="n">my_callback</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="n">dict</span><span class="p">);</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">dict</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">result</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span> <span class="cm">/* Pass error back */</span>
<span class="cm">/* Here maybe use the result */</span>
<span class="n">Py_DECREF</span><span class="p">(</span><span class="n">result</span><span class="p">);</span>
</pre></div>
</div>
</div>
<div class="section" id="extracting-parameters-in-extension-functions">
<span id="parsetuple"></span><h2>1.7. Extracting Parameters in Extension Functions<a class="headerlink" href="#extracting-parameters-in-extension-functions" title="Permalink to this headline">¶</a></h2>
<p id="index-1">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function is declared as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="nf">PyArg_ParseTuple</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="p">...);</span>
</pre></div>
</div>
<p>The <em>arg</em> argument must be a tuple object containing an argument list passed
from Python to a C function.  The <em>format</em> argument must be a format string,
whose syntax is explained in <a class="reference internal" href="../c-api/arg.html#arg-parsing"><span class="std std-ref">Parsing arguments and building values</span></a> in the Python/C API Reference
Manual.  The remaining arguments must be addresses of variables whose type is
determined by the format string.</p>
<p>Note that while <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> checks that the Python arguments have
the required types, it cannot check the validity of the addresses of C variables
passed to the call: if you make mistakes there, your code will probably crash or
at least overwrite random bits in memory.  So be careful!</p>
<p>Note that any Python object references which are provided to the caller are
<em>borrowed</em> references; do not decrement their reference count!</p>
<p>Some example calls:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">ok</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">;</span>
<span class="kt">long</span> <span class="n">k</span><span class="p">,</span> <span class="n">l</span><span class="p">;</span>
<span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">s</span><span class="p">;</span>
<span class="kt">int</span> <span class="n">size</span><span class="p">;</span>

<span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;&quot;</span><span class="p">);</span> <span class="cm">/* No arguments */</span>
    <span class="cm">/* Python call: f() */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">s</span><span class="p">);</span> <span class="cm">/* A string */</span>
    <span class="cm">/* Possible Python call: f(&#39;whoops!&#39;) */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;lls&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">k</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">l</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">s</span><span class="p">);</span> <span class="cm">/* Two longs and a string */</span>
    <span class="cm">/* Possible Python call: f(1, 2, &#39;three&#39;) */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;(ii)s#&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">i</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">j</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">s</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">size</span><span class="p">);</span>
    <span class="cm">/* A pair of ints and a string, whose size is also returned */</span>
    <span class="cm">/* Possible Python call: f((1, 2), &#39;three&#39;) */</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">file</span><span class="p">;</span>
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">mode</span> <span class="o">=</span> <span class="s">&quot;r&quot;</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">bufsize</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s|si&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">file</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">mode</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">bufsize</span><span class="p">);</span>
    <span class="cm">/* A string, and optionally another string and an integer */</span>
    <span class="cm">/* Possible Python calls:</span>
<span class="cm">       f(&#39;spam&#39;)</span>
<span class="cm">       f(&#39;spam&#39;, &#39;w&#39;)</span>
<span class="cm">       f(&#39;spam&#39;, &#39;wb&#39;, 100000) */</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
    <span class="kt">int</span> <span class="n">left</span><span class="p">,</span> <span class="n">top</span><span class="p">,</span> <span class="n">right</span><span class="p">,</span> <span class="n">bottom</span><span class="p">,</span> <span class="n">h</span><span class="p">,</span> <span class="n">v</span><span class="p">;</span>
    <span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;((ii)(ii))(ii)&quot;</span><span class="p">,</span>
             <span class="o">&amp;</span><span class="n">left</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">top</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">right</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">bottom</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">h</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">v</span><span class="p">);</span>
    <span class="cm">/* A rectangle and a point */</span>
    <span class="cm">/* Possible Python call:</span>
<span class="cm">       f(((0, 0), (400, 300)), (10, 10)) */</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
    <span class="n">Py_complex</span> <span class="n">c</span><span class="p">;</span>
    <span class="n">ok</span> <span class="o">=</span> <span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;D:myfunction&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">c</span><span class="p">);</span>
    <span class="cm">/* a complex, also providing a function name for errors */</span>
    <span class="cm">/* Possible Python call: myfunction(1+2j) */</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="keyword-parameters-for-extension-functions">
<span id="parsetupleandkeywords"></span><h2>1.8. Keyword Parameters for Extension Functions<a class="headerlink" href="#keyword-parameters-for-extension-functions" title="Permalink to this headline">¶</a></h2>
<p id="index-2">The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> function is declared as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="nf">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">arg</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwdict</span><span class="p">,</span>
                                <span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[],</span> <span class="p">...);</span>
</pre></div>
</div>
<p>The <em>arg</em> and <em>format</em> parameters are identical to those of the
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> function.  The <em>kwdict</em> parameter is the dictionary of
keywords received as the third parameter from the Python runtime.  The <em>kwlist</em>
parameter is a <em>NULL</em>-terminated list of strings which identify the parameters;
the names are matched with the type information from <em>format</em> from left to
right.  On success, <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> returns true, otherwise
it returns false and raises an appropriate exception.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Nested tuples cannot be parsed when using keyword arguments!  Keyword parameters
passed in which are not present in the <em>kwlist</em> will cause <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to
be raised.</p>
</div>
<p id="index-3">Here is an example module which uses keywords, based on an example by Geoff
Philbrick (<a class="reference external" href="mailto:philbrick&#37;&#52;&#48;hks&#46;com">philbrick<span>&#64;</span>hks<span>&#46;</span>com</a>):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;Python.h&quot;</span><span class="cp"></span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">keywdarg_parrot</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">keywds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">voltage</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">state</span> <span class="o">=</span> <span class="s">&quot;a stiff&quot;</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">action</span> <span class="o">=</span> <span class="s">&quot;voom&quot;</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">type</span> <span class="o">=</span> <span class="s">&quot;Norwegian Blue&quot;</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;voltage&quot;</span><span class="p">,</span> <span class="s">&quot;state&quot;</span><span class="p">,</span> <span class="s">&quot;action&quot;</span><span class="p">,</span> <span class="s">&quot;type&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">keywds</span><span class="p">,</span> <span class="s">&quot;i|sss&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                     <span class="o">&amp;</span><span class="n">voltage</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">state</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">action</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">type</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">printf</span><span class="p">(</span><span class="s">&quot;-- This parrot wouldn&#39;t %s if you put %i Volts through it.</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span>
           <span class="n">action</span><span class="p">,</span> <span class="n">voltage</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">&quot;-- Lovely plumage, the %s -- It&#39;s %s!</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">type</span><span class="p">,</span> <span class="n">state</span><span class="p">);</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">Py_None</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">keywdarg_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="cm">/* The cast of the function is necessary since PyCFunction values</span>
<span class="cm">     * only take two PyObject* parameters, and keywdarg_parrot() takes</span>
<span class="cm">     * three.</span>
<span class="cm">     */</span>
    <span class="p">{</span><span class="s">&quot;parrot&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">keywdarg_parrot</span><span class="p">,</span> <span class="n">METH_VARARGS</span> <span class="o">|</span> <span class="n">METH_KEYWORDS</span><span class="p">,</span>
     <span class="s">&quot;Print a lovely skit to standard output.&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>   <span class="cm">/* sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">initkeywdarg</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
  <span class="cm">/* Create the module and add the functions */</span>
  <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;keywdarg&quot;</span><span class="p">,</span> <span class="n">keywdarg_methods</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="building-arbitrary-values">
<span id="buildvalue"></span><h2>1.9. Building Arbitrary Values<a class="headerlink" href="#building-arbitrary-values" title="Permalink to this headline">¶</a></h2>
<p>This function is the counterpart to <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>.  It is declared
as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span><span class="nf">Py_BuildValue</span><span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="n">format</span><span class="p">,</span> <span class="p">...);</span>
</pre></div>
</div>
<p>It recognizes a set of format units similar to the ones recognized by
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>, but the arguments (which are input to the function,
not output) must not be pointers, just values.  It returns a new Python object,
suitable for returning from a C function called from Python.</p>
<p>One difference with <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>: while the latter requires its
first argument to be a tuple (since Python argument lists are always represented
as tuples internally), <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> does not always build a tuple.  It
builds a tuple only if its format string contains two or more format units. If
the format string is empty, it returns <code class="docutils literal notranslate"><span class="pre">None</span></code>; if it contains exactly one
format unit, it returns whatever object is described by that format unit.  To
force it to return a tuple of size 0 or one, parenthesize the format string.</p>
<p>Examples (to the left the call, to the right the resulting Python value):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Py_BuildValue(&quot;&quot;)                        None
Py_BuildValue(&quot;i&quot;, 123)                  123
Py_BuildValue(&quot;iii&quot;, 123, 456, 789)      (123, 456, 789)
Py_BuildValue(&quot;s&quot;, &quot;hello&quot;)              &#39;hello&#39;
Py_BuildValue(&quot;ss&quot;, &quot;hello&quot;, &quot;world&quot;)    (&#39;hello&#39;, &#39;world&#39;)
Py_BuildValue(&quot;s#&quot;, &quot;hello&quot;, 4)          &#39;hell&#39;
Py_BuildValue(&quot;()&quot;)                      ()
Py_BuildValue(&quot;(i)&quot;, 123)                (123,)
Py_BuildValue(&quot;(ii)&quot;, 123, 456)          (123, 456)
Py_BuildValue(&quot;(i,i)&quot;, 123, 456)         (123, 456)
Py_BuildValue(&quot;[i,i]&quot;, 123, 456)         [123, 456]
Py_BuildValue(&quot;{s:i,s:i}&quot;,
              &quot;abc&quot;, 123, &quot;def&quot;, 456)    {&#39;abc&#39;: 123, &#39;def&#39;: 456}
Py_BuildValue(&quot;((ii)(ii)) (ii)&quot;,
              1, 2, 3, 4, 5, 6)          (((1, 2), (3, 4)), (5, 6))
</pre></div>
</div>
</div>
<div class="section" id="reference-counts">
<span id="refcounts"></span><h2>1.10. Reference Counts<a class="headerlink" href="#reference-counts" title="Permalink to this headline">¶</a></h2>
<p>In languages like C or C++, the programmer is responsible for dynamic allocation
and deallocation of memory on the heap.  In C, this is done using the functions
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.  In C++, the operators <code class="docutils literal notranslate"><span class="pre">new</span></code> and
<code class="docutils literal notranslate"><span class="pre">delete</span></code> are used with essentially the same meaning and we’ll restrict
the following discussion to the C case.</p>
<p>Every block of memory allocated with <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> should eventually be
returned to the pool of available memory by exactly one call to <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.
It is important to call <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> at the right time.  If a block’s address
is forgotten but <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> is not called for it, the memory it occupies
cannot be reused until the program terminates.  This is called a <em class="dfn">memory
leak</em>.  On the other hand, if a program calls <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> for a block and then
continues to use the block, it creates a conflict with re-use of the block
through another <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> call.  This is called <em class="dfn">using freed memory</em>.
It has the same bad consequences as referencing uninitialized data — core
dumps, wrong results, mysterious crashes.</p>
<p>Common causes of memory leaks are unusual paths through the code.  For instance,
a function may allocate a block of memory, do some calculation, and then free
the block again.  Now a change in the requirements for the function may add a
test to the calculation that detects an error condition and can return
prematurely from the function.  It’s easy to forget to free the allocated memory
block when taking this premature exit, especially when it is added later to the
code.  Such leaks, once introduced, often go undetected for a long time: the
error exit is taken only in a small fraction of all calls, and most modern
machines have plenty of virtual memory, so the leak only becomes apparent in a
long-running process that uses the leaking function frequently.  Therefore, it’s
important to prevent leaks from happening by having a coding convention or
strategy that minimizes this kind of errors.</p>
<p>Since Python makes heavy use of <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>, it needs a
strategy to avoid memory leaks as well as the use of freed memory.  The chosen
method is called <em class="dfn">reference counting</em>.  The principle is simple: every
object contains a counter, which is incremented when a reference to the object
is stored somewhere, and which is decremented when a reference to it is deleted.
When the counter reaches zero, the last reference to the object has been deleted
and the object is freed.</p>
<p>An alternative strategy is called <em class="dfn">automatic garbage collection</em>.
(Sometimes, reference counting is also referred to as a garbage collection
strategy, hence my use of “automatic” to distinguish the two.)  The big
advantage of automatic garbage collection is that the user doesn’t need to call
<code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> explicitly.  (Another claimed advantage is an improvement in speed
or memory usage — this is no hard fact however.)  The disadvantage is that for
C, there is no truly portable automatic garbage collector, while reference
counting can be implemented portably (as long as the functions <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>
and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> are available — which the C Standard guarantees). Maybe some
day a sufficiently portable automatic garbage collector will be available for C.
Until then, we’ll have to live with reference counts.</p>
<p>While Python uses the traditional reference counting implementation, it also
offers a cycle detector that works to detect reference cycles.  This allows
applications to not worry about creating direct or indirect circular references;
these are the weakness of garbage collection implemented using only reference
counting.  Reference cycles consist of objects which contain (possibly indirect)
references to themselves, so that each object in the cycle has a reference count
which is non-zero.  Typical reference counting implementations are not able to
reclaim the memory belonging to any objects in a reference cycle, or referenced
from the objects in the cycle, even though there are no further references to
the cycle itself.</p>
<p>The cycle detector is able to detect garbage cycles and can reclaim them so long
as there are no finalizers implemented in Python (<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods).
When there are such finalizers, the detector exposes the cycles through the
<a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module (specifically, the <a class="reference internal" href="../library/gc.html#gc.garbage" title="gc.garbage"><code class="xref py py-attr docutils literal notranslate"><span class="pre">garbage</span></code></a> variable in that module).
The <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module also exposes a way to run the detector (the
<a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">collect()</span></code></a> function), as well as configuration
interfaces and the ability to disable the detector at runtime.  The cycle
detector is considered an optional component; though it is included by default,
it can be disabled at build time using the <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-cycle-gc</span></code> option
to the <strong class="program">configure</strong> script on Unix platforms (including Mac OS X) or by
removing the definition of <code class="docutils literal notranslate"><span class="pre">WITH_CYCLE_GC</span></code> in the <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code> header on
other platforms.  If the cycle detector is disabled in this way, the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a>
module will not be available.</p>
<div class="section" id="reference-counting-in-python">
<span id="refcountsinpython"></span><h3>1.10.1. Reference Counting in Python<a class="headerlink" href="#reference-counting-in-python" title="Permalink to this headline">¶</a></h3>
<p>There are two macros, <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>, which handle the
incrementing and decrementing of the reference count. <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> also
frees the object when the count reaches zero. For flexibility, it doesn’t call
<code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> directly — rather, it makes a call through a function pointer in
the object’s <em class="dfn">type object</em>.  For this purpose (and others), every object
also contains a pointer to its type object.</p>
<p>The big question now remains: when to use <code class="docutils literal notranslate"><span class="pre">Py_INCREF(x)</span></code> and <code class="docutils literal notranslate"><span class="pre">Py_DECREF(x)</span></code>?
Let’s first introduce some terms.  Nobody “owns” an object; however, you can
<em class="dfn">own a reference</em> to an object.  An object’s reference count is now defined
as the number of owned references to it.  The owner of a reference is
responsible for calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> when the reference is no longer
needed.  Ownership of a reference can be transferred.  There are three ways to
dispose of an owned reference: pass it on, store it, or call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>.
Forgetting to dispose of an owned reference creates a memory leak.</p>
<p>It is also possible to <em class="dfn">borrow</em> <a class="footnote-reference" href="#id6" id="id2">[2]</a> a reference to an object.  The
borrower of a reference should not call <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>.  The borrower must
not hold on to the object longer than the owner from which it was borrowed.
Using a borrowed reference after the owner has disposed of it risks using freed
memory and should be avoided completely <a class="footnote-reference" href="#id7" id="id3">[3]</a>.</p>
<p>The advantage of borrowing over owning a reference is that you don’t need to
take care of disposing of the reference on all possible paths through the code
— in other words, with a borrowed reference you don’t run the risk of leaking
when a premature exit is taken.  The disadvantage of borrowing over owning is
that there are some subtle situations where in seemingly correct code a borrowed
reference can be used after the owner from which it was borrowed has in fact
disposed of it.</p>
<p>A borrowed reference can be changed into an owned reference by calling
<a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>.  This does not affect the status of the owner from which the
reference was borrowed — it creates a new owned reference, and gives full
owner responsibilities (the new owner must dispose of the reference properly, as
well as the previous owner).</p>
</div>
<div class="section" id="ownership-rules">
<span id="ownershiprules"></span><h3>1.10.2. Ownership Rules<a class="headerlink" href="#ownership-rules" title="Permalink to this headline">¶</a></h3>
<p>Whenever an object reference is passed into or out of a function, it is part of
the function’s interface specification whether ownership is transferred with the
reference or not.</p>
<p>Most functions that return a reference to an object pass on ownership with the
reference.  In particular, all functions whose function it is to create a new
object, such as <a class="reference internal" href="../c-api/int.html#c.PyInt_FromLong" title="PyInt_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInt_FromLong()</span></code></a> and <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, pass
ownership to the receiver.  Even if the object is not actually new, you still
receive ownership of a new reference to that object.  For instance,
<a class="reference internal" href="../c-api/int.html#c.PyInt_FromLong" title="PyInt_FromLong"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInt_FromLong()</span></code></a> maintains a cache of popular values and can return a
reference to a cached item.</p>
<p>Many functions that extract objects from other objects also transfer ownership
with the reference, for instance <a class="reference internal" href="../c-api/object.html#c.PyObject_GetAttrString" title="PyObject_GetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetAttrString()</span></code></a>.  The picture
is less clear, here, however, since a few common routines are exceptions:
<a class="reference internal" href="../c-api/tuple.html#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>, <a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItem" title="PyDict_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItem()</span></code></a>, and
<a class="reference internal" href="../c-api/dict.html#c.PyDict_GetItemString" title="PyDict_GetItemString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_GetItemString()</span></code></a> all return references that you borrow from the
tuple, list or dictionary.</p>
<p>The function <a class="reference internal" href="../c-api/import.html#c.PyImport_AddModule" title="PyImport_AddModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_AddModule()</span></code></a> also returns a borrowed reference, even
though it may actually create the object it returns: this is possible because an
owned reference to the object is stored in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
<p>When you pass an object reference into another function, in general, the
function borrows the reference from you — if it needs to store it, it will use
<a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> to become an independent owner.  There are exactly two
important exceptions to this rule: <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_SetItem" title="PyTuple_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_SetItem()</span></code></a> and
<a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>.  These functions take over ownership of the item passed
to them — even if they fail!  (Note that <a class="reference internal" href="../c-api/dict.html#c.PyDict_SetItem" title="PyDict_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyDict_SetItem()</span></code></a> and friends
don’t take over ownership — they are “normal.”)</p>
<p>When a C function is called from Python, it borrows references to its arguments
from the caller.  The caller owns a reference to the object, so the borrowed
reference’s lifetime is guaranteed until the function returns.  Only when such a
borrowed reference must be stored or passed on, it must be turned into an owned
reference by calling <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a>.</p>
<p>The object reference returned from a C function that is called from Python must
be an owned reference — ownership is transferred from the function to its
caller.</p>
</div>
<div class="section" id="thin-ice">
<span id="thinice"></span><h3>1.10.3. Thin Ice<a class="headerlink" href="#thin-ice" title="Permalink to this headline">¶</a></h3>
<p>There are a few situations where seemingly harmless use of a borrowed reference
can lead to problems.  These all have to do with implicit invocations of the
interpreter, which can cause the owner of a reference to dispose of it.</p>
<p>The first and most important case to know about is using <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> on
an unrelated object while borrowing a reference to a list item.  For instance:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>

    <span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">));</span>
    <span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">stdout</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span> <span class="cm">/* BUG! */</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This function first borrows a reference to <code class="docutils literal notranslate"><span class="pre">list[0]</span></code>, then replaces
<code class="docutils literal notranslate"><span class="pre">list[1]</span></code> with the value <code class="docutils literal notranslate"><span class="pre">0</span></code>, and finally prints the borrowed reference.
Looks harmless, right?  But it’s not!</p>
<p>Let’s follow the control flow into <a class="reference internal" href="../c-api/list.html#c.PyList_SetItem" title="PyList_SetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_SetItem()</span></code></a>.  The list owns
references to all its items, so when item 1 is replaced, it has to dispose of
the original item 1.  Now let’s suppose the original item 1 was an instance of a
user-defined class, and let’s further suppose that the class defined a
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.  If this class instance has a reference count of 1,
disposing of it will call its <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.</p>
<p>Since it is written in Python, the <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method can execute arbitrary
Python code.  Could it perhaps do something to invalidate the reference to
<code class="docutils literal notranslate"><span class="pre">item</span></code> in <code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code>?  You bet!  Assuming that the list passed into
<code class="xref c c-func docutils literal notranslate"><span class="pre">bug()</span></code> is accessible to the <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, it could execute a
statement to the effect of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">list[0]</span></code>, and assuming this was the last
reference to that object, it would free the memory associated with it, thereby
invalidating <code class="docutils literal notranslate"><span class="pre">item</span></code>.</p>
<p>The solution, once you know the source of the problem, is easy: temporarily
increment the reference count.  The correct version of the function reads:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">no_bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
    <span class="n">PyList_SetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="mi">0L</span><span class="p">));</span>
    <span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">stdout</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">item</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This is a true story.  An older version of Python contained variants of this bug
and someone spent a considerable amount of time in a C debugger to figure out
why his <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods would fail…</p>
<p>The second case of problems with a borrowed reference is a variant involving
threads.  Normally, multiple threads in the Python interpreter can’t get in each
other’s way, because there is a global lock protecting Python’s entire object
space.  However, it is possible to temporarily release this lock using the macro
<a class="reference internal" href="../c-api/init.html#c.Py_BEGIN_ALLOW_THREADS" title="Py_BEGIN_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_BEGIN_ALLOW_THREADS</span></code></a>, and to re-acquire it using
<a class="reference internal" href="../c-api/init.html#c.Py_END_ALLOW_THREADS" title="Py_END_ALLOW_THREADS"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_END_ALLOW_THREADS</span></code></a>.  This is common around blocking I/O calls, to
let other threads use the processor while waiting for the I/O to complete.
Obviously, the following function has the same problem as the previous one:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span>
<span class="nf">bug</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">list</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">item</span> <span class="o">=</span> <span class="n">PyList_GetItem</span><span class="p">(</span><span class="n">list</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="n">Py_BEGIN_ALLOW_THREADS</span>
    <span class="p">...</span><span class="n">some</span> <span class="n">blocking</span> <span class="n">I</span><span class="o">/</span><span class="n">O</span> <span class="n">call</span><span class="p">...</span>
    <span class="n">Py_END_ALLOW_THREADS</span>
    <span class="n">PyObject_Print</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="n">stdout</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span> <span class="cm">/* BUG! */</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="null-pointers">
<span id="nullpointers"></span><h3>1.10.4. NULL Pointers<a class="headerlink" href="#null-pointers" title="Permalink to this headline">¶</a></h3>
<p>In general, functions that take object references as arguments do not expect you
to pass them <em>NULL</em> pointers, and will dump core (or cause later core dumps) if
you do so.  Functions that return object references generally return <em>NULL</em> only
to indicate that an exception occurred.  The reason for not testing for <em>NULL</em>
arguments is that functions often pass the objects they receive on to other
function — if each function were to test for <em>NULL</em>, there would be a lot of
redundant tests and the code would run more slowly.</p>
<p>It is better to test for <em>NULL</em> only at the “source:” when a pointer that may be
<em>NULL</em> is received, for example, from <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> or from a function that
may raise an exception.</p>
<p>The macros <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> do not check for <em>NULL</em>
pointers — however, their variants <a class="reference internal" href="../c-api/refcounting.html#c.Py_XINCREF" title="Py_XINCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XINCREF()</span></code></a> and <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a>
do.</p>
<p>The macros for checking for a particular object type (<code class="docutils literal notranslate"><span class="pre">Pytype_Check()</span></code>) don’t
check for <em>NULL</em> pointers — again, there is much code that calls several of
these in a row to test an object against various different expected types, and
this would generate redundant tests.  There are no variants with <em>NULL</em>
checking.</p>
<p>The C function calling mechanism guarantees that the argument list passed to C
functions (<code class="docutils literal notranslate"><span class="pre">args</span></code> in the examples) is never <em>NULL</em> — in fact it guarantees
that it is always a tuple <a class="footnote-reference" href="#id8" id="id4">[4]</a>.</p>
<p>It is a severe error to ever let a <em>NULL</em> pointer “escape” to the Python user.</p>
</div>
</div>
<div class="section" id="writing-extensions-in-c">
<span id="cplusplus"></span><h2>1.11. Writing Extensions in C++<a class="headerlink" href="#writing-extensions-in-c" title="Permalink to this headline">¶</a></h2>
<p>It is possible to write extension modules in C++.  Some restrictions apply.  If
the main program (the Python interpreter) is compiled and linked by the C
compiler, global or static objects with constructors cannot be used.  This is
not a problem if the main program is linked by the C++ compiler.  Functions that
will be called by the Python interpreter (in particular, module initialization
functions) have to be declared using <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code>. It is unnecessary to
enclose the Python header files in <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span> <span class="pre">{...}</span></code> — they use this form
already if the symbol <code class="docutils literal notranslate"><span class="pre">__cplusplus</span></code> is defined (all recent C++ compilers
define this symbol).</p>
</div>
<div class="section" id="providing-a-c-api-for-an-extension-module">
<span id="using-capsules"></span><h2>1.12. Providing a C API for an Extension Module<a class="headerlink" href="#providing-a-c-api-for-an-extension-module" title="Permalink to this headline">¶</a></h2>
<p>Many extension modules just provide new functions and types to be used from
Python, but sometimes the code in an extension module can be useful for other
extension modules. For example, an extension module could implement a type
“collection” which works like lists without order. Just like the standard Python
list type has a C API which permits extension modules to create and manipulate
lists, this new collection type should have a set of C functions for direct
manipulation from other extension modules.</p>
<p>At first sight this seems easy: just write the functions (without declaring them
<code class="docutils literal notranslate"><span class="pre">static</span></code>, of course), provide an appropriate header file, and document
the C API. And in fact this would work if all extension modules were always
linked statically with the Python interpreter. When modules are used as shared
libraries, however, the symbols defined in one module may not be visible to
another module. The details of visibility depend on the operating system; some
systems use one global namespace for the Python interpreter and all extension
modules (Windows, for example), whereas others require an explicit list of
imported symbols at module link time (AIX is one example), or offer a choice of
different strategies (most Unices). And even if symbols are globally visible,
the module whose functions one wishes to call might not have been loaded yet!</p>
<p>Portability therefore requires not to make any assumptions about symbol
visibility. This means that all symbols in extension modules should be declared
<code class="docutils literal notranslate"><span class="pre">static</span></code>, except for the module’s initialization function, in order to
avoid name clashes with other extension modules (as discussed in section
<a class="reference internal" href="#methodtable"><span class="std std-ref">The Module’s Method Table and Initialization Function</span></a>). And it means that symbols that <em>should</em> be accessible from
other extension modules must be exported in a different way.</p>
<p>Python provides a special mechanism to pass C-level information (pointers) from
one extension module to another one: Capsules. A Capsule is a Python data type
which stores a pointer (<code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code>).  Capsules can only be created and
accessed via their C API, but they can be passed around like any other Python
object. In particular,  they can be assigned to a name in an extension module’s
namespace. Other extension modules can then import this module, retrieve the
value of this name, and then retrieve the pointer from the Capsule.</p>
<p>There are many ways in which Capsules can be used to export the C API of an
extension module. Each function could get its own Capsule, or all C API pointers
could be stored in an array whose address is published in a Capsule. And the
various tasks of storing and retrieving the pointers can be distributed in
different ways between the module providing the code and the client modules.</p>
<p>Whichever method you choose, it’s important to name your Capsules properly.
The function <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_New" title="PyCapsule_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_New()</span></code></a> takes a name parameter
(<code class="xref c c-type docutils literal notranslate"><span class="pre">const</span> <span class="pre">char</span> <span class="pre">*</span></code>); you’re permitted to pass in a <em>NULL</em> name, but
we strongly encourage you to specify a name.  Properly named Capsules provide
a degree of runtime type-safety; there is no feasible way to tell one unnamed
Capsule from another.</p>
<p>In particular, Capsules used to expose C APIs should be given a name following
this convention:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">modulename</span><span class="p">.</span><span class="n">attributename</span>
</pre></div>
</div>
<p>The convenience function <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_Import" title="PyCapsule_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_Import()</span></code></a> makes it easy to
load a C API provided via a Capsule, but only if the Capsule’s name
matches this convention.  This behavior gives C API users a high degree
of certainty that the Capsule they load contains the correct C API.</p>
<p>The following example demonstrates an approach that puts most of the burden on
the writer of the exporting module, which is appropriate for commonly used
library modules. It stores all C API pointers (just one in the example!) in an
array of <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code> pointers which becomes the value of a Capsule. The header
file corresponding to the module provides a macro that takes care of importing
the module and retrieving its C API pointers; client modules only have to call
this macro before accessing the C API.</p>
<p>The exporting module is a modification of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> module from section
<a class="reference internal" href="#extending-simpleexample"><span class="std std-ref">A Simple Example</span></a>. The function <code class="xref py py-func docutils literal notranslate"><span class="pre">spam.system()</span></code> does not call
the C library function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> directly, but a function
<code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code>, which would of course do something more complicated in
reality (such as adding “spam” to every command). This function
<code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is also exported to other extension modules.</p>
<p>The function <code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is a plain C function, declared
<code class="docutils literal notranslate"><span class="pre">static</span></code> like everything else:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">PySpam_System</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The function <code class="xref c c-func docutils literal notranslate"><span class="pre">spam_system()</span></code> is modified in a trivial way:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">spam_system</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">command</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">sts</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;s&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">command</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">sts</span> <span class="o">=</span> <span class="n">PySpam_System</span><span class="p">(</span><span class="n">command</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;i&quot;</span><span class="p">,</span> <span class="n">sts</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the beginning of the module, right after the line</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;Python.h&quot;</span><span class="cp"></span>
</pre></div>
</div>
<p>two more lines must be added:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#define SPAM_MODULE</span>
<span class="cp">#include</span> <span class="cpf">&quot;spammodule.h&quot;</span><span class="cp"></span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">#define</span></code> is used to tell the header file that it is being included in the
exporting module, not a client module. Finally, the module’s initialization
function must take care of initializing the C API pointer array:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">initspam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>
    <span class="k">static</span> <span class="kt">void</span> <span class="o">*</span><span class="n">PySpam_API</span><span class="p">[</span><span class="n">PySpam_API_pointers</span><span class="p">];</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">c_api_object</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;spam&quot;</span><span class="p">,</span> <span class="n">SpamMethods</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="cm">/* Initialize the C API pointer array */</span>
    <span class="n">PySpam_API</span><span class="p">[</span><span class="n">PySpam_System_NUM</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">PySpam_System</span><span class="p">;</span>

    <span class="cm">/* Create a Capsule containing the API pointer array&#39;s address */</span>
    <span class="n">c_api_object</span> <span class="o">=</span> <span class="n">PyCapsule_New</span><span class="p">((</span><span class="kt">void</span> <span class="o">*</span><span class="p">)</span><span class="n">PySpam_API</span><span class="p">,</span> <span class="s">&quot;spam._C_API&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">c_api_object</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;_C_API&quot;</span><span class="p">,</span> <span class="n">c_api_object</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">PySpam_API</span></code> is declared <code class="docutils literal notranslate"><span class="pre">static</span></code>; otherwise the pointer
array would disappear when <code class="xref py py-func docutils literal notranslate"><span class="pre">initspam()</span></code> terminates!</p>
<p>The bulk of the work is in the header file <code class="file docutils literal notranslate"><span class="pre">spammodule.h</span></code>, which looks
like this:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#ifndef Py_SPAMMODULE_H</span>
<span class="cp">#define Py_SPAMMODULE_H</span>
<span class="cp">#ifdef __cplusplus</span>
<span class="k">extern</span> <span class="s">&quot;C&quot;</span> <span class="p">{</span>
<span class="cp">#endif</span>

<span class="cm">/* Header file for spammodule */</span>

<span class="cm">/* C API functions */</span>
<span class="cp">#define PySpam_System_NUM 0</span>
<span class="cp">#define PySpam_System_RETURN int</span>
<span class="cp">#define PySpam_System_PROTO (const char *command)</span>

<span class="cm">/* Total number of C API pointers */</span>
<span class="cp">#define PySpam_API_pointers 1</span>


<span class="cp">#ifdef SPAM_MODULE</span>
<span class="cm">/* This section is used when compiling spammodule.c */</span>

<span class="k">static</span> <span class="n">PySpam_System_RETURN</span> <span class="n">PySpam_System</span> <span class="n">PySpam_System_PROTO</span><span class="p">;</span>

<span class="cp">#else</span>
<span class="cm">/* This section is used in modules that use spammodule&#39;s API */</span>

<span class="k">static</span> <span class="kt">void</span> <span class="o">**</span><span class="n">PySpam_API</span><span class="p">;</span>

<span class="cp">#define PySpam_System \</span>
<span class="cp"> (*(PySpam_System_RETURN (*)PySpam_System_PROTO) PySpam_API[PySpam_System_NUM])</span>

<span class="cm">/* Return -1 on error, 0 on success.</span>
<span class="cm"> * PyCapsule_Import will set an exception if there&#39;s an error.</span>
<span class="cm"> */</span>
<span class="k">static</span> <span class="kt">int</span>
<span class="nf">import_spam</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PySpam_API</span> <span class="o">=</span> <span class="p">(</span><span class="kt">void</span> <span class="o">**</span><span class="p">)</span><span class="n">PyCapsule_Import</span><span class="p">(</span><span class="s">&quot;spam._C_API&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">PySpam_API</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="o">?</span> <span class="mi">0</span> <span class="o">:</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>

<span class="cp">#endif</span>

<span class="cp">#ifdef __cplusplus</span>
<span class="p">}</span>
<span class="cp">#endif</span>

<span class="cp">#endif </span><span class="cm">/* !defined(Py_SPAMMODULE_H) */</span><span class="cp"></span>
</pre></div>
</div>
<p>All that a client module must do in order to have access to the function
<code class="xref c c-func docutils literal notranslate"><span class="pre">PySpam_System()</span></code> is to call the function (or rather macro)
<code class="xref c c-func docutils literal notranslate"><span class="pre">import_spam()</span></code> in its initialization function:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">initclient</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;client&quot;</span><span class="p">,</span> <span class="n">ClientMethods</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">import_spam</span><span class="p">()</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="cm">/* additional initialization can happen here */</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The main disadvantage of this approach is that the file <code class="file docutils literal notranslate"><span class="pre">spammodule.h</span></code> is
rather complicated. However, the basic structure is the same for each function
that is exported, so it has to be learned only once.</p>
<p>Finally it should be mentioned that Capsules offer additional functionality,
which is especially useful for memory allocation and deallocation of the pointer
stored in a Capsule. The details are described in the Python/C API Reference
Manual in the section <a class="reference internal" href="../c-api/capsule.html#capsules"><span class="std std-ref">Capsules</span></a> and in the implementation of Capsules (files
<code class="file docutils literal notranslate"><span class="pre">Include/pycapsule.h</span></code> and <code class="file docutils literal notranslate"><span class="pre">Objects/pycapsule.c</span></code> in the Python source
code distribution).</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>An interface for this function already exists in the standard module <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>
— it was chosen as a simple and straightforward example.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>The metaphor of “borrowing” a reference is not completely correct: the owner
still has a copy of the reference.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id7" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>Checking that the reference count is at least 1 <strong>does not work</strong> — the
reference count itself could be in freed memory and may thus be reused for
another object!</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id8" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[4]</a></td><td>These guarantees don’t hold when you use the “old” style calling convention —
this is still found in much existing code.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">1. Extending Python with C or C++</a><ul>
<li><a class="reference internal" href="#a-simple-example">1.1. A Simple Example</a></li>
<li><a class="reference internal" href="#intermezzo-errors-and-exceptions">1.2. Intermezzo: Errors and Exceptions</a></li>
<li><a class="reference internal" href="#back-to-the-example">1.3. Back to the Example</a></li>
<li><a class="reference internal" href="#the-module-s-method-table-and-initialization-function">1.4. The Module’s Method Table and Initialization Function</a></li>
<li><a class="reference internal" href="#compilation-and-linkage">1.5. Compilation and Linkage</a></li>
<li><a class="reference internal" href="#calling-python-functions-from-c">1.6. Calling Python Functions from C</a></li>
<li><a class="reference internal" href="#extracting-parameters-in-extension-functions">1.7. Extracting Parameters in Extension Functions</a></li>
<li><a class="reference internal" href="#keyword-parameters-for-extension-functions">1.8. Keyword Parameters for Extension Functions</a></li>
<li><a class="reference internal" href="#building-arbitrary-values">1.9. Building Arbitrary Values</a></li>
<li><a class="reference internal" href="#reference-counts">1.10. Reference Counts</a><ul>
<li><a class="reference internal" href="#reference-counting-in-python">1.10.1. Reference Counting in Python</a></li>
<li><a class="reference internal" href="#ownership-rules">1.10.2. Ownership Rules</a></li>
<li><a class="reference internal" href="#thin-ice">1.10.3. Thin Ice</a></li>
<li><a class="reference internal" href="#null-pointers">1.10.4. NULL Pointers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#writing-extensions-in-c">1.11. Writing Extensions in C++</a></li>
<li><a class="reference internal" href="#providing-a-c-api-for-an-extension-module">1.12. Providing a C API for an Extension Module</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Extending and Embedding the Python Interpreter</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="newtypes.html"
                        title="next chapter">2. Defining New Types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/extending.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="newtypes.html" title="2. Defining New Types"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Extending and Embedding the Python Interpreter"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\l?G��/�/html/extending/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Extending and Embedding the Python Interpreter &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. Extending Python with C or C++" href="extending.html" />
    <link rel="prev" title="41. Undocumented Modules" href="../library/undoc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="1. Extending Python with C or C++"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../library/undoc.html" title="41. Undocumented Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="extending-and-embedding-the-python-interpreter">
<span id="extending-index"></span><h1>Extending and Embedding the Python Interpreter<a class="headerlink" href="#extending-and-embedding-the-python-interpreter" title="Permalink to this headline">¶</a></h1>
<p>This document describes how to write modules in C or C++ to extend the Python
interpreter with new modules.  Those modules can not only define new functions
but also new object types and their methods.  The document also describes how
to embed the Python interpreter in another application, for use as an extension
language.  Finally, it shows how to compile and link extension modules so that
they can be loaded dynamically (at run time) into the interpreter, if the
underlying operating system supports this feature.</p>
<p>This document assumes basic knowledge about Python.  For an informal
introduction to the language, see <a class="reference internal" href="../tutorial/index.html#tutorial-index"><span class="std std-ref">The Python Tutorial</span></a>.  <a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a>
gives a more formal definition of the language.  <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a> documents
the existing object types, functions and modules (both built-in and written in
Python) that give the language its wide application range.</p>
<p>For a detailed description of the whole Python/C API, see the separate
<a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This guide only covers the basic tools for creating extensions provided
as part of this version of CPython. Third party tools may offer simpler
alternatives. Refer to the <a class="reference external" href="https://packaging.python.org/en/latest/extensions/">binary extensions section</a> in the Python
Packaging User Guide for more information.</p>
</div>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="extending.html">1. Extending Python with C or C++</a><ul>
<li class="toctree-l2"><a class="reference internal" href="extending.html#a-simple-example">1.1. A Simple Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#intermezzo-errors-and-exceptions">1.2. Intermezzo: Errors and Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#back-to-the-example">1.3. Back to the Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#the-module-s-method-table-and-initialization-function">1.4. The Module’s Method Table and Initialization Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#compilation-and-linkage">1.5. Compilation and Linkage</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#calling-python-functions-from-c">1.6. Calling Python Functions from C</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#extracting-parameters-in-extension-functions">1.7. Extracting Parameters in Extension Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#keyword-parameters-for-extension-functions">1.8. Keyword Parameters for Extension Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#building-arbitrary-values">1.9. Building Arbitrary Values</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#reference-counts">1.10. Reference Counts</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#writing-extensions-in-c">1.11. Writing Extensions in C++</a></li>
<li class="toctree-l2"><a class="reference internal" href="extending.html#providing-a-c-api-for-an-extension-module">1.12. Providing a C API for an Extension Module</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="newtypes.html">2. Defining New Types</a><ul>
<li class="toctree-l2"><a class="reference internal" href="newtypes.html#the-basics">2.1. The Basics</a></li>
<li class="toctree-l2"><a class="reference internal" href="newtypes.html#type-methods">2.2. Type Methods</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="building.html">3. Building C and C++ Extensions with distutils</a><ul>
<li class="toctree-l2"><a class="reference internal" href="building.html#distributing-your-extension-modules">3.1. Distributing your extension modules</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="windows.html">4. Building C and C++ Extensions on Windows</a><ul>
<li class="toctree-l2"><a class="reference internal" href="windows.html#a-cookbook-approach">4.1. A Cookbook Approach</a></li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#differences-between-unix-and-windows">4.2. Differences Between Unix and Windows</a></li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#using-dlls-in-practice">4.3. Using DLLs in Practice</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="embedding.html">5. Embedding Python in Another Application</a><ul>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#very-high-level-embedding">5.1. Very High Level Embedding</a></li>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#beyond-very-high-level-embedding-an-overview">5.2. Beyond Very High Level Embedding: An overview</a></li>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#pure-embedding">5.3. Pure Embedding</a></li>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#extending-embedded-python">5.4. Extending Embedded Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#embedding-python-in-c">5.5. Embedding Python in C++</a></li>
<li class="toctree-l2"><a class="reference internal" href="embedding.html#compiling-and-linking-under-unix-like-systems">5.6. Compiling and Linking under Unix-like systems</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../library/undoc.html"
                        title="previous chapter">41. Undocumented Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="extending.html"
                        title="next chapter">1. Extending Python with C or C++</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="1. Extending Python with C or C++"
             >next</a> |</li>
        <li class="right" >
          <a href="../library/undoc.html" title="41. Undocumented Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�3D���html/extending/newtypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Defining New Types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="3. Building C and C++ Extensions with distutils" href="building.html" />
    <link rel="prev" title="1. Extending Python with C or C++" href="extending.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/newtypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="building.html" title="3. Building C and C++ Extensions with distutils"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="1. Extending Python with C or C++"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="defining-new-types">
<span id="id1"></span><h1>2. Defining New Types<a class="headerlink" href="#defining-new-types" title="Permalink to this headline">¶</a></h1>
<p>As mentioned in the last chapter, Python allows the writer of an extension
module to define new types that can be manipulated from Python code, much like
strings and lists in core Python.</p>
<p>This is not hard; the code for all extension types follows a pattern, but there
are some details that you need to understand before you can get started.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The way new types are defined changed dramatically (and for the better) in
Python 2.2.  This document documents how to define new types for Python 2.2 and
later.  If you need to support older versions of Python, you will need to refer
to <a class="reference external" href="https://www.python.org/doc/versions/">older versions of this documentation</a>.</p>
</div>
<div class="section" id="the-basics">
<span id="dnt-basics"></span><h2>2.1. The Basics<a class="headerlink" href="#the-basics" title="Permalink to this headline">¶</a></h2>
<p>The Python runtime sees all Python objects as variables of type
<a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.  A <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> is not a very magnificent object - it
just contains the refcount and a pointer to the object’s “type object”.  This is
where the action is; the type object determines which (C) functions get called
when, for instance, an attribute gets looked up on an object or it is multiplied
by another object.  These C functions are called “type methods”.</p>
<p>So, if you want to define a new object type, you need to create a new type
object.</p>
<p>This sort of thing can only be explained by example, so here’s a minimal, but
complete, module that defines a new type:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="cm">/* Type-specific fields go here. */</span>
<span class="p">}</span> <span class="n">noddy_NoddyObject</span><span class="p">;</span>

<span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">noddy_NoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>             <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">noddy_NoddyObject</span><span class="p">),</span> <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_itemsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span><span class="p">,</span>        <span class="cm">/* tp_flags */</span>
    <span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">noddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="cp">#ifndef PyMODINIT_FUNC	</span><span class="cm">/* declarations for DLL import/export */</span><span class="cp"></span>
<span class="cp">#define PyMODINIT_FUNC void</span>
<span class="cp">#endif</span>
<span class="n">PyMODINIT_FUNC</span>
<span class="nf">initnoddy</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span> 
<span class="p">{</span>
    <span class="n">PyObject</span><span class="o">*</span> <span class="n">m</span><span class="p">;</span>

    <span class="n">noddy_NoddyType</span><span class="p">.</span><span class="n">tp_new</span> <span class="o">=</span> <span class="n">PyType_GenericNew</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;noddy&quot;</span><span class="p">,</span> <span class="n">noddy_methods</span><span class="p">,</span>
                       <span class="s">&quot;Example module that creates an extension type.&quot;</span><span class="p">);</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Noddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Now that’s quite a bit to take in at once, but hopefully bits will seem familiar
from the last chapter.</p>
<p>The first bit that will be new is:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
<span class="p">}</span> <span class="n">noddy_NoddyObject</span><span class="p">;</span>
</pre></div>
</div>
<p>This is what a Noddy object will contain—in this case, nothing more than every
Python object contains, namely a refcount and a pointer to a type object.  These
are the fields the <code class="docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code> macro brings in.  The reason for the macro
is to standardize the layout and to enable special debugging fields in debug
builds.  Note that there is no semicolon after the <code class="docutils literal notranslate"><span class="pre">PyObject_HEAD</span></code> macro; one
is included in the macro definition.  Be wary of adding one by accident; it’s
easy to do from habit, and your compiler might not complain, but someone else’s
probably will!  (On Windows, MSVC is known to call this an error and refuse to
compile the code.)</p>
<p>For contrast, let’s take a look at the corresponding definition for standard
Python integers:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="kt">long</span> <span class="n">ob_ival</span><span class="p">;</span>
<span class="p">}</span> <span class="n">PyIntObject</span><span class="p">;</span>
</pre></div>
</div>
<p>Moving on, we come to the crunch — the type object.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">noddy_NoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>             <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">noddy_NoddyObject</span><span class="p">),</span> <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_itemsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span><span class="p">,</span>        <span class="cm">/* tp_flags */</span>
    <span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>Now if you go and look up the definition of <a class="reference internal" href="../c-api/type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a> in
<code class="file docutils literal notranslate"><span class="pre">object.h</span></code> you’ll see that it has many more fields that the definition
above.  The remaining fields will be filled with zeros by the C compiler, and
it’s common practice to not specify them explicitly unless you need them.</p>
<p>This is so important that we’re going to pick the top of it apart still
further:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>This line is a bit of a wart; what we’d like to write is:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="o">&amp;</span><span class="n">PyType_Type</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>as the type of a type object is “type”, but this isn’t strictly conforming C and
some compilers complain.  Fortunately, this member will be filled in for us by
<a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>              <span class="cm">/* tp_name */</span>
</pre></div>
</div>
<p>The name of our type.  This will appear in the default textual representation of
our objects and in some error messages, for example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="s">&quot;&quot;</span> <span class="o">+</span> <span class="n">noddy</span><span class="p">.</span><span class="n">new_noddy</span><span class="p">()</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">)</span><span class="o">:</span>
  <span class="n">File</span> <span class="s">&quot;&lt;stdin&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">1</span><span class="p">,</span> <span class="n">in</span> <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span>
<span class="nl">TypeError</span><span class="p">:</span> <span class="n">cannot</span> <span class="n">add</span> <span class="n">type</span> <span class="s">&quot;noddy.Noddy&quot;</span> <span class="n">to</span> <span class="n">string</span>
</pre></div>
</div>
<p>Note that the name is a dotted name that includes both the module name and the
name of the type within the module. The module in this case is <code class="xref py py-mod docutils literal notranslate"><span class="pre">noddy</span></code> and
the type is <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code>, so we set the type name to <code class="xref py py-class docutils literal notranslate"><span class="pre">noddy.Noddy</span></code>.
One side effect of using an undotted name is that the pydoc documentation tool
will not list the new type in the module documentation.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">sizeof</span><span class="p">(</span><span class="n">noddy_NoddyObject</span><span class="p">),</span>  <span class="cm">/* tp_basicsize */</span>
</pre></div>
</div>
<p>This is so that Python knows how much memory to allocate when you call
<a class="reference internal" href="../c-api/allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you want your type to be subclassable from Python, and your type has the same
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> as its base type, you may have problems with multiple
inheritance.  A Python subclass of your type will have to list your type first
in its <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a>, or else it will not be able to call your type’s
<a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method without getting an error.  You can avoid this problem by
ensuring that your type has a larger value for <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_basicsize" title="PyTypeObject.tp_basicsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_basicsize</span></code></a> than its
base type does.  Most of the time, this will be true anyway, because either your
base type will be <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, or else you will be adding data members to
your base type, and therefore increasing its size.</p>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="mi">0</span><span class="p">,</span>                          <span class="cm">/* tp_itemsize */</span>
</pre></div>
</div>
<p>This has to do with variable length objects like lists and strings. Ignore this
for now.</p>
<p>Skipping a number of type methods that we don’t provide, we set the class flags
to <a class="reference internal" href="../c-api/typeobj.html#Py_TPFLAGS_DEFAULT" title="Py_TPFLAGS_DEFAULT"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_DEFAULT</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_TPFLAGS_DEFAULT</span><span class="p">,</span>        <span class="cm">/* tp_flags */</span>
</pre></div>
</div>
<p>All types should include this constant in their flags.  It enables all of the
members defined by the current version of Python.</p>
<p>We provide a doc string for the type in <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_doc" title="PyTypeObject.tp_doc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_doc</span></code></a>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
</pre></div>
</div>
<p>Now we get into the type methods, the things that make your objects different
from the others.  We aren’t going to implement any of these in this version of
the module.  We’ll expand this example later to have more interesting behavior.</p>
<p>For now, all we want to be able to do is to create new <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> objects.
To enable object creation, we have to provide a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> implementation.
In this case, we can just use the default implementation provided by the API
function <a class="reference internal" href="../c-api/type.html#c.PyType_GenericNew" title="PyType_GenericNew"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericNew()</span></code></a>.  We’d like to just assign this to the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> slot, but we can’t, for portability sake, On some platforms or
compilers, we can’t statically initialize a structure member with a function
defined in another C module, so, instead, we’ll assign the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> slot
in the module initialization function just before calling
<a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">noddy_NoddyType</span><span class="p">.</span><span class="n">tp_new</span> <span class="o">=</span> <span class="n">PyType_GenericNew</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span><span class="p">;</span>
</pre></div>
</div>
<p>All the other type methods are <em>NULL</em>, so we’ll go over them later — that’s
for a later section!</p>
<p>Everything else in the file should be familiar, except for some code in
<code class="xref c c-func docutils literal notranslate"><span class="pre">initnoddy()</span></code>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span><span class="p">;</span>
</pre></div>
</div>
<p>This initializes the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> type, filing in a number of members,
including <code class="xref py py-attr docutils literal notranslate"><span class="pre">ob_type</span></code> that we initially set to <em>NULL</em>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Noddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">noddy_NoddyType</span><span class="p">);</span>
</pre></div>
</div>
<p>This adds the type to the module dictionary.  This allows us to create
<code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> instances by calling the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> class:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="n">import</span> <span class="n">noddy</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">mynoddy</span> <span class="o">=</span> <span class="n">noddy</span><span class="p">.</span><span class="n">Noddy</span><span class="p">()</span>
</pre></div>
</div>
<p>That’s it!  All that remains is to build it; put the above code in a file called
<code class="file docutils literal notranslate"><span class="pre">noddy.c</span></code> and</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">from</span> <span class="n">distutils</span><span class="p">.</span><span class="n">core</span> <span class="n">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;noddy&quot;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s">&quot;1.0&quot;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span><span class="n">Extension</span><span class="p">(</span><span class="s">&quot;noddy&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s">&quot;noddy.c&quot;</span><span class="p">])])</span>
</pre></div>
</div>
<p>in a file called <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>; then typing</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python setup.py build
</pre></div>
</div>
<p>at a shell should produce a file <code class="file docutils literal notranslate"><span class="pre">noddy.so</span></code> in a subdirectory; move to
that directory and fire up Python — you should be able to <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">noddy</span></code> and
play around with Noddy objects.</p>
<p>That wasn’t so hard, was it?</p>
<p>Of course, the current Noddy type is pretty uninteresting. It has no data and
doesn’t do anything. It can’t even be subclassed.</p>
<div class="section" id="adding-data-and-methods-to-the-basic-example">
<h3>2.1.1. Adding data and methods to the Basic example<a class="headerlink" href="#adding-data-and-methods-to-the-basic-example" title="Permalink to this headline">¶</a></h3>
<p>Let’s extend the basic example to add some data and methods.  Let’s also make
the type usable as a base class. We’ll create a new module, <code class="xref py py-mod docutils literal notranslate"><span class="pre">noddy2</span></code> that
adds these capabilities:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;structmember.h&quot;</span><span class="cp"></span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="p">;</span> <span class="cm">/* first name */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">last</span><span class="p">;</span>  <span class="cm">/* last name */</span>
    <span class="kt">int</span> <span class="n">number</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Noddy</span><span class="p">;</span>

<span class="k">static</span> <span class="kt">void</span>
<span class="nf">Noddy_dealloc</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_new</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">type</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">;</span>

    <span class="n">self</span> <span class="o">=</span> <span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="p">)</span><span class="n">type</span><span class="o">-&gt;</span><span class="n">tp_alloc</span><span class="p">(</span><span class="n">type</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_init</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">last</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">,</span> <span class="s">&quot;|OOi&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">first</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">last</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span><span class="p">))</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">last</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">last</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>


<span class="k">static</span> <span class="n">PyMemberDef</span> <span class="n">Noddy_members</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">first</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;first name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">last</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;last name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="n">T_INT</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">number</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;noddy number&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_name</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">format</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">format</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;%s %s&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;first&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">args</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;OO&quot;</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">args</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">PyString_Format</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="n">args</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">args</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">Noddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">Noddy_name</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the name, combining the first and last name&quot;</span>
    <span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">NoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>             <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">),</span>             <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_itemsize */</span>
    <span class="p">(</span><span class="n">destructor</span><span class="p">)</span><span class="n">Noddy_dealloc</span><span class="p">,</span> <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span>
        <span class="n">Py_TPFLAGS_BASETYPE</span><span class="p">,</span>   <span class="cm">/* tp_flags */</span>
    <span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_traverse */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_clear */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_richcompare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_weaklistoffset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iter */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iternext */</span>
    <span class="n">Noddy_methods</span><span class="p">,</span>             <span class="cm">/* tp_methods */</span>
    <span class="n">Noddy_members</span><span class="p">,</span>             <span class="cm">/* tp_members */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_base */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dict */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_get */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_set */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dictoffset */</span>
    <span class="p">(</span><span class="n">initproc</span><span class="p">)</span><span class="n">Noddy_init</span><span class="p">,</span>      <span class="cm">/* tp_init */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_alloc */</span>
    <span class="n">Noddy_new</span><span class="p">,</span>                 <span class="cm">/* tp_new */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">module_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="cp">#ifndef PyMODINIT_FUNC	</span><span class="cm">/* declarations for DLL import/export */</span><span class="cp"></span>
<span class="cp">#define PyMODINIT_FUNC void</span>
<span class="cp">#endif</span>
<span class="n">PyMODINIT_FUNC</span>
<span class="nf">initnoddy2</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span><span class="o">*</span> <span class="n">m</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;noddy2&quot;</span><span class="p">,</span> <span class="n">module_methods</span><span class="p">,</span>
                       <span class="s">&quot;Example module that creates an extension type.&quot;</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Noddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>This version of the module has a number of changes.</p>
<p>We’ve added an extra include:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;structmember.h&gt;</span><span class="cp"></span>
</pre></div>
</div>
<p>This include provides declarations that we use to handle attributes, as
described a bit later.</p>
<p>The name of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> object structure has been shortened to
<code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code>.  The type object name has been shortened to <code class="xref py py-class docutils literal notranslate"><span class="pre">NoddyType</span></code>.</p>
<p>The  <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> type now has three data attributes, <em>first</em>, <em>last</em>, and
<em>number</em>.  The <em>first</em> and <em>last</em> variables are Python strings containing first
and last names. The <em>number</em> attribute is an integer.</p>
<p>The object structure is updated accordingly:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">last</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">number</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Noddy</span><span class="p">;</span>
</pre></div>
</div>
<p>Because we now have data to manage, we have to be more careful about object
allocation and deallocation.  At a minimum, we need a deallocation method:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">void</span>
<span class="nf">Noddy_dealloc</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>which is assigned to the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> member:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">destructor</span><span class="p">)</span><span class="n">Noddy_dealloc</span><span class="p">,</span> <span class="cm">/*tp_dealloc*/</span>
</pre></div>
</div>
<p>This method decrements the reference counts of the two Python attributes. We use
<a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> here because the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> members
could be <em>NULL</em>.  It then calls the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_free</span></code></a> member of the object’s type
to free the object’s memory.  Note that the object’s type might not be
<code class="xref py py-class docutils literal notranslate"><span class="pre">NoddyType</span></code>, because the object may be an instance of a subclass.</p>
<p>We want to make sure that the first and last names are initialized to empty
strings, so we provide a new method:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_new</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">type</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">;</span>

    <span class="n">self</span> <span class="o">=</span> <span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="p">)</span><span class="n">type</span><span class="o">-&gt;</span><span class="n">tp_alloc</span><span class="p">(</span><span class="n">type</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
          <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
          <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
          <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
          <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>and install it in the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> member:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Noddy_new</span><span class="p">,</span>                 <span class="cm">/* tp_new */</span>
</pre></div>
</div>
<p>The new member is responsible for creating (as opposed to initializing) objects
of the type.  It is exposed in Python as the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method.  See the
paper titled “Unifying types and classes in Python” for a detailed discussion of
the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method.  One reason to implement a new method is to assure
the initial values of instance variables.  In this case, we use the new method
to make sure that the initial values of the members <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> are not <em>NULL</em>. If we didn’t care whether the initial values were
<em>NULL</em>, we could have used <a class="reference internal" href="../c-api/type.html#c.PyType_GenericNew" title="PyType_GenericNew"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericNew()</span></code></a> as our new method, as we
did before.  <a class="reference internal" href="../c-api/type.html#c.PyType_GenericNew" title="PyType_GenericNew"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericNew()</span></code></a> initializes all of the instance variable
members to <em>NULL</em>.</p>
<p>The new method is a static method that is passed the type being instantiated and
any arguments passed when the type was called, and that returns the new object
created. New methods always accept positional and keyword arguments, but they
often ignore the arguments, leaving the argument handling to initializer
methods. Note that if the type supports subclassing, the type passed may not be
the type being defined.  The new method calls the tp_alloc slot to allocate
memory. We don’t fill the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_alloc</span></code></a> slot ourselves. Rather
<a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> fills it for us by inheriting it from our base class,
which is <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> by default.  Most types use the default allocation.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you are creating a co-operative <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> (one that calls a base type’s
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>), you must <em>not</em> try to determine what method
to call using method resolution order at runtime.  Always statically determine
what type you are going to call, and call its <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a> directly, or via
<code class="docutils literal notranslate"><span class="pre">type-&gt;tp_base-&gt;tp_new</span></code>.  If you do not do this, Python subclasses of your
type that also inherit from other Python-defined classes may not work correctly.
(Specifically, you may not be able to create instances of such subclasses
without getting a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.)</p>
</div>
<p>We provide an initialization function:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_init</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">last</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">,</span> <span class="s">&quot;|OOi&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">first</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">last</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span><span class="p">))</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">last</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">last</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>by filling the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> slot.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">initproc</span><span class="p">)</span><span class="n">Noddy_init</span><span class="p">,</span>         <span class="cm">/* tp_init */</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> slot is exposed in Python as the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method. It
is used to initialize an object after it’s created. Unlike the new method, we
can’t guarantee that the initializer is called.  The initializer isn’t called
when unpickling objects and it can be overridden.  Our initializer accepts
arguments to provide initial values for our instance. Initializers always accept
positional and keyword arguments.</p>
<p>Initializers can be called multiple times.  Anyone can call the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>
method on our objects.  For this reason, we have to be extra careful when
assigning the new values.  We might be tempted, for example to assign the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> member like this:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>But this would be risky.  Our type doesn’t restrict the type of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> member, so it could be any kind of object.  It could have a
destructor that causes code to be executed that tries to access the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> member.  To be paranoid and protect ourselves against this
possibility, we almost always reassign members before decrementing their
reference counts.  When don’t we have to do this?</p>
<ul class="simple">
<li>when we absolutely know that the reference count is greater than 1</li>
<li>when we know that deallocation of the object <a class="footnote-reference" href="#id7" id="id2">[1]</a> will not cause any calls
back into our type’s code</li>
<li>when decrementing a reference count in a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> handler when
garbage-collections is not supported <a class="footnote-reference" href="#id8" id="id3">[2]</a></li>
</ul>
<p>We want to expose our instance variables as attributes. There are a
number of ways to do that. The simplest way is to define member definitions:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMemberDef</span> <span class="n">Noddy_members</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">first</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;first name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">last</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;last name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="n">T_INT</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">number</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;noddy number&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>and put the definitions in the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_members" title="PyTypeObject.tp_members"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_members</span></code></a> slot:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Noddy_members</span><span class="p">,</span>             <span class="cm">/* tp_members */</span>
</pre></div>
</div>
<p>Each member definition has a member name, type, offset, access flags and
documentation string. See the <a class="reference internal" href="#generic-attribute-management"><span class="std std-ref">Generic Attribute Management</span></a> section below for
details.</p>
<p>A disadvantage of this approach is that it doesn’t provide a way to restrict the
types of objects that can be assigned to the Python attributes.  We expect the
first and last names to be strings, but any Python objects can be assigned.
Further, the attributes can be deleted, setting the C pointers to <em>NULL</em>.  Even
though we can make sure the members are initialized to non-<em>NULL</em> values, the
members can be set to <em>NULL</em> if the attributes are deleted.</p>
<p>We define a single method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">name()</span></code>, that outputs the objects name as the
concatenation of the first and last names.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_name</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">format</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">format</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;%s %s&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;first&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">args</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;OO&quot;</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">args</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">PyString_Format</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="n">args</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">args</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The method is implemented as a C function that takes a <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> (or
<code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> subclass) instance as the first argument.  Methods always take an
instance as the first argument. Methods often take positional and keyword
arguments as well, but in this case we don’t take any and don’t need to accept
a positional argument tuple or keyword argument dictionary. This method is
equivalent to the Python method:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">def</span> <span class="n">name</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">:</span>
   <span class="k">return</span> <span class="s">&quot;%s %s&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">self</span><span class="p">.</span><span class="n">first</span><span class="p">,</span> <span class="n">self</span><span class="p">.</span><span class="n">last</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that we have to check for the possibility that our <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> members are <em>NULL</em>.  This is because they can be deleted, in which
case they are set to <em>NULL</em>.  It would be better to prevent deletion of these
attributes and to restrict the attribute values to be strings.  We’ll see how to
do that in the next section.</p>
<p>Now that we’ve defined the method, we need to create an array of method
definitions:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">Noddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">Noddy_name</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the name, combining the first and last name&quot;</span>
    <span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>and assign them to the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_methods</span></code></a> slot:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Noddy_methods</span><span class="p">,</span>             <span class="cm">/* tp_methods */</span>
</pre></div>
</div>
<p>Note that we used the <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a> flag to indicate that the method is
passed no arguments.</p>
<p>Finally, we’ll make our type usable as a base class.  We’ve written our methods
carefully so far so that they don’t make any assumptions about the type of the
object being created or used, so all we need to do is to add the
<a class="reference internal" href="../c-api/typeobj.html#Py_TPFLAGS_BASETYPE" title="Py_TPFLAGS_BASETYPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_BASETYPE</span></code></a> to our class flag definition:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span> <span class="n">Py_TPFLAGS_BASETYPE</span><span class="p">,</span> <span class="cm">/*tp_flags*/</span>
</pre></div>
</div>
<p>We rename <code class="xref c c-func docutils literal notranslate"><span class="pre">initnoddy()</span></code> to <code class="xref c c-func docutils literal notranslate"><span class="pre">initnoddy2()</span></code> and update the module name
passed to <a class="reference internal" href="../c-api/allocation.html#c.Py_InitModule3" title="Py_InitModule3"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_InitModule3()</span></code></a>.</p>
<p>Finally, we update our <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> file to build the new module:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">from</span> <span class="n">distutils</span><span class="p">.</span><span class="n">core</span> <span class="n">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;noddy&quot;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s">&quot;1.0&quot;</span><span class="p">,</span>
      <span class="n">ext_modules</span><span class="o">=</span><span class="p">[</span>
         <span class="n">Extension</span><span class="p">(</span><span class="s">&quot;noddy&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s">&quot;noddy.c&quot;</span><span class="p">]),</span>
         <span class="n">Extension</span><span class="p">(</span><span class="s">&quot;noddy2&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s">&quot;noddy2.c&quot;</span><span class="p">]),</span>
         <span class="p">])</span>
</pre></div>
</div>
</div>
<div class="section" id="providing-finer-control-over-data-attributes">
<h3>2.1.2. Providing finer control over data attributes<a class="headerlink" href="#providing-finer-control-over-data-attributes" title="Permalink to this headline">¶</a></h3>
<p>In this section, we’ll provide finer control over how the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> attributes are set in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> example. In the previous
version of our module, the instance variables <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code>
could be set to non-string values or even deleted. We want to make sure that
these attributes always contain strings.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;structmember.h&quot;</span><span class="cp"></span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">last</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">number</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Noddy</span><span class="p">;</span>

<span class="k">static</span> <span class="kt">void</span>
<span class="nf">Noddy_dealloc</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_new</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">type</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">;</span>

    <span class="n">self</span> <span class="o">=</span> <span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="p">)</span><span class="n">type</span><span class="o">-&gt;</span><span class="n">tp_alloc</span><span class="p">(</span><span class="n">type</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_init</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">last</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">,</span> <span class="s">&quot;|SSi&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">first</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">last</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span><span class="p">))</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">last</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">last</span><span class="p">;</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMemberDef</span> <span class="n">Noddy_members</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="n">T_INT</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">number</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;noddy number&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_getfirst</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_setfirst</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">value</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">&quot;Cannot delete the first attribute&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyString_Check</span><span class="p">(</span><span class="n">value</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span>
                        <span class="s">&quot;The first attribute value must be a string&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_getlast</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_setlast</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">value</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">&quot;Cannot delete the last attribute&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyString_Check</span><span class="p">(</span><span class="n">value</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span>
                        <span class="s">&quot;The last attribute value must be a string&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyGetSetDef</span> <span class="n">Noddy_getseters</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span>
     <span class="p">(</span><span class="n">getter</span><span class="p">)</span><span class="n">Noddy_getfirst</span><span class="p">,</span> <span class="p">(</span><span class="n">setter</span><span class="p">)</span><span class="n">Noddy_setfirst</span><span class="p">,</span>
     <span class="s">&quot;first name&quot;</span><span class="p">,</span>
     <span class="nb">NULL</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;last&quot;</span><span class="p">,</span>
     <span class="p">(</span><span class="n">getter</span><span class="p">)</span><span class="n">Noddy_getlast</span><span class="p">,</span> <span class="p">(</span><span class="n">setter</span><span class="p">)</span><span class="n">Noddy_setlast</span><span class="p">,</span>
     <span class="s">&quot;last name&quot;</span><span class="p">,</span>
     <span class="nb">NULL</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_name</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">format</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">format</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;%s %s&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">args</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;OO&quot;</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">args</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">PyString_Format</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="n">args</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">args</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">Noddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">Noddy_name</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the name, combining the first and last name&quot;</span>
    <span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">NoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>             <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">),</span>             <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_itemsize */</span>
    <span class="p">(</span><span class="n">destructor</span><span class="p">)</span><span class="n">Noddy_dealloc</span><span class="p">,</span> <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span>
        <span class="n">Py_TPFLAGS_BASETYPE</span><span class="p">,</span>   <span class="cm">/* tp_flags */</span>
    <span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_traverse */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_clear */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_richcompare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_weaklistoffset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iter */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iternext */</span>
    <span class="n">Noddy_methods</span><span class="p">,</span>             <span class="cm">/* tp_methods */</span>
    <span class="n">Noddy_members</span><span class="p">,</span>             <span class="cm">/* tp_members */</span>
    <span class="n">Noddy_getseters</span><span class="p">,</span>           <span class="cm">/* tp_getset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_base */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dict */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_get */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_set */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dictoffset */</span>
    <span class="p">(</span><span class="n">initproc</span><span class="p">)</span><span class="n">Noddy_init</span><span class="p">,</span>      <span class="cm">/* tp_init */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_alloc */</span>
    <span class="n">Noddy_new</span><span class="p">,</span>                 <span class="cm">/* tp_new */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">module_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="cp">#ifndef PyMODINIT_FUNC	</span><span class="cm">/* declarations for DLL import/export */</span><span class="cp"></span>
<span class="cp">#define PyMODINIT_FUNC void</span>
<span class="cp">#endif</span>
<span class="n">PyMODINIT_FUNC</span>
<span class="nf">initnoddy3</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span><span class="o">*</span> <span class="n">m</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;noddy3&quot;</span><span class="p">,</span> <span class="n">module_methods</span><span class="p">,</span>
                       <span class="s">&quot;Example module that creates an extension type.&quot;</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Noddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>To provide greater control, over the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> attributes,
we’ll use custom getter and setter functions.  Here are the functions for
getting and setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> attribute:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Noddy_getfirst</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="n">Noddy_setfirst</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">value</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">closure</span><span class="p">)</span>
<span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">value</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">&quot;Cannot delete the first attribute&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyString_Check</span><span class="p">(</span><span class="n">value</span><span class="p">))</span> <span class="p">{</span>
    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span>
                    <span class="s">&quot;The first attribute value must be a string&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
  <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">value</span><span class="p">);</span>
  <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span>

  <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The getter function is passed a <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> object and a “closure”, which is
void pointer. In this case, the closure is ignored. (The closure supports an
advanced usage in which definition data is passed to the getter and setter. This
could, for example, be used to allow a single set of getter and setter functions
that decide the attribute to get or set based on data in the closure.)</p>
<p>The setter function is passed the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> object, the new value, and the
closure. The new value may be <em>NULL</em>, in which case the attribute is being
deleted.  In our setter, we raise an error if the attribute is deleted or if the
attribute value is not a string.</p>
<p>We create an array of <a class="reference internal" href="../c-api/structures.html#c.PyGetSetDef" title="PyGetSetDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyGetSetDef</span></code></a> structures:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyGetSetDef</span> <span class="n">Noddy_getseters</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span>
     <span class="p">(</span><span class="n">getter</span><span class="p">)</span><span class="n">Noddy_getfirst</span><span class="p">,</span> <span class="p">(</span><span class="n">setter</span><span class="p">)</span><span class="n">Noddy_setfirst</span><span class="p">,</span>
     <span class="s">&quot;first name&quot;</span><span class="p">,</span>
     <span class="nb">NULL</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;last&quot;</span><span class="p">,</span>
     <span class="p">(</span><span class="n">getter</span><span class="p">)</span><span class="n">Noddy_getlast</span><span class="p">,</span> <span class="p">(</span><span class="n">setter</span><span class="p">)</span><span class="n">Noddy_setlast</span><span class="p">,</span>
     <span class="s">&quot;last name&quot;</span><span class="p">,</span>
     <span class="nb">NULL</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>and register it in the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_getset" title="PyTypeObject.tp_getset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getset</span></code></a> slot:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Noddy_getseters</span><span class="p">,</span>           <span class="cm">/* tp_getset */</span>
</pre></div>
</div>
<p>to register our attribute getters and setters.</p>
<p>The last item in a <a class="reference internal" href="../c-api/structures.html#c.PyGetSetDef" title="PyGetSetDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyGetSetDef</span></code></a> structure is the closure mentioned
above. In this case, we aren’t using the closure, so we just pass <em>NULL</em>.</p>
<p>We also remove the member definitions for these attributes:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMemberDef</span> <span class="n">Noddy_members</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="n">T_INT</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">number</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;noddy number&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>We also need to update the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_init" title="PyTypeObject.tp_init"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_init</span></code></a> handler to only allow strings <a class="footnote-reference" href="#id9" id="id4">[3]</a> to
be passed:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_init</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">last</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">,</span> <span class="s">&quot;|SSi&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">first</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">last</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span><span class="p">))</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">last</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">last</span><span class="p">;</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>With these changes, we can assure that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code>
members are never <em>NULL</em> so we can remove checks for <em>NULL</em> values in almost all
cases. This means that most of the <a class="reference internal" href="../c-api/refcounting.html#c.Py_XDECREF" title="Py_XDECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_XDECREF()</span></code></a> calls can be converted to
<a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a> calls. The only place we can’t change these calls is in the
deallocator, where there is the possibility that the initialization of these
members failed in the constructor.</p>
<p>We also rename the module initialization function and module name in the
initialization function, as we did before, and we add an extra definition to the
<code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> file.</p>
</div>
<div class="section" id="supporting-cyclic-garbage-collection">
<h3>2.1.3. Supporting cyclic garbage collection<a class="headerlink" href="#supporting-cyclic-garbage-collection" title="Permalink to this headline">¶</a></h3>
<p>Python has a cyclic-garbage collector that can identify unneeded objects even
when their reference counts are not zero. This can happen when objects are
involved in cycles.  For example, consider:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="n">l</span> <span class="o">=</span> <span class="p">[]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">l</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">l</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">del</span> <span class="n">l</span>
</pre></div>
</div>
<p>In this example, we create a list that contains itself. When we delete it, it
still has a reference from itself. Its reference count doesn’t drop to zero.
Fortunately, Python’s cyclic-garbage collector will eventually figure out that
the list is garbage and free it.</p>
<p>In the second version of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> example, we allowed any kind of
object to be stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">first</span></code> or <code class="xref py py-attr docutils literal notranslate"><span class="pre">last</span></code> attributes <a class="footnote-reference" href="#id10" id="id5">[4]</a>. This
means that <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> objects can participate in cycles:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="n">import</span> <span class="n">noddy2</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">n</span> <span class="o">=</span> <span class="n">noddy2</span><span class="p">.</span><span class="n">Noddy</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">l</span> <span class="o">=</span> <span class="p">[</span><span class="n">n</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">n</span><span class="p">.</span><span class="n">first</span> <span class="o">=</span> <span class="n">l</span>
</pre></div>
</div>
<p>This is pretty silly, but it gives us an excuse to add support for the
cyclic-garbage collector to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> example.  To support cyclic
garbage collection, types need to fill two slots and set a class flag that
enables these slots:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;structmember.h&quot;</span><span class="cp"></span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">last</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">number</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Noddy</span><span class="p">;</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_traverse</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">vret</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">vret</span> <span class="o">=</span> <span class="n">visit</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">vret</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">vret</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">vret</span> <span class="o">=</span> <span class="n">visit</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">vret</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">vret</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_clear</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>

    <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">void</span>
<span class="nf">Noddy_dealloc</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject_GC_UnTrack</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
    <span class="n">Noddy_clear</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_new</span><span class="p">(</span><span class="n">PyTypeObject</span> <span class="o">*</span><span class="n">type</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">;</span>

    <span class="n">self</span> <span class="o">=</span> <span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="p">)</span><span class="n">type</span><span class="o">-&gt;</span><span class="n">tp_alloc</span><span class="p">(</span><span class="n">type</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_init</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">first</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">last</span><span class="o">=</span><span class="nb">NULL</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="k">static</span> <span class="kt">char</span> <span class="o">*</span><span class="n">kwlist</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">};</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyArg_ParseTupleAndKeywords</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">,</span> <span class="s">&quot;|OOi&quot;</span><span class="p">,</span> <span class="n">kwlist</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">first</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">last</span><span class="p">,</span>
                                      <span class="o">&amp;</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">number</span><span class="p">))</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">first</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="n">first</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
        <span class="n">Py_INCREF</span><span class="p">(</span><span class="n">last</span><span class="p">);</span>
        <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="n">last</span><span class="p">;</span>
        <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>


<span class="k">static</span> <span class="n">PyMemberDef</span> <span class="n">Noddy_members</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;first&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">first</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;first name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;last&quot;</span><span class="p">,</span> <span class="n">T_OBJECT_EX</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">last</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;last name&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;number&quot;</span><span class="p">,</span> <span class="n">T_INT</span><span class="p">,</span> <span class="n">offsetof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">,</span> <span class="n">number</span><span class="p">),</span> <span class="mi">0</span><span class="p">,</span>
     <span class="s">&quot;noddy number&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Noddy_name</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">format</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">format</span> <span class="o">=</span> <span class="n">PyString_FromString</span><span class="p">(</span><span class="s">&quot;%s %s&quot;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">format</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;first&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span> <span class="s">&quot;last&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">args</span> <span class="o">=</span> <span class="n">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;OO&quot;</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">args</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">PyString_Format</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="n">args</span><span class="p">);</span>
    <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">args</span><span class="p">);</span>

    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">Noddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;name&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">Noddy_name</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the name, combining the first and last name&quot;</span>
    <span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">NoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;noddy.Noddy&quot;</span><span class="p">,</span>             <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">Noddy</span><span class="p">),</span>             <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_itemsize */</span>
    <span class="p">(</span><span class="n">destructor</span><span class="p">)</span><span class="n">Noddy_dealloc</span><span class="p">,</span> <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span>
        <span class="n">Py_TPFLAGS_BASETYPE</span> <span class="o">|</span>
        <span class="n">Py_TPFLAGS_HAVE_GC</span><span class="p">,</span>    <span class="cm">/* tp_flags */</span>
    <span class="s">&quot;Noddy objects&quot;</span><span class="p">,</span>           <span class="cm">/* tp_doc */</span>
    <span class="p">(</span><span class="n">traverseproc</span><span class="p">)</span><span class="n">Noddy_traverse</span><span class="p">,</span>   <span class="cm">/* tp_traverse */</span>
    <span class="p">(</span><span class="n">inquiry</span><span class="p">)</span><span class="n">Noddy_clear</span><span class="p">,</span>           <span class="cm">/* tp_clear */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_richcompare */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_weaklistoffset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iter */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_iternext */</span>
    <span class="n">Noddy_methods</span><span class="p">,</span>             <span class="cm">/* tp_methods */</span>
    <span class="n">Noddy_members</span><span class="p">,</span>             <span class="cm">/* tp_members */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_getset */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_base */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dict */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_get */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_descr_set */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_dictoffset */</span>
    <span class="p">(</span><span class="n">initproc</span><span class="p">)</span><span class="n">Noddy_init</span><span class="p">,</span>      <span class="cm">/* tp_init */</span>
    <span class="mi">0</span><span class="p">,</span>                         <span class="cm">/* tp_alloc */</span>
    <span class="n">Noddy_new</span><span class="p">,</span>                 <span class="cm">/* tp_new */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">module_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">}</span>  <span class="cm">/* Sentinel */</span>
<span class="p">};</span>

<span class="cp">#ifndef PyMODINIT_FUNC	</span><span class="cm">/* declarations for DLL import/export */</span><span class="cp"></span>
<span class="cp">#define PyMODINIT_FUNC void</span>
<span class="cp">#endif</span>
<span class="n">PyMODINIT_FUNC</span>
<span class="nf">initnoddy4</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span><span class="o">*</span> <span class="n">m</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;noddy4&quot;</span><span class="p">,</span> <span class="n">module_methods</span><span class="p">,</span>
                       <span class="s">&quot;Example module that creates an extension type.&quot;</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Noddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">NoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The traversal method provides access to subobjects that could participate in
cycles:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_traverse</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">vret</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">vret</span> <span class="o">=</span> <span class="n">visit</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">vret</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">vret</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">vret</span> <span class="o">=</span> <span class="n">visit</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">,</span> <span class="n">arg</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">vret</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">vret</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>For each subobject that can participate in cycles, we need to call the
<code class="xref c c-func docutils literal notranslate"><span class="pre">visit()</span></code> function, which is passed to the traversal method. The
<code class="xref c c-func docutils literal notranslate"><span class="pre">visit()</span></code> function takes as arguments the subobject and the extra argument
<em>arg</em> passed to the traversal method.  It returns an integer value that must be
returned if it is non-zero.</p>
<p>Python 2.4 and higher provide a <a class="reference internal" href="../c-api/gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a> macro that automates calling
visit functions.  With <a class="reference internal" href="../c-api/gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a>, <code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_traverse()</span></code> can be
simplified:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_traverse</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Note that the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> implementation must name its arguments exactly
<em>visit</em> and <em>arg</em> in order to use <a class="reference internal" href="../c-api/gcsupport.html#c.Py_VISIT" title="Py_VISIT"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_VISIT()</span></code></a>.  This is to encourage
uniformity across these boring implementations.</p>
</div>
<p>We also need to provide a method for clearing any subobjects that can
participate in cycles.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_clear</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>

    <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>

    <span class="n">tmp</span> <span class="o">=</span> <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">tmp</span><span class="p">);</span>

    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Notice the use of a temporary variable in <code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_clear()</span></code>. We use the
temporary variable so that we can set each member to <em>NULL</em> before decrementing
its reference count.  We do this because, as was discussed earlier, if the
reference count drops to zero, we might cause code to run that calls back into
the object.  In addition, because we now support garbage collection, we also
have to worry about code being run that triggers garbage collection.  If garbage
collection is run, our <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> handler could get called. We can’t
take a chance of having <code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_traverse()</span></code> called when a member’s reference
count has dropped to zero and its value hasn’t been set to <em>NULL</em>.</p>
<p>Python 2.4 and higher provide a <a class="reference internal" href="../c-api/refcounting.html#c.Py_CLEAR" title="Py_CLEAR"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CLEAR()</span></code></a> that automates the careful
decrementing of reference counts.  With <a class="reference internal" href="../c-api/refcounting.html#c.Py_CLEAR" title="Py_CLEAR"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CLEAR()</span></code></a>, the
<code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_clear()</span></code> function can be simplified:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Noddy_clear</span><span class="p">(</span><span class="n">Noddy</span> <span class="o">*</span><span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">first</span><span class="p">);</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">last</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that <code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_dealloc()</span></code> may call arbitrary functions through
<code class="docutils literal notranslate"><span class="pre">__del__</span></code> method or weakref callback. It means circular GC can be
triggered inside the function.  Since GC assumes reference count is not zero,
we need to untrack the object from GC by calling <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_UnTrack()</span></code></a>
before clearing members. Here is reimplemented deallocator which uses
<a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_UnTrack()</span></code></a> and <code class="xref c c-func docutils literal notranslate"><span class="pre">Noddy_clear()</span></code>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">void</span>
<span class="nf">Noddy_dealloc</span><span class="p">(</span><span class="n">Noddy</span><span class="o">*</span> <span class="n">self</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject_GC_UnTrack</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
    <span class="n">Noddy_clear</span><span class="p">(</span><span class="n">self</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">self</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Finally, we add the <a class="reference internal" href="../c-api/typeobj.html#Py_TPFLAGS_HAVE_GC" title="Py_TPFLAGS_HAVE_GC"><code class="xref py py-const docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_GC</span></code></a> flag to the class flags:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span> <span class="n">Py_TPFLAGS_BASETYPE</span> <span class="o">|</span> <span class="n">Py_TPFLAGS_HAVE_GC</span><span class="p">,</span> <span class="cm">/* tp_flags */</span>
</pre></div>
</div>
<p>That’s pretty much it.  If we had written custom <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_alloc</span></code></a> or
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_free" title="PyTypeObject.tp_free"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_free</span></code></a> slots, we’d need to modify them for cyclic-garbage collection.
Most extensions will use the versions automatically provided.</p>
</div>
<div class="section" id="subclassing-other-types">
<h3>2.1.4. Subclassing other types<a class="headerlink" href="#subclassing-other-types" title="Permalink to this headline">¶</a></h3>
<p>It is possible to create new extension types that are derived from existing
types. It is easiest to inherit from the built in types, since an extension can
easily use the <code class="xref py py-class docutils literal notranslate"><span class="pre">PyTypeObject</span></code> it needs. It can be difficult to share
these <code class="xref py py-class docutils literal notranslate"><span class="pre">PyTypeObject</span></code> structures between extension modules.</p>
<p>In this example we will create a <code class="xref py py-class docutils literal notranslate"><span class="pre">Shoddy</span></code> type that inherits from the
built-in <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> type. The new type will be completely compatible with
regular lists, but will have an additional <code class="xref py py-meth docutils literal notranslate"><span class="pre">increment()</span></code> method that
increases an internal counter.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;&gt;&gt;</span> <span class="n">import</span> <span class="n">shoddy</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">s</span> <span class="o">=</span> <span class="n">shoddy</span><span class="p">.</span><span class="n">Shoddy</span><span class="p">(</span><span class="n">range</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">s</span><span class="p">.</span><span class="n">extend</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">print</span> <span class="n">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="mi">6</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">print</span> <span class="n">s</span><span class="p">.</span><span class="n">increment</span><span class="p">()</span>
<span class="mi">1</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">print</span> <span class="n">s</span><span class="p">.</span><span class="n">increment</span><span class="p">()</span>
<span class="mi">2</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>

<span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyListObject</span> <span class="n">list</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">state</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Shoddy</span><span class="p">;</span>


<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">Shoddy_increment</span><span class="p">(</span><span class="n">Shoddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">unused</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">state</span><span class="o">++</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">PyInt_FromLong</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">state</span><span class="p">);</span>
<span class="p">}</span>


<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">Shoddy_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;increment&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">Shoddy_increment</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span>
     <span class="n">PyDoc_STR</span><span class="p">(</span><span class="s">&quot;increment state counter&quot;</span><span class="p">)},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span>	<span class="nb">NULL</span><span class="p">},</span>
<span class="p">};</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">Shoddy_init</span><span class="p">(</span><span class="n">Shoddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyList_Type</span><span class="p">.</span><span class="n">tp_init</span><span class="p">((</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">state</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>


<span class="k">static</span> <span class="n">PyTypeObject</span> <span class="n">ShoddyType</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyVarObject_HEAD_INIT</span><span class="p">(</span><span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="s">&quot;shoddy.Shoddy&quot;</span><span class="p">,</span>         <span class="cm">/* tp_name */</span>
    <span class="k">sizeof</span><span class="p">(</span><span class="n">Shoddy</span><span class="p">),</span>          <span class="cm">/* tp_basicsize */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_itemsize */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_dealloc */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_print */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_getattr */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_setattr */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_compare */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_repr */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_as_number */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_as_sequence */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_as_mapping */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_hash */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_call */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_str */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_getattro */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_setattro */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_as_buffer */</span>
    <span class="n">Py_TPFLAGS_DEFAULT</span> <span class="o">|</span>
        <span class="n">Py_TPFLAGS_BASETYPE</span><span class="p">,</span> <span class="cm">/* tp_flags */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_doc */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_traverse */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_clear */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_richcompare */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_weaklistoffset */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_iter */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_iternext */</span>
    <span class="n">Shoddy_methods</span><span class="p">,</span>          <span class="cm">/* tp_methods */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_members */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_getset */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_base */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_dict */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_descr_get */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_descr_set */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_dictoffset */</span>
    <span class="p">(</span><span class="n">initproc</span><span class="p">)</span><span class="n">Shoddy_init</span><span class="p">,</span>   <span class="cm">/* tp_init */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_alloc */</span>
    <span class="mi">0</span><span class="p">,</span>                       <span class="cm">/* tp_new */</span>
<span class="p">};</span>

<span class="n">PyMODINIT_FUNC</span>
<span class="nf">initshoddy</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>

    <span class="n">ShoddyType</span><span class="p">.</span><span class="n">tp_base</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">PyList_Type</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;shoddy&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="s">&quot;Shoddy module&quot;</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Shoddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span> <span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>As you can see, the source code closely resembles the <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> examples in
previous sections. We will break down the main differences between them.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyListObject</span> <span class="n">list</span><span class="p">;</span>
    <span class="kt">int</span> <span class="n">state</span><span class="p">;</span>
<span class="p">}</span> <span class="n">Shoddy</span><span class="p">;</span>
</pre></div>
</div>
<p>The primary difference for derived type objects is that the base type’s object
structure must be the first value. The base type will already include the
<a class="reference internal" href="../c-api/structures.html#c.PyObject_HEAD" title="PyObject_HEAD"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HEAD()</span></code></a> at the beginning of its structure.</p>
<p>When a Python object is a <code class="xref py py-class docutils literal notranslate"><span class="pre">Shoddy</span></code> instance, its <em>PyObject*</em> pointer can
be safely cast to both <em>PyListObject*</em> and <em>Shoddy*</em>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">Shoddy_init</span><span class="p">(</span><span class="n">Shoddy</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">kwds</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyList_Type</span><span class="p">.</span><span class="n">tp_init</span><span class="p">((</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
       <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="n">self</span><span class="o">-&gt;</span><span class="n">state</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__init__</span></code> method for our type, we can see how to call through to
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__init__</span></code> method of the base type.</p>
<p>This pattern is important when writing a type with custom <a class="reference internal" href="../library/new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-attr docutils literal notranslate"><span class="pre">new</span></code></a> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">dealloc</span></code> methods. The <a class="reference internal" href="../library/new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-attr docutils literal notranslate"><span class="pre">new</span></code></a> method should not actually create the
memory for the object with <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_alloc</span></code></a>, that will be handled by the base
class when calling its <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_new" title="PyTypeObject.tp_new"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_new</span></code></a>.</p>
<p>When filling out the <a class="reference internal" href="../c-api/type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTypeObject()</span></code></a> for the <code class="xref py py-class docutils literal notranslate"><span class="pre">Shoddy</span></code> type, you see
a slot for <code class="xref c c-func docutils literal notranslate"><span class="pre">tp_base()</span></code>. Due to cross platform compiler issues, you can’t
fill that field directly with the <a class="reference internal" href="../c-api/list.html#c.PyList_Type" title="PyList_Type"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Type()</span></code></a>; it can be done later in
the module’s <code class="xref c c-func docutils literal notranslate"><span class="pre">init()</span></code> function.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyMODINIT_FUNC</span>
<span class="nf">initshoddy</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">;</span>

    <span class="n">ShoddyType</span><span class="p">.</span><span class="n">tp_base</span> <span class="o">=</span> <span class="o">&amp;</span><span class="n">PyList_Type</span><span class="p">;</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">PyType_Ready</span><span class="p">(</span><span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">m</span> <span class="o">=</span> <span class="n">Py_InitModule3</span><span class="p">(</span><span class="s">&quot;shoddy&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="s">&quot;Shoddy module&quot;</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">m</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="n">Py_INCREF</span><span class="p">(</span><span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">);</span>
    <span class="n">PyModule_AddObject</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s">&quot;Shoddy&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span> <span class="o">&amp;</span><span class="n">ShoddyType</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Before calling <a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a>, the type structure must have the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_base" title="PyTypeObject.tp_base"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_base</span></code></a> slot filled in. When we are deriving a new type, it is not
necessary to fill out the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_alloc" title="PyTypeObject.tp_alloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_alloc</span></code></a> slot with <a class="reference internal" href="../c-api/type.html#c.PyType_GenericNew" title="PyType_GenericNew"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_GenericNew()</span></code></a>
– the allocate function from the base type will be inherited.</p>
<p>After that, calling <a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> and adding the type object to the
module is the same as with the basic <code class="xref py py-class docutils literal notranslate"><span class="pre">Noddy</span></code> examples.</p>
</div>
</div>
<div class="section" id="type-methods">
<span id="dnt-type-methods"></span><h2>2.2. Type Methods<a class="headerlink" href="#type-methods" title="Permalink to this headline">¶</a></h2>
<p>This section aims to give a quick fly-by on the various type methods you can
implement and what they do.</p>
<p>Here is the definition of <a class="reference internal" href="../c-api/type.html#c.PyTypeObject" title="PyTypeObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyTypeObject</span></code></a>, with some fields only used in
debug builds omitted:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="n">_typeobject</span> <span class="p">{</span>
    <span class="n">PyObject_VAR_HEAD</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">tp_name</span><span class="p">;</span> <span class="cm">/* For printing, in format &quot;&lt;module&gt;.&lt;name&gt;&quot; */</span>
    <span class="kt">int</span> <span class="n">tp_basicsize</span><span class="p">,</span> <span class="n">tp_itemsize</span><span class="p">;</span> <span class="cm">/* For allocation */</span>

    <span class="cm">/* Methods to implement standard operations */</span>

    <span class="n">destructor</span> <span class="n">tp_dealloc</span><span class="p">;</span>
    <span class="n">printfunc</span> <span class="n">tp_print</span><span class="p">;</span>
    <span class="n">getattrfunc</span> <span class="n">tp_getattr</span><span class="p">;</span>
    <span class="n">setattrfunc</span> <span class="n">tp_setattr</span><span class="p">;</span>
    <span class="n">cmpfunc</span> <span class="n">tp_compare</span><span class="p">;</span>
    <span class="n">reprfunc</span> <span class="n">tp_repr</span><span class="p">;</span>

    <span class="cm">/* Method suites for standard classes */</span>

    <span class="n">PyNumberMethods</span> <span class="o">*</span><span class="n">tp_as_number</span><span class="p">;</span>
    <span class="n">PySequenceMethods</span> <span class="o">*</span><span class="n">tp_as_sequence</span><span class="p">;</span>
    <span class="n">PyMappingMethods</span> <span class="o">*</span><span class="n">tp_as_mapping</span><span class="p">;</span>

    <span class="cm">/* More standard operations (here for binary compatibility) */</span>

    <span class="n">hashfunc</span> <span class="n">tp_hash</span><span class="p">;</span>
    <span class="n">ternaryfunc</span> <span class="n">tp_call</span><span class="p">;</span>
    <span class="n">reprfunc</span> <span class="n">tp_str</span><span class="p">;</span>
    <span class="n">getattrofunc</span> <span class="n">tp_getattro</span><span class="p">;</span>
    <span class="n">setattrofunc</span> <span class="n">tp_setattro</span><span class="p">;</span>

    <span class="cm">/* Functions to access object as input/output buffer */</span>
    <span class="n">PyBufferProcs</span> <span class="o">*</span><span class="n">tp_as_buffer</span><span class="p">;</span>

    <span class="cm">/* Flags to define presence of optional/expanded features */</span>
    <span class="kt">long</span> <span class="n">tp_flags</span><span class="p">;</span>

    <span class="kt">char</span> <span class="o">*</span><span class="n">tp_doc</span><span class="p">;</span> <span class="cm">/* Documentation string */</span>

    <span class="cm">/* Assigned meaning in release 2.0 */</span>
    <span class="cm">/* call function for all accessible objects */</span>
    <span class="n">traverseproc</span> <span class="n">tp_traverse</span><span class="p">;</span>

    <span class="cm">/* delete references to contained objects */</span>
    <span class="n">inquiry</span> <span class="n">tp_clear</span><span class="p">;</span>

    <span class="cm">/* Assigned meaning in release 2.1 */</span>
    <span class="cm">/* rich comparisons */</span>
    <span class="n">richcmpfunc</span> <span class="n">tp_richcompare</span><span class="p">;</span>

    <span class="cm">/* weak reference enabler */</span>
    <span class="kt">long</span> <span class="n">tp_weaklistoffset</span><span class="p">;</span>

    <span class="cm">/* Added in release 2.2 */</span>
    <span class="cm">/* Iterators */</span>
    <span class="n">getiterfunc</span> <span class="n">tp_iter</span><span class="p">;</span>
    <span class="n">iternextfunc</span> <span class="n">tp_iternext</span><span class="p">;</span>

    <span class="cm">/* Attribute descriptor and subclassing stuff */</span>
    <span class="k">struct</span> <span class="n">PyMethodDef</span> <span class="o">*</span><span class="n">tp_methods</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">PyMemberDef</span> <span class="o">*</span><span class="n">tp_members</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">PyGetSetDef</span> <span class="o">*</span><span class="n">tp_getset</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">_typeobject</span> <span class="o">*</span><span class="n">tp_base</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_dict</span><span class="p">;</span>
    <span class="n">descrgetfunc</span> <span class="n">tp_descr_get</span><span class="p">;</span>
    <span class="n">descrsetfunc</span> <span class="n">tp_descr_set</span><span class="p">;</span>
    <span class="kt">long</span> <span class="n">tp_dictoffset</span><span class="p">;</span>
    <span class="n">initproc</span> <span class="n">tp_init</span><span class="p">;</span>
    <span class="n">allocfunc</span> <span class="n">tp_alloc</span><span class="p">;</span>
    <span class="n">newfunc</span> <span class="n">tp_new</span><span class="p">;</span>
    <span class="n">freefunc</span> <span class="n">tp_free</span><span class="p">;</span> <span class="cm">/* Low-level free-memory routine */</span>
    <span class="n">inquiry</span> <span class="n">tp_is_gc</span><span class="p">;</span> <span class="cm">/* For PyObject_IS_GC */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_bases</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_mro</span><span class="p">;</span> <span class="cm">/* method resolution order */</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_cache</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_subclasses</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">tp_weaklist</span><span class="p">;</span>

<span class="p">}</span> <span class="n">PyTypeObject</span><span class="p">;</span>
</pre></div>
</div>
<p>Now that’s a <em>lot</em> of methods.  Don’t worry too much though - if you have a type
you want to define, the chances are very good that you will only implement a
handful of these.</p>
<p>As you probably expect by now, we’re going to go over this and give more
information about the various handlers.  We won’t go in the order they are
defined in the structure, because there is a lot of historical baggage that
impacts the ordering of the fields; be sure your type initialization keeps the
fields in the right order!  It’s often easiest to find an example that includes
all the fields you need (even if they’re initialized to <code class="docutils literal notranslate"><span class="pre">0</span></code>) and then change
the values to suit your new type.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">char</span> <span class="o">*</span><span class="n">tp_name</span><span class="p">;</span> <span class="cm">/* For printing */</span>
</pre></div>
</div>
<p>The name of the type - as mentioned in the last section, this will appear in
various places, almost entirely for diagnostic purposes. Try to choose something
that will be helpful in such a situation!</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">int</span> <span class="n">tp_basicsize</span><span class="p">,</span> <span class="n">tp_itemsize</span><span class="p">;</span> <span class="cm">/* For allocation */</span>
</pre></div>
</div>
<p>These fields tell the runtime how much memory to allocate when new objects of
this type are created.  Python has some built-in support for variable length
structures (think: strings, lists) which is where the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_itemsize</span></code></a> field
comes in.  This will be dealt with later.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">char</span> <span class="o">*</span><span class="n">tp_doc</span><span class="p">;</span>
</pre></div>
</div>
<p>Here you can put a string (or its address) that you want returned when the
Python script references <code class="docutils literal notranslate"><span class="pre">obj.__doc__</span></code> to retrieve the doc string.</p>
<p>Now we come to the basic type methods—the ones most extension types will
implement.</p>
<div class="section" id="finalization-and-de-allocation">
<h3>2.2.1. Finalization and De-allocation<a class="headerlink" href="#finalization-and-de-allocation" title="Permalink to this headline">¶</a></h3>
<div class="highlight-c notranslate" id="index-0"><div class="highlight"><pre><span></span><span class="n">destructor</span> <span class="n">tp_dealloc</span><span class="p">;</span>
</pre></div>
</div>
<p>This function is called when the reference count of the instance of your type is
reduced to zero and the Python interpreter wants to reclaim it.  If your type
has memory to free or other clean-up to perform, you can put it here.  The
object itself needs to be freed here as well.  Here is an example of this
function:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">void</span>
<span class="nf">newdatatype_dealloc</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span> <span class="n">obj</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">free</span><span class="p">(</span><span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="p">);</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">(</span><span class="n">obj</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p id="index-1">One important requirement of the deallocator function is that it leaves any
pending exceptions alone.  This is important since deallocators are frequently
called as the interpreter unwinds the Python stack; when the stack is unwound
due to an exception (rather than normal returns), nothing is done to protect the
deallocators from seeing that an exception has already been set.  Any actions
which a deallocator performs which may cause additional Python code to be
executed may detect that an exception has been set.  This can lead to misleading
errors from the interpreter.  The proper way to protect against this is to save
a pending exception before performing the unsafe action, and restoring it when
done.  This can be done using the <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Fetch" title="PyErr_Fetch"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Fetch()</span></code></a> and
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Restore" title="PyErr_Restore"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Restore()</span></code></a> functions:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">void</span>
<span class="nf">my_dealloc</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">obj</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">MyObject</span> <span class="o">*</span><span class="n">self</span> <span class="o">=</span> <span class="p">(</span><span class="n">MyObject</span> <span class="o">*</span><span class="p">)</span> <span class="n">obj</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">cbresult</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">my_callback</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyObject</span> <span class="o">*</span><span class="n">err_type</span><span class="p">,</span> <span class="o">*</span><span class="n">err_value</span><span class="p">,</span> <span class="o">*</span><span class="n">err_traceback</span><span class="p">;</span>
        <span class="kt">int</span> <span class="n">have_error</span> <span class="o">=</span> <span class="n">PyErr_Occurred</span><span class="p">()</span> <span class="o">?</span> <span class="mi">1</span> <span class="o">:</span> <span class="mi">0</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">have_error</span><span class="p">)</span>
            <span class="n">PyErr_Fetch</span><span class="p">(</span><span class="o">&amp;</span><span class="n">err_type</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">err_value</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">err_traceback</span><span class="p">);</span>

        <span class="n">cbresult</span> <span class="o">=</span> <span class="n">PyObject_CallObject</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">my_callback</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">cbresult</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
            <span class="n">PyErr_WriteUnraisable</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">my_callback</span><span class="p">);</span>
        <span class="k">else</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">cbresult</span><span class="p">);</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">have_error</span><span class="p">)</span>
            <span class="n">PyErr_Restore</span><span class="p">(</span><span class="n">err_type</span><span class="p">,</span> <span class="n">err_value</span><span class="p">,</span> <span class="n">err_traceback</span><span class="p">);</span>

        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">self</span><span class="o">-&gt;</span><span class="n">my_callback</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="n">Py_TYPE</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">tp_free</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span><span class="n">self</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="object-presentation">
<h3>2.2.2. Object Presentation<a class="headerlink" href="#object-presentation" title="Permalink to this headline">¶</a></h3>
<p id="index-2">In Python, there are three ways to generate a textual representation of an
object: the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function (or equivalent back-tick syntax), the
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function, and the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.  For most objects, the
<a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement is equivalent to the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function, but it is
possible to special-case printing to a <code class="xref c c-type docutils literal notranslate"><span class="pre">FILE*</span></code> if necessary; this should
only be done if efficiency is identified as a problem and profiling suggests
that creating a temporary string object to be written to a file is too
expensive.</p>
<p>These handlers are all optional, and most types at most need to implement the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> and <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> handlers.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">reprfunc</span> <span class="n">tp_repr</span><span class="p">;</span>
<span class="n">reprfunc</span> <span class="n">tp_str</span><span class="p">;</span>
<span class="n">printfunc</span> <span class="n">tp_print</span><span class="p">;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> handler should return a string object containing a
representation of the instance for which it is called.  Here is a simple
example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">newdatatype_repr</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span> <span class="n">obj</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">PyString_FromFormat</span><span class="p">(</span><span class="s">&quot;Repr-ified_newdatatype{{size:\%d}}&quot;</span><span class="p">,</span>
                               <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>If no <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> handler is specified, the interpreter will supply a
representation that uses the type’s <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_name" title="PyTypeObject.tp_name"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_name</span></code></a> and a uniquely-identifying
value for the object.</p>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> handler is to <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> what the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> handler
described above is to <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>; that is, it is called when Python code calls
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> on an instance of your object.  Its implementation is very similar
to the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> function, but the resulting string is intended for human
consumption.  If <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_str</span></code></a> is not specified, the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_repr</span></code></a> handler is
used instead.</p>
<p>Here is a simple example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">newdatatype_str</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span> <span class="n">obj</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">PyString_FromFormat</span><span class="p">(</span><span class="s">&quot;Stringified_newdatatype{{size:\%d}}&quot;</span><span class="p">,</span>
                               <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The print function will be called whenever Python needs to “print” an instance
of the type.  For example, if ‘node’ is an instance of type TreeNode, then the
print function is called when Python code calls:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">print</span> <span class="n">node</span>
</pre></div>
</div>
<p>There is a flags argument and one flag, <code class="xref py py-const docutils literal notranslate"><span class="pre">Py_PRINT_RAW</span></code>, and it suggests
that you print without string quotes and possibly without interpreting escape
sequences.</p>
<p>The print function receives a file object as an argument. You will likely want
to write to that file object.</p>
<p>Here is a sample print function:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">newdatatype_print</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="kt">FILE</span> <span class="o">*</span><span class="n">fp</span><span class="p">,</span> <span class="kt">int</span> <span class="n">flags</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">flags</span> <span class="o">&amp;</span> <span class="n">Py_PRINT_RAW</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="s">&quot;&lt;{newdatatype object--size: %d}&gt;&quot;</span><span class="p">,</span>
                <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">else</span> <span class="p">{</span>
        <span class="n">fprintf</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="s">&quot;</span><span class="se">\&quot;</span><span class="s">&lt;{newdatatype object--size: %d}&gt;</span><span class="se">\&quot;</span><span class="s">&quot;</span><span class="p">,</span>
                <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="attribute-management">
<h3>2.2.3. Attribute Management<a class="headerlink" href="#attribute-management" title="Permalink to this headline">¶</a></h3>
<p>For every object which can support attributes, the corresponding type must
provide the functions that control how the attributes are resolved.  There needs
to be a function which can retrieve attributes (if any are defined), and another
to set attributes (if setting attributes is allowed).  Removing an attribute is
a special case, for which the new value passed to the handler is <em>NULL</em>.</p>
<p>Python supports two pairs of attribute handlers; a type that supports attributes
only needs to implement the functions for one pair.  The difference is that one
pair takes the name of the attribute as a <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>, while the other
accepts a <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a>.  Each type can use whichever pair makes more
sense for the implementation’s convenience.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">getattrfunc</span>  <span class="n">tp_getattr</span><span class="p">;</span>        <span class="cm">/* char * version */</span>
<span class="n">setattrfunc</span>  <span class="n">tp_setattr</span><span class="p">;</span>
<span class="cm">/* ... */</span>
<span class="n">getattrofunc</span> <span class="n">tp_getattrofunc</span><span class="p">;</span>   <span class="cm">/* PyObject * version */</span>
<span class="n">setattrofunc</span> <span class="n">tp_setattrofunc</span><span class="p">;</span>
</pre></div>
</div>
<p>If accessing attributes of an object is always a simple operation (this will be
explained shortly), there are generic implementations which can be used to
provide the <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> version of the attribute management functions.
The actual need for type-specific attribute handlers almost completely
disappeared starting with Python 2.2, though there are many examples which have
not been updated to use some of the new generic mechanism that is available.</p>
<div class="section" id="generic-attribute-management">
<span id="id6"></span><h4>2.2.3.1. Generic Attribute Management<a class="headerlink" href="#generic-attribute-management" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>Most extension types only use <em>simple</em> attributes.  So, what makes the
attributes simple?  There are only a couple of conditions that must be met:</p>
<ol class="arabic simple">
<li>The name of the attributes must be known when <a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> is
called.</li>
<li>No special processing is needed to record that an attribute was looked up or
set, nor do actions need to be taken based on the value.</li>
</ol>
<p>Note that this list does not place any restrictions on the values of the
attributes, when the values are computed, or how relevant data is stored.</p>
<p>When <a class="reference internal" href="../c-api/type.html#c.PyType_Ready" title="PyType_Ready"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyType_Ready()</span></code></a> is called, it uses three tables referenced by the
type object to create <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a>s which are placed in the dictionary of the
type object.  Each descriptor controls access to one attribute of the instance
object.  Each of the tables is optional; if all three are <em>NULL</em>, instances of
the type will only have attributes that are inherited from their base type, and
should leave the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattro</span></code></a> and <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattro</span></code></a> fields <em>NULL</em> as
well, allowing the base type to handle attributes.</p>
<p>The tables are declared as three fields of the type object:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">struct</span> <span class="n">PyMethodDef</span> <span class="o">*</span><span class="n">tp_methods</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">PyMemberDef</span> <span class="o">*</span><span class="n">tp_members</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">PyGetSetDef</span> <span class="o">*</span><span class="n">tp_getset</span><span class="p">;</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_methods</span></code></a> is not <em>NULL</em>, it must refer to an array of
<a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structures.  Each entry in the table is an instance of this
structure:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="n">PyMethodDef</span> <span class="p">{</span>
    <span class="k">const</span> <span class="kt">char</span>  <span class="o">*</span><span class="n">ml_name</span><span class="p">;</span>       <span class="cm">/* method name */</span>
    <span class="n">PyCFunction</span>  <span class="n">ml_meth</span><span class="p">;</span>       <span class="cm">/* implementation function */</span>
    <span class="kt">int</span>          <span class="n">ml_flags</span><span class="p">;</span>      <span class="cm">/* flags */</span>
    <span class="k">const</span> <span class="kt">char</span>  <span class="o">*</span><span class="n">ml_doc</span><span class="p">;</span>        <span class="cm">/* docstring */</span>
<span class="p">}</span> <span class="n">PyMethodDef</span><span class="p">;</span>
</pre></div>
</div>
<p>One entry should be defined for each method provided by the type; no entries are
needed for methods inherited from a base type.  One additional entry is needed
at the end; it is a sentinel that marks the end of the array.  The
<code class="xref py py-attr docutils literal notranslate"><span class="pre">ml_name</span></code> field of the sentinel must be <em>NULL</em>.</p>
<p>XXX Need to refer to some unified discussion of the structure fields, shared
with the next section.</p>
<p>The second table is used to define attributes which map directly to data stored
in the instance.  A variety of primitive C types are supported, and access may
be read-only or read-write.  The structures in the table are defined as:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="n">PyMemberDef</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">;</span>
    <span class="kt">int</span>   <span class="n">type</span><span class="p">;</span>
    <span class="kt">int</span>   <span class="n">offset</span><span class="p">;</span>
    <span class="kt">int</span>   <span class="n">flags</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">doc</span><span class="p">;</span>
<span class="p">}</span> <span class="n">PyMemberDef</span><span class="p">;</span>
</pre></div>
</div>
<p>For each entry in the table, a <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a> will be constructed and added to the
type which will be able to extract a value from the instance structure.  The
<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> field should contain one of the type codes defined in the
<code class="file docutils literal notranslate"><span class="pre">structmember.h</span></code> header; the value will be used to determine how to
convert Python values to and from C values.  The <code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code> field is used to
store flags which control how the attribute can be accessed.</p>
<p>XXX Need to move some of this to a shared section!</p>
<p>The following flag constants are defined in <code class="file docutils literal notranslate"><span class="pre">structmember.h</span></code>; they may be
combined using bitwise-OR.</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">READONLY</span></code></td>
<td>Never writable.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">RO</span></code></td>
<td>Shorthand for <code class="xref py py-const docutils literal notranslate"><span class="pre">READONLY</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">READ_RESTRICTED</span></code></td>
<td>Not readable in restricted mode.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">WRITE_RESTRICTED</span></code></td>
<td>Not writable in restricted mode.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">RESTRICTED</span></code></td>
<td>Not readable or writable in restricted mode.</td>
</tr>
</tbody>
</table>
<p id="index-3">An interesting advantage of using the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_members" title="PyTypeObject.tp_members"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_members</span></code></a> table to build
descriptors that are used at runtime is that any attribute defined this way can
have an associated doc string simply by providing the text in the table.  An
application can use the introspection API to retrieve the descriptor from the
class object, and get the doc string using its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attribute.</p>
<p>As with the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_methods</span></code></a> table, a sentinel entry with a <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> value
of <em>NULL</em> is required.</p>
</div>
<div class="section" id="type-specific-attribute-management">
<h4>2.2.3.2. Type-specific Attribute Management<a class="headerlink" href="#type-specific-attribute-management" title="Permalink to this headline">¶</a></h4>
<p>For simplicity, only the <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code> version will be demonstrated here; the
type of the name parameter is the only difference between the <code class="xref c c-type docutils literal notranslate"><span class="pre">char*</span></code>
and <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> flavors of the interface. This example effectively does
the same thing as the generic example above, but does not use the generic
support added in Python 2.2.  The value in showing this is two-fold: it
demonstrates how basic attribute management can be done in a way that is
portable to older versions of Python, and explains how the handler functions are
called, so that if you do need to extend their functionality, you’ll understand
what needs to be done.</p>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_getattr</span></code></a> handler is called when the object requires an attribute
look-up.  It is called in the same situations where the <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>
method of a class would be called.</p>
<p>A likely way to handle this is (1) to implement a set of functions (such as
<code class="xref c c-func docutils literal notranslate"><span class="pre">newdatatype_getSize()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">newdatatype_setSize()</span></code> in the example
below), (2) provide a method table listing these functions, and (3) provide a
getattr function that returns the result of a lookup in that table.  The method
table uses the same structure as the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_methods</span></code></a> field of the type
object.</p>
<p>Here is an example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">newdatatype_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;getSize&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">newdatatype_getSize</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
     <span class="s">&quot;Return the current size.&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="s">&quot;setSize&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">newdatatype_setSize</span><span class="p">,</span> <span class="n">METH_VARARGS</span><span class="p">,</span>
     <span class="s">&quot;Set the size.&quot;</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>           <span class="cm">/* sentinel */</span>
<span class="p">};</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">newdatatype_getattr</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">Py_FindMethod</span><span class="p">(</span><span class="n">newdatatype_methods</span><span class="p">,</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span><span class="n">obj</span><span class="p">,</span> <span class="n">name</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> handler is called when the <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> or
<a class="reference internal" href="../reference/datamodel.html#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delattr__()</span></code></a> method of a class instance would be called.  When an
attribute should be deleted, the third parameter will be <em>NULL</em>.  Here is an
example that simply raises an exception; if this were really all you wanted, the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_setattr</span></code></a> handler should be set to <em>NULL</em>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">newdatatype_setattr</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">v</span><span class="p">)</span>
<span class="p">{</span>
    <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="n">PyErr_Format</span><span class="p">(</span><span class="n">PyExc_RuntimeError</span><span class="p">,</span> <span class="s">&quot;Read-only attribute: \%s&quot;</span><span class="p">,</span> <span class="n">name</span><span class="p">);</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="object-comparison">
<h3>2.2.4. Object Comparison<a class="headerlink" href="#object-comparison" title="Permalink to this headline">¶</a></h3>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">cmpfunc</span> <span class="n">tp_compare</span><span class="p">;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a> handler is called when comparisons are needed and the
object does not implement the specific rich comparison method which matches the
requested comparison.  (It is always used if defined and the
<a class="reference internal" href="../c-api/object.html#c.PyObject_Compare" title="PyObject_Compare"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Compare()</span></code></a> or <a class="reference internal" href="../c-api/object.html#c.PyObject_Cmp" title="PyObject_Cmp"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Cmp()</span></code></a> functions are used, or if
<a class="reference internal" href="../library/functions.html#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a> is used from Python.) It is analogous to the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method.
This function should return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if <em>obj1</em> is less than <em>obj2</em>, <code class="docutils literal notranslate"><span class="pre">0</span></code> if they
are equal, and <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>obj1</em> is greater than <em>obj2</em>. (It was previously
allowed to return arbitrary negative or positive integers for less than and
greater than, respectively; as of Python 2.2, this is no longer allowed.  In the
future, other return values may be assigned a different meaning.)</p>
<p>A <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_compare" title="PyTypeObject.tp_compare"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_compare</span></code></a> handler may raise an exception.  In this case it should
return a negative value.  The caller has to test for the exception using
<a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Occurred" title="PyErr_Occurred"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Occurred()</span></code></a>.</p>
<p>Here is a sample implementation:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">int</span>
<span class="nf">newdatatype_compare</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span> <span class="n">obj1</span><span class="p">,</span> <span class="n">newdatatypeobject</span> <span class="o">*</span> <span class="n">obj2</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">long</span> <span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">obj1</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">&lt;</span>
        <span class="n">obj2</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">result</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">obj1</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span> <span class="o">&gt;</span>
             <span class="n">obj2</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">result</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">else</span> <span class="p">{</span>
        <span class="n">result</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="abstract-protocol-support">
<h3>2.2.5. Abstract Protocol Support<a class="headerlink" href="#abstract-protocol-support" title="Permalink to this headline">¶</a></h3>
<p>Python supports a variety of <em>abstract</em> ‘protocols;’ the specific interfaces
provided to use these interfaces are documented in <a class="reference internal" href="../c-api/abstract.html#abstract"><span class="std std-ref">Abstract Objects Layer</span></a>.</p>
<p>A number of these abstract interfaces were defined early in the development of
the Python implementation.  In particular, the number, mapping, and sequence
protocols have been part of Python since the beginning.  Other protocols have
been added over time.  For protocols which depend on several handler routines
from the type implementation, the older protocols have been defined as optional
blocks of handlers referenced by the type object.  For newer protocols there are
additional slots in the main type object, with a flag bit being set to indicate
that the slots are present and should be checked by the interpreter.  (The flag
bit does not indicate that the slot values are non-<em>NULL</em>. The flag may be set
to indicate the presence of a slot, but a slot may still be unfilled.)</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyNumberMethods</span>   <span class="o">*</span><span class="n">tp_as_number</span><span class="p">;</span>
<span class="n">PySequenceMethods</span> <span class="o">*</span><span class="n">tp_as_sequence</span><span class="p">;</span>
<span class="n">PyMappingMethods</span>  <span class="o">*</span><span class="n">tp_as_mapping</span><span class="p">;</span>
</pre></div>
</div>
<p>If you wish your object to be able to act like a number, a sequence, or a
mapping object, then you place the address of a structure that implements the C
type <a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a>, <a class="reference internal" href="../c-api/typeobj.html#c.PySequenceMethods" title="PySequenceMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PySequenceMethods</span></code></a>, or
<a class="reference internal" href="../c-api/typeobj.html#c.PyMappingMethods" title="PyMappingMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMappingMethods</span></code></a>, respectively. It is up to you to fill in this
structure with appropriate values. You can find examples of the use of each of
these in the <code class="file docutils literal notranslate"><span class="pre">Objects</span></code> directory of the Python source distribution.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">hashfunc</span> <span class="n">tp_hash</span><span class="p">;</span>
</pre></div>
</div>
<p>This function, if you choose to provide it, should return a hash number for an
instance of your data type. Here is a moderately pointless example:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">long</span>
<span class="nf">newdatatype_hash</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span><span class="n">obj</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">long</span> <span class="n">result</span><span class="p">;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">result</span> <span class="o">*</span> <span class="mi">3</span><span class="p">;</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">ternaryfunc</span> <span class="n">tp_call</span><span class="p">;</span>
</pre></div>
</div>
<p>This function is called when an instance of your data type is “called”, for
example, if <code class="docutils literal notranslate"><span class="pre">obj1</span></code> is an instance of your data type and the Python script
contains <code class="docutils literal notranslate"><span class="pre">obj1('hello')</span></code>, the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_call" title="PyTypeObject.tp_call"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_call</span></code></a> handler is invoked.</p>
<p>This function takes three arguments:</p>
<ol class="arabic simple">
<li><em>arg1</em> is the instance of the data type which is the subject of the call. If
the call is <code class="docutils literal notranslate"><span class="pre">obj1('hello')</span></code>, then <em>arg1</em> is <code class="docutils literal notranslate"><span class="pre">obj1</span></code>.</li>
<li><em>arg2</em> is a tuple containing the arguments to the call.  You can use
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> to extract the arguments.</li>
<li><em>arg3</em> is a dictionary of keyword arguments that were passed. If this is
non-<em>NULL</em> and you support keyword arguments, use
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> to extract the arguments.  If you do not
want to support keyword arguments and this is non-<em>NULL</em>, raise a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> with a message saying that keyword arguments are not supported.</li>
</ol>
<p>Here is a desultory example of the implementation of the call function.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cm">/* Implement the call function.</span>
<span class="cm"> *    obj1 is the instance receiving the call.</span>
<span class="cm"> *    obj2 is a tuple containing the arguments to the call, in this</span>
<span class="cm"> *         case 3 strings.</span>
<span class="cm"> */</span>
<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">newdatatype_call</span><span class="p">(</span><span class="n">newdatatypeobject</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">other</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">arg1</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">arg2</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">arg3</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;sss:call&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arg1</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arg2</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">arg3</span><span class="p">))</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">PyString_FromFormat</span><span class="p">(</span>
        <span class="s">&quot;Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">,</span>
        <span class="n">obj</span><span class="o">-&gt;</span><span class="n">obj_UnderlyingDatatypePtr</span><span class="o">-&gt;</span><span class="n">size</span><span class="p">,</span>
        <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">);</span>
    <span class="n">printf</span><span class="p">(</span><span class="s">&quot;\%s&quot;</span><span class="p">,</span> <span class="n">PyString_AS_STRING</span><span class="p">(</span><span class="n">result</span><span class="p">));</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>XXX some fields need to be added here…</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cm">/* Added in release 2.2 */</span>
<span class="cm">/* Iterators */</span>
<span class="n">getiterfunc</span> <span class="n">tp_iter</span><span class="p">;</span>
<span class="n">iternextfunc</span> <span class="n">tp_iternext</span><span class="p">;</span>
</pre></div>
</div>
<p>These functions provide support for the iterator protocol.  Any object which
wishes to support iteration over its contents (which may be generated during
iteration) must implement the <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code> handler.  Objects which are returned
by a <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code> handler must implement both the <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code> and <code class="docutils literal notranslate"><span class="pre">tp_iternext</span></code>
handlers. Both handlers take exactly one parameter, the instance for which they
are being called, and return a new reference.  In the case of an error, they
should set an exception and return <em>NULL</em>.</p>
<p>For an object which represents an iterable collection, the <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code> handler
must return an iterator object.  The iterator object is responsible for
maintaining the state of the iteration.  For collections which can support
multiple iterators which do not interfere with each other (as lists and tuples
do), a new iterator should be created and returned.  Objects which can only be
iterated over once (usually due to side effects of iteration) should implement
this handler by returning a new reference to themselves, and should also
implement the <code class="docutils literal notranslate"><span class="pre">tp_iternext</span></code> handler.  File objects are an example of such an
iterator.</p>
<p>Iterator objects should implement both handlers.  The <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code> handler should
return a new reference to the iterator (this is the same as the <code class="docutils literal notranslate"><span class="pre">tp_iter</span></code>
handler for objects which can only be iterated over destructively).  The
<code class="docutils literal notranslate"><span class="pre">tp_iternext</span></code> handler should return a new reference to the next object in the
iteration if there is one.  If the iteration has reached the end, it may return
<em>NULL</em> without setting an exception or it may set <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>; avoiding
the exception can yield slightly better performance.  If an actual error occurs,
it should set an exception and return <em>NULL</em>.</p>
</div>
<div class="section" id="weak-reference-support">
<span id="weakref-support"></span><h3>2.2.6. Weak Reference Support<a class="headerlink" href="#weak-reference-support" title="Permalink to this headline">¶</a></h3>
<p>One of the goals of Python’s weak-reference implementation is to allow any type
to participate in the weak reference mechanism without incurring the overhead on
those objects which do not benefit by weak referencing (such as numbers).</p>
<p>For an object to be weakly referencable, the extension must include a
<a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> field in the instance structure for the use of the weak
reference mechanism; it must be initialized to <em>NULL</em> by the object’s
constructor.  It must also set the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_weaklistoffset</span></code></a> field of the
corresponding type object to the offset of the field. For example, the instance
type is defined with the following structure:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">typedef</span> <span class="k">struct</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD</span>
    <span class="n">PyClassObject</span> <span class="o">*</span><span class="n">in_class</span><span class="p">;</span>       <span class="cm">/* The class object */</span>
    <span class="n">PyObject</span>      <span class="o">*</span><span class="n">in_dict</span><span class="p">;</span>        <span class="cm">/* A dictionary */</span>
    <span class="n">PyObject</span>      <span class="o">*</span><span class="n">in_weakreflist</span><span class="p">;</span> <span class="cm">/* List of weak references */</span>
<span class="p">}</span> <span class="n">PyInstanceObject</span><span class="p">;</span>
</pre></div>
</div>
<p>The statically-declared type object for instances is defined this way:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyTypeObject</span> <span class="n">PyInstance_Type</span> <span class="o">=</span> <span class="p">{</span>
    <span class="n">PyObject_HEAD_INIT</span><span class="p">(</span><span class="o">&amp;</span><span class="n">PyType_Type</span><span class="p">)</span>
    <span class="mi">0</span><span class="p">,</span>
    <span class="s">&quot;module.instance&quot;</span><span class="p">,</span>

    <span class="cm">/* Lots of stuff omitted for brevity... */</span>

    <span class="n">Py_TPFLAGS_DEFAULT</span><span class="p">,</span>                         <span class="cm">/* tp_flags */</span>
    <span class="mi">0</span><span class="p">,</span>                                          <span class="cm">/* tp_doc */</span>
    <span class="mi">0</span><span class="p">,</span>                                          <span class="cm">/* tp_traverse */</span>
    <span class="mi">0</span><span class="p">,</span>                                          <span class="cm">/* tp_clear */</span>
    <span class="mi">0</span><span class="p">,</span>                                          <span class="cm">/* tp_richcompare */</span>
    <span class="n">offsetof</span><span class="p">(</span><span class="n">PyInstanceObject</span><span class="p">,</span> <span class="n">in_weakreflist</span><span class="p">),</span> <span class="cm">/* tp_weaklistoffset */</span>
<span class="p">};</span>
</pre></div>
</div>
<p>The type constructor is responsible for initializing the weak reference list to
<em>NULL</em>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">instance_new</span><span class="p">()</span> <span class="p">{</span>
    <span class="cm">/* Other initialization stuff omitted for brevity */</span>

    <span class="n">self</span><span class="o">-&gt;</span><span class="n">in_weakreflist</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="k">return</span> <span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span> <span class="n">self</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The only further addition is that the destructor needs to call the weak
reference manager to clear any weak references.  This is only required if the
weak reference list is non-<em>NULL</em>:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">static</span> <span class="kt">void</span>
<span class="nf">instance_dealloc</span><span class="p">(</span><span class="n">PyInstanceObject</span> <span class="o">*</span><span class="n">inst</span><span class="p">)</span>
<span class="p">{</span>
    <span class="cm">/* Allocate temporaries if needed, but do not begin</span>
<span class="cm">       destruction just yet.</span>
<span class="cm">     */</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">inst</span><span class="o">-&gt;</span><span class="n">in_weakreflist</span> <span class="o">!=</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="n">PyObject_ClearWeakRefs</span><span class="p">((</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">)</span> <span class="n">inst</span><span class="p">);</span>

    <span class="cm">/* Proceed with object destruction normally. */</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="more-suggestions">
<h3>2.2.7. More Suggestions<a class="headerlink" href="#more-suggestions" title="Permalink to this headline">¶</a></h3>
<p>Remember that you can omit most of these functions, in which case you provide
<code class="docutils literal notranslate"><span class="pre">0</span></code> as a value.  There are type definitions for each of the functions you must
provide.  They are in <code class="file docutils literal notranslate"><span class="pre">object.h</span></code> in the Python include directory that
comes with the source distribution of Python.</p>
<p>In order to learn how to implement any specific method for your new data type,
do the following: Download and unpack the Python source distribution.  Go the
<code class="file docutils literal notranslate"><span class="pre">Objects</span></code> directory, then search the C source files for <code class="docutils literal notranslate"><span class="pre">tp_</span></code> plus the
function you want (for example, <code class="docutils literal notranslate"><span class="pre">tp_print</span></code> or <code class="docutils literal notranslate"><span class="pre">tp_compare</span></code>).  You will find
examples of the function you want to implement.</p>
<p>When you need to verify that an object is an instance of the type you are
implementing, use the <a class="reference internal" href="../c-api/object.html#c.PyObject_TypeCheck" title="PyObject_TypeCheck"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_TypeCheck()</span></code></a> function. A sample of its use
might be something like the following:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="o">!</span> <span class="n">PyObject_TypeCheck</span><span class="p">(</span><span class="n">some_object</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">MyType</span><span class="p">))</span> <span class="p">{</span>
    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_TypeError</span><span class="p">,</span> <span class="s">&quot;arg #1 not a mything&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id7" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[1]</a></td><td>This is true when we know that the object is a basic type, like a string or a
float.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id8" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[2]</a></td><td>We relied on this in the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_dealloc</span></code></a> handler in this example, because our
type doesn’t support garbage collection. Even if a type supports garbage
collection, there are calls that can be made to “untrack” the object from
garbage collection, however, these calls are advanced and not covered here.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id9" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[3]</a></td><td>We now know that the first and last members are strings, so perhaps we could be
less careful about decrementing their reference counts, however, we accept
instances of string subclasses. Even though deallocating normal strings won’t
call back into our objects, we can’t guarantee that deallocating an instance of
a string subclass won’t call back into our objects.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id10" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id5">[4]</a></td><td>Even in the third version, we aren’t guaranteed to avoid cycles.  Instances of
string subclasses are allowed and string subclasses could allow cycles even if
normal strings don’t.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Defining New Types</a><ul>
<li><a class="reference internal" href="#the-basics">2.1. The Basics</a><ul>
<li><a class="reference internal" href="#adding-data-and-methods-to-the-basic-example">2.1.1. Adding data and methods to the Basic example</a></li>
<li><a class="reference internal" href="#providing-finer-control-over-data-attributes">2.1.2. Providing finer control over data attributes</a></li>
<li><a class="reference internal" href="#supporting-cyclic-garbage-collection">2.1.3. Supporting cyclic garbage collection</a></li>
<li><a class="reference internal" href="#subclassing-other-types">2.1.4. Subclassing other types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#type-methods">2.2. Type Methods</a><ul>
<li><a class="reference internal" href="#finalization-and-de-allocation">2.2.1. Finalization and De-allocation</a></li>
<li><a class="reference internal" href="#object-presentation">2.2.2. Object Presentation</a></li>
<li><a class="reference internal" href="#attribute-management">2.2.3. Attribute Management</a><ul>
<li><a class="reference internal" href="#generic-attribute-management">2.2.3.1. Generic Attribute Management</a></li>
<li><a class="reference internal" href="#type-specific-attribute-management">2.2.3.2. Type-specific Attribute Management</a></li>
</ul>
</li>
<li><a class="reference internal" href="#object-comparison">2.2.4. Object Comparison</a></li>
<li><a class="reference internal" href="#abstract-protocol-support">2.2.5. Abstract Protocol Support</a></li>
<li><a class="reference internal" href="#weak-reference-support">2.2.6. Weak Reference Support</a></li>
<li><a class="reference internal" href="#more-suggestions">2.2.7. More Suggestions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="extending.html"
                        title="previous chapter">1. Extending Python with C or C++</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="building.html"
                        title="next chapter">3. Building C and C++ Extensions with distutils</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/newtypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="building.html" title="3. Building C and C++ Extensions with distutils"
             >next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="1. Extending Python with C or C++"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\o�P�G�Ghtml/extending/windows.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. Building C and C++ Extensions on Windows &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="5. Embedding Python in Another Application" href="embedding.html" />
    <link rel="prev" title="3. Building C and C++ Extensions with distutils" href="building.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/extending/windows.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="embedding.html" title="5. Embedding Python in Another Application"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="building.html" title="3. Building C and C++ Extensions with distutils"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="building-c-and-c-extensions-on-windows">
<span id="building-on-windows"></span><h1>4. Building C and C++ Extensions on Windows<a class="headerlink" href="#building-c-and-c-extensions-on-windows" title="Permalink to this headline">¶</a></h1>
<p>This chapter briefly explains how to create a Windows extension module for
Python using Microsoft Visual C++, and follows with more detailed background
information on how it works.  The explanatory material is useful for both the
Windows programmer learning to build Python extensions and the Unix programmer
interested in producing software which can be successfully built on both Unix
and Windows.</p>
<p>Module authors are encouraged to use the distutils approach for building
extension modules, instead of the one described in this section. You will still
need the C compiler that was used to build Python; typically Microsoft Visual
C++.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This chapter mentions a number of filenames that include an encoded Python
version number.  These filenames are represented with the version number shown
as <code class="docutils literal notranslate"><span class="pre">XY</span></code>; in practice, <code class="docutils literal notranslate"><span class="pre">'X'</span></code> will be the major version number and <code class="docutils literal notranslate"><span class="pre">'Y'</span></code>
will be the minor version number of the Python release you’re working with.  For
example, if you are using Python 2.2.1, <code class="docutils literal notranslate"><span class="pre">XY</span></code> will actually be <code class="docutils literal notranslate"><span class="pre">22</span></code>.</p>
</div>
<div class="section" id="a-cookbook-approach">
<span id="win-cookbook"></span><h2>4.1. A Cookbook Approach<a class="headerlink" href="#a-cookbook-approach" title="Permalink to this headline">¶</a></h2>
<p>There are two approaches to building extension modules on Windows, just as there
are on Unix: use the <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> package to control the build process, or
do things manually.  The distutils approach works well for most extensions;
documentation on using <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> to build and package extension modules
is available in <a class="reference internal" href="../distutils/index.html#distutils-index"><span class="std std-ref">Distributing Python Modules (Legacy version)</span></a>.  If you find you really need to do
things manually, it may be instructive to study the project file for the
<a class="reference external" href="https://github.com/python/cpython/tree/2.7/PCbuild/winsound.vcxproj">winsound</a> standard library module.</p>
</div>
<div class="section" id="differences-between-unix-and-windows">
<span id="dynamic-linking"></span><h2>4.2. Differences Between Unix and Windows<a class="headerlink" href="#differences-between-unix-and-windows" title="Permalink to this headline">¶</a></h2>
<p>Unix and Windows use completely different paradigms for run-time loading of
code.  Before you try to build a module that can be dynamically loaded, be aware
of how your system works.</p>
<p>In Unix, a shared object (<code class="file docutils literal notranslate"><span class="pre">.so</span></code>) file contains code to be used by the
program, and also the names of functions and data that it expects to find in the
program.  When the file is joined to the program, all references to those
functions and data in the file’s code are changed to point to the actual
locations in the program where the functions and data are placed in memory.
This is basically a link operation.</p>
<p>In Windows, a dynamic-link library (<code class="file docutils literal notranslate"><span class="pre">.dll</span></code>) file has no dangling
references.  Instead, an access to functions or data goes through a lookup
table.  So the DLL code does not have to be fixed up at runtime to refer to the
program’s memory; instead, the code already uses the DLL’s lookup table, and the
lookup table is modified at runtime to point to the functions and data.</p>
<p>In Unix, there is only one type of library file (<code class="file docutils literal notranslate"><span class="pre">.a</span></code>) which contains code
from several object files (<code class="file docutils literal notranslate"><span class="pre">.o</span></code>).  During the link step to create a shared
object file (<code class="file docutils literal notranslate"><span class="pre">.so</span></code>), the linker may find that it doesn’t know where an
identifier is defined.  The linker will look for it in the object files in the
libraries; if it finds it, it will include all the code from that object file.</p>
<p>In Windows, there are two types of library, a static library and an import
library (both called <code class="file docutils literal notranslate"><span class="pre">.lib</span></code>).  A static library is like a Unix <code class="file docutils literal notranslate"><span class="pre">.a</span></code>
file; it contains code to be included as necessary. An import library is
basically used only to reassure the linker that a certain identifier is legal,
and will be present in the program when the DLL is loaded.  So the linker uses
the information from the import library to build the lookup table for using
identifiers that are not included in the DLL.  When an application or a DLL is
linked, an import library may be generated, which will need to be used for all
future DLLs that depend on the symbols in the application or DLL.</p>
<p>Suppose you are building two dynamic-load modules, B and C, which should share
another block of code A.  On Unix, you would <em>not</em> pass <code class="file docutils literal notranslate"><span class="pre">A.a</span></code> to the
linker for <code class="file docutils literal notranslate"><span class="pre">B.so</span></code> and <code class="file docutils literal notranslate"><span class="pre">C.so</span></code>; that would cause it to be included
twice, so that B and C would each have their own copy.  In Windows, building
<code class="file docutils literal notranslate"><span class="pre">A.dll</span></code> will also build <code class="file docutils literal notranslate"><span class="pre">A.lib</span></code>.  You <em>do</em> pass <code class="file docutils literal notranslate"><span class="pre">A.lib</span></code> to the
linker for B and C.  <code class="file docutils literal notranslate"><span class="pre">A.lib</span></code> does not contain code; it just contains
information which will be used at runtime to access A’s code.</p>
<p>In Windows, using an import library is sort of like using <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">spam</span></code>; it
gives you access to spam’s names, but does not create a separate copy.  On Unix,
linking with a library is more like <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">spam</span> <span class="pre">import</span> <span class="pre">*</span></code>; it does create a
separate copy.</p>
</div>
<div class="section" id="using-dlls-in-practice">
<span id="win-dlls"></span><h2>4.3. Using DLLs in Practice<a class="headerlink" href="#using-dlls-in-practice" title="Permalink to this headline">¶</a></h2>
<p>Windows Python is built in Microsoft Visual C++; using other compilers may or
may not work (though Borland seems to).  The rest of this section is MSVC++
specific.</p>
<p>When creating DLLs in Windows, you must pass <code class="file docutils literal notranslate"><span class="pre">pythonXY.lib</span></code> to the linker.
To build two DLLs, spam and ni (which uses C functions found in spam), you could
use these commands:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">cl</span> <span class="o">/</span><span class="n">LD</span> <span class="o">/</span><span class="n">I</span><span class="o">/</span><span class="n">python</span><span class="o">/</span><span class="n">include</span> <span class="n">spam</span><span class="p">.</span><span class="n">c</span> <span class="p">..</span><span class="o">/</span><span class="n">libs</span><span class="o">/</span><span class="n">pythonXY</span><span class="p">.</span><span class="n">lib</span>
<span class="n">cl</span> <span class="o">/</span><span class="n">LD</span> <span class="o">/</span><span class="n">I</span><span class="o">/</span><span class="n">python</span><span class="o">/</span><span class="n">include</span> <span class="n">ni</span><span class="p">.</span><span class="n">c</span> <span class="n">spam</span><span class="p">.</span><span class="n">lib</span> <span class="p">..</span><span class="o">/</span><span class="n">libs</span><span class="o">/</span><span class="n">pythonXY</span><span class="p">.</span><span class="n">lib</span>
</pre></div>
</div>
<p>The first command created three files: <code class="file docutils literal notranslate"><span class="pre">spam.obj</span></code>, <code class="file docutils literal notranslate"><span class="pre">spam.dll</span></code> and
<code class="file docutils literal notranslate"><span class="pre">spam.lib</span></code>.  <code class="file docutils literal notranslate"><span class="pre">Spam.dll</span></code> does not contain any Python functions (such
as <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>), but it does know how to find the Python code
thanks to <code class="file docutils literal notranslate"><span class="pre">pythonXY.lib</span></code>.</p>
<p>The second command created <code class="file docutils literal notranslate"><span class="pre">ni.dll</span></code> (and <code class="file docutils literal notranslate"><span class="pre">.obj</span></code> and <code class="file docutils literal notranslate"><span class="pre">.lib</span></code>),
which knows how to find the necessary functions from spam, and also from the
Python executable.</p>
<p>Not every identifier is exported to the lookup table.  If you want any other
modules (including Python) to be able to see your identifiers, you have to say
<code class="docutils literal notranslate"><span class="pre">_declspec(dllexport)</span></code>, as in <code class="docutils literal notranslate"><span class="pre">void</span> <span class="pre">_declspec(dllexport)</span> <span class="pre">initspam(void)</span></code> or
<code class="docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">_declspec(dllexport)</span> <span class="pre">*NiGetSpamData(void)</span></code>.</p>
<p>Developer Studio will throw in a lot of import libraries that you do not really
need, adding about 100K to your executable.  To get rid of them, use the Project
Settings dialog, Link tab, to specify <em>ignore default libraries</em>.  Add the
correct <code class="file docutils literal notranslate"><span class="pre">msvcrtxx.lib</span></code> to the list of libraries.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Building C and C++ Extensions on Windows</a><ul>
<li><a class="reference internal" href="#a-cookbook-approach">4.1. A Cookbook Approach</a></li>
<li><a class="reference internal" href="#differences-between-unix-and-windows">4.2. Differences Between Unix and Windows</a></li>
<li><a class="reference internal" href="#using-dlls-in-practice">4.3. Using DLLs in Practice</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="building.html"
                        title="previous chapter">3. Building C and C++ Extensions with distutils</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="embedding.html"
                        title="next chapter">5. Embedding Python in Another Application</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/extending/windows.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="embedding.html" title="5. Embedding Python in Another Application"
             >next</a> |</li>
        <li class="right" >
          <a href="building.html" title="3. Building C and C++ Extensions with distutils"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Extending and Embedding the Python Interpreter</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\؎x��H�Hhtml/faq/design.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Design and History FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Library and Extension FAQ" href="library.html" />
    <link rel="prev" title="Programming FAQ" href="programming.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/design.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="programming.html" title="Programming FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="design-and-history-faq">
<h1><a class="toc-backref" href="#id1">Design and History FAQ</a><a class="headerlink" href="#design-and-history-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#design-and-history-faq" id="id1">Design and History FAQ</a><ul>
<li><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements" id="id2">Why does Python use indentation for grouping of statements?</a></li>
<li><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations" id="id3">Why am I getting strange results with simple arithmetic operations?</a></li>
<li><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate" id="id4">Why are floating point calculations so inaccurate?</a></li>
<li><a class="reference internal" href="#why-are-python-strings-immutable" id="id5">Why are Python strings immutable?</a></li>
<li><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls" id="id6">Why must ‘self’ be used explicitly in method definitions and calls?</a></li>
<li><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression" id="id7">Why can’t I use an assignment in an expression?</a></li>
<li><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" id="id8">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
<li><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method" id="id9">Why is join() a string method instead of a list or tuple method?</a></li>
<li><a class="reference internal" href="#how-fast-are-exceptions" id="id10">How fast are exceptions?</a></li>
<li><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python" id="id11">Why isn’t there a switch or case statement in Python?</a></li>
<li><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation" id="id12">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
<li><a class="reference internal" href="#why-can-t-lambda-expressions-contain-statements" id="id13">Why can’t lambda expressions contain statements?</a></li>
<li><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language" id="id14">Can Python be compiled to machine code, C or some other language?</a></li>
<li><a class="reference internal" href="#how-does-python-manage-memory" id="id15">How does Python manage memory?</a></li>
<li><a class="reference internal" href="#why-isn-t-all-memory-freed-when-python-exits" id="id16">Why isn’t all memory freed when Python exits?</a></li>
<li><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types" id="id17">Why are there separate tuple and list data types?</a></li>
<li><a class="reference internal" href="#how-are-lists-implemented-in-cpython" id="id18">How are lists implemented in CPython?</a></li>
<li><a class="reference internal" href="#how-are-dictionaries-implemented-in-cpython" id="id19">How are dictionaries implemented in CPython?</a></li>
<li><a class="reference internal" href="#why-must-dictionary-keys-be-immutable" id="id20">Why must dictionary keys be immutable?</a></li>
<li><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list" id="id21">Why doesn’t list.sort() return the sorted list?</a></li>
<li><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python" id="id22">How do you specify and enforce an interface spec in Python?</a></li>
<li><a class="reference internal" href="#why-is-there-no-goto" id="id23">Why is there no goto?</a></li>
<li><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash" id="id24">Why can’t raw strings (r-strings) end with a backslash?</a></li>
<li><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments" id="id25">Why doesn’t Python have a “with” statement for attribute assignments?</a></li>
<li><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements" id="id26">Why are colons required for the if/while/def/class statements?</a></li>
<li><a class="reference internal" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples" id="id27">Why does Python allow commas at the end of lists and tuples?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="why-does-python-use-indentation-for-grouping-of-statements">
<h2><a class="toc-backref" href="#id2">Why does Python use indentation for grouping of statements?</a><a class="headerlink" href="#why-does-python-use-indentation-for-grouping-of-statements" title="Permalink to this headline">¶</a></h2>
<p>Guido van Rossum believes that using indentation for grouping is extremely
elegant and contributes a lot to the clarity of the average Python program.
Most people learn to love this feature after a while.</p>
<p>Since there are no begin/end brackets there cannot be a disagreement between
grouping perceived by the parser and the human reader.  Occasionally C
programmers will encounter a fragment of code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">x</span> <span class="o">&lt;=</span> <span class="n">y</span><span class="p">)</span>
        <span class="n">x</span><span class="o">++</span><span class="p">;</span>
        <span class="n">y</span><span class="o">--</span><span class="p">;</span>
<span class="n">z</span><span class="o">++</span><span class="p">;</span>
</pre></div>
</div>
<p>Only the <code class="docutils literal notranslate"><span class="pre">x++</span></code> statement is executed if the condition is true, but the
indentation leads you to believe otherwise.  Even experienced C programmers will
sometimes stare at it a long time wondering why <code class="docutils literal notranslate"><span class="pre">y</span></code> is being decremented even
for <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span></code>.</p>
<p>Because there are no begin/end brackets, Python is much less prone to
coding-style conflicts.  In C there are many different ways to place the braces.
If you’re used to reading and writing code that uses one style, you will feel at
least slightly uneasy when reading (or being required to write) another style.</p>
<p>Many coding styles place begin/end brackets on a line by themselves.  This makes
programs considerably longer and wastes valuable screen space, making it harder
to get a good overview of a program.  Ideally, a function should fit on one
screen (say, 20–30 lines).  20 lines of Python can do a lot more work than 20
lines of C.  This is not solely due to the lack of begin/end brackets – the
lack of declarations and the high-level data types are also responsible – but
the indentation-based syntax certainly helps.</p>
</div>
<div class="section" id="why-am-i-getting-strange-results-with-simple-arithmetic-operations">
<h2><a class="toc-backref" href="#id3">Why am I getting strange results with simple arithmetic operations?</a><a class="headerlink" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations" title="Permalink to this headline">¶</a></h2>
<p>See the next question.</p>
</div>
<div class="section" id="why-are-floating-point-calculations-so-inaccurate">
<h2><a class="toc-backref" href="#id4">Why are floating point calculations so inaccurate?</a><a class="headerlink" href="#why-are-floating-point-calculations-so-inaccurate" title="Permalink to this headline">¶</a></h2>
<p>People are often very surprised by results like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.2</span> <span class="o">-</span> <span class="mf">1.0</span>
<span class="go">0.19999999999999996</span>
</pre></div>
</div>
<p>and think it is a bug in Python. It’s not.  This has nothing to do with Python,
but with how the underlying C platform handles floating point numbers, and
ultimately with the inaccuracies introduced when writing down numbers as a
string of a fixed number of digits.</p>
<p>The internal representation of floating point numbers uses a fixed number of
binary digits to represent a decimal number.  Some decimal numbers can’t be
represented exactly in binary, resulting in small roundoff errors.</p>
<p>In decimal math, there are many numbers that can’t be represented with a fixed
number of decimal digits, e.g.  1/3 = 0.3333333333…….</p>
<p>In base 2, 1/2 = 0.1, 1/4 = 0.01, 1/8 = 0.001, etc.  .2 equals 2/10 equals 1/5,
resulting in the binary fractional number 0.001100110011001…</p>
<p>Floating point numbers only have 32 or 64 bits of precision, so the digits are
cut off at some point, and the resulting number is 0.199999999999999996 in
decimal, not 0.2.</p>
<p>A floating point number’s <code class="docutils literal notranslate"><span class="pre">repr()</span></code> function prints as many digits are
necessary to make <code class="docutils literal notranslate"><span class="pre">eval(repr(f))</span> <span class="pre">==</span> <span class="pre">f</span></code> true for any float f.  The <code class="docutils literal notranslate"><span class="pre">str()</span></code>
function prints fewer digits and this often results in the more sensible number
that was probably intended:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.1</span> <span class="o">-</span> <span class="mf">0.9</span>
<span class="go">0.20000000000000007</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="mf">1.1</span> <span class="o">-</span> <span class="mf">0.9</span>
<span class="go">0.2</span>
</pre></div>
</div>
<p>One of the consequences of this is that it is error-prone to compare the result
of some computation to a float with <code class="docutils literal notranslate"><span class="pre">==</span></code>. Tiny inaccuracies may mean that
<code class="docutils literal notranslate"><span class="pre">==</span></code> fails.  Instead, you have to check that the difference between the two
numbers is less than a certain threshold:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">epsilon</span> <span class="o">=</span> <span class="mf">0.0000000000001</span>  <span class="c1"># Tiny allowed error</span>
<span class="n">expected_result</span> <span class="o">=</span> <span class="mf">0.4</span>

<span class="k">if</span> <span class="n">expected_result</span><span class="o">-</span><span class="n">epsilon</span> <span class="o">&lt;=</span> <span class="n">computation</span><span class="p">()</span> <span class="o">&lt;=</span> <span class="n">expected_result</span><span class="o">+</span><span class="n">epsilon</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Please see the chapter on <a class="reference internal" href="../tutorial/floatingpoint.html#tut-fp-issues"><span class="std std-ref">floating point arithmetic</span></a> in
the Python tutorial for more information.</p>
</div>
<div class="section" id="why-are-python-strings-immutable">
<h2><a class="toc-backref" href="#id5">Why are Python strings immutable?</a><a class="headerlink" href="#why-are-python-strings-immutable" title="Permalink to this headline">¶</a></h2>
<p>There are several advantages.</p>
<p>One is performance: knowing that a string is immutable means we can allocate
space for it at creation time, and the storage requirements are fixed and
unchanging.  This is also one of the reasons for the distinction between tuples
and lists.</p>
<p>Another advantage is that strings in Python are considered as “elemental” as
numbers.  No amount of activity will change the value 8 to anything else, and in
Python, no amount of activity will change the string “eight” to anything else.</p>
</div>
<div class="section" id="why-must-self-be-used-explicitly-in-method-definitions-and-calls">
<span id="why-self"></span><h2><a class="toc-backref" href="#id6">Why must ‘self’ be used explicitly in method definitions and calls?</a><a class="headerlink" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls" title="Permalink to this headline">¶</a></h2>
<p>The idea was borrowed from Modula-3.  It turns out to be very useful, for a
variety of reasons.</p>
<p>First, it’s more obvious that you are using a method or instance attribute
instead of a local variable.  Reading <code class="docutils literal notranslate"><span class="pre">self.x</span></code> or <code class="docutils literal notranslate"><span class="pre">self.meth()</span></code> makes it
absolutely clear that an instance variable or method is used even if you don’t
know the class definition by heart.  In C++, you can sort of tell by the lack of
a local variable declaration (assuming globals are rare or easily recognizable)
– but in Python, there are no local variable declarations, so you’d have to
look up the class definition to be sure.  Some C++ and Java coding standards
call for instance attributes to have an <code class="docutils literal notranslate"><span class="pre">m_</span></code> prefix, so this explicitness is
still useful in those languages, too.</p>
<p>Second, it means that no special syntax is necessary if you want to explicitly
reference or call the method from a particular class.  In C++, if you want to
use a method from a base class which is overridden in a derived class, you have
to use the <code class="docutils literal notranslate"><span class="pre">::</span></code> operator – in Python you can write
<code class="docutils literal notranslate"><span class="pre">baseclass.methodname(self,</span> <span class="pre">&lt;argument</span> <span class="pre">list&gt;)</span></code>.  This is particularly useful
for <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> methods, and in general in cases where a derived class
method wants to extend the base class method of the same name and thus has to
call the base class method somehow.</p>
<p>Finally, for instance variables it solves a syntactic problem with assignment:
since local variables in Python are (by definition!) those variables to which a
value is assigned in a function body (and that aren’t explicitly declared
global), there has to be some way to tell the interpreter that an assignment was
meant to assign to an instance variable instead of to a local variable, and it
should preferably be syntactic (for efficiency reasons).  C++ does this through
declarations, but Python doesn’t have declarations and it would be a pity having
to introduce them just for this purpose.  Using the explicit <code class="docutils literal notranslate"><span class="pre">self.var</span></code> solves
this nicely.  Similarly, for using instance variables, having to write
<code class="docutils literal notranslate"><span class="pre">self.var</span></code> means that references to unqualified names inside a method don’t
have to search the instance’s directories.  To put it another way, local
variables and instance variables live in two different namespaces, and you need
to tell Python which namespace to use.</p>
</div>
<div class="section" id="why-can-t-i-use-an-assignment-in-an-expression">
<h2><a class="toc-backref" href="#id7">Why can’t I use an assignment in an expression?</a><a class="headerlink" href="#why-can-t-i-use-an-assignment-in-an-expression" title="Permalink to this headline">¶</a></h2>
<p>Many people used to C or Perl complain that they want to use this C idiom:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="p">(</span><span class="n">line</span> <span class="o">=</span> <span class="n">readline</span><span class="p">(</span><span class="n">f</span><span class="p">))</span> <span class="p">{</span>
    <span class="c1">// do something with line</span>
<span class="p">}</span>
</pre></div>
</div>
<p>where in Python you’re forced to write this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="o">...</span>  <span class="c1"># do something with line</span>
</pre></div>
</div>
<p>The reason for not allowing assignment in Python expressions is a common,
hard-to-find bug in those other languages, caused by this construct:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="p">(</span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">// error handling</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
    <span class="c1">// code that only works for nonzero x</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The error is a simple typo: <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">0</span></code>, which assigns 0 to the variable <code class="docutils literal notranslate"><span class="pre">x</span></code>,
was written while the comparison <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">0</span></code> is certainly what was intended.</p>
<p>Many alternatives have been proposed.  Most are hacks that save some typing but
use arbitrary or cryptic syntax or keywords, and fail the simple criterion for
language change proposals: it should intuitively suggest the proper meaning to a
human reader who has not yet been introduced to the construct.</p>
<p>An interesting phenomenon is that most experienced Python programmers recognize
the <code class="docutils literal notranslate"><span class="pre">while</span> <span class="pre">True</span></code> idiom and don’t seem to be missing the assignment in
expression construct much; it’s only newcomers who express a strong desire to
add this to the language.</p>
<p>There’s an alternative way of spelling this that seems attractive but is
generally less robust than the “while True” solution:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">line</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="k">while</span> <span class="n">line</span><span class="p">:</span>
    <span class="o">...</span>  <span class="c1"># do something with line...</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
<p>The problem with this is that if you change your mind about exactly how you get
the next line (e.g. you want to change it into <code class="docutils literal notranslate"><span class="pre">sys.stdin.readline()</span></code>) you
have to remember to change two places in your program – the second occurrence
is hidden at the bottom of the loop.</p>
<p>The best approach is to use iterators, making it possible to loop through
objects using the <code class="docutils literal notranslate"><span class="pre">for</span></code> statement.  For example, in the current version of
Python file objects support the iterator protocol, so you can now write simply:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
    <span class="o">...</span>  <span class="c1"># do something with line...</span>
</pre></div>
</div>
</div>
<div class="section" id="why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">
<h2><a class="toc-backref" href="#id8">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a><a class="headerlink" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list" title="Permalink to this headline">¶</a></h2>
<p>As Guido said:</p>
<blockquote>
<div><p>(a) For some operations, prefix notation just reads better than
postfix – prefix (and infix!) operations have a long tradition in
mathematics which likes notations where the visuals help the
mathematician thinking about a problem. Compare the easy with which we
rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of
doing the same thing using a raw OO notation.</p>
<p>(b) When I read code that says len(x) I <em>know</em> that it is asking for
the length of something. This tells me two things: the result is an
integer, and the argument is some kind of container. To the contrary,
when I read x.len(), I have to already know that x is some kind of
container implementing an interface or inheriting from a class that
has a standard len(). Witness the confusion we occasionally have when
a class that is not implementing a mapping has a get() or keys()
method, or something that isn’t a file has a write() method.</p>
<p class="attribution">&mdash;<a class="reference external" href="https://mail.python.org/pipermail/python-3000/2006-November/004643.html">https://mail.python.org/pipermail/python-3000/2006-November/004643.html</a></p>
</div></blockquote>
</div>
<div class="section" id="why-is-join-a-string-method-instead-of-a-list-or-tuple-method">
<h2><a class="toc-backref" href="#id9">Why is join() a string method instead of a list or tuple method?</a><a class="headerlink" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method" title="Permalink to this headline">¶</a></h2>
<p>Strings became much more like other standard types starting in Python 1.6, when
methods were added which give the same functionality that has always been
available using the functions of the string module.  Most of these new methods
have been widely accepted, but the one which appears to make some programmers
feel uncomfortable is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">,</span> <span class="s1">&#39;8&#39;</span><span class="p">,</span> <span class="s1">&#39;16&#39;</span><span class="p">])</span>
</pre></div>
</div>
<p>which gives the result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;1, 2, 4, 8, 16&quot;</span>
</pre></div>
</div>
<p>There are two common arguments against this usage.</p>
<p>The first runs along the lines of: “It looks really ugly using a method of a
string literal (string constant)”, to which the answer is that it might, but a
string literal is just a fixed value. If the methods are to be allowed on names
bound to strings there is no logical reason to make them unavailable on
literals.</p>
<p>The second objection is typically cast as: “I am really telling a sequence to
join its members together with a string constant”.  Sadly, you aren’t.  For some
reason there seems to be much less difficulty with having <a class="reference internal" href="../library/stdtypes.html#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> as
a string method, since in that case it is easy to see that</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;1, 2, 4, 8, 16&quot;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;, &quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>is an instruction to a string literal to return the substrings delimited by the
given separator (or, by default, arbitrary runs of white space).  In this case a
Unicode string returns a list of Unicode strings, an ASCII string returns a list
of ASCII strings, and everyone is happy.</p>
<p><a class="reference internal" href="../library/stdtypes.html#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is a string method because in using it you are telling the
separator string to iterate over a sequence of strings and insert itself between
adjacent elements.  This method can be used with any argument which obeys the
rules for sequence objects, including any new classes you might define yourself.</p>
<p>Because this is a string method it can work for Unicode strings as well as plain
ASCII strings.  If <code class="docutils literal notranslate"><span class="pre">join()</span></code> were a method of the sequence types then the
sequence types would have to decide which type of string to return depending on
the type of the separator.</p>
<p>If none of these arguments persuade you, then for the moment you can continue to
use the <code class="docutils literal notranslate"><span class="pre">join()</span></code> function from the string module, which allows you to write</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">string</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">,</span> <span class="s1">&#39;8&#39;</span><span class="p">,</span> <span class="s1">&#39;16&#39;</span><span class="p">],</span> <span class="s2">&quot;, &quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="how-fast-are-exceptions">
<h2><a class="toc-backref" href="#id10">How fast are exceptions?</a><a class="headerlink" href="#how-fast-are-exceptions" title="Permalink to this headline">¶</a></h2>
<p>A try/except block is extremely efficient if no exceptions are raised.  Actually
catching an exception is expensive.  In versions of Python prior to 2.0 it was
common to use this idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
    <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">getvalue</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
</pre></div>
</div>
<p>This only made sense when you expected the dict to have the key almost all the
time.  If that wasn’t the case, you coded it like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">mydict</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">getvalue</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 2.0 and higher, you can code this as <code class="docutils literal notranslate"><span class="pre">value</span> <span class="pre">=</span>
<span class="pre">mydict.setdefault(key,</span> <span class="pre">getvalue(key))</span></code>.</p>
</div>
</div>
<div class="section" id="why-isn-t-there-a-switch-or-case-statement-in-python">
<h2><a class="toc-backref" href="#id11">Why isn’t there a switch or case statement in Python?</a><a class="headerlink" href="#why-isn-t-there-a-switch-or-case-statement-in-python" title="Permalink to this headline">¶</a></h2>
<p>You can do this easily enough with a sequence of <code class="docutils literal notranslate"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">elif...</span> <span class="pre">else</span></code>.
There have been some proposals for switch statement syntax, but there is no
consensus (yet) on whether and how to do range tests.  See <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0275"><strong>PEP 275</strong></a> for
complete details and the current status.</p>
<p>For cases where you need to choose from a very large number of possibilities,
you can create a dictionary mapping case values to functions to call.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">function_1</span><span class="p">(</span><span class="o">...</span><span class="p">):</span>
    <span class="o">...</span>

<span class="n">functions</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="n">function_1</span><span class="p">,</span>
             <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="n">function_2</span><span class="p">,</span>
             <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">method_1</span><span class="p">,</span> <span class="o">...</span><span class="p">}</span>

<span class="n">func</span> <span class="o">=</span> <span class="n">functions</span><span class="p">[</span><span class="n">value</span><span class="p">]</span>
<span class="n">func</span><span class="p">()</span>
</pre></div>
</div>
<p>For calling methods on objects, you can simplify yet further by using the
<a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> built-in to retrieve methods with a particular name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">visit_a</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">...</span><span class="p">):</span>
    <span class="o">...</span>
<span class="o">...</span>

<span class="k">def</span> <span class="nf">dispatch</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
    <span class="n">method_name</span> <span class="o">=</span> <span class="s1">&#39;visit_&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="n">method</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">method_name</span><span class="p">)</span>
    <span class="n">method</span><span class="p">()</span>
</pre></div>
</div>
<p>It’s suggested that you use a prefix for the method names, such as <code class="docutils literal notranslate"><span class="pre">visit_</span></code> in
this example.  Without such a prefix, if values are coming from an untrusted
source, an attacker would be able to call any method on your object.</p>
</div>
<div class="section" id="can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">
<h2><a class="toc-backref" href="#id12">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a><a class="headerlink" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation" title="Permalink to this headline">¶</a></h2>
<p>Answer 1: Unfortunately, the interpreter pushes at least one C stack frame for
each Python stack frame.  Also, extensions can call back into Python at almost
random moments.  Therefore, a complete threads implementation requires thread
support for C.</p>
<p>Answer 2: Fortunately, there is <a class="reference external" href="http://www.stackless.com">Stackless Python</a>,
which has a completely redesigned interpreter loop that avoids the C stack.</p>
</div>
<div class="section" id="why-can-t-lambda-expressions-contain-statements">
<h2><a class="toc-backref" href="#id13">Why can’t lambda expressions contain statements?</a><a class="headerlink" href="#why-can-t-lambda-expressions-contain-statements" title="Permalink to this headline">¶</a></h2>
<p>Python lambda expressions cannot contain statements because Python’s syntactic
framework can’t handle statements nested inside expressions.  However, in
Python, this is not a serious problem.  Unlike lambda forms in other languages,
where they add functionality, Python lambdas are only a shorthand notation if
you’re too lazy to define a function.</p>
<p>Functions are already first class objects in Python, and can be declared in a
local scope.  Therefore the only advantage of using a lambda instead of a
locally-defined function is that you don’t need to invent a name for the
function – but that’s just a local variable to which the function object (which
is exactly the same type of object that a lambda expression yields) is assigned!</p>
</div>
<div class="section" id="can-python-be-compiled-to-machine-code-c-or-some-other-language">
<h2><a class="toc-backref" href="#id14">Can Python be compiled to machine code, C or some other language?</a><a class="headerlink" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="http://cython.org/">Cython</a> compiles a modified version of Python with
optional annotations into C extensions.  <a class="reference external" href="http://www.nuitka.net/">Nuitka</a> is
an up-and-coming compiler of Python into C++ code, aiming to support the full
Python language. For compiling to Java you can consider
<a class="reference external" href="https://voc.readthedocs.io">VOC</a>.</p>
</div>
<div class="section" id="how-does-python-manage-memory">
<h2><a class="toc-backref" href="#id15">How does Python manage memory?</a><a class="headerlink" href="#how-does-python-manage-memory" title="Permalink to this headline">¶</a></h2>
<p>The details of Python memory management depend on the implementation.  The
standard C implementation of Python uses reference counting to detect
inaccessible objects, and another mechanism to collect reference cycles,
periodically executing a cycle detection algorithm which looks for inaccessible
cycles and deletes the objects involved. The <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module provides functions
to perform a garbage collection, obtain debugging statistics, and tune the
collector’s parameters.</p>
<p>Jython relies on the Java runtime so the JVM’s garbage collector is used.  This
difference can cause some subtle porting problems if your Python code depends on
the behavior of the reference counting implementation.</p>
<p>Sometimes objects get stuck in tracebacks temporarily and hence are not
deallocated when you might expect.  Clear the tracebacks with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="n">sys</span><span class="o">.</span><span class="n">exc_clear</span><span class="p">()</span>
<span class="n">sys</span><span class="o">.</span><span class="n">exc_traceback</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">last_traceback</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
<p>Tracebacks are used for reporting errors, implementing debuggers and related
things.  They contain a portion of the program state extracted during the
handling of an exception (usually the most recent exception).</p>
<p>In the absence of circularities and tracebacks, Python programs do not need to
manage memory explicitly.</p>
<p>Why doesn’t Python use a more traditional garbage collection scheme?  For one
thing, this is not a C standard feature and hence it’s not portable.  (Yes, we
know about the Boehm GC library.  It has bits of assembler code for <em>most</em>
common platforms, not for all of them, and although it is mostly transparent, it
isn’t completely transparent; patches are required to get Python to work with
it.)</p>
<p>Traditional GC also becomes a problem when Python is embedded into other
applications.  While in a standalone Python it’s fine to replace the standard
malloc() and free() with versions provided by the GC library, an application
embedding Python may want to have its <em>own</em> substitute for malloc() and free(),
and may not want Python’s.  Right now, Python works with anything that
implements malloc() and free() properly.</p>
<p>In Jython, the following code (which is fine in CPython) will probably run out
of file descriptors long before it runs out of memory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">very_long_list_of_files</span><span class="p">:</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Using the current reference counting and destructor scheme, each new assignment
to f closes the previous file.  Using GC, this is not guaranteed.  If you want
to write code that will work with any Python implementation, you should
explicitly close the file or use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement; this will work
regardless of GC:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">very_long_list_of_files</span><span class="p">:</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">c</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="why-isn-t-all-memory-freed-when-python-exits">
<h2><a class="toc-backref" href="#id16">Why isn’t all memory freed when Python exits?</a><a class="headerlink" href="#why-isn-t-all-memory-freed-when-python-exits" title="Permalink to this headline">¶</a></h2>
<p>Objects referenced from the global namespaces of Python modules are not always
deallocated when Python exits.  This may happen if there are circular
references.  There are also certain bits of memory that are allocated by the C
library that are impossible to free (e.g. a tool like Purify will complain about
these).  Python is, however, aggressive about cleaning up memory on exit and
does try to destroy every single object.</p>
<p>If you want to force Python to delete certain things on deallocation use the
<a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module to run a function that will force those deletions.</p>
</div>
<div class="section" id="why-are-there-separate-tuple-and-list-data-types">
<h2><a class="toc-backref" href="#id17">Why are there separate tuple and list data types?</a><a class="headerlink" href="#why-are-there-separate-tuple-and-list-data-types" title="Permalink to this headline">¶</a></h2>
<p>Lists and tuples, while similar in many respects, are generally used in
fundamentally different ways.  Tuples can be thought of as being similar to
Pascal records or C structs; they’re small collections of related data which may
be of different types which are operated on as a group.  For example, a
Cartesian coordinate is appropriately represented as a tuple of two or three
numbers.</p>
<p>Lists, on the other hand, are more like arrays in other languages.  They tend to
hold a varying number of objects all of which have the same type and which are
operated on one-by-one.  For example, <code class="docutils literal notranslate"><span class="pre">os.listdir('.')</span></code> returns a list of
strings representing the files in the current directory.  Functions which
operate on this output would generally not break if you added another file or
two to the directory.</p>
<p>Tuples are immutable, meaning that once a tuple has been created, you can’t
replace any of its elements with a new value.  Lists are mutable, meaning that
you can always change a list’s elements.  Only immutable elements can be used as
dictionary keys, and hence only tuples and not lists can be used as keys.</p>
</div>
<div class="section" id="how-are-lists-implemented-in-cpython">
<h2><a class="toc-backref" href="#id18">How are lists implemented in CPython?</a><a class="headerlink" href="#how-are-lists-implemented-in-cpython" title="Permalink to this headline">¶</a></h2>
<p>CPython’s lists are really variable-length arrays, not Lisp-style linked lists.
The implementation uses a contiguous array of references to other objects, and
keeps a pointer to this array and the array’s length in a list head structure.</p>
<p>This makes indexing a list <code class="docutils literal notranslate"><span class="pre">a[i]</span></code> an operation whose cost is independent of
the size of the list or the value of the index.</p>
<p>When items are appended or inserted, the array of references is resized.  Some
cleverness is applied to improve the performance of appending items repeatedly;
when the array must be grown, some extra space is allocated so the next few
times don’t require an actual resize.</p>
</div>
<div class="section" id="how-are-dictionaries-implemented-in-cpython">
<h2><a class="toc-backref" href="#id19">How are dictionaries implemented in CPython?</a><a class="headerlink" href="#how-are-dictionaries-implemented-in-cpython" title="Permalink to this headline">¶</a></h2>
<p>CPython’s dictionaries are implemented as resizable hash tables.  Compared to
B-trees, this gives better performance for lookup (the most common operation by
far) under most circumstances, and the implementation is simpler.</p>
<p>Dictionaries work by computing a hash code for each key stored in the dictionary
using the <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> built-in function.  The hash code varies widely depending
on the key; for example, “Python” hashes to -539294296 while “python”, a string
that differs by a single bit, hashes to 1142331976.  The hash code is then used
to calculate a location in an internal array where the value will be stored.
Assuming that you’re storing keys that all have different hash values, this
means that dictionaries take constant time – O(1), in computer science notation
– to retrieve a key.  It also means that no sorted order of the keys is
maintained, and traversing the array as the <code class="docutils literal notranslate"><span class="pre">.keys()</span></code> and <code class="docutils literal notranslate"><span class="pre">.items()</span></code> do will
output the dictionary’s content in some arbitrary jumbled order.</p>
</div>
<div class="section" id="why-must-dictionary-keys-be-immutable">
<h2><a class="toc-backref" href="#id20">Why must dictionary keys be immutable?</a><a class="headerlink" href="#why-must-dictionary-keys-be-immutable" title="Permalink to this headline">¶</a></h2>
<p>The hash table implementation of dictionaries uses a hash value calculated from
the key value to find the key.  If the key were a mutable object, its value
could change, and thus its hash could also change.  But since whoever changes
the key object can’t tell that it was being used as a dictionary key, it can’t
move the entry around in the dictionary.  Then, when you try to look up the same
object in the dictionary it won’t be found because its hash value is different.
If you tried to look up the old value it wouldn’t be found either, because the
value of the object found in that hash bin would be different.</p>
<p>If you want a dictionary indexed with a list, simply convert the list to a tuple
first; the function <code class="docutils literal notranslate"><span class="pre">tuple(L)</span></code> creates a tuple with the same entries as the
list <code class="docutils literal notranslate"><span class="pre">L</span></code>.  Tuples are immutable and can therefore be used as dictionary keys.</p>
<p>Some unacceptable solutions that have been proposed:</p>
<ul>
<li><p class="first">Hash lists by their address (object ID).  This doesn’t work because if you
construct a new list with the same value it won’t be found; e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mydict</span> <span class="o">=</span> <span class="p">{[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]:</span> <span class="s1">&#39;12&#39;</span><span class="p">}</span>
<span class="nb">print</span> <span class="n">mydict</span><span class="p">[[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]]</span>
</pre></div>
</div>
<p>would raise a KeyError exception because the id of the <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2]</span></code> used in the
second line differs from that in the first line.  In other words, dictionary
keys should be compared using <code class="docutils literal notranslate"><span class="pre">==</span></code>, not using <a class="reference internal" href="../reference/expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>.</p>
</li>
<li><p class="first">Make a copy when using a list as a key.  This doesn’t work because the list,
being a mutable object, could contain a reference to itself, and then the
copying code would run into an infinite loop.</p>
</li>
<li><p class="first">Allow lists as keys but tell the user not to modify them.  This would allow a
class of hard-to-track bugs in programs when you forgot or modified a list by
accident. It also invalidates an important invariant of dictionaries: every
value in <code class="docutils literal notranslate"><span class="pre">d.keys()</span></code> is usable as a key of the dictionary.</p>
</li>
<li><p class="first">Mark lists as read-only once they are used as a dictionary key.  The problem
is that it’s not just the top-level object that could change its value; you
could use a tuple containing a list as a key.  Entering anything as a key into
a dictionary would require marking all objects reachable from there as
read-only – and again, self-referential objects could cause an infinite loop.</p>
</li>
</ul>
<p>There is a trick to get around this if you need to, but use it at your own risk:
You can wrap a mutable structure inside a class instance which has both a
<a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method.  You must then make sure that the
hash value for all such wrapper objects that reside in a dictionary (or other
hash based structure), remain fixed while the object is in the dictionary (or
other structure).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ListWrapper</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">the_list</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span> <span class="o">=</span> <span class="n">the_list</span>

    <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">the_list</span>

    <span class="k">def</span> <span class="nf">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">l</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">the_list</span>
        <span class="n">result</span> <span class="o">=</span> <span class="mi">98767</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)</span><span class="o">*</span><span class="mi">555</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">el</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">result</span> <span class="o">=</span> <span class="n">result</span> <span class="o">+</span> <span class="p">(</span><span class="nb">hash</span><span class="p">(</span><span class="n">el</span><span class="p">)</span> <span class="o">%</span> <span class="mi">9999999</span><span class="p">)</span> <span class="o">*</span> <span class="mi">1001</span> <span class="o">+</span> <span class="n">i</span>
            <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
                <span class="n">result</span> <span class="o">=</span> <span class="p">(</span><span class="n">result</span> <span class="o">%</span> <span class="mi">7777777</span><span class="p">)</span> <span class="o">+</span> <span class="n">i</span> <span class="o">*</span> <span class="mi">333</span>
        <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Note that the hash computation is complicated by the possibility that some
members of the list may be unhashable and also by the possibility of arithmetic
overflow.</p>
<p>Furthermore it must always be the case that if <code class="docutils literal notranslate"><span class="pre">o1</span> <span class="pre">==</span> <span class="pre">o2</span></code> (ie <code class="docutils literal notranslate"><span class="pre">o1.__eq__(o2)</span>
<span class="pre">is</span> <span class="pre">True</span></code>) then <code class="docutils literal notranslate"><span class="pre">hash(o1)</span> <span class="pre">==</span> <span class="pre">hash(o2)</span></code> (ie, <code class="docutils literal notranslate"><span class="pre">o1.__hash__()</span> <span class="pre">==</span> <span class="pre">o2.__hash__()</span></code>),
regardless of whether the object is in a dictionary or not.  If you fail to meet
these restrictions dictionaries and other hash based structures will misbehave.</p>
<p>In the case of ListWrapper, whenever the wrapper object is in a dictionary the
wrapped list must not change to avoid anomalies.  Don’t do this unless you are
prepared to think hard about the requirements and the consequences of not
meeting them correctly.  Consider yourself warned.</p>
</div>
<div class="section" id="why-doesn-t-list-sort-return-the-sorted-list">
<h2><a class="toc-backref" href="#id21">Why doesn’t list.sort() return the sorted list?</a><a class="headerlink" href="#why-doesn-t-list-sort-return-the-sorted-list" title="Permalink to this headline">¶</a></h2>
<p>In situations where performance matters, making a copy of the list just to sort
it would be wasteful. Therefore, <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> sorts the list in place. In
order to remind you of that fact, it does not return the sorted list.  This way,
you won’t be fooled into accidentally overwriting a list when you need a sorted
copy but also need to keep the unsorted version around.</p>
<p>In Python 2.4 a new built-in function – <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> – has been added.
This function creates a new list from a provided iterable, sorts it and returns
it.  For example, here’s how to iterate over the keys of a dictionary in sorted
order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">mydict</span><span class="p">):</span>
    <span class="o">...</span>  <span class="c1"># do whatever with mydict[key]...</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-you-specify-and-enforce-an-interface-spec-in-python">
<h2><a class="toc-backref" href="#id22">How do you specify and enforce an interface spec in Python?</a><a class="headerlink" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python" title="Permalink to this headline">¶</a></h2>
<p>An interface specification for a module as provided by languages such as C++ and
Java describes the prototypes for the methods and functions of the module.  Many
feel that compile-time enforcement of interface specifications helps in the
construction of large programs.</p>
<p>Python 2.6 adds an <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module that lets you define Abstract Base Classes
(ABCs).  You can then use <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> to check
whether an instance or a class implements a particular ABC.  The
<a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module defines a set of useful ABCs such as
<a class="reference internal" href="../library/collections.html#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>, <a class="reference internal" href="../library/collections.html#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a>, and
<a class="reference internal" href="../library/collections.html#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a>.</p>
<p>For Python, many of the advantages of interface specifications can be obtained
by an appropriate test discipline for components.  There is also a tool,
PyChecker, which can be used to find problems due to subclassing.</p>
<p>A good test suite for a module can both provide a regression test and serve as a
module interface specification and a set of examples.  Many Python modules can
be run as a script to provide a simple “self test.”  Even modules which use
complex external interfaces can often be tested in isolation using trivial
“stub” emulations of the external interface.  The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> and
<a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> modules or third-party test frameworks can be used to construct
exhaustive test suites that exercise every line of code in a module.</p>
<p>An appropriate testing discipline can help build large complex applications in
Python as well as having interface specifications would.  In fact, it can be
better because an interface specification cannot test certain properties of a
program.  For example, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> method is expected to add new elements
to the end of some internal list; an interface specification cannot test that
your <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> implementation will actually do this correctly, but it’s
trivial to check this property in a test suite.</p>
<p>Writing test suites is very helpful, and you might want to design your code with
an eye to making it easily tested.  One increasingly popular technique,
test-directed development, calls for writing parts of the test suite first,
before you write any of the actual code.  Of course Python allows you to be
sloppy and not write test cases at all.</p>
</div>
<div class="section" id="why-is-there-no-goto">
<h2><a class="toc-backref" href="#id23">Why is there no goto?</a><a class="headerlink" href="#why-is-there-no-goto" title="Permalink to this headline">¶</a></h2>
<p>You can use exceptions to provide a “structured goto” that even works across
function calls.  Many feel that exceptions can conveniently emulate all
reasonable uses of the “go” or “goto” constructs of C, Fortran, and other
languages.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">label</span><span class="p">:</span> <span class="k">pass</span>  <span class="c1"># declare a label</span>

<span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">if</span> <span class="n">condition</span><span class="p">:</span> <span class="k">raise</span> <span class="n">label</span><span class="p">()</span>  <span class="c1"># goto label</span>
    <span class="o">...</span>
<span class="k">except</span> <span class="n">label</span><span class="p">:</span>  <span class="c1"># where to goto</span>
    <span class="k">pass</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This doesn’t allow you to jump into the middle of a loop, but that’s usually
considered an abuse of goto anyway.  Use sparingly.</p>
</div>
<div class="section" id="why-can-t-raw-strings-r-strings-end-with-a-backslash">
<h2><a class="toc-backref" href="#id24">Why can’t raw strings (r-strings) end with a backslash?</a><a class="headerlink" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash" title="Permalink to this headline">¶</a></h2>
<p>More precisely, they can’t end with an odd number of backslashes: the unpaired
backslash at the end escapes the closing quote character, leaving an
unterminated string.</p>
<p>Raw strings were designed to ease creating input for processors (chiefly regular
expression engines) that want to do their own backslash escape processing. Such
processors consider an unmatched trailing backslash to be an error anyway, so
raw strings disallow that.  In return, they allow you to pass on the string
quote character by escaping it with a backslash.  These rules work well when
r-strings are used for their intended purpose.</p>
<p>If you’re trying to build Windows pathnames, note that all Windows system calls
accept forward slashes too:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;/mydir/file.txt&quot;</span><span class="p">)</span>  <span class="c1"># works fine!</span>
</pre></div>
</div>
<p>If you’re trying to build a pathname for a DOS command, try e.g. one of</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">dir</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&quot;\this\is\my\dos\dir&quot;</span> <span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span>
<span class="nb">dir</span> <span class="o">=</span> <span class="sa">r</span><span class="s2">&quot;\this\is\my\dos\dir\ &quot;</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="nb">dir</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="se">\\</span><span class="s2">this</span><span class="se">\\</span><span class="s2">is</span><span class="se">\\</span><span class="s2">my</span><span class="se">\\</span><span class="s2">dos</span><span class="se">\\</span><span class="s2">dir</span><span class="se">\\</span><span class="s2">&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="why-doesn-t-python-have-a-with-statement-for-attribute-assignments">
<h2><a class="toc-backref" href="#id25">Why doesn’t Python have a “with” statement for attribute assignments?</a><a class="headerlink" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments" title="Permalink to this headline">¶</a></h2>
<p>Python has a ‘with’ statement that wraps the execution of a block, calling code
on the entrance and exit from the block.  Some language have a construct that
looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">obj</span><span class="p">:</span>
    <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>               <span class="c1"># equivalent to obj.a = 1</span>
    <span class="n">total</span> <span class="o">=</span> <span class="n">total</span> <span class="o">+</span> <span class="mi">1</span>   <span class="c1"># obj.total = obj.total + 1</span>
</pre></div>
</div>
<p>In Python, such a construct would be ambiguous.</p>
<p>Other languages, such as Object Pascal, Delphi, and C++, use static types, so
it’s possible to know, in an unambiguous way, what member is being assigned
to. This is the main point of static typing – the compiler <em>always</em> knows the
scope of every variable at compile time.</p>
<p>Python uses dynamic types. It is impossible to know in advance which attribute
will be referenced at runtime. Member attributes may be added or removed from
objects on the fly. This makes it impossible to know, from a simple reading,
what attribute is being referenced: a local one, a global one, or a member
attribute?</p>
<p>For instance, take the following incomplete snippet:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
    <span class="k">with</span> <span class="n">a</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">x</span>
</pre></div>
</div>
<p>The snippet assumes that “a” must have a member attribute called “x”.  However,
there is nothing in Python that tells the interpreter this. What should happen
if “a” is, let us say, an integer?  If there is a global variable named “x”,
will it be used inside the with block?  As you see, the dynamic nature of Python
makes such choices much harder.</p>
<p>The primary benefit of “with” and similar language features (reduction of code
volume) can, however, easily be achieved in Python by assignment.  Instead of:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">21</span>
<span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="mi">42</span>
<span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span><span class="o">.</span><span class="n">c</span> <span class="o">=</span> <span class="mi">63</span>
</pre></div>
</div>
<p>write this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ref</span> <span class="o">=</span> <span class="n">function</span><span class="p">(</span><span class="n">args</span><span class="p">)</span><span class="o">.</span><span class="n">mydict</span><span class="p">[</span><span class="n">index</span><span class="p">][</span><span class="n">index</span><span class="p">]</span>
<span class="n">ref</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">21</span>
<span class="n">ref</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="mi">42</span>
<span class="n">ref</span><span class="o">.</span><span class="n">c</span> <span class="o">=</span> <span class="mi">63</span>
</pre></div>
</div>
<p>This also has the side-effect of increasing execution speed because name
bindings are resolved at run-time in Python, and the second version only needs
to perform the resolution once.</p>
</div>
<div class="section" id="why-are-colons-required-for-the-if-while-def-class-statements">
<h2><a class="toc-backref" href="#id26">Why are colons required for the if/while/def/class statements?</a><a class="headerlink" href="#why-are-colons-required-for-the-if-while-def-class-statements" title="Permalink to this headline">¶</a></h2>
<p>The colon is required primarily to enhance readability (one of the results of
the experimental ABC language).  Consider this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span>
    <span class="nb">print</span> <span class="n">a</span>
</pre></div>
</div>
<p>versus</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">a</span>
</pre></div>
</div>
<p>Notice how the second one is slightly easier to read.  Notice further how a
colon sets off the example in this FAQ answer; it’s a standard usage in English.</p>
<p>Another minor reason is that the colon makes it easier for editors with syntax
highlighting; they can look for colons to decide when indentation needs to be
increased instead of having to do a more elaborate parsing of the program text.</p>
</div>
<div class="section" id="why-does-python-allow-commas-at-the-end-of-lists-and-tuples">
<h2><a class="toc-backref" href="#id27">Why does Python allow commas at the end of lists and tuples?</a><a class="headerlink" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples" title="Permalink to this headline">¶</a></h2>
<p>Python lets you add a trailing comma at the end of lists, tuples, and
dictionaries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,]</span>
<span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,)</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s2">&quot;A&quot;</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span>
    <span class="s2">&quot;B&quot;</span><span class="p">:</span> <span class="p">[</span><span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">],</span>  <span class="c1"># last trailing comma is optional but good style</span>
<span class="p">}</span>
</pre></div>
</div>
<p>There are several reasons to allow this.</p>
<p>When you have a literal value for a list, tuple, or dictionary spread across
multiple lines, it’s easier to add more elements because you don’t have to
remember to add a comma to the previous line.  The lines can also be reordered
without creating a syntax error.</p>
<p>Accidentally omitting the comma can lead to errors that are hard to diagnose.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span>
  <span class="s2">&quot;fee&quot;</span><span class="p">,</span>
  <span class="s2">&quot;fie&quot;</span>
  <span class="s2">&quot;foo&quot;</span><span class="p">,</span>
  <span class="s2">&quot;fum&quot;</span>
<span class="p">]</span>
</pre></div>
</div>
<p>This list looks like it has four elements, but it actually contains three:
“fee”, “fiefoo” and “fum”.  Always adding the comma avoids this source of error.</p>
<p>Allowing the trailing comma may also make programmatic code generation easier.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Design and History FAQ</a><ul>
<li><a class="reference internal" href="#why-does-python-use-indentation-for-grouping-of-statements">Why does Python use indentation for grouping of statements?</a></li>
<li><a class="reference internal" href="#why-am-i-getting-strange-results-with-simple-arithmetic-operations">Why am I getting strange results with simple arithmetic operations?</a></li>
<li><a class="reference internal" href="#why-are-floating-point-calculations-so-inaccurate">Why are floating point calculations so inaccurate?</a></li>
<li><a class="reference internal" href="#why-are-python-strings-immutable">Why are Python strings immutable?</a></li>
<li><a class="reference internal" href="#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must ‘self’ be used explicitly in method definitions and calls?</a></li>
<li><a class="reference internal" href="#why-can-t-i-use-an-assignment-in-an-expression">Why can’t I use an assignment in an expression?</a></li>
<li><a class="reference internal" href="#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
<li><a class="reference internal" href="#why-is-join-a-string-method-instead-of-a-list-or-tuple-method">Why is join() a string method instead of a list or tuple method?</a></li>
<li><a class="reference internal" href="#how-fast-are-exceptions">How fast are exceptions?</a></li>
<li><a class="reference internal" href="#why-isn-t-there-a-switch-or-case-statement-in-python">Why isn’t there a switch or case statement in Python?</a></li>
<li><a class="reference internal" href="#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
<li><a class="reference internal" href="#why-can-t-lambda-expressions-contain-statements">Why can’t lambda expressions contain statements?</a></li>
<li><a class="reference internal" href="#can-python-be-compiled-to-machine-code-c-or-some-other-language">Can Python be compiled to machine code, C or some other language?</a></li>
<li><a class="reference internal" href="#how-does-python-manage-memory">How does Python manage memory?</a></li>
<li><a class="reference internal" href="#why-isn-t-all-memory-freed-when-python-exits">Why isn’t all memory freed when Python exits?</a></li>
<li><a class="reference internal" href="#why-are-there-separate-tuple-and-list-data-types">Why are there separate tuple and list data types?</a></li>
<li><a class="reference internal" href="#how-are-lists-implemented-in-cpython">How are lists implemented in CPython?</a></li>
<li><a class="reference internal" href="#how-are-dictionaries-implemented-in-cpython">How are dictionaries implemented in CPython?</a></li>
<li><a class="reference internal" href="#why-must-dictionary-keys-be-immutable">Why must dictionary keys be immutable?</a></li>
<li><a class="reference internal" href="#why-doesn-t-list-sort-return-the-sorted-list">Why doesn’t list.sort() return the sorted list?</a></li>
<li><a class="reference internal" href="#how-do-you-specify-and-enforce-an-interface-spec-in-python">How do you specify and enforce an interface spec in Python?</a></li>
<li><a class="reference internal" href="#why-is-there-no-goto">Why is there no goto?</a></li>
<li><a class="reference internal" href="#why-can-t-raw-strings-r-strings-end-with-a-backslash">Why can’t raw strings (r-strings) end with a backslash?</a></li>
<li><a class="reference internal" href="#why-doesn-t-python-have-a-with-statement-for-attribute-assignments">Why doesn’t Python have a “with” statement for attribute assignments?</a></li>
<li><a class="reference internal" href="#why-are-colons-required-for-the-if-while-def-class-statements">Why are colons required for the if/while/def/class statements?</a></li>
<li><a class="reference internal" href="#why-does-python-allow-commas-at-the-end-of-lists-and-tuples">Why does Python allow commas at the end of lists and tuples?</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="programming.html"
                        title="previous chapter">Programming FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="library.html"
                        title="next chapter">Library and Extension FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/design.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="programming.html" title="Programming FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\������html/faq/extending.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Extending/Embedding FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python on Windows FAQ" href="windows.html" />
    <link rel="prev" title="Library and Extension FAQ" href="library.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/extending.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="Python on Windows FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="extending-embedding-faq">
<h1><a class="toc-backref" href="#id2">Extending/Embedding FAQ</a><a class="headerlink" href="#extending-embedding-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#extending-embedding-faq" id="id2">Extending/Embedding FAQ</a><ul>
<li><a class="reference internal" href="#can-i-create-my-own-functions-in-c" id="id3">Can I create my own functions in C?</a></li>
<li><a class="reference internal" href="#id1" id="id4">Can I create my own functions in C++?</a></li>
<li><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives" id="id5">Writing C is hard; are there any alternatives?</a></li>
<li><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c" id="id6">How can I execute arbitrary Python statements from C?</a></li>
<li><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" id="id7">How can I evaluate an arbitrary Python expression from C?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object" id="id8">How do I extract C values from a Python object?</a></li>
<li><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" id="id9">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
<li><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c" id="id10">How do I call an object’s method from C?</a></li>
<li><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" id="id11">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
<li><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c" id="id12">How do I access a module written in Python from C?</a></li>
<li><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python" id="id13">How do I interface to C++ objects from Python?</a></li>
<li><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" id="id14">I added a module using the Setup file and the make fails; why?</a></li>
<li><a class="reference internal" href="#how-do-i-debug-an-extension" id="id15">How do I debug an extension?</a></li>
<li><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" id="id16">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
<li><a class="reference internal" href="#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean" id="id17">What does “SystemError: _PyImport_FixupExtension: module yourmodule not loaded” mean?</a></li>
<li><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input" id="id18">How do I tell “incomplete input” from “invalid input”?</a></li>
<li><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" id="id19">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
<li><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" id="id20">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
<li><a class="reference internal" href="#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2" id="id21">When importing module X, why do I get “undefined symbol: PyUnicodeUCS2*”?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="can-i-create-my-own-functions-in-c">
<h2><a class="toc-backref" href="#id3">Can I create my own functions in C?</a><a class="headerlink" href="#can-i-create-my-own-functions-in-c" title="Permalink to this headline">¶</a></h2>
<p>Yes, you can create built-in modules containing functions, variables, exceptions
and even new types in C.  This is explained in the document
<a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a>.</p>
<p>Most intermediate or advanced Python books will also cover this topic.</p>
</div>
<div class="section" id="id1">
<h2><a class="toc-backref" href="#id4">Can I create my own functions in C++?</a><a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>Yes, using the C compatibility features found in C++.  Place <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span> <span class="pre">{</span>
<span class="pre">...</span> <span class="pre">}</span></code> around the Python include files and put <code class="docutils literal notranslate"><span class="pre">extern</span> <span class="pre">&quot;C&quot;</span></code> before each
function that is going to be called by the Python interpreter.  Global or static
C++ objects with constructors are probably not a good idea.</p>
</div>
<div class="section" id="writing-c-is-hard-are-there-any-alternatives">
<span id="c-wrapper-software"></span><h2><a class="toc-backref" href="#id5">Writing C is hard; are there any alternatives?</a><a class="headerlink" href="#writing-c-is-hard-are-there-any-alternatives" title="Permalink to this headline">¶</a></h2>
<p>There are a number of alternatives to writing your own C extensions, depending
on what you’re trying to do.</p>
<p>If you need more speed, <a class="reference external" href="http://psyco.sourceforge.net/">Psyco</a> generates x86
assembly code from Python bytecode.  You can use Psyco to compile the most
time-critical functions in your code, and gain a significant improvement with
very little effort, as long as you’re running on a machine with an
x86-compatible processor.</p>
<p><a class="reference external" href="http://cython.org">Cython</a> and its relative <a class="reference external" href="https://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/">Pyrex</a> are compilers
that accept a slightly modified form of Python and generate the corresponding
C code.  Pyrex makes it possible to write an extension without having to learn
Python’s C API.</p>
<p>If you need to interface to some C or C++ library for which no Python extension
currently exists, you can try wrapping the library’s data types and functions
with a tool such as <a class="reference external" href="http://www.swig.org">SWIG</a>.  <a class="reference external" href="https://riverbankcomputing.com/software/sip/intro">SIP</a>, <a class="reference external" href="http://cxx.sourceforge.net/">CXX</a> <a class="reference external" href="http://www.boost.org/libs/python/doc/index.html">Boost</a>, or <a class="reference external" href="https://github.com/scipy/weave">Weave</a> are also
alternatives for wrapping C++ libraries.</p>
</div>
<div class="section" id="how-can-i-execute-arbitrary-python-statements-from-c">
<h2><a class="toc-backref" href="#id6">How can I execute arbitrary Python statements from C?</a><a class="headerlink" href="#how-can-i-execute-arbitrary-python-statements-from-c" title="Permalink to this headline">¶</a></h2>
<p>The highest-level function to do this is <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleString()</span></code></a> which takes
a single string argument to be executed in the context of the module
<code class="docutils literal notranslate"><span class="pre">__main__</span></code> and returns 0 for success and -1 when an exception occurred
(including <code class="docutils literal notranslate"><span class="pre">SyntaxError</span></code>).  If you want more control, use
<a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_String" title="PyRun_String"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_String()</span></code></a>; see the source for <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_SimpleString" title="PyRun_SimpleString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_SimpleString()</span></code></a> in
<code class="docutils literal notranslate"><span class="pre">Python/pythonrun.c</span></code>.</p>
</div>
<div class="section" id="how-can-i-evaluate-an-arbitrary-python-expression-from-c">
<h2><a class="toc-backref" href="#id7">How can I evaluate an arbitrary Python expression from C?</a><a class="headerlink" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c" title="Permalink to this headline">¶</a></h2>
<p>Call the function <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_String" title="PyRun_String"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_String()</span></code></a> from the previous question with the
start symbol <a class="reference internal" href="../c-api/veryhigh.html#c.Py_eval_input" title="Py_eval_input"><code class="xref c c-data docutils literal notranslate"><span class="pre">Py_eval_input</span></code></a>; it parses an expression, evaluates it and
returns its value.</p>
</div>
<div class="section" id="how-do-i-extract-c-values-from-a-python-object">
<h2><a class="toc-backref" href="#id8">How do I extract C values from a Python object?</a><a class="headerlink" href="#how-do-i-extract-c-values-from-a-python-object" title="Permalink to this headline">¶</a></h2>
<p>That depends on the object’s type.  If it’s a tuple, <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_Size" title="PyTuple_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_Size()</span></code></a>
returns its length and <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_GetItem" title="PyTuple_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_GetItem()</span></code></a> returns the item at a specified
index.  Lists have similar functions, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyListSize()</span></code> and
<a class="reference internal" href="../c-api/list.html#c.PyList_GetItem" title="PyList_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_GetItem()</span></code></a>.</p>
<p>For strings, <a class="reference internal" href="../c-api/string.html#c.PyString_Size" title="PyString_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_Size()</span></code></a> returns its length and
<a class="reference internal" href="../c-api/string.html#c.PyString_AsString" title="PyString_AsString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_AsString()</span></code></a> a pointer to its value.  Note that Python strings may
contain null bytes so C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">strlen()</span></code> should not be used.</p>
<p>To test the type of an object, first make sure it isn’t <em>NULL</em>, and then use
<a class="reference internal" href="../c-api/string.html#c.PyString_Check" title="PyString_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyString_Check()</span></code></a>, <a class="reference internal" href="../c-api/tuple.html#c.PyTuple_Check" title="PyTuple_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyTuple_Check()</span></code></a>, <a class="reference internal" href="../c-api/list.html#c.PyList_Check" title="PyList_Check"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Check()</span></code></a>, etc.</p>
<p>There is also a high-level API to Python objects which is provided by the
so-called ‘abstract’ interface – read <code class="docutils literal notranslate"><span class="pre">Include/abstract.h</span></code> for further
details.  It allows interfacing with any kind of Python sequence using calls
like <a class="reference internal" href="../c-api/sequence.html#c.PySequence_Length" title="PySequence_Length"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_Length()</span></code></a>, <a class="reference internal" href="../c-api/sequence.html#c.PySequence_GetItem" title="PySequence_GetItem"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySequence_GetItem()</span></code></a>, etc.)  as well as
many other useful protocols.</p>
</div>
<div class="section" id="how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">
<h2><a class="toc-backref" href="#id9">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a><a class="headerlink" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length" title="Permalink to this headline">¶</a></h2>
<p>You can’t.  Use <code class="docutils literal notranslate"><span class="pre">t</span> <span class="pre">=</span> <span class="pre">PyTuple_New(n)</span></code> instead, and fill it with objects using
<code class="docutils literal notranslate"><span class="pre">PyTuple_SetItem(t,</span> <span class="pre">i,</span> <span class="pre">o)</span></code> – note that this “eats” a reference count of
<code class="docutils literal notranslate"><span class="pre">o</span></code>, so you have to <a class="reference internal" href="../c-api/refcounting.html#c.Py_INCREF" title="Py_INCREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_INCREF()</span></code></a> it.  Lists have similar functions
<code class="docutils literal notranslate"><span class="pre">PyList_New(n)</span></code> and <code class="docutils literal notranslate"><span class="pre">PyList_SetItem(l,</span> <span class="pre">i,</span> <span class="pre">o)</span></code>.  Note that you <em>must</em> set all
the tuple items to some value before you pass the tuple to Python code –
<code class="docutils literal notranslate"><span class="pre">PyTuple_New(n)</span></code> initializes them to NULL, which isn’t a valid Python value.</p>
</div>
<div class="section" id="how-do-i-call-an-object-s-method-from-c">
<h2><a class="toc-backref" href="#id10">How do I call an object’s method from C?</a><a class="headerlink" href="#how-do-i-call-an-object-s-method-from-c" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../c-api/object.html#c.PyObject_CallMethod" title="PyObject_CallMethod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallMethod()</span></code></a> function can be used to call an arbitrary
method of an object.  The parameters are the object, the name of the method to
call, a format string like that used with <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a>, and the
argument values:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">PyObject_CallMethod</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">object</span><span class="p">,</span> <span class="kt">char</span> <span class="o">*</span><span class="n">method_name</span><span class="p">,</span>
                    <span class="kt">char</span> <span class="o">*</span><span class="n">arg_format</span><span class="p">,</span> <span class="p">...);</span>
</pre></div>
</div>
<p>This works for any object that has methods – whether built-in or user-defined.
You are responsible for eventually <a class="reference internal" href="../c-api/refcounting.html#c.Py_DECREF" title="Py_DECREF"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_DECREF()</span></code></a>’ing the return value.</p>
<p>To call, e.g., a file object’s “seek” method with arguments 10, 0 (assuming the
file object pointer is “f”):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="n">PyObject_CallMethod</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s">&quot;seek&quot;</span><span class="p">,</span> <span class="s">&quot;(ii)&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">res</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="p">...</span> <span class="n">an</span> <span class="n">exception</span> <span class="n">occurred</span> <span class="p">...</span>
<span class="p">}</span>
<span class="k">else</span> <span class="p">{</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">res</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Note that since <a class="reference internal" href="../c-api/object.html#c.PyObject_CallObject" title="PyObject_CallObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_CallObject()</span></code></a> <em>always</em> wants a tuple for the
argument list, to call a function without arguments, pass “()” for the format,
and to call a function with one argument, surround the argument in parentheses,
e.g. “(i)”.</p>
</div>
<div class="section" id="how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">
<h2><a class="toc-backref" href="#id11">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a><a class="headerlink" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr" title="Permalink to this headline">¶</a></h2>
<p>In Python code, define an object that supports the <code class="docutils literal notranslate"><span class="pre">write()</span></code> method.  Assign
this object to <a class="reference internal" href="../library/sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.  Call print_error, or
just allow the standard traceback mechanism to work. Then, the output will go
wherever your <code class="docutils literal notranslate"><span class="pre">write()</span></code> method sends it.</p>
<p>The easiest way to do this is to use the StringIO class in the standard library.</p>
<p>Sample code and use for catching stdout:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">StdoutCatcher</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">stuff</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">+</span> <span class="n">stuff</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span> <span class="o">=</span> <span class="n">StdoutCatcher</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="s1">&#39;foo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="s1">&#39;hello world!&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
<span class="go">foo</span>
<span class="go">hello world!</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-access-a-module-written-in-python-from-c">
<h2><a class="toc-backref" href="#id12">How do I access a module written in Python from C?</a><a class="headerlink" href="#how-do-i-access-a-module-written-in-python-from-c" title="Permalink to this headline">¶</a></h2>
<p>You can get a pointer to the module object as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">module</span> <span class="o">=</span> <span class="n">PyImport_ImportModule</span><span class="p">(</span><span class="s">&quot;&lt;modulename&gt;&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>If the module hasn’t been imported yet (i.e. it is not yet present in
<a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>), this initializes the module; otherwise it simply returns
the value of <code class="docutils literal notranslate"><span class="pre">sys.modules[&quot;&lt;modulename&gt;&quot;]</span></code>.  Note that it doesn’t enter the
module into any namespace – it only ensures it has been initialized and is
stored in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p>
<p>You can then access the module’s attributes (i.e. any name defined in the
module) as follows:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">attr</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">module</span><span class="p">,</span> <span class="s">&quot;&lt;attrname&gt;&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>Calling <a class="reference internal" href="../c-api/object.html#c.PyObject_SetAttrString" title="PyObject_SetAttrString"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_SetAttrString()</span></code></a> to assign to variables in the module
also works.</p>
</div>
<div class="section" id="how-do-i-interface-to-c-objects-from-python">
<h2><a class="toc-backref" href="#id13">How do I interface to C++ objects from Python?</a><a class="headerlink" href="#how-do-i-interface-to-c-objects-from-python" title="Permalink to this headline">¶</a></h2>
<p>Depending on your requirements, there are many approaches.  To do this manually,
begin by reading <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">the “Extending and Embedding” document</span></a>.  Realize that for the Python run-time system, there isn’t a
whole lot of difference between C and C++ – so the strategy of building a new
Python type around a C structure (pointer) type will also work for C++ objects.</p>
<p>For C++ libraries, see <a class="reference internal" href="#c-wrapper-software"><span class="std std-ref">Writing C is hard; are there any alternatives?</span></a>.</p>
</div>
<div class="section" id="i-added-a-module-using-the-setup-file-and-the-make-fails-why">
<h2><a class="toc-backref" href="#id14">I added a module using the Setup file and the make fails; why?</a><a class="headerlink" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why" title="Permalink to this headline">¶</a></h2>
<p>Setup must end in a newline, if there is no newline there, the build process
fails.  (Fixing this requires some ugly shell script hackery, and this bug is so
minor that it doesn’t seem worth the effort.)</p>
</div>
<div class="section" id="how-do-i-debug-an-extension">
<h2><a class="toc-backref" href="#id15">How do I debug an extension?</a><a class="headerlink" href="#how-do-i-debug-an-extension" title="Permalink to this headline">¶</a></h2>
<p>When using GDB with dynamically loaded extensions, you can’t set a breakpoint in
your extension until your extension is loaded.</p>
<p>In your <code class="docutils literal notranslate"><span class="pre">.gdbinit</span></code> file (or interactively), add the command:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>br _PyImport_LoadDynamicModule
</pre></div>
</div>
<p>Then, when you run GDB:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> gdb /local/bin/python
<span class="go">gdb) run myscript.py</span>
<span class="go">gdb) continue # repeat until your extension is loaded</span>
<span class="go">gdb) finish   # so that your extension is loaded</span>
<span class="go">gdb) br myfunction.c:50</span>
<span class="go">gdb) continue</span>
</pre></div>
</div>
</div>
<div class="section" id="i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">
<h2><a class="toc-backref" href="#id16">I want to compile a Python module on my Linux system, but some files are missing. Why?</a><a class="headerlink" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why" title="Permalink to this headline">¶</a></h2>
<p>Most packaged versions of Python don’t include the
<code class="file docutils literal notranslate"><span class="pre">/usr/lib/python2.</span><em><span class="pre">x</span></em><span class="pre">/config/</span></code> directory, which contains various files
required for compiling Python extensions.</p>
<p>For Red Hat, install the python-devel RPM to get the necessary files.</p>
<p>For Debian, run <code class="docutils literal notranslate"><span class="pre">apt-get</span> <span class="pre">install</span> <span class="pre">python-dev</span></code>.</p>
</div>
<div class="section" id="what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean">
<h2><a class="toc-backref" href="#id17">What does “SystemError: _PyImport_FixupExtension: module yourmodule not loaded” mean?</a><a class="headerlink" href="#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean" title="Permalink to this headline">¶</a></h2>
<p>This means that you have created an extension module named “yourmodule”, but
your module init function does not initialize with that name.</p>
<p>Every module init function will have a line similar to:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">module</span> <span class="o">=</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;yourmodule&quot;</span><span class="p">,</span> <span class="n">yourmodule_functions</span><span class="p">);</span>
</pre></div>
</div>
<p>If the string passed to this function is not the same name as your extension
module, the <a class="reference internal" href="../library/exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> exception will be raised.</p>
</div>
<div class="section" id="how-do-i-tell-incomplete-input-from-invalid-input">
<h2><a class="toc-backref" href="#id18">How do I tell “incomplete input” from “invalid input”?</a><a class="headerlink" href="#how-do-i-tell-incomplete-input-from-invalid-input" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want to emulate the Python interactive interpreter’s behavior,
where it gives you a continuation prompt when the input is incomplete (e.g. you
typed the start of an “if” statement or you didn’t close your parentheses or
triple string quotes), but it gives you a syntax error message immediately when
the input is invalid.</p>
<p>In Python you can use the <a class="reference internal" href="../library/codeop.html#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> module, which approximates the parser’s
behavior sufficiently.  IDLE uses this, for example.</p>
<p>The easiest way to do it in C is to call <a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_InteractiveLoop" title="PyRun_InteractiveLoop"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveLoop()</span></code></a> (perhaps
in a separate thread) and let the Python interpreter handle the input for
you. You can also set the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ReadlineFunctionPointer()</span></code> to point at your
custom input function. See <code class="docutils literal notranslate"><span class="pre">Modules/readline.c</span></code> and <code class="docutils literal notranslate"><span class="pre">Parser/myreadline.c</span></code>
for more hints.</p>
<p>However sometimes you have to run the embedded Python interpreter in the same
thread as your rest application and you can’t allow the
<a class="reference internal" href="../c-api/veryhigh.html#c.PyRun_InteractiveLoop" title="PyRun_InteractiveLoop"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyRun_InteractiveLoop()</span></code></a> to stop while waiting for user input.  The one
solution then is to call <code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_ParseString()</span></code> and test for <code class="docutils literal notranslate"><span class="pre">e.error</span></code>
equal to <code class="docutils literal notranslate"><span class="pre">E_EOF</span></code>, which means the input is incomplete.  Here’s a sample code
fragment, untested, inspired by code from Alex Farber:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;node.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;errcode.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;grammar.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;parsetok.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;compile.h&gt;</span><span class="cp"></span>

<span class="kt">int</span> <span class="nf">testcomplete</span><span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="n">code</span><span class="p">)</span>
  <span class="cm">/* code should end in \n */</span>
  <span class="cm">/* return -1 for error, 0 for incomplete, 1 for complete */</span>
<span class="p">{</span>
  <span class="n">node</span> <span class="o">*</span><span class="n">n</span><span class="p">;</span>
  <span class="n">perrdetail</span> <span class="n">e</span><span class="p">;</span>

  <span class="n">n</span> <span class="o">=</span> <span class="n">PyParser_ParseString</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">_PyParser_Grammar</span><span class="p">,</span>
                           <span class="n">Py_file_input</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">e</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="n">n</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">e</span><span class="p">.</span><span class="n">error</span> <span class="o">==</span> <span class="n">E_EOF</span><span class="p">)</span>
      <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
    <span class="k">return</span> <span class="o">-</span><span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="n">PyNode_Free</span><span class="p">(</span><span class="n">n</span><span class="p">);</span>
  <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>Another solution is trying to compile the received string with
<a class="reference internal" href="../c-api/veryhigh.html#c.Py_CompileString" title="Py_CompileString"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_CompileString()</span></code></a>. If it compiles without errors, try to execute the
returned code object by calling <a class="reference internal" href="../c-api/veryhigh.html#c.PyEval_EvalCode" title="PyEval_EvalCode"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_EvalCode()</span></code></a>. Otherwise save the
input for later. If the compilation fails, find out if it’s an error or just
more input is required - by extracting the message string from the exception
tuple and comparing it to the string “unexpected EOF while parsing”.  Here is a
complete example using the GNU readline library (you may want to ignore
<strong>SIGINT</strong> while calling readline()):</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&lt;stdio.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;readline.h&gt;</span><span class="cp"></span>

<span class="cp">#include</span> <span class="cpf">&lt;Python.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;object.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;compile.h&gt;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&lt;eval.h&gt;</span><span class="cp"></span>

<span class="kt">int</span> <span class="nf">main</span> <span class="p">(</span><span class="kt">int</span> <span class="n">argc</span><span class="p">,</span> <span class="kt">char</span><span class="o">*</span> <span class="n">argv</span><span class="p">[])</span>
<span class="p">{</span>
  <span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">,</span> <span class="n">done</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>                          <span class="cm">/* lengths of line, code */</span>
  <span class="kt">char</span> <span class="n">ps1</span><span class="p">[]</span> <span class="o">=</span> <span class="s">&quot;&gt;&gt;&gt; &quot;</span><span class="p">;</span>
  <span class="kt">char</span> <span class="n">ps2</span><span class="p">[]</span> <span class="o">=</span> <span class="s">&quot;... &quot;</span><span class="p">;</span>
  <span class="kt">char</span> <span class="o">*</span><span class="n">prompt</span> <span class="o">=</span> <span class="n">ps1</span><span class="p">;</span>
  <span class="kt">char</span> <span class="o">*</span><span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">line</span><span class="p">,</span> <span class="o">*</span><span class="n">code</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
  <span class="n">PyObject</span> <span class="o">*</span><span class="n">src</span><span class="p">,</span> <span class="o">*</span><span class="n">glb</span><span class="p">,</span> <span class="o">*</span><span class="n">loc</span><span class="p">;</span>
  <span class="n">PyObject</span> <span class="o">*</span><span class="n">exc</span><span class="p">,</span> <span class="o">*</span><span class="n">val</span><span class="p">,</span> <span class="o">*</span><span class="n">trb</span><span class="p">,</span> <span class="o">*</span><span class="n">obj</span><span class="p">,</span> <span class="o">*</span><span class="n">dum</span><span class="p">;</span>

  <span class="n">Py_Initialize</span> <span class="p">();</span>
  <span class="n">loc</span> <span class="o">=</span> <span class="n">PyDict_New</span> <span class="p">();</span>
  <span class="n">glb</span> <span class="o">=</span> <span class="n">PyDict_New</span> <span class="p">();</span>
  <span class="n">PyDict_SetItemString</span> <span class="p">(</span><span class="n">glb</span><span class="p">,</span> <span class="s">&quot;__builtins__&quot;</span><span class="p">,</span> <span class="n">PyEval_GetBuiltins</span> <span class="p">());</span>

  <span class="k">while</span> <span class="p">(</span><span class="o">!</span><span class="n">done</span><span class="p">)</span>
  <span class="p">{</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">readline</span> <span class="p">(</span><span class="n">prompt</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="nb">NULL</span> <span class="o">==</span> <span class="n">line</span><span class="p">)</span>                          <span class="cm">/* Ctrl-D pressed */</span>
    <span class="p">{</span>
      <span class="n">done</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="k">else</span>
    <span class="p">{</span>
      <span class="n">i</span> <span class="o">=</span> <span class="n">strlen</span> <span class="p">(</span><span class="n">line</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span>
        <span class="n">add_history</span> <span class="p">(</span><span class="n">line</span><span class="p">);</span>                    <span class="cm">/* save non-empty lines */</span>

      <span class="k">if</span> <span class="p">(</span><span class="nb">NULL</span> <span class="o">==</span> <span class="n">code</span><span class="p">)</span>                        <span class="cm">/* nothing in code yet */</span>
        <span class="n">j</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
      <span class="k">else</span>
        <span class="n">j</span> <span class="o">=</span> <span class="n">strlen</span> <span class="p">(</span><span class="n">code</span><span class="p">);</span>

      <span class="n">code</span> <span class="o">=</span> <span class="n">realloc</span> <span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">i</span> <span class="o">+</span> <span class="n">j</span> <span class="o">+</span> <span class="mi">2</span><span class="p">);</span>
      <span class="k">if</span> <span class="p">(</span><span class="nb">NULL</span> <span class="o">==</span> <span class="n">code</span><span class="p">)</span>                        <span class="cm">/* out of memory */</span>
        <span class="n">exit</span> <span class="p">(</span><span class="mi">1</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="mi">0</span> <span class="o">==</span> <span class="n">j</span><span class="p">)</span>                              <span class="cm">/* code was empty, so */</span>
        <span class="n">code</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="sc">&#39;\0&#39;</span><span class="p">;</span>                        <span class="cm">/* keep strncat happy */</span>

      <span class="n">strncat</span> <span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">line</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span>                 <span class="cm">/* append line to code */</span>
      <span class="n">code</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="sc">&#39;\n&#39;</span><span class="p">;</span>                      <span class="cm">/* append &#39;\n&#39; to code */</span>
      <span class="n">code</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="n">j</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="sc">&#39;\0&#39;</span><span class="p">;</span>

      <span class="n">src</span> <span class="o">=</span> <span class="n">Py_CompileString</span> <span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="s">&quot;&lt;stdin&gt;&quot;</span><span class="p">,</span> <span class="n">Py_single_input</span><span class="p">);</span>

      <span class="k">if</span> <span class="p">(</span><span class="nb">NULL</span> <span class="o">!=</span> <span class="n">src</span><span class="p">)</span>                         <span class="cm">/* compiled just fine - */</span>
      <span class="p">{</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">ps1</span>  <span class="o">==</span> <span class="n">prompt</span> <span class="o">||</span>                  <span class="cm">/* &quot;&gt;&gt;&gt; &quot; or */</span>
            <span class="sc">&#39;\n&#39;</span> <span class="o">==</span> <span class="n">code</span><span class="p">[</span><span class="n">i</span> <span class="o">+</span> <span class="n">j</span> <span class="o">-</span> <span class="mi">1</span><span class="p">])</span>           <span class="cm">/* &quot;... &quot; and double &#39;\n&#39; */</span>
        <span class="p">{</span>                                               <span class="cm">/* so execute it */</span>
          <span class="n">dum</span> <span class="o">=</span> <span class="n">PyEval_EvalCode</span> <span class="p">((</span><span class="n">PyCodeObject</span> <span class="o">*</span><span class="p">)</span><span class="n">src</span><span class="p">,</span> <span class="n">glb</span><span class="p">,</span> <span class="n">loc</span><span class="p">);</span>
          <span class="n">Py_XDECREF</span> <span class="p">(</span><span class="n">dum</span><span class="p">);</span>
          <span class="n">Py_XDECREF</span> <span class="p">(</span><span class="n">src</span><span class="p">);</span>
          <span class="n">free</span> <span class="p">(</span><span class="n">code</span><span class="p">);</span>
          <span class="n">code</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
          <span class="k">if</span> <span class="p">(</span><span class="n">PyErr_Occurred</span> <span class="p">())</span>
            <span class="n">PyErr_Print</span> <span class="p">();</span>
          <span class="n">prompt</span> <span class="o">=</span> <span class="n">ps1</span><span class="p">;</span>
        <span class="p">}</span>
      <span class="p">}</span>                                        <span class="cm">/* syntax error or E_EOF? */</span>
      <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">PyErr_ExceptionMatches</span> <span class="p">(</span><span class="n">PyExc_SyntaxError</span><span class="p">))</span>
      <span class="p">{</span>
        <span class="n">PyErr_Fetch</span> <span class="p">(</span><span class="o">&amp;</span><span class="n">exc</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">val</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">trb</span><span class="p">);</span>        <span class="cm">/* clears exception! */</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">PyArg_ParseTuple</span> <span class="p">(</span><span class="n">val</span><span class="p">,</span> <span class="s">&quot;sO&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">msg</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">obj</span><span class="p">)</span> <span class="o">&amp;&amp;</span>
            <span class="o">!</span><span class="n">strcmp</span> <span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="s">&quot;unexpected EOF while parsing&quot;</span><span class="p">))</span> <span class="cm">/* E_EOF */</span>
        <span class="p">{</span>
          <span class="n">Py_XDECREF</span> <span class="p">(</span><span class="n">exc</span><span class="p">);</span>
          <span class="n">Py_XDECREF</span> <span class="p">(</span><span class="n">val</span><span class="p">);</span>
          <span class="n">Py_XDECREF</span> <span class="p">(</span><span class="n">trb</span><span class="p">);</span>
          <span class="n">prompt</span> <span class="o">=</span> <span class="n">ps2</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span>                                   <span class="cm">/* some other syntax error */</span>
        <span class="p">{</span>
          <span class="n">PyErr_Restore</span> <span class="p">(</span><span class="n">exc</span><span class="p">,</span> <span class="n">val</span><span class="p">,</span> <span class="n">trb</span><span class="p">);</span>
          <span class="n">PyErr_Print</span> <span class="p">();</span>
          <span class="n">free</span> <span class="p">(</span><span class="n">code</span><span class="p">);</span>
          <span class="n">code</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
          <span class="n">prompt</span> <span class="o">=</span> <span class="n">ps1</span><span class="p">;</span>
        <span class="p">}</span>
      <span class="p">}</span>
      <span class="k">else</span>                                     <span class="cm">/* some non-syntax error */</span>
      <span class="p">{</span>
        <span class="n">PyErr_Print</span> <span class="p">();</span>
        <span class="n">free</span> <span class="p">(</span><span class="n">code</span><span class="p">);</span>
        <span class="n">code</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
        <span class="n">prompt</span> <span class="o">=</span> <span class="n">ps1</span><span class="p">;</span>
      <span class="p">}</span>

      <span class="n">free</span> <span class="p">(</span><span class="n">line</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">glb</span><span class="p">);</span>
  <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">loc</span><span class="p">);</span>
  <span class="n">Py_Finalize</span><span class="p">();</span>
  <span class="n">exit</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">
<h2><a class="toc-backref" href="#id19">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a><a class="headerlink" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual" title="Permalink to this headline">¶</a></h2>
<p>To dynamically load g++ extension modules, you must recompile Python, relink it
using g++ (change LINKCC in the Python Modules Makefile), and link your
extension module using g++ (e.g., <code class="docutils literal notranslate"><span class="pre">g++</span> <span class="pre">-shared</span> <span class="pre">-o</span> <span class="pre">mymodule.so</span> <span class="pre">mymodule.o</span></code>).</p>
</div>
<div class="section" id="can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">
<h2><a class="toc-backref" href="#id20">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a><a class="headerlink" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance" title="Permalink to this headline">¶</a></h2>
<p>Yes, you can inherit from built-in classes such as <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, etc.</p>
<p>The Boost Python Library (BPL, <a class="reference external" href="http://www.boost.org/libs/python/doc/index.html">http://www.boost.org/libs/python/doc/index.html</a>)
provides a way of doing this from C++ (i.e. you can inherit from an extension
class written in C++ using the BPL).</p>
</div>
<div class="section" id="when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2">
<h2><a class="toc-backref" href="#id21">When importing module X, why do I get “undefined symbol: PyUnicodeUCS2*”?</a><a class="headerlink" href="#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2" title="Permalink to this headline">¶</a></h2>
<p>You are using a version of Python that uses a 4-byte representation for Unicode
characters, but some C extension module you are importing was compiled using a
Python that uses a 2-byte representation for Unicode characters (the default).</p>
<p>If instead the name of the undefined symbol starts with <code class="docutils literal notranslate"><span class="pre">PyUnicodeUCS4</span></code>, the
problem is the reverse: Python was built using 2-byte Unicode characters, and
the extension module was compiled using a Python with 4-byte Unicode characters.</p>
<p>This can easily occur when using pre-built extension packages.  RedHat Linux
7.x, in particular, provided a “python2” binary that is compiled with 4-byte
Unicode.  This only causes the link failure if the extension uses any of the
<code class="docutils literal notranslate"><span class="pre">PyUnicode_*()</span></code> functions.  It is also a problem if an extension uses any of
the Unicode-related format specifiers for <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> (or similar) or
parameter specifications for <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>.</p>
<p>You can check the size of the Unicode character a Python interpreter is using by
checking the value of sys.maxunicode:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">maxunicode</span> <span class="o">&gt;</span> <span class="mi">65535</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s1">&#39;UCS4 build&#39;</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s1">&#39;UCS2 build&#39;</span>
</pre></div>
</div>
<p>The only way to solve this problem is to use extension modules compiled with a
Python binary built using the same size for Unicode characters.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Extending/Embedding FAQ</a><ul>
<li><a class="reference internal" href="#can-i-create-my-own-functions-in-c">Can I create my own functions in C?</a></li>
<li><a class="reference internal" href="#id1">Can I create my own functions in C++?</a></li>
<li><a class="reference internal" href="#writing-c-is-hard-are-there-any-alternatives">Writing C is hard; are there any alternatives?</a></li>
<li><a class="reference internal" href="#how-can-i-execute-arbitrary-python-statements-from-c">How can I execute arbitrary Python statements from C?</a></li>
<li><a class="reference internal" href="#how-can-i-evaluate-an-arbitrary-python-expression-from-c">How can I evaluate an arbitrary Python expression from C?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-c-values-from-a-python-object">How do I extract C values from a Python object?</a></li>
<li><a class="reference internal" href="#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
<li><a class="reference internal" href="#how-do-i-call-an-object-s-method-from-c">How do I call an object’s method from C?</a></li>
<li><a class="reference internal" href="#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
<li><a class="reference internal" href="#how-do-i-access-a-module-written-in-python-from-c">How do I access a module written in Python from C?</a></li>
<li><a class="reference internal" href="#how-do-i-interface-to-c-objects-from-python">How do I interface to C++ objects from Python?</a></li>
<li><a class="reference internal" href="#i-added-a-module-using-the-setup-file-and-the-make-fails-why">I added a module using the Setup file and the make fails; why?</a></li>
<li><a class="reference internal" href="#how-do-i-debug-an-extension">How do I debug an extension?</a></li>
<li><a class="reference internal" href="#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
<li><a class="reference internal" href="#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean">What does “SystemError: _PyImport_FixupExtension: module yourmodule not loaded” mean?</a></li>
<li><a class="reference internal" href="#how-do-i-tell-incomplete-input-from-invalid-input">How do I tell “incomplete input” from “invalid input”?</a></li>
<li><a class="reference internal" href="#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
<li><a class="reference internal" href="#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
<li><a class="reference internal" href="#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2">When importing module X, why do I get “undefined symbol: PyUnicodeUCS2*”?</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="library.html"
                        title="previous chapter">Library and Extension FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="windows.html"
                        title="next chapter">Python on Windows FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/extending.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="Python on Windows FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="library.html" title="Library and Extension FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�K-�-�html/faq/general.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>General Python FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Programming FAQ" href="programming.html" />
    <link rel="prev" title="Python Frequently Asked Questions" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/general.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="programming.html" title="Programming FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python Frequently Asked Questions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="general-python-faq">
<h1><a class="toc-backref" href="#id2">General Python FAQ</a><a class="headerlink" href="#general-python-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#general-python-faq" id="id2">General Python FAQ</a><ul>
<li><a class="reference internal" href="#general-information" id="id3">General Information</a><ul>
<li><a class="reference internal" href="#what-is-python" id="id4">What is Python?</a></li>
<li><a class="reference internal" href="#what-is-the-python-software-foundation" id="id5">What is the Python Software Foundation?</a></li>
<li><a class="reference internal" href="#are-there-copyright-restrictions-on-the-use-of-python" id="id6">Are there copyright restrictions on the use of Python?</a></li>
<li><a class="reference internal" href="#why-was-python-created-in-the-first-place" id="id7">Why was Python created in the first place?</a></li>
<li><a class="reference internal" href="#what-is-python-good-for" id="id8">What is Python good for?</a></li>
<li><a class="reference internal" href="#how-does-the-python-version-numbering-scheme-work" id="id9">How does the Python version numbering scheme work?</a></li>
<li><a class="reference internal" href="#how-do-i-obtain-a-copy-of-the-python-source" id="id10">How do I obtain a copy of the Python source?</a></li>
<li><a class="reference internal" href="#how-do-i-get-documentation-on-python" id="id11">How do I get documentation on Python?</a></li>
<li><a class="reference internal" href="#i-ve-never-programmed-before-is-there-a-python-tutorial" id="id12">I’ve never programmed before. Is there a Python tutorial?</a></li>
<li><a class="reference internal" href="#is-there-a-newsgroup-or-mailing-list-devoted-to-python" id="id13">Is there a newsgroup or mailing list devoted to Python?</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-beta-test-version-of-python" id="id14">How do I get a beta test version of Python?</a></li>
<li><a class="reference internal" href="#how-do-i-submit-bug-reports-and-patches-for-python" id="id15">How do I submit bug reports and patches for Python?</a></li>
<li><a class="reference internal" href="#are-there-any-published-articles-about-python-that-i-can-reference" id="id16">Are there any published articles about Python that I can reference?</a></li>
<li><a class="reference internal" href="#are-there-any-books-on-python" id="id17">Are there any books on Python?</a></li>
<li><a class="reference internal" href="#where-in-the-world-is-www-python-org-located" id="id18">Where in the world is www.python.org located?</a></li>
<li><a class="reference internal" href="#why-is-it-called-python" id="id19">Why is it called Python?</a></li>
<li><a class="reference internal" href="#do-i-have-to-like-monty-python-s-flying-circus" id="id20">Do I have to like “Monty Python’s Flying Circus”?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#python-in-the-real-world" id="id21">Python in the real world</a><ul>
<li><a class="reference internal" href="#how-stable-is-python" id="id22">How stable is Python?</a></li>
<li><a class="reference internal" href="#how-many-people-are-using-python" id="id23">How many people are using Python?</a></li>
<li><a class="reference internal" href="#have-any-significant-projects-been-done-in-python" id="id24">Have any significant projects been done in Python?</a></li>
<li><a class="reference internal" href="#what-new-developments-are-expected-for-python-in-the-future" id="id25">What new developments are expected for Python in the future?</a></li>
<li><a class="reference internal" href="#is-it-reasonable-to-propose-incompatible-changes-to-python" id="id26">Is it reasonable to propose incompatible changes to Python?</a></li>
<li><a class="reference internal" href="#is-python-a-good-language-for-beginning-programmers" id="id27">Is Python a good language for beginning programmers?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#upgrading-python" id="id28">Upgrading Python</a><ul>
<li><a class="reference internal" href="#what-is-this-bsddb185-module-my-application-keeps-complaining-about" id="id29">What is this bsddb185 module my application keeps complaining about?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-information">
<h2><a class="toc-backref" href="#id3">General Information</a><a class="headerlink" href="#general-information" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-is-python">
<h3><a class="toc-backref" href="#id4">What is Python?</a><a class="headerlink" href="#what-is-python" title="Permalink to this headline">¶</a></h3>
<p>Python is an interpreted, interactive, object-oriented programming language.  It
incorporates modules, exceptions, dynamic typing, very high level dynamic data
types, and classes.  Python combines remarkable power with very clear syntax.
It has interfaces to many system calls and libraries, as well as to various
window systems, and is extensible in C or C++.  It is also usable as an
extension language for applications that need a programmable interface.
Finally, Python is portable: it runs on many Unix variants, on the Mac, and on
PCs under MS-DOS, Windows, Windows NT, and OS/2.</p>
<p>To find out more, start with <a class="reference internal" href="../tutorial/index.html#tutorial-index"><span class="std std-ref">The Python Tutorial</span></a>.  The <a class="reference external" href="https://wiki.python.org/moin/BeginnersGuide">Beginner’s Guide to
Python</a> links to other
introductory tutorials and resources for learning Python.</p>
</div>
<div class="section" id="what-is-the-python-software-foundation">
<h3><a class="toc-backref" href="#id5">What is the Python Software Foundation?</a><a class="headerlink" href="#what-is-the-python-software-foundation" title="Permalink to this headline">¶</a></h3>
<p>The Python Software Foundation is an independent non-profit organization that
holds the copyright on Python versions 2.1 and newer.  The PSF’s mission is to
advance open source technology related to the Python programming language and to
publicize the use of Python.  The PSF’s home page is at
<a class="reference external" href="https://www.python.org/psf/">https://www.python.org/psf/</a>.</p>
<p>Donations to the PSF are tax-exempt in the US.  If you use Python and find it
helpful, please contribute via <a class="reference external" href="https://www.python.org/psf/donations/">the PSF donation page</a>.</p>
</div>
<div class="section" id="are-there-copyright-restrictions-on-the-use-of-python">
<h3><a class="toc-backref" href="#id6">Are there copyright restrictions on the use of Python?</a><a class="headerlink" href="#are-there-copyright-restrictions-on-the-use-of-python" title="Permalink to this headline">¶</a></h3>
<p>You can do anything you want with the source, as long as you leave the
copyrights in and display those copyrights in any documentation about Python
that you produce.  If you honor the copyright rules, it’s OK to use Python for
commercial use, to sell copies of Python in source or binary form (modified or
unmodified), or to sell products that incorporate Python in some form.  We would
still like to know about all commercial use of Python, of course.</p>
<p>See <a class="reference external" href="https://www.python.org/psf/license/">the PSF license page</a> to find further
explanations and a link to the full text of the license.</p>
<p>The Python logo is trademarked, and in certain cases permission is required to
use it.  Consult <a class="reference external" href="https://www.python.org/psf/trademarks/">the Trademark Usage Policy</a> for more information.</p>
</div>
<div class="section" id="why-was-python-created-in-the-first-place">
<h3><a class="toc-backref" href="#id7">Why was Python created in the first place?</a><a class="headerlink" href="#why-was-python-created-in-the-first-place" title="Permalink to this headline">¶</a></h3>
<p>Here’s a <em>very</em> brief summary of what started it all, written by Guido van
Rossum:</p>
<blockquote>
<div><p>I had extensive experience with implementing an interpreted language in the
ABC group at CWI, and from working with this group I had learned a lot about
language design.  This is the origin of many Python features, including the
use of indentation for statement grouping and the inclusion of
very-high-level data types (although the details are all different in
Python).</p>
<p>I had a number of gripes about the ABC language, but also liked many of its
features.  It was impossible to extend the ABC language (or its
implementation) to remedy my complaints – in fact its lack of extensibility
was one of its biggest problems.  I had some experience with using Modula-2+
and talked with the designers of Modula-3 and read the Modula-3 report.
Modula-3 is the origin of the syntax and semantics used for exceptions, and
some other Python features.</p>
<p>I was working in the Amoeba distributed operating system group at CWI.  We
needed a better way to do system administration than by writing either C
programs or Bourne shell scripts, since Amoeba had its own system call
interface which wasn’t easily accessible from the Bourne shell.  My
experience with error handling in Amoeba made me acutely aware of the
importance of exceptions as a programming language feature.</p>
<p>It occurred to me that a scripting language with a syntax like ABC but with
access to the Amoeba system calls would fill the need.  I realized that it
would be foolish to write an Amoeba-specific language, so I decided that I
needed a language that was generally extensible.</p>
<p>During the 1989 Christmas holidays, I had a lot of time on my hand, so I
decided to give it a try.  During the next year, while still mostly working
on it in my own time, Python was used in the Amoeba project with increasing
success, and the feedback from colleagues made me add many early
improvements.</p>
<p>In February 1991, after just over a year of development, I decided to post to
USENET.  The rest is in the <code class="docutils literal notranslate"><span class="pre">Misc/HISTORY</span></code> file.</p>
</div></blockquote>
</div>
<div class="section" id="what-is-python-good-for">
<h3><a class="toc-backref" href="#id8">What is Python good for?</a><a class="headerlink" href="#what-is-python-good-for" title="Permalink to this headline">¶</a></h3>
<p>Python is a high-level general-purpose programming language that can be applied
to many different classes of problems.</p>
<p>The language comes with a large standard library that covers areas such as
string processing (regular expressions, Unicode, calculating differences between
files), Internet protocols (HTTP, FTP, SMTP, XML-RPC, POP, IMAP, CGI
programming), software engineering (unit testing, logging, profiling, parsing
Python code), and operating system interfaces (system calls, filesystems, TCP/IP
sockets).  Look at the table of contents for <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a> to get an idea
of what’s available.  A wide variety of third-party extensions are also
available.  Consult <a class="reference external" href="https://pypi.org">the Python Package Index</a> to
find packages of interest to you.</p>
</div>
<div class="section" id="how-does-the-python-version-numbering-scheme-work">
<h3><a class="toc-backref" href="#id9">How does the Python version numbering scheme work?</a><a class="headerlink" href="#how-does-the-python-version-numbering-scheme-work" title="Permalink to this headline">¶</a></h3>
<p>Python versions are numbered A.B.C or A.B.  A is the major version number – it
is only incremented for really major changes in the language.  B is the minor
version number, incremented for less earth-shattering changes.  C is the
micro-level – it is incremented for each bugfix release.  See <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0006"><strong>PEP 6</strong></a> for more
information about bugfix releases.</p>
<p>Not all releases are bugfix releases.  In the run-up to a new major release, a
series of development releases are made, denoted as alpha, beta, or release
candidate.  Alphas are early releases in which interfaces aren’t yet finalized;
it’s not unexpected to see an interface change between two alpha releases.
Betas are more stable, preserving existing interfaces but possibly adding new
modules, and release candidates are frozen, making no changes except as needed
to fix critical bugs.</p>
<p>Alpha, beta and release candidate versions have an additional suffix.  The
suffix for an alpha version is “aN” for some small number N, the suffix for a
beta version is “bN” for some small number N, and the suffix for a release
candidate version is “cN” for some small number N.  In other words, all versions
labeled 2.0aN precede the versions labeled 2.0bN, which precede versions labeled
2.0cN, and <em>those</em> precede 2.0.</p>
<p>You may also find version numbers with a “+” suffix, e.g. “2.2+”.  These are
unreleased versions, built directly from the CPython development repository.  In
practice, after a final minor release is made, the version is incremented to the
next minor version, which becomes the “a0” version, e.g. “2.4a0”.</p>
<p>See also the documentation for <a class="reference internal" href="../library/sys.html#sys.version" title="sys.version"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.version</span></code></a>, <a class="reference internal" href="../library/sys.html#sys.hexversion" title="sys.hexversion"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.hexversion</span></code></a>, and
<a class="reference internal" href="../library/sys.html#sys.version_info" title="sys.version_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.version_info</span></code></a>.</p>
</div>
<div class="section" id="how-do-i-obtain-a-copy-of-the-python-source">
<h3><a class="toc-backref" href="#id10">How do I obtain a copy of the Python source?</a><a class="headerlink" href="#how-do-i-obtain-a-copy-of-the-python-source" title="Permalink to this headline">¶</a></h3>
<p>The latest Python source distribution is always available from python.org, at
<a class="reference external" href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>.  The latest development sources can be obtained
at <a class="reference external" href="https://github.com/python/cpython/">https://github.com/python/cpython/</a>.</p>
<p>The source distribution is a gzipped tar file containing the complete C source,
Sphinx-formatted documentation, Python library modules, example programs, and
several useful pieces of freely distributable software.  The source will compile
and run out of the box on most UNIX platforms.</p>
<p>Consult the <a class="reference external" href="https://docs.python.org/devguide/setup.html">Getting Started section of the Python Developer’s Guide</a> for more
information on getting the source code and compiling it.</p>
</div>
<div class="section" id="how-do-i-get-documentation-on-python">
<h3><a class="toc-backref" href="#id11">How do I get documentation on Python?</a><a class="headerlink" href="#how-do-i-get-documentation-on-python" title="Permalink to this headline">¶</a></h3>
<p>The standard documentation for the current stable version of Python is available
at <a class="reference external" href="https://docs.python.org/3/">https://docs.python.org/3/</a>.  PDF, plain text, and downloadable HTML versions are
also available at <a class="reference external" href="https://docs.python.org/3/download.html">https://docs.python.org/3/download.html</a>.</p>
<p>The documentation is written in reStructuredText and processed by <a class="reference external" href="http://sphinx-doc.org/">the Sphinx
documentation tool</a>.  The reStructuredText source for
the documentation is part of the Python source distribution.</p>
</div>
<div class="section" id="i-ve-never-programmed-before-is-there-a-python-tutorial">
<h3><a class="toc-backref" href="#id12">I’ve never programmed before. Is there a Python tutorial?</a><a class="headerlink" href="#i-ve-never-programmed-before-is-there-a-python-tutorial" title="Permalink to this headline">¶</a></h3>
<p>There are numerous tutorials and books available.  The standard documentation
includes <a class="reference internal" href="../tutorial/index.html#tutorial-index"><span class="std std-ref">The Python Tutorial</span></a>.</p>
<p>Consult <a class="reference external" href="https://wiki.python.org/moin/BeginnersGuide">the Beginner’s Guide</a> to
find information for beginning Python programmers, including lists of tutorials.</p>
</div>
<div class="section" id="is-there-a-newsgroup-or-mailing-list-devoted-to-python">
<h3><a class="toc-backref" href="#id13">Is there a newsgroup or mailing list devoted to Python?</a><a class="headerlink" href="#is-there-a-newsgroup-or-mailing-list-devoted-to-python" title="Permalink to this headline">¶</a></h3>
<p>There is a newsgroup, <em class="newsgroup">comp.lang.python</em>, and a mailing list,
<a class="reference external" href="https://mail.python.org/mailman/listinfo/python-list">python-list</a>.  The
newsgroup and mailing list are gatewayed into each other – if you can read news
it’s unnecessary to subscribe to the mailing list.
<em class="newsgroup">comp.lang.python</em> is high-traffic, receiving hundreds of postings
every day, and Usenet readers are often more able to cope with this volume.</p>
<p>Announcements of new software releases and events can be found in
comp.lang.python.announce, a low-traffic moderated list that receives about five
postings per day.  It’s available as <a class="reference external" href="https://mail.python.org/mailman/listinfo/python-announce-list">the python-announce mailing list</a>.</p>
<p>More info about other mailing lists and newsgroups
can be found at <a class="reference external" href="https://www.python.org/community/lists/">https://www.python.org/community/lists/</a>.</p>
</div>
<div class="section" id="how-do-i-get-a-beta-test-version-of-python">
<h3><a class="toc-backref" href="#id14">How do I get a beta test version of Python?</a><a class="headerlink" href="#how-do-i-get-a-beta-test-version-of-python" title="Permalink to this headline">¶</a></h3>
<p>Alpha and beta releases are available from <a class="reference external" href="https://www.python.org/downloads/">https://www.python.org/downloads/</a>.  All
releases are announced on the comp.lang.python and comp.lang.python.announce
newsgroups and on the Python home page at <a class="reference external" href="https://www.python.org/">https://www.python.org/</a>; an RSS feed of
news is available.</p>
<p>You can also access the development version of Python through Git.  See
<a class="reference external" href="https://docs.python.org/devguide/">The Python Developer’s Guide</a> for details.</p>
</div>
<div class="section" id="how-do-i-submit-bug-reports-and-patches-for-python">
<h3><a class="toc-backref" href="#id15">How do I submit bug reports and patches for Python?</a><a class="headerlink" href="#how-do-i-submit-bug-reports-and-patches-for-python" title="Permalink to this headline">¶</a></h3>
<p>To report a bug or submit a patch, please use the Roundup installation at
<a class="reference external" href="https://bugs.python.org/">https://bugs.python.org/</a>.</p>
<p>You must have a Roundup account to report bugs; this makes it possible for us to
contact you if we have follow-up questions.  It will also enable Roundup to send
you updates as we act on your bug. If you had previously used SourceForge to
report bugs to Python, you can obtain your Roundup password through Roundup’s
<a class="reference external" href="https://bugs.python.org/user?&#64;template=forgotten">password reset procedure</a>.</p>
<p>For more information on how Python is developed, consult <a class="reference external" href="https://docs.python.org/devguide/">the Python Developer’s
Guide</a>.</p>
</div>
<div class="section" id="are-there-any-published-articles-about-python-that-i-can-reference">
<h3><a class="toc-backref" href="#id16">Are there any published articles about Python that I can reference?</a><a class="headerlink" href="#are-there-any-published-articles-about-python-that-i-can-reference" title="Permalink to this headline">¶</a></h3>
<p>It’s probably best to cite your favorite book about Python.</p>
<p>The very first article about Python was written in 1991 and is now quite
outdated.</p>
<blockquote>
<div>Guido van Rossum and Jelke de Boer, “Interactively Testing Remote Servers
Using the Python Programming Language”, CWI Quarterly, Volume 4, Issue 4
(December 1991), Amsterdam, pp 283–303.</div></blockquote>
</div>
<div class="section" id="are-there-any-books-on-python">
<h3><a class="toc-backref" href="#id17">Are there any books on Python?</a><a class="headerlink" href="#are-there-any-books-on-python" title="Permalink to this headline">¶</a></h3>
<p>Yes, there are many, and more are being published.  See the python.org wiki at
<a class="reference external" href="https://wiki.python.org/moin/PythonBooks">https://wiki.python.org/moin/PythonBooks</a> for a list.</p>
<p>You can also search online bookstores for “Python” and filter out the Monty
Python references; or perhaps search for “Python” and “language”.</p>
</div>
<div class="section" id="where-in-the-world-is-www-python-org-located">
<h3><a class="toc-backref" href="#id18">Where in the world is www.python.org located?</a><a class="headerlink" href="#where-in-the-world-is-www-python-org-located" title="Permalink to this headline">¶</a></h3>
<p>The Python project’s infrastructure is located all over the world.
<a class="reference external" href="https://www.python.org">www.python.org</a> is graciously hosted by <a class="reference external" href="https://www.rackspace.com">Rackspace</a>, with CDN caching provided by <a class="reference external" href="https://www.fastly.com">Fastly</a>.  <a class="reference external" href="http://www.upfrontsystems.co.za/">Upfront Systems</a> hosts <a class="reference external" href="https://bugs.python.org">bugs.python.org</a>.  Many other Python services like <a class="reference external" href="https://wiki.python.org">the Wiki</a> are hosted by <a class="reference external" href="https://osuosl.org">Oregon State
University Open Source Lab</a>.</p>
</div>
<div class="section" id="why-is-it-called-python">
<h3><a class="toc-backref" href="#id19">Why is it called Python?</a><a class="headerlink" href="#why-is-it-called-python" title="Permalink to this headline">¶</a></h3>
<p>When he began implementing Python, Guido van Rossum was also reading the
published scripts from <a class="reference external" href="https://en.wikipedia.org/wiki/Monty_Python">“Monty Python’s Flying Circus”</a>, a BBC comedy series from the 1970s.  Van Rossum
thought he needed a name that was short, unique, and slightly mysterious, so he
decided to call the language Python.</p>
</div>
<div class="section" id="do-i-have-to-like-monty-python-s-flying-circus">
<h3><a class="toc-backref" href="#id20">Do I have to like “Monty Python’s Flying Circus”?</a><a class="headerlink" href="#do-i-have-to-like-monty-python-s-flying-circus" title="Permalink to this headline">¶</a></h3>
<p>No, but it helps.  :)</p>
</div>
</div>
<div class="section" id="python-in-the-real-world">
<h2><a class="toc-backref" href="#id21">Python in the real world</a><a class="headerlink" href="#python-in-the-real-world" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-stable-is-python">
<h3><a class="toc-backref" href="#id22">How stable is Python?</a><a class="headerlink" href="#how-stable-is-python" title="Permalink to this headline">¶</a></h3>
<p>Very stable.  New, stable releases have been coming out roughly every 6 to 18
months since 1991, and this seems likely to continue.  Currently there are
usually around 18 months between major releases.</p>
<p>The developers issue “bugfix” releases of older versions, so the stability of
existing releases gradually improves.  Bugfix releases, indicated by a third
component of the version number (e.g. 3.5.3, 3.6.2), are managed for stability;
only fixes for known problems are included in a bugfix release, and it’s
guaranteed that interfaces will remain the same throughout a series of bugfix
releases.</p>
<p>The latest stable releases can always be found on the <a class="reference external" href="https://www.python.org/downloads/">Python download page</a>.  There are two production-ready version
of Python: 2.x and 3.x, but the recommended one at this times is Python 3.x.
Although Python 2.x is still widely used, <a class="reference external" href="https://www.python.org/dev/peps/pep-0373/">it will not be
maintained after January 1, 2020</a>.
Python 2.x was known for having more third-party libraries available, however,
by the time of this writing, most of the widely used libraries support Python 3.x,
and some are even dropping the Python 2.x support.</p>
</div>
<div class="section" id="how-many-people-are-using-python">
<h3><a class="toc-backref" href="#id23">How many people are using Python?</a><a class="headerlink" href="#how-many-people-are-using-python" title="Permalink to this headline">¶</a></h3>
<p>There are probably tens of thousands of users, though it’s difficult to obtain
an exact count.</p>
<p>Python is available for free download, so there are no sales figures, and it’s
available from many different sites and packaged with many Linux distributions,
so download statistics don’t tell the whole story either.</p>
<p>The comp.lang.python newsgroup is very active, but not all Python users post to
the group or even read it.</p>
</div>
<div class="section" id="have-any-significant-projects-been-done-in-python">
<h3><a class="toc-backref" href="#id24">Have any significant projects been done in Python?</a><a class="headerlink" href="#have-any-significant-projects-been-done-in-python" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference external" href="https://www.python.org/about/success">https://www.python.org/about/success</a> for a list of projects that use Python.
Consulting the proceedings for <a class="reference external" href="https://www.python.org/community/workshops/">past Python conferences</a> will reveal contributions from many
different companies and organizations.</p>
<p>High-profile Python projects include <a class="reference external" href="http://www.list.org">the Mailman mailing list manager</a> and <a class="reference external" href="http://www.zope.org">the Zope application server</a>.  Several Linux distributions, most notably <a class="reference external" href="https://www.redhat.com">Red Hat</a>, have written part or all of their installer and
system administration software in Python.  Companies that use Python internally
include Google, Yahoo, and Lucasfilm Ltd.</p>
</div>
<div class="section" id="what-new-developments-are-expected-for-python-in-the-future">
<h3><a class="toc-backref" href="#id25">What new developments are expected for Python in the future?</a><a class="headerlink" href="#what-new-developments-are-expected-for-python-in-the-future" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference external" href="https://www.python.org/dev/peps/">https://www.python.org/dev/peps/</a> for the Python Enhancement Proposals
(PEPs). PEPs are design documents describing a suggested new feature for Python,
providing a concise technical specification and a rationale.  Look for a PEP
titled “Python X.Y Release Schedule”, where X.Y is a version that hasn’t been
publicly released yet.</p>
<p>New development is discussed on <a class="reference external" href="https://mail.python.org/mailman/listinfo/python-dev/">the python-dev mailing list</a>.</p>
</div>
<div class="section" id="is-it-reasonable-to-propose-incompatible-changes-to-python">
<h3><a class="toc-backref" href="#id26">Is it reasonable to propose incompatible changes to Python?</a><a class="headerlink" href="#is-it-reasonable-to-propose-incompatible-changes-to-python" title="Permalink to this headline">¶</a></h3>
<p>In general, no.  There are already millions of lines of Python code around the
world, so any change in the language that invalidates more than a very small
fraction of existing programs has to be frowned upon.  Even if you can provide a
conversion program, there’s still the problem of updating all documentation;
many books have been written about Python, and we don’t want to invalidate them
all at a single stroke.</p>
<p>Providing a gradual upgrade path is necessary if a feature has to be changed.
<span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0005"><strong>PEP 5</strong></a> describes the procedure followed for introducing backward-incompatible
changes while minimizing disruption for users.</p>
</div>
<div class="section" id="is-python-a-good-language-for-beginning-programmers">
<h3><a class="toc-backref" href="#id27">Is Python a good language for beginning programmers?</a><a class="headerlink" href="#is-python-a-good-language-for-beginning-programmers" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>It is still common to start students with a procedural and statically typed
language such as Pascal, C, or a subset of C++ or Java.  Students may be better
served by learning Python as their first language.  Python has a very simple and
consistent syntax and a large standard library and, most importantly, using
Python in a beginning programming course lets students concentrate on important
programming skills such as problem decomposition and data type design.  With
Python, students can be quickly introduced to basic concepts such as loops and
procedures.  They can probably even work with user-defined objects in their very
first course.</p>
<p>For a student who has never programmed before, using a statically typed language
seems unnatural.  It presents additional complexity that the student must master
and slows the pace of the course.  The students are trying to learn to think
like a computer, decompose problems, design consistent interfaces, and
encapsulate data.  While learning to use a statically typed language is
important in the long term, it is not necessarily the best topic to address in
the students’ first programming course.</p>
<p>Many other aspects of Python make it a good first language.  Like Java, Python
has a large standard library so that students can be assigned programming
projects very early in the course that <em>do</em> something.  Assignments aren’t
restricted to the standard four-function calculator and check balancing
programs.  By using the standard library, students can gain the satisfaction of
working on realistic applications as they learn the fundamentals of programming.
Using the standard library also teaches students about code reuse.  Third-party
modules such as PyGame are also helpful in extending the students’ reach.</p>
<p>Python’s interactive interpreter enables students to test language features
while they’re programming.  They can keep a window with the interpreter running
while they enter their program’s source in another window.  If they can’t
remember the methods for a list, they can do something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">L</span><span class="p">)</span> 
<span class="go">[&#39;__add__&#39;, &#39;__class__&#39;, &#39;__contains__&#39;, &#39;__delattr__&#39;, &#39;__delitem__&#39;,</span>
<span class="go">&#39;__delslice__&#39;, &#39;__doc__&#39;, &#39;__eq__&#39;, &#39;__format__&#39;, &#39;__ge__&#39;,</span>
<span class="go">&#39;__getattribute__&#39;, &#39;__getitem__&#39;, &#39;__getslice__&#39;, &#39;__gt__&#39;,</span>
<span class="go">&#39;__hash__&#39;, &#39;__iadd__&#39;, &#39;__imul__&#39;, &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__le__&#39;,</span>
<span class="go">&#39;__len__&#39;, &#39;__lt__&#39;, &#39;__mul__&#39;, &#39;__ne__&#39;, &#39;__new__&#39;, &#39;__reduce__&#39;,</span>
<span class="go">&#39;__reduce_ex__&#39;, &#39;__repr__&#39;, &#39;__reversed__&#39;, &#39;__rmul__&#39;,</span>
<span class="go">&#39;__setattr__&#39;, &#39;__setitem__&#39;, &#39;__setslice__&#39;, &#39;__sizeof__&#39;, &#39;__str__&#39;,</span>
<span class="go">&#39;__subclasshook__&#39;, &#39;append&#39;, &#39;count&#39;, &#39;extend&#39;, &#39;index&#39;, &#39;insert&#39;,</span>
<span class="go">&#39;pop&#39;, &#39;remove&#39;, &#39;reverse&#39;, &#39;sort&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">)</span>
<span class="go">Help on built-in function append:</span>

<span class="go">append(...)</span>
<span class="go">    L.append(object) -- append object to end</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[1]</span>
</pre></div>
</div>
<p>With the interpreter, documentation is never far from the student as he’s
programming.</p>
<p>There are also good IDEs for Python.  IDLE is a cross-platform IDE for Python
that is written in Python using Tkinter.  PythonWin is a Windows-specific IDE.
Emacs users will be happy to know that there is a very good Python mode for
Emacs.  All of these programming environments provide syntax highlighting,
auto-indenting, and access to the interactive interpreter while coding.  Consult
<a class="reference external" href="https://wiki.python.org/moin/PythonEditors">the Python wiki</a> for a full list
of Python editing environments.</p>
<p>If you want to discuss Python’s use in education, you may be interested in
joining <a class="reference external" href="https://www.python.org/community/sigs/current/edu-sig">the edu-sig mailing list</a>.</p>
</div>
</div>
<div class="section" id="upgrading-python">
<h2><a class="toc-backref" href="#id28">Upgrading Python</a><a class="headerlink" href="#upgrading-python" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-is-this-bsddb185-module-my-application-keeps-complaining-about">
<h3><a class="toc-backref" href="#id29">What is this bsddb185 module my application keeps complaining about?</a><a class="headerlink" href="#what-is-this-bsddb185-module-my-application-keeps-complaining-about" title="Permalink to this headline">¶</a></h3>
<p>Starting with Python2.3, the distribution includes the <cite>PyBSDDB package
&lt;http://pybsddb.sf.net/&gt;</cite> as a replacement for the old bsddb module.  It
includes functions which provide backward compatibility at the API level, but
requires a newer version of the underlying <a class="reference external" href="http://www.sleepycat.com">Berkeley DB</a> library.  Files created with the older bsddb module
can’t be opened directly using the new module.</p>
<p>Using your old version of Python and a pair of scripts which are part of Python
2.3 (db2pickle.py and pickle2db.py, in the Tools/scripts directory) you can
convert your old database files to the new format.  Using your old Python
version, run the db2pickle.py script to convert it to a pickle, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python2</span><span class="o">.</span><span class="mi">2</span> <span class="o">&lt;</span><span class="n">pathto</span><span class="o">&gt;/</span><span class="n">db2pickley</span><span class="o">.</span><span class="n">py</span> <span class="n">database</span><span class="o">.</span><span class="n">db</span> <span class="n">database</span><span class="o">.</span><span class="n">pck</span>
</pre></div>
</div>
<p>Rename your database file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mv</span> <span class="n">database</span><span class="o">.</span><span class="n">db</span> <span class="n">olddatabase</span><span class="o">.</span><span class="n">db</span>
</pre></div>
</div>
<p>Now convert the pickle file to a new format database:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">&lt;</span><span class="n">pathto</span><span class="o">&gt;/</span><span class="n">pickle2db</span><span class="o">.</span><span class="n">py</span> <span class="n">database</span><span class="o">.</span><span class="n">db</span> <span class="n">database</span><span class="o">.</span><span class="n">pck</span>
</pre></div>
</div>
<p>The precise commands you use will vary depending on the particulars of your
installation.  For full details about operation of these two scripts check the
doc string at the start of each one.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">General Python FAQ</a><ul>
<li><a class="reference internal" href="#general-information">General Information</a></li>
<li><a class="reference internal" href="#python-in-the-real-world">Python in the real world</a></li>
<li><a class="reference internal" href="#upgrading-python">Upgrading Python</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Python Frequently Asked Questions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="programming.html"
                        title="next chapter">Programming FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/general.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="programming.html" title="Programming FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python Frequently Asked Questions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\#tmBBhtml/faq/gui.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Graphic User Interface FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="“Why is Python Installed on my Computer?” FAQ" href="installed.html" />
    <link rel="prev" title="Python on Windows FAQ" href="windows.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/gui.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="installed.html" title="“Why is Python Installed on my Computer?” FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="Python on Windows FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="graphic-user-interface-faq">
<h1><a class="toc-backref" href="#id1">Graphic User Interface FAQ</a><a class="headerlink" href="#graphic-user-interface-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#graphic-user-interface-faq" id="id1">Graphic User Interface FAQ</a><ul>
<li><a class="reference internal" href="#what-platform-independent-gui-toolkits-exist-for-python" id="id2">What platform-independent GUI toolkits exist for Python?</a><ul>
<li><a class="reference internal" href="#tkinter" id="id3">Tkinter</a></li>
<li><a class="reference internal" href="#wxwidgets" id="id4">wxWidgets</a></li>
<li><a class="reference internal" href="#qt" id="id5">Qt</a></li>
<li><a class="reference internal" href="#gtk" id="id6">Gtk+</a></li>
<li><a class="reference internal" href="#fltk" id="id7">FLTK</a></li>
<li><a class="reference internal" href="#opengl" id="id8">OpenGL</a></li>
</ul>
</li>
<li><a class="reference internal" href="#what-platform-specific-gui-toolkits-exist-for-python" id="id9">What platform-specific GUI toolkits exist for Python?</a></li>
<li><a class="reference internal" href="#tkinter-questions" id="id10">Tkinter questions</a><ul>
<li><a class="reference internal" href="#how-do-i-freeze-tkinter-applications" id="id11">How do I freeze Tkinter applications?</a></li>
<li><a class="reference internal" href="#can-i-have-tk-events-handled-while-waiting-for-i-o" id="id12">Can I have Tk events handled while waiting for I/O?</a></li>
<li><a class="reference internal" href="#i-can-t-get-key-bindings-to-work-in-tkinter-why" id="id13">I can’t get key bindings to work in Tkinter: why?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="what-platform-independent-gui-toolkits-exist-for-python">
<h2><a class="toc-backref" href="#id2">What platform-independent GUI toolkits exist for Python?</a><a class="headerlink" href="#what-platform-independent-gui-toolkits-exist-for-python" title="Permalink to this headline">¶</a></h2>
<p>Depending on what platform(s) you are aiming at, there are several.</p>
<div class="section" id="tkinter">
<h3><a class="toc-backref" href="#id3">Tkinter</a><a class="headerlink" href="#tkinter" title="Permalink to this headline">¶</a></h3>
<p>Standard builds of Python include an object-oriented interface to the Tcl/Tk
widget set, called Tkinter.  This is probably the easiest to install and use.
For more info about Tk, including pointers to the source, see the Tcl/Tk home
page at <a class="reference external" href="https://www.tcl.tk">https://www.tcl.tk</a>.  Tcl/Tk is fully portable to the Mac OS X, Windows,
and Unix platforms.</p>
</div>
<div class="section" id="wxwidgets">
<h3><a class="toc-backref" href="#id4">wxWidgets</a><a class="headerlink" href="#wxwidgets" title="Permalink to this headline">¶</a></h3>
<p>wxWidgets (<a class="reference external" href="https://www.wxwidgets.org">https://www.wxwidgets.org</a>) is a free, portable GUI class
library written in C++ that provides a native look and feel on a
number of platforms, with Windows, Mac OS X, GTK, X11, all listed as
current stable targets.  Language bindings are available for a number
of languages including Python, Perl, Ruby, etc.</p>
<p>wxPython (<a class="reference external" href="http://www.wxpython.org">http://www.wxpython.org</a>) is the Python binding for
wxwidgets.  While it often lags slightly behind the official wxWidgets
releases, it also offers a number of features via pure Python
extensions that are not available in other language bindings.  There
is an active wxPython user and developer community.</p>
<p>Both wxWidgets and wxPython are free, open source, software with
permissive licences that allow their use in commercial products as
well as in freeware or shareware.</p>
</div>
<div class="section" id="qt">
<h3><a class="toc-backref" href="#id5">Qt</a><a class="headerlink" href="#qt" title="Permalink to this headline">¶</a></h3>
<p>There are bindings available for the Qt toolkit (using either <a class="reference external" href="https://riverbankcomputing.com/software/pyqt/intro">PyQt</a> or <a class="reference external" href="https://wiki.qt.io/PySide">PySide</a>) and for KDE (<a class="reference external" href="https://techbase.kde.org/Languages/Python/Using_PyKDE_4">PyKDE4</a>).
PyQt is currently more mature than PySide, but you must buy a PyQt license from
<a class="reference external" href="https://www.riverbankcomputing.com/commercial/license-faq">Riverbank Computing</a>
if you want to write proprietary applications.  PySide is free for all applications.</p>
<p>Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses
are available from <a class="reference external" href="https://www.qt.io/licensing/">The Qt Company</a>.</p>
</div>
<div class="section" id="gtk">
<h3><a class="toc-backref" href="#id6">Gtk+</a><a class="headerlink" href="#gtk" title="Permalink to this headline">¶</a></h3>
<p>PyGtk bindings for the <a class="reference external" href="http://www.gtk.org">Gtk+ toolkit</a> have been
implemented by James Henstridge; see &lt;<a class="reference external" href="http://www.pygtk.org">http://www.pygtk.org</a>&gt;.</p>
</div>
<div class="section" id="fltk">
<h3><a class="toc-backref" href="#id7">FLTK</a><a class="headerlink" href="#fltk" title="Permalink to this headline">¶</a></h3>
<p>Python bindings for <a class="reference external" href="http://www.fltk.org">the FLTK toolkit</a>, a simple yet
powerful and mature cross-platform windowing system, are available from <a class="reference external" href="http://pyfltk.sourceforge.net">the
PyFLTK project</a>.</p>
</div>
<div class="section" id="opengl">
<h3><a class="toc-backref" href="#id8">OpenGL</a><a class="headerlink" href="#opengl" title="Permalink to this headline">¶</a></h3>
<p>For OpenGL bindings, see <a class="reference external" href="http://pyopengl.sourceforge.net">PyOpenGL</a>.</p>
</div>
</div>
<div class="section" id="what-platform-specific-gui-toolkits-exist-for-python">
<h2><a class="toc-backref" href="#id9">What platform-specific GUI toolkits exist for Python?</a><a class="headerlink" href="#what-platform-specific-gui-toolkits-exist-for-python" title="Permalink to this headline">¶</a></h2>
<p>By installing the <a class="reference external" href="https://pythonhosted.org/pyobjc/">PyObjc Objective-C bridge</a>, Python programs can use Mac OS X’s
Cocoa libraries.</p>
<p><a class="reference internal" href="windows.html#windows-faq"><span class="std std-ref">Pythonwin</span></a> by Mark Hammond includes an interface to the
Microsoft Foundation Classes and a Python programming environment
that’s written mostly in Python using the MFC classes.</p>
</div>
<div class="section" id="tkinter-questions">
<h2><a class="toc-backref" href="#id10">Tkinter questions</a><a class="headerlink" href="#tkinter-questions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-freeze-tkinter-applications">
<h3><a class="toc-backref" href="#id11">How do I freeze Tkinter applications?</a><a class="headerlink" href="#how-do-i-freeze-tkinter-applications" title="Permalink to this headline">¶</a></h3>
<p>Freeze is a tool to create stand-alone applications.  When freezing Tkinter
applications, the applications will not be truly stand-alone, as the application
will still need the Tcl and Tk libraries.</p>
<p>One solution is to ship the application with the Tcl and Tk libraries, and point
to them at run-time using the <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TCL_LIBRARY</span></code> and <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TK_LIBRARY</span></code>
environment variables.</p>
<p>To get truly stand-alone applications, the Tcl scripts that form the library
have to be integrated into the application as well. One tool supporting that is
SAM (stand-alone modules), which is part of the Tix distribution
(<a class="reference external" href="http://tix.sourceforge.net/">http://tix.sourceforge.net/</a>).</p>
<p>Build Tix with SAM enabled, perform the appropriate call to
<code class="xref c c-func docutils literal notranslate"><span class="pre">Tclsam_init()</span></code>, etc. inside Python’s
<code class="file docutils literal notranslate"><span class="pre">Modules/tkappinit.c</span></code>, and link with libtclsam and libtksam (you
might include the Tix libraries as well).</p>
</div>
<div class="section" id="can-i-have-tk-events-handled-while-waiting-for-i-o">
<h3><a class="toc-backref" href="#id12">Can I have Tk events handled while waiting for I/O?</a><a class="headerlink" href="#can-i-have-tk-events-handled-while-waiting-for-i-o" title="Permalink to this headline">¶</a></h3>
<p>On platforms other than Windows, yes, and you don’t even
need threads!  But you’ll have to restructure your I/O
code a bit.  Tk has the equivalent of Xt’s <code class="xref c c-func docutils literal notranslate"><span class="pre">XtAddInput()</span></code> call, which allows you
to register a callback function which will be called from the Tk mainloop when
I/O is possible on a file descriptor.  See <a class="reference internal" href="../library/tkinter.html#tkinter-file-handlers"><span class="std std-ref">File Handlers</span></a>.</p>
</div>
<div class="section" id="i-can-t-get-key-bindings-to-work-in-tkinter-why">
<h3><a class="toc-backref" href="#id13">I can’t get key bindings to work in Tkinter: why?</a><a class="headerlink" href="#i-can-t-get-key-bindings-to-work-in-tkinter-why" title="Permalink to this headline">¶</a></h3>
<p>An often-heard complaint is that event handlers bound to events with the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">bind()</span></code> method don’t get handled even when the appropriate key is pressed.</p>
<p>The most common cause is that the widget to which the binding applies doesn’t
have “keyboard focus”.  Check out the Tk documentation for the focus command.
Usually a widget is given the keyboard focus by clicking in it (but not for
labels; see the takefocus option).</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Graphic User Interface FAQ</a><ul>
<li><a class="reference internal" href="#what-platform-independent-gui-toolkits-exist-for-python">What platform-independent GUI toolkits exist for Python?</a></li>
<li><a class="reference internal" href="#what-platform-specific-gui-toolkits-exist-for-python">What platform-specific GUI toolkits exist for Python?</a></li>
<li><a class="reference internal" href="#tkinter-questions">Tkinter questions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="windows.html"
                        title="previous chapter">Python on Windows FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="installed.html"
                        title="next chapter">“Why is Python Installed on my Computer?” FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/gui.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="installed.html" title="“Why is Python Installed on my Computer?” FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="Python on Windows FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\EF�U��html/faq/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python Frequently Asked Questions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="General Python FAQ" href="general.html" />
    <link rel="prev" title="Argparse Tutorial" href="../howto/argparse.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../howto/argparse.html" title="Argparse Tutorial"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-frequently-asked-questions">
<span id="faq-index"></span><h1>Python Frequently Asked Questions<a class="headerlink" href="#python-frequently-asked-questions" title="Permalink to this headline">¶</a></h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="general.html">General Python FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="programming.html">Programming FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="design.html">Design and History FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="library.html">Library and Extension FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="extending.html">Extending/Embedding FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="windows.html">Python on Windows FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="gui.html">Graphic User Interface FAQ</a></li>
<li class="toctree-l1"><a class="reference internal" href="installed.html">“Why is Python Installed on my Computer?” FAQ</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../howto/argparse.html"
                        title="previous chapter">Argparse Tutorial</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="general.html"
                        title="next chapter">General Python FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="../howto/argparse.html" title="Argparse Tutorial"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\`�Rh�$�$html/faq/installed.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>“Why is Python Installed on my Computer?” FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Glossary" href="../glossary.html" />
    <link rel="prev" title="Graphic User Interface FAQ" href="gui.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/installed.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../glossary.html" title="Glossary"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gui.html" title="Graphic User Interface FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="why-is-python-installed-on-my-computer-faq">
<h1>“Why is Python Installed on my Computer?” FAQ<a class="headerlink" href="#why-is-python-installed-on-my-computer-faq" title="Permalink to this headline">¶</a></h1>
<div class="section" id="what-is-python">
<h2>What is Python?<a class="headerlink" href="#what-is-python" title="Permalink to this headline">¶</a></h2>
<p>Python is a programming language.  It’s used for many different applications.
It’s used in some high schools and colleges as an introductory programming
language because Python is easy to learn, but it’s also used by professional
software developers at places such as Google, NASA, and Lucasfilm Ltd.</p>
<p>If you wish to learn more about Python, start with the <a class="reference external" href="https://wiki.python.org/moin/BeginnersGuide">Beginner’s Guide to
Python</a>.</p>
</div>
<div class="section" id="why-is-python-installed-on-my-machine">
<h2>Why is Python installed on my machine?<a class="headerlink" href="#why-is-python-installed-on-my-machine" title="Permalink to this headline">¶</a></h2>
<p>If you find Python installed on your system but don’t remember installing it,
there are several possible ways it could have gotten there.</p>
<ul class="simple">
<li>Perhaps another user on the computer wanted to learn programming and installed
it; you’ll have to figure out who’s been using the machine and might have
installed it.</li>
<li>A third-party application installed on the machine might have been written in
Python and included a Python installation.  For a home computer, the most
common such application is <a class="reference external" href="http://pysolfc.sourceforge.net/">PySol</a>, a
solitaire game that includes over 1000 different games and variations.</li>
<li>Some Windows machines also have Python installed.  At this writing we’re aware
of computers from Hewlett-Packard and Compaq that include Python.  Apparently
some of HP/Compaq’s administrative tools are written in Python.</li>
<li>All Apple computers running Mac OS X have Python installed; it’s included in
the base installation.</li>
</ul>
</div>
<div class="section" id="can-i-delete-python">
<h2>Can I delete Python?<a class="headerlink" href="#can-i-delete-python" title="Permalink to this headline">¶</a></h2>
<p>That depends on where Python came from.</p>
<p>If someone installed it deliberately, you can remove it without hurting
anything.  On Windows, use the Add/Remove Programs icon in the Control Panel.</p>
<p>If Python was installed by a third-party application, you can also remove it,
but that application will no longer work.  You should use that application’s
uninstaller rather than removing Python directly.</p>
<p>If Python came with your operating system, removing it is not recommended.  If
you remove it, whatever tools were written in Python will no longer run, and
some of them might be important to you.  Reinstalling the whole system would
then be required to fix things again.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">“Why is Python Installed on my Computer?” FAQ</a><ul>
<li><a class="reference internal" href="#what-is-python">What is Python?</a></li>
<li><a class="reference internal" href="#why-is-python-installed-on-my-machine">Why is Python installed on my machine?</a></li>
<li><a class="reference internal" href="#can-i-delete-python">Can I delete Python?</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gui.html"
                        title="previous chapter">Graphic User Interface FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../glossary.html"
                        title="next chapter">Glossary</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/installed.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../glossary.html" title="Glossary"
             >next</a> |</li>
        <li class="right" >
          <a href="gui.html" title="Graphic User Interface FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\}��}�}html/faq/library.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Library and Extension FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Extending/Embedding FAQ" href="extending.html" />
    <link rel="prev" title="Design and History FAQ" href="design.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/library.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="Extending/Embedding FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="library-and-extension-faq">
<h1><a class="toc-backref" href="#id1">Library and Extension FAQ</a><a class="headerlink" href="#library-and-extension-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#library-and-extension-faq" id="id1">Library and Extension FAQ</a><ul>
<li><a class="reference internal" href="#general-library-questions" id="id2">General Library Questions</a><ul>
<li><a class="reference internal" href="#how-do-i-find-a-module-or-application-to-perform-task-x" id="id3">How do I find a module or application to perform task X?</a></li>
<li><a class="reference internal" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" id="id4">Where is the math.py (socket.py, regex.py, etc.) source file?</a></li>
<li><a class="reference internal" href="#how-do-i-make-a-python-script-executable-on-unix" id="id5">How do I make a Python script executable on Unix?</a></li>
<li><a class="reference internal" href="#is-there-a-curses-termcap-package-for-python" id="id6">Is there a curses/termcap package for Python?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-c-s-onexit-in-python" id="id7">Is there an equivalent to C’s onexit() in Python?</a></li>
<li><a class="reference internal" href="#why-don-t-my-signal-handlers-work" id="id8">Why don’t my signal handlers work?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-tasks" id="id9">Common tasks</a><ul>
<li><a class="reference internal" href="#how-do-i-test-a-python-program-or-component" id="id10">How do I test a Python program or component?</a></li>
<li><a class="reference internal" href="#how-do-i-create-documentation-from-doc-strings" id="id11">How do I create documentation from doc strings?</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-single-keypress-at-a-time" id="id12">How do I get a single keypress at a time?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#threads" id="id13">Threads</a><ul>
<li><a class="reference internal" href="#how-do-i-program-using-threads" id="id14">How do I program using threads?</a></li>
<li><a class="reference internal" href="#none-of-my-threads-seem-to-run-why" id="id15">None of my threads seem to run: why?</a></li>
<li><a class="reference internal" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" id="id16">How do I parcel out work among a bunch of worker threads?</a></li>
<li><a class="reference internal" href="#what-kinds-of-global-value-mutation-are-thread-safe" id="id17">What kinds of global value mutation are thread-safe?</a></li>
<li><a class="reference internal" href="#can-t-we-get-rid-of-the-global-interpreter-lock" id="id18">Can’t we get rid of the Global Interpreter Lock?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#input-and-output" id="id19">Input and Output</a><ul>
<li><a class="reference internal" href="#how-do-i-delete-a-file-and-other-file-questions" id="id20">How do I delete a file? (And other file questions…)</a></li>
<li><a class="reference internal" href="#how-do-i-copy-a-file" id="id21">How do I copy a file?</a></li>
<li><a class="reference internal" href="#how-do-i-read-or-write-binary-data" id="id22">How do I read (or write) binary data?</a></li>
<li><a class="reference internal" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" id="id23">I can’t seem to use os.read() on a pipe created with os.popen(); why?</a></li>
<li><a class="reference internal" href="#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" id="id24">How do I run a subprocess with pipes connected to both input and output?</a></li>
<li><a class="reference internal" href="#how-do-i-access-the-serial-rs232-port" id="id25">How do I access the serial (RS232) port?</a></li>
<li><a class="reference internal" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" id="id26">Why doesn’t closing sys.stdout (stdin, stderr) really close it?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#network-internet-programming" id="id27">Network/Internet Programming</a><ul>
<li><a class="reference internal" href="#what-www-tools-are-there-for-python" id="id28">What WWW tools are there for Python?</a></li>
<li><a class="reference internal" href="#how-can-i-mimic-cgi-form-submission-method-post" id="id29">How can I mimic CGI form submission (METHOD=POST)?</a></li>
<li><a class="reference internal" href="#what-module-should-i-use-to-help-with-generating-html" id="id30">What module should I use to help with generating HTML?</a></li>
<li><a class="reference internal" href="#how-do-i-send-mail-from-a-python-script" id="id31">How do I send mail from a Python script?</a></li>
<li><a class="reference internal" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" id="id32">How do I avoid blocking in the connect() method of a socket?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#databases" id="id33">Databases</a><ul>
<li><a class="reference internal" href="#are-there-any-interfaces-to-database-packages-in-python" id="id34">Are there any interfaces to database packages in Python?</a></li>
<li><a class="reference internal" href="#how-do-you-implement-persistent-objects-in-python" id="id35">How do you implement persistent objects in Python?</a></li>
<li><a class="reference internal" href="#why-is-cpickle-so-slow" id="id36">Why is cPickle so slow?</a></li>
<li><a class="reference internal" href="#if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" id="id37">If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a></li>
<li><a class="reference internal" href="#i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" id="id38">I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, ‘Invalid argument’). Help! How can I restore my data?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mathematics-and-numerics" id="id39">Mathematics and Numerics</a><ul>
<li><a class="reference internal" href="#how-do-i-generate-random-numbers-in-python" id="id40">How do I generate random numbers in Python?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-library-questions">
<h2><a class="toc-backref" href="#id2">General Library Questions</a><a class="headerlink" href="#general-library-questions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-find-a-module-or-application-to-perform-task-x">
<h3><a class="toc-backref" href="#id3">How do I find a module or application to perform task X?</a><a class="headerlink" href="#how-do-i-find-a-module-or-application-to-perform-task-x" title="Permalink to this headline">¶</a></h3>
<p>Check <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">the Library Reference</span></a> to see if there’s a relevant
standard library module.  (Eventually you’ll learn what’s in the standard
library and will be able to skip this step.)</p>
<p>For third-party packages, search the <a class="reference external" href="https://pypi.org">Python Package Index</a> or try <a class="reference external" href="https://www.google.com">Google</a> or
another Web search engine.  Searching for “Python” plus a keyword or two for
your topic of interest will usually find something helpful.</p>
</div>
<div class="section" id="where-is-the-math-py-socket-py-regex-py-etc-source-file">
<h3><a class="toc-backref" href="#id4">Where is the math.py (socket.py, regex.py, etc.) source file?</a><a class="headerlink" href="#where-is-the-math-py-socket-py-regex-py-etc-source-file" title="Permalink to this headline">¶</a></h3>
<p>If you can’t find a source file for a module it may be a built-in or
dynamically loaded module implemented in C, C++ or other compiled language.
In this case you may not have the source file or it may be something like
<code class="file docutils literal notranslate"><span class="pre">mathmodule.c</span></code>, somewhere in a C source directory (not on the Python Path).</p>
<p>There are (at least) three kinds of modules in Python:</p>
<ol class="arabic">
<li><p class="first">modules written in Python (.py);</p>
</li>
<li><p class="first">modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);</p>
</li>
<li><p class="first">modules written in C and linked with the interpreter; to get a list of these,
type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="nb">print</span> <span class="n">sys</span><span class="o">.</span><span class="n">builtin_module_names</span>
</pre></div>
</div>
</li>
</ol>
</div>
<div class="section" id="how-do-i-make-a-python-script-executable-on-unix">
<h3><a class="toc-backref" href="#id5">How do I make a Python script executable on Unix?</a><a class="headerlink" href="#how-do-i-make-a-python-script-executable-on-unix" title="Permalink to this headline">¶</a></h3>
<p>You need to do two things: the script file’s mode must be executable and the
first line must begin with <code class="docutils literal notranslate"><span class="pre">#!</span></code> followed by the path of the Python
interpreter.</p>
<p>The first is done by executing <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">+x</span> <span class="pre">scriptfile</span></code> or perhaps <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">755</span>
<span class="pre">scriptfile</span></code>.</p>
<p>The second can be done in a number of ways.  The most straightforward way is to
write</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>
</pre></div>
</div>
<p>as the very first line of your file, using the pathname for where the Python
interpreter is installed on your platform.</p>
<p>If you would like the script to be independent of where the Python interpreter
lives, you can use the <strong class="program">env</strong> program.  Almost all Unix variants support
the following, assuming the Python interpreter is in a directory on the user’s
<span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
</pre></div>
</div>
<p><em>Don’t</em> do this for CGI scripts.  The <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable for CGI scripts is
often very minimal, so you need to use the actual absolute pathname of the
interpreter.</p>
<p>Occasionally, a user’s environment is so full that the <strong class="program">/usr/bin/env</strong>
program fails; or there’s no env program at all.  In that case, you can try the
following hack (due to Alex Rezinsky):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#! /bin/sh</span>
<span class="sd">&quot;&quot;&quot;:&quot;</span>
<span class="sd">exec python $0 ${1+&quot;$@&quot;}</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>The minor disadvantage is that this defines the script’s __doc__ string.
However, you can fix that by adding</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;...Whatever...&quot;&quot;&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="is-there-a-curses-termcap-package-for-python">
<h3><a class="toc-backref" href="#id6">Is there a curses/termcap package for Python?</a><a class="headerlink" href="#is-there-a-curses-termcap-package-for-python" title="Permalink to this headline">¶</a></h3>
<p>For Unix variants the standard Python source distribution comes with a curses
module in the <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Modules">Modules</a> subdirectory, though it’s not compiled by default.
(Note that this is not available in the Windows distribution – there is no
curses module for Windows.)</p>
<p>The <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module supports basic curses features as well as many additional
functions from ncurses and SYSV curses such as colour, alternative character set
support, pads, and mouse support. This means the module isn’t compatible with
operating systems that only have BSD curses, but there don’t seem to be any
currently maintained OSes that fall into this category.</p>
<p>For Windows: use <a class="reference external" href="http://effbot.org/zone/console-index.htm">the consolelib module</a>.</p>
</div>
<div class="section" id="is-there-an-equivalent-to-c-s-onexit-in-python">
<h3><a class="toc-backref" href="#id7">Is there an equivalent to C’s onexit() in Python?</a><a class="headerlink" href="#is-there-an-equivalent-to-c-s-onexit-in-python" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module provides a register function that is similar to C’s
<code class="xref c c-func docutils literal notranslate"><span class="pre">onexit()</span></code>.</p>
</div>
<div class="section" id="why-don-t-my-signal-handlers-work">
<h3><a class="toc-backref" href="#id8">Why don’t my signal handlers work?</a><a class="headerlink" href="#why-don-t-my-signal-handlers-work" title="Permalink to this headline">¶</a></h3>
<p>The most common problem is that the signal handler is declared with the wrong
argument list.  It is called as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">handler</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">)</span>
</pre></div>
</div>
<p>so it should be declared with two arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">handler</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="common-tasks">
<h2><a class="toc-backref" href="#id9">Common tasks</a><a class="headerlink" href="#common-tasks" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-test-a-python-program-or-component">
<h3><a class="toc-backref" href="#id10">How do I test a Python program or component?</a><a class="headerlink" href="#how-do-i-test-a-python-program-or-component" title="Permalink to this headline">¶</a></h3>
<p>Python comes with two testing frameworks.  The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module finds
examples in the docstrings for a module and runs them, comparing the output with
the expected output given in the docstring.</p>
<p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module is a fancier testing framework modelled on Java and
Smalltalk testing frameworks.</p>
<p>To make testing easier, you should use good modular design in your program.
Your program should have almost all functionality
encapsulated in either functions or class methods – and this sometimes has the
surprising and delightful effect of making the program run faster (because local
variable accesses are faster than global accesses).  Furthermore the program
should avoid depending on mutating global variables, since this makes testing
much more difficult to do.</p>
<p>The “global main logic” of your program may be as simple as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main_logic</span><span class="p">()</span>
</pre></div>
</div>
<p>at the bottom of the main module of your program.</p>
<p>Once your program is organized as a tractable collection of functions and class
behaviours you should write test functions that exercise the behaviours.  A test
suite that automates a sequence of tests can be associated with each module.
This sounds like a lot of work, but since Python is so terse and flexible it’s
surprisingly easy.  You can make coding much more pleasant and fun by writing
your test functions in parallel with the “production code”, since this makes it
easy to find bugs and even design flaws earlier.</p>
<p>“Support modules” that are not intended to be the main module of a program may
include a self-test of the module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">self_test</span><span class="p">()</span>
</pre></div>
</div>
<p>Even programs that interact with complex external interfaces may be tested when
the external interfaces are unavailable by using “fake” interfaces implemented
in Python.</p>
</div>
<div class="section" id="how-do-i-create-documentation-from-doc-strings">
<h3><a class="toc-backref" href="#id11">How do I create documentation from doc strings?</a><a class="headerlink" href="#how-do-i-create-documentation-from-doc-strings" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module can create HTML from the doc strings in your Python
source code.  An alternative for creating API documentation purely from
docstrings is <a class="reference external" href="http://epydoc.sourceforge.net/">epydoc</a>.  <a class="reference external" href="http://sphinx-doc.org">Sphinx</a> can also include docstring content.</p>
</div>
<div class="section" id="how-do-i-get-a-single-keypress-at-a-time">
<h3><a class="toc-backref" href="#id12">How do I get a single keypress at a time?</a><a class="headerlink" href="#how-do-i-get-a-single-keypress-at-a-time" title="Permalink to this headline">¶</a></h3>
<p>For Unix variants there are several solutions.  It’s straightforward to do this
using curses, but curses is a fairly large module to learn.  Here’s a solution
without curses:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">termios</span><span class="o">,</span> <span class="nn">fcntl</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">os</span>
<span class="n">fd</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">fileno</span><span class="p">()</span>

<span class="n">oldterm</span> <span class="o">=</span> <span class="n">termios</span><span class="o">.</span><span class="n">tcgetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">)</span>
<span class="n">newattr</span> <span class="o">=</span> <span class="n">termios</span><span class="o">.</span><span class="n">tcgetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">)</span>
<span class="n">newattr</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="n">newattr</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">&amp;</span> <span class="o">~</span><span class="n">termios</span><span class="o">.</span><span class="n">ICANON</span> <span class="o">&amp;</span> <span class="o">~</span><span class="n">termios</span><span class="o">.</span><span class="n">ECHO</span>
<span class="n">termios</span><span class="o">.</span><span class="n">tcsetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TCSANOW</span><span class="p">,</span> <span class="n">newattr</span><span class="p">)</span>

<span class="n">oldflags</span> <span class="o">=</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">fcntl</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_GETFL</span><span class="p">)</span>
<span class="n">fcntl</span><span class="o">.</span><span class="n">fcntl</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_SETFL</span><span class="p">,</span> <span class="n">oldflags</span> <span class="o">|</span> <span class="n">os</span><span class="o">.</span><span class="n">O_NONBLOCK</span><span class="p">)</span>

<span class="k">try</span><span class="p">:</span>
    <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">c</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
            <span class="nb">print</span> <span class="s2">&quot;Got character&quot;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span> <span class="k">pass</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">termios</span><span class="o">.</span><span class="n">tcsetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TCSAFLUSH</span><span class="p">,</span> <span class="n">oldterm</span><span class="p">)</span>
    <span class="n">fcntl</span><span class="o">.</span><span class="n">fcntl</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_SETFL</span><span class="p">,</span> <span class="n">oldflags</span><span class="p">)</span>
</pre></div>
</div>
<p>You need the <a class="reference internal" href="../library/termios.html#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> and the <a class="reference internal" href="../library/fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fcntl</span></code></a> module for any of this to work,
and I’ve only tried it on Linux, though it should work elsewhere.  In this code,
characters are read and printed one at a time.</p>
<p><a class="reference internal" href="../library/termios.html#termios.tcsetattr" title="termios.tcsetattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">termios.tcsetattr()</span></code></a> turns off stdin’s echoing and disables canonical mode.
<code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.fnctl()</span></code> is used to obtain stdin’s file descriptor flags and modify
them for non-blocking mode.  Since reading stdin when it is empty results in an
<a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>, this error is caught and ignored.</p>
</div>
</div>
<div class="section" id="threads">
<h2><a class="toc-backref" href="#id13">Threads</a><a class="headerlink" href="#threads" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-program-using-threads">
<h3><a class="toc-backref" href="#id14">How do I program using threads?</a><a class="headerlink" href="#how-do-i-program-using-threads" title="Permalink to this headline">¶</a></h3>
<p>Be sure to use the <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module and not the <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module.
The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module builds convenient abstractions on top of the
low-level primitives provided by the <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module.</p>
<p>Aahz has a set of slides from his threading tutorial that are helpful; see
<a class="reference external" href="http://www.pythoncraft.com/OSCON2001/">http://www.pythoncraft.com/OSCON2001/</a>.</p>
</div>
<div class="section" id="none-of-my-threads-seem-to-run-why">
<h3><a class="toc-backref" href="#id15">None of my threads seem to run: why?</a><a class="headerlink" href="#none-of-my-threads-seem-to-run-why" title="Permalink to this headline">¶</a></h3>
<p>As soon as the main thread exits, all threads are killed.  Your main thread is
running too quickly, giving the threads no time to do any work.</p>
<p>A simple fix is to add a sleep to the end of the program that’s long enough for
all the threads to finish:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">thread_task</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="nb">print</span> <span class="n">name</span><span class="p">,</span> <span class="n">i</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
    <span class="n">T</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">thread_task</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">i</span><span class="p">))</span>
    <span class="n">T</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># &lt;----------------------------!</span>
</pre></div>
</div>
<p>But now (on many platforms) the threads don’t run in parallel, but appear to run
sequentially, one at a time!  The reason is that the OS thread scheduler doesn’t
start a new thread until the previous thread is blocked.</p>
<p>A simple fix is to add a tiny sleep to the start of the run function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">thread_task</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.001</span><span class="p">)</span> <span class="c1"># &lt;---------------------!</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="nb">print</span> <span class="n">name</span><span class="p">,</span> <span class="n">i</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
    <span class="n">T</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">thread_task</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">i</span><span class="p">))</span>
    <span class="n">T</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
<p>Instead of trying to guess a good delay value for <a class="reference internal" href="../library/time.html#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.sleep()</span></code></a>,
it’s better to use some kind of semaphore mechanism.  One idea is to use the
<a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module to create a queue object, let each thread append a token to
the queue when it finishes, and let the main thread read as many tokens from the
queue as there are threads.</p>
</div>
<div class="section" id="how-do-i-parcel-out-work-among-a-bunch-of-worker-threads">
<h3><a class="toc-backref" href="#id16">How do I parcel out work among a bunch of worker threads?</a><a class="headerlink" href="#how-do-i-parcel-out-work-among-a-bunch-of-worker-threads" title="Permalink to this headline">¶</a></h3>
<p>Use the <a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module to create a queue containing a list of jobs.  The
<a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> class maintains a list of objects and has a <code class="docutils literal notranslate"><span class="pre">.put(obj)</span></code>
method that adds items to the queue and a <code class="docutils literal notranslate"><span class="pre">.get()</span></code> method to return them.
The class will take care of the locking necessary to ensure that each job is
handed out exactly once.</p>
<p>Here’s a trivial example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">Queue</span><span class="o">,</span> <span class="nn">time</span>

<span class="c1"># The worker thread gets jobs off the queue.  When the queue is empty, it</span>
<span class="c1"># assumes there will be no more work and exits.</span>
<span class="c1"># (Realistically workers will run until terminated.)</span>
<span class="k">def</span> <span class="nf">worker</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s1">&#39;Running worker&#39;</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">arg</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">block</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">Queue</span><span class="o">.</span><span class="n">Empty</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s1">&#39;Worker&#39;</span><span class="p">,</span> <span class="n">threading</span><span class="o">.</span><span class="n">currentThread</span><span class="p">(),</span>
            <span class="nb">print</span> <span class="s1">&#39;queue empty&#39;</span>
            <span class="k">break</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s1">&#39;Worker&#39;</span><span class="p">,</span> <span class="n">threading</span><span class="o">.</span><span class="n">currentThread</span><span class="p">(),</span>
            <span class="nb">print</span> <span class="s1">&#39;running with argument&#39;</span><span class="p">,</span> <span class="n">arg</span>
            <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="p">)</span>

<span class="c1"># Create queue</span>
<span class="n">q</span> <span class="o">=</span> <span class="n">Queue</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>

<span class="c1"># Start a pool of 5 workers</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">worker</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;worker </span><span class="si">%i</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span>
    <span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="c1"># Begin adding work to the queue</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">50</span><span class="p">):</span>
    <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>

<span class="c1"># Give threads time to run</span>
<span class="nb">print</span> <span class="s1">&#39;Main thread sleeping&#39;</span>
<span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>When run, this will produce the following output:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker &lt;Thread(worker 1, started)&gt; running with argument 0
Worker &lt;Thread(worker 2, started)&gt; running with argument 1
Worker &lt;Thread(worker 3, started)&gt; running with argument 2
Worker &lt;Thread(worker 4, started)&gt; running with argument 3
Worker &lt;Thread(worker 5, started)&gt; running with argument 4
Worker &lt;Thread(worker 1, started)&gt; running with argument 5
...
</pre></div>
</div>
<p>Consult the module’s documentation for more details; the <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>
class provides a featureful interface.</p>
</div>
<div class="section" id="what-kinds-of-global-value-mutation-are-thread-safe">
<h3><a class="toc-backref" href="#id17">What kinds of global value mutation are thread-safe?</a><a class="headerlink" href="#what-kinds-of-global-value-mutation-are-thread-safe" title="Permalink to this headline">¶</a></h3>
<p>A <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is used internally to ensure that only
one thread runs in the Python VM at a time.  In general, Python offers to switch
among threads only between bytecode instructions; how frequently it switches can
be set via <a class="reference internal" href="../library/sys.html#sys.setcheckinterval" title="sys.setcheckinterval"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setcheckinterval()</span></code></a>.  Each bytecode instruction and
therefore all the C implementation code reached from each instruction is
therefore atomic from the point of view of a Python program.</p>
<p>In theory, this means an exact accounting requires an exact understanding of the
PVM bytecode implementation.  In practice, it means that operations on shared
variables of built-in data types (ints, lists, dicts, etc) that “look atomic”
really are.</p>
<p>For example, the following operations are all atomic (L, L1, L2 are lists, D,
D1, D2 are dicts, x, y are objects, i, j are ints):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">L1</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">L2</span><span class="p">)</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">L</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="n">L1</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">L2</span>
<span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">y</span>
<span class="n">x</span><span class="o">.</span><span class="n">field</span> <span class="o">=</span> <span class="n">y</span>
<span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span>
<span class="n">D1</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">D2</span><span class="p">)</span>
<span class="n">D</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
</pre></div>
</div>
<p>These aren’t:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">=</span> <span class="n">i</span><span class="o">+</span><span class="mi">1</span>
<span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">L</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
<span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">j</span><span class="p">]</span>
<span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">D</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Operations that replace other objects may invoke those other objects’
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method when their reference count reaches zero, and that can
affect things.  This is especially true for the mass updates to dictionaries and
lists.  When in doubt, use a mutex!</p>
</div>
<div class="section" id="can-t-we-get-rid-of-the-global-interpreter-lock">
<h3><a class="toc-backref" href="#id18">Can’t we get rid of the Global Interpreter Lock?</a><a class="headerlink" href="#can-t-we-get-rid-of-the-global-interpreter-lock" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> (GIL) is often seen as a hindrance to Python’s
deployment on high-end multiprocessor server machines, because a multi-threaded
Python program effectively only uses one CPU, due to the insistence that
(almost) all Python code can only run while the GIL is held.</p>
<p>Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
patch set (the “free threading” patches) that removed the GIL and replaced it
with fine-grained locking.  Unfortunately, even on Windows (where locks are very
efficient) this ran ordinary Python code about twice as slow as the interpreter
using the GIL.  On Linux the performance loss was even worse because pthread
locks aren’t as efficient.</p>
<p>Since then, the idea of getting rid of the GIL has occasionally come up but
nobody has found a way to deal with the expected slowdown, and users who don’t
use threads would not be happy if their code ran at half the speed.  Greg’s
free threading patch set has not been kept up-to-date for later Python versions.</p>
<p>This doesn’t mean that you can’t make good use of Python on multi-CPU machines!
You just have to be creative with dividing the work up between multiple
<em>processes</em> rather than multiple <em>threads</em>.  Judicious use of C extensions will
also help; if you use a C extension to perform a time-consuming task, the
extension can release the GIL while the thread of execution is in the C code and
allow other threads to get some work done.</p>
<p>It has been suggested that the GIL should be a per-interpreter-state lock rather
than truly global; interpreters then wouldn’t be able to share objects.
Unfortunately, this isn’t likely to happen either.  It would be a tremendous
amount of work, because many object implementations currently have global state.
For example, small integers and short strings are cached; these caches would
have to be moved to the interpreter state.  Other object types have their own
free list; these free lists would have to be moved to the interpreter state.
And so on.</p>
<p>And I doubt that it can even be done in finite time, because the same problem
exists for 3rd party extensions.  It is likely that 3rd party extensions are
being written at a faster rate than you can convert them to store all their
global state in the interpreter state.</p>
<p>And finally, once you have multiple interpreters not sharing any state, what
have you gained over running each interpreter in a separate process?</p>
</div>
</div>
<div class="section" id="input-and-output">
<h2><a class="toc-backref" href="#id19">Input and Output</a><a class="headerlink" href="#input-and-output" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-delete-a-file-and-other-file-questions">
<h3><a class="toc-backref" href="#id20">How do I delete a file? (And other file questions…)</a><a class="headerlink" href="#how-do-i-delete-a-file-and-other-file-questions" title="Permalink to this headline">¶</a></h3>
<p>Use <code class="docutils literal notranslate"><span class="pre">os.remove(filename)</span></code> or <code class="docutils literal notranslate"><span class="pre">os.unlink(filename)</span></code>; for documentation, see
the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module.  The two functions are identical; <code class="xref py py-func docutils literal notranslate"><span class="pre">unlink()</span></code> is simply
the name of the Unix system call for this function.</p>
<p>To remove a directory, use <a class="reference internal" href="../library/os.html#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.rmdir()</span></code></a>; use <a class="reference internal" href="../library/os.html#os.mkdir" title="os.mkdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.mkdir()</span></code></a> to create one.
<code class="docutils literal notranslate"><span class="pre">os.makedirs(path)</span></code> will create any intermediate directories in <code class="docutils literal notranslate"><span class="pre">path</span></code> that
don’t exist. <code class="docutils literal notranslate"><span class="pre">os.removedirs(path)</span></code> will remove intermediate directories as
long as they’re empty; if you want to delete an entire directory tree and its
contents, use <a class="reference internal" href="../library/shutil.html#shutil.rmtree" title="shutil.rmtree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.rmtree()</span></code></a>.</p>
<p>To rename a file, use <code class="docutils literal notranslate"><span class="pre">os.rename(old_path,</span> <span class="pre">new_path)</span></code>.</p>
<p>To truncate a file, open it using <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">open(filename,</span> <span class="pre">&quot;r+&quot;)</span></code>, and use
<code class="docutils literal notranslate"><span class="pre">f.truncate(offset)</span></code>; offset defaults to the current seek position.  There’s
also <code class="docutils literal notranslate"><span class="pre">os.ftruncate(fd,</span> <span class="pre">offset)</span></code> for files opened with <a class="reference internal" href="../library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>, where
<em>fd</em> is the file descriptor (a small integer).</p>
<p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module also contains a number of functions to work on files
including <a class="reference internal" href="../library/shutil.html#shutil.copyfile" title="shutil.copyfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyfile()</span></code></a>, <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>, and
<a class="reference internal" href="../library/shutil.html#shutil.rmtree" title="shutil.rmtree"><code class="xref py py-func docutils literal notranslate"><span class="pre">rmtree()</span></code></a>.</p>
</div>
<div class="section" id="how-do-i-copy-a-file">
<h3><a class="toc-backref" href="#id21">How do I copy a file?</a><a class="headerlink" href="#how-do-i-copy-a-file" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module contains a <a class="reference internal" href="../library/shutil.html#shutil.copyfile" title="shutil.copyfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyfile()</span></code></a> function.  Note
that on MacOS 9 it doesn’t copy the resource fork and Finder info.</p>
</div>
<div class="section" id="how-do-i-read-or-write-binary-data">
<h3><a class="toc-backref" href="#id22">How do I read (or write) binary data?</a><a class="headerlink" href="#how-do-i-read-or-write-binary-data" title="Permalink to this headline">¶</a></h3>
<p>To read or write complex binary data formats, it’s best to use the <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a>
module.  It allows you to take a string containing binary data (usually numbers)
and convert it to Python objects; and vice versa.</p>
<p>For example, the following code reads two 2-byte integers and one 4-byte integer
in big-endian format from a file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">)</span>  <span class="c1"># Open in binary mode for portability</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s2">&quot;&gt;hhl&quot;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
</pre></div>
</div>
<p>The ‘&gt;’ in the format string forces big-endian data; the letter ‘h’ reads one
“short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the
string.</p>
<p>For data that is more regular (e.g. a homogeneous list of ints or floats),
you can also use the <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module.</p>
</div>
<div class="section" id="i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why">
<h3><a class="toc-backref" href="#id23">I can’t seem to use os.read() on a pipe created with os.popen(); why?</a><a class="headerlink" href="#i-can-t-seem-to-use-os-read-on-a-pipe-created-with-os-popen-why" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../library/os.html#os.read" title="os.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.read()</span></code></a> is a low-level function which takes a file descriptor, a small
integer representing the opened file.  <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> creates a high-level
file object, the same type returned by the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.
Thus, to read <em>n</em> bytes from a pipe <em>p</em> created with <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, you need to
use <code class="docutils literal notranslate"><span class="pre">p.read(n)</span></code>.</p>
</div>
<div class="section" id="how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output">
<h3><a class="toc-backref" href="#id24">How do I run a subprocess with pipes connected to both input and output?</a><a class="headerlink" href="#how-do-i-run-a-subprocess-with-pipes-connected-to-both-input-and-output" title="Permalink to this headline">¶</a></h3>
<p>Use the <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">popen2</span>
<span class="n">fromchild</span><span class="p">,</span> <span class="n">tochild</span> <span class="o">=</span> <span class="n">popen2</span><span class="o">.</span><span class="n">popen2</span><span class="p">(</span><span class="s2">&quot;command&quot;</span><span class="p">)</span>
<span class="n">tochild</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;input</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">tochild</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
<span class="n">output</span> <span class="o">=</span> <span class="n">fromchild</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
<p>Warning: in general it is unwise to do this because you can easily cause a
deadlock where your process is blocked waiting for output from the child while
the child is blocked waiting for input from you.  This can be caused by the
parent expecting the child to output more text than it does or by data being
stuck in stdio buffers due to lack of flushing.  The Python parent
can of course explicitly flush the data it sends to the child before it reads
any output, but if the child is a naive C program it may have been written to
never explicitly flush its output, even if it is interactive, since flushing is
normally automatic.</p>
<p>Note that a deadlock is also possible if you use <code class="xref py py-func docutils literal notranslate"><span class="pre">popen3()</span></code> to read stdout
and stderr. If one of the two is too large for the internal buffer (increasing
the buffer size does not help) and you <code class="docutils literal notranslate"><span class="pre">read()</span></code> the other one first, there is
a deadlock, too.</p>
<p>Note on a bug in popen2: unless your program calls <code class="docutils literal notranslate"><span class="pre">wait()</span></code> or <code class="docutils literal notranslate"><span class="pre">waitpid()</span></code>,
finished child processes are never removed, and eventually calls to popen2 will
fail because of a limit on the number of child processes.  Calling
<a class="reference internal" href="../library/os.html#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.waitpid()</span></code></a> with the <a class="reference internal" href="../library/os.html#os.WNOHANG" title="os.WNOHANG"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.WNOHANG</span></code></a> option can prevent this; a good
place to insert such a call would be before calling <code class="docutils literal notranslate"><span class="pre">popen2</span></code> again.</p>
<p>In many cases, all you really need is to run some data through a command and get
the result back.  Unless the amount of data is very large, the easiest way to do
this is to write it to a temporary file and run the command with that temporary
file as input.  The standard module <a class="reference internal" href="../library/tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a> exports a
<a class="reference internal" href="../library/tempfile.html#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code></a> function to generate unique temporary file names.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tempfile</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">class</span> <span class="nc">Popen3</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This is a deadlock-safe version of popen that returns</span>
<span class="sd">    an object with errorlevel, out (a string) and err (a string).</span>
<span class="sd">    (capturestderr may not work under windows.)</span>
<span class="sd">    Example: print Popen3(&#39;grep spam&#39;,&#39;\n\nhere spam\n\n&#39;).out</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">command</span><span class="p">,</span><span class="nb">input</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span><span class="n">capturestderr</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">outfile</span><span class="o">=</span><span class="n">tempfile</span><span class="o">.</span><span class="n">mktemp</span><span class="p">()</span>
        <span class="n">command</span><span class="o">=</span><span class="s2">&quot;( </span><span class="si">%s</span><span class="s2"> ) &gt; </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">command</span><span class="p">,</span><span class="n">outfile</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">input</span><span class="p">:</span>
            <span class="n">infile</span><span class="o">=</span><span class="n">tempfile</span><span class="o">.</span><span class="n">mktemp</span><span class="p">()</span>
            <span class="nb">open</span><span class="p">(</span><span class="n">infile</span><span class="p">,</span><span class="s2">&quot;w&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
            <span class="n">command</span><span class="o">=</span><span class="n">command</span><span class="o">+</span><span class="s2">&quot; &lt;&quot;</span><span class="o">+</span><span class="n">infile</span>
        <span class="k">if</span> <span class="n">capturestderr</span><span class="p">:</span>
            <span class="n">errfile</span><span class="o">=</span><span class="n">tempfile</span><span class="o">.</span><span class="n">mktemp</span><span class="p">()</span>
            <span class="n">command</span><span class="o">=</span><span class="n">command</span><span class="o">+</span><span class="s2">&quot; 2&gt;&quot;</span><span class="o">+</span><span class="n">errfile</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">errorlevel</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="n">command</span><span class="p">)</span> <span class="o">&gt;&gt;</span> <span class="mi">8</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">out</span><span class="o">=</span><span class="nb">open</span><span class="p">(</span><span class="n">outfile</span><span class="p">,</span><span class="s2">&quot;r&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
        <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">outfile</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">input</span><span class="p">:</span>
            <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">infile</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">capturestderr</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">err</span><span class="o">=</span><span class="nb">open</span><span class="p">(</span><span class="n">errfile</span><span class="p">,</span><span class="s2">&quot;r&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
            <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">errfile</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that many interactive programs (e.g. vi) don’t work well with pipes
substituted for standard input and output.  You will have to use pseudo ttys
(“ptys”) instead of pipes. Or you can use a Python interface to Don Libes’
“expect” library.  A Python extension that interfaces to expect is called “expy”
and available from <a class="reference external" href="http://expectpy.sourceforge.net">http://expectpy.sourceforge.net</a>.  A pure Python solution that
works like expect is <a class="reference external" href="https://pypi.org/project/pexpect/">pexpect</a>.</p>
</div>
<div class="section" id="how-do-i-access-the-serial-rs232-port">
<h3><a class="toc-backref" href="#id25">How do I access the serial (RS232) port?</a><a class="headerlink" href="#how-do-i-access-the-serial-rs232-port" title="Permalink to this headline">¶</a></h3>
<p>For Win32, POSIX (Linux, BSD, etc.), Jython:</p>
<blockquote>
<div><a class="reference external" href="http://pyserial.sourceforge.net">http://pyserial.sourceforge.net</a></div></blockquote>
<p>For Unix, see a Usenet post by Mitch Chapman:</p>
<blockquote>
<div><a class="reference external" href="https://groups.google.com/groups?selm=34A04430.CF9&#64;ohioee.com">https://groups.google.com/groups?selm=34A04430.CF9&#64;ohioee.com</a></div></blockquote>
</div>
<div class="section" id="why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it">
<h3><a class="toc-backref" href="#id26">Why doesn’t closing sys.stdout (stdin, stderr) really close it?</a><a class="headerlink" href="#why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it" title="Permalink to this headline">¶</a></h3>
<p>Python file objects are a high-level layer of abstraction on top of C streams,
which in turn are a medium-level layer of abstraction on top of (among other
things) low-level C file descriptors.</p>
<p>For most file objects you create in Python via the built-in <code class="docutils literal notranslate"><span class="pre">file</span></code>
constructor, <code class="docutils literal notranslate"><span class="pre">f.close()</span></code> marks the Python file object as being closed from
Python’s point of view, and also arranges to close the underlying C stream.
This also happens automatically in <code class="docutils literal notranslate"><span class="pre">f</span></code>’s destructor, when <code class="docutils literal notranslate"><span class="pre">f</span></code> becomes
garbage.</p>
<p>But stdin, stdout and stderr are treated specially by Python, because of the
special status also given to them by C.  Running <code class="docutils literal notranslate"><span class="pre">sys.stdout.close()</span></code> marks
the Python-level file object as being closed, but does <em>not</em> close the
associated C stream.</p>
<p>To close the underlying C stream for one of these three, you should first be
sure that’s what you really want to do (e.g., you may confuse extension modules
trying to do I/O).  If it is, use os.close:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>   <span class="c1"># close C&#39;s stdin stream</span>
<span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>   <span class="c1"># close C&#39;s stdout stream</span>
<span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>   <span class="c1"># close C&#39;s stderr stream</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="network-internet-programming">
<h2><a class="toc-backref" href="#id27">Network/Internet Programming</a><a class="headerlink" href="#network-internet-programming" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-www-tools-are-there-for-python">
<h3><a class="toc-backref" href="#id28">What WWW tools are there for Python?</a><a class="headerlink" href="#what-www-tools-are-there-for-python" title="Permalink to this headline">¶</a></h3>
<p>See the chapters titled <a class="reference internal" href="../library/internet.html#internet"><span class="std std-ref">Internet Protocols and Support</span></a> and <a class="reference internal" href="../library/netdata.html#netdata"><span class="std std-ref">Internet Data Handling</span></a> in the Library
Reference Manual.  Python has many modules that will help you build server-side
and client-side web systems.</p>
<p>A summary of available frameworks is maintained by Paul Boddie at
<a class="reference external" href="https://wiki.python.org/moin/WebProgramming">https://wiki.python.org/moin/WebProgramming</a>.</p>
<p>Cameron Laird maintains a useful set of pages about Python web technologies at
<a class="reference external" href="http://phaseit.net/claird/comp.lang.python/web_python">http://phaseit.net/claird/comp.lang.python/web_python</a>.</p>
</div>
<div class="section" id="how-can-i-mimic-cgi-form-submission-method-post">
<h3><a class="toc-backref" href="#id29">How can I mimic CGI form submission (METHOD=POST)?</a><a class="headerlink" href="#how-can-i-mimic-cgi-form-submission-method-post" title="Permalink to this headline">¶</a></h3>
<p>I would like to retrieve web pages that are the result of POSTing a form. Is
there existing code that would let me do this easily?</p>
<p>Yes. Here’s a simple example that uses httplib:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>

<span class="kn">import</span> <span class="nn">httplib</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">time</span>

<span class="c1"># build the query string</span>
<span class="n">qs</span> <span class="o">=</span> <span class="s2">&quot;First=Josephine&amp;MI=Q&amp;Last=Public&quot;</span>

<span class="c1"># connect and send the server a path</span>
<span class="n">httpobj</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTP</span><span class="p">(</span><span class="s1">&#39;www.some-server.out-there&#39;</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">putrequest</span><span class="p">(</span><span class="s1">&#39;POST&#39;</span><span class="p">,</span> <span class="s1">&#39;/cgi-bin/some-cgi-script&#39;</span><span class="p">)</span>
<span class="c1"># now generate the rest of the HTTP headers...</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">putheader</span><span class="p">(</span><span class="s1">&#39;Accept&#39;</span><span class="p">,</span> <span class="s1">&#39;*/*&#39;</span><span class="p">)</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">putheader</span><span class="p">(</span><span class="s1">&#39;Connection&#39;</span><span class="p">,</span> <span class="s1">&#39;Keep-Alive&#39;</span><span class="p">)</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">putheader</span><span class="p">(</span><span class="s1">&#39;Content-type&#39;</span><span class="p">,</span> <span class="s1">&#39;application/x-www-form-urlencoded&#39;</span><span class="p">)</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">putheader</span><span class="p">(</span><span class="s1">&#39;Content-length&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%d</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="nb">len</span><span class="p">(</span><span class="n">qs</span><span class="p">))</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">endheaders</span><span class="p">()</span>
<span class="n">httpobj</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">qs</span><span class="p">)</span>
<span class="c1"># find out what the server said in response...</span>
<span class="n">reply</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">hdrs</span> <span class="o">=</span> <span class="n">httpobj</span><span class="o">.</span><span class="n">getreply</span><span class="p">()</span>
<span class="k">if</span> <span class="n">reply</span> <span class="o">!=</span> <span class="mi">200</span><span class="p">:</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">httpobj</span><span class="o">.</span><span class="n">getfile</span><span class="p">()</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
</pre></div>
</div>
<p>Note that in general for percent-encoded POST operations, query strings must be
quoted using <a class="reference internal" href="../library/urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a>.  For example, to send
<code class="docutils literal notranslate"><span class="pre">name=Guy</span> <span class="pre">Steele,</span> <span class="pre">Jr.</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Guy Steele, Jr.&#39;</span><span class="p">})</span>
<span class="go">&#39;name=Guy+Steele%2C+Jr.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="what-module-should-i-use-to-help-with-generating-html">
<h3><a class="toc-backref" href="#id30">What module should I use to help with generating HTML?</a><a class="headerlink" href="#what-module-should-i-use-to-help-with-generating-html" title="Permalink to this headline">¶</a></h3>
<p>You can find a collection of useful links on the <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">Web Programming wiki page</a>.</p>
</div>
<div class="section" id="how-do-i-send-mail-from-a-python-script">
<h3><a class="toc-backref" href="#id31">How do I send mail from a Python script?</a><a class="headerlink" href="#how-do-i-send-mail-from-a-python-script" title="Permalink to this headline">¶</a></h3>
<p>Use the standard library module <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a>.</p>
<p>Here’s a very simple interactive mail sender that uses it.  This method will
work on any host that supports an SMTP listener.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">smtplib</span>

<span class="n">fromaddr</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;From: &quot;</span><span class="p">)</span>
<span class="n">toaddrs</span>  <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;To: &quot;</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Enter message, end with ^D:&quot;</span>
<span class="n">msg</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="n">msg</span> <span class="o">+=</span> <span class="n">line</span>

<span class="c1"># The actual mail send</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">fromaddr</span><span class="p">,</span> <span class="n">toaddrs</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>A Unix-only alternative uses sendmail.  The location of the sendmail program
varies between systems; sometimes it is <code class="docutils literal notranslate"><span class="pre">/usr/lib/sendmail</span></code>, sometimes
<code class="docutils literal notranslate"><span class="pre">/usr/sbin/sendmail</span></code>.  The sendmail manual page will help you out.  Here’s
some sample code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>

<span class="n">SENDMAIL</span> <span class="o">=</span> <span class="s2">&quot;/usr/sbin/sendmail&quot;</span>  <span class="c1"># sendmail location</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> -t -i&quot;</span> <span class="o">%</span> <span class="n">SENDMAIL</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;To: receiver@example.com</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Subject: test</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span> <span class="c1"># blank line separating headers from body</span>
<span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Some text</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;some more text</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">sts</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">if</span> <span class="n">sts</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Sendmail exit status&quot;</span><span class="p">,</span> <span class="n">sts</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-avoid-blocking-in-the-connect-method-of-a-socket">
<h3><a class="toc-backref" href="#id32">How do I avoid blocking in the connect() method of a socket?</a><a class="headerlink" href="#how-do-i-avoid-blocking-in-the-connect-method-of-a-socket" title="Permalink to this headline">¶</a></h3>
<p>The select module is commonly used to help with asynchronous I/O on sockets.</p>
<p>To prevent the TCP connect from blocking, you can set the socket to non-blocking
mode.  Then when you do the <code class="docutils literal notranslate"><span class="pre">connect()</span></code>, you will either connect immediately
(unlikely) or get an exception that contains the error number as <code class="docutils literal notranslate"><span class="pre">.errno</span></code>.
<code class="docutils literal notranslate"><span class="pre">errno.EINPROGRESS</span></code> indicates that the connection is in progress, but hasn’t
finished yet.  Different OSes will return different values, so you’re going to
have to check what’s returned on your system.</p>
<p>You can use the <code class="docutils literal notranslate"><span class="pre">connect_ex()</span></code> method to avoid creating an exception.  It will
just return the errno value.  To poll, you can call <code class="docutils literal notranslate"><span class="pre">connect_ex()</span></code> again later
– 0 or <code class="docutils literal notranslate"><span class="pre">errno.EISCONN</span></code> indicate that you’re connected – or you can pass this
socket to select to check if it’s writable.</p>
</div>
</div>
<div class="section" id="databases">
<h2><a class="toc-backref" href="#id33">Databases</a><a class="headerlink" href="#databases" title="Permalink to this headline">¶</a></h2>
<div class="section" id="are-there-any-interfaces-to-database-packages-in-python">
<h3><a class="toc-backref" href="#id34">Are there any interfaces to database packages in Python?</a><a class="headerlink" href="#are-there-any-interfaces-to-database-packages-in-python" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>Python 2.3 includes the <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> package which provides an interface to the
BerkeleyDB library.  Interfaces to disk-based hashes such as <a class="reference internal" href="../library/dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">DBM</span></code></a>
and <a class="reference internal" href="../library/gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">GDBM</span></code></a> are also included with standard Python.</p>
<p>Support for most relational databases is available.  See the
<a class="reference external" href="https://wiki.python.org/moin/DatabaseProgramming">DatabaseProgramming wiki page</a> for details.</p>
</div>
<div class="section" id="how-do-you-implement-persistent-objects-in-python">
<h3><a class="toc-backref" href="#id35">How do you implement persistent objects in Python?</a><a class="headerlink" href="#how-do-you-implement-persistent-objects-in-python" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> library module solves this in a very general way (though you
still can’t store things like open files, sockets or windows), and the
<a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> library module uses pickle and (g)dbm to create persistent
mappings containing arbitrary Python objects.  For better performance, you can
use the <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module.</p>
<p>A more awkward way of doing things is to use pickle’s little sister, marshal.
The <a class="reference internal" href="../library/marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module provides very fast ways to store noncircular basic
Python types to files and strings, and back again.  Although marshal does not do
fancy things like store instances or handle shared references properly, it does
run extremely fast.  For example, loading a half megabyte of data may take less
than a third of a second.  This often beats doing something more complex and
general such as using gdbm with pickle/shelve.</p>
</div>
<div class="section" id="why-is-cpickle-so-slow">
<h3><a class="toc-backref" href="#id36">Why is cPickle so slow?</a><a class="headerlink" href="#why-is-cpickle-so-slow" title="Permalink to this headline">¶</a></h3>
<p>By default <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> uses a relatively old and slow format for backward
compatibility.  You can however specify other protocol versions that are
faster:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">largeString</span> <span class="o">=</span> <span class="s1">&#39;z&#39;</span> <span class="o">*</span> <span class="p">(</span><span class="mi">100</span> <span class="o">*</span> <span class="mi">1024</span><span class="p">)</span>
<span class="n">myPickle</span> <span class="o">=</span> <span class="n">cPickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">largeString</span><span class="p">,</span> <span class="n">protocol</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come">
<h3><a class="toc-backref" href="#id37">If my program crashes with a bsddb (or anydbm) database open, it gets corrupted. How come?</a><a class="headerlink" href="#if-my-program-crashes-with-a-bsddb-or-anydbm-database-open-it-gets-corrupted-how-come" title="Permalink to this headline">¶</a></h3>
<p>Databases opened for write access with the bsddb module (and often by the anydbm
module, since it will preferentially use bsddb) must explicitly be closed using
the <code class="docutils literal notranslate"><span class="pre">.close()</span></code> method of the database.  The underlying library caches database
contents which need to be converted to on-disk form and written.</p>
<p>If you have initialized a new bsddb database but not written anything to it
before the program crashes, you will often wind up with a zero-length file and
encounter an exception the next time the file is opened.</p>
</div>
<div class="section" id="i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data">
<h3><a class="toc-backref" href="#id38">I tried to open Berkeley DB file, but bsddb produces bsddb.error: (22, ‘Invalid argument’). Help! How can I restore my data?</a><a class="headerlink" href="#i-tried-to-open-berkeley-db-file-but-bsddb-produces-bsddb-error-22-invalid-argument-help-how-can-i-restore-my-data" title="Permalink to this headline">¶</a></h3>
<p>Don’t panic! Your data is probably intact. The most frequent cause for the error
is that you tried to open an earlier Berkeley DB file with a later version of
the Berkeley DB library.</p>
<p>Many Linux systems now have all three versions of Berkeley DB available.  If you
are migrating from version 1 to a newer version use db_dump185 to dump a plain
text version of the database.  If you are migrating from version 2 to version 3
use db2_dump to create a plain text version of the database.  In either case,
use db_load to create a new native database for the latest version installed on
your computer.  If you have version 3 of Berkeley DB installed, you should be
able to use db2_load to create a native version 2 database.</p>
<p>You should move away from Berkeley DB version 1 files because the hash file code
contains known bugs that can corrupt your data.</p>
</div>
</div>
<div class="section" id="mathematics-and-numerics">
<h2><a class="toc-backref" href="#id39">Mathematics and Numerics</a><a class="headerlink" href="#mathematics-and-numerics" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-generate-random-numbers-in-python">
<h3><a class="toc-backref" href="#id40">How do I generate random numbers in Python?</a><a class="headerlink" href="#how-do-i-generate-random-numbers-in-python" title="Permalink to this headline">¶</a></h3>
<p>The standard module <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> implements a random number generator.  Usage
is simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">random</span>
<span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span>
</pre></div>
</div>
<p>This returns a random floating point number in the range [0, 1).</p>
<p>There are also many other specialized generators in this module, such as:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">randrange(a,</span> <span class="pre">b)</span></code> chooses an integer in the range [a, b).</li>
<li><code class="docutils literal notranslate"><span class="pre">uniform(a,</span> <span class="pre">b)</span></code> chooses a floating point number in the range [a, b).</li>
<li><code class="docutils literal notranslate"><span class="pre">normalvariate(mean,</span> <span class="pre">sdev)</span></code> samples the normal (Gaussian) distribution.</li>
</ul>
<p>Some higher-level functions operate on sequences directly, such as:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">choice(S)</span></code> chooses random element from a given sequence</li>
<li><code class="docutils literal notranslate"><span class="pre">shuffle(L)</span></code> shuffles a list in-place, i.e. permutes it randomly</li>
</ul>
<p>There’s also a <code class="docutils literal notranslate"><span class="pre">Random</span></code> class you can instantiate to create independent
multiple random number generators.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Library and Extension FAQ</a><ul>
<li><a class="reference internal" href="#general-library-questions">General Library Questions</a></li>
<li><a class="reference internal" href="#common-tasks">Common tasks</a></li>
<li><a class="reference internal" href="#threads">Threads</a></li>
<li><a class="reference internal" href="#input-and-output">Input and Output</a></li>
<li><a class="reference internal" href="#network-internet-programming">Network/Internet Programming</a></li>
<li><a class="reference internal" href="#databases">Databases</a></li>
<li><a class="reference internal" href="#mathematics-and-numerics">Mathematics and Numerics</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="design.html"
                        title="previous chapter">Design and History FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="extending.html"
                        title="next chapter">Extending/Embedding FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/library.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="extending.html" title="Extending/Embedding FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��h�]T]Thtml/faq/programming.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Programming FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Design and History FAQ" href="design.html" />
    <link rel="prev" title="General Python FAQ" href="general.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/programming.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="programming-faq">
<h1><a class="toc-backref" href="#id1">Programming FAQ</a><a class="headerlink" href="#programming-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#programming-faq" id="id1">Programming FAQ</a><ul>
<li><a class="reference internal" href="#general-questions" id="id2">General Questions</a><ul>
<li><a class="reference internal" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" id="id3">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a></li>
<li><a class="reference internal" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" id="id4">Is there a tool to help find bugs or perform static analysis?</a></li>
<li><a class="reference internal" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" id="id5">How can I create a stand-alone binary from a Python script?</a></li>
<li><a class="reference internal" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" id="id6">Are there coding standards or a style guide for Python programs?</a></li>
<li><a class="reference internal" href="#my-program-is-too-slow-how-do-i-speed-it-up" id="id7">My program is too slow. How do I speed it up?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#core-language" id="id8">Core Language</a><ul>
<li><a class="reference internal" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" id="id9">Why am I getting an UnboundLocalError when the variable has a value?</a></li>
<li><a class="reference internal" href="#what-are-the-rules-for-local-and-global-variables-in-python" id="id10">What are the rules for local and global variables in Python?</a></li>
<li><a class="reference internal" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" id="id11">Why do lambdas defined in a loop with different values all return the same result?</a></li>
<li><a class="reference internal" href="#how-do-i-share-global-variables-across-modules" id="id12">How do I share global variables across modules?</a></li>
<li><a class="reference internal" href="#what-are-the-best-practices-for-using-import-in-a-module" id="id13">What are the “best practices” for using import in a module?</a></li>
<li><a class="reference internal" href="#why-are-default-values-shared-between-objects" id="id14">Why are default values shared between objects?</a></li>
<li><a class="reference internal" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" id="id15">How can I pass optional or keyword parameters from one function to another?</a></li>
<li><a class="reference internal" href="#what-is-the-difference-between-arguments-and-parameters" id="id16">What is the difference between arguments and parameters?</a></li>
<li><a class="reference internal" href="#why-did-changing-list-y-also-change-list-x" id="id17">Why did changing list ‘y’ also change list ‘x’?</a></li>
<li><a class="reference internal" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" id="id18">How do I write a function with output parameters (call by reference)?</a></li>
<li><a class="reference internal" href="#how-do-you-make-a-higher-order-function-in-python" id="id19">How do you make a higher order function in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-copy-an-object-in-python" id="id20">How do I copy an object in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-find-the-methods-or-attributes-of-an-object" id="id21">How can I find the methods or attributes of an object?</a></li>
<li><a class="reference internal" href="#how-can-my-code-discover-the-name-of-an-object" id="id22">How can my code discover the name of an object?</a></li>
<li><a class="reference internal" href="#what-s-up-with-the-comma-operator-s-precedence" id="id23">What’s up with the comma operator’s precedence?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-of-c-s-ternary-operator" id="id24">Is there an equivalent of C’s “?:” ternary operator?</a></li>
<li><a class="reference internal" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" id="id25">Is it possible to write obfuscated one-liners in Python?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#numbers-and-strings" id="id26">Numbers and strings</a><ul>
<li><a class="reference internal" href="#how-do-i-specify-hexadecimal-and-octal-integers" id="id27">How do I specify hexadecimal and octal integers?</a></li>
<li><a class="reference internal" href="#why-does-22-10-return-3" id="id28">Why does -22 // 10 return -3?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-string-to-a-number" id="id29">How do I convert a string to a number?</a></li>
<li><a class="reference internal" href="#how-do-i-convert-a-number-to-a-string" id="id30">How do I convert a number to a string?</a></li>
<li><a class="reference internal" href="#how-do-i-modify-a-string-in-place" id="id31">How do I modify a string in place?</a></li>
<li><a class="reference internal" href="#how-do-i-use-strings-to-call-functions-methods" id="id32">How do I use strings to call functions/methods?</a></li>
<li><a class="reference internal" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" id="id33">Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?</a></li>
<li><a class="reference internal" href="#is-there-a-scanf-or-sscanf-equivalent" id="id34">Is there a scanf() or sscanf() equivalent?</a></li>
<li><a class="reference internal" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" id="id35">What does ‘UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequences-tuples-lists" id="id36">Sequences (Tuples/Lists)</a><ul>
<li><a class="reference internal" href="#how-do-i-convert-between-tuples-and-lists" id="id37">How do I convert between tuples and lists?</a></li>
<li><a class="reference internal" href="#what-s-a-negative-index" id="id38">What’s a negative index?</a></li>
<li><a class="reference internal" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" id="id39">How do I iterate over a sequence in reverse order?</a></li>
<li><a class="reference internal" href="#how-do-you-remove-duplicates-from-a-list" id="id40">How do you remove duplicates from a list?</a></li>
<li><a class="reference internal" href="#how-do-you-make-an-array-in-python" id="id41">How do you make an array in Python?</a></li>
<li><a class="reference internal" href="#how-do-i-create-a-multidimensional-list" id="id42">How do I create a multidimensional list?</a></li>
<li><a class="reference internal" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" id="id43">How do I apply a method to a sequence of objects?</a></li>
<li><a class="reference internal" href="#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works" id="id44">Why does a_tuple[i] += [‘item’] raise an exception when the addition works?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#dictionaries" id="id45">Dictionaries</a><ul>
<li><a class="reference internal" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" id="id46">How can I get a dictionary to display its keys in a consistent order?</a></li>
<li><a class="reference internal" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" id="id47">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a></li>
<li><a class="reference internal" href="#how-can-i-sort-one-list-by-values-from-another-list" id="id48">How can I sort one list by values from another list?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#objects" id="id49">Objects</a><ul>
<li><a class="reference internal" href="#what-is-a-class" id="id50">What is a class?</a></li>
<li><a class="reference internal" href="#what-is-a-method" id="id51">What is a method?</a></li>
<li><a class="reference internal" href="#what-is-self" id="id52">What is self?</a></li>
<li><a class="reference internal" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" id="id53">How do I check if an object is an instance of a given class or of a subclass of it?</a></li>
<li><a class="reference internal" href="#what-is-delegation" id="id54">What is delegation?</a></li>
<li><a class="reference internal" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" id="id55">How do I call a method defined in a base class from a derived class that overrides it?</a></li>
<li><a class="reference internal" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" id="id56">How can I organize my code to make it easier to change the base class?</a></li>
<li><a class="reference internal" href="#how-do-i-create-static-class-data-and-static-class-methods" id="id57">How do I create static class data and static class methods?</a></li>
<li><a class="reference internal" href="#how-can-i-overload-constructors-or-methods-in-python" id="id58">How can I overload constructors (or methods) in Python?</a></li>
<li><a class="reference internal" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" id="id59">I try to use __spam and I get an error about _SomeClassName__spam.</a></li>
<li><a class="reference internal" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" id="id60">My class defines __del__ but it is not called when I delete the object.</a></li>
<li><a class="reference internal" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" id="id61">How do I get a list of all instances of a given class?</a></li>
<li><a class="reference internal" href="#why-does-the-result-of-id-appear-to-be-not-unique" id="id62">Why does the result of <code class="docutils literal notranslate"><span class="pre">id()</span></code> appear to be not unique?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modules" id="id63">Modules</a><ul>
<li><a class="reference internal" href="#how-do-i-create-a-pyc-file" id="id64">How do I create a .pyc file?</a></li>
<li><a class="reference internal" href="#how-do-i-find-the-current-module-name" id="id65">How do I find the current module name?</a></li>
<li><a class="reference internal" href="#how-can-i-have-modules-that-mutually-import-each-other" id="id66">How can I have modules that mutually import each other?</a></li>
<li><a class="reference internal" href="#import-x-y-z-returns-module-x-how-do-i-get-z" id="id67">__import__(‘x.y.z’) returns &lt;module ‘x’&gt;; how do I get z?</a></li>
<li><a class="reference internal" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" id="id68">When I edit an imported module and reimport it, the changes don’t show up.  Why does this happen?</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="general-questions">
<h2><a class="toc-backref" href="#id2">General Questions</a><a class="headerlink" href="#general-questions" title="Permalink to this headline">¶</a></h2>
<div class="section" id="is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc">
<h3><a class="toc-backref" href="#id3">Is there a source code level debugger with breakpoints, single-stepping, etc.?</a><a class="headerlink" href="#is-there-a-source-code-level-debugger-with-breakpoints-single-stepping-etc" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>The pdb module is a simple but adequate console-mode debugger for Python. It is
part of the standard Python library, and is <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">documented</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">Library</span>
<span class="pre">Reference</span> <span class="pre">Manual</span></code></a>. You can also write your own debugger by using the code
for pdb as an example.</p>
<p>The IDLE interactive development environment, which is part of the standard
Python distribution (normally available as Tools/scripts/idle), includes a
graphical debugger.</p>
<p>PythonWin is a Python IDE that includes a GUI debugger based on pdb.  The
Pythonwin debugger colors breakpoints and has quite a few cool features such as
debugging non-Pythonwin programs.  Pythonwin is available as part of the <a class="reference external" href="https://sourceforge.net/projects/pywin32/">Python
for Windows Extensions</a> project and
as a part of the ActivePython distribution (see
<a class="reference external" href="https://www.activestate.com/activepython">https://www.activestate.com/activepython</a>).</p>
<p><a class="reference external" href="http://boa-constructor.sourceforge.net/">Boa Constructor</a> is an IDE and GUI
builder that uses wxWidgets.  It offers visual frame creation and manipulation,
an object inspector, many views on the source like object browsers, inheritance
hierarchies, doc string generated html documentation, an advanced debugger,
integrated help, and Zope support.</p>
<p><a class="reference external" href="http://eric-ide.python-projects.org/">Eric</a> is an IDE built on PyQt
and the Scintilla editing component.</p>
<p>Pydb is a version of the standard Python debugger pdb, modified for use with DDD
(Data Display Debugger), a popular graphical debugger front end.  Pydb can be
found at <a class="reference external" href="http://bashdb.sourceforge.net/pydb/">http://bashdb.sourceforge.net/pydb/</a> and DDD can be found at
<a class="reference external" href="https://www.gnu.org/software/ddd">https://www.gnu.org/software/ddd</a>.</p>
<p>There are a number of commercial Python IDEs that include graphical debuggers.
They include:</p>
<ul class="simple">
<li>Wing IDE (<a class="reference external" href="https://wingware.com/">https://wingware.com/</a>)</li>
<li>Komodo IDE (<a class="reference external" href="https://komodoide.com/">https://komodoide.com/</a>)</li>
<li>PyCharm (<a class="reference external" href="https://www.jetbrains.com/pycharm/">https://www.jetbrains.com/pycharm/</a>)</li>
</ul>
</div>
<div class="section" id="is-there-a-tool-to-help-find-bugs-or-perform-static-analysis">
<h3><a class="toc-backref" href="#id4">Is there a tool to help find bugs or perform static analysis?</a><a class="headerlink" href="#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis" title="Permalink to this headline">¶</a></h3>
<p>Yes.</p>
<p>PyChecker is a static analysis tool that finds bugs in Python source code and
warns about code complexity and style.  You can get PyChecker from
<a class="reference external" href="http://pychecker.sourceforge.net/">http://pychecker.sourceforge.net/</a>.</p>
<p><a class="reference external" href="https://www.pylint.org/">Pylint</a> is another tool that checks
if a module satisfies a coding standard, and also makes it possible to write
plug-ins to add a custom feature.  In addition to the bug checking that
PyChecker performs, Pylint offers some additional features such as checking line
length, whether variable names are well-formed according to your coding
standard, whether declared interfaces are fully implemented, and more.
<a class="reference external" href="https://docs.pylint.org/">https://docs.pylint.org/</a> provides a full list of Pylint’s features.</p>
</div>
<div class="section" id="how-can-i-create-a-stand-alone-binary-from-a-python-script">
<h3><a class="toc-backref" href="#id5">How can I create a stand-alone binary from a Python script?</a><a class="headerlink" href="#how-can-i-create-a-stand-alone-binary-from-a-python-script" title="Permalink to this headline">¶</a></h3>
<p>You don’t need the ability to compile Python to C code if all you want is a
stand-alone program that users can download and run without having to install
the Python distribution first.  There are a number of tools that determine the
set of modules required by a program and bind these modules together with a
Python binary to produce a single executable.</p>
<p>One is to use the freeze tool, which is included in the Python source tree as
<code class="docutils literal notranslate"><span class="pre">Tools/freeze</span></code>. It converts Python byte code to C arrays; a C compiler you can
embed all your modules into a new program, which is then linked with the
standard Python modules.</p>
<p>It works by scanning your source recursively for import statements (in both
forms) and looking for the modules in the standard Python path as well as in the
source directory (for built-in modules).  It then turns the bytecode for modules
written in Python into C code (array initializers that can be turned into code
objects using the marshal module) and creates a custom-made config file that
only contains those built-in modules which are actually used in the program.  It
then compiles the generated C code and links it with the rest of the Python
interpreter to form a self-contained binary which acts exactly like your script.</p>
<p>Obviously, freeze requires a C compiler.  There are several other utilities
which don’t. One is Thomas Heller’s py2exe (Windows only) at</p>
<blockquote>
<div><a class="reference external" href="http://www.py2exe.org/">http://www.py2exe.org/</a></div></blockquote>
<p>Another tool is Anthony Tuininga’s <a class="reference external" href="http://cx-freeze.sourceforge.net/">cx_Freeze</a>.</p>
</div>
<div class="section" id="are-there-coding-standards-or-a-style-guide-for-python-programs">
<h3><a class="toc-backref" href="#id6">Are there coding standards or a style guide for Python programs?</a><a class="headerlink" href="#are-there-coding-standards-or-a-style-guide-for-python-programs" title="Permalink to this headline">¶</a></h3>
<p>Yes.  The coding style required for standard library modules is documented as
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a>.</p>
</div>
<div class="section" id="my-program-is-too-slow-how-do-i-speed-it-up">
<h3><a class="toc-backref" href="#id7">My program is too slow. How do I speed it up?</a><a class="headerlink" href="#my-program-is-too-slow-how-do-i-speed-it-up" title="Permalink to this headline">¶</a></h3>
<p>That’s a tough one, in general.  There are many tricks to speed up Python code;
consider rewriting parts in C as a last resort.</p>
<p>In some cases it’s possible to automatically translate Python to C or x86
assembly language, meaning that you don’t have to modify your code to gain
increased speed.</p>
<p><a class="reference external" href="http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/">Pyrex</a> can compile a
slightly modified version of Python code into a C extension, and can be used on
many different platforms.</p>
<p><a class="reference external" href="http://psyco.sourceforge.net">Psyco</a> is a just-in-time compiler that
translates Python code into x86 assembly language.  If you can use it, Psyco can
provide dramatic speedups for critical functions.</p>
<p>The rest of this answer will discuss various tricks for squeezing a bit more
speed out of Python code.  <em>Never</em> apply any optimization tricks unless you know
you need them, after profiling has indicated that a particular function is the
heavily executed hot spot in the code.  Optimizations almost always make the
code less clear, and you shouldn’t pay the costs of reduced clarity (increased
development time, greater likelihood of bugs) unless the resulting performance
benefit is worth it.</p>
<p>There is a page on the wiki devoted to <a class="reference external" href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips">performance tips</a>.</p>
<p>Guido van Rossum has written up an anecdote related to optimization at
<a class="reference external" href="https://www.python.org/doc/essays/list2str">https://www.python.org/doc/essays/list2str</a>.</p>
<p>One thing to notice is that function and (especially) method calls are rather
expensive; if you have designed a purely OO interface with lots of tiny
functions that don’t do much more than get or set an instance variable or call
another method, you might consider using a more direct way such as directly
accessing instance variables.  Also see the standard module <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> which
makes it possible to find out where your program is spending most of its time
(if you have some patience – the profiling itself can slow your program down by
an order of magnitude).</p>
<p>Remember that many standard optimization heuristics you may know from other
programming experience may well apply to Python.  For example it may be faster
to send output to output devices using larger writes rather than smaller ones in
order to reduce the overhead of kernel system calls.  Thus CGI scripts that
write all output in “one shot” may be faster than those that write lots of small
pieces of output.</p>
<p>Also, be sure to use Python’s core features where appropriate.  For example,
slicing allows programs to chop up lists and other sequence objects in a single
tick of the interpreter’s mainloop using highly optimized C implementations.
Thus to get the same effect as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L2</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
    <span class="n">L2</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">L1</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
</pre></div>
</div>
<p>it is much shorter and far faster to use</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L2</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">L1</span><span class="p">[:</span><span class="mi">3</span><span class="p">])</span>  <span class="c1"># &quot;list&quot; is redundant if L1 is a list.</span>
</pre></div>
</div>
<p>Note that the functionally-oriented built-in functions such as <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>,
<a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>, and friends can be a convenient accelerator for loops that
perform a single task.  For example to pair the elements of two lists
together:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">zip</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">])</span>
<span class="go">[(1, 4), (2, 5), (3, 6)]</span>
</pre></div>
</div>
<p>or to compute a number of sines:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="go">[0.841470984808, 0.909297426826, 0.14112000806, -0.756802495308]</span>
</pre></div>
</div>
<p>The operation completes very quickly in such cases.</p>
<p>Other examples include the <code class="docutils literal notranslate"><span class="pre">join()</span></code> and <code class="docutils literal notranslate"><span class="pre">split()</span></code> <a class="reference internal" href="../library/stdtypes.html#string-methods"><span class="std std-ref">methods
of string objects</span></a>.
For example if s1..s7 are large (10K+) strings then
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;.join([s1,s2,s3,s4,s5,s6,s7])</span></code> may be far faster than the more obvious
<code class="docutils literal notranslate"><span class="pre">s1+s2+s3+s4+s5+s6+s7</span></code>, since the “summation” will compute many
subexpressions, whereas <code class="docutils literal notranslate"><span class="pre">join()</span></code> does all the copying in one pass.  For
manipulating strings, use the <code class="docutils literal notranslate"><span class="pre">replace()</span></code> and the <code class="docutils literal notranslate"><span class="pre">format()</span></code> <a class="reference internal" href="../library/stdtypes.html#string-methods"><span class="std std-ref">methods
on string objects</span></a>.  Use regular expressions only when you’re
not dealing with constant string patterns.  You may still use <a class="reference internal" href="../library/stdtypes.html#string-formatting"><span class="std std-ref">the old %
operations</span></a> <code class="docutils literal notranslate"><span class="pre">string</span> <span class="pre">%</span> <span class="pre">tuple</span></code> and <code class="docutils literal notranslate"><span class="pre">string</span> <span class="pre">%</span> <span class="pre">dictionary</span></code>.</p>
<p>Be sure to use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> built-in method to do sorting, and see the
<a class="reference external" href="https://wiki.python.org/moin/HowTo/Sorting">sorting mini-HOWTO</a> for examples
of moderately advanced usage.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> beats other techniques for
sorting in all but the most extreme circumstances.</p>
<p>Another common trick is to “push loops into functions or methods.”  For example
suppose you have a program that runs slowly and you use the profiler to
determine that a Python function <code class="docutils literal notranslate"><span class="pre">ff()</span></code> is being called lots of times.  If you
notice that <code class="docutils literal notranslate"><span class="pre">ff()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">ff</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="o">...</span> <span class="c1"># do something with x computing result...</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>tends to be called in loops like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">list</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">ff</span><span class="p">,</span> <span class="n">oldlist</span><span class="p">)</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">sequence</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">ff</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
    <span class="o">...</span> <span class="c1"># do something with value...</span>
</pre></div>
</div>
<p>then you can often eliminate function call overhead by rewriting <code class="docutils literal notranslate"><span class="pre">ff()</span></code> to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">ffseq</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
    <span class="n">resultseq</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq</span><span class="p">:</span>
        <span class="o">...</span> <span class="c1"># do something with x computing result...</span>
        <span class="n">resultseq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">resultseq</span>
</pre></div>
</div>
<p>and rewrite the two examples to <code class="docutils literal notranslate"><span class="pre">list</span> <span class="pre">=</span> <span class="pre">ffseq(oldlist)</span></code> and to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">ffseq</span><span class="p">(</span><span class="n">sequence</span><span class="p">):</span>
    <span class="o">...</span> <span class="c1"># do something with value...</span>
</pre></div>
</div>
<p>Single calls to <code class="docutils literal notranslate"><span class="pre">ff(x)</span></code> translate to <code class="docutils literal notranslate"><span class="pre">ffseq([x])[0]</span></code> with little penalty.
Of course this technique is not always appropriate and there are other variants
which you can figure out.</p>
<p>You can gain some performance by explicitly storing the results of a function or
method lookup into a local variable.  A loop like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">token</span><span class="p">:</span>
    <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>resolves <code class="docutils literal notranslate"><span class="pre">dict.get</span></code> every iteration.  If the method isn’t going to change, a
slightly faster implementation is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">dict_get</span> <span class="o">=</span> <span class="nb">dict</span><span class="o">.</span><span class="n">get</span>  <span class="c1"># look up the method once</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">token</span><span class="p">:</span>
    <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">dict_get</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Default arguments can be used to determine values once, at compile time instead
of at run time.  This can only be done for functions or objects which will not
be changed during program execution, such as replacing</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">degree_sin</span><span class="p">(</span><span class="n">deg</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">(</span><span class="n">deg</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">/</span> <span class="mf">180.0</span><span class="p">)</span>
</pre></div>
</div>
<p>with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">degree_sin</span><span class="p">(</span><span class="n">deg</span><span class="p">,</span> <span class="n">factor</span><span class="o">=</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="o">/</span><span class="mf">180.0</span><span class="p">,</span> <span class="n">sin</span><span class="o">=</span><span class="n">math</span><span class="o">.</span><span class="n">sin</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">sin</span><span class="p">(</span><span class="n">deg</span> <span class="o">*</span> <span class="n">factor</span><span class="p">)</span>
</pre></div>
</div>
<p>Because this trick uses default arguments for terms which should not be changed,
it should only be used when you are not concerned with presenting a possibly
confusing API to your users.</p>
</div>
</div>
<div class="section" id="core-language">
<h2><a class="toc-backref" href="#id8">Core Language</a><a class="headerlink" href="#core-language" title="Permalink to this headline">¶</a></h2>
<div class="section" id="why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value">
<h3><a class="toc-backref" href="#id9">Why am I getting an UnboundLocalError when the variable has a value?</a><a class="headerlink" href="#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value" title="Permalink to this headline">¶</a></h3>
<p>It can be a surprise to get the UnboundLocalError in previously working
code when it is modified by adding an assignment statement somewhere in
the body of a function.</p>
<p>This code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bar</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>works, but this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>results in an UnboundLocalError:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">UnboundLocalError</span>: <span class="n">local variable &#39;x&#39; referenced before assignment</span>
</pre></div>
</div>
<p>This is because when you make an assignment to a variable in a scope, that
variable becomes local to that scope and shadows any similarly named variable
in the outer scope.  Since the last statement in foo assigns a new value to
<code class="docutils literal notranslate"><span class="pre">x</span></code>, the compiler recognizes it as a local variable.  Consequently when the
earlier <code class="docutils literal notranslate"><span class="pre">print</span> <span class="pre">x</span></code> attempts to print the uninitialized local variable and
an error results.</p>
<p>In the example above you can access the outer scope variable by declaring it
global:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foobar</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">global</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foobar</span><span class="p">()</span>
<span class="go">10</span>
</pre></div>
</div>
<p>This explicit declaration is required in order to remind you that (unlike the
superficially analogous situation with class and instance variables) you are
actually modifying the value of the variable in the outer scope:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">x</span>
<span class="go">11</span>
</pre></div>
</div>
</div>
<div class="section" id="what-are-the-rules-for-local-and-global-variables-in-python">
<h3><a class="toc-backref" href="#id10">What are the rules for local and global variables in Python?</a><a class="headerlink" href="#what-are-the-rules-for-local-and-global-variables-in-python" title="Permalink to this headline">¶</a></h3>
<p>In Python, variables that are only referenced inside a function are implicitly
global.  If a variable is assigned a value anywhere within the function’s body,
it’s assumed to be a local unless explicitly declared as global.</p>
<p>Though a bit surprising at first, a moment’s consideration explains this.  On
one hand, requiring <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> for assigned variables provides a bar
against unintended side-effects.  On the other hand, if <code class="docutils literal notranslate"><span class="pre">global</span></code> was required
for all global references, you’d be using <code class="docutils literal notranslate"><span class="pre">global</span></code> all the time.  You’d have
to declare as global every reference to a built-in function or to a component of
an imported module.  This clutter would defeat the usefulness of the <code class="docutils literal notranslate"><span class="pre">global</span></code>
declaration for identifying side-effects.</p>
</div>
<div class="section" id="why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result">
<h3><a class="toc-backref" href="#id11">Why do lambdas defined in a loop with different values all return the same result?</a><a class="headerlink" href="#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result" title="Permalink to this headline">¶</a></h3>
<p>Assume you use a for loop to define a few different lambdas (or even plain
functions), e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>This gives you a list that contains 5 lambdas that calculate <code class="docutils literal notranslate"><span class="pre">x**2</span></code>.  You
might expect that, when called, they would return, respectively, <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">1</span></code>,
<code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">9</span></code>, and <code class="docutils literal notranslate"><span class="pre">16</span></code>.  However, when you actually try you will see that
they all return <code class="docutils literal notranslate"><span class="pre">16</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
<span class="go">16</span>
</pre></div>
</div>
<p>This happens because <code class="docutils literal notranslate"><span class="pre">x</span></code> is not local to the lambdas, but is defined in
the outer scope, and it is accessed when the lambda is called — not when it
is defined.  At the end of the loop, the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> is <code class="docutils literal notranslate"><span class="pre">4</span></code>, so all the
functions now return <code class="docutils literal notranslate"><span class="pre">4**2</span></code>, i.e. <code class="docutils literal notranslate"><span class="pre">16</span></code>.  You can also verify this by
changing the value of <code class="docutils literal notranslate"><span class="pre">x</span></code> and see how the results of the lambdas change:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">64</span>
</pre></div>
</div>
<p>In order to avoid this, you need to save the values in variables local to the
lambdas, so that they don’t rely on the value of the global <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="k">lambda</span> <span class="n">n</span><span class="o">=</span><span class="n">x</span><span class="p">:</span> <span class="n">n</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>Here, <code class="docutils literal notranslate"><span class="pre">n=x</span></code> creates a new variable <code class="docutils literal notranslate"><span class="pre">n</span></code> local to the lambda and computed
when the lambda is defined so that it has the same value that <code class="docutils literal notranslate"><span class="pre">x</span></code> had at
that point in the loop.  This means that the value of <code class="docutils literal notranslate"><span class="pre">n</span></code> will be <code class="docutils literal notranslate"><span class="pre">0</span></code>
in the first lambda, <code class="docutils literal notranslate"><span class="pre">1</span></code> in the second, <code class="docutils literal notranslate"><span class="pre">2</span></code> in the third, and so on.
Therefore each lambda will now return the correct result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">2</span><span class="p">]()</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">4</span><span class="p">]()</span>
<span class="go">16</span>
</pre></div>
</div>
<p>Note that this behaviour is not peculiar to lambdas, but applies to regular
functions too.</p>
</div>
<div class="section" id="how-do-i-share-global-variables-across-modules">
<h3><a class="toc-backref" href="#id12">How do I share global variables across modules?</a><a class="headerlink" href="#how-do-i-share-global-variables-across-modules" title="Permalink to this headline">¶</a></h3>
<p>The canonical way to share information across modules within a single program is
to create a special module (often called config or cfg).  Just import the config
module in all modules of your application; the module then becomes available as
a global name.  Because there is only one instance of each module, any changes
made to the module object get reflected everywhere.  For example:</p>
<p>config.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>   <span class="c1"># Default value of the &#39;x&#39; configuration setting</span>
</pre></div>
</div>
<p>mod.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
<span class="n">config</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>main.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">config</span>
<span class="kn">import</span> <span class="nn">mod</span>
<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">x</span>
</pre></div>
</div>
<p>Note that using a module is also the basis for implementing the Singleton design
pattern, for the same reason.</p>
</div>
<div class="section" id="what-are-the-best-practices-for-using-import-in-a-module">
<h3><a class="toc-backref" href="#id13">What are the “best practices” for using import in a module?</a><a class="headerlink" href="#what-are-the-best-practices-for-using-import-in-a-module" title="Permalink to this headline">¶</a></h3>
<p>In general, don’t use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">modulename</span> <span class="pre">import</span> <span class="pre">*</span></code>.  Doing so clutters the
importer’s namespace, and makes it much harder for linters to detect undefined
names.</p>
<p>Import modules at the top of a file.  Doing so makes it clear what other modules
your code requires and avoids questions of whether the module name is in scope.
Using one import per line makes it easy to add and delete module imports, but
using multiple imports per line uses less screen space.</p>
<p>It’s good practice if you import modules in the following order:</p>
<ol class="arabic simple">
<li>standard library modules – e.g. <code class="docutils literal notranslate"><span class="pre">sys</span></code>, <code class="docutils literal notranslate"><span class="pre">os</span></code>, <code class="docutils literal notranslate"><span class="pre">getopt</span></code>, <code class="docutils literal notranslate"><span class="pre">re</span></code></li>
<li>third-party library modules (anything installed in Python’s site-packages
directory) – e.g. mx.DateTime, ZODB, PIL.Image, etc.</li>
<li>locally-developed modules</li>
</ol>
<p>Only use explicit relative package imports.  If you’re writing code that’s in
the <code class="docutils literal notranslate"><span class="pre">package.sub.m1</span></code> module and want to import <code class="docutils literal notranslate"><span class="pre">package.sub.m2</span></code>, do not just
write <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">m2</span></code>, even though it’s legal.  Write <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package.sub</span> <span class="pre">import</span>
<span class="pre">m2</span></code> or <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">.</span> <span class="pre">import</span> <span class="pre">m2</span></code> instead.</p>
<p>It is sometimes necessary to move imports to a function or class to avoid
problems with circular imports.  Gordon McMillan says:</p>
<blockquote>
<div>Circular imports are fine where both modules use the “import &lt;module&gt;” form
of import.  They fail when the 2nd module wants to grab a name out of the
first (“from module import name”) and the import is at the top level.  That’s
because names in the 1st are not yet available, because the first module is
busy importing the 2nd.</div></blockquote>
<p>In this case, if the second module is only used in one function, then the import
can easily be moved into that function.  By the time the import is called, the
first module will have finished initializing, and the second module can do its
import.</p>
<p>It may also be necessary to move imports out of the top level of code if some of
the modules are platform-specific.  In that case, it may not even be possible to
import all of the modules at the top of the file.  In this case, importing the
correct modules in the corresponding platform-specific code is a good option.</p>
<p>Only move imports into a local scope, such as inside a function definition, if
it’s necessary to solve a problem such as avoiding a circular import or are
trying to reduce the initialization time of a module.  This technique is
especially helpful if many of the imports are unnecessary depending on how the
program executes.  You may also want to move imports into a function if the
modules are only ever used in that function.  Note that loading a module the
first time may be expensive because of the one time initialization of the
module, but loading a module multiple times is virtually free, costing only a
couple of dictionary lookups.  Even if the module name has gone out of scope,
the module is probably available in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>.</p>
</div>
<div class="section" id="why-are-default-values-shared-between-objects">
<h3><a class="toc-backref" href="#id14">Why are default values shared between objects?</a><a class="headerlink" href="#why-are-default-values-shared-between-objects" title="Permalink to this headline">¶</a></h3>
<p>This type of bug commonly bites neophyte programmers.  Consider this function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="p">{}):</span>  <span class="c1"># Danger: shared reference to one dict for all calls</span>
    <span class="o">...</span> <span class="n">compute</span> <span class="n">something</span> <span class="o">...</span>
    <span class="n">mydict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
    <span class="k">return</span> <span class="n">mydict</span>
</pre></div>
</div>
<p>The first time you call this function, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains a single item.  The
second time, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> contains two items because when <code class="docutils literal notranslate"><span class="pre">foo()</span></code> begins
executing, <code class="docutils literal notranslate"><span class="pre">mydict</span></code> starts out with an item already in it.</p>
<p>It is often expected that a function call creates new objects for default
values. This is not what happens. Default values are created exactly once, when
the function is defined.  If that object is changed, like the dictionary in this
example, subsequent calls to the function will refer to this changed object.</p>
<p>By definition, immutable objects such as numbers, strings, tuples, and <code class="docutils literal notranslate"><span class="pre">None</span></code>,
are safe from change. Changes to mutable objects such as dictionaries, lists,
and class instances can lead to confusion.</p>
<p>Because of this feature, it is good programming practice to not use mutable
objects as default values.  Instead, use <code class="docutils literal notranslate"><span class="pre">None</span></code> as the default value and
inside the function, check if the parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code> and create a new
list/dictionary/whatever if it is.  For example, don’t write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="p">{}):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>but:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">mydict</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">mydict</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">mydict</span> <span class="o">=</span> <span class="p">{}</span>  <span class="c1"># create a new dict for local namespace</span>
</pre></div>
</div>
<p>This feature can be useful.  When you have a function that’s time-consuming to
compute, a common technique is to cache the parameters and the resulting value
of each call to the function, and return the cached value if the same value is
requested again.  This is called “memoizing”, and can be implemented like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Callers will never provide a third parameter for this function.</span>
<span class="k">def</span> <span class="nf">expensive</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">_cache</span><span class="o">=</span><span class="p">{}):</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)</span> <span class="ow">in</span> <span class="n">_cache</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span>

    <span class="c1"># Calculate the value</span>
    <span class="n">result</span> <span class="o">=</span> <span class="o">...</span> <span class="n">expensive</span> <span class="n">computation</span> <span class="o">...</span>
    <span class="n">_cache</span><span class="p">[(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">)]</span> <span class="o">=</span> <span class="n">result</span>           <span class="c1"># Store result in the cache</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>You could use a global variable containing a dictionary instead of the default
value; it’s a matter of taste.</p>
</div>
<div class="section" id="how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another">
<h3><a class="toc-backref" href="#id15">How can I pass optional or keyword parameters from one function to another?</a><a class="headerlink" href="#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another" title="Permalink to this headline">¶</a></h3>
<p>Collect the arguments using the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> specifiers in the function’s
parameter list; this gives you the positional arguments as a tuple and the
keyword arguments as a dictionary.  You can then pass these arguments when
calling another function by using <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;width&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;14.3c&#39;</span>
    <span class="o">...</span>
    <span class="n">g</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>In the unlikely case that you care about Python versions older than 2.0, use
<a class="reference internal" href="../library/functions.html#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="o">...</span>
    <span class="n">kwargs</span><span class="p">[</span><span class="s1">&#39;width&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;14.3c&#39;</span>
    <span class="o">...</span>
    <span class="n">apply</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="p">(</span><span class="n">x</span><span class="p">,)</span><span class="o">+</span><span class="n">args</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="what-is-the-difference-between-arguments-and-parameters">
<span id="faq-argument-vs-parameter"></span><span id="index-1"></span><h3><a class="toc-backref" href="#id16">What is the difference between arguments and parameters?</a><a class="headerlink" href="#what-is-the-difference-between-arguments-and-parameters" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">Parameters</span></a> are defined by the names that appear in a
function definition, whereas <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a> are the values
actually passed to a function when calling it.  Parameters define what types of
arguments a function can accept.  For example, given the function definition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p><em>foo</em>, <em>bar</em> and <em>kwargs</em> are parameters of <code class="docutils literal notranslate"><span class="pre">func</span></code>.  However, when calling
<code class="docutils literal notranslate"><span class="pre">func</span></code>, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">func</span><span class="p">(</span><span class="mi">42</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="mi">314</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">somevar</span><span class="p">)</span>
</pre></div>
</div>
<p>the values <code class="docutils literal notranslate"><span class="pre">42</span></code>, <code class="docutils literal notranslate"><span class="pre">314</span></code>, and <code class="docutils literal notranslate"><span class="pre">somevar</span></code> are arguments.</p>
</div>
<div class="section" id="why-did-changing-list-y-also-change-list-x">
<h3><a class="toc-backref" href="#id17">Why did changing list ‘y’ also change list ‘x’?</a><a class="headerlink" href="#why-did-changing-list-y-also-change-list-x" title="Permalink to this headline">¶</a></h3>
<p>If you wrote code like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span>
<span class="go">[10]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">[10]</span>
</pre></div>
</div>
<p>you might be wondering why appending an element to <code class="docutils literal notranslate"><span class="pre">y</span></code> changed <code class="docutils literal notranslate"><span class="pre">x</span></code> too.</p>
<p>There are two factors that produce this result:</p>
<ol class="arabic simple">
<li>Variables are simply names that refer to objects.  Doing <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">x</span></code> doesn’t
create a copy of the list – it creates a new variable <code class="docutils literal notranslate"><span class="pre">y</span></code> that refers to
the same object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to.  This means that there is only one object
(the list), and both <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> refer to it.</li>
<li>Lists are <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>, which means that you can change their content.</li>
</ol>
<p>After the call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, the content of the mutable object has
changed from <code class="docutils literal notranslate"><span class="pre">[]</span></code> to <code class="docutils literal notranslate"><span class="pre">[10]</span></code>.  Since both the variables refer to the same
object, using either name accesses the modified value <code class="docutils literal notranslate"><span class="pre">[10]</span></code>.</p>
<p>If we instead assign an immutable object to <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">5</span>  <span class="c1"># ints are immutable</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>  <span class="c1"># 5 can&#39;t be mutated, we are creating a new object here</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span>
<span class="go">5</span>
</pre></div>
</div>
<p>we can see that in this case <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are not equal anymore.  This is
because integers are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, and when we do <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span> <span class="pre">1</span></code> we are not
mutating the int <code class="docutils literal notranslate"><span class="pre">5</span></code> by incrementing its value; instead, we are creating a
new object (the int <code class="docutils literal notranslate"><span class="pre">6</span></code>) and assigning it to <code class="docutils literal notranslate"><span class="pre">x</span></code> (that is, changing which
object <code class="docutils literal notranslate"><span class="pre">x</span></code> refers to).  After this assignment we have two objects (the ints
<code class="docutils literal notranslate"><span class="pre">6</span></code> and <code class="docutils literal notranslate"><span class="pre">5</span></code>) and two variables that refer to them (<code class="docutils literal notranslate"><span class="pre">x</span></code> now refers to
<code class="docutils literal notranslate"><span class="pre">6</span></code> but <code class="docutils literal notranslate"><span class="pre">y</span></code> still refers to <code class="docutils literal notranslate"><span class="pre">5</span></code>).</p>
<p>Some operations (for example <code class="docutils literal notranslate"><span class="pre">y.append(10)</span></code> and <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code>) mutate the
object, whereas superficially similar operations (for example <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">=</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">[10]</span></code>
and <code class="docutils literal notranslate"><span class="pre">sorted(y)</span></code>) create a new object.  In general in Python (and in all cases
in the standard library) a method that mutates an object will return <code class="docutils literal notranslate"><span class="pre">None</span></code>
to help avoid getting the two types of operations confused.  So if you
mistakenly write <code class="docutils literal notranslate"><span class="pre">y.sort()</span></code> thinking it will give you a sorted copy of <code class="docutils literal notranslate"><span class="pre">y</span></code>,
you’ll instead end up with <code class="docutils literal notranslate"><span class="pre">None</span></code>, which will likely cause your program to
generate an easily diagnosed error.</p>
<p>However, there is one class of operations where the same operation sometimes
has different behaviors with different types:  the augmented assignment
operators.  For example, <code class="docutils literal notranslate"><span class="pre">+=</span></code> mutates lists but not tuples or ints (<code class="docutils literal notranslate"><span class="pre">a_list</span>
<span class="pre">+=</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a_list.extend([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></code> and mutates
<code class="docutils literal notranslate"><span class="pre">a_list</span></code>, whereas <code class="docutils literal notranslate"><span class="pre">some_tuple</span> <span class="pre">+=</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code> and <code class="docutils literal notranslate"><span class="pre">some_int</span> <span class="pre">+=</span> <span class="pre">1</span></code> create
new objects).</p>
<p>In other words:</p>
<ul class="simple">
<li>If we have a mutable object (<code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>,
etc.), we can use some specific operations to mutate it and all the variables
that refer to it will see the change.</li>
<li>If we have an immutable object (<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>,
etc.), all the variables that refer to it will always see the same value,
but operations that transform that value into a new value always return a new
object.</li>
</ul>
<p>If you want to know if two variables refer to the same object or not, you can
use the <a class="reference internal" href="../reference/expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator, or the built-in function <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>.</p>
</div>
<div class="section" id="how-do-i-write-a-function-with-output-parameters-call-by-reference">
<h3><a class="toc-backref" href="#id18">How do I write a function with output parameters (call by reference)?</a><a class="headerlink" href="#how-do-i-write-a-function-with-output-parameters-call-by-reference" title="Permalink to this headline">¶</a></h3>
<p>Remember that arguments are passed by assignment in Python.  Since assignment
just creates references to objects, there’s no alias between an argument name in
the caller and callee, and so no call-by-reference per se.  You can achieve the
desired effect in a number of ways.</p>
<ol class="arabic">
<li><p class="first">By returning a tuple of the results:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func2</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span>        <span class="c1"># a and b are local names</span>
    <span class="n">b</span> <span class="o">=</span> <span class="n">b</span> <span class="o">+</span> <span class="mi">1</span>              <span class="c1"># assigned to new objects</span>
    <span class="k">return</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>            <span class="c1"># return new values</span>

<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">func2</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>                 <span class="c1"># output: new-value 100</span>
</pre></div>
</div>
<p>This is almost always the clearest solution.</p>
</li>
<li><p class="first">By using global variables.  This isn’t thread-safe, and is not recommended.</p>
</li>
<li><p class="first">By passing a mutable (changeable in-place) object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func1</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
    <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span>     <span class="c1"># &#39;a&#39; references a mutable list</span>
    <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>        <span class="c1"># changes a shared object</span>

<span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="mi">99</span><span class="p">]</span>
<span class="n">func1</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>     <span class="c1"># output: new-value 100</span>
</pre></div>
</div>
</li>
<li><p class="first">By passing in a dictionary that gets mutated:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func3</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
    <span class="n">args</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span>     <span class="c1"># args is a mutable dictionary</span>
    <span class="n">args</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>   <span class="c1"># change it in-place</span>

<span class="n">args</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="mi">99</span><span class="p">}</span>
<span class="n">func3</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span>
</pre></div>
</div>
</li>
<li><p class="first">Or bundle up values in a class instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">callByRef</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">**</span><span class="n">args</span><span class="p">):</span>
        <span class="k">for</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="ow">in</span> <span class="n">args</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">func4</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
    <span class="n">args</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;new-value&#39;</span>        <span class="c1"># args is a mutable callByRef</span>
    <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span> <span class="o">+</span> <span class="mi">1</span>         <span class="c1"># change object in-place</span>

<span class="n">args</span> <span class="o">=</span> <span class="n">callByRef</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="s1">&#39;old-value&#39;</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">99</span><span class="p">)</span>
<span class="n">func4</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">b</span>
</pre></div>
</div>
<p>There’s almost never a good reason to get this complicated.</p>
</li>
</ol>
<p>Your best choice is to return a tuple containing the multiple results.</p>
</div>
<div class="section" id="how-do-you-make-a-higher-order-function-in-python">
<h3><a class="toc-backref" href="#id19">How do you make a higher order function in Python?</a><a class="headerlink" href="#how-do-you-make-a-higher-order-function-in-python" title="Permalink to this headline">¶</a></h3>
<p>You have two choices: you can use nested scopes or you can use callable objects.
For example, suppose you wanted to define <code class="docutils literal notranslate"><span class="pre">linear(a,b)</span></code> which returns a
function <code class="docutils literal notranslate"><span class="pre">f(x)</span></code> that computes the value <code class="docutils literal notranslate"><span class="pre">a*x+b</span></code>.  Using nested scopes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">linear</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">result</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="n">b</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Or using a callable object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">linear</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="n">x</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span>
</pre></div>
</div>
<p>In both cases,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">taxes</span> <span class="o">=</span> <span class="n">linear</span><span class="p">(</span><span class="mf">0.3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>gives a callable object where <code class="docutils literal notranslate"><span class="pre">taxes(10e6)</span> <span class="pre">==</span> <span class="pre">0.3</span> <span class="pre">*</span> <span class="pre">10e6</span> <span class="pre">+</span> <span class="pre">2</span></code>.</p>
<p>The callable object approach has the disadvantage that it is a bit slower and
results in slightly longer code.  However, note that a collection of callables
can share their signature via inheritance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">exponential</span><span class="p">(</span><span class="n">linear</span><span class="p">):</span>
    <span class="c1"># __init__ inherited</span>
    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">*</span> <span class="p">(</span><span class="n">x</span> <span class="o">**</span> <span class="bp">self</span><span class="o">.</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>Object can encapsulate state for several methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">counter</span><span class="p">:</span>

    <span class="n">value</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">def</span> <span class="nf">set</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">x</span>

    <span class="k">def</span> <span class="nf">up</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">down</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">-</span> <span class="mi">1</span>

<span class="n">count</span> <span class="o">=</span> <span class="n">counter</span><span class="p">()</span>
<span class="n">inc</span><span class="p">,</span> <span class="n">dec</span><span class="p">,</span> <span class="n">reset</span> <span class="o">=</span> <span class="n">count</span><span class="o">.</span><span class="n">up</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">down</span><span class="p">,</span> <span class="n">count</span><span class="o">.</span><span class="n">set</span>
</pre></div>
</div>
<p>Here <code class="docutils literal notranslate"><span class="pre">inc()</span></code>, <code class="docutils literal notranslate"><span class="pre">dec()</span></code> and <code class="docutils literal notranslate"><span class="pre">reset()</span></code> act like functions which share the
same counting variable.</p>
</div>
<div class="section" id="how-do-i-copy-an-object-in-python">
<h3><a class="toc-backref" href="#id20">How do I copy an object in Python?</a><a class="headerlink" href="#how-do-i-copy-an-object-in-python" title="Permalink to this headline">¶</a></h3>
<p>In general, try <a class="reference internal" href="../library/copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> or <a class="reference internal" href="../library/copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.deepcopy()</span></code></a> for the general case.
Not all objects can be copied, but most can.</p>
<p>Some objects can be copied more easily.  Dictionaries have a <a class="reference internal" href="../library/stdtypes.html#dict.copy" title="dict.copy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">newdict</span> <span class="o">=</span> <span class="n">olddict</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
</pre></div>
</div>
<p>Sequences can be copied by slicing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">new_l</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:]</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-find-the-methods-or-attributes-of-an-object">
<h3><a class="toc-backref" href="#id21">How can I find the methods or attributes of an object?</a><a class="headerlink" href="#how-can-i-find-the-methods-or-attributes-of-an-object" title="Permalink to this headline">¶</a></h3>
<p>For an instance x of a user-defined class, <code class="docutils literal notranslate"><span class="pre">dir(x)</span></code> returns an alphabetized
list of the names containing the instance attributes and methods and attributes
defined by its class.</p>
</div>
<div class="section" id="how-can-my-code-discover-the-name-of-an-object">
<h3><a class="toc-backref" href="#id22">How can my code discover the name of an object?</a><a class="headerlink" href="#how-can-my-code-discover-the-name-of-an-object" title="Permalink to this headline">¶</a></h3>
<p>Generally speaking, it can’t, because objects don’t really have names.
Essentially, assignment always binds a name to a value; The same is true of
<code class="docutils literal notranslate"><span class="pre">def</span></code> and <code class="docutils literal notranslate"><span class="pre">class</span></code> statements, but in that case the value is a
callable. Consider the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">B</span> <span class="o">=</span> <span class="n">A</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">B</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">b</span>
<span class="go">&lt;__main__.A instance at 0x16D07CC&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">a</span>
<span class="go">&lt;__main__.A instance at 0x16D07CC&gt;</span>
</pre></div>
</div>
<p>Arguably the class has a name: even though it is bound to two names and invoked
through the name B the created instance is still reported as an instance of
class A.  However, it is impossible to say whether the instance’s name is a or
b, since both names are bound to the same value.</p>
<p>Generally speaking it should not be necessary for your code to “know the names”
of particular values. Unless you are deliberately writing introspective
programs, this is usually an indication that a change of approach might be
beneficial.</p>
<p>In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer to
this question:</p>
<blockquote>
<div><p>The same way as you get the name of that cat you found on your porch: the cat
(object) itself cannot tell you its name, and it doesn’t really care – so
the only way to find out what it’s called is to ask all your neighbours
(namespaces) if it’s their cat (object)…</p>
<p>….and don’t be surprised if you’ll find that it’s known by many names, or
no name at all!</p>
</div></blockquote>
</div>
<div class="section" id="what-s-up-with-the-comma-operator-s-precedence">
<h3><a class="toc-backref" href="#id23">What’s up with the comma operator’s precedence?</a><a class="headerlink" href="#what-s-up-with-the-comma-operator-s-precedence" title="Permalink to this headline">¶</a></h3>
<p>Comma is not an operator in Python.  Consider this session:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span>
<span class="go">(False, &#39;a&#39;)</span>
</pre></div>
</div>
<p>Since the comma is not an operator, but a separator between expressions the
above is evaluated as if you had entered:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="s2">&quot;b&quot;</span><span class="p">),</span> <span class="s2">&quot;a&quot;</span>
</pre></div>
</div>
<p>not:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;a&quot;</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The same is true of the various assignment operators (<code class="docutils literal notranslate"><span class="pre">=</span></code>, <code class="docutils literal notranslate"><span class="pre">+=</span></code> etc).  They
are not truly operators but syntactic delimiters in assignment statements.</p>
</div>
<div class="section" id="is-there-an-equivalent-of-c-s-ternary-operator">
<h3><a class="toc-backref" href="#id24">Is there an equivalent of C’s “?:” ternary operator?</a><a class="headerlink" href="#is-there-an-equivalent-of-c-s-ternary-operator" title="Permalink to this headline">¶</a></h3>
<p>Yes, this feature was added in Python 2.5. The syntax would be as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">on_true</span><span class="p">]</span> <span class="k">if</span> <span class="p">[</span><span class="n">expression</span><span class="p">]</span> <span class="k">else</span> <span class="p">[</span><span class="n">on_false</span><span class="p">]</span>

<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">25</span>

<span class="n">small</span> <span class="o">=</span> <span class="n">x</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="k">else</span> <span class="n">y</span>
</pre></div>
</div>
<p>For versions previous to 2.5 the answer would be ‘No’.</p>
</div>
<div class="section" id="is-it-possible-to-write-obfuscated-one-liners-in-python">
<h3><a class="toc-backref" href="#id25">Is it possible to write obfuscated one-liners in Python?</a><a class="headerlink" href="#is-it-possible-to-write-obfuscated-one-liners-in-python" title="Permalink to this headline">¶</a></h3>
<p>Yes.  Usually this is done by nesting <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> within
<a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a>.  See the following three examples, due to Ulf Bartelt:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Primes &lt; 1000</span>
<span class="nb">print</span> <span class="nb">filter</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">*</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">!=</span><span class="mi">0</span><span class="p">,</span>
<span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="o">=</span><span class="n">y</span><span class="p">:</span><span class="n">y</span><span class="o">%</span><span class="n">x</span><span class="p">,</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="nb">int</span><span class="p">(</span><span class="nb">pow</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="mf">0.5</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))),</span><span class="mi">1</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1000</span><span class="p">)))</span>

<span class="c1"># First 10 Fibonacci numbers</span>
<span class="nb">print</span> <span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">)</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span><span class="n">f</span><span class="p">))</span> <span class="k">if</span> <span class="n">x</span><span class="o">&gt;</span><span class="mi">1</span> <span class="k">else</span> <span class="mi">1</span><span class="p">:</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">f</span><span class="p">),</span>
<span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>

<span class="c1"># Mandelbrot set</span>
<span class="nb">print</span> <span class="p">(</span><span class="k">lambda</span> <span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="p">,</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="p">,</span><span class="n">IM</span><span class="p">,</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">,</span>
<span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">,</span><span class="n">L</span><span class="o">=</span><span class="k">lambda</span> <span class="n">yc</span><span class="p">,</span><span class="n">Iu</span><span class="o">=</span><span class="n">Iu</span><span class="p">,</span><span class="n">Io</span><span class="o">=</span><span class="n">Io</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span><span class="n">i</span><span class="o">=</span><span class="n">IM</span><span class="p">,</span>
<span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">Sy</span><span class="o">=</span><span class="n">Sy</span><span class="p">:</span><span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span><span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">xc</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">yc</span><span class="o">=</span><span class="n">yc</span><span class="p">,</span><span class="n">Ru</span><span class="o">=</span><span class="n">Ru</span><span class="p">,</span><span class="n">Ro</span><span class="o">=</span><span class="n">Ro</span><span class="p">,</span>
<span class="n">i</span><span class="o">=</span><span class="n">i</span><span class="p">,</span><span class="n">Sx</span><span class="o">=</span><span class="n">Sx</span><span class="p">,</span><span class="n">F</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="o">=</span><span class="k">lambda</span> <span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">:(</span><span class="n">k</span><span class="o">&lt;=</span><span class="mi">0</span><span class="p">)</span><span class="ow">or</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span>
<span class="o">&gt;=</span><span class="mf">4.0</span><span class="p">)</span> <span class="ow">or</span> <span class="mi">1</span><span class="o">+</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">-</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">xc</span><span class="p">,</span><span class="mf">2.0</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">y</span><span class="o">+</span><span class="n">yc</span><span class="p">,</span><span class="n">k</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="n">f</span><span class="p">(</span><span class="n">xc</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="n">f</span><span class="p">):</span><span class="nb">chr</span><span class="p">(</span>
<span class="mi">64</span><span class="o">+</span><span class="n">F</span><span class="p">(</span><span class="n">Ru</span><span class="o">+</span><span class="n">x</span><span class="o">*</span><span class="p">(</span><span class="n">Ro</span><span class="o">-</span><span class="n">Ru</span><span class="p">)</span><span class="o">/</span><span class="n">Sx</span><span class="p">,</span><span class="n">yc</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="n">i</span><span class="p">)),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sx</span><span class="p">))):</span><span class="n">L</span><span class="p">(</span><span class="n">Iu</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="p">(</span><span class="n">Io</span><span class="o">-</span><span class="n">Iu</span><span class="p">)</span><span class="o">/</span><span class="n">Sy</span><span class="p">),</span><span class="nb">range</span><span class="p">(</span><span class="n">Sy</span>
<span class="p">))))(</span><span class="o">-</span><span class="mf">2.1</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.2</span><span class="p">,</span> <span class="mf">1.2</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">24</span><span class="p">)</span>
<span class="c1">#    \___ ___/  \___ ___/  |   |   |__ lines on screen</span>
<span class="c1">#        V          V      |   |______ columns on screen</span>
<span class="c1">#        |          |      |__________ maximum of &quot;iterations&quot;</span>
<span class="c1">#        |          |_________________ range on y axis</span>
<span class="c1">#        |____________________________ range on x axis</span>
</pre></div>
</div>
<p>Don’t try this at home, kids!</p>
</div>
</div>
<div class="section" id="numbers-and-strings">
<h2><a class="toc-backref" href="#id26">Numbers and strings</a><a class="headerlink" href="#numbers-and-strings" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-specify-hexadecimal-and-octal-integers">
<h3><a class="toc-backref" href="#id27">How do I specify hexadecimal and octal integers?</a><a class="headerlink" href="#how-do-i-specify-hexadecimal-and-octal-integers" title="Permalink to this headline">¶</a></h3>
<p>To specify an octal digit, precede the octal value with a zero, and then a lower
or uppercase “o”.  For example, to set the variable “a” to the octal value “10”
(8 in decimal), type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mo">0o10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">8</span>
</pre></div>
</div>
<p>Hexadecimal is just as easy.  Simply precede the hexadecimal number with a zero,
and then a lower or uppercase “x”.  Hexadecimal digits can be specified in lower
or uppercase.  For example, in the Python interpreter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mh">0xa5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">165</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="mh">0XB2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">178</span>
</pre></div>
</div>
</div>
<div class="section" id="why-does-22-10-return-3">
<h3><a class="toc-backref" href="#id28">Why does -22 // 10 return -3?</a><a class="headerlink" href="#why-does-22-10-return-3" title="Permalink to this headline">¶</a></h3>
<p>It’s primarily driven by the desire that <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">j</span></code>.
If you want that, and also want:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">==</span> <span class="p">(</span><span class="n">i</span> <span class="o">//</span> <span class="n">j</span><span class="p">)</span> <span class="o">*</span> <span class="n">j</span> <span class="o">+</span> <span class="p">(</span><span class="n">i</span> <span class="o">%</span> <span class="n">j</span><span class="p">)</span>
</pre></div>
</div>
<p>then integer division has to return the floor.  C also requires that identity to
hold, and then compilers that truncate <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">//</span> <span class="pre">j</span></code> need to make <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> have
the same sign as <code class="docutils literal notranslate"><span class="pre">i</span></code>.</p>
<p>There are few real use cases for <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> when <code class="docutils literal notranslate"><span class="pre">j</span></code> is negative.  When <code class="docutils literal notranslate"><span class="pre">j</span></code>
is positive, there are many, and in virtually all of them it’s more useful for
<code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">%</span> <span class="pre">j</span></code> to be <code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">0</span></code>.  If the clock says 10 now, what did it say 200 hours
ago?  <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">2</span></code> is useful; <code class="docutils literal notranslate"><span class="pre">-190</span> <span class="pre">%</span> <span class="pre">12</span> <span class="pre">==</span> <span class="pre">-10</span></code> is a bug waiting to
bite.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Python 2, <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></code> returns the same as <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">//</span> <span class="pre">b</span></code> if
<code class="docutils literal notranslate"><span class="pre">__future__.division</span></code> is not in effect.  This is also known as “classic”
division.</p>
</div>
</div>
<div class="section" id="how-do-i-convert-a-string-to-a-number">
<h3><a class="toc-backref" href="#id29">How do I convert a string to a number?</a><a class="headerlink" href="#how-do-i-convert-a-string-to-a-number" title="Permalink to this headline">¶</a></h3>
<p>For integers, use the built-in <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type constructor, e.g. <code class="docutils literal notranslate"><span class="pre">int('144')</span>
<span class="pre">==</span> <span class="pre">144</span></code>.  Similarly, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> converts to floating-point,
e.g. <code class="docutils literal notranslate"><span class="pre">float('144')</span> <span class="pre">==</span> <span class="pre">144.0</span></code>.</p>
<p>By default, these interpret the number as decimal, so that <code class="docutils literal notranslate"><span class="pre">int('0144')</span> <span class="pre">==</span>
<span class="pre">144</span></code> and <code class="docutils literal notranslate"><span class="pre">int('0x144')</span></code> raises <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>. <code class="docutils literal notranslate"><span class="pre">int(string,</span> <span class="pre">base)</span></code> takes
the base to convert from as a second optional argument, so <code class="docutils literal notranslate"><span class="pre">int('0x144',</span> <span class="pre">16)</span> <span class="pre">==</span>
<span class="pre">324</span></code>.  If the base is specified as 0, the number is interpreted using Python’s
rules: a leading ‘0’ indicates octal, and ‘0x’ indicates a hex number.</p>
<p>Do not use the built-in function <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> if all you need is to convert
strings to numbers.  <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> will be significantly slower and it presents a
security risk: someone could pass you a Python expression that might have
unwanted side effects.  For example, someone could pass
<code class="docutils literal notranslate"><span class="pre">__import__('os').system(&quot;rm</span> <span class="pre">-rf</span> <span class="pre">$HOME&quot;)</span></code> which would erase your home
directory.</p>
<p><a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> also has the effect of interpreting numbers as Python expressions,
so that e.g. <code class="docutils literal notranslate"><span class="pre">eval('09')</span></code> gives a syntax error because Python regards numbers
starting with ‘0’ as octal (base 8).</p>
</div>
<div class="section" id="how-do-i-convert-a-number-to-a-string">
<h3><a class="toc-backref" href="#id30">How do I convert a number to a string?</a><a class="headerlink" href="#how-do-i-convert-a-number-to-a-string" title="Permalink to this headline">¶</a></h3>
<p>To convert, e.g., the number 144 to the string ‘144’, use the built-in type
constructor <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.  If you want a hexadecimal or octal representation, use
the built-in functions <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> or <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a>.  For fancy formatting, see
the <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a> section, e.g. <code class="docutils literal notranslate"><span class="pre">&quot;{:04d}&quot;.format(144)</span></code> yields
<code class="docutils literal notranslate"><span class="pre">'0144'</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;{:.3f}&quot;.format(1/3)</span></code> yields <code class="docutils literal notranslate"><span class="pre">'0.333'</span></code>.  You may also use
<a class="reference internal" href="../library/stdtypes.html#string-formatting"><span class="std std-ref">the % operator</span></a> on strings.  See the library reference
manual for details.</p>
</div>
<div class="section" id="how-do-i-modify-a-string-in-place">
<h3><a class="toc-backref" href="#id31">How do I modify a string in place?</a><a class="headerlink" href="#how-do-i-modify-a-string-in-place" title="Permalink to this headline">¶</a></h3>
<p>You can’t, because strings are immutable.  If you need an object with this
ability, try converting the string to a list or use the array module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">io</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Hello, world&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">a</span>
<span class="go">[&#39;H&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;, &#39;,&#39;, &#39; &#39;, &#39;w&#39;, &#39;o&#39;, &#39;r&#39;, &#39;l&#39;, &#39;d&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">7</span><span class="p">:]</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="s2">&quot;there!&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">&#39;Hello, there!&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">a</span>
<span class="go">array(&#39;c&#39;, &#39;Hello, world&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;y&#39;</span><span class="p">;</span> <span class="nb">print</span> <span class="n">a</span>
<span class="go">array(&#39;c&#39;, &#39;yello, world&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">tostring</span><span class="p">()</span>
<span class="go">&#39;yello, world&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-use-strings-to-call-functions-methods">
<h3><a class="toc-backref" href="#id32">How do I use strings to call functions/methods?</a><a class="headerlink" href="#how-do-i-use-strings-to-call-functions-methods" title="Permalink to this headline">¶</a></h3>
<p>There are various techniques.</p>
<ul>
<li><p class="first">The best is to use a dictionary that maps strings to functions.  The primary
advantage of this technique is that the strings do not need to match the names
of the functions.  This is also the primary technique used to emulate a case
construct:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">a</span><span class="p">():</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">b</span><span class="p">():</span>
    <span class="k">pass</span>

<span class="n">dispatch</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;go&#39;</span><span class="p">:</span> <span class="n">a</span><span class="p">,</span> <span class="s1">&#39;stop&#39;</span><span class="p">:</span> <span class="n">b</span><span class="p">}</span>  <span class="c1"># Note lack of parens for funcs</span>

<span class="n">dispatch</span><span class="p">[</span><span class="n">get_input</span><span class="p">()]()</span>  <span class="c1"># Note trailing parens to call function</span>
</pre></div>
</div>
</li>
<li><p class="first">Use the built-in function <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">foo</span>
<span class="nb">getattr</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">)()</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> works on any object, including classes, class
instances, modules, and so on.</p>
<p>This is used in several places in the standard library, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">do_foo</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="k">def</span> <span class="nf">do_bar</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">foo_instance</span><span class="p">,</span> <span class="s1">&#39;do_&#39;</span> <span class="o">+</span> <span class="n">opname</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
</li>
<li><p class="first">Use <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> or <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> to resolve the function name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">myFunc</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s2">&quot;hello&quot;</span>

<span class="n">fname</span> <span class="o">=</span> <span class="s2">&quot;myFunc&quot;</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">locals</span><span class="p">()[</span><span class="n">fname</span><span class="p">]</span>
<span class="n">f</span><span class="p">()</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">eval</span><span class="p">(</span><span class="n">fname</span><span class="p">)</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>Note: Using <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> is slow and dangerous.  If you don’t have absolute
control over the contents of the string, someone could pass a string that
resulted in an arbitrary function being executed.</p>
</li>
</ul>
</div>
<div class="section" id="is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings">
<h3><a class="toc-backref" href="#id33">Is there an equivalent to Perl’s chomp() for removing trailing newlines from strings?</a><a class="headerlink" href="#is-there-an-equivalent-to-perl-s-chomp-for-removing-trailing-newlines-from-strings" title="Permalink to this headline">¶</a></h3>
<p>Starting with Python 2.2, you can use <code class="docutils literal notranslate"><span class="pre">S.rstrip(&quot;\r\n&quot;)</span></code> to remove all
occurrences of any line terminator from the end of the string <code class="docutils literal notranslate"><span class="pre">S</span></code> without
removing other trailing whitespace.  If the string <code class="docutils literal notranslate"><span class="pre">S</span></code> represents more than
one line, with several empty lines at the end, the line terminators for all the
blank lines will be removed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;line 1 </span><span class="se">\r\n</span><span class="s2">&quot;</span>
<span class="gp">... </span>         <span class="s2">&quot;</span><span class="se">\r\n</span><span class="s2">&quot;</span>
<span class="gp">... </span>         <span class="s2">&quot;</span><span class="se">\r\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lines</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n\r</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">&#39;line 1 &#39;</span>
</pre></div>
</div>
<p>Since this is typically only desired when reading text one line at a time, using
<code class="docutils literal notranslate"><span class="pre">S.rstrip()</span></code> this way works well.</p>
<p>For older versions of Python, there are two partial substitutes:</p>
<ul class="simple">
<li>If you want to remove all trailing whitespace, use the <code class="docutils literal notranslate"><span class="pre">rstrip()</span></code> method of
string objects.  This removes all trailing whitespace, not just a single
newline.</li>
<li>Otherwise, if there is only one line in the string <code class="docutils literal notranslate"><span class="pre">S</span></code>, use
<code class="docutils literal notranslate"><span class="pre">S.splitlines()[0]</span></code>.</li>
</ul>
</div>
<div class="section" id="is-there-a-scanf-or-sscanf-equivalent">
<h3><a class="toc-backref" href="#id34">Is there a scanf() or sscanf() equivalent?</a><a class="headerlink" href="#is-there-a-scanf-or-sscanf-equivalent" title="Permalink to this headline">¶</a></h3>
<p>Not as such.</p>
<p>For simple input parsing, the easiest approach is usually to split the line into
whitespace-delimited words using the <a class="reference internal" href="../library/stdtypes.html#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> method of string objects
and then convert decimal strings to numeric values using <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> or
<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>.  <code class="docutils literal notranslate"><span class="pre">split()</span></code> supports an optional “sep” parameter which is useful
if the line uses something other than whitespace as a separator.</p>
<p>For more complicated input parsing, regular expressions are more powerful
than C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">sscanf()</span></code> and better suited for the task.</p>
</div>
<div class="section" id="what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean">
<h3><a class="toc-backref" href="#id35">What does ‘UnicodeError: ASCII [decoding,encoding] error: ordinal not in range(128)’ mean?</a><a class="headerlink" href="#what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean" title="Permalink to this headline">¶</a></h3>
<p>This error indicates that your Python installation can handle only 7-bit ASCII
strings.  There are a couple ways to fix or work around the problem.</p>
<p>If your programs must handle data in arbitrary character set encodings, the
environment the application runs in will generally identify the encoding of the
data it is handing you.  You need to convert the input to Unicode data using
that encoding.  For example, a program that handles email or web input will
typically find character set encoding information in Content-Type headers.  This
can then be used to properly convert input data to Unicode. Assuming the string
referred to by <code class="docutils literal notranslate"><span class="pre">value</span></code> is encoded as UTF-8:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">value</span> <span class="o">=</span> <span class="n">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>will return a Unicode object.  If the data is not correctly encoded as UTF-8,
the above call will raise a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> exception.</p>
<p>If you only want strings converted to Unicode which have non-ASCII data, you can
try converting them first assuming an ASCII encoding, and then generate Unicode
objects if that fails:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s2">&quot;ascii&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">UnicodeError</span><span class="p">:</span>
    <span class="n">value</span> <span class="o">=</span> <span class="n">unicode</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># value was valid ASCII data</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>It’s possible to set a default encoding in a file called <code class="docutils literal notranslate"><span class="pre">sitecustomize.py</span></code>
that’s part of the Python library.  However, this isn’t recommended because
changing the Python-wide default encoding may cause third-party extension
modules to fail.</p>
<p>Note that on Windows, there is an encoding known as “mbcs”, which uses an
encoding specific to your current locale.  In many cases, and particularly when
working with COM, this may be an appropriate default encoding to use.</p>
</div>
</div>
<div class="section" id="sequences-tuples-lists">
<h2><a class="toc-backref" href="#id36">Sequences (Tuples/Lists)</a><a class="headerlink" href="#sequences-tuples-lists" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-convert-between-tuples-and-lists">
<h3><a class="toc-backref" href="#id37">How do I convert between tuples and lists?</a><a class="headerlink" href="#how-do-i-convert-between-tuples-and-lists" title="Permalink to this headline">¶</a></h3>
<p>The type constructor <code class="docutils literal notranslate"><span class="pre">tuple(seq)</span></code> converts any sequence (actually, any
iterable) into a tuple with the same items in the same order.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">tuple([1,</span> <span class="pre">2,</span> <span class="pre">3])</span></code> yields <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code> and <code class="docutils literal notranslate"><span class="pre">tuple('abc')</span></code>
yields <code class="docutils literal notranslate"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></code>.  If the argument is a tuple, it does not make a copy
but returns the same object, so it is cheap to call <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a> when you
aren’t sure that an object is already a tuple.</p>
<p>The type constructor <code class="docutils literal notranslate"><span class="pre">list(seq)</span></code> converts any sequence or iterable into a list
with the same items in the same order.  For example, <code class="docutils literal notranslate"><span class="pre">list((1,</span> <span class="pre">2,</span> <span class="pre">3))</span></code> yields
<code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code> and <code class="docutils literal notranslate"><span class="pre">list('abc')</span></code> yields <code class="docutils literal notranslate"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></code>.  If the argument
is a list, it makes a copy just like <code class="docutils literal notranslate"><span class="pre">seq[:]</span></code> would.</p>
</div>
<div class="section" id="what-s-a-negative-index">
<h3><a class="toc-backref" href="#id38">What’s a negative index?</a><a class="headerlink" href="#what-s-a-negative-index" title="Permalink to this headline">¶</a></h3>
<p>Python sequences are indexed with positive numbers and negative numbers.  For
positive numbers 0 is the first index 1 is the second index and so forth.  For
negative indices -1 is the last index and -2 is the penultimate (next to last)
index and so forth.  Think of <code class="docutils literal notranslate"><span class="pre">seq[-n]</span></code> as the same as <code class="docutils literal notranslate"><span class="pre">seq[len(seq)-n]</span></code>.</p>
<p>Using negative indices can be very convenient.  For example <code class="docutils literal notranslate"><span class="pre">S[:-1]</span></code> is all of
the string except for its last character, which is useful for removing the
trailing newline from a string.</p>
</div>
<div class="section" id="how-do-i-iterate-over-a-sequence-in-reverse-order">
<h3><a class="toc-backref" href="#id39">How do I iterate over a sequence in reverse order?</a><a class="headerlink" href="#how-do-i-iterate-over-a-sequence-in-reverse-order" title="Permalink to this headline">¶</a></h3>
<p>Use the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> built-in function, which is new in Python 2.4:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">sequence</span><span class="p">):</span>
    <span class="o">...</span>  <span class="c1"># do something with x ...</span>
</pre></div>
</div>
<p>This won’t touch your original sequence, but build a new copy with reversed
order to iterate over.</p>
<p>With Python 2.3, you can use an extended slice syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">sequence</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]:</span>
    <span class="o">...</span>  <span class="c1"># do something with x ...</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-you-remove-duplicates-from-a-list">
<h3><a class="toc-backref" href="#id40">How do you remove duplicates from a list?</a><a class="headerlink" href="#how-do-you-remove-duplicates-from-a-list" title="Permalink to this headline">¶</a></h3>
<p>See the Python Cookbook for a long discussion of many ways to do this:</p>
<blockquote>
<div><a class="reference external" href="https://code.activestate.com/recipes/52560/">https://code.activestate.com/recipes/52560/</a></div></blockquote>
<p>If you don’t mind reordering the list, sort it and then scan from the end of the
list, deleting duplicates as you go:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">mylist</span><span class="p">:</span>
    <span class="n">mylist</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
    <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">mylist</span><span class="p">)</span><span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">last</span> <span class="o">==</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]:</span>
            <span class="k">del</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">last</span> <span class="o">=</span> <span class="n">mylist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</pre></div>
</div>
<p>If all elements of the list may be used as dictionary keys (i.e. they are all
hashable) this is often faster</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">:</span>
    <span class="n">d</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">mylist</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
</pre></div>
</div>
<p>In Python 2.5 and later, the following is possible instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mylist</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">mylist</span><span class="p">))</span>
</pre></div>
</div>
<p>This converts the list into a set, thereby removing duplicates, and then back
into a list.</p>
</div>
<div class="section" id="how-do-you-make-an-array-in-python">
<h3><a class="toc-backref" href="#id41">How do you make an array in Python?</a><a class="headerlink" href="#how-do-you-make-an-array-in-python" title="Permalink to this headline">¶</a></h3>
<p>Use a list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s2">&quot;this&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;is&quot;</span><span class="p">,</span> <span class="s2">&quot;an&quot;</span><span class="p">,</span> <span class="s2">&quot;array&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>Lists are equivalent to C or Pascal arrays in their time complexity; the primary
difference is that a Python list can contain objects of many different types.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">array</span></code> module also provides methods for creating arrays of fixed types
with compact representations, but they are slower to index than lists.  Also
note that the Numeric extensions and others define array-like structures with
various characteristics as well.</p>
<p>To get Lisp-style linked lists, you can emulate cons cells using tuples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lisp_list</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;like&quot;</span><span class="p">,</span>  <span class="p">(</span><span class="s2">&quot;this&quot;</span><span class="p">,</span>  <span class="p">(</span><span class="s2">&quot;example&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span> <span class="p">)</span> <span class="p">)</span>
</pre></div>
</div>
<p>If mutability is desired, you could use lists instead of tuples.  Here the
analogue of lisp car is <code class="docutils literal notranslate"><span class="pre">lisp_list[0]</span></code> and the analogue of cdr is
<code class="docutils literal notranslate"><span class="pre">lisp_list[1]</span></code>.  Only do this if you’re sure you really need to, because it’s
usually a lot slower than using Python lists.</p>
</div>
<div class="section" id="how-do-i-create-a-multidimensional-list">
<span id="faq-multidimensional-list"></span><h3><a class="toc-backref" href="#id42">How do I create a multidimensional list?</a><a class="headerlink" href="#how-do-i-create-a-multidimensional-list" title="Permalink to this headline">¶</a></h3>
<p>You probably tried to make a multidimensional array like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
</pre></div>
</div>
<p>This looks correct if you print it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
<span class="go">[[None, None], [None, None], [None, None]]</span>
</pre></div>
</div>
<p>But when you assign a value, it shows up in multiple places:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">A</span>
<span class="go">[[5, None], [5, None], [5, None]]</span>
</pre></div>
</div>
<p>The reason is that replicating a list with <code class="docutils literal notranslate"><span class="pre">*</span></code> doesn’t create copies, it only
creates references to the existing objects.  The <code class="docutils literal notranslate"><span class="pre">*3</span></code> creates a list
containing 3 references to the same list of length two.  Changes to one row will
show in all rows, which is almost certainly not what you want.</p>
<p>The suggested approach is to create a list of the desired length first and then
fill in each element with a newly created list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">A</span> <span class="o">=</span> <span class="p">[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">3</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
    <span class="n">A</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">2</span>
</pre></div>
</div>
<p>This generates a list containing 3 different lists of length two.  You can also
use a list comprehension:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">w</span><span class="p">,</span> <span class="n">h</span> <span class="o">=</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>
<span class="n">A</span> <span class="o">=</span> <span class="p">[[</span><span class="kc">None</span><span class="p">]</span> <span class="o">*</span> <span class="n">w</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">h</span><span class="p">)]</span>
</pre></div>
</div>
<p>Or, you can use an extension that provides a matrix datatype; <a class="reference external" href="http://www.numpy.org/">NumPy</a> is the best known.</p>
</div>
<div class="section" id="how-do-i-apply-a-method-to-a-sequence-of-objects">
<h3><a class="toc-backref" href="#id43">How do I apply a method to a sequence of objects?</a><a class="headerlink" href="#how-do-i-apply-a-method-to-a-sequence-of-objects" title="Permalink to this headline">¶</a></h3>
<p>Use a list comprehension:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">mylist</span><span class="p">]</span>
</pre></div>
</div>
<p>More generically, you can try the following function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">method_map</span><span class="p">(</span><span class="n">objects</span><span class="p">,</span> <span class="n">method</span><span class="p">,</span> <span class="n">arguments</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;method_map([a,b], &quot;meth&quot;, (1,2)) gives [a.meth(1,2), b.meth(1,2)]&quot;&quot;&quot;</span>
    <span class="n">nobjects</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">objects</span><span class="p">)</span>
    <span class="n">methods</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">getattr</span><span class="p">,</span> <span class="n">objects</span><span class="p">,</span> <span class="p">[</span><span class="n">method</span><span class="p">]</span><span class="o">*</span><span class="n">nobjects</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">map</span><span class="p">(</span><span class="n">apply</span><span class="p">,</span> <span class="n">methods</span><span class="p">,</span> <span class="p">[</span><span class="n">arguments</span><span class="p">]</span><span class="o">*</span><span class="n">nobjects</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works">
<h3><a class="toc-backref" href="#id44">Why does a_tuple[i] += [‘item’] raise an exception when the addition works?</a><a class="headerlink" href="#why-does-a-tuple-i-item-raise-an-exception-when-the-addition-works" title="Permalink to this headline">¶</a></h3>
<p>This is because of a combination of the fact that augmented assignment
operators are <em>assignment</em> operators, and the difference between mutable and
immutable objects in Python.</p>
<p>This discussion applies in general when augmented assignment operators are
applied to elements of a tuple that point to mutable objects, but we’ll use
a <code class="docutils literal notranslate"><span class="pre">list</span></code> and <code class="docutils literal notranslate"><span class="pre">+=</span></code> as our exemplar.</p>
<p>If you wrote:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gt">Traceback (most recent call last):</span>
   <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>The reason for the exception should be immediately clear: <code class="docutils literal notranslate"><span class="pre">1</span></code> is added to the
object <code class="docutils literal notranslate"><span class="pre">a_tuple[0]</span></code> points to (<code class="docutils literal notranslate"><span class="pre">1</span></code>), producing the result object, <code class="docutils literal notranslate"><span class="pre">2</span></code>,
but when we attempt to assign the result of the computation, <code class="docutils literal notranslate"><span class="pre">2</span></code>, to element
<code class="docutils literal notranslate"><span class="pre">0</span></code> of the tuple, we get an error because we can’t change what an element of
a tuple points to.</p>
<p>Under the covers, what this augmented assignment statement is doing is
approximately this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>It is the assignment part of the operation that produces the error, since a
tuple is immutable.</p>
<p>When you write something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span> <span class="o">=</span> <span class="p">([</span><span class="s1">&#39;foo&#39;</span><span class="p">],</span> <span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+=</span> <span class="p">[</span><span class="s1">&#39;item&#39;</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>The exception is a bit more surprising, and even more surprising is the fact
that even though there was an error, the append worked:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">[&#39;foo&#39;, &#39;item&#39;]</span>
</pre></div>
</div>
<p>To see why this happens, you need to know that (a) if an object implements an
<code class="docutils literal notranslate"><span class="pre">__iadd__</span></code> magic method, it gets called when the <code class="docutils literal notranslate"><span class="pre">+=</span></code> augmented assignment
is executed, and its return value is what gets used in the assignment statement;
and (b) for lists, <code class="docutils literal notranslate"><span class="pre">__iadd__</span></code> is equivalent to calling <code class="docutils literal notranslate"><span class="pre">extend</span></code> on the list
and returning the list.  That’s why we say that for lists, <code class="docutils literal notranslate"><span class="pre">+=</span></code> is a
“shorthand” for <code class="docutils literal notranslate"><span class="pre">list.extend</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">+=</span> <span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span>
<span class="go">[1]</span>
</pre></div>
</div>
<p>This is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_list</span><span class="o">.</span><span class="fm">__iadd__</span><span class="p">([</span><span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_list</span> <span class="o">=</span> <span class="n">result</span>
</pre></div>
</div>
<p>The object pointed to by a_list has been mutated, and the pointer to the
mutated object is assigned back to <code class="docutils literal notranslate"><span class="pre">a_list</span></code>.  The end result of the
assignment is a no-op, since it is a pointer to the same object that <code class="docutils literal notranslate"><span class="pre">a_list</span></code>
was previously pointing to, but the assignment still happens.</p>
<p>Thus, in our tuple example what is happening is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="fm">__iadd__</span><span class="p">([</span><span class="s1">&#39;item&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">__iadd__</span></code> succeeds, and thus the list is extended, but even though
<code class="docutils literal notranslate"><span class="pre">result</span></code> points to the same object that <code class="docutils literal notranslate"><span class="pre">a_tuple[0]</span></code> already points to,
that final assignment still results in an error, because tuples are immutable.</p>
</div>
</div>
<div class="section" id="dictionaries">
<h2><a class="toc-backref" href="#id45">Dictionaries</a><a class="headerlink" href="#dictionaries" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order">
<h3><a class="toc-backref" href="#id46">How can I get a dictionary to display its keys in a consistent order?</a><a class="headerlink" href="#how-can-i-get-a-dictionary-to-display-its-keys-in-a-consistent-order" title="Permalink to this headline">¶</a></h3>
<p>You can’t.  Dictionaries store their keys in an unpredictable order, so the
display order of a dictionary’s elements will be similarly unpredictable.</p>
<p>This can be frustrating if you want to save a printable version to a file, make
some changes and then compare it with some other printed dictionary.  In this
case, use the <code class="docutils literal notranslate"><span class="pre">pprint</span></code> module to pretty-print the dictionary; the items will
be presented in order sorted by the key.</p>
<p>A more complicated solution is to subclass <code class="docutils literal notranslate"><span class="pre">dict</span></code> to create a
<code class="docutils literal notranslate"><span class="pre">SortedDict</span></code> class that prints itself in a predictable order.  Here’s one
simpleminded implementation of such a class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">SortedDict</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
        <span class="n">result</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;</span><span class="si">{!r}</span><span class="s2">: </span><span class="si">{!r}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="bp">self</span><span class="p">[</span><span class="n">k</span><span class="p">])</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">)</span>
        <span class="k">return</span> <span class="s2">&quot;{{</span><span class="si">{}</span><span class="s2">}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">result</span><span class="p">))</span>

    <span class="fm">__str__</span> <span class="o">=</span> <span class="fm">__repr__</span>
</pre></div>
</div>
<p>This will work for many common situations you might encounter, though it’s far
from a perfect solution. The largest flaw is that if some values in the
dictionary are also dictionaries, their values won’t be presented in any
particular order.</p>
</div>
<div class="section" id="i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python">
<h3><a class="toc-backref" href="#id47">I want to do a complicated sort: can you do a Schwartzian Transform in Python?</a><a class="headerlink" href="#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python" title="Permalink to this headline">¶</a></h3>
<p>The technique, attributed to Randal Schwartz of the Perl community, sorts the
elements of a list by a metric which maps each element to its “sort value”. In
Python, use the <code class="docutils literal notranslate"><span class="pre">key</span></code> argument for the <code class="xref py py-func docutils literal notranslate"><span class="pre">sort()</span></code> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Isorted</span> <span class="o">=</span> <span class="n">L</span><span class="p">[:]</span>
<span class="n">Isorted</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">s</span><span class="p">:</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="p">[</span><span class="mi">10</span><span class="p">:</span><span class="mi">15</span><span class="p">]))</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-sort-one-list-by-values-from-another-list">
<h3><a class="toc-backref" href="#id48">How can I sort one list by values from another list?</a><a class="headerlink" href="#how-can-i-sort-one-list-by-values-from-another-list" title="Permalink to this headline">¶</a></h3>
<p>Merge them into a single list of tuples, sort the resulting list, and then pick
out the element you want.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">list1</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;what&quot;</span><span class="p">,</span> <span class="s2">&quot;I&#39;m&quot;</span><span class="p">,</span> <span class="s2">&quot;sorting&quot;</span><span class="p">,</span> <span class="s2">&quot;by&quot;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">list2</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;something&quot;</span><span class="p">,</span> <span class="s2">&quot;else&quot;</span><span class="p">,</span> <span class="s2">&quot;to&quot;</span><span class="p">,</span> <span class="s2">&quot;sort&quot;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">list1</span><span class="p">,</span> <span class="n">list2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span>
<span class="go">[(&#39;what&#39;, &#39;something&#39;), (&quot;I&#39;m&quot;, &#39;else&#39;), (&#39;sorting&#39;, &#39;to&#39;), (&#39;by&#39;, &#39;sort&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="p">[</span> <span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">pairs</span> <span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">result</span>
<span class="go">[&#39;else&#39;, &#39;sort&#39;, &#39;to&#39;, &#39;something&#39;]</span>
</pre></div>
</div>
<p>An alternative for the last step is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">pairs</span><span class="p">:</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>If you find this more legible, you might prefer to use this instead of the final
list comprehension.  However, it is almost twice as slow for long lists.  Why?
First, the <code class="docutils literal notranslate"><span class="pre">append()</span></code> operation has to reallocate memory, and while it uses
some tricks to avoid doing that each time, it still has to do it occasionally,
and that costs quite a bit.  Second, the expression “result.append” requires an
extra attribute lookup, and third, there’s a speed reduction from having to make
all those function calls.</p>
</div>
</div>
<div class="section" id="objects">
<h2><a class="toc-backref" href="#id49">Objects</a><a class="headerlink" href="#objects" title="Permalink to this headline">¶</a></h2>
<div class="section" id="what-is-a-class">
<h3><a class="toc-backref" href="#id50">What is a class?</a><a class="headerlink" href="#what-is-a-class" title="Permalink to this headline">¶</a></h3>
<p>A class is the particular object type created by executing a class statement.
Class objects are used as templates to create instance objects, which embody
both the data (attributes) and code (methods) specific to a datatype.</p>
<p>A class can be based on one or more other classes, called its base class(es). It
then inherits the attributes and methods of its base classes. This allows an
object model to be successively refined by inheritance.  You might have a
generic <code class="docutils literal notranslate"><span class="pre">Mailbox</span></code> class that provides basic accessor methods for a mailbox,
and subclasses such as <code class="docutils literal notranslate"><span class="pre">MboxMailbox</span></code>, <code class="docutils literal notranslate"><span class="pre">MaildirMailbox</span></code>, <code class="docutils literal notranslate"><span class="pre">OutlookMailbox</span></code>
that handle various specific mailbox formats.</p>
</div>
<div class="section" id="what-is-a-method">
<h3><a class="toc-backref" href="#id51">What is a method?</a><a class="headerlink" href="#what-is-a-method" title="Permalink to this headline">¶</a></h3>
<p>A method is a function on some object <code class="docutils literal notranslate"><span class="pre">x</span></code> that you normally call as
<code class="docutils literal notranslate"><span class="pre">x.name(arguments...)</span></code>.  Methods are defined as functions inside the class
definition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">arg</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">attribute</span>
</pre></div>
</div>
</div>
<div class="section" id="what-is-self">
<h3><a class="toc-backref" href="#id52">What is self?</a><a class="headerlink" href="#what-is-self" title="Permalink to this headline">¶</a></h3>
<p>Self is merely a conventional name for the first argument of a method.  A method
defined as <code class="docutils literal notranslate"><span class="pre">meth(self,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> should be called as <code class="docutils literal notranslate"><span class="pre">x.meth(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code> for
some instance <code class="docutils literal notranslate"><span class="pre">x</span></code> of the class in which the definition occurs; the called
method will think it is called as <code class="docutils literal notranslate"><span class="pre">meth(x,</span> <span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>.</p>
<p>See also <a class="reference internal" href="design.html#why-self"><span class="std std-ref">Why must ‘self’ be used explicitly in method definitions and calls?</span></a>.</p>
</div>
<div class="section" id="how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it">
<h3><a class="toc-backref" href="#id53">How do I check if an object is an instance of a given class or of a subclass of it?</a><a class="headerlink" href="#how-do-i-check-if-an-object-is-an-instance-of-a-given-class-or-of-a-subclass-of-it" title="Permalink to this headline">¶</a></h3>
<p>Use the built-in function <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">cls)</span></code>.  You can check if an object
is an instance of any of a number of classes by providing a tuple instead of a
single class, e.g. <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">(class1,</span> <span class="pre">class2,</span> <span class="pre">...))</span></code>, and can also
check whether an object is one of Python’s built-in types, e.g.
<code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">str)</span></code> or <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">(int,</span> <span class="pre">long,</span> <span class="pre">float,</span> <span class="pre">complex))</span></code>.</p>
<p>Note that most programs do not use <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> on user-defined classes
very often.  If you are developing the classes yourself, a more proper
object-oriented style is to define methods on the classes that encapsulate a
particular behaviour, instead of checking the object’s class and doing a
different thing based on what class it is.  For example, if you have a function
that does something:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">Mailbox</span><span class="p">):</span>
        <span class="o">...</span>  <span class="c1"># code to search a mailbox</span>
    <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">Document</span><span class="p">):</span>
        <span class="o">...</span>  <span class="c1"># code to search a document</span>
    <span class="k">elif</span> <span class="o">...</span>
</pre></div>
</div>
<p>A better approach is to define a <code class="docutils literal notranslate"><span class="pre">search()</span></code> method on all the classes and just
call it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mailbox</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>  <span class="c1"># code to search a mailbox</span>

<span class="k">class</span> <span class="nc">Document</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">search</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>  <span class="c1"># code to search a document</span>

<span class="n">obj</span><span class="o">.</span><span class="n">search</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="what-is-delegation">
<h3><a class="toc-backref" href="#id54">What is delegation?</a><a class="headerlink" href="#what-is-delegation" title="Permalink to this headline">¶</a></h3>
<p>Delegation is an object oriented technique (also called a design pattern).
Let’s say you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code> and want to change the behaviour of just one
of its methods.  You can create a new class that provides a new implementation
of the method you’re interested in changing and delegates all other methods to
the corresponding method of <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
<p>Python programmers can easily implement delegation.  For example, the following
class implements a class that behaves like a file but converts all written data
to uppercase:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">UpperOut</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span> <span class="o">=</span> <span class="n">outfile</span>

    <span class="k">def</span> <span class="nf">write</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">s</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>

    <span class="k">def</span> <span class="nf">__getattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">_outfile</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>Here the <code class="docutils literal notranslate"><span class="pre">UpperOut</span></code> class redefines the <code class="docutils literal notranslate"><span class="pre">write()</span></code> method to convert the
argument string to uppercase before calling the underlying
<code class="docutils literal notranslate"><span class="pre">self.__outfile.write()</span></code> method.  All other methods are delegated to the
underlying <code class="docutils literal notranslate"><span class="pre">self.__outfile</span></code> object.  The delegation is accomplished via the
<code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> method; consult <a class="reference internal" href="../reference/datamodel.html#attribute-access"><span class="std std-ref">the language reference</span></a>
for more information about controlling attribute access.</p>
<p>Note that for more general cases delegation can get trickier. When attributes
must be set as well as retrieved, the class must define a <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a>
method too, and it must do so carefully.  The basic implementation of
<a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> is roughly equivalent to the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">X</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Most <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> implementations must modify <code class="docutils literal notranslate"><span class="pre">self.__dict__</span></code> to store
local state for self without causing an infinite recursion.</p>
</div>
<div class="section" id="how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it">
<h3><a class="toc-backref" href="#id55">How do I call a method defined in a base class from a derived class that overrides it?</a><a class="headerlink" href="#how-do-i-call-a-method-defined-in-a-base-class-from-a-derived-class-that-overrides-it" title="Permalink to this headline">¶</a></h3>
<p>If you’re using new-style classes, use the built-in <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">Derived</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">meth</span><span class="p">()</span>
</pre></div>
</div>
<p>If you’re using classic classes: For a class definition such as <code class="docutils literal notranslate"><span class="pre">class</span>
<span class="pre">Derived(Base):</span> <span class="pre">...</span></code> you can call method <code class="docutils literal notranslate"><span class="pre">meth()</span></code> defined in <code class="docutils literal notranslate"><span class="pre">Base</span></code> (or one
of <code class="docutils literal notranslate"><span class="pre">Base</span></code>’s base classes) as <code class="docutils literal notranslate"><span class="pre">Base.meth(self,</span> <span class="pre">arguments...)</span></code>.  Here,
<code class="docutils literal notranslate"><span class="pre">Base.meth</span></code> is an unbound method, so you need to provide the <code class="docutils literal notranslate"><span class="pre">self</span></code>
argument.</p>
</div>
<div class="section" id="how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class">
<h3><a class="toc-backref" href="#id56">How can I organize my code to make it easier to change the base class?</a><a class="headerlink" href="#how-can-i-organize-my-code-to-make-it-easier-to-change-the-base-class" title="Permalink to this headline">¶</a></h3>
<p>You could define an alias for the base class, assign the real base class to it
before your class definition, and use the alias throughout your class.  Then all
you have to change is the value assigned to the alias.  Incidentally, this trick
is also handy if you want to decide dynamically (e.g. depending on availability
of resources) which base class to use.  Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">BaseAlias</span> <span class="o">=</span> <span class="o">&lt;</span><span class="n">real</span> <span class="n">base</span> <span class="n">class</span><span class="o">&gt;</span>

<span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">BaseAlias</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">BaseAlias</span><span class="o">.</span><span class="n">meth</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-create-static-class-data-and-static-class-methods">
<h3><a class="toc-backref" href="#id57">How do I create static class data and static class methods?</a><a class="headerlink" href="#how-do-i-create-static-class-data-and-static-class-methods" title="Permalink to this headline">¶</a></h3>
<p>Both static data and static methods (in the sense of C++ or Java) are supported
in Python.</p>
<p>For static data, simply define a class attribute.  To assign a new value to the
attribute, you have to explicitly use the class name in the assignment:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>   <span class="c1"># number of times C.__init__ called</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">+</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">getcount</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span>  <span class="c1"># or return self.count</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">c.count</span></code> also refers to <code class="docutils literal notranslate"><span class="pre">C.count</span></code> for any <code class="docutils literal notranslate"><span class="pre">c</span></code> such that <code class="docutils literal notranslate"><span class="pre">isinstance(c,</span>
<span class="pre">C)</span></code> holds, unless overridden by <code class="docutils literal notranslate"><span class="pre">c</span></code> itself or by some class on the base-class
search path from <code class="docutils literal notranslate"><span class="pre">c.__class__</span></code> back to <code class="docutils literal notranslate"><span class="pre">C</span></code>.</p>
<p>Caution: within a method of C, an assignment like <code class="docutils literal notranslate"><span class="pre">self.count</span> <span class="pre">=</span> <span class="pre">42</span></code> creates a
new and unrelated instance named “count” in <code class="docutils literal notranslate"><span class="pre">self</span></code>’s own dict.  Rebinding of a
class-static data name must always specify the class whether inside a method or
not:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">C</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">314</span>
</pre></div>
</div>
<p>Static methods are possible since Python 2.2:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">static</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">):</span>
        <span class="c1"># No &#39;self&#39; parameter!</span>
        <span class="o">...</span>
    <span class="n">static</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">static</span><span class="p">)</span>
</pre></div>
</div>
<p>With Python 2.4’s decorators, this can also be written as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">static</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="n">arg3</span><span class="p">):</span>
        <span class="c1"># No &#39;self&#39; parameter!</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>However, a far more straightforward way to get the effect of a static method is
via a simple module-level function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">getcount</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">C</span><span class="o">.</span><span class="n">count</span>
</pre></div>
</div>
<p>If your code is structured so as to define one class (or tightly related class
hierarchy) per module, this supplies the desired encapsulation.</p>
</div>
<div class="section" id="how-can-i-overload-constructors-or-methods-in-python">
<h3><a class="toc-backref" href="#id58">How can I overload constructors (or methods) in Python?</a><a class="headerlink" href="#how-can-i-overload-constructors-or-methods-in-python" title="Permalink to this headline">¶</a></h3>
<p>This answer actually applies to all methods, but the question usually comes up
first in the context of constructors.</p>
<p>In C++ you’d write</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">class</span> <span class="n">C</span> <span class="p">{</span>
    <span class="n">C</span><span class="p">()</span> <span class="p">{</span> <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;No arguments</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span> <span class="p">}</span>
    <span class="n">C</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="p">)</span> <span class="p">{</span> <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;Argument is &quot;</span> <span class="o">&lt;&lt;</span> <span class="n">i</span> <span class="o">&lt;&lt;</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In Python you have to write a single constructor that catches all cases using
default arguments.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">i</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s2">&quot;No arguments&quot;</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s2">&quot;Argument is&quot;</span><span class="p">,</span> <span class="n">i</span>
</pre></div>
</div>
<p>This is not entirely equivalent, but close enough in practice.</p>
<p>You could also try a variable-length argument list, e.g.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The same approach works for all method definitions.</p>
</div>
<div class="section" id="i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam">
<h3><a class="toc-backref" href="#id59">I try to use __spam and I get an error about _SomeClassName__spam.</a><a class="headerlink" href="#i-try-to-use-spam-and-i-get-an-error-about-someclassname-spam" title="Permalink to this headline">¶</a></h3>
<p>Variable names with double leading underscores are “mangled” to provide a simple
but effective way to define class private variables.  Any identifier of the form
<code class="docutils literal notranslate"><span class="pre">__spam</span></code> (at least two leading underscores, at most one trailing underscore)
is textually replaced with <code class="docutils literal notranslate"><span class="pre">_classname__spam</span></code>, where <code class="docutils literal notranslate"><span class="pre">classname</span></code> is the
current class name with any leading underscores stripped.</p>
<p>This doesn’t guarantee privacy: an outside user can still deliberately access
the “_classname__spam” attribute, and private values are visible in the object’s
<code class="docutils literal notranslate"><span class="pre">__dict__</span></code>.  Many Python programmers never bother to use private variable
names at all.</p>
</div>
<div class="section" id="my-class-defines-del-but-it-is-not-called-when-i-delete-the-object">
<h3><a class="toc-backref" href="#id60">My class defines __del__ but it is not called when I delete the object.</a><a class="headerlink" href="#my-class-defines-del-but-it-is-not-called-when-i-delete-the-object" title="Permalink to this headline">¶</a></h3>
<p>There are several possible reasons for this.</p>
<p>The del statement does not necessarily call <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> – it simply
decrements the object’s reference count, and if this reaches zero
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> is called.</p>
<p>If your data structures contain circular links (e.g. a tree where each child has
a parent reference and each parent has a list of children) the reference counts
will never go back to zero.  Once in a while Python runs an algorithm to detect
such cycles, but the garbage collector might run some time after the last
reference to your data structure vanishes, so your <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method may be
called at an inconvenient and random time. This is inconvenient if you’re trying
to reproduce a problem. Worse, the order in which object’s <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a>
methods are executed is arbitrary.  You can run <a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">gc.collect()</span></code></a> to force a
collection, but there <em>are</em> pathological cases where objects will never be
collected.</p>
<p>Despite the cycle collector, it’s still a good idea to define an explicit
<code class="docutils literal notranslate"><span class="pre">close()</span></code> method on objects to be called whenever you’re done with them.  The
<code class="docutils literal notranslate"><span class="pre">close()</span></code> method can then remove attributes that refer to subobjecs.  Don’t
call <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> directly – <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> should call <code class="docutils literal notranslate"><span class="pre">close()</span></code> and
<code class="docutils literal notranslate"><span class="pre">close()</span></code> should make sure that it can be called more than once for the same
object.</p>
<p>Another way to avoid cyclical references is to use the <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module,
which allows you to point to objects without incrementing their reference count.
Tree data structures, for instance, should use weak references for their parent
and sibling references (if they need them!).</p>
<p>If the object has ever been a local variable in a function that caught an
expression in an except clause, chances are that a reference to the object still
exists in that function’s stack frame as contained in the stack trace.
Normally, calling <a class="reference internal" href="../library/sys.html#sys.exc_clear" title="sys.exc_clear"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_clear()</span></code></a> will take care of this by clearing the
last recorded exception.</p>
<p>Finally, if your <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method raises an exception, a warning message
is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.</p>
</div>
<div class="section" id="how-do-i-get-a-list-of-all-instances-of-a-given-class">
<h3><a class="toc-backref" href="#id61">How do I get a list of all instances of a given class?</a><a class="headerlink" href="#how-do-i-get-a-list-of-all-instances-of-a-given-class" title="Permalink to this headline">¶</a></h3>
<p>Python does not keep track of all instances of a class (or of a built-in type).
You can program the class’s constructor to keep track of all instances by
keeping a list of weak references to each instance.</p>
</div>
<div class="section" id="why-does-the-result-of-id-appear-to-be-not-unique">
<h3><a class="toc-backref" href="#id62">Why does the result of <code class="docutils literal notranslate"><span class="pre">id()</span></code> appear to be not unique?</a><a class="headerlink" href="#why-does-the-result-of-id-appear-to-be-not-unique" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> builtin returns an integer that is guaranteed to be unique during
the lifetime of the object.  Since in CPython, this is the object’s memory
address, it happens frequently that after an object is deleted from memory, the
next freshly created object is allocated at the same position in memory.  This
is illustrated by this example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="go">13901272</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="mi">2000</span><span class="p">)</span>
<span class="go">13901272</span>
</pre></div>
</div>
<p>The two ids belong to different integer objects that are created before, and
deleted immediately after execution of the <code class="docutils literal notranslate"><span class="pre">id()</span></code> call.  To be sure that
objects whose id you want to examine are still alive, create another reference
to the object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">1000</span><span class="p">;</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">2000</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">13901272</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="go">13891296</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="modules">
<h2><a class="toc-backref" href="#id63">Modules</a><a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-do-i-create-a-pyc-file">
<h3><a class="toc-backref" href="#id64">How do I create a .pyc file?</a><a class="headerlink" href="#how-do-i-create-a-pyc-file" title="Permalink to this headline">¶</a></h3>
<p>When a module is imported for the first time (or when the source is more recent
than the current compiled file) a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file containing the compiled code
should be created in the same directory as the <code class="docutils literal notranslate"><span class="pre">.py</span></code> file.</p>
<p>One reason that a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file may not be created is permissions problems with
the directory. This can happen, for example, if you develop as one user but run
as another, such as if you are testing with a web server.  Creation of a .pyc
file is automatic if you’re importing a module and Python has the ability
(permissions, free space, etc…) to write the compiled module back to the
directory.</p>
<p>Running Python on a top level script is not considered an import and no
<code class="docutils literal notranslate"><span class="pre">.pyc</span></code> will be created.  For example, if you have a top-level module
<code class="docutils literal notranslate"><span class="pre">foo.py</span></code> that imports another module <code class="docutils literal notranslate"><span class="pre">xyz.py</span></code>, when you run <code class="docutils literal notranslate"><span class="pre">foo</span></code>,
<code class="docutils literal notranslate"><span class="pre">xyz.pyc</span></code> will be created since <code class="docutils literal notranslate"><span class="pre">xyz</span></code> is imported, but no <code class="docutils literal notranslate"><span class="pre">foo.pyc</span></code> file
will be created since <code class="docutils literal notranslate"><span class="pre">foo.py</span></code> isn’t being imported.</p>
<p>If you need to create <code class="docutils literal notranslate"><span class="pre">foo.pyc</span></code> – that is, to create a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> file for a module
that is not imported – you can, using the <a class="reference internal" href="../library/py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> and
<a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> modules.</p>
<p>The <a class="reference internal" href="../library/py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> module can manually compile any module.  One way is to use
the <code class="docutils literal notranslate"><span class="pre">compile()</span></code> function in that module interactively:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">py_compile</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">py_compile</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;foo.py&#39;</span><span class="p">)</span>                 
</pre></div>
</div>
<p>This will write the <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> to the same location as <code class="docutils literal notranslate"><span class="pre">foo.py</span></code> (or you can
override that with the optional parameter <code class="docutils literal notranslate"><span class="pre">cfile</span></code>).</p>
<p>You can also automatically compile all files in a directory or directories using
the <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> module.  You can do it from the shell prompt by running
<code class="docutils literal notranslate"><span class="pre">compileall.py</span></code> and providing the path of a directory containing Python files
to compile:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">compileall</span> <span class="o">.</span>
</pre></div>
</div>
</div>
<div class="section" id="how-do-i-find-the-current-module-name">
<h3><a class="toc-backref" href="#id65">How do I find the current module name?</a><a class="headerlink" href="#how-do-i-find-the-current-module-name" title="Permalink to this headline">¶</a></h3>
<p>A module can find out its own module name by looking at the predefined global
variable <code class="docutils literal notranslate"><span class="pre">__name__</span></code>.  If this has the value <code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>, the program is
running as a script.  Many modules that are usually used by importing them also
provide a command-line interface or a self-test, and only execute this code
after checking <code class="docutils literal notranslate"><span class="pre">__name__</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s1">&#39;Running test...&#39;</span>
    <span class="o">...</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="how-can-i-have-modules-that-mutually-import-each-other">
<h3><a class="toc-backref" href="#id66">How can I have modules that mutually import each other?</a><a class="headerlink" href="#how-can-i-have-modules-that-mutually-import-each-other" title="Permalink to this headline">¶</a></h3>
<p>Suppose you have the following modules:</p>
<p>foo.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">bar</span> <span class="k">import</span> <span class="n">bar_var</span>
<span class="n">foo_var</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>bar.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">foo</span> <span class="k">import</span> <span class="n">foo_var</span>
<span class="n">bar_var</span> <span class="o">=</span> <span class="mi">2</span>
</pre></div>
</div>
<p>The problem is that the interpreter will perform the following steps:</p>
<ul class="simple">
<li>main imports foo</li>
<li>Empty globals for foo are created</li>
<li>foo is compiled and starts executing</li>
<li>foo imports bar</li>
<li>Empty globals for bar are created</li>
<li>bar is compiled and starts executing</li>
<li>bar imports foo (which is a no-op since there already is a module named foo)</li>
<li>bar.foo_var = foo.foo_var</li>
</ul>
<p>The last step fails, because Python isn’t done with interpreting <code class="docutils literal notranslate"><span class="pre">foo</span></code> yet and
the global symbol dictionary for <code class="docutils literal notranslate"><span class="pre">foo</span></code> is still empty.</p>
<p>The same thing happens when you use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">foo</span></code>, and then try to access
<code class="docutils literal notranslate"><span class="pre">foo.foo_var</span></code> in global code.</p>
<p>There are (at least) three possible workarounds for this problem.</p>
<p>Guido van Rossum recommends avoiding all uses of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">&lt;module&gt;</span> <span class="pre">import</span> <span class="pre">...</span></code>,
and placing all code inside functions.  Initializations of global variables and
class variables should use constants or built-in functions only.  This means
everything from an imported module is referenced as <code class="docutils literal notranslate"><span class="pre">&lt;module&gt;.&lt;name&gt;</span></code>.</p>
<p>Jim Roskind suggests performing steps in the following order in each module:</p>
<ul class="simple">
<li>exports (globals, functions, and classes that don’t need imported base
classes)</li>
<li><code class="docutils literal notranslate"><span class="pre">import</span></code> statements</li>
<li>active code (including globals that are initialized from imported values).</li>
</ul>
<p>van Rossum doesn’t like this approach much because the imports appear in a
strange place, but it does work.</p>
<p>Matthias Urlichs recommends restructuring your code so that the recursive import
is not necessary in the first place.</p>
<p>These solutions are not mutually exclusive.</p>
</div>
<div class="section" id="import-x-y-z-returns-module-x-how-do-i-get-z">
<h3><a class="toc-backref" href="#id67">__import__(‘x.y.z’) returns &lt;module ‘x’&gt;; how do I get z?</a><a class="headerlink" href="#import-x-y-z-returns-module-x-how-do-i-get-z" title="Permalink to this headline">¶</a></h3>
<p>Consider using the convenience function <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">import_module()</span></code></a> from
<a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">z</span> <span class="o">=</span> <span class="n">importlib</span><span class="o">.</span><span class="n">import_module</span><span class="p">(</span><span class="s1">&#39;x.y.z&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen">
<h3><a class="toc-backref" href="#id68">When I edit an imported module and reimport it, the changes don’t show up.  Why does this happen?</a><a class="headerlink" href="#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen" title="Permalink to this headline">¶</a></h3>
<p>For reasons of efficiency as well as consistency, Python only reads the module
file on the first time a module is imported.  If it didn’t, in a program
consisting of many modules where each one imports the same basic module, the
basic module would be parsed and re-parsed many times.  To force rereading of a
changed module, do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">modname</span>
<span class="n">reload</span><span class="p">(</span><span class="n">modname</span><span class="p">)</span>
</pre></div>
</div>
<p>Warning: this technique is not 100% fool-proof.  In particular, modules
containing statements like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">modname</span> <span class="k">import</span> <span class="n">some_objects</span>
</pre></div>
</div>
<p>will continue to work with the old version of the imported objects.  If the
module contains class definitions, existing class instances will <em>not</em> be
updated to use the new class definition.  This can result in the following
paradoxical behaviour:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">cls</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="bp">cls</span><span class="o">.</span><span class="n">C</span><span class="p">()</span>                <span class="c1"># Create an instance of C</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reload</span><span class="p">(</span><span class="bp">cls</span><span class="p">)</span>
<span class="go">&lt;module &#39;cls&#39; from &#39;cls.pyc&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="bp">cls</span><span class="o">.</span><span class="n">C</span><span class="p">)</span>       <span class="c1"># isinstance is false?!?</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The nature of the problem is made clear if you print out the class objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="vm">__class__</span>
<span class="go">&lt;class cls.C at 0x7352a0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="bp">cls</span><span class="o">.</span><span class="n">C</span>
<span class="go">&lt;class cls.C at 0x4198d0&gt;</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Programming FAQ</a><ul>
<li><a class="reference internal" href="#general-questions">General Questions</a></li>
<li><a class="reference internal" href="#core-language">Core Language</a></li>
<li><a class="reference internal" href="#numbers-and-strings">Numbers and strings</a></li>
<li><a class="reference internal" href="#sequences-tuples-lists">Sequences (Tuples/Lists)</a></li>
<li><a class="reference internal" href="#dictionaries">Dictionaries</a></li>
<li><a class="reference internal" href="#objects">Objects</a></li>
<li><a class="reference internal" href="#modules">Modules</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="general.html"
                        title="previous chapter">General Python FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="design.html"
                        title="next chapter">Design and History FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/programming.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="design.html" title="Design and History FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="general.html" title="General Python FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��9���html/faq/windows.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python on Windows FAQ &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Graphic User Interface FAQ" href="gui.html" />
    <link rel="prev" title="Extending/Embedding FAQ" href="extending.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/faq/windows.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gui.html" title="Graphic User Interface FAQ"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="Extending/Embedding FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-on-windows-faq">
<span id="windows-faq"></span><h1><a class="toc-backref" href="#id1">Python on Windows FAQ</a><a class="headerlink" href="#python-on-windows-faq" title="Permalink to this headline">¶</a></h1>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#python-on-windows-faq" id="id1">Python on Windows FAQ</a><ul>
<li><a class="reference internal" href="#how-do-i-run-a-python-program-under-windows" id="id2">How do I run a Python program under Windows?</a></li>
<li><a class="reference internal" href="#how-do-i-make-python-scripts-executable" id="id3">How do I make Python scripts executable?</a></li>
<li><a class="reference internal" href="#why-does-python-sometimes-take-so-long-to-start" id="id4">Why does Python sometimes take so long to start?</a></li>
<li><a class="reference internal" href="#how-do-i-make-an-executable-from-a-python-script" id="id5">How do I make an executable from a Python script?</a></li>
<li><a class="reference internal" href="#is-a-pyd-file-the-same-as-a-dll" id="id6">Is a <code class="docutils literal notranslate"><span class="pre">*.pyd</span></code> file the same as a DLL?</a></li>
<li><a class="reference internal" href="#how-can-i-embed-python-into-a-windows-application" id="id7">How can I embed Python into a Windows application?</a></li>
<li><a class="reference internal" href="#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source" id="id8">How do I keep editors from inserting tabs into my Python source?</a></li>
<li><a class="reference internal" href="#how-do-i-check-for-a-keypress-without-blocking" id="id9">How do I check for a keypress without blocking?</a></li>
<li><a class="reference internal" href="#how-do-i-emulate-os-kill-in-windows" id="id10">How do I emulate os.kill() in Windows?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-the-downloaded-documentation-on-windows" id="id11">How do I extract the downloaded documentation on Windows?</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="how-do-i-run-a-python-program-under-windows">
<h2><a class="toc-backref" href="#id2">How do I run a Python program under Windows?</a><a class="headerlink" href="#how-do-i-run-a-python-program-under-windows" title="Permalink to this headline">¶</a></h2>
<p>This is not necessarily a straightforward question. If you are already familiar
with running programs from the Windows command line then everything will seem
obvious; otherwise, you might need a little more guidance.</p>
<p>Unless you use some sort of integrated development environment, you will end up
<em>typing</em> Windows commands into what is variously referred to as a “DOS window”
or “Command prompt window”.  Usually you can create such a window from your
Start menu; under Windows 7 the menu selection is <span class="menuselection">Start ‣
Programs ‣ Accessories ‣ Command Prompt</span>.  You should be able to recognize
when you have started such a window because you will see a Windows “command
prompt”, which usually looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">C</span><span class="p">:</span>\<span class="o">&gt;</span>
</pre></div>
</div>
<p>The letter may be different, and there might be other things after it, so you
might just as easily see something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">D</span><span class="p">:</span>\<span class="n">YourName</span>\<span class="n">Projects</span>\<span class="n">Python</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>depending on how your computer has been set up and what else you have recently
done with it.  Once you have started such a window, you are well on the way to
running Python programs.</p>
<p>You need to realize that your Python scripts have to be processed by another
program called the Python <em>interpreter</em>.  The interpreter reads your script,
compiles it into bytecodes, and then executes the bytecodes to run your
program. So, how do you arrange for the interpreter to handle your Python?</p>
<p>First, you need to make sure that your command window recognises the word
“python” as an instruction to start the interpreter.  If you have opened a
command window, you should try entering the command <code class="docutils literal notranslate"><span class="pre">python</span></code> and hitting
return.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">C</span><span class="p">:</span>\<span class="n">Users</span>\<span class="n">YourName</span><span class="o">&gt;</span> <span class="n">python</span>
</pre></div>
</div>
<p>You should then see something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Python</span> <span class="mf">2.7</span><span class="o">.</span><span class="mi">3</span> <span class="p">(</span><span class="n">default</span><span class="p">,</span> <span class="n">Apr</span> <span class="mi">10</span> <span class="mi">2012</span><span class="p">,</span> <span class="mf">22.71</span><span class="p">:</span><span class="mi">26</span><span class="p">)</span> <span class="p">[</span><span class="n">MSC</span> <span class="n">v</span><span class="o">.</span><span class="mi">1500</span> <span class="mi">32</span> <span class="n">bit</span> <span class="p">(</span><span class="n">Intel</span><span class="p">)]</span> <span class="n">on</span> <span class="n">win32</span>
<span class="n">Type</span> <span class="s2">&quot;help&quot;</span><span class="p">,</span> <span class="s2">&quot;copyright&quot;</span><span class="p">,</span> <span class="s2">&quot;credits&quot;</span> <span class="ow">or</span> <span class="s2">&quot;license&quot;</span> <span class="k">for</span> <span class="n">more</span> <span class="n">information</span><span class="o">.</span>
<span class="o">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You have started the interpreter in “interactive mode”. That means you can enter
Python statements or expressions interactively and have them executed or
evaluated while you wait.  This is one of Python’s strongest features.  Check it
by entering a few expressions of your choice and seeing the results:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s2">&quot;Hello&quot;</span>
<span class="go">Hello</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;Hello&quot;</span> <span class="o">*</span> <span class="mi">3</span>
<span class="go">&#39;HelloHelloHello&#39;</span>
</pre></div>
</div>
<p>Many people use the interactive mode as a convenient yet highly programmable
calculator.  When you want to end your interactive Python session, hold the <kbd class="kbd docutils literal notranslate">Ctrl</kbd>
key down while you enter a <kbd class="kbd docutils literal notranslate">Z</kbd>, then hit the “<kbd class="kbd docutils literal notranslate">Enter</kbd>” key to get back to your
Windows command prompt.</p>
<p>You may also find that you have a Start-menu entry such as <span class="menuselection">Start
‣ Programs ‣ Python 2.7 ‣ Python (command line)</span> that results in you
seeing the <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code> prompt in a new window.  If so, the window will disappear
after you enter the <kbd class="kbd docutils literal notranslate">Ctrl-Z</kbd> character; Windows is running a single “python”
command in the window, and closes it when you terminate the interpreter.</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">python</span></code> command, instead of displaying the interpreter prompt <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>,
gives you a message like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;python&#39;</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">recognized</span> <span class="k">as</span> <span class="n">an</span> <span class="n">internal</span> <span class="ow">or</span> <span class="n">external</span> <span class="n">command</span><span class="p">,</span> <span class="n">operable</span> <span class="n">program</span> <span class="ow">or</span> <span class="n">batch</span> <span class="n">file</span><span class="o">.</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Bad</span> <span class="n">command</span> <span class="ow">or</span> <span class="n">filename</span>
</pre></div>
</div>
<p>then you need to make sure that your computer knows where to find the Python
interpreter.  To do this you will have to modify a setting called PATH, which is
a list of directories where Windows will look for programs.</p>
<p>You should arrange for Python’s installation directory to be added to the PATH
of every command window as it starts.  If you installed Python fairly recently
then the command</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">dir</span> <span class="n">C</span><span class="p">:</span>\<span class="n">py</span><span class="o">*</span>
</pre></div>
</div>
<p>will probably tell you where it is installed; the usual location is something
like <code class="docutils literal notranslate"><span class="pre">C:\Python27</span></code>.  Otherwise you will be reduced to a search of your whole
disk … use <span class="menuselection">Tools ‣ Find</span> or hit the <span class="guilabel">Search</span>
button and look for “python.exe”.  Supposing you discover that Python is
installed in the <code class="docutils literal notranslate"><span class="pre">C:\Python27</span></code> directory (the default at the time of writing),
you should make sure that entering the command</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">c</span><span class="p">:</span>\<span class="n">Python27</span>\<span class="n">python</span>
</pre></div>
</div>
<p>starts up the interpreter as above (and don’t forget you’ll need a “<kbd class="kbd docutils literal notranslate">Ctrl-Z</kbd>” and
an “<kbd class="kbd docutils literal notranslate">Enter</kbd>” to get out of it). Once you have verified the directory, you can
add it to the system path to make it easier to start Python by just running
the <code class="docutils literal notranslate"><span class="pre">python</span></code> command. This is currently an option in the installer as of
CPython 2.7.</p>
<p>More information about environment variables can be found on the
<a class="reference internal" href="../using/windows.html#setting-envvars"><span class="std std-ref">Using Python on Windows</span></a> page.</p>
</div>
<div class="section" id="how-do-i-make-python-scripts-executable">
<h2><a class="toc-backref" href="#id3">How do I make Python scripts executable?</a><a class="headerlink" href="#how-do-i-make-python-scripts-executable" title="Permalink to this headline">¶</a></h2>
<p>On Windows, the standard Python installer already associates the .py
extension with a file type (Python.File) and gives that file type an open
command that runs the interpreter (<code class="docutils literal notranslate"><span class="pre">D:\Program</span> <span class="pre">Files\Python\python.exe</span> <span class="pre">&quot;%1&quot;</span>
<span class="pre">%*</span></code>).  This is enough to make scripts executable from the command prompt as
‘foo.py’.  If you’d rather be able to execute the script by simple typing ‘foo’
with no extension you need to add .py to the PATHEXT environment variable.</p>
</div>
<div class="section" id="why-does-python-sometimes-take-so-long-to-start">
<h2><a class="toc-backref" href="#id4">Why does Python sometimes take so long to start?</a><a class="headerlink" href="#why-does-python-sometimes-take-so-long-to-start" title="Permalink to this headline">¶</a></h2>
<p>Usually Python starts very quickly on Windows, but occasionally there are bug
reports that Python suddenly begins to take a long time to start up.  This is
made even more puzzling because Python will work fine on other Windows systems
which appear to be configured identically.</p>
<p>The problem may be caused by a misconfiguration of virus checking software on
the problem machine.  Some virus scanners have been known to introduce startup
overhead of two orders of magnitude when the scanner is configured to monitor
all reads from the filesystem.  Try checking the configuration of virus scanning
software on your systems to ensure that they are indeed configured identically.
McAfee, when configured to scan all file system read activity, is a particular
offender.</p>
</div>
<div class="section" id="how-do-i-make-an-executable-from-a-python-script">
<h2><a class="toc-backref" href="#id5">How do I make an executable from a Python script?</a><a class="headerlink" href="#how-do-i-make-an-executable-from-a-python-script" title="Permalink to this headline">¶</a></h2>
<p>See <a class="reference external" href="http://www.py2exe.org/">http://www.py2exe.org/</a> for a distutils extension that allows you
to create console and GUI executables from Python code.</p>
</div>
<div class="section" id="is-a-pyd-file-the-same-as-a-dll">
<h2><a class="toc-backref" href="#id6">Is a <code class="docutils literal notranslate"><span class="pre">*.pyd</span></code> file the same as a DLL?</a><a class="headerlink" href="#is-a-pyd-file-the-same-as-a-dll" title="Permalink to this headline">¶</a></h2>
<p>Yes, .pyd files are dll’s, but there are a few differences.  If you have a DLL
named <code class="docutils literal notranslate"><span class="pre">foo.pyd</span></code>, then it must have a function <code class="docutils literal notranslate"><span class="pre">initfoo()</span></code>.  You can then
write Python “import foo”, and Python will search for foo.pyd (as well as
foo.py, foo.pyc) and if it finds it, will attempt to call <code class="docutils literal notranslate"><span class="pre">initfoo()</span></code> to
initialize it.  You do not link your .exe with foo.lib, as that would cause
Windows to require the DLL to be present.</p>
<p>Note that the search path for foo.pyd is PYTHONPATH, not the same as the path
that Windows uses to search for foo.dll.  Also, foo.pyd need not be present to
run your program, whereas if you linked your program with a dll, the dll is
required.  Of course, foo.pyd is required if you want to say <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">foo</span></code>.  In
a DLL, linkage is declared in the source code with <code class="docutils literal notranslate"><span class="pre">__declspec(dllexport)</span></code>.
In a .pyd, linkage is defined in a list of available functions.</p>
</div>
<div class="section" id="how-can-i-embed-python-into-a-windows-application">
<h2><a class="toc-backref" href="#id7">How can I embed Python into a Windows application?</a><a class="headerlink" href="#how-can-i-embed-python-into-a-windows-application" title="Permalink to this headline">¶</a></h2>
<p>Embedding the Python interpreter in a Windows app can be summarized as follows:</p>
<ol class="arabic">
<li><p class="first">Do _not_ build Python into your .exe file directly.  On Windows, Python must
be a DLL to handle importing modules that are themselves DLL’s.  (This is the
first key undocumented fact.)  Instead, link to <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.dll</span></code>; it is
typically installed in <code class="docutils literal notranslate"><span class="pre">C:\Windows\System</span></code>.  <em>NN</em> is the Python version, a
number such as “27” for Python 2.7.</p>
<p>You can link to Python in two different ways.  Load-time linking means
linking against <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.lib</span></code>, while run-time linking means linking
against <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.dll</span></code>.  (General note: <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.lib</span></code> is the
so-called “import lib” corresponding to <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.dll</span></code>.  It merely
defines symbols for the linker.)</p>
<p>Run-time linking greatly simplifies link options; everything happens at run
time.  Your code must load <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.dll</span></code> using the Windows
<code class="docutils literal notranslate"><span class="pre">LoadLibraryEx()</span></code> routine.  The code must also use access routines and data
in <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.dll</span></code> (that is, Python’s C API’s) using pointers obtained
by the Windows <code class="docutils literal notranslate"><span class="pre">GetProcAddress()</span></code> routine.  Macros can make using these
pointers transparent to any C code that calls routines in Python’s C API.</p>
<p>Borland note: convert <code class="file docutils literal notranslate"><span class="pre">python</span><em><span class="pre">NN</span></em><span class="pre">.lib</span></code> to OMF format using Coff2Omf.exe
first.</p>
</li>
<li><p class="first">If you use SWIG, it is easy to create a Python “extension module” that will
make the app’s data and methods available to Python.  SWIG will handle just
about all the grungy details for you.  The result is C code that you link
<em>into</em> your .exe file (!)  You do _not_ have to create a DLL file, and this
also simplifies linking.</p>
</li>
<li><p class="first">SWIG will create an init function (a C function) whose name depends on the
name of the extension module.  For example, if the name of the module is leo,
the init function will be called initleo().  If you use SWIG shadow classes,
as you should, the init function will be called initleoc().  This initializes
a mostly hidden helper class used by the shadow class.</p>
<p>The reason you can link the C code in step 2 into your .exe file is that
calling the initialization function is equivalent to importing the module
into Python! (This is the second key undocumented fact.)</p>
</li>
<li><p class="first">In short, you can use the following code to initialize the Python interpreter
with your extension module.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;python.h&quot;</span><span class="cp"></span>
<span class="p">...</span>
<span class="n">Py_Initialize</span><span class="p">();</span>  <span class="c1">// Initialize Python.</span>
<span class="n">initmyAppc</span><span class="p">();</span>  <span class="c1">// Initialize (import) the helper class.</span>
<span class="n">PyRun_SimpleString</span><span class="p">(</span><span class="s">&quot;import myApp&quot;</span><span class="p">);</span>  <span class="c1">// Import the shadow class.</span>
</pre></div>
</div>
</li>
<li><p class="first">There are two problems with Python’s C API which will become apparent if you
use a compiler other than MSVC, the compiler used to build pythonNN.dll.</p>
<p>Problem 1: The so-called “Very High Level” functions that take FILE *
arguments will not work in a multi-compiler environment because each
compiler’s notion of a struct FILE will be different.  From an implementation
standpoint these are very _low_ level functions.</p>
<p>Problem 2: SWIG generates the following code when generating wrappers to void
functions:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="n">Py_INCREF</span><span class="p">(</span><span class="n">Py_None</span><span class="p">);</span>
<span class="n">_resultobj</span> <span class="o">=</span> <span class="n">Py_None</span><span class="p">;</span>
<span class="k">return</span> <span class="n">_resultobj</span><span class="p">;</span>
</pre></div>
</div>
<p>Alas, Py_None is a macro that expands to a reference to a complex data
structure called _Py_NoneStruct inside pythonNN.dll.  Again, this code will
fail in a mult-compiler environment.  Replace such code by:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="k">return</span> <span class="nf">Py_BuildValue</span><span class="p">(</span><span class="s">&quot;&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>It may be possible to use SWIG’s <code class="docutils literal notranslate"><span class="pre">%typemap</span></code> command to make the change
automatically, though I have not been able to get this to work (I’m a
complete SWIG newbie).</p>
</li>
<li><p class="first">Using a Python shell script to put up a Python interpreter window from inside
your Windows app is not a good idea; the resulting window will be independent
of your app’s windowing system.  Rather, you (or the wxPythonWindow class)
should create a “native” interpreter window.  It is easy to connect that
window to the Python interpreter.  You can redirect Python’s i/o to _any_
object that supports read and write, so all you need is a Python object
(defined in your extension module) that contains read() and write() methods.</p>
</li>
</ol>
</div>
<div class="section" id="how-do-i-keep-editors-from-inserting-tabs-into-my-python-source">
<h2><a class="toc-backref" href="#id8">How do I keep editors from inserting tabs into my Python source?</a><a class="headerlink" href="#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source" title="Permalink to this headline">¶</a></h2>
<p>The FAQ does not recommend using tabs, and the Python style guide, <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a>,
recommends 4 spaces for distributed Python code; this is also the Emacs
python-mode default.</p>
<p>Under any editor, mixing tabs and spaces is a bad idea.  MSVC is no different in
this respect, and is easily configured to use spaces: Take <span class="menuselection">Tools
‣ Options ‣ Tabs</span>, and for file type “Default” set “Tab size” and “Indent
size” to 4, and select the “Insert spaces” radio button.</p>
<p>If you suspect mixed tabs and spaces are causing problems in leading whitespace,
run Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">-t</span></code></a> switch or run the <a class="reference internal" href="../library/tabnanny.html#module-tabnanny" title="tabnanny: Tool for detecting white space related problems in Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tabnanny</span></code></a> module to
check a directory tree in batch mode.</p>
</div>
<div class="section" id="how-do-i-check-for-a-keypress-without-blocking">
<h2><a class="toc-backref" href="#id9">How do I check for a keypress without blocking?</a><a class="headerlink" href="#how-do-i-check-for-a-keypress-without-blocking" title="Permalink to this headline">¶</a></h2>
<p>Use the msvcrt module.  This is a standard Windows-specific extension module.
It defines a function <code class="docutils literal notranslate"><span class="pre">kbhit()</span></code> which checks whether a keyboard hit is
present, and <code class="docutils literal notranslate"><span class="pre">getch()</span></code> which gets one character without echoing it.</p>
</div>
<div class="section" id="how-do-i-emulate-os-kill-in-windows">
<h2><a class="toc-backref" href="#id10">How do I emulate os.kill() in Windows?</a><a class="headerlink" href="#how-do-i-emulate-os-kill-in-windows" title="Permalink to this headline">¶</a></h2>
<p>Prior to Python 2.7 and 3.2, to terminate a process, you can use <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>

<span class="k">def</span> <span class="nf">kill</span><span class="p">(</span><span class="n">pid</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;kill function for Win32&quot;&quot;&quot;</span>
    <span class="n">kernel32</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span>
    <span class="n">handle</span> <span class="o">=</span> <span class="n">kernel32</span><span class="o">.</span><span class="n">OpenProcess</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">pid</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">(</span><span class="mi">0</span> <span class="o">!=</span> <span class="n">kernel32</span><span class="o">.</span><span class="n">TerminateProcess</span><span class="p">(</span><span class="n">handle</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
</pre></div>
</div>
<p>In 2.7 and 3.2, <a class="reference internal" href="../library/os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a> is implemented similar to the above function,
with the additional feature of being able to send <kbd class="kbd docutils literal notranslate">Ctrl+C</kbd> and <kbd class="kbd docutils literal notranslate">Ctrl+Break</kbd>
to console subprocesses which are designed to handle those signals. See
<a class="reference internal" href="../library/os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a> for further details.</p>
</div>
<div class="section" id="how-do-i-extract-the-downloaded-documentation-on-windows">
<h2><a class="toc-backref" href="#id11">How do I extract the downloaded documentation on Windows?</a><a class="headerlink" href="#how-do-i-extract-the-downloaded-documentation-on-windows" title="Permalink to this headline">¶</a></h2>
<p>Sometimes, when you download the documentation package to a Windows machine
using a web browser, the file extension of the saved file ends up being .EXE.
This is a mistake; the extension should be .TGZ.</p>
<p>Simply rename the downloaded file to have the .TGZ extension, and WinZip will be
able to handle it.  (If your copy of WinZip doesn’t, get a newer one from
<a class="reference external" href="https://www.winzip.com">https://www.winzip.com</a>.)</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Python on Windows FAQ</a><ul>
<li><a class="reference internal" href="#how-do-i-run-a-python-program-under-windows">How do I run a Python program under Windows?</a></li>
<li><a class="reference internal" href="#how-do-i-make-python-scripts-executable">How do I make Python scripts executable?</a></li>
<li><a class="reference internal" href="#why-does-python-sometimes-take-so-long-to-start">Why does Python sometimes take so long to start?</a></li>
<li><a class="reference internal" href="#how-do-i-make-an-executable-from-a-python-script">How do I make an executable from a Python script?</a></li>
<li><a class="reference internal" href="#is-a-pyd-file-the-same-as-a-dll">Is a <code class="docutils literal notranslate"><span class="pre">*.pyd</span></code> file the same as a DLL?</a></li>
<li><a class="reference internal" href="#how-can-i-embed-python-into-a-windows-application">How can I embed Python into a Windows application?</a></li>
<li><a class="reference internal" href="#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source">How do I keep editors from inserting tabs into my Python source?</a></li>
<li><a class="reference internal" href="#how-do-i-check-for-a-keypress-without-blocking">How do I check for a keypress without blocking?</a></li>
<li><a class="reference internal" href="#how-do-i-emulate-os-kill-in-windows">How do I emulate os.kill() in Windows?</a></li>
<li><a class="reference internal" href="#how-do-i-extract-the-downloaded-documentation-on-windows">How do I extract the downloaded documentation on Windows?</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="extending.html"
                        title="previous chapter">Extending/Embedding FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gui.html"
                        title="next chapter">Graphic User Interface FAQ</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/faq/windows.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gui.html" title="Graphic User Interface FAQ"
             >next</a> |</li>
        <li class="right" >
          <a href="extending.html" title="Extending/Embedding FAQ"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Frequently Asked Questions</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�
�Z�Z�html/genindex-S.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-S.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; S</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.S">S (in module re)</a>
</li>
      <li><a href="library/stat.html#stat.S_ENFMT">S_ENFMT (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_eval">s_eval() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_exec">s_exec() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_execfile">s_execfile() (rexec.RExec method)</a>
</li>
      <li><a href="library/stat.html#stat.S_IEXEC">S_IEXEC (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFBLK">S_IFBLK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFCHR">S_IFCHR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFDIR">S_IFDIR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFIFO">S_IFIFO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFLNK">S_IFLNK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFMT">S_IFMT() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFREG">S_IFREG (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFSOCK">S_IFSOCK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IMODE">S_IMODE() (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_import">s_import() (rexec.RExec method)</a>
</li>
      <li><a href="library/stat.html#stat.S_IREAD">S_IREAD (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRGRP">S_IRGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IROTH">S_IROTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRUSR">S_IRUSR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXG">S_IRWXG (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXO">S_IRWXO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXU">S_IRWXU (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISBLK">S_ISBLK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISCHR">S_ISCHR() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISDIR">S_ISDIR() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISFIFO">S_ISFIFO() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISGID">S_ISGID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISLNK">S_ISLNK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISREG">S_ISREG() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISSOCK">S_ISSOCK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISUID">S_ISUID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISVTX">S_ISVTX (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWGRP">S_IWGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWOTH">S_IWOTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWRITE">S_IWRITE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWUSR">S_IWUSR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXGRP">S_IXGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXOTH">S_IXOTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXUSR">S_IXUSR (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_reload">s_reload() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_unload">s_unload() (rexec.RExec method)</a>
</li>
      <li><a href="library/string.html#string.Template.safe_substitute">safe_substitute() (string.Template method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.SafeConfigParser">SafeConfigParser (class in ConfigParser)</a>
</li>
      <li><a href="library/pprint.html#pprint.saferepr">saferepr() (in module pprint)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.same_files">same_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.same_quantum">same_quantum() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.same_quantum">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.samefile">samefile() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.sameopenfile">sameopenfile() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.samestat">samestat() (in module os.path)</a>
</li>
      <li><a href="library/random.html#random.sample">sample() (in module random)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.save">save() (cookielib.FileCookieJar method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.save_bgn">save_bgn() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.save_end">save_end() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SaveKey">SaveKey() (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.savetty">savetty() (in module curses)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.SAX2DOM">SAX2DOM (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXException">SAXException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXNotRecognizedException">SAXNotRecognizedException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXNotSupportedException">SAXNotSupportedException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXParseException">SAXParseException</a>
</li>
      <li><a href="library/imageop.html#imageop.scale">scale() (in module imageop)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.scaleb">scaleb() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.scaleb">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scalebarvalues">scalebarvalues() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/re.html#index-0">scanf()</a>
</li>
      <li><a href="library/sched.html#module-sched">sched (module)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler">scheduler (class in sched)</a>
</li>
      <li><a href="library/msilib.html#msilib.schema">schema (in module msilib)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.sci">sci() (in module fpformat)</a>
</li>
      <li><a href="reference/executionmodel.html#index-1">scope</a>, <a href="reference/executionmodel.html#index-5">[1]</a>
</li>
      <li><a href="library/carbon.html#index-0">Scrap Manager</a>
</li>
      <li><a href="library/turtle.html#turtle.Screen">Screen (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.screensize">screensize() (in module turtle)</a>
</li>
      <li><a href="library/doctest.html#doctest.script_from_examples">script_from_examples() (in module doctest)</a>
</li>
      <li><a href="library/curses.html#curses.window.scroll">scroll() (curses.window method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scrollbar_callback">scrollbar_callback() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scrollbars">scrollbars() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/turtle.html#turtle.ScrolledCanvas">ScrolledCanvas (class in turtle)</a>
</li>
      <li><a href="library/scrolledtext.html#module-ScrolledText">ScrolledText (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.scrollok">scrollok() (curses.window method)</a>
</li>
      <li>
    search

      <ul>
        <li><a href="c-api/init.html#index-0">path, module</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.search">search() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/re.html#re.search">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.search">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.SEARCH_ERROR">SEARCH_ERROR (in module imp)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.second">second (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.second">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/multifile.html#multifile.MultiFile.section_divider">section_divider() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.sections">sections() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.secure">secure (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/sha.html#index-0">Secure Hash Algorithm</a>
</li>
      <li><a href="library/hashlib.html#index-0">secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512</a>
</li>
      <li><a href="library/ssl.html#index-1">Secure Sockets Layer</a>
</li>
      <li>
    security

      <ul>
        <li><a href="library/cgi.html#index-1">CGI</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.see">see() (ttk.Treeview method)</a>
</li>
      <li><a href="library/random.html#random.seed">seed() (in module random)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.seek">seek() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/chunk.html#chunk.Chunk.seek">(chunk.Chunk method)</a>
</li>
        <li><a href="library/stdtypes.html#file.seek">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.seek">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.seek">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.seek">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.seek">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_CUR">SEEK_CUR (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_CUR">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_END">SEEK_END (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_END">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_SET">SEEK_SET (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_SET">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.IOBase.seekable">seekable() (io.IOBase method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.segcountproc">segcountproc (C type)</a>
</li>
      <li><a href="library/tix.html#Tix.Select">Select (class in Tix)</a>
</li>
      <li><a href="library/select.html#module-select">select (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.select">select() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/gl.html#gl.select">(in module gl)</a>
</li>
        <li><a href="library/select.html#select.select">(in module select)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.select">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLSocket.selected_alpn_protocol">selected_alpn_protocol() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.selected_npn_protocol">selected_npn_protocol() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection">selection() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_add">selection_add() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_remove">selection_remove() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_set">selection_set() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_toggle">selection_toggle() (ttk.Treeview method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Semaphore">Semaphore (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Semaphore">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Semaphore">Semaphore() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/thread.html#index-0">semaphores, binary</a>
</li>
      <li><a href="library/token.html#token.SEMI">SEMI (in module token)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo.send">send() (aetools.TalkTo method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.send">(Connection method)</a>
</li>
        <li><a href="library/asyncore.html#asyncore.dispatcher.send">(asyncore.dispatcher method)</a>
</li>
        <li><a href="reference/expressions.html#generator.send">(generator method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.send">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.send">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.send">(logging.handlers.DatagramHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.send">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.send">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.send_bytes">send_bytes() (Connection method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_error">send_error() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_flowing_data">send_flowing_data() (formatter.writer method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_header">send_header() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_hor_rule">send_hor_rule() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_label_data">send_label_data() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_line_break">send_line_break() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_literal_data">send_literal_data() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_paragraph">send_paragraph() (formatter.writer method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_response">send_response() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen.send_signal">send_signal() (subprocess.Popen method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.sendall">sendall() (socket.socket method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.sendcmd">sendcmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.sendfile">sendfile() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.sendmail">sendmail() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.sendto">sendto() (socket.socket method)</a>
</li>
      <li><a href="library/os.html#os.sep">sep (in module os)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Separator">Separator() (in module FrameWork)</a>
</li>
      <li><a href="glossary.html#term-sequence"><strong>sequence</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-32">item</a>
</li>
        <li><a href="library/stdtypes.html#index-20">iteration</a>
</li>
        <li><a href="c-api/concrete.html#index-1">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/compound_stmts.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-17">[3]</a>, <a href="reference/datamodel.html#index-56">[4]</a>, <a href="reference/expressions.html#index-32">[5]</a>, <a href="reference/expressions.html#index-35">[6]</a>, <a href="reference/expressions.html#index-67">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="library/stdtypes.html#index-29">types, mutable</a>
</li>
        <li><a href="library/stdtypes.html#index-22">types, operations on</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Sequence">Sequence (class in collections)</a>
</li>
      <li><a href="library/msilib.html#msilib.sequence">sequence (in module msilib)</a>
</li>
      <li><a href="library/parser.html#parser.sequence2st">sequence2st() (in module parser)</a>
</li>
      <li><a href="library/operator.html#operator.sequenceIncludes">sequenceIncludes() (in module operator)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher">SequenceMatcher (class in difflib)</a>, <a href="library/difflib.html#difflib.SequenceMatcher">[1]</a>
</li>
      <li><a href="library/cookie.html#Cookie.SerialCookie">SerialCookie (class in Cookie)</a>
</li>
      <li>
    serializing

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.serve_forever">serve_forever() (SocketServer.BaseServer method)</a>
</li>
      <li>
    server

      <ul>
        <li><a href="library/basehttpserver.html#index-0">WWW</a>, <a href="library/cgi.html#index-0">[1]</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.server">server (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_activate">server_activate() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_address">server_address (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_bind">server_bind() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_close">server_close() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.server_software">server_software (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.server_version">server_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.server_version">(SimpleHTTPServer.SimpleHTTPRequestHandler attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy">ServerProxy (class in xmlrpclib)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.session_stats">session_stats() (ssl.SSLContext method)</a>
</li>
      <li>
    set

      <ul>
        <li><a href="reference/expressions.html#index-18">display</a>
</li>
        <li><a href="c-api/set.html#index-0">object</a>, <a href="library/stdtypes.html#index-31">[1]</a>, <a href="reference/datamodel.html#index-30">[2]</a>, <a href="reference/expressions.html#index-18">[3]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#set">set (built-in class)</a>
</li>
      <li><a href="library/collections.html#collections.Set">Set (class in collections)</a>

      <ul>
        <li><a href="library/sets.html#sets.Set">(class in sets)</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-4">Set Breakpoint</a>
</li>
      <li>
    set type

      <ul>
        <li><a href="reference/datamodel.html#index-29">object</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.set">set() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.SafeConfigParser.set">(ConfigParser.SafeConfigParser method)</a>
</li>
        <li><a href="library/cookie.html#Cookie.Morsel.set">(Cookie.Morsel method)</a>
</li>
        <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.set">(EasyDialogs.ProgressBar method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.set">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/test.html#test.support.EnvironmentVarGuard.set">(test.support.EnvironmentVarGuard method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.set">(threading.Event method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Combobox.set">(ttk.Combobox method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.set">(ttk.Treeview method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="c-api/intro.html#index-8">set_all()</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.set_allowed_domains">set_allowed_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_alpn_protocols">set_alpn_protocols() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer.set_app">set_app() (wsgiref.simple_server.WSGIServer method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.set_authorizer">set_authorizer() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.set_blocked_domains">set_blocked_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_boundary">set_boundary() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_break">set_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_charset">set_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.set_children">set_children() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_ciphers">set_ciphers() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/readline.html#readline.set_completer">set_completer() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.set_completer_delims">set_completer_delims() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.set_completion_display_matches_hook">set_completion_display_matches_hook() (in module readline)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_continue">set_continue() (bdb.Bdb method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_conversion_mode">set_conversion_mode() (in module ctypes)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_cookie">set_cookie() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_cookie_if_ok">set_cookie_if_ok() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Feature.set_current">set_current() (msilib.Feature method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_date">set_date() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/gc.html#gc.set_debug">set_debug() (in module gc)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.set_debuglevel">set_debuglevel() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPConnection.set_debuglevel">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.set_debuglevel">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.set_debuglevel">(poplib.POP3 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.set_debuglevel">(smtplib.SMTP method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.set_debuglevel">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.set_default_type">set_default_type() (email.message.Message method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_default_verify_paths">set_default_verify_paths() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.set_defaults">set_defaults() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.set_defaults">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_ecdh_curve">set_ecdh_curve() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_errno">set_errno() (in module ctypes)</a>
</li>
      <li><a href="library/fl.html#fl.set_event_call_back">set_event_call_back() (in module fl)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.set_executable">set_executable() (in module multiprocessing)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_executables">set_executables() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_flags">set_flags() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.set_flags">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.set_flags">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.set_form_position">set_form_position() (fl.form method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage.set_from">set_from() (mailbox.mboxMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.set_from">(mailbox.MMDFMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.set_graphics_mode">set_graphics_mode() (in module fl)</a>
</li>
      <li><a href="library/readline.html#readline.set_history_length">set_history_length() (in module readline)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_include_dirs">set_include_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_info">set_info() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.set_labels">set_labels() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_last_error">set_last_error() (in module ctypes)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_libraries">set_libraries() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_library_dirs">set_library_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/dis.html#opcode-SET_LINENO">SET_LINENO (opcode)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_link_objects">set_link_objects() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-set_literal">set_literal (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.set_location">set_location() (bsddb.bsddbobject method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_next">set_next() (bdb.Bdb method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.set_nonstandard_attr">set_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_npn_protocols">set_npn_protocols() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.set_ok">set_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.set_option_negotiation_callback">set_option_negotiation_callback() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.set_output_charset">set_output_charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_param">set_param() (email.message.Message method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.set_pasv">set_pasv() (ftplib.FTP method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_payload">set_payload() (email.message.Message method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_policy">set_policy() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.set_position">set_position() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/readline.html#readline.set_pre_input_hook">set_pre_input_hook() (in module readline)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.set_progress_handler">set_progress_handler() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.set_proxy">set_proxy() (urllib2.Request method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.set_python_build">set_python_build() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_quit">set_quit() (bdb.Bdb method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.set_recsrc">set_recsrc() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_return">set_return() (bdb.Bdb method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_runtime_library_dirs">set_runtime_library_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seq1">set_seq1() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seq2">set_seq2() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seqs">set_seqs() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH.set_sequences">set_sequences() (mailbox.MH method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MHMessage.set_sequences">(mailbox.MHMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_documentation">set_server_documentation() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_documentation">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_name">set_server_name() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_name">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_title">set_server_title() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_title">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_servername_callback">set_servername_callback() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.set_spacing">set_spacing() (formatter.formatter method)</a>
</li>
      <li><a href="library/readline.html#readline.set_startup_hook">set_startup_hook() (in module readline)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_step">set_step() (bdb.Bdb method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_subdir">set_subdir() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.set_terminator">set_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/gc.html#gc.set_threshold">set_threshold() (in module gc)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_trace">set_trace() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/bdb.html#bdb.set_trace">(in module bdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.set_trace">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.set_trace">(pdb.Pdb method)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.set_tunnel">set_tunnel() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_type">set_type() (email.message.Message method)</a>
</li>
      <li><a href="library/doctest.html#doctest.set_unittest_reportflags">set_unittest_reportflags() (in module doctest)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_unixfrom">set_unixfrom() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_until">set_until() (bdb.Bdb method)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.set_url">set_url() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.set_usage">set_usage() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.set_userptr">set_userptr() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.set_visible">set_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/signal.html#signal.set_wakeup_fd">set_wakeup_fd() (in module signal)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setacl">setacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setannotation">setannotation() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.setarrowcursor">setarrowcursor() (in module FrameWork)</a>
</li>
      <li><a href="library/functions.html#setattr">setattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttribute">setAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNode">setAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNodeNS">setAttributeNodeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNS">setAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.SetBase">SetBase() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.setblocking">setblocking() (socket.socket method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setByteStream">setByteStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/tty.html#tty.setcbreak">setcbreak() (in module tty)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setCharacterStream">setCharacterStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="c-api/init.html#index-14">setcheckinterval() (in module sys)</a>, <a href="library/sys.html#sys.setcheckinterval">[1]</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setcomptype">setcomptype() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setcomptype">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setcomptype">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setContentHandler">setContentHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/decimal.html#decimal.setcontext">setcontext() (in module decimal)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.setcontext">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.SetCreatorAndType">SetCreatorAndType() (in module MacOS)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.setcurrent">setcurrent() (mhlib.Folder method)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.setDaemon">setDaemon() (threading.Thread method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.setdefault">setdefault() (dict method)</a>
</li>
      <li><a href="library/sys.html#sys.setdefaultencoding">setdefaultencoding() (in module sys)</a>
</li>
      <li><a href="library/socket.html#socket.setdefaulttimeout">setdefaulttimeout() (in module socket)</a>
</li>
      <li><a href="library/sys.html#sys.setdlopenflags">setdlopenflags() (in module sys)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.setDocumentLocator">setDocumentLocator() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setDTDHandler">setDTDHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.setegid">setegid() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setEncoding">setEncoding() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setEntityResolver">setEntityResolver() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setErrorHandler">setErrorHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.seteuid">seteuid() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setFeature">setFeature() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/calendar.html#calendar.setfirstweekday">setfirstweekday() (in module calendar)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.setfmt">setfmt() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.setFormatter">setFormatter() (logging.Handler method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setframerate">setframerate() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setframerate">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setframerate">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.setgid">setgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setgroups">setgroups() (in module os)</a>
</li>
      <li><a href="library/turtle.html#turtle.seth">seth() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.setheading">setheading() (in module turtle)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetInteger">SetInteger() (msilib.Record method)</a>
</li>
      <li><a href="library/operator.html#operator.setitem">setitem() (in module operator)</a>
</li>
      <li><a href="library/signal.html#signal.setitimer">setitimer() (in module signal)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.setlast">setlast() (mhlib.Folder method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.setLevel">setLevel() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.setLevel">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.setliteral">setliteral() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/locale.html#locale.setlocale">setlocale() (in module locale)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setLocale">setLocale() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/logging.html#logging.setLoggerClass">setLoggerClass() (in module logging)</a>
</li>
      <li><a href="library/syslog.html#syslog.setlogmask">setlogmask() (in module syslog)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setmark">setmark() (aifc.aifc method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler.setMaxConns">setMaxConns() (urllib2.CacheFTPHandler method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.setmode">setmode() (in module msvcrt)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.setName">setName() (threading.Thread method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setnchannels">setnchannels() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setnchannels">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setnchannels">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.setnframes">setnframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setnframes">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setnframes">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.setnomoretags">setnomoretags() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/jpeg.html#jpeg.setoption">setoption() (in module jpeg)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.SetParamEntityParsing">SetParamEntityParsing() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.setparameters">setparameters() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setparams">setparams() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/al.html#al.setparams">(in module al)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.setparams">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setparams">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.setpassword">setpassword() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/fm.html#fm.setpath">setpath() (in module fm)</a>
</li>
      <li><a href="library/os.html#os.setpgid">setpgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setpgrp">setpgrp() (in module os)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setpos">setpos() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.setpos">(in module turtle)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.setpos">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.setpos">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.setposition">setposition() (in module turtle)</a>
</li>
      <li><a href="library/sys.html#sys.setprofile">setprofile() (in module sys)</a>

      <ul>
        <li><a href="library/threading.html#threading.setprofile">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.SetProperty">SetProperty() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setProperty">setProperty() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setPublicId">setPublicId() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setquota">setquota() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/tty.html#tty.setraw">setraw() (in module tty)</a>
</li>
      <li><a href="library/sys.html#sys.setrecursionlimit">setrecursionlimit() (in module sys)</a>
</li>
      <li><a href="library/os.html#os.setregid">setregid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setresgid">setresgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setresuid">setresuid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setreuid">setreuid() (in module os)</a>
</li>
      <li><a href="library/resource.html#resource.setrlimit">setrlimit() (in module resource)</a>
</li>
      <li><a href="library/sets.html#module-sets">sets (module)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setsampwidth">setsampwidth() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setsampwidth">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setsampwidth">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.setscrreg">setscrreg() (curses.window method)</a>
</li>
      <li><a href="library/os.html#os.setsid">setsid() (in module os)</a>
</li>
      <li><a href="library/operator.html#operator.setslice">setslice() (in module operator)</a>
</li>
      <li><a href="library/socket.html#socket.socket.setsockopt">setsockopt() (socket.socket method)</a>
</li>
      <li><a href="library/random.html#random.setstate">setstate() (in module random)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetStream">SetStream() (msilib.Record method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetString">SetString() (msilib.Record method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setSystemId">setSystemId() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/curses.html#curses.setsyx">setsyx() (in module curses)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.setTarget">setTarget() (logging.handlers.MemoryHandler method)</a>
</li>
      <li><a href="library/turtle.html#turtle.settiltangle">settiltangle() (in module turtle)</a>
</li>
      <li><a href="library/socket.html#socket.socket.settimeout">settimeout() (socket.socket method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler.setTimeout">setTimeout() (urllib2.CacheFTPHandler method)</a>
</li>
      <li><a href="library/sys.html#sys.settrace">settrace() (in module sys)</a>

      <ul>
        <li><a href="library/threading.html#threading.settrace">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.settscdump">settscdump() (in module sys)</a>
</li>
      <li><a href="library/ic.html#ic.IC.settypecreator">settypecreator() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.settypecreator">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.setuid">setuid() (in module os)</a>
</li>
      <li><a href="library/turtle.html#turtle.setundobuffer">setundobuffer() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.setup">setup() (in module distutils.core)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.setup">(SocketServer.BaseRequestHandler method)</a>
</li>
        <li><a href="library/turtle.html#turtle.setup">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.setUp">setUp() (unittest.TestCase method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.setup_environ">setup_environ() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_EXCEPT">SETUP_EXCEPT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_FINALLY">SETUP_FINALLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_LOOP">SETUP_LOOP (opcode)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.setup_testing_defaults">setup_testing_defaults() (in module wsgiref.util)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_WITH">SETUP_WITH (opcode)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.setUpClass">setUpClass() (unittest.TestCase method)</a>
</li>
      <li><a href="library/curses.html#curses.setupterm">setupterm() (in module curses)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SetValue">SetValue() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SetValueEx">SetValueEx() (in module _winreg)</a>
</li>
      <li><a href="c-api/file.html#index-4">setvbuf()</a>
</li>
      <li><a href="library/framework.html#FrameWork.setwatchcursor">setwatchcursor() (in module FrameWork)</a>
</li>
      <li><a href="library/turtle.html#turtle.setworldcoordinates">setworldcoordinates() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.setx">setx() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.sety">sety() (in module turtle)</a>
</li>
      <li><a href="library/stat.html#stat.SF_APPEND">SF_APPEND (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_ARCHIVED">SF_ARCHIVED (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_IMMUTABLE">SF_IMMUTABLE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_NOUNLINK">SF_NOUNLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_SNAPSHOT">SF_SNAPSHOT (in module stat)</a>
</li>
      <li><a href="library/sgmllib.html#index-0">SGML</a>
</li>
      <li>
    sgmllib

      <ul>
        <li><a href="library/htmllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#module-sgmllib">sgmllib (module)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParseError">SGMLParseError</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser">SGMLParser (class in sgmllib)</a>

      <ul>
        <li><a href="library/htmllib.html#index-1">(in module sgmllib)</a>
</li>
      </ul></li>
      <li><a href="library/sha.html#module-sha">sha (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.Shape">Shape (class in turtle)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.shape">shape (memoryview attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.shape">shape() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.shapesize">shapesize() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.shared_object_filename">shared_object_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/shelve.html#shelve.Shelf">Shelf (class in shelve)</a>
</li>
      <li>
    shelve

      <ul>
        <li><a href="library/marshal.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/shelve.html#module-shelve">shelve (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.shift">shift() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.shift">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.shift_path_info">shift_path_info() (in module wsgiref.util)</a>
</li>
      <li>
    shifting

      <ul>
        <li><a href="reference/expressions.html#index-58">operation</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex">shlex (class in shlex)</a>

      <ul>
        <li><a href="library/shlex.html#module-shlex">(module)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.shortDescription">shortDescription() (unittest.TestCase method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.shouldFlush">shouldFlush() (logging.handlers.BufferingHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.shouldFlush">(logging.handlers.MemoryHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestResult.shouldStop">shouldStop (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.show">show() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/fl.html#fl.show_choice">show_choice() (in module fl)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.show_compilers">show_compilers() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/fl.html#fl.show_file_selector">show_file_selector() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.form.show_form">show_form() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.show_input">show_input() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.show_message">show_message() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.show_question">show_question() (in module fl)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter.showsyntaxerror">showsyntaxerror() (code.InteractiveInterpreter method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/code.html#code.InteractiveInterpreter.showtraceback">showtraceback() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="library/turtle.html#turtle.showturtle">showturtle() (in module turtle)</a>
</li>
      <li><a href="library/warnings.html#warnings.showwarning">showwarning() (in module warnings)</a>
</li>
      <li><a href="library/random.html#random.shuffle">shuffle() (in module random)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.shutdown">shutdown() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.shutdown">(SocketServer.BaseServer method)</a>
</li>
        <li><a href="library/macostools.html#findertools.shutdown">(in module findertools)</a>
</li>
        <li><a href="library/logging.html#logging.shutdown">(in module logging)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.shutdown">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.shutdown">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#module-shutil">shutil (module)</a>
</li>
      <li><a href="library/signal.html#signal.SIG_DFL">SIG_DFL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.SIG_IGN">SIG_IGN (in module signal)</a>
</li>
      <li><a href="c-api/exceptions.html#index-2">SIGINT</a>, <a href="c-api/exceptions.html#index-3">[1]</a>
</li>
      <li><a href="library/signal.html#signal.siginterrupt">siginterrupt() (in module signal)</a>
</li>
      <li>
    signal

      <ul>
        <li><a href="c-api/exceptions.html#index-2">module</a>, <a href="library/thread.html#index-2">[1]</a>
</li>
      </ul></li>
      <li><a href="library/signal.html#module-signal">signal (module)</a>
</li>
      <li><a href="library/signal.html#signal.signal">signal() (in module signal)</a>
</li>
      <li>
    simple

      <ul>
        <li><a href="reference/simple_stmts.html#index-0">statement</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#index-0">Simple Mail Transfer Protocol</a>
</li>
      <li><a href="library/cookie.html#Cookie.SimpleCookie">SimpleCookie (class in Cookie)</a>
</li>
      <li><a href="library/warnings.html#warnings.simplefilter">simplefilter() (in module warnings)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.SimpleHandler">SimpleHandler (class in wsgiref.handlers)</a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler">SimpleHTTPRequestHandler (class in SimpleHTTPServer)</a>
</li>
      <li>
    SimpleHTTPServer

      <ul>
        <li><a href="library/basehttpserver.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/simplehttpserver.html#module-SimpleHTTPServer">SimpleHTTPServer (module)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler">SimpleXMLRPCRequestHandler (class in SimpleXMLRPCServer)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer">SimpleXMLRPCServer (class in SimpleXMLRPCServer)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#module-SimpleXMLRPCServer">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.sin">sin() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.sin">(in module math)</a>
</li>
      </ul></li>
      <li>
    singleton

      <ul>
        <li><a href="reference/datamodel.html#index-24">tuple</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.sinh">sinh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.sinh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/site.html#module-site">site (module)</a>
</li>
      <li>
    site command line option

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-base">--user-base</a>
</li>
        <li><a href="library/site.html#cmdoption-site-user-site">--user-site</a>
</li>
      </ul></li>
      <li>
    site-packages

      <ul>
        <li><a href="library/site.html#index-1">directory</a>
</li>
      </ul></li>
      <li>
    site-python

      <ul>
        <li><a href="library/site.html#index-1">directory</a>
</li>
      </ul></li>
      <li>
    sitecustomize

      <ul>
        <li><a href="library/site.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/struct.html#struct.Struct.size">size (struct.Struct attribute)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.size">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.size">size() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/mmap.html#mmap.mmap.size">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Sized">Sized (class in collections)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.sizeof">sizeof() (in module ctypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.SKIP">SKIP (in module doctest)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.skip">skip() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.skip">(in module unittest)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.skipIf">skipIf() (in module unittest)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.skipinitialspace">skipinitialspace (csv.Dialect attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.skipped">skipped (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.skippedEntity">skippedEntity() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/unittest.html#unittest.SkipTest">SkipTest</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.skipTest">skipTest() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.skipUnless">skipUnless() (in module unittest)</a>
</li>
      <li><a href="library/token.html#token.SLASH">SLASH (in module token)</a>
</li>
      <li><a href="library/token.html#token.SLASHEQUAL">SLASHEQUAL (in module token)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.slave">slave() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/macostools.html#findertools.sleep">sleep() (in module findertools)</a>

      <ul>
        <li><a href="library/time.html#time.sleep">(in module time)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-34">slice</a>, <a href="glossary.html#term-slice"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/dis.html#index-0">built-in function</a>, <a href="library/types.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-69">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-89">object</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#slice">slice (built-in class)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+0">SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+1">SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+2">SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+3">SLICE+3 (opcode)</a>
</li>
      <li><a href="c-api/slice.html#index-0">SliceType (in module types)</a>, <a href="library/types.html#types.SliceType">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-18">slicing</a>, <a href="reference/datamodel.html#index-25">[1]</a>, <a href="reference/expressions.html#index-34">[2]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-13">assignment</a>
</li>
        <li><a href="reference/expressions.html#index-36">extended</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.SmartCookie">SmartCookie (class in Cookie)</a>
</li>
      <li>
    SMTP

      <ul>
        <li><a href="library/smtplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#smtplib.SMTP">SMTP (class in smtplib)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP_SSL">SMTP_SSL (class in smtplib)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPAuthenticationError">SMTPAuthenticationError</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPConnectError">SMTPConnectError</a>
</li>
      <li><a href="library/smtpd.html#module-smtpd">smtpd (module)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPDataError">SMTPDataError</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPException">SMTPException</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler">SMTPHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPHeloError">SMTPHeloError</a>
</li>
      <li><a href="library/smtplib.html#module-smtplib">smtplib (module)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPRecipientsRefused">SMTPRecipientsRefused</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPResponseException">SMTPResponseException</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPSenderRefused">SMTPSenderRefused</a>
</li>
      <li><a href="library/smtpd.html#smtpd.SMTPServer">SMTPServer (class in smtpd)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPServerDisconnected">SMTPServerDisconnected</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_ALIAS">SND_ALIAS (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_ASYNC">SND_ASYNC (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_FILENAME">SND_FILENAME (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_LOOP">SND_LOOP (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_MEMORY">SND_MEMORY (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NODEFAULT">SND_NODEFAULT (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NOSTOP">SND_NOSTOP (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NOWAIT">SND_NOWAIT (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_PURGE">SND_PURGE (in module winsound)</a>
</li>
      <li><a href="library/sndhdr.html#module-sndhdr">sndhdr (module)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer.sniff">sniff() (csv.Sniffer method)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer">Sniffer (class in csv)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_DGRAM">SOCK_DGRAM (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_RAW">SOCK_RAW (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_RDM">SOCK_RDM (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_SEQPACKET">SOCK_SEQPACKET (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_STREAM">SOCK_STREAM (in module socket)</a>
</li>
      <li>
    socket

      <ul>
        <li><a href="library/internet.html#index-1">module</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/socket.html#index-1">object</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#module-socket">socket (module)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.socket">(SocketServer.BaseServer attribute)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.socket">socket() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/select.html#index-0">(in module socket)</a>, <a href="library/socket.html#socket.socket">[1]</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.socket_type">socket_type (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler">SocketHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socket.html#socket.socketpair">socketpair() (in module socket)</a>
</li>
      <li><a href="library/socketserver.html#module-SocketServer">SocketServer (module)</a>
</li>
      <li><a href="library/socket.html#socket.SocketType">SocketType (in module socket)</a>
</li>
      <li><a href="c-api/file.html#index-5">softspace (file attribute)</a>, <a href="library/stdtypes.html#file.softspace">[1]</a>
</li>
      <li><a href="library/socket.html#socket.SOMAXCONN">SOMAXCONN (in module socket)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.sort">sort() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.sort_stats">sort_stats() (pstats.Stats method)</a>
</li>
      <li><a href="library/functions.html#sorted">sorted() (built-in function)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.sortTestMethodsUsing">sortTestMethodsUsing (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.source">source (doctest.Example attribute)</a>

      <ul>
        <li><a href="library/shlex.html#shlex.shlex.source">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-4">source character set</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.sourcehook">sourcehook() (shlex.shlex method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">space</a>
</li>
      <li><a href="library/re.html#re.MatchObject.span">span() (re.MatchObject method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.spawn">spawn() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="library/pty.html#pty.spawn">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.spawnl">spawnl() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnle">spawnle() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnlp">spawnlp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnlpe">spawnlpe() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnv">spawnv() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnve">spawnve() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnvp">spawnvp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnvpe">spawnvpe() (in module os)</a>
</li>
      <li>
    special

      <ul>
        <li><a href="reference/datamodel.html#index-5">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-5">attribute, generic</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-special-method"><strong>special method</strong></a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.specified_attributes">specified_attributes (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.speed">speed() (in module turtle)</a>

      <ul>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.speed">(ossaudiodev.oss_audio_device method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.splash">splash() (in module MacOS)</a>
</li>
      <li><a href="library/os.path.html#os.path.split">split() (in module os.path)</a>

      <ul>
        <li><a href="library/re.html#re.split">(in module re)</a>
</li>
        <li><a href="library/shlex.html#shlex.split">(in module shlex)</a>
</li>
        <li><a href="library/string.html#string.split">(in module string)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.split">(re.RegexObject method)</a>
</li>
        <li><a href="library/stdtypes.html#str.split">(str method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.split_quoted">split_quoted() (in module distutils.util)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitdrive">splitdrive() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitext">splitext() (in module os.path)</a>
</li>
      <li><a href="library/string.html#string.splitfields">splitfields() (in module string)</a>
</li>
      <li><a href="library/stdtypes.html#str.splitlines">splitlines() (str method)</a>

      <ul>
        <li><a href="library/stdtypes.html#unicode.splitlines">(unicode method)</a>
</li>
      </ul></li>
      <li><a href="library/urlparse.html#urlparse.SplitResult">SplitResult (class in urlparse)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitunc">splitunc() (in module os.path)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.SpooledTemporaryFile">SpooledTemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">sprintf-style formatting</a>
</li>
      <li><a href="library/spwd.html#module-spwd">spwd (module)</a>
</li>
      <li><a href="library/sqlite3.html#module-sqlite3">sqlite3 (module)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.sqlite_version">sqlite_version (in module sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.sqlite_version_info">sqlite_version_info (in module sqlite3)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.sqrt">sqrt() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.sqrt">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.sqrt">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.sqrt">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#index-1">SSL</a>
</li>
      <li><a href="library/ssl.html#module-ssl">ssl (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_SSL.ssl">ssl() (imaplib.IMAP4_SSL method)</a>
</li>
      <li><a href="library/ssl.html#index-18">SSL_CERT_FILE</a>
</li>
      <li><a href="library/ssl.html#index-19">SSL_CERT_PATH</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.ssl_version">ssl_version (ftplib.FTP_TLS attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext">SSLContext (class in ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLEOFError">SSLEOFError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLError">SSLError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSyscallError">SSLSyscallError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLWantReadError">SSLWantReadError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLWantWriteError">SSLWantWriteError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLZeroReturnError">SSLZeroReturnError</a>
</li>
      <li><a href="library/turtle.html#turtle.st">st() (in module turtle)</a>
</li>
      <li><a href="library/parser.html#parser.st2list">st2list() (in module parser)</a>
</li>
      <li><a href="library/parser.html#parser.st2tuple">st2tuple() (in module parser)</a>
</li>
      <li><a href="library/stat.html#stat.ST_ATIME">ST_ATIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_CTIME">ST_CTIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_DEV">ST_DEV (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_GID">ST_GID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_INO">ST_INO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_MODE">ST_MODE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_MTIME">ST_MTIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_NLINK">ST_NLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_SIZE">ST_SIZE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_UID">ST_UID (in module stat)</a>
</li>
      <li>
    stack

      <ul>
        <li><a href="reference/datamodel.html#index-67">execution</a>
</li>
        <li><a href="reference/datamodel.html#index-67">trace</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-3">stack viewer</a>
</li>
      <li><a href="library/inspect.html#inspect.stack">stack() (in module inspect)</a>
</li>
      <li><a href="library/thread.html#thread.stack_size">stack_size() (in module thread)</a>

      <ul>
        <li><a href="library/threading.html#threading.stack_size">(in module threading)</a>
</li>
      </ul></li>
      <li>
    stackable

      <ul>
        <li><a href="library/codecs.html#index-0">streams</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.stamp">stamp() (in module turtle)</a>
</li>
      <li>
    standard

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">output</a>, <a href="reference/simple_stmts.html#index-24">[1]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-15">Standard C</a>
</li>
      <li><a href="reference/toplevel_components.html#index-4">standard input</a>
</li>
      <li><a href="library/base64.html#base64.standard_b64decode">standard_b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.standard_b64encode">standard_b64encode() (in module base64)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.StandardError">StandardError</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-standarderror">standarderror (2to3 fixer)</a>
</li>
      <li><a href="library/curses.html#curses.window.standend">standend() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.standout">standout() (curses.window method)</a>
</li>
      <li><a href="library/token.html#token.STAR">STAR (in module token)</a>
</li>
      <li><a href="library/token.html#token.STAREQUAL">STAREQUAL (in module token)</a>
</li>
      <li><a href="library/itertools.html#itertools.starmap">starmap() (in module itertools)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.start">start (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-70">(slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      </ul></li>
      <li><a href="library/hotshot.html#hotshot.Profile.start">start() (hotshot.Profile method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.start">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.start">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/re.html#re.MatchObject.start">(re.MatchObject method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.start">(threading.Thread method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Progressbar.start">(ttk.Progressbar method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.start">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.start_color">start_color() (in module curses)</a>
</li>
      <li><a href="library/msilib.html#msilib.Directory.start_component">start_component() (msilib.Directory method)</a>
</li>
      <li><a href="library/thread.html#thread.start_new_thread">start_new_thread() (in module thread)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.startbody">startbody() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartCdataSectionHandler">StartCdataSectionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler">StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startDocument">startDocument() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startElement">startElement() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartElementHandler">StartElementHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startElementNS">startElementNS() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTF_USESHOWWINDOW">STARTF_USESHOWWINDOW (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTF_USESTDHANDLES">STARTF_USESTDHANDLES (in module subprocess)</a>
</li>
      <li><a href="library/os.html#os.startfile">startfile() (in module os)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.startmultipartbody">startmultipartbody() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler">StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startPrefixMapping">startPrefixMapping() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/stdtypes.html#str.startswith">startswith() (str method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.startTest">startTest() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.startTestRun">startTestRun() (unittest.TestResult method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.starttls">starttls() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO">STARTUPINFO (class in subprocess)</a>
</li>
      <li>
    stat

      <ul>
        <li><a href="library/os.html#index-16">module</a>
</li>
      </ul></li>
      <li><a href="library/stat.html#module-stat">stat (module)</a>
</li>
      <li><a href="library/os.html#os.stat">stat() (in module os)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.stat">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.stat">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.stat_float_times">stat_float_times() (in module os)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget.state">state() (ttk.Widget method)</a>
</li>
      <li><a href="glossary.html#term-statement"><strong>statement</strong></a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-21">*</a>, <a href="tutorial/controlflow.html#index-2">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">**</a>, <a href="tutorial/controlflow.html#index-3">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-19">@</a>
</li>
        <li><a href="library/exceptions.html#index-2">assert</a>, <a href="reference/simple_stmts.html#index-15">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">assignment</a>, <a href="reference/simple_stmts.html#index-3">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-14">assignment, augmented</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">break</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-33">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">class</a>
</li>
        <li><a href="reference/compound_stmts.html#index-0">compound</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">continue</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">def</a>
</li>
        <li><a href="library/stdtypes.html#index-30">del</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-75">[2]</a>, <a href="reference/simple_stmts.html#index-18">[3]</a>
</li>
        <li><a href="library/exceptions.html#index-0">except</a>
</li>
        <li><a href="library/stdtypes.html#index-41">exec</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>, <a href="reference/simple_stmts.html#index-56">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-1">expression</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">for</a>, <a href="reference/simple_stmts.html#index-33">[1]</a>, <a href="reference/simple_stmts.html#index-37">[2]</a>, <a href="tutorial/controlflow.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-0">[4]</a>
</li>
        <li><a href="reference/executionmodel.html#index-9">from</a>
</li>
        <li><a href="reference/simple_stmts.html#index-52">future</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">global</a>, <a href="reference/simple_stmts.html#index-54">[1]</a>, <a href="reference/simple_stmts.html#index-7">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-2">if</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>
</li>
        <li><a href="library/functions.html#index-8">import</a>, <a href="library/imp.html#index-0">[1]</a>, <a href="library/imputil.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-47">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-4">loop</a>, <a href="reference/compound_stmts.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-17">pass</a>
</li>
        <li><a href="library/stdtypes.html#index-1">print</a>, <a href="reference/datamodel.html#index-78">[1]</a>, <a href="reference/simple_stmts.html#index-22">[2]</a>
</li>
        <li><a href="library/exceptions.html#index-1">raise</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">return</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/simple_stmts.html#index-26">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-0">simple</a>
</li>
        <li><a href="library/exceptions.html#index-0">try</a>, <a href="reference/compound_stmts.html#index-10">[1]</a>, <a href="reference/datamodel.html#index-68">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-2">while</a>, <a href="reference/compound_stmts.html#index-4">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-15">with</a>, <a href="reference/datamodel.html#index-96">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-28">yield</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-7">statement grouping</a>
</li>
      <li>
    staticmethod

      <ul>
        <li><a href="c-api/structures.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#staticmethod">staticmethod() (built-in function)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats">Stats (class in pstats)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.status">status (httplib.HTTPResponse attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.status">status() (imaplib.IMAP4 method)</a>
</li>
      <li>
    statvfs

      <ul>
        <li><a href="library/os.html#index-17">module</a>
</li>
      </ul></li>
      <li><a href="library/statvfs.html#module-statvfs">statvfs (module)</a>
</li>
      <li><a href="library/os.html#os.statvfs">statvfs() (in module os)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_ERROR_HANDLE">STD_ERROR_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_INPUT_HANDLE">STD_INPUT_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_OUTPUT_HANDLE">STD_OUTPUT_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/tix.html#Tix.StdButtonBox">StdButtonBox (class in Tix)</a>
</li>
      <li><a href="c-api/init.html#index-21">stderr (in module sys)</a>, <a href="library/sys.html#sys.stderr">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stderr">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-21">stdin (in module sys)</a>, <a href="library/sys.html#sys.stdin">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stdin">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-58">stdio</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STDOUT">STDOUT (in module subprocess)</a>
</li>
      <li><a href="c-api/init.html#index-21">stdout (in module sys)</a>, <a href="library/sys.html#sys.stdout">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/simple_stmts.html#index-24">[3]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stdout">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#index-0">Stein, Greg</a>
</li>
      <li><a href="reference/datamodel.html#index-70">step (slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      <li><a href="library/ttk.html#ttk.Progressbar.step">step() (ttk.Progressbar method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.stereocontrols">stereocontrols() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/cd.html#cd.STILL">STILL (in module cd)</a>
</li>
      <li><a href="reference/datamodel.html#index-70">stop (slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile.stop">stop() (hotshot.Profile method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Progressbar.stop">(ttk.Progressbar method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.stop">(unittest.TestResult method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-STOP_CODE">STOP_CODE (opcode)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.stop_here">stop_here() (bdb.Bdb method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.StopIteration">StopIteration</a>

      <ul>
        <li><a href="reference/expressions.html#index-25">exception</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/logging.config.html#logging.config.stopListening">stopListening() (in module logging.config)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.stopTest">stopTest() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.stopTestRun">stopTestRun() (unittest.TestResult method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.storbinary">storbinary() (ftplib.FTP method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.store">store() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.STORE_ACTIONS">STORE_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_ATTR">STORE_ATTR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_DEREF">STORE_DEREF (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_FAST">STORE_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_GLOBAL">STORE_GLOBAL (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_MAP">STORE_MAP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_NAME">STORE_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+0">STORE_SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+1">STORE_SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+2">STORE_SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+3">STORE_SLICE+3 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SUBSCR">STORE_SUBSCR (opcode)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.storlines">storlines() (ftplib.FTP method)</a>
</li>
      <li>
    str

      <ul>
        <li><a href="c-api/object.html#index-3">built-in function</a>, <a href="extending/newtypes.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-78">[2]</a>, <a href="reference/expressions.html#index-21">[3]</a>
</li>
        <li><a href="library/functions.html#index-3">format</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#str">str (built-in class)</a>
</li>
      <li><a href="library/locale.html#locale.str">str() (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.strcoll">strcoll() (in module locale)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.StreamError">StreamError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.StreamHandler">StreamHandler (class in logging)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamReader">StreamReader (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamReaderWriter">StreamReaderWriter (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamRecoder">StreamRecoder (class in codecs)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.StreamRequestHandler">StreamRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/codecs.html#index-0">streams</a>

      <ul>
        <li><a href="library/codecs.html#index-0">stackable</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.StreamWriter">StreamWriter (class in codecs)</a>
</li>
      <li><a href="c-api/exceptions.html#index-1">strerror()</a>

      <ul>
        <li><a href="library/os.html#os.strerror">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.strftime">strftime() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.strftime">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.strftime">(datetime.time method)</a>
</li>
        <li><a href="library/time.html#time.strftime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.strict">strict (csv.Dialect attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_domain">strict_domain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/codecs.html#codecs.strict_errors">strict_errors() (in module codecs)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_domain">strict_ns_domain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_set_initial_dollar">strict_ns_set_initial_dollar (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_set_path">strict_ns_set_path (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_unverifiable">strict_ns_unverifiable (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_rfc2965_unverifiable">strict_rfc2965_unverifiable (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.strides">strides (memoryview attribute)</a>
</li>
      <li>
    string

      <ul>
        <li><a href="reference/lexical_analysis.html#index-14">Unicode</a>
</li>
        <li><a href="reference/datamodel.html#index-22">comparison</a>
</li>
        <li><a href="reference/datamodel.html#index-77">conversion</a>, <a href="reference/expressions.html#index-19">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-25">formatting</a>
</li>
        <li><a href="library/stdtypes.html#index-25">interpolation</a>
</li>
        <li><a href="reference/expressions.html#index-33">item</a>
</li>
        <li><a href="library/stdtypes.html#index-23">methods</a>
</li>
        <li><a href="library/locale.html#index-7">module</a>, <a href="library/locale.html#index-8">[1]</a>, <a href="library/stdtypes.html#index-27">[2]</a>
</li>
        <li><a href="c-api/string.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-21">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.STRING">STRING (in module token)</a>
</li>
      <li><a href="library/string.html#module-string">string (module)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.string">(re.MatchObject attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-12">string literal</a>
</li>
      <li><a href="library/ctypes.html#ctypes.string_at">string_at() (in module ctypes)</a>
</li>
      <li><a href="library/io.html#io.StringIO">StringIO (class in io)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO">(class in StringIO)</a>
</li>
        <li><a href="library/stringio.html#module-StringIO">(module)</a>
</li>
      </ul></li>
      <li><a href="library/stringio.html#cStringIO.StringIO">StringIO() (in module cStringIO)</a>
</li>
      <li><a href="library/stringprep.html#module-stringprep">stringprep (module)</a>
</li>
      <li><a href="tutorial/controlflow.html#index-1">strings, documentation</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="c-api/string.html#index-1">StringType (in module types)</a>, <a href="library/types.html#types.StringType">[1]</a>
</li>
      <li><a href="library/types.html#types.StringTypes">StringTypes (in module types)</a>
</li>
      <li><a href="library/string.html#string.strip">strip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.strip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.strip_dirs">strip_dirs() (pstats.Stats method)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.stripspaces">stripspaces (curses.textpad.Textbox attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.strptime">strptime() (datetime.datetime class method)</a>

      <ul>
        <li><a href="library/time.html#time.strptime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.strtobool">strtobool() (in module distutils.util)</a>
</li>
      <li>
    struct

      <ul>
        <li><a href="library/socket.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="library/struct.html#struct.Struct">Struct (class in struct)</a>
</li>
      <li><a href="library/struct.html#module-struct">struct (module)</a>
</li>
      <li><a href="glossary.html#term-struct-sequence"><strong>struct sequence</strong></a>
</li>
      <li><a href="library/time.html#time.struct_time">struct_time (class in time)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Structure">Structure (class in ctypes)</a>
</li>
      <li>
    structures

      <ul>
        <li><a href="library/struct.html#index-0">C</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.strxfrm">strxfrm() (in module locale)</a>
</li>
      <li><a href="library/parser.html#parser.STType">STType (in module parser)</a>
</li>
      <li>
    style

      <ul>
        <li><a href="tutorial/controlflow.html#index-5">coding</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Style">Style (class in ttk)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.StyledText">StyledText (class in aetypes)</a>
</li>
      <li><a href="library/operator.html#operator.sub">sub() (in module operator)</a>

      <ul>
        <li><a href="library/re.html#re.sub">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.sub">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.sub_commands">sub_commands (distutils.cmd.Command attribute)</a>
</li>
      <li>
    subclassing

      <ul>
        <li><a href="reference/datamodel.html#index-73">immutable types</a>
</li>
      </ul></li>
      <li><a href="library/filecmp.html#filecmp.dircmp.subdirs">subdirs (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement">SubElement() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/framework.html#FrameWork.SubMenu">SubMenu() (in module FrameWork)</a>
</li>
      <li><a href="library/re.html#re.subn">subn() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.subn">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Subnormal">Subnormal (class in decimal)</a>
</li>
      <li><a href="library/curses.html#curses.window.subpad">subpad() (curses.window method)</a>
</li>
      <li><a href="library/subprocess.html#module-subprocess">subprocess (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.subscribe">subscribe() (imaplib.IMAP4 method)</a>
</li>
      <li>
    subscript

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-17">subscription</a>, <a href="reference/datamodel.html#index-25">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/expressions.html#index-31">[3]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-10">assignment</a>
</li>
      </ul></li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.subsequent_indent">subsequent_indent (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.subst_vars">subst_vars() (in module distutils.util)</a>
</li>
      <li><a href="library/string.html#string.Template.substitute">substitute() (string.Template method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.subtract">subtract() (collections.Counter method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.subtract">(decimal.Context method)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-57">subtraction</a>
</li>
      <li><a href="library/sys.html#sys.subversion">subversion (in module sys)</a>
</li>
      <li><a href="library/curses.html#curses.window.subwin">subwin() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.successful">successful() (multiprocessing.pool.AsyncResult method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.suffix_map">suffix_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.suffix_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/compound_stmts.html#index-1">suite</a>
</li>
      <li><a href="library/parser.html#parser.suite">suite() (in module parser)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.suiteClass">suiteClass (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/functions.html#sum">sum() (built-in function)</a>
</li>
      <li><a href="c-api/intro.html#index-10">sum_list()</a>
</li>
      <li><a href="c-api/intro.html#index-11">sum_sequence()</a>, <a href="c-api/intro.html#index-16">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.summarize">summarize() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/sunau.html#module-sunau">sunau (module)</a>
</li>
      <li>
    SUNAUDIODEV

      <ul>
        <li><a href="library/sunaudio.html#index-1">module</a>
</li>
      </ul></li>
      <li>
    sunaudiodev

      <ul>
        <li><a href="library/sunaudio.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/sunaudio.html#module-SUNAUDIODEV">SUNAUDIODEV (module)</a>
</li>
      <li><a href="library/sunaudio.html#module-sunaudiodev">sunaudiodev (module)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.Class.super">super (pyclbr.Class attribute)</a>
</li>
      <li><a href="library/functions.html#super">super() (built-in function)</a>
</li>
      <li><a href="library/os.path.html#os.path.supports_unicode_filenames">supports_unicode_filenames (in module os.path)</a>
</li>
      <li>
    suppression

      <ul>
        <li><a href="reference/simple_stmts.html#index-23">newline</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.SW_HIDE">SW_HIDE (in module subprocess)</a>
</li>
      <li><a href="library/string.html#string.swapcase">swapcase() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.swapcase">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#dl.dl.sym">sym() (dl.dl method)</a>
</li>
      <li><a href="library/symbol.html#symbol.sym_name">sym_name (in module symbol)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol">Symbol (class in symtable)</a>
</li>
      <li><a href="library/symbol.html#module-symbol">symbol (module)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable">SymbolTable (class in symtable)</a>
</li>
      <li><a href="library/os.html#os.symlink">symlink() (in module os)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.symmetric_difference">symmetric_difference() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.symmetric_difference_update">symmetric_difference_update() (frozenset method)</a>
</li>
      <li><a href="library/symtable.html#module-symtable">symtable (module)</a>
</li>
      <li><a href="library/symtable.html#symtable.symtable">symtable() (in module symtable)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.sync">sync() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.sync">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.dumbdbm.sync">(dumbdbm.dumbdbm method)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.sync">(in module gdbm)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.sync">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/shelve.html#shelve.Shelf.sync">(shelve.Shelf method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.syncdown">syncdown() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.synchronized">synchronized() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager">SyncManager (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/curses.html#curses.window.syncok">syncok() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.syncup">syncup() (curses.window method)</a>
</li>
      <li><a href="reference/expressions.html#index-2">syntax</a>, <a href="reference/introduction.html#index-0">[1]</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.SyntaxErr">SyntaxErr</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SyntaxError">SyntaxError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SyntaxWarning">SyntaxWarning</a>
</li>
      <li>
    sys

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/simple_stmts.html#index-24">[4]</a>, <a href="reference/toplevel_components.html#index-2">[5]</a>, <a href="tutorial/modules.html#index-4">[6]</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#module-sys">sys (module)</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.exc_info</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.exc_traceback</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.last_traceback</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">sys.meta_path</a>
</li>
      <li><a href="reference/simple_stmts.html#index-40">sys.modules</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path_hooks</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path_importer_cache</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stderr</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stdin</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stdout</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-sys_exc">sys_exc (2to3 fixer)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.sys_version">sys_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/macos.html#MacOS.SysBeep">SysBeep() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.sysconf">sysconf() (in module os)</a>
</li>
      <li><a href="library/os.html#os.sysconf_names">sysconf_names (in module os)</a>
</li>
      <li><a href="library/sysconfig.html#module-sysconfig">sysconfig (module)</a>
</li>
      <li><a href="library/syslog.html#module-syslog">syslog (module)</a>
</li>
      <li><a href="library/syslog.html#syslog.syslog">syslog() (in module syslog)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler">SysLogHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/os.html#os.system">system() (in module os)</a>

      <ul>
        <li><a href="library/platform.html#platform.system">(in module platform)</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.system_alias">system_alias() (in module platform)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SystemError">SystemError</a>

      <ul>
        <li><a href="c-api/module.html#index-4">(built-in exception)</a>, <a href="c-api/module.html#index-5">[1]</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.SystemExit">SystemExit</a>

      <ul>
        <li><a href="reference/executionmodel.html#index-15">(built-in exception)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.systemId">systemId (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/random.html#random.SystemRandom">SystemRandom (class in random)</a>
</li>
      <li><a href="library/subprocess.html#index-3">SystemRoot</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ ��r3O3Ohtml/genindex-Symbols.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-Symbols.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; Symbols</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    !=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    %

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#index-25">% formatting</a>
</li>
      <li><a href="library/stdtypes.html#index-25">% interpolation</a>
</li>
      <li>
    %=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="using/windows.html#index-1">%PATH%</a>
</li>
      <li>
    &amp;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &amp;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    *

      <ul>
        <li><a href="reference/expressions.html#index-40">in function calls</a>
</li>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">statement</a>, <a href="tutorial/controlflow.html#index-2">[1]</a>
</li>
      </ul></li>
      <li>
    **

      <ul>
        <li><a href="reference/expressions.html#index-41">in function calls</a>
</li>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">statement</a>, <a href="tutorial/controlflow.html#index-3">[1]</a>
</li>
      </ul></li>
      <li>
    **=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    *=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    +

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    +=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    -

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    --help

      <ul>
        <li><a href="using/cmdline.html#cmdoption-help">command line option</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-help">trace command line option</a>
</li>
      </ul></li>
      <li>
    --ignore-dir=&lt;dir&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-ignore-dir">trace command line option</a>
</li>
      </ul></li>
      <li>
    --ignore-module=&lt;mod&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-ignore-module">trace command line option</a>
</li>
      </ul></li>
      <li>
    --user-base

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-base">site command line option</a>
</li>
      </ul></li>
      <li>
    --user-site

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-site">site command line option</a>
</li>
      </ul></li>
      <li>
    --version

      <ul>
        <li><a href="using/cmdline.html#cmdoption-version">command line option</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-version">trace command line option</a>
</li>
      </ul></li>
      <li>
    -3

      <ul>
        <li><a href="using/cmdline.html#cmdoption-3">command line option</a>
</li>
      </ul></li>
      <li>
    -=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    -?

      <ul>
        <li><a href="using/cmdline.html#cmdoption">command line option</a>
</li>
      </ul></li>
      <li>
    -B

      <ul>
        <li><a href="using/cmdline.html#id1">command line option</a>
</li>
      </ul></li>
      <li>
    -b

      <ul>
        <li><a href="using/cmdline.html#cmdoption-b">command line option</a>
</li>
      </ul></li>
      <li>
    -b, --buffer

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-b">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -c &lt;command&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-c">command line option</a>
</li>
      </ul></li>
      <li>
    -c &lt;zipfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-c">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -c, --catch

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-c">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -c, --clock

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-c">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -c, --count

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-c">trace command line option</a>
</li>
      </ul></li>
      <li>
    -C, --coverdir=&lt;dir&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-coverdir">trace command line option</a>
</li>
      </ul></li>
      <li>
    -d

      <ul>
        <li><a href="using/cmdline.html#cmdoption-d">command line option</a>
</li>
      </ul></li>
      <li>
    -d destdir

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-d">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -E

      <ul>
        <li><a href="using/cmdline.html#cmdoption-e">command line option</a>
</li>
      </ul></li>
      <li>
    -e &lt;zipfile&gt; &lt;output_dir&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-e">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -f

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-f">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -f, --failfast

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-f">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -f, --file=&lt;file&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-f">trace command line option</a>
</li>
      </ul></li>
      <li>
    -g, --timing

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-g">trace command line option</a>
</li>
      </ul></li>
      <li>
    -h

      <ul>
        <li><a href="using/cmdline.html#cmdoption-h">command line option</a>
</li>
      </ul></li>
      <li>
    -h, --help

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-h">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -i

      <ul>
        <li><a href="using/cmdline.html#cmdoption-i">command line option</a>
</li>
      </ul></li>
      <li>
    -i list

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-i">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -J

      <ul>
        <li><a href="using/cmdline.html#cmdoption-j">command line option</a>
</li>
      </ul></li>
      <li>
    -l

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-l">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -l &lt;zipfile&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-l">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -l, --listfuncs

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-l">trace command line option</a>
</li>
      </ul></li>
      <li>
    -m &lt;module-name&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-m">command line option</a>
</li>
      </ul></li>
      <li>
    -m, --missing

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-m">trace command line option</a>
</li>
      </ul></li>
      <li>
    -n N, --number=N

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-n">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -O

      <ul>
        <li><a href="using/cmdline.html#cmdoption-o">command line option</a>
</li>
      </ul></li>
      <li>
    -OO

      <ul>
        <li><a href="using/cmdline.html#cmdoption-oo">command line option</a>
</li>
      </ul></li>
      <li>
    -p, --pattern pattern

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-p">unittest-discover command line option</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    -q

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-q">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -Q &lt;arg&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-q">command line option</a>
</li>
      </ul></li>
      <li>
    -R

      <ul>
        <li><a href="using/cmdline.html#cmdoption-r">command line option</a>
</li>
      </ul></li>
      <li>
    -r N, --repeat=N

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-r">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -R, --no-report

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-no-report">trace command line option</a>
</li>
      </ul></li>
      <li>
    -r, --report

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-r">trace command line option</a>
</li>
      </ul></li>
      <li>
    -S

      <ul>
        <li><a href="using/cmdline.html#id2">command line option</a>
</li>
      </ul></li>
      <li>
    -s

      <ul>
        <li><a href="using/cmdline.html#cmdoption-s">command line option</a>
</li>
      </ul></li>
      <li>
    -s S, --setup=S

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-s">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -s, --start-directory directory

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-s">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -s, --summary

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-s">trace command line option</a>
</li>
      </ul></li>
      <li>
    -t

      <ul>
        <li><a href="using/cmdline.html#cmdoption-t">command line option</a>
</li>
      </ul></li>
      <li>
    -t &lt;zipfile&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-t">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -t, --time

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-t">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -t, --top-level-directory directory

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-t">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -t, --trace

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-t">trace command line option</a>
</li>
      </ul></li>
      <li>
    -T, --trackcalls

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-trackcalls">trace command line option</a>
</li>
      </ul></li>
      <li>
    -U

      <ul>
        <li><a href="using/cmdline.html#id4">command line option</a>
</li>
      </ul></li>
      <li>
    -u

      <ul>
        <li><a href="using/cmdline.html#cmdoption-u">command line option</a>
</li>
      </ul></li>
      <li>
    -V

      <ul>
        <li><a href="using/cmdline.html#cmdoption-v">command line option</a>
</li>
      </ul></li>
      <li>
    -v

      <ul>
        <li><a href="using/cmdline.html#id3">command line option</a>
</li>
      </ul></li>
      <li>
    -v, --verbose

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-v">timeit command line option</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-v">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -W arg

      <ul>
        <li><a href="using/cmdline.html#cmdoption-w">command line option</a>
</li>
      </ul></li>
      <li>
    -X

      <ul>
        <li><a href="using/cmdline.html#id5">command line option</a>
</li>
      </ul></li>
      <li>
    -x

      <ul>
        <li><a href="using/cmdline.html#cmdoption-x">command line option</a>
</li>
      </ul></li>
      <li>
    -x regex

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-x">compileall command line option</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-1"><strong>...</strong></a>
</li>
      <li>
    .ini

      <ul>
        <li><a href="library/configparser.html#index-0">file</a>
</li>
      </ul></li>
      <li>
    .pdbrc

      <ul>
        <li><a href="library/pdb.html#index-2">file</a>
</li>
      </ul></li>
      <li><a href="distutils/packageindex.html#index-2">.pypirc file</a>
</li>
      <li>
    .pythonrc.py

      <ul>
        <li><a href="library/user.html#index-0">file</a>
</li>
      </ul></li>
      <li>
    /

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    //

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    //=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    /=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-2to3"><strong>2to3</strong></a>
</li>
      <li>
    &lt;

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &lt;&lt;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &lt;&lt;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    &lt;=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#index-2">&lt;protocol&gt;_proxy</a>
</li>
      <li>
    =

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">assignment statement</a>
</li>
      </ul></li>
      <li>
    ==

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;&gt;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &gt;&gt;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term"><strong>&gt;&gt;&gt;</strong></a>
</li>
      <li>
    @

      <ul>
        <li><a href="reference/compound_stmts.html#index-19">statement</a>
</li>
      </ul></li>
      <li>
    ^

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    ^=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    |

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    |=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    ~

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��w����html/genindex-T.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-T.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; T</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/locale.html#locale.T_FMT">T_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.T_FMT_AMPM">T_FMT_AMPM (in module locale)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">tab</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.tab">tab() (ttk.Notebook method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.TabError">TabError</a>
</li>
      <li><a href="library/tabnanny.html#module-tabnanny">tabnanny (module)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.tabs">tabs() (ttk.Notebook method)</a>
</li>
      <li>
    tabular

      <ul>
        <li><a href="library/csv.html#index-0">data</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag">tag (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_bind">tag_bind() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_configure">tag_configure() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_has">tag_has() (ttk.Treeview method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.tagName">tagName (xml.dom.Element attribute)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail">tail (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="library/itertools.html#itertools.takewhile">takewhile() (in module itertools)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo">TalkTo (class in aetools)</a>
</li>
      <li><a href="library/cmath.html#cmath.tan">tan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.tan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.tanh">tanh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.tanh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarError">TarError</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile">TarFile (class in tarfile)</a>, <a href="library/tarfile.html#tarfile.TarFile">[1]</a>
</li>
      <li><a href="library/tarfile.html#module-tarfile">tarfile (module)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat">TarFileCompat (class in tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat.TAR_GZIPPED">TarFileCompat.TAR_GZIPPED (in module tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat.TAR_PLAIN">TarFileCompat.TAR_PLAIN (in module tarfile)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-5">target</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-18">deletion</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">list</a>, <a href="reference/simple_stmts.html#index-5">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-6">list assignment</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">list, deletion</a>
</li>
        <li><a href="reference/simple_stmts.html#index-35">loop control</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.ProcessingInstruction.target">target (xml.dom.ProcessingInstruction attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo">TarInfo (class in tarfile)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue.task_done">task_done() (multiprocessing.JoinableQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.task_done">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-68">tb_frame (traceback attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_lasti (traceback attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_lineno (traceback attribute)</a>
</li>
      <li><a href="library/traceback.html#traceback.tb_lineno">tb_lineno() (in module traceback)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_next (traceback attribute)</a>
</li>
      <li><a href="library/termios.html#termios.tcdrain">tcdrain() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcflow">tcflow() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcflush">tcflush() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcgetattr">tcgetattr() (in module termios)</a>
</li>
      <li><a href="library/os.html#os.tcgetpgrp">tcgetpgrp() (in module os)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Tcl">Tcl() (in module Tkinter)</a>
</li>
      <li><a href="faq/gui.html#index-0">TCL_LIBRARY</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.TCPServer">TCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/termios.html#termios.tcsendbreak">tcsendbreak() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcsetattr">tcsetattr() (in module termios)</a>
</li>
      <li><a href="library/os.html#os.tcsetpgrp">tcsetpgrp() (in module os)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.tearDown">tearDown() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.tearDownClass">tearDownClass() (unittest.TestCase method)</a>
</li>
      <li><a href="library/itertools.html#itertools.tee">tee() (in module itertools)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.tell">tell() (aifc.aifc method)</a>, <a href="library/aifc.html#aifc.aifc.tell">[1]</a>

      <ul>
        <li><a href="library/bz2.html#bz2.BZ2File.tell">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.tell">(chunk.Chunk method)</a>
</li>
        <li><a href="library/stdtypes.html#file.tell">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.tell">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.tell">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.tell">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.tell">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.tell">(sunau.AU_read method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.tell">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.tell">(wave.Wave_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.tell">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet">Telnet (class in telnetlib)</a>
</li>
      <li><a href="library/telnetlib.html#module-telnetlib">telnetlib (module)</a>
</li>
      <li><a href="library/tempfile.html#index-2">TEMP</a>
</li>
      <li><a href="library/tempfile.html#tempfile.tempdir">tempdir (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#module-tempfile">tempfile (module)</a>
</li>
      <li><a href="library/pipes.html#pipes.Template">Template (class in pipes)</a>

      <ul>
        <li><a href="library/string.html#string.Template">(class in string)</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.template">template (in module tempfile)</a>

      <ul>
        <li><a href="library/string.html#string.Template.template">(string.Template attribute)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.tempnam">tempnam() (in module os)</a>
</li>
      <li>
    temporary

      <ul>
        <li><a href="library/tempfile.html#index-0">file</a>
</li>
        <li><a href="library/tempfile.html#index-0">file name</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.TemporaryFile">TemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/curses.html#index-1">TERM</a>, <a href="library/curses.html#index-2">[1]</a>
</li>
      <li><a href="library/curses.html#curses.termattrs">termattrs() (in module curses)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.terminate">terminate() (multiprocessing.pool.multiprocessing.Pool method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.terminate">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.terminate">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-14">termination model</a>
</li>
      <li><a href="library/termios.html#module-termios">termios (module)</a>
</li>
      <li><a href="library/curses.html#curses.termname">termname() (in module curses)</a>
</li>
      <li>
    ternary

      <ul>
        <li><a href="reference/expressions.html#index-73">operator</a>
</li>
      </ul></li>
      <li>
    test

      <ul>
        <li><a href="reference/expressions.html#index-68">identity</a>
</li>
        <li><a href="reference/expressions.html#index-67">membership</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.test">test (doctest.DocTestFailure attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.UnexpectedException.test">(doctest.UnexpectedException attribute)</a>
</li>
        <li><a href="library/test.html#module-test">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#cgi.test">test() (in module cgi)</a>

      <ul>
        <li><a href="library/mutex.html#mutex.mutex.test">(mutex.mutex method)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#module-test.support">test.support (module)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex.testandset">testandset() (mutex.mutex method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase">TestCase (class in unittest)</a>
</li>
      <li><a href="library/test.html#test.support.TestFailed">TestFailed</a>
</li>
      <li><a href="library/doctest.html#doctest.testfile">testfile() (in module doctest)</a>
</li>
      <li><a href="library/test.html#test.support.TESTFN">TESTFN (in module test.support)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader">TestLoader (class in unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.testMethodPrefix">testMethodPrefix (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.testmod">testmod() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult">TestResult (class in unittest)</a>
</li>
      <li><a href="library/imghdr.html#imghdr.tests">tests (in module imghdr)</a>
</li>
      <li><a href="library/doctest.html#doctest.testsource">testsource() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.testsRun">testsRun (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite">TestSuite (class in unittest)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.testzip">testzip() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/msilib.html#msilib.text">text (in module msilib)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.text">(xml.etree.ElementTree.Element attribute)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog.text">text() (msilib.Dialog method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.text_factory">text_factory (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox">Textbox (class in curses.textpad)</a>
</li>
      <li><a href="library/calendar.html#calendar.TextCalendar">TextCalendar (class in calendar)</a>
</li>
      <li><a href="library/gettext.html#gettext.textdomain">textdomain() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.textdomain">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.text_file.TextFile">TextFile (class in distutils.text_file)</a>
</li>
      <li><a href="library/io.html#io.TextIOBase">TextIOBase (class in io)</a>
</li>
      <li><a href="library/io.html#io.TextIOWrapper">TextIOWrapper (class in io)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestResult">TextTestResult (class in unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestRunner">TextTestRunner (class in unittest)</a>
</li>
      <li><a href="library/textwrap.html#module-textwrap">textwrap (module)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper">TextWrapper (class in textwrap)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_create">theme_create() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_names">theme_names() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_settings">theme_settings() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_use">theme_use() (ttk.Style method)</a>
</li>
      <li><a href="library/locale.html#locale.THOUSEP">THOUSEP (in module locale)</a>
</li>
      <li>
    thread

      <ul>
        <li><a href="c-api/init.html#index-20">module</a>
</li>
      </ul></li>
      <li><a href="library/threading.html#threading.Thread">Thread (class in threading)</a>
</li>
      <li><a href="library/thread.html#module-thread">thread (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.thread">thread() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/threading.html#threading.ThreadError">ThreadError</a>
</li>
      <li><a href="library/threading.html#module-threading">threading (module)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingMixIn">ThreadingMixIn (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingTCPServer">ThreadingTCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingUDPServer">ThreadingUDPServer (class in SocketServer)</a>
</li>
      <li>
    threads

      <ul>
        <li><a href="library/thread.html#index-3">IRIX</a>
</li>
        <li><a href="library/thread.html#index-1">POSIX</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-throw">throw (2to3 fixer)</a>
</li>
      <li><a href="reference/expressions.html#generator.throw">throw() (generator method)</a>
</li>
      <li><a href="library/fl.html#fl.tie">tie() (in module fl)</a>
</li>
      <li><a href="library/curses.html#curses.tigetflag">tigetflag() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.tigetnum">tigetnum() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.tigetstr">tigetstr() (in module curses)</a>
</li>
      <li><a href="library/token.html#token.TILDE">TILDE (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.tilt">tilt() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.tiltangle">tiltangle() (in module turtle)</a>
</li>
      <li><a href="library/datetime.html#datetime.time">time (class in datetime)</a>

      <ul>
        <li><a href="library/time.html#module-time">(module)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.time">time() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/time.html#time.time">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.Time2Internaldate">Time2Internaldate() (in module imaplib)</a>
</li>
      <li><a href="library/datetime.html#datetime.timedelta">timedelta (class in datetime)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler">TimedRotatingFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/calendar.html#calendar.timegm">timegm() (in module calendar)</a>
</li>
      <li><a href="library/timeit.html#module-timeit">timeit (module)</a>
</li>
      <li>
    timeit command line option

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-c">-c, --clock</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-h">-h, --help</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-n">-n N, --number=N</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-r">-r N, --repeat=N</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-s">-s S, --setup=S</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-t">-t, --time</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-v">-v, --verbose</a>
</li>
      </ul></li>
      <li><a href="library/timeit.html#timeit.timeit">timeit() (in module timeit)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer.timeit">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.timeout">timeout</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.timeout">(SocketServer.BaseServer attribute)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.timeout">timeout() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.TimeoutError">TimeoutError</a>
</li>
      <li><a href="library/threading.html#threading.Timer">Timer (class in threading)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer">(class in timeit)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.times">times() (in module os)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.timetuple">timetuple() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.timetuple">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.timetz">timetz() (datetime.datetime method)</a>
</li>
      <li><a href="library/time.html#time.timezone">timezone (in module time)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.title">title() (EasyDialogs.ProgressBar method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.title">(in module turtle)</a>
</li>
        <li><a href="library/stdtypes.html#str.title">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#index-0">Tix</a>

      <ul>
        <li><a href="library/tix.html#Tix.Tix">(class in Tix)</a>
</li>
        <li><a href="library/tix.html#module-Tix">(module)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/tix.html#Tix.tixCommand.tix_addbitmapdir">tix_addbitmapdir() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_cget">tix_cget() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_configure">tix_configure() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_filedialog">tix_filedialog() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_getbitmap">tix_getbitmap() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_getimage">tix_getimage() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#index-1">TIX_LIBRARY</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_option_get">tix_option_get() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_resetoptions">tix_resetoptions() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand">tixCommand (class in Tix)</a>
</li>
      <li><a href="library/tk.html#index-0">Tk</a>

      <ul>
        <li><a href="library/tkinter.html#Tkinter.Tk">(class in Tkinter)</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#index-2">Tk Option Data Types</a>
</li>
      <li><a href="faq/gui.html#index-1">TK_LIBRARY</a>
</li>
      <li><a href="library/tk.html#index-0">Tkinter</a>

      <ul>
        <li><a href="library/tkinter.html#module-Tkinter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#Tix.TList">TList (class in Tix)</a>
</li>
      <li><a href="library/ssl.html#index-1">TLS</a>
</li>
      <li><a href="library/os.html#index-19">TMP</a>, <a href="library/tempfile.html#index-3">[1]</a>
</li>
      <li><a href="library/os.html#os.TMP_MAX">TMP_MAX (in module os)</a>
</li>
      <li><a href="library/os.html#index-18">TMPDIR</a>, <a href="library/tempfile.html#index-1">[1]</a>
</li>
      <li><a href="library/os.html#os.tmpfile">tmpfile() (in module os)</a>
</li>
      <li><a href="library/os.html#os.tmpnam">tmpnam() (in module os)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_eng_string">to_eng_string() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.to_eng_string">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Decimal.to_integral">to_integral() (decimal.Decimal method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_integral_exact">to_integral_exact() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.to_integral_exact">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Decimal.to_integral_value">to_integral_value() (decimal.Decimal method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_sci_string">to_sci_string() (decimal.Context method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.to_splittable">to_splittable() (email.charset.Charset method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.ToASCII">ToASCII() (in module encodings.idna)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.tobuf">tobuf() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.tobytes">tobytes() (memoryview method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.tochild">tochild (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.today">today() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.today">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.tofile">tofile() (array.array method)</a>
</li>
      <li><a href="library/token.html#token.tok_name">tok_name (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">token</a>

      <ul>
        <li><a href="library/token.html#module-token">(module)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.token">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tokenize.html#tokenize.TokenError">TokenError</a>
</li>
      <li><a href="library/tokenize.html#module-tokenize">tokenize (module)</a>
</li>
      <li><a href="library/tokenize.html#tokenize.tokenize">tokenize() (in module tokenize)</a>
</li>
      <li><a href="library/array.html#array.array.tolist">tolist() (array.array method)</a>

      <ul>
        <li><a href="library/stdtypes.html#memoryview.tolist">(memoryview method)</a>
</li>
        <li><a href="library/parser.html#parser.ST.tolist">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/audioop.html#audioop.tomono">tomono() (in module audioop)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.toordinal">toordinal() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.toordinal">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.top">top() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/poplib.html#poplib.POP3.top">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.top_panel">top_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml">toprettyxml() (xml.dom.minidom.Node method)</a>
</li>
      <li><a href="library/audioop.html#audioop.tostereo">tostereo() (in module audioop)</a>
</li>
      <li><a href="library/array.html#array.array.tostring">tostring() (array.array method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring">(in module xml.etree.ElementTree)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.tostringlist">tostringlist() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.total_changes">total_changes (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/functools.html#functools.total_ordering">total_ordering() (in module functools)</a>
</li>
      <li><a href="library/datetime.html#datetime.timedelta.total_seconds">total_seconds() (datetime.timedelta method)</a>
</li>
      <li><a href="library/parser.html#parser.ST.totuple">totuple() (parser.ST method)</a>
</li>
      <li><a href="library/macostools.html#macostools.touched">touched() (in module macostools)</a>
</li>
      <li><a href="library/curses.html#curses.window.touchline">touchline() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.touchwin">touchwin() (curses.window method)</a>
</li>
      <li><a href="library/array.html#array.array.tounicode">tounicode() (array.array method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.ToUnicode">ToUnicode() (in module encodings.idna)</a>
</li>
      <li><a href="library/imageop.html#imageop.tovideo">tovideo() (in module imageop)</a>
</li>
      <li><a href="library/turtle.html#turtle.towards">towards() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.toxml">toxml() (xml.dom.minidom.Node method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_mapping">tp_as_mapping (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_number">tp_as_number (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_sequence">tp_as_sequence (C member)</a>
</li>
      <li><a href="library/curses.html#curses.tparm">tparm() (in module curses)</a>
</li>
      <li>
    trace

      <ul>
        <li><a href="reference/datamodel.html#index-67">stack</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.Trace">Trace (class in trace)</a>
</li>
      <li><a href="library/trace.html#module-trace">trace (module)</a>
</li>
      <li>
    trace command line option

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-help">--help</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-ignore-dir">--ignore-dir=&lt;dir&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-ignore-module">--ignore-module=&lt;mod&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-version">--version</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-coverdir">-C, --coverdir=&lt;dir&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-no-report">-R, --no-report</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-trackcalls">-T, --trackcalls</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-c">-c, --count</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-f">-f, --file=&lt;file&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-g">-g, --timing</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-l">-l, --listfuncs</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-m">-m, --missing</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-r">-r, --report</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-s">-s, --summary</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-t">-t, --trace</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#index-13">trace function</a>, <a href="library/sys.html#index-3">[1]</a>, <a href="library/threading.html#index-1">[2]</a>
</li>
      <li><a href="library/inspect.html#inspect.trace">trace() (in module inspect)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.trace_dispatch">trace_dispatch() (bdb.Bdb method)</a>
</li>
      <li>
    traceback

      <ul>
        <li><a href="library/sys.html#index-1">object</a>, <a href="library/traceback.html#index-0">[1]</a>, <a href="reference/compound_stmts.html#index-11">[2]</a>, <a href="reference/datamodel.html#index-67">[3]</a>, <a href="reference/simple_stmts.html#index-32">[4]</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#module-traceback">traceback (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.traceback_limit">traceback_limit (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/sys.html#sys.tracebacklimit">tracebacklimit (in module sys)</a>
</li>
      <li>
    tracebacks

      <ul>
        <li><a href="library/cgitb.html#index-0">in CGI scripts</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.TracebackType">TracebackType (in module types)</a>
</li>
      <li><a href="library/turtle.html#turtle.tracer">tracer() (in module turtle)</a>, <a href="library/turtle.html#turtle.tracer">[1]</a>
</li>
      <li>
    trailing

      <ul>
        <li><a href="reference/expressions.html#index-78">comma</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.transfercmd">transfercmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/test.html#test.support.TransientResource">TransientResource (class in test.support)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.translate">translate() (in module fnmatch)</a>

      <ul>
        <li><a href="library/string.html#string.translate">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#str.translate">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.translation">translation() (in module gettext)</a>
</li>
      <li><a href="library/ssl.html#index-1">Transport Layer Security</a>
</li>
      <li><a href="c-api/gcsupport.html#c.traverseproc">traverseproc (C type)</a>
</li>
      <li><a href="library/tix.html#Tix.Tree">Tree (class in Tix)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder">TreeBuilder (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview">Treeview (class in ttk)</a>
</li>
      <li><a href="library/random.html#random.triangular">triangular() (in module random)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">triple-quoted string</a>, <a href="glossary.html#term-triple-quoted-string"><strong>[1]</strong></a>
</li>
      <li><a href="library/stdtypes.html#index-43">True</a>, <a href="library/stdtypes.html#index-6">[1]</a>, <a href="reference/datamodel.html#index-13">[2]</a>
</li>
      <li><a href="library/stdtypes.html#index-5">true</a>
</li>
      <li><a href="library/constants.html#True">True (built-in variable)</a>
</li>
      <li><a href="library/operator.html#operator.truediv">truediv() (in module operator)</a>
</li>
      <li><a href="library/math.html#math.trunc">trunc() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/stdtypes.html#file.truncate">truncate() (file method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.truncate">(io.IOBase method)</a>
</li>
      </ul></li>
      <li>
    truth

      <ul>
        <li><a href="library/stdtypes.html#index-2">value</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.truth">truth() (in module operator)</a>
</li>
      <li>
    try

      <ul>
        <li><a href="library/exceptions.html#index-0">statement</a>, <a href="reference/compound_stmts.html#index-10">[1]</a>, <a href="reference/datamodel.html#index-68">[2]</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#index-0">ttk</a>

      <ul>
        <li><a href="library/ttk.html#module-ttk">(module)</a>
</li>
      </ul></li>
      <li><a href="library/imgfile.html#imgfile.ttob">ttob() (in module imgfile)</a>
</li>
      <li>
    tty

      <ul>
        <li><a href="library/termios.html#index-0">I/O control</a>
</li>
      </ul></li>
      <li><a href="library/tty.html#module-tty">tty (module)</a>
</li>
      <li><a href="library/os.html#os.ttyname">ttyname() (in module os)</a>
</li>
      <li>
    tuple

      <ul>
        <li><a href="c-api/list.html#index-2">built-in function</a>, <a href="c-api/sequence.html#index-1">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-12">display</a>
</li>
        <li><a href="reference/datamodel.html#index-24">empty</a>, <a href="reference/expressions.html#index-11">[1]</a>
</li>
        <li><a href="c-api/tuple.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-24">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>, <a href="reference/expressions.html#index-77">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-24">singleton</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#tuple">tuple() (built-in function)</a>
</li>
      <li><a href="library/parser.html#parser.tuple2st">tuple2st() (in module parser)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-tuple_params">tuple_params (2to3 fixer)</a>
</li>
      <li><a href="c-api/tuple.html#index-1">TupleType (in module types)</a>, <a href="library/types.html#types.TupleType">[1]</a>
</li>
      <li><a href="library/fpectl.html#fpectl.turnoff_sigfpe">turnoff_sigfpe() (in module fpectl)</a>
</li>
      <li><a href="library/fpectl.html#fpectl.turnon_sigfpe">turnon_sigfpe() (in module fpectl)</a>
</li>
      <li><a href="library/turtle.html#turtle.Turtle">Turtle (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#module-turtle">turtle (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.turtles">turtles() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.TurtleScreen">TurtleScreen (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.turtlesize">turtlesize() (in module turtle)</a>
</li>
      <li><a href="library/compiler.html#index-0">Tutt, Bill</a>
</li>
      <li><a href="reference/datamodel.html#index-4">type</a>, <a href="glossary.html#term-type"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/functions.html#index-0">Boolean</a>
</li>
        <li><a href="c-api/object.html#index-10">built-in function</a>, <a href="library/stdtypes.html#index-42">[1]</a>, <a href="library/types.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-1">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-4">data</a>
</li>
        <li><a href="reference/datamodel.html#index-4">hierarchy</a>
</li>
        <li><a href="reference/expressions.html#index-9">immutable data</a>
</li>
        <li><a href="c-api/intro.html#index-5">object</a>, <a href="c-api/type.html#index-0">[1]</a>, <a href="library/functions.html#index-7">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">operations on dictionary</a>
</li>
        <li><a href="library/stdtypes.html#index-30">operations on list</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#type">type (built-in class)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Type">Type (class in aetypes)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.type">type (optparse.Option attribute)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.type">(socket.socket attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.type">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">type of an object</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.TYPE_CHECKER">TYPE_CHECKER (optparse.Option attribute)</a>
</li>
      <li><a href="library/curses.html#curses.typeahead">typeahead() (in module curses)</a>
</li>
      <li><a href="library/array.html#array.array.typecode">typecode (array.array attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.TYPED_ACTIONS">TYPED_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators.typed_subpart_iterator">typed_subpart_iterator() (in module email.iterators)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.TypeError">TypeError</a>

      <ul>
        <li><a href="reference/expressions.html#index-51">exception</a>
</li>
      </ul></li>
      <li>
    types

      <ul>
        <li><a href="library/stdtypes.html#index-0">built-in</a>
</li>
        <li><a href="library/stdtypes.html#index-42">module</a>
</li>
        <li><a href="library/stdtypes.html#index-29">mutable sequence</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations on integer</a>
</li>
        <li><a href="library/stdtypes.html#index-32">operations on mapping</a>
</li>
        <li><a href="library/stdtypes.html#index-16">operations on numeric</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operations on sequence</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-types">types (2to3 fixer)</a>

      <ul>
        <li><a href="library/types.html#module-types">(module)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.TYPES">TYPES (optparse.Option attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-59">types, internal</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.types_map">types_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.types_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes.types_map_inv">types_map_inv (mimetypes.MimeTypes attribute)</a>
</li>
      <li><a href="c-api/type.html#index-1">TypeType (in module types)</a>, <a href="library/types.html#types.TypeType">[1]</a>
</li>
      <li><a href="library/time.html#index-10">TZ</a>, <a href="library/time.html#index-11">[1]</a>, <a href="library/time.html#index-12">[2]</a>, <a href="library/time.html#index-13">[3]</a>, <a href="library/time.html#index-14">[4]</a>, <a href="library/time.html#index-15">[5]</a>
</li>
      <li><a href="library/datetime.html#datetime.tzinfo">tzinfo (class in datetime)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.tzinfo">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.tzinfo">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.tzname">tzname (in module time)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.tzname">tzname() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.tzname">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.tzname">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.tzset">tzset() (in module time)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�6�X����html/genindex-U.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-U.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; U</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.U">U (in module re)</a>
</li>
      <li><a href="library/aifc.html#index-1">u-LAW</a>, <a href="library/audioop.html#index-0">[1]</a>, <a href="library/sndhdr.html#index-0">[2]</a>, <a href="library/sunaudio.html#index-0">[3]</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.ucd_3_2_0">ucd_3_2_0 (in module unicodedata)</a>
</li>
      <li><a href="library/select.html#select.kevent.udata">udata (select.kevent attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.UDPServer">UDPServer (class in SocketServer)</a>
</li>
      <li><a href="library/stat.html#stat.UF_APPEND">UF_APPEND (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_COMPRESSED">UF_COMPRESSED (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_HIDDEN">UF_HIDDEN (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_IMMUTABLE">UF_IMMUTABLE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_NODUMP">UF_NODUMP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_NOUNLINK">UF_NOUNLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_OPAQUE">UF_OPAQUE (in module stat)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ugettext">ugettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ugettext">(gettext.NullTranslations method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.uid">uid (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.uid">uid() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.uidl">uidl() (poplib.POP3 method)</a>
</li>
      <li><a href="library/audioop.html#audioop.ulaw2lin">ulaw2lin() (in module audioop)</a>
</li>
      <li><a href="c-api/long.html#index-4">ULONG_MAX</a>
</li>
      <li><a href="library/os.html#os.umask">umask() (in module os)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.uname">uname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/os.html#os.uname">uname() (in module os)</a>

      <ul>
        <li><a href="library/platform.html#platform.uname">(in module platform)</a>
</li>
      </ul></li>
      <li>
    unary

      <ul>
        <li><a href="reference/expressions.html#index-47">arithmetic operation</a>
</li>
        <li><a href="reference/expressions.html#index-47">bitwise operation</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-UNARY_CONVERT">UNARY_CONVERT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_INVERT">UNARY_INVERT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_NEGATIVE">UNARY_NEGATIVE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_NOT">UNARY_NOT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_POSITIVE">UNARY_POSITIVE (opcode)</a>
</li>
      <li>
    unbinding

      <ul>
        <li><a href="reference/simple_stmts.html#index-19">name</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnboundLocalError">UnboundLocalError</a>, <a href="reference/executionmodel.html#index-8">[1]</a>
</li>
      <li><a href="library/types.html#types.UnboundMethodType">UnboundMethodType (in module types)</a>
</li>
      <li><a href="library/functions.html#index-4">unbuffered I/O</a>
</li>
      <li>
    UNC paths

      <ul>
        <li><a href="library/os.html#index-14">and os.makedirs()</a>
</li>
      </ul></li>
      <li><a href="library/zlib.html#zlib.Decompress.unconsumed_tail">unconsumed_tail (zlib.Decompress attribute)</a>
</li>
      <li><a href="library/curses.html#curses.unctrl">unctrl() (in module curses)</a>

      <ul>
        <li><a href="library/curses.ascii.html#curses.ascii.unctrl">(in module curses.ascii)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.undefine_macro">undefine_macro() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Underflow">Underflow (class in decimal)</a>
</li>
      <li><a href="library/turtle.html#turtle.undo">undo() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.undobufferentries">undobufferentries() (in module turtle)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.undoc_header">undoc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.unescape">unescape() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/doctest.html#doctest.UnexpectedException">UnexpectedException</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.unexpectedSuccesses">unexpectedSuccesses (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.unfreeze_form">unfreeze_form() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.ungetch">ungetch() (in module curses)</a>

      <ul>
        <li><a href="library/msvcrt.html#msvcrt.ungetch">(in module msvcrt)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.ungetmouse">ungetmouse() (in module curses)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ungettext">ungettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ungettext">(gettext.NullTranslations method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.ungetwch">ungetwch() (in module msvcrt)</a>
</li>
      <li><a href="library/binascii.html#binascii.unhexlify">unhexlify() (in module binascii)</a>
</li>
      <li>
    unichr

      <ul>
        <li><a href="reference/datamodel.html#index-23">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#unichr">unichr() (built-in function)</a>
</li>
      <li><a href="library/codecs.html#index-0">Unicode</a>, <a href="library/unicodedata.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>

      <ul>
        <li><a href="library/unicodedata.html#index-0">database</a>
</li>
        <li><a href="library/stdtypes.html#index-21">object</a>
</li>
      </ul></li>
      <li>
    unicode

      <ul>
        <li><a href="c-api/object.html#index-5">built-in function</a>, <a href="reference/datamodel.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-83">[2]</a>, <a href="tutorial/introduction.html#index-0">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">object</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-unicode">unicode (2to3 fixer)</a>
</li>
      <li><a href="library/re.html#re.UNICODE">UNICODE (in module re)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">Unicode Consortium</a>
</li>
      <li><a href="library/functions.html#unicode">unicode() (built-in function)</a>
</li>
      <li><a href="library/unicodedata.html#module-unicodedata">unicodedata (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeDecodeError">UnicodeDecodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeEncodeError">UnicodeEncodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError">UnicodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeTranslateError">UnicodeTranslateError</a>
</li>
      <li><a href="library/types.html#types.UnicodeType">UnicodeType (in module types)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeWarning">UnicodeWarning</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.unidata_version">unidata_version (in module unicodedata)</a>
</li>
      <li><a href="library/difflib.html#difflib.unified_diff">unified_diff() (in module difflib)</a>
</li>
      <li><a href="library/random.html#random.uniform">uniform() (in module random)</a>
</li>
      <li><a href="library/httplib.html#httplib.UnimplementedFileMode">UnimplementedFileMode</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager.uninstall">uninstall() (imputil.ImportManager method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Union">Union (class in ctypes)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.union">union() (frozenset method)</a>
</li>
      <li><a href="library/unittest.html#module-unittest">unittest (module)</a>
</li>
      <li>
    unittest command line option

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-b">-b, --buffer</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-c">-c, --catch</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-f">-f, --failfast</a>
</li>
      </ul></li>
      <li>
    unittest-discover command line option

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-p">-p, --pattern pattern</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-s">-s, --start-directory directory</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-t">-t, --top-level-directory directory</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-v">-v, --verbose</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-universal-newlines"><strong>universal newlines</strong></a>

      <ul>
        <li><a href="whatsnew/2.3.html#index-8">What&#39;s new</a>, <a href="whatsnew/2.4.html#index-7">[1]</a>, <a href="whatsnew/2.5.html#index-18">[2]</a>, <a href="whatsnew/2.6.html#index-13">[3]</a>
</li>
        <li><a href="library/bz2.html#index-0">bz2.BZ2File class</a>
</li>
        <li><a href="library/stdtypes.html#index-36">file.newlines attribute</a>
</li>
        <li><a href="library/io.html#index-2">io.IncrementalNewlineDecoder class</a>
</li>
        <li><a href="library/io.html#index-1">io.TextIOWrapper class</a>
</li>
        <li><a href="library/io.html#index-0">open() (in module io)</a>
</li>
        <li><a href="library/functions.html#index-5">open() built-in function</a>
</li>
        <li><a href="library/stdtypes.html#index-24">str.splitlines method</a>
</li>
        <li><a href="library/subprocess.html#index-1">subprocess module</a>
</li>
        <li><a href="library/zipfile.html#index-0">zipfile.ZipFile.open method</a>
</li>
      </ul></li>
      <li><a href="reference/toplevel_components.html#index-4">UNIX</a>

      <ul>
        <li><a href="library/fcntl.html#index-0">I/O control</a>
</li>
        <li><a href="library/fcntl.html#index-0">file control</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.UnixDatagramServer">UnixDatagramServer (class in SocketServer)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.unixfrom">unixfrom (rfc822.Message attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.UnixMailbox">UnixMailbox (class in mailbox)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.UnixStreamServer">UnixStreamServer (class in SocketServer)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Unknown">Unknown (class in aetypes)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_charref">unknown_charref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.unknown_decl">unknown_decl() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_endtag">unknown_endtag() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_entityref">unknown_entityref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.unknown_open">unknown_open() (urllib2.BaseHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.UnknownHandler.unknown_open">(urllib2.UnknownHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_starttag">unknown_starttag() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.UnknownHandler">UnknownHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.UnknownProtocol">UnknownProtocol</a>
</li>
      <li><a href="library/httplib.html#httplib.UnknownTransferEncoding">UnknownTransferEncoding</a>
</li>
      <li><a href="library/os.html#os.unlink">unlink() (in module os)</a>

      <ul>
        <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.unlink">(xml.dom.minidom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Babyl.unlock">unlock() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.unlock">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.unlock">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.unlock">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.unlock">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.unlock">(mailbox.mbox method)</a>
</li>
        <li><a href="library/mutex.html#mutex.mutex.unlock">(mutex.mutex method)</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#mimify.unmimify">unmimify() (in module mimify)</a>
</li>
      <li><a href="library/aepack.html#aepack.unpack">unpack() (in module aepack)</a>

      <ul>
        <li><a href="library/struct.html#struct.unpack">(in module struct)</a>
</li>
        <li><a href="library/struct.html#struct.Struct.unpack">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_array">unpack_array() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_bytes">unpack_bytes() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_double">unpack_double() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_farray">unpack_farray() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_float">unpack_float() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_fopaque">unpack_fopaque() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/struct.html#struct.unpack_from">unpack_from() (in module struct)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.unpack_from">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_fstring">unpack_fstring() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_list">unpack_list() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_opaque">unpack_opaque() (xdrlib.Unpacker method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/dis.html#opcode-UNPACK_SEQUENCE">UNPACK_SEQUENCE (opcode)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_string">unpack_string() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker">Unpacker (class in xdrlib)</a>
</li>
      <li><a href="library/aetools.html#aetools.unpackevent">unpackevent() (in module aetools)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler.unparsedEntityDecl">unparsedEntityDecl() (xml.sax.handler.DTDHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler">UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pickle.html#pickle.Unpickler">Unpickler (class in pickle)</a>
</li>
      <li><a href="library/pickle.html#pickle.UnpicklingError">UnpicklingError</a>
</li>
      <li><a href="library/fl.html#fl.unqdevice">unqdevice() (in module fl)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.unquote">unquote() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.unquote">(in module rfc822)</a>
</li>
        <li><a href="library/urllib.html#urllib.unquote">(in module urllib)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib.unquote_plus">unquote_plus() (in module urllib)</a>
</li>
      <li><a href="reference/datamodel.html#index-2">unreachable object</a>
</li>
      <li><a href="distutils/apiref.html#distutils.text_file.TextFile.unreadline">unreadline() (distutils.text_file.TextFile method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-17">unrecognized escape sequence</a>
</li>
      <li><a href="library/select.html#select.epoll.unregister">unregister() (select.epoll method)</a>

      <ul>
        <li><a href="library/select.html#select.poll.unregister">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#shutil.unregister_archive_format">unregister_archive_format() (in module shutil)</a>
</li>
      <li><a href="library/csv.html#csv.unregister_dialect">unregister_dialect() (in module csv)</a>
</li>
      <li><a href="library/test.html#test.support.EnvironmentVarGuard.unset">unset() (test.support.EnvironmentVarGuard method)</a>
</li>
      <li><a href="library/os.html#os.unsetenv">unsetenv() (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.unsubscribe">unsubscribe() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/io.html#io.UnsupportedOperation">UnsupportedOperation</a>
</li>
      <li><a href="library/tokenize.html#tokenize.untokenize">untokenize() (in module tokenize)</a>
</li>
      <li><a href="library/curses.html#curses.window.untouchwin">untouchwin() (curses.window method)</a>
</li>
      <li><a href="library/zlib.html#zlib.Decompress.unused_data">unused_data (zlib.Decompress attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.unwrap">unwrap() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.up">up() (in module turtle)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.update">update() (collections.Counter method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.update">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.update">(frozenset method)</a>
</li>
        <li><a href="library/hashlib.html#hashlib.hash.update">(hashlib.hash method)</a>
</li>
        <li><a href="library/hmac.html#hmac.HMAC.update">(hmac.HMAC method)</a>
</li>
        <li><a href="library/turtle.html#turtle.update">(in module turtle)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.update">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.update">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.update">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.update">(sha.sha method)</a>
</li>
        <li><a href="library/trace.html#trace.CoverageResults.update">(trace.CoverageResults method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.update_panels">update_panels() (in module curses.panel)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.update_visible">update_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/functools.html#functools.update_wrapper">update_wrapper() (in module functools)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.updatescrollbars">updatescrollbars() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/string.html#string.upper">upper() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.upper">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.uppercase">uppercase (in module string)</a>
</li>
      <li><a href="library/os.html#os.urandom">urandom() (in module os)</a>
</li>
      <li><a href="library/basehttpserver.html#index-0">URL</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/robotparser.html#index-0">[2]</a>, <a href="library/urllib.html#index-0">[3]</a>, <a href="library/urlparse.html#index-0">[4]</a>

      <ul>
        <li><a href="library/urlparse.html#index-0">parsing</a>
</li>
        <li><a href="library/urlparse.html#index-0">relative</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.url">url (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.url2pathname">url2pathname() (in module urllib)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlcleanup">urlcleanup() (in module urllib)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urldefrag">urldefrag() (in module urlparse)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlencode">urlencode() (in module urllib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.URLError">URLError</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urljoin">urljoin() (in module urlparse)</a>
</li>
      <li>
    urllib

      <ul>
        <li><a href="library/httplib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-urllib">urllib (2to3 fixer)</a>

      <ul>
        <li><a href="library/urllib.html#module-urllib">(module)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#module-urllib2">urllib2 (module)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlopen">urlopen() (in module urllib)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.urlopen">(in module urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib.URLopener">URLopener (class in urllib)</a>
</li>
      <li>
    urlparse

      <ul>
        <li><a href="library/urllib.html#index-11">module</a>
</li>
      </ul></li>
      <li><a href="library/urlparse.html#module-urlparse">urlparse (module)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlparse">urlparse() (in module urlparse)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlretrieve">urlretrieve() (in module urllib)</a>
</li>
      <li><a href="library/base64.html#base64.urlsafe_b64decode">urlsafe_b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.urlsafe_b64encode">urlsafe_b64encode() (in module base64)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlsplit">urlsplit() (in module urlparse)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlunparse">urlunparse() (in module urlparse)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlunsplit">urlunsplit() (in module urlparse)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.urn">urn (uuid.UUID attribute)</a>
</li>
      <li><a href="library/curses.html#curses.use_default_colors">use_default_colors() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.use_env">use_env() (in module curses)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.use_rawinput">use_rawinput (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.UseForeignDTD">UseForeignDTD() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/getpass.html#index-1">USER</a>
</li>
      <li>
    user

      <ul>
        <li><a href="library/user.html#index-0">configuration file</a>
</li>
        <li><a href="library/os.html#index-0">effective id</a>
</li>
        <li><a href="library/os.html#index-6">id</a>
</li>
        <li><a href="library/os.html#index-8">id, setting</a>
</li>
      </ul></li>
      <li><a href="library/user.html#module-user">user (module)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.user">user() (poplib.POP3 method)</a>
</li>
      <li>
    user-defined

      <ul>
        <li><a href="reference/datamodel.html#index-36">function</a>
</li>
        <li><a href="reference/expressions.html#index-42">function call</a>
</li>
        <li><a href="reference/datamodel.html#index-38">method</a>
</li>
      </ul></li>
      <li>
    user-defined function

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">object</a>, <a href="reference/datamodel.html#index-36">[1]</a>, <a href="reference/expressions.html#index-42">[2]</a>
</li>
      </ul></li>
      <li>
    user-defined method

      <ul>
        <li><a href="reference/datamodel.html#index-38">object</a>
</li>
      </ul></li>
      <li><a href="whatsnew/2.7.html#index-9">USER_BASE</a>

      <ul>
        <li><a href="library/site.html#site.USER_BASE">(in module site)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.user_call">user_call() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_exception">user_exception() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_line">user_line() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_return">user_return() (bdb.Bdb method)</a>
</li>
      <li><a href="library/site.html#site.USER_SITE">USER_SITE (in module site)</a>
</li>
      <li>
    usercustomize

      <ul>
        <li><a href="library/site.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="library/userdict.html#UserDict.UserDict">UserDict (class in UserDict)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserDict">(module)</a>
</li>
      </ul></li>
      <li><a href="library/userdict.html#UserList.UserList">UserList (class in UserList)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserList">(module)</a>
</li>
      </ul></li>
      <li><a href="library/getpass.html#index-3">USERNAME</a>
</li>
      <li><a href="install/index.html#index-6">USERPROFILE</a>, <a href="library/os.path.html#index-4">[1]</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.userptr">userptr() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/userdict.html#UserString.UserString">UserString (class in UserString)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserString">(module)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UserWarning">UserWarning</a>
</li>
      <li><a href="library/tarfile.html#tarfile.USTAR_FORMAT">USTAR_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/time.html#index-5">UTC</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcfromtimestamp">utcfromtimestamp() (datetime.datetime class method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcnow">utcnow() (datetime.datetime class method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcoffset">utcoffset() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.utcoffset">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.utcoffset">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.utctimetuple">utctimetuple() (datetime.datetime method)</a>
</li>
      <li><a href="library/os.html#os.utime">utime() (in module os)</a>
</li>
      <li>
    uu

      <ul>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/uu.html#module-uu">uu (module)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID">UUID (class in uuid)</a>
</li>
      <li><a href="library/uuid.html#module-uuid">uuid (module)</a>
</li>
      <li><a href="library/uuid.html#index-2">uuid1</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid1">uuid1() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-3">uuid3</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid3">uuid3() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-4">uuid4</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid4">uuid4() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-5">uuid5</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid5">uuid5() (in module uuid)</a>
</li>
      <li><a href="library/msilib.html#msilib.UuidCreate">UuidCreate() (in module msilib)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ �Q�3030html/genindex-V.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-V.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; V</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/wsgiref.html#wsgiref.validate.validator">validator() (in module wsgiref.validate)</a>
</li>
      <li>
    value

      <ul>
        <li><a href="reference/compound_stmts.html#index-20">default parameter</a>
</li>
        <li><a href="library/stdtypes.html#index-2">truth</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.Morsel.value">value (Cookie.Morsel attribute)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.value">(cookielib.Cookie attribute)</a>
</li>
        <li><a href="library/ctypes.html#ctypes._SimpleCData.value">(ctypes._SimpleCData attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Attr.value">(xml.dom.Attr attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">value of an object</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Value">Value() (in module multiprocessing)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.Value">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Value">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.value_decode">value_decode() (Cookie.BaseCookie method)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.value_encode">value_encode() (Cookie.BaseCookie method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ValueError">ValueError</a>

      <ul>
        <li><a href="reference/expressions.html#index-59">exception</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary.valuerefs">valuerefs() (weakref.WeakValueDictionary method)</a>
</li>
      <li>
    values

      <ul>
        <li><a href="library/stdtypes.html#index-43">Boolean</a>
</li>
        <li><a href="reference/simple_stmts.html#index-2">writing</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#dict.values">values() (dict method)</a>

      <ul>
        <li><a href="library/email.message.html#email.message.Message.values">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.values">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.ValuesView">ValuesView (class in collections)</a>
</li>
      <li>
    variable

      <ul>
        <li><a href="reference/executionmodel.html#index-7">free</a>, <a href="reference/simple_stmts.html#index-20">[1]</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.variant">variant (uuid.UUID attribute)</a>
</li>
      <li><a href="library/gl.html#gl.varray">varray() (in module gl)</a>
</li>
      <li><a href="library/functions.html#vars">vars() (built-in function)</a>
</li>
      <li><a href="library/token.html#token.VBAR">VBAR (in module token)</a>
</li>
      <li><a href="library/scrolledtext.html#ScrolledText.ScrolledText.vbar">vbar (ScrolledText.ScrolledText attribute)</a>
</li>
      <li><a href="library/token.html#token.VBAREQUAL">VBAREQUAL (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.Vec2D">Vec2D (class in turtle)</a>
</li>
      <li><a href="library/re.html#re.VERBOSE">VERBOSE (in module re)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.verbose">verbose (in module tabnanny)</a>

      <ul>
        <li><a href="library/test.html#test.support.verbose">(in module test.support)</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#smtplib.SMTP.verify">verify() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_CRL_CHECK_CHAIN">VERIFY_CRL_CHECK_CHAIN (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_CRL_CHECK_LEAF">VERIFY_CRL_CHECK_LEAF (in module ssl)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/ssl.html#ssl.VERIFY_DEFAULT">VERIFY_DEFAULT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.verify_flags">verify_flags (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.verify_mode">verify_mode (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.verify_request">verify_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_X509_STRICT">VERIFY_X509_STRICT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_X509_TRUSTED_FIRST">VERIFY_X509_TRUSTED_FIRST (in module ssl)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.version">version (cookielib.Cookie attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPResponse.version">(httplib.HTTPResponse attribute)</a>
</li>
        <li><a href="library/curses.html#curses.version">(in module curses)</a>
</li>
        <li><a href="library/marshal.html#marshal.version">(in module marshal)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.version">(in module sqlite3)</a>
</li>
        <li><a href="c-api/init.html#index-5">(in module sys)</a>, <a href="c-api/init.html#index-8">[1]</a>, <a href="c-api/init.html#index-9">[2]</a>, <a href="library/sys.html#sys.version">[3]</a>
</li>
        <li><a href="library/urllib.html#urllib.URLopener.version">(urllib.URLopener attribute)</a>
</li>
        <li><a href="library/uuid.html#uuid.UUID.version">(uuid.UUID attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ensurepip.html#ensurepip.version">version() (in module ensurepip)</a>

      <ul>
        <li><a href="library/platform.html#platform.version">(in module platform)</a>
</li>
        <li><a href="library/ssl.html#ssl.SSLSocket.version">(ssl.SSLSocket method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.version_info">version_info (in module sqlite3)</a>

      <ul>
        <li><a href="library/sys.html#sys.version_info">(in module sys)</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.version_string">version_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.vformat">vformat() (string.Formatter method)</a>
</li>
      <li><a href="library/undoc.html#module-videoreader">videoreader (module)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewitems">viewitems() (dict method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewkeys">viewkeys() (dict method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewvalues">viewvalues() (dict method)</a>
</li>
      <li><a href="glossary.html#term-virtual-environment"><strong>virtual environment</strong></a>
</li>
      <li><a href="glossary.html#term-virtual-machine"><strong>virtual machine</strong></a>
</li>
      <li><a href="library/ast.html#ast.NodeVisitor.visit">visit() (ast.NodeVisitor method)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.visitproc">visitproc (C type)</a>
</li>
      <li><a href="library/curses.html#curses.window.vline">vline() (curses.window method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.VMSError">VMSError</a>
</li>
      <li><a href="library/gl.html#gl.vnarray">vnarray() (in module gl)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.voidcmd">voidcmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.volume">volume (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/random.html#random.vonmisesvariate">vonmisesvariate() (in module random)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\p����Y�Yhtml/genindex-W.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-W.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; W</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/undoc.html#module-W">W (module)</a>
</li>
      <li><a href="library/os.html#os.W_OK">W_OK (in module os)</a>
</li>
      <li><a href="library/os.html#os.wait">wait() (in module os)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.wait">(multiprocessing.pool.AsyncResult method)</a>
</li>
        <li><a href="library/popen2.html#popen2.Popen3.wait">(popen2.Popen3 method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.wait">(subprocess.Popen method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.wait">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.wait">(threading.Event method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.wait3">wait3() (in module os)</a>
</li>
      <li><a href="library/os.html#os.wait4">wait4() (in module os)</a>
</li>
      <li><a href="library/os.html#os.waitpid">waitpid() (in module os)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.walk">walk() (email.message.Message method)</a>

      <ul>
        <li><a href="library/ast.html#ast.walk">(in module ast)</a>
</li>
        <li><a href="library/compiler.html#compiler.walk">(in module compiler)</a>
</li>
        <li><a href="library/compiler.html#compiler.visitor.walk">(in module compiler.visitor)</a>
</li>
        <li><a href="library/os.html#os.walk">(in module os)</a>
</li>
        <li><a href="library/os.path.html#os.path.walk">(in module os.path)</a>
</li>
      </ul></li>
      <li><a href="library/pkgutil.html#pkgutil.walk_packages">walk_packages() (in module pkgutil)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.want">want (doctest.Example attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.warn">warn() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.warn">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/warnings.html#warnings.warn">(in module warnings)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#warnings.warn_explicit">warn_explicit() (in module warnings)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.Warning">Warning</a>
</li>
      <li><a href="library/logging.html#logging.warning">warning() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.warning">(logging.Logger method)</a>
</li>
        <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.warning">(xml.sax.handler.ErrorHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#index-0">warnings</a>

      <ul>
        <li><a href="library/warnings.html#module-warnings">(module)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.WarningsRecorder">WarningsRecorder (class in test.support)</a>
</li>
      <li><a href="library/sys.html#sys.warnoptions">warnoptions (in module sys)</a>
</li>
      <li><a href="library/warnings.html#warnings.warnpy3k">warnpy3k() (in module warnings)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.wasSuccessful">wasSuccessful() (unittest.TestResult method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.WatchedFileHandler">WatchedFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/wave.html#module-wave">wave (module)</a>
</li>
      <li><a href="library/os.html#os.WCONTINUED">WCONTINUED (in module os)</a>
</li>
      <li><a href="library/os.html#os.WCOREDUMP">WCOREDUMP() (in module os)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary">WeakKeyDictionary (class in weakref)</a>
</li>
      <li><a href="library/weakref.html#module-weakref">weakref (module)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakSet">WeakSet (class in weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary">WeakValueDictionary (class in weakref)</a>
</li>
      <li><a href="library/webbrowser.html#module-webbrowser">webbrowser (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.weekday">weekday() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.weekday">(datetime.datetime method)</a>
</li>
        <li><a href="library/calendar.html#calendar.weekday">(in module calendar)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.weekheader">weekheader() (in module calendar)</a>
</li>
      <li><a href="library/random.html#random.weibullvariate">weibullvariate() (in module random)</a>
</li>
      <li><a href="library/os.html#os.WEXITSTATUS">WEXITSTATUS() (in module os)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.wfile">wfile (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/imghdr.html#imghdr.what">what() (in module imghdr)</a>

      <ul>
        <li><a href="library/sndhdr.html#sndhdr.what">(in module sndhdr)</a>
</li>
      </ul></li>
      <li><a href="library/sndhdr.html#sndhdr.whathdr">whathdr() (in module sndhdr)</a>
</li>
      <li><a href="library/whichdb.html#module-whichdb">whichdb (module)</a>
</li>
      <li><a href="library/whichdb.html#whichdb.whichdb">whichdb() (in module whichdb)</a>
</li>
      <li>
    while

      <ul>
        <li><a href="library/stdtypes.html#index-2">statement</a>, <a href="reference/compound_stmts.html#index-4">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-7">whitespace</a>

      <ul>
        <li><a href="library/string.html#string.whitespace">(in module string)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.whitespace">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex.whitespace_split">whitespace_split (shlex.shlex attribute)</a>
</li>
      <li><a href="library/random.html#random.whseed">whseed() (in module random)</a>
</li>
      <li><a href="library/random.html#random.WichmannHill">WichmannHill (class in random)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget">Widget (class in ttk)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.width">width (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.width">width() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.WIFCONTINUED">WIFCONTINUED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFEXITED">WIFEXITED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFSIGNALED">WIFSIGNALED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFSTOPPED">WIFSTOPPED() (in module os)</a>
</li>
      <li><a href="library/tempfile.html#index-4">Wimp$ScrapDir</a>
</li>
      <li><a href="library/platform.html#platform.win32_ver">win32_ver() (in module platform)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WinDLL">WinDLL (class in ctypes)</a>
</li>
      <li><a href="library/tkinter.html#index-1">window manager (widgets)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.window">window() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Window">Window() (in module FrameWork)</a>
</li>
      <li><a href="library/turtle.html#turtle.window_height">window_height() (in module turtle)</a>, <a href="library/turtle.html#turtle.window_height">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.window_width">window_width() (in module turtle)</a>, <a href="library/turtle.html#turtle.window_width">[1]</a>
</li>
      <li><a href="library/framework.html#FrameWork.windowbounds">windowbounds() (in module FrameWork)</a>
</li>
      <li><a href="library/configparser.html#index-0">Windows ini file</a>
</li>
      <li><a href="library/exceptions.html#exceptions.WindowsError">WindowsError</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WinError">WinError() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WINFUNCTYPE">WINFUNCTYPE() (in module ctypes)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/select.html#index-1">WinSock</a>
</li>
      <li><a href="library/winsound.html#module-winsound">winsound (module)</a>
</li>
      <li><a href="library/sys.html#sys.winver">winver (in module sys)</a>
</li>
      <li>
    with

      <ul>
        <li><a href="reference/compound_stmts.html#index-15">statement</a>, <a href="reference/datamodel.html#index-96">[1]</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-WITH_CLEANUP">WITH_CLEANUP (opcode)</a>
</li>
      <li><a href="library/macos.html#MacOS.WMAvailable">WMAvailable() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.WNOHANG">WNOHANG (in module os)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.wordchars">wordchars (shlex.shlex attribute)</a>
</li>
      <li><a href="library/internet.html#index-0">World Wide Web</a>, <a href="library/robotparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-0">[2]</a>, <a href="library/urlparse.html#index-0">[3]</a>
</li>
      <li><a href="library/textwrap.html#textwrap.wrap">wrap() (in module textwrap)</a>

      <ul>
        <li><a href="library/textwrap.html#textwrap.TextWrapper.wrap">(textwrap.TextWrapper method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.wrap_socket">wrap_socket() (in module ssl)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLContext.wrap_socket">(ssl.SSLContext method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.wrap_text">wrap_text() (in module distutils.fancy_getopt)</a>
</li>
      <li><a href="library/curses.html#curses.wrapper">wrapper() (in module curses)</a>
</li>
      <li><a href="library/functools.html#functools.wraps">wraps() (in module functools)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.WRITABLE">WRITABLE (in module Tkinter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.writable">writable() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.writable">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.write">write() (array.array method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.write">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.write">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/code.html#code.InteractiveInterpreter.write">(code.InteractiveInterpreter method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamWriter.write">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/email.generator.html#email.generator.Generator.write">(email.generator.Generator method)</a>
</li>
        <li><a href="library/stdtypes.html#file.write">(file method)</a>
</li>
        <li><a href="library/imgfile.html#imgfile.write">(in module imgfile)</a>
</li>
        <li><a href="library/os.html#os.write">(in module os)</a>
</li>
        <li><a href="library/turtle.html#turtle.write">(in module turtle)</a>
</li>
        <li><a href="library/io.html#io.BufferedIOBase.write">(io.BufferedIOBase method)</a>
</li>
        <li><a href="library/io.html#io.BufferedWriter.write">(io.BufferedWriter method)</a>
</li>
        <li><a href="library/io.html#io.RawIOBase.write">(io.RawIOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.write">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.write">(mmap.mmap method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.write">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.write">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write">(xml.etree.ElementTree.ElementTree method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.write">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/mmap.html#mmap.mmap.write_byte">write_byte() (mmap.mmap method)</a>
</li>
      <li><a href="library/turtle.html#turtle.write_docstringdict">write_docstringdict() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.file_util.write_file">write_file() (in module distutils.file_util)</a>
</li>
      <li><a href="library/readline.html#readline.write_history_file">write_history_file() (in module readline)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">WRITE_RESTRICTED</a>
</li>
      <li><a href="library/trace.html#trace.CoverageResults.write_results">write_results() (trace.CoverageResults method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.writeall">writeall() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.writebufferproc">writebufferproc (C type)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.writeframes">writeframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.writeframes">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.writeframes">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.writeframesraw">writeframesraw() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.writeframesraw">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.writeframesraw">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.DictWriter.writeheader">writeheader() (csv.DictWriter method)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.writelines">writelines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamWriter.writelines">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/stdtypes.html#file.writelines">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.writelines">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#plistlib.writePlist">writePlist() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.writePlistToResource">writePlistToResource() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.writePlistToString">writePlistToString() (in module plistlib)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.PyZipFile.writepy">writepy() (zipfile.PyZipFile method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.writer">writer (formatter.formatter attribute)</a>
</li>
      <li><a href="library/csv.html#csv.writer">writer() (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvwriter.writerow">writerow() (csv.csvwriter method)</a>
</li>
      <li><a href="library/csv.html#csv.csvwriter.writerows">writerows() (csv.csvwriter method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.writestr">writestr() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.writexml">writexml() (xml.dom.minidom.Node method)</a>
</li>
      <li>
    writing

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">values</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.WrongDocumentErr">WrongDocumentErr</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-ws_comma">ws_comma (2to3 fixer)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_file_wrapper">wsgi_file_wrapper (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_multiprocess">wsgi_multiprocess (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_multithread">wsgi_multithread (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_run_once">wsgi_run_once (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref">wsgiref (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.handlers">wsgiref.handlers (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.headers">wsgiref.headers (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.simple_server">wsgiref.simple_server (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.util">wsgiref.util (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.validate">wsgiref.validate (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler">WSGIRequestHandler (class in wsgiref.simple_server)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer">WSGIServer (class in wsgiref.simple_server)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.wShowWindow">wShowWindow (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/os.html#os.WSTOPSIG">WSTOPSIG() (in module os)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.wstring_at">wstring_at() (in module ctypes)</a>
</li>
      <li><a href="library/os.html#os.WTERMSIG">WTERMSIG() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WUNTRACED">WUNTRACED (in module os)</a>
</li>
      <li><a href="library/internet.html#index-0">WWW</a>, <a href="library/robotparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-0">[2]</a>, <a href="library/urlparse.html#index-0">[3]</a>

      <ul>
        <li><a href="library/basehttpserver.html#index-0">server</a>, <a href="library/cgi.html#index-0">[1]</a>
</li>
      </ul></li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\r�~�$�$html/genindex-X.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-X.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; X</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.X">X (in module re)</a>
</li>
      <li><a href="library/ssl.html#index-16">X509 certificate</a>
</li>
      <li><a href="library/os.html#os.X_OK">X_OK (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.xatom">xatom() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/turtle.html#turtle.xcor">xcor() (in module turtle)</a>
</li>
      <li><a href="library/pickle.html#index-1">XDR</a>, <a href="library/xdrlib.html#index-0">[1]</a>
</li>
      <li><a href="library/xdrlib.html#module-xdrlib">xdrlib (module)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xgtitle">xgtitle() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xhdr">xhdr() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/htmlparser.html#index-0">XHTML</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.XHTML_NAMESPACE">XHTML_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/xml.html#module-xml">xml (module)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XML">XML() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.dom.html#module-xml.dom">xml.dom (module)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#module-xml.dom.minidom">xml.dom.minidom (module)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#module-xml.dom.pulldom">xml.dom.pulldom (module)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#module-xml.etree.ElementTree">xml.etree.ElementTree (module)</a>
</li>
      <li><a href="library/pyexpat.html#module-xml.parsers.expat">xml.parsers.expat (module)</a>
</li>
      <li><a href="library/xml.sax.html#module-xml.sax">xml.sax (module)</a>
</li>
      <li><a href="library/xml.sax.handler.html#module-xml.sax.handler">xml.sax.handler (module)</a>
</li>
      <li><a href="library/xml.sax.utils.html#module-xml.sax.saxutils">xml.sax.saxutils (module)</a>
</li>
      <li><a href="library/xml.sax.reader.html#module-xml.sax.xmlreader">xml.sax.xmlreader (module)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/xml.dom.html#xml.dom.XML_NAMESPACE">XML_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/codecs.html#codecs.xmlcharrefreplace_errors">xmlcharrefreplace_errors() (in module codecs)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.XmlDeclHandler">XmlDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.XMLFilterBase">XMLFilterBase (class in xml.sax.saxutils)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.XMLGenerator">XMLGenerator (class in xml.sax.saxutils)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLID">XMLID() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.XMLNS_NAMESPACE">XMLNS_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser">XMLParser (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.XMLParserType">XMLParserType (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader">XMLReader (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/xmlrpclib.html#module-xmlrpclib">xmlrpclib (module)</a>
</li>
      <li>
    xor

      <ul>
        <li><a href="reference/expressions.html#index-62">bitwise</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.xor">xor() (in module operator)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xover">xover() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xpath">xpath() (nntplib.NNTP method)</a>
</li>
      <li>
    xrange

      <ul>
        <li><a href="library/types.html#index-2">built-in function</a>
</li>
        <li><a href="library/stdtypes.html#index-21">object</a>, <a href="library/stdtypes.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-xrange">xrange (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#xrange">xrange() (built-in function)</a>
</li>
      <li><a href="library/types.html#types.XRangeType">XRangeType (in module types)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-xreadlines">xreadlines (2to3 fixer)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.xreadlines">xreadlines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.xreadlines">(file method)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.xview">xview() (ttk.Treeview method)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�!A�html/genindex-Y.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-Y.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; Y</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/time.html#index-2">Y2K</a>
</li>
      <li><a href="library/turtle.html#turtle.ycor">ycor() (in module turtle)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.year">year (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.year">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#index-2">Year 2000</a>
</li>
      <li><a href="library/time.html#index-1">Year 2038</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.yeardatescalendar">yeardatescalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.yeardays2calendar">yeardays2calendar() (calendar.Calendar method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/calendar.html#calendar.Calendar.yeardayscalendar">yeardayscalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/locale.html#locale.YESEXPR">YESEXPR (in module locale)</a>
</li>
      <li>
    yield

      <ul>
        <li><a href="reference/expressions.html#index-22">expression</a>
</li>
        <li><a href="reference/expressions.html#index-22">keyword</a>
</li>
        <li><a href="reference/simple_stmts.html#index-28">statement</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-YIELD_VALUE">YIELD_VALUE (opcode)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.yiq_to_rgb">yiq_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.yview">yview() (ttk.Treeview method)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�)�x##html/genindex-Z.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-Z.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; Z</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="glossary.html#term-zen-of-python"><strong>Zen of Python</strong></a>
</li>
      <li><a href="library/exceptions.html#exceptions.ZeroDivisionError">ZeroDivisionError</a>

      <ul>
        <li><a href="reference/expressions.html#index-54">exception</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.zfill">zfill() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.zfill">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-zip">zip (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#zip">zip() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.zip">(in module future_builtins)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZIP_DEFLATED">ZIP_DEFLATED (in module zipfile)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZIP_STORED">ZIP_STORED (in module zipfile)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile">ZipFile (class in zipfile)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/zipfile.html#module-zipfile">zipfile (module)</a>
</li>
      <li>
    zipfile command line option

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-c">-c &lt;zipfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-e">-e &lt;zipfile&gt; &lt;output_dir&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-l">-l &lt;zipfile&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-t">-t &lt;zipfile&gt;</a>
</li>
      </ul></li>
      <li><a href="library/zipimport.html#module-zipimport">zipimport (module)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter">zipimporter (class in zipimport)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.ZipImportError">ZipImportError</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo">ZipInfo (class in zipfile)</a>
</li>
      <li><a href="library/zlib.html#module-zlib">zlib (module)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ <��V�V�html/genindex-_.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-_.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; _</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/operator.html#operator.__abs__">__abs__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__abs__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__add__">__add__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__add__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__add__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="tutorial/modules.html#index-8">__all__</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-49">(optional module attribute)</a>
</li>
        <li><a href="c-api/import.html#index-0">(package variable)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__and__">__and__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__and__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#class.__bases__">__bases__ (class attribute)</a>, <a href="reference/datamodel.html#index-53">[1]</a>
</li>
      <li>
    __builtin__

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/intro.html#index-20">[1]</a>, <a href="reference/simple_stmts.html#index-57">[2]</a>, <a href="reference/toplevel_components.html#index-2">[3]</a>, <a href="tutorial/modules.html#index-7">[4]</a>
</li>
      </ul></li>
      <li><a href="library/__builtin__.html#module-__builtin__">__builtin__ (module)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-57">__builtins__</a>
</li>
      <li><a href="reference/datamodel.html#object.__call__">__call__() (object method)</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
      <li><a href="library/stdtypes.html#instance.__class__">__class__ (instance attribute)</a>, <a href="reference/datamodel.html#index-57">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__closure__ (function attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-11">__cmp__() (instance method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__cmp__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-37">__code__ (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#object.__coerce__">__coerce__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__complex__">__complex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__concat__">__concat__() (in module operator)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__contains__">__contains__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__contains__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__contains__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__contains__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#index-1">__copy__() (copy protocol)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-16">__debug__</a>

      <ul>
        <li><a href="library/constants.html#__debug__">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#index-1">__deepcopy__() (copy protocol)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__defaults__ (function attribute)</a>
</li>
      <li><a href="library/io.html#io.IOBase.__del__">__del__() (io.IOBase method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__del__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__delattr__">__delattr__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__delete__">__delete__() (object method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__delitem__">__delitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__delitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.__delitem__">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__delitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__delitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__delslice__">__delslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__delslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-53">__dict__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-57">(instance attribute)</a>, <a href="reference/datamodel.html#index-85">[1]</a>
</li>
        <li><a href="c-api/module.html#index-3">(module attribute)</a>, <a href="reference/datamodel.html#index-48">[1]</a>
</li>
        <li><a href="library/stdtypes.html#object.__dict__">(object attribute)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__displayhook__">__displayhook__ (in module sys)</a>
</li>
      <li><a href="library/operator.html#operator.__div__">__div__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__div__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__divmod__">__divmod__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-53">__doc__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="reference/datamodel.html#index-49">[1]</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.__enter__">__enter__() (_winreg.PyHKEY method)</a>

      <ul>
        <li><a href="library/stdtypes.html#contextmanager.__enter__">(contextmanager method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__enter__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.__eq__">__eq__() (email.charset.Charset method)</a>

      <ul>
        <li><a href="library/email.header.html#email.header.Header.__eq__">(email.header.Header method)</a>
</li>
        <li><a href="library/operator.html#operator.__eq__">(in module operator)</a>
</li>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__eq__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__excepthook__">__excepthook__ (in module sys)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.__exit__">__exit__() (_winreg.PyHKEY method)</a>

      <ul>
        <li><a href="library/stdtypes.html#contextmanager.__exit__">(contextmanager method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__exit__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__file__</a>

      <ul>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="c-api/module.html#index-5">[1]</a>, <a href="reference/datamodel.html#index-49">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__float__">__float__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__floordiv__">__floordiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__floordiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#index-3">__format__</a>
</li>
      <li><a href="library/datetime.html#datetime.date.__format__">__format__() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.__format__">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.__format__">(datetime.time method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-future"><strong>__future__</strong></a>

      <ul>
        <li><a href="library/__future__.html#module-__future__">(module)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ge__">__ge__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__ge__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__get__">__get__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__getattr__">__getattr__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__getattribute__">__getattribute__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__getinitargs__">__getinitargs__() (object method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__getitem__">__getitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__getitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__getitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#index-72">(mapping object method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__getitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__getnewargs__">__getnewargs__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__getslice__">__getslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__getslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__getstate__">__getstate__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__globals__ (function attribute)</a>
</li>
      <li><a href="library/operator.html#operator.__gt__">__gt__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__gt__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__hash__">__hash__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__hex__">__hex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__iadd__">__iadd__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__iadd__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__iadd__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__iand__">__iand__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__iand__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__iconcat__">__iconcat__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__idiv__">__idiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__idiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ifloordiv__">__ifloordiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ifloordiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ilshift__">__ilshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ilshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__imod__">__imod__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__imod__">(object method)</a>
</li>
      </ul></li>
      <li>
    __import__

      <ul>
        <li><a href="c-api/import.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#__import__">__import__() (built-in function)</a>
</li>
      <li><a href="library/operator.html#operator.__imul__">__imul__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__imul__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__index__">__index__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__index__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Handler.__init__">__init__() (logging.Handler method)</a>

      <ul>
        <li><a href="howto/logging.html#logging.logging.Formatter.__init__">(logging.logging.Formatter method)</a>
</li>
        <li><a href="reference/datamodel.html#index-46">(object method)</a>, <a href="reference/datamodel.html#object.__init__">[1]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#class.__instancecheck__">__instancecheck__() (class method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__int__">__int__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__inv__">__inv__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__invert__">__invert__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__invert__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ior__">__ior__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ior__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ipow__">__ipow__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ipow__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__irepeat__">__irepeat__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__irshift__">__irshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__irshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__isub__">__isub__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__isub__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__isub__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#container.__iter__">__iter__() (container method)</a>

      <ul>
        <li><a href="library/stdtypes.html#iterator.__iter__">(iterator method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__iter__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__iter__">(object method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.__iter__">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__itruediv__">__itruediv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__itruediv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ixor__">__ixor__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ixor__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__le__">__le__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__le__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.__len__">__len__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__len__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#index-82">(mapping object method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__len__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__len__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__loader__</a>
</li>
      <li><a href="reference/datamodel.html#object.__long__">__long__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__lshift__">__lshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__lshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__lt__">__lt__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__lt__">(object method)</a>
</li>
      </ul></li>
      <li>
    __main__

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/runpy.html#index-0">[3]</a>, <a href="library/runpy.html#index-3">[4]</a>, <a href="reference/executionmodel.html#index-11">[5]</a>, <a href="reference/toplevel_components.html#index-2">[6]</a>, <a href="reference/toplevel_components.html#index-3">[7]</a>
</li>
      </ul></li>
      <li><a href="library/__main__.html#module-__main__">__main__ (module)</a>
</li>
      <li><a href="library/stdtypes.html#object.__members__">__members__ (object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#__metaclass__">__metaclass__ (built-in variable)</a>
</li>
      <li><a href="library/stdtypes.html#object.__methods__">__methods__ (object attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-33">__missing__()</a>

      <ul>
        <li><a href="library/collections.html#collections.defaultdict.__missing__">(collections.defaultdict method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__missing__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__mod__">__mod__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__mod__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-53">__module__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#class.__mro__">__mro__ (class attribute)</a>
</li>
      <li><a href="library/operator.html#operator.__mul__">__mul__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__mul__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__name__</a>

      <ul>
        <li><a href="reference/datamodel.html#index-53">(class attribute)</a>
</li>
        <li><a href="library/stdtypes.html#definition.__name__">(definition attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="c-api/module.html#index-4">[1]</a>, <a href="reference/datamodel.html#index-49">[2]</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.__ne__">__ne__() (email.charset.Charset method)</a>

      <ul>
        <li><a href="library/email.header.html#email.header.Header.__ne__">(email.header.Header method)</a>
</li>
        <li><a href="library/operator.html#operator.__ne__">(in module operator)</a>
</li>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__ne__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__neg__">__neg__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__neg__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__new__">__new__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-88">__nonzero__() (object method)</a>, <a href="reference/datamodel.html#object.__nonzero__">[1]</a>
</li>
      <li><a href="library/operator.html#operator.__not__">__not__() (in module operator)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/datamodel.html#object.__oct__">__oct__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__or__">__or__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__or__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__package__</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">__path__</a>, <a href="reference/simple_stmts.html#index-46">[1]</a>
</li>
      <li><a href="library/operator.html#operator.__pos__">__pos__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__pos__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__pow__">__pow__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__pow__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__radd__">__radd__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rand__">__rand__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rcmp__">__rcmp__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rdiv__">__rdiv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rdivmod__">__rdivmod__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__reduce__">__reduce__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__reduce_ex__">__reduce_ex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__repeat__">__repeat__() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy.__repr__">__repr__() (multiprocessing.managers.BaseProxy method)</a>

      <ul>
        <li><a href="library/netrc.html#netrc.netrc.__repr__">(netrc.netrc method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__repr__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__reversed__">__reversed__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rfloordiv__">__rfloordiv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rlshift__">__rlshift__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rmod__">__rmod__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rmul__">__rmul__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__ror__">__ror__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rpow__">__rpow__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rrshift__">__rrshift__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__rshift__">__rshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__rshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__rsub__">__rsub__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rtruediv__">__rtruediv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rxor__">__rxor__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__set__">__set__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-84">__setattr__() (object method)</a>, <a href="reference/datamodel.html#object.__setattr__">[1]</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__setitem__">__setitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__setitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__setitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.__setitem__">(mailbox.Maildir method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__setitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__setslice__">__setslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__setslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__setstate__">__setstate__() (object method)</a>
</li>
      <li><a href="glossary.html#term-slots"><strong>__slots__</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#__slots__">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__stderr__">__stderr__ (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.__stdin__">__stdin__ (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.__stdout__">__stdout__ (in module sys)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.__str__">__str__() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.__str__">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.__str__">(datetime.time method)</a>
</li>
        <li><a href="library/email.charset.html#email.charset.Charset.__str__">(email.charset.Charset method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.__str__">(email.header.Header method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.__str__">(email.message.Message method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy.__str__">(multiprocessing.managers.BaseProxy method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__str__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__str__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__sub__">__sub__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__sub__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__sub__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#class.__subclasscheck__">__subclasscheck__() (class method)</a>
</li>
      <li><a href="library/stdtypes.html#class.__subclasses__">__subclasses__() (class method)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta.__subclasshook__">__subclasshook__() (abc.ABCMeta method)</a>
</li>
      <li><a href="library/operator.html#operator.__truediv__">__truediv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__truediv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.header.html#email.header.Header.__unicode__">__unicode__() (email.header.Header method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__unicode__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__xor__">__xor__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__xor__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.Structure._anonymous_">_anonymous_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/collections.html#collections.somenamedtuple._asdict">_asdict() (collections.somenamedtuple method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._b_base_">_b_base_ (ctypes._CData attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._b_needsfree_">_b_needsfree_ (ctypes._CData attribute)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy._callmethod">_callmethod() (multiprocessing.managers.BaseProxy method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData">_CData (class in ctypes)</a>
</li>
      <li><a href="library/sys.html#sys._clear_type_cache">_clear_type_cache() (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys._current_frames">_current_frames() (in module sys)</a>
</li>
      <li><a href="library/os.html#os._exit">_exit() (in module os)</a>
</li>
      <li><a href="library/ast.html#ast.AST._fields">_fields (ast.AST attribute)</a>

      <ul>
        <li><a href="library/collections.html#collections.somenamedtuple._fields">(collections.somenamedtuple attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.Structure._fields_">_fields_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler._flush">_flush() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="c-api/import.html#c._frozen">_frozen (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr">_FuncPtr (class in ctypes)</a>
</li>
      <li><a href="library/sys.html#sys._getframe">_getframe() (in module sys)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy._getvalue">_getvalue() (multiprocessing.managers.BaseProxy method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL._handle">_handle (ctypes.PyDLL attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl._https_verify_certificates">_https_verify_certificates() (in module ssl)</a>
</li>
      <li><a href="c-api/import.html#c._inittab">_inittab (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Array._length_">_length_ (ctypes.Array attribute)</a>
</li>
      <li>
    _locale

      <ul>
        <li><a href="library/locale.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.somenamedtuple._make">_make() (collections.somenamedtuple class method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestRunner._makeResult">_makeResult() (unittest.TextTestRunner method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL._name">_name (ctypes.PyDLL attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._objects">_objects (ctypes._CData attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Structure._pack_">_pack_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations._parse">_parse() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer">_Pointer (class in ctypes)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_diff">_Py_c_diff (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_neg">_Py_c_neg (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_pow">_Py_c_pow (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_prod">_Py_c_prod (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_quot">_Py_c_quot (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_sum">_Py_c_sum (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._Py_NoneStruct">_Py_NoneStruct (C variable)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_FindExtension">_PyImport_FindExtension (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_Fini">_PyImport_Fini (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_FixupExtension">_PyImport_FixupExtension (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_Init">_PyImport_Init (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_Del">_PyObject_Del (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c._PyObject_GC_TRACK">_PyObject_GC_TRACK (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c._PyObject_GC_UNTRACK">_PyObject_GC_UNTRACK (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_New">_PyObject_New (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_NewVar">_PyObject_NewVar (C function)</a>
</li>
      <li><a href="c-api/string.html#c._PyString_Resize">_PyString_Resize (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c._PyTuple_Resize">_PyTuple_Resize (C function)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application._quit">_quit() (FrameWork.Application method)</a>
</li>
      <li><a href="library/collections.html#collections.somenamedtuple._replace">_replace() (collections.somenamedtuple method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree._setroot">_setroot() (xml.etree.ElementTree.ElementTree method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._SimpleCData">_SimpleCData (class in ctypes)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo._start">_start() (aetools.TalkTo method)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators._structure">_structure() (in module email.iterators)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer._type_">_type_ (ctypes._Pointer attribute)</a>

      <ul>
        <li><a href="library/ctypes.html#ctypes.Array._type_">(ctypes.Array attribute)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib._urlopener">_urlopener (in module urllib)</a>
</li>
      <li><a href="library/_winreg.html#module-_winreg">_winreg (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler._write">_write() (wsgiref.handlers.BaseHandler method)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\{Q-p==html/genindex-all.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-all.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index</h1>

<div class="genindex-jumpbox">
 <a href="#Symbols"><strong>Symbols</strong></a>
 | <a href="#_"><strong>_</strong></a>
 | <a href="#A"><strong>A</strong></a>
 | <a href="#B"><strong>B</strong></a>
 | <a href="#C"><strong>C</strong></a>
 | <a href="#D"><strong>D</strong></a>
 | <a href="#E"><strong>E</strong></a>
 | <a href="#F"><strong>F</strong></a>
 | <a href="#G"><strong>G</strong></a>
 | <a href="#H"><strong>H</strong></a>
 | <a href="#I"><strong>I</strong></a>
 | <a href="#J"><strong>J</strong></a>
 | <a href="#K"><strong>K</strong></a>
 | <a href="#L"><strong>L</strong></a>
 | <a href="#M"><strong>M</strong></a>
 | <a href="#N"><strong>N</strong></a>
 | <a href="#O"><strong>O</strong></a>
 | <a href="#P"><strong>P</strong></a>
 | <a href="#Q"><strong>Q</strong></a>
 | <a href="#R"><strong>R</strong></a>
 | <a href="#S"><strong>S</strong></a>
 | <a href="#T"><strong>T</strong></a>
 | <a href="#U"><strong>U</strong></a>
 | <a href="#V"><strong>V</strong></a>
 | <a href="#W"><strong>W</strong></a>
 | <a href="#X"><strong>X</strong></a>
 | <a href="#Y"><strong>Y</strong></a>
 | <a href="#Z"><strong>Z</strong></a>
 
</div>
<h2 id="Symbols">Symbols</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    !=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    %

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#index-25">% formatting</a>
</li>
      <li><a href="library/stdtypes.html#index-25">% interpolation</a>
</li>
      <li>
    %=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="using/windows.html#index-1">%PATH%</a>
</li>
      <li>
    &amp;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &amp;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    *

      <ul>
        <li><a href="reference/expressions.html#index-40">in function calls</a>
</li>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">statement</a>, <a href="tutorial/controlflow.html#index-2">[1]</a>
</li>
      </ul></li>
      <li>
    **

      <ul>
        <li><a href="reference/expressions.html#index-41">in function calls</a>
</li>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">statement</a>, <a href="tutorial/controlflow.html#index-3">[1]</a>
</li>
      </ul></li>
      <li>
    **=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    *=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    +

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    +=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    -

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    --help

      <ul>
        <li><a href="using/cmdline.html#cmdoption-help">command line option</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-help">trace command line option</a>
</li>
      </ul></li>
      <li>
    --ignore-dir=&lt;dir&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-ignore-dir">trace command line option</a>
</li>
      </ul></li>
      <li>
    --ignore-module=&lt;mod&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-ignore-module">trace command line option</a>
</li>
      </ul></li>
      <li>
    --user-base

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-base">site command line option</a>
</li>
      </ul></li>
      <li>
    --user-site

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-site">site command line option</a>
</li>
      </ul></li>
      <li>
    --version

      <ul>
        <li><a href="using/cmdline.html#cmdoption-version">command line option</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-version">trace command line option</a>
</li>
      </ul></li>
      <li>
    -3

      <ul>
        <li><a href="using/cmdline.html#cmdoption-3">command line option</a>
</li>
      </ul></li>
      <li>
    -=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    -?

      <ul>
        <li><a href="using/cmdline.html#cmdoption">command line option</a>
</li>
      </ul></li>
      <li>
    -B

      <ul>
        <li><a href="using/cmdline.html#id1">command line option</a>
</li>
      </ul></li>
      <li>
    -b

      <ul>
        <li><a href="using/cmdline.html#cmdoption-b">command line option</a>
</li>
      </ul></li>
      <li>
    -b, --buffer

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-b">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -c &lt;command&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-c">command line option</a>
</li>
      </ul></li>
      <li>
    -c &lt;zipfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-c">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -c, --catch

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-c">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -c, --clock

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-c">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -c, --count

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-c">trace command line option</a>
</li>
      </ul></li>
      <li>
    -C, --coverdir=&lt;dir&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-coverdir">trace command line option</a>
</li>
      </ul></li>
      <li>
    -d

      <ul>
        <li><a href="using/cmdline.html#cmdoption-d">command line option</a>
</li>
      </ul></li>
      <li>
    -d destdir

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-d">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -E

      <ul>
        <li><a href="using/cmdline.html#cmdoption-e">command line option</a>
</li>
      </ul></li>
      <li>
    -e &lt;zipfile&gt; &lt;output_dir&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-e">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -f

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-f">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -f, --failfast

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-f">unittest command line option</a>
</li>
      </ul></li>
      <li>
    -f, --file=&lt;file&gt;

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-f">trace command line option</a>
</li>
      </ul></li>
      <li>
    -g, --timing

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-g">trace command line option</a>
</li>
      </ul></li>
      <li>
    -h

      <ul>
        <li><a href="using/cmdline.html#cmdoption-h">command line option</a>
</li>
      </ul></li>
      <li>
    -h, --help

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-h">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -i

      <ul>
        <li><a href="using/cmdline.html#cmdoption-i">command line option</a>
</li>
      </ul></li>
      <li>
    -i list

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-i">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -J

      <ul>
        <li><a href="using/cmdline.html#cmdoption-j">command line option</a>
</li>
      </ul></li>
      <li>
    -l

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-l">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -l &lt;zipfile&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-l">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -l, --listfuncs

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-l">trace command line option</a>
</li>
      </ul></li>
      <li>
    -m &lt;module-name&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-m">command line option</a>
</li>
      </ul></li>
      <li>
    -m, --missing

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-m">trace command line option</a>
</li>
      </ul></li>
      <li>
    -n N, --number=N

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-n">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -O

      <ul>
        <li><a href="using/cmdline.html#cmdoption-o">command line option</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    -OO

      <ul>
        <li><a href="using/cmdline.html#cmdoption-oo">command line option</a>
</li>
      </ul></li>
      <li>
    -p, --pattern pattern

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-p">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -q

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-q">compileall command line option</a>
</li>
      </ul></li>
      <li>
    -Q &lt;arg&gt;

      <ul>
        <li><a href="using/cmdline.html#cmdoption-q">command line option</a>
</li>
      </ul></li>
      <li>
    -R

      <ul>
        <li><a href="using/cmdline.html#cmdoption-r">command line option</a>
</li>
      </ul></li>
      <li>
    -r N, --repeat=N

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-r">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -R, --no-report

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-no-report">trace command line option</a>
</li>
      </ul></li>
      <li>
    -r, --report

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-r">trace command line option</a>
</li>
      </ul></li>
      <li>
    -S

      <ul>
        <li><a href="using/cmdline.html#id2">command line option</a>
</li>
      </ul></li>
      <li>
    -s

      <ul>
        <li><a href="using/cmdline.html#cmdoption-s">command line option</a>
</li>
      </ul></li>
      <li>
    -s S, --setup=S

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-s">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -s, --start-directory directory

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-s">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -s, --summary

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-s">trace command line option</a>
</li>
      </ul></li>
      <li>
    -t

      <ul>
        <li><a href="using/cmdline.html#cmdoption-t">command line option</a>
</li>
      </ul></li>
      <li>
    -t &lt;zipfile&gt;

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-t">zipfile command line option</a>
</li>
      </ul></li>
      <li>
    -t, --time

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-t">timeit command line option</a>
</li>
      </ul></li>
      <li>
    -t, --top-level-directory directory

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-t">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -t, --trace

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-t">trace command line option</a>
</li>
      </ul></li>
      <li>
    -T, --trackcalls

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-trackcalls">trace command line option</a>
</li>
      </ul></li>
      <li>
    -U

      <ul>
        <li><a href="using/cmdline.html#id4">command line option</a>
</li>
      </ul></li>
      <li>
    -u

      <ul>
        <li><a href="using/cmdline.html#cmdoption-u">command line option</a>
</li>
      </ul></li>
      <li>
    -V

      <ul>
        <li><a href="using/cmdline.html#cmdoption-v">command line option</a>
</li>
      </ul></li>
      <li>
    -v

      <ul>
        <li><a href="using/cmdline.html#id3">command line option</a>
</li>
      </ul></li>
      <li>
    -v, --verbose

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-v">timeit command line option</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-v">unittest-discover command line option</a>
</li>
      </ul></li>
      <li>
    -W arg

      <ul>
        <li><a href="using/cmdline.html#cmdoption-w">command line option</a>
</li>
      </ul></li>
      <li>
    -X

      <ul>
        <li><a href="using/cmdline.html#id5">command line option</a>
</li>
      </ul></li>
      <li>
    -x

      <ul>
        <li><a href="using/cmdline.html#cmdoption-x">command line option</a>
</li>
      </ul></li>
      <li>
    -x regex

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-x">compileall command line option</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-1"><strong>...</strong></a>
</li>
      <li>
    .ini

      <ul>
        <li><a href="library/configparser.html#index-0">file</a>
</li>
      </ul></li>
      <li>
    .pdbrc

      <ul>
        <li><a href="library/pdb.html#index-2">file</a>
</li>
      </ul></li>
      <li><a href="distutils/packageindex.html#index-2">.pypirc file</a>
</li>
      <li>
    .pythonrc.py

      <ul>
        <li><a href="library/user.html#index-0">file</a>
</li>
      </ul></li>
      <li>
    /

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    //

      <ul>
        <li><a href="library/stdtypes.html#index-15">operator</a>
</li>
      </ul></li>
      <li>
    //=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    /=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-2to3"><strong>2to3</strong></a>
</li>
      <li>
    &lt;

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &lt;&lt;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &lt;&lt;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    &lt;=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#index-2">&lt;protocol&gt;_proxy</a>
</li>
      <li>
    =

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">assignment statement</a>
</li>
      </ul></li>
      <li>
    ==

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;=

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
      </ul></li>
      <li>
    &gt;&gt;

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    &gt;&gt;=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term"><strong>&gt;&gt;&gt;</strong></a>
</li>
      <li>
    @

      <ul>
        <li><a href="reference/compound_stmts.html#index-19">statement</a>
</li>
      </ul></li>
      <li>
    ^

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    ^=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    |

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
      <li>
    |=

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">augmented assignment</a>
</li>
      </ul></li>
      <li>
    ~

      <ul>
        <li><a href="library/stdtypes.html#index-19">operator</a>
</li>
      </ul></li>
  </ul></td>
</tr></table>

<h2 id="_">_</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/operator.html#operator.__abs__">__abs__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__abs__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__add__">__add__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__add__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__add__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="tutorial/modules.html#index-8">__all__</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-49">(optional module attribute)</a>
</li>
        <li><a href="c-api/import.html#index-0">(package variable)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__and__">__and__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__and__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#class.__bases__">__bases__ (class attribute)</a>, <a href="reference/datamodel.html#index-53">[1]</a>
</li>
      <li>
    __builtin__

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/intro.html#index-20">[1]</a>, <a href="reference/simple_stmts.html#index-57">[2]</a>, <a href="reference/toplevel_components.html#index-2">[3]</a>, <a href="tutorial/modules.html#index-7">[4]</a>
</li>
      </ul></li>
      <li><a href="library/__builtin__.html#module-__builtin__">__builtin__ (module)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-57">__builtins__</a>
</li>
      <li><a href="reference/datamodel.html#object.__call__">__call__() (object method)</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
      <li><a href="library/stdtypes.html#instance.__class__">__class__ (instance attribute)</a>, <a href="reference/datamodel.html#index-57">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__closure__ (function attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-11">__cmp__() (instance method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__cmp__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-37">__code__ (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#object.__coerce__">__coerce__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__complex__">__complex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__concat__">__concat__() (in module operator)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__contains__">__contains__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__contains__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__contains__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__contains__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#index-1">__copy__() (copy protocol)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-16">__debug__</a>

      <ul>
        <li><a href="library/constants.html#__debug__">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#index-1">__deepcopy__() (copy protocol)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__defaults__ (function attribute)</a>
</li>
      <li><a href="library/io.html#io.IOBase.__del__">__del__() (io.IOBase method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__del__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__delattr__">__delattr__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__delete__">__delete__() (object method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__delitem__">__delitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__delitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.__delitem__">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__delitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__delitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__delslice__">__delslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__delslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-53">__dict__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-57">(instance attribute)</a>, <a href="reference/datamodel.html#index-85">[1]</a>
</li>
        <li><a href="c-api/module.html#index-3">(module attribute)</a>, <a href="reference/datamodel.html#index-48">[1]</a>
</li>
        <li><a href="library/stdtypes.html#object.__dict__">(object attribute)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__displayhook__">__displayhook__ (in module sys)</a>
</li>
      <li><a href="library/operator.html#operator.__div__">__div__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__div__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__divmod__">__divmod__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-53">__doc__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="reference/datamodel.html#index-49">[1]</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.__enter__">__enter__() (_winreg.PyHKEY method)</a>

      <ul>
        <li><a href="library/stdtypes.html#contextmanager.__enter__">(contextmanager method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__enter__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.__eq__">__eq__() (email.charset.Charset method)</a>

      <ul>
        <li><a href="library/email.header.html#email.header.Header.__eq__">(email.header.Header method)</a>
</li>
        <li><a href="library/operator.html#operator.__eq__">(in module operator)</a>
</li>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__eq__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__excepthook__">__excepthook__ (in module sys)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.__exit__">__exit__() (_winreg.PyHKEY method)</a>

      <ul>
        <li><a href="library/stdtypes.html#contextmanager.__exit__">(contextmanager method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__exit__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__file__</a>

      <ul>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="c-api/module.html#index-5">[1]</a>, <a href="reference/datamodel.html#index-49">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__float__">__float__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__floordiv__">__floordiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__floordiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#index-3">__format__</a>
</li>
      <li><a href="library/datetime.html#datetime.date.__format__">__format__() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.__format__">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.__format__">(datetime.time method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-future"><strong>__future__</strong></a>

      <ul>
        <li><a href="library/__future__.html#module-__future__">(module)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ge__">__ge__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__ge__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__get__">__get__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__getattr__">__getattr__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__getattribute__">__getattribute__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__getinitargs__">__getinitargs__() (object method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__getitem__">__getitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__getitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__getitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#index-72">(mapping object method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__getitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__getnewargs__">__getnewargs__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__getslice__">__getslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__getslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__getstate__">__getstate__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">__globals__ (function attribute)</a>
</li>
      <li><a href="library/operator.html#operator.__gt__">__gt__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__gt__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__hash__">__hash__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__hex__">__hex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__iadd__">__iadd__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__iadd__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__iadd__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__iand__">__iand__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__iand__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__iconcat__">__iconcat__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__idiv__">__idiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__idiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ifloordiv__">__ifloordiv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ifloordiv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ilshift__">__ilshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ilshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__imod__">__imod__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__imod__">(object method)</a>
</li>
      </ul></li>
      <li>
    __import__

      <ul>
        <li><a href="c-api/import.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#__import__">__import__() (built-in function)</a>
</li>
      <li><a href="library/operator.html#operator.__imul__">__imul__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__imul__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__index__">__index__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__index__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Handler.__init__">__init__() (logging.Handler method)</a>

      <ul>
        <li><a href="howto/logging.html#logging.logging.Formatter.__init__">(logging.logging.Formatter method)</a>
</li>
        <li><a href="reference/datamodel.html#index-46">(object method)</a>, <a href="reference/datamodel.html#object.__init__">[1]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#class.__instancecheck__">__instancecheck__() (class method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__int__">__int__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__inv__">__inv__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__invert__">__invert__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__invert__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ior__">__ior__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ior__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ipow__">__ipow__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ipow__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__irepeat__">__irepeat__() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.__irshift__">__irshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__irshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__isub__">__isub__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__isub__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__isub__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#container.__iter__">__iter__() (container method)</a>

      <ul>
        <li><a href="library/stdtypes.html#iterator.__iter__">(iterator method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__iter__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__iter__">(object method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.__iter__">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__itruediv__">__itruediv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__itruediv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__ixor__">__ixor__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__ixor__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__le__">__le__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__le__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.__len__">__len__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__len__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="reference/datamodel.html#index-82">(mapping object method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__len__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__len__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__loader__</a>
</li>
      <li><a href="reference/datamodel.html#object.__long__">__long__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__lshift__">__lshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__lshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__lt__">__lt__() (in module operator)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__lt__">(object method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    __main__

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/runpy.html#index-0">[3]</a>, <a href="library/runpy.html#index-3">[4]</a>, <a href="reference/executionmodel.html#index-11">[5]</a>, <a href="reference/toplevel_components.html#index-2">[6]</a>, <a href="reference/toplevel_components.html#index-3">[7]</a>
</li>
      </ul></li>
      <li><a href="library/__main__.html#module-__main__">__main__ (module)</a>
</li>
      <li><a href="library/stdtypes.html#object.__members__">__members__ (object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#__metaclass__">__metaclass__ (built-in variable)</a>
</li>
      <li><a href="library/stdtypes.html#object.__methods__">__methods__ (object attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-33">__missing__()</a>

      <ul>
        <li><a href="library/collections.html#collections.defaultdict.__missing__">(collections.defaultdict method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__missing__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__mod__">__mod__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__mod__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-53">__module__ (class attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#class.__mro__">__mro__ (class attribute)</a>
</li>
      <li><a href="library/operator.html#operator.__mul__">__mul__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__mul__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__name__</a>

      <ul>
        <li><a href="reference/datamodel.html#index-53">(class attribute)</a>
</li>
        <li><a href="library/stdtypes.html#definition.__name__">(definition attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-37">(function attribute)</a>
</li>
        <li><a href="reference/datamodel.html#index-39">(method attribute)</a>
</li>
        <li><a href="c-api/module.html#index-2">(module attribute)</a>, <a href="c-api/module.html#index-4">[1]</a>, <a href="reference/datamodel.html#index-49">[2]</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.__ne__">__ne__() (email.charset.Charset method)</a>

      <ul>
        <li><a href="library/email.header.html#email.header.Header.__ne__">(email.header.Header method)</a>
</li>
        <li><a href="library/operator.html#operator.__ne__">(in module operator)</a>
</li>
        <li><a href="library/stdtypes.html#index-11">(instance method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__ne__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__neg__">__neg__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__neg__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__new__">__new__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-88">__nonzero__() (object method)</a>, <a href="reference/datamodel.html#object.__nonzero__">[1]</a>
</li>
      <li><a href="library/operator.html#operator.__not__">__not__() (in module operator)</a>
</li>
      <li><a href="reference/datamodel.html#object.__oct__">__oct__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__or__">__or__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__or__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-46">__package__</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">__path__</a>, <a href="reference/simple_stmts.html#index-46">[1]</a>
</li>
      <li><a href="library/operator.html#operator.__pos__">__pos__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__pos__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__pow__">__pow__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__pow__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__radd__">__radd__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rand__">__rand__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rcmp__">__rcmp__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rdiv__">__rdiv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rdivmod__">__rdivmod__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__reduce__">__reduce__() (object method)</a>
</li>
      <li><a href="library/pickle.html#object.__reduce_ex__">__reduce_ex__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__repeat__">__repeat__() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy.__repr__">__repr__() (multiprocessing.managers.BaseProxy method)</a>

      <ul>
        <li><a href="library/netrc.html#netrc.netrc.__repr__">(netrc.netrc method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__repr__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__reversed__">__reversed__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rfloordiv__">__rfloordiv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rlshift__">__rlshift__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rmod__">__rmod__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rmul__">__rmul__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__ror__">__ror__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rpow__">__rpow__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rrshift__">__rrshift__() (object method)</a>
</li>
      <li><a href="library/operator.html#operator.__rshift__">__rshift__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__rshift__">(object method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#object.__rsub__">__rsub__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rtruediv__">__rtruediv__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__rxor__">__rxor__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#object.__set__">__set__() (object method)</a>
</li>
      <li><a href="reference/datamodel.html#index-84">__setattr__() (object method)</a>, <a href="reference/datamodel.html#object.__setattr__">[1]</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.__setitem__">__setitem__() (email.message.Message method)</a>

      <ul>
        <li><a href="library/operator.html#operator.__setitem__">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.__setitem__">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.__setitem__">(mailbox.Maildir method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__setitem__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__setslice__">__setslice__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__setslice__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#object.__setstate__">__setstate__() (object method)</a>
</li>
      <li><a href="glossary.html#term-slots"><strong>__slots__</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#__slots__">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.__stderr__">__stderr__ (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.__stdin__">__stdin__ (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.__stdout__">__stdout__ (in module sys)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.__str__">__str__() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.__str__">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.__str__">(datetime.time method)</a>
</li>
        <li><a href="library/email.charset.html#email.charset.Charset.__str__">(email.charset.Charset method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.__str__">(email.header.Header method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.__str__">(email.message.Message method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy.__str__">(multiprocessing.managers.BaseProxy method)</a>
</li>
        <li><a href="reference/datamodel.html#object.__str__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__str__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__sub__">__sub__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__sub__">(object method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.AddressList.__sub__">(rfc822.AddressList method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#class.__subclasscheck__">__subclasscheck__() (class method)</a>
</li>
      <li><a href="library/stdtypes.html#class.__subclasses__">__subclasses__() (class method)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta.__subclasshook__">__subclasshook__() (abc.ABCMeta method)</a>
</li>
      <li><a href="library/operator.html#operator.__truediv__">__truediv__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__truediv__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/email.header.html#email.header.Header.__unicode__">__unicode__() (email.header.Header method)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__unicode__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.__xor__">__xor__() (in module operator)</a>

      <ul>
        <li><a href="reference/datamodel.html#object.__xor__">(object method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.Structure._anonymous_">_anonymous_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/collections.html#collections.somenamedtuple._asdict">_asdict() (collections.somenamedtuple method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._b_base_">_b_base_ (ctypes._CData attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._b_needsfree_">_b_needsfree_ (ctypes._CData attribute)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy._callmethod">_callmethod() (multiprocessing.managers.BaseProxy method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData">_CData (class in ctypes)</a>
</li>
      <li><a href="library/sys.html#sys._clear_type_cache">_clear_type_cache() (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys._current_frames">_current_frames() (in module sys)</a>
</li>
      <li><a href="library/os.html#os._exit">_exit() (in module os)</a>
</li>
      <li><a href="library/ast.html#ast.AST._fields">_fields (ast.AST attribute)</a>

      <ul>
        <li><a href="library/collections.html#collections.somenamedtuple._fields">(collections.somenamedtuple attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.Structure._fields_">_fields_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler._flush">_flush() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="c-api/import.html#c._frozen">_frozen (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr">_FuncPtr (class in ctypes)</a>
</li>
      <li><a href="library/sys.html#sys._getframe">_getframe() (in module sys)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy._getvalue">_getvalue() (multiprocessing.managers.BaseProxy method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL._handle">_handle (ctypes.PyDLL attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl._https_verify_certificates">_https_verify_certificates() (in module ssl)</a>
</li>
      <li><a href="c-api/import.html#c._inittab">_inittab (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Array._length_">_length_ (ctypes.Array attribute)</a>
</li>
      <li>
    _locale

      <ul>
        <li><a href="library/locale.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.somenamedtuple._make">_make() (collections.somenamedtuple class method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestRunner._makeResult">_makeResult() (unittest.TextTestRunner method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL._name">_name (ctypes.PyDLL attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData._objects">_objects (ctypes._CData attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Structure._pack_">_pack_ (ctypes.Structure attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations._parse">_parse() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer">_Pointer (class in ctypes)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_diff">_Py_c_diff (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_neg">_Py_c_neg (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_pow">_Py_c_pow (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_prod">_Py_c_prod (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_quot">_Py_c_quot (C function)</a>
</li>
      <li><a href="c-api/complex.html#c._Py_c_sum">_Py_c_sum (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._Py_NoneStruct">_Py_NoneStruct (C variable)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_FindExtension">_PyImport_FindExtension (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_Fini">_PyImport_Fini (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_FixupExtension">_PyImport_FixupExtension (C function)</a>
</li>
      <li><a href="c-api/import.html#c._PyImport_Init">_PyImport_Init (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_Del">_PyObject_Del (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c._PyObject_GC_TRACK">_PyObject_GC_TRACK (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c._PyObject_GC_UNTRACK">_PyObject_GC_UNTRACK (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_New">_PyObject_New (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c._PyObject_NewVar">_PyObject_NewVar (C function)</a>
</li>
      <li><a href="c-api/string.html#c._PyString_Resize">_PyString_Resize (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c._PyTuple_Resize">_PyTuple_Resize (C function)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application._quit">_quit() (FrameWork.Application method)</a>
</li>
      <li><a href="library/collections.html#collections.somenamedtuple._replace">_replace() (collections.somenamedtuple method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree._setroot">_setroot() (xml.etree.ElementTree.ElementTree method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._SimpleCData">_SimpleCData (class in ctypes)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo._start">_start() (aetools.TalkTo method)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators._structure">_structure() (in module email.iterators)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer._type_">_type_ (ctypes._Pointer attribute)</a>

      <ul>
        <li><a href="library/ctypes.html#ctypes.Array._type_">(ctypes.Array attribute)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib._urlopener">_urlopener (in module urllib)</a>
</li>
      <li><a href="library/_winreg.html#module-_winreg">_winreg (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler._write">_write() (wsgiref.handlers.BaseHandler method)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="A">A</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/aifc.html#index-1">A-LAW</a>, <a href="library/sndhdr.html#index-0">[1]</a>
</li>
      <li><a href="library/audioop.html#index-0">a-LAW</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_base64">a2b_base64() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_hex">a2b_hex() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_hqx">a2b_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_qp">a2b_qp() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_uu">a2b_uu() (in module binascii)</a>
</li>
      <li><a href="library/abc.html#module-abc">abc (module)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta">ABCMeta (class in abc)</a>
</li>
      <li><a href="c-api/sys.html#index-0">abort()</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.abort">(ftplib.FTP method)</a>
</li>
        <li><a href="library/os.html#os.abort">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.above">above() (curses.panel.Panel method)</a>
</li>
      <li>
    abs

      <ul>
        <li><a href="c-api/number.html#index-2">built-in function</a>, <a href="reference/datamodel.html#index-93">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#abs">abs() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.abs">(decimal.Context method)</a>
</li>
        <li><a href="library/operator.html#operator.abs">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.abspath">abspath() (in module os.path)</a>
</li>
      <li><a href="glossary.html#term-abstract-base-class"><strong>abstract base class</strong></a>
</li>
      <li><a href="library/urllib2.html#urllib2.AbstractBasicAuthHandler">AbstractBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.AbstractDigestAuthHandler">AbstractDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/formatter.html#formatter.AbstractFormatter">AbstractFormatter (class in formatter)</a>
</li>
      <li><a href="library/abc.html#abc.abstractmethod">abstractmethod() (in module abc)</a>
</li>
      <li><a href="library/abc.html#abc.abstractproperty">abstractproperty() (in module abc)</a>
</li>
      <li><a href="library/formatter.html#formatter.AbstractWriter">AbstractWriter (class in formatter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.accept">accept() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.accept">(multiprocessing.connection.Listener method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.accept">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.accept2dyear">accept2dyear (in module time)</a>
</li>
      <li><a href="library/os.html#os.access">access() (in module os)</a>
</li>
      <li><a href="library/cmath.html#cmath.acos">acos() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.acos">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.acosh">acosh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.acosh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Handler.acquire">acquire() (logging.Handler method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Lock.acquire">(multiprocessing.Lock method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.RLock.acquire">(multiprocessing.RLock method)</a>
</li>
        <li><a href="library/thread.html#thread.lock.acquire">(thread.lock method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.acquire">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Lock.acquire">(threading.Lock method)</a>
</li>
        <li><a href="library/threading.html#threading.RLock.acquire">(threading.RLock method)</a>
</li>
        <li><a href="library/threading.html#threading.Semaphore.acquire">(threading.Semaphore method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.acquire_lock">acquire_lock() (in module imp)</a>
</li>
      <li><a href="library/argparse.html#argparse.Action">Action (class in argparse)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.action">action (optparse.Option attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.ACTIONS">ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.activate_form">activate_form() (fl.form method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.active_children">active_children() (in module multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.active_count">active_count() (in module threading)</a>
</li>
      <li><a href="library/threading.html#threading.activeCount">activeCount() (in module threading)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.add">add() (decimal.Context method)</a>

      <ul>
        <li><a href="library/stdtypes.html#frozenset.add">(frozenset method)</a>
</li>
        <li><a href="library/audioop.html#audioop.add">(in module audioop)</a>
</li>
        <li><a href="library/operator.html#operator.add">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.add">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.add">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/msilib.html#msilib.RadioButtonGroup.add">(msilib.RadioButtonGroup method)</a>
</li>
        <li><a href="library/profile.html#pstats.Stats.add">(pstats.Stats method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.add">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.add">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.add_alias">add_alias() (in module email.charset)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_argument">add_argument() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_argument_group">add_argument_group() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_box">add_box() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_browser">add_browser() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_button">add_button() (fl.form method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.add_cgi_vars">add_cgi_vars() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.add_charset">add_charset() (in module email.charset)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_choice">add_choice() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_clock">add_clock() (fl.form method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.add_codec">add_codec() (in module email.charset)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.add_cookie_header">add_cookie_header() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_counter">add_counter() (fl.form method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_data">add_data() (in module msilib)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.add_data">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.add_dial">add_dial() (fl.form method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.add_fallback">add_fallback() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Directory.add_file">add_file() (msilib.Directory method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.add_flag">add_flag() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.add_flag">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.add_flag">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.add_flowing_data">add_flowing_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.add_folder">add_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.add_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.OpenerDirector.add_handler">add_handler() (urllib2.OpenerDirector method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.add_header">add_header() (email.message.Message method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.add_header">(urllib2.Request method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.headers.Headers.add_header">(wsgiref.headers.Headers method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.add_history">add_history() (in module readline)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_hor_rule">add_hor_rule() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_include_dir">add_include_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_input">add_input() (fl.form method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.add_label">add_label() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_label_data">add_label_data() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_library">add_library() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_library_dir">add_library_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_lightbutton">add_lightbutton() (fl.form method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_line_break">add_line_break() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_link_object">add_link_object() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_literal_data">add_literal_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_menu">add_menu() (fl.form method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_mutually_exclusive_group">add_mutually_exclusive_group() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.add_option">add_option() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.add_parent">add_parent() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr.add_password">add_password() (urllib2.HTTPPasswordMgr method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_positioner">add_positioner() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_roundbutton">add_roundbutton() (fl.form method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_runtime_library_dir">add_runtime_library_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.add_section">add_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage.add_sequence">add_sequence() (mailbox.MHMessage method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_slider">add_slider() (fl.form method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_stream">add_stream() (in module msilib)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_subparsers">add_subparsers() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager.add_suffix">add_suffix() (imputil.ImportManager method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_tables">add_tables() (in module msilib)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_text">add_text() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_timer">add_timer() (fl.form method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.add_type">add_type() (in module mimetypes)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.add_unredirected_header">add_unredirected_header() (urllib2.Request method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_valslider">add_valslider() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.window.addch">addch() (curses.window method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.addCleanup">addCleanup() (unittest.TestCase method)</a>
</li>
      <li><a href="library/turtle.html#turtle.Shape.addcomponent">addcomponent() (turtle.Shape method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addError">addError() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addExpectedFailure">addExpectedFailure() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addFailure">addFailure() (unittest.TestResult method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.addfile">addfile() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.addFilter">addFilter() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.addFilter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger.addHandler">addHandler() (logging.Logger method)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.addheader">addheader() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile.addinfo">addinfo() (hotshot.Profile method)</a>
</li>
      <li><a href="reference/expressions.html#index-56">addition</a>
</li>
      <li><a href="library/logging.html#logging.addLevelName">addLevelName() (in module logging)</a>
</li>
      <li><a href="library/curses.html#curses.window.addnstr">addnstr() (curses.window method)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.AddPackagePath">AddPackagePath() (in module modulefinder)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.address">address (multiprocessing.connection.Listener attribute)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.address">(multiprocessing.managers.BaseManager attribute)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.address_family">address_family (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.address_string">address_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.AddressList">AddressList (class in rfc822)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.AddressList.addresslist">addresslist (rfc822.AddressList attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.addressof">addressof() (in module ctypes)</a>
</li>
      <li><a href="library/turtle.html#turtle.addshape">addshape() (in module turtle)</a>
</li>
      <li><a href="library/site.html#site.addsitedir">addsitedir() (in module site)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addSkip">addSkip() (unittest.TestResult method)</a>
</li>
      <li><a href="library/curses.html#curses.window.addstr">addstr() (curses.window method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addSuccess">addSuccess() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite.addTest">addTest() (unittest.TestSuite method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite.addTests">addTests() (unittest.TestSuite method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.addTypeEqualityFunc">addTypeEqualityFunc() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addUnexpectedSuccess">addUnexpectedSuccess() (unittest.TestResult method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.adjusted">adjusted() (decimal.Decimal method)</a>
</li>
      <li><a href="library/zlib.html#zlib.adler32">adler32() (in module zlib)</a>
</li>
      <li><a href="library/audioop.html#index-0">ADPCM, Intel/DVI</a>
</li>
      <li><a href="library/audioop.html#audioop.adpcm2lin">adpcm2lin() (in module audioop)</a>
</li>
      <li><a href="library/aepack.html#module-aepack">aepack (module)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer">AEServer (class in MiniAEFrame)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.AEText">AEText (class in aetypes)</a>
</li>
      <li><a href="library/aetools.html#module-aetools">aetools (module)</a>
</li>
      <li><a href="library/aetypes.html#module-aetypes">aetypes (module)</a>
</li>
      <li><a href="library/socket.html#socket.AF_INET">AF_INET (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.AF_INET6">AF_INET6 (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.AF_UNIX">AF_UNIX (in module socket)</a>
</li>
      <li><a href="library/aifc.html#module-aifc">aifc (module)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.aifc">aifc() (aifc.aifc method)</a>
</li>
      <li><a href="library/aifc.html#index-0">AIFF</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.aiff">aiff() (aifc.aifc method)</a>
</li>
      <li><a href="library/aifc.html#index-0">AIFF-C</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li>
    AL

      <ul>
        <li><a href="library/al.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/al.html#module-AL">AL (module)</a>
</li>
      <li><a href="library/al.html#module-al">al (module)</a>
</li>
      <li><a href="library/signal.html#signal.alarm">alarm() (in module signal)</a>
</li>
      <li><a href="library/audioop.html#audioop.alaw2lin">alaw2lin() (in module audioop)</a>
</li>
      <li><a href="library/ssl.html#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE">ALERT_DESCRIPTION_HANDSHAKE_FAILURE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR">ALERT_DESCRIPTION_INTERNAL_ERROR (in module ssl)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.algorithms_available">algorithms_available (in module hashlib)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.algorithms_guaranteed">algorithms_guaranteed (in module hashlib)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.alignment">alignment() (in module ctypes)</a>
</li>
      <li><a href="library/functions.html#all">all() (built-in function)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.all_errors">all_errors (in module ftplib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.all_features">all_features (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.all_properties">all_properties (in module xml.sax.handler)</a>
</li>
      <li><a href="library/thread.html#thread.allocate_lock">allocate_lock() (in module thread)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.allow_reuse_address">allow_reuse_address (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.allowed_domains">allowed_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.alt">alt() (in module curses.ascii)</a>
</li>
      <li><a href="library/locale.html#locale.ALT_DIGITS">ALT_DIGITS (in module locale)</a>
</li>
      <li><a href="library/os.html#os.altsep">altsep (in module os)</a>
</li>
      <li><a href="library/time.html#time.altzone">altzone (in module time)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.ALWAYS_TYPED_ACTIONS">ALWAYS_TYPED_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/token.html#token.AMPER">AMPER (in module token)</a>
</li>
      <li><a href="library/token.html#token.AMPEREQUAL">AMPEREQUAL (in module token)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.anchor_bgn">anchor_bgn() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.anchor_end">anchor_end() (htmllib.HTMLParser method)</a>
</li>
      <li>
    and

      <ul>
        <li><a href="reference/expressions.html#index-61">bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-6">operator</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-71">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.and_">and_() (in module operator)</a>
</li>
      <li><a href="library/dircache.html#dircache.annotate">annotate() (in module dircache)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.announce">announce() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    anonymous

      <ul>
        <li><a href="reference/expressions.html#index-75">function</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.answer_challenge">answer_challenge() (in module multiprocessing.connection)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/functions.html#any">any() (built-in function)</a>
</li>
      <li><a href="library/anydbm.html#module-anydbm">anydbm (module)</a>
</li>
      <li><a href="library/sys.html#sys.api_version">api_version (in module sys)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.apop">apop() (poplib.POP3 method)</a>
</li>
      <li><a href="whatsnew/2.6.html#index-5">APPDATA</a>
</li>
      <li><a href="library/array.html#array.array.append">append() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.append">(collections.deque method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.append">(email.header.Header method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.append">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/msilib.html#msilib.CAB.append">(msilib.CAB method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.append">(pipes.Template method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.append">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.appendChild">appendChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/collections.html#collections.deque.appendleft">appendleft() (collections.deque method)</a>
</li>
      <li><a href="library/macostools.html#index-0">AppleEvents</a>, <a href="library/miniaeframe.html#index-0">[1]</a>
</li>
      <li><a href="library/undoc.html#module-applesingle">applesingle (module)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application">Application() (in module FrameWork)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.application_uri">application_uri() (in module wsgiref.util)</a>
</li>
      <li>
    apply

      <ul>
        <li><a href="c-api/object.html#index-6">built-in function</a>, <a href="c-api/object.html#index-7">[1]</a>, <a href="c-api/object.html#index-8">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-apply">apply (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#apply">apply() (built-in function)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply_async">apply_async() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/platform.html#platform.architecture">architecture() (in module platform)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.archive">archive (zipimport.zipimporter attribute)</a>
</li>
      <li><a href="library/repr.html#repr.aRepr">aRepr (in module repr)</a>
</li>
      <li><a href="library/argparse.html#module-argparse">argparse (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BaseException.args">args (exceptions.BaseException attribute)</a>

      <ul>
        <li><a href="library/functools.html#functools.partial.args">(functools.partial attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.argtypes">argtypes (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="glossary.html#term-argument"><strong>argument</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-38">call semantics</a>
</li>
        <li><a href="faq/programming.html#index-1">difference from parameter</a>
</li>
        <li><a href="reference/datamodel.html#index-35">function</a>
</li>
        <li><a href="reference/compound_stmts.html#index-20">function definition</a>
</li>
      </ul></li>
      <li><a href="library/argparse.html#argparse.ArgumentDefaultsHelpFormatter">ArgumentDefaultsHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.ArgumentError">ArgumentError</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser">ArgumentParser (class in argparse)</a>
</li>
      <li><a href="c-api/init.html#index-10">argv (in module sys)</a>, <a href="library/sys.html#sys.argv">[1]</a>
</li>
      <li><a href="library/stdtypes.html#index-15">arithmetic</a>

      <ul>
        <li><a href="reference/expressions.html#index-3">conversion</a>
</li>
        <li><a href="reference/expressions.html#index-52">operation, binary</a>
</li>
        <li><a href="reference/expressions.html#index-47">operation, unary</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.ArithmeticError">ArithmeticError</a>
</li>
      <li>
    array

      <ul>
        <li><a href="reference/datamodel.html#index-28">module</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array">array (class in array)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Array">Array (class in ctypes)</a>
</li>
      <li><a href="library/array.html#module-array">array (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Array">Array() (in module multiprocessing)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.Array">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Array">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#index-0">arrays</a>
</li>
      <li><a href="library/array.html#array.ArrayType">ArrayType (in module array)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.article">article() (nntplib.NNTP method)</a>
</li>
      <li>
    as

      <ul>
        <li><a href="reference/simple_stmts.html#index-38">import statement</a>
</li>
        <li><a href="reference/compound_stmts.html#index-15">with statement</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#float.as_integer_ratio">as_integer_ratio() (float method)</a>
</li>
      <li><a href="library/formatter.html#formatter.AS_IS">AS_IS (in module formatter)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.as_string">as_string() (email.message.Message method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.as_tuple">as_tuple() (decimal.Decimal method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ascii">ascii() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.ascii">(in module future_builtins)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-21">ASCII@ASCII</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/introduction.html#index-1">[2]</a>, <a href="reference/lexical_analysis.html#index-13">[3]</a>, <a href="reference/lexical_analysis.html#index-16">[4]</a>, <a href="reference/lexical_analysis.html#index-21">[5]</a>
</li>
      <li><a href="library/string.html#string.ascii_letters">ascii_letters (in module string)</a>
</li>
      <li><a href="library/string.html#string.ascii_lowercase">ascii_lowercase (in module string)</a>
</li>
      <li><a href="library/string.html#string.ascii_uppercase">ascii_uppercase (in module string)</a>
</li>
      <li><a href="library/time.html#time.asctime">asctime() (in module time)</a>
</li>
      <li><a href="library/cmath.html#cmath.asin">asin() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.asin">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.asinh">asinh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.asinh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFileForOpen">AskFileForOpen() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFileForSave">AskFileForSave() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFolder">AskFolder() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskPassword">AskPassword() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskString">AskString() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskYesNoCancel">AskYesNoCancel() (in module EasyDialogs)</a>
</li>
      <li>
    assert

      <ul>
        <li><a href="library/exceptions.html#index-2">statement</a>, <a href="reference/simple_stmts.html#index-15">[1]</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.assert_line_data">assert_line_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertAlmostEqual">assertAlmostEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertDictContainsSubset">assertDictContainsSubset() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertDictEqual">assertDictEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertEqual">assertEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertFalse">assertFalse() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertGreater">assertGreater() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertGreaterEqual">assertGreaterEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIn">assertIn() (unittest.TestCase method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.AssertionError">AssertionError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-16">exception</a>
</li>
      </ul></li>
      <li>
    assertions

      <ul>
        <li><a href="reference/simple_stmts.html#index-15">debugging</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIs">assertIs() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsInstance">assertIsInstance() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNone">assertIsNone() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNot">assertIsNot() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNotNone">assertIsNotNone() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertItemsEqual">assertItemsEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertLess">assertLess() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertLessEqual">assertLessEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertListEqual">assertListEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertMultiLineEqual">assertMultiLineEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotAlmostEqual">assertNotAlmostEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotEqual">assertNotEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotIn">assertNotIn() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotIsInstance">assertNotIsInstance() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotRegexpMatches">assertNotRegexpMatches() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRaises">assertRaises() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRaisesRegexp">assertRaisesRegexp() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRegexpMatches">assertRegexpMatches() (unittest.TestCase method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-asserts">asserts (2to3 fixer)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertSequenceEqual">assertSequenceEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertSetEqual">assertSetEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertTrue">assertTrue() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertTupleEqual">assertTupleEqual() (unittest.TestCase method)</a>
</li>
      <li>
    assignment

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">attribute</a>, <a href="reference/simple_stmts.html#index-9">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-14">augmented</a>
</li>
        <li><a href="reference/datamodel.html#index-51">class attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-55">class instance attribute</a>
</li>
        <li><a href="library/stdtypes.html#index-30">extended slice</a>
</li>
        <li><a href="library/stdtypes.html#index-30">slice</a>
</li>
        <li><a href="reference/simple_stmts.html#index-13">slicing</a>
</li>
        <li><a href="reference/datamodel.html#index-25">statement</a>, <a href="reference/simple_stmts.html#index-3">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-30">subscript</a>
</li>
        <li><a href="reference/simple_stmts.html#index-10">subscription</a>
</li>
        <li><a href="reference/simple_stmts.html#index-6">target list</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.AST">AST (class in ast)</a>
</li>
      <li><a href="library/ast.html#module-ast">ast (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.astimezone">astimezone() (datetime.datetime method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor">ASTVisitor (class in compiler.visitor)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat">async_chat (class in asynchat)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.ac_in_buffer_size">async_chat.ac_in_buffer_size (in module asynchat)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.ac_out_buffer_size">async_chat.ac_out_buffer_size (in module asynchat)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.asyncevents">asyncevents() (FrameWork.Application method)</a>
</li>
      <li><a href="library/asynchat.html#module-asynchat">asynchat (module)</a>
</li>
      <li><a href="library/asyncore.html#module-asyncore">asyncore (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult">AsyncResult (class in multiprocessing.pool)</a>
</li>
      <li><a href="library/token.html#token.AT">AT (in module token)</a>
</li>
      <li><a href="library/cmath.html#cmath.atan">atan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.atan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.atan2">atan2() (in module math)</a>
</li>
      <li><a href="library/cmath.html#cmath.atanh">atanh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.atanh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/atexit.html#module-atexit">atexit (module)</a>
</li>
      <li><a href="library/cd.html#cd.atime">atime (in module cd)</a>
</li>
      <li><a href="library/locale.html#locale.atof">atof() (in module locale)</a>

      <ul>
        <li><a href="library/string.html#string.atof">(in module string)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.atoi">atoi() (in module locale)</a>

      <ul>
        <li><a href="library/string.html#string.atoi">(in module string)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.atol">atol() (in module string)</a>
</li>
      <li><a href="reference/expressions.html#index-4">atom</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.attach">attach() (email.message.Message method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.AttlistDeclHandler">AttlistDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/operator.html#operator.attrgetter">attrgetter() (in module operator)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.attrib">attrib (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-5">attribute</a>, <a href="glossary.html#term-attribute"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">assignment</a>, <a href="reference/simple_stmts.html#index-9">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-51">assignment, class</a>
</li>
        <li><a href="reference/datamodel.html#index-55">assignment, class instance</a>
</li>
        <li><a href="reference/datamodel.html#index-50">class</a>
</li>
        <li><a href="reference/datamodel.html#index-54">class instance</a>
</li>
        <li><a href="reference/simple_stmts.html#index-21">deletion</a>
</li>
        <li><a href="reference/datamodel.html#index-5">generic special</a>
</li>
        <li><a href="reference/expressions.html#index-29">reference</a>
</li>
        <li><a href="reference/datamodel.html#index-5">special</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.AttributeError">AttributeError</a>

      <ul>
        <li><a href="reference/expressions.html#index-30">exception</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.attributes">attributes (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesImpl">AttributesImpl (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNSImpl">AttributesNSImpl (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/curses.html#curses.window.attroff">attroff() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.attron">attron() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.attrset">attrset() (curses.window method)</a>
</li>
      <li><a href="library/cd.html#cd.audio">audio (in module cd)</a>
</li>
      <li><a href="library/aifc.html#index-0">Audio Interchange File Format</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G721">AUDIO_FILE_ENCODING_ADPCM_G721 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G722">AUDIO_FILE_ENCODING_ADPCM_G722 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3">AUDIO_FILE_ENCODING_ADPCM_G723_3 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5">AUDIO_FILE_ENCODING_ADPCM_G723_5 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ALAW_8">AUDIO_FILE_ENCODING_ALAW_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_DOUBLE">AUDIO_FILE_ENCODING_DOUBLE (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_FLOAT">AUDIO_FILE_ENCODING_FLOAT (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_16">AUDIO_FILE_ENCODING_LINEAR_16 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_24">AUDIO_FILE_ENCODING_LINEAR_24 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_32">AUDIO_FILE_ENCODING_LINEAR_32 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_8">AUDIO_FILE_ENCODING_LINEAR_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_MULAW_8">AUDIO_FILE_ENCODING_MULAW_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_MAGIC">AUDIO_FILE_MAGIC (in module sunau)</a>
</li>
      <li><a href="library/ossaudiodev.html#index-0">AUDIODEV</a>
</li>
      <li><a href="library/audioop.html#module-audioop">audioop (module)</a>
</li>
      <li>
    augmented

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">assignment</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.auth">auth() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.authenticate">authenticate() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.AuthenticationError">AuthenticationError</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.authenticators">authenticators() (netrc.netrc method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.authkey">authkey (multiprocessing.Process attribute)</a>
</li>
      <li><a href="library/autogil.html#module-autoGIL">autoGIL (module)</a>
</li>
      <li><a href="library/autogil.html#autoGIL.AutoGILError">AutoGILError</a>
</li>
      <li><a href="library/audioop.html#audioop.avg">avg() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.avgpp">avgpp() (in module audioop)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="B">B</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/base64.html#base64.b16decode">b16decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b16encode">b16encode() (in module base64)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_base64">b2a_base64() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_hex">b2a_hex() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_hqx">b2a_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_qp">b2a_qp() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_uu">b2a_uu() (in module binascii)</a>
</li>
      <li><a href="library/base64.html#base64.b32decode">b32decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b32encode">b32encode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b64decode">b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b64encode">b64encode() (in module base64)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl">Babyl (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMailbox">BabylMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage">BabylMessage (class in mailbox)</a>
</li>
      <li><a href="library/turtle.html#turtle.back">back() (in module turtle)</a>
</li>
      <li><a href="reference/datamodel.html#index-77">back-quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      <li><a href="library/token.html#token.BACKQUOTE">BACKQUOTE (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-5">backslash character</a>
</li>
      <li><a href="library/codecs.html#codecs.backslashreplace_errors">backslashreplace_errors() (in module codecs)</a>
</li>
      <li>
    backward

      <ul>
        <li><a href="reference/datamodel.html#index-77">quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.backward">backward() (in module turtle)</a>
</li>
      <li><a href="library/imageop.html#imageop.backward_compatible">backward_compatible (in module imageop)</a>
</li>
      <li><a href="library/httplib.html#httplib.BadStatusLine">BadStatusLine</a>
</li>
      <li><a href="library/zipfile.html#zipfile.BadZipfile">BadZipfile</a>
</li>
      <li><a href="library/tix.html#Tix.Balloon">Balloon (class in Tix)</a>
</li>
      <li><a href="howto/doanddont.html#index-0">bare except</a>
</li>
      <li>
    base64

      <ul>
        <li><a href="library/base64.html#index-0">encoding</a>
</li>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/base64.html#module-base64">base64 (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseCGIHandler">BaseCGIHandler (class in wsgiref.handlers)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie">BaseCookie (class in Cookie)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BaseException">BaseException</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler">BaseHandler (class in urllib2)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler">(class in wsgiref.handlers)</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler">BaseHTTPRequestHandler (class in BaseHTTPServer)</a>
</li>
      <li><a href="library/basehttpserver.html#module-BaseHTTPServer">BaseHTTPServer (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager">BaseManager (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/os.path.html#os.path.basename">basename() (in module os.path)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy">BaseProxy (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler">BaseRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer">BaseServer (class in SocketServer)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-basestring">basestring (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#basestring">basestring() (built-in function)</a>
</li>
      <li><a href="library/logging.html#logging.basicConfig">basicConfig() (in module logging)</a>
</li>
      <li><a href="library/decimal.html#decimal.BasicContext">BasicContext (class in decimal)</a>
</li>
      <li><a href="library/bastion.html#module-Bastion">Bastion (module)</a>
</li>
      <li><a href="library/bastion.html#Bastion.Bastion">Bastion() (in module Bastion)</a>
</li>
      <li><a href="library/bastion.html#Bastion.BastionClass">BastionClass (class in Bastion)</a>
</li>
      <li><a href="library/curses.html#curses.baudrate">baudrate() (in module curses)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.bbox">bbox() (ttk.Treeview method)</a>
</li>
      <li>
    bdb

      <ul>
        <li><a href="library/pdb.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb">Bdb (class in bdb)</a>
</li>
      <li><a href="library/bdb.html#module-bdb">bdb (module)</a>
</li>
      <li><a href="library/bdb.html#bdb.BdbQuit">BdbQuit</a>
</li>
      <li><a href="glossary.html#term-bdfl"><strong>BDFL</strong></a>
</li>
      <li><a href="distutils/apiref.html#distutils.command.bdist_msi.bdist_msi">bdist_msi (class in distutils.command.bdist_msi)</a>
</li>
      <li><a href="library/curses.html#curses.beep">beep() (in module curses)</a>
</li>
      <li><a href="library/winsound.html#winsound.Beep">Beep() (in module winsound)</a>
</li>
      <li><a href="library/turtle.html#turtle.begin_fill">begin_fill() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.begin_poly">begin_poly() (in module turtle)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.below">below() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/timeit.html#index-0">Benchmarking</a>
</li>
      <li><a href="library/time.html#index-8">benchmarking</a>
</li>
      <li><a href="library/random.html#random.betavariate">betavariate() (in module random)</a>
</li>
      <li><a href="library/turtle.html#turtle.bgcolor">bgcolor() (in module turtle)</a>
</li>
      <li><a href="library/fl.html#fl.form.bgn_group">bgn_group() (fl.form method)</a>
</li>
      <li><a href="library/turtle.html#turtle.bgpic">bgpic() (in module turtle)</a>
</li>
      <li><a href="library/audioop.html#audioop.bias">bias() (in module audioop)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.bidirectional">bidirectional() (in module unicodedata)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.BigEndianStructure">BigEndianStructure (class in ctypes)</a>
</li>
      <li><a href="library/functions.html#bin">bin() (built-in function)</a>
</li>
      <li>
    binary

      <ul>
        <li><a href="reference/expressions.html#index-52">arithmetic operation</a>
</li>
        <li><a href="reference/expressions.html#index-60">bitwise operation</a>
</li>
        <li><a href="library/struct.html#index-0">data, packing</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Binary">Binary (class in msilib)</a>

      <ul>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary">(class in xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">binary literal</a>
</li>
      <li><a href="library/thread.html#index-0">binary semaphores</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_ADD">BINARY_ADD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_AND">BINARY_AND (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_DIVIDE">BINARY_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_FLOOR_DIVIDE">BINARY_FLOOR_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_LSHIFT">BINARY_LSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_MODULO">BINARY_MODULO (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_MULTIPLY">BINARY_MULTIPLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_OR">BINARY_OR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_POWER">BINARY_POWER (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_RSHIFT">BINARY_RSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_SUBSCR">BINARY_SUBSCR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_SUBTRACT">BINARY_SUBTRACT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_TRUE_DIVIDE">BINARY_TRUE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_XOR">BINARY_XOR (opcode)</a>
</li>
      <li><a href="library/binascii.html#module-binascii">binascii (module)</a>
</li>
      <li><a href="library/tkinter.html#index-3">bind (widgets)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.bind">bind() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.bind">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.bind_textdomain_codeset">bind_textdomain_codeset() (in module gettext)</a>
</li>
      <li>
    binding

      <ul>
        <li><a href="reference/simple_stmts.html#index-54">global name</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">name</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/executionmodel.html#index-2">[2]</a>, <a href="reference/simple_stmts.html#index-3">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>, <a href="reference/simple_stmts.html#index-48">[5]</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.bindtextdomain">bindtextdomain() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.bindtextdomain">(in module locale)</a>
</li>
      </ul></li>
      <li>
    binhex

      <ul>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/binhex.html#module-binhex">binhex (module)</a>
</li>
      <li><a href="library/binhex.html#binhex.binhex">binhex() (in module binhex)</a>
</li>
      <li><a href="library/bisect.html#module-bisect">bisect (module)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect">bisect() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect_left">bisect_left() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect_right">bisect_right() (in module bisect)</a>
</li>
      <li><a href="library/stdtypes.html#int.bit_length">bit_length() (int method)</a>

      <ul>
        <li><a href="library/stdtypes.html#long.bit_length">(long method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog.bitmap">bitmap() (msilib.Dialog method)</a>
</li>
      <li>
    bitwise

      <ul>
        <li><a href="reference/expressions.html#index-61">and</a>
</li>
        <li><a href="reference/expressions.html#index-60">operation, binary</a>
</li>
        <li><a href="reference/expressions.html#index-47">operation, unary</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
        <li><a href="reference/expressions.html#index-63">or</a>
</li>
        <li><a href="reference/expressions.html#index-62">xor</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.bk">bk() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.window.bkgd">bkgd() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.bkgdset">bkgdset() (curses.window method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-6">blank line</a>
</li>
      <li><a href="reference/executionmodel.html#index-3">block</a>

      <ul>
        <li><a href="reference/executionmodel.html#index-1">code</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.blocked_domains">blocked_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/io.html#io.BlockingIOError">BlockingIOError</a>
</li>
      <li><a href="library/cd.html#cd.BLOCKSIZE">BLOCKSIZE (in module cd)</a>
</li>
      <li><a href="library/sha.html#sha.blocksize">blocksize (in module sha)</a>
</li>
      <li><a href="reference/expressions.html#index-1">BNF</a>, <a href="reference/introduction.html#index-0">[1]</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.body">body() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.body_encode">body_encode() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.body_encoding">body_encoding (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators.body_line_iterator">body_line_iterator() (in module email.iterators)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM">BOM (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_BE">BOM_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_LE">BOM_LE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16">BOM_UTF16 (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16_BE">BOM_UTF16_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16_LE">BOM_UTF16_LE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32">BOM_UTF32 (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32_BE">BOM_UTF32_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32_LE">BOM_UTF32_LE (in module codecs)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/codecs.html#codecs.BOM_UTF8">BOM_UTF8 (in module codecs)</a>
</li>
      <li><a href="library/functions.html#bool">bool (built-in class)</a>
</li>
      <li>
    Boolean

      <ul>
        <li><a href="library/stdtypes.html#index-13">object</a>, <a href="reference/datamodel.html#index-13">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-69">operation</a>
</li>
        <li><a href="library/stdtypes.html#index-2">operations</a>, <a href="library/stdtypes.html#index-7">[1]</a>
</li>
        <li><a href="library/functions.html#index-0">type</a>
</li>
        <li><a href="library/stdtypes.html#index-43">values</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Boolean">Boolean (class in aetypes)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.boolean">boolean() (in module xmlrpclib)</a>
</li>
      <li><a href="library/types.html#types.BooleanType">BooleanType (in module types)</a>
</li>
      <li><a href="library/ensurepip.html#ensurepip.bootstrap">bootstrap() (in module ensurepip)</a>
</li>
      <li><a href="library/curses.html#curses.window.border">border() (curses.window method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.bottom">bottom() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.bottom_panel">bottom_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.BoundaryError">BoundaryError</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.BoundedSemaphore">BoundedSemaphore (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.BoundedSemaphore">BoundedSemaphore() (in module threading)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.BoundedSemaphore">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.box">box() (curses.window method)</a>
</li>
      <li>
    break

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-33">[4]</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.break_anywhere">break_anywhere() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.break_here">break_here() (bdb.Bdb method)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.break_long_words">break_long_words (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/dis.html#opcode-BREAK_LOOP">BREAK_LOOP (opcode)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.break_on_hyphens">break_on_hyphens (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint">Breakpoint (class in bdb)</a>
</li>
      <li><a href="library/idle.html#index-4">breakpoints</a>
</li>
      <li><a href="library/webbrowser.html#index-0">BROWSER</a>, <a href="library/webbrowser.html#index-1">[1]</a>
</li>
      <li>
    bsddb

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/dbhash.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
      </ul></li>
      <li><a href="library/bsddb.html#module-bsddb">bsddb (module)</a>
</li>
      <li><a href="library/shelve.html#shelve.BsdDbShelf">BsdDbShelf (class in shelve)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.btopen">btopen() (in module bsddb)</a>
</li>
      <li>
    buffer

      <ul>
        <li><a href="library/types.html#index-4">built-in function</a>
</li>
        <li><a href="c-api/buffer.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-buffer">buffer (2to3 fixer)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.buffer">(io.TextIOBase attribute)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.buffer">(unittest.TestResult attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/buffer.html#index-0">buffer interface</a>
</li>
      <li><a href="library/functions.html#index-4">buffer size, I/O</a>
</li>
      <li><a href="library/functions.html#buffer">buffer() (built-in function)</a>
</li>
      <li><a href="library/array.html#array.array.buffer_info">buffer_info() (array.array method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_size">buffer_size (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_text">buffer_text (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_used">buffer_used (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase">BufferedIOBase (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedRandom">BufferedRandom (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedReader">BufferedReader (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedRWPair">BufferedRWPair (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedWriter">BufferedWriter (class in io)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BufferError">BufferError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler">BufferingHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.BufferTooShort">BufferTooShort</a>, <a href="library/multiprocessing.html#multiprocessing.connection.BufferTooShort">[1]</a>
</li>
      <li><a href="c-api/buffer.html#index-2">BufferType (in module types)</a>, <a href="library/types.html#types.BufferType">[1]</a>
</li>
      <li><a href="library/macostools.html#macostools.BUFSIZ">BUFSIZ (in module macostools)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.bufsize">bufsize() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_CLASS">BUILD_CLASS (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_LIST">BUILD_LIST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_MAP">BUILD_MAP (opcode)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.build_opener">build_opener() (in module urllib2)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_SET">BUILD_SET (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_SLICE">BUILD_SLICE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_TUPLE">BUILD_TUPLE (opcode)</a>
</li>
      <li><a href="library/undoc.html#module-buildtools">buildtools (module)</a>
</li>
      <li>
    built-in

      <ul>
        <li><a href="reference/datamodel.html#index-45">method</a>
</li>
        <li><a href="library/stdtypes.html#index-0">types</a>
</li>
      </ul></li>
      <li>
    built-in function

      <ul>
        <li><a href="c-api/import.html#index-1">__import__</a>
</li>
        <li><a href="c-api/number.html#index-2">abs</a>, <a href="reference/datamodel.html#index-93">[1]</a>
</li>
        <li><a href="c-api/object.html#index-6">apply</a>, <a href="c-api/object.html#index-7">[1]</a>, <a href="c-api/object.html#index-8">[2]</a>
</li>
        <li><a href="library/types.html#index-4">buffer</a>
</li>
        <li><a href="c-api/object.html#index-4">bytes</a>
</li>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="reference/datamodel.html#index-21">chr</a>, <a href="reference/datamodel.html#index-22">[1]</a>
</li>
        <li><a href="c-api/structures.html#index-0">classmethod</a>
</li>
        <li><a href="c-api/object.html#index-0">cmp</a>, <a href="c-api/object.html#index-1">[1]</a>, <a href="library/locale.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-80">[3]</a>
</li>
        <li><a href="c-api/number.html#index-4">coerce</a>
</li>
        <li><a href="c-api/import.html#index-4">compile</a>, <a href="library/parser.html#index-2">[1]</a>, <a href="library/stdtypes.html#index-40">[2]</a>, <a href="library/types.html#index-1">[3]</a>, <a href="reference/simple_stmts.html#index-55">[4]</a>
</li>
        <li><a href="library/stdtypes.html#index-15">complex</a>, <a href="reference/datamodel.html#index-94">[1]</a>
</li>
        <li><a href="c-api/number.html#index-0">divmod</a>, <a href="reference/datamodel.html#index-90">[1]</a>, <a href="reference/datamodel.html#index-91">[2]</a>
</li>
        <li><a href="library/parser.html#index-1">eval</a>, <a href="library/pprint.html#index-0">[1]</a>, <a href="library/pprint.html#index-1">[2]</a>, <a href="library/stdtypes.html#index-41">[3]</a>, <a href="library/string.html#index-7">[4]</a>, <a href="reference/simple_stmts.html#index-55">[5]</a>, <a href="reference/simple_stmts.html#index-58">[6]</a>, <a href="reference/toplevel_components.html#index-6">[7]</a>
</li>
        <li><a href="library/user.html#index-2">execfile</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-34">file</a>
</li>
        <li><a href="c-api/number.html#index-7">float</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-5">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-58">globals</a>
</li>
        <li><a href="c-api/object.html#index-9">hash</a>, <a href="c-api/typeobj.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-81">[2]</a>
</li>
        <li><a href="tutorial/stdlib.html#index-0">help</a>
</li>
        <li><a href="reference/datamodel.html#index-95">hex</a>
</li>
        <li><a href="reference/datamodel.html#index-1">id</a>
</li>
        <li><a href="library/sys.html#index-14">input</a>, <a href="reference/toplevel_components.html#index-7">[1]</a>
</li>
        <li><a href="c-api/number.html#index-5">int</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-94">[2]</a>
</li>
        <li><a href="c-api/dict.html#index-3">len</a>, <a href="c-api/list.html#index-1">[1]</a>, <a href="c-api/mapping.html#index-0">[2]</a>, <a href="c-api/object.html#index-11">[3]</a>, <a href="c-api/sequence.html#index-0">[4]</a>, <a href="c-api/set.html#index-1">[5]</a>, <a href="library/stdtypes.html#index-22">[6]</a>, <a href="library/stdtypes.html#index-32">[7]</a>, <a href="reference/datamodel.html#index-17">[8]</a>, <a href="reference/datamodel.html#index-29">[9]</a>, <a href="reference/datamodel.html#index-32">[10]</a>, <a href="reference/datamodel.html#index-88">[11]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-58">locals</a>
</li>
        <li><a href="c-api/number.html#index-6">long</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-8">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="library/stdtypes.html#index-22">max</a>
</li>
        <li><a href="library/stdtypes.html#index-22">min</a>
</li>
        <li><a href="reference/datamodel.html#index-44">object</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-95">oct</a>
</li>
        <li><a href="reference/datamodel.html#index-58">open</a>, <a href="tutorial/inputoutput.html#index-0">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-21">ord</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>
</li>
        <li><a href="c-api/number.html#index-1">pow</a>, <a href="c-api/number.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-90">[2]</a>, <a href="reference/datamodel.html#index-90">[3]</a>, <a href="reference/datamodel.html#index-91">[4]</a>, <a href="reference/datamodel.html#index-92">[5]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-8">range</a>
</li>
        <li><a href="library/sys.html#index-14">raw_input</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
        <li><a href="c-api/import.html#index-3">reload</a>, <a href="library/imp.html#index-2">[1]</a>, <a href="library/imp.html#index-5">[2]</a>, <a href="library/sys.html#index-5">[3]</a>
</li>
        <li><a href="c-api/object.html#index-2">repr</a>, <a href="c-api/typeobj.html#index-1">[1]</a>, <a href="extending/newtypes.html#index-2">[2]</a>, <a href="reference/datamodel.html#index-76">[3]</a>, <a href="reference/expressions.html#index-21">[4]</a>, <a href="reference/simple_stmts.html#index-2">[5]</a>
</li>
        <li><a href="library/dis.html#index-0">slice</a>, <a href="library/types.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-69">[2]</a>
</li>
        <li><a href="c-api/structures.html#index-1">staticmethod</a>
</li>
        <li><a href="c-api/object.html#index-3">str</a>, <a href="extending/newtypes.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-78">[2]</a>, <a href="reference/expressions.html#index-21">[3]</a>
</li>
        <li><a href="c-api/list.html#index-2">tuple</a>, <a href="c-api/sequence.html#index-1">[1]</a>
</li>
        <li><a href="c-api/object.html#index-10">type</a>, <a href="library/stdtypes.html#index-42">[1]</a>, <a href="library/types.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-1">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">unichr</a>
</li>
        <li><a href="c-api/object.html#index-5">unicode</a>, <a href="reference/datamodel.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-83">[2]</a>, <a href="tutorial/introduction.html#index-0">[3]</a>
</li>
        <li><a href="library/types.html#index-2">xrange</a>
</li>
      </ul></li>
      <li>
    built-in method

      <ul>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="reference/datamodel.html#index-45">object</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.builtin_module_names">builtin_module_names (in module sys)</a>
</li>
      <li><a href="library/types.html#types.BuiltinFunctionType">BuiltinFunctionType (in module types)</a>
</li>
      <li><a href="library/imputil.html#imputil.BuiltinImporter">BuiltinImporter (class in imputil)</a>
</li>
      <li><a href="library/types.html#types.BuiltinMethodType">BuiltinMethodType (in module types)</a>
</li>
      <li>
    builtins

      <ul>
        <li><a href="c-api/init.html#index-21">module</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#Tix.ButtonBox">ButtonBox (class in Tix)</a>
</li>
      <li><a href="library/turtle.html#turtle.bye">bye() (in module turtle)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.byref">byref() (in module ctypes)</a>
</li>
      <li><a href="reference/datamodel.html#index-21">byte</a>
</li>
      <li>
    byte-code

      <ul>
        <li><a href="library/imp.html#index-1">file</a>, <a href="library/imp.html#index-3">[1]</a>, <a href="library/py_compile.html#index-0">[2]</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.byte_compile">byte_compile() (in module distutils.util)</a>
</li>
      <li><a href="reference/datamodel.html#index-27">bytearray</a>

      <ul>
        <li><a href="c-api/bytearray.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#bytearray">bytearray (built-in class)</a>
</li>
      <li><a href="reference/datamodel.html#index-60">bytecode</a>, <a href="glossary.html#term-bytecode"><strong>[1]</strong></a>
</li>
      <li><a href="library/sys.html#sys.byteorder">byteorder (in module sys)</a>
</li>
      <li>
    bytes

      <ul>
        <li><a href="c-api/object.html#index-4">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.bytes">bytes (uuid.UUID attribute)</a>
</li>
      <li><a href="glossary.html#term-bytes-like-object"><strong>bytes-like object</strong></a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.bytes_le">bytes_le (uuid.UUID attribute)</a>
</li>
      <li><a href="library/io.html#io.BytesIO">BytesIO (class in io)</a>
</li>
      <li><a href="library/array.html#array.array.byteswap">byteswap() (array.array method)</a>
</li>
      <li><a href="library/bz2.html#module-bz2">bz2 (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor">BZ2Compressor (class in bz2)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Decompressor">BZ2Decompressor (class in bz2)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File">BZ2File (class in bz2)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="C">C</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/lexical_analysis.html#index-15">C</a>

      <ul>
        <li><a href="library/stdtypes.html#index-13">language</a>, <a href="reference/datamodel.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-4">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-65">[4]</a>
</li>
        <li><a href="library/struct.html#index-0">structures</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.c_bool">c_bool (class in ctypes)</a>
</li>
      <li><a href="library/imp.html#imp.C_BUILTIN">C_BUILTIN (in module imp)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_byte">c_byte (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_char">c_char (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_char_p">c_char_p (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_double">c_double (class in ctypes)</a>
</li>
      <li><a href="library/imp.html#imp.C_EXTENSION">C_EXTENSION (in module imp)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_float">c_float (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int">c_int (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int16">c_int16 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int32">c_int32 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int64">c_int64 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int8">c_int8 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_long">c_long (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_longdouble">c_longdouble (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_longlong">c_longlong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_short">c_short (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_size_t">c_size_t (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ssize_t">c_ssize_t (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ubyte">c_ubyte (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint">c_uint (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint16">c_uint16 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint32">c_uint32 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint64">c_uint64 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint8">c_uint8 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ulong">c_ulong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ulonglong">c_ulonglong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ushort">c_ushort (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_void_p">c_void_p (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_wchar">c_wchar (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_wchar_p">c_wchar_p (class in ctypes)</a>
</li>
      <li><a href="library/msilib.html#msilib.CAB">CAB (class in msilib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler">CacheFTPHandler (class in urllib2)</a>
</li>
      <li><a href="library/struct.html#struct.calcsize">calcsize() (in module struct)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar">Calendar (class in calendar)</a>
</li>
      <li><a href="library/calendar.html#module-calendar">calendar (module)</a>
</li>
      <li><a href="library/calendar.html#calendar.calendar">calendar() (in module calendar)</a>
</li>
      <li><a href="reference/expressions.html#index-38">call</a>

      <ul>
        <li><a href="reference/expressions.html#index-43">built-in function</a>
</li>
        <li><a href="reference/expressions.html#index-43">built-in method</a>
</li>
        <li><a href="reference/expressions.html#index-45">class instance</a>
</li>
        <li><a href="reference/datamodel.html#index-46">class object</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-52">[2]</a>, <a href="reference/expressions.html#index-44">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-35">function</a>, <a href="reference/expressions.html#index-42">[1]</a>, <a href="reference/expressions.html#index-43">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-87">instance</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-43">method</a>
</li>
        <li><a href="reference/simple_stmts.html#index-2">procedure</a>
</li>
        <li><a href="reference/expressions.html#index-42">user-defined function</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#dl.dl.call">call() (dl.dl method)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.call">(in module subprocess)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION">CALL_FUNCTION (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_KW">CALL_FUNCTION_KW (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_VAR">CALL_FUNCTION_VAR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_VAR_KW">CALL_FUNCTION_VAR_KW (opcode)</a>
</li>
      <li><a href="library/sys.html#sys.call_tracing">call_tracing() (in module sys)</a>
</li>
      <li>
    callable

      <ul>
        <li><a href="reference/datamodel.html#index-35">object</a>, <a href="reference/expressions.html#index-38">[1]</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Callable">Callable (class in collections)</a>
</li>
      <li><a href="library/functions.html#callable">callable() (built-in function)</a>
</li>
      <li><a href="library/weakref.html#weakref.CallableProxyType">CallableProxyType (in module weakref)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback">callback (optparse.Option attribute)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer.callback">callback() (MiniAEFrame.AEServer method)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback_args">callback_args (optparse.Option attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback_kwargs">callback_kwargs (optparse.Option attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError">CalledProcessError</a>
</li>
      <li><a href="c-api/memory.html#index-0">calloc()</a>
</li>
      <li><a href="library/curses.html#curses.can_change_color">can_change_color() (in module curses)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.can_fetch">can_fetch() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.cancel">cancel() (sched.scheduler method)</a>

      <ul>
        <li><a href="library/threading.html#threading.Timer.cancel">(threading.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.cancel_join_thread">cancel_join_thread() (multiprocessing.Queue method)</a>
</li>
      <li><a href="library/httplib.html#httplib.CannotSendHeader">CannotSendHeader</a>
</li>
      <li><a href="library/httplib.html#httplib.CannotSendRequest">CannotSendRequest</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.canonic">canonic() (bdb.Bdb method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.canonical">canonical() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.canonical">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.capitalize">capitalize() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.capitalize">(str method)</a>
</li>
      </ul></li>
      <li>
    Capsule

      <ul>
        <li><a href="c-api/capsule.html#index-0">object</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.captured_stdout">captured_stdout() (in module test.support)</a>
</li>
      <li><a href="library/logging.html#logging.captureWarnings">captureWarnings() (in module logging)</a>
</li>
      <li><a href="library/string.html#string.capwords">capwords() (in module string)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.AE">Carbon.AE (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.AH">Carbon.AH (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.App">Carbon.App (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Appearance">Carbon.Appearance (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CarbonEvents">Carbon.CarbonEvents (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CarbonEvt">Carbon.CarbonEvt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CF">Carbon.CF (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CG">Carbon.CG (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Cm">Carbon.Cm (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Components">Carbon.Components (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.ControlAccessor">Carbon.ControlAccessor (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Controls">Carbon.Controls (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CoreFounation">Carbon.CoreFounation (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CoreGraphics">Carbon.CoreGraphics (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Ctl">Carbon.Ctl (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dialogs">Carbon.Dialogs (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dlg">Carbon.Dlg (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Drag">Carbon.Drag (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dragconst">Carbon.Dragconst (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Events">Carbon.Events (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Evt">Carbon.Evt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.File">Carbon.File (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Files">Carbon.Files (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Fm">Carbon.Fm (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Folder">Carbon.Folder (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Folders">Carbon.Folders (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Fonts">Carbon.Fonts (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Help">Carbon.Help (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.IBCarbon">Carbon.IBCarbon (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.IBCarbonRuntime">Carbon.IBCarbonRuntime (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Icns">Carbon.Icns (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Icons">Carbon.Icons (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Launch">Carbon.Launch (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.LaunchServices">Carbon.LaunchServices (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.List">Carbon.List (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Lists">Carbon.Lists (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.MacHelp">Carbon.MacHelp (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.MediaDescr">Carbon.MediaDescr (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Menu">Carbon.Menu (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Menus">Carbon.Menus (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Mlte">Carbon.Mlte (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.OSA">Carbon.OSA (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.OSAconst">Carbon.OSAconst (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qd">Carbon.Qd (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qdoffs">Carbon.Qdoffs (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QDOffscreen">Carbon.QDOffscreen (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qt">Carbon.Qt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QuickDraw">Carbon.QuickDraw (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QuickTime">Carbon.QuickTime (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Res">Carbon.Res (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Resources">Carbon.Resources (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Scrap">Carbon.Scrap (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Snd">Carbon.Snd (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Sound">Carbon.Sound (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.TE">Carbon.TE (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.TextEdit">Carbon.TextEdit (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Win">Carbon.Win (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Windows">Carbon.Windows (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.cast">cast() (in module ctypes)</a>
</li>
      <li><a href="library/nis.html#nis.cat">cat() (in module nis)</a>
</li>
      <li><a href="library/cd.html#cd.catalog">catalog (in module cd)</a>
</li>
      <li><a href="library/warnings.html#warnings.catch_warnings">catch_warnings (class in warnings)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.category">category() (in module unicodedata)</a>
</li>
      <li><a href="library/curses.html#curses.cbreak">cbreak() (in module curses)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-24">CC</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler">CCompiler (class in distutils.ccompiler)</a>
</li>
      <li><a href="library/cd.html#module-cd">cd (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.CDLL">CDLL (class in ctypes)</a>
</li>
      <li><a href="library/cd.html#cd.CDROM">CDROM (in module cd)</a>
</li>
      <li><a href="library/math.html#math.ceil">ceil() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/string.html#string.center">center() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.center">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.CERT_NONE">CERT_NONE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CERT_OPTIONAL">CERT_OPTIONAL (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CERT_REQUIRED">CERT_REQUIRED (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.cert_store_stats">cert_store_stats() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ssl.html#ssl.cert_time_to_seconds">cert_time_to_seconds() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CertificateError">CertificateError</a>
</li>
      <li><a href="library/ssl.html#index-15">certificates</a>
</li>
      <li><a href="install/index.html#index-10">CFLAGS</a>, <a href="install/index.html#index-9">[1]</a>, <a href="whatsnew/2.3.html#index-25">[2]</a>
</li>
      <li><a href="library/undoc.html#module-cfmfile">cfmfile (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.CFUNCTYPE">CFUNCTYPE() (in module ctypes)</a>
</li>
      <li>
    CGI

      <ul>
        <li><a href="library/cgi.html#index-4">debugging</a>
</li>
        <li><a href="library/cgitb.html#index-0">exceptions</a>
</li>
        <li><a href="library/cgi.html#index-0">protocol</a>
</li>
        <li><a href="library/cgi.html#index-1">security</a>
</li>
        <li><a href="library/cgitb.html#index-0">tracebacks</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#module-cgi">cgi (module)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories">cgi_directories (CGIHTTPServer.CGIHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.CGIHandler">CGIHandler (class in wsgiref.handlers)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler">CGIHTTPRequestHandler (class in CGIHTTPServer)</a>
</li>
      <li>
    CGIHTTPServer

      <ul>
        <li><a href="library/basehttpserver.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/cgihttpserver.html#module-CGIHTTPServer">CGIHTTPServer (module)</a>
</li>
      <li><a href="library/cgitb.html#module-cgitb">cgitb (module)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler">CGIXMLRPCRequestHandler (class in SimpleXMLRPCServer)</a>
</li>
      <li><a href="library/itertools.html#itertools.chain">chain() (in module itertools)</a>
</li>
      <li>
    chaining

      <ul>
        <li><a href="library/stdtypes.html#index-9">comparisons</a>, <a href="reference/expressions.html#index-66">[1]</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.change_root">change_root() (in module distutils.util)</a>
</li>
      <li><a href="library/ssl.html#ssl.CHANNEL_BINDING_TYPES">CHANNEL_BINDING_TYPES (in module ssl)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.channels">channels() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/locale.html#locale.CHAR_MAX">CHAR_MAX (in module locale)</a>
</li>
      <li><a href="library/unicodedata.html#index-0">character</a>, <a href="reference/datamodel.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>, <a href="reference/expressions.html#index-33">[3]</a>
</li>
      <li><a href="reference/datamodel.html#index-22">character set</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CharacterDataHandler">CharacterDataHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.characters">characters() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/io.html#io.BlockingIOError.characters_written">characters_written (io.BlockingIOError attribute)</a>
</li>
      <li><a href="c-api/typeobj.html#c.charbufferproc">charbufferproc (C type)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset">Charset (class in email.charset)</a>
</li>
      <li><a href="library/mimify.html#mimify.CHARSET">CHARSET (in module mimify)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.charset">charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/os.html#os.chdir">chdir() (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.check">check() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/tabnanny.html#tabnanny.check">(in module tabnanny)</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.check_call">check_call() (in module subprocess)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.check_environ">check_environ() (in module distutils.util)</a>
</li>
      <li><a href="library/fl.html#fl.check_forms">check_forms() (in module fl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.check_hostname">check_hostname (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker.check_output">check_output() (doctest.OutputChecker method)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.check_output">(in module subprocess)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.check_py3k_warnings">check_py3k_warnings() (in module test.support)</a>
</li>
      <li><a href="library/string.html#string.Formatter.check_unused_args">check_unused_args() (string.Formatter method)</a>
</li>
      <li><a href="library/test.html#test.support.check_warnings">check_warnings() (in module test.support)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.checkbox">checkbox() (msilib.Dialog method)</a>
</li>
      <li><a href="library/linecache.html#linecache.checkcache">checkcache() (in module linecache)</a>
</li>
      <li><a href="library/bdb.html#bdb.checkfuncname">checkfuncname() (in module bdb)</a>
</li>
      <li><a href="library/tix.html#Tix.CheckList">CheckList (class in Tix)</a>
</li>
      <li>
    checksum

      <ul>
        <li><a href="library/zlib.html#index-0">Cyclic Redundancy Check</a>
</li>
        <li><a href="library/md5.html#index-0">MD5</a>
</li>
        <li><a href="library/sha.html#index-0">SHA</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.chflags">chflags() (in module os)</a>
</li>
      <li><a href="library/curses.html#curses.window.chgat">chgat() (curses.window method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.childerr">childerr (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.childNodes">childNodes (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/os.html#os.chmod">chmod() (in module os)</a>
</li>
      <li><a href="library/random.html#random.choice">choice() (in module random)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.choices">choices (optparse.Option attribute)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.choose_boundary">choose_boundary() (in module mimetools)</a>
</li>
      <li><a href="library/os.html#os.chown">chown() (in module os)</a>
</li>
      <li>
    chr

      <ul>
        <li><a href="reference/datamodel.html#index-21">built-in function</a>, <a href="reference/datamodel.html#index-22">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#chr">chr() (built-in function)</a>
</li>
      <li><a href="library/os.html#os.chroot">chroot() (in module os)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk">Chunk (class in chunk)</a>
</li>
      <li><a href="library/chunk.html#module-chunk">chunk (module)</a>
</li>
      <li>
    cipher

      <ul>
        <li><a href="library/crypt.html#index-0">DES</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLSocket.cipher">cipher() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.circle">circle() (in module turtle)</a>
</li>
      <li><a href="library/token.html#token.CIRCUMFLEX">CIRCUMFLEX (in module token)</a>
</li>
      <li><a href="library/token.html#token.CIRCUMFLEXEQUAL">CIRCUMFLEXEQUAL (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Clamped">Clamped (class in decimal)</a>
</li>
      <li><a href="glossary.html#term-class"><strong>class</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-50">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-51">attribute assignment</a>
</li>
        <li><a href="reference/datamodel.html#index-71">classic</a>
</li>
        <li><a href="reference/datamodel.html#index-74">constructor</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">definition</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-54">instance</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">name</a>
</li>
        <li><a href="reference/datamodel.html#index-71">new-style</a>
</li>
        <li><a href="c-api/class.html#index-0">object</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-46">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/expressions.html#index-44">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-71">old-style</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">statement</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Class">Class (class in symtable)</a>
</li>
      <li><a href="library/idle.html#index-1">Class browser</a>
</li>
      <li>
    class instance

      <ul>
        <li><a href="reference/datamodel.html#index-54">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-55">attribute assignment</a>
</li>
        <li><a href="reference/expressions.html#index-45">call</a>
</li>
        <li><a href="reference/datamodel.html#index-46">object</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-54">[2]</a>, <a href="reference/expressions.html#index-45">[3]</a>
</li>
      </ul></li>
      <li>
    class object

      <ul>
        <li><a href="reference/datamodel.html#index-46">call</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-52">[2]</a>, <a href="reference/expressions.html#index-44">[3]</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-classic-class"><strong>classic class</strong></a>
</li>
      <li>
    classmethod

      <ul>
        <li><a href="c-api/structures.html#index-0">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#classmethod">classmethod() (built-in function)</a>
</li>
      <li><a href="library/new.html#new.classobj">classobj() (in module new)</a>
</li>
      <li><a href="c-api/class.html#index-1">ClassType (in module types)</a>, <a href="library/types.html#types.ClassType">[1]</a>
</li>
      <li><a href="reference/compound_stmts.html#index-1">clause</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.clean">clean() (mailbox.Maildir method)</a>
</li>
      <li><a href="library/inspect.html#inspect.cleandoc">cleandoc() (in module inspect)</a>
</li>
      <li><a href="c-api/sys.html#index-2">cleanup functions</a>
</li>
      <li><a href="library/idle.html#index-4">Clear Breakpoint</a>
</li>
      <li><a href="library/collections.html#collections.deque.clear">clear() (collections.deque method)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.CookieJar.clear">(cookielib.CookieJar method)</a>
</li>
        <li><a href="library/curses.html#curses.window.clear">(curses.window method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.clear">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.clear">(frozenset method)</a>
</li>
        <li><a href="library/turtle.html#turtle.clear">(in module turtle)</a>, <a href="library/turtle.html#turtle.clear">[1]</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.clear">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.clear">(threading.Event method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.clear">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_all_breaks">clear_all_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_all_file_breaks">clear_all_file_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_bpbynumber">clear_bpbynumber() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_break">clear_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.clear_flags">clear_flags() (decimal.Context method)</a>
</li>
      <li><a href="library/readline.html#readline.clear_history">clear_history() (in module readline)</a>
</li>
      <li><a href="library/pickle.html#pickle.Pickler.clear_memo">clear_memo() (pickle.Pickler method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.clear_session_cookies">clear_session_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/linecache.html#linecache.clearcache">clearcache() (in module linecache)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.ClearData">ClearData() (msilib.Record method)</a>
</li>
      <li><a href="library/curses.html#curses.window.clearok">clearok() (curses.window method)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearscreen">clearscreen() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearstamp">clearstamp() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearstamps">clearstamps() (in module turtle)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Client">Client() (in module multiprocessing.connection)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.client_address">client_address (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/time.html#time.clock">clock() (in module time)</a>
</li>
      <li><a href="library/email.generator.html#email.generator.Generator.clone">clone() (email.generator.Generator method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.clone">(in module turtle)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.clone">(pipes.Template method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.cloneNode">cloneNode() (xml.dom.minidom.Node method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Node.cloneNode">(xml.dom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.Close">Close() (_winreg.PyHKEY method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.close">close() (aifc.aifc method)</a>, <a href="library/aifc.html#aifc.aifc.close">[1]</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.close">(Connection method)</a>
</li>
        <li><a href="library/framework.html#FrameWork.Window.close">(FrameWork.Window method)</a>
</li>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.close">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/asyncore.html#asyncore.dispatcher.close">(asyncore.dispatcher method)</a>
</li>
        <li><a href="library/bsddb.html#bsddb.bsddbobject.close">(bsddb.bsddbobject method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.close">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.close">(chunk.Chunk method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.close">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/dl.html#dl.dl.close">(dl.dl method)</a>
</li>
        <li><a href="library/email.parser.html#email.parser.FeedParser.close">(email.parser.FeedParser method)</a>
</li>
        <li><a href="library/stdtypes.html#file.close">(file method)</a>
</li>
        <li><a href="library/ftplib.html#ftplib.FTP.close">(ftplib.FTP method)</a>
</li>
        <li><a href="reference/expressions.html#generator.close">(generator method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.close">(hotshot.Profile method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.close">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.close">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/anydbm.html#anydbm.close">(in module anydbm)</a>
</li>
        <li><a href="library/dbm.html#dbm.close">(in module dbm)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.close">(in module dumbdbm)</a>
</li>
        <li><a href="library/fileinput.html#fileinput.close">(in module fileinput)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.close">(in module gdbm)</a>
</li>
        <li><a href="c-api/init.html#index-23">(in module os)</a>, <a href="library/os.html#os.close">[1]</a>
</li>
        <li><a href="library/io.html#io.IOBase.close">(io.IOBase method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.FileHandler.close">(logging.FileHandler method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.close">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.close">(logging.handlers.MemoryHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.close">(logging.handlers.NTEventLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.close">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.close">(logging.handlers.SysLogHandler method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.close">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.close">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.close">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.close">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.View.Close">Close() (msilib.View method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.close">close() (multiprocessing.connection.Listener method)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO.close">(StringIO.StringIO method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.close">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.close">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.close">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/select.html#select.epoll.close">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.close">(select.kqueue method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.close">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/shelve.html#shelve.Shelf.close">(shelve.Shelf method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.close">(socket.socket method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.Connection.close">(sqlite3.Connection method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.close">(sunau.AU_read method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.close">(sunau.AU_write method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.close">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.close">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.BaseHandler.close">(urllib2.BaseHandler method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.close">(wave.Wave_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.close">(wave.Wave_write method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.close">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.close">(xml.etree.ElementTree.XMLParser method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.close">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.close">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/asynchat.html#asynchat.async_chat.close_when_done">close_when_done() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/stdtypes.html#file.closed">closed (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.closed">(io.IOBase attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.closed">(ossaudiodev.oss_audio_device attribute)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.CloseKey">CloseKey() (in module _winreg)</a>
</li>
      <li><a href="library/syslog.html#syslog.closelog">closelog() (in module syslog)</a>
</li>
      <li><a href="library/os.html#os.closerange">closerange() (in module os)</a>
</li>
      <li><a href="library/contextlib.html#contextlib.closing">closing() (in module contextlib)</a>
</li>
      <li><a href="library/curses.html#curses.window.clrtobot">clrtobot() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.clrtoeol">clrtoeol() (curses.window method)</a>
</li>
      <li><a href="library/cmath.html#module-cmath">cmath (module)</a>
</li>
      <li>
    cmd

      <ul>
        <li><a href="library/pdb.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd">Cmd (class in cmd)</a>
</li>
      <li><a href="library/cmd.html#module-cmd">cmd (module)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.CalledProcessError.cmd">(subprocess.CalledProcessError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.cmdloop">cmdloop() (cmd.Cmd method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.cmdqueue">cmdqueue (cmd.Cmd attribute)</a>
</li>
      <li>
    cmp

      <ul>
        <li><a href="c-api/object.html#index-0">built-in function</a>, <a href="c-api/object.html#index-1">[1]</a>, <a href="library/locale.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-80">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#cmp">cmp() (built-in function)</a>

      <ul>
        <li><a href="library/filecmp.html#filecmp.cmp">(in module filecmp)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#dis.cmp_op">cmp_op (in module dis)</a>
</li>
      <li><a href="library/functools.html#functools.cmp_to_key">cmp_to_key() (in module functools)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.cmpfiles">cmpfiles() (in module filecmp)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_argcount (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_cellvars (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_code (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_consts (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_filename (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_firstlineno (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_flags (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_freevars (code object attribute)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.CO_FUTURE_DIVISION">CO_FUTURE_DIVISION (C variable)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_lnotab (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_name (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_names (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_nlocals (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_stacksize (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_varnames (code object attribute)</a>
</li>
      <li>
    CObject

      <ul>
        <li><a href="c-api/cobject.html#index-0">object</a>
</li>
      </ul></li>
      <li>
    code

      <ul>
        <li><a href="reference/executionmodel.html#index-1">block</a>
</li>
      </ul></li>
      <li><a href="library/code.html#module-code">code (module)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPError.code">(urllib2.HTTPError attribute)</a>
</li>
        <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.code">(xml.parsers.expat.ExpatError attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/code.html#index-0">code object</a>, <a href="library/marshal.html#index-1">[1]</a>, <a href="library/stdtypes.html#index-39">[2]</a>, <a href="reference/datamodel.html#index-60">[3]</a>
</li>
      <li><a href="library/new.html#new.code">code() (in module new)</a>
</li>
      <li><a href="library/codecs.html#index-0">Codecs</a>

      <ul>
        <li><a href="library/codecs.html#index-0">decode</a>
</li>
        <li><a href="library/codecs.html#index-0">encode</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#module-codecs">codecs (module)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.coded_value">coded_value (Cookie.Morsel attribute)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/codeop.html#module-codeop">codeop (module)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.codepoint2name">codepoint2name (in module htmlentitydefs)</a>
</li>
      <li><a href="library/locale.html#locale.CODESET">CODESET (in module locale)</a>
</li>
      <li><a href="library/types.html#types.CodeType">CodeType (in module types)</a>
</li>
      <li>
    coding

      <ul>
        <li><a href="tutorial/controlflow.html#index-5">style</a>
</li>
      </ul></li>
      <li>
    coerce

      <ul>
        <li><a href="c-api/number.html#index-4">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#coerce">coerce() (built-in function)</a>
</li>
      <li><a href="glossary.html#term-coercion"><strong>coercion</strong></a>
</li>
      <li><a href="library/ast.html#ast.AST.col_offset">col_offset (ast.AST attribute)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.collapse_rfc2231_value">collapse_rfc2231_value() (in module email.utils)</a>
</li>
      <li><a href="library/gc.html#gc.collect">collect() (in module gc)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.collect_incoming_data">collect_incoming_data() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/collections.html#module-collections">collections (module)</a>
</li>
      <li><a href="library/token.html#token.COLON">COLON (in module token)</a>
</li>
      <li><a href="library/fl.html#fl.color">color() (in module fl)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.color">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.color_content">color_content() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.color_pair">color_pair() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.colormode">colormode() (in module turtle)</a>
</li>
      <li><a href="library/colorpicker.html#module-ColorPicker">ColorPicker (module)</a>
</li>
      <li><a href="library/colorsys.html#module-colorsys">colorsys (module)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.column">column() (ttk.Treeview method)</a>
</li>
      <li><a href="library/curses.html#index-4">COLUMNS</a>, <a href="library/curses.html#index-6">[1]</a>
</li>
      <li><a href="library/itertools.html#itertools.combinations">combinations() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.combinations_with_replacement">combinations_with_replacement() (in module itertools)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.combine">combine() (datetime.datetime class method)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.combining">combining() (in module unicodedata)</a>
</li>
      <li><a href="library/tix.html#Tix.ComboBox">ComboBox (class in Tix)</a>
</li>
      <li><a href="library/ttk.html#ttk.Combobox">Combobox (class in ttk)</a>
</li>
      <li><a href="reference/expressions.html#index-12">comma</a>

      <ul>
        <li><a href="reference/expressions.html#index-78">trailing</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.COMMA">COMMA (in module token)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.command">command (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command">Command (class in distutils.cmd)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.core.Command">(class in distutils.core)</a>
</li>
      </ul></li>
      <li><a href="reference/toplevel_components.html#index-4">command line</a>
</li>
      <li>
    command line option

      <ul>
        <li><a href="using/cmdline.html#cmdoption-help">--help</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-version">--version</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-3">-3</a>
</li>
        <li><a href="using/cmdline.html#cmdoption">-?</a>
</li>
        <li><a href="using/cmdline.html#id1">-B</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-e">-E</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-j">-J</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-o">-O</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-oo">-OO</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-q">-Q &lt;arg&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-r">-R</a>
</li>
        <li><a href="using/cmdline.html#id2">-S</a>
</li>
        <li><a href="using/cmdline.html#id4">-U</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-v">-V</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-w">-W arg</a>
</li>
        <li><a href="using/cmdline.html#id5">-X</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-b">-b</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-c">-c &lt;command&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-d">-d</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-h">-h</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-i">-i</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-m">-m &lt;module-name&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-s">-s</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-t">-t</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-u">-u</a>
</li>
        <li><a href="using/cmdline.html#id3">-v</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-x">-x</a>
</li>
      </ul></li>
      <li><a href="library/codeop.html#codeop.CommandCompiler">CommandCompiler (class in codeop)</a>
</li>
      <li><a href="library/commands.html#module-commands">commands (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-3">comment</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.comment">(cookielib.Cookie attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tokenize.html#tokenize.COMMENT">COMMENT (in module tokenize)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.comment">comment (zipfile.ZipFile attribute)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipInfo.comment">(zipfile.ZipInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Comment">Comment() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.comment_url">comment_url (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.commenters">commenters (shlex.shlex attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CommentHandler">CommentHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.CAB.commit">commit() (msilib.CAB method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.Commit">Commit() (msilib.Database method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.commit">commit() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common">common (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/cgi.html#index-0">Common Gateway Interface</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_dirs">common_dirs (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_files">common_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_funny">common_funny (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.common_types">common_types (in module mimetypes)</a>
</li>
      <li><a href="library/os.path.html#os.path.commonprefix">commonprefix() (in module os.path)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen.communicate">communicate() (subprocess.Popen method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.compare">compare() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare">(decimal.Decimal method)</a>
</li>
        <li><a href="library/difflib.html#difflib.Differ.compare">(difflib.Differ method)</a>
</li>
      </ul></li>
      <li><a href="library/hmac.html#hmac.compare_digest">compare_digest() (in module hmac)</a>
</li>
      <li><a href="library/dis.html#opcode-COMPARE_OP">COMPARE_OP (opcode)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.compare_signal">compare_signal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_signal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.compare_total">compare_total() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_total">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.compare_total_mag">compare_total_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_total_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li>
    comparing

      <ul>
        <li><a href="library/stdtypes.html#index-10">objects</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-64">comparison</a>

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
        <li><a href="reference/datamodel.html#index-22">string</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Comparison">Comparison (class in aetypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.COMPARISON_FLAGS">COMPARISON_FLAGS (in module doctest)</a>
</li>
      <li><a href="reference/datamodel.html#index-79">comparisons</a>, <a href="reference/datamodel.html#index-80">[1]</a>

      <ul>
        <li><a href="library/stdtypes.html#index-9">chaining</a>, <a href="reference/expressions.html#index-66">[1]</a>
</li>
      </ul></li>
      <li>
    compile

      <ul>
        <li><a href="c-api/import.html#index-4">built-in function</a>, <a href="library/parser.html#index-2">[1]</a>, <a href="library/stdtypes.html#index-40">[2]</a>, <a href="library/types.html#index-1">[3]</a>, <a href="reference/simple_stmts.html#index-55">[4]</a>
</li>
      </ul></li>
      <li><a href="library/codeop.html#codeop.Compile">Compile (class in codeop)</a>
</li>
      <li><a href="library/functions.html#compile">compile() (built-in function)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.compile">(distutils.ccompiler.CCompiler method)</a>
</li>
        <li><a href="library/compiler.html#compiler.compile">(in module compiler)</a>
</li>
        <li><a href="library/py_compile.html#py_compile.compile">(in module py_compile)</a>
</li>
        <li><a href="library/re.html#re.compile">(in module re)</a>
</li>
        <li><a href="library/parser.html#parser.ST.compile">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/code.html#code.compile_command">compile_command() (in module code)</a>

      <ul>
        <li><a href="library/codeop.html#codeop.compile_command">(in module codeop)</a>
</li>
      </ul></li>
      <li><a href="library/compileall.html#compileall.compile_dir">compile_dir() (in module compileall)</a>
</li>
      <li><a href="library/compileall.html#compileall.compile_file">compile_file() (in module compileall)</a>
</li>
      <li><a href="library/compileall.html#compileall.compile_path">compile_path() (in module compileall)</a>
</li>
      <li>
    compileall

      <ul>
        <li><a href="tutorial/modules.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/compileall.html#module-compileall">compileall (module)</a>
</li>
      <li>
    compileall command line option

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-d">-d destdir</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-f">-f</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-i">-i list</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-l">-l</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-q">-q</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-x">-x regex</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-directory">directory ...</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-file">file ...</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#compiler.compileFile">compileFile() (in module compiler)</a>
</li>
      <li><a href="library/compiler.html#module-compiler">compiler (module)</a>
</li>
      <li><a href="library/compiler.html#module-compiler.ast">compiler.ast (module)</a>
</li>
      <li><a href="library/compiler.html#module-compiler.visitor">compiler.visitor (module)</a>
</li>
      <li><a href="library/parser.html#parser.compilest">compilest() (in module parser)</a>
</li>
      <li><a href="library/rlcompleter.html#rlcompleter.Completer.complete">complete() (rlcompleter.Completer method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.complete_statement">complete_statement() (in module sqlite3)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.completedefault">completedefault() (cmd.Cmd method)</a>
</li>
      <li>
    complex

      <ul>
        <li><a href="library/stdtypes.html#index-15">built-in function</a>, <a href="reference/datamodel.html#index-94">[1]</a>
</li>
        <li><a href="reference/lexical_analysis.html#index-18">literal</a>
</li>
        <li><a href="reference/datamodel.html#index-16">number</a>
</li>
        <li><a href="reference/datamodel.html#index-16">object</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#complex">complex (built-in class)</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex">Complex (class in numbers)</a>
</li>
      <li><a href="glossary.html#term-complex-number"><strong>complex number</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="c-api/complex.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.ComplexType">ComplexType (in module types)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.ComponentItem">ComponentItem (class in aetypes)</a>
</li>
      <li>
    compound

      <ul>
        <li><a href="reference/compound_stmts.html#index-0">statement</a>
</li>
      </ul></li>
      <li>
    comprehensions

      <ul>
        <li><a href="reference/expressions.html#index-13">list</a>, <a href="reference/expressions.html#index-14">[1]</a>
</li>
      </ul></li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor.compress">compress() (bz2.BZ2Compressor method)</a>

      <ul>
        <li><a href="library/bz2.html#bz2.compress">(in module bz2)</a>
</li>
        <li><a href="library/itertools.html#itertools.compress">(in module itertools)</a>
</li>
        <li><a href="library/jpeg.html#jpeg.compress">(in module jpeg)</a>
</li>
        <li><a href="library/zlib.html#zlib.compress">(in module zlib)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.compress">(zlib.Compress method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.compress_size">compress_size (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.compress_type">compress_type (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.compression">compression() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.CompressionError">CompressionError</a>
</li>
      <li><a href="library/zlib.html#zlib.compressobj">compressobj() (in module zlib)</a>
</li>
      <li><a href="library/os.html#index-29">COMSPEC</a>, <a href="library/subprocess.html#index-2">[1]</a>
</li>
      <li><a href="library/operator.html#operator.concat">concat() (in module operator)</a>
</li>
      <li>
    concatenation

      <ul>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Condition">Condition (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Condition">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Control.condition">condition() (msilib.Control method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Condition">Condition() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li>
    Conditional

      <ul>
        <li><a href="reference/expressions.html#index-69">expression</a>
</li>
      </ul></li>
      <li>
    conditional

      <ul>
        <li><a href="reference/expressions.html#index-73">expression</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser">ConfigParser (class in ConfigParser)</a>

      <ul>
        <li><a href="library/configparser.html#module-ConfigParser">(module)</a>
</li>
      </ul></li>
      <li>
    configuration

      <ul>
        <li><a href="library/configparser.html#index-0">file</a>
</li>
        <li><a href="library/pdb.html#index-2">file, debugger</a>
</li>
        <li><a href="library/site.html#index-2">file, path</a>
</li>
        <li><a href="library/user.html#index-0">file, user</a>
</li>
      </ul></li>
      <li><a href="library/sysconfig.html#index-0">configuration information</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.configure">configure() (ttk.Style method)</a>
</li>
      <li><a href="library/os.html#os.confstr">confstr() (in module os)</a>
</li>
      <li><a href="library/os.html#os.confstr_names">confstr_names (in module os)</a>
</li>
      <li><a href="library/stdtypes.html#index-16">conjugate() (complex number method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.conjugate">(decimal.Decimal method)</a>
</li>
        <li><a href="library/numbers.html#numbers.Complex.conjugate">(numbers.Complex method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.connect">connect() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.connect">(ftplib.FTP method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.connect">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.connect">(in module sqlite3)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.connect">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.connect">(smtplib.SMTP method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.connect">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.socket.connect_ex">connect_ex() (socket.socket method)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection">Connection (built-in class)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Connection">(class in sqlite3)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.connection">connection (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.ConnectRegistry">ConnectRegistry() (in module _winreg)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.const">const (optparse.Option attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-11">constant</a>
</li>
      <li>
    constructor

      <ul>
        <li><a href="reference/datamodel.html#index-74">class</a>
</li>
      </ul></li>
      <li><a href="library/copy_reg.html#copy_reg.constructor">constructor() (in module copy_reg)</a>
</li>
      <li><a href="reference/datamodel.html#index-3">container</a>, <a href="reference/datamodel.html#index-50">[1]</a>

      <ul>
        <li><a href="library/stdtypes.html#index-20">iteration over</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Container">Container (class in collections)</a>
</li>
      <li><a href="library/operator.html#operator.contains">contains() (in module operator)</a>
</li>
      <li>
    content type

      <ul>
        <li><a href="library/mimetypes.html#index-0">MIME</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler">ContentHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer.contents">contents (ctypes._Pointer attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.ContentTooShortError">ContentTooShortError</a>
</li>
      <li><a href="library/decimal.html#decimal.Context">Context (class in decimal)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.context">context (ssl.SSLSocket attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-37">context management protocol</a>
</li>
      <li><a href="library/stdtypes.html#index-37">context manager</a>, <a href="reference/datamodel.html#index-96">[1]</a>, <a href="glossary.html#term-context-manager"><strong>[2]</strong></a>
</li>
      <li><a href="library/difflib.html#difflib.context_diff">context_diff() (in module difflib)</a>
</li>
      <li><a href="library/contextlib.html#module-contextlib">contextlib (module)</a>
</li>
      <li><a href="library/contextlib.html#contextlib.contextmanager">contextmanager() (in module contextlib)</a>
</li>
      <li>
    continue

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-CONTINUE_LOOP">CONTINUE_LOOP (opcode)</a>
</li>
      <li><a href="library/msilib.html#msilib.Control">Control (class in msilib)</a>

      <ul>
        <li><a href="library/tix.html#Tix.Control">(class in Tix)</a>
</li>
      </ul></li>
      <li><a href="library/cd.html#cd.control">control (in module cd)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.control">control() (msilib.Dialog method)</a>

      <ul>
        <li><a href="library/select.html#select.kqueue.control">(select.kqueue method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.controlnames">controlnames (in module curses.ascii)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.controls">controls() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li>
    conversion

      <ul>
        <li><a href="reference/expressions.html#index-3">arithmetic</a>
</li>
        <li><a href="reference/datamodel.html#index-77">string</a>, <a href="reference/expressions.html#index-19">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.ConversionError">ConversionError</a>
</li>
      <li>
    conversions

      <ul>
        <li><a href="library/stdtypes.html#index-18">numeric</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.convert">convert() (email.charset.Charset method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.convert_arg_line_to_args">convert_arg_line_to_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_charref">convert_charref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_codepoint">convert_codepoint() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_entityref">convert_entityref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.convert_field">convert_field() (string.Formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.convert_path">convert_path() (in module distutils.util)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie">Cookie (class in cookielib)</a>

      <ul>
        <li><a href="library/cookie.html#module-Cookie">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.CookieError">CookieError</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar">CookieJar (class in cookielib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPCookieProcessor.cookiejar">cookiejar (urllib2.HTTPCookieProcessor attribute)</a>
</li>
      <li><a href="library/cookielib.html#module-cookielib">cookielib (module)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy">CookiePolicy (class in cookielib)</a>
</li>
      <li><a href="library/time.html#index-5">Coordinated Universal Time</a>
</li>
      <li><a href="library/idle.html#index-4">Copy</a>
</li>
      <li>
    copy

      <ul>
        <li><a href="library/copy_reg.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#module-copy">copy (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy">copy() (decimal.Context method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.copy">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.copy">(frozenset method)</a>
</li>
        <li><a href="library/hashlib.html#hashlib.hash.copy">(hashlib.hash method)</a>
</li>
        <li><a href="library/hmac.html#hmac.HMAC.copy">(hmac.HMAC method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.copy">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/copy.html#copy.copy">(in module copy)</a>
</li>
        <li><a href="library/macostools.html#findertools.copy">(in module findertools)</a>
</li>
        <li><a href="library/macostools.html#macostools.copy">(in module macostools)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.copy">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/shutil.html#shutil.copy">(in module shutil)</a>
</li>
        <li><a href="library/md5.html#md5.md5.copy">(md5.md5 method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.copy">(pipes.Template method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.copy">(sha.sha method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.copy">(zlib.Compress method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.copy">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#shutil.copy2">copy2() (in module shutil)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_abs">copy_abs() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_abs">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.copy_decimal">copy_decimal() (decimal.Context method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.file_util.copy_file">copy_file() (in module distutils.file_util)</a>
</li>
      <li><a href="library/ast.html#ast.copy_location">copy_location() (in module ast)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_negate">copy_negate() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_negate">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/copy_reg.html#module-copy_reg">copy_reg (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_sign">copy_sign() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_sign">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.dir_util.copy_tree">copy_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.copybinary">copybinary() (in module mimetools)</a>
</li>
      <li><a href="library/shutil.html#shutil.copyfile">copyfile() (in module shutil)</a>
</li>
      <li><a href="library/shutil.html#shutil.copyfileobj">copyfileobj() (in module shutil)</a>
</li>
      <li><a href="library/shutil.html#index-0">copying files</a>
</li>
      <li><a href="library/mimetools.html#mimetools.copyliteral">copyliteral() (in module mimetools)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.copymessage">copymessage() (mhlib.Folder method)</a>
</li>
      <li><a href="library/shutil.html#shutil.copymode">copymode() (in module shutil)</a>
</li>
      <li><a href="library/constants.html#copyright">copyright (built-in variable)</a>

      <ul>
        <li><a href="c-api/init.html#index-7">(in module sys)</a>, <a href="library/sys.html#sys.copyright">[1]</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.copysign">copysign() (in module math)</a>
</li>
      <li><a href="library/shutil.html#shutil.copystat">copystat() (in module shutil)</a>
</li>
      <li><a href="library/macostools.html#macostools.copytree">copytree() (in module macostools)</a>

      <ul>
        <li><a href="library/shutil.html#shutil.copytree">(in module shutil)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-23">coroutine</a>
</li>
      <li><a href="library/cmath.html#cmath.cos">cos() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.cos">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.cosh">cosh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.cosh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.count">count() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.count">(collections.deque method)</a>
</li>
        <li><a href="library/itertools.html#itertools.count">(in module itertools)</a>
</li>
        <li><a href="library/string.html#string.count">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/stdtypes.html#str.count">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Counter">Counter (class in collections)</a>
</li>
      <li><a href="library/operator.html#operator.countOf">countOf() (in module operator)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.countTestCases">countTestCases() (unittest.TestCase method)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.TestSuite.countTestCases">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.CoverageResults">CoverageResults (class in trace)</a>
</li>
      <li>
    cPickle

      <ul>
        <li><a href="library/copy_reg.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#module-cPickle">cPickle (module)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-26">CPP</a>
</li>
      <li><a href="whatsnew/2.3.html#index-28">CPPFLAGS</a>
</li>
      <li><a href="library/profile.html#module-cProfile">cProfile (module)</a>
</li>
      <li><a href="library/time.html#index-8">CPU time</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.cpu_count">cpu_count() (in module multiprocessing)</a>
</li>
      <li><a href="glossary.html#term-cpython"><strong>CPython</strong></a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.CRC">CRC (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/binascii.html#binascii.crc32">crc32() (in module binascii)</a>

      <ul>
        <li><a href="library/zlib.html#zlib.crc32">(in module zlib)</a>
</li>
      </ul></li>
      <li><a href="library/binascii.html#binascii.crc_hqx">crc_hqx() (in module binascii)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.create">create() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_aggregate">create_aggregate() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_collation">create_collation() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/socket.html#socket.create_connection">create_connection() (in module socket)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.create_decimal">create_decimal() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.create_decimal_from_float">create_decimal_from_float() (decimal.Context method)</a>
</li>
      <li><a href="library/ssl.html#ssl.create_default_context">create_default_context() (in module ssl)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_function">create_function() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CREATE_NEW_CONSOLE">CREATE_NEW_CONSOLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP">CREATE_NEW_PROCESS_GROUP (in module subprocess)</a>
</li>
      <li><a href="distutils/builtdist.html#create_shortcut">create_shortcut() (built-in function)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.create_socket">create_socket() (asyncore.dispatcher method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.create_static_lib">create_static_lib() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.create_stats">create_stats() (profile.Profile method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.create_string_buffer">create_string_buffer() (in module ctypes)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.create_system">create_system (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dir_util.create_tree">create_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.create_unicode_buffer">create_unicode_buffer() (in module ctypes)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.create_version">create_version (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createAttribute">createAttribute() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createAttributeNS">createAttributeNS() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createComment">createComment() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.createDocument">createDocument() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.createDocumentType">createDocumentType() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createElement">createElement() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createElementNS">createElementNS() (xml.dom.Document method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Widget.tk.createfilehandler">createfilehandler() (Tkinter.Widget.tk method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.CreateKey">CreateKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.CreateKeyEx">CreateKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.createLock">createLock() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.NullHandler.createLock">(logging.NullHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/cd.html#cd.createparser">createparser() (in module cd)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createProcessingInstruction">createProcessingInstruction() (xml.dom.Document method)</a>
</li>
      <li><a href="library/msilib.html#msilib.CreateRecord">CreateRecord() (in module msilib)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.createSocket">createSocket() (logging.handlers.SocketHandler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createTextNode">createTextNode() (xml.dom.Document method)</a>
</li>
      <li><a href="library/constants.html#credits">credits (built-in variable)</a>
</li>
      <li><a href="library/logging.html#logging.critical">critical() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.critical">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.CRNCYSTR">CRNCYSTR (in module locale)</a>
</li>
      <li><a href="library/imageop.html#imageop.crop">crop() (in module imageop)</a>
</li>
      <li><a href="library/audioop.html#audioop.cross">cross() (in module audioop)</a>
</li>
      <li>
    crypt

      <ul>
        <li><a href="library/pwd.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/crypt.html#module-crypt">crypt (module)</a>
</li>
      <li><a href="library/crypt.html#crypt.crypt">crypt() (in module crypt)</a>
</li>
      <li><a href="library/crypt.html#index-0">crypt(3)</a>, <a href="library/crypt.html#index-1">[1]</a>, <a href="library/crypt.html#index-2">[2]</a>
</li>
      <li><a href="library/crypto.html#index-0">cryptography</a>
</li>
      <li><a href="library/stringio.html#module-cStringIO">cStringIO (module)</a>
</li>
      <li><a href="library/csv.html#index-0">csv</a>

      <ul>
        <li><a href="library/csv.html#module-csv">(module)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.ctermid">ctermid() (in module os)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.ctime">ctime() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.ctime">(datetime.datetime method)</a>
</li>
        <li><a href="library/time.html#time.ctime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.ctrl">ctrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/signal.html#signal.CTRL_BREAK_EVENT">CTRL_BREAK_EVENT (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.CTRL_C_EVENT">CTRL_C_EVENT (in module signal)</a>
</li>
      <li><a href="library/ctypes.html#module-ctypes">ctypes (module)</a>
</li>
      <li><a href="library/os.html#os.curdir">curdir (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.currency">currency() (in module locale)</a>
</li>
      <li><a href="library/ttk.html#ttk.Combobox.current">current() (ttk.Combobox method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.current_process">current_process() (in module multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.current_thread">current_thread() (in module threading)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentByteIndex">CurrentByteIndex (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentColumnNumber">CurrentColumnNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/inspect.html#inspect.currentframe">currentframe() (in module inspect)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentLineNumber">CurrentLineNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/threading.html#threading.currentThread">currentThread() (in module threading)</a>
</li>
      <li><a href="library/curses.html#curses.curs_set">curs_set() (in module curses)</a>
</li>
      <li><a href="library/curses.html#module-curses">curses (module)</a>
</li>
      <li><a href="library/curses.ascii.html#module-curses.ascii">curses.ascii (module)</a>
</li>
      <li><a href="library/curses.panel.html#module-curses.panel">curses.panel (module)</a>
</li>
      <li><a href="library/curses.html#module-curses.textpad">curses.textpad (module)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor">Cursor (class in sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.cursor">cursor() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/curses.html#curses.window.cursyncup">cursyncup() (curses.window method)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.curval">curval (EasyDialogs.ProgressBar attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.customize_compiler">customize_compiler() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/idle.html#index-4">Cut</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.cwd">cwd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/itertools.html#itertools.cycle">cycle() (in module itertools)</a>
</li>
      <li><a href="library/zlib.html#index-0">Cyclic Redundancy Check</a>
</li>
  </ul></td>
</tr></table>

<h2 id="D">D</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/locale.html#locale.D_FMT">D_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.D_T_FMT">D_T_FMT (in module locale)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.daemon">daemon (multiprocessing.Process attribute)</a>

      <ul>
        <li><a href="library/threading.html#threading.Thread.daemon">(threading.Thread attribute)</a>
</li>
      </ul></li>
      <li>
    dangling

      <ul>
        <li><a href="reference/compound_stmts.html#index-2">else</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-0">data</a>

      <ul>
        <li><a href="library/struct.html#index-0">packing binary</a>
</li>
        <li><a href="library/csv.html#index-0">tabular</a>
</li>
        <li><a href="reference/datamodel.html#index-4">type</a>
</li>
        <li><a href="reference/expressions.html#index-9">type, immutable</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#plistlib.Data">Data (class in plistlib)</a>
</li>
      <li><a href="library/select.html#select.kevent.data">data (select.kevent attribute)</a>

      <ul>
        <li><a href="library/userdict.html#UserDict.IterableUserDict.data">(UserDict.IterableUserDict attribute)</a>
</li>
        <li><a href="library/userdict.html#UserList.UserList.data">(UserList.UserList attribute)</a>
</li>
        <li><a href="library/userdict.html#UserString.MutableString.data">(UserString.MutableString attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Comment.data">(xml.dom.Comment attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.ProcessingInstruction.data">(xml.dom.ProcessingInstruction attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Text.data">(xml.dom.Text attribute)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.data">(xmlrpclib.Binary attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.data">data() (xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      <li>
    database

      <ul>
        <li><a href="library/unicodedata.html#index-0">Unicode</a>
</li>
      </ul></li>
      <li><a href="library/dumbdbm.html#index-0">databases</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler">DatagramHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.DatagramRequestHandler">DatagramRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/cd.html#cd.DATASIZE">DATASIZE (in module cd)</a>
</li>
      <li><a href="library/datetime.html#datetime.date">date (class in datetime)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.date">date() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.date">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.date_time">date_time (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.date_time_string">date_time_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime">datetime (class in datetime)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime">DateTime (class in xmlrpclib)</a>
</li>
      <li><a href="library/datetime.html#module-datetime">datetime (module)</a>
</li>
      <li><a href="reference/expressions.html#index-16">datum</a>
</li>
      <li><a href="library/datetime.html#datetime.date.day">day (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.day">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.day_abbr">day_abbr (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.day_name">day_name (in module calendar)</a>
</li>
      <li><a href="library/time.html#time.daylight">daylight (in module time)</a>
</li>
      <li><a href="library/time.html#index-6">Daylight Saving Time</a>
</li>
      <li><a href="library/shelve.html#shelve.DbfilenameShelf">DbfilenameShelf (class in shelve)</a>
</li>
      <li>
    dbhash

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/dbhash.html#module-dbhash">dbhash (module)</a>
</li>
      <li>
    dbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/gdbm.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
      </ul></li>
      <li><a href="library/dbm.html#module-dbm">dbm (module)</a>
</li>
      <li><a href="library/locale.html#locale.dcgettext">dcgettext() (in module locale)</a>
</li>
      <li><a href="library/fl.html#fl.form.deactivate_form">deactivate_form() (fl.form method)</a>
</li>
      <li><a href="extending/newtypes.html#index-0">deallocation, object</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.debug">debug (imaplib.IMAP4 attribute)</a>
</li>
      <li><a href="library/re.html#re.DEBUG">DEBUG (in module re)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.debug">debug (shlex.shlex attribute)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.debug">(zipfile.ZipFile attribute)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.debug">debug() (in module doctest)</a>

      <ul>
        <li><a href="library/logging.html#logging.debug">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.debug">(logging.Logger method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.debug">(pipes.Template method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestCase.debug">(unittest.TestCase method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.debug">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/gc.html#gc.DEBUG_COLLECTABLE">DEBUG_COLLECTABLE (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_INSTANCES">DEBUG_INSTANCES (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_LEAK">DEBUG_LEAK (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_OBJECTS">DEBUG_OBJECTS (in module gc)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.debug_print">debug_print() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_SAVEALL">DEBUG_SAVEALL (in module gc)</a>
</li>
      <li><a href="library/doctest.html#doctest.debug_src">debug_src() (in module doctest)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_STATS">DEBUG_STATS (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_UNCOLLECTABLE">DEBUG_UNCOLLECTABLE (in module gc)</a>
</li>
      <li><a href="library/idle.html#index-3">debugger</a>, <a href="library/sys.html#index-13">[1]</a>, <a href="library/sys.html#index-3">[2]</a>

      <ul>
        <li><a href="library/pdb.html#index-2">configuration file</a>
</li>
      </ul></li>
      <li><a href="library/pdb.html#index-0">debugging</a>

      <ul>
        <li><a href="library/cgi.html#index-4">CGI</a>
</li>
        <li><a href="reference/simple_stmts.html#index-15">assertions</a>
</li>
      </ul></li>
      <li><a href="library/smtpd.html#smtpd.DebuggingServer">DebuggingServer (class in smtpd)</a>
</li>
      <li><a href="library/doctest.html#doctest.DebugRunner">DebugRunner (class in doctest)</a>
</li>
      <li><a href="library/macos.html#MacOS.DebugStr">DebugStr() (in module MacOS)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal">Decimal (class in decimal)</a>
</li>
      <li><a href="library/decimal.html#module-decimal">decimal (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">decimal literal</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.decimal">decimal() (in module unicodedata)</a>
</li>
      <li><a href="library/decimal.html#decimal.DecimalException">DecimalException (class in decimal)</a>
</li>
      <li>
    decode

      <ul>
        <li><a href="library/codecs.html#index-0">Codecs</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.Codec.decode">decode() (codecs.Codec method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.IncrementalDecoder.decode">(codecs.IncrementalDecoder method)</a>
</li>
        <li><a href="library/base64.html#base64.decode">(in module base64)</a>
</li>
        <li><a href="library/codecs.html#codecs.decode">(in module codecs)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.decode">(in module mimetools)</a>
</li>
        <li><a href="library/quopri.html#quopri.decode">(in module quopri)</a>
</li>
        <li><a href="library/uu.html#uu.decode">(in module uu)</a>
</li>
        <li><a href="library/json.html#json.JSONDecoder.decode">(json.JSONDecoder method)</a>
</li>
        <li><a href="library/stdtypes.html#str.decode">(str method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.decode">(xmlrpclib.Binary method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime.decode">(xmlrpclib.DateTime method)</a>
</li>
      </ul></li>
      <li><a href="library/email.header.html#email.header.decode_header">decode_header() (in module email.header)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.decode_params">decode_params() (in module email.utils)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.decode_rfc2231">decode_rfc2231() (in module email.utils)</a>
</li>
      <li><a href="library/email.generator.html#email.generator.DecodedGenerator">DecodedGenerator (class in email.generator)</a>
</li>
      <li><a href="library/base64.html#base64.decodestring">decodestring() (in module base64)</a>

      <ul>
        <li><a href="library/quopri.html#quopri.decodestring">(in module quopri)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.decomposition">decomposition() (in module unicodedata)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Decompressor.decompress">decompress() (bz2.BZ2Decompressor method)</a>

      <ul>
        <li><a href="library/bz2.html#bz2.decompress">(in module bz2)</a>
</li>
        <li><a href="library/jpeg.html#jpeg.decompress">(in module jpeg)</a>
</li>
        <li><a href="library/zlib.html#zlib.decompress">(in module zlib)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.decompress">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/zlib.html#zlib.decompressobj">decompressobj() (in module zlib)</a>
</li>
      <li><a href="glossary.html#term-decorator"><strong>decorator</strong></a>
</li>
      <li><a href="library/token.html#token.DEDENT">DEDENT (in module token)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-2">DEDENT token</a>, <a href="reference/lexical_analysis.html#index-8">[1]</a>
</li>
      <li><a href="library/textwrap.html#textwrap.dedent">dedent() (in module textwrap)</a>
</li>
      <li><a href="library/copy.html#copy.deepcopy">deepcopy() (in module copy)</a>
</li>
      <li>
    def

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">statement</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.def_prog_mode">def_prog_mode() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.def_shell_mode">def_shell_mode() (in module curses)</a>
</li>
      <li>
    default

      <ul>
        <li><a href="reference/compound_stmts.html#index-20">parameter value</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.default">default (optparse.Option attribute)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.default">default() (cmd.Cmd method)</a>

      <ul>
        <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.default">(compiler.visitor.ASTVisitor method)</a>
</li>
        <li><a href="library/json.html#json.JSONEncoder.default">(json.JSONEncoder method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.DEFAULT_BUFFER_SIZE">DEFAULT_BUFFER_SIZE (in module io)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.default_bufsize">default_bufsize (in module xml.dom.pulldom)</a>
</li>
      <li><a href="library/collections.html#collections.defaultdict.default_factory">default_factory (collections.defaultdict attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.DEFAULT_FORMAT">DEFAULT_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.default_open">default_open() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/timeit.html#timeit.default_timer">default_timer() (in module timeit)</a>
</li>
      <li><a href="library/decimal.html#decimal.DefaultContext">DefaultContext (class in decimal)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy">DefaultCookiePolicy (class in cookielib)</a>
</li>
      <li><a href="library/collections.html#collections.defaultdict">defaultdict (class in collections)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.DefaultHandler">DefaultHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.DefaultHandlerExpand">DefaultHandlerExpand() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.defaults">defaults() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/unittest.html#unittest.defaultTestLoader">defaultTestLoader (in module unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.defaultTestResult">defaultTestResult() (unittest.TestCase method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.defects">defects (email.message.Message attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.define_macro">define_macro() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    definition

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">class</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">function</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.defpath">defpath (in module os)</a>
</li>
      <li><a href="library/math.html#math.degrees">degrees() (in module math)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.degrees">(in module turtle)</a>
</li>
      </ul></li>
      <li>
    del

      <ul>
        <li><a href="library/stdtypes.html#index-30">statement</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-75">[2]</a>, <a href="reference/simple_stmts.html#index-18">[3]</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.del_param">del_param() (email.message.Message method)</a>
</li>
      <li><a href="library/functions.html#delattr">delattr() (built-in function)</a>
</li>
      <li><a href="library/turtle.html#turtle.delay">delay() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.delay_output">delay_output() (in module curses)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.delayload">delayload (cookielib.FileCookieJar attribute)</a>
</li>
      <li><a href="library/curses.html#curses.window.delch">delch() (curses.window method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.dele">dele() (poplib.POP3 method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.delete">delete() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.delete">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.delete">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-DELETE_ATTR">DELETE_ATTR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_FAST">DELETE_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_GLOBAL">DELETE_GLOBAL (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_NAME">DELETE_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+0">DELETE_SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+1">DELETE_SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+2">DELETE_SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+3">DELETE_SLICE+3 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SUBSCR">DELETE_SUBSCR (opcode)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.deleteacl">deleteacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Widget.tk.deletefilehandler">deletefilehandler() (Tkinter.Widget.tk method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.deletefolder">deletefolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteKey">DeleteKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteKeyEx">DeleteKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.window.deleteln">deleteln() (curses.window method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.deleteMe">deleteMe() (bdb.Breakpoint method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteValue">DeleteValue() (in module _winreg)</a>
</li>
      <li>
    deletion

      <ul>
        <li><a href="reference/simple_stmts.html#index-21">attribute</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">target</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">target list</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.delimiter">delimiter (csv.Dialect attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-20">delimiters</a>
</li>
      <li><a href="library/operator.html#operator.delitem">delitem() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.deliver_challenge">deliver_challenge() (in module multiprocessing.connection)</a>
</li>
      <li><a href="library/operator.html#operator.delslice">delslice() (in module operator)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.demo_app">demo_app() (in module wsgiref.simple_server)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational.denominator">denominator (numbers.Rational attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.DeprecationWarning">DeprecationWarning</a>
</li>
      <li><a href="library/collections.html#collections.deque">deque (class in collections)</a>
</li>
      <li><a href="library/ssl.html#ssl.DER_cert_to_PEM_cert">DER_cert_to_PEM_cert() (in module ssl)</a>
</li>
      <li><a href="library/curses.html#curses.window.derwin">derwin() (curses.window method)</a>
</li>
      <li>
    DES

      <ul>
        <li><a href="library/crypt.html#index-0">cipher</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.description">description (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.description">description() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.descriptions">descriptions() (nntplib.NNTP method)</a>
</li>
      <li><a href="glossary.html#term-descriptor"><strong>descriptor</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-35">file</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.dest">dest (optparse.Option attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-75">destructor</a>, <a href="reference/simple_stmts.html#index-8">[1]</a>
</li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.Detach">Detach() (_winreg.PyHKEY method)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase.detach">detach() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.detach">(io.TextIOBase method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.detach">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.detect_language">detect_language() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/profile.html#index-0">deterministic profiling</a>
</li>
      <li><a href="library/gl.html#module-DEVICE">DEVICE (module)</a>
</li>
      <li><a href="library/os.html#os.devnull">devnull (in module os)</a>
</li>
      <li><a href="library/gettext.html#gettext.dgettext">dgettext() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.dgettext">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect">Dialect (class in csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.dialect">dialect (csv.csvreader attribute)</a>

      <ul>
        <li><a href="library/csv.html#csv.csvwriter.dialect">(csv.csvwriter attribute)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog">Dialog (class in msilib)</a>
</li>
      <li><a href="library/framework.html#FrameWork.DialogWindow">DialogWindow() (in module FrameWork)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-dict">dict (2to3 fixer)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict">(built-in class)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.dict">dict() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/logging.config.html#logging.config.dictConfig">dictConfig() (in module logging.config)</a>
</li>
      <li><a href="glossary.html#term-dictionary"><strong>dictionary</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-16">display</a>
</li>
        <li><a href="c-api/dict.html#index-0">object</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-33">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/datamodel.html#index-81">[4]</a>, <a href="reference/expressions.html#index-16">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/simple_stmts.html#index-12">[7]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">type, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-dictionary-view"><strong>dictionary view</strong></a>
</li>
      <li><a href="c-api/dict.html#index-1">DictionaryType (in module types)</a>, <a href="library/types.html#types.DictionaryType">[1]</a>
</li>
      <li><a href="library/userdict.html#UserDict.DictMixin">DictMixin (class in UserDict)</a>
</li>
      <li><a href="library/types.html#types.DictProxyType">DictProxyType (in module types)</a>
</li>
      <li><a href="library/csv.html#csv.DictReader">DictReader (class in csv)</a>
</li>
      <li><a href="c-api/dict.html#index-1">DictType (in module types)</a>, <a href="library/types.html#types.DictType">[1]</a>
</li>
      <li><a href="library/csv.html#csv.DictWriter">DictWriter (class in csv)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.diff_files">diff_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/difflib.html#difflib.Differ">Differ (class in difflib)</a>, <a href="library/difflib.html#difflib.Differ">[1]</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.difference">difference() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.difference_update">difference_update() (frozenset method)</a>
</li>
      <li><a href="library/difflib.html#module-difflib">difflib (module)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/hashlib.html#hashlib.hash.digest">digest() (hashlib.hash method)</a>

      <ul>
        <li><a href="library/hmac.html#hmac.HMAC.digest">(hmac.HMAC method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.digest">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.digest">(sha.sha method)</a>
</li>
      </ul></li>
      <li><a href="library/md5.html#md5.digest_size">digest_size (in module md5)</a>

      <ul>
        <li><a href="library/sha.html#sha.digest_size">(in module sha)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.digit">digit() (in module unicodedata)</a>
</li>
      <li><a href="library/string.html#string.digits">digits (in module string)</a>
</li>
      <li><a href="library/functions.html#dir">dir() (built-in function)</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.dir">(ftplib.FTP method)</a>
</li>
      </ul></li>
      <li><a href="library/dircache.html#module-dircache">dircache (module)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp">dircmp (class in filecmp)</a>
</li>
      <li>
    directory

      <ul>
        <li><a href="library/os.html#index-13">changing</a>
</li>
        <li><a href="library/os.html#index-14">creating</a>
</li>
        <li><a href="library/os.html#index-15">deleting</a>, <a href="library/shutil.html#index-1">[1]</a>
</li>
        <li><a href="library/site.html#index-1">site-packages</a>
</li>
        <li><a href="library/site.html#index-1">site-python</a>
</li>
        <li><a href="library/os.html#index-20">traversal</a>
</li>
        <li><a href="library/os.html#index-20">walking</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Directory">Directory (class in msilib)</a>
</li>
      <li>
    directory ...

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-directory">compileall command line option</a>
</li>
      </ul></li>
      <li><a href="distutils/builtdist.html#directory_created">directory_created() (built-in function)</a>
</li>
      <li><a href="library/tix.html#Tix.DirList">DirList (class in Tix)</a>
</li>
      <li><a href="library/os.path.html#os.path.dirname">dirname() (in module os.path)</a>
</li>
      <li><a href="library/tix.html#Tix.DirSelectBox">DirSelectBox (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.DirSelectDialog">DirSelectDialog (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.DirTree">DirTree (class in Tix)</a>
</li>
      <li><a href="library/dis.html#module-dis">dis (module)</a>
</li>
      <li><a href="library/dis.html#dis.dis">dis() (in module dis)</a>

      <ul>
        <li><a href="library/pickletools.html#pickletools.dis">(in module pickletools)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Breakpoint.disable">disable() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/gc.html#gc.disable">(in module gc)</a>
</li>
        <li><a href="library/logging.html#logging.disable">(in module logging)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.disable">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.OptionParser.disable_interspersed_args">disable_interspersed_args() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DisableReflectionKey">DisableReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/dis.html#dis.disassemble">disassemble() (in module dis)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.discard">discard (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.discard">discard() (frozenset method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.discard">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.discard">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/asynchat.html#asynchat.async_chat.discard_buffers">discard_buffers() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/dis.html#dis.disco">disco() (in module dis)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.discover">discover() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.dispatch">dispatch() (compiler.visitor.ASTVisitor method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_call">dispatch_call() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_exception">dispatch_exception() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_line">dispatch_line() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_return">dispatch_return() (bdb.Bdb method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher">dispatcher (class in asyncore)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher_with_send">dispatcher_with_send (class in asyncore)</a>
</li>
      <li>
    display

      <ul>
        <li><a href="reference/expressions.html#index-16">dictionary</a>
</li>
        <li><a href="reference/expressions.html#index-13">list</a>
</li>
        <li><a href="reference/expressions.html#index-18">set</a>
</li>
        <li><a href="reference/expressions.html#index-12">tuple</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.displayhook">displayhook() (in module sys)</a>
</li>
      <li><a href="library/platform.html#platform.dist">dist() (in module platform)</a>
</li>
      <li><a href="library/turtle.html#turtle.distance">distance() (in module turtle)</a>
</li>
      <li><a href="library/dis.html#dis.distb">distb() (in module dis)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.Distribution">Distribution (class in distutils.core)</a>
</li>
      <li><a href="library/distutils.html#module-distutils">distutils (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.archive_util">distutils.archive_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.bcppcompiler">distutils.bcppcompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.ccompiler">distutils.ccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.cmd">distutils.cmd (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command">distutils.command (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist">distutils.command.bdist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_dumb">distutils.command.bdist_dumb (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_msi">distutils.command.bdist_msi (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_packager">distutils.command.bdist_packager (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_rpm">distutils.command.bdist_rpm (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_wininst">distutils.command.bdist_wininst (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build">distutils.command.build (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_clib">distutils.command.build_clib (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_ext">distutils.command.build_ext (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_py">distutils.command.build_py (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_scripts">distutils.command.build_scripts (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.check">distutils.command.check (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.clean">distutils.command.clean (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.config">distutils.command.config (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install">distutils.command.install (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_data">distutils.command.install_data (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_headers">distutils.command.install_headers (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_lib">distutils.command.install_lib (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_scripts">distutils.command.install_scripts (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.register">distutils.command.register (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.sdist">distutils.command.sdist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.core">distutils.core (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.cygwinccompiler">distutils.cygwinccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.debug">distutils.debug (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dep_util">distutils.dep_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dir_util">distutils.dir_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dist">distutils.dist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.emxccompiler">distutils.emxccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.errors">distutils.errors (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.extension">distutils.extension (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.fancy_getopt">distutils.fancy_getopt (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.file_util">distutils.file_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.filelist">distutils.filelist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.log">distutils.log (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.msvccompiler">distutils.msvccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.spawn">distutils.spawn (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.sysconfig">distutils.sysconfig (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.text_file">distutils.text_file (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.unixccompiler">distutils.unixccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.util">distutils.util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.version">distutils.version (module)</a>
</li>
      <li><a href="distutils/setupscript.html#index-0">DISTUTILS_DEBUG</a>
</li>
      <li><a href="library/imageop.html#imageop.dither2grey2">dither2grey2() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.dither2mono">dither2mono() (in module imageop)</a>
</li>
      <li><a href="library/operator.html#operator.div">div() (in module operator)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.divide">divide() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.divide_int">divide_int() (decimal.Context method)</a>
</li>
      <li><a href="reference/expressions.html#index-54">division</a>

      <ul>
        <li><a href="library/stdtypes.html#index-17">integer</a>
</li>
        <li><a href="library/stdtypes.html#index-17">long integer</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.DivisionByZero">DivisionByZero (class in decimal)</a>
</li>
      <li>
    divmod

      <ul>
        <li><a href="c-api/number.html#index-0">built-in function</a>, <a href="reference/datamodel.html#index-90">[1]</a>, <a href="reference/datamodel.html#index-91">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#divmod">divmod() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.divmod">(decimal.Context method)</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#module-dl">dl (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.DllCanUnloadNow">DllCanUnloadNow() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.DllGetClassObject">DllGetClassObject() (in module ctypes)</a>
</li>
      <li><a href="library/sys.html#sys.dllhandle">dllhandle (in module sys)</a>
</li>
      <li><a href="library/gettext.html#gettext.dngettext">dngettext() (in module gettext)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_activate">do_activate() (FrameWork.ScrolledWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.Window.do_activate">(FrameWork.Window method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.do_char">do_char() (FrameWork.Application method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.do_clear">do_clear() (bdb.Bdb method)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.do_command">do_command() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Window.do_contentclick">do_contentclick() (FrameWork.Window method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ControlsWindow.do_controlhit">do_controlhit() (FrameWork.ControlsWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_controlhit">(FrameWork.ScrolledWindow method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.do_dialogevent">do_dialogevent() (FrameWork.Application method)</a>
</li>
      <li><a href="library/fl.html#fl.do_forms">do_forms() (in module fl)</a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET">do_GET() (SimpleHTTPServer.SimpleHTTPRequestHandler method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.do_handshake">do_handshake() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD">do_HEAD() (SimpleHTTPServer.SimpleHTTPRequestHandler method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.DialogWindow.do_itemhit">do_itemhit() (FrameWork.DialogWindow method)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler.do_POST">do_POST() (CGIHTTPServer.CGIHTTPRequestHandler method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_postresize">do_postresize() (FrameWork.ScrolledWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.Window.do_postresize">(FrameWork.Window method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Window.do_update">do_update() (FrameWork.Window method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.doc_header">doc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler">DocCGIXMLRPCRequestHandler (class in DocXMLRPCServer)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocFileSuite">DocFileSuite() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.doCleanups">doCleanups() (unittest.TestCase method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.docmd">docmd() (smtplib.SMTP method)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-23">docstring</a>, <a href="glossary.html#term-docstring"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.docstring">(doctest.DocTest attribute)</a>
</li>
      </ul></li>
      <li><a href="tutorial/controlflow.html#index-1">docstrings</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTest">DocTest (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#module-doctest">doctest (module)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure">DocTestFailure</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFinder">DocTestFinder (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser">DocTestParser (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner">DocTestRunner (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestSuite">DocTestSuite() (in module doctest)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.doctype">doctype() (xml.etree.ElementTree.TreeBuilder method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.doctype">(xml.etree.ElementTree.XMLParser method)</a>
</li>
      </ul></li>
      <li>
    documentation

      <ul>
        <li><a href="library/pydoc.html#index-0">generation</a>
</li>
        <li><a href="library/pydoc.html#index-0">online</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-63">documentation string</a>
</li>
      <li><a href="tutorial/controlflow.html#index-1">documentation strings</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.documentElement">documentElement (xml.dom.Document attribute)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCRequestHandler">DocXMLRPCRequestHandler (class in DocXMLRPCServer)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer">DocXMLRPCServer (class in DocXMLRPCServer)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#module-DocXMLRPCServer">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.domain_initial_dot">domain_initial_dot (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.domain_return_ok">domain_return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.domain_specified">domain_specified (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainLiberal">DomainLiberal (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainRFC2965Match">DomainRFC2965Match (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrict">DomainStrict (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrictNoDots">DomainStrictNoDots (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrictNonDomain">DomainStrictNonDomain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream">DOMEventStream (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMException">DOMException</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DomstringSizeErr">DomstringSizeErr</a>
</li>
      <li><a href="library/turtle.html#turtle.done">done() (in module turtle)</a>

      <ul>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.done">(xdrlib.Unpacker method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DONT_ACCEPT_BLANKLINE">DONT_ACCEPT_BLANKLINE (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DONT_ACCEPT_TRUE_FOR_1">DONT_ACCEPT_TRUE_FOR_1 (in module doctest)</a>
</li>
      <li><a href="library/sys.html#sys.dont_write_bytecode">dont_write_bytecode (in module sys)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler.doRollover">doRollover() (logging.handlers.RotatingFileHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler.doRollover">(logging.handlers.TimedRotatingFileHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.DOT">DOT (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.dot">dot() (in module turtle)</a>
</li>
      <li><a href="library/re.html#re.DOTALL">DOTALL (in module re)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.doublequote">doublequote (csv.Dialect attribute)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESLASH">DOUBLESLASH (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESLASHEQUAL">DOUBLESLASHEQUAL (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESTAR">DOUBLESTAR (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESTAREQUAL">DOUBLESTAREQUAL (in module token)</a>
</li>
      <li><a href="library/curses.html#curses.doupdate">doupdate() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.down">down() (in module turtle)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.drop_whitespace">drop_whitespace (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/itertools.html#itertools.dropwhile">dropwhile() (in module itertools)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.dst">dst() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.dst">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.dst">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler">DTDHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="glossary.html#term-duck-typing"><strong>duck-typing</strong></a>
</li>
      <li>
    dumbdbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/dumbdbm.html#module-dumbdbm">dumbdbm (module)</a>
</li>
      <li><a href="library/formatter.html#formatter.DumbWriter">DumbWriter (class in formatter)</a>
</li>
      <li><a href="library/dummy_thread.html#module-dummy_thread">dummy_thread (module)</a>
</li>
      <li><a href="library/dummy_threading.html#module-dummy_threading">dummy_threading (module)</a>
</li>
      <li><a href="library/ast.html#ast.dump">dump() (in module ast)</a>

      <ul>
        <li><a href="library/json.html#json.dump">(in module json)</a>
</li>
        <li><a href="library/marshal.html#marshal.dump">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.dump">(in module pickle)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.dump">(in module xml.etree.ElementTree)</a>
</li>
        <li><a href="library/pickle.html#pickle.Pickler.dump">(pickle.Pickler method)</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#rfc822.dump_address_pair">dump_address_pair() (in module rfc822)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.dump_stats">dump_stats() (profile.Profile method)</a>

      <ul>
        <li><a href="library/profile.html#pstats.Stats.dump_stats">(pstats.Stats method)</a>
</li>
      </ul></li>
      <li><a href="library/json.html#json.dumps">dumps() (in module json)</a>

      <ul>
        <li><a href="library/marshal.html#marshal.dumps">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.dumps">(in module pickle)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.dumps">(in module xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.dup">dup() (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.dup">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.dup2">dup2() (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.dup2">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-DUP_TOP">DUP_TOP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DUP_TOPX">DUP_TOPX (opcode)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.DuplicateSectionError">DuplicateSectionError</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.dwFlags">dwFlags (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/imputil.html#imputil.DynLoadSuffixImporter">DynLoadSuffixImporter (class in imputil)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="E">E</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/cmath.html#cmath.e">e (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.e">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.E2BIG">E2BIG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EACCES">EACCES (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADDRINUSE">EADDRINUSE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADDRNOTAVAIL">EADDRNOTAVAIL (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADV">EADV (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EAFNOSUPPORT">EAFNOSUPPORT (in module errno)</a>
</li>
      <li><a href="glossary.html#term-eafp"><strong>EAFP</strong></a>
</li>
      <li><a href="library/errno.html#errno.EAGAIN">EAGAIN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EALREADY">EALREADY (in module errno)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.east_asian_width">east_asian_width() (in module unicodedata)</a>
</li>
      <li><a href="library/easydialogs.html#module-EasyDialogs">EasyDialogs (module)</a>
</li>
      <li><a href="library/errno.html#errno.EBADE">EBADE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADF">EBADF (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADFD">EBADFD (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADMSG">EBADMSG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADR">EBADR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADRQC">EBADRQC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADSLT">EBADSLT (in module errno)</a>
</li>
      <li><a href="reference/datamodel.html#index-22">EBCDIC</a>
</li>
      <li><a href="library/errno.html#errno.EBFONT">EBFONT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBUSY">EBUSY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECHILD">ECHILD (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.echo">echo() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.window.echochar">echochar() (curses.window method)</a>
</li>
      <li><a href="library/errno.html#errno.ECHRNG">ECHRNG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECOMM">ECOMM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNABORTED">ECONNABORTED (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNREFUSED">ECONNREFUSED (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNRESET">ECONNRESET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDEADLK">EDEADLK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDEADLOCK">EDEADLOCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDESTADDRREQ">EDESTADDRREQ (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.edit">edit() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/errno.html#errno.EDOM">EDOM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDOTDOT">EDOTDOT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDQUOT">EDQUOT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EEXIST">EEXIST (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EFAULT">EFAULT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EFBIG">EFBIG (in module errno)</a>
</li>
      <li><a href="library/bdb.html#bdb.effective">effective() (in module bdb)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.ehlo">ehlo() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.ehlo_or_helo_if_needed">ehlo_or_helo_if_needed() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/errno.html#errno.EHOSTDOWN">EHOSTDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EHOSTUNREACH">EHOSTUNREACH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EIDRM">EIDRM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EILSEQ">EILSEQ (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINPROGRESS">EINPROGRESS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINTR">EINTR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINVAL">EINVAL (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EIO">EIO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISCONN">EISCONN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISDIR">EISDIR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISNAM">EISNAM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL2HLT">EL2HLT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL2NSYNC">EL2NSYNC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL3HLT">EL3HLT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL3RST">EL3RST (in module errno)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element">Element (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_create">element_create() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_names">element_names() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_options">element_options() (ttk.Style method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ElementDeclHandler">ElementDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.elements">elements() (collections.Counter method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree">ElementTree (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBACC">ELIBACC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBBAD">ELIBBAD (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBEXEC">ELIBEXEC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBMAX">ELIBMAX (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBSCN">ELIBSCN (in module errno)</a>
</li>
      <li>
    elif

      <ul>
        <li><a href="reference/compound_stmts.html#index-3">keyword</a>
</li>
      </ul></li>
      <li><a href="library/uu.html#index-0">Ellinghouse, Lance</a>
</li>
      <li>
    Ellipsis

      <ul>
        <li><a href="reference/datamodel.html#index-8">object</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#Ellipsis">Ellipsis (built-in variable)</a>
</li>
      <li><a href="library/doctest.html#doctest.ELLIPSIS">ELLIPSIS (in module doctest)</a>
</li>
      <li><a href="library/types.html#types.EllipsisType">EllipsisType (in module types)</a>
</li>
      <li><a href="library/errno.html#errno.ELNRNG">ELNRNG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELOOP">ELOOP (in module errno)</a>
</li>
      <li>
    else

      <ul>
        <li><a href="reference/compound_stmts.html#index-2">dangling</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">keyword</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>, <a href="reference/compound_stmts.html#index-4">[2]</a>, <a href="reference/compound_stmts.html#index-6">[3]</a>, <a href="reference/simple_stmts.html#index-34">[4]</a>
</li>
      </ul></li>
      <li><a href="library/email.html#module-email">email (module)</a>
</li>
      <li><a href="library/email.charset.html#module-email.charset">email.charset (module)</a>
</li>
      <li><a href="library/email.encoders.html#module-email.encoders">email.encoders (module)</a>
</li>
      <li><a href="library/email.errors.html#module-email.errors">email.errors (module)</a>
</li>
      <li><a href="library/email.generator.html#module-email.generator">email.generator (module)</a>
</li>
      <li><a href="library/email.header.html#module-email.header">email.header (module)</a>
</li>
      <li><a href="library/email.iterators.html#module-email.iterators">email.iterators (module)</a>
</li>
      <li><a href="library/email.message.html#module-email.message">email.message (module)</a>
</li>
      <li><a href="library/email.mime.html#module-email.mime">email.mime (module)</a>
</li>
      <li><a href="library/email.parser.html#module-email.parser">email.parser (module)</a>
</li>
      <li><a href="library/email.utils.html#module-email.utils">email.utils (module)</a>
</li>
      <li><a href="library/errno.html#errno.EMFILE">EMFILE (in module errno)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.FileHandler.emit">emit() (logging.FileHandler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Handler.emit">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.NullHandler.emit">(logging.NullHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.StreamHandler.emit">(logging.StreamHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.emit">(logging.handlers.BufferingHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.emit">(logging.handlers.DatagramHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler.emit">(logging.handlers.HTTPHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.emit">(logging.handlers.NTEventLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler.emit">(logging.handlers.RotatingFileHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler.emit">(logging.handlers.SMTPHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.emit">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.emit">(logging.handlers.SysLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler.emit">(logging.handlers.TimedRotatingFileHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.WatchedFileHandler.emit">(logging.handlers.WatchedFileHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EMLINK">EMLINK (in module errno)</a>
</li>
      <li><a href="library/queue.html#Queue.Empty">Empty</a>
</li>
      <li>
    empty

      <ul>
        <li><a href="reference/expressions.html#index-14">list</a>
</li>
        <li><a href="reference/datamodel.html#index-24">tuple</a>, <a href="reference/expressions.html#index-11">[1]</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.empty">empty() (multiprocessing.multiprocessing.queues.SimpleQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.empty">(Queue.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.empty">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/sched.html#sched.scheduler.empty">(sched.scheduler method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.EMPTY_NAMESPACE">EMPTY_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.emptyline">emptyline() (cmd.Cmd method)</a>
</li>
      <li><a href="library/errno.html#errno.EMSGSIZE">EMSGSIZE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EMULTIHOP">EMULTIHOP (in module errno)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.enable">enable() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/cgitb.html#cgitb.enable">(in module cgitb)</a>
</li>
        <li><a href="library/gc.html#gc.enable">(in module gc)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.enable">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.enable_callback_tracebacks">enable_callback_tracebacks() (in module sqlite3)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.enable_interspersed_args">enable_interspersed_args() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.enable_load_extension">enable_load_extension() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.enable_traversal">enable_traversal() (ttk.Notebook method)</a>
</li>
      <li><a href="library/site.html#site.ENABLE_USER_SITE">ENABLE_USER_SITE (in module site)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.EnableReflectionKey">EnableReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/errno.html#errno.ENAMETOOLONG">ENAMETOOLONG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENAVAIL">ENAVAIL (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.window.enclose">enclose() (curses.window method)</a>
</li>
      <li>
    encode

      <ul>
        <li><a href="library/codecs.html#index-0">Codecs</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.Codec.encode">encode() (codecs.Codec method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.IncrementalEncoder.encode">(codecs.IncrementalEncoder method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.encode">(email.header.Header method)</a>
</li>
        <li><a href="library/base64.html#base64.encode">(in module base64)</a>
</li>
        <li><a href="library/codecs.html#codecs.encode">(in module codecs)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.encode">(in module mimetools)</a>
</li>
        <li><a href="library/quopri.html#quopri.encode">(in module quopri)</a>
</li>
        <li><a href="library/uu.html#uu.encode">(in module uu)</a>
</li>
        <li><a href="library/json.html#json.JSONEncoder.encode">(json.JSONEncoder method)</a>
</li>
        <li><a href="library/stdtypes.html#str.encode">(str method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.encode">(xmlrpclib.Binary method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Boolean.encode">(xmlrpclib.Boolean method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime.encode">(xmlrpclib.DateTime method)</a>
</li>
      </ul></li>
      <li><a href="library/email.encoders.html#email.encoders.encode_7or8bit">encode_7or8bit() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_base64">encode_base64() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_noop">encode_noop() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_quopri">encode_quopri() (in module email.encoders)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.encode_rfc2231">encode_rfc2231() (in module email.utils)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.encode_threshold">encode_threshold (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler attribute)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.encoded_header_len">encoded_header_len() (email.charset.Charset method)</a>
</li>
      <li><a href="library/codecs.html#codecs.EncodedFile">EncodedFile() (in module codecs)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.encodePriority">encodePriority() (logging.handlers.SysLogHandler method)</a>
</li>
      <li><a href="library/base64.html#base64.encodestring">encodestring() (in module base64)</a>

      <ul>
        <li><a href="library/quopri.html#quopri.encodestring">(in module quopri)</a>
</li>
      </ul></li>
      <li>
    encoding

      <ul>
        <li><a href="library/base64.html#index-0">base64</a>
</li>
        <li><a href="library/quopri.html#index-0">quoted-printable</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.encoding">encoding (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.encoding">(file attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.ENCODING">ENCODING (in module tarfile)</a>
</li>
      <li><a href="library/io.html#io.TextIOBase.encoding">encoding (io.TextIOBase attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-4">encoding declarations (source file)</a>
</li>
      <li><a href="library/codecs.html#module-encodings.idna">encodings.idna (module)</a>
</li>
      <li><a href="library/codecs.html#module-encodings.utf_8_sig">encodings.utf_8_sig (module)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.encodings_map">encodings_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.encodings_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.end">end (exceptions.UnicodeError attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.end">end() (re.MatchObject method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.end">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.end_fill">end_fill() (in module turtle)</a>
</li>
      <li><a href="library/dis.html#opcode-END_FINALLY">END_FINALLY (opcode)</a>
</li>
      <li><a href="library/fl.html#fl.form.end_group">end_group() (fl.form method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.end_headers">end_headers() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.end_marker">end_marker() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.end_paragraph">end_paragraph() (formatter.formatter method)</a>
</li>
      <li><a href="library/turtle.html#turtle.end_poly">end_poly() (in module turtle)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndCdataSectionHandler">EndCdataSectionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler">EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endDocument">endDocument() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endElement">endElement() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndElementHandler">EndElementHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endElementNS">endElementNS() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.endheaders">endheaders() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/token.html#token.ENDMARKER">ENDMARKER (in module token)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndNamespaceDeclHandler">EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/gl.html#gl.endpick">endpick() (in module gl)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.endpos">endpos (re.MatchObject attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endPrefixMapping">endPrefixMapping() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/gl.html#gl.endselect">endselect() (in module gl)</a>
</li>
      <li><a href="library/stdtypes.html#str.endswith">endswith() (str method)</a>
</li>
      <li><a href="library/curses.html#curses.endwin">endwin() (in module curses)</a>
</li>
      <li><a href="library/errno.html#errno.ENETDOWN">ENETDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENETRESET">ENETRESET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENETUNREACH">ENETUNREACH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENFILE">ENFILE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOANO">ENOANO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOBUFS">ENOBUFS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOCSI">ENOCSI (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENODATA">ENODATA (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENODEV">ENODEV (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOENT">ENOENT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOEXEC">ENOEXEC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOLCK">ENOLCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOLINK">ENOLINK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOMEM">ENOMEM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOMSG">ENOMSG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENONET">ENONET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOPKG">ENOPKG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOPROTOOPT">ENOPROTOOPT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSPC">ENOSPC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSR">ENOSR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSTR">ENOSTR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSYS">ENOSYS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTBLK">ENOTBLK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTCONN">ENOTCONN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTDIR">ENOTDIR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTEMPTY">ENOTEMPTY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTNAM">ENOTNAM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTSOCK">ENOTSOCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTTY">ENOTTY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTUNIQ">ENOTUNIQ (in module errno)</a>
</li>
      <li><a href="library/ensurepip.html#module-ensurepip">ensurepip (module)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.enter">enter() (sched.scheduler method)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.enterabs">enterabs() (sched.scheduler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.entities">entities (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EntityDeclHandler">EntityDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.entitydefs">entitydefs (in module htmlentitydefs)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.EntityResolver">EntityResolver (class in xml.sax.handler)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Enum">Enum (class in aetypes)</a>
</li>
      <li><a href="library/ssl.html#ssl.enum_certificates">enum_certificates() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.enum_crls">enum_crls() (in module ssl)</a>
</li>
      <li><a href="library/functions.html#enumerate">enumerate() (built-in function)</a>

      <ul>
        <li><a href="library/fm.html#fm.enumerate">(in module fm)</a>
</li>
        <li><a href="library/threading.html#threading.enumerate">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.EnumKey">EnumKey() (in module _winreg)</a>
</li>
      <li><a href="library/aetools.html#aetools.enumsubst">enumsubst() (in module aetools)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.EnumValue">EnumValue() (in module _winreg)</a>
</li>
      <li><a href="library/os.html#os.environ">environ (in module os)</a>

      <ul>
        <li><a href="library/posix.html#posix.environ">(in module posix)</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-6">environment</a>
</li>
      <li>
    environment variable

      <ul>
        <li><a href="using/windows.html#index-1">%PATH%</a>
</li>
        <li><a href="library/urllib2.html#index-2">&lt;protocol&gt;_proxy</a>
</li>
        <li><a href="whatsnew/2.6.html#index-5">APPDATA</a>
</li>
        <li><a href="library/ossaudiodev.html#index-0">AUDIODEV</a>
</li>
        <li><a href="library/webbrowser.html#index-0">BROWSER</a>, <a href="library/webbrowser.html#index-1">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-24">CC</a>
</li>
        <li><a href="install/index.html#index-10">CFLAGS</a>, <a href="install/index.html#index-9">[1]</a>, <a href="whatsnew/2.3.html#index-25">[2]</a>
</li>
        <li><a href="library/curses.html#index-4">COLUMNS</a>, <a href="library/curses.html#index-6">[1]</a>
</li>
        <li><a href="library/os.html#index-29">COMSPEC</a>, <a href="library/subprocess.html#index-2">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-26">CPP</a>
</li>
        <li><a href="whatsnew/2.3.html#index-28">CPPFLAGS</a>
</li>
        <li><a href="distutils/setupscript.html#index-0">DISTUTILS_DEBUG</a>
</li>
        <li><a href="distutils/apiref.html#index-1">HOME</a>, <a href="install/index.html#index-4">[1]</a>, <a href="install/index.html#index-5">[2]</a>, <a href="library/os.path.html#index-2">[3]</a>, <a href="library/os.path.html#index-3">[4]</a>, <a href="library/user.html#index-3">[5]</a>
</li>
        <li><a href="install/index.html#index-7">HOMEDRIVE</a>, <a href="library/os.path.html#index-6">[1]</a>
</li>
        <li><a href="install/index.html#index-8">HOMEPATH</a>, <a href="library/os.path.html#index-5">[1]</a>
</li>
        <li><a href="library/idle.html#index-5">IDLESTARTUP</a>
</li>
        <li><a href="library/webbrowser.html#index-2">KDEDIR</a>
</li>
        <li><a href="library/gettext.html#index-3">LANG</a>, <a href="library/gettext.html#index-7">[1]</a>, <a href="library/locale.html#index-1">[2]</a>, <a href="library/locale.html#index-2">[3]</a>, <a href="library/locale.html#index-3">[4]</a>
</li>
        <li><a href="library/gettext.html#index-0">LANGUAGE</a>, <a href="library/gettext.html#index-4">[1]</a>
</li>
        <li><a href="library/gettext.html#index-1">LC_ALL</a>, <a href="library/gettext.html#index-5">[1]</a>
</li>
        <li><a href="library/gettext.html#index-2">LC_MESSAGES</a>, <a href="library/gettext.html#index-6">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-12">LDCXXSHARED</a>
</li>
        <li><a href="whatsnew/2.3.html#index-27">LDFLAGS</a>
</li>
        <li><a href="library/curses.html#index-0">LINES</a>, <a href="library/curses.html#index-3">[1]</a>, <a href="library/curses.html#index-5">[2]</a>
</li>
        <li><a href="library/getpass.html#index-2">LNAME</a>
</li>
        <li><a href="library/getpass.html#index-0">LOGNAME</a>, <a href="library/os.html#index-2">[1]</a>
</li>
        <li><a href="library/ossaudiodev.html#index-1">MIXERDEV</a>
</li>
        <li><a href="library/pdb.html#index-3">PAGER</a>, <a href="library/pydoc.html#index-1">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-22">PATH</a>, <a href="c-api/intro.html#index-23">[1]</a>, <a href="distutils/packageindex.html#index-1">[2]</a>, <a href="faq/library.html#index-0">[3]</a>, <a href="faq/library.html#index-1">[4]</a>, <a href="library/cgi.html#index-2">[5]</a>, <a href="library/cgi.html#index-5">[6]</a>, <a href="library/os.html#index-21">[7]</a>, <a href="library/os.html#index-22">[8]</a>, <a href="library/os.html#index-23">[9]</a>, <a href="library/os.html#index-26">[10]</a>, <a href="library/os.html#index-27">[11]</a>, <a href="library/os.html#index-28">[12]</a>, <a href="library/os.html#index-30">[13]</a>, <a href="library/webbrowser.html#index-3">[14]</a>, <a href="tutorial/appendix.html#index-0">[15]</a>, <a href="tutorial/modules.html#index-2">[16]</a>, <a href="using/cmdline.html#index-18">[17]</a>, <a href="using/unix.html#index-2">[18]</a>
</li>
        <li><a href="distutils/apiref.html#index-2">PLAT</a>
</li>
        <li><a href="library/getopt.html#index-0">POSIXLY_CORRECT</a>
</li>
        <li><a href="using/cmdline.html#index-3">PYTHON*</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONCASEOK">PYTHONCASEOK</a>, <a href="whatsnew/2.1.html#index-8">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONDEBUG">PYTHONDEBUG</a>, <a href="using/cmdline.html#index-2">[1]</a>
</li>
        <li><a href="library/pydoc.html#index-2">PYTHONDOCS</a>
</li>
        <li><a href="library/sys.html#index-0">PYTHONDONTWRITEBYTECODE</a>, <a href="using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE">[1]</a>, <a href="using/cmdline.html#index-1">[2]</a>, <a href="whatsnew/2.6.html#index-20">[3]</a>, <a href="whatsnew/2.6.html#index-24">[4]</a>
</li>
        <li><a href="c-api/typeobj.html#index-0">PYTHONDUMPREFS</a>, <a href="using/cmdline.html#envvar-PYTHONDUMPREFS">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONEXECUTABLE">PYTHONEXECUTABLE</a>
</li>
        <li><a href="library/random.html#index-0">PYTHONHASHSEED</a>, <a href="using/cmdline.html#envvar-PYTHONHASHSEED">[1]</a>, <a href="using/cmdline.html#index-10">[2]</a>, <a href="using/cmdline.html#index-23">[3]</a>
</li>
        <li><a href="c-api/init.html#index-11">PYTHONHOME</a>, <a href="c-api/init.html#index-12">[1]</a>, <a href="c-api/intro.html#index-24">[2]</a>, <a href="c-api/intro.html#index-27">[3]</a>, <a href="install/index.html#index-0">[4]</a>, <a href="install/index.html#index-1">[5]</a>, <a href="using/cmdline.html#envvar-PYTHONHOME">[6]</a>, <a href="using/cmdline.html#index-16">[7]</a>, <a href="using/cmdline.html#index-17">[8]</a>, <a href="using/cmdline.html#index-20">[9]</a>, <a href="using/cmdline.html#index-5">[10]</a>, <a href="using/windows.html#index-3">[11]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONHTTPSVERIFY">PYTHONHTTPSVERIFY</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONINSPECT">PYTHONINSPECT</a>, <a href="using/cmdline.html#index-7">[1]</a>, <a href="whatsnew/2.3.html#index-29">[2]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONIOENCODING">PYTHONIOENCODING</a>, <a href="whatsnew/2.6.html#index-21">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONMALLOCSTATS">PYTHONMALLOCSTATS</a>
</li>
        <li><a href="library/site.html#index-5">PYTHONNOUSERSITE</a>, <a href="library/site.html#index-8">[1]</a>, <a href="using/cmdline.html#envvar-PYTHONNOUSERSITE">[2]</a>, <a href="whatsnew/2.6.html#index-6">[3]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONOPTIMIZE">PYTHONOPTIMIZE</a>, <a href="using/cmdline.html#index-8">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-25">PYTHONPATH</a>, <a href="c-api/intro.html#index-28">[1]</a>, <a href="install/index.html#index-2">[2]</a>, <a href="install/index.html#index-3">[3]</a>, <a href="library/cgi.html#index-3">[4]</a>, <a href="library/sys.html#index-7">[5]</a>, <a href="library/sys.html#index-8">[6]</a>, <a href="tutorial/modules.html#index-1">[7]</a>, <a href="tutorial/modules.html#index-5">[8]</a>, <a href="tutorial/modules.html#index-6">[9]</a>, <a href="using/cmdline.html#envvar-PYTHONPATH">[10]</a>, <a href="using/cmdline.html#index-19">[11]</a>, <a href="using/cmdline.html#index-21">[12]</a>, <a href="using/cmdline.html#index-22">[13]</a>, <a href="using/cmdline.html#index-4">[14]</a>, <a href="using/mac.html#index-0">[15]</a>, <a href="using/windows.html#index-2">[16]</a>, <a href="using/windows.html#index-4">[17]</a>
</li>
        <li><a href="c-api/typeobj.html#index-3">PYTHONSHOWALLOCCOUNT</a>, <a href="using/cmdline.html#envvar-PYTHONSHOWALLOCCOUNT">[1]</a>, <a href="whatsnew/2.7.html#index-15">[2]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONSHOWREFCOUNT">PYTHONSHOWREFCOUNT</a>, <a href="whatsnew/2.7.html#index-14">[1]</a>
</li>
        <li><a href="library/idle.html#index-6">PYTHONSTARTUP</a>, <a href="library/readline.html#index-0">[1]</a>, <a href="library/rlcompleter.html#index-0">[2]</a>, <a href="library/user.html#index-1">[3]</a>, <a href="tutorial/appendix.html#index-1">[4]</a>, <a href="tutorial/interactive.html#index-1">[5]</a>, <a href="using/cmdline.html#envvar-PYTHONSTARTUP">[6]</a>, <a href="using/cmdline.html#index-6">[7]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONTHREADDEBUG">PYTHONTHREADDEBUG</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONUNBUFFERED">PYTHONUNBUFFERED</a>, <a href="using/cmdline.html#index-12">[1]</a>
</li>
        <li><a href="library/site.html#index-6">PYTHONUSERBASE</a>, <a href="library/site.html#index-7">[1]</a>, <a href="using/cmdline.html#envvar-PYTHONUSERBASE">[2]</a>, <a href="whatsnew/2.6.html#index-4">[3]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONVERBOSE">PYTHONVERBOSE</a>, <a href="using/cmdline.html#index-13">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONWARNINGS">PYTHONWARNINGS</a>, <a href="using/cmdline.html#index-15">[1]</a>, <a href="whatsnew/2.7.html#index-1">[2]</a>, <a href="whatsnew/2.7.html#index-8">[3]</a>
</li>
        <li><a href="library/time.html#index-3">PYTHONY2K</a>, <a href="library/time.html#index-4">[1]</a>, <a href="library/time.html#index-7">[2]</a>, <a href="using/cmdline.html#envvar-PYTHONY2K">[3]</a>
</li>
        <li><a href="library/xml.dom.html#index-0">PYTHON_DOM</a>
</li>
        <li><a href="library/ssl.html#index-18">SSL_CERT_FILE</a>
</li>
        <li><a href="library/ssl.html#index-19">SSL_CERT_PATH</a>
</li>
        <li><a href="library/subprocess.html#index-3">SystemRoot</a>
</li>
        <li><a href="faq/gui.html#index-0">TCL_LIBRARY</a>
</li>
        <li><a href="library/tempfile.html#index-2">TEMP</a>
</li>
        <li><a href="library/curses.html#index-1">TERM</a>, <a href="library/curses.html#index-2">[1]</a>
</li>
        <li><a href="library/tix.html#index-1">TIX_LIBRARY</a>
</li>
        <li><a href="faq/gui.html#index-1">TK_LIBRARY</a>
</li>
        <li><a href="library/os.html#index-19">TMP</a>, <a href="library/tempfile.html#index-3">[1]</a>
</li>
        <li><a href="library/os.html#index-18">TMPDIR</a>, <a href="library/tempfile.html#index-1">[1]</a>
</li>
        <li><a href="library/time.html#index-10">TZ</a>, <a href="library/time.html#index-11">[1]</a>, <a href="library/time.html#index-12">[2]</a>, <a href="library/time.html#index-13">[3]</a>, <a href="library/time.html#index-14">[4]</a>, <a href="library/time.html#index-15">[5]</a>
</li>
        <li><a href="library/getpass.html#index-1">USER</a>
</li>
        <li><a href="library/getpass.html#index-3">USERNAME</a>
</li>
        <li><a href="install/index.html#index-6">USERPROFILE</a>, <a href="library/os.path.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-9">USER_BASE</a>
</li>
        <li><a href="library/tempfile.html#index-4">Wimp$ScrapDir</a>
</li>
        <li><a href="c-api/intro.html#index-1">exec_prefix</a>, <a href="c-api/intro.html#index-4">[1]</a>, <a href="using/unix.html#index-1">[2]</a>
</li>
        <li><a href="library/urllib.html#index-3">ftp_proxy</a>
</li>
        <li><a href="howto/urllib2.html#index-1">http_proxy</a>, <a href="library/urllib.html#index-2">[1]</a>, <a href="library/urllib2.html#index-0">[2]</a>, <a href="library/urllib2.html#index-6">[3]</a>
</li>
        <li><a href="library/urllib.html#index-4">no_proxy</a>, <a href="library/urllib.html#index-6">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-0">prefix</a>, <a href="c-api/intro.html#index-2">[1]</a>, <a href="c-api/intro.html#index-3">[2]</a>, <a href="using/unix.html#index-0">[3]</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    environment variables

      <ul>
        <li><a href="library/os.html#index-10">deleting</a>
</li>
        <li><a href="library/os.html#index-7">setting</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.EnvironmentError">EnvironmentError</a>
</li>
      <li><a href="library/test.html#test.support.EnvironmentVarGuard">EnvironmentVarGuard (class in test.support)</a>
</li>
      <li><a href="library/errno.html#errno.ENXIO">ENXIO (in module errno)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.eof">eof (shlex.shlex attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.EOFError">EOFError</a>

      <ul>
        <li><a href="c-api/file.html#index-3">(built-in exception)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EOPNOTSUPP">EOPNOTSUPP (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EOVERFLOW">EOVERFLOW (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPERM">EPERM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPFNOSUPPORT">EPFNOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.epilogue">epilogue (email.message.Message attribute)</a>
</li>
      <li><a href="library/errno.html#errno.EPIPE">EPIPE (in module errno)</a>
</li>
      <li><a href="library/time.html#index-0">epoch</a>
</li>
      <li><a href="library/select.html#select.epoll">epoll() (in module select)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTO">EPROTO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTONOSUPPORT">EPROTONOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTOTYPE">EPROTOTYPE (in module errno)</a>
</li>
      <li><a href="library/operator.html#operator.eq">eq() (in module operator)</a>
</li>
      <li><a href="library/token.html#token.EQEQUAL">EQEQUAL (in module token)</a>
</li>
      <li><a href="library/token.html#token.EQUAL">EQUAL (in module token)</a>
</li>
      <li><a href="library/locale.html#locale.ERA">ERA (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_D_FMT">ERA_D_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_D_T_FMT">ERA_D_T_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_T_FMT">ERA_T_FMT (in module locale)</a>
</li>
      <li><a href="library/errno.html#errno.ERANGE">ERANGE (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.window.erase">erase() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.erasechar">erasechar() (in module curses)</a>
</li>
      <li><a href="library/errno.html#errno.EREMCHG">EREMCHG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EREMOTE">EREMOTE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EREMOTEIO">EREMOTEIO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ERESTART">ERESTART (in module errno)</a>
</li>
      <li><a href="library/math.html#math.erf">erf() (in module math)</a>
</li>
      <li><a href="library/math.html#math.erfc">erfc() (in module math)</a>
</li>
      <li><a href="library/errno.html#errno.EROFS">EROFS (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.ERR">ERR (in module curses)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.errcheck">errcheck (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.errcode">errcode (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.errmsg">errmsg (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li>
    errno

      <ul>
        <li><a href="library/exceptions.html#index-3">module</a>, <a href="library/socket.html#index-2">[1]</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#module-errno">errno (module)</a>
</li>
      <li><a href="library/binascii.html#binascii.Error">Error</a>, <a href="library/binhex.html#binhex.Error">[1]</a>, <a href="library/configparser.html#ConfigParser.Error">[2]</a>, <a href="library/csv.html#csv.Error">[3]</a>, <a href="library/locale.html#locale.Error">[4]</a>, <a href="library/macos.html#MacOS.Error">[5]</a>, <a href="library/mailbox.html#mailbox.Error">[6]</a>, <a href="library/shutil.html#shutil.Error">[7]</a>, <a href="library/sunau.html#sunau.Error">[8]</a>, <a href="library/uu.html#uu.Error">[9]</a>, <a href="library/wave.html#wave.Error">[10]</a>, <a href="library/webbrowser.html#webbrowser.Error">[11]</a>, <a href="library/xdrlib.html#xdrlib.Error">[12]</a>
</li>
      <li><a href="library/anydbm.html#anydbm.error">error</a>, <a href="library/audioop.html#audioop.error">[1]</a>, <a href="library/cd.html#cd.error">[2]</a>, <a href="library/copy.html#copy.error">[3]</a>, <a href="library/curses.html#curses.error">[4]</a>, <a href="library/dbhash.html#dbhash.error">[5]</a>, <a href="library/dbm.html#dbm.error">[6]</a>, <a href="library/dl.html#dl.error">[7]</a>, <a href="library/dumbdbm.html#dumbdbm.error">[8]</a>, <a href="library/gdbm.html#gdbm.error">[9]</a>, <a href="library/getopt.html#getopt.error">[10]</a>, <a href="library/ic.html#ic.error">[11]</a>, <a href="library/imageop.html#imageop.error">[12]</a>, <a href="library/imgfile.html#imgfile.error">[13]</a>, <a href="library/jpeg.html#jpeg.error">[14]</a>, <a href="library/nis.html#nis.error">[15]</a>, <a href="library/os.html#os.error">[16]</a>, <a href="library/pyexpat.html#xml.parsers.expat.error">[17]</a>, <a href="library/re.html#re.error">[18]</a>, <a href="library/resource.html#resource.error">[19]</a>, <a href="library/select.html#select.error">[20]</a>, <a href="library/socket.html#socket.error">[21]</a>, <a href="library/struct.html#struct.error">[22]</a>, <a href="library/sunaudio.html#sunaudiodev.error">[23]</a>, <a href="library/thread.html#thread.error">[24]</a>, <a href="library/zlib.html#zlib.error">[25]</a>
</li>
      <li><a href="library/cd.html#cd.ERROR">ERROR (in module cd)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">error handling</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.error">error() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/logging.html#logging.error">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.error">(logging.Logger method)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.Folder.error">(mhlib.Folder method)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.MH.error">(mhlib.MH method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.OpenerDirector.error">(urllib2.OpenerDirector method)</a>
</li>
        <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.error">(xml.sax.handler.ErrorHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_body">error_body (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.error_content_type">error_content_type (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_headers">error_headers (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.error_leader">error_leader() (shlex.shlex method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.error_message_format">error_message_format (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_output">error_output() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_perm">error_perm</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_proto">error_proto</a>, <a href="library/poplib.html#poplib.error_proto">[1]</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_reply">error_reply</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_status">error_status (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_temp">error_temp</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorByteIndex">ErrorByteIndex (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/errno.html#errno.errorcode">errorcode (in module errno)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorCode">ErrorCode (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorColumnNumber">ErrorColumnNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler">ErrorHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorLineNumber">ErrorLineNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li>
    Errors

      <ul>
        <li><a href="library/logging.html#index-0">logging</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-13">errors</a>

      <ul>
        <li><a href="library/stdtypes.html#file.errors">(file attribute)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.errors">(io.TextIOBase attribute)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.errors">(unittest.TestResult attribute)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ErrorString">ErrorString() (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/token.html#token.ERRORTOKEN">ERRORTOKEN (in module token)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.escape">escape (shlex.shlex attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-15">escape sequence</a>
</li>
      <li><a href="library/cgi.html#cgi.escape">escape() (in module cgi)</a>

      <ul>
        <li><a href="library/re.html#re.escape">(in module re)</a>
</li>
        <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.escape">(in module xml.sax.saxutils)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.escapechar">escapechar (csv.Dialect attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.escapedquotes">escapedquotes (shlex.shlex attribute)</a>
</li>
      <li><a href="library/errno.html#errno.ESHUTDOWN">ESHUTDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESOCKTNOSUPPORT">ESOCKTNOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESPIPE">ESPIPE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESRCH">ESRCH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESRMNT">ESRMNT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESTALE">ESTALE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESTRPIPE">ESTRPIPE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ETIME">ETIME (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ETIMEDOUT">ETIMEDOUT (in module errno)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.Etiny">Etiny() (decimal.Context method)</a>
</li>
      <li><a href="library/errno.html#errno.ETOOMANYREFS">ETOOMANYREFS (in module errno)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.Etop">Etop() (decimal.Context method)</a>
</li>
      <li><a href="library/errno.html#errno.ETXTBSY">ETXTBSY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUCLEAN">EUCLEAN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUNATCH">EUNATCH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUSERS">EUSERS (in module errno)</a>
</li>
      <li>
    eval

      <ul>
        <li><a href="library/parser.html#index-1">built-in function</a>, <a href="library/pprint.html#index-0">[1]</a>, <a href="library/pprint.html#index-1">[2]</a>, <a href="library/stdtypes.html#index-41">[3]</a>, <a href="library/string.html#index-7">[4]</a>, <a href="reference/simple_stmts.html#index-55">[5]</a>, <a href="reference/simple_stmts.html#index-58">[6]</a>, <a href="reference/toplevel_components.html#index-6">[7]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#eval">eval() (built-in function)</a>
</li>
      <li>
    evaluation

      <ul>
        <li><a href="reference/expressions.html#index-79">order</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Event">Event (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Event">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/sched.html#index-0">event scheduling</a>
</li>
      <li><a href="library/msilib.html#msilib.Control.event">event() (msilib.Control method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Event">Event() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/tkinter.html#index-3">events (widgets)</a>
</li>
      <li><a href="library/errno.html#errno.EWOULDBLOCK">EWOULDBLOCK (in module errno)</a>
</li>
      <li><a href="library/os.html#os.EX_CANTCREAT">EX_CANTCREAT (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_CONFIG">EX_CONFIG (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_DATAERR">EX_DATAERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_IOERR">EX_IOERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOHOST">EX_NOHOST (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOINPUT">EX_NOINPUT (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOPERM">EX_NOPERM (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOTFOUND">EX_NOTFOUND (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOUSER">EX_NOUSER (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OK">EX_OK (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OSERR">EX_OSERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OSFILE">EX_OSFILE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_PROTOCOL">EX_PROTOCOL (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_SOFTWARE">EX_SOFTWARE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_TEMPFAIL">EX_TEMPFAIL (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_UNAVAILABLE">EX_UNAVAILABLE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_USAGE">EX_USAGE (in module os)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example">Example (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.example">example (doctest.DocTestFailure attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.UnexpectedException.example">(doctest.UnexpectedException attribute)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTest.examples">examples (doctest.DocTest attribute)</a>
</li>
      <li><a href="library/sys.html#sys.exc_clear">exc_clear() (in module sys)</a>
</li>
      <li><a href="library/doctest.html#doctest.UnexpectedException.exc_info">exc_info (doctest.UnexpectedException attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-67">(in module sys)</a>
</li>
      </ul></li>
      <li><a href="c-api/intro.html#index-15">exc_info() (in module sys)</a>, <a href="library/sys.html#sys.exc_info">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.exc_msg">exc_msg (doctest.Example attribute)</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_traceback (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_traceback">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/datamodel.html#index-67">[4]</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_type (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_type">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_value (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_value">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>
</li>
      <li><a href="library/csv.html#csv.excel">excel (class in csv)</a>
</li>
      <li><a href="library/csv.html#csv.excel_tab">excel_tab (class in csv)</a>
</li>
      <li>
    except

      <ul>
        <li><a href="howto/doanddont.html#index-0">bare</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">keyword</a>
</li>
        <li><a href="library/exceptions.html#index-0">statement</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-except">except (2to3 fixer)</a>
</li>
      <li><a href="library/cgitb.html#index-1">excepthook() (in module sys)</a>, <a href="library/sys.html#sys.excepthook">[1]</a>
</li>
      <li><a href="library/exceptions.html#exceptions.Exception">Exception</a>
</li>
      <li><a href="reference/executionmodel.html#index-12">exception</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-16">AssertionError</a>
</li>
        <li><a href="reference/expressions.html#index-30">AttributeError</a>
</li>
        <li><a href="reference/expressions.html#index-26">GeneratorExit</a>
</li>
        <li><a href="reference/simple_stmts.html#index-44">ImportError</a>, <a href="reference/simple_stmts.html#index-47">[1]</a>, <a href="reference/simple_stmts.html#index-48">[2]</a>
</li>
        <li><a href="reference/expressions.html#index-6">NameError</a>
</li>
        <li><a href="reference/simple_stmts.html#index-24">RuntimeError</a>
</li>
        <li><a href="reference/expressions.html#index-25">StopIteration</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-51">TypeError</a>
</li>
        <li><a href="reference/expressions.html#index-59">ValueError</a>
</li>
        <li><a href="reference/expressions.html#index-54">ZeroDivisionError</a>
</li>
        <li><a href="reference/datamodel.html#index-67">handler</a>
</li>
        <li><a href="reference/simple_stmts.html#index-31">raising</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#Tkinter.EXCEPTION">EXCEPTION (in module Tkinter)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">exception handler</a>
</li>
      <li><a href="library/logging.html#logging.exception">exception() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.exception">(logging.Logger method)</a>
</li>
      </ul></li>
      <li>
    exceptions

      <ul>
        <li><a href="library/cgitb.html#index-0">in CGI scripts</a>
</li>
        <li><a href="c-api/intro.html#index-20">module</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#module-exceptions">exceptions (module)</a>
</li>
      <li>
    exclusive

      <ul>
        <li><a href="reference/expressions.html#index-62">or</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EXDEV">EXDEV (in module errno)</a>
</li>
      <li>
    exec

      <ul>
        <li><a href="library/stdtypes.html#index-41">statement</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>, <a href="reference/simple_stmts.html#index-56">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-exec">exec (2to3 fixer)</a>
</li>
      <li><a href="c-api/intro.html#index-1">exec_prefix</a>, <a href="c-api/intro.html#index-4">[1]</a>, <a href="using/unix.html#index-1">[2]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.EXEC_PREFIX">EXEC_PREFIX (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sys.html#sys.exec_prefix">exec_prefix (in module sys)</a>
</li>
      <li><a href="library/dis.html#opcode-EXEC_STMT">EXEC_STMT (opcode)</a>
</li>
      <li>
    execfile

      <ul>
        <li><a href="library/user.html#index-2">built-in function</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-execfile">execfile (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#execfile">execfile() (built-in function)</a>
</li>
      <li><a href="library/os.html#os.execl">execl() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execle">execle() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execlp">execlp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execlpe">execlpe() (in module os)</a>
</li>
      <li><a href="c-api/init.html#index-3">executable (in module sys)</a>, <a href="library/sys.html#sys.executable">[1]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.executable_filename">executable_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.execute">execute() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.util.execute">(in module distutils.util)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.View.Execute">Execute() (msilib.View method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.execute">execute() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.execute">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.executemany">executemany() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.executemany">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.executescript">executescript() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.executescript">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li>
    execution

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">frame</a>, <a href="reference/executionmodel.html#index-4">[1]</a>
</li>
        <li><a href="reference/executionmodel.html#index-10">restricted</a>
</li>
        <li><a href="reference/datamodel.html#index-67">stack</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-0">execution model</a>
</li>
      <li><a href="library/os.html#os.execv">execv() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execve">execve() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execvp">execvp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execvpe">execvpe() (in module os)</a>
</li>
      <li><a href="library/tix.html#Tix.ExFileSelectBox">ExFileSelectBox (class in Tix)</a>
</li>
      <li><a href="library/errno.html#errno.EXFULL">EXFULL (in module errno)</a>
</li>
      <li><a href="library/os.path.html#os.path.exists">exists() (in module os.path)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.exists">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#exit">exit (built-in variable)</a>
</li>
      <li><a href="c-api/sys.html#index-1">exit()</a>

      <ul>
        <li><a href="library/argparse.html#argparse.ArgumentParser.exit">(argparse.ArgumentParser method)</a>
</li>
        <li><a href="library/sys.html#sys.exit">(in module sys)</a>
</li>
        <li><a href="library/thread.html#thread.exit">(in module thread)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.exitcode">exitcode (multiprocessing.Process attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-exitfunc">exitfunc (2to3 fixer)</a>

      <ul>
        <li><a href="library/sys.html#sys.exitfunc">(in module sys)</a>
</li>
        <li><a href="library/atexit.html#index-0">(in sys)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.exitonclick">exitonclick() (in module turtle)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.exp">exp() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.exp">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.exp">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.exp">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/re.html#re.MatchObject.expand">expand() (re.MatchObject method)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.expand_tabs">expand_tabs (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.ExpandEnvironmentStrings">ExpandEnvironmentStrings() (in module _winreg)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.expandNode">expandNode() (xml.dom.pulldom.DOMEventStream method)</a>
</li>
      <li><a href="library/string.html#string.expandtabs">expandtabs() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.expandtabs">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.expanduser">expanduser() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.expandvars">expandvars() (in module os.path)</a>
</li>
      <li><a href="library/pyexpat.html#index-0">Expat</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError">ExpatError</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.expect">expect() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/unittest.html#unittest.expectedFailure">expectedFailure() (in module unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.expectedFailures">expectedFailures (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.expires">expires (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/math.html#math.expm1">expm1() (in module math)</a>
</li>
      <li><a href="library/random.html#random.expovariate">expovariate() (in module random)</a>
</li>
      <li><a href="library/parser.html#parser.expr">expr() (in module parser)</a>
</li>
      <li><a href="reference/expressions.html#index-0">expression</a>, <a href="glossary.html#term-expression"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-69">Conditional</a>
</li>
        <li><a href="reference/expressions.html#index-73">conditional</a>
</li>
        <li><a href="reference/expressions.html#index-15">generator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-22">lambda</a>, <a href="reference/expressions.html#index-75">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-76">list</a>, <a href="reference/simple_stmts.html#index-1">[1]</a>, <a href="reference/simple_stmts.html#index-4">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-1">statement</a>
</li>
        <li><a href="reference/expressions.html#index-22">yield</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.expunge">expunge() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/array.html#array.array.extend">extend() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.extend">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.extend">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/pkgutil.html#pkgutil.extend_path">extend_path() (in module pkgutil)</a>
</li>
      <li>
    extended

      <ul>
        <li><a href="reference/expressions.html#index-36">slicing</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-25">extended print statement</a>
</li>
      <li>
    extended slice

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-19">extended slicing</a>
</li>
      <li><a href="library/dis.html#opcode-EXTENDED_ARG">EXTENDED_ARG (opcode)</a>
</li>
      <li><a href="library/decimal.html#decimal.ExtendedContext">ExtendedContext (class in decimal)</a>
</li>
      <li><a href="library/collections.html#collections.deque.extendleft">extendleft() (collections.deque method)</a>
</li>
      <li>
    extension

      <ul>
        <li><a href="reference/datamodel.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.core.Extension">Extension (class in distutils.core)</a>
</li>
      <li><a href="glossary.html#term-extension-module"><strong>extension module</strong></a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map">extensions_map (SimpleHTTPServer.SimpleHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/pickle.html#index-1">External Data Representation</a>, <a href="library/xdrlib.html#index-0">[1]</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.external_attr">external_attr (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.ExternalClashError">ExternalClashError</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ExternalEntityParserCreate">ExternalEntityParserCreate() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ExternalEntityRefHandler">ExternalEntityRefHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.extra">extra (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extract">extract() (tarfile.TarFile method)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.extract">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.extract_cookies">extract_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/traceback.html#traceback.extract_stack">extract_stack() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.extract_tb">extract_tb() (in module traceback)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.extract_version">extract_version (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extractall">extractall() (tarfile.TarFile method)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.extractall">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.ExtractError">ExtractError</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extractfile">extractfile() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/os.html#os.extsep">extsep (in module os)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="F">F</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/datamodel.html#index-65">f_back (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BAVAIL">F_BAVAIL (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BFREE">F_BFREE (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BLOCKS">F_BLOCKS (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BSIZE">F_BSIZE (in module statvfs)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_builtins (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_code (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_traceback (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_type (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_value (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FAVAIL">F_FAVAIL (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FFREE">F_FFREE (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FILES">F_FILES (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FLAG">F_FLAG (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FRSIZE">F_FRSIZE (in module statvfs)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_globals (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_lasti (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_lineno (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_locals (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_NAMEMAX">F_NAMEMAX (in module statvfs)</a>
</li>
      <li><a href="library/os.html#os.F_OK">F_OK (in module os)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_restricted (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_trace (frame attribute)</a>
</li>
      <li><a href="library/math.html#math.fabs">fabs() (in module math)</a>
</li>
      <li><a href="library/math.html#math.factorial">factorial() (in module math)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.fail">fail() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.failfast">failfast (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.failureException">failureException (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.failures">failures (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-43">False</a>, <a href="library/stdtypes.html#index-6">[1]</a>, <a href="reference/datamodel.html#index-13">[2]</a>
</li>
      <li><a href="library/stdtypes.html#index-2">false</a>
</li>
      <li><a href="library/stdtypes.html#index-4">False (Built-in object)</a>

      <ul>
        <li><a href="library/constants.html#False">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.socket.family">family (socket.socket attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.fancy_getopt">fancy_getopt() (in module distutils.fancy_getopt)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt">FancyGetopt (class in distutils.fancy_getopt)</a>
</li>
      <li><a href="library/urllib.html#urllib.FancyURLopener">FancyURLopener (class in urllib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.fatalError">fatalError() (xml.sax.handler.ErrorHandler method)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault">Fault (class in xmlrpclib)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault.faultCode">faultCode (xmlrpclib.Fault attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault.faultString">faultString (xmlrpclib.Fault attribute)</a>
</li>
      <li><a href="library/os.html#os.fchdir">fchdir() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fchmod">fchmod() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fchown">fchown() (in module os)</a>
</li>
      <li><a href="library/msilib.html#msilib.FCICreate">FCICreate() (in module msilib)</a>
</li>
      <li>
    fcntl

      <ul>
        <li><a href="library/stdtypes.html#index-35">module</a>
</li>
      </ul></li>
      <li><a href="library/fcntl.html#module-fcntl">fcntl (module)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.fcntl">fcntl() (in module fcntl)</a>, <a href="library/posixfile.html#index-1">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.fd">fd() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.fdatasync">fdatasync() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fdopen">fdopen() (in module os)</a>
</li>
      <li><a href="library/msilib.html#msilib.Feature">Feature (class in msilib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_external_ges">feature_external_ges (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_external_pes">feature_external_pes (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_namespace_prefixes">feature_namespace_prefixes (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_namespaces">feature_namespaces (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_string_interning">feature_string_interning (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_validation">feature_validation (in module xml.sax.handler)</a>
</li>
      <li><a href="library/email.parser.html#email.parser.FeedParser.feed">feed() (email.parser.FeedParser method)</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.feed">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.feed">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.feed">(xml.etree.ElementTree.XMLParser method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.feed">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
      </ul></li>
      <li><a href="library/email.parser.html#email.parser.FeedParser">FeedParser (class in email.parser)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.fetch">fetch() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.Fetch">Fetch() (msilib.View method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchall">fetchall() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchmany">fetchmany() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchone">fetchone() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/select.html#select.kevent.fflags">fflags (select.kevent attribute)</a>
</li>
      <li><a href="library/csv.html#csv.field_size_limit">field_size_limit() (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.fieldnames">fieldnames (csv.csvreader attribute)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.fields">fields (uuid.UUID attribute)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo">fifo (class in asynchat)</a>
</li>
      <li>
    file

      <ul>
        <li><a href="library/configparser.html#index-0">.ini</a>
</li>
        <li><a href="library/pdb.html#index-2">.pdbrc</a>
</li>
        <li><a href="library/user.html#index-0">.pythonrc.py</a>
</li>
        <li><a href="library/stdtypes.html#index-34">built-in function</a>
</li>
        <li><a href="library/imp.html#index-1">byte-code</a>, <a href="library/imp.html#index-3">[1]</a>, <a href="library/py_compile.html#index-0">[2]</a>
</li>
        <li><a href="library/configparser.html#index-0">configuration</a>
</li>
        <li><a href="library/shutil.html#index-0">copying</a>
</li>
        <li><a href="library/pdb.html#index-2">debugger configuration</a>
</li>
        <li><a href="library/stdtypes.html#index-35">descriptor</a>
</li>
        <li><a href="library/posix.html#index-1">large files</a>
</li>
        <li><a href="library/mimetypes.html#index-2">mime.types</a>
</li>
        <li><a href="c-api/file.html#index-0">object</a>, <a href="library/stdtypes.html#index-34">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/toplevel_components.html#index-8">[3]</a>, <a href="tutorial/inputoutput.html#index-0">[4]</a>
</li>
        <li><a href="library/site.html#index-2">path configuration</a>
</li>
        <li><a href="library/plistlib.html#index-0">plist</a>
</li>
        <li><a href="library/tempfile.html#index-0">temporary</a>
</li>
        <li><a href="library/user.html#index-0">user configuration</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.file">file (pyclbr.Class attribute)</a>

      <ul>
        <li><a href="library/pyclbr.html#pyclbr.Function.file">(pyclbr.Function attribute)</a>
</li>
      </ul></li>
      <li>
    file ...

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-file">compileall command line option</a>
</li>
      </ul></li>
      <li>
    file control

      <ul>
        <li><a href="library/fcntl.html#index-0">UNIX</a>
</li>
      </ul></li>
      <li>
    file name

      <ul>
        <li><a href="library/tempfile.html#index-0">temporary</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-file-object"><strong>file object</strong></a>

      <ul>
        <li><a href="library/posixfile.html#index-0">POSIX</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#file">file() (built-in function)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.file">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-file-like-object"><strong>file-like object</strong></a>
</li>
      <li><a href="distutils/builtdist.html#file_created">file_created() (built-in function)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.file_dispatcher">file_dispatcher (class in asyncore)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FileHandler.file_open">file_open() (urllib2.FileHandler method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.file_size">file_size (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.file_wrapper">file_wrapper (class in asyncore)</a>
</li>
      <li><a href="library/filecmp.html#module-filecmp">filecmp (module)</a>
</li>
      <li><a href="library/logging.config.html#logging.config.fileConfig">fileConfig() (in module logging.config)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar">FileCookieJar (class in cookielib)</a>
</li>
      <li><a href="library/tix.html#Tix.FileEntry">FileEntry (class in Tix)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.FileHandler">FileHandler (class in logging)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.FileHandler">(class in urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.FileInput">FileInput (class in fileinput)</a>
</li>
      <li><a href="library/fileinput.html#module-fileinput">fileinput (module)</a>
</li>
      <li><a href="library/io.html#io.FileIO">FileIO (class in io)</a>
</li>
      <li><a href="library/fileinput.html#fileinput.filelineno">filelineno() (in module fileinput)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.filename">filename (cookielib.FileCookieJar attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.filename">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipInfo.filename">(zipfile.ZipInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.filename">filename() (in module fileinput)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.filename_only">filename_only (in module tabnanny)</a>
</li>
      <li>
    filenames

      <ul>
        <li><a href="library/glob.html#index-0">pathname expansion</a>
</li>
        <li><a href="library/fnmatch.html#index-0">wildcard expansion</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.fileno">fileno() (Connection method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.fileno">(SocketServer.BaseServer method)</a>
</li>
        <li><a href="library/stdtypes.html#file.fileno">(file method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.fileno">(hotshot.Profile method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPResponse.fileno">(httplib.HTTPResponse method)</a>
</li>
        <li><a href="library/fileinput.html#fileinput.fileno">(in module fileinput)</a>
</li>
        <li><a href="library/io.html#io.IOBase.fileno">(io.IOBase method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.fileno">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.fileno">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/select.html#select.epoll.fileno">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.fileno">(select.kqueue method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.fileno">(socket.socket method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.fileno">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#posixfile.fileopen">fileopen() (in module posixfile)</a>
</li>
      <li><a href="library/tix.html#Tix.FileSelectBox">FileSelectBox (class in Tix)</a>
</li>
      <li><a href="library/argparse.html#argparse.FileType">FileType (class in argparse)</a>

      <ul>
        <li><a href="c-api/file.html#index-1">(in module types)</a>, <a href="library/types.html#types.FileType">[1]</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.FileWrapper">FileWrapper (class in wsgiref.util)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.fill">fill() (in module textwrap)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.fill">(in module turtle)</a>
</li>
        <li><a href="library/textwrap.html#textwrap.TextWrapper.fill">(textwrap.TextWrapper method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.fillcolor">fillcolor() (in module turtle)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-filter">filter (2to3 fixer)</a>
</li>
      <li><a href="library/logging.html#logging.Filter">Filter (class in logging)</a>
</li>
      <li><a href="library/select.html#select.kevent.filter">filter (select.kevent attribute)</a>
</li>
      <li><a href="library/functions.html#filter">filter() (built-in function)</a>

      <ul>
        <li><a href="library/curses.html#curses.filter">(in module curses)</a>
</li>
        <li><a href="library/fnmatch.html#fnmatch.filter">(in module fnmatch)</a>
</li>
        <li><a href="library/future_builtins.html#future_builtins.filter">(in module future_builtins)</a>
</li>
        <li><a href="library/logging.html#logging.Filter.filter">(logging.Filter method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.filter">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.filter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#warnings.filterwarnings">filterwarnings() (in module warnings)</a>
</li>
      <li><a href="extending/newtypes.html#index-0">finalization, of objects</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.finalize_options">finalize_options() (distutils.cmd.Command method)</a>
</li>
      <li>
    finally

      <ul>
        <li><a href="reference/compound_stmts.html#index-10">keyword</a>, <a href="reference/compound_stmts.html#index-13">[1]</a>, <a href="reference/simple_stmts.html#index-27">[2]</a>, <a href="reference/simple_stmts.html#index-36">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTestFinder.find">find() (doctest.DocTestFinder method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.find">(in module gettext)</a>
</li>
        <li><a href="library/string.html#string.find">(in module string)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.find">(mmap.mmap method)</a>
</li>
        <li><a href="library/stdtypes.html#str.find">(str method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.find">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.find">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.find_first">find_first() (fl.form method)</a>
</li>
      <li><a href="library/pickle.html#index-4">find_global() (pickle protocol)</a>
</li>
      <li><a href="library/fl.html#fl.form.find_last">find_last() (fl.form method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.util.find_library">find_library() (in module ctypes.util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.find_library_file">find_library_file() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.find_loader">find_loader() (in module pkgutil)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.find_longest_match">find_longest_match() (difflib.SequenceMatcher method)</a>
</li>
      <li>
    find_module

      <ul>
        <li><a href="reference/simple_stmts.html#index-41">finder</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.NullImporter.find_module">find_module() (imp.NullImporter method)</a>

      <ul>
        <li><a href="library/imp.html#imp.find_module">(in module imp)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.find_module">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.util.find_msvcrt">find_msvcrt() (in module ctypes.util)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr.find_user_password">find_user_password() (urllib2.HTTPPasswordMgr method)</a>
</li>
      <li><a href="library/re.html#re.findall">findall() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.findall">(re.RegexObject method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findall">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger.findCaller">findCaller() (logging.Logger method)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">finder</a>, <a href="glossary.html#term-finder"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-41">find_module</a>
</li>
      </ul></li>
      <li><a href="library/macostools.html#module-findertools">findertools (module)</a>
</li>
      <li><a href="library/audioop.html#audioop.findfactor">findfactor() (in module audioop)</a>
</li>
      <li><a href="library/test.html#test.support.findfile">findfile() (in module test.support)</a>
</li>
      <li><a href="library/audioop.html#audioop.findfit">findfit() (in module audioop)</a>
</li>
      <li><a href="library/fm.html#fm.findfont">findfont() (in module fm)</a>
</li>
      <li><a href="library/re.html#re.finditer">finditer() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.finditer">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#dis.findlabels">findlabels() (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.findlinestarts">findlinestarts() (in module dis)</a>
</li>
      <li><a href="library/mailcap.html#mailcap.findmatch">findmatch() (in module mailcap)</a>
</li>
      <li><a href="library/audioop.html#audioop.findmax">findmax() (in module audioop)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext">findtext() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findtext">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.finish">finish() (SocketServer.BaseRequestHandler method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.finish_request">finish_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo.first">first() (asynchat.fifo method)</a>

      <ul>
        <li><a href="library/bsddb.html#bsddb.bsddbobject.first">(bsddb.bsddbobject method)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.dbhash.first">(dbhash.dbhash method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.firstChild">firstChild (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.firstkey">firstkey() (in module gdbm)</a>
</li>
      <li><a href="library/calendar.html#calendar.firstweekday">firstweekday() (in module calendar)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.fix">fix() (in module fpformat)</a>
</li>
      <li><a href="library/ast.html#ast.fix_missing_locations">fix_missing_locations() (in module ast)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.fix_sentence_endings">fix_sentence_endings (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/fl.html#module-FL">FL (module)</a>
</li>
      <li><a href="library/fl.html#module-fl">fl (module)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.flag_bits">flag_bits (zipfile.ZipInfo attribute)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/sys.html#sys.flags">flags (in module sys)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.flags">(re.RegexObject attribute)</a>
</li>
        <li><a href="library/select.html#select.kevent.flags">(select.kevent attribute)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#posixfile.posixfile.flags">flags() (posixfile.posixfile method)</a>
</li>
      <li><a href="library/curses.html#curses.flash">flash() (in module curses)</a>
</li>
      <li><a href="library/email.generator.html#email.generator.Generator.flatten">flatten() (email.generator.Generator method)</a>
</li>
      <li>
    flattening

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li>
    float

      <ul>
        <li><a href="c-api/number.html#index-7">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-5">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#float">float (built-in class)</a>
</li>
      <li><a href="library/sys.html#sys.float_info">float_info (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.float_repr_style">float_repr_style (in module sys)</a>
</li>
      <li>
    floating point

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="reference/datamodel.html#index-15">number</a>
</li>
        <li><a href="c-api/float.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-15">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">floating point literal</a>
</li>
      <li><a href="library/exceptions.html#exceptions.FloatingPointError">FloatingPointError</a>, <a href="library/fpectl.html#fpectl.FloatingPointError">[1]</a>
</li>
      <li><a href="library/types.html#types.FloatType">FloatType (in module types)</a>

      <ul>
        <li><a href="c-api/float.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/fcntl.html#fcntl.flock">flock() (in module fcntl)</a>
</li>
      <li><a href="glossary.html#term-floor-division"><strong>floor division</strong></a>
</li>
      <li><a href="library/math.html#math.floor">floor() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/operator.html#operator.floordiv">floordiv() (in module operator)</a>
</li>
      <li><a href="library/fl.html#module-flp">flp (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor.flush">flush() (bz2.BZ2Compressor method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.flush">(file method)</a>
</li>
        <li><a href="library/formatter.html#formatter.writer.flush">(formatter.writer method)</a>
</li>
        <li><a href="library/io.html#io.BufferedWriter.flush">(io.BufferedWriter method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.flush">(io.IOBase method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.flush">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.StreamHandler.flush">(logging.StreamHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.flush">(logging.handlers.BufferingHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.flush">(logging.handlers.MemoryHandler method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.flush">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.flush">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.flush">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.flush">(mmap.mmap method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.flush">(zlib.Compress method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.flush">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.flush_softspace">flush_softspace() (formatter.formatter method)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.flushheaders">flushheaders() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/curses.html#curses.flushinp">flushinp() (in module curses)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.FlushKey">FlushKey() (in module _winreg)</a>
</li>
      <li><a href="library/fm.html#module-fm">fm (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.fma">fma() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.fma">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.fmod">fmod() (in module math)</a>
</li>
      <li><a href="library/fnmatch.html#module-fnmatch">fnmatch (module)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.fnmatch">fnmatch() (in module fnmatch)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.fnmatchcase">fnmatchcase() (in module fnmatch)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.focus">focus() (ttk.Treeview method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder">Folder (class in mhlib)</a>
</li>
      <li><a href="library/fm.html#index-0">Font Manager, IRIS</a>
</li>
      <li><a href="library/fm.html#fm.fontpath">fontpath() (in module fm)</a>
</li>
      <li><a href="c-api/file.html#index-2">fopen()</a>
</li>
      <li>
    for

      <ul>
        <li><a href="reference/compound_stmts.html#index-6">statement</a>, <a href="reference/simple_stmts.html#index-33">[1]</a>, <a href="reference/simple_stmts.html#index-37">[2]</a>, <a href="tutorial/controlflow.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-0">[4]</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-FOR_ITER">FOR_ITER (opcode)</a>
</li>
      <li><a href="library/test.html#test.support.forget">forget() (in module test.support)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Notebook.forget">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.fork">fork() (in module os)</a>

      <ul>
        <li><a href="library/pty.html#pty.fork">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.ForkingMixIn">ForkingMixIn (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ForkingTCPServer">ForkingTCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ForkingUDPServer">ForkingUDPServer (class in SocketServer)</a>
</li>
      <li><a href="library/os.html#os.forkpty">forkpty() (in module os)</a>
</li>
      <li><a href="library/tix.html#Tix.Form">Form (class in Tix)</a>
</li>
      <li>
    format

      <ul>
        <li><a href="library/functions.html#index-3">str</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#memoryview.format">format (memoryview attribute)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.format">(struct.Struct attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#format">format() (built-in function)</a>

      <ul>
        <li><a href="library/locale.html#locale.format">(in module locale)</a>
</li>
        <li><a href="library/logging.html#logging.Formatter.format">(logging.Formatter method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.format">(logging.Handler method)</a>
</li>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.format">(pprint.PrettyPrinter method)</a>
</li>
        <li><a href="library/stdtypes.html#str.format">(str method)</a>
</li>
        <li><a href="library/string.html#string.Formatter.format">(string.Formatter method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.format_exc">format_exc() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_exception">format_exception() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_exception_only">format_exception_only() (in module traceback)</a>
</li>
      <li><a href="library/string.html#string.Formatter.format_field">format_field() (string.Formatter method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.format_help">format_help() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_list">format_list() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_stack">format_stack() (in module traceback)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.format_stack_entry">format_stack_entry() (bdb.Bdb method)</a>
</li>
      <li><a href="library/locale.html#locale.format_string">format_string() (in module locale)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_tb">format_tb() (in module traceback)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.format_usage">format_usage() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.formataddr">formataddr() (in module email.utils)</a>
</li>
      <li><a href="library/inspect.html#inspect.formatargspec">formatargspec() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.formatargvalues">formatargvalues() (in module inspect)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.formatdate">formatdate() (in module email.utils)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.FormatError">FormatError</a>
</li>
      <li><a href="library/ctypes.html#ctypes.FormatError">FormatError() (in module ctypes)</a>
</li>
      <li><a href="library/logging.html#logging.Formatter.formatException">formatException() (logging.Formatter method)</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatmonth">formatmonth() (calendar.HTMLCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.TextCalendar.formatmonth">(calendar.TextCalendar method)</a>
</li>
      </ul></li>
      <li>
    formatter

      <ul>
        <li><a href="library/htmllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Formatter">Formatter (class in logging)</a>

      <ul>
        <li><a href="library/string.html#string.Formatter">(class in string)</a>
</li>
      </ul></li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.formatter">formatter (htmllib.HTMLParser attribute)</a>

      <ul>
        <li><a href="library/formatter.html#module-formatter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Formatter.formatTime">formatTime() (logging.Formatter method)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">formatting, string (%)</a>
</li>
      <li><a href="library/warnings.html#warnings.formatwarning">formatwarning() (in module warnings)</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatyear">formatyear() (calendar.HTMLCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.TextCalendar.formatyear">(calendar.TextCalendar method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatyearpage">formatyearpage() (calendar.HTMLCalendar method)</a>
</li>
      <li><a href="library/fl.html#index-0">FORMS Library</a>
</li>
      <li><a href="library/turtle.html#turtle.forward">forward() (in module turtle)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.found_terminator">found_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.fp">fp (rfc822.Message attribute)</a>
</li>
      <li><a href="library/os.html#os.fpathconf">fpathconf() (in module os)</a>
</li>
      <li><a href="library/fpectl.html#module-fpectl">fpectl (module)</a>
</li>
      <li><a href="library/fpformat.html#module-fpformat">fpformat (module)</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction">Fraction (class in fractions)</a>
</li>
      <li><a href="library/fractions.html#module-fractions">fractions (module)</a>
</li>
      <li>
    frame

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">execution</a>, <a href="reference/executionmodel.html#index-4">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-64">object</a>
</li>
      </ul></li>
      <li><a href="library/scrolledtext.html#ScrolledText.ScrolledText.frame">frame (ScrolledText.ScrolledText attribute)</a>
</li>
      <li><a href="library/types.html#types.FrameType">FrameType (in module types)</a>
</li>
      <li>
    FrameWork

      <ul>
        <li><a href="library/miniaeframe.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#module-FrameWork">FrameWork (module)</a>
</li>
      <li>
    free

      <ul>
        <li><a href="reference/executionmodel.html#index-7">variable</a>, <a href="reference/simple_stmts.html#index-20">[1]</a>
</li>
      </ul></li>
      <li><a href="c-api/memory.html#index-0">free()</a>
</li>
      <li><a href="c-api/import.html#index-5">freeze utility</a>
</li>
      <li><a href="library/fl.html#fl.form.freeze_form">freeze_form() (fl.form method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.freeze_support">freeze_support() (in module multiprocessing)</a>
</li>
      <li><a href="library/math.html#math.frexp">frexp() (in module math)</a>
</li>
      <li>
    from

      <ul>
        <li><a href="reference/simple_stmts.html#index-38">keyword</a>
</li>
        <li><a href="reference/executionmodel.html#index-9">statement</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._CData.from_address">from_address() (ctypes._CData method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_buffer">from_buffer() (ctypes._CData method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_buffer_copy">from_buffer_copy() (ctypes._CData method)</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction.from_decimal">from_decimal() (fractions.Fraction method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.from_float">from_float() (decimal.Decimal method)</a>

      <ul>
        <li><a href="library/fractions.html#fractions.Fraction.from_float">(fractions.Fraction method)</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.chain.from_iterable">from_iterable() (itertools.chain class method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_param">from_param() (ctypes._CData method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.from_splittable">from_splittable() (email.charset.Charset method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.frombuf">frombuf() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.fromchild">fromchild (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/socket.html#socket.fromfd">fromfd() (in module socket)</a>

      <ul>
        <li><a href="library/select.html#select.epoll.fromfd">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.fromfd">(select.kqueue method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromfile">fromfile() (array.array method)</a>
</li>
      <li><a href="library/stdtypes.html#float.fromhex">fromhex() (float method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.fromkeys">fromkeys() (collections.Counter method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.fromkeys">(dict method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromlist">fromlist() (array.array method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.fromordinal">fromordinal() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.fromordinal">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromstring">fromstring() (array.array method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstring">(in module xml.etree.ElementTree)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstringlist">fromstringlist() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.fromtarfile">fromtarfile() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.fromtimestamp">fromtimestamp() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.fromtimestamp">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromunicode">fromunicode() (array.array method)</a>
</li>
      <li><a href="library/datetime.html#datetime.tzinfo.fromutc">fromutc() (datetime.tzinfo method)</a>
</li>
      <li>
    frozenset

      <ul>
        <li><a href="c-api/set.html#index-0">object</a>, <a href="reference/datamodel.html#index-31">[1]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset">frozenset (built-in class)</a>
</li>
      <li><a href="library/os.html#os.fstat">fstat() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fstatvfs">fstatvfs() (in module os)</a>
</li>
      <li><a href="library/math.html#math.fsum">fsum() (in module math)</a>
</li>
      <li><a href="library/os.html#os.fsync">fsync() (in module os)</a>
</li>
      <li><a href="library/urllib.html#index-10">FTP</a>

      <ul>
        <li><a href="library/ftplib.html#index-0">ftplib (standard module)</a>
</li>
        <li><a href="library/ftplib.html#index-0">protocol</a>, <a href="library/urllib.html#index-8">[1]</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP">FTP (class in ftplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FTPHandler.ftp_open">ftp_open() (urllib2.FTPHandler method)</a>
</li>
      <li><a href="library/urllib.html#index-3">ftp_proxy</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS">FTP_TLS (class in ftplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FTPHandler">FTPHandler (class in urllib2)</a>
</li>
      <li><a href="library/ftplib.html#module-ftplib">ftplib (module)</a>
</li>
      <li><a href="library/ftplib.html#index-3">ftpmirror.py</a>
</li>
      <li><a href="library/os.html#os.ftruncate">ftruncate() (in module os)</a>
</li>
      <li><a href="library/queue.html#Queue.Full">Full</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.full">full() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.full">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/functools.html#functools.partial.func">func (functools.partial attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_closure (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_code (function attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-40">(function object attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-37">func_defaults (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_dict (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_doc (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_globals (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_name (function attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-funcattrs">funcattrs (2to3 fixer)</a>
</li>
      <li><a href="glossary.html#term-function"><strong>function</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-75">anonymous</a>
</li>
        <li><a href="reference/datamodel.html#index-35">argument</a>
</li>
        <li><a href="reference/datamodel.html#index-35">call</a>, <a href="reference/expressions.html#index-42">[1]</a>, <a href="reference/expressions.html#index-43">[2]</a>
</li>
        <li><a href="reference/expressions.html#index-42">call, user-defined</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">definition</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-22">generator</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">name</a>
</li>
        <li><a href="c-api/function.html#index-0">object</a>, <a href="reference/compound_stmts.html#index-18">[1]</a>, <a href="reference/datamodel.html#index-36">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-42">[4]</a>, <a href="reference/expressions.html#index-43">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-36">user-defined</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Function">Function (class in symtable)</a>
</li>
      <li><a href="library/new.html#new.function">function() (in module new)</a>
</li>
      <li><a href="library/unittest.html#unittest.FunctionTestCase">FunctionTestCase (class in unittest)</a>
</li>
      <li><a href="library/types.html#types.FunctionType">FunctionType (in module types)</a>
</li>
      <li><a href="library/functools.html#module-functools">functools (module)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.funny_files">funny_files (filecmp.dircmp attribute)</a>
</li>
      <li>
    future

      <ul>
        <li><a href="reference/simple_stmts.html#index-52">statement</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-future">future (2to3 fixer)</a>
</li>
      <li><a href="library/future_builtins.html#module-future_builtins">future_builtins (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.FutureWarning">FutureWarning</a>
</li>
  </ul></td>
</tr></table>

<h2 id="G">G</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/aifc.html#index-1">G.722</a>
</li>
      <li><a href="library/socket.html#socket.gaierror">gaierror</a>
</li>
      <li><a href="library/math.html#math.gamma">gamma() (in module math)</a>
</li>
      <li><a href="library/random.html#random.gammavariate">gammavariate() (in module random)</a>
</li>
      <li><a href="library/gc.html#gc.garbage">garbage (in module gc)</a>
</li>
      <li><a href="reference/datamodel.html#index-2">garbage collection</a>, <a href="glossary.html#term-garbage-collection"><strong>[1]</strong></a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.gather">gather() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/random.html#random.gauss">gauss() (in module random)</a>
</li>
      <li><a href="library/gc.html#module-gc">gc (module)</a>
</li>
      <li><a href="library/fractions.html#fractions.gcd">gcd() (in module fractions)</a>
</li>
      <li>
    gdbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/shelve.html#index-1">[1]</a>, <a href="reference/datamodel.html#index-34">[2]</a>
</li>
      </ul></li>
      <li><a href="library/gdbm.html#module-gdbm">gdbm (module)</a>
</li>
      <li><a href="library/operator.html#operator.ge">ge() (in module operator)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.gen_lib_options">gen_lib_options() (in module distutils.ccompiler)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.gen_preprocess_options">gen_preprocess_options() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/msilib.html#msilib.gen_uuid">gen_uuid() (in module msilib)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.generate_help">generate_help() (distutils.fancy_getopt.FancyGetopt method)</a>
</li>
      <li><a href="library/tokenize.html#tokenize.generate_tokens">generate_tokens() (in module tokenize)</a>
</li>
      <li><a href="glossary.html#index-3">generator</a>, <a href="glossary.html#term-generator"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-15">expression</a>
</li>
        <li><a href="reference/datamodel.html#index-43">function</a>, <a href="reference/expressions.html#index-22">[1]</a>, <a href="reference/simple_stmts.html#index-28">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-43">iterator</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-62">object</a>, <a href="reference/expressions.html#index-15">[1]</a>, <a href="reference/expressions.html#index-24">[2]</a>
</li>
      </ul></li>
      <li><a href="library/email.generator.html#email.generator.Generator">Generator (class in email.generator)</a>
</li>
      <li><a href="glossary.html#index-4">generator expression</a>, <a href="glossary.html#term-generator-expression"><strong>[1]</strong></a>
</li>
      <li><a href="library/exceptions.html#exceptions.GeneratorExit">GeneratorExit</a>

      <ul>
        <li><a href="reference/expressions.html#index-26">exception</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.GeneratorType">GeneratorType (in module types)</a>
</li>
      <li>
    generic

      <ul>
        <li><a href="reference/datamodel.html#index-5">special attribute</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.NodeVisitor.generic_visit">generic_visit() (ast.NodeVisitor method)</a>
</li>
      <li><a href="library/pickletools.html#pickletools.genops">genops() (in module pickletools)</a>
</li>
      <li><a href="library/gensuitemodule.html#module-gensuitemodule">gensuitemodule (module)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser.get">get() (ConfigParser.ConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.get">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/queue.html#Queue.Queue.get">(Queue.Queue method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.get">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.get">(email.message.Message method)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.get">(in module webbrowser)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.get">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.get">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.get">(multiprocessing.multiprocessing.queues.SimpleQueue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.get">(multiprocessing.pool.AsyncResult method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.get">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.Message.get">(rfc822.Message method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Combobox.get">(ttk.Combobox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_all">get_all() (email.message.Message method)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.headers.Headers.get_all">(wsgiref.headers.Headers method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.get_all_breaks">get_all_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer.get_app">get_app() (wsgiref.simple_server.WSGIServer method)</a>
</li>
      <li><a href="library/shutil.html#shutil.get_archive_formats">get_archive_formats() (in module shutil)</a>
</li>
      <li><a href="library/readline.html#readline.get_begidx">get_begidx() (in module readline)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.get_body_encoding">get_body_encoding() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_boundary">get_boundary() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_break">get_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_breaks">get_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.get_buffer">get_buffer() (xdrlib.Packer method)</a>

      <ul>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.get_buffer">(xdrlib.Unpacker method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.get_ca_certs">get_ca_certs() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.get_channel_binding">get_channel_binding() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_charset">get_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_charsets">get_charsets() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_children">get_children() (symtable.SymbolTable method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.get_children">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.get_close_matches">get_close_matches() (in module difflib)</a>
</li>
      <li><a href="library/imputil.html#imputil.BuiltinImporter.get_code">get_code() (imputil.BuiltinImporter method)</a>

      <ul>
        <li><a href="library/imputil.html#imputil.Importer.get_code">(imputil.Importer method)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_code">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.get_completer">get_completer() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_completer_delims">get_completer_delims() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_completion_type">get_completion_type() (in module readline)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_h_filename">get_config_h_filename() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_h_filename">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_var">get_config_var() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_var">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_vars">get_config_vars() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_vars">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_content_charset">get_content_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_maintype">get_content_maintype() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_subtype">get_content_subtype() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_type">get_content_type() (email.message.Message method)</a>
</li>
      <li><a href="library/gc.html#gc.get_count">get_count() (in module gc)</a>
</li>
      <li><a href="library/readline.html#readline.get_current_history_length">get_current_history_length() (in module readline)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_data">get_data() (in module pkgutil)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.get_data">(urllib2.Request method)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_data">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_date">get_date() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/gc.html#gc.get_debug">get_debug() (in module gc)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.get_default">get_default() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.get_default_compiler">get_default_compiler() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/nis.html#nis.get_default_domain">get_default_domain() (in module nis)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_default_type">get_default_type() (email.message.Message method)</a>
</li>
      <li><a href="library/ssl.html#ssl.get_default_verify_paths">get_default_verify_paths() (in module ssl)</a>
</li>
      <li><a href="library/csv.html#csv.get_dialect">get_dialect() (in module csv)</a>
</li>
      <li><a href="library/fl.html#fl.get_directory">get_directory() (in module fl)</a>
</li>
      <li><a href="library/ast.html#ast.get_docstring">get_docstring() (in module ast)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.get_doctest">get_doctest() (doctest.DocTestParser method)</a>
</li>
      <li><a href="library/readline.html#readline.get_endidx">get_endidx() (in module readline)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.get_environ">get_environ() (wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.get_errno">get_errno() (in module ctypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.get_examples">get_examples() (doctest.DocTestParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.get_field">get_field() (string.Formatter method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.get_file">get_file() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.get_file">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.get_file">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.get_file">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.get_file">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.get_file">(mailbox.mbox method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.get_file_breaks">get_file_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_filename">get_filename() (email.message.Message method)</a>

      <ul>
        <li><a href="library/fl.html#fl.get_filename">(in module fl)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_filename">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_flags">get_flags() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.get_flags">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.get_flags">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Maildir.get_folder">get_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.get_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Function.get_frees">get_frees() (symtable.Function method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage.get_from">get_from() (mailbox.mboxMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.get_from">(mailbox.MMDFMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.Request.get_full_url">get_full_url() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_globals">get_globals() (symtable.Function method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_grouped_opcodes">get_grouped_opcodes() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_header">get_header() (urllib2.Request method)</a>
</li>
      <li><a href="library/readline.html#readline.get_history_item">get_history_item() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_history_length">get_history_length() (in module readline)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_host">get_host() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_id">get_id() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/thread.html#thread.get_ident">get_ident() (in module thread)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_identifiers">get_identifiers() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_importer">get_importer() (in module pkgutil)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_info">get_info() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/dis.html#opcode-GET_ITER">GET_ITER (opcode)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.get_labels">get_labels() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.BabylMessage.get_labels">(mailbox.BabylMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.get_last_error">get_last_error() (in module ctypes)</a>
</li>
      <li><a href="library/readline.html#readline.get_line_buffer">get_line_buffer() (in module readline)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_lineno">get_lineno() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_loader">get_loader() (in module pkgutil)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_locals">get_locals() (symtable.Function method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.get_logger">get_logger() (in module multiprocessing)</a>
</li>
      <li><a href="library/imp.html#imp.get_magic">get_magic() (in module imp)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_makefile_filename">get_makefile_filename() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_makefile_filename">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_matching_blocks">get_matching_blocks() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Mailbox.get_message">get_message() (mailbox.Mailbox method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_method">get_method() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Class.get_methods">get_methods() (symtable.Class method)</a>
</li>
      <li><a href="library/fl.html#fl.get_mouse">get_mouse() (in module fl)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.get_name">get_name() (symtable.Symbol method)</a>

      <ul>
        <li><a href="library/symtable.html#symtable.SymbolTable.get_name">(symtable.SymbolTable method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.get_namespace">get_namespace() (symtable.Symbol method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.get_namespaces">get_namespaces() (symtable.Symbol method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.get_nonstandard_attr">get_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.get_nowait">get_nowait() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.get_nowait">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/gc.html#gc.get_objects">get_objects() (in module gc)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_opcodes">get_opcodes() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_option">get_option() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_option_group">get_option_group() (optparse.OptionParser method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.get_option_order">get_option_order() (distutils.fancy_getopt.FancyGetopt method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_origin_req_host">get_origin_req_host() (urllib2.Request method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.get_osfhandle">get_osfhandle() (in module msvcrt)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.get_output_charset">get_output_charset() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_param">get_param() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_parameters">get_parameters() (symtable.Function method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_params">get_params() (email.message.Message method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_path">get_path() (in module sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_path_names">get_path_names() (in module sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_paths">get_paths() (in module sysconfig)</a>
</li>
      <li><a href="library/fl.html#fl.get_pattern">get_pattern() (in module fl)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_payload">get_payload() (email.message.Message method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.get_platform">get_platform() (in module distutils.util)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_platform">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.get_poly">get_poly() (in module turtle)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.get_position">get_position() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_python_inc">get_python_inc() (in module distutils.sysconfig)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_python_lib">get_python_lib() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_python_version">get_python_version() (in module sysconfig)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.get_recsrc">get_recsrc() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/gc.html#gc.get_referents">get_referents() (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.get_referrers">get_referrers() (in module gc)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.get_request">get_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/fl.html#fl.get_rgbmode">get_rgbmode() (in module fl)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_scheme">get_scheme() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_scheme_names">get_scheme_names() (in module sysconfig)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_selector">get_selector() (urllib2.Request method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH.get_sequences">get_sequences() (mailbox.MH method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MHMessage.get_sequences">(mailbox.MHMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.get_server">get_server() (multiprocessing.managers.BaseManager method)</a>
</li>
      <li><a href="library/ssl.html#ssl.get_server_certificate">get_server_certificate() (in module ssl)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.get_socket">get_socket() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.get_source">get_source() (zipimport.zipimporter method)</a>
</li>
      <li><a href="distutils/builtdist.html#get_special_folder_path">get_special_folder_path() (built-in function)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_stack">get_stack() (bdb.Bdb method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.get_starttag_text">get_starttag_text() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.get_starttag_text">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_stderr">get_stderr() (wsgiref.handlers.BaseHandler method)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.get_stderr">(wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_stdin">get_stdin() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Mailbox.get_string">get_string() (mailbox.Mailbox method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_subdir">get_subdir() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/imp.html#imp.get_suffixes">get_suffixes() (in module imp)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_symbols">get_symbols() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.get_terminator">get_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/gc.html#gc.get_threshold">get_threshold() (in module gc)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.get_token">get_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_type">get_type() (symtable.SymbolTable method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.get_type">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_unixfrom">get_unixfrom() (email.message.Message method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_usage">get_usage() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.get_value">get_value() (string.Formatter method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_version">get_version() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.get_visible">get_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.getabouttext">getabouttext() (FrameWork.Application method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getacl">getacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getaddr">getaddr() (rfc822.Message method)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.getaddresses">getaddresses() (in module email.utils)</a>
</li>
      <li><a href="library/socket.html#socket.getaddrinfo">getaddrinfo() (in module socket)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getaddrlist">getaddrlist() (rfc822.Message method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getallmatchingheaders">getallmatchingheaders() (rfc822.Message method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getannotation">getannotation() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getargspec">getargspec() (in module inspect)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.GetArgv">GetArgv() (in module EasyDialogs)</a>
</li>
      <li><a href="library/inspect.html#inspect.getargvalues">getargvalues() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.getatime">getatime() (in module os.path)</a>
</li>
      <li><a href="library/functions.html#getattr">getattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttribute">getAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNode">getAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNodeNS">getAttributeNodeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNS">getAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.GetBase">GetBase() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/curses.html#curses.window.getbegyx">getbegyx() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.getbkgd">getbkgd() (curses.window method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getboolean">getboolean() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getByteStream">getByteStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getcallargs">getcallargs() (in module inspect)</a>
</li>
      <li><a href="library/turtle.html#turtle.getcanvas">getcanvas() (in module turtle)</a>
</li>
      <li><a href="library/mailcap.html#mailcap.getcaps">getcaps() (in module mailcap)</a>
</li>
      <li><a href="library/curses.html#curses.window.getch">getch() (curses.window method)</a>

      <ul>
        <li><a href="library/msvcrt.html#msvcrt.getch">(in module msvcrt)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getCharacterStream">getCharacterStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getche">getche() (in module msvcrt)</a>
</li>
      <li><a href="library/sys.html#sys.getcheckinterval">getcheckinterval() (in module sys)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.getChild">getChild() (logging.Logger method)</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node.getChildNodes">getChildNodes() (compiler.ast.Node method)</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node.getChildren">getChildren() (compiler.ast.Node method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren">getchildren() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getclasstree">getclasstree() (in module inspect)</a>
</li>
      <li><a href="library/colorpicker.html#ColorPicker.GetColor">GetColor() (in module ColorPicker)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.GetColumnInfo">GetColumnInfo() (msilib.View method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getColumnNumber">getColumnNumber() (xml.sax.xmlreader.Locator method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getcomments">getcomments() (in module inspect)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getcompname">getcompname() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getcompname">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getcompname">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getcomptype">getcomptype() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getcomptype">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getcomptype">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getContentHandler">getContentHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/decimal.html#decimal.getcontext">getcontext() (in module decimal)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.getcontext">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.GetCreatorAndType">GetCreatorAndType() (in module MacOS)</a>
</li>
      <li><a href="library/os.path.html#os.path.getctime">getctime() (in module os.path)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getcurrent">getcurrent() (mhlib.Folder method)</a>
</li>
      <li><a href="library/os.html#os.getcwd">getcwd() (in module os)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-getcwdu">getcwdu (2to3 fixer)</a>
</li>
      <li><a href="library/os.html#os.getcwdu">getcwdu() (in module os)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getdate">getdate() (rfc822.Message method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getdate_tz">getdate_tz() (rfc822.Message method)</a>
</li>
      <li><a href="library/codecs.html#codecs.getdecoder">getdecoder() (in module codecs)</a>
</li>
      <li><a href="library/sys.html#sys.getdefaultencoding">getdefaultencoding() (in module sys)</a>
</li>
      <li><a href="library/locale.html#locale.getdefaultlocale">getdefaultlocale() (in module locale)</a>
</li>
      <li><a href="library/socket.html#socket.getdefaulttimeout">getdefaulttimeout() (in module socket)</a>
</li>
      <li><a href="library/sys.html#sys.getdlopenflags">getdlopenflags() (in module sys)</a>
</li>
      <li><a href="library/inspect.html#inspect.getdoc">getdoc() (in module inspect)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.getDOMImplementation">getDOMImplementation() (in module xml.dom)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getDTDHandler">getDTDHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.getEffectiveLevel">getEffectiveLevel() (logging.Logger method)</a>
</li>
      <li><a href="library/os.html#os.getegid">getegid() (in module os)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.getElementsByTagName">getElementsByTagName() (xml.dom.Document method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Element.getElementsByTagName">(xml.dom.Element method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/xml.dom.html#xml.dom.Document.getElementsByTagNameNS">getElementsByTagNameNS() (xml.dom.Document method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Element.getElementsByTagNameNS">(xml.dom.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.getencoder">getencoder() (in module codecs)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getencoding">getencoding() (mimetools.Message method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getEncoding">getEncoding() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getEntityResolver">getEntityResolver() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.getenv">getenv() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getErrorHandler">getErrorHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/macos.html#MacOS.GetErrorString">GetErrorString() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.geteuid">geteuid() (in module os)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.getEvent">getEvent() (xml.dom.pulldom.DOMEventStream method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getEventCategory">getEventCategory() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getEventType">getEventType() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXException.getException">getException() (xml.sax.SAXException method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getFeature">getFeature() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetFieldCount">GetFieldCount() (msilib.Record method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getfile">getfile() (in module inspect)</a>
</li>
      <li><a href="library/sys.html#sys.getfilesystemencoding">getfilesystemencoding() (in module sys)</a>
</li>
      <li><a href="library/cgi.html#cgi.FieldStorage.getfirst">getfirst() (cgi.FieldStorage method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getfirstmatchingheader">getfirstmatchingheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getfloat">getfloat() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.getfmts">getfmts() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/socket.html#socket.getfqdn">getfqdn() (in module socket)</a>
</li>
      <li><a href="library/inspect.html#inspect.getframeinfo">getframeinfo() (in module inspect)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getframerate">getframerate() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getframerate">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getframerate">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.getfullname">getfullname() (mhlib.Folder method)</a>
</li>
      <li><a href="library/os.html#os.getgid">getgid() (in module os)</a>
</li>
      <li><a href="library/grp.html#grp.getgrall">getgrall() (in module grp)</a>
</li>
      <li><a href="library/grp.html#grp.getgrgid">getgrgid() (in module grp)</a>
</li>
      <li><a href="library/grp.html#grp.getgrnam">getgrnam() (in module grp)</a>
</li>
      <li><a href="library/os.html#os.getgroups">getgroups() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.getheader">getheader() (httplib.HTTPResponse method)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.Message.getheader">(rfc822.Message method)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.getheaders">getheaders() (httplib.HTTPResponse method)</a>
</li>
      <li><a href="library/os.html#index-9">gethostbyaddr() (in module socket)</a>, <a href="library/socket.html#socket.gethostbyaddr">[1]</a>
</li>
      <li><a href="library/socket.html#socket.gethostbyname">gethostbyname() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.gethostbyname_ex">gethostbyname_ex() (in module socket)</a>
</li>
      <li><a href="library/os.html#index-9">gethostname() (in module socket)</a>, <a href="library/socket.html#socket.gethostname">[1]</a>
</li>
      <li><a href="library/codecs.html#codecs.getincrementaldecoder">getincrementaldecoder() (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.getincrementalencoder">getincrementalencoder() (in module codecs)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.getinfo">getinfo() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getinnerframes">getinnerframes() (in module inspect)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.GetInputContext">GetInputContext() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getint">getint() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetInteger">GetInteger() (msilib.Record method)</a>
</li>
      <li><a href="library/operator.html#operator.getitem">getitem() (in module operator)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator">getiterator() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.getiterator">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/signal.html#signal.getitimer">getitimer() (in module signal)</a>
</li>
      <li><a href="library/curses.html#curses.window.getkey">getkey() (curses.window method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getlast">getlast() (mhlib.Folder method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.GetLastError">GetLastError() (in module ctypes)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getLength">getLength() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/logging.html#logging.getLevelName">getLevelName() (in module logging)</a>
</li>
      <li><a href="library/linecache.html#linecache.getline">getline() (in module linecache)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getLineNumber">getLineNumber() (xml.sax.xmlreader.Locator method)</a>
</li>
      <li><a href="library/cgi.html#cgi.FieldStorage.getlist">getlist() (cgi.FieldStorage method)</a>
</li>
      <li><a href="library/os.html#os.getloadavg">getloadavg() (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.getlocale">getlocale() (in module locale)</a>
</li>
      <li><a href="library/logging.html#logging.getLogger">getLogger() (in module logging)</a>
</li>
      <li><a href="library/logging.html#logging.getLoggerClass">getLoggerClass() (in module logging)</a>
</li>
      <li><a href="library/os.html#os.getlogin">getlogin() (in module os)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getmaintype">getmaintype() (mimetools.Message method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getmark">getmark() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getmark">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getmark">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getmarkers">getmarkers() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getmarkers">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getmarkers">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.getmaxyx">getmaxyx() (curses.window method)</a>
</li>
      <li><a href="library/fl.html#fl.getmcolor">getmcolor() (in module fl)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.getmember">getmember() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmembers">getmembers() (in module inspect)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarFile.getmembers">(tarfile.TarFile method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.LogRecord.getMessage">getMessage() (logging.LogRecord method)</a>

      <ul>
        <li><a href="library/xml.sax.html#xml.sax.SAXException.getMessage">(xml.sax.SAXException method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.getmessagefilename">getmessagefilename() (mhlib.Folder method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getMessageID">getMessageID() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmodule">getmodule() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmoduleinfo">getmoduleinfo() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmodulename">getmodulename() (in module inspect)</a>
</li>
      <li><a href="library/curses.html#curses.getmouse">getmouse() (in module curses)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmro">getmro() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.getmtime">getmtime() (in module os.path)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.getname">getname() (chunk.Chunk method)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.getName">getName() (threading.Thread method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getNameByQName">getNameByQName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/socket.html#socket.getnameinfo">getnameinfo() (in module socket)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.getnames">getnames() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getNames">getNames() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getnchannels">getnchannels() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getnchannels">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getnchannels">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getnframes">getnframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getnframes">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getnframes">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#index-1">getnode</a>
</li>
      <li><a href="library/uuid.html#uuid.getnode">getnode() (in module uuid)</a>
</li>
      <li><a href="library/getopt.html#module-getopt">getopt (module)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.getopt">getopt() (distutils.fancy_getopt.FancyGetopt method)</a>

      <ul>
        <li><a href="library/getopt.html#getopt.getopt">(in module getopt)</a>
</li>
      </ul></li>
      <li><a href="library/getopt.html#getopt.GetoptError">GetoptError</a>
</li>
      <li><a href="library/inspect.html#inspect.getouterframes">getouterframes() (in module inspect)</a>
</li>
      <li><a href="library/commands.html#commands.getoutput">getoutput() (in module commands)</a>
</li>
      <li><a href="library/resource.html#resource.getpagesize">getpagesize() (in module resource)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getparam">getparam() (mimetools.Message method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getparams">getparams() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/al.html#al.getparams">(in module al)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.getparams">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getparams">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.getparyx">getparyx() (curses.window method)</a>
</li>
      <li><a href="library/getpass.html#module-getpass">getpass (module)</a>
</li>
      <li><a href="library/getpass.html#getpass.getpass">getpass() (in module getpass)</a>
</li>
      <li><a href="library/getpass.html#getpass.GetPassWarning">GetPassWarning</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.getpath">getpath() (mhlib.MH method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.getpeercert">getpeercert() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getpeername">getpeername() (socket.socket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.getpen">getpen() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.getpgid">getpgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.getpgrp">getpgrp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.getpid">getpid() (in module os)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getplist">getplist() (mimetools.Message method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.getpos">getpos() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/os.html#os.getppid">getppid() (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.getpreferredencoding">getpreferredencoding() (in module locale)</a>
</li>
      <li><a href="library/sys.html#sys.getprofile">getprofile() (in module sys)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.getprofile">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.GetProperty">GetProperty() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getProperty">getProperty() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.GetPropertyCount">GetPropertyCount() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/socket.html#socket.getprotobyname">getprotobyname() (in module socket)</a>
</li>
      <li><a href="library/urllib.html#urllib.getproxies">getproxies() (in module urllib)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getPublicId">getPublicId() (xml.sax.xmlreader.InputSource method)</a>

      <ul>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getPublicId">(xml.sax.xmlreader.Locator method)</a>
</li>
      </ul></li>
      <li><a href="library/pwd.html#pwd.getpwall">getpwall() (in module pwd)</a>
</li>
      <li><a href="library/pwd.html#pwd.getpwnam">getpwnam() (in module pwd)</a>
</li>
      <li><a href="library/pwd.html#pwd.getpwuid">getpwuid() (in module pwd)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getQNameByName">getQNameByName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getQNames">getQNames() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getquota">getquota() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getquotaroot">getquotaroot() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/random.html#random.getrandbits">getrandbits() (in module random)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getrawheader">getrawheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/codecs.html#codecs.getreader">getreader() (in module codecs)</a>
</li>
      <li><a href="library/sys.html#sys.getrecursionlimit">getrecursionlimit() (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.getrefcount">getrefcount() (in module sys)</a>
</li>
      <li><a href="library/os.html#os.getresgid">getresgid() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.getresponse">getresponse() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/os.html#os.getresuid">getresuid() (in module os)</a>
</li>
      <li><a href="library/resource.html#resource.getrlimit">getrlimit() (in module resource)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.getroot">getroot() (xml.etree.ElementTree.ElementTree method)</a>
</li>
      <li><a href="library/resource.html#resource.getrusage">getrusage() (in module resource)</a>
</li>
      <li><a href="library/audioop.html#audioop.getsample">getsample() (in module audioop)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getsampwidth">getsampwidth() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getsampwidth">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getsampwidth">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.getscreen">getscreen() (in module turtle)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.getscrollbarvalues">getscrollbarvalues() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getsequences">getsequences() (mhlib.Folder method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getsequencesfilename">getsequencesfilename() (mhlib.Folder method)</a>
</li>
      <li><a href="library/socket.html#socket.getservbyname">getservbyname() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.getservbyport">getservbyport() (in module socket)</a>
</li>
      <li><a href="library/types.html#types.GetSetDescriptorType">GetSetDescriptorType (in module types)</a>
</li>
      <li><a href="library/turtle.html#turtle.getshapes">getshapes() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.getsid">getsid() (in module os)</a>
</li>
      <li><a href="library/signal.html#signal.getsignal">getsignal() (in module signal)</a>
</li>
      <li><a href="library/site.html#site.getsitepackages">getsitepackages() (in module site)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.getsize">getsize() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/os.path.html#os.path.getsize">(in module os.path)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.getsizeof">getsizeof() (in module sys)</a>
</li>
      <li><a href="library/imgfile.html#imgfile.getsizes">getsizes() (in module imgfile)</a>
</li>
      <li><a href="library/operator.html#operator.getslice">getslice() (in module operator)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getsockname">getsockname() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getsockopt">getsockopt() (socket.socket method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsource">getsource() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsourcefile">getsourcefile() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsourcelines">getsourcelines() (in module inspect)</a>
</li>
      <li><a href="library/spwd.html#spwd.getspall">getspall() (in module spwd)</a>
</li>
      <li><a href="library/spwd.html#spwd.getspnam">getspnam() (in module spwd)</a>
</li>
      <li><a href="library/random.html#random.getstate">getstate() (in module random)</a>
</li>
      <li><a href="library/commands.html#commands.getstatus">getstatus() (in module commands)</a>
</li>
      <li><a href="library/commands.html#commands.getstatusoutput">getstatusoutput() (in module commands)</a>
</li>
      <li><a href="library/curses.html#curses.window.getstr">getstr() (curses.window method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetString">GetString() (msilib.Record method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler.getSubject">getSubject() (logging.handlers.SMTPHandler method)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getsubtype">getsubtype() (mimetools.Message method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.GetSummaryInformation">GetSummaryInformation() (msilib.Database method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getSystemId">getSystemId() (xml.sax.xmlreader.InputSource method)</a>

      <ul>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getSystemId">(xml.sax.xmlreader.Locator method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.getsyx">getsyx() (in module curses)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.gettarinfo">gettarinfo() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.gettempdir">gettempdir() (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.gettempprefix">gettempprefix() (in module tempfile)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.getTestCaseNames">getTestCaseNames() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/gettext.html#module-gettext">gettext (module)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.gettext">gettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.gettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.gettext">(in module gettext)</a>
</li>
        <li><a href="library/locale.html#locale.gettext">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.GetTicks">GetTicks() (in module MacOS)</a>
</li>
      <li><a href="library/socket.html#socket.socket.gettimeout">gettimeout() (socket.socket method)</a>
</li>
      <li><a href="library/sys.html#sys.gettrace">gettrace() (in module sys)</a>
</li>
      <li><a href="library/turtle.html#turtle.getturtle">getturtle() (in module turtle)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.gettype">gettype() (mimetools.Message method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getType">getType() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/os.html#os.getuid">getuid() (in module os)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.ParseResult.geturl">geturl() (urlparse.ParseResult method)</a>
</li>
      <li><a href="library/getpass.html#getpass.getuser">getuser() (in module getpass)</a>
</li>
      <li><a href="library/site.html#site.getuserbase">getuserbase() (in module site)</a>
</li>
      <li><a href="library/site.html#site.getusersitepackages">getusersitepackages() (in module site)</a>
</li>
      <li><a href="library/io.html#io.BytesIO.getvalue">getvalue() (io.BytesIO method)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO.getvalue">(StringIO.StringIO method)</a>
</li>
        <li><a href="library/io.html#io.StringIO.getvalue">(io.StringIO method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getValue">getValue() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getValueByQName">getValueByQName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getwch">getwch() (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getwche">getwche() (in module msvcrt)</a>
</li>
      <li><a href="library/weakref.html#weakref.getweakrefcount">getweakrefcount() (in module weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.getweakrefs">getweakrefs() (in module weakref)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.getwelcome">getwelcome() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.getwelcome">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.getwelcome">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.getwin">getwin() (in module curses)</a>
</li>
      <li><a href="library/sys.html#sys.getwindowsversion">getwindowsversion() (in module sys)</a>
</li>
      <li><a href="library/codecs.html#codecs.getwriter">getwriter() (in module codecs)</a>
</li>
      <li><a href="library/curses.html#curses.window.getyx">getyx() (curses.window method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.gid">gid (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="c-api/init.html#index-13">GIL</a>, <a href="glossary.html#term-gil"><strong>[1]</strong></a>
</li>
      <li><a href="library/gl.html#module-GL">GL (module)</a>
</li>
      <li><a href="library/gl.html#module-gl">gl (module)</a>
</li>
      <li>
    glob

      <ul>
        <li><a href="library/fnmatch.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/glob.html#module-glob">glob (module)</a>
</li>
      <li><a href="library/glob.html#glob.glob">glob() (in module glob)</a>

      <ul>
        <li><a href="library/msilib.html#msilib.Directory.glob">(msilib.Directory method)</a>
</li>
      </ul></li>
      <li>
    global

      <ul>
        <li><a href="reference/simple_stmts.html#index-54">name binding</a>
</li>
        <li><a href="reference/datamodel.html#index-37">namespace</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">statement</a>, <a href="reference/simple_stmts.html#index-54">[1]</a>, <a href="reference/simple_stmts.html#index-7">[2]</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-13">global interpreter lock</a>, <a href="glossary.html#term-global-interpreter-lock"><strong>[1]</strong></a>
</li>
      <li>
    globals

      <ul>
        <li><a href="reference/simple_stmts.html#index-58">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#globals">globals() (built-in function)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTest.globs">globs (doctest.DocTest attribute)</a>
</li>
      <li><a href="library/time.html#time.gmtime">gmtime() (in module time)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.gname">gname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/gettext.html#index-9">GNOME</a>
</li>
      <li><a href="library/tarfile.html#tarfile.GNU_FORMAT">GNU_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/getopt.html#getopt.gnu_getopt">gnu_getopt() (in module getopt)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.got">got (doctest.DocTestFailure attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.goto">goto() (in module turtle)</a>
</li>
      <li><a href="reference/introduction.html#index-0">grammar</a>
</li>
      <li><a href="library/tk.html#index-0">Graphical User Interface</a>
</li>
      <li><a href="library/token.html#token.GREATER">GREATER (in module token)</a>
</li>
      <li><a href="library/token.html#token.GREATEREQUAL">GREATEREQUAL (in module token)</a>
</li>
      <li><a href="library/time.html#index-5">Greenwich Mean Time</a>
</li>
      <li><a href="library/imageop.html#imageop.grey22grey">grey22grey() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2grey2">grey2grey2() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2grey4">grey2grey4() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2mono">grey2mono() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey42grey">grey42grey() (in module imageop)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.group">group() (nntplib.NNTP method)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.group">(re.MatchObject method)</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.groupby">groupby() (in module itertools)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.groupdict">groupdict() (re.MatchObject method)</a>
</li>
      <li><a href="library/re.html#re.RegexObject.groupindex">groupindex (re.RegexObject attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">grouping</a>
</li>
      <li><a href="library/re.html#re.RegexObject.groups">groups (re.RegexObject attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.groups">groups() (re.MatchObject method)</a>
</li>
      <li><a href="library/grp.html#module-grp">grp (module)</a>
</li>
      <li><a href="library/operator.html#operator.gt">gt() (in module operator)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.guess_all_extensions">guess_all_extensions() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_all_extensions">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.guess_extension">guess_extension() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_extension">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.guess_scheme">guess_scheme() (in module wsgiref.util)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.guess_type">guess_type() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_type">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/tk.html#index-0">GUI</a>
</li>
      <li><a href="library/gzip.html#module-gzip">gzip (module)</a>
</li>
      <li><a href="library/gzip.html#gzip.GzipFile">GzipFile (class in gzip)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="H">H</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/curses.html#curses.halfdelay">halfdelay() (in module curses)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">handle an exception</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.handle">handle() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.handle">(SocketServer.BaseRequestHandler method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.handle">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.handle">(logging.Logger method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.NullHandler.handle">(logging.NullHandler method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.handle">(wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_accept">handle_accept() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_charref">handle_charref() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_charref">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_close">handle_close() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_comment">handle_comment() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_comment">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_connect">handle_connect() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_data">handle_data() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_data">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_decl">handle_decl() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_decl">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_endtag">handle_endtag() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_endtag">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_entityref">handle_entityref() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_entityref">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_error">handle_error() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_error">(SocketServer.BaseServer method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_expt">handle_expt() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.handle_image">handle_image() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request">handle_one_request() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_pi">handle_pi() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_read">handle_read() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.handle_request">handle_request() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_request">(SocketServer.BaseServer method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_startendtag">handle_startendtag() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_starttag">handle_starttag() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_starttag">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_timeout">handle_timeout() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_write">handle_write() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.handleError">handleError() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.handleError">(logging.handlers.SocketHandler method)</a>
</li>
      </ul></li>
      <li>
    handler

      <ul>
        <li><a href="reference/datamodel.html#index-67">exception</a>
</li>
      </ul></li>
      <li><a href="library/cgitb.html#cgitb.handler">handler() (in module cgitb)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_ALPN">HAS_ALPN (in module ssl)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_children">has_children() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/curses.html#curses.has_colors">has_colors() (in module curses)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.has_data">has_data() (urllib2.Request method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_ECDH">HAS_ECDH (in module ssl)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_exec">has_exec() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.has_extn">has_extn() (smtplib.SMTP method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.has_function">has_function() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer.has_header">has_header() (csv.Sniffer method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.has_header">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.has_ic">has_ic() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.has_il">has_il() (in module curses)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_import_star">has_import_star() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/socket.html#socket.has_ipv6">has_ipv6 (in module socket)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-has_key">has_key (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.has_key">has_key() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.has_key">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.has_key">(email.message.Message method)</a>
</li>
        <li><a href="library/curses.html#curses.has_key">(in module curses)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.has_key">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.has_nonstandard_attr">has_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_NPN">HAS_NPN (in module ssl)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.has_option">has_option() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.has_option">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.has_section">has_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_SNI">HAS_SNI (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_TLSv1_3">HAS_TLSv1_3 (in module ssl)</a>
</li>
      <li><a href="library/functions.html#hasattr">hasattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.hasAttribute">hasAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.hasAttributeNS">hasAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.hasAttributes">hasAttributes() (xml.dom.Node method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.hasChildNodes">hasChildNodes() (xml.dom.Node method)</a>
</li>
      <li><a href="library/dis.html#dis.hascompare">hascompare (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasconst">hasconst (in module dis)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.hasFeature">hasFeature() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/dis.html#dis.hasfree">hasfree (in module dis)</a>
</li>
      <li>
    hash

      <ul>
        <li><a href="c-api/object.html#index-9">built-in function</a>, <a href="c-api/typeobj.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-81">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-3">hash character</a>
</li>
      <li><a href="library/functions.html#hash">hash() (built-in function)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.block_size">hash.block_size (in module hashlib)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.digest_size">hash.digest_size (in module hashlib)</a>
</li>
      <li><a href="reference/expressions.html#index-17">hashable</a>, <a href="glossary.html#term-hashable"><strong>[1]</strong></a>
</li>
      <li><a href="library/collections.html#collections.Hashable">Hashable (class in collections)</a>
</li>
      <li><a href="library/hashlib.html#module-hashlib">hashlib (module)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hashlib.algorithms">hashlib.algorithms (in module hashlib)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.hashopen">hashopen() (in module bsddb)</a>
</li>
      <li><a href="library/dis.html#dis.hasjabs">hasjabs (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasjrel">hasjrel (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.haslocal">haslocal (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasname">hasname (in module dis)</a>
</li>
      <li><a href="library/dis.html#opcode-HAVE_ARGUMENT">HAVE_ARGUMENT (opcode)</a>
</li>
      <li><a href="library/test.html#test.support.have_unicode">have_unicode (in module test.support)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.head">head() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/email.header.html#email.header.Header">Header (class in email.header)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.header_encode">header_encode() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.header_encoding">header_encoding (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.header_items">header_items() (urllib2.Request method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.header_offset">header_offset (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.HeaderError">HeaderError</a>
</li>
      <li><a href="library/email.errors.html#email.errors.HeaderParseError">HeaderParseError</a>
</li>
      <li>
    headers

      <ul>
        <li><a href="library/cgi.html#index-0">MIME</a>, <a href="library/mimetypes.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.headers">headers (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.headers.Headers">Headers (class in wsgiref.headers)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.headers">headers (rfc822.Message attribute)</a>

      <ul>
        <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.headers">(xmlrpclib.ProtocolError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.heading">heading() (in module turtle)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.heading">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/heapq.html#heapq.heapify">heapify() (in module heapq)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.heapmin">heapmin() (in module msvcrt)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappop">heappop() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappush">heappush() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappushpop">heappushpop() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#module-heapq">heapq (module)</a>
</li>
      <li><a href="library/heapq.html#heapq.heapreplace">heapreplace() (in module heapq)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.helo">helo() (smtplib.SMTP method)</a>
</li>
      <li>
    help

      <ul>
        <li><a href="tutorial/stdlib.html#index-0">built-in function</a>
</li>
        <li><a href="library/pydoc.html#index-0">online</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/optparse.html#optparse.Option.help">help (optparse.Option attribute)</a>
</li>
      <li><a href="library/functions.html#help">help() (built-in function)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.help">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.herror">herror</a>
</li>
      <li>
    hex

      <ul>
        <li><a href="reference/datamodel.html#index-95">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.hex">hex (uuid.UUID attribute)</a>
</li>
      <li><a href="library/functions.html#hex">hex() (built-in function)</a>

      <ul>
        <li><a href="library/stdtypes.html#float.hex">(float method)</a>
</li>
        <li><a href="library/future_builtins.html#future_builtins.hex">(in module future_builtins)</a>
</li>
      </ul></li>
      <li>
    hexadecimal

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">hexadecimal literal</a>
</li>
      <li><a href="library/binhex.html#binhex.hexbin">hexbin() (in module binhex)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.hexdigest">hexdigest() (hashlib.hash method)</a>

      <ul>
        <li><a href="library/hmac.html#hmac.HMAC.hexdigest">(hmac.HMAC method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.hexdigest">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.hexdigest">(sha.sha method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.hexdigits">hexdigits (in module string)</a>
</li>
      <li><a href="library/binascii.html#binascii.hexlify">hexlify() (in module binascii)</a>
</li>
      <li><a href="library/sys.html#sys.hexversion">hexversion (in module sys)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.hidden">hidden() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.hide">hide() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Notebook.hide">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.hide_cookie2">hide_cookie2 (cookielib.CookiePolicy attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.hide_form">hide_form() (fl.form method)</a>
</li>
      <li><a href="library/turtle.html#turtle.hideturtle">hideturtle() (in module turtle)</a>
</li>
      <li>
    hierarchy

      <ul>
        <li><a href="reference/datamodel.html#index-4">type</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.HierarchyRequestErr">HierarchyRequestErr</a>
</li>
      <li><a href="library/pickle.html#pickle.HIGHEST_PROTOCOL">HIGHEST_PROTOCOL (in module pickle)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CLASSES_ROOT">HKEY_CLASSES_ROOT (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CURRENT_CONFIG">HKEY_CURRENT_CONFIG (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CURRENT_USER">HKEY_CURRENT_USER (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_DYN_DATA">HKEY_DYN_DATA (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_LOCAL_MACHINE">HKEY_LOCAL_MACHINE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_PERFORMANCE_DATA">HKEY_PERFORMANCE_DATA (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_USERS">HKEY_USERS (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.window.hline">hline() (curses.window method)</a>
</li>
      <li><a href="library/tix.html#Tix.HList">HList (class in Tix)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.hls_to_rgb">hls_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/hmac.html#module-hmac">hmac (module)</a>
</li>
      <li><a href="distutils/apiref.html#index-1">HOME</a>, <a href="install/index.html#index-4">[1]</a>, <a href="install/index.html#index-5">[2]</a>, <a href="library/os.path.html#index-2">[3]</a>, <a href="library/os.path.html#index-3">[4]</a>, <a href="library/user.html#index-3">[5]</a>
</li>
      <li><a href="library/turtle.html#turtle.home">home() (in module turtle)</a>
</li>
      <li><a href="install/index.html#index-7">HOMEDRIVE</a>, <a href="library/os.path.html#index-6">[1]</a>
</li>
      <li><a href="install/index.html#index-8">HOMEPATH</a>, <a href="library/os.path.html#index-5">[1]</a>
</li>
      <li><a href="library/fileinput.html#fileinput.hook_compressed">hook_compressed() (in module fileinput)</a>
</li>
      <li><a href="library/fileinput.html#fileinput.hook_encoded">hook_encoded() (in module fileinput)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.hosts">hosts (netrc.netrc attribute)</a>
</li>
      <li><a href="library/hotshot.html#module-hotshot">hotshot (module)</a>
</li>
      <li><a href="library/hotshot.html#module-hotshot.stats">hotshot.stats (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.hour">hour (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.hour">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.HRESULT">HRESULT (class in ctypes)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdError">hStdError (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdInput">hStdInput (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdOutput">hStdOutput (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.hsv_to_rgb">hsv_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/turtle.html#turtle.ht">ht() (in module turtle)</a>
</li>
      <li><a href="library/htmllib.html#index-0">HTML</a>, <a href="library/htmlparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-9">[2]</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar">HTMLCalendar (class in calendar)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff">HtmlDiff (class in difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.__init__">HtmlDiff.__init__() (in module difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.make_file">HtmlDiff.make_file() (in module difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.make_table">HtmlDiff.make_table() (in module difflib)</a>
</li>
      <li><a href="library/htmllib.html#module-htmlentitydefs">htmlentitydefs (module)</a>
</li>
      <li>
    htmllib

      <ul>
        <li><a href="library/urllib.html#index-9">module</a>
</li>
      </ul></li>
      <li><a href="library/htmllib.html#module-htmllib">htmllib (module)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParseError">HTMLParseError</a>, <a href="library/htmlparser.html#HTMLParser.HTMLParseError">[1]</a>
</li>
      <li><a href="library/formatter.html#index-0">HTMLParser (class in htmllib)</a>, <a href="library/htmllib.html#htmllib.HTMLParser">[1]</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser">(class in HTMLParser)</a>
</li>
        <li><a href="library/htmlparser.html#module-HTMLParser">(module)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.htonl">htonl() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.htons">htons() (in module socket)</a>
</li>
      <li>
    HTTP

      <ul>
        <li><a href="library/httplib.html#index-0">httplib (standard module)</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">protocol</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/httplib.html#index-0">[2]</a>, <a href="library/urllib.html#index-8">[3]</a>, <a href="library/urllib.html#index-9">[4]</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_301">http_error_301() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_302">http_error_302() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_303">http_error_303() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_307">http_error_307() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPBasicAuthHandler.http_error_401">http_error_401() (urllib2.HTTPBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPDigestAuthHandler.http_error_401">(urllib2.HTTPDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.ProxyBasicAuthHandler.http_error_407">http_error_407() (urllib2.ProxyBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.ProxyDigestAuthHandler.http_error_407">(urllib2.ProxyDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.AbstractBasicAuthHandler.http_error_auth_reqed">http_error_auth_reqed() (urllib2.AbstractBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.AbstractDigestAuthHandler.http_error_auth_reqed">(urllib2.AbstractDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.http_error_default">http_error_default() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.http_error_nnn">http_error_nnn() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPHandler.http_open">http_open() (urllib2.HTTPHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTP_PORT">HTTP_PORT (in module httplib)</a>
</li>
      <li><a href="howto/urllib2.html#index-1">http_proxy</a>, <a href="library/urllib.html#index-2">[1]</a>, <a href="library/urllib2.html#index-0">[2]</a>, <a href="library/urllib2.html#index-6">[3]</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor.http_response">http_response() (urllib2.HTTPErrorProcessor method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.http_version">http_version (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPBasicAuthHandler">HTTPBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection">HTTPConnection (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPCookieProcessor">HTTPCookieProcessor (class in urllib2)</a>
</li>
      <li><a href="library/basehttpserver.html#index-0">httpd</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPDefaultErrorHandler">HTTPDefaultErrorHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPDigestAuthHandler">HTTPDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPError">HTTPError</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor">HTTPErrorProcessor (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPException">HTTPException</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler">HTTPHandler (class in logging.handlers)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPHandler">(class in urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#module-httplib">httplib (module)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPMessage">HTTPMessage (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr">HTTPPasswordMgr (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgrWithDefaultRealm">HTTPPasswordMgrWithDefaultRealm (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler">HTTPRedirectHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse">HTTPResponse (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPSHandler.https_open">https_open() (urllib2.HTTPSHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPS_PORT">HTTPS_PORT (in module httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor.https_response">https_response() (urllib2.HTTPErrorProcessor method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPSConnection">HTTPSConnection (class in httplib)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.HTTPServer">HTTPServer (class in BaseHTTPServer)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPSHandler">HTTPSHandler (class in urllib2)</a>
</li>
      <li><a href="library/htmllib.html#index-0">hypertext</a>
</li>
      <li><a href="library/math.html#math.hypot">hypot() (in module math)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="I">I</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.I">I (in module re)</a>
</li>
      <li>
    I/O control

      <ul>
        <li><a href="library/termios.html#index-0">POSIX</a>
</li>
        <li><a href="library/fcntl.html#index-0">UNIX</a>
</li>
        <li><a href="library/functions.html#index-4">buffering</a>, <a href="library/os.html#index-11">[1]</a>, <a href="library/socket.html#index-3">[2]</a>
</li>
        <li><a href="library/termios.html#index-0">tty</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.iadd">iadd() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.iand">iand() (in module operator)</a>
</li>
      <li><a href="library/ic.html#ic.IC">IC (class in ic)</a>
</li>
      <li><a href="library/ic.html#module-ic">ic (module)</a>
</li>
      <li>
    icglue

      <ul>
        <li><a href="library/ic.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.iconcat">iconcat() (in module operator)</a>
</li>
      <li><a href="library/undoc.html#module-icopen">icopen (module)</a>
</li>
      <li>
    id

      <ul>
        <li><a href="reference/datamodel.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#id">id() (built-in function)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.TestCase.id">(unittest.TestCase method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.idcok">idcok() (curses.window method)</a>
</li>
      <li><a href="library/cd.html#cd.ident">ident (in module cd)</a>

      <ul>
        <li><a href="library/select.html#select.kevent.ident">(select.kevent attribute)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.ident">(threading.Thread attribute)</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.identchars">identchars (cmd.Cmd attribute)</a>
</li>
      <li><a href="reference/expressions.html#index-5">identifier</a>, <a href="reference/lexical_analysis.html#index-9">[1]</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.identify">identify() (ttk.Notebook method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.identify">(ttk.Treeview method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Widget.identify">(ttk.Widget method)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_column">identify_column() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_element">identify_element() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_region">identify_region() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_row">identify_row() (ttk.Treeview method)</a>
</li>
      <li>
    identity

      <ul>
        <li><a href="reference/expressions.html#index-68">test</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">identity of an object</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-idioms">idioms (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.idiv">idiv() (in module operator)</a>
</li>
      <li><a href="library/idle.html#index-0">IDLE</a>, <a href="glossary.html#term-idle"><strong>[1]</strong></a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.idle">idle() (FrameWork.Application method)</a>
</li>
      <li><a href="library/idle.html#index-5">IDLESTARTUP</a>
</li>
      <li><a href="library/curses.html#curses.window.idlok">idlok() (curses.window method)</a>
</li>
      <li><a href="library/fpectl.html#index-0">IEEE-754</a>
</li>
      <li>
    if

      <ul>
        <li><a href="library/stdtypes.html#index-2">statement</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.ifilter">ifilter() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.ifilterfalse">ifilterfalse() (in module itertools)</a>
</li>
      <li><a href="library/operator.html#operator.ifloordiv">ifloordiv() (in module operator)</a>
</li>
      <li><a href="library/glob.html#glob.iglob">iglob() (in module glob)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.ignorableWhitespace">ignorableWhitespace() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/codecs.html#codecs.ignore_errors">ignore_errors() (in module codecs)</a>
</li>
      <li><a href="library/doctest.html#doctest.IGNORE_EXCEPTION_DETAIL">IGNORE_EXCEPTION_DETAIL (in module doctest)</a>
</li>
      <li><a href="library/shutil.html#shutil.ignore_patterns">ignore_patterns() (in module shutil)</a>
</li>
      <li><a href="library/re.html#re.IGNORECASE">IGNORECASE (in module re)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.ihave">ihave() (nntplib.NNTP method)</a>
</li>
      <li>
    ihooks

      <ul>
        <li><a href="c-api/import.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.ilshift">ilshift() (in module operator)</a>
</li>
      <li><a href="reference/datamodel.html#index-40">im_class (method attribute)</a>, <a href="reference/datamodel.html#index-42">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-39">im_func (method attribute)</a>, <a href="reference/datamodel.html#index-40">[1]</a>, <a href="reference/datamodel.html#index-41">[2]</a>, <a href="reference/datamodel.html#index-42">[3]</a>
</li>
      <li><a href="reference/datamodel.html#index-39">im_self (method attribute)</a>, <a href="reference/datamodel.html#index-40">[1]</a>, <a href="reference/datamodel.html#index-42">[2]</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex.imag">imag (numbers.Complex attribute)</a>
</li>
      <li><a href="library/imageop.html#module-imageop">imageop (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">imaginary literal</a>
</li>
      <li><a href="library/itertools.html#itertools.imap">imap() (in module itertools)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.imap">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      </ul></li>
      <li>
    IMAP4

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4">IMAP4 (class in imaplib)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.abort">IMAP4.abort</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.error">IMAP4.error</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.readonly">IMAP4.readonly</a>
</li>
      <li>
    IMAP4_SSL

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_SSL">IMAP4_SSL (class in imaplib)</a>
</li>
      <li>
    IMAP4_stream

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_stream">IMAP4_stream (class in imaplib)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.imap_unordered">imap_unordered() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/imaplib.html#module-imaplib">imaplib (module)</a>
</li>
      <li><a href="library/imgfile.html#module-imgfile">imgfile (module)</a>
</li>
      <li><a href="library/imghdr.html#module-imghdr">imghdr (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.immedok">immedok() (curses.window method)</a>
</li>
      <li><a href="glossary.html#term-immutable"><strong>immutable</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-9">data type</a>
</li>
        <li><a href="reference/datamodel.html#index-20">object</a>, <a href="reference/expressions.html#index-17">[1]</a>, <a href="reference/expressions.html#index-9">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">immutable object</a>
</li>
      <li>
    immutable sequence

      <ul>
        <li><a href="reference/datamodel.html#index-20">object</a>
</li>
      </ul></li>
      <li>
    immutable types

      <ul>
        <li><a href="reference/datamodel.html#index-73">subclassing</a>
</li>
      </ul></li>
      <li><a href="library/sets.html#sets.ImmutableSet">ImmutableSet (class in sets)</a>
</li>
      <li><a href="library/operator.html#operator.imod">imod() (in module operator)</a>
</li>
      <li>
    imp

      <ul>
        <li><a href="library/functions.html#index-8">module</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#module-imp">imp (module)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.ImpImporter">ImpImporter (class in pkgutil)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.ImpLoader">ImpLoader (class in pkgutil)</a>
</li>
      <li>
    import

      <ul>
        <li><a href="library/functions.html#index-8">statement</a>, <a href="library/imp.html#index-0">[1]</a>, <a href="library/imputil.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-47">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-import">import (2to3 fixer)</a>
</li>
      <li><a href="library/imputil.html#imputil.DynLoadSuffixImporter.import_file">import_file() (imputil.DynLoadSuffixImporter method)</a>
</li>
      <li><a href="library/test.html#test.support.import_fresh_module">import_fresh_module() (in module test.support)</a>
</li>
      <li><a href="library/dis.html#opcode-IMPORT_FROM">IMPORT_FROM (opcode)</a>
</li>
      <li><a href="library/importlib.html#importlib.import_module">import_module() (in module importlib)</a>

      <ul>
        <li><a href="library/test.html#test.support.import_module">(in module test.support)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-IMPORT_NAME">IMPORT_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-IMPORT_STAR">IMPORT_STAR (opcode)</a>
</li>
      <li><a href="library/imputil.html#imputil.Importer.import_top">import_top() (imputil.Importer method)</a>
</li>
      <li><a href="glossary.html#term-importer"><strong>importer</strong></a>
</li>
      <li><a href="library/imputil.html#imputil.Importer">Importer (class in imputil)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ImportError">ImportError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">exception</a>, <a href="reference/simple_stmts.html#index-47">[1]</a>, <a href="reference/simple_stmts.html#index-48">[2]</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-importing"><strong>importing</strong></a>
</li>
      <li><a href="library/importlib.html#module-importlib">importlib (module)</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager">ImportManager (class in imputil)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-imports">imports (2to3 fixer)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-imports2">imports2 (2to3 fixer)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ImportWarning">ImportWarning</a>
</li>
      <li><a href="library/httplib.html#httplib.ImproperConnectionState">ImproperConnectionState</a>
</li>
      <li><a href="library/imputil.html#module-imputil">imputil (module)</a>
</li>
      <li><a href="library/operator.html#operator.imul">imul() (in module operator)</a>
</li>
      <li>
    in

      <ul>
        <li><a href="reference/compound_stmts.html#index-6">keyword</a>
</li>
        <li><a href="library/stdtypes.html#index-12">operator</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._CData.in_dll">in_dll() (ctypes._CData method)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_a1">in_table_a1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_b1">in_table_b1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c11">in_table_c11() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c11_c12">in_table_c11_c12() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c12">in_table_c12() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c21">in_table_c21() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c21_c22">in_table_c21_c22() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c22">in_table_c22() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c3">in_table_c3() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c4">in_table_c4() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c5">in_table_c5() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c6">in_table_c6() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c7">in_table_c7() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c8">in_table_c8() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c9">in_table_c9() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_d1">in_table_d1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_d2">in_table_d2() (in module stringprep)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.inc">inc() (EasyDialogs.ProgressBar method)</a>
</li>
      <li><a href="library/curses.html#curses.window.inch">inch() (curses.window method)</a>
</li>
      <li>
    inclusive

      <ul>
        <li><a href="reference/expressions.html#index-63">or</a>
</li>
      </ul></li>
      <li><a href="library/binascii.html#binascii.Incomplete">Incomplete</a>
</li>
      <li><a href="library/httplib.html#httplib.IncompleteRead">IncompleteRead</a>
</li>
      <li><a href="c-api/intro.html#index-17">incr_item()</a>, <a href="c-api/intro.html#index-18">[1]</a>
</li>
      <li><a href="library/ast.html#ast.increment_lineno">increment_lineno() (in module ast)</a>
</li>
      <li><a href="library/codecs.html#codecs.IncrementalDecoder">IncrementalDecoder (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.IncrementalEncoder">IncrementalEncoder (class in codecs)</a>
</li>
      <li><a href="library/io.html#io.IncrementalNewlineDecoder">IncrementalNewlineDecoder (class in io)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser">IncrementalParser (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.indent">indent (doctest.Example attribute)</a>
</li>
      <li><a href="library/token.html#token.INDENT">INDENT (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-8">INDENT token</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">indentation</a>
</li>
      <li><a href="library/exceptions.html#exceptions.IndentationError">IndentationError</a>
</li>
      <li><a href="library/jpeg.html#index-0">Independent JPEG Group</a>
</li>
      <li><a href="library/cd.html#cd.index">index (in module cd)</a>
</li>
      <li><a href="reference/datamodel.html#index-17">index operation</a>
</li>
      <li><a href="library/array.html#array.array.index">index() (array.array method)</a>

      <ul>
        <li><a href="library/operator.html#operator.index">(in module operator)</a>
</li>
        <li><a href="library/string.html#string.index">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/stdtypes.html#str.index">(str method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.index">(ttk.Notebook method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.index">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.IndexError">IndexError</a>
</li>
      <li><a href="library/operator.html#operator.indexOf">indexOf() (in module operator)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.IndexSizeErr">IndexSizeErr</a>
</li>
      <li><a href="reference/datamodel.html#slice.indices">indices() (slice method)</a>
</li>
      <li><a href="library/socket.html#socket.inet_aton">inet_aton() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_ntoa">inet_ntoa() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_ntop">inet_ntop() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_pton">inet_pton() (in module socket)</a>
</li>
      <li><a href="library/decimal.html#decimal.Inexact">Inexact (class in decimal)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.infile">infile (shlex.shlex attribute)</a>
</li>
      <li><a href="library/functions.html#index-2">Infinity</a>, <a href="library/string.html#index-6">[1]</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.info">info() (gettext.NullTranslations method)</a>

      <ul>
        <li><a href="library/logging.html#logging.info">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.info">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.infolist">infolist() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/carbon.html#Carbon.Scrap.InfoScrap">InfoScrap() (in module Carbon.Scrap)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-23">inheritance</a>
</li>
      <li><a href="library/configparser.html#index-0">ini file</a>
</li>
      <li><a href="library/fm.html#fm.init">init() (in module fm)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.init">(in module mimetypes)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.init_builtin">init_builtin() (in module imp)</a>
</li>
      <li><a href="library/curses.html#curses.init_color">init_color() (in module curses)</a>
</li>
      <li><a href="library/msilib.html#msilib.init_database">init_database() (in module msilib)</a>
</li>
      <li><a href="library/imp.html#imp.init_frozen">init_frozen() (in module imp)</a>
</li>
      <li><a href="library/curses.html#curses.init_pair">init_pair() (in module curses)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.inited">inited (in module mimetypes)</a>
</li>
      <li><a href="library/os.html#os.initgroups">initgroups() (in module os)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.initial_indent">initial_indent (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.initialize_options">initialize_options() (distutils.cmd.Command method)</a>
</li>
      <li><a href="library/curses.html#curses.initscr">initscr() (in module curses)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_ADD">INPLACE_ADD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_AND">INPLACE_AND (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_DIVIDE">INPLACE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_FLOOR_DIVIDE">INPLACE_FLOOR_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_LSHIFT">INPLACE_LSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_MODULO">INPLACE_MODULO (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_MULTIPLY">INPLACE_MULTIPLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_OR">INPLACE_OR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_POWER">INPLACE_POWER (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_RSHIFT">INPLACE_RSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_SUBTRACT">INPLACE_SUBTRACT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_TRUE_DIVIDE">INPLACE_TRUE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_XOR">INPLACE_XOR (opcode)</a>
</li>
      <li><a href="reference/toplevel_components.html#index-5">input</a>

      <ul>
        <li><a href="library/sys.html#index-14">built-in function</a>, <a href="reference/toplevel_components.html#index-7">[1]</a>
</li>
        <li><a href="reference/toplevel_components.html#index-8">raw</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-input">input (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#input">input() (built-in function)</a>

      <ul>
        <li><a href="library/fileinput.html#fileinput.input">(in module fileinput)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.input_charset">input_charset (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.input_codec">input_codec (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/tix.html#Tix.InputOnly">InputOnly (class in Tix)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource">InputSource (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/stringio.html#cStringIO.InputType">InputType (in module cStringIO)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.inquiry">inquiry (C type)</a>
</li>
      <li><a href="library/curses.html#curses.window.insch">insch() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.insdelln">insdelln() (curses.window method)</a>
</li>
      <li><a href="library/array.html#array.array.insert">insert() (array.array method)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.insert">(ttk.Notebook method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.insert">(ttk.Treeview method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.insert">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.insert_text">insert_text() (in module readline)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.insertBefore">insertBefore() (xml.dom.Node method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.InsertionLoc">InsertionLoc (class in aetypes)</a>
</li>
      <li><a href="library/curses.html#curses.window.insertln">insertln() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.insnstr">insnstr() (curses.window method)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort">insort() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort_left">insort_left() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort_right">insort_right() (in module bisect)</a>
</li>
      <li><a href="library/inspect.html#module-inspect">inspect (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.insstr">insstr() (curses.window method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.install">install() (gettext.NullTranslations method)</a>

      <ul>
        <li><a href="library/imputil.html#imputil.ImportManager.install">(imputil.ImportManager method)</a>
</li>
        <li><a href="library/gettext.html#gettext.install">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.install_opener">install_opener() (in module urllib2)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer.installaehandler">installaehandler() (MiniAEFrame.AEServer method)</a>
</li>
      <li><a href="library/autogil.html#autoGIL.installAutoGIL">installAutoGIL() (in module autoGIL)</a>
</li>
      <li><a href="library/unittest.html#unittest.installHandler">installHandler() (in module unittest)</a>
</li>
      <li>
    instance

      <ul>
        <li><a href="reference/datamodel.html#index-87">call</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-54">class</a>
</li>
        <li><a href="c-api/class.html#index-2">object</a>, <a href="reference/datamodel.html#index-46">[1]</a>, <a href="reference/datamodel.html#index-50">[2]</a>, <a href="reference/datamodel.html#index-54">[3]</a>, <a href="reference/expressions.html#index-45">[4]</a>
</li>
      </ul></li>
      <li><a href="library/new.html#new.instance">instance() (in module new)</a>
</li>
      <li><a href="library/new.html#new.instancemethod">instancemethod() (in module new)</a>
</li>
      <li><a href="library/types.html#types.InstanceType">InstanceType (in module types)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget.instate">instate() (ttk.Widget method)</a>
</li>
      <li><a href="library/curses.html#curses.window.instr">instr() (curses.window method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.instream">instream (shlex.shlex attribute)</a>
</li>
      <li>
    int

      <ul>
        <li><a href="c-api/number.html#index-5">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-94">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#int">int (built-in class)</a>

      <ul>
        <li><a href="library/uuid.html#uuid.UUID.int">(uuid.UUID attribute)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.Int2AP">Int2AP() (in module imaplib)</a>
</li>
      <li><a href="reference/datamodel.html#index-23">integer</a>

      <ul>
        <li><a href="library/stdtypes.html#index-17">division</a>
</li>
        <li><a href="library/stdtypes.html#index-17">division, long</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals, long</a>
</li>
        <li><a href="c-api/int.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-10">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-14">representation</a>
</li>
        <li><a href="library/stdtypes.html#index-19">types, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-integer-division"><strong>integer division</strong></a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">integer literal</a>
</li>
      <li><a href="library/numbers.html#numbers.Integral">Integral (class in numbers)</a>
</li>
      <li><a href="library/idle.html#index-0">Integrated Development Environment</a>
</li>
      <li><a href="library/audioop.html#index-0">Intel/DVI ADPCM</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole.interact">interact() (code.InteractiveConsole method)</a>

      <ul>
        <li><a href="library/code.html#code.interact">(in module code)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.interact">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-interactive"><strong>interactive</strong></a>
</li>
      <li><a href="reference/toplevel_components.html#index-3">interactive mode</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole">InteractiveConsole (class in code)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter">InteractiveInterpreter (class in code)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-intern">intern (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#intern">intern() (built-in function)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/datamodel.html#index-59">internal type</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.internal_attr">internal_attr (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.Internaldate2tuple">Internaldate2tuple() (in module imaplib)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.internalSubset">internalSubset (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/internet.html#index-0">Internet</a>
</li>
      <li><a href="library/urllib.html#index-5">Internet Config</a>
</li>
      <li><a href="library/stdtypes.html#index-25">interpolation, string (%)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationDepthError">InterpolationDepthError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationError">InterpolationError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationMissingOptionError">InterpolationMissingOptionError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationSyntaxError">InterpolationSyntaxError</a>
</li>
      <li><a href="glossary.html#term-interpreted"><strong>interpreted</strong></a>
</li>
      <li><a href="reference/toplevel_components.html#index-0">interpreter</a>
</li>
      <li><a href="c-api/init.html#index-13">interpreter lock</a>
</li>
      <li><a href="library/sys.html#index-11">interpreter prompts</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.interrupt">interrupt() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/thread.html#thread.interrupt_main">interrupt_main() (in module thread)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.intersection">intersection() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.intersection_update">intersection_update() (frozenset method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.IntlText">IntlText (class in aetypes)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.IntlWritingCode">IntlWritingCode (class in aetypes)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.intro">intro (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/types.html#types.IntType">IntType (in module types)</a>

      <ul>
        <li><a href="c-api/int.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.InuseAttributeErr">InuseAttributeErr</a>
</li>
      <li><a href="library/operator.html#operator.inv">inv() (in module operator)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidAccessErr">InvalidAccessErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidCharacterErr">InvalidCharacterErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidModificationErr">InvalidModificationErr</a>
</li>
      <li><a href="library/decimal.html#decimal.InvalidOperation">InvalidOperation (class in decimal)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidStateErr">InvalidStateErr</a>
</li>
      <li><a href="library/httplib.html#httplib.InvalidURL">InvalidURL</a>
</li>
      <li><a href="reference/expressions.html#index-50">inversion</a>
</li>
      <li><a href="library/operator.html#operator.invert">invert() (in module operator)</a>
</li>
      <li><a href="reference/datamodel.html#index-35">invocation</a>
</li>
      <li><a href="library/io.html#module-io">io (module)</a>
</li>
      <li><a href="library/io.html#io.IOBase">IOBase (class in io)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.ioctl">ioctl() (in module fcntl)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.ioctl">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.IOError">IOError</a>
</li>
      <li><a href="library/operator.html#operator.ior">ior() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.ipow">ipow() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.irepeat">irepeat() (in module operator)</a>
</li>
      <li><a href="library/fm.html#index-0">IRIS Font Manager</a>
</li>
      <li>
    IRIX

      <ul>
        <li><a href="library/thread.html#index-3">threads</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.irshift">irshift() (in module operator)</a>
</li>
      <li>
    is

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
      </ul></li>
      <li>
    is not

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.is_">is_() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.is_alive">is_alive() (multiprocessing.Process method)</a>

      <ul>
        <li><a href="library/threading.html#threading.Thread.is_alive">(threading.Thread method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_assigned">is_assigned() (symtable.Symbol method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.is_blocked">is_blocked() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/imp.html#imp.is_builtin">is_builtin() (in module imp)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_canonical">is_canonical() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_canonical">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.IS_CHARACTER_JUNK">IS_CHARACTER_JUNK() (in module difflib)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.is_data">is_data() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_declared_global">is_declared_global() (symtable.Symbol method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo.is_empty">is_empty() (asynchat.fifo method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.is_expired">is_expired() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_finite">is_finite() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_finite">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_free">is_free() (symtable.Symbol method)</a>
</li>
      <li><a href="library/imp.html#imp.is_frozen">is_frozen() (in module imp)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_global">is_global() (symtable.Symbol method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.is_hop_by_hop">is_hop_by_hop() (in module wsgiref.util)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_imported">is_imported() (symtable.Symbol method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_infinite">is_infinite() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_infinite">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#float.is_integer">is_integer() (float method)</a>
</li>
      <li><a href="library/test.html#test.support.is_jython">is_jython (in module test.support)</a>
</li>
      <li><a href="library/difflib.html#difflib.IS_LINE_JUNK">IS_LINE_JUNK() (in module difflib)</a>
</li>
      <li><a href="library/curses.html#curses.window.is_linetouched">is_linetouched() (curses.window method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_local">is_local() (symtable.Symbol method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.is_multipart">is_multipart() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_namespace">is_namespace() (symtable.Symbol method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_nan">is_nan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_nan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.SymbolTable.is_nested">is_nested() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_normal">is_normal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_normal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.is_not">is_not() (in module operator)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.is_not_allowed">is_not_allowed() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.is_optimized">is_optimized() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.is_package">is_package() (zipimport.zipimporter method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_parameter">is_parameter() (symtable.Symbol method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.is_python_build">is_python_build() (in module sysconfig)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_qnan">is_qnan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_qnan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_referenced">is_referenced() (symtable.Symbol method)</a>
</li>
      <li><a href="library/test.html#test.support.is_resource_enabled">is_resource_enabled() (in module test.support)</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.is_scriptable">is_scriptable() (in module gensuitemodule)</a>
</li>
      <li><a href="library/threading.html#threading.Event.is_set">is_set() (threading.Event method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_signed">is_signed() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_signed">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.is_snan">is_snan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_snan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.is_subnormal">is_subnormal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_subnormal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.is_tarfile">is_tarfile() (in module tarfile)</a>
</li>
      <li><a href="library/curses.html#curses.is_term_resized">is_term_resized() (in module curses)</a>
</li>
      <li><a href="library/gc.html#gc.is_tracked">is_tracked() (in module gc)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.is_unverifiable">is_unverifiable() (urllib2.Request method)</a>
</li>
      <li><a href="library/curses.html#curses.window.is_wintouched">is_wintouched() (curses.window method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_zero">is_zero() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_zero">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.is_zipfile">is_zipfile() (in module zipfile)</a>
</li>
      <li><a href="library/os.path.html#os.path.isabs">isabs() (in module os.path)</a>
</li>
      <li><a href="library/inspect.html#inspect.isabstract">isabstract() (in module inspect)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.isAlive">isAlive() (threading.Thread method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isalnum">isalnum() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isalnum">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isalpha">isalpha() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isalpha">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isascii">isascii() (in module curses.ascii)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.isatty">isatty() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.isatty">(file method)</a>
</li>
        <li><a href="library/os.html#os.isatty">(in module os)</a>
</li>
        <li><a href="library/io.html#io.IOBase.isatty">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isblank">isblank() (in module curses.ascii)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isblk">isblk() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isbuiltin">isbuiltin() (in module inspect)</a>
</li>
      <li><a href="library/operator.html#operator.isCallable">isCallable() (in module operator)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.ischr">ischr() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isclass">isclass() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.iscntrl">iscntrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/inspect.html#inspect.iscode">iscode() (in module inspect)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.iscomment">iscomment() (rfc822.Message method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isctrl">isctrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.isDaemon">isDaemon() (threading.Thread method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isdatadescriptor">isdatadescriptor() (in module inspect)</a>
</li>
      <li><a href="library/stdtypes.html#unicode.isdecimal">isdecimal() (unicode method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isdev">isdev() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isdigit">isdigit() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isdigit">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.isdir">isdir() (in module os.path)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.isdir">(tarfile.TarInfo method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset.isdisjoint">isdisjoint() (frozenset method)</a>
</li>
      <li><a href="library/turtle.html#turtle.isdown">isdown() (in module turtle)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.iselement">iselement() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/gc.html#gc.isenabled">isenabled() (in module gc)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.isEnabledFor">isEnabledFor() (logging.Logger method)</a>
</li>
      <li><a href="library/curses.html#curses.isendwin">isendwin() (in module curses)</a>
</li>
      <li><a href="library/token.html#token.ISEOF">ISEOF() (in module token)</a>
</li>
      <li><a href="library/parser.html#parser.isexpr">isexpr() (in module parser)</a>

      <ul>
        <li><a href="library/parser.html#parser.ST.isexpr">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isfifo">isfifo() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/os.path.html#os.path.isfile">isfile() (in module os.path)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.isfile">(tarfile.TarInfo method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.isfirstline">isfirstline() (in module fileinput)</a>
</li>
      <li><a href="library/inspect.html#inspect.isframe">isframe() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isfunction">isfunction() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgenerator">isgenerator() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgeneratorfunction">isgeneratorfunction() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgetsetdescriptor">isgetsetdescriptor() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isgraph">isgraph() (in module curses.ascii)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.isheader">isheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/cmath.html#cmath.isinf">isinf() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.isinf">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-isinstance">isinstance (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#isinstance">isinstance() (built-in function)</a>
</li>
      <li><a href="library/keyword.html#keyword.iskeyword">iskeyword() (in module keyword)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.islast">islast() (rfc822.Message method)</a>
</li>
      <li><a href="library/calendar.html#calendar.isleap">isleap() (in module calendar)</a>
</li>
      <li><a href="library/itertools.html#itertools.islice">islice() (in module itertools)</a>
</li>
      <li><a href="library/os.path.html#os.path.islink">islink() (in module os.path)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.islnk">islnk() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.islower">islower() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.islower">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.isMappingType">isMappingType() (in module operator)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismemberdescriptor">ismemberdescriptor() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ismeta">ismeta() (in module curses.ascii)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismethod">ismethod() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismethoddescriptor">ismethoddescriptor() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismodule">ismodule() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.ismount">ismount() (in module os.path)</a>
</li>
      <li><a href="library/cmath.html#cmath.isnan">isnan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.isnan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.ISNONTERMINAL">ISNONTERMINAL() (in module token)</a>
</li>
      <li><a href="library/operator.html#operator.isNumberType">isNumberType() (in module operator)</a>
</li>
      <li><a href="library/stdtypes.html#unicode.isnumeric">isnumeric() (unicode method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.isocalendar">isocalendar() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isocalendar">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.isoformat">isoformat() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isoformat">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.isoformat">(datetime.time method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.isolation_level">isolation_level (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.isoweekday">isoweekday() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isoweekday">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isprint">isprint() (in module curses.ascii)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ispunct">ispunct() (in module curses.ascii)</a>
</li>
      <li><a href="library/fl.html#fl.isqueued">isqueued() (in module fl)</a>
</li>
      <li><a href="library/pprint.html#pprint.isreadable">isreadable() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.isreadable">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/pprint.html#pprint.isrecursive">isrecursive() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.isrecursive">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isreg">isreg() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.isReservedKey">isReservedKey() (Cookie.Morsel method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isroutine">isroutine() (in module inspect)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.isSameNode">isSameNode() (xml.dom.Node method)</a>
</li>
      <li><a href="library/operator.html#operator.isSequenceType">isSequenceType() (in module operator)</a>
</li>
      <li><a href="library/threading.html#threading.Event.isSet">isSet() (threading.Event method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isspace">isspace() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isspace">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.isstdin">isstdin() (in module fileinput)</a>
</li>
      <li><a href="library/functions.html#issubclass">issubclass() (built-in function)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.issubset">issubset() (frozenset method)</a>
</li>
      <li><a href="library/parser.html#parser.issuite">issuite() (in module parser)</a>

      <ul>
        <li><a href="library/parser.html#parser.ST.issuite">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset.issuperset">issuperset() (frozenset method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.issym">issym() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/token.html#token.ISTERMINAL">ISTERMINAL() (in module token)</a>
</li>
      <li><a href="library/stdtypes.html#str.istitle">istitle() (str method)</a>
</li>
      <li><a href="library/inspect.html#inspect.istraceback">istraceback() (in module inspect)</a>
</li>
      <li><a href="library/operator.html#operator.isub">isub() (in module operator)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isupper">isupper() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isupper">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.isvisible">isvisible() (in module turtle)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isxdigit">isxdigit() (in module curses.ascii)</a>
</li>
      <li>
    item

      <ul>
        <li><a href="reference/expressions.html#index-32">sequence</a>
</li>
        <li><a href="reference/expressions.html#index-33">string</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-17">item selection</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.item">item() (ttk.Treeview method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.NamedNodeMap.item">(xml.dom.NamedNodeMap method)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.NodeList.item">(xml.dom.NodeList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.itemgetter">itemgetter() (in module operator)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser.items">items() (ConfigParser.ConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.items">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.items">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.items">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.items">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.items">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.itemsize">itemsize (array.array attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#memoryview.itemsize">(memoryview attribute)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.ItemsView">ItemsView (class in collections)</a>
</li>
      <li><a href="library/functions.html#iter">iter() (built-in function)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.iter">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.iter_child_nodes">iter_child_nodes() (in module ast)</a>
</li>
      <li><a href="library/ast.html#ast.iter_fields">iter_fields() (in module ast)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.iter_importers">iter_importers() (in module pkgutil)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.iter_modules">iter_modules() (in module pkgutil)</a>
</li>
      <li><a href="glossary.html#term-iterable"><strong>iterable</strong></a>
</li>
      <li><a href="library/collections.html#collections.Iterable">Iterable (class in collections)</a>
</li>
      <li><a href="library/userdict.html#UserDict.IterableUserDict">IterableUserDict (class in UserDict)</a>
</li>
      <li><a href="glossary.html#term-iterator"><strong>iterator</strong></a>
</li>
      <li><a href="library/collections.html#collections.Iterator">Iterator (class in collections)</a>
</li>
      <li><a href="library/stdtypes.html#index-20">iterator protocol</a>
</li>
      <li><a href="library/codecs.html#codecs.iterdecode">iterdecode() (in module codecs)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.iterdump">iterdump (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/codecs.html#codecs.iterencode">iterencode() (in module codecs)</a>

      <ul>
        <li><a href="library/json.html#json.JSONEncoder.iterencode">(json.JSONEncoder method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iterfind">iterfind() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.iterfind">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#dict.iteritems">iteritems() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.iteritems">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary.iterkeyrefs">iterkeyrefs() (weakref.WeakKeyDictionary method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.iterkeys">iterkeys() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.iterkeys">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdates">itermonthdates() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdays">itermonthdays() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdays2">itermonthdays2() (calendar.Calendar method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse">iterparse() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext">itertext() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-itertools">itertools (2to3 fixer)</a>

      <ul>
        <li><a href="library/itertools.html#module-itertools">(module)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-itertools_imports">itertools_imports (2to3 fixer)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary.itervaluerefs">itervaluerefs() (weakref.WeakValueDictionary method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.itervalues">itervalues() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.itervalues">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.Calendar.iterweekdays">iterweekdays() (calendar.Calendar method)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_PROF">ITIMER_PROF (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_REAL">ITIMER_REAL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_VIRTUAL">ITIMER_VIRTUAL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ItimerError">ItimerError</a>
</li>
      <li><a href="library/operator.html#operator.itruediv">itruediv() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.ixor">ixor() (in module operator)</a>
</li>
      <li><a href="library/itertools.html#itertools.izip">izip() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.izip_longest">izip_longest() (in module itertools)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="J">J</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/uu.html#index-0">Jansen, Jack</a>
</li>
      <li>
    Java

      <ul>
        <li><a href="reference/datamodel.html#index-15">language</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.java_ver">java_ver() (in module platform)</a>
</li>
      <li><a href="library/jpeg.html#index-2">JFIF</a>, <a href="library/jpeg.html#index-3">[1]</a>
</li>
      <li><a href="library/os.path.html#os.path.join">join() (in module os.path)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.join">(Queue.Queue method)</a>
</li>
        <li><a href="library/string.html#string.join">(in module string)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue.join">(multiprocessing.JoinableQueue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.join">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/stdtypes.html#str.join">(str method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.join">(threading.Thread method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.join_thread">join_thread() (multiprocessing.Queue method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue">JoinableQueue (class in multiprocessing)</a>
</li>
      <li><a href="library/string.html#string.joinfields">joinfields() (in module string)</a>
</li>
      <li><a href="library/jpeg.html#module-jpeg">jpeg (module)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.js_output">js_output() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.js_output">(Cookie.Morsel method)</a>
</li>
      </ul></li>
      <li>
    json

      <ul>
        <li><a href="tutorial/inputoutput.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/json.html#module-json">json (module)</a>
</li>
      <li><a href="library/json.html#json.JSONDecoder">JSONDecoder (class in json)</a>
</li>
      <li><a href="library/json.html#json.JSONEncoder">JSONEncoder (class in json)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_ABSOLUTE">JUMP_ABSOLUTE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_FORWARD">JUMP_FORWARD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_IF_FALSE_OR_POP">JUMP_IF_FALSE_OR_POP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_IF_TRUE_OR_POP">JUMP_IF_TRUE_OR_POP (opcode)</a>
</li>
      <li><a href="library/random.html#random.jumpahead">jumpahead() (in module random)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="K">K</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/msvcrt.html#msvcrt.kbhit">kbhit() (in module msvcrt)</a>
</li>
      <li><a href="library/webbrowser.html#index-2">KDEDIR</a>
</li>
      <li><a href="library/select.html#select.kevent">kevent() (in module select)</a>
</li>
      <li><a href="reference/expressions.html#index-16">key</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.key">(Cookie.Morsel attribute)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-key-function"><strong>key function</strong></a>
</li>
      <li><a href="reference/expressions.html#index-16">key/datum pair</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_ALL_ACCESS">KEY_ALL_ACCESS (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_CREATE_LINK">KEY_CREATE_LINK (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_CREATE_SUB_KEY">KEY_CREATE_SUB_KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_ENUMERATE_SUB_KEYS">KEY_ENUMERATE_SUB_KEYS (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_EXECUTE">KEY_EXECUTE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_NOTIFY">KEY_NOTIFY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_QUERY_VALUE">KEY_QUERY_VALUE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_READ">KEY_READ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_SET_VALUE">KEY_SET_VALUE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WOW64_32KEY">KEY_WOW64_32KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WOW64_64KEY">KEY_WOW64_64KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WRITE">KEY_WRITE (in module _winreg)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.KeyboardInterrupt">KeyboardInterrupt</a>

      <ul>
        <li><a href="c-api/exceptions.html#index-2">(built-in exception)</a>, <a href="c-api/exceptions.html#index-3">[1]</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.KeyError">KeyError</a>
</li>
      <li><a href="library/curses.html#curses.keyname">keyname() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.window.keypad">keypad() (curses.window method)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary.keyrefs">keyrefs() (weakref.WeakKeyDictionary method)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.keys">keys() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.keys">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.keys">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.keys">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.Row.keys">(sqlite3.Row method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.keys">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/aetools.html#aetools.keysubst">keysubst() (in module aetools)</a>
</li>
      <li><a href="library/collections.html#collections.KeysView">KeysView (class in collections)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-10">keyword</a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-3">elif</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">else</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>, <a href="reference/compound_stmts.html#index-4">[2]</a>, <a href="reference/compound_stmts.html#index-6">[3]</a>, <a href="reference/simple_stmts.html#index-34">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">except</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">finally</a>, <a href="reference/compound_stmts.html#index-13">[1]</a>, <a href="reference/simple_stmts.html#index-27">[2]</a>, <a href="reference/simple_stmts.html#index-36">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-38">from</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">in</a>
</li>
        <li><a href="reference/expressions.html#index-22">yield</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Keyword">Keyword (class in aetypes)</a>
</li>
      <li><a href="library/keyword.html#module-keyword">keyword (module)</a>
</li>
      <li><a href="glossary.html#term-keyword-argument"><strong>keyword argument</strong></a>
</li>
      <li><a href="library/functools.html#functools.partial.keywords">keywords (functools.partial attribute)</a>
</li>
      <li><a href="library/os.html#os.kill">kill() (in module os)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.kill">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.killchar">killchar() (in module curses)</a>
</li>
      <li><a href="library/os.html#os.killpg">killpg() (in module os)</a>
</li>
      <li>
    knee

      <ul>
        <li><a href="library/imp.html#index-5">module</a>, <a href="library/imputil.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.knownfiles">knownfiles (in module mimetypes)</a>
</li>
      <li><a href="library/select.html#select.kqueue">kqueue() (in module select)</a>
</li>
      <li><a href="library/keyword.html#keyword.kwlist">kwlist (in module keyword)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="L">L</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.L">L (in module re)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.label">label() (EasyDialogs.ProgressBar method)</a>
</li>
      <li><a href="library/tix.html#Tix.LabelEntry">LabelEntry (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.LabelFrame">LabelFrame (class in Tix)</a>
</li>
      <li><a href="glossary.html#term-lambda"><strong>lambda</strong></a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-22">expression</a>, <a href="reference/expressions.html#index-75">[1]</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.LambdaType">LambdaType (in module types)</a>
</li>
      <li><a href="library/gettext.html#index-3">LANG</a>, <a href="library/gettext.html#index-7">[1]</a>, <a href="library/locale.html#index-1">[2]</a>, <a href="library/locale.html#index-2">[3]</a>, <a href="library/locale.html#index-3">[4]</a>
</li>
      <li><a href="library/gettext.html#index-0">LANGUAGE</a>, <a href="library/gettext.html#index-4">[1]</a>
</li>
      <li>
    language

      <ul>
        <li><a href="library/stdtypes.html#index-13">C</a>, <a href="reference/datamodel.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-4">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-65">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-15">Java</a>
</li>
        <li><a href="reference/compound_stmts.html#index-8">Pascal</a>
</li>
      </ul></li>
      <li><a href="library/posix.html#index-1">large files</a>
</li>
      <li><a href="library/zipfile.html#zipfile.LargeZipFile">LargeZipFile</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.last">last (multifile.MultiFile attribute)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.last">last() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.last">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.last">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.last_accepted">last_accepted (multiprocessing.connection.Listener attribute)</a>
</li>
      <li><a href="library/sys.html#sys.last_traceback">last_traceback (in module sys)</a>, <a href="reference/datamodel.html#index-67">[1]</a>
</li>
      <li><a href="library/sys.html#sys.last_type">last_type (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.last_value">last_value (in module sys)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.lastChild">lastChild (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.lastcmd">lastcmd (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.lastgroup">lastgroup (re.MatchObject attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.lastindex">lastindex (re.MatchObject attribute)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.lastpart">lastpart() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.lastrowid">lastrowid (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/macostools.html#findertools.launch">launch() (in module findertools)</a>
</li>
      <li><a href="library/ic.html#ic.IC.launchurl">launchurl() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.launchurl">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Style.layout">layout() (ttk.Style method)</a>
</li>
      <li><a href="library/token.html#token.LBRACE">LBRACE (in module token)</a>
</li>
      <li><a href="glossary.html#term-lbyl"><strong>LBYL</strong></a>
</li>
      <li><a href="library/gettext.html#index-1">LC_ALL</a>, <a href="library/gettext.html#index-5">[1]</a>

      <ul>
        <li><a href="library/locale.html#locale.LC_ALL">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.LC_COLLATE">LC_COLLATE (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_CTYPE">LC_CTYPE (in module locale)</a>
</li>
      <li><a href="library/gettext.html#index-2">LC_MESSAGES</a>, <a href="library/gettext.html#index-6">[1]</a>

      <ul>
        <li><a href="library/locale.html#locale.LC_MESSAGES">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.LC_MONETARY">LC_MONETARY (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_NUMERIC">LC_NUMERIC (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_TIME">LC_TIME (in module locale)</a>
</li>
      <li><a href="library/os.html#os.lchflags">lchflags() (in module os)</a>
</li>
      <li><a href="library/os.html#os.lchmod">lchmod() (in module os)</a>
</li>
      <li><a href="library/os.html#os.lchown">lchown() (in module os)</a>
</li>
      <li><a href="whatsnew/2.7.html#index-12">LDCXXSHARED</a>
</li>
      <li><a href="library/math.html#math.ldexp">ldexp() (in module math)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-27">LDFLAGS</a>
</li>
      <li><a href="library/gettext.html#gettext.ldgettext">ldgettext() (in module gettext)</a>
</li>
      <li><a href="library/gettext.html#gettext.ldngettext">ldngettext() (in module gettext)</a>
</li>
      <li><a href="library/operator.html#operator.le">le() (in module operator)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">leading whitespace</a>
</li>
      <li><a href="library/calendar.html#calendar.leapdays">leapdays() (in module calendar)</a>
</li>
      <li><a href="library/curses.html#curses.window.leaveok">leaveok() (curses.window method)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left">left (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.left">left() (in module turtle)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left_list">left_list (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left_only">left_only (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/token.html#token.LEFTSHIFT">LEFTSHIFT (in module token)</a>
</li>
      <li><a href="library/token.html#token.LEFTSHIFTEQUAL">LEFTSHIFTEQUAL (in module token)</a>
</li>
      <li>
    len

      <ul>
        <li><a href="c-api/dict.html#index-3">built-in function</a>, <a href="c-api/list.html#index-1">[1]</a>, <a href="c-api/mapping.html#index-0">[2]</a>, <a href="c-api/object.html#index-11">[3]</a>, <a href="c-api/sequence.html#index-0">[4]</a>, <a href="c-api/set.html#index-1">[5]</a>, <a href="library/stdtypes.html#index-22">[6]</a>, <a href="library/stdtypes.html#index-32">[7]</a>, <a href="reference/datamodel.html#index-17">[8]</a>, <a href="reference/datamodel.html#index-29">[9]</a>, <a href="reference/datamodel.html#index-32">[10]</a>, <a href="reference/datamodel.html#index-88">[11]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#len">len() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NamedNodeMap.length">length (xml.dom.NamedNodeMap attribute)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.NodeList.length">(xml.dom.NodeList attribute)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.LESS">LESS (in module token)</a>
</li>
      <li><a href="library/token.html#token.LESSEQUAL">LESSEQUAL (in module token)</a>
</li>
      <li><a href="library/string.html#string.letters">letters (in module string)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.level">level (multifile.MultiFile attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">lexical analysis</a>
</li>
      <li><a href="reference/introduction.html#index-1">lexical definitions</a>
</li>
      <li><a href="library/os.path.html#os.path.lexists">lexists() (in module os.path)</a>
</li>
      <li><a href="library/math.html#math.lgamma">lgamma() (in module math)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.lgettext">lgettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.lgettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.lgettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#module-lib2to3">lib2to3 (module)</a>
</li>
      <li><a href="library/platform.html#platform.libc_ver">libc_ver() (in module platform)</a>
</li>
      <li><a href="library/dbm.html#dbm.library">library (in module dbm)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLError.library">(ssl.SSLError attribute)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_dir_option">library_dir_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_filename">library_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_option">library_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.LibraryLoader">LibraryLoader (class in ctypes)</a>
</li>
      <li><a href="library/constants.html#license">license (built-in variable)</a>
</li>
      <li><a href="library/queue.html#Queue.LifoQueue">LifoQueue (class in Queue)</a>
</li>
      <li><a href="library/thread.html#index-0">light-weight processes</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction.limit_denominator">limit_denominator() (fractions.Fraction method)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2adpcm">lin2adpcm() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2alaw">lin2alaw() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2lin">lin2lin() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2ulaw">lin2ulaw() (in module audioop)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-5">line continuation</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-2">line joining</a>, <a href="reference/lexical_analysis.html#index-5">[1]</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-1">line structure</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.line">line() (msilib.Dialog method)</a>
</li>
      <li><a href="library/functions.html#index-4">line-buffered I/O</a>
</li>
      <li><a href="library/io.html#io.TextIOWrapper.line_buffering">line_buffering (io.TextIOWrapper attribute)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.line_num">line_num (csv.csvreader attribute)</a>
</li>
      <li><a href="library/linecache.html#module-linecache">linecache (module)</a>
</li>
      <li><a href="library/ast.html#ast.AST.lineno">lineno (ast.AST attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.lineno">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/doctest.html#doctest.Example.lineno">(doctest.Example attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Class.lineno">(pyclbr.Class attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Function.lineno">(pyclbr.Function attribute)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.lineno">(shlex.shlex attribute)</a>
</li>
        <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.lineno">(xml.parsers.expat.ExpatError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.lineno">lineno() (in module fileinput)</a>
</li>
      <li><a href="library/curses.html#index-0">LINES</a>, <a href="library/curses.html#index-3">[1]</a>, <a href="library/curses.html#index-5">[2]</a>
</li>
      <li><a href="library/os.html#os.linesep">linesep (in module os)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.lineterminator">lineterminator (csv.Dialect attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link">link() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="library/os.html#os.link">(in module os)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_executable">link_executable() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_shared_lib">link_shared_lib() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_shared_object">link_shared_object() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/macos.html#MacOS.linkmodel">linkmodel (in module MacOS)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.linkname">linkname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/platform.html#platform.linux_distribution">linux_distribution() (in module platform)</a>
</li>
      <li><a href="glossary.html#term-list"><strong>list</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-6">assignment, target</a>
</li>
        <li><a href="reference/expressions.html#index-13">comprehensions</a>, <a href="reference/expressions.html#index-14">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">deletion target</a>
</li>
        <li><a href="reference/expressions.html#index-13">display</a>
</li>
        <li><a href="reference/expressions.html#index-14">empty</a>
</li>
        <li><a href="reference/expressions.html#index-76">expression</a>, <a href="reference/simple_stmts.html#index-1">[1]</a>, <a href="reference/simple_stmts.html#index-4">[2]</a>
</li>
        <li><a href="c-api/list.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="library/stdtypes.html#index-29">[2]</a>, <a href="reference/datamodel.html#index-26">[3]</a>, <a href="reference/expressions.html#index-14">[4]</a>, <a href="reference/expressions.html#index-30">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/expressions.html#index-35">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">target</a>, <a href="reference/simple_stmts.html#index-5">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-30">type, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-list-comprehension"><strong>list comprehension</strong></a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.list">list() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.list">(multiprocessing.managers.SyncManager method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.list">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.list">(poplib.POP3 method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.list">(tarfile.TarFile method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LIST_APPEND">LIST_APPEND (opcode)</a>
</li>
      <li><a href="library/csv.html#csv.list_dialects">list_dialects() (in module csv)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.list_folders">list_folders() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.list_folders">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.MH.listallfolders">listallfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listallsubfolders">listallsubfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/dircache.html#dircache.listdir">listdir() (in module dircache)</a>

      <ul>
        <li><a href="library/os.html#os.listdir">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.listen">listen() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/logging.config.html#logging.config.listen">(in module logging.config)</a>
</li>
        <li><a href="library/turtle.html#turtle.listen">(in module turtle)</a>
</li>
        <li><a href="library/socket.html#socket.socket.listen">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener">Listener (class in multiprocessing.connection)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listfolders">listfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.listmessages">listmessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.listMethods">listMethods() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li><a href="library/tix.html#Tix.ListNoteBook">ListNoteBook (class in Tix)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listsubfolders">listsubfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/types.html#types.ListType">ListType (in module types)</a>
</li>
      <li><a href="reference/expressions.html#index-8">literal</a>, <a href="reference/lexical_analysis.html#index-11">[1]</a>
</li>
      <li><a href="library/ast.html#ast.literal_eval">literal_eval() (in module ast)</a>
</li>
      <li>
    literals

      <ul>
        <li><a href="library/stdtypes.html#index-14">complex number</a>
</li>
        <li><a href="library/stdtypes.html#index-14">floating point</a>
</li>
        <li><a href="library/stdtypes.html#index-14">hexadecimal</a>
</li>
        <li><a href="library/stdtypes.html#index-14">integer</a>
</li>
        <li><a href="library/stdtypes.html#index-14">long integer</a>
</li>
        <li><a href="library/stdtypes.html#index-14">numeric</a>
</li>
        <li><a href="library/stdtypes.html#index-14">octal</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.LittleEndianStructure">LittleEndianStructure (class in ctypes)</a>
</li>
      <li><a href="library/string.html#string.ljust">ljust() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.ljust">(str method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/msvcrt.html#msvcrt.LK_LOCK">LK_LOCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_NBLCK">LK_NBLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_NBRLCK">LK_NBRLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_RLCK">LK_RLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_UNLCK">LK_UNLCK (in module msvcrt)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.LMTP">LMTP (class in smtplib)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.ln">ln() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.ln">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/getpass.html#index-2">LNAME</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.lngettext">lngettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.lngettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.lngettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.load">load() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.FileCookieJar.load">(cookielib.FileCookieJar method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.stats.load">(in module hotshot.stats)</a>
</li>
        <li><a href="library/json.html#json.load">(in module json)</a>
</li>
        <li><a href="library/marshal.html#marshal.load">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.load">(in module pickle)</a>
</li>
        <li><a href="library/pickle.html#pickle.Unpickler.load">(pickle.Unpickler method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LOAD_ATTR">LOAD_ATTR (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_cert_chain">load_cert_chain() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_CLOSURE">LOAD_CLOSURE (opcode)</a>
</li>
      <li><a href="library/imp.html#imp.load_compiled">load_compiled() (in module imp)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_CONST">LOAD_CONST (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_default_certs">load_default_certs() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_DEREF">LOAD_DEREF (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_dh_params">load_dh_params() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/imp.html#imp.load_dynamic">load_dynamic() (in module imp)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.load_extension">load_extension() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_FAST">LOAD_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_GLOBAL">LOAD_GLOBAL (opcode)</a>
</li>
      <li><a href="library/pickle.html#index-4">load_global() (pickle protocol)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_LOCALS">LOAD_LOCALS (opcode)</a>
</li>
      <li>
    load_module

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">loader</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.load_module">load_module() (in module imp)</a>

      <ul>
        <li><a href="library/zipimport.html#zipimport.zipimporter.load_module">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LOAD_NAME">LOAD_NAME (opcode)</a>
</li>
      <li><a href="library/imp.html#imp.load_source">load_source() (in module imp)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_verify_locations">load_verify_locations() (ssl.SSLContext method)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-44">loader</a>, <a href="glossary.html#term-loader"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">load_module</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.LoadError">LoadError</a>
</li>
      <li><a href="library/_winreg.html#_winreg.LoadKey">LoadKey() (in module _winreg)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.LibraryLoader.LoadLibrary">LoadLibrary() (ctypes.LibraryLoader method)</a>
</li>
      <li><a href="library/json.html#json.loads">loads() (in module json)</a>

      <ul>
        <li><a href="library/marshal.html#marshal.loads">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.loads">(in module pickle)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.loads">(in module xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromModule">loadTestsFromModule() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromName">loadTestsFromName() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromNames">loadTestsFromNames() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromTestCase">loadTestsFromTestCase() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/threading.html#threading.local">local (class in threading)</a>
</li>
      <li><a href="library/decimal.html#decimal.localcontext">localcontext() (in module decimal)</a>
</li>
      <li><a href="library/re.html#re.LOCALE">LOCALE (in module re)</a>
</li>
      <li><a href="library/locale.html#module-locale">locale (module)</a>
</li>
      <li><a href="library/locale.html#locale.localeconv">localeconv() (in module locale)</a>
</li>
      <li><a href="library/calendar.html#calendar.LocaleHTMLCalendar">LocaleHTMLCalendar (class in calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.LocaleTextCalendar">LocaleTextCalendar (class in calendar)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Attr.localName">localName (xml.dom.Attr attribute)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Node.localName">(xml.dom.Node attribute)</a>
</li>
      </ul></li>
      <li>
    locals

      <ul>
        <li><a href="reference/simple_stmts.html#index-58">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#locals">locals() (built-in function)</a>
</li>
      <li><a href="library/time.html#time.localtime">localtime() (in module time)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator">Locator (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Lock">Lock (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.Lock">Lock() (in module threading)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.lock">lock() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.lock">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.lock">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.lock">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.lock">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.lock">(mailbox.mbox method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Lock">Lock() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex.lock">lock() (mutex.mutex method)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.lock">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-13">lock, interpreter</a>
</li>
      <li><a href="library/imp.html#imp.lock_held">lock_held() (in module imp)</a>
</li>
      <li><a href="library/thread.html#thread.lock.locked">locked() (thread.lock method)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.lockf">lockf() (in module fcntl)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.locking">locking() (in module msvcrt)</a>
</li>
      <li><a href="library/thread.html#thread.LockType">LockType (in module thread)</a>
</li>
      <li><a href="library/cmath.html#cmath.log">log() (in module cmath)</a>

      <ul>
        <li><a href="library/logging.html#logging.log">(in module logging)</a>
</li>
        <li><a href="library/math.html#math.log">(in module math)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.log">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.log10">log10() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.log10">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.log10">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.log10">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.log1p">log1p() (in module math)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_date_time_string">log_date_time_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_error">log_error() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.log_exception">log_exception() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_message">log_message() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_request">log_request() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.log_to_stderr">log_to_stderr() (in module multiprocessing)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.logb">logb() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logb">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger">Logger (class in logging)</a>
</li>
      <li><a href="library/logging.html#logging.LoggerAdapter">LoggerAdapter (class in logging)</a>
</li>
      <li>
    logging

      <ul>
        <li><a href="library/logging.html#index-0">Errors</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#module-logging">logging (module)</a>
</li>
      <li><a href="library/logging.config.html#module-logging.config">logging.config (module)</a>
</li>
      <li><a href="library/logging.handlers.html#module-logging.handlers">logging.handlers (module)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Logical">Logical (class in aetypes)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-2">logical line</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.logical_and">logical_and() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_and">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_invert">logical_invert() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_invert">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_or">logical_or() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_or">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_xor">logical_xor() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_xor">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.login">login() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.login">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.login">(smtplib.SMTP method)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.login_cram_md5">login_cram_md5() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/getpass.html#index-0">LOGNAME</a>, <a href="library/os.html#index-2">[1]</a>
</li>
      <li><a href="library/random.html#random.lognormvariate">lognormvariate() (in module random)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.logout">logout() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/logging.html#logging.LogRecord">LogRecord (class in logging)</a>
</li>
      <li>
    long

      <ul>
        <li><a href="c-api/number.html#index-6">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-8">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="library/stdtypes.html#index-17">integer division</a>
</li>
        <li><a href="library/stdtypes.html#index-14">integer literals</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-long">long (2to3 fixer)</a>

      <ul>
        <li><a href="library/functions.html#long">(built-in class)</a>
</li>
      </ul></li>
      <li>
    long integer

      <ul>
        <li><a href="c-api/long.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-12">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">long integer literal</a>
</li>
      <li><a href="library/sys.html#sys.long_info">long_info (in module sys)</a>
</li>
      <li><a href="c-api/int.html#index-2">LONG_MAX</a>, <a href="c-api/long.html#index-2">[1]</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.longMessage">longMessage (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/curses.html#curses.longname">longname() (in module curses)</a>
</li>
      <li><a href="library/types.html#types.LongType">LongType (in module types)</a>

      <ul>
        <li><a href="c-api/long.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.lookup">lookup() (in module codecs)</a>

      <ul>
        <li><a href="library/unicodedata.html#unicodedata.lookup">(in module unicodedata)</a>
</li>
        <li><a href="library/symtable.html#symtable.SymbolTable.lookup">(symtable.SymbolTable method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Style.lookup">(ttk.Style method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.lookup_error">lookup_error() (in module codecs)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.LookupError">LookupError</a>
</li>
      <li>
    loop

      <ul>
        <li><a href="reference/compound_stmts.html#index-9">over mutable sequence</a>
</li>
        <li><a href="reference/compound_stmts.html#index-4">statement</a>, <a href="reference/compound_stmts.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
      </ul></li>
      <li>
    loop control

      <ul>
        <li><a href="reference/simple_stmts.html#index-35">target</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.loop">loop() (in module asyncore)</a>
</li>
      <li><a href="library/string.html#string.lower">lower() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.lower">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.lowercase">lowercase (in module string)</a>
</li>
      <li><a href="library/token.html#token.LPAR">LPAR (in module token)</a>
</li>
      <li><a href="library/os.html#os.lseek">lseek() (in module os)</a>
</li>
      <li><a href="library/operator.html#operator.lshift">lshift() (in module operator)</a>
</li>
      <li><a href="library/token.html#token.LSQB">LSQB (in module token)</a>
</li>
      <li><a href="library/os.html#os.lstat">lstat() (in module os)</a>
</li>
      <li><a href="library/string.html#string.lstrip">lstrip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.lstrip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.lsub">lsub() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/operator.html#operator.lt">lt() (in module operator)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.lt">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">Lundh, Fredrik</a>
</li>
      <li><a href="library/cookielib.html#cookielib.LWPCookieJar">LWPCookieJar (class in cookielib)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="M">M</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.M">M (in module re)</a>
</li>
      <li><a href="library/platform.html#platform.mac_ver">mac_ver() (in module platform)</a>
</li>
      <li>
    macerrors

      <ul>
        <li><a href="library/macos.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/undoc.html#module-macerrors">macerrors (module)</a>
</li>
      <li><a href="library/platform.html#platform.machine">machine() (in module platform)</a>
</li>
      <li><a href="library/macos.html#module-MacOS">MacOS (module)</a>
</li>
      <li><a href="library/macostools.html#module-macostools">macostools (module)</a>
</li>
      <li><a href="library/macpath.html#module-macpath">macpath (module)</a>
</li>
      <li><a href="library/undoc.html#module-macresource">macresource (module)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.macros">macros (netrc.netrc attribute)</a>
</li>
      <li>
    mailbox

      <ul>
        <li><a href="library/rfc822.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Mailbox">Mailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#module-mailbox">mailbox (module)</a>
</li>
      <li><a href="library/mailcap.html#module-mailcap">mailcap (module)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir">Maildir (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage">MaildirMessage (class in mailbox)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.MailmanProxy">MailmanProxy (class in smtpd)</a>
</li>
      <li><a href="c-api/init.html#index-1">main()</a>, <a href="c-api/init.html#index-10">[1]</a>

      <ul>
        <li><a href="library/py_compile.html#py_compile.main">(in module py_compile)</a>
</li>
        <li><a href="library/unittest.html#unittest.main">(in module unittest)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.mainloop">mainloop() (FrameWork.Application method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.mainloop">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.major">major() (in module os)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_archive">make_archive() (in module distutils.archive_util)</a>

      <ul>
        <li><a href="library/shutil.html#shutil.make_archive">(in module shutil)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-MAKE_CLOSURE">MAKE_CLOSURE (opcode)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.make_cookies">make_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/fl.html#fl.make_form">make_form() (in module fl)</a>
</li>
      <li><a href="library/dis.html#opcode-MAKE_FUNCTION">MAKE_FUNCTION (opcode)</a>
</li>
      <li><a href="library/email.header.html#email.header.make_header">make_header() (in module email.header)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.make_msgid">make_msgid() (in module email.utils)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.make_parser">make_parser() (in module xml.sax)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.make_server">make_server() (in module wsgiref.simple_server)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_tarball">make_tarball() (in module distutils.archive_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_zipfile">make_zipfile() (in module distutils.archive_util)</a>
</li>
      <li><a href="library/os.html#os.makedev">makedev() (in module os)</a>
</li>
      <li><a href="library/os.html#os.makedirs">makedirs() (in module os)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.makeelement">makeelement() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="reference/datamodel.html#index-58">makefile() (socket method)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.makefile">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.MH.makefolder">makefolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/logging.html#logging.makeLogRecord">makeLogRecord() (in module logging)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.makePickle">makePickle() (logging.handlers.SocketHandler method)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.makeRecord">makeRecord() (logging.Logger method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.makeSocket">makeSocket() (logging.handlers.DatagramHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.makeSocket">(logging.handlers.SocketHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.maketrans">maketrans() (in module string)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.makeusermenus">makeusermenus() (FrameWork.Application method)</a>
</li>
      <li><a href="c-api/memory.html#index-0">malloc()</a>
</li>
      <li>
    mangling

      <ul>
        <li><a href="reference/expressions.html#index-7">name</a>, <a href="tutorial/classes.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-map">map (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#map">map() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.map">(in module future_builtins)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Style.map">(ttk.Style method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map_async">map_async() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.map_table_b2">map_table_b2() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.map_table_b3">map_table_b3() (in module stringprep)</a>
</li>
      <li><a href="library/fl.html#fl.mapcolor">mapcolor() (in module fl)</a>
</li>
      <li><a href="library/ic.html#ic.IC.mapfile">mapfile() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.mapfile">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler.mapLogRecord">mapLogRecord() (logging.handlers.HTTPHandler method)</a>
</li>
      <li><a href="glossary.html#term-mapping"><strong>mapping</strong></a>

      <ul>
        <li><a href="c-api/concrete.html#index-2">object</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/expressions.html#index-32">[4]</a>, <a href="reference/simple_stmts.html#index-12">[5]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">types, operations on</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Mapping">Mapping (class in collections)</a>
</li>
      <li><a href="library/msilib.html#msilib.Control.mapping">mapping() (msilib.Control method)</a>
</li>
      <li><a href="library/collections.html#collections.MappingView">MappingView (class in collections)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.mapPriority">mapPriority() (logging.handlers.SysLogHandler method)</a>
</li>
      <li><a href="library/nis.html#nis.maps">maps() (in module nis)</a>
</li>
      <li><a href="library/ic.html#ic.IC.maptypecreator">maptypecreator() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.maptypecreator">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/marshal.html#module-marshal">marshal (module)</a>
</li>
      <li>
    marshalling

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li>
    masking

      <ul>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
      </ul></li>
      <li><a href="library/nis.html#nis.match">match() (in module nis)</a>

      <ul>
        <li><a href="library/re.html#re.match">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.match">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.match_hostname">match_hostname() (in module ssl)</a>
</li>
      <li><a href="library/re.html#re.MatchObject">MatchObject (class in re)</a>
</li>
      <li>
    math

      <ul>
        <li><a href="library/cmath.html#index-0">module</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      </ul></li>
      <li><a href="library/math.html#module-math">math (module)</a>
</li>
      <li>
    max

      <ul>
        <li><a href="library/stdtypes.html#index-22">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.max">max (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.max">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.max">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.max">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#max">max() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.max">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.max">(decimal.Decimal method)</a>
</li>
        <li><a href="library/audioop.html#audioop.max">(in module audioop)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.MAX_INTERPOLATION_DEPTH">MAX_INTERPOLATION_DEPTH (in module ConfigParser)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.max_mag">max_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.max_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/repr.html#repr.Repr.maxarray">maxarray (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxdeque">maxdeque (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxdict">maxdict (repr.Repr attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.maxDiff">maxDiff (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxfrozenset">maxfrozenset (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxint">maxint (in module sys)</a>
</li>
      <li><a href="library/collections.html#collections.deque.maxlen">maxlen (collections.deque attribute)</a>
</li>
      <li><a href="library/mimify.html#mimify.MAXLEN">MAXLEN (in module mimify)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlevel">maxlevel (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlist">maxlist (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlong">maxlong (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxother">maxother (repr.Repr attribute)</a>
</li>
      <li><a href="library/audioop.html#audioop.maxpp">maxpp() (in module audioop)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxset">maxset (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxsize">maxsize (in module sys)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxstring">maxstring (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxtuple">maxtuple (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxunicode">maxunicode (in module sys)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.maxval">maxval (EasyDialogs.ProgressBar attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.MAXYEAR">MAXYEAR (in module datetime)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONASTERISK">MB_ICONASTERISK (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONEXCLAMATION">MB_ICONEXCLAMATION (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONHAND">MB_ICONHAND (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONQUESTION">MB_ICONQUESTION (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_OK">MB_OK (in module winsound)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mbox">mbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage">mboxMessage (class in mailbox)</a>
</li>
      <li><a href="library/md5.html#module-md5">md5 (module)</a>
</li>
      <li><a href="library/md5.html#md5.md5">md5() (in module md5)</a>
</li>
      <li><a href="library/types.html#types.MemberDescriptorType">MemberDescriptorType (in module types)</a>
</li>
      <li>
    membership

      <ul>
        <li><a href="reference/expressions.html#index-67">test</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.memmove">memmove() (in module ctypes)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.MemoryError">MemoryError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler">MemoryHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview">memoryview (built-in class)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.memset">memset() (in module ctypes)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Menu">Menu() (in module FrameWork)</a>
</li>
      <li><a href="library/framework.html#FrameWork.MenuBar">MenuBar() (in module FrameWork)</a>
</li>
      <li><a href="library/framework.html#FrameWork.MenuItem">MenuItem() (in module FrameWork)</a>
</li>
      <li><a href="library/heapq.html#heapq.merge">merge() (in module heapq)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message">Message (class in email.message)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Message">(class in mailbox)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.Message">(class in mhlib)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.Message">(class in mimetools)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.Message">(class in rfc822)</a>
</li>
        <li><a href="library/basehttpserver.html#index-1">(in module mimetools)</a>
</li>
      </ul></li>
      <li><a href="library/hashlib.html#index-0">message digest, MD5</a>, <a href="library/md5.html#index-0">[1]</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.Message">Message() (in module EasyDialogs)</a>
</li>
      <li><a href="library/email.parser.html#email.message_from_file">message_from_file() (in module email)</a>
</li>
      <li><a href="library/email.parser.html#email.message_from_string">message_from_string() (in module email)</a>
</li>
      <li><a href="library/winsound.html#winsound.MessageBeep">MessageBeep() (in module winsound)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.MessageClass">MessageClass (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MessageError">MessageError</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MessageParseError">MessageParseError</a>
</li>
      <li><a href="library/curses.html#curses.meta">meta() (in module curses)</a>
</li>
      <li><a href="library/sys.html#sys.meta_path">meta_path (in module sys)</a>
</li>
      <li><a href="glossary.html#term-metaclass"><strong>metaclass</strong></a>

      <ul>
        <li><a href="library/2to3.html#2to3fixer-metaclass">(2to3 fixer)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.metavar">metavar (optparse.Option attribute)</a>
</li>
      <li><a href="library/tix.html#Tix.Meter">Meter (class in Tix)</a>
</li>
      <li><a href="c-api/structures.html#METH_CLASS">METH_CLASS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_COEXIST">METH_COEXIST (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_KEYWORDS">METH_KEYWORDS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_NOARGS">METH_NOARGS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_O">METH_O (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_OLDARGS">METH_OLDARGS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_STATIC">METH_STATIC (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_VARARGS">METH_VARARGS (built-in variable)</a>
</li>
      <li><a href="glossary.html#term-method"><strong>method</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-45">built-in</a>
</li>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="c-api/method.html#index-0">object</a>, <a href="library/stdtypes.html#index-38">[1]</a>, <a href="reference/datamodel.html#index-38">[2]</a>, <a href="reference/datamodel.html#index-45">[3]</a>, <a href="reference/expressions.html#index-43">[4]</a>, <a href="tutorial/classes.html#index-0">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-38">user-defined</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-method-resolution-order"><strong>method resolution order</strong></a>
</li>
      <li><a href="library/2to3.html#2to3fixer-methodattrs">methodattrs (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.methodcaller">methodcaller() (in module operator)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.methodHelp">methodHelp() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li>
    methods

      <ul>
        <li><a href="library/stdtypes.html#index-23">string</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.methods">methods (pyclbr.Class attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.methodSignature">methodSignature() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li><a href="c-api/function.html#index-1">MethodType (in module types)</a>, <a href="c-api/method.html#index-1">[1]</a>, <a href="library/types.html#types.MethodType">[2]</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH">MH (class in mailbox)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH">(class in mhlib)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#module-mhlib">mhlib (module)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMailbox">MHMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage">MHMessage (class in mailbox)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.microsecond">microsecond (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.microsecond">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li>
    MIME

      <ul>
        <li><a href="library/base64.html#index-0">base64 encoding</a>
</li>
        <li><a href="library/mimetypes.html#index-0">content type</a>
</li>
        <li><a href="library/cgi.html#index-0">headers</a>, <a href="library/mimetypes.html#index-1">[1]</a>
</li>
        <li><a href="library/quopri.html#index-0">quoted-printable encoding</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#mimify.mime_decode_header">mime_decode_header() (in module mimify)</a>
</li>
      <li><a href="library/mimify.html#mimify.mime_encode_header">mime_encode_header() (in module mimify)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.application.MIMEApplication">MIMEApplication (class in email.mime.application)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.audio.MIMEAudio">MIMEAudio (class in email.mime.audio)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.base.MIMEBase">MIMEBase (class in email.mime.base)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.image.MIMEImage">MIMEImage (class in email.mime.image)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.message.MIMEMessage">MIMEMessage (class in email.mime.message)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.multipart.MIMEMultipart">MIMEMultipart (class in email.mime.multipart)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.nonmultipart.MIMENonMultipart">MIMENonMultipart (class in email.mime.nonmultipart)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.text.MIMEText">MIMEText (class in email.mime.text)</a>
</li>
      <li>
    mimetools

      <ul>
        <li><a href="library/urllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/mimetools.html#module-mimetools">mimetools (module)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes">MimeTypes (class in mimetypes)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/mimetypes.html#module-mimetypes">mimetypes (module)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter">MimeWriter (class in MimeWriter)</a>

      <ul>
        <li><a href="library/mimewriter.html#module-MimeWriter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#module-mimify">mimify (module)</a>
</li>
      <li><a href="library/mimify.html#mimify.mimify">mimify() (in module mimify)</a>
</li>
      <li>
    min

      <ul>
        <li><a href="library/stdtypes.html#index-22">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.min">min (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.min">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.min">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.min">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#min">min() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.min">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.min">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.min_mag">min_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.min_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.MINEQUAL">MINEQUAL (in module token)</a>
</li>
      <li><a href="library/miniaeframe.html#module-MiniAEFrame">MiniAEFrame (module)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.MiniApplication">MiniApplication (class in MiniAEFrame)</a>
</li>
      <li><a href="library/audioop.html#audioop.minmax">minmax() (in module audioop)</a>
</li>
      <li><a href="library/os.html#os.minor">minor() (in module os)</a>
</li>
      <li><a href="reference/expressions.html#index-48">minus</a>
</li>
      <li><a href="library/token.html#token.MINUS">MINUS (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.minus">minus() (decimal.Context method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.minute">minute (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.minute">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.MINYEAR">MINYEAR (in module datetime)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.mirrored">mirrored() (in module unicodedata)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.misc_header">misc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.MissingSectionHeaderError">MissingSectionHeaderError</a>
</li>
      <li><a href="library/ossaudiodev.html#index-1">MIXERDEV</a>
</li>
      <li><a href="library/macostools.html#macostools.mkalias">mkalias() (in module macostools)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.mkd">mkd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/os.html#os.mkdir">mkdir() (in module os)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.mkdtemp">mkdtemp() (in module tempfile)</a>
</li>
      <li><a href="library/os.html#os.mkfifo">mkfifo() (in module os)</a>
</li>
      <li><a href="library/os.html#os.mknod">mknod() (in module os)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.mkpath">mkpath() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.dir_util.mkpath">(in module distutils.dir_util)</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.mkstemp">mkstemp() (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.mktemp">mktemp() (in module tempfile)</a>
</li>
      <li><a href="library/time.html#time.mktime">mktime() (in module time)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.mktime_tz">mktime_tz() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.mktime_tz">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/mmap.html#mmap.mmap">mmap (class in mmap)</a>

      <ul>
        <li><a href="library/mmap.html#module-mmap">(module)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MMDF">MMDF (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MmdfMailbox">MmdfMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MMDFMessage">MMDFMessage (class in mailbox)</a>
</li>
      <li><a href="library/operator.html#operator.mod">mod() (in module operator)</a>
</li>
      <li><a href="library/stdtypes.html#file.mode">mode (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.FileIO.mode">(io.FileIO attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.mode">(ossaudiodev.oss_audio_device attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.mode">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.mode">mode() (in module turtle)</a>
</li>
      <li><a href="library/math.html#math.modf">modf() (in module math)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.modified">modified() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.Modify">Modify() (msilib.View method)</a>
</li>
      <li><a href="library/select.html#select.epoll.modify">modify() (select.epoll method)</a>

      <ul>
        <li><a href="library/select.html#select.poll.modify">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-module"><strong>module</strong></a>

      <ul>
        <li><a href="library/al.html#index-0">AL</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">CGIHTTPServer</a>
</li>
        <li><a href="library/miniaeframe.html#index-0">FrameWork</a>
</li>
        <li><a href="library/sunaudio.html#index-1">SUNAUDIODEV</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">SimpleHTTPServer</a>
</li>
        <li><a href="c-api/init.html#index-0">__builtin__</a>, <a href="c-api/intro.html#index-20">[1]</a>, <a href="reference/simple_stmts.html#index-57">[2]</a>, <a href="reference/toplevel_components.html#index-2">[3]</a>, <a href="tutorial/modules.html#index-7">[4]</a>
</li>
        <li><a href="c-api/init.html#index-0">__main__</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/runpy.html#index-0">[3]</a>, <a href="library/runpy.html#index-3">[4]</a>, <a href="reference/executionmodel.html#index-11">[5]</a>, <a href="reference/toplevel_components.html#index-2">[6]</a>, <a href="reference/toplevel_components.html#index-3">[7]</a>
</li>
        <li><a href="library/locale.html#index-0">_locale</a>
</li>
        <li><a href="reference/datamodel.html#index-28">array</a>
</li>
        <li><a href="library/binascii.html#index-0">base64</a>
</li>
        <li><a href="library/pdb.html#index-1">bdb</a>
</li>
        <li><a href="library/binascii.html#index-0">binhex</a>
</li>
        <li><a href="library/anydbm.html#index-0">bsddb</a>, <a href="library/dbhash.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
        <li><a href="c-api/init.html#index-21">builtins</a>
</li>
        <li><a href="library/copy_reg.html#index-0">cPickle</a>
</li>
        <li><a href="library/pdb.html#index-1">cmd</a>
</li>
        <li><a href="tutorial/modules.html#index-3">compileall</a>
</li>
        <li><a href="library/copy_reg.html#index-0">copy</a>
</li>
        <li><a href="library/pwd.html#index-0">crypt</a>
</li>
        <li><a href="library/anydbm.html#index-0">dbhash</a>
</li>
        <li><a href="library/anydbm.html#index-0">dbm</a>, <a href="library/gdbm.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
        <li><a href="library/anydbm.html#index-0">dumbdbm</a>
</li>
        <li><a href="library/exceptions.html#index-3">errno</a>, <a href="library/socket.html#index-2">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-20">exceptions</a>
</li>
        <li><a href="reference/datamodel.html#index-4">extension</a>
</li>
        <li><a href="library/stdtypes.html#index-35">fcntl</a>
</li>
        <li><a href="library/htmllib.html#index-1">formatter</a>
</li>
        <li><a href="library/anydbm.html#index-0">gdbm</a>, <a href="library/shelve.html#index-1">[1]</a>, <a href="reference/datamodel.html#index-34">[2]</a>
</li>
        <li><a href="library/fnmatch.html#index-2">glob</a>
</li>
        <li><a href="library/urllib.html#index-9">htmllib</a>
</li>
        <li><a href="library/ic.html#index-0">icglue</a>
</li>
        <li><a href="c-api/import.html#index-2">ihooks</a>
</li>
        <li><a href="library/functions.html#index-8">imp</a>
</li>
        <li><a href="reference/simple_stmts.html#index-38">importing</a>
</li>
        <li><a href="tutorial/inputoutput.html#index-1">json</a>
</li>
        <li><a href="library/imp.html#index-5">knee</a>, <a href="library/imputil.html#index-1">[1]</a>
</li>
        <li><a href="library/macos.html#index-0">macerrors</a>
</li>
        <li><a href="library/rfc822.html#index-3">mailbox</a>
</li>
        <li><a href="library/cmath.html#index-0">math</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
        <li><a href="library/urllib.html#index-1">mimetools</a>
</li>
        <li><a href="reference/datamodel.html#index-49">namespace</a>
</li>
        <li><a href="c-api/module.html#index-0">object</a>, <a href="reference/datamodel.html#index-47">[1]</a>, <a href="reference/expressions.html#index-30">[2]</a>
</li>
        <li><a href="library/posix.html#index-0">os</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/copy.html#index-0">pickle</a>, <a href="library/copy_reg.html#index-0">[1]</a>, <a href="library/marshal.html#index-0">[2]</a>, <a href="library/pickle.html#index-5">[3]</a>, <a href="library/shelve.html#index-0">[4]</a>
</li>
        <li><a href="library/os.html#index-12">pty</a>
</li>
        <li><a href="library/os.path.html#index-1">pwd</a>
</li>
        <li><a href="library/pyexpat.html#index-1">pyexpat</a>
</li>
        <li><a href="library/fnmatch.html#index-1">re</a>, <a href="library/stdtypes.html#index-27">[1]</a>, <a href="library/string.html#index-0">[2]</a>
</li>
        <li><a href="tutorial/interactive.html#index-0">readline</a>
</li>
        <li><a href="c-api/import.html#index-2">rexec</a>
</li>
        <li><a href="library/mimetools.html#index-0">rfc822</a>
</li>
        <li><a href="tutorial/interactive.html#index-0">rlcompleter</a>
</li>
        <li><a href="c-api/init.html#index-0">search path</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
        <li><a href="library/htmllib.html#index-1">sgmllib</a>
</li>
        <li><a href="library/marshal.html#index-0">shelve</a>
</li>
        <li><a href="c-api/exceptions.html#index-2">signal</a>, <a href="library/thread.html#index-2">[1]</a>
</li>
        <li><a href="library/site.html#index-3">sitecustomize</a>
</li>
        <li><a href="library/internet.html#index-1">socket</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/os.html#index-16">stat</a>
</li>
        <li><a href="library/os.html#index-17">statvfs</a>
</li>
        <li><a href="library/locale.html#index-7">string</a>, <a href="library/locale.html#index-8">[1]</a>, <a href="library/stdtypes.html#index-27">[2]</a>
</li>
        <li><a href="library/socket.html#index-4">struct</a>
</li>
        <li><a href="library/sunaudio.html#index-2">sunaudiodev</a>
</li>
        <li><a href="c-api/init.html#index-0">sys</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/simple_stmts.html#index-24">[4]</a>, <a href="reference/toplevel_components.html#index-2">[5]</a>, <a href="tutorial/modules.html#index-4">[6]</a>
</li>
        <li><a href="c-api/init.html#index-20">thread</a>
</li>
        <li><a href="library/stdtypes.html#index-42">types</a>
</li>
        <li><a href="library/httplib.html#index-1">urllib</a>
</li>
        <li><a href="library/urllib.html#index-11">urlparse</a>
</li>
        <li><a href="library/site.html#index-4">usercustomize</a>
</li>
        <li><a href="library/binascii.html#index-0">uu</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.module">module (pyclbr.Class attribute)</a>

      <ul>
        <li><a href="library/pyclbr.html#pyclbr.Function.module">(pyclbr.Function attribute)</a>
</li>
      </ul></li>
      <li><a href="library/new.html#new.module">module() (in module new)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ModuleFinder">ModuleFinder (class in modulefinder)</a>
</li>
      <li><a href="library/modulefinder.html#module-modulefinder">modulefinder (module)</a>
</li>
      <li><a href="c-api/import.html#index-0">modules (in module sys)</a>, <a href="c-api/init.html#index-0">[1]</a>, <a href="library/sys.html#sys.modules">[2]</a>

      <ul>
        <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.modules">(modulefinder.ModuleFinder attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/module.html#index-1">ModuleType (in module types)</a>, <a href="library/types.html#types.ModuleType">[1]</a>
</li>
      <li><a href="reference/expressions.html#index-55">modulo</a>
</li>
      <li><a href="library/imageop.html#imageop.mono2grey">mono2grey() (in module imageop)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.month">month (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.month">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.month">month() (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.month_abbr">month_abbr (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.month_name">month_name (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.monthcalendar">monthcalendar() (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdatescalendar">monthdatescalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdays2calendar">monthdays2calendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdayscalendar">monthdayscalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.monthrange">monthrange() (in module calendar)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel">Morsel (class in Cookie)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.most_common">most_common() (collections.Counter method)</a>
</li>
      <li><a href="library/curses.html#curses.mouseinterval">mouseinterval() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.mousemask">mousemask() (in module curses)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.move">move() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/curses.html#curses.window.move">(curses.window method)</a>
</li>
        <li><a href="library/macostools.html#findertools.move">(in module findertools)</a>
</li>
        <li><a href="library/shutil.html#shutil.move">(in module shutil)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.move">(mmap.mmap method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.move">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.move_file">move_file() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.file_util.move_file">(in module distutils.file_util)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.movemessage">movemessage() (mhlib.Folder method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.MozillaCookieJar">MozillaCookieJar (class in cookielib)</a>
</li>
      <li><a href="glossary.html#term-mro"><strong>MRO</strong></a>
</li>
      <li><a href="library/stdtypes.html#class.mro">mro() (class method)</a>
</li>
      <li><a href="library/cd.html#cd.msftoframe">msftoframe() (in module cd)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.msg">msg (httplib.HTTPResponse attribute)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.msg">msg() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/msilib.html#index-0">msi</a>
</li>
      <li><a href="library/msilib.html#module-msilib">msilib (module)</a>
</li>
      <li><a href="library/msvcrt.html#module-msvcrt">msvcrt (module)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.mt_interact">mt_interact() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.mtime">mtime (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.mtime">mtime() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/audioop.html#audioop.mul">mul() (in module audioop)</a>

      <ul>
        <li><a href="library/operator.html#operator.mul">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.MultiCall">MultiCall (class in xmlrpclib)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile">MultiFile (class in multifile)</a>
</li>
      <li><a href="library/multifile.html#module-multifile">multifile (module)</a>
</li>
      <li><a href="library/re.html#re.MULTILINE">MULTILINE (in module re)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MultipartConversionError">MultipartConversionError</a>
</li>
      <li><a href="reference/expressions.html#index-53">multiplication</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.multiply">multiply() (decimal.Context method)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing">multiprocessing (module)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.connection">multiprocessing.connection (module)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.dummy">multiprocessing.dummy (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.multiprocessing.Manager">multiprocessing.Manager() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.managers">multiprocessing.managers (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool">multiprocessing.Pool (class in multiprocessing.pool)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.pool">multiprocessing.pool (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue">multiprocessing.queues.SimpleQueue (class in multiprocessing)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.sharedctypes">multiprocessing.sharedctypes (module)</a>
</li>
      <li><a href="glossary.html#term-mutable"><strong>mutable</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-25">object</a>, <a href="reference/simple_stmts.html#index-10">[1]</a>, <a href="reference/simple_stmts.html#index-3">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-29">sequence types</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">mutable object</a>
</li>
      <li>
    mutable sequence

      <ul>
        <li><a href="reference/compound_stmts.html#index-9">loop over</a>
</li>
        <li><a href="reference/datamodel.html#index-25">object</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.MutableMapping">MutableMapping (class in collections)</a>
</li>
      <li><a href="library/collections.html#collections.MutableSequence">MutableSequence (class in collections)</a>
</li>
      <li><a href="library/collections.html#collections.MutableSet">MutableSet (class in collections)</a>
</li>
      <li><a href="library/userdict.html#UserString.MutableString">MutableString (class in UserString)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex">mutex (class in mutex)</a>

      <ul>
        <li><a href="library/mutex.html#module-mutex">(module)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.mvderwin">mvderwin() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.mvwin">mvwin() (curses.window method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.myrights">myrights() (imaplib.IMAP4 method)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="N">N</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/token.html#token.N_TOKENS">N_TOKENS (in module token)</a>
</li>
      <li><a href="reference/executionmodel.html#index-2">name</a>, <a href="reference/expressions.html#index-5">[1]</a>, <a href="reference/lexical_analysis.html#index-9">[2]</a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">binding</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/executionmodel.html#index-2">[2]</a>, <a href="reference/simple_stmts.html#index-3">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>, <a href="reference/simple_stmts.html#index-48">[5]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-54">binding, global</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">class</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">function</a>
</li>
        <li><a href="reference/expressions.html#index-7">mangling</a>, <a href="tutorial/classes.html#index-1">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-3">rebinding</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">unbinding</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.name">name (cookielib.Cookie attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.name">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/stdtypes.html#file.name">(file attribute)</a>
</li>
        <li><a href="library/os.html#os.name">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.NAME">NAME (in module token)</a>
</li>
      <li><a href="library/io.html#io.FileIO.name">name (io.FileIO attribute)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.name">(multiprocessing.Process attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.name">(ossaudiodev.oss_audio_device attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Class.name">(pyclbr.Class attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Function.name">(pyclbr.Function attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.name">(tarfile.TarInfo attribute)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.name">(threading.Thread attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Attr.name">(xml.dom.Attr attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.DocumentType.name">(xml.dom.DocumentType attribute)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.name">name() (in module unicodedata)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.name2codepoint">name2codepoint (in module htmlentitydefs)</a>
</li>
      <li><a href="glossary.html#term-named-tuple"><strong>named tuple</strong></a>
</li>
      <li><a href="library/tempfile.html#tempfile.NamedTemporaryFile">NamedTemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/collections.html#collections.namedtuple">namedtuple() (in module collections)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.NameError">NameError</a>

      <ul>
        <li><a href="reference/expressions.html#index-6">exception</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-8">NameError (built-in exception)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.namelist">namelist() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.nameprep">nameprep() (in module encodings.idna)</a>
</li>
      <li>
    names

      <ul>
        <li><a href="reference/expressions.html#index-7">private</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-1">namespace</a>, <a href="glossary.html#term-namespace"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">global</a>
</li>
        <li><a href="reference/datamodel.html#index-49">module</a>
</li>
      </ul></li>
      <li><a href="library/argparse.html#argparse.Namespace">Namespace (class in argparse)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.Namespace">(class in multiprocessing.managers)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.namespace">namespace() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Namespace">Namespace() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_DNS">NAMESPACE_DNS (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_OID">NAMESPACE_OID (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_URL">NAMESPACE_URL (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_X500">NAMESPACE_X500 (in module uuid)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NamespaceErr">NamespaceErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.namespaceURI">namespaceURI (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/functions.html#index-2">NaN</a>, <a href="library/string.html#index-6">[1]</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.NannyNag">NannyNag</a>
</li>
      <li><a href="library/curses.html#curses.napms">napms() (in module curses)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.nargs">nargs (optparse.Option attribute)</a>
</li>
      <li><a href="library/undoc.html#module-Nav">Nav (module)</a>
</li>
      <li><a href="library/easydialogs.html#index-0">Navigation Services</a>
</li>
      <li><a href="library/difflib.html#difflib.ndiff">ndiff() (in module difflib)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.ndim">ndim (memoryview attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-ne">ne (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.ne">ne() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.neg">neg() (in module operator)</a>
</li>
      <li><a href="reference/expressions.html#index-48">negation</a>
</li>
      <li><a href="glossary.html#term-nested-scope"><strong>nested scope</strong></a>
</li>
      <li><a href="library/contextlib.html#contextlib.nested">nested() (in module contextlib)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc">netrc (class in netrc)</a>

      <ul>
        <li><a href="library/netrc.html#module-netrc">(module)</a>
</li>
      </ul></li>
      <li><a href="library/netrc.html#netrc.NetrcParseError">NetrcParseError</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.netscape">netscape (cookielib.CookiePolicy attribute)</a>
</li>
      <li><a href="library/nntplib.html#index-0">Network News Transfer Protocol</a>
</li>
      <li><a href="library/new.html#module-new">new (module)</a>
</li>
      <li><a href="library/hmac.html#hmac.new">new() (in module hmac)</a>

      <ul>
        <li><a href="library/md5.html#md5.new">(in module md5)</a>
</li>
        <li><a href="library/sha.html#sha.new">(in module sha)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-new-style-class"><strong>new-style class</strong></a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_alignment">new_alignment() (formatter.writer method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.new_compiler">new_compiler() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_font">new_font() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_margin">new_margin() (formatter.writer method)</a>
</li>
      <li><a href="library/imp.html#imp.new_module">new_module() (in module imp)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.new_panel">new_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_spacing">new_spacing() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_styles">new_styles() (formatter.writer method)</a>
</li>
      <li><a href="library/al.html#al.newconfig">newconfig() (in module al)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer">newer() (in module distutils.dep_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer_group">newer_group() (in module distutils.dep_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer_pairwise">newer_pairwise() (in module distutils.dep_util)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.newgroups">newgroups() (nntplib.NNTP method)</a>
</li>
      <li>
    newline

      <ul>
        <li><a href="reference/simple_stmts.html#index-23">suppression</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.NEWLINE">NEWLINE (in module token)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-2">NEWLINE token</a>, <a href="reference/lexical_analysis.html#index-2">[1]</a>
</li>
      <li><a href="library/stdtypes.html#file.newlines">newlines (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.newlines">(io.TextIOBase attribute)</a>
</li>
      </ul></li>
      <li><a href="library/nntplib.html#nntplib.NNTP.newnews">newnews() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/curses.html#curses.newpad">newpad() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.newwin">newwin() (in module curses)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-next">next (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.next">next() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/functions.html#next">(built-in function)</a>
</li>
        <li><a href="library/csv.html#csv.csvreader.next">(csv.csvreader method)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.dbhash.next">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/stdtypes.html#file.next">(file method)</a>
</li>
        <li><a href="reference/expressions.html#generator.next">(generator method)</a>
</li>
        <li><a href="library/stdtypes.html#iterator.next">(iterator method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.oldmailbox.next">(mailbox.oldmailbox method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.next">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.next">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.next">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.next">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_minus">next_minus() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_minus">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_plus">next_plus() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_plus">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_toward">next_toward() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_toward">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.nextfile">nextfile() (in module fileinput)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.nextkey">nextkey() (in module gdbm)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.nextpart">nextpart() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nextSibling">nextSibling (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ngettext">ngettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ngettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.ngettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.nice">nice() (in module os)</a>
</li>
      <li><a href="library/nis.html#module-nis">nis (module)</a>
</li>
      <li><a href="library/sha.html#index-0">NIST</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/tokenize.html#tokenize.NL">NL (in module tokenize)</a>
</li>
      <li><a href="library/curses.html#curses.nl">nl() (in module curses)</a>
</li>
      <li><a href="library/locale.html#locale.nl_langinfo">nl_langinfo() (in module locale)</a>
</li>
      <li><a href="library/heapq.html#heapq.nlargest">nlargest() (in module heapq)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.nlst">nlst() (ftplib.FTP method)</a>
</li>
      <li>
    NNTP

      <ul>
        <li><a href="library/nntplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/nntplib.html#nntplib.NNTP">NNTP (class in nntplib)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPDataError">NNTPDataError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPError">NNTPError</a>
</li>
      <li><a href="library/nntplib.html#module-nntplib">nntplib (module)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPPermanentError">NNTPPermanentError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPProtocolError">NNTPProtocolError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPReplyError">NNTPReplyError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPTemporaryError">NNTPTemporaryError</a>
</li>
      <li><a href="library/urllib.html#index-4">no_proxy</a>, <a href="library/urllib.html#index-6">[1]</a>
</li>
      <li><a href="library/curses.html#curses.nocbreak">nocbreak() (in module curses)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NoDataAllowedErr">NoDataAllowedErr</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node">Node (class in compiler.ast)</a>
</li>
      <li><a href="library/platform.html#platform.node">node() (in module platform)</a>
</li>
      <li><a href="library/curses.html#curses.window.nodelay">nodelay() (curses.window method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeName">nodeName (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/ast.html#ast.NodeTransformer">NodeTransformer (class in ast)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeType">nodeType (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeValue">nodeValue (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/ast.html#ast.NodeVisitor">NodeVisitor (class in ast)</a>
</li>
      <li><a href="library/cd.html#cd.NODISC">NODISC (in module cd)</a>
</li>
      <li><a href="library/curses.html#curses.noecho">noecho() (in module curses)</a>
</li>
      <li><a href="library/locale.html#locale.NOEXPR">NOEXPR (in module locale)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.nofill">nofill (htmllib.HTMLParser attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.nok_builtin_names">nok_builtin_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/pickle.html#pickle.Unpickler.noload">noload() (pickle.Unpickler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NoModificationAllowedErr">NoModificationAllowedErr</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.nonblock">nonblock() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li>
    None

      <ul>
        <li><a href="c-api/none.html#index-0">object</a>, <a href="reference/datamodel.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#index-3">None (Built-in object)</a>

      <ul>
        <li><a href="library/constants.html#None">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.NoneType">NoneType (in module types)</a>
</li>
      <li><a href="library/curses.html#curses.nonl">nonl() (in module curses)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-nonzero">nonzero (2to3 fixer)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.noop">noop() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/poplib.html#poplib.POP3.noop">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.NoOptionError">NoOptionError</a>
</li>
      <li><a href="library/dis.html#opcode-NOP">NOP (opcode)</a>
</li>
      <li><a href="library/curses.html#curses.noqiflush">noqiflush() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.noraw">noraw() (in module curses)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.normalize">normalize() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.normalize">(decimal.Decimal method)</a>
</li>
        <li><a href="library/locale.html#locale.normalize">(in module locale)</a>
</li>
        <li><a href="library/unicodedata.html#unicodedata.normalize">(in module unicodedata)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Node.normalize">(xml.dom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.NORMALIZE_WHITESPACE">NORMALIZE_WHITESPACE (in module doctest)</a>
</li>
      <li><a href="library/random.html#random.normalvariate">normalvariate() (in module random)</a>
</li>
      <li><a href="library/os.path.html#os.path.normcase">normcase() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.normpath">normpath() (in module os.path)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.NoSectionError">NoSectionError</a>
</li>
      <li><a href="library/mailbox.html#mailbox.NoSuchMailboxError">NoSuchMailboxError</a>
</li>
      <li>
    not

      <ul>
        <li><a href="library/stdtypes.html#index-8">operator</a>, <a href="reference/expressions.html#index-70">[1]</a>
</li>
      </ul></li>
      <li>
    not in

      <ul>
        <li><a href="library/stdtypes.html#index-12">operator</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.not_">not_() (in module operator)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.NotANumber">NotANumber</a>
</li>
      <li><a href="reference/introduction.html#index-0">notation</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler.notationDecl">notationDecl() (xml.sax.handler.DTDHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.NotationDeclHandler">NotationDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.notations">notations (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/httplib.html#httplib.NotConnected">NotConnected</a>
</li>
      <li><a href="library/tix.html#Tix.NoteBook">NoteBook (class in Tix)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook">Notebook (class in ttk)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.NotEmptyError">NotEmptyError</a>
</li>
      <li><a href="library/token.html#token.NOTEQUAL">NOTEQUAL (in module token)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NotFoundErr">NotFoundErr</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notify">notify() (threading.Condition method)</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notify_all">notify_all() (threading.Condition method)</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notifyAll">notifyAll() (threading.Condition method)</a>
</li>
      <li><a href="library/curses.html#curses.window.notimeout">notimeout() (curses.window method)</a>
</li>
      <li>
    NotImplemented

      <ul>
        <li><a href="reference/datamodel.html#index-7">object</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#NotImplemented">NotImplemented (built-in variable)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.NotImplementedError">NotImplementedError</a>
</li>
      <li><a href="library/types.html#types.NotImplementedType">NotImplementedType (in module types)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.NotStandaloneHandler">NotStandaloneHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NotSupportedErr">NotSupportedErr</a>
</li>
      <li><a href="library/curses.html#curses.window.noutrefresh">noutrefresh() (curses.window method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.now">now() (datetime.datetime class method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.NProperty">NProperty (class in aetypes)</a>
</li>
      <li><a href="library/signal.html#signal.NSIG">NSIG (in module signal)</a>
</li>
      <li><a href="library/heapq.html#heapq.nsmallest">nsmallest() (in module heapq)</a>
</li>
      <li><a href="library/token.html#token.NT_OFFSET">NT_OFFSET (in module token)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler">NTEventLogHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socket.html#socket.ntohl">ntohl() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.ntohs">ntohs() (in module socket)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.ntransfercmd">ntransfercmd() (ftplib.FTP method)</a>
</li>
      <li>
    null

      <ul>
        <li><a href="reference/simple_stmts.html#index-17">operation</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.NullFormatter">NullFormatter (class in formatter)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.NullHandler">NullHandler (class in logging)</a>
</li>
      <li><a href="library/imp.html#imp.NullImporter">NullImporter (class in imp)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations">NullTranslations (class in gettext)</a>
</li>
      <li><a href="library/formatter.html#formatter.NullWriter">NullWriter (class in formatter)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">number</a>

      <ul>
        <li><a href="reference/datamodel.html#index-16">complex</a>
</li>
        <li><a href="reference/datamodel.html#index-15">floating point</a>
</li>
      </ul></li>
      <li><a href="library/numbers.html#numbers.Number">Number (class in numbers)</a>
</li>
      <li><a href="library/token.html#token.NUMBER">NUMBER (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.number_class">number_class() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.number_class">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/numbers.html#module-numbers">numbers (module)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational.numerator">numerator (numbers.Rational attribute)</a>
</li>
      <li>
    numeric

      <ul>
        <li><a href="library/stdtypes.html#index-18">conversions</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="c-api/concrete.html#index-0">object</a>, <a href="library/stdtypes.html#index-10">[1]</a>, <a href="library/stdtypes.html#index-13">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/datamodel.html#index-9">[4]</a>
</li>
        <li><a href="library/stdtypes.html#index-16">types, operations on</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">numeric literal</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.numeric">numeric() (in module unicodedata)</a>
</li>
      <li><a href="library/functions.html#index-6">Numerical Python</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-numliterals">numliterals (2to3 fixer)</a>
</li>
      <li><a href="library/gl.html#gl.nurbscurve">nurbscurve() (in module gl)</a>
</li>
      <li><a href="library/gl.html#gl.nurbssurface">nurbssurface() (in module gl)</a>
</li>
      <li><a href="library/gl.html#gl.nvarray">nvarray() (in module gl)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="O">O</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/os.html#os.O_APPEND">O_APPEND (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_ASYNC">O_ASYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_BINARY">O_BINARY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_CREAT">O_CREAT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DIRECT">O_DIRECT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DIRECTORY">O_DIRECTORY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DSYNC">O_DSYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_EXCL">O_EXCL (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_EXLOCK">O_EXLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NDELAY">O_NDELAY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOATIME">O_NOATIME (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOCTTY">O_NOCTTY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOFOLLOW">O_NOFOLLOW (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOINHERIT">O_NOINHERIT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NONBLOCK">O_NONBLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RANDOM">O_RANDOM (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RDONLY">O_RDONLY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RDWR">O_RDWR (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RSYNC">O_RSYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SEQUENTIAL">O_SEQUENTIAL (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SHLOCK">O_SHLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SHORT_LIVED">O_SHORT_LIVED (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SYNC">O_SYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TEMPORARY">O_TEMPORARY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TEXT">O_TEXT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TRUNC">O_TRUNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_WRONLY">O_WRONLY (in module os)</a>
</li>
      <li><a href="reference/datamodel.html#index-0">object</a>, <a href="glossary.html#term-object"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-13">Boolean</a>, <a href="reference/datamodel.html#index-13">[1]</a>
</li>
        <li><a href="c-api/cobject.html#index-0">CObject</a>
</li>
        <li><a href="c-api/capsule.html#index-0">Capsule</a>
</li>
        <li><a href="reference/datamodel.html#index-8">Ellipsis</a>
</li>
        <li><a href="c-api/none.html#index-0">None</a>, <a href="reference/datamodel.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-7">NotImplemented</a>
</li>
        <li><a href="library/stdtypes.html#index-21">Unicode</a>
</li>
        <li><a href="c-api/buffer.html#index-0">buffer</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-44">built-in function</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-45">built-in method</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="c-api/bytearray.html#index-0">bytearray</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-35">callable</a>, <a href="reference/expressions.html#index-38">[1]</a>
</li>
        <li><a href="c-api/class.html#index-0">class</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-46">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/expressions.html#index-44">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-46">class instance</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-54">[2]</a>, <a href="reference/expressions.html#index-45">[3]</a>
</li>
        <li><a href="c-api/code.html#index-0">code</a>, <a href="library/marshal.html#index-1">[1]</a>, <a href="library/stdtypes.html#index-39">[2]</a>, <a href="reference/datamodel.html#index-60">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-16">complex</a>
</li>
        <li><a href="c-api/complex.html#index-0">complex number</a>, <a href="library/stdtypes.html#index-13">[1]</a>
</li>
        <li><a href="extending/newtypes.html#index-0">deallocation</a>
</li>
        <li><a href="c-api/dict.html#index-0">dictionary</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-33">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/datamodel.html#index-81">[4]</a>, <a href="reference/expressions.html#index-16">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/simple_stmts.html#index-12">[7]</a>
</li>
        <li><a href="c-api/file.html#index-0">file</a>, <a href="library/stdtypes.html#index-34">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/toplevel_components.html#index-8">[3]</a>, <a href="tutorial/inputoutput.html#index-0">[4]</a>
</li>
        <li><a href="extending/newtypes.html#index-0">finalization</a>
</li>
        <li><a href="c-api/float.html#index-0">floating point</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-15">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-64">frame</a>
</li>
        <li><a href="c-api/set.html#index-0">frozenset</a>, <a href="reference/datamodel.html#index-31">[1]</a>
</li>
        <li><a href="c-api/function.html#index-0">function</a>, <a href="reference/compound_stmts.html#index-18">[1]</a>, <a href="reference/datamodel.html#index-36">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-42">[4]</a>, <a href="reference/expressions.html#index-43">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-62">generator</a>, <a href="reference/expressions.html#index-15">[1]</a>, <a href="reference/expressions.html#index-24">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-20">immutable</a>, <a href="reference/expressions.html#index-17">[1]</a>, <a href="reference/expressions.html#index-9">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-20">immutable sequence</a>
</li>
        <li><a href="c-api/class.html#index-2">instance</a>, <a href="reference/datamodel.html#index-46">[1]</a>, <a href="reference/datamodel.html#index-50">[2]</a>, <a href="reference/datamodel.html#index-54">[3]</a>, <a href="reference/expressions.html#index-45">[4]</a>
</li>
        <li><a href="c-api/int.html#index-0">integer</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-10">[2]</a>
</li>
        <li><a href="c-api/list.html#index-0">list</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="library/stdtypes.html#index-29">[2]</a>, <a href="reference/datamodel.html#index-26">[3]</a>, <a href="reference/expressions.html#index-14">[4]</a>, <a href="reference/expressions.html#index-30">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/expressions.html#index-35">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="c-api/long.html#index-0">long integer</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-12">[2]</a>
</li>
        <li><a href="c-api/concrete.html#index-2">mapping</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/expressions.html#index-32">[4]</a>, <a href="reference/simple_stmts.html#index-12">[5]</a>
</li>
        <li><a href="c-api/method.html#index-0">method</a>, <a href="library/stdtypes.html#index-38">[1]</a>, <a href="reference/datamodel.html#index-38">[2]</a>, <a href="reference/datamodel.html#index-45">[3]</a>, <a href="reference/expressions.html#index-43">[4]</a>, <a href="tutorial/classes.html#index-0">[5]</a>
</li>
        <li><a href="c-api/module.html#index-0">module</a>, <a href="reference/datamodel.html#index-47">[1]</a>, <a href="reference/expressions.html#index-30">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">mutable</a>, <a href="reference/simple_stmts.html#index-10">[1]</a>, <a href="reference/simple_stmts.html#index-3">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">mutable sequence</a>
</li>
        <li><a href="c-api/concrete.html#index-0">numeric</a>, <a href="library/stdtypes.html#index-10">[1]</a>, <a href="library/stdtypes.html#index-13">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/datamodel.html#index-9">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-11">plain integer</a>
</li>
        <li><a href="reference/expressions.html#index-20">recursive</a>
</li>
        <li><a href="c-api/concrete.html#index-1">sequence</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/compound_stmts.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-17">[3]</a>, <a href="reference/datamodel.html#index-56">[4]</a>, <a href="reference/expressions.html#index-32">[5]</a>, <a href="reference/expressions.html#index-35">[6]</a>, <a href="reference/expressions.html#index-67">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="c-api/set.html#index-0">set</a>, <a href="library/stdtypes.html#index-31">[1]</a>, <a href="reference/datamodel.html#index-30">[2]</a>, <a href="reference/expressions.html#index-18">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-29">set type</a>
</li>
        <li><a href="reference/datamodel.html#index-89">slice</a>
</li>
        <li><a href="library/socket.html#index-1">socket</a>
</li>
        <li><a href="c-api/string.html#index-0">string</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-21">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>
</li>
        <li><a href="library/sys.html#index-1">traceback</a>, <a href="library/traceback.html#index-0">[1]</a>, <a href="reference/compound_stmts.html#index-11">[2]</a>, <a href="reference/datamodel.html#index-67">[3]</a>, <a href="reference/simple_stmts.html#index-32">[4]</a>
</li>
        <li><a href="c-api/tuple.html#index-0">tuple</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-24">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>, <a href="reference/expressions.html#index-77">[5]</a>
</li>
        <li><a href="c-api/intro.html#index-5">type</a>, <a href="c-api/type.html#index-0">[1]</a>, <a href="library/functions.html#index-7">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">unicode</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">user-defined function</a>, <a href="reference/datamodel.html#index-36">[1]</a>, <a href="reference/expressions.html#index-42">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-38">user-defined method</a>
</li>
        <li><a href="library/stdtypes.html#index-21">xrange</a>, <a href="library/stdtypes.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#object">object (built-in class)</a>

      <ul>
        <li><a href="library/exceptions.html#exceptions.UnicodeError.object">(exceptions.UnicodeError attribute)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.object_filenames">object_filenames() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    objects

      <ul>
        <li><a href="library/stdtypes.html#index-10">comparing</a>
</li>
        <li><a href="library/pickle.html#index-0">flattening</a>
</li>
        <li><a href="library/pickle.html#index-0">marshalling</a>
</li>
        <li><a href="library/pickle.html#index-0">persistent</a>
</li>
        <li><a href="library/pickle.html#index-0">pickling</a>
</li>
        <li><a href="library/pickle.html#index-0">serializing</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.ObjectSpecifier">ObjectSpecifier (class in aetypes)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.obufcount">obufcount() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.obuffree">obuffree() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li>
    oct

      <ul>
        <li><a href="reference/datamodel.html#index-95">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#oct">oct() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.oct">(in module future_builtins)</a>
</li>
      </ul></li>
      <li>
    octal

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">octal literal</a>
</li>
      <li><a href="library/string.html#string.octdigits">octdigits (in module string)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.offset">offset (xml.parsers.expat.ExpatError attribute)</a>
</li>
      <li><a href="library/curses.html#curses.OK">OK (in module curses)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_builtin_modules">ok_builtin_modules (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_file_types">ok_file_types (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_path">ok_path (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_posix_names">ok_posix_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_sys_names">ok_sys_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.OleDLL">OleDLL (class in ctypes)</a>
</li>
      <li><a href="library/turtle.html#turtle.onclick">onclick() (in module turtle)</a>, <a href="library/turtle.html#turtle.onclick">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.ondrag">ondrag() (in module turtle)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.onecmd">onecmd() (cmd.Cmd method)</a>
</li>
      <li><a href="library/turtle.html#turtle.onkey">onkey() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.onrelease">onrelease() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.onscreenclick">onscreenclick() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.ontimer">ontimer() (in module turtle)</a>
</li>
      <li><a href="library/token.html#token.OP">OP (in module token)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_ALL">OP_ALL (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_CIPHER_SERVER_PREFERENCE">OP_CIPHER_SERVER_PREFERENCE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_ENABLE_MIDDLEBOX_COMPAT">OP_ENABLE_MIDDLEBOX_COMPAT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_COMPRESSION">OP_NO_COMPRESSION (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_SSLv2">OP_NO_SSLv2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_SSLv3">OP_NO_SSLv3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1">OP_NO_TLSv1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_1">OP_NO_TLSv1_1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_2">OP_NO_TLSv1_2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_3">OP_NO_TLSv1_3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_SINGLE_DH_USE">OP_SINGLE_DH_USE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_SINGLE_ECDH_USE">OP_SINGLE_ECDH_USE (in module ssl)</a>
</li>
      <li>
    open

      <ul>
        <li><a href="reference/datamodel.html#index-58">built-in function</a>, <a href="tutorial/inputoutput.html#index-0">[1]</a>
</li>
      </ul></li>
      <li><a href="library/miniaeframe.html#index-0">Open Scripting Architecture</a>
</li>
      <li><a href="library/functions.html#open">open() (built-in function)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.DialogWindow.open">(FrameWork.DialogWindow method)</a>
</li>
        <li><a href="library/framework.html#FrameWork.Window.open">(FrameWork.Window method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.open">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.open">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/aifc.html#aifc.open">(in module aifc)</a>
</li>
        <li><a href="library/anydbm.html#anydbm.open">(in module anydbm)</a>
</li>
        <li><a href="library/cd.html#cd.open">(in module cd)</a>
</li>
        <li><a href="library/codecs.html#codecs.open">(in module codecs)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.open">(in module dbhash)</a>
</li>
        <li><a href="library/dbm.html#dbm.open">(in module dbm)</a>
</li>
        <li><a href="library/dl.html#dl.open">(in module dl)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.open">(in module dumbdbm)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.open">(in module gdbm)</a>
</li>
        <li><a href="library/gzip.html#gzip.open">(in module gzip)</a>
</li>
        <li><a href="library/io.html#io.open">(in module io)</a>
</li>
        <li><a href="library/os.html#os.open">(in module os)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.open">(in module ossaudiodev)</a>
</li>
        <li><a href="library/posixfile.html#posixfile.open">(in module posixfile)</a>
</li>
        <li><a href="library/shelve.html#shelve.open">(in module shelve)</a>
</li>
        <li><a href="library/sunau.html#sunau.open">(in module sunau)</a>
</li>
        <li><a href="library/sunaudio.html#sunaudiodev.open">(in module sunaudiodev)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.open">(in module tarfile)</a>
</li>
        <li><a href="library/wave.html#wave.open">(in module wave)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.open">(in module webbrowser)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.open">(pipes.Template method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.open">(tarfile.TarFile class method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.open">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/urllib.html#urllib.URLopener.open">(urllib.URLopener method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.OpenerDirector.open">(urllib2.OpenerDirector method)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.controller.open">(webbrowser.controller method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.open">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/webbrowser.html#webbrowser.open_new">open_new() (in module webbrowser)</a>

      <ul>
        <li><a href="library/webbrowser.html#webbrowser.controller.open_new">(webbrowser.controller method)</a>
</li>
      </ul></li>
      <li><a href="library/webbrowser.html#webbrowser.open_new_tab">open_new_tab() (in module webbrowser)</a>

      <ul>
        <li><a href="library/webbrowser.html#webbrowser.controller.open_new_tab">(webbrowser.controller method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.open_osfhandle">open_osfhandle() (in module msvcrt)</a>
</li>
      <li><a href="library/urllib.html#urllib.URLopener.open_unknown">open_unknown() (urllib.URLopener method)</a>
</li>
      <li><a href="library/msilib.html#msilib.OpenDatabase">OpenDatabase() (in module msilib)</a>
</li>
      <li><a href="library/dircache.html#dircache.opendir">opendir() (in module dircache)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.OpenerDirector">OpenerDirector (class in urllib2)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.openfolder">openfolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/sunau.html#sunau.openfp">openfp() (in module sunau)</a>

      <ul>
        <li><a href="library/wave.html#wave.openfp">(in module wave)</a>
</li>
      </ul></li>
      <li><a href="library/gl.html#index-0">OpenGL</a>
</li>
      <li><a href="library/_winreg.html#_winreg.OpenKey">OpenKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.OpenKeyEx">OpenKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/syslog.html#syslog.openlog">openlog() (in module syslog)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Message.openmessage">openmessage() (mhlib.Message method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.openmixer">openmixer() (in module ossaudiodev)</a>
</li>
      <li><a href="library/al.html#al.openport">openport() (in module al)</a>
</li>
      <li><a href="library/os.html#os.openpty">openpty() (in module os)</a>

      <ul>
        <li><a href="library/pty.html#pty.openpty">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.openrf">openrf() (in module MacOS)</a>
</li>
      <li>
    OpenSSL

      <ul>
        <li><a href="library/hashlib.html#index-2">(use in module hashlib)</a>
</li>
        <li><a href="library/ssl.html#index-0">(use in module ssl)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION">OPENSSL_VERSION (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION_INFO">OPENSSL_VERSION_INFO (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION_NUMBER">OPENSSL_VERSION_NUMBER (in module ssl)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.OpenView">OpenView() (msilib.Database method)</a>
</li>
      <li>
    operation

      <ul>
        <li><a href="reference/expressions.html#index-69">Boolean</a>
</li>
        <li><a href="reference/expressions.html#index-52">binary arithmetic</a>
</li>
        <li><a href="reference/expressions.html#index-60">binary bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-22">concatenation</a>
</li>
        <li><a href="library/stdtypes.html#index-22">extended slice</a>
</li>
        <li><a href="reference/simple_stmts.html#index-17">null</a>
</li>
        <li><a href="library/stdtypes.html#index-22">repetition</a>
</li>
        <li><a href="reference/expressions.html#index-58">shifting</a>
</li>
        <li><a href="library/stdtypes.html#index-22">slice</a>
</li>
        <li><a href="library/stdtypes.html#index-22">subscript</a>
</li>
        <li><a href="reference/expressions.html#index-47">unary arithmetic</a>
</li>
        <li><a href="reference/expressions.html#index-47">unary bitwise</a>
</li>
      </ul></li>
      <li>
    operations

      <ul>
        <li><a href="library/stdtypes.html#index-2">Boolean</a>, <a href="library/stdtypes.html#index-7">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-19">bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-19">masking</a>
</li>
        <li><a href="library/stdtypes.html#index-19">shifting</a>
</li>
      </ul></li>
      <li>
    operations on

      <ul>
        <li><a href="library/stdtypes.html#index-32">dictionary type</a>
</li>
        <li><a href="library/stdtypes.html#index-19">integer types</a>
</li>
        <li><a href="library/stdtypes.html#index-30">list type</a>
</li>
        <li><a href="library/stdtypes.html#index-32">mapping types</a>
</li>
        <li><a href="library/stdtypes.html#index-16">numeric types</a>
</li>
        <li><a href="library/stdtypes.html#index-22">sequence types</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li>
    operator

      <ul>
        <li><a href="library/stdtypes.html#index-9">!=</a>
</li>
        <li><a href="library/stdtypes.html#index-15">%</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&amp;</a>
</li>
        <li><a href="library/stdtypes.html#index-15">*</a>
</li>
        <li><a href="library/stdtypes.html#index-15">**</a>
</li>
        <li><a href="library/stdtypes.html#index-15">+</a>
</li>
        <li><a href="library/stdtypes.html#index-15">-</a>
</li>
        <li><a href="library/stdtypes.html#index-15">/</a>
</li>
        <li><a href="library/stdtypes.html#index-15">//</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&lt;</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&lt;&lt;</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&lt;=</a>
</li>
        <li><a href="library/stdtypes.html#index-9">==</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&gt;</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&gt;=</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&gt;&gt;</a>
</li>
        <li><a href="library/stdtypes.html#index-19">^</a>
</li>
        <li><a href="library/stdtypes.html#index-6">and</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-71">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">comparison</a>
</li>
        <li><a href="library/stdtypes.html#index-12">in</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">is</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">is not</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-8">not</a>, <a href="reference/expressions.html#index-70">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-12">not in</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-6">or</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-72">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-72">overloading</a>
</li>
        <li><a href="reference/expressions.html#index-80">precedence</a>
</li>
        <li><a href="reference/expressions.html#index-73">ternary</a>
</li>
        <li><a href="library/stdtypes.html#index-19">|</a>
</li>
        <li><a href="library/stdtypes.html#index-19">~</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#module-operator">operator (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-19">operators</a>
</li>
      <li><a href="library/dis.html#dis.opmap">opmap (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.opname">opname (in module dis)</a>
</li>
      <li><a href="library/pickletools.html#pickletools.optimize">optimize() (in module pickletools)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionGroup">OptionGroup (class in optparse)</a>
</li>
      <li><a href="library/tix.html#Tix.OptionMenu">OptionMenu (class in Tix)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser">OptionParser (class in optparse)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.options">options (doctest.Example attribute)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLContext.options">(ssl.SSLContext attribute)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.options">options() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.optionxform">optionxform() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/optparse.html#module-optparse">optparse (module)</a>
</li>
      <li>
    or

      <ul>
        <li><a href="reference/expressions.html#index-63">bitwise</a>
</li>
        <li><a href="reference/expressions.html#index-62">exclusive</a>
</li>
        <li><a href="reference/expressions.html#index-63">inclusive</a>
</li>
        <li><a href="library/stdtypes.html#index-6">operator</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-72">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.or_">or_() (in module operator)</a>
</li>
      <li>
    ord

      <ul>
        <li><a href="reference/datamodel.html#index-21">built-in function</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#ord">ord() (built-in function)</a>
</li>
      <li>
    order

      <ul>
        <li><a href="reference/expressions.html#index-79">evaluation</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ordered_attributes">ordered_attributes (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/collections.html#collections.OrderedDict">OrderedDict (class in collections)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Ordinal">Ordinal (class in aetypes)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.origin_server">origin_server (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li>
    os

      <ul>
        <li><a href="library/posix.html#index-0">module</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
      </ul></li>
      <li><a href="library/os.html#module-os">os (module)</a>
</li>
      <li><a href="library/os.path.html#module-os.path">os.path (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.os_environ">os_environ (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.OSError">OSError</a>
</li>
      <li><a href="library/ossaudiodev.html#module-ossaudiodev">ossaudiodev (module)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.OSSAudioError">OSSAudioError</a>
</li>
      <li><a href="reference/simple_stmts.html#index-2">output</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">standard</a>, <a href="reference/simple_stmts.html#index-24">[1]</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError.output">output (subprocess.CalledProcessError attribute)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.output">output() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.output">(Cookie.Morsel method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.output_charset">output_charset (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.output_charset">output_charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.output_codec">output_codec (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker.output_difference">output_difference() (doctest.OutputChecker method)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker">OutputChecker (class in doctest)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.OutputString">OutputString() (Cookie.Morsel method)</a>
</li>
      <li><a href="library/stringio.html#cStringIO.OutputType">OutputType (in module cStringIO)</a>
</li>
      <li><a href="library/decimal.html#decimal.Overflow">Overflow (class in decimal)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.OverflowError">OverflowError</a>

      <ul>
        <li><a href="c-api/long.html#index-2">(built-in exception)</a>, <a href="c-api/long.html#index-3">[1]</a>, <a href="c-api/long.html#index-4">[2]</a>, <a href="c-api/long.html#index-5">[3]</a>, <a href="c-api/long.html#index-6">[4]</a>, <a href="reference/datamodel.html#index-11">[5]</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.overlay">overlay() (curses.window method)</a>
</li>
      <li>
    overloading

      <ul>
        <li><a href="reference/datamodel.html#index-72">operator</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#index-0">Overmars, Mark</a>
</li>
      <li><a href="library/curses.html#curses.window.overwrite">overwrite() (curses.window method)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="P">P</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/os.html#os.P_DETACH">P_DETACH (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_NOWAIT">P_NOWAIT (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_NOWAITO">P_NOWAITO (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_OVERLAY">P_OVERLAY (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_WAIT">P_WAIT (in module os)</a>
</li>
      <li><a href="library/aepack.html#aepack.pack">pack() (in module aepack)</a>

      <ul>
        <li><a href="library/struct.html#struct.pack">(in module struct)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.pack">(mailbox.MH method)</a>
</li>
        <li><a href="library/struct.html#struct.Struct.pack">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_array">pack_array() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_bytes">pack_bytes() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_double">pack_double() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_farray">pack_farray() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_float">pack_float() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_fopaque">pack_fopaque() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_fstring">pack_fstring() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/struct.html#struct.pack_into">pack_into() (in module struct)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.pack_into">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_list">pack_list() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_opaque">pack_opaque() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_string">pack_string() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/site.html#index-2">package</a>, <a href="reference/simple_stmts.html#index-39">[1]</a>, <a href="glossary.html#term-package"><strong>[2]</strong></a>
</li>
      <li>
    package variable

      <ul>
        <li><a href="c-api/import.html#index-0">__all__</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer">Packer (class in xdrlib)</a>
</li>
      <li><a href="library/aetools.html#aetools.packevent">packevent() (in module aetools)</a>
</li>
      <li>
    packing

      <ul>
        <li><a href="library/struct.html#index-0">binary data</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#index-0">packing (widgets)</a>
</li>
      <li><a href="library/pdb.html#index-3">PAGER</a>, <a href="library/pydoc.html#index-1">[1]</a>
</li>
      <li><a href="library/curses.html#curses.pair_content">pair_content() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.pair_number">pair_number() (in module curses)</a>
</li>
      <li><a href="library/tix.html#Tix.PanedWindow">PanedWindow (class in Tix)</a>
</li>
      <li><a href="glossary.html#term-parameter"><strong>parameter</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-39">call semantics</a>
</li>
        <li><a href="faq/programming.html#index-1">difference from argument</a>
</li>
        <li><a href="reference/compound_stmts.html#index-17">function definition</a>
</li>
        <li><a href="reference/compound_stmts.html#index-20">value, default</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.pardir">pardir (in module os)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-paren">paren (2to3 fixer)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.parent">parent (urllib2.BaseHandler attribute)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.parent">parent() (ttk.Treeview method)</a>
</li>
      <li><a href="reference/expressions.html#index-10">parenthesized form</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.parentNode">parentNode (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/random.html#random.paretovariate">paretovariate() (in module random)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.parse">parse() (doctest.DocTestParser method)</a>

      <ul>
        <li><a href="library/email.parser.html#email.parser.Parser.parse">(email.parser.Parser method)</a>
</li>
        <li><a href="library/ast.html#ast.parse">(in module ast)</a>
</li>
        <li><a href="library/cgi.html#cgi.parse">(in module cgi)</a>
</li>
        <li><a href="library/compiler.html#compiler.parse">(in module compiler)</a>
</li>
        <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.parse">(in module xml.dom.minidom)</a>
</li>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.parse">(in module xml.dom.pulldom)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.parse">(in module xml.etree.ElementTree)</a>
</li>
        <li><a href="library/xml.sax.html#xml.sax.parse">(in module xml.sax)</a>
</li>
        <li><a href="library/robotparser.html#robotparser.RobotFileParser.parse">(robotparser.RobotFileParser method)</a>
</li>
        <li><a href="library/string.html#string.Formatter.parse">(string.Formatter method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.parse">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.Parse">Parse() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.parse">parse() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/readline.html#readline.parse_and_bind">parse_and_bind() (in module readline)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.parse_args">parse_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.PARSE_COLNAMES">PARSE_COLNAMES (in module sqlite3)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.parse_config_h">parse_config_h() (in module sysconfig)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.PARSE_DECLTYPES">PARSE_DECLTYPES (in module sqlite3)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_header">parse_header() (in module cgi)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.parse_known_args">parse_known_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_multipart">parse_multipart() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_qs">parse_qs() (in module cgi)</a>

      <ul>
        <li><a href="library/urlparse.html#urlparse.parse_qs">(in module urlparse)</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#cgi.parse_qsl">parse_qsl() (in module cgi)</a>

      <ul>
        <li><a href="library/urlparse.html#urlparse.parse_qsl">(in module urlparse)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parseaddr">parseaddr() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parseaddr">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parsedate">parsedate() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parsedate">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parsedate_tz">parsedate_tz() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parsedate_tz">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#compiler.parseFile">parseFile() (in module compiler)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile">ParseFile() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.ParseFlags">ParseFlags() (in module imaplib)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">parser</a>
</li>
      <li><a href="library/email.parser.html#email.parser.Parser">Parser (class in email.parser)</a>
</li>
      <li><a href="library/parser.html#module-parser">parser (module)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ParserCreate">ParserCreate() (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/parser.html#parser.ParserError">ParserError</a>
</li>
      <li><a href="library/urlparse.html#urlparse.ParseResult">ParseResult (class in urlparse)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.parsesequence">parsesequence() (mhlib.Folder method)</a>
</li>
      <li><a href="library/email.parser.html#email.parser.Parser.parsestr">parsestr() (email.parser.Parser method)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.parseString">parseString() (in module xml.dom.minidom)</a>

      <ul>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.parseString">(in module xml.dom.pulldom)</a>
</li>
        <li><a href="library/xml.sax.html#xml.sax.parseString">(in module xml.sax)</a>
</li>
      </ul></li>
      <li><a href="library/ic.html#ic.IC.parseurl">parseurl() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.parseurl">(in module ic)</a>
</li>
      </ul></li>
      <li>
    parsing

      <ul>
        <li><a href="library/parser.html#index-0">Python source code</a>
</li>
        <li><a href="library/urlparse.html#index-0">URL</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.ParsingError">ParsingError</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.partial">partial() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/functools.html#functools.partial">(in module functools)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#str.partition">partition() (str method)</a>
</li>
      <li>
    Pascal

      <ul>
        <li><a href="reference/compound_stmts.html#index-8">language</a>
</li>
      </ul></li>
      <li>
    pass

      <ul>
        <li><a href="reference/simple_stmts.html#index-17">statement</a>
</li>
      </ul></li>
      <li><a href="library/poplib.html#poplib.POP3.pass_">pass_() (poplib.POP3 method)</a>
</li>
      <li><a href="library/idle.html#index-4">Paste</a>
</li>
      <li><a href="c-api/intro.html#index-22">PATH</a>, <a href="c-api/intro.html#index-23">[1]</a>, <a href="distutils/packageindex.html#index-1">[2]</a>, <a href="faq/library.html#index-0">[3]</a>, <a href="faq/library.html#index-1">[4]</a>, <a href="library/cgi.html#index-2">[5]</a>, <a href="library/cgi.html#index-5">[6]</a>, <a href="library/os.html#index-21">[7]</a>, <a href="library/os.html#index-22">[8]</a>, <a href="library/os.html#index-23">[9]</a>, <a href="library/os.html#index-26">[10]</a>, <a href="library/os.html#index-27">[11]</a>, <a href="library/os.html#index-28">[12]</a>, <a href="library/os.html#index-30">[13]</a>, <a href="library/webbrowser.html#index-3">[14]</a>, <a href="tutorial/appendix.html#index-0">[15]</a>, <a href="tutorial/modules.html#index-2">[16]</a>, <a href="using/cmdline.html#index-18">[17]</a>, <a href="using/unix.html#index-2">[18]</a>
</li>
      <li>
    path

      <ul>
        <li><a href="library/site.html#index-2">configuration file</a>
</li>
        <li><a href="c-api/init.html#index-0">module search</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
        <li><a href="library/os.path.html#index-0">operations</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.path">path (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.path">(cookielib.Cookie attribute)</a>
</li>
        <li><a href="c-api/init.html#index-0">(in module sys)</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/sys.html#sys.path">[3]</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-1">Path browser</a>
</li>
      <li><a href="library/sys.html#sys.path_hooks">path_hooks (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.path_importer_cache">path_importer_cache (in module sys)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.path_return_ok">path_return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/os.html#os.pathconf">pathconf() (in module os)</a>
</li>
      <li><a href="library/os.html#os.pathconf_names">pathconf_names (in module os)</a>
</li>
      <li><a href="library/urllib.html#urllib.pathname2url">pathname2url() (in module urllib)</a>
</li>
      <li><a href="library/os.html#os.pathsep">pathsep (in module os)</a>
</li>
      <li><a href="library/re.html#re.RegexObject.pattern">pattern (re.RegexObject attribute)</a>
</li>
      <li><a href="library/signal.html#signal.pause">pause() (in module signal)</a>
</li>
      <li><a href="library/cd.html#cd.PAUSED">PAUSED (in module cd)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.PAX_FORMAT">PAX_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.pax_headers">pax_headers (tarfile.TarFile attribute)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.pax_headers">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/hashlib.html#hashlib.pbkdf2_hmac">pbkdf2_hmac() (in module hashlib)</a>
</li>
      <li><a href="library/turtle.html#turtle.pd">pd() (in module turtle)</a>
</li>
      <li><a href="library/pdb.html#index-1">Pdb (class in pdb)</a>, <a href="library/pdb.html#pdb.Pdb">[1]</a>
</li>
      <li><a href="library/pdb.html#module-pdb">pdb (module)</a>
</li>
      <li><a href="library/io.html#io.BufferedReader.peek">peek() (io.BufferedReader method)</a>
</li>
      <li><a href="library/ssl.html#ssl.PEM_cert_to_DER_cert">PEM_cert_to_DER_cert() (in module ssl)</a>
</li>
      <li><a href="library/turtle.html#turtle.pen">pen() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.pencolor">pencolor() (in module turtle)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.PendingDeprecationWarning">PendingDeprecationWarning</a>
</li>
      <li><a href="library/turtle.html#turtle.pendown">pendown() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.pensize">pensize() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.penup">penup() (in module turtle)</a>
</li>
      <li><a href="glossary.html#term-pep"><strong>PEP</strong></a>
</li>
      <li><a href="library/token.html#token.PERCENT">PERCENT (in module token)</a>
</li>
      <li><a href="library/token.html#token.PERCENTEQUAL">PERCENTEQUAL (in module token)</a>
</li>
      <li><a href="library/timeit.html#index-0">Performance</a>
</li>
      <li><a href="library/itertools.html#itertools.permutations">permutations() (in module itertools)</a>
</li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.Persist">Persist() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/pickle.html#index-0">persistence</a>
</li>
      <li>
    persistent

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#index-3">persistent_id (pickle protocol)</a>
</li>
      <li><a href="library/pickle.html#index-3">persistent_load (pickle protocol)</a>
</li>
      <li><a href="library/pprint.html#pprint.pformat">pformat() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.pformat">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.phase">phase() (in module cmath)</a>
</li>
      <li><a href="extending/extending.html#index-3">Philbrick, Geoff</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-15">physical line</a>, <a href="reference/lexical_analysis.html#index-2">[1]</a>, <a href="reference/lexical_analysis.html#index-5">[2]</a>
</li>
      <li><a href="library/cmath.html#cmath.pi">pi (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.pi">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/gl.html#gl.pick">pick() (in module gl)</a>
</li>
      <li>
    pickle

      <ul>
        <li><a href="library/copy.html#index-0">module</a>, <a href="library/copy_reg.html#index-0">[1]</a>, <a href="library/marshal.html#index-0">[2]</a>, <a href="library/pickle.html#index-5">[3]</a>, <a href="library/shelve.html#index-0">[4]</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#module-pickle">pickle (module)</a>
</li>
      <li><a href="library/copy_reg.html#copy_reg.pickle">pickle() (in module copy_reg)</a>
</li>
      <li><a href="library/pickle.html#pickle.PickleError">PickleError</a>
</li>
      <li><a href="library/pickle.html#pickle.Pickler">Pickler (class in pickle)</a>
</li>
      <li><a href="library/pickletools.html#module-pickletools">pickletools (module)</a>
</li>
      <li>
    pickling

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#pickle.PicklingError">PicklingError</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.pid">pid (multiprocessing.Process attribute)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.Popen3.pid">(popen2.Popen3 attribute)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.pid">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">PIL (the Python Imaging Library)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.PIPE">PIPE (in module subprocess)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Pipe">Pipe() (in module multiprocessing)</a>
</li>
      <li><a href="library/os.html#os.pipe">pipe() (in module os)</a>
</li>
      <li><a href="library/select.html#select.select.PIPE_BUF">PIPE_BUF (select.select attribute)</a>
</li>
      <li><a href="library/pipes.html#module-pipes">pipes (module)</a>
</li>
      <li><a href="library/undoc.html#module-PixMapWrapper">PixMapWrapper (module)</a>
</li>
      <li><a href="library/imp.html#imp.PKG_DIRECTORY">PKG_DIRECTORY (in module imp)</a>
</li>
      <li><a href="library/pkgutil.html#module-pkgutil">pkgutil (module)</a>
</li>
      <li>
    plain integer

      <ul>
        <li><a href="reference/datamodel.html#index-11">object</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">plain integer literal</a>
</li>
      <li><a href="distutils/apiref.html#index-2">PLAT</a>
</li>
      <li><a href="c-api/init.html#index-6">platform (in module sys)</a>, <a href="library/sys.html#sys.platform">[1]</a>

      <ul>
        <li><a href="library/platform.html#module-platform">(module)</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.platform">platform() (in module platform)</a>
</li>
      <li><a href="library/cd.html#cd.PLAYING">PLAYING (in module cd)</a>
</li>
      <li><a href="library/winsound.html#winsound.PlaySound">PlaySound() (in module winsound)</a>
</li>
      <li>
    plist

      <ul>
        <li><a href="library/plistlib.html#index-0">file</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#module-plistlib">plistlib (module)</a>
</li>
      <li><a href="library/os.html#os.plock">plock() (in module os)</a>
</li>
      <li><a href="reference/expressions.html#index-49">plus</a>
</li>
      <li><a href="library/token.html#token.PLUS">PLUS (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.plus">plus() (decimal.Context method)</a>
</li>
      <li><a href="library/token.html#token.PLUSEQUAL">PLUSEQUAL (in module token)</a>
</li>
      <li><a href="library/pdb.html#pdb.pm">pm() (in module pdb)</a>
</li>
      <li><a href="library/cd.html#cd.pnum">pnum (in module cd)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.POINTER">POINTER() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.pointer">pointer() (in module ctypes)</a>
</li>
      <li><a href="library/cmath.html#cmath.polar">polar() (in module cmath)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection.poll">poll() (Connection method)</a>

      <ul>
        <li><a href="library/select.html#select.poll">(in module select)</a>
</li>
        <li><a href="library/popen2.html#popen2.Popen3.poll">(popen2.Popen3 method)</a>
</li>
        <li><a href="library/select.html#select.epoll.poll">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.poll.poll">(select.poll method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.poll">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.pop">pop() (array.array method)</a>

      <ul>
        <li><a href="library/asynchat.html#asynchat.fifo.pop">(asynchat.fifo method)</a>
</li>
        <li><a href="library/collections.html#collections.deque.pop">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.pop">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.pop">(frozenset method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.pop">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.pop">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li>
    POP3

      <ul>
        <li><a href="library/poplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/poplib.html#poplib.POP3">POP3 (class in poplib)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3_SSL">POP3_SSL (class in poplib)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_alignment">pop_alignment() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_BLOCK">POP_BLOCK (opcode)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_font">pop_font() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_JUMP_IF_FALSE">POP_JUMP_IF_FALSE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_JUMP_IF_TRUE">POP_JUMP_IF_TRUE (opcode)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_margin">pop_margin() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.pop_source">pop_source() (shlex.shlex method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_style">pop_style() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_TOP">POP_TOP (opcode)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen">Popen (class in subprocess)</a>
</li>
      <li><a href="library/os.html#os.popen">popen() (in module os)</a>, <a href="library/select.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/platform.html#platform.popen">(in module platform)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#module-popen2">popen2 (module)</a>
</li>
      <li><a href="library/os.html#os.popen2">popen2() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen2">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#popen2.Popen3">Popen3 (class in popen2)</a>
</li>
      <li><a href="library/os.html#os.popen3">popen3() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen3">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#popen2.Popen4">Popen4 (class in popen2)</a>
</li>
      <li><a href="library/os.html#os.popen4">popen4() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen4">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.OrderedDict.popitem">popitem() (collections.OrderedDict method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.popitem">(dict method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.popitem">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.deque.popleft">popleft() (collections.deque method)</a>
</li>
      <li><a href="library/poplib.html#module-poplib">poplib (module)</a>
</li>
      <li><a href="library/tix.html#Tix.PopupMenu">PopupMenu (class in Tix)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.port">port (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.port_specified">port_specified (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.PortableUnixMailbox">PortableUnixMailbox (class in mailbox)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.pos">pos (re.MatchObject attribute)</a>
</li>
      <li><a href="library/operator.html#operator.pos">pos() (in module operator)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.pos">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.position">position() (in module turtle)</a>
</li>
      <li><a href="glossary.html#term-positional-argument"><strong>positional argument</strong></a>
</li>
      <li>
    POSIX

      <ul>
        <li><a href="library/termios.html#index-0">I/O control</a>
</li>
        <li><a href="library/posixfile.html#index-0">file object</a>
</li>
        <li><a href="library/thread.html#index-1">threads</a>
</li>
      </ul></li>
      <li><a href="library/posix.html#module-posix">posix (module)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarFile.posix">(tarfile.TarFile attribute)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#module-posixfile">posixfile (module)</a>
</li>
      <li><a href="library/getopt.html#index-0">POSIXLY_CORRECT</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.post">post() (nntplib.NNTP method)</a>

      <ul>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.post">(ossaudiodev.oss_audio_device method)</a>
</li>
      </ul></li>
      <li><a href="library/pdb.html#pdb.post_mortem">post_mortem() (in module pdb)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.postcmd">postcmd() (cmd.Cmd method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.postloop">postloop() (cmd.Cmd method)</a>
</li>
      <li>
    pow

      <ul>
        <li><a href="c-api/number.html#index-1">built-in function</a>, <a href="c-api/number.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-90">[2]</a>, <a href="reference/datamodel.html#index-90">[3]</a>, <a href="reference/datamodel.html#index-91">[4]</a>, <a href="reference/datamodel.html#index-92">[5]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#pow">pow() (built-in function)</a>

      <ul>
        <li><a href="library/math.html#math.pow">(in module math)</a>
</li>
        <li><a href="library/operator.html#operator.pow">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.power">power() (decimal.Context method)</a>
</li>
      <li><a href="library/pprint.html#module-pprint">pprint (module)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.pprint">pprint() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.pprint">(in module pprint)</a>
</li>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.pprint">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.prcal">prcal() (in module calendar)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.preamble">preamble (email.message.Message attribute)</a>
</li>
      <li>
    precedence

      <ul>
        <li><a href="reference/expressions.html#index-80">operator</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.precmd">precmd() (cmd.Cmd method)</a>
</li>
      <li><a href="c-api/intro.html#index-0">prefix</a>, <a href="c-api/intro.html#index-2">[1]</a>, <a href="c-api/intro.html#index-3">[2]</a>, <a href="using/unix.html#index-0">[3]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.PREFIX">PREFIX (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sys.html#sys.prefix">prefix (in module sys)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Attr.prefix">(xml.dom.Attr attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Node.prefix">(xml.dom.Node attribute)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.prefix">(zipimport.zipimporter attribute)</a>
</li>
      </ul></li>
      <li><a href="library/site.html#site.PREFIXES">PREFIXES (in module site)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.preloop">preloop() (cmd.Cmd method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.preorder">preorder() (compiler.visitor.ASTVisitor method)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.prepare_input_source">prepare_input_source() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/pipes.html#pipes.Template.prepend">prepend() (pipes.Template method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.preprocess">preprocess() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/pprint.html#pprint.PrettyPrinter">PrettyPrinter (class in pprint)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.prev">prev() (ttk.Treeview method)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.previous">previous() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.previous">(dbhash.dbhash method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.previousSibling">previousSibling (xml.dom.Node attribute)</a>
</li>
      <li><a href="reference/expressions.html#index-28">primary</a>
</li>
      <li>
    print

      <ul>
        <li><a href="library/stdtypes.html#index-1">statement</a>, <a href="reference/datamodel.html#index-78">[1]</a>, <a href="reference/simple_stmts.html#index-22">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-print">print (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#print">print() (built-in function)</a>
</li>
      <li><a href="library/macostools.html#findertools.Print">Print() (in module findertools)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats.print_callees">print_callees() (pstats.Stats method)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats.print_callers">print_callers() (pstats.Stats method)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_directory">print_directory() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_environ">print_environ() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_environ_usage">print_environ_usage() (in module cgi)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_exc">print_exc() (in module traceback)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer.print_exc">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.print_exception">print_exception() (in module traceback)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_EXPR">PRINT_EXPR (opcode)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_form">print_form() (in module cgi)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.print_help">print_help() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_ITEM">PRINT_ITEM (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_ITEM_TO">PRINT_ITEM_TO (opcode)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_last">print_last() (in module traceback)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_NEWLINE">PRINT_NEWLINE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_NEWLINE_TO">PRINT_NEWLINE_TO (opcode)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_stack">print_stack() (in module traceback)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.print_stats">print_stats() (profile.Profile method)</a>

      <ul>
        <li><a href="library/profile.html#pstats.Stats.print_stats">(pstats.Stats method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.print_tb">print_tb() (in module traceback)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.print_usage">print_usage() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.print_usage">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.OptionParser.print_version">print_version() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/string.html#string.printable">printable (in module string)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.printdir">printdir() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">printf-style formatting</a>
</li>
      <li><a href="library/queue.html#Queue.PriorityQueue">PriorityQueue (class in Queue)</a>
</li>
      <li>
    private

      <ul>
        <li><a href="reference/expressions.html#index-7">names</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.TextCalendar.prmonth">prmonth() (calendar.TextCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.prmonth">(in module calendar)</a>
</li>
      </ul></li>
      <li>
    procedure

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">call</a>
</li>
      </ul></li>
      <li>
    process

      <ul>
        <li><a href="library/os.html#index-1">group</a>, <a href="library/os.html#index-3">[1]</a>
</li>
        <li><a href="library/os.html#index-4">id</a>
</li>
        <li><a href="library/os.html#index-5">id of parent</a>
</li>
        <li><a href="library/os.html#index-24">killing</a>, <a href="library/os.html#index-25">[1]</a>
</li>
        <li><a href="library/os.html#index-24">signalling</a>, <a href="library/os.html#index-25">[1]</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process">Process (class in multiprocessing)</a>
</li>
      <li><a href="library/logging.html#logging.LoggerAdapter.process">process() (logging.LoggerAdapter method)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.SMTPServer.process_message">process_message() (smtpd.SMTPServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.process_request">process_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.process_tokens">process_tokens() (in module tabnanny)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.ProcessError">ProcessError</a>
</li>
      <li><a href="library/thread.html#index-0">processes, light-weight</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.processfile">processfile() (in module gensuitemodule)</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.processfile_fromresource">processfile_fromresource() (in module gensuitemodule)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ProcessingInstruction">ProcessingInstruction() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.processingInstruction">processingInstruction() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ProcessingInstructionHandler">ProcessingInstructionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/time.html#index-8">processor time</a>
</li>
      <li><a href="library/platform.html#platform.processor">processor() (in module platform)</a>
</li>
      <li><a href="library/itertools.html#itertools.product">product() (in module itertools)</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile">Profile (class in hotshot)</a>

      <ul>
        <li><a href="library/profile.html#profile.Profile">(class in profile)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#module-profile">profile (module)</a>
</li>
      <li><a href="library/sys.html#index-12">profile function</a>, <a href="library/sys.html#index-2">[1]</a>, <a href="library/threading.html#index-2">[2]</a>
</li>
      <li><a href="library/sys.html#index-12">profiler</a>, <a href="library/sys.html#index-2">[1]</a>
</li>
      <li><a href="library/profile.html#index-0">profiling, deterministic</a>
</li>
      <li><a href="reference/toplevel_components.html#index-1">program</a>
</li>
      <li><a href="library/ttk.html#ttk.Progressbar">Progressbar (class in ttk)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar">ProgressBar() (in module EasyDialogs)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.prompt">prompt (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.FancyURLopener.prompt_user_passwd">prompt_user_passwd() (urllib.FancyURLopener method)</a>
</li>
      <li><a href="library/sys.html#index-11">prompts, interpreter</a>
</li>
      <li><a href="library/logging.html#logging.Logger.propagate">propagate (logging.Logger attribute)</a>
</li>
      <li><a href="library/functions.html#property">property (built-in class)</a>
</li>
      <li><a href="library/plistlib.html#index-0">property list</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_declaration_handler">property_declaration_handler (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_dom_node">property_dom_node (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_lexical_handler">property_lexical_handler (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_xml_string">property_xml_string (in module xml.sax.handler)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.prot_c">prot_c() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.prot_p">prot_p() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.proto">proto (socket.socket attribute)</a>
</li>
      <li>
    protocol

      <ul>
        <li><a href="library/cgi.html#index-0">CGI</a>
</li>
        <li><a href="library/ftplib.html#index-0">FTP</a>, <a href="library/urllib.html#index-8">[1]</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">HTTP</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/httplib.html#index-0">[2]</a>, <a href="library/urllib.html#index-8">[3]</a>, <a href="library/urllib.html#index-9">[4]</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4_SSL</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4_stream</a>
</li>
        <li><a href="library/nntplib.html#index-0">NNTP</a>
</li>
        <li><a href="library/poplib.html#index-0">POP3</a>
</li>
        <li><a href="library/smtplib.html#index-0">SMTP</a>
</li>
        <li><a href="library/telnetlib.html#index-0">Telnet</a>
</li>
        <li><a href="library/stdtypes.html#index-37">context management</a>
</li>
        <li><a href="library/stdtypes.html#index-20">iterator</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.protocol">protocol (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv2">PROTOCOL_SSLv2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv23">PROTOCOL_SSLv23 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv3">PROTOCOL_SSLv3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLS">PROTOCOL_TLS (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1">PROTOCOL_TLSv1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1_1">PROTOCOL_TLSv1_1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1_2">PROTOCOL_TLSv1_2 (in module ssl)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.protocol_version">protocol_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.PROTOCOL_VERSION">PROTOCOL_VERSION (imaplib.IMAP4 attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError">ProtocolError (class in xmlrpclib)</a>
</li>
      <li><a href="library/weakref.html#weakref.proxy">proxy() (in module weakref)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.proxyauth">proxyauth() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyBasicAuthHandler">ProxyBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyDigestAuthHandler">ProxyDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyHandler">ProxyHandler (class in urllib2)</a>
</li>
      <li><a href="library/weakref.html#weakref.ProxyType">ProxyType (in module weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.ProxyTypes">ProxyTypes (in module weakref)</a>
</li>
      <li><a href="library/fm.html#fm.prstr">prstr() (in module fm)</a>
</li>
      <li><a href="library/calendar.html#calendar.TextCalendar.pryear">pryear() (calendar.TextCalendar method)</a>
</li>
      <li><a href="library/sys.html#sys.ps1">ps1 (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.ps2">ps2 (in module sys)</a>
</li>
      <li><a href="library/profile.html#module-pstats">pstats (module)</a>
</li>
      <li><a href="library/thread.html#index-1">pthreads</a>
</li>
      <li><a href="library/cd.html#cd.ptime">ptime (in module cd)</a>
</li>
      <li>
    pty

      <ul>
        <li><a href="library/os.html#index-12">module</a>
</li>
      </ul></li>
      <li><a href="library/pty.html#module-pty">pty (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.pu">pu() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.publicId">publicId (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.PullDOM">PullDOM (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/string.html#string.punctuation">punctuation (in module string)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.PureProxy">PureProxy (class in smtpd)</a>
</li>
      <li><a href="library/re.html#re.purge">purge() (in module re)</a>
</li>
      <li><a href="library/ssl.html#ssl.Purpose.CLIENT_AUTH">Purpose.CLIENT_AUTH (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.Purpose.SERVER_AUTH">Purpose.SERVER_AUTH (in module ssl)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.push">push() (asynchat.async_chat method)</a>

      <ul>
        <li><a href="library/asynchat.html#asynchat.fifo.push">(asynchat.fifo method)</a>
</li>
        <li><a href="library/code.html#code.InteractiveConsole.push">(code.InteractiveConsole method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.push">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.push_alignment">push_alignment() (formatter.formatter method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_font">push_font() (formatter.formatter method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_margin">push_margin() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.push_source">push_source() (shlex.shlex method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_style">push_style() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.push_token">push_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.push_with_producer">push_with_producer() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.pushbutton">pushbutton() (msilib.Dialog method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.put">put() (multiprocessing.multiprocessing.queues.SimpleQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.put">(Queue.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.put">(multiprocessing.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.put_nowait">put_nowait() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.put_nowait">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.putch">putch() (in module msvcrt)</a>
</li>
      <li><a href="library/os.html#os.putenv">putenv() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.putheader">putheader() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/curses.html#curses.putp">putp() (in module curses)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.putrequest">putrequest() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.putsequences">putsequences() (mhlib.Folder method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.putwch">putwch() (in module msvcrt)</a>
</li>
      <li><a href="library/curses.html#curses.window.putwin">putwin() (curses.window method)</a>
</li>
      <li>
    pwd

      <ul>
        <li><a href="library/os.path.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/pwd.html#module-pwd">pwd (module)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.pwd">pwd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/gl.html#gl.pwlcurve">pwlcurve() (in module gl)</a>
</li>
      <li><a href="library/sys.html#sys.py3kwarning">py3kwarning (in module sys)</a>
</li>
      <li><a href="c-api/init.html#c.Py_AddPendingCall">Py_AddPendingCall (C function)</a>
</li>
      <li><a href="c-api/init.html#index-25">Py_AddPendingCall()</a>
</li>
      <li><a href="c-api/sys.html#c.Py_AtExit">Py_AtExit (C function)</a>
</li>
      <li><a href="c-api/init.html#index-16">Py_BEGIN_ALLOW_THREADS</a>

      <ul>
        <li><a href="c-api/init.html#c.Py_BEGIN_ALLOW_THREADS">(C macro)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#c.Py_BLOCK_THREADS">Py_BLOCK_THREADS (C macro)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer">Py_buffer (C type)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.buf">Py_buffer.buf (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.internal">Py_buffer.internal (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.itemsize">Py_buffer.itemsize (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.ndim">Py_buffer.ndim (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.readonly">Py_buffer.readonly (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.shape">Py_buffer.shape (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.strides">Py_buffer.strides (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.suboffsets">Py_buffer.suboffsets (C member)</a>
</li>
      <li><a href="c-api/arg.html#c.Py_BuildValue">Py_BuildValue (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_CLEAR">Py_CLEAR (C function)</a>
</li>
      <li><a href="library/py_compile.html#module-py_compile">py_compile (module)</a>
</li>
      <li><a href="library/imp.html#imp.PY_COMPILED">PY_COMPILED (in module imp)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_CompileString">Py_CompileString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#index-0">Py_CompileString()</a>, <a href="c-api/veryhigh.html#index-1">[1]</a>, <a href="c-api/veryhigh.html#index-2">[2]</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_CompileStringFlags">Py_CompileStringFlags (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.Py_complex">Py_complex (C type)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_DECREF">Py_DECREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-6">Py_DECREF()</a>
</li>
      <li><a href="c-api/slice.html#c.Py_Ellipsis">Py_Ellipsis (C variable)</a>
</li>
      <li><a href="c-api/init.html#index-16">Py_END_ALLOW_THREADS</a>

      <ul>
        <li><a href="c-api/init.html#c.Py_END_ALLOW_THREADS">(C macro)</a>
</li>
      </ul></li>
      <li><a href="c-api/buffer.html#c.Py_END_OF_BUFFER">Py_END_OF_BUFFER (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_EndInterpreter">Py_EndInterpreter (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.Py_EnterRecursiveCall">Py_EnterRecursiveCall (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_eval_input">Py_eval_input (C variable)</a>
</li>
      <li><a href="c-api/sys.html#c.Py_Exit">Py_Exit (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_False">Py_False (C variable)</a>
</li>
      <li><a href="c-api/sys.html#c.Py_FatalError">Py_FatalError (C function)</a>
</li>
      <li><a href="c-api/init.html#index-10">Py_FatalError()</a>
</li>
      <li><a href="c-api/sys.html#c.Py_FdIsInteractive">Py_FdIsInteractive (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_file_input">Py_file_input (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_Finalize">Py_Finalize (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">Py_Finalize()</a>, <a href="c-api/init.html#index-22">[1]</a>, <a href="c-api/init.html#index-24">[2]</a>, <a href="c-api/sys.html#index-1">[3]</a>, <a href="c-api/sys.html#index-2">[4]</a>
</li>
      <li><a href="c-api/structures.html#c.Py_FindMethod">Py_FindMethod (C function)</a>
</li>
      <li><a href="library/imp.html#imp.PY_FROZEN">PY_FROZEN (in module imp)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetBuildInfo">Py_GetBuildInfo (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetCompiler">Py_GetCompiler (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetCopyright">Py_GetCopyright (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetExecPrefix">Py_GetExecPrefix (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetExecPrefix()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPath">Py_GetPath (C function)</a>
</li>
      <li><a href="c-api/init.html#index-1">Py_GetPath()</a>, <a href="c-api/intro.html#index-26">[1]</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPlatform">Py_GetPlatform (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPrefix">Py_GetPrefix (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetPrefix()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetProgramFullPath">Py_GetProgramFullPath (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetProgramFullPath()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetProgramName">Py_GetProgramName (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPythonHome">Py_GetPythonHome (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetVersion">Py_GetVersion (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_INCREF">Py_INCREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-6">Py_INCREF()</a>
</li>
      <li><a href="c-api/init.html#c.Py_Initialize">Py_Initialize (C function)</a>
</li>
      <li><a href="c-api/init.html#index-1">Py_Initialize()</a>, <a href="c-api/init.html#index-19">[1]</a>, <a href="c-api/init.html#index-22">[2]</a>, <a href="c-api/intro.html#index-20">[3]</a>
</li>
      <li><a href="c-api/init.html#c.Py_InitializeEx">Py_InitializeEx (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule">Py_InitModule (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule3">Py_InitModule3 (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule4">Py_InitModule4 (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_IsInitialized">Py_IsInitialized (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-29">Py_IsInitialized()</a>
</li>
      <li><a href="c-api/exceptions.html#c.Py_LeaveRecursiveCall">Py_LeaveRecursiveCall (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_Main">Py_Main (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_NewInterpreter">Py_NewInterpreter (C function)</a>
</li>
      <li><a href="c-api/none.html#c.Py_None">Py_None (C variable)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.py_object">py_object (class in ctypes)</a>
</li>
      <li><a href="c-api/file.html#index-6">Py_PRINT_RAW</a>
</li>
      <li><a href="c-api/structures.html#c.Py_REFCNT">Py_REFCNT (C macro)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_RETURN_FALSE">Py_RETURN_FALSE (C macro)</a>
</li>
      <li><a href="c-api/none.html#c.Py_RETURN_NONE">Py_RETURN_NONE (C macro)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_RETURN_TRUE">Py_RETURN_TRUE (C macro)</a>
</li>
      <li><a href="c-api/init.html#c.Py_SetProgramName">Py_SetProgramName (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">Py_SetProgramName()</a>, <a href="c-api/init.html#index-2">[1]</a>, <a href="c-api/init.html#index-3">[2]</a>, <a href="c-api/intro.html#index-26">[3]</a>
</li>
      <li><a href="c-api/init.html#c.Py_SetPythonHome">Py_SetPythonHome (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_single_input">Py_single_input (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.Py_SIZE">Py_SIZE (C macro)</a>
</li>
      <li><a href="library/imp.html#imp.PY_SOURCE">PY_SOURCE (in module imp)</a>
</li>
      <li><a href="c-api/long.html#index-3">PY_SSIZE_T_MAX</a>
</li>
      <li><a href="library/imputil.html#imputil.py_suffix_importer">py_suffix_importer() (in module imputil)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_BASETYPE">Py_TPFLAGS_BASETYPE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_CHECKTYPES">Py_TPFLAGS_CHECKTYPES (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_DEFAULT">Py_TPFLAGS_DEFAULT (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_GC">Py_TPFLAGS_GC (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_CLASS">Py_TPFLAGS_HAVE_CLASS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GC">Py_TPFLAGS_HAVE_GC (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GETCHARBUFFER">Py_TPFLAGS_HAVE_GETCHARBUFFER (built-in variable)</a>, <a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GETCHARBUFFER">[1]</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_INPLACEOPS">Py_TPFLAGS_HAVE_INPLACEOPS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_ITER">Py_TPFLAGS_HAVE_ITER (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_RICHCOMPARE">Py_TPFLAGS_HAVE_RICHCOMPARE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_SEQUENCE_IN">Py_TPFLAGS_HAVE_SEQUENCE_IN (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_WEAKREFS">Py_TPFLAGS_HAVE_WEAKREFS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HEAPTYPE">Py_TPFLAGS_HEAPTYPE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_READY">Py_TPFLAGS_READY (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_READYING">Py_TPFLAGS_READYING (built-in variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_tracefunc">Py_tracefunc (C type)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_True">Py_True (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.Py_TYPE">Py_TYPE (C macro)</a>
</li>
      <li><a href="c-api/init.html#c.Py_UNBLOCK_THREADS">Py_UNBLOCK_THREADS (C macro)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE">Py_UNICODE (C type)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISALNUM">Py_UNICODE_ISALNUM (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISALPHA">Py_UNICODE_ISALPHA (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISDECIMAL">Py_UNICODE_ISDECIMAL (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISDIGIT">Py_UNICODE_ISDIGIT (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISLINEBREAK">Py_UNICODE_ISLINEBREAK (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISLOWER">Py_UNICODE_ISLOWER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISNUMERIC">Py_UNICODE_ISNUMERIC (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISSPACE">Py_UNICODE_ISSPACE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISTITLE">Py_UNICODE_ISTITLE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISUPPER">Py_UNICODE_ISUPPER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TODECIMAL">Py_UNICODE_TODECIMAL (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TODIGIT">Py_UNICODE_TODIGIT (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOLOWER">Py_UNICODE_TOLOWER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TONUMERIC">Py_UNICODE_TONUMERIC (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOTITLE">Py_UNICODE_TOTITLE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOUPPER">Py_UNICODE_TOUPPER (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.Py_VaBuildValue">Py_VaBuildValue (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.Py_VISIT">Py_VISIT (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_XDECREF">Py_XDECREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-19">Py_XDECREF()</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_XINCREF">Py_XINCREF (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyAnySet_Check">PyAnySet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyAnySet_CheckExact">PyAnySet_CheckExact (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_Parse">PyArg_Parse (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_ParseTuple">PyArg_ParseTuple (C function)</a>
</li>
      <li><a href="extending/extending.html#index-1">PyArg_ParseTuple()</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_ParseTupleAndKeywords">PyArg_ParseTupleAndKeywords (C function)</a>
</li>
      <li><a href="extending/extending.html#index-2">PyArg_ParseTupleAndKeywords()</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_UnpackTuple">PyArg_UnpackTuple (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_VaParse">PyArg_VaParse (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_VaParseTupleAndKeywords">PyArg_VaParseTupleAndKeywords (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.PyBool_Check">PyBool_Check (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.PyBool_FromLong">PyBool_FromLong (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Check">PyBuffer_Check (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FillContiguousStrides">PyBuffer_FillContiguousStrides (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FillInfo">PyBuffer_FillInfo (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromMemory">PyBuffer_FromMemory (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromObject">PyBuffer_FromObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromReadWriteMemory">PyBuffer_FromReadWriteMemory (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromReadWriteObject">PyBuffer_FromReadWriteObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_IsContiguous">PyBuffer_IsContiguous (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_New">PyBuffer_New (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Release">PyBuffer_Release (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_SizeFromFormat">PyBuffer_SizeFromFormat (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Type">PyBuffer_Type (C variable)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBufferObject">PyBufferObject (C type)</a>
</li>
      <li><a href="c-api/buffer.html#index-1">PyBufferProcs</a>

      <ul>
        <li><a href="c-api/typeobj.html#c.PyBufferProcs">(C type)</a>
</li>
      </ul></li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_AS_STRING">PyByteArray_AS_STRING (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_AsString">PyByteArray_AsString (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Check">PyByteArray_Check (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_CheckExact">PyByteArray_CheckExact (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Concat">PyByteArray_Concat (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_FromObject">PyByteArray_FromObject (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_FromStringAndSize">PyByteArray_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_GET_SIZE">PyByteArray_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Resize">PyByteArray_Resize (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Size">PyByteArray_Size (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Type">PyByteArray_Type (C variable)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArrayObject">PyByteArrayObject (C type)</a>
</li>
      <li><a href="c-api/object.html#c.PyCallable_Check">PyCallable_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_Check">PyCallIter_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_New">PyCallIter_New (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_Type">PyCallIter_Type (C variable)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule">PyCapsule (C type)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_CheckExact">PyCapsule_CheckExact (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_Destructor">PyCapsule_Destructor (C type)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetContext">PyCapsule_GetContext (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetDestructor">PyCapsule_GetDestructor (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetName">PyCapsule_GetName (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetPointer">PyCapsule_GetPointer (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_Import">PyCapsule_Import (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_IsValid">PyCapsule_IsValid (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_New">PyCapsule_New (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetContext">PyCapsule_SetContext (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetDestructor">PyCapsule_SetDestructor (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetName">PyCapsule_SetName (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetPointer">PyCapsule_SetPointer (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Check">PyCell_Check (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_GET">PyCell_GET (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Get">PyCell_Get (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_New">PyCell_New (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_SET">PyCell_SET (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Set">PyCell_Set (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Type">PyCell_Type (C variable)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCellObject">PyCellObject (C type)</a>
</li>
      <li><a href="c-api/structures.html#c.PyCFunction">PyCFunction (C type)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_Check">PyClass_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_IsSubclass">PyClass_IsSubclass (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_Type">PyClass_Type (C variable)</a>
</li>
      <li><a href="c-api/class.html#c.PyClassObject">PyClassObject (C type)</a>
</li>
      <li><a href="library/pyclbr.html#module-pyclbr">pyclbr (module)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject">PyCObject (C type)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_AsVoidPtr">PyCObject_AsVoidPtr (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_Check">PyCObject_Check (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_FromVoidPtr">PyCObject_FromVoidPtr (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_FromVoidPtrAndDesc">PyCObject_FromVoidPtrAndDesc (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_GetDesc">PyCObject_GetDesc (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_SetVoidPtr">PyCObject_SetVoidPtr (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_Check">PyCode_Check (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_GetNumFree">PyCode_GetNumFree (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_New">PyCode_New (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_NewEmpty">PyCode_NewEmpty (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_Type">PyCode_Type (C variable)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_BackslashReplaceErrors">PyCodec_BackslashReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Decode">PyCodec_Decode (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Decoder">PyCodec_Decoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Encode">PyCodec_Encode (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Encoder">PyCodec_Encoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IgnoreErrors">PyCodec_IgnoreErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IncrementalDecoder">PyCodec_IncrementalDecoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IncrementalEncoder">PyCodec_IncrementalEncoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_KnownEncoding">PyCodec_KnownEncoding (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_LookupError">PyCodec_LookupError (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Register">PyCodec_Register (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_RegisterError">PyCodec_RegisterError (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_ReplaceErrors">PyCodec_ReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StreamReader">PyCodec_StreamReader (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StreamWriter">PyCodec_StreamWriter (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StrictErrors">PyCodec_StrictErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_XMLCharRefReplaceErrors">PyCodec_XMLCharRefReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCodeObject">PyCodeObject (C type)</a>
</li>
      <li><a href="library/py_compile.html#py_compile.PyCompileError">PyCompileError</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyCompilerFlags">PyCompilerFlags (C type)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_AsCComplex">PyComplex_AsCComplex (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_Check">PyComplex_Check (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_CheckExact">PyComplex_CheckExact (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_FromCComplex">PyComplex_FromCComplex (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_FromDoubles">PyComplex_FromDoubles (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_ImagAsDouble">PyComplex_ImagAsDouble (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_RealAsDouble">PyComplex_RealAsDouble (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_Type">PyComplex_Type (C variable)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplexObject">PyComplexObject (C type)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_Check">PyDate_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_CheckExact">PyDate_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_FromDate">PyDate_FromDate (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_FromTimestamp">PyDate_FromTimestamp (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_Check">PyDateTime_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_CheckExact">PyDateTime_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_HOUR">PyDateTime_DATE_GET_HOUR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_MICROSECOND">PyDateTime_DATE_GET_MICROSECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_MINUTE">PyDateTime_DATE_GET_MINUTE (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_SECOND">PyDateTime_DATE_GET_SECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_FromDateAndTime">PyDateTime_FromDateAndTime (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_FromTimestamp">PyDateTime_FromTimestamp (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_DAY">PyDateTime_GET_DAY (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_MONTH">PyDateTime_GET_MONTH (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_YEAR">PyDateTime_GET_YEAR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_HOUR">PyDateTime_TIME_GET_HOUR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_MICROSECOND">PyDateTime_TIME_GET_MICROSECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_MINUTE">PyDateTime_TIME_GET_MINUTE (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_SECOND">PyDateTime_TIME_GET_SECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_Check">PyDelta_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_CheckExact">PyDelta_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_FromDSU">PyDelta_FromDSU (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_IsData">PyDescr_IsData (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewClassMethod">PyDescr_NewClassMethod (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewGetSet">PyDescr_NewGetSet (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewMember">PyDescr_NewMember (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewMethod">PyDescr_NewMethod (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewWrapper">PyDescr_NewWrapper (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Check">PyDict_Check (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_CheckExact">PyDict_CheckExact (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Clear">PyDict_Clear (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Contains">PyDict_Contains (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Copy">PyDict_Copy (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_DelItem">PyDict_DelItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_DelItemString">PyDict_DelItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_GetItem">PyDict_GetItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_GetItemString">PyDict_GetItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Items">PyDict_Items (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Keys">PyDict_Keys (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Merge">PyDict_Merge (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_MergeFromSeq2">PyDict_MergeFromSeq2 (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_New">PyDict_New (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Next">PyDict_Next (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_SetItem">PyDict_SetItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_SetItemString">PyDict_SetItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Size">PyDict_Size (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Type">PyDict_Type (C variable)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Update">PyDict_Update (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Values">PyDict_Values (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDictObject">PyDictObject (C type)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDictProxy_New">PyDictProxy_New (C function)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL">PyDLL (class in ctypes)</a>
</li>
      <li><a href="library/pydoc.html#module-pydoc">pydoc (module)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_BadArgument">PyErr_BadArgument (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_BadInternalCall">PyErr_BadInternalCall (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_CheckSignals">PyErr_CheckSignals (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Clear">PyErr_Clear (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-13">PyErr_Clear()</a>, <a href="c-api/intro.html#index-19">[1]</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_ExceptionMatches">PyErr_ExceptionMatches (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-19">PyErr_ExceptionMatches()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Fetch">PyErr_Fetch (C function)</a>
</li>
      <li><a href="extending/newtypes.html#index-1">PyErr_Fetch()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Format">PyErr_Format (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_GivenExceptionMatches">PyErr_GivenExceptionMatches (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NewException">PyErr_NewException (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NewExceptionWithDoc">PyErr_NewExceptionWithDoc (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NoMemory">PyErr_NoMemory (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NormalizeException">PyErr_NormalizeException (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Occurred">PyErr_Occurred (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-12">PyErr_Occurred()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Print">PyErr_Print (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_PrintEx">PyErr_PrintEx (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Restore">PyErr_Restore (C function)</a>
</li>
      <li><a href="extending/newtypes.html#index-1">PyErr_Restore()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErr">PyErr_SetExcFromWindowsErr (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErrWithFilename">PyErr_SetExcFromWindowsErrWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErrWithFilenameObject">PyErr_SetExcFromWindowsErrWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrno">PyErr_SetFromErrno (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrnoWithFilename">PyErr_SetFromErrnoWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrnoWithFilenameObject">PyErr_SetFromErrnoWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErr">PyErr_SetFromWindowsErr (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErrWithFilename">PyErr_SetFromWindowsErrWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErrWithFilenameObject">PyErr_SetFromWindowsErrWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetInterrupt">PyErr_SetInterrupt (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetNone">PyErr_SetNone (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetObject">PyErr_SetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetString">PyErr_SetString (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-13">PyErr_SetString()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Warn">PyErr_Warn (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnEx">PyErr_WarnEx (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnExplicit">PyErr_WarnExplicit (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnPy3k">PyErr_WarnPy3k (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WriteUnraisable">PyErr_WriteUnraisable (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_AcquireLock">PyEval_AcquireLock (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_AcquireLock()</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_AcquireThread">PyEval_AcquireThread (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalCode">PyEval_EvalCode (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalCodeEx">PyEval_EvalCodeEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalFrame">PyEval_EvalFrame (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalFrameEx">PyEval_EvalFrameEx (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetBuiltins">PyEval_GetBuiltins (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_GetCallStats">PyEval_GetCallStats (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFrame">PyEval_GetFrame (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFuncDesc">PyEval_GetFuncDesc (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFuncName">PyEval_GetFuncName (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetGlobals">PyEval_GetGlobals (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetLocals">PyEval_GetLocals (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetRestricted">PyEval_GetRestricted (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_InitThreads">PyEval_InitThreads (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_InitThreads()</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_MergeCompilerFlags">PyEval_MergeCompilerFlags (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReInitThreads">PyEval_ReInitThreads (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReleaseLock">PyEval_ReleaseLock (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_ReleaseLock()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReleaseThread">PyEval_ReleaseThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-18">PyEval_ReleaseThread()</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_RestoreThread">PyEval_RestoreThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-17">PyEval_RestoreThread()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SaveThread">PyEval_SaveThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-17">PyEval_SaveThread()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SetProfile">PyEval_SetProfile (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SetTrace">PyEval_SetTrace (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ThreadsInitialized">PyEval_ThreadsInitialized (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ArithmeticError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_AssertionError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_AttributeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_BaseException</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_BufferError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_BytesWarning</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="c-api/exceptions.html#index-5">PyExc_DeprecationWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_EnvironmentError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_EOFError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_Exception</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_FloatingPointError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_FutureWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_GeneratorExit</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ImportError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_ImportWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IndentationError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IndexError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IOError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_KeyboardInterrupt</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_KeyError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_LookupError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_MemoryError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_NameError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_NotImplementedError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_OSError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_OverflowError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_PendingDeprecationWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ReferenceError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_RuntimeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_RuntimeWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_StandardError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_StopIteration</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SyntaxError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_SyntaxWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SystemError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SystemExit</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_TabError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_TypeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnboundLocalError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeDecodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeEncodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeTranslateError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_UnicodeWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_UserWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ValueError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_VMSError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_Warning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_WindowsError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ZeroDivisionError</a>
</li>
      <li>
    pyexpat

      <ul>
        <li><a href="library/pyexpat.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="c-api/file.html#c.PyFile_AsFile">PyFile_AsFile (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Check">PyFile_Check (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_CheckExact">PyFile_CheckExact (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_DecUseCount">PyFile_DecUseCount (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_FromFile">PyFile_FromFile (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_FromString">PyFile_FromString (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_GetLine">PyFile_GetLine (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_IncUseCount">PyFile_IncUseCount (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Name">PyFile_Name (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetBufSize">PyFile_SetBufSize (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetEncoding">PyFile_SetEncoding (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetEncodingAndErrors">PyFile_SetEncodingAndErrors (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SoftSpace">PyFile_SoftSpace (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Type">PyFile_Type (C variable)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_WriteObject">PyFile_WriteObject (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_WriteString">PyFile_WriteString (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFileObject">PyFileObject (C type)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AS_DOUBLE">PyFloat_AS_DOUBLE (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsDouble">PyFloat_AsDouble (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsReprString">PyFloat_AsReprString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsString">PyFloat_AsString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_Check">PyFloat_Check (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_CheckExact">PyFloat_CheckExact (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_ClearFreeList">PyFloat_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_FromDouble">PyFloat_FromDouble (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_FromString">PyFloat_FromString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetInfo">PyFloat_GetInfo (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetMax">PyFloat_GetMax (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetMin">PyFloat_GetMin (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_Type">PyFloat_Type (C variable)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloatObject">PyFloatObject (C type)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyFrame_GetLineNumber">PyFrame_GetLineNumber (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_Check">PyFrozenSet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_CheckExact">PyFrozenSet_CheckExact (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_New">PyFrozenSet_New (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_Type">PyFrozenSet_Type (C variable)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_Check">PyFunction_Check (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetClosure">PyFunction_GetClosure (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetCode">PyFunction_GetCode (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetDefaults">PyFunction_GetDefaults (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetGlobals">PyFunction_GetGlobals (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetModule">PyFunction_GetModule (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_New">PyFunction_New (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_SetClosure">PyFunction_SetClosure (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_SetDefaults">PyFunction_SetDefaults (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_Type">PyFunction_Type (C variable)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunctionObject">PyFunctionObject (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PYFUNCTYPE">PYFUNCTYPE() (in module ctypes)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_Check">PyGen_Check (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_CheckExact">PyGen_CheckExact (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_New">PyGen_New (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_Type">PyGen_Type (C variable)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGenObject">PyGenObject (C type)</a>
</li>
      <li><a href="c-api/structures.html#c.PyGetSetDef">PyGetSetDef (C type)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_Ensure">PyGILState_Ensure (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_GetThisThreadState">PyGILState_GetThisThreadState (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_Release">PyGILState_Release (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_AddModule">PyImport_AddModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_AppendInittab">PyImport_AppendInittab (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_Cleanup">PyImport_Cleanup (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExecCodeModule">PyImport_ExecCodeModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExecCodeModuleEx">PyImport_ExecCodeModuleEx (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExtendInittab">PyImport_ExtendInittab (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_FrozenModules">PyImport_FrozenModules (C variable)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetImporter">PyImport_GetImporter (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetMagicNumber">PyImport_GetMagicNumber (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetModuleDict">PyImport_GetModuleDict (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_Import">PyImport_Import (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportFrozenModule">PyImport_ImportFrozenModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModule">PyImport_ImportModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleEx">PyImport_ImportModuleEx (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleLevel">PyImport_ImportModuleLevel (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleNoBlock">PyImport_ImportModuleNoBlock (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ReloadModule">PyImport_ReloadModule (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyIndex_Check">PyIndex_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_Check">PyInstance_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_New">PyInstance_New (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_NewRaw">PyInstance_NewRaw (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_Type">PyInstance_Type (C variable)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AS_LONG">PyInt_AS_LONG (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsLong">PyInt_AsLong (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsSsize_t">PyInt_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsUnsignedLongLongMask">PyInt_AsUnsignedLongLongMask (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsUnsignedLongMask">PyInt_AsUnsignedLongMask (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_Check">PyInt_Check (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_CheckExact">PyInt_CheckExact (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_ClearFreeList">PyInt_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromLong">PyInt_FromLong (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromSize_t">PyInt_FromSize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromSsize_t">PyInt_FromSsize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromString">PyInt_FromString (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_GetMax">PyInt_GetMax (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_Type">PyInt_Type (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState">PyInterpreterState (C type)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Clear">PyInterpreterState_Clear (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Delete">PyInterpreterState_Delete (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Head">PyInterpreterState_Head (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_New">PyInterpreterState_New (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Next">PyInterpreterState_Next (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_ThreadHead">PyInterpreterState_ThreadHead (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyIntObject">PyIntObject (C type)</a>
</li>
      <li><a href="c-api/iter.html#c.PyIter_Check">PyIter_Check (C function)</a>
</li>
      <li><a href="c-api/iter.html#c.PyIter_Next">PyIter_Next (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Append">PyList_Append (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_AsTuple">PyList_AsTuple (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Check">PyList_Check (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_CheckExact">PyList_CheckExact (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GET_ITEM">PyList_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GET_SIZE">PyList_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GetItem">PyList_GetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-9">PyList_GetItem()</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GetSlice">PyList_GetSlice (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Insert">PyList_Insert (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_New">PyList_New (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Reverse">PyList_Reverse (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SET_ITEM">PyList_SET_ITEM (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SetItem">PyList_SetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-7">PyList_SetItem()</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SetSlice">PyList_SetSlice (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Size">PyList_Size (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Sort">PyList_Sort (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Type">PyList_Type (C variable)</a>
</li>
      <li><a href="c-api/list.html#c.PyListObject">PyListObject (C type)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsDouble">PyLong_AsDouble (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLong">PyLong_AsLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongAndOverflow">PyLong_AsLongAndOverflow (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongLong">PyLong_AsLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongLongAndOverflow">PyLong_AsLongLongAndOverflow (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsSsize_t">PyLong_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLong">PyLong_AsUnsignedLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongLong">PyLong_AsUnsignedLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongLongMask">PyLong_AsUnsignedLongLongMask (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongMask">PyLong_AsUnsignedLongMask (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsVoidPtr">PyLong_AsVoidPtr (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_Check">PyLong_Check (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_CheckExact">PyLong_CheckExact (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromDouble">PyLong_FromDouble (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromLong">PyLong_FromLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromLongLong">PyLong_FromLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromSize_t">PyLong_FromSize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromSsize_t">PyLong_FromSsize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromString">PyLong_FromString (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnicode">PyLong_FromUnicode (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnsignedLong">PyLong_FromUnsignedLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnsignedLongLong">PyLong_FromUnsignedLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromVoidPtr">PyLong_FromVoidPtr (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_Type">PyLong_Type (C variable)</a>
</li>
      <li><a href="c-api/long.html#c.PyLongObject">PyLongObject (C type)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Check">PyMapping_Check (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_DelItem">PyMapping_DelItem (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_DelItemString">PyMapping_DelItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_GetItemString">PyMapping_GetItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_HasKey">PyMapping_HasKey (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_HasKeyString">PyMapping_HasKeyString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Items">PyMapping_Items (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Keys">PyMapping_Keys (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Length">PyMapping_Length (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_SetItemString">PyMapping_SetItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Size">PyMapping_Size (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Values">PyMapping_Values (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods">PyMappingMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_ass_subscript">PyMappingMethods.mp_ass_subscript (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_length">PyMappingMethods.mp_length (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_subscript">PyMappingMethods.mp_subscript (C member)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadLastObjectFromFile">PyMarshal_ReadLastObjectFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadLongFromFile">PyMarshal_ReadLongFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadObjectFromFile">PyMarshal_ReadObjectFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadObjectFromString">PyMarshal_ReadObjectFromString (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadShortFromFile">PyMarshal_ReadShortFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteLongToFile">PyMarshal_WriteLongToFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteObjectToFile">PyMarshal_WriteObjectToFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteObjectToString">PyMarshal_WriteObjectToString (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Del">PyMem_Del (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Free">PyMem_Free (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Malloc">PyMem_Malloc (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_New">PyMem_New (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Realloc">PyMem_Realloc (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Resize">PyMem_Resize (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyMemberDef">PyMemberDef (C type)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_Check">PyMemoryView_Check (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_FromBuffer">PyMemoryView_FromBuffer (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_FromObject">PyMemoryView_FromObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_GET_BUFFER">PyMemoryView_GET_BUFFER (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_GetContiguous">PyMemoryView_GetContiguous (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Check">PyMethod_Check (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Class">PyMethod_Class (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_ClearFreeList">PyMethod_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Function">PyMethod_Function (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_CLASS">PyMethod_GET_CLASS (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_FUNCTION">PyMethod_GET_FUNCTION (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_SELF">PyMethod_GET_SELF (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_New">PyMethod_New (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Self">PyMethod_Self (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Type">PyMethod_Type (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.PyMethodDef">PyMethodDef (C type)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddIntConstant">PyModule_AddIntConstant (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddIntMacro">PyModule_AddIntMacro (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddObject">PyModule_AddObject (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddStringConstant">PyModule_AddStringConstant (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddStringMacro">PyModule_AddStringMacro (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_Check">PyModule_Check (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_CheckExact">PyModule_CheckExact (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetDict">PyModule_GetDict (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetFilename">PyModule_GetFilename (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetName">PyModule_GetName (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_New">PyModule_New (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_Type">PyModule_Type (C variable)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Absolute">PyNumber_Absolute (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Add">PyNumber_Add (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_And">PyNumber_And (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_AsSsize_t">PyNumber_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Check">PyNumber_Check (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Coerce">PyNumber_Coerce (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_CoerceEx">PyNumber_CoerceEx (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Divide">PyNumber_Divide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Divmod">PyNumber_Divmod (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Float">PyNumber_Float (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_FloorDivide">PyNumber_FloorDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Index">PyNumber_Index (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceAdd">PyNumber_InPlaceAdd (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceAnd">PyNumber_InPlaceAnd (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceDivide">PyNumber_InPlaceDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceFloorDivide">PyNumber_InPlaceFloorDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceLshift">PyNumber_InPlaceLshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceMultiply">PyNumber_InPlaceMultiply (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceOr">PyNumber_InPlaceOr (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlacePower">PyNumber_InPlacePower (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceRemainder">PyNumber_InPlaceRemainder (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceRshift">PyNumber_InPlaceRshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceSubtract">PyNumber_InPlaceSubtract (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceTrueDivide">PyNumber_InPlaceTrueDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceXor">PyNumber_InPlaceXor (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Int">PyNumber_Int (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Invert">PyNumber_Invert (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Long">PyNumber_Long (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Lshift">PyNumber_Lshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Multiply">PyNumber_Multiply (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Negative">PyNumber_Negative (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Or">PyNumber_Or (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Positive">PyNumber_Positive (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Power">PyNumber_Power (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Remainder">PyNumber_Remainder (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Rshift">PyNumber_Rshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Subtract">PyNumber_Subtract (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_ToBase">PyNumber_ToBase (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_TrueDivide">PyNumber_TrueDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Xor">PyNumber_Xor (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyNumberMethods">PyNumberMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyNumberMethods.nb_coerce">PyNumberMethods.nb_coerce (C member)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject">PyObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject._ob_next">PyObject._ob_next (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject._ob_prev">PyObject._ob_prev (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject.ob_refcnt">PyObject.ob_refcnt (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject.ob_type">PyObject.ob_type (C member)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsCharBuffer">PyObject_AsCharBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_AsFileDescriptor">PyObject_AsFileDescriptor (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsReadBuffer">PyObject_AsReadBuffer (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsWriteBuffer">PyObject_AsWriteBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Bytes">PyObject_Bytes (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Call">PyObject_Call (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallFunction">PyObject_CallFunction (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallFunctionObjArgs">PyObject_CallFunctionObjArgs (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallMethod">PyObject_CallMethod (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallMethodObjArgs">PyObject_CallMethodObjArgs (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallObject">PyObject_CallObject (C function)</a>
</li>
      <li><a href="extending/extending.html#index-0">PyObject_CallObject()</a>
</li>
      <li><a href="c-api/buffer.html#c.PyObject_CheckBuffer">PyObject_CheckBuffer (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_CheckReadBuffer">PyObject_CheckReadBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Cmp">PyObject_Cmp (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Compare">PyObject_Compare (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_Del">PyObject_Del (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelAttr">PyObject_DelAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelAttrString">PyObject_DelAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelItem">PyObject_DelItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Dir">PyObject_Dir (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Free">PyObject_Free (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Del">PyObject_GC_Del (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_New">PyObject_GC_New (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_NewVar">PyObject_GC_NewVar (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Resize">PyObject_GC_Resize (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Track">PyObject_GC_Track (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_UnTrack">PyObject_GC_UnTrack (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GenericGetAttr">PyObject_GenericGetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GenericSetAttr">PyObject_GenericSetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetAttr">PyObject_GetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetAttrString">PyObject_GetAttrString (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyObject_GetBuffer">PyObject_GetBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetItem">PyObject_GetItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetIter">PyObject_GetIter (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HasAttr">PyObject_HasAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HasAttrString">PyObject_HasAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Hash">PyObject_Hash (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HashNotImplemented">PyObject_HashNotImplemented (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_HEAD">PyObject_HEAD (C macro)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_HEAD_INIT">PyObject_HEAD_INIT (C macro)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_Init">PyObject_Init (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_InitVar">PyObject_InitVar (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsInstance">PyObject_IsInstance (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsSubclass">PyObject_IsSubclass (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsTrue">PyObject_IsTrue (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Length">PyObject_Length (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Malloc">PyObject_Malloc (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_New">PyObject_New (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_NewVar">PyObject_NewVar (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Not">PyObject_Not (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Print">PyObject_Print (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Realloc">PyObject_Realloc (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Repr">PyObject_Repr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_RichCompare">PyObject_RichCompare (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_RichCompareBool">PyObject_RichCompareBool (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetAttr">PyObject_SetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetAttrString">PyObject_SetAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetItem">PyObject_SetItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Size">PyObject_Size (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Str">PyObject_Str (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Type">PyObject_Type (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_TypeCheck">PyObject_TypeCheck (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Unicode">PyObject_Unicode (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_VAR_HEAD">PyObject_VAR_HEAD (C macro)</a>
</li>
      <li><a href="library/gl.html#index-0">PyOpenGL</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_AfterFork">PyOS_AfterFork (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_atof">PyOS_ascii_atof (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_formatd">PyOS_ascii_formatd (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_strtod">PyOS_ascii_strtod (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_CheckStack">PyOS_CheckStack (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_double_to_string">PyOS_double_to_string (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_getsig">PyOS_getsig (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_setsig">PyOS_setsig (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_snprintf">PyOS_snprintf (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_stricmp">PyOS_stricmp (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_string_to_double">PyOS_string_to_double (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_strnicmp">PyOS_strnicmp (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_vsnprintf">PyOS_vsnprintf (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseFile">PyParser_SimpleParseFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseFileFlags">PyParser_SimpleParseFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseString">PyParser_SimpleParseString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseStringFlags">PyParser_SimpleParseStringFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseStringFlagsFilename">PyParser_SimpleParseStringFlagsFilename (C function)</a>
</li>
      <li>
    PyPI

      <ul>
        <li><a href="distutils/packageindex.html#index-0">(see Python Package Index (PyPI))</a>
</li>
      </ul></li>
      <li><a href="c-api/descriptor.html#c.PyProperty_Type">PyProperty_Type (C variable)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFile">PyRun_AnyFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileEx">PyRun_AnyFileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileExFlags">PyRun_AnyFileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileFlags">PyRun_AnyFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_File">PyRun_File (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileEx">PyRun_FileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileExFlags">PyRun_FileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileFlags">PyRun_FileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveLoop">PyRun_InteractiveLoop (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveLoopFlags">PyRun_InteractiveLoopFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveOne">PyRun_InteractiveOne (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveOneFlags">PyRun_InteractiveOneFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFile">PyRun_SimpleFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileEx">PyRun_SimpleFileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileExFlags">PyRun_SimpleFileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileFlags">PyRun_SimpleFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleString">PyRun_SimpleString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleStringFlags">PyRun_SimpleStringFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_String">PyRun_String (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_StringFlags">PyRun_StringFlags (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_Check">PySeqIter_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_New">PySeqIter_New (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_Type">PySeqIter_Type (C variable)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Check">PySequence_Check (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Concat">PySequence_Concat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Contains">PySequence_Contains (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Count">PySequence_Count (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_DelItem">PySequence_DelItem (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_DelSlice">PySequence_DelSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast">PySequence_Fast (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_GET_ITEM">PySequence_Fast_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_GET_SIZE">PySequence_Fast_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_ITEMS">PySequence_Fast_ITEMS (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_GetItem">PySequence_GetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-9">PySequence_GetItem()</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_GetSlice">PySequence_GetSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Index">PySequence_Index (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_InPlaceConcat">PySequence_InPlaceConcat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_InPlaceRepeat">PySequence_InPlaceRepeat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_ITEM">PySequence_ITEM (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Length">PySequence_Length (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_List">PySequence_List (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Repeat">PySequence_Repeat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_SetItem">PySequence_SetItem (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_SetSlice">PySequence_SetSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Size">PySequence_Size (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Tuple">PySequence_Tuple (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods">PySequenceMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_ass_item">PySequenceMethods.sq_ass_item (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_concat">PySequenceMethods.sq_concat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_contains">PySequenceMethods.sq_contains (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_inplace_concat">PySequenceMethods.sq_inplace_concat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_inplace_repeat">PySequenceMethods.sq_inplace_repeat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_item">PySequenceMethods.sq_item (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_length">PySequenceMethods.sq_length (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_repeat">PySequenceMethods.sq_repeat (C member)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Add">PySet_Add (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Check">PySet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Clear">PySet_Clear (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Contains">PySet_Contains (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Discard">PySet_Discard (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_GET_SIZE">PySet_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_New">PySet_New (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Pop">PySet_Pop (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Size">PySet_Size (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Type">PySet_Type (C variable)</a>
</li>
      <li><a href="c-api/set.html#c.PySetObject">PySetObject (C type)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PySignal_SetWakeupFd">PySignal_SetWakeupFd (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_Check">PySlice_Check (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_GetIndices">PySlice_GetIndices (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_GetIndicesEx">PySlice_GetIndicesEx (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_New">PySlice_New (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_Type">PySlice_Type (C variable)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AS_STRING">PyString_AS_STRING (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsDecodedObject">PyString_AsDecodedObject (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsEncodedObject">PyString_AsEncodedObject (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsString">PyString_AsString (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsStringAndSize">PyString_AsStringAndSize (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Check">PyString_Check (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_CheckExact">PyString_CheckExact (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Concat">PyString_Concat (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_ConcatAndDel">PyString_ConcatAndDel (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Decode">PyString_Decode (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Encode">PyString_Encode (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Format">PyString_Format (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromFormat">PyString_FromFormat (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromFormatV">PyString_FromFormatV (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromString">PyString_FromString (C function)</a>
</li>
      <li><a href="c-api/dict.html#index-2">PyString_FromString()</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromStringAndSize">PyString_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_GET_SIZE">PyString_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_InternFromString">PyString_InternFromString (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_InternInPlace">PyString_InternInPlace (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Size">PyString_Size (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Type">PyString_Type (C variable)</a>
</li>
      <li><a href="c-api/string.html#c.PyStringObject">PyStringObject (C type)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_AddWarnOption">PySys_AddWarnOption (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_GetFile">PySys_GetFile (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_GetObject">PySys_GetObject (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_ResetWarnOptions">PySys_ResetWarnOptions (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PySys_SetArgv">PySys_SetArgv (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PySys_SetArgv()</a>
</li>
      <li><a href="c-api/init.html#c.PySys_SetArgvEx">PySys_SetArgvEx (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PySys_SetArgvEx()</a>, <a href="c-api/intro.html#index-21">[1]</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_SetObject">PySys_SetObject (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_SetPath">PySys_SetPath (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_WriteStderr">PySys_WriteStderr (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_WriteStdout">PySys_WriteStdout (C function)</a>
</li>
      <li><a href="glossary.html#term-python-3000"><strong>Python 3000</strong></a>
</li>
      <li><a href="library/idle.html#index-0">Python Editor</a>
</li>
      <li>
    Python Enhancement Proposals

      <ul>
        <li><a href="glossary.html#index-6">PEP 1</a>
</li>
        <li><a href="whatsnew/2.0.html#index-0">PEP 100</a>
</li>
        <li><a href="using/windows.html#index-0">PEP 11</a>
</li>
        <li><a href="library/weakref.html#index-0">PEP 205</a>, <a href="whatsnew/2.1.html#index-6">[1]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-2">PEP 207</a>
</li>
        <li><a href="whatsnew/2.1.html#index-10">PEP 208</a>
</li>
        <li><a href="whatsnew/2.1.html#index-9">PEP 217</a>
</li>
        <li><a href="whatsnew/2.3.html#index-0">PEP 218</a>, <a href="whatsnew/2.4.html#index-0">[1]</a>, <a href="whatsnew/2.4.html#index-13">[2]</a>
</li>
        <li><a href="library/__future__.html#index-0">PEP 227</a>, <a href="whatsnew/2.1.html#index-0">[1]</a>, <a href="whatsnew/2.2.html#index-16">[2]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-5">PEP 229</a>
</li>
        <li><a href="using/cmdline.html#index-14">PEP 230</a>, <a href="whatsnew/2.1.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-7">PEP 232</a>
</li>
        <li><a href="whatsnew/2.2.html#index-7">PEP 234</a>
</li>
        <li><a href="library/functions.html#index-1">PEP 236</a>, <a href="reference/simple_stmts.html#index-53">[1]</a>, <a href="whatsnew/2.1.html#index-1">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-26">PEP 237</a>, <a href="whatsnew/2.2.html#index-10">[1]</a>, <a href="whatsnew/2.4.html#index-1">[2]</a>, <a href="whatsnew/2.4.html#index-16">[3]</a>
</li>
        <li><a href="c-api/veryhigh.html#index-3">PEP 238</a>, <a href="glossary.html#index-2">[1]</a>, <a href="library/__future__.html#index-2">[2]</a>, <a href="using/cmdline.html#index-9">[3]</a>, <a href="whatsnew/2.2.html#index-11">[4]</a>, <a href="whatsnew/2.2.html#index-12">[5]</a>, <a href="whatsnew/2.2.html#index-13">[6]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-11">PEP 241</a>
</li>
        <li><a href="whatsnew/2.1.html#index-12">PEP 243</a>
</li>
        <li><a href="library/sqlite3.html#index-0">PEP 249</a>, <a href="library/sqlite3.html#index-1">[1]</a>, <a href="whatsnew/2.5.html#index-21">[2]</a>, <a href="whatsnew/2.5.html#index-22">[3]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-2">PEP 252</a>, <a href="whatsnew/2.2.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-0">PEP 253</a>, <a href="whatsnew/2.2.html#index-1">[1]</a>, <a href="whatsnew/2.2.html#index-3">[2]</a>, <a href="whatsnew/2.2.html#index-5">[3]</a>, <a href="whatsnew/2.2.html#index-6">[4]</a>
</li>
        <li><a href="library/__future__.html#index-1">PEP 255</a>, <a href="reference/simple_stmts.html#index-29">[1]</a>, <a href="whatsnew/2.2.html#index-8">[2]</a>, <a href="whatsnew/2.2.html#index-9">[3]</a>, <a href="whatsnew/2.3.html#index-1">[4]</a>, <a href="whatsnew/2.3.html#index-2">[5]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-14">PEP 261</a>, <a href="whatsnew/2.2.html#index-15">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-3">PEP 263</a>, <a href="whatsnew/2.5.html#index-17">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-22">PEP 264</a>
</li>
        <li><a href="library/zipimport.html#index-0">PEP 273</a>, <a href="whatsnew/2.3.html#index-4">[1]</a>, <a href="whatsnew/2.3.html#index-5">[2]</a>
</li>
        <li><a href="faq/design.html#index-0">PEP 275</a>
</li>
        <li><a href="whatsnew/2.3.html#index-7">PEP 277</a>
</li>
        <li><a href="glossary.html#index-7">PEP 278</a>, <a href="whatsnew/2.3.html#index-9">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-10">PEP 279</a>
</li>
        <li><a href="library/logging.html#index-1">PEP 282</a>, <a href="library/shutil.html#index-2">[1]</a>, <a href="whatsnew/2.3.html#index-11">[2]</a>, <a href="whatsnew/2.3.html#index-12">[3]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-13">PEP 285</a>, <a href="whatsnew/2.3.html#index-14">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-10">PEP 288</a>
</li>
        <li><a href="howto/functional.html#index-0">PEP 289</a>, <a href="whatsnew/2.4.html#index-15">[1]</a>, <a href="whatsnew/2.4.html#index-2">[2]</a>
</li>
        <li><a href="library/string.html#index-4">PEP 292</a>, <a href="whatsnew/2.4.html#index-3">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-15">PEP 293</a>
</li>
        <li><a href="whatsnew/2.6.html#index-1">PEP 3000</a>
</li>
        <li><a href="distutils/apiref.html#index-4">PEP 301</a>, <a href="whatsnew/2.3.html#index-16">[1]</a>
</li>
        <li><a href="glossary.html#index-1">PEP 302</a>, <a href="glossary.html#index-5">[1]</a>, <a href="library/functions.html#index-9">[2]</a>, <a href="library/imp.html#index-4">[3]</a>, <a href="library/linecache.html#index-1">[4]</a>, <a href="library/pkgutil.html#index-0">[5]</a>, <a href="library/pkgutil.html#index-1">[6]</a>, <a href="library/pkgutil.html#index-10">[7]</a>, <a href="library/pkgutil.html#index-11">[8]</a>, <a href="library/pkgutil.html#index-2">[9]</a>, <a href="library/pkgutil.html#index-3">[10]</a>, <a href="library/pkgutil.html#index-4">[11]</a>, <a href="library/pkgutil.html#index-5">[12]</a>, <a href="library/pkgutil.html#index-6">[13]</a>, <a href="library/pkgutil.html#index-7">[14]</a>, <a href="library/pkgutil.html#index-8">[15]</a>, <a href="library/pkgutil.html#index-9">[16]</a>, <a href="library/runpy.html#index-1">[17]</a>, <a href="library/runpy.html#index-2">[18]</a>, <a href="library/runpy.html#index-4">[19]</a>, <a href="library/sys.html#index-10">[20]</a>, <a href="library/sys.html#index-4">[21]</a>, <a href="library/sys.html#index-9">[22]</a>, <a href="library/zipimport.html#index-1">[23]</a>, <a href="reference/simple_stmts.html#index-42">[24]</a>, <a href="reference/simple_stmts.html#index-45">[25]</a>, <a href="whatsnew/2.3.html#index-17">[26]</a>, <a href="whatsnew/2.3.html#index-18">[27]</a>, <a href="whatsnew/2.3.html#index-19">[28]</a>, <a href="whatsnew/2.3.html#index-6">[29]</a>
</li>
        <li><a href="library/csv.html#index-1">PEP 305</a>, <a href="whatsnew/2.3.html#index-20">[1]</a>
</li>
        <li><a href="library/pickle.html#index-2">PEP 307</a>, <a href="whatsnew/2.3.html#index-21">[1]</a>, <a href="whatsnew/2.3.html#index-22">[2]</a>, <a href="whatsnew/2.3.html#index-23">[3]</a>
</li>
        <li><a href="reference/expressions.html#index-74">PEP 308</a>, <a href="whatsnew/2.5.html#index-1">[1]</a>, <a href="whatsnew/2.5.html#index-2">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-3">PEP 309</a>
</li>
        <li><a href="whatsnew/2.6.html#index-2">PEP 3100</a>
</li>
        <li><a href="library/string.html#index-1">PEP 3101</a>, <a href="library/string.html#index-2">[1]</a>, <a href="whatsnew/2.6.html#index-9">[2]</a>
</li>
        <li><a href="library/__future__.html#index-5">PEP 3105</a>, <a href="whatsnew/2.6.html#index-10">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-6">PEP 3106</a>
</li>
        <li><a href="whatsnew/2.6.html#index-11">PEP 3110</a>
</li>
        <li><a href="library/__future__.html#index-6">PEP 3112</a>, <a href="whatsnew/2.6.html#index-12">[1]</a>
</li>
        <li><a href="glossary.html#index-8">PEP 3116</a>, <a href="whatsnew/2.6.html#index-14">[1]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-15">PEP 3118</a>
</li>
        <li><a href="library/abc.html#index-0">PEP 3119</a>, <a href="library/collections.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-86">[2]</a>, <a href="whatsnew/2.6.html#index-16">[3]</a>
</li>
        <li><a href="howto/cporting.html#index-0">PEP 3121</a>
</li>
        <li><a href="whatsnew/2.6.html#index-17">PEP 3127</a>
</li>
        <li><a href="whatsnew/2.6.html#index-18">PEP 3129</a>
</li>
        <li><a href="whatsnew/2.7.html#index-7">PEP 3137</a>
</li>
        <li><a href="distutils/apiref.html#index-0">PEP 314</a>, <a href="whatsnew/2.5.html#index-4">[1]</a>
</li>
        <li><a href="library/abc.html#index-1">PEP 3141</a>, <a href="library/numbers.html#index-0">[1]</a>, <a href="whatsnew/2.6.html#index-19">[2]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-12">PEP 318</a>, <a href="whatsnew/2.4.html#index-4">[1]</a>, <a href="whatsnew/2.4.html#index-5">[2]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-14">PEP 322</a>, <a href="whatsnew/2.4.html#index-6">[1]</a>
</li>
        <li><a href="library/subprocess.html#index-0">PEP 324</a>, <a href="whatsnew/2.4.html#index-8">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-11">PEP 325</a>
</li>
        <li><a href="whatsnew/2.4.html#index-9">PEP 327</a>
</li>
        <li><a href="library/__future__.html#index-3">PEP 328</a>, <a href="reference/simple_stmts.html#index-51">[1]</a>, <a href="whatsnew/2.4.html#index-10">[2]</a>, <a href="whatsnew/2.4.html#index-17">[3]</a>, <a href="whatsnew/2.5.html#index-5">[4]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-11">PEP 331</a>
</li>
        <li><a href="howto/webservers.html#index-0">PEP 333</a>, <a href="library/wsgiref.html#index-0">[1]</a>, <a href="library/wsgiref.html#index-1">[2]</a>, <a href="library/wsgiref.html#index-10">[3]</a>, <a href="library/wsgiref.html#index-11">[4]</a>, <a href="library/wsgiref.html#index-12">[5]</a>, <a href="library/wsgiref.html#index-13">[6]</a>, <a href="library/wsgiref.html#index-14">[7]</a>, <a href="library/wsgiref.html#index-2">[8]</a>, <a href="library/wsgiref.html#index-3">[9]</a>, <a href="library/wsgiref.html#index-4">[10]</a>, <a href="library/wsgiref.html#index-6">[11]</a>, <a href="library/wsgiref.html#index-7">[12]</a>, <a href="library/wsgiref.html#index-8">[13]</a>, <a href="library/wsgiref.html#index-9">[14]</a>, <a href="whatsnew/2.5.html#index-23">[15]</a>, <a href="whatsnew/2.5.html#index-24">[16]</a>
</li>
        <li><a href="library/runpy.html#index-5">PEP 338</a>, <a href="using/cmdline.html#index-0">[1]</a>, <a href="whatsnew/2.5.html#index-6">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-27">PEP 339</a>
</li>
        <li><a href="whatsnew/2.5.html#index-7">PEP 341</a>
</li>
        <li><a href="howto/functional.html#index-1">PEP 342</a>, <a href="reference/expressions.html#index-27">[1]</a>, <a href="reference/simple_stmts.html#index-30">[2]</a>, <a href="whatsnew/2.5.html#index-28">[3]</a>, <a href="whatsnew/2.5.html#index-8">[4]</a>, <a href="whatsnew/2.5.html#index-9">[5]</a>
</li>
        <li><a href="glossary.html#index-0">PEP 343</a>, <a href="library/__future__.html#index-4">[1]</a>, <a href="library/contextlib.html#index-0">[2]</a>, <a href="reference/compound_stmts.html#index-16">[3]</a>, <a href="reference/datamodel.html#index-97">[4]</a>, <a href="whatsnew/2.5.html#index-12">[5]</a>, <a href="whatsnew/2.6.html#index-3">[6]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-25">PEP 347</a>
</li>
        <li><a href="whatsnew/2.5.html#index-13">PEP 352</a>, <a href="whatsnew/2.6.html#index-25">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-14">PEP 353</a>, <a href="whatsnew/2.5.html#index-15">[1]</a>, <a href="whatsnew/2.5.html#index-26">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-0">PEP 356</a>
</li>
        <li><a href="whatsnew/2.5.html#index-16">PEP 357</a>
</li>
        <li><a href="whatsnew/2.6.html#index-0">PEP 361</a>
</li>
        <li><a href="library/runpy.html#index-6">PEP 366</a>
</li>
        <li><a href="library/site.html#index-9">PEP 370</a>, <a href="using/cmdline.html#index-11">[1]</a>, <a href="using/cmdline.html#index-24">[2]</a>, <a href="using/cmdline.html#index-25">[3]</a>, <a href="whatsnew/2.6.html#index-7">[4]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-8">PEP 371</a>
</li>
        <li><a href="whatsnew/2.7.html#index-2">PEP 372</a>
</li>
        <li><a href="whatsnew/2.7.html#index-0">PEP 373</a>
</li>
        <li><a href="library/string.html#index-3">PEP 378</a>, <a href="whatsnew/2.7.html#index-3">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-4">PEP 389</a>
</li>
        <li><a href="whatsnew/2.7.html#index-5">PEP 391</a>
</li>
        <li><a href="distributing/index.html#index-0">PEP 427</a>
</li>
        <li><a href="whatsnew/2.7.html#index-16">PEP 434</a>
</li>
        <li><a href="library/ensurepip.html#index-0">PEP 453</a>, <a href="whatsnew/2.7.html#index-22">[1]</a>, <a href="whatsnew/2.7.html#index-23">[2]</a>, <a href="whatsnew/2.7.html#index-24">[3]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-17">PEP 466</a>, <a href="whatsnew/2.7.html#index-18">[1]</a>, <a href="whatsnew/2.7.html#index-19">[2]</a>, <a href="whatsnew/2.7.html#index-20">[3]</a>
</li>
        <li><a href="library/ssl.html#index-2">PEP 476</a>, <a href="whatsnew/2.7.html#index-25">[1]</a>
</li>
        <li><a href="library/ensurepip.html#index-1">PEP 477</a>, <a href="whatsnew/2.7.html#index-21">[1]</a>
</li>
        <li><a href="library/ssl.html#index-3">PEP 493</a>, <a href="whatsnew/2.7.html#index-26">[1]</a>
</li>
        <li><a href="faq/general.html#index-1">PEP 5</a>, <a href="whatsnew/2.1.html#index-3">[1]</a>
</li>
        <li><a href="faq/general.html#index-0">PEP 6</a>
</li>
        <li><a href="faq/programming.html#index-0">PEP 8</a>, <a href="faq/windows.html#index-0">[1]</a>, <a href="library/email.html#index-7">[2]</a>, <a href="library/threading.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-6">[4]</a>, <a href="using/unix.html#index-3">[5]</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">Python Imaging Library</a>
</li>
      <li><a href="distutils/packageindex.html#index-0">Python Package Index (PyPI)</a>

      <ul>
        <li><a href="distutils/packageindex.html#index-2">.pypirc file</a>
</li>
      </ul></li>
      <li><a href="using/cmdline.html#index-3">PYTHON*</a>
</li>
      <li><a href="library/platform.html#platform.python_branch">python_branch() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_build">python_build() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_compiler">python_compiler() (in module platform)</a>
</li>
      <li><a href="library/xml.dom.html#index-0">PYTHON_DOM</a>
</li>
      <li><a href="library/platform.html#platform.python_implementation">python_implementation() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_revision">python_revision() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_version">python_version() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_version_tuple">python_version_tuple() (in module platform)</a>
</li>
      <li><a href="whatsnew/2.1.html#index-8">PYTHONCASEOK</a>
</li>
      <li><a href="using/cmdline.html#index-2">PYTHONDEBUG</a>
</li>
      <li><a href="library/pydoc.html#index-2">PYTHONDOCS</a>
</li>
      <li><a href="library/sys.html#index-0">PYTHONDONTWRITEBYTECODE</a>, <a href="using/cmdline.html#index-1">[1]</a>, <a href="whatsnew/2.6.html#index-20">[2]</a>, <a href="whatsnew/2.6.html#index-24">[3]</a>
</li>
      <li><a href="c-api/typeobj.html#index-0">PYTHONDUMPREFS</a>
</li>
      <li><a href="library/random.html#index-0">PYTHONHASHSEED</a>, <a href="using/cmdline.html#index-10">[1]</a>, <a href="using/cmdline.html#index-23">[2]</a>
</li>
      <li><a href="c-api/init.html#index-11">PYTHONHOME</a>, <a href="c-api/init.html#index-12">[1]</a>, <a href="c-api/intro.html#index-24">[2]</a>, <a href="c-api/intro.html#index-27">[3]</a>, <a href="install/index.html#index-0">[4]</a>, <a href="install/index.html#index-1">[5]</a>, <a href="using/cmdline.html#index-16">[6]</a>, <a href="using/cmdline.html#index-17">[7]</a>, <a href="using/cmdline.html#index-20">[8]</a>, <a href="using/cmdline.html#index-5">[9]</a>, <a href="using/windows.html#index-3">[10]</a>
</li>
      <li><a href="glossary.html#term-pythonic"><strong>Pythonic</strong></a>
</li>
      <li><a href="using/cmdline.html#index-7">PYTHONINSPECT</a>, <a href="whatsnew/2.3.html#index-29">[1]</a>
</li>
      <li><a href="whatsnew/2.6.html#index-21">PYTHONIOENCODING</a>
</li>
      <li><a href="library/site.html#index-5">PYTHONNOUSERSITE</a>, <a href="library/site.html#index-8">[1]</a>, <a href="whatsnew/2.6.html#index-6">[2]</a>
</li>
      <li><a href="using/cmdline.html#index-8">PYTHONOPTIMIZE</a>
</li>
      <li><a href="c-api/intro.html#index-25">PYTHONPATH</a>, <a href="c-api/intro.html#index-28">[1]</a>, <a href="install/index.html#index-2">[2]</a>, <a href="install/index.html#index-3">[3]</a>, <a href="library/cgi.html#index-3">[4]</a>, <a href="library/sys.html#index-7">[5]</a>, <a href="library/sys.html#index-8">[6]</a>, <a href="tutorial/modules.html#index-1">[7]</a>, <a href="tutorial/modules.html#index-5">[8]</a>, <a href="tutorial/modules.html#index-6">[9]</a>, <a href="using/cmdline.html#index-19">[10]</a>, <a href="using/cmdline.html#index-21">[11]</a>, <a href="using/cmdline.html#index-22">[12]</a>, <a href="using/cmdline.html#index-4">[13]</a>, <a href="using/mac.html#index-0">[14]</a>, <a href="using/windows.html#index-2">[15]</a>, <a href="using/windows.html#index-4">[16]</a>
</li>
      <li><a href="c-api/typeobj.html#index-3">PYTHONSHOWALLOCCOUNT</a>, <a href="whatsnew/2.7.html#index-15">[1]</a>
</li>
      <li><a href="whatsnew/2.7.html#index-14">PYTHONSHOWREFCOUNT</a>
</li>
      <li><a href="library/idle.html#index-6">PYTHONSTARTUP</a>, <a href="library/readline.html#index-0">[1]</a>, <a href="library/rlcompleter.html#index-0">[2]</a>, <a href="library/user.html#index-1">[3]</a>, <a href="tutorial/appendix.html#index-1">[4]</a>, <a href="tutorial/interactive.html#index-1">[5]</a>, <a href="using/cmdline.html#index-6">[6]</a>
</li>
      <li><a href="using/cmdline.html#index-12">PYTHONUNBUFFERED</a>
</li>
      <li><a href="library/site.html#index-6">PYTHONUSERBASE</a>, <a href="library/site.html#index-7">[1]</a>, <a href="whatsnew/2.6.html#index-4">[2]</a>
</li>
      <li><a href="using/cmdline.html#index-13">PYTHONVERBOSE</a>
</li>
      <li><a href="using/cmdline.html#index-15">PYTHONWARNINGS</a>, <a href="whatsnew/2.7.html#index-1">[1]</a>, <a href="whatsnew/2.7.html#index-8">[2]</a>
</li>
      <li><a href="library/time.html#index-3">PYTHONY2K</a>, <a href="library/time.html#index-4">[1]</a>, <a href="library/time.html#index-7">[2]</a>
</li>
      <li><a href="c-api/init.html#index-15">PyThreadState</a>, <a href="c-api/init.html#index-15">[1]</a>

      <ul>
        <li><a href="c-api/init.html#c.PyThreadState">(C type)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#c.PyThreadState_Clear">PyThreadState_Clear (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Delete">PyThreadState_Delete (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Get">PyThreadState_Get (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_GetDict">PyThreadState_GetDict (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_New">PyThreadState_New (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Next">PyThreadState_Next (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_SetAsyncExc">PyThreadState_SetAsyncExc (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Swap">PyThreadState_Swap (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_Check">PyTime_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_CheckExact">PyTime_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_FromTime">PyTime_FromTime (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_CALL">PyTrace_C_CALL (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_EXCEPTION">PyTrace_C_EXCEPTION (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_RETURN">PyTrace_C_RETURN (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_CALL">PyTrace_CALL (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_EXCEPTION">PyTrace_EXCEPTION (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_LINE">PyTrace_LINE (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_RETURN">PyTrace_RETURN (C variable)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Check">PyTuple_Check (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_CheckExact">PyTuple_CheckExact (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_ClearFreeList">PyTuple_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GET_ITEM">PyTuple_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GET_SIZE">PyTuple_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GetItem">PyTuple_GetItem (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GetSlice">PyTuple_GetSlice (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_New">PyTuple_New (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Pack">PyTuple_Pack (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_SET_ITEM">PyTuple_SET_ITEM (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_SetItem">PyTuple_SetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-7">PyTuple_SetItem()</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Size">PyTuple_Size (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Type">PyTuple_Type (C variable)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTupleObject">PyTupleObject (C type)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Check">PyType_Check (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_CheckExact">PyType_CheckExact (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_ClearCache">PyType_ClearCache (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_GenericAlloc">PyType_GenericAlloc (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_GenericNew">PyType_GenericNew (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_HasFeature">PyType_HasFeature (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#index-4">PyType_HasFeature()</a>
</li>
      <li><a href="c-api/type.html#c.PyType_IS_GC">PyType_IS_GC (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_IsSubtype">PyType_IsSubtype (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Modified">PyType_Modified (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Ready">PyType_Ready (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Type">PyType_Type (C variable)</a>
</li>
      <li><a href="c-api/type.html#c.PyTypeObject">PyTypeObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_alloc">PyTypeObject.tp_alloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_allocs">PyTypeObject.tp_allocs (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_as_buffer">PyTypeObject.tp_as_buffer (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_base">PyTypeObject.tp_base (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_bases">PyTypeObject.tp_bases (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_basicsize">PyTypeObject.tp_basicsize (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_cache">PyTypeObject.tp_cache (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_call">PyTypeObject.tp_call (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_clear">PyTypeObject.tp_clear (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_compare">PyTypeObject.tp_compare (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dealloc">PyTypeObject.tp_dealloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_descr_get">PyTypeObject.tp_descr_get (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_descr_set">PyTypeObject.tp_descr_set (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dict">PyTypeObject.tp_dict (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dictoffset">PyTypeObject.tp_dictoffset (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_doc">PyTypeObject.tp_doc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_flags">PyTypeObject.tp_flags (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_free">PyTypeObject.tp_free (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_frees">PyTypeObject.tp_frees (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getattr">PyTypeObject.tp_getattr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getattro">PyTypeObject.tp_getattro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getset">PyTypeObject.tp_getset (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_hash">PyTypeObject.tp_hash (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_init">PyTypeObject.tp_init (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_is_gc">PyTypeObject.tp_is_gc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_itemsize">PyTypeObject.tp_itemsize (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_iter">PyTypeObject.tp_iter (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_iternext">PyTypeObject.tp_iternext (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_maxalloc">PyTypeObject.tp_maxalloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_members">PyTypeObject.tp_members (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_methods">PyTypeObject.tp_methods (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_mro">PyTypeObject.tp_mro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_name">PyTypeObject.tp_name (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_new">PyTypeObject.tp_new (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_next">PyTypeObject.tp_next (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_print">PyTypeObject.tp_print (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_repr">PyTypeObject.tp_repr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_richcompare">PyTypeObject.tp_richcompare (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_setattr">PyTypeObject.tp_setattr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_setattro">PyTypeObject.tp_setattro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_str">PyTypeObject.tp_str (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_subclasses">PyTypeObject.tp_subclasses (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_traverse">PyTypeObject.tp_traverse (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_weaklist">PyTypeObject.tp_weaklist (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_weaklistoffset">PyTypeObject.tp_weaklistoffset (C member)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTZInfo_Check">PyTZInfo_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTZInfo_CheckExact">PyTZInfo_CheckExact (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AS_DATA">PyUnicode_AS_DATA (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AS_UNICODE">PyUnicode_AS_UNICODE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsASCIIString">PyUnicode_AsASCIIString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsCharmapString">PyUnicode_AsCharmapString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsEncodedString">PyUnicode_AsEncodedString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsLatin1String">PyUnicode_AsLatin1String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsMBCSString">PyUnicode_AsMBCSString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsRawUnicodeEscapeString">PyUnicode_AsRawUnicodeEscapeString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUnicode">PyUnicode_AsUnicode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUnicodeEscapeString">PyUnicode_AsUnicodeEscapeString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF16String">PyUnicode_AsUTF16String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF32String">PyUnicode_AsUTF32String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF8String">PyUnicode_AsUTF8String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsWideChar">PyUnicode_AsWideChar (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Check">PyUnicode_Check (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_CheckExact">PyUnicode_CheckExact (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_ClearFreeList">PyUnicode_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Compare">PyUnicode_Compare (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Concat">PyUnicode_Concat (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Contains">PyUnicode_Contains (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Count">PyUnicode_Count (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Decode">PyUnicode_Decode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeASCII">PyUnicode_DecodeASCII (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeCharmap">PyUnicode_DecodeCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeLatin1">PyUnicode_DecodeLatin1 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeMBCS">PyUnicode_DecodeMBCS (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeMBCSStateful">PyUnicode_DecodeMBCSStateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeRawUnicodeEscape">PyUnicode_DecodeRawUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUnicodeEscape">PyUnicode_DecodeUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF16">PyUnicode_DecodeUTF16 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF16Stateful">PyUnicode_DecodeUTF16Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF32">PyUnicode_DecodeUTF32 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF32Stateful">PyUnicode_DecodeUTF32Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF7">PyUnicode_DecodeUTF7 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF7Stateful">PyUnicode_DecodeUTF7Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF8">PyUnicode_DecodeUTF8 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF8Stateful">PyUnicode_DecodeUTF8Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Encode">PyUnicode_Encode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeASCII">PyUnicode_EncodeASCII (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeCharmap">PyUnicode_EncodeCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeLatin1">PyUnicode_EncodeLatin1 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeMBCS">PyUnicode_EncodeMBCS (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeRawUnicodeEscape">PyUnicode_EncodeRawUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUnicodeEscape">PyUnicode_EncodeUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF16">PyUnicode_EncodeUTF16 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF32">PyUnicode_EncodeUTF32 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF7">PyUnicode_EncodeUTF7 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF8">PyUnicode_EncodeUTF8 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Find">PyUnicode_Find (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Format">PyUnicode_Format (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromEncodedObject">PyUnicode_FromEncodedObject (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromFormat">PyUnicode_FromFormat (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromFormatV">PyUnicode_FromFormatV (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromObject">PyUnicode_FromObject (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromString">PyUnicode_FromString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromStringAndSize">PyUnicode_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromUnicode">PyUnicode_FromUnicode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromWideChar">PyUnicode_FromWideChar (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GET_DATA_SIZE">PyUnicode_GET_DATA_SIZE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GET_SIZE">PyUnicode_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GetSize">PyUnicode_GetSize (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Join">PyUnicode_Join (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Replace">PyUnicode_Replace (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_RichCompare">PyUnicode_RichCompare (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Split">PyUnicode_Split (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Splitlines">PyUnicode_Splitlines (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Tailmatch">PyUnicode_Tailmatch (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Translate">PyUnicode_Translate (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_TranslateCharmap">PyUnicode_TranslateCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Type">PyUnicode_Type (C variable)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_Create">PyUnicodeDecodeError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetEncoding">PyUnicodeDecodeError_GetEncoding (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetEnd">PyUnicodeDecodeError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetObject">PyUnicodeDecodeError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetReason">PyUnicodeDecodeError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetStart">PyUnicodeDecodeError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetEnd">PyUnicodeDecodeError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetReason">PyUnicodeDecodeError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetStart">PyUnicodeDecodeError_SetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_Create">PyUnicodeEncodeError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetEncoding">PyUnicodeEncodeError_GetEncoding (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetEnd">PyUnicodeEncodeError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetObject">PyUnicodeEncodeError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetReason">PyUnicodeEncodeError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetStart">PyUnicodeEncodeError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetEnd">PyUnicodeEncodeError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetReason">PyUnicodeEncodeError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetStart">PyUnicodeEncodeError_SetStart (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicodeObject">PyUnicodeObject (C type)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_Create">PyUnicodeTranslateError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetEnd">PyUnicodeTranslateError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetObject">PyUnicodeTranslateError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetReason">PyUnicodeTranslateError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetStart">PyUnicodeTranslateError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetEnd">PyUnicodeTranslateError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetReason">PyUnicodeTranslateError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetStart">PyUnicodeTranslateError_SetStart (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyVarObject">PyVarObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyVarObject.ob_size">PyVarObject.ob_size (C member)</a>
</li>
      <li><a href="c-api/structures.html#c.PyVarObject_HEAD_INIT">PyVarObject_HEAD_INIT (C macro)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_Check">PyWeakref_Check (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_CheckProxy">PyWeakref_CheckProxy (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_CheckRef">PyWeakref_CheckRef (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_GET_OBJECT">PyWeakref_GET_OBJECT (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_GetObject">PyWeakref_GetObject (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_NewProxy">PyWeakref_NewProxy (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_NewRef">PyWeakref_NewRef (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyWrapper_New">PyWrapper_New (C function)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.PyZipFile">PyZipFile (class in zipfile)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="Q">Q</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/fl.html#fl.qdevice">qdevice() (in module fl)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.QDPoint">QDPoint (class in aetypes)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.QDRectangle">QDRectangle (class in aetypes)</a>
</li>
      <li><a href="library/fl.html#fl.qenter">qenter() (in module fl)</a>
</li>
      <li><a href="library/curses.html#curses.qiflush">qiflush() (in module curses)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.QName">QName (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/fl.html#fl.qread">qread() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.qreset">qreset() (in module fl)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.qsize">qsize() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.qsize">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.qtest">qtest() (in module fl)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.quantize">quantize() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.quantize">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.QueryInfoKey">QueryInfoKey() (in module _winreg)</a>
</li>
      <li><a href="library/al.html#al.queryparams">queryparams() (in module al)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryReflectionKey">QueryReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryValue">QueryValue() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryValueEx">QueryValueEx() (in module _winreg)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue">Queue (class in multiprocessing)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue">(class in Queue)</a>
</li>
        <li><a href="library/queue.html#module-Queue">(module)</a>
</li>
      </ul></li>
      <li><a href="library/sched.html#sched.scheduler.queue">queue (sched.scheduler attribute)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Queue">Queue() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.quick_ratio">quick_ratio() (difflib.SequenceMatcher method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/constants.html#quit">quit (built-in variable)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.quit">quit() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.quit">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.quit">(poplib.POP3 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.quit">(smtplib.SMTP method)</a>
</li>
      </ul></li>
      <li><a href="library/quopri.html#module-quopri">quopri (module)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.quote">quote() (in module email.utils)</a>

      <ul>
        <li><a href="library/pipes.html#pipes.quote">(in module pipes)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.quote">(in module rfc822)</a>
</li>
        <li><a href="library/urllib.html#urllib.quote">(in module urllib)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.QUOTE_ALL">QUOTE_ALL (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_MINIMAL">QUOTE_MINIMAL (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_NONE">QUOTE_NONE (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_NONNUMERIC">QUOTE_NONNUMERIC (in module csv)</a>
</li>
      <li><a href="library/urllib.html#urllib.quote_plus">quote_plus() (in module urllib)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.quoteattr">quoteattr() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.quotechar">quotechar (csv.Dialect attribute)</a>
</li>
      <li>
    quoted-printable

      <ul>
        <li><a href="library/quopri.html#index-0">encoding</a>
</li>
      </ul></li>
      <li>
    quotes

      <ul>
        <li><a href="reference/datamodel.html#index-77">backward</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-77">reverse</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex.quotes">quotes (shlex.shlex attribute)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.quoting">quoting (csv.Dialect attribute)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="R">R</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/rexec.html#rexec.RExec.r_eval">r_eval() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_exec">r_exec() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_execfile">r_execfile() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_import">r_import() (rexec.RExec method)</a>
</li>
      <li><a href="library/os.html#os.R_OK">R_OK (in module os)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_open">r_open() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_reload">r_reload() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_unload">r_unload() (rexec.RExec method)</a>
</li>
      <li><a href="library/math.html#math.radians">radians() (in module math)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.radians">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.RadioButtonGroup">RadioButtonGroup (class in msilib)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.radiogroup">radiogroup() (msilib.Dialog method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.radix">radix() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.radix">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.RADIXCHAR">RADIXCHAR (in module locale)</a>
</li>
      <li>
    raise

      <ul>
        <li><a href="library/exceptions.html#index-1">statement</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-raise">raise (2to3 fixer)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">raise an exception</a>
</li>
      <li><a href="library/dis.html#opcode-RAISE_VARARGS">RAISE_VARARGS (opcode)</a>
</li>
      <li>
    raising

      <ul>
        <li><a href="reference/simple_stmts.html#index-31">exception</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.RAND_add">RAND_add() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.RAND_egd">RAND_egd() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.RAND_status">RAND_status() (in module ssl)</a>
</li>
      <li><a href="library/random.html#random.randint">randint() (in module random)</a>
</li>
      <li><a href="library/random.html#module-random">random (module)</a>
</li>
      <li><a href="library/random.html#random.random">random() (in module random)</a>
</li>
      <li><a href="library/random.html#random.randrange">randrange() (in module random)</a>
</li>
      <li>
    range

      <ul>
        <li><a href="reference/compound_stmts.html#index-8">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Range">Range (class in aetypes)</a>
</li>
      <li><a href="library/functions.html#range">range() (built-in function)</a>
</li>
      <li><a href="library/audioop.html#audioop.ratecv">ratecv() (in module audioop)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.ratio">ratio() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational">Rational (class in numbers)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase.raw">raw (io.BufferedIOBase attribute)</a>
</li>
      <li><a href="reference/toplevel_components.html#index-8">raw input</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">raw string</a>
</li>
      <li><a href="library/curses.html#curses.raw">raw() (in module curses)</a>
</li>
      <li><a href="library/json.html#json.JSONDecoder.raw_decode">raw_decode() (json.JSONDecoder method)</a>
</li>
      <li>
    raw_input

      <ul>
        <li><a href="library/sys.html#index-14">built-in function</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-raw_input">raw_input (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#raw_input">raw_input() (built-in function)</a>

      <ul>
        <li><a href="library/code.html#code.InteractiveConsole.raw_input">(code.InteractiveConsole method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.RawArray">RawArray() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser">RawConfigParser (class in ConfigParser)</a>
</li>
      <li><a href="library/argparse.html#argparse.RawDescriptionHelpFormatter">RawDescriptionHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/io.html#io.RawIOBase">RawIOBase (class in io)</a>
</li>
      <li><a href="library/turtle.html#turtle.RawPen">RawPen (class in turtle)</a>
</li>
      <li><a href="library/argparse.html#argparse.RawTextHelpFormatter">RawTextHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/turtle.html#turtle.RawTurtle">RawTurtle (class in turtle)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.RawValue">RawValue() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/token.html#token.RBRACE">RBRACE (in module token)</a>
</li>
      <li>
    re

      <ul>
        <li><a href="library/fnmatch.html#index-1">module</a>, <a href="library/stdtypes.html#index-27">[1]</a>, <a href="library/string.html#index-0">[2]</a>
</li>
      </ul></li>
      <li><a href="library/re.html#module-re">re (module)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.re">(re.MatchObject attribute)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.read">read() (array.array method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.read">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.read">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.read">(chunk.Chunk method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamReader.read">(codecs.StreamReader method)</a>
</li>
        <li><a href="library/stdtypes.html#file.read">(file method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPResponse.read">(httplib.HTTPResponse method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.read">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/imgfile.html#imgfile.read">(in module imgfile)</a>
</li>
        <li><a href="library/os.html#os.read">(in module os)</a>
</li>
        <li><a href="library/io.html#io.BufferedIOBase.read">(io.BufferedIOBase method)</a>
</li>
        <li><a href="library/io.html#io.BufferedReader.read">(io.BufferedReader method)</a>
</li>
        <li><a href="library/io.html#io.RawIOBase.read">(io.RawIOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.read">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.read">(mimetypes.MimeTypes method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.read">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.read">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.read">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/robotparser.html#robotparser.RobotFileParser.read">(robotparser.RobotFileParser method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.read">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.BufferedIOBase.read1">read1() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.BufferedReader.read1">(io.BufferedReader method)</a>
</li>
        <li><a href="library/io.html#io.BytesIO.read1">(io.BytesIO method)</a>
</li>
      </ul></li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_all">read_all() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mmap.html#mmap.mmap.read_byte">read_byte() (mmap.mmap method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_eager">read_eager() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/readline.html#readline.read_history_file">read_history_file() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.read_init_file">read_init_file() (in module readline)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_lazy">read_lazy() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.read_mime_types">read_mime_types() (in module mimetypes)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">READ_RESTRICTED</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_sb_data">read_sb_data() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_some">read_some() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.read_token">read_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_until">read_until() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_very_eager">read_very_eager() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_very_lazy">read_very_lazy() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes.read_windows_registry">read_windows_registry() (mimetypes.MimeTypes method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.READABLE">READABLE (in module Tkinter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.readable">readable() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.readable">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.RawIOBase.readall">readall() (io.RawIOBase method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.readbufferproc">readbufferproc (C type)</a>
</li>
      <li><a href="library/csv.html#csv.reader">reader() (in module csv)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.ReadError">ReadError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.readfp">readfp() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.readfp">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.readframes">readframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.readframes">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.readframes">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.BufferedIOBase.readinto">readinto() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.RawIOBase.readinto">(io.RawIOBase method)</a>
</li>
      </ul></li>
      <li>
    readline

      <ul>
        <li><a href="tutorial/interactive.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#module-readline">readline (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.readline">readline() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamReader.readline">(codecs.StreamReader method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.readline">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/stdtypes.html#file.readline">(file method)</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.readline">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.readline">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.readline">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.readline">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.readline">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/bz2.html#bz2.BZ2File.readlines">readlines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamReader.readlines">(codecs.StreamReader method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.readlines">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/stdtypes.html#file.readlines">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.readlines">(io.IOBase method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.readlines">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.readlink">readlink() (in module os)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.readmodule">readmodule() (in module pyclbr)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.readmodule_ex">readmodule_ex() (in module pyclbr)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">READONLY</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.readonly">readonly (memoryview attribute)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlist">readPlist() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlistFromResource">readPlistFromResource() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlistFromString">readPlistFromString() (in module plistlib)</a>
</li>
      <li><a href="library/imgfile.html#imgfile.readscaled">readscaled() (in module imgfile)</a>
</li>
      <li><a href="library/cd.html#cd.READY">READY (in module cd)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.ready">ready() (multiprocessing.pool.AsyncResult method)</a>
</li>
      <li><a href="library/numbers.html#numbers.Real">Real (class in numbers)</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex.real">real (numbers.Complex attribute)</a>
</li>
      <li><a href="library/chunk.html#index-0">Real Media File Format</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.real_quick_ratio">real_quick_ratio() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="c-api/memory.html#index-0">realloc()</a>
</li>
      <li><a href="library/os.path.html#os.path.realpath">realpath() (in module os.path)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.reason">reason (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPResponse.reason">(httplib.HTTPResponse attribute)</a>
</li>
        <li><a href="library/ssl.html#ssl.SSLError.reason">(ssl.SSLError attribute)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.HTTPError.reason">(urllib2.HTTPError attribute)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.URLError.reason">(urllib2.URLError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.reattach">reattach() (ttk.Treeview method)</a>
</li>
      <li>
    rebinding

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">name</a>
</li>
      </ul></li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.reccontrols">reccontrols() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.recent">recent() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/cmath.html#cmath.rect">rect() (in module cmath)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.rectangle">rectangle() (in module curses.textpad)</a>
</li>
      <li>
    recursive

      <ul>
        <li><a href="reference/expressions.html#index-20">object</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.recv">recv() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.recv">(Connection method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.recv">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.recv_bytes">recv_bytes() (Connection method)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection.recv_bytes_into">recv_bytes_into() (Connection method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recv_into">recv_into() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recvfrom">recvfrom() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recvfrom_into">recvfrom_into() (socket.socket method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.redirect_request">redirect_request() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/readline.html#readline.redisplay">redisplay() (in module readline)</a>
</li>
      <li><a href="library/fl.html#fl.form.redraw_form">redraw_form() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.window.redrawln">redrawln() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.redrawwin">redrawwin() (curses.window method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-reduce">reduce (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#reduce">reduce() (built-in function)</a>

      <ul>
        <li><a href="library/functools.html#functools.reduce">(in module functools)</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.ref">ref (class in weakref)</a>
</li>
      <li>
    reference

      <ul>
        <li><a href="reference/expressions.html#index-29">attribute</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-reference-count"><strong>reference count</strong></a>
</li>
      <li><a href="reference/datamodel.html#index-2">reference counting</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ReferenceError">ReferenceError</a>, <a href="library/weakref.html#weakref.ReferenceError">[1]</a>
</li>
      <li><a href="library/weakref.html#weakref.ReferenceType">ReferenceType (in module weakref)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.refilemessages">refilemessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/curses.html#curses.window.refresh">refresh() (curses.window method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_BINARY">REG_BINARY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD">REG_DWORD (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD_BIG_ENDIAN">REG_DWORD_BIG_ENDIAN (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD_LITTLE_ENDIAN">REG_DWORD_LITTLE_ENDIAN (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_EXPAND_SZ">REG_EXPAND_SZ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_FULL_RESOURCE_DESCRIPTOR">REG_FULL_RESOURCE_DESCRIPTOR (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_LINK">REG_LINK (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_MULTI_SZ">REG_MULTI_SZ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_NONE">REG_NONE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_RESOURCE_LIST">REG_RESOURCE_LIST (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_RESOURCE_REQUIREMENTS_LIST">REG_RESOURCE_REQUIREMENTS_LIST (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_SZ">REG_SZ (in module _winreg)</a>
</li>
      <li><a href="library/re.html#re.RegexObject">RegexObject (class in re)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta.register">register() (abc.ABCMeta method)</a>

      <ul>
        <li><a href="library/atexit.html#atexit.register">(in module atexit)</a>
</li>
        <li><a href="library/codecs.html#codecs.register">(in module codecs)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.register">(in module webbrowser)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.register">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/select.html#select.epoll.register">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.poll.register">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.register_adapter">register_adapter() (in module sqlite3)</a>
</li>
      <li><a href="library/shutil.html#shutil.register_archive_format">register_archive_format() (in module shutil)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.register_converter">register_converter() (in module sqlite3)</a>
</li>
      <li><a href="library/csv.html#csv.register_dialect">register_dialect() (in module csv)</a>
</li>
      <li><a href="library/codecs.html#codecs.register_error">register_error() (in module codecs)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function">register_function() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_function">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_instance">register_instance() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_instance">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_introspection_functions">register_introspection_functions() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_introspection_functions">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_multicall_functions">register_multicall_functions() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_multicall_functions">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace">register_namespace() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/doctest.html#doctest.register_optionflag">register_optionflag() (in module doctest)</a>
</li>
      <li><a href="library/turtle.html#turtle.register_shape">register_shape() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.registerDOMImplementation">registerDOMImplementation() (in module xml.dom)</a>
</li>
      <li><a href="library/unittest.html#unittest.registerResult">registerResult() (in module unittest)</a>
</li>
      <li>
    relative

      <ul>
        <li><a href="library/urlparse.html#index-0">URL</a>
</li>
        <li><a href="reference/simple_stmts.html#index-50">import</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.release">release() (in module platform)</a>

      <ul>
        <li><a href="library/logging.html#logging.Handler.release">(logging.Handler method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Lock.release">(multiprocessing.Lock method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.RLock.release">(multiprocessing.RLock method)</a>
</li>
        <li><a href="library/thread.html#thread.lock.release">(thread.lock method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.release">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Lock.release">(threading.Lock method)</a>
</li>
        <li><a href="library/threading.html#threading.RLock.release">(threading.RLock method)</a>
</li>
        <li><a href="library/threading.html#threading.Semaphore.release">(threading.Semaphore method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.release_lock">release_lock() (in module imp)</a>
</li>
      <li>
    reload

      <ul>
        <li><a href="c-api/import.html#index-3">built-in function</a>, <a href="library/imp.html#index-2">[1]</a>, <a href="library/imp.html#index-5">[2]</a>, <a href="library/sys.html#index-5">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#reload">reload() (built-in function)</a>
</li>
      <li><a href="library/os.path.html#os.path.relpath">relpath() (in module os.path)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.remainder">remainder() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.remainder_near">remainder_near() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.remainder_near">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.remove">remove() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.remove">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.remove">(frozenset method)</a>
</li>
        <li><a href="library/os.html#os.remove">(in module os)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.remove">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.remove">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.remove_flag">remove_flag() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.remove_flag">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.remove_flag">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Maildir.remove_folder">remove_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.remove_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.remove_history_item">remove_history_item() (in module readline)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.remove_label">remove_label() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.remove_option">remove_option() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.remove_option">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Directory.remove_pyc">remove_pyc() (msilib.Directory method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.remove_section">remove_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage.remove_sequence">remove_sequence() (mailbox.MHMessage method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dir_util.remove_tree">remove_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttribute">removeAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttributeNode">removeAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttributeNS">removeAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.removeChild">removeChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/os.html#os.removedirs">removedirs() (in module os)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.removeFilter">removeFilter() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.removeFilter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.removeHandler">removeHandler() (in module unittest)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.removeHandler">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.removemessages">removemessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/unittest.html#unittest.removeResult">removeResult() (in module unittest)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.rename">rename() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.rename">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/os.html#os.rename">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-renames">renames (2to3 fixer)</a>
</li>
      <li><a href="library/os.html#os.renames">renames() (in module os)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.reorganize">reorganize() (in module gdbm)</a>
</li>
      <li><a href="library/itertools.html#itertools.repeat">repeat() (in module itertools)</a>

      <ul>
        <li><a href="library/operator.html#operator.repeat">(in module operator)</a>
</li>
        <li><a href="library/timeit.html#timeit.repeat">(in module timeit)</a>
</li>
        <li><a href="library/timeit.html#timeit.Timer.repeat">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li>
    repetition

      <ul>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.replace">replace() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.date.replace">(datetime.date method)</a>
</li>
        <li><a href="library/datetime.html#datetime.datetime.replace">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.replace">(datetime.time method)</a>
</li>
        <li><a href="library/string.html#string.replace">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#str.replace">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.replace_errors">replace_errors() (in module codecs)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.replace_header">replace_header() (email.message.Message method)</a>
</li>
      <li><a href="library/readline.html#readline.replace_history_item">replace_history_item() (in module readline)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.replace_whitespace">replace_whitespace (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.replaceChild">replaceChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ReplacePackage">ReplacePackage() (in module modulefinder)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.report">report() (filecmp.dircmp method)</a>

      <ul>
        <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.report">(modulefinder.ModuleFinder method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.REPORT_CDIFF">REPORT_CDIFF (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_failure">report_failure() (doctest.DocTestRunner method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/filecmp.html#filecmp.dircmp.report_full_closure">report_full_closure() (filecmp.dircmp method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_NDIFF">REPORT_NDIFF (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_ONLY_FIRST_FAILURE">REPORT_ONLY_FIRST_FAILURE (in module doctest)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.report_partial_closure">report_partial_closure() (filecmp.dircmp method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_start">report_start() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_success">report_success() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_UDIFF">REPORT_UDIFF (in module doctest)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.report_unbalanced">report_unbalanced() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_unexpected_exception">report_unexpected_exception() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORTING_FLAGS">REPORTING_FLAGS (in module doctest)</a>
</li>
      <li>
    repr

      <ul>
        <li><a href="c-api/object.html#index-2">built-in function</a>, <a href="c-api/typeobj.html#index-1">[1]</a>, <a href="extending/newtypes.html#index-2">[2]</a>, <a href="reference/datamodel.html#index-76">[3]</a>, <a href="reference/expressions.html#index-21">[4]</a>, <a href="reference/simple_stmts.html#index-2">[5]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-repr">repr (2to3 fixer)</a>
</li>
      <li><a href="library/repr.html#repr.Repr">Repr (class in repr)</a>
</li>
      <li><a href="library/functions.html#repr">repr() (built-in function)</a>

      <ul>
        <li><a href="library/repr.html#repr.repr">(in module repr)</a>
</li>
        <li><a href="library/repr.html#repr.Repr.repr">(repr.Repr method)</a>
</li>
      </ul></li>
      <li><a href="library/repr.html#repr.Repr.repr1">repr1() (repr.Repr method)</a>
</li>
      <li>
    representation

      <ul>
        <li><a href="reference/datamodel.html#index-14">integer</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.Request">Request (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.request">request() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.request_queue_size">request_queue_size (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.request_uri">request_uri() (in module wsgiref.util)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.request_version">request_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.RequestHandlerClass">RequestHandlerClass (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/test.html#test.support.requires">requires() (in module test.support)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.reserved">reserved (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-10">reserved word</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_FUTURE">RESERVED_FUTURE (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_MICROSOFT">RESERVED_MICROSOFT (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_NCS">RESERVED_NCS (in module uuid)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.reset">reset() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.reset">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/codecs.html#codecs.IncrementalDecoder.reset">(codecs.IncrementalDecoder method)</a>
</li>
        <li><a href="library/codecs.html#codecs.IncrementalEncoder.reset">(codecs.IncrementalEncoder method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamReader.reset">(codecs.StreamReader method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamWriter.reset">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/dircache.html#dircache.reset">(in module dircache)</a>
</li>
        <li><a href="library/turtle.html#turtle.reset">(in module turtle)</a>, <a href="library/turtle.html#turtle.reset">[1]</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.reset">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.reset">(pipes.Template method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.reset">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/xdrlib.html#xdrlib.Packer.reset">(xdrlib.Packer method)</a>
</li>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.reset">(xdrlib.Unpacker method)</a>
</li>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.reset">(xml.dom.pulldom.DOMEventStream method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.reset">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.reset_prog_mode">reset_prog_mode() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.reset_shell_mode">reset_shell_mode() (in module curses)</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole.resetbuffer">resetbuffer() (code.InteractiveConsole method)</a>
</li>
      <li><a href="library/locale.html#locale.resetlocale">resetlocale() (in module locale)</a>
</li>
      <li><a href="library/turtle.html#turtle.resetscreen">resetscreen() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.resetty">resetty() (in module curses)</a>
</li>
      <li><a href="library/warnings.html#warnings.resetwarnings">resetwarnings() (in module warnings)</a>
</li>
      <li><a href="library/curses.html#curses.window.resize">resize() (curses.window method)</a>

      <ul>
        <li><a href="library/ctypes.html#ctypes.resize">(in module ctypes)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.resize">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.resize_term">resize_term() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.resizemode">resizemode() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.resizeterm">resizeterm() (in module curses)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.resolution">resolution (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.resolution">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.resolution">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.resolution">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.EntityResolver.resolveEntity">resolveEntity() (xml.sax.handler.EntityResolver method)</a>
</li>
      <li><a href="library/resource.html#module-resource">resource (module)</a>
</li>
      <li><a href="library/test.html#test.support.ResourceDenied">ResourceDenied</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.response">response() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/httplib.html#httplib.ResponseNotReady">ResponseNotReady</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.responses">responses (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.responses">(in module httplib)</a>
</li>
      </ul></li>
      <li><a href="library/macostools.html#findertools.restart">restart() (in module findertools)</a>
</li>
      <li><a href="library/difflib.html#difflib.restore">restore() (in module difflib)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">RESTRICTED</a>
</li>
      <li>
    restricted

      <ul>
        <li><a href="reference/executionmodel.html#index-10">execution</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.restype">restype (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="library/trace.html#trace.Trace.results">results() (trace.Trace method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.retr">retr() (poplib.POP3 method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.retrbinary">retrbinary() (ftplib.FTP method)</a>
</li>
      <li><a href="library/urllib.html#urllib.URLopener.retrieve">retrieve() (urllib.URLopener method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.retrlines">retrlines() (ftplib.FTP method)</a>
</li>
      <li>
    return

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/simple_stmts.html#index-26">[2]</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.return_ok">return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/dis.html#opcode-RETURN_VALUE">RETURN_VALUE (opcode)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError.returncode">returncode (subprocess.CalledProcessError attribute)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.returncode">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.returns_unicode">returns_unicode (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li>
    reverse

      <ul>
        <li><a href="reference/datamodel.html#index-77">quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.reverse">reverse() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.reverse">(collections.deque method)</a>
</li>
        <li><a href="library/audioop.html#audioop.reverse">(in module audioop)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.reverse_order">reverse_order() (pstats.Stats method)</a>
</li>
      <li><a href="library/functions.html#reversed">reversed() (built-in function)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.revert">revert() (cookielib.FileCookieJar method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.rewind">rewind() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.rewind">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.rewind">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#rfc822.Message.rewindbody">rewindbody() (rfc822.Message method)</a>
</li>
      <li>
    rexec

      <ul>
        <li><a href="c-api/import.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/rexec.html#rexec.RExec">RExec (class in rexec)</a>
</li>
      <li><a href="library/rexec.html#module-rexec">rexec (module)</a>
</li>
      <li>
    RFC

      <ul>
        <li><a href="library/xdrlib.html#index-1">RFC 1014</a>, <a href="library/xdrlib.html#index-2">[1]</a>
</li>
        <li><a href="library/time.html#index-18">RFC 1123</a>
</li>
        <li><a href="library/hashlib.html#index-1">RFC 1321</a>, <a href="library/md5.html#index-1">[1]</a>
</li>
        <li><a href="library/ssl.html#index-17">RFC 1422</a>
</li>
        <li><a href="library/base64.html#index-4">RFC 1521</a>, <a href="library/quopri.html#index-1">[1]</a>, <a href="library/quopri.html#index-3">[2]</a>
</li>
        <li><a href="library/quopri.html#index-2">RFC 1522</a>
</li>
        <li><a href="library/mailcap.html#index-0">RFC 1524</a>, <a href="library/mailcap.html#index-1">[1]</a>
</li>
        <li><a href="library/poplib.html#index-1">RFC 1725</a>
</li>
        <li><a href="library/imaplib.html#index-2">RFC 1730</a>
</li>
        <li><a href="library/urlparse.html#index-8">RFC 1738</a>
</li>
        <li><a href="library/ssl.html#index-4">RFC 1750</a>
</li>
        <li><a href="library/locale.html#index-4">RFC 1766</a>, <a href="library/locale.html#index-5">[1]</a>
</li>
        <li><a href="library/urlparse.html#index-1">RFC 1808</a>, <a href="library/urlparse.html#index-7">[1]</a>
</li>
        <li><a href="library/xdrlib.html#index-3">RFC 1832</a>, <a href="library/xdrlib.html#index-4">[1]</a>
</li>
        <li><a href="library/htmllib.html#index-2">RFC 1866</a>
</li>
        <li><a href="library/smtplib.html#index-2">RFC 1869</a>, <a href="library/smtplib.html#index-4">[1]</a>
</li>
        <li><a href="library/email.html#index-9">RFC 1894</a>
</li>
        <li><a href="whatsnew/2.6.html#index-22">RFC 2033</a>
</li>
        <li><a href="library/email.header.html#index-4">RFC 2045</a>, <a href="library/email.html#index-3">[1]</a>, <a href="library/email.message.html#index-3">[2]</a>, <a href="library/email.message.html#index-4">[3]</a>, <a href="library/email.message.html#index-5">[4]</a>, <a href="library/email.message.html#index-8">[5]</a>, <a href="library/multifile.html#index-0">[6]</a>
</li>
        <li><a href="library/email.header.html#index-5">RFC 2046</a>, <a href="library/email.html#index-4">[1]</a>
</li>
        <li><a href="library/email.header.html#index-11">RFC 2047</a>, <a href="library/email.header.html#index-13">[1]</a>, <a href="library/email.header.html#index-6">[2]</a>, <a href="library/email.header.html#index-8">[3]</a>, <a href="library/email.html#index-5">[4]</a>
</li>
        <li><a href="library/imaplib.html#index-1">RFC 2060</a>, <a href="library/imaplib.html#index-3">[1]</a>
</li>
        <li><a href="library/cookie.html#index-1">RFC 2068</a>
</li>
        <li><a href="library/hmac.html#index-0">RFC 2104</a>, <a href="whatsnew/2.2.html#index-17">[1]</a>
</li>
        <li><a href="library/cookie.html#index-0">RFC 2109</a>, <a href="library/cookie.html#index-2">[1]</a>, <a href="library/cookie.html#index-3">[2]</a>, <a href="library/cookie.html#index-4">[3]</a>, <a href="library/cookie.html#index-5">[4]</a>, <a href="library/cookielib.html#index-1">[5]</a>, <a href="library/cookielib.html#index-2">[6]</a>
</li>
        <li><a href="library/email.header.html#index-7">RFC 2231</a>, <a href="library/email.html#index-6">[1]</a>, <a href="library/email.html#index-8">[2]</a>, <a href="library/email.message.html#index-2">[3]</a>, <a href="library/email.message.html#index-6">[4]</a>, <a href="library/email.message.html#index-7">[5]</a>, <a href="library/email.message.html#index-9">[6]</a>, <a href="library/email.utils.html#index-4">[7]</a>, <a href="library/email.utils.html#index-5">[8]</a>, <a href="library/email.utils.html#index-6">[9]</a>, <a href="library/email.utils.html#index-7">[10]</a>, <a href="library/email.utils.html#index-8">[11]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-19">RFC 2342</a>
</li>
        <li><a href="library/urlparse.html#index-6">RFC 2368</a>
</li>
        <li><a href="library/urlparse.html#index-2">RFC 2396</a>, <a href="library/urlparse.html#index-5">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-18">RFC 2487</a>
</li>
        <li><a href="howto/urllib2.html#index-0">RFC 2616</a>, <a href="library/urllib.html#index-7">[1]</a>, <a href="library/urllib2.html#index-4">[2]</a>, <a href="library/urllib2.html#index-5">[3]</a>, <a href="library/wsgiref.html#index-5">[4]</a>
</li>
        <li><a href="library/urlparse.html#index-4">RFC 2732</a>, <a href="whatsnew/2.7.html#index-11">[1]</a>
</li>
        <li><a href="library/httplib.html#index-4">RFC 2774</a>
</li>
        <li><a href="library/httplib.html#index-3">RFC 2817</a>
</li>
        <li><a href="library/ssl.html#index-5">RFC 2818</a>
</li>
        <li><a href="library/email.html#index-1">RFC 2821</a>
</li>
        <li><a href="library/email.errors.html#index-0">RFC 2822</a>, <a href="library/email.errors.html#index-1">[1]</a>, <a href="library/email.errors.html#index-2">[2]</a>, <a href="library/email.errors.html#index-3">[3]</a>, <a href="library/email.generator.html#index-0">[4]</a>, <a href="library/email.generator.html#index-1">[5]</a>, <a href="library/email.header.html#index-0">[6]</a>, <a href="library/email.header.html#index-10">[7]</a>, <a href="library/email.header.html#index-12">[8]</a>, <a href="library/email.header.html#index-2">[9]</a>, <a href="library/email.header.html#index-3">[10]</a>, <a href="library/email.header.html#index-9">[11]</a>, <a href="library/email.html#index-0">[12]</a>, <a href="library/email.html#index-2">[13]</a>, <a href="library/email.message.html#index-0">[14]</a>, <a href="library/email.message.html#index-1">[15]</a>, <a href="library/email.parser.html#index-0">[16]</a>, <a href="library/email.utils.html#index-0">[17]</a>, <a href="library/email.utils.html#index-1">[18]</a>, <a href="library/email.utils.html#index-2">[19]</a>, <a href="library/email.utils.html#index-3">[20]</a>, <a href="library/email.utils.html#index-9">[21]</a>, <a href="library/mailbox.html#index-0">[22]</a>, <a href="library/rfc822.html#index-0">[23]</a>, <a href="library/rfc822.html#index-1">[24]</a>, <a href="library/rfc822.html#index-10">[25]</a>, <a href="library/rfc822.html#index-12">[26]</a>, <a href="library/rfc822.html#index-2">[27]</a>, <a href="library/rfc822.html#index-4">[28]</a>, <a href="library/rfc822.html#index-5">[29]</a>, <a href="library/rfc822.html#index-6">[30]</a>, <a href="library/rfc822.html#index-7">[31]</a>, <a href="library/rfc822.html#index-8">[32]</a>, <a href="library/smtpd.html#index-0">[33]</a>, <a href="library/time.html#index-19">[34]</a>, <a href="library/time.html#index-9">[35]</a>, <a href="whatsnew/2.2.html#index-20">[36]</a>
</li>
        <li><a href="library/cookielib.html#index-4">RFC 2964</a>
</li>
        <li><a href="library/cookielib.html#index-0">RFC 2965</a>, <a href="library/cookielib.html#index-3">[1]</a>, <a href="library/urllib2.html#index-1">[2]</a>, <a href="library/urllib2.html#index-3">[3]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-23">RFC 3207</a>
</li>
        <li><a href="library/httplib.html#index-2">RFC 3229</a>
</li>
        <li><a href="library/ssl.html#index-11">RFC 3280</a>
</li>
        <li><a href="library/stringprep.html#index-0">RFC 3454</a>
</li>
        <li><a href="library/codecs.html#index-1">RFC 3490</a>, <a href="library/codecs.html#index-3">[1]</a>, <a href="library/codecs.html#index-5">[2]</a>, <a href="library/codecs.html#index-6">[3]</a>, <a href="library/codecs.html#index-7">[4]</a>
</li>
        <li><a href="library/codecs.html#index-2">RFC 3492</a>, <a href="library/codecs.html#index-4">[1]</a>
</li>
        <li><a href="library/socket.html#index-0">RFC 3493</a>
</li>
        <li><a href="library/base64.html#index-1">RFC 3548</a>, <a href="library/base64.html#index-2">[1]</a>, <a href="library/base64.html#index-3">[2]</a>, <a href="library/binascii.html#index-1">[3]</a>
</li>
        <li><a href="library/urlparse.html#index-3">RFC 3986</a>, <a href="whatsnew/2.7.html#index-10">[1]</a>, <a href="whatsnew/2.7.html#index-13">[2]</a>
</li>
        <li><a href="library/uuid.html#index-0">RFC 4122</a>, <a href="library/uuid.html#index-6">[1]</a>, <a href="library/uuid.html#index-7">[2]</a>, <a href="whatsnew/2.5.html#index-19">[3]</a>, <a href="whatsnew/2.5.html#index-20">[4]</a>
</li>
        <li><a href="library/ftplib.html#index-2">RFC 4217</a>
</li>
        <li><a href="library/ssl.html#index-9">RFC 4366</a>
</li>
        <li><a href="library/json.html#index-1">RFC 4627</a>, <a href="library/json.html#index-3">[1]</a>
</li>
        <li><a href="library/ssl.html#index-10">RFC 5246</a>
</li>
        <li><a href="library/ssl.html#index-7">RFC 5280</a>
</li>
        <li><a href="library/ssl.html#index-12">RFC 5929</a>
</li>
        <li><a href="library/ssl.html#index-14">RFC 6066</a>
</li>
        <li><a href="library/ssl.html#index-6">RFC 6125</a>
</li>
        <li><a href="library/json.html#index-0">RFC 7159</a>, <a href="library/json.html#index-2">[1]</a>, <a href="library/json.html#index-4">[2]</a>
</li>
        <li><a href="library/ssl.html#index-13">RFC 7301</a>, <a href="library/ssl.html#index-8">[1]</a>
</li>
        <li><a href="library/smtplib.html#index-1">RFC 821</a>, <a href="library/smtplib.html#index-3">[1]</a>
</li>
        <li><a href="distutils/apiref.html#index-3">RFC 822</a>, <a href="library/configparser.html#index-1">[1]</a>, <a href="library/email.header.html#index-1">[2]</a>, <a href="library/gettext.html#index-8">[3]</a>, <a href="library/httplib.html#index-5">[4]</a>, <a href="library/rfc822.html#index-11">[5]</a>, <a href="library/rfc822.html#index-13">[6]</a>, <a href="library/rfc822.html#index-9">[7]</a>, <a href="library/smtplib.html#index-5">[8]</a>, <a href="library/smtplib.html#index-6">[9]</a>, <a href="library/smtplib.html#index-7">[10]</a>, <a href="library/smtplib.html#index-8">[11]</a>, <a href="library/time.html#index-16">[12]</a>, <a href="library/time.html#index-17">[13]</a>, <a href="whatsnew/2.2.html#index-21">[14]</a>
</li>
        <li><a href="library/telnetlib.html#index-1">RFC 854</a>, <a href="library/telnetlib.html#index-2">[1]</a>
</li>
        <li><a href="library/ftplib.html#index-1">RFC 959</a>
</li>
        <li><a href="library/nntplib.html#index-1">RFC 977</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.rfc2109">rfc2109 (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.rfc2109_as_netscape">rfc2109_as_netscape (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.rfc2965">rfc2965 (cookielib.CookiePolicy attribute)</a>
</li>
      <li>
    rfc822

      <ul>
        <li><a href="library/mimetools.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#module-rfc822">rfc822 (module)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.rfc822_escape">rfc822_escape() (in module distutils.util)</a>
</li>
      <li><a href="library/uuid.html#uuid.RFC_4122">RFC_4122 (in module uuid)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.rfile">rfile (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/string.html#string.rfind">rfind() (in module string)</a>

      <ul>
        <li><a href="library/mmap.html#mmap.mmap.rfind">(mmap.mmap method)</a>
</li>
        <li><a href="library/stdtypes.html#str.rfind">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_hls">rgb_to_hls() (in module colorsys)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_hsv">rgb_to_hsv() (in module colorsys)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_yiq">rgb_to_yiq() (in module colorsys)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.RGBColor">RGBColor (class in aetypes)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right">right (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.right">right() (in module turtle)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right_list">right_list (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right_only">right_only (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/token.html#token.RIGHTSHIFT">RIGHTSHIFT (in module token)</a>
</li>
      <li><a href="library/token.html#token.RIGHTSHIFTEQUAL">RIGHTSHIFTEQUAL (in module token)</a>
</li>
      <li><a href="library/string.html#string.rindex">rindex() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rindex">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.rjust">rjust() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rjust">(str method)</a>
</li>
      </ul></li>
      <li>
    rlcompleter

      <ul>
        <li><a href="tutorial/interactive.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/rlcompleter.html#module-rlcompleter">rlcompleter (module)</a>
</li>
      <li><a href="library/binascii.html#binascii.rlecode_hqx">rlecode_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.rledecode_hqx">rledecode_hqx() (in module binascii)</a>
</li>
      <li><a href="library/resource.html#resource.RLIM_INFINITY">RLIM_INFINITY (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_AS">RLIMIT_AS (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_CORE">RLIMIT_CORE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_CPU">RLIMIT_CPU (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_DATA">RLIMIT_DATA (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_FSIZE">RLIMIT_FSIZE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_MEMLOCK">RLIMIT_MEMLOCK (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_NOFILE">RLIMIT_NOFILE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_NPROC">RLIMIT_NPROC (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_OFILE">RLIMIT_OFILE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_RSS">RLIMIT_RSS (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_STACK">RLIMIT_STACK (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_VMEM">RLIMIT_VMEM (in module resource)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.RLock">RLock (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.RLock">RLock() (in module threading)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.RLock">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.rmd">rmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/os.html#os.rmdir">rmdir() (in module os)</a>
</li>
      <li><a href="library/chunk.html#index-0">RMFF</a>
</li>
      <li><a href="library/audioop.html#audioop.rms">rms() (in module audioop)</a>
</li>
      <li><a href="library/shutil.html#shutil.rmtree">rmtree() (in module shutil)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.rnopen">rnopen() (in module bsddb)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">RO</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser">RobotFileParser (class in robotparser)</a>
</li>
      <li><a href="library/robotparser.html#module-robotparser">robotparser (module)</a>
</li>
      <li><a href="library/robotparser.html#index-0">robots.txt</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.rollback">rollback() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_FOUR">ROT_FOUR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_THREE">ROT_THREE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_TWO">ROT_TWO (opcode)</a>
</li>
      <li><a href="library/collections.html#collections.deque.rotate">rotate() (collections.deque method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.rotate">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.rotate">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler">RotatingFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/functions.html#round">round() (built-in function)</a>
</li>
      <li><a href="library/decimal.html#decimal.Rounded">Rounded (class in decimal)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Row">Row (class in sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.row_factory">row_factory (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.rowcount">rowcount (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/token.html#token.RPAR">RPAR (in module token)</a>
</li>
      <li><a href="library/stdtypes.html#str.rpartition">rpartition() (str method)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.rpc_paths">rpc_paths (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler attribute)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.rpop">rpop() (poplib.POP3 method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.rset">rset() (poplib.POP3 method)</a>
</li>
      <li><a href="library/operator.html#operator.rshift">rshift() (in module operator)</a>
</li>
      <li><a href="library/string.html#string.rsplit">rsplit() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rsplit">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.RSQB">RSQB (in module token)</a>
</li>
      <li><a href="library/string.html#string.rstrip">rstrip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rstrip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.rt">rt() (in module turtle)</a>
</li>
      <li><a href="library/dl.html#dl.RTLD_LAZY">RTLD_LAZY (in module dl)</a>
</li>
      <li><a href="library/dl.html#dl.RTLD_NOW">RTLD_NOW (in module dl)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.ruler">ruler (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/idle.html#index-2">Run script</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.run">run() (bdb.Bdb method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.cmd.Command.run">(distutils.cmd.Command method)</a>
</li>
        <li><a href="library/doctest.html#doctest.DocTestRunner.run">(doctest.DocTestRunner method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.run">(hotshot.Profile method)</a>
</li>
        <li><a href="library/pdb.html#pdb.run">(in module pdb)</a>
</li>
        <li><a href="library/profile.html#profile.run">(in module profile)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.run">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.run">(pdb.Pdb method)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.run">(profile.Profile method)</a>
</li>
        <li><a href="library/sched.html#sched.scheduler.run">(sched.scheduler method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.run">(threading.Thread method)</a>
</li>
        <li><a href="library/trace.html#trace.Trace.run">(trace.Trace method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestCase.run">(unittest.TestCase method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.run">(unittest.TestSuite method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.run">(wsgiref.handlers.BaseHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.run_docstring_examples">run_docstring_examples() (in module doctest)</a>
</li>
      <li><a href="library/runpy.html#runpy.run_module">run_module() (in module runpy)</a>
</li>
      <li><a href="library/runpy.html#runpy.run_path">run_path() (in module runpy)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.run_script">run_script() (modulefinder.ModuleFinder method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.run_setup">run_setup() (in module distutils.core)</a>
</li>
      <li><a href="library/test.html#test.support.run_unittest">run_unittest() (in module test.support)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.runcall">runcall() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/hotshot.html#hotshot.Profile.runcall">(hotshot.Profile method)</a>
</li>
        <li><a href="library/pdb.html#pdb.runcall">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.runcall">(pdb.Pdb method)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.runcall">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/code.html#code.InteractiveInterpreter.runcode">runcode() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.runctx">runctx() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/hotshot.html#hotshot.Profile.runctx">(hotshot.Profile method)</a>
</li>
        <li><a href="library/profile.html#profile.runctx">(in module profile)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.runctx">(profile.Profile method)</a>
</li>
        <li><a href="library/trace.html#trace.Trace.runctx">(trace.Trace method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.runeval">runeval() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/pdb.html#pdb.runeval">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.runeval">(pdb.Pdb method)</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.Trace.runfunc">runfunc() (trace.Trace method)</a>
</li>
      <li><a href="library/runpy.html#module-runpy">runpy (module)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter.runsource">runsource() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.runtime_library_dir_option">runtime_library_dir_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.RuntimeError">RuntimeError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-24">exception</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.runtimemodel">runtimemodel (in module MacOS)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.RuntimeWarning">RuntimeWarning</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_BOTH">RUSAGE_BOTH (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_CHILDREN">RUSAGE_CHILDREN (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_SELF">RUSAGE_SELF (in module resource)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="S">S</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.S">S (in module re)</a>
</li>
      <li><a href="library/stat.html#stat.S_ENFMT">S_ENFMT (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_eval">s_eval() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_exec">s_exec() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_execfile">s_execfile() (rexec.RExec method)</a>
</li>
      <li><a href="library/stat.html#stat.S_IEXEC">S_IEXEC (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFBLK">S_IFBLK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFCHR">S_IFCHR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFDIR">S_IFDIR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFIFO">S_IFIFO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFLNK">S_IFLNK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFMT">S_IFMT() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFREG">S_IFREG (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IFSOCK">S_IFSOCK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IMODE">S_IMODE() (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_import">s_import() (rexec.RExec method)</a>
</li>
      <li><a href="library/stat.html#stat.S_IREAD">S_IREAD (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRGRP">S_IRGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IROTH">S_IROTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRUSR">S_IRUSR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXG">S_IRWXG (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXO">S_IRWXO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IRWXU">S_IRWXU (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISBLK">S_ISBLK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISCHR">S_ISCHR() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISDIR">S_ISDIR() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISFIFO">S_ISFIFO() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISGID">S_ISGID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISLNK">S_ISLNK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISREG">S_ISREG() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISSOCK">S_ISSOCK() (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISUID">S_ISUID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_ISVTX">S_ISVTX (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWGRP">S_IWGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWOTH">S_IWOTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWRITE">S_IWRITE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IWUSR">S_IWUSR (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXGRP">S_IXGRP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXOTH">S_IXOTH (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.S_IXUSR">S_IXUSR (in module stat)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_reload">s_reload() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.s_unload">s_unload() (rexec.RExec method)</a>
</li>
      <li><a href="library/string.html#string.Template.safe_substitute">safe_substitute() (string.Template method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.SafeConfigParser">SafeConfigParser (class in ConfigParser)</a>
</li>
      <li><a href="library/pprint.html#pprint.saferepr">saferepr() (in module pprint)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.same_files">same_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.same_quantum">same_quantum() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.same_quantum">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.samefile">samefile() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.sameopenfile">sameopenfile() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.samestat">samestat() (in module os.path)</a>
</li>
      <li><a href="library/random.html#random.sample">sample() (in module random)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.save">save() (cookielib.FileCookieJar method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.save_bgn">save_bgn() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.save_end">save_end() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SaveKey">SaveKey() (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.savetty">savetty() (in module curses)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.SAX2DOM">SAX2DOM (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXException">SAXException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXNotRecognizedException">SAXNotRecognizedException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXNotSupportedException">SAXNotSupportedException</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXParseException">SAXParseException</a>
</li>
      <li><a href="library/imageop.html#imageop.scale">scale() (in module imageop)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.scaleb">scaleb() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.scaleb">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scalebarvalues">scalebarvalues() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/re.html#index-0">scanf()</a>
</li>
      <li><a href="library/sched.html#module-sched">sched (module)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler">scheduler (class in sched)</a>
</li>
      <li><a href="library/msilib.html#msilib.schema">schema (in module msilib)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.sci">sci() (in module fpformat)</a>
</li>
      <li><a href="reference/executionmodel.html#index-1">scope</a>, <a href="reference/executionmodel.html#index-5">[1]</a>
</li>
      <li><a href="library/carbon.html#index-0">Scrap Manager</a>
</li>
      <li><a href="library/turtle.html#turtle.Screen">Screen (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.screensize">screensize() (in module turtle)</a>
</li>
      <li><a href="library/doctest.html#doctest.script_from_examples">script_from_examples() (in module doctest)</a>
</li>
      <li><a href="library/curses.html#curses.window.scroll">scroll() (curses.window method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scrollbar_callback">scrollbar_callback() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.scrollbars">scrollbars() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/turtle.html#turtle.ScrolledCanvas">ScrolledCanvas (class in turtle)</a>
</li>
      <li><a href="library/scrolledtext.html#module-ScrolledText">ScrolledText (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.scrollok">scrollok() (curses.window method)</a>
</li>
      <li>
    search

      <ul>
        <li><a href="c-api/init.html#index-0">path, module</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.search">search() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/re.html#re.search">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.search">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.SEARCH_ERROR">SEARCH_ERROR (in module imp)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.second">second (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.second">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/multifile.html#multifile.MultiFile.section_divider">section_divider() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.sections">sections() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.secure">secure (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/sha.html#index-0">Secure Hash Algorithm</a>
</li>
      <li><a href="library/hashlib.html#index-0">secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512</a>
</li>
      <li><a href="library/ssl.html#index-1">Secure Sockets Layer</a>
</li>
      <li>
    security

      <ul>
        <li><a href="library/cgi.html#index-1">CGI</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.see">see() (ttk.Treeview method)</a>
</li>
      <li><a href="library/random.html#random.seed">seed() (in module random)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.seek">seek() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/chunk.html#chunk.Chunk.seek">(chunk.Chunk method)</a>
</li>
        <li><a href="library/stdtypes.html#file.seek">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.seek">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.seek">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.seek">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.seek">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_CUR">SEEK_CUR (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_CUR">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_END">SEEK_END (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_END">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.SEEK_SET">SEEK_SET (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.SEEK_SET">(in module posixfile)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.IOBase.seekable">seekable() (io.IOBase method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.segcountproc">segcountproc (C type)</a>
</li>
      <li><a href="library/tix.html#Tix.Select">Select (class in Tix)</a>
</li>
      <li><a href="library/select.html#module-select">select (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.select">select() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/gl.html#gl.select">(in module gl)</a>
</li>
        <li><a href="library/select.html#select.select">(in module select)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.select">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLSocket.selected_alpn_protocol">selected_alpn_protocol() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.selected_npn_protocol">selected_npn_protocol() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection">selection() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_add">selection_add() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_remove">selection_remove() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_set">selection_set() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.selection_toggle">selection_toggle() (ttk.Treeview method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Semaphore">Semaphore (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Semaphore">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Semaphore">Semaphore() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/thread.html#index-0">semaphores, binary</a>
</li>
      <li><a href="library/token.html#token.SEMI">SEMI (in module token)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo.send">send() (aetools.TalkTo method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.send">(Connection method)</a>
</li>
        <li><a href="library/asyncore.html#asyncore.dispatcher.send">(asyncore.dispatcher method)</a>
</li>
        <li><a href="reference/expressions.html#generator.send">(generator method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.send">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.send">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.send">(logging.handlers.DatagramHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.send">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.send">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.send_bytes">send_bytes() (Connection method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_error">send_error() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_flowing_data">send_flowing_data() (formatter.writer method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_header">send_header() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_hor_rule">send_hor_rule() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_label_data">send_label_data() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_line_break">send_line_break() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_literal_data">send_literal_data() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.send_paragraph">send_paragraph() (formatter.writer method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.send_response">send_response() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen.send_signal">send_signal() (subprocess.Popen method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.sendall">sendall() (socket.socket method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.sendcmd">sendcmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.sendfile">sendfile() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.sendmail">sendmail() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.sendto">sendto() (socket.socket method)</a>
</li>
      <li><a href="library/os.html#os.sep">sep (in module os)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Separator">Separator() (in module FrameWork)</a>
</li>
      <li><a href="glossary.html#term-sequence"><strong>sequence</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-32">item</a>
</li>
        <li><a href="library/stdtypes.html#index-20">iteration</a>
</li>
        <li><a href="c-api/concrete.html#index-1">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/compound_stmts.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-17">[3]</a>, <a href="reference/datamodel.html#index-56">[4]</a>, <a href="reference/expressions.html#index-32">[5]</a>, <a href="reference/expressions.html#index-35">[6]</a>, <a href="reference/expressions.html#index-67">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="library/stdtypes.html#index-29">types, mutable</a>
</li>
        <li><a href="library/stdtypes.html#index-22">types, operations on</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Sequence">Sequence (class in collections)</a>
</li>
      <li><a href="library/msilib.html#msilib.sequence">sequence (in module msilib)</a>
</li>
      <li><a href="library/parser.html#parser.sequence2st">sequence2st() (in module parser)</a>
</li>
      <li><a href="library/operator.html#operator.sequenceIncludes">sequenceIncludes() (in module operator)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher">SequenceMatcher (class in difflib)</a>, <a href="library/difflib.html#difflib.SequenceMatcher">[1]</a>
</li>
      <li><a href="library/cookie.html#Cookie.SerialCookie">SerialCookie (class in Cookie)</a>
</li>
      <li>
    serializing

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.serve_forever">serve_forever() (SocketServer.BaseServer method)</a>
</li>
      <li>
    server

      <ul>
        <li><a href="library/basehttpserver.html#index-0">WWW</a>, <a href="library/cgi.html#index-0">[1]</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.server">server (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_activate">server_activate() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_address">server_address (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_bind">server_bind() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.server_close">server_close() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.server_software">server_software (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.server_version">server_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.server_version">(SimpleHTTPServer.SimpleHTTPRequestHandler attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy">ServerProxy (class in xmlrpclib)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.session_stats">session_stats() (ssl.SSLContext method)</a>
</li>
      <li>
    set

      <ul>
        <li><a href="reference/expressions.html#index-18">display</a>
</li>
        <li><a href="c-api/set.html#index-0">object</a>, <a href="library/stdtypes.html#index-31">[1]</a>, <a href="reference/datamodel.html#index-30">[2]</a>, <a href="reference/expressions.html#index-18">[3]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#set">set (built-in class)</a>
</li>
      <li><a href="library/collections.html#collections.Set">Set (class in collections)</a>

      <ul>
        <li><a href="library/sets.html#sets.Set">(class in sets)</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-4">Set Breakpoint</a>
</li>
      <li>
    set type

      <ul>
        <li><a href="reference/datamodel.html#index-29">object</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.set">set() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.SafeConfigParser.set">(ConfigParser.SafeConfigParser method)</a>
</li>
        <li><a href="library/cookie.html#Cookie.Morsel.set">(Cookie.Morsel method)</a>
</li>
        <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.set">(EasyDialogs.ProgressBar method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.set">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/test.html#test.support.EnvironmentVarGuard.set">(test.support.EnvironmentVarGuard method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.set">(threading.Event method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Combobox.set">(ttk.Combobox method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.set">(ttk.Treeview method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.set">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="c-api/intro.html#index-8">set_all()</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.set_allowed_domains">set_allowed_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_alpn_protocols">set_alpn_protocols() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer.set_app">set_app() (wsgiref.simple_server.WSGIServer method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.set_authorizer">set_authorizer() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.set_blocked_domains">set_blocked_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_boundary">set_boundary() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_break">set_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_charset">set_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.set_children">set_children() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_ciphers">set_ciphers() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/readline.html#readline.set_completer">set_completer() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.set_completer_delims">set_completer_delims() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.set_completion_display_matches_hook">set_completion_display_matches_hook() (in module readline)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_continue">set_continue() (bdb.Bdb method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_conversion_mode">set_conversion_mode() (in module ctypes)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_cookie">set_cookie() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_cookie_if_ok">set_cookie_if_ok() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Feature.set_current">set_current() (msilib.Feature method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_date">set_date() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/gc.html#gc.set_debug">set_debug() (in module gc)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.set_debuglevel">set_debuglevel() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPConnection.set_debuglevel">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.set_debuglevel">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.set_debuglevel">(poplib.POP3 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.set_debuglevel">(smtplib.SMTP method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.set_debuglevel">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.set_default_type">set_default_type() (email.message.Message method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_default_verify_paths">set_default_verify_paths() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.set_defaults">set_defaults() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.set_defaults">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_ecdh_curve">set_ecdh_curve() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_errno">set_errno() (in module ctypes)</a>
</li>
      <li><a href="library/fl.html#fl.set_event_call_back">set_event_call_back() (in module fl)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.set_executable">set_executable() (in module multiprocessing)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_executables">set_executables() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_flags">set_flags() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.set_flags">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.set_flags">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.set_form_position">set_form_position() (fl.form method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage.set_from">set_from() (mailbox.mboxMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.set_from">(mailbox.MMDFMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.set_graphics_mode">set_graphics_mode() (in module fl)</a>
</li>
      <li><a href="library/readline.html#readline.set_history_length">set_history_length() (in module readline)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_include_dirs">set_include_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_info">set_info() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.set_labels">set_labels() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.set_last_error">set_last_error() (in module ctypes)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_libraries">set_libraries() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_library_dirs">set_library_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/dis.html#opcode-SET_LINENO">SET_LINENO (opcode)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_link_objects">set_link_objects() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-set_literal">set_literal (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.set_location">set_location() (bsddb.bsddbobject method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_next">set_next() (bdb.Bdb method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.set_nonstandard_attr">set_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_npn_protocols">set_npn_protocols() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.set_ok">set_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.set_option_negotiation_callback">set_option_negotiation_callback() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.set_output_charset">set_output_charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_param">set_param() (email.message.Message method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.set_pasv">set_pasv() (ftplib.FTP method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_payload">set_payload() (email.message.Message method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.set_policy">set_policy() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.set_position">set_position() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/readline.html#readline.set_pre_input_hook">set_pre_input_hook() (in module readline)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.set_progress_handler">set_progress_handler() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.set_proxy">set_proxy() (urllib2.Request method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.set_python_build">set_python_build() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_quit">set_quit() (bdb.Bdb method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.set_recsrc">set_recsrc() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_return">set_return() (bdb.Bdb method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.set_runtime_library_dirs">set_runtime_library_dirs() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seq1">set_seq1() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seq2">set_seq2() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.set_seqs">set_seqs() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH.set_sequences">set_sequences() (mailbox.MH method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MHMessage.set_sequences">(mailbox.MHMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_documentation">set_server_documentation() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_documentation">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_name">set_server_name() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_name">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_title">set_server_title() (DocXMLRPCServer.DocCGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer.set_server_title">(DocXMLRPCServer.DocXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.set_servername_callback">set_servername_callback() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.set_spacing">set_spacing() (formatter.formatter method)</a>
</li>
      <li><a href="library/readline.html#readline.set_startup_hook">set_startup_hook() (in module readline)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_step">set_step() (bdb.Bdb method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.set_subdir">set_subdir() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.set_terminator">set_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/gc.html#gc.set_threshold">set_threshold() (in module gc)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_trace">set_trace() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/bdb.html#bdb.set_trace">(in module bdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.set_trace">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.set_trace">(pdb.Pdb method)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.set_tunnel">set_tunnel() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_type">set_type() (email.message.Message method)</a>
</li>
      <li><a href="library/doctest.html#doctest.set_unittest_reportflags">set_unittest_reportflags() (in module doctest)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.set_unixfrom">set_unixfrom() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.set_until">set_until() (bdb.Bdb method)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.set_url">set_url() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.set_usage">set_usage() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.set_userptr">set_userptr() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.set_visible">set_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/signal.html#signal.set_wakeup_fd">set_wakeup_fd() (in module signal)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setacl">setacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setannotation">setannotation() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.setarrowcursor">setarrowcursor() (in module FrameWork)</a>
</li>
      <li><a href="library/functions.html#setattr">setattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttribute">setAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNode">setAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNodeNS">setAttributeNodeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.setAttributeNS">setAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.SetBase">SetBase() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.setblocking">setblocking() (socket.socket method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setByteStream">setByteStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/tty.html#tty.setcbreak">setcbreak() (in module tty)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setCharacterStream">setCharacterStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="c-api/init.html#index-14">setcheckinterval() (in module sys)</a>, <a href="library/sys.html#sys.setcheckinterval">[1]</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setcomptype">setcomptype() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setcomptype">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setcomptype">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setContentHandler">setContentHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/decimal.html#decimal.setcontext">setcontext() (in module decimal)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.setcontext">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.SetCreatorAndType">SetCreatorAndType() (in module MacOS)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.setcurrent">setcurrent() (mhlib.Folder method)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.setDaemon">setDaemon() (threading.Thread method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.setdefault">setdefault() (dict method)</a>
</li>
      <li><a href="library/sys.html#sys.setdefaultencoding">setdefaultencoding() (in module sys)</a>
</li>
      <li><a href="library/socket.html#socket.setdefaulttimeout">setdefaulttimeout() (in module socket)</a>
</li>
      <li><a href="library/sys.html#sys.setdlopenflags">setdlopenflags() (in module sys)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.setDocumentLocator">setDocumentLocator() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setDTDHandler">setDTDHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.setegid">setegid() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setEncoding">setEncoding() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setEntityResolver">setEntityResolver() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setErrorHandler">setErrorHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.seteuid">seteuid() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setFeature">setFeature() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/calendar.html#calendar.setfirstweekday">setfirstweekday() (in module calendar)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.setfmt">setfmt() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.setFormatter">setFormatter() (logging.Handler method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setframerate">setframerate() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setframerate">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setframerate">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.setgid">setgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setgroups">setgroups() (in module os)</a>
</li>
      <li><a href="library/turtle.html#turtle.seth">seth() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.setheading">setheading() (in module turtle)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetInteger">SetInteger() (msilib.Record method)</a>
</li>
      <li><a href="library/operator.html#operator.setitem">setitem() (in module operator)</a>
</li>
      <li><a href="library/signal.html#signal.setitimer">setitimer() (in module signal)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.setlast">setlast() (mhlib.Folder method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.setLevel">setLevel() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.setLevel">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.setliteral">setliteral() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/locale.html#locale.setlocale">setlocale() (in module locale)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setLocale">setLocale() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/logging.html#logging.setLoggerClass">setLoggerClass() (in module logging)</a>
</li>
      <li><a href="library/syslog.html#syslog.setlogmask">setlogmask() (in module syslog)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setmark">setmark() (aifc.aifc method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler.setMaxConns">setMaxConns() (urllib2.CacheFTPHandler method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.setmode">setmode() (in module msvcrt)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.setName">setName() (threading.Thread method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setnchannels">setnchannels() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setnchannels">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setnchannels">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.setnframes">setnframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setnframes">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setnframes">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.setnomoretags">setnomoretags() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/jpeg.html#jpeg.setoption">setoption() (in module jpeg)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.SetParamEntityParsing">SetParamEntityParsing() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.setparameters">setparameters() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setparams">setparams() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/al.html#al.setparams">(in module al)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.setparams">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setparams">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.setpassword">setpassword() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/fm.html#fm.setpath">setpath() (in module fm)</a>
</li>
      <li><a href="library/os.html#os.setpgid">setpgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setpgrp">setpgrp() (in module os)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setpos">setpos() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.setpos">(in module turtle)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.setpos">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.setpos">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.setposition">setposition() (in module turtle)</a>
</li>
      <li><a href="library/sys.html#sys.setprofile">setprofile() (in module sys)</a>

      <ul>
        <li><a href="library/threading.html#threading.setprofile">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.SetProperty">SetProperty() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.setProperty">setProperty() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setPublicId">setPublicId() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.setquota">setquota() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/tty.html#tty.setraw">setraw() (in module tty)</a>
</li>
      <li><a href="library/sys.html#sys.setrecursionlimit">setrecursionlimit() (in module sys)</a>
</li>
      <li><a href="library/os.html#os.setregid">setregid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setresgid">setresgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setresuid">setresuid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.setreuid">setreuid() (in module os)</a>
</li>
      <li><a href="library/resource.html#resource.setrlimit">setrlimit() (in module resource)</a>
</li>
      <li><a href="library/sets.html#module-sets">sets (module)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.setsampwidth">setsampwidth() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.setsampwidth">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.setsampwidth">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.setscrreg">setscrreg() (curses.window method)</a>
</li>
      <li><a href="library/os.html#os.setsid">setsid() (in module os)</a>
</li>
      <li><a href="library/operator.html#operator.setslice">setslice() (in module operator)</a>
</li>
      <li><a href="library/socket.html#socket.socket.setsockopt">setsockopt() (socket.socket method)</a>
</li>
      <li><a href="library/random.html#random.setstate">setstate() (in module random)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetStream">SetStream() (msilib.Record method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.SetString">SetString() (msilib.Record method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.setSystemId">setSystemId() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/curses.html#curses.setsyx">setsyx() (in module curses)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.setTarget">setTarget() (logging.handlers.MemoryHandler method)</a>
</li>
      <li><a href="library/turtle.html#turtle.settiltangle">settiltangle() (in module turtle)</a>
</li>
      <li><a href="library/socket.html#socket.socket.settimeout">settimeout() (socket.socket method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler.setTimeout">setTimeout() (urllib2.CacheFTPHandler method)</a>
</li>
      <li><a href="library/sys.html#sys.settrace">settrace() (in module sys)</a>

      <ul>
        <li><a href="library/threading.html#threading.settrace">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.settscdump">settscdump() (in module sys)</a>
</li>
      <li><a href="library/ic.html#ic.IC.settypecreator">settypecreator() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.settypecreator">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.setuid">setuid() (in module os)</a>
</li>
      <li><a href="library/turtle.html#turtle.setundobuffer">setundobuffer() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.setup">setup() (in module distutils.core)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.setup">(SocketServer.BaseRequestHandler method)</a>
</li>
        <li><a href="library/turtle.html#turtle.setup">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.setUp">setUp() (unittest.TestCase method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.setup_environ">setup_environ() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_EXCEPT">SETUP_EXCEPT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_FINALLY">SETUP_FINALLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_LOOP">SETUP_LOOP (opcode)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.setup_testing_defaults">setup_testing_defaults() (in module wsgiref.util)</a>
</li>
      <li><a href="library/dis.html#opcode-SETUP_WITH">SETUP_WITH (opcode)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.setUpClass">setUpClass() (unittest.TestCase method)</a>
</li>
      <li><a href="library/curses.html#curses.setupterm">setupterm() (in module curses)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SetValue">SetValue() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.SetValueEx">SetValueEx() (in module _winreg)</a>
</li>
      <li><a href="c-api/file.html#index-4">setvbuf()</a>
</li>
      <li><a href="library/framework.html#FrameWork.setwatchcursor">setwatchcursor() (in module FrameWork)</a>
</li>
      <li><a href="library/turtle.html#turtle.setworldcoordinates">setworldcoordinates() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.setx">setx() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.sety">sety() (in module turtle)</a>
</li>
      <li><a href="library/stat.html#stat.SF_APPEND">SF_APPEND (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_ARCHIVED">SF_ARCHIVED (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_IMMUTABLE">SF_IMMUTABLE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_NOUNLINK">SF_NOUNLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.SF_SNAPSHOT">SF_SNAPSHOT (in module stat)</a>
</li>
      <li><a href="library/sgmllib.html#index-0">SGML</a>
</li>
      <li>
    sgmllib

      <ul>
        <li><a href="library/htmllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#module-sgmllib">sgmllib (module)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParseError">SGMLParseError</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser">SGMLParser (class in sgmllib)</a>

      <ul>
        <li><a href="library/htmllib.html#index-1">(in module sgmllib)</a>
</li>
      </ul></li>
      <li><a href="library/sha.html#module-sha">sha (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.Shape">Shape (class in turtle)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.shape">shape (memoryview attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.shape">shape() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.shapesize">shapesize() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.shared_object_filename">shared_object_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/shelve.html#shelve.Shelf">Shelf (class in shelve)</a>
</li>
      <li>
    shelve

      <ul>
        <li><a href="library/marshal.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/shelve.html#module-shelve">shelve (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.shift">shift() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.shift">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.shift_path_info">shift_path_info() (in module wsgiref.util)</a>
</li>
      <li>
    shifting

      <ul>
        <li><a href="reference/expressions.html#index-58">operation</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex">shlex (class in shlex)</a>

      <ul>
        <li><a href="library/shlex.html#module-shlex">(module)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.shortDescription">shortDescription() (unittest.TestCase method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.shouldFlush">shouldFlush() (logging.handlers.BufferingHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.shouldFlush">(logging.handlers.MemoryHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestResult.shouldStop">shouldStop (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.show">show() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/fl.html#fl.show_choice">show_choice() (in module fl)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.show_compilers">show_compilers() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/fl.html#fl.show_file_selector">show_file_selector() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.form.show_form">show_form() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.show_input">show_input() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.show_message">show_message() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.show_question">show_question() (in module fl)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter.showsyntaxerror">showsyntaxerror() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter.showtraceback">showtraceback() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="library/turtle.html#turtle.showturtle">showturtle() (in module turtle)</a>
</li>
      <li><a href="library/warnings.html#warnings.showwarning">showwarning() (in module warnings)</a>
</li>
      <li><a href="library/random.html#random.shuffle">shuffle() (in module random)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.shutdown">shutdown() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.shutdown">(SocketServer.BaseServer method)</a>
</li>
        <li><a href="library/macostools.html#findertools.shutdown">(in module findertools)</a>
</li>
        <li><a href="library/logging.html#logging.shutdown">(in module logging)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.shutdown">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.shutdown">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#module-shutil">shutil (module)</a>
</li>
      <li><a href="library/signal.html#signal.SIG_DFL">SIG_DFL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.SIG_IGN">SIG_IGN (in module signal)</a>
</li>
      <li><a href="c-api/exceptions.html#index-2">SIGINT</a>, <a href="c-api/exceptions.html#index-3">[1]</a>
</li>
      <li><a href="library/signal.html#signal.siginterrupt">siginterrupt() (in module signal)</a>
</li>
      <li>
    signal

      <ul>
        <li><a href="c-api/exceptions.html#index-2">module</a>, <a href="library/thread.html#index-2">[1]</a>
</li>
      </ul></li>
      <li><a href="library/signal.html#module-signal">signal (module)</a>
</li>
      <li><a href="library/signal.html#signal.signal">signal() (in module signal)</a>
</li>
      <li>
    simple

      <ul>
        <li><a href="reference/simple_stmts.html#index-0">statement</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#index-0">Simple Mail Transfer Protocol</a>
</li>
      <li><a href="library/cookie.html#Cookie.SimpleCookie">SimpleCookie (class in Cookie)</a>
</li>
      <li><a href="library/warnings.html#warnings.simplefilter">simplefilter() (in module warnings)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.SimpleHandler">SimpleHandler (class in wsgiref.handlers)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler">SimpleHTTPRequestHandler (class in SimpleHTTPServer)</a>
</li>
      <li>
    SimpleHTTPServer

      <ul>
        <li><a href="library/basehttpserver.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/simplehttpserver.html#module-SimpleHTTPServer">SimpleHTTPServer (module)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler">SimpleXMLRPCRequestHandler (class in SimpleXMLRPCServer)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer">SimpleXMLRPCServer (class in SimpleXMLRPCServer)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#module-SimpleXMLRPCServer">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.sin">sin() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.sin">(in module math)</a>
</li>
      </ul></li>
      <li>
    singleton

      <ul>
        <li><a href="reference/datamodel.html#index-24">tuple</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.sinh">sinh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.sinh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/site.html#module-site">site (module)</a>
</li>
      <li>
    site command line option

      <ul>
        <li><a href="library/site.html#cmdoption-site-user-base">--user-base</a>
</li>
        <li><a href="library/site.html#cmdoption-site-user-site">--user-site</a>
</li>
      </ul></li>
      <li>
    site-packages

      <ul>
        <li><a href="library/site.html#index-1">directory</a>
</li>
      </ul></li>
      <li>
    site-python

      <ul>
        <li><a href="library/site.html#index-1">directory</a>
</li>
      </ul></li>
      <li>
    sitecustomize

      <ul>
        <li><a href="library/site.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/struct.html#struct.Struct.size">size (struct.Struct attribute)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.size">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.size">size() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/mmap.html#mmap.mmap.size">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Sized">Sized (class in collections)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.sizeof">sizeof() (in module ctypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.SKIP">SKIP (in module doctest)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.skip">skip() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.skip">(in module unittest)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.skipIf">skipIf() (in module unittest)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.skipinitialspace">skipinitialspace (csv.Dialect attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.skipped">skipped (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.skippedEntity">skippedEntity() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/unittest.html#unittest.SkipTest">SkipTest</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.skipTest">skipTest() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.skipUnless">skipUnless() (in module unittest)</a>
</li>
      <li><a href="library/token.html#token.SLASH">SLASH (in module token)</a>
</li>
      <li><a href="library/token.html#token.SLASHEQUAL">SLASHEQUAL (in module token)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.slave">slave() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/macostools.html#findertools.sleep">sleep() (in module findertools)</a>

      <ul>
        <li><a href="library/time.html#time.sleep">(in module time)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-34">slice</a>, <a href="glossary.html#term-slice"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/dis.html#index-0">built-in function</a>, <a href="library/types.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-69">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-89">object</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#slice">slice (built-in class)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+0">SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+1">SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+2">SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-SLICE+3">SLICE+3 (opcode)</a>
</li>
      <li><a href="c-api/slice.html#index-0">SliceType (in module types)</a>, <a href="library/types.html#types.SliceType">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-18">slicing</a>, <a href="reference/datamodel.html#index-25">[1]</a>, <a href="reference/expressions.html#index-34">[2]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-13">assignment</a>
</li>
        <li><a href="reference/expressions.html#index-36">extended</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.SmartCookie">SmartCookie (class in Cookie)</a>
</li>
      <li>
    SMTP

      <ul>
        <li><a href="library/smtplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#smtplib.SMTP">SMTP (class in smtplib)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP_SSL">SMTP_SSL (class in smtplib)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPAuthenticationError">SMTPAuthenticationError</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPConnectError">SMTPConnectError</a>
</li>
      <li><a href="library/smtpd.html#module-smtpd">smtpd (module)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPDataError">SMTPDataError</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPException">SMTPException</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler">SMTPHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPHeloError">SMTPHeloError</a>
</li>
      <li><a href="library/smtplib.html#module-smtplib">smtplib (module)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPRecipientsRefused">SMTPRecipientsRefused</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPResponseException">SMTPResponseException</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPSenderRefused">SMTPSenderRefused</a>
</li>
      <li><a href="library/smtpd.html#smtpd.SMTPServer">SMTPServer (class in smtpd)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTPServerDisconnected">SMTPServerDisconnected</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_ALIAS">SND_ALIAS (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_ASYNC">SND_ASYNC (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_FILENAME">SND_FILENAME (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_LOOP">SND_LOOP (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_MEMORY">SND_MEMORY (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NODEFAULT">SND_NODEFAULT (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NOSTOP">SND_NOSTOP (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_NOWAIT">SND_NOWAIT (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.SND_PURGE">SND_PURGE (in module winsound)</a>
</li>
      <li><a href="library/sndhdr.html#module-sndhdr">sndhdr (module)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer.sniff">sniff() (csv.Sniffer method)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer">Sniffer (class in csv)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_DGRAM">SOCK_DGRAM (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_RAW">SOCK_RAW (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_RDM">SOCK_RDM (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_SEQPACKET">SOCK_SEQPACKET (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.SOCK_STREAM">SOCK_STREAM (in module socket)</a>
</li>
      <li>
    socket

      <ul>
        <li><a href="library/internet.html#index-1">module</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/socket.html#index-1">object</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#module-socket">socket (module)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.socket">(SocketServer.BaseServer attribute)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.socket">socket() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/select.html#index-0">(in module socket)</a>, <a href="library/socket.html#socket.socket">[1]</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.socket_type">socket_type (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler">SocketHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socket.html#socket.socketpair">socketpair() (in module socket)</a>
</li>
      <li><a href="library/socketserver.html#module-SocketServer">SocketServer (module)</a>
</li>
      <li><a href="library/socket.html#socket.SocketType">SocketType (in module socket)</a>
</li>
      <li><a href="c-api/file.html#index-5">softspace (file attribute)</a>, <a href="library/stdtypes.html#file.softspace">[1]</a>
</li>
      <li><a href="library/socket.html#socket.SOMAXCONN">SOMAXCONN (in module socket)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.sort">sort() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.sort_stats">sort_stats() (pstats.Stats method)</a>
</li>
      <li><a href="library/functions.html#sorted">sorted() (built-in function)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.sortTestMethodsUsing">sortTestMethodsUsing (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.source">source (doctest.Example attribute)</a>

      <ul>
        <li><a href="library/shlex.html#shlex.shlex.source">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-4">source character set</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.sourcehook">sourcehook() (shlex.shlex method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">space</a>
</li>
      <li><a href="library/re.html#re.MatchObject.span">span() (re.MatchObject method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.spawn">spawn() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="library/pty.html#pty.spawn">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.spawnl">spawnl() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnle">spawnle() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnlp">spawnlp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnlpe">spawnlpe() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnv">spawnv() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnve">spawnve() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnvp">spawnvp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.spawnvpe">spawnvpe() (in module os)</a>
</li>
      <li>
    special

      <ul>
        <li><a href="reference/datamodel.html#index-5">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-5">attribute, generic</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-special-method"><strong>special method</strong></a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.specified_attributes">specified_attributes (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.speed">speed() (in module turtle)</a>

      <ul>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.speed">(ossaudiodev.oss_audio_device method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.splash">splash() (in module MacOS)</a>
</li>
      <li><a href="library/os.path.html#os.path.split">split() (in module os.path)</a>

      <ul>
        <li><a href="library/re.html#re.split">(in module re)</a>
</li>
        <li><a href="library/shlex.html#shlex.split">(in module shlex)</a>
</li>
        <li><a href="library/string.html#string.split">(in module string)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.split">(re.RegexObject method)</a>
</li>
        <li><a href="library/stdtypes.html#str.split">(str method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.split_quoted">split_quoted() (in module distutils.util)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitdrive">splitdrive() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitext">splitext() (in module os.path)</a>
</li>
      <li><a href="library/string.html#string.splitfields">splitfields() (in module string)</a>
</li>
      <li><a href="library/stdtypes.html#str.splitlines">splitlines() (str method)</a>

      <ul>
        <li><a href="library/stdtypes.html#unicode.splitlines">(unicode method)</a>
</li>
      </ul></li>
      <li><a href="library/urlparse.html#urlparse.SplitResult">SplitResult (class in urlparse)</a>
</li>
      <li><a href="library/os.path.html#os.path.splitunc">splitunc() (in module os.path)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.SpooledTemporaryFile">SpooledTemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">sprintf-style formatting</a>
</li>
      <li><a href="library/spwd.html#module-spwd">spwd (module)</a>
</li>
      <li><a href="library/sqlite3.html#module-sqlite3">sqlite3 (module)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.sqlite_version">sqlite_version (in module sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.sqlite_version_info">sqlite_version_info (in module sqlite3)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.sqrt">sqrt() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.sqrt">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.sqrt">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.sqrt">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#index-1">SSL</a>
</li>
      <li><a href="library/ssl.html#module-ssl">ssl (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_SSL.ssl">ssl() (imaplib.IMAP4_SSL method)</a>
</li>
      <li><a href="library/ssl.html#index-18">SSL_CERT_FILE</a>
</li>
      <li><a href="library/ssl.html#index-19">SSL_CERT_PATH</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.ssl_version">ssl_version (ftplib.FTP_TLS attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext">SSLContext (class in ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLEOFError">SSLEOFError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLError">SSLError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSyscallError">SSLSyscallError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLWantReadError">SSLWantReadError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLWantWriteError">SSLWantWriteError</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLZeroReturnError">SSLZeroReturnError</a>
</li>
      <li><a href="library/turtle.html#turtle.st">st() (in module turtle)</a>
</li>
      <li><a href="library/parser.html#parser.st2list">st2list() (in module parser)</a>
</li>
      <li><a href="library/parser.html#parser.st2tuple">st2tuple() (in module parser)</a>
</li>
      <li><a href="library/stat.html#stat.ST_ATIME">ST_ATIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_CTIME">ST_CTIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_DEV">ST_DEV (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_GID">ST_GID (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_INO">ST_INO (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_MODE">ST_MODE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_MTIME">ST_MTIME (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_NLINK">ST_NLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_SIZE">ST_SIZE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.ST_UID">ST_UID (in module stat)</a>
</li>
      <li>
    stack

      <ul>
        <li><a href="reference/datamodel.html#index-67">execution</a>
</li>
        <li><a href="reference/datamodel.html#index-67">trace</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-3">stack viewer</a>
</li>
      <li><a href="library/inspect.html#inspect.stack">stack() (in module inspect)</a>
</li>
      <li><a href="library/thread.html#thread.stack_size">stack_size() (in module thread)</a>

      <ul>
        <li><a href="library/threading.html#threading.stack_size">(in module threading)</a>
</li>
      </ul></li>
      <li>
    stackable

      <ul>
        <li><a href="library/codecs.html#index-0">streams</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.stamp">stamp() (in module turtle)</a>
</li>
      <li>
    standard

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">output</a>, <a href="reference/simple_stmts.html#index-24">[1]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-15">Standard C</a>
</li>
      <li><a href="reference/toplevel_components.html#index-4">standard input</a>
</li>
      <li><a href="library/base64.html#base64.standard_b64decode">standard_b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.standard_b64encode">standard_b64encode() (in module base64)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.StandardError">StandardError</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-standarderror">standarderror (2to3 fixer)</a>
</li>
      <li><a href="library/curses.html#curses.window.standend">standend() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.standout">standout() (curses.window method)</a>
</li>
      <li><a href="library/token.html#token.STAR">STAR (in module token)</a>
</li>
      <li><a href="library/token.html#token.STAREQUAL">STAREQUAL (in module token)</a>
</li>
      <li><a href="library/itertools.html#itertools.starmap">starmap() (in module itertools)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.start">start (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-70">(slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      </ul></li>
      <li><a href="library/hotshot.html#hotshot.Profile.start">start() (hotshot.Profile method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.start">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.start">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/re.html#re.MatchObject.start">(re.MatchObject method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.start">(threading.Thread method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Progressbar.start">(ttk.Progressbar method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.start">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.start_color">start_color() (in module curses)</a>
</li>
      <li><a href="library/msilib.html#msilib.Directory.start_component">start_component() (msilib.Directory method)</a>
</li>
      <li><a href="library/thread.html#thread.start_new_thread">start_new_thread() (in module thread)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.startbody">startbody() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartCdataSectionHandler">StartCdataSectionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler">StartDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startDocument">startDocument() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startElement">startElement() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartElementHandler">StartElementHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startElementNS">startElementNS() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTF_USESHOWWINDOW">STARTF_USESHOWWINDOW (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTF_USESTDHANDLES">STARTF_USESTDHANDLES (in module subprocess)</a>
</li>
      <li><a href="library/os.html#os.startfile">startfile() (in module os)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.startmultipartbody">startmultipartbody() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler">StartNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.startPrefixMapping">startPrefixMapping() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/stdtypes.html#str.startswith">startswith() (str method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.startTest">startTest() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.startTestRun">startTestRun() (unittest.TestResult method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.starttls">starttls() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO">STARTUPINFO (class in subprocess)</a>
</li>
      <li>
    stat

      <ul>
        <li><a href="library/os.html#index-16">module</a>
</li>
      </ul></li>
      <li><a href="library/stat.html#module-stat">stat (module)</a>
</li>
      <li><a href="library/os.html#os.stat">stat() (in module os)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.stat">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.stat">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.stat_float_times">stat_float_times() (in module os)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget.state">state() (ttk.Widget method)</a>
</li>
      <li><a href="glossary.html#term-statement"><strong>statement</strong></a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-21">*</a>, <a href="tutorial/controlflow.html#index-2">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-21">**</a>, <a href="tutorial/controlflow.html#index-3">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-19">@</a>
</li>
        <li><a href="library/exceptions.html#index-2">assert</a>, <a href="reference/simple_stmts.html#index-15">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">assignment</a>, <a href="reference/simple_stmts.html#index-3">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-14">assignment, augmented</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">break</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-33">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">class</a>
</li>
        <li><a href="reference/compound_stmts.html#index-0">compound</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">continue</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">def</a>
</li>
        <li><a href="library/stdtypes.html#index-30">del</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-75">[2]</a>, <a href="reference/simple_stmts.html#index-18">[3]</a>
</li>
        <li><a href="library/exceptions.html#index-0">except</a>
</li>
        <li><a href="library/stdtypes.html#index-41">exec</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>, <a href="reference/simple_stmts.html#index-56">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-1">expression</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">for</a>, <a href="reference/simple_stmts.html#index-33">[1]</a>, <a href="reference/simple_stmts.html#index-37">[2]</a>, <a href="tutorial/controlflow.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-0">[4]</a>
</li>
        <li><a href="reference/executionmodel.html#index-9">from</a>
</li>
        <li><a href="reference/simple_stmts.html#index-52">future</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">global</a>, <a href="reference/simple_stmts.html#index-54">[1]</a>, <a href="reference/simple_stmts.html#index-7">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-2">if</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>
</li>
        <li><a href="library/functions.html#index-8">import</a>, <a href="library/imp.html#index-0">[1]</a>, <a href="library/imputil.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-47">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-4">loop</a>, <a href="reference/compound_stmts.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-17">pass</a>
</li>
        <li><a href="library/stdtypes.html#index-1">print</a>, <a href="reference/datamodel.html#index-78">[1]</a>, <a href="reference/simple_stmts.html#index-22">[2]</a>
</li>
        <li><a href="library/exceptions.html#index-1">raise</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">return</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/simple_stmts.html#index-26">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-0">simple</a>
</li>
        <li><a href="library/exceptions.html#index-0">try</a>, <a href="reference/compound_stmts.html#index-10">[1]</a>, <a href="reference/datamodel.html#index-68">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-2">while</a>, <a href="reference/compound_stmts.html#index-4">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-15">with</a>, <a href="reference/datamodel.html#index-96">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-28">yield</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-7">statement grouping</a>
</li>
      <li>
    staticmethod

      <ul>
        <li><a href="c-api/structures.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#staticmethod">staticmethod() (built-in function)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats">Stats (class in pstats)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.status">status (httplib.HTTPResponse attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.status">status() (imaplib.IMAP4 method)</a>
</li>
      <li>
    statvfs

      <ul>
        <li><a href="library/os.html#index-17">module</a>
</li>
      </ul></li>
      <li><a href="library/statvfs.html#module-statvfs">statvfs (module)</a>
</li>
      <li><a href="library/os.html#os.statvfs">statvfs() (in module os)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_ERROR_HANDLE">STD_ERROR_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_INPUT_HANDLE">STD_INPUT_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STD_OUTPUT_HANDLE">STD_OUTPUT_HANDLE (in module subprocess)</a>
</li>
      <li><a href="library/tix.html#Tix.StdButtonBox">StdButtonBox (class in Tix)</a>
</li>
      <li><a href="c-api/init.html#index-21">stderr (in module sys)</a>, <a href="library/sys.html#sys.stderr">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stderr">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-21">stdin (in module sys)</a>, <a href="library/sys.html#sys.stdin">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stdin">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-58">stdio</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STDOUT">STDOUT (in module subprocess)</a>
</li>
      <li><a href="c-api/init.html#index-21">stdout (in module sys)</a>, <a href="library/sys.html#sys.stdout">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/simple_stmts.html#index-24">[3]</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.stdout">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#index-0">Stein, Greg</a>
</li>
      <li><a href="reference/datamodel.html#index-70">step (slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      <li><a href="library/ttk.html#ttk.Progressbar.step">step() (ttk.Progressbar method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.stereocontrols">stereocontrols() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/cd.html#cd.STILL">STILL (in module cd)</a>
</li>
      <li><a href="reference/datamodel.html#index-70">stop (slice object attribute)</a>, <a href="reference/expressions.html#index-37">[1]</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile.stop">stop() (hotshot.Profile method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Progressbar.stop">(ttk.Progressbar method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.stop">(unittest.TestResult method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-STOP_CODE">STOP_CODE (opcode)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.stop_here">stop_here() (bdb.Bdb method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.StopIteration">StopIteration</a>

      <ul>
        <li><a href="reference/expressions.html#index-25">exception</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/logging.config.html#logging.config.stopListening">stopListening() (in module logging.config)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.stopTest">stopTest() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.stopTestRun">stopTestRun() (unittest.TestResult method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.storbinary">storbinary() (ftplib.FTP method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.store">store() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.STORE_ACTIONS">STORE_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_ATTR">STORE_ATTR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_DEREF">STORE_DEREF (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_FAST">STORE_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_GLOBAL">STORE_GLOBAL (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_MAP">STORE_MAP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_NAME">STORE_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+0">STORE_SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+1">STORE_SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+2">STORE_SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SLICE+3">STORE_SLICE+3 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-STORE_SUBSCR">STORE_SUBSCR (opcode)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.storlines">storlines() (ftplib.FTP method)</a>
</li>
      <li>
    str

      <ul>
        <li><a href="c-api/object.html#index-3">built-in function</a>, <a href="extending/newtypes.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-78">[2]</a>, <a href="reference/expressions.html#index-21">[3]</a>
</li>
        <li><a href="library/functions.html#index-3">format</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#str">str (built-in class)</a>
</li>
      <li><a href="library/locale.html#locale.str">str() (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.strcoll">strcoll() (in module locale)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.StreamError">StreamError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.StreamHandler">StreamHandler (class in logging)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamReader">StreamReader (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamReaderWriter">StreamReaderWriter (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.StreamRecoder">StreamRecoder (class in codecs)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.StreamRequestHandler">StreamRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/codecs.html#index-0">streams</a>

      <ul>
        <li><a href="library/codecs.html#index-0">stackable</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.StreamWriter">StreamWriter (class in codecs)</a>
</li>
      <li><a href="c-api/exceptions.html#index-1">strerror()</a>

      <ul>
        <li><a href="library/os.html#os.strerror">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.strftime">strftime() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.strftime">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.strftime">(datetime.time method)</a>
</li>
        <li><a href="library/time.html#time.strftime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.strict">strict (csv.Dialect attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_domain">strict_domain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/codecs.html#codecs.strict_errors">strict_errors() (in module codecs)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_domain">strict_ns_domain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_set_initial_dollar">strict_ns_set_initial_dollar (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_set_path">strict_ns_set_path (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_ns_unverifiable">strict_ns_unverifiable (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.strict_rfc2965_unverifiable">strict_rfc2965_unverifiable (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.strides">strides (memoryview attribute)</a>
</li>
      <li>
    string

      <ul>
        <li><a href="reference/lexical_analysis.html#index-14">Unicode</a>
</li>
        <li><a href="reference/datamodel.html#index-22">comparison</a>
</li>
        <li><a href="reference/datamodel.html#index-77">conversion</a>, <a href="reference/expressions.html#index-19">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-25">formatting</a>
</li>
        <li><a href="library/stdtypes.html#index-25">interpolation</a>
</li>
        <li><a href="reference/expressions.html#index-33">item</a>
</li>
        <li><a href="library/stdtypes.html#index-23">methods</a>
</li>
        <li><a href="library/locale.html#index-7">module</a>, <a href="library/locale.html#index-8">[1]</a>, <a href="library/stdtypes.html#index-27">[2]</a>
</li>
        <li><a href="c-api/string.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-21">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.STRING">STRING (in module token)</a>
</li>
      <li><a href="library/string.html#module-string">string (module)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.string">(re.MatchObject attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-12">string literal</a>
</li>
      <li><a href="library/ctypes.html#ctypes.string_at">string_at() (in module ctypes)</a>
</li>
      <li><a href="library/io.html#io.StringIO">StringIO (class in io)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO">(class in StringIO)</a>
</li>
        <li><a href="library/stringio.html#module-StringIO">(module)</a>
</li>
      </ul></li>
      <li><a href="library/stringio.html#cStringIO.StringIO">StringIO() (in module cStringIO)</a>
</li>
      <li><a href="library/stringprep.html#module-stringprep">stringprep (module)</a>
</li>
      <li><a href="tutorial/controlflow.html#index-1">strings, documentation</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="c-api/string.html#index-1">StringType (in module types)</a>, <a href="library/types.html#types.StringType">[1]</a>
</li>
      <li><a href="library/types.html#types.StringTypes">StringTypes (in module types)</a>
</li>
      <li><a href="library/string.html#string.strip">strip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.strip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.strip_dirs">strip_dirs() (pstats.Stats method)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.stripspaces">stripspaces (curses.textpad.Textbox attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.strptime">strptime() (datetime.datetime class method)</a>

      <ul>
        <li><a href="library/time.html#time.strptime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.strtobool">strtobool() (in module distutils.util)</a>
</li>
      <li>
    struct

      <ul>
        <li><a href="library/socket.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="library/struct.html#struct.Struct">Struct (class in struct)</a>
</li>
      <li><a href="library/struct.html#module-struct">struct (module)</a>
</li>
      <li><a href="glossary.html#term-struct-sequence"><strong>struct sequence</strong></a>
</li>
      <li><a href="library/time.html#time.struct_time">struct_time (class in time)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Structure">Structure (class in ctypes)</a>
</li>
      <li>
    structures

      <ul>
        <li><a href="library/struct.html#index-0">C</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.strxfrm">strxfrm() (in module locale)</a>
</li>
      <li><a href="library/parser.html#parser.STType">STType (in module parser)</a>
</li>
      <li>
    style

      <ul>
        <li><a href="tutorial/controlflow.html#index-5">coding</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Style">Style (class in ttk)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.StyledText">StyledText (class in aetypes)</a>
</li>
      <li><a href="library/operator.html#operator.sub">sub() (in module operator)</a>

      <ul>
        <li><a href="library/re.html#re.sub">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.sub">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.sub_commands">sub_commands (distutils.cmd.Command attribute)</a>
</li>
      <li>
    subclassing

      <ul>
        <li><a href="reference/datamodel.html#index-73">immutable types</a>
</li>
      </ul></li>
      <li><a href="library/filecmp.html#filecmp.dircmp.subdirs">subdirs (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.SubElement">SubElement() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/framework.html#FrameWork.SubMenu">SubMenu() (in module FrameWork)</a>
</li>
      <li><a href="library/re.html#re.subn">subn() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.subn">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Subnormal">Subnormal (class in decimal)</a>
</li>
      <li><a href="library/curses.html#curses.window.subpad">subpad() (curses.window method)</a>
</li>
      <li><a href="library/subprocess.html#module-subprocess">subprocess (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.subscribe">subscribe() (imaplib.IMAP4 method)</a>
</li>
      <li>
    subscript

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-17">subscription</a>, <a href="reference/datamodel.html#index-25">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/expressions.html#index-31">[3]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-10">assignment</a>
</li>
      </ul></li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.subsequent_indent">subsequent_indent (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.subst_vars">subst_vars() (in module distutils.util)</a>
</li>
      <li><a href="library/string.html#string.Template.substitute">substitute() (string.Template method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.subtract">subtract() (collections.Counter method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.subtract">(decimal.Context method)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-57">subtraction</a>
</li>
      <li><a href="library/sys.html#sys.subversion">subversion (in module sys)</a>
</li>
      <li><a href="library/curses.html#curses.window.subwin">subwin() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.successful">successful() (multiprocessing.pool.AsyncResult method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.suffix_map">suffix_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.suffix_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/compound_stmts.html#index-1">suite</a>
</li>
      <li><a href="library/parser.html#parser.suite">suite() (in module parser)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.suiteClass">suiteClass (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/functions.html#sum">sum() (built-in function)</a>
</li>
      <li><a href="c-api/intro.html#index-10">sum_list()</a>
</li>
      <li><a href="c-api/intro.html#index-11">sum_sequence()</a>, <a href="c-api/intro.html#index-16">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.summarize">summarize() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/sunau.html#module-sunau">sunau (module)</a>
</li>
      <li>
    SUNAUDIODEV

      <ul>
        <li><a href="library/sunaudio.html#index-1">module</a>
</li>
      </ul></li>
      <li>
    sunaudiodev

      <ul>
        <li><a href="library/sunaudio.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/sunaudio.html#module-SUNAUDIODEV">SUNAUDIODEV (module)</a>
</li>
      <li><a href="library/sunaudio.html#module-sunaudiodev">sunaudiodev (module)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.Class.super">super (pyclbr.Class attribute)</a>
</li>
      <li><a href="library/functions.html#super">super() (built-in function)</a>
</li>
      <li><a href="library/os.path.html#os.path.supports_unicode_filenames">supports_unicode_filenames (in module os.path)</a>
</li>
      <li>
    suppression

      <ul>
        <li><a href="reference/simple_stmts.html#index-23">newline</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.SW_HIDE">SW_HIDE (in module subprocess)</a>
</li>
      <li><a href="library/string.html#string.swapcase">swapcase() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.swapcase">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#dl.dl.sym">sym() (dl.dl method)</a>
</li>
      <li><a href="library/symbol.html#symbol.sym_name">sym_name (in module symbol)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol">Symbol (class in symtable)</a>
</li>
      <li><a href="library/symbol.html#module-symbol">symbol (module)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable">SymbolTable (class in symtable)</a>
</li>
      <li><a href="library/os.html#os.symlink">symlink() (in module os)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.symmetric_difference">symmetric_difference() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.symmetric_difference_update">symmetric_difference_update() (frozenset method)</a>
</li>
      <li><a href="library/symtable.html#module-symtable">symtable (module)</a>
</li>
      <li><a href="library/symtable.html#symtable.symtable">symtable() (in module symtable)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.sync">sync() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.sync">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.dumbdbm.sync">(dumbdbm.dumbdbm method)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.sync">(in module gdbm)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.sync">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/shelve.html#shelve.Shelf.sync">(shelve.Shelf method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.syncdown">syncdown() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.synchronized">synchronized() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager">SyncManager (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/curses.html#curses.window.syncok">syncok() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.syncup">syncup() (curses.window method)</a>
</li>
      <li><a href="reference/expressions.html#index-2">syntax</a>, <a href="reference/introduction.html#index-0">[1]</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.SyntaxErr">SyntaxErr</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SyntaxError">SyntaxError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SyntaxWarning">SyntaxWarning</a>
</li>
      <li>
    sys

      <ul>
        <li><a href="c-api/init.html#index-0">module</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/simple_stmts.html#index-24">[4]</a>, <a href="reference/toplevel_components.html#index-2">[5]</a>, <a href="tutorial/modules.html#index-4">[6]</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#module-sys">sys (module)</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.exc_info</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.exc_traceback</a>
</li>
      <li><a href="reference/datamodel.html#index-67">sys.last_traceback</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">sys.meta_path</a>
</li>
      <li><a href="reference/simple_stmts.html#index-40">sys.modules</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path_hooks</a>
</li>
      <li><a href="reference/simple_stmts.html#index-43">sys.path_importer_cache</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stderr</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stdin</a>
</li>
      <li><a href="reference/datamodel.html#index-58">sys.stdout</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-sys_exc">sys_exc (2to3 fixer)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.sys_version">sys_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/macos.html#MacOS.SysBeep">SysBeep() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.sysconf">sysconf() (in module os)</a>
</li>
      <li><a href="library/os.html#os.sysconf_names">sysconf_names (in module os)</a>
</li>
      <li><a href="library/sysconfig.html#module-sysconfig">sysconfig (module)</a>
</li>
      <li><a href="library/syslog.html#module-syslog">syslog (module)</a>
</li>
      <li><a href="library/syslog.html#syslog.syslog">syslog() (in module syslog)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler">SysLogHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/os.html#os.system">system() (in module os)</a>

      <ul>
        <li><a href="library/platform.html#platform.system">(in module platform)</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.system_alias">system_alias() (in module platform)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.SystemError">SystemError</a>

      <ul>
        <li><a href="c-api/module.html#index-4">(built-in exception)</a>, <a href="c-api/module.html#index-5">[1]</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.SystemExit">SystemExit</a>

      <ul>
        <li><a href="reference/executionmodel.html#index-15">(built-in exception)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.systemId">systemId (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/random.html#random.SystemRandom">SystemRandom (class in random)</a>
</li>
      <li><a href="library/subprocess.html#index-3">SystemRoot</a>
</li>
  </ul></td>
</tr></table>

<h2 id="T">T</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/locale.html#locale.T_FMT">T_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.T_FMT_AMPM">T_FMT_AMPM (in module locale)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">tab</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.tab">tab() (ttk.Notebook method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.TabError">TabError</a>
</li>
      <li><a href="library/tabnanny.html#module-tabnanny">tabnanny (module)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.tabs">tabs() (ttk.Notebook method)</a>
</li>
      <li>
    tabular

      <ul>
        <li><a href="library/csv.html#index-0">data</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tag">tag (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_bind">tag_bind() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_configure">tag_configure() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.tag_has">tag_has() (ttk.Treeview method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.tagName">tagName (xml.dom.Element attribute)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.tail">tail (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="library/itertools.html#itertools.takewhile">takewhile() (in module itertools)</a>
</li>
      <li><a href="library/aetools.html#aetools.TalkTo">TalkTo (class in aetools)</a>
</li>
      <li><a href="library/cmath.html#cmath.tan">tan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.tan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.tanh">tanh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.tanh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarError">TarError</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile">TarFile (class in tarfile)</a>, <a href="library/tarfile.html#tarfile.TarFile">[1]</a>
</li>
      <li><a href="library/tarfile.html#module-tarfile">tarfile (module)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat">TarFileCompat (class in tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat.TAR_GZIPPED">TarFileCompat.TAR_GZIPPED (in module tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFileCompat.TAR_PLAIN">TarFileCompat.TAR_PLAIN (in module tarfile)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-5">target</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-18">deletion</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">list</a>, <a href="reference/simple_stmts.html#index-5">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-6">list assignment</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">list, deletion</a>
</li>
        <li><a href="reference/simple_stmts.html#index-35">loop control</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.ProcessingInstruction.target">target (xml.dom.ProcessingInstruction attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo">TarInfo (class in tarfile)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue.task_done">task_done() (multiprocessing.JoinableQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.task_done">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-68">tb_frame (traceback attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_lasti (traceback attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_lineno (traceback attribute)</a>
</li>
      <li><a href="library/traceback.html#traceback.tb_lineno">tb_lineno() (in module traceback)</a>
</li>
      <li><a href="reference/datamodel.html#index-68">tb_next (traceback attribute)</a>
</li>
      <li><a href="library/termios.html#termios.tcdrain">tcdrain() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcflow">tcflow() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcflush">tcflush() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcgetattr">tcgetattr() (in module termios)</a>
</li>
      <li><a href="library/os.html#os.tcgetpgrp">tcgetpgrp() (in module os)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Tcl">Tcl() (in module Tkinter)</a>
</li>
      <li><a href="faq/gui.html#index-0">TCL_LIBRARY</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.TCPServer">TCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/termios.html#termios.tcsendbreak">tcsendbreak() (in module termios)</a>
</li>
      <li><a href="library/termios.html#termios.tcsetattr">tcsetattr() (in module termios)</a>
</li>
      <li><a href="library/os.html#os.tcsetpgrp">tcsetpgrp() (in module os)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.tearDown">tearDown() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.tearDownClass">tearDownClass() (unittest.TestCase method)</a>
</li>
      <li><a href="library/itertools.html#itertools.tee">tee() (in module itertools)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.tell">tell() (aifc.aifc method)</a>, <a href="library/aifc.html#aifc.aifc.tell">[1]</a>

      <ul>
        <li><a href="library/bz2.html#bz2.BZ2File.tell">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.tell">(chunk.Chunk method)</a>
</li>
        <li><a href="library/stdtypes.html#file.tell">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.tell">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.tell">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.tell">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.tell">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.tell">(sunau.AU_read method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.tell">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.tell">(wave.Wave_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.tell">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet">Telnet (class in telnetlib)</a>
</li>
      <li><a href="library/telnetlib.html#module-telnetlib">telnetlib (module)</a>
</li>
      <li><a href="library/tempfile.html#index-2">TEMP</a>
</li>
      <li><a href="library/tempfile.html#tempfile.tempdir">tempdir (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#module-tempfile">tempfile (module)</a>
</li>
      <li><a href="library/pipes.html#pipes.Template">Template (class in pipes)</a>

      <ul>
        <li><a href="library/string.html#string.Template">(class in string)</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.template">template (in module tempfile)</a>

      <ul>
        <li><a href="library/string.html#string.Template.template">(string.Template attribute)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.tempnam">tempnam() (in module os)</a>
</li>
      <li>
    temporary

      <ul>
        <li><a href="library/tempfile.html#index-0">file</a>
</li>
        <li><a href="library/tempfile.html#index-0">file name</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.TemporaryFile">TemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/curses.html#index-1">TERM</a>, <a href="library/curses.html#index-2">[1]</a>
</li>
      <li><a href="library/curses.html#curses.termattrs">termattrs() (in module curses)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.terminate">terminate() (multiprocessing.pool.multiprocessing.Pool method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.terminate">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.terminate">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-14">termination model</a>
</li>
      <li><a href="library/termios.html#module-termios">termios (module)</a>
</li>
      <li><a href="library/curses.html#curses.termname">termname() (in module curses)</a>
</li>
      <li>
    ternary

      <ul>
        <li><a href="reference/expressions.html#index-73">operator</a>
</li>
      </ul></li>
      <li>
    test

      <ul>
        <li><a href="reference/expressions.html#index-68">identity</a>
</li>
        <li><a href="reference/expressions.html#index-67">membership</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.test">test (doctest.DocTestFailure attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.UnexpectedException.test">(doctest.UnexpectedException attribute)</a>
</li>
        <li><a href="library/test.html#module-test">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#cgi.test">test() (in module cgi)</a>

      <ul>
        <li><a href="library/mutex.html#mutex.mutex.test">(mutex.mutex method)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#module-test.support">test.support (module)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex.testandset">testandset() (mutex.mutex method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase">TestCase (class in unittest)</a>
</li>
      <li><a href="library/test.html#test.support.TestFailed">TestFailed</a>
</li>
      <li><a href="library/doctest.html#doctest.testfile">testfile() (in module doctest)</a>
</li>
      <li><a href="library/test.html#test.support.TESTFN">TESTFN (in module test.support)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader">TestLoader (class in unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.testMethodPrefix">testMethodPrefix (unittest.TestLoader attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.testmod">testmod() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult">TestResult (class in unittest)</a>
</li>
      <li><a href="library/imghdr.html#imghdr.tests">tests (in module imghdr)</a>
</li>
      <li><a href="library/doctest.html#doctest.testsource">testsource() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.testsRun">testsRun (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite">TestSuite (class in unittest)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.testzip">testzip() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/msilib.html#msilib.text">text (in module msilib)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.text">(xml.etree.ElementTree.Element attribute)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog.text">text() (msilib.Dialog method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.text_factory">text_factory (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox">Textbox (class in curses.textpad)</a>
</li>
      <li><a href="library/calendar.html#calendar.TextCalendar">TextCalendar (class in calendar)</a>
</li>
      <li><a href="library/gettext.html#gettext.textdomain">textdomain() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.textdomain">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.text_file.TextFile">TextFile (class in distutils.text_file)</a>
</li>
      <li><a href="library/io.html#io.TextIOBase">TextIOBase (class in io)</a>
</li>
      <li><a href="library/io.html#io.TextIOWrapper">TextIOWrapper (class in io)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestResult">TextTestResult (class in unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TextTestRunner">TextTestRunner (class in unittest)</a>
</li>
      <li><a href="library/textwrap.html#module-textwrap">textwrap (module)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper">TextWrapper (class in textwrap)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_create">theme_create() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_names">theme_names() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_settings">theme_settings() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.theme_use">theme_use() (ttk.Style method)</a>
</li>
      <li><a href="library/locale.html#locale.THOUSEP">THOUSEP (in module locale)</a>
</li>
      <li>
    thread

      <ul>
        <li><a href="c-api/init.html#index-20">module</a>
</li>
      </ul></li>
      <li><a href="library/threading.html#threading.Thread">Thread (class in threading)</a>
</li>
      <li><a href="library/thread.html#module-thread">thread (module)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.thread">thread() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/threading.html#threading.ThreadError">ThreadError</a>
</li>
      <li><a href="library/threading.html#module-threading">threading (module)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingMixIn">ThreadingMixIn (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingTCPServer">ThreadingTCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ThreadingUDPServer">ThreadingUDPServer (class in SocketServer)</a>
</li>
      <li>
    threads

      <ul>
        <li><a href="library/thread.html#index-3">IRIX</a>
</li>
        <li><a href="library/thread.html#index-1">POSIX</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-throw">throw (2to3 fixer)</a>
</li>
      <li><a href="reference/expressions.html#generator.throw">throw() (generator method)</a>
</li>
      <li><a href="library/fl.html#fl.tie">tie() (in module fl)</a>
</li>
      <li><a href="library/curses.html#curses.tigetflag">tigetflag() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.tigetnum">tigetnum() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.tigetstr">tigetstr() (in module curses)</a>
</li>
      <li><a href="library/token.html#token.TILDE">TILDE (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.tilt">tilt() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.tiltangle">tiltangle() (in module turtle)</a>
</li>
      <li><a href="library/datetime.html#datetime.time">time (class in datetime)</a>

      <ul>
        <li><a href="library/time.html#module-time">(module)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.time">time() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/time.html#time.time">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.Time2Internaldate">Time2Internaldate() (in module imaplib)</a>
</li>
      <li><a href="library/datetime.html#datetime.timedelta">timedelta (class in datetime)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler">TimedRotatingFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/calendar.html#calendar.timegm">timegm() (in module calendar)</a>
</li>
      <li><a href="library/timeit.html#module-timeit">timeit (module)</a>
</li>
      <li>
    timeit command line option

      <ul>
        <li><a href="library/timeit.html#cmdoption-timeit-c">-c, --clock</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-h">-h, --help</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-n">-n N, --number=N</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-r">-r N, --repeat=N</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-s">-s S, --setup=S</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-t">-t, --time</a>
</li>
        <li><a href="library/timeit.html#cmdoption-timeit-v">-v, --verbose</a>
</li>
      </ul></li>
      <li><a href="library/timeit.html#timeit.timeit">timeit() (in module timeit)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer.timeit">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.timeout">timeout</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.timeout">(SocketServer.BaseServer attribute)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.timeout">timeout() (curses.window method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.TimeoutError">TimeoutError</a>
</li>
      <li><a href="library/threading.html#threading.Timer">Timer (class in threading)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer">(class in timeit)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.times">times() (in module os)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.timetuple">timetuple() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.timetuple">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.timetz">timetz() (datetime.datetime method)</a>
</li>
      <li><a href="library/time.html#time.timezone">timezone (in module time)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.title">title() (EasyDialogs.ProgressBar method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.title">(in module turtle)</a>
</li>
        <li><a href="library/stdtypes.html#str.title">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#index-0">Tix</a>

      <ul>
        <li><a href="library/tix.html#Tix.Tix">(class in Tix)</a>
</li>
        <li><a href="library/tix.html#module-Tix">(module)</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_addbitmapdir">tix_addbitmapdir() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_cget">tix_cget() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_configure">tix_configure() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_filedialog">tix_filedialog() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_getbitmap">tix_getbitmap() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_getimage">tix_getimage() (Tix.tixCommand method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/tix.html#index-1">TIX_LIBRARY</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_option_get">tix_option_get() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand.tix_resetoptions">tix_resetoptions() (Tix.tixCommand method)</a>
</li>
      <li><a href="library/tix.html#Tix.tixCommand">tixCommand (class in Tix)</a>
</li>
      <li><a href="library/tk.html#index-0">Tk</a>

      <ul>
        <li><a href="library/tkinter.html#Tkinter.Tk">(class in Tkinter)</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#index-2">Tk Option Data Types</a>
</li>
      <li><a href="faq/gui.html#index-1">TK_LIBRARY</a>
</li>
      <li><a href="library/tk.html#index-0">Tkinter</a>

      <ul>
        <li><a href="library/tkinter.html#module-Tkinter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#Tix.TList">TList (class in Tix)</a>
</li>
      <li><a href="library/ssl.html#index-1">TLS</a>
</li>
      <li><a href="library/os.html#index-19">TMP</a>, <a href="library/tempfile.html#index-3">[1]</a>
</li>
      <li><a href="library/os.html#os.TMP_MAX">TMP_MAX (in module os)</a>
</li>
      <li><a href="library/os.html#index-18">TMPDIR</a>, <a href="library/tempfile.html#index-1">[1]</a>
</li>
      <li><a href="library/os.html#os.tmpfile">tmpfile() (in module os)</a>
</li>
      <li><a href="library/os.html#os.tmpnam">tmpnam() (in module os)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_eng_string">to_eng_string() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.to_eng_string">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Decimal.to_integral">to_integral() (decimal.Decimal method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_integral_exact">to_integral_exact() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.to_integral_exact">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Decimal.to_integral_value">to_integral_value() (decimal.Decimal method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.to_sci_string">to_sci_string() (decimal.Context method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.to_splittable">to_splittable() (email.charset.Charset method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.ToASCII">ToASCII() (in module encodings.idna)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.tobuf">tobuf() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.tobytes">tobytes() (memoryview method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.tochild">tochild (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.today">today() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.today">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.tofile">tofile() (array.array method)</a>
</li>
      <li><a href="library/token.html#token.tok_name">tok_name (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">token</a>

      <ul>
        <li><a href="library/token.html#module-token">(module)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.token">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tokenize.html#tokenize.TokenError">TokenError</a>
</li>
      <li><a href="library/tokenize.html#module-tokenize">tokenize (module)</a>
</li>
      <li><a href="library/tokenize.html#tokenize.tokenize">tokenize() (in module tokenize)</a>
</li>
      <li><a href="library/array.html#array.array.tolist">tolist() (array.array method)</a>

      <ul>
        <li><a href="library/stdtypes.html#memoryview.tolist">(memoryview method)</a>
</li>
        <li><a href="library/parser.html#parser.ST.tolist">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/audioop.html#audioop.tomono">tomono() (in module audioop)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.toordinal">toordinal() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.toordinal">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.top">top() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/poplib.html#poplib.POP3.top">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.top_panel">top_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.toprettyxml">toprettyxml() (xml.dom.minidom.Node method)</a>
</li>
      <li><a href="library/audioop.html#audioop.tostereo">tostereo() (in module audioop)</a>
</li>
      <li><a href="library/array.html#array.array.tostring">tostring() (array.array method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.tostring">(in module xml.etree.ElementTree)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.tostringlist">tostringlist() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.total_changes">total_changes (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/functools.html#functools.total_ordering">total_ordering() (in module functools)</a>
</li>
      <li><a href="library/datetime.html#datetime.timedelta.total_seconds">total_seconds() (datetime.timedelta method)</a>
</li>
      <li><a href="library/parser.html#parser.ST.totuple">totuple() (parser.ST method)</a>
</li>
      <li><a href="library/macostools.html#macostools.touched">touched() (in module macostools)</a>
</li>
      <li><a href="library/curses.html#curses.window.touchline">touchline() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.touchwin">touchwin() (curses.window method)</a>
</li>
      <li><a href="library/array.html#array.array.tounicode">tounicode() (array.array method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.ToUnicode">ToUnicode() (in module encodings.idna)</a>
</li>
      <li><a href="library/imageop.html#imageop.tovideo">tovideo() (in module imageop)</a>
</li>
      <li><a href="library/turtle.html#turtle.towards">towards() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.toxml">toxml() (xml.dom.minidom.Node method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_mapping">tp_as_mapping (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_number">tp_as_number (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.tp_as_sequence">tp_as_sequence (C member)</a>
</li>
      <li><a href="library/curses.html#curses.tparm">tparm() (in module curses)</a>
</li>
      <li>
    trace

      <ul>
        <li><a href="reference/datamodel.html#index-67">stack</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.Trace">Trace (class in trace)</a>
</li>
      <li><a href="library/trace.html#module-trace">trace (module)</a>
</li>
      <li>
    trace command line option

      <ul>
        <li><a href="library/trace.html#cmdoption-trace-help">--help</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-ignore-dir">--ignore-dir=&lt;dir&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-ignore-module">--ignore-module=&lt;mod&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-version">--version</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-coverdir">-C, --coverdir=&lt;dir&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-no-report">-R, --no-report</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-trackcalls">-T, --trackcalls</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-c">-c, --count</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-f">-f, --file=&lt;file&gt;</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-g">-g, --timing</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-l">-l, --listfuncs</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-m">-m, --missing</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-r">-r, --report</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-s">-s, --summary</a>
</li>
        <li><a href="library/trace.html#cmdoption-trace-t">-t, --trace</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#index-13">trace function</a>, <a href="library/sys.html#index-3">[1]</a>, <a href="library/threading.html#index-1">[2]</a>
</li>
      <li><a href="library/inspect.html#inspect.trace">trace() (in module inspect)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.trace_dispatch">trace_dispatch() (bdb.Bdb method)</a>
</li>
      <li>
    traceback

      <ul>
        <li><a href="library/sys.html#index-1">object</a>, <a href="library/traceback.html#index-0">[1]</a>, <a href="reference/compound_stmts.html#index-11">[2]</a>, <a href="reference/datamodel.html#index-67">[3]</a>, <a href="reference/simple_stmts.html#index-32">[4]</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#module-traceback">traceback (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.traceback_limit">traceback_limit (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/sys.html#sys.tracebacklimit">tracebacklimit (in module sys)</a>
</li>
      <li>
    tracebacks

      <ul>
        <li><a href="library/cgitb.html#index-0">in CGI scripts</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.TracebackType">TracebackType (in module types)</a>
</li>
      <li><a href="library/turtle.html#turtle.tracer">tracer() (in module turtle)</a>, <a href="library/turtle.html#turtle.tracer">[1]</a>
</li>
      <li>
    trailing

      <ul>
        <li><a href="reference/expressions.html#index-78">comma</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.transfercmd">transfercmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/test.html#test.support.TransientResource">TransientResource (class in test.support)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.translate">translate() (in module fnmatch)</a>

      <ul>
        <li><a href="library/string.html#string.translate">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#str.translate">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.translation">translation() (in module gettext)</a>
</li>
      <li><a href="library/ssl.html#index-1">Transport Layer Security</a>
</li>
      <li><a href="c-api/gcsupport.html#c.traverseproc">traverseproc (C type)</a>
</li>
      <li><a href="library/tix.html#Tix.Tree">Tree (class in Tix)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder">TreeBuilder (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview">Treeview (class in ttk)</a>
</li>
      <li><a href="library/random.html#random.triangular">triangular() (in module random)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">triple-quoted string</a>, <a href="glossary.html#term-triple-quoted-string"><strong>[1]</strong></a>
</li>
      <li><a href="library/stdtypes.html#index-43">True</a>, <a href="library/stdtypes.html#index-6">[1]</a>, <a href="reference/datamodel.html#index-13">[2]</a>
</li>
      <li><a href="library/stdtypes.html#index-5">true</a>
</li>
      <li><a href="library/constants.html#True">True (built-in variable)</a>
</li>
      <li><a href="library/operator.html#operator.truediv">truediv() (in module operator)</a>
</li>
      <li><a href="library/math.html#math.trunc">trunc() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/stdtypes.html#file.truncate">truncate() (file method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.truncate">(io.IOBase method)</a>
</li>
      </ul></li>
      <li>
    truth

      <ul>
        <li><a href="library/stdtypes.html#index-2">value</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.truth">truth() (in module operator)</a>
</li>
      <li>
    try

      <ul>
        <li><a href="library/exceptions.html#index-0">statement</a>, <a href="reference/compound_stmts.html#index-10">[1]</a>, <a href="reference/datamodel.html#index-68">[2]</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#index-0">ttk</a>

      <ul>
        <li><a href="library/ttk.html#module-ttk">(module)</a>
</li>
      </ul></li>
      <li><a href="library/imgfile.html#imgfile.ttob">ttob() (in module imgfile)</a>
</li>
      <li>
    tty

      <ul>
        <li><a href="library/termios.html#index-0">I/O control</a>
</li>
      </ul></li>
      <li><a href="library/tty.html#module-tty">tty (module)</a>
</li>
      <li><a href="library/os.html#os.ttyname">ttyname() (in module os)</a>
</li>
      <li>
    tuple

      <ul>
        <li><a href="c-api/list.html#index-2">built-in function</a>, <a href="c-api/sequence.html#index-1">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-12">display</a>
</li>
        <li><a href="reference/datamodel.html#index-24">empty</a>, <a href="reference/expressions.html#index-11">[1]</a>
</li>
        <li><a href="c-api/tuple.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-24">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>, <a href="reference/expressions.html#index-77">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-24">singleton</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#tuple">tuple() (built-in function)</a>
</li>
      <li><a href="library/parser.html#parser.tuple2st">tuple2st() (in module parser)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-tuple_params">tuple_params (2to3 fixer)</a>
</li>
      <li><a href="c-api/tuple.html#index-1">TupleType (in module types)</a>, <a href="library/types.html#types.TupleType">[1]</a>
</li>
      <li><a href="library/fpectl.html#fpectl.turnoff_sigfpe">turnoff_sigfpe() (in module fpectl)</a>
</li>
      <li><a href="library/fpectl.html#fpectl.turnon_sigfpe">turnon_sigfpe() (in module fpectl)</a>
</li>
      <li><a href="library/turtle.html#turtle.Turtle">Turtle (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#module-turtle">turtle (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.turtles">turtles() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.TurtleScreen">TurtleScreen (class in turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.turtlesize">turtlesize() (in module turtle)</a>
</li>
      <li><a href="library/compiler.html#index-0">Tutt, Bill</a>
</li>
      <li><a href="reference/datamodel.html#index-4">type</a>, <a href="glossary.html#term-type"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/functions.html#index-0">Boolean</a>
</li>
        <li><a href="c-api/object.html#index-10">built-in function</a>, <a href="library/stdtypes.html#index-42">[1]</a>, <a href="library/types.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-1">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-4">data</a>
</li>
        <li><a href="reference/datamodel.html#index-4">hierarchy</a>
</li>
        <li><a href="reference/expressions.html#index-9">immutable data</a>
</li>
        <li><a href="c-api/intro.html#index-5">object</a>, <a href="c-api/type.html#index-0">[1]</a>, <a href="library/functions.html#index-7">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">operations on dictionary</a>
</li>
        <li><a href="library/stdtypes.html#index-30">operations on list</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#type">type (built-in class)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Type">Type (class in aetypes)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.type">type (optparse.Option attribute)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.type">(socket.socket attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.type">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">type of an object</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.TYPE_CHECKER">TYPE_CHECKER (optparse.Option attribute)</a>
</li>
      <li><a href="library/curses.html#curses.typeahead">typeahead() (in module curses)</a>
</li>
      <li><a href="library/array.html#array.array.typecode">typecode (array.array attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.TYPED_ACTIONS">TYPED_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators.typed_subpart_iterator">typed_subpart_iterator() (in module email.iterators)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.TypeError">TypeError</a>

      <ul>
        <li><a href="reference/expressions.html#index-51">exception</a>
</li>
      </ul></li>
      <li>
    types

      <ul>
        <li><a href="library/stdtypes.html#index-0">built-in</a>
</li>
        <li><a href="library/stdtypes.html#index-42">module</a>
</li>
        <li><a href="library/stdtypes.html#index-29">mutable sequence</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations on integer</a>
</li>
        <li><a href="library/stdtypes.html#index-32">operations on mapping</a>
</li>
        <li><a href="library/stdtypes.html#index-16">operations on numeric</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operations on sequence</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-types">types (2to3 fixer)</a>

      <ul>
        <li><a href="library/types.html#module-types">(module)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.TYPES">TYPES (optparse.Option attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-59">types, internal</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.types_map">types_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.types_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes.types_map_inv">types_map_inv (mimetypes.MimeTypes attribute)</a>
</li>
      <li><a href="c-api/type.html#index-1">TypeType (in module types)</a>, <a href="library/types.html#types.TypeType">[1]</a>
</li>
      <li><a href="library/time.html#index-10">TZ</a>, <a href="library/time.html#index-11">[1]</a>, <a href="library/time.html#index-12">[2]</a>, <a href="library/time.html#index-13">[3]</a>, <a href="library/time.html#index-14">[4]</a>, <a href="library/time.html#index-15">[5]</a>
</li>
      <li><a href="library/datetime.html#datetime.tzinfo">tzinfo (class in datetime)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.tzinfo">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.tzinfo">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.tzname">tzname (in module time)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.tzname">tzname() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.tzname">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.tzname">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.tzset">tzset() (in module time)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="U">U</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.U">U (in module re)</a>
</li>
      <li><a href="library/aifc.html#index-1">u-LAW</a>, <a href="library/audioop.html#index-0">[1]</a>, <a href="library/sndhdr.html#index-0">[2]</a>, <a href="library/sunaudio.html#index-0">[3]</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.ucd_3_2_0">ucd_3_2_0 (in module unicodedata)</a>
</li>
      <li><a href="library/select.html#select.kevent.udata">udata (select.kevent attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.UDPServer">UDPServer (class in SocketServer)</a>
</li>
      <li><a href="library/stat.html#stat.UF_APPEND">UF_APPEND (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_COMPRESSED">UF_COMPRESSED (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_HIDDEN">UF_HIDDEN (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_IMMUTABLE">UF_IMMUTABLE (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_NODUMP">UF_NODUMP (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_NOUNLINK">UF_NOUNLINK (in module stat)</a>
</li>
      <li><a href="library/stat.html#stat.UF_OPAQUE">UF_OPAQUE (in module stat)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ugettext">ugettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ugettext">(gettext.NullTranslations method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.uid">uid (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.uid">uid() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.uidl">uidl() (poplib.POP3 method)</a>
</li>
      <li><a href="library/audioop.html#audioop.ulaw2lin">ulaw2lin() (in module audioop)</a>
</li>
      <li><a href="c-api/long.html#index-4">ULONG_MAX</a>
</li>
      <li><a href="library/os.html#os.umask">umask() (in module os)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.uname">uname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/os.html#os.uname">uname() (in module os)</a>

      <ul>
        <li><a href="library/platform.html#platform.uname">(in module platform)</a>
</li>
      </ul></li>
      <li>
    unary

      <ul>
        <li><a href="reference/expressions.html#index-47">arithmetic operation</a>
</li>
        <li><a href="reference/expressions.html#index-47">bitwise operation</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-UNARY_CONVERT">UNARY_CONVERT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_INVERT">UNARY_INVERT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_NEGATIVE">UNARY_NEGATIVE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_NOT">UNARY_NOT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-UNARY_POSITIVE">UNARY_POSITIVE (opcode)</a>
</li>
      <li>
    unbinding

      <ul>
        <li><a href="reference/simple_stmts.html#index-19">name</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnboundLocalError">UnboundLocalError</a>, <a href="reference/executionmodel.html#index-8">[1]</a>
</li>
      <li><a href="library/types.html#types.UnboundMethodType">UnboundMethodType (in module types)</a>
</li>
      <li><a href="library/functions.html#index-4">unbuffered I/O</a>
</li>
      <li>
    UNC paths

      <ul>
        <li><a href="library/os.html#index-14">and os.makedirs()</a>
</li>
      </ul></li>
      <li><a href="library/zlib.html#zlib.Decompress.unconsumed_tail">unconsumed_tail (zlib.Decompress attribute)</a>
</li>
      <li><a href="library/curses.html#curses.unctrl">unctrl() (in module curses)</a>

      <ul>
        <li><a href="library/curses.ascii.html#curses.ascii.unctrl">(in module curses.ascii)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.undefine_macro">undefine_macro() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Underflow">Underflow (class in decimal)</a>
</li>
      <li><a href="library/turtle.html#turtle.undo">undo() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.undobufferentries">undobufferentries() (in module turtle)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.undoc_header">undoc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.unescape">unescape() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/doctest.html#doctest.UnexpectedException">UnexpectedException</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.unexpectedSuccesses">unexpectedSuccesses (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.unfreeze_form">unfreeze_form() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.ungetch">ungetch() (in module curses)</a>

      <ul>
        <li><a href="library/msvcrt.html#msvcrt.ungetch">(in module msvcrt)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.ungetmouse">ungetmouse() (in module curses)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ungettext">ungettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ungettext">(gettext.NullTranslations method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.ungetwch">ungetwch() (in module msvcrt)</a>
</li>
      <li><a href="library/binascii.html#binascii.unhexlify">unhexlify() (in module binascii)</a>
</li>
      <li>
    unichr

      <ul>
        <li><a href="reference/datamodel.html#index-23">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#unichr">unichr() (built-in function)</a>
</li>
      <li><a href="library/codecs.html#index-0">Unicode</a>, <a href="library/unicodedata.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>

      <ul>
        <li><a href="library/unicodedata.html#index-0">database</a>
</li>
        <li><a href="library/stdtypes.html#index-21">object</a>
</li>
      </ul></li>
      <li>
    unicode

      <ul>
        <li><a href="c-api/object.html#index-5">built-in function</a>, <a href="reference/datamodel.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-83">[2]</a>, <a href="tutorial/introduction.html#index-0">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">object</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-unicode">unicode (2to3 fixer)</a>
</li>
      <li><a href="library/re.html#re.UNICODE">UNICODE (in module re)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">Unicode Consortium</a>
</li>
      <li><a href="library/functions.html#unicode">unicode() (built-in function)</a>
</li>
      <li><a href="library/unicodedata.html#module-unicodedata">unicodedata (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeDecodeError">UnicodeDecodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeEncodeError">UnicodeEncodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError">UnicodeError</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeTranslateError">UnicodeTranslateError</a>
</li>
      <li><a href="library/types.html#types.UnicodeType">UnicodeType (in module types)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeWarning">UnicodeWarning</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.unidata_version">unidata_version (in module unicodedata)</a>
</li>
      <li><a href="library/difflib.html#difflib.unified_diff">unified_diff() (in module difflib)</a>
</li>
      <li><a href="library/random.html#random.uniform">uniform() (in module random)</a>
</li>
      <li><a href="library/httplib.html#httplib.UnimplementedFileMode">UnimplementedFileMode</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager.uninstall">uninstall() (imputil.ImportManager method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Union">Union (class in ctypes)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.union">union() (frozenset method)</a>
</li>
      <li><a href="library/unittest.html#module-unittest">unittest (module)</a>
</li>
      <li>
    unittest command line option

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-b">-b, --buffer</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-c">-c, --catch</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-f">-f, --failfast</a>
</li>
      </ul></li>
      <li>
    unittest-discover command line option

      <ul>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-p">-p, --pattern pattern</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-s">-s, --start-directory directory</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-t">-t, --top-level-directory directory</a>
</li>
        <li><a href="library/unittest.html#cmdoption-unittest-discover-v">-v, --verbose</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-universal-newlines"><strong>universal newlines</strong></a>

      <ul>
        <li><a href="whatsnew/2.3.html#index-8">What&#39;s new</a>, <a href="whatsnew/2.4.html#index-7">[1]</a>, <a href="whatsnew/2.5.html#index-18">[2]</a>, <a href="whatsnew/2.6.html#index-13">[3]</a>
</li>
        <li><a href="library/bz2.html#index-0">bz2.BZ2File class</a>
</li>
        <li><a href="library/stdtypes.html#index-36">file.newlines attribute</a>
</li>
        <li><a href="library/io.html#index-2">io.IncrementalNewlineDecoder class</a>
</li>
        <li><a href="library/io.html#index-1">io.TextIOWrapper class</a>
</li>
        <li><a href="library/io.html#index-0">open() (in module io)</a>
</li>
        <li><a href="library/functions.html#index-5">open() built-in function</a>
</li>
        <li><a href="library/stdtypes.html#index-24">str.splitlines method</a>
</li>
        <li><a href="library/subprocess.html#index-1">subprocess module</a>
</li>
        <li><a href="library/zipfile.html#index-0">zipfile.ZipFile.open method</a>
</li>
      </ul></li>
      <li><a href="reference/toplevel_components.html#index-4">UNIX</a>

      <ul>
        <li><a href="library/fcntl.html#index-0">I/O control</a>
</li>
        <li><a href="library/fcntl.html#index-0">file control</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.UnixDatagramServer">UnixDatagramServer (class in SocketServer)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.unixfrom">unixfrom (rfc822.Message attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.UnixMailbox">UnixMailbox (class in mailbox)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.UnixStreamServer">UnixStreamServer (class in SocketServer)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Unknown">Unknown (class in aetypes)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_charref">unknown_charref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.unknown_decl">unknown_decl() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_endtag">unknown_endtag() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_entityref">unknown_entityref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.unknown_open">unknown_open() (urllib2.BaseHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.UnknownHandler.unknown_open">(urllib2.UnknownHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.unknown_starttag">unknown_starttag() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.UnknownHandler">UnknownHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.UnknownProtocol">UnknownProtocol</a>
</li>
      <li><a href="library/httplib.html#httplib.UnknownTransferEncoding">UnknownTransferEncoding</a>
</li>
      <li><a href="library/os.html#os.unlink">unlink() (in module os)</a>

      <ul>
        <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.unlink">(xml.dom.minidom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Babyl.unlock">unlock() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.unlock">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.unlock">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.unlock">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.unlock">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.unlock">(mailbox.mbox method)</a>
</li>
        <li><a href="library/mutex.html#mutex.mutex.unlock">(mutex.mutex method)</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#mimify.unmimify">unmimify() (in module mimify)</a>
</li>
      <li><a href="library/aepack.html#aepack.unpack">unpack() (in module aepack)</a>

      <ul>
        <li><a href="library/struct.html#struct.unpack">(in module struct)</a>
</li>
        <li><a href="library/struct.html#struct.Struct.unpack">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_array">unpack_array() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_bytes">unpack_bytes() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_double">unpack_double() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_farray">unpack_farray() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_float">unpack_float() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_fopaque">unpack_fopaque() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/struct.html#struct.unpack_from">unpack_from() (in module struct)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.unpack_from">(struct.Struct method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_fstring">unpack_fstring() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_list">unpack_list() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_opaque">unpack_opaque() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/dis.html#opcode-UNPACK_SEQUENCE">UNPACK_SEQUENCE (opcode)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.unpack_string">unpack_string() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker">Unpacker (class in xdrlib)</a>
</li>
      <li><a href="library/aetools.html#aetools.unpackevent">unpackevent() (in module aetools)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler.unparsedEntityDecl">unparsedEntityDecl() (xml.sax.handler.DTDHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler">UnparsedEntityDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pickle.html#pickle.Unpickler">Unpickler (class in pickle)</a>
</li>
      <li><a href="library/pickle.html#pickle.UnpicklingError">UnpicklingError</a>
</li>
      <li><a href="library/fl.html#fl.unqdevice">unqdevice() (in module fl)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.unquote">unquote() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.unquote">(in module rfc822)</a>
</li>
        <li><a href="library/urllib.html#urllib.unquote">(in module urllib)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib.unquote_plus">unquote_plus() (in module urllib)</a>
</li>
      <li><a href="reference/datamodel.html#index-2">unreachable object</a>
</li>
      <li><a href="distutils/apiref.html#distutils.text_file.TextFile.unreadline">unreadline() (distutils.text_file.TextFile method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-17">unrecognized escape sequence</a>
</li>
      <li><a href="library/select.html#select.epoll.unregister">unregister() (select.epoll method)</a>

      <ul>
        <li><a href="library/select.html#select.poll.unregister">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#shutil.unregister_archive_format">unregister_archive_format() (in module shutil)</a>
</li>
      <li><a href="library/csv.html#csv.unregister_dialect">unregister_dialect() (in module csv)</a>
</li>
      <li><a href="library/test.html#test.support.EnvironmentVarGuard.unset">unset() (test.support.EnvironmentVarGuard method)</a>
</li>
      <li><a href="library/os.html#os.unsetenv">unsetenv() (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.unsubscribe">unsubscribe() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/io.html#io.UnsupportedOperation">UnsupportedOperation</a>
</li>
      <li><a href="library/tokenize.html#tokenize.untokenize">untokenize() (in module tokenize)</a>
</li>
      <li><a href="library/curses.html#curses.window.untouchwin">untouchwin() (curses.window method)</a>
</li>
      <li><a href="library/zlib.html#zlib.Decompress.unused_data">unused_data (zlib.Decompress attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.unwrap">unwrap() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.up">up() (in module turtle)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.update">update() (collections.Counter method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.update">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.update">(frozenset method)</a>
</li>
        <li><a href="library/hashlib.html#hashlib.hash.update">(hashlib.hash method)</a>
</li>
        <li><a href="library/hmac.html#hmac.HMAC.update">(hmac.HMAC method)</a>
</li>
        <li><a href="library/turtle.html#turtle.update">(in module turtle)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.update">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.update">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.update">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.update">(sha.sha method)</a>
</li>
        <li><a href="library/trace.html#trace.CoverageResults.update">(trace.CoverageResults method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.update_panels">update_panels() (in module curses.panel)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.update_visible">update_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/functools.html#functools.update_wrapper">update_wrapper() (in module functools)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.updatescrollbars">updatescrollbars() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/string.html#string.upper">upper() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.upper">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.uppercase">uppercase (in module string)</a>
</li>
      <li><a href="library/os.html#os.urandom">urandom() (in module os)</a>
</li>
      <li><a href="library/basehttpserver.html#index-0">URL</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/robotparser.html#index-0">[2]</a>, <a href="library/urllib.html#index-0">[3]</a>, <a href="library/urlparse.html#index-0">[4]</a>

      <ul>
        <li><a href="library/urlparse.html#index-0">parsing</a>
</li>
        <li><a href="library/urlparse.html#index-0">relative</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.url">url (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.url2pathname">url2pathname() (in module urllib)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlcleanup">urlcleanup() (in module urllib)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urldefrag">urldefrag() (in module urlparse)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlencode">urlencode() (in module urllib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.URLError">URLError</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urljoin">urljoin() (in module urlparse)</a>
</li>
      <li>
    urllib

      <ul>
        <li><a href="library/httplib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-urllib">urllib (2to3 fixer)</a>

      <ul>
        <li><a href="library/urllib.html#module-urllib">(module)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#module-urllib2">urllib2 (module)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlopen">urlopen() (in module urllib)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.urlopen">(in module urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/urllib.html#urllib.URLopener">URLopener (class in urllib)</a>
</li>
      <li>
    urlparse

      <ul>
        <li><a href="library/urllib.html#index-11">module</a>
</li>
      </ul></li>
      <li><a href="library/urlparse.html#module-urlparse">urlparse (module)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlparse">urlparse() (in module urlparse)</a>
</li>
      <li><a href="library/urllib.html#urllib.urlretrieve">urlretrieve() (in module urllib)</a>
</li>
      <li><a href="library/base64.html#base64.urlsafe_b64decode">urlsafe_b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.urlsafe_b64encode">urlsafe_b64encode() (in module base64)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlsplit">urlsplit() (in module urlparse)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlunparse">urlunparse() (in module urlparse)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.urlunsplit">urlunsplit() (in module urlparse)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.urn">urn (uuid.UUID attribute)</a>
</li>
      <li><a href="library/curses.html#curses.use_default_colors">use_default_colors() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.use_env">use_env() (in module curses)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.use_rawinput">use_rawinput (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.UseForeignDTD">UseForeignDTD() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/getpass.html#index-1">USER</a>
</li>
      <li>
    user

      <ul>
        <li><a href="library/user.html#index-0">configuration file</a>
</li>
        <li><a href="library/os.html#index-0">effective id</a>
</li>
        <li><a href="library/os.html#index-6">id</a>
</li>
        <li><a href="library/os.html#index-8">id, setting</a>
</li>
      </ul></li>
      <li><a href="library/user.html#module-user">user (module)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.user">user() (poplib.POP3 method)</a>
</li>
      <li>
    user-defined

      <ul>
        <li><a href="reference/datamodel.html#index-36">function</a>
</li>
        <li><a href="reference/expressions.html#index-42">function call</a>
</li>
        <li><a href="reference/datamodel.html#index-38">method</a>
</li>
      </ul></li>
      <li>
    user-defined function

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">object</a>, <a href="reference/datamodel.html#index-36">[1]</a>, <a href="reference/expressions.html#index-42">[2]</a>
</li>
      </ul></li>
      <li>
    user-defined method

      <ul>
        <li><a href="reference/datamodel.html#index-38">object</a>
</li>
      </ul></li>
      <li><a href="whatsnew/2.7.html#index-9">USER_BASE</a>

      <ul>
        <li><a href="library/site.html#site.USER_BASE">(in module site)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.user_call">user_call() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_exception">user_exception() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_line">user_line() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.user_return">user_return() (bdb.Bdb method)</a>
</li>
      <li><a href="library/site.html#site.USER_SITE">USER_SITE (in module site)</a>
</li>
      <li>
    usercustomize

      <ul>
        <li><a href="library/site.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="library/userdict.html#UserDict.UserDict">UserDict (class in UserDict)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserDict">(module)</a>
</li>
      </ul></li>
      <li><a href="library/userdict.html#UserList.UserList">UserList (class in UserList)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserList">(module)</a>
</li>
      </ul></li>
      <li><a href="library/getpass.html#index-3">USERNAME</a>
</li>
      <li><a href="install/index.html#index-6">USERPROFILE</a>, <a href="library/os.path.html#index-4">[1]</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.userptr">userptr() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/userdict.html#UserString.UserString">UserString (class in UserString)</a>

      <ul>
        <li><a href="library/userdict.html#module-UserString">(module)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UserWarning">UserWarning</a>
</li>
      <li><a href="library/tarfile.html#tarfile.USTAR_FORMAT">USTAR_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/time.html#index-5">UTC</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcfromtimestamp">utcfromtimestamp() (datetime.datetime class method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcnow">utcnow() (datetime.datetime class method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.utcoffset">utcoffset() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.utcoffset">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.utcoffset">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.datetime.utctimetuple">utctimetuple() (datetime.datetime method)</a>
</li>
      <li><a href="library/os.html#os.utime">utime() (in module os)</a>
</li>
      <li>
    uu

      <ul>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/uu.html#module-uu">uu (module)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID">UUID (class in uuid)</a>
</li>
      <li><a href="library/uuid.html#module-uuid">uuid (module)</a>
</li>
      <li><a href="library/uuid.html#index-2">uuid1</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid1">uuid1() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-3">uuid3</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid3">uuid3() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-4">uuid4</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid4">uuid4() (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#index-5">uuid5</a>
</li>
      <li><a href="library/uuid.html#uuid.uuid5">uuid5() (in module uuid)</a>
</li>
      <li><a href="library/msilib.html#msilib.UuidCreate">UuidCreate() (in module msilib)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="V">V</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/wsgiref.html#wsgiref.validate.validator">validator() (in module wsgiref.validate)</a>
</li>
      <li>
    value

      <ul>
        <li><a href="reference/compound_stmts.html#index-20">default parameter</a>
</li>
        <li><a href="library/stdtypes.html#index-2">truth</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.Morsel.value">value (Cookie.Morsel attribute)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.value">(cookielib.Cookie attribute)</a>
</li>
        <li><a href="library/ctypes.html#ctypes._SimpleCData.value">(ctypes._SimpleCData attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Attr.value">(xml.dom.Attr attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">value of an object</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Value">Value() (in module multiprocessing)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.Value">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Value">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.value_decode">value_decode() (Cookie.BaseCookie method)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.value_encode">value_encode() (Cookie.BaseCookie method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ValueError">ValueError</a>

      <ul>
        <li><a href="reference/expressions.html#index-59">exception</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary.valuerefs">valuerefs() (weakref.WeakValueDictionary method)</a>
</li>
      <li>
    values

      <ul>
        <li><a href="library/stdtypes.html#index-43">Boolean</a>
</li>
        <li><a href="reference/simple_stmts.html#index-2">writing</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#dict.values">values() (dict method)</a>

      <ul>
        <li><a href="library/email.message.html#email.message.Message.values">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.values">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.ValuesView">ValuesView (class in collections)</a>
</li>
      <li>
    variable

      <ul>
        <li><a href="reference/executionmodel.html#index-7">free</a>, <a href="reference/simple_stmts.html#index-20">[1]</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.variant">variant (uuid.UUID attribute)</a>
</li>
      <li><a href="library/gl.html#gl.varray">varray() (in module gl)</a>
</li>
      <li><a href="library/functions.html#vars">vars() (built-in function)</a>
</li>
      <li><a href="library/token.html#token.VBAR">VBAR (in module token)</a>
</li>
      <li><a href="library/scrolledtext.html#ScrolledText.ScrolledText.vbar">vbar (ScrolledText.ScrolledText attribute)</a>
</li>
      <li><a href="library/token.html#token.VBAREQUAL">VBAREQUAL (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.Vec2D">Vec2D (class in turtle)</a>
</li>
      <li><a href="library/re.html#re.VERBOSE">VERBOSE (in module re)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.verbose">verbose (in module tabnanny)</a>

      <ul>
        <li><a href="library/test.html#test.support.verbose">(in module test.support)</a>
</li>
      </ul></li>
      <li><a href="library/smtplib.html#smtplib.SMTP.verify">verify() (smtplib.SMTP method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/ssl.html#ssl.VERIFY_CRL_CHECK_CHAIN">VERIFY_CRL_CHECK_CHAIN (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_CRL_CHECK_LEAF">VERIFY_CRL_CHECK_LEAF (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_DEFAULT">VERIFY_DEFAULT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.verify_flags">verify_flags (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.verify_mode">verify_mode (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.verify_request">verify_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_X509_STRICT">VERIFY_X509_STRICT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.VERIFY_X509_TRUSTED_FIRST">VERIFY_X509_TRUSTED_FIRST (in module ssl)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.version">version (cookielib.Cookie attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPResponse.version">(httplib.HTTPResponse attribute)</a>
</li>
        <li><a href="library/curses.html#curses.version">(in module curses)</a>
</li>
        <li><a href="library/marshal.html#marshal.version">(in module marshal)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.version">(in module sqlite3)</a>
</li>
        <li><a href="c-api/init.html#index-5">(in module sys)</a>, <a href="c-api/init.html#index-8">[1]</a>, <a href="c-api/init.html#index-9">[2]</a>, <a href="library/sys.html#sys.version">[3]</a>
</li>
        <li><a href="library/urllib.html#urllib.URLopener.version">(urllib.URLopener attribute)</a>
</li>
        <li><a href="library/uuid.html#uuid.UUID.version">(uuid.UUID attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ensurepip.html#ensurepip.version">version() (in module ensurepip)</a>

      <ul>
        <li><a href="library/platform.html#platform.version">(in module platform)</a>
</li>
        <li><a href="library/ssl.html#ssl.SSLSocket.version">(ssl.SSLSocket method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.version_info">version_info (in module sqlite3)</a>

      <ul>
        <li><a href="library/sys.html#sys.version_info">(in module sys)</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.version_string">version_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.vformat">vformat() (string.Formatter method)</a>
</li>
      <li><a href="library/undoc.html#module-videoreader">videoreader (module)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewitems">viewitems() (dict method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewkeys">viewkeys() (dict method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.viewvalues">viewvalues() (dict method)</a>
</li>
      <li><a href="glossary.html#term-virtual-environment"><strong>virtual environment</strong></a>
</li>
      <li><a href="glossary.html#term-virtual-machine"><strong>virtual machine</strong></a>
</li>
      <li><a href="library/ast.html#ast.NodeVisitor.visit">visit() (ast.NodeVisitor method)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.visitproc">visitproc (C type)</a>
</li>
      <li><a href="library/curses.html#curses.window.vline">vline() (curses.window method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.VMSError">VMSError</a>
</li>
      <li><a href="library/gl.html#gl.vnarray">vnarray() (in module gl)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.voidcmd">voidcmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.volume">volume (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/random.html#random.vonmisesvariate">vonmisesvariate() (in module random)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="W">W</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/undoc.html#module-W">W (module)</a>
</li>
      <li><a href="library/os.html#os.W_OK">W_OK (in module os)</a>
</li>
      <li><a href="library/os.html#os.wait">wait() (in module os)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.wait">(multiprocessing.pool.AsyncResult method)</a>
</li>
        <li><a href="library/popen2.html#popen2.Popen3.wait">(popen2.Popen3 method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.wait">(subprocess.Popen method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.wait">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.wait">(threading.Event method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.wait3">wait3() (in module os)</a>
</li>
      <li><a href="library/os.html#os.wait4">wait4() (in module os)</a>
</li>
      <li><a href="library/os.html#os.waitpid">waitpid() (in module os)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.walk">walk() (email.message.Message method)</a>

      <ul>
        <li><a href="library/ast.html#ast.walk">(in module ast)</a>
</li>
        <li><a href="library/compiler.html#compiler.walk">(in module compiler)</a>
</li>
        <li><a href="library/compiler.html#compiler.visitor.walk">(in module compiler.visitor)</a>
</li>
        <li><a href="library/os.html#os.walk">(in module os)</a>
</li>
        <li><a href="library/os.path.html#os.path.walk">(in module os.path)</a>
</li>
      </ul></li>
      <li><a href="library/pkgutil.html#pkgutil.walk_packages">walk_packages() (in module pkgutil)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.want">want (doctest.Example attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.warn">warn() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.warn">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/warnings.html#warnings.warn">(in module warnings)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#warnings.warn_explicit">warn_explicit() (in module warnings)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.Warning">Warning</a>
</li>
      <li><a href="library/logging.html#logging.warning">warning() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.warning">(logging.Logger method)</a>
</li>
        <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.warning">(xml.sax.handler.ErrorHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#index-0">warnings</a>

      <ul>
        <li><a href="library/warnings.html#module-warnings">(module)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.WarningsRecorder">WarningsRecorder (class in test.support)</a>
</li>
      <li><a href="library/sys.html#sys.warnoptions">warnoptions (in module sys)</a>
</li>
      <li><a href="library/warnings.html#warnings.warnpy3k">warnpy3k() (in module warnings)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.wasSuccessful">wasSuccessful() (unittest.TestResult method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.WatchedFileHandler">WatchedFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/wave.html#module-wave">wave (module)</a>
</li>
      <li><a href="library/os.html#os.WCONTINUED">WCONTINUED (in module os)</a>
</li>
      <li><a href="library/os.html#os.WCOREDUMP">WCOREDUMP() (in module os)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary">WeakKeyDictionary (class in weakref)</a>
</li>
      <li><a href="library/weakref.html#module-weakref">weakref (module)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakSet">WeakSet (class in weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary">WeakValueDictionary (class in weakref)</a>
</li>
      <li><a href="library/webbrowser.html#module-webbrowser">webbrowser (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.weekday">weekday() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.weekday">(datetime.datetime method)</a>
</li>
        <li><a href="library/calendar.html#calendar.weekday">(in module calendar)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.weekheader">weekheader() (in module calendar)</a>
</li>
      <li><a href="library/random.html#random.weibullvariate">weibullvariate() (in module random)</a>
</li>
      <li><a href="library/os.html#os.WEXITSTATUS">WEXITSTATUS() (in module os)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.wfile">wfile (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/imghdr.html#imghdr.what">what() (in module imghdr)</a>

      <ul>
        <li><a href="library/sndhdr.html#sndhdr.what">(in module sndhdr)</a>
</li>
      </ul></li>
      <li><a href="library/sndhdr.html#sndhdr.whathdr">whathdr() (in module sndhdr)</a>
</li>
      <li><a href="library/whichdb.html#module-whichdb">whichdb (module)</a>
</li>
      <li><a href="library/whichdb.html#whichdb.whichdb">whichdb() (in module whichdb)</a>
</li>
      <li>
    while

      <ul>
        <li><a href="library/stdtypes.html#index-2">statement</a>, <a href="reference/compound_stmts.html#index-4">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-7">whitespace</a>

      <ul>
        <li><a href="library/string.html#string.whitespace">(in module string)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.whitespace">(shlex.shlex attribute)</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex.whitespace_split">whitespace_split (shlex.shlex attribute)</a>
</li>
      <li><a href="library/random.html#random.whseed">whseed() (in module random)</a>
</li>
      <li><a href="library/random.html#random.WichmannHill">WichmannHill (class in random)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget">Widget (class in ttk)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.width">width (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.width">width() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.WIFCONTINUED">WIFCONTINUED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFEXITED">WIFEXITED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFSIGNALED">WIFSIGNALED() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WIFSTOPPED">WIFSTOPPED() (in module os)</a>
</li>
      <li><a href="library/tempfile.html#index-4">Wimp$ScrapDir</a>
</li>
      <li><a href="library/platform.html#platform.win32_ver">win32_ver() (in module platform)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WinDLL">WinDLL (class in ctypes)</a>
</li>
      <li><a href="library/tkinter.html#index-1">window manager (widgets)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.window">window() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Window">Window() (in module FrameWork)</a>
</li>
      <li><a href="library/turtle.html#turtle.window_height">window_height() (in module turtle)</a>, <a href="library/turtle.html#turtle.window_height">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.window_width">window_width() (in module turtle)</a>, <a href="library/turtle.html#turtle.window_width">[1]</a>
</li>
      <li><a href="library/framework.html#FrameWork.windowbounds">windowbounds() (in module FrameWork)</a>
</li>
      <li><a href="library/configparser.html#index-0">Windows ini file</a>
</li>
      <li><a href="library/exceptions.html#exceptions.WindowsError">WindowsError</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WinError">WinError() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.WINFUNCTYPE">WINFUNCTYPE() (in module ctypes)</a>
</li>
      <li><a href="library/select.html#index-1">WinSock</a>
</li>
      <li><a href="library/winsound.html#module-winsound">winsound (module)</a>
</li>
      <li><a href="library/sys.html#sys.winver">winver (in module sys)</a>
</li>
      <li>
    with

      <ul>
        <li><a href="reference/compound_stmts.html#index-15">statement</a>, <a href="reference/datamodel.html#index-96">[1]</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/dis.html#opcode-WITH_CLEANUP">WITH_CLEANUP (opcode)</a>
</li>
      <li><a href="library/macos.html#MacOS.WMAvailable">WMAvailable() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.WNOHANG">WNOHANG (in module os)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.wordchars">wordchars (shlex.shlex attribute)</a>
</li>
      <li><a href="library/internet.html#index-0">World Wide Web</a>, <a href="library/robotparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-0">[2]</a>, <a href="library/urlparse.html#index-0">[3]</a>
</li>
      <li><a href="library/textwrap.html#textwrap.wrap">wrap() (in module textwrap)</a>

      <ul>
        <li><a href="library/textwrap.html#textwrap.TextWrapper.wrap">(textwrap.TextWrapper method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.wrap_socket">wrap_socket() (in module ssl)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLContext.wrap_socket">(ssl.SSLContext method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.wrap_text">wrap_text() (in module distutils.fancy_getopt)</a>
</li>
      <li><a href="library/curses.html#curses.wrapper">wrapper() (in module curses)</a>
</li>
      <li><a href="library/functools.html#functools.wraps">wraps() (in module functools)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.WRITABLE">WRITABLE (in module Tkinter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.writable">writable() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.writable">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.write">write() (array.array method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.write">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.write">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/code.html#code.InteractiveInterpreter.write">(code.InteractiveInterpreter method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamWriter.write">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/email.generator.html#email.generator.Generator.write">(email.generator.Generator method)</a>
</li>
        <li><a href="library/stdtypes.html#file.write">(file method)</a>
</li>
        <li><a href="library/imgfile.html#imgfile.write">(in module imgfile)</a>
</li>
        <li><a href="library/os.html#os.write">(in module os)</a>
</li>
        <li><a href="library/turtle.html#turtle.write">(in module turtle)</a>
</li>
        <li><a href="library/io.html#io.BufferedIOBase.write">(io.BufferedIOBase method)</a>
</li>
        <li><a href="library/io.html#io.BufferedWriter.write">(io.BufferedWriter method)</a>
</li>
        <li><a href="library/io.html#io.RawIOBase.write">(io.RawIOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.write">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.write">(mmap.mmap method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.write">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.write">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write">(xml.etree.ElementTree.ElementTree method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.write">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/mmap.html#mmap.mmap.write_byte">write_byte() (mmap.mmap method)</a>
</li>
      <li><a href="library/turtle.html#turtle.write_docstringdict">write_docstringdict() (in module turtle)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.file_util.write_file">write_file() (in module distutils.file_util)</a>
</li>
      <li><a href="library/readline.html#readline.write_history_file">write_history_file() (in module readline)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">WRITE_RESTRICTED</a>
</li>
      <li><a href="library/trace.html#trace.CoverageResults.write_results">write_results() (trace.CoverageResults method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.writeall">writeall() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.writebufferproc">writebufferproc (C type)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.writeframes">writeframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.writeframes">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.writeframes">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.writeframesraw">writeframesraw() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_write.writeframesraw">(sunau.AU_write method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.writeframesraw">(wave.Wave_write method)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.DictWriter.writeheader">writeheader() (csv.DictWriter method)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.writelines">writelines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamWriter.writelines">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/stdtypes.html#file.writelines">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.writelines">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#plistlib.writePlist">writePlist() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.writePlistToResource">writePlistToResource() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.writePlistToString">writePlistToString() (in module plistlib)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.PyZipFile.writepy">writepy() (zipfile.PyZipFile method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.writer">writer (formatter.formatter attribute)</a>
</li>
      <li><a href="library/csv.html#csv.writer">writer() (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvwriter.writerow">writerow() (csv.csvwriter method)</a>
</li>
      <li><a href="library/csv.html#csv.csvwriter.writerows">writerows() (csv.csvwriter method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.writestr">writestr() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.writexml">writexml() (xml.dom.minidom.Node method)</a>
</li>
      <li>
    writing

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">values</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.WrongDocumentErr">WrongDocumentErr</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-ws_comma">ws_comma (2to3 fixer)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_file_wrapper">wsgi_file_wrapper (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_multiprocess">wsgi_multiprocess (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_multithread">wsgi_multithread (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.wsgi_run_once">wsgi_run_once (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref">wsgiref (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.handlers">wsgiref.handlers (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.headers">wsgiref.headers (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.simple_server">wsgiref.simple_server (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.util">wsgiref.util (module)</a>
</li>
      <li><a href="library/wsgiref.html#module-wsgiref.validate">wsgiref.validate (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler">WSGIRequestHandler (class in wsgiref.simple_server)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer">WSGIServer (class in wsgiref.simple_server)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.wShowWindow">wShowWindow (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/os.html#os.WSTOPSIG">WSTOPSIG() (in module os)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.wstring_at">wstring_at() (in module ctypes)</a>
</li>
      <li><a href="library/os.html#os.WTERMSIG">WTERMSIG() (in module os)</a>
</li>
      <li><a href="library/os.html#os.WUNTRACED">WUNTRACED (in module os)</a>
</li>
      <li><a href="library/internet.html#index-0">WWW</a>, <a href="library/robotparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-0">[2]</a>, <a href="library/urlparse.html#index-0">[3]</a>

      <ul>
        <li><a href="library/basehttpserver.html#index-0">server</a>, <a href="library/cgi.html#index-0">[1]</a>
</li>
      </ul></li>
  </ul></td>
</tr></table>

<h2 id="X">X</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.X">X (in module re)</a>
</li>
      <li><a href="library/ssl.html#index-16">X509 certificate</a>
</li>
      <li><a href="library/os.html#os.X_OK">X_OK (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.xatom">xatom() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/turtle.html#turtle.xcor">xcor() (in module turtle)</a>
</li>
      <li><a href="library/pickle.html#index-1">XDR</a>, <a href="library/xdrlib.html#index-0">[1]</a>
</li>
      <li><a href="library/xdrlib.html#module-xdrlib">xdrlib (module)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xgtitle">xgtitle() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xhdr">xhdr() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/htmlparser.html#index-0">XHTML</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.XHTML_NAMESPACE">XHTML_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/xml.html#module-xml">xml (module)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XML">XML() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.dom.html#module-xml.dom">xml.dom (module)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#module-xml.dom.minidom">xml.dom.minidom (module)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#module-xml.dom.pulldom">xml.dom.pulldom (module)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#module-xml.etree.ElementTree">xml.etree.ElementTree (module)</a>
</li>
      <li><a href="library/pyexpat.html#module-xml.parsers.expat">xml.parsers.expat (module)</a>
</li>
      <li><a href="library/xml.sax.html#module-xml.sax">xml.sax (module)</a>
</li>
      <li><a href="library/xml.sax.handler.html#module-xml.sax.handler">xml.sax.handler (module)</a>
</li>
      <li><a href="library/xml.sax.utils.html#module-xml.sax.saxutils">xml.sax.saxutils (module)</a>
</li>
      <li><a href="library/xml.sax.reader.html#module-xml.sax.xmlreader">xml.sax.xmlreader (module)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.XML_NAMESPACE">XML_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/codecs.html#codecs.xmlcharrefreplace_errors">xmlcharrefreplace_errors() (in module codecs)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.XmlDeclHandler">XmlDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.XMLFilterBase">XMLFilterBase (class in xml.sax.saxutils)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.XMLGenerator">XMLGenerator (class in xml.sax.saxutils)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLID">XMLID() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.XMLNS_NAMESPACE">XMLNS_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser">XMLParser (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.XMLParserType">XMLParserType (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader">XMLReader (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/xmlrpclib.html#module-xmlrpclib">xmlrpclib (module)</a>
</li>
      <li>
    xor

      <ul>
        <li><a href="reference/expressions.html#index-62">bitwise</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.xor">xor() (in module operator)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xover">xover() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.xpath">xpath() (nntplib.NNTP method)</a>
</li>
      <li>
    xrange

      <ul>
        <li><a href="library/types.html#index-2">built-in function</a>
</li>
        <li><a href="library/stdtypes.html#index-21">object</a>, <a href="library/stdtypes.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-xrange">xrange (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#xrange">xrange() (built-in function)</a>
</li>
      <li><a href="library/types.html#types.XRangeType">XRangeType (in module types)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-xreadlines">xreadlines (2to3 fixer)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.xreadlines">xreadlines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.xreadlines">(file method)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.xview">xview() (ttk.Treeview method)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="Y">Y</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/time.html#index-2">Y2K</a>
</li>
      <li><a href="library/turtle.html#turtle.ycor">ycor() (in module turtle)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.year">year (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.year">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#index-2">Year 2000</a>
</li>
      <li><a href="library/time.html#index-1">Year 2038</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.yeardatescalendar">yeardatescalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.yeardays2calendar">yeardays2calendar() (calendar.Calendar method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/calendar.html#calendar.Calendar.yeardayscalendar">yeardayscalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/locale.html#locale.YESEXPR">YESEXPR (in module locale)</a>
</li>
      <li>
    yield

      <ul>
        <li><a href="reference/expressions.html#index-22">expression</a>
</li>
        <li><a href="reference/expressions.html#index-22">keyword</a>
</li>
        <li><a href="reference/simple_stmts.html#index-28">statement</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-YIELD_VALUE">YIELD_VALUE (opcode)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.yiq_to_rgb">yiq_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.yview">yview() (ttk.Treeview method)</a>
</li>
  </ul></td>
</tr></table>

<h2 id="Z">Z</h2>
<table style="width: 100%" class="indextable genindextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="glossary.html#term-zen-of-python"><strong>Zen of Python</strong></a>
</li>
      <li><a href="library/exceptions.html#exceptions.ZeroDivisionError">ZeroDivisionError</a>

      <ul>
        <li><a href="reference/expressions.html#index-54">exception</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.zfill">zfill() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.zfill">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-zip">zip (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#zip">zip() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.zip">(in module future_builtins)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZIP_DEFLATED">ZIP_DEFLATED (in module zipfile)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZIP_STORED">ZIP_STORED (in module zipfile)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile">ZipFile (class in zipfile)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/zipfile.html#module-zipfile">zipfile (module)</a>
</li>
      <li>
    zipfile command line option

      <ul>
        <li><a href="library/zipfile.html#cmdoption-zipfile-c">-c &lt;zipfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-e">-e &lt;zipfile&gt; &lt;output_dir&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-l">-l &lt;zipfile&gt;</a>
</li>
        <li><a href="library/zipfile.html#cmdoption-zipfile-t">-t &lt;zipfile&gt;</a>
</li>
      </ul></li>
      <li><a href="library/zipimport.html#module-zipimport">zipimport (module)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter">zipimporter (class in zipimport)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.ZipImportError">ZipImportError</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo">ZipInfo (class in zipfile)</a>
</li>
      <li><a href="library/zlib.html#module-zlib">zlib (module)</a>
</li>
  </ul></td>
</tr></table>



          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�|�html/genindex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="#" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="#" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

   <h1 id="index">Index</h1>

   <p>Index pages by letter:</p>

   <div class="genindex-jumpbox">
   <p><a href="genindex-Symbols.html"><strong>Symbols</strong></a>
     | <a href="genindex-_.html"><strong>_</strong></a>
     | <a href="genindex-A.html"><strong>A</strong></a>
     | <a href="genindex-B.html"><strong>B</strong></a>
     | <a href="genindex-C.html"><strong>C</strong></a>
     | <a href="genindex-D.html"><strong>D</strong></a>
     | <a href="genindex-E.html"><strong>E</strong></a>
     | <a href="genindex-F.html"><strong>F</strong></a>
     | <a href="genindex-G.html"><strong>G</strong></a>
     | <a href="genindex-H.html"><strong>H</strong></a>
     | <a href="genindex-I.html"><strong>I</strong></a>
     | <a href="genindex-J.html"><strong>J</strong></a>
     | <a href="genindex-K.html"><strong>K</strong></a>
     | <a href="genindex-L.html"><strong>L</strong></a>
     | <a href="genindex-M.html"><strong>M</strong></a>
     | <a href="genindex-N.html"><strong>N</strong></a>
     | <a href="genindex-O.html"><strong>O</strong></a>
     | <a href="genindex-P.html"><strong>P</strong></a>
     | <a href="genindex-Q.html"><strong>Q</strong></a>
     | <a href="genindex-R.html"><strong>R</strong></a>
     | <a href="genindex-S.html"><strong>S</strong></a>
     | <a href="genindex-T.html"><strong>T</strong></a>
     | <a href="genindex-U.html"><strong>U</strong></a>
     | <a href="genindex-V.html"><strong>V</strong></a>
     | <a href="genindex-W.html"><strong>W</strong></a>
     | <a href="genindex-X.html"><strong>X</strong></a>
     | <a href="genindex-Y.html"><strong>Y</strong></a>
     | <a href="genindex-Z.html"><strong>Z</strong></a>
     </p>

   <p><a href="genindex-all.html"><strong>Full index on one page</strong>
                                               (can be huge)</a></p>
   </div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="#" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��$�QLQLhtml/glossary.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Glossary &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="next" title="About these documents" href="about.html" />
    <link rel="prev" title="“Why is Python Installed on my Computer?” FAQ" href="faq/installed.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/glossary.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="about.html" title="About these documents"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="faq/installed.html" title="“Why is Python Installed on my Computer?” FAQ"
             accesskey="P">previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="glossary">
<span id="id1"></span><h1>Glossary<a class="headerlink" href="#glossary" title="Permalink to this headline">¶</a></h1>
<dl class="glossary docutils">
<dt id="term"><code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code></dt>
<dd>The default Python prompt of the interactive shell.  Often seen for code
examples which can be executed interactively in the interpreter.</dd>
<dt id="term-1"><code class="docutils literal notranslate"><span class="pre">...</span></code></dt>
<dd>The default Python prompt of the interactive shell when entering code for
an indented code block, when within a pair of matching left and right
delimiters (parentheses, square brackets, curly braces or triple quotes),
or after specifying a decorator.</dd>
<dt id="term-2to3">2to3</dt>
<dd><p class="first">A tool that tries to convert Python 2.x code to Python 3.x code by
handling most of the incompatibilities which can be detected by parsing the
source and traversing the parse tree.</p>
<p class="last">2to3 is available in the standard library as <a class="reference internal" href="library/2to3.html#module-lib2to3" title="lib2to3: the 2to3 library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lib2to3</span></code></a>; a standalone
entry point is provided as <code class="file docutils literal notranslate"><span class="pre">Tools/scripts/2to3</span></code>.  See
<a class="reference internal" href="library/2to3.html#to3-reference"><span class="std std-ref">2to3 - Automated Python 2 to 3 code translation</span></a>.</p>
</dd>
<dt id="term-abstract-base-class">abstract base class</dt>
<dd>Abstract base classes complement <a class="reference internal" href="#term-duck-typing"><span class="xref std std-term">duck-typing</span></a> by
providing a way to define interfaces when other techniques like
<a class="reference internal" href="library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> would be clumsy or subtly wrong (for example with
<a class="reference internal" href="reference/datamodel.html#new-style-special-lookup"><span class="std std-ref">magic methods</span></a>).  ABCs introduce virtual
subclasses, which are classes that don’t inherit from a class but are
still recognized by <a class="reference internal" href="library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>; see the
<a class="reference internal" href="library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module documentation.  Python comes with many built-in ABCs for
data structures (in the <a class="reference internal" href="library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module), numbers (in the
<a class="reference internal" href="library/numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module), and streams (in the <a class="reference internal" href="library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module). You can
create your own ABCs with the <a class="reference internal" href="library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module.</dd>
<dt id="term-argument">argument</dt>
<dd><p class="first">A value passed to a <a class="reference internal" href="#term-function"><span class="xref std std-term">function</span></a> (or <a class="reference internal" href="#term-method"><span class="xref std std-term">method</span></a>) when calling the
function.  There are two types of arguments:</p>
<ul>
<li><p class="first"><em class="dfn">keyword argument</em>: an argument preceded by an identifier (e.g.
<code class="docutils literal notranslate"><span class="pre">name=</span></code>) in a function call or passed as a value in a dictionary
preceded by <code class="docutils literal notranslate"><span class="pre">**</span></code>.  For example, <code class="docutils literal notranslate"><span class="pre">3</span></code> and <code class="docutils literal notranslate"><span class="pre">5</span></code> are both keyword
arguments in the following calls to <a class="reference internal" href="library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">complex</span><span class="p">(</span><span class="n">real</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">imag</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="nb">complex</span><span class="p">(</span><span class="o">**</span><span class="p">{</span><span class="s1">&#39;real&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;imag&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">})</span>
</pre></div>
</div>
</li>
<li><p class="first"><em class="dfn">positional argument</em>: an argument that is not a keyword argument.
Positional arguments can appear at the beginning of an argument list
and/or be passed as elements of an <a class="reference internal" href="#term-iterable"><span class="xref std std-term">iterable</span></a> preceded by <code class="docutils literal notranslate"><span class="pre">*</span></code>.
For example, <code class="docutils literal notranslate"><span class="pre">3</span></code> and <code class="docutils literal notranslate"><span class="pre">5</span></code> are both positional arguments in the
following calls:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">complex</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="nb">complex</span><span class="p">(</span><span class="o">*</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
</pre></div>
</div>
</li>
</ul>
<p>Arguments are assigned to the named local variables in a function body.
See the <a class="reference internal" href="reference/expressions.html#calls"><span class="std std-ref">Calls</span></a> section for the rules governing this assignment.
Syntactically, any expression can be used to represent an argument; the
evaluated value is assigned to the local variable.</p>
<p class="last">See also the <a class="reference internal" href="#term-parameter"><span class="xref std std-term">parameter</span></a> glossary entry and the FAQ question on
<a class="reference internal" href="faq/programming.html#faq-argument-vs-parameter"><span class="std std-ref">the difference between arguments and parameters</span></a>.</p>
</dd>
<dt id="term-attribute">attribute</dt>
<dd>A value associated with an object which is referenced by name using
dotted expressions.  For example, if an object <em>o</em> has an attribute
<em>a</em> it would be referenced as <em>o.a</em>.</dd>
<dt id="term-bdfl">BDFL</dt>
<dd>Benevolent Dictator For Life, a.k.a. <a class="reference external" href="https://www.python.org/~guido/">Guido van Rossum</a>, Python’s creator.</dd>
<dt id="term-bytes-like-object">bytes-like object</dt>
<dd>An object that supports the <a class="reference internal" href="c-api/buffer.html#bufferobjects"><span class="std std-ref">buffer protocol</span></a>,
like <a class="reference internal" href="library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> or <a class="reference internal" href="library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.
Bytes-like objects can be used for various operations that expect
binary data, such as compression, saving to a binary file or sending
over a socket. Some operations need the binary data to be mutable,
in which case not all bytes-like objects can apply.</dd>
<dt id="term-bytecode">bytecode</dt>
<dd><p class="first">Python source code is compiled into bytecode, the internal representation
of a Python program in the CPython interpreter.  The bytecode is also
cached in <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> and <code class="docutils literal notranslate"><span class="pre">.pyo</span></code> files so that executing the same file is
faster the second time (recompilation from source to bytecode can be
avoided).  This “intermediate language” is said to run on a
<a class="reference internal" href="#term-virtual-machine"><span class="xref std std-term">virtual machine</span></a> that executes the machine code corresponding to
each bytecode. Do note that bytecodes are not expected to work between
different Python virtual machines, nor to be stable between Python
releases.</p>
<p class="last">A list of bytecode instructions can be found in the documentation for
<a class="reference internal" href="library/dis.html#bytecodes"><span class="std std-ref">the dis module</span></a>.</p>
</dd>
<dt id="term-class">class</dt>
<dd>A template for creating user-defined objects. Class definitions
normally contain method definitions which operate on instances of the
class.</dd>
<dt id="term-classic-class">classic class</dt>
<dd>Any class which does not inherit from <a class="reference internal" href="library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.  See
<a class="reference internal" href="#term-new-style-class"><span class="xref std std-term">new-style class</span></a>.  Classic classes have been removed in Python 3.</dd>
<dt id="term-coercion">coercion</dt>
<dd>The implicit conversion of an instance of one type to another during an
operation which involves two arguments of the same type.  For example,
<code class="docutils literal notranslate"><span class="pre">int(3.15)</span></code> converts the floating point number to the integer <code class="docutils literal notranslate"><span class="pre">3</span></code>, but
in <code class="docutils literal notranslate"><span class="pre">3+4.5</span></code>, each argument is of a different type (one int, one float),
and both must be converted to the same type before they can be added or it
will raise a <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.  Coercion between two operands can be
performed with the <code class="docutils literal notranslate"><span class="pre">coerce</span></code> built-in function; thus, <code class="docutils literal notranslate"><span class="pre">3+4.5</span></code> is
equivalent to calling <code class="docutils literal notranslate"><span class="pre">operator.add(*coerce(3,</span> <span class="pre">4.5))</span></code> and results in
<code class="docutils literal notranslate"><span class="pre">operator.add(3.0,</span> <span class="pre">4.5)</span></code>.  Without coercion, all arguments of even
compatible types would have to be normalized to the same value by the
programmer, e.g., <code class="docutils literal notranslate"><span class="pre">float(3)+4.5</span></code> rather than just <code class="docutils literal notranslate"><span class="pre">3+4.5</span></code>.</dd>
<dt id="term-complex-number">complex number</dt>
<dd>An extension of the familiar real number system in which all numbers are
expressed as a sum of a real part and an imaginary part.  Imaginary
numbers are real multiples of the imaginary unit (the square root of
<code class="docutils literal notranslate"><span class="pre">-1</span></code>), often written <code class="docutils literal notranslate"><span class="pre">i</span></code> in mathematics or <code class="docutils literal notranslate"><span class="pre">j</span></code> in
engineering.  Python has built-in support for complex numbers, which are
written with this latter notation; the imaginary part is written with a
<code class="docutils literal notranslate"><span class="pre">j</span></code> suffix, e.g., <code class="docutils literal notranslate"><span class="pre">3+1j</span></code>.  To get access to complex equivalents of the
<a class="reference internal" href="library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module, use <a class="reference internal" href="library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a>.  Use of complex numbers is a fairly
advanced mathematical feature.  If you’re not aware of a need for them,
it’s almost certain you can safely ignore them.</dd>
<dt id="term-context-manager">context manager</dt>
<dd>An object which controls the environment seen in a <a class="reference internal" href="reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement by defining <a class="reference internal" href="reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods.
See <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a>.</dd>
<dt id="term-cpython">CPython</dt>
<dd>The canonical implementation of the Python programming language, as
distributed on <a class="reference external" href="https://www.python.org">python.org</a>.  The term “CPython”
is used when necessary to distinguish this implementation from others
such as Jython or IronPython.</dd>
<dt id="term-decorator">decorator</dt>
<dd><p class="first">A function returning another function, usually applied as a function
transformation using the <code class="docutils literal notranslate"><span class="pre">&#64;wrapper</span></code> syntax.  Common examples for
decorators are <a class="reference internal" href="library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> and <a class="reference internal" href="library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a>.</p>
<p>The decorator syntax is merely syntactic sugar, the following two
function definitions are semantically equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">...</span><span class="p">):</span>
    <span class="o">...</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>

<span class="nd">@staticmethod</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">...</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p class="last">The same concept exists for classes, but is less commonly used there.  See
the documentation for <a class="reference internal" href="reference/compound_stmts.html#function"><span class="std std-ref">function definitions</span></a> and
<a class="reference internal" href="reference/compound_stmts.html#class"><span class="std std-ref">class definitions</span></a> for more about decorators.</p>
</dd>
<dt id="term-descriptor">descriptor</dt>
<dd><p class="first">Any <em>new-style</em> object which defines the methods <a class="reference internal" href="reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>,
<a class="reference internal" href="reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, or <a class="reference internal" href="reference/datamodel.html#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>.  When a class attribute is a
descriptor, its special binding behavior is triggered upon attribute
lookup.  Normally, using <em>a.b</em> to get, set or delete an attribute looks up
the object named <em>b</em> in the class dictionary for <em>a</em>, but if <em>b</em> is a
descriptor, the respective descriptor method gets called.  Understanding
descriptors is a key to a deep understanding of Python because they are
the basis for many features including functions, methods, properties,
class methods, static methods, and reference to super classes.</p>
<p class="last">For more information about descriptors’ methods, see <a class="reference internal" href="reference/datamodel.html#descriptors"><span class="std std-ref">Implementing Descriptors</span></a>.</p>
</dd>
<dt id="term-dictionary">dictionary</dt>
<dd>An associative array, where arbitrary keys are mapped to values.  The
keys can be any object with <a class="reference internal" href="reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>  and <a class="reference internal" href="reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> methods.
Called a hash in Perl.</dd>
<dt id="term-dictionary-view">dictionary view</dt>
<dd>The objects returned from <a class="reference internal" href="library/stdtypes.html#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewkeys()</span></code></a>, <a class="reference internal" href="library/stdtypes.html#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewvalues()</span></code></a>,
and <a class="reference internal" href="library/stdtypes.html#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewitems()</span></code></a> are called dictionary views. They provide a dynamic
view on the dictionary’s entries, which means that when the dictionary
changes, the view reflects these changes. To force the
dictionary view to become a full list use <code class="docutils literal notranslate"><span class="pre">list(dictview)</span></code>.  See
<a class="reference internal" href="library/stdtypes.html#dict-views"><span class="std std-ref">Dictionary view objects</span></a>.</dd>
<dt id="term-docstring">docstring</dt>
<dd>A string literal which appears as the first expression in a class,
function or module.  While ignored when the suite is executed, it is
recognized by the compiler and put into the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attribute
of the enclosing class, function or module.  Since it is available via
introspection, it is the canonical place for documentation of the
object.</dd>
<dt id="term-duck-typing">duck-typing</dt>
<dd>A programming style which does not look at an object’s type to determine
if it has the right interface; instead, the method or attribute is simply
called or used (“If it looks like a duck and quacks like a duck, it
must be a duck.”)  By emphasizing interfaces rather than specific types,
well-designed code improves its flexibility by allowing polymorphic
substitution.  Duck-typing avoids tests using <a class="reference internal" href="library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> or
<a class="reference internal" href="library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a>.  (Note, however, that duck-typing can be complemented
with <a class="reference internal" href="#term-abstract-base-class"><span class="xref std std-term">abstract base classes</span></a>.)  Instead, it
typically employs <a class="reference internal" href="library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> tests or <a class="reference internal" href="#term-eafp"><span class="xref std std-term">EAFP</span></a> programming.</dd>
<dt id="term-eafp">EAFP</dt>
<dd>Easier to ask for forgiveness than permission.  This common Python coding
style assumes the existence of valid keys or attributes and catches
exceptions if the assumption proves false.  This clean and fast style is
characterized by the presence of many <a class="reference internal" href="reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> and <a class="reference internal" href="reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
statements.  The technique contrasts with the <a class="reference internal" href="#term-lbyl"><span class="xref std std-term">LBYL</span></a> style
common to many other languages such as C.</dd>
<dt id="term-expression">expression</dt>
<dd>A piece of syntax which can be evaluated to some value.  In other words,
an expression is an accumulation of expression elements like literals,
names, attribute access, operators or function calls which all return a
value.  In contrast to many other languages, not all language constructs
are expressions.  There are also <a class="reference internal" href="#term-statement"><span class="xref std std-term">statement</span></a>s which cannot be used
as expressions, such as <a class="reference internal" href="reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> or <a class="reference internal" href="reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>.  Assignments
are also statements, not expressions.</dd>
<dt id="term-extension-module">extension module</dt>
<dd>A module written in C or C++, using Python’s C API to interact with the
core and with user code.</dd>
<dt id="term-file-object">file object</dt>
<dd><p class="first">An object exposing a file-oriented API (with methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>) to an underlying resource.  Depending
on the way it was created, a file object can mediate access to a real
on-disk file or to another type of storage or communication device
(for example standard input/output, in-memory buffers, sockets, pipes,
etc.).  File objects are also called <em class="dfn">file-like objects</em> or
<em class="dfn">streams</em>.</p>
<p class="last">There are actually three categories of file objects: raw binary files,
buffered binary files and text files.  Their interfaces are defined in the
<a class="reference internal" href="library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module.  The canonical way to create a file object is by using
the <a class="reference internal" href="library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.</p>
</dd>
<dt id="term-file-like-object">file-like object</dt>
<dd>A synonym for <a class="reference internal" href="#term-file-object"><span class="xref std std-term">file object</span></a>.</dd>
<dt id="term-finder">finder</dt>
<dd>An object that tries to find the <a class="reference internal" href="#term-loader"><span class="xref std std-term">loader</span></a> for a module. It must
implement a method named <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code>. See <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for
details.</dd>
<dt id="term-floor-division">floor division</dt>
<dd>Mathematical division that rounds down to nearest integer.  The floor
division operator is <code class="docutils literal notranslate"><span class="pre">//</span></code>.  For example, the expression <code class="docutils literal notranslate"><span class="pre">11</span> <span class="pre">//</span> <span class="pre">4</span></code>
evaluates to <code class="docutils literal notranslate"><span class="pre">2</span></code> in contrast to the <code class="docutils literal notranslate"><span class="pre">2.75</span></code> returned by float true
division.  Note that <code class="docutils literal notranslate"><span class="pre">(-11)</span> <span class="pre">//</span> <span class="pre">4</span></code> is <code class="docutils literal notranslate"><span class="pre">-3</span></code> because that is <code class="docutils literal notranslate"><span class="pre">-2.75</span></code>
rounded <em>downward</em>. See <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a>.</dd>
<dt id="term-function">function</dt>
<dd>A series of statements which returns some value to a caller. It can also
be passed zero or more <a class="reference internal" href="#term-argument"><span class="xref std std-term">arguments</span></a> which may be used in
the execution of the body. See also <a class="reference internal" href="#term-parameter"><span class="xref std std-term">parameter</span></a>, <a class="reference internal" href="#term-method"><span class="xref std std-term">method</span></a>,
and the <a class="reference internal" href="reference/compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> section.</dd>
<dt id="term-future">__future__</dt>
<dd><p class="first">A pseudo-module which programmers can use to enable new language features
which are not compatible with the current interpreter.  For example, the
expression <code class="docutils literal notranslate"><span class="pre">11/4</span></code> currently evaluates to <code class="docutils literal notranslate"><span class="pre">2</span></code>. If the module in which
it is executed had enabled <em>true division</em> by executing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">division</span>
</pre></div>
</div>
<p>the expression <code class="docutils literal notranslate"><span class="pre">11/4</span></code> would evaluate to <code class="docutils literal notranslate"><span class="pre">2.75</span></code>.  By importing the
<a class="reference internal" href="library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> module and evaluating its variables, you can see when a
new feature was first added to the language and when it will become the
default:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">__future__</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">__future__</span><span class="o">.</span><span class="n">division</span>
<span class="go">_Feature((2, 2, 0, &#39;alpha&#39;, 2), (3, 0, 0, &#39;alpha&#39;, 0), 8192)</span>
</pre></div>
</div>
</dd>
<dt id="term-garbage-collection">garbage collection</dt>
<dd>The process of freeing memory when it is not used anymore.  Python
performs garbage collection via reference counting and a cyclic garbage
collector that is able to detect and break reference cycles.</dd>
<dt id="index-3"><span id="term-generator"></span>generator</dt>
<dd>A function which returns an iterator.  It looks like a normal function
except that it contains <a class="reference internal" href="reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statements for producing a series
of values usable in a for-loop or that can be retrieved one at a time with
the <a class="reference internal" href="library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> function. Each <a class="reference internal" href="reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> temporarily suspends
processing, remembering the location execution state (including local
variables and pending try-statements).  When the generator resumes, it
picks up where it left off (in contrast to functions which start fresh on
every invocation).</dd>
<dt id="index-4"><span id="term-generator-expression"></span>generator expression</dt>
<dd><p class="first">An expression that returns an iterator.  It looks like a normal expression
followed by a <a class="reference internal" href="reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> expression defining a loop variable, range,
and an optional <a class="reference internal" href="reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> expression.  The combined expression
generates values for an enclosing function:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>         <span class="c1"># sum of squares 0, 1, 4, ... 81</span>
<span class="go">285</span>
</pre></div>
</div>
</dd>
<dt id="term-gil">GIL</dt>
<dd>See <a class="reference internal" href="#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a>.</dd>
<dt id="term-global-interpreter-lock">global interpreter lock</dt>
<dd><p class="first">The mechanism used by the <a class="reference internal" href="#term-cpython"><span class="xref std std-term">CPython</span></a> interpreter to assure that
only one thread executes Python <a class="reference internal" href="#term-bytecode"><span class="xref std std-term">bytecode</span></a> at a time.
This simplifies the CPython implementation by making the object model
(including critical built-in types such as <a class="reference internal" href="library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>) implicitly
safe against concurrent access.  Locking the entire interpreter
makes it easier for the interpreter to be multi-threaded, at the
expense of much of the parallelism afforded by multi-processor
machines.</p>
<p>However, some extension modules, either standard or third-party,
are designed so as to release the GIL when doing computationally-intensive
tasks such as compression or hashing.  Also, the GIL is always released
when doing I/O.</p>
<p class="last">Past efforts to create a “free-threaded” interpreter (one which locks
shared data at a much finer granularity) have not been successful
because performance suffered in the common single-processor case. It
is believed that overcoming this performance issue would make the
implementation much more complicated and therefore costlier to maintain.</p>
</dd>
<dt id="term-hashable">hashable</dt>
<dd><p class="first">An object is <em>hashable</em> if it has a hash value which never changes during
its lifetime (it needs a <a class="reference internal" href="reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method), and can be compared to
other objects (it needs an <a class="reference internal" href="reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> or <a class="reference internal" href="reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method).
Hashable objects which compare equal must have the same hash value.</p>
<p>Hashability makes an object usable as a dictionary key and a set member,
because these data structures use the hash value internally.</p>
<p class="last">All of Python’s immutable built-in objects are hashable, while no mutable
containers (such as lists or dictionaries) are.  Objects which are
instances of user-defined classes are hashable by default; they all
compare unequal (except with themselves), and their hash value is derived
from their <a class="reference internal" href="library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>.</p>
</dd>
<dt id="term-idle">IDLE</dt>
<dd>An Integrated Development Environment for Python.  IDLE is a basic editor
and interpreter environment which ships with the standard distribution of
Python.</dd>
<dt id="term-immutable">immutable</dt>
<dd>An object with a fixed value.  Immutable objects include numbers, strings and
tuples.  Such an object cannot be altered.  A new object has to
be created if a different value has to be stored.  They play an important
role in places where a constant hash value is needed, for example as a key
in a dictionary.</dd>
<dt id="term-integer-division">integer division</dt>
<dd>Mathematical division discarding any remainder.  For example, the
expression <code class="docutils literal notranslate"><span class="pre">11/4</span></code> currently evaluates to <code class="docutils literal notranslate"><span class="pre">2</span></code> in contrast to the
<code class="docutils literal notranslate"><span class="pre">2.75</span></code> returned by float division.  Also called <em>floor division</em>.
When dividing two integers the outcome will always be another integer
(having the floor function applied to it). However, if one of the operands
is another numeric type (such as a <a class="reference internal" href="library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>), the result will be
coerced (see <a class="reference internal" href="#term-coercion"><span class="xref std std-term">coercion</span></a>) to a common type.  For example, an integer
divided by a float will result in a float value, possibly with a decimal
fraction.  Integer division can be forced by using the <code class="docutils literal notranslate"><span class="pre">//</span></code> operator
instead of the <code class="docutils literal notranslate"><span class="pre">/</span></code> operator.  See also <a class="reference internal" href="#term-future"><span class="xref std std-term">__future__</span></a>.</dd>
<dt id="term-importing">importing</dt>
<dd>The process by which Python code in one module is made available to
Python code in another module.</dd>
<dt id="term-importer">importer</dt>
<dd>An object that both finds and loads a module; both a
<a class="reference internal" href="#term-finder"><span class="xref std std-term">finder</span></a> and <a class="reference internal" href="#term-loader"><span class="xref std std-term">loader</span></a> object.</dd>
<dt id="term-interactive">interactive</dt>
<dd>Python has an interactive interpreter which means you can enter
statements and expressions at the interpreter prompt, immediately
execute them and see their results.  Just launch <code class="docutils literal notranslate"><span class="pre">python</span></code> with no
arguments (possibly by selecting it from your computer’s main
menu). It is a very powerful way to test out new ideas or inspect
modules and packages (remember <code class="docutils literal notranslate"><span class="pre">help(x)</span></code>).</dd>
<dt id="term-interpreted">interpreted</dt>
<dd>Python is an interpreted language, as opposed to a compiled one,
though the distinction can be blurry because of the presence of the
bytecode compiler.  This means that source files can be run directly
without explicitly creating an executable which is then run.
Interpreted languages typically have a shorter development/debug cycle
than compiled ones, though their programs generally also run more
slowly.  See also <a class="reference internal" href="#term-interactive"><span class="xref std std-term">interactive</span></a>.</dd>
<dt id="term-iterable">iterable</dt>
<dd>An object capable of returning its members one at a time. Examples of
iterables include all sequence types (such as <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>,
and <a class="reference internal" href="library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>) and some non-sequence types like <a class="reference internal" href="library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>
and <a class="reference internal" href="library/functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> and objects of any classes you define
with an <a class="reference internal" href="reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> or <a class="reference internal" href="reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.  Iterables can be
used in a <a class="reference internal" href="reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop and in many other places where a sequence is
needed (<a class="reference internal" href="library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>, <a class="reference internal" href="library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>, …).  When an iterable object is passed
as an argument to the built-in function <a class="reference internal" href="library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a>, it returns an
iterator for the object.  This iterator is good for one pass over the set
of values.  When using iterables, it is usually not necessary to call
<a class="reference internal" href="library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> or deal with iterator objects yourself.  The <code class="docutils literal notranslate"><span class="pre">for</span></code>
statement does that automatically for you, creating a temporary unnamed
variable to hold the iterator for the duration of the loop.  See also
<a class="reference internal" href="#term-iterator"><span class="xref std std-term">iterator</span></a>, <a class="reference internal" href="#term-sequence"><span class="xref std std-term">sequence</span></a>, and <a class="reference internal" href="#term-generator"><span class="xref std std-term">generator</span></a>.</dd>
<dt id="term-iterator">iterator</dt>
<dd><p class="first">An object representing a stream of data.  Repeated calls to the iterator’s
<a class="reference internal" href="reference/expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method return successive items in the stream.  When no more
data are available a <a class="reference internal" href="library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is raised instead.  At
this point, the iterator object is exhausted and any further calls to its
<a class="reference internal" href="reference/expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method just raise <a class="reference internal" href="library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> again.  Iterators are
required to have an <a class="reference internal" href="reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method that returns the iterator
object itself so every iterator is also iterable and may be used in most
places where other iterables are accepted.  One notable exception is code
which attempts multiple iteration passes.  A container object (such as a
<code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>) produces a fresh new iterator each time you pass it to the
<a class="reference internal" href="library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> function or use it in a <a class="reference internal" href="reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop.  Attempting this
with an iterator will just return the same exhausted iterator object used
in the previous iteration pass, making it appear like an empty container.</p>
<p class="last">More information can be found in <a class="reference internal" href="library/stdtypes.html#typeiter"><span class="std std-ref">Iterator Types</span></a>.</p>
</dd>
<dt id="term-key-function">key function</dt>
<dd><p class="first">A key function or collation function is a callable that returns a value
used for sorting or ordering.  For example, <a class="reference internal" href="library/locale.html#locale.strxfrm" title="locale.strxfrm"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strxfrm()</span></code></a> is
used to produce a sort key that is aware of locale specific sort
conventions.</p>
<p>A number of tools in Python accept key functions to control how elements
are ordered or grouped.  They include <a class="reference internal" href="library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>, <a class="reference internal" href="library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>,
<a class="reference internal" href="library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code>, <a class="reference internal" href="library/heapq.html#heapq.nsmallest" title="heapq.nsmallest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nsmallest()</span></code></a>,
<a class="reference internal" href="library/heapq.html#heapq.nlargest" title="heapq.nlargest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nlargest()</span></code></a>, and <a class="reference internal" href="library/itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.groupby()</span></code></a>.</p>
<p class="last">There are several ways to create a key function.  For example. the
<a class="reference internal" href="library/stdtypes.html#str.lower" title="str.lower"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.lower()</span></code></a> method can serve as a key function for case insensitive
sorts.  Alternatively, an ad-hoc key function can be built from a
<a class="reference internal" href="reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> expression such as <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">r:</span> <span class="pre">(r[0],</span> <span class="pre">r[2])</span></code>.  Also,
the <a class="reference internal" href="library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module provides three key function constructors:
<a class="reference internal" href="library/operator.html#operator.attrgetter" title="operator.attrgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code></a>, <a class="reference internal" href="library/operator.html#operator.itemgetter" title="operator.itemgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itemgetter()</span></code></a>, and
<a class="reference internal" href="library/operator.html#operator.methodcaller" title="operator.methodcaller"><code class="xref py py-func docutils literal notranslate"><span class="pre">methodcaller()</span></code></a>.  See the <a class="reference internal" href="howto/sorting.html#sortinghowto"><span class="std std-ref">Sorting HOW TO</span></a> for examples of how to create and use key functions.</p>
</dd>
<dt id="term-keyword-argument">keyword argument</dt>
<dd>See <a class="reference internal" href="#term-argument"><span class="xref std std-term">argument</span></a>.</dd>
<dt id="term-lambda">lambda</dt>
<dd>An anonymous inline function consisting of a single <a class="reference internal" href="#term-expression"><span class="xref std std-term">expression</span></a>
which is evaluated when the function is called.  The syntax to create
a lambda function is <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">[parameters]:</span> <span class="pre">expression</span></code></dd>
<dt id="term-lbyl">LBYL</dt>
<dd><p class="first">Look before you leap.  This coding style explicitly tests for
pre-conditions before making calls or lookups.  This style contrasts with
the <a class="reference internal" href="#term-eafp"><span class="xref std std-term">EAFP</span></a> approach and is characterized by the presence of many
<a class="reference internal" href="reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements.</p>
<p class="last">In a multi-threaded environment, the LBYL approach can risk introducing a
race condition between “the looking” and “the leaping”.  For example, the
code, <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">key</span> <span class="pre">in</span> <span class="pre">mapping:</span> <span class="pre">return</span> <span class="pre">mapping[key]</span></code> can fail if another
thread removes <em>key</em> from <em>mapping</em> after the test, but before the lookup.
This issue can be solved with locks or by using the EAFP approach.</p>
</dd>
<dt id="term-list">list</dt>
<dd>A built-in Python <a class="reference internal" href="#term-sequence"><span class="xref std std-term">sequence</span></a>.  Despite its name it is more akin
to an array in other languages than to a linked list since access to
elements is O(1).</dd>
<dt id="term-list-comprehension">list comprehension</dt>
<dd>A compact way to process all or part of the elements in a sequence and
return a list with the results.  <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">[&quot;0x%02x&quot;</span> <span class="pre">%</span> <span class="pre">x</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span>
<span class="pre">range(256)</span> <span class="pre">if</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">2</span> <span class="pre">==</span> <span class="pre">0]</span></code> generates a list of strings containing
even hex numbers (0x..) in the range from 0 to 255. The <a class="reference internal" href="reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>
clause is optional.  If omitted, all elements in <code class="docutils literal notranslate"><span class="pre">range(256)</span></code> are
processed.</dd>
<dt id="term-loader">loader</dt>
<dd>An object that loads a module. It must define a method named
<code class="xref py py-meth docutils literal notranslate"><span class="pre">load_module()</span></code>. A loader is typically returned by a
<a class="reference internal" href="#term-finder"><span class="xref std std-term">finder</span></a>. See <span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for details.</dd>
<dt id="term-mapping">mapping</dt>
<dd>A container object that supports arbitrary key lookups and implements the
methods specified in the <a class="reference internal" href="library/collections.html#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> or
<a class="reference internal" href="library/collections.html#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a>
<a class="reference internal" href="library/collections.html#collections-abstract-base-classes"><span class="std std-ref">abstract base classes</span></a>.  Examples
include <a class="reference internal" href="library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="library/collections.html#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.defaultdict</span></code></a>,
<a class="reference internal" href="library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a> and <a class="reference internal" href="library/collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.Counter</span></code></a>.</dd>
<dt id="term-metaclass">metaclass</dt>
<dd><p class="first">The class of a class.  Class definitions create a class name, a class
dictionary, and a list of base classes.  The metaclass is responsible for
taking those three arguments and creating the class.  Most object oriented
programming languages provide a default implementation.  What makes Python
special is that it is possible to create custom metaclasses.  Most users
never need this tool, but when the need arises, metaclasses can provide
powerful, elegant solutions.  They have been used for logging attribute
access, adding thread-safety, tracking object creation, implementing
singletons, and many other tasks.</p>
<p class="last">More information can be found in <a class="reference internal" href="reference/datamodel.html#metaclasses"><span class="std std-ref">Customizing class creation</span></a>.</p>
</dd>
<dt id="term-method">method</dt>
<dd>A function which is defined inside a class body.  If called as an attribute
of an instance of that class, the method will get the instance object as
its first <a class="reference internal" href="#term-argument"><span class="xref std std-term">argument</span></a> (which is usually called <code class="docutils literal notranslate"><span class="pre">self</span></code>).
See <a class="reference internal" href="#term-function"><span class="xref std std-term">function</span></a> and <a class="reference internal" href="#term-nested-scope"><span class="xref std std-term">nested scope</span></a>.</dd>
<dt id="term-method-resolution-order">method resolution order</dt>
<dd>Method Resolution Order is the order in which base classes are searched
for a member during lookup. See <a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">The Python 2.3 Method Resolution Order</a> for details of the
algorithm used by the Python interpreter since the 2.3 release.</dd>
<dt id="term-module">module</dt>
<dd><p class="first">An object that serves as an organizational unit of Python code.  Modules
have a namespace containing arbitrary Python objects.  Modules are loaded
into Python by the process of <a class="reference internal" href="#term-importing"><span class="xref std std-term">importing</span></a>.</p>
<p class="last">See also <a class="reference internal" href="#term-package"><span class="xref std std-term">package</span></a>.</p>
</dd>
<dt id="term-mro">MRO</dt>
<dd>See <a class="reference internal" href="#term-method-resolution-order"><span class="xref std std-term">method resolution order</span></a>.</dd>
<dt id="term-mutable">mutable</dt>
<dd>Mutable objects can change their value but keep their <a class="reference internal" href="library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>.  See
also <a class="reference internal" href="#term-immutable"><span class="xref std std-term">immutable</span></a>.</dd>
<dt id="term-named-tuple">named tuple</dt>
<dd><p class="first">Any tuple-like class whose indexable elements are also accessible using
named attributes (for example, <a class="reference internal" href="library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> returns a
tuple-like object where the <em>year</em> is accessible either with an
index such as <code class="docutils literal notranslate"><span class="pre">t[0]</span></code> or with a named attribute like <code class="docutils literal notranslate"><span class="pre">t.tm_year</span></code>).</p>
<p class="last">A named tuple can be a built-in type such as <a class="reference internal" href="library/time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a>,
or it can be created with a regular class definition.  A full featured
named tuple can also be created with the factory function
<a class="reference internal" href="library/collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.namedtuple()</span></code></a>.  The latter approach automatically
provides extra features such as a self-documenting representation like
<code class="docutils literal notranslate"><span class="pre">Employee(name='jones',</span> <span class="pre">title='programmer')</span></code>.</p>
</dd>
<dt id="term-namespace">namespace</dt>
<dd>The place where a variable is stored.  Namespaces are implemented as
dictionaries.  There are the local, global and built-in namespaces as well
as nested namespaces in objects (in methods).  Namespaces support
modularity by preventing naming conflicts.  For instance, the functions
<code class="xref py py-func docutils literal notranslate"><span class="pre">__builtin__.open()</span></code> and <a class="reference internal" href="library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> are distinguished by their
namespaces.  Namespaces also aid readability and maintainability by making
it clear which module implements a function.  For instance, writing
<a class="reference internal" href="library/random.html#random.seed" title="random.seed"><code class="xref py py-func docutils literal notranslate"><span class="pre">random.seed()</span></code></a> or <a class="reference internal" href="library/itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a> makes it clear that those
functions are implemented by the <a class="reference internal" href="library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> and <a class="reference internal" href="library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a>
modules, respectively.</dd>
<dt id="term-nested-scope">nested scope</dt>
<dd>The ability to refer to a variable in an enclosing definition.  For
instance, a function defined inside another function can refer to
variables in the outer function.  Note that nested scopes work only for
reference and not for assignment which will always write to the innermost
scope.  In contrast, local variables both read and write in the innermost
scope.  Likewise, global variables read and write to the global namespace.</dd>
<dt id="term-new-style-class">new-style class</dt>
<dd><p class="first">Any class which inherits from <a class="reference internal" href="library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.  This includes all built-in
types like <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> and <a class="reference internal" href="library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  Only new-style classes can
use Python’s newer, versatile features like <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code>,
descriptors, properties, and <a class="reference internal" href="reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>.</p>
<p class="last">More information can be found in <a class="reference internal" href="reference/datamodel.html#newstyle"><span class="std std-ref">New-style and classic classes</span></a>.</p>
</dd>
<dt id="term-object">object</dt>
<dd>Any data with state (attributes or value) and defined behavior
(methods).  Also the ultimate base class of any <a class="reference internal" href="#term-new-style-class"><span class="xref std std-term">new-style
class</span></a>.</dd>
<dt id="term-package">package</dt>
<dd>A Python <a class="reference internal" href="#term-module"><span class="xref std std-term">module</span></a> which can contain submodules or recursively,
subpackages.  Technically, a package is a Python module with an
<code class="docutils literal notranslate"><span class="pre">__path__</span></code> attribute.</dd>
<dt id="term-parameter">parameter</dt>
<dd><p class="first">A named entity in a <a class="reference internal" href="#term-function"><span class="xref std std-term">function</span></a> (or method) definition that
specifies an <a class="reference internal" href="#term-argument"><span class="xref std std-term">argument</span></a> (or in some cases, arguments) that the
function can accept.  There are four types of parameters:</p>
<ul>
<li><p class="first"><em class="dfn">positional-or-keyword</em>: specifies an argument that can be passed
either <a class="reference internal" href="#term-argument"><span class="xref std std-term">positionally</span></a> or as a <a class="reference internal" href="#term-argument"><span class="xref std std-term">keyword argument</span></a>.  This is the default kind of parameter, for example <em>foo</em>
and <em>bar</em> in the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">foo</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span> <span class="o">...</span>
</pre></div>
</div>
</li>
<li><p class="first"><em class="dfn">positional-only</em>: specifies an argument that can be supplied only
by position.  Python has no syntax for defining positional-only
parameters.  However, some built-in functions have positional-only
parameters (e.g. <a class="reference internal" href="library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a>).</p>
</li>
<li><p class="first"><em class="dfn">var-positional</em>: specifies that an arbitrary sequence of
positional arguments can be provided (in addition to any positional
arguments already accepted by other parameters).  Such a parameter can
be defined by prepending the parameter name with <code class="docutils literal notranslate"><span class="pre">*</span></code>, for example
<em>args</em> in the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="o">...</span>
</pre></div>
</div>
</li>
<li><p class="first"><em class="dfn">var-keyword</em>: specifies that arbitrarily many keyword arguments
can be provided (in addition to any keyword arguments already accepted
by other parameters).  Such a parameter can be defined by prepending
the parameter name with <code class="docutils literal notranslate"><span class="pre">**</span></code>, for example <em>kwargs</em> in the example
above.</p>
</li>
</ul>
<p>Parameters can specify both optional and required arguments, as well as
default values for some optional arguments.</p>
<p class="last">See also the <a class="reference internal" href="#term-argument"><span class="xref std std-term">argument</span></a> glossary entry, the FAQ question on
<a class="reference internal" href="faq/programming.html#faq-argument-vs-parameter"><span class="std std-ref">the difference between arguments and parameters</span></a>, and the <a class="reference internal" href="reference/compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> section.</p>
</dd>
<dt id="term-pep">PEP</dt>
<dd><p class="first">Python Enhancement Proposal. A PEP is a design document
providing information to the Python community, or describing a new
feature for Python or its processes or environment. PEPs should
provide a concise technical specification and a rationale for proposed
features.</p>
<p>PEPs are intended to be the primary mechanisms for proposing major new
features, for collecting community input on an issue, and for documenting
the design decisions that have gone into Python. The PEP author is
responsible for building consensus within the community and documenting
dissenting opinions.</p>
<p class="last">See <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0001"><strong>PEP 1</strong></a>.</p>
</dd>
<dt id="term-positional-argument">positional argument</dt>
<dd>See <a class="reference internal" href="#term-argument"><span class="xref std std-term">argument</span></a>.</dd>
<dt id="term-python-3000">Python 3000</dt>
<dd>Nickname for the Python 3.x release line (coined long ago when the release
of version 3 was something in the distant future.)  This is also
abbreviated “Py3k”.</dd>
<dt id="term-pythonic">Pythonic</dt>
<dd><p class="first">An idea or piece of code which closely follows the most common idioms
of the Python language, rather than implementing code using concepts
common to other languages.  For example, a common idiom in Python is
to loop over all elements of an iterable using a <a class="reference internal" href="reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>
statement.  Many other languages don’t have this type of construct, so
people unfamiliar with Python sometimes use a numerical counter instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">food</span><span class="p">)):</span>
    <span class="nb">print</span> <span class="n">food</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
</pre></div>
</div>
<p>As opposed to the cleaner, Pythonic method:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">piece</span> <span class="ow">in</span> <span class="n">food</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">piece</span>
</pre></div>
</div>
</dd>
<dt id="term-reference-count">reference count</dt>
<dd>The number of references to an object.  When the reference count of an
object drops to zero, it is deallocated.  Reference counting is
generally not visible to Python code, but it is a key element of the
<a class="reference internal" href="#term-cpython"><span class="xref std std-term">CPython</span></a> implementation.  The <a class="reference internal" href="library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module defines a
<a class="reference internal" href="library/sys.html#sys.getrefcount" title="sys.getrefcount"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrefcount()</span></code></a> function that programmers can call to return the
reference count for a particular object.</dd>
<dt id="term-slots">__slots__</dt>
<dd>A declaration inside a <a class="reference internal" href="#term-new-style-class"><span class="xref std std-term">new-style class</span></a> that saves memory by
pre-declaring space for instance attributes and eliminating instance
dictionaries.  Though popular, the technique is somewhat tricky to get
right and is best reserved for rare cases where there are large numbers of
instances in a memory-critical application.</dd>
<dt id="term-sequence">sequence</dt>
<dd>An <a class="reference internal" href="#term-iterable"><span class="xref std std-term">iterable</span></a> which supports efficient element access using integer
indices via the <a class="reference internal" href="reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> special method and defines a
<a class="reference internal" href="library/functions.html#len" title="len"><code class="xref py py-meth docutils literal notranslate"><span class="pre">len()</span></code></a> method that returns the length of the sequence.
Some built-in sequence types are <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>,
<a class="reference internal" href="library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, and <a class="reference internal" href="library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>. Note that <a class="reference internal" href="library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> also
supports <a class="reference internal" href="reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> and <a class="reference internal" href="reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>, but is considered a
mapping rather than a sequence because the lookups use arbitrary
<a class="reference internal" href="#term-immutable"><span class="xref std std-term">immutable</span></a> keys rather than integers.</dd>
<dt id="term-slice">slice</dt>
<dd>An object usually containing a portion of a <a class="reference internal" href="#term-sequence"><span class="xref std std-term">sequence</span></a>.  A slice is
created using the subscript notation, <code class="docutils literal notranslate"><span class="pre">[]</span></code> with colons between numbers
when several are given, such as in <code class="docutils literal notranslate"><span class="pre">variable_name[1:3:5]</span></code>.  The bracket
(subscript) notation uses <a class="reference internal" href="library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> objects internally (or in older
versions, <a class="reference internal" href="reference/datamodel.html#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a> and <a class="reference internal" href="reference/datamodel.html#object.__setslice__" title="object.__setslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setslice__()</span></code></a>).</dd>
<dt id="term-special-method">special method</dt>
<dd>A method that is called implicitly by Python to execute a certain
operation on a type, such as addition.  Such methods have names starting
and ending with double underscores.  Special methods are documented in
<a class="reference internal" href="reference/datamodel.html#specialnames"><span class="std std-ref">Special method names</span></a>.</dd>
<dt id="term-statement">statement</dt>
<dd>A statement is part of a suite (a “block” of code).  A statement is either
an <a class="reference internal" href="#term-expression"><span class="xref std std-term">expression</span></a> or one of several constructs with a keyword, such
as <a class="reference internal" href="reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> or <a class="reference internal" href="reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>.</dd>
<dt id="term-struct-sequence">struct sequence</dt>
<dd>A tuple with named elements. Struct sequences expose an interface similiar
to <a class="reference internal" href="#term-named-tuple"><span class="xref std std-term">named tuple</span></a> in that elements can be accessed either by
index or as an attribute. However, they do not have any of the named tuple
methods like <a class="reference internal" href="library/collections.html#collections.somenamedtuple._make" title="collections.somenamedtuple._make"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_make()</span></code></a> or
<a class="reference internal" href="library/collections.html#collections.somenamedtuple._asdict" title="collections.somenamedtuple._asdict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_asdict()</span></code></a>. Examples of struct sequences
include <a class="reference internal" href="library/sys.html#sys.float_info" title="sys.float_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.float_info</span></code></a> and the return value of <a class="reference internal" href="library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>.</dd>
<dt id="term-triple-quoted-string">triple-quoted string</dt>
<dd>A string which is bound by three instances of either a quotation mark
(“) or an apostrophe (‘).  While they don’t provide any functionality
not available with single-quoted strings, they are useful for a number
of reasons.  They allow you to include unescaped single and double
quotes within a string and they can span multiple lines without the
use of the continuation character, making them especially useful when
writing docstrings.</dd>
<dt id="term-type">type</dt>
<dd>The type of a Python object determines what kind of object it is; every
object has a type.  An object’s type is accessible as its
<a class="reference internal" href="library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> attribute or can be retrieved with
<code class="docutils literal notranslate"><span class="pre">type(obj)</span></code>.</dd>
<dt id="term-universal-newlines">universal newlines</dt>
<dd>A manner of interpreting text streams in which all of the following are
recognized as ending a line: the Unix end-of-line convention <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>,
the Windows convention <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>, and the old Macintosh convention
<code class="docutils literal notranslate"><span class="pre">'\r'</span></code>.  See <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0278"><strong>PEP 278</strong></a> and <span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3116"><strong>PEP 3116</strong></a>, as well as
<a class="reference internal" href="library/stdtypes.html#str.splitlines" title="str.splitlines"><code class="xref py py-func docutils literal notranslate"><span class="pre">str.splitlines()</span></code></a> for an additional use.</dd>
<dt id="term-virtual-environment">virtual environment</dt>
<dd>A cooperatively isolated runtime environment that allows Python users
and applications to install and upgrade Python distribution packages
without interfering with the behaviour of other Python applications
running on the same system.</dd>
<dt id="term-virtual-machine">virtual machine</dt>
<dd>A computer defined entirely in software.  Python’s virtual machine
executes the <a class="reference internal" href="#term-bytecode"><span class="xref std std-term">bytecode</span></a> emitted by the bytecode compiler.</dd>
<dt id="term-zen-of-python">Zen of Python</dt>
<dd>Listing of Python design principles and philosophies that are helpful in
understanding and using the language.  The listing can be found by typing
“<code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">this</span></code>” at the interactive prompt.</dd>
</dl>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="faq/installed.html"
                        title="previous chapter">“Why is Python Installed on my Computer?” FAQ</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="about.html"
                        title="next chapter">About these documents</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/glossary.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="about.html" title="About these documents"
             >next</a> |</li>
        <li class="right" >
          <a href="faq/installed.html" title="“Why is Python Installed on my Computer?” FAQ"
             >previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��oW#W#html/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/index.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="#">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <h1>Python 2.7.16 documentation</h1>
  <p>
  Welcome! This is the documentation for Python 2.7.16.
  </p>
  <p><strong>Parts of the documentation:</strong></p>
  <table class="contentstable" align="center"><tr>
    <td width="50%">
      <p class="biglink"><a class="biglink" href="whatsnew/2.7.html">What's new in Python 2.7?</a><br/>
         <span class="linkdescr">or <a href="whatsnew/index.html">all "What's new" documents</a> since 2.0</span></p>
      <p class="biglink"><a class="biglink" href="tutorial/index.html">Tutorial</a><br/>
         <span class="linkdescr">start here</span></p>
      <p class="biglink"><a class="biglink" href="library/index.html">Library Reference</a><br/>
         <span class="linkdescr">keep this under your pillow</span></p>
      <p class="biglink"><a class="biglink" href="reference/index.html">Language Reference</a><br/>
         <span class="linkdescr">describes syntax and language elements</span></p>
      <p class="biglink"><a class="biglink" href="using/index.html">Python Setup and Usage</a><br/>
         <span class="linkdescr">how to use Python on different platforms</span></p>
      <p class="biglink"><a class="biglink" href="howto/index.html">Python HOWTOs</a><br/>
         <span class="linkdescr">in-depth documents on specific topics</span></p>
    </td><td width="50%">
      <p class="biglink"><a class="biglink" href="installing/index.html">Installing Python Modules</a><br/>
         <span class="linkdescr">installing from the Python Package Index &amp; other sources</span></p>
      <p class="biglink"><a class="biglink" href="distributing/index.html">Distributing Python Modules</a><br/>
         <span class="linkdescr">publishing modules for installation by others</span></p>
      <p class="biglink"><a class="biglink" href="extending/index.html">Extending and Embedding</a><br/>
         <span class="linkdescr">tutorial for C/C++ programmers</span></p>
      <p class="biglink"><a class="biglink" href="c-api/index.html">Python/C API</a><br/>
         <span class="linkdescr">reference for C/C++ programmers</span></p>
      <p class="biglink"><a class="biglink" href="faq/index.html">FAQs</a><br/>
         <span class="linkdescr">frequently asked questions (with answers!)</span></p>
    </td></tr>
  </table>

  <p><strong>Indices and tables:</strong></p>
  <table class="contentstable" align="center"><tr>
    <td width="50%">
      <p class="biglink"><a class="biglink" href="py-modindex.html">Global Module Index</a><br/>
         <span class="linkdescr">quick access to all modules</span></p>
      <p class="biglink"><a class="biglink" href="genindex.html">General Index</a><br/>
         <span class="linkdescr">all functions, classes, terms</span></p>
      <p class="biglink"><a class="biglink" href="glossary.html">Glossary</a><br/>
         <span class="linkdescr">the most important terms explained</span></p>
    </td><td width="50%">
      <p class="biglink"><a class="biglink" href="search.html">Search page</a><br/>
         <span class="linkdescr">search this documentation</span></p>
      <p class="biglink"><a class="biglink" href="contents.html">Complete Table of Contents</a><br/>
         <span class="linkdescr">lists all sections and subsections</span></p>
    </td></tr>
  </table>

  <p><strong>Meta information:</strong></p>
  <table class="contentstable" align="center"><tr>
    <td width="50%">
      <p class="biglink"><a class="biglink" href="bugs.html">Reporting bugs</a></p>
      <p class="biglink"><a class="biglink" href="about.html">About the documentation</a></p>
    </td><td width="50%">
      <p class="biglink"><a class="biglink" href="license.html">History and License of Python</a></p>
      <p class="biglink"><a class="biglink" href="copyright.html">Copyright</a></p>
    </td></tr>
  </table>

          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<h3>Download</h3>
<p><a href="download.html">Download these documents</a></p>
<h3>Docs by version</h3>
<ul>
  <li><a href="https://docs.python.org/3.8/">Python 3.8 (in development)</a></li>
  <li><a href="https://docs.python.org/3.7/">Python 3.7 (stable)</a></li>
  <li><a href="https://docs.python.org/3.6/">Python 3.6 (security-fixes)</a></li>
  <li><a href="https://docs.python.org/3.5/">Python 3.5 (security-fixes)</a></li>
  <li><a href="https://docs.python.org/2.7/">Python 2.7 (stable)</a></li>
  <li><a href="https://www.python.org/doc/versions/">All versions</a></li>
</ul>

<h3>Other resources</h3>
<ul>
  
  <li><a href="https://www.python.org/dev/peps/">PEP Index</a></li>
  <li><a href="https://wiki.python.org/moin/BeginnersGuide">Beginner's Guide</a></li>
  <li><a href="https://wiki.python.org/moin/PythonBooks">Book List</a></li>
  <li><a href="https://www.python.org/doc/av/">Audio/Visual Talks</a></li>
</ul>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="#">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�5xՃ���html/license.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>History and License &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="next" title="Distributing Python Modules (Legacy version)" href="distutils/index.html" />
    <link rel="prev" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/license.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distutils/index.html" title="Distributing Python Modules (Legacy version)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="copyright.html" title="Copyright"
             accesskey="P">previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="history-and-license">
<span id="id1"></span><h1>History and License<a class="headerlink" href="#history-and-license" title="Permalink to this headline">¶</a></h1>
<div class="section" id="history-of-the-software">
<h2>History of the software<a class="headerlink" href="#history-of-the-software" title="Permalink to this headline">¶</a></h2>
<p>Python was created in the early 1990s by Guido van Rossum at Stichting
Mathematisch Centrum (CWI, see <a class="reference external" href="https://www.cwi.nl/">https://www.cwi.nl/</a>) in the Netherlands as a
successor of a language called ABC.  Guido remains Python’s principal author,
although it includes many contributions from others.</p>
<p>In 1995, Guido continued his work on Python at the Corporation for National
Research Initiatives (CNRI, see <a class="reference external" href="https://www.cnri.reston.va.us/">https://www.cnri.reston.va.us/</a>) in Reston,
Virginia where he released several versions of the software.</p>
<p>In May 2000, Guido and the Python core development team moved to BeOpen.com to
form the BeOpen PythonLabs team.  In October of the same year, the PythonLabs
team moved to Digital Creations (now Zope Corporation; see
<a class="reference external" href="http://www.zope.com/">http://www.zope.com/</a>).  In 2001, the Python Software Foundation (PSF, see
<a class="reference external" href="https://www.python.org/psf/">https://www.python.org/psf/</a>) was formed, a non-profit organization created
specifically to own Python-related Intellectual Property.  Zope Corporation is a
sponsoring member of the PSF.</p>
<p>All Python releases are Open Source (see <a class="reference external" href="https://opensource.org/">https://opensource.org/</a> for the Open
Source Definition). Historically, most, but not all, Python releases have also
been GPL-compatible; the table below summarizes the various releases.</p>
<table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="20%" />
<col width="16%" />
<col width="17%" />
<col width="24%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Release</th>
<th class="head">Derived from</th>
<th class="head">Year</th>
<th class="head">Owner</th>
<th class="head">GPL compatible?</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0.9.0 thru 1.2</td>
<td>n/a</td>
<td>1991-1995</td>
<td>CWI</td>
<td>yes</td>
</tr>
<tr class="row-odd"><td>1.3 thru 1.5.2</td>
<td>1.2</td>
<td>1995-1999</td>
<td>CNRI</td>
<td>yes</td>
</tr>
<tr class="row-even"><td>1.6</td>
<td>1.5.2</td>
<td>2000</td>
<td>CNRI</td>
<td>no</td>
</tr>
<tr class="row-odd"><td>2.0</td>
<td>1.6</td>
<td>2000</td>
<td>BeOpen.com</td>
<td>no</td>
</tr>
<tr class="row-even"><td>1.6.1</td>
<td>1.6</td>
<td>2001</td>
<td>CNRI</td>
<td>no</td>
</tr>
<tr class="row-odd"><td>2.1</td>
<td>2.0+1.6.1</td>
<td>2001</td>
<td>PSF</td>
<td>no</td>
</tr>
<tr class="row-even"><td>2.0.1</td>
<td>2.0+1.6.1</td>
<td>2001</td>
<td>PSF</td>
<td>yes</td>
</tr>
<tr class="row-odd"><td>2.1.1</td>
<td>2.1+2.0.1</td>
<td>2001</td>
<td>PSF</td>
<td>yes</td>
</tr>
<tr class="row-even"><td>2.1.2</td>
<td>2.1.1</td>
<td>2002</td>
<td>PSF</td>
<td>yes</td>
</tr>
<tr class="row-odd"><td>2.1.3</td>
<td>2.1.2</td>
<td>2002</td>
<td>PSF</td>
<td>yes</td>
</tr>
<tr class="row-even"><td>2.2 and above</td>
<td>2.1.1</td>
<td>2001-now</td>
<td>PSF</td>
<td>yes</td>
</tr>
</tbody>
</table>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">GPL-compatible doesn’t mean that we’re distributing Python under the GPL.  All
Python licenses, unlike the GPL, let you distribute a modified version without
making your changes open source. The GPL-compatible licenses make it possible to
combine Python with other software that is released under the GPL; the others
don’t.</p>
</div>
<p>Thanks to the many outside volunteers who have worked under Guido’s direction to
make these releases possible.</p>
</div>
<div class="section" id="terms-and-conditions-for-accessing-or-otherwise-using-python">
<h2>Terms and conditions for accessing or otherwise using Python<a class="headerlink" href="#terms-and-conditions-for-accessing-or-otherwise-using-python" title="Permalink to this headline">¶</a></h2>
<div class="section" id="psf-license-agreement-for-python-release">
<h3>PSF LICENSE AGREEMENT FOR PYTHON 2.7.16<a class="headerlink" href="#psf-license-agreement-for-python-release" title="Permalink to this headline">¶</a></h3>
<pre class="literal-block">
1. This LICENSE AGREEMENT is between the Python Software Foundation (&quot;PSF&quot;), and
   the Individual or Organization (&quot;Licensee&quot;) accessing and otherwise using Python
   2.7.16 software in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 2.7.16 alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., &quot;Copyright © 2001-2019 Python Software Foundation; All Rights
   Reserved&quot; are retained in Python 2.7.16 alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 2.7.16 or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python
   2.7.16.

4. PSF is making Python 2.7.16 available to Licensee on an &quot;AS IS&quot; basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON 2.7.16 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 2.7.16
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 2.7.16, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python 2.7.16, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.
</pre>
</div>
<div class="section" id="beopen-com-license-agreement-for-python-2-0">
<h3>BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0<a class="headerlink" href="#beopen-com-license-agreement-for-python-2-0" title="Permalink to this headline">¶</a></h3>
<p>BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1. This LICENSE AGREEMENT is between BeOpen.com (&quot;BeOpen&quot;), having an office at
   160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization
   (&quot;Licensee&quot;) accessing and otherwise using this software in source or binary
   form and its associated documentation (&quot;the Software&quot;).

2. Subject to the terms and conditions of this BeOpen Python License Agreement,
   BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license
   to reproduce, analyze, test, perform and/or display publicly, prepare derivative
   works, distribute, and otherwise use the Software alone or in any derivative
   version, provided, however, that the BeOpen Python License is retained in the
   Software, alone or in any derivative version prepared by Licensee.

3. BeOpen is making the Software available to Licensee on an &quot;AS IS&quot; basis.
   BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING,
   MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF
   ADVISED OF THE POSSIBILITY THEREOF.

5. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

6. This License Agreement shall be governed by and interpreted in all respects
   by the law of the State of California, excluding conflict of law provisions.
   Nothing in this License Agreement shall be deemed to create any relationship of
   agency, partnership, or joint venture between BeOpen and Licensee.  This License
   Agreement does not grant permission to use BeOpen trademarks or trade names in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.  As an exception, the &quot;BeOpen Python&quot; logos available at
   http://www.pythonlabs.com/logos.html may be used according to the permissions
   granted on that web page.

7. By copying, installing or otherwise using the software, Licensee agrees to be
   bound by the terms and conditions of this License Agreement.
</pre></div>
</div>
</div>
<div class="section" id="cnri-license-agreement-for-python-1-6-1">
<h3>CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1<a class="headerlink" href="#cnri-license-agreement-for-python-1-6-1" title="Permalink to this headline">¶</a></h3>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>1. This LICENSE AGREEMENT is between the Corporation for National Research
   Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191
   (&quot;CNRI&quot;), and the Individual or Organization (&quot;Licensee&quot;) accessing and
   otherwise using Python 1.6.1 software in source or binary form and its
   associated documentation.

2. Subject to the terms and conditions of this License Agreement, CNRI hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python 1.6.1 alone or in any derivative version,
   provided, however, that CNRI&#39;s License Agreement and CNRI&#39;s notice of copyright,
   i.e., &quot;Copyright © 1995-2001 Corporation for National Research Initiatives; All
   Rights Reserved&quot; are retained in Python 1.6.1 alone or in any derivative version
   prepared by Licensee.  Alternately, in lieu of CNRI&#39;s License Agreement,
   Licensee may substitute the following text (omitting the quotes): &quot;Python 1.6.1
   is made available subject to the terms and conditions in CNRI&#39;s License
   Agreement.  This Agreement together with Python 1.6.1 may be located on the
   Internet using the following unique, persistent identifier (known as a handle):
   1895.22/1013.  This Agreement may also be obtained from a proxy server on the
   Internet using the following URL: http://hdl.handle.net/1895.22/1013.&quot;

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python 1.6.1 or any part thereof, and wants to make the derivative
   work available to others as provided herein, then Licensee hereby agrees to
   include in any such work a brief summary of the changes made to Python 1.6.1.

4. CNRI is making Python 1.6.1 available to Licensee on an &quot;AS IS&quot; basis.  CNRI
   MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF EXAMPLE,
   BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY
   OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF
   PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR
   ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. This License Agreement shall be governed by the federal intellectual property
   law of the United States, including without limitation the federal copyright
   law, and, to the extent such U.S. federal law does not apply, by the law of the
   Commonwealth of Virginia, excluding Virginia&#39;s conflict of law provisions.
   Notwithstanding the foregoing, with regard to derivative works based on Python
   1.6.1 that incorporate non-separable material that was previously distributed
   under the GNU General Public License (GPL), the law of the Commonwealth of
   Virginia shall govern this License Agreement only as to issues arising under or
   with respect to Paragraphs 4, 5, and 7 of this License Agreement.  Nothing in
   this License Agreement shall be deemed to create any relationship of agency,
   partnership, or joint venture between CNRI and Licensee.  This License Agreement
   does not grant permission to use CNRI trademarks or trade name in a trademark
   sense to endorse or promote products or services of Licensee, or any third
   party.

8. By clicking on the &quot;ACCEPT&quot; button where indicated, or by copying, installing
   or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and
   conditions of this License Agreement.
</pre></div>
</div>
</div>
<div class="section" id="cwi-license-agreement-for-python-0-9-0-through-1-2">
<h3>CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2<a class="headerlink" href="#cwi-license-agreement-for-python-0-9-0-through-1-2" title="Permalink to this headline">¶</a></h3>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright © 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The
Netherlands.  All rights reserved.

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided that
the above copyright notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting documentation, and that
the name of Stichting Mathematisch Centrum or CWI not be used in advertising or
publicity pertaining to distribution of the software without specific, written
prior permission.

STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
</pre></div>
</div>
</div>
</div>
<div class="section" id="licenses-and-acknowledgements-for-incorporated-software">
<h2>Licenses and Acknowledgements for Incorporated Software<a class="headerlink" href="#licenses-and-acknowledgements-for-incorporated-software" title="Permalink to this headline">¶</a></h2>
<p>This section is an incomplete, but growing list of licenses and acknowledgements
for third-party software incorporated in the Python distribution.</p>
<div class="section" id="mersenne-twister">
<h3>Mersenne Twister<a class="headerlink" href="#mersenne-twister" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">_random</span></code> module includes code based on a download from
<a class="reference external" href="http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html">http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/emt19937ar.html</a>. The following are
the verbatim comments from the original code:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.

Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).

Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

 3. The names of its contributors may not be used to endorse or promote
    products derived from this software without specific prior written
    permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
&quot;AS IS&quot; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


Any feedback is very welcome.
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
</pre></div>
</div>
</div>
<div class="section" id="sockets">
<h3>Sockets<a class="headerlink" href="#sockets" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module uses the functions, <code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code>, and
<code class="xref py py-func docutils literal notranslate"><span class="pre">getnameinfo()</span></code>, which are coded in separate source files from the WIDE
Project, <a class="reference external" href="http://www.wide.ad.jp/">http://www.wide.ad.jp/</a>.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS&#39;&#39; AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
</pre></div>
</div>
</div>
<div class="section" id="floating-point-exception-control">
<h3>Floating point exception control<a class="headerlink" href="#floating-point-exception-control" title="Permalink to this headline">¶</a></h3>
<p>The source for the <a class="reference internal" href="library/fpectl.html#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module includes the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>  ---------------------------------------------------------------------
 /                       Copyright (c) 1996.                           \
|          The Regents of the University of California.                 |
|                        All rights reserved.                           |
|                                                                       |
|   Permission to use, copy, modify, and distribute this software for   |
|   any purpose without fee is hereby granted, provided that this en-   |
|   tire notice is included in all copies of any software which is or   |
|   includes  a  copy  or  modification  of  this software and in all   |
|   copies of the supporting documentation for such software.           |
|                                                                       |
|   This  work was produced at the University of California, Lawrence   |
|   Livermore National Laboratory under  contract  no.  W-7405-ENG-48   |
|   between  the  U.S.  Department  of  Energy and The Regents of the   |
|   University of California for the operation of UC LLNL.              |
|                                                                       |
|                              DISCLAIMER                               |
|                                                                       |
|   This  software was prepared as an account of work sponsored by an   |
|   agency of the United States Government. Neither the United States   |
|   Government  nor the University of California nor any of their em-   |
|   ployees, makes any warranty, express or implied, or  assumes  any   |
|   liability  or  responsibility  for the accuracy, completeness, or   |
|   usefulness of any information,  apparatus,  product,  or  process   |
|   disclosed,   or  represents  that  its  use  would  not  infringe   |
|   privately-owned rights. Reference herein to any specific  commer-   |
|   cial  products,  process,  or  service  by trade name, trademark,   |
|   manufacturer, or otherwise, does not  necessarily  constitute  or   |
|   imply  its endorsement, recommendation, or favoring by the United   |
|   States Government or the University of California. The views  and   |
|   opinions  of authors expressed herein do not necessarily state or   |
|   reflect those of the United States Government or  the  University   |
|   of  California,  and shall not be used for advertising or product   |
 \  endorsement purposes.                                              /
  ---------------------------------------------------------------------
</pre></div>
</div>
</div>
<div class="section" id="md5-message-digest-algorithm">
<h3>MD5 message digest algorithm<a class="headerlink" href="#md5-message-digest-algorithm" title="Permalink to this headline">¶</a></h3>
<p>The source code for the <a class="reference internal" href="library/md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> module contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (C) 1999, 2002 Aladdin Enterprises.  All rights reserved.

This software is provided &#39;as-is&#39;, without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.

L. Peter Deutsch
ghost@aladdin.com

Independent implementation of MD5 (RFC 1321).

This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
      http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A.  It does not include
any code or documentation that is identified in the RFC as being
copyrighted.

The original and principal author of md5.h is L. Peter Deutsch
&lt;ghost@aladdin.com&gt;.  Other authors are noted in the change history
that follows (in reverse chronological order):

2002-04-13 lpd Removed support for non-ANSI compilers; removed
      references to Ghostscript; clarified derivation from RFC 1321;
      now handles byte order either statically or dynamically.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5);
      added conditionalization for C++ compilation from Martin
      Purschke &lt;purschke@bnl.gov&gt;.
1999-05-03 lpd Original version.
</pre></div>
</div>
</div>
<div class="section" id="asynchronous-socket-services">
<h3>Asynchronous socket services<a class="headerlink" href="#asynchronous-socket-services" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/asynchat.html#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a> and <a class="reference internal" href="library/asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> modules contain the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright 1996 by Sam Rushing

                        All Rights Reserved

Permission to use, copy, modify, and distribute this software and
its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of Sam
Rushing not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="cookie-management">
<h3>Cookie management<a class="headerlink" href="#cookie-management" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright 2000 by Timothy O&#39;Malley &lt;timo@alum.mit.edu&gt;

               All Rights Reserved

Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Timothy O&#39;Malley  not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

Timothy O&#39;Malley DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS, IN NO EVENT SHALL Timothy O&#39;Malley BE LIABLE FOR
ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="execution-tracing">
<h3>Execution tracing<a class="headerlink" href="#execution-tracing" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/trace.html#module-trace" title="trace: Trace or track Python statement execution."><code class="xref py py-mod docutils literal notranslate"><span class="pre">trace</span></code></a> module contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>portions copyright 2001, Autonomous Zones Industries, Inc., all rights...
err...  reserved and offered to the public under the terms of the
Python 2.2 license.
Author: Zooko O&#39;Whielacronx
http://zooko.com/
mailto:zooko@zooko.com

Copyright 2000, Mojam Media, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1999, Bioreason, Inc., all rights reserved.
Author: Andrew Dalke

Copyright 1995-1997, Automatrix, Inc., all rights reserved.
Author: Skip Montanaro

Copyright 1991-1995, Stichting Mathematisch Centrum, all rights reserved.


Permission to use, copy, modify, and distribute this Python software and
its associated documentation for any purpose without fee is hereby
granted, provided that the above copyright notice appears in all copies,
and that both that copyright notice and this permission notice appear in
supporting documentation, and that the name of neither Automatrix,
Bioreason or Mojam Media be used in advertising or publicity pertaining to
distribution of the software without specific, written prior permission.
</pre></div>
</div>
</div>
<div class="section" id="uuencode-and-uudecode-functions">
<h3>UUencode and UUdecode functions<a class="headerlink" href="#uuencode-and-uudecode-functions" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/uu.html#module-uu" title="uu: Encode and decode files in uuencode format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">uu</span></code></a> module contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright 1994 by Lance Ellinghouse
Cathedral City, California Republic, United States of America.
                       All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Lance Ellinghouse
not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE CENTRUM BE LIABLE
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

Modified by Jack Jansen, CWI, July 1995:
- Use binascii module to do the actual line-by-line conversion
  between ascii and binary. This results in a 1000-fold speedup. The C
  version is still 5 times faster, though.
- Arguments more compliant with Python standard
</pre></div>
</div>
</div>
<div class="section" id="xml-remote-procedure-calls">
<h3>XML Remote Procedure Calls<a class="headerlink" href="#xml-remote-procedure-calls" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>    The XML-RPC client interface is

Copyright (c) 1999-2002 by Secret Labs AB
Copyright (c) 1999-2002 by Fredrik Lundh

By obtaining, using, and/or copying this software and/or its
associated documentation, you agree that you have read, understood,
and will comply with the following terms and conditions:

Permission to use, copy, modify, and distribute this software and
its associated documentation for any purpose and without fee is
hereby granted, provided that the above copyright notice appears in
all copies, and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
Secret Labs AB or the author not be used in advertising or publicity
pertaining to distribution of the software without specific, written
prior permission.

SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="test-epoll">
<h3>test_epoll<a class="headerlink" href="#test-epoll" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">test_epoll</span></code> contains the following notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (c) 2001-2006 Twisted Matrix Laboratories.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
&quot;Software&quot;), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="select-kqueue">
<h3>Select kqueue<a class="headerlink" href="#select-kqueue" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> and contains the following notice for the kqueue interface:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS&#39;&#39; AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
</pre></div>
</div>
</div>
<div class="section" id="strtod-and-dtoa">
<h3>strtod and dtoa<a class="headerlink" href="#strtod-and-dtoa" title="Permalink to this headline">¶</a></h3>
<p>The file <code class="file docutils literal notranslate"><span class="pre">Python/dtoa.c</span></code>, which supplies C functions dtoa and
strtod for conversion of C doubles to and from strings, is derived
from the file of the same name by David M. Gay, currently available
from <a class="reference external" href="http://www.netlib.org/fp/">http://www.netlib.org/fp/</a>.  The original file, as retrieved on
March 16, 2009, contains the following copyright and licensing
notice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>/****************************************************************
 *
 * The author of this software is David M. Gay.
 *
 * Copyright (c) 1991, 2000, 2001 by Lucent Technologies.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose without fee is hereby granted, provided that this entire notice
 * is included in all copies of any software which is or includes a copy
 * or modification of this software and in all copies of the supporting
 * documentation for such software.
 *
 * THIS SOFTWARE IS BEING PROVIDED &quot;AS IS&quot;, WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHOR NOR LUCENT MAKES ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 *
 ***************************************************************/
</pre></div>
</div>
</div>
<div class="section" id="openssl">
<h3>OpenSSL<a class="headerlink" href="#openssl" title="Permalink to this headline">¶</a></h3>
<p>The modules <a class="reference internal" href="library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a>, <a class="reference internal" href="library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a>, <a class="reference internal" href="library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a>, <a class="reference internal" href="library/crypt.html#module-crypt" title="crypt: The crypt() function used to check Unix passwords. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">crypt</span></code></a> use
the OpenSSL library for added performance if made available by the
operating system. Additionally, the Windows and Mac OS X installers for
Python may include a copy of the OpenSSL libraries, so we include a copy
of the OpenSSL license here:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>LICENSE ISSUES
==============

The OpenSSL toolkit stays under a dual license, i.e. both the conditions of
the OpenSSL License and the original SSLeay license apply to the toolkit.
See below for the actual license texts. Actually both licenses are BSD-style
Open Source licenses. In case of any license issues related to OpenSSL
please contact openssl-core@openssl.org.

OpenSSL License
---------------

  /* ====================================================================
   * Copyright (c) 1998-2008 The OpenSSL Project.  All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   *
   * 1. Redistributions of source code must retain the above copyright
   *    notice, this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in
   *    the documentation and/or other materials provided with the
   *    distribution.
   *
   * 3. All advertising materials mentioning features or use of this
   *    software must display the following acknowledgment:
   *    &quot;This product includes software developed by the OpenSSL Project
   *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)&quot;
   *
   * 4. The names &quot;OpenSSL Toolkit&quot; and &quot;OpenSSL Project&quot; must not be used to
   *    endorse or promote products derived from this software without
   *    prior written permission. For written permission, please contact
   *    openssl-core@openssl.org.
   *
   * 5. Products derived from this software may not be called &quot;OpenSSL&quot;
   *    nor may &quot;OpenSSL&quot; appear in their names without prior written
   *    permission of the OpenSSL Project.
   *
   * 6. Redistributions of any form whatsoever must retain the following
   *    acknowledgment:
   *    &quot;This product includes software developed by the OpenSSL Project
   *    for use in the OpenSSL Toolkit (http://www.openssl.org/)&quot;
   *
   * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS&#39;&#39; AND ANY
   * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
   * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
   * OF THE POSSIBILITY OF SUCH DAMAGE.
   * ====================================================================
   *
   * This product includes cryptographic software written by Eric Young
   * (eay@cryptsoft.com).  This product includes software written by Tim
   * Hudson (tjh@cryptsoft.com).
   *
   */

Original SSLeay License
-----------------------

  /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
   * All rights reserved.
   *
   * This package is an SSL implementation written
   * by Eric Young (eay@cryptsoft.com).
   * The implementation was written so as to conform with Netscapes SSL.
   *
   * This library is free for commercial and non-commercial use as long as
   * the following conditions are aheared to.  The following conditions
   * apply to all code found in this distribution, be it the RC4, RSA,
   * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
   * included with this distribution is covered by the same copyright terms
   * except that the holder is Tim Hudson (tjh@cryptsoft.com).
   *
   * Copyright remains Eric Young&#39;s, and as such any Copyright notices in
   * the code are not to be removed.
   * If this package is used in a product, Eric Young should be given attribution
   * as the author of the parts of the library used.
   * This can be in the form of a textual message at program startup or
   * in documentation (online or textual) provided with the package.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions
   * are met:
   * 1. Redistributions of source code must retain the copyright
   *    notice, this list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright
   *    notice, this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. All advertising materials mentioning features or use of this software
   *    must display the following acknowledgement:
   *    &quot;This product includes cryptographic software written by
   *     Eric Young (eay@cryptsoft.com)&quot;
   *    The word &#39;cryptographic&#39; can be left out if the rouines from the library
   *    being used are not cryptographic related :-).
   * 4. If you include any Windows specific code (or a derivative thereof) from
   *    the apps directory (application code) you must include an acknowledgement:
   *    &quot;This product includes software written by Tim Hudson (tjh@cryptsoft.com)&quot;
   *
   * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS&#39;&#39; AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
   * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
   * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
   * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
   * SUCH DAMAGE.
   *
   * The licence and distribution terms for any publically available version or
   * derivative of this code cannot be changed.  i.e. this code cannot simply be
   * copied and put under another distribution licence
   * [including the GNU Public Licence.]
   */
</pre></div>
</div>
</div>
<div class="section" id="expat">
<h3>expat<a class="headerlink" href="#expat" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> extension is built using an included copy of the expat
sources unless the build is configured <code class="docutils literal notranslate"><span class="pre">--with-system-expat</span></code>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (c) 1998, 1999, 2000 Thai Open Source Software Center Ltd
                               and Clark Cooper

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
&quot;Software&quot;), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="libffi">
<h3>libffi<a class="headerlink" href="#libffi" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">_ctypes</span></code> extension is built using an included copy of the libffi
sources unless the build is configured <code class="docutils literal notranslate"><span class="pre">--with-system-libffi</span></code>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (c) 1996-2008  Red Hat, Inc and others.

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
``Software&#39;&#39;), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED ``AS IS&#39;&#39;, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
</pre></div>
</div>
</div>
<div class="section" id="zlib">
<h3>zlib<a class="headerlink" href="#zlib" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> extension is built using an included copy of the zlib
sources if the zlib version found on the system is too old to be
used for the build:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler

This software is provided &#39;as-is&#39;, without any express or implied
warranty.  In no event will the authors be held liable for any damages
arising from the use of this software.

Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not
   claim that you wrote the original software. If you use this software
   in a product, an acknowledgment in the product documentation would be
   appreciated but is not required.

2. Altered source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

3. This notice may not be removed or altered from any source distribution.

Jean-loup Gailly        Mark Adler
jloup@gzip.org          madler@alumni.caltech.edu
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">History and License</a><ul>
<li><a class="reference internal" href="#history-of-the-software">History of the software</a></li>
<li><a class="reference internal" href="#terms-and-conditions-for-accessing-or-otherwise-using-python">Terms and conditions for accessing or otherwise using Python</a><ul>
<li><a class="reference internal" href="#psf-license-agreement-for-python-release">PSF LICENSE AGREEMENT FOR PYTHON 2.7.16</a></li>
<li><a class="reference internal" href="#beopen-com-license-agreement-for-python-2-0">BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0</a></li>
<li><a class="reference internal" href="#cnri-license-agreement-for-python-1-6-1">CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1</a></li>
<li><a class="reference internal" href="#cwi-license-agreement-for-python-0-9-0-through-1-2">CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2</a></li>
</ul>
</li>
<li><a class="reference internal" href="#licenses-and-acknowledgements-for-incorporated-software">Licenses and Acknowledgements for Incorporated Software</a><ul>
<li><a class="reference internal" href="#mersenne-twister">Mersenne Twister</a></li>
<li><a class="reference internal" href="#sockets">Sockets</a></li>
<li><a class="reference internal" href="#floating-point-exception-control">Floating point exception control</a></li>
<li><a class="reference internal" href="#md5-message-digest-algorithm">MD5 message digest algorithm</a></li>
<li><a class="reference internal" href="#asynchronous-socket-services">Asynchronous socket services</a></li>
<li><a class="reference internal" href="#cookie-management">Cookie management</a></li>
<li><a class="reference internal" href="#execution-tracing">Execution tracing</a></li>
<li><a class="reference internal" href="#uuencode-and-uudecode-functions">UUencode and UUdecode functions</a></li>
<li><a class="reference internal" href="#xml-remote-procedure-calls">XML Remote Procedure Calls</a></li>
<li><a class="reference internal" href="#test-epoll">test_epoll</a></li>
<li><a class="reference internal" href="#select-kqueue">Select kqueue</a></li>
<li><a class="reference internal" href="#strtod-and-dtoa">strtod and dtoa</a></li>
<li><a class="reference internal" href="#openssl">OpenSSL</a></li>
<li><a class="reference internal" href="#expat">expat</a></li>
<li><a class="reference internal" href="#libffi">libffi</a></li>
<li><a class="reference internal" href="#zlib">zlib</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="copyright.html"
                        title="previous chapter">Copyright</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="distutils/index.html"
                        title="next chapter">Distributing Python Modules (Legacy version)</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/license.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distutils/index.html" title="Distributing Python Modules (Legacy version)"
             >next</a> |</li>
        <li class="right" >
          <a href="copyright.html" title="Copyright"
             >previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\#��@�@�html/py-modindex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python Module Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />

    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/py-modindex.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    


    <script type="text/javascript">
      DOCUMENTATION_OPTIONS.COLLAPSE_INDEX = true;
    </script>


  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="#" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

   <h1>Python Module Index</h1>

   <div class="modindex-jumpbox">
   <a href="#cap-_"><strong>_</strong></a> | 
   <a href="#cap-a"><strong>a</strong></a> | 
   <a href="#cap-b"><strong>b</strong></a> | 
   <a href="#cap-c"><strong>c</strong></a> | 
   <a href="#cap-d"><strong>d</strong></a> | 
   <a href="#cap-e"><strong>e</strong></a> | 
   <a href="#cap-f"><strong>f</strong></a> | 
   <a href="#cap-g"><strong>g</strong></a> | 
   <a href="#cap-h"><strong>h</strong></a> | 
   <a href="#cap-i"><strong>i</strong></a> | 
   <a href="#cap-j"><strong>j</strong></a> | 
   <a href="#cap-k"><strong>k</strong></a> | 
   <a href="#cap-l"><strong>l</strong></a> | 
   <a href="#cap-m"><strong>m</strong></a> | 
   <a href="#cap-n"><strong>n</strong></a> | 
   <a href="#cap-o"><strong>o</strong></a> | 
   <a href="#cap-p"><strong>p</strong></a> | 
   <a href="#cap-q"><strong>q</strong></a> | 
   <a href="#cap-r"><strong>r</strong></a> | 
   <a href="#cap-s"><strong>s</strong></a> | 
   <a href="#cap-t"><strong>t</strong></a> | 
   <a href="#cap-u"><strong>u</strong></a> | 
   <a href="#cap-v"><strong>v</strong></a> | 
   <a href="#cap-w"><strong>w</strong></a> | 
   <a href="#cap-x"><strong>x</strong></a> | 
   <a href="#cap-z"><strong>z</strong></a>
   </div>

   <table class="indextable modindextable">
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-_"><td></td><td>
       <strong>_</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/__builtin__.html#module-__builtin__"><code class="xref">__builtin__</code></a></td><td>
       <em>The module that provides the built-in namespace.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/__future__.html#module-__future__"><code class="xref">__future__</code></a></td><td>
       <em>Future statement definitions</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/__main__.html#module-__main__"><code class="xref">__main__</code></a></td><td>
       <em>The environment where the top-level script is run.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/_winreg.html#module-_winreg"><code class="xref">_winreg</code></a> <em>(Windows)</em></td><td>
       <em>Routines and objects for manipulating the Windows registry.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-a"><td></td><td>
       <strong>a</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/abc.html#module-abc"><code class="xref">abc</code></a></td><td>
       <em>Abstract base classes according to PEP 3119.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/aepack.html#module-aepack"><code class="xref">aepack</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Conversion between Python variables and AppleEvent data containers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/aetools.html#module-aetools"><code class="xref">aetools</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Basic support for sending Apple Events</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/aetypes.html#module-aetypes"><code class="xref">aetypes</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Python representation of the Apple Event Object Model.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/aifc.html#module-aifc"><code class="xref">aifc</code></a></td><td>
       <em>Read and write audio files in AIFF or AIFC format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/al.html#module-al"><code class="xref">al</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Audio functions on the SGI.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/al.html#module-AL"><code class="xref">AL</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Constants used with the al module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/anydbm.html#module-anydbm"><code class="xref">anydbm</code></a></td><td>
       <em>Generic interface to DBM-style database modules.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-applesingle"><code class="xref">applesingle</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Rudimentary decoder for AppleSingle format files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/argparse.html#module-argparse"><code class="xref">argparse</code></a></td><td>
       <em>Command-line option and argument parsing library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/array.html#module-array"><code class="xref">array</code></a></td><td>
       <em>Space efficient arrays of uniformly typed numeric values.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ast.html#module-ast"><code class="xref">ast</code></a></td><td>
       <em>Abstract Syntax Tree classes and manipulation.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/asynchat.html#module-asynchat"><code class="xref">asynchat</code></a></td><td>
       <em>Support for asynchronous command/response protocols.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/asyncore.html#module-asyncore"><code class="xref">asyncore</code></a></td><td>
       <em>A base class for developing asynchronous socket handling
services.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/atexit.html#module-atexit"><code class="xref">atexit</code></a></td><td>
       <em>Register and execute cleanup functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/audioop.html#module-audioop"><code class="xref">audioop</code></a></td><td>
       <em>Manipulate raw audio data.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/autogil.html#module-autoGIL"><code class="xref">autoGIL</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Global Interpreter Lock handling in event loops.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-b"><td></td><td>
       <strong>b</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/base64.html#module-base64"><code class="xref">base64</code></a></td><td>
       <em>RFC 3548: Base16, Base32, Base64 Data Encodings</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/basehttpserver.html#module-BaseHTTPServer"><code class="xref">BaseHTTPServer</code></a></td><td>
       <em>Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/bastion.html#module-Bastion"><code class="xref">Bastion</code></a></td><td><strong>Deprecated:</strong>
       <em>Providing restricted access to objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/bdb.html#module-bdb"><code class="xref">bdb</code></a></td><td>
       <em>Debugger framework.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/binascii.html#module-binascii"><code class="xref">binascii</code></a></td><td>
       <em>Tools for converting between binary and various ASCII-encoded binary
representations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/binhex.html#module-binhex"><code class="xref">binhex</code></a></td><td>
       <em>Encode and decode files in binhex4 format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/bisect.html#module-bisect"><code class="xref">bisect</code></a></td><td>
       <em>Array bisection algorithms for binary searching.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/bsddb.html#module-bsddb"><code class="xref">bsddb</code></a></td><td>
       <em>Interface to Berkeley DB database library</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-buildtools"><code class="xref">buildtools</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Helper module for BuildApplet, BuildApplication and macfreeze.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/bz2.html#module-bz2"><code class="xref">bz2</code></a></td><td>
       <em>Interface to compression and decompression routines compatible with bzip2.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-c"><td></td><td>
       <strong>c</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/calendar.html#module-calendar"><code class="xref">calendar</code></a></td><td>
       <em>Functions for working with calendars, including some emulation of the Unix cal
program.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-1" style="display: none" alt="-" /></td>
       <td>
       <code class="xref">Carbon</code></td><td>
       <em></em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.AE"><code class="xref">Carbon.AE</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Apple Events toolbox.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.AH"><code class="xref">Carbon.AH</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Apple Help manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.App"><code class="xref">Carbon.App</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Appearance Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Appearance"><code class="xref">Carbon.Appearance</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constant definitions for the interface to the Appearance Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CarbonEvents"><code class="xref">Carbon.CarbonEvents</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon Event Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CarbonEvt"><code class="xref">Carbon.CarbonEvt</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon Event Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CF"><code class="xref">Carbon.CF</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Core Foundation.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CG"><code class="xref">Carbon.CG</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to Core Graphics.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Cm"><code class="xref">Carbon.Cm</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Component Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Components"><code class="xref">Carbon.Components</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Component Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.ControlAccessor"><code class="xref">Carbon.ControlAccessor</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Accessor functions for the interface to the Control Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Controls"><code class="xref">Carbon.Controls</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Control Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CoreFounation"><code class="xref">Carbon.CoreFounation</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to CoreFoundation.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.CoreGraphics"><code class="xref">Carbon.CoreGraphics</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to CoreGraphics.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Ctl"><code class="xref">Carbon.Ctl</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Control Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Dialogs"><code class="xref">Carbon.Dialogs</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Dialog Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Dlg"><code class="xref">Carbon.Dlg</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Dialog Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Drag"><code class="xref">Carbon.Drag</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Drag and Drop Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Dragconst"><code class="xref">Carbon.Dragconst</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Drag and Drop Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Events"><code class="xref">Carbon.Events</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the classic Event Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Evt"><code class="xref">Carbon.Evt</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the classic Event Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.File"><code class="xref">Carbon.File</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the File Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Files"><code class="xref">Carbon.Files</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the File Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Fm"><code class="xref">Carbon.Fm</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Font Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Folder"><code class="xref">Carbon.Folder</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Folder Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Folders"><code class="xref">Carbon.Folders</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Folder Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Fonts"><code class="xref">Carbon.Fonts</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Font Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Help"><code class="xref">Carbon.Help</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon Help Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.IBCarbon"><code class="xref">Carbon.IBCarbon</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon InterfaceBuilder support libraries.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.IBCarbonRuntime"><code class="xref">Carbon.IBCarbonRuntime</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon InterfaceBuilder support libraries.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Icns"><code class="xref">Carbon.Icns</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon Icon Manager</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Icons"><code class="xref">Carbon.Icons</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon Icon Manager</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Launch"><code class="xref">Carbon.Launch</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon Launch Services.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.LaunchServices"><code class="xref">Carbon.LaunchServices</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon Launch Services.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.List"><code class="xref">Carbon.List</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the List Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Lists"><code class="xref">Carbon.Lists</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the List Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.MacHelp"><code class="xref">Carbon.MacHelp</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon Help Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.MediaDescr"><code class="xref">Carbon.MediaDescr</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Parsers and generators for Quicktime Media descriptors</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Menu"><code class="xref">Carbon.Menu</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Menu Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Menus"><code class="xref">Carbon.Menus</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Menu Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Mlte"><code class="xref">Carbon.Mlte</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the MultiLingual Text Editor.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.OSA"><code class="xref">Carbon.OSA</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Carbon OSA Library.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.OSAconst"><code class="xref">Carbon.OSAconst</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Carbon OSA Library.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Qd"><code class="xref">Carbon.Qd</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the QuickDraw toolbox.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Qdoffs"><code class="xref">Carbon.Qdoffs</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the QuickDraw Offscreen APIs.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.QDOffscreen"><code class="xref">Carbon.QDOffscreen</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the QuickDraw Offscreen APIs.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Qt"><code class="xref">Carbon.Qt</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the QuickTime toolbox.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.QuickDraw"><code class="xref">Carbon.QuickDraw</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the QuickDraw toolbox.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.QuickTime"><code class="xref">Carbon.QuickTime</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the QuickTime toolbox.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Res"><code class="xref">Carbon.Res</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Resource Manager and Handles.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Resources"><code class="xref">Carbon.Resources</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Resource Manager and Handles.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Scrap"><code class="xref">Carbon.Scrap</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>The Scrap Manager provides basic services for implementing cut &amp; paste and
clipboard operations.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Snd"><code class="xref">Carbon.Snd</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Sound Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Sound"><code class="xref">Carbon.Sound</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Sound Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.TE"><code class="xref">Carbon.TE</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to TextEdit.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.TextEdit"><code class="xref">Carbon.TextEdit</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to TextEdit.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Win"><code class="xref">Carbon.Win</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the Window Manager.</em></td></tr>
     <tr class="cg-1">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/carbon.html#module-Carbon.Windows"><code class="xref">Carbon.Windows</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for the interface to the Window Manager.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cd.html#module-cd"><code class="xref">cd</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the CD-ROM on Silicon Graphics systems.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-cfmfile"><code class="xref">cfmfile</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Code Fragment Resource module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cgi.html#module-cgi"><code class="xref">cgi</code></a></td><td>
       <em>Helpers for running Python scripts via the Common Gateway Interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cgihttpserver.html#module-CGIHTTPServer"><code class="xref">CGIHTTPServer</code></a></td><td>
       <em>This module provides a request handler for HTTP servers which can run CGI
scripts.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cgitb.html#module-cgitb"><code class="xref">cgitb</code></a></td><td>
       <em>Configurable traceback handler for CGI scripts.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/chunk.html#module-chunk"><code class="xref">chunk</code></a></td><td>
       <em>Module to read IFF chunks.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cmath.html#module-cmath"><code class="xref">cmath</code></a></td><td>
       <em>Mathematical functions for complex numbers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cmd.html#module-cmd"><code class="xref">cmd</code></a></td><td>
       <em>Build line-oriented command interpreters.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/code.html#module-code"><code class="xref">code</code></a></td><td>
       <em>Facilities to implement read-eval-print loops.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/codecs.html#module-codecs"><code class="xref">codecs</code></a></td><td>
       <em>Encode and decode data and streams.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/codeop.html#module-codeop"><code class="xref">codeop</code></a></td><td>
       <em>Compile (possibly incomplete) Python code.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/collections.html#module-collections"><code class="xref">collections</code></a></td><td>
       <em>High-performance datatypes</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/colorpicker.html#module-ColorPicker"><code class="xref">ColorPicker</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to the standard color selection dialog.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/colorsys.html#module-colorsys"><code class="xref">colorsys</code></a></td><td>
       <em>Conversion functions between RGB and other color systems.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/commands.html#module-commands"><code class="xref">commands</code></a> <em>(Unix)</em></td><td><strong>Deprecated:</strong>
       <em>Utility functions for running external commands.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/compileall.html#module-compileall"><code class="xref">compileall</code></a></td><td>
       <em>Tools for byte-compiling all Python source files in a directory tree.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-2" style="display: none" alt="-" /></td>
       <td>
       <a href="library/compiler.html#module-compiler"><code class="xref">compiler</code></a></td><td><strong>Deprecated:</strong>
       <em>Python code compiler written in Python.</em></td></tr>
     <tr class="cg-2">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/compiler.html#module-compiler.ast"><code class="xref">compiler.ast</code></a></td><td>
       <em></em></td></tr>
     <tr class="cg-2">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/compiler.html#module-compiler.visitor"><code class="xref">compiler.visitor</code></a></td><td>
       <em></em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/configparser.html#module-ConfigParser"><code class="xref">ConfigParser</code></a></td><td>
       <em>Configuration file parser.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/contextlib.html#module-contextlib"><code class="xref">contextlib</code></a></td><td>
       <em>Utilities for with-statement contexts.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cookie.html#module-Cookie"><code class="xref">Cookie</code></a></td><td>
       <em>Support for HTTP state management (cookies).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/cookielib.html#module-cookielib"><code class="xref">cookielib</code></a></td><td>
       <em>Classes for automatic handling of HTTP cookies.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/copy.html#module-copy"><code class="xref">copy</code></a></td><td>
       <em>Shallow and deep copy operations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/copy_reg.html#module-copy_reg"><code class="xref">copy_reg</code></a></td><td>
       <em>Register pickle support functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pickle.html#module-cPickle"><code class="xref">cPickle</code></a></td><td>
       <em>Faster version of pickle, but not subclassable.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/profile.html#module-cProfile"><code class="xref">cProfile</code></a></td><td>
       <em></em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/crypt.html#module-crypt"><code class="xref">crypt</code></a> <em>(Unix)</em></td><td>
       <em>The crypt() function used to check Unix passwords.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/stringio.html#module-cStringIO"><code class="xref">cStringIO</code></a></td><td>
       <em>Faster version of StringIO, but not subclassable.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/csv.html#module-csv"><code class="xref">csv</code></a></td><td>
       <em>Write and read tabular data to and from delimited files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ctypes.html#module-ctypes"><code class="xref">ctypes</code></a></td><td>
       <em>A foreign function library for Python.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-3" style="display: none" alt="-" /></td>
       <td>
       <a href="library/curses.html#module-curses"><code class="xref">curses</code></a> <em>(Unix)</em></td><td>
       <em>An interface to the curses library, providing portable terminal
handling.</em></td></tr>
     <tr class="cg-3">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/curses.ascii.html#module-curses.ascii"><code class="xref">curses.ascii</code></a></td><td>
       <em>Constants and set-membership functions for ASCII characters.</em></td></tr>
     <tr class="cg-3">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/curses.panel.html#module-curses.panel"><code class="xref">curses.panel</code></a></td><td>
       <em>A panel stack extension that adds depth to  curses windows.</em></td></tr>
     <tr class="cg-3">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/curses.html#module-curses.textpad"><code class="xref">curses.textpad</code></a></td><td>
       <em>Emacs-like input editing in a curses window.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-d"><td></td><td>
       <strong>d</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/datetime.html#module-datetime"><code class="xref">datetime</code></a></td><td>
       <em>Basic date and time types.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dbhash.html#module-dbhash"><code class="xref">dbhash</code></a></td><td>
       <em>DBM-style interface to the BSD database library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dbm.html#module-dbm"><code class="xref">dbm</code></a> <em>(Unix)</em></td><td>
       <em>The standard &#34;database&#34; interface, based on ndbm.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/decimal.html#module-decimal"><code class="xref">decimal</code></a></td><td>
       <em>Implementation of the General Decimal Arithmetic  Specification.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gl.html#module-DEVICE"><code class="xref">DEVICE</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Constants used with the gl module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/difflib.html#module-difflib"><code class="xref">difflib</code></a></td><td>
       <em>Helpers for computing differences between objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dircache.html#module-dircache"><code class="xref">dircache</code></a></td><td><strong>Deprecated:</strong>
       <em>Return directory listing, with cache mechanism.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dis.html#module-dis"><code class="xref">dis</code></a></td><td>
       <em>Disassembler for Python bytecode.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-4" style="display: none" alt="-" /></td>
       <td>
       <a href="library/distutils.html#module-distutils"><code class="xref">distutils</code></a></td><td>
       <em>Support for building and installing Python modules into an
existing Python installation.</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.archive_util"><code class="xref">distutils.archive_util</code></a></td><td>
       <em>Utility functions for creating archive files (tarballs, zip files, ...)</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.bcppcompiler"><code class="xref">distutils.bcppcompiler</code></a></td><td>
       <em></em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.ccompiler"><code class="xref">distutils.ccompiler</code></a></td><td>
       <em>Abstract CCompiler class</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.cmd"><code class="xref">distutils.cmd</code></a></td><td>
       <em>This module provides the abstract base class Command. This class
is subclassed by the modules in the distutils.command subpackage.</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command"><code class="xref">distutils.command</code></a></td><td>
       <em>This subpackage contains one module for each standard Distutils command.</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist"><code class="xref">distutils.command.bdist</code></a></td><td>
       <em>Build a binary installer for a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist_dumb"><code class="xref">distutils.command.bdist_dumb</code></a></td><td>
       <em>Build a &#34;dumb&#34; installer - a simple archive of files</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist_msi"><code class="xref">distutils.command.bdist_msi</code></a></td><td>
       <em>Build a binary distribution as a Windows MSI file</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist_packager"><code class="xref">distutils.command.bdist_packager</code></a></td><td>
       <em>Abstract base class for packagers</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist_rpm"><code class="xref">distutils.command.bdist_rpm</code></a></td><td>
       <em>Build a binary distribution as a Redhat RPM and SRPM</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.bdist_wininst"><code class="xref">distutils.command.bdist_wininst</code></a></td><td>
       <em>Build a Windows installer</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.build"><code class="xref">distutils.command.build</code></a></td><td>
       <em>Build all files of a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.build_clib"><code class="xref">distutils.command.build_clib</code></a></td><td>
       <em>Build any C libraries in a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.build_ext"><code class="xref">distutils.command.build_ext</code></a></td><td>
       <em>Build any extensions in a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.build_py"><code class="xref">distutils.command.build_py</code></a></td><td>
       <em>Build the .py/.pyc files of a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.build_scripts"><code class="xref">distutils.command.build_scripts</code></a></td><td>
       <em>Build the scripts of a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.check"><code class="xref">distutils.command.check</code></a></td><td>
       <em>Check the metadata of a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.clean"><code class="xref">distutils.command.clean</code></a></td><td>
       <em>Clean a package build area</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.config"><code class="xref">distutils.command.config</code></a></td><td>
       <em>Perform package configuration</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.install"><code class="xref">distutils.command.install</code></a></td><td>
       <em>Install a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.install_data"><code class="xref">distutils.command.install_data</code></a></td><td>
       <em>Install data files from a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.install_headers"><code class="xref">distutils.command.install_headers</code></a></td><td>
       <em>Install C/C++ header files from a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.install_lib"><code class="xref">distutils.command.install_lib</code></a></td><td>
       <em>Install library files from a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.install_scripts"><code class="xref">distutils.command.install_scripts</code></a></td><td>
       <em>Install script files from a package</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.register"><code class="xref">distutils.command.register</code></a></td><td>
       <em>Register a module with the Python Package Index</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.command.sdist"><code class="xref">distutils.command.sdist</code></a></td><td>
       <em>Build a source distribution</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.core"><code class="xref">distutils.core</code></a></td><td>
       <em>The core Distutils functionality</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.cygwinccompiler"><code class="xref">distutils.cygwinccompiler</code></a></td><td>
       <em></em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.debug"><code class="xref">distutils.debug</code></a></td><td>
       <em>Provides the debug flag for distutils</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.dep_util"><code class="xref">distutils.dep_util</code></a></td><td>
       <em>Utility functions for simple dependency checking</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.dir_util"><code class="xref">distutils.dir_util</code></a></td><td>
       <em>Utility functions for operating on directories and directory trees</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.dist"><code class="xref">distutils.dist</code></a></td><td>
       <em>Provides the Distribution class, which represents the module distribution being
built/installed/distributed</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.emxccompiler"><code class="xref">distutils.emxccompiler</code></a></td><td>
       <em>OS/2 EMX Compiler support</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.errors"><code class="xref">distutils.errors</code></a></td><td>
       <em>Provides standard distutils exceptions</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.extension"><code class="xref">distutils.extension</code></a></td><td>
       <em>Provides the Extension class, used to describe C/C++ extension modules in setup
scripts</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.fancy_getopt"><code class="xref">distutils.fancy_getopt</code></a></td><td>
       <em>Additional getopt functionality</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.file_util"><code class="xref">distutils.file_util</code></a></td><td>
       <em>Utility functions for operating on single files</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.filelist"><code class="xref">distutils.filelist</code></a></td><td>
       <em>The FileList class, used for poking about the file system and
building lists of files.</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.log"><code class="xref">distutils.log</code></a></td><td>
       <em>A simple logging mechanism, 282-style</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.msvccompiler"><code class="xref">distutils.msvccompiler</code></a></td><td>
       <em>Microsoft Compiler</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.spawn"><code class="xref">distutils.spawn</code></a></td><td>
       <em>Provides the spawn() function</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.sysconfig"><code class="xref">distutils.sysconfig</code></a></td><td>
       <em>Low-level access to configuration information of the Python interpreter.</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.text_file"><code class="xref">distutils.text_file</code></a></td><td>
       <em>provides the TextFile class, a simple interface to text files</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.unixccompiler"><code class="xref">distutils.unixccompiler</code></a></td><td>
       <em>UNIX C Compiler</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.util"><code class="xref">distutils.util</code></a></td><td>
       <em>Miscellaneous other utility functions</em></td></tr>
     <tr class="cg-4">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="distutils/apiref.html#module-distutils.version"><code class="xref">distutils.version</code></a></td><td>
       <em>implements classes that represent module version numbers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dl.html#module-dl"><code class="xref">dl</code></a> <em>(Unix)</em></td><td><strong>Deprecated:</strong>
       <em>Call C functions in shared objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/doctest.html#module-doctest"><code class="xref">doctest</code></a></td><td>
       <em>Test pieces of code within docstrings.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/docxmlrpcserver.html#module-DocXMLRPCServer"><code class="xref">DocXMLRPCServer</code></a></td><td>
       <em>Self-documenting XML-RPC server implementation.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dumbdbm.html#module-dumbdbm"><code class="xref">dumbdbm</code></a></td><td>
       <em>Portable implementation of the simple DBM interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dummy_thread.html#module-dummy_thread"><code class="xref">dummy_thread</code></a></td><td>
       <em>Drop-in replacement for the thread module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/dummy_threading.html#module-dummy_threading"><code class="xref">dummy_threading</code></a></td><td>
       <em>Drop-in replacement for the threading module.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-e"><td></td><td>
       <strong>e</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/easydialogs.html#module-EasyDialogs"><code class="xref">EasyDialogs</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Basic Macintosh dialogs.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-5" style="display: none" alt="-" /></td>
       <td>
       <a href="library/email.html#module-email"><code class="xref">email</code></a></td><td>
       <em>Package supporting the parsing, manipulating, and generating email messages,
including MIME documents.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.charset.html#module-email.charset"><code class="xref">email.charset</code></a></td><td>
       <em>Character Sets</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.encoders.html#module-email.encoders"><code class="xref">email.encoders</code></a></td><td>
       <em>Encoders for email message payloads.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.errors.html#module-email.errors"><code class="xref">email.errors</code></a></td><td>
       <em>The exception classes used by the email package.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.generator.html#module-email.generator"><code class="xref">email.generator</code></a></td><td>
       <em>Generate flat text email messages from a message structure.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.header.html#module-email.header"><code class="xref">email.header</code></a></td><td>
       <em>Representing non-ASCII headers</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.iterators.html#module-email.iterators"><code class="xref">email.iterators</code></a></td><td>
       <em>Iterate over a  message object tree.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.message.html#module-email.message"><code class="xref">email.message</code></a></td><td>
       <em>The base class representing email messages.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.mime.html#module-email.mime"><code class="xref">email.mime</code></a></td><td>
       <em>Build MIME messages.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.parser.html#module-email.parser"><code class="xref">email.parser</code></a></td><td>
       <em>Parse flat text email messages to produce a message object structure.</em></td></tr>
     <tr class="cg-5">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/email.utils.html#module-email.utils"><code class="xref">email.utils</code></a></td><td>
       <em>Miscellaneous email package utilities.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-6" style="display: none" alt="-" /></td>
       <td>
       <code class="xref">encodings</code></td><td>
       <em></em></td></tr>
     <tr class="cg-6">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/codecs.html#module-encodings.idna"><code class="xref">encodings.idna</code></a></td><td>
       <em>Internationalized Domain Names implementation</em></td></tr>
     <tr class="cg-6">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/codecs.html#module-encodings.utf_8_sig"><code class="xref">encodings.utf_8_sig</code></a></td><td>
       <em>UTF-8 codec with BOM signature</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ensurepip.html#module-ensurepip"><code class="xref">ensurepip</code></a></td><td>
       <em>Bootstrapping the ``pip`` installer into an existing Python
installation or virtual environment.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/errno.html#module-errno"><code class="xref">errno</code></a></td><td>
       <em>Standard errno system symbols.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/exceptions.html#module-exceptions"><code class="xref">exceptions</code></a></td><td>
       <em>Standard exception classes.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-f"><td></td><td>
       <strong>f</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fcntl.html#module-fcntl"><code class="xref">fcntl</code></a> <em>(Unix)</em></td><td>
       <em>The fcntl() and ioctl() system calls.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/filecmp.html#module-filecmp"><code class="xref">filecmp</code></a></td><td>
       <em>Compare files efficiently.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fileinput.html#module-fileinput"><code class="xref">fileinput</code></a></td><td>
       <em>Loop over standard input or a list of files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/macostools.html#module-findertools"><code class="xref">findertools</code></a> <em>(Mac)</em></td><td>
       <em>Wrappers around the finder&#39;s Apple Events interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fl.html#module-fl"><code class="xref">fl</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>FORMS library for applications with graphical user interfaces.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fl.html#module-FL"><code class="xref">FL</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Constants used with the fl module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fl.html#module-flp"><code class="xref">flp</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Functions for loading stored FORMS designs.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fm.html#module-fm"><code class="xref">fm</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Font Manager interface for SGI workstations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fnmatch.html#module-fnmatch"><code class="xref">fnmatch</code></a></td><td>
       <em>Unix shell style filename pattern matching.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/formatter.html#module-formatter"><code class="xref">formatter</code></a></td><td>
       <em>Generic output formatter and device interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fpectl.html#module-fpectl"><code class="xref">fpectl</code></a> <em>(Unix)</em></td><td>
       <em>Provide control for floating point exception handling.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fpformat.html#module-fpformat"><code class="xref">fpformat</code></a></td><td><strong>Deprecated:</strong>
       <em>General floating point formatting functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/fractions.html#module-fractions"><code class="xref">fractions</code></a></td><td>
       <em>Rational numbers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/framework.html#module-FrameWork"><code class="xref">FrameWork</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interactive application framework.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ftplib.html#module-ftplib"><code class="xref">ftplib</code></a></td><td>
       <em>FTP protocol client (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/functools.html#module-functools"><code class="xref">functools</code></a></td><td>
       <em>Higher-order functions and operations on callable objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/future_builtins.html#module-future_builtins"><code class="xref">future_builtins</code></a></td><td>
       <em></em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-g"><td></td><td>
       <strong>g</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gc.html#module-gc"><code class="xref">gc</code></a></td><td>
       <em>Interface to the cycle-detecting garbage collector.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gdbm.html#module-gdbm"><code class="xref">gdbm</code></a> <em>(Unix)</em></td><td>
       <em>GNU&#39;s reinterpretation of dbm.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gensuitemodule.html#module-gensuitemodule"><code class="xref">gensuitemodule</code></a> <em>(Mac)</em></td><td>
       <em>Create a stub package from an OSA dictionary</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/getopt.html#module-getopt"><code class="xref">getopt</code></a></td><td>
       <em>Portable parser for command line options; support both short and long option
names.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/getpass.html#module-getpass"><code class="xref">getpass</code></a></td><td>
       <em>Portable reading of passwords and retrieval of the userid.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gettext.html#module-gettext"><code class="xref">gettext</code></a></td><td>
       <em>Multilingual internationalization services.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gl.html#module-gl"><code class="xref">gl</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Functions from the Silicon Graphics Graphics Library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gl.html#module-GL"><code class="xref">GL</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Constants used with the gl module.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/glob.html#module-glob"><code class="xref">glob</code></a></td><td>
       <em>Unix shell style pathname pattern expansion.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/grp.html#module-grp"><code class="xref">grp</code></a> <em>(Unix)</em></td><td>
       <em>The group database (getgrnam() and friends).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/gzip.html#module-gzip"><code class="xref">gzip</code></a></td><td>
       <em>Interfaces for gzip compression and decompression using file objects.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-h"><td></td><td>
       <strong>h</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/hashlib.html#module-hashlib"><code class="xref">hashlib</code></a></td><td>
       <em>Secure hash and message digest algorithms.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/heapq.html#module-heapq"><code class="xref">heapq</code></a></td><td>
       <em>Heap queue algorithm (a.k.a. priority queue).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/hmac.html#module-hmac"><code class="xref">hmac</code></a></td><td>
       <em>Keyed-Hashing for Message Authentication (HMAC) implementation</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-7" style="display: none" alt="-" /></td>
       <td>
       <a href="library/hotshot.html#module-hotshot"><code class="xref">hotshot</code></a></td><td>
       <em>High performance logging profiler, mostly written in C.</em></td></tr>
     <tr class="cg-7">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/hotshot.html#module-hotshot.stats"><code class="xref">hotshot.stats</code></a></td><td>
       <em>Statistical analysis for Hotshot</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/htmllib.html#module-htmlentitydefs"><code class="xref">htmlentitydefs</code></a></td><td>
       <em>Definitions of HTML general entities.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/htmllib.html#module-htmllib"><code class="xref">htmllib</code></a></td><td><strong>Deprecated:</strong>
       <em>A parser for HTML documents.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/htmlparser.html#module-HTMLParser"><code class="xref">HTMLParser</code></a></td><td>
       <em>A simple parser that can handle HTML and XHTML.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/httplib.html#module-httplib"><code class="xref">httplib</code></a></td><td>
       <em>HTTP and HTTPS protocol client (requires sockets).</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-i"><td></td><td>
       <strong>i</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ic.html#module-ic"><code class="xref">ic</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Access to the Mac OS X Internet Config.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-icopen"><code class="xref">icopen</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Internet Config replacement for open().</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imageop.html#module-imageop"><code class="xref">imageop</code></a></td><td><strong>Deprecated:</strong>
       <em>Manipulate raw image data.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imaplib.html#module-imaplib"><code class="xref">imaplib</code></a></td><td>
       <em>IMAP4 protocol client (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imgfile.html#module-imgfile"><code class="xref">imgfile</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Support for SGI imglib files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imghdr.html#module-imghdr"><code class="xref">imghdr</code></a></td><td>
       <em>Determine the type of image contained in a file or byte stream.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imp.html#module-imp"><code class="xref">imp</code></a></td><td>
       <em>Access the implementation of the import statement.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/importlib.html#module-importlib"><code class="xref">importlib</code></a></td><td>
       <em>Convenience wrappers for __import__</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/imputil.html#module-imputil"><code class="xref">imputil</code></a></td><td><strong>Deprecated:</strong>
       <em>Manage and augment the import process.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/inspect.html#module-inspect"><code class="xref">inspect</code></a></td><td>
       <em>Extract information and source code from live objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/io.html#module-io"><code class="xref">io</code></a></td><td>
       <em>Core tools for working with streams.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/itertools.html#module-itertools"><code class="xref">itertools</code></a></td><td>
       <em>Functions creating iterators for efficient looping.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-j"><td></td><td>
       <strong>j</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/jpeg.html#module-jpeg"><code class="xref">jpeg</code></a> <em>(IRIX)</em></td><td><strong>Deprecated:</strong>
       <em>Read and write image files in compressed JPEG format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/json.html#module-json"><code class="xref">json</code></a></td><td>
       <em>Encode and decode the JSON format.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-k"><td></td><td>
       <strong>k</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/keyword.html#module-keyword"><code class="xref">keyword</code></a></td><td>
       <em>Test whether a string is a keyword in Python.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-l"><td></td><td>
       <strong>l</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/2to3.html#module-lib2to3"><code class="xref">lib2to3</code></a></td><td>
       <em>the 2to3 library</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/linecache.html#module-linecache"><code class="xref">linecache</code></a></td><td>
       <em>This module provides random access to individual lines from text files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/locale.html#module-locale"><code class="xref">locale</code></a></td><td>
       <em>Internationalization services.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-8" style="display: none" alt="-" /></td>
       <td>
       <a href="library/logging.html#module-logging"><code class="xref">logging</code></a></td><td>
       <em>Flexible event logging system for applications.</em></td></tr>
     <tr class="cg-8">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/logging.config.html#module-logging.config"><code class="xref">logging.config</code></a></td><td>
       <em>Configuration of the logging module.</em></td></tr>
     <tr class="cg-8">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/logging.handlers.html#module-logging.handlers"><code class="xref">logging.handlers</code></a></td><td>
       <em>Handlers for the logging module.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-m"><td></td><td>
       <strong>m</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-macerrors"><code class="xref">macerrors</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Constant definitions for many Mac OS error codes.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/macos.html#module-MacOS"><code class="xref">MacOS</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Access to Mac OS-specific interpreter features.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/macostools.html#module-macostools"><code class="xref">macostools</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Convenience routines for file manipulation.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/macpath.html#module-macpath"><code class="xref">macpath</code></a></td><td>
       <em>Mac OS 9 path manipulation functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-macresource"><code class="xref">macresource</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Locate script resources.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mailbox.html#module-mailbox"><code class="xref">mailbox</code></a></td><td>
       <em>Manipulate mailboxes in various formats</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mailcap.html#module-mailcap"><code class="xref">mailcap</code></a></td><td>
       <em>Mailcap file handling.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/marshal.html#module-marshal"><code class="xref">marshal</code></a></td><td>
       <em>Convert Python objects to streams of bytes and back (with different
constraints).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/math.html#module-math"><code class="xref">math</code></a></td><td>
       <em>Mathematical functions (sin() etc.).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/md5.html#module-md5"><code class="xref">md5</code></a></td><td><strong>Deprecated:</strong>
       <em>RSA&#39;s MD5 message digest algorithm.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mhlib.html#module-mhlib"><code class="xref">mhlib</code></a></td><td><strong>Deprecated:</strong>
       <em>Manipulate MH mailboxes from Python.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mimetools.html#module-mimetools"><code class="xref">mimetools</code></a></td><td><strong>Deprecated:</strong>
       <em>Tools for parsing MIME-style message bodies.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mimetypes.html#module-mimetypes"><code class="xref">mimetypes</code></a></td><td>
       <em>Mapping of filename extensions to MIME types.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mimewriter.html#module-MimeWriter"><code class="xref">MimeWriter</code></a></td><td><strong>Deprecated:</strong>
       <em>Write MIME format files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mimify.html#module-mimify"><code class="xref">mimify</code></a></td><td><strong>Deprecated:</strong>
       <em>Mimification and unmimification of mail messages.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/miniaeframe.html#module-MiniAEFrame"><code class="xref">MiniAEFrame</code></a> <em>(Mac)</em></td><td>
       <em>Support to act as an Open Scripting Architecture (OSA) server (&#34;Apple Events&#34;).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mmap.html#module-mmap"><code class="xref">mmap</code></a></td><td>
       <em>Interface to memory-mapped files for Unix and Windows.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/modulefinder.html#module-modulefinder"><code class="xref">modulefinder</code></a></td><td>
       <em>Find modules used by a script.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/msilib.html#module-msilib"><code class="xref">msilib</code></a> <em>(Windows)</em></td><td>
       <em>Creation of Microsoft Installer files, and CAB files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/msvcrt.html#module-msvcrt"><code class="xref">msvcrt</code></a> <em>(Windows)</em></td><td>
       <em>Miscellaneous useful routines from the MS VC++ runtime.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/multifile.html#module-multifile"><code class="xref">multifile</code></a></td><td><strong>Deprecated:</strong>
       <em>Support for reading files which contain distinct parts, such as some MIME data.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-9" style="display: none" alt="-" /></td>
       <td>
       <a href="library/multiprocessing.html#module-multiprocessing"><code class="xref">multiprocessing</code></a></td><td>
       <em>Process-based &#34;threading&#34; interface.</em></td></tr>
     <tr class="cg-9">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/multiprocessing.html#module-multiprocessing.connection"><code class="xref">multiprocessing.connection</code></a></td><td>
       <em>API for dealing with sockets.</em></td></tr>
     <tr class="cg-9">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/multiprocessing.html#module-multiprocessing.dummy"><code class="xref">multiprocessing.dummy</code></a></td><td>
       <em>Dumb wrapper around threading.</em></td></tr>
     <tr class="cg-9">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/multiprocessing.html#module-multiprocessing.managers"><code class="xref">multiprocessing.managers</code></a></td><td>
       <em>Share data between process with shared objects.</em></td></tr>
     <tr class="cg-9">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/multiprocessing.html#module-multiprocessing.pool"><code class="xref">multiprocessing.pool</code></a></td><td>
       <em>Create pools of processes.</em></td></tr>
     <tr class="cg-9">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/multiprocessing.html#module-multiprocessing.sharedctypes"><code class="xref">multiprocessing.sharedctypes</code></a></td><td>
       <em>Allocate ctypes objects from shared memory.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/mutex.html#module-mutex"><code class="xref">mutex</code></a></td><td><strong>Deprecated:</strong>
       <em>Lock and queue for mutual exclusion.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-n"><td></td><td>
       <strong>n</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-Nav"><code class="xref">Nav</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Interface to Navigation Services.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/netrc.html#module-netrc"><code class="xref">netrc</code></a></td><td>
       <em>Loading of .netrc files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/new.html#module-new"><code class="xref">new</code></a></td><td><strong>Deprecated:</strong>
       <em>Interface to the creation of runtime implementation objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/nis.html#module-nis"><code class="xref">nis</code></a> <em>(Unix)</em></td><td>
       <em>Interface to Sun&#39;s NIS (Yellow Pages) library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/nntplib.html#module-nntplib"><code class="xref">nntplib</code></a></td><td>
       <em>NNTP protocol client (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/numbers.html#module-numbers"><code class="xref">numbers</code></a></td><td>
       <em>Numeric abstract base classes (Complex, Real, Integral, etc.).</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-o"><td></td><td>
       <strong>o</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/operator.html#module-operator"><code class="xref">operator</code></a></td><td>
       <em>Functions corresponding to the standard operators.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/optparse.html#module-optparse"><code class="xref">optparse</code></a></td><td><strong>Deprecated:</strong>
       <em>Command-line option parsing library.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-10" style="display: none" alt="-" /></td>
       <td>
       <a href="library/os.html#module-os"><code class="xref">os</code></a></td><td>
       <em>Miscellaneous operating system interfaces.</em></td></tr>
     <tr class="cg-10">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/os.path.html#module-os.path"><code class="xref">os.path</code></a></td><td>
       <em>Operations on pathnames.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ossaudiodev.html#module-ossaudiodev"><code class="xref">ossaudiodev</code></a> <em>(Linux, FreeBSD)</em></td><td>
       <em>Access to OSS-compatible audio devices.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-p"><td></td><td>
       <strong>p</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/parser.html#module-parser"><code class="xref">parser</code></a></td><td>
       <em>Access parse trees for Python source code.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pdb.html#module-pdb"><code class="xref">pdb</code></a></td><td>
       <em>The Python debugger for interactive interpreters.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pickle.html#module-pickle"><code class="xref">pickle</code></a></td><td>
       <em>Convert Python objects to streams of bytes and back.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pickletools.html#module-pickletools"><code class="xref">pickletools</code></a></td><td>
       <em>Contains extensive comments about the pickle protocols and pickle-machine
opcodes, as well as some useful functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pipes.html#module-pipes"><code class="xref">pipes</code></a> <em>(Unix)</em></td><td>
       <em>A Python interface to Unix shell pipelines.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-PixMapWrapper"><code class="xref">PixMapWrapper</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Wrapper for PixMap objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pkgutil.html#module-pkgutil"><code class="xref">pkgutil</code></a></td><td>
       <em>Utilities for the import system.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/platform.html#module-platform"><code class="xref">platform</code></a></td><td>
       <em>Retrieves as much platform identifying data as possible.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/plistlib.html#module-plistlib"><code class="xref">plistlib</code></a></td><td>
       <em>Generate and parse Mac OS X plist files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/popen2.html#module-popen2"><code class="xref">popen2</code></a></td><td><strong>Deprecated:</strong>
       <em>Subprocesses with accessible standard I/O streams.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/poplib.html#module-poplib"><code class="xref">poplib</code></a></td><td>
       <em>POP3 protocol client (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/posix.html#module-posix"><code class="xref">posix</code></a> <em>(Unix)</em></td><td>
       <em>The most common POSIX system calls (normally used via module os).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/posixfile.html#module-posixfile"><code class="xref">posixfile</code></a> <em>(Unix)</em></td><td><strong>Deprecated:</strong>
       <em>A file-like object with support for locking.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pprint.html#module-pprint"><code class="xref">pprint</code></a></td><td>
       <em>Data pretty printer.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/profile.html#module-profile"><code class="xref">profile</code></a></td><td>
       <em>Python source profiler.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/profile.html#module-pstats"><code class="xref">pstats</code></a></td><td>
       <em>Statistics object for use with the profiler.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pty.html#module-pty"><code class="xref">pty</code></a> <em>(Linux)</em></td><td>
       <em>Pseudo-Terminal Handling for Linux.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pwd.html#module-pwd"><code class="xref">pwd</code></a> <em>(Unix)</em></td><td>
       <em>The password database (getpwnam() and friends).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/py_compile.html#module-py_compile"><code class="xref">py_compile</code></a></td><td>
       <em>Generate byte-code files from Python source files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pyclbr.html#module-pyclbr"><code class="xref">pyclbr</code></a></td><td>
       <em>Supports information extraction for a Python class browser.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/pydoc.html#module-pydoc"><code class="xref">pydoc</code></a></td><td>
       <em>Documentation generator and online help system.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-q"><td></td><td>
       <strong>q</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/queue.html#module-Queue"><code class="xref">Queue</code></a></td><td>
       <em>A synchronized queue class.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/quopri.html#module-quopri"><code class="xref">quopri</code></a></td><td>
       <em>Encode and decode files using the MIME quoted-printable encoding.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-r"><td></td><td>
       <strong>r</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/random.html#module-random"><code class="xref">random</code></a></td><td>
       <em>Generate pseudo-random numbers with various common distributions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/re.html#module-re"><code class="xref">re</code></a></td><td>
       <em>Regular expression operations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/readline.html#module-readline"><code class="xref">readline</code></a> <em>(Unix)</em></td><td>
       <em>GNU readline support for Python.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/resource.html#module-resource"><code class="xref">resource</code></a> <em>(Unix)</em></td><td>
       <em>An interface to provide resource usage information on the current process.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/rexec.html#module-rexec"><code class="xref">rexec</code></a></td><td><strong>Deprecated:</strong>
       <em>Basic restricted execution framework.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/rfc822.html#module-rfc822"><code class="xref">rfc822</code></a></td><td><strong>Deprecated:</strong>
       <em>Parse 2822 style mail messages.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/rlcompleter.html#module-rlcompleter"><code class="xref">rlcompleter</code></a></td><td>
       <em>Python identifier completion, suitable for the GNU readline library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/robotparser.html#module-robotparser"><code class="xref">robotparser</code></a></td><td>
       <em>Loads a robots.txt file and answers questions about
fetchability of other URLs.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/runpy.html#module-runpy"><code class="xref">runpy</code></a></td><td>
       <em>Locate and run Python modules without importing them first.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-s"><td></td><td>
       <strong>s</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sched.html#module-sched"><code class="xref">sched</code></a></td><td>
       <em>General purpose event scheduler.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/scrolledtext.html#module-ScrolledText"><code class="xref">ScrolledText</code></a> <em>(Tk)</em></td><td>
       <em>Text widget with a vertical scroll bar.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/select.html#module-select"><code class="xref">select</code></a></td><td>
       <em>Wait for I/O completion on multiple streams.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sets.html#module-sets"><code class="xref">sets</code></a></td><td><strong>Deprecated:</strong>
       <em>Implementation of sets of unique elements.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sgmllib.html#module-sgmllib"><code class="xref">sgmllib</code></a></td><td><strong>Deprecated:</strong>
       <em>Only as much of an SGML parser as needed to parse HTML.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sha.html#module-sha"><code class="xref">sha</code></a></td><td><strong>Deprecated:</strong>
       <em>NIST&#39;s secure hash algorithm, SHA.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/shelve.html#module-shelve"><code class="xref">shelve</code></a></td><td>
       <em>Python object persistence.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/shlex.html#module-shlex"><code class="xref">shlex</code></a></td><td>
       <em>Simple lexical analysis for Unix shell-like languages.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/shutil.html#module-shutil"><code class="xref">shutil</code></a></td><td>
       <em>High-level file operations, including copying.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/signal.html#module-signal"><code class="xref">signal</code></a></td><td>
       <em>Set handlers for asynchronous events.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/simplehttpserver.html#module-SimpleHTTPServer"><code class="xref">SimpleHTTPServer</code></a></td><td>
       <em>This module provides a basic request handler for HTTP servers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/simplexmlrpcserver.html#module-SimpleXMLRPCServer"><code class="xref">SimpleXMLRPCServer</code></a></td><td>
       <em>Basic XML-RPC server implementation.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/site.html#module-site"><code class="xref">site</code></a></td><td>
       <em>Module responsible for site-specific configuration.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/smtpd.html#module-smtpd"><code class="xref">smtpd</code></a></td><td>
       <em>A SMTP server implementation in Python.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/smtplib.html#module-smtplib"><code class="xref">smtplib</code></a></td><td>
       <em>SMTP protocol client (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sndhdr.html#module-sndhdr"><code class="xref">sndhdr</code></a></td><td>
       <em>Determine type of a sound file.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/socket.html#module-socket"><code class="xref">socket</code></a></td><td>
       <em>Low-level networking interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/socketserver.html#module-SocketServer"><code class="xref">SocketServer</code></a></td><td>
       <em>A framework for network servers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/spwd.html#module-spwd"><code class="xref">spwd</code></a> <em>(Unix)</em></td><td>
       <em>The shadow password database (getspnam() and friends).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sqlite3.html#module-sqlite3"><code class="xref">sqlite3</code></a></td><td>
       <em>A DB-API 2.0 implementation using SQLite 3.x.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ssl.html#module-ssl"><code class="xref">ssl</code></a></td><td>
       <em>TLS/SSL wrapper for socket objects</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/stat.html#module-stat"><code class="xref">stat</code></a></td><td>
       <em>Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/statvfs.html#module-statvfs"><code class="xref">statvfs</code></a></td><td><strong>Deprecated:</strong>
       <em>Constants for interpreting the result of os.statvfs().</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/string.html#module-string"><code class="xref">string</code></a></td><td>
       <em>Common string operations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/stringio.html#module-StringIO"><code class="xref">StringIO</code></a></td><td>
       <em>Read and write strings as if they were files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/stringprep.html#module-stringprep"><code class="xref">stringprep</code></a></td><td>
       <em>String preparation, as per RFC 3453</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/struct.html#module-struct"><code class="xref">struct</code></a></td><td>
       <em>Interpret strings as packed binary data.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/subprocess.html#module-subprocess"><code class="xref">subprocess</code></a></td><td>
       <em>Subprocess management.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sunau.html#module-sunau"><code class="xref">sunau</code></a></td><td>
       <em>Provide an interface to the Sun AU sound format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sunaudio.html#module-sunaudiodev"><code class="xref">sunaudiodev</code></a> <em>(SunOS)</em></td><td><strong>Deprecated:</strong>
       <em>Access to Sun audio hardware.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sunaudio.html#module-SUNAUDIODEV"><code class="xref">SUNAUDIODEV</code></a> <em>(SunOS)</em></td><td><strong>Deprecated:</strong>
       <em>Constants for use with sunaudiodev.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/symbol.html#module-symbol"><code class="xref">symbol</code></a></td><td>
       <em>Constants representing internal nodes of the parse tree.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/symtable.html#module-symtable"><code class="xref">symtable</code></a></td><td>
       <em>Interface to the compiler&#39;s internal symbol tables.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sys.html#module-sys"><code class="xref">sys</code></a></td><td>
       <em>Access system-specific parameters and functions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/sysconfig.html#module-sysconfig"><code class="xref">sysconfig</code></a></td><td>
       <em>Python&#39;s configuration information</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/syslog.html#module-syslog"><code class="xref">syslog</code></a> <em>(Unix)</em></td><td>
       <em>An interface to the Unix syslog library routines.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-t"><td></td><td>
       <strong>t</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tabnanny.html#module-tabnanny"><code class="xref">tabnanny</code></a></td><td>
       <em>Tool for detecting white space related problems in Python source files in a
directory tree.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tarfile.html#module-tarfile"><code class="xref">tarfile</code></a></td><td>
       <em>Read and write tar-format archive files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/telnetlib.html#module-telnetlib"><code class="xref">telnetlib</code></a></td><td>
       <em>Telnet client class.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tempfile.html#module-tempfile"><code class="xref">tempfile</code></a></td><td>
       <em>Generate temporary files and directories.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/termios.html#module-termios"><code class="xref">termios</code></a> <em>(Unix)</em></td><td>
       <em>POSIX style tty control.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-11" style="display: none" alt="-" /></td>
       <td>
       <a href="library/test.html#module-test"><code class="xref">test</code></a></td><td>
       <em>Regression tests package containing the testing suite for Python.</em></td></tr>
     <tr class="cg-11">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/test.html#module-test.support"><code class="xref">test.support</code></a></td><td>
       <em>Support for Python regression tests.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/textwrap.html#module-textwrap"><code class="xref">textwrap</code></a></td><td>
       <em>Text wrapping and filling</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/thread.html#module-thread"><code class="xref">thread</code></a></td><td>
       <em>Create multiple threads of control within one interpreter.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/threading.html#module-threading"><code class="xref">threading</code></a></td><td>
       <em>Higher-level threading interface.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/time.html#module-time"><code class="xref">time</code></a></td><td>
       <em>Time access and conversions.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/timeit.html#module-timeit"><code class="xref">timeit</code></a></td><td>
       <em>Measure the execution time of small code snippets.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tix.html#module-Tix"><code class="xref">Tix</code></a></td><td>
       <em>Tk Extension Widgets for Tkinter</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tkinter.html#module-Tkinter"><code class="xref">Tkinter</code></a></td><td>
       <em>Interface to Tcl/Tk for graphical user interfaces</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/token.html#module-token"><code class="xref">token</code></a></td><td>
       <em>Constants representing terminal nodes of the parse tree.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tokenize.html#module-tokenize"><code class="xref">tokenize</code></a></td><td>
       <em>Lexical scanner for Python source code.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/trace.html#module-trace"><code class="xref">trace</code></a></td><td>
       <em>Trace or track Python statement execution.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/traceback.html#module-traceback"><code class="xref">traceback</code></a></td><td>
       <em>Print or retrieve a stack traceback.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/ttk.html#module-ttk"><code class="xref">ttk</code></a></td><td>
       <em>Tk themed widget set</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/tty.html#module-tty"><code class="xref">tty</code></a> <em>(Unix)</em></td><td>
       <em>Utility functions that perform common terminal control operations.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/turtle.html#module-turtle"><code class="xref">turtle</code></a></td><td>
       <em>Turtle graphics for Tk</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/types.html#module-types"><code class="xref">types</code></a></td><td>
       <em>Names for built-in types.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-u"><td></td><td>
       <strong>u</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/unicodedata.html#module-unicodedata"><code class="xref">unicodedata</code></a></td><td>
       <em>Access the Unicode Database.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/unittest.html#module-unittest"><code class="xref">unittest</code></a></td><td>
       <em>Unit testing framework for Python.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/urllib.html#module-urllib"><code class="xref">urllib</code></a></td><td>
       <em>Open an arbitrary network resource by URL (requires sockets).</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/urllib2.html#module-urllib2"><code class="xref">urllib2</code></a></td><td>
       <em>Next generation URL opening library.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/urlparse.html#module-urlparse"><code class="xref">urlparse</code></a></td><td>
       <em>Parse URLs into or assemble them from components.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/user.html#module-user"><code class="xref">user</code></a></td><td><strong>Deprecated:</strong>
       <em>A standard way to reference user-specific modules.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/userdict.html#module-UserDict"><code class="xref">UserDict</code></a></td><td>
       <em>Class wrapper for dictionary objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/userdict.html#module-UserList"><code class="xref">UserList</code></a></td><td>
       <em>Class wrapper for list objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/userdict.html#module-UserString"><code class="xref">UserString</code></a></td><td>
       <em>Class wrapper for string objects.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/uu.html#module-uu"><code class="xref">uu</code></a></td><td>
       <em>Encode and decode files in uuencode format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/uuid.html#module-uuid"><code class="xref">uuid</code></a></td><td>
       <em>UUID objects (universally unique identifiers) according to RFC 4122</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-v"><td></td><td>
       <strong>v</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-videoreader"><code class="xref">videoreader</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Read QuickTime movies frame by frame for further processing.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-w"><td></td><td>
       <strong>w</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/undoc.html#module-W"><code class="xref">W</code></a> <em>(Mac)</em></td><td><strong>Deprecated:</strong>
       <em>Widgets for the Mac, built on top of FrameWork.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/warnings.html#module-warnings"><code class="xref">warnings</code></a></td><td>
       <em>Issue warning messages and control their disposition.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/wave.html#module-wave"><code class="xref">wave</code></a></td><td>
       <em>Provide an interface to the WAV sound format.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/weakref.html#module-weakref"><code class="xref">weakref</code></a></td><td>
       <em>Support for weak references and weak dictionaries.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/webbrowser.html#module-webbrowser"><code class="xref">webbrowser</code></a></td><td>
       <em>Easy-to-use controller for Web browsers.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/whichdb.html#module-whichdb"><code class="xref">whichdb</code></a></td><td>
       <em>Guess which DBM-style module created a given database.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/winsound.html#module-winsound"><code class="xref">winsound</code></a> <em>(Windows)</em></td><td>
       <em>Access to the sound-playing machinery for Windows.</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-12" style="display: none" alt="-" /></td>
       <td>
       <a href="library/wsgiref.html#module-wsgiref"><code class="xref">wsgiref</code></a></td><td>
       <em>WSGI Utilities and Reference Implementation.</em></td></tr>
     <tr class="cg-12">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/wsgiref.html#module-wsgiref.handlers"><code class="xref">wsgiref.handlers</code></a></td><td>
       <em>WSGI server/gateway base classes.</em></td></tr>
     <tr class="cg-12">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/wsgiref.html#module-wsgiref.headers"><code class="xref">wsgiref.headers</code></a></td><td>
       <em>WSGI response header tools.</em></td></tr>
     <tr class="cg-12">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/wsgiref.html#module-wsgiref.simple_server"><code class="xref">wsgiref.simple_server</code></a></td><td>
       <em>A simple WSGI HTTP server.</em></td></tr>
     <tr class="cg-12">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/wsgiref.html#module-wsgiref.util"><code class="xref">wsgiref.util</code></a></td><td>
       <em>WSGI environment utilities.</em></td></tr>
     <tr class="cg-12">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/wsgiref.html#module-wsgiref.validate"><code class="xref">wsgiref.validate</code></a></td><td>
       <em>WSGI conformance checker.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-x"><td></td><td>
       <strong>x</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/xdrlib.html#module-xdrlib"><code class="xref">xdrlib</code></a></td><td>
       <em>Encoders and decoders for the External Data Representation (XDR).</em></td></tr>
     <tr>
       <td><img src="_static/minus.png" class="toggler"
              id="toggle-13" style="display: none" alt="-" /></td>
       <td>
       <a href="library/xml.html#module-xml"><code class="xref">xml</code></a></td><td>
       <em>Package containing XML processing modules</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.dom.html#module-xml.dom"><code class="xref">xml.dom</code></a></td><td>
       <em>Document Object Model API for Python.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.dom.minidom.html#module-xml.dom.minidom"><code class="xref">xml.dom.minidom</code></a></td><td>
       <em>Minimal Document Object Model (DOM) implementation.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.dom.pulldom.html#module-xml.dom.pulldom"><code class="xref">xml.dom.pulldom</code></a></td><td>
       <em>Support for building partial DOM trees from SAX events.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.etree.elementtree.html#module-xml.etree.ElementTree"><code class="xref">xml.etree.ElementTree</code></a></td><td>
       <em>Implementation of the ElementTree API.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/pyexpat.html#module-xml.parsers.expat"><code class="xref">xml.parsers.expat</code></a></td><td>
       <em>An interface to the Expat non-validating XML parser.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.sax.html#module-xml.sax"><code class="xref">xml.sax</code></a></td><td>
       <em>Package containing SAX2 base classes and convenience functions.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.sax.handler.html#module-xml.sax.handler"><code class="xref">xml.sax.handler</code></a></td><td>
       <em>Base classes for SAX event handlers.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.sax.utils.html#module-xml.sax.saxutils"><code class="xref">xml.sax.saxutils</code></a></td><td>
       <em>Convenience functions and classes for use with SAX.</em></td></tr>
     <tr class="cg-13">
       <td></td>
       <td>&#160;&#160;&#160;
       <a href="library/xml.sax.reader.html#module-xml.sax.xmlreader"><code class="xref">xml.sax.xmlreader</code></a></td><td>
       <em>Interface which SAX-compliant XML parsers must implement.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/xmlrpclib.html#module-xmlrpclib"><code class="xref">xmlrpclib</code></a></td><td>
       <em>XML-RPC client access.</em></td></tr>
     <tr class="pcap"><td></td><td>&#160;</td><td></td></tr>
     <tr class="cap" id="cap-z"><td></td><td>
       <strong>z</strong></td><td></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/zipfile.html#module-zipfile"><code class="xref">zipfile</code></a></td><td>
       <em>Read and write ZIP-format archive files.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/zipimport.html#module-zipimport"><code class="xref">zipimport</code></a></td><td>
       <em>support for importing Python modules from ZIP archives.</em></td></tr>
     <tr>
       <td></td>
       <td>
       <a href="library/zlib.html#module-zlib"><code class="xref">zlib</code></a></td><td>
       <em>Low-level interface to compression and decompression routines compatible with
gzip.</em></td></tr>
   </table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="#" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�R8WLLhtml/objects.invnu�[���# Sphinx inventory version 2
# Project: Python
# Version: 2.7
# The remainder of this file is compressed using zlib.
xڼ�]w�8��y?��ך�=ꮨ�:u�N��uʒK�#2�"!�e�`�m�$%J@�
F���I</�?	l�����u3���z��N������������|���ɩL��;��?����4;oi�N4|����2fم�4�O�nTq^H���5)�׻*O0�4�~��VDܙ~�r��|�N`�jܣ��XbΧ�x�q�T�tɲ�#R�X�MU���^]�w:�/��s��[��	��S�$3���bߖEQ��Xd�D>ӔgxIL(��$�Q�%E{}Q@�a���
DW�HlhB��Y�m�'�}bEJ�����z�Bj]�K:-
r6�
���*�n��n�X}�o�V%�P}�`s5s"���0β��Ё*��)&ZWY<P*_�`���o(����,��S+~W�yYTaY���r2�X�V���,�^�B+i,�VJ�:��+��#�!X�+-Q�F�CMDVںP���d��34���|�	�O�9|�X�R���2V?ֺh����,U�Y�Qd���'�Ǻ�\=�+�R��bb���4g<���$q����l�ٱ�ʎ-2;���Ibhś�[K��w/z:�kZ\�2U�z
�M�q��
�-_i\[��D,��ګ� L�[QSwѾ[[w�u/[�*}*(@�r`t=O��@t��ub��E64OHH�E�
n�+�I<R�
� f�����7�c�
L2,���)�J�`��1��-c�
�##�d��U�A܆c^R��[>��5��Ղ���ߟ��)6�n��	-�r�-?�;%��OS�^j	1��5��CgA-��e��P9�A�V�cxf)9NyM�aQb4��4�IIwqj�"�.l�1[���n���_7>��b�Yo���Of����(�à���C̹��H�/I�#x���H�y��}C�̧���-��Jυ�+=d�(`€���Z{)�S6iRp�4��TQܾB0��"�DK�q�[�91�WS�gZ�X���,�0�D�i�׏nPt�$ρފ�~���g��K�>Ϧ���4�{s3@	%�=s�8� $?��b�(i
'̟b�(�@�쓄 I�=C�?��H��շ�����ߕa���|΍-27L�q�5�W���<2uFz�;I*��b�<�hZ+91�A�3��|µ�B.nf$�_��j\��Q�̚�4o�=�2<Q��OT``���F}��i�^��־�a��鑅`	f��`�D�%�B��ê(h�^D�/Q��m�P���J$�lh�Y�>�x8����8���;��������ḟ���V�+F^7j���,SBQ�v�2L,�a5��6�)2o"j*O�0.1���o`N.�f�91,��w���gt�{��4S�SAI��?3�G�z�
�ϒ�0T6죘<TqR�G=$T=ҳr\�-I���U6�8�'��vƸ�+��_�7#�PQT�����w�@�J/D�ץ�3j�u�R�6�q�YX�
\����ےwD�J�!ַufhW��4�.�?V�[�@�Y�,$��wL��!2��(dso\2@�4|��V�R[}a���@��3�7�S�fp�������`�l�ɇ�i��ʚpv(���F�"���v*
	#�%؃|�q-7{?�_�گ"f����mh^X"d��U��v��ɥ��hsy�p
�	"j
'Il�3�#qBtI�V��ږnU�����-"������~v�
և-�&5��=Ceo��KͰsr8�0^�}`�Dg�|�R%�I�0m[��,�L�
?@m}�x�R�Z�%�.�rJF�yf
hx�D��N1����P�r�JCQC9Ҭ��\3̮�m�1
�[M~hܕu�����w��(2�X��syN�H�J����̪H�?i(Tpoa�څ/ѱ����c~Ō�NZ������39ơ�g�UP�'8 k>x1u	%��D^�w�x�+���V$�
��cZ}�ȶ�3Se��%�B
:1p�L;��Ȇ�)�c��0/��^J�9�r�?��w�M��
η�eP�׌�njF�#��3�oH���]{D=24{�R6F`Kt�pc��i�K�\w�Q�yAſ�����y��(h�����y��������%�DZ�P�ո7���\�"}K��7}�͈N'n��ވ�0����؊ �9w��?әybސe&�IB�K�m����P�
�7b�b0c ��݂jO(�²�9����ո�����7}�֕S#b��4��"�	��(}<�t�F�;�A�ްi8�$�-������7��zȾ�m����"l-`�?eZ��,6��R�:p�"pxI�5�=��$�E��G�Lt�"�4�s^��s
B#��PU��G�\a�ځ��p��E�Jn���������O�+e:|`��m��a[�45����yϽ+�I�s!ђ��^��&,2�!�!W	[��lO��&.꓿L���u<�P��Me{�u�v���s��?�$���7�ɑɹ<�
�l>�@���ɦ>��=�0+�N��چ ��c�r����4�`��^̠c���W�nW��3&�8Vf`���v,�A0�	��t�EpO��ٮ��E���3VV#����hơZ����T��d9���Z�gN�+���[m|�khs`��M(����v��N��D�	]�Ը���B�I7�$�!��Zps���t0�s�T��}�g��"(��	�*��}m�6����{���¡�ASPmǃ3�@q��HJ�т�	�wt��J�\%e�'g�.p���HtCSg�H�m�/C�2L�ʫ����Q��'��G���m��Vm&��{E���ߡ9�/��0�[oPYSv�
�a��B����P���m�g�j[%	�	��8H�z�o������xPf"+f�%����<�L�F�F�HK]��\g��AMHuxQo�j�ʎ2"��>�!|}G�Q�aٴ�Q��ld�~�a}����T�C��`��'9�4gy"�yKp��-g}��U�v�/�\��{�VU���4�l�g3���Q�hZ1�5�+s��Zl��1`��]ҧ<��͏-�,͉����2��rR�+IM˲��%)�;k��i�bh!+ڋ6f�T<���;���鬈�]�ws5�D�q�7��aY�Q1�JKDyk�-��PE\��@�5�
�v�%����|*-��j��m���`�Z� �,h(T��@VL��I��x
����#D,1C0D�d4��["���!��
�v�@�Vx �m�Ƞ���7��}�rh}���	7���VH �kַ
��Кv��p��JPtV�Y61Z���
��P7���eê�0�u����@�D}s��)�%c��i�+XN�R{E���ʂiv��B�����I�a$<z���#���:�DB���d,����_gԇEx^�x�^9h�vI��ah+uOb<�x��lKb�l1�U�-�|Ӥ**F֐=w̄�T���z��|�Q��n�|k��g��$:ͩ��Wz�
hxT�mf�j&�x��0h��`5ؙ�,+{ä�8��Dx�Ĭ�P]yәT^��E��u�a��Ȅj�X���eoJS��a��g^�cT�DGp�.[|a0M�0�atg8�3�&M���iݺ[�S�M��-�x�yH
��ۛ
�j�N�}�O*�nͥ@���R^}?�,�?���'Х
�0[�V����b$~�HL?�0���0�ץ�ƭ�w!�΅����n��бq���ղ��J׷�bi���f���is�`̆(-����D�1-���ad�B��o��A��A�J�ĕ3k�n�껑С��f�d��5i:�g.�uy���x7Oo�����#���HGl(��T2������Q0X�3!��H���0�չo�]GT���a�[�v��6��Vv)��vN�puC,pu1��.���(�h0�
:�꺅>^ɢ��Y8���)����on`�ʇ`6].{�zѩ�����_�ân�f�{ݸ:��/���S�p�ɦ~<\�W��2a'�%Œ
,6��E++dT�!�ʂ�1�)!Cct�B���Ť�}�P�hB:�•�$�?Ln'e�[G\�5$ǡ<ط����>��9���f7%�Ix’j�7l���F_��fy0Ń�X���@v8��E�ա��� �M�8��RR��B�c3�T���q����+�k'�i�Kd#,A���[8%����&8�m?�#Xd1l�k!@5�p�lɛͧp��7�"�8<��8ܣq�>��z��F6�eAZ{�p������N�apwg�3iǦC3&$<�f��
5�F����v�4+�C���4\�c�����^��/
;�
�3��C�?�`@�q�3��n�s��6��4�+��YA
7
�>�iD��o �*E�"�+��:"8�:z�ζ$�op�c��v�8m�q��Yy���_��)E�"��w��Ϊ;�1�j;F�lG��G��/�T�K-�+H�QN=�����u��/�Ξ�6�#��v��y?u��t7ա�B(���b�~��Q>���W�Z�HI�曍&h~I�8�~�m��|��IN�B�����݇���x�|F͍�L�qDe	��Y�0e��ѡ/Jv�|�s�3mTŒ{$@��t+e��䀩��6����$,T}R?T	R��Bʨvˇ���j�|X�����?<P_߽ʏys����5���5���5���5�]_k\}����va�7��J��X?��C�]�v�`���A�-�pY�#�}N{x�cWɢǝr�������8PLJ1���,�І�m�v�n���n�$.qTg>�ݑ8U&<��v�Ob;1͗��豈�˼�%�s��C��A�[A��G�B���C7�e�]?��|�����<+���h�;�!�,H�������/4��&;��������n�ԃ����*�.�����F��m��i�xX�g���*N"u���VUqwx"�-�S�M>���G��[�e�nu�����	����Z?]�8�6S:�|�<I��|��F��K�\V�ߩ�x�u�"�D~�0�Kz�J��UfG�H����uq��$���&��0�ll��v�6E}�gA}R7X�r\@��\�2]�#�O����3��9ע�6�4<;$}���4]�c��"��o�|��t;��
���k� �;�_���\�qW��ș�D�B�#�����g��9:1j���+�ݷ��xt�J���}Xٜ_	����GiZ��j��;�G9�m^�ԛ�cط��E���/�`5VI���x�u��9�žu,�����y�t�|�b@1�Z<O�(t�u�À��փH��P���!P��|��a���t6ǀ��n�__^0�ܭ�)P\~���,٭�Y�[#Sv����V�(��w�o�����y\NW�4J�)L�P�诘؀X 	�2V�Qbr��y�e��)�O$MZ%�t���P���Q�rr�|��T�dh��1}'�����w{<��� &4�\�7!/�����^΋T�55���43���:y�p���>�L�k̅�����7��}]aa���m<=��1�_�7��e�P��l��j�xW���� ����zձ2z����}a�@������RW����I�^M�WY�K�v�HQ7�"�����8�Y��ޥ��˞$��Q�������)��z�t��DM�w���D�Ҝ#�EB�L�1�Kg�Ґ(U�H6?�����_����gQ
kG���%]�{
��v/[Z�(h)y�T�9WN&�����F�(���0�b�u�<S�ɑ���uy�,��ۗ��D����N@�4���X�IL�2h��5�mJ*~�5�ҔJ m���4�Y�D�"Ϩ�u��[�l��j�/I�ڟ�.����Ƨ�����D��_��5��O�����+�Q�����R��]�����/�X�)�,dI���k|iR�W{�s���̿F^�N�4�-��*���
�*�6��~;���.��B���zЈ��6�c�r;Jf�&�t��vD��w��\QKk���X�[p�u10��ep�O����QG��@�(.hX�"67�>D,xYowڲh��j��ӹ>	뷽�k�o(�q%���Ϟ0�W�~����{�%�M1KE��
���,���ܱ���O�ʈ���$?�!�2AP�1�U���C���%�Ct�Ǖ����D`�@>a*�K"Z�AT8.���:/�_<Ѝ���b�rf�1�$bTsB���V�H bT��ƻg"��3�b�(�Z��Bb�X&%�Э�S�mW���>D�R��e��P��B�Q���M�<Xv�k>6��((V�z�
Ÿ�M�f勂f������l���0Ӊ�,�Q�)<?�GE���,aŋ(m�]���{;Q�“zЬ��{������t�+߯��^�7��)Y%&�f�v�	�Q{��J�U��!)閪��z���0=_��K�5Ey
�QG{����S�S2����W�y�{�X�曗�r*��/;�������6��Z��
��v+6R�?D$}e6�c���NE~�xOlm����TI����h�4Rr�9%و����1C(��v"<`���{R�[F-/^]ͽk�wU�S�IR�qS됏���w:r�iDG.3�Oo�:��[aŶ�@Gh��e��ˮ�u�*�X�$����a�0a�o�.��ܖ14.<	.h���sI���� �J{��x���0�W�4�!�X~,��e���ߢ��J�^_ʇxхGH���wy`%�j�w>4�J�?F�Z��"dT
L�*����v\D
Tt�_l�1��@�4���@��}�}��ɷQ����"&	��nc�_���(ݩ���L�v��g~d������̲�!b�g�yh��p�1Ͼ.�G����0Y��A��G�U)��kd�
+���q��{�+r��������(yiGd����=�}�Vv�ɔ����O�X�ԴA�'fVْw�r�,�x���ĵWF
�A���侠��k�?_w6cpe)AH<�b�IX�/5�� �8��$��=M�eR�9V�L����˴6���ռ$Y�q��?u�j�Mn��hU��M�-ߊ������<�yż��NňO��U��g	"�����Fh���p��H��*D~Z��ý��7/��t��Y!%q�0�����J��e�H��%X�UV?9a
Q]�k-L9��2,r�; ֌`�^h$g�pQu�1�݆"�]Oل#%����|
E_-g�,��j�R�dO
5��ޒ<$	S�	��mx/��M�?tU.�y	Ҝ�d�����z�oe����]h�
v[�D�����GǧJ]U�ҀV�5��Т`��	�i���"��;��;�u��m���l.��
[�����u��^�$�]�p�-��]�@i�)q���6����'���Hs2Z}zI���i�SS�q�h���D��$DZ��$�<Z���8:���϶�{�������*{��G+��ݷ`��n��������z���>���6���z��b��n�ܯN��0��n�[����n�= �z��R����r?y���-M�l�2�KK�M��MVL�h���p�Ny�>Z�@M�N�8��u{��������	�' ��8{�Y/�-ji9�+/������1���!�Cn���R�Z�������V���N��}��:���'�Ew)�2�W���db5���,:��SoP�f�t����ń�����\��tn����0����L,������&\N�~����y�&��:����ʂ��"����{@�r�i�0�>����*i���i9��
�۹�u}�a�Q��f���$�a����rb��@οM��
#�A���n�m�i�����r:��_�]�0>n�o����t3���?_站7�1����?c:���������X��C��h�oK�7����O�i^�M�x%�� `�%p�-��x)b&��3�B���6��f�*ÞWc:XaG1s#1��7�3(c�fG��i\�@%�oA�t[C�u5}}\��ߵu�W�����E��k��zd�@�iY����v�����״���I�Rlq��b>�^er}0��K���K�c�����mx�L��f��a\c����!��g��-�}�	`����r�,g3�8�O=�\Lu�ˤ��35�h�D�z�ʂ�>�p�'��[�6�tm\��F/�f�I}� (O�'�D��:��B ��=�/��<��5���ϘU���/�M6oG�H,|���{PLC�V�l*^O�Ahr���^���%h�܌䴬r=K̓Ln�e��n-�H'�4��}�>��t�2;L�r&*$K�}��s���ڏ�FS�(���'�\�j���AlMM��g�Nk���r'���w:F�4���(�����dž�(5��ܩ*#���!����f�F�`��������ٷ�=��ȫ5G!<��-Ύ���"���^�:�F��Of[t�����$�dx��Ed����7�şm���,�v\,�q�z�[
m�I�yxCk1ˮDZ{.��v�6�e�ً�p+�+1��i� �UY��}:���h�֚0v��=s��w�;�}��@�[���k@.@}�Õ��:��ʣ��0Ib.������)t��9��Z�u��y)���P9��v.�b%}`��	x��];=� �ں\{a����n�Y^���u	qsZF�vb�\L��m؝k�fכ���r���˔�Q���	��/���2�TE�)~ti���4n������t1�\��ɦ��,��
����i��ߣ6����/�j�f��
ۅ�~���rav���ѷ?&�?6�4T?�H�Ѥ|��r*�%ζ/�A(-F���z��Q�c�?|�ì�x�����?֎�n�n!�+7�v���'�)
��բ��h�ޚV��tqw�."�cP�����*e"_U�B��с���c8?{�`_�IgA��:�5l$7���p=�C%��}j_k<��	�I�i��kN�7y���W�R�hY�J�h�@y���jGy�+��|�YA���y�Y�|&甍y1MJ��7\m|o�>�p\5�[p�	EUˏ��b���λAh�em��CR�D�|�� Q�H�g.��y�,�ۥ릊Cu��D���6���c<���z�i����f�����i���nov�������n
���t<Og��9�~�o�֛��=��^Fv�$4].��l6߂ə"��r��
�n_��;(=_�>�7p���g��9[�w�'pp��:�|�._�n�=�f;��<������ȑ���0��р��d$B4I���wZ/gY'롁vv4D>�A�	��x3-�����K(�ϊgy;"���*TWy%�y��
��T�%�(�� ��W�>.�+�\�v�9Rb���t�l��^E?��oׯٽͷ���e��@u���d�_��"̫5���%����0x3���b3C�-J	Yi�Q鶴DU��s�pdj'f�yoR&�Mfϴ���O�/ȝ[���j�\�{34F����F���l\�S�H��iQ��8�>?'4oϞ�RZ��'v���t����@L�L��6�4!���H�cڒ�%�Ȥ������h��R1��^��&�|�g'S�b.�9E�95�|��?�|:o@i��Jv���m?Ό���1gpL����s&��,2.*�H�%�`���PB�p}�g�ά�JZ���̒�&p�z�4���z�o1���4���[��-�8��/���	�lDIvL`)���p������ٖ��Dg�5|����ܘ�`#���E>���o�/\8��#q�e(�%��݁	�ԩ�´!���x�0&S&,O$�hU��Z��)N�#��T�z�CY��e‘��c	G��m��m��mn6hAp�����&@�A$E�k��v@��N�;׉���[��n*�N:�
O2�Qo�qs.�,?a���)� ��'�iZv9���>�ի~�׏/ݖ.���P�
7c+8�D�'T�=�P��tIAҫ�o�ӧX��I�bj�A�����屹D�Mr�����͌Zf�ΰ�'�4��
J*8�p�&�Ve%j�9�-�x�NG�s��%�
һ����I�Ѡd�w_Y�Q9��g웭UJ��(��(Uܴ�]J�Ml�#�TR�ȮZ��:�\!f�c�z-4F��k��c'��'�fl%�(9	�܆|<J��q^_@�ol����$
r6�1⍦��O���6��V�;��x���D��3�)�Ծ:�������C��U�~�)�7��
���.�y������b�ŠT�$�'�˒`J^�m9�lAs.(�۷����NICG`�d��U2L�*�`�Y��JC���|��=d�,���R�lZR���є�&�!�Id<X�eB��p���ZLk{N�J�� ��'Cϣc��<.ؽXe����]����B����Y�;�AQ��n�g���&�?�VLr���ga�L��\v��N��'Q���� �Zt]�D2$	hs۟s�,�8� ɛ�۳\�3���b7/�/A+�/�]�NH(�2A3�i���!����Q�ԚL�q������4��"�!Ke%0^���<$E�Ē{(�;�(�"X�QH)YOG�+��&w<���S�����',�+R�����B"��4� c�������0VPs[#^���B�\�,e�~��-�\.5�wP�h��
�|�t��s,>
�DJp5G��i5y'h{��g�\nf�M�AY0��1�<���X��N2r
d�S�M@F��(-�{���bN�LA��}S@&g��T��j�ފ�H�����k�ի~�^?�n��ԁ%�x7Vϣ�]ߧ�9���@��-���$�`B>P���9�DŽC��`ٿW����l$4�gj'�����5{Q�W@AQ4��…���Qb�;DZ
^���U�@�%��@�u����zV���<̔l{)����[ɾ.��f�d�X�7�f&���ސt4�psK���6�w�p���iC[���y���ߣ�B�Ƨ.}�����_��|���o�ʷ��
�ƫ��.HLk㛴��\�vyLȫ"��@��wp�����l�G{}5���:(�=���w�����$;�q�~ho�`LH2��!H()i�]y�1����}�?gU�7,��H�;��l��6_ڱkog�GVв* ��@%�;�l��<|�猋�;+d1�Fr��� @oP岹c<��|���y���J��O������(��ee�UFe�Kލ��*�z�U	�9���=�����B2�d9��P�����s�(�%U�U�U0W��ݨ��^��t�⼱����X[?s4Ca��M膅��S���tc�{��BĻ3pS��Q7��3��8����Q`��:a��o���\�� ɗ}p�=��Ξ�'���8����A��dQ����H�:�äNX����p���ć3,5k�*���2D��r�kD�+]"5 ��\=ӇMLj���b���`��~���z|��\�$���x�q���Ŭ"�

&ӛ��_<2�^�7��ROտL��l�(�Q�f�A�Dx�F�8X���	��<"�ǬB�X}�(
�,���$��Yy�2E �V4������lhF�P�]0��y��}���K_[<{��icD�l�߰{��$l~�g��=$�]T:��v�B�S�7�arkk�L�q���0O>�(X�E=�o0�x��H����Dt>���-2�&��m!"—8|3�6�ի^�
_��a�S��C�K�.X}g��`X�Z�+��J�
�&5(I��0��a���Ŭ���[Z����)�ʓ���le�#�|���+,�D��!)�񤼕΢{'z���k��B�v�Kd��ͧ��>Aht��/&��t�"�d�W����y^��H�O�ht0�r#��A�L0��C��XHQ����[0�T��N��l��C��I�m�a�%7"Qk���×��i;����C&�4��U��M��Ρ=��I��)(g����ۄ<��Ũ?L�&����_:��-�8�=n�����n���Fk���j���ΆݽL_��Gw�����a���?��mw��r������g9�,o���^�p����G��yKX��߹����=[
vg)?��P���޹��~ݹ���v�s��<��	�~Q,<꿋��:��'yJy[�B��1J��E��-"�H9#ȍ�~��v�Y�8���z&��2Ή�#��ɡ�g@Y���gF��P��*�;zhn�u!J�]S�ܛ�s��h��B�_��|�tnRt@N����Tez���M?�鬥zӘ+t�ڲ�j���V��[;֞��`1'��0��2.[�ʬ�y�s(c\Ͻgd>N�ɡ�Oge��ѝi�T�����;w$X��k҂a�m�e@��
����ܮ�[��z���b��I_1�~�TOIȌ��u�����AI2�{���&�vĤu��Ctc����R�i��� @~"�a��]�2g�y@�-%Z��R-�g
��@��a^�j&���,��8︛�����~wd~V�2�C�H��O-X��;P<1~�"j^�H�A>�rR"�V��83i�Q�2ږ6�D��%l����0H�z �냒��`ªy7&G*1�+�G,�;�9`@Ӛ�-�E�q��B�vuτ�o��p7���$a4䆋�
.i�Ր'�����*�WQh
�h�au&�d���YU��:��>�9+ɧ�LM�؛�l�k�7�h4d�+�@iJ2�TAv��rcE��*���u�s�8x���/��_wO�;����w�L���?�	y�W�9ۮ-�F�fPn�����g(�p�Z�$ɣ
���s�Qֈ��sk�)��E#2@#�Ŷ,(I7���c���eq�6���C�#��%{�����CzWcؘ6���t��%;x.bz*h��s�j��a
�����Z�00GZF�|q4�q�
�zݑ����~*3b����nj�b =��a���w�U9���t'm���Āy�
F�J,�$�%
�L�2S�:���+�p\<�ճ�Y=i0��]cVW2��Si
�>3��iB���f�[c���$�ݬ����;��D[%:�IWY��Nh�LSO�"��0isVI/U�Ή9�j_ZV_U�<"�Q€�7�ϣK�������.|�.��B�A�7Q�~&y�ؼ²x�+e��+�Ė���7`?���Ő���cz���y��#/�^����6��F(�;I*�/�͗���^nLhn	pI�k~j�g����ϊ"�&H�-^ ���:V�l]�U�x˗����/��oJ��3���a������b,g�%Y��D��f���r˲�gb�vQ����<4�Z�˦�r)y��"��k�?������8�W/uC��E�兩�qoΫ��-��Ѭ�${J8���h������WM�L�S���N��HK�=�*ܣ\T�{�p��t��Z�u��i^�R�}�Ϋ�ؼ�q�c8ؾ�8)��|8ɬP�"_��^LLW�9���8��Kk1Y@f�U{]���rW)hհ��a�	[�(`8߯�"����Ň�	����7x��l�-aRyAYwsJYnͳ�`*�,9�	�4�)\.�:��L�2Ӿ֔��+y�l��^��]9ZV���%��l�H4�!R���%�fobLiL��&��73���r��:L�iisdN?�u��"�i�(�`�(�A��eL� b�j<�a,�^!��y\P�#!�Xg,�X�:�6kXLjML�!���%�#F��iOh���ÏSR�C��/��|$8
���)�X���Z�Oh�zDc')���N���+��w��b�B��V��N�L�&\�GPt^���Rr=c�ں|ۯ���!`o�Z9K��Uy�ЈbX�m�TB��Q#w��6��xԮF-3��ж��l�G��h:�a�?��c'�&4���ɫ4i4&��P-㽼]=���i&���(�U;F~��=���"�s4u�$�FA�6�Q��d�Ȼ~G��Fw4���+kd����9>�i�tڜ^;nª�[~E�5���qKl���_',S�:
L��������.]eb�+��1囎���,�_���rN��C�n.FO(o����ҭ���Z��p�/��sh)"o��J?�?cQ����g�ZX~�,���-�]�k����F�
P�܋����R�"�s�^|�q�k�����$5�/���nW�O�(��w�(�eU�	�Oi���ޠQ\��\�9�OS�M?�������S@��/����٣�C�aS�ܹ��Y���ߵM��d�h�V��`���%�B�QyrC�=��v�#W�Ey,��s���x���͞��}�����r�J��r���>Hc[f�g�-����w�`��$�w��X-��`�^�A�W����b��l��=z=���[��
Iі��"��O�L�ks�T����[$�-�
4F���S���S�����(+C�TJ�ˠ${'�*�i�,PM��Ϲ��כN�� �Xb�pW�~V��9�Z�aI�����K����|D���iq��I{�x��e
����O1�8�'��4;,����q�����Jb��|�q��n�]�?��f�?^�\�c�I2#�k&�P����௴����}G0�I�V�ێ��A��p�m3߾.w�t]֯�,�С9pj��<ѷ�&��L(��
+E/��j7���\�{9'�O���'�*6�u�AOb��Ly/�9e�����=ry�8͚���q��X��8�� �~0{��Vwoj`��B��Jg�F�PP�D}����c@��x'�n3��J�%#�DN
�"�8"�aW�$
�K	i�[dB��e4ɨ��E�̳by���9��o����q�nTt�՞�^����h	��l`��^��D�kwH�v��;�?�S�./5璂�v�9�W�@�A�_Ka�C�澶�!j�V��9B�$�pL� 2Db`�Բ5��S| �`*p=��嫂�
^�*x��e�g|�*.����8�F�&�����=��zM�]��buY;FB.��AK���k�^�gS��GgAPcs˝ɯ�"tn뀼c��
w�=�Y��6H-f�����9'c	;5ś�N~��,
��O�{X=��*�i	U��/�֏��Y��x���[��8�H90�~Ic�{}�
o���|���ڪP	�����ʃ�O�K�/	c�OH��#f���	Q|�K�cA򓏀�EX����*�J'/�\��c�<�K�O�r !\Aܓ**f�GQ�È�dr���9��@z/F�o@Fz484'14��G`�驈��`G�Ɍ�M�1�W0��j�͝���,�0_�b`
�/� ����9�II����Z("&�q�ob#��P0�ϟ`�K'�T��b�n=8��C���7
���|�io�$�C(���/�'��Td����T'	���U�_��!+������������)��d�#'��oL��a�w;���g��i(V�"�;nL�H1��C���d4�ʹ��L�~���%{�E���AbOӎ?g	V�,��8�Qd���L��;9�v�\E䊛h���t��Y�䛷��l���(�ma��I]>�K�3�T��h�}%Db�J��Z��d���\�Zbp;�n���j;oStyC�"-R��)3p(9b�!�*G��$j�-��;28��1�=�f4\xo��N��3��/��-)f���L-ڐ�<���Iy�����摫�>�n���i�d�����"����
.�k)^BuN�H~!"'
�*��T���K ���ָ7f�A�4{�A�Dn���!���e2]8�e�,p$���NA
�4^de%�o��!=�X�?Tx:L0-6��9����(ٞ�X������YX�6�	�N
N�������#�zͤ�N�!��D{����'�U�K�皕`8��Ol,E?�EqͺQ�̗9Z�8
Q�H%8.Mi�#3T��3��D�j>J��"�D�8��8���p�7</ڃ�`@�y�STZ!4a��%}�q�|�e�RV�(�*�uS�D��0K�rM��ͫ���
��Q����n;�<,X��ATU�kWa�Z���<.�",�+�����#⊂S��X�/�q<�UQ]r|�X\�V��oA�w�] �@&�v%�}�[˼�x����|��J|��B�j�5�/� � 8(S{�ø� ��P2"Ƌ�Py�Q���|��K4bi���9�ԑa"�י��?(}��!\L��y��-^�,3���m_��YΒ��XaR�.��˝pp�E�.�Sc��O!;S�E��Mj`��~�k	tè~!\���e-�t�t��|�E�E��WB�g���D�D{=F/q��)�W����M���qZ�A���yj<�%NC�E~2�'^�-\:)xt�ꗌ}��H����=�T��V��̭@~�ߠT���5@�*��ǽ����8�V�3�̧,���]P��p�&_�yWR����]G�����#G��Q���g������u�y��أ#��}�?��ϯ����ZY�֯-��D4��r�<�xãKi�{�Z�d%I���pp*^���
B�j5)�S��HY�j\���d�X��׏���0%S�s	AaF��v,/�{�*�@�G
f=�j`XNMG��DjȬT�S��sH������uǚ����Sk�ni�D�y׏e��8���j+|�D�z�m�Ɵ����83�*�Qé�A��9�"J[�qh�
���L��py7)��c�h�l� %G�L~Ɠ��(�[�q
=e�d."��,�_n4e�b�.��㌎lk�ŋ���Od�uH	�y��	��<�OѸ��	d$ór����O�e�����{F�OZ0� ����_���Ѥ���ę�@���s�`���h&�(�)�q��|���yZ%e�'ȑ����+>O��}�Y��ŴIrW� �z��R��=o��џ�Jt��ȪUPy�l�
��G���nl��IJ�xU�T�_���:?�dc�b�q��	�t���h	i��X���~����1*$��i��@Èy��+^BGL���]C4r�|�13�;5Ӿ�@̴���*�����V�8f�}Cc&�7��r��gx-��]@�\���3Ďf��q3Ďx��eӤ���o���{���!v�3�N��F�;�M�f����t�w�b�3���L�3���;Q��ᓕ3Q��&j=Qkps��F̙.�Ǥ碁��,~�sQ@Lz.,|�sAb[&�iKG���x`�=:�˅h`����1l��a��>��4��p�W�#;��ϒ��a�]d��0"]�h�ӂ��h-��C��Z�mX%#b�ݡ�3�*�p��ɏk��v��D�@���W�@��9�etw��<m_̈́���@�/Xi��b)��>��Y�=ss4�@28��vEĔ)�@�@Aиǵ�銂(�/�a+�ٹ�<��1�����z��8+%Md��w8���L�����c�^��k@�d�����o��A��h�U��Ԅ
����h��Q�${��b̾M7��n�	��u�B`�X�Q��h�gR�'`~߱͵f,;R.&m�d@�YO^�w,X��(`��
���p��	E��6��(!�Y��[�Fb~BcHP1�-@��1���QT���̫fxDM��^���]�u��*�a|��m��UY|�E]�y	K!�`�ꗚ�yA�� �
[W�Lb�9Cj�^a��uC0�,;���{㺑�����羊�R�م�!A�&-�$L���o�Oem�NE�AS[��GBp\�]ˎ(!{��y=gT�w��D�3�JM�:�O8�=�U���W:�Em�����:�m�9eyJr7���u�0U����4oH!F�4�݈\��E�<8j��扱w%��D�ܓ$E��8�r]��a�˲.��N�h�٬#�X]⡑��
�!L��Mc�hvΤ��7r����УhU&�u�^��RKGk����x.��a�θ}U#�������D/'����b�`)�M���X��8II?iX�i�����鎣ս���h�*W/�����'�{�ˎ�=�����F
��r<M~#�h����9b����<�#���x����QD��)GN��Y��Ƶd��4;���D�4��؊籃y�'�)#�w�m2���8�T~�y��A
��i&󢩋1!�պ6#I��ˈ�3���p!yW�E	�4BO��h2�^I��]Q9|S[��9+F1�%~<9�Nx�ڷ���n;s����ɡ&{�h� ��8J)�G�������ob�T��"O���:!�8�F	���h��h��P�o�[��E���W,<���[$��Fv�⣯�,�ͺ�2�ZFIK^��~cȍP�[���RA���������豂dc^��w[#��~N���8 P7�bFXR
����^�Wk�x8����rԋ��
�{P�er1�|}��^)������D���+s]X�*T�(��o�h��]G��3tSM��F�@���������1y�|��A�<���[��Tt�I�Yd�f��/`�Un��w�3�r}�%��	4�˝�D�jv.u����|U�Y?F���|d��#a�n1���m�uM����"0��>�/�������jx�a�K�ʅ�������~
N7�c(��bD)�%7��
5ZD�h-3��a,�fV���W��:PLm�|�BT���d'~{j� =k_aҿ�)�R���ɨw
��C����E��#M�>\u��syi&���Hv�A�X����[@���`Z���r�4:�I0�j�R�;��!�Ǘ/�!���y��ϊٶi�E��%h�j�Kl�$�3	j-�:�[7���N&���1XN���n�j�g�t��1�2�v�W�j��Zx�[~N]\ڭqߺ���daI�F�w��~�6�g���f�]������V��]�.��^��l6����7yx
+�ۼ΃��&�HA.�m�,3��2r,�]ɶ�ͧ ,�In������V��')�O����@w��8&l��^2��}B�D⤪�µ��
os�3�c�}�H���q��-�5�6o���EtP8�k����i�pP2�ڄ�����Ẓ��&F`�k�F��UR�v�Щ���?�R��Ϝ
�s�
	Z���y���0�A�7��r�]����r.Z
#ڷ0H9��jy�<d%Gv-��<��9����������j�����Hh!�b���t��d�x�.��?�-v���t���2�ʙ�[���Y2�VEnuju��4��m3Yov��W���F�����	����z��#xZl���I��f�y�z��m�q�zi�oLB��S
�J��{� b�!��=���O)�"�����C��\,Qe�ejr3(���{f�P�Tv�q)��!�� ����f��ƙ�4�ص�p"�to���~ן�7ϭ�u�.�4_}f"�K&ʶx�a�sP��*�)E.t�ry��	7=
idQ�8����˥آ��O�5.�dvչ�w52F~��W�NF��1_?ڳ��a3ܑ��,Ā��p���Q����AB3M���;���8���_��u딗f��c����X�&��b<���q8�^?SF�-��n���<qO�����"���i*R���[��։�_���	�7+����1��4k�	���(Rc�(B?+�1N����TL	]�|�]2����r=�o��R뒾RϔsrKf� ���H!-
7�+ђ�~HVXr��Ɛy��Tu�_����ܝ�Nld9[�l�"H� ��ZG% 9��#V�ƶ�r`ȹ�巋�>��xx��&20�vl����j}�H.m�y��ެ"�������w��2�����e�u7�{}/3�
��h�P+�SRCx����|���H��"iOմ�8,iָ0�X�������72F^�i����Vg��&���8bb�4���t�#���P��($֝��O�ۮ��I�ɋ��/H'���܆yZ嬕�"��?X4�v��(�:Z�E�>0�о���6��#�I���AlD�57�WU^`9��x��q����k�j#5)>��9a$GLn
����j�/@B1�v�;���R����J^P�Z7��
�'$��u�|�֜�ٚ��[>^��c�I)6^ǫݖ+C@:$yC�ԟ�-��k�y�7Ѧq�BU��:/�M�2���y�ꮬ���y>��m��]D�ժ(f���
� �����ǩ�\!�H�3M�¥���Q��0j�n�T�Xv+�b�����[�������Y�PںE�Wޚ�O�F�]Ƕ���	��(��2^qܵ��e�1���7�ik�%IH�iP�/_������Ƭ#z�֬^G�"M��*�)Oy ��$�
?��|KȠ�Z������T����Gh�7e/��+�J�OJ*���x�BM��UǛm|G�Vu�}[S�o�ɎM�����wWC��3p��FK��`�*�?�U谈�Jx��}k�&{�J��G�[�[�s��ReS��'-�zk?z�M?j�����f�r��8��	��7���v"V���~��	���i�޾��
�����b��z�!�����qq�r�q���
q�9���|�tϟ���
�u�9�o��#��f垂���3��j5}�v�b6�'Q���v���/�9_� �v'�������v'�sw��W�����+��?A�o뭈�xEa:���,7��Xn9�X�l�_E�����Խ�Y�ݝne�8\B�]M�S|���x-�������_A��*�r� F��8��� �C�og�%`��t"�������b�>�x^.V�ʹ;l����n�
xQ��z���
6�\�am�p�+mSW�<[���5������|�]\?NwS��w��9`�'\C�j��O�kH=Y����׀1�j����om�����`�I���xr������݁zx�������2(ηkPq��Z��V��V�x1�w'��7OK�)+=�2�h_k/���]�@�kD�$����t��z�<���\��s@!���% y6k@����
QȪ����T����c�y�"-�ц��[<�?�_��.:���������w����r>u/
����U���=�?֯���R��!��O�K硷:G�~K�IXo�.��^^��ǯ��E\�RZơ�Hԝؽ
�(�U
����|D�^�A#�	)��}�B��B��G�����Y��!4_?��c^�|MiVz�x��S�DZd��䩒'a���rm�YqEh,�>�X��Ή��_:,��.�[��̧��o���)�EV�f�ʱY�d��}B�LSVx�eER�Vt�ʅ4�#�;�|��[/����}�h��L~\�%��Ʋ�O�6�u�#H�Ef[�g�+��%��8�aߞE�U�k��8�~�P
�aG�>��ιW�z��.�%I⧣�����G�gc	�$1��ҊƐ��9�TP���t1��$�	)��;���U�r��?{����fU�����}p����1~�9n�HC�	��n����!��ufe��!�J�!7��7���^(]p�\HX}I�+�������򠿻�%x��7Z�ؼ���Մ]l� u�A�tH*~�1�9C��Y/��f�ބЏ�U= 쳄D�b��w�#�!��
�J����%5�7�/D�#%(�ql8�>1	���o���{���[.L�{��w�6�y�p�f�K�!�W墸h|�?R3��+��c,7:qO�K�}4�,;c5��n�P(�$z(}ؠ��-������cm�tCE&I �j�}�:�_L<���	��
�ʍZ�';���#��ભLx�K�V�b�o�F�VAזunI�Ui+X_���ڀ�57_��(_O�������-����|�� �T��������sY�5m�-[�i�5�Z��1��Ҕ���ך�sA'/E��r�^➕�3#ф愄�u�HT�veA�SUF�#��	5�Ӳ���fV��q)����)���21��s1��t:!�ѻ<���U��NuT{�	s_�n0�bd��4ܫdB��
ײ�v�ĝ`UV��$�וH���f)�*�3��L�B.�#�Ǔ8zU��@��x'	0`�cE"��DDq�f�'���!b( 
J�F�$�F4*���&y�/���N�Я*����4,Yqvk��M��)�8�y.�.�;P����{H�_�V�2�yo]+�����s@P~F�=���f���v��ɩ����:�a����wel��)���?7�cA�S���u���*�i�j���}4�;ր	QFyi�gp����v�A�#�i�f�"�J��b�A���6׵YK�^'�	b���K���y̮��j\N�Otn�:�=�'v���Kͭ��q;��Ec,iة�Ů!�RR6��{iW��'`��>���7��Gs�gB�v�3�����`i�򶟐�7�m���������\KX>u��.
?�W 8�X�{$���nI#=��&'r[���P%�v��ub�ݭwt���(!R�b0��$���*uD�����<I�kj��#���7�u�R9��-PG�G�W��r|4RR��W��g�r��'a��w�H��F�ߴ�CnY�LW8�|\�C�"�H�Zv�������
.w;؜�H�3��!KGKp��uP]%|��U��nt<��[�����J�mφo
�U�W?v?�����U���A�<��Q��͠�uD��k�R��Ŋ�ӕ*RK<�7�!�4���0v���x~���˛��7�X�׃�%�
����]�n�I�4���3����;��14�~�0�'��k�Z�r\꺌pa„�N5_fA���T�@�*�[;
<$<}��L�ih\Zw������Y���W{�e	C`N�������9�8<J�N�UU�)$0��\��7��U�U�?�^��q�u=!{��93d�o�X�5't@�GE"���(.�ȑ�4	Y
�,aƑ�J�I�%��Z8�$L�����Y�� �˚�TY�E�n��f�4���$������˾:&�&:'��������.$�����bDv���KbB���i��B4�cHΓ�c�\���W��f������r��Jj�LYAM�"�eYgY�l�(��]����~��&L�d�Ej�8w[/������T���|�% ����FUH1	P��$��Z���*ԃ�࣐�?�r(-���QlZ�u�)z��	c��NK'2��Q��@�#��p�`a�+�g�1���1�e�x�8x�����|��>hM���
�Xmwӕ��-��Osu�~�og���|�5I�w���k��@�#/X��l�s,f�do���Xx��I�o��؃[��Ze�>�CLw�U���0R������K"7$��/�F�������ҕC#���~� �N5]��sj[�׸Wy�#
!O€����uAYq$Y3�qc����nM�i�M�֞��Ou��v������;��1�'E!c@�W��ܺ�i�܍�~�}-*�8/m��FQ#%f���8\H]	*��UEW���i(ϋDE�E�ٻf=%.�+K�i/��4�|������a�f���\��MO=�U����ܐ�.5�s�/��=��.��ZP#Vq��X�]��h"���DP=��zm
�_�:Z��7Z6�d�l�qT�qTp����:��&gx��6uQ{I���=�lW�������8;0o	^�!w�d��$���H2�*��~黻��*X�Id%��Sl򷈥$�yp�|r�*sU��Q'� .C����Azթ�,��I�N��a=�r��V^k�3�ߊv�oC��T(��gŽIWV:�i�9Ϫb�ê0Zй�Uq �+�N������3�H��$	$�c�7�9�kr]<l�2��jOb�s�p��П��!�Dq?���o�k�拿��3�:���p˲|��|�U���̸{C�?�;q�͍�ᰙ�N0צ
8ͻ^|��$92u��;��v��n%�F�+"�Ò�눮��d/�F��yj�gǢ�H
{M\@\XO��eG���$H��[t��RbZ8죔�?��P�����7>���y�4��@He�WV�o�*�XJ�#�Rͧ�OE
���Y�d�7�_Vċ~Q��=Og��n[�3 5�@��h���HA��G���s�ps�J.��'q�������
�a䪊qb6��D-Ɓ٢��`hZ(q��O{1�A
�����䨂��IŒ�6�~�_hV��9���‰vPs�N��C.7�i�_�w}]��m0�����%��q�%�����E�Y�z����ڣ�؄d�<��?*���@���ݦ*�ɢ�q��J@�$�u-�	'��+=� 5���w��W? �VT�/{���w���}0#Y�ʭ�7J"Zxl��	V��۽����#b���sU��<p�IqRiɽd�|��<�6�(�Uy�d��Jq�_���\�\��C��J������J?_-6��˦S�P�u��$ J6�D�5��Hʏ�N�E�xc�3n�>�M����Oc`o�Ud��to��V
-Ҽ`9-�!�&��\dr�(�m�|��$������X���m�Y��p���Y|��P��>7V�*o��^��%X~לϙw��鴝*w)B�~�$�G����aWN8jlQW����OI�.���gD�U"���}H��p��~X7wݹ�Iʹ��y'y�߅|��&ΰ�~�2�nj^9���i�Z�Ч&RL�1�y��o�˭9���R��7*]<,�+�F&�E�^|9�ɦ�hA߈�K��R�Ta���HT$/��P$&q�o�hJ�P ��B������D�8�n��jFݕ?O_��m�`���lֻ�l���7��zeq
�\N������i;��Fqe���3={�s�K��t��c{lg�g�aa�m&1�x>��ă�Q	UA֚�$��_B��*M��S�&�I��zx�0���>�Z��i7\�9�Ax�[N������ڬF���j��HPme�=�"�b��n����-G6�<��&4��p� ���9�7Q��D�bO���JPX���n�s�N׌��\�6������ҁ���ڨ����^4�KZn{X����2^���Iڐ@��b1�-��[%4˃WF�d�|R׬��I���`�W��$X8��EDÒA���3��~�(e���eΞqq&������?V[j��Ej����gЧ�?
,����K;��f��;�����#6���6%�tj/"��gq~be�M�9�Ed/Ɏ�)̠|��Lٮ.+o-¸�t�Z��O�ˁ.-y���҇���e��͗��ܬ�����ٲ���W�{�g�ռ��
���Z���M����8�̦���O����|1{t��Y�g�t�]�l�3����d3���6���%��]D�j�w�rq��e���I��(��8�K�p�(''��SڍtF:��B�7�+Ƒ��2A�E��ݳY3�W��|�z';?�6��JU&��@�c�6�k��]SCW�)�Mf[�P�h�=S���ײ�4�W	[�	�Ѭ�xI�ou�$�èPg&���+���?"rC��%u��o=v�(Q$DHY@.�o/�o��R���o�Gw
6�l�/x���a�J^��V��2�>!BIk�7\�)�J�v���6Pe�O�I����{OW+���K��ڇ^[5Ģ��ˉ���|�X����R!)ۇv�
R}0�FI�2-@y�3S^H��s��O[�	��)8�Dɋ|@�GS� �@�pc�C+Sz�O7<�3v���[�c�{Q��M!+�a�;P`���K��&;b�!��B��2�ld�)�q�3���D&���TU�Y�킨Y�!�$`��+��A���sF�heȇ����f�|�3�[T"��#���W5��|e=�T�fJ�a����m=�|�3pC�P�m���W߼1�
<��+���
f�;)��Ϡ��/DNN@��\Wn�c�G�%l�����(�!e��$%�}W-��`o�V��S�ι��K��|咲2�`�B�=�gO�������4�x���÷��u��e���/�Cծ�z��@8�SU��e_җ9a���Qɷ�ׂZ����PE����@�}%VD ���#$gЪ�9�>��cbP�2Q��qϫ$��!?^�w�=25�qi7��s�j�:7��ӷ�k�{����m��Q�ã�AQ-�}�Ι{
����c���܇c-����ࢻ���qIYF	�k��C\۩���׆��8�Ԓ�q�=�T����C[]��_�K"�T����T��-�e�P��������!fWʑ�mM���,Å֖�=O�
����og`�B���̱�#�~��-oK��:�ݛni�*��֘7F���{�Q~�*+R��n���{Ocb��^̱�a��SD��/���FV7>.�)���Ή8
h1�Nzz9/��V��W�Њ�^7�LV����D�'����
�+#�!��Rv4���F���{څ+�!�3�
���B�<�����lA����c���o�ZZ�W�D�,>����i}��Ҋ�)=�E�"+��d>������U- �pn19�v���K^u�S���hц�n�6��^��[��1C,��[_r���Yԍ΃�N�:Rr����l~���@��̻����H�;��f#ax�;�;Zy�'�rv�ߖL(�w�U��>hyy��y��os���6�b��'�y�A�g��l��?���;��==�0�w8`���{�h}��(4b�f1��N����d7�1�?�8�y��N�Ͷ8Hv��qk8-_�g�Ҿ�3��?#g���\#
�f�8����;���z���W�tpo�~vg��
���5� �' [n.8*�$ �D��)�:�;�P�ٮ^�)M����e�^[E)೶�!$o8.���O��Ms��K{c�Lyơ�+=�����>��*:b�3��cU��3}�0<+����ߵIX�\��� �H����8v�r�L��(f�������-�GXS���gE�X��˨S�8��my�>'�����'�kC�W�l0���q�<x`x�A?J(�5[V�!l3��T���𙿱!eL�g7�Ia���?n�8�\�qn�J�NZpQ���a�P+�n�ch<�"ex+&��Q*4���&i�~E���N��.����!�����Չ#�9�P�G/(f��'�����ʮ
W�}�c�ʴ��O�ނ����T��W��Xv�iNj+��o��\Y74�o	8�s�����2.��j/���Fb�C�
9�@%��"����e�(����h �i����@�M�༵N_��a�NOЖ3�-�c�Z,��-��me�G�5����f@����]��!
j�~0��(E���N-;�@���������PS�_�
���@PnH{�iaUq�E>�����1ر@j��齦na[{�Ac�M�b��l)���m����̳��>�qnv�o�-�����[I9J�)���Ȳ����n��Ք��:z㼩��ž��&���TN�2�?/��%e��^�p���o����8�s�M�!��r6�}BzG)%�籚���)So~[�l�bTu:����i
�$�\~�>�Vy�t���VÞu��l|����1Sۋ�Ӻ����H�R�n���u)?�q��p,a�6�#�dG�M�(�x�?�<8�n��ɐ��tZw�3�j-��}�7~v?��*�����`� �b�M�c���V�u0����Ĝ��z �џ�d��^o[ȇ�/O����;���c�=�b7��>��q���B�Q���[4d��g�݌]�9��(�� &}b���Kl*�7`��68A��l��Y,(t}��ኄH>_��I��N�6�3���JcPf�E�"�I/�V)?�~"1��Q��H�����\L}�nT�w�I�=6�}��*���KS8Q��~<���ǐ�h
�lT��VNm��h�hmh
��E[�W.ٓ�	4�>#V1`t�+��'@eCCĨ9+�,�wz�N�$E���=^=':�����Ww��дyoϏO�\���+�PFF*\$�+W�߱$�\�U�Sh�D�{rR�ۅAO"�?��=	���~z^��܏��j��(��,�th9��bX�e���46ŏ�����S��2��~B�h]@JSܢϖ-�N��x���]h�*���fq����k���L�D��)�k�TM�I���'i�P�i��e�o64[0�c�5�J��DW m�Q���%5�
%��
�7�
= �L]kR�P䐉e%A���%�Gɒf7(up+��Ї O&�*���(�U�E���Lnu��+F�^1F�
j�R��9<P�XK�-�SE�Vc�<���B��<��_���T�L��Ǚ6n;S�@
��Gl0�
Ć�#�^kh+�ۦ���$�U�U׿�vu�p��Xy�!V]W�X�j#���ŷA�.�X�n���g����{�*�[�
ޠ���BۃVћ:V'|:;:����_^T[���M�"����1⹟�B�G�%`Q��Ӌ��	�������1��gƒ�
���!@��HQ�Ͽ�?�{�	�<�|��?�<�g
~�!"t�ʛ�(����?]R��W����	���)0&cb��;́�/\pD�eyAdc��政��f~�	���	\/!���ե��I�1�b������v��Z)�,�ݿ����W�4�6�,��VS�2-��O������'���Y�����}?�2�m·�G��zl���G���pFg����$��`96Mi�U_�B�c���^y�s���k��.�I�3W<u�[��էf)�3E�R��u��~𳰰a%�&w�gv
z(�r�ee����G��#Fݳ�&�@��)�)Pk�"��Y$�og��ŀ���#?u��C���lIv����9Y�rf�p���^��T�m��&k�`��ë��*��֏hvT{*M�Q��I�׮<�0Ay��efKx�DL��I��n��m��z�9UZ���	vQ�s�ྫ�l���0pp� ����	'��HB?OqY%�J�]�ӱ�S�[ ,y��� �H�6�q�}��w��o�Z�Xq��]��)�j��4�w�:��x��d3�Q�3� W�Fk���H���N>��%!^Ǝ��6H��t��(��c����SNjJ�h-�u�~�PU�؀��<�zy��bc;U	Cu��:C���:�M��ӳ�l{M�{���跥��I��;��o*�.P?!o�:	uY��1;�js-�y�s1[���X���I�(hh�Ɨ='��rƝ)$���v>C�Ϧ/��b�t:���G�:�mk&@��8��	�6b��R��B4�؆�z��A�1���i�~C���J8�]�UFUs�Ni�֕��I���U�T��ʆ�"w�::���&I�:��x(�X��)/���J�'�,J�r��u��<��ou�vy�k3
켙�������=TuaJ��;œ<�1&u%�,%��6�fo��U7�STk�Z�He�u�&c��k�~S�d��]�I���e��J��?�o��p�W�n	(c>��S鋵��D�EI�]�K�pB6�9�}��ڡ��7y/�BX��6��MVL�/\31���j#mz	h�r��{ʡ8O����t^V{\��H�1D.W�ެk�d�U��+8.�U�����.��i�G�`_�5����*�V��O��)/pv��IΎ��>xk9�je�C"����"��y�ï3��0�HRB�F��ZmRCU���{)���`��XVp�k�f,(r<�Ī��(J��)��s2�(Yh9f�Wz1��U���DKSCp�>$pܑ%^!_=���"CR�-��z���om�p#�Eo跠��u�>�a�//~���o�(��-���@,�^�(B,��pu�d|�
�� �h�	�#:1?���u���͈:�[, �M������$��t9X<[>ʚ�"!#
!�W�y�L:
C}��64w��oO�Bg<z+�,	=ٯ�Bc,7�H4U�ޠe\4s����
Ѐ���G\uw��5uw���4��t����-
�Nx�ݍ����97�c���,�/U&-��W���[9"JO<��'1�j��T-Nϔ��M۫��D��eN���v�{�
6���_<J����}���VK]Dk���TVO�8%��kg�u�Ypָ�/%�M��������J��g粢�"�>��޳6�`�v�DoC�b�6���J�&�Q2-g��he�HO�WpǑ�Y&��I,W���h�����Ǟ*^~�q��JN�)�*c��8c耖�2^��h��ߞ�
�$3�3�
o�p��7�u˛��q�(�C�w_�o�NQf��cg��'I9Ye��{�ȱ��F�^n��o§v�Q|KyG�X|��}(=Jt�ɲ��xX�6ꆲh	1x�`���2ɪ�����jT1z�U��x����'�e�}�c�c��X����Q����������^z�����2J{x���y�H�pCҥ�ؼ�;+I/��C�
;�����cs�{�*{���A
�Ip��(^U�a��Q�t*��ٖ���y�O�n;����FW����
��{𼌥���A�"��@6���ڲ��C��������8om{I�Q۝��u5|��n��G�bj��;H{o�������)q#k7�N#�n>)/>��1b+��
��3J|��Y���Ua��D�t�;��c,:�2x��!��kl)��(CZ%�0��l�����{��y�QT����5E�{�"Yx�꧖�|L�Q����N|��$�➯2賢a���$�h{E�39�e�g�2���������S��H����	�7D��x�
�8��(3&ȶ�-8�ޗō��)��|��_��T�$x�5�-U�NO�`��p���ꎡ,��
���.��}��mT;�'�`h���JX��\�w:�V^]���:�uE�%qe��sm_�p����Y�9��i��~�qw��wC�?�\����`MxxCt'l�1|��0l��R�Ue�S���xG�;1y����Z�C�
Qe�ZqZ��b_�l^ȕU:�xΰ�CXx��m�D��3�߯�u󧺾\��ƺ���?�U8Gk'��{�1��t�J�
в�3-�:p�‟))�T۹����)�E'���t���,"a����)h���F~P�r�3�]DL��c����
Ĵ �Jz?�y����S�Q0}���@��VN�"���l4�\�٫�l��x����߱s�U0�Dq�C_��{�޳�>�jA�8�A
����Wq��><:�^ٌ#�>8c~���q��l���.�O��;��Ԑ��b�"�z�FD^`M�9&\��M�A
#�2��U�{q7��؁e�d�Q���i��ą!�Kh���N�)��,Օ��&���^��J�T���,gT��fۙqD|A�{f	�y0i�o���-*�PF{3�o��$�s�L򌚷GF�r*G�+�U@������(xmQ�A��M�r�B��^M,3��#��ٓ/N4���G�N4�����E��h�St�����pF��*[�����(�rr2ID9�
�R�N��@{H�<�<+��37fD,�q<9�@���iؙ��i�VFEd#����fb�Em�FĎD��$<��e���V|��1��Ѳ&��2� �ΏɃ�l�d(ca�ǃ����4#�S9�gć4������P���X13r
0
�0ِqHF���X��T1d�)��LA}PbQR�$�.W(,��ʤ *t����R��|[in�V�
���`�/���<	��4�ZD��7˲�U�t]��`�։�n�Z,}dT.�����&��\"r��ԁ��V�a��f�
7#0<Y���u�����f�
��l�hR��$fC
D3Z@�7�4�A���2
�61�#�6reK�;AN��o�L� �v��C�ҍ�A�8�U�(�9�&@aH��P�@�)��
e������!:�,�|u��ո��J �7<��3��
O��i9Y��	$��E�:����Z"�[��/���3�d̹�	��1J�P��FC,�d$'4�j�N�ʱ��1���r���>�Nw�/n+^n�����%��H��R�bO�d�M��������wJ���l1�)�ն\Jn��RRK�0
s$@r�����\P B�Im>��g�k�q2AQ ��ylFj��͉A���:�
|g)o��T7Vii�x����[h�ͭ�Q`�c������=z�ն��f6\f��(���7�>��6��U��7�W���/�S����d^�
��l���lՏW�����>�K���3�@2���ո�D��~{Im#�j'�>T�*FB�;�nb���܁Tg)Y�%� �]>⫌�oLj�?��*j���G;�b�J3��|�c�:c<X�|�gW�b�*���i�|�w�K���t��M7����@����Ы���S���n2�l���W�!�����1�|�~q
��m���V/�G�/ۙۓ�~s�uͪ�i��9]oV��t�p
�]=�~L6nʻ��i2wS~YN��a'_����|s�䔷+o�^�\ޫ��s9u	�u��l�t	�XW��|3�"B���t}�����-�^�r�8[L��\Mv��[��n�(��Z,V?��Η�g���-��kl&��ճS���r�[��p��~;��e���'N`����W�����1s�}��Um�j�X�v��N/u�yq�����=����n2��r��1q){uȕK����S�[{n�o����l��7}�8�tj�u���!���<���������)�nf�/�kh��.���|��Mv/[G`�t�'BE���[N`����kx9~�,�?��j:�����=��r��L�ިSQv�iSn)�;����ť�}X9saiJ�Sen����G���!�>h��%hƹcn5Ʊ�f>�G�><O"�P�=�9V8�m��5늬z}vQ9���|�|K*�=�%��$ʀ_�B��-�ʉ�=n���,��WA"l�	�~C�Ȧ����n�������zTk��.�-g������=d���!����q^�*t�v���s-�
�_˱�Y�����s`v�ܕY���@cq���<�~��Q�:Ť<=f�{`�0&p���&"�����y��s���5�c���cA�Q�јLj�<����Ȁ���"w�b����{�|���k�W&�k��Q���Q✊W�;��w
��5��/�e��mH�N_�t��S�m���5|�Q�L�v�u/j֜�+���`ub����<I3v�>���J�rR]9M�Q����`�|�3t��_�B5�!rg"'�И�
 𐵥��C�go�!�l�
b��)ӊ�l�ρ/���
�2�#aB�	�׭8�SY{�piѠ0����=�ع�6w��M�h�{����`�U�[�'�uhׅ5�i��F��i�	�!���B���+"��������}8^n�u�f=c�nXW��xة0
�2��,M�҄�-M��,5i�HcVnE@DŽ����Ę�8E�H�a¢�ST`W���r��.x���p���r^�����LB_���.�
��c���6�a����fG&#��v��s�^�rL�{W�}��j�^��D V�e��;�Da������B���_�A�W��c뛐Y�5F�E�jQѰ��7,B]ﭶۉ�}f�L{'v�b/;���ò��' �����_Q��š^(���F�'?IX,ƒ݀�B�ZO��H��M�ᜏ�m��{�8Z7�#��d����qY~�zqk$�C��*t�#A�T9��HAޑ�ZB����R?��-g�X�A����q��z�T�w����1]N�)#���Z<�3>�C����ވ�T�{%/c�Ȃ����9'F{X1��ʹP�8�y��igD�V�s����u�h�۝�<�F��S���H34$
������.zmP^�ا����Mv��U�	h&`u��׼�0MV�C��/�g������!(�c�X�������
(�������pYa>�
�^؛�Tӗg~�ܐ��wC�q�w��*�A��qZg�c�:[\��dJ/�=��K�i@�Ȕ��Ͽ}�mw�S��^��������F3vB���)L��?���Eɑ�/I�~ʆyP�41)��	'�����T@aB��p.��׃$s��ZT�#{�-�{�(G�)�V����O���UW��ڪ�-�7n�n�?MY�K(gM	�p<����#��W�X�����^l0r����"�bs�(�u�Gu}~N��S}4|m��[�*���G.3ϳl�C$�����Y��"	\��,KK�v;YG+Ht��Ѭ�� �M���,���ͥ���-~�
?N2�A^d`i���C������|e�O� �L�O�W�W�kpg��OQB�ߤZ@�Q�"�$-߄lX�չYNȚ�"�ē��DNj(�t� @O�l-bvf�ڒL)X�L��"1D�e�i�Y���J��lC@�6�^����x��݂�3�=J~��l@d{%om{y�жW7�>�3<�!o�qgm[r@�2~�0����;�lek��"�C�9������}�fwj���[�7^^^7[U;o��u��9�r������
��c@-�Y��Hl��oĺ3��J`��΀���e*���z����}����y/O�,��A�,��"��Xv�x��a�Nx�T朇��."|�2�gx��2p&n�J�����7��j�(
�	WD!>u��9�m�D��S=9T�9�d�!Ey��P��C�WWa+#-�	^��4G��w,f��pg6��ϙMbY9��mjec�����J�+�e�R;�Qx����ȿ���M�e]s�շ�E����mm~Yg�0���p�S�N�P���GB
�kw7t���3��"��'i�G���Mu�Z����5���_9����S�LE>�p�]�����v�{50�|]9�T/�}
��u"\��!����ili�{@�������8ֲ���T�8R)�J��e�Tگ��\�5����jϙ9֦Х�
��K;�b���SS�1��<�������#WR�>���[��K��k�g
R���J��G���úi~�i���!�w�&��	��2���nކ�x�]��Ghnw��zk}����w{�i݉��aJ�>���3�{`;��exZ}y���f�n\k�Pً*�D�Ѳ�[>$��(���HY�$���G��%�qC����	�����H�巇�@W�]4�P��N��������	���Q�����Q��e�֗C�p�h��O�|l%���z4���NnT���kݦ��GFm�������O�=Gl_:��`;�X��1�#�Ȏ�����T
!,W���a2��Q��M�X̏ʚ)S��$4�3��^��O�-x���،h����|���aJ!��p�&N6W2���p\�D�}1�Ɠs$� �w&{ʘV"�O����6�߽(I��OfDg����8��brL������j7Y,����|[�6��d;���b5�,����,v��|���i������C?@{b�H��4����j#6:��_FAN����7�D�b�$,ǫH��2F���?�f��̃��A�C
7��>�~+�ޗ�Q�`Q,ٸ�c���)��Y��#�2�%��Sۉ��5�QP��8��m;��d9���?f��+�^�g�2�]`�����"�SG�V�t����B7�?hZdG�_��CX�U���k�n��)���
�ʛ��XuC9*>E"�����q��ɸ:��WV?h�*�1�7�Y�� �A�b�v�"�X��Y��,9�'����s��?�7^;*y���,�P�l����h�և�=9���Q�y�K�[�k�P�)�|��ȿPP��yX!Ș�<�"�Uo1J��ջ�WOw7Lx'�_i�C+��H3V���C����7�SK{X��	f9�l�tB�1a��'if*~����< �P�pՌ�2�K�͵H��U�媭�X��� ��������o
��*We�~q%���wf���:u�z<�0"-oF�Ս�b�<�y�M�0���_H��d7!�O�hI}�=n����
�X7�)��ǹ�Ҋ�v7!f�2w�7_>͗s�7t���|�y_W��$p�}�x�̖$x;[<���S�s��uظ����2�����X!V��5J�`�J�;�&R]��*�;Ri���	է��(�7�B�FK�e�/��z�L�k3Rm���"�x�Ƽ�T]F�x��J�6.�h��J]�8�H(� �Az���bn
Ln���b>�\��6Z��I�&S,�yA��j�f���Z��ԣ
�E����\�2�I�_�n�ՙU�%Vu���")-*�pn?�s
��u��X/+ɉ����
}�"����C�����J�����'��H(ߜ,!��HГ	�ˀBf�=J�=/�H"��tF�>�R�(r4�����,RTwL/�����]Z=:�6sR$((�YX����μuo�V_3��{9��<��n�說uo�~�c�u���e�z4?��!���)�`��V{�.�/�#:@+��EcĊ3�.��|�J��6}U��Y,��[�bS�����T�;���W��`�U��dF���5,�@��\��1���`��:${���ڣ�}{�V����Ym��P@��=b�a�,*���!�ӭ�ρf���rQ)�f#�����C敽1�T��y���˱�<X7(��Q��_�zXz�QXe-(մ�ע|U��ҥ����DWc|�D���jO��*���wϓ��z��y__��˦q�L�^?�	����A�X�]���Yɋ��ȕ��-�*��E���x�!Crսn����o�=r��¾Q1���S?f��.4O��f���g;���� �7%ٌF�eH��_3�XoN�c����t�0f�s���,� d�i��,	eWZV*����u2���xE��c5�	(A�]h��j���H��g�a̜���k�ߓ�ſ�X`�2CKL��,2'��͜�n#�iW�����m
S�#��r�0Ȥ\'����a]��=��}`�"?5܅g��]�2伾�U������`�[lz�뱱fX����0�S'@Y�=v��}�-�r[]m���7�]自3�|0����$��Bi+�1����6����j0�k�,R�����*,`�،�XA�g�?P�	���k�E<fZ�����䷩�u���>"2��7�c�l҉��]y��OJ����tX	��j��|A��{��T�2����}�z���S�]���d��<b9��C�_x�$�P��n�W���)��j�Go�+��
�@�,�0�:0���+��G�Kԫ_w��9���F�Zf��B}�[����f�}��&�y�?fK���=9�R��y�Q^A�АL�
�1��^P���lw6
���{<2������oKw@N�A#>"�z���]K�;���	@���w�"�w�(���m<;+�Mb�$��ʋ����b�le1��w3c���m���i�s�u�ſ��A���⇡�F�;�0�����T�#����A>Ƹ2��`=Y�}P�;��S6ʓ����j��.1�<�G�;�2��>�i�,��-�ހe�+~�(>��:�gh]dGl�wkdʮH�`�;_��v�]
�cKyϘ��B�%�v������D��Nv2�9$p�s"���;1�3:x	c!����a�<�����#Jt�!;&X��(&���}z�
q,��c�Gl8)�Z���G��ʦ3-k]@���ӳ���eɤǽaA�F2ņ��TAE���aÞd+K/ˆ��l��q�F�2�k�.���м����m����'x����������n��˓'o�4zXjs]�Q��r��خ��y��6�g$������8���ד�o�,+���w�"{�����K��*cInL�襪?��U�o�33׽R����Uu~(J�Cv�8WS=n����a��N\��0Ej������4)Z�ތv�G|V9	{��H�Q5
��7D�y���SΓ�2�%j7ǶKr�Ӱ����DʈN1A�ִ\{z,���0���V��ن�,���m��BV�>��(�N�����VP5g�eu����o�hN*n�_$� �	�:}終��h2��6.\�"c�!F�yQ�s"[%�Ԩ#�
�,J��Ĕ�zZemOӫ�Rm�纐�S*@mB]�-���|n×,����4a�&*'f"�m$�/fWv�vG��6��jNTy�����f��Y�h�f��˺�|��]�r���;��݅�~�C���F�)2�32^z �����1$1�VL1 w+��'��"Ȣ�^`n���/��g���$%Ӣ�&��
g���}�q����w��`8�q�g���g�?�^�KC���MQ���b��ϖ�܏Ֆ��h�i
5
�{+�����5B�aU�HК���|�𤦣T�v#�Q�LN��yB�9e?F���*�I8��.į'��̛��ɳy���|�M�?�8t��QD�xe�����v$�ΖS߰B�€��N]9_Vm��g~��o�tݦ�)l������ʟ�2�Y�*�/����%\W�#:*�a�
���d1��d��N7�n�Zz�'����o3�i2_�M7j��|��m���7�lV���X��3�+�yk���~�of�N�̈�l�}�/��o�"t@Y(���R�s��|�m�@;���z����=�}��&���%�*�l���5��]v����-�o�x��_�g��v�1�l�' ʖ��-_���6n�g�0h
9����}~��z/��i��-�3G�ڷ�<|\̾�~���y=�9�˕��m�sSA2_޾��\�dp
|��O��m�|%���nR��+U������6b�Y�VrX�"o�_����
�Vbn	�¸eW��\���b>[����;�ZWl#;je�������ƙ�pE�;���ڸBg,�eZy})�����&pbrX�"o�3X��,_�(|�z-$�o@� �����$�'/�3�L���^��}�x�66��צ��V0��ɴ��W~�4��$�$�(=AVv���W/@��	�@����	O�����z��֩r�n꫟�b��W��}�.I���p�}Ő��*��J0c��,��m��@�l缨)~N��b�ѦA&5�z�U��W��U��NX����I�jSC=,à��.�6Ed�d�H��*��Z�n�E�]~�I�a~H(sh�?,��Y�C�xn��7U=�Ϧ��'s�)W�\�&O�q�4yY�����U{u�S4�ۼlw�G�i��:��)�SQ�v�u��y�YN���n.��`��l���n]�%ř���bg�h��ew�N�+�
�{}{\嗢���N�w,���}�&�li\�k����3w`����SK,��r��\̗�9��d����9r6�Nc;���B?�p�m��v�\9�}6�0��fv�C���97�����u{�����9����o�7���{����2�L��9�f��]|k�|h]�S�lf�22�|۬��}��_��or���7L�&�s�mU���z[�mw�*��@]��	�S�j��zU�݁���/��c��9�Li��)�?6�	shL��I�OL�:'�7���/>3w�����9hzQ��Ǘ�5"8f�%��z�[r�����oƕ��A��Wy�8~Uן���?&����cd�6C"ʩ��X@�Dx�'��(��ȇyZL�!�
���F���O7(s5j�+*i��qe����ҵڮ �K3Po�r��ZYuX�B��'�ʔ0�����]��E1G@�C���'�I�'E��1B=���;�DE����L�Q�"MQ���C_��
��&l&��(E��)\�KcܛȐ�"��������m`#��M[L�M�`�B�i�L!�V�<���d��z�s��mҦ�ם��M�2����'��u�jb�]
E�̾x~��\j"�4	kW���]�L���`4vS؋���m��i]�L�<����e�9�G�4��y+��o�f�Ay1�kc�
S=i�"a@�d ��4�n\��M�8�v��j�����'
�w"
���=�z�N��*P�kF=���O��Id��]3�E�Qw��z^���(�z���x�cA*����JOќ�u�Z�x���� #��_t2�y|��B4�T9J�Z�nw�f(�5�i$�����ܘf�T���]���V�x��z�/�h�:��~�@��
�/�U+|�e���x:+�:T�_C�=T࿇
��P��*�
�C�cH,Hg?����
ȲX@.�-S��.o�0A-n�Ƕ��"03��)�1���i���=|b�����`�Tf:��@X'&�n;�������pǮY�e��s�}e��\
��ݪp�5��&�������ve��}'k�7��l���mV/k���,\�ٷc�*��
��E��xz��p�q�5�ol|~�kψ��Ё�V����hۭ�."��B��FԗZ�|H��ߚ�QS&RZD�6qX:�0J�*pr�(%r���dP�z���Uvz��lvO�x��Ǐ��q�_�Z*�Gea������#�g�~ߟ�g�ܕN�ze�yBoC�VC�����DIX�!�=�^v�W�XZ��RCS�/�/�A
2�$~��t0��n�!��ơ��OwV8#���_5y�0FSW'/����͖ӕ��2y\O��o���x��*��e�_��#:������w������NW����l��U`1_�&�A�˿F���"������>O�ͧ
۬�ڰ#��A`�P�\��EÇLF��';}��W2Z�a��2��OLcm�#zP��(�v)�h�5�{���8!���832S��1�攜 �������+Nx�
L(�
K+�%N|�_����w�Y
2�چq4�?�"���
���a]	��a�(ܣ}�vŸCM#��y�ӊ�V�����W�}��m��f/�)}�Oyc��æy�
�e�v����xjG�[c�F��1r�Z���P6�J�6��`��l�����1ã+gܲa�A|��Hx�ѣc9<uQ����U��*�4zh��9m|C�tq��CK��hj]���L̈]ݜ�k�&+�@Qf��w�(��<�"r�r�R� �M�*�V�Qv��#�i(Ouc����2�j�
��g�
�R5��|P�Q"ʬ�9�g�N�k�bڣ"���@�~/����煑Hc�r���<�@�f$��rt�!�oQ��Q�̋�1t3?�����k,2Y9�p���8a�*�+৑�4{'xv|s	�/�8�YZ���s�.9�YX�b}��j�6�_�-ryހ��,:�r�Z%�U?�����>�/X�F=��W�>Lֆ�\�&J6������;`S��4�C�⻧�^*�2ч[�c�����l
�¹�6�7�r?��Cg,�d�uq{D���Ei�Io~�WG��9�J*2�+u.8R�Ϣ�U{�@G�f����HdL������^4x��1 j7|P�����?/�V������P>ip�HI86$:�sK���\q�G��!띃A�V%�F^�|m�)��f�ZWI�S
��j=�ή#�^,�s���)�s���_܂}q
v����ϒ�y�.�� ����~
t(�M�@6O*�jyND����V��zC{D�ش�M��>�E��U�nِ�
���!��#4/,�f�����N��xm�Ѵ�@�7�p�UAP%j�Ѓ��n���u*FU�íƞ�_�D �z�,v![�3�g�Zj-��!EBDh
8J!�`���LUJ]�_�+�U�(ե�!�v�g_�"���9_K��r�x���Nf47��ߥ��{�*ܠ�kRi��Z�ɞ�bh?-h����+�X[xY]��x��e��n��{�\-�O�����ot��	u�i�y6n^�z���PqNK��!�ߙ/G)�ד��{���V��3��|��_�����3Sg��l�<�����,��`�O�+Op�뎝���Fw\����B�K��Ǒ ���r|�'oNI����N��Oa�kpQο)����R�K�a7�x�3_��&u"��'�Mb^�L���R���7p�KF�i��ͱ[/�}�JKt$G��7�QЈ�!"4%
K}���rg�HE��LC�(yT�l�a徆LJ���Wk�N��9'7B�j<)�b@T���E�#�崾���Xi��eX��	r�7O���IVsg�3�E��	��Wh��2h���I0'�z���"����pG:�����.k$X���)���Ш�U"���S{OW�a"�̆)I
��7�]��S�3(cK�����7�)?)x	;�<Ҷ���I]t�6w���+Y�MC+[�Xʞ'T&Y��,�ԍ�6�<�2W3]�{5�%��Ϯ8����)���4��C��;T[t��s�P�=Ca,��A���!��;ĥ�,U���E
��2<��-�+E�)r�
�ܐ��ry�3"�0Kޢ�'g���ٷ��B�M䷩�)��hQ2EB�0��,`�,�����]X`7��/F����D�PY�`[&�~�?ĆͶT�i^��1��Ƣ
h�j�W�AT:���fF�gGFx��<x����v�2&N��c|��_�12��NYJ=��-�!>�]D#��HT��u;��-���v�mS˛�v���������PUl@��p<�#�1�n\e���A�钞����Œ�ޭe�j�Uw�6�>@	���xB��Ot��h@�"Y^#?���$(VY�/�+Y�)�Q���y���!�ol@�bh�B�)t�Nj�knL�nSR^^��ug�h�[���regP��G�f�z�b��Z�azQ*+R�I
�g�Y�~��s��p��
�X� �I're��b���0 a�޵�9Ӑã�.P4՝���
F�eg?=�̞����KS.�X�X���j{%�G��p�	�`D��O7����+Z��򳷪^�^����b�(�t�r:�	:=�e�a�p�pk�zCM�fX�7Ò}Ӳ��tC��~� ����ė�C�3�ܺ(Ⱦ~	�p�#�p�E@L��m@�c�	D٘I���~�v��d��l�Xz�J����i/��r�I�}٨�����T����~�\��K��U;,���A��޳i}���u�)��վ��H_����E?PE�Kx�Ff�3��q�O�c`ԉ2=BlsZCp�z�_b��!��S�E��_q�E�X��gdy���"�պ�:իK���?�.�0�g+�O��QV�(7V.y�(Z�}�һ�25c�%lh�R���r�'t�3��g�\4��D�3��0ꈒ�u�;ݷ��N�׳���\�����_&gb���d���/�����7ӗ���'�@=�t�X-�??O\?�gK�z\!�*���d����r��v�
�@E4[>>O6������8}T`�a��m�\0�iIdpT��KLq�og�'�m1��R��y�,��R����d��,fO���
��X��-&,N|�^��߿���Y�J����ɳ�KZ�~(_�W����y����̹,_���Wɥ�+�sά֮!e�:E��*8*o��W�¢�7��������W�,D}� ��v�<w���/��E����8�m
��/��_�ӭ¢�-��̐��W�
�a��i9�j�g��
{-��;��}���,ѫG=`�v��"����Q�]�;���N��|�#�0!�fF��-��4��G8�)��
7�]��N�֡h����V$�?Tm|�	k�&߻�k~��Nu��ӫ�PY��1�{
]��W.�tU�G�h����D��*��n֏�0�%��*"�&�\��2.߷,�;�9P[sC=�צ���{�al��[�&p���܈�ԑa	�J,y��1��ǨöQ@��~�lw*k[�g�n�F@�(dH�2��bI�>Ќ`����� ��{<!ܐuƏ�H��Ϝ�P+��c)��Զ6l�0:�CiT��B�A�Guz�2���\�l�gtEc�R6q&`_q�Q�smt�}���>�>כ�qd!S��{�ػS�?쫞�]_۸8'H(��(ghH�NH�}��@BX��G��Z�r�)\�<ҋk���;F�y�߱�{��b�{�+��39�7lU��u�H�g���f��"Q-)��
�Є��KQ�y��O�1�k���k���1�G���ܠ���CY�rtÞ|l��Qw������#`�٨�P"����i�8�-��`�V^SF歧��ˍ����;�.Rp۝�Sg^d9dgC�ꦿ������|6����&2Gf+G��H$�㘅S?y�<�)ÆW3s�r�'`�a��Q��_���:#L�L�-kN0�^�S@Pr4�x�S�6.��&���gX(�$�ͽ�Q�X��ʆ���b�܇���qV[#�(h��y莅�X���@��,ޡ��]�H
�s!ϱ�;��$$��·
�`/O�8�6zds� E��g��X{t@g��N�t�(,�6*��-R���)���9�h��  9`�$���XY�#���x�D��>L��ĩϘ��#�P��cΑ=�W!5Y<	3��e^���rb����̺���&�d��u����I�vJ
�
dAM�@��:@��lD��4�+�<�)c�S3�҅IP�Z|��E �����K�̉��t���"�̖���/\��c|�����ی)4E#�<�À�Lf��3|}�	d/B���H_O��2�)c�>D`+~�J � ��<B�X���Y��~#d�(�.?��≲��$�"lB�����՝i��a5r�N��T(%��5�B���1�dj?�� .�k�j����v�՝�Z���UY���ڕl!���٨D�S�h���1�T�
�c*\�s��(�:�,�
/3Y��P�8�R�rL�=G�W.�Q@�q1Jط��pP�e�#�c�(E��\��1��[��}�9�A����Y���e��?�fC,y���U�W;�*m�8½���h�pEv�>nL<;�=�1�_�����//�}j�s#����2}�ܿķ�e��5-��.o�������HN���G	���/�c����}o�QV���/#�{e�ȳ���}���
���E�Վ�jC�Ht��������O���^��e
}�ԁFp:��[�����QO�����A��}���
��I�~���;J�������7�Q��cZ���OXnUn��k���MX-(1�S{b�j��w�P}���B����lt�j��$>s�k��Jj*0�I�G��*���c$l�'?N�k|Ӈ�qT�x�y2T@��'����v��"�c�%gg1�K^0!F�%)�8-�s��B����k�6P��$3�n*��j��ڰ#�H��<8���i�Gb$�2YC�F|�����R4�l�Ҵˊ�@Ͻ��E[�����vL9��F�ߥ����r�G9�Q<.26k�	0٠vъBr2��g�=�G6$g��1:�H@E\X9V}I��]�ijf�:b�$Ԛސr�g��&�A�Yp����ȁ2�C�[��g	�8v�����x����#7�h���5�c�'�D=!��\�/�Z'#��b�)�t��Iպq�KP�v?�R^�j%�1ą�㖄v��§�7&6��Z��Pq�syIX�5��[���t&jܾ�jjr�L
S��}q��L�Б�/-W��(�(�>�^cC�42<�~�Rb�s��E%A1�}�Z��}Q)
�H~[T;��}��</R{�=r�z9��~o]a����!�K�4{����u�N��6��WF���aw�#����
�'����1����[UZ�z��5ϰ��EANt�S#�	O�4�%������랾��W^V���#ηj:l�3�VjI<�Ipy�,xʠj�>�r���S�R�X!1�Qp�����'�+�����)dL�	��ҭ��N��{��5��3s�~�>������I}��"�Ƒ��kC�4.��,BdD�.����&��m�Χ���8|�څ��bi��-ؗ��^h��_}�"?�:	sC�1("C橧g��//{���&��ct����vT�H�|lFIT�S�R�b��I#��`t����Ӝ����E+I�隱p+�#QuR�̙���=�֔rǪ��g�C;��!����	����A�R|&����2�Q��փZG�@�h��~��h�k��W�y�O�/g���]K��cY���E�x���\v��ȇzȀ��Ϙ/�F�6z���|̘Hy��a51@�Z>nJ�!X�����#>�[u��߃R![�$lM����SU�7̏��ܰr�:�%���*�+�
[�������z�3\/��V�\:�)n��r�~&A�q+=�~��G6b���o��cP�P~����}$r�Ĩp�9�!M�zl���TQҲ��
,��Vs��9�mZ��6_$u%g�Ĕa3��(�PıW-U����ım\��(2ϳHܔm��Ɯ��������/Ey�%���M!�J��,:D�>&f�2n�Vl/8�e��Mj�:�)((��-:`�c_Dq�]���K[}X#�.+��X�g�AK���iʹ��V�Z���@�����Rت#������ߖ�>2ƣ�`Kzv�/%$�y�hR�%�EB��H��y�^��Pw�0�-!��W�JC�O��En��?�܄��ww���ˋʏ�v=�μG���+i@V�G,"k,����_n�f��m��=zO/���	=ϧ��ve�l�Snj�<M����[藗��
;�a�-��l�3,w�X�c;�,Y�>H�%X���"S�G�.&{��V�;���\�_q����o��2C��Q��(d<��|�'�Ctگw?KO_�H}��M���E�kڭ�
|��em��6^�������'=ve�����y�2�Fy�Cv�������W�ƀb��EJ^�v�W�	�C��2o��lŔUt~N�d��t��2��Ann�賟��A�	�'?IXL���X9��4T�紱����?�Dg�r1e�vpq\��Ei㊄�Sr�X��V��V�8�60�06,�4�8����ۢ+OX.�� �!u�׌�=Ky�۹Tק~�59����6<jô�ـ�;�^����o�r5Ri�9��٤�k.�&P�ܥ�2[��;+�l@.��:��5�#���dWX���@��X�Y��@U%w��>��В���Yhn�T�[�;6�I���Y>��$���� ��=RG+hk�����t��x����>E�)4ި�uK]u�Śbk����m��nv#�o|e�_o��7�����n��o3�%����t1y���%��>Y>���_f[R�+샖=hY���˶~�8t�|�&��d�K�ƶ.�x�i���Ee<�X��x�y����疫����e����%��Տɜ�e��1?�1G��n����_W� XoI�~�[���H�c	<x���L
'�8'(�v��ȫoʕ[��<�@��r��S�y
l��)���H	�Z�;��~�X.s/O,JF��;�z>��c~�X�^�V����
6Kޢl�G����TKBu�c)�Y��������U;�&2���{qt��q�nz���{��X%F˞�A̴<0�l~R��#��2���&%Mrh���_�H׎?�(ه�W
l�5۷��YG5�>����Z�:+n~l�ͫ}��w�'���88)S:�^Შ�6oh@f�"eII�q����Tٙ��i���2��*��"��wbK��Q�׎��iXbq�*�^�E��?ey�q$Z މ���~��34�G(�}e}$J���hA�:E��Sf�(9p�ƛG��;ty���\?�2�R���Y]��Z[��"-�¬�p�\ԭ�nw��:��N���2�B��
t8��aށ>J�A�?#�<��.�)/�Rq�,��K89ݍSfW�%I��FBȻ@H�K7x�_Z��K��!Q	�-�@���6�^�0�!�mCG_�:��v/�m'���y��y�(�w;iy-�g0��19�~�y�ǵyh��F��'d2��D��z���P��C�������n�2�C�]�<�8C���j;h_B��'�	�h���4TI�4Y<�JyĄ�S�A�2����4�Y٪(�-Y�=���2���D��V�X-$G���z�G�z=M���^=ȟrh��qS���e�_��ѵHM�/k���J�p%
��0q9;�T�e'���Q�ѭ��y���k�>L�hY�Tq#6y&lA5j��3�2 5k�M��*�
|Smj*J��r'2RZ�G�b�J F�b�J�_�=�Q�1 8]�UJ�6OB�Am�I!�����+'�����W�DY6@㙇ѡZ ��}Z^�2�r��jk�W�n�%��(�Di�=rJJK?�=�$��;i�W0H(d��Kd��������
?��|��U�Q��'��I��(y��۝� �/����#�(Q����(����iy�����b��/�9QANӶ�k�~�zTGF�O��@�� -�Tx�:�ƈ�ˠ=<mŪf�"^�A��Q�����,vD\9��X5J�x���Ӻ�|[�)�rZc\`����r?;f��K���'R<�����X��)Q���{^�&�?��-���tE�O��9J����*�F_�Gn$A���&)�/�dž�j���l_G�{���fV
'�m>�P��"��JR,I�}�!�Mi�"������'?	{�'VV����-�cE-ߗ]��T�����/C5j��� ����J��w7��J��5�L�iV/����`�)C�2���T�:z��I@�eX����T �z�L,�t]=��
'���_P6~���Sr�}�*��z���!���sD�rKƒOWf
|��� �r��tA3�Ce��Q��
��?����'��E�z������u�gT��?~J����f��b6�p=6��׿{�e������R������Oi0��ٕ�|�+��ƿQ��s5)>�4|8�$
n�k�{��?Jk�-���XiT�|U�M�5-v�K���+� �m�$>ꌧ-,r����ŘMʕF�GԎ�+���إ�*<zɺJ�`��9�m�zK��֧
�R���U=oߺZtt�z��k>������A�9��̄^;ύ��E�3.I���YK��� �����D�Xq��(a	G��}�Ze�7�����4���R	6�U�+�u�F��G��-�P�͞=�ml<�r�}<�"S;C�^r��J(�)��s�,�{،Ew!kÈ����Ѳ�Vo��W���Q��,	���m���c�>����[�˜�ͦБӚG�e\I�܍[Q��tX7�Q��kՑ���<�T���m�k��ް�h�˕��Q��IZ�:�Q�j�YK��ўwY������2��d�
'eZ�y�c)�V�u:ԍ�U�(��i��致��=������~B��"+�XtLw���~��Q�W����A���J�5��W��dz�e,�w�d3�44Qn�`���HY"zb���j�����v��ɚA��zw��P��LeJ-"{�
�1�<�T7Ƈ鎑�pjU}��6�o�o����7��Z�Q�_�!���ʐ�Lϛ�f1��}���Z�����ɳ�������x���8E�u�u4�e���`y]L<�~o'ɿFiZ��U�Fd�p��}��ȥ\K�X��l���*��Pc���PtF�ä�y����G��R��/cT��1��i]��I��A����Ȣ-o�tE?��Ci�I���ud���6dCU�R�j��;������|T��3�#���V~M�J�@UY�YY���^�ZUV.^(�)9�Ӷ�[c����n����#
d�3��FˀVN�N�m#��b�L��;;��1��e�XX�:8�%���'��^z���$�%�M�T&?���>ـ�s䲞�E�	^d�Pɿ�35��S$C�P���P�C�A��߈<\�K����9�
vme�%�ӕ�h��Hl����N�ي?Fk������w�A.����g)��E��?'���yd���ؾ�(׳鐪j�H��uU����i���d#�
��"}=P=N�n��3�gI�þY	Zuݲ9��er$U�I�M|�k���ħ�61�kk��ѫl%������IӃ����h��ZZ�#�9(�4�E�Kid��r��b�j[.7˂c�vW�FS�[*K�Ϧ7Ar]M�GӴ�ª�O+V�S����b%>�X�񋕔T-V<�"��fizN��&�՝�Q"��d�6a}ƺ�?mo��6����)qv�Qu�`W�5�O��%��nM-R��a�$D�E,�L_�C���D��I�\S@b"}.�,"�2��a��5t���x<��qz {���(=����'���݌��8����yp����L��(�a��Q�!���_z5��l��˓ù�Vg~h?Ԑ6��+ud������PFD��y�zb�r��W��q�c�>�=x�1^o�"�8Y���K3��fuh3+x"�0��h1�1��e��VY��/�v�N�\ݹ���o��w����g�� جW�R1�?��noqVx7��o�{|#�?.���N'��V���~ �/(�׬��f5��|O'�"��sǟ!SvyXә�)$H'?��L�Ù��1}X'7�έ��0έ��E��-i��s*9{���K�)Zy�����kQ�KYC�2�:�?;d:!��Y��9&�m�
�R���FA��)�Ǣp�ڃa ��L6����]��CQ��8�yyto����hKP�
����YR#��>mw��D��]�}V��R���`�g�\�ͤ�ZҠG|�q&0�o��'@r	4�j�&PAr!�_~5s_�W�A'yn�~8�jʝѰO������A(������8$cs8���3���7ƾ��j��i�~�)�P�u�L���o�s|�26|Z�׻b՗�<�R�Ŷ�����|h[�r��j�\LۂCv���ڴM!��@��iխ3��3�#��sS>�*��
�Բր&.}�@�T�����"����VO bQ�b�V��q�x3����A,��G��h/��J<�5��s;�'C��L��aL�0�x�z�h����
\��i��ޯM?�l���gYgY
gI��l���Y��,��,�>���<�իWȣ�M�,�YQ�� ������7JR�.ZG�x
�/��,��ɫ7D�4��4{YNj%�p����c+�Ox"S�\� ~�N�H/�Cu�8[�*�I2+�@��&~�.P'�<S��tt�q��5��N~n}џ[_���t}�^@�oK^�H�N `C��!f%��y���>����2�D�z뻽����$(��M�ǜ2��b��#T��>���JF?�Β2�0�h�'�U���ӗ$��%a�y(��|����z�����ߧ���H�m�L���/`������9����b0����C���/�O�]ߞ?\�g{��\�]�}0��`���Où���û��!l��ӳ�M�.�����ӿN����pyu>=�:��2]]�'Cy�O�m|1�������P�������ӫ�������́lӿ~:���#X�U|{}wz12��no&�7j���W����dr?�����L�nߝ^
f�̅��pT���~8���@�7����w�ɠ�A��縸9��W+�Րm����xr=�2QU]�OO�?��z�D��ɐ����d ����.�U�7^���~2}{=�i��`��dȂvyswuzv1L��L70
ݿ��0�O��J|�7T��|�e>�=��
����N.�	�A�0���nz�n|{�0�Ȧ��O����.߫��j_P}�����9C�Av����]��W���ed9��?�_庽"P ����<��d*� �խ�����ק����5\��2���S=��a,�9���0�A2����dz��P%G\£�7��������Łl�*��������▾u�>?G�_�Je�Ż����Χ{�9�>�8��]b�.j��q�ar���Z?��?�/.�༽>����n����g���]�=���F}�˛>�:;ܞ)�tr����}_܏/'t������pޝN>�����zv�p39�_
�C���?y��8�x�N��ۇ�w��_�2�˾;�}�w{����$�p�@��ɠ���R	���ޫ����b�p���![��:g�>���>��ɧ��X�˝�W�.�&C�k�m���x>]�\��3��fHG�Z
VW
�S
VP��H5�r_����H�x �a��z
 �Axbv ����b��0�����f��|���3\�'C�.⺹�p:���b0����n��3���ӳ�N�{P��FX������a� ������]i:}�a��i�?�!K��ʢ��C4�?os�Ξ���k(�H��sp�G��ڡ�ͲY�,�9p��N��\�E,8�q�8
r�r���a�M^K���
����\��*�ǹ��A�@���xaa	�%$�pd?MTv�*�ؐ^��]�V�T��O��O�Z`"�;g�R��ޮ�;"�`��H�qQ��s�om*d?lT�?�b
5�P��#�l\N~i����pU�`���)�҅�o�����'�v.x�ϑ��]�5C�fI��n`��9T�r��QDy{�6
,�Uj��ry6�Z��,}L��P�ZΐzG�XmhX_�;��0��2u
�觍+�z
���^��L���4����U�j|��-�6��*��̃�-	4
r@'j���(�iY�#��AFx��^F��M�m�g���5�of�bч�BS�A��Qv�ͯI�3I���"��$��2�U��S?�j�Z����C��l�'�mg����>�~-b�"�ƭ���|�`��3�S"F��]_+"E���ݥ�A�_��n�E�]'4qۗ\�^��I�k8�"�����1���R��,)��[n([L�%���^�3��
2���CT�2"�F�D]�����
���S�2pj�D����X��ҽ��L�Y��!�KX����̷:��$��zD��x��RC��a�K�B2m�r%�j�{�՟s���r��TS ˓h�.yN�gy���t�$n���:ÅPE��x�3ؔ��+U�<���c�+�S�,p�vR4m�๣V�Ŵ(7��'jc~IJ�ԏJ�����&�"�a\�\.L��h4~iW	d���B��^����
S_�T�.S��z������_XX_�u��\���K�PI��ڶy�YL�C��s��o
�����:�%�+�'GA��P����t�:�hP�e^��6�L)�&����-/H���7�[�['౰�u�,0���G���ǧӬ����pd\#��eB��MU���F-��+T[�/�Q�	�B��zA���<|��z���aZ�Kd�����q���1��`
l��B�l�,vi�ӟ�a�Qh�ظ1D�0
c0I�Pp&쁣�5�P<pZpKZ�-��%���"����O�新[f�#h98d͟�̻4CДd��/-().�$��,Ҩ�c�X����� IU)`��e�0[<��,r3�:@A��+%�M��	�s~���Q���X�e�=%�N�F�}�4�$]şq�hh	QH3n���%o���_�i�u�'�?A4�����4����M�/
E4LpSg�K~:&Ϙf�WF����)�[��m��C
XdU0e��x�о�U^C�ꡂ ��G[U
�Á��O��H�d�{��g&��W",^2�0���~�n��n7��}/ ��:�ţ�i��+<Ysُ���A���o8�d�w���8t�dy-�]����76@�OCO��$�T�}�^<˳uXe�g�u���K<cZ�V�4��j^�X,f�_	I�cT���M�8f��B�i8s�5h?D��2�z?@�J3|��6#�7d�x�.�Eͧz2{R��&a��Bx�lWnw%^(�b��H`�E�+nf�E�E���&��I�b�#��~���}�4��_a�^~��9M�Vx��]q\���J��?#�?�I-���!�y�>Y��sB�j 6����Q��'�7Ul�jڥ�g��(��5|��@TQ�1�T�#��ׅ��<�v���z�@�r�R�IA�!Z�x���_4MT,�Ҳ�ȟI���:M�jH`��^J'�P�s�p�t����h�/�(ϣ}ی
���VO�DQ��^��4ʹ
��0�G"x'�V2j��P2�SX�~K݆A�p�o�����6ead_j��3�:&���]�����ᱛh���^�z`�Kخ+X}7�A����f��C魻�q�k��Ϭ�]+qe(z��Q��D7��Ŏ����LJ|�p��LkAR�h��3R��^�`�&���.0L�i�{9Yܳ�)��y�i��%��{lsA�^�4�P�}pX �D�����q��5�D@��7��"�
�e��,x��,�D(h0$��ز5@)!8���}-����d�����!m$�
xʌ	~
[W@$���^9��#Z�����Ʈ#��3.\g������O��$-��t���%"t.�r.�Ư�x��t��04>D�bX���Nf	�{����u�6�ñ��ؓ\�6H�!k�����&Q>�DjW%�:����w�k��/��(uM��p�v���c�����k
¥�o���Rr�k�<Cyg��T�ݶ�KZ�u-"c�ئqa�z6\x�,P��M��&>n. �k����:��h�c��<E?Yc]lǴ��z0�9�O4jtEd�y1����/�T^����93�˘f��
��y���<\N�N��'oM�.֦�uf�J�k#�	�ۺ����	*
/+8����R���8v��0yǚU(�]Lj�l���F/
�iw-�?v��a�^����E\�XeA��ӲX'���1󬓚f�-�l殐�� tuvV�x!�LKE����&�0��\��|P\��k�r��M1|̓)�cn�:�z�<���Q��D{�c��j��>�L%R�%�8���� )b�J)�o�J��:���U�7�$��W�:4���K=�%����	�fj��x�����|��&�1�����'$�I��|�`T�4�Jf_c|��X�e4����{�`����R���3�����t�w��'w�+�y�ǯ�.܁=��c�b��B�b�[ӄ1=DDU@���z�3�oY���8X�g�:D�x�:������T�@S®�3_�&����m��^9C���x�5�.k�)�"�����w��E�J��s��!������#��t��㼂
�E�m��B�hu��U-ko��n�rPھ��b���166#�@�l,���nKL6ã��w(nT��Va_��Ѯ��#��f{0�vh]��
D����T+���KV�y�s�Ⱥ�,ӆy}	i3ޒ*rZN�	��yq5	�f��#�#�|�
))ޫ�1�n�䪈e����t�>f�� D�x4B�
��=�m�R\d�WQC��Eܯ�,qi)�����%~�,�Aۭ�B�dmt����U�B�Ɗ�f��x�LMU�!oJ{�=�X�K��K*p�����?������8��.�"���!���Q�	�@95h��Q�q󦅛J+�t�����H�_v���Z�sX�*�X��6���C���u5���
��
��K[�:�G�kLU��F�#�_��$p�YI�Ů`�����=�lDI`Vt�䚮q�,��I�]G�"�m6��B�9��n_�>�ueDn��K#�"i�%*��E�����Q��u��9p�u^�(]7��MU�uY��R��uጘ0�j��Onl ��J̈́~�1Xgb
0j
z�*���}_�s�ڕ�D��cȉ���T����3�slPK�c�B�P�C1���Sr�e�]�.3���.��UdO5�V?�>v��/L�y5l��ZQ�C�'0i�J��j�fVf�-��@�gX�����x����'����h�C65,�2��ʵ��˶�Yi�[�r|����c��-��b�:��6�O�zI�P{C`\1F
�(`=�e�fU�h�U[L����Zm��$n7b'���#s�3�\؁�V���r����<�4���Z�f�d�?��w�ZTTa���0=h��}q��a��P(�>��N�"u����p��.�r����W
�^��#��]�
����S�,�M��ӟ�����}����8Xb��7�7
�hǻ�Pls.��=�R��ɍ���ͷU/�>��w�r����.�b/��4����E�V4>W��O��7�mE6���1�o�&E=���6��J��:j˼xI�S<7JO��c^f3��㦄ۍh��w�Dk}��^�{�u��GK�^T�w+|;������bծntu��Ʃ��.]�N��+�j�d����.���UL 0T�S#L�EJ�O���mv��	�zT+��i��{�F��y��+ X�;x��`�6�u�F�a�Tp�\����9�/�3(�B+�~�%�Es�<f/i8G'�D�6���:�
4 �3�>�B�t�s+�_F�`�c��B	� 
{���[A�q�7V:� [��=��h^���q�L�����Tk� ܂�M�W֦���B\Dx�^����3R��Mq(� �/����R�c���R�>�6��A��}�+B�B��@�9d�I
M#l�4di�#���d��`+O���f�~�kRSe��c�ʧ���=һ#����{�2�.�'���c���UA2�SB��>ytO�mk1p��ʅg�����vP���CC��>a�7Fdr�5�.��I��]�X�х�QE�A[4G+AXd.����Qپ��>���vHE�e�7��av��N�;��6"Uu���͇?���!&��`x����{���x�q�'X�4�aK���mW����2�>k-Br�g��������m��>G��t�Ɨ~��U�稡`�m������!��q5?���K�O��[�a
Ə}�,KJ��m�BCQ�`���Y~��ɷ�1*p���W�c�:&��̣�
��i�����نn���v�~12�'�ܲ��b���k��*nd7�O�)�^0��u�Fi;Pi�aqj�X�[�F~շe����H_��;�0D[�h�Ԯ"�{d���U{�M�P�8�`��ۆ�֤}B"��1		� �e��ٚ`�O�|�0r�ǼT\5��N4#��9�<�P|g�q�w9��6ӝD�o/�s��b<F��7����]qˣ�?���=��V�BX�hݏwL������~��'-�0�jUT���K�OJ̍�2��z�i�R $���h�p�o�kq#�<*Yt���dyU}���:�cq�Y�he�m��v�2<���0��^T����'�{E������/�'Ǐ�}l筇^s��p�_G_n+�d��-�M��sD��3
�\zm�:v!�4?[����0I��8}ĶKł��q���sQq!�o�8���vڏ��.xk5>�2�����;,kA�Ī�, ����s%a�E��sB����5k�&0/lx&Y��Z��e��_�r�Y+G@�~��vM{�/،�@��L!��W̪�hdV��_ˤ�������_�7�`1��}�6��[�	��H0DV��$�[�h��h��v#��!���@N��10a`��,`��W	*�H�f�1��Z�������iDF�`7�5PZdsK���fF�r,HK��HŁ(b��?Hع̓7p��͢�B��݈H:���=���
�������B,l�^}�Nφ-L�p�S�s#�K��5�� �[{c-�=��ec�+ȅm��<�O0��1S���m�B�����\��H����֩@�(d�TU��w��Z�z�7��\�.m����	6�Ṏ�gpI���~uT�N��c6ōkԹi�/)���
�S�q��2��2;!?�kF�3Ϟ,��46̔�pN6��o�5a9Sۿ��i�Z&7�������T�%��M�r�m�GvtH�x���:���� k��2{N�׼v�4ߦ0q��p\"�7w��K��ֲ����0f=��Q�<n���2�`�E�з�w۵ܳ�pu1G����	��2:�2Ztܱ-�&�\�-RN��[�I��W��^Z �~��(�l��>��M���DFT�]����W�wg�|��
��u� Q+Թk�[�B��JP���SS���;'��!'\�V�~�/�~�� п�س�$�b^U0[R0���G��#��!x��Ԁ���t�=qT�Z�+H��涆�G��Z��j¨��B��;��l������_���
!7]�:ξ.���ќ��)�%Ƭ^�p�m�Xe/aR����Y����j6�Ko�~--􉚯�Sϡr�g�Q*,<���9dXh|���oDv�/Iն�,�ԫ��A^��|�;e��,z�@��Wr��^3��Y6_�t�=��U2_�z��;���)��JR�����lh�Ϩ�]�,�6I�i�:�"m�`-1���|���V� ���&[���ց���8�F�|�|k��%[�������A��Ѐ�D2Ę��.���i�a���v�n��A1�w�j3Lv�N���z���~��3�Iu@�q�a��VLN�N@ ^�	�V/�M�jP��Q� VHs�M�";w�w~:9�Hܭ����(� ���S�CO�>���kwD\�!����/�U�rq�3����H�θO�q}���l1��&ҵ�OS%[�?����nbI�r�Ȏ�������ȶFo�$W�@�
%�{�/��D����x����O7�85����@ޘ}��_Y�MK��>�L�⫥Ú�ۘ�ڈ�)�`JJu�vP��IzD?�
�
oVY��/&}�M^��ӵ?�z��P��gAhl4@�#o�s���u�����pj�F���;��j�|�0y��C��q���s��m�&J��P�F���[��%���2\)� �-`fn��#q(�Y�hKܣ	L`Q�`]�&N�b��)�
r9>��@*����+>̟�I5�d���[�uEI��Y��m��\}Q�����mꇳn۠f�|I2
f�����/t#�9���a�}�� [?(p\ �=C������]
��qKJF��'y��w]�}����b���?��菟Q�nw�&e�E�9�R���+�j_s�t�@���C8�Lj:ǻ�4�خ�Rg&͉�w�rA��vT	�Nk×S
L��S�2�&I�,W�$�gNSO�I.�tF�v��*5fd�
1���6����Cko�i�7Q�dP�d"1Bk2��#m%n\Q�&�
I���<�a]���L`�4(5Қ�C�k_H|͸�V8������!�Ѝ��1#l� �����8�$=ǁ9��:΀_#4�!	�6����m;Xځ�T�~9�u_a�е
��#D��9�?@V�vYj/�/��_�D��	Ʒ�W�gNC�M7�ޕ�H>���[�Z�,��e���3��T�,�1�2Ȏ�i"�iq�4��'�SE����E�љ�H�װ�息YA@7r�1J7���:���!m��k�a	U=����6��ٯޓ
�M�D�_�nV�}�=m���9���~[I�?Sm��k���T-9��&(�s�9N����w���p_h�j0c�������V�Y8�O���}��>8-����..h!��n]&�dC/��u-Qn����".�h�ΞA7l08�@����:�!P�۲V}�D7U��q��R�XbF�u��Y�t\XͺKjl��Y8����.�5���&����}��l(/�H\@h���Z�aP�i)�0��z������mdQ��͏%���N&3G��QE��'j��{�����)3��\��9��}��+�c�2�%�?F�{����d-��wxP��HM�c�eE���Q�otc����ø�g!���N/�,�Q���j>(�*Al�Ai�,����3�9���HB��+�Ew_�'��N��j��  �W��iq�a��(�"�����v�p���k�[*�r�!#��2����Ӭ�����Z�9D�BlEh����Z���	$+)����ۍL�E�a�y���U��<B���X�eOڡRx���X�Cҧ�&1�ףG	~0P]��&`3U/�ƫ��٩+W� T�|ҙ��A�]g�@�H��>��5�jB���Ĥ�j���0�;���͘1���K�U��&�d�c#(��L31��qZc���"�F�MF�����m����^E�r)[��$ҏIƽ�}ZF�����i�ȅ���5+l�v��&�<W�-���S]�5�=���C�zlX�g(��*j��j����	
.��E[%)@c�,�� �CǮRy��HK���o�~��J��=*���r�/,+<h�"��pWX������:.�Sa��7T:g�^6̬�I�
P������ΰ��3��BЌ��Z�8T|Q��x []+��A�ʛ���x���2`�]
��yE�xK��;T�h'�����Uj[
p��!d���m�e���w�O�);԰i��9�\���;�0�
#`�j�c�(�������#�8L�IU��)��X6K���2��)5Oh�XPm�[�YL�I��A�N�0�Dq���J��9�N��H�S+��|�����q|o�[�����[�q9Y��rŇ�,��R��ȯ7�ܴ�,�jÊ)p�i�8]c+Y��`X��AJ�Dԛ/tX:�<�G��\"��\��l��9Б-��Bd���k��V�:�>�/����a�I�JT�����U�)�w��#��ZSkU���K�f����O���(�L$;�'�R�����>��s�zbb��|�*с�W���J�+�?|���o1|;��F���hĦ�!EJ���Z���P�����X4Z��K�����O+?�*+�)��F�И� 
�T�JV�s%Uݓh20B�頂@�۬i�5�4���m�wH����YD��ahco/ n	Ǧ:��MaU�w�[�LmeGF� ��]�҉�`��D��c�}�^&Y�a�N���1���҃#E��.�lCj�ӴLB���n�Dbv/O�e���گ�����jW��c��x����C'�b*�������pk�3~�p�}�(�E�0��9QH��3���u>&$����QnQ�oH��gr���G�g)�ު��i�T�3Ь;����r4a*�RVPx8-�q�(�"�]���!�J���1�*����?�e�F�na� �%'5_(a�v!��L�We��@#�r�~�Z�|�L�0�ȩ�	,�oI�����x���AU�:���s�ml0���R�<��54���j��jep˼��s^�|n������<��1�?�=3�ڨ��4�w���3]`	��؝ڳ��L�\n�,n�=3:m)���jg%?��6�y�ǖ4�hG����o��}1�^
�E �����?&p�Hq�i���#�u��n�?�u.-Vb��
#����d�$)C�����v���v�L��
���rU;O��aͨ/����a+���' �&���ݏ���[g��_O��fW�=�j�̣���&��Ҿ\*�y��{o�f`ya��&#
���6�7��V��vm
��8�\n|�'�R긫,f�LE��5R�Ϯ�hܨ��1&���.s��`���6�����8�w������5hc�b�l�d��%p�"�c85t�F�}u/
�9q�9o!�#��i3r�H�
�_#�[T�p>�:Cg�aE��S;F�0k�$]�yR�M��Ip���.���C��D�~��?a%��x6rWH'�þ����择g_�3I���ѯ�ȍɵ��e�kR
&�w/��X
��Gq�#�F*��S/ ��+
��8-�jU����Ђ긹.%���]W	k��b�,.R�ʪ�:��-jb�R�����B�I�����j0$�7P�qu�6���?�J���U��sp/�Ջ���^z����qzL�-��I�̟x �a,�l��D�N���/�EL���h�\���}=Q�]�
�z@��^C�(�c�I�y�3�yR0}�e�
\���ei$EC��d�y�#�v�k�$NpE���EX�R�D"����)�c�}o�I=W���x������[�-W7�`��-e1�g���q�\��"�"��*��$��(9�� ��#͎"��D��tm���B�+�?�Y��2��;�o�+�m
@�j�{N�z�/�;j�Q�Drfv�!þ��S�qg��"����ⷩ�F23�Es�
'���G�s��
+/��c�I�{]�-TsN�S�x�@&�I&��^�9��a�d���*������nJ{v¨��iiŧ�
���L_���=��p� W
�v��7��%�H|�������u�7�_�|���Ok�����G�-"*�H^sp9#�/zw�u�}�oy�[��6����S[[��b������M��S��
��U�t߀a�e�s5��M\�P�Q2$����=�4j�/p�/���?�]R@��&(\�D�0h��﫵--���P�D.�NƵ�ٳ�6#V��ը�zPB�ƒ:9;uBh7�*
֚ݷ%�}u��P��?�Q3)��C���5��U�S��on����N�7���k�V]��ރL��a��1��6�W`:zD�w�eM�!����Q͙�Q�9f� �W�|�c��A�9�XG��"��^!��ر��TX�U�R�R�k�x��Jpq O�6!��v
�DY��0���g�^F��t�-9��{���P���!����M�.��� S�C��@�g{{��(�s?�4�XU]G5�W�&�G\[����6�5�ѐ�#�0+JW�8^Ǫil,a5ϼ�����G��V E��U�&��E���^�!^��N1^�N��
�b�Ǧ����7��S/���Nv�i��R��ԀZur<��&jn7�	:S�$ے�u�	���9ɳ�u+��^h��9:Ur.���KEcF��O=&,(�ә�VH���A��rSQ��"*�;3w������fk����]1E�ń�{A�\L���W��HU��A����`�NpK�Ӗ�S
�U)�pH��cZYqQ���`����P��Teb:8�|�������5�ڋ�f�њZ�[$�FA����>\Z8jg�C�+�S2n�F=��@�&%L��.�ఄ[GT�B��1�Y�]�E�Wr*|�Y��|�J�+V��B��r�I���;Rh,Ⱥ
|��[-��n�L~��V�gN��]%�X���Lg�M���h�Ƌ��d����H���ރ��v7�����ʝ����F٧�U�Ee�ǔ�?�•A�s���W-փ���uey�X�*��ʦ�j�%�c	�v4�!���R���P1 ]Gi�ݭ��-�^�G��Zf�WC�"A-��W4e����\�_��v=:��UC��T��G_UTB51�Fj�y�ӏ��������ߜп�����T�֝�J��BC���3��$.���cDiWQM�Z)ҠHG�+Xb��9Q/7��z��yQ3�Uh�/��s` �4*�I���2J�!�z7��� .[��K媤��
T8�Ѵ�����)��G�p!g���p���Dp�]/3�s�6�X4t(0 ������̻8RGȽ���~9�~a(�>5�?���4 �-4��lO4"�{	�+e��)����a�Q�5 ���C�J�:R��XI����%�&]x8^�*ŷ>�o�e����2(p˶���*��sn��V/�c�OT�C��wؓ��eeΫ'�<ڢ�
g>��(��B+g
Ք3�%������Ȟ��M[���Li��.�ʱX��H�%6�����>��un
ih�P��F�Qd%_~�P�j��?62 64"�B�@N	�4U;X��u�uw`�W��j�t��S��#X��$~��5��I`�T4�ԟ֩E5�ؿ1S��m��.{�AZ�"q�����6���JL�Y�qG�ʲ|��t��ʤXR��wDO/��z,�I�Ζ.���aK��@S��B�Es�����D므ʤ��
�d���1
m��W�x�w�bP��R]�P��/c1��M�I\�"o� w\(5gY��@yceU���r���������]��\��
M�fT��g����
8\*�����u��U�#��(��@*�?(�a�kcT��ڌh�[h�s�
-#C�.��-���۽o�D6^����xK%�ٵ�;mP�H����ↂ!�`SS~�7\�h��^�
iH��w-J��l�d�(�pج7㯇/9nsM%0/���3�K���FG�)��@TҤ}Z�7jf�bfn�e�K�[�0Ixf역Aj��n	��q��iw`���<V��")�kub�T��`��U�2�w�T[�i��&,wj"�A���Dy�Eb�60X$I�_�)O~4q��7�z��!�BK�3q�X�kX&���ˈYS���ð�q����{1�8^X,aP���Vl%�1r���Z�U;�4(Դ6MTi�	���o����.�'W/"H@8��,�0�<T����`�����L���C��!��5���s���x�m��k�F],�7�p��>Z�ذ}p���pK��[0�9|WR
�u��<R�����)qу��B�W��jG��H��o�`q��M
�7�5�mxN͔ �H�`�����'v��(x,_�<�$�2*�-B���@c�n:�ʍ�^���5ݦr^����5w�Z~Ϭ�8T�U�W�>���je���V��m��mՁd-���|8���@��__�ߝY�q�~���9�l�H�*2N���ʕj��x�'o�V�󤍻�O)�V�.�5�y��4�վ8'��,,�LF��[i���BR����nlwu�����;��bΜ��3��O��9��+>����P��:K*�Y�=9�0W�/�/��Q=�xҺ�jp���R���ACbtz���<z��;�����"K^��j؟��њ®H��e�g^�5��X�@⓷V�E\��GЃV���Q�֣I��÷��^�˜�V�Bǹ��c����j4�*RI���k�4Mbף���yU�M\b#�f�U�R$s���5Ȁ�ԩB�~�N61�e�������*�5k�r�Jz�Vg	w^��m�[�Ul�ヷ�uR��D��pa��3�O!��6�Jﺐ�5-�oY�ͣ�V�G�D��]IM��{��FF���j���ֹ�of�PWItZvs�ň�@N����w��'�!�>�B�E	ki�\������S������g���'MH��E��!bS�y�6-j}qZ�d~F�2O
L\��|.
Vͤ�[a�b�NAҒ�Ą���ȷ�E��s?k+�i�!��JN�,4=�����]�B����n`i�Q�1�A#Αj7/�������w��ֶ��v%|.t�1��؄��
��=�����<[[�T����)=�&ڇ��8¾LI!ckZԲ�W�[q���!��*����.���I?�*���o��pR}١�ݰ�^�)`*���$��h*��¬{��f9}_�J"e�a�.�iZ�EL\nZ��LJ'`�7ө���l��Z�H;\><qx�@��Z�^î%�u-ɨ��>���̷R,NjK}L[j�����c}eǹ�Ad a�;q��
�Pp5.���V�<�̩�L�V?�e�W@S�`#�Y���Q��]��j�"]�9�YQl�o��X�s{�4&��-�kp��I@�J01<�;��w%]�*����:/�g����)�	V63{�tp�rvȮ�
\�W�.EG�"�,�l�ժʑڋ!����D�C���
�БFdV��HG��S�J���h��
iH�mr[���6�w�$�[����x/�yrAp��@�p|��*�셷B'Kf`_<K��-�6"8G��[A7��K=S!��4j�l6Aۇ+����Fh����_��O+臷�9���M�XA�!�5�w$��6�֦fp*b�ߍ�']����x^T��G��l��.��0��,�\��րj:Z�P�Xp�=�Y⍶q��BW]*��I�Ae�y�*Ѱ@E�%^�Ť��oc�9�����m�Tݡ[��`l�-��6r�D*ԸL�m1����Z."��8�~�]��jѩ.���F���j~�u�>&^ȏd"BG4��	�*�9�5D˿�˻��si@c��K��b�$�O��=T��=L&��s�8(W�=y�srͯԋ�8��ֶ((�k= �I�
��خ�[��<�������_w*S�`� ����&`��e�j6���q!
�\�Ⱦ�c]�E�:�G�7?!W+S�M�.$0CK�t�m,�f�ZQ)c�30T�Bc	��>�vʸ�`�>g;-��vq���x�1���k�'
��+��6V���ӭ�aG�j�ve5��QK�Z8(8�d����]4�Bqe���I�m;j�4:b8V퓑�q�1��eQWw;u�(I����[�O��
6�\�k�;[�?��ȁ��V����`�T@t��x��m�x��_�hm��PE���:�o�����] ���>&b�u�51p�v���b+V~�.�&��v�T�(Γ�,�i�����I��O^��O�����A�s��4�F7�,��'Qk�}4�ހ%�fOE]Ƞ���CE~��^D�n����XJZ5hC�kK^�*pM����	�Jy�P�?��wF\�Dl�'��dU�[
T�d@ښ��x��$̉bԦ��u��<MN/P�J���X	��'��a���-:*2�&)�k�z.��wq59`��nX�z�M�H"g�R����FL�n�`A��/���.��j�3��AWY�tp߲f� bNjJEEs<l�5Y�4MV,���G�4Q�.�޲"�n��y^�k���PWď��������og�X�Ç45��m:)�B�G�VO��]�Z
������
�6k5�iH��->T��OȦ���ږ�o��ٕ��%H=%��]�JP�Ɵ��E?��Su�C�p U΄h+���q��|����%h�E���7,�?ҋ༐؃�+���x�J���7���b��=��J7�Q�ț�q���c�Z��%��ҴQ��E�����M�n��Ӽ�TĀL�����c���G����PD�
�6l���pН��VG�RS:�	���#�d۲��\��ls1�ߍ��r�x{wv�L;򳽂�<#p�L�ER�+-Y����t�ek�@W�E��G��R��w����8��:�:v�C�Ⱦ�y-�*�����m�Cag�g�W�Y�mk��F��-gy�>u�8�o�޲[�ݲ���yOd����J0�*�)�����S�~',�&�uS�*�y�l��^Q�*f�o���MD`,\}���X������ӲI��E�t4�q�XN�f5�Q	"��2�J���Ĭ5�\�9
8��-��7��R&U2�s��\��x��Yi�>I�Ҧ���H���&���GI��S��mM[�x��#3S��{Ӹ_m�"��S�42�6YA�-ԇ��_��B�&�NZh�̟�u�u��-�E������C�J�
�«���
*�>�N=�C���g+��a�=ϩ�ܖ�NrwE�[da)�T�ۈ�Wk�3��B}�_������ӥ�i�=nÜ��2��̿#`�#��b������&�{��	e�U�f�dJc���3)�j���`�*���"��uЖV�"�S�w����ePV�s���Q�߳$\;�ҍ��oHC7�#
�������#B	A2�?��"E/B�Ihx⬻9��=�P	��TΊ���EU35�	�Ár$�	W��S���/ �	,S�E�yP?���6�#nsA۲|�3T��o�m�A�c+�J
���)9���䪩��� c��xрͥ�GVS_|��
�z�GQ�<����(�X�<�����J%KT���|N�*ȪV����K4(��b���eeT�l:
h��0�e��l���b�̢G��:aY�l�u��;pcC"
]�̣R�θߛ}�
t��`ca
��	�l��b��%���.g==?���<�ɧd��MP</����Q#(@`��N���s��|~D1,G
2>C�M-bbcd�JRM���4��^��)$
�~\�+�j,�b�-�X6�4q7riL���h��ngT��z$��aT9B|<Uŝwp�x���P"�HU?Fm='�b��+ϰ@׬<�W]7�(ULMG*<}��('��D�^R$��_D%�ITd�g��Q�S;�4�����
Uix4��J�!m}�o���8�Tv�5gNrl��,@)��1�e�[c�;XA�uͻ)��%
i�ZuȸҪM������k�-��"]4XpQ	�Uł���
H��CѠR4@*�0*Q�V��C:�f4i�S�7���o}�S���@��[�<��~����j���9��ST��Q�}�R��"{i9N@o`.bT��(���ep��{+Z���
Fs=�gQ���B֐�ݱ�Ư��+��CP��U%:��b�r�A
'�ݏD��J��[W��&DUd@��m8�ވ�^}R&���h㍮�U\1�Vn���L0����'��K��oR�-ԯ�[�uQ���9DS���msPj7��с��Tup�
�����܈^ح��#��h`�i	���Ad�4xQ�](�ytΊ�V�y+ѥ\��v�h�J�.�cJ��]z;n�vi�k@�v� ��|r�>T?7P/F�Y�ދ&�U�/ X��GoQ/8�04Q5�����4i5�5`���(�f�WU��������m��aF�C�T��Z�u�PWbY����3��7&�V6:W��:k�U��*����o�攫u���-���{�2B֔"T��6��T�A[5�M�Q.�\�r+A���A,�Z�,]�hZ2T�_U�J��mck�LИ�Q>�ӌ�f	�.�j��J$�K+\$���Qi��J%&4r�E���h,:�}����`5�U)�AH�CS��3%��:k���{D�c<���bB�7iz&iM�NhzR	w�:a/JjMQ]�m��ebc�X���;t�������@r���8�X����~C)!i�(������C���Fg�UK9(J�t91g����˩U���2�����a7�鬣�l2_��a1�
�3����/q#�*��J���N�)R��<�kh��A�F�
 Oq�R���k��R��m�c��NZڷ��|;k4o��FV�/�(�?�F��.�Qf!��"�+�L����U���lXʱ��
1�ϥ��VG~��:U�4
���4\�Pu��Sa�=��9V�+�����d�e�M���Փ��j@5y�M�x%�'��)�uZ�:�gy[E�,L��&�%�p�r��DK�(�%%	?|�Q�E��U���Ć���R����
�ix�I���*&M�+^�,���^`�/vr�q/�p,��M�{�_�	��0ō�NBP�����v�CюOD�]���nG�J)p�K~�d!�	����>@��Y����]����^��Ҧ���������#4���K��j�s�y����N��0$b��G/1"�a���&3��5�7�>8)DM��
J���~Q+��o��E\ӡX��	�`�=��vj=��:���䫅��"|�=5�7��T�~4,�F%)�/Hx�w�G��]�ˤ�CRW�t�!��D��qr/��}W��y��I%l�@T�������v����	�������^@�p��EƂB.�A�*�p��~zwYE~�
50�S��#K�ð��6�x��n�I�ꄯj�>��`��p\y bx��	���M3�肊 ���m�|�j?��T���j^꧿��eb1�q҅R+8�8�h>�/��Rc��P8��Ȁ.�[\^�k	��/K�5Ƥsܺ�&,��C���Қ�jX�<�V�4o��w_�F����B�4x����(pH���B
˴�������?����������М�"�(�y�Ve8|�!:�C���yE#LR����$�d\������<�(��:�:�����ɑ	zRѿ(8��CX���Z��(�^YP2�TݵbUAp�.�L=0��0�,�c��<�Вյ'��֡�&�G��$
)�-y��AG�7%�$��܈�a�J@�P_V�YҮj�4g-�b��CNjysۓ��X��,T�t/"�g4�֙�k�fF��[��:���ܕ���\�m?��2ŷ�v��w�$���vW�JO�r�K|�i���Xr��Y��0ZD�r�)s�@0!��3�Z�jd���#�)���ը3�vI�1�xt䇉���
��g�����Y�N�tP=�`A���FN~j�
A7�A�6�SK���%
��!�\Zlgn�o%G�J���S*k�pٳTa�f;��47����R
T�����
�(�X���L��2�4M5�?�`�P���P�(�ۆe/g:�J�n�ʵ�;�w�hl1�%�!d<�d˃Ҷ3;{ѯ)ڼ��bJH���yN�3�����c����0*)yF\�-�B�[AȲiU���R�~��A�qA���]6�t��C�IL��	�}/�Z�e�K���Ȗ�%�zh	-?�E�rC}*�}lz�35i~��ꄁ"��N�B��BF	���/T�t����2����W�L��#Z���"ᇒ���9�U�a�p���gNU����������
��V�$���0��
%�S#���+��(qk�_7��E(g)J��N�Ћ�c�j�$g�G�IӅqn�E�E�\U-�;9�L�0u��Iދ��h��C��!�=��xR]�@�p
��k5��SN�%�N��4֪�G�cP�}��~�x��z}���T�b��<��8��4y��g�nop�b��o��H�쮔��3s�4�|�Z��pJ�j	'!�S����e=1u[4#�ٯOo.�_�'��J�F�h���xZ�%+�!��y=2ϺսO�=�\T�X�k�J�IY1�m(XJ����Db���m������8�����`'�~��&���`Ma1jwdLB�>r�C@F�btZ]%��)��PF�z���Z#�џe���(V�7�讍Q4����L� n~�h�K������-fk���N��[�{F��V�^���Vjm滖Q��u�iN-�J�#9�^ή�*�q�؃�l�V�)k�4�����iD�Iϊ��:�Rr�Vb�NΜCÖ��(̗�XN����A=�x�ѻ�"I��%�����ܚ	b��w�&�	���6��1[/�
��ƨ�z��UW=��6�WC�?>	�س
NHw�P���p�uʱ��샆��,� Q\�n(+�#cq�G�f�����x��U�_�d���5�hb�-
ܩ���i Gi�_a�Z�H��m��%ՈV�	s��Ms��ia
��,i�b�hCM�f%���~{_�HZ�9*J��xƎ���d�)������P
�8�̜.���JHӵhZ���?��N�rS6�!�d��
}YEe��/�O^�l�T=� c1���!ZI���6h��-U*(v��N!�`�Wf?��@��^�B�bP�P9�7�j�Q#@q(X��=1v��hr���������T��ms0%k�!
:�o^��26�FHp��N��WP�'�k�y
�j�5ˊ$4	���l��
��uM
�J�����$a�:8><\�(��F�q}8�@��.�!��(<+�	E�8�L8W��A��׷�M�������:�?��O1	Mr�M�}����(��6QM�c.:1heG���)i!���Hz\���e��"꺙j���񵲱L
&��a�j�U�c��s�`j�Q%pn-p�
�������%�xu6���\�O�~ ���
R]ԑ;��~`s⭠�1��Z�B2�{%�()�B�V���Ğu�-�a�4����w�Z�br�3g���"wM���W0��L�T�(M�ZFw���"iH��Xlk�
ir�/��K7��޶���O���ql���9��a4K��:�PhC����<�vw҆D�e]��b�7T�0���}|�@�
�X��A�HB;�KϕpL�}�=���ɳe��{�⫫$≪�%<�I��Y�'�I�i�*"���羈v�N�K��l�p[�8������C������Z�%A-ޛ���Nؽ�h�<$�����}��*�P���aL�q�����P��j�f5�yKecb��ŀ�+�}�o4کx�8���$j��"\1"s�_t�Tl'-Ni��X�X��2�]/Y����.�,���\��gC�r�:b	]�!(u6	����_b>���[$K�Y?�T!��W�2u���H����19t_�݈��j����'DT7�2���|gv)J�0�=��f�q��-W-�n�>Kq�(�N��;�h�o���;�Q$V�8�S-��E*pY���B;���7I� F�#;�B}I�r*X̍Y�>�s-������IC��k��4P/[��c�>dqh^����V�Ol�uH��k�'~���h�c#�lJ
������+>��(��_eT8_�,0[/�om�Z�����
�|�Z�M��h�h3[Dǚ���d�4{�x�h[V��$��{����"������6x\G�2NL��%�;l�B�0L�WԎzbKڕP�Jꍲ���V:aK�Y‡,v��{� B8�y��`�&-��Y7oD�9!�eA�h�	��`�l���{�Iv�:���ݨ͹�IN×��@�/A�����Y�{ �"&x��ͧ�~H�4���<�#
+���ф��6P'�gXN����k9y�W�z@_�,Z�ys`=o|��P��5�������G�Մ/Q��n�T�Ӂ��6�m|��[r���J~>����bNO�b���n���-�,}\�gJ8�˗X-�^c�F<a�][��8�sh�c�ƕl�%����q?F;u�c��9�@�`a�:�x��E��w�����u�F���>/�NʯN���	�&��P����f�TMņ3:{{sQ3�|ӷ��Xe/���W�s����籠�<���v�'.Z/}U����Zx���ҩb�~k��T��
���ƃ��a�7�%ֶnBbK�!Hb���8�K���~hw�3Ƴ�n�-�-Rw�ͻLa���؅��@ԍ��jeav��k��P�&e�>����q�}o
���r	@�=b6��b��[�Dw��!��7"O,�g�\ăj灯��
�^`{�zO�<�@�y�*-%�xS�ZG
�LM,��2m�<�4����>@�bW�`�sk���N����Q�l�-�=�����n��m͏�:�ìA;�s<����Sdw%F'�'Ņ��싊�/P��F&�f�;�c�=]]�+0�6l/��;?N��G��c�Y�Tk�Y�÷A�e�k�~�\����^�̫)�X��m%K0��2�5a*w*:�T�<&�v�KX�Y��P��l梐��
���.P�\�TK�Q�xy�I{�k1%1 �����yi�+�};��>��r���#1�=�N���W�t��3�J�Yt8���R<.5����I^�@�MS�ů�D����̲�z��W�v�r�����2N�s3dv����`�"�%��Ĭ��KJdy]3�r�s+l�#�Ն����f��ǔ�\�5����r���|칔
���CM�D���]�8�̯�<f��hv"Q�D{����[
��K0�ʇbk>~u
��B좡p�e�x��76�f�qq���n��aZ�zcq��!�c�U��:��a?�����/��9|��9��
�M�������$�P�9��_}��x���/(%��*B;��
,l!��)�6j6©����Οk"�#c:��d>]3#ކ߿���n����@����d����	5�$_�B`��Cvʗӌ��=���-$F)(5�X��6���b��G�6���	�I�u����[%��r��s��l�D��k_�_߲����s(��J	{���)�R�#����5�{}&7j�^�	�H���0�p��
N�0.HE����[άn0�p?����-��N��Q;7�}G��|k�.�Z+�Ý�SC�ݾ�M?F��7��7�f
��%I0~퍡�����!~Ի��m)�X���b��
?!����䗷:�w�����x���g����@
+ќ蒗@~�9���-z
����}c�=���JK����~��C�G��A.���:��<7�wO�N�_�ŕ��U�����{��[I�l\� �ژNW��.��C
��"(�~J��^?B�5��O����l��S��Wi4�"�7}�������pX�������O}����[;N��(�O���37~�۸�T�p�*@
Jv��A�Ɉ��E�E��t�(�)�3:GV�[�d81,�Ĺە:Y�N��Uc�̟�<����"�IZ�}����w�V~����P;A㚹i�N�ڣ�����*0�n�a���y3d�&����]��s�����
ƕ��hu�)�V	=퍰�a�E;1-پ�Йm*}w{��|m`n���l��'�ꅗPr5a(B��S���E��H���9p��?Z����Ḯ:`�
G$��b�w�m����GM��B�N�K�O�
�3y���[$�m�h�a��3�d��jS��[�`]5in�+@��	�CɗU�M�
�ᷣC�����K���e�y�΂8��Q�H���$w�y�mI����0�]�5�@p�|�x[\�e;���f�sه��[@/�晣qynju^�����<Q�O�!1���	<O�>T�LZ�� ��R�u�Ƃ����v�$7���N.Q�|T�S|R	l��\�W�o���k�^��L7
�'Jw�~�p�l�2j����]z�߷��5c�FYU#@�����FN��C�w�g�X��w[�j
��4���F�Q�@���S�T2n���ivb��׹�0�МE�J�E�Q�e�.��X͏ ,"'Y�t򱒼P��I�-�������#T11�f7��$T�^$K�]w�927��������� ��L(���:D\�vs:>%̍of{���-�n��_�5�
u��S��n�Ȥ��\Gn�'�@$W������
����T�p��3=h]Ak`	������Aӡ�l���z���l�Ǝ��"y����T�:Q�yu�yw�@ܕ��O��~���wf��
VK��sB���>gsMR=YH��eo[������t
���K��ߥ�lX�Aa�7��}�IC$
�1l��I�la�92�7��.I�cT[�^��}]�/{Nw�>��Y��H�N�m��h�CV��%"Ȫ�ǜ�(���!Ha��L0%�PT�D5 CP�:Zͣ�i�nw���P��R�Ҙh�P�;�&�}�
�z/w�4k]�� j��`�;��Ld�'A����8C{'�T%QO��w����ٮ�Ѵ\{�3d4j`xV��P������MK�9H�N87N�N�ص�_"
��x�7�[�h�%O�*VvʻVK	���	�ׄb�q:��>�X~��b�q<�j�D�wQK�Mp�x�ܼ2^��\H��w�5X�9���Z�l~0+Rd��Y;�y@+��sv5+��p^�spEOy:�/�~��&�^�<c�s���6��I��"v�m�Ƕ>aДZ�?a�f��	p�Y�?�~��H^�M�"�1��Q�m0�Y��צ�z��x��E��(���O��o�.��I�^�uT ,'�v���OL����z
l�!
λv�mn�h�J������€��7�1�As�Q��Z:X�.-����8X��5�h�2!Q���8}Nr��Ȏ�d�Cߘ^> �ὓ�0��.)�4;,�=C��AB��c|��:V^���>������<����oAHm��+�����w}%o��֩��F2
$<J�q�Sy?�./����'<j1#�wE#Z��{A1-'�LPX�-(�h���
��b���/$� NE'.=�
���P������t�&���o���]�|�˜c&�Dܬ��,ʙ��d�oް��olS��_��+�C~z5#��P?�y�1iA.��B�H8QK�g�?�
4w�,Ş�o�~Roɢ���1��!�?_����ڧ�6޾i��{�Z��bU��l3*m��pҷ6��t��쩂�S_�����*,Ȳ2^����K_�_ޒ5	��4`^]��)ast4�f��S�h�$�1h�L-�A�o��
<�#�ֶ��0곾���$������3�H��fZm��pw(ᄖֵ��j�<>Z*
��y���w��OrӴ +L���tAؐ�@�����6�=Un��
$W��:��q�v�����u�oR�,�Eа��1r⅐�6$
�8��+�v��"(��4`�0�*�ꬆ~���b'@r�Q�-�M�64�_%�?G���x]�{���oǦ%��2���r��fU���w	]��1 T������@�dMul2�ˆ��@wڇ����wO��b��;�DSm��<�YAZ#D�牰X^��j��I�
?�8Bn���7��s0$Xy$j�*���G���Dׂ�Yt-���F�H��~_���HS�I��]QWUH���x��DI�.���W�wg�k��ȭ?���g��9FeR�������@��P�(�0KS�����@��*D'10?�Fj��n���4D�2�:h�$����
ͬB��=�7C �]����h�6?��92b�W„0�lr�,�7�u:E��tTl�m��8a��ד;3��� %�h�ۦ+4��
zd�N�ij�#q�~��o�HM�T^avrrЍ���.e:cg��P�F�w�j8#(�R���1��W	�]@A����(��-#�Q���X[$z/S���EB=t�J$�SU�A̵���Y!���쌃��(���Ns! #N��|�0�bz+t#��1e��c��y������6��٠�SJ�5fYj��=��'B'
�
:��@�Z���^��
FK��
��o�I�0l[Eʄb�㼤��F�¤����;��\�4��0�7YI�Q���pъ�hE�>^R�;��B=�,�Y�l���^��.��g�Wg���\��/H�An�~��P�T��h�V@��[z"SZo�.�X/Qwz�Y�/���g`�O��;���8!��<)�W��}fF�•PT����R!������u�x�|���(A�P�J]
	��x}�����{�VP�n�Y�����pxjS��LkD���oq!���@�@���%��K[3�49sQ2�:Wci�,5�@}`.�`Zl�&�SwБ��^�z猪_��v�;�l
���1�t�1���*B����]�^�5��(�١���WiOq�ؕ&��
e�
�9��M�J��CM2@��e��$_+v�=�`x��q�%��˩@f���i�p���F��h?�D�!�iN	�PW�L�zX_���%��
�n���e���N��2
[�O[p�^�k)�!�&&	Τ���Ñ��3hʹ���ގ�C�"2��|̉G���wM�
;����۱�…<�qK��1�n�l���3����L�+�Q>�@�:�Ԩ�S%����������
V��Ĝ ۽vY�bb��Q׭��������I|+�ܟ��:�m�PvirW/��M(��v�:��(w<wJ*p���Z���0�u���1/��.�$�Xsp����1ڛрaڡ����q,N,1i�,F�I���e��8<���<*:j��m�` et^DkkX�!|ȳ�V[k��U�&�!'�>����GÜ��;|`zƋ0�x��4��%;����_E��7�<�I��އu6��NjW0���e�҉G�����.�ֈH 3�W0��ώ�\C�.�W$��W`�o|#�c�v��L��pʳ�;5��ܪ�q�!�N�2fe�X9$�6���b�4(����0���A�ڃ`JF�
gYq ҳ�4?��������:?�#���o�|�G͇�
�c6�'����}2��?�:d&Oā'6�a�I��1섂�L��D�^��^�(��b�_4��֌O$�V��C��e
��su 0���h��Ȅ9$9l�}І�8�A��vކ�b'�	ș��ok_Au���lMp�G찳h�W�6(ֈ��a@k��Iֈ�8�k�t��P�F�N׌�|&Y�`�}�Y�5H��0T0�pv1i���-�MB
�`6L���x�a6����o�ISX0�mW������<&[f����*��"�Y�J�"�f/.j��a����F�Sb���'��I�4��e
�A�4�F�c�6�d�l�u	��@n���Q=oIHۭ��D5��Ө��'F�O�H����@w��+�w*��3�>p
7�;��ud	�b�P?X;�m�A��ۊ��`f��DGF�b�Z�Q�4뚊�G�R���]�g�v9���1����׋�0�04�=
�S�4�Ⱥ��}��&W\vF\��$�>	����sCV���mE6�����z��L��,�h��m�0IH4f�5�B;��zVԪ>�\�XC��x�	H/X��n����Ki�����^¯�[�'%�3�1Z�Ln�wI_��Pm)���Q?'H�\;gپj�o`'wބ\\��`F��D�O���0/���9�ꬪ6�]E�l��2�A�4lL�-sɗdT���C�6�*�y���?���^$���XS�x���� o�ǔȶ�)N4�R�:��l㩾���>�즱�V?З�Ɠ~s1ϣ�Q_)I
���g�ĩ.ƫa�'���A�"�NA�X�D���H��6�f�����8J�<�h�|��R�d�-I��h�x=�����H�N�X3�*T�#믣]5����z�q	?�)�K����b��]��Ҽ���k}��F��#�/�_Sd(��M����Y�3�-����'"�g��h�j�|��'��H5�!���n@\
$m��8�Q>/�2]n”�k.��9P��"r�-L���)�J��q˯"�׫�{f�@���h�?�<���	��د,��DDQ\OE7�^[���[:�CҭH���k�eD���<3��՜�ǩ��A4�;=�{�Z�қo�(E2��]QF-)Vt��V�/�X�n���+��<0�y�9�?(��۳t���6�o?WX$ݘ���d�<���c�I.l[7QM~� ���~MgU'���7u�a�pW$u]���B��������䝱�c
�(�`��~�Y�q3:m��0�e�N��z
�dP`�c�q4�N�!R��W}���%z$�ӈo��}�O��qK�KY���F���F�?lbe;�f�H�B4�f�멐U����?DC䚢i��/���
e{��(�2bZ�Ul\9��/�L��Ve�|-�?5�[��̀��؊Q�3p!�M�s
51�ľ��g]�uś�Y���Ă}�Zc�T6R{V�S��m��Mxe�Wk�w�ЅoL�
���F��)LƖ+9	�w���T`��(�̩�hV�}IQ��ܭ������RS����0[~����{�pQˋ��i�~��6���ňU�����ZhcP�v�yŶ��]����"G9��}M�[�\fT�w�fW桠�MJ�a[Z�Ȗ�8Ќ�qs�@y�ޭ8��A�������a�R���ڰS���'Ey�{��h��^��ݠ8��"Xm�EQ�E�6�����W��80�V9'�)�sS���<�Z�آ�W����~y�L��`�<��� ,^}s�0Mn������kƌpĉl,��4�@�:V)l�w�Ц4w�U����1S^�¢�+���t�
�)�/t��V2k(V�E�8�K�}-ܪ�Ŝzf� � �x��Mo�z]�ަi�q�}E��X�t��勞ऀY
�|x	��HFt��e��Oa��9Гd������:an��AS� ���t�FyRLMY�L���۬,�}:�^�-��h�7�A���=٥��mɶ��4�_��D�.8�l{8k.�}��/Y���y�	��(�i���i��T��/��䤑�2��{7��(�ᢔ�:ip��H���Jp:�� ��w%�eD9ՋZH�Q����k��N�#{�v%Ҕ+��0yBД6�t�`o�b%�`��:�H��*W�7t����jz^(R/X69Y7f�}Φ��<��R��GFx��S��!׆��k]���M�!�,B�ꀋ��VZ|�+jv+�k\������vH`�H�:�u��ش��۸P�w����6��<�5�7����[�0��Z�
�q^d`aU�g���`�07�ε�
���C��8�И���+��/#ޗκ�D��,�T`0��ҽ�7��p�+'�c�4�=X�8�8�a9\�N��3���|k9_�&�.�����ް�#��u�<�w:���YzcRku���w�+�XNd��M[[9�U;0R��G0�BA�QR�|��<mչ���4��2̢\�H8�3����*����b6���i{h`_�mhV'�A�h���ן��ϖ0ӏ��.�*����S��6Cx*A�\�t��&�>�{)*R��A�vo(H�FĞ!?˗|
�e,�ɧ�:�ğ��4��GU�Ӛ�w��2��(�k���B*�K��U^I���G�A�Q��%�¦��~�#��>K�j���Y+�F�Hӛib�ho�>h��:U|X��S[�xre�;x��С'�|���l�%�E���YB��g�;��6�����<��B�5�kG���$���0`O��_�T�hx�CSʷ����H7��gڨ��)�2�Z9�����xd�J�����<�	#@|��N��$1�M�b*���.KE3@�9r/3����0�d,�'%GV����T�'(�̛�5:*Ba��A��Dz��,5��?��EM7žI�S�{���l���
���
�J�ST�� S�y��p��ok<o��V��{�6]��]/4]��?u[�k
F��֟[|�_DV�ʰe1`�Қd� �/ֳ?$
���-F��~}�Ti&K�+/`��_V��c�؝��G�z�d4�^��-7Vo�xM�(�y
?~���e�橾s�T��<����1��0DqѪ�v�Z"���H����U׮oa�VY/�8e߱l���݀E��F��m�!�\Q|�̓+oF��D$.4Ȁ$�^"�^;B�6�ɧ��.s>��i%2�}T�#W�(#x
�ߖ�(��*k����G�J��7e�|�����e[z��tr�[� a���A��M=4�GҘ]l����ܓ���"��53��f����g>��O^��R�&�T�C�0�af�G��`�oF~�׬'���b��8d����VV�����;��Y�͉���~T.���ۑx���!��S�⪋V!5J��PK�DGG��@:��гk}�P�����WA5�<�*�*�T?���x��Gňd�(�C�9aӖ��t� �Y�m�i��X�?�F'�s5b:�j�L��线;�������������̽AL�t'V
p��ǧ��O��~>��:�/�dn3ΐa�h<d��
�Y��	J������Gh�m���dm ������UQ��v��GC�(pF�β=�VtCǤ�}�nke��XmZЖ65��%"�-�j �+5k@T�t&\���B}�����PPˢ�
�a�}�ƀ<�8�^�>��=��/4n�����	�J��k\���d*·��j؆����ra�e��vB�]v���yT��A��?v���FD����ɳ[���g��Op%;���l7zbP
Is��`G����$��B��J\.CP�
:� P���j�/��\��1��^(���	� ��6�ȋ	�6ȑ�h��y�y9������ȷ6�w��&@��A���|?�
���j�լ;��0�m41؎^yvH.�׉���7���Ŵ4.o[������+�t���KJL]���� ��4K��H���.�1n`��i���������E�$�a�ܵu�����<t@�ٖ�7Y+X͠#���`�5���lW,$�62��-mE�4loorV��"[�MB0���!��}}vV��8�y>�R�k�>!�U[m��l�3�)��6~��;y{��l��%ht����'F�߆���&!	<�V�E8R��e�U��j����Qv���0O0���
|���)�U�hD�\�F?���y*��Ln�9R��{r��Zu��5d�>l|,���ٮ�H�ў�݀��7w��F��M�s�I0��ɇ��Og��7C�z+��u�!
oh�>>Ѻ�#P�A8D8���;O�
<�1�g覛�9�ΡDzߖ迺q�a=P=�a��	�=(䬱�.H���:�M�=|�e-�O�P����ø-�E�et�����H��1V�F�`��5g1��"/1��8���R��Ǭ��fS�`�CY�	EwhXP���2փ�x5�6�\P8��bB����<K������D����v=��N~�x䐯�`���ǘ�&����(�cQJ�y,J�(rap��H��'S�qaI�4M94�����wj�PK
%�\[!����html/searchindex.jsnu�[���Search.setIndex({docnames:["about","bugs","c-api/abstract","c-api/allocation","c-api/arg","c-api/bool","c-api/buffer","c-api/bytearray","c-api/capsule","c-api/cell","c-api/class","c-api/cobject","c-api/code","c-api/codec","c-api/complex","c-api/concrete","c-api/conversion","c-api/datetime","c-api/descriptor","c-api/dict","c-api/exceptions","c-api/file","c-api/float","c-api/function","c-api/gcsupport","c-api/gen","c-api/import","c-api/index","c-api/init","c-api/int","c-api/intro","c-api/iter","c-api/iterator","c-api/list","c-api/long","c-api/mapping","c-api/marshal","c-api/memory","c-api/method","c-api/module","c-api/none","c-api/number","c-api/objbuffer","c-api/object","c-api/objimpl","c-api/refcounting","c-api/reflection","c-api/sequence","c-api/set","c-api/slice","c-api/string","c-api/structures","c-api/sys","c-api/tuple","c-api/type","c-api/typeobj","c-api/unicode","c-api/utilities","c-api/veryhigh","c-api/weakref","contents","copyright","distributing/index","distutils/apiref","distutils/builtdist","distutils/commandref","distutils/configfile","distutils/examples","distutils/extending","distutils/index","distutils/introduction","distutils/packageindex","distutils/setupscript","distutils/sourcedist","distutils/uploading","extending/building","extending/embedding","extending/extending","extending/index","extending/newtypes","extending/windows","faq/design","faq/extending","faq/general","faq/gui","faq/index","faq/installed","faq/library","faq/programming","faq/windows","glossary","howto/argparse","howto/cporting","howto/curses","howto/descriptor","howto/doanddont","howto/functional","howto/index","howto/logging","howto/logging-cookbook","howto/pyporting","howto/regex","howto/sockets","howto/sorting","howto/unicode","howto/urllib2","howto/webservers","install/index","installing/index","library/2to3","library/__builtin__","library/__future__","library/__main__","library/_winreg","library/abc","library/aepack","library/aetools","library/aetypes","library/aifc","library/al","library/allos","library/anydbm","library/archiving","library/argparse","library/array","library/ast","library/asynchat","library/asyncore","library/atexit","library/audioop","library/autogil","library/base64","library/basehttpserver","library/bastion","library/bdb","library/binascii","library/binhex","library/bisect","library/bsddb","library/bz2","library/calendar","library/carbon","library/cd","library/cgi","library/cgihttpserver","library/cgitb","library/chunk","library/cmath","library/cmd","library/code","library/codecs","library/codeop","library/collections","library/colorpicker","library/colorsys","library/commands","library/compileall","library/compiler","library/configparser","library/constants","library/contextlib","library/cookie","library/cookielib","library/copy","library/copy_reg","library/crypt","library/crypto","library/csv","library/ctypes","library/curses","library/curses.ascii","library/curses.panel","library/custominterp","library/datatypes","library/datetime","library/dbhash","library/dbm","library/debug","library/decimal","library/development","library/difflib","library/dircache","library/dis","library/distribution","library/distutils","library/dl","library/doctest","library/docxmlrpcserver","library/dumbdbm","library/dummy_thread","library/dummy_threading","library/easydialogs","library/email","library/email-examples","library/email.charset","library/email.encoders","library/email.errors","library/email.generator","library/email.header","library/email.iterators","library/email.message","library/email.mime","library/email.parser","library/email.utils","library/ensurepip","library/errno","library/exceptions","library/fcntl","library/filecmp","library/fileformats","library/fileinput","library/filesys","library/fl","library/fm","library/fnmatch","library/formatter","library/fpectl","library/fpformat","library/fractions","library/framework","library/frameworks","library/ftplib","library/functions","library/functools","library/future_builtins","library/gc","library/gdbm","library/gensuitemodule","library/getopt","library/getpass","library/gettext","library/gl","library/glob","library/grp","library/gzip","library/hashlib","library/heapq","library/hmac","library/hotshot","library/htmllib","library/htmlparser","library/httplib","library/i18n","library/ic","library/idle","library/imageop","library/imaplib","library/imgfile","library/imghdr","library/imp","library/importlib","library/imputil","library/index","library/inspect","library/internet","library/intro","library/io","library/ipc","library/itertools","library/jpeg","library/json","library/keyword","library/language","library/linecache","library/locale","library/logging","library/logging.config","library/logging.handlers","library/mac","library/macos","library/macosa","library/macostools","library/macpath","library/mailbox","library/mailcap","library/markup","library/marshal","library/math","library/md5","library/mhlib","library/mimetools","library/mimetypes","library/mimewriter","library/mimify","library/miniaeframe","library/misc","library/mm","library/mmap","library/modulefinder","library/modules","library/msilib","library/msvcrt","library/multifile","library/multiprocessing","library/mutex","library/netdata","library/netrc","library/new","library/nis","library/nntplib","library/numbers","library/numeric","library/operator","library/optparse","library/os","library/os.path","library/ossaudiodev","library/othergui","library/parser","library/pdb","library/persistence","library/pickle","library/pickletools","library/pipes","library/pkgutil","library/platform","library/plistlib","library/popen2","library/poplib","library/posix","library/posixfile","library/pprint","library/profile","library/pty","library/pwd","library/py_compile","library/pyclbr","library/pydoc","library/pyexpat","library/python","library/queue","library/quopri","library/random","library/re","library/readline","library/repr","library/resource","library/restricted","library/rexec","library/rfc822","library/rlcompleter","library/robotparser","library/runpy","library/sched","library/scrolledtext","library/select","library/sets","library/sgi","library/sgmllib","library/sha","library/shelve","library/shlex","library/shutil","library/signal","library/simplehttpserver","library/simplexmlrpcserver","library/site","library/smtpd","library/smtplib","library/sndhdr","library/socket","library/socketserver","library/someos","library/spwd","library/sqlite3","library/ssl","library/stat","library/statvfs","library/stdtypes","library/string","library/stringio","library/stringprep","library/strings","library/struct","library/subprocess","library/sun","library/sunau","library/sunaudio","library/symbol","library/symtable","library/sys","library/sysconfig","library/syslog","library/tabnanny","library/tarfile","library/telnetlib","library/tempfile","library/termios","library/test","library/textwrap","library/thread","library/threading","library/time","library/timeit","library/tix","library/tk","library/tkinter","library/token","library/tokenize","library/trace","library/traceback","library/ttk","library/tty","library/turtle","library/types","library/undoc","library/unicodedata","library/unittest","library/unix","library/urllib","library/urllib2","library/urlparse","library/user","library/userdict","library/uu","library/uuid","library/warnings","library/wave","library/weakref","library/webbrowser","library/whichdb","library/windows","library/winsound","library/wsgiref","library/xdrlib","library/xml","library/xml.dom","library/xml.dom.minidom","library/xml.dom.pulldom","library/xml.etree.elementtree","library/xml.sax","library/xml.sax.handler","library/xml.sax.reader","library/xml.sax.utils","library/xmlrpclib","library/zipfile","library/zipimport","library/zlib","license","reference/compound_stmts","reference/datamodel","reference/executionmodel","reference/expressions","reference/grammar","reference/index","reference/introduction","reference/lexical_analysis","reference/simple_stmts","reference/toplevel_components","tutorial/appendix","tutorial/appetite","tutorial/classes","tutorial/controlflow","tutorial/datastructures","tutorial/errors","tutorial/floatingpoint","tutorial/index","tutorial/inputoutput","tutorial/interactive","tutorial/interpreter","tutorial/introduction","tutorial/modules","tutorial/stdlib","tutorial/stdlib2","tutorial/whatnow","using/cmdline","using/index","using/mac","using/unix","using/windows","whatsnew/2.0","whatsnew/2.1","whatsnew/2.2","whatsnew/2.3","whatsnew/2.4","whatsnew/2.5","whatsnew/2.6","whatsnew/2.7","whatsnew/index"],envversion:53,filenames:["about.rst","bugs.rst","c-api/abstract.rst","c-api/allocation.rst","c-api/arg.rst","c-api/bool.rst","c-api/buffer.rst","c-api/bytearray.rst","c-api/capsule.rst","c-api/cell.rst","c-api/class.rst","c-api/cobject.rst","c-api/code.rst","c-api/codec.rst","c-api/complex.rst","c-api/concrete.rst","c-api/conversion.rst","c-api/datetime.rst","c-api/descriptor.rst","c-api/dict.rst","c-api/exceptions.rst","c-api/file.rst","c-api/float.rst","c-api/function.rst","c-api/gcsupport.rst","c-api/gen.rst","c-api/import.rst","c-api/index.rst","c-api/init.rst","c-api/int.rst","c-api/intro.rst","c-api/iter.rst","c-api/iterator.rst","c-api/list.rst","c-api/long.rst","c-api/mapping.rst","c-api/marshal.rst","c-api/memory.rst","c-api/method.rst","c-api/module.rst","c-api/none.rst","c-api/number.rst","c-api/objbuffer.rst","c-api/object.rst","c-api/objimpl.rst","c-api/refcounting.rst","c-api/reflection.rst","c-api/sequence.rst","c-api/set.rst","c-api/slice.rst","c-api/string.rst","c-api/structures.rst","c-api/sys.rst","c-api/tuple.rst","c-api/type.rst","c-api/typeobj.rst","c-api/unicode.rst","c-api/utilities.rst","c-api/veryhigh.rst","c-api/weakref.rst","contents.rst","copyright.rst","distributing/index.rst","distutils/apiref.rst","distutils/builtdist.rst","distutils/commandref.rst","distutils/configfile.rst","distutils/examples.rst","distutils/extending.rst","distutils/index.rst","distutils/introduction.rst","distutils/packageindex.rst","distutils/setupscript.rst","distutils/sourcedist.rst","distutils/uploading.rst","extending/building.rst","extending/embedding.rst","extending/extending.rst","extending/index.rst","extending/newtypes.rst","extending/windows.rst","faq/design.rst","faq/extending.rst","faq/general.rst","faq/gui.rst","faq/index.rst","faq/installed.rst","faq/library.rst","faq/programming.rst","faq/windows.rst","glossary.rst","howto/argparse.rst","howto/cporting.rst","howto/curses.rst","howto/descriptor.rst","howto/doanddont.rst","howto/functional.rst","howto/index.rst","howto/logging.rst","howto/logging-cookbook.rst","howto/pyporting.rst","howto/regex.rst","howto/sockets.rst","howto/sorting.rst","howto/unicode.rst","howto/urllib2.rst","howto/webservers.rst","install/index.rst","installing/index.rst","library/2to3.rst","library/__builtin__.rst","library/__future__.rst","library/__main__.rst","library/_winreg.rst","library/abc.rst","library/aepack.rst","library/aetools.rst","library/aetypes.rst","library/aifc.rst","library/al.rst","library/allos.rst","library/anydbm.rst","library/archiving.rst","library/argparse.rst","library/array.rst","library/ast.rst","library/asynchat.rst","library/asyncore.rst","library/atexit.rst","library/audioop.rst","library/autogil.rst","library/base64.rst","library/basehttpserver.rst","library/bastion.rst","library/bdb.rst","library/binascii.rst","library/binhex.rst","library/bisect.rst","library/bsddb.rst","library/bz2.rst","library/calendar.rst","library/carbon.rst","library/cd.rst","library/cgi.rst","library/cgihttpserver.rst","library/cgitb.rst","library/chunk.rst","library/cmath.rst","library/cmd.rst","library/code.rst","library/codecs.rst","library/codeop.rst","library/collections.rst","library/colorpicker.rst","library/colorsys.rst","library/commands.rst","library/compileall.rst","library/compiler.rst","library/configparser.rst","library/constants.rst","library/contextlib.rst","library/cookie.rst","library/cookielib.rst","library/copy.rst","library/copy_reg.rst","library/crypt.rst","library/crypto.rst","library/csv.rst","library/ctypes.rst","library/curses.rst","library/curses.ascii.rst","library/curses.panel.rst","library/custominterp.rst","library/datatypes.rst","library/datetime.rst","library/dbhash.rst","library/dbm.rst","library/debug.rst","library/decimal.rst","library/development.rst","library/difflib.rst","library/dircache.rst","library/dis.rst","library/distribution.rst","library/distutils.rst","library/dl.rst","library/doctest.rst","library/docxmlrpcserver.rst","library/dumbdbm.rst","library/dummy_thread.rst","library/dummy_threading.rst","library/easydialogs.rst","library/email.rst","library/email-examples.rst","library/email.charset.rst","library/email.encoders.rst","library/email.errors.rst","library/email.generator.rst","library/email.header.rst","library/email.iterators.rst","library/email.message.rst","library/email.mime.rst","library/email.parser.rst","library/email.utils.rst","library/ensurepip.rst","library/errno.rst","library/exceptions.rst","library/fcntl.rst","library/filecmp.rst","library/fileformats.rst","library/fileinput.rst","library/filesys.rst","library/fl.rst","library/fm.rst","library/fnmatch.rst","library/formatter.rst","library/fpectl.rst","library/fpformat.rst","library/fractions.rst","library/framework.rst","library/frameworks.rst","library/ftplib.rst","library/functions.rst","library/functools.rst","library/future_builtins.rst","library/gc.rst","library/gdbm.rst","library/gensuitemodule.rst","library/getopt.rst","library/getpass.rst","library/gettext.rst","library/gl.rst","library/glob.rst","library/grp.rst","library/gzip.rst","library/hashlib.rst","library/heapq.rst","library/hmac.rst","library/hotshot.rst","library/htmllib.rst","library/htmlparser.rst","library/httplib.rst","library/i18n.rst","library/ic.rst","library/idle.rst","library/imageop.rst","library/imaplib.rst","library/imgfile.rst","library/imghdr.rst","library/imp.rst","library/importlib.rst","library/imputil.rst","library/index.rst","library/inspect.rst","library/internet.rst","library/intro.rst","library/io.rst","library/ipc.rst","library/itertools.rst","library/jpeg.rst","library/json.rst","library/keyword.rst","library/language.rst","library/linecache.rst","library/locale.rst","library/logging.rst","library/logging.config.rst","library/logging.handlers.rst","library/mac.rst","library/macos.rst","library/macosa.rst","library/macostools.rst","library/macpath.rst","library/mailbox.rst","library/mailcap.rst","library/markup.rst","library/marshal.rst","library/math.rst","library/md5.rst","library/mhlib.rst","library/mimetools.rst","library/mimetypes.rst","library/mimewriter.rst","library/mimify.rst","library/miniaeframe.rst","library/misc.rst","library/mm.rst","library/mmap.rst","library/modulefinder.rst","library/modules.rst","library/msilib.rst","library/msvcrt.rst","library/multifile.rst","library/multiprocessing.rst","library/mutex.rst","library/netdata.rst","library/netrc.rst","library/new.rst","library/nis.rst","library/nntplib.rst","library/numbers.rst","library/numeric.rst","library/operator.rst","library/optparse.rst","library/os.rst","library/os.path.rst","library/ossaudiodev.rst","library/othergui.rst","library/parser.rst","library/pdb.rst","library/persistence.rst","library/pickle.rst","library/pickletools.rst","library/pipes.rst","library/pkgutil.rst","library/platform.rst","library/plistlib.rst","library/popen2.rst","library/poplib.rst","library/posix.rst","library/posixfile.rst","library/pprint.rst","library/profile.rst","library/pty.rst","library/pwd.rst","library/py_compile.rst","library/pyclbr.rst","library/pydoc.rst","library/pyexpat.rst","library/python.rst","library/queue.rst","library/quopri.rst","library/random.rst","library/re.rst","library/readline.rst","library/repr.rst","library/resource.rst","library/restricted.rst","library/rexec.rst","library/rfc822.rst","library/rlcompleter.rst","library/robotparser.rst","library/runpy.rst","library/sched.rst","library/scrolledtext.rst","library/select.rst","library/sets.rst","library/sgi.rst","library/sgmllib.rst","library/sha.rst","library/shelve.rst","library/shlex.rst","library/shutil.rst","library/signal.rst","library/simplehttpserver.rst","library/simplexmlrpcserver.rst","library/site.rst","library/smtpd.rst","library/smtplib.rst","library/sndhdr.rst","library/socket.rst","library/socketserver.rst","library/someos.rst","library/spwd.rst","library/sqlite3.rst","library/ssl.rst","library/stat.rst","library/statvfs.rst","library/stdtypes.rst","library/string.rst","library/stringio.rst","library/stringprep.rst","library/strings.rst","library/struct.rst","library/subprocess.rst","library/sun.rst","library/sunau.rst","library/sunaudio.rst","library/symbol.rst","library/symtable.rst","library/sys.rst","library/sysconfig.rst","library/syslog.rst","library/tabnanny.rst","library/tarfile.rst","library/telnetlib.rst","library/tempfile.rst","library/termios.rst","library/test.rst","library/textwrap.rst","library/thread.rst","library/threading.rst","library/time.rst","library/timeit.rst","library/tix.rst","library/tk.rst","library/tkinter.rst","library/token.rst","library/tokenize.rst","library/trace.rst","library/traceback.rst","library/ttk.rst","library/tty.rst","library/turtle.rst","library/types.rst","library/undoc.rst","library/unicodedata.rst","library/unittest.rst","library/unix.rst","library/urllib.rst","library/urllib2.rst","library/urlparse.rst","library/user.rst","library/userdict.rst","library/uu.rst","library/uuid.rst","library/warnings.rst","library/wave.rst","library/weakref.rst","library/webbrowser.rst","library/whichdb.rst","library/windows.rst","library/winsound.rst","library/wsgiref.rst","library/xdrlib.rst","library/xml.rst","library/xml.dom.rst","library/xml.dom.minidom.rst","library/xml.dom.pulldom.rst","library/xml.etree.elementtree.rst","library/xml.sax.rst","library/xml.sax.handler.rst","library/xml.sax.reader.rst","library/xml.sax.utils.rst","library/xmlrpclib.rst","library/zipfile.rst","library/zipimport.rst","library/zlib.rst","license.rst","reference/compound_stmts.rst","reference/datamodel.rst","reference/executionmodel.rst","reference/expressions.rst","reference/grammar.rst","reference/index.rst","reference/introduction.rst","reference/lexical_analysis.rst","reference/simple_stmts.rst","reference/toplevel_components.rst","tutorial/appendix.rst","tutorial/appetite.rst","tutorial/classes.rst","tutorial/controlflow.rst","tutorial/datastructures.rst","tutorial/errors.rst","tutorial/floatingpoint.rst","tutorial/index.rst","tutorial/inputoutput.rst","tutorial/interactive.rst","tutorial/interpreter.rst","tutorial/introduction.rst","tutorial/modules.rst","tutorial/stdlib.rst","tutorial/stdlib2.rst","tutorial/whatnow.rst","using/cmdline.rst","using/index.rst","using/mac.rst","using/unix.rst","using/windows.rst","whatsnew/2.0.rst","whatsnew/2.1.rst","whatsnew/2.2.rst","whatsnew/2.3.rst","whatsnew/2.4.rst","whatsnew/2.5.rst","whatsnew/2.6.rst","whatsnew/2.7.rst","whatsnew/index.rst"],objects:{"":{"--help":[465,13,1,"cmdoption-help"],"--version":[465,13,1,"cmdoption-version"],"-3":[465,13,1,"cmdoption-3"],"-?":[465,13,1,"cmdoption"],"-B":[465,13,1,"id1"],"-E":[465,13,1,"cmdoption-e"],"-J":[465,13,1,"cmdoption-j"],"-O":[465,13,1,"cmdoption-o"],"-OO":[465,13,1,"cmdoption-oo"],"-Q":[465,13,1,"cmdoption-q"],"-R":[465,13,1,"cmdoption-r"],"-S":[465,13,1,"id2"],"-U":[465,13,1,"id4"],"-V":[465,13,1,"cmdoption-v"],"-W":[465,13,1,"cmdoption-w"],"-X":[465,13,1,"id5"],"-b":[465,13,1,"cmdoption-b"],"-c":[465,13,1,"cmdoption-c"],"-d":[465,13,1,"cmdoption-d"],"-h":[465,13,1,"cmdoption-h"],"-i":[465,13,1,"cmdoption-i"],"-m":[465,13,1,"cmdoption-m"],"-s":[465,13,1,"cmdoption-s"],"-t":[465,13,1,"cmdoption-t"],"-u":[465,13,1,"cmdoption-u"],"-v":[465,13,1,"id3"],"-x":[465,13,1,"cmdoption-x"],"DELETE_SLICE+0":[182,14,1,"-"],"DELETE_SLICE+1":[182,14,1,"-"],"DELETE_SLICE+2":[182,14,1,"-"],"DELETE_SLICE+3":[182,14,1,"-"],"SLICE+0":[182,14,1,"-"],"SLICE+1":[182,14,1,"-"],"SLICE+2":[182,14,1,"-"],"SLICE+3":[182,14,1,"-"],"STORE_SLICE+0":[182,14,1,"-"],"STORE_SLICE+1":[182,14,1,"-"],"STORE_SLICE+2":[182,14,1,"-"],"STORE_SLICE+3":[182,14,1,"-"],"float":[222,6,1,""],"import":[109,16,1,"-"],"int":[222,6,1,""],"long":[109,16,1,"-"],"new":[297,5,0,"-"],"super":[222,9,1,""],"throw":[109,16,1,"-"],AL:[119,5,0,"-"],BINARY_ADD:[182,14,1,"-"],BINARY_AND:[182,14,1,"-"],BINARY_DIVIDE:[182,14,1,"-"],BINARY_FLOOR_DIVIDE:[182,14,1,"-"],BINARY_LSHIFT:[182,14,1,"-"],BINARY_MODULO:[182,14,1,"-"],BINARY_MULTIPLY:[182,14,1,"-"],BINARY_OR:[182,14,1,"-"],BINARY_POWER:[182,14,1,"-"],BINARY_RSHIFT:[182,14,1,"-"],BINARY_SUBSCR:[182,14,1,"-"],BINARY_SUBTRACT:[182,14,1,"-"],BINARY_TRUE_DIVIDE:[182,14,1,"-"],BINARY_XOR:[182,14,1,"-"],BREAK_LOOP:[182,14,1,"-"],BUILD_CLASS:[182,14,1,"-"],BUILD_LIST:[182,14,1,"-"],BUILD_MAP:[182,14,1,"-"],BUILD_SET:[182,14,1,"-"],BUILD_SLICE:[182,14,1,"-"],BUILD_TUPLE:[182,14,1,"-"],BaseHTTPServer:[132,5,0,"-"],Bastion:[133,5,0,"-"],CALL_FUNCTION:[182,14,1,"-"],CALL_FUNCTION_KW:[182,14,1,"-"],CALL_FUNCTION_VAR:[182,14,1,"-"],CALL_FUNCTION_VAR_KW:[182,14,1,"-"],CGIHTTPServer:[144,5,0,"-"],COMPARE_OP:[182,14,1,"-"],CONTINUE_LOOP:[182,14,1,"-"],CO_FUTURE_DIVISION:[58,0,1,"c.CO_FUTURE_DIVISION"],ColorPicker:[153,5,0,"-"],ConfigParser:[158,5,0,"-"],Connection:[293,6,1,""],Cookie:[161,5,0,"-"],DELETE_ATTR:[182,14,1,"-"],DELETE_FAST:[182,14,1,"-"],DELETE_GLOBAL:[182,14,1,"-"],DELETE_NAME:[182,14,1,"-"],DELETE_SUBSCR:[182,14,1,"-"],DEVICE:[231,5,0,"-"],DUP_TOP:[182,14,1,"-"],DUP_TOPX:[182,14,1,"-"],DocXMLRPCServer:[187,5,0,"-"],END_FINALLY:[182,14,1,"-"],EXEC_STMT:[182,14,1,"-"],EXTENDED_ARG:[182,14,1,"-"],EasyDialogs:[191,5,0,"-"],Ellipsis:[159,11,1,""],FL:[212,5,0,"-"],FOR_ITER:[182,14,1,"-"],False:[159,11,1,""],FrameWork:[219,5,0,"-"],GET_ITER:[182,14,1,"-"],GL:[231,5,0,"-"],HAVE_ARGUMENT:[182,14,1,"-"],HTMLParser:[240,5,0,"-"],IMPORT_FROM:[182,14,1,"-"],IMPORT_NAME:[182,14,1,"-"],IMPORT_STAR:[182,14,1,"-"],INPLACE_ADD:[182,14,1,"-"],INPLACE_AND:[182,14,1,"-"],INPLACE_DIVIDE:[182,14,1,"-"],INPLACE_FLOOR_DIVIDE:[182,14,1,"-"],INPLACE_LSHIFT:[182,14,1,"-"],INPLACE_MODULO:[182,14,1,"-"],INPLACE_MULTIPLY:[182,14,1,"-"],INPLACE_OR:[182,14,1,"-"],INPLACE_POWER:[182,14,1,"-"],INPLACE_RSHIFT:[182,14,1,"-"],INPLACE_SUBTRACT:[182,14,1,"-"],INPLACE_TRUE_DIVIDE:[182,14,1,"-"],INPLACE_XOR:[182,14,1,"-"],JUMP_ABSOLUTE:[182,14,1,"-"],JUMP_FORWARD:[182,14,1,"-"],JUMP_IF_FALSE_OR_POP:[182,14,1,"-"],JUMP_IF_TRUE_OR_POP:[182,14,1,"-"],LIST_APPEND:[182,14,1,"-"],LOAD_ATTR:[182,14,1,"-"],LOAD_CLOSURE:[182,14,1,"-"],LOAD_CONST:[182,14,1,"-"],LOAD_DEREF:[182,14,1,"-"],LOAD_FAST:[182,14,1,"-"],LOAD_GLOBAL:[182,14,1,"-"],LOAD_LOCALS:[182,14,1,"-"],LOAD_NAME:[182,14,1,"-"],MAKE_CLOSURE:[182,14,1,"-"],MAKE_FUNCTION:[182,14,1,"-"],METH_CLASS:[51,11,1,""],METH_COEXIST:[51,11,1,""],METH_KEYWORDS:[51,11,1,""],METH_NOARGS:[51,11,1,""],METH_O:[51,11,1,""],METH_OLDARGS:[51,11,1,""],METH_STATIC:[51,11,1,""],METH_VARARGS:[51,11,1,""],MacOS:[269,5,0,"-"],MimeWriter:[282,5,0,"-"],MiniAEFrame:[284,5,0,"-"],NOP:[182,14,1,"-"],Nav:[405,5,0,"-"],None:[159,11,1,""],NotImplemented:[159,11,1,""],POP_BLOCK:[182,14,1,"-"],POP_JUMP_IF_FALSE:[182,14,1,"-"],POP_JUMP_IF_TRUE:[182,14,1,"-"],POP_TOP:[182,14,1,"-"],PRINT_EXPR:[182,14,1,"-"],PRINT_ITEM:[182,14,1,"-"],PRINT_ITEM_TO:[182,14,1,"-"],PRINT_NEWLINE:[182,14,1,"-"],PRINT_NEWLINE_TO:[182,14,1,"-"],PYTHONCASEOK:[465,15,1,"-"],PYTHONDEBUG:[465,15,1,"-"],PYTHONDONTWRITEBYTECODE:[465,15,1,"-"],PYTHONDUMPREFS:[465,15,1,"-"],PYTHONEXECUTABLE:[465,15,1,"-"],PYTHONHASHSEED:[465,15,1,"-"],PYTHONHOME:[465,15,1,"-"],PYTHONHTTPSVERIFY:[465,15,1,"-"],PYTHONINSPECT:[465,15,1,"-"],PYTHONIOENCODING:[465,15,1,"-"],PYTHONMALLOCSTATS:[465,15,1,"-"],PYTHONNOUSERSITE:[465,15,1,"-"],PYTHONOPTIMIZE:[465,15,1,"-"],PYTHONPATH:[465,15,1,"-"],PYTHONSHOWALLOCCOUNT:[465,15,1,"-"],PYTHONSHOWREFCOUNT:[465,15,1,"-"],PYTHONSTARTUP:[465,15,1,"-"],PYTHONTHREADDEBUG:[465,15,1,"-"],PYTHONUNBUFFERED:[465,15,1,"-"],PYTHONUSERBASE:[465,15,1,"-"],PYTHONVERBOSE:[465,15,1,"-"],PYTHONWARNINGS:[465,15,1,"-"],PYTHONY2K:[465,15,1,"-"],PixMapWrapper:[405,5,0,"-"],PyAnySet_Check:[48,1,1,"c.PyAnySet_Check"],PyAnySet_CheckExact:[48,1,1,"c.PyAnySet_CheckExact"],PyArg_Parse:[4,1,1,"c.PyArg_Parse"],PyArg_ParseTuple:[4,1,1,"c.PyArg_ParseTuple"],PyArg_ParseTupleAndKeywords:[4,1,1,"c.PyArg_ParseTupleAndKeywords"],PyArg_UnpackTuple:[4,1,1,"c.PyArg_UnpackTuple"],PyArg_VaParse:[4,1,1,"c.PyArg_VaParse"],PyArg_VaParseTupleAndKeywords:[4,1,1,"c.PyArg_VaParseTupleAndKeywords"],PyBool_Check:[5,1,1,"c.PyBool_Check"],PyBool_FromLong:[5,1,1,"c.PyBool_FromLong"],PyBufferObject:[6,2,1,"c.PyBufferObject"],PyBufferProcs:[55,2,1,"c.PyBufferProcs"],PyBuffer_Check:[6,1,1,"c.PyBuffer_Check"],PyBuffer_FillContiguousStrides:[6,1,1,"c.PyBuffer_FillContiguousStrides"],PyBuffer_FillInfo:[6,1,1,"c.PyBuffer_FillInfo"],PyBuffer_FromMemory:[6,1,1,"c.PyBuffer_FromMemory"],PyBuffer_FromObject:[6,1,1,"c.PyBuffer_FromObject"],PyBuffer_FromReadWriteMemory:[6,1,1,"c.PyBuffer_FromReadWriteMemory"],PyBuffer_FromReadWriteObject:[6,1,1,"c.PyBuffer_FromReadWriteObject"],PyBuffer_IsContiguous:[6,1,1,"c.PyBuffer_IsContiguous"],PyBuffer_New:[6,1,1,"c.PyBuffer_New"],PyBuffer_Release:[6,1,1,"c.PyBuffer_Release"],PyBuffer_SizeFromFormat:[6,1,1,"c.PyBuffer_SizeFromFormat"],PyBuffer_Type:[6,0,1,"c.PyBuffer_Type"],PyByteArrayObject:[7,2,1,"c.PyByteArrayObject"],PyByteArray_AS_STRING:[7,1,1,"c.PyByteArray_AS_STRING"],PyByteArray_AsString:[7,1,1,"c.PyByteArray_AsString"],PyByteArray_Check:[7,1,1,"c.PyByteArray_Check"],PyByteArray_CheckExact:[7,1,1,"c.PyByteArray_CheckExact"],PyByteArray_Concat:[7,1,1,"c.PyByteArray_Concat"],PyByteArray_FromObject:[7,1,1,"c.PyByteArray_FromObject"],PyByteArray_FromStringAndSize:[7,1,1,"c.PyByteArray_FromStringAndSize"],PyByteArray_GET_SIZE:[7,1,1,"c.PyByteArray_GET_SIZE"],PyByteArray_Resize:[7,1,1,"c.PyByteArray_Resize"],PyByteArray_Size:[7,1,1,"c.PyByteArray_Size"],PyByteArray_Type:[7,0,1,"c.PyByteArray_Type"],PyCFunction:[51,2,1,"c.PyCFunction"],PyCObject:[11,2,1,"c.PyCObject"],PyCObject_AsVoidPtr:[11,1,1,"c.PyCObject_AsVoidPtr"],PyCObject_Check:[11,1,1,"c.PyCObject_Check"],PyCObject_FromVoidPtr:[11,1,1,"c.PyCObject_FromVoidPtr"],PyCObject_FromVoidPtrAndDesc:[11,1,1,"c.PyCObject_FromVoidPtrAndDesc"],PyCObject_GetDesc:[11,1,1,"c.PyCObject_GetDesc"],PyCObject_SetVoidPtr:[11,1,1,"c.PyCObject_SetVoidPtr"],PyCallIter_Check:[32,1,1,"c.PyCallIter_Check"],PyCallIter_New:[32,1,1,"c.PyCallIter_New"],PyCallIter_Type:[32,0,1,"c.PyCallIter_Type"],PyCallable_Check:[43,1,1,"c.PyCallable_Check"],PyCapsule:[8,2,1,"c.PyCapsule"],PyCapsule_CheckExact:[8,1,1,"c.PyCapsule_CheckExact"],PyCapsule_Destructor:[8,2,1,"c.PyCapsule_Destructor"],PyCapsule_GetContext:[8,1,1,"c.PyCapsule_GetContext"],PyCapsule_GetDestructor:[8,1,1,"c.PyCapsule_GetDestructor"],PyCapsule_GetName:[8,1,1,"c.PyCapsule_GetName"],PyCapsule_GetPointer:[8,1,1,"c.PyCapsule_GetPointer"],PyCapsule_Import:[8,1,1,"c.PyCapsule_Import"],PyCapsule_IsValid:[8,1,1,"c.PyCapsule_IsValid"],PyCapsule_New:[8,1,1,"c.PyCapsule_New"],PyCapsule_SetContext:[8,1,1,"c.PyCapsule_SetContext"],PyCapsule_SetDestructor:[8,1,1,"c.PyCapsule_SetDestructor"],PyCapsule_SetName:[8,1,1,"c.PyCapsule_SetName"],PyCapsule_SetPointer:[8,1,1,"c.PyCapsule_SetPointer"],PyCellObject:[9,2,1,"c.PyCellObject"],PyCell_Check:[9,1,1,"c.PyCell_Check"],PyCell_GET:[9,1,1,"c.PyCell_GET"],PyCell_Get:[9,1,1,"c.PyCell_Get"],PyCell_New:[9,1,1,"c.PyCell_New"],PyCell_SET:[9,1,1,"c.PyCell_SET"],PyCell_Set:[9,1,1,"c.PyCell_Set"],PyCell_Type:[9,0,1,"c.PyCell_Type"],PyClassObject:[10,2,1,"c.PyClassObject"],PyClass_Check:[10,1,1,"c.PyClass_Check"],PyClass_IsSubclass:[10,1,1,"c.PyClass_IsSubclass"],PyClass_Type:[10,0,1,"c.PyClass_Type"],PyCodeObject:[12,2,1,"c.PyCodeObject"],PyCode_Check:[12,1,1,"c.PyCode_Check"],PyCode_GetNumFree:[12,1,1,"c.PyCode_GetNumFree"],PyCode_New:[12,1,1,"c.PyCode_New"],PyCode_NewEmpty:[12,1,1,"c.PyCode_NewEmpty"],PyCode_Type:[12,0,1,"c.PyCode_Type"],PyCodec_BackslashReplaceErrors:[13,1,1,"c.PyCodec_BackslashReplaceErrors"],PyCodec_Decode:[13,1,1,"c.PyCodec_Decode"],PyCodec_Decoder:[13,1,1,"c.PyCodec_Decoder"],PyCodec_Encode:[13,1,1,"c.PyCodec_Encode"],PyCodec_Encoder:[13,1,1,"c.PyCodec_Encoder"],PyCodec_IgnoreErrors:[13,1,1,"c.PyCodec_IgnoreErrors"],PyCodec_IncrementalDecoder:[13,1,1,"c.PyCodec_IncrementalDecoder"],PyCodec_IncrementalEncoder:[13,1,1,"c.PyCodec_IncrementalEncoder"],PyCodec_KnownEncoding:[13,1,1,"c.PyCodec_KnownEncoding"],PyCodec_LookupError:[13,1,1,"c.PyCodec_LookupError"],PyCodec_Register:[13,1,1,"c.PyCodec_Register"],PyCodec_RegisterError:[13,1,1,"c.PyCodec_RegisterError"],PyCodec_ReplaceErrors:[13,1,1,"c.PyCodec_ReplaceErrors"],PyCodec_StreamReader:[13,1,1,"c.PyCodec_StreamReader"],PyCodec_StreamWriter:[13,1,1,"c.PyCodec_StreamWriter"],PyCodec_StrictErrors:[13,1,1,"c.PyCodec_StrictErrors"],PyCodec_XMLCharRefReplaceErrors:[13,1,1,"c.PyCodec_XMLCharRefReplaceErrors"],PyCompilerFlags:[58,2,1,"c.PyCompilerFlags"],PyComplexObject:[14,2,1,"c.PyComplexObject"],PyComplex_AsCComplex:[14,1,1,"c.PyComplex_AsCComplex"],PyComplex_Check:[14,1,1,"c.PyComplex_Check"],PyComplex_CheckExact:[14,1,1,"c.PyComplex_CheckExact"],PyComplex_FromCComplex:[14,1,1,"c.PyComplex_FromCComplex"],PyComplex_FromDoubles:[14,1,1,"c.PyComplex_FromDoubles"],PyComplex_ImagAsDouble:[14,1,1,"c.PyComplex_ImagAsDouble"],PyComplex_RealAsDouble:[14,1,1,"c.PyComplex_RealAsDouble"],PyComplex_Type:[14,0,1,"c.PyComplex_Type"],PyDateTime_Check:[17,1,1,"c.PyDateTime_Check"],PyDateTime_CheckExact:[17,1,1,"c.PyDateTime_CheckExact"],PyDateTime_DATE_GET_HOUR:[17,1,1,"c.PyDateTime_DATE_GET_HOUR"],PyDateTime_DATE_GET_MICROSECOND:[17,1,1,"c.PyDateTime_DATE_GET_MICROSECOND"],PyDateTime_DATE_GET_MINUTE:[17,1,1,"c.PyDateTime_DATE_GET_MINUTE"],PyDateTime_DATE_GET_SECOND:[17,1,1,"c.PyDateTime_DATE_GET_SECOND"],PyDateTime_FromDateAndTime:[17,1,1,"c.PyDateTime_FromDateAndTime"],PyDateTime_FromTimestamp:[17,1,1,"c.PyDateTime_FromTimestamp"],PyDateTime_GET_DAY:[17,1,1,"c.PyDateTime_GET_DAY"],PyDateTime_GET_MONTH:[17,1,1,"c.PyDateTime_GET_MONTH"],PyDateTime_GET_YEAR:[17,1,1,"c.PyDateTime_GET_YEAR"],PyDateTime_TIME_GET_HOUR:[17,1,1,"c.PyDateTime_TIME_GET_HOUR"],PyDateTime_TIME_GET_MICROSECOND:[17,1,1,"c.PyDateTime_TIME_GET_MICROSECOND"],PyDateTime_TIME_GET_MINUTE:[17,1,1,"c.PyDateTime_TIME_GET_MINUTE"],PyDateTime_TIME_GET_SECOND:[17,1,1,"c.PyDateTime_TIME_GET_SECOND"],PyDate_Check:[17,1,1,"c.PyDate_Check"],PyDate_CheckExact:[17,1,1,"c.PyDate_CheckExact"],PyDate_FromDate:[17,1,1,"c.PyDate_FromDate"],PyDate_FromTimestamp:[17,1,1,"c.PyDate_FromTimestamp"],PyDelta_Check:[17,1,1,"c.PyDelta_Check"],PyDelta_CheckExact:[17,1,1,"c.PyDelta_CheckExact"],PyDelta_FromDSU:[17,1,1,"c.PyDelta_FromDSU"],PyDescr_IsData:[18,1,1,"c.PyDescr_IsData"],PyDescr_NewClassMethod:[18,1,1,"c.PyDescr_NewClassMethod"],PyDescr_NewGetSet:[18,1,1,"c.PyDescr_NewGetSet"],PyDescr_NewMember:[18,1,1,"c.PyDescr_NewMember"],PyDescr_NewMethod:[18,1,1,"c.PyDescr_NewMethod"],PyDescr_NewWrapper:[18,1,1,"c.PyDescr_NewWrapper"],PyDictObject:[19,2,1,"c.PyDictObject"],PyDictProxy_New:[19,1,1,"c.PyDictProxy_New"],PyDict_Check:[19,1,1,"c.PyDict_Check"],PyDict_CheckExact:[19,1,1,"c.PyDict_CheckExact"],PyDict_Clear:[19,1,1,"c.PyDict_Clear"],PyDict_Contains:[19,1,1,"c.PyDict_Contains"],PyDict_Copy:[19,1,1,"c.PyDict_Copy"],PyDict_DelItem:[19,1,1,"c.PyDict_DelItem"],PyDict_DelItemString:[19,1,1,"c.PyDict_DelItemString"],PyDict_GetItem:[19,1,1,"c.PyDict_GetItem"],PyDict_GetItemString:[19,1,1,"c.PyDict_GetItemString"],PyDict_Items:[19,1,1,"c.PyDict_Items"],PyDict_Keys:[19,1,1,"c.PyDict_Keys"],PyDict_Merge:[19,1,1,"c.PyDict_Merge"],PyDict_MergeFromSeq2:[19,1,1,"c.PyDict_MergeFromSeq2"],PyDict_New:[19,1,1,"c.PyDict_New"],PyDict_Next:[19,1,1,"c.PyDict_Next"],PyDict_SetItem:[19,1,1,"c.PyDict_SetItem"],PyDict_SetItemString:[19,1,1,"c.PyDict_SetItemString"],PyDict_Size:[19,1,1,"c.PyDict_Size"],PyDict_Type:[19,0,1,"c.PyDict_Type"],PyDict_Update:[19,1,1,"c.PyDict_Update"],PyDict_Values:[19,1,1,"c.PyDict_Values"],PyErr_BadArgument:[20,1,1,"c.PyErr_BadArgument"],PyErr_BadInternalCall:[20,1,1,"c.PyErr_BadInternalCall"],PyErr_CheckSignals:[20,1,1,"c.PyErr_CheckSignals"],PyErr_Clear:[20,1,1,"c.PyErr_Clear"],PyErr_ExceptionMatches:[20,1,1,"c.PyErr_ExceptionMatches"],PyErr_Fetch:[20,1,1,"c.PyErr_Fetch"],PyErr_Format:[20,1,1,"c.PyErr_Format"],PyErr_GivenExceptionMatches:[20,1,1,"c.PyErr_GivenExceptionMatches"],PyErr_NewException:[20,1,1,"c.PyErr_NewException"],PyErr_NewExceptionWithDoc:[20,1,1,"c.PyErr_NewExceptionWithDoc"],PyErr_NoMemory:[20,1,1,"c.PyErr_NoMemory"],PyErr_NormalizeException:[20,1,1,"c.PyErr_NormalizeException"],PyErr_Occurred:[20,1,1,"c.PyErr_Occurred"],PyErr_Print:[20,1,1,"c.PyErr_Print"],PyErr_PrintEx:[20,1,1,"c.PyErr_PrintEx"],PyErr_Restore:[20,1,1,"c.PyErr_Restore"],PyErr_SetExcFromWindowsErr:[20,1,1,"c.PyErr_SetExcFromWindowsErr"],PyErr_SetExcFromWindowsErrWithFilename:[20,1,1,"c.PyErr_SetExcFromWindowsErrWithFilename"],PyErr_SetExcFromWindowsErrWithFilenameObject:[20,1,1,"c.PyErr_SetExcFromWindowsErrWithFilenameObject"],PyErr_SetFromErrno:[20,1,1,"c.PyErr_SetFromErrno"],PyErr_SetFromErrnoWithFilename:[20,1,1,"c.PyErr_SetFromErrnoWithFilename"],PyErr_SetFromErrnoWithFilenameObject:[20,1,1,"c.PyErr_SetFromErrnoWithFilenameObject"],PyErr_SetFromWindowsErr:[20,1,1,"c.PyErr_SetFromWindowsErr"],PyErr_SetFromWindowsErrWithFilename:[20,1,1,"c.PyErr_SetFromWindowsErrWithFilename"],PyErr_SetFromWindowsErrWithFilenameObject:[20,1,1,"c.PyErr_SetFromWindowsErrWithFilenameObject"],PyErr_SetInterrupt:[20,1,1,"c.PyErr_SetInterrupt"],PyErr_SetNone:[20,1,1,"c.PyErr_SetNone"],PyErr_SetObject:[20,1,1,"c.PyErr_SetObject"],PyErr_SetString:[20,1,1,"c.PyErr_SetString"],PyErr_Warn:[20,1,1,"c.PyErr_Warn"],PyErr_WarnEx:[20,1,1,"c.PyErr_WarnEx"],PyErr_WarnExplicit:[20,1,1,"c.PyErr_WarnExplicit"],PyErr_WarnPy3k:[20,1,1,"c.PyErr_WarnPy3k"],PyErr_WriteUnraisable:[20,1,1,"c.PyErr_WriteUnraisable"],PyEval_AcquireLock:[28,1,1,"c.PyEval_AcquireLock"],PyEval_AcquireThread:[28,1,1,"c.PyEval_AcquireThread"],PyEval_EvalCode:[58,1,1,"c.PyEval_EvalCode"],PyEval_EvalCodeEx:[58,1,1,"c.PyEval_EvalCodeEx"],PyEval_EvalFrame:[58,1,1,"c.PyEval_EvalFrame"],PyEval_EvalFrameEx:[58,1,1,"c.PyEval_EvalFrameEx"],PyEval_GetBuiltins:[46,1,1,"c.PyEval_GetBuiltins"],PyEval_GetCallStats:[28,1,1,"c.PyEval_GetCallStats"],PyEval_GetFrame:[46,1,1,"c.PyEval_GetFrame"],PyEval_GetFuncDesc:[46,1,1,"c.PyEval_GetFuncDesc"],PyEval_GetFuncName:[46,1,1,"c.PyEval_GetFuncName"],PyEval_GetGlobals:[46,1,1,"c.PyEval_GetGlobals"],PyEval_GetLocals:[46,1,1,"c.PyEval_GetLocals"],PyEval_GetRestricted:[46,1,1,"c.PyEval_GetRestricted"],PyEval_InitThreads:[28,1,1,"c.PyEval_InitThreads"],PyEval_MergeCompilerFlags:[58,1,1,"c.PyEval_MergeCompilerFlags"],PyEval_ReInitThreads:[28,1,1,"c.PyEval_ReInitThreads"],PyEval_ReleaseLock:[28,1,1,"c.PyEval_ReleaseLock"],PyEval_ReleaseThread:[28,1,1,"c.PyEval_ReleaseThread"],PyEval_RestoreThread:[28,1,1,"c.PyEval_RestoreThread"],PyEval_SaveThread:[28,1,1,"c.PyEval_SaveThread"],PyEval_SetProfile:[28,1,1,"c.PyEval_SetProfile"],PyEval_SetTrace:[28,1,1,"c.PyEval_SetTrace"],PyEval_ThreadsInitialized:[28,1,1,"c.PyEval_ThreadsInitialized"],PyFileObject:[21,2,1,"c.PyFileObject"],PyFile_AsFile:[21,1,1,"c.PyFile_AsFile"],PyFile_Check:[21,1,1,"c.PyFile_Check"],PyFile_CheckExact:[21,1,1,"c.PyFile_CheckExact"],PyFile_DecUseCount:[21,1,1,"c.PyFile_DecUseCount"],PyFile_FromFile:[21,1,1,"c.PyFile_FromFile"],PyFile_FromString:[21,1,1,"c.PyFile_FromString"],PyFile_GetLine:[21,1,1,"c.PyFile_GetLine"],PyFile_IncUseCount:[21,1,1,"c.PyFile_IncUseCount"],PyFile_Name:[21,1,1,"c.PyFile_Name"],PyFile_SetBufSize:[21,1,1,"c.PyFile_SetBufSize"],PyFile_SetEncoding:[21,1,1,"c.PyFile_SetEncoding"],PyFile_SetEncodingAndErrors:[21,1,1,"c.PyFile_SetEncodingAndErrors"],PyFile_SoftSpace:[21,1,1,"c.PyFile_SoftSpace"],PyFile_Type:[21,0,1,"c.PyFile_Type"],PyFile_WriteObject:[21,1,1,"c.PyFile_WriteObject"],PyFile_WriteString:[21,1,1,"c.PyFile_WriteString"],PyFloatObject:[22,2,1,"c.PyFloatObject"],PyFloat_AS_DOUBLE:[22,1,1,"c.PyFloat_AS_DOUBLE"],PyFloat_AsDouble:[22,1,1,"c.PyFloat_AsDouble"],PyFloat_AsReprString:[22,1,1,"c.PyFloat_AsReprString"],PyFloat_AsString:[22,1,1,"c.PyFloat_AsString"],PyFloat_Check:[22,1,1,"c.PyFloat_Check"],PyFloat_CheckExact:[22,1,1,"c.PyFloat_CheckExact"],PyFloat_ClearFreeList:[22,1,1,"c.PyFloat_ClearFreeList"],PyFloat_FromDouble:[22,1,1,"c.PyFloat_FromDouble"],PyFloat_FromString:[22,1,1,"c.PyFloat_FromString"],PyFloat_GetInfo:[22,1,1,"c.PyFloat_GetInfo"],PyFloat_GetMax:[22,1,1,"c.PyFloat_GetMax"],PyFloat_GetMin:[22,1,1,"c.PyFloat_GetMin"],PyFloat_Type:[22,0,1,"c.PyFloat_Type"],PyFrame_GetLineNumber:[46,1,1,"c.PyFrame_GetLineNumber"],PyFrozenSet_Check:[48,1,1,"c.PyFrozenSet_Check"],PyFrozenSet_CheckExact:[48,1,1,"c.PyFrozenSet_CheckExact"],PyFrozenSet_New:[48,1,1,"c.PyFrozenSet_New"],PyFrozenSet_Type:[48,0,1,"c.PyFrozenSet_Type"],PyFunctionObject:[23,2,1,"c.PyFunctionObject"],PyFunction_Check:[23,1,1,"c.PyFunction_Check"],PyFunction_GetClosure:[23,1,1,"c.PyFunction_GetClosure"],PyFunction_GetCode:[23,1,1,"c.PyFunction_GetCode"],PyFunction_GetDefaults:[23,1,1,"c.PyFunction_GetDefaults"],PyFunction_GetGlobals:[23,1,1,"c.PyFunction_GetGlobals"],PyFunction_GetModule:[23,1,1,"c.PyFunction_GetModule"],PyFunction_New:[23,1,1,"c.PyFunction_New"],PyFunction_SetClosure:[23,1,1,"c.PyFunction_SetClosure"],PyFunction_SetDefaults:[23,1,1,"c.PyFunction_SetDefaults"],PyFunction_Type:[23,0,1,"c.PyFunction_Type"],PyGILState_Ensure:[28,1,1,"c.PyGILState_Ensure"],PyGILState_GetThisThreadState:[28,1,1,"c.PyGILState_GetThisThreadState"],PyGILState_Release:[28,1,1,"c.PyGILState_Release"],PyGenObject:[25,2,1,"c.PyGenObject"],PyGen_Check:[25,1,1,"c.PyGen_Check"],PyGen_CheckExact:[25,1,1,"c.PyGen_CheckExact"],PyGen_New:[25,1,1,"c.PyGen_New"],PyGen_Type:[25,0,1,"c.PyGen_Type"],PyGetSetDef:[51,2,1,"c.PyGetSetDef"],PyImport_AddModule:[26,1,1,"c.PyImport_AddModule"],PyImport_AppendInittab:[26,1,1,"c.PyImport_AppendInittab"],PyImport_Cleanup:[26,1,1,"c.PyImport_Cleanup"],PyImport_ExecCodeModule:[26,1,1,"c.PyImport_ExecCodeModule"],PyImport_ExecCodeModuleEx:[26,1,1,"c.PyImport_ExecCodeModuleEx"],PyImport_ExtendInittab:[26,1,1,"c.PyImport_ExtendInittab"],PyImport_FrozenModules:[26,0,1,"c.PyImport_FrozenModules"],PyImport_GetImporter:[26,1,1,"c.PyImport_GetImporter"],PyImport_GetMagicNumber:[26,1,1,"c.PyImport_GetMagicNumber"],PyImport_GetModuleDict:[26,1,1,"c.PyImport_GetModuleDict"],PyImport_Import:[26,1,1,"c.PyImport_Import"],PyImport_ImportFrozenModule:[26,1,1,"c.PyImport_ImportFrozenModule"],PyImport_ImportModule:[26,1,1,"c.PyImport_ImportModule"],PyImport_ImportModuleEx:[26,1,1,"c.PyImport_ImportModuleEx"],PyImport_ImportModuleLevel:[26,1,1,"c.PyImport_ImportModuleLevel"],PyImport_ImportModuleNoBlock:[26,1,1,"c.PyImport_ImportModuleNoBlock"],PyImport_ReloadModule:[26,1,1,"c.PyImport_ReloadModule"],PyIndex_Check:[41,1,1,"c.PyIndex_Check"],PyInstance_Check:[10,1,1,"c.PyInstance_Check"],PyInstance_New:[10,1,1,"c.PyInstance_New"],PyInstance_NewRaw:[10,1,1,"c.PyInstance_NewRaw"],PyInstance_Type:[10,0,1,"c.PyInstance_Type"],PyIntObject:[29,2,1,"c.PyIntObject"],PyInt_AS_LONG:[29,1,1,"c.PyInt_AS_LONG"],PyInt_AsLong:[29,1,1,"c.PyInt_AsLong"],PyInt_AsSsize_t:[29,1,1,"c.PyInt_AsSsize_t"],PyInt_AsUnsignedLongLongMask:[29,1,1,"c.PyInt_AsUnsignedLongLongMask"],PyInt_AsUnsignedLongMask:[29,1,1,"c.PyInt_AsUnsignedLongMask"],PyInt_Check:[29,1,1,"c.PyInt_Check"],PyInt_CheckExact:[29,1,1,"c.PyInt_CheckExact"],PyInt_ClearFreeList:[29,1,1,"c.PyInt_ClearFreeList"],PyInt_FromLong:[29,1,1,"c.PyInt_FromLong"],PyInt_FromSize_t:[29,1,1,"c.PyInt_FromSize_t"],PyInt_FromSsize_t:[29,1,1,"c.PyInt_FromSsize_t"],PyInt_FromString:[29,1,1,"c.PyInt_FromString"],PyInt_GetMax:[29,1,1,"c.PyInt_GetMax"],PyInt_Type:[29,0,1,"c.PyInt_Type"],PyInterpreterState:[28,2,1,"c.PyInterpreterState"],PyInterpreterState_Clear:[28,1,1,"c.PyInterpreterState_Clear"],PyInterpreterState_Delete:[28,1,1,"c.PyInterpreterState_Delete"],PyInterpreterState_Head:[28,1,1,"c.PyInterpreterState_Head"],PyInterpreterState_New:[28,1,1,"c.PyInterpreterState_New"],PyInterpreterState_Next:[28,1,1,"c.PyInterpreterState_Next"],PyInterpreterState_ThreadHead:[28,1,1,"c.PyInterpreterState_ThreadHead"],PyIter_Check:[31,1,1,"c.PyIter_Check"],PyIter_Next:[31,1,1,"c.PyIter_Next"],PyListObject:[33,2,1,"c.PyListObject"],PyList_Append:[33,1,1,"c.PyList_Append"],PyList_AsTuple:[33,1,1,"c.PyList_AsTuple"],PyList_Check:[33,1,1,"c.PyList_Check"],PyList_CheckExact:[33,1,1,"c.PyList_CheckExact"],PyList_GET_ITEM:[33,1,1,"c.PyList_GET_ITEM"],PyList_GET_SIZE:[33,1,1,"c.PyList_GET_SIZE"],PyList_GetItem:[33,1,1,"c.PyList_GetItem"],PyList_GetSlice:[33,1,1,"c.PyList_GetSlice"],PyList_Insert:[33,1,1,"c.PyList_Insert"],PyList_New:[33,1,1,"c.PyList_New"],PyList_Reverse:[33,1,1,"c.PyList_Reverse"],PyList_SET_ITEM:[33,1,1,"c.PyList_SET_ITEM"],PyList_SetItem:[33,1,1,"c.PyList_SetItem"],PyList_SetSlice:[33,1,1,"c.PyList_SetSlice"],PyList_Size:[33,1,1,"c.PyList_Size"],PyList_Sort:[33,1,1,"c.PyList_Sort"],PyList_Type:[33,0,1,"c.PyList_Type"],PyLongObject:[34,2,1,"c.PyLongObject"],PyLong_AsDouble:[34,1,1,"c.PyLong_AsDouble"],PyLong_AsLong:[34,1,1,"c.PyLong_AsLong"],PyLong_AsLongAndOverflow:[34,1,1,"c.PyLong_AsLongAndOverflow"],PyLong_AsLongLong:[34,1,1,"c.PyLong_AsLongLong"],PyLong_AsLongLongAndOverflow:[34,1,1,"c.PyLong_AsLongLongAndOverflow"],PyLong_AsSsize_t:[34,1,1,"c.PyLong_AsSsize_t"],PyLong_AsUnsignedLong:[34,1,1,"c.PyLong_AsUnsignedLong"],PyLong_AsUnsignedLongLong:[34,1,1,"c.PyLong_AsUnsignedLongLong"],PyLong_AsUnsignedLongLongMask:[34,1,1,"c.PyLong_AsUnsignedLongLongMask"],PyLong_AsUnsignedLongMask:[34,1,1,"c.PyLong_AsUnsignedLongMask"],PyLong_AsVoidPtr:[34,1,1,"c.PyLong_AsVoidPtr"],PyLong_Check:[34,1,1,"c.PyLong_Check"],PyLong_CheckExact:[34,1,1,"c.PyLong_CheckExact"],PyLong_FromDouble:[34,1,1,"c.PyLong_FromDouble"],PyLong_FromLong:[34,1,1,"c.PyLong_FromLong"],PyLong_FromLongLong:[34,1,1,"c.PyLong_FromLongLong"],PyLong_FromSize_t:[34,1,1,"c.PyLong_FromSize_t"],PyLong_FromSsize_t:[34,1,1,"c.PyLong_FromSsize_t"],PyLong_FromString:[34,1,1,"c.PyLong_FromString"],PyLong_FromUnicode:[34,1,1,"c.PyLong_FromUnicode"],PyLong_FromUnsignedLong:[34,1,1,"c.PyLong_FromUnsignedLong"],PyLong_FromUnsignedLongLong:[34,1,1,"c.PyLong_FromUnsignedLongLong"],PyLong_FromVoidPtr:[34,1,1,"c.PyLong_FromVoidPtr"],PyLong_Type:[34,0,1,"c.PyLong_Type"],PyMappingMethods:[55,2,1,"c.PyMappingMethods"],PyMapping_Check:[35,1,1,"c.PyMapping_Check"],PyMapping_DelItem:[35,1,1,"c.PyMapping_DelItem"],PyMapping_DelItemString:[35,1,1,"c.PyMapping_DelItemString"],PyMapping_GetItemString:[35,1,1,"c.PyMapping_GetItemString"],PyMapping_HasKey:[35,1,1,"c.PyMapping_HasKey"],PyMapping_HasKeyString:[35,1,1,"c.PyMapping_HasKeyString"],PyMapping_Items:[35,1,1,"c.PyMapping_Items"],PyMapping_Keys:[35,1,1,"c.PyMapping_Keys"],PyMapping_Length:[35,1,1,"c.PyMapping_Length"],PyMapping_SetItemString:[35,1,1,"c.PyMapping_SetItemString"],PyMapping_Size:[35,1,1,"c.PyMapping_Size"],PyMapping_Values:[35,1,1,"c.PyMapping_Values"],PyMarshal_ReadLastObjectFromFile:[36,1,1,"c.PyMarshal_ReadLastObjectFromFile"],PyMarshal_ReadLongFromFile:[36,1,1,"c.PyMarshal_ReadLongFromFile"],PyMarshal_ReadObjectFromFile:[36,1,1,"c.PyMarshal_ReadObjectFromFile"],PyMarshal_ReadObjectFromString:[36,1,1,"c.PyMarshal_ReadObjectFromString"],PyMarshal_ReadShortFromFile:[36,1,1,"c.PyMarshal_ReadShortFromFile"],PyMarshal_WriteLongToFile:[36,1,1,"c.PyMarshal_WriteLongToFile"],PyMarshal_WriteObjectToFile:[36,1,1,"c.PyMarshal_WriteObjectToFile"],PyMarshal_WriteObjectToString:[36,1,1,"c.PyMarshal_WriteObjectToString"],PyMem_Del:[37,1,1,"c.PyMem_Del"],PyMem_Free:[37,1,1,"c.PyMem_Free"],PyMem_Malloc:[37,1,1,"c.PyMem_Malloc"],PyMem_New:[37,1,1,"c.PyMem_New"],PyMem_Realloc:[37,1,1,"c.PyMem_Realloc"],PyMem_Resize:[37,1,1,"c.PyMem_Resize"],PyMemberDef:[51,2,1,"c.PyMemberDef"],PyMemoryView_Check:[6,1,1,"c.PyMemoryView_Check"],PyMemoryView_FromBuffer:[6,1,1,"c.PyMemoryView_FromBuffer"],PyMemoryView_FromObject:[6,1,1,"c.PyMemoryView_FromObject"],PyMemoryView_GET_BUFFER:[6,1,1,"c.PyMemoryView_GET_BUFFER"],PyMemoryView_GetContiguous:[6,1,1,"c.PyMemoryView_GetContiguous"],PyMethodDef:[51,2,1,"c.PyMethodDef"],PyMethod_Check:[38,1,1,"c.PyMethod_Check"],PyMethod_Class:[38,1,1,"c.PyMethod_Class"],PyMethod_ClearFreeList:[38,1,1,"c.PyMethod_ClearFreeList"],PyMethod_Function:[38,1,1,"c.PyMethod_Function"],PyMethod_GET_CLASS:[38,1,1,"c.PyMethod_GET_CLASS"],PyMethod_GET_FUNCTION:[38,1,1,"c.PyMethod_GET_FUNCTION"],PyMethod_GET_SELF:[38,1,1,"c.PyMethod_GET_SELF"],PyMethod_New:[38,1,1,"c.PyMethod_New"],PyMethod_Self:[38,1,1,"c.PyMethod_Self"],PyMethod_Type:[38,0,1,"c.PyMethod_Type"],PyModule_AddIntConstant:[39,1,1,"c.PyModule_AddIntConstant"],PyModule_AddIntMacro:[39,1,1,"c.PyModule_AddIntMacro"],PyModule_AddObject:[39,1,1,"c.PyModule_AddObject"],PyModule_AddStringConstant:[39,1,1,"c.PyModule_AddStringConstant"],PyModule_AddStringMacro:[39,1,1,"c.PyModule_AddStringMacro"],PyModule_Check:[39,1,1,"c.PyModule_Check"],PyModule_CheckExact:[39,1,1,"c.PyModule_CheckExact"],PyModule_GetDict:[39,1,1,"c.PyModule_GetDict"],PyModule_GetFilename:[39,1,1,"c.PyModule_GetFilename"],PyModule_GetName:[39,1,1,"c.PyModule_GetName"],PyModule_New:[39,1,1,"c.PyModule_New"],PyModule_Type:[39,0,1,"c.PyModule_Type"],PyNumberMethods:[55,2,1,"c.PyNumberMethods"],PyNumber_Absolute:[41,1,1,"c.PyNumber_Absolute"],PyNumber_Add:[41,1,1,"c.PyNumber_Add"],PyNumber_And:[41,1,1,"c.PyNumber_And"],PyNumber_AsSsize_t:[41,1,1,"c.PyNumber_AsSsize_t"],PyNumber_Check:[41,1,1,"c.PyNumber_Check"],PyNumber_Coerce:[41,1,1,"c.PyNumber_Coerce"],PyNumber_CoerceEx:[41,1,1,"c.PyNumber_CoerceEx"],PyNumber_Divide:[41,1,1,"c.PyNumber_Divide"],PyNumber_Divmod:[41,1,1,"c.PyNumber_Divmod"],PyNumber_Float:[41,1,1,"c.PyNumber_Float"],PyNumber_FloorDivide:[41,1,1,"c.PyNumber_FloorDivide"],PyNumber_InPlaceAdd:[41,1,1,"c.PyNumber_InPlaceAdd"],PyNumber_InPlaceAnd:[41,1,1,"c.PyNumber_InPlaceAnd"],PyNumber_InPlaceDivide:[41,1,1,"c.PyNumber_InPlaceDivide"],PyNumber_InPlaceFloorDivide:[41,1,1,"c.PyNumber_InPlaceFloorDivide"],PyNumber_InPlaceLshift:[41,1,1,"c.PyNumber_InPlaceLshift"],PyNumber_InPlaceMultiply:[41,1,1,"c.PyNumber_InPlaceMultiply"],PyNumber_InPlaceOr:[41,1,1,"c.PyNumber_InPlaceOr"],PyNumber_InPlacePower:[41,1,1,"c.PyNumber_InPlacePower"],PyNumber_InPlaceRemainder:[41,1,1,"c.PyNumber_InPlaceRemainder"],PyNumber_InPlaceRshift:[41,1,1,"c.PyNumber_InPlaceRshift"],PyNumber_InPlaceSubtract:[41,1,1,"c.PyNumber_InPlaceSubtract"],PyNumber_InPlaceTrueDivide:[41,1,1,"c.PyNumber_InPlaceTrueDivide"],PyNumber_InPlaceXor:[41,1,1,"c.PyNumber_InPlaceXor"],PyNumber_Index:[41,1,1,"c.PyNumber_Index"],PyNumber_Int:[41,1,1,"c.PyNumber_Int"],PyNumber_Invert:[41,1,1,"c.PyNumber_Invert"],PyNumber_Long:[41,1,1,"c.PyNumber_Long"],PyNumber_Lshift:[41,1,1,"c.PyNumber_Lshift"],PyNumber_Multiply:[41,1,1,"c.PyNumber_Multiply"],PyNumber_Negative:[41,1,1,"c.PyNumber_Negative"],PyNumber_Or:[41,1,1,"c.PyNumber_Or"],PyNumber_Positive:[41,1,1,"c.PyNumber_Positive"],PyNumber_Power:[41,1,1,"c.PyNumber_Power"],PyNumber_Remainder:[41,1,1,"c.PyNumber_Remainder"],PyNumber_Rshift:[41,1,1,"c.PyNumber_Rshift"],PyNumber_Subtract:[41,1,1,"c.PyNumber_Subtract"],PyNumber_ToBase:[41,1,1,"c.PyNumber_ToBase"],PyNumber_TrueDivide:[41,1,1,"c.PyNumber_TrueDivide"],PyNumber_Xor:[41,1,1,"c.PyNumber_Xor"],PyOS_AfterFork:[52,1,1,"c.PyOS_AfterFork"],PyOS_CheckStack:[52,1,1,"c.PyOS_CheckStack"],PyOS_ascii_atof:[16,1,1,"c.PyOS_ascii_atof"],PyOS_ascii_formatd:[16,1,1,"c.PyOS_ascii_formatd"],PyOS_ascii_strtod:[16,1,1,"c.PyOS_ascii_strtod"],PyOS_double_to_string:[16,1,1,"c.PyOS_double_to_string"],PyOS_getsig:[52,1,1,"c.PyOS_getsig"],PyOS_setsig:[52,1,1,"c.PyOS_setsig"],PyOS_snprintf:[16,1,1,"c.PyOS_snprintf"],PyOS_stricmp:[16,1,1,"c.PyOS_stricmp"],PyOS_string_to_double:[16,1,1,"c.PyOS_string_to_double"],PyOS_strnicmp:[16,1,1,"c.PyOS_strnicmp"],PyOS_vsnprintf:[16,1,1,"c.PyOS_vsnprintf"],PyObject:[51,2,1,"c.PyObject"],PyObject_AsCharBuffer:[42,1,1,"c.PyObject_AsCharBuffer"],PyObject_AsFileDescriptor:[43,1,1,"c.PyObject_AsFileDescriptor"],PyObject_AsReadBuffer:[42,1,1,"c.PyObject_AsReadBuffer"],PyObject_AsWriteBuffer:[42,1,1,"c.PyObject_AsWriteBuffer"],PyObject_Bytes:[43,1,1,"c.PyObject_Bytes"],PyObject_Call:[43,1,1,"c.PyObject_Call"],PyObject_CallFunction:[43,1,1,"c.PyObject_CallFunction"],PyObject_CallFunctionObjArgs:[43,1,1,"c.PyObject_CallFunctionObjArgs"],PyObject_CallMethod:[43,1,1,"c.PyObject_CallMethod"],PyObject_CallMethodObjArgs:[43,1,1,"c.PyObject_CallMethodObjArgs"],PyObject_CallObject:[43,1,1,"c.PyObject_CallObject"],PyObject_CheckBuffer:[6,1,1,"c.PyObject_CheckBuffer"],PyObject_CheckReadBuffer:[42,1,1,"c.PyObject_CheckReadBuffer"],PyObject_Cmp:[43,1,1,"c.PyObject_Cmp"],PyObject_Compare:[43,1,1,"c.PyObject_Compare"],PyObject_Del:[3,1,1,"c.PyObject_Del"],PyObject_DelAttr:[43,1,1,"c.PyObject_DelAttr"],PyObject_DelAttrString:[43,1,1,"c.PyObject_DelAttrString"],PyObject_DelItem:[43,1,1,"c.PyObject_DelItem"],PyObject_Dir:[43,1,1,"c.PyObject_Dir"],PyObject_Free:[37,1,1,"c.PyObject_Free"],PyObject_GC_Del:[24,1,1,"c.PyObject_GC_Del"],PyObject_GC_New:[24,1,1,"c.PyObject_GC_New"],PyObject_GC_NewVar:[24,1,1,"c.PyObject_GC_NewVar"],PyObject_GC_Resize:[24,1,1,"c.PyObject_GC_Resize"],PyObject_GC_Track:[24,1,1,"c.PyObject_GC_Track"],PyObject_GC_UnTrack:[24,1,1,"c.PyObject_GC_UnTrack"],PyObject_GenericGetAttr:[43,1,1,"c.PyObject_GenericGetAttr"],PyObject_GenericSetAttr:[43,1,1,"c.PyObject_GenericSetAttr"],PyObject_GetAttr:[43,1,1,"c.PyObject_GetAttr"],PyObject_GetAttrString:[43,1,1,"c.PyObject_GetAttrString"],PyObject_GetBuffer:[6,1,1,"c.PyObject_GetBuffer"],PyObject_GetItem:[43,1,1,"c.PyObject_GetItem"],PyObject_GetIter:[43,1,1,"c.PyObject_GetIter"],PyObject_HEAD:[51,4,1,"c.PyObject_HEAD"],PyObject_HEAD_INIT:[51,4,1,"c.PyObject_HEAD_INIT"],PyObject_HasAttr:[43,1,1,"c.PyObject_HasAttr"],PyObject_HasAttrString:[43,1,1,"c.PyObject_HasAttrString"],PyObject_Hash:[43,1,1,"c.PyObject_Hash"],PyObject_HashNotImplemented:[43,1,1,"c.PyObject_HashNotImplemented"],PyObject_Init:[3,1,1,"c.PyObject_Init"],PyObject_InitVar:[3,1,1,"c.PyObject_InitVar"],PyObject_IsInstance:[43,1,1,"c.PyObject_IsInstance"],PyObject_IsSubclass:[43,1,1,"c.PyObject_IsSubclass"],PyObject_IsTrue:[43,1,1,"c.PyObject_IsTrue"],PyObject_Length:[43,1,1,"c.PyObject_Length"],PyObject_Malloc:[37,1,1,"c.PyObject_Malloc"],PyObject_New:[3,1,1,"c.PyObject_New"],PyObject_NewVar:[3,1,1,"c.PyObject_NewVar"],PyObject_Not:[43,1,1,"c.PyObject_Not"],PyObject_Print:[43,1,1,"c.PyObject_Print"],PyObject_Realloc:[37,1,1,"c.PyObject_Realloc"],PyObject_Repr:[43,1,1,"c.PyObject_Repr"],PyObject_RichCompare:[43,1,1,"c.PyObject_RichCompare"],PyObject_RichCompareBool:[43,1,1,"c.PyObject_RichCompareBool"],PyObject_SetAttr:[43,1,1,"c.PyObject_SetAttr"],PyObject_SetAttrString:[43,1,1,"c.PyObject_SetAttrString"],PyObject_SetItem:[43,1,1,"c.PyObject_SetItem"],PyObject_Size:[43,1,1,"c.PyObject_Size"],PyObject_Str:[43,1,1,"c.PyObject_Str"],PyObject_Type:[43,1,1,"c.PyObject_Type"],PyObject_TypeCheck:[43,1,1,"c.PyObject_TypeCheck"],PyObject_Unicode:[43,1,1,"c.PyObject_Unicode"],PyObject_VAR_HEAD:[51,4,1,"c.PyObject_VAR_HEAD"],PyParser_SimpleParseFile:[58,1,1,"c.PyParser_SimpleParseFile"],PyParser_SimpleParseFileFlags:[58,1,1,"c.PyParser_SimpleParseFileFlags"],PyParser_SimpleParseString:[58,1,1,"c.PyParser_SimpleParseString"],PyParser_SimpleParseStringFlags:[58,1,1,"c.PyParser_SimpleParseStringFlags"],PyParser_SimpleParseStringFlagsFilename:[58,1,1,"c.PyParser_SimpleParseStringFlagsFilename"],PyProperty_Type:[18,0,1,"c.PyProperty_Type"],PyRun_AnyFile:[58,1,1,"c.PyRun_AnyFile"],PyRun_AnyFileEx:[58,1,1,"c.PyRun_AnyFileEx"],PyRun_AnyFileExFlags:[58,1,1,"c.PyRun_AnyFileExFlags"],PyRun_AnyFileFlags:[58,1,1,"c.PyRun_AnyFileFlags"],PyRun_File:[58,1,1,"c.PyRun_File"],PyRun_FileEx:[58,1,1,"c.PyRun_FileEx"],PyRun_FileExFlags:[58,1,1,"c.PyRun_FileExFlags"],PyRun_FileFlags:[58,1,1,"c.PyRun_FileFlags"],PyRun_InteractiveLoop:[58,1,1,"c.PyRun_InteractiveLoop"],PyRun_InteractiveLoopFlags:[58,1,1,"c.PyRun_InteractiveLoopFlags"],PyRun_InteractiveOne:[58,1,1,"c.PyRun_InteractiveOne"],PyRun_InteractiveOneFlags:[58,1,1,"c.PyRun_InteractiveOneFlags"],PyRun_SimpleFile:[58,1,1,"c.PyRun_SimpleFile"],PyRun_SimpleFileEx:[58,1,1,"c.PyRun_SimpleFileEx"],PyRun_SimpleFileExFlags:[58,1,1,"c.PyRun_SimpleFileExFlags"],PyRun_SimpleFileFlags:[58,1,1,"c.PyRun_SimpleFileFlags"],PyRun_SimpleString:[58,1,1,"c.PyRun_SimpleString"],PyRun_SimpleStringFlags:[58,1,1,"c.PyRun_SimpleStringFlags"],PyRun_String:[58,1,1,"c.PyRun_String"],PyRun_StringFlags:[58,1,1,"c.PyRun_StringFlags"],PySeqIter_Check:[32,1,1,"c.PySeqIter_Check"],PySeqIter_New:[32,1,1,"c.PySeqIter_New"],PySeqIter_Type:[32,0,1,"c.PySeqIter_Type"],PySequenceMethods:[55,2,1,"c.PySequenceMethods"],PySequence_Check:[47,1,1,"c.PySequence_Check"],PySequence_Concat:[47,1,1,"c.PySequence_Concat"],PySequence_Contains:[47,1,1,"c.PySequence_Contains"],PySequence_Count:[47,1,1,"c.PySequence_Count"],PySequence_DelItem:[47,1,1,"c.PySequence_DelItem"],PySequence_DelSlice:[47,1,1,"c.PySequence_DelSlice"],PySequence_Fast:[47,1,1,"c.PySequence_Fast"],PySequence_Fast_GET_ITEM:[47,1,1,"c.PySequence_Fast_GET_ITEM"],PySequence_Fast_GET_SIZE:[47,1,1,"c.PySequence_Fast_GET_SIZE"],PySequence_Fast_ITEMS:[47,1,1,"c.PySequence_Fast_ITEMS"],PySequence_GetItem:[47,1,1,"c.PySequence_GetItem"],PySequence_GetSlice:[47,1,1,"c.PySequence_GetSlice"],PySequence_ITEM:[47,1,1,"c.PySequence_ITEM"],PySequence_InPlaceConcat:[47,1,1,"c.PySequence_InPlaceConcat"],PySequence_InPlaceRepeat:[47,1,1,"c.PySequence_InPlaceRepeat"],PySequence_Index:[47,1,1,"c.PySequence_Index"],PySequence_Length:[47,1,1,"c.PySequence_Length"],PySequence_List:[47,1,1,"c.PySequence_List"],PySequence_Repeat:[47,1,1,"c.PySequence_Repeat"],PySequence_SetItem:[47,1,1,"c.PySequence_SetItem"],PySequence_SetSlice:[47,1,1,"c.PySequence_SetSlice"],PySequence_Size:[47,1,1,"c.PySequence_Size"],PySequence_Tuple:[47,1,1,"c.PySequence_Tuple"],PySetObject:[48,2,1,"c.PySetObject"],PySet_Add:[48,1,1,"c.PySet_Add"],PySet_Check:[48,1,1,"c.PySet_Check"],PySet_Clear:[48,1,1,"c.PySet_Clear"],PySet_Contains:[48,1,1,"c.PySet_Contains"],PySet_Discard:[48,1,1,"c.PySet_Discard"],PySet_GET_SIZE:[48,1,1,"c.PySet_GET_SIZE"],PySet_New:[48,1,1,"c.PySet_New"],PySet_Pop:[48,1,1,"c.PySet_Pop"],PySet_Size:[48,1,1,"c.PySet_Size"],PySet_Type:[48,0,1,"c.PySet_Type"],PySignal_SetWakeupFd:[20,1,1,"c.PySignal_SetWakeupFd"],PySlice_Check:[49,1,1,"c.PySlice_Check"],PySlice_GetIndices:[49,1,1,"c.PySlice_GetIndices"],PySlice_GetIndicesEx:[49,1,1,"c.PySlice_GetIndicesEx"],PySlice_New:[49,1,1,"c.PySlice_New"],PySlice_Type:[49,0,1,"c.PySlice_Type"],PyStringObject:[50,2,1,"c.PyStringObject"],PyString_AS_STRING:[50,1,1,"c.PyString_AS_STRING"],PyString_AsDecodedObject:[50,1,1,"c.PyString_AsDecodedObject"],PyString_AsEncodedObject:[50,1,1,"c.PyString_AsEncodedObject"],PyString_AsString:[50,1,1,"c.PyString_AsString"],PyString_AsStringAndSize:[50,1,1,"c.PyString_AsStringAndSize"],PyString_Check:[50,1,1,"c.PyString_Check"],PyString_CheckExact:[50,1,1,"c.PyString_CheckExact"],PyString_Concat:[50,1,1,"c.PyString_Concat"],PyString_ConcatAndDel:[50,1,1,"c.PyString_ConcatAndDel"],PyString_Decode:[50,1,1,"c.PyString_Decode"],PyString_Encode:[50,1,1,"c.PyString_Encode"],PyString_Format:[50,1,1,"c.PyString_Format"],PyString_FromFormat:[50,1,1,"c.PyString_FromFormat"],PyString_FromFormatV:[50,1,1,"c.PyString_FromFormatV"],PyString_FromString:[50,1,1,"c.PyString_FromString"],PyString_FromStringAndSize:[50,1,1,"c.PyString_FromStringAndSize"],PyString_GET_SIZE:[50,1,1,"c.PyString_GET_SIZE"],PyString_InternFromString:[50,1,1,"c.PyString_InternFromString"],PyString_InternInPlace:[50,1,1,"c.PyString_InternInPlace"],PyString_Size:[50,1,1,"c.PyString_Size"],PyString_Type:[50,0,1,"c.PyString_Type"],PySys_AddWarnOption:[52,1,1,"c.PySys_AddWarnOption"],PySys_GetFile:[52,1,1,"c.PySys_GetFile"],PySys_GetObject:[52,1,1,"c.PySys_GetObject"],PySys_ResetWarnOptions:[52,1,1,"c.PySys_ResetWarnOptions"],PySys_SetArgv:[28,1,1,"c.PySys_SetArgv"],PySys_SetArgvEx:[28,1,1,"c.PySys_SetArgvEx"],PySys_SetObject:[52,1,1,"c.PySys_SetObject"],PySys_SetPath:[52,1,1,"c.PySys_SetPath"],PySys_WriteStderr:[52,1,1,"c.PySys_WriteStderr"],PySys_WriteStdout:[52,1,1,"c.PySys_WriteStdout"],PyTZInfo_Check:[17,1,1,"c.PyTZInfo_Check"],PyTZInfo_CheckExact:[17,1,1,"c.PyTZInfo_CheckExact"],PyThreadState:[28,2,1,"c.PyThreadState"],PyThreadState_Clear:[28,1,1,"c.PyThreadState_Clear"],PyThreadState_Delete:[28,1,1,"c.PyThreadState_Delete"],PyThreadState_Get:[28,1,1,"c.PyThreadState_Get"],PyThreadState_GetDict:[28,1,1,"c.PyThreadState_GetDict"],PyThreadState_New:[28,1,1,"c.PyThreadState_New"],PyThreadState_Next:[28,1,1,"c.PyThreadState_Next"],PyThreadState_SetAsyncExc:[28,1,1,"c.PyThreadState_SetAsyncExc"],PyThreadState_Swap:[28,1,1,"c.PyThreadState_Swap"],PyTime_Check:[17,1,1,"c.PyTime_Check"],PyTime_CheckExact:[17,1,1,"c.PyTime_CheckExact"],PyTime_FromTime:[17,1,1,"c.PyTime_FromTime"],PyTrace_CALL:[28,0,1,"c.PyTrace_CALL"],PyTrace_C_CALL:[28,0,1,"c.PyTrace_C_CALL"],PyTrace_C_EXCEPTION:[28,0,1,"c.PyTrace_C_EXCEPTION"],PyTrace_C_RETURN:[28,0,1,"c.PyTrace_C_RETURN"],PyTrace_EXCEPTION:[28,0,1,"c.PyTrace_EXCEPTION"],PyTrace_LINE:[28,0,1,"c.PyTrace_LINE"],PyTrace_RETURN:[28,0,1,"c.PyTrace_RETURN"],PyTupleObject:[53,2,1,"c.PyTupleObject"],PyTuple_Check:[53,1,1,"c.PyTuple_Check"],PyTuple_CheckExact:[53,1,1,"c.PyTuple_CheckExact"],PyTuple_ClearFreeList:[53,1,1,"c.PyTuple_ClearFreeList"],PyTuple_GET_ITEM:[53,1,1,"c.PyTuple_GET_ITEM"],PyTuple_GET_SIZE:[53,1,1,"c.PyTuple_GET_SIZE"],PyTuple_GetItem:[53,1,1,"c.PyTuple_GetItem"],PyTuple_GetSlice:[53,1,1,"c.PyTuple_GetSlice"],PyTuple_New:[53,1,1,"c.PyTuple_New"],PyTuple_Pack:[53,1,1,"c.PyTuple_Pack"],PyTuple_SET_ITEM:[53,1,1,"c.PyTuple_SET_ITEM"],PyTuple_SetItem:[53,1,1,"c.PyTuple_SetItem"],PyTuple_Size:[53,1,1,"c.PyTuple_Size"],PyTuple_Type:[53,0,1,"c.PyTuple_Type"],PyTypeObject:[54,2,1,"c.PyTypeObject"],PyType_Check:[54,1,1,"c.PyType_Check"],PyType_CheckExact:[54,1,1,"c.PyType_CheckExact"],PyType_ClearCache:[54,1,1,"c.PyType_ClearCache"],PyType_GenericAlloc:[54,1,1,"c.PyType_GenericAlloc"],PyType_GenericNew:[54,1,1,"c.PyType_GenericNew"],PyType_HasFeature:[54,1,1,"c.PyType_HasFeature"],PyType_IS_GC:[54,1,1,"c.PyType_IS_GC"],PyType_IsSubtype:[54,1,1,"c.PyType_IsSubtype"],PyType_Modified:[54,1,1,"c.PyType_Modified"],PyType_Ready:[54,1,1,"c.PyType_Ready"],PyType_Type:[54,0,1,"c.PyType_Type"],PyUnicodeDecodeError_Create:[20,1,1,"c.PyUnicodeDecodeError_Create"],PyUnicodeDecodeError_GetEncoding:[20,1,1,"c.PyUnicodeDecodeError_GetEncoding"],PyUnicodeDecodeError_GetEnd:[20,1,1,"c.PyUnicodeDecodeError_GetEnd"],PyUnicodeDecodeError_GetObject:[20,1,1,"c.PyUnicodeDecodeError_GetObject"],PyUnicodeDecodeError_GetReason:[20,1,1,"c.PyUnicodeDecodeError_GetReason"],PyUnicodeDecodeError_GetStart:[20,1,1,"c.PyUnicodeDecodeError_GetStart"],PyUnicodeDecodeError_SetEnd:[20,1,1,"c.PyUnicodeDecodeError_SetEnd"],PyUnicodeDecodeError_SetReason:[20,1,1,"c.PyUnicodeDecodeError_SetReason"],PyUnicodeDecodeError_SetStart:[20,1,1,"c.PyUnicodeDecodeError_SetStart"],PyUnicodeEncodeError_Create:[20,1,1,"c.PyUnicodeEncodeError_Create"],PyUnicodeEncodeError_GetEncoding:[20,1,1,"c.PyUnicodeEncodeError_GetEncoding"],PyUnicodeEncodeError_GetEnd:[20,1,1,"c.PyUnicodeEncodeError_GetEnd"],PyUnicodeEncodeError_GetObject:[20,1,1,"c.PyUnicodeEncodeError_GetObject"],PyUnicodeEncodeError_GetReason:[20,1,1,"c.PyUnicodeEncodeError_GetReason"],PyUnicodeEncodeError_GetStart:[20,1,1,"c.PyUnicodeEncodeError_GetStart"],PyUnicodeEncodeError_SetEnd:[20,1,1,"c.PyUnicodeEncodeError_SetEnd"],PyUnicodeEncodeError_SetReason:[20,1,1,"c.PyUnicodeEncodeError_SetReason"],PyUnicodeEncodeError_SetStart:[20,1,1,"c.PyUnicodeEncodeError_SetStart"],PyUnicodeObject:[56,2,1,"c.PyUnicodeObject"],PyUnicodeTranslateError_Create:[20,1,1,"c.PyUnicodeTranslateError_Create"],PyUnicodeTranslateError_GetEnd:[20,1,1,"c.PyUnicodeTranslateError_GetEnd"],PyUnicodeTranslateError_GetObject:[20,1,1,"c.PyUnicodeTranslateError_GetObject"],PyUnicodeTranslateError_GetReason:[20,1,1,"c.PyUnicodeTranslateError_GetReason"],PyUnicodeTranslateError_GetStart:[20,1,1,"c.PyUnicodeTranslateError_GetStart"],PyUnicodeTranslateError_SetEnd:[20,1,1,"c.PyUnicodeTranslateError_SetEnd"],PyUnicodeTranslateError_SetReason:[20,1,1,"c.PyUnicodeTranslateError_SetReason"],PyUnicodeTranslateError_SetStart:[20,1,1,"c.PyUnicodeTranslateError_SetStart"],PyUnicode_AS_DATA:[56,1,1,"c.PyUnicode_AS_DATA"],PyUnicode_AS_UNICODE:[56,1,1,"c.PyUnicode_AS_UNICODE"],PyUnicode_AsASCIIString:[56,1,1,"c.PyUnicode_AsASCIIString"],PyUnicode_AsCharmapString:[56,1,1,"c.PyUnicode_AsCharmapString"],PyUnicode_AsEncodedString:[56,1,1,"c.PyUnicode_AsEncodedString"],PyUnicode_AsLatin1String:[56,1,1,"c.PyUnicode_AsLatin1String"],PyUnicode_AsMBCSString:[56,1,1,"c.PyUnicode_AsMBCSString"],PyUnicode_AsRawUnicodeEscapeString:[56,1,1,"c.PyUnicode_AsRawUnicodeEscapeString"],PyUnicode_AsUTF16String:[56,1,1,"c.PyUnicode_AsUTF16String"],PyUnicode_AsUTF32String:[56,1,1,"c.PyUnicode_AsUTF32String"],PyUnicode_AsUTF8String:[56,1,1,"c.PyUnicode_AsUTF8String"],PyUnicode_AsUnicode:[56,1,1,"c.PyUnicode_AsUnicode"],PyUnicode_AsUnicodeEscapeString:[56,1,1,"c.PyUnicode_AsUnicodeEscapeString"],PyUnicode_AsWideChar:[56,1,1,"c.PyUnicode_AsWideChar"],PyUnicode_Check:[56,1,1,"c.PyUnicode_Check"],PyUnicode_CheckExact:[56,1,1,"c.PyUnicode_CheckExact"],PyUnicode_ClearFreeList:[56,1,1,"c.PyUnicode_ClearFreeList"],PyUnicode_Compare:[56,1,1,"c.PyUnicode_Compare"],PyUnicode_Concat:[56,1,1,"c.PyUnicode_Concat"],PyUnicode_Contains:[56,1,1,"c.PyUnicode_Contains"],PyUnicode_Count:[56,1,1,"c.PyUnicode_Count"],PyUnicode_Decode:[56,1,1,"c.PyUnicode_Decode"],PyUnicode_DecodeASCII:[56,1,1,"c.PyUnicode_DecodeASCII"],PyUnicode_DecodeCharmap:[56,1,1,"c.PyUnicode_DecodeCharmap"],PyUnicode_DecodeLatin1:[56,1,1,"c.PyUnicode_DecodeLatin1"],PyUnicode_DecodeMBCS:[56,1,1,"c.PyUnicode_DecodeMBCS"],PyUnicode_DecodeMBCSStateful:[56,1,1,"c.PyUnicode_DecodeMBCSStateful"],PyUnicode_DecodeRawUnicodeEscape:[56,1,1,"c.PyUnicode_DecodeRawUnicodeEscape"],PyUnicode_DecodeUTF16:[56,1,1,"c.PyUnicode_DecodeUTF16"],PyUnicode_DecodeUTF16Stateful:[56,1,1,"c.PyUnicode_DecodeUTF16Stateful"],PyUnicode_DecodeUTF32:[56,1,1,"c.PyUnicode_DecodeUTF32"],PyUnicode_DecodeUTF32Stateful:[56,1,1,"c.PyUnicode_DecodeUTF32Stateful"],PyUnicode_DecodeUTF7:[56,1,1,"c.PyUnicode_DecodeUTF7"],PyUnicode_DecodeUTF7Stateful:[56,1,1,"c.PyUnicode_DecodeUTF7Stateful"],PyUnicode_DecodeUTF8:[56,1,1,"c.PyUnicode_DecodeUTF8"],PyUnicode_DecodeUTF8Stateful:[56,1,1,"c.PyUnicode_DecodeUTF8Stateful"],PyUnicode_DecodeUnicodeEscape:[56,1,1,"c.PyUnicode_DecodeUnicodeEscape"],PyUnicode_Encode:[56,1,1,"c.PyUnicode_Encode"],PyUnicode_EncodeASCII:[56,1,1,"c.PyUnicode_EncodeASCII"],PyUnicode_EncodeCharmap:[56,1,1,"c.PyUnicode_EncodeCharmap"],PyUnicode_EncodeLatin1:[56,1,1,"c.PyUnicode_EncodeLatin1"],PyUnicode_EncodeMBCS:[56,1,1,"c.PyUnicode_EncodeMBCS"],PyUnicode_EncodeRawUnicodeEscape:[56,1,1,"c.PyUnicode_EncodeRawUnicodeEscape"],PyUnicode_EncodeUTF16:[56,1,1,"c.PyUnicode_EncodeUTF16"],PyUnicode_EncodeUTF32:[56,1,1,"c.PyUnicode_EncodeUTF32"],PyUnicode_EncodeUTF7:[56,1,1,"c.PyUnicode_EncodeUTF7"],PyUnicode_EncodeUTF8:[56,1,1,"c.PyUnicode_EncodeUTF8"],PyUnicode_EncodeUnicodeEscape:[56,1,1,"c.PyUnicode_EncodeUnicodeEscape"],PyUnicode_Find:[56,1,1,"c.PyUnicode_Find"],PyUnicode_Format:[56,1,1,"c.PyUnicode_Format"],PyUnicode_FromEncodedObject:[56,1,1,"c.PyUnicode_FromEncodedObject"],PyUnicode_FromFormat:[56,1,1,"c.PyUnicode_FromFormat"],PyUnicode_FromFormatV:[56,1,1,"c.PyUnicode_FromFormatV"],PyUnicode_FromObject:[56,1,1,"c.PyUnicode_FromObject"],PyUnicode_FromString:[56,1,1,"c.PyUnicode_FromString"],PyUnicode_FromStringAndSize:[56,1,1,"c.PyUnicode_FromStringAndSize"],PyUnicode_FromUnicode:[56,1,1,"c.PyUnicode_FromUnicode"],PyUnicode_FromWideChar:[56,1,1,"c.PyUnicode_FromWideChar"],PyUnicode_GET_DATA_SIZE:[56,1,1,"c.PyUnicode_GET_DATA_SIZE"],PyUnicode_GET_SIZE:[56,1,1,"c.PyUnicode_GET_SIZE"],PyUnicode_GetSize:[56,1,1,"c.PyUnicode_GetSize"],PyUnicode_Join:[56,1,1,"c.PyUnicode_Join"],PyUnicode_Replace:[56,1,1,"c.PyUnicode_Replace"],PyUnicode_RichCompare:[56,1,1,"c.PyUnicode_RichCompare"],PyUnicode_Split:[56,1,1,"c.PyUnicode_Split"],PyUnicode_Splitlines:[56,1,1,"c.PyUnicode_Splitlines"],PyUnicode_Tailmatch:[56,1,1,"c.PyUnicode_Tailmatch"],PyUnicode_Translate:[56,1,1,"c.PyUnicode_Translate"],PyUnicode_TranslateCharmap:[56,1,1,"c.PyUnicode_TranslateCharmap"],PyUnicode_Type:[56,0,1,"c.PyUnicode_Type"],PyVarObject:[51,2,1,"c.PyVarObject"],PyVarObject_HEAD_INIT:[51,4,1,"c.PyVarObject_HEAD_INIT"],PyWeakref_Check:[59,1,1,"c.PyWeakref_Check"],PyWeakref_CheckProxy:[59,1,1,"c.PyWeakref_CheckProxy"],PyWeakref_CheckRef:[59,1,1,"c.PyWeakref_CheckRef"],PyWeakref_GET_OBJECT:[59,1,1,"c.PyWeakref_GET_OBJECT"],PyWeakref_GetObject:[59,1,1,"c.PyWeakref_GetObject"],PyWeakref_NewProxy:[59,1,1,"c.PyWeakref_NewProxy"],PyWeakref_NewRef:[59,1,1,"c.PyWeakref_NewRef"],PyWrapper_New:[18,1,1,"c.PyWrapper_New"],Py_AddPendingCall:[28,1,1,"c.Py_AddPendingCall"],Py_AtExit:[52,1,1,"c.Py_AtExit"],Py_BEGIN_ALLOW_THREADS:[28,4,1,"c.Py_BEGIN_ALLOW_THREADS"],Py_BLOCK_THREADS:[28,4,1,"c.Py_BLOCK_THREADS"],Py_BuildValue:[4,1,1,"c.Py_BuildValue"],Py_CLEAR:[45,1,1,"c.Py_CLEAR"],Py_CompileString:[58,1,1,"c.Py_CompileString"],Py_CompileStringFlags:[58,1,1,"c.Py_CompileStringFlags"],Py_DECREF:[45,1,1,"c.Py_DECREF"],Py_END_ALLOW_THREADS:[28,4,1,"c.Py_END_ALLOW_THREADS"],Py_END_OF_BUFFER:[6,0,1,"c.Py_END_OF_BUFFER"],Py_Ellipsis:[49,0,1,"c.Py_Ellipsis"],Py_EndInterpreter:[28,1,1,"c.Py_EndInterpreter"],Py_EnterRecursiveCall:[20,1,1,"c.Py_EnterRecursiveCall"],Py_Exit:[52,1,1,"c.Py_Exit"],Py_False:[5,0,1,"c.Py_False"],Py_FatalError:[52,1,1,"c.Py_FatalError"],Py_FdIsInteractive:[52,1,1,"c.Py_FdIsInteractive"],Py_Finalize:[28,1,1,"c.Py_Finalize"],Py_FindMethod:[51,1,1,"c.Py_FindMethod"],Py_GetBuildInfo:[28,1,1,"c.Py_GetBuildInfo"],Py_GetCompiler:[28,1,1,"c.Py_GetCompiler"],Py_GetCopyright:[28,1,1,"c.Py_GetCopyright"],Py_GetExecPrefix:[28,1,1,"c.Py_GetExecPrefix"],Py_GetPath:[28,1,1,"c.Py_GetPath"],Py_GetPlatform:[28,1,1,"c.Py_GetPlatform"],Py_GetPrefix:[28,1,1,"c.Py_GetPrefix"],Py_GetProgramFullPath:[28,1,1,"c.Py_GetProgramFullPath"],Py_GetProgramName:[28,1,1,"c.Py_GetProgramName"],Py_GetPythonHome:[28,1,1,"c.Py_GetPythonHome"],Py_GetVersion:[28,1,1,"c.Py_GetVersion"],Py_INCREF:[45,1,1,"c.Py_INCREF"],Py_InitModule3:[3,1,1,"c.Py_InitModule3"],Py_InitModule4:[3,1,1,"c.Py_InitModule4"],Py_InitModule:[3,1,1,"c.Py_InitModule"],Py_Initialize:[28,1,1,"c.Py_Initialize"],Py_InitializeEx:[28,1,1,"c.Py_InitializeEx"],Py_IsInitialized:[28,1,1,"c.Py_IsInitialized"],Py_LeaveRecursiveCall:[20,1,1,"c.Py_LeaveRecursiveCall"],Py_Main:[58,1,1,"c.Py_Main"],Py_NewInterpreter:[28,1,1,"c.Py_NewInterpreter"],Py_None:[40,0,1,"c.Py_None"],Py_REFCNT:[51,4,1,"c.Py_REFCNT"],Py_RETURN_FALSE:[5,4,1,"c.Py_RETURN_FALSE"],Py_RETURN_NONE:[40,4,1,"c.Py_RETURN_NONE"],Py_RETURN_TRUE:[5,4,1,"c.Py_RETURN_TRUE"],Py_SIZE:[51,4,1,"c.Py_SIZE"],Py_SetProgramName:[28,1,1,"c.Py_SetProgramName"],Py_SetPythonHome:[28,1,1,"c.Py_SetPythonHome"],Py_TPFLAGS_BASETYPE:[55,11,1,""],Py_TPFLAGS_CHECKTYPES:[55,11,1,""],Py_TPFLAGS_DEFAULT:[55,11,1,""],Py_TPFLAGS_GC:[55,11,1,""],Py_TPFLAGS_HAVE_CLASS:[55,11,1,""],Py_TPFLAGS_HAVE_GC:[55,11,1,""],Py_TPFLAGS_HAVE_GETCHARBUFFER:[55,11,1,""],Py_TPFLAGS_HAVE_INPLACEOPS:[55,11,1,""],Py_TPFLAGS_HAVE_ITER:[55,11,1,""],Py_TPFLAGS_HAVE_RICHCOMPARE:[55,11,1,""],Py_TPFLAGS_HAVE_SEQUENCE_IN:[55,11,1,""],Py_TPFLAGS_HAVE_WEAKREFS:[55,11,1,""],Py_TPFLAGS_HEAPTYPE:[55,11,1,""],Py_TPFLAGS_READY:[55,11,1,""],Py_TPFLAGS_READYING:[55,11,1,""],Py_TYPE:[51,4,1,"c.Py_TYPE"],Py_True:[5,0,1,"c.Py_True"],Py_UNBLOCK_THREADS:[28,4,1,"c.Py_UNBLOCK_THREADS"],Py_UNICODE:[56,2,1,"c.Py_UNICODE"],Py_UNICODE_ISALNUM:[56,1,1,"c.Py_UNICODE_ISALNUM"],Py_UNICODE_ISALPHA:[56,1,1,"c.Py_UNICODE_ISALPHA"],Py_UNICODE_ISDECIMAL:[56,1,1,"c.Py_UNICODE_ISDECIMAL"],Py_UNICODE_ISDIGIT:[56,1,1,"c.Py_UNICODE_ISDIGIT"],Py_UNICODE_ISLINEBREAK:[56,1,1,"c.Py_UNICODE_ISLINEBREAK"],Py_UNICODE_ISLOWER:[56,1,1,"c.Py_UNICODE_ISLOWER"],Py_UNICODE_ISNUMERIC:[56,1,1,"c.Py_UNICODE_ISNUMERIC"],Py_UNICODE_ISSPACE:[56,1,1,"c.Py_UNICODE_ISSPACE"],Py_UNICODE_ISTITLE:[56,1,1,"c.Py_UNICODE_ISTITLE"],Py_UNICODE_ISUPPER:[56,1,1,"c.Py_UNICODE_ISUPPER"],Py_UNICODE_TODECIMAL:[56,1,1,"c.Py_UNICODE_TODECIMAL"],Py_UNICODE_TODIGIT:[56,1,1,"c.Py_UNICODE_TODIGIT"],Py_UNICODE_TOLOWER:[56,1,1,"c.Py_UNICODE_TOLOWER"],Py_UNICODE_TONUMERIC:[56,1,1,"c.Py_UNICODE_TONUMERIC"],Py_UNICODE_TOTITLE:[56,1,1,"c.Py_UNICODE_TOTITLE"],Py_UNICODE_TOUPPER:[56,1,1,"c.Py_UNICODE_TOUPPER"],Py_VISIT:[24,1,1,"c.Py_VISIT"],Py_VaBuildValue:[4,1,1,"c.Py_VaBuildValue"],Py_XDECREF:[45,1,1,"c.Py_XDECREF"],Py_XINCREF:[45,1,1,"c.Py_XINCREF"],Py_buffer:[6,2,1,"c.Py_buffer"],Py_complex:[14,2,1,"c.Py_complex"],Py_eval_input:[58,0,1,"c.Py_eval_input"],Py_file_input:[58,0,1,"c.Py_file_input"],Py_single_input:[58,0,1,"c.Py_single_input"],Py_tracefunc:[28,2,1,"c.Py_tracefunc"],Queue:[330,5,0,"-"],RAISE_VARARGS:[182,14,1,"-"],RETURN_VALUE:[182,14,1,"-"],ROT_FOUR:[182,14,1,"-"],ROT_THREE:[182,14,1,"-"],ROT_TWO:[182,14,1,"-"],SETUP_EXCEPT:[182,14,1,"-"],SETUP_FINALLY:[182,14,1,"-"],SETUP_LOOP:[182,14,1,"-"],SETUP_WITH:[182,14,1,"-"],SET_LINENO:[182,14,1,"-"],STOP_CODE:[182,14,1,"-"],STORE_ATTR:[182,14,1,"-"],STORE_DEREF:[182,14,1,"-"],STORE_FAST:[182,14,1,"-"],STORE_GLOBAL:[182,14,1,"-"],STORE_MAP:[182,14,1,"-"],STORE_NAME:[182,14,1,"-"],STORE_SUBSCR:[182,14,1,"-"],SUNAUDIODEV:[377,5,0,"-"],ScrolledText:[344,5,0,"-"],SimpleHTTPServer:[354,5,0,"-"],SimpleXMLRPCServer:[355,5,0,"-"],SocketServer:[361,5,0,"-"],StringIO:[370,5,0,"-"],Tix:[394,5,0,"-"],Tkinter:[396,5,0,"-"],True:[159,11,1,""],UNARY_CONVERT:[182,14,1,"-"],UNARY_INVERT:[182,14,1,"-"],UNARY_NEGATIVE:[182,14,1,"-"],UNARY_NOT:[182,14,1,"-"],UNARY_POSITIVE:[182,14,1,"-"],UNPACK_SEQUENCE:[182,14,1,"-"],UserDict:[413,5,0,"-"],UserList:[413,5,0,"-"],UserString:[413,5,0,"-"],W:[405,5,0,"-"],WITH_CLEANUP:[182,14,1,"-"],YIELD_VALUE:[182,14,1,"-"],_PyImport_FindExtension:[26,1,1,"c._PyImport_FindExtension"],_PyImport_Fini:[26,1,1,"c._PyImport_Fini"],_PyImport_FixupExtension:[26,1,1,"c._PyImport_FixupExtension"],_PyImport_Init:[26,1,1,"c._PyImport_Init"],_PyObject_Del:[3,1,1,"c._PyObject_Del"],_PyObject_GC_TRACK:[24,1,1,"c._PyObject_GC_TRACK"],_PyObject_GC_UNTRACK:[24,1,1,"c._PyObject_GC_UNTRACK"],_PyObject_New:[3,1,1,"c._PyObject_New"],_PyObject_NewVar:[3,1,1,"c._PyObject_NewVar"],_PyString_Resize:[50,1,1,"c._PyString_Resize"],_PyTuple_Resize:[53,1,1,"c._PyTuple_Resize"],_Py_NoneStruct:[3,0,1,"c._Py_NoneStruct"],_Py_c_diff:[14,1,1,"c._Py_c_diff"],_Py_c_neg:[14,1,1,"c._Py_c_neg"],_Py_c_pow:[14,1,1,"c._Py_c_pow"],_Py_c_prod:[14,1,1,"c._Py_c_prod"],_Py_c_quot:[14,1,1,"c._Py_c_quot"],_Py_c_sum:[14,1,1,"c._Py_c_sum"],__builtin__:[110,5,0,"-"],__debug__:[159,11,1,""],__future__:[111,5,0,"-"],__import__:[222,9,1,""],__main__:[112,5,0,"-"],__metaclass__:[440,11,1,""],__slots__:[440,11,1,""],_frozen:[26,2,1,"c._frozen"],_inittab:[26,2,1,"c._inittab"],_winreg:[113,5,0,"-"],abc:[114,5,0,"-"],abs:[222,9,1,""],aepack:[115,5,0,"-"],aetools:[116,5,0,"-"],aetypes:[117,5,0,"-"],aifc:[118,5,0,"-"],al:[119,5,0,"-"],all:[222,9,1,""],any:[222,9,1,""],anydbm:[121,5,0,"-"],applesingle:[405,5,0,"-"],apply:[109,16,1,"-"],argparse:[123,5,0,"-"],array:[124,5,0,"-"],asserts:[109,16,1,"-"],ast:[125,5,0,"-"],asynchat:[126,5,0,"-"],asyncore:[127,5,0,"-"],atexit:[128,5,0,"-"],audioop:[129,5,0,"-"],autoGIL:[130,5,0,"-"],base64:[131,5,0,"-"],basestring:[109,16,1,"-"],bdb:[134,5,0,"-"],bin:[222,9,1,""],binascii:[135,5,0,"-"],binhex:[136,5,0,"-"],bisect:[137,5,0,"-"],bool:[222,6,1,""],bsddb:[138,5,0,"-"],buffer:[109,16,1,"-"],buildtools:[405,5,0,"-"],bytearray:[222,6,1,""],bz2:[139,5,0,"-"],cPickle:[311,5,0,"-"],cProfile:[322,5,0,"-"],cStringIO:[370,5,0,"-"],calendar:[140,5,0,"-"],callable:[222,9,1,""],cd:[142,5,0,"-"],cfmfile:[405,5,0,"-"],cgi:[143,5,0,"-"],cgitb:[145,5,0,"-"],charbufferproc:[55,2,1,"c.charbufferproc"],chr:[222,9,1,""],chunk:[146,5,0,"-"],classmethod:[222,9,1,""],cmath:[147,5,0,"-"],cmd:[148,5,0,"-"],cmp:[222,9,1,""],code:[149,5,0,"-"],codecs:[150,5,0,"-"],codeop:[151,5,0,"-"],coerce:[222,9,1,""],collections:[152,5,0,"-"],colorsys:[154,5,0,"-"],commands:[155,5,0,"-"],compile:[222,9,1,""],compileall:[156,5,0,"-"],compiler:[157,5,0,"-"],complex:[222,6,1,""],contextlib:[160,5,0,"-"],cookielib:[162,5,0,"-"],copy:[163,5,0,"-"],copy_reg:[164,5,0,"-"],copyright:[159,11,1,""],create_shortcut:[64,9,1,""],credits:[159,11,1,""],crypt:[165,5,0,"-"],csv:[167,5,0,"-"],ctypes:[168,5,0,"-"],curses:[169,5,0,"-"],datetime:[174,5,0,"-"],dbhash:[175,5,0,"-"],dbm:[176,5,0,"-"],decimal:[178,5,0,"-"],delattr:[222,9,1,""],dict:[109,16,1,"-"],difflib:[180,5,0,"-"],dir:[222,9,1,""],dircache:[181,5,0,"-"],directory_created:[64,9,1,""],dis:[182,5,0,"-"],distutils:[184,5,0,"-"],divmod:[222,9,1,""],dl:[185,5,0,"-"],doctest:[186,5,0,"-"],dumbdbm:[188,5,0,"-"],dummy_thread:[189,5,0,"-"],dummy_threading:[190,5,0,"-"],email:[192,5,0,"-"],ensurepip:[204,5,0,"-"],enumerate:[222,9,1,""],errno:[205,5,0,"-"],eval:[222,9,1,""],except:[109,16,1,"-"],exceptions:[206,5,0,"-"],exec:[109,16,1,"-"],execfile:[109,16,1,"-"],exit:[159,11,1,""],exitfunc:[109,16,1,"-"],fcntl:[207,5,0,"-"],file:[222,9,1,""],file_created:[64,9,1,""],filecmp:[208,5,0,"-"],fileinput:[210,5,0,"-"],filter:[109,16,1,"-"],findertools:[271,5,0,"-"],fl:[212,5,0,"-"],flp:[212,5,0,"-"],fm:[213,5,0,"-"],fnmatch:[214,5,0,"-"],format:[222,9,1,""],formatter:[215,5,0,"-"],fpectl:[216,5,0,"-"],fpformat:[217,5,0,"-"],fractions:[218,5,0,"-"],frozenset:[368,6,1,""],ftplib:[221,5,0,"-"],funcattrs:[109,16,1,"-"],functools:[223,5,0,"-"],future:[109,16,1,"-"],future_builtins:[224,5,0,"-"],gc:[225,5,0,"-"],gdbm:[226,5,0,"-"],gensuitemodule:[227,5,0,"-"],get_special_folder_path:[64,9,1,""],getattr:[222,9,1,""],getcwdu:[109,16,1,"-"],getopt:[228,5,0,"-"],getpass:[229,5,0,"-"],gettext:[230,5,0,"-"],gl:[231,5,0,"-"],glob:[232,5,0,"-"],globals:[222,9,1,""],grp:[233,5,0,"-"],gzip:[234,5,0,"-"],has_key:[109,16,1,"-"],hasattr:[222,9,1,""],hash:[222,9,1,""],hashlib:[235,5,0,"-"],heapq:[236,5,0,"-"],help:[222,9,1,""],hex:[222,9,1,""],hmac:[237,5,0,"-"],hotshot:[238,5,0,"-"],htmlentitydefs:[239,5,0,"-"],htmllib:[239,5,0,"-"],httplib:[241,5,0,"-"],ic:[243,5,0,"-"],icopen:[405,5,0,"-"],id:[222,9,1,""],idioms:[109,16,1,"-"],imageop:[245,5,0,"-"],imaplib:[246,5,0,"-"],imgfile:[247,5,0,"-"],imghdr:[248,5,0,"-"],imp:[249,5,0,"-"],importlib:[250,5,0,"-"],imports2:[109,16,1,"-"],imports:[109,16,1,"-"],imputil:[251,5,0,"-"],input:[109,16,1,"-"],inquiry:[24,2,1,"c.inquiry"],inspect:[253,5,0,"-"],intern:[109,16,1,"-"],io:[256,5,0,"-"],isinstance:[109,16,1,"-"],issubclass:[222,9,1,""],iter:[222,9,1,""],itertools:[109,16,1,"-"],itertools_imports:[109,16,1,"-"],jpeg:[259,5,0,"-"],json:[260,5,0,"-"],keyword:[261,5,0,"-"],len:[222,9,1,""],lib2to3:[109,5,0,"-"],license:[159,11,1,""],linecache:[263,5,0,"-"],locale:[264,5,0,"-"],locals:[222,9,1,""],logging:[265,5,0,"-"],macerrors:[405,5,0,"-"],macostools:[271,5,0,"-"],macpath:[272,5,0,"-"],macresource:[405,5,0,"-"],mailbox:[273,5,0,"-"],mailcap:[274,5,0,"-"],map:[109,16,1,"-"],marshal:[276,5,0,"-"],math:[277,5,0,"-"],max:[222,9,1,""],md5:[278,5,0,"-"],memoryview:[368,6,1,""],metaclass:[109,16,1,"-"],methodattrs:[109,16,1,"-"],mhlib:[279,5,0,"-"],mimetools:[280,5,0,"-"],mimetypes:[281,5,0,"-"],mimify:[283,5,0,"-"],min:[222,9,1,""],mmap:[287,5,0,"-"],modulefinder:[288,5,0,"-"],msilib:[290,5,0,"-"],msvcrt:[291,5,0,"-"],multifile:[292,5,0,"-"],multiprocessing:[293,5,0,"-"],mutex:[294,5,0,"-"],ne:[109,16,1,"-"],netrc:[296,5,0,"-"],next:[109,16,1,"-"],nis:[298,5,0,"-"],nntplib:[299,5,0,"-"],nonzero:[109,16,1,"-"],numbers:[300,5,0,"-"],numliterals:[109,16,1,"-"],object:[222,6,1,""],oct:[222,9,1,""],open:[222,9,1,""],operator:[302,5,0,"-"],optparse:[303,5,0,"-"],ord:[222,9,1,""],os:[304,5,0,"-"],ossaudiodev:[306,5,0,"-"],paren:[109,16,1,"-"],parser:[308,5,0,"-"],pdb:[309,5,0,"-"],pickle:[311,5,0,"-"],pickletools:[312,5,0,"-"],pipes:[313,5,0,"-"],pkgutil:[314,5,0,"-"],platform:[315,5,0,"-"],plistlib:[316,5,0,"-"],popen2:[317,5,0,"-"],poplib:[318,5,0,"-"],posix:[319,5,0,"-"],posixfile:[320,5,0,"-"],pow:[222,9,1,""],pprint:[321,5,0,"-"],print:[109,16,1,"-"],profile:[322,5,0,"-"],property:[222,6,1,""],pstats:[322,5,0,"-"],pty:[323,5,0,"-"],pwd:[324,5,0,"-"],py_compile:[325,5,0,"-"],pyclbr:[326,5,0,"-"],pydoc:[327,5,0,"-"],quit:[159,11,1,""],quopri:[331,5,0,"-"],raise:[109,16,1,"-"],random:[332,5,0,"-"],range:[222,9,1,""],raw_input:[109,16,1,"-"],re:[333,5,0,"-"],readbufferproc:[55,2,1,"c.readbufferproc"],readline:[334,5,0,"-"],reduce:[109,16,1,"-"],reload:[222,9,1,""],renames:[109,16,1,"-"],repr:[109,16,1,"-"],resource:[336,5,0,"-"],reversed:[222,9,1,""],rexec:[338,5,0,"-"],rfc822:[339,5,0,"-"],rlcompleter:[340,5,0,"-"],robotparser:[341,5,0,"-"],round:[222,9,1,""],runpy:[342,5,0,"-"],sched:[343,5,0,"-"],segcountproc:[55,2,1,"c.segcountproc"],select:[345,5,0,"-"],set:[368,6,1,""],set_literal:[109,16,1,"-"],setattr:[222,9,1,""],sets:[346,5,0,"-"],sgmllib:[348,5,0,"-"],sha:[349,5,0,"-"],shelve:[350,5,0,"-"],shlex:[351,5,0,"-"],shutil:[352,5,0,"-"],signal:[353,5,0,"-"],site:[356,5,0,"-"],slice:[222,6,1,""],smtpd:[357,5,0,"-"],smtplib:[358,5,0,"-"],sndhdr:[359,5,0,"-"],socket:[360,5,0,"-"],sorted:[222,9,1,""],spwd:[363,5,0,"-"],sqlite3:[364,5,0,"-"],ssl:[365,5,0,"-"],standarderror:[109,16,1,"-"],stat:[366,5,0,"-"],staticmethod:[222,9,1,""],statvfs:[367,5,0,"-"],str:[222,6,1,""],string:[369,5,0,"-"],stringprep:[371,5,0,"-"],struct:[373,5,0,"-"],subprocess:[374,5,0,"-"],sum:[222,9,1,""],sunau:[376,5,0,"-"],sunaudiodev:[377,5,0,"-"],symbol:[378,5,0,"-"],symtable:[379,5,0,"-"],sys:[380,5,0,"-"],sys_exc:[109,16,1,"-"],sysconfig:[381,5,0,"-"],syslog:[382,5,0,"-"],tabnanny:[383,5,0,"-"],tarfile:[384,5,0,"-"],telnetlib:[385,5,0,"-"],tempfile:[386,5,0,"-"],termios:[387,5,0,"-"],test:[388,5,0,"-"],textwrap:[389,5,0,"-"],thread:[390,5,0,"-"],threading:[391,5,0,"-"],time:[392,5,0,"-"],timeit:[393,5,0,"-"],token:[397,5,0,"-"],tokenize:[398,5,0,"-"],tp_as_mapping:[55,3,1,"c.tp_as_mapping"],tp_as_number:[55,3,1,"c.tp_as_number"],tp_as_sequence:[55,3,1,"c.tp_as_sequence"],trace:[399,5,0,"-"],traceback:[400,5,0,"-"],traverseproc:[24,2,1,"c.traverseproc"],ttk:[401,5,0,"-"],tty:[402,5,0,"-"],tuple:[222,9,1,""],tuple_params:[109,16,1,"-"],turtle:[403,5,0,"-"],type:[222,6,1,""],types:[109,16,1,"-"],unichr:[222,9,1,""],unicode:[109,16,1,"-"],unicodedata:[406,5,0,"-"],unittest:[407,5,0,"-"],urllib2:[410,5,0,"-"],urllib:[109,16,1,"-"],urlparse:[411,5,0,"-"],user:[412,5,0,"-"],uu:[414,5,0,"-"],uuid:[415,5,0,"-"],vars:[222,9,1,""],videoreader:[405,5,0,"-"],visitproc:[24,2,1,"c.visitproc"],warnings:[416,5,0,"-"],wave:[417,5,0,"-"],weakref:[418,5,0,"-"],webbrowser:[419,5,0,"-"],whichdb:[420,5,0,"-"],winsound:[422,5,0,"-"],writebufferproc:[55,2,1,"c.writebufferproc"],ws_comma:[109,16,1,"-"],wsgiref:[423,5,0,"-"],xdrlib:[424,5,0,"-"],xml:[425,5,0,"-"],xmlrpclib:[434,5,0,"-"],xrange:[109,16,1,"-"],xreadlines:[109,16,1,"-"],zip:[109,16,1,"-"],zipfile:[435,5,0,"-"],zipimport:[436,5,0,"-"],zlib:[437,5,0,"-"]},"BaseHTTPServer.BaseHTTPRequestHandler":{MessageClass:[132,7,1,""],address_string:[132,8,1,""],client_address:[132,7,1,""],command:[132,7,1,""],date_time_string:[132,8,1,""],end_headers:[132,8,1,""],error_content_type:[132,7,1,""],error_message_format:[132,7,1,""],handle:[132,8,1,""],handle_one_request:[132,8,1,""],headers:[132,7,1,""],log_date_time_string:[132,8,1,""],log_error:[132,8,1,""],log_message:[132,8,1,""],log_request:[132,8,1,""],path:[132,7,1,""],protocol_version:[132,7,1,""],request_version:[132,7,1,""],responses:[132,7,1,""],rfile:[132,7,1,""],send_error:[132,8,1,""],send_header:[132,8,1,""],send_response:[132,8,1,""],server:[132,7,1,""],server_version:[132,7,1,""],sys_version:[132,7,1,""],version_string:[132,8,1,""],wfile:[132,7,1,""]},"CGIHTTPServer.CGIHTTPRequestHandler":{cgi_directories:[144,7,1,""],do_POST:[144,8,1,""]},"Carbon.Scrap":{InfoScrap:[141,9,1,""]},"ConfigParser.ConfigParser":{get:[158,8,1,""],items:[158,8,1,""]},"ConfigParser.RawConfigParser":{add_section:[158,8,1,""],defaults:[158,8,1,""],get:[158,8,1,""],getboolean:[158,8,1,""],getfloat:[158,8,1,""],getint:[158,8,1,""],has_option:[158,8,1,""],has_section:[158,8,1,""],items:[158,8,1,""],options:[158,8,1,""],optionxform:[158,8,1,""],read:[158,8,1,""],readfp:[158,8,1,""],remove_option:[158,8,1,""],remove_section:[158,8,1,""],sections:[158,8,1,""],set:[158,8,1,""],write:[158,8,1,""]},"ConfigParser.SafeConfigParser":{set:[158,8,1,""]},"Cookie.BaseCookie":{js_output:[161,8,1,""],load:[161,8,1,""],output:[161,8,1,""],value_decode:[161,8,1,""],value_encode:[161,8,1,""]},"Cookie.Morsel":{OutputString:[161,8,1,""],coded_value:[161,7,1,""],isReservedKey:[161,8,1,""],js_output:[161,8,1,""],key:[161,7,1,""],output:[161,8,1,""],set:[161,8,1,""],value:[161,7,1,""]},"DocXMLRPCServer.DocCGIXMLRPCRequestHandler":{set_server_documentation:[187,8,1,""],set_server_name:[187,8,1,""],set_server_title:[187,8,1,""]},"DocXMLRPCServer.DocXMLRPCServer":{set_server_documentation:[187,8,1,""],set_server_name:[187,8,1,""],set_server_title:[187,8,1,""]},"EasyDialogs.ProgressBar":{curval:[191,7,1,""],inc:[191,8,1,""],label:[191,8,1,""],maxval:[191,7,1,""],set:[191,8,1,""],title:[191,8,1,""]},"FrameWork.Application":{_quit:[219,8,1,""],asyncevents:[219,8,1,""],do_char:[219,8,1,""],do_dialogevent:[219,8,1,""],getabouttext:[219,8,1,""],idle:[219,8,1,""],mainloop:[219,8,1,""],makeusermenus:[219,8,1,""]},"FrameWork.ControlsWindow":{do_controlhit:[219,8,1,""]},"FrameWork.DialogWindow":{do_itemhit:[219,8,1,""],open:[219,8,1,""]},"FrameWork.ScrolledWindow":{do_activate:[219,8,1,""],do_controlhit:[219,8,1,""],do_postresize:[219,8,1,""],getscrollbarvalues:[219,8,1,""],scalebarvalues:[219,8,1,""],scrollbar_callback:[219,8,1,""],scrollbars:[219,8,1,""],updatescrollbars:[219,8,1,""]},"FrameWork.Window":{close:[219,8,1,""],do_activate:[219,8,1,""],do_contentclick:[219,8,1,""],do_postresize:[219,8,1,""],do_update:[219,8,1,""],open:[219,8,1,""]},"HTMLParser.HTMLParser":{close:[240,8,1,""],feed:[240,8,1,""],get_starttag_text:[240,8,1,""],getpos:[240,8,1,""],handle_charref:[240,8,1,""],handle_comment:[240,8,1,""],handle_data:[240,8,1,""],handle_decl:[240,8,1,""],handle_endtag:[240,8,1,""],handle_entityref:[240,8,1,""],handle_pi:[240,8,1,""],handle_startendtag:[240,8,1,""],handle_starttag:[240,8,1,""],reset:[240,8,1,""],unknown_decl:[240,8,1,""]},"MimeWriter.MimeWriter":{addheader:[282,8,1,""],flushheaders:[282,8,1,""],lastpart:[282,8,1,""],nextpart:[282,8,1,""],startbody:[282,8,1,""],startmultipartbody:[282,8,1,""]},"MiniAEFrame.AEServer":{callback:[284,8,1,""],installaehandler:[284,8,1,""]},"Queue.Queue":{empty:[330,8,1,""],full:[330,8,1,""],get:[330,8,1,""],get_nowait:[330,8,1,""],join:[330,8,1,""],put:[330,8,1,""],put_nowait:[330,8,1,""],qsize:[330,8,1,""],task_done:[330,8,1,""]},"ScrolledText.ScrolledText":{frame:[344,7,1,""],vbar:[344,7,1,""]},"SimpleHTTPServer.SimpleHTTPRequestHandler":{do_GET:[354,8,1,""],do_HEAD:[354,8,1,""],extensions_map:[354,7,1,""],server_version:[354,7,1,""]},"SimpleXMLRPCServer.CGIXMLRPCRequestHandler":{handle_request:[355,8,1,""],register_function:[355,8,1,""],register_instance:[355,8,1,""],register_introspection_functions:[355,8,1,""],register_multicall_functions:[355,8,1,""]},"SimpleXMLRPCServer.SimpleXMLRPCRequestHandler":{encode_threshold:[355,7,1,""],rpc_paths:[355,7,1,""]},"SimpleXMLRPCServer.SimpleXMLRPCServer":{register_function:[355,8,1,""],register_instance:[355,8,1,""],register_introspection_functions:[355,8,1,""],register_multicall_functions:[355,8,1,""]},"SocketServer.BaseRequestHandler":{finish:[361,8,1,""],handle:[361,8,1,""],setup:[361,8,1,""]},"SocketServer.BaseServer":{RequestHandlerClass:[361,7,1,""],address_family:[361,7,1,""],allow_reuse_address:[361,7,1,""],fileno:[361,8,1,""],finish_request:[361,8,1,""],get_request:[361,8,1,""],handle_error:[361,8,1,""],handle_request:[361,8,1,""],handle_timeout:[361,8,1,""],process_request:[361,8,1,""],request_queue_size:[361,7,1,""],serve_forever:[361,8,1,""],server_activate:[361,8,1,""],server_address:[361,7,1,""],server_bind:[361,8,1,""],server_close:[361,8,1,""],shutdown:[361,8,1,""],socket:[361,7,1,""],socket_type:[361,7,1,""],timeout:[361,7,1,""],verify_request:[361,8,1,""]},"StringIO.StringIO":{close:[370,8,1,""],getvalue:[370,8,1,""]},"Tix.tixCommand":{tix_addbitmapdir:[394,8,1,""],tix_cget:[394,8,1,""],tix_configure:[394,8,1,""],tix_filedialog:[394,8,1,""],tix_getbitmap:[394,8,1,""],tix_getimage:[394,8,1,""],tix_option_get:[394,8,1,""],tix_resetoptions:[394,8,1,""]},"Tkinter.Widget.tk":{createfilehandler:[396,8,1,""],deletefilehandler:[396,8,1,""]},"UserDict.IterableUserDict":{data:[413,7,1,""]},"UserList.UserList":{data:[413,7,1,""]},"UserString.MutableString":{data:[413,7,1,""]},"_winreg.PyHKEY":{Close:[113,8,1,""],Detach:[113,8,1,""],__enter__:[113,8,1,""],__exit__:[113,8,1,""]},"abc.ABCMeta":{__subclasshook__:[114,8,1,""],register:[114,8,1,""]},"aetools.TalkTo":{_start:[116,8,1,""],send:[116,8,1,""]},"aifc.aifc":{aifc:[118,8,1,""],aiff:[118,8,1,""],close:[118,8,1,""],getcompname:[118,8,1,""],getcomptype:[118,8,1,""],getframerate:[118,8,1,""],getmark:[118,8,1,""],getmarkers:[118,8,1,""],getnchannels:[118,8,1,""],getnframes:[118,8,1,""],getparams:[118,8,1,""],getsampwidth:[118,8,1,""],readframes:[118,8,1,""],rewind:[118,8,1,""],setcomptype:[118,8,1,""],setframerate:[118,8,1,""],setmark:[118,8,1,""],setnchannels:[118,8,1,""],setnframes:[118,8,1,""],setparams:[118,8,1,""],setpos:[118,8,1,""],setsampwidth:[118,8,1,""],tell:[118,8,1,""],writeframes:[118,8,1,""],writeframesraw:[118,8,1,""]},"argparse.ArgumentParser":{add_argument:[123,8,1,""],add_argument_group:[123,8,1,""],add_mutually_exclusive_group:[123,8,1,""],add_subparsers:[123,8,1,""],convert_arg_line_to_args:[123,8,1,""],error:[123,8,1,""],exit:[123,8,1,""],format_help:[123,8,1,""],format_usage:[123,8,1,""],get_default:[123,8,1,""],parse_args:[123,8,1,""],parse_known_args:[123,8,1,""],print_help:[123,8,1,""],print_usage:[123,8,1,""],set_defaults:[123,8,1,""]},"array.array":{append:[124,8,1,""],buffer_info:[124,8,1,""],byteswap:[124,8,1,""],count:[124,8,1,""],extend:[124,8,1,""],fromfile:[124,8,1,""],fromlist:[124,8,1,""],fromstring:[124,8,1,""],fromunicode:[124,8,1,""],index:[124,8,1,""],insert:[124,8,1,""],itemsize:[124,7,1,""],pop:[124,8,1,""],read:[124,8,1,""],remove:[124,8,1,""],reverse:[124,8,1,""],tofile:[124,8,1,""],tolist:[124,8,1,""],tostring:[124,8,1,""],tounicode:[124,8,1,""],typecode:[124,7,1,""],write:[124,8,1,""]},"ast.AST":{_fields:[125,7,1,""],col_offset:[125,7,1,""],lineno:[125,7,1,""]},"ast.NodeVisitor":{generic_visit:[125,8,1,""],visit:[125,8,1,""]},"asynchat.async_chat":{ac_in_buffer_size:[126,11,1,""],ac_out_buffer_size:[126,11,1,""],close_when_done:[126,8,1,""],collect_incoming_data:[126,8,1,""],discard_buffers:[126,8,1,""],found_terminator:[126,8,1,""],get_terminator:[126,8,1,""],push:[126,8,1,""],push_with_producer:[126,8,1,""],set_terminator:[126,8,1,""]},"asynchat.fifo":{first:[126,8,1,""],is_empty:[126,8,1,""],pop:[126,8,1,""],push:[126,8,1,""]},"asyncore.dispatcher":{accept:[127,8,1,""],bind:[127,8,1,""],close:[127,8,1,""],connect:[127,8,1,""],create_socket:[127,8,1,""],handle_accept:[127,8,1,""],handle_close:[127,8,1,""],handle_connect:[127,8,1,""],handle_error:[127,8,1,""],handle_expt:[127,8,1,""],handle_read:[127,8,1,""],handle_write:[127,8,1,""],listen:[127,8,1,""],readable:[127,8,1,""],recv:[127,8,1,""],send:[127,8,1,""],writable:[127,8,1,""]},"bdb.Bdb":{break_anywhere:[134,8,1,""],break_here:[134,8,1,""],canonic:[134,8,1,""],clear_all_breaks:[134,8,1,""],clear_all_file_breaks:[134,8,1,""],clear_bpbynumber:[134,8,1,""],clear_break:[134,8,1,""],dispatch_call:[134,8,1,""],dispatch_exception:[134,8,1,""],dispatch_line:[134,8,1,""],dispatch_return:[134,8,1,""],do_clear:[134,8,1,""],format_stack_entry:[134,8,1,""],get_all_breaks:[134,8,1,""],get_break:[134,8,1,""],get_breaks:[134,8,1,""],get_file_breaks:[134,8,1,""],get_stack:[134,8,1,""],reset:[134,8,1,""],run:[134,8,1,""],runcall:[134,8,1,""],runctx:[134,8,1,""],runeval:[134,8,1,""],set_break:[134,8,1,""],set_continue:[134,8,1,""],set_next:[134,8,1,""],set_quit:[134,8,1,""],set_return:[134,8,1,""],set_step:[134,8,1,""],set_trace:[134,8,1,""],set_until:[134,8,1,""],stop_here:[134,8,1,""],trace_dispatch:[134,8,1,""],user_call:[134,8,1,""],user_exception:[134,8,1,""],user_line:[134,8,1,""],user_return:[134,8,1,""]},"bdb.Breakpoint":{deleteMe:[134,8,1,""],disable:[134,8,1,""],enable:[134,8,1,""],pprint:[134,8,1,""]},"bsddb.bsddbobject":{close:[138,8,1,""],first:[138,8,1,""],has_key:[138,8,1,""],keys:[138,8,1,""],last:[138,8,1,""],next:[138,8,1,""],previous:[138,8,1,""],set_location:[138,8,1,""],sync:[138,8,1,""]},"bz2.BZ2Compressor":{compress:[139,8,1,""],flush:[139,8,1,""]},"bz2.BZ2Decompressor":{decompress:[139,8,1,""]},"bz2.BZ2File":{close:[139,8,1,""],read:[139,8,1,""],readline:[139,8,1,""],readlines:[139,8,1,""],seek:[139,8,1,""],tell:[139,8,1,""],write:[139,8,1,""],writelines:[139,8,1,""],xreadlines:[139,8,1,""]},"calendar.Calendar":{itermonthdates:[140,8,1,""],itermonthdays2:[140,8,1,""],itermonthdays:[140,8,1,""],iterweekdays:[140,8,1,""],monthdatescalendar:[140,8,1,""],monthdays2calendar:[140,8,1,""],monthdayscalendar:[140,8,1,""],yeardatescalendar:[140,8,1,""],yeardays2calendar:[140,8,1,""],yeardayscalendar:[140,8,1,""]},"calendar.HTMLCalendar":{formatmonth:[140,8,1,""],formatyear:[140,8,1,""],formatyearpage:[140,8,1,""]},"calendar.TextCalendar":{formatmonth:[140,8,1,""],formatyear:[140,8,1,""],prmonth:[140,8,1,""],pryear:[140,8,1,""]},"cgi.FieldStorage":{getfirst:[143,8,1,""],getlist:[143,8,1,""]},"chunk.Chunk":{close:[146,8,1,""],getname:[146,8,1,""],getsize:[146,8,1,""],isatty:[146,8,1,""],read:[146,8,1,""],seek:[146,8,1,""],skip:[146,8,1,""],tell:[146,8,1,""]},"class":{__bases__:[368,7,1,""],__instancecheck__:[440,8,1,""],__mro__:[368,7,1,""],__subclasscheck__:[440,8,1,""],__subclasses__:[368,8,1,""],mro:[368,8,1,""]},"cmd.Cmd":{"default":[148,8,1,""],cmdloop:[148,8,1,""],cmdqueue:[148,7,1,""],completedefault:[148,8,1,""],doc_header:[148,7,1,""],emptyline:[148,8,1,""],identchars:[148,7,1,""],intro:[148,7,1,""],lastcmd:[148,7,1,""],misc_header:[148,7,1,""],onecmd:[148,8,1,""],postcmd:[148,8,1,""],postloop:[148,8,1,""],precmd:[148,8,1,""],preloop:[148,8,1,""],prompt:[148,7,1,""],ruler:[148,7,1,""],undoc_header:[148,7,1,""],use_rawinput:[148,7,1,""]},"code.InteractiveConsole":{interact:[149,8,1,""],push:[149,8,1,""],raw_input:[149,8,1,""],resetbuffer:[149,8,1,""]},"code.InteractiveInterpreter":{runcode:[149,8,1,""],runsource:[149,8,1,""],showsyntaxerror:[149,8,1,""],showtraceback:[149,8,1,""],write:[149,8,1,""]},"codecs.Codec":{decode:[150,8,1,""],encode:[150,8,1,""]},"codecs.IncrementalDecoder":{decode:[150,8,1,""],reset:[150,8,1,""]},"codecs.IncrementalEncoder":{encode:[150,8,1,""],reset:[150,8,1,""]},"codecs.StreamReader":{read:[150,8,1,""],readline:[150,8,1,""],readlines:[150,8,1,""],reset:[150,8,1,""]},"codecs.StreamWriter":{reset:[150,8,1,""],write:[150,8,1,""],writelines:[150,8,1,""]},"collections.Counter":{elements:[152,8,1,""],fromkeys:[152,8,1,""],most_common:[152,8,1,""],subtract:[152,8,1,""],update:[152,8,1,""]},"collections.OrderedDict":{popitem:[152,8,1,""]},"collections.defaultdict":{__missing__:[152,8,1,""],default_factory:[152,7,1,""]},"collections.deque":{append:[152,8,1,""],appendleft:[152,8,1,""],clear:[152,8,1,""],count:[152,8,1,""],extend:[152,8,1,""],extendleft:[152,8,1,""],maxlen:[152,7,1,""],pop:[152,8,1,""],popleft:[152,8,1,""],remove:[152,8,1,""],reverse:[152,8,1,""],rotate:[152,8,1,""]},"collections.somenamedtuple":{_asdict:[152,8,1,""],_fields:[152,7,1,""],_make:[152,12,1,""],_replace:[152,8,1,""]},"compiler.ast":{Node:[157,6,1,""]},"compiler.ast.Node":{getChildNodes:[157,8,1,""],getChildren:[157,8,1,""]},"compiler.visitor":{ASTVisitor:[157,6,1,""],walk:[157,9,1,""]},"compiler.visitor.ASTVisitor":{"default":[157,8,1,""],dispatch:[157,8,1,""],preorder:[157,8,1,""]},"cookielib.Cookie":{comment:[162,7,1,""],comment_url:[162,7,1,""],discard:[162,7,1,""],domain_initial_dot:[162,7,1,""],domain_specified:[162,7,1,""],expires:[162,7,1,""],get_nonstandard_attr:[162,8,1,""],has_nonstandard_attr:[162,8,1,""],is_expired:[162,8,1,""],name:[162,7,1,""],path:[162,7,1,""],port:[162,7,1,""],port_specified:[162,7,1,""],rfc2109:[162,7,1,""],secure:[162,7,1,""],set_nonstandard_attr:[162,8,1,""],value:[162,7,1,""],version:[162,7,1,""]},"cookielib.CookieJar":{add_cookie_header:[162,8,1,""],clear:[162,8,1,""],clear_session_cookies:[162,8,1,""],extract_cookies:[162,8,1,""],make_cookies:[162,8,1,""],set_cookie:[162,8,1,""],set_cookie_if_ok:[162,8,1,""],set_policy:[162,8,1,""]},"cookielib.CookiePolicy":{domain_return_ok:[162,8,1,""],hide_cookie2:[162,7,1,""],netscape:[162,7,1,""],path_return_ok:[162,8,1,""],return_ok:[162,8,1,""],rfc2965:[162,7,1,""],set_ok:[162,8,1,""]},"cookielib.DefaultCookiePolicy":{DomainLiberal:[162,7,1,""],DomainRFC2965Match:[162,7,1,""],DomainStrict:[162,7,1,""],DomainStrictNoDots:[162,7,1,""],DomainStrictNonDomain:[162,7,1,""],allowed_domains:[162,8,1,""],blocked_domains:[162,8,1,""],is_blocked:[162,8,1,""],is_not_allowed:[162,8,1,""],rfc2109_as_netscape:[162,7,1,""],set_allowed_domains:[162,8,1,""],set_blocked_domains:[162,8,1,""],strict_domain:[162,7,1,""],strict_ns_domain:[162,7,1,""],strict_ns_set_initial_dollar:[162,7,1,""],strict_ns_set_path:[162,7,1,""],strict_ns_unverifiable:[162,7,1,""],strict_rfc2965_unverifiable:[162,7,1,""]},"cookielib.FileCookieJar":{delayload:[162,7,1,""],filename:[162,7,1,""],load:[162,8,1,""],revert:[162,8,1,""],save:[162,8,1,""]},"csv.Dialect":{delimiter:[167,7,1,""],doublequote:[167,7,1,""],escapechar:[167,7,1,""],lineterminator:[167,7,1,""],quotechar:[167,7,1,""],quoting:[167,7,1,""],skipinitialspace:[167,7,1,""],strict:[167,7,1,""]},"csv.DictWriter":{writeheader:[167,8,1,""]},"csv.Sniffer":{has_header:[167,8,1,""],sniff:[167,8,1,""]},"csv.csvreader":{dialect:[167,7,1,""],fieldnames:[167,7,1,""],line_num:[167,7,1,""],next:[167,8,1,""]},"csv.csvwriter":{dialect:[167,7,1,""],writerow:[167,8,1,""],writerows:[167,8,1,""]},"ctypes.Array":{_length_:[168,7,1,""],_type_:[168,7,1,""]},"ctypes.LibraryLoader":{LoadLibrary:[168,8,1,""]},"ctypes.PyDLL":{_handle:[168,7,1,""],_name:[168,7,1,""]},"ctypes.Structure":{_anonymous_:[168,7,1,""],_fields_:[168,7,1,""],_pack_:[168,7,1,""]},"ctypes._CData":{_b_base_:[168,7,1,""],_b_needsfree_:[168,7,1,""],_objects:[168,7,1,""],from_address:[168,8,1,""],from_buffer:[168,8,1,""],from_buffer_copy:[168,8,1,""],from_param:[168,8,1,""],in_dll:[168,8,1,""]},"ctypes._FuncPtr":{argtypes:[168,7,1,""],errcheck:[168,7,1,""],restype:[168,7,1,""]},"ctypes._Pointer":{_type_:[168,7,1,""],contents:[168,7,1,""]},"ctypes._SimpleCData":{value:[168,7,1,""]},"ctypes.util":{find_library:[168,9,1,""],find_msvcrt:[168,9,1,""]},"curses.ascii":{alt:[170,9,1,""],ascii:[170,9,1,""],controlnames:[170,11,1,""],ctrl:[170,9,1,""],isalnum:[170,9,1,""],isalpha:[170,9,1,""],isascii:[170,9,1,""],isblank:[170,9,1,""],iscntrl:[170,9,1,""],isctrl:[170,9,1,""],isdigit:[170,9,1,""],isgraph:[170,9,1,""],islower:[170,9,1,""],ismeta:[170,9,1,""],isprint:[170,9,1,""],ispunct:[170,9,1,""],isspace:[170,9,1,""],isupper:[170,9,1,""],isxdigit:[170,9,1,""],unctrl:[170,9,1,""]},"curses.panel":{bottom_panel:[171,9,1,""],new_panel:[171,9,1,""],top_panel:[171,9,1,""],update_panels:[171,9,1,""]},"curses.panel.Panel":{above:[171,8,1,""],below:[171,8,1,""],bottom:[171,8,1,""],hidden:[171,8,1,""],hide:[171,8,1,""],move:[171,8,1,""],replace:[171,8,1,""],set_userptr:[171,8,1,""],show:[171,8,1,""],top:[171,8,1,""],userptr:[171,8,1,""],window:[171,8,1,""]},"curses.textpad":{Textbox:[169,6,1,""],rectangle:[169,9,1,""]},"curses.textpad.Textbox":{do_command:[169,8,1,""],edit:[169,8,1,""],gather:[169,8,1,""],stripspaces:[169,7,1,""]},"curses.window":{addch:[169,8,1,""],addnstr:[169,8,1,""],addstr:[169,8,1,""],attroff:[169,8,1,""],attron:[169,8,1,""],attrset:[169,8,1,""],bkgd:[169,8,1,""],bkgdset:[169,8,1,""],border:[169,8,1,""],box:[169,8,1,""],chgat:[169,8,1,""],clear:[169,8,1,""],clearok:[169,8,1,""],clrtobot:[169,8,1,""],clrtoeol:[169,8,1,""],cursyncup:[169,8,1,""],delch:[169,8,1,""],deleteln:[169,8,1,""],derwin:[169,8,1,""],echochar:[169,8,1,""],enclose:[169,8,1,""],erase:[169,8,1,""],getbegyx:[169,8,1,""],getbkgd:[169,8,1,""],getch:[169,8,1,""],getkey:[169,8,1,""],getmaxyx:[169,8,1,""],getparyx:[169,8,1,""],getstr:[169,8,1,""],getyx:[169,8,1,""],hline:[169,8,1,""],idcok:[169,8,1,""],idlok:[169,8,1,""],immedok:[169,8,1,""],inch:[169,8,1,""],insch:[169,8,1,""],insdelln:[169,8,1,""],insertln:[169,8,1,""],insnstr:[169,8,1,""],insstr:[169,8,1,""],instr:[169,8,1,""],is_linetouched:[169,8,1,""],is_wintouched:[169,8,1,""],keypad:[169,8,1,""],leaveok:[169,8,1,""],move:[169,8,1,""],mvderwin:[169,8,1,""],mvwin:[169,8,1,""],nodelay:[169,8,1,""],notimeout:[169,8,1,""],noutrefresh:[169,8,1,""],overlay:[169,8,1,""],overwrite:[169,8,1,""],putwin:[169,8,1,""],redrawln:[169,8,1,""],redrawwin:[169,8,1,""],refresh:[169,8,1,""],resize:[169,8,1,""],scroll:[169,8,1,""],scrollok:[169,8,1,""],setscrreg:[169,8,1,""],standend:[169,8,1,""],standout:[169,8,1,""],subpad:[169,8,1,""],subwin:[169,8,1,""],syncdown:[169,8,1,""],syncok:[169,8,1,""],syncup:[169,8,1,""],timeout:[169,8,1,""],touchline:[169,8,1,""],touchwin:[169,8,1,""],untouchwin:[169,8,1,""],vline:[169,8,1,""]},"datetime.date":{__format__:[174,8,1,""],__str__:[174,8,1,""],ctime:[174,8,1,""],day:[174,7,1,""],fromordinal:[174,12,1,""],fromtimestamp:[174,12,1,""],isocalendar:[174,8,1,""],isoformat:[174,8,1,""],isoweekday:[174,8,1,""],max:[174,7,1,""],min:[174,7,1,""],month:[174,7,1,""],replace:[174,8,1,""],resolution:[174,7,1,""],strftime:[174,8,1,""],timetuple:[174,8,1,""],today:[174,12,1,""],toordinal:[174,8,1,""],weekday:[174,8,1,""],year:[174,7,1,""]},"datetime.datetime":{__format__:[174,8,1,""],__str__:[174,8,1,""],astimezone:[174,8,1,""],combine:[174,12,1,""],ctime:[174,8,1,""],date:[174,8,1,""],day:[174,7,1,""],dst:[174,8,1,""],fromordinal:[174,12,1,""],fromtimestamp:[174,12,1,""],hour:[174,7,1,""],isocalendar:[174,8,1,""],isoformat:[174,8,1,""],isoweekday:[174,8,1,""],max:[174,7,1,""],microsecond:[174,7,1,""],min:[174,7,1,""],minute:[174,7,1,""],month:[174,7,1,""],now:[174,12,1,""],replace:[174,8,1,""],resolution:[174,7,1,""],second:[174,7,1,""],strftime:[174,8,1,""],strptime:[174,12,1,""],time:[174,8,1,""],timetuple:[174,8,1,""],timetz:[174,8,1,""],today:[174,12,1,""],toordinal:[174,8,1,""],tzinfo:[174,7,1,""],tzname:[174,8,1,""],utcfromtimestamp:[174,12,1,""],utcnow:[174,12,1,""],utcoffset:[174,8,1,""],utctimetuple:[174,8,1,""],weekday:[174,8,1,""],year:[174,7,1,""]},"datetime.time":{__format__:[174,8,1,""],__str__:[174,8,1,""],dst:[174,8,1,""],hour:[174,7,1,""],isoformat:[174,8,1,""],max:[174,7,1,""],microsecond:[174,7,1,""],min:[174,7,1,""],minute:[174,7,1,""],replace:[174,8,1,""],resolution:[174,7,1,""],second:[174,7,1,""],strftime:[174,8,1,""],tzinfo:[174,7,1,""],tzname:[174,8,1,""],utcoffset:[174,8,1,""]},"datetime.timedelta":{max:[174,7,1,""],min:[174,7,1,""],resolution:[174,7,1,""],total_seconds:[174,8,1,""]},"datetime.tzinfo":{dst:[174,8,1,""],fromutc:[174,8,1,""],tzname:[174,8,1,""],utcoffset:[174,8,1,""]},"dbhash.dbhash":{first:[175,8,1,""],last:[175,8,1,""],next:[175,8,1,""],previous:[175,8,1,""],sync:[175,8,1,""]},"decimal.Context":{Etiny:[178,8,1,""],Etop:[178,8,1,""],abs:[178,8,1,""],add:[178,8,1,""],canonical:[178,8,1,""],clear_flags:[178,8,1,""],compare:[178,8,1,""],compare_signal:[178,8,1,""],compare_total:[178,8,1,""],compare_total_mag:[178,8,1,""],copy:[178,8,1,""],copy_abs:[178,8,1,""],copy_decimal:[178,8,1,""],copy_negate:[178,8,1,""],copy_sign:[178,8,1,""],create_decimal:[178,8,1,""],create_decimal_from_float:[178,8,1,""],divide:[178,8,1,""],divide_int:[178,8,1,""],divmod:[178,8,1,""],exp:[178,8,1,""],fma:[178,8,1,""],is_canonical:[178,8,1,""],is_finite:[178,8,1,""],is_infinite:[178,8,1,""],is_nan:[178,8,1,""],is_normal:[178,8,1,""],is_qnan:[178,8,1,""],is_signed:[178,8,1,""],is_snan:[178,8,1,""],is_subnormal:[178,8,1,""],is_zero:[178,8,1,""],ln:[178,8,1,""],log10:[178,8,1,""],logb:[178,8,1,""],logical_and:[178,8,1,""],logical_invert:[178,8,1,""],logical_or:[178,8,1,""],logical_xor:[178,8,1,""],max:[178,8,1,""],max_mag:[178,8,1,""],min:[178,8,1,""],min_mag:[178,8,1,""],minus:[178,8,1,""],multiply:[178,8,1,""],next_minus:[178,8,1,""],next_plus:[178,8,1,""],next_toward:[178,8,1,""],normalize:[178,8,1,""],number_class:[178,8,1,""],plus:[178,8,1,""],power:[178,8,1,""],quantize:[178,8,1,""],radix:[178,8,1,""],remainder:[178,8,1,""],remainder_near:[178,8,1,""],rotate:[178,8,1,""],same_quantum:[178,8,1,""],scaleb:[178,8,1,""],shift:[178,8,1,""],sqrt:[178,8,1,""],subtract:[178,8,1,""],to_eng_string:[178,8,1,""],to_integral_exact:[178,8,1,""],to_sci_string:[178,8,1,""]},"decimal.Decimal":{adjusted:[178,8,1,""],as_tuple:[178,8,1,""],canonical:[178,8,1,""],compare:[178,8,1,""],compare_signal:[178,8,1,""],compare_total:[178,8,1,""],compare_total_mag:[178,8,1,""],conjugate:[178,8,1,""],copy_abs:[178,8,1,""],copy_negate:[178,8,1,""],copy_sign:[178,8,1,""],exp:[178,8,1,""],fma:[178,8,1,""],from_float:[178,8,1,""],is_canonical:[178,8,1,""],is_finite:[178,8,1,""],is_infinite:[178,8,1,""],is_nan:[178,8,1,""],is_normal:[178,8,1,""],is_qnan:[178,8,1,""],is_signed:[178,8,1,""],is_snan:[178,8,1,""],is_subnormal:[178,8,1,""],is_zero:[178,8,1,""],ln:[178,8,1,""],log10:[178,8,1,""],logb:[178,8,1,""],logical_and:[178,8,1,""],logical_invert:[178,8,1,""],logical_or:[178,8,1,""],logical_xor:[178,8,1,""],max:[178,8,1,""],max_mag:[178,8,1,""],min:[178,8,1,""],min_mag:[178,8,1,""],next_minus:[178,8,1,""],next_plus:[178,8,1,""],next_toward:[178,8,1,""],normalize:[178,8,1,""],number_class:[178,8,1,""],quantize:[178,8,1,""],radix:[178,8,1,""],remainder_near:[178,8,1,""],rotate:[178,8,1,""],same_quantum:[178,8,1,""],scaleb:[178,8,1,""],shift:[178,8,1,""],sqrt:[178,8,1,""],to_eng_string:[178,8,1,""],to_integral:[178,8,1,""],to_integral_exact:[178,8,1,""],to_integral_value:[178,8,1,""]},"difflib.Differ":{compare:[180,8,1,""]},"difflib.HtmlDiff":{__init__:[180,9,1,""],make_file:[180,9,1,""],make_table:[180,9,1,""]},"difflib.SequenceMatcher":{find_longest_match:[180,8,1,""],get_grouped_opcodes:[180,8,1,""],get_matching_blocks:[180,8,1,""],get_opcodes:[180,8,1,""],quick_ratio:[180,8,1,""],ratio:[180,8,1,""],real_quick_ratio:[180,8,1,""],set_seq1:[180,8,1,""],set_seq2:[180,8,1,""],set_seqs:[180,8,1,""]},"distutils.archive_util":{make_archive:[63,9,1,""],make_tarball:[63,9,1,""],make_zipfile:[63,9,1,""]},"distutils.ccompiler":{CCompiler:[63,6,1,""],gen_lib_options:[63,9,1,""],gen_preprocess_options:[63,9,1,""],get_default_compiler:[63,9,1,""],new_compiler:[63,9,1,""],show_compilers:[63,9,1,""]},"distutils.ccompiler.CCompiler":{add_include_dir:[63,8,1,""],add_library:[63,8,1,""],add_library_dir:[63,8,1,""],add_link_object:[63,8,1,""],add_runtime_library_dir:[63,8,1,""],announce:[63,8,1,""],compile:[63,8,1,""],create_static_lib:[63,8,1,""],debug_print:[63,8,1,""],define_macro:[63,8,1,""],detect_language:[63,8,1,""],executable_filename:[63,8,1,""],execute:[63,8,1,""],find_library_file:[63,8,1,""],has_function:[63,8,1,""],library_dir_option:[63,8,1,""],library_filename:[63,8,1,""],library_option:[63,8,1,""],link:[63,8,1,""],link_executable:[63,8,1,""],link_shared_lib:[63,8,1,""],link_shared_object:[63,8,1,""],mkpath:[63,8,1,""],move_file:[63,8,1,""],object_filenames:[63,8,1,""],preprocess:[63,8,1,""],runtime_library_dir_option:[63,8,1,""],set_executables:[63,8,1,""],set_include_dirs:[63,8,1,""],set_libraries:[63,8,1,""],set_library_dirs:[63,8,1,""],set_link_objects:[63,8,1,""],set_runtime_library_dirs:[63,8,1,""],shared_object_filename:[63,8,1,""],spawn:[63,8,1,""],undefine_macro:[63,8,1,""],warn:[63,8,1,""]},"distutils.cmd":{Command:[63,6,1,""]},"distutils.cmd.Command":{finalize_options:[63,8,1,""],initialize_options:[63,8,1,""],run:[63,8,1,""],sub_commands:[63,7,1,""]},"distutils.command":{bdist:[63,5,0,"-"],bdist_dumb:[63,5,0,"-"],bdist_msi:[63,5,0,"-"],bdist_packager:[63,5,0,"-"],bdist_rpm:[63,5,0,"-"],bdist_wininst:[63,5,0,"-"],build:[63,5,0,"-"],build_clib:[63,5,0,"-"],build_ext:[63,5,0,"-"],build_py:[63,5,0,"-"],build_scripts:[63,5,0,"-"],check:[63,5,0,"-"],clean:[63,5,0,"-"],config:[63,5,0,"-"],install:[63,5,0,"-"],install_data:[63,5,0,"-"],install_headers:[63,5,0,"-"],install_lib:[63,5,0,"-"],install_scripts:[63,5,0,"-"],register:[63,5,0,"-"],sdist:[63,5,0,"-"]},"distutils.command.bdist_msi":{bdist_msi:[63,6,1,""]},"distutils.core":{Command:[63,6,1,""],Distribution:[63,6,1,""],Extension:[63,6,1,""],run_setup:[63,9,1,""],setup:[63,9,1,""]},"distutils.dep_util":{newer:[63,9,1,""],newer_group:[63,9,1,""],newer_pairwise:[63,9,1,""]},"distutils.dir_util":{copy_tree:[63,9,1,""],create_tree:[63,9,1,""],mkpath:[63,9,1,""],remove_tree:[63,9,1,""]},"distutils.fancy_getopt":{FancyGetopt:[63,6,1,""],fancy_getopt:[63,9,1,""],wrap_text:[63,9,1,""]},"distutils.fancy_getopt.FancyGetopt":{generate_help:[63,8,1,""],get_option_order:[63,8,1,""],getopt:[63,8,1,""]},"distutils.file_util":{copy_file:[63,9,1,""],move_file:[63,9,1,""],write_file:[63,9,1,""]},"distutils.sysconfig":{EXEC_PREFIX:[63,11,1,""],PREFIX:[63,11,1,""],customize_compiler:[63,9,1,""],get_config_h_filename:[63,9,1,""],get_config_var:[63,9,1,""],get_config_vars:[63,9,1,""],get_makefile_filename:[63,9,1,""],get_python_inc:[63,9,1,""],get_python_lib:[63,9,1,""],set_python_build:[63,9,1,""]},"distutils.text_file":{TextFile:[63,6,1,""]},"distutils.text_file.TextFile":{close:[63,8,1,""],open:[63,8,1,""],readline:[63,8,1,""],readlines:[63,8,1,""],unreadline:[63,8,1,""],warn:[63,8,1,""]},"distutils.util":{byte_compile:[63,9,1,""],change_root:[63,9,1,""],check_environ:[63,9,1,""],convert_path:[63,9,1,""],execute:[63,9,1,""],get_platform:[63,9,1,""],rfc822_escape:[63,9,1,""],split_quoted:[63,9,1,""],strtobool:[63,9,1,""],subst_vars:[63,9,1,""]},"dl.dl":{call:[185,8,1,""],close:[185,8,1,""],sym:[185,8,1,""]},"doctest.DocTest":{docstring:[186,7,1,""],examples:[186,7,1,""],filename:[186,7,1,""],globs:[186,7,1,""],lineno:[186,7,1,""],name:[186,7,1,""]},"doctest.DocTestFailure":{example:[186,7,1,""],got:[186,7,1,""],test:[186,7,1,""]},"doctest.DocTestFinder":{find:[186,8,1,""]},"doctest.DocTestParser":{get_doctest:[186,8,1,""],get_examples:[186,8,1,""],parse:[186,8,1,""]},"doctest.DocTestRunner":{report_failure:[186,8,1,""],report_start:[186,8,1,""],report_success:[186,8,1,""],report_unexpected_exception:[186,8,1,""],run:[186,8,1,""],summarize:[186,8,1,""]},"doctest.Example":{exc_msg:[186,7,1,""],indent:[186,7,1,""],lineno:[186,7,1,""],options:[186,7,1,""],source:[186,7,1,""],want:[186,7,1,""]},"doctest.OutputChecker":{check_output:[186,8,1,""],output_difference:[186,8,1,""]},"doctest.UnexpectedException":{example:[186,7,1,""],exc_info:[186,7,1,""],test:[186,7,1,""]},"dumbdbm.dumbdbm":{sync:[188,8,1,""]},"email.charset":{Charset:[194,6,1,""],add_alias:[194,9,1,""],add_charset:[194,9,1,""],add_codec:[194,9,1,""]},"email.charset.Charset":{__eq__:[194,8,1,""],__ne__:[194,8,1,""],__str__:[194,8,1,""],body_encode:[194,8,1,""],body_encoding:[194,7,1,""],convert:[194,8,1,""],encoded_header_len:[194,8,1,""],from_splittable:[194,8,1,""],get_body_encoding:[194,8,1,""],get_output_charset:[194,8,1,""],header_encode:[194,8,1,""],header_encoding:[194,7,1,""],input_charset:[194,7,1,""],input_codec:[194,7,1,""],output_charset:[194,7,1,""],output_codec:[194,7,1,""],to_splittable:[194,8,1,""]},"email.encoders":{encode_7or8bit:[195,9,1,""],encode_base64:[195,9,1,""],encode_noop:[195,9,1,""],encode_quopri:[195,9,1,""]},"email.errors":{BoundaryError:[196,10,1,""],HeaderParseError:[196,10,1,""],MessageError:[196,10,1,""],MessageParseError:[196,10,1,""],MultipartConversionError:[196,10,1,""]},"email.generator":{DecodedGenerator:[197,6,1,""],Generator:[197,6,1,""]},"email.generator.Generator":{clone:[197,8,1,""],flatten:[197,8,1,""],write:[197,8,1,""]},"email.header":{Header:[198,6,1,""],decode_header:[198,9,1,""],make_header:[198,9,1,""]},"email.header.Header":{__eq__:[198,8,1,""],__ne__:[198,8,1,""],__str__:[198,8,1,""],__unicode__:[198,8,1,""],append:[198,8,1,""],encode:[198,8,1,""]},"email.iterators":{_structure:[199,9,1,""],body_line_iterator:[199,9,1,""],typed_subpart_iterator:[199,9,1,""]},"email.message":{Message:[200,6,1,""]},"email.message.Message":{__contains__:[200,8,1,""],__delitem__:[200,8,1,""],__getitem__:[200,8,1,""],__len__:[200,8,1,""],__setitem__:[200,8,1,""],__str__:[200,8,1,""],add_header:[200,8,1,""],as_string:[200,8,1,""],attach:[200,8,1,""],defects:[200,7,1,""],del_param:[200,8,1,""],epilogue:[200,7,1,""],get:[200,8,1,""],get_all:[200,8,1,""],get_boundary:[200,8,1,""],get_charset:[200,8,1,""],get_charsets:[200,8,1,""],get_content_charset:[200,8,1,""],get_content_maintype:[200,8,1,""],get_content_subtype:[200,8,1,""],get_content_type:[200,8,1,""],get_default_type:[200,8,1,""],get_filename:[200,8,1,""],get_param:[200,8,1,""],get_params:[200,8,1,""],get_payload:[200,8,1,""],get_unixfrom:[200,8,1,""],has_key:[200,8,1,""],is_multipart:[200,8,1,""],items:[200,8,1,""],keys:[200,8,1,""],preamble:[200,7,1,""],replace_header:[200,8,1,""],set_boundary:[200,8,1,""],set_charset:[200,8,1,""],set_default_type:[200,8,1,""],set_param:[200,8,1,""],set_payload:[200,8,1,""],set_type:[200,8,1,""],set_unixfrom:[200,8,1,""],values:[200,8,1,""],walk:[200,8,1,""]},"email.mime.application":{MIMEApplication:[201,6,1,""]},"email.mime.audio":{MIMEAudio:[201,6,1,""]},"email.mime.base":{MIMEBase:[201,6,1,""]},"email.mime.image":{MIMEImage:[201,6,1,""]},"email.mime.message":{MIMEMessage:[201,6,1,""]},"email.mime.multipart":{MIMEMultipart:[201,6,1,""]},"email.mime.nonmultipart":{MIMENonMultipart:[201,6,1,""]},"email.mime.text":{MIMEText:[201,6,1,""]},"email.parser":{FeedParser:[202,6,1,""],Parser:[202,6,1,""]},"email.parser.FeedParser":{close:[202,8,1,""],feed:[202,8,1,""]},"email.parser.Parser":{parse:[202,8,1,""],parsestr:[202,8,1,""]},"email.utils":{collapse_rfc2231_value:[203,9,1,""],decode_params:[203,9,1,""],decode_rfc2231:[203,9,1,""],encode_rfc2231:[203,9,1,""],formataddr:[203,9,1,""],formatdate:[203,9,1,""],getaddresses:[203,9,1,""],make_msgid:[203,9,1,""],mktime_tz:[203,9,1,""],parseaddr:[203,9,1,""],parsedate:[203,9,1,""],parsedate_tz:[203,9,1,""],quote:[203,9,1,""],unquote:[203,9,1,""]},"encodings.idna":{ToASCII:[150,9,1,""],ToUnicode:[150,9,1,""],nameprep:[150,9,1,""]},"exceptions.BaseException":{args:[206,7,1,""]},"exceptions.UnicodeError":{encoding:[206,7,1,""],end:[206,7,1,""],object:[206,7,1,""],reason:[206,7,1,""],start:[206,7,1,""]},"filecmp.dircmp":{common:[208,7,1,""],common_dirs:[208,7,1,""],common_files:[208,7,1,""],common_funny:[208,7,1,""],diff_files:[208,7,1,""],funny_files:[208,7,1,""],left:[208,7,1,""],left_list:[208,7,1,""],left_only:[208,7,1,""],report:[208,8,1,""],report_full_closure:[208,8,1,""],report_partial_closure:[208,8,1,""],right:[208,7,1,""],right_list:[208,7,1,""],right_only:[208,7,1,""],same_files:[208,7,1,""],subdirs:[208,7,1,""]},"fl.form":{activate_form:[212,8,1,""],add_box:[212,8,1,""],add_browser:[212,8,1,""],add_button:[212,8,1,""],add_choice:[212,8,1,""],add_clock:[212,8,1,""],add_counter:[212,8,1,""],add_dial:[212,8,1,""],add_input:[212,8,1,""],add_lightbutton:[212,8,1,""],add_menu:[212,8,1,""],add_positioner:[212,8,1,""],add_roundbutton:[212,8,1,""],add_slider:[212,8,1,""],add_text:[212,8,1,""],add_timer:[212,8,1,""],add_valslider:[212,8,1,""],bgn_group:[212,8,1,""],deactivate_form:[212,8,1,""],end_group:[212,8,1,""],find_first:[212,8,1,""],find_last:[212,8,1,""],freeze_form:[212,8,1,""],hide_form:[212,8,1,""],redraw_form:[212,8,1,""],set_form_position:[212,8,1,""],show_form:[212,8,1,""],unfreeze_form:[212,8,1,""]},"float":{as_integer_ratio:[368,8,1,""],fromhex:[368,8,1,""],hex:[368,8,1,""],is_integer:[368,8,1,""]},"formatter.formatter":{add_flowing_data:[215,8,1,""],add_hor_rule:[215,8,1,""],add_label_data:[215,8,1,""],add_line_break:[215,8,1,""],add_literal_data:[215,8,1,""],assert_line_data:[215,8,1,""],end_paragraph:[215,8,1,""],flush_softspace:[215,8,1,""],pop_alignment:[215,8,1,""],pop_font:[215,8,1,""],pop_margin:[215,8,1,""],pop_style:[215,8,1,""],push_alignment:[215,8,1,""],push_font:[215,8,1,""],push_margin:[215,8,1,""],push_style:[215,8,1,""],set_spacing:[215,8,1,""],writer:[215,7,1,""]},"formatter.writer":{flush:[215,8,1,""],new_alignment:[215,8,1,""],new_font:[215,8,1,""],new_margin:[215,8,1,""],new_spacing:[215,8,1,""],new_styles:[215,8,1,""],send_flowing_data:[215,8,1,""],send_hor_rule:[215,8,1,""],send_label_data:[215,8,1,""],send_line_break:[215,8,1,""],send_literal_data:[215,8,1,""],send_paragraph:[215,8,1,""]},"fractions.Fraction":{from_decimal:[218,8,1,""],from_float:[218,8,1,""],limit_denominator:[218,8,1,""]},"ftplib.FTP":{"delete":[221,8,1,""],abort:[221,8,1,""],close:[221,8,1,""],connect:[221,8,1,""],cwd:[221,8,1,""],dir:[221,8,1,""],getwelcome:[221,8,1,""],login:[221,8,1,""],mkd:[221,8,1,""],nlst:[221,8,1,""],ntransfercmd:[221,8,1,""],pwd:[221,8,1,""],quit:[221,8,1,""],rename:[221,8,1,""],retrbinary:[221,8,1,""],retrlines:[221,8,1,""],rmd:[221,8,1,""],sendcmd:[221,8,1,""],set_debuglevel:[221,8,1,""],set_pasv:[221,8,1,""],size:[221,8,1,""],storbinary:[221,8,1,""],storlines:[221,8,1,""],transfercmd:[221,8,1,""],voidcmd:[221,8,1,""]},"ftplib.FTP_TLS":{auth:[221,8,1,""],prot_c:[221,8,1,""],prot_p:[221,8,1,""],ssl_version:[221,7,1,""]},"functools.partial":{args:[223,7,1,""],func:[223,7,1,""],keywords:[223,7,1,""]},"gettext.GNUTranslations":{gettext:[230,8,1,""],lgettext:[230,8,1,""],lngettext:[230,8,1,""],ngettext:[230,8,1,""],ugettext:[230,8,1,""],ungettext:[230,8,1,""]},"gettext.NullTranslations":{_parse:[230,8,1,""],add_fallback:[230,8,1,""],charset:[230,8,1,""],gettext:[230,8,1,""],info:[230,8,1,""],install:[230,8,1,""],lgettext:[230,8,1,""],lngettext:[230,8,1,""],ngettext:[230,8,1,""],output_charset:[230,8,1,""],set_output_charset:[230,8,1,""],ugettext:[230,8,1,""],ungettext:[230,8,1,""]},"hashlib.hash":{block_size:[235,11,1,""],copy:[235,8,1,""],digest:[235,8,1,""],digest_size:[235,11,1,""],hexdigest:[235,8,1,""],update:[235,8,1,""]},"hashlib.hashlib":{algorithms:[235,11,1,""]},"hmac.HMAC":{copy:[237,8,1,""],digest:[237,8,1,""],hexdigest:[237,8,1,""],update:[237,8,1,""]},"hotshot.Profile":{addinfo:[238,8,1,""],close:[238,8,1,""],fileno:[238,8,1,""],run:[238,8,1,""],runcall:[238,8,1,""],runctx:[238,8,1,""],start:[238,8,1,""],stop:[238,8,1,""]},"hotshot.stats":{load:[238,9,1,""]},"htmllib.HTMLParser":{anchor_bgn:[239,8,1,""],anchor_end:[239,8,1,""],formatter:[239,7,1,""],handle_image:[239,8,1,""],nofill:[239,7,1,""],save_bgn:[239,8,1,""],save_end:[239,8,1,""]},"httplib.HTTPConnection":{close:[241,8,1,""],connect:[241,8,1,""],endheaders:[241,8,1,""],getresponse:[241,8,1,""],putheader:[241,8,1,""],putrequest:[241,8,1,""],request:[241,8,1,""],send:[241,8,1,""],set_debuglevel:[241,8,1,""],set_tunnel:[241,8,1,""]},"httplib.HTTPResponse":{fileno:[241,8,1,""],getheader:[241,8,1,""],getheaders:[241,8,1,""],msg:[241,7,1,""],read:[241,8,1,""],reason:[241,7,1,""],status:[241,7,1,""],version:[241,7,1,""]},"ic.IC":{launchurl:[243,8,1,""],mapfile:[243,8,1,""],maptypecreator:[243,8,1,""],parseurl:[243,8,1,""],settypecreator:[243,8,1,""]},"imaplib.IMAP4":{"delete":[246,8,1,""],PROTOCOL_VERSION:[246,7,1,""],abort:[246,10,1,""],append:[246,8,1,""],authenticate:[246,8,1,""],check:[246,8,1,""],close:[246,8,1,""],copy:[246,8,1,""],create:[246,8,1,""],debug:[246,7,1,""],deleteacl:[246,8,1,""],error:[246,10,1,""],expunge:[246,8,1,""],fetch:[246,8,1,""],getacl:[246,8,1,""],getannotation:[246,8,1,""],getquota:[246,8,1,""],getquotaroot:[246,8,1,""],list:[246,8,1,""],login:[246,8,1,""],login_cram_md5:[246,8,1,""],logout:[246,8,1,""],lsub:[246,8,1,""],myrights:[246,8,1,""],namespace:[246,8,1,""],noop:[246,8,1,""],open:[246,8,1,""],partial:[246,8,1,""],proxyauth:[246,8,1,""],read:[246,8,1,""],readline:[246,8,1,""],readonly:[246,10,1,""],recent:[246,8,1,""],rename:[246,8,1,""],response:[246,8,1,""],search:[246,8,1,""],select:[246,8,1,""],send:[246,8,1,""],setacl:[246,8,1,""],setannotation:[246,8,1,""],setquota:[246,8,1,""],shutdown:[246,8,1,""],socket:[246,8,1,""],sort:[246,8,1,""],status:[246,8,1,""],store:[246,8,1,""],subscribe:[246,8,1,""],thread:[246,8,1,""],uid:[246,8,1,""],unsubscribe:[246,8,1,""],xatom:[246,8,1,""]},"imaplib.IMAP4_SSL":{ssl:[246,8,1,""]},"imp.NullImporter":{find_module:[249,8,1,""]},"imputil.BuiltinImporter":{get_code:[251,8,1,""]},"imputil.DynLoadSuffixImporter":{import_file:[251,8,1,""]},"imputil.ImportManager":{add_suffix:[251,8,1,""],install:[251,8,1,""],uninstall:[251,8,1,""]},"imputil.Importer":{get_code:[251,8,1,""],import_top:[251,8,1,""]},"int":{bit_length:[368,8,1,""]},"io.BlockingIOError":{characters_written:[256,7,1,""]},"io.BufferedIOBase":{detach:[256,8,1,""],raw:[256,7,1,""],read1:[256,8,1,""],read:[256,8,1,""],readinto:[256,8,1,""],write:[256,8,1,""]},"io.BufferedReader":{peek:[256,8,1,""],read1:[256,8,1,""],read:[256,8,1,""]},"io.BufferedWriter":{flush:[256,8,1,""],write:[256,8,1,""]},"io.BytesIO":{getvalue:[256,8,1,""],read1:[256,8,1,""]},"io.FileIO":{mode:[256,7,1,""],name:[256,7,1,""]},"io.IOBase":{__del__:[256,8,1,""],close:[256,8,1,""],closed:[256,7,1,""],fileno:[256,8,1,""],flush:[256,8,1,""],isatty:[256,8,1,""],readable:[256,8,1,""],readline:[256,8,1,""],readlines:[256,8,1,""],seek:[256,8,1,""],seekable:[256,8,1,""],tell:[256,8,1,""],truncate:[256,8,1,""],writable:[256,8,1,""],writelines:[256,8,1,""]},"io.RawIOBase":{read:[256,8,1,""],readall:[256,8,1,""],readinto:[256,8,1,""],write:[256,8,1,""]},"io.StringIO":{getvalue:[256,8,1,""]},"io.TextIOBase":{buffer:[256,7,1,""],detach:[256,8,1,""],encoding:[256,7,1,""],errors:[256,7,1,""],newlines:[256,7,1,""],read:[256,8,1,""],readline:[256,8,1,""],seek:[256,8,1,""],tell:[256,8,1,""],write:[256,8,1,""]},"io.TextIOWrapper":{line_buffering:[256,7,1,""]},"itertools.chain":{from_iterable:[258,12,1,""]},"json.JSONDecoder":{decode:[260,8,1,""],raw_decode:[260,8,1,""]},"json.JSONEncoder":{"default":[260,8,1,""],encode:[260,8,1,""],iterencode:[260,8,1,""]},"logging.FileHandler":{close:[267,8,1,""],emit:[267,8,1,""]},"logging.Filter":{filter:[265,8,1,""]},"logging.Formatter":{format:[265,8,1,""],formatException:[265,8,1,""],formatTime:[265,8,1,""]},"logging.Handler":{__init__:[265,8,1,""],acquire:[265,8,1,""],addFilter:[265,8,1,""],close:[265,8,1,""],createLock:[265,8,1,""],emit:[265,8,1,""],filter:[265,8,1,""],flush:[265,8,1,""],format:[265,8,1,""],handle:[265,8,1,""],handleError:[265,8,1,""],release:[265,8,1,""],removeFilter:[265,8,1,""],setFormatter:[265,8,1,""],setLevel:[265,8,1,""]},"logging.LogRecord":{getMessage:[265,8,1,""]},"logging.Logger":{addFilter:[265,8,1,""],addHandler:[265,8,1,""],critical:[265,8,1,""],debug:[265,8,1,""],error:[265,8,1,""],exception:[265,8,1,""],filter:[265,8,1,""],findCaller:[265,8,1,""],getChild:[265,8,1,""],getEffectiveLevel:[265,8,1,""],handle:[265,8,1,""],info:[265,8,1,""],isEnabledFor:[265,8,1,""],log:[265,8,1,""],makeRecord:[265,8,1,""],propagate:[265,7,1,""],removeFilter:[265,8,1,""],removeHandler:[265,8,1,""],setLevel:[265,8,1,""],warning:[265,8,1,""]},"logging.LoggerAdapter":{process:[265,8,1,""]},"logging.NullHandler":{createLock:[267,8,1,""],emit:[267,8,1,""],handle:[267,8,1,""]},"logging.StreamHandler":{emit:[267,8,1,""],flush:[267,8,1,""]},"logging.config":{dictConfig:[266,9,1,""],fileConfig:[266,9,1,""],listen:[266,9,1,""],stopListening:[266,9,1,""]},"logging.handlers":{BufferingHandler:[267,6,1,""],DatagramHandler:[267,6,1,""],HTTPHandler:[267,6,1,""],MemoryHandler:[267,6,1,""],NTEventLogHandler:[267,6,1,""],RotatingFileHandler:[267,6,1,""],SMTPHandler:[267,6,1,""],SocketHandler:[267,6,1,""],SysLogHandler:[267,6,1,""],TimedRotatingFileHandler:[267,6,1,""],WatchedFileHandler:[267,6,1,""]},"logging.handlers.BufferingHandler":{emit:[267,8,1,""],flush:[267,8,1,""],shouldFlush:[267,8,1,""]},"logging.handlers.DatagramHandler":{emit:[267,8,1,""],makeSocket:[267,8,1,""],send:[267,8,1,""]},"logging.handlers.HTTPHandler":{emit:[267,8,1,""],mapLogRecord:[267,8,1,""]},"logging.handlers.MemoryHandler":{close:[267,8,1,""],flush:[267,8,1,""],setTarget:[267,8,1,""],shouldFlush:[267,8,1,""]},"logging.handlers.NTEventLogHandler":{close:[267,8,1,""],emit:[267,8,1,""],getEventCategory:[267,8,1,""],getEventType:[267,8,1,""],getMessageID:[267,8,1,""]},"logging.handlers.RotatingFileHandler":{doRollover:[267,8,1,""],emit:[267,8,1,""]},"logging.handlers.SMTPHandler":{emit:[267,8,1,""],getSubject:[267,8,1,""]},"logging.handlers.SocketHandler":{close:[267,8,1,""],createSocket:[267,8,1,""],emit:[267,8,1,""],handleError:[267,8,1,""],makePickle:[267,8,1,""],makeSocket:[267,8,1,""],send:[267,8,1,""]},"logging.handlers.SysLogHandler":{close:[267,8,1,""],emit:[267,8,1,""],encodePriority:[267,8,1,""],mapPriority:[267,8,1,""]},"logging.handlers.TimedRotatingFileHandler":{doRollover:[267,8,1,""],emit:[267,8,1,""]},"logging.handlers.WatchedFileHandler":{emit:[267,8,1,""]},"logging.logging.Formatter":{__init__:[98,8,1,""]},"long":{bit_length:[368,8,1,""]},"mailbox.Babyl":{get_file:[273,8,1,""],get_labels:[273,8,1,""],lock:[273,8,1,""],unlock:[273,8,1,""]},"mailbox.BabylMessage":{add_label:[273,8,1,""],get_labels:[273,8,1,""],get_visible:[273,8,1,""],remove_label:[273,8,1,""],set_labels:[273,8,1,""],set_visible:[273,8,1,""],update_visible:[273,8,1,""]},"mailbox.MH":{__delitem__:[273,8,1,""],add_folder:[273,8,1,""],close:[273,8,1,""],discard:[273,8,1,""],flush:[273,8,1,""],get_file:[273,8,1,""],get_folder:[273,8,1,""],get_sequences:[273,8,1,""],list_folders:[273,8,1,""],lock:[273,8,1,""],pack:[273,8,1,""],remove:[273,8,1,""],remove_folder:[273,8,1,""],set_sequences:[273,8,1,""],unlock:[273,8,1,""]},"mailbox.MHMessage":{add_sequence:[273,8,1,""],get_sequences:[273,8,1,""],remove_sequence:[273,8,1,""],set_sequences:[273,8,1,""]},"mailbox.MMDF":{get_file:[273,8,1,""],lock:[273,8,1,""],unlock:[273,8,1,""]},"mailbox.MMDFMessage":{add_flag:[273,8,1,""],get_flags:[273,8,1,""],get_from:[273,8,1,""],remove_flag:[273,8,1,""],set_flags:[273,8,1,""],set_from:[273,8,1,""]},"mailbox.Mailbox":{__contains__:[273,8,1,""],__delitem__:[273,8,1,""],__getitem__:[273,8,1,""],__iter__:[273,8,1,""],__len__:[273,8,1,""],__setitem__:[273,8,1,""],add:[273,8,1,""],clear:[273,8,1,""],close:[273,8,1,""],discard:[273,8,1,""],flush:[273,8,1,""],get:[273,8,1,""],get_file:[273,8,1,""],get_message:[273,8,1,""],get_string:[273,8,1,""],has_key:[273,8,1,""],items:[273,8,1,""],iteritems:[273,8,1,""],iterkeys:[273,8,1,""],itervalues:[273,8,1,""],keys:[273,8,1,""],lock:[273,8,1,""],pop:[273,8,1,""],popitem:[273,8,1,""],remove:[273,8,1,""],unlock:[273,8,1,""],update:[273,8,1,""],values:[273,8,1,""]},"mailbox.Maildir":{__setitem__:[273,8,1,""],add:[273,8,1,""],add_folder:[273,8,1,""],clean:[273,8,1,""],close:[273,8,1,""],flush:[273,8,1,""],get_file:[273,8,1,""],get_folder:[273,8,1,""],list_folders:[273,8,1,""],lock:[273,8,1,""],remove_folder:[273,8,1,""],unlock:[273,8,1,""],update:[273,8,1,""]},"mailbox.MaildirMessage":{add_flag:[273,8,1,""],get_date:[273,8,1,""],get_flags:[273,8,1,""],get_info:[273,8,1,""],get_subdir:[273,8,1,""],remove_flag:[273,8,1,""],set_date:[273,8,1,""],set_flags:[273,8,1,""],set_info:[273,8,1,""],set_subdir:[273,8,1,""]},"mailbox.mbox":{get_file:[273,8,1,""],lock:[273,8,1,""],unlock:[273,8,1,""]},"mailbox.mboxMessage":{add_flag:[273,8,1,""],get_flags:[273,8,1,""],get_from:[273,8,1,""],remove_flag:[273,8,1,""],set_flags:[273,8,1,""],set_from:[273,8,1,""]},"mailbox.oldmailbox":{next:[273,8,1,""]},"md5.md5":{copy:[278,8,1,""],digest:[278,8,1,""],hexdigest:[278,8,1,""],update:[278,8,1,""]},"mhlib.Folder":{copymessage:[279,8,1,""],error:[279,8,1,""],getcurrent:[279,8,1,""],getfullname:[279,8,1,""],getlast:[279,8,1,""],getmessagefilename:[279,8,1,""],getsequences:[279,8,1,""],getsequencesfilename:[279,8,1,""],listmessages:[279,8,1,""],movemessage:[279,8,1,""],parsesequence:[279,8,1,""],putsequences:[279,8,1,""],refilemessages:[279,8,1,""],removemessages:[279,8,1,""],setcurrent:[279,8,1,""],setlast:[279,8,1,""]},"mhlib.MH":{deletefolder:[279,8,1,""],error:[279,8,1,""],getcontext:[279,8,1,""],getpath:[279,8,1,""],getprofile:[279,8,1,""],listallfolders:[279,8,1,""],listallsubfolders:[279,8,1,""],listfolders:[279,8,1,""],listsubfolders:[279,8,1,""],makefolder:[279,8,1,""],openfolder:[279,8,1,""],setcontext:[279,8,1,""]},"mhlib.Message":{openmessage:[279,8,1,""]},"mimetools.Message":{getencoding:[280,8,1,""],getmaintype:[280,8,1,""],getparam:[280,8,1,""],getplist:[280,8,1,""],getsubtype:[280,8,1,""],gettype:[280,8,1,""]},"mimetypes.MimeTypes":{encodings_map:[281,7,1,""],guess_all_extensions:[281,8,1,""],guess_extension:[281,8,1,""],guess_type:[281,8,1,""],read:[281,8,1,""],read_windows_registry:[281,8,1,""],readfp:[281,8,1,""],suffix_map:[281,7,1,""],types_map:[281,7,1,""],types_map_inv:[281,7,1,""]},"mmap.mmap":{close:[287,8,1,""],find:[287,8,1,""],flush:[287,8,1,""],move:[287,8,1,""],read:[287,8,1,""],read_byte:[287,8,1,""],readline:[287,8,1,""],resize:[287,8,1,""],rfind:[287,8,1,""],seek:[287,8,1,""],size:[287,8,1,""],tell:[287,8,1,""],write:[287,8,1,""],write_byte:[287,8,1,""]},"modulefinder.ModuleFinder":{modules:[288,7,1,""],report:[288,8,1,""],run_script:[288,8,1,""]},"msilib.CAB":{append:[290,8,1,""],commit:[290,8,1,""]},"msilib.Control":{condition:[290,8,1,""],event:[290,8,1,""],mapping:[290,8,1,""]},"msilib.Database":{Commit:[290,8,1,""],GetSummaryInformation:[290,8,1,""],OpenView:[290,8,1,""]},"msilib.Dialog":{bitmap:[290,8,1,""],checkbox:[290,8,1,""],control:[290,8,1,""],line:[290,8,1,""],pushbutton:[290,8,1,""],radiogroup:[290,8,1,""],text:[290,8,1,""]},"msilib.Directory":{add_file:[290,8,1,""],glob:[290,8,1,""],remove_pyc:[290,8,1,""],start_component:[290,8,1,""]},"msilib.Feature":{set_current:[290,8,1,""]},"msilib.RadioButtonGroup":{add:[290,8,1,""]},"msilib.Record":{ClearData:[290,8,1,""],GetFieldCount:[290,8,1,""],GetInteger:[290,8,1,""],GetString:[290,8,1,""],SetInteger:[290,8,1,""],SetStream:[290,8,1,""],SetString:[290,8,1,""]},"msilib.SummaryInformation":{GetProperty:[290,8,1,""],GetPropertyCount:[290,8,1,""],Persist:[290,8,1,""],SetProperty:[290,8,1,""]},"msilib.View":{Close:[290,8,1,""],Execute:[290,8,1,""],Fetch:[290,8,1,""],GetColumnInfo:[290,8,1,""],Modify:[290,8,1,""]},"multifile.MultiFile":{end_marker:[292,8,1,""],is_data:[292,8,1,""],last:[292,7,1,""],level:[292,7,1,""],next:[292,8,1,""],pop:[292,8,1,""],push:[292,8,1,""],read:[292,8,1,""],readline:[292,8,1,""],readlines:[292,8,1,""],section_divider:[292,8,1,""],seek:[292,8,1,""],tell:[292,8,1,""]},"multiprocessing.JoinableQueue":{join:[293,8,1,""],task_done:[293,8,1,""]},"multiprocessing.Lock":{acquire:[293,8,1,""],release:[293,8,1,""]},"multiprocessing.Process":{authkey:[293,7,1,""],daemon:[293,7,1,""],exitcode:[293,7,1,""],is_alive:[293,8,1,""],join:[293,8,1,""],name:[293,7,1,""],pid:[293,7,1,""],run:[293,8,1,""],start:[293,8,1,""],terminate:[293,8,1,""]},"multiprocessing.Queue":{cancel_join_thread:[293,8,1,""],close:[293,8,1,""],empty:[293,8,1,""],full:[293,8,1,""],get:[293,8,1,""],get_nowait:[293,8,1,""],join_thread:[293,8,1,""],put:[293,8,1,""],put_nowait:[293,8,1,""],qsize:[293,8,1,""]},"multiprocessing.RLock":{acquire:[293,8,1,""],release:[293,8,1,""]},"multiprocessing.connection":{AuthenticationError:[293,10,1,""],BufferTooShort:[293,10,1,""],Client:[293,9,1,""],Listener:[293,6,1,""],ProcessError:[293,10,1,""],TimeoutError:[293,10,1,""],answer_challenge:[293,9,1,""],deliver_challenge:[293,9,1,""]},"multiprocessing.connection.Listener":{accept:[293,8,1,""],address:[293,7,1,""],close:[293,8,1,""],last_accepted:[293,7,1,""]},"multiprocessing.managers":{BaseManager:[293,6,1,""],BaseProxy:[293,6,1,""],Namespace:[293,6,1,""],SyncManager:[293,6,1,""]},"multiprocessing.managers.BaseManager":{address:[293,7,1,""],connect:[293,8,1,""],get_server:[293,8,1,""],register:[293,8,1,""],shutdown:[293,8,1,""],start:[293,8,1,""]},"multiprocessing.managers.BaseProxy":{__repr__:[293,8,1,""],__str__:[293,8,1,""],_callmethod:[293,8,1,""],_getvalue:[293,8,1,""]},"multiprocessing.managers.SyncManager":{Array:[293,8,1,""],BoundedSemaphore:[293,8,1,""],Condition:[293,8,1,""],Event:[293,8,1,""],Lock:[293,8,1,""],Namespace:[293,8,1,""],Queue:[293,8,1,""],RLock:[293,8,1,""],Semaphore:[293,8,1,""],Value:[293,8,1,""],dict:[293,8,1,""],list:[293,8,1,""]},"multiprocessing.multiprocessing.queues":{SimpleQueue:[293,6,1,""]},"multiprocessing.multiprocessing.queues.SimpleQueue":{empty:[293,8,1,""],get:[293,8,1,""],put:[293,8,1,""]},"multiprocessing.pool":{AsyncResult:[293,6,1,""]},"multiprocessing.pool.AsyncResult":{get:[293,8,1,""],ready:[293,8,1,""],successful:[293,8,1,""],wait:[293,8,1,""]},"multiprocessing.pool.multiprocessing":{Pool:[293,6,1,""]},"multiprocessing.pool.multiprocessing.Pool":{apply:[293,8,1,""],apply_async:[293,8,1,""],close:[293,8,1,""],imap:[293,8,1,""],imap_unordered:[293,8,1,""],join:[293,8,1,""],map:[293,8,1,""],map_async:[293,8,1,""],terminate:[293,8,1,""]},"multiprocessing.sharedctypes":{"synchronized":[293,9,1,""],Array:[293,9,1,""],RawArray:[293,9,1,""],RawValue:[293,9,1,""],Value:[293,9,1,""],copy:[293,9,1,""]},"multiprocessing.sharedctypes.multiprocessing":{Manager:[293,9,1,""]},"mutex.mutex":{lock:[294,8,1,""],test:[294,8,1,""],testandset:[294,8,1,""],unlock:[294,8,1,""]},"netrc.netrc":{__repr__:[296,8,1,""],authenticators:[296,8,1,""],hosts:[296,7,1,""],macros:[296,7,1,""]},"new":{"function":[297,9,1,""],classobj:[297,9,1,""],code:[297,9,1,""],instance:[297,9,1,""],instancemethod:[297,9,1,""],module:[297,9,1,""]},"nntplib.NNTP":{article:[299,8,1,""],body:[299,8,1,""],date:[299,8,1,""],description:[299,8,1,""],descriptions:[299,8,1,""],getwelcome:[299,8,1,""],group:[299,8,1,""],head:[299,8,1,""],help:[299,8,1,""],ihave:[299,8,1,""],last:[299,8,1,""],list:[299,8,1,""],newgroups:[299,8,1,""],newnews:[299,8,1,""],next:[299,8,1,""],post:[299,8,1,""],quit:[299,8,1,""],set_debuglevel:[299,8,1,""],slave:[299,8,1,""],stat:[299,8,1,""],xgtitle:[299,8,1,""],xhdr:[299,8,1,""],xover:[299,8,1,""],xpath:[299,8,1,""]},"numbers.Complex":{conjugate:[300,8,1,""],imag:[300,7,1,""],real:[300,7,1,""]},"numbers.Rational":{denominator:[300,7,1,""],numerator:[300,7,1,""]},"optparse.Option":{"const":[303,7,1,""],"default":[303,7,1,""],ACTIONS:[303,7,1,""],ALWAYS_TYPED_ACTIONS:[303,7,1,""],STORE_ACTIONS:[303,7,1,""],TYPED_ACTIONS:[303,7,1,""],TYPES:[303,7,1,""],TYPE_CHECKER:[303,7,1,""],action:[303,7,1,""],callback:[303,7,1,""],callback_args:[303,7,1,""],callback_kwargs:[303,7,1,""],choices:[303,7,1,""],dest:[303,7,1,""],help:[303,7,1,""],metavar:[303,7,1,""],nargs:[303,7,1,""],type:[303,7,1,""]},"optparse.OptionParser":{add_option:[303,8,1,""],disable_interspersed_args:[303,8,1,""],enable_interspersed_args:[303,8,1,""],get_option:[303,8,1,""],get_option_group:[303,8,1,""],get_usage:[303,8,1,""],get_version:[303,8,1,""],has_option:[303,8,1,""],print_usage:[303,8,1,""],print_version:[303,8,1,""],remove_option:[303,8,1,""],set_defaults:[303,8,1,""],set_usage:[303,8,1,""]},"os.path":{abspath:[305,9,1,""],basename:[305,9,1,""],commonprefix:[305,9,1,""],dirname:[305,9,1,""],exists:[305,9,1,""],expanduser:[305,9,1,""],expandvars:[305,9,1,""],getatime:[305,9,1,""],getctime:[305,9,1,""],getmtime:[305,9,1,""],getsize:[305,9,1,""],isabs:[305,9,1,""],isdir:[305,9,1,""],isfile:[305,9,1,""],islink:[305,9,1,""],ismount:[305,9,1,""],join:[305,9,1,""],lexists:[305,9,1,""],normcase:[305,9,1,""],normpath:[305,9,1,""],realpath:[305,9,1,""],relpath:[305,9,1,""],samefile:[305,9,1,""],sameopenfile:[305,9,1,""],samestat:[305,9,1,""],split:[305,9,1,""],splitdrive:[305,9,1,""],splitext:[305,9,1,""],splitunc:[305,9,1,""],supports_unicode_filenames:[305,11,1,""],walk:[305,9,1,""]},"ossaudiodev.oss_audio_device":{bufsize:[306,8,1,""],channels:[306,8,1,""],close:[306,8,1,""],closed:[306,7,1,""],fileno:[306,8,1,""],getfmts:[306,8,1,""],mode:[306,7,1,""],name:[306,7,1,""],nonblock:[306,8,1,""],obufcount:[306,8,1,""],obuffree:[306,8,1,""],post:[306,8,1,""],read:[306,8,1,""],reset:[306,8,1,""],setfmt:[306,8,1,""],setparameters:[306,8,1,""],speed:[306,8,1,""],sync:[306,8,1,""],write:[306,8,1,""],writeall:[306,8,1,""]},"ossaudiodev.oss_mixer_device":{close:[306,8,1,""],controls:[306,8,1,""],fileno:[306,8,1,""],get:[306,8,1,""],get_recsrc:[306,8,1,""],reccontrols:[306,8,1,""],set:[306,8,1,""],set_recsrc:[306,8,1,""],stereocontrols:[306,8,1,""]},"parser.ST":{compile:[308,8,1,""],isexpr:[308,8,1,""],issuite:[308,8,1,""],tolist:[308,8,1,""],totuple:[308,8,1,""]},"pdb.Pdb":{run:[309,8,1,""],runcall:[309,8,1,""],runeval:[309,8,1,""],set_trace:[309,8,1,""]},"pickle.Pickler":{clear_memo:[311,8,1,""],dump:[311,8,1,""]},"pickle.Unpickler":{load:[311,8,1,""],noload:[311,8,1,""]},"pipes.Template":{append:[313,8,1,""],clone:[313,8,1,""],copy:[313,8,1,""],debug:[313,8,1,""],open:[313,8,1,""],prepend:[313,8,1,""],reset:[313,8,1,""]},"popen2.Popen3":{childerr:[317,7,1,""],fromchild:[317,7,1,""],pid:[317,7,1,""],poll:[317,8,1,""],tochild:[317,7,1,""],wait:[317,8,1,""]},"poplib.POP3":{apop:[318,8,1,""],dele:[318,8,1,""],getwelcome:[318,8,1,""],list:[318,8,1,""],noop:[318,8,1,""],pass_:[318,8,1,""],quit:[318,8,1,""],retr:[318,8,1,""],rpop:[318,8,1,""],rset:[318,8,1,""],set_debuglevel:[318,8,1,""],stat:[318,8,1,""],top:[318,8,1,""],uidl:[318,8,1,""],user:[318,8,1,""]},"posixfile.posixfile":{dup2:[320,8,1,""],dup:[320,8,1,""],file:[320,8,1,""],flags:[320,8,1,""],lock:[320,8,1,""]},"pprint.PrettyPrinter":{format:[321,8,1,""],isreadable:[321,8,1,""],isrecursive:[321,8,1,""],pformat:[321,8,1,""],pprint:[321,8,1,""]},"profile.Profile":{create_stats:[322,8,1,""],disable:[322,8,1,""],dump_stats:[322,8,1,""],enable:[322,8,1,""],print_stats:[322,8,1,""],run:[322,8,1,""],runcall:[322,8,1,""],runctx:[322,8,1,""]},"pstats.Stats":{add:[322,8,1,""],dump_stats:[322,8,1,""],print_callees:[322,8,1,""],print_callers:[322,8,1,""],print_stats:[322,8,1,""],reverse_order:[322,8,1,""],sort_stats:[322,8,1,""],strip_dirs:[322,8,1,""]},"pyclbr.Class":{"super":[326,7,1,""],file:[326,7,1,""],lineno:[326,7,1,""],methods:[326,7,1,""],module:[326,7,1,""],name:[326,7,1,""]},"pyclbr.Function":{file:[326,7,1,""],lineno:[326,7,1,""],module:[326,7,1,""],name:[326,7,1,""]},"re.MatchObject":{end:[333,8,1,""],endpos:[333,7,1,""],expand:[333,8,1,""],group:[333,8,1,""],groupdict:[333,8,1,""],groups:[333,8,1,""],lastgroup:[333,7,1,""],lastindex:[333,7,1,""],pos:[333,7,1,""],re:[333,7,1,""],span:[333,8,1,""],start:[333,8,1,""],string:[333,7,1,""]},"re.RegexObject":{findall:[333,8,1,""],finditer:[333,8,1,""],flags:[333,7,1,""],groupindex:[333,7,1,""],groups:[333,7,1,""],match:[333,8,1,""],pattern:[333,7,1,""],search:[333,8,1,""],split:[333,8,1,""],sub:[333,8,1,""],subn:[333,8,1,""]},"repr.Repr":{maxarray:[335,7,1,""],maxdeque:[335,7,1,""],maxdict:[335,7,1,""],maxfrozenset:[335,7,1,""],maxlevel:[335,7,1,""],maxlist:[335,7,1,""],maxlong:[335,7,1,""],maxother:[335,7,1,""],maxset:[335,7,1,""],maxstring:[335,7,1,""],maxtuple:[335,7,1,""],repr1:[335,8,1,""],repr:[335,8,1,""]},"rexec.RExec":{nok_builtin_names:[338,7,1,""],ok_builtin_modules:[338,7,1,""],ok_file_types:[338,7,1,""],ok_path:[338,7,1,""],ok_posix_names:[338,7,1,""],ok_sys_names:[338,7,1,""],r_eval:[338,8,1,""],r_exec:[338,8,1,""],r_execfile:[338,8,1,""],r_import:[338,8,1,""],r_open:[338,8,1,""],r_reload:[338,8,1,""],r_unload:[338,8,1,""],s_eval:[338,8,1,""],s_exec:[338,8,1,""],s_execfile:[338,8,1,""],s_import:[338,8,1,""],s_reload:[338,8,1,""],s_unload:[338,8,1,""]},"rfc822.AddressList":{__add__:[339,8,1,""],__iadd__:[339,8,1,""],__isub__:[339,8,1,""],__len__:[339,8,1,""],__str__:[339,8,1,""],__sub__:[339,8,1,""],addresslist:[339,7,1,""]},"rfc822.Message":{fp:[339,7,1,""],get:[339,8,1,""],getaddr:[339,8,1,""],getaddrlist:[339,8,1,""],getallmatchingheaders:[339,8,1,""],getdate:[339,8,1,""],getdate_tz:[339,8,1,""],getfirstmatchingheader:[339,8,1,""],getheader:[339,8,1,""],getrawheader:[339,8,1,""],headers:[339,7,1,""],iscomment:[339,8,1,""],isheader:[339,8,1,""],islast:[339,8,1,""],rewindbody:[339,8,1,""],unixfrom:[339,7,1,""]},"rlcompleter.Completer":{complete:[340,8,1,""]},"robotparser.RobotFileParser":{can_fetch:[341,8,1,""],modified:[341,8,1,""],mtime:[341,8,1,""],parse:[341,8,1,""],read:[341,8,1,""],set_url:[341,8,1,""]},"sched.scheduler":{cancel:[343,8,1,""],empty:[343,8,1,""],enter:[343,8,1,""],enterabs:[343,8,1,""],queue:[343,7,1,""],run:[343,8,1,""]},"select.epoll":{close:[345,8,1,""],fileno:[345,8,1,""],fromfd:[345,8,1,""],modify:[345,8,1,""],poll:[345,8,1,""],register:[345,8,1,""],unregister:[345,8,1,""]},"select.kevent":{data:[345,7,1,""],fflags:[345,7,1,""],filter:[345,7,1,""],flags:[345,7,1,""],ident:[345,7,1,""],udata:[345,7,1,""]},"select.kqueue":{close:[345,8,1,""],control:[345,8,1,""],fileno:[345,8,1,""],fromfd:[345,8,1,""]},"select.poll":{modify:[345,8,1,""],poll:[345,8,1,""],register:[345,8,1,""],unregister:[345,8,1,""]},"select.select":{PIPE_BUF:[345,7,1,""]},"sgmllib.SGMLParser":{close:[348,8,1,""],convert_charref:[348,8,1,""],convert_codepoint:[348,8,1,""],convert_entityref:[348,8,1,""],feed:[348,8,1,""],get_starttag_text:[348,8,1,""],handle_charref:[348,8,1,""],handle_comment:[348,8,1,""],handle_data:[348,8,1,""],handle_decl:[348,8,1,""],handle_endtag:[348,8,1,""],handle_entityref:[348,8,1,""],handle_starttag:[348,8,1,""],report_unbalanced:[348,8,1,""],reset:[348,8,1,""],setliteral:[348,8,1,""],setnomoretags:[348,8,1,""],unknown_charref:[348,8,1,""],unknown_endtag:[348,8,1,""],unknown_entityref:[348,8,1,""],unknown_starttag:[348,8,1,""]},"sha.sha":{copy:[349,8,1,""],digest:[349,8,1,""],hexdigest:[349,8,1,""],update:[349,8,1,""]},"shelve.Shelf":{close:[350,8,1,""],sync:[350,8,1,""]},"shlex.shlex":{commenters:[351,7,1,""],debug:[351,7,1,""],eof:[351,7,1,""],error_leader:[351,8,1,""],escape:[351,7,1,""],escapedquotes:[351,7,1,""],get_token:[351,8,1,""],infile:[351,7,1,""],instream:[351,7,1,""],lineno:[351,7,1,""],pop_source:[351,8,1,""],push_source:[351,8,1,""],push_token:[351,8,1,""],quotes:[351,7,1,""],read_token:[351,8,1,""],source:[351,7,1,""],sourcehook:[351,8,1,""],token:[351,7,1,""],whitespace:[351,7,1,""],whitespace_split:[351,7,1,""],wordchars:[351,7,1,""]},"smtpd.SMTPServer":{process_message:[357,8,1,""]},"smtplib.SMTP":{connect:[358,8,1,""],docmd:[358,8,1,""],ehlo:[358,8,1,""],ehlo_or_helo_if_needed:[358,8,1,""],has_extn:[358,8,1,""],helo:[358,8,1,""],login:[358,8,1,""],quit:[358,8,1,""],sendmail:[358,8,1,""],set_debuglevel:[358,8,1,""],starttls:[358,8,1,""],verify:[358,8,1,""]},"socket.socket":{accept:[360,8,1,""],bind:[360,8,1,""],close:[360,8,1,""],connect:[360,8,1,""],connect_ex:[360,8,1,""],family:[360,7,1,""],fileno:[360,8,1,""],getpeername:[360,8,1,""],getsockname:[360,8,1,""],getsockopt:[360,8,1,""],gettimeout:[360,8,1,""],ioctl:[360,8,1,""],listen:[360,8,1,""],makefile:[360,8,1,""],proto:[360,7,1,""],recv:[360,8,1,""],recv_into:[360,8,1,""],recvfrom:[360,8,1,""],recvfrom_into:[360,8,1,""],send:[360,8,1,""],sendall:[360,8,1,""],sendto:[360,8,1,""],setblocking:[360,8,1,""],setsockopt:[360,8,1,""],settimeout:[360,8,1,""],shutdown:[360,8,1,""],type:[360,7,1,""]},"sqlite3.Connection":{close:[364,8,1,""],commit:[364,8,1,""],create_aggregate:[364,8,1,""],create_collation:[364,8,1,""],create_function:[364,8,1,""],cursor:[364,8,1,""],enable_load_extension:[364,8,1,""],execute:[364,8,1,""],executemany:[364,8,1,""],executescript:[364,8,1,""],interrupt:[364,8,1,""],isolation_level:[364,7,1,""],iterdump:[364,7,1,""],load_extension:[364,8,1,""],rollback:[364,8,1,""],row_factory:[364,7,1,""],set_authorizer:[364,8,1,""],set_progress_handler:[364,8,1,""],text_factory:[364,7,1,""],total_changes:[364,7,1,""]},"sqlite3.Cursor":{connection:[364,7,1,""],description:[364,7,1,""],execute:[364,8,1,""],executemany:[364,8,1,""],executescript:[364,8,1,""],fetchall:[364,8,1,""],fetchmany:[364,8,1,""],fetchone:[364,8,1,""],lastrowid:[364,7,1,""],rowcount:[364,7,1,""]},"sqlite3.Row":{keys:[364,8,1,""]},"ssl.Purpose":{CLIENT_AUTH:[365,11,1,""],SERVER_AUTH:[365,11,1,""]},"ssl.SSLContext":{cert_store_stats:[365,8,1,""],check_hostname:[365,7,1,""],get_ca_certs:[365,8,1,""],load_cert_chain:[365,8,1,""],load_default_certs:[365,8,1,""],load_dh_params:[365,8,1,""],load_verify_locations:[365,8,1,""],options:[365,7,1,""],protocol:[365,7,1,""],session_stats:[365,8,1,""],set_alpn_protocols:[365,8,1,""],set_ciphers:[365,8,1,""],set_default_verify_paths:[365,8,1,""],set_ecdh_curve:[365,8,1,""],set_npn_protocols:[365,8,1,""],set_servername_callback:[365,8,1,""],verify_flags:[365,7,1,""],verify_mode:[365,7,1,""],wrap_socket:[365,8,1,""]},"ssl.SSLError":{library:[365,7,1,""],reason:[365,7,1,""]},"ssl.SSLSocket":{cipher:[365,8,1,""],compression:[365,8,1,""],context:[365,7,1,""],do_handshake:[365,8,1,""],get_channel_binding:[365,8,1,""],getpeercert:[365,8,1,""],selected_alpn_protocol:[365,8,1,""],selected_npn_protocol:[365,8,1,""],unwrap:[365,8,1,""],version:[365,8,1,""]},"string.Formatter":{check_unused_args:[369,8,1,""],convert_field:[369,8,1,""],format:[369,8,1,""],format_field:[369,8,1,""],get_field:[369,8,1,""],get_value:[369,8,1,""],parse:[369,8,1,""],vformat:[369,8,1,""]},"string.Template":{safe_substitute:[369,8,1,""],substitute:[369,8,1,""],template:[369,7,1,""]},"struct.Struct":{format:[373,7,1,""],pack:[373,8,1,""],pack_into:[373,8,1,""],size:[373,7,1,""],unpack:[373,8,1,""],unpack_from:[373,8,1,""]},"subprocess.CalledProcessError":{cmd:[374,7,1,""],output:[374,7,1,""],returncode:[374,7,1,""]},"subprocess.Popen":{communicate:[374,8,1,""],kill:[374,8,1,""],pid:[374,7,1,""],poll:[374,8,1,""],returncode:[374,7,1,""],send_signal:[374,8,1,""],stderr:[374,7,1,""],stdin:[374,7,1,""],stdout:[374,7,1,""],terminate:[374,8,1,""],wait:[374,8,1,""]},"subprocess.STARTUPINFO":{dwFlags:[374,7,1,""],hStdError:[374,7,1,""],hStdInput:[374,7,1,""],hStdOutput:[374,7,1,""],wShowWindow:[374,7,1,""]},"sunau.AU_read":{close:[376,8,1,""],getcompname:[376,8,1,""],getcomptype:[376,8,1,""],getframerate:[376,8,1,""],getmark:[376,8,1,""],getmarkers:[376,8,1,""],getnchannels:[376,8,1,""],getnframes:[376,8,1,""],getparams:[376,8,1,""],getsampwidth:[376,8,1,""],readframes:[376,8,1,""],rewind:[376,8,1,""],setpos:[376,8,1,""],tell:[376,8,1,""]},"sunau.AU_write":{close:[376,8,1,""],setcomptype:[376,8,1,""],setframerate:[376,8,1,""],setnchannels:[376,8,1,""],setnframes:[376,8,1,""],setparams:[376,8,1,""],setsampwidth:[376,8,1,""],tell:[376,8,1,""],writeframes:[376,8,1,""],writeframesraw:[376,8,1,""]},"symtable.Class":{get_methods:[379,8,1,""]},"symtable.Function":{get_frees:[379,8,1,""],get_globals:[379,8,1,""],get_locals:[379,8,1,""],get_parameters:[379,8,1,""]},"symtable.Symbol":{get_name:[379,8,1,""],get_namespace:[379,8,1,""],get_namespaces:[379,8,1,""],is_assigned:[379,8,1,""],is_declared_global:[379,8,1,""],is_free:[379,8,1,""],is_global:[379,8,1,""],is_imported:[379,8,1,""],is_local:[379,8,1,""],is_namespace:[379,8,1,""],is_parameter:[379,8,1,""],is_referenced:[379,8,1,""]},"symtable.SymbolTable":{get_children:[379,8,1,""],get_id:[379,8,1,""],get_identifiers:[379,8,1,""],get_lineno:[379,8,1,""],get_name:[379,8,1,""],get_symbols:[379,8,1,""],get_type:[379,8,1,""],has_children:[379,8,1,""],has_exec:[379,8,1,""],has_import_star:[379,8,1,""],is_nested:[379,8,1,""],is_optimized:[379,8,1,""],lookup:[379,8,1,""]},"tarfile.TarFile":{add:[384,8,1,""],addfile:[384,8,1,""],close:[384,8,1,""],extract:[384,8,1,""],extractall:[384,8,1,""],extractfile:[384,8,1,""],getmember:[384,8,1,""],getmembers:[384,8,1,""],getnames:[384,8,1,""],gettarinfo:[384,8,1,""],list:[384,8,1,""],next:[384,8,1,""],open:[384,12,1,""],pax_headers:[384,7,1,""],posix:[384,7,1,""]},"tarfile.TarFileCompat":{TAR_GZIPPED:[384,11,1,""],TAR_PLAIN:[384,11,1,""]},"tarfile.TarInfo":{frombuf:[384,8,1,""],fromtarfile:[384,8,1,""],gid:[384,7,1,""],gname:[384,7,1,""],isblk:[384,8,1,""],ischr:[384,8,1,""],isdev:[384,8,1,""],isdir:[384,8,1,""],isfifo:[384,8,1,""],isfile:[384,8,1,""],islnk:[384,8,1,""],isreg:[384,8,1,""],issym:[384,8,1,""],linkname:[384,7,1,""],mode:[384,7,1,""],mtime:[384,7,1,""],name:[384,7,1,""],pax_headers:[384,7,1,""],size:[384,7,1,""],tobuf:[384,8,1,""],type:[384,7,1,""],uid:[384,7,1,""],uname:[384,7,1,""]},"telnetlib.Telnet":{close:[385,8,1,""],expect:[385,8,1,""],fileno:[385,8,1,""],get_socket:[385,8,1,""],interact:[385,8,1,""],msg:[385,8,1,""],mt_interact:[385,8,1,""],open:[385,8,1,""],read_all:[385,8,1,""],read_eager:[385,8,1,""],read_lazy:[385,8,1,""],read_sb_data:[385,8,1,""],read_some:[385,8,1,""],read_until:[385,8,1,""],read_very_eager:[385,8,1,""],read_very_lazy:[385,8,1,""],set_debuglevel:[385,8,1,""],set_option_negotiation_callback:[385,8,1,""],write:[385,8,1,""]},"test.support":{EnvironmentVarGuard:[388,6,1,""],ResourceDenied:[388,10,1,""],TESTFN:[388,11,1,""],TestFailed:[388,10,1,""],TransientResource:[388,6,1,""],WarningsRecorder:[388,6,1,""],captured_stdout:[388,9,1,""],check_py3k_warnings:[388,9,1,""],check_warnings:[388,9,1,""],findfile:[388,9,1,""],forget:[388,9,1,""],have_unicode:[388,11,1,""],import_fresh_module:[388,9,1,""],import_module:[388,9,1,""],is_jython:[388,11,1,""],is_resource_enabled:[388,9,1,""],requires:[388,9,1,""],run_unittest:[388,9,1,""],verbose:[388,11,1,""]},"test.support.EnvironmentVarGuard":{set:[388,8,1,""],unset:[388,8,1,""]},"textwrap.TextWrapper":{break_long_words:[389,7,1,""],break_on_hyphens:[389,7,1,""],drop_whitespace:[389,7,1,""],expand_tabs:[389,7,1,""],fill:[389,8,1,""],fix_sentence_endings:[389,7,1,""],initial_indent:[389,7,1,""],replace_whitespace:[389,7,1,""],subsequent_indent:[389,7,1,""],width:[389,7,1,""],wrap:[389,8,1,""]},"thread.lock":{acquire:[390,8,1,""],locked:[390,8,1,""],release:[390,8,1,""]},"threading.Condition":{acquire:[391,8,1,""],notify:[391,8,1,""],notifyAll:[391,8,1,""],notify_all:[391,8,1,""],release:[391,8,1,""],wait:[391,8,1,""]},"threading.Event":{clear:[391,8,1,""],isSet:[391,8,1,""],is_set:[391,8,1,""],set:[391,8,1,""],wait:[391,8,1,""]},"threading.Lock":{acquire:[391,8,1,""],release:[391,8,1,""]},"threading.RLock":{acquire:[391,8,1,""],release:[391,8,1,""]},"threading.Semaphore":{acquire:[391,8,1,""],release:[391,8,1,""]},"threading.Thread":{daemon:[391,7,1,""],getName:[391,8,1,""],ident:[391,7,1,""],isAlive:[391,8,1,""],isDaemon:[391,8,1,""],is_alive:[391,8,1,""],join:[391,8,1,""],name:[391,7,1,""],run:[391,8,1,""],setDaemon:[391,8,1,""],setName:[391,8,1,""],start:[391,8,1,""]},"threading.Timer":{cancel:[391,8,1,""]},"timeit.Timer":{print_exc:[393,8,1,""],repeat:[393,8,1,""],timeit:[393,8,1,""]},"trace.CoverageResults":{update:[399,8,1,""],write_results:[399,8,1,""]},"trace.Trace":{results:[399,8,1,""],run:[399,8,1,""],runctx:[399,8,1,""],runfunc:[399,8,1,""]},"ttk.Combobox":{current:[401,8,1,""],get:[401,8,1,""],set:[401,8,1,""]},"ttk.Notebook":{add:[401,8,1,""],enable_traversal:[401,8,1,""],forget:[401,8,1,""],hide:[401,8,1,""],identify:[401,8,1,""],index:[401,8,1,""],insert:[401,8,1,""],select:[401,8,1,""],tab:[401,8,1,""],tabs:[401,8,1,""]},"ttk.Progressbar":{start:[401,8,1,""],step:[401,8,1,""],stop:[401,8,1,""]},"ttk.Style":{configure:[401,8,1,""],element_create:[401,8,1,""],element_names:[401,8,1,""],element_options:[401,8,1,""],layout:[401,8,1,""],lookup:[401,8,1,""],map:[401,8,1,""],theme_create:[401,8,1,""],theme_names:[401,8,1,""],theme_settings:[401,8,1,""],theme_use:[401,8,1,""]},"ttk.Treeview":{"delete":[401,8,1,""],bbox:[401,8,1,""],column:[401,8,1,""],detach:[401,8,1,""],exists:[401,8,1,""],focus:[401,8,1,""],get_children:[401,8,1,""],heading:[401,8,1,""],identify:[401,8,1,""],identify_column:[401,8,1,""],identify_element:[401,8,1,""],identify_region:[401,8,1,""],identify_row:[401,8,1,""],index:[401,8,1,""],insert:[401,8,1,""],item:[401,8,1,""],move:[401,8,1,""],next:[401,8,1,""],parent:[401,8,1,""],prev:[401,8,1,""],reattach:[401,8,1,""],see:[401,8,1,""],selection:[401,8,1,""],selection_add:[401,8,1,""],selection_remove:[401,8,1,""],selection_set:[401,8,1,""],selection_toggle:[401,8,1,""],set:[401,8,1,""],set_children:[401,8,1,""],tag_bind:[401,8,1,""],tag_configure:[401,8,1,""],tag_has:[401,8,1,""],xview:[401,8,1,""],yview:[401,8,1,""]},"ttk.Widget":{identify:[401,8,1,""],instate:[401,8,1,""],state:[401,8,1,""]},"turtle.Shape":{addcomponent:[403,8,1,""]},"unittest-discover":{"--pattern":[407,13,1,"cmdoption-unittest-discover-p"],"--start-directory":[407,13,1,"cmdoption-unittest-discover-s"],"--top-level-directory":[407,13,1,"cmdoption-unittest-discover-t"],"--verbose":[407,13,1,"cmdoption-unittest-discover-v"],"-p":[407,13,1,"cmdoption-unittest-discover-p"],"-s":[407,13,1,"cmdoption-unittest-discover-s"],"-t":[407,13,1,"cmdoption-unittest-discover-t"],"-v":[407,13,1,"cmdoption-unittest-discover-v"]},"unittest.TestCase":{addCleanup:[407,8,1,""],addTypeEqualityFunc:[407,8,1,""],assertAlmostEqual:[407,8,1,""],assertDictContainsSubset:[407,8,1,""],assertDictEqual:[407,8,1,""],assertEqual:[407,8,1,""],assertFalse:[407,8,1,""],assertGreater:[407,8,1,""],assertGreaterEqual:[407,8,1,""],assertIn:[407,8,1,""],assertIs:[407,8,1,""],assertIsInstance:[407,8,1,""],assertIsNone:[407,8,1,""],assertIsNot:[407,8,1,""],assertIsNotNone:[407,8,1,""],assertItemsEqual:[407,8,1,""],assertLess:[407,8,1,""],assertLessEqual:[407,8,1,""],assertListEqual:[407,8,1,""],assertMultiLineEqual:[407,8,1,""],assertNotAlmostEqual:[407,8,1,""],assertNotEqual:[407,8,1,""],assertNotIn:[407,8,1,""],assertNotIsInstance:[407,8,1,""],assertNotRegexpMatches:[407,8,1,""],assertRaises:[407,8,1,""],assertRaisesRegexp:[407,8,1,""],assertRegexpMatches:[407,8,1,""],assertSequenceEqual:[407,8,1,""],assertSetEqual:[407,8,1,""],assertTrue:[407,8,1,""],assertTupleEqual:[407,8,1,""],countTestCases:[407,8,1,""],debug:[407,8,1,""],defaultTestResult:[407,8,1,""],doCleanups:[407,8,1,""],fail:[407,8,1,""],failureException:[407,7,1,""],id:[407,8,1,""],longMessage:[407,7,1,""],maxDiff:[407,7,1,""],run:[407,8,1,""],setUp:[407,8,1,""],setUpClass:[407,8,1,""],shortDescription:[407,8,1,""],skipTest:[407,8,1,""],tearDown:[407,8,1,""],tearDownClass:[407,8,1,""]},"unittest.TestLoader":{discover:[407,8,1,""],getTestCaseNames:[407,8,1,""],loadTestsFromModule:[407,8,1,""],loadTestsFromName:[407,8,1,""],loadTestsFromNames:[407,8,1,""],loadTestsFromTestCase:[407,8,1,""],sortTestMethodsUsing:[407,7,1,""],suiteClass:[407,7,1,""],testMethodPrefix:[407,7,1,""]},"unittest.TestResult":{addError:[407,8,1,""],addExpectedFailure:[407,8,1,""],addFailure:[407,8,1,""],addSkip:[407,8,1,""],addSuccess:[407,8,1,""],addUnexpectedSuccess:[407,8,1,""],buffer:[407,7,1,""],errors:[407,7,1,""],expectedFailures:[407,7,1,""],failfast:[407,7,1,""],failures:[407,7,1,""],shouldStop:[407,7,1,""],skipped:[407,7,1,""],startTest:[407,8,1,""],startTestRun:[407,8,1,""],stop:[407,8,1,""],stopTest:[407,8,1,""],stopTestRun:[407,8,1,""],testsRun:[407,7,1,""],unexpectedSuccesses:[407,7,1,""],wasSuccessful:[407,8,1,""]},"unittest.TestSuite":{__iter__:[407,8,1,""],addTest:[407,8,1,""],addTests:[407,8,1,""],countTestCases:[407,8,1,""],debug:[407,8,1,""],run:[407,8,1,""]},"unittest.TextTestRunner":{_makeResult:[407,8,1,""]},"urllib.FancyURLopener":{prompt_user_passwd:[409,8,1,""]},"urllib.URLopener":{open:[409,8,1,""],open_unknown:[409,8,1,""],retrieve:[409,8,1,""],version:[409,7,1,""]},"urllib2.AbstractBasicAuthHandler":{http_error_auth_reqed:[410,8,1,""]},"urllib2.AbstractDigestAuthHandler":{http_error_auth_reqed:[410,8,1,""]},"urllib2.BaseHandler":{add_parent:[410,8,1,""],close:[410,8,1,""],default_open:[410,8,1,""],http_error_default:[410,8,1,""],http_error_nnn:[410,8,1,""],parent:[410,7,1,""],unknown_open:[410,8,1,""]},"urllib2.CacheFTPHandler":{setMaxConns:[410,8,1,""],setTimeout:[410,8,1,""]},"urllib2.FTPHandler":{ftp_open:[410,8,1,""]},"urllib2.FileHandler":{file_open:[410,8,1,""]},"urllib2.HTTPBasicAuthHandler":{http_error_401:[410,8,1,""]},"urllib2.HTTPCookieProcessor":{cookiejar:[410,7,1,""]},"urllib2.HTTPDigestAuthHandler":{http_error_401:[410,8,1,""]},"urllib2.HTTPError":{code:[410,7,1,""],reason:[410,7,1,""]},"urllib2.HTTPErrorProcessor":{http_response:[410,8,1,""],https_response:[410,8,1,""]},"urllib2.HTTPHandler":{http_open:[410,8,1,""]},"urllib2.HTTPPasswordMgr":{add_password:[410,8,1,""],find_user_password:[410,8,1,""]},"urllib2.HTTPRedirectHandler":{http_error_301:[410,8,1,""],http_error_302:[410,8,1,""],http_error_303:[410,8,1,""],http_error_307:[410,8,1,""],redirect_request:[410,8,1,""]},"urllib2.HTTPSHandler":{https_open:[410,8,1,""]},"urllib2.OpenerDirector":{add_handler:[410,8,1,""],error:[410,8,1,""],open:[410,8,1,""]},"urllib2.ProxyBasicAuthHandler":{http_error_407:[410,8,1,""]},"urllib2.ProxyDigestAuthHandler":{http_error_407:[410,8,1,""]},"urllib2.Request":{add_data:[410,8,1,""],add_header:[410,8,1,""],add_unredirected_header:[410,8,1,""],get_data:[410,8,1,""],get_full_url:[410,8,1,""],get_header:[410,8,1,""],get_host:[410,8,1,""],get_method:[410,8,1,""],get_origin_req_host:[410,8,1,""],get_selector:[410,8,1,""],get_type:[410,8,1,""],has_data:[410,8,1,""],has_header:[410,8,1,""],header_items:[410,8,1,""],is_unverifiable:[410,8,1,""],set_proxy:[410,8,1,""]},"urllib2.URLError":{reason:[410,7,1,""]},"urllib2.UnknownHandler":{unknown_open:[410,8,1,""]},"urlparse.ParseResult":{geturl:[411,8,1,""]},"uuid.UUID":{"int":[415,7,1,""],bytes:[415,7,1,""],bytes_le:[415,7,1,""],fields:[415,7,1,""],hex:[415,7,1,""],urn:[415,7,1,""],variant:[415,7,1,""],version:[415,7,1,""]},"wave.Wave_read":{close:[417,8,1,""],getcompname:[417,8,1,""],getcomptype:[417,8,1,""],getframerate:[417,8,1,""],getmark:[417,8,1,""],getmarkers:[417,8,1,""],getnchannels:[417,8,1,""],getnframes:[417,8,1,""],getparams:[417,8,1,""],getsampwidth:[417,8,1,""],readframes:[417,8,1,""],rewind:[417,8,1,""],setpos:[417,8,1,""],tell:[417,8,1,""]},"wave.Wave_write":{close:[417,8,1,""],setcomptype:[417,8,1,""],setframerate:[417,8,1,""],setnchannels:[417,8,1,""],setnframes:[417,8,1,""],setparams:[417,8,1,""],setsampwidth:[417,8,1,""],tell:[417,8,1,""],writeframes:[417,8,1,""],writeframesraw:[417,8,1,""]},"weakref.WeakKeyDictionary":{iterkeyrefs:[418,8,1,""],keyrefs:[418,8,1,""]},"weakref.WeakValueDictionary":{itervaluerefs:[418,8,1,""],valuerefs:[418,8,1,""]},"webbrowser.controller":{open:[419,8,1,""],open_new:[419,8,1,""],open_new_tab:[419,8,1,""]},"wsgiref.handlers":{BaseCGIHandler:[423,6,1,""],BaseHandler:[423,6,1,""],CGIHandler:[423,6,1,""],SimpleHandler:[423,6,1,""]},"wsgiref.handlers.BaseHandler":{_flush:[423,8,1,""],_write:[423,8,1,""],add_cgi_vars:[423,8,1,""],error_body:[423,7,1,""],error_headers:[423,7,1,""],error_output:[423,8,1,""],error_status:[423,7,1,""],get_scheme:[423,8,1,""],get_stderr:[423,8,1,""],get_stdin:[423,8,1,""],http_version:[423,7,1,""],log_exception:[423,8,1,""],origin_server:[423,7,1,""],os_environ:[423,7,1,""],run:[423,8,1,""],sendfile:[423,8,1,""],server_software:[423,7,1,""],setup_environ:[423,8,1,""],traceback_limit:[423,7,1,""],wsgi_file_wrapper:[423,7,1,""],wsgi_multiprocess:[423,7,1,""],wsgi_multithread:[423,7,1,""],wsgi_run_once:[423,7,1,""]},"wsgiref.headers":{Headers:[423,6,1,""]},"wsgiref.headers.Headers":{add_header:[423,8,1,""],get_all:[423,8,1,""]},"wsgiref.simple_server":{WSGIRequestHandler:[423,6,1,""],WSGIServer:[423,6,1,""],demo_app:[423,9,1,""],make_server:[423,9,1,""]},"wsgiref.simple_server.WSGIRequestHandler":{get_environ:[423,8,1,""],get_stderr:[423,8,1,""],handle:[423,8,1,""]},"wsgiref.simple_server.WSGIServer":{get_app:[423,8,1,""],set_app:[423,8,1,""]},"wsgiref.util":{FileWrapper:[423,6,1,""],application_uri:[423,9,1,""],guess_scheme:[423,9,1,""],is_hop_by_hop:[423,9,1,""],request_uri:[423,9,1,""],setup_testing_defaults:[423,9,1,""],shift_path_info:[423,9,1,""]},"wsgiref.validate":{validator:[423,9,1,""]},"xdrlib.Packer":{get_buffer:[424,8,1,""],pack_array:[424,8,1,""],pack_bytes:[424,8,1,""],pack_double:[424,8,1,""],pack_farray:[424,8,1,""],pack_float:[424,8,1,""],pack_fopaque:[424,8,1,""],pack_fstring:[424,8,1,""],pack_list:[424,8,1,""],pack_opaque:[424,8,1,""],pack_string:[424,8,1,""],reset:[424,8,1,""]},"xdrlib.Unpacker":{done:[424,8,1,""],get_buffer:[424,8,1,""],get_position:[424,8,1,""],reset:[424,8,1,""],set_position:[424,8,1,""],unpack_array:[424,8,1,""],unpack_bytes:[424,8,1,""],unpack_double:[424,8,1,""],unpack_farray:[424,8,1,""],unpack_float:[424,8,1,""],unpack_fopaque:[424,8,1,""],unpack_fstring:[424,8,1,""],unpack_list:[424,8,1,""],unpack_opaque:[424,8,1,""],unpack_string:[424,8,1,""]},"xml.dom":{DOMException:[426,10,1,""],DomstringSizeErr:[426,10,1,""],EMPTY_NAMESPACE:[426,11,1,""],HierarchyRequestErr:[426,10,1,""],IndexSizeErr:[426,10,1,""],InuseAttributeErr:[426,10,1,""],InvalidAccessErr:[426,10,1,""],InvalidCharacterErr:[426,10,1,""],InvalidModificationErr:[426,10,1,""],InvalidStateErr:[426,10,1,""],NamespaceErr:[426,10,1,""],NoDataAllowedErr:[426,10,1,""],NoModificationAllowedErr:[426,10,1,""],NotFoundErr:[426,10,1,""],NotSupportedErr:[426,10,1,""],SyntaxErr:[426,10,1,""],WrongDocumentErr:[426,10,1,""],XHTML_NAMESPACE:[426,11,1,""],XMLNS_NAMESPACE:[426,11,1,""],XML_NAMESPACE:[426,11,1,""],getDOMImplementation:[426,9,1,""],minidom:[427,5,0,"-"],pulldom:[428,5,0,"-"],registerDOMImplementation:[426,9,1,""]},"xml.dom.Attr":{localName:[426,7,1,""],name:[426,7,1,""],prefix:[426,7,1,""],value:[426,7,1,""]},"xml.dom.Comment":{data:[426,7,1,""]},"xml.dom.DOMImplementation":{createDocument:[426,8,1,""],createDocumentType:[426,8,1,""],hasFeature:[426,8,1,""]},"xml.dom.Document":{createAttribute:[426,8,1,""],createAttributeNS:[426,8,1,""],createComment:[426,8,1,""],createElement:[426,8,1,""],createElementNS:[426,8,1,""],createProcessingInstruction:[426,8,1,""],createTextNode:[426,8,1,""],documentElement:[426,7,1,""],getElementsByTagName:[426,8,1,""],getElementsByTagNameNS:[426,8,1,""]},"xml.dom.DocumentType":{entities:[426,7,1,""],internalSubset:[426,7,1,""],name:[426,7,1,""],notations:[426,7,1,""],publicId:[426,7,1,""],systemId:[426,7,1,""]},"xml.dom.Element":{getAttribute:[426,8,1,""],getAttributeNS:[426,8,1,""],getAttributeNode:[426,8,1,""],getAttributeNodeNS:[426,8,1,""],getElementsByTagName:[426,8,1,""],getElementsByTagNameNS:[426,8,1,""],hasAttribute:[426,8,1,""],hasAttributeNS:[426,8,1,""],removeAttribute:[426,8,1,""],removeAttributeNS:[426,8,1,""],removeAttributeNode:[426,8,1,""],setAttribute:[426,8,1,""],setAttributeNS:[426,8,1,""],setAttributeNode:[426,8,1,""],setAttributeNodeNS:[426,8,1,""],tagName:[426,7,1,""]},"xml.dom.NamedNodeMap":{item:[426,8,1,""],length:[426,7,1,""]},"xml.dom.Node":{appendChild:[426,8,1,""],attributes:[426,7,1,""],childNodes:[426,7,1,""],cloneNode:[426,8,1,""],firstChild:[426,7,1,""],hasAttributes:[426,8,1,""],hasChildNodes:[426,8,1,""],insertBefore:[426,8,1,""],isSameNode:[426,8,1,""],lastChild:[426,7,1,""],localName:[426,7,1,""],namespaceURI:[426,7,1,""],nextSibling:[426,7,1,""],nodeName:[426,7,1,""],nodeType:[426,7,1,""],nodeValue:[426,7,1,""],normalize:[426,8,1,""],parentNode:[426,7,1,""],prefix:[426,7,1,""],previousSibling:[426,7,1,""],removeChild:[426,8,1,""],replaceChild:[426,8,1,""]},"xml.dom.NodeList":{item:[426,8,1,""],length:[426,7,1,""]},"xml.dom.ProcessingInstruction":{data:[426,7,1,""],target:[426,7,1,""]},"xml.dom.Text":{data:[426,7,1,""]},"xml.dom.minidom":{parse:[427,9,1,""],parseString:[427,9,1,""]},"xml.dom.minidom.Node":{cloneNode:[427,8,1,""],toprettyxml:[427,8,1,""],toxml:[427,8,1,""],unlink:[427,8,1,""],writexml:[427,8,1,""]},"xml.dom.pulldom":{DOMEventStream:[428,6,1,""],PullDOM:[428,6,1,""],SAX2DOM:[428,6,1,""],default_bufsize:[428,11,1,""],parse:[428,9,1,""],parseString:[428,9,1,""]},"xml.dom.pulldom.DOMEventStream":{expandNode:[428,8,1,""],getEvent:[428,8,1,""],reset:[428,8,1,""]},"xml.etree":{ElementTree:[429,5,0,"-"]},"xml.etree.ElementTree":{Comment:[429,9,1,""],Element:[429,6,1,""],ElementTree:[429,6,1,""],ProcessingInstruction:[429,9,1,""],QName:[429,6,1,""],SubElement:[429,9,1,""],TreeBuilder:[429,6,1,""],XML:[429,9,1,""],XMLID:[429,9,1,""],XMLParser:[429,6,1,""],dump:[429,9,1,""],fromstring:[429,9,1,""],fromstringlist:[429,9,1,""],iselement:[429,9,1,""],iterparse:[429,9,1,""],parse:[429,9,1,""],register_namespace:[429,9,1,""],tostring:[429,9,1,""],tostringlist:[429,9,1,""]},"xml.etree.ElementTree.Element":{append:[429,8,1,""],attrib:[429,7,1,""],clear:[429,8,1,""],extend:[429,8,1,""],find:[429,8,1,""],findall:[429,8,1,""],findtext:[429,8,1,""],get:[429,8,1,""],getchildren:[429,8,1,""],getiterator:[429,8,1,""],insert:[429,8,1,""],items:[429,8,1,""],iter:[429,8,1,""],iterfind:[429,8,1,""],itertext:[429,8,1,""],keys:[429,8,1,""],makeelement:[429,8,1,""],remove:[429,8,1,""],set:[429,8,1,""],tag:[429,7,1,""],tail:[429,7,1,""],text:[429,7,1,""]},"xml.etree.ElementTree.ElementTree":{_setroot:[429,8,1,""],find:[429,8,1,""],findall:[429,8,1,""],findtext:[429,8,1,""],getiterator:[429,8,1,""],getroot:[429,8,1,""],iter:[429,8,1,""],iterfind:[429,8,1,""],parse:[429,8,1,""],write:[429,8,1,""]},"xml.etree.ElementTree.TreeBuilder":{close:[429,8,1,""],data:[429,8,1,""],doctype:[429,8,1,""],end:[429,8,1,""],start:[429,8,1,""]},"xml.etree.ElementTree.XMLParser":{close:[429,8,1,""],doctype:[429,8,1,""],feed:[429,8,1,""]},"xml.parsers":{expat:[328,5,0,"-"]},"xml.parsers.expat":{ErrorString:[328,9,1,""],ExpatError:[328,10,1,""],ParserCreate:[328,9,1,""],XMLParserType:[328,11,1,""],error:[328,10,1,""]},"xml.parsers.expat.ExpatError":{code:[328,7,1,""],lineno:[328,7,1,""],offset:[328,7,1,""]},"xml.parsers.expat.xmlparser":{AttlistDeclHandler:[328,8,1,""],CharacterDataHandler:[328,8,1,""],CommentHandler:[328,8,1,""],CurrentByteIndex:[328,7,1,""],CurrentColumnNumber:[328,7,1,""],CurrentLineNumber:[328,7,1,""],DefaultHandler:[328,8,1,""],DefaultHandlerExpand:[328,8,1,""],ElementDeclHandler:[328,8,1,""],EndCdataSectionHandler:[328,8,1,""],EndDoctypeDeclHandler:[328,8,1,""],EndElementHandler:[328,8,1,""],EndNamespaceDeclHandler:[328,8,1,""],EntityDeclHandler:[328,8,1,""],ErrorByteIndex:[328,7,1,""],ErrorCode:[328,7,1,""],ErrorColumnNumber:[328,7,1,""],ErrorLineNumber:[328,7,1,""],ExternalEntityParserCreate:[328,8,1,""],ExternalEntityRefHandler:[328,8,1,""],GetBase:[328,8,1,""],GetInputContext:[328,8,1,""],NotStandaloneHandler:[328,8,1,""],NotationDeclHandler:[328,8,1,""],Parse:[328,8,1,""],ParseFile:[328,8,1,""],ProcessingInstructionHandler:[328,8,1,""],SetBase:[328,8,1,""],SetParamEntityParsing:[328,8,1,""],StartCdataSectionHandler:[328,8,1,""],StartDoctypeDeclHandler:[328,8,1,""],StartElementHandler:[328,8,1,""],StartNamespaceDeclHandler:[328,8,1,""],UnparsedEntityDeclHandler:[328,8,1,""],UseForeignDTD:[328,8,1,""],XmlDeclHandler:[328,8,1,""],buffer_size:[328,7,1,""],buffer_text:[328,7,1,""],buffer_used:[328,7,1,""],ordered_attributes:[328,7,1,""],returns_unicode:[328,7,1,""],specified_attributes:[328,7,1,""]},"xml.sax":{SAXException:[430,10,1,""],SAXNotRecognizedException:[430,10,1,""],SAXNotSupportedException:[430,10,1,""],SAXParseException:[430,10,1,""],handler:[431,5,0,"-"],make_parser:[430,9,1,""],parse:[430,9,1,""],parseString:[430,9,1,""],saxutils:[433,5,0,"-"],xmlreader:[432,5,0,"-"]},"xml.sax.SAXException":{getException:[430,8,1,""],getMessage:[430,8,1,""]},"xml.sax.handler":{ContentHandler:[431,6,1,""],DTDHandler:[431,6,1,""],EntityResolver:[431,6,1,""],ErrorHandler:[431,6,1,""],all_features:[431,11,1,""],all_properties:[431,11,1,""],feature_external_ges:[431,11,1,""],feature_external_pes:[431,11,1,""],feature_namespace_prefixes:[431,11,1,""],feature_namespaces:[431,11,1,""],feature_string_interning:[431,11,1,""],feature_validation:[431,11,1,""],property_declaration_handler:[431,11,1,""],property_dom_node:[431,11,1,""],property_lexical_handler:[431,11,1,""],property_xml_string:[431,11,1,""]},"xml.sax.handler.ContentHandler":{characters:[431,8,1,""],endDocument:[431,8,1,""],endElement:[431,8,1,""],endElementNS:[431,8,1,""],endPrefixMapping:[431,8,1,""],ignorableWhitespace:[431,8,1,""],processingInstruction:[431,8,1,""],setDocumentLocator:[431,8,1,""],skippedEntity:[431,8,1,""],startDocument:[431,8,1,""],startElement:[431,8,1,""],startElementNS:[431,8,1,""],startPrefixMapping:[431,8,1,""]},"xml.sax.handler.DTDHandler":{notationDecl:[431,8,1,""],unparsedEntityDecl:[431,8,1,""]},"xml.sax.handler.EntityResolver":{resolveEntity:[431,8,1,""]},"xml.sax.handler.ErrorHandler":{error:[431,8,1,""],fatalError:[431,8,1,""],warning:[431,8,1,""]},"xml.sax.saxutils":{XMLFilterBase:[433,6,1,""],XMLGenerator:[433,6,1,""],escape:[433,9,1,""],prepare_input_source:[433,9,1,""],quoteattr:[433,9,1,""],unescape:[433,9,1,""]},"xml.sax.xmlreader":{AttributesImpl:[432,6,1,""],AttributesNSImpl:[432,6,1,""],IncrementalParser:[432,6,1,""],InputSource:[432,6,1,""],Locator:[432,6,1,""],XMLReader:[432,6,1,""]},"xml.sax.xmlreader.Attributes":{getLength:[432,8,1,""],getNames:[432,8,1,""],getType:[432,8,1,""],getValue:[432,8,1,""]},"xml.sax.xmlreader.AttributesNS":{getNameByQName:[432,8,1,""],getQNameByName:[432,8,1,""],getQNames:[432,8,1,""],getValueByQName:[432,8,1,""]},"xml.sax.xmlreader.IncrementalParser":{close:[432,8,1,""],feed:[432,8,1,""],reset:[432,8,1,""]},"xml.sax.xmlreader.InputSource":{getByteStream:[432,8,1,""],getCharacterStream:[432,8,1,""],getEncoding:[432,8,1,""],getPublicId:[432,8,1,""],getSystemId:[432,8,1,""],setByteStream:[432,8,1,""],setCharacterStream:[432,8,1,""],setEncoding:[432,8,1,""],setPublicId:[432,8,1,""],setSystemId:[432,8,1,""]},"xml.sax.xmlreader.Locator":{getColumnNumber:[432,8,1,""],getLineNumber:[432,8,1,""],getPublicId:[432,8,1,""],getSystemId:[432,8,1,""]},"xml.sax.xmlreader.XMLReader":{getContentHandler:[432,8,1,""],getDTDHandler:[432,8,1,""],getEntityResolver:[432,8,1,""],getErrorHandler:[432,8,1,""],getFeature:[432,8,1,""],getProperty:[432,8,1,""],parse:[432,8,1,""],setContentHandler:[432,8,1,""],setDTDHandler:[432,8,1,""],setEntityResolver:[432,8,1,""],setErrorHandler:[432,8,1,""],setFeature:[432,8,1,""],setLocale:[432,8,1,""],setProperty:[432,8,1,""]},"xmlrpclib.Binary":{data:[434,7,1,""],decode:[434,8,1,""],encode:[434,8,1,""]},"xmlrpclib.Boolean":{encode:[434,8,1,""]},"xmlrpclib.DateTime":{decode:[434,8,1,""],encode:[434,8,1,""]},"xmlrpclib.Fault":{faultCode:[434,7,1,""],faultString:[434,7,1,""]},"xmlrpclib.ProtocolError":{errcode:[434,7,1,""],errmsg:[434,7,1,""],headers:[434,7,1,""],url:[434,7,1,""]},"xmlrpclib.ServerProxy.system":{listMethods:[434,8,1,""],methodHelp:[434,8,1,""],methodSignature:[434,8,1,""]},"zipfile.PyZipFile":{writepy:[435,8,1,""]},"zipfile.ZipFile":{close:[435,8,1,""],comment:[435,7,1,""],debug:[435,7,1,""],extract:[435,8,1,""],extractall:[435,8,1,""],getinfo:[435,8,1,""],infolist:[435,8,1,""],namelist:[435,8,1,""],open:[435,8,1,""],printdir:[435,8,1,""],read:[435,8,1,""],setpassword:[435,8,1,""],testzip:[435,8,1,""],write:[435,8,1,""],writestr:[435,8,1,""]},"zipfile.ZipInfo":{CRC:[435,7,1,""],comment:[435,7,1,""],compress_size:[435,7,1,""],compress_type:[435,7,1,""],create_system:[435,7,1,""],create_version:[435,7,1,""],date_time:[435,7,1,""],external_attr:[435,7,1,""],extra:[435,7,1,""],extract_version:[435,7,1,""],file_size:[435,7,1,""],filename:[435,7,1,""],flag_bits:[435,7,1,""],header_offset:[435,7,1,""],internal_attr:[435,7,1,""],reserved:[435,7,1,""],volume:[435,7,1,""]},"zipimport.zipimporter":{archive:[436,7,1,""],find_module:[436,8,1,""],get_code:[436,8,1,""],get_data:[436,8,1,""],get_filename:[436,8,1,""],get_source:[436,8,1,""],is_package:[436,8,1,""],load_module:[436,8,1,""],prefix:[436,7,1,""]},"zlib.Compress":{compress:[437,8,1,""],copy:[437,8,1,""],flush:[437,8,1,""]},"zlib.Decompress":{copy:[437,8,1,""],decompress:[437,8,1,""],flush:[437,8,1,""],unconsumed_tail:[437,7,1,""],unused_data:[437,7,1,""]},BaseHTTPServer:{BaseHTTPRequestHandler:[132,6,1,""],HTTPServer:[132,6,1,""]},Bastion:{Bastion:[133,9,1,""],BastionClass:[133,6,1,""]},CGIHTTPServer:{CGIHTTPRequestHandler:[144,6,1,""]},Carbon:{AE:[141,5,0,"-"],AH:[141,5,0,"-"],App:[141,5,0,"-"],Appearance:[141,5,0,"-"],CF:[141,5,0,"-"],CG:[141,5,0,"-"],CarbonEvents:[141,5,0,"-"],CarbonEvt:[141,5,0,"-"],Cm:[141,5,0,"-"],Components:[141,5,0,"-"],ControlAccessor:[141,5,0,"-"],Controls:[141,5,0,"-"],CoreFounation:[141,5,0,"-"],CoreGraphics:[141,5,0,"-"],Ctl:[141,5,0,"-"],Dialogs:[141,5,0,"-"],Dlg:[141,5,0,"-"],Drag:[141,5,0,"-"],Dragconst:[141,5,0,"-"],Events:[141,5,0,"-"],Evt:[141,5,0,"-"],File:[141,5,0,"-"],Files:[141,5,0,"-"],Fm:[141,5,0,"-"],Folder:[141,5,0,"-"],Folders:[141,5,0,"-"],Fonts:[141,5,0,"-"],Help:[141,5,0,"-"],IBCarbon:[141,5,0,"-"],IBCarbonRuntime:[141,5,0,"-"],Icns:[141,5,0,"-"],Icons:[141,5,0,"-"],Launch:[141,5,0,"-"],LaunchServices:[141,5,0,"-"],List:[141,5,0,"-"],Lists:[141,5,0,"-"],MacHelp:[141,5,0,"-"],MediaDescr:[141,5,0,"-"],Menu:[141,5,0,"-"],Menus:[141,5,0,"-"],Mlte:[141,5,0,"-"],OSA:[141,5,0,"-"],OSAconst:[141,5,0,"-"],QDOffscreen:[141,5,0,"-"],Qd:[141,5,0,"-"],Qdoffs:[141,5,0,"-"],Qt:[141,5,0,"-"],QuickDraw:[141,5,0,"-"],QuickTime:[141,5,0,"-"],Res:[141,5,0,"-"],Resources:[141,5,0,"-"],Scrap:[141,5,0,"-"],Snd:[141,5,0,"-"],Sound:[141,5,0,"-"],TE:[141,5,0,"-"],TextEdit:[141,5,0,"-"],Win:[141,5,0,"-"],Windows:[141,5,0,"-"]},ColorPicker:{GetColor:[153,9,1,""]},ConfigParser:{ConfigParser:[158,6,1,""],DuplicateSectionError:[158,10,1,""],Error:[158,10,1,""],InterpolationDepthError:[158,10,1,""],InterpolationError:[158,10,1,""],InterpolationMissingOptionError:[158,10,1,""],InterpolationSyntaxError:[158,10,1,""],MAX_INTERPOLATION_DEPTH:[158,11,1,""],MissingSectionHeaderError:[158,10,1,""],NoOptionError:[158,10,1,""],NoSectionError:[158,10,1,""],ParsingError:[158,10,1,""],RawConfigParser:[158,6,1,""],SafeConfigParser:[158,6,1,""]},Connection:{close:[293,8,1,""],fileno:[293,8,1,""],poll:[293,8,1,""],recv:[293,8,1,""],recv_bytes:[293,8,1,""],recv_bytes_into:[293,8,1,""],send:[293,8,1,""],send_bytes:[293,8,1,""]},Cookie:{BaseCookie:[161,6,1,""],CookieError:[161,10,1,""],Morsel:[161,6,1,""],SerialCookie:[161,6,1,""],SimpleCookie:[161,6,1,""],SmartCookie:[161,6,1,""]},DocXMLRPCServer:{DocCGIXMLRPCRequestHandler:[187,6,1,""],DocXMLRPCRequestHandler:[187,6,1,""],DocXMLRPCServer:[187,6,1,""]},EasyDialogs:{AskFileForOpen:[191,9,1,""],AskFileForSave:[191,9,1,""],AskFolder:[191,9,1,""],AskPassword:[191,9,1,""],AskString:[191,9,1,""],AskYesNoCancel:[191,9,1,""],GetArgv:[191,9,1,""],Message:[191,9,1,""],ProgressBar:[191,9,1,""]},FrameWork:{Application:[219,9,1,""],DialogWindow:[219,9,1,""],Menu:[219,9,1,""],MenuBar:[219,9,1,""],MenuItem:[219,9,1,""],Separator:[219,9,1,""],SubMenu:[219,9,1,""],Window:[219,9,1,""],setarrowcursor:[219,9,1,""],setwatchcursor:[219,9,1,""],windowbounds:[219,9,1,""]},HTMLParser:{HTMLParseError:[240,10,1,""],HTMLParser:[240,6,1,""]},MacOS:{DebugStr:[269,9,1,""],Error:[269,10,1,""],GetCreatorAndType:[269,9,1,""],GetErrorString:[269,9,1,""],GetTicks:[269,9,1,""],SetCreatorAndType:[269,9,1,""],SysBeep:[269,9,1,""],WMAvailable:[269,9,1,""],linkmodel:[269,11,1,""],openrf:[269,9,1,""],runtimemodel:[269,11,1,""],splash:[269,9,1,""]},MimeWriter:{MimeWriter:[282,6,1,""]},MiniAEFrame:{AEServer:[284,6,1,""],MiniApplication:[284,6,1,""]},PyMappingMethods:{mp_ass_subscript:[55,3,1,"c.PyMappingMethods.mp_ass_subscript"],mp_length:[55,3,1,"c.PyMappingMethods.mp_length"],mp_subscript:[55,3,1,"c.PyMappingMethods.mp_subscript"]},PyNumberMethods:{nb_coerce:[55,3,1,"c.PyNumberMethods.nb_coerce"]},PyObject:{_ob_next:[55,3,1,"c.PyObject._ob_next"],_ob_prev:[55,3,1,"c.PyObject._ob_prev"],ob_refcnt:[55,3,1,"c.PyObject.ob_refcnt"],ob_type:[55,3,1,"c.PyObject.ob_type"]},PySequenceMethods:{sq_ass_item:[55,3,1,"c.PySequenceMethods.sq_ass_item"],sq_concat:[55,3,1,"c.PySequenceMethods.sq_concat"],sq_contains:[55,3,1,"c.PySequenceMethods.sq_contains"],sq_inplace_concat:[55,3,1,"c.PySequenceMethods.sq_inplace_concat"],sq_inplace_repeat:[55,3,1,"c.PySequenceMethods.sq_inplace_repeat"],sq_item:[55,3,1,"c.PySequenceMethods.sq_item"],sq_length:[55,3,1,"c.PySequenceMethods.sq_length"],sq_repeat:[55,3,1,"c.PySequenceMethods.sq_repeat"]},PyTypeObject:{tp_alloc:[55,3,1,"c.PyTypeObject.tp_alloc"],tp_allocs:[55,3,1,"c.PyTypeObject.tp_allocs"],tp_as_buffer:[55,3,1,"c.PyTypeObject.tp_as_buffer"],tp_base:[55,3,1,"c.PyTypeObject.tp_base"],tp_bases:[55,3,1,"c.PyTypeObject.tp_bases"],tp_basicsize:[55,3,1,"c.PyTypeObject.tp_basicsize"],tp_cache:[55,3,1,"c.PyTypeObject.tp_cache"],tp_call:[55,3,1,"c.PyTypeObject.tp_call"],tp_clear:[55,3,1,"c.PyTypeObject.tp_clear"],tp_compare:[55,3,1,"c.PyTypeObject.tp_compare"],tp_dealloc:[55,3,1,"c.PyTypeObject.tp_dealloc"],tp_descr_get:[55,3,1,"c.PyTypeObject.tp_descr_get"],tp_descr_set:[55,3,1,"c.PyTypeObject.tp_descr_set"],tp_dict:[55,3,1,"c.PyTypeObject.tp_dict"],tp_dictoffset:[55,3,1,"c.PyTypeObject.tp_dictoffset"],tp_doc:[55,3,1,"c.PyTypeObject.tp_doc"],tp_flags:[55,3,1,"c.PyTypeObject.tp_flags"],tp_free:[55,3,1,"c.PyTypeObject.tp_free"],tp_frees:[55,3,1,"c.PyTypeObject.tp_frees"],tp_getattr:[55,3,1,"c.PyTypeObject.tp_getattr"],tp_getattro:[55,3,1,"c.PyTypeObject.tp_getattro"],tp_getset:[55,3,1,"c.PyTypeObject.tp_getset"],tp_hash:[55,3,1,"c.PyTypeObject.tp_hash"],tp_init:[55,3,1,"c.PyTypeObject.tp_init"],tp_is_gc:[55,3,1,"c.PyTypeObject.tp_is_gc"],tp_itemsize:[55,3,1,"c.PyTypeObject.tp_itemsize"],tp_iter:[55,3,1,"c.PyTypeObject.tp_iter"],tp_iternext:[55,3,1,"c.PyTypeObject.tp_iternext"],tp_maxalloc:[55,3,1,"c.PyTypeObject.tp_maxalloc"],tp_members:[55,3,1,"c.PyTypeObject.tp_members"],tp_methods:[55,3,1,"c.PyTypeObject.tp_methods"],tp_mro:[55,3,1,"c.PyTypeObject.tp_mro"],tp_name:[55,3,1,"c.PyTypeObject.tp_name"],tp_new:[55,3,1,"c.PyTypeObject.tp_new"],tp_next:[55,3,1,"c.PyTypeObject.tp_next"],tp_print:[55,3,1,"c.PyTypeObject.tp_print"],tp_repr:[55,3,1,"c.PyTypeObject.tp_repr"],tp_richcompare:[55,3,1,"c.PyTypeObject.tp_richcompare"],tp_setattr:[55,3,1,"c.PyTypeObject.tp_setattr"],tp_setattro:[55,3,1,"c.PyTypeObject.tp_setattro"],tp_str:[55,3,1,"c.PyTypeObject.tp_str"],tp_subclasses:[55,3,1,"c.PyTypeObject.tp_subclasses"],tp_traverse:[55,3,1,"c.PyTypeObject.tp_traverse"],tp_weaklist:[55,3,1,"c.PyTypeObject.tp_weaklist"],tp_weaklistoffset:[55,3,1,"c.PyTypeObject.tp_weaklistoffset"]},PyVarObject:{ob_size:[55,3,1,"c.PyVarObject.ob_size"]},Py_buffer:{buf:[6,3,1,"c.Py_buffer.buf"],internal:[6,3,1,"c.Py_buffer.internal"],itemsize:[6,3,1,"c.Py_buffer.itemsize"],ndim:[6,3,1,"c.Py_buffer.ndim"],readonly:[6,3,1,"c.Py_buffer.readonly"],shape:[6,3,1,"c.Py_buffer.shape"],strides:[6,3,1,"c.Py_buffer.strides"],suboffsets:[6,3,1,"c.Py_buffer.suboffsets"]},Queue:{Empty:[330,10,1,""],Full:[330,10,1,""],LifoQueue:[330,6,1,""],PriorityQueue:[330,6,1,""],Queue:[330,6,1,""]},SimpleHTTPServer:{SimpleHTTPRequestHandler:[354,6,1,""]},SimpleXMLRPCServer:{CGIXMLRPCRequestHandler:[355,6,1,""],SimpleXMLRPCRequestHandler:[355,6,1,""],SimpleXMLRPCServer:[355,6,1,""]},SocketServer:{BaseRequestHandler:[361,6,1,""],BaseServer:[361,6,1,""],DatagramRequestHandler:[361,6,1,""],ForkingMixIn:[361,6,1,""],ForkingTCPServer:[361,6,1,""],ForkingUDPServer:[361,6,1,""],StreamRequestHandler:[361,6,1,""],TCPServer:[361,6,1,""],ThreadingMixIn:[361,6,1,""],ThreadingTCPServer:[361,6,1,""],ThreadingUDPServer:[361,6,1,""],UDPServer:[361,6,1,""],UnixDatagramServer:[361,6,1,""],UnixStreamServer:[361,6,1,""]},StringIO:{StringIO:[370,6,1,""]},Tix:{Balloon:[394,6,1,""],ButtonBox:[394,6,1,""],CheckList:[394,6,1,""],ComboBox:[394,6,1,""],Control:[394,6,1,""],DirList:[394,6,1,""],DirSelectBox:[394,6,1,""],DirSelectDialog:[394,6,1,""],DirTree:[394,6,1,""],ExFileSelectBox:[394,6,1,""],FileEntry:[394,6,1,""],FileSelectBox:[394,6,1,""],Form:[394,6,1,""],HList:[394,6,1,""],InputOnly:[394,6,1,""],LabelEntry:[394,6,1,""],LabelFrame:[394,6,1,""],ListNoteBook:[394,6,1,""],Meter:[394,6,1,""],NoteBook:[394,6,1,""],OptionMenu:[394,6,1,""],PanedWindow:[394,6,1,""],PopupMenu:[394,6,1,""],Select:[394,6,1,""],StdButtonBox:[394,6,1,""],TList:[394,6,1,""],Tix:[394,6,1,""],Tree:[394,6,1,""],tixCommand:[394,6,1,""]},Tkinter:{EXCEPTION:[396,11,1,""],READABLE:[396,11,1,""],Tcl:[396,9,1,""],Tk:[396,6,1,""],WRITABLE:[396,11,1,""]},UserDict:{DictMixin:[413,6,1,""],IterableUserDict:[413,6,1,""],UserDict:[413,6,1,""]},UserList:{UserList:[413,6,1,""]},UserString:{MutableString:[413,6,1,""],UserString:[413,6,1,""]},_winreg:{CloseKey:[113,9,1,""],ConnectRegistry:[113,9,1,""],CreateKey:[113,9,1,""],CreateKeyEx:[113,9,1,""],DeleteKey:[113,9,1,""],DeleteKeyEx:[113,9,1,""],DeleteValue:[113,9,1,""],DisableReflectionKey:[113,9,1,""],EnableReflectionKey:[113,9,1,""],EnumKey:[113,9,1,""],EnumValue:[113,9,1,""],ExpandEnvironmentStrings:[113,9,1,""],FlushKey:[113,9,1,""],HKEY_CLASSES_ROOT:[113,11,1,""],HKEY_CURRENT_CONFIG:[113,11,1,""],HKEY_CURRENT_USER:[113,11,1,""],HKEY_DYN_DATA:[113,11,1,""],HKEY_LOCAL_MACHINE:[113,11,1,""],HKEY_PERFORMANCE_DATA:[113,11,1,""],HKEY_USERS:[113,11,1,""],KEY_ALL_ACCESS:[113,11,1,""],KEY_CREATE_LINK:[113,11,1,""],KEY_CREATE_SUB_KEY:[113,11,1,""],KEY_ENUMERATE_SUB_KEYS:[113,11,1,""],KEY_EXECUTE:[113,11,1,""],KEY_NOTIFY:[113,11,1,""],KEY_QUERY_VALUE:[113,11,1,""],KEY_READ:[113,11,1,""],KEY_SET_VALUE:[113,11,1,""],KEY_WOW64_32KEY:[113,11,1,""],KEY_WOW64_64KEY:[113,11,1,""],KEY_WRITE:[113,11,1,""],LoadKey:[113,9,1,""],OpenKey:[113,9,1,""],OpenKeyEx:[113,9,1,""],QueryInfoKey:[113,9,1,""],QueryReflectionKey:[113,9,1,""],QueryValue:[113,9,1,""],QueryValueEx:[113,9,1,""],REG_BINARY:[113,11,1,""],REG_DWORD:[113,11,1,""],REG_DWORD_BIG_ENDIAN:[113,11,1,""],REG_DWORD_LITTLE_ENDIAN:[113,11,1,""],REG_EXPAND_SZ:[113,11,1,""],REG_FULL_RESOURCE_DESCRIPTOR:[113,11,1,""],REG_LINK:[113,11,1,""],REG_MULTI_SZ:[113,11,1,""],REG_NONE:[113,11,1,""],REG_RESOURCE_LIST:[113,11,1,""],REG_RESOURCE_REQUIREMENTS_LIST:[113,11,1,""],REG_SZ:[113,11,1,""],SaveKey:[113,9,1,""],SetValue:[113,9,1,""],SetValueEx:[113,9,1,""]},abc:{ABCMeta:[114,6,1,""],abstractmethod:[114,9,1,""],abstractproperty:[114,9,1,""]},aepack:{pack:[115,9,1,""],unpack:[115,9,1,""]},aetools:{TalkTo:[116,6,1,""],enumsubst:[116,9,1,""],keysubst:[116,9,1,""],packevent:[116,9,1,""],unpackevent:[116,9,1,""]},aetypes:{AEText:[117,6,1,""],Boolean:[117,6,1,""],Comparison:[117,6,1,""],ComponentItem:[117,6,1,""],Enum:[117,6,1,""],InsertionLoc:[117,6,1,""],IntlText:[117,6,1,""],IntlWritingCode:[117,6,1,""],Keyword:[117,6,1,""],Logical:[117,6,1,""],NProperty:[117,6,1,""],ObjectSpecifier:[117,6,1,""],Ordinal:[117,6,1,""],QDPoint:[117,6,1,""],QDRectangle:[117,6,1,""],RGBColor:[117,6,1,""],Range:[117,6,1,""],StyledText:[117,6,1,""],Type:[117,6,1,""],Unknown:[117,6,1,""]},aifc:{open:[118,9,1,""]},al:{getparams:[119,9,1,""],newconfig:[119,9,1,""],openport:[119,9,1,""],queryparams:[119,9,1,""],setparams:[119,9,1,""]},anydbm:{close:[121,9,1,""],error:[121,10,1,""],open:[121,9,1,""]},argparse:{Action:[123,6,1,""],ArgumentDefaultsHelpFormatter:[123,6,1,""],ArgumentParser:[123,6,1,""],FileType:[123,6,1,""],Namespace:[123,6,1,""],RawDescriptionHelpFormatter:[123,6,1,""],RawTextHelpFormatter:[123,6,1,""]},array:{ArrayType:[124,11,1,""],array:[124,6,1,""]},ast:{AST:[125,6,1,""],NodeTransformer:[125,6,1,""],NodeVisitor:[125,6,1,""],copy_location:[125,9,1,""],dump:[125,9,1,""],fix_missing_locations:[125,9,1,""],get_docstring:[125,9,1,""],increment_lineno:[125,9,1,""],iter_child_nodes:[125,9,1,""],iter_fields:[125,9,1,""],literal_eval:[125,9,1,""],parse:[125,9,1,""],walk:[125,9,1,""]},asynchat:{async_chat:[126,6,1,""],fifo:[126,6,1,""]},asyncore:{dispatcher:[127,6,1,""],dispatcher_with_send:[127,6,1,""],file_dispatcher:[127,6,1,""],file_wrapper:[127,6,1,""],loop:[127,9,1,""]},atexit:{register:[128,9,1,""]},audioop:{add:[129,9,1,""],adpcm2lin:[129,9,1,""],alaw2lin:[129,9,1,""],avg:[129,9,1,""],avgpp:[129,9,1,""],bias:[129,9,1,""],cross:[129,9,1,""],error:[129,10,1,""],findfactor:[129,9,1,""],findfit:[129,9,1,""],findmax:[129,9,1,""],getsample:[129,9,1,""],lin2adpcm:[129,9,1,""],lin2alaw:[129,9,1,""],lin2lin:[129,9,1,""],lin2ulaw:[129,9,1,""],max:[129,9,1,""],maxpp:[129,9,1,""],minmax:[129,9,1,""],mul:[129,9,1,""],ratecv:[129,9,1,""],reverse:[129,9,1,""],rms:[129,9,1,""],tomono:[129,9,1,""],tostereo:[129,9,1,""],ulaw2lin:[129,9,1,""]},autoGIL:{AutoGILError:[130,10,1,""],installAutoGIL:[130,9,1,""]},base64:{b16decode:[131,9,1,""],b16encode:[131,9,1,""],b32decode:[131,9,1,""],b32encode:[131,9,1,""],b64decode:[131,9,1,""],b64encode:[131,9,1,""],decode:[131,9,1,""],decodestring:[131,9,1,""],encode:[131,9,1,""],encodestring:[131,9,1,""],standard_b64decode:[131,9,1,""],standard_b64encode:[131,9,1,""],urlsafe_b64decode:[131,9,1,""],urlsafe_b64encode:[131,9,1,""]},bdb:{Bdb:[134,6,1,""],BdbQuit:[134,10,1,""],Breakpoint:[134,6,1,""],checkfuncname:[134,9,1,""],effective:[134,9,1,""],set_trace:[134,9,1,""]},binascii:{Error:[135,10,1,""],Incomplete:[135,10,1,""],a2b_base64:[135,9,1,""],a2b_hex:[135,9,1,""],a2b_hqx:[135,9,1,""],a2b_qp:[135,9,1,""],a2b_uu:[135,9,1,""],b2a_base64:[135,9,1,""],b2a_hex:[135,9,1,""],b2a_hqx:[135,9,1,""],b2a_qp:[135,9,1,""],b2a_uu:[135,9,1,""],crc32:[135,9,1,""],crc_hqx:[135,9,1,""],hexlify:[135,9,1,""],rlecode_hqx:[135,9,1,""],rledecode_hqx:[135,9,1,""],unhexlify:[135,9,1,""]},binhex:{Error:[136,10,1,""],binhex:[136,9,1,""],hexbin:[136,9,1,""]},bisect:{bisect:[137,9,1,""],bisect_left:[137,9,1,""],bisect_right:[137,9,1,""],insort:[137,9,1,""],insort_left:[137,9,1,""],insort_right:[137,9,1,""]},bsddb:{btopen:[138,9,1,""],hashopen:[138,9,1,""],rnopen:[138,9,1,""]},bz2:{BZ2Compressor:[139,6,1,""],BZ2Decompressor:[139,6,1,""],BZ2File:[139,6,1,""],compress:[139,9,1,""],decompress:[139,9,1,""]},cStringIO:{InputType:[370,11,1,""],OutputType:[370,11,1,""],StringIO:[370,9,1,""]},calendar:{Calendar:[140,6,1,""],HTMLCalendar:[140,6,1,""],LocaleHTMLCalendar:[140,6,1,""],LocaleTextCalendar:[140,6,1,""],TextCalendar:[140,6,1,""],calendar:[140,9,1,""],day_abbr:[140,11,1,""],day_name:[140,11,1,""],firstweekday:[140,9,1,""],isleap:[140,9,1,""],leapdays:[140,9,1,""],month:[140,9,1,""],month_abbr:[140,11,1,""],month_name:[140,11,1,""],monthcalendar:[140,9,1,""],monthrange:[140,9,1,""],prcal:[140,9,1,""],prmonth:[140,9,1,""],setfirstweekday:[140,9,1,""],timegm:[140,9,1,""],weekday:[140,9,1,""],weekheader:[140,9,1,""]},cd:{BLOCKSIZE:[142,11,1,""],CDROM:[142,11,1,""],DATASIZE:[142,11,1,""],ERROR:[142,11,1,""],NODISC:[142,11,1,""],PAUSED:[142,11,1,""],PLAYING:[142,11,1,""],READY:[142,11,1,""],STILL:[142,11,1,""],atime:[142,11,1,""],audio:[142,11,1,""],catalog:[142,11,1,""],control:[142,11,1,""],createparser:[142,9,1,""],error:[142,10,1,""],ident:[142,11,1,""],index:[142,11,1,""],msftoframe:[142,9,1,""],open:[142,9,1,""],pnum:[142,11,1,""],ptime:[142,11,1,""]},cgi:{escape:[143,9,1,""],parse:[143,9,1,""],parse_header:[143,9,1,""],parse_multipart:[143,9,1,""],parse_qs:[143,9,1,""],parse_qsl:[143,9,1,""],print_directory:[143,9,1,""],print_environ:[143,9,1,""],print_environ_usage:[143,9,1,""],print_form:[143,9,1,""],test:[143,9,1,""]},cgitb:{enable:[145,9,1,""],handler:[145,9,1,""]},chunk:{Chunk:[146,6,1,""]},cmath:{acos:[147,9,1,""],acosh:[147,9,1,""],asin:[147,9,1,""],asinh:[147,9,1,""],atan:[147,9,1,""],atanh:[147,9,1,""],cos:[147,9,1,""],cosh:[147,9,1,""],e:[147,11,1,""],exp:[147,9,1,""],isinf:[147,9,1,""],isnan:[147,9,1,""],log10:[147,9,1,""],log:[147,9,1,""],phase:[147,9,1,""],pi:[147,11,1,""],polar:[147,9,1,""],rect:[147,9,1,""],sin:[147,9,1,""],sinh:[147,9,1,""],sqrt:[147,9,1,""],tan:[147,9,1,""],tanh:[147,9,1,""]},cmd:{Cmd:[148,6,1,""]},code:{InteractiveConsole:[149,6,1,""],InteractiveInterpreter:[149,6,1,""],compile_command:[149,9,1,""],interact:[149,9,1,""]},codecs:{BOM:[150,11,1,""],BOM_BE:[150,11,1,""],BOM_LE:[150,11,1,""],BOM_UTF16:[150,11,1,""],BOM_UTF16_BE:[150,11,1,""],BOM_UTF16_LE:[150,11,1,""],BOM_UTF32:[150,11,1,""],BOM_UTF32_BE:[150,11,1,""],BOM_UTF32_LE:[150,11,1,""],BOM_UTF8:[150,11,1,""],EncodedFile:[150,9,1,""],IncrementalDecoder:[150,6,1,""],IncrementalEncoder:[150,6,1,""],StreamReader:[150,6,1,""],StreamReaderWriter:[150,6,1,""],StreamRecoder:[150,6,1,""],StreamWriter:[150,6,1,""],backslashreplace_errors:[150,9,1,""],decode:[150,9,1,""],encode:[150,9,1,""],getdecoder:[150,9,1,""],getencoder:[150,9,1,""],getincrementaldecoder:[150,9,1,""],getincrementalencoder:[150,9,1,""],getreader:[150,9,1,""],getwriter:[150,9,1,""],ignore_errors:[150,9,1,""],iterdecode:[150,9,1,""],iterencode:[150,9,1,""],lookup:[150,9,1,""],lookup_error:[150,9,1,""],open:[150,9,1,""],register:[150,9,1,""],register_error:[150,9,1,""],replace_errors:[150,9,1,""],strict_errors:[150,9,1,""],xmlcharrefreplace_errors:[150,9,1,""]},codeop:{CommandCompiler:[151,6,1,""],Compile:[151,6,1,""],compile_command:[151,9,1,""]},collections:{Callable:[152,6,1,""],Container:[152,6,1,""],Counter:[152,6,1,""],Hashable:[152,6,1,""],ItemsView:[152,6,1,""],Iterable:[152,6,1,""],Iterator:[152,6,1,""],KeysView:[152,6,1,""],Mapping:[152,6,1,""],MappingView:[152,6,1,""],MutableMapping:[152,6,1,""],MutableSequence:[152,6,1,""],MutableSet:[152,6,1,""],OrderedDict:[152,6,1,""],Sequence:[152,6,1,""],Set:[152,6,1,""],Sized:[152,6,1,""],ValuesView:[152,6,1,""],defaultdict:[152,6,1,""],deque:[152,6,1,""],namedtuple:[152,9,1,""]},colorsys:{hls_to_rgb:[154,9,1,""],hsv_to_rgb:[154,9,1,""],rgb_to_hls:[154,9,1,""],rgb_to_hsv:[154,9,1,""],rgb_to_yiq:[154,9,1,""],yiq_to_rgb:[154,9,1,""]},commands:{getoutput:[155,9,1,""],getstatus:[155,9,1,""],getstatusoutput:[155,9,1,""]},compileall:{"-d":[156,13,1,"cmdoption-compileall-d"],"-f":[156,13,1,"cmdoption-compileall-f"],"-i":[156,13,1,"cmdoption-compileall-i"],"-l":[156,13,1,"cmdoption-compileall-l"],"-q":[156,13,1,"cmdoption-compileall-q"],"-x":[156,13,1,"cmdoption-compileall-x"],compile_dir:[156,9,1,""],compile_file:[156,9,1,""],compile_path:[156,9,1,""],directory:[156,13,1,"cmdoption-compileall-arg-directory"],file:[156,13,1,"cmdoption-compileall-arg-file"]},compiler:{ast:[157,5,0,"-"],compile:[157,9,1,""],compileFile:[157,9,1,""],parse:[157,9,1,""],parseFile:[157,9,1,""],visitor:[157,5,0,"-"],walk:[157,9,1,""]},container:{__iter__:[368,8,1,""]},contextlib:{closing:[160,9,1,""],contextmanager:[160,9,1,""],nested:[160,9,1,""]},contextmanager:{__enter__:[368,8,1,""],__exit__:[368,8,1,""]},cookielib:{Cookie:[162,6,1,""],CookieJar:[162,6,1,""],CookiePolicy:[162,6,1,""],DefaultCookiePolicy:[162,6,1,""],FileCookieJar:[162,6,1,""],LWPCookieJar:[162,6,1,""],LoadError:[162,10,1,""],MozillaCookieJar:[162,6,1,""]},copy:{copy:[163,9,1,""],deepcopy:[163,9,1,""],error:[163,10,1,""]},copy_reg:{constructor:[164,9,1,""],pickle:[164,9,1,""]},crypt:{crypt:[165,9,1,""]},csv:{Dialect:[167,6,1,""],DictReader:[167,6,1,""],DictWriter:[167,6,1,""],Error:[167,10,1,""],QUOTE_ALL:[167,11,1,""],QUOTE_MINIMAL:[167,11,1,""],QUOTE_NONE:[167,11,1,""],QUOTE_NONNUMERIC:[167,11,1,""],Sniffer:[167,6,1,""],excel:[167,6,1,""],excel_tab:[167,6,1,""],field_size_limit:[167,9,1,""],get_dialect:[167,9,1,""],list_dialects:[167,9,1,""],reader:[167,9,1,""],register_dialect:[167,9,1,""],unregister_dialect:[167,9,1,""],writer:[167,9,1,""]},ctypes:{ArgumentError:[168,10,1,""],Array:[168,6,1,""],BigEndianStructure:[168,6,1,""],CDLL:[168,6,1,""],CFUNCTYPE:[168,9,1,""],DllCanUnloadNow:[168,9,1,""],DllGetClassObject:[168,9,1,""],FormatError:[168,9,1,""],GetLastError:[168,9,1,""],HRESULT:[168,6,1,""],LibraryLoader:[168,6,1,""],LittleEndianStructure:[168,6,1,""],OleDLL:[168,6,1,""],POINTER:[168,9,1,""],PYFUNCTYPE:[168,9,1,""],PyDLL:[168,6,1,""],Structure:[168,6,1,""],Union:[168,6,1,""],WINFUNCTYPE:[168,9,1,""],WinDLL:[168,6,1,""],WinError:[168,9,1,""],_CData:[168,6,1,""],_FuncPtr:[168,6,1,""],_Pointer:[168,6,1,""],_SimpleCData:[168,6,1,""],addressof:[168,9,1,""],alignment:[168,9,1,""],byref:[168,9,1,""],c_bool:[168,6,1,""],c_byte:[168,6,1,""],c_char:[168,6,1,""],c_char_p:[168,6,1,""],c_double:[168,6,1,""],c_float:[168,6,1,""],c_int16:[168,6,1,""],c_int32:[168,6,1,""],c_int64:[168,6,1,""],c_int8:[168,6,1,""],c_int:[168,6,1,""],c_long:[168,6,1,""],c_longdouble:[168,6,1,""],c_longlong:[168,6,1,""],c_short:[168,6,1,""],c_size_t:[168,6,1,""],c_ssize_t:[168,6,1,""],c_ubyte:[168,6,1,""],c_uint16:[168,6,1,""],c_uint32:[168,6,1,""],c_uint64:[168,6,1,""],c_uint8:[168,6,1,""],c_uint:[168,6,1,""],c_ulong:[168,6,1,""],c_ulonglong:[168,6,1,""],c_ushort:[168,6,1,""],c_void_p:[168,6,1,""],c_wchar:[168,6,1,""],c_wchar_p:[168,6,1,""],cast:[168,9,1,""],create_string_buffer:[168,9,1,""],create_unicode_buffer:[168,9,1,""],get_errno:[168,9,1,""],get_last_error:[168,9,1,""],memmove:[168,9,1,""],memset:[168,9,1,""],pointer:[168,9,1,""],py_object:[168,6,1,""],resize:[168,9,1,""],set_conversion_mode:[168,9,1,""],set_errno:[168,9,1,""],set_last_error:[168,9,1,""],sizeof:[168,9,1,""],string_at:[168,9,1,""],wstring_at:[168,9,1,""]},curses:{ERR:[169,11,1,""],OK:[169,11,1,""],ascii:[170,5,0,"-"],baudrate:[169,9,1,""],beep:[169,9,1,""],can_change_color:[169,9,1,""],cbreak:[169,9,1,""],color_content:[169,9,1,""],color_pair:[169,9,1,""],curs_set:[169,9,1,""],def_prog_mode:[169,9,1,""],def_shell_mode:[169,9,1,""],delay_output:[169,9,1,""],doupdate:[169,9,1,""],echo:[169,9,1,""],endwin:[169,9,1,""],erasechar:[169,9,1,""],error:[169,10,1,""],filter:[169,9,1,""],flash:[169,9,1,""],flushinp:[169,9,1,""],getmouse:[169,9,1,""],getsyx:[169,9,1,""],getwin:[169,9,1,""],halfdelay:[169,9,1,""],has_colors:[169,9,1,""],has_ic:[169,9,1,""],has_il:[169,9,1,""],has_key:[169,9,1,""],init_color:[169,9,1,""],init_pair:[169,9,1,""],initscr:[169,9,1,""],is_term_resized:[169,9,1,""],isendwin:[169,9,1,""],keyname:[169,9,1,""],killchar:[169,9,1,""],longname:[169,9,1,""],meta:[169,9,1,""],mouseinterval:[169,9,1,""],mousemask:[169,9,1,""],napms:[169,9,1,""],newpad:[169,9,1,""],newwin:[169,9,1,""],nl:[169,9,1,""],nocbreak:[169,9,1,""],noecho:[169,9,1,""],nonl:[169,9,1,""],noqiflush:[169,9,1,""],noraw:[169,9,1,""],pair_content:[169,9,1,""],pair_number:[169,9,1,""],panel:[171,5,0,"-"],putp:[169,9,1,""],qiflush:[169,9,1,""],raw:[169,9,1,""],reset_prog_mode:[169,9,1,""],reset_shell_mode:[169,9,1,""],resetty:[169,9,1,""],resize_term:[169,9,1,""],resizeterm:[169,9,1,""],savetty:[169,9,1,""],setsyx:[169,9,1,""],setupterm:[169,9,1,""],start_color:[169,9,1,""],termattrs:[169,9,1,""],termname:[169,9,1,""],textpad:[169,5,0,"-"],tigetflag:[169,9,1,""],tigetnum:[169,9,1,""],tigetstr:[169,9,1,""],tparm:[169,9,1,""],typeahead:[169,9,1,""],unctrl:[169,9,1,""],ungetch:[169,9,1,""],ungetmouse:[169,9,1,""],use_default_colors:[169,9,1,""],use_env:[169,9,1,""],version:[169,11,1,""],wrapper:[169,9,1,""]},datetime:{MAXYEAR:[174,11,1,""],MINYEAR:[174,11,1,""],date:[174,6,1,""],datetime:[174,6,1,""],time:[174,6,1,""],timedelta:[174,6,1,""],tzinfo:[174,6,1,""]},dbhash:{error:[175,10,1,""],open:[175,9,1,""]},dbm:{close:[176,9,1,""],error:[176,10,1,""],library:[176,11,1,""],open:[176,9,1,""]},decimal:{BasicContext:[178,6,1,""],Clamped:[178,6,1,""],Context:[178,6,1,""],Decimal:[178,6,1,""],DecimalException:[178,6,1,""],DefaultContext:[178,6,1,""],DivisionByZero:[178,6,1,""],ExtendedContext:[178,6,1,""],Inexact:[178,6,1,""],InvalidOperation:[178,6,1,""],Overflow:[178,6,1,""],Rounded:[178,6,1,""],Subnormal:[178,6,1,""],Underflow:[178,6,1,""],getcontext:[178,9,1,""],localcontext:[178,9,1,""],setcontext:[178,9,1,""]},definition:{__name__:[368,7,1,""]},dict:{clear:[368,8,1,""],copy:[368,8,1,""],fromkeys:[368,8,1,""],get:[368,8,1,""],has_key:[368,8,1,""],items:[368,8,1,""],iteritems:[368,8,1,""],iterkeys:[368,8,1,""],itervalues:[368,8,1,""],keys:[368,8,1,""],pop:[368,8,1,""],popitem:[368,8,1,""],setdefault:[368,8,1,""],update:[368,8,1,""],values:[368,8,1,""],viewitems:[368,8,1,""],viewkeys:[368,8,1,""],viewvalues:[368,8,1,""]},difflib:{Differ:[180,6,1,""],HtmlDiff:[180,6,1,""],IS_CHARACTER_JUNK:[180,9,1,""],IS_LINE_JUNK:[180,9,1,""],SequenceMatcher:[180,6,1,""],context_diff:[180,9,1,""],get_close_matches:[180,9,1,""],ndiff:[180,9,1,""],restore:[180,9,1,""],unified_diff:[180,9,1,""]},dircache:{annotate:[181,9,1,""],listdir:[181,9,1,""],opendir:[181,9,1,""],reset:[181,9,1,""]},dis:{cmp_op:[182,11,1,""],dis:[182,9,1,""],disassemble:[182,9,1,""],disco:[182,9,1,""],distb:[182,9,1,""],findlabels:[182,9,1,""],findlinestarts:[182,9,1,""],hascompare:[182,11,1,""],hasconst:[182,11,1,""],hasfree:[182,11,1,""],hasjabs:[182,11,1,""],hasjrel:[182,11,1,""],haslocal:[182,11,1,""],hasname:[182,11,1,""],opmap:[182,11,1,""],opname:[182,11,1,""]},distutils:{archive_util:[63,5,0,"-"],bcppcompiler:[63,5,0,"-"],ccompiler:[63,5,0,"-"],cmd:[63,5,0,"-"],command:[63,5,0,"-"],core:[63,5,0,"-"],cygwinccompiler:[63,5,0,"-"],debug:[63,5,0,"-"],dep_util:[63,5,0,"-"],dir_util:[63,5,0,"-"],dist:[63,5,0,"-"],emxccompiler:[63,5,0,"-"],errors:[63,5,0,"-"],extension:[63,5,0,"-"],fancy_getopt:[63,5,0,"-"],file_util:[63,5,0,"-"],filelist:[63,5,0,"-"],log:[63,5,0,"-"],msvccompiler:[63,5,0,"-"],spawn:[63,5,0,"-"],sysconfig:[63,5,0,"-"],text_file:[63,5,0,"-"],unixccompiler:[63,5,0,"-"],util:[63,5,0,"-"],version:[63,5,0,"-"]},dl:{RTLD_LAZY:[185,11,1,""],RTLD_NOW:[185,11,1,""],error:[185,10,1,""],open:[185,9,1,""]},doctest:{COMPARISON_FLAGS:[186,11,1,""],DONT_ACCEPT_BLANKLINE:[186,11,1,""],DONT_ACCEPT_TRUE_FOR_1:[186,11,1,""],DebugRunner:[186,6,1,""],DocFileSuite:[186,9,1,""],DocTest:[186,6,1,""],DocTestFailure:[186,10,1,""],DocTestFinder:[186,6,1,""],DocTestParser:[186,6,1,""],DocTestRunner:[186,6,1,""],DocTestSuite:[186,9,1,""],ELLIPSIS:[186,11,1,""],Example:[186,6,1,""],IGNORE_EXCEPTION_DETAIL:[186,11,1,""],NORMALIZE_WHITESPACE:[186,11,1,""],OutputChecker:[186,6,1,""],REPORTING_FLAGS:[186,11,1,""],REPORT_CDIFF:[186,11,1,""],REPORT_NDIFF:[186,11,1,""],REPORT_ONLY_FIRST_FAILURE:[186,11,1,""],REPORT_UDIFF:[186,11,1,""],SKIP:[186,11,1,""],UnexpectedException:[186,10,1,""],debug:[186,9,1,""],debug_src:[186,9,1,""],register_optionflag:[186,9,1,""],run_docstring_examples:[186,9,1,""],script_from_examples:[186,9,1,""],set_unittest_reportflags:[186,9,1,""],testfile:[186,9,1,""],testmod:[186,9,1,""],testsource:[186,9,1,""]},dumbdbm:{close:[188,9,1,""],error:[188,10,1,""],open:[188,9,1,""]},email:{charset:[194,5,0,"-"],encoders:[195,5,0,"-"],errors:[196,5,0,"-"],generator:[197,5,0,"-"],header:[198,5,0,"-"],iterators:[199,5,0,"-"],message:[200,5,0,"-"],message_from_file:[202,9,1,""],message_from_string:[202,9,1,""],mime:[201,5,0,"-"],parser:[202,5,0,"-"],utils:[203,5,0,"-"]},encodings:{idna:[150,5,0,"-"],utf_8_sig:[150,5,0,"-"]},ensurepip:{bootstrap:[204,9,1,""],version:[204,9,1,""]},errno:{E2BIG:[205,11,1,""],EACCES:[205,11,1,""],EADDRINUSE:[205,11,1,""],EADDRNOTAVAIL:[205,11,1,""],EADV:[205,11,1,""],EAFNOSUPPORT:[205,11,1,""],EAGAIN:[205,11,1,""],EALREADY:[205,11,1,""],EBADE:[205,11,1,""],EBADF:[205,11,1,""],EBADFD:[205,11,1,""],EBADMSG:[205,11,1,""],EBADR:[205,11,1,""],EBADRQC:[205,11,1,""],EBADSLT:[205,11,1,""],EBFONT:[205,11,1,""],EBUSY:[205,11,1,""],ECHILD:[205,11,1,""],ECHRNG:[205,11,1,""],ECOMM:[205,11,1,""],ECONNABORTED:[205,11,1,""],ECONNREFUSED:[205,11,1,""],ECONNRESET:[205,11,1,""],EDEADLK:[205,11,1,""],EDEADLOCK:[205,11,1,""],EDESTADDRREQ:[205,11,1,""],EDOM:[205,11,1,""],EDOTDOT:[205,11,1,""],EDQUOT:[205,11,1,""],EEXIST:[205,11,1,""],EFAULT:[205,11,1,""],EFBIG:[205,11,1,""],EHOSTDOWN:[205,11,1,""],EHOSTUNREACH:[205,11,1,""],EIDRM:[205,11,1,""],EILSEQ:[205,11,1,""],EINPROGRESS:[205,11,1,""],EINTR:[205,11,1,""],EINVAL:[205,11,1,""],EIO:[205,11,1,""],EISCONN:[205,11,1,""],EISDIR:[205,11,1,""],EISNAM:[205,11,1,""],EL2HLT:[205,11,1,""],EL2NSYNC:[205,11,1,""],EL3HLT:[205,11,1,""],EL3RST:[205,11,1,""],ELIBACC:[205,11,1,""],ELIBBAD:[205,11,1,""],ELIBEXEC:[205,11,1,""],ELIBMAX:[205,11,1,""],ELIBSCN:[205,11,1,""],ELNRNG:[205,11,1,""],ELOOP:[205,11,1,""],EMFILE:[205,11,1,""],EMLINK:[205,11,1,""],EMSGSIZE:[205,11,1,""],EMULTIHOP:[205,11,1,""],ENAMETOOLONG:[205,11,1,""],ENAVAIL:[205,11,1,""],ENETDOWN:[205,11,1,""],ENETRESET:[205,11,1,""],ENETUNREACH:[205,11,1,""],ENFILE:[205,11,1,""],ENOANO:[205,11,1,""],ENOBUFS:[205,11,1,""],ENOCSI:[205,11,1,""],ENODATA:[205,11,1,""],ENODEV:[205,11,1,""],ENOENT:[205,11,1,""],ENOEXEC:[205,11,1,""],ENOLCK:[205,11,1,""],ENOLINK:[205,11,1,""],ENOMEM:[205,11,1,""],ENOMSG:[205,11,1,""],ENONET:[205,11,1,""],ENOPKG:[205,11,1,""],ENOPROTOOPT:[205,11,1,""],ENOSPC:[205,11,1,""],ENOSR:[205,11,1,""],ENOSTR:[205,11,1,""],ENOSYS:[205,11,1,""],ENOTBLK:[205,11,1,""],ENOTCONN:[205,11,1,""],ENOTDIR:[205,11,1,""],ENOTEMPTY:[205,11,1,""],ENOTNAM:[205,11,1,""],ENOTSOCK:[205,11,1,""],ENOTTY:[205,11,1,""],ENOTUNIQ:[205,11,1,""],ENXIO:[205,11,1,""],EOPNOTSUPP:[205,11,1,""],EOVERFLOW:[205,11,1,""],EPERM:[205,11,1,""],EPFNOSUPPORT:[205,11,1,""],EPIPE:[205,11,1,""],EPROTO:[205,11,1,""],EPROTONOSUPPORT:[205,11,1,""],EPROTOTYPE:[205,11,1,""],ERANGE:[205,11,1,""],EREMCHG:[205,11,1,""],EREMOTE:[205,11,1,""],EREMOTEIO:[205,11,1,""],ERESTART:[205,11,1,""],EROFS:[205,11,1,""],ESHUTDOWN:[205,11,1,""],ESOCKTNOSUPPORT:[205,11,1,""],ESPIPE:[205,11,1,""],ESRCH:[205,11,1,""],ESRMNT:[205,11,1,""],ESTALE:[205,11,1,""],ESTRPIPE:[205,11,1,""],ETIME:[205,11,1,""],ETIMEDOUT:[205,11,1,""],ETOOMANYREFS:[205,11,1,""],ETXTBSY:[205,11,1,""],EUCLEAN:[205,11,1,""],EUNATCH:[205,11,1,""],EUSERS:[205,11,1,""],EWOULDBLOCK:[205,11,1,""],EXDEV:[205,11,1,""],EXFULL:[205,11,1,""],errorcode:[205,11,1,""]},exceptions:{ArithmeticError:[206,10,1,""],AssertionError:[206,10,1,""],AttributeError:[206,10,1,""],BaseException:[206,10,1,""],BufferError:[206,10,1,""],DeprecationWarning:[206,10,1,""],EOFError:[206,10,1,""],EnvironmentError:[206,10,1,""],Exception:[206,10,1,""],FloatingPointError:[206,10,1,""],FutureWarning:[206,10,1,""],GeneratorExit:[206,10,1,""],IOError:[206,10,1,""],ImportError:[206,10,1,""],ImportWarning:[206,10,1,""],IndentationError:[206,10,1,""],IndexError:[206,10,1,""],KeyError:[206,10,1,""],KeyboardInterrupt:[206,10,1,""],LookupError:[206,10,1,""],MemoryError:[206,10,1,""],NameError:[206,10,1,""],NotImplementedError:[206,10,1,""],OSError:[206,10,1,""],OverflowError:[206,10,1,""],PendingDeprecationWarning:[206,10,1,""],ReferenceError:[206,10,1,""],RuntimeError:[206,10,1,""],RuntimeWarning:[206,10,1,""],StandardError:[206,10,1,""],StopIteration:[206,10,1,""],SyntaxError:[206,10,1,""],SyntaxWarning:[206,10,1,""],SystemError:[206,10,1,""],SystemExit:[206,10,1,""],TabError:[206,10,1,""],TypeError:[206,10,1,""],UnboundLocalError:[206,10,1,""],UnicodeDecodeError:[206,10,1,""],UnicodeEncodeError:[206,10,1,""],UnicodeError:[206,10,1,""],UnicodeTranslateError:[206,10,1,""],UnicodeWarning:[206,10,1,""],UserWarning:[206,10,1,""],VMSError:[206,10,1,""],ValueError:[206,10,1,""],Warning:[206,10,1,""],WindowsError:[206,10,1,""],ZeroDivisionError:[206,10,1,""]},fcntl:{fcntl:[207,9,1,""],flock:[207,9,1,""],ioctl:[207,9,1,""],lockf:[207,9,1,""]},file:{close:[368,8,1,""],closed:[368,7,1,""],encoding:[368,7,1,""],errors:[368,7,1,""],fileno:[368,8,1,""],flush:[368,8,1,""],isatty:[368,8,1,""],mode:[368,7,1,""],name:[368,7,1,""],newlines:[368,7,1,""],next:[368,8,1,""],read:[368,8,1,""],readline:[368,8,1,""],readlines:[368,8,1,""],seek:[368,8,1,""],softspace:[368,7,1,""],tell:[368,8,1,""],truncate:[368,8,1,""],write:[368,8,1,""],writelines:[368,8,1,""],xreadlines:[368,8,1,""]},filecmp:{cmp:[208,9,1,""],cmpfiles:[208,9,1,""],dircmp:[208,6,1,""]},fileinput:{FileInput:[210,6,1,""],close:[210,9,1,""],filelineno:[210,9,1,""],filename:[210,9,1,""],fileno:[210,9,1,""],hook_compressed:[210,9,1,""],hook_encoded:[210,9,1,""],input:[210,9,1,""],isfirstline:[210,9,1,""],isstdin:[210,9,1,""],lineno:[210,9,1,""],nextfile:[210,9,1,""]},findertools:{Print:[271,9,1,""],copy:[271,9,1,""],launch:[271,9,1,""],move:[271,9,1,""],restart:[271,9,1,""],shutdown:[271,9,1,""],sleep:[271,9,1,""]},fl:{check_forms:[212,9,1,""],color:[212,9,1,""],do_forms:[212,9,1,""],get_directory:[212,9,1,""],get_filename:[212,9,1,""],get_mouse:[212,9,1,""],get_pattern:[212,9,1,""],get_rgbmode:[212,9,1,""],getmcolor:[212,9,1,""],isqueued:[212,9,1,""],make_form:[212,9,1,""],mapcolor:[212,9,1,""],qdevice:[212,9,1,""],qenter:[212,9,1,""],qread:[212,9,1,""],qreset:[212,9,1,""],qtest:[212,9,1,""],set_event_call_back:[212,9,1,""],set_graphics_mode:[212,9,1,""],show_choice:[212,9,1,""],show_file_selector:[212,9,1,""],show_input:[212,9,1,""],show_message:[212,9,1,""],show_question:[212,9,1,""],tie:[212,9,1,""],unqdevice:[212,9,1,""]},fm:{enumerate:[213,9,1,""],findfont:[213,9,1,""],fontpath:[213,9,1,""],init:[213,9,1,""],prstr:[213,9,1,""],setpath:[213,9,1,""]},fnmatch:{filter:[214,9,1,""],fnmatch:[214,9,1,""],fnmatchcase:[214,9,1,""],translate:[214,9,1,""]},formatter:{AS_IS:[215,11,1,""],AbstractFormatter:[215,6,1,""],AbstractWriter:[215,6,1,""],DumbWriter:[215,6,1,""],NullFormatter:[215,6,1,""],NullWriter:[215,6,1,""]},fpectl:{FloatingPointError:[216,10,1,""],turnoff_sigfpe:[216,9,1,""],turnon_sigfpe:[216,9,1,""]},fpformat:{NotANumber:[217,10,1,""],fix:[217,9,1,""],sci:[217,9,1,""]},fractions:{Fraction:[218,6,1,""],gcd:[218,9,1,""]},frozenset:{add:[368,8,1,""],clear:[368,8,1,""],copy:[368,8,1,""],difference:[368,8,1,""],difference_update:[368,8,1,""],discard:[368,8,1,""],intersection:[368,8,1,""],intersection_update:[368,8,1,""],isdisjoint:[368,8,1,""],issubset:[368,8,1,""],issuperset:[368,8,1,""],pop:[368,8,1,""],remove:[368,8,1,""],symmetric_difference:[368,8,1,""],symmetric_difference_update:[368,8,1,""],union:[368,8,1,""],update:[368,8,1,""]},ftplib:{FTP:[221,6,1,""],FTP_TLS:[221,6,1,""],all_errors:[221,11,1,""],error_perm:[221,10,1,""],error_proto:[221,10,1,""],error_reply:[221,10,1,""],error_temp:[221,10,1,""]},functools:{cmp_to_key:[223,9,1,""],partial:[223,9,1,""],reduce:[223,9,1,""],total_ordering:[223,9,1,""],update_wrapper:[223,9,1,""],wraps:[223,9,1,""]},future_builtins:{ascii:[224,9,1,""],filter:[224,9,1,""],hex:[224,9,1,""],map:[224,9,1,""],oct:[224,9,1,""],zip:[224,9,1,""]},gc:{DEBUG_COLLECTABLE:[225,11,1,""],DEBUG_INSTANCES:[225,11,1,""],DEBUG_LEAK:[225,11,1,""],DEBUG_OBJECTS:[225,11,1,""],DEBUG_SAVEALL:[225,11,1,""],DEBUG_STATS:[225,11,1,""],DEBUG_UNCOLLECTABLE:[225,11,1,""],collect:[225,9,1,""],disable:[225,9,1,""],enable:[225,9,1,""],garbage:[225,11,1,""],get_count:[225,9,1,""],get_debug:[225,9,1,""],get_objects:[225,9,1,""],get_referents:[225,9,1,""],get_referrers:[225,9,1,""],get_threshold:[225,9,1,""],is_tracked:[225,9,1,""],isenabled:[225,9,1,""],set_debug:[225,9,1,""],set_threshold:[225,9,1,""]},gdbm:{close:[226,9,1,""],error:[226,10,1,""],firstkey:[226,9,1,""],nextkey:[226,9,1,""],open:[226,9,1,""],reorganize:[226,9,1,""],sync:[226,9,1,""]},generator:{"throw":[442,8,1,""],close:[442,8,1,""],next:[442,8,1,""],send:[442,8,1,""]},gensuitemodule:{is_scriptable:[227,9,1,""],processfile:[227,9,1,""],processfile_fromresource:[227,9,1,""]},getopt:{GetoptError:[228,10,1,""],error:[228,10,1,""],getopt:[228,9,1,""],gnu_getopt:[228,9,1,""]},getpass:{GetPassWarning:[229,10,1,""],getpass:[229,9,1,""],getuser:[229,9,1,""]},gettext:{NullTranslations:[230,6,1,""],bind_textdomain_codeset:[230,9,1,""],bindtextdomain:[230,9,1,""],dgettext:[230,9,1,""],dngettext:[230,9,1,""],find:[230,9,1,""],gettext:[230,9,1,""],install:[230,9,1,""],ldgettext:[230,9,1,""],ldngettext:[230,9,1,""],lgettext:[230,9,1,""],lngettext:[230,9,1,""],ngettext:[230,9,1,""],textdomain:[230,9,1,""],translation:[230,9,1,""]},gl:{endpick:[231,9,1,""],endselect:[231,9,1,""],nurbscurve:[231,9,1,""],nurbssurface:[231,9,1,""],nvarray:[231,9,1,""],pick:[231,9,1,""],pwlcurve:[231,9,1,""],select:[231,9,1,""],varray:[231,9,1,""],vnarray:[231,9,1,""]},glob:{glob:[232,9,1,""],iglob:[232,9,1,""]},grp:{getgrall:[233,9,1,""],getgrgid:[233,9,1,""],getgrnam:[233,9,1,""]},gzip:{GzipFile:[234,6,1,""],open:[234,9,1,""]},hashlib:{algorithms_available:[235,11,1,""],algorithms_guaranteed:[235,11,1,""],pbkdf2_hmac:[235,9,1,""]},heapq:{heapify:[236,9,1,""],heappop:[236,9,1,""],heappush:[236,9,1,""],heappushpop:[236,9,1,""],heapreplace:[236,9,1,""],merge:[236,9,1,""],nlargest:[236,9,1,""],nsmallest:[236,9,1,""]},hmac:{"new":[237,9,1,""],compare_digest:[237,9,1,""]},hotshot:{Profile:[238,6,1,""],stats:[238,5,0,"-"]},htmlentitydefs:{codepoint2name:[239,11,1,""],entitydefs:[239,11,1,""],name2codepoint:[239,11,1,""]},htmllib:{HTMLParseError:[239,10,1,""],HTMLParser:[239,6,1,""]},httplib:{BadStatusLine:[241,10,1,""],CannotSendHeader:[241,10,1,""],CannotSendRequest:[241,10,1,""],HTTPConnection:[241,6,1,""],HTTPException:[241,10,1,""],HTTPMessage:[241,6,1,""],HTTPResponse:[241,6,1,""],HTTPSConnection:[241,6,1,""],HTTPS_PORT:[241,11,1,""],HTTP_PORT:[241,11,1,""],ImproperConnectionState:[241,10,1,""],IncompleteRead:[241,10,1,""],InvalidURL:[241,10,1,""],NotConnected:[241,10,1,""],ResponseNotReady:[241,10,1,""],UnimplementedFileMode:[241,10,1,""],UnknownProtocol:[241,10,1,""],UnknownTransferEncoding:[241,10,1,""],responses:[241,11,1,""]},ic:{IC:[243,6,1,""],error:[243,10,1,""],launchurl:[243,9,1,""],mapfile:[243,9,1,""],maptypecreator:[243,9,1,""],parseurl:[243,9,1,""],settypecreator:[243,9,1,""]},imageop:{backward_compatible:[245,11,1,""],crop:[245,9,1,""],dither2grey2:[245,9,1,""],dither2mono:[245,9,1,""],error:[245,10,1,""],grey22grey:[245,9,1,""],grey2grey2:[245,9,1,""],grey2grey4:[245,9,1,""],grey2mono:[245,9,1,""],grey42grey:[245,9,1,""],mono2grey:[245,9,1,""],scale:[245,9,1,""],tovideo:[245,9,1,""]},imaplib:{IMAP4:[246,6,1,""],IMAP4_SSL:[246,6,1,""],IMAP4_stream:[246,6,1,""],Int2AP:[246,9,1,""],Internaldate2tuple:[246,9,1,""],ParseFlags:[246,9,1,""],Time2Internaldate:[246,9,1,""]},imgfile:{error:[247,10,1,""],getsizes:[247,9,1,""],read:[247,9,1,""],readscaled:[247,9,1,""],ttob:[247,9,1,""],write:[247,9,1,""]},imghdr:{tests:[248,11,1,""],what:[248,9,1,""]},imp:{C_BUILTIN:[249,11,1,""],C_EXTENSION:[249,11,1,""],NullImporter:[249,6,1,""],PKG_DIRECTORY:[249,11,1,""],PY_COMPILED:[249,11,1,""],PY_FROZEN:[249,11,1,""],PY_SOURCE:[249,11,1,""],SEARCH_ERROR:[249,11,1,""],acquire_lock:[249,9,1,""],find_module:[249,9,1,""],get_magic:[249,9,1,""],get_suffixes:[249,9,1,""],init_builtin:[249,9,1,""],init_frozen:[249,9,1,""],is_builtin:[249,9,1,""],is_frozen:[249,9,1,""],load_compiled:[249,9,1,""],load_dynamic:[249,9,1,""],load_module:[249,9,1,""],load_source:[249,9,1,""],lock_held:[249,9,1,""],new_module:[249,9,1,""],release_lock:[249,9,1,""]},importlib:{import_module:[250,9,1,""]},imputil:{BuiltinImporter:[251,6,1,""],DynLoadSuffixImporter:[251,6,1,""],ImportManager:[251,6,1,""],Importer:[251,6,1,""],py_suffix_importer:[251,9,1,""]},inspect:{cleandoc:[253,9,1,""],currentframe:[253,9,1,""],formatargspec:[253,9,1,""],formatargvalues:[253,9,1,""],getargspec:[253,9,1,""],getargvalues:[253,9,1,""],getcallargs:[253,9,1,""],getclasstree:[253,9,1,""],getcomments:[253,9,1,""],getdoc:[253,9,1,""],getfile:[253,9,1,""],getframeinfo:[253,9,1,""],getinnerframes:[253,9,1,""],getmembers:[253,9,1,""],getmodule:[253,9,1,""],getmoduleinfo:[253,9,1,""],getmodulename:[253,9,1,""],getmro:[253,9,1,""],getouterframes:[253,9,1,""],getsource:[253,9,1,""],getsourcefile:[253,9,1,""],getsourcelines:[253,9,1,""],isabstract:[253,9,1,""],isbuiltin:[253,9,1,""],isclass:[253,9,1,""],iscode:[253,9,1,""],isdatadescriptor:[253,9,1,""],isframe:[253,9,1,""],isfunction:[253,9,1,""],isgenerator:[253,9,1,""],isgeneratorfunction:[253,9,1,""],isgetsetdescriptor:[253,9,1,""],ismemberdescriptor:[253,9,1,""],ismethod:[253,9,1,""],ismethoddescriptor:[253,9,1,""],ismodule:[253,9,1,""],isroutine:[253,9,1,""],istraceback:[253,9,1,""],stack:[253,9,1,""],trace:[253,9,1,""]},instance:{__class__:[368,7,1,""]},io:{BlockingIOError:[256,10,1,""],BufferedIOBase:[256,6,1,""],BufferedRWPair:[256,6,1,""],BufferedRandom:[256,6,1,""],BufferedReader:[256,6,1,""],BufferedWriter:[256,6,1,""],BytesIO:[256,6,1,""],DEFAULT_BUFFER_SIZE:[256,11,1,""],FileIO:[256,6,1,""],IOBase:[256,6,1,""],IncrementalNewlineDecoder:[256,6,1,""],RawIOBase:[256,6,1,""],StringIO:[256,6,1,""],TextIOBase:[256,6,1,""],TextIOWrapper:[256,6,1,""],UnsupportedOperation:[256,10,1,""],open:[256,9,1,""]},iterator:{__iter__:[368,8,1,""],next:[368,8,1,""]},itertools:{chain:[258,9,1,""],combinations:[258,9,1,""],combinations_with_replacement:[258,9,1,""],compress:[258,9,1,""],count:[258,9,1,""],cycle:[258,9,1,""],dropwhile:[258,9,1,""],groupby:[258,9,1,""],ifilter:[258,9,1,""],ifilterfalse:[258,9,1,""],imap:[258,9,1,""],islice:[258,9,1,""],izip:[258,9,1,""],izip_longest:[258,9,1,""],permutations:[258,9,1,""],product:[258,9,1,""],repeat:[258,9,1,""],starmap:[258,9,1,""],takewhile:[258,9,1,""],tee:[258,9,1,""]},jpeg:{compress:[259,9,1,""],decompress:[259,9,1,""],error:[259,10,1,""],setoption:[259,9,1,""]},json:{JSONDecoder:[260,6,1,""],JSONEncoder:[260,6,1,""],dump:[260,9,1,""],dumps:[260,9,1,""],load:[260,9,1,""],loads:[260,9,1,""]},keyword:{iskeyword:[261,9,1,""],kwlist:[261,11,1,""]},linecache:{checkcache:[263,9,1,""],clearcache:[263,9,1,""],getline:[263,9,1,""]},locale:{ALT_DIGITS:[264,11,1,""],CHAR_MAX:[264,11,1,""],CODESET:[264,11,1,""],CRNCYSTR:[264,11,1,""],D_FMT:[264,11,1,""],D_T_FMT:[264,11,1,""],ERA:[264,11,1,""],ERA_D_FMT:[264,11,1,""],ERA_D_T_FMT:[264,11,1,""],ERA_T_FMT:[264,11,1,""],Error:[264,10,1,""],LC_ALL:[264,11,1,""],LC_COLLATE:[264,11,1,""],LC_CTYPE:[264,11,1,""],LC_MESSAGES:[264,11,1,""],LC_MONETARY:[264,11,1,""],LC_NUMERIC:[264,11,1,""],LC_TIME:[264,11,1,""],NOEXPR:[264,11,1,""],RADIXCHAR:[264,11,1,""],THOUSEP:[264,11,1,""],T_FMT:[264,11,1,""],T_FMT_AMPM:[264,11,1,""],YESEXPR:[264,11,1,""],atof:[264,9,1,""],atoi:[264,9,1,""],bindtextdomain:[264,9,1,""],currency:[264,9,1,""],dcgettext:[264,9,1,""],dgettext:[264,9,1,""],format:[264,9,1,""],format_string:[264,9,1,""],getdefaultlocale:[264,9,1,""],getlocale:[264,9,1,""],getpreferredencoding:[264,9,1,""],gettext:[264,9,1,""],localeconv:[264,9,1,""],nl_langinfo:[264,9,1,""],normalize:[264,9,1,""],resetlocale:[264,9,1,""],setlocale:[264,9,1,""],str:[264,9,1,""],strcoll:[264,9,1,""],strxfrm:[264,9,1,""],textdomain:[264,9,1,""]},logging:{FileHandler:[267,6,1,""],Filter:[265,6,1,""],Formatter:[265,6,1,""],LogRecord:[265,6,1,""],Logger:[265,6,1,""],LoggerAdapter:[265,6,1,""],NullHandler:[267,6,1,""],StreamHandler:[267,6,1,""],addLevelName:[265,9,1,""],basicConfig:[265,9,1,""],captureWarnings:[265,9,1,""],config:[266,5,0,"-"],critical:[265,9,1,""],debug:[265,9,1,""],disable:[265,9,1,""],error:[265,9,1,""],exception:[265,9,1,""],getLevelName:[265,9,1,""],getLogger:[265,9,1,""],getLoggerClass:[265,9,1,""],handlers:[267,5,0,"-"],info:[265,9,1,""],log:[265,9,1,""],makeLogRecord:[265,9,1,""],setLoggerClass:[265,9,1,""],shutdown:[265,9,1,""],warning:[265,9,1,""]},macostools:{BUFSIZ:[271,11,1,""],copy:[271,9,1,""],copytree:[271,9,1,""],mkalias:[271,9,1,""],touched:[271,9,1,""]},mailbox:{Babyl:[273,6,1,""],BabylMailbox:[273,6,1,""],BabylMessage:[273,6,1,""],Error:[273,10,1,""],ExternalClashError:[273,10,1,""],FormatError:[273,10,1,""],MH:[273,6,1,""],MHMailbox:[273,6,1,""],MHMessage:[273,6,1,""],MMDF:[273,6,1,""],MMDFMessage:[273,6,1,""],Mailbox:[273,6,1,""],Maildir:[273,6,1,""],MaildirMessage:[273,6,1,""],Message:[273,6,1,""],MmdfMailbox:[273,6,1,""],NoSuchMailboxError:[273,10,1,""],NotEmptyError:[273,10,1,""],PortableUnixMailbox:[273,6,1,""],UnixMailbox:[273,6,1,""],mbox:[273,6,1,""],mboxMessage:[273,6,1,""]},mailcap:{findmatch:[274,9,1,""],getcaps:[274,9,1,""]},marshal:{dump:[276,9,1,""],dumps:[276,9,1,""],load:[276,9,1,""],loads:[276,9,1,""],version:[276,11,1,""]},math:{acos:[277,9,1,""],acosh:[277,9,1,""],asin:[277,9,1,""],asinh:[277,9,1,""],atan2:[277,9,1,""],atan:[277,9,1,""],atanh:[277,9,1,""],ceil:[277,9,1,""],copysign:[277,9,1,""],cos:[277,9,1,""],cosh:[277,9,1,""],degrees:[277,9,1,""],e:[277,11,1,""],erf:[277,9,1,""],erfc:[277,9,1,""],exp:[277,9,1,""],expm1:[277,9,1,""],fabs:[277,9,1,""],factorial:[277,9,1,""],floor:[277,9,1,""],fmod:[277,9,1,""],frexp:[277,9,1,""],fsum:[277,9,1,""],gamma:[277,9,1,""],hypot:[277,9,1,""],isinf:[277,9,1,""],isnan:[277,9,1,""],ldexp:[277,9,1,""],lgamma:[277,9,1,""],log10:[277,9,1,""],log1p:[277,9,1,""],log:[277,9,1,""],modf:[277,9,1,""],pi:[277,11,1,""],pow:[277,9,1,""],radians:[277,9,1,""],sin:[277,9,1,""],sinh:[277,9,1,""],sqrt:[277,9,1,""],tan:[277,9,1,""],tanh:[277,9,1,""],trunc:[277,9,1,""]},md5:{"new":[278,9,1,""],digest_size:[278,11,1,""],md5:[278,9,1,""]},memoryview:{format:[368,7,1,""],itemsize:[368,7,1,""],ndim:[368,7,1,""],readonly:[368,7,1,""],shape:[368,7,1,""],strides:[368,7,1,""],tobytes:[368,8,1,""],tolist:[368,8,1,""]},mhlib:{Folder:[279,6,1,""],MH:[279,6,1,""],Message:[279,6,1,""]},mimetools:{Message:[280,6,1,""],choose_boundary:[280,9,1,""],copybinary:[280,9,1,""],copyliteral:[280,9,1,""],decode:[280,9,1,""],encode:[280,9,1,""]},mimetypes:{MimeTypes:[281,6,1,""],add_type:[281,9,1,""],common_types:[281,11,1,""],encodings_map:[281,11,1,""],guess_all_extensions:[281,9,1,""],guess_extension:[281,9,1,""],guess_type:[281,9,1,""],init:[281,9,1,""],inited:[281,11,1,""],knownfiles:[281,11,1,""],read_mime_types:[281,9,1,""],suffix_map:[281,11,1,""],types_map:[281,11,1,""]},mimify:{CHARSET:[283,11,1,""],MAXLEN:[283,11,1,""],mime_decode_header:[283,9,1,""],mime_encode_header:[283,9,1,""],mimify:[283,9,1,""],unmimify:[283,9,1,""]},mmap:{mmap:[287,6,1,""]},modulefinder:{AddPackagePath:[288,9,1,""],ModuleFinder:[288,6,1,""],ReplacePackage:[288,9,1,""]},msilib:{Binary:[290,6,1,""],CAB:[290,6,1,""],Control:[290,6,1,""],CreateRecord:[290,9,1,""],Dialog:[290,6,1,""],Directory:[290,6,1,""],FCICreate:[290,9,1,""],Feature:[290,6,1,""],OpenDatabase:[290,9,1,""],RadioButtonGroup:[290,6,1,""],UuidCreate:[290,9,1,""],add_data:[290,9,1,""],add_stream:[290,9,1,""],add_tables:[290,9,1,""],gen_uuid:[290,9,1,""],init_database:[290,9,1,""],schema:[290,11,1,""],sequence:[290,11,1,""],text:[290,11,1,""]},msvcrt:{LK_LOCK:[291,11,1,""],LK_NBLCK:[291,11,1,""],LK_NBRLCK:[291,11,1,""],LK_RLCK:[291,11,1,""],LK_UNLCK:[291,11,1,""],get_osfhandle:[291,9,1,""],getch:[291,9,1,""],getche:[291,9,1,""],getwch:[291,9,1,""],getwche:[291,9,1,""],heapmin:[291,9,1,""],kbhit:[291,9,1,""],locking:[291,9,1,""],open_osfhandle:[291,9,1,""],putch:[291,9,1,""],putwch:[291,9,1,""],setmode:[291,9,1,""],ungetch:[291,9,1,""],ungetwch:[291,9,1,""]},multifile:{MultiFile:[292,6,1,""]},multiprocessing:{Array:[293,9,1,""],BoundedSemaphore:[293,6,1,""],BufferTooShort:[293,10,1,""],Condition:[293,6,1,""],Event:[293,6,1,""],JoinableQueue:[293,6,1,""],Lock:[293,6,1,""],Pipe:[293,9,1,""],Process:[293,6,1,""],Queue:[293,6,1,""],RLock:[293,6,1,""],Semaphore:[293,6,1,""],Value:[293,9,1,""],active_children:[293,9,1,""],connection:[293,5,0,"-"],cpu_count:[293,9,1,""],current_process:[293,9,1,""],dummy:[293,5,0,"-"],freeze_support:[293,9,1,""],get_logger:[293,9,1,""],log_to_stderr:[293,9,1,""],managers:[293,5,0,"-"],pool:[293,5,0,"-"],set_executable:[293,9,1,""],sharedctypes:[293,5,0,"-"]},mutex:{mutex:[294,6,1,""]},netrc:{NetrcParseError:[296,10,1,""],netrc:[296,6,1,""]},nis:{cat:[298,9,1,""],error:[298,10,1,""],get_default_domain:[298,9,1,""],maps:[298,9,1,""],match:[298,9,1,""]},nntplib:{NNTP:[299,6,1,""],NNTPDataError:[299,10,1,""],NNTPError:[299,10,1,""],NNTPPermanentError:[299,10,1,""],NNTPProtocolError:[299,10,1,""],NNTPReplyError:[299,10,1,""],NNTPTemporaryError:[299,10,1,""]},numbers:{Complex:[300,6,1,""],Integral:[300,6,1,""],Number:[300,6,1,""],Rational:[300,6,1,""],Real:[300,6,1,""]},object:{__abs__:[440,8,1,""],__add__:[440,8,1,""],__and__:[440,8,1,""],__call__:[440,8,1,""],__cmp__:[440,8,1,""],__coerce__:[440,8,1,""],__complex__:[440,8,1,""],__contains__:[440,8,1,""],__del__:[440,8,1,""],__delattr__:[440,8,1,""],__delete__:[440,8,1,""],__delitem__:[440,8,1,""],__delslice__:[440,8,1,""],__dict__:[368,7,1,""],__div__:[440,8,1,""],__divmod__:[440,8,1,""],__enter__:[440,8,1,""],__eq__:[440,8,1,""],__exit__:[440,8,1,""],__float__:[440,8,1,""],__floordiv__:[440,8,1,""],__ge__:[440,8,1,""],__get__:[440,8,1,""],__getattr__:[440,8,1,""],__getattribute__:[440,8,1,""],__getinitargs__:[311,8,1,""],__getitem__:[440,8,1,""],__getnewargs__:[311,8,1,""],__getslice__:[440,8,1,""],__getstate__:[311,8,1,""],__gt__:[440,8,1,""],__hash__:[440,8,1,""],__hex__:[440,8,1,""],__iadd__:[440,8,1,""],__iand__:[440,8,1,""],__idiv__:[440,8,1,""],__ifloordiv__:[440,8,1,""],__ilshift__:[440,8,1,""],__imod__:[440,8,1,""],__imul__:[440,8,1,""],__index__:[440,8,1,""],__init__:[440,8,1,""],__int__:[440,8,1,""],__invert__:[440,8,1,""],__ior__:[440,8,1,""],__ipow__:[440,8,1,""],__irshift__:[440,8,1,""],__isub__:[440,8,1,""],__iter__:[440,8,1,""],__itruediv__:[440,8,1,""],__ixor__:[440,8,1,""],__le__:[440,8,1,""],__len__:[440,8,1,""],__long__:[440,8,1,""],__lshift__:[440,8,1,""],__lt__:[440,8,1,""],__members__:[368,7,1,""],__methods__:[368,7,1,""],__missing__:[440,8,1,""],__mod__:[440,8,1,""],__mul__:[440,8,1,""],__ne__:[440,8,1,""],__neg__:[440,8,1,""],__new__:[440,8,1,""],__nonzero__:[440,8,1,""],__oct__:[440,8,1,""],__or__:[440,8,1,""],__pos__:[440,8,1,""],__pow__:[440,8,1,""],__radd__:[440,8,1,""],__rand__:[440,8,1,""],__rcmp__:[440,8,1,""],__rdiv__:[440,8,1,""],__rdivmod__:[440,8,1,""],__reduce__:[311,8,1,""],__reduce_ex__:[311,8,1,""],__repr__:[440,8,1,""],__reversed__:[440,8,1,""],__rfloordiv__:[440,8,1,""],__rlshift__:[440,8,1,""],__rmod__:[440,8,1,""],__rmul__:[440,8,1,""],__ror__:[440,8,1,""],__rpow__:[440,8,1,""],__rrshift__:[440,8,1,""],__rshift__:[440,8,1,""],__rsub__:[440,8,1,""],__rtruediv__:[440,8,1,""],__rxor__:[440,8,1,""],__set__:[440,8,1,""],__setattr__:[440,8,1,""],__setitem__:[440,8,1,""],__setslice__:[440,8,1,""],__setstate__:[311,8,1,""],__str__:[440,8,1,""],__sub__:[440,8,1,""],__truediv__:[440,8,1,""],__unicode__:[440,8,1,""],__xor__:[440,8,1,""]},operator:{__abs__:[302,9,1,""],__add__:[302,9,1,""],__and__:[302,9,1,""],__concat__:[302,9,1,""],__contains__:[302,9,1,""],__delitem__:[302,9,1,""],__delslice__:[302,9,1,""],__div__:[302,9,1,""],__eq__:[302,9,1,""],__floordiv__:[302,9,1,""],__ge__:[302,9,1,""],__getitem__:[302,9,1,""],__getslice__:[302,9,1,""],__gt__:[302,9,1,""],__iadd__:[302,9,1,""],__iand__:[302,9,1,""],__iconcat__:[302,9,1,""],__idiv__:[302,9,1,""],__ifloordiv__:[302,9,1,""],__ilshift__:[302,9,1,""],__imod__:[302,9,1,""],__imul__:[302,9,1,""],__index__:[302,9,1,""],__inv__:[302,9,1,""],__invert__:[302,9,1,""],__ior__:[302,9,1,""],__ipow__:[302,9,1,""],__irepeat__:[302,9,1,""],__irshift__:[302,9,1,""],__isub__:[302,9,1,""],__itruediv__:[302,9,1,""],__ixor__:[302,9,1,""],__le__:[302,9,1,""],__lshift__:[302,9,1,""],__lt__:[302,9,1,""],__mod__:[302,9,1,""],__mul__:[302,9,1,""],__ne__:[302,9,1,""],__neg__:[302,9,1,""],__not__:[302,9,1,""],__or__:[302,9,1,""],__pos__:[302,9,1,""],__pow__:[302,9,1,""],__repeat__:[302,9,1,""],__rshift__:[302,9,1,""],__setitem__:[302,9,1,""],__setslice__:[302,9,1,""],__sub__:[302,9,1,""],__truediv__:[302,9,1,""],__xor__:[302,9,1,""],abs:[302,9,1,""],add:[302,9,1,""],and_:[302,9,1,""],attrgetter:[302,9,1,""],concat:[302,9,1,""],contains:[302,9,1,""],countOf:[302,9,1,""],delitem:[302,9,1,""],delslice:[302,9,1,""],div:[302,9,1,""],eq:[302,9,1,""],floordiv:[302,9,1,""],ge:[302,9,1,""],getitem:[302,9,1,""],getslice:[302,9,1,""],gt:[302,9,1,""],iadd:[302,9,1,""],iand:[302,9,1,""],iconcat:[302,9,1,""],idiv:[302,9,1,""],ifloordiv:[302,9,1,""],ilshift:[302,9,1,""],imod:[302,9,1,""],imul:[302,9,1,""],index:[302,9,1,""],indexOf:[302,9,1,""],inv:[302,9,1,""],invert:[302,9,1,""],ior:[302,9,1,""],ipow:[302,9,1,""],irepeat:[302,9,1,""],irshift:[302,9,1,""],isCallable:[302,9,1,""],isMappingType:[302,9,1,""],isNumberType:[302,9,1,""],isSequenceType:[302,9,1,""],is_:[302,9,1,""],is_not:[302,9,1,""],isub:[302,9,1,""],itemgetter:[302,9,1,""],itruediv:[302,9,1,""],ixor:[302,9,1,""],le:[302,9,1,""],lshift:[302,9,1,""],lt:[302,9,1,""],methodcaller:[302,9,1,""],mod:[302,9,1,""],mul:[302,9,1,""],ne:[302,9,1,""],neg:[302,9,1,""],not_:[302,9,1,""],or_:[302,9,1,""],pos:[302,9,1,""],pow:[302,9,1,""],repeat:[302,9,1,""],rshift:[302,9,1,""],sequenceIncludes:[302,9,1,""],setitem:[302,9,1,""],setslice:[302,9,1,""],sub:[302,9,1,""],truediv:[302,9,1,""],truth:[302,9,1,""],xor:[302,9,1,""]},optparse:{OptionGroup:[303,6,1,""],OptionParser:[303,6,1,""]},os:{EX_CANTCREAT:[304,11,1,""],EX_CONFIG:[304,11,1,""],EX_DATAERR:[304,11,1,""],EX_IOERR:[304,11,1,""],EX_NOHOST:[304,11,1,""],EX_NOINPUT:[304,11,1,""],EX_NOPERM:[304,11,1,""],EX_NOTFOUND:[304,11,1,""],EX_NOUSER:[304,11,1,""],EX_OK:[304,11,1,""],EX_OSERR:[304,11,1,""],EX_OSFILE:[304,11,1,""],EX_PROTOCOL:[304,11,1,""],EX_SOFTWARE:[304,11,1,""],EX_TEMPFAIL:[304,11,1,""],EX_UNAVAILABLE:[304,11,1,""],EX_USAGE:[304,11,1,""],F_OK:[304,11,1,""],O_APPEND:[304,11,1,""],O_ASYNC:[304,11,1,""],O_BINARY:[304,11,1,""],O_CREAT:[304,11,1,""],O_DIRECT:[304,11,1,""],O_DIRECTORY:[304,11,1,""],O_DSYNC:[304,11,1,""],O_EXCL:[304,11,1,""],O_EXLOCK:[304,11,1,""],O_NDELAY:[304,11,1,""],O_NOATIME:[304,11,1,""],O_NOCTTY:[304,11,1,""],O_NOFOLLOW:[304,11,1,""],O_NOINHERIT:[304,11,1,""],O_NONBLOCK:[304,11,1,""],O_RANDOM:[304,11,1,""],O_RDONLY:[304,11,1,""],O_RDWR:[304,11,1,""],O_RSYNC:[304,11,1,""],O_SEQUENTIAL:[304,11,1,""],O_SHLOCK:[304,11,1,""],O_SHORT_LIVED:[304,11,1,""],O_SYNC:[304,11,1,""],O_TEMPORARY:[304,11,1,""],O_TEXT:[304,11,1,""],O_TRUNC:[304,11,1,""],O_WRONLY:[304,11,1,""],P_DETACH:[304,11,1,""],P_NOWAIT:[304,11,1,""],P_NOWAITO:[304,11,1,""],P_OVERLAY:[304,11,1,""],P_WAIT:[304,11,1,""],R_OK:[304,11,1,""],SEEK_CUR:[304,11,1,""],SEEK_END:[304,11,1,""],SEEK_SET:[304,11,1,""],TMP_MAX:[304,11,1,""],WCONTINUED:[304,11,1,""],WCOREDUMP:[304,9,1,""],WEXITSTATUS:[304,9,1,""],WIFCONTINUED:[304,9,1,""],WIFEXITED:[304,9,1,""],WIFSIGNALED:[304,9,1,""],WIFSTOPPED:[304,9,1,""],WNOHANG:[304,11,1,""],WSTOPSIG:[304,9,1,""],WTERMSIG:[304,9,1,""],WUNTRACED:[304,11,1,""],W_OK:[304,11,1,""],X_OK:[304,11,1,""],_exit:[304,9,1,""],abort:[304,9,1,""],access:[304,9,1,""],altsep:[304,11,1,""],chdir:[304,9,1,""],chflags:[304,9,1,""],chmod:[304,9,1,""],chown:[304,9,1,""],chroot:[304,9,1,""],close:[304,9,1,""],closerange:[304,9,1,""],confstr:[304,9,1,""],confstr_names:[304,11,1,""],ctermid:[304,9,1,""],curdir:[304,11,1,""],defpath:[304,11,1,""],devnull:[304,11,1,""],dup2:[304,9,1,""],dup:[304,9,1,""],environ:[304,11,1,""],error:[304,10,1,""],execl:[304,9,1,""],execle:[304,9,1,""],execlp:[304,9,1,""],execlpe:[304,9,1,""],execv:[304,9,1,""],execve:[304,9,1,""],execvp:[304,9,1,""],execvpe:[304,9,1,""],extsep:[304,11,1,""],fchdir:[304,9,1,""],fchmod:[304,9,1,""],fchown:[304,9,1,""],fdatasync:[304,9,1,""],fdopen:[304,9,1,""],fork:[304,9,1,""],forkpty:[304,9,1,""],fpathconf:[304,9,1,""],fstat:[304,9,1,""],fstatvfs:[304,9,1,""],fsync:[304,9,1,""],ftruncate:[304,9,1,""],getcwd:[304,9,1,""],getcwdu:[304,9,1,""],getegid:[304,9,1,""],getenv:[304,9,1,""],geteuid:[304,9,1,""],getgid:[304,9,1,""],getgroups:[304,9,1,""],getloadavg:[304,9,1,""],getlogin:[304,9,1,""],getpgid:[304,9,1,""],getpgrp:[304,9,1,""],getpid:[304,9,1,""],getppid:[304,9,1,""],getresgid:[304,9,1,""],getresuid:[304,9,1,""],getsid:[304,9,1,""],getuid:[304,9,1,""],initgroups:[304,9,1,""],isatty:[304,9,1,""],kill:[304,9,1,""],killpg:[304,9,1,""],lchflags:[304,9,1,""],lchmod:[304,9,1,""],lchown:[304,9,1,""],linesep:[304,11,1,""],link:[304,9,1,""],listdir:[304,9,1,""],lseek:[304,9,1,""],lstat:[304,9,1,""],major:[304,9,1,""],makedev:[304,9,1,""],makedirs:[304,9,1,""],minor:[304,9,1,""],mkdir:[304,9,1,""],mkfifo:[304,9,1,""],mknod:[304,9,1,""],name:[304,11,1,""],nice:[304,9,1,""],open:[304,9,1,""],openpty:[304,9,1,""],pardir:[304,11,1,""],path:[305,5,0,"-"],pathconf:[304,9,1,""],pathconf_names:[304,11,1,""],pathsep:[304,11,1,""],pipe:[304,9,1,""],plock:[304,9,1,""],popen2:[304,9,1,""],popen3:[304,9,1,""],popen4:[304,9,1,""],popen:[304,9,1,""],putenv:[304,9,1,""],read:[304,9,1,""],readlink:[304,9,1,""],remove:[304,9,1,""],removedirs:[304,9,1,""],rename:[304,9,1,""],renames:[304,9,1,""],rmdir:[304,9,1,""],sep:[304,11,1,""],setegid:[304,9,1,""],seteuid:[304,9,1,""],setgid:[304,9,1,""],setgroups:[304,9,1,""],setpgid:[304,9,1,""],setpgrp:[304,9,1,""],setregid:[304,9,1,""],setresgid:[304,9,1,""],setresuid:[304,9,1,""],setreuid:[304,9,1,""],setsid:[304,9,1,""],setuid:[304,9,1,""],spawnl:[304,9,1,""],spawnle:[304,9,1,""],spawnlp:[304,9,1,""],spawnlpe:[304,9,1,""],spawnv:[304,9,1,""],spawnve:[304,9,1,""],spawnvp:[304,9,1,""],spawnvpe:[304,9,1,""],startfile:[304,9,1,""],stat:[304,9,1,""],stat_float_times:[304,9,1,""],statvfs:[304,9,1,""],strerror:[304,9,1,""],symlink:[304,9,1,""],sysconf:[304,9,1,""],sysconf_names:[304,11,1,""],system:[304,9,1,""],tcgetpgrp:[304,9,1,""],tcsetpgrp:[304,9,1,""],tempnam:[304,9,1,""],times:[304,9,1,""],tmpfile:[304,9,1,""],tmpnam:[304,9,1,""],ttyname:[304,9,1,""],umask:[304,9,1,""],uname:[304,9,1,""],unlink:[304,9,1,""],unsetenv:[304,9,1,""],urandom:[304,9,1,""],utime:[304,9,1,""],wait3:[304,9,1,""],wait4:[304,9,1,""],wait:[304,9,1,""],waitpid:[304,9,1,""],walk:[304,9,1,""],write:[304,9,1,""]},ossaudiodev:{OSSAudioError:[306,10,1,""],open:[306,9,1,""],openmixer:[306,9,1,""]},parser:{ParserError:[308,10,1,""],STType:[308,11,1,""],compilest:[308,9,1,""],expr:[308,9,1,""],isexpr:[308,9,1,""],issuite:[308,9,1,""],sequence2st:[308,9,1,""],st2list:[308,9,1,""],st2tuple:[308,9,1,""],suite:[308,9,1,""],tuple2st:[308,9,1,""]},pdb:{Pdb:[309,6,1,""],pm:[309,9,1,""],post_mortem:[309,9,1,""],run:[309,9,1,""],runcall:[309,9,1,""],runeval:[309,9,1,""],set_trace:[309,9,1,""]},pickle:{HIGHEST_PROTOCOL:[311,11,1,""],PickleError:[311,10,1,""],Pickler:[311,6,1,""],PicklingError:[311,10,1,""],Unpickler:[311,6,1,""],UnpicklingError:[311,10,1,""],dump:[311,9,1,""],dumps:[311,9,1,""],load:[311,9,1,""],loads:[311,9,1,""]},pickletools:{dis:[312,9,1,""],genops:[312,9,1,""],optimize:[312,9,1,""]},pipes:{Template:[313,6,1,""],quote:[313,9,1,""]},pkgutil:{ImpImporter:[314,6,1,""],ImpLoader:[314,6,1,""],extend_path:[314,9,1,""],find_loader:[314,9,1,""],get_data:[314,9,1,""],get_importer:[314,9,1,""],get_loader:[314,9,1,""],iter_importers:[314,9,1,""],iter_modules:[314,9,1,""],walk_packages:[314,9,1,""]},platform:{architecture:[315,9,1,""],dist:[315,9,1,""],java_ver:[315,9,1,""],libc_ver:[315,9,1,""],linux_distribution:[315,9,1,""],mac_ver:[315,9,1,""],machine:[315,9,1,""],node:[315,9,1,""],platform:[315,9,1,""],popen:[315,9,1,""],processor:[315,9,1,""],python_branch:[315,9,1,""],python_build:[315,9,1,""],python_compiler:[315,9,1,""],python_implementation:[315,9,1,""],python_revision:[315,9,1,""],python_version:[315,9,1,""],python_version_tuple:[315,9,1,""],release:[315,9,1,""],system:[315,9,1,""],system_alias:[315,9,1,""],uname:[315,9,1,""],version:[315,9,1,""],win32_ver:[315,9,1,""]},plistlib:{Data:[316,6,1,""],readPlist:[316,9,1,""],readPlistFromResource:[316,9,1,""],readPlistFromString:[316,9,1,""],writePlist:[316,9,1,""],writePlistToResource:[316,9,1,""],writePlistToString:[316,9,1,""]},popen2:{Popen3:[317,6,1,""],Popen4:[317,6,1,""],popen2:[317,9,1,""],popen3:[317,9,1,""],popen4:[317,9,1,""]},poplib:{POP3:[318,6,1,""],POP3_SSL:[318,6,1,""],error_proto:[318,10,1,""]},posix:{environ:[319,11,1,""]},posixfile:{SEEK_CUR:[320,11,1,""],SEEK_END:[320,11,1,""],SEEK_SET:[320,11,1,""],fileopen:[320,9,1,""],open:[320,9,1,""]},pprint:{PrettyPrinter:[321,6,1,""],isreadable:[321,9,1,""],isrecursive:[321,9,1,""],pformat:[321,9,1,""],pprint:[321,9,1,""],saferepr:[321,9,1,""]},profile:{Profile:[322,6,1,""],run:[322,9,1,""],runctx:[322,9,1,""]},pstats:{Stats:[322,6,1,""]},pty:{fork:[323,9,1,""],openpty:[323,9,1,""],spawn:[323,9,1,""]},pwd:{getpwall:[324,9,1,""],getpwnam:[324,9,1,""],getpwuid:[324,9,1,""]},py_compile:{PyCompileError:[325,10,1,""],compile:[325,9,1,""],main:[325,9,1,""]},pyclbr:{readmodule:[326,9,1,""],readmodule_ex:[326,9,1,""]},quopri:{decode:[331,9,1,""],decodestring:[331,9,1,""],encode:[331,9,1,""],encodestring:[331,9,1,""]},random:{SystemRandom:[332,6,1,""],WichmannHill:[332,6,1,""],betavariate:[332,9,1,""],choice:[332,9,1,""],expovariate:[332,9,1,""],gammavariate:[332,9,1,""],gauss:[332,9,1,""],getrandbits:[332,9,1,""],getstate:[332,9,1,""],jumpahead:[332,9,1,""],lognormvariate:[332,9,1,""],normalvariate:[332,9,1,""],paretovariate:[332,9,1,""],randint:[332,9,1,""],random:[332,9,1,""],randrange:[332,9,1,""],sample:[332,9,1,""],seed:[332,9,1,""],setstate:[332,9,1,""],shuffle:[332,9,1,""],triangular:[332,9,1,""],uniform:[332,9,1,""],vonmisesvariate:[332,9,1,""],weibullvariate:[332,9,1,""],whseed:[332,9,1,""]},re:{DEBUG:[333,11,1,""],DOTALL:[333,11,1,""],I:[333,11,1,""],IGNORECASE:[333,11,1,""],L:[333,11,1,""],LOCALE:[333,11,1,""],M:[333,11,1,""],MULTILINE:[333,11,1,""],MatchObject:[333,6,1,""],RegexObject:[333,6,1,""],S:[333,11,1,""],U:[333,11,1,""],UNICODE:[333,11,1,""],VERBOSE:[333,11,1,""],X:[333,11,1,""],compile:[333,9,1,""],error:[333,10,1,""],escape:[333,9,1,""],findall:[333,9,1,""],finditer:[333,9,1,""],match:[333,9,1,""],purge:[333,9,1,""],search:[333,9,1,""],split:[333,9,1,""],sub:[333,9,1,""],subn:[333,9,1,""]},readline:{add_history:[334,9,1,""],clear_history:[334,9,1,""],get_begidx:[334,9,1,""],get_completer:[334,9,1,""],get_completer_delims:[334,9,1,""],get_completion_type:[334,9,1,""],get_current_history_length:[334,9,1,""],get_endidx:[334,9,1,""],get_history_item:[334,9,1,""],get_history_length:[334,9,1,""],get_line_buffer:[334,9,1,""],insert_text:[334,9,1,""],parse_and_bind:[334,9,1,""],read_history_file:[334,9,1,""],read_init_file:[334,9,1,""],redisplay:[334,9,1,""],remove_history_item:[334,9,1,""],replace_history_item:[334,9,1,""],set_completer:[334,9,1,""],set_completer_delims:[334,9,1,""],set_completion_display_matches_hook:[334,9,1,""],set_history_length:[334,9,1,""],set_pre_input_hook:[334,9,1,""],set_startup_hook:[334,9,1,""],write_history_file:[334,9,1,""]},repr:{Repr:[335,6,1,""],aRepr:[335,11,1,""],repr:[335,9,1,""]},resource:{RLIMIT_AS:[336,11,1,""],RLIMIT_CORE:[336,11,1,""],RLIMIT_CPU:[336,11,1,""],RLIMIT_DATA:[336,11,1,""],RLIMIT_FSIZE:[336,11,1,""],RLIMIT_MEMLOCK:[336,11,1,""],RLIMIT_NOFILE:[336,11,1,""],RLIMIT_NPROC:[336,11,1,""],RLIMIT_OFILE:[336,11,1,""],RLIMIT_RSS:[336,11,1,""],RLIMIT_STACK:[336,11,1,""],RLIMIT_VMEM:[336,11,1,""],RLIM_INFINITY:[336,11,1,""],RUSAGE_BOTH:[336,11,1,""],RUSAGE_CHILDREN:[336,11,1,""],RUSAGE_SELF:[336,11,1,""],error:[336,10,1,""],getpagesize:[336,9,1,""],getrlimit:[336,9,1,""],getrusage:[336,9,1,""],setrlimit:[336,9,1,""]},rexec:{RExec:[338,6,1,""]},rfc822:{AddressList:[339,6,1,""],Message:[339,6,1,""],dump_address_pair:[339,9,1,""],mktime_tz:[339,9,1,""],parseaddr:[339,9,1,""],parsedate:[339,9,1,""],parsedate_tz:[339,9,1,""],quote:[339,9,1,""],unquote:[339,9,1,""]},robotparser:{RobotFileParser:[341,6,1,""]},runpy:{run_module:[342,9,1,""],run_path:[342,9,1,""]},sched:{scheduler:[343,6,1,""]},select:{epoll:[345,9,1,""],error:[345,10,1,""],kevent:[345,9,1,""],kqueue:[345,9,1,""],poll:[345,9,1,""],select:[345,9,1,""]},sets:{ImmutableSet:[346,6,1,""],Set:[346,6,1,""]},sgmllib:{SGMLParseError:[348,10,1,""],SGMLParser:[348,6,1,""]},sha:{"new":[349,9,1,""],blocksize:[349,11,1,""],digest_size:[349,11,1,""]},shelve:{BsdDbShelf:[350,6,1,""],DbfilenameShelf:[350,6,1,""],Shelf:[350,6,1,""],open:[350,9,1,""]},shlex:{shlex:[351,6,1,""],split:[351,9,1,""]},shutil:{Error:[352,10,1,""],copy2:[352,9,1,""],copy:[352,9,1,""],copyfile:[352,9,1,""],copyfileobj:[352,9,1,""],copymode:[352,9,1,""],copystat:[352,9,1,""],copytree:[352,9,1,""],get_archive_formats:[352,9,1,""],ignore_patterns:[352,9,1,""],make_archive:[352,9,1,""],move:[352,9,1,""],register_archive_format:[352,9,1,""],rmtree:[352,9,1,""],unregister_archive_format:[352,9,1,""]},signal:{CTRL_BREAK_EVENT:[353,11,1,""],CTRL_C_EVENT:[353,11,1,""],ITIMER_PROF:[353,11,1,""],ITIMER_REAL:[353,11,1,""],ITIMER_VIRTUAL:[353,11,1,""],ItimerError:[353,10,1,""],NSIG:[353,11,1,""],SIG_DFL:[353,11,1,""],SIG_IGN:[353,11,1,""],alarm:[353,9,1,""],getitimer:[353,9,1,""],getsignal:[353,9,1,""],pause:[353,9,1,""],set_wakeup_fd:[353,9,1,""],setitimer:[353,9,1,""],siginterrupt:[353,9,1,""],signal:[353,9,1,""]},site:{"--user-base":[356,13,1,"cmdoption-site-user-base"],"--user-site":[356,13,1,"cmdoption-site-user-site"],ENABLE_USER_SITE:[356,11,1,""],PREFIXES:[356,11,1,""],USER_BASE:[356,11,1,""],USER_SITE:[356,11,1,""],addsitedir:[356,9,1,""],getsitepackages:[356,9,1,""],getuserbase:[356,9,1,""],getusersitepackages:[356,9,1,""]},slice:{indices:[440,8,1,""]},smtpd:{DebuggingServer:[357,6,1,""],MailmanProxy:[357,6,1,""],PureProxy:[357,6,1,""],SMTPServer:[357,6,1,""]},smtplib:{LMTP:[358,6,1,""],SMTP:[358,6,1,""],SMTPAuthenticationError:[358,10,1,""],SMTPConnectError:[358,10,1,""],SMTPDataError:[358,10,1,""],SMTPException:[358,10,1,""],SMTPHeloError:[358,10,1,""],SMTPRecipientsRefused:[358,10,1,""],SMTPResponseException:[358,10,1,""],SMTPSenderRefused:[358,10,1,""],SMTPServerDisconnected:[358,10,1,""],SMTP_SSL:[358,6,1,""]},sndhdr:{what:[359,9,1,""],whathdr:[359,9,1,""]},socket:{AF_INET6:[360,11,1,""],AF_INET:[360,11,1,""],AF_UNIX:[360,11,1,""],SOCK_DGRAM:[360,11,1,""],SOCK_RAW:[360,11,1,""],SOCK_RDM:[360,11,1,""],SOCK_SEQPACKET:[360,11,1,""],SOCK_STREAM:[360,11,1,""],SOMAXCONN:[360,11,1,""],SocketType:[360,11,1,""],create_connection:[360,9,1,""],error:[360,10,1,""],fromfd:[360,9,1,""],gaierror:[360,10,1,""],getaddrinfo:[360,9,1,""],getdefaulttimeout:[360,9,1,""],getfqdn:[360,9,1,""],gethostbyaddr:[360,9,1,""],gethostbyname:[360,9,1,""],gethostbyname_ex:[360,9,1,""],gethostname:[360,9,1,""],getnameinfo:[360,9,1,""],getprotobyname:[360,9,1,""],getservbyname:[360,9,1,""],getservbyport:[360,9,1,""],has_ipv6:[360,11,1,""],herror:[360,10,1,""],htonl:[360,9,1,""],htons:[360,9,1,""],inet_aton:[360,9,1,""],inet_ntoa:[360,9,1,""],inet_ntop:[360,9,1,""],inet_pton:[360,9,1,""],ntohl:[360,9,1,""],ntohs:[360,9,1,""],setdefaulttimeout:[360,9,1,""],socket:[360,9,1,""],socketpair:[360,9,1,""],timeout:[360,10,1,""]},spwd:{getspall:[363,9,1,""],getspnam:[363,9,1,""]},sqlite3:{Connection:[364,6,1,""],Cursor:[364,6,1,""],PARSE_COLNAMES:[364,11,1,""],PARSE_DECLTYPES:[364,11,1,""],Row:[364,6,1,""],complete_statement:[364,9,1,""],connect:[364,9,1,""],enable_callback_tracebacks:[364,9,1,""],register_adapter:[364,9,1,""],register_converter:[364,9,1,""],sqlite_version:[364,11,1,""],sqlite_version_info:[364,11,1,""],version:[364,11,1,""],version_info:[364,11,1,""]},ssl:{ALERT_DESCRIPTION_HANDSHAKE_FAILURE:[365,11,1,""],ALERT_DESCRIPTION_INTERNAL_ERROR:[365,11,1,""],CERT_NONE:[365,11,1,""],CERT_OPTIONAL:[365,11,1,""],CERT_REQUIRED:[365,11,1,""],CHANNEL_BINDING_TYPES:[365,11,1,""],CertificateError:[365,10,1,""],DER_cert_to_PEM_cert:[365,9,1,""],HAS_ALPN:[365,11,1,""],HAS_ECDH:[365,11,1,""],HAS_NPN:[365,11,1,""],HAS_SNI:[365,11,1,""],HAS_TLSv1_3:[365,11,1,""],OPENSSL_VERSION:[365,11,1,""],OPENSSL_VERSION_INFO:[365,11,1,""],OPENSSL_VERSION_NUMBER:[365,11,1,""],OP_ALL:[365,11,1,""],OP_CIPHER_SERVER_PREFERENCE:[365,11,1,""],OP_ENABLE_MIDDLEBOX_COMPAT:[365,11,1,""],OP_NO_COMPRESSION:[365,11,1,""],OP_NO_SSLv2:[365,11,1,""],OP_NO_SSLv3:[365,11,1,""],OP_NO_TLSv1:[365,11,1,""],OP_NO_TLSv1_1:[365,11,1,""],OP_NO_TLSv1_2:[365,11,1,""],OP_NO_TLSv1_3:[365,11,1,""],OP_SINGLE_DH_USE:[365,11,1,""],OP_SINGLE_ECDH_USE:[365,11,1,""],PEM_cert_to_DER_cert:[365,9,1,""],PROTOCOL_SSLv23:[365,11,1,""],PROTOCOL_SSLv2:[365,11,1,""],PROTOCOL_SSLv3:[365,11,1,""],PROTOCOL_TLS:[365,11,1,""],PROTOCOL_TLSv1:[365,11,1,""],PROTOCOL_TLSv1_1:[365,11,1,""],PROTOCOL_TLSv1_2:[365,11,1,""],RAND_add:[365,9,1,""],RAND_egd:[365,9,1,""],RAND_status:[365,9,1,""],SSLContext:[365,6,1,""],SSLEOFError:[365,10,1,""],SSLError:[365,10,1,""],SSLSyscallError:[365,10,1,""],SSLWantReadError:[365,10,1,""],SSLWantWriteError:[365,10,1,""],SSLZeroReturnError:[365,10,1,""],VERIFY_CRL_CHECK_CHAIN:[365,11,1,""],VERIFY_CRL_CHECK_LEAF:[365,11,1,""],VERIFY_DEFAULT:[365,11,1,""],VERIFY_X509_STRICT:[365,11,1,""],VERIFY_X509_TRUSTED_FIRST:[365,11,1,""],_https_verify_certificates:[365,9,1,""],cert_time_to_seconds:[365,9,1,""],create_default_context:[365,9,1,""],enum_certificates:[365,9,1,""],enum_crls:[365,9,1,""],get_default_verify_paths:[365,9,1,""],get_server_certificate:[365,9,1,""],match_hostname:[365,9,1,""],wrap_socket:[365,9,1,""]},stat:{SF_APPEND:[366,11,1,""],SF_ARCHIVED:[366,11,1,""],SF_IMMUTABLE:[366,11,1,""],SF_NOUNLINK:[366,11,1,""],SF_SNAPSHOT:[366,11,1,""],ST_ATIME:[366,11,1,""],ST_CTIME:[366,11,1,""],ST_DEV:[366,11,1,""],ST_GID:[366,11,1,""],ST_INO:[366,11,1,""],ST_MODE:[366,11,1,""],ST_MTIME:[366,11,1,""],ST_NLINK:[366,11,1,""],ST_SIZE:[366,11,1,""],ST_UID:[366,11,1,""],S_ENFMT:[366,11,1,""],S_IEXEC:[366,11,1,""],S_IFBLK:[366,11,1,""],S_IFCHR:[366,11,1,""],S_IFDIR:[366,11,1,""],S_IFIFO:[366,11,1,""],S_IFLNK:[366,11,1,""],S_IFMT:[366,9,1,""],S_IFREG:[366,11,1,""],S_IFSOCK:[366,11,1,""],S_IMODE:[366,9,1,""],S_IREAD:[366,11,1,""],S_IRGRP:[366,11,1,""],S_IROTH:[366,11,1,""],S_IRUSR:[366,11,1,""],S_IRWXG:[366,11,1,""],S_IRWXO:[366,11,1,""],S_IRWXU:[366,11,1,""],S_ISBLK:[366,9,1,""],S_ISCHR:[366,9,1,""],S_ISDIR:[366,9,1,""],S_ISFIFO:[366,9,1,""],S_ISGID:[366,11,1,""],S_ISLNK:[366,9,1,""],S_ISREG:[366,9,1,""],S_ISSOCK:[366,9,1,""],S_ISUID:[366,11,1,""],S_ISVTX:[366,11,1,""],S_IWGRP:[366,11,1,""],S_IWOTH:[366,11,1,""],S_IWRITE:[366,11,1,""],S_IWUSR:[366,11,1,""],S_IXGRP:[366,11,1,""],S_IXOTH:[366,11,1,""],S_IXUSR:[366,11,1,""],UF_APPEND:[366,11,1,""],UF_COMPRESSED:[366,11,1,""],UF_HIDDEN:[366,11,1,""],UF_IMMUTABLE:[366,11,1,""],UF_NODUMP:[366,11,1,""],UF_NOUNLINK:[366,11,1,""],UF_OPAQUE:[366,11,1,""]},statvfs:{F_BAVAIL:[367,11,1,""],F_BFREE:[367,11,1,""],F_BLOCKS:[367,11,1,""],F_BSIZE:[367,11,1,""],F_FAVAIL:[367,11,1,""],F_FFREE:[367,11,1,""],F_FILES:[367,11,1,""],F_FLAG:[367,11,1,""],F_FRSIZE:[367,11,1,""],F_NAMEMAX:[367,11,1,""]},str:{capitalize:[368,8,1,""],center:[368,8,1,""],count:[368,8,1,""],decode:[368,8,1,""],encode:[368,8,1,""],endswith:[368,8,1,""],expandtabs:[368,8,1,""],find:[368,8,1,""],format:[368,8,1,""],index:[368,8,1,""],isalnum:[368,8,1,""],isalpha:[368,8,1,""],isdigit:[368,8,1,""],islower:[368,8,1,""],isspace:[368,8,1,""],istitle:[368,8,1,""],isupper:[368,8,1,""],join:[368,8,1,""],ljust:[368,8,1,""],lower:[368,8,1,""],lstrip:[368,8,1,""],partition:[368,8,1,""],replace:[368,8,1,""],rfind:[368,8,1,""],rindex:[368,8,1,""],rjust:[368,8,1,""],rpartition:[368,8,1,""],rsplit:[368,8,1,""],rstrip:[368,8,1,""],split:[368,8,1,""],splitlines:[368,8,1,""],startswith:[368,8,1,""],strip:[368,8,1,""],swapcase:[368,8,1,""],title:[368,8,1,""],translate:[368,8,1,""],upper:[368,8,1,""],zfill:[368,8,1,""]},string:{Formatter:[369,6,1,""],Template:[369,6,1,""],ascii_letters:[369,11,1,""],ascii_lowercase:[369,11,1,""],ascii_uppercase:[369,11,1,""],atof:[369,9,1,""],atoi:[369,9,1,""],atol:[369,9,1,""],capitalize:[369,9,1,""],capwords:[369,9,1,""],center:[369,9,1,""],count:[369,9,1,""],digits:[369,11,1,""],expandtabs:[369,9,1,""],find:[369,9,1,""],hexdigits:[369,11,1,""],index:[369,9,1,""],join:[369,9,1,""],joinfields:[369,9,1,""],letters:[369,11,1,""],ljust:[369,9,1,""],lower:[369,9,1,""],lowercase:[369,11,1,""],lstrip:[369,9,1,""],maketrans:[369,9,1,""],octdigits:[369,11,1,""],printable:[369,11,1,""],punctuation:[369,11,1,""],replace:[369,9,1,""],rfind:[369,9,1,""],rindex:[369,9,1,""],rjust:[369,9,1,""],rsplit:[369,9,1,""],rstrip:[369,9,1,""],split:[369,9,1,""],splitfields:[369,9,1,""],strip:[369,9,1,""],swapcase:[369,9,1,""],translate:[369,9,1,""],upper:[369,9,1,""],uppercase:[369,11,1,""],whitespace:[369,11,1,""],zfill:[369,9,1,""]},stringprep:{in_table_a1:[371,9,1,""],in_table_b1:[371,9,1,""],in_table_c11:[371,9,1,""],in_table_c11_c12:[371,9,1,""],in_table_c12:[371,9,1,""],in_table_c21:[371,9,1,""],in_table_c21_c22:[371,9,1,""],in_table_c22:[371,9,1,""],in_table_c3:[371,9,1,""],in_table_c4:[371,9,1,""],in_table_c5:[371,9,1,""],in_table_c6:[371,9,1,""],in_table_c7:[371,9,1,""],in_table_c8:[371,9,1,""],in_table_c9:[371,9,1,""],in_table_d1:[371,9,1,""],in_table_d2:[371,9,1,""],map_table_b2:[371,9,1,""],map_table_b3:[371,9,1,""]},struct:{Struct:[373,6,1,""],calcsize:[373,9,1,""],error:[373,10,1,""],pack:[373,9,1,""],pack_into:[373,9,1,""],unpack:[373,9,1,""],unpack_from:[373,9,1,""]},subprocess:{CREATE_NEW_CONSOLE:[374,11,1,""],CREATE_NEW_PROCESS_GROUP:[374,11,1,""],CalledProcessError:[374,10,1,""],PIPE:[374,11,1,""],Popen:[374,6,1,""],STARTF_USESHOWWINDOW:[374,11,1,""],STARTF_USESTDHANDLES:[374,11,1,""],STARTUPINFO:[374,6,1,""],STDOUT:[374,11,1,""],STD_ERROR_HANDLE:[374,11,1,""],STD_INPUT_HANDLE:[374,11,1,""],STD_OUTPUT_HANDLE:[374,11,1,""],SW_HIDE:[374,11,1,""],call:[374,9,1,""],check_call:[374,9,1,""],check_output:[374,9,1,""]},sunau:{AUDIO_FILE_ENCODING_ADPCM_G721:[376,11,1,""],AUDIO_FILE_ENCODING_ADPCM_G722:[376,11,1,""],AUDIO_FILE_ENCODING_ADPCM_G723_3:[376,11,1,""],AUDIO_FILE_ENCODING_ADPCM_G723_5:[376,11,1,""],AUDIO_FILE_ENCODING_ALAW_8:[376,11,1,""],AUDIO_FILE_ENCODING_DOUBLE:[376,11,1,""],AUDIO_FILE_ENCODING_FLOAT:[376,11,1,""],AUDIO_FILE_ENCODING_LINEAR_16:[376,11,1,""],AUDIO_FILE_ENCODING_LINEAR_24:[376,11,1,""],AUDIO_FILE_ENCODING_LINEAR_32:[376,11,1,""],AUDIO_FILE_ENCODING_LINEAR_8:[376,11,1,""],AUDIO_FILE_ENCODING_MULAW_8:[376,11,1,""],AUDIO_FILE_MAGIC:[376,11,1,""],Error:[376,10,1,""],open:[376,9,1,""],openfp:[376,9,1,""]},sunaudiodev:{error:[377,10,1,""],open:[377,9,1,""]},symbol:{sym_name:[378,11,1,""]},symtable:{Class:[379,6,1,""],Function:[379,6,1,""],Symbol:[379,6,1,""],SymbolTable:[379,6,1,""],symtable:[379,9,1,""]},sys:{__displayhook__:[380,11,1,""],__excepthook__:[380,11,1,""],__stderr__:[380,11,1,""],__stdin__:[380,11,1,""],__stdout__:[380,11,1,""],_clear_type_cache:[380,9,1,""],_current_frames:[380,9,1,""],_getframe:[380,9,1,""],api_version:[380,11,1,""],argv:[380,11,1,""],builtin_module_names:[380,11,1,""],byteorder:[380,11,1,""],call_tracing:[380,9,1,""],copyright:[380,11,1,""],displayhook:[380,9,1,""],dllhandle:[380,11,1,""],dont_write_bytecode:[380,11,1,""],exc_clear:[380,9,1,""],exc_info:[380,9,1,""],exc_traceback:[380,11,1,""],exc_type:[380,11,1,""],exc_value:[380,11,1,""],excepthook:[380,9,1,""],exec_prefix:[380,11,1,""],executable:[380,11,1,""],exit:[380,9,1,""],exitfunc:[380,11,1,""],flags:[380,11,1,""],float_info:[380,11,1,""],float_repr_style:[380,11,1,""],getcheckinterval:[380,9,1,""],getdefaultencoding:[380,9,1,""],getdlopenflags:[380,9,1,""],getfilesystemencoding:[380,9,1,""],getprofile:[380,9,1,""],getrecursionlimit:[380,9,1,""],getrefcount:[380,9,1,""],getsizeof:[380,9,1,""],gettrace:[380,9,1,""],getwindowsversion:[380,9,1,""],hexversion:[380,11,1,""],last_traceback:[380,11,1,""],last_type:[380,11,1,""],last_value:[380,11,1,""],long_info:[380,11,1,""],maxint:[380,11,1,""],maxsize:[380,11,1,""],maxunicode:[380,11,1,""],meta_path:[380,11,1,""],modules:[380,11,1,""],path:[380,11,1,""],path_hooks:[380,11,1,""],path_importer_cache:[380,11,1,""],platform:[380,11,1,""],prefix:[380,11,1,""],ps1:[380,11,1,""],ps2:[380,11,1,""],py3kwarning:[380,11,1,""],setcheckinterval:[380,9,1,""],setdefaultencoding:[380,9,1,""],setdlopenflags:[380,9,1,""],setprofile:[380,9,1,""],setrecursionlimit:[380,9,1,""],settrace:[380,9,1,""],settscdump:[380,9,1,""],stderr:[380,11,1,""],stdin:[380,11,1,""],stdout:[380,11,1,""],subversion:[380,11,1,""],tracebacklimit:[380,11,1,""],version:[380,11,1,""],version_info:[380,11,1,""],warnoptions:[380,11,1,""],winver:[380,11,1,""]},sysconfig:{get_config_h_filename:[381,9,1,""],get_config_var:[381,9,1,""],get_config_vars:[381,9,1,""],get_makefile_filename:[381,9,1,""],get_path:[381,9,1,""],get_path_names:[381,9,1,""],get_paths:[381,9,1,""],get_platform:[381,9,1,""],get_python_version:[381,9,1,""],get_scheme_names:[381,9,1,""],is_python_build:[381,9,1,""],parse_config_h:[381,9,1,""]},syslog:{closelog:[382,9,1,""],openlog:[382,9,1,""],setlogmask:[382,9,1,""],syslog:[382,9,1,""]},tabnanny:{NannyNag:[383,10,1,""],check:[383,9,1,""],filename_only:[383,11,1,""],process_tokens:[383,9,1,""],verbose:[383,11,1,""]},tarfile:{CompressionError:[384,10,1,""],DEFAULT_FORMAT:[384,11,1,""],ENCODING:[384,11,1,""],ExtractError:[384,10,1,""],GNU_FORMAT:[384,11,1,""],HeaderError:[384,10,1,""],PAX_FORMAT:[384,11,1,""],ReadError:[384,10,1,""],StreamError:[384,10,1,""],TarError:[384,10,1,""],TarFile:[384,6,1,""],TarFileCompat:[384,6,1,""],TarInfo:[384,6,1,""],USTAR_FORMAT:[384,11,1,""],is_tarfile:[384,9,1,""],open:[384,9,1,""]},telnetlib:{Telnet:[385,6,1,""]},tempfile:{NamedTemporaryFile:[386,9,1,""],SpooledTemporaryFile:[386,9,1,""],TemporaryFile:[386,9,1,""],gettempdir:[386,9,1,""],gettempprefix:[386,9,1,""],mkdtemp:[386,9,1,""],mkstemp:[386,9,1,""],mktemp:[386,9,1,""],tempdir:[386,11,1,""],template:[386,11,1,""]},termios:{tcdrain:[387,9,1,""],tcflow:[387,9,1,""],tcflush:[387,9,1,""],tcgetattr:[387,9,1,""],tcsendbreak:[387,9,1,""],tcsetattr:[387,9,1,""]},test:{support:[388,5,0,"-"]},textwrap:{TextWrapper:[389,6,1,""],dedent:[389,9,1,""],fill:[389,9,1,""],wrap:[389,9,1,""]},thread:{LockType:[390,11,1,""],allocate_lock:[390,9,1,""],error:[390,10,1,""],exit:[390,9,1,""],get_ident:[390,9,1,""],interrupt_main:[390,9,1,""],stack_size:[390,9,1,""],start_new_thread:[390,9,1,""]},threading:{BoundedSemaphore:[391,9,1,""],Condition:[391,6,1,""],Event:[391,6,1,""],Lock:[391,9,1,""],RLock:[391,9,1,""],Semaphore:[391,6,1,""],Thread:[391,6,1,""],ThreadError:[391,10,1,""],Timer:[391,6,1,""],activeCount:[391,9,1,""],active_count:[391,9,1,""],currentThread:[391,9,1,""],current_thread:[391,9,1,""],enumerate:[391,9,1,""],local:[391,6,1,""],setprofile:[391,9,1,""],settrace:[391,9,1,""],stack_size:[391,9,1,""]},time:{accept2dyear:[392,11,1,""],altzone:[392,11,1,""],asctime:[392,9,1,""],clock:[392,9,1,""],ctime:[392,9,1,""],daylight:[392,11,1,""],gmtime:[392,9,1,""],localtime:[392,9,1,""],mktime:[392,9,1,""],sleep:[392,9,1,""],strftime:[392,9,1,""],strptime:[392,9,1,""],struct_time:[392,6,1,""],time:[392,9,1,""],timezone:[392,11,1,""],tzname:[392,11,1,""],tzset:[392,9,1,""]},timeit:{"--clock":[393,13,1,"cmdoption-timeit-c"],"--help":[393,13,1,"cmdoption-timeit-h"],"--number":[393,13,1,"cmdoption-timeit-n"],"--repeat":[393,13,1,"cmdoption-timeit-r"],"--setup":[393,13,1,"cmdoption-timeit-s"],"--time":[393,13,1,"cmdoption-timeit-t"],"--verbose":[393,13,1,"cmdoption-timeit-v"],"-c":[393,13,1,"cmdoption-timeit-c"],"-h":[393,13,1,"cmdoption-timeit-h"],"-n":[393,13,1,"cmdoption-timeit-n"],"-r":[393,13,1,"cmdoption-timeit-r"],"-s":[393,13,1,"cmdoption-timeit-s"],"-t":[393,13,1,"cmdoption-timeit-t"],"-v":[393,13,1,"cmdoption-timeit-v"],Timer:[393,6,1,""],default_timer:[393,9,1,""],repeat:[393,9,1,""],timeit:[393,9,1,""]},token:{AMPER:[397,11,1,""],AMPEREQUAL:[397,11,1,""],AT:[397,11,1,""],BACKQUOTE:[397,11,1,""],CIRCUMFLEX:[397,11,1,""],CIRCUMFLEXEQUAL:[397,11,1,""],COLON:[397,11,1,""],COMMA:[397,11,1,""],DEDENT:[397,11,1,""],DOT:[397,11,1,""],DOUBLESLASH:[397,11,1,""],DOUBLESLASHEQUAL:[397,11,1,""],DOUBLESTAR:[397,11,1,""],DOUBLESTAREQUAL:[397,11,1,""],ENDMARKER:[397,11,1,""],EQEQUAL:[397,11,1,""],EQUAL:[397,11,1,""],ERRORTOKEN:[397,11,1,""],GREATER:[397,11,1,""],GREATEREQUAL:[397,11,1,""],INDENT:[397,11,1,""],ISEOF:[397,9,1,""],ISNONTERMINAL:[397,9,1,""],ISTERMINAL:[397,9,1,""],LBRACE:[397,11,1,""],LEFTSHIFT:[397,11,1,""],LEFTSHIFTEQUAL:[397,11,1,""],LESS:[397,11,1,""],LESSEQUAL:[397,11,1,""],LPAR:[397,11,1,""],LSQB:[397,11,1,""],MINEQUAL:[397,11,1,""],MINUS:[397,11,1,""],NAME:[397,11,1,""],NEWLINE:[397,11,1,""],NOTEQUAL:[397,11,1,""],NT_OFFSET:[397,11,1,""],NUMBER:[397,11,1,""],N_TOKENS:[397,11,1,""],OP:[397,11,1,""],PERCENT:[397,11,1,""],PERCENTEQUAL:[397,11,1,""],PLUS:[397,11,1,""],PLUSEQUAL:[397,11,1,""],RBRACE:[397,11,1,""],RIGHTSHIFT:[397,11,1,""],RIGHTSHIFTEQUAL:[397,11,1,""],RPAR:[397,11,1,""],RSQB:[397,11,1,""],SEMI:[397,11,1,""],SLASH:[397,11,1,""],SLASHEQUAL:[397,11,1,""],STAR:[397,11,1,""],STAREQUAL:[397,11,1,""],STRING:[397,11,1,""],TILDE:[397,11,1,""],VBAR:[397,11,1,""],VBAREQUAL:[397,11,1,""],tok_name:[397,11,1,""]},tokenize:{COMMENT:[398,11,1,""],NL:[398,11,1,""],TokenError:[398,10,1,""],generate_tokens:[398,9,1,""],tokenize:[398,9,1,""],untokenize:[398,9,1,""]},trace:{"--count":[399,13,1,"cmdoption-trace-c"],"--coverdir":[399,13,1,"cmdoption-trace-coverdir"],"--file":[399,13,1,"cmdoption-trace-f"],"--help":[399,13,1,"cmdoption-trace-help"],"--ignore-dir":[399,13,1,"cmdoption-trace-ignore-dir"],"--ignore-module":[399,13,1,"cmdoption-trace-ignore-module"],"--listfuncs":[399,13,1,"cmdoption-trace-l"],"--missing":[399,13,1,"cmdoption-trace-m"],"--no-report":[399,13,1,"cmdoption-trace-no-report"],"--report":[399,13,1,"cmdoption-trace-r"],"--summary":[399,13,1,"cmdoption-trace-s"],"--timing":[399,13,1,"cmdoption-trace-g"],"--trace":[399,13,1,"cmdoption-trace-t"],"--trackcalls":[399,13,1,"cmdoption-trace-trackcalls"],"--version":[399,13,1,"cmdoption-trace-version"],"-C":[399,13,1,"cmdoption-trace-coverdir"],"-R":[399,13,1,"cmdoption-trace-no-report"],"-T":[399,13,1,"cmdoption-trace-trackcalls"],"-c":[399,13,1,"cmdoption-trace-c"],"-f":[399,13,1,"cmdoption-trace-f"],"-g":[399,13,1,"cmdoption-trace-g"],"-l":[399,13,1,"cmdoption-trace-l"],"-m":[399,13,1,"cmdoption-trace-m"],"-r":[399,13,1,"cmdoption-trace-r"],"-s":[399,13,1,"cmdoption-trace-s"],"-t":[399,13,1,"cmdoption-trace-t"],CoverageResults:[399,6,1,""],Trace:[399,6,1,""]},traceback:{extract_stack:[400,9,1,""],extract_tb:[400,9,1,""],format_exc:[400,9,1,""],format_exception:[400,9,1,""],format_exception_only:[400,9,1,""],format_list:[400,9,1,""],format_stack:[400,9,1,""],format_tb:[400,9,1,""],print_exc:[400,9,1,""],print_exception:[400,9,1,""],print_last:[400,9,1,""],print_stack:[400,9,1,""],print_tb:[400,9,1,""],tb_lineno:[400,9,1,""]},ttk:{Combobox:[401,6,1,""],Notebook:[401,6,1,""],Progressbar:[401,6,1,""],Style:[401,6,1,""],Treeview:[401,6,1,""],Widget:[401,6,1,""]},tty:{setcbreak:[402,9,1,""],setraw:[402,9,1,""]},turtle:{"goto":[403,9,1,""],RawPen:[403,6,1,""],RawTurtle:[403,6,1,""],Screen:[403,6,1,""],ScrolledCanvas:[403,6,1,""],Shape:[403,6,1,""],Turtle:[403,6,1,""],TurtleScreen:[403,6,1,""],Vec2D:[403,6,1,""],addshape:[403,9,1,""],back:[403,9,1,""],backward:[403,9,1,""],begin_fill:[403,9,1,""],begin_poly:[403,9,1,""],bgcolor:[403,9,1,""],bgpic:[403,9,1,""],bk:[403,9,1,""],bye:[403,9,1,""],circle:[403,9,1,""],clear:[403,9,1,""],clearscreen:[403,9,1,""],clearstamp:[403,9,1,""],clearstamps:[403,9,1,""],clone:[403,9,1,""],color:[403,9,1,""],colormode:[403,9,1,""],degrees:[403,9,1,""],delay:[403,9,1,""],distance:[403,9,1,""],done:[403,9,1,""],dot:[403,9,1,""],down:[403,9,1,""],end_fill:[403,9,1,""],end_poly:[403,9,1,""],exitonclick:[403,9,1,""],fd:[403,9,1,""],fill:[403,9,1,""],fillcolor:[403,9,1,""],forward:[403,9,1,""],get_poly:[403,9,1,""],getcanvas:[403,9,1,""],getpen:[403,9,1,""],getscreen:[403,9,1,""],getshapes:[403,9,1,""],getturtle:[403,9,1,""],heading:[403,9,1,""],hideturtle:[403,9,1,""],home:[403,9,1,""],ht:[403,9,1,""],isdown:[403,9,1,""],isvisible:[403,9,1,""],left:[403,9,1,""],listen:[403,9,1,""],lt:[403,9,1,""],mainloop:[403,9,1,""],mode:[403,9,1,""],onclick:[403,9,1,""],ondrag:[403,9,1,""],onkey:[403,9,1,""],onrelease:[403,9,1,""],onscreenclick:[403,9,1,""],ontimer:[403,9,1,""],pd:[403,9,1,""],pen:[403,9,1,""],pencolor:[403,9,1,""],pendown:[403,9,1,""],pensize:[403,9,1,""],penup:[403,9,1,""],pos:[403,9,1,""],position:[403,9,1,""],pu:[403,9,1,""],radians:[403,9,1,""],register_shape:[403,9,1,""],reset:[403,9,1,""],resetscreen:[403,9,1,""],resizemode:[403,9,1,""],right:[403,9,1,""],rt:[403,9,1,""],screensize:[403,9,1,""],seth:[403,9,1,""],setheading:[403,9,1,""],setpos:[403,9,1,""],setposition:[403,9,1,""],settiltangle:[403,9,1,""],setundobuffer:[403,9,1,""],setup:[403,9,1,""],setworldcoordinates:[403,9,1,""],setx:[403,9,1,""],sety:[403,9,1,""],shape:[403,9,1,""],shapesize:[403,9,1,""],showturtle:[403,9,1,""],speed:[403,9,1,""],st:[403,9,1,""],stamp:[403,9,1,""],tilt:[403,9,1,""],tiltangle:[403,9,1,""],title:[403,9,1,""],towards:[403,9,1,""],tracer:[403,9,1,""],turtles:[403,9,1,""],turtlesize:[403,9,1,""],undo:[403,9,1,""],undobufferentries:[403,9,1,""],up:[403,9,1,""],update:[403,9,1,""],width:[403,9,1,""],window_height:[403,9,1,""],window_width:[403,9,1,""],write:[403,9,1,""],write_docstringdict:[403,9,1,""],xcor:[403,9,1,""],ycor:[403,9,1,""]},types:{BooleanType:[404,11,1,""],BufferType:[404,11,1,""],BuiltinFunctionType:[404,11,1,""],BuiltinMethodType:[404,11,1,""],ClassType:[404,11,1,""],CodeType:[404,11,1,""],ComplexType:[404,11,1,""],DictProxyType:[404,11,1,""],DictType:[404,11,1,""],DictionaryType:[404,11,1,""],EllipsisType:[404,11,1,""],FileType:[404,11,1,""],FloatType:[404,11,1,""],FrameType:[404,11,1,""],FunctionType:[404,11,1,""],GeneratorType:[404,11,1,""],GetSetDescriptorType:[404,11,1,""],InstanceType:[404,11,1,""],IntType:[404,11,1,""],LambdaType:[404,11,1,""],ListType:[404,11,1,""],LongType:[404,11,1,""],MemberDescriptorType:[404,11,1,""],MethodType:[404,11,1,""],ModuleType:[404,11,1,""],NoneType:[404,11,1,""],NotImplementedType:[404,11,1,""],SliceType:[404,11,1,""],StringType:[404,11,1,""],StringTypes:[404,11,1,""],TracebackType:[404,11,1,""],TupleType:[404,11,1,""],TypeType:[404,11,1,""],UnboundMethodType:[404,11,1,""],UnicodeType:[404,11,1,""],XRangeType:[404,11,1,""]},unicode:{isdecimal:[368,8,1,""],isnumeric:[368,8,1,""],splitlines:[368,8,1,""]},unicodedata:{bidirectional:[406,9,1,""],category:[406,9,1,""],combining:[406,9,1,""],decimal:[406,9,1,""],decomposition:[406,9,1,""],digit:[406,9,1,""],east_asian_width:[406,9,1,""],lookup:[406,9,1,""],mirrored:[406,9,1,""],name:[406,9,1,""],normalize:[406,9,1,""],numeric:[406,9,1,""],ucd_3_2_0:[406,11,1,""],unidata_version:[406,11,1,""]},unittest:{"--buffer":[407,13,1,"cmdoption-unittest-b"],"--catch":[407,13,1,"cmdoption-unittest-c"],"--failfast":[407,13,1,"cmdoption-unittest-f"],"-b":[407,13,1,"cmdoption-unittest-b"],"-c":[407,13,1,"cmdoption-unittest-c"],"-f":[407,13,1,"cmdoption-unittest-f"],FunctionTestCase:[407,6,1,""],SkipTest:[407,10,1,""],TestCase:[407,6,1,""],TestLoader:[407,6,1,""],TestResult:[407,6,1,""],TestSuite:[407,6,1,""],TextTestResult:[407,6,1,""],TextTestRunner:[407,6,1,""],defaultTestLoader:[407,11,1,""],expectedFailure:[407,9,1,""],installHandler:[407,9,1,""],main:[407,9,1,""],registerResult:[407,9,1,""],removeHandler:[407,9,1,""],removeResult:[407,9,1,""],skip:[407,9,1,""],skipIf:[407,9,1,""],skipUnless:[407,9,1,""]},urllib2:{AbstractBasicAuthHandler:[410,6,1,""],AbstractDigestAuthHandler:[410,6,1,""],BaseHandler:[410,6,1,""],CacheFTPHandler:[410,6,1,""],FTPHandler:[410,6,1,""],FileHandler:[410,6,1,""],HTTPBasicAuthHandler:[410,6,1,""],HTTPCookieProcessor:[410,6,1,""],HTTPDefaultErrorHandler:[410,6,1,""],HTTPDigestAuthHandler:[410,6,1,""],HTTPError:[410,10,1,""],HTTPErrorProcessor:[410,6,1,""],HTTPHandler:[410,6,1,""],HTTPPasswordMgr:[410,6,1,""],HTTPPasswordMgrWithDefaultRealm:[410,6,1,""],HTTPRedirectHandler:[410,6,1,""],HTTPSHandler:[410,6,1,""],OpenerDirector:[410,6,1,""],ProxyBasicAuthHandler:[410,6,1,""],ProxyDigestAuthHandler:[410,6,1,""],ProxyHandler:[410,6,1,""],Request:[410,6,1,""],URLError:[410,10,1,""],UnknownHandler:[410,6,1,""],build_opener:[410,9,1,""],install_opener:[410,9,1,""],urlopen:[410,9,1,""]},urllib:{ContentTooShortError:[409,10,1,""],FancyURLopener:[409,6,1,""],URLopener:[409,6,1,""],_urlopener:[409,11,1,""],getproxies:[409,9,1,""],pathname2url:[409,9,1,""],quote:[409,9,1,""],quote_plus:[409,9,1,""],unquote:[409,9,1,""],unquote_plus:[409,9,1,""],url2pathname:[409,9,1,""],urlcleanup:[409,9,1,""],urlencode:[409,9,1,""],urlopen:[409,9,1,""],urlretrieve:[409,9,1,""]},urlparse:{ParseResult:[411,6,1,""],SplitResult:[411,6,1,""],parse_qs:[411,9,1,""],parse_qsl:[411,9,1,""],urldefrag:[411,9,1,""],urljoin:[411,9,1,""],urlparse:[411,9,1,""],urlsplit:[411,9,1,""],urlunparse:[411,9,1,""],urlunsplit:[411,9,1,""]},uu:{Error:[414,10,1,""],decode:[414,9,1,""],encode:[414,9,1,""]},uuid:{NAMESPACE_DNS:[415,11,1,""],NAMESPACE_OID:[415,11,1,""],NAMESPACE_URL:[415,11,1,""],NAMESPACE_X500:[415,11,1,""],RESERVED_FUTURE:[415,11,1,""],RESERVED_MICROSOFT:[415,11,1,""],RESERVED_NCS:[415,11,1,""],RFC_4122:[415,11,1,""],UUID:[415,6,1,""],getnode:[415,9,1,""],uuid1:[415,9,1,""],uuid3:[415,9,1,""],uuid4:[415,9,1,""],uuid5:[415,9,1,""]},warnings:{catch_warnings:[416,6,1,""],filterwarnings:[416,9,1,""],formatwarning:[416,9,1,""],resetwarnings:[416,9,1,""],showwarning:[416,9,1,""],simplefilter:[416,9,1,""],warn:[416,9,1,""],warn_explicit:[416,9,1,""],warnpy3k:[416,9,1,""]},wave:{Error:[417,10,1,""],open:[417,9,1,""],openfp:[417,9,1,""]},weakref:{CallableProxyType:[418,11,1,""],ProxyType:[418,11,1,""],ProxyTypes:[418,11,1,""],ReferenceError:[418,10,1,""],ReferenceType:[418,11,1,""],WeakKeyDictionary:[418,6,1,""],WeakSet:[418,6,1,""],WeakValueDictionary:[418,6,1,""],getweakrefcount:[418,9,1,""],getweakrefs:[418,9,1,""],proxy:[418,9,1,""],ref:[418,6,1,""]},webbrowser:{Error:[419,10,1,""],get:[419,9,1,""],open:[419,9,1,""],open_new:[419,9,1,""],open_new_tab:[419,9,1,""],register:[419,9,1,""]},whichdb:{whichdb:[420,9,1,""]},winsound:{Beep:[422,9,1,""],MB_ICONASTERISK:[422,11,1,""],MB_ICONEXCLAMATION:[422,11,1,""],MB_ICONHAND:[422,11,1,""],MB_ICONQUESTION:[422,11,1,""],MB_OK:[422,11,1,""],MessageBeep:[422,9,1,""],PlaySound:[422,9,1,""],SND_ALIAS:[422,11,1,""],SND_ASYNC:[422,11,1,""],SND_FILENAME:[422,11,1,""],SND_LOOP:[422,11,1,""],SND_MEMORY:[422,11,1,""],SND_NODEFAULT:[422,11,1,""],SND_NOSTOP:[422,11,1,""],SND_NOWAIT:[422,11,1,""],SND_PURGE:[422,11,1,""]},wsgiref:{handlers:[423,5,0,"-"],headers:[423,5,0,"-"],simple_server:[423,5,0,"-"],util:[423,5,0,"-"],validate:[423,5,0,"-"]},xdrlib:{ConversionError:[424,10,1,""],Error:[424,10,1,""],Packer:[424,6,1,""],Unpacker:[424,6,1,""]},xml:{dom:[426,5,0,"-"],sax:[430,5,0,"-"]},xmlrpclib:{"boolean":[434,9,1,""],Binary:[434,6,1,""],DateTime:[434,6,1,""],Fault:[434,6,1,""],MultiCall:[434,6,1,""],ProtocolError:[434,6,1,""],ServerProxy:[434,6,1,""],dumps:[434,9,1,""],loads:[434,9,1,""]},zipfile:{"-c":[435,13,1,"cmdoption-zipfile-c"],"-e":[435,13,1,"cmdoption-zipfile-e"],"-l":[435,13,1,"cmdoption-zipfile-l"],"-t":[435,13,1,"cmdoption-zipfile-t"],BadZipfile:[435,10,1,""],LargeZipFile:[435,10,1,""],PyZipFile:[435,6,1,""],ZIP_DEFLATED:[435,11,1,""],ZIP_STORED:[435,11,1,""],ZipFile:[435,6,1,""],ZipInfo:[435,6,1,""],is_zipfile:[435,9,1,""]},zipimport:{ZipImportError:[436,10,1,""],zipimporter:[436,6,1,""]},zlib:{adler32:[437,9,1,""],compress:[437,9,1,""],compressobj:[437,9,1,""],crc32:[437,9,1,""],decompress:[437,9,1,""],decompressobj:[437,9,1,""],error:[437,10,1,""]}},objnames:{"0":["c","var","C variable"],"1":["c","function","C function"],"10":["py","exception","Python exception"],"11":["py","data","Python data"],"12":["py","classmethod","Python class method"],"13":["std","cmdoption","program option"],"14":["std","opcode","opcode"],"15":["std","envvar","environment variable"],"16":["std","2to3fixer","2to3fixer"],"2":["c","type","C type"],"3":["c","member","C member"],"4":["c","macro","C macro"],"5":["py","module","Python module"],"6":["py","class","Python class"],"7":["py","attribute","Python attribute"],"8":["py","method","Python method"],"9":["py","function","Python function"]},objtypes:{"0":"c:var","1":"c:function","10":"py:exception","11":"py:data","12":"py:classmethod","13":"std:cmdoption","14":"std:opcode","15":"std:envvar","16":"std:2to3fixer","2":"c:type","3":"c:member","4":"c:macro","5":"py:module","6":"py:class","7":"py:attribute","8":"py:method","9":"py:function"},terms:{"0000007f":150,"0000050000069649e":277,"0000050000166668e":277,"000007ff":150,"0000ffff":150,"000s":407,"0010ffff":150,"00112444be1e":[415,475],"001j":446,"001s":407,"005s":407,"007b":104,"00c7":[406,442],"00e9":104,"00ff":150,"0123456789abcdef":457,"0123456789abcdefabcdef":369,"012p1":161,"01bb6f00122b177f36cab49cea8b6b26":365,"01ff":[104,470],"02d":333,"02e":178,"02x":[90,369],"0377l":446,"0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5":235,"03d":[193,368],"04d":88,"04e":322,"04x":104,"05edt":392,"077e010":446,"08x":135,"0a0b0c0d0e0f":415,"0a1":111,"0a2":111,"0a3":[111,380],"0a3b9":333,"0alpha1":470,"0an":83,"0b1":111,"0b100101":[368,477],"0b101010":369,"0b10101101":476,"0b101111":476,"0b1101":476,"0beta1":470,"0bf2":104,"0bn":83,"0c9aee199e5d":[415,475],"0cn":83,"0e0":[178,446],"0f84":104,"0goofi":473,"0o10":88,"0o21":476,"0o52":[369,476],"0th":333,"0x0":150,"0x00":[168,170],"0x00000020":168,"0x0020":460,"0x00a1db50":451,"0x00ac18f0":186,"0x00b18c90":94,"0x00c45070":94,"0x010502f0":380,"0x020100a3":380,"0x02070000":92,"0x03000000":92,"0x03010000":92,"0x04":440,"0x08":440,"0x0bf2":104,"0x1":[178,368,476],"0x10":440,"0x1000":440,"0x100000000l":446,"0x1021":135,"0x10ffff":[104,222],"0x12":415,"0x12131415":373,"0x1234":415,"0x12345678":415,"0x12345678123456781234567812345678":415,"0x12ca":104,"0x144":88,"0x16d07cc":88,"0x1d000000":168,"0x1f":170,"0x1l":222,"0x20":440,"0x2000":440,"0x2a":[222,369],"0x3":368,"0x34":415,"0x37f080":477,"0x37f850":477,"0x384698":386,"0x400cad2c":473,"0x400cad4c":473,"0x402c2080":474,"0x402c2090":474,"0x402ef0d4":474,"0x4198d0":88,"0x50":104,"0x5678":415,"0x567812345678":415,"0x5aa730":293,"0x7352a0":88,"0x77ab28":368,"0x7f":170,"0x7f4e7dd8fa80":364,"0x7ff":104,"0x80":[104,170],"0x8116870":472,"0x8117f90":[472,473],"0x90":135,"0x9080bfl":365,"0x9f":104,"0xa":380,"0xa5":88,"0xb":380,"0xb2":88,"0xb77e6fac":429,"0xb77ec1cc":429,"0xb77ec26c":429,"0xb77ec2ac":429,"0xbb":150,"0xbf":150,"0xc":380,"0xc000":101,"0xdeadbeef":446,"0xef":150,"0xf":380,"0xff":[104,150,222],"0xffd2":101,"0xfffe":150,"0xffff":222,"0xffffffff":[135,437,473],"0xffffffffl":473,"0xxxxxxx":150,"100000000000000005551115123125l":455,"10042ed0":452,"100k":80,"100th":393,"10aedt":392,"10c":373,"10d":457,"10e6":88,"10j":446,"10k":88,"10px":475,"10s":373,"10shhb":373,"10th":339,"10xxxxxx":150,"110xxxxx":150,"1110xxxx":150,"11110xxx":150,"11da":[415,475],"1234567890123l":472,"123e":178,"12ca":104,"12f":474,"12g":470,"12s":99,"14e":446,"14j":446,"152x261":64,"15g":380,"15s":[99,265,266,477],"16be":150,"16fd2706":[415,475],"16g":380,"16le":150,"17g":470,"18014398509481984l":476,"18288201344j":474,"18446744073709551616l":472,"1970s":83,"1980s":[104,476],"1990s":[438,476],"1a2":72,"1am":174,"1beta1":470,"1e100":[186,277,442,446],"1e100j":446,"1e300":186,"1e50":368,"1e500":16,"1mb":477,"1p2":468,"1st":[88,174,392],"1xx":132,"1ytw3":386,"200c":477,"200x100":396,"200x200":403,"20th":470,"217160342717258261933904529e":398,"21716034272e":398,"2251799813685248l":476,"23e":178,"24n":369,"256k":475,"25c8":360,"265252859812191058636308480000000l":186,"2am":174,"2devel9":477,"2e2":178,"2gb":104,"2nd":[88,333],"2to3":[60,90,113,121,132,144,158,161,162,164,176,179,187,188,189,224,226,239,240,241,252,330,335,341,344,354,355,361,390,394,396,409,410,411,413,420,434,446,476,477],"30l":186,"30pm":174,"30t21":473,"30x":409,"320px":475,"321000e":178,"321e":178,"32be":150,"32bit":[64,135,437,472],"32c18f":403,"32kb":[390,391],"32le":150,"33af":104,"33cc8c":403,"340k":471,"34a04430":87,"354aa":333,"3b8a":[415,475],"3bsd":360,"3ca4":[415,475],"3de":365,"3dgamer":472,"3dm":142,"3rd":[87,457],"3x4":453,"3xxx":476,"417a":477,"433b":[415,475],"43c":396,"45356m":475,"49g":477,"4a0":83,"4dom":470,"4kb":[390,391],"4sight":213,"4th":364,"52g":477,"5511151231257827e":178,"5555555555555p":476,"561702493119680037517373933e":178,"5aef":360,"5qtpn6xq2rawqk":386,"5r92":472,"5th":364,"6004799503160661l":476,"60th":[269,393],"61261m":476,"64bit":[64,381],"65535l":477,"68k":306,"6a1":[107,476],"6fa459ea":[415,475],"6final":470,"6th":457,"6yd86yt":472,"7074029114692207l":476,"70th":174,"717ak":333,"718ak":333,"71i":472,"727ak":333,"730920th":174,"750000e":476,"77e10":446,"79228162514264337593543950336l":446,"7bit":[194,195,280],"7econnolli":409,"7eguido":411,"80a0960":457,"81w":369,"82eb":[415,475],"86yd":472,"87a":248,"886313e1":[415,475],"894e":[415,475],"89a":248,"8baf":[415,475],"8bit":[195,280],"8bitmim":358,"8c7fada847da":[415,475],"8ghz":322,"8svx":359,"8th":[283,370],"9470143l":365,"9514790517935283e":477,"9514790517935289e":477,"95f0":365,"999999999999ap":178,"9b90":[415,475],"9tjqk":333,"\u00e4\u00f6\u00fc":460,"\u00e5strand":[473,474],"\u03c0":[147,277],"\u03c9":104,"abcd\u00e9":104,"abstract":[27,33,48,60,69,81,82,87,90,104,117,126,160,161,168,173,174,178,206,215,218,219,222,239,252,253,256,262,267,301,302,308,313,329,346,365,368,396,410,423,440,442,451,452,473,475,477,478],"alliancefran\u00e7ais":[150,473],"andr\u00e9":[104,230,364,470,471,472,473,475],"avi\u00f3n":477,"boolean":[15,30,60,63,98,103,117,120,125,134,158,162,168,169,174,182,186,191,215,222,239,252,254,260,266,276,293,302,306,316,333,360,361,365,384,391,392,396,401,426,427,439,440,444,453,471,474,475,476,477,478],"break":[30,55,56,60,66,72,79,81,87,89,90,93,96,99,100,101,102,107,125,134,143,150,157,168,169,182,186,198,215,219,222,225,236,244,258,273,292,293,303,309,321,328,337,338,348,353,358,360,364,365,368,369,385,387,388,389,407,411,412,423,425,427,439,440,441,443,444,446,451,454,456,460,463,465,470,471,472,473,475,476,477],"byte":[4,6,9,13,15,16,20,21,26,36,37,43,51,52,55,56,60,63,64,82,87,88,90,92,99,100,101,102,104,106,111,113,118,119,120,124,125,127,129,135,139,141,146,150,170,182,191,194,198,201,205,207,221,222,235,237,241,245,246,247,248,249,252,256,259,260,262,266,278,287,291,293,298,304,305,306,308,310,311,315,317,323,325,328,333,336,338,345,349,353,360,365,366,368,372,374,376,380,384,385,388,392,396,409,410,415,417,424,427,430,431,432,435,437,438,440,442,446,451,457,460,461,463,465,469,472,473,474,475,477,478],"caf\u00e9":104,"case":[1,4,6,10,13,16,19,20,21,26,28,29,30,31,41,43,45,47,49,51,52,54,55,56,58,60,63,64,66,67,70,71,72,73,75,76,77,79,83,87,88,90,91,93,94,95,96,98,99,100,101,102,103,104,105,109,110,111,113,117,118,123,124,125,127,129,134,135,136,138,143,147,148,150,151,152,156,158,161,162,168,169,170,174,178,179,180,182,185,186,191,192,193,194,197,198,200,202,203,204,206,207,214,215,219,222,225,230,231,232,234,236,240,241,243,246,247,251,253,256,259,263,264,265,266,267,271,273,274,277,280,281,287,290,293,294,300,303,304,305,306,308,309,311,313,314,315,317,318,321,322,328,330,332,333,337,338,339,343,348,350,352,353,354,355,357,358,360,361,364,365,368,369,370,371,373,374,378,380,384,385,388,391,392,393,394,396,401,403,405,406,408,409,410,411,412,413,416,423,425,426,427,431,432,438,439,440,441,442,446,447,448,449,451,452,453,454,455,459,461,463,465,470,472,473,474,475,476,477,478],"catch":[30,60,72,81,88,90,93,95,96,100,104,105,106,161,167,186,206,222,253,303,336,338,351,352,353,388,392,407,410,424,440,442,454,470,473,475,476,477],"char":[3,4,6,7,8,12,13,16,19,20,21,22,26,28,29,30,34,35,36,37,39,42,43,46,47,50,51,52,55,56,58,76,77,79,82,92,116,124,135,150,168,169,185,191,227,240,244,260,264,291,368,369,373,393,396,425,429,451,473,475,476,477],"chrigstr\u00f6m":477,"class":[2,15,19,20,28,31,38,43,45,46,51,54,55,56,59,60,68,69,70,72,77,79,83,84,87,89,90,93,95,96,98,99,100,101,102,103,106,109,110,111,113,115,116,117,120,124,127,132,133,134,137,139,140,144,146,148,151,157,158,160,161,162,163,164,167,168,169,170,172,173,174,177,178,179,180,182,186,187,188,191,192,193,194,195,197,198,200,201,206,210,211,212,215,218,219,221,222,223,234,238,239,240,241,242,243,244,246,249,251,252,254,257,258,260,262,265,266,267,270,275,279,280,281,282,284,287,288,292,294,295,296,297,299,301,302,303,306,307,308,309,310,312,313,314,316,317,318,321,327,329,332,333,334,335,337,338,339,340,341,343,344,345,346,348,350,351,354,355,357,358,360,361,362,364,365,369,370,372,374,379,380,384,385,388,389,391,392,393,394,395,396,399,401,404,406,409,410,411,415,416,418,419,421,424,425,426,427,428,429,430,432,433,434,435,436,441,442,443,444,445,447,450,452,453,454,456,457,461,462,463,465,469,470,471,473,474,477,478],"co\u00f6per":104,"const":[4,6,7,8,12,13,16,19,20,21,26,28,39,42,43,46,47,50,52,56,58,60,77,79,92,120,157,185,303,427],"d\u00f6rwald":[473,474,475],"default":[4,6,13,20,23,28,30,37,50,51,55,56,58,60,63,64,66,67,68,71,72,73,77,79,80,81,82,87,89,90,91,93,94,96,98,99,100,101,104,105,106,107,108,109,113,115,116,118,120,121,124,125,126,127,129,131,132,133,134,137,138,139,140,143,144,145,146,148,149,150,151,152,153,156,157,158,159,161,162,167,168,169,170,174,175,176,178,180,182,185,186,187,188,191,192,193,194,195,197,198,199,200,201,202,203,204,206,207,208,210,212,215,216,219,221,222,223,225,226,227,228,229,230,232,234,236,237,238,239,240,241,243,244,246,247,253,256,257,258,259,260,264,265,266,267,271,273,274,281,282,283,287,290,292,293,296,297,298,299,300,304,305,306,308,309,310,311,312,315,317,318,319,320,321,322,323,325,328,329,330,331,332,333,334,335,338,339,345,348,350,351,352,353,354,355,356,358,360,361,368,369,373,374,380,381,382,384,385,386,388,389,390,391,392,393,396,399,401,402,403,405,406,407,409,410,411,413,414,417,419,422,423,427,428,429,430,431,432,433,434,435,437,439,440,441,442,443,446,447,453,454,455,456,457,458,459,460,461,463,465,467,468,469,470,471,472,473,474,475,476],"devan\u0101gar\u012b":178,"enum":117,"export":[6,30,37,45,55,60,63,72,76,77,79,80,87,88,95,107,116,120,125,140,161,167,174,249,270,302,308,311,319,322,360,380,398,404,409,447,458,461,473,477],"f\u00fcrstenau":477,"fern\u00e1ndez":477,"final":[26,27,30,37,52,54,55,60,63,72,77,78,81,83,87,88,93,96,98,99,100,101,102,103,107,111,114,129,134,150,157,160,168,178,180,182,186,192,206,249,251,253,255,256,265,273,282,292,293,303,309,313,322,328,333,339,356,361,364,365,368,369,380,384,386,387,389,390,391,396,400,401,403,407,410,418,422,425,430,439,440,441,442,443,446,447,450,451,452,454,455,457,458,470,471,472,473,474,476,477,478],"float":[4,15,16,36,41,51,55,60,79,87,88,90,95,100,115,117,119,123,124,129,147,152,154,158,167,168,174,180,186,203,206,212,218,222,225,231,246,252,258,260,264,273,276,277,293,300,301,303,304,305,311,316,322,329,332,336,345,353,360,364,365,369,372,373,380,391,392,393,398,403,404,406,424,434,440,442,453,456,457,460,461,462,465,470,471,472,473,475,476,477,478],"fran\u00e7oi":230,"fu\u00dfbal":200,"function":[2,3,4,5,8,10,11,12,14,15,16,17,19,20,21,22,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53,54,55,57,58,59,60,64,68,69,70,72,75,76,78,79,80,83,84,87,89,90,91,92,93,97,98,99,100,104,105,106,107,109,110,111,113,114,115,116,118,120,121,123,125,126,127,128,129,130,132,133,134,135,136,137,138,139,141,142,144,145,149,150,151,154,155,157,158,159,160,162,163,167,170,173,174,175,178,179,180,181,182,186,191,192,193,194,195,197,198,199,200,201,202,203,204,205,206,207,208,210,211,213,216,217,219,221,224,225,226,227,228,229,230,231,232,235,236,237,238,239,241,243,244,245,246,247,248,249,251,252,254,255,256,257,259,260,262,263,264,267,269,270,271,274,275,276,278,280,281,282,283,284,287,290,293,294,297,298,300,301,303,305,306,308,309,310,311,312,313,314,315,316,317,319,320,321,322,323,325,327,328,329,332,333,334,335,336,337,338,339,342,343,345,346,347,349,350,351,352,353,354,355,356,358,359,360,361,362,366,370,371,372,376,377,379,382,383,384,385,386,387,389,390,391,392,393,395,396,397,398,399,400,404,406,408,410,411,412,413,414,415,417,418,419,420,421,422,423,424,425,426,427,430,431,432,433,435,436,437,440,441,442,443,444,447,448,450,451,454,455,456,457,458,460,462,463,464,465,467,469,472,473,477,478],"goto":[30,60,92,182,403],"gr\u00e9goir":475,"gust\u00e4bel":[473,475,476,477],"h\u00e4ring":[364,472,475,477],"ib\u00e1\u00f1ez":230,"import":[8,11,20,27,28,30,37,55,57,58,60,62,63,67,68,70,71,72,73,75,76,77,79,80,81,83,86,87,89,90,91,92,93,94,96,98,99,100,101,102,103,104,105,106,107,109,110,111,113,114,116,118,119,120,121,123,124,125,126,127,128,131,132,138,140,141,143,144,145,148,151,152,154,155,156,157,158,159,160,161,162,164,165,167,168,169,174,176,178,180,181,182,184,185,186,187,188,189,190,193,194,197,198,200,202,203,206,207,208,210,212,213,214,216,217,218,219,221,222,223,224,226,227,228,230,231,232,234,235,236,238,239,240,241,244,246,248,250,252,253,255,256,258,260,263,264,270,273,274,275,277,278,281,287,288,292,293,303,304,305,308,309,311,313,314,317,318,319,320,321,322,326,327,328,330,333,334,335,338,340,341,342,343,344,346,350,352,353,354,355,356,358,360,361,362,364,365,366,368,369,370,373,374,377,379,380,381,382,383,384,385,387,388,390,392,393,394,396,398,399,400,401,403,404,405,406,407,409,410,411,412,413,415,416,418,420,422,423,424,425,426,427,429,431,434,439,440,441,442,443,444,446,449,451,452,453,454,455,456,457,458,459,462,463,465,467,470,472,477,478],"int":[3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,38,39,41,42,43,46,47,48,49,50,51,52,53,54,55,56,58,59,60,76,77,79,82,87,88,90,91,95,98,100,101,109,111,113,119,123,124,125,126,128,152,168,174,178,180,185,186,212,222,223,225,231,240,246,252,253,256,260,276,290,300,303,304,306,311,319,332,345,364,369,373,379,393,398,404,407,415,426,427,429,434,440,442,451,452,454,457,460,461,463,465,470,472,473,474,475,476,477],"j\u00f3nsson":477,"j\u00f6rg":474,"j\u00fcrgen":474,"jes\u00fa":[476,477],"jos\u00e9":477,"kristj\u00e1n":477,"l\u00f6wi":[104,230,470,472,473,474,475,477],"long":[4,5,15,19,26,28,29,30,36,39,41,43,50,51,55,56,58,60,63,66,71,72,77,79,81,82,83,87,88,90,91,95,96,98,99,100,101,102,105,106,107,109,113,114,123,124,132,135,136,137,139,157,158,167,168,169,174,178,180,185,186,191,198,205,206,207,219,221,222,228,231,238,243,252,256,258,260,266,276,277,290,293,300,303,304,308,311,315,317,319,322,332,333,335,341,345,350,353,358,361,364,365,369,373,380,384,389,392,393,394,395,396,401,404,409,416,418,423,426,427,434,438,439,440,442,451,457,460,461,463,465,470,471,473,475,476,477,478],"na\u00efv":[104,471],"new":[0,1,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,53,54,55,56,58,59,60,64,69,71,72,76,77,78,81,82,87,88,89,90,91,92,93,94,98,99,100,101,102,103,104,105,106,109,113,114,119,120,121,123,124,125,126,127,128,129,132,134,137,138,139,140,143,145,146,147,148,149,150,151,152,155,156,157,158,159,160,161,162,163,167,168,169,170,173,174,175,176,178,180,182,184,186,187,191,192,194,196,197,198,200,201,202,203,204,206,207,208,210,212,214,215,218,219,221,222,223,224,225,226,228,230,232,234,235,236,237,238,239,240,241,244,245,246,248,249,250,251,252,253,256,258,260,263,264,265,266,267,271,273,274,276,277,278,279,280,281,282,287,288,289,290,291,293,294,296,298,299,300,302,304,305,306,308,309,311,312,313,314,315,317,318,320,321,322,323,327,328,329,330,332,333,334,335,336,338,339,341,342,343,345,346,348,349,351,352,353,354,355,356,357,358,360,361,363,364,365,368,369,371,373,374,379,380,381,384,385,386,387,388,389,390,391,392,393,394,396,398,399,400,401,403,404,405,406,407,409,410,411,413,415,418,419,422,423,426,427,428,429,430,431,432,433,434,435,436,437,439,442,444,445,446,447,450,451,452,453,454,455,456,457,458,460,461,462,463,464,465,467,469],"null":[2,3,4,6,7,8,9,10,11,13,14,15,16,17,19,20,21,22,23,24,25,26,28,29,30,31,33,34,35,36,37,38,39,41,43,45,46,47,48,49,50,51,52,53,55,56,58,59,60,76,79,82,92,94,99,100,107,113,162,167,168,185,219,222,235,260,274,278,290,298,304,333,349,360,364,365,373,376,424,426,427,435,447,470,474,477],"o\u017carowski":477,"petten\u00f2":475,"public":[28,48,60,62,83,87,95,102,104,105,108,148,157,162,167,168,180,192,197,199,202,227,235,240,241,256,262,273,292,293,296,303,311,328,330,338,339,351,360,365,369,379,380,384,389,393,395,409,410,424,425,426,429,432,438,447,451,470,471,473,474,476,477],"return":[3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,46,47,48,49,50,51,52,53,54,55,56,58,59,60,63,64,76,77,79,82,87,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,110,113,114,115,116,118,119,120,121,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,141,142,143,145,146,147,148,149,150,151,152,153,155,156,157,158,159,160,161,162,163,164,165,167,169,170,171,174,175,176,178,180,181,182,185,186,188,191,192,194,196,197,198,199,200,201,202,203,204,206,207,208,210,212,213,214,217,218,219,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,243,244,245,246,247,248,249,250,251,253,256,258,259,260,261,263,264,265,266,267,269,271,273,274,276,277,278,279,280,281,282,283,284,287,290,291,292,293,294,296,297,298,299,300,302,303,304,305,306,308,309,311,312,313,314,315,316,317,318,320,321,322,323,324,326,328,330,331,332,333,334,335,336,338,339,340,341,342,343,345,346,348,349,351,352,353,354,355,356,358,359,360,361,363,364,365,366,367,368,369,370,371,373,374,376,377,379,380,381,382,384,385,386,387,388,389,390,391,392,393,394,396,397,398,399,400,401,403,404,406,407,409,410,411,413,415,416,417,418,419,420,422,423,424,425,426,427,429,430,431,432,433,434,435,436,437,439,440,441,442,443,444,446,449,451,452,453,454,457,458,460,461,462,463,465,470,471,472,473,474,475,476,477],"s\u00e9bastien":469,"short":[1,4,36,37,51,56,60,63,72,83,87,89,95,96,99,101,102,106,107,123,124,132,151,152,167,168,169,186,191,222,228,231,237,256,273,293,300,303,304,315,332,368,373,380,393,396,403,407,427,429,442,445,452,453,461,465,469,470,472,473,475,477],"static":[4,17,24,28,30,51,55,56,60,63,76,77,79,80,81,82,83,90,92,101,111,207,222,223,269,333,391,396,405,438,440,451,465,471,472,473,474,477],"super":[88,90,94,99,101,107,114,123,222,293,326,336,367,403,410,418,440,451,461,472,476],"switch":[11,28,56,60,87,89,92,102,105,106,107,108,150,162,174,186,204,221,230,236,244,256,303,336,339,342,354,369,380,403,440,452,465,470,472,473,474,475,476,477],"throw":[58,80,96,98,109,169,253,411,442,450,475],"transient":[244,266],"true":[4,5,6,7,8,9,10,11,12,14,17,18,19,20,21,22,23,25,28,29,30,31,32,33,34,35,38,39,43,46,47,48,49,50,52,53,54,55,56,58,59,63,70,77,79,81,87,88,90,91,93,96,98,99,100,103,104,107,109,113,114,116,123,125,126,127,132,133,134,135,138,139,140,143,146,147,148,149,150,152,156,157,158,159,162,167,168,169,171,174,178,180,182,186,192,193,194,195,197,198,200,202,203,204,207,208,210,214,215,221,222,225,227,228,230,236,239,241,249,253,256,258,260,261,264,265,266,267,273,281,283,291,292,293,294,299,302,303,304,305,306,308,309,311,313,315,316,317,321,322,325,328,330,331,333,337,338,339,341,342,343,346,350,351,352,353,355,356,358,361,364,365,368,369,371,373,374,379,380,381,383,384,386,388,389,390,391,392,397,399,401,403,404,407,409,410,411,414,416,418,419,423,426,429,431,434,435,436,439,440,442,443,447,451,452,453,454,455,457,460,461,462,463,470,472,473,474,475,476,477],"try":[6,20,30,37,51,55,60,64,67,72,77,79,80,81,82,83,87,89,90,93,95,96,98,99,100,101,102,104,105,106,107,123,128,129,135,139,142,143,144,151,158,160,167,168,169,174,180,182,186,189,190,193,194,205,206,216,221,222,228,230,236,249,251,253,256,258,260,267,273,288,292,293,300,303,304,306,308,311,314,322,323,333,334,338,340,351,352,355,358,360,361,364,365,368,374,380,384,385,387,388,390,393,394,396,400,403,409,410,416,419,423,424,434,435,440,441,442,443,444,445,446,447,449,450,451,452,454,455,457,460,465,470,471,472,473,474,476,477,478],"var":[81,90,94,95,123,157,158,181,222,267,365,381,386,457,461,474,475,476,477],"void":[3,4,6,8,9,11,18,19,20,21,22,24,26,28,30,33,34,36,37,42,45,50,51,52,53,54,55,56,77,79,80,89,92,168,333,373,427,477],"while":[1,6,15,19,21,24,28,30,31,43,45,55,59,60,62,63,64,68,70,72,76,77,79,82,83,87,88,89,90,92,93,94,95,96,98,99,100,101,102,104,106,107,108,109,114,115,116,123,125,127,130,132,133,142,143,147,150,157,158,160,162,164,167,168,169,171,174,178,180,182,183,186,191,192,196,200,203,206,215,219,222,224,226,230,235,236,238,239,240,244,249,251,252,256,258,263,265,266,273,276,277,292,293,294,303,304,308,309,311,314,317,319,322,325,328,330,332,333,338,339,343,345,346,348,353,357,358,360,361,364,365,368,369,373,374,376,380,386,388,389,390,391,392,396,399,400,403,407,409,410,416,417,426,427,429,437,440,442,443,444,445,446,447,448,449,451,452,453,454,455,457,460,461,462,463,465,470,471,472,473,474,475,476,477],"ziad\u00e9":[476,477],ACE:[150,473],ACS:169,AES:473,AND:[72,104,438,442],ARE:438,Added:[55,60,79,96,138,152,156,163,169,210,222,230,236,260,264,266,296,302,304,321,325,333,336,342,351,352,364,369,380,384,388,391,398,407,409,411,416,418,434,435,470,474,475,476,478],Adding:[55,60,69,101,120,301,333,338,401,410,413,470,473,474,476,478],AgE:364,Age:[365,473],And:[64,72,77,91,96,98,99,100,102,106,107,123,125,157,160,167,168,178,186,193,222,230,236,255,302,303,333,337,338,355,364,365,384,401,435,471,475],Are:[60,179,385,456],BEING:438,BUT:[350,438],Being:[1,101,151,346,368],But:[55,66,70,77,79,81,84,87,88,91,92,93,95,96,100,101,102,105,113,152,182,186,218,256,264,273,303,364,365,368,380,392,401,409,440,443,447,451,455,472,473,475,477],CCS:365,CVS:[73,208,304,470,471,472,473,474,475],Cls:447,DES:[165,324,438],DNS:[150,360,365],DOS:[63,81,83,89,169,210,299,303,435,458,459,465,469,470,472],DoS:425,Doing:[88,98,365,407,440],EXE:[89,457,472],Ewing:470,FOR:60,For:[1,3,4,6,9,16,19,20,24,26,28,30,34,35,37,39,45,50,55,58,60,62,63,64,66,67,70,71,72,73,75,76,77,78,79,80,81,82,83,84,86,87,88,89,90,91,92,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,110,113,114,117,118,123,125,127,131,132,134,137,138,139,140,142,143,144,147,150,151,152,157,158,160,161,162,163,167,168,169,170,174,175,178,179,180,182,184,185,186,191,192,193,194,197,198,199,200,201,202,203,205,206,207,208,211,212,214,216,219,221,222,223,225,227,228,230,231,232,235,236,238,239,240,241,242,244,246,252,253,255,256,258,259,260,265,266,267,270,272,273,274,276,277,278,280,281,287,290,291,293,299,300,301,302,303,304,305,306,308,309,311,314,315,317,319,320,322,327,328,329,330,332,336,337,338,339,341,342,346,348,351,352,353,356,358,360,361,364,365,366,368,369,370,371,372,373,374,379,380,381,382,383,384,385,387,388,389,390,391,392,393,394,395,396,400,401,403,404,406,407,409,410,411,412,413,414,415,418,419,422,423,424,425,426,427,429,430,434,435,436,437,438,439,440,442,443,444,445,446,447,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,467,468,469,470,471,472,473,474,475,476,478],Going:77,HLS:154,Has:[30,293,306,332],ICs:243,IDE:[60,83,88,383,405,466,469,470,472],IDEs:[60,83,88,466],IDs:[293,401,418,474],INTO:364,IPS:99,ITS:438,Ice:60,Ides:462,Its:[19,26,51,55,60,62,76,77,79,91,94,106,134,145,158,162,168,169,191,192,222,230,236,256,265,278,284,293,322,342,355,360,365,380,384,390,391,392,403,409,422,435,439,440,442,456,465,470],LHS:447,NCS:415,NFS:[63,95,205],NIS:[60,233,252,408],NOT:[105,162,352,423,438,442],Not:[30,55,60,63,70,79,80,83,88,91,105,106,107,125,132,141,157,162,178,205,225,226,241,269,273,276,293,304,332,339,345,351,353,368,418,446,473,474,475,476],ONE:[104,123,368,406],ORed:[55,186,207,222,304,320,396,422],ORing:365,OSes:[87,256,470],One:[51,58,60,76,77,79,81,84,87,88,90,93,94,95,96,101,102,104,105,106,108,119,122,123,131,147,149,157,168,186,197,215,222,230,244,293,311,318,321,322,331,333,353,357,364,365,368,371,384,388,389,401,409,416,429,440,442,445,446,447,454,457,458,459,460,461,462,470,471,472,473,474,475,476,477],PCs:83,RCS:[73,208],REs:[101,333],RFS:205,RHS:447,Res:[60,268],SUCH:438,Such:[30,55,63,77,81,90,98,123,142,164,180,200,202,244,304,309,311,319,339,407,440,442,447,461,473,477],THAT:438,THE:[197,438],TIS:474,TLS:[60,221,241,252,257,267,358,360,472,476,477],TOS:182,TTS:99,That:[28,55,60,63,64,73,76,79,82,86,88,89,91,93,94,98,100,101,102,103,106,107,143,152,160,169,178,180,186,216,258,260,265,303,316,333,351,358,364,374,386,388,389,413,423,432,437,439,440,442,447,454,455,461,472,473,475,476],The:[1,2,3,4,5,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,36,38,39,41,42,43,45,47,48,49,50,51,52,53,54,55,56,57,59,60,62,65,66,67,68,69,70,72,74,76,78,80,81,82,83,84,87,88,89,90,92,94,95,98,99,102,105,108,109,110,111,113,114,115,116,117,118,119,120,121,122,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,184,185,186,187,188,189,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,209,210,211,212,213,214,216,217,218,219,220,221,222,223,224,225,226,227,228,229,231,232,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,254,255,256,257,258,259,260,263,264,265,266,267,268,269,270,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,294,296,297,298,299,301,302,304,305,306,307,308,310,312,313,314,315,316,317,318,320,321,323,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,364,365,366,367,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,397,398,399,400,401,402,404,405,406,407,408,409,410,411,412,413,414,415,417,418,419,420,422,423,424,425,427,428,430,431,433,434,435,436,437,438,441,443,445,446,448,450,451,454,455,457,458,460,462,463,464,465,466,468,469,470,471,478],Their:[16,55,90,106,150,202,266,304,380,391,429,440,441,442,446],Then:[72,76,81,82,87,88,93,99,107,143,169,174,180,182,186,267,274,290,300,303,354,356,361,364,365,368,369,454,460,469],There:[4,5,6,10,20,21,23,28,30,31,36,38,39,40,43,51,55,59,63,64,68,72,73,76,77,79,80,81,82,83,84,87,88,89,90,91,93,95,96,98,99,100,101,102,103,104,105,106,107,108,123,125,127,131,136,143,146,147,148,150,151,152,157,162,167,168,171,174,178,182,185,186,192,200,202,203,212,222,223,230,231,235,243,246,253,255,256,265,266,273,276,290,293,300,303,304,307,308,311,317,322,328,345,346,351,353,360,361,364,365,368,370,371,373,374,384,385,386,391,393,394,396,401,403,405,407,409,416,424,426,427,430,431,435,437,439,440,441,442,446,448,451,452,453,454,456,457,460,461,462,464,467,468,470,471,472,473,474,475,476,477],These:[0,4,6,7,20,28,30,35,36,37,43,47,50,51,52,55,56,58,62,63,64,72,75,76,77,79,80,81,83,87,88,91,93,96,98,99,100,101,102,104,105,106,107,108,113,123,134,135,141,143,148,150,152,156,158,162,167,168,169,170,174,177,178,180,183,186,192,195,198,200,202,212,221,225,230,231,235,236,243,244,247,253,258,262,264,265,266,268,273,277,281,291,293,300,302,303,304,305,308,311,317,322,328,333,334,336,358,360,361,364,366,368,369,370,374,379,380,381,384,391,392,396,399,403,405,407,410,411,418,423,425,426,427,429,430,439,440,441,442,445,446,447,451,452,453,455,457,459,461,462,463,465,468,470,472,474,476,477],UCS:[4,56,260,380,472],UFS:271,USE:438,USING:438,Use:[16,22,26,30,47,60,77,81,82,87,88,89,90,93,97,102,105,109,113,114,124,135,139,140,143,150,152,155,159,162,168,169,178,182,185,186,193,200,212,222,239,244,258,263,265,269,277,278,279,293,297,299,300,302,303,304,316,317,318,319,322,327,332,348,349,353,364,365,366,368,369,370,373,374,380,384,386,392,394,395,401,409,410,411,429,438,439,451,452,454,467,471,472,475,476,477],Used:[55,60,116,152,169,178,180,182,200,223,257,258,293,330,332,333,365,388,401,403,407,475,477],Useful:[4,60,118,128,143,152,185,198,252,258,265,266,284,308,364,403,421],Uses:[63,150,162,194,277,368,437],Using:[6,24,51,60,70,77,78,81,83,88,89,94,96,97,104,106,114,152,155,158,168,174,177,179,186,213,221,222,224,228,230,235,252,254,257,260,265,266,268,273,303,304,310,317,321,333,344,362,365,368,369,386,395,404,407,410,418,427,436,442,446,447,451,456,461,466,470,471,472,473,474,477,478],VMS:[20,206,303],VMs:182,WAS:104,WILL:[385,438],WITH:[104,150,361,406,438,442],Was:104,Will:[29,63,76,109,113,126,168,246,293,333],With:[4,51,60,63,67,75,76,79,83,88,93,96,98,99,100,102,105,106,107,108,123,125,148,150,152,157,160,169,178,200,207,210,222,225,230,244,277,293,300,303,309,322,330,333,364,365,368,374,381,394,401,403,407,416,427,434,439,442,447,451,460,467,469,471,472,473,475,476,477],YES:212,Yes:[77,81,82,83,87,88,89,91,113,178,191,452,460,472],___:88,______:88,__________:88,_________________:88,_____________________:396,____________________________:88,__abs__:[302,440],__add__:[55,83,253,300,302,339,440],__aepack__:115,__all__:[26,244,251,288,447,461,471],__and__:[152,302,440],__as_immutable__:346,__as_temporarily_immutable__:346,__bases__:[43,79,222,368,440,473],__bool__:[109,393],__builtin__:[28,30,60,90,222,251,252,258,329,337,340,380,441,446,447,448,451,461,473],__builtin_new:60,__builtins__:[26,82,110,222,244,337,441,447,461],__call__:[88,123,151,152,192,197,222,293,302,418,440,442],__capsulethunk_h:92,__class__:[43,83,88,90,94,152,311,368,416,440,451,472,473,476],__closure__:[109,440],__cmp__:[79,90,103,178,346,368,434,440,442,470,471,473,476,477],__code__:440,__coerce__:[440,472,477],__complex__:[14,147,260,440,476],__concat__:302,__conform__:364,__console__:149,__contains__:[48,51,83,152,200,258,273,302,346,368,413,423,440,442,470,473,474,476],__copy__:[163,258],__counter:418,__cplusplu:77,__debug__:[159,447,461,473],__declspec:89,__deepcopy__:163,__defaults__:440,__del__:[20,28,45,77,79,87,225,256,418,440],__delattr__:[79,83,440],__delete__:[90,94,440,472],__delitem__:[83,152,200,273,302,413,423,426,429,440,473],__delslice__:[83,302,440],__dict__:[10,39,43,55,88,94,99,110,114,134,152,186,222,223,249,251,265,267,309,311,322,337,368,404,434,440,451,471,472,477],__dir__:[222,476],__displayhook__:[380,461],__div__:[302,440],__divmod__:440,__doc__:[39,55,79,83,87,90,94,141,149,186,222,223,253,300,327,334,340,439,440,451,452,461,471,472,473],__enter__:[90,99,113,160,182,368,439,440,475,476,477],__eq__:[81,83,90,103,152,159,194,198,223,302,346,368,440,471,476,477],__excepthook__:[380,461],__exit__:[90,99,113,160,182,368,439,440,475,476,477],__file__:[26,39,91,186,222,253,293,314,340,342,407,436,440,447,473],__float__:[22,147,440],__floordiv__:[100,302,440,472],__format__:[83,174,222,369,476,477],__func__:[109,253,440,476,477],__future__:[58,60,88,90,99,100,109,151,182,222,224,252,261,302,329,368,440,447,465,472,473,475,476,478],__ge__:[83,103,152,223,302,368,440,471,477],__get__:[90,94,253,440,472],__getattr__:[79,88,94,168,208,222,311,340,440,458,472,476],__getattribute__:[83,90,94,222,311,440,472,476],__getinitargs__:311,__getitem__:[32,56,83,90,99,103,114,152,168,200,210,222,273,293,302,369,413,423,426,429,440,442,463,472,473,474],__getnewargs__:[152,311,473],__getslice__:[83,90,288,293,302,440],__getstate__:[152,311,473],__globals__:440,__gt__:[83,103,152,223,302,368,440,471,477],__hash__:[55,81,83,90,152,300,346,413,440,465,475,476],__hello__:168,__hex__:[222,224,440,476],__iadd__:[83,88,152,302,339,440,470],__iand__:[152,302,440],__iconcat__:302,__idiv__:[302,440],__ifloordiv__:[302,440],__ilshift__:[302,440],__imod__:[302,440],__import__:[26,60,182,222,249,251,252,266,289,338,461,476],__imul__:[83,302,440],__index__:[60,222,224,302,368,373,440,476,477,478],__init__:[55,67,70,72,79,81,82,83,87,88,94,98,99,102,103,110,123,126,127,132,152,160,164,167,168,174,180,219,222,258,265,266,267,270,284,293,297,311,314,322,334,338,364,369,391,396,407,413,418,423,435,440,451,454,461,463,470,471,472,473,475,476],__instancecheck__:440,__int64:[168,373],__int__:[373,434,440,475,477],__inv__:302,__invert__:[302,440],__iop__:440,__ior__:[152,302,440],__ipow__:[302,440],__irepeat__:302,__irshift__:[302,440],__isub__:[152,302,339,440,470],__iter__:[55,83,90,99,114,152,167,222,253,258,273,293,364,368,407,413,423,435,440,442,451,472,473,476],__itruediv__:[302,440],__ixor__:[152,302,440],__le__:[83,103,152,223,302,368,440,471,477],__len__:[83,90,114,152,200,222,273,293,302,339,368,426,429,440,473,474],__loader__:[263,342,447],__long__:440,__lshift__:[302,440],__lt__:[83,103,152,159,223,302,368,440,442,471,477],__main__:[28,30,58,60,82,87,88,94,98,99,134,180,186,193,222,228,238,244,252,288,293,303,304,309,322,327,329,338,340,342,361,366,388,393,407,441,448,451,454,461,465,471,474,475,476,477],__members__:[368,472],__metaclass__:[109,114,440,472,476],__methods__:[368,472],__missing__:[152,368,440,475],__mod__:[100,302,440],__module__:[20,23,55,223,253,288,440,473],__mro__:[94,114,222,368,440],__mul__:[83,302,440],__name:174,__name__:[39,55,87,88,94,98,99,112,134,149,152,158,180,186,193,222,223,228,251,253,265,293,300,303,309,314,327,335,340,342,355,361,366,368,388,393,407,440,447,461,472,473,476],__ne__:[83,103,152,194,198,302,346,440,471],__neg__:[302,440],__new__:[79,83,152,160,311,440],__next__:[109,293,442],__nonzero__:[109,113,302,368,393,434,440,442],__not__:302,__oct__:[224,440,476],__offset:174,__op__:440,__or__:[152,302,440],__outfil:88,__package__:[222,342,447,461,476],__path__:[26,90,249,251,314,326,380,447,461],__phello__:168,__pos__:[302,440],__pow__:[302,440],__pure_virtu:60,__pycapsule_getfield:92,__pycapsule_setfield:92,__r:300,__radd__:[300,440],__rand__:440,__rcmp__:440,__rdiv__:440,__rdivmod__:440,__reduce__:[83,152,311,475],__reduce_ex__:[83,311],__repeat__:302,__repr__:[83,88,103,152,174,194,222,293,296,364,434,440,463,472,473],__reversed__:[83,152,222,440],__rfloordiv__:440,__rlshift__:440,__rmod__:440,__rmul__:[83,440],__rop__:440,__ror__:440,__rpow__:440,__rrshift__:440,__rshift__:[302,440],__rsub__:440,__rtruediv__:440,__rxor__:440,__safe_for_unpickling__:[311,473],__self__:[253,440,476],__set__:[90,94,253,440,472],__setattr__:[79,83,88,311,440,472],__setitem__:[83,152,200,273,302,311,413,423,426,429,440,473],__setslice__:[83,90,302,440],__setstate__:[311,473],__sizeof__:[83,380,476],__slots__:[55,60,90,152,472,477],__spam:[442,451],__stderr__:[380,461],__stdin__:[380,461],__stdout__:[380,461],__str__:[83,88,98,99,152,174,194,197,198,200,265,293,311,339,369,440,454,472],__sub__:[152,302,339,440],__subclasscheck__:[54,114,440],__subclasses__:368,__subclasshook__:[83,114],__test__:186,__truediv__:[100,302,440,472],__trunc__:277,__unicode__:[198,222,440,472,477],__updat:451,__version__:[125,169,354,407],__vm:20,__warningregistry__:416,__weakref__:[55,440],__x:94,__xor__:[152,302,440],_abcol:152,_add:300,_anonymous_:168,_any_:89,_as_parameter_:168,_asdict:[90,152,476,477],_ast:[125,475],_attribut:284,_audiodata:201,_b_base_:168,_b_needsfree_:168,_bcpp:107,_beginthreadex:477,_bool:[168,373,476],_bootstrap:293,_build_pi:68,_builtinsuit:476,_c_api:77,_cach:[88,293,471],_callmethod:293,_cdata:168,_cfg:403,_charset:[192,201,230],_cl:152,_class:[202,284],_classname__spam:[88,451],_clear_type_cach:[380,461],_clearcach:222,_commit:304,_compil:322,_compile_charset:322,_connect:407,_copy_file_cont:63,_count:128,_create_unverified_context:[241,477],_ctype:[168,438,477],_current_fram:[380,461,475],_darc:73,_data:201,_debug:30,_debug_info:293,_declspec:80,_deco:474,_default_typ:192,_defaultformatt:266,_dispatch:355,_dummy_thread:189,_encod:[192,201],_error:410,_error_cod:410,_errorhold:407,_exit:[128,206,304,380],_expand:288,_exposed_:293,_factori:202,_fallback:230,_featur:[90,111,222],_field:[125,152,476,477],_fields_:[168,293],_file:386,_flush:423,_foo:72,_free:475,_from_iter:152,_frozen:[26,168],_funcptr:168,_get_anothervalu:426,_get_foo:427,_get_somevalu:426,_getfram:[98,380,461,471],_getvalu:293,_grouper:258,_ham__spam:442,_handl:168,_hash:152,_helper:476,_hotshot:238,_https_verify_certif:[365,465,477],_id2obj_dict:418,_identityfunct:322,_imagedata:201,_info:230,_inittab:26,_int64:4,_inverted_registri:288,_isdst:174,_itemgett:152,_length_:168,_local:264,_logpath:352,_low_:89,_lsprof:322,_maintyp:[192,201],_major:192,_make:[90,152,373],_makeresult:407,_malloc:475,_mangle_from_:197,_mapping__upd:451,_mappingsubclass__upd:451,_maxfreelist:476,_mercuri:461,_method_to_typeid_:293,_minor:192,_msg:201,_name:[168,200],_node:58,_not_:89,_ob_next:[51,55],_ob_prev:[51,55],_object:[168,284],_open:410,_operator_fallback:300,_optimize_charset:322,_optimize_unicod:288,_outfil:88,_output_charset:230,_pack_:168,_param:[200,201,423],_pars:230,_patternend:288,_pc_pipe_buf:317,_pid:293,_pointer:168,_pool:293,_popen:304,_properti:152,_proxi:[409,410],_py:30,_py_c_diff:14,_py_c_neg:14,_py_c_pow:14,_py_c_prod:14,_py_c_quot:14,_py_c_sum:14,_py_dealloc:45,_py_forgetrefer:45,_py_newrefer:45,_py_nonestruct:[3,89],_py_reftot:45,_pyimport_findextens:26,_pyimport_fini:26,_pyimport_fixupextens:[26,60],_pyimport_init:26,_pyimport_inittab:77,_pyimport_loaddynamicmodul:82,_pyio:477,_pyobject_del:[3,55],_pyobject_extra_init:51,_pyobject_gc_track:24,_pyobject_gc_untrack:24,_pyobject_getdictptr:55,_pyobject_new:3,_pyobject_newvar:3,_pyparser_grammar:82,_pystring_res:50,_pytuple_res:[53,472],_quit:219,_random:438,_regrtest_top:186,_remoteaddr:357,_replac:[152,476],_repr:346,_request:410,_rescal:178,_respons:410,_resultobj:89,_root:396,_save:28,_screen:403,_self:152,_send_traceback_head:476,_set_anothervalu:426,_set_foo:427,_setroot:429,_shutdown:477,_signatur:116,_simplecdata:168,_slotnam:288,_socket:473,_spam:451,_srcfile:98,_sre:[101,214,288,333,338],_start:116,_state:92,_stdcallfuncptr:168,_stream:290,_structur:[192,199],_subpart:201,_subtyp:[192,193,201],_temp:222,_temporarilyimmutableset:346,_test:407,_text:201,_texttestresult:407,_thread:[28,189,190,390,473],_threading_loc:391,_time:174,_timer:293,_tkinter:[395,396,473],_tupl:152,_type:[284,288],_type_:168,_typeobject:[55,79],_urlopen:409,_validation_record:290,_valu:[94,200],_voltag:222,_warn:388,_weakref:4,_winreg:[60,252,421,470,476,477],_write:423,_xmlplu:288,_xx_:270,a0c8f0:403,a1b2c3:333,a2b_base64:135,a2b_hex:[135,150],a2b_hqx:135,a2b_qp:135,a2b_uu:135,a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2:235,a7p10:368,a8098c1a:[415,475],a_altcharset:169,a_attribut:169,a_blink:[93,169],a_bold:[93,169,476],a_bool:158,a_chartext:169,a_color:169,a_dim:[93,169],a_expr:442,a_float:158,a_horizont:169,a_invi:169,a_left:169,a_list:88,a_lock:390,a_low:169,a_norm:169,a_protect:169,a_revers:[93,169],a_right:169,a_standout:[93,169],a_top:169,a_tupl:157,a_underlin:[93,169],a_url:105,a_vert:169,aaa:477,aaaa:[258,477],aaaaa:477,aaaaaa:333,aaaaaaaaaa:321,aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:321,aaaab:333,aaaabbbccd:258,aaaabbbccdaabbb:258,aaab:333,aahz:[87,470,474,475],ababababab:101,abandon:[206,431],abbc:96,abbccad:258,abbrevi:[60,90,104,120,140,169,174,178,264,303,309,322,374,392,429,463,465],abc123:476,abc:[60,77,81,83,88,90,96,100,101,104,152,168,222,228,252,258,265,266,293,301,329,333,346,368,369,388,438,440,442,451,453,460,470,472,473,474,475,476,477],abcabcabc:470,abcb:101,abcbd:101,abcd:[101,104,180,258,473,476],abcdef:[104,152,168,258,333,477],abcdefg:[258,302],abcdefghij:332,abcdefghijk:104,abcdefghijklm:476,abcdefghijklmnopqrstuvwxyz0123456789:333,abcdefghijklmnopqrstuvwxyz:[369,477],abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz:477,abcefg:368,abcmeta:[114,440,476],abday_1:264,abday_7:264,abdolmalek:333,abelson:96,abi:477,abid:391,abil:[6,62,66,76,77,88,90,91,93,96,98,99,101,107,108,118,152,184,186,225,293,303,342,369,407,413,426,435,436,438,440,452,471,472,473,475,476,477],abl:[3,6,28,55,64,70,71,72,77,79,80,81,83,87,89,90,93,98,99,100,101,102,104,106,108,124,129,143,150,151,168,169,174,196,206,215,222,236,240,265,266,267,303,304,306,308,311,323,328,338,352,359,370,374,384,391,396,403,416,422,423,426,442,445,447,456,459,470,471,472,475,477],abmon_12:264,abmon_1:264,abnorm:[309,380,411],abnsec:333,abort:[16,52,77,95,99,205,221,246,304,309,364,365,385,407,473],about:[1,4,6,13,20,22,28,30,36,37,50,55,60,63,64,67,70,72,75,76,77,78,79,80,81,84,86,87,89,90,91,93,94,95,96,98,99,100,101,102,104,105,106,107,113,115,117,123,124,125,129,134,141,142,147,148,149,150,152,154,162,164,167,168,170,174,178,179,180,192,194,202,206,208,212,213,216,219,221,222,225,230,231,235,237,243,244,245,253,254,255,258,265,266,267,273,288,293,299,300,302,303,304,308,309,311,312,315,317,318,320,322,326,332,333,334,336,338,339,341,350,352,357,358,363,364,365,366,368,370,374,380,384,385,388,395,396,400,401,407,410,413,416,418,423,424,425,426,430,432,435,439,440,441,442,445,447,450,452,453,454,456,457,460,461,464,465,469,471,472,473,474,475,476,477,478],abov:[4,20,21,28,30,37,43,52,55,64,68,70,71,72,73,75,76,77,79,88,89,90,91,92,93,94,95,96,98,99,100,101,103,104,105,106,107,109,115,118,119,121,123,125,137,138,142,143,147,150,152,162,167,168,169,170,171,174,178,180,182,185,186,191,192,193,206,207,212,216,221,230,235,236,241,243,244,249,256,258,264,265,266,267,270,277,287,293,299,300,303,304,305,308,309,311,315,317,322,327,333,338,342,348,352,353,355,356,359,360,364,365,366,368,369,370,374,376,380,384,386,388,392,394,396,399,401,403,404,407,409,410,411,413,414,416,418,423,424,426,438,440,445,446,447,451,452,454,455,460,461,465,470,471,472,473,474,475,476,477],abra:369,abracadabra:[94,152,293,369,453,474],abridg:273,abrupt:361,abruptli:[365,391],abs:[41,55,90,96,147,174,178,222,277,300,302,368,403,440,442,451,453,461],absenc:[81,98,105,106,159,333,390,391,423,440,460],absent:[123,152,169,207,266,309,360,368,369,409],absmax:219,absmin:219,abso:117,absolut:[26,28,41,55,60,72,76,79,81,87,88,98,107,111,113,117,129,134,142,143,146,147,178,182,186,206,212,218,222,230,232,250,256,266,277,287,302,303,304,305,315,351,358,368,380,384,386,396,403,411,431,435,437,440,442,447,451,457,461,465,470,474,476,477,478],absolute_import:[100,111,447,475],abspath:[193,305,477],abstractbasicauthhandl:[60,254],abstractdigestauthhandl:[60,254],abstractformatt:215,abstractmethod:[114,476],abstractproperti:[114,476],abstractwrit:215,abus:[81,425,447],abxcd:180,abxd:101,abycdf:180,ac_in_buffer_s:126,ac_out_buffer_s:126,acceler:[88,403,470,471,475],accent:104,accept2dyear:392,accept:[4,14,16,19,21,22,24,28,29,33,34,39,50,53,55,56,58,59,63,72,77,79,81,82,87,88,90,91,93,95,96,99,100,101,102,103,104,105,106,111,113,123,124,127,131,132,133,143,147,148,150,152,153,157,158,162,165,168,169,170,174,178,180,186,191,203,207,218,221,222,223,224,228,230,241,243,244,256,258,260,264,265,266,273,287,291,293,300,302,303,304,306,308,311,320,328,331,333,345,346,350,351,352,353,358,360,361,364,365,368,369,370,374,380,384,386,388,389,392,394,398,399,401,407,409,414,419,423,426,427,432,434,435,437,438,440,442,446,447,451,452,463,470,471,472,473,474,475,476,477],acceptlist:388,acceptstr:388,accepttupl:388,access:[3,4,6,8,9,11,15,20,23,26,28,30,41,45,47,48,51,52,55,56,60,63,69,70,76,77,79,80,83,88,89,90,94,95,98,99,100,103,104,105,106,107,108,110,114,115,116,119,120,124,132,138,139,141,143,147,150,152,153,157,161,162,167,174,175,178,182,186,191,193,200,202,204,205,206,210,213,219,222,224,225,230,231,233,235,236,242,244,247,252,253,254,255,256,257,258,259,262,265,267,268,270,271,273,277,281,286,287,289,290,291,292,293,295,296,302,303,304,305,307,309,310,311,314,319,324,328,329,333,334,336,337,338,345,347,350,352,355,358,360,361,363,365,366,368,369,374,375,380,384,385,388,391,393,394,396,401,403,404,405,406,407,409,413,418,421,422,423,425,426,427,429,431,439,441,442,447,451,453,456,457,459,460,461,463,464,467,469,470,471,473,474,475,476,477],access_copi:287,access_read:287,access_writ:287,accesslog:462,accessor:[8,60,88,103,222,275,427,475],accessori:[70,89,107],accid:[79,81,222,451,476,477],accident:[28,81,100,180,186,206,447,451,454,461,471,473,476],accommod:[76,396,453,474],accompani:[30,273,345,358,360,405,440,471],accomplish:[28,30,88,100,123,169,319,350,409,426],accord:[16,28,29,34,56,58,60,63,72,88,94,99,104,116,133,143,150,155,162,167,168,174,178,192,193,200,203,208,222,227,230,232,233,246,252,253,254,258,264,265,266,270,290,292,303,304,322,339,341,365,366,368,371,373,380,392,394,401,403,407,409,426,438,440,442,446,453,472,473,474,475],accordingli:[56,79,91,93,96,106,167,210,222,260,332,346,368,401,404,409,440,472,476],account:[1,55,62,63,83,87,101,102,108,150,152,174,178,180,198,203,221,264,266,296,321,324,363,373,385,392,438,455,475],accssor:[60,268],acct:221,accum_valu:222,accumul:[90,93,123,178,222,282,303,304,322,351,399,407,452,471],accur:[37,100,132,168,202,277,303,322,384,392,393,435,474,476,477],accuraci:[174,258,277,301,322,393,438,474],accustom:[100,178,458],ace:333,aces:333,achiev:[28,62,66,67,76,81,88,96,99,123,150,158,168,174,222,236,258,265,344,365,368,391,393,396,401,407,447,470,472,473,475],achim:476,acidli:472,ack:[0,170,476],acknowledg:[60,158,170,242,478],acl:[246,352],acm:[162,332,443],aco:[147,277],acosh:[147,277,476],acquaint:303,acquir:[28,30,77,91,160,207,249,265,273,293,294,344,365,368,384,390,391,440,475,476,477],acquire_lock:249,acquire_resourc:160,acquisit:[207,265],acronym:[104,392],across:[37,57,60,62,63,66,72,73,79,81,91,100,107,123,135,168,174,182,184,186,222,253,257,258,264,265,267,293,311,312,345,350,368,380,386,391,401,403,409,410,437,442,446,473,474,476,477],acs_:93,acs_bbss:169,acs_block:169,acs_board:169,acs_bsb:169,acs_bssb:169,acs_bsss:169,acs_bte:169,acs_bullet:169,acs_ckboard:169,acs_darrow:169,acs_degre:169,acs_diamond:169,acs_gequ:169,acs_hlin:169,acs_lantern:169,acs_larrow:169,acs_lequ:169,acs_llcorn:169,acs_lrcorn:169,acs_lte:169,acs_nequ:169,acs_pi:169,acs_plminu:[93,169],acs_plu:169,acs_rarrow:169,acs_rte:169,acs_s1:169,acs_s3:169,acs_s7:169,acs_s9:169,acs_sbb:169,acs_sbsb:169,acs_sbss:169,acs_ssb:169,acs_ssbb:169,acs_sssb:169,acs_ssss:169,acs_sterl:169,acs_tte:169,acs_uarrow:169,acs_ulcorn:[93,169],acs_urcorn:169,acs_vlin:169,act:[55,59,72,79,83,88,92,93,96,98,100,114,134,161,168,174,200,222,223,246,250,256,265,293,304,339,368,380,391,394,401,413,440,447,460,470,471,476],action:[1,28,37,48,55,60,63,77,79,91,93,101,104,106,120,126,134,148,152,160,167,169,180,193,207,215,228,236,241,290,307,309,313,322,343,345,353,361,380,384,385,387,390,391,396,401,403,407,409,410,416,418,423,437,438,440,447,452,456,465,470,471,473,474,475,476,477],actionbuttonlabel:191,actiontext:290,activ:[28,30,43,55,62,72,76,81,83,84,88,89,93,100,101,102,106,108,127,134,143,145,152,162,167,169,178,204,210,212,219,221,244,261,274,293,303,306,309,322,328,361,364,368,374,377,380,391,392,396,401,403,427,431,447,458,470,472,473,475,476,477],activate_form:212,active_children:293,active_count:[293,391,476],activecount:[391,476],activeforeground:396,activepython:[88,469],activest:[88,107,396,464,467,470],actor:[429,452],actual:[4,6,14,20,28,29,30,43,48,54,55,58,62,63,64,67,72,77,79,80,81,87,88,90,91,92,93,94,96,98,99,100,101,102,104,106,107,113,118,124,125,127,132,133,138,143,152,155,158,160,165,168,169,170,186,193,195,201,202,206,221,222,225,230,232,236,246,256,258,265,266,267,273,283,287,290,293,303,304,306,308,309,311,315,318,322,332,338,339,343,350,358,359,360,361,364,365,368,369,374,376,380,384,391,392,396,398,407,409,410,411,413,423,426,430,435,437,438,439,440,441,445,446,447,451,452,455,462,465,470,471,472,473,474,475,476,477],acut:[83,104,440],acw:244,adam:[364,476,477],adapt:[37,55,60,99,109,113,121,129,132,144,152,158,161,162,164,168,176,187,188,189,222,226,230,239,240,241,292,309,310,330,335,341,344,354,355,361,365,390,394,396,403,409,410,411,413,420,434,470,471,475,477],adapt_datetim:364,adapt_point:364,adat:316,add:[4,6,24,26,30,39,48,51,55,62,63,64,68,71,72,73,77,79,80,81,82,83,86,87,88,89,90,91,93,96,98,99,100,101,103,104,105,106,107,109,118,123,124,125,126,127,129,139,142,143,145,149,150,152,156,157,158,159,161,162,169,174,178,186,192,194,200,201,212,215,219,221,222,230,236,238,239,249,256,258,260,265,266,273,275,279,281,282,290,293,300,302,303,304,311,313,314,315,319,320,321,322,333,335,338,340,345,346,352,355,356,358,364,365,368,380,384,388,394,396,401,403,407,410,411,413,418,423,426,427,429,430,434,435,436,440,442,445,446,447,450,451,452,453,454,457,458,459,460,463,465,467,468,469,470,471,472,473,474,475,476,477],add_:212,add_alia:194,add_argu:[60,91,120,228,477],add_argument_group:123,add_box:212,add_brows:212,add_browser_lin:212,add_button:212,add_cgi_var:423,add_charset:194,add_choic:212,add_clock:212,add_codec:194,add_cookie_head:162,add_count:212,add_data:[290,410],add_dial:212,add_fallback:230,add_fil:290,add_flag:273,add_flowing_data:215,add_fold:273,add_handl:[105,410],add_head:[192,193,200,201,410,423],add_help:[60,120],add_help_opt:303,add_histori:[82,334],add_hor_rul:215,add_include_dir:63,add_input:212,add_label:273,add_label_data:215,add_librari:63,add_library_dir:63,add_lightbutton:212,add_line_break:215,add_link_object:63,add_literal_data:215,add_menu:212,add_mutually_exclusive_group:[91,123],add_opt:[123,180,193,303,473],add_option_group:303,add_par:410,add_pars:123,add_password:[105,410],add_payload:[192,196],add_position:212,add_roundbutton:212,add_runtime_library_dir:63,add_sect:158,add_sequ:273,add_slid:212,add_stream:290,add_subpars:123,add_suffix:251,add_tabl:290,add_task:236,add_text:212,add_tim:212,add_trick:451,add_typ:281,add_unredirected_head:[162,410],add_valslid:212,addcallback:142,addch:[93,169],addcleanup:[407,477],addcompon:403,added:[3,19,26,28,30,43,50,55,60,62,63,68,72,73,77,79,81,88,89,90,91,93,96,98,99,100,101,103,106,107,108,109,114,123,125,127,129,135,139,142,143,147,148,150,152,158,161,162,167,168,171,174,178,182,186,191,192,196,199,200,201,202,212,215,221,222,225,226,229,234,236,241,244,249,252,256,258,263,265,266,267,273,276,277,281,290,293,299,303,304,309,311,314,315,318,320,321,322,330,335,338,339,342,346,350,355,356,358,360,365,368,369,373,380,382,384,385,392,396,403,407,409,410,416,417,419,423,426,427,429,434,435,438,440,442,447,453,457,459,465,469,470,471,472,473,474,475,476,477],adder:96,adder_funct:355,adderror:407,addexpectedfailur:407,addfailur:407,addfil:384,addfilt:[98,99,265],addfold:191,addhandl:[98,99,265],addhead:[192,282,410],addict:471,addind:427,addinfo:238,adding:[19,30,41,54,55,77,79,80,81,83,87,88,90,93,96,99,100,105,107,114,125,129,143,152,157,158,162,178,194,200,201,222,260,265,273,283,300,303,304,346,368,391,413,418,423,429,435,436,440,446,447,454,457,460,461,469,470,472,473,474,475,476,477],addison:396,addit:[1,4,20,26,28,30,36,37,51,55,58,60,62,63,64,67,68,69,73,75,77,79,83,87,89,90,95,96,98,99,101,104,106,107,108,109,113,114,118,121,123,125,127,129,131,132,138,140,141,143,149,150,152,158,162,163,167,168,169,172,174,175,176,178,180,182,184,186,188,192,196,200,201,204,207,210,215,216,218,221,222,223,226,230,234,235,238,239,240,241,246,251,252,256,260,264,265,266,270,273,275,276,277,281,282,293,295,302,303,304,305,307,308,310,311,315,318,319,320,321,322,326,328,333,335,338,346,348,350,351,356,358,360,365,366,369,372,373,374,376,378,380,384,385,386,388,389,390,391,392,393,394,395,396,398,401,403,405,406,407,409,410,411,413,416,418,423,424,426,427,430,431,432,433,435,439,441,442,443,444,445,446,447,449,451,453,454,456,457,459,460,461,463,464,465,466,470,471,472,473,474,475,476,477],addition:[28,55,64,99,101,106,107,123,181,221,282,293,303,304,318,327,374,396,426,438,470,477],additional:365,addlevelnam:265,addnewfil:191,addnstr:169,addoldfil:191,addpackagepath:288,addr:[126,127,143,187,355,360,365],addr_typ:360,address:[4,20,41,50,55,60,63,70,72,77,79,81,83,88,93,98,99,101,102,109,117,124,127,132,162,168,174,180,182,186,192,193,203,205,207,222,241,243,265,267,273,284,333,336,339,355,357,358,360,361,362,365,368,410,411,415,423,440,470,472,473,475,476,477],address_famili:[360,361],address_str:132,addresse:267,addresslist:[60,295],addressof:168,addshap:403,addsitedir:[107,356],addskip:407,addstr:[93,169],addsuccess:407,addtest:[186,407],addto_brows:212,addto_choic:212,addto_menu:212,addtwic:451,addtypeequalityfunc:[407,477],addunexpectedsuccess:407,adequ:[55,88,455,477],adher:[72,132,150,260,293,339,445,452],adict:316,adjac:[63,81,101,174,180,291,333,407,426,446,452],adject:[128,457],adjust:[4,9,47,62,72,100,108,123,169,174,178,321,342,365,368,392,394,396,401,440,470,477],adler32:[235,437],adler:[437,438],adminemailhandl:99,adminexecutesequ:290,administ:[470,476],administr:[26,28,52,63,66,70,72,83,86,98,106,107,143,148,222,246,298,356,360,423,441,449,459,469,474],adminuisequ:290,ado:147,adopt:[321,410,452,471,472,473,476],adpcm2lin:129,adpcm:129,adpcmfrag:129,ads:162,advanc:[27,60,79,81,82,83,88,90,93,101,102,107,120,167,168,169,178,179,222,236,258,265,266,267,287,303,346,360,364,365,368,369,374,380,393,418,427,435,445,450,451,458,462,463,469,473,478],advantag:[1,72,77,79,81,88,96,98,99,103,106,107,127,157,160,178,222,311,368,393,394,407,427,429,431,457,460,462,470,473,474],advent:106,adverb:[60,372],advertis:[95,205,358,365,438,476],advis:[6,98,240,246,293,304,391,438,440,459],advisori:[102,273,465,470],advtexecutesequ:290,aealmlobdk:333,aedesc:[115,116],aeiou:368,aeobject:117,aepack:[60,116,117,252,270,476],aeserv:[60,270],aest:392,aet:227,aetext:117,aetool:[60,252,270,284,476],aetyp:[60,115,116,252,270,476],aeut:227,af_inet6:360,af_inet:[39,99,102,127,293,360,361,365,476],af_netlink:[360,475],af_pip:293,af_tipc:360,af_unix:[293,360,361],af_unspec:360,afalsevalu:316,affair:470,affect:[3,28,30,33,63,66,67,77,87,94,96,99,101,107,113,114,134,157,158,162,169,174,178,182,186,198,222,230,239,244,256,259,264,273,287,302,304,311,314,319,321,328,333,334,335,336,364,368,369,380,384,388,392,393,394,401,403,407,418,426,439,440,442,447,449,451,461,465,470,471,472,473,475,476,477],affin:178,affix:440,afford:[90,470],afloat:316,afmt_a_law:306,afmt_ima_adpcm:306,afmt_mu_law:306,afmt_queri:306,afmt_s16_b:306,afmt_s16_l:306,afmt_s8:306,afmt_u16_b:306,afmt_u16_l:306,afmt_u8:306,aforement:[28,364],afoul:[471,473],afresh:[98,265],africa:476,after:[3,4,6,7,16,20,21,24,28,30,37,50,52,54,55,56,63,64,66,71,72,73,76,77,79,81,83,88,89,90,92,93,95,96,98,99,100,101,102,103,105,106,107,109,111,113,118,120,123,126,127,128,132,134,135,137,139,140,142,143,145,146,148,149,160,168,169,171,174,178,180,182,186,191,194,196,200,201,202,204,205,206,207,210,216,217,219,221,222,225,227,228,234,241,243,244,245,246,247,251,256,258,263,264,265,267,273,287,288,291,293,302,303,304,305,306,309,312,314,315,317,318,320,322,328,332,333,334,339,343,345,346,353,356,358,360,361,362,363,364,365,366,368,369,371,374,376,380,384,386,387,388,389,390,391,392,393,394,396,400,401,403,407,409,416,417,418,423,425,426,431,432,435,437,439,440,441,442,445,447,449,450,451,452,454,456,457,459,460,461,463,465,467,470,471,472,473,474,475,476,477,478],afterward:[28,76,125,168,174,178,258,345,364,380,385,440,459,460,472,473],again:[24,28,55,63,64,67,71,72,77,81,86,87,88,89,90,93,95,96,99,101,102,103,105,108,119,135,138,143,152,158,162,168,169,174,192,197,205,208,244,249,256,258,259,265,267,277,287,291,293,303,304,306,309,311,322,327,345,351,353,358,364,365,368,377,380,388,391,394,401,403,406,416,425,437,439,440,442,446,451,454,455,457,460,461,464,470,472,473,476],against:[6,43,63,72,76,77,79,81,88,89,90,92,100,101,106,109,119,123,129,168,180,186,235,273,276,287,303,311,315,318,321,322,328,333,338,342,364,365,388,394,396,401,403,416,425,427,428,429,430,434,465,470,471,472,473,474,475],age:[63,100,103,152,161,162,364,365,462,472,474],agenc:[364,365,438],agent:[101,105,273,274,341,358,409,410,472,476],ages:477,aggreg:[258,364,407],aggregate_class:364,aggress:[36,81,475],agl:168,ago:[88,90,472],agre:[365,438],agreement:[60,470],ahead:[101,118,198,258,332,368,385,392,426,461,474],ahear:438,ahi:180,ahlstrom:[436,470,473],ahoi:161,ai_:360,ai_canonnam:360,ai_numerichost:360,ai_pass:360,aid:[55,90,191,462,473,474,477],aifc:[60,252,286,359,376,417,470],aiff:[60,146,252,286,359,405,461],aiffread:461,aiffwrit:461,aim:[37,62,76,79,81,84,100,105,107,277,290,380,440,469,472,474,475],aio:345,aix:[77,319],ajp:106,aka:[125,186,381,425,440],akei:316,akin:90,akm:101,akt5:333,akt5q:333,akt:333,al_:119,ala:89,alacazam:[453,474],aladdin:438,alan:[475,476],alarm:[322,353],alaw2lin:129,alaw:[118,376],albatross:230,albeit:[192,230,452],alberto:476,albrecht:333,alert:[93,102,240,267,365,416],alert_description_:365,alert_description_handshake_failur:365,alert_description_internal_error:365,alex:[82,87,473,476,477],alexand:[476,477],alexandr:[476,477],alexei:476,algebra:[258,476],algorithm:[28,37,43,60,81,88,90,101,103,122,129,131,135,139,143,150,165,166,173,174,178,180,186,230,235,237,245,246,252,253,256,264,267,277,286,290,311,314,322,324,332,338,346,365,368,389,392,393,410,423,435,436,437,442,451,470,472,473,475,477],algorithms_avail:[235,477],algorithms_guarante:[235,477],alia:[20,26,37,43,50,52,56,63,72,88,100,115,124,125,150,152,161,168,170,194,228,230,256,271,298,302,303,304,309,328,339,346,365,374,388,401,403,404,407,419,434,441,451],alias:[50,60,63,76,92,150,179,194,230,264,271,309,315,360,391,401,403,440,451,471,473,476],aliaslist:360,alien:391,align:[6,55,60,120,146,212,215,239,245,369,372,401,403,424,476,477],alist:[182,316,339,440],aliv:[55,87,88,168,225,293,318,368,391,418,440,463,465,471,477],all:[1,2,4,6,10,13,19,20,24,26,28,29,30,33,37,41,45,48,50,51,52,54,55,56,60,61,64,65,66,67,68,69,70,71,72,73,75,76,77,79,80,82,83,84,86,87,89,90,91,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,110,113,114,115,118,119,120,123,124,125,126,127,128,129,132,134,135,136,137,139,140,141,143,146,148,149,150,151,152,154,156,157,158,160,161,162,167,168,169,170,174,175,178,180,182,183,184,185,186,187,191,192,193,195,196,197,198,199,200,201,202,203,204,205,206,207,208,210,212,214,215,218,219,220,221,222,223,225,226,227,228,230,231,232,233,234,235,236,237,238,239,240,241,243,244,245,246,247,249,251,252,253,254,255,256,258,260,261,263,264,265,266,267,269,270,271,273,274,276,277,278,279,281,282,283,285,287,290,292,296,298,299,300,302,304,305,306,307,308,309,311,312,314,315,316,317,318,320,322,324,325,326,327,328,330,332,336,338,339,342,343,345,346,348,349,350,351,352,353,355,356,358,360,361,362,363,364,365,366,368,369,371,372,373,374,376,377,380,381,382,383,384,385,386,387,388,389,391,392,393,394,396,398,399,400,401,403,404,405,406,407,409,410,413,415,416,417,418,419,422,423,424,425,426,427,429,430,431,432,433,434,435,437,438,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,465,467,468,469,470,471,472,473,474,475,476],all_equ:258,all_error:221,all_featur:431,all_properti:431,all_recipi:203,allen:365,allevi:470,alli:471,alliancefranais:[150,473],alloc:[4,20,24,26,27,28,30,44,49,55,60,76,77,81,88,102,113,168,225,256,293,304,311,328,360,390,391,401,432,465,470,471,472,475,477,478],allocate_lock:390,allocationgranular:287,allocfunc:[55,79],allow:[1,3,4,6,14,15,16,19,21,22,28,29,30,33,34,36,39,43,50,53,55,56,60,62,63,64,68,71,72,76,77,79,82,84,87,88,89,90,91,92,93,96,98,99,100,101,102,103,104,105,106,108,109,113,123,125,126,130,131,133,136,138,139,140,143,144,146,149,150,152,153,158,160,161,162,165,167,168,169,172,174,177,178,185,186,187,191,194,198,200,204,206,210,215,216,219,221,222,223,228,230,231,234,235,238,239,241,244,246,247,256,258,259,260,261,263,264,265,266,267,270,273,277,280,281,282,284,287,288,293,294,296,297,298,299,303,304,306,308,309,314,317,321,322,327,328,332,333,334,335,337,338,341,342,343,344,345,348,349,350,351,353,355,360,361,364,365,368,369,371,374,376,377,378,380,384,386,388,389,391,392,394,395,396,397,399,401,403,405,407,409,410,411,412,413,414,416,417,418,419,422,423,425,426,427,428,431,432,434,435,436,437,439,440,441,442,443,446,447,450,451,452,454,457,460,462,463,465,467,470,471,472,473,474,475,476,477],allow_dotted_nam:355,allow_exit_without_flush:293,allow_foo:266,allow_frag:411,allow_nan:260,allow_no_valu:[158,477],allow_non:[187,355,434,473],allow_reuse_address:[99,355,361,476],allowed_domain:162,allowremov:142,allowunassign:150,allowzip64:435,alltest:407,almost:[16,28,30,55,66,70,76,79,81,87,88,90,91,93,95,101,102,104,106,107,109,120,123,127,147,149,157,169,236,264,266,274,293,299,303,332,333,364,368,380,396,407,437,440,445,455,462,471,473,476],alo:180,alon:[6,50,79,84,99,101,104,107,187,224,309,333,342,351,355,438,445,472,475],along:[6,30,31,63,72,81,96,98,99,107,123,127,128,129,147,156,168,173,178,186,192,210,230,238,249,267,287,311,322,365,368,369,374,383,401,407,423,430,441,462,470,471,472,473,474,476,477],alongsid:[63,66,236,394],alpha:[63,72,83,90,111,216,276,332,373,380,381,470,471,476],alphabet:[56,88,91,104,131,165,170,178,215,222,265,273,315,322,356,368,446,473,474,475,476,477],alphanumer:[56,101,143,170,186,266,270,333,348,351,368,392,463,473],alpn:365,alqueryparam:119,alreadi:[1,4,20,21,26,28,29,33,43,47,50,53,58,62,63,64,70,77,79,80,81,83,88,89,90,91,93,96,100,101,102,103,104,106,107,108,109,113,121,123,125,127,135,137,143,152,158,162,163,168,174,180,192,193,196,200,204,205,210,215,219,221,222,224,225,236,244,246,249,256,258,265,266,273,281,290,291,293,303,304,311,314,321,322,334,335,345,352,360,368,374,380,382,385,388,391,396,401,403,407,409,413,414,416,419,426,427,433,439,440,442,447,451,452,453,457,461,464,469,470,472,473,474,475,476,477],also:[1,3,4,6,8,9,20,21,24,28,30,45,47,48,51,52,55,56,58,59,62,63,64,66,67,71,72,75,76,77,78,79,80,81,82,83,84,86,87,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,110,111,113,114,116,117,121,122,123,124,125,128,129,134,136,139,140,141,142,143,144,145,146,147,148,149,150,151,152,155,156,157,158,159,160,161,162,165,167,168,169,173,174,178,180,182,183,186,191,192,194,195,196,197,198,200,201,202,206,207,208,210,212,213,216,218,219,221,222,223,225,227,228,230,231,233,234,235,236,237,239,240,241,243,244,246,247,251,252,253,255,256,258,259,260,264,265,266,267,269,270,273,276,278,281,282,283,287,288,290,293,300,302,303,304,305,306,307,308,309,310,311,314,315,317,318,319,320,321,322,323,326,327,328,332,333,336,337,338,339,342,343,345,346,348,350,352,354,356,358,360,361,364,365,366,368,369,370,371,372,373,374,375,378,379,380,384,386,387,388,389,390,391,392,393,394,395,396,397,398,399,401,403,404,405,406,407,409,410,413,414,415,416,418,419,422,423,424,425,426,427,429,430,431,432,433,434,435,436,438,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,467,469,470,471,472,473,474,475,476,477],alt:[169,170,239,240,244,401,470],alt_digit:264,altchar:131,alter:[6,19,63,71,90,146,162,178,191,246,260,266,274,320,342,346,368,384,403,436,438,440,457,463,470,474],alter_si:342,altern:[0,16,20,43,60,62,64,69,71,77,78,81,87,88,90,94,96,99,101,104,105,106,109,110,113,123,125,128,131,136,147,150,152,158,167,168,169,170,173,178,184,185,186,193,196,200,204,207,210,219,221,222,228,230,239,241,247,252,256,258,266,267,273,277,278,303,304,306,308,309,311,314,315,319,328,330,332,338,346,352,360,361,364,365,368,369,373,374,380,384,385,394,395,398,400,401,404,407,409,416,418,423,427,438,440,442,444,446,447,456,457,459,461,463,465,466,470,471,472,473,474,475,476,477],although:[30,55,63,67,70,72,76,81,83,87,91,92,98,99,106,107,126,127,139,168,174,180,186,193,200,201,232,256,260,265,273,276,290,293,303,304,306,311,321,333,353,364,365,368,369,381,392,394,395,409,423,427,430,431,432,438,439,440,442,445,446,447,451,452,453,454,455,461,465,470],alti:473,altinstal:[204,468,477],altogeth:[98,99,143,440],altsep:304,altzon:[174,392],alum:438,alumni:438,alwai:[0,4,6,13,16,20,26,28,30,31,35,36,37,41,43,47,51,53,55,56,59,63,64,66,70,72,73,77,79,81,82,83,88,90,91,92,93,94,95,96,98,99,100,101,102,105,106,107,109,113,121,123,125,129,131,132,133,134,143,147,149,150,152,161,168,169,171,174,175,176,178,180,186,188,194,200,201,204,206,219,221,222,224,226,230,231,235,236,240,241,244,246,249,253,256,260,264,265,266,267,269,273,275,277,278,282,292,293,303,304,305,306,308,311,315,317,319,321,331,333,337,338,339,346,348,349,353,356,360,361,364,365,368,369,373,374,380,384,386,388,389,390,391,392,396,400,401,407,410,411,416,423,425,426,427,429,431,433,437,439,440,441,442,446,447,451,452,453,454,457,460,461,463,465,469,470,471,472,473,474,475,476,477],always_typed_act:303,amanda:469,amauri:[476,477],amaz:[95,186,472],ambigu:[8,30,60,81,96,101,123,174,244,252,262,303,309,333,439,442,443,445,446,452,470,476],ambiti:474,amd64:[63,64,373,381],amdk6:315,ame:460,america:[174,438,477],american:[93,104],amessag:197,amk:[101,104,333,473,476,477],amoeba:83,among:[103,129,168,180,186,213,219,225,273,293,345,348,373,380,392,394,396,440,446,447,467,469],amongst:[276,365],amort:308,amount:[28,30,77,81,87,96,102,126,169,178,191,221,236,241,256,282,293,299,303,306,318,321,336,338,350,353,360,366,368,373,389,391,392,401,403,409,425,427,437,451,452,454,460,471,474,476],amp:[348,433],amper:397,amperequ:397,ampersand:477,amplifi:178,amplitud:476,amsterdam:[28,83,392,438],amt:241,an_error:400,an_int:158,an_item_is_avail:391,analog:[24,33,50,56,63,64,79,88,178,265,266,293,389,403,459,472,474,475,477],analogu:[63,88,293],analysi:[28,60,63,101,126,145,147,180,182,220,237,252,262,288,322,442,444,445,455,465,475],analyst:216,analyz:[100,111,157,167,177,288,312,351,438,446,475,476,477],anand:477,anatoli:477,ancestor:[63,98,104,169,265,266,293,365,401,440,451,473],ancestri:471,anchor:[239,250,396,401,477],anchor_bgn:239,anchor_end:239,anchorag:96,anchorlist:239,ancient:[384,460,475],and_:[96,302],and_expr:[442,443],and_test:[442,443],anded:170,ander:477,andi:[469,476],andrew:[103,169,438,470,472,473,474,475],andrich:470,anecdot:88,angl:[101,134,147,150,203,222,277,332,339,403,476,477],angular:[60,301,445],ani:[1,4,5,6,7,8,9,12,16,17,19,20,21,23,24,26,28,30,32,33,34,37,38,40,45,48,49,50,51,54,55,56,58,60,64,66,67,68,69,70,71,72,73,76,77,79,80,81,88,89,90,91,93,94,95,96,98,99,100,101,102,103,104,106,107,113,114,118,123,126,127,128,132,133,136,137,139,140,142,143,145,147,148,149,150,151,152,155,158,160,161,162,163,165,167,168,169,170,171,174,175,178,180,182,183,186,188,192,197,198,199,200,201,202,204,206,210,212,214,215,216,218,219,221,222,223,225,226,230,232,234,235,236,241,244,246,249,253,256,258,260,261,263,264,265,266,267,270,272,273,277,278,281,283,287,292,293,296,297,300,302,303,304,305,306,308,309,311,314,317,318,322,327,328,332,333,334,336,337,338,339,340,342,343,345,346,348,349,351,352,353,354,356,358,360,361,364,365,368,369,370,373,374,376,380,384,385,386,388,389,390,391,392,394,396,398,399,401,403,404,407,409,410,411,413,415,416,417,418,422,423,424,425,426,427,429,431,432,433,434,435,436,437,438,439,440,441,442,445,446,447,451,452,453,454,455,457,458,460,461,465,467,469,470,471,472,473,474,475,476,477],anim:[60,230,395,401,476],anint:316,annex:[277,476],annoi:[93,101,143,167,236,265,470,476],annot:[81,181,246,264,399,418],annotate_field:125,announc:[63,83,215,464],annoy:[104,106,472,473],anod:205,anomal:388,anomali:[81,178],anonym:[1,90,112,168,212,221,266,287,365,403,439,442,452,470],anoth:[6,21,26,28,30,37,51,55,60,63,64,66,67,71,72,77,78,79,80,81,82,83,86,87,89,90,91,93,95,96,98,99,100,101,102,103,104,105,106,107,109,113,123,124,127,134,143,148,150,152,157,162,168,169,174,178,186,189,190,206,218,221,222,223,230,235,256,258,260,266,273,279,293,298,302,303,304,308,309,311,313,317,322,323,325,328,332,333,338,346,348,352,353,361,365,368,369,370,374,380,390,391,394,398,399,401,403,407,409,410,411,418,423,424,425,426,427,429,430,435,438,439,440,442,447,451,452,453,454,455,457,458,461,463,467,469,470,471,472,473,474,475,476,477],another_funct:400,another_year:174,anotherstr:316,anothervalu:426,ansi2knr:438,ansi:[37,150,168,264,392,438,470],answer:[1,62,63,81,88,91,108,147,186,266,273,280,322,341,369,396,451,453,455,457,462,464,470,474],answer_challeng:293,anthoni:[69,88,472,474,475],anti:[60,97,401],antoin:[476,477],antti:475,anydbm:[60,175,176,188,226,252,310,350,477],anymor:[88,90,102,222,260,477],anyon:[79,100,107,365,438,471,477,478],anyset:48,anyth:[4,30,36,55,60,63,66,68,72,73,76,77,79,81,83,86,87,88,91,93,96,98,101,102,104,106,107,113,117,123,127,143,152,168,169,170,174,178,186,200,245,246,256,267,293,303,309,313,324,333,340,350,358,364,369,374,376,380,386,391,401,417,429,440,442,449,451,452,454,457,460,461,467,471,472,475,476],anytim:[143,365,396],anywai:[55,72,79,81,91,107,162,168,174,222,244,247,293,407,442,453,471,472],anywher:[73,88,101,106,134,143,152,178,180,258,266,303,333,338,360,380,398,441],aodlambelk:333,aon:403,apach:[106,293,365,470],apart:[63,70,79,96,98,101,125,180,277,293,303,314,332,338,348,376,442,446,460,473,477],ape:180,aperiod:403,api:[6,8,11,14,15,17,20,30,33,37,40,48,51,52,55,56,57,60,69,72,76,78,79,82,83,87,88,89,90,93,98,99,100,102,105,106,109,113,123,138,141,151,152,167,168,169,179,183,184,192,197,206,228,236,242,243,252,256,260,265,266,267,268,271,273,275,290,291,293,295,304,306,310,311,314,332,333,334,355,360,365,368,369,370,374,380,383,388,390,391,405,407,422,423,425,427,430,431,434,441,442,444,446,447,451,456,469,470,471,472,478],api_vers:[380,461,473],apiv:3,apl:258,apo:348,apop:318,apostroph:[90,368],app:[60,89,102,106,227,267,268,396,409,423,438,476,477],appar:[77,86,89,93,95,143,424,452,455,470,474],apparatu:438,appdata:[356,476],appear:[20,36,51,52,58,60,63,79,81,87,89,90,91,93,96,98,99,100,107,109,123,125,136,142,143,150,156,157,158,167,168,169,178,180,185,186,187,191,200,219,222,225,227,230,235,244,246,253,264,266,267,268,273,290,309,322,328,331,339,360,368,369,384,389,395,396,401,409,418,423,424,426,429,432,438,439,440,442,443,445,446,447,449,452,453,458,459,460,465,471,473,475,476,477],appel:180,append:[33,50,52,63,79,81,82,83,87,88,98,99,102,107,109,123,124,126,143,149,150,152,157,168,174,175,176,178,181,182,191,193,198,200,219,222,223,225,226,234,246,248,249,256,258,265,266,267,270,273,282,290,292,293,303,311,313,314,320,330,334,350,352,356,366,368,377,380,384,386,393,398,407,409,416,423,424,427,429,435,439,440,446,451,452,453,457,460,461,463,465,470,471,473,474,475,476,477],append_const:[123,303],appendchild:[426,427,470],appendix:[60,438,456,459],appendleft:[152,474],appetit:[60,456,472],appl:[60,86,104,115,117,152,180,191,219,252,268,270,284,302,316,453,462,467,473,476,477],appleev:[60,116,252,270,271,284],applescript:[116,117,227,270],applesingl:[60,476],applet:[269,337,338,405,467],appletrawmain:476,appletrunn:476,appli:[2,5,6,16,43,45,48,55,56,63,64,70,71,72,73,77,81,83,84,90,95,96,98,106,107,109,117,123,124,125,129,132,147,150,152,161,162,168,169,170,174,178,180,182,186,195,203,206,214,221,222,230,249,256,265,273,274,281,293,303,304,309,311,322,328,332,333,335,338,342,365,368,392,393,396,398,401,406,407,409,411,425,427,429,438,439,440,442,446,447,449,451,453,457,460,461,464,465,469,470,471,472,473,474,475,476,477],applic:[28,30,41,55,56,60,63,77,78,79,80,81,82,86,88,90,94,95,96,98,99,100,101,102,104,105,106,107,108,109,110,113,116,117,123,125,126,127,128,131,141,143,149,158,160,161,167,169,174,178,180,184,186,191,192,193,194,200,201,206,215,222,223,227,235,236,241,242,243,244,252,255,256,260,264,265,266,267,268,269,270,271,273,274,275,281,284,286,290,291,293,302,303,304,305,307,308,311,317,318,322,328,333,337,343,346,351,353,354,360,364,365,368,371,372,374,380,386,389,391,394,396,401,403,406,407,409,410,411,416,418,423,426,427,429,430,431,432,433,435,436,437,438,442,445,447,450,453,454,456,457,458,461,462,463,466,468,469,470,471,472,473,474,476,477,478],application_uri:423,applicationwid:178,apply_async:[293,476],applyresult:293,appnam:[243,267],appreci:[94,435,438,451],approach:[30,60,68,72,77,78,79,81,82,88,90,91,94,96,98,99,103,104,105,106,137,143,152,178,180,186,204,237,251,277,304,317,343,361,364,365,368,390,391,393,407,429,434,440,442,451,456,462,463,470,471,475,476,477],appropri:[1,4,14,16,21,36,37,43,47,50,56,63,67,70,72,77,79,81,84,88,93,96,98,99,100,101,102,103,105,107,108,109,121,123,124,127,130,132,138,142,143,149,150,157,158,162,169,174,176,178,186,194,195,197,200,201,202,216,221,222,224,230,236,237,239,241,246,256,260,264,265,266,267,273,277,300,303,304,308,311,322,328,333,345,348,353,358,361,365,368,369,373,374,386,391,392,394,400,403,405,409,410,419,424,426,427,429,431,435,440,441,442,453,463,465,468,470,471,472,473,474,476],approv:[72,133,162,410,470,477],approxim:[34,41,82,88,139,150,152,169,178,180,186,218,222,244,293,330,368,374,388,400,403,407,442,455,457,476,477],appspot:477,appurlopen:409,apr:[89,96,472,475],april:[174,446,470,471],apt:[82,469],aqua:467,aquamac:467,arab:[150,178,215,368,470,477],arahesi:477,aranguren:476,arbcd:474,arbitrari:[4,20,28,30,32,42,45,47,48,55,60,70,76,78,79,81,87,88,90,91,96,99,101,102,104,105,107,120,123,126,131,132,143,150,151,152,161,168,171,178,185,215,222,230,232,233,235,238,240,252,254,260,265,266,273,278,293,298,304,305,306,308,309,311,321,324,333,345,346,348,349,350,353,355,356,360,361,363,368,369,374,390,392,396,403,405,407,412,413,414,426,429,434,440,441,442,451,453,456,457,470,471,472,473,474,475,476,477],arbitrarili:[58,70,90,125,142,152,266,332,368,409,442,457,474],arc:[147,277,403,476,477],arch:476,archi:429,architectur:[60,63,106,117,124,206,216,252,270,274,276,288,315,381,426,440,461,468,473,474,476],archiv:[60,64,69,70,73,107,211,252,273,289,366,462,464,470,475,476,477,478],archive_nam:352,archive_util:69,archivepath:436,arcnam:[384,435],arduou:470,area1:99,area2:99,area:[4,37,69,83,93,98,99,133,169,200,222,244,255,256,287,336,337,386,401,440,445,456,470,475,476],aregtyp:384,aren:[45,79,81,83,87,88,93,96,101,102,104,108,109,147,158,168,197,206,209,225,266,267,303,361,365,368,396,434,442,459,470,471,472,473,474,475,476,477],arena:[30,37,465,475],arepr:335,arfrev:477,arg0:304,arg1:[79,88,96,123,185,222,303,304,440,472,473,475],arg2:[79,88,96,185,222,303,440,472,473,475],arg3:[79,88],arg:[4,10,17,24,28,43,50,51,54,55,56,58,63,76,77,79,81,87,88,90,91,92,94,98,99,103,107,109,123,125,128,134,142,148,152,157,160,167,168,180,193,205,206,207,215,222,223,228,235,238,244,246,253,258,265,266,273,278,293,302,303,304,305,309,311,312,315,322,325,330,349,352,364,368,369,374,380,381,385,388,390,391,396,399,401,403,407,410,439,440,447,452,454,459,465,470,473,474,475,476,477],arg_format:82,arg_lin:123,arg_nam:369,argc:[28,30,58,76,77,82,182],argcount:[12,58,297],argdef:297,arginfo:253,arglist:[77,443],argnam:157,argpars:[60,97,120,228,252,303,462,478],argspec:253,argstr:358,argtyp:168,argu:[470,472,477],arguabl:[88,365],argument:[3,6,8,11,13,14,16,17,19,20,21,22,23,24,26,27,28,30,32,34,41,42,43,45,50,51,52,53,55,56,57,58,60,63,64,70,72,75,76,77,79,81,82,89,90,93,94,95,96,98,99,100,101,102,103,104,105,107,109,111,113,115,116,117,118,119,120,121,124,125,126,127,128,129,131,132,134,135,136,137,138,139,141,142,143,145,146,147,148,149,150,151,152,155,156,157,158,159,160,162,163,164,167,169,170,174,175,176,178,180,182,185,186,188,191,192,193,194,195,197,198,200,201,202,203,205,206,207,210,212,215,218,219,221,222,223,224,225,226,228,229,230,231,234,235,236,237,238,239,240,241,243,244,245,246,248,249,250,252,253,256,257,258,260,264,265,266,267,269,270,273,276,277,278,280,281,282,283,284,287,288,290,292,293,294,296,297,298,299,300,302,304,305,306,308,309,311,312,313,314,315,317,320,321,322,327,328,331,332,333,334,336,338,339,341,342,343,345,346,348,349,351,352,353,354,355,356,357,358,360,364,365,366,368,369,373,377,379,380,381,382,384,385,386,387,388,389,390,391,392,393,396,398,399,400,401,403,404,407,409,410,411,412,413,414,415,416,419,422,423,424,426,427,429,432,433,434,435,436,437,438,439,440,441,442,443,447,448,450,451,453,454,456,457,458,460,461,463,465,470,471,472,473,474,475,476,477],argument_default:[60,120],argument_list:[134,439,442],argumentdefaultshelpformatt:123,argumenterror:[123,168],argumentpars:[60,91,120,228,477],argumenttypeerror:123,argv:[28,30,58,60,63,64,76,77,82,95,99,120,186,191,210,228,244,293,303,304,309,323,342,361,366,380,382,407,454,459,461,462,465,473,477],argvemul:476,arial:403,aris:[30,70,90,103,106,178,256,265,266,276,311,346,404,438,442,463,472,474],arith_expr:443,arithmet:[60,95,174,206,218,222,252,277,301,302,368,380,434,440,444,446,451,452,456,462,473,474,475],arithmeticerror:[20,178,206,461],arizona:[472,473],arm:373,armin:[474,475,476,477],armor:200,arnaud:474,aros:96,around:[6,20,22,26,28,52,62,69,76,77,79,81,82,83,88,92,96,100,102,106,108,110,127,129,145,158,169,174,178,186,201,202,207,210,222,236,244,249,253,267,271,276,277,282,290,293,298,303,307,309,311,314,316,333,339,342,350,365,384,386,400,401,403,407,413,418,439,440,442,443,447,450,451,452,453,454,458,464,465,470,471,472,473,474,475,476,477],arpa:385,arr1:293,arr2:293,arr:[168,293],arrai:[3,4,6,15,26,29,47,50,55,56,58,60,76,77,79,81,87,90,104,120,140,150,163,170,173,207,222,231,236,252,256,288,293,295,298,338,368,373,387,404,418,424,434,440,450,453,463,473,474,475,476,477],arrang:[72,87,89,96,98,99,174,186,192,236,253,266,293,365,391,394,396,401],arraydesc:168,arrayobject:72,arrays:364,arraytyp:124,arriv:[20,132,162,186,293,353,361,365,392,453,470],arrow:[169,219,244,309,394,403,454],art:[72,146,147,152,186,236,339],articl:[1,96,104,106,235,273,299,403,470,471,472,473,474,475,476,477],articlefil:299,artifact:[269,306],artifici:[168,461],arvin:476,as_complex:260,as_i:215,as_integer_ratio:[368,476],as_str:[192,193,197,198,200],as_tupl:[178,476],ascend:[60,322,368,439],ascher:471,ascii:[15,60,81,93,99,101,102,104,120,131,136,150,167,168,169,193,194,198,200,201,203,221,222,224,230,235,237,243,252,260,278,283,291,295,296,311,328,331,333,349,351,364,365,369,370,371,376,384,414,429,434,438,440,445,446,452,453,457,459,460,470,472,473,474,475,476],ascii_lett:[161,369,472],ascii_lowercas:[333,369,472],ascii_uppercas:[369,472],ascrib:98,asctim:[98,99,265,266,392,471,477],asdl:[125,475],ashley_0:463,ashley_1:463,ashley_2:463,ashley_:463,asian:[150,406,474],asid:[1,102,322,384,440],asimov:333,asin:[147,277],asinh:[147,277,476],ask:[60,63,81,88,90,93,95,99,101,106,127,152,162,191,216,221,222,227,233,235,244,253,256,278,280,299,303,309,318,324,349,363,365,368,409,429,430,440,442,443,447,454,464,474,475,476,477],ask_ok:452,askfileforopen:191,askfileforsav:191,askfold:191,askpassword:191,askstr:191,askyesnocancel:191,asn:365,asnam:125,asnebc:333,aspect:[37,76,77,83,101,105,174,186,192,236,247,266,304,308,337,440,447],aspn:[105,277],assattr:157,assembl:[81,82,88,96,104,157,364,374,440,445,475],assert:[30,60,99,103,109,114,125,157,159,174,186,206,228,251,293,303,309,333,364,388,407,416,427,443,444,446,461,473,474,476],assert_:[109,407],assert_line_data:215,assert_stmt:[443,447],assertalmostequ:[109,407,477],assertcountequ:407,assertdictcontainssubset:[407,477],assertdictequ:[407,477],assertequ:[109,407,462,477],assertfals:[109,407,477],assertgreat:[407,477],assertgreaterequ:[407,477],asserti:[407,477],assertin:[407,477],assertionerror:[20,157,206,293,391,407,423,429,447,461],assertisinst:[407,477],assertisnon:[407,477],assertisnot:[407,477],assertisnotnon:[407,477],assertitemsequ:[407,477],assertless:[407,477],assertlessequ:[407,477],assertlistequ:[407,477],assertmultilineequ:[407,477],assertnotalmostequ:[109,407,477],assertnotequ:[109,407],assertnotin:[407,477],assertnotisinst:[407,477],assertnotregexpmatch:[407,477],assertrais:[109,407,462,477],assertraisesregexp:[407,477],assertregexpmatch:[407,477],assertsequenceequ:[407,477],assertsetequ:[407,477],asserttru:[109,407,477],asserttupleequ:[407,477],assign:[1,30,33,47,55,60,63,77,79,82,83,88,90,91,94,96,104,106,109,123,124,125,150,152,158,159,162,163,168,169,178,182,186,198,200,205,206,222,223,236,243,273,287,293,302,303,304,305,309,311,317,319,328,338,350,351,365,368,373,379,380,389,401,406,407,409,416,427,429,435,439,440,441,442,443,444,446,451,452,453,459,460,461,471,472,473,474,475,476,477,478],assignment_stmt:447,assist:[96,104,106,262,287,472,473,474,475,476,477],asslist:157,assnam:157,assoc:[345,469],associ:[4,11,21,23,28,38,51,52,55,58,62,63,70,77,79,87,89,90,93,98,101,102,105,106,108,113,123,126,132,134,142,143,167,169,171,178,182,186,197,200,206,213,215,230,239,241,244,253,265,281,293,296,303,304,306,308,309,311,328,355,360,368,371,377,380,384,388,391,393,394,396,401,407,409,418,419,422,423,426,429,431,432,434,435,436,438,440,441,447,449,451,453,454,464,469,477],assort:[63,186,394],asstr:192,asstupl:157,assum:[4,6,28,30,36,47,49,53,55,62,63,72,73,76,77,78,79,81,82,87,88,90,95,96,98,99,100,101,102,103,104,107,108,123,132,137,140,143,146,147,150,152,157,162,167,168,174,181,193,197,198,200,203,204,206,215,222,231,236,246,248,255,264,266,293,299,303,304,308,309,311,314,327,339,356,360,364,365,368,369,373,374,384,386,389,392,401,407,409,412,413,424,432,438,440,442,446,447,449,451,453,455,457,461,469,470,471,472,475,476],assumpt:[28,55,77,79,90,95,128,152,174,245,360,442,472,476],assur:[34,79,90,368,398,440,477],ast:[60,222,252,262,308,379,443,475],astamp:403,asterisk:[125,246,324,368,422,429,453,458],astimezon:174,astr:316,astvisitor:157,astz:174,asymmetr:150,asymmetri:[380,440],async_chat:[126,127],async_dispatch:219,asyncev:219,asynchat:[60,127,252,257,438,476],asynchron:[27,60,87,219,252,254,257,265,293,360,377,422,477],asyncor:[60,126,252,257,357,361,438,474,476],asyncresult:293,asynczip:463,at_end_lin:288,atan2:[147,277],atan:[147,277,476],atanh:[147,277,476],atend:396,atexit:[60,81,87,109,252,329,334,380,458,470,474],atheo:[380,473],atim:[142,304],atinsert:396,atle:475,atof:[16,264,369,474,475],atoi:[76,264,369],atol:369,atom:[24,60,87,225,293,294,304,330,353,368,391,443,444,477],atop:[365,475,476],atruevalu:316,atselfirst:396,atsellast:396,attach:[28,71,76,98,99,152,174,186,193,196,200,201,202,205,265,266,269,345,394,407,423,440,462,471,473,477],attack:[81,104,235,237,266,304,338,364,365,425,457,475,477],attempt:[8,26,29,30,41,52,55,88,89,90,93,97,101,104,105,106,108,114,115,116,118,123,133,148,158,162,165,169,176,178,180,186,192,202,203,205,206,216,219,221,222,236,241,244,247,253,256,260,263,264,266,267,273,291,293,304,306,311,318,325,327,328,333,334,336,338,339,343,345,352,353,356,358,359,360,361,364,365,368,370,373,380,385,388,389,391,407,409,410,413,415,417,420,423,426,431,432,433,435,436,437,440,442,444,451,454,456,457,460,461,470,471,472,473,474,475,476,477],atten:461,attent:[101,106,169,403,461,473],attitud:186,attlistdeclhandl:328,attnam:328,attr:[60,82,93,125,161,169,240,275,290,302,303,311,328,348,396,407,429,431,432,433,470,471,474],attr_nam:[43,55,472],attract:[81,273,396,476],attrdict:265,attrgett:[90,96,103,302,474,475,476],attrib:[429,475],attribut:[8,18,19,20,21,23,26,28,30,39,43,49,51,54,55,60,63,82,90,94,96,98,99,101,103,105,109,110,111,113,116,117,120,123,124,125,126,133,134,139,140,143,148,150,151,152,157,158,159,161,162,167,168,169,174,178,182,186,191,192,194,200,202,206,207,208,212,215,219,221,222,223,228,233,234,235,239,240,241,243,244,246,249,252,253,256,266,267,273,275,278,284,290,293,296,302,304,306,311,314,315,316,317,318,324,326,327,328,333,335,336,337,338,343,344,345,348,349,351,353,354,355,357,358,360,361,363,364,365,369,370,373,374,377,380,384,386,387,388,389,391,392,393,403,404,407,409,410,411,413,415,416,418,423,424,426,427,429,430,431,433,434,435,436,437,438,439,441,446,447,451,453,454,458,461,462,463,470,473,474,475,476,477,478],attribute_nam:369,attribute_nod:426,attributeerror:[20,43,51,94,133,143,168,206,222,251,266,293,311,333,368,393,426,427,440,442,447,461,470,472,477],attributenam:[8,77],attributeref:[442,447],attributesimpl:432,attributesn:[60,275,430,431],attributesnsimpl:432,attrnam:[82,157,426],attroff:169,attron:169,attrset:169,au_read:[60,286],au_writ:[60,286],audibl:[99,169],audienc:[69,72,98,445,473],audio:[60,118,142,146,193,201,252,286,347,375,376,388,405,417,422,470],audio_:377,audio_file_encoding_adpcm_g721:376,audio_file_encoding_adpcm_g722:376,audio_file_encoding_adpcm_g723_3:376,audio_file_encoding_adpcm_g723_5:376,audio_file_encoding_alaw_8:376,audio_file_encoding_doubl:376,audio_file_encoding_float:376,audio_file_encoding_linear_16:376,audio_file_encoding_linear_24:376,audio_file_encoding_linear_32:376,audio_file_encoding_linear_8:376,audio_file_encoding_mulaw_8:376,audio_file_mag:376,audio_mac:476,audio_obj:377,audiodev:[306,377,405,476],audioio:377,audioop:[60,252,286,338,475],audit:473,aug:[28,96,107,174,221,436,472,473],augassign:[125,157,443],augload:125,augment:[60,63,88,186,266,281,326,394,440,446,465,478],augmented_assignment_stmt:447,augop:447,augstor:125,augtarget:447,auguri:473,august:[104,349,475],augustu:446,aunicodevalu:316,auread:461,austin:476,australia:[392,464],austria:[364,429],auth:[221,246,267,473],auth_handl:410,authent:[60,71,106,166,221,235,246,252,265,267,296,299,318,358,362,365,409,410,434,437,472,477],authenticationerror:293,authinfo:299,authkei:293,authobject:246,author:[26,62,63,64,69,71,72,75,77,80,90,91,92,93,94,95,96,98,99,100,101,102,103,105,106,107,108,128,184,186,206,300,304,364,365,396,407,410,423,434,438,461,467,470,471,472,473,474,475,476,477],author_email:[63,64,72,75],authoris:246,authorit:[105,437],authorized_kei:352,authorizer_callback:364,authpriv:267,authreq:410,authuri:410,auto:[28,64,66,83,105,244,403,458,460,470,477],autocommit:364,autocomplet:[244,458],autocompletewindow:244,autoconf:[63,70],autodetect:[63,104,384,410,471,475],autoexec:[101,469],autoexpand:244,autogil:[60,252,268,476],autogilerror:130,autoincr:401,autojunk:180,autom:[30,60,79,87,90,100,179,221,252,299,407,450,471,477],automag:93,automat:[6,9,20,28,30,48,52,60,62,64,66,67,72,73,77,79,87,88,89,90,92,93,94,96,100,101,102,104,106,107,109,113,117,121,123,127,128,130,132,142,144,148,150,152,157,158,159,161,162,164,167,168,169,173,176,178,179,180,184,186,187,188,189,193,194,201,212,213,222,223,225,226,234,239,240,241,265,266,273,274,287,290,293,299,303,304,305,309,311,319,322,327,330,334,335,340,341,344,350,354,355,356,358,360,361,364,365,368,369,373,376,377,380,384,388,390,393,394,395,396,401,403,407,409,410,411,413,417,420,423,431,434,436,437,438,440,441,442,446,449,451,452,457,458,460,462,463,464,469,470,471,472,473,474,475,476,477],automata:101,automatrix:438,automount:28,autonom:[361,438],autorais:[419,475],autosav:244,autotool:477,auwrit:461,auxiliari:[60,99,134,192,219,257,258],auxiliary_modul:99,avail:[4,5,6,8,11,20,21,28,30,37,48,50,52,56,58,60,62,63,64,66,68,69,70,71,72,73,75,76,77,79,80,81,83,84,87,88,89,90,93,94,95,98,99,100,101,102,104,105,106,107,108,109,110,113,114,118,119,120,121,123,124,126,127,130,132,138,139,141,142,147,148,150,152,156,157,158,165,166,167,168,169,173,175,178,182,184,188,192,194,202,204,205,206,207,210,212,213,215,219,221,222,223,224,230,231,233,235,236,239,241,244,249,250,252,253,255,256,259,260,264,265,266,268,269,271,272,273,275,277,281,285,286,287,291,293,296,298,303,304,305,306,307,308,309,311,315,316,317,319,322,324,327,328,329,330,331,332,333,335,336,337,338,340,342,343,344,345,346,348,350,351,352,353,355,356,357,358,360,361,362,363,364,365,367,368,369,371,373,374,377,380,382,384,385,387,388,390,391,392,394,395,396,400,401,405,406,407,409,410,413,415,418,419,420,421,423,424,425,426,427,429,430,431,432,434,435,436,437,438,439,440,441,442,444,445,446,447,448,450,452,455,456,458,459,460,461,464,465,467,468,470,471,472,473,474,475,476,477],availmask:169,avenu:[333,438,472],averag:[81,94,104,129,236,245,293,304,322,401,445,462],avg:129,avgpp:129,avion:476,avoid:[6,16,28,37,38,55,62,72,76,77,79,81,88,90,93,96,98,100,101,102,103,104,106,111,123,124,141,150,160,163,167,168,174,178,197,204,207,225,236,237,246,253,260,268,273,277,287,293,300,303,305,311,328,333,335,352,360,364,366,368,374,377,380,384,389,393,394,407,418,422,425,426,427,433,439,440,442,446,447,451,452,453,454,458,460,463,470,472,473,474,475,476,477],awai:[10,20,28,30,72,87,96,98,102,123,161,169,174,178,186,206,222,252,303,304,305,322,332,364,368,450,451,455,463,472,473],await:[470,473],awaken:391,awar:[43,60,62,80,83,86,90,95,101,102,103,108,171,174,192,193,198,200,201,223,230,256,264,274,275,304,308,338,365,369,393,401,416,432,447,462,467,470,472,473,474],awful:95,awk:[450,470],awkward:[87,137,316],awkwardli:477,axi:[88,147,277,401],aycock:471,ayt:385,b10:94,b16decod:131,b16encod:131,b2a_base64:135,b2a_hex:[135,150],b2a_hqx:135,b2a_qp:135,b2a_uu:135,b32decod:131,b32encod:131,b64decod:131,b64encod:131,babyl:[60,295],babylmailbox:273,babylmessag:[60,295],bac:123,back:[1,4,19,24,26,29,30,36,37,55,60,62,63,78,79,81,87,88,89,91,96,99,100,101,102,109,115,123,124,132,135,143,147,148,150,158,162,167,169,174,178,182,186,192,194,197,200,207,215,222,229,230,255,256,260,266,267,276,287,291,293,300,303,305,306,309,311,333,339,350,355,360,361,364,365,377,378,380,388,392,396,397,398,403,409,411,429,433,434,435,437,439,440,446,447,451,455,458,470,471,472,473,474,475,476,477],backend:[150,169],background:[28,60,64,80,93,102,106,120,127,160,169,242,244,293,394,396,401,403,439,440,463,474],backgroundbrows:419,backgroundcolor:403,backgroundimag:403,backlog:[127,293,360],backport:[6,42,60,100,139,204,407,476],backquot:[60,157,257,397],backrefer:[101,333],backslash:[13,60,63,73,107,150,151,155,186,203,224,256,293,304,333,339,348,374,446,457,460,473,474],backslashreplac:[150,256,368,473],backslashreplace_error:150,backspac:[93,101,169,170,244,333,446,458,459],backtick:109,backtrac:441,backtrack:101,backup:[99,109,210,271,384,476],backupcount:[99,266,267,477],backward:[22,56,58,72,83,87,98,117,123,124,132,134,138,139,143,158,161,162,169,174,181,186,192,202,206,222,228,236,241,244,245,246,249,256,266,273,276,278,280,282,283,292,299,304,305,306,308,311,322,332,336,339,346,360,368,376,383,386,392,398,403,405,409,411,413,414,417,425,434,440,442,443,451,454,458,470,472,473,475,476],backward_compat:245,bacon:[123,152,180,288,368,400,404,409],baconhamegg:288,bad:[16,63,66,76,77,89,91,92,95,98,100,102,105,119,123,125,167,180,185,186,197,205,244,264,273,293,303,322,384,403,435,461,472,476],bad_gatewai:241,bad_request:241,badger:123,badli:[374,414],badmodul:288,badstatuslin:241,badzipfil:435,baffl:323,bag:[152,193,451],baggag:79,bailei:476,bak:210,bake:[167,333],balanc:[83,101,152,236,365],balloon:394,baltic:150,bam:[98,265],banana:[152,302,453,462],band:[127,215,345],bandwidth:[99,104,106,477],bank:476,banner:[127,148,149],banquet:476,bar:[24,63,66,67,72,88,90,95,98,99,101,123,148,158,162,168,169,191,219,228,249,260,265,266,293,302,303,304,305,309,314,322,333,338,344,356,384,388,396,401,407,423,435,436,442,445,470,476],bar_pars:123,bar_var:88,barber:191,bare:[63,72,95,186,303,358,447,467,475],barebon:467,barn:476,barran:476,barri:[230,470,471,472,474,475,476],bartelt:88,base16:[60,252,295,474],base1:451,base2:451,base32:[60,252,295,474],base3:451,base64:[60,104,135,150,193,194,195,198,200,201,235,252,280,283,295,331,365,434,472,474],base64_codec:150,base64seto:56,base64whitespac:56,base:[3,4,6,10,13,20,22,25,28,29,30,34,41,42,54,55,56,60,64,69,70,72,73,77,79,81,86,87,90,91,93,94,95,96,98,100,101,102,104,105,106,107,108,116,117,120,121,123,125,131,134,135,137,138,140,144,147,157,158,162,165,168,172,173,174,178,179,182,184,186,187,192,193,194,195,196,197,198,200,201,206,215,218,219,222,223,227,234,235,236,237,239,240,241,242,243,244,246,251,252,253,254,258,260,264,265,266,267,273,275,277,280,281,290,291,299,301,302,303,304,305,307,310,311,318,320,322,326,327,328,329,333,334,335,337,338,346,348,350,352,354,355,356,358,359,360,361,362,364,365,368,369,372,373,374,377,380,381,384,388,391,392,394,396,401,405,406,407,409,410,411,413,415,416,419,424,425,426,427,429,430,432,433,434,435,437,438,439,440,441,442,446,447,451,454,455,458,461,462,463,465,467,469,470,471,472,473,474,475,478],base_dir:[63,352],base_environ:423,base_nam:[63,352],basealia:88,basecgihandl:423,baseclass:[81,117,297,440],baseclassnam:451,baseconfigur:266,basecooki:161,basedir:[63,290],baseexcept:[20,206,461,475,476],basehandl:[60,254,423],basehttp:132,basehttprequesthandl:[105,132,144,354,410,423],basehttpserv:[60,105,144,252,254,293,354,410,423],baselin:393,basemanag:293,basenam:[63,64,95,186,188,303,305,352,394,396,435],basepkgnam:227,baseproxi:293,baserequesthandl:361,baserotatinghandl:[98,474],baseserv:[132,361],baseset:346,basestr:[104,109,222,451,461,473],basetestsuit:407,basetwo:223,bash:[148,458],bashdb:88,basi:[56,63,88,90,95,98,99,132,162,168,184,216,240,260,265,273,322,348,365,368,438,447,450,460,465,472,473],basic:[20,28,30,55,56,60,63,66,67,69,70,77,78,80,83,87,88,90,93,96,99,100,104,106,107,109,116,123,124,134,137,150,158,160,169,173,177,179,180,230,234,239,240,243,244,252,254,256,257,265,266,267,268,279,282,293,295,303,314,316,322,332,336,337,341,344,354,360,361,368,373,374,384,388,391,395,400,401,409,410,422,429,430,431,434,437,442,446,451,453,455,456,457,458,460,465,470,472,473,475,476,477],basicconfig:[98,99,265,474],basiccontext:178,basket:453,bass:248,bastin:[104,474],bastion:[60,252,337,473],bastionclass:133,bat:[101,388,469],batch:[89,98,101,374,450,463],batchrenam:463,batista:[474,476],batteri:[60,456],baud:93,baudrat:169,bauer:473,baxter:[69,472,474,475],baz:[95,98,99,123,158,244,260,265,266,293,304,333,407,423],bbb:258,bbbb:101,bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb:321,bbc:[83,450],bbdeioqsrstuuvvwxx3:465,bbedit:[169,467],bbhhiillqq:477,bbox:401,bcd:101,bcde:[180,477],bce:368,bclass:101,bcpp:107,bcppcompil:69,bd1a:[415,475],bdb:[60,158,177,252,309,477],bdbquit:134,bdfl:90,bdist:[64,69,70],bdist_:[64,471],bdist_dumb:[64,69,75],bdist_msi:[64,69,290],bdist_openpkg:68,bdist_packag:69,bdist_pkgtool:70,bdist_rpm:[64,66,69,70,75,470],bdist_sdux:70,bdist_wheel:62,bdist_wininst:[64,69,70,71,75,470],bean:[167,333],bear:[107,162,174,293,380],beast:[102,458],beat:[87,88],beaten:386,beauti:180,beazlei:472,becam:[81,96,111,159,392,413,446,470,476,477],becaus:[4,6,20,22,28,30,31,37,41,45,47,51,53,55,56,63,64,71,72,73,76,77,79,81,86,87,88,89,90,91,93,95,96,98,99,100,101,102,103,104,105,106,107,109,111,123,124,125,130,135,137,140,143,144,149,150,152,157,158,161,162,163,168,174,178,180,186,200,202,205,206,207,219,222,225,230,231,236,244,253,256,258,260,265,266,267,271,273,276,290,293,298,300,303,304,305,306,308,309,311,313,322,323,332,333,337,338,345,346,350,353,356,360,361,364,365,368,369,374,376,380,385,388,391,392,393,394,400,402,403,407,409,413,416,417,418,420,422,423,426,431,434,435,437,439,440,441,442,446,447,450,451,453,454,455,460,461,462,470,471,472,473,474,475,476,477],beck:[388,407,471],becom:[24,28,30,55,63,77,81,83,87,88,89,90,92,93,94,96,99,100,101,102,103,104,106,109,111,127,129,150,157,167,169,186,198,200,215,219,222,236,244,253,256,258,293,303,304,305,309,311,322,345,351,368,369,374,380,391,396,401,405,418,435,440,441,442,446,447,452,455,457,463,470,471,472,473,474,475,476,477],beda:477,bee:63,been:[1,2,4,6,12,16,19,20,28,30,37,42,50,51,55,56,63,64,65,68,72,73,75,77,79,81,82,84,86,87,88,89,90,91,93,94,96,98,99,100,101,102,104,105,106,107,109,113,115,116,117,118,119,121,123,124,126,127,128,129,130,132,133,136,138,141,142,143,144,146,148,150,153,155,157,158,160,161,162,164,168,169,171,174,175,176,178,180,181,185,186,187,188,189,191,192,198,199,200,201,203,205,206,210,212,213,215,216,217,219,221,222,223,225,226,230,231,236,239,240,241,243,244,245,247,249,250,251,253,256,258,259,264,265,266,267,268,269,270,271,273,279,280,281,287,290,291,292,293,294,297,299,303,304,305,306,308,309,311,314,316,320,322,323,328,330,332,333,334,335,336,337,338,339,341,344,348,351,353,354,355,356,358,360,361,364,365,367,368,373,374,377,380,382,384,386,387,388,390,391,392,394,395,396,401,404,405,406,407,409,410,411,412,413,416,418,419,420,424,427,429,432,434,435,436,437,438,439,440,441,442,447,448,454,455,457,458,461,462,463,470,471,472,473,474,475,476,477],beep:[169,422,459],beer:168,befor:[4,6,17,20,21,24,26,28,30,33,37,45,48,50,51,52,53,55,58,63,64,66,68,71,72,73,76,77,79,80,81,82,87,88,90,91,93,94,96,98,99,101,102,103,104,105,106,107,113,118,119,123,124,128,129,137,139,140,142,143,146,148,149,150,151,152,158,160,162,167,168,169,174,178,180,182,186,191,194,196,197,200,210,215,217,221,222,225,229,231,238,241,244,246,251,256,258,264,265,266,267,273,281,282,283,287,293,299,300,303,304,306,309,311,314,318,321,322,327,328,333,334,339,342,343,345,346,351,352,353,355,356,358,360,361,363,364,365,368,369,370,371,373,374,379,380,384,385,388,389,390,391,392,394,401,403,407,409,410,416,418,423,426,427,428,430,431,432,435,438,439,440,441,442,446,447,449,451,452,453,454,457,459,460,461,464,465,470,471,472,473,474,475,476,477],beforehand:243,beg:169,began:[83,104,162,265,470,471],begidx:148,begin:[16,30,51,63,68,77,79,81,82,87,88,89,90,96,99,100,101,102,106,107,118,123,133,138,140,142,143,148,157,158,169,170,174,175,178,180,186,197,200,203,207,212,215,221,222,232,238,239,244,249,253,255,260,273,287,293,299,304,305,313,314,328,333,334,338,339,342,356,358,364,365,368,369,373,376,380,384,385,386,389,393,396,398,401,410,417,429,431,432,439,440,441,442,445,446,447,449,450,451,452,453,454,457,458,460,461,464,465,472,475,476,477],begin_fil:403,begin_i:[93,169],begin_poli:403,begin_x:[93,169],beginn:[83,86,351],begun:[391,473,474],behalf:353,behav:[16,20,55,56,88,91,92,99,101,124,138,156,168,176,178,222,223,226,273,287,320,358,361,365,368,369,380,382,386,389,396,407,440,442,449,451,470,471,472,473,474,475,476,477],behavior:[1,16,19,20,30,37,60,71,77,79,81,82,88,90,92,93,94,98,99,102,114,123,135,144,149,157,158,165,167,168,169,173,178,180,186,201,206,210,222,224,240,241,253,258,260,264,265,267,273,276,277,281,293,296,303,304,309,311,314,328,344,345,346,351,360,361,365,368,369,373,374,380,388,391,392,396,400,401,407,409,410,411,412,413,416,423,426,429,440,442,446,447,451,454,460,465,473,474,475,476,477],behaviour:[28,29,30,72,73,87,88,90,91,96,98,99,101,107,162,184,185,207,216,222,237,256,264,265,266,267,271,293,303,304,314,333,334,338,353,361,365,380,389,403,409,432,434,440,442,465,469,470,471,472,473,474,475,476,477],behind:[63,84,92,94,106,107,127,168,186,343,440,451,457,471,474],being:[6,15,21,24,28,29,30,33,38,55,56,58,62,63,64,71,72,77,79,81,83,87,88,89,93,94,96,98,99,100,101,102,103,104,105,106,107,108,123,124,126,140,150,152,156,157,160,167,169,174,182,186,189,190,194,196,208,210,215,222,223,225,230,236,244,246,249,253,256,258,259,260,264,265,266,267,273,280,281,283,287,292,293,303,304,306,308,309,311,314,315,317,320,321,322,323,326,328,332,333,334,337,342,345,346,352,353,361,364,365,368,369,373,380,383,384,386,388,389,391,392,393,396,401,407,410,418,423,426,430,431,433,438,439,440,442,445,447,450,451,454,455,460,461,463,470,471,472,473,474,475,476,477],bel:[170,446],belchenko:477,believ:[81,90,96,102,236,303,447,473],bell:[169,170,269,446,475],belmont:474,belong:[28,37,67,70,77,88,107,134,162,186,219,243,274,290,303,328,361,368,401,416,426,432,439,451,452,477],belopolski:[476,477],below:[4,20,21,26,28,30,48,52,55,58,72,75,77,79,94,96,98,99,104,107,115,118,119,123,124,125,126,134,138,142,144,147,150,157,158,162,163,164,167,169,171,174,178,182,186,187,191,194,206,212,213,215,218,219,221,222,225,230,233,236,240,241,243,244,246,248,249,252,256,264,265,266,267,273,276,280,281,291,293,303,304,305,306,308,309,311,320,324,328,330,332,333,334,335,336,338,342,345,351,352,353,354,356,358,361,363,365,366,368,369,371,374,377,380,382,383,384,385,388,389,390,391,392,396,399,401,403,407,409,410,416,422,429,430,434,437,438,439,440,442,446,447,451,452,454,455,470,471,473,475,476,477],belowmous:212,ben:[471,475],benchmark:[238,293,322,392,465,470,471,473,474,475,477],benchtim:238,bend:474,beneath:[109,429],benefici:[88,99],benefit:[62,79,81,88,96,100,103,106,108,178,184,222,265,266,311,388,401,416,418,423,440,451,472,473,474,477],benevol:[90,470],bengt:476,beni:474,benign:162,benjamin:[92,476,477],bent:101,beo:360,beopen:[60,61],bereft:452,berkelei:[60,83,102,252,310,396,405,467],berkeleydb:[87,473,476,477],bernat:365,bernstein:476,bertogli:476,besid:[71,152,212,219,243,256,401,404,446,447,452,460,469],best:[26,30,48,60,64,72,81,83,87,90,92,93,95,96,98,100,106,129,142,143,174,178,180,186,192,193,194,221,222,230,236,241,249,257,265,293,303,315,321,322,360,364,380,384,393,394,396,403,419,434,447,450,452,453,455,462,467,470,474,475],bestreads:142,bet:77,beta:[72,111,332,380,470,476],betavari:332,bethard:[475,477],better:[30,63,64,72,75,76,77,79,81,83,87,88,93,95,96,100,101,102,104,106,108,123,129,137,138,151,168,180,186,207,216,225,228,231,236,258,264,273,293,303,304,308,318,320,322,345,346,364,365,374,384,391,392,401,403,407,412,414,429,437,440,451,452,454,455,457,461,470,472,473,474,475,476,477],betti:434,between:[14,28,29,30,33,34,37,47,51,55,60,63,64,66,69,76,77,78,79,81,82,83,87,90,92,93,95,96,98,101,102,103,104,106,107,113,120,123,125,129,139,140,150,152,158,163,168,169,174,178,182,186,191,192,194,200,202,208,210,215,219,222,230,236,240,244,252,253,256,258,259,264,265,266,269,270,276,277,281,286,287,295,300,302,304,306,308,309,311,315,322,330,332,333,334,348,353,356,360,361,362,363,364,365,368,373,376,378,380,385,386,388,389,391,392,393,394,396,397,398,401,403,407,409,416,417,423,426,427,429,433,434,437,438,440,442,445,447,451,452,453,454,455,457,460,461,462,465,470,472,473,474,475,476,477,478],beverag:98,bewar:[206,218,260,293,350,365,462],beyond:[1,28,55,60,72,78,91,93,98,101,113,120,139,152,178,253,260,266,273,291,304,333,365,368,405,445,452,467,471],bf_getcharbuff:55,bf_getreadbuf:150,bf_getreadbuff:55,bf_getsegcount:55,bf_getwritebuff:55,bfoo:333,bgcolor:403,bgenloc:476,bgn_group:212,bgnline:231,bgpic:403,bhi:180,bia:[129,322],bias:[200,473],bick:[96,423],bidirect:[104,154,256,293,371,406,470],big5:[150,474],big5hksc:[150,474],big:[56,72,77,87,96,99,104,106,113,119,146,150,168,169,182,230,236,245,267,306,311,373,376,380,415,445,463,472,473,474,477],bigcharset:472,bigendian:146,bigendianstructur:168,bigendianunion:168,bigger:[106,245,384],biggest:[83,93,100],bigobject:260,biject:28,bill:[157,368,457,470,476],billi:471,billion:[101,425],bin:[28,30,60,72,76,81,82,87,96,99,104,105,106,107,143,144,155,181,193,221,222,257,263,303,304,311,313,341,368,369,409,410,449,459,461,462,467,468,473,474,475,476,477],binari:[36,37,41,55,56,60,64,69,70,72,75,78,79,81,82,83,90,92,95,99,106,107,113,120,124,129,131,136,138,150,168,173,178,182,193,195,207,218,221,222,227,230,234,235,236,237,243,246,249,252,253,254,264,266,267,273,276,278,290,291,295,303,304,311,314,315,316,317,331,349,354,360,368,369,372,380,381,386,390,396,409,414,418,437,438,440,444,446,447,450,453,455,456,457,465,467,468,470,473,474,475,476,477],binary32:373,binary64:373,binary_add:182,binary_and:182,binary_divid:182,binary_floor_divid:182,binary_form:365,binary_lshift:182,binary_modulo:182,binary_multipli:182,binary_or:182,binary_pow:182,binary_rshift:182,binary_subscr:182,binary_subtract:182,binary_true_divid:182,binary_xor:182,binaryfunc:55,binascii:[60,131,136,150,235,252,295,338,414,438,477],bind:[12,51,60,81,88,90,94,95,99,102,127,163,169,185,186,222,230,231,244,253,264,266,275,297,307,357,360,361,365,379,394,395,401,403,425,439,440,442,444,445,447,451,456,467,470,471,472,474,475,476],bind_and_activ:[187,355,361,476],bind_textdomain_codeset:[230,264,474],bindigit:446,bindsocket:365,bindtag:401,bindtextdomain:[230,264],binhex4:[60,135,252,295],binhex:[60,135,252,295],bininteg:446,binop:[125,476],binutil:107,biondi:475,bioreason:438,bird:104,birmingham:469,birthdai:462,bisect:[60,173,252,463,474],bisect_left:137,bisect_right:137,bit:[3,4,6,19,24,28,30,33,34,35,36,42,43,47,48,49,50,51,53,54,55,56,58,60,63,64,72,77,79,81,84,88,89,91,92,93,96,99,101,102,104,106,115,118,120,129,135,141,142,145,146,147,150,161,162,167,169,170,173,175,178,186,193,194,198,207,208,222,225,230,243,245,268,269,271,276,277,278,283,294,298,300,303,304,306,314,315,319,328,332,333,345,349,352,359,360,365,366,368,370,373,374,376,380,382,384,386,393,396,401,414,415,421,426,434,435,437,440,442,446,451,452,455,457,460,465,470,471,472,473,474,475,476,477],bit_length:[368,477],bitand:[125,157],bitbucket:[62,108],bite:[88,101,303],bitfield:[51,111,222],bitmap:[64,72,248,253,290,345,394,396,401],bitmapimag:396,bitmask:[55,186,306,345],bitor:[125,157],bits_per_digit:[380,477],bits_per_sampl:359,bitwis:[41,60,79,93,96,101,169,170,186,207,222,291,302,304,333,422,440,444,473,476,477],bitxor:[125,157],bjorn:475,bkgd:169,bkgdset:169,black:[93,137,169,244,245,339,401,403,463,473,474],blackbox:388,blacklist:162,blah:[67,104,303,396],blai:475,blake:[96,365],bland:[303,475,476],blank:[60,63,66,87,88,96,123,126,132,143,169,178,180,186,197,200,202,215,241,244,266,309,339,354,356,364,365,368,403,411,423,429,447,448,452,457,460,474],blanklin:[83,186,215,474],bleedin:452,blend:157,bletch:356,blib:107,blindli:100,blink:[93,169],blksize:[256,423],blktype:384,blo:180,bloat:101,blob:[364,365],block:[4,6,8,26,28,30,37,48,55,60,70,77,79,80,81,90,92,93,99,101,104,105,109,113,119,127,134,135,142,160,162,168,169,170,178,180,182,186,189,190,192,196,202,205,207,221,222,235,241,244,249,253,256,257,258,259,280,291,293,304,306,317,320,327,330,336,337,345,349,352,353,358,360,363,364,366,367,368,374,377,379,380,384,385,388,391,407,409,410,419,422,429,432,439,440,441,442,447,452,457,460,462,471,472,473,475,476,477],block_siz:235,blocked_domain:162,blockingioerror:256,blocksiz:[142,221,304,349,384],blog:[106,475],blow:[63,99,143,303],blown:[104,472],blowup:425,blue:[77,93,101,103,137,152,153,154,169,231,368,396,401,403,418,452,453,463,473,474],blur:[186,247],blurri:[90,247],bmp:[56,64,150,248,396,446],bnf:[442,445,471],bnl:438,boa:88,board:[96,106,169,405,472,473],bob:[293,467,475,476,477],bobsavag:467,boddi:[87,469],bodi:[63,81,87,88,90,105,106,109,125,131,132,157,160,174,182,193,194,197,200,202,222,240,241,246,273,274,282,299,331,339,353,368,388,410,423,429,439,440,441,442,447,452,460,474,475,476],body_enc:194,body_encod:194,body_line_iter:[192,199],boehm:81,boer:83,bogu:[200,435,477],boil:106,boilerpl:[77,300,388],bold:[93,169,215,396],boldfac:[93,476],bolen:[470,472],bolton:477,bom:[56,60,104,106,260,372],bom_b:150,bom_l:150,bom_utf16:150,bom_utf16_b:150,bom_utf16_l:150,bom_utf32:150,bom_utf32_b:150,bom_utf32_l:150,bom_utf8:150,bomb:425,bone:467,bonu:471,book:[82,96,100,101,106,140,147,174,222,270,273,307,333,364,388,395,396,456,464],bookkeep:[28,169,332],bookmark:474,bookstor:83,bool:[93,117,125,159,168,222,258,260,300,302,368,373,380,404,407,412,434,440,451,461,473,476],booleantyp:404,booleanvar:396,boolop:125,boom:313,boost:[82,474],boot:[181,269],bootstrap:[60,108,183,252,461],border:[93,169,396,401,411],bordertyp:212,bore:[79,255,452,477],borland:[69,80,89,472],borlandccompil:63,borrow:[3,4,9,19,20,21,23,26,28,30,33,38,39,46,47,52,53,59,77,81,96,106,139,205,452,472,473,474],borzenkov:476,bosch:470,boss:364,botfram:134,both:[4,6,14,16,20,21,28,30,34,43,48,50,55,56,62,63,64,70,71,72,76,77,78,79,80,81,84,88,90,91,92,94,96,98,99,100,101,102,103,104,106,107,108,111,113,123,127,129,131,136,140,141,142,143,147,150,151,152,161,162,167,168,169,174,178,180,182,184,186,191,192,193,194,198,200,201,202,204,207,208,214,218,219,222,230,231,233,237,238,244,249,253,256,265,277,283,284,287,290,291,293,298,300,303,304,305,306,307,308,309,311,314,315,317,318,322,332,333,334,336,338,339,342,346,348,350,352,353,356,357,360,361,364,365,368,369,370,373,377,380,381,387,389,391,393,396,399,401,403,407,409,410,411,413,416,418,423,427,429,433,434,438,439,440,441,442,446,447,448,451,452,453,457,460,461,462,463,465,468,469,470,471,472,473,474,475,476,477],bother:[88,93,99,100,104,293,442,471,472],bottl:[168,476],bottleneck:177,bottom:[72,77,81,87,96,168,169,171,219,247,256,304,309,365,396,401,403,440,446,450,458,470,472,473],bottom_panel:171,bottommost:[219,451],boudewijn:307,bounc:[273,470],bound:[12,33,37,38,47,49,51,53,81,84,88,90,94,98,99,101,102,106,127,128,139,150,152,157,160,180,182,206,222,223,230,246,253,266,293,297,302,332,333,348,351,355,360,365,368,379,380,391,393,394,396,401,409,418,438,439,440,441,442,447,451,454,458,460,461,470,472,473,475,476,477],boundari:[28,101,137,146,174,186,194,196,200,201,245,273,280,282,292,293,333,368,373,388,446,452,476],boundaryerror:196,boundedsemaphor:[293,391],boundless:440,bourn:[83,313],box:[1,83,93,99,106,169,191,212,247,273,394,396,401,442,458,459],boxcar:434,boxtyp:212,bpbynumb:134,bpl:82,bplist:134,bpnumber:309,bpo:[92,293,475,476,477],bpython:458,brace:[28,81,90,290,368,369,415,442,446,453,463],bracket:[4,28,81,90,96,99,101,104,134,203,214,222,232,240,273,309,339,348,368,406,426,429,440,442,445,446,447,450,451,452,453,457,460,475,476,477],brain:[102,474],bram:[446,472],branch:[60,147,182,315,333,380,388,394,451,470,475,476],brand:[48,50,53,77,318],brandl:[475,476,477],brave:453,breach:438,breadth:[368,403,451,463],breadth_first_search:463,break_anywher:134,break_her:134,break_long_word:389,break_loop:182,break_on_hyphen:389,break_stmt:[443,447],breakag:[446,470,471,473],breakdown:[177,178],breaker:236,breakout:169,breakpoint:[82,126,134,137,177,244,269,309,475],bremmer:472,brent:396,brett:[100,322,473,474,475,476,477],breviti:[30,79,303,452],brew:101,brian:[445,470,473,474,476,477],brian_1979:435,bridg:[84,106],brief:[60,83,105,107,123,186,192,222,223,240,266,303,322,333,336,399,438,453,456,470,472,474,475],briefli:[80,106,178,475],brigg:472,bright:93,bright_side_of_death:400,bring:[79,106,152,174,244,258,327,369,394],british:93,brittl:100,brk:385,broad:[96,106,303,472,475],broadcast:360,broadli:[174,477],broccoli:364,broken:[28,71,72,99,102,104,109,180,202,205,215,232,240,253,264,293,304,305,318,348,365,368,380,389,407,411,427,446,475],broomstick:186,brought:[91,102,401,473],brouwer:476,brown:[403,476],brows:[93,105,255,327,401,452,464,476],browser:[60,88,89,96,102,104,105,106,126,143,145,161,180,212,215,244,252,254,262,274,322,327,337,338,409,410,411,451,463,470,471,473,474,475,476],browsercontrol:470,broytmann:475,brun:473,brute:235,bruynoogh:476,bsd:[60,87,93,102,121,169,176,207,252,310,336,345,350,353,360,366,374,392,405,438,449,470,472,476],bsddb185:[138,405,473],bsddb3:473,bsddb:[60,83,121,175,188,252,258,310,350,418,440,473,476,477],bsddbiter:258,bsddbobject:138,bsddbshelf:350,bstate:169,btflag:138,btn:[401,403],btopen:[138,350],btree:[60,310],bucket:440,bud:[200,423],buddi:451,buf1:37,buf2:37,buf3:37,buf:[6,22,37,157,207,338,384,475],buf_len:[16,474],buff:240,buffer:[2,4,7,15,16,22,27,28,36,37,44,50,56,58,60,63,64,79,87,90,93,98,102,104,109,120,123,124,126,127,139,141,143,149,150,168,169,205,206,207,212,215,222,231,234,235,239,240,252,267,271,276,282,287,291,293,304,306,317,328,339,345,348,351,352,360,362,364,369,370,372,373,374,377,384,385,391,404,407,410,413,423,424,429,430,437,451,453,458,460,461,465,472,473,474,475,477,478],buffer_info:124,buffer_len:42,buffer_length:4,buffer_s:[127,256,328,476],buffer_text:[328,473],buffer_us:328,bufferediobas:[256,396,476,477],bufferedrandom:[256,476],bufferedread:[256,476,477],bufferedrwpair:[256,476],bufferedwrit:[256,476],buffererror:[6,20,206,461],bufferingformatt:98,bufferinghandl:267,bufferobject:6,buffertooshort:293,buffertyp:[6,404],buflen:360,bufsiz:[37,77,123,210,271,304,306,315,317,320,338,360,374,384,386,427,428,437,474],bug:[0,30,60,72,76,77,81,82,87,89,91,96,99,100,104,143,162,197,222,238,241,273,311,315,322,365,388,391,395,439,451,455,470,471,472,473,474,475,476,477],bugfix:[83,91,100,380,470,471,472,473,475,476,477],buggi:[93,102,470,472],bugless:95,bui:[84,364,365,475],build:[27,28,48,50,51,56,57,60,62,64,65,66,69,70,71,72,73,78,79,81,82,84,87,88,89,90,94,102,103,105,106,108,124,126,127,129,132,137,149,150,152,168,174,176,178,180,183,186,201,219,227,236,252,258,275,277,291,303,304,308,315,328,332,345,346,356,360,361,364,365,368,370,380,381,396,405,407,409,425,426,438,453,462,465,466,467,469,470,472,478],build_class:182,build_clib:69,build_ext:[66,69,72,107],build_list:182,build_map:182,build_open:[105,162,410],build_pi:[66,68,69],build_requir:64,build_script:69,build_set:182,build_slic:182,build_temp:63,build_tupl:182,buildappl:405,buildapplet:60,buildbot:299,buildcmd:68,builddat:315,builder:[68,88,107,426,427,429],buildno:315,buildrequir:64,buildtool:[60,476],built:[6,10,15,18,20,21,26,30,32,41,43,50,51,54,55,60,62,63,66,69,70,71,72,73,75,77,78,79,80,81,82,83,87,88,90,94,95,98,99,100,103,104,105,106,107,108,109,111,113,114,115,116,119,121,123,124,125,143,147,149,150,151,152,157,158,169,170,173,178,180,182,194,196,198,201,203,208,211,212,216,224,225,230,236,244,249,251,252,253,255,256,258,264,269,277,281,293,300,302,303,304,305,307,308,309,311,314,320,321,322,327,328,329,334,335,337,338,360,364,365,369,370,372,373,374,380,381,388,390,396,398,401,403,407,409,413,416,418,426,427,431,434,436,438,439,440,441,442,444,445,446,447,448,450,451,452,453,454,455,457,460,461,462,463,465,467,469,471,472,473,475,476,477,478],builtin:[28,46,60,88,94,95,103,125,222,230,244,252,253,266,314,322,329,356,441,476],builtin_module_nam:[87,380,447,461],builtinfunctiontyp:404,builtinimport:251,builtinmethodtyp:404,bulgarian:150,bulk:[77,107,178,255],bullet:[169,191,215],bulletin:106,bulletproof:95,bunch:[63,72,193,202,303,450,470,471,472,473,476],bundl:[60,64,88,106,108,197,202,204,221,227,269,365,395,410,451,466,467,473,477],bundlebuild:476,burden:[77,477],bureaucraci:63,burger:333,bus:113,busi:[28,72,88,102,205,267,361,396,422,431,438,452],businesscategori:365,but1:212,but2:212,but3:212,butter:364,button:[89,142,143,169,191,212,219,290,394,396,401,403,438,469],button_alt:169,button_ctrl:169,button_shift:169,buttonbox:394,buttonn_click:169,buttonn_double_click:169,buttonn_press:169,buttonn_releas:169,buttonn_triple_click:169,bword:101,bye:[246,299,403],byelorussian:150,bypass:[185,222,304,365,369,440],byref:[168,476],byte_compil:63,bytearrai:[7,60,90,104,222,252,256,365,369,372,413,440,453,460,461,465,476,477],bytecod:[12,26,28,30,58,60,63,64,82,87,88,89,90,96,101,222,252,253,262,308,325,342,379,380,440,461,465,470,471,472,473,474,475,476,477],bytedesign:403,bytefil:432,byteord:[56,373,380,461],bytes_l:415,bytes_recd:102,bytes_warn:380,bytesio:[158,256,476],bytesobject:92,bytesourc:182,bytesperpixel:259,bytestr:[150,364,368,429,476],byteswap:124,byteswarn:[20,206,416,461],bz2:[60,63,73,122,150,168,210,252,352,384,462,473,477],bz2_codec:150,bz2compressor:139,bz2decompressor:139,bz2file:[139,384,477],bzip2:[60,63,64,73,122,210,252,352,384],bzr:73,bztar:[73,352],c0a80001:369,c89:476,c99:[147,168,277,368,373,380,476],c_api_object:77,c_bool:[168,476],c_buffer:168,c_builtin:249,c_byte:168,c_byte_array_4:168,c_call:[134,380],c_char:[168,293],c_char_p:[168,475],c_doubl:[168,293,475],c_except:[134,380],c_extens:[249,314,338],c_float:[168,475],c_int16:168,c_int32:168,c_int64:168,c_int8:168,c_int:[168,293,475],c_long:168,c_long_array_10:168,c_longdoubl:168,c_longlong:168,c_return:[134,380],c_s:168,c_short:[168,293],c_size_t:168,c_ssize_t:168,c_string:168,c_ubyt:168,c_uint16:168,c_uint32:168,c_uint64:168,c_uint8:168,c_uint:168,c_ulong:168,c_ulonglong:168,c_ushort:168,c_void_p:168,c_warn:388,c_wchar:168,c_wchar_p:168,ca_cert:365,caaat:101,cab:[60,421,475],cabinet:290,cabl:121,cabnam:290,cacert:365,cach:[26,37,54,60,77,83,87,88,90,98,101,105,106,121,150,156,168,180,211,213,222,230,249,252,263,265,293,314,325,333,350,364,365,368,380,388,407,409,410,418,447,463,471,473,475,476,477],cached_stat:364,cacheftphandl:[60,254],caches:138,cad:369,cadata:365,caddi:142,cadefault:410,caesar:150,cafil:[365,410,477],caissuer:365,cake:102,cal:[109,140,341,409],calc_item:473,calcsiz:[222,373],calcul:[30,50,52,55,56,60,77,83,88,89,91,94,95,96,103,123,140,152,157,169,174,178,193,194,201,216,219,222,277,293,306,320,353,369,373,377,379,382,392,393,403,440,442,446,450,456,461,463,472,475,476],calculate_numb:95,calculate_someth:178,calculatestar:293,calderon:477,calendar:[60,173,174,252,392,462,470,473],calendr:[140,174],calibr:[60,177],california:[365,438],call:[3,4,6,8,10,11,12,13,14,16,19,20,21,22,24,25,26,28,30,32,37,38,41,43,45,47,50,51,52,53,54,55,56,58,59,60,62,63,64,70,71,72,73,75,76,78,79,80,84,87,89,90,91,92,93,94,95,98,99,101,102,103,104,105,106,107,108,109,113,114,115,118,120,123,124,125,126,127,128,129,132,133,134,137,138,139,141,142,143,146,148,149,150,151,152,156,157,158,159,160,162,163,164,167,169,171,174,178,180,181,182,186,187,188,191,192,194,196,197,198,200,201,202,205,206,208,210,212,213,215,216,219,221,222,223,225,229,230,231,234,235,236,237,238,239,240,241,244,246,248,249,252,253,256,258,259,260,264,265,266,267,270,271,273,276,277,278,281,283,284,287,290,291,292,293,294,297,299,300,302,304,305,306,308,309,311,314,317,318,320,321,322,323,324,328,330,332,333,334,335,336,337,338,339,340,343,345,346,348,349,350,351,352,353,354,355,356,358,360,361,364,365,366,368,369,370,373,374,376,377,380,381,382,383,385,386,387,388,389,390,391,392,393,394,396,398,399,400,401,403,404,406,407,408,409,410,413,414,415,416,417,418,419,422,423,424,426,427,428,429,430,431,432,434,435,436,437,439,440,441,446,447,450,451,452,453,454,457,458,459,460,461,462,463,464,465,469,470,471,472,473,474,475,476,477],call_funct:182,call_function_kw:182,call_function_var:182,call_function_var_kw:182,call_profil:28,call_trac:[380,461],callabl:[28,32,38,43,51,55,59,60,76,77,88,90,93,96,99,101,114,123,152,164,168,169,182,201,202,219,221,222,238,246,252,266,273,283,293,297,301,302,303,310,311,328,343,352,353,374,380,386,391,393,398,407,409,413,418,423,439,442,456,461,471,472,473,474,475,476,477],callable_object:43,callableproxytyp:418,callback:[4,8,11,13,24,28,55,59,60,77,79,84,95,120,123,130,141,142,212,219,221,284,290,293,322,328,334,364,365,366,385,396,401,418,431,463,475,476,478],callback_:123,callback_arg:303,callback_kwarg:303,callbyref:88,calle:[88,157,219,399,452],calledprocesserror:[374,477],caller:[4,6,16,20,21,26,28,29,30,31,39,50,55,56,77,79,88,90,94,95,96,113,134,149,150,168,182,221,249,253,256,265,302,304,308,322,358,360,364,365,380,386,391,399,401,407,409,414,416,417,419,434,440,441,442,447,451,452,454,471,472,473,474,475,476,477],callfunc:157,calloc:37,callsomefunct:28,callstat:461,calltip:[60,395],caltech:438,calvin:364,cambridgeincolour:154,came:[86,98,100,101,186,198,293,449,454,471,472,473,474,475],camel:476,camelcas:[391,452],cameron:87,cammin:475,can:[1,4,6,8,11,12,13,15,16,20,21,23,24,26,28,29,30,31,32,34,36,39,41,45,47,48,51,52,53,55,56,58,59,60,62,63,64,66,67,68,70,71,72,73,75,76,77,78,79,80,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,110,111,113,114,116,118,119,121,123,124,125,126,127,128,129,131,132,134,135,136,137,138,139,140,141,142,143,144,145,146,147,149,150,151,152,154,155,156,157,158,159,160,161,162,163,164,167,168,169,170,171,173,174,175,176,178,179,180,181,182,183,184,186,187,191,192,193,194,196,198,200,201,202,203,204,205,206,207,210,212,214,215,216,217,218,219,221,222,223,225,226,227,228,230,232,234,235,236,237,238,239,240,241,243,244,246,247,248,249,251,253,255,256,257,258,259,260,264,265,266,267,269,270,271,272,273,274,276,277,278,279,281,282,283,284,287,288,290,291,292,293,297,299,300,302,303,304,305,306,308,309,310,312,313,314,316,317,318,319,320,321,322,325,326,327,328,330,332,333,334,335,336,337,338,339,340,341,343,345,346,348,349,350,351,352,353,354,355,356,357,358,360,361,364,365,366,367,368,369,370,371,373,374,376,377,379,380,381,382,384,385,386,387,388,389,390,391,392,393,394,396,398,399,400,401,403,405,406,407,409,410,411,412,413,414,416,417,418,419,420,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,463,464,465,467,468,469,470,471,472,473,474,475,476,477],can_change_color:[93,169],can_fetch:341,canadian:[93,150],cancel:[30,64,129,143,153,169,170,191,212,290,328,343,353,391,394,401,439,449],cancel_join_thread:293,cancelbuttonlabel:191,candid:[83,94,111,230,380,475,476,477],canin:451,caniusepython3:100,cannon:[100,473,474,475,476,477],cannot:[6,28,30,33,34,43,47,50,55,58,59,64,72,76,77,79,81,88,90,91,93,96,98,100,103,105,106,109,113,114,116,124,130,132,139,143,144,150,152,158,159,168,169,174,178,186,198,205,206,207,210,212,216,221,222,224,225,230,233,236,244,249,253,256,264,265,266,267,273,277,281,283,287,291,293,304,306,308,309,311,313,314,315,321,322,324,328,332,333,336,337,345,346,350,352,359,360,361,363,364,365,368,369,370,374,377,380,384,386,388,391,392,396,409,410,418,422,426,427,429,431,432,434,435,437,438,439,440,441,442,446,447,451,452,453,454,455,457,460,463,465,469,472,473,475,476,477],cannotsendhead:241,cannotsendrequest:241,canon:[63,87,88,90,134,178,194,259,303,305,360,371,406,442,477],canonic:339,canonnam:360,canva:[396,403,476],canvas:403,canvasheight:403,canvaswidth:403,canvheight:403,canvwidth:403,cap:274,capabl:[56,60,64,79,90,93,96,99,101,105,107,108,125,127,169,178,186,236,246,252,254,256,274,291,303,319,321,334,338,339,364,377,394,411,429,431,458,462,472,473,474,475],capac:[99,169,267,391,475,477],capath:[365,410],capi:477,capit:[104,107,178,269,368,369,406,442,451,452,470],capnam:169,capsul:[11,15,60,77,96],capsulethunk:92,caption:168,captur:[60,93,96,125,174,186,265,304,317,332,333,369,374,383,388,416,474],captured_stdout:388,capturestderr:[87,317,374],capturewarn:[265,416],capword:369,car:88,carbon:[60,115,116,191,268,269,476],carbonev:[60,268],carbonevt:[60,268],card:[232,306,333,441,447],cardin:[346,368],care:[28,30,55,58,60,63,70,72,73,77,79,87,88,94,98,99,100,101,104,105,106,123,125,134,152,168,174,178,186,189,190,200,215,219,225,230,254,258,265,266,269,273,293,297,300,303,311,322,328,332,338,353,357,368,370,374,380,384,407,424,427,429,451,455,457,459,470,474,475,476,477],carefulli:[15,20,45,58,79,88,143,311,317,322,333,338,350,465,474,475,476,477],carel:472,caret:[169,170,186,333,400],carl:[476,477],carlson:476,carneiro:474,carri:[63,93,98,104,150,178,216,226,265,277,293,303,308,332,407,426,441,446,453,475,476,477],carriag:[101,106,136,167,170,202,256,333,351,368,389,423,434,446,473,475],cartesian:[81,147,258,476],cascad:140,casefold:131,cast:[6,29,37,51,77,79,81,168,178,373],casual:455,cat:[88,99,101,152,155,230,298,374,452,462],catalog:[60,72,142,242,470,471,473],catalogu:471,catch_warn:[388,416,476],catchbreak:407,categor:[303,416,442],categori:[27,60,63,70,72,87,90,98,104,206,264,267,302,329,368,406,446,465,470,471,475,476],cater:[99,186,266,267],cathedr:438,caught:[20,87,88,95,145,149,160,206,314,318,340,352,364,388,390,392,396,407,412,430,436,440,471,476],caus:[4,6,15,16,20,28,30,37,41,45,50,55,56,58,68,71,72,77,79,80,81,82,84,87,88,89,95,98,99,101,104,105,106,109,112,113,123,126,134,143,145,148,150,151,158,161,163,167,168,169,178,180,182,185,186,191,205,206,217,219,222,225,226,227,228,231,240,241,244,245,246,253,256,260,264,265,267,273,276,277,281,282,291,292,293,304,308,309,314,315,321,322,327,328,333,338,345,348,350,353,356,360,365,368,369,370,380,382,386,389,390,391,393,398,401,407,409,410,416,418,426,431,434,435,438,439,440,441,442,447,449,451,452,454,457,459,461,463,465,469,470,471,472,473,474,475,476,477],caution:[77,88,303,304,311,418,429,454,475],cautionari:474,cautiou:[123,273],caveat:[60,222,242,322,390,409,440,447,468],caviti:401,cazabon:477,cb_type:365,cba:333,cbreak:[93,169,402],cbresult:79,cbs:[346,368],cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc:235,ccbench:477,ccc:401,cccccccccccccccccccc:321,ccitt:[135,376],ccompil:69,ccp:475,ccs:203,cdata:[328,348,426,432],cdata_section_nod:426,cdatasect:[60,275,427],cddb:476,cdecl:168,cdefg:302,cdf246:476,cdgetstatu:142,cdll:[168,475],cdn:83,cdplayer:476,cdr:88,cdrom:[142,181],cdt:174,cea:[476,477],cedilla:[406,442],ceil:[277,300,368,476],celementtre:[429,475],celeri:364,cell:[15,23,58,60,88,93,94,120,167,168,182,236,252,297,337,401,440,476],cellvar:12,celtic:150,cent:463,center:[140,169,178,215,244,246,253,293,368,369,396,401,403,438,457,474,476],centimetr:396,centr:72,central:[150,174,200,222,298,470,471,472,473,475],centric:104,centrum:[28,61,438],centuri:[140,174,392],cern:409,cert:[365,477],cert_byt:365,cert_fil:[241,409],cert_non:365,cert_opt:365,cert_req:365,cert_requir:365,cert_store_stat:365,cert_tim:365,cert_time_to_second:365,certain:[15,20,36,37,43,55,58,63,66,77,80,81,83,90,93,95,96,98,99,101,102,123,124,127,133,134,142,150,174,180,186,194,206,219,222,244,251,264,265,266,267,273,293,303,305,306,309,311,319,320,322,339,360,365,368,371,374,384,391,392,393,396,405,406,407,409,411,416,423,426,434,440,442,446,452,453,461,468,469,470,471,472,473,474,476,477],certainli:[81,88,93,101,102,168,274,293,470,471,472,473,477],certainti:[77,113],certfil:[221,246,318,358,365,470],certic:365,certif:[60,221,241,246,257,267,318,358,409,410,434,476],certificate_verify_fail:365,certificateerror:365,ceval:380,cf9:87,cf_flag:58,cfarrai:141,cfbase:141,cfdata:141,cfdictionari:141,cffi:77,cfg:[64,66,72,73,88,107,158,266,403,476],cfgparser:158,cfile:[88,325],cflag:[76,107,319,387,473],cfm:[227,269],cfmfile:[60,476],cfoo:228,cfrg:405,cfrunloop:130,cfstring:141,cftuvsux:91,cfunctyp:168,cfurl:141,cget:401,cgi:[60,83,88,105,132,187,252,254,341,345,355,409,410,411,423,462,464,470,476],cgi_data:126,cgi_directori:144,cgihandl:423,cgihttprequesthandl:144,cgihttpserv:[60,132,252,254],cgitb:[60,106,143,252,254],cgixmlrpcrequesthandl:[60,187,254,474],chacha20:365,chad:[104,473,475,476],chain:[55,60,94,96,105,157,168,221,222,236,246,257,258,265,318,358,368,380,410,440,442,451,453,476],challeng:[236,463],chambon:477,chanc:[30,79,88,98,100,102,128,174,300,357,391,451,475],chang:[3,4,6,12,14,16,19,20,21,22,24,26,28,29,30,33,34,35,36,37,39,42,43,47,48,49,50,52,53,54,55,56,58,60,63,64,66,67,70,71,72,73,76,77,79,80,81,82,89,90,91,93,94,95,96,99,100,101,104,105,106,107,109,111,113,116,123,124,125,128,133,135,138,139,140,142,143,147,148,150,151,152,156,158,159,161,162,163,167,168,169,171,174,178,180,181,182,186,188,191,192,197,200,201,202,203,204,205,206,207,208,210,215,218,219,221,222,225,226,227,228,229,234,235,236,238,240,241,242,243,244,246,253,256,258,260,263,264,265,266,267,271,273,276,277,281,287,290,293,296,298,299,302,304,305,309,311,316,317,318,319,321,322,325,328,332,333,334,335,336,338,339,342,345,346,348,350,351,352,353,355,356,358,360,361,363,364,365,366,368,369,371,373,374,376,378,380,383,384,385,386,387,388,389,390,391,392,393,394,396,397,398,401,402,403,407,409,410,411,412,413,416,417,418,419,423,426,427,428,429,432,434,435,437,438,439,440,441,442,443,445,446,447,449,450,451,452,453,457,458,459,460,461,462,465,467,469,478],change_root:63,changeabl:88,changelist:345,changelog:477,channel:[106,118,119,126,127,129,168,205,221,266,293,306,359,365,376,417,472],channel_binding_typ:365,chao:[106,403],chapman:[87,474],chapter:[2,15,20,30,37,44,57,58,67,70,76,77,79,80,81,87,96,120,122,157,166,172,173,179,209,211,213,220,242,254,255,257,268,270,285,286,289,295,301,310,329,347,362,372,375,380,393,396,405,408,421,442,445,446,448,450,453,454,457,458],char_data:328,char_gener:364,char_max:264,charact:[4,6,13,15,16,28,29,34,36,42,50,55,60,63,66,72,73,77,81,82,87,88,89,90,93,99,102,108,113,115,116,117,118,120,123,124,126,131,135,140,142,143,148,150,158,161,165,167,168,174,178,180,186,191,192,193,195,197,198,200,201,203,213,214,215,219,221,222,224,226,228,230,231,232,235,237,239,240,243,244,246,252,256,263,264,266,269,270,273,276,278,283,284,287,291,293,295,296,304,305,311,316,320,321,328,331,333,334,335,340,348,349,351,352,355,360,361,364,366,368,369,371,372,374,380,384,385,386,387,389,392,394,396,398,401,404,406,407,409,415,424,426,427,429,430,431,432,433,434,435,440,442,445,446,447,449,452,453,457,458,459,460,463,465,470,471,472,473,474,475,476,477],character:90,character_encod:104,characterdata:427,characterdatahandl:328,characterist:[6,88,311,371,380,475,476],characters_written:256,charbufferproc:55,charfil:432,charg:[105,438,463],charjunk:180,charl:[470,477],charmap:150,charref:101,charset:[60,106,174,192,193,198,200,201,203,230,246,283,295,365],chart:[94,104],chat:102,chdir:[63,206,293,304,352,462],che:475,cheap:[66,88,168,451],cheat:100,check:[4,6,9,15,17,18,20,22,26,28,29,30,31,33,34,38,43,47,48,50,51,52,53,54,55,56,59,60,62,64,69,71,76,77,79,81,82,83,84,87,91,92,93,94,95,96,98,101,102,104,106,107,114,119,120,123,131,134,143,148,157,158,162,168,169,170,178,179,193,206,207,212,221,222,229,233,240,241,244,246,252,253,260,263,265,266,267,269,273,274,277,293,294,296,298,300,304,305,306,308,314,315,317,318,334,336,338,339,341,345,346,352,354,356,358,360,364,365,366,368,369,372,373,374,380,383,388,391,394,398,401,404,407,408,409,410,416,418,423,429,432,434,435,437,442,447,450,451,453,458,459,464,465,468,469,470,471,472,473,474,475,476,477],check_cal:374,check_choic:303,check_circular:260,check_complex:303,check_environ:63,check_form:212,check_hostnam:365,check_moon:303,check_mytyp:303,check_ord:303,check_output:[186,374,477],check_py3k_warn:388,check_same_thread:364,check_unused_arg:369,check_warn:[388,476],checkbox:[143,290],checkbutton:[394,401],checkcach:263,checker:[60,100,123,169,186,254,303,474,475],checkfuncnam:134,checkin:470,checklist:394,checkout:[123,380,469,477],checkpoint:[246,380],checksum:[135,278,384,437],chees:[364,452,464],cheeseshop:452,chem:469,chenet:477,chermsid:473,cherniavski:474,chess:[96,472,473],chessboard:[96,472,473],chevron:447,chflag:[304,366,476],chgat:[169,476],chief:[395,455],chiefli:81,child1:328,child2:328,child:[28,87,88,98,99,102,106,123,125,157,205,206,246,287,293,304,308,317,323,328,336,345,360,361,374,386,401,407,426,427,429,440,470,474,475,476,477],child_conn:293,child_stderr:[304,317,374],child_stdin:[304,317,374],child_stdout:[304,317,374],child_stdout_and_stderr:[304,317,374],child_traceback:374,childerr:317,childless:477,childnod:[426,427,470],children:[88,98,125,157,236,265,293,304,328,336,396,401,426,427,429,470,477],chines:[150,474],chip:[102,161,477],chmod:[87,99,106,143,304,366,449,468],choic:[60,63,77,81,87,88,89,91,99,100,101,102,105,120,143,147,186,212,230,253,258,265,266,273,303,322,328,332,350,365,373,394,442,445,457,459,462,467,468,472,475],choos:[60,63,71,77,79,81,87,91,96,99,100,101,102,104,106,107,123,150,186,230,255,265,303,306,311,322,332,364,365,368,373,391,394,396,415,429,435,467,469,472,473,477],choose_boundari:280,chop:[88,293,305,470,474],chore:470,chose:[101,445,475],chosen:[56,77,94,98,101,107,178,191,221,235,255,256,266,293,303,311,332,360,365,369,373,384,386,394,415,431,447,462,465,473,474],chown:[99,304],chowntest:99,chr:[88,104,222,328,364,440,461,475,477],chri:[473,475,476],christian:[438,470,474,476],christma:83,christoph:473,chrome:419,chromium:419,chronolog:[104,438],chroot:[304,337],chrtype:384,chu:476,chunk:[4,6,12,55,60,99,102,104,126,139,172,221,240,252,256,258,260,286,293,315,328,352,409,423,431,432,470,473,475,477],chunksiz:[293,315],cial:438,cipher:[60,257,477],circl:[403,476],circu:[178,222,450],circuit:[237,368,453],circular:[24,28,30,77,79,81,88,260,380,403,440,471],circumflex:397,circumflexequ:397,circumst:[20,37,81,88,93,98,99,106,119,143,162,192,215,216,265,303,336,410,419,435,440,447,451,454,474],circumv:[368,425],citat:380,cite:83,citi:[96,341,365,438],city_list:96,cjkcodec:474,claim:[30,77,100,180,196,304,365,373,438],claird:87,clamp:178,clara:438,clarendon:147,clarif:50,clarifi:[100,101,434,438,451,460,475,476],clariti:[81,88,102,303,386,392,439],clark:438,clarkson:396,clash:[77,168,192,265,266,273,442,446,451,461,476],class1:[88,472],class2:[88,472],class_:230,classcommand:396,classdef:[125,439,443],classic:[41,55,60,88,90,96,141,164,176,202,230,269,273,302,314,403,444,460,469,472,473,475,477],classif:[60,301,303],classifi:[63,72,100,225,333,473,477],classinfo:222,classinst:309,classmethod:[51,90,94,114,152,168,174,178,186,222,258,293,384,407,440,461,472,474,477],classnam:[20,88,125,152,394,396,439,451],classobj:297,classobject:94,classroom:403,classtyp:[10,404,440],claudiu:470,claus:[60,88,90,93,95,96,157,160,182,206,253,293,309,328,368,380,388,390,439,440,441,442,443,447,449,451,453,454,456,470,475,476],clean:[20,30,60,69,77,79,81,90,102,106,123,125,128,150,167,182,186,205,206,244,253,273,291,293,298,361,380,388,432,440,442,456,470,471,472,474,475,476,477],cleandoc:[125,253],cleaner:[90,100,311,470],cleanest:322,cleanfutur:472,cleanli:[92,101,106,238,365],cleans:[63,338],cleanup:[30,52,60,96,99,113,120,128,160,219,304,362,380,390,407,427,439,441,465,470,472,475,477],clear:[20,21,22,28,29,30,36,38,41,53,54,55,56,71,73,77,79,81,82,83,88,90,93,101,102,104,105,152,162,169,178,186,221,224,225,231,244,263,265,267,273,281,303,304,309,311,314,333,334,339,346,353,364,365,368,380,388,391,401,403,409,416,429,439,440,451,453,460,470,472,473,475,476,477],clear_all_break:134,clear_all_file_break:134,clear_bpbynumb:134,clear_break:134,clear_brows:212,clear_choic:212,clear_flag:178,clear_glob:186,clear_histori:334,clear_memo:311,clear_session_cooki:162,clearcach:263,cleardata:290,clearer:[96,100,186,303,470,471,472,473,474,476],clearest:[88,473],clearli:[96,100,101,123,236,463,470,472,475],clearok:169,clearscreen:403,clearstamp:403,cleartext:165,clees:[429,452],clement:429,clen:126,clever:[72,81,143,236,369,472],cleverli:236,click:[84,102,143,169,191,212,219,243,244,304,403,438,449,467,469],client:[6,53,60,77,87,94,98,99,102,105,126,132,134,143,158,161,192,200,227,252,254,256,257,265,270,296,304,345,355,360,361,362,403,409,410,423,426,433,438,451,452,472,474,476],client_address:[132,144,354,361,423],client_auth:365,client_thread:102,clientip:265,clientmethod:77,clientnam:191,clientsocket:102,cliff:[473,477],clinton:477,clip:[41,49,169,447],clipboard:[141,244,307],clobber:[63,162,303],clock:[88,120,174,212,269,293,322,336,392,393,403,405,476],clock_seq:415,clock_seq_hi_vari:415,clock_seq_low:415,clockwis:403,clone:[192,197,230,235,237,278,293,313,349,401,403,426,445,468],clonenod:[426,427],close:[21,28,58,63,72,79,81,82,88,89,90,95,96,98,99,102,104,106,113,118,119,121,126,127,136,138,139,142,146,149,152,157,160,162,169,176,180,185,188,192,193,202,206,210,215,219,221,222,226,230,234,238,239,240,241,244,246,249,251,253,256,265,267,269,273,287,290,293,299,303,304,306,311,313,317,320,322,328,345,348,350,351,355,358,360,361,364,365,368,370,374,376,377,384,385,386,388,391,394,401,409,410,417,423,429,432,435,440,442,447,452,454,455,457,463,470,474,475,476,477],close_fd:[374,474],close_when_don:126,closeconnect:407,closefd:256,closeit:58,closekei:113,closelog:382,closeport:119,closer:[416,451,455,477],closerang:[304,476],closest:[178,218,222,455,476,477],closur:[23,51,58,79,182,297,303,368],cloth:[192,202],clr:105,clrtobot:169,clrtoeol:169,cls:[43,88,114,152,222,223,253,260,407,440,472,474],clue:303,clumsi:[81,90],clumsier:[471,472],clunkier:251,cluster:[180,222,258,360,465,476],clutter:[88,99],cmath:[60,90,252,277,301,338,474,476],cmd1:123,cmd2:123,cmd:[60,68,69,99,123,134,155,169,191,220,221,238,252,304,309,313,315,317,322,358,374,399,465],cmdclass:[63,68],cmdloop:148,cmdqueue:148,cmdstr:191,cmode:403,cmowz:368,cmp:[43,60,79,96,208,222,264,302,364,368,407,442,453,461,470,471,474],cmp_func:168,cmp_op:182,cmp_to_kei:[103,222,223,368,477],cmpcach:470,cmpfile:208,cmpfunc:[55,79,168],cmpop:125,cnf:394,cnn:121,cnri:[60,470],cnt:152,co_argcount:[253,440],co_cellvar:[182,440],co_cod:[253,440],co_const:[182,253,440],co_filenam:[26,253,440,477],co_firstlineno:[182,253,440],co_flag:[253,440],co_freevar:[182,297,440],co_future_divis:58,co_lnotab:[182,253,440],co_nam:[182,253,297,440],co_nloc:[253,440],co_stacks:[253,440],co_varnam:[182,253,440],coalesc:322,coars:63,coarser:380,cobj:11,cobject:[15,60,477],cocoa:[84,219,467],code:[3,4,6,8,9,11,15,16,19,20,23,24,26,30,31,33,34,35,36,37,42,43,45,47,48,49,50,52,53,54,55,56,57,58,60,63,64,70,72,76,77,79,80,82,83,84,87,89,90,91,92,93,94,95,96,97,98,99,101,102,103,106,107,111,114,115,116,117,118,120,124,125,126,127,128,129,132,133,134,135,136,137,138,140,142,143,144,145,148,150,152,154,156,157,158,159,160,161,162,167,168,169,172,174,175,177,178,179,180,182,184,185,186,189,190,191,192,200,205,206,207,208,210,214,216,218,219,221,222,223,224,226,227,228,230,232,234,235,236,237,238,239,240,241,243,245,246,248,249,251,252,255,256,258,259,260,261,263,264,265,266,267,269,270,271,273,274,276,281,282,283,287,288,293,296,297,298,299,300,303,304,306,308,309,311,312,313,314,315,316,317,318,321,322,323,325,326,327,328,329,330,331,332,333,334,335,337,338,340,342,343,345,348,350,351,352,355,356,357,358,359,360,361,362,364,365,366,369,371,373,374,376,378,379,380,381,383,384,385,386,388,389,392,394,395,396,397,398,399,400,401,404,409,410,411,412,413,414,417,418,419,423,424,425,426,427,428,429,430,431,434,435,436,438,439,440,441,442,445,446,447,449,450,451,454,455,456,457,458,460,461,462,463,464,465,469,470,471,472,474,475,476,477,478],code_context:253,codec:[15,27,50,57,60,100,104,167,194,206,222,252,256,260,368,372,384,459,460,462,470,472,474,475,478],codecinfo:[150,475],codecnam:194,codecontext:244,coded_valu:161,codenam:315,codeop:[60,82,172,252],codepag:150,codepoint2nam:239,codepoint:348,coder:[129,136,460],codereview:477,codeset:[150,230,264,380,472],codestr:297,codetyp:404,codewarrior:[270,476],coeffici:[178,368,473],coerc:[41,55,56,90,158,178,191,194,200,222,230,260,440,442,461,470],coercion:[55,56,60,90,150,222,369,442,475,477,478],coff2omf:[89,107],coff:107,coghlan:[96,100,342,474,475,476,477],coher:186,coin:90,col1:212,col2:212,col:[364,369,403],col_offset:125,cole:[473,474],collabor:[60,108,473],collaps:[197,200,215,239,305],collapse_join:63,collapse_rfc2231_valu:[200,203],collat:[90,264,364],collate_revers:364,colleagu:83,collect:[26,27,37,44,45,55,59,60,63,67,70,77,81,87,88,90,96,97,98,99,100,101,102,106,113,114,123,125,126,127,137,157,158,162,163,168,171,173,184,186,206,222,225,252,255,258,260,279,293,302,311,318,322,328,330,339,352,360,361,368,373,380,385,386,393,401,403,407,409,413,417,418,427,429,440,442,447,450,453,461,463,464,469,472,473,474,475,476,478],collect_incoming_data:126,collector:[24,55,60,77,79,81,88,90,96,252,303,329,380,418,427,470,472,475,476,477],colleg:86,collid:[293,333,410],collin:[96,476,477],collis:[101,235,300,346,350],colombia:429,colon:[4,60,73,90,101,186,196,200,228,230,241,273,309,333,339,358,369,397,423,426,439,440,442,451,454,465,469,476,477],color:[60,88,113,117,152,169,212,231,240,245,252,259,268,286,394,395,396,398,401,440,453],color_black:[93,169],color_blu:169,color_cont:169,color_cyan:169,color_green:169,color_magenta:169,color_numb:169,color_pair:[93,169],color_r:[93,169],color_whit:[93,169],color_yellow:169,colored_btn:401,colorfaq:154,colormap:[247,474],colormix:403,colormod:403,colorpick:[60,252,268,476],colorsi:[60,252,286],colorstr:403,colorstring1:403,colorstring2:403,colour:[87,93,101,470],column:[60,88,104,125,140,143,167,169,180,182,186,215,244,260,290,310,322,328,368,369,373,395,398,407,432,453,457,470,477],com:[60,61,71,77,83,87,88,89,94,98,99,100,101,102,104,105,113,121,138,154,162,168,174,193,259,304,309,333,341,364,365,368,409,410,429,434,464,467,469,472,474,475,476,477],comb:453,combin:[28,50,51,55,56,60,63,71,72,76,79,83,88,90,93,96,99,102,104,105,106,108,113,118,123,132,150,152,160,161,162,168,169,174,178,186,215,225,236,244,256,257,258,264,265,303,304,305,306,317,322,333,345,356,358,361,364,368,369,371,373,374,382,384,396,401,403,405,406,407,411,422,436,438,440,442,447,451,452,453,457,470,474,475,476,477],combinations_with_replac:[152,258,477],combinator:258,combo:[394,401],combobox:[60,394,395],comboboxselect:401,come:[6,56,62,63,66,73,79,81,83,88,90,91,93,94,95,98,100,102,104,105,106,107,137,143,150,161,169,178,186,212,230,231,293,303,306,307,333,334,339,356,361,365,368,395,396,401,410,413,426,431,440,445,447,450,451,452,454,457,461,464,467,468,470,471,472,473,474,476],comedi:83,comfort:[95,104,186],comma:[4,60,63,68,72,109,143,152,167,178,182,186,246,264,265,266,273,303,333,339,368,369,388,397,399,409,440,442,447,452,453,457,460,465,474,475,476,477,478],command:[20,30,58,60,62,64,66,69,70,72,75,76,77,80,81,82,83,84,87,88,89,91,93,98,99,100,101,104,106,107,108,109,112,120,122,132,143,149,159,169,177,179,182,183,184,186,191,201,219,220,221,227,230,246,252,257,262,270,271,274,283,284,290,293,299,304,306,313,315,317,318,319,322,324,325,327,342,351,355,356,358,364,365,372,374,380,385,386,395,396,401,403,408,409,416,419,423,429,440,441,443,447,448,449,450,456,458,459,460,461,464,466,467,468,469,470,471,472,473,474,475,476,478],command_lin:374,command_nam:63,command_packag:68,command_templ:63,commandcompil:151,commandlin:[63,72],commandlist:191,commaspac:193,commenc:[142,391],comment:[1,50,56,60,63,66,73,77,96,99,101,104,109,157,158,161,162,168,186,213,219,240,244,253,271,275,296,304,312,324,327,328,333,348,351,388,398,411,429,431,435,436,438,447,449,452,459,460,470,472,473,475,477],comment_nod:426,comment_url:162,commenthandl:328,commer:438,commerci:[83,84,88,93,306,438,476],commit:[123,290,299,318,364,475,476,477],committ:299,committe:476,common:[20,27,28,30,41,43,44,55,60,62,63,68,70,71,75,77,79,81,83,84,86,88,90,91,93,94,96,98,102,103,104,105,117,123,137,144,150,152,160,162,167,168,174,175,180,185,186,192,194,197,202,208,211,218,221,222,235,236,237,238,244,252,254,256,258,260,263,265,270,273,274,278,288,293,299,303,304,306,310,311,315,332,339,346,348,349,352,358,361,365,368,372,374,387,388,389,390,391,393,394,396,403,407,408,410,424,434,435,437,439,440,442,446,451,452,453,454,455,460,461,462,465,470,471,472,473,474,475,476,477],common_dir:208,common_fil:208,common_funni:208,common_typ:281,commonli:[28,63,77,87,88,90,93,96,101,104,106,108,123,180,200,222,252,270,281,295,304,308,361,368,371,374,384,394,396,407,410,411,433,434,440,447,452,456,457,472,474,475,476],commonnam:365,commonplac:100,commonprefix:305,commonwealth:438,commun:[0,60,62,72,83,84,88,90,99,102,106,108,127,186,205,241,244,252,267,293,304,317,346,353,360,361,365,374,391,401,423,434,457,463,467,470,471,474,475,476],comp:[83,87,88,98,299,464,471,472,475],comp_for:[442,443],comp_if:[442,443],comp_it:[442,443],comp_op:443,comp_oper:442,comp_siz:463,compact:[37,88,90,101,104,125,143,180,195,260,331,373,442,451,461],compactli:[124,450,463,473],compani:[83,84,104,365,475,476],companion:[27,95,127,243,377,473],companydata:152,compaq:86,compar:[8,20,43,55,56,60,73,81,82,87,88,90,91,93,95,98,100,101,102,103,104,106,107,108,113,125,142,157,168,174,178,180,182,186,194,198,200,208,222,223,236,237,251,253,260,264,273,276,293,303,307,308,322,328,332,364,365,368,371,388,393,406,407,413,429,440,442,446,451,456,458,463,465,470,471,472,473,474,475,476,477],comparand:174,compare_digest:[237,477],compare_op:182,compare_sign:178,compare_tot:178,compare_total_mag:178,comparison:[16,20,43,55,56,60,72,81,96,100,103,109,113,117,137,152,159,168,173,174,178,180,186,211,214,222,223,236,252,270,292,293,302,305,308,364,369,371,407,440,443,444,446,453,460,465,470,472,473,474,475,476,477,478],comparison_flag:186,compass:396,compat:[4,6,22,28,37,55,56,58,60,63,72,79,82,83,87,90,92,93,98,101,104,105,106,107,117,122,123,124,132,134,138,143,144,150,151,158,161,162,163,168,176,178,181,182,186,192,202,206,222,223,224,228,230,238,241,245,246,247,249,252,256,260,264,266,269,273,278,280,282,283,284,286,292,293,299,304,308,311,313,315,322,332,333,336,338,339,343,346,351,352,354,360,364,365,368,376,380,383,384,386,388,391,392,395,398,403,405,406,407,409,410,411,413,414,415,417,423,425,427,434,436,438,439,440,443,446,447,451,454,469,470,471,472,473,475,476,477],compel:[266,477],compens:[322,339],compet:106,competit:102,compil:[26,28,30,51,52,55,58,60,66,69,70,72,75,78,79,80,83,87,88,89,90,95,96,104,106,108,109,111,125,149,150,168,172,182,186,214,222,238,241,246,249,252,253,255,262,266,276,315,319,322,328,333,334,338,342,351,364,365,368,373,380,381,385,388,393,396,401,404,407,416,426,435,438,440,441,443,445,446,447,450,451,456,465,466,468,470,471,472,473,475,476,477],compile_command:[149,151],compile_dir:156,compile_fil:156,compile_path:156,compile_typ:379,compileal:[60,88,252,262,325,461],compileerror:63,compilefil:157,compileflag:186,compiler_flag:[111,222],compilerflag:111,compilest:308,complain:[55,79,81,91,99,244,471],complaint:[83,84,91,452,454,471],complement:[90,101,333,368,380,440],complementari:[277,332,424,477],complet:[20,28,37,52,55,56,60,61,63,73,77,79,80,81,82,83,88,89,92,93,96,97,99,101,102,104,106,107,119,123,128,132,135,139,140,143,147,148,149,150,151,156,158,160,169,174,178,180,186,191,192,200,201,202,206,207,212,219,221,222,231,233,236,239,240,243,247,249,250,252,266,267,273,274,290,293,303,304,306,307,317,322,330,332,333,346,348,351,352,354,360,361,362,364,365,366,368,374,384,387,388,391,394,395,396,398,399,400,401,407,409,411,423,424,426,427,429,432,438,440,441,444,445,451,455,457,458,460,461,462,464,467,470,471,472,473,474,475,476,477],complete_:148,complete_foo:148,complete_stat:364,completedefault:148,completekei:[148,309],complex:[4,6,15,30,60,62,64,75,76,77,81,83,87,88,89,90,91,94,99,101,102,105,106,107,108,123,125,126,127,167,174,178,180,193,222,252,260,266,276,277,282,300,301,303,308,311,333,338,369,374,403,404,410,434,440,442,446,450,451,452,453,457,460,461,462,465,472,474,475,476,477],complexencod:260,complextyp:[14,404],compli:[178,260,273,328,413,438,476],complianc:[60,178,295,423,426],compliant:[99,106,109,135,192,194,195,197,198,202,203,207,230,260,273,275,364,391,423,425,438,472,475,477],complic:[6,28,55,72,77,81,90,93,96,100,101,102,105,106,107,129,157,162,168,180,186,207,303,311,333,396,440,442,450,454,457,460,470,472,473,474,475,476,477],compnam:[118,376,417],compon:[1,30,37,60,63,77,81,83,88,98,99,101,104,105,106,108,113,153,157,162,163,169,174,178,204,230,232,252,254,255,268,270,290,300,304,305,308,333,351,355,368,369,380,381,382,386,392,393,401,403,407,409,410,426,431,435,440,444,446,469,473,474,477],componentflag:290,componentitem:117,compos:[55,60,132,165,193,198,274,292,304,358,381,382,394,406,446],composit:[273,401,406,453],compound:[30,60,163,302,369,389,394,395,401,444,446,448,460,476],compound_stmt:[439,443,448],comprehens:[60,87,88,90,105,109,125,139,182,280,292,339,440,442,451,456,462,468,474,475,477,478],compress:[28,60,63,64,73,90,106,118,135,150,193,210,234,252,258,259,281,290,306,352,365,366,376,384,405,417,425,435,456,464,472,473,475,477],compress_s:435,compress_typ:[435,477],compressionerror:384,compresslevel:[139,234,384],compressobj:437,compressor:[139,259],compris:[55,182,216,314,339,442,446,447,476],compromis:[392,415,437,452],comptyp:[118,376,417],compulsori:[471,472,473],comput:[28,30,43,50,55,60,63,75,76,79,81,83,84,85,87,88,89,90,93,94,95,96,98,101,103,104,106,107,113,124,129,135,140,147,152,154,170,174,178,182,186,208,215,216,219,221,222,231,235,236,237,245,247,252,258,265,267,277,278,293,305,315,321,322,332,346,349,356,360,361,365,368,372,391,393,403,407,415,437,439,440,442,446,447,449,450,451,453,455,457,462,463,465,467,469,470,471,472,473,475,476,477],computation:90,computer_nam:113,computernam:113,comspec:[304,374],con:[88,364],concat:[7,56,96,302],concaten:[6,20,46,47,60,63,79,101,123,124,143,149,150,222,235,237,273,278,302,304,305,328,333,338,349,358,365,368,369,384,400,437,440,442,454,457,460,473,474],conceiv:[30,66,271,311,384,412,451],concentr:[64,70,77,83,101,105,332,463,476],concept:[60,69,83,90,96,98,100,106,107,114,161,178,186,256,293,313,323,360,368,384,391,407,429,440,447,450,456,472,473],conceptu:[94,98,123,129,200,270,369,416],concern:[70,88,98,107,150,222,239,267,328,353,365,380,412,438,440,471,472,477],concert:232,concis:[83,90,96,303,364,440,451,452,453,470,474],conclud:[91,96,98,101],conclus:60,concret:[27,60,63,101,114,125,152,157,168,174,230,256,266,303,361,407,411,426,433,472,473,476],concurr:[28,90,99,138,219,273,293,311,350,365,477],cond:[134,293,475],condcom:240,condens:[127,235,266,278,475],condit:[28,52,55,60,77,79,81,90,96,99,105,106,107,112,120,126,132,134,137,178,180,196,206,222,228,236,240,246,256,265,266,273,274,290,293,304,308,309,328,332,333,345,360,362,364,368,380,386,388,407,416,418,430,432,434,439,440,441,444,452,454,456,460,463,470,471,472,474,476,477,478],condition1:96,condition2:96,condition3:96,condition:[60,265,438],condition_func:293,conditional_express:442,conditionn:96,conditionspeed_func:293,conduc:202,conduct:249,conf:[98,99,101,463,473],confer:[83,364,401,471,475],confid:[100,143],confidenti:106,config:[60,66,69,72,73,76,82,88,98,99,119,120,158,244,252,264,265,267,268,303,352,380,381,396,463,473,477],config_dict:266,configdict:477,configfil:158,configpars:[60,209,252,266,351,470,474,477],configur:[16,28,30,55,56,60,64,68,69,70,71,72,76,77,88,89,93,96,101,104,106,113,120,144,164,168,176,180,184,206,209,221,222,243,244,252,255,265,267,273,274,303,304,319,321,328,329,334,344,347,351,357,360,365,380,387,390,391,394,395,396,401,407,409,410,425,427,433,434,438,440,461,463,465,466,468,470,471,472,473,474,475,476,478],configure_log:99,confin:[169,186],confirm:[71,98,305,309,409,410,416],conflict:[60,64,77,81,90,101,103,105,113,120,123,152,230,241,320,346,380,438,451,465],conflict_handl:[60,120,303],confluenc:100,conform:[24,60,79,135,143,158,174,178,216,222,254,275,308,328,339,411,427,429,434,438,440,474],confront:[30,430,473],confstr:304,confstr_nam:304,confus:[30,55,72,76,81,87,88,93,100,101,103,105,106,111,149,160,168,178,180,186,212,303,304,311,315,333,346,409,440,442,451,452,460,470,471,472,473,474,475,477],confusingli:[101,105,446,470],conin:374,conio:469,conjug:[178,300,368,476],conjunct:[26,152,159,175,180,183,186,222,284,311,332,365,441,446],conn1:293,conn2:293,conn:[127,152,241,293,360,364,365,391,475],connect:[60,89,93,95,99,102,105,106,113,120,126,127,132,143,152,162,202,205,221,241,244,246,256,265,267,299,303,304,310,317,318,323,358,360,361,362,365,368,373,374,385,388,391,394,396,403,409,410,414,423,425,427,430,432,434,438,442,446,454,457,459,460,465,470,474,475,476,477],connect_ex:[87,360,470],connectdb:391,connectregistri:113,connid:99,connolli:409,connor:473,connstream:365,conout:374,consecut:[4,19,63,96,150,258,368,369,403,446,465,474],consensu:[81,90,446,470],consequ:[37,66,77,81,88,157,167,212,236,253,293,360,368,442,445,451,455,475,477],consequenti:438,conserv:[100,126,308,412,471,474],consid:[28,43,48,55,56,60,62,63,64,76,77,79,81,88,90,91,92,94,95,96,99,101,104,106,107,109,114,123,133,134,137,139,143,156,159,168,169,174,178,180,182,186,189,192,199,200,206,215,222,228,230,232,236,255,256,260,265,266,273,278,293,300,303,304,308,309,322,328,333,334,338,339,345,351,352,354,355,364,365,368,369,374,380,384,388,389,390,391,392,396,407,409,410,413,423,426,427,440,441,442,447,451,453,455,461,465,470,471,472,473,474,475,477],consider:[30,60,77,81,88,98,106,169,186,221,241,257,273,329,364,426,427,450,470,473,474,475,477],consist:[4,14,16,20,28,30,45,49,58,62,63,72,77,83,90,93,96,98,100,106,107,118,125,129,135,140,142,143,146,150,152,158,162,169,170,174,180,184,186,192,200,202,222,228,240,241,244,245,246,255,260,264,266,273,277,293,297,311,313,322,333,339,343,348,351,358,361,368,369,371,376,386,389,394,401,403,407,409,426,439,440,442,446,452,453,460,467,468,470,471,472,473,476,477],consol:[58,60,72,88,89,93,98,99,168,170,172,186,197,219,222,266,304,327,334,374,395,421,449,469,472,476],console1:99,console2:99,consolehandl:98,consolelib:87,consolid:473,consortium:[104,426,446],const_on:30,constant:[3,6,28,39,51,55,60,79,81,88,90,93,99,110,120,123,125,142,150,152,157,161,167,170,174,178,182,185,186,207,211,222,223,225,226,235,236,241,249,252,253,256,257,258,262,264,268,275,276,278,290,291,293,297,301,303,306,308,310,311,312,320,321,322,333,336,338,345,347,349,360,366,368,372,375,380,382,384,385,387,388,390,396,398,405,406,415,421,422,426,429,431,434,435,437,440,442,446,465,470,472,473,474,475,476,477],constant_factori:152,constantli:457,consti:182,constitu:[203,339,426],constitut:[180,438],constrain:[58,124,125,321,440,442,472,475],constraint:[96,178,255,265,321,368,475,476],construct:[3,6,20,47,51,57,58,60,64,72,76,77,79,81,88,90,94,96,98,99,101,103,106,123,132,133,150,152,157,160,162,163,168,178,186,191,197,206,208,215,218,222,225,239,240,249,258,265,266,276,290,293,303,308,311,321,322,328,333,334,346,348,351,356,358,364,365,368,373,374,384,386,391,403,404,407,411,416,418,425,427,428,429,430,434,439,440,441,442,446,447,451,452,453,459,462,465,469,470,471,472,474,475,477],constructor:[4,10,16,20,24,46,48,55,56,60,63,72,77,79,82,87,90,94,96,98,99,100,104,109,123,125,127,140,149,150,152,158,162,164,167,168,174,178,180,186,187,191,192,195,197,198,200,201,202,206,208,210,218,222,234,235,237,242,246,256,257,258,260,265,266,273,287,293,297,302,303,311,317,318,321,322,330,338,343,344,345,346,350,355,357,358,360,361,365,368,369,370,379,384,385,389,391,393,396,403,407,409,410,413,416,419,423,429,435,436,440,447,453,473,474,475,476,477],consult:[63,64,83,87,88,93,96,98,101,104,107,138,142,147,168,174,222,230,265,266,273,304,306,333,336,358,360,364,366,384,392,395,413,423,437,457,469,470,472,473,474,475,476,477],consum:[6,56,87,88,96,101,102,123,126,143,150,167,182,202,256,258,260,292,293,303,304,322,330,333,336,339,350,373,391,407,425,437,459,465,470,474,475,476,477],consumpt:[79,253,308,336,352,440,457],cont:186,contact:[83,94,106,410,423,438],contain:[4,9,13,19,22,23,24,26,28,29,30,33,35,36,37,42,47,48,50,51,52,55,56,60,63,64,68,70,72,73,75,76,77,79,80,82,83,87,88,89,90,93,94,96,98,99,100,101,102,103,104,105,106,107,109,113,116,117,118,119,120,121,125,126,129,131,132,133,134,135,136,138,139,140,141,142,143,144,145,149,150,151,155,156,157,158,161,162,163,164,167,168,169,170,173,174,175,179,180,182,186,191,192,193,194,195,196,198,200,201,202,203,206,208,213,215,219,221,222,225,226,230,231,232,234,235,236,237,238,239,240,241,244,245,246,248,249,252,253,255,256,259,260,261,264,265,266,267,270,271,273,274,276,278,279,280,281,283,287,288,290,293,294,295,296,297,298,299,301,302,303,304,305,306,308,309,311,312,314,315,316,318,321,322,324,325,326,327,328,332,333,336,338,339,341,342,345,346,348,349,350,352,354,355,356,357,358,360,361,364,365,367,368,369,373,374,377,379,380,381,383,384,386,387,388,389,392,393,394,396,398,399,400,401,403,404,405,407,409,410,411,414,415,416,418,419,420,422,423,424,425,426,429,430,431,432,433,434,435,436,437,438,439,441,442,445,446,447,449,451,452,453,454,455,456,457,459,460,461,463,464,465,468,469,470,471,472,473,474,475,476,477],contemporari:[256,332],content:[0,4,6,7,9,22,28,33,34,37,47,50,51,55,56,58,63,66,71,74,75,76,79,91,93,96,98,101,104,105,106,107,111,121,124,126,131,132,141,142,143,146,149,150,152,168,169,171,179,182,186,192,193,194,195,196,197,199,200,201,202,203,207,208,209,219,221,222,230,234,237,239,240,241,244,252,253,255,256,260,266,273,275,279,280,281,282,287,288,290,304,311,312,314,331,334,339,346,348,352,354,355,356,357,360,364,365,368,369,370,372,376,384,386,389,396,398,405,408,409,410,413,423,425,427,429,431,432,433,434,435,441,442,446,451,452,454,457,458,460,461,465,470,471,472,473,474,475,476,477],contenthandl:[60,275,428,430,432,433,470],contenttooshorterror:409,context:[8,20,47,58,60,62,64,70,77,82,88,90,92,95,96,102,104,113,123,125,126,145,150,174,179,180,182,221,222,236,241,251,252,253,256,257,260,265,266,273,293,301,307,309,310,321,328,329,333,335,336,339,378,380,384,388,391,394,395,397,407,409,410,418,426,430,431,434,435,439,442,446,447,449,453,454,470,477],context_diff:180,context_expr:125,contextfilt:99,contextlib:[60,252,329,368,477],contextmanag:[160,368,475,476],contextu:[60,180,265],conti:477,contigu:[4,6,55,81,180,246,273,431,476],continu:[4,20,30,31,52,60,66,77,81,82,83,88,90,94,96,98,104,105,111,114,120,125,126,127,132,142,147,148,150,157,158,169,182,186,192,193,196,197,198,200,202,222,241,244,246,251,258,259,273,291,292,303,304,305,309,311,328,333,339,352,360,361,365,368,390,398,407,416,431,437,438,439,440,441,442,443,444,446,451,454,456,458,459,460,463,470,472,473,474,475,476,477],continuation_w:198,continue_loop:182,continue_stmt:[443,447],contract:[368,438],contractu:470,contradictori:303,contrari:[81,180,345,457],contrarili:461,contrast:[79,90,103,106,178,322,346,365,368,396,440,442,462,472],contrib:396,contribut:[0,60,62,70,81,83,93,108,193,230,307,322,333,405,414,438,464,468,470,471,472,473,474,475,476,477],contributor:[60,62,108,438],contriv:186,control:[4,27,28,30,37,51,57,60,63,66,67,69,77,80,82,86,88,90,93,98,101,103,107,113,116,123,127,134,138,142,143,145,148,150,157,163,167,168,169,170,174,178,180,184,186,191,204,206,207,210,215,219,221,222,225,226,229,234,244,246,252,254,256,257,260,266,267,268,270,273,281,290,291,293,299,303,304,306,309,310,311,316,318,320,321,322,323,328,329,331,335,336,338,344,345,351,355,360,361,362,365,368,371,373,374,377,380,384,386,391,394,395,396,399,400,401,407,408,409,422,429,431,434,437,439,440,441,442,445,447,449,451,454,455,456,457,458,459,463,465,467,470,471,472,473,474,475,476,477],control_next:290,controlaccessor:[60,268],controlcondit:290,controlev:290,controlnam:170,controlpanel:396,controlswindow:[60,268],controversi:[303,472],conttyp:384,conv:463,convei:169,conveni:[4,6,17,20,24,26,28,37,39,55,60,64,68,71,77,79,81,87,88,89,92,98,99,101,103,104,105,106,107,123,140,143,149,150,152,158,162,168,178,182,194,195,197,198,200,201,202,203,219,222,223,230,244,252,253,254,256,265,266,268,269,273,281,289,293,302,303,306,308,311,322,346,351,364,365,368,374,376,384,387,388,389,392,393,394,396,407,411,412,417,423,425,426,429,430,432,439,440,446,447,451,452,454,458,460,461,470,472,473,474,475,476,477],convent:[51,55,63,67,70,72,77,88,90,93,94,98,99,104,107,136,140,162,168,169,170,174,215,222,228,230,231,242,264,273,303,305,306,368,369,374,380,389,392,407,410,440,442,445,446,447,451,452,454,458,461,462,463,468,470,471,472,473,474,475,476,477],convention:[8,77,162,303,304],convers:[4,27,28,30,34,41,55,56,57,60,76,83,90,93,94,102,104,120,123,127,131,135,136,150,167,173,174,178,194,216,222,252,256,260,264,270,273,281,286,300,301,303,311,348,360,365,368,369,372,373,380,384,398,404,414,432,438,440,444,447,460,461,475,476,477,478],conversionerror:424,conversionsyntax:476,convert:[4,13,14,16,20,22,28,34,41,48,49,51,55,56,60,63,71,72,73,76,77,79,81,83,87,89,90,94,96,98,99,101,102,103,104,106,107,109,110,113,115,116,121,123,124,128,129,132,136,142,143,144,147,150,152,154,157,158,161,162,164,167,168,169,170,174,176,178,186,187,188,189,194,198,200,201,207,214,216,221,222,223,224,226,230,231,239,240,241,243,245,246,252,257,258,260,262,264,265,266,267,273,276,277,280,281,283,293,295,300,302,303,304,305,310,311,313,316,321,330,333,335,341,344,346,348,354,355,358,360,361,368,369,373,376,380,384,390,392,394,396,398,401,405,407,409,410,411,413,415,420,423,427,429,431,434,435,440,442,446,447,451,454,455,457,460,465,470,471,472,473,474,475,476,477],convert_arg_line_to_arg:123,convert_charref:348,convert_codepoint:348,convert_entityref:348,convert_field:369,convert_path:63,convert_point:364,convinc:[98,264],conwai:396,cook:[169,385,440],cookbook:[30,60,67,78,88,97,98,105,265,266,267,277,393,464],cooki:[60,105,252,254,365,390,410,474,476,477],cookie2:162,cookie3:162,cookie_spec:162,cookieerror:161,cookiejar:[60,254,410],cookielib:[60,161,252,254,410,477],cookiepolici:[60,254],cool:[64,88],cooper:[28,90,114,222,380,438,451],coord:369,coordin:[60,62,81,93,108,154,168,169,171,174,219,231,245,273,290,301,364,369,392,396,401,403,463,470,476],cope:[72,83,474],copi:[4,6,28,45,48,50,55,56,60,62,63,64,68,70,72,77,80,81,89,91,92,96,107,108,109,123,125,143,152,164,168,169,173,178,181,186,207,215,222,223,230,235,237,244,246,249,252,258,271,273,278,279,280,281,283,287,293,303,304,311,313,314,333,339,346,349,350,352,368,369,374,381,388,396,403,407,409,411,413,416,423,431,432,437,438,439,440,451,452,460,461,471,472,473,474,475,476,477],copied_list:163,copy2:352,copy_ab:178,copy_decim:178,copy_fil:63,copy_loc:125,copy_neg:178,copy_reg:[60,163,252,288,310,311],copy_sign:178,copy_tre:63,copybinari:280,copyfil:[87,352,462,477],copyfileobj:[234,352],copyliter:280,copymessag:279,copymod:352,copyreg:164,copyright:[28,60,62,64,77,89,107,159,244,293,338,380,438,459,461],copysign:[277,476],copystat:352,copytim:271,copytre:[60,87,211,271,476,477],corba:426,corderoi:476,core:[1,20,24,45,52,60,62,67,68,69,70,71,72,75,77,79,90,98,100,101,116,119,120,128,158,200,222,231,238,252,255,258,264,267,268,270,302,303,304,312,322,327,332,336,353,388,391,426,438,444,447,461,469,471,472,473,474,475,476,477,478],corefoun:[60,268],corefound:141,coregraph:[60,268],corner:[16,93,95,169,259,368,403,423,472,475,476],coroutin:[96,442,447,475],corp:472,corpor:[61,62,108,438],correct:[1,28,55,64,77,80,88,95,96,101,104,105,106,109,115,135,157,160,162,168,186,193,208,219,240,243,244,246,247,271,277,287,293,300,303,304,306,308,328,339,352,360,364,365,369,374,376,380,392,396,407,410,417,427,431,437,440,442,446,451,452,454,469,470,472,473,474,475,476,477],correctli:[6,51,55,79,81,88,92,113,118,123,128,143,150,174,178,186,200,203,232,243,244,264,273,304,305,308,311,339,368,369,384,388,400,423,440,446,453,454,455,472,474,476,477],correspond:[4,9,14,16,20,25,26,28,30,35,43,49,50,51,55,56,60,63,64,67,72,73,77,79,82,88,89,90,92,93,96,98,101,102,104,105,107,111,117,118,121,123,124,126,135,140,142,148,152,162,167,168,169,170,174,178,186,191,192,205,206,210,212,215,221,222,223,230,233,239,246,249,253,256,258,260,264,265,266,273,293,302,303,304,306,311,321,322,324,328,331,332,333,345,348,351,353,355,358,360,363,365,368,369,373,374,379,380,381,389,391,394,395,396,398,400,401,404,406,407,410,411,414,418,419,422,426,431,433,434,435,436,437,439,440,442,443,447,451,452,453,454,460,465,469,471,472,473,474,475,476,477],correspondingli:[273,470],corrupt:[37,52,104,135,162,169,205,207,273,293,457],cos:[147,178,218,277,462,473],cosh:[147,277],cosin:[147,178,277],cost:[76,81,88,106,152,162,174,180,279,308,393,440,470,473,476,477],costa:429,costlier:90,could:[6,20,22,26,28,29,30,49,55,63,64,67,68,75,77,79,80,81,86,88,92,93,94,95,96,98,99,100,102,103,104,105,106,107,109,114,123,124,125,129,143,148,152,167,168,169,174,186,192,193,194,197,201,206,208,221,225,228,230,236,237,244,249,256,258,260,265,266,267,269,271,273,282,293,294,303,304,305,306,309,311,315,322,325,328,333,335,338,360,380,384,388,391,395,407,411,412,414,415,416,418,423,426,440,442,445,446,450,451,452,454,457,460,461,465,469,470,471,472,473,474,475,476,477],couldn:[77,104,105,256,304,353,364,436,471,472,475,477],count0:225,count1:225,count2:225,count:[3,4,5,9,20,21,27,28,40,41,43,47,49,50,51,55,60,78,79,81,82,83,87,88,90,91,95,96,101,103,104,110,119,123,124,127,134,135,139,141,143,152,168,169,174,180,182,186,200,210,222,225,236,238,244,246,253,256,258,265,273,287,290,293,299,303,309,311,318,322,330,333,345,351,364,365,368,369,373,380,389,391,392,393,396,399,407,409,429,440,442,446,447,453,460,463,465,470,472,473,474,475,476,477],count_alloc:[55,465,477],countcal:399,counter:[60,77,79,88,90,96,128,173,180,182,193,212,215,236,258,293,303,368,380,391,439,442,451,472,474,475,476,477],counterclockwis:[147,403],countermeasur:425,counterpart:[77,96,99,115,117,169,222,256,258,265,272,273,346,368,377,387,477],countfunc:399,countless:470,countof:302,countri:[142,162,264,365,429,460,474],country_data:429,country_data_as_str:429,countrydata:429,countrynam:365,counttestcas:407,coupl:[60,67,72,73,79,88,99,100,102,106,123,265,293,303,353,395,410,425,469],courier:[273,396],cournapeau:477,cours:[63,64,67,70,72,73,77,79,81,83,87,88,89,95,96,98,99,102,106,107,114,168,178,186,192,198,202,255,266,293,294,300,303,304,361,365,396,403,426,434,440,451,452,457,458,460,465,470,471,473],cousin:311,cout:88,cover:[62,69,70,72,78,79,82,83,88,93,97,98,99,101,102,104,106,107,108,160,162,186,266,293,303,311,333,358,374,396,399,407,426,437,438,445,446,456,463,465,470,471,472,475],coverag:[28,60,380,396,399,440],coverageresult:399,coverdir:399,cowl:193,cowlishaw:474,coyot:162,cp037:150,cp1006:150,cp1026:150,cp1140:150,cp1250:150,cp1251:[150,368],cp1252:[150,459],cp1253:150,cp1254:150,cp1255:150,cp1256:150,cp1257:150,cp1258:150,cp1361:150,cp154:150,cp424:150,cp437:[150,435],cp500:150,cp720:[150,477],cp737:150,cp775:150,cp819:150,cp850:150,cp852:150,cp855:150,cp856:150,cp857:150,cp858:[150,477],cp860:150,cp861:150,cp862:150,cp863:150,cp864:150,cp865:150,cp866:150,cp869:150,cp874:150,cp875:150,cp932:[150,474],cp936:150,cp949:[150,474],cp950:[150,474],cp_acp:150,cpanel:105,cpickl:[60,164,252,310,312,350,473,475,477],cplx:476,cpp:[72,473],cpparg:107,cppflag:473,cprofil:[60,177,238,475],cpu:[87,102,150,236,238,293,393,425,467,473],cpu_count:293,cpython:[12,60,77,78,83,88,89,90,91,95,110,182,204,222,249,253,277,315,342,368,380,391,404,418,440,441,442,445,447,465,468,469,471,472,473,475,476,477],crabgrass:453,crack:165,craft:[161,197,222,457],craig:473,cram:246,crash:[6,30,77,92,106,143,168,185,273,293,297,303,309,311,380,391,470,475,476],crazi:102,crc32:[135,235,437,462,463],crc:[135,435,437],crc_hqx:135,creat:[0,1,2,3,4,6,7,8,9,10,11,12,14,17,19,20,21,22,24,25,26,29,30,34,38,48,50,51,53,55,56,58,59,60,66,68,69,70,71,72,75,77,78,79,80,81,84,89,90,92,93,94,98,99,100,101,103,104,105,106,107,108,113,114,116,118,120,121,124,125,126,127,132,134,138,139,140,142,143,146,149,150,152,156,157,158,160,163,167,168,169,174,175,176,178,180,182,186,187,188,189,190,192,193,195,197,198,202,204,206,207,210,211,212,215,219,221,222,223,225,226,227,230,234,235,236,239,240,241,243,244,246,249,252,253,256,262,265,266,267,270,271,273,274,276,278,279,282,287,290,291,292,293,294,295,297,301,304,305,309,310,311,312,314,317,318,320,321,322,328,332,333,336,337,338,339,340,345,349,350,352,354,355,356,357,360,361,364,365,366,368,369,370,373,374,379,380,384,386,388,389,390,391,393,394,396,398,399,401,403,404,407,409,410,413,414,415,418,419,423,426,427,429,430,431,432,433,434,435,436,438,439,440,441,442,445,446,447,449,451,452,453,454,457,458,460,461,462,463,464,465,467,468,469,470,471,472,473,474,475,476,477],create_aggreg:364,create_col:364,create_connect:[360,476,477],create_decim:[178,476],create_decimal_from_float:178,create_default_context:[241,365,477],create_funct:364,create_lin:470,create_method:293,create_new_consol:374,create_new_process_group:374,create_pars:[430,432],create_polygon:470,create_shortcut:64,create_socket:127,create_stat:322,create_static_lib:63,create_string_buff:[168,475],create_system:435,create_tre:63,create_unicode_buff:168,create_vers:435,createattribut:426,createattributen:426,createcom:426,createconnect:407,createdocu:[426,427],createdocumenttyp:426,createel:426,createelementn:426,createexpensiveconnectionobject:407,createfilehandl:396,createkei:113,createkeyex:[113,477],createlock:[265,267],createpars:142,createpath:271,createprocess:374,createprocessinginstruct:426,createrecord:290,createsocket:267,createtextnod:[426,427],createwidget:396,creation:[5,21,28,30,55,60,75,79,81,88,90,96,98,99,102,106,120,122,123,124,127,152,173,178,191,212,219,230,252,253,254,257,265,271,273,290,293,303,305,308,335,336,366,368,374,386,394,396,426,438,451,473],creationflag:[374,474],creativ:87,creator:[0,63,90,99,116,227,243,269,271,293,352,405,427,435,436,445],creator_signatur:227,creatorsignatur:227,credenti:[71,267,299],credit:[89,107,159,244,258,396,459,461],crew:[472,473,475],crisscross:231,crit:267,criteria:[98,246,265,322],criterion:[81,246,470],critic:[82,83,88,90,98,99,103,238,265,266,267,303,322,353,422,450,462,463,473,475,476],crl3:365,crl4:365,crl:365,crldistributionpoint:365,crlf:[56,106,161,221],crncystr:264,cro:101,cron:267,crop:[245,388],cross:[60,62,63,69,76,79,83,84,102,107,120,129,161,174,184,205,234,244,304,307,426,429,446,467,470,471,472,473,476,477],crossov:169,crow:101,crt:[365,477],crt_assembly_vers:477,crtassem:477,crucial:470,crude:169,cruft:443,crumb:186,crunch:[79,471],crux:407,crypt:[60,252,324,408,438],cryptedpasswd:165,cryptgenrandom:304,cryptic:[81,143],cryptoapi:474,cryptograph:[28,60,252,304,332,349,437,438],cryptographi:237,cryptographic_hash_algorithm:235,cryptographic_hash_funct:235,cryptsoft:438,csbig5:150,csd:315,cserna:477,cshrc:[305,467],csi:205,csidl_appdata:64,csidl_common_desktopdirectori:64,csidl_common_program:64,csidl_common_startmenu:64,csidl_common_startup:64,csidl_desktopdirectori:64,csidl_font:64,csidl_program:64,csidl_startmenu:64,csidl_startup:64,csidl_str:64,csiso2022jp:150,csiso2022kr:150,csiso58gb231280:150,csptcp154:150,csrc:235,css:[140,240,410],csshiftji:150,cst:174,cstringio:[60,167,200,252,311,372,476],csv:[60,152,209,252,462,473,475],csv_reader:167,csvfile:167,csvreader:167,csvwriter:167,ctermid:304,ctime:[76,174,180,305,366,392,473],ctl:[60,231,268,377],ctlpoint:231,ctrl:[82,89,93,99,159,170,293,353,361,452,465,470,475],ctrl_break_ev:[304,353,374,477],ctrl_c_event:[304,353,374,477],ctx:[125,178,365,476],ctype:[28,60,77,89,120,185,193,200,252,282,314,362,477],ctypes_configur:91,cube:[453,457,460],cubic:180,cud1:169,cud:169,cull:322,cultur:[230,264,463],cum:322,cumbersom:[76,178,396],cumtim:[238,322],cumul:[96,210,222,322,399,458,475],cup:169,cur:[273,364],cur_block:142,cur_thread:361,curdir:[208,304,305],curiou:143,curl:162,curli:[90,104,290,369,406,415,442,446,453,476,477],curmax:219,curmin:219,curr:178,currenc:[178,264,475],currency_symbol:[264,463],current:[3,6,8,9,16,20,26,28,29,30,36,43,46,52,54,55,56,58,60,62,63,64,67,70,72,73,77,79,81,82,83,84,87,89,90,91,92,93,95,96,97,99,101,104,105,106,107,113,118,119,123,124,125,126,130,132,134,139,140,141,142,143,144,145,146,147,148,150,156,157,158,161,163,165,167,168,169,171,174,175,178,182,184,186,188,191,193,200,203,204,205,207,210,212,213,214,215,216,219,220,221,222,225,230,234,236,240,243,244,245,246,247,249,253,254,256,258,259,260,264,265,267,269,270,273,276,277,279,280,281,284,287,290,291,292,293,299,303,304,305,306,309,311,314,315,320,321,322,323,325,327,328,330,332,333,334,336,340,341,343,351,352,353,354,360,364,365,368,369,374,376,377,380,381,382,384,386,390,391,392,394,396,399,400,401,403,405,407,409,410,411,412,415,416,417,422,423,424,426,427,429,431,432,434,435,436,437,438,439,440,441,442,445,446,447,449,451,452,455,457,458,459,461,462,463,465,467,469,470,471,472,473,474,475,476,477],current_d:364,current_process:293,current_thread:[293,361,391],current_timestamp:364,currentbyteindex:328,currentclass:440,currentcolumnnumb:328,currentfram:253,currentlinenumb:328,currentthread:[87,180,391],currenttim:434,curri:96,currkei:258,currvalu:258,curs:[60,97,120,252,469,470,471,474,476],curs_set:[93,169],cursor:[60,93,138,148,152,167,169,219,244,304,310,334,394,396,401,458,475,476],cursorfont:396,cursyncup:169,curtin:477,curv:[147,231,365,403],curval:191,curve_nam:365,custom:[30,60,63,75,77,79,82,88,90,94,105,109,114,120,125,132,152,158,177,186,202,216,222,244,249,251,252,260,265,267,271,273,289,303,310,311,334,340,356,362,365,368,372,380,391,401,407,410,412,416,423,426,429,434,442,450,451,453,456,458,463,470,473,474,475,476,477],customadapt:99,customari:[178,389,440,461,465],customerror:186,customformatterfactori:266,customis:[440,470],customiz:[64,174,456,477],customize_compil:63,cut:[63,81,101,141,147,244,308,392,462,474,476],cutoff:180,cuu1:169,cuu:169,cve:[28,365,477],cwd:[221,374,474],cwi:[60,83,240,241,339,348,360,411,467],cx_freez:[88,293],cxx:[82,381],cyan:[93,169,463],cycl:[24,54,55,60,77,79,81,88,90,96,99,204,225,253,258,380,401,416,440,447,450,463,471,473,475,476,477,478],cyclic:[3,27,44,55,60,88,90,303,427,437,440],cygwin1:107,cygwin:[69,304,380,458,469,471,473],cygwinccompil:63,cygwincompil:69,cypher:150,cyril:[104,150],cyru:246,cython:[81,82,92],czotter:322,d380000000000p:368,d_file_offset_bit:319,d_fmt:264,d_largefile64_sourc:319,d_t_fmt:264,dad:473,daemon:[98,99,106,267,293,330,358,360,361,365,391,473,476],daemon_thread:361,daft:99,dai:[17,77,83,87,101,102,106,140,161,174,260,264,267,304,363,365,392,404,435,446,462,464,470,473,475,476,477],daili:[96,462,472],daisi:452,dale:473,dalk:[103,438,472,473,475],damag:[26,384,438],damien:476,damn:102,dan:[474,475],danc:453,danger:[26,30,52,88,95,104,216,293,303,304,338,365,445,471,474,475],dangl:[77,80,369,439],daniel:[473,476,477],danish:150,dare:360,dark:[244,472],dart:403,darwin:[28,380,392,470,476],dash:[143,169,200,423],dashrepl:333,dat:[72,188],data1:[241,311],data2:[241,311],data:[4,6,11,18,27,28,30,37,42,43,45,48,50,51,55,56,57,60,65,69,71,73,76,77,80,82,83,89,90,91,92,93,94,95,99,101,103,107,113,117,118,119,120,123,124,125,126,127,132,134,135,136,137,139,140,142,143,144,149,150,152,158,161,162,163,167,169,170,171,174,175,177,178,188,194,195,200,201,202,205,206,207,209,212,213,215,221,222,226,227,230,234,235,236,239,240,241,243,244,246,247,248,252,253,255,256,258,259,260,264,265,270,271,273,274,275,276,280,281,286,287,290,292,293,296,299,301,303,304,306,308,312,314,316,317,319,322,326,328,330,333,338,339,345,348,350,352,355,356,357,358,359,360,361,364,365,366,368,369,370,371,372,374,376,377,378,381,384,385,386,387,390,391,392,394,395,399,401,403,404,405,406,407,409,410,411,413,414,417,418,422,423,425,426,427,428,429,430,431,432,433,434,435,436,437,438,442,444,446,450,451,454,456,460,461,464,470,471,472,473,475,476,477,478],data_fil:[63,72,73],data_struct:476,data_to_send:99,databas:[1,60,76,83,101,104,106,138,162,167,169,174,188,226,229,243,252,264,281,310,311,322,333,350,371,372,391,392,394,396,401,407,408,410,421,446,450,462,463,471,472,473,475,476,477],databaseconnect:[475,476],databaseprogram:87,datafil:[392,473],datagram:[361,365,463],datagramhandl:[60,98,120,266],datagramrequesthandl:361,datas:142,dataset:[94,103,158,236,346,474],datasourc:427,datastream:311,datatyp:[60,88,168,173,178,243,252,260,463,474,476,477,478],date1:174,date2:174,date:[17,28,60,63,69,76,87,106,107,132,140,156,162,173,186,192,203,252,264,265,266,267,273,299,302,315,339,363,364,365,384,392,409,434,435,436,446,456,461,463,465,470,474,475,476,478],date_str:174,date_tim:[246,435],date_time_str:132,datefmt:[98,99,265,266],datestr:246,datetim:[15,60,88,140,173,252,254,316,364,365,369,392,404,462,465,473,474,475,476,477],datetime1:174,datetime2:174,datum:[442,447],dave:[103,473,474,477],david:[96,230,438,469,470,471,472,473,474,476,477],day_1:264,day_7:264,day_abbr:140,day_nam:140,daylight:[174,203,339,392],days_to_go:174,db2_dump:87,db2_load:87,db2pickl:[83,473],db2picklei:83,db77e160355:[415,475],db_connect:[475,476],db_dump185:87,db_load:87,db_row:364,db_transact:[475,476],dbc:[56,150],dbcursor:418,dbenv:138,dbfilenameshelf:350,dbhash:[60,121,138,252,310,350,420],dbl_dig:380,dbl_epsilon:380,dbl_mant_dig:380,dbl_max:[22,380],dbl_max_10_exp:380,dbl_max_exp:380,dbl_min:[22,380],dbl_min_10_exp:380,dbl_min_exp:380,dbm:[60,87,138,252,310,311,350,440,477],dbmlibord:477,dbopen:138,dbsequenc:138,dbshelv:476,dc1:170,dc2:170,dc3:170,dc4:170,dcab:457,dcba:473,dcgettext:[230,264],dcmp:208,dct:260,ddd:[88,217],dddddddddddddddddddd:321,ddde:217,ddir:156,ddthh:174,de_d:[174,264],deactiv:[212,219,380,396],deactivate_form:212,dead:[102,293,321,451,452,473],deadlock:[28,87,189,190,205,293,304,317,374,380,391,476],deaf:361,deal:[6,14,15,30,37,72,76,87,88,90,95,100,101,102,104,123,149,150,192,194,211,217,240,241,256,264,291,293,303,317,343,348,396,403,438,451,457,470,472,473,474,475],deal_with_cli:365,dealloc:[6,24,30,45,50,55,77,79,81,90,225,418,447,471,472,477],dealt:[79,102,149,303],death:102,deb:474,debian:[64,82,107,185,221,315,468,470,471],debug:[27,28,55,60,69,71,79,81,88,90,93,95,98,99,100,101,106,107,125,134,145,168,178,179,199,215,221,225,241,246,252,254,265,266,267,288,293,299,303,309,311,313,315,318,333,338,351,357,358,364,368,380,384,385,394,395,407,429,434,435,440,441,446,447,457,462,463,466,468,470,471,472,473,475,476],debug_collect:225,debug_inst:225,debug_leak:225,debug_object:225,debug_print:63,debug_saveal:225,debug_src:186,debug_stat:225,debug_uncollect:225,debugg:[27,60,77,81,177,186,206,244,252,269,335,380,407,440,451,469,472,473,475,476,477],debuggingserv:[60,254],debuglevel:[241,385,410],debugrunn:186,debugstr:269,dec:[28,88,96,102,174,216,218,221,276,462,472,473],decatur:96,decemb:[83,174,446,462,472,473],decent:[102,269,460],decept:[304,473],decid:[79,81,83,88,96,98,100,102,106,134,149,162,169,174,186,225,361,364,391,447,461,475,477],decim:[16,52,56,60,81,88,90,101,104,125,152,170,174,217,218,222,240,252,260,264,266,301,303,322,333,348,368,369,380,391,392,398,406,407,442,455,456,457,460,465,470,475,476,477,478],decimal_point:264,decimalexcept:178,decimalinteg:446,decimaltupl:178,decis:[90,100,102,149,401,447,470,474,475,477],decistmt:398,deck:152,decl:240,declar:[4,28,30,51,55,60,62,63,72,77,79,81,87,88,89,90,96,104,114,117,141,152,164,168,184,222,240,256,266,270,282,292,303,328,348,351,361,364,379,419,425,426,427,429,431,432,440,441,447,450,451,459,473,475,476,477],declassifi:101,declhandl:431,deco:474,decod:[13,50,56,60,99,100,104,124,129,131,135,150,161,167,168,192,193,197,198,199,200,201,203,206,209,222,227,247,252,256,280,283,284,292,295,312,359,360,364,365,368,384,392,409,434,457,460,462,465,470,472,474,475,476,477],decode_base64:283,decode_func:470,decode_head:[198,203],decode_param:[192,203],decode_rfc2231:[192,203],decoded_seq:198,decoded_str:198,decodedgener:[192,197],decodestr:[131,150,331],decompos:[4,83,96,406],decomposit:[83,406],decompress:[135,139,150,210,234,259,417,425,437,462,475],decompressobj:437,decompressor:[139,259,437],deconfigur:98,deconstruct:4,decor:[60,88,90,99,114,128,157,160,222,223,292,368,407,439,442,443,475,477,478],decorated_foo:99,decorator_list:125,decoupl:463,decreas:[3,236,392,470,474,477],decref:[30,55,56],decrement:[4,21,30,45,50,55,77,79,81,88,191,293,309,353,391,440],decrypt:[365,435],dedent:[123,244,389,397,439,443,446],dedic:[28,99,186,365],deduc:[55,167,186,293,322,384,469],deed:101,deem:[52,92,202,230,265,267,311,333,337,338,368,423,438,470,471,475,477],deep:[60,64,72,90,173,245,252,311,321,351,380,426,427,462],deepcopi:[88,152,163,477],deeper:[94,105,184,186,321,369,380],deepli:[98,163,388,463,470,476],def:[19,30,52,58,60,76,77,79,82,87,88,89,90,94,95,96,98,99,101,102,103,104,106,107,109,110,114,123,125,126,127,128,129,132,137,151,152,157,158,160,162,164,165,167,168,174,178,180,182,186,193,208,222,223,228,230,231,236,240,244,249,251,253,258,260,265,266,273,292,293,300,302,303,308,311,326,328,330,333,334,335,338,343,352,353,355,358,361,364,365,366,368,369,377,379,384,387,388,389,391,393,396,398,400,403,404,407,416,418,423,427,429,434,439,440,442,443,446,447,451,452,453,454,458,461,462,463,470,471,472,473,474,475,476,477],def_prog_mod:169,def_shell_mod:169,default_account:152,default_buffer_s:256,default_bufs:428,default_domain:298,default_factori:152,default_format:384,default_logging_config_port:266,default_mod:168,default_namespac:[429,477],default_open:410,default_pip:204,default_tcp_logging_port:[99,266],default_tim:393,default_udp_logging_port:266,default_valu:92,defaultcontext:178,defaultcookiepolici:[60,254],defaultdict:[60,90,173,368,475],defaultdir:290,defaulthandl:328,defaulthandlerexpand:328,defaultloc:191,defaultoptionflag:191,defaultsizetestcas:407,defaulttest:407,defaulttestload:407,defaulttestresult:407,defaultverifypath:365,defaultwidgetsizetestcas:407,defcount:58,defeat:[88,101,416,440],defect:[60,192,200,202,295,474],defenestr:452,defer:[55,60,98,186,242,256,267,364,396,471,476],defghi:152,defi:473,defici:[1,339,376,417],defin:[3,4,6,8,11,13,14,20,24,26,28,29,30,31,37,39,44,50,51,52,55,56,60,62,63,66,71,72,73,75,76,77,78,80,81,82,83,87,89,90,92,93,94,95,96,98,99,100,101,103,104,105,106,107,113,114,115,116,117,118,119,120,123,124,125,126,128,129,131,132,134,135,136,138,141,142,143,144,146,147,148,150,152,154,155,157,158,160,161,162,163,164,167,168,169,171,174,176,178,181,182,185,186,188,191,192,196,197,200,205,206,207,208,215,216,217,219,221,222,223,225,226,227,230,231,233,234,235,236,239,240,241,243,244,245,246,247,248,249,251,253,255,256,258,259,260,261,263,264,265,267,269,271,273,276,277,280,281,282,283,284,293,294,297,298,299,300,301,302,304,306,308,309,311,313,315,316,317,318,319,320,321,322,323,324,326,328,330,331,332,333,334,336,337,339,340,342,343,345,346,347,348,349,351,353,354,358,360,361,363,364,365,366,367,368,369,371,373,374,376,377,378,380,381,382,384,386,387,388,390,391,392,393,394,396,397,399,400,401,402,403,404,406,407,409,410,411,412,413,414,415,416,417,419,423,424,425,426,427,429,430,431,434,435,436,438,439,440,441,442,445,446,447,449,450,451,456,458,460,461,463,465,470,471,472,473,474,475,476,477],define_macro:[63,72,75,470],definit:[12,26,30,51,52,55,60,63,72,73,77,78,79,88,90,93,101,114,115,123,131,134,140,150,152,168,169,174,182,206,212,215,222,223,227,230,241,244,252,265,267,275,290,300,303,311,322,327,329,338,342,348,358,368,369,378,380,385,389,392,397,403,405,406,407,409,415,424,425,426,427,430,438,440,441,442,444,445,446,447,452,453,456,461,471,472,473,474,475,476,477],deflat:437,defmacro:96,defparamet:439,defpath:304,defstat:472,deftyp:231,defunct:28,defus:[60,275],defusedexpat:425,defusedxml:425,deg:[88,473],dega:315,degener:368,degrad:169,degre:[77,169,277,403,440,473],degree_sin:88,deiconifi:244,deili:477,deiniti:[93,169],del:[35,43,47,51,60,77,79,88,94,125,151,152,157,170,182,200,222,225,230,236,244,253,273,293,302,303,304,305,308,311,334,339,350,368,404,418,440,441,442,443,444,446,451,456,458,463,470,471,473,475,476,477],del_param:200,del_stmt:[443,447],delai:[20,87,93,169,244,253,267,293,320,343,353,360,403,409,410,440,461,476],delattr:[222,451,461],delawar:365,delay_output:169,delayfunc:343,delayload:162,delch:169,dele:318,deleg:[37,98,99,127,222,265,266,300,311,342,407,440],delet:[5,33,43,45,47,51,52,55,56,60,77,79,81,90,94,95,99,101,111,113,121,125,126,127,134,142,152,157,167,169,170,171,180,182,200,201,206,210,212,213,221,222,226,236,244,246,267,273,279,293,302,304,309,318,350,352,364,366,368,369,376,377,380,386,388,391,396,401,403,404,416,418,423,437,439,440,441,446,447,449,451,453,458,467,472,473,475,476,477,478],delete_attr:182,delete_browser_lin:212,delete_choic:212,delete_fast:182,delete_glob:182,delete_nam:182,delete_nth:152,delete_object:212,delete_slic:182,delete_subscr:182,deleteacl:[246,474],deletechar:[368,369],deletefilehandl:396,deletefold:279,deletekei:113,deletekeyex:[113,477],deleteln:169,deletem:134,deletepars:142,deletesomethingdb:407,deletevalu:113,deliber:[86,88,123,303,318,407,465],delic:[28,55],delight:87,delim:138,delimit:[28,52,60,63,81,88,90,101,102,143,167,186,197,244,246,253,273,292,299,303,333,334,339,348,368,369,374,396,398,411,444,463,469,473],delitem:302,deliv:[98,105,174,222,345,353,358,401,442,452,476],deliver_challeng:293,deliveri:[192,193,200,202,273,304,360],delphi:81,delslic:302,delta:[60,129,174,182,241,252,293,372,407,472,474,477],delx:[94,222],demain:476,demand:[37,158,293,303],demis:452,demo:[60,75,76,77,91,93,99,169,244,249,251,355,394,395,396,405,423,427,462,473,476],demo_app:423,demonstr:[70,75,77,79,91,92,101,102,114,128,157,161,168,178,215,216,287,293,303,321,333,334,341,352,364,396,399,400,401,403,407,429,440,442,452,453,457,460,462,471],demoscript:403,deni:[133,205,361,473],denial:[425,465],denmark:470,denomin:[218,300,368,476],denot:[40,54,60,83,104,144,161,182,304,336,365,368,396,409,440,442,446,447,451,453,470,476],dep_util:69,depart:[152,222,368,438],depend:[5,13,16,28,30,46,51,55,56,60,62,64,69,72,75,76,77,79,80,81,82,83,84,86,87,88,89,90,93,94,96,98,99,101,102,103,104,106,107,108,113,127,134,139,140,142,143,148,150,157,161,162,165,168,169,174,178,180,184,186,194,204,207,210,215,221,222,225,230,234,235,244,249,253,254,256,258,264,265,266,267,271,273,277,288,290,292,293,304,311,322,323,324,330,332,333,336,337,345,350,352,353,358,360,361,364,365,366,367,368,369,371,373,374,376,380,381,384,385,386,387,388,390,392,393,396,401,403,404,407,410,412,417,418,422,423,429,431,434,437,440,441,442,446,447,451,454,460,461,463,464,465,468,470,471,472,473,474,475,476,477],deploi:[106,198,239,240,348,396,467],deploy:[87,98,106,304],deprec:[6,11,16,20,22,37,42,43,47,51,55,60,72,91,92,101,109,119,124,133,138,139,141,142,143,150,155,157,160,161,168,173,175,179,181,185,186,192,196,197,200,201,202,206,212,213,217,222,231,239,241,244,245,247,251,256,259,268,271,278,279,280,282,283,292,294,295,297,299,302,303,304,305,313,315,317,320,328,338,339,346,348,349,365,367,368,371,372,373,377,380,384,386,388,391,392,396,400,403,405,409,412,413,414,416,429,439,440,442,469,471,472,475,478],deprecationwarn:[20,104,160,192,206,373,388,416,461,465,471,473,477],dept:451,depth:[20,43,98,156,158,169,171,197,200,292,311,321,335,368,380,384,394,407,429,440,451,452,456,470,471,472],dequ:[60,173,258,330,418,442,453,463,474,475,476,477],dequeit:258,der:[365,415,476],der_cert_byt:365,der_cert_to_pem_cert:365,derefer:[293,384],dereferenc:[14,168,225,418],deregist:293,derek:477,deriv:[10,20,28,43,54,60,64,68,79,81,90,94,104,107,114,123,125,134,149,150,158,161,166,168,169,170,174,187,192,196,197,198,206,215,222,230,239,240,246,253,256,265,274,279,292,297,299,303,305,311,321,322,324,327,328,346,348,361,365,369,403,407,410,413,415,416,418,423,424,427,432,434,438,440,446,451,454,470,473,474,475,476,477],derivedclassnam:451,dershowitz:[140,174],derwin:169,desc:[11,251,290],descend:[60,98,114,125,156,253,265,293,322,366,383,401,426,427,429,451,465,475,477],descr:[18,92,94,168,191],descrgetfunc:[55,79],describ:[1,4,10,12,15,18,20,21,26,27,30,42,43,44,51,52,54,55,58,63,64,67,69,71,73,76,77,78,79,80,81,83,90,93,96,98,99,104,105,106,107,108,109,113,118,119,120,122,123,126,131,134,141,142,143,144,150,152,157,161,166,167,168,169,172,173,178,179,180,186,191,192,194,198,200,206,208,209,211,212,215,217,219,220,221,222,230,237,239,241,242,243,246,248,249,252,253,254,255,256,257,260,264,265,266,267,268,270,273,281,285,286,289,290,295,300,301,303,304,306,308,310,311,317,319,320,322,326,328,329,330,331,332,333,335,336,338,342,345,346,347,348,352,358,359,360,362,364,365,366,368,369,372,373,374,375,377,380,383,386,390,391,392,394,396,401,403,407,408,410,411,414,421,422,423,424,426,429,430,432,434,435,436,437,439,440,442,444,445,446,447,448,451,452,453,454,456,457,458,459,460,461,465,469,470,471,472,473,474,475,476,477],descript:[1,4,6,11,20,46,51,56,60,63,64,71,72,73,75,78,91,93,94,98,107,111,118,120,126,127,129,138,141,157,163,167,168,169,180,186,187,191,192,197,198,200,205,207,211,212,219,222,230,249,253,264,265,266,269,270,275,287,299,303,304,306,308,309,311,327,352,353,360,364,365,368,370,373,376,377,382,385,387,388,392,394,396,401,403,407,409,416,417,424,430,431,434,440,441,442,445,447,452,456,465,470,471,472,473,474,475,477],descriptor:[15,20,26,28,43,55,60,79,81,84,87,90,97,115,117,119,120,127,168,169,205,207,210,238,246,253,256,266,268,279,287,291,293,305,306,320,323,326,336,345,353,360,361,368,374,377,384,385,386,387,396,402,404,439,442,447,474,475,476,477],descrobject:94,descrsetfunc:[55,79],deselect_brows:212,deselect_browser_lin:212,deseri:[260,457,477],deserv:[273,461,470],design:[30,60,62,64,71,83,85,87,88,89,90,94,96,98,99,100,102,104,105,106,107,108,116,117,135,137,145,150,152,158,169,174,178,183,186,192,197,204,222,228,230,235,237,239,252,256,273,276,282,284,292,303,304,307,322,331,337,338,340,346,347,360,364,365,384,388,391,394,396,411,423,429,433,434,437,450,451,453,461,463,470,471,472,473,474,475,476,477],desir:[28,30,37,50,77,81,88,93,96,98,99,101,106,107,113,123,142,150,168,169,180,205,215,222,231,235,236,239,240,264,273,274,281,287,303,305,309,311,321,332,333,334,338,361,365,368,369,388,389,391,394,396,401,403,407,409,418,432,435,440,442,452,453,454,461,470,472,473,474,475,476,477],desk:[98,450,460],desktop:[64,72,104,419,469],despit:[76,88,90,102,141,260,365,462,476],dest:[60,91,120,125,157,193,228,287,303,473,475,476,477],dest_nam:63,destdir:[156,271],destin:[60,63,98,104,169,205,245,265,266,273,279,287,303,352,360,382,474,476],destr:11,destroi:[8,28,53,55,59,81,96,102,113,219,256,287,303,369,377,386,391,396,407,418,440,470,472,473,475],destruct:[28,77,79,148,169,253,256,368,440,471],destructor:[8,11,28,55,79,81,87,92,390,440,447],destwin:169,desultori:79,detach:[113,256,304,401],detail:[1,12,16,21,27,48,55,56,58,60,62,63,64,68,71,72,75,76,77,78,79,80,81,82,83,87,88,89,90,91,93,94,95,96,97,98,99,101,104,105,107,109,110,113,116,119,120,123,129,132,133,134,136,143,145,164,165,167,168,169,174,177,178,180,182,184,186,191,192,197,200,202,206,207,213,216,219,222,230,231,242,243,244,249,253,259,260,273,274,276,277,290,302,303,304,308,311,312,332,333,336,341,342,351,358,360,361,364,366,368,369,373,374,377,380,382,384,385,388,389,391,396,400,404,407,410,416,418,423,426,431,434,435,439,440,441,442,444,445,447,449,450,451,453,454,455,460,463,464,465,467,469,470,471,472,473,474,475,476,477],detect:[21,24,30,36,43,52,55,60,63,77,79,81,88,90,96,101,102,105,109,127,128,150,157,167,169,174,178,182,206,212,222,231,240,248,252,262,273,277,303,304,305,306,311,321,328,334,351,364,365,368,380,389,391,407,409,410,419,423,440,441,442,446,448,454,465,470,471,472,473,476,477],detect_languag:63,detect_typ:364,detector:[3,54,77,253,440,477],determin:[1,3,4,8,19,20,29,30,34,43,47,60,63,72,77,79,88,90,93,98,100,101,102,103,104,106,107,113,121,123,124,127,134,142,143,147,149,150,151,168,169,171,174,175,176,178,180,185,186,188,191,207,222,226,230,241,246,252,253,256,260,261,264,265,266,267,273,274,277,282,286,288,293,297,303,304,306,308,309,311,315,317,321,322,326,328,333,334,335,337,345,346,348,350,351,360,364,368,369,371,373,374,377,380,381,382,384,387,392,393,396,398,401,403,407,409,410,415,416,426,431,437,439,440,441,442,445,446,447,451,452,453,454,461,472,473,475,476,477],determine_par:251,determinist:[60,101,177,253,332,360,385,453],detlef:[470,473],deutsch:438,dev:[82,83,99,142,181,212,229,263,267,273,274,304,306,353,377,443,449,470,471,472,473,474,475,476,477],dev_stag:315,dev_team:266,devel:82,develop:[0,1,28,60,62,64,69,70,72,79,80,81,84,86,88,89,90,98,100,101,104,106,107,108,143,152,160,168,177,178,244,252,262,265,266,267,270,303,307,364,374,380,388,394,396,403,416,429,434,435,438,450,452,456,462,467,468,469,471,472,473,474,475,477,478],developerwork:96,devguid:91,deviat:[56,100,332,393,411],devic:[58,60,63,88,90,113,119,142,150,169,170,205,215,222,236,245,252,256,267,286,304,305,307,345,347,352,353,366,368,374,375,384,405,446,448,459,465,470,476],devis:332,devnul:[293,304],devot:[88,101,466],dez:174,dezemb:174,dfballer:200,dfile:325,dfoo:63,dgettext:[230,264],dhfile:365,diaeresi:150,diagnos:[81,88,98,308],diagnost:[28,79,98,296,383,423,434],diagon:104,diagram:[67,98,186,222,236,361,472],dial:212,dialect:[60,209,364,473,475],dialog:[60,80,212,219,227,244,252,268,290,303,394,396,405,469],dialogwindow:[60,268],diamet:403,diamond:[60,169,222,440,451],dice:201,dichotomi:100,dickinson:[476,477],dict1:476,dict2:476,dict:[10,19,20,26,30,50,52,55,60,77,81,82,87,88,90,94,96,106,109,123,125,152,157,158,163,167,173,174,186,222,225,252,253,260,265,266,273,279,293,297,311,316,350,365,369,380,401,404,407,413,418,434,440,442,447,451,452,453,457,461,463,465,470,472,473,474,475,476,477],dict_comprehens:442,dict_displai:442,dict_factori:364,dict_fromkei:94,dict_get:88,dict_kei:477,dict_typ:158,dictat:[6,90,220,222,328,451,470,476],dictcomp:125,dictconfig:[60,98,266,477],dictconfigclass:266,dictconfigur:266,dictionari:[4,10,15,18,20,23,26,28,30,37,39,43,46,51,55,56,58,60,63,72,77,79,87,90,94,95,96,98,103,105,109,115,116,120,121,123,127,132,133,138,143,149,150,152,158,161,163,165,167,168,173,174,176,178,182,186,188,193,194,200,201,205,206,208,219,222,223,226,227,230,236,239,241,243,251,252,253,260,264,265,267,270,273,274,276,279,281,284,288,293,296,297,298,302,303,304,309,311,312,316,319,321,322,326,328,333,337,338,339,342,346,350,354,358,364,365,369,371,378,380,381,384,388,390,391,394,396,397,399,401,403,404,407,409,410,411,416,418,423,429,432,433,439,440,441,447,450,451,452,456,457,463,470,471,472,473,474,475,476,478],dictionarytyp:404,dictit:258,dictmixin:[188,350,413,440,473],dictobject:[94,475],dictoffset:55,dictorsetmak:443,dictproxi:222,dictproxytyp:404,dictread:167,dicttyp:[19,404],dictview:[90,368],dictwrit:167,did:[1,3,43,55,73,79,91,100,101,102,105,162,186,198,265,296,303,304,328,333,351,364,365,380,386,410,413,431,439,453,460,470,471,472],didn:[79,82,88,91,92,93,100,101,104,127,140,303,333,358,364,368,470,471,472,474,475,476,477],die:[60,345],died:[102,317],diederich:475,diego:475,dierk:365,dies:93,dietmar:471,diff:[100,109,180,186,407,471,474,477],diff_fil:208,differ:[14,28,30,37,43,50,51,55,56,58,60,63,64,68,70,71,72,75,76,77,78,79,81,82,83,86,87,89,90,91,92,93,94,96,98,99,101,102,103,104,105,106,107,109,113,123,124,125,126,127,129,138,141,142,143,148,149,150,151,152,162,163,164,165,167,168,169,174,178,186,194,198,200,208,212,219,221,222,223,224,227,230,235,236,237,241,243,249,255,256,257,258,264,265,266,267,269,273,274,276,277,281,287,290,293,295,300,302,303,304,305,306,307,308,309,311,314,315,317,322,327,328,330,332,333,334,335,336,337,339,346,348,350,351,353,355,358,360,361,364,368,369,370,372,373,374,377,380,381,384,386,388,389,391,393,394,395,396,400,401,404,407,409,410,411,412,423,426,427,435,439,440,441,442,445,446,447,451,452,453,454,455,460,461,462,463,465,466,467,468,469,470,471,472,473,474,475,476,477],difference_upd:[346,368,476],differenti:[178,222,334,409],diffi:365,difficult:[62,68,72,79,83,87,93,96,98,100,101,104,106,123,127,219,236,266,359,409,418,463,470,471,472,473,474,477],difficulti:[81,100,293,470,473],difflib:[60,186,208,252,372,471,472,474,475,476,477],dig:[217,311,380],digest:[60,91,166,199,200,237,252,293,318,410,475,477],digest_s:[235,237,278,349],digestmod:237,digicert:365,digicertsha2extendedvalidationserverca:365,digit:[29,30,34,52,56,67,81,88,101,102,104,118,129,131,135,142,150,152,161,170,174,178,186,217,218,221,222,235,237,259,264,266,278,299,304,333,335,349,365,368,369,380,386,392,393,396,406,407,409,410,415,437,438,446,455,465,470,474,475,476,477],dijkstra:391,dim:[125,169,219],dima:474,dimens:[6,168,169,231,368,476],dimension:[6,231,332,368,394,403],diminish:108,ding:303,dinsdal:106,dionn:474,dir1:208,dir2:208,dir:[43,60,63,64,66,72,73,81,83,88,89,95,107,109,156,158,176,188,204,221,222,253,264,280,293,303,304,340,368,374,386,394,399,435,456,462,473,476],dir_util:69,dircach:[60,211,252,474,476],dircmp:[60,211,470,475],direct:[15,28,30,56,60,62,63,76,77,81,88,94,106,107,108,109,110,117,119,125,140,147,150,152,168,174,178,179,210,215,219,222,270,279,284,303,319,321,322,328,365,368,380,386,389,390,392,393,401,403,410,413,426,429,433,438,440,447,451,453,462,463,470,472,473,475,476,477,478],directive_opt:186,directive_option_nam:186,directli:[6,12,24,26,28,37,39,40,43,51,52,55,56,59,63,64,68,72,76,77,79,83,86,87,88,89,90,94,98,99,100,103,105,106,108,110,114,123,132,135,138,143,150,151,156,160,163,167,168,174,178,180,182,184,186,191,200,201,203,204,205,206,215,218,222,223,225,236,239,241,244,256,260,264,265,266,273,287,293,303,304,305,306,317,319,322,333,334,339,344,350,354,355,358,361,364,365,368,369,374,384,386,388,391,394,396,399,401,405,407,409,410,413,418,423,426,429,430,433,440,441,442,445,449,451,452,453,454,460,461,462,463,465,469,470,472,473,475,476,477],director:410,directori:[28,30,60,64,66,67,68,69,70,72,73,75,76,77,79,81,82,83,87,88,89,91,96,104,107,109,120,143,144,145,155,156,158,169,180,186,188,193,204,205,212,214,221,222,230,232,244,246,249,252,256,273,288,293,296,299,303,305,309,314,319,324,325,327,334,337,338,342,351,354,356,365,366,368,374,380,381,383,384,388,394,396,399,403,407,409,410,412,419,421,435,436,438,447,449,456,459,462,465,468,469,470,471,473,474,475,477,478],directory_cr:64,diritta:475,dirk:364,dirlist:394,dirnam:[95,221,273,293,304,305,314,407],dirpath:304,dirselectbox:394,dirselectdialog:394,dirti:101,dirtre:394,dirtyp:384,dis:[60,90,252,262,312],disabl:[20,28,30,63,64,73,77,87,98,107,109,113,123,133,134,143,167,169,178,180,186,197,210,219,221,222,225,238,241,244,253,256,265,266,267,293,303,309,322,337,338,345,351,353,356,358,360,363,364,365,374,388,396,401,403,407,409,410,435,449,465,470,471,472,473,474,475,476,477],disable_existing_logg:[98,99,266],disable_interspersed_arg:[123,303],disable_nagle_algorithm:477,disablereflectionkei:[113,476,477],disablesev:345,disadvantag:[77,79,87,88,101,150,178,365,393,472],disagr:81,disagre:[96,409,470],disallow:[81,104,123,311,338,360,364,368,436,476],disambigu:[8,442],disappear:[55,77,79,89,98,102,472,474],disassembl:[60,252,262,312],disc:[142,403],discard:[30,33,48,50,56,58,77,90,96,102,126,131,143,149,152,157,162,174,178,191,256,265,273,293,296,303,339,346,357,368,370,377,387,401,407,416,418,427,429,432,439,460,465,472,475,476,477],discard_buff:126,discern:234,disciplin:81,disclaim:[221,299,376,417,438],disclos:438,disco:182,disconnect:[60,113,318,358],discontigu:6,discourag:[72,96,150,216,365,374,386,388,407,472,475],discov:[89,100,102,161,174,200,339,388,407,431,471,472,473,477],discover:326,discoveri:[60,179,186,358,434],discrep:[95,314],discret:[166,215,286,361],discrimin:348,discuss:[15,28,30,76,77,79,83,88,96,101,104,105,107,163,174,180,206,216,230,256,265,266,277,304,311,333,350,365,407,409,426,434,437,446,447,451,453,457,470,471,472,475,476,477],disentangl:96,disguis:[104,319,333,440],dish:368,disjoint:[346,368],disk0s2:477,disk:[87,89,90,96,98,104,113,138,139,141,162,175,188,206,211,226,236,241,256,263,267,273,287,290,304,306,310,336,338,350,364,368,386,429,435,473,475,476],dislik:105,dispatch:[81,88,98,102,123,126,127,132,134,148,157,169,219,284,322,335,357,407,434],dispatch_:134,dispatch_cal:134,dispatch_except:134,dispatch_lin:134,dispatch_return:134,dispatcher_with_send:127,displai:[60,64,69,83,89,91,101,104,106,120,123,125,143,145,148,149,158,159,171,178,186,191,215,219,244,245,252,253,264,265,273,290,304,309,321,327,333,334,366,369,371,374,380,384,389,393,394,396,398,399,400,401,403,407,410,416,419,438,440,447,452,454,455,460,463,465,470,472,473,474,475,476,477,478],displaycolumn:401,displayhook:[380,461,471],displaymatch:333,dispos:[30,77,360,407],disposit:[193,200,246,304,416,423],disrupt:83,dissect:[101,255,471,472],dissent:[90,470],dist:[64,68,69,72,315,403,475],dist_fil:68,distanc:[147,396,403],distant:[90,457],distb:182,distclass:63,distcmd:68,distinct:[14,30,37,60,63,81,90,93,100,101,102,104,129,152,157,174,178,186,222,252,258,266,277,280,295,303,308,322,332,356,365,368,396,423,442,454,457,470,472,476],distinguish:[51,55,63,70,72,77,90,92,125,147,162,169,186,192,256,266,277,328,365,381,401,440,442,454,460,469,471,472,477],distnam:[107,315],distort:403,distract:[93,303],distribut:[0,26,28,30,56,58,60,65,66,70,71,76,77,78,79,80,83,84,87,88,89,90,92,101,107,108,169,178,180,184,192,216,221,227,230,249,251,252,270,273,293,308,314,315,332,364,378,381,384,394,396,397,403,430,438,456,458,461,464,466,468,469,470,471,473,475,476,477],distribution_nam:64,distributionmetadata:72,distributor:[70,365],distro:[315,468],disturb:339,distutil:[60,62,64,66,67,69,72,73,77,78,79,80,89,108,183,252,290,356,381,465,467,469,471,475,476,477,478],distutils2:477,distutils_debug:72,distutils_use_sdk:63,distutilsexecerror:63,distutilsfileerror:63,ditch:463,dither2grey2:245,dither2mono:245,dither:245,div:[96,125,157,178,216,240,302,355],dive:469,diverg:[365,472],divid:[41,87,90,93,101,129,142,178,182,186,218,277,292,322,332,394,434,446,454,476],divide_int:178,dividend:[14,178],divis:[41,56,58,60,88,90,99,111,135,174,178,182,206,216,222,302,368,440,441,442,447,453,454,460,465,473,474,476,477,478],division_new:380,division_warn:380,divisionbyzero:[178,474],divisor:[14,178,218,460],divmod:[41,178,222,300,368,440,442,455,461],dixon:193,django:[60,99,309,477],djgbxn:293,dklen:235,dl_export:473,dl_import:473,dle:170,dlfcn:380,dlg:[60,268,290],dlgclass:394,dll:[28,60,70,77,78,79,87,107,120,267,380,394,396,470,475,476],dllcanunloadnow:168,dllexport:[80,89],dllgetclassobject:168,dllhandl:380,dllname:[107,267],dlltool:107,dlltype:168,dlobject:185,dlog:[191,219],dlopen:[168,185,380,472,475],dmajor_vers:75,dmaxcol:169,dmaxrow:169,dmesg:374,dmincol:169,dminor_vers:75,dminrow:169,dmitri:474,dml:364,dname:63,dnd:396,dndebug:[75,76],dngettext:230,do_:[88,132,148],do_about:219,do_activ:219,do_bar:[88,148],do_char:219,do_clear:134,do_command:169,do_contentclick:219,do_controlhit:219,do_dialogev:219,do_encod:92,do_ev:212,do_foo:[88,148],do_form:212,do_get:[144,354],do_handshak:365,do_handshake_on_connect:365,do_head:[144,354],do_help:148,do_itemhit:219,do_my_adding_stuff:300,do_my_other_adding_stuff:300,do_post:144,do_postclos:219,do_postopen:219,do_postres:219,do_setlocal:264,do_shel:148,do_someth:[21,98,99,143,160,365,407],do_something_us:418,do_spam:132,do_tag:[239,348],do_upd:219,do_work:330,dobb:180,doc:[1,3,20,51,66,75,79,82,83,88,91,92,94,100,101,104,105,113,114,152,157,168,212,222,244,253,297,304,327,365,380,393,396,405,411,419,429,440,458,463,464,468,470,472,473,475,476,477],doc_fil:66,doc_head:148,doccgixmlrpcrequesthandl:[60,254],docfilecas:186,docfilesuit:[186,475],dock:191,docleanup:[407,477],docmd:358,docstr:[3,20,23,51,55,60,79,87,90,125,148,152,157,179,222,223,241,243,244,253,270,327,352,395,398,407,423,439,447,451,452,462,465,470,471,472,473,474,475,476,477],docstringdict:403,doctest:[60,81,83,87,88,101,103,104,105,109,168,174,179,180,208,252,346,388,392,400,407,411,461,462,471,473,475,477],doctestcas:186,doctestfailur:186,doctestfind:[60,179,474],doctestpars:[60,179],doctestrunn:[60,179,474],doctestsuit:[186,407,473],doctyp:[105,240,328,348,410,426,429],doctypenam:328,document:[16,17,20,24,27,30,37,48,55,56,61,62,63,64,69,70,72,75,76,77,78,79,80,82,84,88,90,91,92,93,94,95,97,98,99,100,101,103,104,105,106,107,108,109,110,111,113,115,117,119,123,124,127,132,133,134,138,141,143,148,152,158,162,164,168,169,173,174,179,180,184,186,191,192,194,198,200,202,212,214,218,219,222,223,230,231,243,244,246,252,253,254,256,259,260,264,265,266,267,270,271,273,274,275,280,290,291,293,295,301,303,304,306,307,308,309,311,313,316,319,321,328,336,337,338,349,350,351,358,360,361,364,365,366,368,374,380,384,387,388,389,390,391,392,394,395,396,401,403,405,407,410,411,416,419,425,427,428,430,431,432,433,434,435,436,437,438,440,442,445,446,447,449,450,454,455,456,458,461,462,464,465,466,467,468,469,470,471,472,473,474,475],document_nod:426,document_type_nod:426,documentel:[426,427,470],documentfactori:428,documentfrag:427,documenthandl:[431,432],documenttyp:[60,275,427],docutil:[0,71,72,476],docxmlrpcrequesthandl:187,docxmlrpcserv:[60,252,254,473,475,476],dodg:474,doe:[3,4,6,16,19,20,21,22,26,27,28,29,30,33,37,39,45,47,48,50,51,52,53,55,56,58,59,60,62,63,64,67,71,73,76,77,79,80,87,90,91,93,94,95,96,98,99,100,101,102,103,105,106,107,108,113,114,121,123,126,130,137,138,139,142,143,146,149,152,156,157,158,161,162,163,168,169,171,174,178,180,182,186,188,191,192,193,194,195,200,202,204,206,210,213,214,215,217,218,221,222,224,225,227,228,230,234,236,238,239,240,243,244,245,249,251,253,255,256,258,260,264,265,266,267,271,273,276,281,282,284,287,293,294,299,302,303,304,305,306,308,311,313,314,315,319,322,325,328,332,333,336,338,342,345,346,348,350,355,358,360,361,364,365,366,368,369,370,373,374,376,377,379,380,382,384,386,388,389,390,391,392,396,399,400,401,404,407,409,410,411,413,417,419,422,423,426,427,429,430,431,432,433,434,435,436,438,439,440,441,442,446,447,448,451,452,453,454,456,458,460,461,463,465,467,469,470,471,472,474,475,476,477],doerwald:476,does_esmtp:358,doesn:[4,6,16,19,20,28,30,55,60,63,64,70,72,73,76,77,79,80,82,84,88,89,93,96,98,99,100,101,102,104,105,107,109,113,121,123,125,132,134,139,140,143,150,160,161,162,167,168,174,175,176,180,186,192,193,195,198,200,206,225,226,235,236,244,256,258,260,264,265,273,282,292,300,303,304,309,311,314,318,328,330,332,333,338,339,340,350,356,358,360,364,365,369,380,391,392,393,396,403,406,407,412,416,420,423,425,434,436,437,438,440,442,452,457,459,460,461,468,470,471,472,473,474,475,476,477],dog:[101,152,333,346,451],dogwood:333,doing:[1,6,21,31,55,63,71,72,81,82,87,88,90,91,93,96,98,99,100,101,102,103,104,107,127,135,143,151,162,168,178,208,227,249,256,287,288,293,303,304,306,318,333,361,364,365,366,369,386,388,391,392,403,407,440,453,460,461,472,475,476,477],dollar:155,dom1:427,dom2:427,dom3:427,dom:[60,252,275,425,431,462,471,473,475],domain:[60,70,95,98,161,162,205,230,255,264,266,267,293,298,339,358,360,361,371,372,380,415,440,450,473,475],domain_initial_dot:162,domain_return_ok:162,domain_specifi:162,domainliber:162,domainrfc2965match:162,domainstrict:162,domainstrictnodot:162,domainstrictnondomain:162,domenu_:219,domeventstream:[60,275],domexcept:[426,427],domimplement:[60,275,427],domin:[137,162],domstr:[426,427],domstring_size_err:426,domstringsizeerr:426,domtimestamp:427,don:[1,4,5,7,16,20,24,28,30,41,43,50,51,55,63,64,66,67,70,72,73,75,77,79,81,82,83,84,86,89,90,91,92,93,95,96,98,99,100,101,102,103,104,106,107,113,123,125,134,143,145,146,147,151,156,158,162,163,168,171,174,180,182,186,193,203,208,212,215,222,230,241,244,255,258,260,265,266,273,277,282,293,303,304,306,309,311,321,322,332,333,339,345,358,364,365,368,369,376,380,391,393,395,396,407,409,412,417,418,423,434,435,437,438,440,442,450,451,452,453,454,455,457,460,461,465,470,471,472,473,474,475,476,477],donald:[152,477],donat:[83,474],done:[1,4,13,21,26,28,30,31,41,43,47,48,55,56,63,64,72,73,75,76,77,79,82,87,88,89,91,93,96,98,99,100,101,102,104,105,106,107,121,123,129,139,142,143,148,150,151,158,167,168,169,174,178,182,186,191,192,193,199,200,208,217,219,222,229,232,236,244,245,247,249,256,264,265,266,270,287,293,303,304,306,311,320,322,328,330,333,339,354,361,364,365,368,369,374,380,384,385,386,387,388,391,392,393,394,401,403,405,409,410,416,418,424,427,429,430,440,442,447,450,451,452,457,458,459,461,463,469,470,471,472,473,475,476],done_queu:293,dong:303,donnel:472,donni:128,donotsepar:351,dont:385,dont_accept_blanklin:186,dont_accept_true_for_1:186,dont_inherit:[157,222],dont_write_bytecod:[380,461,476],doodah:316,dool:469,doom:[293,475],door:[105,123],dorais:325,dorfman:474,dormant:99,dorollov:267,dos:81,dose:104,doseq:409,dot:[20,26,55,63,79,90,92,94,98,99,101,107,157,162,186,222,232,244,249,251,253,258,264,265,266,273,281,284,302,314,327,333,340,360,368,384,386,396,397,403,407,435,436,440,445,447,451,458,459,461,476],dotal:[101,333],dotproduct:258,dotted_as_nam:443,dotted_nam:[439,443],dotview:91,doubl:[4,14,16,22,30,34,51,55,56,63,82,88,90,101,108,124,143,150,152,157,167,168,186,191,203,212,231,235,244,246,260,267,277,293,304,333,339,348,351,368,369,373,374,385,392,424,433,434,438,440,442,446,449,453,455,460,467,473,474,475,476],double_revers:103,doublebuf:212,doublebuff:212,doublelib:157,doublequot:167,doubleslash:397,doubleslashequ:397,doublestar:397,doublestarequ:397,doublestuff:161,doublevar:396,doubli:[30,55,440,477],doubt:[55,87,93,174,475],doubtless:[96,471,472,473],doug:438,dougla:364,doupdat:[93,169,171],dove:[98,99],down:[28,30,66,72,76,79,81,88,89,90,96,98,100,102,106,107,143,169,171,182,186,205,219,236,244,251,265,293,304,309,322,330,333,345,360,361,365,380,391,396,401,403,407,413,440,451,455,458,463,465,470,472,473,477],downcast:[4,30],downgrad:162,download:[60,63,64,70,72,79,83,88,104,106,107,243,394,409,438,440,451,464,467,468,469,475,476,477],download_url:[63,72,475],downsid:106,downward:[90,368],dozen:[72,462,476],dpkg:474,draft:[96,143,273,365,380,426,450,470,471,472,473,474,475,476,477],drag:[60,219,268,307,394,396,401,403,467],dragconst:[60,268],drain:[365,377],drake:[0,443,470,471,472,473,475,476],dramat:[79,88,251],drastic:109,draw:[60,93,148,169,244,307,395,396,401,476],draw_doubl:476,drawabl:476,drawback:[116,195,303],drawn:[104,148,169,213,403],drive:[63,102,107,142,236,303,304,305,384,388,396,407,435,438,469],driven:[63,64,88,102,281,388,407,426,470],driver:[75,113,169,186,205,230,306,388,422,432,473],drop:[24,55,60,62,63,79,83,90,98,104,106,111,152,186,205,212,222,247,252,258,267,268,293,307,318,322,330,335,343,362,365,374,380,389,390,396,401,411,469,470,471,472,474,475,476],drop_whitespac:[389,476],dropdown:401,dropwhil:[96,258],drum:101,drummer:101,drwx:352,drwxr:[91,221],dry:[63,68,303],dry_run:[63,352],dsn:[192,358],dsp:306,dst:[63,168,174,271,304,311,352,392],dstar_arg:157,dstdiff:174,dstend:174,dstend_1967_1986:174,dstend_1987_2006:174,dstend_2007:174,dstname:[174,352],dstoff:174,dstoffset:174,dston:174,dststart:174,dststart_1967_1986:174,dststart_1987_2006:174,dststart_2007:174,dsu:103,dt1:174,dt2:174,dt3:174,dtd:[105,240,328,410,425,431,432],dtdhandler:[60,275,432],dtdst:174,dtl:365,dtoa:[60,477],dtoff:174,dtor:92,dual:[360,438],dubiou:[206,416],duck:[90,476],due:[4,20,55,58,79,81,87,88,95,98,100,105,106,139,150,157,169,180,182,215,218,225,244,256,265,266,273,293,304,308,315,317,328,333,337,364,365,368,374,377,391,407,439,440,442,452,469,470,471,474,476,477],dum:82,dumb:[69,102,188,385],dumbdbm:[60,121,252,310,350],dumbdm:188,dumbwrit:215,dummi:[12,60,77,168,180,230,272,304,362,365,384,391,403,423],dummy_thread:[60,252,362,390,391,473],dump:[72,77,87,98,99,119,125,138,143,161,164,167,222,227,231,260,264,276,296,304,311,322,353,364,366,380,423,429,434,457,465,470,471,472,473,476,477],dump_address_pair:[192,203,339],dump_stat:322,duncan:476,dunn:307,dup2:[304,320],dup:[127,152,304,320],dup_top:182,dup_topx:182,duplex:[293,306],duplic:[19,63,96,109,127,152,157,178,180,182,189,190,200,245,247,265,273,304,314,320,339,346,360,368,369,388,390,407,423,435,440,442,452,453,458,472,474,475,476],duplicatesectionerror:158,durat:[28,30,63,90,99,142,174,273,293,322,361,368,387,422,477],dure:[16,19,28,45,55,56,60,63,79,80,81,83,88,90,94,100,106,125,127,128,137,143,150,157,159,163,168,169,178,206,210,219,222,223,225,230,237,256,260,265,266,267,273,290,304,308,311,322,328,333,334,340,352,353,356,358,364,365,368,380,387,388,391,392,393,399,401,404,407,412,416,418,429,430,431,432,436,439,440,442,446,447,450,451,454,462,470,473,474,475,476,477],duru:106,dustin:476,dutch:[391,446],dvd:306,dvi:129,dwarf:440,dwayn:476,dwell:77,dwflag:374,dword:168,dxob:369,dyck:474,dyer:477,dylan:473,dyld:470,dylib:168,dynam:[8,11,19,26,28,37,45,55,58,60,63,70,72,75,76,77,78,80,81,82,83,87,88,90,98,99,102,106,111,114,120,129,180,185,222,244,249,335,358,368,369,380,394,396,401,403,405,423,436,438,440,442,447,451,456,470,472,473,475,476],dynload:[107,380],dynload_:470,dynloadsuffiximport:251,dyoo:467,e000000000000p:476,e2big:205,e_eof:82,eacc:[205,207,304],each:[1,4,6,9,12,19,20,24,26,28,30,32,35,52,55,56,63,64,66,70,71,72,73,75,77,79,80,81,82,83,87,89,90,91,93,94,95,96,98,99,100,101,102,103,104,105,106,107,109,111,113,118,121,123,125,126,127,129,132,137,138,139,140,143,145,146,150,151,152,156,157,158,161,162,167,168,169,171,178,180,181,182,186,192,198,199,200,205,208,210,212,215,219,221,222,228,230,231,235,236,241,244,245,246,248,249,253,255,256,258,260,264,265,266,267,273,274,281,283,290,292,293,299,303,304,305,306,307,308,309,311,317,318,321,322,323,328,330,332,333,334,336,338,339,343,346,351,352,355,356,358,361,364,365,366,367,368,369,371,380,381,382,384,385,387,388,389,391,393,394,396,398,399,400,401,403,406,407,409,410,411,413,416,418,423,424,425,426,427,429,431,433,434,435,439,440,441,442,445,446,447,448,451,453,457,460,461,462,465,469,470,471,472,473,474,475,476,477],eaddrinus:205,eaddrnotavail:205,eadv:205,eafnosupport:205,eafp:[90,304],eagain:[127,205,207],eager:[385,464],eai:438,eai_:360,ealreadi:205,ear:309,earli:[30,79,83,152,219,303,365,391,396,427,438,470,474,476],earlier:[28,50,63,71,76,79,87,88,92,93,96,98,100,101,105,107,108,141,143,151,168,169,178,182,186,188,192,204,230,265,269,272,276,277,303,304,305,311,332,333,365,369,389,390,399,407,409,413,418,427,431,437,440,442,446,453,458,460,467,469,470,471,472,473,474,475,476,477],earliest:[140,174,180,392,454],earth:83,eas:[60,81,123,138,250,308,350,407,447,470],easi:[60,62,64,66,70,77,79,81,86,87,88,89,91,93,99,101,102,103,104,105,106,107,108,123,143,152,167,174,178,186,199,212,228,266,303,304,320,351,360,365,368,407,423,427,450,451,452,453,454,455,456,471,472,474,475,476,477,478],easier:[64,66,67,69,72,81,87,89,90,93,96,100,101,103,106,107,108,126,127,152,167,186,201,206,304,321,322,327,344,388,390,404,407,423,445,451,452,453,455,460,461,462,463,466,470,471,472,473,474,475,476,477],easiest:[77,79,82,84,87,88,92,102,106,123,162,186,303,304],easili:[6,20,64,66,69,76,77,79,81,82,83,87,88,89,91,98,99,100,101,106,143,150,157,158,167,168,174,193,222,230,236,292,309,333,364,368,386,391,403,407,412,418,446,456,457,458,462,468,470,473,475],east:[174,392,401,403,406,474],east_asian_width:406,eastern:[150,174,392,462],eastlak:365,easydialog:[60,252,268,476],eat:82,ebad:205,ebadf:205,ebadfd:205,ebadmsg:205,ebadr:205,ebadrqc:205,ebadslt:205,ebcdic:[104,150,440],ebfont:205,ebi:[475,476],ebusi:205,ecdh:365,echild:205,echo:[60,87,89,91,93,129,169,229,257,260,291,304,360,374,387,407,442,459,461,469,476],echocancel:129,echochar:169,echofilt:461,echohandl:127,echoserv:127,echrng:205,ecma:260,ecmascript:[260,426],ecol:398,ecomm:205,econnabort:205,econnrefus:205,econnreset:205,economi:368,ecosystem:106,edeadlk:205,edeadlock:205,edestaddrreq:205,edg:[60,100,168,169,186,362,388,389,403,460],edict:116,edit:[60,63,66,71,83,93,96,101,104,106,107,109,148,169,180,212,222,260,273,274,283,304,307,308,322,333,384,395,396,401,438,456,459,463,470,471,473,474,476],edit_modnam:227,editor:[60,76,81,90,95,101,104,106,222,268,270,311,395,446,460,461,466,467,470,476],editori:470,edness:202,edom:[14,205],edotdot:205,edquot:205,eds:147,edsger:391,edt:[174,392,462],edu:[83,96,246,409,438,467,472,473],educ:[83,413],edward:[471,472,474,475],ee8a:[415,475],ee8v4:472,eec:467,eest:392,eet:392,eexist:[193,205],efault:205,efbig:205,eff:365,effbot:[93,396,429,475,477],effect:[1,13,20,26,28,45,55,62,67,77,79,81,87,88,93,94,96,98,99,100,101,102,103,105,106,107,108,111,113,123,124,134,151,162,168,169,174,178,182,186,191,192,202,204,207,210,213,222,236,239,244,245,256,258,259,260,261,264,265,266,267,280,293,302,303,304,306,311,314,322,328,332,333,336,338,340,343,345,350,351,355,356,365,366,368,373,380,384,388,391,392,401,403,407,416,418,428,439,440,442,446,447,451,452,453,456,458,461,465,470,471,472,473,474,475,476,477],effici:[3,53,58,60,62,79,81,87,88,90,93,96,102,103,104,113,143,150,152,167,168,173,174,178,208,214,222,235,236,237,252,278,301,302,304,310,311,312,321,332,333,346,349,368,370,373,380,389,413,423,425,437,440,452,453,456,457,461,462,472,474,476],efford:96,effort:[0,82,90,97,99,101,103,104,106,192,223,277,321,368,451,457,470,472,473,474,476,477],effortless:462,egd:365,egenix:104,egg:[152,167,180,222,256,321,333,348,368,374,400,409,429,435,454,457,460,470],eggi:180,egid:304,egypt:392,ehlo:358,ehlo_or_helo_if_need:358,ehlo_resp:358,ehopp:410,ehostdown:205,ehostunreach:205,ehresman:475,eidrm:205,eiffel:472,eiffelmethod:472,eight:[81,104,142,169,381,396,446,470,473,474],eighth:415,eilseq:205,einprogress:[87,205],eintr:[20,205,477],einval:[205,304],eio:205,eisconn:[87,205],eisdir:205,eisnam:205,either:[6,8,13,19,20,21,28,30,31,43,48,50,51,52,56,59,63,64,66,71,72,73,76,77,79,81,83,84,87,88,90,91,93,94,95,96,98,100,101,102,104,105,107,108,110,112,113,118,123,125,127,129,131,134,136,139,142,143,144,147,149,150,151,152,160,162,164,167,168,169,170,174,178,180,182,184,185,186,187,192,194,195,196,198,200,202,203,207,215,217,218,219,221,222,230,232,237,240,241,243,244,246,247,250,256,258,260,265,266,267,269,271,273,283,284,287,290,293,300,303,304,305,306,308,309,311,313,314,316,322,328,331,333,336,338,339,342,343,345,346,348,351,355,356,359,360,364,365,368,369,370,373,374,380,384,385,386,388,391,392,393,394,396,398,401,403,405,407,409,410,413,415,416,418,419,423,426,427,429,430,431,432,433,434,435,437,438,439,440,441,442,446,447,450,451,453,454,455,457,460,461,465,467,468,469,470,471,472,473,474,475,476,477],eject:142,el2hlt:205,el2nsync:205,el3hlt:205,el3rst:205,elabor:[81,101,107,219,222,269,396,459,470,473],eland:474,elaps:[169,267,293,304,322,360,392],eldon:477,elect:463,electron:[146,365],eleg:[81,90,94,456],elegantli:474,elem1:[328,475],elem2:[328,475],elem:[96,152,222,258,368,429,453,475,477],element:[4,6,28,35,43,47,48,56,60,62,81,87,88,90,101,103,104,106,115,118,124,126,127,129,132,142,143,148,152,157,164,167,168,170,173,178,180,186,187,200,202,203,206,215,222,228,236,239,240,249,252,253,258,260,265,270,274,275,292,293,294,303,304,305,308,311,316,328,332,333,336,339,348,352,368,369,374,380,392,394,396,398,401,407,409,411,418,424,427,431,432,433,434,439,440,442,451,452,453,460,463,465,470,471,472,473,474,475,476,477],element_cr:401,element_factori:429,element_index:369,element_nam:401,element_nod:426,element_opt:401,elementari:[147,169,403],elementdeclhandl:328,elementinclud:475,elementnam:401,elementpath:475,elementtre:[60,252,275,425,427],elementwis:[302,470,471],elev:64,eleven:368,elibacc:205,elibbad:205,elibexec:205,elibmax:205,elibscn:205,elid:[216,299],elif:[81,88,91,93,96,99,105,126,157,174,180,193,228,293,300,338,352,366,380,384,439,443,446,452,475],elimin:[88,90,98,100,103,152,157,178,180,258,260,273,305,312,386,451,453,463,474],elink:[419,475],elixir:106,ellinghous:[414,438],ellips:[440,442],ellipsi:[15,55,60,101,105,125,157,159,174,186,276,404,440,442,446,461,474],ellipsistyp:404,ellipt:365,elm:333,elnam:328,elnrng:205,eloop:205,elp:309,els:[19,31,36,37,46,55,56,60,63,72,76,77,79,81,82,87,88,89,91,92,96,99,100,101,102,105,107,111,124,125,126,143,157,158,160,165,168,169,174,178,180,185,186,193,200,215,222,228,236,240,241,245,246,249,251,258,260,267,273,281,293,300,302,303,304,311,330,333,335,337,338,340,352,360,365,366,368,369,374,380,384,386,391,396,398,401,403,404,416,418,423,426,435,439,442,443,445,446,447,454,456,463,470,473,474,475,476,477],else_:157,elsewher:[9,63,87,149,158,293,338,342,380,404,426,446],elt:125,em64t:381,emac:[83,89,93,101,104,148,169,244,273,351,446,458,467,476],email:[1,60,62,63,69,70,71,72,88,98,100,106,108,131,135,235,237,252,266,267,273,274,278,280,282,283,292,295,304,333,339,349,358,365,392,405,438,462,463,472,474,475,476,477],email_address:[203,339],emailaddress:365,emax:178,emb:[26,27,28,30,58,60,76,77,78,88,106,186,242,322,393,425,429,472,477],emb_numarg:76,embed:[3,4,27,28,45,56,60,63,64,77,81,85,89,93,94,101,102,104,106,167,187,198,215,222,264,290,322,331,355,374,388,392,394,416,444,446,447,456,458,462,468,469,471,472,475,477,478],embedd:[30,161,293,469],embmethod:76,embodi:[63,88,426],emerg:[104,126,267,452,470],emfil:205,emin:178,emiss:265,emit:[63,90,98,99,157,169,258,265,267,401,427,429,447,462,465,473,476],emlink:205,emp:152,emperor:264,emphas:[90,96,186],emphasi:106,emploi:[90,143,311],employe:[90,152,346,451],employeerecord:152,empt:144,empti:[4,12,19,21,26,28,33,43,48,52,63,64,67,68,72,77,79,82,87,88,90,96,101,102,113,121,123,124,126,127,131,132,134,138,139,140,143,146,148,150,152,158,167,174,175,176,180,186,200,203,205,206,210,219,221,222,225,226,228,229,230,232,233,234,236,240,241,244,249,253,256,258,264,265,266,267,273,274,281,287,292,293,294,297,299,303,304,305,311,315,328,330,331,332,333,339,343,345,346,350,351,352,354,355,356,360,364,365,368,369,370,373,380,384,385,389,392,394,396,399,401,403,406,407,409,410,411,413,419,420,423,424,426,427,429,434,435,436,437,439,440,442,447,451,453,457,458,459,460,461,465,469,473,474,475,476,477],emptiv:127,empty_namespac:426,emptylin:148,emsgsiz:205,emt19937ar:438,emt:438,emu:180,emul:[28,60,82,88,94,106,107,127,139,149,151,169,186,207,249,251,258,262,264,273,293,303,314,323,353,385,439,447,451,472,473,476],emultihop:205,emx:[69,304,305,380,473],emxccompil:69,en_u:174,enabl:[6,8,20,28,30,43,55,60,64,79,83,84,90,93,101,105,106,107,109,111,116,132,134,143,145,148,150,151,168,169,174,177,178,186,191,219,221,225,230,244,251,253,256,266,292,293,309,319,322,325,328,332,333,353,355,356,360,364,365,368,369,374,377,380,384,388,393,399,401,403,405,407,416,423,430,431,435,439,440,446,447,450,458,459,463,465,471,472,473,474,475,476],enable_callback_traceback:364,enable_interspersed_arg:303,enable_load_extens:[364,477],enable_travers:401,enable_user_sit:356,enablereflectionkei:[113,476,477],enametoolong:205,enavail:205,enc:[21,124],encapsul:[8,83,87,88,109,148,198,215,246,256,296,318,358,380,426,430,432,434,439,474,475,476,477],enclos:[77,90,101,108,169,191,193,222,241,246,253,260,299,309,333,351,368,369,388,393,426,441,442,445,446,447,451,452,453,460,471,472,475],enclosur:442,encod:[4,20,21,50,56,57,60,63,66,72,80,87,92,98,99,100,105,106,115,119,124,125,129,135,140,141,143,146,161,167,168,169,170,174,178,186,187,192,193,194,197,198,200,201,202,203,206,209,210,222,230,235,241,246,252,253,256,264,267,280,281,283,295,304,306,311,317,328,339,348,355,360,364,365,368,370,372,373,376,380,382,384,409,411,427,429,432,433,434,435,440,447,452,456,460,462,465,470,471,472,474,475,476,477,478],encode_7or8bit:195,encode_base64:[193,195],encode_func:470,encode_noop:195,encode_object:92,encode_quopri:195,encode_rfc2231:[192,203],encode_threshold:[355,477],encoded_header_len:194,encodedfil:150,encodeprior:267,encodestr:[131,150,331],encoding_decl:443,encoding_typ:365,encodingdecl:[328,427,429],encodingnam:465,encodings_map:281,encount:[13,30,48,81,87,88,101,104,105,106,123,143,146,152,157,161,167,178,186,192,205,206,228,239,240,260,265,266,274,292,296,303,305,309,311,325,328,348,351,361,365,368,385,407,416,431,451,453,454,457,461,470,473,474,475,476],encourag:[77,79,80,100,113,206,252,303,351,374,427,431,445,450,470,471],encrypt:[126,150,233,246,318,324,358,363,365,435,470,472,473,477],encycloped:396,end:[4,6,20,21,24,26,28,30,32,33,36,53,55,56,60,63,66,70,72,75,76,77,79,82,83,87,88,89,90,91,96,98,99,101,102,104,106,107,108,114,118,123,124,126,127,132,135,136,139,140,142,143,146,148,150,151,152,158,160,162,167,169,170,174,178,180,182,186,200,202,203,204,206,207,212,215,219,222,235,239,240,241,243,244,246,253,256,258,260,265,266,267,270,273,282,287,291,292,293,299,303,304,305,306,308,309,313,314,318,320,322,323,328,331,332,333,334,339,348,351,352,354,358,360,365,368,369,373,374,384,385,386,388,389,392,397,398,399,400,401,404,407,409,410,416,423,424,426,427,429,431,432,435,437,439,440,442,445,446,447,448,449,450,452,453,454,455,456,457,458,459,460,461,463,465,469,470,472,473,474,475,476,477],end_el:328,end_fil:403,end_fin:182,end_group:212,end_head:132,end_mark:292,end_paragraph:215,end_poli:403,end_tag:[239,348],endcdatasectionhandl:328,enddoctypedeclhandl:328,enddocu:431,endeavor:92,endel:[431,470],endelementhandl:328,endelementn:431,endhead:[87,241],endian:[26,56,87,104,113,119,146,150,168,230,245,306,373,376,380,415,463],endidx:148,endif:[77,79,92,240],endless:[470,472,475],endlessli:[96,258,474],endlin:231,endmark:[397,443],endnamespacedeclhandl:328,endors:[30,438],endpick:231,endpo:333,endpoint:[102,126,127,205,256,332,360,403],endprefixmap:431,endptr:16,endselect:231,endswith:[311,368,470,473,475,476],endtag:348,endwin:[93,169],energet:129,energi:[129,438],enetdown:205,enetreset:205,enetunreach:205,enfil:205,enforc:[19,60,162,178,200,222,304,338,353,366,369,373,396,403,426,427,442,443,447,451,465,471,472,475],eng:438,engag:[28,380],engin:[81,83,87,90,96,101,106,178,264,333,346,364,401,429,431,461,470,472,474,476,477],engineering_manag:346,english:[81,99,101,104,106,150,303,389,392,403,445,446,477],english_unit:463,enhanc:[56,60,81,83,90,93,96,102,167,184,252,266,365,374,386,388,442,447,458,470,471,472,474,475,478],enjoi:255,enlarg:168,enlighten:147,enoano:205,enobuf:205,enocsi:205,enodata:205,enodev:205,enoent:[205,345],enoexec:205,enolck:205,enolink:205,enomem:205,enomsg:205,enonet:205,enopkg:205,enoprotoopt:205,enorm:[96,102,458],enosi:205,enospc:205,enosr:205,enostr:205,enotblk:205,enotconn:205,enotdir:205,enotempti:205,enotnam:205,enotsock:205,enotti:205,enotuniq:205,enough:[4,37,67,72,73,81,87,88,89,93,94,98,100,101,102,104,105,106,150,167,168,174,180,186,197,247,256,258,303,304,322,332,339,363,365,368,374,377,388,389,393,418,440,447,453,465,467,470,471,472,473],enq:170,enqueu:[293,330],enquiri:170,enregistr:104,enrich:76,ensu:28,ensur:[6,16,28,37,55,63,65,66,77,79,82,87,89,93,95,98,99,101,107,111,113,115,123,126,150,160,174,178,186,200,204,222,234,236,238,249,253,260,265,287,293,303,304,311,350,360,365,368,374,384,387,388,389,391,401,407,410,418,423,434,440,454,461,470,473,475,476,477],ensure_ascii:260,ensure_fromlist:251,ensure_valu:303,ensurepip:[60,108,183,252],ent:240,entail:[283,465],enter:[1,30,71,81,82,83,87,88,89,90,93,96,101,102,106,127,134,143,148,149,151,158,169,182,191,212,222,244,256,291,303,309,343,348,358,364,365,368,380,385,391,394,396,403,416,440,441,448,451,452,454,455,459,460,461,463,465,472,473,475],enterab:343,enterpris:438,entertain:143,enthought:469,entir:[0,4,21,30,55,63,66,72,73,77,79,87,88,90,93,100,101,102,103,104,107,109,113,137,140,143,152,160,163,169,188,193,200,202,212,215,225,230,236,239,240,244,252,256,258,264,265,267,273,303,306,333,336,338,339,348,352,364,365,368,369,370,384,389,391,393,401,403,406,407,409,424,426,429,432,438,439,441,446,447,452,453,457,460,465,471,473,474,475,476,477],entireti:[231,459],entiti:[60,90,101,105,240,252,266,275,328,348,425,426,427,429,431,432,433,473],entity_nod:426,entitydeclhandl:328,entitydef:[239,348],entitynam:328,entityref:101,entityrefer:427,entityresolv:[60,275,432],entranc:81,entrant:265,entri:[4,19,26,28,30,43,55,67,72,77,79,81,89,90,91,93,94,96,99,104,105,106,107,113,116,123,134,137,140,150,152,158,162,168,169,178,182,184,186,194,222,230,233,236,243,244,246,249,253,258,263,266,267,273,274,279,290,293,294,296,303,304,305,308,311,314,315,319,321,322,324,328,330,333,335,342,350,351,358,363,364,365,367,368,379,380,386,388,391,394,396,398,400,401,403,416,418,419,435,440,442,447,453,463,465,469,471,472,473,474,475,476,477],entropi:365,entry_find:236,entry_func:334,entryconfig:396,entrynam:243,entrythingi:396,enum_certif:365,enum_crl:365,enumer:[20,60,81,96,103,104,113,116,117,152,213,222,258,293,364,391,452,453,461,463,478],enumkei:113,enumsubst:116,enumvalu:113,env:[72,87,99,104,106,193,304,365,374,410,449,459,468,473,474],envdir:400,envelop:[193,196,197,200,202,246,273,357,358],environ:[26,28,30,55,58,60,62,63,64,72,83,84,87,88,89,90,94,95,98,104,105,106,107,108,113,133,143,150,169,178,187,204,222,228,229,230,235,237,238,244,249,252,254,264,266,278,303,304,305,306,308,309,311,319,322,327,329,337,340,342,343,346,349,355,360,361,365,368,374,377,380,386,388,392,394,396,399,407,409,410,412,419,426,440,441,448,449,452,456,458,461,466,467,468,470,471,472,473,474,476],environment:[409,465],environmenterror:[20,95,206,461],environmentvarguard:[388,476],envvar:[264,388],enxio:205,eof:[58,82,102,139,148,149,159,186,206,221,222,256,280,292,299,345,351,365,368,385,447,465,475],eoferror:[20,21,36,124,139,146,149,206,222,276,293,311,358,385,461],eooh:273,eopnotsupp:205,eot:[102,170],eoverflow:205,epc2002:104,eperm:205,epfnosupport:205,epilog:[60,120,303,475],epilogu:200,epip:205,epiphani:419,epler:471,epoch:[140,162,168,203,246,273,305,365,392,434,471],epol:[60,362,476],epollerr:345,epollet:345,epollhup:345,epollin:345,epollmsg:345,epolloneshot:345,epollout:345,epollpri:345,epollrdband:345,epollrdnorm:345,epollwrband:345,epollwrnorm:345,eproto:205,eprotonosupport:205,eprototyp:205,eprt:221,epsilon:[81,380,476],epsv:221,epydoc:87,eqequ:397,equal:[4,6,30,32,37,47,52,55,56,58,79,81,82,88,90,91,92,96,99,103,109,123,129,137,152,157,162,168,169,174,178,180,186,191,194,198,200,208,218,222,223,225,228,236,256,258,260,264,274,277,287,300,302,304,306,308,322,330,332,333,346,351,364,368,369,371,373,388,389,391,397,401,403,406,407,418,424,426,429,436,440,442,446,447,452,453,455,460,461,463,470,471,472,473,474,475,476,477],equat:332,equidistribut:332,equiv:293,equival:[4,6,19,20,21,28,30,33,35,37,41,43,47,48,50,51,53,55,56,63,72,77,79,81,84,89,90,91,92,93,94,96,100,101,106,107,109,113,117,119,123,124,125,137,139,142,147,152,157,158,160,161,162,168,169,170,174,178,180,199,200,202,206,212,215,222,223,228,230,231,235,236,237,239,240,249,258,260,264,266,267,273,277,278,293,296,299,302,303,304,305,306,308,311,312,313,314,317,319,322,330,332,333,335,338,342,345,346,349,354,360,365,368,369,374,376,380,381,384,388,390,392,396,403,406,407,409,411,413,417,419,426,437,439,440,442,446,447,450,451,452,453,454,457,460,465,470,471,472,473,474,475,476,477],era:[264,475],era_d_fmt:264,era_d_t_fmt:264,era_t_fmt:264,erang:205,eras:[88,93,99,169,385,457,458],erasechar:169,ered:240,eremchg:205,eremot:205,eremoteio:205,erestart:205,erf:[94,277,477],erfc:[277,477],erhard:474,eric:[88,93,169,429,438,453,470,471,474,476,477],erich:407,erik:476,erof:205,erow:398,err:[21,87,93,95,169,206,228,267,352,407,434,438],err_traceback:79,err_typ:79,err_valu:79,errata:[162,260,434],errcheck:168,errcod:[58,82,434],errfil:87,errmsg:434,errno:[14,20,30,60,77,87,120,168,193,206,207,252,269,304,328,338,345,360,365,454,476],erron:[276,303,311,391,403,425,470],error:[4,6,16,18,19,20,21,22,26,28,29,30,31,33,36,37,38,39,41,42,43,47,48,49,50,52,53,54,55,56,57,58,59,60,64,69,72,76,78,79,81,82,83,91,92,93,95,96,98,99,100,101,102,104,106,113,119,120,121,123,124,127,128,129,132,134,135,136,138,139,142,143,144,148,149,150,151,155,156,157,158,160,163,167,168,169,174,175,176,180,185,186,188,192,193,198,200,202,203,205,206,208,210,216,221,222,226,228,237,239,240,243,244,245,246,247,256,258,259,260,262,263,264,265,266,267,269,273,275,277,279,284,287,292,293,295,296,298,299,301,304,305,306,311,314,317,318,319,322,325,333,336,338,339,345,346,348,351,352,353,354,355,356,358,360,361,364,365,368,373,374,376,377,380,382,384,385,388,390,391,396,398,400,401,407,409,410,411,412,413,414,416,417,418,419,421,422,423,424,426,430,431,432,434,435,437,439,440,441,442,446,447,450,451,453,456,460,461,463,465,470,471,472,474,475,476,477,478],error_bodi:423,error_cod:407,error_content_typ:132,error_data:299,error_handl:[150,430],error_head:423,error_lead:351,error_message_format:132,error_out:92,error_output:423,error_perm:[221,299],error_proto:[221,299,318],error_repli:[221,299],error_statu:423,error_temp:[221,299],errorbyteindex:328,errorcod:[205,328],errorcolumnnumb:328,errorhandl:[60,275,430,432,465,476],errorlevel:[87,384],errorlinenumb:328,errorstr:328,errortoken:[397,398],erupt:472,ervo:101,esc:[170,191,458],escap:[13,15,37,60,63,77,79,81,93,95,101,104,106,143,150,155,167,169,170,224,256,260,299,308,313,333,335,337,351,369,374,392,403,409,411,433,434,442,446,460,463,470,471,474,476,477],escapechar:167,escapedquot:351,escapeseq:446,eshutdown:205,esmtp:358,esmtp_featur:358,esocktnosupport:205,esoter:[472,475],espeak:99,especi:[28,62,64,67,72,76,77,87,88,90,91,100,104,107,127,141,152,174,178,186,195,236,247,256,260,266,273,283,304,309,317,322,325,328,330,332,339,365,366,374,396,413,418,426,439,445,452,460,463,470,472,473,476,477],esperanto:150,espip:205,esrch:205,esrmnt:205,essai:[88,478],essenc:96,essenti:[28,60,77,88,96,101,102,106,117,207,230,252,255,266,267,277,299,303,304,317,342,350,361,368,380,403,407,416,427,435,440,444,450,470,472,477],est:[174,392,462],establish:[1,98,113,127,186,221,236,246,267,293,311,314,345,358,365,385,396,409,440,441,477],estal:205,estim:299,estrpip:205,etb:170,etc:[62,63,64,72,75,81,82,84,90,96,98,99,102,104,105,107,117,123,125,129,139,143,148,157,161,162,177,181,192,201,212,219,221,240,243,244,245,247,253,256,263,264,265,267,273,274,281,284,290,293,303,304,314,315,324,333,348,352,356,360,364,365,374,377,380,384,391,394,396,403,407,411,423,426,438,440,447,448,451,452,453,458,461,469,470,472,473,474,475,476,477],etern:101,ethiop:104,ethnomathemat:403,etim:205,etimedout:[205,476],etini:178,etiquett:102,etoomanyref:205,etop:178,etr:63,etre:[60,252,275,425,427,475,477],etter:406,eturn:309,etx:170,etxtbsi:205,etyp:[400,401],euc:[150,194,474],euc_jis_2004:150,euc_jisx0213:150,euc_jp:150,euc_kr:150,euccn:150,eucgb2312:150,eucjis2004:150,eucjisx0213:150,eucjp:[150,174],euckr:150,euclean:205,euclidean:277,eudora:318,euid:304,eunatch:205,euro:[104,150,477],europ:[104,150,174,392,464,477],european:[140,150,477],europython:104,euser:205,eval:[12,55,81,82,88,109,124,134,149,151,157,206,222,266,308,309,321,338,368,369,394,400,441,442,443,446,447,448,451,461,470,474,476],eval_input:443,evalu:[3,28,58,60,72,77,88,89,90,95,96,125,182,222,230,238,258,265,293,309,338,340,342,368,380,407,409,439,440,441,444,446,447,452,453,458,460,470,473,474,475,476,477],evan:475,even:[4,16,20,26,28,30,37,50,51,52,55,62,63,64,67,71,72,77,79,81,82,83,84,87,88,89,90,91,95,96,99,100,101,102,104,106,107,108,109,113,114,123,126,127,135,143,147,150,156,159,160,162,168,169,174,178,182,184,186,194,195,196,201,202,206,207,222,225,230,236,244,249,253,256,259,264,265,266,267,273,277,293,303,304,305,309,311,322,332,333,338,339,351,352,353,358,364,365,368,373,380,391,392,401,406,407,411,418,419,423,427,431,433,434,435,438,440,442,443,445,446,447,450,451,452,453,454,456,457,458,460,461,462,465,469,470,471,472,473,474,475,476,477],evenli:258,event:[26,28,37,60,63,77,83,93,98,115,116,117,126,127,134,169,173,174,212,215,219,236,238,239,252,257,265,267,268,284,290,293,322,328,345,357,362,364,365,377,380,384,395,426,427,428,429,430,431,432,433,438,454,463,468,469,470,475,476,477],event_func:293,eventcod:77,eventlist:345,eventloop:269,eventmap:290,eventmask:[345,476],eventproc:191,eventu:[28,30,77,79,82,87,102,104,161,186,197,293,410,425,427,434,450,471,472,474,475,476,477],ever:[21,63,77,88,95,102,104,106,111,125,169,197,256,258,291,292,293,307,440,472,473,475,476,477],everi:[6,28,30,37,43,55,63,64,66,70,72,77,79,80,81,82,83,88,89,90,94,95,96,98,99,101,102,104,105,106,107,109,114,125,132,135,150,151,162,168,169,174,175,178,180,186,200,222,226,230,236,238,258,260,265,270,293,303,304,306,314,328,330,333,339,346,353,361,364,368,374,376,379,380,381,382,389,391,401,403,407,410,423,424,426,429,434,440,445,449,452,455,456,460,461,465,469,470,471,472,473,474,475,476,477],everybodi:[143,161],everydai:[94,222,252,407],everyon:[68,70,81,396],everyth:[3,55,63,66,73,77,79,88,89,93,100,101,102,104,105,106,107,123,163,186,214,217,266,270,303,304,305,333,352,357,364,385,396,416,434,445,447,460,476],everywher:[88,102],evil:[158,477],evolut:[62,108,470,471],evolv:[106,266,440,451,453],evt:[60,268],ewouldblock:[127,205],ewt:475,ex_cantcreat:304,ex_config:304,ex_dataerr:304,ex_ioerr:304,ex_nohost:304,ex_noinput:304,ex_noperm:304,ex_notfound:304,ex_nous:304,ex_ok:304,ex_oserr:304,ex_osfil:304,ex_protocol:304,ex_softwar:304,ex_tempfail:304,ex_unavail:304,ex_usag:304,exact:[16,30,63,64,72,73,83,87,96,101,102,104,106,108,109,168,169,174,178,186,197,206,218,219,252,256,273,277,301,303,304,337,339,368,381,396,398,407,429,442,444,447,455,463,470,471,475,476,477],exactli:[4,6,8,21,24,30,50,51,56,58,62,63,67,77,79,81,87,88,93,99,101,103,109,123,124,137,143,144,145,157,160,162,168,174,178,186,195,197,200,202,217,218,222,228,236,253,264,265,266,273,277,293,299,303,305,306,311,328,333,336,345,358,360,361,364,365,368,371,373,374,386,387,389,391,400,407,415,418,437,439,440,442,446,447,451,453,455,463,470,472,473,474,475,476,477],exam:137,examin:[26,55,60,76,88,94,98,107,111,168,179,219,225,253,262,309,322,351,358,368,380,388,426,450,471,473,475,476],exampl:[4,6,15,16,19,20,21,27,28,30,34,39,45,51,55,60,63,64,66,68,69,71,72,73,75,76,78,80,81,82,83,87,88,89,90,91,92,93,95,96,100,101,102,103,104,105,106,107,108,109,110,114,118,119,120,121,122,124,125,129,130,131,134,136,138,140,143,144,150,151,154,155,160,163,165,168,169,173,174,177,178,179,182,185,192,194,196,198,199,200,201,202,203,206,207,208,209,210,211,214,215,217,218,219,221,222,223,225,227,228,230,231,232,235,239,244,248,252,253,254,256,257,258,260,262,263,264,265,266,267,270,274,275,277,278,280,281,284,287,289,291,295,299,300,302,304,306,309,310,313,314,315,319,320,322,327,329,330,332,335,337,339,340,341,343,348,351,354,356,362,364,366,368,370,371,372,374,377,379,380,381,388,389,392,394,396,397,398,399,401,403,404,406,408,411,412,413,416,419,422,424,425,426,431,435,438,439,440,442,445,446,447,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,468,469,470,471,472,473,474,475,476,477],examplescreen:403,exampleturtl:403,examplexml:429,exc:[13,20,28,41,82,109,388,407,476],exc_clear:[81,88,380,461,473],exc_info:[28,30,98,99,109,113,134,145,182,186,265,352,380,400,407,423,439,440,454,461,473,475,476],exc_msg:186,exc_tb:368,exc_text:[99,265],exc_traceback:[20,30,77,81,109,380,400,404,439,440,461],exc_typ:[20,30,77,109,368,380,400,439,440,461],exc_val:368,exc_valu:[20,30,77,109,380,400,439,440,461,477],exce:[16,29,52,158,178,225,256,304,311,319,336,368,386,391,426,452,477],exceed:[205,267,336,389,437,473,474,476],excel:[88,104,167,186,396,467,473,474],excel_tab:167,except:[2,4,6,8,13,16,19,21,22,26,27,28,31,33,34,35,36,41,43,45,47,49,50,51,52,53,54,55,56,58,59,60,67,69,70,72,73,78,79,82,83,87,90,91,92,93,94,96,100,101,102,104,106,107,109,111,113,116,118,119,121,123,124,125,126,127,128,129,130,133,134,135,136,138,142,143,145,146,147,149,150,151,152,155,157,158,159,160,161,162,163,167,168,169,170,174,175,176,178,179,180,182,185,188,189,190,191,192,193,197,200,201,202,207,209,210,212,213,217,221,222,226,227,228,229,230,234,235,237,238,239,240,241,243,244,245,246,247,249,251,252,253,255,256,257,258,259,260,262,263,264,265,266,267,269,275,276,277,278,282,287,288,290,292,295,296,298,299,300,303,304,305,306,309,311,314,316,318,319,322,325,329,330,331,333,334,336,337,338,339,340,343,345,346,348,349,351,352,353,354,355,356,357,358,360,361,362,364,368,369,370,372,376,377,380,383,384,386,387,388,389,390,391,392,393,394,396,398,400,407,409,410,411,414,416,417,418,419,423,427,429,430,431,432,434,435,436,437,439,440,442,443,444,445,446,447,448,449,450,452,453,456,457,459,461,463,465,470,471,472,473,474,478],except_claus:443,excepthandl:125,excepthook:[145,380,461,471],exception1:475,exception2:475,exception:322,exception_hierarchi:476,excerpt:[145,178],excess:[107,109,119,168,178,245,335,392,439,442,452],exchang:[60,76,102,104,106,168,205,235,236,237,278,287,304,330,349,362,365,384,457,476,477],excinfo:352,excit:[94,450,470,472],exclam:[103,273,309,369,401,422],exclud:[4,16,56,73,94,101,152,156,186,225,258,273,288,290,304,322,328,365,368,384,391,401,438,440,442,453,460,476,477],exclude_empti:186,exclus:[37,41,60,70,88,101,102,107,120,140,169,173,178,207,215,252,267,273,302,303,304,320,364,368,384,399,419,438,442,451,469,476],exctyp:380,excursu:[60,395,466],excus:79,exdev:205,exe:[63,64,70,89,101,267,293,304,333,356,435,449,469,477],exec:[12,28,60,63,77,87,107,109,125,134,157,182,205,206,222,238,244,304,308,309,320,322,338,368,379,380,388,398,399,400,441,443,444,446,448,449,451,470,471,472,474,475],exec_prefix:[28,30,63,107,293,356,380,399,461,465,468],exec_stmt:[182,443,447],execcgi:106,execfil:[60,63,109,186,222,338,412,441,447,451,461,473,474],execl:[303,304],execlp:304,execut:[12,20,26,28,30,43,45,46,52,58,60,63,64,70,71,72,75,76,77,79,80,81,88,90,91,95,96,100,101,106,107,111,112,113,123,128,133,134,141,142,143,144,148,149,152,155,156,157,160,161,168,177,179,184,206,216,222,227,236,246,249,251,252,253,256,264,265,266,268,274,289,290,293,294,303,304,305,308,309,313,315,317,322,327,334,336,343,345,350,352,353,355,356,360,364,366,368,371,374,380,386,388,390,391,392,394,395,396,405,407,410,412,416,419,423,439,440,442,444,447,448,451,452,454,456,457,458,459,460,462,465,466,467,468,470,471,472,473,474,476,477,478],executable_filenam:63,executemani:364,executescript:364,executexx:364,execv:[303,304,319],execvp:[304,374],exemplar:88,exemplari:438,exemplifi:[266,452],exempt:[83,477],exercis:[77,81,87,98,102,152,179,265,297,303,322,388,476],exfileselectbox:394,exful:205,exhaust:[4,55,81,90,96,126,150,182,222,253,258,388,396,439,442,452,453,472,474,475,476],exhibit:[256,440,451],exif:248,exist:[4,6,19,20,21,26,28,29,30,43,48,50,51,52,55,58,59,60,63,64,68,70,71,72,73,76,77,78,79,82,83,87,88,90,94,95,96,98,99,100,101,104,105,106,107,108,109,111,113,118,121,123,124,125,134,137,138,139,143,148,150,152,156,157,158,161,162,163,167,168,174,175,176,185,186,188,191,193,200,201,204,205,206,208,210,215,219,222,224,226,230,234,235,236,238,243,244,246,249,253,256,258,266,267,272,273,274,276,280,281,287,290,293,298,303,304,305,306,308,309,311,314,322,327,332,333,334,338,339,342,348,350,352,353,356,365,366,368,369,370,373,374,380,381,384,386,388,390,392,394,396,401,403,406,407,409,410,412,413,414,416,418,419,420,423,426,429,434,435,436,439,440,442,444,445,446,447,451,453,455,457,458,460,461,465,469,470,471,472,473,474,475,476,477],existing_db:364,existing_fil:96,exit:[28,30,52,58,60,64,77,82,87,91,92,93,95,96,99,120,143,155,159,160,167,169,178,180,182,193,204,206,219,228,244,249,252,258,265,293,303,304,309,317,322,325,329,338,345,353,356,360,361,364,368,374,380,385,388,390,391,393,399,404,407,416,419,422,423,435,439,440,442,449,459,461,462,465,470,471,472,473,474,475,476,477],exitcod:293,exitfunc:[109,128,380,470,474],exitonclick:403,exot:[260,410,472],exp:[14,147,178,216,277,332,369,476,477],expand:[28,51,55,79,89,91,101,104,107,113,158,178,186,197,230,244,253,266,293,303,305,328,333,355,368,369,381,389,392,396,401,411,425,426,429,431,469,472,473,476],expand_tab:389,expandenvironmentstr:[113,476],expandnod:428,expandtab:[368,369,389],expandus:[107,158,162,232,305,334,352,374,458],expandvar:[232,305,374,476],expans:[28,51,60,157,158,211,214,244,252,305,322,328,374,389,425,435,452,474],expat:[60,72,252,275,316,425,429,431,470,471,473,475,477],expat_extens:470,expaterror:[60,275],expect:[1,4,20,24,50,51,55,60,66,67,68,70,72,77,79,80,81,87,88,90,91,93,94,96,98,99,100,101,102,104,105,106,107,108,111,123,125,127,143,146,150,152,162,164,168,169,178,179,180,182,186,192,206,215,218,221,222,230,241,251,253,260,264,265,267,271,273,287,293,302,303,339,350,351,353,360,373,380,385,388,392,396,401,403,409,413,414,423,424,431,432,434,437,440,442,447,451,452,455,463,469,470,471,472,473,474,475,476,477],expectation_fail:241,expected_result:81,expectedfailur:407,expectedfailuretestcas:407,expectpi:87,expens:[55,70,79,81,88,90,98,103,137,180,238,256,264,300,322,361,365,437,442,463,474],expensive_func1:98,expensive_func2:98,experi:[83,88,96,98,101,106,168,230,322,364,374,403,426,450,456,470,471,472,476,477],experienc:81,experiment:[3,72,81,94,157,244,273,322,364,396,426,445,473],expert:[216,303,460,461],expi:87,expir:[161,162,205,293,353,358,360,363,409],expiri:162,explain:[30,37,55,72,75,77,79,80,82,88,91,93,96,98,100,101,104,105,106,107,125,132,143,157,162,163,168,174,186,206,222,240,270,303,309,320,368,401,407,437,442,450,451,455,458,464,465,470,471,472,473,474,475,476,477],explan:[60,72,83,101,105,132,174,264,273,293,294,296,309,313,333,354,364,368,380,392,396,403,410,453,454,457,464,470,471,472,473,474,475,476],explanatori:[80,186,308,328],explicit:[20,24,30,60,62,63,72,73,77,81,88,95,98,101,102,109,128,162,174,180,200,204,222,230,267,303,328,342,351,361,368,369,380,388,407,418,427,430,440,442,449,451,453,460,461,470,471,475,477,478],explicitli:[6,25,28,30,43,55,60,62,63,64,66,67,72,77,79,87,88,90,93,96,98,100,101,106,107,108,109,110,113,143,149,160,162,168,171,178,198,201,204,206,207,210,221,222,225,230,233,249,252,253,260,264,266,273,277,290,293,303,304,305,306,321,325,350,352,353,358,360,361,364,365,368,369,374,377,380,382,396,403,407,409,416,423,426,436,439,440,441,442,446,449,451,452,460,461,465,472,473,475,476,477],explod:[470,472],exploit:[143,304,338,425,465],explor:[91,98,103,105,107,227,240,244,270,304,407,429,440,458,476],expm1:[277,477],expon:[91,178,277,368,369,380,446,474,476],exponentfloat:446,exponenti:[14,88,147,178,267,302,332,368,425,442,473,474,476],export_symbol:[63,72],exportselect:401,expos:[6,14,19,21,23,33,38,39,40,48,51,55,56,63,71,76,77,79,90,91,98,105,106,113,133,168,178,204,260,264,265,290,293,313,321,350,351,355,368,369,371,374,380,399,406,409,418,440,473,476,477],expositori:186,expovari:332,expr1:[96,157,442,470],expr2:[96,157,442,470],expr3:[96,157,442],expr4:442,expr5:442,expr:[96,125,134,157,308,407,443,447,454,470,474],expr_context:125,expr_stmt:443,express:[19,35,41,43,47,58,60,72,77,83,88,89,90,97,99,104,117,123,125,134,147,151,154,157,174,178,180,182,186,214,216,222,230,232,244,252,253,258,264,266,273,277,293,302,308,309,322,332,338,340,353,360,365,368,369,372,373,380,385,392,393,396,398,399,404,406,407,415,416,418,429,438,439,440,441,444,446,450,453,454,456,457,458,460,461,462,465,470,471,472,473,476,477,478],expression1:447,expression2:447,expression_list:[439,442,447,448],expression_nocond:442,expression_stmt:447,exprlist:443,exprn:[96,470],expung:246,ext:[66,98,99,150,182,193,266,281,305,309,463,473,474],ext_modul:[63,67,72,73,75,79,470],ext_packag:72,extant:200,extend:[4,6,26,27,28,30,37,55,60,67,69,75,79,81,83,85,87,88,93,95,99,101,105,106,107,120,123,124,127,132,140,147,150,152,157,158,159,168,169,174,180,182,186,187,192,197,199,200,202,221,222,223,239,248,249,256,258,260,270,273,275,277,281,287,291,293,311,314,322,328,334,345,348,352,358,360,365,368,380,384,398,401,403,407,425,426,429,440,441,442,444,447,451,453,456,460,461,469,471,474,476,477,478],extend_path:314,extended_arg:182,extended_sl:442,extendedcontext:178,extendedref:418,extendleft:152,extens:[1,4,6,8,10,11,20,24,27,30,37,39,43,49,51,55,56,58,60,64,66,68,69,70,76,78,79,81,83,84,85,88,89,90,93,97,100,101,106,113,120,124,131,144,145,165,168,169,174,176,184,186,188,193,210,214,222,225,230,236,241,242,243,246,249,252,253,254,256,260,267,269,273,275,281,289,299,300,303,304,307,309,310,318,322,326,328,331,332,333,350,351,352,358,360,364,365,368,380,381,384,391,395,396,403,404,407,412,418,425,426,427,430,431,434,435,438,440,442,444,449,450,451,456,461,462,465,467,468,469,470,471,472,473,474,475,476,477],extension_nam:63,extensionclass:470,extensions_map:354,extent:[30,163,256,287,401,403,438],extern:[30,60,63,64,72,73,77,81,82,87,89,99,103,120,124,143,150,158,168,188,208,222,237,244,249,265,274,276,304,310,328,352,361,364,368,374,386,388,396,405,423,424,425,426,429,431,432,435,440,442,447,454,464,469,476],external_attr:435,externalclasherror:273,externalentityparsercr:328,externalentityrefhandl:328,extra:[11,16,30,50,55,56,63,79,81,88,90,93,99,105,107,109,123,131,157,167,178,186,200,212,219,241,265,270,273,276,284,293,303,333,352,365,368,374,384,385,393,401,429,435,440,443,453,457,463,470,473,476,477],extra_arg:352,extra_compile_arg:[63,72],extra_link_arg:[63,72],extra_object:[63,72],extra_postarg:63,extra_prearg:63,extra_s:463,extract:[13,17,30,60,64,76,78,79,81,96,101,162,169,174,180,186,192,195,222,230,236,241,253,258,302,304,308,326,333,350,368,380,384,400,435,438,440,452,453,454,462,473,474,475,476,477],extract_cooki:162,extract_mime_part_match:292,extract_stack:400,extract_tb:400,extract_vers:435,extractal:[384,435,475,476],extracted_list:400,extracterror:384,extractfil:384,extractor:[302,474],extraglob:186,extran:[126,260,322,396],extrasact:167,extrem:[81,87,88,96,99,104,139,202,260,296,338,426,435,442,454],extsep:304,extslic:125,eye:[81,131,178,180,452,475],ezio:477,f100:452,f5d:472,f5r8f:472,f5r:472,f6stal:198,f86e:[415,475],f_back:[253,440],f_bavail:[304,367],f_bfree:[304,367],f_block:[304,367],f_bsize:[304,367],f_builtin:[253,440],f_close:21,f_code:[253,440,473],f_exc_traceback:[253,440],f_exc_typ:[253,440],f_exc_valu:[253,440],f_favail:[304,367],f_ffree:[304,367],f_file:[304,367],f_flag:[304,367],f_frsize:[304,367],f_getfl:87,f_global:[253,440],f_in:234,f_lasti:[253,440,473],f_lineno:[253,440,473],f_local:[253,404,440],f_namemax:[304,367],f_ok:304,f_out:234,f_restrict:[253,440],f_setfl:[87,207],f_setlkw:207,f_trace:[253,440],f_wrlck:207,fab:277,fabian:476,face:[28,102,117,192,314,337,403,470,476],facil:[28,60,93,98,119,120,134,149,155,169,244,252,262,267,273,304,317,365,382,384,403,440,458,460,469,473],facilit:[71,215,222,266,334,404,416],fact:[26,30,56,64,66,67,70,72,77,81,83,88,89,92,95,96,98,101,102,105,106,107,140,158,168,178,185,186,201,204,216,222,265,288,303,311,322,348,384,392,396,400,410,423,440,442,445,451,452,455,460,461,470,471,476],facto:[104,162,169,384,407,411,434],factor:[88,104,129,152,186,213,303,317,407,442,443,452,472,477],factori:[13,55,60,63,90,95,123,150,160,164,168,173,186,202,223,265,266,267,273,277,287,293,303,311,317,352,355,364,370,391,396,404,418,423,426,429,434,440,472,475,476],factual:104,facundo:[474,476],fail:[4,8,16,20,26,28,30,37,39,49,50,55,56,60,72,76,77,79,81,87,88,89,90,91,92,95,99,100,101,102,105,106,111,113,127,143,146,147,150,157,161,168,186,203,204,206,207,222,244,248,249,253,256,258,264,266,273,274,287,292,293,303,304,305,306,308,309,315,320,332,336,339,350,352,354,356,358,360,365,368,369,374,380,384,388,391,394,407,409,410,415,424,432,434,436,440,441,442,447,452,454,457,461,470,472,473,474,475,476,477],failed_depend:241,failfast:[407,477],failif:[109,407],failifalmostequ:[109,407],failifequ:[109,407],failobj:200,failunless:[109,407],failunlessalmostequ:[109,407],failunlessequ:[109,407],failunlessrais:[109,407],failur:[4,7,8,11,14,16,19,20,21,22,23,24,26,28,30,33,34,35,37,41,43,47,48,50,51,52,53,56,58,60,63,72,77,82,92,100,101,162,168,169,179,186,244,267,287,291,304,308,336,356,365,368,369,388,391,471,474,476,477],failure_count:186,failureexcept:[186,407],fair:[365,407,411,472],fairli:[43,55,66,73,87,89,90,93,97,102,104,186,199,270,290,315,322,350,393,426,427,457,470,472,473,475,476],faithfulli:[104,308,380],fake:[64,87,303,423,440],fakeseq:473,fall:[19,26,37,70,87,96,98,169,174,178,191,200,206,222,229,245,256,266,300,302,306,343,377,440,446,452,459,470,472,473,475,476,477],fallback:[30,188,230,388,401,422,440],fallback_charset:203,fallback_oper:300,fals:[4,5,8,10,11,18,19,28,30,31,35,41,43,46,54,55,56,58,63,77,87,88,90,91,96,98,99,100,105,114,123,125,126,127,131,133,135,140,146,148,149,150,152,158,159,162,167,168,169,171,174,178,180,182,186,192,194,196,197,200,202,203,204,207,208,210,214,215,222,225,228,230,239,241,249,253,256,258,260,264,265,266,267,269,273,281,292,293,294,302,303,304,305,306,308,311,316,317,321,325,328,330,331,339,341,342,346,350,351,352,353,355,356,358,361,364,365,368,373,374,380,381,384,386,388,389,390,391,392,399,401,403,404,407,410,411,416,423,429,431,434,435,439,440,442,443,447,451,452,453,460,461,463,465,473,474,475,476,477],false_v:475,false_valu:475,famili:[4,15,28,37,60,63,64,69,96,104,127,193,205,230,257,273,293,304,310,317,360,361,380,382,426,469,473,474,475,477],familiar:[30,79,89,90,91,93,96,101,106,149,228,255,260,407,455,457,467,471,472,473,476],famou:395,fan:77,fanci:[87,88,93,452,473,477],fancier:[60,87,123,180,456,474,475,477],fanciest:473,fancy_getopt:69,fancygetopt:63,fancyinteg:311,fancyurlopen:409,faq:[60,63,85,90,93,106,280,301,318,368,411,464,469,475,477],far:[64,72,77,79,81,83,88,91,101,102,106,162,180,235,236,237,247,256,270,277,278,282,293,303,322,332,333,338,349,351,353,385,392,394,407,409,445,457,470,471,472,473,474,476],farber:82,farg:223,farrugia:469,fashion:[43,159,216,260,293,317,322,333,360,391,439,440,442,452,474,477],fast:[28,56,60,87,90,102,103,129,152,222,226,235,249,252,256,258,275,292,302,322,330,332,393,395,403,440,453,457,464,470,474,475,477],fastcgi:[60,423],faster:[6,43,47,60,87,88,90,101,102,103,106,152,168,169,202,222,231,235,252,258,293,308,310,322,332,365,368,372,403,437,438,461,463,464,470,471,472,473,474,475,476,477],fastest:[6,102,103,234,293,403,437,462,476],fastli:83,fat32:304,fat3:63,fat64:63,fat:[63,113,304,381],fatal:[20,28,37,52,77,128,365,380,384,449,454,477],fatalerror:431,fault:[26,60,63,98,168,185,254,303,336,475,477],faultcod:434,faulti:[13,216],faultstr:434,favor:[152,305,337,346,368,388,409,438,439,446,474,476],favorit:[77,83,104,453,461],favour:[6,43,47,160,475],favourit:[95,98],fbar:303,fblogg:265,fcgi:106,fchdir:304,fchmod:[304,476],fchown:[304,476],fcicreat:290,fcicreatefil:290,fcntl:[60,87,252,320,360,368,377,408,472,473,474,476],fd2:304,fd_high:304,fd_low:304,fdatasync:304,fdcba:137,fdel:[94,114,222],fdesign:212,fdopen:[291,304,360,368,386,440],fdrake:443,fds:345,fdst:352,feasibl:[55,70,77,192,350],feather:104,featur:[3,20,43,47,54,55,60,63,68,72,75,78,79,81,82,83,84,87,88,89,90,94,95,96,98,101,104,106,107,111,120,137,138,139,143,145,147,151,157,158,162,168,169,171,172,186,192,204,206,213,215,222,236,244,250,252,260,265,268,293,303,304,309,314,333,346,347,358,362,364,365,373,374,375,380,388,396,401,403,407,408,409,410,413,416,418,421,423,425,426,427,430,431,432,438,439,440,442,445,446,447,449,450,451,452,456,458,459,460,461,462,463,464,465,467,468,469,470,471,472,473,474,476,478],feature_external_g:431,feature_external_p:431,feature_namespac:431,feature_namespace_prefix:431,feature_string_intern:431,feature_valid:431,featurecompon:290,featureless:222,featurenam:[111,432],feb:[91,96,101,174,459,472],februar:174,februari:[83,174,392,446],fed:[202,235,240,278,293,328,348,349,475],feder:438,fedora:468,fedora_draft_document:468,fedoraproject:468,fee:[81,438],feebl:186,feed:[83,106,135,169,170,202,235,239,240,258,278,293,341,348,349,368,423,429,432,437,463,475],feedback:[60,83,230,438,474],feeder:293,feedpars:[60,192,196,295,474],feel:[81,84,91,92,93,100,222,303,307,320,395,401,405,472,473,476],feff:[56,104,150],fell:[452,462,471,472,473],felling:472,femal:99,fenner:476,fetch:[26,55,60,96,97,167,246,258,290,293,302,330,341,360,364,365,409,410,434,463,474],fetchabl:470,fetchal:[152,364,475],fetched_python_logo:434,fetchmail:318,fetchmani:364,fetchon:[364,475],feurzig:403,few:[4,10,23,28,30,39,62,63,64,68,77,81,88,89,91,94,95,96,98,101,106,107,123,127,129,150,165,168,169,174,178,180,186,192,193,195,221,222,236,240,244,249,290,293,302,303,308,312,331,333,338,356,358,360,365,368,380,388,393,400,407,409,410,437,440,445,451,457,470,471,472,473,475,476,477],fewer:[81,101,167,256,333,346,364,401,452,473,475],ffactor:138,fffd:[13,104,150,194,222,470],fffe:[56,150],ffff:470,ffffff:403,fflag:345,fflush:368,ffoo:303,ffseq:88,fget:[94,114,222,368],fib2:[452,461],fib:[452,461],fibo:461,fibonacci:[88,452,460,461],fiction:429,fiddl:364,fido:451,fie:81,fiefoo:81,field1:477,field2:477,field:[1,3,4,6,12,17,24,26,30,48,51,55,60,71,72,77,79,87,92,94,98,107,113,120,125,136,141,142,143,146,150,158,167,169,173,174,178,192,198,200,203,212,233,243,258,265,274,290,302,304,324,328,336,339,343,360,363,365,366,368,369,373,374,376,380,382,384,387,392,396,398,401,405,409,411,415,423,427,429,435,451,457,463,465,470,471,472,473,475,476,477],field_nam:[152,369],field_size_limit:[167,475],fieldbackground:401,fieldnam:[125,152,167,339,476],fieldstorag:143,fieldvalu:203,fifo:[126,152,293,304,330,366,384],fifotyp:384,fifth:[104,169,244,368,392],fig:161,figur:[63,67,77,79,83,86,88,91,93,96,100,101,104,123,178,186,303,322,384,451,470,471,472,473,474,475,476,477],file1:477,file2:477,file:[1,6,15,16,17,20,22,26,27,28,29,36,39,43,52,55,56,58,60,62,64,65,67,68,69,70,75,76,77,79,80,81,83,84,90,91,92,95,96,101,102,104,105,106,108,109,110,112,113,119,120,121,122,124,125,127,128,129,131,132,134,135,138,142,143,144,145,146,148,149,150,152,155,156,157,160,162,163,168,169,170,175,176,178,179,180,182,184,185,188,191,192,193,197,199,200,201,202,205,206,207,210,212,214,215,216,221,222,226,227,228,229,230,231,232,236,238,239,240,241,243,246,248,249,252,253,260,262,263,264,265,267,268,269,273,275,276,279,280,281,283,286,288,293,295,299,303,305,306,308,309,310,311,312,313,314,315,317,318,321,322,323,324,326,327,328,331,333,335,336,337,338,339,340,341,342,345,347,348,350,351,353,354,356,358,360,361,362,364,365,366,367,372,373,374,377,378,379,380,381,383,385,387,388,390,391,392,393,395,397,398,399,400,402,403,404,405,406,407,408,409,410,411,412,416,418,419,420,421,422,423,425,427,430,432,433,434,435,436,437,438,440,441,442,443,444,446,447,450,451,452,453,454,456,458,459,460,463,465,466,467,469,470,471,472,474,475,476,477,478],file_cont:234,file_cr:64,file_dispatch:127,file_input:443,file_list:96,file_nam:113,file_obj:[470,473],file_open:410,file_or_dir:383,file_path:342,file_s:[435,472],file_util:[69,477],file_wrapp:[127,423],filecmp:[60,180,211,252,470],fileconfig:[98,99,266,477],filecont:241,filecookiejar:[60,254],filecr:191,filedescriptor:304,fileencod:446,fileentri:394,filehandl:[60,98,99,105,120,254,265,266,311,409,476],fileinput:[60,211,222,252,304,380,475],fileio:[256,477],fileitem:143,filelik:423,filelineno:210,filelist:69,filemod:[98,99,265,384],filenam:[12,20,21,52,58,60,63,64,67,68,70,73,80,87,89,96,98,99,101,107,109,113,121,123,125,134,136,138,139,141,143,149,150,151,152,157,158,162,167,168,176,180,186,188,193,197,200,206,210,211,212,221,222,226,227,230,232,234,238,243,244,248,249,251,252,253,256,263,265,266,267,274,288,290,293,295,296,297,303,304,305,306,308,309,313,314,316,320,322,333,334,337,338,342,350,351,359,374,377,379,380,383,384,386,388,394,396,400,403,407,409,416,419,420,422,423,427,429,430,435,440,449,457,458,463,465,471,472,473,474,475,476,477],filename_onli:383,filename_or_fil:427,filename_or_stream:430,filenameobject:20,filenames:463,fileno:[43,52,87,99,127,207,210,238,241,256,287,293,304,306,317,345,360,361,365,368,377,385,386,387,396,409,472,475],fileobj:[234,384],fileobject:[158,320],fileopen:320,filepath:305,fileselectbox:394,fileselectdialog:394,filesystem:[28,63,64,70,72,73,83,89,104,107,131,134,210,263,271,273,293,304,305,314,337,338,342,352,365,367,407,416,461,465,471,477],filetyp:[21,60,120,191,243,404,477],filewrapp:423,fill:[4,6,19,28,33,39,41,48,53,55,56,60,79,82,83,88,93,96,99,100,102,105,106,118,119,123,125,143,168,169,182,186,197,200,230,252,256,258,267,283,304,364,365,368,369,372,374,392,395,396,442,451,463,470,472,473,474,475,476],fillabl:119,fillchar:[368,369],fillcolor:403,filler:258,fillpoint:119,fillstat:403,fillvalu:[258,476],filter:[60,83,88,95,96,98,106,109,120,129,133,152,169,177,180,208,210,214,222,224,245,247,258,266,329,345,384,388,442,453,461,463,470,471,472,473,474,476,477],filtered_data:453,filterfals:109,filterproc:191,filterwarn:[416,471,473],finalbodi:125,finalize_opt:63,financi:463,find:[1,26,28,29,55,60,62,63,64,66,70,72,73,76,77,79,80,81,83,86,89,90,92,95,96,98,100,101,102,104,105,106,107,109,111,120,123,125,129,137,138,143,150,152,158,169,174,180,182,186,194,196,200,202,206,212,218,230,231,232,236,243,244,249,251,252,253,264,265,275,287,289,303,304,311,312,314,315,327,338,340,360,364,365,368,369,372,380,388,391,392,393,396,405,407,409,412,418,426,437,441,442,445,446,447,449,450,451,452,453,455,458,460,461,464,466,467,470,471,472,473,474,475,476,477],find_execut:63,find_first:212,find_g:137,find_glob:311,find_gt:137,find_head_packag:251,find_l:137,find_last:212,find_librari:168,find_library_fil:63,find_load:314,find_longest_match:180,find_lt:137,find_modul:[90,249,251,380,436,447,473],find_msvcrt:168,find_recursionlimit:470,find_user_password:410,findal:[101,152,333,429,462],findcal:265,finder:[60,87,90,115,136,186,243,252,268,270,288,380,447,467,474,476],findertool:[60,252,268,476],findfactor:129,findfil:388,findfit:129,findfont:213,findit:[101,288,333,472],findlabel:182,findlinestart:182,findmatch:274,findmax:129,findtext:429,fine:[60,77,81,82,87,88,89,99,102,104,105,138,162,168,169,186,192,197,202,222,273,303,333,365,396,409,410,455,457,462,463,467,470,471,473,475],finer:[60,90,98,265,304,407],finfo:251,finger:161,fingerprint:278,finish:[21,54,64,76,82,87,88,95,98,99,134,139,148,241,256,293,328,361,364,365,368,384,419,427,429,432,434,435,437,439,447,454,457,463,465,475,476],finish_request:361,finit:[16,22,30,87,93,96,101,178,218,277,368,380,440,455],finlei:333,fiori:476,fip:[235,349],fips180:235,fir:117,fire:[79,123,127,353,469],firefox:[162,410,419,475],firewal:[244,293,425,471],first:[1,3,4,6,12,13,14,15,16,19,20,22,26,28,29,30,32,34,36,37,41,43,47,51,52,55,56,59,60,62,63,70,71,72,73,76,77,79,80,81,82,87,88,89,90,91,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,111,113,117,118,121,123,124,125,126,127,128,129,132,134,137,138,139,140,142,143,146,148,149,150,152,157,160,161,162,163,165,167,168,169,170,174,175,178,180,182,186,191,193,196,197,198,200,202,203,206,207,210,212,213,218,219,222,228,229,230,231,235,236,241,244,246,247,249,251,253,255,256,258,259,260,263,264,265,266,267,270,273,274,277,280,281,282,284,287,290,292,293,294,298,299,302,303,304,305,306,308,309,311,313,317,320,321,322,327,328,330,333,334,339,342,345,346,350,351,352,358,360,361,364,365,366,368,369,370,373,374,377,379,380,382,384,385,386,387,388,389,392,393,394,396,398,400,401,403,406,407,409,410,415,416,418,423,424,426,429,430,434,435,439,440,441,442,445,446,447,448,449,450,452,453,454,455,456,457,459,461,463,465,467,468,469,470,471,472,473,474,475,476,477],first_16:168,first_nam:[167,333],first_sunday_on_or_aft:174,firstchild:426,firstheaderlineiscontinuationdefect:196,firstkei:226,firstli:[160,342,391],firstlin:150,firstlineno:[12,297],firstnam:[223,364],firstweekdai:140,fish:105,fit:[30,63,72,77,81,92,102,104,106,123,136,142,168,169,170,178,182,186,207,221,222,236,293,303,321,322,373,403,407,410,426,437,438,463,473,474,477],fitzroi:473,five:[83,99,125,137,142,178,253,273,311,333,361,364,365,380,398,411,470,476],fix:[1,30,37,42,48,55,60,72,80,81,82,83,86,87,88,90,91,93,95,96,100,101,102,103,107,108,109,120,143,151,152,157,162,168,169,173,174,186,192,197,217,236,244,252,256,258,280,293,301,304,311,333,338,369,373,391,424,437,438,440,465,470,474,475,476,478],fix_missing_loc:125,fix_sentence_end:389,fixabl:337,fixdiv:465,fixed_width:213,fixedoffset:174,fixer:[60,179],fixmenudimst:219,fixpoint:411,fixtur:[60,179,477],fkeyword:223,fl_:212,fl_addto_form:212,fl_bgn_form:212,fl_color:212,fl_end_form:212,fl_getmcolor:212,fl_init:212,fl_mapcolor:212,fl_rgbmode:212,flag:[6,12,16,20,21,24,43,51,52,54,55,58,60,63,76,77,79,87,91,98,100,103,109,111,120,121,125,126,131,134,138,143,148,153,157,162,167,168,169,174,175,176,178,179,188,192,197,200,202,203,207,215,222,225,226,230,234,239,243,246,247,256,264,266,271,273,281,287,290,291,293,297,299,308,311,313,317,318,319,320,321,327,328,331,333,345,350,352,353,356,360,361,364,365,366,367,368,369,374,380,383,386,387,391,392,396,400,401,403,407,411,416,417,422,423,424,429,434,435,440,461,465,471,472,473,474,475,476,477],flag_bit:435,flag_list:246,flagstaff:96,flagstr:246,flaki:95,flash:[93,169],flat:[106,157,180,192,197,199,200,202,396,401],flatten:[157,192,197,198,200,258,311,453],flavor:[63,79,102,186,221,304,320,353,366,368,407,440,442,456,458],flavour:[101,384,475],flaw:[87,88,332,374,472],flawlessli:[469,475,476],fledg:63,flew:454,flexibl:[72,77,87,90,91,94,98,101,106,109,143,152,168,180,186,200,230,265,266,293,303,306,338,365,368,369,374,384,392,416,427,429,440,450,451,462,463,470,471,473,475,477],flicker:[93,169,245],float_info:[90,368,380,461,476],float_repr_styl:[380,461,477],floatabl:303,floatingpointerror:[20,206,216,461],floatmax:119,floatnumb:[442,446],floatobject:216,floattyp:[22,404],flock:[207,273],floor:[41,88,90,100,174,178,186,222,277,300,368,442,460,472,476],floordiv:[96,125,157,302],floppi:181,florent:477,flori:476,flour:364,flow:[30,60,77,96,142,169,170,178,215,219,239,257,304,360,374,385,439,441,442,453,456,470,472,473,475,476],flow_stmt:443,flowinfo:360,flp:[60,252,347,476],flt:218,flt_radix:380,flt_round:380,flup:106,flurri:[93,470],flush:[87,98,99,102,113,127,139,150,169,215,222,256,265,267,273,287,293,304,328,336,350,360,368,377,390,423,429,437],flush_level:99,flush_softspac:215,flusher:113,flushhead:282,flushinp:169,flushkei:113,flushlevel:[99,267],fly:[30,60,79,81,178,222,242,450],fma:178,fmenumer:213,fmfindfont:213,fmgetcom:213,fmgetfontinfo:213,fmgetfontnam:213,fmgetstrwidth:213,fminit:213,fmod:[277,442],fmprstr:213,fmscalefont:213,fmsetfont:213,fmsetpath:213,fmt:[98,174,197,265,306,320,373,463,476],fmtparam:167,fname:[88,266],fnctl:87,fnmatch:[60,211,232,252,374],fnmatchcas:214,fno:76,fnum:99,fobj:449,focal:430,focu:[84,102,174,212,219,244,384,396,401,403,462,477],focus:[62,105,106,238,322,475],foil:358,fold:[79,198,371,438,474,475],folder:[60,64,106,191,246,268,271,273,295,386,467,469],folk:463,follow:[4,5,6,13,16,17,20,24,28,29,30,34,36,37,43,45,48,50,51,55,56,58,63,64,67,70,71,72,73,75,76,77,79,80,81,82,83,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,114,115,116,117,118,119,121,123,124,125,126,127,128,129,132,134,135,136,137,138,140,141,142,143,144,146,147,148,149,150,151,152,154,155,157,158,160,161,162,167,168,169,170,171,173,174,175,176,178,180,181,182,185,186,188,191,192,194,196,197,198,199,200,202,203,205,206,207,208,210,212,213,215,216,217,218,219,221,222,223,225,226,227,228,230,231,232,233,234,235,236,237,238,239,240,241,243,244,245,246,247,248,249,253,256,258,259,260,263,264,265,266,267,270,271,272,273,276,277,278,279,280,282,283,284,287,292,293,294,296,297,298,299,300,301,302,303,304,305,306,308,309,311,313,314,316,317,318,319,320,321,322,323,324,326,328,330,332,333,334,336,338,339,340,341,343,344,345,346,348,349,351,353,354,355,356,358,360,361,363,364,365,366,368,369,370,373,374,376,377,380,381,382,384,385,386,387,388,389,390,391,392,393,394,396,398,399,400,401,402,403,404,405,406,407,409,410,411,412,413,414,415,416,417,418,419,420,422,423,424,425,426,427,429,430,431,432,434,435,436,437,438,439,440,441,442,443,445,446,447,448,451,452,453,454,455,457,458,459,460,461,462,463,465,468,469,470,471,472,473,474,475,476,477],followlink:[304,476],font:[60,104,117,205,212,215,244,252,268,347,389,394,396,401,403],fontnam:[213,403],fontpath:213,fontset:394,fontsiz:403,fonttyp:403,foo1:[72,293,333],foo2:[72,293,333],foo3:333,foo:[24,63,64,66,67,70,72,81,82,88,89,90,91,95,98,99,101,105,106,107,113,114,123,125,143,148,158,162,168,186,200,228,244,249,260,264,265,266,274,293,302,303,304,305,311,314,322,333,338,356,364,368,384,388,407,423,427,429,435,436,439,440,442,470,472,473,476,477],foo_bar:[66,123,303],foo_bcpp:107,foo_inst:88,foo_pars:123,foo_typ:55,foo_var:88,fooaction:123,foobar:[67,88,214,222,241,303,333],food:[77,90,457],foodir:158,fool:[81,88,470,474],foolish:83,foomodul:107,foopkg:67,foord:[105,477],foot:[102,462],footer:365,footnot:[60,66,77,79,101,107,114,143,146,174,186,192,193,195,197,202,203,222,225,230,236,239,260,276,309,311,322,328,339,364,365,368,392,419,427,429,434,439,440,441,442,446,447,449,451,452,453,458,460,461],footprint:[37,93,225],fopen:[21,222],for_it:182,for_loop:475,for_stmt:[439,443],forai:107,forbid:[133,260,338,365,477],forbidden:[105,241,338,476],forbul:95,forc:[4,55,63,64,77,81,87,88,90,96,100,106,107,145,151,156,169,174,175,178,186,197,225,226,235,239,240,244,246,256,259,291,304,322,332,333,348,360,369,373,380,388,392,418,423,454,457,465,477],forcegrai:259,forcetyp:115,forcibl:107,forego:438,foreground:[93,169,212,231,244,401,463],foreign:[60,100,120,252],foreseen:107,forestal:245,forev:[102,126,132,471,472,473,474],forg:338,forgeot:[476,477],forget:[30,63,66,76,77,89,178,364,388,401,442,451,455,474,475,476],forgiv:[90,470],forgot:81,forgotten:[77,104,282,453],fork:[28,52,72,77,87,102,136,206,269,271,287,293,304,316,323,345,352,361,365,386,473,477],forkingmixin:361,forkingtcpserv:361,forkingudpserv:361,forkpti:304,form01:266,form02:266,form03:266,form04:266,form05:266,form06:266,form07:266,form08:266,form09:266,form:[1,4,6,20,26,28,32,33,47,48,50,55,60,63,64,68,72,76,77,81,82,83,84,88,91,93,95,96,98,99,101,102,104,105,106,107,111,113,114,117,123,132,134,141,143,150,152,157,158,160,161,167,168,169,170,174,178,180,186,191,195,200,201,203,215,218,222,228,230,239,240,241,246,247,249,252,253,255,258,259,264,265,266,267,273,275,276,280,281,293,299,304,305,308,310,311,314,316,317,318,321,330,333,339,346,347,348,356,360,364,365,368,369,371,373,376,377,380,384,388,389,391,392,393,395,396,401,403,406,407,409,410,411,412,415,416,423,424,426,429,434,438,439,440,441,446,447,448,450,451,452,454,455,456,457,458,461,463,465,470,471,472,474,475,476,477],formal:[60,63,78,186,192,303,308,333,369,411,430,440,441,442,445,447,452,456,470,472],format:[4,6,20,27,30,36,41,43,50,52,55,56,57,60,62,63,64,70,71,72,73,77,79,82,83,87,88,89,91,94,95,100,101,102,104,105,107,108,109,113,116,118,119,120,122,123,125,127,129,131,132,135,136,138,140,143,145,146,150,152,157,158,162,168,174,178,180,186,191,192,193,194,197,198,200,202,203,205,217,221,222,226,228,230,234,239,240,243,245,246,247,248,252,253,259,260,263,264,265,267,274,276,279,281,283,285,290,295,296,302,303,304,305,306,307,310,313,314,315,316,318,320,321,322,328,331,333,334,335,339,348,350,351,352,357,358,360,361,362,364,365,372,374,376,377,380,385,392,394,395,396,400,401,403,406,407,409,410,411,414,415,416,417,420,423,429,435,436,437,439,440,442,445,451,452,453,454,455,456,460,461,462,465,470,471,472,473,474,475,478],format_cod:16,format_exc:400,format_except:400,format_exception_onli:[186,400],format_field:369,format_help:123,format_list:400,format_spec:[222,369,476],format_stack:400,format_stack_entri:134,format_str:[264,369,463,475],format_tb:400,format_usag:123,formataddr:203,formatarg:253,formatargspec:253,formatargvalu:253,formatd:[203,474],formaterror:[168,273],formatexcept:[99,265],formatmessag:[20,168,206],formatmonth:140,formatmonthnam:140,formatparagraph:244,formatt:[60,120,123,239,252,266,267,282,285,303,369,473,477],formatted_err:407,formatted_lin:400,formatter_class:[60,120],formatter_form01:266,formatter_simpleformatt:98,formattim:265,formatvalu:253,formatvararg:253,formatvarkw:253,formatwarn:[265,416,476],formatweekdai:140,formatyear:140,formatyearpag:140,formcont:143,formcontentdict:143,formed:432,former:[63,64,115,134,150,151,163,168,169,178,259,311,314,322,394,396,403,407,440,442],formerli:[48,124,161,222,265,287,293,307,311,330,332,346,368,392,447],formfe:[369,389,446],formodulenam:[115,116],formula:[81,230],forth:[20,64,70,72,88,93,101,102,107,152,182,304,333,345,470,472,473,475],fortifi:133,fortran:[6,81,455,471,474,476],fortun:[77,79,81,93,143],forward:[56,63,81,92,96,101,106,125,137,146,148,152,168,169,174,175,193,223,230,244,251,273,300,305,308,309,365,403,423,427,440,453,458,464,469,470,471,472,474,476],foster:97,found:[4,13,18,19,26,28,30,43,48,52,55,56,62,63,67,70,72,76,77,80,81,82,83,87,88,89,90,94,95,96,98,99,101,104,105,106,108,111,123,125,126,132,138,139,142,143,150,152,154,155,156,157,158,161,162,163,167,168,169,181,182,186,187,192,196,200,202,206,207,208,216,219,222,225,228,230,233,236,240,241,244,246,249,251,253,263,264,265,266,273,274,276,281,287,288,291,292,293,296,304,306,308,309,314,324,328,332,333,339,346,348,352,353,354,355,358,360,363,364,365,368,369,374,377,380,381,384,385,388,398,401,404,406,407,409,410,416,422,423,426,429,430,431,434,436,438,439,440,441,442,445,446,447,451,452,453,454,457,458,459,461,462,463,467,469,470,471,472,473,475,477],found_termin:126,foundat:[60,61,62,72,84,96,108,268,338,365,438,467,469,473,474,476],four:[26,51,56,81,83,90,91,93,101,102,104,116,118,123,150,157,169,180,182,221,222,241,244,253,266,269,273,284,290,303,328,356,360,361,368,369,376,396,401,403,413,431,446,452,463,476],fourfold:470,fourth:[96,111,158,169,256,321,392,434,472],fourthought:470,foutfil:303,fp1:305,fp2:305,fpathconf:304,fpdef:443,fpectl:[60,206,252,329,438],fpetest:216,fpetestmodul:216,fpformat:[60,252,372,476],fpic:75,fplist:443,fprintf:[76,79],fqdn:358,fqname:251,frac_digit:[264,463],fractalcurv:403,fraction:[60,77,81,83,90,104,152,174,186,222,252,264,277,300,301,304,322,333,364,365,368,391,392,403,442,446,455,460,472,473,474,475,477],fragment1:129,fragment2:129,fragment:[58,60,72,81,82,96,129,135,270,308,328,411,429,475,477],frame:[9,12,20,25,28,30,43,46,58,81,87,88,118,129,134,142,163,169,177,182,253,260,309,344,353,359,365,368,376,377,380,394,396,400,401,404,417,423,439,440,441,471,473,474,475,477],frame_lineno:134,framemak:[169,396],framer:[118,376,417],frametyp:404,framework:[60,63,81,87,95,114,126,141,148,168,177,179,186,191,241,252,254,268,269,284,307,337,355,356,358,365,380,409,410,423,440,465,467,472,473,476,477,478],franc:96,francesco:473,francisco:[341,365],francoi:477,frank:333,frankenstein:389,franklin:477,fraser:473,fread:368,frechet:477,fred:[0,99,328,396,443,470,471,472,473,475,476],fredrik:[0,88,93,96,259,396,405,429,434,438,470,471,472,474,475,477],free:[4,6,8,12,16,22,28,29,30,37,38,45,53,55,56,62,77,79,81,82,83,84,87,88,90,91,92,93,96,100,102,106,107,128,142,150,157,168,180,182,185,187,212,222,225,229,230,293,303,315,330,355,367,370,377,379,380,405,407,418,426,434,438,439,440,441,442,447,456,457,471,472,473,475,476],free_list:476,freebsd:[60,93,304,306,345,380,466,475],freed:[6,22,28,29,37,38,53,56,60,77,79,225,236,293,380,440,463,471,473,475],freedom:[311,447],freefunc:[55,79],freeli:[62,83,100,126,127,186,438,456],freevar:12,freewar:84,freez:[26,88,212,223,249],freeze_form:212,freeze_object:212,freeze_support:293,freht:477,french:[101,104,105,392],frequenc:[99,118,225,376,417,422,476],frequent:[30,60,77,79,87,88,101,102,104,105,159,180,244,257,264,280,293,303,318,407,449,452,453,457,462,464,473,474,476,477],fresh:[55,90,96,150,151,293,321,342,388,468,469,472,473],freshfruit:453,freshli:88,freshmeat:472,frexp:277,fri:203,fridai:140,friedl:[101,333],friend:[30,55,60,77,88,107,159,192,368,474],friendli:[1,55,93,123,303,380,407,442,451,470],friendlier:396,fro:104,frob:[158,228],frobbl:123,frobnic:418,frobozz:368,from:[0,1,3,4,5,6,7,8,9,10,11,14,15,17,19,20,21,22,23,24,26,30,31,33,34,35,36,37,38,39,40,41,43,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,62,64,66,67,68,69,70,71,72,73,75,76,78,79,80,81,83,84,86,90,91,92,93,94,96,100,101,102,103,104,105,106,107,108,109,111,112,113,114,118,119,120,123,124,125,126,127,128,129,131,132,134,136,138,139,140,141,142,143,144,145,146,148,149,150,151,152,154,155,156,157,158,160,161,162,165,167,169,170,171,174,178,180,181,182,186,187,189,190,191,193,194,195,196,197,198,199,200,202,203,204,205,206,207,208,211,212,215,216,218,219,221,222,223,224,225,227,229,230,231,234,235,236,238,239,240,241,243,244,246,247,248,249,250,251,252,253,255,256,257,258,260,263,264,265,266,267,269,270,271,273,274,276,277,279,280,281,283,287,288,289,290,292,293,295,296,297,299,300,301,302,303,304,305,306,308,309,310,311,313,314,315,316,317,318,319,320,322,323,325,326,327,328,330,332,333,334,335,336,337,338,339,340,342,343,344,345,346,348,349,350,351,352,353,354,355,356,357,358,360,361,364,365,366,368,369,370,371,373,376,377,379,380,381,384,385,386,387,388,389,391,392,393,394,395,396,397,398,399,400,401,404,405,406,407,409,410,411,413,414,415,416,418,419,421,422,423,424,425,426,427,428,429,430,431,432,434,435,437,438,439,440,441,442,443,445,446,447,448,449,451,452,453,454,455,456,457,458,459,460,462,463,465,467,468,469,470,471,472,474,475,477,478],from_:[200,273],from_addr:358,from_address:[168,293],from_buff:[168,476],from_buffer_copi:[168,476],from_decim:218,from_float:[178,218,477],from_iter:[258,476],from_param:168,from_splitt:194,from_what:457,fromaddr:[87,266,267,358,365],fromag:101,frombuf:384,fromchild:[87,317],fromdat:180,fromdesc:180,fromfd:[345,360],fromfil:[124,180],fromfile_prefix_char:[60,120],fromfiled:180,fromhex:[368,476],fromkei:[94,152,368,473],fromlin:180,fromlist:[26,124,182,222,249,251,338],fromnam:221,fromordin:174,fromstr:[124,429],fromstringlist:429,fromtarfil:384,fromtimestamp:[17,174,316],fromunicod:124,fromutc:174,front:[30,33,63,88,101,180,197,219,244,255,314,410,416,436,440,442,453,458,460,465,470,473,475,477],frontend:150,frontier:365,frontmost:[219,270],frown:[83,461],frozen:[26,83,168,212,222,249,251,293,314,380,440,447,469,473],frozenset:[48,60,173,222,252,276,321,346,407,418,440,442,461,474,475,476],frozent:168,fruit:[321,440,453],frustrat:88,fs_imp:251,fseek:368,fset:[94,114,222],fsrc:352,fsref:[115,191,269,271],fsspec:[115,191,243,269,271],fstat:[304,305,338,366,472],fstatvf:[304,472],fsum:[222,277,476],fsync:[304,368],ftell:368,ftp:[60,83,105,106,212,252,254,267,296,338,365,406,409,410,411,425,468,470,471,476,477],ftp_open:410,ftp_proxi:409,ftp_tl:[60,254,477],ftphandler:[60,105,254],ftplib:[60,150,252,254,409,471,473,476,477],ftpmirror:[221,472],ftpwrapper:476,ftruncat:[87,304],fts3:364,ftype:469,fudg:161,fulfil:[91,105,132,365,396,471,473],full:[8,28,30,55,60,63,64,71,72,77,81,83,87,88,90,91,93,94,96,98,100,101,105,106,110,124,127,137,140,150,152,156,157,158,159,162,165,167,168,172,174,178,180,186,191,197,205,206,211,213,215,219,220,222,225,227,244,249,250,258,265,267,271,277,279,289,290,293,303,304,306,308,309,315,330,333,339,348,358,360,361,365,368,374,377,380,384,392,396,403,407,411,413,419,423,427,429,434,435,440,441,444,446,447,451,459,460,461,463,465,470,471,472,473,474,475,476,477],full_distribution_nam:315,full_url:105,fullblown:269,fullcircl:403,fuller:471,fulli:[28,55,63,66,73,84,88,100,106,123,141,202,215,219,222,251,255,258,266,267,293,311,315,330,353,358,360,368,374,384,391,407,415,423,426,429,433,436,451,465,469,472,477],fullnam:[156,249,314,436,473],fulltext:364,fulltime_manag:346,fullurl:409,fullwidth:178,fulton:[470,474],fum:81,fun:[87,158,403,407],func1:88,func2:[88,238],func3:88,func4:88,func:[28,38,46,52,63,81,88,90,95,96,123,125,128,134,142,157,160,168,169,205,222,223,238,253,258,265,293,303,322,328,355,364,368,380,388,391,396,399,407,439,474,476],func_:440,func_closur:[109,182,440],func_cod:[253,368,440],func_default:[253,440],func_descr_get:94,func_dict:440,func_doc:[253,440],func_glob:[253,337,440],func_nam:[253,440,474],func_spec:168,funcattr:109,funcdef:[439,443],funcnam:[12,63,76,134,265,439,451],funcobject:94,function_1:81,function_2:81,functional_program:96,functiondef:125,functiontestcas:407,functiontyp:[23,404],functool:[60,103,109,222,252,258,301,368,440,475,476,477],fund:[463,470,475],fundament:[27,28,30,55,60,70,81,83,102,120,293,303,311,321,322,353,367,418,440,470,476],funk:[230,470],funni:[93,129,168,294,311,442],funny_fil:208,furnish:438,furrfu:472,further:[28,36,55,77,79,81,82,83,89,90,92,96,98,102,105,106,114,124,126,127,134,139,143,146,150,161,165,168,181,182,186,206,210,222,228,240,243,244,256,264,265,277,291,303,304,306,309,311,317,333,353,360,361,365,368,370,380,396,425,426,431,432,437,440,442,451,465,470,471,472,473,474,476,477],furthermor:[28,81,87,107,150,256,266,267,273,368],fuse:178,futur:[21,30,60,63,73,79,80,90,95,98,99,100,101,107,109,116,127,151,157,158,161,167,174,181,186,192,204,206,222,224,236,238,252,266,284,296,303,304,308,311,322,329,343,345,360,365,383,388,391,392,404,407,409,415,416,425,429,437,439,440,442,446,451,453,457,461,470,471,472,473,474,475,476,478],future_builtin:[60,109,252,329],future_stmt:447,futurewarn:[20,206,416,461,473,474,477],fuzzili:236,fwrapv:76,fxn:416,g722:118,gabriel:477,gaedk:476,gai:[438,477],gai_strerror:360,gaierror:360,gailli:438,gain:[82,83,87,88,134,139,222,256,377,410,473,474,475,476,477],galeon:419,gallahad:[152,453],gallew:470,game:[86,102,123,450,475,476],gamma:[277,332,407,477],gammavari:332,gap:[273,396],garbag:[3,27,37,44,45,55,59,60,77,81,87,88,90,96,99,102,127,151,168,171,186,206,252,276,293,303,311,329,360,364,380,386,393,407,418,427,440,442,447,463,472,473,474,475,476,477,478],garlic:364,garshol:470,gass:474,gatewai:[60,83,105,252,254,464,475],gateway_timeout:241,gather:[93,123,169,222,322,365,399,407],gauss:332,gaussian:[87,247,332],gave:[88,104,407,477],gawain:477,gaynor:477,gb18030:[150,474],gb2312:[150,406,474],gbk:[150,474],gbyte:435,gcc:[28,63,75,107,168,315,469,476,477],gcd:218,gdb:[82,269,477],gdbinit:[82,477],gdbm:[60,72,87,121,176,188,252,310,350,420,440],gdppc:429,gecko:410,gedmina:104,geert:473,gellekum:471,gen:[96,258,472,473],gen_lib_opt:63,gen_mov:463,gen_preprocess_opt:63,gen_uuid:290,genallsuit:227,genellina:477,gener:[0,1,9,13,15,20,26,27,28,30,32,43,51,55,58,60,63,64,66,67,69,71,72,73,76,77,80,81,82,85,89,90,94,98,99,101,102,103,104,106,107,109,111,113,115,116,117,123,125,126,129,131,134,135,138,143,145,148,150,152,155,160,161,162,163,167,168,169,173,174,175,176,178,179,180,182,184,186,187,188,192,193,200,206,209,211,216,219,221,222,223,225,226,230,235,236,238,240,244,245,246,247,252,253,257,258,262,264,265,266,267,268,269,270,273,275,276,277,285,290,292,293,295,299,300,301,302,304,307,308,310,311,317,318,323,325,328,331,333,334,335,338,340,343,346,348,350,351,353,354,357,358,360,362,364,366,369,370,371,374,378,380,383,384,389,391,392,394,397,398,399,400,401,403,404,406,407,409,411,412,415,418,423,424,425,426,427,429,431,433,434,437,438,439,440,441,443,445,446,447,450,452,453,454,455,456,457,461,464,466,469,470,471,476,477,478],general_category_valu:104,generalis:99,generate_help:63,generate_int:[96,472,473],generate_token:398,generator:472,generator_express:442,generatorexit:[20,95,96,206,253,442,461,475,476],generatorexp:125,generatorproxi:293,generatortyp:404,generic_visit:125,genericbrows:419,genexp:96,genexpr:157,genexpr_for:442,genexprfor:157,genexprif:157,genexprinn:157,genop:312,genshi:106,gensuitemodul:[60,115,116,117,252,270,476],gent0113:174,gentl:[91,123,472],gentler:[101,333],gentli:364,genuin:[77,186,207,477],geoff:77,geograph:[174,464],geometri:[60,344,395,396,401],georg:[258,457,475,476,477],gerald:96,gerber:473,gerhard:[364,472,475,476,477],german:[264,403],germani:364,gestalt:180,get:[4,6,13,20,26,28,29,30,47,51,55,56,58,60,63,66,67,72,75,76,77,79,80,89,90,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,115,118,119,123,127,129,132,134,135,140,142,143,152,157,158,162,168,169,174,178,180,182,186,187,191,192,200,201,203,208,222,224,225,227,228,230,231,233,236,241,243,244,245,246,253,255,256,258,260,263,264,265,266,267,269,270,273,279,288,290,292,293,299,300,303,304,306,309,311,314,315,318,322,323,327,330,332,333,334,339,340,350,351,354,356,358,360,361,364,365,366,368,369,374,376,380,381,384,385,386,388,394,396,401,407,409,410,412,415,417,419,423,426,427,429,430,431,432,434,437,439,440,442,447,448,449,450,451,454,455,459,460,461,463,466,469,470,471,472,473,474,475,476,477],get_al:[192,200,203,423],get_all_break:134,get_all_link:474,get_an_available_item:391,get_app:423,get_archive_format:352,get_begidx:334,get_body_encod:194,get_boundari:[192,200],get_break:134,get_brows:212,get_browser_lin:212,get_browser_maxlin:212,get_buff:424,get_button:212,get_ca_cert:365,get_channel_bind:365,get_charset:[192,200],get_children:[379,401],get_choic:212,get_choice_text:212,get_clock:212,get_close_match:180,get_cod:[251,436],get_complet:334,get_completer_delim:334,get_completion_typ:334,get_config_h_filenam:[63,381],get_config_var:[63,76,304,381,477],get_content_charset:200,get_content_maintyp:[193,200],get_content_subtyp:200,get_content_typ:[193,200],get_count:[225,475],get_counter_valu:212,get_current_history_length:[334,473],get_dat:273,get_data:[314,410,436,476],get_debug:225,get_default:123,get_default_compil:63,get_default_domain:298,get_default_typ:200,get_default_verify_path:365,get_dial_bound:212,get_dial_valu:212,get_dialect:167,get_directori:212,get_distutil_opt:473,get_docstr:125,get_doctest:186,get_endidx:334,get_environ:423,get_errno:[168,476],get_exampl:186,get_field:369,get_fil:273,get_file_break:134,get_filenam:[192,193,200,212,436],get_flag:273,get_fold:273,get_fre:379,get_from:273,get_full_url:[162,410],get_glob:379,get_grouped_opcod:180,get_head:[162,410],get_history_item:[334,473],get_history_length:334,get_host:[162,410],get_id:[379,390,391],get_identifi:379,get_import:314,get_info:273,get_input:[88,212],get_it:182,get_item_point:6,get_iter:114,get_label:273,get_last_error:[168,476],get_line_buff:[334,340],get_lineno:379,get_load:314,get_loc:379,get_lock:293,get_logg:293,get_mag:249,get_main_typ:[192,200],get_makefile_filenam:[63,76,381],get_matching_block:[180,475],get_menu:212,get_messag:273,get_method:[379,410],get_mous:212,get_nam:379,get_namespac:379,get_nonstandard_attr:162,get_nowait:[258,293,330],get_obj:293,get_object:225,get_opcod:180,get_operator_modul:293,get_opt:303,get_option_group:303,get_option_ord:63,get_origin_req_host:[162,410],get_osfhandl:291,get_output_charset:194,get_par:472,get_param:[192,200,203],get_paramet:379,get_path:[381,477],get_path_nam:381,get_pattern:212,get_payload:[192,193,199,200,201,202],get_platform:[63,381],get_poli:403,get_posit:424,get_positioner_xbound:212,get_positioner_xvalu:212,get_positioner_ybound:212,get_positioner_yvalu:212,get_python_inc:[63,72],get_python_lib:63,get_python_vers:381,get_queu:293,get_recsrc:306,get_refer:[55,225,473],get_referr:225,get_request:361,get_rgbmod:212,get_schem:423,get_scheme_nam:381,get_selector:410,get_sequ:273,get_serv:293,get_server_certif:365,get_siz:472,get_slider_bound:212,get_slider_valu:212,get_socket:385,get_sourc:436,get_special_folder_path:64,get_stack:134,get_starttag_text:[240,348],get_stat:96,get_statu:95,get_stderr:423,get_stdin:423,get_str:273,get_subdir:273,get_subtyp:[192,200],get_suffix:249,get_symbol:379,get_termin:126,get_threshold:225,get_tim:212,get_token:351,get_typ:[162,192,200,379,410],get_unixfrom:200,get_usag:303,get_valu:369,get_vers:303,get_vis:273,getabouttext:219,getacl:[246,472],getaddr:339,getaddress:203,getaddrinfo:[105,360,438],getaddrlist:339,getal:192,getallmatchinghead:[162,339],getannot:246,getarg:476,getargspec:253,getargv:191,getargvalu:253,getatim:305,getattr:[79,81,88,98,152,157,168,182,222,293,302,303,369,412,451,461,470],getattrfunc:[55,79],getattribut:[426,440],getattributen:426,getattributenod:426,getattributenoden:426,getattrofunc:[55,79],getbas:328,getbegyx:169,getbkgd:169,getbodyastext:192,getboolean:158,getboundari:192,getbytestream:432,getc:471,getcallarg:[253,477],getcanva:403,getcap:274,getch:[89,93,169,291],getchannel:[119,472],getcharacterstream:432,getcharset:192,getcheckinterv:[380,461,473],getchild:[265,477],getchildnod:157,getchildren:[157,429,477],getclasstre:253,getcod:[409,410],getcolor:153,getcolumninfo:290,getcolumnnumb:432,getcom:[213,253,327],getcompnam:[118,376,417],getcomptyp:[118,376,417],getconf:319,getconfig:119,getcontenthandl:432,getcontext:[178,279,463,474],getcount:[88,302],getcreatorandtyp:269,getctim:305,getcurr:279,getcurrenttim:434,getcwd:[109,304,305,338,462],getcwdu:[109,304,473],getdat:339,getdate_tz:339,getdecod:150,getdecodedpayload:192,getdefaultencod:[380,384,461],getdefaultlocal:264,getdefaulttimeout:360,getdlopenflag:[380,461,472],getdoc:253,getdomimplement:[426,427],getdtdhandl:432,geteffectivelevel:265,getegid:[304,338],getelementsbytagnam:[426,427,470],getelementsbytagnamen:426,getencod:[150,280,292,432],getentityresolv:432,getenv:[304,319],geterrorhandl:432,geterrorstr:269,geteuid:[304,338],getev:428,geteventcategori:267,geteventtyp:267,getexcept:430,getfamili:475,getfd:119,getfeatur:432,getfieldcount:290,getfil:[87,119,253],getfilenam:192,getfilesystemencod:[104,380,384,461],getfillpoint:119,getfirst:143,getfirstmatchinghead:339,getfloat:158,getfloatmax:119,getfmt:306,getfontinfo:213,getfontnam:213,getfqdn:[358,360],getframeinfo:253,getframer:[118,376,417],getfullnam:279,getfunc:133,getgid:[304,338],getgral:233,getgrgid:233,getgrnam:[99,233,473],getgroup:304,gethead:[126,241,339],gethostbyaddr:[304,360],gethostbynam:360,gethostbyname_ex:360,gethostnam:[102,304,360],getincrementaldecod:150,getincrementalencod:[150,167],getinfo:[377,435],getinnerfram:253,getinputcontext:328,getint:158,getinteg:[290,476],getitem:[302,472],getiter:[429,477],getiterfunc:[55,79],getitim:[353,476],getkei:169,getlast:279,getlasterror:[20,168,206],getlength:432,getlevelnam:[99,265],getlin:263,getlinenumb:432,getlist:143,getloadavg:304,getlocal:[174,264,392],getlogg:[98,99,265,473,477],getloggerclass:265,getlogin:304,getmaintyp:[192,280],getmandatoryreleas:111,getmark:[118,376,417],getmaxyx:169,getmcolor:[212,231],getmemb:[253,384],getmessag:[265,430],getmessagefilenam:279,getmessageid:267,getmodul:253,getmodulehandl:168,getmodulehandlea:168,getmodulehandlew:168,getmoduleinfo:[253,476],getmodulenam:253,getmous:169,getmro:253,getmtim:305,getnam:[146,384,391,432],getnamebyqnam:432,getnameinfo:[360,438],getnchannel:[118,376,417],getnfram:[118,376,417],getnod:415,getobject:461,getopt:[60,69,88,91,120,191,252,303,462,473,477],getopterror:228,getoptionalreleas:111,getouterfram:253,getoutput:155,getpages:336,getparam:[118,119,192,280,292,376,417],getparyx:169,getpass:[60,120,165,246,252,291,318,385,387,476],getpasswarn:229,getpath:[30,279],getpayloadastext:192,getpeercert:[365,476],getpeernam:[360,365],getpen:403,getpgid:[304,473],getpgrp:[207,304],getpid:[293,304,338],getplist:[280,292],getpo:240,getppid:[293,304,338],getpreferredencod:[169,230,256,264],getprocaddress:89,getprofil:[279,380,461,476],getproperti:[290,432],getpropertycount:290,getproto:475,getprotobynam:360,getproxi:[105,409,410],getpublicid:432,getpwal:324,getpwnam:[99,165,324],getpwuid:[107,304,324],getqnam:432,getqnamebynam:432,getqueues:119,getquota:246,getquotaroot:246,getrandbit:[332,474],getrawhead:339,getread:[150,167,260],getrecursionlimit:[380,461,470],getrefcount:[90,380,461],getrepli:87,getresgid:[304,477],getrespons:241,getresuid:[304,477],getrlimit:336,getroot:[429,475],getrusag:[304,336,475],getsampfmt:119,getsampl:129,getsampwidth:[118,376,417],getscreen:403,getscrollbarvalu:219,getsequ:279,getsequencesfilenam:279,getservbynam:360,getservbyport:[360,474],getset:[18,55,253],getsetdescriptortyp:404,getshap:403,getsid:[304,474],getsign:353,getsitepackag:[356,477],getsiz:[79,146,247,304,305],getsizeof:[380,461,476],getslic:[293,302],getsocknam:[360,365],getsockopt:[360,365,477],getsourc:253,getsourcefil:253,getsourcelin:253,getspal:363,getspnam:363,getstat:[92,332],getstatenam:434,getstatu:[119,142,155],getstatusoutput:155,getstr:[93,169,290,476],getstrwidth:213,getsubject:267,getsubtyp:[192,280],getsummaryinform:290,getsystemid:432,getsyx:169,gettarinfo:384,gettempdir:386,gettempprefix:386,getter:[43,51,79,94,222,476],gettestcasenam:407,gettext:[60,242,252,264,427,446,462,470,474],gettick:269,gettimeofdai:[174,392],gettimeout:[360,365],gettotalrefcount:461,gettrac:[380,461,476],gettrackinfo:142,getturtl:403,gettyp:[192,280,292,432,475],getuid:[304,338],geturl:[60,409,410,411],getus:[229,246,318],getuserbas:[356,477],getusersitepackag:[356,449,477],getvalu:[81,94,143,167,200,234,256,260,292,311,322,370,388,432],getvaluebyqnam:432,getversionex:380,getwch:[291,476],getweakref:418,getweakrefcount:418,getwelcom:[221,299,318],getwidth:119,getwin:169,getwindowrect:168,getwindowsvers:[380,477],getwrit:[150,260],getx:[94,114,222],getyx:169,ghaer:364,ghi:[152,168,265,474],ghost:438,ghostscript:438,gi_cod:[253,476],gi_fram:[253,475],gi_run:253,giampaolo:477,giant:[106,186],gib:[470,473,475],gid:[99,233,304,324,384,476,477],gif:[72,200,201,232,248,396,403,423,475],gigabyt:[384,425],gil:[21,37,55,60,87,90,130,168,235,476,477],gilfix:473,gilstat:28,git:[73,83],github:[62,83,108,364],giuca:477,give:[6,13,20,26,30,34,55,56,63,64,72,76,77,78,79,80,81,82,83,87,88,89,91,93,94,100,101,102,103,104,106,113,118,123,124,125,129,141,142,143,146,147,148,150,153,168,169,174,177,178,180,186,206,208,213,216,219,221,222,228,230,247,253,256,266,267,269,271,277,281,287,288,293,296,298,303,304,305,309,321,328,332,333,338,339,361,364,365,368,369,374,376,380,391,392,393,396,401,403,407,409,411,419,425,426,427,431,435,440,442,445,448,449,452,455,456,457,460,461,462,463,464,465,469,470,472,473,475,476,477],given:[3,4,6,13,17,20,21,26,28,30,37,43,49,50,51,55,56,58,63,64,68,70,71,72,76,77,81,84,87,90,91,93,96,98,101,102,103,104,105,106,107,109,114,117,118,123,124,125,126,132,134,139,140,142,146,147,148,149,150,152,153,156,158,159,161,162,167,168,169,170,171,174,178,180,182,185,186,193,194,198,200,201,203,204,206,208,210,212,216,218,219,221,222,223,227,228,230,231,233,234,237,241,243,246,247,249,251,253,256,260,264,265,266,267,273,274,277,279,280,281,283,287,290,292,293,296,297,299,300,302,303,304,306,308,309,311,313,314,315,319,320,322,324,327,328,333,339,345,351,352,353,355,356,358,359,360,361,363,364,365,368,369,370,371,373,374,380,382,384,385,391,392,393,394,396,399,400,401,403,406,407,409,410,411,415,416,419,420,423,424,426,427,429,430,433,435,436,437,438,439,440,441,442,445,446,447,449,451,452,453,455,457,458,459,460,461,463,465,470,471,472,473,474,475,476,477],gla:469,glanc:[99,451,473],glb:82,glib:474,glingl:403,glob:[60,72,73,99,134,186,211,214,252,290,305,309,352,374,462,476,477],global:[20,23,26,27,30,45,46,52,55,58,60,68,73,77,81,82,90,92,95,96,105,107,110,123,125,127,128,134,151,152,157,168,169,182,186,194,204,206,210,212,221,222,230,238,241,244,247,249,251,252,253,258,267,268,281,293,297,303,309,311,318,322,334,337,338,342,355,356,358,360,368,369,379,380,384,385,386,390,391,399,403,407,410,412,416,429,439,440,441,443,444,446,448,449,451,452,461,465,467,474,475,476,477],global_stmt:[443,447],globalnam:288,globe:174,glori:30,glossari:[60,70,104,456],glow:403,glu:460,glue:[76,106,270,472,474],glw:476,glyph:[104,213],gmane:299,gmt1:174,gmt2:174,gmt:[60,98,132,174,203,265,365,392],gmtime:[98,99,140,174,203,265,273,316,392,472],gname:384,gnome:[230,307,474],gnosi:96,gnu:[60,63,71,82,88,121,176,185,188,228,234,242,252,264,303,310,350,362,384,438,446,449,458,459,468,470,473,474,476,477],gnu_format:384,gnu_getopt:[228,473],gnutransl:[60,242],gnutype_spars:384,goal:[55,72,79,96,104,222,388,429,445,471,473,475,476],god:322,goe:[1,30,72,80,91,100,101,162,169,170,186,230,266,270,293,303,328,330,400,439,447,461,472],going:[6,63,79,82,87,88,91,96,100,101,102,104,107,118,134,143,174,178,230,236,288,303,322,365,374,423,429,434,440,451,456,470,472,476],golden:469,golf:451,gon:403,gone:[88,90,91,105,241,470,471,473,476],good:[0,1,15,30,45,55,60,67,70,79,81,82,87,88,89,90,91,94,95,98,99,101,102,104,105,106,107,123,143,147,148,168,169,174,180,185,186,195,202,219,222,235,236,270,293,303,304,306,307,308,333,357,364,365,377,389,393,395,396,403,407,409,412,427,434,438,440,451,452,456,457,467,468,470,471,473,474,476,477],goodby:[99,128,454],goodger:[471,472,474],goodi:[107,143],goofi:473,googl:[83,86,87,98,105,419,434,475,476,477],gopher:411,gopherlib:476,gordon:[88,102,470,473],got:[0,48,77,87,91,105,111,152,186,293,358,377,410,442,452,465,475],gotcha:[95,106],gotten:[20,47,86,143,174,178,181,293,305,330,470],gov:[162,235,438,473],govern:[90,178,411,434,438],gpa:451,gpf:470,gpg:[71,475],gpl:[273,438,472],gpled:472,gprof:474,gr_gid:[99,233,473],gr_mem:233,gr_name:[233,473],gr_passwd:233,grab:[30,64,88,98,99,294,391,468,469],gracefulli:[333,391,460,477],gracious:83,grad:403,grade:[103,137,222,368,403,473],gradelevel:373,gradian:403,gradual:[83,471,472],graduat:451,graem:471,graft:73,graham:[453,476],grail:[337,338,419,453],grain:[87,98,169,186,227,265,409],gram:333,graminit:308,grammar:[58,60,82,96,109,149,157,262,308,369,378,397,439,444,445,446,448,470,471,475],grand:[332,429],grandchildren:429,grant:[62,94,101,305,320,338,438,470,471,475],granular:[63,90,99,304,380,393,462],graph:[266,270,303,403,472],graphic:[60,64,85,88,104,107,142,150,165,169,213,248,252,268,327,331,347,394,396,407,419,450,469,476],grasp:[106,427],grave:471,gravi:306,gravit:403,gray25:396,gray50:396,graymap:248,grayscal:259,grayson:396,great:[28,72,76,95,98,106,162,236,333,396,453,475],greater:[6,21,33,34,49,55,56,79,88,92,93,99,103,104,134,135,137,152,169,174,178,180,191,200,215,222,223,230,246,267,277,304,308,309,332,336,337,346,356,358,368,380,397,401,403,407,423,426,437,440,451,452,457,459,460,470,472,473,474,475],greaterequ:397,greatest:[218,368],greatli:[89,106,311,413,462,470,471,472,473,476,477],greedi:[60,150,333,385],greek8:150,greek:[104,150],green2:401,green3:401,green4:401,green:[93,152,153,154,169,231,240,403,418,463,473,474],greenish:169,greenwich:[203,339,392],greet:[109,318,358],greg:[66,69,72,87,107,157,470,472,473,474,475],gregg:470,gregor:476,gregori:[475,476,477],gregorian:[140,174],grei:396,grep:[87,244,374,470],grew:192,grey22grei:245,grey2grey2:245,grey2grey4:245,grey2mono:245,grey42grei:245,greyscal:[245,247,259],grid:[344,401],grip:[265,401],gripe:83,grisbi:476,grok:106,groov:396,gross:475,ground:[66,169],group1:[123,333],group2:123,group:[6,60,62,63,64,73,83,87,90,91,98,99,104,106,107,108,113,120,143,150,152,167,170,178,179,180,186,212,222,246,252,255,258,259,264,273,290,293,299,304,324,328,333,346,352,356,360,363,365,366,368,369,374,384,391,394,401,408,416,425,431,434,439,440,442,445,446,450,460,463,469,470,474,475,476,477],group_mask:475,groupbi:[90,96,223,258,302,474],groupdict:333,grouper:258,groupindex:333,groupn:333,grouppattern:299,grow:[48,53,67,91,95,99,102,106,152,186,236,252,267,307,334,401,438,461,470,474,476,477],grown:[81,186,192,345],grp:[60,99,252,324,363,408,473],grumbl:453,grungi:89,grunt:472,gstate:28,gte:125,gtk:[307,474,476],guarante:[6,8,16,28,30,47,48,50,55,56,59,63,71,76,77,79,81,83,88,93,103,106,113,124,162,168,174,178,180,182,186,197,200,222,235,253,258,276,277,281,287,293,297,303,311,322,330,332,345,368,380,386,389,390,391,398,416,418,423,424,429,431,439,440,465,474,475,477],guard:[55,71,292,327,391],guess:[30,60,87,91,144,150,186,193,201,203,225,252,253,264,281,310,322,339,354,396,409,423,445,451,460,473],guess_all_extens:281,guess_extens:[193,281],guess_schem:423,guess_typ:[193,281,354],gui:[60,64,87,88,89,96,104,116,244,303,307,364,366,395,396,421,450,466,469,476],guid:[1,60,69,78,83,86,89,93,97,100,104,107,108,120,178,180,184,204,213,222,270,306,394,396,452,457,464,468,469,476,477],guidanc:[89,477],guidelin:[1,60,259,362,388,440,470,471,475],guido:[81,83,88,90,180,288,311,396,438,453,461,470,471,472,473,475,476,477],guil:476,guilherm:[476,477],gullibl:143,gumbi:396,gunk:316,gunther:429,gunzip:[107,234],guru:459,gusi:470,gustaebel:474,gustavo:[230,472,473,474,475],gut:[72,143],gvim:467,gvr:[470,472,473,474,477],gward:[66,72],gxx:258,gzip:[60,63,64,73,83,106,122,150,193,210,252,281,352,355,384,425,438,462,470,473,477],gzipfil:[234,384,477],gztar:[63,64,73,352],h2py:380,h_errno:360,habit:[79,102,230,273,452],hack:[81,87,96,186,311,351,409,465,470,471,472],hacker:143,hackeri:82,hackish:475,had:[28,37,63,64,76,79,83,88,90,91,96,99,102,104,109,123,124,125,128,148,150,162,169,178,186,196,236,293,304,309,328,330,339,345,360,364,365,368,369,396,399,407,410,411,426,439,440,452,455,459,469,470,471,472,473,474,475,476,477],haer:476,hagen:477,hagino:472,hairi:303,halanta:104,half:[87,93,169,277,306,360,396,446,455,477],halfdelai:[93,169],halfwai:455,halt:[178,205,303,407,452],halv:[137,360,474,477],ham:[152,180,222,288,404,442],hamish:474,hamlet:[152,470],hammer:[453,470],hammond:[84,267,315,458,469,470,472,473],hamster:180,han:473,hand01:266,hand02:266,hand03:266,hand04:266,hand05:266,hand06:266,hand07:266,hand08:266,hand09:266,hand2:396,hand:[55,72,77,79,81,83,87,88,96,100,101,102,106,107,125,157,168,169,178,197,200,201,216,222,230,255,318,333,339,361,368,392,396,403,413,442,445,447,450,451,453,456,457,460,461,462,463,470,471,472,473,475,476],handdraw:403,handi:[60,63,88,93,94,100,101,102,106,107,140,168,169,180,192,251,303,395,449,450,452,456,461,470,474],handier:350,handl:[4,6,13,26,27,28,29,30,36,37,40,49,51,55,56,58,60,63,64,70,72,77,79,81,82,83,87,88,89,90,91,93,95,96,98,99,100,101,102,103,104,106,107,109,115,117,120,123,126,127,128,132,134,135,136,139,145,149,150,157,160,161,164,167,168,170,173,174,178,179,185,186,187,193,197,205,206,207,212,213,215,216,219,221,222,230,239,240,241,249,252,253,254,256,257,260,262,265,266,267,268,273,280,284,287,288,291,292,293,300,304,305,306,309,311,322,323,332,333,335,339,345,348,350,351,352,353,355,357,361,366,368,369,373,374,380,383,384,386,388,392,394,396,398,409,410,416,418,419,421,423,425,426,429,431,434,435,438,439,440,441,442,446,447,451,452,456,457,459,460,461,462,463,465,467,469,470,471,472,474,475,478],handle_accept:127,handle_charref:[240,348],handle_clos:127,handle_com:[240,348],handle_connect:127,handle_data:[239,240,348],handle_decl:[240,348],handle_endtag:[240,348],handle_entityref:[240,348],handle_error:[127,361],handle_expt:127,handle_imag:239,handle_one_request:132,handle_pi:240,handle_read:127,handle_request:[99,126,132,355,361,423,477],handle_sigpol:377,handle_stackframe_without_leak:253,handle_startendtag:240,handle_starttag:[240,348],handle_timeout:[361,476,477],handle_writ:[126,127],handleerror:[98,265,267],handleev:219,handlelogrecord:99,handlepoint:427,handler:[3,20,24,28,51,52,55,57,60,77,79,84,95,120,125,132,143,145,150,157,169,182,187,206,216,219,239,240,252,254,256,257,266,275,284,293,303,304,322,328,329,348,352,355,364,368,380,382,395,407,410,419,427,428,430,432,433,434,439,440,441,454,470,473,474,475,476,477],handler_class:[132,423],handler_consolehandl:98,handler_hand01:266,handler_hand02:266,handler_hand03:266,handler_hand04:266,handler_hand05:266,handler_hand06:266,handler_hand07:266,handler_hand08:266,handler_hand09:266,handler_ord:410,handlernam:328,handleslid:427,handleslideshow:427,handleslideshowtitl:427,handleslidetitl:427,handletoc:427,handshak:365,hang:[102,105,293,315,345,353,473],hangup:353,hanoi:403,hansen:472,happen:[1,16,20,28,29,30,60,64,77,79,81,87,89,91,92,93,95,99,100,102,105,106,107,119,127,149,168,169,174,180,192,201,202,216,221,236,256,260,264,267,303,304,306,311,328,345,365,368,369,380,385,387,390,391,401,407,410,423,439,440,441,442,446,447,451,452,454,459,461,469,470,472,474,475,476,477],happi:[81,82,83,87,473],har:[148,407],harbor:[338,472,473],hard:[60,63,68,76,77,79,81,93,95,96,99,100,101,102,106,107,119,158,167,169,180,186,198,215,266,303,304,309,322,333,336,337,348,365,384,394,413,440,451,461,470],hardcod:[72,168,348,468],harder:[81,88,106,186,303,458],hardlink:384,hardwar:[1,28,60,63,107,113,129,142,147,169,178,216,231,252,255,306,336,360,375,381,405,415,455,477],hardwir:322,harm:303,harmless:[77,186,338,401],harold:[96,369],harri:[186,475],has:[0,1,2,4,5,6,8,14,15,19,20,21,22,23,26,28,30,35,37,38,40,41,42,43,45,49,50,51,55,56,62,63,64,66,67,70,72,73,75,76,77,79,80,81,82,83,84,87,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,114,115,116,117,118,119,121,123,124,125,126,127,129,130,132,133,134,136,138,140,142,143,144,146,147,148,149,150,151,153,155,157,158,160,161,162,164,167,168,169,170,174,175,176,178,180,181,182,185,186,187,188,189,191,192,196,197,198,199,200,201,202,203,204,205,206,208,210,212,213,215,216,217,218,219,221,222,225,226,228,230,231,235,236,237,239,240,241,243,244,245,246,247,249,250,251,253,256,258,259,260,264,265,266,267,269,270,271,273,276,277,278,279,280,281,283,287,290,292,293,294,296,297,299,303,304,305,306,307,308,309,311,315,316,318,320,322,326,328,330,332,333,334,335,336,338,339,341,343,344,345,346,348,349,350,351,354,355,356,357,358,360,361,364,365,366,367,368,369,373,374,376,377,379,380,381,382,384,385,386,387,388,389,390,391,392,393,394,395,396,400,401,403,404,405,406,407,409,410,411,412,413,416,418,419,420,423,424,425,426,427,429,431,432,434,435,436,437,439,440,441,442,446,447,448,450,451,452,453,454,455,456,457,458,460,461,462,463,464,465,467,469,470,471,472,473,474,475,476,477],has_alpn:365,has_children:379,has_color:[93,169],has_data:410,has_ecdh:365,has_exec:379,has_extn:358,has_funct:63,has_head:[162,167,410],has_ic:169,has_il:169,has_import_star:379,has_internal_subset:328,has_ipv6:360,has_kei:[109,121,138,169,200,251,273,350,368,423,432,440,470,471,472,473],has_nonstandard_attr:162,has_npn:365,has_opt:[158,303],has_sect:158,has_sni:365,has_tlsv1_3:365,hasattr:[43,90,94,105,185,222,251,293,311,334,393,407,461,473,476],hasattribut:426,hasattributen:426,haschildnod:426,hascompar:182,hasconst:182,hasfeatur:426,hasfre:182,hash:[28,43,55,60,79,81,87,90,96,135,152,165,166,174,175,222,226,252,278,300,310,332,346,349,368,410,415,418,437,440,442,446,449,460,461,465,472,473,475,476,477],hash_random:380,hashabl:[19,43,55,88,90,114,152,174,180,218,302,332,346,364,368,418,440,442,473,474,476,477],hashfunc:[55,79],hashlib:[28,60,166,237,252,278,349,438,476,477],hashopen:[138,350],hashtabl:138,hasjab:182,hasjrel:182,haskel:[96,258,470,473],hasloc:182,hasn:[12,28,30,63,79,82,83,87,107,180,309,317,323,328,356,365,374,382,470,471,475,476],hasnam:182,hast:477,hat:[64,70,82,83,107,438,462],hatch:[63,477],haunt:368,hauser:470,have:[0,1,2,4,6,8,11,16,19,20,21,24,26,28,30,37,41,43,50,51,52,55,56,60,62,63,64,65,66,67,68,70,71,72,73,74,75,76,77,79,80,82,86,87,89,90,91,92,93,94,95,96,98,99,101,102,103,104,105,106,107,108,109,110,111,113,114,117,118,119,123,124,125,126,127,128,129,130,133,134,135,137,138,140,141,142,143,146,147,148,149,150,151,152,155,156,157,158,160,161,162,167,168,169,170,171,174,175,178,180,182,185,186,187,191,192,194,196,197,198,200,201,202,206,207,210,212,215,216,218,219,221,222,223,224,225,226,230,231,235,236,238,240,241,243,244,245,246,249,253,255,256,258,260,263,264,265,266,267,268,269,270,271,273,277,279,281,282,283,284,287,290,291,292,293,294,296,297,299,302,303,304,305,306,307,308,309,311,314,317,318,320,321,322,325,328,330,332,333,337,338,339,340,343,345,346,348,350,351,353,355,358,360,361,363,364,365,366,368,369,370,371,373,374,376,377,380,381,382,384,385,386,387,388,389,390,391,392,394,395,396,400,401,403,405,407,409,410,412,413,414,415,416,417,418,423,424,426,427,429,430,431,434,435,437,438,439,440,441,442,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,463,465,467,468,469,470,471,472,473,474,475,476,477],have_argu:182,have_bar:72,have_error:79,have_foo:72,have_long_long:50,have_strftim:72,have_unicod:388,haven:[28,73,91,101,104,143,178,454,476,477],haxx:162,hazard:374,hcom:359,hda:374,hdl:[411,438],hdlr:265,hdr:[87,410],head:[28,55,81,101,132,170,181,193,240,241,251,299,305,322,354,356,361,365,401,403,409,429,470,472],headach:451,header:[3,6,17,22,29,30,55,56,60,66,69,72,77,79,87,88,92,98,101,107,118,119,126,132,135,140,143,146,148,158,161,162,167,168,176,180,186,192,193,194,195,196,197,199,200,201,202,203,207,212,230,231,234,241,246,252,254,267,273,280,281,282,283,295,299,308,318,331,354,358,359,360,365,376,380,381,384,397,400,405,409,410,414,427,434,435,437,438,439,441,451,462,463,471,473,475,476,477],header_enc:194,header_encod:194,header_item:[162,410],header_nam:[198,410,423],header_offset:435,header_valu:410,headererror:384,headerpars:202,headerparseerror:[196,200],headersonli:[192,202],headlin:472,headphon:142,healthi:102,heap:[27,30,37,44,55,60,77,173,252,291,336,463,473,474,476,477],heapifi:[236,463],heapit:258,heapmin:291,heappop:[236,258,463,473,476],heappush:[236,463,473,476],heappushpop:[236,476],heapq:[60,90,173,223,252,330,463,473,474,475,476],heapreplac:236,heapsort:236,heard:[84,451],heart:[81,473],heather:333,heathmor:333,heavi:[20,77,105,370,464,477],heavili:[63,88,107,108,188,358,425,471],hebrew:150,heck:96,hector:474,hedstrom:476,hei:388,height:[93,169,212,213,219,239,244,245,259,290,396,401,403,460,475],heim:[438,476],hel:309,held:[21,26,28,37,87,126,249,256,266,267,293,380,418,435,438,470,475,476,477],hell:77,heller:[88,475,476,477],hellman:365,hello:[60,77,79,82,88,89,92,99,106,109,124,135,143,168,230,240,287,293,313,316,360,361,365,368,374,386,388,389,391,395,407,423,446,451,453,454,457,460,469],hello_world_app:423,hellohellohello:89,helloworld:446,helman:365,helo:358,helo_resp:358,help:[20,50,51,57,60,63,66,67,70,72,79,81,83,89,90,91,94,98,99,100,101,102,104,105,106,107,108,113,120,125,133,143,145,148,150,152,168,169,177,179,180,183,186,192,193,219,221,222,223,227,228,230,231,242,243,250,252,253,255,258,268,270,290,299,304,307,309,317,322,337,338,358,365,368,374,392,393,394,395,396,399,405,407,410,411,429,436,440,443,446,447,448,450,451,452,456,459,461,462,463,465,467,469,470,471,472,473,474,475,476,477],help_:148,help_bar:148,help_str:63,helper:[4,28,60,89,106,168,198,210,237,252,256,257,262,300,317,333,339,352,368,372,393,403,407,409,475,476],helpformatt:[123,303],helpfulli:91,henc:[28,63,66,77,81,91,99,157,164,186,225,243,245,271,294,303,313,322,339,368,373,374,440,442,474],henstridg:[84,230,470,477],her:340,herald:472,here:[4,6,10,20,24,28,30,37,55,62,63,66,70,72,73,76,77,79,81,82,83,87,88,91,92,93,94,95,96,98,99,101,102,103,104,105,106,107,109,114,117,120,123,125,127,129,134,139,143,146,150,152,161,166,167,168,169,174,178,180,186,192,193,195,196,197,198,200,201,202,203,208,212,217,218,220,221,222,230,231,234,239,241,244,246,250,254,255,256,265,266,267,285,286,293,299,303,304,308,309,311,318,328,329,333,336,337,339,348,351,353,358,360,361,362,364,365,366,368,369,377,380,384,387,388,392,393,396,401,403,404,405,407,408,409,410,415,416,419,423,424,426,427,429,436,438,440,442,445,446,447,451,452,453,454,455,457,458,460,461,464,465,467,468,470,471,472,473,474,475,476,477],hereaft:[98,107,322,453,461],herebi:438,herein:438,hermion:186,herror:360,hertz:422,heterogen:[124,368,453],hetland:[472,473],hetting:[94,96,103,473,474,475,476,477],heurist:[88,180,256],hewlett:[86,470],hex:[50,56,88,90,101,102,104,135,150,168,222,224,365,368,369,380,396,415,440,446,461,463,470,471,473,475,476],hex_codec:150,hexadecim:[101,135,150,170,222,224,235,237,240,270,278,303,333,349,368,369,415,446,470,474,476],hexbin4:135,hexbin:136,hexdigest:[235,237,278,349,364,475],hexdigit:[170,290,369,446],hexinteg:446,hexlifi:[135,235],hexrepl:101,hexstr:135,hexvers:[83,380,461],hflag:138,hhhh:[373,470],hhl:[87,373],hhllhh:207,hhmm:[174,246],hhmmss:299,hi_ther:396,hidden:[28,81,89,106,171,191,244,309,322,332,361,368,401,403],hide:[71,93,167,171,186,208,212,256,303,308,374,388,393,401,403,439,440,451,461,473,477],hide_cookie2:162,hide_form:212,hide_object:212,hideturtl:403,hierarch:[60,98,144,249,251,265,266,355,395,401,411,429,447,461],hierarchi:[30,60,70,72,88,98,114,134,178,192,222,252,253,256,260,265,266,293,300,301,311,353,368,380,394,396,401,407,426,429,439,442,444,447,451,457,473,475,478],hierarchy_request_err:426,hierarchyrequesterr:426,high:[27,33,53,60,77,78,81,82,83,86,87,89,98,99,102,105,119,125,127,169,173,177,178,182,189,211,252,254,256,258,280,293,300,304,306,311,322,332,350,365,368,380,382,390,405,419,444,447,450,456,462,463,472,474,475,476],higher:[26,28,60,79,81,87,96,98,99,104,127,128,134,135,157,169,178,194,199,221,230,241,252,254,256,258,265,266,267,288,290,291,299,301,304,307,318,343,352,360,362,364,365,368,380,384,385,390,393,407,409,410,429,437,460,462,471,472,475,476],highest:[82,98,198,225,265,287,311,345,353,365,368,369,380,442,453,476],highest_protocol:[311,473],highli:[28,37,88,89,95,100,101,104,106,246,249,255,311,323,333,364,365,413,473,474],highlight:[81,83,93,169,180,219,244,407,468,470,477],hilbert:403,hill:332,him:470,hinder:95,hindl:473,hindranc:87,hint:[60,82,100,102,106,150,162,192,198,222,230,242,243,244,256,260,311,315,374,396,434,439,447],hippogryph:186,hirokazu:477,hiroshima:438,his:[0,77,87,104,230,340,438,470,472,476,477],hisao:473,histfil:334,histor:[36,55,77,79,96,104,169,269,273,276,306,360,368,407,430,438,477],histori:[60,61,83,85,99,128,148,174,222,236,244,273,295,309,362,368,391,437,456,459],history_get:334,history_truncate_fil:334,historyconsol:334,historypath:458,hit:[89,93,134,146,168,206,219,309,365,368,385,396,399,417,458,475],hither:454,hive:469,hkcu:469,hkei:113,hkey_:[60,421],hkey_classes_root:113,hkey_current_config:113,hkey_current_us:[113,469],hkey_dyn_data:113,hkey_local_machin:[113,469],hkey_performance_data:113,hkey_us:113,hklm:469,hkn:467,hks:77,hksc:150,hline:169,hlinuxtnam:470,hlist:394,hlp:180,hls_to_rgb:154,hmac:[60,166,235,252,267,293,472,477],hmm:405,hmodul:168,hoc:[90,106],hodgson:473,hold:[6,13,20,26,28,30,48,50,51,55,56,58,67,70,71,77,81,83,88,89,90,98,102,104,107,113,123,124,126,132,158,168,178,182,207,222,236,241,245,249,266,267,273,293,308,333,343,350,360,365,368,373,380,396,407,418,427,429,431,437,440,442,447,455,461,470,471,475,476,477],holder:[438,452,477],hole:[143,161,304,313,337,338,355,386,477],holger:475,holi:[369,453],holidai:83,holist:364,home:[28,63,71,72,83,84,86,88,93,101,143,158,169,181,244,273,274,296,304,305,309,313,319,324,328,334,337,338,356,365,374,381,394,396,403,412,435,437,445,449,469,476],homebrew:101,homedr:[107,305],homepag:[63,106,394],homepath:[107,305],homogen:[87,373,424,453,463],honor:[83,187,309,355,380,390,467,476,477],hood:[98,101,104,106,475,476],hook:[26,60,148,168,174,208,210,222,249,251,252,289,314,321,322,329,338,351,362,405,416,436,440,449,450,470,472,475,477,478],hook_compress:210,hook_encod:210,hop:423,hope:[70,102,206,461,470,471],hopefulli:[79,98,99,212],horch:169,horcicka:476,horizont:[104,169,170,215,219,394,401,403,446,458],horler:476,horribl:[106,457],hors:477,horsen:477,host:[28,62,83,87,99,102,106,127,132,150,162,169,170,205,212,221,241,246,267,273,293,296,298,299,304,305,308,318,333,339,357,358,360,361,365,371,373,385,409,410,411,415,423,434,469,470,473,475,476,477],hostipaddr:280,hostmast:365,hostnam:[105,121,143,150,241,293,304,358,360,365,409,411,434,460,470,473,477],hot:[88,106,322],hotshot:[60,177,252,322,475],hotspot:473,hour:[17,88,101,174,267,273,392,435,446,473],hourglass:396,hous:[104,333],houslei:365,houston:266,how:[0,1,6,8,28,30,51,55,60,63,64,67,68,69,71,72,73,76,77,78,79,80,90,91,92,93,94,95,96,97,98,99,100,101,102,104,105,106,109,111,118,120,123,126,128,129,134,137,143,150,152,157,158,161,162,164,167,168,169,174,178,179,180,182,192,193,194,197,198,202,210,216,222,223,225,226,230,232,234,236,241,243,253,256,258,260,265,266,267,269,270,274,277,287,288,293,299,302,304,311,315,322,330,333,334,335,336,360,361,364,365,368,369,371,374,376,377,380,384,386,389,392,393,395,397,399,401,407,410,416,418,423,424,426,434,440,441,442,443,444,446,447,448,449,450,451,453,454,455,457,460,463,464,465,466,469,470,471,472,473,474,475,476,477],howev:[4,5,6,20,21,28,30,37,43,47,55,63,67,68,72,76,77,79,81,82,83,87,88,90,91,92,93,94,95,96,98,99,101,102,104,105,106,107,109,113,123,127,132,138,143,144,150,152,162,168,169,174,178,186,189,192,196,197,200,201,203,206,219,221,222,225,230,231,234,236,244,245,246,251,255,256,265,266,267,273,274,287,290,293,296,302,303,304,305,308,311,324,332,333,338,339,346,356,360,364,365,368,369,373,374,380,383,384,389,390,391,393,400,401,406,407,409,412,413,414,419,423,426,427,431,432,434,438,440,442,446,451,452,453,454,458,460,461,463,465,467,468,469,470,472,473,474,475,476,477],howmuch:318,howto:[60,88,93,100,103,268,333,360,410,434,470,472,477],hoyt:476,href:[143,193,239,240,241,348,410,429,477],hreftyp:168,hresult:168,hstderror:374,hstdinput:374,hstdoutput:374,hstrerror:360,hsv:154,hsv_to_rgb:154,ht2html:410,htbin:144,htm:[93,138,154,174,354,429,472,473,474,475,476,477],html2fo:472,html4:240,html:[60,71,72,81,82,83,88,93,96,98,101,104,105,106,132,140,143,145,154,162,180,187,193,252,275,280,304,307,327,341,348,354,365,396,406,409,410,411,427,429,433,434,437,438,463,465,467,468,469,470,471,472,473,474,475,476,477],htmlcalendar:140,htmldiff:[180,474],htmlentitydef:[60,240,252,275],htmllib:[60,215,240,252,275,348,409],htmlparseerror:[239,240],htmlparser:[60,215,252,275,348],hton:[102,360],htonl:[102,360],http:[1,60,71,72,75,81,82,83,84,87,88,89,93,96,98,99,100,102,104,105,106,107,124,126,131,138,143,150,152,154,160,174,187,193,203,231,235,239,240,246,252,254,257,259,280,293,327,328,341,345,348,355,360,361,364,365,380,406,409,410,411,419,425,427,429,431,434,437,438,440,451,456,460,462,463,464,465,467,468,469,470,471,472,473,474,475,476],http_cooki:161,http_error_301:410,http_error_302:410,http_error_303:410,http_error_307:410,http_error_30:410,http_error_401:410,http_error_407:410,http_error_:410,http_error_auth_req:410,http_error_default:[409,410],http_error_nnn:410,http_host:423,http_open:410,http_port:241,http_proxi:[105,409,410],http_request_handl:126,http_respons:410,http_version:423,http_version_not_support:241,httpbasicauthhandl:[60,105,254],httpclient:127,httpconnect:[60,254,434,476,477],httpcookieprocessor:[60,162,254,474],httpd:[106,132,281,354,423,475],httpdefaulterrorhandl:[105,410],httpdigestauthhandl:[60,254],httperror:[60,410],httperrorprocessor:[60,105,254],httpexcept:241,httphandler:[60,98,105,120,254,266],httplib:[60,87,105,150,252,254,365,410,434,470,473,474,476,477],httpmessag:[105,241],httpobj:87,httponli:[161,476],httppasswordmgr:[60,105,254],httppasswordmgrwithdefaultrealm:[105,410],httpredirecthandl:[60,105,254],httprespons:[60,254,477],https_open:410,https_port:241,https_respons:410,httpsconnect:[241,410,476,477],httpserver:[132,293,423],httpshandler:[60,254],hudson:[438,471,472,473,475],hue:154,huffman:259,huge:[150,161,256,470],hugh:477,hugo:364,hugunin:445,human:[79,81,98,99,104,116,118,162,180,195,230,265,311,315,358,376,378,380,397,406,417,430,442,457,472],humbl:303,humor:364,hundr:[52,83,186,464],hundredweight:105,hung:345,hunt:[28,303],huntsvil:96,hurd:473,hurri:103,hurt:[86,457,474],hwnd:168,hybrid:174,hye:[474,475],hylton:[470,471,472,473,474,475,476,477],hyperbol:[60,180,301,476],hyperlink:[180,239],hypertext:[105,239,240,275,426],hyphen:[67,150,228,303,333,389,396,415,465,473],hypot:[152,277],hypothet:[303,360,470],hzgb:150,i18n:[230,460,470,477],i386:[63,315,381,468],i586:[63,381],i686:[75,410],i_dont_want_to_store_this_cooki:162,i_gain:377,i_setsig:377,ia64:[64,381],iac:385,iadd:302,iain:475,ian:[96,423],iana:[174,281,328,365,427,429],iand:302,ibcarbon:[60,268],ibcarbonruntim:[60,268],ibm037:150,ibm039:150,ibm1026:150,ibm1140:150,ibm424:150,ibm437:150,ibm500:150,ibm775:150,ibm850:150,ibm852:150,ibm855:150,ibm857:150,ibm858:150,ibm860:150,ibm861:150,ibm862:150,ibm863:150,ibm864:150,ibm865:150,ibm866:150,ibm869:150,ibm:[96,104,150,169,178,364,473,475],ibufcount:377,ibuff:126,icanon:87,icc:477,iceland:[150,475],icglu:[243,476],ichiro:472,icinst:243,icmp:360,icn:[60,268],icon:[60,64,86,243,268,271,396,469,472,473],iconcat:302,iconindex:64,iconpath:64,icopaquedata:243,icopen:[60,476],icursor:401,id2obj:418,id_dsa:352,id_rsa:352,idcok:169,idea:[0,15,29,30,45,63,66,70,72,81,82,83,87,88,89,90,91,93,95,98,99,102,106,107,123,127,174,180,186,219,264,306,377,401,403,405,407,412,440,452,456,464,470,472,473,474,477],ideal:[28,55,66,81,96,100,104,140,174,423,456,461,474],idempot:197,ident:[4,16,40,43,50,56,60,71,72,77,87,88,89,94,96,98,102,104,127,142,147,151,161,174,178,180,182,186,197,200,202,207,208,222,230,247,258,265,271,273,290,302,304,308,311,318,322,333,337,338,345,352,353,360,365,368,369,373,380,382,391,394,404,426,429,440,441,448,451,455,472,473,475,476],identchar:148,identif:[76,142,293,371,391],identifi:[20,28,60,63,72,73,77,79,80,88,90,105,107,110,113,116,120,123,125,134,138,146,152,157,167,168,177,182,186,200,205,230,246,249,252,253,266,270,273,284,290,293,299,304,305,308,309,322,328,333,334,340,345,355,358,360,365,368,369,371,379,380,381,390,391,395,396,398,406,407,409,410,411,415,423,425,426,429,431,432,438,439,440,441,444,447,451,454,458,462,463,469,473,474,475,476,477],identify_column:401,identify_el:401,identify_region:401,identify_row:401,idiom:[28,30,60,77,81,90,97,100,103,109,123,186,222,258,293,313,365,380,418,473],idiomat:[100,109,112],idiosyncrasi:473,idiosyncrat:396,idir:63,idiv:302,idl:[60,82,83,88,90,130,168,170,219,229,252,356,395,403,426,427,429,447,458,467,472,473,478],idle_intro:467,idlefork:473,idlelib:[244,473],idlerc:244,idlestartup:244,idlok:169,idn:150,idna:[60,365,372,406,473],idpattern:369,idref:328,ids:[88,230,266,299,304,311],idstr:203,idx:364,ie9:240,iec:380,ieee:[178,216,260,277,373,442,455,474,476],ierr:20,ietf:[365,438],if_stmt:[157,308,439,443],ifdef:[77,470],ifexp:125,iff:[60,186,252,286],ific:369,ified_newdatatyp:79,ifilt:[96,109,222,224,258,473],ifilterfals:[96,109,222,258],iflag:387,ifloordiv:302,ifndef:[77,79,92],ifneed:394,ifs:[125,157],iglob:232,ignor:[4,13,16,22,28,29,30,34,41,55,58,63,66,77,79,80,82,87,90,92,98,101,104,105,126,127,131,134,139,143,148,150,151,152,155,158,162,167,168,169,174,178,180,182,186,188,193,200,202,207,208,215,222,229,230,234,244,248,249,256,260,265,266,273,276,281,292,293,304,305,309,311,314,316,322,328,330,332,333,334,339,345,351,352,353,356,358,361,364,365,368,369,373,374,380,382,384,392,398,399,401,407,409,410,411,415,416,423,426,431,432,436,439,440,446,448,451,452,461,465,469,470,471,472,473,474,475,476,477],ignorablewhitespac:431,ignore_discard:162,ignore_environ:380,ignore_error:[150,352],ignore_exception_detail:[186,477],ignore_expir:162,ignore_pattern:[352,476],ignore_zero:384,ignorecas:[101,333],ignored_nam:352,ignoredir:399,ignoremod:399,ih3:475,ihav:299,ihook:[26,251,405,470,473,476,477],iid:[168,401],iii:77,iiihh:463,iinput:473,iis:30,ijg:259,ill:[95,178,316],illeg:[12,20,41,91,96,104,150,159,200,205,206,231,304,328,338,339,368,392,401,423,426,435,439,440,441,446,447,471,472,474,475,477],illus:[440,455],illustr:[30,88,98,99,105,123,157,162,165,186,240,266,293,364,368,385,442,474],ilmsux:333,ilshift:302,ilu:338,im_class:[253,440],im_func:[94,109,253,368,440,451,476],im_self:[94,253,368,440,451,476],im_us:241,ima:129,imag:[14,37,60,88,90,143,147,162,169,192,193,195,201,222,239,247,252,259,260,286,300,311,336,368,369,395,401,403,405,409,410,418,422,434,440,463],imagenam:401,imageop:[60,252,286,338,476],imagespec:401,imagin:[77,101,403,457],imaginari:[14,60,90,147,300,368,369,440,442,460,476,477],imagnumb:442,imagpart:451,imap4:[60,252,254,318],imap4_ssl:246,imap4_stream:246,imap4rev1:246,imap:[83,96,109,224,246,258,293,318,365,411,473,474],imap_it:293,imap_unord:293,imap_unordered_it:293,imapiter:293,imaplib:[60,101,252,254,318,472,473,474,477],img:[193,240],img_1074:463,img_1076:463,img_1077:463,imgfil:[60,245,252,347,476],imghdr:[60,201,252,286],imglib:[60,248,252,347],imit:[322,476],immateri:107,immedi:[15,21,24,28,30,55,58,71,77,82,87,88,90,93,94,95,96,100,101,103,146,160,167,168,169,178,185,186,191,206,208,210,212,219,222,226,236,239,244,253,259,264,273,291,293,304,306,309,326,330,333,339,348,351,355,360,364,368,369,374,377,385,386,387,390,391,392,401,407,410,422,426,429,431,432,434,439,440,442,454,462,472,473,474,476,477],immedok:169,immin:256,immisch:475,immort:[222,473],immut:[24,30,50,53,55,60,88,90,152,167,168,173,174,178,218,222,256,368,413,415,440,442,451,453,460,470,473,474,475,476,477],immutableset:[346,473,474],imod:302,imp:[60,251,252,253,289,314,338,380],impact:[79,151,238,373],impart:[60,265],impati:477,imperfect:389,impimport:314,impl:427,implement:[3,4,5,6,7,9,12,14,17,20,21,24,25,27,28,29,30,37,39,43,51,55,56,59,60,63,64,68,70,72,76,77,79,83,84,88,89,90,93,94,95,96,98,101,103,104,105,106,110,113,114,117,121,123,124,125,126,127,132,133,134,139,141,143,144,148,149,150,152,157,158,159,160,161,162,163,165,166,167,168,173,174,175,176,178,180,182,192,200,202,205,210,214,216,218,219,221,222,225,227,230,235,237,239,240,241,246,249,250,251,252,253,254,256,258,264,265,266,267,270,271,272,273,275,277,278,282,284,285,286,290,291,293,295,296,299,301,302,303,304,305,310,311,312,315,317,318,319,320,321,322,326,328,330,332,333,334,338,342,343,344,345,346,348,349,350,351,352,353,354,357,358,360,361,364,365,366,368,369,370,374,376,380,384,385,386,388,390,391,392,395,396,398,400,401,403,404,405,407,409,410,411,412,413,416,417,418,419,425,426,428,429,430,431,432,433,434,435,436,438,439,441,442,444,446,447,450,451,452,453,456,458,462,463,465,470,471,472,473,474,475,476,477],implementor:[43,55,60,301,472,477],impli:[6,26,30,37,51,55,63,72,73,91,99,104,107,109,127,156,212,221,222,236,256,294,303,311,328,332,334,339,365,431,436,438,440,442,447,465,476],implic:[107,293,311,425],implicit:[60,77,90,95,99,109,123,180,222,328,360,373,377,380,386,396,440,447,461,477],implicitli:[72,88,90,150,192,201,221,240,246,256,266,290,306,338,342,348,353,358,364,368,369,374,440,446,447,451,452,465,477],impload:314,import_as_nam:443,import_fil:251,import_fresh_modul:388,import_from:[182,443],import_hook:251,import_modul:[88,222,250,251,266,388,447,477],import_nam:[182,443],import_spam:77,import_star:182,import_stmt:[443,447],import_top:251,importantli:[83,95,308],importdl:470,importerror:[20,26,100,118,151,189,190,206,249,251,266,288,293,311,314,338,340,356,365,380,388,426,436,447,461,471,473,476],importfrom:125,importfunc:251,importlib2:100,importlib:[60,88,100,222,252,266,289,447],importmanag:251,imports2:109,importwarn:[20,206,416,461,475],impos:[194,222,260,304,305,311,335,336,337,445],imposs:[20,55,81,83,88,92,125,150,266,293,326,376,391,417,426,440,447,470,471,472,473,474,476,477],impract:96,improb:150,improp:[388,440],improperconnectionst:241,improperli:[217,470],improv:[1,3,20,60,77,81,82,83,90,91,94,99,101,123,126,137,157,222,311,328,349,365,395,426,438,462,463,478],impuls:247,imputil:[60,249,252,289,470,473,477],imul:302,in6_addr:360,in_addr:360,in_class:79,in_dict:79,in_dll:168,in_error:102,in_fil:414,in_json:476,in_table_a1:371,in_table_b1:371,in_table_c11:371,in_table_c11_c12:371,in_table_c12:371,in_table_c21:371,in_table_c21_c22:371,in_table_c22:371,in_table_c3:371,in_table_c4:371,in_table_c5:371,in_table_c6:371,in_table_c7:371,in_table_c8:371,in_table_c9:371,in_table_d1:371,in_table_d2:371,in_test:129,in_weakreflist:79,inabl:[266,304,343],inaccess:[81,252,304,305,409,440,470,473],inaccur:[60,222,472,474],inaccuraci:[81,474,477],inact:476,inaddr_:360,inaddr_ani:360,inaddr_broadcast:360,inadequ:473,inadvert:476,inappropri:[107,206,361,371,440],inbox:[246,273],inc:[88,102,191,365,424,438,470,476],incarn:[106,439],incdir:72,inch:[169,396],incident:[30,88,107,206,438,451,455],inclhead:146,includ:[1,4,6,10,16,17,24,26,27,28,43,46,48,51,54,55,56,58,60,62,63,64,66,68,71,72,73,75,76,77,79,80,81,82,83,84,86,87,88,89,90,91,92,93,94,95,96,98,99,101,103,104,105,106,107,108,113,117,118,123,125,127,131,132,135,138,139,140,143,145,146,147,149,150,151,152,156,157,158,161,162,165,168,169,170,174,178,180,182,184,186,191,192,193,196,198,200,201,202,204,205,206,211,215,216,221,222,225,227,228,230,232,234,235,236,237,240,244,245,246,249,252,253,256,260,261,262,263,264,265,266,270,273,275,278,280,281,290,296,299,300,302,303,304,305,307,308,309,311,315,316,318,319,321,322,326,328,332,333,336,339,340,346,349,350,351,352,355,358,360,364,365,366,368,369,373,374,376,377,380,381,382,384,385,386,388,391,392,394,395,396,398,399,401,404,407,409,410,411,413,414,416,418,422,423,425,426,427,429,431,432,434,435,437,438,439,440,441,442,445,446,447,451,452,453,456,460,461,463,464,465,467,468,469,470,471,472,473,474,475,476,477],include_attribut:125,include_dir:[63,72,75,470],include_queri:423,includesubdomain:365,inclus:[29,30,34,63,68,83,123,143,174,182,205,222,263,265,304,322,333,351,442,445,447,477],incom:[126,127,132,221,236,293,338,361],incompat:[58,72,90,92,100,111,168,192,226,253,260,265,269,271,273,276,333,437,447,465,470,473,475],incomplet:[26,56,60,81,120,135,139,149,150,157,172,222,239,240,243,244,249,266,328,348,368,438,463,473,474,477],incompleteread:241,inconsist:[192,206,446,449,471],inconveni:[88,92,162],incorpor:[49,60,77,83,98,101,106,178,249,265,311,365,374,429,473,475,476,477],incorrect:[99,101,109,149,161,176,185,186,188,206,226,273,303,304,339,368,392,407,414,427,471,472,473,475],incorrectli:[99,131,185,253,303,304,389,440,465],incr_item:30,incrcount:128,increas:[4,41,60,79,81,83,87,88,91,96,98,104,123,150,180,215,253,265,301,365,368,380,401,407,416,437,446,451,470,472,473,477],increasingli:[81,403,455,476,477],incred:106,incref:[30,55],increment:[4,5,20,21,28,30,41,43,45,50,56,60,72,77,79,83,88,96,99,107,120,125,150,152,168,182,191,202,293,303,304,368,383,391,396,401,427,429,439,452,458,470,472,473,474,475,477],increment_lineno:125,incrementaldecod:[13,60,256,372,475],incrementalencod:[13,60,372,475],incrementalnewlinedecod:256,incrementalpars:[60,275],incremented_item:30,incur:[79,152,178,258],inde:[37,89,102,194,365],indefinit:[102,140,169,174,258,267,273,353,385,477],indent:[60,66,83,89,90,101,109,123,125,186,199,206,215,252,253,260,262,312,321,389,393,394,395,397,427,439,443,450,452,458,460,463,465,470],indentationerror:[20,206,461,470],indentedhelpformatt:303,indentlevel:312,independ:[16,28,30,60,63,64,67,72,77,81,83,87,89,93,96,102,106,127,174,186,197,204,242,258,259,264,273,276,332,339,348,368,373,380,392,393,395,396,401,405,407,426,435,438,440,442,457,460,461,470,477,478],indetermin:[178,191,401,416,424,454],index:[6,30,33,41,47,55,56,60,62,64,69,82,83,87,90,93,96,100,101,103,108,113,114,124,125,129,134,137,142,143,148,152,168,182,183,203,206,208,222,230,231,233,236,239,252,253,255,260,266,287,290,293,302,304,310,311,324,328,333,334,336,339,346,354,363,366,367,368,369,380,385,387,390,392,395,400,401,411,426,429,435,439,440,442,447,451,453,460,461,464,467,470,472,474,476,477,478],index_size_err:426,index_str:369,indexbyt:100,indexerror:[20,32,33,41,53,150,152,168,193,200,206,236,258,293,311,332,333,369,400,440,442,447,460,461,470],indexof:302,indexsizeerr:426,indi:119,indian:403,indic:[3,4,6,20,21,28,30,33,36,43,47,49,51,55,56,63,72,73,77,79,83,87,88,90,96,98,101,102,103,104,105,113,114,118,123,126,127,132,134,135,138,142,148,149,150,153,157,158,159,160,162,167,168,169,174,175,178,182,191,200,204,206,215,219,222,228,231,244,246,249,251,252,253,256,258,264,265,266,273,276,281,287,292,293,299,303,304,305,306,308,309,312,315,318,320,321,322,328,330,333,345,359,360,361,364,365,366,368,369,373,374,376,380,383,386,387,391,392,396,397,398,400,401,407,409,410,411,422,423,424,426,429,434,438,439,440,442,446,447,451,452,453,454,460,461,463,471,472,473,474,475,476,477],indiffer:470,indigo:[119,405],indirect:[6,63,77,222,321,438,440],indirectli:[43,51,63,68,100,163,168,328,374,391,440,441,442,453,454],indistinguish:[102,293,322],individu:[4,37,51,55,64,67,69,94,98,101,107,109,118,139,150,167,178,180,182,186,195,201,213,230,246,248,252,258,265,273,279,282,290,291,292,293,304,305,317,333,352,353,355,369,382,385,388,389,392,401,407,409,415,424,429,434,435,438,440,445,446,447,451,453,460,461,465,471,474,475,477],induc:322,industri:438,ineffici:[137,256,368,413],inequ:[178,194,198,407,442,476],inet:[102,360],inet_aton:360,inet_ntoa:360,inet_ntop:360,inet_pton:360,inevit:100,inexact:178,inf:[178,216,222,260,277,368,369,476,477],infer:[63,123,186,266,293,392,463],inferior:107,infil:[87,123,283,313,351,399,463],infin:[101,147,178,216,222,260,277,332,368,369,474,476],infinit:[16,60,81,88,96,101,178,219,236,246,258,276,277,293,295,304,330,333,334,380,407,440,455,470,474,476],infinitesim:293,infix:81,influenc:[63,243,305,311,352,360,416,465,476],info:[6,60,63,72,77,83,84,87,91,98,99,145,150,162,174,213,230,265,266,267,273,293,352,360,376,396,403,409,410,435,442,463,465,467,471,473,475,476,477],infoflag:6,infolist:435,inform:[0,1,3,4,6,8,13,20,22,28,30,37,42,51,55,58,60,61,62,64,66,67,68,69,70,71,72,75,76,77,78,79,80,81,88,89,90,91,95,96,98,101,103,104,105,106,107,108,109,113,117,119,120,123,124,127,128,132,134,136,141,142,143,145,147,150,154,160,162,163,164,167,168,169,174,178,180,182,184,186,194,202,203,206,207,208,212,215,221,222,225,228,231,233,235,237,238,239,240,241,244,246,252,253,258,259,264,265,266,267,269,271,273,274,277,281,282,287,293,296,299,302,303,308,311,314,315,317,318,320,322,326,328,329,330,333,334,337,339,342,349,352,353,358,360,361,365,366,367,368,369,370,374,377,380,384,387,388,390,391,392,394,395,396,399,400,401,407,408,409,410,411,413,416,418,421,423,425,426,427,429,430,431,432,435,437,438,439,440,441,444,445,446,447,450,454,456,457,459,461,463,465,466,467,469,470,471,472,473,474,475,476,477],infoscrap:141,infozip:[63,435],infrastructur:[62,83,106,108,114,126,127,150,157,365,416,476,477],infrequ:361,infring:438,ing:[30,56,82,101,102,162,186,477],ingredi:[60,364],inher:[123,124,391,429],inherit:[4,43,54,55,60,68,79,81,88,90,94,95,106,114,125,144,148,150,152,157,168,169,174,196,206,215,218,221,222,244,253,256,267,270,273,293,303,304,311,357,361,365,366,368,374,379,386,391,395,396,401,413,426,430,431,432,439,440,455,456,470,473,475,476],inhibit:[197,328],ini:[158,351],init:[28,60,63,79,82,89,213,222,281,322,362,394,458,475,476],init_builtin:249,init_by_arrai:438,init_color:169,init_databas:290,init_frozen:249,init_genrand:438,init_glob:342,init_histori:334,init_kei:438,init_lett:475,init_or_s:168,init_pair:[93,169],initarg:293,initbar:249,initcli:77,initerror:92,initfoo:89,initfunc:26,initgroup:[304,477],initi:[2,3,4,16,19,20,24,26,27,30,37,39,51,53,54,55,60,61,63,72,73,76,78,79,82,87,88,89,93,96,98,99,103,104,106,123,124,126,127,128,129,132,135,142,148,150,152,158,167,168,169,178,180,186,191,194,198,201,206,212,213,215,219,221,222,223,225,230,235,236,237,244,246,249,251,256,260,264,265,266,267,273,278,281,282,287,290,293,296,299,303,304,305,308,311,313,318,322,328,332,334,338,339,340,349,351,356,358,360,361,364,365,368,370,374,380,382,385,386,390,391,392,393,396,401,403,407,410,413,416,429,434,437,438,439,440,447,448,451,453,458,460,461,465,468,470,473,474,475,476,477],initial_byt:256,initial_ind:389,initial_valu:[96,256],initialdata:413,initialis:[17,162,342],initialize_opt:63,initkeywdarg:77,initleo:89,initleoc:89,initlog:452,initmodul:[28,72],initmyappc:89,initmyextens:92,initnam:[77,249],initnoddi:79,initnoddy2:79,initnoddy3:79,initnoddy4:79,initproc:[55,79],initrd:181,initscr:[93,169],initshoddi:79,initsig:28,initspam:[77,80],initv:94,inject:[99,265,364,374,409,425,475],inlin:[90,158,180,235,322,333,407,425,473,475],inner:[160,219,253,333,337,346,364,368,403,429,439,474,477],inner_word:333,innermost:[90,186,328,441,442,451,452],innoc:[30,95],innocu:473,innodb:158,inod:[267,304,366],inord:[96,472,473],inplac:[66,210],inplace_add:182,inplace_and:182,inplace_divid:182,inplace_floor_divid:182,inplace_lshift:182,inplace_modulo:182,inplace_multipli:182,inplace_or:182,inplace_pow:182,inplace_rshift:182,inplace_subtract:182,inplace_true_divid:182,inplace_xor:182,input:[0,4,13,14,16,30,42,50,55,56,58,60,63,77,79,81,88,90,91,96,98,102,103,104,105,106,107,109,112,120,123,126,129,131,132,134,135,136,139,141,143,148,149,150,151,152,158,161,167,168,174,178,180,182,186,191,194,197,202,203,206,211,212,218,222,236,239,240,244,245,252,256,258,259,260,277,280,283,292,293,303,304,306,308,309,311,313,314,317,321,323,325,328,331,333,334,336,339,345,348,351,360,364,365,368,374,377,380,384,385,387,388,389,392,394,397,398,401,403,407,409,411,414,423,424,427,429,430,431,432,433,437,440,441,443,444,445,446,447,449,453,454,455,456,459,460,461,463,465,470,473,474,475,476,477],input_charset:[194,200],input_codec:194,inputdata:129,inputerror:454,inputonli:394,inputrc:[334,458],inputsourc:[60,275,430,431,433],inputtyp:370,inquiri:[24,55,79,256,407],inrat:129,ins:[88,96,346,470,472,473,474],insch:169,inscrib:403,insdelln:169,insec:389,insecur:[296,350,355,364,365,386,457,475],insensit:[13,16,60,90,101,103,134,150,152,158,161,192,200,281,305,333,354,364,371,409,416,423,465,474,476,478],insert:[19,26,28,30,33,53,60,63,76,77,81,83,87,101,109,123,124,137,143,152,163,167,169,180,186,191,212,215,216,236,244,249,250,251,256,260,265,282,290,309,314,321,330,334,343,346,357,364,368,369,380,401,416,418,423,426,429,436,439,440,442,447,451,452,453,458,460,465,468,470,473,475,476,477],insert_browser_lin:212,insert_mod:476,insert_text:[334,340],insertbefor:[426,470],insertionloc:117,insertln:169,insid:[4,8,11,28,37,60,63,72,77,79,81,84,88,89,90,93,96,101,102,134,141,160,167,169,178,185,186,187,196,200,204,222,227,240,245,253,255,256,260,290,293,309,333,348,352,394,396,401,403,436,439,447,451,452,453,454,460,465,471,472,473,474,475,476],insignific:369,insist:[87,320,323,396,458],insnstr:169,insofar:[240,273,348,447],insort:[137,463],insort_left:137,insort_right:137,inspect:[60,77,90,100,111,123,125,186,225,235,252,258,265,273,278,308,309,321,327,329,353,356,365,368,380,384,407,409,435,439,465,470,471,472,476,477],inspector:[88,394],inspir:[82,104,106,193,258,260,391,470,471,473,476],insstr:169,inst:[43,79,125,447,454],inst_nam:476,instal:[26,28,30,60,66,68,69,70,71,73,75,76,79,82,83,84,85,87,88,89,90,93,100,105,106,109,113,121,130,134,156,166,183,205,230,244,251,252,254,255,265,267,281,284,286,315,325,329,334,353,356,364,365,374,380,387,394,396,401,403,405,407,410,416,421,423,427,438,449,459,461,464,465,466,471,472,473,475,476,477,478],install_data:69,install_head:[69,72],install_lib:[65,69],install_open:[105,410],install_script:69,installaehandl:284,installautogil:130,installdir:462,installermast:472,installexecutesequ:290,installhandl:407,installuisequ:290,instanc:[6,7,12,13,14,15,17,19,20,21,22,23,24,28,29,30,33,34,38,39,43,45,46,48,50,51,53,54,55,56,60,63,64,70,72,75,77,79,81,87,90,91,93,94,96,98,99,100,101,103,104,105,111,114,115,117,118,123,125,126,127,128,132,133,134,138,139,140,143,146,148,149,150,151,152,157,158,161,162,163,164,167,168,169,174,178,180,186,187,192,194,196,197,198,200,201,202,205,206,208,210,215,218,219,221,222,223,225,230,231,234,238,239,240,241,243,244,246,247,249,253,256,258,260,265,266,267,269,273,276,279,280,282,290,292,293,296,297,299,300,302,303,304,309,310,312,317,318,321,322,328,332,333,335,337,338,339,340,343,346,348,350,351,352,355,358,360,361,364,365,369,374,376,379,380,381,384,385,388,389,391,393,396,399,403,404,407,409,410,411,413,415,416,417,418,419,422,423,424,426,427,429,430,431,432,434,435,436,439,441,442,446,447,452,453,454,456,457,460,461,462,465,470,471,472,473,474,475,476,477],instance_dealloc:79,instance_new:79,instancemethod:[297,368],instancemethod_cal:94,instancetyp:404,instant:[60,177],instanti:[20,63,79,87,98,105,114,116,117,138,143,146,148,152,168,169,174,180,200,202,206,215,222,230,240,241,246,265,266,273,292,293,300,303,309,311,320,332,338,339,348,351,357,358,361,368,396,401,407,419,424,426,427,430,432,451,454,475,476],instantli:[93,403],instat:401,instead:[3,4,9,12,15,16,20,21,22,26,28,37,41,43,51,52,55,58,60,63,72,76,77,79,80,82,87,88,89,90,91,92,93,94,96,98,99,101,102,103,104,105,106,107,113,123,128,131,132,135,137,139,142,143,144,145,149,150,151,152,155,157,162,167,168,169,174,178,180,184,185,186,189,191,192,193,195,197,198,200,202,203,204,206,212,213,219,222,224,226,228,230,231,236,237,238,239,241,244,246,249,256,258,260,264,267,269,270,273,276,277,278,279,293,297,299,302,303,304,308,309,310,311,314,319,320,321,322,325,326,327,328,332,333,334,338,339,343,346,348,349,350,353,360,361,365,368,369,370,373,374,380,381,384,385,386,390,391,394,396,400,404,405,406,407,409,410,411,413,416,418,423,425,426,427,429,431,439,440,442,443,446,447,450,451,452,453,455,456,457,458,460,461,462,463,465,467,468,470,471,472,473,474,475,476,477],instert:303,institut:[62,108],instr:169,instream:351,instruct:[60,62,63,72,73,80,81,87,89,90,96,107,143,153,157,167,178,186,240,253,262,303,322,328,353,364,365,380,393,407,426,429,431,440,442,447,470,475,477],instrument:322,insuffici:[26,178,186,293,304],insufficient_storag:241,insul:28,insuper:101,int2ap:246,int_curr_symbol:264,int_frac_digit:264,intact:[87,92,99,174,210,219,369,423,474],intargfunc:55,intarray5:168,integ:[4,5,6,13,15,16,20,30,36,37,39,41,43,49,55,56,60,63,76,77,79,81,87,90,91,92,93,95,96,99,100,101,102,104,105,113,115,118,119,123,124,126,127,129,132,139,140,141,142,147,152,158,162,168,169,170,174,178,185,186,191,205,206,207,210,215,217,218,221,222,224,225,231,233,234,241,246,249,251,253,256,258,260,264,265,266,267,269,276,277,287,290,293,300,302,303,304,308,311,316,318,322,324,328,330,332,333,334,335,336,338,345,352,360,361,363,364,365,369,373,374,376,380,387,390,391,392,396,401,403,404,406,411,415,416,424,426,427,429,434,437,439,440,442,447,451,452,454,455,457,460,462,465,470,471,473,475,477,478],integertyp:426,integr:[60,69,77,84,88,89,90,106,120,178,184,186,244,277,300,317,333,361,368,373,395,407,440,442,460,467,468,470,473,474,476],integrityerror:364,intel64:381,intel:[28,63,89,102,129,306,322,373,467,475,477],intellectu:438,intellig:[300,303,305,306,309],intend:[20,26,28,63,68,72,76,77,79,81,87,90,91,96,98,99,101,105,107,138,143,150,152,157,161,163,174,186,188,222,223,245,251,256,265,267,273,276,292,299,304,311,314,315,348,356,360,365,368,369,373,374,380,383,390,396,399,401,403,407,409,410,423,427,434,435,439,440,445,446,447,452,453,454,461,465,470,471,472,473,474,475,476,477],intens:[90,169],intent:[20,26,76,77,174,200,230,277,360,368,369,407,413,423,440,473,474,476],intention:[365,423,434],inter:[141,180,259,317,353,463],interact:[2,20,30,37,52,58,60,63,76,82,83,87,88,89,90,95,99,101,106,107,112,123,125,134,157,159,162,169,172,178,179,182,202,206,210,212,215,222,244,252,256,268,293,303,304,306,309,321,322,327,329,334,337,340,365,374,380,385,390,394,395,396,400,401,403,407,409,412,429,435,440,443,444,445,446,447,450,451,452,456,460,461,462,465,472,473,474,477,478],interactiveconsol:[149,334],interactiveinterpret:149,intercept:380,interchang:[92,99,104,106,118,142,146,235,256,260,265,311,322,368,440,446,457,462,470,476],interest:[19,21,55,60,64,68,72,76,77,79,80,81,83,87,88,93,96,98,99,101,102,106,107,127,143,146,147,152,157,168,174,180,186,202,207,208,216,222,236,238,265,273,275,281,296,301,303,322,328,337,345,368,376,391,393,395,407,410,416,417,431,440,445,447,462,464,470,471,472,473,475,477],interestingli:[103,333],interf:[90,178,393],interfac:[4,6,26,27,28,30,42,55,56,58,60,63,64,70,71,72,76,77,79,83,85,88,90,93,94,95,96,98,100,101,104,105,107,114,119,120,121,122,123,124,128,131,132,136,139,140,142,144,146,148,150,152,158,162,163,164,165,167,168,169,172,177,179,183,185,186,188,189,190,192,199,200,201,202,207,210,211,219,220,222,226,228,230,233,234,235,238,239,241,243,244,249,252,254,255,257,258,259,264,265,268,269,270,273,275,278,279,281,285,286,290,294,297,302,303,305,306,308,309,310,311,315,316,317,318,319,320,322,324,327,328,329,331,337,339,342,343,345,347,348,349,350,353,354,361,362,363,368,370,372,374,375,376,377,379,382,384,387,390,392,394,398,400,402,403,405,408,410,411,413,414,415,416,417,419,421,423,425,426,427,429,430,431,433,438,440,444,450,456,461,466,469,470,472,473,474,475,476,477],interfacebuild:[60,268],interfer:[79,98,106,108,264,393,412],interior:[401,403,471,472],interlac:245,interleav:[186,293,477],interlin:180,interlock:391,intermedi:[82,87,90,96,150,178,192,201,258,277,303,304,308,352,364,365,475],intermediari:[63,64,70],intermezzo:[60,78,456],intermingl:106,intermitt:391,intermix:[106,228],intern:[4,6,7,8,19,20,21,26,28,30,36,37,48,50,52,54,55,56,60,63,77,79,81,83,87,89,90,93,94,96,100,101,104,105,106,109,120,123,124,125,128,139,147,148,149,150,152,158,162,168,173,174,175,186,192,199,202,204,206,222,226,235,238,243,244,252,256,258,263,264,265,267,273,277,279,281,287,289,293,304,308,309,310,311,321,322,328,332,336,339,345,348,351,360,364,365,371,374,378,380,384,385,388,391,392,394,395,396,400,401,403,407,415,416,418,426,427,429,431,434,435,437,439,440,442,447,449,452,455,461,465,471,472,473,474,475,476,477],internal_attr:435,internal_server_error:241,internald:[101,246],internaldate2tupl:246,internalsubset:426,internation:[60,104,170,192,252,291,295,371,372,392,446,460,462,470,473,474],internet:[60,83,97,100,102,104,131,162,204,221,227,235,240,244,252,268,274,278,299,331,337,339,358,360,361,365,372,392,409,410,411,438,456,470,473],interoper:[60,106,129,295,365,457],interp:28,interpformcontentdict:143,interpol:[63,158,217,245,368,442],interpolationdeptherror:158,interpolationerror:158,interpolationmissingoptionerror:158,interpolationsyntaxerror:158,interpos:192,interpret:[4,6,15,16,20,21,26,27,29,30,34,37,41,43,45,46,51,52,55,56,58,60,63,72,73,75,76,77,79,82,83,88,89,90,92,93,94,96,98,99,100,101,104,106,107,108,109,112,123,124,128,138,143,145,150,155,157,158,159,167,168,169,174,178,182,186,202,203,204,206,211,215,219,220,222,231,235,244,246,249,252,255,256,258,260,261,265,266,268,284,287,290,292,293,297,302,303,304,308,309,311,315,317,319,320,321,322,324,325,327,328,329,333,334,338,339,342,345,348,350,351,353,354,356,358,360,365,367,368,369,370,372,374,376,380,387,388,390,391,392,394,396,400,401,404,405,407,409,416,419,422,426,429,435,438,440,441,442,443,444,445,446,447,448,449,450,451,452,453,455,456,457,460,461,463,465,466,468,469,470,471,473,474,478],interprocess:[60,252,293,360],interrupt:[20,28,143,169,170,178,205,206,244,273,293,353,361,364,385,390,391,407,409,422,438,449,452,454,476,477],interrupt_main:390,intersect:[152,346,368,440,453,473,474,476,477],intersection_upd:[346,368,473,476],interspers:[99,303],interv:[98,169,174,267,304,322,353,380,391,401,403,405,474,476],interven:[77,180,186,199,311,368,369,463],intervent:[94,304,317,374,396],intim:[312,315,380],intintargfunc:55,intintobjargproc:55,intltext:117,intlwritingcod:117,intobjargproc:55,intoler:104,intpart:446,intr:169,intra:[60,141,180,456],intraclass:451,intralin:180,intric:403,intricaci:[230,303],intrins:[15,158,302,440],intro:[148,365,467,477],introduc:[42,60,77,81,83,89,90,92,94,96,98,100,101,111,131,151,157,162,192,202,212,215,222,228,230,273,293,303,311,322,351,369,379,386,394,401,403,411,427,429,430,440,441,445,447,450,451,452,456,460,461,470,471,472,473,474,475,476,477],introduct:[27,60,69,78,91,93,106,108,111,123,177,186,252,254,268,310,360,362,365,393,395,396,413,440,444,456,459,467,474,478],introductori:[83,86,91,101,104,360,396,475],introspect:[79,88,90,152,157,355,434],intrud:355,inttyp:[29,288,404],intuit:[81,98,101,143,178,180,394,442,470,471,472],intvar:396,inu:309,inuse_attribute_err:426,inuseattributeerr:426,inv:302,invalid:[20,24,30,54,60,77,81,83,91,95,98,105,113,120,149,151,152,161,168,178,181,186,200,205,206,216,222,225,226,230,240,243,249,260,266,273,277,293,303,304,305,306,311,323,333,336,345,348,353,360,369,374,376,384,388,390,391,392,401,407,416,417,418,426,447,452,453,454,460,461,465,470,476,477],invalid_access_err:426,invalid_character_err:426,invalid_modification_err:426,invalid_state_err:426,invalidaccesserr:426,invalidcharactererr:426,invalidmodificationerr:426,invalidoper:[178,474,476,477],invalidstateerr:426,invalidurl:241,invalrect:219,invalu:[127,186,333],invari:[81,96,178,200,236,258,311,440,451],invent:[81,95,102,104,150,273,391,442,445,473,477],inventor:[273,396],inventori:[142,152,302],invers:[77,135,140,147,161,178,203,222,277,302,311,339,392,442,476],invert:[96,125,150,157,178,302,368,442],invest:98,investig:98,invis:[93,150,169,171,346,403,477],invit:[450,467],invoc:[20,71,75,77,90,94,168,204,276,293,322,391,400,423,431,439,440,449,451,465,466,467,468,474],invoic:476,invok:[4,17,20,26,30,31,45,51,52,55,56,60,62,63,71,79,87,88,96,99,101,107,123,134,143,148,160,162,174,186,204,222,223,227,232,253,264,265,284,293,303,304,305,308,309,311,314,322,325,327,333,334,342,352,354,355,358,361,364,365,368,369,374,380,385,391,393,396,399,401,407,423,430,431,432,434,439,441,446,447,448,451,456,460,461,462,465,471,472,473,474,475,476,477],involuntari:336,involv:[1,24,37,62,63,72,77,79,81,90,94,106,125,147,160,162,169,178,186,206,219,223,225,249,293,300,303,322,364,365,368,373,407,410,440,442,447,451,461,470,477],inward:178,iobas:[207,256],iobench:477,ioctl:[60,124,252,306,360,377,408,474,476],ioerror:[20,87,95,128,146,162,206,207,210,221,222,230,253,256,291,293,304,306,320,334,337,338,345,352,353,354,360,365,368,384,409,410,436,452,454,461,476,477],ior:302,ip_:360,ip_address:360,ip_hdrincl:360,ip_str:360,ipaddrlist:360,ipadi:396,ipadx:396,ipc:60,ipd266:[472,473],ipo:129,ipow:302,ippolito:[475,476,477],ipport_:360,ipproto_:360,ipproto_ip:360,ipproto_tcp:360,ipv4:[360,476],ipv6:[360,365,411,472,476,477],ipv6_:360,ipython:[458,476],ipz:368,irc:106,irepeat:302,iri:213,irix64:[63,381],irix:[60,63,118,119,252,319,381,390],ironpython:[90,315,445,476],irregular:472,irrelev:[186,303,477],irrit:[384,473],irshift:302,irv:453,is_64bit:315,is_:[96,302],is_al:[293,391,476],is_assign:379,is_block:162,is_builtin:249,is_canon:[178,477],is_character_junk:180,is_data:292,is_declared_glob:[379,477],is_empti:126,is_even:[96,434],is_expir:162,is_finit:178,is_fre:379,is_frozen:249,is_glob:379,is_goal:463,is_hop_by_hop:423,is_image_fil:475,is_import:379,is_infinit:178,is_integ:368,is_jython:388,is_line_junk:180,is_linetouch:169,is_loc:379,is_moon_ful:303,is_multipart:[192,196,200,202],is_namespac:379,is_nan:178,is_nest:379,is_norm:178,is_not:[96,302],is_not_allow:162,is_optim:379,is_packag:436,is_paramet:379,is_parameter_ent:328,is_py3k:92,is_python_build:[381,477],is_qnan:178,is_referenc:379,is_resource_en:388,is_script:227,is_set:391,is_sign:178,is_snan:178,is_subnorm:178,is_tarfil:384,is_term_res:169,is_track:[225,477],is_unverifi:410,is_verbos:477,is_wintouch:169,is_zero:178,is_zipfil:[435,477],isaac:333,isab:[272,305],isabstract:[253,476],isal:391,isalnum:[170,368],isalpha:[170,368],isascii:170,isatti:[52,146,256,304,368,457],isblank:170,isblk:384,isbn:[396,464,469],isbuiltin:253,iscal:[302,477],ischr:384,isclass:253,iscntrl:170,iscod:253,iscom:339,isctrl:170,isdaemon:[391,476],isdatadescriptor:253,isdecim:[100,368],isdev:384,isdigit:[170,368],isdir:[272,305,314,352,384],isdisjoint:[152,368],isdown:403,isel:429,isen:225,isenabledfor:[98,265,477],isendwin:169,iseof:397,iserl:147,isexpr:308,isfifo:384,isfil:[193,272,305,384,449],isfin:328,isfirstlin:210,isfram:253,isfunct:253,isgener:[253,476],isgeneratorfunct:[253,476],isgetsetdescriptor:253,isgraph:170,ish:[63,449],ishead:339,ishelllink:64,isindex:143,isinf:[147,277,476],isinst:[55,81,88,90,98,99,104,109,114,143,152,198,222,260,300,302,346,404,407,440,451,461,470,473,474,476],isjunk:180,iskeyword:261,island:93,islast:339,isleap:140,islic:[96,152,222,258,475],islink:[305,352],islnk:384,islow:[170,368],ismap:239,ismappingtyp:302,ismemberdescriptor:253,ismeta:170,ismethod:253,ismethoddescriptor:253,ismodul:253,ismount:305,ismultipart:192,isn:[19,28,45,55,60,62,63,64,70,77,79,82,87,88,91,93,100,101,102,104,107,113,132,149,150,160,162,167,174,186,192,194,198,199,200,212,225,236,239,246,253,256,267,304,328,333,360,361,365,366,368,380,381,407,419,422,423,425,434,440,451,459,460,468,470,471,472,473,474,475,476,477],isnan:[147,277,453,476],isnontermin:397,isnot:125,isnumbertyp:302,isnumer:[100,368],iso2022_jp:150,iso2022_jp_1:150,iso2022_jp_2004:150,iso2022_jp_2:150,iso2022_jp_3:150,iso2022_jp_ext:150,iso2022_kr:150,iso2022jp:150,iso2022kr:150,iso8601:[98,265,266,434],iso8859:150,iso8859_10:150,iso8859_11:150,iso8859_13:150,iso8859_14:150,iso8859_15:150,iso8859_16:150,iso8859_2:150,iso8859_3:150,iso8859_4:150,iso8859_5:150,iso8859_6:150,iso8859_7:150,iso8859_8:150,iso8859_9:150,iso:[104,150,174,180,194,198,200,210,239,259,264,283,328,364,380,415,433,434,446,470,474],iso_8859:474,iso_8859_1:104,isocalendar:174,isoformat:[174,473],isol:[58,81,90,96,106,108,174,186,244,364,407],isolation_level:364,isomorph:470,isort:88,isoweekdai:174,ispe:387,ispkg:314,isprint:170,ispriv:186,ispunct:170,isqueu:212,isrc:142,isread:321,isrecurs:321,isreg:384,isreservedkei:161,isroutin:253,issamenod:426,isselected_browser_lin:212,issequencetyp:302,isset:391,isspac:[170,368],isstdin:210,isstr:288,issu:[20,28,58,60,62,72,79,83,90,98,99,100,104,106,122,123,127,148,150,167,169,174,178,194,215,218,221,222,225,229,235,241,256,257,264,265,273,276,293,303,304,310,311,365,374,392,403,416,418,425,438,454,456,458,463,465,470,471,472,474,475,477],issubclass:[54,81,90,114,222,416,440,451,461,470,476],issubset:[346,368,473],issue12524:241,issue3770:99,issuer:365,issuit:308,issuperset:[346,368,473],issym:384,ist:309,istermin:397,istext:135,istitl:368,istraceback:253,isub:302,isupp:[170,368,407],isvis:403,isxdigit:170,it1:258,it2:258,ital:215,itali:96,italian:403,itamar:472,itanium:[63,373,381,470],item:[2,4,13,19,20,22,26,28,29,30,31,32,33,35,38,47,53,55,56,60,77,79,81,82,87,90,95,96,99,100,103,106,109,113,121,123,124,125,126,127,129,137,138,143,149,152,157,158,161,163,168,176,180,182,186,191,192,193,200,203,206,219,221,222,225,226,233,234,236,244,246,249,251,253,258,260,265,266,273,280,281,293,299,302,304,311,314,315,319,322,324,330,332,333,334,339,342,352,356,359,363,364,365,368,369,373,374,376,380,385,387,391,392,394,395,396,398,400,403,404,411,418,423,424,426,429,432,434,435,436,439,440,442,445,447,451,452,453,457,460,461,463,471,472,473,474,475,476,477],item__:440,item_path:475,item_separ:260,itemgett:[90,103,258,302,474,475],itemlist:33,itemnam:461,items:[6,124,293,368],items_list:451,itemsview:152,iter1:476,iter2:476,iter:[2,15,19,25,27,28,43,48,55,60,79,81,90,94,101,103,109,114,124,125,134,139,140,143,150,152,157,158,160,162,167,168,182,192,200,206,211,222,223,224,230,232,234,236,252,253,256,260,264,273,277,293,295,301,309,311,312,322,333,345,346,364,369,384,388,398,404,407,409,411,413,418,423,426,429,431,434,439,440,447,452,453,456,461,470,471,473,475,476,477,478],iter_child_nod:125,iter_except:258,iter_field:125,iter_import:314,iter_modul:314,itera:96,iterable1:476,iterableuserdict:413,iterb:96,iterchar:364,iterdecod:150,iterdump:364,iterencod:[150,260],iterfind:429,iteritem:[96,109,121,138,273,288,368,413,418,423,440,453,472,473,474],iterkei:[96,109,273,288,368,440,472,473,474,476],iterkeyref:[418,475],itermonthd:140,itermonthdai:140,itermonthdays2:140,iternextfunc:[55,79],iterpars:429,itertext:[429,477],itertool:[60,90,109,152,222,223,224,236,244,252,288,293,301,302,473,474,475,476,477],itertools_import:109,itervalu:[96,109,273,368,440,472,473,474],itervalueref:[418,475],iterweekdai:140,itimer_prof:353,itimer_r:353,itimer_virtu:353,itimererror:353,itn:258,itojun:472,itruediv:302,its:[0,3,4,5,6,7,8,10,11,14,20,21,22,24,26,28,29,30,34,37,41,43,45,48,50,51,53,54,55,56,58,62,63,72,73,76,77,78,79,81,82,83,87,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,114,121,123,124,125,126,127,132,134,137,138,142,143,147,148,150,152,156,157,158,160,162,163,167,168,169,170,174,178,180,182,185,186,187,191,192,194,195,196,198,200,202,203,204,206,210,215,216,219,221,222,224,225,227,228,230,231,235,236,239,240,243,244,246,249,253,256,258,260,265,266,267,273,277,279,281,284,287,288,292,293,294,299,302,303,304,306,309,311,313,314,316,317,318,321,322,323,326,327,328,329,332,333,334,336,337,338,339,340,351,352,355,356,358,360,361,364,365,368,369,373,374,379,380,381,384,386,388,389,390,391,393,394,395,396,399,400,401,403,406,407,409,410,412,413,415,416,417,418,419,423,426,427,429,431,432,433,434,435,437,438,439,440,441,442,445,446,447,448,450,451,452,453,454,455,456,457,458,459,460,461,462,463,465,467,469,470,471,472,473,474,475,476,477],itself:[0,1,4,9,28,37,43,55,59,60,63,64,68,71,72,75,76,77,79,81,88,90,93,94,95,96,98,101,105,106,107,116,123,125,132,134,138,140,143,148,152,157,161,162,165,168,169,170,174,184,186,191,194,206,207,215,216,219,222,227,229,244,249,258,260,266,267,273,287,290,291,293,299,303,304,305,308,310,311,322,328,333,336,338,339,351,357,360,365,368,369,371,374,380,381,384,385,387,388,390,391,396,401,403,407,409,410,414,416,430,431,432,434,436,440,441,445,446,447,451,460,464,465,470,472,473,474,475,476,477],itu:259,ium:460,ival:29,ixor:302,izip:[90,96,109,224,258,474],izip_longest:[258,476],ja_jp:174,jack:[142,333,339,346,368,414,438,453,457,467,472,473,475],jackdaw:99,jacob:476,jacqu:477,jai:[96,471],jail:99,jake:477,jam:303,jame:[84,230,436,438,470,473,475,477],jan:[96,113,174,221,365,472,477],jane:[103,346],janic:346,jansen:[339,414,438,472,473],janssen:476,januar:174,januari:[83,140,146,174,332,392,446,471],japan:[264,464],japanes:[150,264,474],jar:474,jason:[471,473,476],java:[55,60,70,81,83,87,88,96,101,102,114,120,222,304,368,391,407,426,430,431,440,445,450,455,470,474,475,476],java_v:315,javascript:[60,158,161,240,260,457],jcaesar:462,jcea:[138,476,477],jdoe:64,jean:[438,476,477],jeff:[471,473],jeffrei:[101,333,476,477],jelk:83,jen:472,jenvei:477,jeopard:30,jeremi:[470,471,472,473,474,475,476,477],jerri:146,jess:476,jetbrain:88,jewett:[96,474,476],jfif:[248,259],jim:[88,96,99,311,322,445,470,474,476],jinja:106,jira:476,jis:[150,474],jisx0213:[150,474],jiwon:474,jkl:152,jkorpela:104,jloup:438,job:[63,87,93,98,101,104,106,123,140,151,197,202,221,230,293,304,311,369,394,410,450,453,470,476],joe:[105,143,364,403,410],joel:104,joelonsoftwar:104,johab:[150,474],johansson:477,john:[64,103,105,152,180,346,364,396,429,451,452,453,471,474,475,476,477],johns_account:152,johnson:[104,475,476],joi:298,join:[56,60,63,72,80,83,88,95,96,99,102,123,126,143,147,150,161,162,167,178,180,193,222,253,266,272,288,293,304,305,314,330,333,334,335,352,358,361,366,368,369,389,391,393,394,411,426,427,429,452,460,463,470,474,475,476],join_lin:63,join_thread:293,join_timeout_func:293,joinablequeu:293,joiner:150,joinfield:369,joint:438,joke:470,jone:[90,473,475],joona:472,josephin:87,josh:[475,476],josiah:476,jour:104,journal:180,jpeg:[60,248,252,347,396,457,476],jpg:[434,463,475],jpython:470,js_output:161,json:[60,98,99,158,252,266,295,456,477],jsondecod:[260,477],jsonencod:[99,260],jsp:106,jtc1:380,juan:[230,477],judg:107,judici:[87,476],juggl:127,jukka:104,jul:[96,472],juli:[96,180,438,446,455,472,473,477],julian:392,jumbl:81,jump:[81,99,157,182,186,244,309,332,403,440,452,473,475],jump_absolut:182,jump_forward:182,jump_if_false_or_pop:182,jump_if_true_or_pop:182,jumpahead:332,jun:[96,221,392,472],june:[96,104,424],juni:446,junit:[407,471],junk:[155,180,293],jussi:96,just:[0,1,5,6,24,29,30,40,43,49,50,55,56,58,60,63,64,67,70,72,73,75,76,77,79,80,81,82,83,87,88,89,90,91,92,93,94,96,98,99,100,101,102,103,104,105,106,107,123,125,127,138,140,143,148,149,150,151,152,158,161,162,168,169,171,174,178,180,186,192,193,197,206,210,221,222,230,234,238,246,258,264,265,266,267,273,290,293,300,303,304,309,311,322,327,328,333,334,339,345,350,351,355,360,361,364,365,368,369,374,379,380,381,386,388,389,391,394,396,401,403,407,409,418,423,425,426,431,435,436,438,439,440,442,445,446,447,450,451,452,453,454,457,460,461,463,468,469,470,471,472,473,474,475,476,477],justifi:[215,368,369,396,401,457,476],jvm:[81,476],jwzthread:[436,473],jython:[70,81,87,90,95,125,315,388,423,445,460,465,471,474,476],kadidd:410,kahan:147,kaiser:475,kaliszewski:477,kall:474,kamp:470,kanji:150,kappa:332,karaok:461,karatsuba:473,katz:[435,436],kazakh:150,kbhit:[89,291],kde:[84,419],kdedir:419,keebler:161,keep:[28,29,30,56,60,72,79,81,82,87,88,90,91,95,99,100,101,107,123,125,127,137,143,150,152,162,163,168,169,171,178,182,186,200,219,222,225,236,247,253,265,273,287,303,304,311,318,321,333,346,361,364,368,396,403,410,418,423,426,431,439,440,447,451,452,455,458,461,462,463,471,473,474,475,476,477],keep_blank_valu:[143,411],keep_run:132,keepend:[56,150,368],kei:[4,19,28,30,35,43,47,48,55,60,63,71,72,77,87,89,90,93,94,96,98,99,100,109,113,115,116,121,125,132,137,138,143,148,149,152,158,161,166,167,169,174,175,176,178,182,186,188,191,192,200,201,205,206,219,221,222,223,225,226,230,236,238,243,244,246,252,257,258,260,264,265,266,273,274,279,280,282,288,291,298,302,304,306,309,311,316,318,321,322,326,333,334,339,346,350,354,358,362,364,368,369,371,380,384,388,391,396,401,403,407,409,410,411,413,418,423,429,432,433,434,440,442,447,451,452,453,456,457,459,463,465,469,470,471,472,473,474,475,476,477],keith:472,kelli:473,kelsei:470,ken:[104,396],kent:[104,365,388,407,471,475,476],kept:[87,99,162,168,178,182,194,217,222,225,226,249,256,258,267,273,330,361,365,368,413,418,437,454,463,470,472,477],kern:267,kernel32:[89,168],kernel:[63,88,93,345,353,360,377,381,470,475],kevent:[60,362],kevin:[473,474,476,477],key_:169,key_a1:169,key_a3:169,key_all_access:113,key_b2:169,key_backspac:169,key_beg:169,key_break:169,key_btab:169,key_c1:169,key_c3:169,key_cancel:169,key_catab:169,key_clear:169,key_clos:169,key_command:169,key_copi:169,key_creat:169,key_create_link:113,key_create_sub_kei:113,key_ctab:169,key_datum:442,key_datum_list:442,key_dc:169,key_dl:169,key_down:169,key_eic:169,key_end:169,key_ent:169,key_enumerate_sub_kei:113,key_eo:169,key_eol:169,key_execut:113,key_exit:169,key_f0:169,key_f1:169,key_f2:169,key_f3:169,key_f4:169,key_fil:[241,409],key_find:169,key_fn:169,key_func:96,key_help:169,key_hom:[93,169],key_ic:169,key_il:169,key_left:[93,169],key_length:438,key_ll:169,key_mark:169,key_max:169,key_messag:169,key_min:169,key_mous:169,key_mov:169,key_next:169,key_notifi:113,key_npag:169,key_open:169,key_opt:169,key_ppag:[93,169],key_previ:169,key_print:169,key_query_valu:113,key_read:113,key_redo:169,key_refer:169,key_refresh:169,key_replac:169,key_res:169,key_reset:169,key_restart:169,key_resum:169,key_right:169,key_sav:169,key_sbeg:169,key_scancel:169,key_scommand:169,key_scopi:169,key_screat:169,key_sdc:169,key_sdl:169,key_select:169,key_send:169,key_seol:169,key_separ:260,key_set_valu:113,key_sexit:169,key_sf:169,key_sfind:169,key_shelp:169,key_shom:169,key_sic:169,key_sleft:169,key_smessag:169,key_smov:169,key_snext:169,key_sopt:169,key_sprevi:169,key_sprint:169,key_sr:169,key_sredo:169,key_sreplac:169,key_sreset:169,key_sright:169,key_srsum:169,key_ssav:169,key_ssuspend:169,key_stab:169,key_sundo:169,key_suspend:169,key_undo:169,key_up:169,key_val:474,key_wow64_32kei:113,key_wow64_64kei:113,key_writ:113,keybind:[93,169,244,334],keyboard:[84,89,93,169,219,244,374,396,401,407,452,476],keyboardinterrupt:[20,95,98,99,149,191,206,293,353,390,407,449,454,461,475,476,477],keycap:169,keycod:[291,396],keydict:116,keyerror:[13,20,30,48,81,138,152,162,175,176,188,200,206,226,233,236,249,251,258,273,324,339,345,346,350,363,368,369,381,384,406,435,440,461,463,473,474,477],keyfil:[221,246,267,290,318,358,365,470],keyfunc:258,keylist:[473,474],keynam:169,keyout:365,keypad:[93,169],keypath:290,keypress:[60,93,291,476],keyref:[418,475],keystrok:[101,148,169,353,470,477],keysubst:116,keysview:152,keysym:396,keysym_num:396,keywd:77,keywdarg:77,keywdarg_method:77,keywdarg_parrot:77,keyword:[4,10,51,55,58,60,63,70,72,75,78,79,81,87,90,91,96,98,99,103,116,117,123,125,128,132,143,150,152,157,162,167,168,169,174,180,182,186,197,200,201,210,215,222,223,238,244,252,253,256,258,260,262,265,266,270,273,284,287,293,299,302,303,308,311,321,327,340,351,352,356,368,369,382,384,386,388,389,390,391,396,403,407,409,416,423,427,429,439,440,442,443,444,447,453,454,456,457,463,470,472,473,474,475,476,477],keyword_argu:442,keyword_item:442,kfm:419,kfmclient:419,kib:[37,391],kid:[88,403],kiendl:475,kill:[52,60,87,102,128,169,244,293,304,353,374,380,390,423,458,476,477],killchar:169,killpg:[304,473],kind:[1,6,15,30,55,77,79,81,82,90,100,102,104,107,119,123,138,143,157,168,174,186,192,206,212,222,249,253,255,256,278,290,292,293,300,304,313,364,365,368,371,380,391,396,407,416,425,429,430,431,438,439,440,442,451,452,454,455,472,473],kindahl:477,kindli:[474,476],king:[333,470],kite:403,klass:[10,94,265],klein:364,klem:410,klist:350,klose:477,knee:[249,251],knew:[105,300],knight:[96,321,438,453,457,472,473],knot:231,know:[1,6,22,26,28,30,55,59,63,66,71,72,77,79,80,81,83,88,89,91,95,96,98,99,100,101,102,105,106,107,113,115,118,123,127,143,147,162,167,168,170,180,186,193,194,197,222,225,230,236,243,264,266,273,274,292,293,303,304,311,350,357,360,364,365,368,380,396,401,403,409,410,412,416,423,432,434,445,447,450,451,452,454,458,460,461,462,469,470,471,472,475,476,477],knowledg:[78,93,128,174,264,265,300,315,350,413,451,462,476],known:[3,4,28,30,50,53,55,70,72,75,79,83,87,88,89,91,96,102,104,105,106,107,123,143,147,150,158,168,174,194,200,203,206,222,230,235,236,247,256,264,266,269,277,281,283,302,304,308,311,332,337,338,345,346,348,349,364,365,368,369,370,375,376,380,392,394,396,401,403,406,410,416,425,426,431,432,435,437,438,442,445,447,451,452,454,459,460,461,469,473,475,477],known_host:352,known_path:356,knownfil:281,knuth:[152,178],koch:403,kodo:101,koi8:104,koi8_r:150,koi8_u:150,kolam:403,komodo:88,komodoid:88,konqueror:[419,475],korai:474,korean:[150,474],korn:458,korpela:104,kosata:477,kq_ev_add:345,kq_ev_clear:345,kq_ev_delet:345,kq_ev_dis:345,kq_ev_en:345,kq_ev_eof:345,kq_ev_error:345,kq_ev_flag1:345,kq_ev_oneshot:345,kq_ev_sysflag:345,kq_filter_aio:345,kq_filter_netdev:345,kq_filter_proc:345,kq_filter_read:345,kq_filter_sign:345,kq_filter_tim:345,kq_filter_vnod:345,kq_filter_writ:345,kq_note_attrib:345,kq_note_child:345,kq_note_delet:345,kq_note_exec:345,kq_note_exit:345,kq_note_extend:345,kq_note_fork:345,kq_note_link:345,kq_note_linkdown:345,kq_note_linkinv:345,kq_note_linkup:345,kq_note_lowat:345,kq_note_pctrlmask:345,kq_note_pdatamask:345,kq_note_renam:345,kq_note_revok:345,kq_note_track:345,kq_note_trackerr:345,kq_note_writ:345,kqueue:[60,362,476],krah:477,krekel:475,krell:96,kreutz:476,kristol:162,krugler:104,ks_c:150,ks_x:150,ksc5601:150,ksx1001:150,kuba:477,kubica:106,kuchl:[93,96,101,169,470,471,472,473,474,475,476,477],kumaran:477,kung:369,kunstlev:475,kurt:475,kwarg1:[96,475],kwarg2:[96,475],kwarg:[88,90,98,99,109,123,125,128,152,167,222,260,265,284,293,302,303,322,368,369,384,388,390,391,407,452,476],kwcount:58,kwd:[54,55,79,134,152,160,167,223,253,258,293,399,407,475],kwdict:77,kwlist:[77,79,180,261],kws:[58,369],kyle:477,l10:150,l10n:[230,470],l2v0yy9wyxnzd2q:104,laan:476,lab:[83,438,451,470,472,473],laban:477,label:[37,60,81,83,84,96,150,182,191,212,215,219,238,273,290,303,351,369,394,395,396,440,460,472,473],labelentri:394,labelfram:[394,401],laboratori:438,lack:[40,81,83,87,88,93,167,206,208,222,293,304,305,339,390,440,441,442,451,469,470,471,476],lag:[84,322],lahei:474,lai:[72,207,457],laid:[62,63,108],laird:87,lalo:473,lamb:452,lambach:476,lambd:332,lambda:[60,90,94,103,125,134,137,152,157,180,222,253,258,293,332,355,364,368,404,407,439,440,443,444,446,453,456,470,471,472,474,475,476],lambda_expr:442,lambdatyp:404,lambdef:443,lambert:473,lameiro:96,lan:102,lanc:[414,438],lancelot:[429,453],land:[169,300],landmark:469,landscap:[403,476],lang1:230,lang2:230,lang3:230,lang:[83,87,88,98,104,230,264,464,471,472,473,475],languag:[0,1,15,30,60,63,70,72,76,77,78,84,86,87,90,91,92,96,100,101,103,104,105,106,107,111,117,125,150,152,158,168,172,192,198,200,203,209,222,239,240,242,252,255,264,270,275,290,308,311,348,364,368,372,378,380,389,395,397,407,418,426,427,434,438,440,442,445,446,447,448,450,451,452,453,455,456,457,460,461,464,468,471,472,478],language1:230,language_map:63,language_ord:63,lannert:[470,473],lantern:169,laptop:473,lar:[470,473,474,475,476,477],larg:[4,6,16,29,30,48,51,52,55,60,62,63,64,76,81,83,87,88,90,93,96,100,101,102,103,104,105,106,127,168,169,174,178,180,186,205,206,220,222,231,238,246,256,260,277,282,293,303,306,332,338,339,353,368,369,371,374,384,396,408,413,418,425,426,427,440,450,451,452,457,460,462,463,470,471,472,473,474,475,476,477],largefil:388,larger:[4,29,30,34,37,55,70,79,88,93,94,103,104,118,127,139,168,169,174,178,207,222,235,236,256,287,311,319,332,333,336,355,364,368,380,391,393,435,437,440,442,446,450,452,453,454,455,462,464,470,472,473,475,477],largest:[29,88,96,174,178,218,221,222,236,277,336,368,380,437,446,470,471,472,473,474,475,476],largestr:87,largezipfil:435,larri:477,last:[6,19,20,28,30,52,55,63,64,67,77,79,81,87,88,91,93,95,96,98,99,101,102,104,113,114,119,123,124,127,128,134,135,138,140,142,143,148,150,152,158,168,169,174,175,178,180,182,186,188,193,200,203,206,207,210,212,215,216,218,221,222,225,236,244,246,249,253,260,264,265,267,273,279,282,292,293,299,302,303,304,305,309,311,313,322,328,333,334,339,340,341,345,350,351,352,354,359,360,363,364,365,366,368,369,374,380,384,386,392,396,398,400,401,403,406,407,409,411,415,418,422,426,429,431,435,437,439,440,442,443,446,447,451,452,453,454,457,458,460,461,463,465,470,472,473,474,475,476,477],last_accept:293,last_is_sticki:53,last_login:476,last_nam:[167,333],last_traceback:[20,81,309,380,400,440],last_typ:[20,380,400],last_valu:[20,380,400],lastaccess:476,lastchild:426,lastcmd:148,lasterror:[168,476],lastgroup:333,lasti:182,lastindex:333,lastli:442,lastnam:[223,364],lastpart:282,lastrowid:364,lastupdatedordereddict:152,late:[63,93,100,180,185,391,470],latenc:[256,477],later:[20,28,30,55,63,72,73,76,77,79,82,87,88,92,93,95,96,98,99,101,102,103,104,105,106,107,123,128,129,130,143,145,148,150,152,162,168,169,182,186,198,200,219,221,230,256,258,264,288,293,303,311,315,333,343,351,360,364,365,368,376,380,386,407,410,416,417,437,439,440,442,447,450,451,453,460,461,470,471,472,473,476,477],latest:[60,83,87,108,143,174,204,244,466,467,469,477],latex:[101,396,476],latin10:150,latin1:[104,150,283,328,364,475],latin2:150,latin3:150,latin4:150,latin5:150,latin6:150,latin7:150,latin8:150,latin9:150,latin:[15,60,104,125,150,194,222,239,260,283,384,406,435,442,446,447,460,472,473,476],latin_1:[150,194],latitud:369,latter:[37,55,64,77,90,100,102,105,106,115,121,134,142,158,163,174,191,197,203,207,222,236,253,256,259,266,281,292,303,304,314,322,339,360,368,373,394,396,401,403,407,416,439,440,441,442,447,448,451,453,460,462,473],lauder:[472,473],laugh:425,launch:[60,63,90,178,191,229,243,268,271,293,304,374,415,419,467,469,470],launcher:[108,477],launchpad:476,launchservic:[60,268],launchurl:243,law:[129,359,376,377,392,438,475],lawrenc:438,lawson:474,lawyer:95,lax:475,layer:[6,7,10,27,33,50,53,54,60,79,87,102,106,142,318,322,350,358,365,395,434,469,470,473,476],layout:[55,60,67,72,79,98,107,150,265,365,373,380,395,396,415,456,457,476],layoutspec:401,lazi:[81,96,107,113,365,380,385,475],lazili:[162,208,258,407,442],lbrace:397,lbyl:90,lc_:264,lc_all:[169,230,264,463],lc_collat:264,lc_ctype:[104,264],lc_letter:445,lc_messag:[230,264],lc_monetari:264,lc_numer:264,lc_time:264,lchflag:[304,476],lchmod:[304,476],lchown:[304,473],lcol:212,lcy1134:365,lcy:365,ldconfig:168,ldcxxshare:477,ldexp:277,ldflag:[76,473],ldgettext:230,ldir:63,ldj:246,ldl:76,ldngettext:230,leach:429,lead:[16,29,34,56,63,77,79,81,88,89,98,100,101,106,137,143,144,148,150,158,162,174,178,180,186,200,218,222,228,232,244,253,256,265,267,271,273,281,302,304,305,309,322,328,339,360,365,368,369,373,377,380,382,385,388,389,391,392,393,400,407,409,411,416,426,435,439,440,441,442,446,447,448,451,452,457,460,461,465,470,473,474,475,476],leader:351,leaf:[304,308,397],leak:[28,33,77,225,304,380,442,470,471,477],leander:477,leandro:96,leap:[90,98,101,140,174,392],leapdai:140,learn:[1,60,75,77,79,80,81,82,83,86,87,91,94,95,96,101,104,106,143,168,178,186,216,222,244,255,277,337,346,351,364,403,427,450,451,453,454,456,464,472,473,475,476,477],least:[4,22,30,36,43,55,58,63,67,70,76,77,81,87,88,95,99,100,101,102,104,107,108,111,123,126,127,131,134,146,150,152,168,169,174,178,180,186,193,204,207,215,217,222,234,235,246,253,255,256,265,275,276,277,303,304,319,322,345,358,360,365,368,369,373,380,385,388,390,391,393,398,399,409,422,425,435,437,440,442,445,450,451,452,453,454,459,473,476,477],leav:[4,20,26,30,50,58,62,63,77,79,81,83,92,93,96,99,104,113,123,128,152,162,169,178,182,186,200,219,222,224,236,256,258,267,273,293,303,304,311,331,332,364,365,368,396,403,439,440,445,447,451,453,454,455,463,470,472,473,474,475,477],leaveok:[93,169],led:[104,106,158,160,471],lee:[105,474,475,477],leffler:360,left:[4,14,28,41,55,56,63,76,77,90,93,96,101,102,104,107,125,129,133,137,139,147,148,149,152,157,168,169,174,178,180,182,186,200,205,208,215,219,222,228,244,247,256,258,259,265,266,273,290,293,302,303,304,305,306,309,328,333,338,339,342,351,360,365,368,369,374,389,391,394,396,401,403,406,409,427,438,440,442,446,447,451,452,453,454,457,458,459,460,463,470,471,472,473,474,476,477],left_list:208,left_onli:208,left_volum:306,leftarrow:244,leftmost:[101,137,152,180,186,219,223,333,442,474],leftov:303,leftright:403,leftshift:[157,397],leftshiftequ:397,legaci:[42,70,75,80,131,138,141,184,221,308,369,380,407,464,467,477],legal:[8,80,88,104,157,215,239,244,256,308,309,339,355,368,388,392,396,401,441,442,446,452,453,463,471,472,473,475,476,477],legal_char:333,legibl:88,legitim:451,lehmann:474,leif:476,leisur:143,lekhonkhob:91,lekma:477,lemburg:[104,230,364,470,471,472,473,475],len:[6,7,19,33,35,36,43,47,48,50,53,60,79,87,88,90,99,101,102,127,129,137,143,152,168,175,180,182,186,222,230,231,236,241,251,256,258,293,302,303,304,318,320,332,334,339,346,358,364,368,373,388,404,416,423,424,426,429,440,446,451,452,453,454,460,461,462,470,473,474,475,476,477],lend:472,lenfunc:55,length:[3,4,6,7,19,20,21,22,30,33,34,42,43,47,48,49,50,51,53,55,56,60,77,79,81,87,88,90,93,96,99,102,104,105,113,123,124,126,129,131,132,135,138,140,146,150,152,168,169,178,180,182,194,197,198,200,202,207,216,222,226,231,235,237,241,246,258,260,266,267,273,277,278,283,287,293,303,304,308,320,322,328,332,333,334,345,349,352,354,358,360,365,367,368,369,373,377,384,387,389,391,392,401,407,409,410,416,423,424,426,431,434,436,437,439,440,442,446,447,452,453,459,460,463,470,472,473,474,475,476,477],length_requir:241,lengthi:[96,101,258,312,470,471,472,473,474],lengthier:[470,471],lennart:477,lenp:55,lenton:476,leo:89,lesher:477,less:[1,6,21,30,34,52,55,56,63,77,79,81,83,87,88,90,101,103,104,106,107,111,124,137,143,146,150,152,161,168,169,174,178,182,186,200,207,222,223,228,236,244,247,256,265,273,277,284,293,304,309,312,321,322,330,333,338,346,360,368,369,374,380,391,392,394,396,397,400,401,407,409,426,439,440,442,447,451,452,453,457,460,471,472,473,474,475,476],less_than_10:96,lessequ:397,lesser:[337,453],lesson:346,let:[6,20,58,60,63,64,66,71,72,73,76,77,79,81,82,83,87,88,91,93,95,96,98,99,100,101,102,103,104,105,106,107,123,127,139,160,163,168,180,193,230,236,241,249,255,260,264,265,266,303,309,310,313,333,338,350,365,384,396,401,412,429,438,449,451,452,460,470,472,473,474,475,476,477],letter:[63,67,87,89,93,101,104,131,137,150,152,169,170,178,180,186,222,228,264,303,304,305,309,313,324,333,365,368,369,386,389,401,406,407,409,435,442,446,452,453,460,463,470,472,474,475,476,477],level:[6,12,20,26,27,30,37,52,55,60,63,70,77,78,79,81,82,83,87,89,91,92,96,99,100,103,104,105,107,116,120,123,124,125,127,128,135,138,140,141,142,145,147,157,162,169,172,174,175,180,182,186,192,194,198,199,202,204,205,206,211,215,219,221,222,223,225,230,234,236,239,241,243,246,251,252,253,254,256,257,258,266,267,269,273,279,288,290,291,292,293,295,297,299,304,305,306,307,309,311,312,314,315,316,318,321,322,326,327,328,329,332,333,335,338,342,350,351,354,358,362,364,365,368,380,382,384,385,386,388,389,390,394,396,401,402,405,407,410,412,416,418,419,423,425,426,427,429,431,434,435,437,439,440,441,442,444,446,447,450,451,452,456,461,462,463,465,469,470,471,472,473,474,475,476,477],levelnam:[98,99,265,266,267,293,474,477],levelno:265,lever:189,leverag:293,levinson:476,lexer:351,lexic:[60,220,240,252,383,398,431,442,444,445],lexicalhandl:[431,474],lexicograph:[103,258,368,442,453,475],lexist:[305,474],lfactor:129,lflag:387,lfs_cflag:319,lgamma:[277,477],lgettext:[60,242],lgpl:84,lhash:438,liabil:[143,438],liabl:[293,438],lib2to3:[60,90,179],lib:[30,63,64,66,72,75,76,80,82,87,89,91,107,111,114,118,123,125,126,127,128,132,134,137,140,143,148,152,154,156,160,161,162,168,181,182,185,186,189,190,205,208,210,214,218,221,223,228,230,232,234,235,236,237,239,240,241,246,248,251,253,261,263,265,266,267,274,281,288,296,299,303,304,309,312,313,314,315,316,318,321,322,325,326,327,330,331,332,335,340,342,343,350,351,352,355,356,357,358,359,361,365,366,368,369,376,378,379,380,381,383,384,385,386,389,391,393,397,398,399,404,411,413,414,416,417,418,419,424,427,428,429,434,435,436,449,461,463,465,468,469,470,471,472,473,475,476,477],lib_pypi:91,lib_typ:63,libbz2:168,libc:[168,185,315,475],libc_ver:315,libdir:381,libe:87,libedit:334,liber:[186,396],liberror:63,libexpat:425,libffi:[60,477],libfoo:63,liblibnam:63,libm:[107,168],libnam:63,libpython25:107,libpython2:473,libpython:106,librari:[0,6,16,20,21,28,30,37,52,55,58,60,62,64,66,69,70,73,75,76,77,78,80,81,82,83,84,85,88,90,91,93,95,96,97,99,100,101,102,104,105,106,107,108,119,120,123,127,139,142,157,158,162,169,170,174,176,177,179,183,185,186,188,192,205,207,213,222,226,227,228,235,238,249,254,255,259,260,262,264,265,267,269,270,275,277,293,298,303,304,305,307,310,315,316,322,327,328,333,334,338,339,345,347,350,353,356,360,364,365,368,369,380,381,388,391,392,394,395,396,405,407,408,423,425,426,435,437,438,440,442,444,445,446,447,450,453,456,457,458,459,461,464,465,467,469,470,471,472,473,474,475,477,478],libraries_assembly_name_prefix:477,library_dir:[63,72,75],library_dir_opt:63,library_filenam:63,library_opt:63,libraryload:168,libressl:[60,257],libtclsam:84,libtix8183:394,libtk8183:394,libtksam:84,libwww:[162,474],licenc:[72,84,438],licens:[60,61,63,64,72,83,84,89,106,107,108,159,244,273,459,461,472],license:438,lie:[17,293,401,442,447,472,473],liechtenstein:429,lies:[147,174,241,440],lieu:[287,438],life:[60,64,90,158,311,395,426,435,452,470,476],lifecycl:477,lifespan:253,lifetim:[30,37,77,88,90,113,150,222,304,451,471],lifo:[152,330,407],lifoqueu:[330,476],lift:[20,105,116,182,439],ligatur:150,light:[154,168,169,311,390,476,477],lightbutton:212,lighter:407,lightli:104,lighttpd:106,lightweight:[152,208,260,364,425,470,475,476],ligocki:476,like:[0,1,3,4,5,6,9,15,16,20,24,26,28,30,31,37,40,43,48,49,51,53,55,56,60,62,63,64,67,68,71,72,73,75,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,109,113,118,121,123,124,125,126,131,132,134,135,136,138,140,142,143,145,146,148,150,151,152,155,157,158,159,160,161,162,163,164,167,168,169,174,176,178,180,182,185,186,188,191,193,197,199,200,202,206,207,210,217,219,221,222,223,224,226,228,229,230,232,233,234,235,236,237,239,241,244,245,248,252,255,256,258,260,264,265,267,269,273,274,277,278,282,287,292,293,302,303,304,305,306,307,308,309,311,312,313,315,316,317,319,322,324,326,327,328,330,331,332,333,337,338,339,345,346,349,350,351,352,353,358,360,361,363,364,365,366,368,369,370,373,374,376,377,379,380,381,383,384,385,386,387,388,391,392,394,396,400,401,403,404,407,408,409,410,413,414,416,417,423,424,425,426,427,429,431,432,433,435,439,440,442,443,445,446,447,449,450,451,452,453,454,455,457,458,459,460,461,462,463,467,469,470,471,472,473,474,475,476,477],likelihood:[88,280],likewis:[30,48,90,94,109,123,178,180,203,273,339,361,403,431,439,445,451,462],limburg:452,limit:[6,20,30,52,55,56,60,70,87,93,96,99,101,106,109,113,119,132,139,141,156,167,177,178,182,197,202,207,218,219,222,235,243,244,246,252,256,258,266,281,291,295,296,303,304,305,306,311,314,321,326,328,329,330,333,335,337,339,342,343,350,353,360,364,365,368,369,380,384,391,394,400,408,409,423,426,429,432,437,438,440,441,442,445,446,451,456,470,471,472,473,474,475,476],limit_denomin:218,lin2adpcm:129,lin2alaw:129,lin2lin:129,lin2ulaw:129,lindblad:476,lindenmay:403,line:[12,20,21,28,30,46,56,58,60,62,63,64,66,68,70,71,72,73,75,76,77,79,81,82,83,87,88,89,90,91,93,95,96,98,99,100,101,104,105,106,107,108,109,111,114,115,120,122,125,126,131,132,134,135,136,139,140,143,145,147,149,150,151,152,158,159,160,167,168,169,170,174,177,178,179,182,183,184,186,191,193,194,196,197,198,199,200,202,211,212,215,216,220,221,222,227,230,238,240,241,246,247,252,253,256,258,260,262,265,267,270,273,274,280,282,283,287,290,291,292,293,296,299,304,308,309,311,313,314,318,321,322,325,326,327,328,331,332,333,338,339,340,341,342,351,354,355,356,358,362,364,365,368,369,370,372,374,379,380,384,385,389,394,395,396,398,400,403,405,406,416,419,423,427,432,438,439,440,441,442,444,445,447,448,449,451,452,453,454,456,457,459,460,461,463,464,466,467,468,469,470,471,472,473,475,476,478],line_buff:256,line_info:308,line_list:96,line_num:[167,475],linear:[88,129,180,231,236,368,376,451,473],linearli:[129,345],linebreak:56,linecach:[60,211,252],linecount:143,lineev:238,linefe:[135,311,339,351,369,446,473],linejunk:180,lineno:[20,125,134,157,182,186,206,210,238,240,253,263,265,296,309,311,322,326,328,351,416],linesep:[256,304],lineterm:180,linetermin:167,linetim:238,lingard:477,lingl:476,link:[1,30,55,58,60,62,63,72,75,77,78,80,81,82,83,84,87,88,89,90,102,104,106,107,108,113,120,162,170,174,185,193,205,240,258,264,265,269,304,305,307,315,345,349,352,365,366,383,384,394,396,401,405,418,419,423,429,430,440,450,468,470,473,474,476,477],link_execut:63,link_nam:304,link_shared_lib:63,link_shared_object:63,linkag:[60,63,78,89,315],linkcc:82,linker:[63,72,76,80,89,168],linker_ex:63,linker_so:63,linkerror:63,linkforshar:76,linkmodel:269,linknam:384,linkto:352,lint:[100,423],linter:88,linux2:[107,380],linux:[28,56,60,62,63,64,70,75,83,87,93,97,107,168,169,185,205,230,256,267,304,306,315,319,323,345,360,366,374,380,381,384,390,392,396,405,410,466,470,471,473,474,475,476],linux_distribut:315,linuxaudiodev:[306,405,470,473,476],linuxfr:365,linuxjourn:475,linuz:181,lisp:[81,88,96,472],lisp_list:88,list1:[88,407],list2:[88,407],list2str:88,list:[0,1,2,4,13,15,16,22,26,28,29,30,35,37,38,43,45,47,48,51,52,53,55,56,58,60,62,63,64,66,67,68,69,70,71,73,75,77,79,80,82,84,87,89,90,91,93,94,98,100,101,102,103,104,105,106,107,108,109,113,114,115,118,119,121,123,124,125,126,127,134,138,139,140,143,148,150,152,156,157,158,161,162,163,167,168,169,172,173,174,175,178,179,180,182,186,191,192,193,196,198,200,201,202,203,205,206,208,210,211,212,213,214,215,220,221,222,225,226,228,230,231,232,233,235,236,239,240,241,242,243,244,246,248,249,252,253,255,256,257,258,260,264,265,266,267,268,273,274,276,279,280,281,288,289,290,291,292,293,296,298,299,302,303,304,305,306,307,308,309,310,311,313,314,315,316,318,321,322,324,325,326,328,330,332,333,336,339,342,343,345,346,348,350,352,353,354,355,356,358,360,362,363,364,365,369,371,372,374,379,380,381,384,385,386,387,388,389,390,391,392,393,394,396,399,400,401,403,404,405,407,409,410,411,416,418,419,423,424,426,427,429,430,431,432,434,435,436,438,439,440,441,443,444,446,447,451,454,456,457,459,461,462,464,465,467,468,469,471,472,473,474,475,477,478],list_all_object:[96,474],list_append:[182,474],list_attribut:[471,472],list_comprehens:442,list_dialect:167,list_directori:354,list_displai:442,list_fold:273,list_for:[442,443],list_id:273,list_if:[442,443],list_it:[442,443],list_nam:273,list_of_item:311,list_of_pair:152,list_opt:309,listallfold:279,listallsubfold:279,listbasedset:152,listbox:[60,395,401],listcomp:[96,125,157,453],listcompfor:157,listcompif:157,listdir:[72,81,104,181,193,214,230,232,304,305,338,352,354,366,473,474,477],listen:[60,87,99,102,127,132,266,267,299,358,360,361,362,365,403,423,434,443,473,476,477],listfold:279,listfunc:399,listiter:404,listmak:443,listmessag:279,listmethod:[355,434],listnotebook:394,listobject:470,listoflist:258,listproxi:293,listsubfold:279,listtyp:404,listwrapp:81,liter:[50,56,58,60,81,90,100,101,109,111,125,149,150,151,174,186,212,214,222,232,246,255,260,265,266,322,333,348,351,364,368,369,374,392,393,396,398,401,407,411,419,429,431,439,440,444,445,452,460,465,470,472,473,475,477,478],literal_ev:[125,222,476],literal_text:369,littl:[26,56,60,69,70,82,87,88,89,93,96,98,101,102,104,107,113,135,146,150,162,168,169,170,178,180,186,212,222,230,239,245,266,293,303,306,311,316,321,333,353,368,373,380,393,396,405,415,451,452,454,455,463,470,471,472,476],littleendianstructur:168,littleendianunion:168,live:[30,55,59,60,62,63,67,72,77,81,87,95,99,107,108,141,143,159,202,221,225,249,252,293,300,311,329,365,418,426,440,451,459,470,471,472],livermor:438,ljust:[368,369,457,474],lk_:291,lk_lock:291,lk_nblck:291,lk_nbrlck:291,lk_rlck:291,lk_unlck:291,llc:475,lld:[50,477],llength:473,llh0l:373,llib:63,lll:475,llnl:438,lloyd:445,lls:77,llu:[50,477],llx:403,lly:403,lmdef:231,lmtp:[358,476],lname:229,lngettext:230,lnktype:384,lno:265,lnotab:[12,297],lnotab_not:380,load:[8,11,13,26,28,30,36,39,51,52,60,63,72,76,77,78,80,87,88,89,90,98,99,102,105,106,113,120,125,142,143,148,158,161,162,179,182,185,186,221,222,238,244,249,251,252,258,260,265,266,276,281,288,304,309,311,314,322,325,328,332,334,338,347,350,364,365,368,380,394,403,405,426,429,434,436,439,440,447,457,461,463,465,468,470,472,473,475,476,477],load_attr:182,load_brows:212,load_cert_chain:[241,365],load_closur:182,load_compil:249,load_const:182,load_default_cert:365,load_deref:182,load_dh_param:365,load_dynam:249,load_express:308,load_extens:[364,477],load_fast:182,load_glob:[182,311],load_loc:182,load_modul:[90,249,251,436,447,473],load_nam:182,load_sourc:249,load_suit:308,load_tail:251,load_test:[60,179,186],load_verify_loc:[365,410],loadabl:[28,55,70,77,249,321,364],loadavg:473,loader:[90,168,186,314,338,342,380,407,447,473],loaderror:162,loadkei:113,loadlibrari:168,loadlibraryex:89,loadtestsfrom:407,loadtestsfrommodul:[388,407],loadtestsfromnam:[407,477],loadtestsfromtestcas:407,loadtk:396,lobbi:68,loc:[82,264],local0:267,local1:267,local2:267,local3:267,local4:267,local5:267,local6:267,local7:267,local:[4,9,16,26,28,30,43,46,58,60,62,63,71,72,75,77,81,82,87,90,92,95,96,98,99,101,103,104,107,108,113,125,127,134,140,143,144,145,149,157,168,169,174,180,182,183,186,193,203,206,219,222,223,238,242,244,246,249,251,252,253,256,258,265,267,274,287,293,299,305,309,311,322,327,328,333,334,338,339,354,356,357,358,360,365,368,369,379,380,381,384,391,392,399,409,410,425,429,430,431,432,434,439,440,441,442,447,448,449,452,456,457,458,459,460,461,462,463,465,467,468,470,471,472,473,475,476,477,478],local_clear:55,local_hostnam:358,local_travers:55,local_var:63,localaddr:357,localcontext:[178,368,475,476],localeconv:[264,463],localedir:230,localehtmlcalendar:140,localenam:264,localetextcalendar:140,localhost:[87,99,102,105,127,193,241,266,267,293,318,327,355,358,361,385,410,434,462],localitynam:365,localnam:[426,431,432,447],localobject:55,localtim:[90,98,174,203,246,265,392,471,472],localtimezon:174,locat:[4,6,28,30,42,51,60,63,64,71,72,76,80,81,87,88,89,90,93,98,101,105,109,125,129,137,142,150,158,162,168,169,174,176,186,191,204,222,225,244,252,264,266,267,269,270,275,281,289,293,304,305,309,311,312,314,325,326,327,328,333,339,352,365,381,386,392,394,396,403,407,409,410,411,416,423,425,426,429,430,431,438,439,440,447,449,459,461,464,465,467,468,469,470,472,473,474,475,476,477],lock:[4,20,26,27,55,60,77,90,99,102,139,142,158,168,175,205,207,226,241,249,252,256,258,265,267,268,273,291,293,294,304,318,330,332,336,342,350,353,361,362,364,366,390,408,418,440,463,470,472,474,475,476,477],lock_ex:207,lock_held:249,lock_nb:207,lock_sh:207,lock_un:207,lockablefil:472,lockdata:207,lockf:[207,273,320,472,476],lockstep:470,locktyp:390,loewi:[75,476],log01:266,log02:266,log03:266,log04:266,log05:266,log06:266,log07:266,log10:[147,178,277,476],log1p:[277,476],log:[1,60,69,83,90,94,95,96,97,120,126,132,137,138,143,145,147,160,177,186,187,221,230,236,252,256,269,277,299,304,318,332,352,355,358,362,368,380,382,416,423,440,456,462,469,470,471,472,474,475,476,478],log_:267,log_alert:[267,382],log_auth:[267,382],log_authpriv:267,log_con:382,log_crit:[267,382],log_cron:[267,382],log_daemon:[267,382],log_date_time_str:132,log_debug:[267,382],log_emerg:[267,382],log_err:[267,382],log_error:132,log_except:423,log_filenam:99,log_ftp:267,log_if_error:99,log_info:[267,382],log_kern:[267,382],log_local0:[267,382],log_local1:267,log_local2:267,log_local3:267,log_local4:267,log_local5:267,log_local6:267,log_local7:[267,382],log_lpr:[267,382],log_mail:[267,382],log_mask:382,log_messag:[132,293],log_ndelai:382,log_new:[267,382],log_notic:[267,382],log_nowait:382,log_perror:382,log_pid:382,log_request:132,log_syslog:[267,382],log_to_stderr:293,log_upto:382,log_us:[266,267,382],log_uucp:[267,382],log_warn:[267,382],loganberri:453,logarithm:[60,178,236,301,306,332,368,437,473,476],logb:178,logc:117,logconfig:266,logctx:99,logdir:[143,145],logfil:[99,143,238],logger1:99,logger2:99,logger:[60,99,120,266,267,293,352,382,473,477],logger_log01:266,logger_pars:266,logger_root:[98,266],logger_simpleexampl:98,loggeradapt:[60,120,477],logging_rotatingfile_exampl:99,loggingcontext:99,logic:[31,60,63,72,81,87,96,102,106,117,142,169,186,215,219,243,267,273,290,301,302,314,333,369,382,398,447,463,470,473,474,476,477],logical_and:178,logical_invert:178,logical_or:178,logical_xor:178,login:[71,165,221,229,246,296,304,324,358,363,385,410],login_cram_md5:246,loglevel:98,lognam:[99,229,304],lognorm:332,lognormvari:332,logo:[1,64,83,240,403,438],logopt:382,logout:246,logprocess:98,logrecord:[60,98,99,120,267,473],logrecordsocketreceiv:99,logrecordstreamhandl:99,logrequest:[187,355],logrot:267,logtest7:99,logthread:98,logtyp:267,lone:[311,322,442],long_descript:[63,64,71,72,75],long_info:[380,461,477],long_max:[29,34],long_min:[29,34],long_opt:[63,228],long_slic:442,longer:[3,4,6,20,26,30,55,59,63,72,75,77,79,81,86,88,92,93,96,98,100,105,106,111,118,123,129,138,142,162,168,169,180,186,192,197,210,222,223,244,253,258,259,263,266,273,276,283,292,293,303,304,308,322,332,333,343,360,364,365,368,373,380,384,386,389,391,392,401,403,407,418,426,427,435,437,440,442,452,454,458,461,463,467,469,470,471,472,473,474,475,476,477],longest:[180,197,236,244,258,305,446,472,475],longest_match_length:334,longinteg:442,longitud:369,longlink:384,longmessag:[105,132,407,477],longnam:[169,384],longstr:446,longstringchar:446,longstringitem:446,longtyp:[34,404],longval:470,look:[0,6,13,16,24,28,30,31,43,50,55,56,60,63,67,70,72,73,75,76,77,79,80,81,83,84,87,88,89,90,91,93,94,95,96,98,99,100,101,102,104,105,106,107,109,114,115,116,123,125,129,132,137,138,143,150,152,157,158,162,168,169,172,174,178,180,186,200,206,217,219,222,223,230,234,244,245,249,255,263,266,273,292,303,304,305,306,307,311,314,315,320,321,322,327,333,342,348,352,361,364,365,368,369,374,377,380,381,388,392,393,395,400,401,406,407,409,412,423,426,429,436,440,441,442,446,447,452,454,456,457,458,459,460,461,462,468,469,470,471,472,473,474,475,476,477],lookahead:[60,63,333,474],lookalik:473,lookbehind:333,lookup:[54,56,57,60,79,80,81,88,90,94,104,125,132,137,150,152,194,206,219,222,230,258,267,298,302,315,368,369,379,380,396,401,406,463,470,472,474,475,476],lookup_error:[150,473],lookuperror:[13,20,56,150,206,222,380,461],loop:[30,31,58,60,77,81,83,90,93,95,96,98,99,101,102,106,121,126,127,149,151,163,168,169,175,178,182,200,210,212,219,222,226,252,268,276,284,293,301,309,317,322,352,355,357,361,365,368,369,380,393,400,403,429,439,440,441,442,446,447,451,456,457,460,463,465,470,472,473,474,475,476,477],loopback:244,loophol:161,loos:[162,277,391],loper:474,lord:101,lorder:138,lorenz:476,lose:[30,37,95,101,162,174,178,206,240,267,273,333,348,470,477],loser:236,loss:[30,87,129,150,162,178,256,273,277,410,438,442,472,474,476],lossless:398,losslessli:178,lost:[77,91,98,104,152,160,169,174,178,181,223,244,265,267,276,293,322,352,358,361,364,439,461,470,472],lot:[50,63,66,77,79,80,81,82,83,87,88,91,98,101,102,104,105,106,107,141,143,168,186,226,234,244,265,293,303,316,317,322,344,350,354,361,374,380,425,450,451,460,461,464,470,471,472,473,474,476,477],loui:469,louko:475,loup:438,love:[77,81,99,161,167,452],lovett:477,low:[12,30,33,53,55,60,63,70,79,83,87,98,101,102,104,119,124,125,127,135,138,140,141,151,152,157,169,170,182,206,221,243,245,252,256,257,259,269,290,297,304,307,322,332,333,345,350,358,380,382,390,396,402,405,416,418,437,472,473,475,476,477],lower:[13,28,56,63,76,88,90,96,99,100,101,103,116,125,128,134,135,150,152,157,158,169,170,172,175,178,194,198,200,211,215,222,223,236,239,240,246,247,258,259,264,273,280,293,318,322,333,336,339,343,348,354,360,364,365,368,369,378,391,392,393,394,403,409,411,440,442,446,447,453,460,471,473,474,475,476,477],lower_bound:442,lower_case_with_underscor:452,lowercas:[56,96,101,104,131,178,222,264,305,333,364,368,369,380,389,396,409,446,460],lowerright:168,lowest:[37,94,98,236,287,300,330,368,369,391,393,442,453,463,470,475],lownd:476,lp64_wp:475,lp_c_long:168,lpadesc:168,lpar:397,lpcaption:168,lpcstr:168,lpcwstr:168,lpd:438,lpmodulenam:168,lpr:267,lprect:168,lprefix:134,lproxi:293,lptdesc:168,lptext:168,lpthread:76,lpython2:76,lrectread:[245,247,259],lrectwrit:[245,247,259],lrx:169,lry:169,lsampl:129,lseek:[304,339,475],lshift:[125,302],lsize:212,lsm2005:104,lsprof:322,lsqb:397,lst:152,lstat:[304,305,338,366],lstrip:[364,368,369,473],lstrip_w:63,lstyle:212,lsub:246,ltcl83:75,ltd:[83,86,365,438],lte:125,lua:463,lucasfilm:[83,86],lucent:438,luck:426,lucki:[93,168],luckili:[77,100,407,457],lumberjack:[321,400],lumberstack:400,lumholt:396,lundh:[0,88,93,96,259,396,405,429,434,438,470,471,472,474,475,477],lutil:76,lutz:396,lvalu:[50,303],lvl:[99,265],lvlname:99,lwpcookiejar:162,lx11:77,lying:[267,457],lynn:475,lynx:[162,419,474],lzma:425,m10:392,m_expr:442,maart:446,mac:[28,60,62,63,64,77,83,84,86,104,107,108,120,168,209,211,219,222,227,244,252,287,293,304,305,307,322,345,352,356,360,364,365,366,380,381,401,409,410,415,419,438,447,450,465,466],mac_cyril:150,mac_greek:150,mac_iceland:150,mac_latin2:150,mac_roman:150,mac_turkish:150,mac_ver:315,maccentraleurop:150,maccyril:150,macedonian:150,macerror:[60,269,476],macf:476,macgreek:150,machelp:[60,268],machin:[28,29,30,56,60,70,75,77,82,87,89,90,95,98,99,102,104,124,150,162,169,170,193,205,213,221,222,230,231,253,256,257,266,267,271,274,276,293,299,304,315,322,327,355,358,360,364,365,368,373,391,393,415,425,440,445,446,455,457,459,461,467,469,470,471,472,475,476,477],machineri:[20,72,94,314,391,418,422,437,440,447,465,471,472,474,477],macho:269,maciceland:150,macintosh:[60,90,135,136,141,219,222,252,268,271,272,356,374,446,466,470,473],macintyr:[473,475],maclatin2:150,macmillan:470,maco:[60,72,87,219,252,268,304,305,334,470,471,472,473,475,476,477],macostool:[60,252,268,476],macoswindowid:219,macosx:[63,381,419,467],macosx_deployment_target:[63,304],macpath:[60,211,252,305],macpython:[60,141,219,252,268,405,466,472],macresourc:[60,476],macro:[3,4,5,6,15,17,20,24,28,30,33,37,38,39,44,45,47,48,50,51,55,56,59,60,63,66,72,77,79,89,168,216,296,380,473,474,475,476,477],macrom:467,macroman:150,macturkish:150,macvim:467,made:[6,8,9,28,30,55,58,62,63,68,72,76,79,81,83,88,89,90,92,93,95,98,100,101,106,107,108,109,110,111,123,127,158,163,168,169,174,178,182,186,192,193,206,219,221,222,223,230,237,241,245,253,256,258,265,266,267,277,278,287,290,293,304,309,311,321,322,328,334,336,338,342,349,355,356,358,360,365,367,368,369,370,380,384,386,391,396,409,410,416,418,423,426,434,438,440,442,449,451,454,458,461,465,470,471,472,473,474,475,476,477],madler:438,magenta:[93,169,463],magic:[26,88,90,91,103,157,158,168,186,202,230,249,297,311,322,367,376,390,392,418,435,460,465,470,471,473],magnifi:474,magnific:79,magnitud:[88,89,174,178,222,260,277,368,369,425,470],magnu:[472,473],mahler:410,mai:[1,4,6,8,9,13,19,20,21,24,26,28,30,33,37,43,45,47,48,49,50,51,53,55,56,58,59,63,64,66,68,70,71,72,73,75,76,77,78,79,80,81,82,83,87,88,89,90,92,93,94,95,96,98,99,100,101,102,104,105,106,107,108,109,110,111,113,114,116,118,119,123,124,125,126,127,128,129,132,134,135,136,137,138,139,143,148,149,150,151,152,157,158,161,162,163,164,167,168,169,174,175,178,180,182,184,185,186,191,193,194,196,197,198,200,202,203,204,206,207,208,210,215,216,218,219,221,222,225,226,228,229,230,231,233,234,235,236,237,238,239,240,241,243,244,246,249,251,252,253,256,258,260,263,264,265,266,267,269,273,275,276,277,278,281,282,283,287,288,290,291,292,293,296,298,299,300,302,303,304,305,306,308,309,311,313,314,315,316,317,318,319,320,321,322,325,326,328,332,333,334,335,336,337,338,339,342,343,345,348,349,350,351,352,353,355,358,360,361,364,365,366,368,369,370,371,373,374,377,378,379,380,381,383,384,385,386,388,389,390,391,392,393,394,396,397,398,399,400,401,403,404,405,406,407,409,410,411,412,414,415,416,418,419,422,423,426,427,429,430,431,432,434,435,436,437,438,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,468,470,471,472,473,474,475,476,477],mail:[1,60,62,81,96,100,101,106,108,131,193,194,195,198,200,209,243,246,252,267,273,274,280,295,304,331,357,358,365,382,407,423,462,463,464,467,470,471,472,473,474,475,476],mail_admin:99,mail_opt:358,mailaddress:243,mailbox:[60,88,197,246,252,295,318,339,464,475,477],mailcap:[60,252,295],maildir:[60,295,475,477],maildirmailbox:88,maildirmessag:[60,295],mailer:[203,339],mailfrom:357,mailhost:[266,267],mailman:[83,357,472,474],mailmanproxi:[60,254],mailserv:[318,462],mailto:[243,411,438],main:[20,28,30,58,60,67,72,76,77,79,81,82,87,88,90,91,93,95,98,99,112,123,128,143,149,169,177,180,186,192,193,196,197,199,200,201,212,219,223,228,230,231,236,240,244,245,253,256,265,266,270,273,280,293,303,304,325,336,342,343,353,355,361,364,380,384,390,391,393,394,396,401,403,407,410,413,427,431,441,453,461,462,463,464,465,469,472,473,475,477,478],main_log:87,mainfram:104,mainli:[28,63,72,98,125,253,276,286,303,316,381,423,434,440],mainloop:[84,88,102,219,396,401,403],mainprocess:293,mainstream:64,maint:468,maintain:[1,6,28,30,62,63,64,71,72,75,77,79,81,83,87,90,93,103,106,107,108,123,124,137,143,150,152,168,178,184,192,206,212,215,222,225,236,238,239,264,276,280,282,283,292,303,308,322,339,343,348,361,373,376,380,386,394,396,407,416,417,418,419,423,440,445,451,461,462,469,470,472,473,474,475,476,477],maintainer_email:[63,64,72],mainten:[60,62,108,204,461,478],mainthread:99,maintyp:[193,197,199,200],majewski:471,major:[28,70,72,80,83,90,100,102,104,105,106,107,160,162,174,192,201,303,304,307,315,318,338,380,381,411,440,456,464,470,473,475,476,477,478],major_vers:75,make:[4,8,11,13,28,30,52,55,56,60,62,63,64,69,70,72,75,76,77,79,81,83,90,91,93,94,95,96,98,99,101,102,103,104,105,106,107,108,109,111,114,123,124,125,126,127,128,129,137,142,143,148,149,150,152,156,157,158,163,167,168,169,171,174,178,180,186,192,201,203,205,210,213,215,218,222,224,230,234,236,237,239,244,247,256,258,264,265,266,267,273,277,288,290,292,293,300,302,303,304,306,308,311,321,322,326,332,338,339,342,350,351,353,357,360,361,364,365,368,372,373,374,376,380,384,386,388,389,391,393,394,396,398,399,401,403,405,407,409,410,415,416,417,418,419,423,427,432,435,438,439,440,442,443,445,446,447,450,451,452,453,456,457,458,459,460,461,462,463,465,466,467,468,469,471,472,473,474,475,476,478],make_an_item_avail:391,make_arch:[63,352,477],make_closur:182,make_connect:434,make_cooki:162,make_fil:180,make_form:212,make_funct:182,make_head:198,make_incrementor:452,make_msgid:[192,203],make_opt:303,make_pars:[430,432,470],make_serv:[423,475],make_t:180,make_tarbal:63,make_zipfil:63,makedev:[304,473],makedict:288,makedir:[87,304,352],makeel:429,makefil:[28,63,75,76,77,82,232,360,365,368,381,440,470,471,476,477],makefold:279,makelogrecord:[99,265,267],makepickl:[99,267],makerecord:265,makesocket:267,makesometh:407,makesomethingdb:407,maketran:[368,369],makeusermenu:219,mako:106,makoto:438,malaysia:429,malcolm:[333,477],malform:[150,178,196,256,273,305,369,474,476],malformedheaderdefect:196,malfunct:461,malici:[28,266,276,311,328,425,427,428,429,430,434,476],mallei:[438,473],malloc:[4,37,77,81,206,291,437,470,471,473,475],maltes:150,man3:396,man:[16,93,95,119,142,165,231,273,304,327,336,345,353,360,365,366,367,394,396,477],manag:[3,27,28,45,60,83,90,94,95,102,104,105,106,107,108,115,116,120,132,134,143,150,155,160,162,168,178,182,192,206,215,222,251,252,254,256,257,268,269,310,317,329,337,344,346,347,361,362,365,380,384,388,391,395,401,407,409,410,419,434,435,439,445,455,458,462,463,467,468,469,470,473,474,477],managed_resourc:160,mandat:[200,246,260,392],mandatori:[111,246,266,366,452,473],mandatoryreleas:111,mandelbrot:88,mandrak:[64,70,107,315],manfr:457,mangl:[88,200,227,270,335,442,446,451],mangle_from_:[197,200],manheim:396,mani:[0,6,15,16,28,30,51,55,56,58,62,63,64,68,70,73,75,76,77,79,81,82,86,87,88,89,90,92,93,95,96,98,99,101,102,103,104,105,106,107,108,113,117,118,123,125,127,139,141,147,150,152,160,161,162,167,168,169,170,174,178,180,186,192,197,205,215,216,219,221,222,225,230,235,236,239,241,244,252,255,256,258,263,265,268,277,287,293,302,303,304,305,306,307,308,310,311,315,317,318,319,321,322,328,331,332,333,339,343,345,346,350,352,358,360,361,364,365,368,369,374,377,380,384,385,388,389,391,392,393,394,395,396,399,403,405,407,408,410,413,418,419,422,423,426,437,438,440,445,450,451,453,454,455,456,457,460,461,463,464,465,467,468,469,470,471,472,473,474,475,476,477],manifest:[69,72,75,477],manipul:[6,28,30,37,39,48,60,63,77,79,88,96,107,120,134,152,167,168,169,174,178,192,194,211,215,252,268,280,286,293,295,304,308,322,342,346,351,355,356,360,366,368,372,380,394,396,401,409,423,426,429,460,462,463,465,470,473,476],mann:396,manner:[49,77,90,93,99,158,167,219,266,303,308,325,327,333,335,354,364,374,386,393,407,416,440,473,475,476],manpag:[168,377],manquant:105,mant_dig:[380,476],mantissa:[277,474,476],manual:[28,54,60,63,66,71,76,77,78,80,82,87,88,93,95,96,100,104,106,107,109,119,168,169,177,178,186,201,207,252,255,257,265,273,303,304,311,314,316,320,327,334,345,360,364,368,377,380,382,384,387,394,396,409,426,429,437,440,444,445,456,460,462,464,467,468,470,471,472,473,474,476,477],manuel:105,manufactur:[216,290,438],map01:131,map:[2,19,27,37,43,44,60,63,72,79,81,87,88,90,92,96,104,105,106,109,114,115,116,126,127,131,132,144,150,152,167,169,174,175,176,178,182,186,188,194,200,205,206,208,222,224,226,230,236,239,241,243,252,253,258,265,267,273,274,275,288,290,293,295,296,298,301,303,304,306,310,326,328,333,336,339,348,354,360,362,364,365,369,371,374,378,380,391,392,393,395,397,401,403,406,407,409,410,413,418,423,427,429,431,432,440,442,447,451,452,453,455,460,461,463,470,471,472,473,474,475,476,477],map_async:[293,476],map_priv:287,map_shar:287,map_table_b2:371,map_table_b3:371,mapcolor:212,mapfil:243,maplogrecord:267,mapnam:298,mapper:106,mappingsubclass:451,mappingview:152,mapprior:267,maptypecr:243,mar:[96,174,365,445,472,476],marangozov:[470,471,473],marc:[104,230,364,470,471,472,473,475],march:[174,392,403,438,462,470,474],marek:106,margin:215,mari:452,mariu:[104,470],mark:[20,56,79,81,84,87,90,99,100,101,103,104,106,118,123,125,127,134,143,150,169,180,186,212,230,236,239,240,244,260,267,273,307,312,315,318,328,333,345,348,364,368,374,385,396,399,405,407,426,438,442,446,458,469,470,471,472,473,474,475,476,477],marker:[41,118,150,186,239,256,292,311,397],market:[315,475],markovitch:470,markthisstringfortransl:230,markup:[60,104,209,239,240,252,328,348,426,434,476],marshal:[27,57,60,87,88,126,138,252,260,297,310,311,338,434,473,474,477],martelli:[473,476],martin:[75,104,193,230,438,470,472,473,474,475,476,477],maru:477,maruch:470,marvin:346,mask:[55,113,168,169,175,219,304,336,366,382,396,401,440,454,460,474,476],maskpri:382,masquerad:468,mass:[70,87,174,470],massiv:[474,475],master:[83,101,186,293,303,304,306,311,323,333,396,401,403,476],master_read:323,mat:[438,477],match:[4,8,19,20,28,55,56,60,72,73,77,79,88,90,91,93,96,98,102,104,105,120,126,129,134,135,138,140,143,147,148,156,157,161,162,169,174,178,180,186,199,200,208,211,213,223,228,232,240,241,242,244,246,249,252,253,266,273,274,284,292,293,296,298,299,309,311,314,322,328,334,339,340,352,353,355,360,364,365,368,369,372,373,380,385,388,392,394,396,398,401,407,409,410,411,416,419,426,427,429,431,439,440,442,446,451,452,454,456,458,461,463,465,470,471,472,474,475,476,477],match_hostnam:365,matchobj:333,matchobject:333,matejek:193,materi:[80,96,101,157,169,180,234,255,360,394,395,396,438,464,474,477],math:[60,81,88,90,95,96,107,123,147,178,186,205,216,218,222,252,293,300,301,332,338,346,368,403,438,440,442,451,453,457,462,473,474,476,477],math_1:216,mathemat:[41,60,81,90,96,101,152,178,252,302,332,368,440,442,453,456,463,474,476],mathematician:81,mathematisch:[28,61,438],mathewson:472,mathmodul:87,mathsclass:293,matric:471,matrix:[88,140,213,438,453,471],matsumoto:[332,438],matt:[396,477],matter:[63,73,81,88,91,104,106,107,186,264,303,304,348,361,364,368,380,387,401,407,416,440,451,453,455,460,461,465,470,472,474,475,476,477],matthew:193,matthia:[88,477],matur:[1,84],maupin:476,max:[4,90,95,96,102,123,129,152,161,162,174,178,191,222,223,236,365,368,380,440,451,461,475,477],max_10_exp:380,max_buffer_s:256,max_denomin:218,max_ev:345,max_exp:380,max_gain:377,max_interpolation_depth:158,max_length:437,max_mag:178,max_num_field:[143,411],max_siz:386,maxarrai:335,maxblocks:221,maxbyt:[99,266,267,477],maxbytecount:396,maxcol:215,maxconnect:391,maxcount:56,maxdepth:429,maxdequ:335,maxdict:335,maxdiff:407,maxev:345,maxfrozenset:335,maxheaderlen:[197,200],maxim:[129,180,200,368,380,388,451],maximum:[22,52,55,88,95,96,98,99,101,119,127,129,139,150,152,158,167,168,169,178,180,185,191,198,219,221,244,260,267,273,287,290,293,299,304,311,318,333,334,335,336,339,360,363,365,367,368,369,380,384,389,401,403,407,410,411,423,429,440,446,450,470,472,473,475,476,477],maxint:[4,109,258,338,368,380,442,461],maxkeypag:138,maxlen:[152,258,283,476,477],maxlength:293,maxlevel:[156,321,335],maxlinelen:198,maxlist:335,maxlong:335,maxoth:335,maxpp:129,maxreplac:369,maxset:335,maxsiz:[109,293,315,330,380,396,440,442,461],maxsplit:[56,101,333,368,369],maxstr:335,maxtasksperchild:[293,477],maxtri:409,maxtupl:335,maxunicod:[82,380,440,461],maxval:191,maxyear:174,mayb:[55,77,96,102,273,360,407,416,445,450],maze:93,mazin:474,mb_iconasterisk:422,mb_iconexclam:422,mb_iconhand:422,mb_iconquest:422,mb_ok:422,mbc:[15,60,88,104,150,168,380,472,473],mbox:[60,295,339,475],mboxmailbox:88,mboxmessag:[60,295],mboxo:273,mbtn:401,mcafe:89,mcfluff:333,mcguir:477,mcintyr:[475,476],mclai:472,mcmillan:[88,102,473],mcnamara:[473,475],mcs:440,md5:[60,166,235,237,246,252,338,349,364,365,415,475,476,477],md5sum:364,mdt:174,meador:477,mean:[4,6,16,20,26,28,30,45,50,51,52,54,55,56,58,59,60,62,63,64,72,73,77,79,81,87,89,90,91,94,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,114,118,121,123,127,129,134,139,141,142,143,147,148,150,152,158,160,161,162,167,168,169,170,174,175,176,178,180,186,187,191,197,198,201,202,203,206,207,208,210,212,214,215,216,221,222,226,228,233,235,236,241,244,255,256,258,259,260,264,265,266,267,271,273,276,280,281,282,287,290,293,299,300,303,304,305,308,309,311,313,315,320,322,324,328,330,332,333,335,339,343,345,348,350,351,352,353,355,356,358,360,361,363,364,365,366,368,369,373,374,377,380,384,386,387,390,391,392,393,396,400,401,403,404,407,409,410,411,414,415,416,417,418,423,426,429,434,436,437,438,439,440,441,442,445,446,447,451,452,454,455,459,460,461,462,465,468,470,471,472,473,474,475,476,477],meaning:[55,126,186,195,238,266,273,322,328,333,338,365,380,410,415,440,445,447],meaningless:[28,104,304,440,471,472],meant:[28,30,43,70,81,98,100,104,106,125,129,150,189,190,206,236,240,322,360,364,388,396,410,435,452,457,475,476,477],meantim:28,measur:[60,93,100,127,129,147,177,178,180,238,252,304,322,336,361,380,395,396,405,452,456,457,470,473,474,475,476,477],mechan:[6,8,11,13,26,28,30,43,55,69,73,75,77,79,81,82,87,90,93,94,98,102,106,107,111,114,131,132,139,161,162,168,184,186,215,222,242,246,249,251,257,264,265,266,267,273,274,303,311,314,331,336,338,342,346,353,358,361,365,373,391,394,395,396,398,401,407,410,412,416,436,440,447,450,451,452,458,470,471,472,473,474,475,477],media:[60,105,146,268,290,438,469],mediadescr:[60,268],median:94,mediat:90,medium:[48,87,170,474,475],meerkat:472,meet:[81,96,104,128,178,180,186,311,374,407,409,463,470,474],mega:394,megabyt:[87,104,143,271],mei:446,melbourn:392,melotti:477,melt:236,member:[21,26,28,30,47,51,55,60,73,79,81,90,106,109,144,158,161,168,169,174,233,246,258,260,304,305,311,324,327,329,332,339,360,363,364,368,373,377,384,398,404,435,438,440,442,451,453,462,473,474,475,476],memberdescriptortyp:404,membership:[60,93,143,152,170,233,346,368,440,453,474],memberst_mtim:472,memcpi:92,memlevel:437,memmov:[168,476],memo:[163,311,312],memoiz:[88,471],memorandum:273,memori:[3,4,6,15,16,20,24,26,27,28,30,36,41,42,48,50,51,55,58,60,76,77,79,80,82,88,90,96,98,99,101,102,104,106,113,124,126,141,142,143,150,152,168,175,185,202,205,206,222,226,234,236,252,253,256,258,267,273,293,304,308,311,328,336,338,350,352,360,361,362,364,368,370,373,374,386,390,391,418,422,427,429,437,440,446,449,451,453,457,463,465,470,471,473,474,475,476,477],memoryerror:[20,34,48,53,206,308,410,461],memoryhandl:[60,98,99,120,266],memoryview:[15,42,60,90,109,124,222,252,256,461,478],memset:168,mental:107,mention:[30,63,72,73,77,79,80,96,100,101,106,107,168,169,186,206,207,260,265,266,273,293,303,304,351,356,361,370,388,405,438,439,440,442,445,447,454,470],mentorship:1,menu:[60,64,71,89,90,93,191,212,219,268,271,284,394,395,396,403,405,467,469,475],menubar:219,menubutton:401,menuitem:219,merc:373,merchant:438,merci:440,mercuri:[299,380],mere:[88,89,90,160,174,186,222,292,303,374,384,439],merg:[19,88,92,93,94,96,98,99,104,132,144,169,186,187,236,265,291,303,354,355,399,405,425,438,463,470,473,476,477],meridian:392,merit:403,mersenn:[60,332,473],mersennetwist:332,mertz:96,mesg_num:318,mesgnum:318,mess:[93,95,123,303,451,457,472],messag:[4,20,47,52,58,60,63,72,76,77,79,82,87,88,89,91,94,95,96,101,102,103,104,105,106,123,126,131,132,134,135,148,155,156,157,159,162,166,169,186,191,192,193,194,195,196,197,198,199,201,203,205,206,212,219,221,228,229,240,241,242,244,246,252,253,265,266,267,269,274,276,282,288,292,293,295,299,303,304,309,318,325,331,336,351,352,357,358,361,365,366,380,382,383,384,385,388,393,394,400,407,409,410,416,423,430,431,434,441,447,449,451,454,459,460,462,463,464,465,470,471,472,473,474,475,476,477],message_as_str:193,message_bodi:241,message_from_fil:[192,193,199,202,273],message_from_str:[192,202],message_num:246,message_part:246,message_set:246,messagebeep:422,messagebox:168,messageboxa:168,messageclass:132,messagedefect:196,messageerror:196,messagefil:193,messagefromfil:192,messagefromstr:192,messageparseerror:[196,273],messagerfc822:192,messi:[96,473,477],messier:[96,101,472,473,477],met:[28,79,96,98,180,315,438,463,475],meta:[69,71,75,94,109,169,170,214,230,232,303,409,410,440,447,458,472],meta_path:[314,380,447,461,473],metacharact:[60,333,374,474],metacl:440,metaclass:[90,94,109,114,168,222,253,368,440,476],metadata:[60,62,64,70,72,73,105,108,223,304,305,352,366,434,440,478],metaphor:[77,394],metatyp:[55,253],metavar:[60,120,193,303,477],meter:394,meth:[18,38,81,88,109,368,471,474],meth_class:[51,473],meth_coexist:[51,474],meth_keyword:[51,77],meth_noarg:[51,79,92,472,473],meth_o:[51,472],meth_oldarg:[4,51,472],meth_stat:[51,473],meth_vararg:[4,51,76,77,79,472],method:[3,4,5,6,13,14,15,18,19,20,21,22,24,28,30,31,32,40,43,45,46,48,49,50,51,55,58,60,63,76,78,83,84,89,90,91,93,96,98,99,100,103,104,105,106,109,111,113,114,115,118,119,120,121,124,125,126,127,132,134,135,136,137,138,139,140,141,142,143,144,146,147,148,149,150,151,152,156,157,158,159,160,161,162,163,167,168,169,171,174,175,176,178,180,182,185,186,187,188,191,192,193,194,196,197,198,199,200,201,202,203,206,207,208,210,212,213,215,218,219,221,222,223,224,225,226,227,230,231,234,235,236,237,238,239,241,243,244,246,249,251,253,256,260,265,266,267,269,270,271,275,277,278,279,281,282,283,284,287,288,290,292,293,294,295,296,297,299,300,302,304,306,308,309,310,311,313,317,318,320,321,322,326,327,328,330,332,333,335,338,339,340,341,343,344,345,346,348,349,350,351,354,355,358,360,361,365,369,370,372,373,374,376,377,379,380,384,385,386,388,389,390,391,393,394,395,396,398,401,404,405,406,407,409,410,411,413,414,415,417,418,419,423,424,427,429,430,431,432,433,434,435,437,439,441,444,446,447,448,452,453,455,456,458,460,462,463,465,467,471,472,473,476,477,478],method_1:81,method_descriptor:474,method_map:88,method_nam:[81,82],method_not_allow:241,method_to_typeid:293,methodattr:109,methodcal:[90,103,302,476],methodhelp:[355,434],methodnam:[81,293,407,434,451,452],methodrespons:434,methodsignatur:[355,434],methodtyp:[38,94,404],metr:174,metric:[88,213],metzen:180,mezzo:475,mfc:[84,469],mgr1:[160,475,476],mgr2:[160,475,476],mgr:476,mh_profil:273,mh_sequenc:273,mhlib:[60,252,295,476],mhmailbox:273,mhmessag:[60,295],michael:[105,452,453,471,472,473,474,475,476,477],michel:[472,473],michlmayr:476,mick:[403,470,473,475],micro:[83,380,470,477],microphon:306,microsecond:[17,174,364,392,393,476],microsoft:[52,60,64,69,72,80,84,150,158,252,304,380,415,421,446,469,472,473,475,476],microsystem:424,mid:104,midd:117,middl:[66,81,93,117,152,196,309,335,365,389,403,432,451,463,475,477],middleton:471,middlewar:[106,423],midi:236,midnight:[267,476],midpoint:332,midst:385,midwai:437,might:[3,4,6,19,24,28,30,33,34,35,36,42,43,45,47,48,49,50,53,54,55,56,63,64,67,71,72,73,77,79,81,84,86,88,89,92,93,95,96,98,99,100,101,102,104,105,106,107,125,126,127,129,134,135,143,150,162,168,171,174,186,189,190,192,197,202,203,210,218,234,236,238,240,244,260,264,265,266,273,274,292,293,299,303,304,306,308,311,318,319,322,333,337,358,364,365,368,377,380,391,393,396,398,407,410,416,424,440,445,451,452,453,455,458,460,461,465,468,469,470,472,473,474,475,476,477],migrat:[60,87,92,308,365,407,426,447,475,476],mike:[96,396,472,474,475,476],miki:477,mil:462,mile:174,mileag:[4,358],mileston:72,miller:476,millimetr:396,million:[83,106,393,452],millisecond:[98,169,174,265,266,345,401,403,422],mime:[60,101,131,135,143,150,193,198,199,200,202,243,252,273,274,292,295,339,354,409,423,462,472,474,477],mime_decode_head:283,mime_encode_head:283,mimeappl:[192,201],mimeaudio:[193,195,201],mimebas:[192,193,201],mimecntl:192,mimeimag:[192,193,195,196,201],mimelib:[60,295,477],mimemessag:[192,201],mimemultipart:[192,193,201],mimenonmultipart:[192,196,201],mimetext:[192,193,201],mimetool:[60,132,162,192,241,252,279,292,295,339,409,410,476],mimetyp:[60,193,243,252,274,292,295,472,476],mimewrit:[60,252,295,476],mimic:[131,174,222,331,364,400,403,477],mimifi:[60,252,295,331,476],min:[4,90,95,96,101,102,142,152,174,178,222,223,236,368,380,393,451,461,475,477],min_10_exp:380,min_exp:380,min_gain:377,min_mag:178,mind:[56,72,81,88,93,100,101,123,125,137,168,178,245,293,303,455,472,474],minequ:397,mingw32:[63,107],mingw32ccompil:63,mingw:469,mini:[60,88,96,158,222,372,477],miniaefram:[60,252,270,476],miniappl:284,minidom:[60,252,275,425,426,470,471,473],minifieldstorag:143,minilanguag:351,minim:[60,63,67,73,77,79,83,87,93,106,129,143,178,180,186,219,222,238,240,246,252,275,303,311,318,322,333,342,348,353,360,363,364,388,389,410,425,448,451,452,470,475],minimal_hanoi:403,minimalist:[106,403],minimum:[22,37,79,95,99,100,108,124,129,152,168,169,178,219,315,360,368,369,380,390,391,401,413,440,451,457,472,473,476],minkeypag:138,minmax:129,minor:[28,60,72,80,81,82,83,87,93,100,105,152,201,250,304,311,315,339,380,381,431,463,471,472,473,474,475,477],minor_vers:75,minu:[63,169,178,222,225,352,368,369,373,391,397,442,457],minut:[17,102,142,174,267,304,392,435,446,469,473],minwidth:401,minyear:174,mirror:[105,138,175,221,245,266,267,308,397,406,431,464,474],mis:282,misbehav:81,misc:[0,30,83,157,401,470,473,474,475,476,477],misc_head:148,miscalcul:384,miscellan:[60,69,120,148,182,192,209,252,295,362,395,423,466],misconfigur:[89,98,244,368],mise:[104,332],misfeatur:368,misinterpret:129,mislead:[79,145,155,409,427,472],mismatch:[92,186,206,208,356,365,407,471,473,475,477],misnam:474,misnom:26,misplacedenvelopeheaderdefect:196,misrepres:438,miss:[48,60,63,81,100,101,104,152,167,168,174,178,182,196,200,207,222,253,258,265,281,288,300,303,333,352,365,369,391,392,393,394,399,401,407,411,440,442,452,454,463,470,473,474,475,476,477],missingsectionheadererror:158,mission:[83,303],mississ:368,mississippi:[152,368],misspel:[93,95],mist:473,mistak:[77,89,100,101,102,123,161,206,273,303,392,396,474,475,477],mistaken:[197,451,470],mistakenli:88,mistyp:446,misunderstood:102,misus:[28,100,472],mit:[96,438],mitch:87,mitchel:[259,476],mitig:[60,161,301],mitpress:96,mix:[28,37,89,91,100,106,107,114,126,127,174,178,199,201,202,210,212,222,228,231,293,300,306,361,365,368,370,413,440,442,443,446,453,460,461,465,472,473,475,476,477],mixabl:306,mixer:[60,286],mixerdev:306,mixin:[60,152,254,410,413],mixtur:[55,446,451],mjson:260,mk2arg:155,mkalia:271,mkarg:155,mkd:221,mkdir:[63,87,193,304,462],mkdtemp:[304,386],mkfifo:304,mknod:[304,473],mkpath:63,mkstemp:[293,386],mkstringprep:[371,473],mktemp:[87,386,409],mktime:[174,203,316,339,364,392],mktime_tz:[203,339],ml_doc:[51,79],ml_flag:[51,79],ml_meth:[51,79],ml_name:[51,79],mlsd:221,mlte:[60,268],mmap:[37,60,252,362,470,476],mmdf:[60,295],mmdfmailbox:273,mmdfmessag:[60,295],mmm:[123,246],mmmmmm:174,mms:411,mname:251,mnemon:[170,266,365,401,472],mnt:[107,181],mock:407,mod1:[66,72],mod2:[66,72],mod:[88,125,157,249,250,288,302,354,399,447,476],mod_fastcgi:106,mod_fcgid:106,mod_nam:342,mod_php:106,mod_python:60,mod_wsgi:[60,293],modal:191,mode:[4,21,30,36,46,56,60,64,68,69,77,79,83,87,88,89,93,98,99,100,101,104,106,107,109,118,121,123,125,133,138,139,141,142,143,150,157,158,168,169,170,175,176,178,180,182,185,186,188,193,210,212,221,222,226,228,234,244,249,253,256,265,267,268,269,271,273,276,277,291,299,300,303,304,306,311,313,315,317,319,320,332,333,336,337,338,340,348,351,354,358,360,364,365,366,368,373,374,376,377,379,380,384,386,401,402,403,407,414,417,419,431,435,437,440,446,447,448,455,456,457,458,460,461,466,467,471,472,473,474,475,476],model:[37,55,60,87,88,90,97,120,142,160,174,178,192,200,234,252,269,270,275,293,304,317,319,332,337,358,362,391,403,409,427,428,431,444,469,470,472,473,474,475,478],modeless:[191,219],moder:[79,83,88,96,101,221,299,303,318,333,461,472,473],modern:[62,72,77,100,104,131,138,169,170,222,235,307,324,360,365,396,422,454,457,460,467,470,474,476,477],modest:[178,462],modf:277,modif:[19,54,56,58,63,68,73,77,99,109,125,157,180,215,222,246,264,267,271,273,287,293,303,304,305,311,319,342,352,354,361,364,366,368,380,384,401,425,426,435,438,457,461,475,477],modifi:[4,19,20,28,50,55,58,60,62,63,64,68,72,73,77,79,80,81,82,83,87,89,91,92,96,98,99,103,104,105,106,109,113,114,119,121,123,125,126,129,132,144,150,157,165,167,168,169,176,177,178,182,186,187,188,195,200,216,219,222,244,264,265,273,275,276,290,293,303,304,305,308,311,314,319,320,321,322,328,333,335,341,342,345,350,354,355,358,360,361,364,368,369,377,380,384,388,391,392,394,398,401,403,407,409,410,411,414,416,423,425,426,432,433,436,438,439,440,441,445,447,451,452,453,458,461,465,467,469,470,471,473,475,476,477],modnam:[88,157,251,451,461,475],modul:[1,3,4,6,8,10,11,15,17,20,23,24,27,28,30,36,37,51,52,55,57,58,60,64,66,68,70,73,76,78,79,80,81,84,89,90,91,97,100,104,105,106,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,142,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,160,161,162,163,164,165,166,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,185,186,187,188,191,192,193,194,195,196,197,198,199,200,201,202,203,205,206,207,208,209,210,211,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,257,258,259,260,261,262,263,264,266,267,268,269,271,272,273,275,276,277,278,279,280,281,282,283,284,285,286,287,290,291,292,294,295,296,297,298,299,300,302,303,304,305,306,307,308,309,310,312,313,314,316,317,318,320,321,323,324,325,326,327,328,329,330,331,332,334,335,336,337,338,339,340,341,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,360,361,362,363,365,366,367,369,370,371,372,373,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,397,398,399,400,401,402,404,406,408,409,410,411,412,413,414,415,416,417,418,419,421,422,423,424,427,428,429,430,431,432,433,434,435,437,438,439,440,441,442,443,444,445,446,447,448,450,451,452,453,454,455,456,457,458,459,460,462,463,464,465,466,467,468,478],modula:[81,83,276,451],modular:[60,87,90,98],module1:[75,407,470],module2:[407,470],module_glob:[263,416],module_load:314,module_logg:99,module_method:79,module_nam:388,module_or_nam:314,module_rel:186,module_st:92,module_typ:253,moduledef:92,modulefind:[60,252,289],moduleinfo:253,modulenam:[8,77,82,88,227,338,461],moduletyp:[39,404,473],modulo:[99,178,206,222,302,368,401,440,442,454,463,473,477],modulu:[147,476],moin:[83,87,96,467,474],moinmoin:60,mojam:438,mollusk:230,moment:[30,81,88,100,104,174,219,239,256,293,417,451],momentarili:273,mon:[101,174,203,339,473],mon_12:264,mon_1:264,mon_decimal_point:264,mon_group:264,mon_thousands_sep:264,mondai:[140,174,264,267,392],monei:[178,374],monetari:[178,264,475],moneyfmt:178,monitor:[28,89,94,98,154,178,322,361,440,474,476],monitor_gain:377,monkei:123,mono2grei:245,mono:[118,129,306,376,417],monochrom:[245,394],monolingu:230,monomorphic_oper:300,monophon:306,monospac:389,monoton:[180,451,473],monster:389,montag:174,montanaro:[438,470,473,474,475,476],month:[17,83,140,174,264,392,435,446,470,471,473,477],month_abbr:140,month_nam:[140,446],monthcalendar:140,monthdatescalendar:140,monthdays2calendar:140,monthdayscalendar:140,monthrang:140,monti:[77,186,222,435,450,474,476],moo:186,moolenaar:446,moon:303,moor:[472,473,476],moral:311,more:[1,4,6,8,16,20,21,28,30,37,42,43,51,53,55,57,58,60,62,63,64,66,67,69,70,71,72,75,76,77,78,80,81,82,83,84,86,87,88,89,90,92,94,95,96,97,98,99,100,102,103,104,105,106,107,108,109,113,123,124,125,126,127,128,129,131,134,135,136,137,138,139,142,143,146,148,149,150,152,154,155,157,158,160,162,164,167,168,169,174,178,180,182,184,186,188,192,193,194,195,197,200,201,202,206,207,210,212,214,216,219,221,222,223,225,228,230,231,234,235,236,238,240,241,244,246,249,250,251,253,254,256,257,258,260,265,266,267,268,269,270,273,276,277,278,281,284,290,292,293,294,299,301,302,303,304,305,306,307,308,309,311,312,313,314,315,317,318,320,321,322,328,330,331,332,333,337,338,339,341,343,344,345,346,348,350,351,352,353,354,356,360,361,364,365,366,368,369,370,373,374,376,378,379,380,381,384,385,387,388,389,390,391,392,393,394,395,396,397,400,401,404,407,409,410,411,413,416,417,418,422,423,425,426,427,429,431,435,437,438,439,442,445,446,447,449,450,451,454,455,456,457,458,459,460,462,463,464,465,467,469,470,471,472,473,474,475,476,477],moreov:[30,236,273,326,403,453,477],morr:477,morrison:146,morsel:[60,254,476],mortem:[186,309,380,451],mosaic:419,mosh:[95,470,471,472,474],most:[3,4,14,20,28,30,37,51,52,55,56,60,62,63,64,68,70,72,75,76,77,79,80,81,82,83,84,86,87,88,90,91,93,94,95,96,98,99,100,101,102,103,104,105,106,107,109,110,120,121,123,127,129,134,135,137,138,139,140,141,142,143,146,147,150,152,157,158,162,167,168,169,174,178,180,182,184,185,186,191,192,195,197,198,200,202,204,206,207,212,215,216,218,219,221,222,230,231,233,234,236,239,240,244,246,252,253,254,255,256,258,260,264,265,267,268,273,274,277,287,288,292,293,300,302,303,304,305,306,308,309,311,315,318,322,324,328,330,332,333,335,344,345,346,348,350,353,358,360,361,364,365,366,368,369,374,376,378,380,384,386,388,389,390,391,392,393,394,396,400,403,406,407,408,417,418,419,422,423,424,426,427,429,430,431,432,435,437,438,440,442,443,445,446,447,451,452,453,454,455,456,457,458,460,461,462,463,465,467,468,469,470,471,472,473,474,475,476,477,478],most_common:[152,477],mostli:[20,50,55,56,58,63,81,83,84,89,100,102,106,143,186,238,244,265,277,293,322,394,410,411,429,439,447,451,470,471,472,473,475,477],motif:394,motion:[60,169,395],motiv:[72,440,442,471,473,474],motorola:[102,373],mount:[28,142,305,477],mountain:174,mous:[87,93,169,219,244,401,403,470,476],mouseinterv:169,mousemask:169,mouzo:477,move:[63,67,74,79,81,87,88,93,102,105,106,109,123,125,139,147,148,152,155,158,168,169,171,174,182,192,201,210,219,225,236,244,267,271,273,279,287,309,352,368,392,394,401,403,410,413,429,438,450,458,461,462,470,471,472,473,475,476,477],move_fil:63,moved_perman:[241,474],movement:[152,169,236,403,476],movemessag:279,movi:60,moving_averag:152,mozilla:[1,105,162,365,410,419,474],mozillacookiejar:162,mp4:476,mp_ass_subscript:55,mp_length:55,mp_subscript:55,mpeg:274,mpz:474,mro:[43,90,114,368,440,451],ms1361:150,ms932:150,ms936:150,ms949:150,ms950:150,ms_window:20,msc:89,msconfig:469,msd:178,msdn:304,msec:[169,265],msft:364,msftoblock:142,msftofram:142,msg:[63,82,87,99,102,123,125,168,193,195,197,198,199,200,202,203,221,228,237,240,241,264,265,267,273,279,292,296,358,360,385,388,407,409,410,424,430,454,473,474,475],msg_:360,msgfactori:273,msgfile:193,msgfmt:[230,477],msglen:102,msgnum:246,msgreader:192,msgtype:292,msi:[63,64,290,469,475],msicolinfo_nam:290,msicolinfo_typ:290,msicreaterecord:290,msidatabasecommit:290,msidatabaseopenview:290,msidbopen_cr:290,msidbopen_createdirect:290,msidbopen_direct:290,msidbopen_patchfil:290,msidbopen_readonli:290,msidbopen_transact:290,msie:[105,161],msierror:290,msigetsummaryinform:290,msilib:[60,252,421,475,476],msimodify_assign:290,msimodify_delet:290,msimodify_insert:290,msimodify_insert_temporari:290,msimodify_merg:290,msimodify_refresh:290,msimodify_replac:290,msimodify_seek:290,msimodify_upd:290,msimodify_valid:290,msimodify_validate_delet:290,msimodify_validate_field:290,msimodify_validate_new:290,msiopendatabas:290,msirecordclear:290,msirecordcleardata:290,msirecordgetfieldcount:290,msirecordsetinteg:290,msirecordsetstr:290,msirecordsetstream:290,msisummaryinfogetproperti:290,msisummaryinfogetpropertycount:290,msisummaryinfopersist:290,msisummaryinfosetproperti:290,msiviewclos:290,msiviewexecut:290,msiviewfetch:290,msiviewgetcolumninfo:290,msiviewmodifi:290,mskanji:150,msoft:475,mssdk:63,mst:174,msvc:[79,80,89,168,469,474],msvccompil:69,msvcrt:[60,89,168,252,421,476,477],msvcrtxx:80,mszip:290,mt19937:438,mt2002:438,mt_interact:385,mtime:[181,234,304,341,384],mtimeit:465,mua:273,much:[0,6,16,30,48,55,59,64,72,77,79,81,87,88,90,93,95,96,99,100,101,102,104,105,106,123,124,143,147,150,157,163,168,178,186,202,215,219,222,235,236,238,239,244,253,256,258,267,273,277,293,303,306,307,308,311,315,322,333,350,360,368,374,381,393,396,401,407,426,427,434,437,446,450,451,457,460,461,462,463,470,471,472,473,474,475,476,477],mul:[95,96,129,157,178,258,293,302],mul_stereo:129,mullend:[470,476],muller:477,mult:[89,125],multi:[6,28,30,55,60,87,89,90,96,101,104,111,120,127,139,140,167,178,180,186,222,244,245,257,258,265,266,282,292,293,294,315,330,332,333,336,343,346,351,352,355,368,380,384,391,393,423,435,446,452,456,459,460,461,469,470,475,477,478],multi_statu:241,multibyt:[93,169,194],multical:[60,254,355],multichannel:273,multidimension:368,multifil:[60,192,252,280,295,476],multihop:205,multilin:[101,150,244,292,333,358,407],multilingu:[60,242,252,268,446],multimedia:[60,252,274,306],multipart:[143,193,195,196,199,200,201,202,280,282,283,292],multipartconversionerror:[196,201],multipartinvariantviolationdefect:[196,202],multipl:[9,28,51,55,60,62,63,64,66,67,68,70,72,77,79,81,87,88,90,91,93,96,100,101,102,103,104,105,106,107,114,123,124,127,132,139,143,150,152,160,167,169,178,186,211,215,221,222,228,230,235,236,244,249,252,253,256,258,265,266,273,277,287,291,292,293,302,303,304,309,311,312,314,315,321,328,330,332,333,339,350,361,362,364,365,366,368,379,380,391,393,394,396,398,399,401,403,407,413,415,416,423,425,431,434,439,440,441,442,446,447,452,453,454,456,460,463,465,470,473,474,475,476,477],multiple_choic:241,multiple_result:293,multiplex:102,multipli:[41,76,79,95,129,168,174,178,196,267,322,332,368,369,434,442,455,470,473,474,476],multiplicand:[178,463],multiprocess:[60,99,138,252,362,365,391,423,477,478],multiprocessor:[87,315],multipurpos:[131,331],multiset:152,multithread:[60,138,264,293,310,385,423,473],multitud:[70,104],multiwai:96,mundan:450,mung:[60,372],munmap:37,murrai:477,musi:[341,409],must:[4,6,8,9,11,13,15,16,17,18,19,20,21,23,24,25,26,28,29,30,31,33,34,36,37,38,39,42,43,45,49,50,51,53,54,55,56,58,60,63,64,67,68,71,72,73,77,79,80,82,83,84,87,88,89,90,91,93,96,100,101,102,105,106,107,108,109,113,114,115,118,121,123,124,125,126,127,128,131,132,133,134,135,138,139,143,148,150,153,157,158,160,161,162,164,165,167,168,169,174,175,176,178,180,182,185,186,188,191,193,194,195,197,198,199,200,201,202,210,215,218,219,222,223,225,228,230,231,232,234,235,237,239,241,244,246,249,250,253,256,260,264,265,266,269,270,273,274,276,279,281,282,283,287,288,290,291,292,293,297,303,304,305,306,309,311,313,314,317,322,328,330,331,332,333,336,338,343,345,346,348,350,351,352,353,355,358,360,361,363,364,365,368,369,371,373,374,380,381,384,385,387,388,390,391,392,394,396,398,399,401,403,405,407,409,410,412,414,415,416,418,422,423,426,427,429,430,431,432,433,434,435,436,437,438,439,440,441,442,446,447,448,449,451,452,453,454,460,461,465,467,469,470,471,472,473,474,475,476,477,478],mustard:63,mutabl:[24,30,55,60,81,88,90,96,152,163,168,207,222,287,293,311,346,350,413,418,429,439,440,442,447,451,452,453,460,470,473,475,476,477],mutablemap:[81,90,152,413,476],mutablesequ:152,mutableset:152,mutablestr:413,mutant:303,mutat:[19,88,185,200,225,256,293,350,368,416,472,474],mutate_flag:207,mutex:[60,87,173,252,293,390,391],mutual:[4,60,100,107,120,173,252,266,273,303,320,396,399,419],mvaddstr:93,mvc:106,mvderwin:169,mvwaddstr:93,mvwin:169,mxbase:70,my_abstract_method:114,my_abstract_properti:114,my_app:266,my_birthdai:174,my_callback:[77,79,303],my_dealloc:79,my_decor:[223,475],my_flag:186,my_funct:[109,452],my_logg:99,my_modul:186,my_module_with_doctest:186,my_python_lib:469,my_set_callback:77,my_travers:24,myabc:114,myaddr:365,myapp:[89,98,99,158,396],myapplic:230,myarchiv:[352,463],myarg:374,mycertfil:365,myclass:[94,440,451],mycmd:374,mycmp:103,mycod:109,mycookiepolici:162,mydata:[222,391,427,463],mydequ:258,mydict:[81,88,413,474],mydir:[72,81],mydomain:365,myemptyclass:452,myerror:454,myextens:92,myextension_clear:92,myextension_method:92,myextension_travers:92,myextensionclass:470,myfavouriteshap:403,myfil:[239,304,435,451,454,463],myfilt:99,myfoo:300,myformat:392,myfunc:[88,99,182,333,355],myfunct:[77,82],mygroup:365,myhandl:[98,266],myhtmlpars:240,myintegr:300,myiter:114,mykei:266,mykeyfil:365,mylib:[98,407],mylist:[88,404],mylog:230,mylogg:[99,265],mymanag:293,mymessag:200,mymodul:[72,82,98,230,309,477],mynoddi:79,myobj:92,myobject:79,myoption:303,myorgan:365,myothercontext:178,myownfunct:168,mypackag:98,mypi:100,mypickl:[87,311],mypkg:[72,303],myprogram:123,myproject:[99,407],myreadlin:82,myrec:102,myrepr:335,myright:[246,474],myscript:[82,309,322,449,465],myself:470,mysend:102,myserv:365,myshap:403,myskippedtestcas:407,mysocket:[102,260],mysql:[106,158,477],mysqld:[158,477],mystat:365,mysteri:[20,77,83,102,143,356],mystr:202,mystruct:[168,293],mysum:364,mysuperwhammyfunct:388,mytcphandl:361,mytestcas:407,mytestcase1:388,mytestcase2:388,myth:79,myturtl:403,mytyp:[79,303,364],myudphandl:361,myvar:152,myxml:427,myzip:435,n1256:380,n3f:231,n42:303,n_cs_preced:264,n_sep_by_spac:264,n_sign_posn:264,n_st:231,n_token:397,nagl:477,naiv:[28,87,101,174,235],nak:170,name1:[60,475],name2:[60,475],name2codepoint:[239,240],name:[3,4,6,8,12,13,20,21,23,24,26,28,30,39,43,46,49,50,51,52,55,56,58,60,63,64,67,68,70,71,73,75,76,77,79,80,81,82,83,87,89,90,91,92,93,94,95,96,98,99,100,103,104,105,106,108,109,110,111,113,116,117,118,119,120,121,125,128,132,133,134,136,138,139,140,141,142,143,145,146,148,149,155,156,157,158,159,161,162,167,168,169,170,173,174,175,176,178,180,182,185,186,187,191,192,193,194,198,200,203,205,206,207,208,210,212,213,214,215,219,221,222,223,226,227,228,229,230,232,233,235,238,239,240,241,243,244,245,246,248,249,250,251,252,253,256,258,259,263,264,265,266,267,269,270,273,274,276,277,278,279,280,281,282,283,284,287,288,290,293,295,296,297,298,299,302,303,304,305,306,308,309,310,311,314,315,316,318,321,322,324,325,326,327,328,332,333,334,335,336,337,338,339,340,342,343,344,345,346,348,351,352,353,354,355,356,358,359,360,361,363,365,366,367,368,369,371,372,373,374,376,377,378,379,380,381,383,384,385,386,387,388,391,392,394,396,397,398,399,400,401,403,405,406,407,409,410,411,412,414,415,416,417,418,419,420,422,423,426,427,429,430,431,432,434,435,436,438,439,443,444,445,446,447,449,450,452,453,454,456,457,458,459,460,461,462,463,465,470,471,472,474,475,476,477,478],name_dup:92,name_last:364,name_length:92,name_or_ordin:168,namednodemap:[60,275],namedtemporaryfil:[386,476],namedtupl:[60,90,173,373,453,476,477],nameerror:[20,95,99,168,206,222,309,441,442,447,454,460,461,470,471,472,475],namei:182,namelist:435,nameprep:[150,371],namespac:[28,39,60,72,77,81,82,88,90,95,96,98,120,143,149,159,182,186,202,206,222,224,230,244,246,251,253,265,266,275,293,297,311,328,342,351,379,380,396,412,415,416,426,427,431,432,439,440,441,447,448,449,456,458,461,465,470,471,472,473,475,477],namespace_dn:[415,475],namespace_err:426,namespace_oid:415,namespace_separ:328,namespace_url:415,namespace_x500:415,namespaceerr:426,namespaceuri:[426,432],nan:[60,147,178,216,222,277,295,368,369,453,474,476,477],nand:472,nannynag:383,nanosecond:[113,475],napm:169,narg:[60,120,303,477],narr:186,narrow:[30,56,124,360,368,472],nasa:86,nasti:[102,439],natali:477,nation:[61,438],nativ:[6,36,56,63,84,87,89,104,147,150,160,168,174,222,256,304,307,350,364,373,380,390,403,435,440,467,469,472,477],natur:[30,55,64,70,81,88,101,104,106,147,150,157,166,168,178,186,230,277,287,305,322,332,337,350,360,401,418,419,429,440,442,446,451,455,456,470,474,476,477],nav:[60,476],navi:462,navig:[60,93,169,191,394,395,405],navservic:60,nb_absolut:55,nb_add:55,nb_and:55,nb_coerc:55,nb_divid:55,nb_divmod:55,nb_float:55,nb_floor_divid:55,nb_hex:55,nb_index:[41,55,475],nb_inplace_add:55,nb_inplace_and:55,nb_inplace_divid:55,nb_inplace_floor_divid:55,nb_inplace_lshift:55,nb_inplace_multipli:55,nb_inplace_or:55,nb_inplace_pow:55,nb_inplace_remaind:55,nb_inplace_rshift:55,nb_inplace_subtract:55,nb_inplace_true_divid:55,nb_inplace_xor:55,nb_int:55,nb_invert:55,nb_long:55,nb_lshift:55,nb_multipli:55,nb_neg:55,nb_nonzero:55,nb_oct:55,nb_or:55,nb_posit:55,nb_power:55,nb_remaind:55,nb_rshift:55,nb_subtract:55,nb_true_divid:55,nb_xor:55,nbar:[123,333],nbyte:[291,328,360],ncall:[238,322],nchannel:[118,119,129,306,376,417],ncmdshow:374,ncol:169,ncsa:409,ncurs:[87,93,169,470,471,474],ncycl:258,ndata:[328,431],ndbm:[176,188],nde:368,ndebug:72,ndetail:186,ndiff:[180,186,471,472],ndigit:222,ndim:[6,368],neal:[473,475,476],nearest:[90,174,178,300,441,447,451,455,463],nearli:[98,100,102,106,127,168,178,188,267,309,311,403,440,472,473,476,477],neat:[451,472],neatli:[101,477],neccessari:409,necess:413,necessari:[6,28,30,55,63,72,76,77,79,80,81,82,83,87,88,90,96,98,100,101,103,106,107,109,113,119,121,123,127,134,135,138,147,152,157,162,169,178,186,194,200,201,202,206,213,219,225,231,241,244,246,252,256,258,264,271,273,274,283,287,293,299,303,304,305,311,314,319,320,322,330,338,344,358,360,364,365,368,371,373,374,377,381,382,386,388,389,390,391,393,400,401,403,407,409,410,417,418,423,424,426,431,434,435,437,440,442,446,447,450,451,453,460,472,473,475,476,477],necessarili:[20,63,64,75,76,83,88,89,102,107,158,169,178,186,222,225,273,277,293,304,311,333,360,365,368,390,392,416,423,426,431,438,447,473,475,476,477],ned:477,need:[1,3,4,5,6,8,11,12,16,20,21,24,28,30,37,40,43,49,51,52,55,56,58,60,62,63,64,66,67,68,70,71,72,75,76,77,79,80,81,82,83,84,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,110,111,113,114,116,117,118,119,123,125,126,127,129,132,134,138,139,143,146,147,148,149,150,151,152,157,158,160,162,163,168,169,171,174,178,180,182,184,186,192,193,195,197,200,201,202,203,204,205,206,212,215,219,221,222,224,227,230,234,236,240,243,245,246,251,253,255,256,258,263,264,265,266,267,270,271,273,276,282,287,290,292,293,297,299,303,304,306,308,311,315,317,318,319,321,322,325,328,332,334,335,336,337,339,341,343,346,348,350,351,352,358,360,361,364,365,368,369,373,374,377,380,384,386,387,388,389,391,392,394,395,396,401,403,405,407,409,410,411,412,413,416,418,419,423,425,426,427,428,429,430,431,432,434,435,436,437,440,442,445,446,447,448,449,451,452,453,454,455,457,458,459,460,461,462,463,467,468,469,470,471,472,473,475,476,477],needforspe:475,needn:[28,311,333,380],neg:[6,16,33,34,36,41,47,55,56,63,79,96,101,103,123,124,139,141,146,147,150,152,154,168,169,170,174,178,191,222,223,256,258,260,264,277,287,293,302,311,322,332,333,334,345,352,353,368,369,374,380,391,392,396,403,409,426,440,442,446,447,452,453,457,460,470,473,474,475,476,477],negat:[14,41,178,302,368,442,453],negative_opt:63,negative_sign:264,neglect:[102,113],neglig:[368,438],negoti:[127,365,476],neighbor:[429,472,473],neighbour:88,neil:[470,471,472,473,475,477],neither:[43,63,73,101,131,150,178,186,196,200,203,222,260,265,273,296,303,308,311,361,365,399,401,419,438,440,442],nel:475,nelem:138,nemu:180,neophyt:88,nephew:470,nest:[4,60,77,81,88,90,96,98,101,111,143,157,160,168,180,182,186,196,239,253,258,260,273,292,308,309,321,328,333,337,368,369,379,391,401,425,429,431,439,440,441,442,447,451,452,456,457,460,463,470,475,476,477,478],nested_scop:[111,447,471,472],net:[63,66,72,83,84,87,88,93,105,107,162,174,231,333,345,365,437,438,445,470,471,472,473,474,475,476],netbsd:315,netherland:438,netlib:438,netlink:475,netloc:[411,477],netlog:477,netlogg:477,netrc:[60,209,221,252,299,472],netrcparseerror:296,netscap:[162,169,270,273,419,438,471,474,476],network:[60,98,102,104,105,107,113,121,126,127,129,205,248,252,254,267,293,299,304,311,315,345,355,365,373,384,388,409,411,415,425,454,457,471,472,473,476],netzer:473,neumann:440,neutral:[50,72,77,252],never:[4,6,16,21,24,26,28,30,37,39,52,53,55,68,77,79,87,88,90,91,93,95,96,98,100,101,105,106,107,123,127,129,132,138,142,143,150,162,167,168,169,174,178,180,192,196,200,206,222,230,236,241,256,260,263,264,265,267,276,293,303,304,305,311,314,328,332,333,336,337,345,356,360,361,364,368,369,373,374,384,385,391,396,405,409,410,416,419,426,429,431,435,440,446,451,452,455,461,465,467,470,471,472,473,474,475,476],nevertheless:[70,150,206,303,384,395,461],new_align:215,new_attr:472,new_compil:63,new_featur:109,new_font:215,new_fram:129,new_i:169,new_l:88,new_limit:[167,475],new_mailbox:246,new_margin:215,new_modul:249,new_nod:125,new_noddi:79,new_panel:171,new_path:87,new_rank:429,new_root:63,new_spac:215,new_str:333,new_struct:476,new_styl:215,new_x:169,newattr:[87,426,472],newbi:[89,475,477],newchild:426,newchildren:401,newcom:81,newconfig:119,newdatatyp:79,newdatatype_cal:79,newdatatype_compar:79,newdatatype_dealloc:79,newdatatype_getattr:79,newdatatype_gets:79,newdatatype_hash:79,newdatatype_method:79,newdatatype_print:79,newdatatype_repr:79,newdatatype_setattr:79,newdatatype_sets:79,newdatatype_str:79,newdatatypeobject:79,newdict:88,newdoc:427,newer:[63,79,83,87,89,90,92,98,100,106,118,162,186,266,267,273,304,309,322,328,345,365,368,424,467],newer_group:63,newer_pairwis:63,newest:[71,106],newflag:21,newfontset:394,newfrag:129,newfunc:[55,79,94,223],newgroup:299,newheight:245,newindex:401,newkeyword:223,newl:427,newli:[3,4,28,30,77,88,98,149,162,195,293,304,314,320,356,394,401,403,426,439,440,451,474,476],newlin:[60,63,82,90,95,101,123,131,135,136,139,149,151,155,167,169,180,186,200,202,210,215,222,256,260,263,267,273,287,299,321,333,339,348,351,361,368,369,374,382,389,392,393,397,398,400,409,416,427,434,435,439,443,446,447,448,457,460,463,465,471,474,475,476,477,478],newloc:253,newmailbox:246,newnam:[288,463],newnew:299,newpad:[93,169],newpart:50,newpath:288,newpathnam:396,newpric:152,newschem:394,newscmprio:394,newsgroup:[95,219,299,464,474],newsiz:[24,50,53,287],newsocket:365,newsread:273,newstat:129,newstr:191,newstyl:440,newsyslog:267,newtab:26,newterm:169,newton:[161,333],newurl:410,newval:258,newvalu:304,newwidth:[129,245],newwin:[93,169],next:[1,20,28,31,32,37,55,56,60,72,76,77,79,81,83,87,88,90,93,96,99,100,101,104,107,109,118,126,129,134,138,139,142,143,146,148,149,150,151,152,158,162,167,168,169,175,178,180,182,186,191,200,206,210,215,218,219,222,225,230,236,241,244,253,255,258,265,267,273,287,291,292,293,299,303,304,309,311,321,322,328,332,333,334,343,350,351,360,361,364,365,368,369,374,384,394,401,410,415,416,429,435,439,440,441,442,445,447,448,450,451,452,453,454,458,459,460,461,463,469,470,471,472,473,475,476,477],next_control:290,next_minu:178,next_plu:178,next_toward:178,nextfil:210,nexti:258,nextkei:226,nextpart:282,nextsibl:426,nfc:406,nfd:406,nfkc:[371,406],nfkd:406,nfl:322,nfoo2:333,nframe:[118,376,417],nfs:63,ngettext:230,nginx:[106,365],nglyph:213,ngot:410,nhere:[87,193],nhost:365,nhow:193,nhttp:193,ni_:360,nice:[64,81,91,102,106,128,143,152,168,186,222,236,245,304,358,361,386,419,440,451,452,455,457,458,460,470],nicer:[238,333],niceti:476,nich:93,nichola:[104,473],nick:[96,100,342,440,472,474,475,476,477],nicknam:[90,464],niemey:[230,472,473,474,475],nifti:473,nigetspamdata:80,nil:[434,473],nine:178,nine_year:174,ninth:471,nir:477,nirina:477,nis:[60,252,408,475],nishimura:[332,438],nist:[235,349,473],nitem:[54,55],nl_langinfo:[169,264,380,472],nlargest:[90,223,236,474,475],nline:169,nlocal:[12,297],nlst:221,nmh:273,nnn:[240,410],nntp:[60,192,252,254,411,474],nntpdataerror:299,nntperror:299,nntplib:[60,192,197,252,254,470,474,477],nntppermanenterror:299,nntpprotocolerror:299,nntpreplyerror:299,nntptemporaryerror:299,no_block:[8,92],no_bug:77,no_cont:241,no_data_allowed_err:426,no_modification_allowed_err:426,no_proxi:409,no_sit:380,no_strict_list_append:470,no_user_sit:380,noarch:70,nobject:88,nobodi:[77,87,143,144,235,278,358],noboundaryinmultipartdefect:196,nocbreak:[93,169],nodataallowederr:426,noddi:[24,79],noddy2:79,noddy3:79,noddy4:79,noddy_clear:79,noddy_dealloc:79,noddy_getfirst:79,noddy_getlast:79,noddy_getset:79,noddy_init:79,noddy_memb:79,noddy_method:79,noddy_nam:79,noddy_new:79,noddy_noddyobject:79,noddy_noddytyp:79,noddy_setfirst:79,noddy_setlast:79,noddy_travers:79,noddytyp:79,node:[60,79,82,236,240,262,275,304,305,308,315,360,365,367,378,397,401,415,427,428,429,431,443,463,470,473,475,476,477],node_or_str:125,nodelai:[93,169],nodelist:[60,275,427,440],nodenam:[304,426],nodetransform:[125,476],nodetyp:[157,426,427],nodevalu:426,nodevisitor:[125,476],nodisc:142,noecho:[93,169],noel:307,noexpr:264,nofil:239,nois:[180,303,416],noisi:[92,303],nok_builtin_nam:338,noller:476,noload:311,nome:96,nomodificationallowederr:426,non:[2,3,4,6,8,9,16,19,20,24,26,29,30,34,36,37,43,50,53,55,56,60,63,64,66,70,72,77,79,82,83,87,88,90,93,94,95,96,98,104,105,106,114,117,121,127,131,136,139,142,143,144,148,150,158,162,167,168,169,170,174,178,180,182,185,186,188,192,195,197,198,200,202,204,205,206,215,216,219,221,225,228,229,230,231,234,235,236,237,241,244,245,246,249,252,256,257,258,263,264,265,266,267,270,271,277,278,281,283,284,287,292,293,295,296,297,303,304,305,306,308,309,311,314,315,319,320,322,328,330,331,332,333,334,346,348,349,351,353,356,360,361,364,366,367,368,369,371,373,374,380,381,384,385,389,391,392,397,398,407,409,410,416,419,429,431,434,437,438,440,442,444,446,448,451,452,453,458,460,465,467,469,470,471,472,473,474,475,476,477],non_authoritative_inform:241,non_exist:374,non_existent_fil:374,non_nul:453,non_release_vers:315,nonam:186,nonblock:306,noncircular:87,noncod:98,noncompli:318,nonconform:423,nondescript:106,nondeterminist:[332,360],none:[3,4,15,26,48,49,51,55,56,59,60,63,64,72,77,81,88,90,91,94,95,96,98,99,101,102,103,104,105,109,111,113,114,116,118,121,123,125,126,127,129,131,134,138,139,140,142,143,148,149,150,151,152,157,158,159,161,162,167,168,169,174,178,180,182,185,186,191,193,194,197,198,200,201,203,204,206,210,212,213,215,219,221,222,224,226,228,229,230,234,235,241,246,248,249,250,251,253,256,258,260,264,265,266,267,273,274,276,279,281,287,288,290,293,296,297,298,299,300,302,303,304,309,311,312,314,315,317,320,321,322,326,328,330,332,333,334,338,339,340,342,345,348,350,351,352,353,355,356,359,360,361,364,365,368,369,373,374,376,380,381,384,385,386,388,391,392,393,394,396,399,400,401,403,404,407,409,410,411,416,417,418,419,420,422,423,426,427,429,430,431,432,434,435,436,439,440,442,446,447,448,452,453,457,461,470,471,472,473,474,475,476,477],nonempti:[148,333,403,419,440],nonetyp:[91,159,333,364,404],nonexclus:438,nonexist:423,noninfring:438,nonintegr:178,nonl:169,nonmultipart:201,nonneg:[4,178,360,403,440,442,447],nonobvi:155,nonprint:331,nonspac:104,nonstandard:[364,475],nonzero:[8,20,28,52,56,77,81,101,109,178,191,212,218,219,265,267,287,293,325,332,333,368,369,380,387,390,391,392,440,446,449,476],nonzerodigit:446,noop:[246,293,318,358],nooptionerror:[158,477],nop:[182,385,452],nope:452,nopic:403,noqiflush:169,nor:[20,28,43,73,79,90,91,105,114,131,150,162,212,215,265,282,296,303,309,311,314,330,350,361,365,399,401,419,438,440,442],noraw:169,nordic:150,nores:403,norm:277,normal:[3,4,5,17,19,20,22,23,25,26,28,30,33,49,51,55,58,60,63,64,72,73,75,76,77,79,87,88,90,93,94,95,98,99,102,105,106,107,108,110,111,114,123,127,128,131,134,135,139,140,141,142,148,150,152,158,168,169,174,178,180,186,191,193,194,195,200,206,210,213,214,216,222,227,230,231,240,241,244,252,255,256,264,266,281,287,291,293,303,304,305,308,309,310,314,317,322,325,328,332,333,334,335,339,342,344,346,348,351,353,355,358,360,363,364,365,366,368,369,371,380,386,388,391,392,400,401,403,405,406,407,409,410,411,416,418,423,426,427,430,431,432,434,435,439,440,441,442,443,445,447,449,451,452,454,460,461,465,471,476],normalize_whitespac:[83,104,105,180,186,392,411,461],normalvari:[87,332],normcas:[214,272,305],normpath:[63,272,304,305,477],north:[401,403,477],northampton:105,norwegian:[77,150,452],norwitz:[473,475,476],nos:473,nose:[407,477],nosectionerror:158,noshow:99,nostra:475,nosuchmailboxerror:273,not_:[96,302],not_accept:241,not_extend:241,not_found:241,not_found_err:426,not_impl:241,not_modifi:241,not_supported_err:426,not_test:[442,443],notabl:[30,60,62,83,90,364,408,464,471,472,473,474,475,476,477],notaft:365,notanumb:217,notat:[60,81,90,96,101,104,178,260,287,328,360,368,369,372,374,396,426,427,431,439,440,442,444,446,451,452,453,455,457,461,473,474,475],notation_nod:426,notationdecl:431,notationdeclhandl:328,notationnam:328,notbefor:365,notconnect:241,note:[4,6,10,14,17,20,24,26,28,30,37,40,43,47,50,51,55,56,58,60,63,64,66,67,70,71,72,73,76,77,79,81,82,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,104,105,107,109,110,113,114,117,123,124,125,126,127,128,129,139,143,144,147,149,150,151,152,156,157,158,160,161,162,167,168,169,170,173,174,176,180,181,185,186,191,192,193,195,196,197,199,200,203,206,207,208,212,213,214,215,216,218,221,222,225,226,228,230,232,233,234,238,240,241,244,246,249,253,254,256,257,258,260,264,265,266,267,269,271,273,275,277,282,284,287,292,293,295,296,297,298,299,301,302,303,304,305,306,308,309,311,313,314,315,317,318,319,320,321,322,323,330,331,332,333,335,336,337,339,342,345,346,348,350,351,352,353,355,356,357,358,360,364,368,369,370,373,376,379,380,384,385,387,388,389,390,391,392,393,395,396,398,407,409,410,413,415,416,417,418,419,423,425,426,429,430,431,432,434,435,436,438,439,440,441,442,443,445,446,447,448,449,451,452,453,454,455,457,458,460,461,462,465,469,470,472,473,474,475,476,477],note_track:345,notebook:[60,394,395],notebooktabchang:401,notemptyerror:273,notepad:[150,311,446],noteq:125,notequ:397,noteworthi:[273,456,470,471],notfounderr:426,noth:[20,28,30,63,72,76,77,79,81,82,91,95,98,99,101,102,105,106,107,126,147,156,161,169,174,180,182,186,195,204,206,215,216,221,230,240,244,249,256,264,265,267,273,291,293,303,308,311,318,348,352,353,357,361,365,371,376,385,388,391,396,407,423,433,438,442,446,447,450,451,452,459,461,472,473,476,477],notic:[1,30,72,77,79,81,88,91,98,99,101,102,103,105,107,109,126,150,158,165,178,198,210,225,230,232,256,267,293,338,368,380,381,388,396,401,438,440,442,451,453,459,469,471,473,477],notif:[27,59,60,113,192,377,431,470,477],notifi:[98,100,244,246,293,391,416,418],notify_al:391,notifyal:391,notimeout:169,notimpl:[60,113,114,159,174,300,404,440,461,477],notimplementederror:[20,113,126,162,165,174,206,265,293,304,332,357,365,461],notimplementedtyp:404,notin:125,notion:[51,55,63,89,107,174,178,180,186,311,337,368,401,426,430,442,445,448,449],notori:95,notset:[98,265,266,293],notstandalonehandl:328,notsupportederr:426,nottingham:463,nottinghamfolk:463,notwithstand:[72,438,470],noun:[369,451],noutrefresh:[93,169],nov:[96,132,174,203,221,339,365,392,462,472],novel:[255,472,473,475],novemb:[81,174,446],novic:[303,396,469],now:[1,4,20,30,34,37,48,55,60,64,71,72,73,76,77,79,81,83,87,88,91,93,94,98,99,100,101,102,103,104,105,106,107,123,128,139,143,152,160,162,167,168,174,178,186,192,193,198,201,205,212,216,218,219,235,240,241,246,249,251,256,258,273,277,278,287,293,294,303,304,315,316,322,328,333,356,360,361,364,365,370,380,386,392,393,396,403,404,407,409,418,419,427,429,434,435,438,440,442,446,447,449,450,451,452,453,454,456,460,461,462,465,469,470,471,472,473,474,475,476,477],nowadai:[222,236,384],nowak:473,npb:[150,473],npn:365,nproperti:117,nptr:16,npy_:333,npy_myfunc:333,npython:476,nsampl:119,nsecond:[256,370,460],nsig:353,nsmallest:[90,223,236,474,475],nswe:401,nt4:476,nt_offset:397,nt_user:381,nteventloghandl:[60,98,120,266],nth:[258,401],nthi:157,nthree:180,nto:358,ntoh:[102,360],ntohl:[102,360],ntpath:[305,405],ntransfercmd:221,ntree:180,ntwo:180,nubi:476,nuitka:81,nul:[4,50,55,167,168,169,170,237,304,328,434],null_ptr:168,nullformatt:215,nullhandl:[60,98,99,120],nullimport:[249,380],nulltransl:[60,242],nullwrit:215,num:[14,41,99,125,169,178,230,240,246,287,293,303,369,452,453,476,477],num_fram:142,num_param:364,num_str:260,num_worker_thread:330,numarg:76,numarrai:475,number:[1,2,3,4,6,12,15,16,17,19,20,22,24,26,27,28,29,30,34,35,36,38,43,44,46,47,48,50,51,52,53,56,60,64,66,67,68,69,70,71,72,75,76,77,79,80,81,82,84,89,90,91,93,95,96,98,99,100,101,102,103,104,106,107,108,113,114,117,118,119,123,124,125,126,127,129,132,134,135,139,140,141,142,143,145,150,152,157,158,159,160,161,167,168,169,174,178,180,182,185,186,191,194,198,200,205,206,207,208,210,212,213,215,216,217,219,221,222,223,225,230,231,235,236,240,241,243,244,245,246,247,252,253,255,256,258,262,264,265,267,269,270,273,274,276,279,280,281,290,293,295,296,299,301,302,303,304,305,306,308,309,311,315,316,318,321,322,326,328,330,333,334,335,336,337,339,342,343,345,346,348,351,352,353,354,358,359,360,361,363,364,365,366,367,368,369,373,374,376,377,379,380,381,385,389,391,392,393,396,397,398,399,400,401,403,404,407,409,410,411,415,416,417,418,419,422,423,424,426,429,430,432,433,434,435,440,442,443,445,446,447,448,450,451,452,453,454,455,456,457,459,461,462,463,464,465,467,468,470,471,472,473,474,475,477,478],number_class:178,number_of_process:293,number_of_subs_mad:333,numer:[2,27,36,41,55,56,60,70,72,83,88,90,96,98,101,102,104,105,106,117,126,132,134,135,137,147,167,169,173,178,203,205,206,215,216,218,222,233,234,240,241,252,260,264,265,273,276,293,302,304,308,322,324,328,333,343,345,348,351,358,360,365,369,378,396,397,401,403,406,407,409,410,435,437,442,453,457,460,471,473,474,475,476,477],numeric_compar:103,numeric_level:98,numfre:476,numlin:180,numliter:109,nummessag:318,numpi:[88,124,461,475,476],nurb:231,nurbscurv:231,nurbssurfac:231,nut:102,nvarrai:231,nxn:[96,472,473],nyman:473,nzerodivisionerror:99,o32:107,o_append:[291,304],o_async:304,o_binari:[291,304],o_creat:304,o_direct:304,o_directori:304,o_dsync:304,o_excl:[304,386],o_exlock:[207,304,475],o_ndelai:[102,207,304],o_noatim:304,o_noctti:304,o_nofollow:304,o_noinherit:304,o_nonblock:[87,102,304],o_random:304,o_rdonli:[291,304],o_rdwr:[304,353],o_rsync:304,o_sample_r:377,o_sequenti:304,o_shlock:[207,304,475],o_short_liv:304,o_sync:304,o_temporari:304,o_text:[291,304],o_trunc:304,o_wronli:304,ob_iv:79,ob_refcnt:[51,55],ob_siz:[51,55],ob_typ:[43,51,55,79],obei:[81,105,351,368,440,476],obershelp:180,obj1:[79,117,474],obj2:[79,117,474],obj:[6,10,20,21,28,31,42,50,55,56,79,80,81,82,87,88,90,94,96,99,103,150,168,171,186,222,225,260,287,293,302,311,335,346,368,369,407,418,440,441,451,452,470,471,472,473,474,475,476],obj_or_typ:168,obj_tot:96,obj_underlyingdatatypeptr:79,objc:63,objclass:212,objdump:168,object2:92,object:[4,8,11,13,16,24,26,27,28,31,35,36,41,42,45,46,47,52,58,60,63,70,72,76,77,78,80,81,83,84,89,90,93,94,95,96,100,101,103,104,105,106,107,114,115,116,118,120,121,122,124,125,126,127,131,134,136,139,140,141,143,145,146,147,151,157,159,160,163,164,168,172,173,176,177,179,182,192,194,195,196,197,198,199,200,202,205,206,207,208,209,210,211,213,214,215,216,220,222,224,225,226,227,229,230,233,234,235,237,244,248,249,251,252,254,255,256,257,258,262,267,268,269,270,271,275,278,283,286,287,289,291,295,301,302,303,305,307,309,310,312,314,316,322,324,327,329,331,332,336,337,342,344,347,349,352,353,362,363,369,370,372,373,375,378,379,380,381,386,387,388,389,390,392,393,394,395,396,398,399,400,403,404,406,407,408,411,414,416,421,423,433,437,439,441,442,444,446,447,448,449,452,453,454,456,458,460,461,462,463,465,467,469,470,471,472,475,478],object_filenam:63,object_hook:260,object_pairs_hook:[260,477],objectspecifi:[115,117],objectwis:470,objimpl:470,objn:474,objobjargproc:55,objobjproc:55,objtyp:94,oblig:470,oblivi:348,obmalloc:[471,473,475],obscur:[186,380,476],observ:[3,70,99,130,273,348,403,411,447,472],obsolesc:[318,442,446],obsolet:[55,60,64,72,77,93,96,106,124,143,162,182,249,252,260,304,317,319,328,332,368,392,416,424,470,471,472,475,477],obtain:[6,26,30,56,81,87,89,98,101,108,124,143,145,146,169,174,178,180,222,227,235,243,246,252,256,258,264,265,266,278,287,303,304,317,322,327,332,333,346,365,368,374,379,409,410,413,415,418,423,430,438,439,442,446,451,453,455,460,470,472,473,475,476],obufcount:[306,377],obuff:126,obuffre:306,obviou:[30,55,72,81,88,89,92,96,98,99,101,107,115,169,178,236,306,311,322,340,373,434,470,474,475],obvious:[55,63,64,77,88,99,101,107,265,282,303,315,374,451,470],ocaml:96,occas:[63,105,309,327,373,388,475],occasion:[70,76,81,87,88,89,95,123,124,141,169,178,180,230,244,273,277,303,304,338,339,391,395,447,451,463,470,475,476],occupi:[77,104,118,336,401],occur:[4,6,16,20,26,30,31,34,37,41,52,55,56,63,72,77,79,82,83,88,94,95,96,98,99,100,111,123,125,127,132,134,142,143,145,149,150,156,157,158,160,167,169,178,185,186,189,190,191,205,206,210,216,222,228,230,237,252,253,256,265,267,273,282,293,303,304,308,309,314,317,325,328,333,345,348,352,353,358,360,364,365,368,369,374,380,384,388,389,391,392,396,400,401,403,409,410,416,419,423,425,426,431,434,435,437,439,440,441,442,446,447,449,451,452,453,454,461,463,465,473,475,476,477],occurr:[47,56,63,81,88,91,98,101,124,125,152,169,200,228,273,302,303,332,333,345,368,369,384,416,429,440,441,442,445,446,447,472,474,475],ocert:465,ocsp:365,oct:[88,96,99,107,155,174,221,222,224,365,369,393,440,461,472,476],octagon:403,octal:[101,104,109,121,143,176,188,222,224,226,303,304,333,368,369,446,470,471,473,474,476],octdigit:[369,446],octet:[193,201,318,354,369],octinteg:446,octob:[174,438,470,472,473,476],od1:[152,477],od2:[152,477],odd:[56,60,81,93,96,146,178,321,322,374,386,446,456,470,473,474,475,477],oddbal:303,odict:311,odomet:258,off:[60,63,81,87,90,93,94,96,98,100,101,104,105,107,109,126,148,158,162,168,169,180,182,191,203,208,219,221,236,256,265,266,267,277,301,303,304,305,313,318,320,322,339,351,355,358,364,380,387,392,393,401,403,407,409,412,440,446,447,451,452,456,459,461,463,470,471,472,473,474,475,476],off_t:319,offend:[89,441,454,471],offer:[1,55,62,69,70,77,78,84,87,88,91,93,94,96,98,99,102,104,105,107,113,139,149,152,157,164,178,208,235,236,239,252,256,258,273,293,317,330,333,334,342,348,352,357,364,368,374,392,409,413,424,432,438,450,454,457,462,463,469,470,471,472,473,474,475,476,477],offic:[72,438],offici:[6,28,84,150,194,203,212,222,281,306,339,427,434,435,440,467,469,470,471,472,475,477],offload:293,offscreen:[60,219,268,401],offset:[6,13,19,51,55,79,87,125,129,139,142,146,157,168,174,178,182,203,206,207,221,222,240,256,273,287,293,319,320,328,339,368,373,392,431,435,440,457,470,475,476],offsetof:79,offvalu:396,oflag:387,ofs:168,often:[8,11,12,28,30,51,56,66,68,70,72,77,79,81,83,84,87,88,90,93,95,96,101,104,105,106,107,108,123,127,135,141,143,148,157,163,167,168,174,178,180,186,189,190,192,195,219,222,230,233,236,252,253,258,290,303,322,323,325,351,360,364,365,368,371,377,380,388,391,392,396,407,409,410,430,437,445,446,447,451,453,454,455,457,459,461,462,465,470,471,472,473,474,475,476,477],ohioe:87,ohm:104,oid:[365,415,418],ok_builtin_modul:338,ok_file_typ:338,ok_path:338,ok_posix_nam:338,ok_sys_nam:338,okai:[28,123,264,423,461],okbutton:396,oktob:446,old:[2,4,10,15,27,31,37,50,52,53,55,60,77,81,83,87,88,90,92,94,98,101,106,109,114,123,125,133,136,138,152,162,169,178,179,200,219,222,223,245,246,254,260,266,267,272,273,281,293,303,304,305,311,315,320,322,337,338,350,353,368,369,374,384,387,403,404,405,423,426,431,435,438,439,442,446,447,451,453,454,456,460,465,470,471,473,474,475,476,477],old_express:442,old_expression_list:442,old_lambda_expr:442,old_lambdef:443,old_level:99,old_nod:125,old_password:158,old_path:87,old_test:443,old_width:129,oldattr:426,oldchild:426,olddatabas:83,olddict:88,older:[3,43,55,60,62,63,77,79,83,88,90,93,106,123,142,158,169,178,192,198,222,225,230,235,244,251,257,266,269,273,304,306,308,309,311,317,328,364,365,368,386,388,389,393,398,409,416,431,437,446,467,469,470,473,476,477],oldest:[100,106,225,267,391,418,477],oldflag:87,oldlist:88,oldmailbox:[246,273],oldmask:169,oldnam:288,oldpackag:475,oldpath:288,oldterm:87,oledl:[168,476],oleg:475,oliph:[475,476,477],oliv:470,olivedrab1:401,olivedrab2:401,olsen:[476,477],olson:174,omega:104,omf:[89,107],omg:[426,427],omiss:[328,360],omit:[51,63,71,79,81,90,101,118,119,123,124,127,132,136,139,142,146,152,158,167,169,180,186,197,198,199,212,215,222,230,231,234,246,247,249,256,263,264,273,281,287,290,293,297,303,304,308,309,311,318,328,333,334,338,345,346,351,352,356,358,360,368,369,373,384,392,400,401,402,403,407,409,416,417,425,429,430,438,439,440,442,447,454,457,460,465,473,474,475,477],on_fals:88,on_flag:380,on_or_off:186,on_tru:88,onc:[4,19,20,24,28,30,52,55,71,73,76,77,79,81,87,88,89,93,96,98,99,100,101,103,104,106,107,114,118,123,126,127,128,132,138,139,143,148,150,151,152,157,178,180,186,200,210,215,221,222,230,236,240,244,249,253,256,258,265,266,273,293,294,299,303,304,306,311,319,322,328,330,333,334,345,352,353,356,360,361,364,365,368,373,380,384,391,393,396,398,407,409,410,416,419,423,426,427,429,431,432,437,439,440,442,447,450,451,452,458,461,464,465,470,471,473,474,475,476,477],onclick:403,ondrag:403,ondrej:473,one:[1,3,4,6,8,11,12,14,16,20,21,22,26,28,29,30,32,37,39,43,49,50,51,52,53,55,56,63,64,66,67,70,71,72,73,75,76,77,79,80,81,82,83,87,89,90,91,92,93,94,95,96,98,99,100,101,102,104,105,106,107,109,113,114,116,118,121,123,124,125,126,127,129,131,132,133,134,135,139,140,142,143,146,147,148,149,150,152,157,159,160,162,163,165,167,168,169,174,176,178,180,182,186,191,192,193,194,195,197,198,200,201,202,203,204,206,207,208,210,212,215,216,217,218,219,221,222,223,228,229,230,231,234,235,236,241,244,245,246,247,249,253,256,258,260,263,264,265,266,267,269,270,273,274,275,276,277,279,281,283,287,290,291,292,293,299,300,302,303,304,305,306,307,308,309,311,313,314,316,317,320,321,322,325,328,330,332,333,334,336,338,339,343,345,346,350,351,352,353,356,358,359,360,361,364,365,366,368,369,373,374,377,378,379,380,381,384,385,386,387,388,389,390,391,392,393,394,396,398,399,401,403,406,407,409,410,411,413,415,416,418,420,423,424,425,426,427,429,431,434,435,439,440,441,442,445,446,447,448,451,452,453,454,455,457,458,459,460,461,462,463,464,465,467,470,471,472,473,474,475,476,477],onecmd:148,onelineexceptionformatt:99,onerror:[304,314,352],ones:[56,62,63,77,79,88,90,91,92,95,101,106,107,109,150,162,230,281,303,317,333,350,360,364,368,369,374,388,392,401,404,410,413,423,440,460,470,471,472,473,474,477],oneself:125,ongo:469,onion:364,onkei:403,onli:[0,3,4,5,6,19,20,21,22,24,26,28,30,33,34,36,37,39,42,43,45,47,50,51,52,53,54,55,56,58,60,62,63,64,67,68,69,70,71,72,73,75,76,77,78,79,80,81,82,83,87,88,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,109,113,114,118,121,123,124,125,126,127,128,129,131,133,134,135,136,138,139,141,142,143,144,146,148,150,152,156,157,158,161,162,163,167,168,169,171,174,175,176,178,180,181,184,185,186,188,192,193,194,197,198,199,200,201,202,203,205,206,207,208,210,212,213,215,219,221,222,223,225,226,227,228,230,231,232,234,235,237,238,239,241,245,246,247,249,253,255,256,257,258,259,260,261,264,265,266,267,268,273,276,278,279,280,281,282,283,287,290,291,292,293,298,302,303,304,305,306,308,309,311,313,314,315,316,317,320,321,322,323,324,325,327,328,330,333,334,336,337,338,339,343,345,346,348,349,350,351,352,353,354,355,358,360,361,362,364,365,366,368,369,370,371,373,374,376,377,380,381,383,384,386,387,388,389,390,391,392,393,394,395,396,398,399,400,401,402,403,404,405,407,409,410,411,412,413,414,415,416,417,418,419,420,421,423,426,427,428,429,430,431,432,434,435,436,437,438,439,440,441,442,445,446,447,449,450,451,452,453,454,455,457,459,460,461,462,463,465,468,469,470,471,472,473,474,475,476,477],onlin:[60,83,100,106,179,231,241,252,259,307,396,403,430,438,452,472,476],onoff:219,onreleas:403,onscreenclick:403,ont:309,ontim:403,onto:[63,102,107,167,169,182,215,236,246,311,321,339,351,371,403,407,470,476],ontosi:434,onvalu:396,onward:[96,178,218,253,308,368],oob:127,ooi:79,ooo:446,oop:[186,454],oor:168,op1:442,op2:442,op_al:365,op_cipher_server_prefer:365,op_enable_middlebox_compat:365,op_no_compress:365,op_no_sslv2:365,op_no_sslv3:365,op_no_tlsv1:365,op_no_tlsv1_1:365,op_no_tlsv1_2:365,op_no_tlsv1_3:365,op_single_dh_us:365,op_single_ecdh_us:365,opaqu:[8,11,28,30,66,142,222,256,328,366,424,429,471],opcod:[180,182,312,473,474,476,477],opcodeinfo:312,open:[1,21,28,36,60,63,64,70,71,77,81,83,84,89,90,93,95,96,98,99,100,101,104,106,107,108,109,110,113,117,118,120,121,123,127,128,138,139,142,143,150,152,157,158,160,162,167,169,174,175,176,180,185,188,191,193,202,205,206,207,210,215,219,221,222,226,227,230,231,234,239,240,241,244,246,248,249,252,253,254,256,264,265,266,267,269,270,271,273,276,279,280,281,287,290,292,293,299,305,306,311,313,314,317,318,320,323,328,332,336,337,338,345,348,350,351,353,354,357,358,360,364,365,366,368,374,376,377,380,382,384,385,386,391,392,394,396,400,401,404,412,414,417,419,420,427,429,430,432,434,435,438,440,446,447,449,451,452,454,457,460,461,462,463,467,469,470,471,473,474,475,476,477],open_flag:226,open_func:475,open_item:475,open_new:[419,475],open_new_tab:[419,475],open_osfhandl:291,open_unknown:409,openbsd:[60,466],opencsw:468,opendatabas:290,opendir:181,openerdirector:[60,105,254],openfold:279,openfp:[376,417],opengl:231,openhook:[210,475],openid:1,openkei:113,openkeyex:113,openlog:382,openmessag:279,openmix:306,openport:119,openprocess:89,openpti:[304,323],openrf:269,opensolari:[60,466],opensourc:438,openssl:[60,235,365,470,475,476,477],openssl_cafil:365,openssl_cafile_env:365,openssl_capath:365,openssl_capath_env:365,openssl_no_ssl2:365,openssl_no_sslv3:365,openssl_no_tlsext:365,openssl_vers:[365,477],openssl_version_info:[365,477],openssl_version_numb:[365,477],opensus:468,openview:290,openvm:[287,473],oper:[4,6,15,20,27,28,30,32,36,37,41,43,47,50,55,57,58,60,64,68,69,70,72,73,76,77,78,79,80,83,86,87,89,90,93,95,98,100,101,102,104,105,106,107,108,111,113,117,118,122,123,124,125,127,129,134,137,139,141,142,143,147,150,152,167,168,169,173,174,178,182,194,198,200,204,205,206,207,208,211,213,214,215,216,217,218,221,222,225,230,236,237,239,241,244,245,252,254,255,256,257,258,264,265,267,273,276,277,293,301,305,308,311,319,320,322,323,327,328,330,332,334,336,337,338,345,346,347,350,351,353,358,360,364,366,370,372,374,380,384,385,386,387,388,391,398,401,407,408,409,410,412,413,416,419,421,423,425,426,427,432,434,435,438,439,440,441,444,445,447,450,451,452,453,454,455,456,457,458,459,460,461,465,470,471,473,474,475,476,477,478],opera:[419,475],operand:[55,60,90,91,125,132,150,157,174,206,222,265,301,302,339,368,440,442,447,454,460,472,477],operation:167,opid:43,opinion:[90,438,470,475],opmap:182,opn:[95,442],opnam:[88,182],oppon:236,opportun:343,oppos:[30,63,79,90,93,149,221,410,476],opposit:[91,96,101,152,203,333,339,360,403,470,476],ops:[98,125,157,365],opt:[66,72,76,107,193,228,303,319,396,473,476,477],opt_flag:168,opt_mov:158,opt_str:303,optik:[473,474,475],optim:[28,30,37,51,56,60,63,64,88,101,102,129,139,152,162,169,182,225,253,258,259,263,311,312,322,325,364,368,379,380,391,393,440,447,461,462,465,470,472],optimis:440,optimizedunicod:364,option:[4,20,21,41,43,51,55,60,62,63,64,66,67,68,69,70,76,77,79,81,84,87,89,90,93,96,98,99,101,102,103,105,106,107,108,109,111,115,117,119,120,121,122,124,125,127,128,129,131,132,135,138,139,140,143,145,146,148,149,150,155,156,158,159,164,167,168,169,174,175,176,177,178,179,180,182,188,191,192,193,194,197,198,199,200,201,202,203,204,206,207,208,210,215,218,219,221,222,223,225,226,227,230,231,234,236,241,243,246,247,248,249,252,253,255,256,258,259,260,264,265,266,267,270,271,273,274,281,282,283,287,290,292,293,297,299,304,305,306,309,311,318,321,322,324,326,328,330,331,332,333,338,339,342,345,346,348,350,351,353,355,356,358,360,364,365,368,369,371,374,380,381,382,383,384,385,388,389,390,391,392,393,394,395,400,403,409,410,411,412,415,416,419,423,427,429,430,431,433,434,436,437,439,440,441,442,445,446,447,448,449,452,453,454,457,458,459,460,461,463,464,466,467,468,469,470,471,472,473,474,475,476,477],option_class:303,option_list:303,option_str:123,option_t:63,optional_var:125,optionalreleas:111,optionconflicterror:303,optioncontain:303,optiondummi:63,optionerror:[123,303],optionflag:186,optiongroup:303,optionlist:191,optionmenu:394,optionpars:[123,180,193,303,473,475],optionvalu:303,optionvalueerror:[123,303],optionxform:158,optlist:228,optnam:360,optpars:[60,91,120,180,193,252,474,475,477],optparse_pars:303,optstr:191,or_:[96,302],or_expr:[442,447],or_test:[442,443],oracl:[138,364,475],orang:[152,302,403,453],orchestr:407,ord:[93,104,168,169,170,222,364,440,442,461,470,476],order:[1,6,24,26,28,55,56,60,63,66,68,72,73,76,77,79,81,89,90,91,93,96,98,99,101,102,103,104,105,106,107,109,114,118,119,120,123,124,125,128,133,137,138,143,146,148,150,152,157,158,160,163,167,169,170,171,174,175,178,182,186,191,192,198,200,210,215,222,225,226,228,229,230,231,232,233,236,238,239,245,246,249,252,253,255,258,259,260,264,265,266,273,282,290,293,299,301,302,304,306,308,314,317,322,324,327,328,330,332,333,338,339,343,346,351,354,356,358,360,361,363,364,365,368,369,372,374,376,380,384,386,389,391,392,396,401,403,407,409,410,413,415,416,418,419,423,426,427,429,431,435,437,438,439,440,441,444,446,447,451,452,453,455,463,465,469,470,471,472,473,474,475,476,478],ordered_attribut:328,orderedcount:152,ordereddict:[60,90,158,173,260,477],orderedset:152,orderli:[265,271],ordin:[56,104,117,150,168,169,170,174,368,369,440,443,446,460],ordinari:[87,93,98,101,124,143,186,222,234,312,333,339,350,353,383,384,429,446,447,451,470],ordinarili:[201,351],ore:180,ored:170,oregon:83,oreillynet:472,orels:[125,476],oren:473,orendorff:[473,476],oreo:161,org:[1,62,64,69,71,72,75,81,82,84,87,88,89,90,93,96,99,104,105,107,108,121,124,127,152,160,162,193,221,235,239,240,241,244,293,299,327,328,341,345,360,364,365,380,396,405,406,409,410,411,415,419,423,427,429,431,438,440,443,451,456,460,462,464,465,467,468,470,471,472,473,474,475,476,477],organ:[60,83,87,96,98,101,104,106,179,186,255,365,396,438,447,473],organis:[62,98,108,236,265],organiz:[90,365],organizationalunitnam:365,organizationnam:365,orgnam:98,orient:[4,6,37,60,83,84,88,90,94,96,106,138,140,220,252,270,293,307,311,322,360,368,391,392,395,396,401,403,451,456,471,476],orig:341,origin:[0,6,13,37,50,53,55,59,62,63,64,77,83,88,93,94,98,101,103,104,106,108,109,123,125,127,129,134,135,145,147,150,152,162,163,168,169,178,180,182,186,192,193,200,204,212,222,223,230,234,236,245,249,251,253,258,260,264,265,270,273,277,284,293,303,304,309,311,320,322,332,333,339,342,345,346,349,351,352,357,364,365,368,369,370,374,376,380,384,388,392,403,405,407,409,410,411,416,418,423,424,431,432,433,436,437,438,439,440,445,446,447,451,455,465,470,471,472,473,474,475,476,477],origin_req_host:410,origin_serv:423,original_import:251,original_list:163,original_reload:251,orm:106,orphan:[135,293],ortho2:231,ortran:6,os2:[304,380,381],os2_hom:381,os2emx:380,os2emxpath:305,os_arch:315,os_environ:423,os_nam:315,os_vers:315,osa:[60,115,117,252,268,284,472],osaconst:[60,268],osaterminolog:476,oscon2001:87,oscura:475,oserr:269,oserror:[20,63,64,193,206,304,319,352,374,384,410,461,477],osi:72,osinfo:315,osnam:63,ospe:387,oss:[60,252,286,374,473],oss_audio_devic:306,oss_mixer_devic:306,ossaudiodev:[60,252,286,405,473],ossaudioerror:306,osversioninfoex:380,osx:[130,168,244,405,409],other:[3,4,5,6,8,10,11,14,16,20,23,24,26,27,28,30,34,37,39,40,41,48,49,50,51,52,53,54,55,56,58,60,62,64,66,67,69,70,71,76,77,80,83,84,89,90,91,93,94,95,96,98,100,101,102,103,104,105,107,108,109,113,117,120,121,124,125,127,128,129,130,133,134,135,136,138,139,140,141,143,144,145,146,147,150,151,152,154,156,157,158,159,161,162,163,167,168,169,171,173,174,175,178,180,185,186,188,191,192,194,197,198,200,201,202,204,206,208,215,219,221,222,223,225,230,234,235,236,237,239,240,241,244,246,249,252,253,255,256,257,258,260,262,263,264,265,266,267,269,270,272,273,274,276,278,279,284,287,289,292,293,296,298,299,300,302,304,305,308,309,310,314,315,317,319,321,322,323,324,328,329,332,333,335,342,343,345,346,349,350,351,352,353,355,356,357,358,360,361,362,363,364,365,366,369,371,373,374,377,379,380,382,384,385,386,388,390,391,392,393,395,396,399,401,403,404,406,407,409,410,413,416,418,421,423,425,426,427,429,430,431,432,433,434,435,437,438,439,440,441,442,444,445,447,450,451,452,454,455,456,457,458,459,460,461,462,463,464,465,466,468,478],other_fract:218,othernam:[442,470],othertypeiknowabout:300,otherwis:[3,4,6,8,16,19,20,21,26,28,29,30,34,35,37,38,41,42,43,45,46,47,50,55,56,58,60,63,77,81,82,88,89,91,95,96,98,99,100,101,102,104,105,109,112,115,118,123,124,125,127,129,133,135,139,140,148,149,150,152,158,160,161,162,168,169,171,174,178,180,182,185,186,191,193,194,196,198,200,201,203,204,208,210,218,219,221,222,225,226,229,230,234,241,244,249,252,253,256,258,260,265,266,267,273,277,281,287,293,294,297,302,303,304,305,308,309,311,313,314,315,317,318,320,321,328,330,333,339,342,348,351,352,353,354,355,358,359,360,364,365,368,369,374,376,377,380,381,384,385,386,388,389,391,392,400,401,403,406,407,409,410,411,413,415,417,419,422,423,427,431,434,435,437,439,440,442,446,447,448,449,451,453,457,460,465,469,471,475,476,477],otkidach:473,oudkerk:[293,476],our:[26,30,73,77,79,88,91,99,101,102,104,105,158,168,193,236,251,303,333,358,361,365,423,429,451,472,475,476],our_dispatch:219,ourselv:79,oussoren:[475,476,477],ousterhout:396,out:[16,20,26,29,30,33,34,49,52,53,62,63,64,66,67,70,72,73,76,77,79,81,82,83,84,86,88,89,90,91,93,96,98,99,100,101,102,104,105,106,107,108,121,123,125,126,127,128,129,134,150,152,162,167,168,169,170,174,178,180,186,192,194,200,205,206,207,212,215,216,222,226,230,238,240,244,255,256,260,264,265,282,293,303,304,306,309,311,312,316,317,322,325,327,328,333,336,337,338,345,348,351,360,361,364,365,369,380,388,391,392,396,400,405,407,416,423,426,433,434,437,438,439,440,441,447,449,450,451,452,453,454,457,458,459,460,461,467,470,471,472,473,474,475,476,477],out_fil:414,out_test:129,outbound:102,outcom:[63,90,151,222,277,302,407,442,453],outdat:[83,100,395,476],outer:[9,88,90,106,160,178,182,193,202,240,253,380,439,441,451,454],outermost:[253,391,442,451],outfil:[87,88,123,283,303,313,399,463],outfp:197,outlin:[43,63,98,114,161,365,403],outlinewidth:403,outliv:8,outlookmailbox:88,output:[4,14,16,21,50,52,55,56,60,63,64,71,77,79,81,90,91,93,94,96,98,101,102,104,106,107,109,110,118,123,126,127,129,131,132,135,136,140,141,142,143,144,145,148,149,150,152,155,156,158,161,167,168,169,174,179,180,182,186,193,194,197,199,203,204,210,216,221,222,227,228,231,236,237,238,239,240,241,242,244,245,246,252,256,258,259,260,265,267,270,277,280,282,283,285,288,293,299,303,304,306,308,311,312,313,314,315,317,318,321,322,323,327,328,331,336,338,343,345,346,351,354,356,358,360,361,365,368,369,370,372,374,376,377,380,383,384,385,387,388,389,392,398,399,400,407,409,414,415,416,417,418,423,427,429,433,435,437,440,446,447,449,453,455,456,460,461,465,470,471,472,473,474,475,476,477],output_charset:[194,200,201,230,477],output_codec:194,output_differ:186,output_dir:[63,435],output_fil:[63,322],output_filenam:63,output_libnam:63,output_prognam:63,outputcheck:[60,179,474],outputdata:129,outputstr:161,outputtyp:370,outrat:129,outright:194,outset:476,outsid:[34,41,56,63,66,88,96,98,99,101,102,106,140,150,168,169,174,178,191,200,206,222,245,260,311,327,328,338,343,368,384,388,391,392,393,401,403,429,435,438,440,442,446,447,451,473,474,477],outstand:293,outward:178,over:[19,20,25,28,30,31,37,43,51,60,62,67,77,81,83,86,87,90,93,94,95,96,98,100,101,102,104,108,123,124,126,129,134,137,143,145,152,157,160,162,167,168,169,174,175,178,180,186,199,200,211,216,221,222,226,230,236,238,245,246,249,252,253,256,258,265,266,267,273,281,293,304,311,312,317,318,319,320,322,332,333,336,337,348,352,358,364,365,368,369,374,380,384,386,393,394,395,396,398,399,401,407,414,416,418,423,425,426,429,434,437,439,440,442,446,447,450,451,452,453,455,457,463,470,471,472,473,474,475,476,477],overal:[100,106,167,236,266,303,322,333,477],overcom:[90,139,384,391],overflow:[4,20,29,30,34,81,129,168,174,178,205,216,277,293,368,380,440,474,476,477],overflow_except:16,overflowerror:[20,34,41,149,151,174,186,206,260,277,308,368,392,440,442,461,472,473,476,477],overflowwarn:474,overhaul:386,overhead:[28,30,69,79,88,89,102,238,258,322,364,366,368,380,393,418,440,470,471,472,473,475],overkil:303,overlai:169,overlap:[56,93,101,152,169,180,222,291,303,332,333,368,369,447,471,472],overli:[96,338,472],overload:[55,409,434,440,442,471,472],overmar:212,overrid:[19,30,55,63,66,72,94,98,99,105,107,114,116,123,132,133,134,148,149,152,158,161,162,163,167,168,174,186,191,206,210,219,222,223,227,230,240,246,256,260,265,267,270,274,292,293,298,303,304,311,328,332,338,339,348,351,357,361,368,369,391,403,407,409,410,413,415,416,418,419,423,429,433,435,440,441,451,458,465,470,473,476,477],overridden:[63,68,72,79,81,88,94,99,107,114,123,126,127,132,134,148,161,162,174,219,222,230,239,240,265,267,279,292,303,309,327,342,348,353,357,361,368,384,391,401,407,410,413,416,423,440,454,476,477],overrod:470,overrun:[231,472,477],oversight:477,overview:[27,60,69,78,81,102,104,106,120,166,254,255,280,285,286,303,322,329,362,395,408,425,457,469,470,471,472,473,475,476,477],overwhelm:[91,303],overwrit:[30,77,81,98,109,152,169,193,200,265,334,350,368,384,410,440,452,468,473,476,477],overwritten:[73,99,107,162,273,293,322,352,380,477],own:[4,6,20,21,24,28,30,50,51,52,55,56,60,62,63,64,66,70,72,73,76,77,80,81,83,87,88,90,91,93,95,96,98,99,100,105,107,108,109,120,123,126,127,143,150,158,160,162,163,167,178,186,187,193,202,204,222,230,244,256,265,266,267,273,284,292,293,296,303,304,309,322,332,333,352,360,364,365,368,369,370,374,380,388,389,391,396,403,407,409,412,413,418,419,423,426,429,431,434,437,438,440,442,446,451,452,454,458,461,465,467,468,470,471,472,473,474,475,476,477],owned_file_handl:99,owner:[30,71,73,77,99,142,152,293,304,352,366,384,438,440,463],ownership:[30,60,99,106,293,296,391,476],p263:104,p_cs_preced:264,p_detach:304,p_nowait:[304,374],p_nowaito:304,p_overlai:304,p_sep_by_spac:264,p_sign_posn:264,p_wait:[304,374],paalasma:472,pablo:477,pace:[83,471,476],pacif:174,pack:[60,99,115,116,117,124,129,135,168,207,222,234,245,252,266,273,284,315,344,360,372,396,401,424,437,440,451,453,462,463,475,477],pack_arrai:424,pack_bool:424,pack_byt:424,pack_doubl:424,pack_enum:424,pack_farrai:424,pack_float:424,pack_fopaqu:424,pack_fstr:424,pack_hyp:424,pack_int:424,pack_into:[222,373,475],pack_item:424,pack_list:424,pack_opaqu:424,pack_str:424,pack_typ:424,pack_uhyp:424,pack_uint:424,packag:[13,26,55,56,60,62,66,68,69,70,73,75,78,80,82,83,88,89,90,94,98,99,106,107,109,115,116,117,141,168,169,179,184,186,193,194,195,196,198,199,200,201,202,204,205,222,230,241,249,250,251,252,253,265,266,267,269,270,275,280,281,282,283,288,289,290,292,293,295,308,315,326,327,339,342,350,356,358,360,365,368,380,394,395,396,399,407,409,410,412,427,430,435,436,438,447,449,456,458,462,464,465,466,468,469,470,472,474,477,478],package_data:[72,73],package_dir:[63,67,72],package_test:407,packagenam:75,packard:[86,470],packed_ip:360,packer:[60,209,395],packet:[129,241,267,355,361,434,477],packev:[116,284],packmail:470,pad:[60,87,131,138,146,169,174,178,234,337,368,369,373,376,396,401,424,457,470,473,476,477],padi:396,padnon:258,padx:396,pag:176,page:[0,1,16,60,63,71,72,74,83,84,87,88,89,93,96,99,102,105,106,107,119,123,140,142,150,160,165,169,180,207,222,231,244,252,255,256,265,266,267,273,287,304,307,316,320,327,328,336,337,338,345,353,355,360,364,366,367,377,382,387,390,391,394,396,408,409,410,419,423,429,435,437,438,445,451,460,462,464,470,472,474,475,476,477],pager:[159,309,327],pages:287,pagin:327,pai:[88,99,101,186],paid:470,pain:[101,264,470,475],painless:107,paint:[93,169,403,472],painter:169,pair:[4,19,24,28,35,55,56,60,63,68,72,77,79,83,88,90,93,96,101,123,127,129,134,143,147,152,157,158,161,169,175,180,182,186,192,198,200,203,216,218,222,226,228,230,231,236,239,240,251,253,260,273,277,293,294,299,304,305,309,323,336,339,345,348,360,361,365,368,372,374,381,384,385,388,391,394,396,401,403,407,409,410,411,418,423,426,429,432,440,442,446,447,452,453,471,472,473,474,476,477],pair_cont:169,pair_numb:169,pairwis:258,palin:452,palkovski:473,palmo:150,palomar:230,pan:240,panama:429,pane:[244,326,394,401],panedwindow:[394,401],panel:[60,64,86,120,169,252,396,409,422,471],panelpars:476,panic:[87,267,473],pao:369,paper:[79,104,123,360,407,473],papert:403,paradigm:[80,96],paradox:[88,473],paragraph:[98,187,215,244,260,303,304,365,368,389,429,438,440,452,463,470,473],parallel:[60,63,87,90,96,104,106,222,258,293,407,417,419,463,470,477],param:[99,125,200,203,241,290,292,355,409,411,434,477],paramet:[3,4,6,8,9,10,13,14,19,20,23,24,25,27,30,32,34,38,43,49,50,51,53,55,56,58,59,60,63,78,79,81,82,90,92,96,98,99,101,104,109,113,116,117,118,120,123,127,129,132,133,134,136,137,139,140,141,142,143,148,150,152,156,158,162,164,169,174,175,178,180,182,186,187,191,192,193,196,200,201,203,207,208,209,210,214,217,219,221,222,228,229,230,231,235,240,241,243,244,245,247,252,256,258,260,263,264,265,266,267,269,270,271,273,274,277,280,281,282,284,287,290,291,293,297,299,303,306,308,309,311,315,317,318,321,325,326,328,329,330,332,333,334,336,337,339,343,346,348,350,351,352,355,358,360,361,364,365,368,369,370,371,374,376,377,379,382,384,385,386,388,392,393,394,395,398,399,403,407,409,410,411,413,416,417,418,419,422,423,426,427,428,430,431,433,434,435,437,439,440,441,442,443,447,452,453,458,470,471,472,473,474,475,476,477],parameter:[169,186,364],parameter_list:[439,442],parameteris:99,parameterless:[345,380,451],parametr:104,paramflag:168,paramount:178,paranoid:79,parcel:[396,401],pardir:[208,304],paren:[88,109,167,244,475],parenmatch:244,parent:[30,55,60,63,87,88,98,99,102,117,120,125,169,219,222,236,246,251,256,265,287,290,293,304,305,308,314,317,318,323,328,352,361,365,374,380,401,410,426,429,440,447,451,461,472,473,474,475,476],parent_conn:293,parent_pars:123,parenth_form:442,parenthes:[4,60,72,77,82,90,96,101,132,149,182,246,249,264,315,322,333,368,440,445,446,447,451,452,453,454,458,460,470,474,475,476,477],parenthesi:[95,101,109,244,333,474],parenthesis:368,parentnod:426,pareto:332,paretovari:332,parg:76,pari:[96,101],pariti:100,park:333,parnassu:471,parrot:[77,222,321,452,476],pars:[6,27,57,58,60,63,71,77,81,82,83,88,90,91,95,99,101,107,109,120,125,126,132,142,143,148,149,151,157,158,161,162,167,174,186,192,193,196,200,201,203,209,220,222,228,230,239,240,241,243,246,249,252,254,262,266,273,275,279,281,292,295,296,304,333,338,341,348,354,364,369,374,381,392,396,405,409,416,423,425,426,427,428,430,431,432,433,434,442,443,447,448,454,457,461,462,464,465,470,471,472,473,474,475,476,478],parse_and_bind:[334,340,458],parse_arg:[60,91,120,180,193,228,303,473,477],parse_colnam:364,parse_config_h:381,parse_const:260,parse_decltyp:364,parse_float:260,parse_head:[126,143],parse_int:260,parse_known_arg:123,parse_multipart:143,parse_q:[143,409,411,476],parse_qsl:[143,409,411,476],parseabl:[99,315,351],parseaddr:[203,339],parsed:[203,339],parsedate_tz:[203,339],parseerror:477,parsefil:[157,328],parseflag:246,parsefram:142,parser:[30,60,63,72,77,81,82,91,96,101,104,120,125,149,151,157,167,180,186,192,193,196,197,200,201,206,209,221,252,260,262,266,268,275,295,309,316,333,338,347,351,368,397,425,426,427,428,429,431,433,443,446,447,448,452,454,458,460,465,470,471,473,474,475,477],parser_a:123,parser_b:123,parser_bar:123,parser_class:123,parser_foo:123,parser_list:430,parsercr:328,parsererror:[308,425],parseresult:[411,477],parsermodul:443,parsesequ:279,parsestr:[192,193,196,202,427,428,430,470],parsetok:82,parseurl:243,parsingerror:158,part1:193,part2:193,part:[14,17,20,28,34,50,51,53,55,58,60,62,63,64,69,72,73,76,77,78,79,81,83,84,88,90,93,96,98,99,100,101,102,103,104,105,106,107,108,110,111,114,125,126,131,134,141,143,147,149,150,151,168,169,178,186,191,192,193,197,198,199,200,203,204,212,219,222,225,230,231,244,245,246,252,253,255,256,265,277,280,281,282,283,290,291,293,295,304,305,308,311,314,321,322,328,331,332,333,338,339,340,351,356,360,361,364,365,368,369,371,380,392,394,395,396,400,403,407,409,410,411,418,419,426,427,429,434,437,438,439,440,441,446,447,451,452,453,454,455,456,458,460,461,464,465,466,467,470,471,472,473,474,475,476,477],partak:451,parti:[26,28,63,68,69,70,78,81,83,86,87,88,90,95,106,107,108,139,168,174,222,265,333,365,368,380,381,407,410,438,456,467,469,470,471,473,474,476,477],partial:[0,21,60,88,96,104,105,120,126,141,169,202,246,252,258,267,275,277,301,314,336,342,346,361,368,374,425,470,473,474,476,477,478],partial_cont:241,particip:[3,55,79,162,174,236,265,333,470,472,475,477],particular:[28,30,52,55,58,63,66,67,68,70,71,77,79,81,82,83,88,89,90,94,96,98,99,104,105,106,107,108,114,123,128,138,142,143,150,152,157,160,162,167,169,173,174,184,186,206,212,216,225,231,240,244,246,249,251,253,255,260,261,265,266,273,276,277,279,281,293,299,303,304,314,317,320,333,336,337,339,341,345,352,353,355,358,360,365,366,368,373,374,380,389,390,391,394,396,401,407,409,411,416,426,427,429,437,438,439,440,442,445,446,447,451,455,457,461,470,471,472,473,474,475,476,477],particularli:[62,63,76,81,88,101,105,107,123,293,303,304,309,322,361,381,407,440,457,460,464,470,471,473,474,477],partit:[137,271,332,368,475],partli:106,partnam:251,partner:127,partnership:438,partnum:152,pascal:[81,83,88,96,243,373,439,451,452,453,460,473,477],pass:[3,4,6,8,11,13,15,17,20,24,28,30,31,41,43,45,50,51,55,58,60,63,64,71,72,75,76,77,79,80,81,82,87,90,92,93,94,95,98,100,101,102,104,105,107,108,109,111,113,117,119,120,123,124,125,127,128,129,132,134,135,138,140,142,143,148,149,150,152,156,157,158,159,160,161,162,163,167,169,170,174,180,182,185,186,191,192,195,197,198,199,200,201,202,203,204,206,207,210,215,216,217,219,221,222,227,230,234,235,236,237,238,239,240,241,243,244,245,246,247,249,251,253,256,258,259,260,264,265,266,267,273,274,278,282,284,287,288,290,293,299,303,304,305,306,308,309,311,317,318,319,321,322,328,331,332,333,334,335,336,338,339,343,348,349,350,351,352,353,355,357,358,360,361,364,365,368,369,370,371,373,374,377,379,380,381,385,386,388,391,392,393,394,396,398,399,400,402,403,405,407,409,410,411,416,417,418,419,423,426,427,429,430,431,432,433,434,435,437,439,440,441,442,443,444,446,448,451,453,454,456,457,458,460,461,465,470,471,472,473,474,475,476,477],pass_:318,pass_stmt:[443,447],passag:396,passion:453,passiv:[127,221,471],passwd:[104,167,221,263,324,387,410,474,475,476],password:[60,71,83,105,120,233,235,246,252,267,293,296,299,305,318,358,365,385,387,408,409,410,411,434,435,475,476,477],password_mgr:[105,410],past:[36,83,90,99,106,107,123,135,141,186,238,244,304,311,322,328,369,392,400,423,437,462],pasv:221,pat1:73,pat2:73,pat:101,patch:[1,72,81,87,91,93,101,123,241,338,425,468,470,471,472,473,474,475,476,477],patchcheck:476,patchlevel:[315,380],path1:305,path2:305,path:[26,28,30,52,60,62,63,64,68,70,71,72,76,77,83,87,88,89,95,96,98,99,104,106,108,110,113,123,127,132,134,141,143,144,156,157,158,161,162,168,175,181,186,191,193,204,206,211,213,214,222,230,232,244,249,252,253,256,263,264,266,273,279,288,290,293,299,303,304,309,314,316,322,326,327,329,334,338,342,351,352,354,355,356,358,364,365,366,374,380,382,384,386,388,392,396,403,405,407,409,410,411,419,423,429,434,435,436,440,447,449,451,456,458,459,463,465,466,467,469,470,472,473,474,475,476,477],path_hook:[26,249,314,380,447,461,473],path_importer_cach:[26,249,314,380,447,461,473],path_info:423,path_item:314,path_return_ok:162,path_str:249,pathconf:304,pathconf_nam:304,pathext:89,pathnam:[26,60,63,72,81,87,143,168,191,211,214,221,227,249,251,252,256,265,267,269,271,272,279,288,290,304,319,351,365,366,380,384,386,394,396,409,414,435,436,440,465],pathname2url:409,patholog:[88,455],pathorfil:316,pathsep:[304,356,399,419,465],pathto:83,patienc:[88,293],patrick:476,pattern:[30,60,72,73,79,88,94,98,99,103,106,134,141,152,157,170,180,211,212,246,252,258,277,290,292,293,303,309,322,330,333,352,369,396,403,407,418,439,440,446,456,461,471,473,474,475,476,477],paul:[87,328,469,470,471,472,473,475,476,477],paus:[93,96,142,169,306,353,442,474,475],pax:[384,476],pax_format:[384,476],pax_head:384,paygrad:152,payload:[150,192,193,195,196,197,199,200,201,202,477],payment:105,payment_requir:241,pbkdf2_hmac:[235,477],pbm:248,pbzip2:139,pcall:322,pcall_al:28,pcall_bound_method:28,pcall_cfunct:28,pcall_fast_funct:28,pcall_faster_funct:28,pcall_funct:28,pcall_gener:28,pcall_method:28,pcall_oth:28,pcall_pop:28,pcall_typ:28,pcbuild:[64,388,469,476],pck:83,pcm:306,pcode:219,pctp:474,pdb:[60,88,134,177,186,252,380,473,475,476],pdbrc:309,pdf:[83,98,104,235,259,332,380],pdict:143,pdq:410,pdt:174,peac:403,peach:180,peak:[129,464,475],pear:[152,302,453,462],peculiar:[37,66,88,253,304,451],pedro:476,pedroni:[473,475],peek:[152,256],peel_banana:63,peephol:[474,475],peer:[102,205,357,365],pelleti:472,pem:[221,246,318,358,365],pem_cert_str:365,pem_cert_to_der_cert:365,pen:[60,395],penalti:[88,208,319,470],pencolor:403,pend:[22,28,29,34,79,90,152,215,236,256,258,273,290,318,343,345,377,437,447],pendict:403,pendingdeprecationwarn:[20,206,416,461,473,476,477],pendown:403,penguin:[230,439],pennebak:259,penros:403,pensiz:403,penstat:403,pentium:[380,474],penultim:88,penup:403,peopl:[0,30,81,89,90,95,96,100,101,104,106,107,169,178,180,186,230,303,364,429,442,451,455,470,471,472,473,474,475,476,477],pep:[58,60,62,69,81,83,88,89,90,92,96,104,106,111,114,152,160,167,192,204,222,249,263,265,300,311,314,342,352,356,364,365,368,369,374,380,391,418,423,436,439,440,442,443,447,452,465,468,469,470,478],pepper:364,per:[6,20,26,28,30,60,63,73,83,87,88,95,99,107,108,118,119,123,129,134,135,140,150,152,157,169,174,182,200,203,216,221,245,247,259,265,273,290,293,299,306,318,322,331,333,339,356,357,361,364,365,377,391,392,393,396,399,401,407,434,447,455,461,463,465,473,474,475,477,478],percal:[238,322],perceiv:[81,273],percent:[87,369,397,409,411,463,469,476],percentag:[322,369,476],percentequ:397,percol:236,perfect:[28,88,123,162,247,365],perfect_squar:123,perfectli:[63,96,102,143,192,303,338,442],perform:[15,17,20,28,29,30,37,52,53,55,57,60,68,69,75,76,79,81,84,90,91,92,93,96,98,99,104,106,107,109,113,120,123,126,127,132,135,139,150,156,158,160,162,167,169,173,174,177,178,182,186,201,203,206,207,214,215,221,222,236,241,246,248,252,258,259,260,264,265,266,267,271,274,276,293,299,302,304,308,311,312,318,319,322,328,331,333,335,337,338,339,346,350,353,355,356,360,361,364,365,368,369,373,374,380,386,391,393,396,403,407,409,410,418,431,432,434,435,438,440,442,446,447,450,451,455,456,457,460,461,463,465,470,471,472,473,474,475,476,477],perhap:[28,55,76,77,79,82,83,86,87,95,98,101,102,105,106,107,143,147,162,169,181,186,210,256,264,304,311,315,356,360,427,440,442,450,451,452,454,459,470,471,472,474,475,476],peril:455,perimet:222,period:[28,64,81,98,143,169,174,178,214,265,267,293,305,332,340,341,355,360,361,365,380,389,396,401,442,446,452,470,473,474,475,476,477],perl:[63,81,84,90,96,101,103,162,333,450,455,463,470,474,475],perm:446,perman:[77,105,107,221,246,410,463,469],permiss:[55,61,62,63,72,83,84,88,90,95,98,99,105,106,107,113,156,175,205,208,221,246,296,304,305,325,337,352,366,384,386,409,414,438,449,477],permit:[8,77,92,132,133,142,178,204,205,260,273,322,333,355,374,426,434,438,440,465,475,476],permitscontrol:345,permut:[87,258,332,437,446,470,476],perpendicular:403,perrdetail:82,perrin:474,perror:[206,345],persid:311,persist:[60,121,132,188,244,252,266,276,290,311,364,413,438],persistent_id:311,persistent_load:311,perslist:470,person:[64,96,101,104,107,364,365,438,470,472,476],persona:470,perspect:[423,447],persuad:81,pertain:[1,28,30,55,77,142,256,304,336,380,394,438],pertin:[1,213,265,343],perturb:165,pervad:451,pet:403,peter:[230,393,438,470,471,472,473,474,475,476],peterson:[92,476,477],petrosyan:476,pexpect:87,pexport:107,pformat:321,pfunc:76,pgid:304,pgm:[248,396],pgo:476,pgrp:304,pgsize:138,phase:[62,106,108,147,157,365,401,412,447,476],phaseit:87,phenomenon:81,phi:147,phil:[101,435,436,476],philbrick:77,philip:477,philipp:475,phillip:[475,476],philosophi:[90,462],phoenix:96,phone:[457,463],phonebook:[60,372],photo:[450,463],photofil:463,photoimag:396,php:[106,434,470,472],phrase:[241,246,274,303,442,445,446,473,476],physic:[60,63,93,113,169,186,215,244,287,290,305,339,376,398,460,475],physicist:333,pick:[79,88,90,105,107,129,132,152,231,277,303,391,407,470,475],pickabl:293,picker:153,pickl:[55,60,83,87,98,99,138,152,161,163,168,174,178,192,252,260,262,265,266,267,276,293,308,310,316,346,350,457,474,475,476,477,478],picklabl:[293,311],pickle2db:[83,473],pickle_c:164,pickleerror:311,pickler:[311,312],picklestr:[311,312],pickletool:[60,252,262,476],picklingerror:311,picnam:403,pictur:[77,193,245,259,403,444,472,474],pid:[89,158,280,287,293,304,317,320,323,360,374,475,477],pid_appnam:290,pid_author:290,pid_charcount:290,pid_codepag:290,pid_com:290,pid_create_dtm:290,pid_keyword:290,pid_lastauthor:290,pid_lastprint:290,pid_lastsave_dtm:290,pid_pagecount:290,pid_revnumb:290,pid_secur:290,pid_subject:290,pid_templ:290,pid_titl:290,pid_wordcount:290,pie:364,piec:[63,76,83,88,90,96,101,102,129,135,143,162,171,180,186,270,294,303,365,430,441,446,451,452,472,475],piecewis:231,pier:[472,473],pietraszek:477,pil:[88,259,405],pilgrim:469,pillai:477,pillow:[70,396,461],pimp:476,pinard:230,ping:[470,471,472,475],pink:403,piotr:477,pip:[60,62,100,183,184,252,467],pipe:[60,90,99,101,102,106,205,252,304,309,317,345,352,353,362,366,374,408,474,476,477],pipe_buf:345,pipe_func:293,pipefil:313,pipelin:[60,252,257,408,470],pipenam:293,piper:101,pipermail:[81,464,471,473],pipx:[204,477],pitfal:[30,101],piti:81,pitrou:[476,477],pixel:[152,213,245,247,259,396,401,403],pixmap:[60,248,259,394],pixmapwrapp:[60,476],pkc:[235,365],pkcs_7_asn:365,pkei:19,pkg:[26,63,66,72,250,314,447,465,468,470,471,475,477],pkg_add:468,pkg_directori:[249,314],pkg_name:288,pkgindex:394,pkginfo:227,pkgtool:[64,70],pkgutil:[60,252,289,468,475,476],pkl:311,pkl_file:311,pkunzip:107,pkzip:[435,436,470],place:[1,20,28,30,33,41,47,50,51,55,63,64,66,71,77,79,80,81,82,86,87,90,92,95,96,98,101,103,105,106,107,109,119,123,125,127,133,143,145,150,152,158,160,162,168,169,174,178,180,181,182,186,192,200,210,212,215,219,222,225,230,235,236,244,249,255,256,260,265,266,267,273,277,287,293,294,302,304,305,308,309,311,314,322,328,330,332,333,338,339,361,365,368,369,381,389,394,396,399,401,403,407,409,410,412,414,423,439,440,442,447,451,452,453,455,457,458,459,460,461,463,464,465,467,470,471,472,473,474,475,476,477],placehold:[94,99,106,107,113,182,230,236,265,267,364,369,380,447,463,475],placement:[77,212,314,396],placer:396,plagu:60,plai:[26,30,60,71,79,90,91,102,142,168,178,252,306,365,377,405,407,421,440,450,451],plain:[4,15,60,72,75,77,81,83,87,88,95,99,105,106,124,140,143,145,150,152,157,193,199,200,201,206,207,222,241,265,276,280,364,366,368,370,371,409,410,423,440,442,446,447,452,463,472],plainli:[377,438],plaintext:[246,348],plan:[72,100,102,111,311,419,470,474,475,476,477],plane:[277,403,446],planet:475,planet_and_moon:403,plase:333,plast:258,plat:[28,63,64,107,469],plat_specif:[63,72],platbas:107,platform:[1,4,16,28,30,50,52,56,57,60,62,63,64,68,70,72,73,75,76,77,79,81,83,87,88,93,99,102,119,120,135,136,139,140,147,150,167,168,174,175,185,186,189,190,205,206,216,222,234,235,244,249,252,254,256,264,267,268,272,273,277,291,304,305,307,314,316,317,322,323,336,338,340,345,352,360,361,362,364,365,366,368,373,374,380,381,384,386,388,390,391,392,393,395,396,407,419,421,422,423,437,442,446,449,455,456,457,461,466,467,469,470,472,473,474,475,476,477,478],platinclud:381,platlib:[107,381],platstdlib:381,playab:142,playback:[142,306,377],player:[60,306,333,347,369,377],playground:403,playsound:422,playtrack:142,playtrackab:142,pleas:[0,1,11,28,30,56,62,71,75,81,83,92,98,100,101,102,105,108,123,143,158,168,191,212,221,226,230,241,264,265,266,267,304,315,333,339,352,357,360,364,365,384,387,403,413,423,438,440,442,443,445,452,454,468,470,471,473,475],pleasant:[87,470,471,475],plenti:[77,102],plist:[60,209,252,274,282,467,476],plist_str:476,plistlib:[60,209,252],plmrptoi:333,plock:304,plone:106,plot:474,ploye:438,plst:316,plu:[3,52,55,63,79,87,93,107,123,131,168,169,170,178,180,244,270,293,303,304,314,318,332,333,351,366,380,391,396,397,409,423,427,442,445,457,472,473,474,475],plug:[88,106,219,313,355,364],plugin:[184,405],plumag:[30,77,452],plural:[230,477],plusequ:397,pmincol:169,pminrow:169,pmodul:76,pname:[76,251],pnext:168,png:[193,240,248,396],pngfile:193,pnum:142,poefsrosr:333,pofsros:333,point3d:152,point:[4,6,15,16,19,20,26,28,29,30,33,34,36,37,41,48,50,51,53,55,56,58,60,69,70,77,80,82,84,87,88,90,93,94,96,98,99,100,101,102,104,106,107,108,114,115,117,119,124,126,127,129,134,137,138,142,146,147,150,152,154,158,160,168,169,174,180,181,182,184,186,200,203,206,218,219,221,222,231,235,236,239,244,249,252,258,260,264,265,267,270,271,273,276,277,278,287,290,293,301,303,304,305,308,309,311,315,322,329,332,333,336,338,345,348,349,351,352,364,365,368,369,371,372,373,374,380,381,386,391,392,394,396,398,400,401,403,404,409,410,419,424,425,427,429,430,434,436,437,439,440,441,442,452,454,456,457,458,460,462,467,470,471,472,473,474,475,476,477],point_arrai:168,pointer:[3,4,6,7,8,11,14,16,17,20,21,26,28,30,34,37,42,43,47,48,50,51,52,53,55,56,60,76,79,81,82,84,88,89,92,118,120,142,169,171,185,212,222,287,293,311,315,320,322,373,376,417,435,440,442,447,451,456,464,472,474,475,476,477],pointfloat:446,pointless:79,poke:[63,303],poker:333,polar:[60,301,476],pole:191,poli:[403,470],polic:333,polici:[37,55,62,63,83,99,108,162,256,338,361,365,412,471,474,477],polish:473,polit:[174,221,470],poll:[60,87,126,127,293,317,353,361,362,365,366,374,474,476],poll_interv:361,pollerr:345,pollhup:345,pollin:345,pollnval:345,pollobj:476,pollout:345,pollpri:345,polo:[476,477],poly1305:365,poly1:403,poly2:403,polygon:403,polymorph:[90,433],polynomi:135,polzin:470,pomran:476,pool:[60,62,77,87,108,152,221,258,362,471,473,476,477],pool_sema:391,poolwork:293,poor:[95,300,304,318,322,333,373,471,472],poorli:[95,318,461],pop3:[60,252,254],pop3_ssl:318,pop:[28,83,87,99,124,126,152,178,182,215,236,244,258,273,292,304,318,346,351,365,368,394,401,407,413,440,446,453,463,472,473,474,475,476],pop_align:215,pop_block:182,pop_font:215,pop_jump_if_fals:182,pop_jump_if_tru:182,pop_margin:215,pop_properti:215,pop_sourc:351,pop_styl:215,pop_task:236,pop_top:182,popen2:[60,87,246,252,257,304,474,476],popen3:[60,87,257,304],popen4:[60,257,304,374],popen:[60,99,143,155,257,276,304,313,315,317,319,345,360,368,380,386,440,474,476],popitem:[152,258,273,339,368,413,440,471,473,477],popleft:[152,258,330,453,463,474],poplib:[60,252,254,462,474],popul:[30,60,63,98,117,120,123,125,202,236,265,332,342,407,416,423,427,429,469,473],popular:[62,64,70,77,81,88,90,95,102,103,106,108,127,180,186,254,273,307,403,445,457,459,462,467,469],popup:[191,244],popup_menu:475,popupextens:191,popupmenu:394,porch:88,port:[50,60,63,81,93,97,99,102,103,105,127,132,162,192,221,224,241,246,255,266,267,293,299,318,327,347,354,357,358,360,361,364,365,385,409,411,423,434,465,471,472,478],port_specifi:162,portabl:[30,57,60,63,72,73,77,79,81,83,84,87,102,104,120,121,138,169,185,197,207,208,211,222,234,248,252,259,264,273,277,287,304,310,311,315,319,320,332,339,350,365,366,384,392,404,419,469,470,473],portableunixmailbox:273,portal:468,portion:[14,63,72,81,90,93,96,101,116,129,135,171,174,178,221,223,265,266,267,273,308,355,360,366,401,407,411,423,426,428,432,434,438,447,470],portugues:150,pos:[19,53,117,118,129,146,178,253,287,292,302,304,312,333,334,376,401,403,417,473,477],pose:[100,470,474],posit:[4,6,10,14,17,20,22,28,31,33,34,41,53,55,56,60,77,79,87,88,90,93,101,102,103,104,117,118,120,123,124,125,128,132,133,134,139,141,142,146,147,148,150,152,154,156,168,169,174,178,182,186,191,206,207,212,219,222,223,236,238,243,249,256,258,264,265,271,277,284,287,291,292,293,302,304,311,312,320,328,330,332,334,339,345,346,352,360,368,369,370,372,374,376,380,384,388,390,391,392,396,398,400,401,403,407,410,415,417,424,426,429,431,439,440,441,442,447,451,452,453,457,458,460,463,470,473,474,476,477],position:[90,212],positional_argu:442,positive_sign:264,posix:[60,62,63,72,87,99,102,107,108,140,168,174,203,252,264,296,303,304,305,313,339,345,351,352,361,374,381,384,386,390,391,392,405,408,438,470,473,474,475,476,477],posix_hom:381,posix_prefix:381,posix_us:381,posixfil:[60,252,408,472,476],posixly_correct:228,posixpath:[305,405],possess:[113,191,368],possibl:[1,2,4,6,16,20,26,28,29,30,37,41,43,55,56,58,63,64,66,68,70,72,76,77,79,81,82,83,84,86,87,89,90,91,93,94,95,96,98,100,101,102,104,106,107,108,109,113,118,123,125,126,128,129,134,135,139,141,143,150,151,158,163,165,167,168,169,172,174,175,178,180,182,186,191,192,194,198,200,201,204,206,210,215,222,223,225,226,232,236,238,244,253,256,258,260,264,265,266,267,269,273,274,276,277,281,284,290,291,292,293,297,300,303,304,306,307,308,309,311,315,316,322,323,328,332,333,334,339,345,346,351,353,354,356,360,364,365,368,369,370,371,377,379,380,382,383,384,385,386,388,389,390,391,392,393,394,396,401,403,407,409,410,411,413,415,416,419,422,423,429,431,432,434,435,436,437,438,439,440,442,445,446,447,448,451,452,453,454,455,457,459,460,461,463,465,470,471,472,473,474,475,476,477],post:[83,96,98,104,105,106,126,131,132,143,144,168,186,187,191,219,238,241,243,267,299,306,309,322,355,380,405,409,410,434,451,464,470,472,476],post_f:472,post_mortem:[186,309,476],postalcod:365,postappnam:243,postcmd:148,postcommand:401,postcondit:472,postcreat:243,poster:299,postfil:129,postfix:81,postgresql:[106,364,475],postloop:148,postpon:[169,440],postprocess:243,pot:230,potenti:[28,30,62,63,96,98,99,100,106,108,158,174,221,222,251,258,265,266,293,304,305,361,365,389,407,425,440,471,472,476],potential_err:102,potential_read:102,potential_writ:102,potlmrpi:333,pound:[169,180,449],pow3:293,pow:[41,88,91,125,222,258,277,293,302,355,368,440,442,461,472],powel:147,power:[60,64,83,84,88,90,91,94,106,129,136,155,157,168,178,222,235,301,303,304,309,311,317,333,360,368,393,439,443,444,451,456,460,462,463,473,474,476,477],powerpc:[306,373,474,475,476],powerset:258,poynton:154,pp165:147,ppc64:381,ppc:[63,141,269,381,467,476],ppercas:406,ppm:[248,394,396],ppo:19,pprint:[60,88,134,173,180,252,309,311,365,463,471],ppt:200,pr1:72,pr2:72,practic:[1,30,60,64,78,79,83,87,92,93,94,96,98,99,100,105,106,123,126,127,150,169,170,178,186,196,221,222,241,273,293,332,348,365,368,392,396,427,434,440,442,451,452,454,457,460,461,471,472,473],pragma:[168,364],pragu:174,prc:474,prcal:140,pre:[30,63,70,72,75,77,82,90,98,99,106,108,116,127,144,157,178,180,182,236,239,256,258,265,266,270,303,342,361,391,400,406,407,410,439,467,469,470,473,474,477],pre_f:472,prealloc:37,preambl:[64,193,200],prebuild:184,prec:[178,463,474,475,476],precari:440,precaut:55,preced:[16,60,63,83,90,94,98,99,101,102,103,146,157,158,167,170,174,180,186,202,215,222,239,253,264,265,266,273,281,322,333,348,355,356,360,368,369,373,374,392,396,401,403,411,426,429,434,437,439,440,441,444,445,446,447,451,454,460,471,472],precis:[12,16,22,60,76,81,83,98,119,150,167,174,206,222,230,231,260,266,267,277,293,301,322,327,332,333,364,368,369,380,392,393,410,424,440,442,445,452,455,463,470,474,475,476,477],preclud:[51,152,300,346,368,413],precmd:148,precompil:[58,465,469],precompos:442,precomput:[60,137,421],precondit:[105,472],precondition_fail:241,pred:258,predat:[100,106,170,180],predecessor:[63,251,473],predeclar:77,predefin:[60,77,88,98,101,109,113,148,150,168,169,244,265,290,369,396,419,429,440,456],predetermin:267,predic:[63,96,253,258,302,429,473,476],predict:[88,111,129,158,222,256,465],preexec_fn:[374,474],prefabr:168,prefac:460,prefer:[30,43,60,72,73,81,88,92,96,99,101,105,106,107,108,113,123,127,155,158,167,169,178,193,215,222,230,235,243,256,258,264,273,277,280,282,283,292,302,303,304,311,315,317,327,338,339,343,346,348,365,367,368,374,380,386,388,389,392,395,401,403,404,409,419,432,440,442,446,447,453,458,460,462,463,467,475,477],preferencekei:191,preferenti:87,prefil:129,prefix:[28,30,56,60,63,64,72,77,81,100,101,102,104,119,120,132,148,151,158,162,167,168,169,178,180,182,212,222,228,230,244,266,267,282,292,304,305,309,314,328,333,352,356,368,369,380,381,386,388,394,396,399,401,407,415,426,429,431,436,437,446,451,460,461,465,468,473,476,477],prefix_char:[60,120],preformat:239,prefposit:231,pregener:477,preinstal:468,prejudic:178,preliminari:471,preloop:148,prematur:[77,98,273],preorder:157,prepar:[6,20,58,60,81,104,105,107,140,149,161,174,230,252,256,267,372,374,380,388,403,407,410,430,433,438,460,461,476],preparatori:265,prepare_input_sourc:433,prepareprotocol:364,prepend:[28,56,63,90,94,99,150,156,170,198,219,223,273,292,303,313,351,377,382,389,429],preprocess:[63,167,411],preprocesserror:63,preprocessor:[20,37,63,66,75,107,351,470,477],prerog:98,prescod:[470,471,472,475],prescrib:[216,448],presenc:[28,30,43,55,70,77,79,90,109,155,162,178,210,222,254,296,303,322,365,368,380,440,454,460,472,473],present:[19,26,28,43,55,60,66,72,77,80,82,83,88,89,92,93,95,96,98,99,100,101,102,103,104,105,106,107,123,125,126,131,133,135,137,138,142,143,145,146,148,150,152,158,162,168,169,178,180,186,191,200,204,206,207,218,222,225,227,235,236,237,241,244,260,265,266,267,273,278,280,281,282,283,292,296,299,303,304,305,308,309,321,322,327,328,331,333,336,337,339,346,349,351,360,365,368,369,380,384,385,388,389,390,391,392,393,394,401,403,407,409,410,411,423,426,427,429,431,434,436,437,439,440,442,446,447,452,454,457,461,470,471,472,473,474,475,476,477],preserv:[30,37,60,77,83,96,101,102,103,109,123,138,167,174,178,180,186,197,200,215,232,240,258,266,303,309,348,351,352,384,395,437,440,442,451,470,471,472,473,475,476,477],preserve_mod:63,preserve_symlink:63,preserve_tim:63,preset:315,press:[82,84,93,99,147,169,191,212,291,293,340,394,401,407,458,477],preston:438,presum:[55,98,152,167,273,293,373,411,472,477],pretend:[63,77,100,102,169,440,451,472],pretend_serv:105,pretti:[60,79,88,91,93,106,107,173,180,194,205,219,252,253,260,267,270,303,309,322,398,427,434,442,457,463,470,471,472,475,476],prettyprint:[60,173],prev:[169,401,454],prevail:[121,176,188,442],prevent:[19,21,28,30,37,60,71,77,79,87,90,93,94,98,101,104,105,142,150,152,168,178,180,182,186,191,201,206,222,237,249,260,273,281,292,293,303,311,314,320,337,338,339,360,365,380,403,407,416,418,425,435,437,440,449,460,461,472,473,475,476,477],preventremov:142,previewproc:191,previou:[8,15,20,21,28,33,37,63,72,73,76,77,79,81,82,87,88,90,91,93,95,96,98,99,101,104,123,134,137,138,143,160,168,169,175,178,180,186,192,206,215,219,230,231,241,244,251,258,303,304,305,309,328,332,333,350,351,353,354,358,360,380,382,389,392,394,399,401,403,407,409,410,416,426,439,440,442,451,453,457,461,470,471,472,473,474,475,476,477],previous:[4,20,28,63,71,73,79,83,88,113,123,132,139,142,150,167,169,192,197,200,201,202,206,222,230,249,258,263,266,267,273,281,291,293,303,316,333,353,364,365,368,391,401,407,438,440,447,460,464,465,470,471,472,473,474,475,476,477],previouss:426,pri:382,price:[106,152,364,460,474,475],primari:[60,79,81,88,90,103,186,192,200,201,210,212,265,281,290,308,311,317,322,360,364,365,369,380,398,418,434,444,447,449,458,459,460,461,463,470,471,473,474,476,477],primarili:[81,88,98,107,129,150,152,167,174,192,201,222,223,256,265,293,297,311,374,407,416,423,427,471,472,474,476,477],prime256v1:365,prime:[88,186,293,392,452,462],primit:[60,79,87,168,169,256,302,311,322,333,362,365,390,391,403,426,461,463],princip:[162,365,368,438,463],principl:[27,30,77,90,178,407,423,453,467],print:[20,30,43,52,55,60,63,72,76,77,79,81,87,88,89,90,91,94,95,96,98,99,101,104,105,106,107,109,111,113,120,121,124,125,127,128,134,135,138,140,143,148,149,151,152,156,157,158,159,160,161,164,167,168,169,174,175,176,178,180,182,186,193,197,198,199,200,206,208,214,215,221,222,223,224,225,226,228,229,230,240,241,244,246,252,255,256,260,265,269,270,271,273,276,279,287,288,291,293,299,304,307,309,311,313,316,317,318,321,322,327,328,329,333,334,335,340,343,345,346,351,352,353,354,355,356,357,358,360,361,364,365,366,368,369,370,374,377,380,383,384,385,388,389,390,391,393,394,396,398,399,401,403,407,409,410,414,416,418,423,424,427,429,432,433,434,435,439,440,441,442,443,444,446,449,451,452,453,454,455,457,458,459,460,461,462,463,465,470,471,472,473,474,475,477,478],print_assign:96,print_cal:322,print_calle:322,print_cont:396,print_diff_fil:208,print_directori:143,print_environ:143,print_environ_usag:143,print_error:82,print_exc:[393,400],print_except:[265,267,400],print_expr:182,print_form:143,print_funct:[100,109,111,222,224,447,476],print_help:[123,180,193,303],print_it:396,print_item:182,print_item_to:182,print_last:400,print_newlin:182,print_newline_to:182,print_some_tim:343,print_stack:400,print_stat:[238,322],print_stmt:[443,447],print_tb:400,print_tim:343,print_usag:[123,303],print_vers:303,printabl:[60,88,135,150,167,169,170,194,195,198,200,221,222,224,243,252,280,283,291,295,296,311,369,371,471],printabletyp:476,printdir:435,printdocu:93,printer:[60,101,113,173,213,244,252,396,398,463],printermatch:213,printf:[16,50,56,76,77,79,132,168,475],printfunc:[55,79],printnl:157,printout:322,prior:[4,19,21,28,49,60,72,81,89,103,111,131,144,178,186,222,225,260,265,296,311,313,322,332,351,355,360,365,373,380,382,384,400,407,413,435,438,440,446,455],priori:66,prioriti:[60,94,103,173,192,207,255,260,267,330,343,345,368,382,391,394,442,453,463,472,473,476],priority_numb:330,priorityqu:473,priorityqueu:[330,476],pristin:107,privaci:[71,88,365,412,415],privat:[37,60,88,96,168,180,186,192,221,244,246,287,293,318,358,365,371,388,438,442,446,456,461,471,472,473,476],privileg:[107,113,143,299,304,337,360,363,366,451],prize:332,prmonth:140,prn:72,prng:365,prngd:365,pro:[333,469],probabilist:322,probabl:[3,26,28,30,49,63,64,66,67,70,72,77,79,81,82,83,84,87,88,89,91,93,95,99,100,101,102,104,106,107,113,127,150,151,161,168,174,186,206,219,230,236,245,273,293,304,309,312,315,322,332,338,358,360,361,364,365,393,405,409,415,422,423,431,443,445,451,454,464,465,470,471,472,473,475,476],problem:[1,4,6,20,28,30,52,55,60,62,71,72,77,79,81,82,83,87,88,89,92,93,95,96,98,99,100,102,104,108,119,127,129,141,144,145,150,151,157,158,163,167,174,178,186,192,196,200,202,221,222,230,244,249,252,254,260,264,265,266,284,293,303,304,308,311,322,328,360,364,365,368,383,384,389,394,407,410,418,426,439,449,450,453,454,455,457,460,462,463,464,470,471,472,473,474,475,476,477],problemat:[13,92,266,474],proc0:238,proc7:238,proc:[181,240],proce:[4,66,76,79,152,178,194,258,273,293,322,360,365,386,391,439,442,447,451],procedur:[37,60,63,76,83,96,124,143,150,168,222,322,358,371,403,434,447,452,462,471,472,475],proceed:[83,91,105,394],process:[1,4,20,27,30,51,55,57,58,60,62,64,66,67,69,72,73,76,77,79,80,81,82,83,87,89,90,93,95,96,98,101,102,104,105,106,107,108,109,113,120,123,125,126,127,139,140,143,148,150,155,167,168,169,174,175,186,193,204,205,206,209,210,216,219,222,228,230,238,239,240,241,243,244,246,249,251,252,257,258,264,265,266,267,269,271,273,276,284,287,289,292,295,299,303,306,308,311,317,322,323,328,330,331,333,336,338,342,345,348,352,353,356,358,361,362,364,366,368,371,374,377,380,382,383,384,385,386,390,393,398,399,400,404,407,409,410,416,418,419,423,426,427,429,431,432,434,437,438,439,440,442,446,452,454,457,459,462,465,468,469,471,472,473,474,475,477,478],process_lin:222,process_messag:357,process_request:361,process_token:383,processerror:293,processfil:227,processfile_fromresourc:227,processing_instruction_nod:[426,427],processinginstruct:[60,275,429,431,475],processinginstructionhandl:328,processnam:[265,293],processor:[0,30,63,72,77,81,82,90,104,127,216,293,299,303,304,306,315,328,336,338,373,392,410,425,431,440,470,474,475],procur:438,prod:258,produc:[4,19,30,34,43,52,55,62,75,79,80,83,88,90,93,95,96,98,99,101,102,104,106,107,123,126,139,143,150,152,156,167,169,174,178,179,180,186,192,197,198,200,215,216,221,222,228,230,232,234,236,238,239,243,256,258,260,265,293,299,304,305,308,311,318,322,327,330,332,333,335,339,364,365,368,369,374,380,384,391,396,398,399,403,404,407,409,414,422,423,427,430,431,432,437,438,442,452,460,463,465,470,471,472,473,474,475,476,477],product:[14,66,83,84,87,92,96,98,106,125,157,178,186,236,258,259,267,302,308,338,354,368,380,403,438,442,446,451,461,467,470,471,475,476,477],product_typ:[380,477],productcod:290,productnam:290,productvers:290,prof:238,profession:[86,450,463],professor:333,profici:427,profil:[27,30,60,79,83,88,113,150,252,279,353,365,371,380,391,449,462,467,471,472,474,475,476],profilefunc:380,profit:[83,438],prog:[60,91,120,180,193,303,333],program:[1,4,6,14,15,19,21,26,28,38,39,58,60,63,64,71,72,73,76,77,80,81,84,85,86,90,91,94,95,97,98,99,100,101,105,106,107,108,109,112,113,120,123,127,128,131,133,135,140,142,143,149,150,151,152,157,158,159,160,167,168,174,177,178,185,186,197,206,208,212,221,222,223,225,228,231,234,242,243,244,247,252,253,261,267,268,270,271,273,274,281,291,296,303,304,305,307,309,311,317,319,322,323,327,328,330,332,333,336,338,339,350,353,360,361,362,364,365,368,374,377,380,386,391,393,394,395,399,400,401,403,405,407,412,415,416,418,419,423,426,427,434,435,438,439,440,441,442,444,445,446,447,449,450,451,452,454,456,457,461,463,464,465,466,468,469,470,471,472,473,474,475,476,477],programacion:[138,476],programm:[6,23,27,30,55,72,77,80,81,88,89,90,93,94,98,102,103,104,106,107,113,114,126,128,167,169,174,178,186,191,206,219,222,231,243,252,264,270,273,277,293,303,304,306,346,360,368,380,394,395,396,403,409,412,416,418,439,440,444,447,451,453,454,457,460,469,471,472,474,475,476],programmat:[60,76,81,111,125,177,204,264,266,303,308,323,334,410,416,477],progress:[87,101,143,186,191,192,205,221,222,236,293,300,351,364,365,394,401,413,416,452,470,472,477],progressbar:[60,268,395],prohibit:[186,260,423],project:[0,1,60,63,64,70,73,80,84,88,89,97,99,100,106,107,108,109,174,184,186,204,221,230,231,303,328,407,435,438,445,452,469,470,473,476,477],project_directori:407,prolept:[140,174],promin:107,promis:[72,77,253],promiscu:360,promot:[236,438,452,476],prompt:[58,64,70,71,82,88,89,90,95,107,109,112,123,148,149,153,165,168,186,191,202,212,221,222,229,244,246,309,327,334,358,365,368,374,380,387,400,409,447,449,452,455,458,459,460,461,465,469,473,476],prompt_user_passwd:409,promptli:[160,333,454],prone:[64,81,143,160,186,346,368,413],pronounc:[100,152],proof:[88,96,293,470],prop:231,propag:[20,28,30,31,45,96,98,99,149,152,206,222,238,265,266,293,314,343,368,380,392,407,410,418,439,440,442,447,473,475],proper:[4,6,60,76,79,81,88,106,107,132,147,169,182,194,235,346,360,365,368,373,380,391,407,409,426,429,440,442,458,470],proper_slic:442,properli:[2,3,4,5,6,19,21,24,28,30,33,34,35,36,40,42,43,47,48,49,50,53,54,55,56,77,81,87,88,99,101,102,106,136,155,170,194,197,198,200,202,203,206,230,249,264,276,304,305,322,328,358,365,373,374,384,386,388,391,396,401,407,411,431,447,457,471,472,473,477],properti:[15,51,55,60,81,90,95,96,98,101,103,113,114,115,117,140,152,167,168,169,178,186,194,211,215,222,230,236,253,255,260,264,270,273,290,293,300,316,333,364,368,371,380,386,391,403,404,406,407,426,427,429,430,431,432,438,439,440,447,451,453,461,469,470,472,473,474,475,477],property_declaration_handl:431,property_dom_nod:431,property_lexical_handl:431,property_xml_str:431,propertynam:432,proport:129,propos:[1,30,81,90,146,167,206,256,265,365,374,418,426,440,442,447,470,471,473,474,475,476,477],proprietari:[84,93],prose:186,prospero:411,prot:287,prot_c:221,prot_p:221,prot_read:287,prot_writ:287,protect:[20,28,77,79,119,133,168,169,230,236,246,256,273,287,293,304,321,338,342,351,361,365,366,416,454,465,472,475],proto:[360,410],protocol:[2,6,7,27,48,55,60,81,82,83,87,90,96,102,104,105,106,113,114,126,127,129,132,150,162,167,168,173,174,179,192,203,205,222,252,256,257,260,265,266,267,293,302,304,310,321,350,355,360,361,364,368,371,384,385,396,409,410,423,432,434,436,440,442,451,457,462,470,472,473,475,477,478],protocol_:365,protocol_open:410,protocol_request:410,protocol_respons:410,protocol_sslv23:[221,365],protocol_sslv2:365,protocol_sslv3:365,protocol_tl:365,protocol_tlsv1:365,protocol_tlsv1_1:365,protocol_tlsv1_2:365,protocol_vers:[132,246],protocolerror:[60,254],protocolnam:360,prototyp:[60,75,76,81,120,148,152,178,192,364,470,475,477],provabl:60,prove:[55,90,96,168,365,473],proven:[96,186,473],provid:[1,4,6,8,14,16,20,24,26,28,30,32,35,37,38,39,41,43,47,51,56,60,62,63,64,65,66,67,68,69,71,72,75,76,78,81,82,83,84,87,88,90,91,92,93,94,95,96,99,100,101,103,104,105,106,107,108,110,113,114,115,116,118,119,120,121,122,123,125,126,127,128,129,130,131,132,133,137,138,139,140,141,142,143,145,146,147,148,149,150,151,152,153,155,156,157,158,160,161,162,163,164,167,168,169,173,174,175,176,178,180,182,184,186,187,188,189,190,191,192,194,195,197,198,199,200,201,202,203,204,205,206,207,208,210,212,213,214,215,216,218,219,221,222,223,224,225,226,228,229,230,231,233,234,235,236,237,238,239,240,241,242,243,244,246,247,248,249,250,251,252,253,255,256,257,258,259,260,262,264,265,266,267,269,271,273,275,277,278,279,280,281,282,283,284,285,287,288,289,290,291,293,296,297,299,300,301,302,303,304,306,307,308,310,311,312,314,315,316,317,318,319,320,321,322,324,325,326,328,329,330,332,333,334,335,336,337,338,339,341,342,344,345,346,347,348,349,350,351,352,353,355,356,358,359,360,361,362,363,364,365,368,369,370,371,372,374,375,376,377,378,379,380,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,403,405,406,407,408,409,410,411,413,415,416,417,418,419,422,423,424,425,426,427,429,430,431,432,433,434,435,436,438,439,440,442,447,448,449,450,451,453,454,455,460,461,462,463,465,467,468,470,471,472,473,474,475,476,477],provinc:365,provis:[98,365,438],provok:198,proxi:[19,59,60,116,206,222,241,246,357,362,404,407,409,410,418,426,434,438,440,471,476],proxiedtransport:434,proxy_auth_handl:410,proxy_authentication_requir:241,proxy_handl:410,proxy_support:105,proxyauth:246,proxybasicauthhandl:[60,254],proxydigestauthhandl:[60,254],proxyhandl:[60,105,254,409],proxytyp:[293,418],prstr:213,prune:[73,304],pryear:140,pryor:475,ps1:[58,82,149,338,360,380,449,461,465],ps2:[58,82,149,338,380,449,461,465],pseudo:[55,58,60,87,90,123,252,276,296,301,304,365,368,408,472,473,476],pseudorandom:[235,332],psf:[60,83],psize:245,pslaee:333,pst:174,pstat:[238,322,462,471,475],psyco:[82,88],pt154:150,ptcp154:150,pth:[107,314,356,380,470],pthread:[87,390],pthread_atfork:28,ptime:142,ptr:[6,474],ptraceback:20,ptrptr:55,pty:[60,87,252,304,365,408],ptype:[16,20,315],pub:[221,349,352,468],pubid:429,publicid:[328,426,431],publicli:[83,313,406,438,470],publish:[62,77,101,104,106,108,178,180,183,259,333,341,349,355,364,388,393,396,438,471,477],pull:[77,178,236,345,403,470,474,477],pulldom:[60,252,275,425],puls:99,pumpkin:364,pun:[251,452],punch:386,punctuat:[56,101,104,296,369],punycod:[150,473],puppi:180,purcel:471,purchas:364,pure:[60,64,66,69,70,72,78,84,87,88,94,96,99,100,107,152,168,174,184,212,217,224,244,258,322,332,353,357,382,388,425,451,453,465,472,473,474,475,476,477],purelib:[107,381],pureproxi:[60,254],purg:333,purifi:81,purist:101,puriti:96,purpl:93,purplish:169,purpos:[4,16,28,30,32,37,55,63,72,75,76,77,79,81,83,91,94,98,99,101,103,105,106,111,125,131,147,150,152,157,158,167,168,169,174,178,180,186,192,198,200,201,223,225,230,236,266,276,293,294,303,304,306,308,311,320,322,332,333,340,343,365,369,380,384,391,396,401,404,407,411,413,416,423,426,429,430,438,440,441,442,452,453,458,461,465,470,476,477],purschk:438,push:[63,71,81,88,126,149,169,171,178,182,212,215,236,291,292,311,339,348,351,446,447,452,470,476],push_align:215,push_font:215,push_margin:215,push_properti:215,push_sourc:351,push_styl:215,push_token:351,push_with_produc:126,pushback:351,pushbutton:290,put:[17,30,43,60,63,64,66,67,70,72,73,77,79,81,82,87,89,90,93,95,96,99,101,102,107,120,150,168,182,186,197,206,207,224,230,241,244,266,271,290,293,302,306,311,312,330,338,358,364,365,381,386,389,396,402,420,438,449,452,458,459,460,461,465,468,471,472,473,474,475,476,477],put_nowait:[293,330],putch:291,putchar:169,putenv:[304,319],puthead:[87,241,434],putp:169,putrequest:[87,241,434],putsequ:279,putwch:[291,476],putwin:169,puzzl:[89,475],pvalu:[19,20,76],pvm:87,pw_dir:324,pw_geco:324,pw_gid:324,pw_name:324,pw_passwd:324,pw_shell:324,pw_uid:[99,324],pwd:[60,99,107,165,221,229,233,252,304,305,363,408,435,473],pwlcurv:231,py2:[64,103,333],py2app:467,py2ex:[60,88,89,293,466],py3:[109,333],py3k:[90,100,365],py3k_warn:380,py3kwarn:[380,388,461,476],py_addpendingcal:[28,477],py_atexit:52,py_begin_allow_thread:[4,21,28,77],py_block_thread:28,py_buff:[4,15,60,476],py_buildvalu:[4,30,43,53,60,76,77,79,89,475],py_clear:[45,55,79,92,474],py_cmp_func:168,py_compil:[60,63,88,156,249,252,262,314,338,477],py_compilestr:[58,82],py_compilestringflag:58,py_complex:[4,14,77],py_debug:30,py_decref:[19,20,24,30,31,45,55,76,77,79,82,92],py_dtsf_add_dot_0:16,py_dtsf_alt:16,py_dtsf_sign:16,py_dtst_finit:16,py_dtst_infinit:16,py_dtst_nan:16,py_ellipsi:49,py_enable_shar:381,py_end_allow_thread:[21,28,77],py_end_of_buff:6,py_endinterpret:28,py_enterrecursivecal:20,py_eq:[43,55,56],py_eval_input:[58,82],py_exit:52,py_fals:[5,55,56],py_fatalerror:[16,28,52],py_fdisinteract:52,py_fil:[63,384],py_file_input:[58,82],py_filesystemdefaultencod:56,py_fin:[28,30,52,76,82,477],py_findmethod:[51,79],py_frozen:249,py_g:[43,55,56],py_getbuildinfo:[28,475],py_getcompil:28,py_getcopyright:28,py_getexecprefix:[28,30],py_getpath:[28,30],py_getplatform:28,py_getprefix:[28,30],py_getprogramfullpath:[28,30],py_getprogramnam:28,py_getpythonhom:28,py_getvers:28,py_gt:[43,55,56],py_huge_v:16,py_incref:[30,45,59,77,79,82,89],py_initi:[26,28,30,76,77,82,89],py_initializeex:28,py_initmodul:[3,76,77,82,92],py_initmodule3:[3,79],py_initmodule4:[3,77],py_inspectflag:58,py_interactiveflag:52,py_is_nan:474,py_isalnum:477,py_isalpha:477,py_isdigit:477,py_isiniti:[28,30],py_islow:477,py_isspac:477,py_isupp:477,py_isxdigit:477,py_l:[43,55,56],py_leaverecursivecal:20,py_llong_max:34,py_llong_min:34,py_loc:475,py_local_aggress:475,py_local_inlin:475,py_long_long:[4,29,34],py_lt:[43,55,56],py_main:58,py_major_vers:[92,111,380],py_marshal_vers:36,py_micro_vers:[111,380],py_minor_vers:[111,380],py_modul:[63,67,70,72,73,470],py_n:[43,55,56],py_newinterpret:28,py_non:[3,20,23,28,40,41,49,59,77,89],py_notimpl:[55,56,471],py_object:[168,475],py_optimizeflag:168,py_print_raw:[21,43,55,79],py_py3kwarningflag:[20,476],py_refcnt:[51,476],py_release_level:[111,380],py_release_seri:[111,380],py_return_fals:[5,474],py_return_non:[40,77,474],py_return_tru:[5,474],py_setprogramnam:[28,30,76,77],py_setpythonhom:28,py_single_input:[58,82],py_siz:[51,476],py_sourc:[249,314,338],py_spammodule_h:77,py_ssize_t:[3,4,6,7,16,19,20,24,29,30,33,34,35,36,41,42,43,47,48,49,50,51,53,54,55,56,380,475,476],py_ssize_t_clean:[4,475],py_ssize_t_max:[34,41],py_ssize_t_min:41,py_suffix_import:251,py_tolow:477,py_toupp:477,py_tpflags_basetyp:[55,79],py_tpflags_checktyp:[55,471],py_tpflags_default:[55,79],py_tpflags_gc:[55,472],py_tpflags_have_class:55,py_tpflags_have_gc:[24,54,55,79],py_tpflags_have_getcharbuff:55,py_tpflags_have_inplaceop:55,py_tpflags_have_it:55,py_tpflags_have_richcompar:55,py_tpflags_have_sequence_in:55,py_tpflags_have_version_tag:476,py_tpflags_have_weakref:55,py_tpflags_heaptyp:55,py_tpflags_readi:55,py_trace_ref:[30,51,55],py_tracefunc:28,py_tru:[5,55,56],py_typ:[51,79,476],py_unblock_thread:28,py_unicod:[4,15,20,34,60,124,150],py_unicode_isalnum:56,py_unicode_isalpha:56,py_unicode_isdecim:56,py_unicode_isdigit:56,py_unicode_islinebreak:56,py_unicode_islow:56,py_unicode_isnumer:56,py_unicode_isspac:56,py_unicode_istitl:56,py_unicode_isupp:56,py_unicode_todecim:56,py_unicode_todigit:56,py_unicode_tolow:56,py_unicode_tonumer:56,py_unicode_totitl:56,py_unicode_toupp:56,py_unicode_wid:56,py_vabuildvalu:4,py_version_hex:92,py_visit:[24,55,79,92],py_warn:388,py_xdecref:[30,45,55,76,77,79,82,92],py_xincref:[45,77],pyanyset_check:48,pyanyset_checkexact:48,pyapi_data:473,pyapi_func:473,pyarg_:20,pyarg_noarg:473,pyarg_pars:[4,477],pyarg_parsetupl:[4,6,51,76,77,79,80,82,92,442,470,472,473,475,476],pyarg_parsetupleandkeyword:[4,51,77,79,474],pyarg_unpacktupl:[4,51,472],pyarg_vapars:4,pyarg_vaparsetupleandkeyword:[4,474],pyassem:157,pyast_compil:475,pybaseobject_typ:55,pybench:475,pybool_check:5,pybool_fromlong:5,pybool_typ:5,pybsddb:[83,138,473,476,477],pybuf_any_contigu:6,pybuf_c_contigu:[6,476],pybuf_contig:6,pybuf_contig_ro:6,pybuf_f_contigu:[6,476],pybuf_format:6,pybuf_ful:6,pybuf_full_ro:6,pybuf_indirect:6,pybuf_lock:476,pybuf_nd:6,pybuf_record:6,pybuf_records_ro:6,pybuf_simpl:6,pybuf_strid:6,pybuf_strided_ro:6,pybuf_writ:[6,476],pybuffer_check:6,pybuffer_fillcontiguousstrid:6,pybuffer_fillinfo:6,pybuffer_frommemori:6,pybuffer_fromobject:6,pybuffer_fromreadwritememori:6,pybuffer_fromreadwriteobject:6,pybuffer_iscontigu:6,pybuffer_new:6,pybuffer_releas:[4,6,476],pybuffer_sizefromformat:6,pybuffer_typ:[6,55],pybufferobject:6,pybufferproc:[6,55,79],pybuild:107,pybyt:[50,92],pybytearray_as_str:7,pybytearray_asstr:7,pybytearray_check:7,pybytearray_checkexact:7,pybytearray_concat:7,pybytearray_fromobject:[7,476],pybytearray_fromstringands:[7,476],pybytearray_get_s:7,pybytearray_res:7,pybytearray_s:7,pybytearray_typ:7,pybytearrayobject:7,pybytes_:[50,92],pybytes_check:476,pybytes_fromstr:92,pybytes_fromstringands:476,pybytesobject:476,pyc:[26,69,70,89,90,157,249,276,290,311,338,352,368,380,435,436,461,465,471,473,474,476,477],pycallable_check:[43,76,77],pycalliter_check:32,pycalliter_new:32,pycalliter_typ:32,pycapsul:[8,77,477],pycapsule_checkexact:[8,92],pycapsule_destructor:8,pycapsule_get:8,pycapsule_getcontext:[8,92],pycapsule_getdestructor:[8,92],pycapsule_getnam:[8,92],pycapsule_getpoint:[8,92,477],pycapsule_import:[8,77,92],pycapsule_isvalid:[8,92,477],pycapsule_new:[8,77,92],pycapsule_setcontext:[8,92],pycapsule_setdestructor:[8,92],pycapsule_setnam:[8,92],pycapsule_setpoint:[8,92],pycapsule_typ:92,pycell_check:9,pycell_get:9,pycell_new:9,pycell_set:9,pycell_typ:9,pycellobject:9,pycf_only_ast:[125,475],pycfunct:[51,77,79,92,474],pycfunctionwithkeyword:51,pycharm:88,pycheck:[81,88,475],pyclass_check:10,pyclass_issubclass:10,pyclass_typ:10,pyclassmethod_typ:94,pyclassobject:[10,79],pyclbr:[60,252,262],pycobject:[11,92,477],pycobject_asvoidptr:[11,92,477],pycobject_check:[11,92],pycobject_fromvoidptr:[11,92],pycobject_fromvoidptranddesc:11,pycobject_getdesc:11,pycobject_setpoint:92,pycobject_setvoidptr:11,pycobject_typ:92,pycode_addr2lin:473,pycode_check:12,pycode_getnumfre:12,pycode_new:[12,297,477],pycode_newempti:[12,477],pycode_typ:12,pycodec_backslashreplaceerror:13,pycodec_decod:13,pycodec_encod:13,pycodec_ignoreerror:13,pycodec_incrementaldecod:13,pycodec_incrementalencod:13,pycodec_knownencod:13,pycodec_lookuperror:13,pycodec_regist:13,pycodec_registererror:13,pycodec_replaceerror:13,pycodec_streamread:13,pycodec_streamwrit:13,pycodec_stricterror:13,pycodec_xmlcharrefreplaceerror:13,pycodegen:157,pycodeobject:[12,58,82],pycompileerror:325,pycompilerflag:58,pycomplex_asccomplex:[14,476],pycomplex_check:14,pycomplex_checkexact:14,pycomplex_fromccomplex:14,pycomplex_fromdoubl:14,pycomplex_imagasdoubl:14,pycomplex_realasdoubl:14,pycomplex_typ:14,pycomplexobject:14,pycon:[365,475],pyconfig:[63,77,206,380,381,477],pyd:[60,70,75,87,267,436,475],pydate_check:17,pydate_checkexact:17,pydate_fromd:17,pydate_fromtimestamp:17,pydatetime_check:17,pydatetime_checkexact:17,pydatetime_d:17,pydatetime_date_get_hour:17,pydatetime_date_get_microsecond:17,pydatetime_date_get_minut:17,pydatetime_date_get_second:17,pydatetime_datetim:17,pydatetime_datetimetyp:17,pydatetime_datetyp:17,pydatetime_deltatyp:17,pydatetime_fromdateandtim:17,pydatetime_fromtimestamp:17,pydatetime_get_dai:17,pydatetime_get_month:17,pydatetime_get_year:17,pydatetime_import:17,pydatetime_tim:17,pydatetime_time_get_hour:17,pydatetime_time_get_microsecond:17,pydatetime_time_get_minut:17,pydatetime_time_get_second:17,pydatetime_timetyp:17,pydatetime_tzinfotyp:17,pydatetimeapi:17,pydb:88,pydebug:[30,465,473],pydelta_check:17,pydelta_checkexact:17,pydelta_fromdsu:17,pydescr_isdata:18,pydescr_newclassmethod:18,pydescr_newgetset:18,pydescr_newmemb:18,pydescr_newmethod:18,pydescr_newwrapp:18,pydict_check:[15,19],pydict_checkexact:19,pydict_clear:19,pydict_contain:[19,474],pydict_copi:19,pydict_delitem:19,pydict_delitemstr:19,pydict_getitem:[19,77],pydict_getitemstr:[19,77],pydict_item:19,pydict_kei:19,pydict_merg:19,pydict_mergefromseq2:19,pydict_new:[19,82],pydict_next:19,pydict_s:19,pydict_setitem:[19,77],pydict_setitemstr:[19,82],pydict_typ:19,pydict_upd:19,pydict_valu:19,pydictobject:[19,48],pydictproxy_new:19,pydistutil:[64,107],pydll:168,pydoc:[55,60,79,87,179,187,252,471,472,473,474,477],pydoc_str:79,pyerr_:77,pyerr_badargu:20,pyerr_badinternalcal:20,pyerr_checksign:20,pyerr_clear:[20,30,77],pyerr_exceptionmatch:[20,30,82],pyerr_fetch:[20,79,82],pyerr_format:[20,79,92,477],pyerr_givenexceptionmatch:20,pyerr_newexcept:[20,77,92,475,477],pyerr_newexceptionwithdoc:[20,477],pyerr_nomemori:[20,37,77],pyerr_normalizeexcept:20,pyerr_occur:[8,20,22,29,30,31,43,76,77,79,82],pyerr_print:[20,60,76],pyerr_printex:20,pyerr_restor:[20,79,82],pyerr_set:20,pyerr_setexcfromwindowserr:20,pyerr_setexcfromwindowserrwithfilenam:20,pyerr_setexcfromwindowserrwithfilenameobject:20,pyerr_setfromerrno:[20,77],pyerr_setfromerrnowithfilenam:20,pyerr_setfromerrnowithfilenameobject:20,pyerr_setfromwindowserr:20,pyerr_setfromwindowserrwithfilenam:20,pyerr_setfromwindowserrwithfilenameobject:20,pyerr_setinterrupt:20,pyerr_setnon:20,pyerr_setobject:[20,77],pyerr_setstr:[20,30,77,79,92,477],pyerr_warn:[20,475],pyerr_warnex:[20,416,475],pyerr_warnexplicit:20,pyerr_warnpy3k:20,pyerr_writeunrais:[20,79],pyeval_acquirelock:28,pyeval_acquirethread:28,pyeval_callobject:477,pyeval_evalcod:[58,82],pyeval_evalcodeex:58,pyeval_evalfram:58,pyeval_evalframeex:58,pyeval_getbuiltin:[46,82],pyeval_getcallstat:28,pyeval_getfram:46,pyeval_getfuncdesc:46,pyeval_getfuncnam:46,pyeval_getglob:46,pyeval_getloc:46,pyeval_getrestrict:46,pyeval_initthread:28,pyeval_mergecompilerflag:58,pyeval_reinitthread:28,pyeval_releaselock:28,pyeval_releasethread:28,pyeval_restorethread:28,pyeval_savethread:28,pyeval_setprofil:[28,472],pyeval_settrac:[28,472],pyeval_threadsiniti:[28,474],pyexc_:20,pyexc_arithmeticerror:20,pyexc_assertionerror:20,pyexc_attributeerror:[20,79,92],pyexc_baseexcept:20,pyexc_buffererror:20,pyexc_byteswarn:20,pyexc_deprecationwarn:20,pyexc_environmenterror:20,pyexc_eoferror:20,pyexc_except:20,pyexc_floatingpointerror:20,pyexc_futurewarn:20,pyexc_generatorexit:20,pyexc_importerror:[20,92],pyexc_importwarn:20,pyexc_indentationerror:20,pyexc_indexerror:20,pyexc_ioerror:[20,77],pyexc_keyboardinterrupt:20,pyexc_keyerror:[20,30],pyexc_lookuperror:20,pyexc_memoryerror:20,pyexc_nameerror:20,pyexc_notimplementederror:[20,92],pyexc_oserror:20,pyexc_overflowerror:20,pyexc_pendingdeprecationwarn:20,pyexc_referenceerror:20,pyexc_runtimeerror:[20,79],pyexc_runtimewarn:20,pyexc_standarderror:20,pyexc_stopiter:20,pyexc_syntaxerror:[20,82],pyexc_syntaxwarn:20,pyexc_systemerror:[20,48],pyexc_systemexit:20,pyexc_taberror:20,pyexc_typeerror:[20,77,79],pyexc_unboundlocalerror:20,pyexc_unicodedecodeerror:20,pyexc_unicodeencodeerror:20,pyexc_unicodeerror:20,pyexc_unicodetranslateerror:20,pyexc_unicodewarn:20,pyexc_userwarn:20,pyexc_valueerror:[20,77,477],pyexc_vmserror:20,pyexc_warn:20,pyexc_windowserror:20,pyexc_zerodivisionerror:[20,77],pyexpat:[328,425,438,470,473,475,476,477],pyfile_asfil:21,pyfile_check:21,pyfile_checkexact:21,pyfile_decusecount:[21,476],pyfile_fromfil:21,pyfile_fromstr:21,pyfile_getlin:21,pyfile_incusecount:[21,476],pyfile_nam:21,pyfile_setbufs:21,pyfile_setencod:21,pyfile_setencodinganderror:21,pyfile_softspac:21,pyfile_typ:21,pyfile_writeobject:21,pyfile_writestr:21,pyfileobject:21,pyfloat:22,pyfloat_as_doubl:22,pyfloat_asdoubl:22,pyfloat_asreprstr:22,pyfloat_asstr:22,pyfloat_check:22,pyfloat_checkexact:22,pyfloat_clearfreelist:22,pyfloat_fromdoubl:22,pyfloat_fromstr:22,pyfloat_getinfo:[22,476],pyfloat_getmax:[22,476],pyfloat_getmin:[22,476],pyfloat_typ:22,pyfloatobject:22,pyfltk:84,pyformat_fromstr:477,pyformat_fromstringv:477,pyfp:216,pyfpe_end_protect:216,pyfpe_start_protect:216,pyframe_getlinenumb:[46,477],pyframeobject:[25,28,46,58],pyfrozenset_check:48,pyfrozenset_checkexact:48,pyfrozenset_new:[48,475],pyfrozenset_typ:48,pyfunction_check:23,pyfunction_getclosur:23,pyfunction_getcod:23,pyfunction_getdefault:23,pyfunction_getglob:23,pyfunction_getmodul:23,pyfunction_new:23,pyfunction_setclosur:23,pyfunction_setdefault:23,pyfunction_typ:23,pyfunctionobject:23,pyfunctyp:168,pygam:83,pygc_head_s:472,pygen_check:25,pygen_checkexact:25,pygen_new:25,pygen_typ:25,pygenobject:25,pygetsetdef:[18,51,55,79,253,404],pygettext:230,pygilst:28,pygilstate_:28,pygilstate_ensur:28,pygilstate_getthisthreadst:28,pygilstate_releas:28,pygilstate_st:28,pygtk:[84,307,475],pyhist:334,pyhistori:458,pyhkei:113,pyimport_addmodul:[26,77],pyimport_appendinittab:26,pyimport_cleanup:26,pyimport_execcodemodul:26,pyimport_execcodemoduleex:26,pyimport_extendinittab:26,pyimport_frozenmodul:[26,168],pyimport_getimport:26,pyimport_getmagicnumb:26,pyimport_getmoduledict:26,pyimport_import:[26,76,476],pyimport_importfrozenmodul:26,pyimport_importmodul:[8,26,82,92,471,476],pyimport_importmoduleex:26,pyimport_importmodulelevel:26,pyimport_importmodulenoblock:[8,26,92,476],pyimport_reloadmodul:26,pyindex_check:41,pyinit_myextens:92,pyinstal:293,pyinstance_check:10,pyinstance_new:10,pyinstance_newraw:10,pyinstance_typ:[10,79],pyinstanceobject:79,pyint_:92,pyint_as_long:[19,29],pyint_aslong:[29,30,76],pyint_asssize_t:29,pyint_asunsignedlonglongmask:29,pyint_asunsignedlongmask:29,pyint_check:[29,30],pyint_checkexact:29,pyint_clearfreelist:29,pyint_fromlong:[19,29,30,76,77,79],pyint_fromsize_t:29,pyint_fromssize_t:29,pyint_fromstr:29,pyint_getmax:29,pyint_typ:29,pyinterpreterst:28,pyinterpreterstate_clear:28,pyinterpreterstate_delet:28,pyinterpreterstate_head:[28,472],pyinterpreterstate_new:28,pyinterpreterstate_next:[28,472],pyinterpreterstate_threadhead:[28,472],pyintobject:[29,79],pyiter_check:31,pyiter_next:[31,55],pykde4:84,pylib:475,pylint:[88,100],pylist_append:33,pylist_astupl:33,pylist_check:[30,33,82],pylist_checkexact:33,pylist_get_item:33,pylist_get_s:33,pylist_getitem:[30,33,77,82],pylist_getslic:33,pylist_insert:33,pylist_new:[2,30,33,82],pylist_revers:33,pylist_s:[30,33,475],pylist_set_item:33,pylist_setitem:[30,33,77,82],pylist_setslic:33,pylist_sort:33,pylist_typ:[33,79],pylistobject:[19,33,79],pylists:82,pylon:106,pylong:34,pylong_:92,pylong_asdoubl:34,pylong_aslong:34,pylong_aslongandoverflow:[34,477],pylong_aslonglong:34,pylong_aslonglongandoverflow:[34,477],pylong_asssize_t:34,pylong_asunsignedlong:34,pylong_asunsignedlonglong:34,pylong_asunsignedlonglongmask:34,pylong_asunsignedlongmask:34,pylong_asvoidptr:34,pylong_check:34,pylong_checkexact:34,pylong_fromdoubl:34,pylong_fromlong:[34,77],pylong_fromlonglong:34,pylong_fromsize_t:34,pylong_fromssize_t:34,pylong_fromstr:34,pylong_fromunicod:34,pylong_fromunsignedlong:34,pylong_fromunsignedlonglong:34,pylong_fromvoidptr:34,pylong_typ:34,pylongobject:[29,34],pymalloc:[27,60,471,476,477,478],pymapping_:30,pymapping_check:[35,55],pymapping_delitem:35,pymapping_delitemstr:35,pymapping_getitemstr:35,pymapping_haskei:35,pymapping_haskeystr:35,pymapping_item:35,pymapping_kei:[19,35],pymapping_length:[35,55],pymapping_s:35,pymapping_setitemstr:35,pymapping_valu:35,pymappingmethod:[55,79],pymarshal_readlastobjectfromfil:36,pymarshal_readlongfromfil:36,pymarshal_readobjectfromfil:36,pymarshal_readobjectfromstr:36,pymarshal_readshortfromfil:36,pymarshal_writelongtofil:36,pymarshal_writeobjecttofil:36,pymarshal_writeobjecttostr:36,pymem:[470,475],pymem_:475,pymem_del:[37,471],pymem_fre:[4,16,37,92,473,475],pymem_malloc:[37,92,473,475],pymem_new:[37,471],pymem_realloc:[37,473,475],pymem_res:37,pymemberdef:[18,51,55,79,253,404,477],pymemcompat:473,pymemoryview_check:6,pymemoryview_frombuff:6,pymemoryview_fromobject:6,pymemoryview_get_buff:6,pymemoryview_getcontigu:6,pymethod_check:38,pymethod_class:38,pymethod_clearfreelist:38,pymethod_funct:38,pymethod_get_class:38,pymethod_get_funct:38,pymethod_get_self:38,pymethod_new:38,pymethod_self:38,pymethod_typ:[38,94],pymethoddef:[3,18,51,55,76,77,79,92,473],pymodinit_func:[77,79,92,473],pymodule_:39,pymodule_addintconst:[39,470],pymodule_addintmacro:[39,476],pymodule_addobject:[39,77,79,470],pymodule_addstringconst:[39,470],pymodule_addstringmacro:[39,476],pymodule_check:39,pymodule_checkexact:39,pymodule_cr:92,pymodule_getdict:39,pymodule_getfilenam:39,pymodule_getnam:39,pymodule_getst:92,pymodule_new:39,pymodule_typ:39,pymoduledef:92,pymoduledef_head_init:92,pymp:293,pynode_fre:82,pynone_check:40,pynumber_:30,pynumber_absolut:41,pynumber_add:[30,41],pynumber_and:[41,48],pynumber_asssize_t:41,pynumber_check:41,pynumber_coerc:41,pynumber_coerceex:[41,55],pynumber_divid:41,pynumber_divmod:41,pynumber_float:41,pynumber_floordivid:41,pynumber_index:[41,475],pynumber_inplaceadd:41,pynumber_inplaceand:[41,48],pynumber_inplacedivid:41,pynumber_inplacefloordivid:41,pynumber_inplacelshift:41,pynumber_inplacemultipli:41,pynumber_inplaceor:[41,48],pynumber_inplacepow:41,pynumber_inplaceremaind:41,pynumber_inplacershift:41,pynumber_inplacesubtract:[41,48],pynumber_inplacetruedivid:41,pynumber_inplacexor:[41,48],pynumber_int:41,pynumber_invert:41,pynumber_long:41,pynumber_lshift:41,pynumber_multipli:41,pynumber_neg:41,pynumber_or:[41,48],pynumber_posit:41,pynumber_pow:41,pynumber_remaind:41,pynumber_rshift:41,pynumber_subtract:[41,48],pynumber_tobas:41,pynumber_truedivid:41,pynumber_xor:[41,48],pynumbermethod:[55,79,472,475],pyo:[26,63,70,90,249,290,380,435,436,461,465,473,476,477],pyobjc:[84,219,467],pyobject:[3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20,21,22,23,24,25,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,54,55,56,58,59,76,77,79,80,82,92,125,168,333,472,475,476],pyobject_:[30,39,55,475],pyobject_as_gc:472,pyobject_ascharbuff:42,pyobject_asfiledescriptor:43,pyobject_asreadbuff:42,pyobject_aswritebuff:[6,42],pyobject_byt:43,pyobject_cal:[43,55,77],pyobject_callfunct:[43,475],pyobject_callfunctionobjarg:43,pyobject_callmethod:[43,48,82],pyobject_callmethodobjarg:43,pyobject_callobject:[43,76,77,79,82],pyobject_calloc:37,pyobject_checkbuff:6,pyobject_checkreadbuff:42,pyobject_clearweakref:[55,79],pyobject_cmp:[43,79],pyobject_compar:[43,55,79],pyobject_del:[3,37,55,473],pyobject_delattr:43,pyobject_delattrstr:43,pyobject_delitem:[43,55,473],pyobject_delitemstr:473,pyobject_dir:43,pyobject_fre:[37,473,475],pyobject_from_gc:472,pyobject_gc_del:[24,55,472],pyobject_gc_fini:472,pyobject_gc_init:472,pyobject_gc_new:[24,55,472],pyobject_gc_newvar:[24,55,472],pyobject_gc_res:24,pyobject_gc_track:[24,472],pyobject_gc_untrack:[24,79,472],pyobject_genericgetattr:[43,51,55,94],pyobject_genericsetattr:[43,55],pyobject_getattr:[43,55],pyobject_getattrstr:[43,76,77,82,92],pyobject_getbuff:[6,476],pyobject_getit:[31,43,48,55],pyobject_getitem:[19,30,43,55],pyobject_hasattr:43,pyobject_hasattrstr:43,pyobject_hash:[43,48,55],pyobject_hashnotimpl:[43,55,476],pyobject_head:[51,55,79],pyobject_head_init:[51,55,79],pyobject_init:3,pyobject_initvar:3,pyobject_is_gc:[55,79],pyobject_isinst:43,pyobject_issubclass:[43,54],pyobject_istru:[43,48,55],pyobject_length:[30,43],pyobject_malloc:[37,473,475],pyobject_new:[3,24,37,55,79,473],pyobject_newvar:[3,24,37,473],pyobject_not:43,pyobject_print:[43,48,55,77],pyobject_realloc:[37,473,475],pyobject_repr:[22,43,48,55,56],pyobject_richcompar:[43,55],pyobject_richcomparebool:[43,48],pyobject_s:[43,55],pyobject_setattr:[43,55],pyobject_setattrstr:[43,82],pyobject_setitem:[30,43,55,475],pyobject_str:[22,43,55],pyobject_typ:43,pyobject_typecheck:[43,79],pyobject_unicod:[43,56],pyobject_var_head:[51,55,79],pyobject_varnew:55,pyopengl:[84,231],pyos_afterfork:[28,52],pyos_ascii_atof:[16,474,477],pyos_ascii_formatd:[16,474],pyos_ascii_strtod:[16,474,477],pyos_checkstack:[20,52],pyos_double_to_str:[16,22],pyos_getsig:[52,470],pyos_readlinefunctionpoint:82,pyos_setsig:[52,470],pyos_sighandler_t:52,pyos_snprintf:[16,472],pyos_stricmp:[16,476],pyos_string_to_doubl:[16,477],pyos_strnicmp:[16,476],pyos_vsnprintf:[16,472],pypa:467,pypackag:475,pyparser_astfromfil:475,pyparser_astfromstr:475,pyparser_parsestr:82,pyparser_simpleparsefil:58,pyparser_simpleparsefileflag:58,pyparser_simpleparsestr:58,pyparser_simpleparsestringflag:58,pyparser_simpleparsestringflagsfilenam:58,pypi:[63,68,69,72,74,91,98,100,138,139,315,365,425,445,460,464,473,475,477],pyport:470,pyproperty_typ:[18,94],pyqt3:307,pyqt4:307,pyqt:[84,88,307,467],pyrange_new:[472,475],pyrange_typ:475,pyrex:[82,88],pyrun_anyfil:58,pyrun_anyfileex:58,pyrun_anyfileexflag:58,pyrun_anyfileflag:58,pyrun_fil:58,pyrun_fileex:58,pyrun_fileexflag:58,pyrun_fileflag:58,pyrun_interactiveloop:[58,82],pyrun_interactiveloopflag:58,pyrun_interactiveon:58,pyrun_interactiveoneflag:58,pyrun_simplefil:[58,76],pyrun_simplefileex:58,pyrun_simplefileexflag:58,pyrun_simplefileflag:58,pyrun_simplestr:[28,58,76,82,89],pyrun_simplestringflag:58,pyrun_str:[58,82],pyrun_stringflag:58,pyseqiter_check:32,pyseqiter_new:32,pyseqiter_typ:32,pysequence_:30,pysequence_check:[47,55],pysequence_concat:[47,55],pysequence_contain:[47,55],pysequence_count:47,pysequence_delitem:47,pysequence_delslic:47,pysequence_fast:47,pysequence_fast_get_item:47,pysequence_fast_get_s:47,pysequence_fast_item:47,pysequence_getitem:[30,47,55,82],pysequence_getslic:47,pysequence_index:47,pysequence_inplaceconcat:[47,55],pysequence_inplacerepeat:[47,55],pysequence_item:47,pysequence_length:[30,47,82],pysequence_list:47,pysequence_repeat:[47,55],pysequence_s:[47,55],pysequence_setitem:[30,33,47,55],pysequence_setslic:47,pysequence_tupl:47,pysequencemethod:[55,79],pyseri:87,pyset_add:[48,475],pyset_check:48,pyset_clear:48,pyset_contain:[48,475],pyset_discard:[48,475],pyset_get_s:48,pyset_new:[48,475],pyset_pop:48,pyset_s:[48,475],pyset_typ:48,pysetobject:48,pyshel:[152,178,333],pysid:84,pysignal_setwakeupfd:[20,476],pyslice_check:49,pyslice_getindic:49,pyslice_getindicesex:49,pyslice_new:49,pyslice_typ:49,pysliceobject:49,pysol:86,pyspam_api:77,pyspam_api_point:77,pyspam_system:77,pyspam_system_num:77,pyspam_system_proto:77,pyspam_system_return:77,pysqlit:[364,475,477],pystartup:458,pystaticmethod_typ:94,pyston:[238,473,474,475],pystr:92,pystring_:50,pystring_as_str:[50,79],pystring_asdecodedobject:50,pystring_asencodedobject:50,pystring_asstr:[50,82],pystring_asstringands:50,pystring_check:[50,79,82],pystring_checkexact:50,pystring_concat:50,pystring_concatanddel:50,pystring_decod:50,pystring_encod:50,pystring_format:[50,79],pystring_fromformat:[20,50,79],pystring_fromformatv:50,pystring_fromstr:[19,30,37,50,76,79],pystring_fromstringands:50,pystring_get_s:50,pystring_internfromstr:50,pystring_interninplac:50,pystring_new:473,pystring_s:[50,82],pystring_typ:[50,55],pystringobject:[4,50,476],pysys_addwarnopt:52,pysys_getfil:52,pysys_getobject:52,pysys_resetwarnopt:52,pysys_setargv:[28,477],pysys_setargvex:[28,30,477],pysys_setobject:52,pysys_setpath:52,pysys_writestderr:52,pysys_writestdout:52,pytest:407,pyth:243,python1:[72,107],python25:[107,469],python25_bcpp:107,python26:[462,463,476],python27:[89,107,459,468],python2:[75,76,82,83,104,107,108,109,356,449,471,476],python3:[99,108,109,468,477],python:[2,3,4,5,6,7,8,10,11,12,15,16,17,19,20,21,22,23,24,25,26,29,32,33,34,35,36,37,38,39,40,41,42,43,45,47,48,49,50,51,52,53,54,55,56,57,58,59,61,64,65,66,68,72,73,74,75,79,80,90,91,94,98,99,101,102,103,105,110,111,113,114,116,117,119,120,121,123,124,125,127,128,129,130,131,132,133,134,135,136,138,139,140,141,142,143,144,145,147,149,152,153,155,158,159,160,161,162,163,164,165,167,169,171,173,174,175,176,177,178,179,180,181,183,185,187,188,189,191,192,193,194,197,199,200,201,202,203,204,206,207,211,212,213,216,217,218,219,221,222,223,225,226,227,230,231,232,234,235,236,237,238,239,240,241,242,243,245,247,249,250,251,253,254,255,256,258,259,260,266,267,268,269,270,271,273,275,277,279,280,284,285,287,288,289,290,293,294,297,299,300,302,303,304,305,306,307,310,312,313,314,315,316,317,318,319,321,327,328,330,332,333,334,335,337,338,339,340,341,344,345,348,351,353,354,355,356,358,360,361,365,367,368,369,372,373,374,377,379,380,382,383,384,386,389,390,391,392,394,395,400,401,403,404,405,407,409,410,411,412,413,414,415,418,419,420,423,425,426,427,429,430,431,432,434,435,436,437,439,440,441,442,443,445,446,447,450,452,453,454,455,457,458,462,463,464,465],python_api_vers:[3,473],python_branch:315,python_build:315,python_compil:315,python_dom:426,python_implement:315,python_logo:434,python_revis:315,python_vers:315,python_version_tupl:315,pythonapi:[168,475],pythonbook:83,pythonc:470,pythoncaseok:[465,471],pythoncgislav:284,pythoncor:[64,469],pythoncraft:87,pythondebug:465,pythondecoratorlibrari:474,pythondoc:327,pythondontwritebytecod:[380,465,476],pythondumpref:[55,465],pythonexecut:465,pythonfil:76,pythonhashse:[332,465],pythonhom:[28,30,107,465,469],pythonhost:[365,467],pythonhttpsverifi:[465,477],pythonid:[227,270],pythoninspect:[465,473],pythonioencod:[465,476],pythonlab:[438,470,472],pythonlaunch:467,pythonmac:467,pythonmallocstat:465,pythonnn:89,pythonnousersit:[356,465,476],pythonoptim:465,pythonpath:[30,89,107,143,380,461,465,467,469],pythonrc:[412,449,468],pythonrun:[82,475],pythonshowalloccount:[55,465,477],pythonshowrefcount:[465,477],pythonstartup:[244,334,340,412,449,458,465],pythonthreaddebug:465,pythonunbuff:465,pythonuserbas:[356,465,476],pythonverbos:465,pythonvers:30,pythonw:[269,293,356,467,469,472],pythonwar:259,pythonwarn:[465,477],pythonwin:[83,84,88,168,458,469,470],pythonx:[30,76,107,356,368],pythonxi:80,pythony2k:[392,465],pythreadst:28,pythreadstate_clear:28,pythreadstate_delet:28,pythreadstate_get:28,pythreadstate_getdict:28,pythreadstate_new:28,pythreadstate_next:[28,472],pythreadstate_setasyncexc:28,pythreadstate_swap:28,pytime_check:17,pytime_checkexact:17,pytime_fromtim:17,pytpflags_have_gc:472,pytrace_c_cal:28,pytrace_c_except:28,pytrace_c_return:28,pytrace_cal:28,pytrace_except:28,pytrace_lin:28,pytrace_return:28,pytracebackobject:474,pytuple_check:[53,82],pytuple_checkexact:53,pytuple_clearfreelist:53,pytuple_get_item:53,pytuple_get_s:53,pytuple_getitem:[53,77,82],pytuple_getslic:53,pytuple_new:[30,53,76,82],pytuple_pack:[53,474],pytuple_s:[53,82],pytuple_set_item:53,pytuple_setitem:[30,48,53,76,77,82],pytuple_typ:53,pytupleobject:53,pytyp:100,pytype_:55,pytype_check:[54,77],pytype_checkexact:54,pytype_clearcach:54,pytype_genericalloc:[54,55],pytype_genericnew:[54,79],pytype_hasfeatur:[54,55],pytype_is_gc:54,pytype_issubtyp:54,pytype_modifi:54,pytype_readi:[54,55,79],pytype_typ:[54,55,79],pytypeobject:[3,6,7,9,10,12,14,18,19,21,22,23,24,25,29,30,32,33,34,38,39,40,43,48,49,50,51,53,54,55,56,79,471],pytz:174,pytzinfo_check:17,pytzinfo_checkexact:17,pyunicod:92,pyunicode_:[82,92],pyunicode_as_data:56,pyunicode_as_unicod:56,pyunicode_asasciistr:56,pyunicode_ascharmapstr:56,pyunicode_asencodedstr:56,pyunicode_aslatin1str:56,pyunicode_asmbcsstr:56,pyunicode_asrawunicodeescapestr:56,pyunicode_asunicod:56,pyunicode_asunicodeescapestr:56,pyunicode_asutf16str:56,pyunicode_asutf32str:56,pyunicode_asutf8str:56,pyunicode_aswidechar:56,pyunicode_check:56,pyunicode_checkexact:56,pyunicode_clearfreelist:56,pyunicode_compar:56,pyunicode_concat:56,pyunicode_contain:56,pyunicode_count:56,pyunicode_decod:56,pyunicode_decodeascii:56,pyunicode_decodecharmap:56,pyunicode_decodelatin1:56,pyunicode_decodembc:56,pyunicode_decodembcsst:56,pyunicode_decoderawunicodeescap:56,pyunicode_decodeunicodeescap:56,pyunicode_decodeutf16:56,pyunicode_decodeutf16st:56,pyunicode_decodeutf32:56,pyunicode_decodeutf32st:56,pyunicode_decodeutf7:56,pyunicode_decodeutf7st:56,pyunicode_decodeutf8:56,pyunicode_decodeutf8st:56,pyunicode_encod:56,pyunicode_encodeascii:56,pyunicode_encodecharmap:56,pyunicode_encodelatin1:56,pyunicode_encodembc:56,pyunicode_encoderawunicodeescap:56,pyunicode_encodeunicodeescap:56,pyunicode_encodeutf16:56,pyunicode_encodeutf32:56,pyunicode_encodeutf7:56,pyunicode_encodeutf8:56,pyunicode_find:56,pyunicode_format:56,pyunicode_fromencodedobject:56,pyunicode_fromformat:[56,92],pyunicode_fromformatv:56,pyunicode_fromobject:56,pyunicode_fromstr:56,pyunicode_fromstringands:56,pyunicode_fromunicod:56,pyunicode_fromwidechar:56,pyunicode_get_data_s:56,pyunicode_get_s:56,pyunicode_gets:56,pyunicode_join:56,pyunicode_replac:56,pyunicode_richcompar:56,pyunicode_split:56,pyunicode_splitlin:56,pyunicode_tailmatch:56,pyunicode_transl:56,pyunicode_translatecharmap:56,pyunicode_typ:56,pyunicodedecodeerror_cr:20,pyunicodedecodeerror_getencod:20,pyunicodedecodeerror_getend:20,pyunicodedecodeerror_getobject:20,pyunicodedecodeerror_getreason:20,pyunicodedecodeerror_getstart:20,pyunicodedecodeerror_setend:20,pyunicodedecodeerror_setreason:20,pyunicodedecodeerror_setstart:20,pyunicodeencodeerror_cr:20,pyunicodeencodeerror_getencod:20,pyunicodeencodeerror_getend:20,pyunicodeencodeerror_getobject:20,pyunicodeencodeerror_getreason:20,pyunicodeencodeerror_getstart:20,pyunicodeencodeerror_setend:20,pyunicodeencodeerror_setreason:20,pyunicodeencodeerror_setstart:20,pyunicodeobject:[4,56],pyunicodetranslateerror_cr:20,pyunicodetranslateerror_getend:20,pyunicodetranslateerror_getobject:20,pyunicodetranslateerror_getreason:20,pyunicodetranslateerror_getstart:20,pyunicodetranslateerror_setend:20,pyunicodetranslateerror_setreason:20,pyunicodetranslateerror_setstart:20,pyunicodeucs2:60,pyunicodeucs4:82,pyunit:[388,407,471],pyvarobject:[3,24,51,55],pyvarobject_head_init:[51,79],pyw:[449,469,472],pyweakref_:55,pyweakref_check:59,pyweakref_checkproxi:59,pyweakref_checkref:59,pyweakref_get_object:59,pyweakref_getobject:59,pyweakref_newproxi:59,pyweakref_newref:[4,59],pywin32:[60,466],pywrapper_new:18,pyxml:[60,70,72,275,427,471],pyyaml:477,pyzipfil:[60,122],qa1067:467,qabxcd:180,qdevic:212,qdoff:[60,268],qdoffscreen:[60,268],qdpoint:117,qdrectangl:117,qenter:212,qfoutfil:303,qiflush:169,qmail:273,qmark:364,qname:[60,251,275,426,431,432],qnan:178,qnew:380,qpop:318,qread:212,qreset:212,qsize:[293,330],qsort:168,qtest:212,qty:[364,475],quack:[90,99,476],quad:[360,472],quadrant:277,quadrat:[180,247,368,425,477],quadro:118,qual:157,qualif:[449,465],qualifi:[72,101,222,251,266,267,311,315,333,339,358,360,407,415,432,436,465,475],qualifiednam:426,qualit:396,qualiti:[60,102,118,186,259,304,306,318,407,440,456],qualnam:[98,266],quantifi:[258,328],quantiti:[178,277,365,457,463,473,477],quantiz:[178,463],quarterli:83,quartz:99,queen:[96,333,472,473],queri:[6,60,87,96,101,104,106,113,120,143,150,200,230,262,290,304,315,320,345,364,384,388,394,396,401,409,411,423,426,434,447,475,476,477],query_opt:401,query_str:423,queryinfokei:113,queryparam:119,queryperformancecount:392,queryreflectionkei:[113,476,477],queryvalu:113,queryvalueex:113,quest:[369,453],questhead:396,question:[1,60,63,77,81,82,83,89,90,95,96,98,100,101,102,104,106,111,125,129,137,150,186,191,264,265,280,303,318,341,364,396,422,423,453,457,462,464,470,472,473,475],queu:[28,127,148,169,306,360,387,476],queue:[60,87,102,119,126,152,167,169,173,212,252,258,294,304,343,345,361,362,377,385,387,391,447,456,463,470,473,474,475,476],queue_func:293,queueiter:258,queuemanag:293,queuespeed_func:293,quick:[28,60,62,69,79,96,99,101,105,107,108,301,380,395,405,410,472,473,474,475,476],quick_ratio:180,quickdraw:[60,117,268],quickest:459,quickli:[83,87,88,89,96,99,100,101,102,107,180,210,222,243,333,394,407,437,450,462,471,475],quicktim:[60,268,472],quiet:[63,91,156,178,277,303,388,414,477],quietli:[107,474],quinlan:[473,474,477],quirk:[93,160,445,451,453,467],quirki:364,quit:[6,62,70,71,72,76,77,79,83,87,88,91,93,96,98,101,102,106,123,134,159,168,169,174,193,221,226,236,244,256,277,278,293,299,303,309,318,358,365,396,415,442,445,451,452,458,459,461,462,467,470,471,472,473,475],quixot:473,quopri:[60,135,150,252,283,295],quopri_codec:150,quot:[4,43,60,63,79,81,82,87,90,101,104,108,135,143,150,167,168,191,194,195,198,200,203,222,240,246,252,260,273,280,283,295,309,313,333,339,348,351,368,369,374,386,389,393,396,398,403,409,429,433,438,440,442,445,446,452,457,458,459,460,462,470,473,475],quota:[99,205,246],quotat:[90,143,150,374,476],quote_:167,quote_al:167,quote_minim:167,quote_non:167,quote_nonnumer:167,quote_plu:409,quoteattr:[143,433],quotechar:167,quotedprint:150,quotetab:[135,150,331],quotient:[14,178,222,322,368,442,455],quux:[95,384],qwarn:477,r5r:476,r_eval:338,r_exec:338,r_execfil:338,r_import:338,r_ok:304,r_open:338,r_reload:338,r_unload:338,rabic:406,race:[90,178,386,418],rackspac:83,rad:[104,473],radian:[147,178,277,332,403,473],radic:474,radio:[89,212,290,394],radiobutton:[290,394,401],radiobuttongroup:290,radiogroup:290,radiu:403,radix:[29,34,178,222,264,368,380,446],radixchar:264,raffl:332,rail:106,rais:[2,4,6,13,16,19,20,21,23,26,28,29,30,31,32,34,39,41,43,47,48,50,51,52,53,55,56,58,59,60,63,64,77,79,81,82,90,92,93,94,95,96,99,100,102,104,105,109,113,118,120,121,123,124,125,126,127,128,129,130,131,133,134,135,136,137,138,139,142,143,146,147,149,150,151,152,157,158,159,160,161,162,163,164,165,167,168,169,174,175,176,178,182,185,186,188,191,192,193,195,196,198,200,201,206,207,210,213,216,217,218,219,221,222,225,226,228,229,230,233,236,239,240,241,243,245,246,247,249,251,253,256,258,259,260,263,264,265,266,269,273,276,277,287,290,291,292,293,296,298,299,304,305,306,308,311,314,316,318,319,320,324,325,328,330,332,333,336,337,338,339,340,343,345,346,348,350,352,353,357,358,360,361,363,364,365,368,369,370,373,374,376,377,379,380,381,383,384,385,388,390,391,392,396,398,406,407,409,410,411,414,416,417,418,419,422,423,424,425,426,429,430,431,432,434,435,436,437,439,440,441,442,443,444,446,449,451,452,453,456,457,461,463,465,469,470,471,472,473,474,475,476,477],raise_on_error:186,raise_stmt:[443,447],raise_vararg:182,raiseexcept:[98,265],raison:63,ralf:[475,476],ralph:476,ram:[104,364,475],rambl:96,ran:[87,152,186,206,407,476,477],rand_add:365,rand_byt:365,rand_egd:365,rand_list:96,rand_pseudo_byt:365,rand_statu:365,randal:[88,103],randint:332,random:[28,60,77,81,88,90,93,96,99,104,150,152,165,186,210,211,236,252,255,256,257,258,280,292,293,301,303,304,322,333,345,368,384,386,391,407,415,426,437,456,462,464,465,470,471,472,473,474,475,476,477],random_combin:258,random_combination_with_replac:258,random_permut:258,random_product:258,randomli:[87,293,322,332,472,475],randrang:[87,258,332,462,474],randse:477,rang:[4,17,29,34,41,57,60,62,63,73,76,77,78,79,81,87,90,93,95,96,99,101,104,105,109,117,123,124,129,134,135,138,140,147,150,152,161,168,169,170,174,178,180,182,186,191,205,206,221,222,232,236,246,252,258,260,273,276,287,293,299,306,309,315,318,319,322,329,330,332,333,348,350,360,365,368,369,372,380,392,393,394,396,400,403,404,422,426,434,437,439,440,441,442,445,446,447,451,453,455,456,457,460,461,462,463,465,470,472,473,474,475,476,477],rank:429,ranlib:63,rapid:[152,307,456],rapidli:[106,186,322],rappin:307,rare:[30,55,62,75,81,90,108,127,133,138,162,169,186,196,221,222,265,276,303,350,360,392,426,451,461,463,471,472,475,476],rarer:475,rarg:303,raseliarison:477,rast:248,raster:248,rat:230,ratcliff:180,rate:[87,118,129,236,300,306,322,376,377,417],ratecv:129,rather:[4,6,14,19,25,26,28,36,39,43,48,51,55,63,67,72,76,77,79,86,87,88,89,90,98,99,106,107,108,119,123,125,142,143,147,148,150,152,160,162,169,174,178,184,203,204,206,222,223,225,229,246,256,258,265,266,267,273,277,293,303,304,306,308,315,326,328,332,333,338,342,352,356,360,365,368,369,374,380,384,388,392,393,394,396,407,409,410,416,418,423,426,434,435,436,438,440,442,445,447,450,451,452,457,463,471,472,473,474,476,477],ratio:[180,247,368,403],ration:[60,174,178,252,300,301,368,440,476,477],rational:[83,90,92,204,418,440,470,471,472,473,474,475,476,477],raw:[4,6,15,37,60,71,90,98,101,119,120,125,143,150,158,168,169,186,200,201,202,219,230,243,252,253,286,293,304,351,360,361,365,372,393,396,400,402,409,415,431,437,446,448,460,471,473,475,476],raw_data:453,raw_decod:260,raw_input:[87,109,148,149,165,206,222,244,334,358,364,374,380,385,387,400,448,452,454,461,463],raw_unicode_escap:150,rawarrai:293,rawconfigpars:[60,209,477],rawdata:161,rawdescriptionhelpformatt:123,rawiobas:[256,476],rawparam:200,rawpen:403,rawtexthelpformatt:123,rawturtl:[60,395],rawvalu:293,raymond:[93,94,96,103,169,373,470,471,473,474,475,476,477],raynor:474,rbrace:397,rc4:[365,438],rcn:94,rcpt:358,rcpt_option:358,rcptto:357,rcvall_:360,rcvall_off:360,rcvall_on:360,rdn:365,reach:[20,21,30,45,58,77,79,83,87,88,96,99,101,105,134,139,146,151,222,256,258,265,304,309,311,328,330,345,351,361,368,369,374,400,409,431,439,440,442,447,451,457,470,471,472,473,475,476,477],reachabl:[45,81,102,186,225,303,304,440],reacquir:[28,168,391],react:[93,106,274,470,476],reaction:[470,471],read1:256,read:[4,6,16,19,21,26,28,36,42,51,55,56,58,60,63,70,71,72,73,76,77,79,81,82,83,88,89,90,91,92,93,94,95,96,98,99,100,101,102,105,106,107,109,110,112,114,119,121,122,123,124,126,127,128,131,133,135,136,138,139,142,143,148,149,150,151,152,156,157,158,161,162,168,169,174,175,176,181,186,192,193,199,202,205,206,207,208,209,210,211,212,216,221,222,223,225,226,227,229,230,231,234,236,239,240,241,246,247,249,251,252,255,256,260,263,265,266,270,273,276,280,281,286,287,291,292,293,296,299,303,304,305,306,309,311,313,314,315,316,317,320,322,323,326,327,328,331,333,334,337,338,339,341,343,345,347,348,350,351,352,360,361,364,365,366,368,369,372,373,374,377,380,381,385,386,391,392,396,399,400,401,403,409,410,411,412,414,415,416,421,423,426,429,430,431,432,433,434,435,437,438,440,441,443,446,447,448,449,450,451,452,454,456,458,459,460,461,462,463,464,465,467,469,470,471,472,473,474,475,476,477,478],read_:385,read_al:385,read_byt:287,read_data:457,read_eag:385,read_fil:104,read_histori:334,read_history_fil:[334,458],read_init_fil:[334,340],read_lazi:385,read_mime_typ:281,read_restrict:79,read_sb_data:385,read_som:385,read_token:351,read_until:385,read_very_eag:385,read_very_lazi:385,read_windows_registri:281,readabl:[4,42,55,66,79,81,90,93,95,98,99,101,102,106,116,118,123,127,143,152,157,162,168,180,195,221,230,256,265,266,270,293,304,315,316,321,324,333,346,368,376,378,386,396,397,417,430,450,451,452,453,457,460,461,463,465,471,472,474,476,477],readahead:139,readal:256,readbufferproc:55,readcd:476,readda:142,reader:[30,60,81,83,101,102,106,150,152,193,198,200,209,256,273,274,299,303,311,360,365,406,426,430,431,432,433,445,451,456,473,475],readermod:299,readerror:384,readfp:[158,281,477],readfram:[118,376,417],readfunc:149,readi:[28,83,93,98,100,102,127,134,140,142,168,178,180,267,293,338,345,360,365,400,432,433,456,470,473],readili:[99,256,308,337,385],reading_head:126,readinto:[234,256,476],readlin:[21,60,63,72,81,82,87,95,96,104,128,139,143,148,150,158,180,199,202,206,210,221,222,246,252,256,283,287,292,299,304,311,317,331,339,351,361,362,368,384,396,398,409,435,448,449,451,454,457,458,459,465,470,471,472,473,475,476,477],readlink:[304,338,352],readm:[66,71,73,107,221,468,469,470],readmodul:326,readmodule_ex:326,readonli:[6,51,79,246,368,401,426,427,476],readplist:[316,476],readplistfromresourc:316,readplistfromstr:[316,476],readsamp:119,readscal:247,readthedoc:[423,475],ready_to_read:102,ready_to_writ:102,reak:309,real:[14,30,33,41,52,55,60,63,76,88,90,92,95,105,107,111,124,146,147,149,167,168,186,216,217,222,236,249,260,277,292,299,300,304,315,322,332,333,346,353,364,365,368,369,380,392,396,407,409,410,413,429,440,446,450,451,453,454,455,464,465,475,476,477],real_person:429,real_quick_ratio:180,realhost:434,realis:470,realist:[83,87,96,374,427,437,474,475],realiti:[63,77,174,303,360,405,409,410],realiz:[30,82,83,89,95,100,102,451,455,475,476],realli:[43,56,68,70,75,76,79,80,81,83,88,93,96,101,102,104,106,107,125,127,141,143,174,182,193,293,304,311,322,345,364,368,380,391,392,396,403,406,440,447,450,452,453,457,470,471,472,473,474,475],realloc:[37,47,50,77,82,88,169,474],realm:[105,409,410],realnam:[203,339],realpart:451,realpath:305,ream:476,rearrang:[282,450,463,470,473,475,477],reason:[6,20,28,30,37,40,41,43,55,62,64,68,77,79,81,87,88,89,90,91,95,96,98,100,101,102,104,105,106,107,117,129,143,144,147,148,161,169,174,178,186,206,208,221,230,236,241,244,246,255,256,258,273,277,278,303,304,308,311,315,318,322,338,352,356,364,365,368,374,384,385,389,390,396,403,407,409,410,439,440,443,447,450,451,455,461,472,473,475],reassign:[37,79,159,293],reassur:80,reattach:401,rebind:[88,225,458,474],rebound:[222,447],rebuild:[63,72,77,107,156,405],rec:[328,427,429],recal:[182,244,455,458],recalc:94,recalcul:[94,264,265],recap:94,recast:258,reccontrol:306,receiv:[1,4,15,20,28,30,43,55,59,60,71,76,77,79,82,83,87,96,98,100,102,105,126,127,143,148,150,158,162,168,206,215,219,221,222,240,244,246,265,266,267,276,277,284,293,299,306,311,318,328,330,336,352,353,355,358,360,361,365,374,385,390,400,401,407,410,423,426,430,431,439,440,441,442,452,462,470,473,474,475,476,477],recent:[56,62,63,77,79,81,88,89,91,96,99,104,106,123,126,141,143,152,158,168,178,186,204,216,240,244,246,253,268,292,293,304,306,308,309,319,328,330,332,333,348,365,368,369,374,380,388,394,396,400,403,406,411,418,440,442,447,451,452,453,454,457,460,463,467,470,471,472,473,474,475,476,477],recip:[60,67,88,99,105,137,173,180,249,277,301,304,332,350,364,464],recipi:[193,203,357,358,361],recit:101,reclaim:[11,77,79,222,380,418],reclam:55,recod:[4,150],recogn:[60,63,72,77,81,88,89,90,126,148,158,169,179,182,191,192,210,215,221,222,224,228,235,248,249,256,260,264,281,291,303,308,309,311,333,348,351,368,388,392,409,411,432,446,447,452,461,470],recognis:[89,167,266],recognit:[281,368],recogniz:[81,178,222],recombin:129,recommend:[4,28,37,39,55,62,63,69,70,72,75,76,83,86,88,89,91,92,96,98,100,103,104,106,107,123,138,147,157,165,167,168,174,178,184,186,197,219,222,230,237,238,239,241,244,246,260,265,277,304,306,319,322,328,332,333,338,342,354,360,365,368,374,380,384,386,392,407,409,410,413,415,423,425,426,427,431,432,437,438,440,446,452,461,468,470,472,474,475,476,477],recompil:[63,76,82,90,106,156,222,470,473,477],recomput:98,reconstitut:[265,311],reconstruct:[164,256,311,321,398,423,457],record:[26,28,60,71,79,81,88,96,98,99,103,107,111,115,121,125,134,137,142,152,167,168,169,170,178,193,205,219,236,238,253,258,265,267,273,288,302,303,304,306,310,322,346,364,366,368,373,377,388,403,407,416,421,435,451,456,461,470,473,474,475,476,477],record_foo_seen:303,recount:178,recov:[150,206,218,380,414,431,477],recover:431,recoveri:[246,311,410],recreat:[150,310,440],rect:[147,168,476],rectangl:[77,93,117,169],rectangular:[93,147,403],recur:401,recurs:[27,28,60,63,72,73,77,88,90,96,109,115,116,125,143,156,158,163,180,186,193,200,208,222,249,251,260,271,276,282,293,304,309,311,314,321,322,327,335,350,352,366,380,383,384,391,403,407,409,429,435,440,442,447,451,453,470,471,472,473,474,476],recv:[99,102,127,293,360,361,365,396,477],recv_byt:293,recv_bytes_into:293,recv_into:[360,365,475,477],recvfrom:[360,396],recvfrom_into:[360,475,477],recycl:[102,390,391],red:[64,70,82,83,93,98,99,101,103,107,137,152,153,154,169,231,240,368,396,401,403,418,438,463,473,474],redefin:[63,88,107,134,152,168,222,240,337,348,361,413,440,451,473,476],redefinit:[63,222,440],redemo:101,redesign:[81,476,477],redhat:[69,82,230,315],redirect:[60,64,89,105,144,162,167,241,265,374,380,409,410,456,469,470],redirect_request:410,redisplai:[169,334,473],redistribut:[62,438],redistributor:477,redo:[169,244],redon:440,redraw:[93,212,219,271],redraw_form:212,redraw_object:212,redrawln:169,redrawn:[93,169,403],redrawwin:169,reduc:[30,37,79,88,89,95,96,109,169,178,222,223,237,244,256,308,322,332,368,391,418,425,446,453,461,470,472,473,475,476,477],reduct:[81,88,164,293,311],reductionist:101,redund:[73,77,88,305,437,447,472,477],reedi:473,reenabl:[292,477],reencod:167,reentranc:[60,120],reentrant:[219,256,391],reexecut:[64,222],ref:[4,59,81,101,169,348,418,471,477],refactor:[96,109,407,474],refchild:426,refcount:[50,55,56,79,293,475],refer:[0,3,4,5,6,8,9,10,11,13,14,15,17,18,19,20,21,22,23,24,25,26,28,29,31,32,33,34,35,36,37,38,39,40,41,43,46,47,48,49,50,51,52,53,54,55,56,58,60,62,64,67,69,70,71,72,73,75,76,78,80,81,82,87,89,90,94,95,97,98,99,101,105,106,107,108,113,115,120,123,127,129,132,134,141,142,147,150,152,157,158,162,163,169,173,174,177,178,182,184,191,192,204,205,206,207,212,222,225,227,228,230,233,235,239,240,241,244,249,252,253,254,256,259,260,265,266,267,270,273,275,287,299,300,304,305,307,308,309,311,314,315,319,320,321,327,328,332,333,339,341,342,348,356,360,362,364,365,368,369,370,373,377,378,380,382,387,390,391,392,394,395,397,400,401,403,407,409,410,413,416,425,426,427,431,433,435,438,439,440,441,445,446,447,450,452,453,454,455,456,457,464,465,470,472,473,474,475,476,477,478],referenc:[4,6,9,30,53,55,59,77,79,81,88,90,98,101,123,158,171,185,223,244,293,304,311,333,360,368,379,380,418,426,440,441,451,452,453,457,461,471,472,473,476,477],referenceerror:[20,206,418,461,471,472],referencetyp:418,referenti:81,referr:225,refilemessag:279,refin:88,reflect:[27,57,60,63,64,88,90,91,113,118,123,139,167,169,174,186,191,204,207,223,244,303,304,322,334,360,368,380,396,403,427,438,440,465,476],reflex:442,reflow:215,reformat:[157,244,273,303,473],refresh:[93,169,401,475],refus:[30,79,102,205,350,358],refusenik:452,reg_binari:113,reg_dword:113,reg_dword_big_endian:113,reg_dword_little_endian:113,reg_expand_sz:113,reg_full_resource_descriptor:113,reg_link:113,reg_multi_sz:113,reg_non:113,reg_resource_list:113,reg_resource_requirements_list:113,reg_sz:113,regard:[30,88,92,98,108,114,167,181,235,304,314,353,368,386,426,438,440,451],regardless:[2,21,28,36,50,56,62,63,64,72,81,95,100,106,107,123,135,169,174,178,186,214,222,249,255,256,258,260,308,314,328,353,360,365,368,369,373,374,386,401,403,407,416,418,419,437,440,446,454],regdeletekeyex:113,regebro:477,regen:60,regener:[73,339,477],regent:438,regex:[101,156,214,264,333,338,385,407,471,475,476],regexobject:333,regexp:[388,407],region:[169,239,244,291,320,333,396,401,451,476],regist:[1,13,28,50,52,60,64,69,72,77,79,84,87,104,105,114,123,128,150,167,186,219,252,256,265,281,293,300,304,310,311,334,345,352,355,365,368,380,396,401,403,407,410,416,418,419,422,426,429,431,458,460,464,470,471,473,474,476,477],register_adapt:364,register_archive_format:352,register_convert:364,register_dialect:167,register_error:[150,256,368,473],register_funct:[355,434],register_inst:355,register_introspection_funct:355,register_multicall_funct:[355,434],register_namespac:[429,477],register_optionflag:186,register_shap:403,registerdomimplement:426,registerresult:407,registr:[28,52,71,113,163,311,355,410,476],registri:[20,27,50,56,57,60,158,167,194,249,252,267,281,314,315,365,372,380,409,410,416,421,422,429,469,470,476,477],regloadkei:113,regress:[60,81,179,186,252,260,477],regrtest:[388,473,477],regsub:475,regtyp:384,regular:[8,11,55,60,63,70,71,73,79,81,83,87,88,90,94,96,97,99,104,107,114,123,152,162,167,178,186,193,214,231,234,236,252,258,264,266,273,297,304,305,322,339,345,353,358,365,366,368,369,372,380,384,385,403,407,410,413,416,418,440,446,447,451,460,462,463,470,471,472,473,474,475,476,477],regularli:[28,37,62,100,108,206,403],regulatori:463,rei:474,reid:477,reifschneid:[471,473,474,475,477],reign:264,reilli:[101,333,393,464,469,472],reimplement:[79,403,472],reinforc:464,reingold:[140,174],reinhardt:472,reiniti:55,reinsert:[152,388,401,477],reinstal:[86,107],reinstat:451,reinterpret:[60,252,310],rejeb:474,reject:[95,101,162,447,460,470,477],rel:[26,28,30,60,62,63,64,72,82,87,88,95,98,101,107,109,111,113,124,139,142,146,150,169,174,180,181,182,186,203,204,207,215,219,222,232,250,256,264,265,287,290,292,304,305,311,314,320,322,328,331,333,337,342,343,351,352,354,360,365,368,374,392,394,396,399,401,407,411,423,429,431,435,447,461,462,465,469,470,471,472,474,477,478],relai:357,relat:[1,15,28,37,55,60,69,72,75,81,82,83,87,88,94,99,104,106,107,146,157,169,173,174,186,192,206,209,221,228,236,243,252,254,255,258,273,301,304,308,310,312,328,329,334,360,365,368,380,383,391,392,395,401,416,418,431,438,440,451,463,464,466,467,470,471,473,474,475,476,477],relationship:[43,60,69,174,186,236,310,346,368,380,396,399,418,426,438,440,451,475],relative_modul:447,relativecr:[99,265],relax:[161,174,338],relay:357,releas:[1,3,4,6,9,21,24,30,31,37,51,55,60,64,66,69,70,72,76,77,79,80,83,84,87,90,93,96,100,103,104,105,107,111,116,119,125,160,168,169,182,184,186,192,204,222,235,236,249,256,265,270,273,284,293,294,304,311,315,333,339,360,368,380,383,388,390,391,403,413,416,425,427,438,440,442,447,451,454,461,464,467,468,469,470,471,472,473,474,475,476,478],release_lock:249,release_resourc:160,releaselevel:[380,477],relev:[36,55,63,77,79,87,91,93,96,98,99,116,126,132,158,163,186,207,219,221,222,255,260,266,270,299,303,304,312,314,319,368,374,381,407,423,430,469,470,472,474],reli:[55,60,77,79,88,92,100,102,108,128,138,140,143,152,157,167,174,215,253,260,281,303,311,315,332,338,339,352,386,389,391,392,441,442,447,451,453,461,465,470,473,474,475,477],reliabl:[52,102,150,178,222,293,302,315,419,431,437,451,463,473,477],relicens:474,relief:[396,401],relink:82,relinquish:391,relo:117,reload:[26,77,88,95,162,222,244,249,251,338,380,388,436,461,473],reload_hook:251,reloc:[47,476],relpath:[305,476],remahl:476,remain:[4,22,31,37,55,62,63,67,72,77,79,81,83,99,101,108,123,135,146,152,160,167,168,169,174,178,180,182,184,186,191,210,219,222,225,236,244,246,266,273,277,292,293,303,304,306,309,311,317,336,353,360,364,368,369,380,386,391,401,407,413,418,423,437,438,440,446,453,457,460,462,465,472,473,474,476,477],remaind:[30,41,90,101,123,148,174,178,222,255,266,303,333,368,369,407,442,455,460,476],remainder_near:178,remark:[60,83,273,338,403,456,470,474],remedi:[83,440],rememb:[66,77,79,81,83,86,88,90,91,92,93,94,95,96,98,101,102,104,107,137,151,152,186,222,258,260,293,311,333,353,367,373,401,407,410,418,426,447,451,452,460,461,467,470,471,475,476,477],remind:[30,81,88,368],remot:[60,83,98,99,107,113,124,126,127,205,246,265,266,267,357,360,362,365,385,394,409,410,419,425,434,462,472],remote_command:313,remoteaddr:357,remoteerror:293,remov:[6,16,19,24,26,30,35,48,53,60,63,64,73,77,79,81,83,86,87,90,92,96,98,99,101,103,105,107,109,113,115,116,117,119,123,124,125,126,130,133,134,136,138,141,142,143,148,149,152,153,155,157,158,161,162,167,169,171,174,175,178,181,182,185,186,191,192,197,200,201,203,204,205,212,213,217,219,221,222,225,231,236,238,239,240,243,244,245,246,247,251,253,259,260,264,265,267,268,269,271,273,279,280,290,292,293,294,296,297,302,303,304,305,308,309,311,315,316,318,322,328,330,333,334,338,339,343,345,346,348,352,353,360,364,365,367,368,369,377,380,384,385,386,388,389,401,403,404,405,407,409,410,411,412,413,426,429,435,438,439,440,442,447,451,453,458,459,460,461,463,465,467,469,470,471,472,473,474,478],remove_expon:178,remove_flag:273,remove_fold:273,remove_histori:334,remove_history_item:334,remove_label:273,remove_opt:[158,303],remove_pyc:290,remove_sect:158,remove_sequ:273,remove_task:236,remove_thi:333,remove_tre:63,removeattribut:426,removeattributen:426,removeattributenod:426,removecallback:142,removechild:[426,470],removedir:[87,304],removefilt:[98,265],removehandl:[98,99,265,407,477],removemessag:279,removenameditem:426,removeresult:407,rempt:307,renam:[49,50,63,72,79,83,87,89,99,107,109,113,121,152,158,161,162,164,176,178,188,189,192,221,226,239,240,241,246,267,273,304,330,335,341,344,345,346,352,361,366,388,390,394,396,409,411,434,450,451,452,463,470,472,473,474,476,477],render:[99,104,192,195,213,221,319,339,361,396,401,427,440,473,476,477],rendezv:304,rendit:169,renegoti:477,renumb:[246,440],reobj:214,reopen:[98,221,267,311,385,477],reoprt:333,reorder:[81,88,296,315],reorgan:[226,471,476],reorganis:470,reorpt:333,repack:369,repaint:169,repair:[332,441],repeat:[47,51,55,60,82,90,96,102,123,135,148,152,168,169,174,235,236,237,244,258,278,293,295,302,303,306,309,322,332,333,349,360,361,365,368,369,373,393,399,407,410,425,439,447,454,455,458,460,465,472,473,474,476,477],repeat_on:288,repeatedli:[81,95,101,105,113,148,168,180,258,264,281,368,391,393,403,407,422,423,439,447,463,465,472],repeatfunc:258,repertoir:[104,328,358,394,476],repetit:[101,123,235,258,278,302,333,368,393,407,416,440,442,445,472],repl:333,replac:[13,19,30,33,41,49,53,55,56,60,62,63,68,72,77,81,83,87,88,89,91,93,99,104,105,106,107,109,116,123,125,143,149,150,152,157,168,169,171,173,174,180,182,186,194,200,203,210,222,236,238,239,240,244,251,252,256,257,258,264,265,266,270,273,274,281,288,293,303,304,305,308,309,317,320,321,322,332,333,334,335,339,346,351,352,362,364,368,369,380,384,386,388,389,390,391,392,394,396,398,401,403,406,407,409,410,416,423,425,426,429,431,433,435,440,442,446,447,450,451,454,455,457,460,461,462,465,470,473,474,475,476,477],replace_browser_lin:212,replace_choic:212,replace_error:150,replace_head:200,replace_history_entri:334,replace_history_item:334,replace_path:288,replace_whitespac:389,replacechild:426,replacepackag:288,repli:[87,102,116,132,174,221,273,284,293,299,358,409],replic:[88,96,293,474,477],replica:403,replstr:56,repo:380,report:[0,19,28,30,55,60,63,76,77,81,88,89,98,101,104,123,127,143,145,167,168,169,186,200,206,208,222,233,241,258,288,303,304,308,315,319,322,324,328,333,345,346,353,363,365,366,368,380,393,399,406,407,409,429,431,440,441,454,463,464,470,472,473,474,475,476,477],report_:186,report_cdiff:[186,474],report_failur:186,report_full_closur:208,report_ndiff:[186,474],report_only_first_failur:186,report_partial_closur:208,report_start:186,report_success:186,report_udiff:[186,474],report_unbalanc:348,report_unexpected_except:186,reporthook:409,reporting_flag:186,reposit:[150,368],repositori:[62,71,83,108,380,468,470,471,475,477],repoz:106,repr1:335,repr:[16,20,21,22,43,55,60,79,81,87,99,103,104,109,115,125,127,133,157,167,168,173,174,186,222,224,252,293,311,328,346,358,360,368,369,380,389,398,400,407,440,442,447,454,457,461,463,470,471,473,476,477],repr_fil:335,repr_typ:335,repres:[4,6,7,8,10,11,12,14,16,17,19,21,22,23,28,29,30,33,34,38,39,41,48,50,51,53,55,56,58,60,63,68,72,77,79,80,81,87,88,90,93,96,99,100,101,102,104,105,106,107,112,113,117,123,124,125,134,135,140,141,142,143,146,147,150,152,157,159,161,162,165,168,169,174,178,182,192,197,201,206,207,212,215,218,219,222,231,241,243,245,246,253,256,258,260,264,265,266,273,274,277,279,281,282,283,290,291,293,294,295,296,299,302,303,304,305,308,311,316,317,318,319,320,321,322,328,333,335,336,339,343,345,352,355,360,361,364,365,368,369,371,373,378,379,380,384,385,388,391,392,394,396,397,398,400,401,403,407,409,416,426,427,429,432,434,435,437,438,440,442,446,451,455,457,463,470,472,473,474,475,476,477],represent:[4,6,14,16,22,29,34,36,43,50,51,55,56,60,63,72,73,79,81,82,88,90,94,98,100,102,104,115,117,123,124,133,135,136,142,147,150,152,158,161,168,169,170,174,178,192,197,199,200,202,205,206,215,217,222,227,236,241,243,246,260,264,265,273,274,290,293,301,304,308,311,321,328,335,339,350,360,364,368,369,371,373,374,378,380,384,392,397,403,407,424,426,428,429,437,438,440,446,456,457,463,470,474,475,476,477],reprfunc:[55,79],reprlib:335,reprnam:174,reproduc:[88,105,125,332,409,410,433,438,463],reptil:450,republ:438,reput:1,req:[105,365,410],request:[1,4,6,26,37,60,79,88,96,99,102,104,105,106,108,113,123,126,131,132,143,152,161,162,167,168,169,178,187,204,205,221,222,230,241,244,246,249,252,254,256,273,293,299,302,303,304,305,306,308,318,320,321,328,336,338,345,351,353,355,356,365,368,374,377,392,401,403,409,411,412,423,425,426,432,433,434,440,447,451,460,463,465,470,471,473,474,475,476,477],request_bodi:434,request_entity_too_larg:241,request_host:410,request_method:[105,409,410,423],request_queue_s:361,request_text:355,request_timeout:241,request_uri:423,request_uri_too_long:241,request_vers:132,requested_range_not_satisfi:241,requesthandl:[187,293,355],requesthandlerclass:[132,361,423],requir:[3,4,6,9,16,19,24,30,33,34,35,36,37,42,43,47,48,49,50,51,53,54,55,56,60,62,63,64,66,67,68,71,72,73,75,76,77,79,82,83,86,87,88,89,90,91,93,94,96,98,99,100,101,104,105,106,107,108,109,113,114,116,120,121,124,125,126,133,138,139,140,142,149,150,152,158,162,167,169,174,175,178,186,188,193,194,197,198,204,205,206,215,216,218,221,222,225,228,231,234,236,239,240,241,244,246,253,254,255,256,258,259,260,263,264,265,266,267,273,275,277,290,293,294,299,303,304,306,308,311,312,313,318,321,322,324,328,330,332,333,336,338,345,346,350,356,358,360,361,364,365,368,369,370,373,374,380,384,386,388,390,391,392,394,396,398,402,405,406,407,409,410,411,413,414,416,418,420,423,425,426,430,431,432,433,434,435,437,438,439,440,442,443,446,447,451,452,453,454,457,458,461,463,465,469,470,471,472,473,474,475,476,477],require_int:474,requot:200,rerais:[160,293,368,439,440],reread:88,res:[37,72,82,113,241,293,360],rescan:[150,314],rescu:206,research:[61,96,438],resembl:[79,107,162,169,222,309,351,465,472,476,477],resent:[203,273],resent_cc:203,resent_to:203,reserv:[30,60,61,90,94,102,113,157,270,276,293,311,322,332,363,391,415,426,434,435,438,440,447,454,465,471,476],reserved_futur:415,reserved_microsoft:415,reserved_nc:415,reset:[28,52,83,88,96,105,132,134,142,149,150,152,169,178,181,195,201,205,210,216,240,244,265,293,305,306,313,345,348,353,365,368,369,382,384,388,391,392,394,399,403,416,424,428,429,432,446,472,476],reset_cont:241,reset_prog_mod:169,reset_shell_mod:169,resetbuff:149,resetlocal:264,resetopt:394,resetpars:142,resetscreen:403,resetti:169,resetwarn:416,resid:[81,99,107,193,219,230,273,316,327,336,364,366,469,470],resign:93,resist:[101,235,471,477],resiz:[7,24,37,47,50,53,81,168,169,219,256,287,394,396,401,403,407],resize_term:169,resizemod:403,resizeterm:169,resizetestcas:407,resolut:[55,60,79,81,90,114,120,174,222,253,304,306,311,322,360,368,392,405,440,441,451,473,475],resolv:[79,81,88,98,99,123,158,186,215,250,266,303,304,322,328,360,365,380,394,407,427,431,432,433,440,441,442,451,472],resolve_attr:302,resolve_dotted_attribut:474,resolveent:[431,432],resort:[88,188,264,386,396,472],resourc:[20,28,60,63,70,72,83,87,88,90,97,102,103,108,113,142,160,185,186,191,205,219,227,241,246,252,254,265,268,269,271,275,293,304,307,314,316,332,337,352,360,365,380,388,391,396,401,407,408,410,411,415,423,425,432,434,440,454,457,463,464,465,466,473,475,476,477],resourcedeni:388,resourceid:269,resp:[56,150,264,299],respect:[4,5,6,16,19,20,26,28,34,40,43,45,49,56,63,71,72,76,77,79,81,88,89,90,94,98,99,109,123,129,132,140,143,147,150,152,157,158,159,161,162,167,168,169,174,178,182,186,191,192,215,219,221,222,230,245,249,256,266,267,283,287,293,304,322,323,336,343,348,356,360,361,365,368,369,374,376,384,391,392,394,401,403,407,414,427,438,440,442,447,451,460,463,467,469,470,472,474,476],respond:[71,105,106,132,221,241,355,360,396,423,434,477],respons:[4,6,16,20,30,39,54,55,56,60,62,70,71,77,79,81,82,87,90,96,98,102,104,105,106,107,108,132,148,157,162,167,169,171,174,187,191,200,215,219,221,241,246,247,249,252,254,257,264,265,299,304,311,318,328,343,354,355,358,360,361,364,365,374,377,379,380,386,407,409,410,417,434,438,440,447,463,470,473,476,477],responsenotreadi:241,rest:[16,50,56,80,82,83,87,88,91,95,96,98,101,102,109,157,169,178,186,192,219,221,223,244,265,281,303,305,333,340,348,368,388,401,434,438,439,446,447,450,452,454,457,458,470,472,473,475,476,477],restart:[28,106,169,205,221,244,266,271,309,353,387,461,476,477],restat:322,restkei:167,reston:438,restor:[20,28,30,79,93,99,113,162,163,169,178,180,215,251,264,303,304,311,313,332,334,342,364,380,384,387,391,401,403,416,439,440,470,472,473,475,476],restrict:[46,60,77,79,81,91,101,116,123,124,150,152,168,169,174,178,180,215,222,244,252,253,254,260,293,308,310,311,322,326,333,355,365,371,390,391,426,434,438,439,440,441,442,443,446,447,451,452,469,471,473,474,475,476,477],restructur:[84,88,102,470,471,476],restructuredtext:[0,60,71,72,83,186],restval:167,restyp:[168,316,475],result:[4,7,12,14,17,26,28,30,34,36,37,41,43,46,47,50,53,55,56,58,60,63,64,70,72,75,76,77,79,87,89,90,91,92,93,94,95,96,98,99,100,101,104,107,113,115,118,125,127,129,131,132,134,135,136,143,147,150,151,152,155,161,162,167,168,169,170,174,178,180,182,186,191,197,201,202,203,205,206,207,211,215,216,219,221,222,223,225,227,230,232,234,235,238,243,244,245,246,247,249,252,253,254,256,258,259,260,264,265,266,273,274,277,278,287,290,291,292,293,302,303,304,305,306,308,309,311,317,318,320,321,322,325,328,331,332,333,335,336,339,342,346,348,349,351,352,355,358,360,364,365,367,368,369,371,373,374,379,380,381,384,385,386,388,392,393,398,399,400,401,403,407,409,414,415,416,418,423,426,427,429,432,433,434,437,438,439,440,442,443,446,447,452,453,454,455,457,458,460,461,462,463,469,470,471,472,473,474,475,476,477],resultclass:407,resultseq:88,resum:[13,90,96,160,169,170,182,253,293,304,309,311,328,330,387,391,423,442,447,451,472,473,474,475],resumpt:304,resynchron:104,ret:423,retain:[63,77,103,123,139,151,169,200,222,241,244,258,273,308,351,364,388,398,403,411,434,438,442,446,447],retarget:423,retcod:374,retr:[221,318],retrbinari:221,retri:[101,105,267,365,410,441,452,472,473,477],retriev:[4,8,20,21,23,28,31,34,43,49,60,64,76,77,79,81,87,88,90,93,94,96,101,113,121,124,143,152,155,158,162,163,168,169,202,212,221,222,234,239,244,246,251,252,256,263,264,266,273,293,300,302,304,308,314,316,317,318,329,330,333,336,339,342,345,350,364,365,369,370,377,380,386,388,409,410,418,425,438,440,453,462,464,465,471,472,473,474,475,476,477],retrlin:221,retryabl:304,retryfactor:267,retrymax:267,retrystart:267,return_ok:162,return_stmt:[443,447],return_valu:[92,134,182],returncod:374,returnfram:134,returns_unicod:328,retval:[182,471],reunion:193,reus:[71,77,83,102,106,150,168,186,226,236,304,333,360,361,365,388,389,418,439,450,475],reusabl:[70,106,423],rev:451,revamp:[92,477],reveal:[83,174,237,463,476],revealaccess:94,revers:[33,43,60,77,82,83,93,96,102,103,104,124,128,129,137,147,150,152,158,167,169,175,178,215,222,236,245,258,276,293,300,302,322,328,333,351,364,368,398,407,438,440,442,446,451,452,453,458,461,470,473,475,476,477,478],reverse_numer:103,reverse_ord:322,revert:[94,99,162,241,342,365,477],review:[105,473],revis:[28,60,105,125,215,236,308,315,380,396,405,407,424,470,475,478],revoc:365,revok:345,revolv:[186,236],reward:106,rewind:[118,236,376,417],rewindbodi:339,rework:[471,472,473,475,477],rewrit:[81,88,100,125,210,455,470,473,475,477],rewritenam:125,rewritten:[37,186,293,447,470,471,472,473,476,477],rewrot:[470,473],rexec:[26,60,133,252,337,405,473],rexx:474,reykjavik:475,reynold:333,rezinski:87,rfactor:129,rfc1321:438,rfc1522:135,rfc2087:246,rfc2109:162,rfc2109_as_netscap:162,rfc2342:246,rfc2822:472,rfc2965:162,rfc2980:299,rfc822:[60,132,192,193,199,200,201,202,246,252,273,280,282,295,472,474],rfc822_escap:63,rfc:[60,63,99,101,105,135,150,158,161,162,192,193,194,196,197,198,200,202,203,221,230,235,237,239,241,246,252,254,260,264,273,274,278,292,295,299,318,331,357,358,360,365,371,385,392,409,410,411,423,424,434,438,462,470,472,473,474,475,476,477],rfc_4122:415,rfile:[132,361],rfind:[251,287,368,369,476],rgb:[93,153,154,169,212,247,248,259,303,396,403],rgb_to_hl:154,rgb_to_hsv:154,rgb_to_yiq:154,rgba:247,rgbcolor:117,rgbimg:476,rgbmode:212,rgid:304,rgs:309,rhat:[364,475],rhook:338,rhythm:472,rica:429,ricciardi:473,rich:[55,56,60,79,95,103,109,159,223,302,368,394,396,407,440,442,478],richard:[469,473,475,476],richcmpfunc:[55,79],richi:473,richter:476,rid:[80,102,106,471],riddanc:102,ridg:396,ridicul:186,right:[14,15,36,37,41,56,60,61,63,64,66,67,72,75,76,77,79,81,90,93,96,101,102,104,106,107,109,124,125,126,129,134,137,143,147,148,150,152,157,160,168,169,174,178,180,182,186,200,206,208,215,219,222,244,246,258,265,276,293,299,300,302,303,306,311,322,333,339,344,350,365,368,369,381,389,394,396,401,403,419,421,427,437,438,440,442,446,447,451,453,457,458,460,463,469,470,471,472,473,474,475,476,477],right_list:208,right_onli:208,right_volum:306,rightarrow:244,righter:102,rightli:303,rightmost:[137,150,152,169,178,219,258,304,368,369,442,474],rightshift:[157,397],rightshiftequ:397,rigo:[474,475,476],rigor:[96,222],riku:476,rindex:[368,369,477],ring:269,rip:473,ripemd160:235,risco:[304,380,386,465,471],rise:106,risk:[6,37,77,81,88,90,96,106,206,266,273,293,303,409,476],riski:[79,186],ritrovai:475,ritual:470,riverbank:84,riverbankcomput:467,rjust:[368,369,457,474],rkl:368,rl_attempted_completion_funct:334,rl_completer_word_break_charact:334,rl_completion_display_matches_hook:334,rl_completion_match:334,rl_completion_typ:334,rl_insert_text:334,rl_line_buff:334,rl_parse_and_bind:334,rl_pre_input_hook:334,rl_read_init_fil:334,rl_redisplai:334,rl_startup_hook:334,rlcomplet:[60,252,334,362,458,475,476],rle:135,rlecode_hqx:135,rledecode_hqx:135,rlen:138,rlim_infin:336,rlimit_a:336,rlimit_cor:336,rlimit_cpu:336,rlimit_data:336,rlimit_fs:336,rlimit_memlock:336,rlimit_nofil:336,rlimit_nproc:336,rlimit_ofil:336,rlimit_rss:336,rlimit_stack:336,rlimit_vmem:336,rlist:345,rlock:[60,293,362,476],rmail:273,rmd:221,rmdir:[87,304,352],rmff:146,rmode:403,rms:129,rmtree:[87,293,304,352],rnflag:138,rnopen:[138,350],road:161,robert:[473,475,476,477],robin:[307,429,453],robinson:469,robot:[60,209,252,403,470],robotfilepars:341,robotpars:[60,209,252,470],robotstxt:341,robust:[81,106,143,188,253,395,405,462,467,477],robustli:477,roc:474,rock:123,rocket_launch:162,rocki:[161,476],roddi:477,rodola:477,roi:477,role:[30,70,71,90,150,365,396,429,440],roll:[73,152,219,267,364,386,388,407,451,475,476],rollback:[364,475,476],rollov:[267,386],rom:[60,252,347],roman8:474,roman:[104,215,406,473],romberg:472,rome:96,ronach:[476,477],ronald:[333,475,476,477],roolz:200,room:[37,48,311,445],root:[63,64,67,70,71,72,73,90,98,99,107,108,109,129,132,147,155,157,168,178,181,197,201,202,204,206,221,236,246,251,265,266,277,293,300,304,305,314,316,328,337,352,363,365,366,384,392,394,396,401,426,429,431,435,436,440,463,468,470,473,474,475,476,477],root_dir:[63,352],rootlogg:99,rootobject:316,rosen:322,roskind:[88,322],ross:[333,477],rossum:[81,83,88,90,396,436,438,470,471,472,473,475,476,477],rot13:150,rot:[152,472],rot_13:150,rot_four:182,rot_thre:182,rot_two:182,rotat:[60,98,152,178,231,267,403,474,476,477],rotatingfilehandl:[60,98,99,120,266,474,476,477],rotor:[473,474],rough:[198,314,470],roughli:[83,88,102,104,106,162,222,223,255,258,290,293,303,320,355,396,440,470,476,477],rouin:438,round:[4,55,60,90,162,174,180,186,222,235,277,300,301,332,368,369,380,398,407,442,453,455,457,460,461,462,463,470,472,474,475,476,477],round_05up:178,round_ceil:[178,474],round_down:[178,474],round_floor:178,round_half_down:178,round_half_even:[178,474],round_half_up:178,round_up:178,roundbutton:212,roundoff:[81,442],roundrobin:258,roundtrip:364,roundup:[60,83],rout:[96,102,105,205,339,463,472,473,477],routin:[21,28,36,43,55,60,76,77,79,89,94,104,115,129,135,165,169,185,191,194,207,212,219,226,237,243,245,252,256,264,268,290,304,322,364,392,408,409,421,423,473,474],rovner:475,row:[60,77,88,106,140,167,244,310,398,401,446,453,460,475],row_factori:364,rowcount:364,rowid:364,royalti:438,rozerman:396,rpar:397,rpartit:[342,368,475,477],rpath:107,rpc2:[355,434,475],rpc:[60,83,244,252,254,260,276,338,438,472,473,474,475,476,477],rpc_path:[355,475],rpm:[66,69,70,82,107,468,470,473],rpm_guid:468,rpop:318,rrggbb:396,rrrgggbbb:396,rrrrggggbbbb:396,rsa:[235,278,365,438],rsampl:129,rset:[318,358],rshift:[125,302],rsplit:[368,369,474,477],rsqb:397,rss10:475,rss:[83,106,472],rst2html:71,rst:[104,208],rstrip:[88,368,369,473],rstrip_w:63,rstripextens:244,rsync:411,rsyslog:267,rtime:142,rtld_global:[168,380],rtld_lazi:185,rtld_local:168,rtld_now:[168,185,380],rtsp:411,rtspu:411,ru_idrss:336,ru_inblock:336,ru_isrss:336,ru_ixrss:336,ru_majflt:336,ru_maxrss:336,ru_minflt:336,ru_msgrcv:336,ru_msgsnd:336,ru_nivcsw:336,ru_nsign:336,ru_nswap:336,ru_nvcsw:336,ru_oublock:336,ru_stim:336,ru_utim:336,rubi:[84,96,106,463],rudiment:104,rudimentari:186,ruid:304,rule:[16,20,22,24,28,30,55,60,63,67,81,83,90,94,96,99,100,101,102,104,123,125,143,155,157,161,162,168,170,174,178,180,198,203,215,220,222,225,231,232,236,240,253,264,270,277,303,333,339,341,353,365,368,369,373,374,392,394,411,416,427,431,439,441,442,445,446,447,451,453,459,465,470,471,473,475,476,477],ruler:148,run:[1,20,24,28,30,52,55,56,60,63,64,65,66,68,70,71,72,73,75,76,77,78,79,80,81,82,83,84,86,88,90,91,93,94,95,96,98,99,100,101,102,104,106,107,108,109,111,112,113,116,123,128,130,132,134,143,144,145,149,152,157,158,161,162,165,168,169,177,178,179,184,186,193,197,206,219,225,227,228,230,235,236,238,243,245,252,253,258,264,266,267,269,270,273,288,293,296,299,303,304,305,309,315,322,325,327,334,336,337,338,341,342,343,351,355,356,357,360,361,364,365,368,369,374,380,381,389,390,391,392,393,395,396,399,401,403,404,405,408,409,410,412,415,416,419,423,437,440,441,442,446,447,449,451,452,454,455,459,461,462,463,465,466,469,470,471,472,473,474,475,476,477],run_docstring_exampl:186,run_modul:[342,465],run_nam:342,run_onc:423,run_path:[342,465,477],run_script:288,run_setup:63,run_unittest:388,run_user_cod:400,run_while_tru:132,runawai:470,runcal:[134,238,309,322],runcod:149,runctx:[134,238,322,399],runev:[134,309],runfunc:399,runner:[186,407,474,477],runni:452,runpi:[60,252,289,465,475,476,477],runpool:293,runsourc:149,runtest:[186,407],runtim:[30,45,55,58,60,63,77,79,80,81,90,95,98,104,107,111,168,173,206,222,252,267,269,303,305,308,364,368,374,396,416,421,427,436,440,447,451,465,471,473,477],runtime_library_dir:[63,72],runtime_library_dir_opt:63,runtimeerror:[20,63,96,102,124,160,206,210,256,293,311,358,368,391,422,435,442,447,454,461,473,474,475,477],runtimemodel:269,runtimewarn:[20,206,416,461],rusage_:336,rusage_both:336,rusage_children:336,rusage_self:336,rush:[438,470],russ:470,russel:474,russian:[104,150],ruthlessli:63,ruu:212,rwx:352,rwxr:[91,155,352],rxvt:93,ryan:477,rzinfo:174,s150:99,s92p:472,s_enfmt:[304,366],s_eval:338,s_exec:338,s_execfil:338,s_i:[129,366],s_iexec:[304,366],s_ifblk:[304,366],s_ifchr:[304,366],s_ifdir:366,s_ififo:[304,366],s_iflnk:366,s_ifmt:366,s_ifreg:[304,366],s_ifsock:366,s_imod:366,s_import:338,s_iread:[304,366],s_irgrp:[304,366],s_iroth:[304,366],s_irusr:[304,366],s_irwxg:[304,366],s_irwxo:[304,366],s_irwxu:[304,366],s_isblk:366,s_ischr:366,s_isdir:366,s_isfifo:366,s_isgid:[304,366],s_islnk:366,s_isreg:366,s_issock:366,s_isuid:[304,366],s_isvtx:[304,366],s_iwgrp:[304,366],s_iwoth:[304,366],s_iwrit:[304,366],s_iwusr:[304,366],s_ixgrp:[304,366],s_ixoth:[304,366],s_ixusr:[304,366],s_ji:150,s_jisx0213:150,s_k:231,s_msg:377,s_ord:231,s_reload:338,s_unload:338,sadli:[81,91],sadruddin:474,safari:419,safe:[16,19,20,28,30,37,55,63,64,76,77,79,88,90,95,99,125,131,133,138,140,143,152,167,168,169,186,194,216,222,225,235,237,256,264,265,266,273,278,293,304,308,311,313,326,330,337,338,342,346,349,350,365,369,374,380,388,391,400,404,409,416,418,425,431,442,447,451,470,471,473,476,477],safe_substitut:[369,463,474],safeconfigpars:[60,209],safeguard:472,safer:[186,311,453,473,474],saferepr:321,safest:[93,273],safeti:[7,9,60,77,90,120,139,249,293,303,337,342,343,380,391,477],safetransport:434,sai:[66,67,70,72,76,77,79,80,81,88,89,91,95,99,101,102,104,107,114,115,137,162,167,174,186,198,230,236,264,266,273,293,299,302,338,374,396,410,429,440,445,455,457,471,472,473,475,476,477],said:[30,81,87,90,93,94,106,293,401,439,440,459,460,471,472],sajip:[98,99,473,474,476,477],sake:[63,79,91,93,99,101,236,351,473],sakki:[258,477],salad:368,salari:[222,368,451],sale:83,salmela:96,salt:[165,227,235,465],sam:[84,113,346,438,470],same:[3,4,6,7,10,14,19,20,21,22,28,29,30,33,34,36,37,39,40,41,43,45,47,49,50,51,53,54,55,56,58,60,62,63,64,66,67,68,70,71,72,76,77,79,81,82,83,87,90,91,93,94,95,96,98,99,100,101,102,103,104,105,106,107,109,110,111,113,114,121,123,124,125,126,127,128,129,131,132,134,135,138,139,140,143,147,149,150,152,156,157,158,161,162,163,165,167,168,169,170,174,178,180,181,182,186,187,191,194,197,198,200,202,203,206,207,208,210,214,218,221,222,223,224,227,228,230,231,232,234,235,236,237,239,241,243,244,245,246,249,250,253,256,257,258,260,264,265,266,267,269,270,273,276,277,280,281,283,287,290,291,293,299,300,303,304,305,306,308,309,311,312,314,315,317,318,320,321,322,327,328,332,333,335,336,337,338,339,343,344,345,346,348,349,350,351,352,353,356,358,360,361,364,365,366,368,369,373,374,376,377,380,381,384,385,386,387,388,389,390,391,392,393,394,398,400,401,403,404,406,407,409,410,411,413,415,416,417,418,419,423,426,429,431,434,435,437,438,439,440,441,442,445,446,447,448,449,451,452,453,454,455,456,457,458,460,461,462,463,465,468,470,471,472,473,474,475,476,477],same_fil:208,same_quantum:178,samefil:305,sameopenfil:305,sameorigin:365,samestat:305,samp:473,sampfmt:119,sampl:[63,73,77,79,82,87,94,96,99,101,107,109,118,119,129,167,168,186,221,258,288,306,311,322,332,359,376,377,384,393,401,410,417,429,462,469,471,472,473,476,477],sample_config:[158,477],sample_r:377,sampler:306,samples:118,sampletest:407,sampletestcas:407,sampling_r:359,sampmodul:473,sampwidth:[118,376,417],samstag:174,samuel:[360,473,475],san:[341,365],sand:[104,333],sandbox:337,sane:[158,169,174,333,425],saner:30,sanit:193,saniti:30,santa:438,sape:453,saratoga:438,sarcast:472,sat:[99,174,365],satisfact:[83,365],satisfactorili:77,satisfi:[77,88,105,106,256,293,373,440,453],satur:[102,154],saturdai:[140,174],sau:222,sausag:[152,222,368],sauvag:469,savag:467,save:[1,20,28,30,37,60,71,76,77,79,81,82,88,89,90,96,98,99,106,107,113,123,128,137,139,143,145,162,167,169,174,191,203,225,227,239,244,251,258,264,267,273,293,303,304,311,322,327,333,334,339,364,380,388,392,396,403,416,434,437,439,440,447,450,451,456,458,461,472,474,475,476,477],save_bgn:239,save_end:239,save_histori:[334,458],savecount:128,savedfilenam:191,savekei:113,savetti:169,saw:[72,77,453],saw_foo:303,sax2:[60,252,275,425,427],sax2dom:428,sax2lib:431,sax:[60,143,252,275,425,426,427,428,462,470,471],saxexcept:[60,275],saxnotrecognizedexcept:[430,432],saxnotsupportedexcept:[430,432],saxparseexcept:[430,431],saxutil:[60,143,252,275,430],say_hello:92,say_hi:396,sbin:[87,168,181,333],sc0d4l0:142,sc22:380,scalabl:[345,470],scalar:[129,192,196,200,403],scale:[213,245,247,332,345,401,470,473,476],scaleb:178,scalebarvalu:219,scalefont:213,scan:[67,72,88,89,96,98,101,102,150,169,228,230,247,315,333,345,354,368,369,388,396,409,441,462,465,472,473,475,477],scanf:[60,372],scanner:[89,383,398],scatter:[472,473,477],scenario:[98,99,265,266,407],scene:[168,451,457],scgi:[60,423],sched:[60,173,252,476],schedul:[28,60,83,87,127,173,236,252,353,391,392,401,472,475,476],schema:[60,120,290,477],scheme:[55,81,96,99,102,105,126,129,150,168,174,204,243,244,273,331,356,365,368,381,384,394,409,410,411,423,440,465,470,471,473,476,477],schemenau:[470,471,472,473,475,477],schmidt:470,schmitt:476,schneider:470,schnell:476,school:[86,178,373,473],schoolbook:178,schroeder:475,schuppeni:476,schwartz:[88,101,103,476],schwartzian:103,schwertberg:471,sci:[217,438],scienc:[81,96,101,174,391],scientif:[60,95,178,369,476],scientist:391,scintilla:88,scissor:123,scm:315,scol:398,scope:[9,30,60,81,88,90,98,99,106,111,112,134,160,182,222,328,334,360,379,380,427,429,431,439,440,441,442,447,452,456,467,470,476,478],scopeid:360,score:[137,180,463],scott:[473,475],scrambl:332,scrap:[60,268],scrapdir:386,scrape:93,scraper:470,scratch:[60,91,106,192,195,197,202,295,365,426],screen:[60,81,88,93,96,104,159,169,171,191,219,222,244,269,334,374,394,395,396,398,401,454,463,470,472,473,476],screencast:106,screennam:[394,396],screenshot:477,screensiz:403,screw:102,script:[28,30,60,65,66,67,68,69,70,73,75,76,77,79,81,82,83,84,90,91,95,98,99,101,105,107,109,116,117,123,132,144,156,161,165,176,180,184,186,187,204,206,221,227,228,230,238,240,252,254,269,270,289,303,309,322,325,327,329,342,350,355,356,364,380,381,383,388,395,396,398,401,407,409,410,412,419,423,441,445,446,447,448,450,451,454,456,459,460,462,463,464,465,466,468,470,471,472,473,474,476,477,478],script_arg:63,script_from_exampl:186,script_nam:[63,423],scriptabl:[227,270],scriptbind:244,scriptfil:87,scroll:[60,93,148,169,244,252,395,396,401,458],scrollabl:[60,244,394,395],scrollbar:[219,344,396,401,403],scrollbar_callback:219,scrollcommand:[396,401],scrolledcanva:403,scrolledtext:[60,252,395,396],scrolledwindow:[60,268],scrollok:169,scsi:142,scsi_audio:142,sdeedfish:101,sdev:87,sdist:[64,69,70,71,73,75,470,471,475,477],sdk:63,sdux:64,se_restore_privileg:113,seamless:106,seamlessli:94,sean:[471,473,474,475,477],search:[1,13,20,26,28,30,43,52,56,60,62,63,66,68,72,79,81,83,87,88,89,90,94,95,98,104,129,143,150,152,156,168,173,186,200,208,213,222,230,243,244,246,249,251,253,263,264,265,266,287,288,299,304,309,311,314,322,325,326,327,338,341,351,355,356,364,368,372,374,380,386,389,394,403,407,410,419,426,429,431,435,436,439,440,441,447,450,451,452,456,458,459,460,462,463,465,467,468,470,471,472,473,474,475,476,477],search_criterion:246,search_error:249,search_funct:[13,150],searchabl:386,season:222,sebackupprivileg:113,sec:[101,142,293,392],sechrest:360,secker:477,second:[4,17,19,20,28,30,32,43,51,56,59,72,73,77,79,80,81,87,88,89,90,91,93,95,96,98,100,101,102,103,104,105,106,107,109,118,127,129,142,143,150,157,160,162,163,168,169,174,178,180,182,186,194,202,203,206,207,210,212,218,221,222,228,230,231,236,238,241,244,246,251,253,256,265,266,267,269,273,274,277,281,291,293,303,304,305,306,309,311,313,318,321,322,330,332,333,336,339,345,346,351,352,353,358,360,361,364,365,368,369,370,377,380,381,384,385,386,387,391,392,393,396,397,398,401,403,407,409,410,423,429,434,435,441,442,446,447,451,452,453,455,457,459,460,462,463,470,471,472,473,474,475,476,477],second_16:168,secondari:[103,212,322,380,449,458,459,460,461,477],secondli:[160,391],secreci:365,secret:[293,303,318,365,438,451,470],section1:158,section2:158,section:[6,10,15,30,37,42,45,48,51,55,56,60,63,64,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,83,88,90,93,96,98,99,101,104,105,107,116,119,123,131,143,148,150,152,157,158,162,167,168,174,178,186,192,205,211,213,216,217,222,230,235,241,244,246,255,258,260,265,266,270,273,292,303,304,311,315,317,318,320,322,328,333,345,346,353,360,364,365,368,369,370,372,373,374,380,384,393,395,398,403,407,409,410,411,413,423,426,427,429,431,432,434,435,438,439,440,441,442,446,447,448,451,452,453,455,457,460,461,462,467,470,471,472,473,474,475,476,477],section_divid:292,sector:128,secur:[60,69,88,99,106,107,113,131,144,161,162,166,221,237,241,246,252,254,257,266,267,276,278,293,296,304,311,313,318,328,332,337,338,349,354,355,356,358,386,409,412,423,425,427,428,429,430,434,437,470,471,472,473,475,476],security_attribut:113,see:[0,4,6,8,13,16,20,21,26,28,41,42,51,52,55,56,58,61,62,63,64,70,71,72,73,75,76,77,78,79,80,81,82,83,84,87,88,89,90,91,92,93,94,95,96,98,99,100,101,104,105,106,107,110,113,114,115,116,117,119,122,123,124,129,132,133,134,136,140,142,143,144,148,150,152,158,159,160,162,163,164,165,167,168,169,170,174,175,178,180,182,186,191,192,193,194,197,198,200,201,202,206,207,208,210,212,213,214,216,218,219,221,222,223,225,227,230,231,233,235,236,243,244,249,251,253,255,256,264,265,266,267,268,273,274,276,277,278,280,287,288,290,292,293,294,299,302,303,304,305,306,307,308,309,311,313,314,315,316,317,322,324,327,328,330,332,333,334,336,337,338,341,342,343,345,346,350,351,352,353,354,356,358,360,361,363,364,365,366,367,368,369,370,372,373,374,377,380,381,382,384,385,387,388,389,391,392,393,394,395,396,398,399,400,401,403,406,407,409,410,411,413,416,418,423,425,426,427,428,429,430,431,432,434,435,437,438,439,440,441,442,444,445,446,447,449,451,452,453,454,455,456,457,458,459,460,461,465,467,469,470,471,472,473,474,475,476,477],see_oth:241,seed:[90,293,332,365,438,465,477],seek:[82,87,104,118,139,142,146,167,184,205,207,210,222,236,256,282,287,292,339,368,384,409,437,457,470,476],seek_:256,seek_cur:[139,207,256,287,304,320,368,475],seek_end:[139,207,256,287,304,320,368,475],seek_set:[139,207,256,287,304,320,368,475],seekabl:[118,256,280,292,339,368,376,417,476],seekblock:142,seektrack:142,seem:[55,72,77,79,80,81,82,83,89,95,96,98,101,104,106,123,127,168,208,273,288,293,304,322,377,453,470,471,472,473,475],seemingli:[77,106,186,442,470],seen:[77,87,90,91,96,99,139,148,222,230,253,258,267,273,292,303,311,318,332,351,368,374,388,416,418,429,431,437,442,451,454,462,473,476],seen_add:258,segcountproc:55,segfault:[474,475],segment:[4,6,16,37,42,55,147,185,186,192,207,214,304,411,423,475,477],segreg:337,seilnacht:477,sektion:345,seld:117,seldom:374,select:[1,60,62,63,64,71,72,77,87,89,90,98,101,102,106,108,123,126,127,129,147,152,168,169,191,212,219,230,231,241,242,244,245,246,252,256,257,258,260,264,266,268,271,290,317,322,332,338,353,358,360,361,362,364,368,369,373,386,392,394,396,401,403,419,423,428,429,433,437,439,440,441,442,452,454,457,462,463,467,472,473,474,475,476,477],select_browser_lin:212,selected_alpn_protocol:365,selected_npn_protocol:365,selection_add:401,selection_get:401,selection_remov:401,selection_set:401,selection_toggl:401,selectmod:401,selector:[60,117,241,258,365,387,395,410,477],self:[3,4,11,19,24,28,38,51,55,60,63,64,68,76,77,79,82,87,90,92,94,96,99,102,103,110,114,123,125,126,127,134,152,162,164,167,168,174,178,218,219,222,223,230,240,252,253,254,257,258,260,276,292,293,300,303,309,311,334,335,338,355,361,364,368,369,373,388,394,396,403,407,410,418,426,429,434,439,440,451,452,454,456,462,463,470,471,472,473,475,476,477],self_test:87,selfref_list:311,selftest:465,sell:[83,364,438,475],selm:87,selma:96,selop:401,selva:475,sem_getvalu:293,sem_timedwait:293,sema:293,semant:[4,8,21,30,55,56,63,83,90,95,98,100,113,152,186,192,198,200,202,206,222,239,246,252,255,265,266,267,269,273,293,303,304,306,311,330,337,339,348,350,352,353,360,366,391,392,411,416,437,439,441,442,444,447,451,452,464,465,470,472,473,475,476],semaphor:[60,87,102,205,293,362,390,463,476],semaphore_func:293,semi:[108,293,303,332,397],semicircl:403,semicolon:[4,28,79,101,348,364,439,447,465,469],seminumer:178,send:[60,82,83,88,89,90,93,96,98,100,101,102,105,106,116,126,127,129,132,143,145,150,169,192,193,197,205,215,221,230,239,241,244,246,253,265,266,267,270,283,293,299,304,311,318,331,353,354,357,358,360,361,364,365,374,382,387,405,409,410,423,442,462,463,464,470,473,474,475,477],send_byt:293,send_error:132,send_ev:396,send_flowing_data:215,send_formatted_data:215,send_head:132,send_hor_rul:215,send_host:434,send_label_data:215,send_line_break:215,send_literal_data:215,send_paragraph:215,send_request:434,send_respons:132,send_sign:[374,476],sendal:[360,361,365],sendcmd:221,sender:[87,193,273,358],sendfil:423,sendmail:[87,101,193,333,358,462],sendto:[360,361],sens:[55,63,79,81,88,91,98,102,107,109,123,124,126,137,174,178,201,273,303,322,353,361,364,365,368,369,380,393,396,403,419,438,440,451,455],sensibl:[72,81,102,105,174,235,253,303,442,474,477],sensic:[55,297],sensit:[152,158,214,246,267,281,307,337,368,394,416,465,471,473,474,475,476],sent:[1,20,60,93,96,98,102,104,105,106,126,127,131,132,144,161,169,193,221,240,241,244,246,265,266,267,283,284,293,299,304,318,336,338,353,355,358,360,361,364,365,374,393,409,410,423,434,457,463,470,473,474,475,476,477],sentenc:[96,101,333,389,472,473,476],senthil:477,sentinel:[26,32,77,79,222,258,472],seo:474,sep:[56,88,96,161,174,178,221,222,244,304,305,365,368,369,472,475,476,477],separ:[16,20,28,48,52,55,56,60,63,64,66,68,72,73,75,78,80,82,87,88,92,93,95,98,99,100,101,103,104,106,107,109,114,123,132,143,147,148,150,152,160,161,167,168,170,174,178,180,186,191,192,197,200,214,215,219,222,230,236,241,244,246,256,260,264,265,266,273,281,283,293,303,304,305,309,314,317,327,328,332,333,339,342,346,351,356,358,361,364,365,368,369,374,387,388,389,391,393,395,396,399,407,409,411,415,418,419,423,435,438,439,440,442,445,446,447,452,453,457,460,461,462,463,465,469,470,472,474,475,476,478],septemb:[446,470],seq1:[96,302,407,470],seq2:[19,96,302,407,470],seq:[32,56,88,214,222,258,279,293,302,332,368,440,453,470,474],seq_of_paramet:364,seq_typ:407,seqdict:473,seqnum:463,sequenc:[2,4,13,19,27,28,30,32,34,37,43,44,49,56,58,60,63,72,73,79,81,82,87,90,93,95,96,99,101,104,113,124,125,139,143,149,150,152,157,162,167,168,169,180,182,186,198,201,203,205,206,210,215,222,230,236,252,256,257,258,260,261,264,273,279,281,290,293,302,303,304,308,311,312,313,314,317,326,328,332,333,335,343,345,346,352,360,364,365,369,372,380,384,385,392,396,398,401,403,404,406,407,409,410,413,415,416,418,426,429,430,439,442,443,445,446,447,451,452,456,460,463,470,471,472,473,474,476,477],sequence1:[96,470],sequence2:[96,470],sequence2st:308,sequence3:96,sequence_of_str:139,sequenceinclud:[302,477],sequencematch:[60,372,471,475,476],sequencen:[96,470],sequenti:[60,87,102,122,210,256,293,322,368,391,463],serbian:150,seri:[6,28,42,83,90,95,96,101,103,109,123,135,152,167,168,178,222,258,303,328,381,394,409,423,442,452,460,461,472,474,475,476,477,478],serial:[28,36,60,99,138,141,142,201,252,260,265,267,310,350,353,380,429,457,470,476,477],serialcooki:161,serialis:[99,342],serializ:[161,260],serialnum:373,serialnumb:365,seriou:[81,95,98,186,206,284,374],serious:427,serv:[4,77,81,83,90,98,111,144,178,186,187,198,222,236,239,240,243,266,293,308,327,348,354,364,365,403,413,423,429,446,451,452,454,474],serve_forev:[132,293,354,355,361,423,434,475,476],serve_until_stop:99,server:[60,71,83,87,88,93,95,96,98,102,105,107,117,126,143,144,161,162,168,183,192,193,195,221,241,244,246,252,254,257,265,266,267,269,270,293,299,304,318,327,338,345,354,358,360,364,380,382,385,391,396,407,409,410,438,462,463,471,472,473,474,475,476,477],server_activ:[355,361,476],server_address:[132,361,423],server_auth:365,server_bind:[355,361,476],server_class:[132,423],server_clos:361,server_document:187,server_hostnam:365,server_log:[96,475],server_nam:[132,187,423],server_name_callback:365,server_port:[132,423],server_sid:365,server_softwar:423,server_thread:361,server_titl:187,server_vers:[132,354],servernam:293,serverproxi:[60,254,355],serversocket:102,servic:[60,83,102,105,106,127,191,222,242,252,253,291,293,304,315,335,345,358,360,361,365,392,405,425,434,448,465,467,469,470,474,477],service_pack:[380,477],service_pack_major:[380,477],service_pack_minor:[380,477],service_unavail:241,servicenam:360,servo:101,session:[88,89,98,106,126,157,162,186,206,221,241,293,311,334,358,364,365,380,409,412,447,449,458,461,465,474],session_stat:365,set1:407,set2:407,set:[2,3,4,8,9,11,13,14,15,16,19,20,21,23,24,26,28,30,31,33,34,36,37,39,42,43,45,49,50,51,52,53,54,55,56,58,60,63,64,66,68,72,73,76,77,79,80,81,82,84,87,88,89,90,91,93,94,96,98,99,100,101,102,104,105,107,109,113,116,117,118,119,123,125,126,127,128,132,134,137,138,139,140,141,142,143,145,146,148,149,150,152,153,157,158,161,162,163,165,167,168,169,170,171,173,174,175,177,178,180,182,186,187,191,192,193,195,197,198,200,201,202,203,204,206,207,212,213,215,216,219,221,222,225,228,229,230,235,239,241,243,245,246,247,249,252,253,256,257,258,259,260,264,265,266,267,269,270,273,274,275,276,279,281,282,283,287,288,290,291,292,293,294,295,296,299,302,303,304,305,306,307,309,311,313,315,318,320,321,322,327,328,330,333,334,335,336,337,339,340,341,342,344,345,350,351,352,354,355,356,358,360,361,364,366,369,370,371,374,376,377,380,381,382,383,384,385,386,387,388,389,391,392,394,395,399,400,401,405,406,407,409,410,411,412,413,414,415,416,417,418,419,423,424,426,427,429,430,431,432,434,435,436,437,439,440,441,446,447,449,451,456,458,459,460,461,462,463,464,465,466,467,470,471,472,475,476,477,478],set_al:30,set_allowed_domain:162,set_alpn_protocol:365,set_app:423,set_author:364,set_blocked_domain:162,set_boundari:[192,200],set_break:134,set_browser_fonts:212,set_browser_fontstyl:212,set_browser_specialkei:212,set_browser_toplin:212,set_button:212,set_call_back:212,set_callback:77,set_charset:200,set_children:401,set_choic:212,set_choice_fonts:212,set_choice_fontstyl:212,set_ciph:365,set_complet:[334,340],set_completer_delim:334,set_completion_display_matches_hook:334,set_conflict_handl:303,set_continu:134,set_conversion_mod:168,set_cooki:162,set_cookie_if_ok:162,set_counter_bound:212,set_counter_precis:212,set_counter_return:212,set_counter_step:212,set_counter_valu:212,set_curr:290,set_dat:273,set_debug:225,set_debuglevel:[221,241,299,318,358,385],set_default:[123,303],set_default_typ:200,set_default_verify_path:365,set_dial_bound:212,set_dial_valu:212,set_displai:442,set_ecdh_curv:365,set_errno:[168,476],set_event_call_back:212,set_execut:[63,293],set_flag:273,set_form_posit:212,set_from:273,set_graphics_mod:212,set_history_length:334,set_include_dir:63,set_info:273,set_input:212,set_input_color:212,set_input_return:212,set_label:273,set_last_error:[168,476],set_librari:63,set_library_dir:63,set_lineno:[182,393,473],set_link_object:63,set_liter:109,set_loc:[138,350],set_menu:212,set_next:134,set_nonstandard_attr:162,set_npn_protocol:365,set_ok:162,set_option_negotiation_callback:385,set_output_charset:230,set_param:200,set_pasv:[221,471],set_payload:[192,193,200,201,202],set_polici:162,set_posit:424,set_positioner_xbound:212,set_positioner_xvalu:212,set_positioner_ybound:212,set_positioner_yvalu:212,set_pre_input_hook:334,set_progress_handl:364,set_proxi:[410,434],set_python_build:63,set_quit:134,set_recsrc:306,set_return:134,set_reuse_addr:127,set_runtime_library_dir:63,set_seq1:180,set_seq2:180,set_seq:180,set_sequ:273,set_server_document:187,set_server_nam:187,set_server_titl:187,set_servername_callback:365,set_siz:472,set_slider_bound:212,set_slider_precis:212,set_slider_return:212,set_slider_s:212,set_slider_step:212,set_slider_valu:212,set_spac:215,set_startup_hook:334,set_step:134,set_subdir:273,set_sys_last_var:20,set_termin:126,set_threshold:225,set_tim:212,set_trac:[134,186,309],set_tunnel:241,set_typ:200,set_unittest_reportflag:186,set_unixfrom:200,set_until:134,set_url:341,set_usag:303,set_userptr:171,set_valu:99,set_vis:273,set_wakeup_fd:[20,353,476],setacl:[246,472],setannot:246,setarrowcursor:219,setattr:[88,95,123,222,251,303,418,451,461,470],setattrfunc:[55,79],setattribut:426,setattributen:426,setattributenod:426,setattributenoden:426,setattrofunc:[55,79],setbas:328,setbg:403,setblock:[102,360,365],setboundari:192,setbytestream:432,setcbreak:402,setchannel:119,setcharacterstream:432,setcheckinterv:[28,87,380,461,473],setcomp:125,setcomptyp:[118,376,417],setconfig:119,setcontenthandl:[432,470],setcontext:[178,279],setcreatorandtyp:269,setcurr:279,setdaemon:[391,476],setdefault:[81,152,339,368,423,440,470,473],setdefaultencod:[380,470],setdefaulttimeout:[105,360],setdlopenflag:[380,461,472],setdocumentloc:431,setdtdhandl:432,setegid:304,setencod:432,setentityresolv:432,setenv:63,seterrorhandl:432,seteuid:304,setfeatur:432,setfillpoint:119,setfirstweekdai:140,setfloatmax:119,setfmt:306,setfont:213,setformatt:[98,99,265,267],setframer:[118,376,417],setgid:304,setgroup:304,seth:403,sethead:403,seti:403,setinfo:377,setinteg:290,setit:258,setitem:[302,339],setitim:[353,476],setlast:279,setlasterror:168,setlevel:[98,99,265,293,473],setliter:348,setlocal:[56,169,264,369,432,463],setloggerclass:265,setlogmask:382,setmark:118,setmaxconn:410,setmod:291,setnam:391,setnchannel:[118,376,417],setnfram:[118,376,417],setnomoretag:348,setopt:259,setparam:[118,119,376,417],setparamentitypars:328,setparamet:306,setpassword:435,setpath:213,setpgid:304,setpgrp:304,setpo:[118,376,403,417],setposit:403,setprofil:[293,380,391,461,472],setproperti:[290,432],setpublicid:432,setqueues:119,setquota:246,setraw:402,setrecsrc:306,setrecursionlimit:[311,380,461,470],setregid:304,setresgid:[304,477],setresuid:[304,477],setreuid:304,setrlimit:336,setsampfmt:119,setsampwidth:[118,376,417],setscrreg:169,setsid:304,setsiz:79,setslic:302,setsockopt:[360,365,477],setstat:332,setstr:290,setstream:290,setsystemid:432,setsyx:169,settabl:[283,416,470,472],settarget:267,setter:[43,51,79,94,222,476],settiltangl:403,settimeout:[360,365,410,473],settl:476,settrac:[134,293,380,391,461,472],settscdump:380,settypecr:243,setuid:304,setundobuff:403,setup:[28,60,63,64,67,68,69,70,71,73,75,77,79,93,105,107,184,186,361,364,365,388,393,403,405,407,465,467,469,470,471,472,473,475,476,477],setup_environ:423,setup_except:182,setup_fin:182,setup_keyword:473,setup_loop:182,setup_testing_default:423,setup_with:182,setupclass:[60,179,477],setupmodul:[60,179,477],setupterm:169,setuptool:[62,184,467,477],setvalu:113,setvalueex:113,setvbuf:[21,222],setwatchcursor:219,setwidth:119,setworldcoordin:403,setx:[94,114,222,403],seven:[140,161,178,368,381],seventh:384,sever:[24,28,30,37,55,58,63,64,66,72,76,77,79,80,81,83,84,86,87,88,90,94,95,96,98,99,101,102,104,105,106,107,109,123,140,149,150,152,157,159,168,169,178,182,186,192,194,203,205,206,215,216,221,222,236,252,253,255,256,258,265,266,267,273,275,290,293,298,303,305,306,311,317,319,321,322,325,333,335,339,357,358,360,361,365,366,368,374,384,391,394,398,399,400,401,403,406,407,410,416,418,420,422,425,431,434,437,438,440,441,445,447,450,452,454,456,457,460,461,464,467,470,472,473,474,475,476,477],seymour:403,sf_append:[304,366],sf_archiv:[304,366],sf_immut:[304,366],sf_nounlink:[304,366],sf_snapshot:[304,366],sftp:411,sgi:[60,63,212,231,245,248,252,259,381,390],sgid:304,sgml:[60,239,240,252,275,433,476],sgmllib:[60,239,240,252,275],sgmlop:470,sgmlparseerror:348,sgmlparser:[239,348],sha1:[235,475,477],sha224:[235,475,477],sha256:[235,475,477],sha2:365,sha384:[235,475,477],sha512:[235,475,477],sha:[60,166,235,252,278,338,415,475,476],shadow:[60,88,89,95,165,233,252,314,324,408,462,475],shall:[51,431,438],shallow:[28,60,173,186,208,252,311,346,368,460],shalt:369,shape:[6,60,222,332,368,395,476],shapelist:403,shapenam:403,shapes:403,share:[6,28,30,36,37,51,56,60,62,63,68,70,72,75,77,79,80,82,87,90,102,107,108,120,123,163,178,205,207,230,235,237,249,251,252,258,264,265,269,276,278,287,300,303,304,311,325,332,336,349,350,360,361,362,364,366,369,380,390,391,392,394,396,405,407,408,423,435,437,439,440,442,451,452,461,463,465,473,474,475,476,477],shared_arrai:293,shared_object_filenam:63,shared_valu:293,sharedctyp:[60,362],sharedvalues_func:293,sharepoint:435,sharewar:84,shatter:83,shawn:476,she:380,shebang:[106,459,468],shed:311,sheesh:472,sheet:[100,140],sheila:99,shelf:350,shell:[30,60,63,77,79,82,83,88,89,90,93,96,107,108,113,143,155,158,159,169,186,214,232,252,257,260,299,303,304,305,317,327,351,364,380,395,396,407,408,449,450,458,459,461,462,465,467,468,470,472,474,477],shellexecut:304,shelv:[60,87,121,188,252,276,310,311,413,470,473],shepherd:[470,473],shgetspecialfolderpath:64,shift:[41,60,169,170,178,244,293,302,304,368,401,423,440,444,453,470,472,474,476,477],shift_expr:[442,443],shift_ji:150,shift_jis_2004:150,shift_jisx0213:150,shift_path_info:423,shiftji:150,shiftjis2004:150,shiftjisx0213:150,shik:[474,475],ship:[84,90,95,106,138,142,244,276,407,425,467,469,470,473,477],shlex:[60,158,220,252,309,313,374],shoddi:79,shoddy_incr:79,shoddy_init:79,shoddy_method:79,shoddytyp:79,shoe:101,shop:[452,464],shopkeep:452,short_arrai:168,short_opt:63,short_slic:442,shortcom:[6,42,265,273,473],shortcut:[56,60,64,73,102,186,219,243,244,310,333,368,384,474,476],shortdescript:407,shorten:[79,91,226,335],shorter:[88,90,101,198,222,258,303,312,364,373,442,450,453,457,470,471,474,476,477],shortest:[96,194,222,258,455,470,475,477],shorthand:[20,79,81,88,234,360,389,396,400,416,439,440,442,451,473,474],shortli:[77,79,457,463],shortmessag:[105,132],shortstr:446,shortstringchar:446,shortstringitem:446,shot:[60,88,122,345],should:[1,3,4,6,8,13,16,19,20,21,22,24,26,28,29,30,31,32,36,37,38,43,45,48,50,51,52,53,54,55,56,58,59,60,63,64,67,68,70,71,72,73,75,76,77,79,80,81,82,86,88,89,90,91,92,93,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,114,115,117,118,123,124,126,127,128,129,131,132,133,134,135,137,138,139,140,141,142,143,145,146,147,148,149,150,151,157,158,159,160,161,162,163,164,167,168,169,172,174,175,178,180,181,182,185,186,189,191,192,193,194,195,197,198,199,200,201,202,203,204,205,206,207,212,215,218,219,221,222,223,225,227,228,230,231,235,238,239,240,241,245,246,248,249,251,256,258,260,264,265,266,267,268,270,271,273,276,280,281,282,283,284,287,290,291,292,293,297,298,299,300,303,304,305,306,308,309,311,314,315,317,318,320,321,322,323,324,326,328,332,333,334,335,336,338,339,342,343,344,346,348,350,352,354,355,357,358,360,361,364,365,366,368,369,371,373,374,376,377,380,384,385,386,388,389,390,391,392,393,394,396,398,399,400,401,403,404,405,407,409,410,411,412,413,415,416,417,418,420,422,423,424,426,427,429,430,431,432,433,434,435,437,438,439,440,441,442,443,445,446,447,451,452,453,454,455,459,460,461,464,465,467,468,469,470,471,472,473,474,475,476,477],shouldflush:267,shouldn:[6,60,88,101,204,219,265,274,304,333,364,365,369,380,407,409,460,466,471,472,474,475,476],shouldstop:407,show:[28,30,63,67,71,76,77,78,79,91,92,93,94,95,96,98,99,102,104,105,106,114,123,125,126,137,143,145,150,152,153,157,162,164,168,171,178,180,186,191,198,208,212,222,241,244,246,255,258,273,287,293,302,303,311,322,335,356,360,364,365,368,369,393,394,396,397,399,400,401,403,407,418,434,446,450,451,454,455,460,463,465,470,471,472,473,474,475,476,477],show_choic:212,show_compil:63,show_file_selector:212,show_form:212,show_input:212,show_messag:212,show_miss:399,show_object:212,show_quest:212,shown:[20,30,37,72,73,77,80,91,93,96,98,99,100,103,105,107,125,152,178,180,186,191,244,265,266,303,309,322,327,333,343,369,374,392,394,401,403,411,416,418,450,452,454,476],showparti:274,showsyntaxerror:149,showtraceback:149,showturtl:403,showwarn:[416,476],showwindow:374,shrink:[53,226,474],shrt:368,shrug:102,shrunk:471,shtml:477,shttp:411,shtull:472,shuffl:[87,102,332,333],shut:[76,102,360,361,391,403,440,463,465,473,477],shut_rd:360,shut_rdwr:[360,365],shut_wr:360,shutdown:[102,113,205,246,265,271,293,360,361,365,391,407,465,476],shutil:[60,87,99,122,211,222,234,252,304,368,374,384,462,473,476,477],sibl:[88,109,123,222,401,426,461],sicp:96,side:[13,26,28,60,77,79,81,87,88,96,99,101,102,105,125,137,143,147,152,157,162,169,180,200,204,221,241,257,264,293,299,314,340,350,360,361,368,369,374,377,388,391,396,401,407,418,423,442,447,452,453,458,460,461,463,470,471,472,473,474,475,477],sidebar:1,sidestep:474,sidh:475,sig:[62,69,72,83,108,150,304,353,467,470,471,473,477],sig_dfl:353,sig_ign:353,sigabrt:[304,353],sigact:52,sigalrm:353,sigchld:353,sigfp:[216,353],sight:[77,129],sighup:353,sigil:353,sigint:[20,82,293,353,407],siginterrupt:[353,476],sigkil:[374,474],sigma:332,sign:[16,34,55,60,71,88,124,129,135,147,150,152,155,157,168,169,174,178,192,200,203,218,222,228,257,264,267,274,277,293,303,306,309,339,368,369,373,391,392,409,437,440,442,446,457,459,460,463,469,471,472,474,475,476,477],signal:[6,20,28,52,55,60,89,96,101,128,129,168,169,179,186,206,216,241,252,256,257,265,266,277,293,301,303,304,317,333,336,345,351,365,369,374,377,380,390,391,392,398,410,431,434,454,470,471,472,473,474,475,476,477],signalnum:353,signatur:[55,60,88,94,98,99,104,116,151,152,192,208,222,223,227,243,244,253,256,265,293,303,311,365,372,374,403,431,434,437,451,453,476],signifi:[16,100,185,221,354,364,365,440,446,447],signific:[4,30,36,82,96,101,102,104,150,170,178,182,186,258,276,277,311,322,368,369,380,391,407,440,445,446,455,463,465,470,471,472,474,475,476,477],significand:[369,380],significantli:[88,256,308,346,365,427,465,471,473,474,476,477],signoff:318,signon:102,signum:[87,353,377],sigpip:[353,374],sigpol:377,sigprof:353,sigquit:353,sigsegv:353,sigterm:[293,353,374,476],sigvtalrm:353,sigwinch:169,sigxcpu:336,silenc:[123,340,407,414,477],silent:[4,63,92,98,99,104,206,210,213,222,246,249,265,267,273,304,306,309,317,322,356,369,374,390,411,447,452,465,470,474,475,477],silicon:[142,213,231],silli:[79,168,303,311],sillier:303,similar:[4,6,19,20,24,28,41,51,55,56,58,59,63,64,72,76,77,79,81,82,87,88,89,91,92,94,96,98,99,100,101,104,105,106,107,109,137,140,141,143,147,149,150,152,158,162,163,167,168,169,172,176,178,180,188,192,200,202,222,226,228,230,231,233,236,240,241,244,253,256,258,264,266,273,278,281,291,293,300,303,304,309,314,317,318,322,324,327,333,335,338,339,345,346,351,354,358,360,361,363,365,368,369,370,381,384,388,389,394,400,403,407,409,411,418,423,425,426,427,430,433,437,440,442,446,447,449,451,453,454,457,458,461,465,467,470,471,472,473,474,475,476,477],similarli:[24,63,81,88,93,96,101,104,107,109,123,143,160,174,182,186,214,222,225,266,273,293,311,313,322,330,339,359,360,365,368,373,374,380,393,394,407,424,442,447,453,470,474,475,476,477],similiar:90,simionato:473,simon:473,simpl:[28,30,55,59,60,64,66,69,72,73,75,76,78,79,83,84,87,88,89,91,92,93,94,95,96,99,102,103,104,105,107,111,115,117,121,123,127,128,129,140,143,148,150,152,157,161,165,168,174,179,180,191,192,193,200,202,203,215,220,221,222,225,230,234,235,239,245,246,252,254,256,260,266,273,275,283,287,293,300,303,306,308,309,310,311,316,322,332,333,338,342,355,358,360,368,369,385,390,393,395,399,400,401,404,405,407,408,410,412,416,418,419,420,422,424,425,426,427,429,430,434,435,439,440,442,444,450,451,452,453,454,456,457,460,462,465,470,471,474,475,476,477,478],simple_app:423,simple_exampl:[98,99],simple_logging_config:98,simple_logging_modul:98,simple_serv:[60,254,475],simple_sl:442,simple_stmt:[439,443],simplecooki:161,simpleexampl:[98,99],simplefilt:[388,416,476,477],simpleformatt:98,simplehandl:[423,470],simplehttp:354,simplehttprequesthandl:[144,293,354],simplehttpserv:[60,132,144,252,254,293],simplehttserv:354,simplejson:[476,477],simplemind:88,simplequeu:293,simpler:[4,6,60,64,78,81,91,93,99,101,103,106,107,123,143,152,222,230,251,333,368,369,407,418,427,431,450,453,454,470,471,472,473,475,477,478],simplest:[28,67,72,73,76,77,79,96,98,101,102,105,106,123,127,128,141,150,167,178,186,204,236,308,311,317,333,365,391,407,440,442,451,461,462,463,465,470,472,473],simplewidgettestcas:407,simplexmlrpcrequesthandl:[355,474,477],simplexmlrpcserv:[60,187,252,254,434,462,472,474,475,476,477],simpli:[28,30,45,55,63,66,67,68,72,76,77,79,81,82,87,88,89,90,91,92,93,95,96,99,100,101,104,107,117,123,127,140,145,148,150,152,168,169,174,178,186,202,215,219,221,222,230,239,240,243,244,247,253,256,260,266,269,274,280,293,303,304,309,311,315,316,328,333,342,343,348,353,358,360,361,364,366,368,369,374,380,386,407,410,416,418,419,423,425,426,427,434,438,440,447,451,454,455,457,460,461,467,470,471,472,473,474,475,476,477],simplic:[56,79,106,260,470,472],simplif:207,simplifi:[6,24,26,28,58,79,81,89,90,94,96,101,103,104,105,106,126,150,174,176,197,208,223,273,293,333,338,360,361,394,398,401,413,426,439,442,462,463,472,473,474,475,476,477],simplist:99,simul:[20,60,92,93,94,103,169,234,236,273,308,332,368,372,373,403,413,471,472],simultan:[28,55,99,100,222,232,244,256,273,290,350,353,361,391,394,403,460,476],sin6_flowinfo:360,sin6_scope_id:360,sin:[88,147,178,277,440,451,473],sinc:[12,16,19,20,22,24,28,30,40,51,52,55,63,64,66,67,70,72,73,75,76,77,79,81,82,83,87,88,90,92,93,94,95,98,99,100,101,104,105,106,107,109,110,111,113,119,124,133,134,135,138,139,142,143,149,152,155,157,160,161,162,165,167,168,169,174,175,178,180,181,185,186,192,195,196,197,200,202,203,206,212,213,217,219,222,225,230,231,234,236,239,244,245,246,247,249,251,256,259,260,264,266,267,269,271,273,274,277,278,279,280,282,283,287,292,293,294,297,299,302,303,304,305,306,308,309,311,313,315,317,320,321,322,328,333,337,338,339,345,346,348,349,350,351,352,353,360,361,363,364,365,367,368,369,370,373,377,380,384,386,388,389,391,392,396,399,401,403,404,405,407,409,410,412,413,415,416,423,426,427,429,430,431,434,436,437,439,440,441,442,445,446,450,451,452,453,454,455,457,458,459,460,461,465,468,469,470,471,472,473,474,475,476,477],sine:[88,147,178,277],sine_t:451,singapor:429,singl:[4,13,20,26,28,30,42,50,51,54,55,56,58,59,60,69,70,72,73,75,77,79,81,82,83,89,90,93,94,95,96,97,100,101,102,103,104,105,106,107,123,124,125,127,128,134,135,143,149,150,151,152,156,157,158,160,162,167,168,169,170,174,178,180,182,186,191,192,194,197,198,200,202,206,210,214,215,219,221,222,230,235,236,237,238,239,244,251,253,256,258,263,265,267,273,277,278,279,287,290,292,293,299,303,304,308,309,311,314,315,317,318,321,322,328,333,336,339,341,348,349,351,354,355,360,361,364,365,368,369,373,374,377,379,380,381,388,389,396,398,399,400,401,405,407,409,410,411,413,415,416,418,420,423,424,426,429,431,433,434,435,440,442,443,445,446,447,450,451,452,453,456,457,458,459,460,463,465,470,471,472,473,474,475,476,477],single_input:443,singleton:[15,40,48,49,55,77,88,90,276,333,368,403,434,440,442,453,471],singular:230,sinh:[147,277],sio_:360,sio_rcval:360,sioux:[219,284],sip:[82,307,411],sir:[429,452],sister:87,sit:[311,394,433],site:[60,62,72,83,88,96,104,105,106,107,158,161,162,204,221,222,252,265,304,314,329,337,341,358,380,381,410,412,430,449,456,464,465,469,470,475,477,478],sitecustom:[88,107,356,380,449,477],sitedir:356,situat:[28,30,37,55,62,63,67,77,79,81,88,95,96,98,99,100,102,103,105,106,107,123,143,150,192,196,202,206,216,230,244,256,273,293,303,317,338,358,368,374,377,380,391,414,416,426,440,448,451,452,453,455,472,477],six:[100,103,157,174,253,303,333,364,386,411,415,435,476],sixteen:253,sixth:472,sizabl:[464,471,472],size:[3,4,6,7,16,24,26,30,33,36,37,47,48,50,51,52,53,55,56,60,77,79,81,82,87,89,93,98,99,101,102,104,118,119,120,123,124,126,129,132,134,139,141,142,146,150,152,165,167,169,180,182,212,215,219,221,222,231,235,236,241,244,245,246,247,256,260,264,267,271,278,280,287,292,293,299,304,305,306,315,317,318,319,322,328,330,334,335,336,349,352,354,358,359,360,361,364,366,367,368,369,372,374,376,377,380,384,386,390,391,394,396,401,403,407,409,418,424,426,435,437,440,457,460,463,470,471,472,473,474,475,476,477],size_or_initi:293,size_t:[16,29,34,37,50,56,92,168],sizegrip:[60,395],sizehint:[150,345,368],sizeof:[30,37,55,79,92,168,185,315,373],sizeof_digit:[380,477],sji:[150,174],sjis2004:150,sjis_2004:150,sjisx0213:150,sjoerd:[368,457,470,476],sketch:[162,186,452,475,476],skill:[83,457],skim:464,skimp:186,skip:[6,13,28,30,51,60,63,79,87,88,96,100,101,102,103,104,105,134,146,150,156,158,160,168,174,179,186,199,204,208,210,221,222,255,258,260,273,274,292,309,339,346,351,356,366,373,384,401,431,438,439,447,454,463,465,470,472,473,474,475,476,477],skip_accept_encod:241,skip_blank:63,skip_curdir:156,skip_host:241,skipif:407,skipinitialspac:167,skipkei:260,skippedent:431,skipston:419,skiptest:[388,407,477],skipunless:407,skipunlesshasattr:407,skit:[77,186,450],slackbook:468,slackwar:468,slant:470,slash:[63,72,73,81,101,107,181,303,304,305,327,397,411,423,435,436],slashequ:397,slate:186,slave:[299,304,317,323,396],sle257ohy9fvq07z:365,sleep:[87,96,99,169,231,271,293,343,353,392,476],slen:99,slew:198,slice:[6,15,33,47,53,60,88,90,96,100,124,125,129,152,157,159,163,168,182,201,206,222,228,258,287,302,304,305,332,333,346,368,369,404,431,439,440,446,447,452,453,457,460,461,470,472,474,475,476,477,478],slice__:440,slice_item:442,slice_list:442,slicelength:49,sliceobj:157,sliceop:443,slicetyp:[49,404],slide:[87,104,427],slider:212,slideshow:427,slight:[63,91,99,162,207,339,470,473],slightli:[30,55,72,79,81,82,83,84,88,92,94,96,98,103,105,107,167,230,236,239,256,273,303,304,307,309,311,321,322,332,338,368,374,377,411,438,455,457,470,472,473,474,475,476,477],slimmer:267,sln:64,sloppi:81,slot:[15,31,41,43,51,54,55,60,79,150,182,205,290,293,330,368,440,442,470,471,472,474,475,476],slow:[28,83,93,102,121,137,139,152,219,235,256,292,293,350,361,377,403,415,435,436,450,453,470,471,473,474,476],slowdown:87,slower:[88,95,101,102,106,235,256,293,350,403,463,473,474,476],slowest:[234,403,437],slowli:[77,88,90,99],small:[4,28,37,48,51,55,60,70,72,77,81,83,87,88,93,99,101,102,104,106,150,159,162,168,177,178,180,186,219,244,252,256,258,270,273,277,293,299,304,322,327,332,350,353,360,368,388,391,394,407,423,425,429,437,446,447,450,451,452,453,460,461,463,467,470,471,472,473,474,475,476,477],small_stmt:443,smaller:[29,37,88,93,101,102,106,168,174,178,180,222,236,238,259,322,368,373,381,401,403,411,427,437,440,442,446,453,455,471,473,474,475,476,477],smallest:[96,104,124,174,178,222,236,277,304,368,407,463,473,474,475,476],smalltalk:[87,96,152,407,451,471],smarrita:475,smart:[64,95,192,244,472],smartcooki:161,smaxcol:169,smaxrow:169,smb:95,smincol:169,sminrow:169,smith:[474,475,476,477],sml:258,smooth:[247,259],smtp:[60,83,87,98,192,193,252,254,267,462,470,472,476],smtp_code:358,smtp_error:358,smtp_ssl:[358,476],smtpauthenticationerror:358,smtpconnecterror:358,smtpd:[60,252,254],smtpdataerror:358,smtpexcept:358,smtphandler:[60,98,120,266],smtpheloerror:358,smtplib:[60,87,192,193,197,252,254,267,462,472,476],smtprecipientsrefus:358,smtpresponseexcept:358,smtpsenderrefus:358,smtpserver:[60,254],smtpserverdisconnect:358,snan:[178,477],snap:127,snapshot:366,snd:[60,268,376],snd_alia:422,snd_async:422,snd_filenam:422,snd_loop:422,snd_memori:422,snd_nodefault:422,snd_nostop:422,snd_nowait:422,snd_purg:422,sndctl_dsp_setfmt:306,sndctl_dsp_sync:306,sndhdr:[60,201,252,286],sndr:359,sndt:359,sneakili:472,snew:411,sni:365,snif:[105,311],sniff:167,sniffer:[167,360],snippet:[60,66,81,91,99,161,177,252,266,365,453,469,472,473,475],snmp:102,snowman:99,snprintf:[16,472],so_:360,so_reuseaddr:[127,360],so_setfib:477,soapbox:[60,179],sock:[101,102,126,127,241,322,361,365],sock_:360,sock_dgram:[267,360,361,477],sock_raw:360,sock_rdm:360,sock_seqpacket:360,sock_stream:[99,102,127,267,360,361,365,477],sockaddr:360,sockaddr_in6:360,socket:[60,83,90,96,97,98,99,101,104,132,150,163,202,205,206,221,241,244,246,252,254,257,265,266,267,293,304,318,321,338,339,345,352,353,358,361,366,368,384,385,396,409,410,418,423,440,450,463,470,471,472,473,474,475,476,477],socket_typ:361,sockethandl:[60,98,99,120,266],socketpair:[360,474],socketserv:[60,99,132,252,254,354,355,360,476,477],sockettyp:360,sockstream:102,socktyp:[267,360,477],soft:[169,336],softspac:[21,368],softwar:[1,28,60,61,62,63,64,72,80,84,86,88,89,90,96,98,104,106,107,108,113,132,143,150,169,179,186,204,205,228,242,244,252,259,264,273,304,332,365,423,434,450,460,462,467,468,469,470,471,473,474,476,477,478],soh:170,sol_:360,sol_socket:360,solari:[28,60,63,64,70,242,315,319,375,381,390,392,470,477],sole:[30,63,67,81,91,100,159,178,293,418,454,477],solem:299,solicit:[66,148],solid:[70,169],solidu:[406,446],solitair:86,solitari:293,solut:[30,60,62,64,77,81,82,84,87,88,90,94,96,100,101,102,104,106,107,108,178,236,252,254,333,353,361,364,380,461,462,464,469,470,472,473,474,475,476,477],solv:[28,81,82,87,88,90,92,96,101,104,106,127,244,293,350,384,439,460,464,472,473,475],somaxconn:360,some:[1,2,6,18,20,28,30,37,38,41,51,52,53,55,56,60,62,63,64,66,70,72,75,76,77,79,83,86,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,107,108,109,114,118,119,121,123,124,129,132,135,138,141,143,147,148,149,152,156,157,158,160,161,162,167,168,169,172,173,174,178,180,185,186,191,192,194,195,196,199,200,201,202,203,206,207,208,210,212,213,215,216,218,219,221,222,223,225,226,230,231,234,235,236,238,239,240,243,244,245,246,247,249,252,255,256,257,258,259,260,264,265,266,267,271,273,274,276,277,280,281,282,284,291,293,299,302,303,304,305,306,308,311,312,315,319,320,322,325,326,328,332,333,336,337,338,339,345,348,351,353,356,358,360,361,362,364,365,366,368,369,370,374,380,381,382,384,385,386,388,389,390,391,392,396,397,400,401,403,404,405,407,408,409,410,412,415,416,419,423,425,426,427,429,430,431,432,434,435,437,439,440,441,442,445,446,447,449,450,451,452,453,454,455,457,458,459,460,461,462,464,465,468,469,470,471,472,473,474,475,476,477],some_conn_id:99,some_func:379,some_funct:99,some_handler_inst:105,some_int:88,some_iter:109,some_method:434,some_object:[79,88],some_rlock:391,some_tag:427,some_tupl:88,some_typ:168,some_url:409,some_vari:309,someact:396,somebodi:105,someclass:[109,470],somedai:311,somedata:316,someexcept:407,somefil:[199,230,304,313,399],somehow:[77,81,138,293,384,461,476,477],someiter:167,somelogg:99,somemoredata:316,somenam:368,somenamedtupl:152,someon:[64,77,79,86,88,102,104,107,358,386,429,440,443,477],someone_els:193,someopt:396,somepackag:108,someproxi:409,someserv:105,somestr:374,sometag:429,someth:[6,16,19,28,31,63,70,71,77,79,81,83,87,88,89,90,91,92,93,95,96,98,99,100,101,102,106,107,124,133,134,136,143,157,168,222,228,236,253,258,265,293,303,304,311,319,322,328,336,346,357,361,364,365,376,380,384,388,401,407,410,417,418,423,426,434,451,457,460,463,470,471,472,473,474,475,476,477],sometim:[30,60,62,70,72,73,77,81,82,87,88,90,93,95,96,99,100,101,102,104,105,106,107,108,109,123,126,143,150,160,163,168,169,178,180,186,221,222,240,244,258,266,273,299,303,311,319,320,322,333,338,339,365,366,392,403,407,409,413,440,442,445,447,451,452,453,459,460,463,470,473,474,475,477],someurl:105,somevalu:426,somevar:88,somewhat:[8,20,63,90,95,96,102,106,168,174,199,212,244,264,303,304,308,348,360,386,459,460,461,470,475],somewher:[64,77,87,88,95,99,102,134,144,243,303,328,365,368,409,426,476],somewidget:401,son:470,sonntag:174,soon:[30,71,87,93,95,100,101,102,105,186,228,293,304,309,386,388,416,427,440,453,454,455,473,475],sooner:[168,427,440,476],soothsay:462,sophist:[127,148,265,365,429,459,462,463,472,475],sorri:[92,165,452],sort:[33,60,72,79,80,83,87,89,90,91,96,97,104,105,106,109,123,138,143,152,158,168,173,175,178,180,186,215,222,223,226,236,246,253,258,260,264,273,293,302,303,321,322,330,333,345,346,358,364,368,403,407,410,423,426,440,442,451,452,453,461,463,472,473,474,475,476,477],sort_criteria:246,sort_kei:260,sort_ord:322,sort_stat:[238,322],sortbi:322,sortedcollect:137,sorteddict:88,sorttestmethodsus:407,soul:373,sound:[60,76,87,106,107,118,129,169,252,268,286,306,311,376,377,405,417,421,461,473,476],sound_mixer_:306,sound_mixer_m:306,sound_mixer_pcm:306,sound_mixer_synth:306,sound_mixer_volum:306,soundcard:306,soup:240,sourc:[0,4,6,17,26,28,30,49,58,60,64,66,67,68,69,70,71,75,76,77,79,81,82,84,90,91,92,93,96,99,100,106,107,108,109,111,113,114,118,119,121,123,125,126,127,128,132,134,136,137,138,140,143,144,145,148,149,150,151,152,154,156,157,158,160,161,162,164,167,168,169,176,179,180,182,184,186,187,188,189,190,191,192,202,206,208,210,212,214,216,218,219,221,222,223,226,227,228,230,231,232,234,235,236,237,238,239,240,241,243,245,246,248,249,251,252,255,258,261,262,263,265,266,267,270,274,276,281,288,290,293,296,299,303,304,306,308,309,311,312,313,314,315,316,318,321,322,326,327,329,330,331,332,335,339,340,341,342,343,344,350,351,352,354,355,356,357,358,359,360,361,365,366,368,369,370,371,373,374,376,378,379,380,381,383,384,385,386,389,390,391,392,393,394,395,396,397,399,400,403,404,407,409,410,411,413,414,416,417,418,419,420,423,424,426,427,428,429,430,431,432,433,434,435,436,438,440,443,445,446,447,448,449,453,454,456,457,465,467,468,469,470,471,472,474,475,476,477,478],source1:435,source_address:[241,360,477],source_filenam:63,source_str:308,sourcecod:403,sourcefil:107,sourceforg:[72,83,84,87,88,107,174,231,365,470,471,473,476],sourcehook:351,sourcen:435,sourcewar:107,south:[150,333,401,403,476],southeast:401,sox:405,sp4:476,sp_expir:363,sp_flag:363,sp_inact:363,sp_lstchg:363,sp_max:363,sp_min:363,sp_nam:363,sp_pwd:363,sp_warn:363,space:[4,28,29,34,37,52,55,63,76,77,81,88,89,90,93,95,98,101,102,104,123,135,140,150,152,154,170,178,180,186,191,195,197,198,205,206,215,222,226,239,241,244,246,253,258,264,266,270,273,282,293,303,308,309,312,328,331,332,333,336,346,348,351,353,356,358,368,369,371,374,377,389,390,391,393,394,396,398,401,403,409,423,426,437,438,440,445,446,447,451,452,457,459,460,463,465,470,474,475,476,477],spaciou:368,spam:[77,80,87,99,101,105,123,132,138,162,167,168,222,230,256,266,280,309,321,327,333,348,356,368,374,400,404,409,412,429,435,442,451,454,457,460,461,470,476],spam_appl:99,spam_modul:77,spam_system:77,spam_verbos:412,spamerror:77,spammer:358,spammethod:77,spammifi:77,spammish:[235,278],spammodul:77,spamread:167,spamwrit:167,span:[63,90,101,140,167,182,186,215,240,333,369,439,460,475,476],sparc:[28,306],spare:[346,471],sparingli:81,spark:471,sparrow:473,spars:[19,384],spawn:[60,69,155,257,293,304,317,323,361,391],spawnl:304,spawnlp:[304,374],spawnv:[304,317],spawnvp:[304,374],spdy:365,speak:[28,60,77,88,102,106,107,124,174,222,276,365,368,382,451],speaker:[377,422],spec:[60,64,66,161,236,253,260,364,365,376,401,434,473],speci:64,special:[13,28,30,39,43,55,56,60,63,64,68,71,72,75,77,79,81,87,88,90,93,96,98,99,100,101,104,106,107,108,123,125,134,136,143,144,145,148,152,157,158,159,163,167,168,169,172,173,174,186,206,212,214,216,219,228,230,231,232,244,249,252,253,258,260,264,265,266,273,290,291,293,301,302,303,304,308,314,322,333,335,337,342,351,352,353,360,364,365,366,370,373,374,380,384,387,394,395,396,405,407,409,410,413,418,423,426,427,429,431,434,438,442,444,446,447,450,451,453,459,460,461,467,470,471,472,474,475,476,477,478],specialbuild:30,specialfileerror:477,specialfilt:99,specialis:[99,105],specialti:64,specif:[0,1,6,10,15,20,23,28,30,31,37,51,55,58,59,60,62,63,64,68,69,71,72,73,75,77,80,82,83,88,89,90,91,92,97,98,99,100,101,104,105,106,107,108,109,119,120,123,125,132,143,146,148,157,158,160,161,162,163,164,167,168,169,174,176,178,186,188,192,193,194,198,200,201,204,205,206,207,212,215,221,222,225,226,227,228,230,232,238,239,240,244,249,252,253,255,256,260,264,265,266,267,269,273,276,282,290,293,299,302,304,305,306,307,308,309,311,314,316,322,328,329,332,335,336,339,344,345,348,352,357,360,364,365,366,368,372,378,381,385,386,388,389,390,391,392,393,395,396,397,398,406,407,410,411,415,416,417,423,426,427,429,433,434,436,437,438,439,440,442,444,445,446,447,448,450,451,454,457,460,463,465,467,468,469,470,471,472],specifi:[3,4,6,8,12,13,16,17,19,20,21,26,30,37,43,50,55,58,60,63,64,66,67,68,69,70,71,72,75,77,79,80,82,87,90,91,93,96,98,99,101,102,103,104,105,106,107,108,109,113,115,116,117,118,119,120,121,123,124,125,127,129,131,132,134,135,137,139,140,142,143,147,148,149,150,152,157,158,159,161,162,167,169,174,176,178,180,186,188,191,193,194,197,198,199,200,201,202,203,204,206,210,215,219,221,222,223,225,226,227,228,230,231,232,236,238,241,243,246,247,250,251,253,256,258,260,264,265,266,267,270,271,273,274,277,280,281,283,287,288,290,291,293,296,299,302,303,304,305,306,308,309,311,314,317,318,320,321,322,325,327,328,331,332,333,334,336,337,339,342,345,350,351,352,353,358,360,364,365,367,368,369,373,374,376,380,384,385,386,387,388,390,391,392,393,394,396,398,399,400,401,403,407,409,410,411,412,414,415,416,417,422,423,426,427,429,431,432,435,436,439,440,441,442,443,447,451,452,453,454,455,457,463,465,469,470,471,472,473,474,475,476,478],specific_submodul:461,specified_attribut:328,spectacular:236,speech:[99,306],speed:[7,37,56,77,81,82,87,98,101,106,107,135,152,169,188,208,236,256,258,301,306,309,350,365,380,387,393,403,437,440,450,461,470,471,472,473,474,475,476,477],speedi:236,speedstr:403,speedup:[88,438,471,475,476,477],speedvalu:403,speleotrov:474,spell:[66,72,81,93,104,150,174,255,322,369,391,442,446,447,459,473],spend:[62,88,470],spent:[77,322,336,353,475,476],sphinx:[0,60,83,87,99],spider:[341,470],spill:174,spin:191,spinbox:394,spirit:[72,91],spit:423,splash:269,splice:205,split:[56,60,63,66,72,81,87,88,103,123,129,150,167,178,180,192,193,194,197,198,200,219,228,230,246,258,272,290,302,303,304,305,309,311,313,333,335,338,351,358,364,365,368,369,374,389,398,407,409,410,411,431,446,450,451,457,461,472,473,474,475,476,477],split_quot:63,splitchar:198,splitdriv:305,splitext:[95,305,384,463,476],splitfield:369,splithost:409,splitlin:[88,90,180,368,389,400,476],splitresult:411,splittabl:194,splittyp:409,splitunc:305,spoerri:475,spoken:[64,99],spolski:104,sponsor:438,spoof:410,spool:386,spooledtemporaryfil:[386,476],spoon:72,sport:236,spot:[88,106,306,321,389],spread:[81,102,476],spreadsheet:[94,167,473],spring:[64,101,222,451],sprinkl:445,sprint:[475,476],sprintf:[368,457,470,472],spuriou:178,spwd:[60,233,252,324,408,475],sq_ass_item:55,sq_concat:55,sq_contain:[51,55],sq_inplace_concat:55,sq_inplace_repeat:55,sq_item:55,sq_length:55,sq_repeat:55,sql:[96,104,106,167,258,290,303,364,475],sql_script:364,sqlalchemi:106,sqlite3:[60,106,152,252,310,476,477],sqlite:[60,106,252,310,475,477],sqlite_deni:364,sqlite_ignor:364,sqlite_ok:364,sqlite_omit_load_extens:364,sqlite_vers:364,sqlite_version_info:364,sqlobject:106,sqrt:[123,129,147,178,277,474,475,476],squar:[4,28,88,90,91,96,104,123,129,147,169,178,277,309,322,368,403,429,440,442,445,446,447,451,453,457,460,472,473,476],squeez:88,squirrel:[28,322],src:[63,67,72,82,91,168,186,232,240,271,287,290,304,311,352,473,475],srcname:352,sre:[470,472],sre_compil:[288,322],sre_const:288,sre_flag_unicod:288,sre_match:[101,214,333],sre_pars:288,sre_pattern:101,srmount:205,srow:398,srpm:[64,69],sscanf:168,ssh:[269,313,352,411],ssi:79,ssize_t:[60,168,478],ssizeargfunc:55,ssizeobjargproc:55,ssl3:365,ssl:[60,105,221,241,246,252,257,304,318,358,360,409,410,423,434,438,465,470,473,474,477],ssl_cert_fil:365,ssl_cert_path:365,ssl_mode_auto_retri:477,ssl_op_al:365,ssl_sock:365,ssl_version:[221,365],sslcontext:[221,241,365,409,410,434,477],ssleai:438,ssleoferror:365,sslerror:365,sslobject:246,sslsocket:[365,477],sslsyscallerror:365,sslv23:365,sslv2:365,sslv3:365,sslwantreaderror:365,sslwantwriteerror:365,sslzeroreturnerror:365,sss:[77,79],st2list:308,st2tupl:308,st_atim:[304,366],st_attr:304,st_birthtim:[304,475],st_blksize:304,st_block:304,st_ctime:[304,366],st_dev:[304,366],st_flag:[304,475],st_ftype:304,st_gen:[304,475],st_gid:[304,366],st_ino:[267,304,366],st_mode:[304,366],st_mtime:[180,234,304,366,473],st_nlink:[304,366],st_obtyp:304,st_rdev:304,st_size:[304,366,472],st_uid:[304,366],stab:303,stabil:[1,60,83,236],stabl:[84,90,103,204,222,236,303,368,473,474,477],stack:[9,20,28,30,52,60,77,79,81,88,98,106,120,134,149,152,163,168,169,177,182,186,206,215,244,252,255,292,309,311,329,330,336,348,351,353,360,366,368,380,390,391,394,407,439,440,441,442,446,447,449,454,456,465,470,471,474,475,476,477],stack_siz:[390,391,475],stackless:[81,445],stacklevel:[20,416,475],stacksiz:[12,297],staff:[98,174,352],stage:[63,101,308,391,396,410,416,426,470],stagger:219,stai:[60,311,438,469,478],stake:338,stale:205,stamp:[174,304,403,451,473,474],stamp_id:403,stampid:403,stand:[6,67,72,84,104,106,107,178,187,204,216,303,333,355,470,475,476,477],standalon:[63,70,81,90,106,186,243,270,284,328,365,403,407,467,476],standard:[0,4,6,10,16,21,26,27,28,30,37,52,54,55,56,58,60,62,64,66,69,70,72,73,77,78,79,80,81,82,83,84,87,89,90,91,95,96,98,99,100,101,103,104,105,106,108,109,112,114,119,120,121,123,129,131,132,134,135,137,143,146,147,149,152,153,156,157,162,167,168,169,170,174,175,178,186,192,194,196,197,198,200,201,202,203,206,210,212,214,215,216,217,219,221,222,227,230,231,238,243,244,246,249,251,256,258,259,264,265,266,267,269,270,273,274,275,277,281,283,287,288,290,293,295,299,301,304,305,306,308,311,313,314,317,318,319,320,322,323,325,326,328,332,333,337,338,339,342,346,348,349,350,351,353,356,358,360,361,365,368,369,370,372,373,374,380,381,383,384,385,386,388,390,391,392,393,394,395,396,400,403,404,406,407,409,410,411,412,414,415,416,418,423,424,425,426,429,434,435,438,439,441,442,444,445,446,447,448,449,450,451,453,454,456,457,459,460,464,465,467,468,469,470,471,472,474,475,476,477,478],standard_b64decod:131,standard_b64encod:131,standard_lib:63,standard_option_list:303,standard_rights_read:113,standard_rights_requir:113,standard_rights_writ:113,standard_suit:270,standard_test:407,standard_wai:103,standarderror:[20,109,178,206,461,476],standbi:103,standend:169,standout:169,standpoint:89,stanza:112,star:[152,379,397,445,447],star_arg:157,stararg:[125,476],stare:81,starequ:397,starmap:[96,258],starship:475,start:[4,6,8,19,20,26,28,29,30,34,49,50,55,56,58,60,63,64,67,70,72,73,75,76,79,81,82,83,86,87,88,90,91,94,96,98,99,100,101,102,103,104,105,106,107,108,116,117,118,123,125,126,129,132,134,135,138,139,140,142,143,146,149,150,152,158,159,162,168,169,170,174,175,180,182,186,196,197,206,207,214,216,221,222,225,226,230,231,232,233,236,238,239,240,243,244,246,253,255,256,258,260,264,265,266,267,269,271,273,274,275,282,287,290,292,293,296,299,301,303,304,305,309,311,314,319,320,322,323,327,328,330,332,333,334,338,339,343,348,352,354,356,358,360,361,365,368,369,370,373,374,380,382,384,388,390,391,392,396,399,400,401,403,404,407,409,411,413,416,419,426,427,429,431,434,435,437,439,440,442,443,446,447,449,450,451,452,453,458,459,460,461,462,463,465,467,469,470,471,472,473,474,475,476,477],start_color:[93,169],start_compon:290,start_dir:407,start_el:328,start_new_thread:390,start_respons:[106,423],start_tag:[239,348],startbodi:282,startboundarynotfounddefect:196,startcdatasectionhandl:328,startcom:365,startdoctypedeclhandl:328,startdocu:431,startdtd:474,startel:[431,432,470],startelementhandl:328,startelementn:[431,432],startf_useshowwindow:374,startf_usestdhandl:374,startfil:304,starti:403,starting_nod:463,startmultipartbodi:282,startnamespacedeclhandl:328,startprefixmap:431,startswith:[240,311,364,368,380,407,470,473,475,476],starttagopen:101,starttest:407,starttestrun:[407,477],starttl:[267,358,476],startup:[28,60,89,159,168,266,304,362,380,395,412,438,456,458,461,467,469,475,476],startup_fil:449,startupinfo:[374,474],startx:403,starv:222,stash:107,stat1:305,stat2:305,stat:[60,63,90,104,177,180,208,211,234,238,252,256,267,299,304,305,318,338,365,384,472,473,475,476],stat_float_tim:[304,305,473,475],stat_result:[304,473],statcach:475,state:[6,20,26,27,30,45,46,52,55,60,77,79,81,83,87,88,90,93,96,98,100,101,105,106,113,127,129,134,141,142,143,147,149,150,151,160,162,163,169,205,210,219,225,252,254,256,266,273,294,297,304,306,309,311,313,315,322,328,332,334,340,343,345,360,361,362,364,365,368,374,380,388,391,392,394,395,396,407,411,416,437,438,440,442,447,451,452,454,459,463,470,472,473,475],stateless:[106,129,150],statement:[30,35,41,43,47,51,55,58,60,76,77,79,83,88,89,90,91,96,99,106,107,109,113,125,134,139,143,151,157,159,163,168,177,178,182,186,197,199,206,222,224,234,244,249,252,255,256,261,273,290,293,302,303,308,309,317,319,321,326,329,333,338,362,364,365,368,379,380,383,384,386,387,388,390,393,398,403,407,412,426,435,441,442,443,444,446,448,449,450,451,454,456,457,458,459,460,461,465,470,471,472,473,474,477,478],stateorprovincenam:365,statespec:401,staticmethod:[51,88,90,94,186,222,266,440,461,472,474,477],statinfo:304,statist:[81,83,94,225,299,322,332,365,393,399,465,470,471,475,477],statu:[4,52,63,72,77,81,87,93,95,98,99,105,114,119,123,142,144,152,155,169,192,200,202,204,206,241,246,273,299,303,304,317,318,325,356,361,374,377,380,390,401,409,410,423,449,459,470,474,475,477],statvf:[60,211,252,304,472,476],std66:411,std:[380,392,475],std_error_handl:374,std_input_handl:374,std_output_handl:374,stdbuttonbox:394,stdcall:168,stderr:[20,28,52,60,63,64,76,88,98,99,132,143,149,186,225,229,244,266,267,269,293,303,304,317,325,335,338,364,374,380,384,393,400,407,416,423,440,461,462,463,465,470,474,476,477],stderr_data:474,stderrdata:374,stdin:[28,52,79,81,82,96,123,143,148,156,168,186,207,210,216,229,244,246,293,304,309,335,338,345,351,355,365,368,374,380,384,387,406,410,423,440,442,451,452,453,454,457,460,461,462,463,465,471,472,473,474,476,477],stdin_read:323,stdio:[30,55,76,77,82,87,222,304,339,368,476],stdlib:[30,60,77,92,99,381,425],stdname:[174,322],stdoffset:174,stdout:[28,52,60,63,64,77,91,98,99,123,143,148,168,169,180,182,186,204,208,221,222,244,246,266,267,276,293,303,304,309,312,317,321,322,335,338,357,374,380,384,385,388,399,400,404,407,416,423,429,433,435,440,447,457,461,462,465,470,474,475,476,477],stdout_data:474,stdoutcatch:82,stdoutdata:374,stdscr:[93,169,476],stdsuit:[227,270,476],stdwin:470,steadi:470,steal:[28,30,33,39,47,53],steel:87,steen:396,steer:[30,471,474],stefan:477,stein:[87,157,470],stellenbosch:476,stem:[101,276,477],step:[1,49,60,62,63,64,73,76,80,87,89,95,96,100,101,102,103,105,107,109,123,125,129,134,137,143,150,152,168,177,178,186,222,230,236,241,244,258,265,290,293,303,309,332,361,364,368,369,401,403,430,439,440,442,443,447,452,456,458,470,471,472,473,474,475,476,477],stephen:472,stereo:[118,129,306,376,417,461],stereocontrol:306,stereophon:306,sterl:169,steve:[365,471,476],steven:[471,475,477],stew:364,sticht:[28,61,438],stick:[67,93,106,293,401,472,473,476],sticki:[178,366,401],stiff:[77,452],still:[24,26,28,30,41,42,50,55,59,62,63,67,68,72,76,77,79,80,81,83,84,87,88,90,93,95,96,98,100,101,102,103,104,105,106,107,108,114,123,124,125,131,136,138,142,143,150,158,162,167,168,169,178,182,186,192,198,206,215,219,222,225,230,244,256,259,264,266,267,273,275,287,293,303,304,306,308,311,322,328,336,337,338,339,340,342,350,356,360,361,364,365,368,369,374,380,386,389,391,401,405,407,409,417,418,425,426,432,438,440,442,451,454,455,461,463,465,469,470,471,472,473,474,475,476,477],stinner:477,stippl:169,stitch:202,stmt:[125,157,393,443,476],stmt_list:[439,448],stock:[107,364,475],stolen:[25,30,50,76],stolk:472,stone:238,stop:[49,63,82,88,96,98,99,100,117,134,142,148,151,174,180,186,202,216,219,222,227,228,238,244,258,265,266,270,273,293,303,304,306,309,322,328,332,339,348,361,368,374,377,391,396,401,403,407,422,440,442,452,453,454,455,470,471,472,473,475,476,477],stop_aft:63,stop_cod:182,stop_her:134,stopfram:134,stopiter:[20,55,79,90,96,206,222,258,276,293,364,368,398,440,442,447,451,461,472,473,475,476],stoplisten:[99,266],stoptest:407,stoptestrun:[407,477],stor:221,storag:[4,6,28,30,37,48,56,81,90,104,106,150,158,169,182,256,258,304,312,350,364,373,386,413,440,472,475,476,477],storbinari:[221,476,477],store:[4,6,8,9,16,24,28,36,37,43,49,55,56,60,63,71,77,79,81,82,87,88,90,91,92,94,96,99,101,103,104,106,107,111,113,116,118,120,121,123,124,125,129,132,138,141,143,147,150,152,157,158,162,168,169,174,178,182,186,188,192,193,200,219,221,222,227,232,236,238,239,244,245,246,247,249,252,258,273,274,281,282,283,287,293,299,308,310,311,316,324,328,339,345,347,350,358,359,360,361,365,366,368,373,376,380,381,384,386,391,394,399,400,401,403,407,409,410,413,418,423,426,429,434,435,437,440,442,446,447,451,452,453,454,455,457,458,460,461,462,463,469,470,471,472,473,474,475,476,477],store_act:303,store_attr:182,store_const:[123,303],store_deref:182,store_fals:[123,303],store_fast:182,store_glob:182,store_map:182,store_nam:[182,365],store_slic:182,store_subscr:182,store_tru:[91,123,180,228,303,477],store_valu:303,stori:[28,77,83,236,311,457],storlin:[221,476],storm:472,stormi:470,str1:212,str2:212,str3:212,str:[16,21,22,29,34,43,50,55,56,58,60,79,81,87,88,90,91,93,96,98,99,100,103,104,109,123,125,148,150,158,161,167,169,173,174,178,191,197,198,203,206,222,228,236,240,241,252,256,258,260,264,265,266,292,293,303,304,339,348,351,352,364,369,370,372,380,388,389,393,404,413,415,416,423,429,434,440,442,451,453,454,455,457,460,461,463,465,470,472,473,474,475,476,477],straddl:174,strai:95,straight:[137,152,198,201,251,293,331,396,427,469,470],straightforward:[20,30,43,62,77,87,88,89,99,104,105,106,150,168,266,278,303,345,360,451,460,472,473,476],strain:102,strang:[60,88,127,236,389,390,440,469,471,475,476],strategi:[28,55,77,82,123,127,150,267,357,407,419,437,473],strchr:[92,168],strcmp:[8,16,82],strcoll:[103,223,264],strcpy:104,stream:[13,28,36,60,87,90,96,98,99,102,120,126,132,135,139,142,149,150,167,169,193,201,202,205,211,222,229,234,236,248,252,257,258,260,265,266,267,281,290,292,304,310,312,321,322,328,338,339,348,351,352,354,356,360,361,370,374,376,380,384,398,405,407,409,410,417,423,424,425,428,432,433,434,437,440,445,446,449,461,470,474,475,476,477],stream_or_str:428,stream_read:470,stream_writ:470,streamerror:384,streamhandl:[60,98,99,120,265,266],streamread:[13,60,372,474,475],streamreaderwrit:[60,372],streamrecod:[60,372],streamrequesthandl:[99,361],streamwrit:[13,60,372,475],street:333,streetaddress:365,strength:219,strengthen:203,strerror:[20,205,206,264,304,454,476],stretch:[235,244,401,403,426],stretch_len:403,stretch_wid:403,stretchfactor:403,strfry:475,strftime:[60,98,173,264,265,266,267,273,392,434,462,463,473,475,476],strict:[13,56,76,96,104,150,161,162,167,168,178,192,196,198,202,222,240,241,256,260,273,281,306,365,368,384,392,426,438,442,470,471,473,476,477],strict_domain:162,strict_error:150,strict_ns_domain:162,strict_ns_set_initial_dollar:162,strict_ns_set_path:162,strict_ns_unverifi:162,strict_pars:[143,411],strict_rfc2965_unverifi:162,stricter:[104,167,178,470,471,475],strictli:[55,77,79,102,103,104,107,124,161,197,210,222,276,368,410,440,441,442,446,451,475],stride:[6,368,440,442,473],string1:[264,364,453],string2:[264,364,453],string3:453,string:[4,6,7,8,13,15,19,21,22,23,24,27,28,29,30,34,36,37,39,41,43,46,52,55,56,57,58,60,63,64,66,67,68,72,76,77,79,82,83,90,91,92,93,95,96,98,99,100,102,103,104,105,106,107,109,111,113,115,116,117,118,119,120,121,123,124,125,126,127,129,131,132,133,134,135,138,139,140,141,142,143,146,148,149,150,151,152,153,155,157,158,161,162,164,165,167,168,169,170,173,174,176,178,180,185,186,188,191,192,193,194,197,198,199,200,201,202,203,204,205,206,207,210,212,213,214,215,217,218,219,221,222,223,226,228,229,230,231,232,233,234,235,237,238,239,241,244,245,246,247,248,249,252,253,256,257,259,260,261,264,265,266,267,269,273,274,276,278,280,281,283,287,290,292,293,296,297,298,299,300,302,304,305,306,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,324,325,326,327,328,331,334,335,338,339,345,348,349,350,351,352,354,355,356,357,358,359,360,361,363,364,365,376,377,378,379,380,381,382,384,385,386,387,388,389,391,392,393,394,396,397,398,399,400,401,403,404,406,407,409,410,411,414,415,416,417,419,420,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,443,445,447,448,451,453,454,455,456,458,459,461,463,465,469,471,472,475,477,478],string_at:168,string_convers:442,string_escap:150,stringent:332,stringi:370,stringifi:167,stringified_newdatatyp:79,stringio:[55,60,82,167,200,202,234,252,256,260,273,282,292,311,322,372,386,388,398,423,427,476,477],stringliter:442,stringo:370,stringprefix:446,stringprep:[60,150,252,372,473],stringtyp:[50,404],stringvar:[396,401],strip:[63,88,96,101,123,134,150,155,158,169,170,174,178,180,186,203,221,222,228,244,266,305,322,339,351,358,361,364,368,369,377,382,400,416,435,451,452,453,454,470,473],strip_blank:63,strip_com:63,strip_dir:[63,238,322],stripped_it:96,stripped_lin:96,stripped_list:96,stripspac:169,strive:[455,477],strlen:[82,92,102,104],strncat:82,strncmp:16,stroke:[83,104,472],strong:[81,107,174,219,240,278,365,418,437,471,476],stronger:106,strongest:[89,477],stronghold:133,strongli:[6,77,98,374,380,396,431,440,446,471,472,475],strop:[338,470],stropt:377,strptime:[60,173,365,392,434,472,473,475],strtobool:63,strtod:[16,60],struct:[14,15,18,26,51,55,58,60,79,81,87,89,90,92,99,124,129,168,207,222,252,266,338,360,368,372,380,434,451,463,472,475,476,477],struct_frozen:168,struct_tim:[90,174,246,273,392],structmemb:79,structseq:[22,380,477],structur:[3,4,6,9,10,12,15,17,19,23,25,26,27,28,30,37,41,44,45,48,52,54,58,60,62,75,77,79,81,82,88,89,90,92,93,96,98,101,106,107,120,125,134,141,144,146,150,157,158,169,181,192,197,199,200,201,202,205,207,215,219,220,221,230,233,236,240,243,244,252,253,256,258,260,273,281,290,293,304,305,308,311,321,324,325,333,341,348,354,360,363,365,368,371,373,374,377,388,392,394,403,407,409,411,418,426,429,430,434,435,436,440,444,450,456,461,462,463,470,471,472,473,474,475,476,477],structuredmessag:99,strxfrm:[90,103,264],sts:[77,87,474],sttype:308,stuart:360,stub:[60,81,115,116,117,148,252,270,339],stuck:[81,87],student:[83,103,222,223,373,403,451],student_object:103,student_tupl:103,studi:[60,80,96,186,236,403,432,473,476],studio:[63,64,80,469,476],stuf:149,stuff:[55,63,79,82,95,168,186,251,321],stufft:477,stumbl:102,stupid:393,stutzbach:[476,477],stx:170,style1:477,style:[4,10,15,16,31,43,50,56,60,69,70,73,77,81,89,90,94,96,98,101,104,106,114,117,120,123,132,134,135,138,140,152,158,176,180,187,188,191,200,202,211,212,214,215,222,223,224,226,230,240,241,252,258,265,272,273,281,303,305,309,310,311,322,327,333,339,350,352,353,360,364,368,381,388,391,394,395,396,404,407,408,423,434,438,439,442,444,445,446,447,449,451,456,457,458,462,463,470,471,472,473,474,476,477,478],styledtext:117,stylesheet:[410,477],stype:6,sub:[27,60,64,67,69,72,73,88,96,98,101,113,120,125,157,167,168,169,170,174,180,192,197,200,202,246,251,252,258,266,273,299,302,304,317,322,328,332,333,338,350,368,369,394,407,413,429,453,460,461,462,469,470,472,476,477],sub_command:63,sub_dcmp:208,sub_kei:113,subcal:322,subcategori:104,subcel:337,subclass:[5,6,10,17,20,43,55,60,63,68,81,90,94,98,99,101,105,114,116,117,123,125,126,127,132,133,134,140,148,149,150,152,157,158,167,168,173,174,178,186,192,196,201,206,210,215,217,219,221,222,229,240,241,246,254,256,260,265,266,267,273,280,284,292,293,296,300,303,310,318,321,332,338,339,350,351,357,361,364,365,368,369,370,388,391,394,396,401,403,407,409,410,411,413,414,416,418,423,425,426,430,431,433,434,436,439,441,451,454,463,465,470,472,473,474,475,476,477],subclaus:96,subcod:[116,142],subcommand:[63,65,123,477],subdebug:293,subdir:[72,123,208,273],subdirectori:[67,72,73,75,77,79,87,107,156,193,208,273,304,305,314,356,399,407,435,436,461,470,471,473,476,477],subdivid:142,subel:429,subexpress:[88,101],subfold:279,subfoo:67,subfunct:322,subgroup:[101,333],subitem:461,subject:[12,48,79,87,96,98,105,162,174,186,193,198,200,255,260,266,267,273,299,311,314,322,333,350,360,365,438,440,446,451,468,475],subjectaltnam:365,subkei:[113,469],sublayout:401,sublicens:438,sublist:[394,439,442,470],submenu:219,submiss:[1,105,143,328,470],submit:[1,71,93,105,143,293,470,477],submitt:470,submod:251,submodul:[26,55,90,150,186,222,249,314,342,365,396,399,425,435,461,465,475],submsg:292,subn:[101,333,477],subnam:251,subnegoti:385,subnod:427,subnorm:178,subobj:335,subobjec:88,subobject:79,suboffset:6,subopt:385,subordin:[113,477],subpackag:[26,55,75,90,192,290,407,435,461,470],subpad:169,subpars:123,subparser1:123,subparser2:123,subparser_nam:123,subpart:[192,195,196,197,199,200,201,202,282],subpath:436,subpkg1:447,subpkg2:447,subpkg:[72,250],subprocess32:374,subprocess:[60,89,99,102,155,204,252,257,293,304,360,361,395,403,468,473,476,477,478],subroutin:[63,76,96,475],subscrib:[83,246],subscript:[32,60,90,125,152,157,168,206,244,368,440,443,447,451,460,465,473,476],subscriptlist:443,subsect:[93,101,107,442,452],subsequ:[4,20,28,53,63,88,94,98,101,142,151,162,169,180,182,198,201,221,253,256,258,259,264,266,267,273,287,292,293,303,304,311,330,333,360,364,365,368,369,382,384,390,391,394,396,403,427,437,439,442,445,447,452,453,473,474,475,476,477],subsequent_ind:389,subset:[75,83,96,100,101,102,137,150,158,169,214,235,246,250,260,267,273,296,306,308,319,328,345,346,348,352,368,384,391,407,426,429,431,435,473,475,477],subshel:[232,304],subslic:332,subst_var:63,substanti:[28,77,162,241,276,328,405,426,438,472,474],substitut:[60,63,81,87,88,90,98,99,101,106,109,131,152,158,170,174,178,186,197,239,258,266,274,276,303,322,333,334,338,364,368,369,385,398,401,413,419,438,439,442,447,452,456,457,459,463,473,475,476,477,478],substr:[56,81,96,101,186,235,237,278,287,303,305,333,349,368,369,442,460,470,472,473,474,475,476],substructur:377,subsubdirectori:356,subsubitem:461,subsum:[192,413],subsystem:[96,396,473,475,477],subthread:390,subtl:[20,55,77,81,167,186,207,269,300,303,306,322,338,440,441],subtlest:470,subtleti:[101,162,174,439],subtli:[90,93,95,102,200],subtract:[41,129,152,174,178,277,302,322,403,434,442,446,470,473,476,477],subtre:[28,470],subtupl:20,subtyp:[6,7,8,11,14,17,19,21,22,29,33,34,39,43,48,50,53,54,55,56,191,192,193,197,199,200,201,244,280,281,282,300,303,353,365,368,432,440,472],subvers:[125,380,461,475,476,477],subview:368,subwarn:293,subwidget:394,subwin:169,subwindow:169,succe:[4,8,16,35,41,43,47,88,95,101,113,127,186,203,222,304,308,339,359,360,365,407,426,472,473],succeed:[168,248,293,360,407,454,474],success:[4,6,8,9,11,13,16,19,20,21,26,28,30,33,35,39,41,42,43,47,48,49,50,51,52,53,54,55,56,58,63,77,82,83,88,90,93,96,98,101,105,127,132,137,151,168,169,207,215,221,241,246,249,258,264,287,293,304,306,311,312,328,358,359,360,364,365,373,374,380,393,394,401,407,409,426,440,454,470,473,474,477],successfulli:[28,58,71,75,80,101,102,158,186,222,293,299,303,304,360,365,368,390,423,461,474],successor:438,succinct:[94,462],succinctli:[258,451],suck:102,suddenli:[89,95],sudo:99,suexec:143,suffer:[90,374,407,455,471,472,473],suffic:[306,364,407],suffici:[40,43,55,72,77,82,98,127,150,174,178,186,215,277,304,326,338,365,368,390,391,407,419,431,440,442,447,453],suffix:[56,83,90,99,107,109,168,246,249,251,253,265,266,267,281,333,350,354,358,368,386,409,442,446,460,461,470,472],suffix_map:281,sugalski:475,sugar:[90,161,364,452],suggest:[1,21,60,63,81,83,87,88,94,96,101,104,119,178,189,190,212,222,230,235,299,334,390,391,392,396,412,458,464,470,471,472,473,474,475,476,477],suid:304,suit:[0,55,79,81,87,88,90,96,98,100,116,117,125,152,157,186,222,227,230,256,270,293,303,308,365,388,407,435,438,439,443,447,450,457,461,463,469,475,476,477],suitabl:[17,28,49,55,63,77,96,98,99,104,108,133,135,137,150,161,167,174,180,191,199,200,203,215,219,236,247,258,259,264,265,266,267,273,281,293,299,304,305,311,322,332,339,340,358,360,361,365,369,384,391,393,399,407,409,423,426,437,439,440,456,463,472,473,474,476,477],suite1:407,suite2:407,suite_mask:[380,477],suiteclass:[407,477],sum:[14,30,55,90,96,123,125,129,152,174,178,186,222,258,277,302,304,322,364,368,401,442,451,452,453,455,460,461,462,463,473,474,476],sum_list:30,sum_sequ:30,summar:[89,94,100,104,178,186,350,368,407,438,439,442,474],summari:[60,63,64,72,83,87,139,163,186,239,303,336,399,421,423,438,452,471,472,473,474],summaryinform:290,summat:[88,277],summer:[222,392,475,476],summerfield:307,sun4u:[63,381],sun:[60,64,129,132,174,248,252,276,286,306,375,392,405,408,424],sunau:[60,252,286],sunaudio:405,sunaudiodev:[60,129,252,375,470,476],suncc:477,sundai:[140,174,264,267,392,477],sundri:473,sunken:396,suno:[28,60,252,315,384],sunos5:[28,380],super_getattro:94,supercalifragilisticexpialidoci:[460,463],superclass:[148,222,260,266,326,361,413,440,472,473,475],superfici:88,superflu:364,superimpos:365,superior:258,supersed:[280,292,306,339,470,477],superset:[98,260,319,346,368,407,446,470,473],superstit:101,superus:304,supervis:475,supervisor:337,supplant:413,supplement:[225,304,476],supplementari:[105,360],suppli:[4,16,17,55,63,64,66,70,72,73,79,88,90,93,96,103,105,107,123,125,142,143,145,152,162,168,169,170,174,178,186,191,207,219,221,222,223,235,237,244,246,253,258,265,267,273,293,297,299,303,306,308,309,314,322,328,332,342,346,360,364,365,368,374,381,401,407,409,410,416,418,423,431,434,437,438,439,440,442,447,462,463,465,470,471,472,473,474,475,476,477],support:[3,4,6,9,15,19,20,21,27,30,31,32,33,34,35,41,42,43,47,48,49,50,53,54,55,57,59,60,62,63,64,66,68,72,75,77,78,81,82,83,84,87,88,89,90,92,93,94,98,99,101,102,103,105,106,107,108,109,113,114,117,118,121,122,123,124,125,127,129,131,132,135,136,137,138,139,141,146,147,150,152,156,157,158,160,161,162,163,165,167,168,169,172,173,174,175,176,178,179,180,182,184,185,186,187,191,192,194,197,198,199,202,204,205,206,207,213,214,215,216,218,219,220,221,222,223,225,226,228,229,231,235,239,241,242,246,249,252,253,255,256,257,258,260,262,264,265,266,267,270,271,273,274,275,276,277,280,281,283,290,293,295,299,301,302,303,304,305,306,308,309,310,311,314,315,316,317,318,321,325,328,330,333,334,335,336,337,338,339,345,346,347,348,350,351,352,353,355,358,360,361,362,364,366,368,369,372,373,374,376,377,380,381,386,387,390,391,392,396,398,401,403,404,405,406,407,408,409,410,411,413,414,416,417,418,419,422,423,424,425,426,427,431,432,434,435,436,437,438,439,440,442,443,445,446,447,450,451,453,454,455,458,459,460,461,462,463,467,468,469,471,472,474,475,477,478],support_team:266,supported_dist:315,supports_unicode_filenam:[305,473],suppos:[20,53,55,72,77,80,88,89,102,107,178,186,323,333,356,364,365,369,384,401,447,460,461,475,476,477],supposedli:409,suppress:[29,60,93,98,107,123,145,160,186,217,225,303,329,356,358,368,380,388,423,439,440,449,452,463,469,471,473,475,476,477],suppress_help:303,suppress_ragged_eof:365,suppress_usag:303,sure:[1,3,13,15,45,56,60,70,72,76,79,81,82,87,88,89,93,95,96,98,99,101,106,107,123,125,143,148,157,167,168,178,192,206,222,225,264,293,303,304,311,364,365,376,380,388,391,394,409,410,414,416,417,429,443,447,451,460,462,464,467,472,473,475,476],surfac:[91,231],surpris:[60,81,87,88,102,120,174,178,186,219,222,236,277,293,322,396,440,442,451,455,471,472,475],surprisingli:87,surrog:[56,260,371,426,440,446],surround:[82,96,101,134,161,167,180,222,244,264,280,344,369,374,439,441,453,461,463,470,475,476,477],surviv:[168,225,390],survivor:477,susan:346,suse:[64,70,107,315],susp:169,suspect:[29,89,143,470],suspend:[90,96,169,328,387,391,392,442,472,473,475],suspens:392,sussman:96,suzi:473,suzuki:473,sv1:105,svensson:474,svformcontentdict:143,svg:475,svn:[73,104,123,156,411,473,475,476,477],svnversion:380,svr4:[93,207],sw_hide:374,sw_showdefault:374,swallow:[98,99,463,470,477],swamp:99,swap:[28,76,102,150,152,168,182,293,336,360,373,440,447,462],swapcas:[368,369],swaroop:469,sweep:[225,475],sweet:101,swig:[63,66,72,82,89,469],swig_opt:72,swinstal:[64,70],switchabl:373,switchboard:102,switching_protocol:241,switzerland:429,swordfish:101,syllabl:104,sym:[63,185],sym_nam:378,symbol:[55,58,60,63,72,77,80,88,89,93,104,107,113,119,120,125,149,151,157,168,169,178,182,186,206,212,222,243,252,262,264,267,269,302,304,305,308,312,315,333,336,352,353,360,364,366,368,377,380,383,384,385,387,397,401,403,406,426,431,440,443,445,447,452,458,461,470,472,474,475,477],symbolt:379,symlink:[63,73,232,249,303,304,352,467,474,476],symmetr:[332,346,368,440,442,453,470,472,473,474],symmetri:470,symmetric_differ:[346,368,473],symmetric_difference_upd:[346,368,473],symtabl:[60,252,262,477],symtyp:384,syn:170,sync:[106,138,169,175,188,226,293,306,350],syncdown:169,synch:180,synchron:[60,138,170,173,178,188,205,226,252,256,287,320,350,353,361,362,390,391,440,463,476],synchronis:368,syncmanag:293,syncok:169,syncup:169,synonym:[90,104,169,175,182,198,228,303,366,376,396,417,426,476],synopsi:[327,365],syntact:[81,88,90,157,198,222,240,255,296,308,328,364,368,411,416,430,439,442,445,446,447,451,452,454,474,475],syntax:[4,6,60,63,66,71,73,77,79,81,82,83,88,90,95,96,98,101,104,105,109,120,143,149,151,158,159,178,186,206,222,230,239,244,252,260,262,264,266,275,279,293,302,303,306,308,309,328,339,351,364,368,372,380,400,401,407,409,411,433,434,440,442,444,445,446,447,448,453,455,456,457,459,460,461,463,464,465,468,470,471,472,473,474,475,477,478],syntax_err:426,syntaxerr:426,syntaxerror:[20,58,82,104,149,151,157,159,186,206,222,308,400,441,442,447,453,454,457,460,461,470,471,472],syntaxwarn:[20,206,388,416,461,473],synthes:[96,186],sys:[4,20,26,28,30,52,58,60,63,64,70,72,77,81,82,83,88,90,95,98,99,100,104,106,107,109,111,120,128,132,134,143,145,148,149,156,167,168,169,180,182,186,191,193,204,206,207,208,210,221,222,225,228,229,230,244,249,250,251,252,258,263,265,266,267,276,288,293,303,304,306,309,311,312,314,315,317,321,322,325,326,327,329,335,338,342,345,351,352,356,360,361,364,366,368,373,374,381,382,384,385,387,388,390,391,393,399,400,404,407,410,412,416,423,429,433,435,436,439,440,442,447,448,449,454,457,459,461,462,463,465,469,470,471,472,473,474,475,476,477],sys_exc:109,sys_vers:132,sysbeep:269,syscal:304,sysconf:304,sysconf_nam:304,sysconfig:[60,69,72,76,252,304,329],syslog:[60,98,99,252,267,408,477],syslog_udp_port:[266,267],sysloghandl:[60,98,120,266,382,477],sysmodul:476,sysnam:304,system32:469,system:[3,4,6,19,20,21,24,27,28,29,30,33,34,35,36,37,42,43,47,48,49,50,53,54,55,56,57,60,62,64,66,68,69,70,71,72,73,75,77,78,80,81,83,84,86,87,88,89,90,92,93,95,96,98,99,100,101,104,105,106,107,113,117,124,127,132,134,138,140,144,147,148,150,155,158,165,168,169,174,178,179,184,185,192,202,204,206,211,214,216,221,222,228,229,230,241,243,244,245,249,252,254,255,256,257,264,265,266,267,269,273,274,281,286,287,291,293,296,298,305,306,307,313,314,315,317,320,322,323,324,328,329,332,336,337,338,339,345,347,353,355,356,360,361,364,365,366,367,368,369,373,381,382,384,386,387,388,390,391,392,394,396,403,405,407,408,409,410,419,422,423,425,426,429,431,432,434,435,438,440,446,447,448,449,450,454,456,457,459,461,463,465,467,468,469,470,472,473,474,475,476,477,478],system_alia:315,systemasterisk:422,systemat:186,systemdefault:422,systemerror:[4,20,23,39,43,48,53,55,60,185,206,308,461],systemev:[270,476],systemexclam:422,systemexit:[20,58,63,95,98,128,149,159,191,206,293,338,380,390,422,441,461,475,476],systemhand:422,systemid:[328,426,431,432],systemquest:422,systemrandom:[304,332],systemroot:374,sysv:[87,470,471],t01234:368,t0123:368,t012:368,t_bool:51,t_byte:51,t_char:51,t_doubl:51,t_float:51,t_fmt:264,t_fmt_ampm:264,t_int:[51,79],t_k:231,t_long:51,t_longlong:51,t_object:51,t_object_ex:[51,79],t_ord:231,t_pyssizet:51,t_short:51,t_string:51,t_string_inplac:477,t_ubyt:51,t_uint:51,t_ulong:51,t_ulonglong:51,t_ushort:51,tab:[4,60,80,135,148,167,169,170,180,186,195,197,198,206,215,241,244,253,260,309,331,334,340,348,351,356,368,369,374,389,394,395,419,434,446,452,458,460,465,469,470,475,477],tab_id:401,tabcheck:380,taberror:[20,206,461,470],tabifi:244,tabl:[3,4,6,26,28,30,51,56,60,63,72,78,79,80,81,83,96,98,100,101,104,105,106,113,137,140,142,150,157,168,169,178,180,192,205,222,252,255,259,260,262,264,265,281,293,302,320,333,345,346,361,364,365,368,369,371,373,384,392,396,407,419,421,425,426,435,438,442,446,452,457,458,461,463,472,473,474,475,476,477],tablea:371,tableb:371,tablec:371,tabnanni:[60,89,252,262,470],tabsiz:[180,368,369],tabul:[258,368,427],tabular:[60,167,395],tac:453,tack:98,tackl:470,tad:4,tadek:477,tag1:470,tag:[54,60,101,180,208,215,239,240,287,328,348,371,380,382,395,396,426,429,434,470,475,477],tag_bind:401,tag_configur:401,tag_ha:401,tagbanwa:104,tagnam:[287,401,426,427],taifersar:477,tail:[56,143,152,180,212,251,305,356,429,475],tailor:[76,242,388],take:[0,1,4,6,20,28,30,41,43,50,51,53,55,56,58,60,62,63,66,68,70,72,73,75,77,79,81,82,87,88,90,93,94,95,96,98,99,100,101,102,103,104,106,108,123,125,126,127,129,132,134,140,143,145,150,155,157,158,160,162,167,168,169,170,178,179,180,182,186,191,192,193,195,197,198,200,201,202,203,207,210,218,219,222,227,230,235,238,239,244,248,251,253,256,258,259,260,264,265,266,273,277,281,292,293,303,304,308,311,312,321,322,332,333,339,343,345,348,350,353,360,361,365,368,369,370,374,380,384,386,387,389,393,394,396,401,403,407,410,416,423,424,426,427,428,429,431,433,434,435,437,440,442,447,450,457,459,460,461,470,471,472,473,474,475,476,477,478],take_act:303,takefocu:[84,401],taken:[1,4,39,48,55,58,64,70,77,79,96,99,123,127,129,134,152,174,178,182,186,192,198,200,201,208,215,219,222,225,230,246,264,266,281,287,293,297,304,305,311,315,322,325,328,336,351,353,365,368,373,380,384,388,389,391,396,405,414,416,439,446,447,451,457,461,470,472,473,475],takewhil:[96,258],takuji:438,talent:93,talin:476,talk:[50,83,102,104,106,116,117,355,365,401,440,451,452,467,475],talkto:116,talli:[152,477],tamil:104,tan:[147,277],tandem:216,tangent:[147,277],tanh:[147,277],tape:[236,384],tar:[60,63,64,70,73,83,107,122,252,281,303,352,470,473,474,475,476,477],tar_gzip:384,tar_plain:384,tarbal:[63,64,70,73,470],tarek:[352,476,477],tarerror:384,tarfil:[60,122,252,352,462,473,474,475,476,477],tarfilecompat:384,target:[6,28,30,56,60,63,64,66,72,84,87,98,99,100,107,116,125,152,157,160,163,167,178,182,266,267,293,303,304,308,328,330,333,352,361,379,384,391,396,423,426,429,431,434,435,439,440,441,442,447,473,475,476],target_desc:63,target_handl:99,target_lang:63,target_list:[439,442,447],tarinfo:[60,122,477],task1:463,task2:463,task3:463,task4:463,task:[30,57,60,62,70,77,88,90,91,96,98,101,104,106,107,108,127,137,160,192,197,202,236,273,293,294,322,330,343,355,361,390,391,450,455,460,462,463,464,470,472,476,477],task_don:[293,330,475],task_queu:293,tasks1:293,tasks2:293,tast:88,tax:[83,88,460,463,473],taxonomi:407,taylor:476,tb_frame:[253,404,440],tb_lasti:[253,440],tb_lineno:[253,400,440],tb_next:[253,440],tback:125,tbreak:309,tbutton:401,tcallback:293,tcdrain:387,tcflow:387,tcflush:387,tcgetattr:[87,387],tcgetpgrp:304,tchild:293,tciflush:387,tcioff:387,tcioflush:387,tcion:387,tck:477,tcl83:75,tcl8:477,tcl:[60,84,244,252,394,395,401,463,467,470,473,476,477],tcl_librari:84,tcl_obj:473,tclose:293,tclsam_init:84,tcoflush:387,tcombobox:401,tcooff:387,tcoon:387,tcp:[83,87,98,99,267,293,338,355,360,361,365,476,477],tcp_:360,tcp_nodelai:[102,477],tcpclient:361,tcpserver:[60,99,132,254,265,354,355,477],tcsadrain:387,tcsaflush:[87,387,402],tcsanow:[87,387],tcsendbreak:387,tcsetattr:[87,387,402],tcsetpgrp:304,tcsh:474,tea:462,teach:[83,230,472],team:[62,438,469,470,471,472,477],tear:[186,407],teardown:[186,388,407,477],teardownclass:[60,179,477],teardownmodul:[60,179,477],tebeka:477,technic:[6,83,90,96,105,109,174,206,222,260,303,368,416,467,470,477],techniqu:[30,60,81,88,90,96,99,102,103,104,127,143,152,186,304,322,387,394,452,456,457,463],technolog:[83,87,93,102,106,254,259,270,438],techtonik:477,ted:322,tediou:[64,66,72,104,106,107,125,143,450,470,475],tee:[96,169,258,474],tee_lookahead:258,tel:453,telephon:333,teleprint:170,teletyp:215,tell:[4,26,28,36,55,60,63,67,71,72,77,79,81,83,88,89,91,93,96,99,100,101,102,106,107,109,118,123,127,139,143,146,151,186,219,221,227,256,265,270,271,287,292,293,303,306,330,339,360,361,365,368,376,384,386,395,396,399,409,417,423,451,457,470,472,473,474,476],telnet:[60,252,254,411,476],telnetlib:[60,252,254,476],telopt_:385,temp0:168,temp1:168,temp:[66,75,77,99,107,123,293,304,350,364,386,427],tempdir:386,tempfil:[60,87,211,222,252,293,304,368,409,476],templat:[60,63,69,72,77,88,90,98,222,333,368,372,386,393,403,408,456,457,472,474,476,477],tempnam:304,tempo:101,temporari:[45,48,60,63,64,66,79,87,90,99,105,107,109,134,168,186,211,221,252,258,273,274,293,304,309,342,346,368,380,388,407,410,439,472,474,476],temporarili:[20,30,60,64,77,81,90,99,105,107,140,167,178,186,225,230,265,329,346,353,388,393,401,407,439,476],temporary_redirect:241,temporaryfil:[276,386],tempt:[79,99,100,101,393,446,453,462,465],temptat:[101,407,471],ten:[1,83,152,169,178,322,455,473],ten_year:174,tend:[30,81,88,106,180,318,322,451],tenfold:474,teninteg:168,tenpointsarraytyp:168,tenth:[93,129,169,203,339],tenuous:127,tep:309,term:[30,60,64,70,77,83,88,90,91,94,96,100,104,106,107,114,117,126,142,162,169,178,192,202,203,206,235,250,255,265,276,300,303,311,322,337,339,369,376,401,404,417,418,430,443,447,451,461,474,476,477],termattr:169,termin:[4,6,15,26,28,32,39,50,55,56,58,60,63,70,72,77,87,88,89,93,95,96,98,104,107,113,120,123,126,127,128,148,167,168,170,180,182,186,196,202,219,222,229,238,252,253,256,258,263,264,267,270,273,293,296,303,304,308,309,311,314,339,348,358,361,364,365,368,369,374,380,387,390,391,392,397,398,408,409,416,423,427,431,438,439,441,446,447,451,452,456,465,467,469,470,474,475,476],terminalcommand:476,terminateprocess:[89,293,304,374,476,477],termine:104,terminfo:169,terminolog:[60,69,120,212,227,270,276,392,426,451,471,472,475,476],termio:[60,87,207,252,402,408],termnam:169,termstr:169,ternari:[55,440,442],ternaryfunc:[55,79],terri:453,terribl:[101,236],ters:[87,315,407,444,464],test1:[369,439],test2:[309,369,439],test:[20,30,40,43,54,55,60,63,70,71,72,73,77,79,81,82,88,90,91,93,95,98,99,101,103,104,105,107,114,116,123,125,132,144,148,152,157,168,169,170,178,179,192,193,206,212,214,216,222,228,236,238,240,243,246,248,252,253,254,257,260,262,264,274,283,292,293,294,302,304,308,309,317,318,323,329,332,333,339,346,354,358,364,366,380,389,391,393,394,401,410,412,418,423,429,434,435,438,439,440,443,445,450,452,453,457,460,461,462,463,465,470,471,472,473,474,475,476,477],test_:[388,407],test_averag:462,test_bufio:473,test_c_api:30,test_cas:407,test_class:407,test_condit:293,test_conditionspe:293,test_count:186,test_default_s:407,test_doctest:186,test_epol:60,test_ev:293,test_fail:407,test_feature_on:388,test_feature_two:388,test_find:186,test_format:407,test_func:388,test_gener:[96,472,473],test_isupp:407,test_join_timeout:293,test_lock:293,test_lockspe:293,test_main:388,test_method:407,test_modul:407,test_module1:407,test_module2:407,test_not_run:407,test_noth:407,test_on:407,test_pipespe:293,test_queu:293,test_queuespe:293,test_res:407,test_semaphor:293,test_seqspe:293,test_sharedvalu:293,test_signal_handl:407,test_spam:388,test_split:407,test_support:[388,435,476],test_thre:407,test_two:407,test_upp:407,test_valu:293,test_widget:407,test_windows_support:407,testabl:407,testal:476,testandset:294,testcas:[186,388,407,462,477],testcase1:407,testcase2:407,testcase3:407,testcaseclass:407,testclass:407,testcomplet:82,tester:186,testfail:388,testfil:[186,320,475],testfn:388,testfunc:407,testfuncacceptssequ:388,testlist1:443,testlist:443,testlist_comp:443,testlist_saf:443,testload:[388,407,477],testmethodprefix:407,testmod:[186,462,474],testprogram:407,testpypi:365,testresult:[186,407,477],testrunn:[186,407],testsometh:407,testsourc:186,testsrun:407,teststatisticalfunct:462,teststringmethod:407,testsuit:[186,407,473],testzip:435,tex:101,text1:180,text2:180,text:[4,47,52,55,60,63,64,71,72,76,79,81,83,87,88,90,91,92,96,98,99,101,102,104,105,106,115,117,120,123,125,131,132,140,143,145,148,149,150,151,157,158,159,167,168,170,173,179,180,191,192,193,194,195,197,199,200,201,202,205,206,210,211,212,219,221,222,236,239,240,241,243,246,249,252,253,260,264,265,266,268,273,275,280,290,291,292,296,299,303,304,308,311,317,318,322,327,328,331,332,334,339,340,348,353,354,364,365,368,369,371,372,374,385,386,393,394,395,396,400,401,403,406,407,409,410,415,416,419,423,425,427,429,431,435,438,441,442,445,446,450,457,460,461,463,469,470,471,472,473,474,475,476,477],text_factori:364,text_fil:69,text_nod:[426,427],text_or_uri:429,textbook:[96,101,236,333,475,476],textbox:[60,93,120,476],textcalendar:140,textdomain:[230,264],textedit:[60,268],textfil:[69,136,193],textiobas:[256,396,476,477],textiowrapp:[256,476],textmat:467,textnod:475,textpad:[60,93,120,252,476],textread:311,texttestresult:407,texttestrunn:407,textual:[79,88,92,100,104,123,168,197,230,239,265,269,296,328,333,401,407,426,427,438,442,447,451,472],textvari:[396,401],textwrangl:467,textwrap:[60,123,252,372,463,473,476],textwrapp:[389,473],tgarbag:293,tgot:293,tgtkei:258,tgz:[89,281,468],thai:[150,438],than:[1,4,6,14,16,19,21,25,26,28,29,30,33,34,36,37,39,43,48,49,51,55,56,60,63,64,67,72,76,77,79,81,83,84,86,87,88,89,90,91,92,93,95,96,97,98,100,101,102,103,104,105,106,107,108,111,113,118,119,123,124,125,127,128,134,135,137,139,142,143,147,150,152,157,160,162,167,168,169,174,175,178,180,182,184,186,191,192,194,195,197,200,203,204,206,207,210,211,212,215,216,219,222,223,225,229,230,231,235,236,238,240,244,245,246,247,249,253,256,258,260,265,266,267,273,276,277,281,283,287,292,293,296,299,301,302,303,304,305,306,307,308,309,311,315,317,319,321,322,326,328,330,332,333,336,338,342,343,344,346,350,352,353,355,356,358,360,361,364,365,366,368,369,373,374,379,380,384,385,386,388,389,391,392,393,394,396,400,401,403,404,407,409,410,411,413,416,418,423,425,426,427,429,431,434,435,437,438,439,440,442,445,446,447,450,451,452,453,454,455,457,459,460,461,463,464,465,470,471,472,473,474,475,476,477],thank:[0,80,96,100,104,193,235,293,388,438,470,471,472,473,474,475,476,477],the_answ:451,the_except:407,the_list:81,the_pag:105,the_world_is_flat:459,thei:[2,4,6,7,16,18,20,21,24,25,28,30,37,45,48,51,52,55,56,58,62,63,64,67,68,70,71,72,73,75,77,78,79,81,83,87,88,89,90,91,92,93,94,96,98,99,100,101,102,103,104,105,106,107,108,109,111,113,119,120,123,125,126,127,128,129,134,136,138,140,141,143,146,147,148,150,152,153,157,158,159,160,162,163,166,167,168,169,170,171,174,178,180,182,183,186,191,194,195,200,202,203,206,208,212,221,222,223,224,225,228,230,231,232,233,235,236,240,244,246,249,253,254,256,258,260,265,266,267,271,273,276,277,281,282,283,286,287,290,291,293,302,303,304,305,306,311,314,316,318,320,321,322,323,328,333,336,338,339,343,345,346,352,353,358,359,360,361,362,364,365,366,368,369,370,371,373,374,376,380,384,385,386,388,389,390,391,392,393,394,396,398,399,401,403,406,407,409,410,411,416,418,423,424,425,426,427,429,430,431,432,433,434,435,439,440,441,442,445,446,447,451,452,453,454,457,458,460,461,462,463,465,467,468,470,471,472,473,474,475,476,477,478],theiter:364,theller:475,thello:389,them:[1,4,6,14,15,19,28,30,55,56,58,60,63,64,67,68,70,72,73,77,79,80,81,82,83,84,86,87,88,89,90,91,93,95,96,98,101,102,105,106,107,108,109,113,123,124,125,127,137,138,141,148,150,151,152,156,158,159,162,167,168,169,174,175,178,182,184,186,191,194,201,202,208,222,223,224,225,226,230,232,236,240,249,253,255,256,264,265,266,267,268,271,273,280,292,293,300,302,303,304,305,306,308,311,314,321,322,331,333,336,338,339,342,345,350,358,361,364,365,366,368,369,371,373,374,376,377,385,386,388,389,391,393,394,396,403,405,407,410,411,412,413,415,416,417,425,426,427,429,435,440,442,445,446,447,453,454,457,460,461,462,463,464,465,467,468,469,470,471,472,473,474,475,476,477],theme:[60,244,252,395,473,476],theme_cr:401,theme_nam:401,theme_set:401,theme_us:401,themechang:401,themenam:401,themonth:140,themselv:[28,55,72,77,79,81,89,90,98,101,108,129,143,150,157,163,167,168,230,258,260,276,293,309,311,333,348,368,389,407,427,434,440,442,451,453,465,472,475,476,477],theoret:[60,96,237,301],theori:[30,60,87,173,333,438],thereaft:[264,409,459],therebi:[77,88,219,403,469],therefor:[4,6,28,30,37,55,56,70,72,77,79,81,87,88,90,91,96,100,101,104,106,123,132,135,143,150,162,165,168,174,192,207,221,245,256,264,276,290,293,304,305,311,327,333,337,350,360,365,368,380,391,394,403,416,430,435,437,439,440,442,445,451,454,455,460,461,468,470,471,472,473,474,475,476,477],therein:[276,311],thereof:[127,191,201,221,222,267,391,438,440,441,451],thermomet:191,theses:293,thetestsuit:407,theth:333,theyear:140,thi:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,19,20,21,22,23,24,25,26,27,28,29,30,31,33,34,35,36,37,38,39,40,41,42,43,44,45,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,84,86,87,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,155,156,157,158,159,160,161,162,163,165,166,167,168,169,170,171,172,173,174,175,176,178,179,180,182,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,280,281,282,283,284,285,286,287,288,289,290,291,292,293,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,397,398,399,400,401,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,469,470,471,472,473,474,475,476,477],thick:403,thin:[22,52,60,127,277,298,316,350,395],thing:[28,60,63,70,72,76,77,79,80,81,86,87,88,89,93,95,96,98,100,102,104,105,106,107,115,123,127,149,151,157,160,161,168,186,193,201,207,219,221,244,253,256,265,266,273,277,293,303,308,311,333,344,348,353,356,365,368,371,380,391,393,396,401,404,406,410,412,416,419,442,445,450,451,453,455,460,461,466,467,468,469,470,471,472,473,474,475],thingi:[270,460],think:[50,53,63,64,72,79,81,83,88,95,96,101,102,104,106,107,186,236,265,303,440,442,452,453,460,472,475,476],thinli:319,third:[4,20,24,26,28,53,55,63,68,69,70,77,78,79,81,83,86,87,88,90,91,95,96,98,101,104,106,107,108,118,139,158,168,169,174,178,182,206,222,228,251,256,258,265,266,308,321,333,352,360,364,365,368,369,380,381,400,407,409,410,434,438,440,446,447,453,456,457,460,467,469,470,471,472,473,474,475,476,477],thirti:170,this_dir:407,this_fail:454,tho:460,thoma:[88,470,471,474,475,476,477],thon:460,thorough:[91,333],thoroughli:458,those:[4,6,28,30,31,52,55,56,58,62,63,67,70,72,73,76,77,78,79,80,81,83,87,88,89,90,93,94,95,98,99,100,101,102,103,104,105,106,107,113,119,123,138,139,143,147,150,152,157,161,164,167,168,169,170,174,178,180,182,186,191,192,198,199,200,204,206,208,212,215,216,219,221,222,225,228,234,244,253,256,258,260,264,265,266,273,277,279,281,293,294,300,302,303,304,306,308,309,311,322,324,328,332,333,336,337,338,342,343,346,350,353,358,360,365,368,369,370,373,384,387,392,394,400,401,403,407,409,410,411,416,418,426,429,431,432,435,438,439,440,441,442,446,447,450,451,452,453,459,460,461,462,463,472,473,474,475,476,477],thou:369,though:[1,8,28,30,50,51,55,64,66,67,70,72,77,79,80,83,87,88,89,90,93,96,99,100,101,102,104,105,114,123,127,148,150,152,162,169,178,186,192,196,201,212,230,253,256,260,265,273,277,293,294,303,304,318,325,328,333,348,365,368,369,373,380,391,392,407,410,423,426,431,434,438,440,441,442,445,446,447,451,453,459,460,464,465,469,470,471,472,473,474,475,476],thought:[21,81,83,96,106,293,317,470,472,473],thousand:[60,83,104,252,264,322,333,369,425,452,478],thousands_sep:264,thousep:264,thread:[16,20,21,26,27,30,46,52,55,60,77,82,84,88,90,98,102,120,127,130,138,139,140,152,168,180,216,235,238,246,249,252,264,266,273,294,301,304,317,330,332,336,342,343,346,353,361,362,364,365,368,380,392,400,409,416,418,439,440,456,465,470,472,473,474,475,476,477],thread_task:87,threaddebug:465,threadedtcprequesthandl:361,threadedtcpserv:361,threaderror:391,threadgroup:391,threading_algorithm:246,threadingmixin:361,threadingtcpserv:[99,361],threadingudpserv:361,threadloc:99,threadnam:[99,265],threadsaf:[265,332,395],threat:304,threaten:[96,472,473],three:[4,20,28,30,51,55,64,70,71,72,75,77,79,80,81,87,88,90,98,101,102,103,104,106,107,111,118,123,126,142,150,152,154,157,158,162,164,167,168,169,178,180,182,186,191,200,202,208,212,215,222,223,225,231,235,236,239,240,246,247,264,266,267,273,279,284,287,292,293,296,299,303,306,308,311,321,322,326,328,330,333,345,352,356,360,365,368,373,380,384,385,386,391,392,393,396,401,403,407,409,410,412,419,425,426,430,431,434,439,440,442,445,446,447,448,451,452,453,457,459,461,462,463,467,470,471,472,473,474,475,476,477],three_year:174,threefold:98,threshold0:225,threshold1:225,threshold2:225,threshold:[37,81,98,99,225,245,265,475],throttl:265,through:[4,6,8,11,13,14,17,19,28,37,48,50,55,56,60,63,64,71,72,75,77,79,80,81,83,87,88,91,94,96,98,99,100,101,102,104,105,107,108,121,123,124,132,134,139,142,143,150,158,161,167,168,169,170,174,177,178,186,195,197,198,199,201,204,208,219,227,230,239,241,243,244,249,264,265,266,276,277,287,290,293,303,304,305,309,313,316,319,328,331,333,337,358,360,365,366,368,369,374,377,381,388,389,391,393,394,396,407,410,411,415,418,422,426,427,429,433,434,437,439,440,445,447,450,451,452,453,456,460,461,462,463,464,465,467,469,470,471,472,473,474,475,476,477,478],throughout:[14,56,77,83,88,94,109,178,445,470,472,473,475,476,477],throughput:477,throwflag:58,thrown:[58,96,160,174,178,305,472,473],thru:[138,438],ths:368,thu:[4,30,33,37,63,64,67,70,72,77,81,87,88,90,93,98,99,100,101,106,107,113,118,123,127,128,142,160,162,168,169,199,206,222,228,260,264,265,266,267,293,303,311,314,327,333,338,339,351,364,368,369,380,386,388,392,396,403,407,411,423,439,442,446,447,451,452,453,460,461,465,469,470],thumb:[55,100,180,401],thunderbird:101,thursdai:[140,174],thusli:403,thy:93,tibetan:104,tic:453,tick:[79,88,219,269,322,336,392],ticket:106,tide:394,tidi:[265,407,473,475,476],tidier:475,tie:[212,236],tied:[28,63,157,365],tiedemann:470,ties:[178,322,368,455],tiff:[248,396,475],tiger:333,tigetflag:169,tigetnum:169,tigetstr:169,tight:[98,106],tighten:[162,470,477],tighter:[439,474],tightli:[88,106,245,442,445],tild:[107,232,305,397],tile:[401,403,477],till:[222,293,322,365,385],tilleniu:475,tilt:403,tiltangl:403,tim:[369,393,438,469,470,471,472,473,474,475,477],time2internald:246,time:[1,3,12,17,20,24,28,36,47,55,56,58,60,62,63,64,70,72,73,76,77,78,79,80,81,82,83,84,88,89,90,91,93,95,96,100,101,102,105,106,107,108,113,118,120,123,124,127,128,129,130,132,134,135,140,142,143,149,151,152,156,157,159,162,164,167,168,169,173,177,178,180,184,185,186,198,203,205,208,210,213,222,225,230,231,234,235,236,237,238,239,240,244,246,249,252,253,255,256,258,264,265,266,267,271,273,290,291,293,299,303,304,305,306,308,309,311,312,316,317,319,322,323,328,330,332,333,334,336,337,338,339,341,343,345,348,350,351,352,353,354,360,361,364,365,366,368,370,374,377,380,383,384,385,386,389,390,391,394,396,399,401,403,405,407,409,410,413,415,416,418,423,424,425,426,431,432,434,435,436,438,439,440,441,442,445,446,447,448,449,450,451,452,453,454,456,458,460,461,463,465,470,471,472,474,475,476,477],time_:273,time_hi_vers:415,time_low:415,time_mid:415,time_to_birthdai:174,time_wait:360,timedelta:[17,60,173,404,473,477],timedrotatingfilehandl:[60,98,120,474,476],timefunc:343,timegm:[140,392],timeit:[60,177,252,322,462,465,473,474,476],timeout:[99,102,105,116,127,160,169,221,241,293,318,330,345,358,360,361,364,385,391,410,473,476,477],timeouterror:293,timer1:473,timer2:473,timer:[60,93,177,205,212,293,343,345,353,362,393,401,403,462,472,473,476],timestamp:[63,99,132,140,152,156,174,203,234,236,265,280,304,339,364,365,380,384,399,415,435,473,477],timetupl:[174,364],timetz:174,timeunit:322,timev:203,timezon:[174,203,339,365,392,462],timo:438,timothi:438,timsort:103,tin:[105,273],tini:[4,81,87,88,91,101,106,231,311,470,476,477],tino:473,tiocgpgrp:207,tip:[60,62,88,242,244,391,461,470,477],tipc:[360,476],tipc_:360,tipc_addr_id:360,tipc_addr_nam:360,tipc_addr_nameseq:360,tipc_cluster_scop:360,tipc_node_scop:360,tipc_zone_scop:360,tire:438,tiremove_thisg:333,tirosh:473,tis:473,tishler:[471,473],tismer:470,titl:[1,56,64,79,83,87,90,96,101,104,105,121,123,143,152,187,191,219,240,244,290,293,299,303,360,364,368,369,396,403,427,429,464,470,472,474],titlebar:403,titlecas:[56,368],titledhelpformatt:303,titlestr:403,tix8183:394,tix:[60,84,252,395,396,473],tix_addbitmapdir:394,tix_cget:394,tix_config:394,tix_configur:394,tix_filedialog:394,tix_getbitmap:394,tix_getimag:394,tix_librari:394,tix_option_get:394,tix_resetopt:394,tixcommand:394,tixexfileselectdialog:394,tixinspect:394,tixnotebook:394,tjh:438,tk8183:394,tk_librari:84,tk_popup:394,tkapp:473,tkappinit:84,tkcmd:477,tkcolorchoos:396,tkcommondialog:396,tkconstant:[394,396],tkdnd:396,tkdoc:396,tkfiledialog:396,tkfont:396,tkinter:[60,83,101,244,252,307,327,344,394,395,401,403,467,470,473,476],tkmessagebox:396,tksimpledialog:396,tlabel:401,tld:266,tlist:[293,394],tls1:477,tls:365,tlsv1:365,tm_hour:392,tm_isdst:[174,392],tm_mdai:392,tm_min:392,tm_mon:392,tm_sec:392,tm_wdai:392,tm_ydai:392,tm_year:[90,174,392,472],tmap:293,tmenubutton:401,tmp1223:274,tmp:[79,104,107,181,273,304,338,352,386,470,473,474,475,476,477],tmp_max:304,tmpdir:[304,386],tmpfile:304,tmpg7v1y0:386,tmpnam:304,tmpwriterrexec:338,to_addr:358,to_angl:403,to_eng_str:[178,474],to_integr:178,to_integral_exact:178,to_integral_valu:178,to_output:194,to_sci_str:[178,474],to_splitt:194,toaddr:[87,266,267,358],toaiff:[405,476],toascii:150,tobi:470,tobia:470,tobuf:384,tobyt:[368,477],toc:438,tochild:[87,317],todai:[30,76,100,104,174,306,364,384,434,455,462,471,473,474,476],todat:180,todesc:180,toe:453,tofil:[124,180],tofiled:180,tofold:279,togeth:[16,30,55,60,63,64,70,76,81,88,92,93,96,98,99,100,101,102,106,120,123,150,152,161,162,167,168,182,186,202,210,219,222,258,265,270,273,284,344,365,368,403,407,410,430,438,440,442,451,453,456,460,462,474],toggl:[219,244,401],togglepaus:142,tohexstr:368,tok_nam:397,token:[58,60,87,88,125,252,262,290,296,308,313,328,333,351,374,383,396,410,444,445,454,458,477],tokeneat:398,tokenerror:398,toknum:398,tokval:398,told:[98,243,473],toler:129,tolin:180,tolist:[124,308,368,472,477],tom:[472,475],tomato:364,tomono:129,ton:[279,369],tonam:221,tone:259,toni:[333,476],too:[4,6,16,29,55,60,79,81,87,93,95,96,98,99,101,104,105,106,107,114,123,136,143,147,150,162,163,168,178,182,186,199,205,206,212,225,227,231,256,293,302,303,304,318,321,332,333,337,353,360,361,365,368,369,373,374,380,391,403,425,435,436,437,438,440,445,446,450,452,456,457,460,462,470,471,472,473,474,476,477],took:[103,470],tool:[26,28,30,60,63,64,69,76,78,79,81,82,83,84,86,89,90,93,94,96,98,100,101,106,107,108,109,111,113,120,121,132,139,144,148,152,157,158,161,162,164,176,180,184,186,187,188,189,199,221,223,224,226,230,232,239,240,241,249,252,254,258,260,262,295,302,307,330,335,341,344,351,352,354,355,361,365,380,390,394,396,398,403,405,407,409,410,411,413,420,434,435,451,456,462,465,467,468,469,470,471,472,473,475,476],toolbar:219,toolbox:[60,107,252,268,269,471,472,473],toolchain:[0,476],toolkit:[60,104,244,258,307,349,395,396,438,450,467,470],toolset:[0,94,258,303,462,476],tooltip:403,toordin:174,top:[1,26,28,30,37,60,63,70,72,77,79,81,87,88,93,96,98,100,101,105,106,107,121,123,143,145,150,157,158,162,168,169,171,180,182,186,187,192,202,219,222,230,236,244,246,247,251,252,253,256,264,279,281,295,304,311,314,316,318,322,326,327,328,329,342,365,366,379,380,388,390,391,394,395,396,401,403,407,418,429,434,435,439,440,441,444,446,447,451,453,461,465,468,469,470,471,472,473,475,476,477],top_el:427,top_level_dir:407,top_level_url:105,top_panel:171,topbottom:403,topdown:304,topic:[60,62,72,76,82,83,87,91,93,97,101,106,120,148,186,222,265,303,396,470,473],toplevel:[77,95,152,178,222,379,394,396,401,429],topmost:[219,380,475],topolog:473,toprettyxml:[427,473],torgb:476,torn:440,tort:438,tortiou:438,tos1:182,tos2:182,tos3:182,tos:203,toshiba:142,toss:473,tostereo:129,tostr:[88,124,429,477],tostringlist:429,total:[6,28,30,38,52,53,56,77,81,91,96,118,139,142,152,174,178,180,186,200,221,222,230,236,256,274,322,332,364,365,367,368,369,393,401,407,409,440,442,446,465,477],total_chang:364,total_ord:[103,223,440,442,477],total_second:[174,477],totals:102,tottim:[238,322],totupl:308,touch:[4,60,88,91,106,169,222,271,304,368,405,441,450,461,476],touchlin:169,touchwin:169,tough:88,tounicod:[124,150],tour:[60,96,456,472,473,478],tournament:236,tovideo:245,toward:[60,106,178,186,200,210,220,222,265,368,389,403,440,451,456,471,473,475,476],tower:[60,218,301,403,476],town:102,tox:100,toxml:[427,470,473],tp_:79,tp_alloc:[55,79],tp_as_buff:[55,79],tp_as_map:[55,79],tp_as_numb:[41,55,79],tp_as_sequ:[55,79],tp_base:[55,79],tp_basics:[3,55,79],tp_cach:[55,79],tp_call:[55,79],tp_clear:[24,55,79],tp_compar:[55,79],tp_dealloc:[3,24,55,79],tp_descr_get:[55,79],tp_descr_set:[55,79],tp_dict:[55,79,476],tp_dictoffset:[55,79],tp_doc:[55,79],tp_flag:[24,55,79,476],tp_free:[55,79],tp_getattr:[51,55,79],tp_getattro:[43,51,55,79],tp_getattrofunc:79,tp_getset:[51,55,79],tp_hash:[43,55,79,476],tp_init:[55,79],tp_is_gc:[55,79],tp_items:[3,55,79],tp_iter:[55,79,368,472],tp_iternext:[31,55,79,368,472],tp_maxalloc:55,tp_member:[55,79],tp_method:[55,79],tp_mro:[55,79],tp_name:[55,79],tp_new:[55,79],tp_next:55,tp_print:[55,79],tp_repr:[55,79],tp_richcmp:471,tp_richcompar:[55,79],tp_setattr:[55,79],tp_setattro:[43,55,79],tp_setattrofunc:79,tp_str:[55,79],tp_subclass:[55,79],tp_travers:[24,55,79,225],tp_weaklist:[55,79],tp_weaklistoffset:[55,79],tparm:169,tpip:96,tpool:293,tput:169,tr44:[104,406],trac:476,trace:[27,30,60,73,77,88,92,98,134,149,163,177,236,246,252,253,255,309,380,390,391,400,403,440,447,449,451,465,471,472,473,477],trace_dispatch:134,traceback:[20,30,58,60,72,77,79,81,82,88,91,95,96,98,99,104,106,123,127,128,143,149,152,156,158,168,169,178,182,186,206,216,244,252,253,254,263,265,266,267,293,309,329,333,361,364,365,368,369,370,374,380,393,403,404,406,407,423,439,440,442,447,451,452,453,454,457,460,463,471,472,473,474,475,476,477],traceback_limit:423,tracebacklimit:380,tracebackobject:474,tracebacktyp:404,tracefunc:380,tracer:[399,403,476],track:[20,24,30,60,63,72,81,88,90,98,100,101,142,143,150,151,152,177,178,186,215,219,225,236,252,277,303,304,311,330,345,364,368,396,405,413,426,439,463,470,471,474,477],trackcal:399,tracker:[60,62,108,475,477],tractabl:87,trade:[7,208,303,438,463],trademark:[83,438],tradeoff:37,tradit:[63,77,81,107,150,264,273,303,304,324,326,388,439,462,476],tradition:[107,322,385,473],traffic:[83,360,472],trail:[4,16,28,56,63,72,81,93,96,101,131,135,149,150,151,155,169,178,180,191,200,218,221,222,228,240,244,253,258,260,273,292,299,302,305,328,339,348,368,369,380,382,392,396,400,409,423,426,437,442,446,451,453,457,460,463,465,470,474,476,477],trailer:[98,437,443],trailneg:178,trainer:222,tran:[364,475],transact:[60,96,138,152,162,241,290,310,332,391,410,473,475,476],transaction_count:152,transcript:186,transfer:[28,30,76,77,93,102,105,131,161,194,195,197,198,200,201,221,243,273,276,280,281,293,299,355,358,409,414,434,442,476,477],transfercmd:221,transform:[63,90,94,96,100,102,103,104,109,125,137,150,157,158,167,174,178,186,192,197,200,215,223,236,239,260,264,273,311,346,398,403,439,440,442,460,470,471,476],transientresourc:[388,476],transit:[60,105,174,223,250,266,350,361,410,442,454,472,474,475,477],transitionerror:454,translat:[56,60,63,77,88,90,92,100,101,104,105,106,135,143,144,150,157,168,169,179,205,206,212,214,231,240,242,252,256,260,291,304,348,353,360,368,369,374,395,406,434,440,470,473,474,476,477],transliter:360,transmiss:[104,126,170,267,312,423],transmit:[105,126,129,231,360,387,423,425,434,474],transpar:[81,89,123,150,168,169,210,244,311,384,401,403,409,440,447,471,473,474],transport:[195,201,205,276,308,331,358,365,434,472],transpos:[222,453,474],transposed_row:453,trap:[160,178,216,393,413,472,474],trash:[55,273],trashcan:470,traur:472,travers:[24,26,45,55,79,81,90,96,109,125,156,175,200,226,265,368,401,423,447,470,472,473,475,476,477],traverseproc:[24,55,79],travi:[475,476,477],trb:82,treat:[5,30,40,49,51,56,58,63,87,91,95,96,100,101,104,111,123,124,127,129,144,150,152,158,162,163,169,174,178,180,185,186,207,218,222,223,232,239,258,259,265,266,277,283,292,299,303,305,333,348,351,357,358,364,368,369,374,376,384,388,389,393,396,401,407,409,410,411,416,417,423,439,440,441,442,447,451,459,460,461,470,472,475,476,477],treatment:[43,63,99,215,222,308,411,470],tree:[15,28,60,64,67,69,70,72,73,81,87,88,89,90,96,107,109,138,143,156,157,180,192,199,200,202,208,236,244,252,262,271,275,304,305,310,325,352,366,368,380,383,394,401,403,405,425,426,427,440,463,468,469,470,471,472,473,474,475,476,477],treebuild:[60,275],treenod:79,treeview:[60,395],treeviewclos:401,treeviewopen:401,treeviewselect:401,tremend:[87,452],trent:[469,470,473,475],trevor:474,tri:[13,26,28,77,79,81,88,90,95,96,101,106,107,109,129,151,168,182,185,186,203,222,249,264,267,281,291,293,300,304,315,327,333,336,339,358,364,369,373,403,410,440,442,445,454,470,471,472,473,474,475,476,477],trial:[186,473],triangl:[247,403],triangular:[332,476],trick:[26,81,88,168,380,451,472],tricki:[63,90,92,137,149,303,470,471],trickier:[88,303],trifl:107,trigger:[37,55,60,79,90,94,95,96,100,178,200,204,206,249,303,362,364,380,396,416,425,434,446,451,463,465,471,472,473,474,475,476,477],trigonometr:[60,301,474],trim:191,trio:317,trip:[162,398,476],tripl:[82,90,101,142,180,249,299,304,312,333,345,360,380,389,403,446,460],trivia:475,trivial:[60,64,72,76,77,81,87,96,105,106,120,143,234,293,333,423,451,462,473],trojan:477,trondheim:453,troubl:[76,95,102,105,474],trove:[72,100,473],true_v:475,true_valu:475,truediv:302,truli:[77,84,87,88,273,389,410,477],trunc:[277,300,368,476],truncat:[4,16,52,56,87,88,129,138,139,167,169,178,206,222,234,246,256,258,277,304,334,364,368,369,373,386,409,414,435,442,455,457,470,472,476,477],trunk:[380,475,476],trust:[75,143,241,266,293,314,318,337,365,374,410,476,477],trustworthi:365,truth:[5,60,63,91,96,102,168,222,252,302,373,434,440,442,473],try1_stmt:439,try2_stmt:439,try_stmt:[439,443],tryexcept:[125,157],tryfin:[125,157],tsc:[380,474],tshepang:91,tstate:28,ttermin:293,ttime:142,ttk:[60,252,395,396],ttk_intro:477,ttkstyle:401,ttob:247,ttshandler:99,tty:[60,87,169,222,229,252,256,304,368,408,448,449,459,465,476],ttynam:304,ttys0:353,tucson:96,tue:174,tuesdai:[140,174,267,462],tuininga:88,tunabl:235,tune:[81,138,162,225,303,333,365,437,470,473],tunnel:241,tup:[321,403],tupl:[3,4,13,15,17,20,23,28,30,33,35,37,43,47,48,50,51,55,58,60,63,72,76,77,79,90,96,98,99,101,103,104,105,109,111,113,114,118,121,123,124,125,127,129,132,134,138,139,140,141,142,145,150,153,155,157,162,164,168,169,173,174,178,180,181,182,186,192,200,203,206,213,215,219,221,222,223,225,231,233,235,236,241,243,246,247,249,251,252,253,256,258,259,260,264,265,267,273,274,276,281,288,290,293,296,297,299,300,302,303,304,305,306,308,311,315,316,317,318,322,324,328,330,333,336,338,339,343,345,346,351,352,353,355,357,358,359,360,361,363,364,365,366,367,369,372,373,374,376,379,380,381,385,386,388,390,391,392,396,398,400,401,403,404,407,409,410,411,413,415,416,417,418,423,429,431,432,434,435,439,440,442,447,451,452,454,456,460,461,462,470,471,472,473,474,475,476,477],tuple1:407,tuple2:407,tuple2st:308,tuple_param:109,tupletyp:[53,404],turbo:469,turbogear:60,turkish:150,turn:[4,20,30,51,55,64,77,81,87,88,91,93,94,96,98,100,101,104,105,106,107,109,123,162,168,169,180,186,203,216,222,236,239,244,249,253,264,265,292,293,303,304,310,313,320,339,345,353,354,355,360,364,365,370,380,387,391,393,403,407,409,410,416,437,439,445,446,447,453,458,459,465,470,471,472,473,474,475,476,477],turnoff_sigfp:216,turnon_sigfp:216,turnr:396,turtl:[60,244,252,395,396,476],turtle_docstringdict:403,turtle_docstringdict_german:403,turtle_docstringdict_italian:403,turtledemo:[244,403],turtledemo_two_canvas:403,turtlegraph:403,turtlegraphicserror:403,turtles:403,turtlescreen:[60,395],turtleshap:403,tut:104,tutor:96,tutori:[60,78,81,87,95,97,101,102,105,106,120,152,154,157,169,186,206,222,223,244,265,266,267,275,301,307,308,360,364,395,396,423,444,445,450,460,464,467,469,472,474,475,476],tutt:[157,470],tweak:[303,471,474],twelv:169,twice:[28,80,87,88,96,99,100,103,107,135,157,174,236,237,333,364,416,457,458,465,470,472,473,474,476,477],twin:470,twine:62,twinsun:174,twist:[438,452],twister:[60,332,473],twisti:93,twix:161,two:[4,5,6,13,14,20,24,28,30,31,32,36,37,41,43,50,51,55,56,59,60,63,64,67,70,71,72,73,76,77,79,80,81,83,87,88,89,90,91,94,95,96,98,99,100,101,102,103,104,105,106,107,111,113,118,123,126,127,129,131,132,134,135,137,138,140,142,143,147,149,150,151,152,155,157,160,162,163,164,165,167,168,169,170,174,178,180,182,186,191,192,194,198,200,202,203,204,206,208,210,212,215,218,221,222,223,228,229,230,236,239,244,245,246,248,253,255,256,257,258,264,265,266,269,270,273,277,281,283,287,290,292,293,294,299,300,303,304,306,308,309,311,313,315,318,322,328,330,331,332,333,336,337,339,342,343,346,350,353,356,357,360,361,364,365,366,368,369,370,371,373,376,380,384,388,389,391,392,394,396,398,401,403,404,406,407,409,410,415,416,417,418,423,424,426,429,432,435,437,439,440,442,443,444,445,446,447,448,449,451,452,453,454,455,457,460,461,462,463,467,469,470,471,472,473,474,475,476],twoplac:178,txt:[30,60,66,71,73,81,96,99,107,123,152,162,186,209,214,222,230,232,234,252,256,287,303,304,368,374,380,396,406,435,438,451,454,463,469,470,476,477],tycho:462,typ:246,type2:222,type:[1,2,3,4,5,6,8,9,10,12,14,15,17,18,19,20,21,22,23,24,25,26,27,28,29,32,33,34,35,36,37,38,39,41,42,43,44,45,46,47,48,49,50,51,53,59,60,63,64,69,70,71,77,78,80,82,83,87,88,89,90,91,92,93,94,95,98,99,101,102,105,106,107,109,114,115,117,118,120,121,124,125,126,127,132,134,138,139,142,143,144,145,146,148,150,152,157,158,159,160,161,163,164,165,167,169,170,175,176,178,180,182,185,186,188,191,192,193,194,195,196,197,199,200,201,202,203,205,206,208,212,219,222,225,226,230,231,235,237,239,240,241,243,244,246,247,249,252,255,256,260,264,265,266,267,269,271,274,275,276,277,280,282,284,286,287,288,290,293,295,297,301,302,304,308,309,310,314,315,316,319,320,321,327,328,329,330,332,333,334,335,338,343,345,350,351,352,353,354,360,361,365,366,369,370,372,373,374,376,379,380,384,388,390,392,395,398,400,401,403,405,407,409,410,411,413,416,417,418,419,421,422,423,424,425,427,429,431,432,434,435,439,441,442,444,446,447,448,449,450,451,452,454,456,457,458,459,460,461,463,464,465,469,470,471,477,478],type_:403,type_check:303,type_getattro:94,type_new:55,typeaelist:115,typeaerecord:115,typeahead:169,typealia:115,typecheck:168,typecod:[124,293,404,463],typecode_or_typ:293,typed_act:303,typed_subpart_iter:[192,199],typedef:[8,14,51,52,55,56,79],typedesc:168,typeerror:[4,6,19,20,31,34,36,41,42,43,47,48,50,55,56,59,77,79,88,90,91,96,105,121,124,131,135,152,158,164,168,174,178,186,195,196,200,201,206,222,239,253,258,260,266,276,287,303,316,368,373,380,392,407,418,427,434,440,442,447,452,453,454,460,461,462,470,471,472,473,474,475,476,477],typefloat:[115,117],typefsref:115,typefss:115,typeid:293,typelist:191,typelong:115,typemap:[89,267],typenam:[152,321,364,476],typeobj:407,typeobject:[4,94,472],types_map:[281,476],types_map_inv:281,typesystem:125,typetext:[115,117],typetyp:[54,288,404],typeunicodetext:115,typewrit:205,typic:[16,28,30,51,55,63,64,67,70,73,75,77,80,81,88,89,90,94,98,99,100,105,106,107,108,113,123,126,132,138,143,150,165,178,180,186,191,200,207,210,215,221,222,223,228,230,253,256,258,264,265,266,273,277,281,283,290,293,303,304,308,309,317,319,322,330,334,342,352,356,365,368,369,374,380,381,384,385,391,392,393,396,401,404,407,415,416,423,426,427,430,431,432,436,440,449,450,454,455,460,462,463,465,469,473,474,477],typifi:266,typist:107,typo:[81,96,143,438,442,472],tzfile:392,tzinfo:[60,173,473],tzname:[174,392],tzpars:475,tzset:392,tzvf:352,u00008000:104,u0020:460,u0020world:460,u0043:442,u0062:446,u00c7:442,u0327:442,u0660:[406,470],u1234:[104,150,260],u16:150,u2000ab:470,u2020:222,u2028:368,u2029:368,u20ac:104,u21ef:476,u2603:99,u2641:124,u3000:476,u304:476,u3054:476,u305f:476,u307:476,u3080:476,u3081:476,u31ef:476,u3244:476,u32:150,u4000:473,u4001abc:473,u4500:104,u4500abc:104,u751f:476,u_expr:442,ua000:104,uac:69,uadd:125,uall:[388,473],uat:266,ucd_3_2_0:[406,475],ucnhash_capi:477,ucs2:[56,82,150,222],ucs4:[56,82,150,222,472],udata:345,udp:[98,267,360,361,477],udpserv:[60,254],uf_append:[304,366,476],uf_compress:[304,366],uf_hidden:[304,366],uf_immut:[304,366,476],uf_nodump:[304,366],uf_nounlink:[304,366],uf_opaqu:[304,366],ufeff:[56,99],ufeffunicod:99,uff10:178,uff19:178,ufff:56,ufffd:150,ufffdabc:104,ufs:461,ugettext:230,ugh:95,ugli:[81,82,95,102,180,227,453,470,473],uhc:150,uhhhh:470,uid:[99,143,144,246,280,304,318,324,336,366,384,476,477],uidl:318,uint:168,uit:309,uitext:290,uiuc:409,uji:150,ukrainian:150,ulaw2lin:129,ulaw:[118,376],ulf:88,uli:169,ulong_max:34,ulp:476,ultim:[51,70,81,90,186,303,352,380,384,447,472,474],ultrasound:306,ulx:169,umask:[121,175,176,188,304],umber:406,umlaut:264,ump:309,una:475,unabl:[63,93,95,96,98,105,186,273,345,380,389,475],unacc:104,unaccept:[81,447],unadorn:[60,368],unaffect:[63,178,352,447,473,476],unalia:309,unallow:337,unalt:[73,142,453],unam:[63,304,315,338,380,381,384],unambigu:[81,123,174,266,322,368,440,457,476],unari:[60,178,182,368,440,444,446],unary_convert:182,unary_invert:182,unary_neg:182,unary_not:182,unary_posit:182,unaryadd:157,unaryfunc:55,unaryop:125,unarysub:157,unassign:371,unauthent:[276,311,328,365,425,427,428,429,430,434],unauthor:[105,241],unavail:[81,87,92,105,186,229,293,304,337,440],unavoid:[96,174,474,477],unawar:474,unbeliev:102,unbidden:244,unbind:441,unblock:[293,330],unbound:[38,88,94,99,152,178,222,253,293,297,302,330,368,403,418,440,447,472,474],unboundlocalerror:[20,206,441,461,470],unboundmethodtyp:404,unbrac:369,unbuff:[139,222,256,374,465],unbundl:227,unc:[304,305,435],uncas:368,uncaught:[93,145,380,442,471],unchang:[37,81,94,99,101,109,124,143,148,152,163,168,169,178,215,222,230,258,264,273,304,305,314,332,333,360,368,369,403,440,442,446,451,457,463,472,474,475,476,477],unclean:475,unclear:101,unclos:[244,304,364,398],uncollect:225,uncolor:244,uncom:[193,244,405,472],uncomfort:81,uncommon:475,uncomp_s:463,uncompil:385,uncompress:[118,139,234,259,352,384,435,437],uncondit:[309,446],uncondition:[222,244,293,304,346,390,407,440,449,454,477],unconnect:476,unconsum:437,unconsumed_tail:437,uncontrol:352,uncontroversi:426,unconvert:16,unctrl:[169,170],uncustom:266,undeclar:328,undecod:[13,200,304],undecor:[60,99,368],undef:[66,72],undef_macro:[63,72],undefin:[16,29,37,43,55,56,60,63,66,72,88,92,150,200,202,222,256,277,303,333,346,368,380,416,429,432,440,446,452,460,467],undefine_macro:63,undefinit:63,under:[6,13,20,30,37,58,60,62,63,64,72,73,77,78,81,83,84,87,88,93,96,98,100,101,104,106,107,108,111,113,118,119,123,132,141,143,148,150,168,169,174,180,182,186,192,196,206,207,219,225,230,235,244,256,260,265,266,267,273,290,293,303,304,309,317,322,355,360,364,366,368,374,381,386,392,394,396,399,400,401,403,405,407,409,414,419,434,435,438,440,441,447,454,465,469,470,471,472,473,474,475,476,477],underdevelop:380,underestim:[471,472,473,474,475,476],underflow:178,undergo:476,underli:[16,21,28,47,60,72,78,81,83,87,88,90,94,96,98,99,101,106,113,120,138,146,150,152,167,168,169,180,197,205,206,207,222,241,252,255,256,258,265,266,267,273,277,287,292,293,304,305,306,309,311,318,320,322,328,332,334,336,345,350,353,355,360,361,365,366,368,369,374,386,388,391,392,403,413,418,422,423,426,434,440,461,462,470,472,473,474,475,476,477],underlin:[93,169,401],underneath:63,underscor:[63,67,88,90,133,135,143,150,152,157,168,200,270,273,331,333,351,365,396,423,435,440,441,442,445,446,447,451,458,461,463,476],underspecifi:304,understand:[20,37,60,77,79,87,90,94,98,100,101,102,104,105,106,119,120,123,127,147,162,174,184,186,202,230,241,260,270,277,308,321,322,333,369,380,401,405,423,432,435,439,445,447,451,455,457,470,471,472,473,475,476,477],understood:[30,72,76,102,143,162,167,266,276,304,309,351,393,414,438,440,451],undertaken:454,underw:[473,474,475,476],undesir:[440,471,475],undetect:[77,273,391],undetermin:256,undistinguish:473,undo:[21,28,169,244,265,283,403,458,476],undobuff:403,undobufferentri:403,undobuffers:403,undoc:208,undoc_head:148,undocu:[60,89,119,148,155,251,252,268,276,309,409],undon:[213,244,368,403],undot:79,unduli:455,uneasi:81,unencod:[13,150,192,331,473],unencrypt:365,unequ:[90,178,258,368,407,440,442,474,475],unescap:[90,101,224,333,433,446],uneven:[258,460],unexcit:94,unexpand:425,unexpect:[24,82,83,95,98,152,186,221,265,277,299,358,365,407,409,416,439,446,454,477],unexpectedexcept:186,unexpectedli:[108,336,358,407,416,451,472],unexpectedsuccess:407,unfamiliar:[90,228,265,303,425,475,476],unfil:[79,442],unfinish:[162,293,330],unformat:99,unfortun:[26,81,87,93,95,96,99,100,101,102,105,106,119,143,150,168,293,311,318,322,350,360,365,377,384,396,455,463,471,474,476],unfreez:212,unfreeze_form:212,unfreeze_object:212,ungainli:473,ungetch:[169,291],ungetmous:169,ungettext:230,ungetwch:291,unglow:403,unhandl:[30,58,95,143,149,160,186,228,244,380,390,391,410,440,451,454],unhash:[48,81,407,440,442],unhelp:470,unhexlifi:135,unic:[77,306,324,468],unichr:[104,222,240,406,440,461,470,472,475],unicod:[4,15,21,27,34,43,50,55,57,60,72,81,82,83,88,90,97,99,100,101,109,113,115,122,124,125,140,158,167,168,169,173,174,178,186,191,194,198,200,201,203,206,210,218,222,224,230,237,239,240,252,256,260,276,291,304,305,311,314,316,328,333,351,355,364,369,370,371,372,380,388,392,404,407,413,416,426,427,429,431,432,434,435,440,442,446,447,451,453,456,461,465,471,475,476,477,478],unicode_char:291,unicode_csv_data:167,unicode_csv_read:167,unicode_escap:[99,150],unicode_intern:150,unicode_liter:[99,111,447,465,476],unicode_nam:104,unicodedata:[60,104,252,372,442,470,475,476,477],unicodedecodeerror:[13,20,56,104,150,206,461,475],unicodeencodeerror:[13,20,104,150,206,460,461],unicodeerror:[4,20,150,174,198,206,368,370,427,461,473],unicoderead:167,unicodestr:124,unicodetranslateerror:[13,20,150,206,461],unicodetyp:[56,404],unicodewarn:[20,56,206,416,461,475],unicodewrit:167,unidata_vers:406,unidirect:[256,293],unif:[60,106,474],unifi:[60,79,103,150,180,186,406,440,451,478],unified_diff:180,uniform:[79,87,105,332,411,415,434,461],uniformli:[180,253,332],uniforum:230,unihan:477,unilater:221,unimpl:[162,230],unimplementedfilemod:241,uniniti:[30,50,77,88,141],uninstal:[64,86,204,251,290,467],unintend:[77,88,178,293],unintention:461,uninterest:79,uninterpret:[142,299],union:[60,120,152,339,346,366,368,371,440,453,473,474,476,477],union_upd:[346,473],uniprocessor:315,uniq:[258,474],uniqu:[28,60,62,77,79,83,87,94,100,106,121,123,152,168,173,174,180,203,205,222,228,236,252,253,258,260,273,280,290,293,304,318,328,332,347,364,365,368,375,381,386,391,396,401,408,411,415,438,439,440,451,453,465,469,474,475,477],unique_everseen:258,unique_justseen:258,unique_word:451,uniquekei:258,unistr:[406,470],unit:[4,60,70,77,83,90,96,98,170,174,179,186,216,252,322,343,365,368,369,392,396,401,403,423,438,440,441,446,471,476],unittest2:[407,477],unittest:[60,81,87,109,179,252,388,462,473],univers:[60,63,66,83,90,139,174,222,245,246,256,315,368,374,384,392,396,407,409,415,435,438,447,451,458,467,474,475,476,478],universal_newlin:[374,474],universalsdk:475,unix:[16,20,28,30,52,58,60,64,66,69,70,72,73,75,77,78,83,84,90,93,96,98,102,104,106,120,121,127,135,138,140,144,152,158,162,168,169,175,176,185,188,196,197,200,207,211,222,226,228,229,230,233,244,252,254,256,258,267,269,273,274,287,293,296,298,299,303,304,305,306,307,313,317,318,319,320,323,324,327,336,339,340,345,350,351,353,356,358,360,361,362,363,364,365,366,368,374,380,384,386,387,388,392,393,394,396,402,405,409,419,435,446,447,449,450,457,458,459,462,464,465,466,467,469,470,471,472,473,474,475,476,477],unixccompil:69,unixdatagramserv:361,unixfrom:[197,200,339],unixmailbox:273,unixpwd:167,unixstreamserv:361,unixwar:471,unknow:[471,472],unknown:[26,28,56,101,117,125,129,186,222,245,281,303,304,316,333,348,359,366,368,392,401,409,410,432,452,472,473,477],unknown_charref:348,unknown_decl:240,unknown_endtag:348,unknown_entityref:348,unknown_open:410,unknown_starttag:348,unknown_tag:348,unknownhandl:[60,105,254],unknownprotocol:241,unknowntransferencod:241,unladen:463,unless:[6,11,26,30,37,47,49,50,52,55,63,77,79,81,87,88,89,91,94,96,98,100,101,102,106,107,109,114,115,118,125,128,129,135,136,140,156,158,161,162,174,178,181,182,185,186,193,200,201,203,208,222,224,230,244,253,256,258,260,265,266,273,277,290,292,293,294,303,305,309,320,328,333,339,356,357,358,364,365,368,369,374,380,384,385,389,392,407,409,410,416,422,423,431,438,439,440,441,442,446,447,449,451,452,461,470,471,472,473,474,475,476,477],unlik:[4,28,33,36,48,70,72,79,81,87,88,94,96,98,99,104,106,113,114,126,128,137,142,156,162,167,169,174,178,186,188,194,215,222,228,230,232,236,240,246,256,258,260,273,277,287,302,305,306,309,315,318,342,360,368,369,370,374,378,380,386,388,392,407,423,429,436,438,440,442,445,446,447,451,453,460,462,465,469,471,472,473,475,476,477],unlimit:[334,336,368,374,391,440,446],unlink:[87,206,293,304,345,386,388,401,426,427],unlist:440,unload:[28,338],unlock:[130,142,207,273,291,293,294,318,320,390,391,440,475],unlocked_count:21,unlucki:474,unmaintain:106,unmanag:401,unmap:[56,368,401],unmarsh:276,unmarshal:[36,276,434,473,475],unmatch:[81,258,333,369],unmimifi:283,unmodifi:[4,62,83,142,203,321,339,390,391,411,433],unnam:[77,90,113,168,403,442],unnatur:83,unnecessari:[77,83,88,98,106,123,137,217,273,293,380,411,426,447,471,472,474,477],unnecessarili:152,unneed:[79,427,477],unnorm:20,unnot:[384,477],unobtain:304,unoffici:434,unord:[60,152,173,252,293,368,440,453],unorder:91,unown:293,unpack:[60,64,70,77,79,87,96,99,107,109,115,116,117,124,152,160,182,193,207,209,222,316,369,373,447,453,456,462,463,470,474,475,476],unpack_arrai:424,unpack_byt:424,unpack_doubl:424,unpack_farrai:424,unpack_float:424,unpack_fopaqu:424,unpack_from:[222,373,475],unpack_fstr:424,unpack_item:424,unpack_list:424,unpack_opaqu:424,unpack_sequ:182,unpack_str:424,unpack_typ:424,unpackev:116,unpair:[81,260],unparenthes:442,unpars:[123,328,339,409,431],unparsedentitydecl:431,unparsedentitydeclhandl:328,unpickl:[60,79,99,174,192,265,267,293,310,312,473,476,477],unpicklingerror:311,unpredict:[88,273,304,432,465,472],unprint:195,unprocess:[239,240,348],unprocessable_ent:241,unqdevic:212,unqualifi:[81,157,206,451],unquot:[200,203,240,339,409],unquote_plu:409,unrais:20,unreach:[205,225,380,440],unread:[63,94,339,409,420],unreadlin:63,unreason:475,unrecogn:[50,56,91,228,240,430,435,446],unrecover:431,unredirect:410,unregist:[345,396],unregister_archive_format:352,unregister_dialect:167,unrel:[55,77,88,114,140,273,440],unreleas:83,unreli:[169,304],unrepresent:427,unresolv:348,unrestrict:[52,337,338],unround:178,unruli:334,unsaf:[22,79,124,133,231,313,338,439,473],unsanit:374,unsav:244,unsearch:463,unseek:339,unseen:273,unset:[52,273,304,306,386,388,476,477],unsetenv:[304,476],unshar:336,unsightli:407,unsign:[4,6,26,29,34,50,51,54,56,124,129,135,168,222,231,306,373,376,424,426,427,437,446,463,472,473,475],unsort:[81,152],unspecifi:[100,138,168,186,256,277,298,311,328,401],unsplit:194,unstabl:[109,178],unsubscrib:246,unsuccess:[28,33,249],unsuit:[332,463,471,477],unsupport:[28,91,105,113,213,230,247,256,276,293,306,316,360,365,390,391,454,469,470,474,476],unsupported_media_typ:241,unsupportedoper:256,unt:309,untabifi:244,untermin:81,untest:82,unthread:[30,238,470],until:[26,28,30,55,58,66,76,77,82,87,95,96,98,99,101,102,113,126,127,131,132,139,143,146,162,169,178,191,192,202,210,219,221,222,230,236,240,244,249,256,258,265,267,280,292,293,299,303,304,306,309,311,318,320,322,330,331,334,343,345,348,351,353,360,361,363,364,365,368,369,374,377,380,385,386,387,390,391,393,396,409,416,419,423,424,431,432,437,439,440,447,451,453,454,463,465,470,471,472,473,474,475,476,477],untoken:398,untouch:[4,56,63,304,368],untouchwin:169,untrack:79,untrain:474,untransl:256,untrust:[81,104,125,161,266,276,293,311,326,328,337,350,374,384,425,427,428,429,430,434,435,457,473,476],untyp:472,unununium:460,unus:[53,55,77,79,91,92,169,230,249,256,291,293,312,361,369,376,417,472,476],unused_data:[139,437],unusu:[77,107,174,306,322,336,442],unvarnish:58,unverifi:[162,241,410],unwant:[30,88,151,389,461],unwind:[28,79,440],unwis:[87,368,446],unwound:[79,440],unwrap:365,unwritten:[175,226],unzip:[107,222,435,436,473],upcom:343,upcomp:258,updat:[1,19,28,45,52,60,62,63,71,79,83,87,88,93,94,96,104,106,118,123,128,152,169,171,174,186,188,191,219,222,223,235,236,237,243,246,256,263,273,278,287,290,303,304,311,319,329,332,339,342,346,349,350,364,365,368,369,374,377,381,391,396,399,400,401,403,410,423,429,440,451,470,471,472,473,474,475,476],update_panel:171,update_vis:273,update_wrapp:[223,475],updatepath:[28,30,477],updatescrollbar:219,upfront:[83,476],upgrad:[60,90,105,107,108,120,204,241,472,473,477],upgrade_requir:241,upload:[62,68,105,106,143,338,471,475,477],upon:[14,16,22,28,30,36,76,77,83,90,94,98,106,117,128,148,150,151,160,161,165,167,169,178,186,219,235,241,244,246,273,309,311,338,353,365,376,380,381,399,416,417,426,438,440,450,451,453,461,471,476],upper:[56,63,88,93,96,98,101,104,110,119,125,126,135,143,147,152,157,169,180,215,246,290,293,333,339,360,361,364,365,368,369,394,403,407,440,442,446,447,473],upper_bound:442,upperbound:330,uppercas:[56,88,104,110,123,170,264,303,368,369,409,446,470,477],upperleft:168,upperout:88,upsid:106,upstream:357,upward:[84,93,95,101,169,368,403],urandom:[235,293,304,332,474,477],urdu:150,urgent:345,uri:[105,162,328,365,403,409,410,411,423,425,426,429,431,432,434],url2pathnam:409,url:[60,63,64,70,71,72,75,106,131,138,143,144,162,221,241,243,244,252,254,267,281,327,338,341,348,355,415,419,423,432,433,434,438,462,470,473,474,475,476,477],url_schem:423,url_valu:105,urlcleanup:409,urldefrag:411,urlencod:[87,105,143,241,267,409,410,411],urlerror:[60,410,476],urlich:88,urljoin:411,urllib2:[60,97,109,162,252,254,365,409,462,474,476,477],urllib:[60,87,105,109,160,221,241,252,254,267,341,410,411,470,473,475,476],urlopen:[105,160,162,409,410,462,475,476,477],urlpars:[60,143,252,254,409,476,477],urlretriev:409,urlsafe_b64decod:131,urlsafe_b64encod:131,urlsplit:[60,254,477],urlstr:411,urlunpars:411,urlunsplit:411,urn:[411,415],urtubia:474,urx:403,usabl:[30,34,42,49,55,56,79,81,83,90,100,102,106,127,132,143,150,168,169,174,197,203,222,256,266,280,281,304,305,315,339,360,365,368,369,426,440,442,451,461,472,473,474,475],usag:[4,28,60,63,66,72,76,77,79,81,83,87,88,91,96,98,99,100,101,104,109,114,120,122,127,128,131,144,146,162,167,170,174,177,179,180,189,190,193,210,216,224,228,230,236,241,246,252,254,256,265,267,274,281,283,289,293,295,303,304,309,310,318,322,332,333,338,368,369,370,374,381,386,393,394,395,396,407,408,415,419,423,426,427,437,439,440,457,460,467,472,473,474,475,476,477],use:[1,2,3,4,6,8,9,12,13,14,15,20,21,24,26,28,30,33,36,37,39,43,45,47,49,50,51,53,55,56,58,60,62,63,64,66,67,68,69,70,71,72,73,75,76,77,78,79,80,84,86,89,90,91,92,93,94,95,96,99,100,101,102,103,104,105,106,107,108,109,111,113,116,118,119,123,124,125,126,127,128,129,132,134,135,136,137,138,139,140,141,142,143,146,147,148,149,150,151,152,157,158,160,161,162,163,164,165,167,168,169,174,175,178,180,182,184,185,186,189,190,192,193,194,195,197,198,200,201,202,203,204,205,206,207,210,212,213,215,216,221,222,223,224,225,227,230,231,232,234,235,236,237,238,239,241,244,245,246,247,249,252,253,256,257,258,259,260,262,264,265,266,267,268,269,270,273,274,276,277,278,279,281,282,283,284,287,290,291,292,293,296,297,299,300,302,303,304,305,306,308,309,311,313,314,315,316,317,318,320,322,324,325,326,327,328,332,333,334,335,336,337,338,339,340,341,342,343,346,349,351,353,355,358,360,361,364,365,366,368,369,370,371,372,373,374,378,380,381,383,384,385,386,388,389,390,391,392,393,394,395,396,397,399,400,401,404,405,407,409,410,412,413,415,416,418,419,422,423,426,427,429,430,431,432,433,434,435,436,437,438,439,440,441,442,445,446,447,448,449,450,451,452,453,454,455,457,458,459,460,461,462,463,466,467,468,469,470,471,472,473,474,475,476,477],use_datetim:[434,475],use_default_color:[169,474],use_env:169,use_errno:[168,476],use_last_error:[168,476],use_pol:127,use_proxi:241,use_rawinput:148,use_stackcheck:[20,52],usec:393,usecond:17,used:[2,3,4,6,8,9,10,11,12,16,17,19,20,21,23,24,25,26,27,28,29,30,33,34,36,37,39,42,43,44,45,47,48,49,50,51,52,53,54,55,56,58,60,62,63,64,67,68,71,72,73,75,76,77,79,80,82,83,86,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,107,108,110,113,114,115,116,117,118,121,123,124,125,126,127,128,129,131,132,133,135,137,138,139,140,142,143,144,145,146,147,148,149,150,152,154,156,157,158,159,160,161,162,163,164,165,167,168,169,171,172,173,174,175,176,178,180,182,183,184,185,186,187,188,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,210,211,214,215,221,222,223,225,226,227,228,230,232,234,235,236,237,238,239,240,241,242,243,244,245,246,247,249,252,253,255,256,258,260,262,263,264,265,266,267,270,271,272,273,274,276,277,278,279,280,281,282,283,284,287,289,290,291,292,293,295,296,297,298,299,302,303,304,305,306,308,309,311,312,313,314,315,316,317,318,319,321,322,323,324,325,326,328,330,331,332,333,334,335,336,337,338,339,340,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,358,360,361,364,365,366,368,369,370,371,373,374,375,376,379,380,381,382,383,384,385,386,388,389,390,391,392,393,394,396,398,399,400,401,403,404,405,406,407,409,410,411,412,413,414,415,416,417,418,419,420,422,423,424,426,427,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,456,457,459,460,461,463,465,467,468,469,470,471,472,473,474,475,476,477],used_arg:369,used_kei:369,useforeigndtd:328,useful:[1,3,4,6,8,9,11,28,30,31,38,48,51,58,60,63,64,66,70,71,72,76,77,80,81,82,83,87,88,90,91,92,93,94,95,96,98,99,101,105,106,107,109,110,114,123,124,125,127,129,137,140,141,143,148,149,150,152,157,159,162,168,169,174,178,180,185,186,194,199,200,203,210,218,222,225,230,236,238,240,243,244,245,251,252,253,256,258,259,260,264,265,266,267,273,280,281,282,283,286,287,291,292,294,298,300,302,303,304,305,306,308,309,311,312,314,315,318,322,324,325,328,330,332,333,335,336,338,339,341,346,348,351,353,357,358,360,361,364,365,366,368,369,374,377,380,384,391,393,394,396,398,399,400,401,403,407,409,410,413,416,418,419,423,424,426,429,430,431,432,433,440,442,446,447,448,451,452,453,454,455,457,458,459,460,462,463,464,465,467,470,471,472,473,474,475,476,477],usefulli:[186,477],usefulness:[88,91,129,438],usegmt:203,useless:[155,221,427],usenet:[83,87,98],usenetrc:299,user1:266,user2:266,user32:168,user:[6,16,20,24,28,30,37,56,58,60,62,63,66,69,70,71,72,75,76,77,78,81,82,83,85,86,87,88,89,90,91,94,95,98,99,100,101,103,104,105,106,113,120,123,134,138,142,143,144,147,149,150,151,153,156,158,162,163,165,167,169,171,174,177,178,184,186,191,192,193,204,205,206,208,213,216,219,221,222,225,227,228,229,230,233,240,241,243,244,246,247,249,252,253,256,260,264,265,267,273,274,277,282,283,290,293,296,299,301,303,304,305,306,308,309,311,312,318,324,325,329,333,334,336,339,340,341,345,346,347,351,352,353,356,358,361,363,364,365,366,367,368,374,377,380,381,384,385,386,388,391,394,396,399,400,401,403,404,407,409,410,411,416,419,423,427,429,430,431,434,435,438,439,440,441,442,449,450,451,452,456,457,460,461,462,463,464,465,467,468,469,470,471,472,473,474,475,477,478],user_ag:105,user_bas:[72,107,356,477],user_cal:134,user_except:134,user_lin:134,user_return:134,user_sit:[107,356],userag:341,userbas:107,usercustom:[356,449],userdict:[60,173,188,252,350,440,471,473,476],userfil:143,userid:143,userinfo:[105,410],userland:434,userlist:[60,173,252,472],usernam:[71,99,105,143,165,229,267,304,318,339,358,410,411],userprofil:[107,305],userptr:171,userstr:[60,173,252,470],userwarn:[20,206,229,388,416,461],uses:[3,4,8,20,22,24,25,26,28,36,37,43,45,51,55,56,58,63,64,70,71,75,77,79,80,81,82,87,88,89,90,91,93,94,95,96,98,99,100,101,102,104,105,106,107,114,116,118,123,125,126,127,129,132,133,135,137,139,140,143,148,149,155,157,162,165,168,169,174,178,180,182,186,194,204,212,214,219,222,226,227,228,230,235,236,237,240,241,244,245,253,256,258,260,264,265,266,267,271,273,276,277,281,290,291,293,300,303,304,306,309,311,313,314,315,318,320,321,327,328,332,333,334,335,337,338,339,346,348,351,352,353,354,356,360,361,364,365,366,368,369,371,373,374,379,381,384,386,388,389,391,392,396,400,401,403,405,406,407,409,410,411,416,418,423,425,426,427,429,430,434,436,438,439,440,441,442,445,446,447,451,452,453,457,460,461,463,465,469,470,471,472,473,474,475,476,477],usestd3asciirul:150,usetk:396,using:[1,3,4,6,8,13,14,16,17,19,20,21,22,24,26,28,30,34,36,37,39,40,43,47,48,50,51,52,55,56,57,58,59,60,62,63,64,66,67,70,71,72,73,75,76,77,79,80,81,84,86,89,90,91,92,93,94,95,96,98,101,102,103,104,105,106,107,108,109,111,113,114,116,123,124,125,126,127,129,131,132,135,136,138,139,140,141,142,143,145,146,147,149,150,152,155,156,158,160,161,162,163,167,168,169,170,174,175,178,179,180,181,182,185,186,187,189,192,193,194,196,197,198,199,200,201,203,204,207,208,210,212,213,214,217,221,222,224,225,226,228,229,230,232,234,235,236,239,240,241,244,245,246,249,252,253,256,258,260,263,264,265,266,267,268,271,273,275,278,280,281,282,283,287,290,292,293,297,299,302,303,304,305,306,307,308,309,311,314,315,316,317,318,319,321,322,323,330,332,333,334,336,338,339,342,343,346,348,349,350,351,352,353,354,355,356,358,359,360,361,364,365,368,369,370,371,373,374,380,381,382,383,384,385,386,387,389,390,391,392,393,394,395,396,398,399,400,401,403,404,405,409,410,412,413,415,416,418,419,423,424,426,427,429,431,432,433,434,437,439,440,441,442,443,445,446,447,448,449,450,451,452,453,454,455,457,458,459,460,461,462,463,464,465,467,468,469,470,471,472,473,474,475,476,477],using_idl:403,usno:462,usr:[28,30,72,75,82,87,96,99,104,106,107,143,168,181,193,221,230,232,274,303,311,333,356,368,374,380,381,386,392,396,410,449,459,465,467,468,471,473,475],ustar:[384,476],ustar_format:384,ustimezon:174,ustr:[194,470],usual:[4,17,20,24,28,30,41,55,56,63,64,70,72,73,77,79,81,83,84,87,88,89,90,93,94,95,96,100,101,102,103,104,105,106,107,109,114,116,123,125,127,132,135,139,142,143,146,150,152,162,165,167,168,174,178,180,185,186,194,195,198,200,206,218,219,221,222,227,230,236,244,246,249,252,253,256,258,260,265,267,273,274,277,293,302,303,304,306,309,311,315,316,319,324,333,337,345,352,353,360,361,363,364,365,368,369,374,380,384,388,390,392,394,395,396,400,401,407,409,410,417,418,429,435,436,439,440,442,447,449,450,451,452,453,454,457,459,460,461,463,468,469,470,471,472,473,474,475,476,477],usub:125,utc:[60,174,203,267,339,365,392,476],utcformatt:99,utcfromtimestamp:[174,365],utcnow:174,utcoffset:174,utctimetupl:174,utf16:150,utf32:150,utf8:[125,150,328,364,427,429],utf8_decod:470,utf8_encod:470,utf8_streamread:470,utf8_streamwrit:470,utf8_vers:104,utf8recod:167,utf:[4,15,60,88,99,104,106,125,167,168,174,198,260,316,328,364,365,372,380,384,427,429,434,446,460,470,472,473,474,475,476,477],utf_16:150,utf_16_b:150,utf_16_l:150,utf_32:150,utf_32_b:150,utf_32_l:150,utf_7:150,utf_8:150,utf_8_encod:167,utf_8_sig:[60,372],util:[20,26,27,60,64,69,72,73,88,96,99,106,107,120,121,125,143,150,151,156,169,175,176,178,179,180,186,188,192,200,226,230,241,246,249,252,254,275,280,289,295,303,325,329,331,336,352,359,371,374,389,396,403,407,408,427,435,462,463,469,470,472,474,475,477],utilis:461,utim:304,utterli:186,utyp:168,uu_codec:150,uucp:267,uudecod:60,uue:280,uuencod:[60,131,135,150,252,280,295],uuid1:[415,475],uuid3:[415,475],uuid4:[415,475],uuid5:[415,475],uuid:[60,252,254,290,475],uuidcreat:290,uuidtostr:290,uuuuuu:174,uxxxx:[260,446,460],uxxxxxxxx:446,v2f:231,v3d:231,v3f:231,va_list:[4,16,50,56,474],vacuum:364,vagu:476,val:[16,19,20,63,77,82,94,95,96,137,161,200,212,221,264,368,396,410,475],valedictorian:451,valgrind:477,valid:[3,8,15,16,20,24,37,55,58,60,63,64,76,77,82,88,90,92,93,95,104,106,107,109,113,123,124,125,143,149,150,151,152,161,164,167,168,169,174,178,179,194,222,226,241,254,256,260,263,266,276,280,287,290,293,298,299,308,313,322,328,332,333,336,338,340,342,348,355,358,360,365,368,369,374,376,380,384,388,391,392,401,403,406,407,409,410,417,427,429,431,432,435,436,437,440,442,446,447,451,452,454,459,461,462,463,465,470,476,477],validator_app:423,validhandl:168,valslid:212,valu:[2,3,5,6,8,9,10,11,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,43,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,63,64,66,72,76,78,79,81,90,91,92,93,94,95,98,99,100,101,102,103,104,105,107,109,110,114,115,116,117,118,119,120,121,125,126,127,128,129,132,133,134,135,137,138,139,140,141,142,143,145,146,147,148,149,150,151,152,154,155,156,157,158,159,160,161,162,165,167,169,170,173,174,175,176,180,181,182,185,186,188,191,192,193,194,195,197,198,200,201,203,205,206,207,208,212,215,216,217,218,219,221,222,223,224,225,226,227,228,229,230,231,232,234,235,236,237,238,239,240,241,243,245,246,247,248,249,251,252,253,256,258,259,264,265,266,267,269,270,273,274,276,277,278,279,280,281,282,283,284,287,288,290,291,293,295,297,298,299,300,301,302,304,305,306,308,309,310,311,312,313,314,315,316,317,318,319,321,322,323,326,327,328,330,332,333,334,335,336,338,339,342,343,345,346,348,349,350,351,352,353,355,356,358,359,360,361,365,369,371,373,374,376,378,379,380,381,382,384,385,386,388,390,391,392,393,394,396,397,398,400,401,403,404,406,407,409,410,411,414,415,416,417,418,419,420,421,422,423,424,426,427,428,429,430,431,432,433,434,435,436,437,439,441,444,446,447,451,453,454,455,456,457,458,460,461,462,463,465,469,470,471,472,473,474,475,476,477],valuabl:[68,81,93,230,360],valuator1:212,valuator2:212,value1:[96,475],value2:[96,475],value_decod:161,value_encod:161,value_func:293,value_nam:113,valueerror:[4,6,16,20,29,34,56,63,88,95,98,104,105,123,124,137,149,150,151,152,158,162,167,168,174,186,200,204,206,217,222,225,256,260,266,276,277,287,292,293,303,304,328,330,336,343,350,353,360,365,368,369,370,374,379,380,390,391,392,406,407,411,424,426,442,454,457,461,472,473,474,475,476,477],valuelist:473,valueref:[418,475],valuesview:152,valur:477,valv:303,van:[81,83,88,90,396,436,438,470,471,472,473,475,476,477],vanderbeek:477,vanilla:470,vanish:[88,150,236,418],var_num:182,var_typ:476,vararg:[125,253],vararg_attr:303,vararg_callback:303,varargslist:443,varchar:364,varg:[4,50,56],vari:[4,6,51,63,81,83,87,96,100,101,102,104,107,129,143,150,167,174,186,253,256,264,273,288,308,318,358,361,365,366,368,369,386,388,391,392,416,445,447,465,470,471,472,474,476,477],variabl:[3,4,9,12,16,17,19,20,23,26,28,30,41,43,45,46,48,50,55,56,58,60,62,63,71,72,75,76,77,79,81,82,84,87,89,90,91,93,94,95,96,99,101,104,105,107,108,109,113,120,126,128,129,132,142,143,145,147,148,152,160,169,182,186,192,203,206,207,212,222,225,228,229,230,232,239,244,245,246,247,248,252,253,258,264,265,270,283,290,292,293,296,304,305,306,308,309,311,313,319,327,329,332,333,334,337,338,339,340,342,348,351,353,354,355,360,361,364,366,368,369,373,374,377,379,380,386,388,391,392,393,394,395,400,401,403,409,410,411,412,419,423,424,426,427,428,439,440,441,442,447,449,450,452,453,454,456,457,458,459,460,461,463,466,467,470,471,472,473,474,475,476],variable_nam:90,variant:[4,26,36,41,55,56,77,83,87,88,94,96,101,104,121,123,150,152,157,158,169,174,178,222,246,291,293,302,304,305,332,364,368,384,407,408,415,432,440,457,461,465,475,476,477],variat:[86,94,101,106,152,174,186,222,273,304,318,365,440,461,475],varieti:[30,62,77,79,81,83,96,105,108,123,157,173,178,221,230,275,303,322,374,423,474,475,476,477],variou:[6,17,20,30,37,51,55,57,60,62,63,64,68,72,77,79,82,83,88,90,93,96,100,101,102,103,104,106,107,118,123,135,141,142,143,150,152,157,162,166,168,170,178,180,186,206,208,209,215,219,230,236,241,243,252,256,259,262,266,270,275,286,290,295,301,303,304,308,310,312,315,322,328,332,337,338,339,349,351,360,361,363,365,368,369,373,377,380,391,392,396,404,406,407,409,410,414,423,425,434,438,440,442,446,447,448,450,456,461,464,465,467,468,470,471,472,473,474,475,476,477],various:89,varkw:253,varnam:[12,297,304],varnish:365,varrai:231,vartyp:168,vasiliev:474,vassalotti:477,vast:[70,350],vastli:395,vault:471,vbar:[344,397],vbarequ:397,vc6:469,vc_assembly_publickeytoken:477,vec1:258,vec2:258,vec2d:403,vec:453,vector1:258,vector2:258,vector:[258,277,332,374,393,403,425],vein:407,ven:99,vendor:[64,93,315,450],ventur:438,ver:107,ver_nt_domain_control:380,ver_nt_serv:380,ver_nt_workst:380,ver_platform_win32:380,ver_platform_win32_c:380,ver_platform_win32_nt:380,ver_platform_win32_window:380,verb:[96,102,116,270,304,451,452],verbatim:[186,206,425,438],verbos:[60,63,91,98,99,107,123,152,157,169,186,204,227,228,266,303,313,333,338,351,352,380,383,384,388,393,407,412,434,472,473,474,476,477],verdon:476,verhulst:403,veri:[1,6,10,27,28,30,52,55,60,66,69,72,77,78,79,81,82,83,87,88,89,90,91,93,95,96,98,99,101,102,103,104,105,106,107,124,127,141,143,150,169,174,178,180,186,201,202,222,230,236,239,241,245,251,252,253,256,264,273,293,300,303,311,322,338,348,350,354,358,360,361,368,371,374,385,392,393,394,395,401,405,407,412,413,438,440,442,446,447,450,452,453,455,457,459,460,467,469,470,471,472,473,474,475,477],verif:[60,237,365],verifi:[60,63,79,88,89,96,100,162,179,186,225,257,267,358,364,388,407,416,423,476,477],verify_crl_check_chain:365,verify_crl_check_leaf:365,verify_default:365,verify_flag:365,verify_mod:365,verify_request:361,verify_x509_strict:365,verify_x509_trusted_first:365,verisign:365,versa:[64,76,87,106,168,191,333,368,369,384,399,401,460,476],versatil:[90,222,451,460,463],version2:475,version:[1,3,4,5,6,7,8,12,14,16,17,18,19,20,21,22,24,26,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,45,47,48,49,50,51,53,54,55,56,59,60,62,64,67,68,70,71,72,73,75,77,78,79,80,81,82,87,88,89,90,91,92,93,94,95,96,98,99,101,102,103,104,105,106,109,113,114,118,119,120,123,124,125,127,128,129,132,133,134,135,137,138,139,140,141,142,143,145,147,148,150,151,152,155,156,157,158,159,160,161,162,163,167,168,169,170,174,175,178,180,181,182,184,185,186,187,188,191,192,193,194,196,197,198,200,201,202,203,204,206,207,210,212,213,214,217,218,221,222,223,224,225,226,228,229,230,231,232,233,234,235,236,237,238,239,240,241,243,244,245,246,247,248,249,250,251,252,253,255,256,257,258,259,260,263,264,265,266,267,268,269,271,273,276,277,278,279,280,281,282,283,285,287,288,290,291,292,293,294,296,297,298,299,300,302,304,305,306,308,309,311,312,313,314,315,316,317,318,319,320,321,322,324,325,327,328,329,330,332,333,334,335,336,338,339,342,343,345,346,347,348,349,350,351,352,353,354,355,356,358,360,361,363,364,367,368,369,371,372,373,374,375,376,377,378,380,381,384,385,386,387,388,389,390,391,392,393,394,396,397,398,399,400,401,403,404,405,406,407,409,410,411,412,413,415,417,418,419,422,423,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,446,447,453,455,458,459,461,463,464,465,466,467,469,470,471,472,473,474,475,476,477,478],version_info:[83,100,111,364,380,440,461,470,477],version_str:132,versioninfo:315,versu:[60,81,174,186],vertch:169,vertex:403,vertic:[169,170,215,219,245,309,344,369,389,394,396,401,403,445,446],very_long_list_of_fil:81,vestigi:471,vewwi:303,vex:[99,471],vformat:369,via:[1,6,37,55,56,60,63,71,77,79,83,84,87,88,90,91,96,98,105,106,109,111,113,114,123,126,128,134,143,150,174,180,186,191,193,197,198,200,201,202,206,208,210,215,228,233,236,239,241,244,249,253,264,265,266,267,269,287,293,294,303,304,308,314,322,328,331,333,334,338,340,357,358,360,361,364,365,368,369,386,388,390,403,405,407,409,410,413,423,426,434,440,442,447,451,453,454,464,467,469,470,475,476,477],vice:[64,76,87,106,168,191,333,368,369,384,399,401,460,476],victim:266,victor:477,video:[93,169,245,274,405,476],videoread:[60,476],vienna:161,vietnames:150,view:[6,14,19,60,69,87,88,90,93,107,113,123,150,152,174,178,200,222,236,239,244,270,274,292,304,307,311,322,327,364,366,374,380,394,396,401,403,421,426,438,457,469,470,475,476,478],viewabl:401,viewer:[93,244,267,270,403],viewitem:[90,109,350,368,413,477],viewkei:[90,109,350,368,413,477],viewvalu:[90,109,350,368,413,477],vike:374,villag:463,vim:[446,467],vinai:[98,99,473,474,476,477],vinay_sajip:[98,99],vincent:365,violat:[15,20,55,168,174,207,318,417,451],violet:403,virginia:[396,438],virtu:[225,395],virtual:[30,60,62,77,88,90,108,114,168,169,171,204,222,253,364,365,380,384,395,423,440,451,470,476],virtualenv:108,viru:89,visibl:[3,30,60,77,88,90,93,96,99,102,169,171,180,191,192,200,212,219,244,258,273,314,364,370,386,395,401,410,416,441,462,471,474,475],visit:[24,55,79,92,96,125,157,174,197,225,304,305,327,352,366,431,470,472,473,476],visit_:[81,125],visit_a:81,visit_nam:125,visitfil:366,visitnodetyp:157,visitor:[24,60,125,252],visitproc:[24,55,79,92],visitwhil:157,vista:[69,401],visual:[52,63,64,72,80,81,88,93,100,107,333,365,394,452,469,470,473,476],vita:475,vixen:99,vladimir:[470,471,473],vline:169,vm_name:315,vm_releas:315,vm_vendor:315,vmin:387,vminfo:315,vmlinuz:181,vmserror:[20,206],vnarrai:231,voc:[81,359],vocod:461,voic:[99,472],voidcmd:221,voidspac:[105,477],vol:332,volatil:180,volt:[77,452],voltag:[77,222,452],volum:[81,83,152,258,306,374,377,435,474],volumin:311,volunt:[0,1,64,438,445,476],voluntari:336,voluntarili:260,von:[104,230,332,440,470,472,473,474,475,476,477],vonmisesvari:332,voom:[77,452],vooooom:452,vote:[470,475],voter:475,vpa:169,vret:79,vrfy:358,vs7:469,vs8:469,vsapi:401,vsnprintf:[16,472],vsprintf:472,vt100:[93,169],vt_ptr:168,vtabl:477,vtbl_index:168,vtime:387,vulgar:368,vulner:[60,104,186,237,252,275,304,328,338,364,374,427,428,429,430,434,437,475],vvv:[91,123,409],vvvv:91,w3c:[105,240,241,410,426,427,431,440,471],w3m:419,w3school:364,w_ok:304,wabbit:303,waddstr:93,wafer:161,wai:[4,6,16,20,21,26,28,30,36,37,43,48,50,51,55,58,60,62,63,64,66,67,68,70,72,73,75,76,77,79,81,82,83,86,87,88,89,90,91,92,93,94,95,96,98,99,100,101,102,105,106,107,108,111,123,124,126,127,128,129,133,134,139,142,143,147,149,150,151,152,156,162,163,164,165,168,169,174,178,180,186,192,194,197,200,202,211,212,219,221,222,228,230,235,236,238,245,246,255,258,264,265,266,269,273,276,277,287,289,293,296,302,303,304,306,308,309,311,317,320,321,322,332,333,337,339,349,350,351,353,356,358,360,361,364,365,368,370,373,374,380,383,384,388,391,393,394,396,400,403,404,406,407,409,410,411,412,413,416,418,419,426,429,431,434,437,438,439,440,442,445,446,447,449,450,451,452,453,454,455,457,459,460,461,462,463,465,467,469,470,471,472,473,474,475,476,477],wait3:[304,475],wait4:[304,475],wait:[60,68,77,82,87,88,89,93,99,102,104,105,116,155,169,189,190,202,206,219,252,291,293,294,304,306,317,320,330,343,353,358,360,361,362,364,365,366,374,377,387,390,391,407,409,419,452,460,463,473,474,475,476,477],waitabl:345,waiter:391,waitflag:390,waitpid:[87,304,475],wake:[244,391,476],wakeup:353,waldman:470,walk:[60,63,123,125,193,197,199,200,202,252,272,303,304,305,374,424,472,476],walk_packag:314,walker:477,walktre:366,wall:[75,76,174,322,392,393,476],walli:403,walter:[473,474,475,476],walwai:473,walzer:477,want:[0,6,10,27,28,30,43,49,55,60,63,64,66,67,68,70,71,72,73,75,76,77,79,80,81,83,84,86,87,89,91,92,93,94,95,96,98,99,100,101,102,104,105,106,107,110,114,117,123,125,129,132,134,135,139,143,145,148,149,151,157,158,162,168,169,172,174,180,184,186,191,193,197,198,200,207,210,212,219,222,224,228,230,235,243,244,246,264,265,266,267,273,274,275,277,281,284,287,292,293,300,303,304,305,309,311,314,322,332,333,338,345,358,360,361,364,365,368,369,374,380,389,391,393,396,400,401,403,407,409,410,411,415,416,423,429,435,438,440,441,449,450,451,452,453,454,457,460,461,463,465,467,468,469,470,471,472,473,474,475,476,477],want_sigfpe_handl:206,wanti:219,wantobject:473,wantx:219,ward:[66,69,72,107,470,472,473,474,475],ware:477,wari:[79,455],warn:[27,29,45,60,63,71,72,81,87,88,95,98,99,100,102,104,109,120,160,161,179,206,229,252,266,267,276,293,311,322,329,333,363,364,374,380,384,388,396,407,412,414,423,430,431,432,440,441,446,447,452,461,462,463,465,469,470,472,473,474,475,476,478],warn_explicit:[20,416],warnal:465,warner:476,warningcategori:388,warningrecord:388,warningsrecord:388,warnopt:[52,380,416,461],warnpy3k:416,warrant:[161,222,416],warranti:438,warsaw:[230,470,471,472,474,475,476],wart:[79,470],washington:[96,246],wasn:[26,63,79,81,83,106,123,222,245,303,321,407,436,454,470,472,473,475,476],wassuccess:407,wast:[81,99,104,440],watch:[52,95,98,100,127,178,212,219,236,267,345,396,462],watchedfilehandl:[60,98,120,476],watchexp:178,water:345,wav:[60,129,252,286,359,422,461],wave:[60,146,252,286,376,470],wave_read:[60,286],wave_writ:[60,286],waveform:422,wavread:461,wavwrit:461,wbit:437,wchar:56,wchar_t:[15,60,168],wconio:[60,466],wcontinu:304,wcoredump:304,wdefault:477,weak:[4,15,42,55,60,77,88,173,206,219,223,235,252,365,368,395,407,440,441,456,472,475,477,478],weaker:[95,471],weakkeydictionari:[418,475],weakli:[55,59,79,418],weaklink:473,weakref:[20,55,60,79,88,173,206,252,293,463,471,472,474,475,477],weakref_ref:4,weakset:[418,477],weakvaluedictionari:[418,463,475],weapon:453,weav:82,web:[1,60,62,71,72,87,88,89,96,97,99,100,102,104,105,107,126,132,143,144,161,187,215,244,252,254,255,267,274,327,337,338,341,354,364,365,409,423,426,438,456,463,464,470,471,472,473,474,475,476],web_python:87,webbrows:[60,252,254,470,475],webdav:241,weber:473,webp:396,webprogram:87,webserv:[106,365],websit:[60,72,105,121,138,445,467],wed:174,wednesdai:[140,174],weed:73,week:[140,174,264,392,470],weekdai:[140,174,267,392],weekhead:140,weibul:332,weibullvari:332,weight:[168,369,390,407],weighta:129,weightb:129,weikart:475,weird:123,weird_json:260,welbourn:472,welch:396,welcom:[0,1,76,127,221,293,299,338,403,438,459,475],well:[1,30,43,45,49,55,56,62,63,70,71,72,77,79,80,81,82,83,84,87,88,89,90,91,96,98,99,100,101,102,104,105,106,107,108,120,129,131,134,135,143,145,149,150,152,158,162,168,169,178,186,193,194,206,207,210,215,221,222,225,228,230,235,238,240,249,252,255,256,258,261,265,266,273,276,281,282,283,288,299,300,302,303,304,311,321,333,335,342,348,352,358,362,364,365,369,370,380,384,387,388,389,390,393,394,396,398,400,401,403,407,409,411,418,425,426,429,430,432,434,440,442,443,450,451,452,453,454,456,460,461,463,468,469,470,471,472,473,474,475,476,477],welter:473,wena:91,went:[77,91,104,134,206,306,358,360,377,407,409,470,472,475,476],were:[1,15,16,21,28,30,48,55,58,63,73,77,79,81,86,91,92,94,95,96,98,101,102,104,106,107,109,111,123,124,125,128,131,134,143,148,150,152,158,168,169,174,178,180,186,192,196,197,200,202,206,208,221,222,228,230,235,236,240,260,265,266,267,276,277,281,287,293,296,300,304,306,308,311,320,321,322,328,330,332,333,338,339,346,348,350,355,358,364,368,369,374,380,384,391,396,399,401,403,405,407,410,411,413,416,423,427,439,440,442,445,446,447,451,455,458,460,461,470,471,472,473,474,475,476,477],weren:[96,101,104,471,472,473,474,475,477],werneck:476,werror:100,weslei:396,west:[150,174,392,401,403],western:[104,150,392,446,460],wether:365,wexitstatu:304,wfile:[132,361],wg14:380,what:[1,4,6,20,25,28,30,36,50,51,55,56,60,62,63,64,66,68,70,72,73,76,79,81,89,90,91,95,96,99,100,101,102,104,105,106,107,109,119,120,123,125,127,132,139,143,147,157,158,161,162,167,168,169,174,177,178,179,202,206,207,212,219,221,222,227,230,235,236,244,246,248,249,250,264,265,266,267,270,271,274,288,300,304,306,310,328,332,333,334,345,348,352,359,360,361,364,365,368,369,371,373,374,377,380,387,388,392,394,396,399,401,403,411,412,416,426,427,429,437,439,440,441,442,445,446,447,451,452,453,454,455,456,460,461,467],whatev:[4,26,63,68,72,73,77,81,86,87,88,95,98,99,101,102,104,107,123,143,152,158,168,174,194,197,256,265,266,303,304,309,333,357,368,385,391,409,423,442,454,461,470,471,472,473,474,477],whathdr:359,whats_on_the_telli:439,whatsnew:475,whatsoev:[303,343,438],whatsound:470,wheel:[62,72,108,180,221,244],when:[2,4,6,8,9,10,11,13,14,16,20,21,26,28,29,30,31,32,33,36,37,38,41,43,44,45,47,50,51,52,55,56,58,59,60,62,63,64,68,71,72,73,75,76,77,79,80,83,84,87,89,90,91,92,93,94,96,99,100,101,103,104,105,106,107,108,109,111,113,116,118,119,121,123,124,125,126,127,128,129,130,131,132,133,134,136,139,141,142,143,144,145,146,147,148,149,150,152,157,158,159,160,161,162,164,165,167,168,169,170,174,176,178,180,182,185,186,187,188,189,190,191,192,194,195,196,197,198,200,201,202,203,204,206,207,210,212,213,215,216,217,219,221,222,223,225,226,227,228,229,230,234,235,236,237,239,240,241,244,246,248,249,251,253,255,256,258,260,261,264,265,266,267,268,269,273,277,281,282,283,284,287,290,292,293,294,296,297,298,299,302,303,304,305,306,308,309,311,313,314,315,317,318,319,320,322,325,327,328,330,331,332,333,335,336,337,338,339,340,341,342,344,345,346,348,350,351,352,353,354,355,358,359,360,361,364,365,366,368,369,370,371,373,374,376,380,381,382,384,385,386,387,388,390,391,392,393,394,396,398,399,400,401,402,403,405,407,409,410,411,412,413,414,415,416,417,418,419,420,423,425,426,427,429,430,431,432,433,434,435,436,437,439,440,441,442,445,446,447,448,449,451,452,453,454,455,457,458,459,460,461,462,463,465,467,469,470,471,472,473,474,475,476,477],whenc:[139,146,207,256,287,292,320,368,472],whenev:[20,45,56,58,77,79,81,88,94,95,98,104,107,123,139,169,178,202,216,219,222,225,253,265,267,273,293,303,328,330,337,338,345,380,396,401,403,426,429,440,451,458,461,472,473,475,476,477],where:[4,6,20,21,28,30,33,35,36,41,43,47,51,52,55,56,58,63,66,67,70,72,73,77,79,80,81,82,86,88,89,90,91,93,94,95,96,98,99,101,102,103,104,105,106,107,109,111,116,117,123,125,127,129,132,140,142,143,145,146,147,150,152,156,157,160,162,167,168,169,174,178,180,182,186,189,190,191,196,198,200,204,206,215,216,218,219,221,222,223,227,230,236,240,241,243,244,246,247,249,251,253,256,258,260,263,264,265,266,270,273,276,277,281,282,287,290,291,293,294,299,300,302,303,304,305,306,307,308,311,313,314,315,319,320,322,324,328,331,333,338,339,346,348,351,352,354,358,360,361,364,365,368,369,374,377,380,385,387,388,391,392,393,396,398,399,400,401,403,407,409,410,416,418,423,426,427,429,431,432,434,435,436,437,438,439,440,441,442,445,446,447,449,451,452,453,454,455,459,460,461,463,464,465,470,471,472,473,474,475,476,477],wherea:[77,88,89,99,192,240,260,265,293,308,333,410,452],wherebi:[129,143,266,311,442],wherei:106,wherev:[77,82,93,101,104,124,152,169,364,396,414,452,472,475],whet:[60,456,472],whether:[1,6,8,13,20,29,30,51,55,56,62,63,64,66,77,79,81,82,88,89,93,94,95,96,98,100,101,102,104,106,107,113,114,116,119,123,127,131,134,143,145,148,149,150,151,152,153,157,158,161,162,168,169,174,178,182,186,200,202,204,214,215,222,230,234,238,243,247,249,251,253,256,264,266,269,273,274,281,293,294,303,304,305,306,308,309,311,314,317,321,322,324,328,330,331,333,337,339,341,345,346,355,356,358,361,365,368,371,373,374,380,383,386,388,390,391,392,396,399,401,407,409,410,411,416,418,423,426,431,435,437,438,440,441,442,447,451,452,453,454,459,461,465,472,473,474,475,476,477],which:[0,1,2,3,4,6,9,10,13,14,15,16,19,20,22,24,26,27,28,29,30,31,34,37,38,39,42,43,45,46,47,49,51,52,53,54,55,56,58,59,60,63,64,66,67,68,70,71,72,73,75,76,77,79,80,81,82,83,84,87,88,89,90,91,92,93,94,95,96,98,99,101,102,103,104,105,106,107,108,109,110,111,112,113,116,117,118,119,123,124,125,126,127,128,129,131,132,133,134,135,136,137,138,139,140,142,143,146,147,148,149,150,151,152,155,156,157,158,159,160,161,162,163,164,165,167,168,169,170,171,173,174,175,178,179,180,181,182,184,185,188,191,192,193,194,196,197,198,200,201,202,203,205,206,207,208,210,212,214,215,218,219,221,222,223,225,227,228,229,230,232,234,235,236,239,240,241,243,244,245,246,247,249,250,251,252,253,254,255,256,258,260,264,265,266,267,270,271,273,274,277,278,279,280,281,282,284,287,288,290,291,292,293,295,296,297,299,300,302,303,304,305,306,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,330,331,332,333,334,335,336,338,339,341,343,344,345,346,348,349,350,351,352,353,354,355,356,357,358,359,360,361,364,365,367,368,369,370,371,373,374,376,377,378,380,382,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,403,404,405,406,407,409,410,411,412,413,415,416,417,418,419,422,423,424,426,427,429,430,432,433,434,435,436,437,438,439,440,441,442,445,446,447,449,450,451,452,453,454,455,457,458,459,460,461,462,463,464,465,467,468,469,470,471,472,473,474,475,476,477],whichdb:[60,121,175,176,188,226,252,310],whichev:[55,77,79,107,174,317,373,407],whichsid:401,whielacronx:438,while_stmt:[157,439,443],whit:473,whitacr:104,white:[81,93,101,169,170,231,244,245,374,401,403,438,445,463],whitebox:388,whitelist:162,whitespac:[16,56,60,63,66,72,88,89,96,101,109,123,132,135,148,152,158,167,170,178,180,186,197,198,215,218,222,239,240,244,253,260,292,296,309,328,331,333,339,348,351,368,369,373,374,383,389,392,400,426,431,447,448,452,460,465,470,473,476,477],whitespace_split:351,whittl:303,who:[1,8,11,27,64,71,72,77,81,83,86,87,95,98,99,103,104,106,107,128,156,228,230,246,265,276,304,312,336,364,365,369,373,384,403,412,427,436,438,443,457,470,472,473,474,475,477],whoami:368,whoever:[81,459],whole:[16,37,63,67,69,78,82,83,86,89,101,102,106,129,150,169,174,192,202,219,241,243,258,264,265,287,303,304,318,333,345,364,368,389,394,407,426,429,437,439,450,460,468,470,477],wholli:369,whom:438,whoop:77,whose:[2,4,20,22,26,28,30,55,63,77,81,88,89,90,91,94,99,113,123,124,125,126,127,152,161,162,167,168,169,174,178,186,195,207,208,212,222,228,233,236,241,249,253,256,265,266,267,273,276,293,300,303,304,311,322,324,333,336,338,352,356,360,363,368,369,386,388,391,396,399,400,401,407,409,410,416,429,431,438,440,442,447,451,453,455,470,471,472,474,475,476,477],whrandom:475,whseed:332,why:[1,30,60,77,85,93,95,96,98,100,106,107,114,143,157,161,168,182,186,197,258,273,277,293,303,308,311,352,364,407,423,440,451,454,455,472,475,477],why_:182,wichmann:332,wichmannhil:332,wid:219,wide:[2,27,30,60,62,63,78,81,83,88,93,96,98,104,106,107,108,123,124,129,140,158,162,168,169,174,178,186,215,219,244,252,255,264,273,291,306,318,329,350,365,369,372,374,384,394,409,412,426,438,457,472,475,476,477],widen:368,wider:[69,104,106,276,474],widespread:[100,198,445,471],widget:[60,84,93,107,120,244,252,303,307,395,403,407,470,473,474],widgetresizetestcas:407,widgettestcas:407,widgettestsuit:407,widgit:365,width:[63,88,93,101,118,119,123,129,140,150,152,168,169,212,213,219,239,244,245,259,290,303,321,368,369,376,389,392,396,401,403,406,417,457,460,463,470,473,475,476,477],widthxheight:396,wieczorek:477,wifcontinu:304,wifexit:304,wifsign:304,wifstop:304,wiki:[83,87,88,96,104,106,152,235,307,364,365,467,474,475,477],wikipedia:[96,104,106,152,235,273,403,475],wild:[441,447],wildcard:[60,214,232,284,299,374,454,456],wildfir:102,wildli:470,wildmat:299,willing:[91,303,338,365,455],wilson:[365,473,474],wimp:386,win32:[20,56,64,70,87,89,113,168,267,293,304,315,360,374,380,381,392,405,422,469,470,476],win32_ver:315,win32al:315,win32pip:315,win32servic:267,win64:[63,105,405,470],win95:[60,120],win:[19,28,60,64,93,169,171,236,268,303,381,407,469],winapi:168,winc:405,wind:[64,87,107,303],windir:113,windll:[89,168,476],window:[4,15,20,28,30,52,55,58,60,62,69,70,71,72,73,77,78,79,81,83,84,85,86,87,88,90,98,100,102,104,105,106,108,115,116,117,120,143,144,150,158,162,163,168,171,184,191,206,212,222,229,231,249,252,256,257,267,268,269,270,273,274,276,277,281,284,287,290,291,299,303,304,305,307,314,317,345,351,352,353,356,358,360,362,365,366,368,373,380,381,384,386,388,390,391,392,393,394,395,401,407,409,410,414,419,435,437,438,440,446,447,449,450,452,457,458,459,461,465,466,467,470,471,472,474,475,478],window_height:403,window_width:403,windowbound:219,windowobject:169,windowsdefault:419,windowserror:[20,113,168,206,352],windowtitl:191,wine:476,winerror:[168,206],winfo_class:401,winfunctyp:168,wing:88,wingwar:88,wininst:64,winner:[236,332],winopen:231,winreg:[113,461],winsock:[345,360],winsound:[60,80,252,421],winter:[96,222,476,477],winton:96,wintyp:168,winuserapi:168,winver:380,winzip:[89,107,435],wipe:162,wire:[93,98,150,169,265,266,371,434],wisdom:392,wise:[77,178,451,472],wish:[63,64,70,71,72,77,79,86,93,96,98,101,107,123,150,158,174,186,234,260,265,273,287,303,333,358,365,366,374,401,412,413,418,423,440,450,458,467,471,474,475,476,477,478],wit:81,witch:462,with_cleanup:182,with_cycle_gc:77,with_item:[439,443],with_stat:[111,368,439,446,447,475,476],with_stmt:[439,443],with_traceback:109,within:[4,19,28,29,37,40,45,47,60,62,63,68,77,79,88,90,92,93,99,101,102,108,115,123,149,150,158,167,168,169,174,178,180,186,191,194,210,215,219,222,225,229,230,239,244,246,251,253,255,265,270,273,293,295,305,308,309,321,322,326,327,330,333,337,338,342,348,351,360,361,364,368,369,374,379,388,396,401,403,407,410,416,426,427,429,436,439,440,441,442,446,447,451,452,453,457,458,460,461,465,470,471,472,473,474,475,476,477],without:[4,6,8,9,10,16,19,20,22,28,29,30,33,34,37,47,48,50,51,52,55,58,60,62,63,68,70,71,72,73,76,77,79,81,82,86,87,88,90,91,93,94,95,96,98,99,101,102,103,104,106,107,108,114,123,125,127,128,135,137,139,143,148,150,152,158,160,161,162,163,167,168,169,174,175,176,178,180,183,186,188,198,200,202,206,210,212,215,221,222,223,226,228,229,230,232,236,239,240,245,246,249,253,255,256,258,264,265,273,287,291,293,297,299,300,302,303,304,306,308,309,311,317,318,320,322,328,332,333,338,340,342,343,345,348,350,352,356,360,364,365,367,368,369,370,374,376,377,380,384,385,386,388,389,390,391,392,393,395,396,403,404,405,407,409,410,416,417,418,419,423,426,427,432,435,436,438,439,440,441,442,446,447,448,449,451,452,453,454,460,461,462,463,465,469,470,471,472,473,474,475,476,477],withyear:140,wizard:[99,465,472],wladmir:476,wlist:345,wmavail:269,wnohang:[87,304],woken:[293,476],wolfeboro:365,wolfson:471,won:[4,28,36,66,77,79,81,88,93,96,98,99,101,102,104,114,124,125,143,162,174,175,178,186,201,226,230,232,267,303,311,312,317,338,380,384,396,407,432,437,440,455,458,465,471,472,474,475,476,477],wonder:[0,81,88,103,106,143,167,322,364,445,470,473],wont:385,wood:123,word:[1,4,8,28,55,60,62,63,64,67,72,77,81,83,88,89,90,93,95,101,102,104,123,147,150,152,157,165,168,174,180,186,212,215,236,244,270,303,309,311,332,333,334,346,351,364,368,369,376,389,391,396,429,433,438,440,441,442,445,446,447,452,453,456,458,460,467,470,472,474,475,476],wordchar:351,work:[4,10,14,16,20,21,28,30,31,32,36,37,38,48,52,55,56,60,62,63,64,67,72,76,77,79,80,81,82,86,89,90,91,92,93,94,95,96,98,99,100,101,102,103,104,105,106,113,118,120,121,122,123,124,125,127,128,136,137,140,141,142,143,150,152,156,157,162,168,169,174,179,180,182,183,185,191,192,207,210,211,213,215,216,219,221,222,224,228,230,238,239,240,243,244,246,249,251,252,257,258,260,262,264,265,267,271,273,275,277,293,300,301,302,303,304,305,311,312,315,317,319,320,322,323,330,339,345,350,352,353,354,361,364,365,368,369,373,374,380,384,386,387,388,389,390,391,394,396,400,401,402,403,405,407,409,410,413,416,419,423,426,429,430,434,436,438,439,440,442,445,449,450,451,452,453,454,456,457,458,459,460,461,462,465,466,469,470,471,472,473,474,475,476,477],workaround:[88,186,260,339,365,368,425],workdir:64,worker:[60,63,99,106,330,362,391,475,476,477],workfil:457,workhors:470,workstat:[119,380],world:[60,62,63,64,77,82,88,93,102,106,124,135,143,168,174,215,230,255,287,292,293,303,313,324,343,360,361,365,374,386,388,389,391,395,403,407,409,410,423,426,438,446,451,453,454,457,460,464,465,469],worldwid:198,worri:[30,67,77,79,93,98,100,104,107,143,174,303,333,339,407,461,472,477],wors:[87,88,95,101,102,174,260],worst:[100,101,102,168,180,236,465,474],worth:[82,88,106,118,142,186,221,266,293,445,456,465,467,470,471,472,475],worthi:451,worthwhil:[101,311,475],would:[1,6,16,26,28,30,41,49,51,52,54,55,56,63,64,66,67,68,70,72,76,77,79,80,81,83,86,87,88,89,90,93,94,95,96,98,99,100,101,102,104,106,107,109,113,114,124,135,137,143,147,150,152,157,158,160,162,164,167,168,169,174,178,180,186,192,193,196,198,200,202,205,206,216,222,223,226,228,230,234,236,240,249,252,253,255,256,260,265,266,267,274,276,281,283,288,293,300,303,304,308,311,313,315,318,322,327,332,333,334,336,337,338,339,345,348,350,353,354,361,364,365,366,368,369,371,373,374,382,386,388,391,396,400,401,403,406,407,413,416,418,419,424,426,435,436,437,438,439,440,441,442,445,446,447,451,452,453,455,457,458,460,461,469,470,471,472,473,474,475,476,477],wouldn:[63,77,81,87,100,101,249,439,452,470,471,472,473,474,476],wound:106,wouter:[470,471,474,475,476,477],wparam:168,wrap:[6,16,18,51,60,63,81,82,94,103,109,110,113,123,127,129,148,150,167,168,169,180,186,197,198,202,214,215,223,230,232,252,256,258,260,265,266,290,293,303,304,307,314,346,364,365,372,373,380,382,396,405,407,413,423,429,432,433,439,440,452,463,469,472,473,474,475,476,477],wrap_socket:[365,476,477],wrap_text:63,wrapcolumn:180,wrapper:[16,18,20,22,26,51,52,60,69,81,89,90,93,99,103,104,106,110,127,135,155,168,169,173,186,202,207,216,223,252,257,271,276,277,289,290,293,298,308,314,316,342,345,360,368,369,388,389,395,400,416,423,426,429,434,439,440,451,467,469,470,471,472,474,475,476,477],wrapper_assign:223,wrapper_descriptor:474,wrapper_upd:223,wrapperbas:18,wrec:476,wrefresh:169,wrinkl:43,wrist:462,writabl:[6,51,55,79,87,102,123,127,143,152,246,256,287,293,304,316,339,352,368,373,386,396,440,451,474,476],write:[1,4,6,16,20,21,22,24,27,28,30,31,36,51,52,55,56,60,63,64,69,70,73,76,78,79,81,83,84,86,89,90,92,93,95,96,98,99,100,101,102,105,106,107,109,113,114,119,121,122,123,124,126,127,128,131,132,136,138,139,143,148,149,150,151,152,156,158,160,162,168,169,172,175,176,179,180,186,193,197,200,207,209,210,215,220,221,222,223,224,226,228,230,234,236,242,244,246,247,252,256,260,266,267,273,276,280,282,283,286,287,293,296,299,303,304,305,306,311,313,316,317,318,320,321,322,323,325,331,333,334,337,338,345,347,350,351,353,360,361,364,365,366,368,372,373,374,377,380,382,385,386,395,398,399,401,403,407,413,414,416,421,423,426,427,429,431,433,434,435,437,440,444,447,450,451,452,454,455,456,460,461,462,463,464,465,470,471,472,473,474,477],write_byt:287,write_docstringdict:403,write_fil:63,write_histori:334,write_history_fil:[334,458],write_lin:99,write_multiple_item:452,write_restrict:79,write_result:399,writeabl:[6,42,168,256],writeal:306,writeback:350,writebufferproc:55,writefram:[118,376,417],writeframesraw:[118,376,417],writehead:167,writelin:[139,150,180,256,368,470],writepi:435,writeplist:[316,476],writeplisttoresourc:316,writeplisttostr:[316,476],writer:[0,30,37,60,77,79,150,186,209,222,239,242,252,256,285,295,333,396,398,427,432,473],writerow:167,writesamp:[119,142],writestr:[435,477],writexml:427,written:[0,6,16,20,21,30,36,37,43,50,52,56,60,63,64,67,68,70,72,73,76,77,78,79,81,83,84,86,87,88,90,91,93,94,96,99,100,101,102,104,106,107,109,113,118,124,126,127,135,136,139,143,145,149,150,157,167,168,169,175,184,186,188,198,200,212,222,225,226,229,230,234,238,245,247,249,252,253,255,256,258,259,260,267,273,276,282,287,290,292,293,303,304,306,311,313,316,317,322,325,327,334,337,338,342,345,350,353,355,361,364,365,368,376,377,383,384,386,387,388,396,399,403,404,405,407,416,417,418,423,424,426,429,434,435,436,438,440,445,446,447,449,450,451,452,453,454,455,457,460,461,464,465,470,471,472,473,474,475,476,477],wrong:[4,15,28,37,71,72,77,87,90,95,100,101,104,105,107,123,134,168,174,186,205,206,246,303,304,306,358,360,364,373,377,392,407,440,460,461,471,473,474,475,476],wrong_document_err:426,wrongdocumenterr:426,wrongli:96,wrote:[88,96,104,361,438,470,472,474],ws_comma:109,wsaioctl:[360,476],wsgi:[60,252,254,475],wsgi_app:475,wsgi_file_wrapp:423,wsgi_multiprocess:423,wsgi_multithread:423,wsgi_run_onc:423,wsgiref:[60,106,252,254],wsgirequesthandl:423,wsgiserv:[106,423],wshowwindow:374,wstopsig:304,wstrict:[75,76],wstring_at:168,wtermsig:304,wuntrac:304,www:[71,72,82,84,88,89,95,96,102,104,105,106,107,121,124,127,138,143,150,154,160,162,174,193,239,240,241,246,259,328,341,345,348,364,365,368,380,396,406,409,410,411,419,427,429,434,437,438,440,451,456,460,464,465,467,468,469,470,471,472,473,474,475,476,477],wxpython:[84,307,467],wxpythonwindow:89,wxrwxr:221,wxwidget:[88,307],wxwindow:307,wxy:474,x00:[100,168,333,373,415],x00lo:168,x01:[373,415],x02:[373,415],x03:[373,415],x04:[415,472],x05:415,x06:415,x07:415,x08:[373,415],x08ar:260,x0b:[368,415],x0c:[368,415],x0e:415,x0f:415,x10:472,x11:[72,84,93,101,401,410,419],x11r6:72,x123456:470,x12:[373,415],x13:373,x14:373,x15:373,x1c:368,x1d:368,x1e:[235,278,368],x32:373,x34:415,x3e:240,x509:[365,409],x509_asn:365,x509_ca:365,x509v3:365,x56:[415,470],x64:[64,105,380,476],x78:415,x80:[104,472],x80abc:104,x80abcd:104,x83:[235,278],x84:476,x85:368,x86:[82,88,168,373,476],x86_64:[63,381],x87:476,x87_double_round:477,x89:476,x8d:[235,278],x94:104,x9c:[235,278,472],x9f:104,x_ok:304,x_root:396,xa1:[235,278],xa4:460,xa5:[235,278],xac:104,xaf:476,xatom:246,xb4:104,xb6:460,xbb:[99,446],xbbd:[235,278],xbc:460,xbf:[99,446],xbm:[248,394,396],xc0:472,xc1:472,xc3:[104,460],xc5benraa:316,xc9:[235,278,472],xc_:396,xc_hand2:396,xcompil:107,xcor:403,xd6sterreich:364,xd9:[235,278],xdd:[235,278],xde:[104,235,278],xdf:316,xdr:[60,124,209,252,311,373],xdrlib:[60,124,209,252,373],xdummi:403,xe0:291,xe2:476,xe3:476,xe4:[104,364,460],xe4n:264,xe4ssig:316,xe9:[104,235,278],xea:104,xef:[99,446],xenix:205,xf0:[235,278],xf6:[364,460],xf6stal:198,xfc:[364,460],xff:[235,278],xgettext:230,xgtitl:299,xhdr:299,xhh:446,xhhhh:470,xhtml1:[105,239],xhtml:[60,105,239,252,275,328,348,426,427,429],xhtml_namespac:426,xicluna:477,xkcd:364,xlib:[72,396],xlinker:[76,107],xlinux:473,xlist:345,xml11:[328,427,429],xml:[13,60,72,83,96,101,104,106,143,150,252,254,256,275,288,307,316,410,462,463,471,472,473,474,475,476,477,478],xml_cquant_non:328,xml_cquant_opt:328,xml_cquant_plu:328,xml_cquant_rep:328,xml_ctype_ani:328,xml_ctype_choic:328,xml_ctype_empti:328,xml_ctype_mix:328,xml_ctype_nam:328,xml_ctype_seq:328,xml_declar:[429,477],xml_error_abort:328,xml_error_async_ent:328,xml_error_attribute_external_entity_ref:328,xml_error_bad_char_ref:328,xml_error_binary_entity_ref:328,xml_error_cant_change_feature_once_pars:328,xml_error_duplicate_attribut:328,xml_error_entity_declared_in_p:328,xml_error_external_entity_handl:328,xml_error_feature_requires_xml_dtd:328,xml_error_finish:328,xml_error_incomplete_p:328,xml_error_incorrect_encod:328,xml_error_invalid_token:328,xml_error_junk_after_doc_el:328,xml_error_misplaced_xml_pi:328,xml_error_no_el:328,xml_error_no_memori:328,xml_error_not_standalon:328,xml_error_not_suspend:328,xml_error_param_entity_ref:328,xml_error_partial_char:328,xml_error_publicid:328,xml_error_recursive_entity_ref:328,xml_error_suspend:328,xml_error_suspend_p:328,xml_error_syntax:328,xml_error_tag_mismatch:328,xml_error_text_decl:328,xml_error_unbound_prefix:328,xml_error_unclosed_cdata_sect:328,xml_error_unclosed_token:328,xml_error_undeclaring_prefix:328,xml_error_undefined_ent:328,xml_error_unexpected_st:328,xml_error_unknown_encod:328,xml_error_xml_decl:328,xml_n:470,xml_namespac:426,xml_param_entity_parsing_alwai:328,xml_param_entity_parsing_nev:328,xml_param_entity_parsing_unless_standalon:328,xml_text:429,xmlcharrefreplac:[104,150,256,368,473],xmlcharrefreplace_error:150,xmldeclhandl:328,xmlfilterbas:433,xmlgener:433,xmlid:429,xmllib:[101,470],xmln:[328,429,477],xmlns_namespac:426,xmlpars:470,xmlparser:[60,275,477],xmlparsertyp:328,xmlproc:470,xmlproc_pars:72,xmlproc_val:72,xmlreader:[60,252,275,430,431,433],xmlrole:470,xmlrpc:[187,355,425,434,472],xmlrpclib:[60,252,254,355,365,425,438,462,472,473,474,475,476,477],xmltok:470,xmpeg:274,xnnn:240,xoff:170,xon:170,xor:[178,302,442],xor_expr:[442,443],xorig:213,xover:299,xpath:[60,275,299,425],xpm:394,xpot:230,xrang:[60,104,109,123,175,222,252,258,293,304,332,369,372,393,404,413,453,460,461,462,471,472,473,474],xrangetyp:404,xreadlin:[109,139,368,471,473,474],xscrollcommand:401,xsize:213,xsl:472,xtaddinput:84,xterm:[93,169],xvec:451,xview:401,xxmodul:77,xxx:[36,79,98,123,125,157,212,213,352,477],xxxx:446,xxxxxxxx:446,xyz:[88,123,191,266,407],xyzyx:123,xyzz:123,xyzzi:368,y2k:392,y_root:396,yahoo:[83,121,475,476],yakov:470,yamamoto:477,yaml:[98,260,266,477],yank:458,yapaxi:168,yasskin:[476,477],ycor:403,ydai:174,ydummi:403,year:[17,83,90,101,106,140,142,174,186,392,429,435,438,446,465,469,471,473,475,476,477],yeardatescalendar:140,yeardays2calendar:140,yeardayscalendar:140,yee:[470,471,472,475],yello:88,yellow:[60,93,137,152,169,252,403,408,463,474],yeltsin:364,yes:[63,84,158,169,186,191,264,265,328,333,365,368,396,423,429,438,452],yesexpr:264,yet:[2,4,12,13,24,26,28,55,63,77,79,81,82,83,84,87,88,89,91,93,95,100,101,108,111,126,139,143,157,168,169,178,186,191,200,213,222,225,236,238,255,293,306,309,317,322,323,348,356,365,368,374,391,426,437,446,447,450,451,457,458,461,470,472,473,475,477],yield:[25,50,56,60,79,81,88,90,96,106,111,114,125,134,143,152,157,160,167,174,180,182,222,232,249,253,256,258,260,273,293,304,311,314,332,333,339,351,364,368,384,409,415,423,426,429,434,439,440,443,444,446,451,455,472,473,475,476,477],yield_atom:442,yield_expr:443,yield_express:[442,447],yield_stmt:[443,447],yield_valu:182,yinyang:403,yiq:154,yiq_to_rgb:154,yorig:213,york:174,you:[0,1,3,4,6,10,12,15,19,20,21,26,28,29,30,33,36,43,45,49,50,52,55,58,59,60,62,63,64,66,67,70,71,72,73,76,77,79,80,82,83,84,86,89,90,91,92,93,96,98,99,101,102,103,104,105,106,107,108,109,113,114,115,116,117,118,119,123,125,126,127,128,129,132,135,136,138,139,140,141,142,143,145,146,147,148,150,151,152,157,158,160,161,162,167,168,169,170,171,172,174,177,178,179,180,183,186,189,192,193,194,195,197,198,200,201,202,206,207,210,212,216,218,219,221,222,224,225,226,227,229,230,231,234,235,236,238,241,242,243,244,246,247,248,251,253,255,256,258,260,263,264,265,266,267,268,270,273,274,275,276,277,278,282,287,292,293,299,300,303,304,305,306,309,311,313,317,318,319,321,322,327,328,332,333,334,338,339,345,349,350,351,352,357,358,360,361,363,364,365,366,368,369,374,377,380,384,385,386,388,389,390,391,392,393,394,395,396,399,400,401,403,407,409,410,411,412,413,415,416,417,418,419,423,424,425,426,427,428,429,430,431,433,434,435,437,438,440,442,443,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,464,466,467,468,469,470,471,472,473,474,475,476,477],young:438,youngest:225,your:[1,3,4,6,17,19,24,28,30,33,34,35,36,42,43,47,48,49,50,52,53,54,55,56,60,62,63,64,66,67,68,70,71,72,73,76,77,78,79,80,81,82,83,84,86,87,88,89,90,91,92,93,95,96,98,101,102,104,105,107,108,109,113,119,120,121,123,126,127,129,132,144,145,150,151,158,161,162,164,169,174,176,177,186,187,188,189,192,193,195,197,198,200,202,206,216,219,220,222,225,226,235,239,240,241,242,243,244,253,254,256,260,264,265,266,267,270,271,273,284,287,293,304,309,310,311,316,318,319,320,322,327,330,332,333,334,335,338,341,344,345,352,354,355,358,360,361,365,366,368,369,370,373,374,385,386,387,388,389,390,391,392,393,394,396,401,403,405,407,409,410,411,412,413,416,418,420,426,427,429,431,434,435,438,440,445,449,451,452,453,455,456,457,458,459,461,464,465,467,468,469,470,471,472,473,474,475,476,477],your_computed_bia:322,your_dict:186,your_integer_time_func:322,your_script:106,your_time_func:322,yourhostnam:143,yourmodul:60,yourmodule_funct:82,yournam:89,yourscript:303,yourself:[4,6,30,55,60,76,81,88,90,93,95,101,102,104,106,107,116,125,148,169,171,186,197,212,260,264,265,303,309,345,358,364,365,380,407,426,443,455,457,468,469,475],yourtransform:125,yscrollcommand:401,ysize:213,yuck:[102,461],yuor:333,yve:474,yvec:451,yview:401,yyi:123,yymmdd:299,yyyi:[174,246],z123fg:368,z_0:333,z_default_compress:437,z_default_strategi:437,z_filter:437,z_finish:437,z_full_flush:437,z_huffman_onli:437,z_sync_flush:437,zachari:477,zack:346,zadka:[95,470,471,472,474],zap:[182,267],zbcefg:368,zebra:99,zen:90,zephyr:99,zero:[4,6,14,16,20,24,26,28,30,33,37,45,48,55,56,70,77,79,87,88,90,98,99,101,103,104,113,123,125,129,131,135,138,140,147,150,152,168,169,174,178,180,185,186,191,197,200,204,206,215,216,222,223,225,234,236,244,245,246,247,256,258,265,267,271,273,277,287,293,294,303,304,309,328,330,332,333,334,339,345,353,360,365,366,368,369,370,373,374,380,384,387,390,391,392,401,407,426,429,435,437,440,441,442,445,446,447,452,453,454,455,457,459,460,463,465,470,473,474,475,476,477],zerodict:475,zerodivisionerror:[20,99,174,178,206,218,293,442,454,461,462,473],zesti:99,zfill:[368,369,457,473],zgf0ysb0bybizsblbmnvzgvk:131,ziegler:477,ziga:477,zinfo_or_arcnam:435,zip64:[435,475],zip:[60,63,64,70,73,88,90,96,107,109,122,135,150,152,222,224,252,258,289,352,368,369,384,425,451,453,461,463,470,474,475,476,477,478],zip_defl:[435,463],zip_stor:435,zipexhaust:258,zipextfil:435,zipfil:[60,63,64,73,122,252,263,342,352,384,416,462,463,465,470,475,476,477],zipimport:[60,252,289,473,475],zipimporterror:436,zipinfo:[60,122,476],zlib:[28,60,101,107,122,150,234,235,252,352,435,462,472,473,475],zlib_codec:150,zmod:470,zodb:[88,106,472],zombi:[293,475],zone:[93,174,392,429,438,473,475,477],zoneh:101,zoneinfo:[174,392],zonem:101,zonen:101,zoo:[403,439],zooko:438,zoom:244,zoomheight:244,zope2:106,zope:[60,83,88,438,471,472],zsolt:477,ztar:[63,64,73]},titles:["About these documents","Reporting Bugs","Abstract Objects Layer","Allocating Objects on the Heap","Parsing arguments and building values","Boolean Objects","Buffers and Memoryview Objects","Byte Array Objects","Capsules","Cell Objects","Class and Instance Objects","CObjects","Code Objects","Codec registry and support functions","Complex Number Objects","Concrete Objects Layer","String conversion and formatting","DateTime Objects","Descriptor Objects","Dictionary Objects","Exception Handling","File Objects","Floating Point Objects","Function Objects","Supporting Cyclic Garbage Collection","Generator Objects","Importing Modules","Python/C API Reference Manual","Initialization, Finalization, and Threads","Plain Integer Objects","Introduction","Iterator Protocol","Iterator Objects","List Objects","Long Integer Objects","Mapping Protocol","Data marshalling support","Memory Management","Method Objects","Module Objects","The <code class=\"docutils literal notranslate\"><span class=\"pre\">None</span></code> Object","Number Protocol","Old Buffer Protocol","Object Protocol","Object Implementation Support","Reference Counting","Reflection","Sequence Protocol","Set Objects","Slice Objects","String/Bytes Objects","Common Object Structures","Operating System Utilities","Tuple Objects","Type Objects","Type Objects","Unicode Objects and Codecs","Utilities","The Very High Level Layer","Weak Reference Objects","Python Documentation contents","Copyright","Distributing Python Modules","10. API Reference","5. Creating Built Distributions","9. Command Reference","3. Writing the Setup Configuration File","7. Examples","8. Extending Distutils","Distributing Python Modules (Legacy version)","1. An Introduction to Distutils","6. The Python Package Index (PyPI)","2. Writing the Setup Script","4. Creating a Source Distribution","Uploading Packages to the Package Index","3. Building C and C++ Extensions with distutils","5. Embedding Python in Another Application","1. Extending Python with C or C++","Extending and Embedding the Python Interpreter","2. Defining New Types","4. Building C and C++ Extensions on Windows","Design and History FAQ","Extending/Embedding FAQ","General Python FAQ","Graphic User Interface FAQ","Python Frequently Asked Questions","\u201cWhy is Python Installed on my Computer?\u201d FAQ","Library and Extension FAQ","Programming FAQ","Python on Windows FAQ","Glossary","Argparse Tutorial","Porting Extension Modules to Python 3","Curses Programming with Python","Descriptor HowTo Guide","Idioms and Anti-Idioms in Python","Functional Programming HOWTO","Python HOWTOs","Logging HOWTO","Logging Cookbook","Porting Python 2 Code to Python 3","Regular Expression HOWTO","Socket Programming HOWTO","Sorting HOW TO","Unicode HOWTO","HOWTO Fetch Internet Resources Using urllib2","HOWTO Use Python in the web","Installing Python Modules (Legacy version)","Installing Python Modules","25.4. 2to3 - Automated Python 2 to 3 code translation","28.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">__builtin__</span></code> \u2014 Built-in objects","28.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">__future__</span></code> \u2014 Future statement definitions","28.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">__main__</span></code> \u2014 Top-level script environment","35.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">_winreg</span></code> \u2014 Windows registry access","28.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">abc</span></code> \u2014 Abstract Base Classes","38.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">aepack</span></code> \u2014 Conversion between Python variables and AppleEvent data containers","38.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">aetools</span></code> \u2014 OSA client support","38.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">aetypes</span></code> \u2014 AppleEvent objects","21.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">aifc</span></code> \u2014 Read and write AIFF and AIFC files","39.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">al</span></code> \u2014 Audio functions on the SGI","15. Generic Operating System Services","11.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">anydbm</span></code> \u2014 Generic access to DBM-style databases","12. Data Compression and Archiving","15.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">argparse</span></code> \u2014 Parser for command-line options, arguments and sub-commands","8.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">array</span></code> \u2014 Efficient arrays of numeric values","32.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">ast</span></code> \u2014 Abstract Syntax Trees","17.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">asynchat</span></code> \u2014 Asynchronous socket command/response handler","17.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">asyncore</span></code> \u2014 Asynchronous socket handler","28.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">atexit</span></code> \u2014 Exit handlers","21.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">audioop</span></code> \u2014 Manipulate raw audio data","37.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">autoGIL</span></code> \u2014 Global Interpreter Lock handling in event loops","18.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">base64</span></code> \u2014 RFC 3548: Base16, Base32, Base64 Data Encodings","20.18. <code class=\"docutils literal notranslate\"><span class=\"pre\">BaseHTTPServer</span></code> \u2014 Basic HTTP server","30.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">Bastion</span></code> \u2014 Restricting access to objects","26.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">bdb</span></code> \u2014 Debugger framework","18.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">binascii</span></code> \u2014 Convert between binary and ASCII","18.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">binhex</span></code> \u2014 Encode and decode binhex4 files","8.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">bisect</span></code> \u2014 Array bisection algorithm","11.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">bsddb</span></code> \u2014 Interface to Berkeley DB library","12.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">bz2</span></code> \u2014 Compression compatible with <strong class=\"program\">bzip2</strong>","8.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">calendar</span></code> \u2014 General calendar-related functions","37.8. Mac OS Toolbox Modules","39.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">cd</span></code> \u2014 CD-ROM access on SGI systems","20.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">cgi</span></code> \u2014 Common Gateway Interface support","20.20. <code class=\"docutils literal notranslate\"><span class=\"pre\">CGIHTTPServer</span></code> \u2014 CGI-capable HTTP request handler","20.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">cgitb</span></code> \u2014 Traceback manager for CGI scripts","21.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">chunk</span></code> \u2014 Read IFF chunked data","9.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">cmath</span></code> \u2014 Mathematical functions for complex numbers","23.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">cmd</span></code> \u2014 Support for line-oriented command interpreters","29.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">code</span></code> \u2014 Interpreter base classes","7.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">codecs</span></code> \u2014 Codec registry and base classes","29.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">codeop</span></code> \u2014 Compile Python code","8.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">collections</span></code> \u2014 High-performance container datatypes","37.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">ColorPicker</span></code> \u2014 Color selection dialog","21.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">colorsys</span></code> \u2014 Conversions between color systems","36.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">commands</span></code> \u2014 Utilities for running commands","32.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">compileall</span></code> \u2014 Byte-compile Python libraries","33. Python compiler package","13.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">ConfigParser</span></code> \u2014 Configuration file parser","4. Built-in Constants","28.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">contextlib</span></code> \u2014 Utilities for <code class=\"docutils literal notranslate\"><span class=\"pre\">with</span></code>-statement contexts","20.22. <code class=\"docutils literal notranslate\"><span class=\"pre\">Cookie</span></code> \u2014 HTTP state management","20.21. <code class=\"docutils literal notranslate\"><span class=\"pre\">cookielib</span></code> \u2014 Cookie handling for HTTP clients","8.17. <code class=\"docutils literal notranslate\"><span class=\"pre\">copy</span></code> \u2014 Shallow and deep copy operations","11.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">copy_reg</span></code> \u2014 Register <code class=\"docutils literal notranslate\"><span class=\"pre\">pickle</span></code> support functions","36.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">crypt</span></code> \u2014 Function to check Unix passwords","14. Cryptographic Services","13.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">csv</span></code> \u2014 CSV File Reading and Writing","15.17. <code class=\"docutils literal notranslate\"><span class=\"pre\">ctypes</span></code> \u2014 A foreign function library for Python","15.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">curses</span></code> \u2014 Terminal handling for character-cell displays","15.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">curses.ascii</span></code> \u2014 Utilities for ASCII characters","15.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">curses.panel</span></code> \u2014 A panel stack extension for curses","29. Custom Python Interpreters","8. Data Types","8.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">datetime</span></code> \u2014 Basic date and time types","11.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">dbhash</span></code> \u2014 DBM-style interface to the BSD database library","11.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">dbm</span></code> \u2014 Simple \u201cdatabase\u201d interface","26. Debugging and Profiling","9.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">decimal</span></code> \u2014 Decimal fixed point and floating point arithmetic","25. Development Tools","7.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">difflib</span></code> \u2014 Helpers for computing deltas","10.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">dircache</span></code> \u2014 Cached directory listings","32.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">dis</span></code> \u2014 Disassembler for Python bytecode","27. Software Packaging and Distribution","27.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">distutils</span></code> \u2014 Building and installing Python modules","36.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">dl</span></code> \u2014 Call C functions in shared objects","25.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">doctest</span></code> \u2014 Test interactive Python examples","20.25. <code class=\"docutils literal notranslate\"><span class=\"pre\">DocXMLRPCServer</span></code> \u2014 Self-documenting XML-RPC server","11.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">dumbdbm</span></code> \u2014 Portable DBM implementation","16.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">dummy_thread</span></code> \u2014 Drop-in replacement for the <code class=\"docutils literal notranslate\"><span class=\"pre\">thread</span></code> module","16.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">dummy_threading</span></code> \u2014 Drop-in replacement for the <code class=\"docutils literal notranslate\"><span class=\"pre\">threading</span></code> module","37.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">EasyDialogs</span></code> \u2014 Basic Macintosh dialogs","18.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">email</span></code> \u2014 An email and MIME handling package","18.1.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">email</span></code>: Examples","18.1.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.charset</span></code>: Representing character sets","18.1.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.encoders</span></code>: Encoders","18.1.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.errors</span></code>: Exception and Defect classes","18.1.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.generator</span></code>: Generating MIME documents","18.1.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.header</span></code>: Internationalized headers","18.1.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.iterators</span></code>: Iterators","18.1.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.message</span></code>: Representing an email message","18.1.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.mime</span></code>: Creating email and MIME objects from scratch","18.1.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.parser</span></code>: Parsing email messages","18.1.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">email.utils</span></code>: Miscellaneous utilities","27.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">ensurepip</span></code> \u2014 Bootstrapping the <code class=\"docutils literal notranslate\"><span class=\"pre\">pip</span></code> installer","15.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">errno</span></code> \u2014 Standard errno system symbols","6. Built-in Exceptions","36.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">fcntl</span></code> \u2014 The <code class=\"docutils literal notranslate\"><span class=\"pre\">fcntl</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">ioctl</span></code> system calls","10.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">filecmp</span></code> \u2014 File and Directory Comparisons","13. File Formats","10.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">fileinput</span></code> \u2014 Iterate over lines from multiple input streams","10. File and Directory Access","39.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">fl</span></code> \u2014 FORMS library for graphical user interfaces","39.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">fm</span></code> \u2014 <em>Font Manager</em> interface","10.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">fnmatch</span></code> \u2014 Unix filename pattern matching","34.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">formatter</span></code> \u2014 Generic output formatting","28.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">fpectl</span></code> \u2014 Floating point exception control","7.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">fpformat</span></code> \u2014 Floating point conversions","9.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">fractions</span></code> \u2014 Rational numbers","37.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">FrameWork</span></code> \u2014 Interactive application framework","23. Program Frameworks","20.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">ftplib</span></code> \u2014 FTP protocol client","2. Built-in Functions","9.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">functools</span></code> \u2014 Higher-order functions and operations on callable objects","28.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">future_builtins</span></code> \u2014 Python 3 builtins","28.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">gc</span></code> \u2014 Garbage Collector interface","11.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">gdbm</span></code> \u2014 GNU\u2019s reinterpretation of dbm","38.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">gensuitemodule</span></code> \u2014 Generate OSA stub packages","15.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">getopt</span></code> \u2014 C-style parser for command line options","15.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">getpass</span></code> \u2014 Portable password input","22.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">gettext</span></code> \u2014 Multilingual internationalization services","39.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">gl</span></code> \u2014 <em>Graphics Library</em> interface","10.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">glob</span></code> \u2014 Unix style pathname pattern expansion","36.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">grp</span></code> \u2014 The group database","12.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">gzip</span></code> \u2014 Support for <strong class=\"program\">gzip</strong> files","14.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">hashlib</span></code> \u2014 Secure hashes and message digests","8.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">heapq</span></code> \u2014 Heap queue algorithm","14.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">hmac</span></code> \u2014 Keyed-Hashing for Message Authentication","26.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">hotshot</span></code> \u2014 High performance logging profiler","19.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">htmllib</span></code> \u2014 A parser for HTML documents","19.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">HTMLParser</span></code> \u2014 Simple HTML and XHTML parser","20.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">httplib</span></code> \u2014 HTTP protocol client","22. Internationalization","37.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">ic</span></code> \u2014 Access to the Mac OS X Internet Config","24.6. IDLE","21.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">imageop</span></code> \u2014 Manipulate raw image data","20.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">imaplib</span></code> \u2014 IMAP4 protocol client","39.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">imgfile</span></code> \u2014 Support for SGI imglib files","21.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">imghdr</span></code> \u2014 Determine the type of an image","31.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">imp</span></code> \u2014 Access the <code class=\"docutils literal notranslate\"><span class=\"pre\">import</span></code> internals","31.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">importlib</span></code> \u2014 Convenience wrappers for <code class=\"docutils literal notranslate\"><span class=\"pre\">__import__()</span></code>","31.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">imputil</span></code> \u2014 Import utilities","The Python Standard Library","28.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">inspect</span></code> \u2014 Inspect live objects","20. Internet Protocols and Support","1. Introduction","15.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">io</span></code> \u2014 Core tools for working with streams","17. Interprocess Communication and Networking","9.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">itertools</span></code> \u2014 Functions creating iterators for efficient looping","39.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">jpeg</span></code> \u2014 Read and write JPEG files","18.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">json</span></code> \u2014 JSON encoder and decoder","32.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">keyword</span></code> \u2014 Testing for Python keywords","32. Python Language Services","10.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">linecache</span></code> \u2014 Random access to text lines","22.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">locale</span></code> \u2014 Internationalization services","15.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">logging</span></code> \u2014 Logging facility for Python","15.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">logging.config</span></code> \u2014 Logging configuration","15.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">logging.handlers</span></code> \u2014 Logging handlers","37. Mac OS X specific services","37.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">MacOS</span></code> \u2014 Access to Mac OS interpreter features","38. MacPython OSA Modules","37.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">macostools</span></code> \u2014 Convenience routines for file manipulation","10.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">macpath</span></code> \u2014 Mac OS 9 path manipulation functions","18.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">mailbox</span></code> \u2014 Manipulate mailboxes in various formats","18.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">mailcap</span></code> \u2014 Mailcap file handling","19. Structured Markup Processing Tools","11.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">marshal</span></code> \u2014 Internal Python object serialization","9.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">math</span></code> \u2014 Mathematical functions","14.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">md5</span></code> \u2014 MD5 message digest algorithm","18.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">mhlib</span></code> \u2014 Access to MH mailboxes","18.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">mimetools</span></code> \u2014 Tools for parsing MIME messages","18.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">mimetypes</span></code> \u2014 Map filenames to MIME types","18.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">MimeWriter</span></code> \u2014 Generic MIME file writer","18.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">mimify</span></code> \u2014 MIME processing of mail messages","38.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">MiniAEFrame</span></code> \u2014 Open Scripting Architecture server support","34. Miscellaneous Services","21. Multimedia Services","16.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">mmap</span></code> \u2014 Memory-mapped file support","31.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">modulefinder</span></code> \u2014 Find modules used by a script","31. Importing Modules","35.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">msilib</span></code> \u2014 Read and write Microsoft Installer files","35.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">msvcrt</span></code> \u2014 Useful routines from the MS VC++ runtime","18.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">multifile</span></code> \u2014 Support for files containing distinct parts","16.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">multiprocessing</span></code> \u2014 Process-based \u201cthreading\u201d interface","8.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">mutex</span></code> \u2014 Mutual exclusion support","18. Internet Data Handling","13.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">netrc</span></code> \u2014 netrc file processing","8.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">new</span></code> \u2014 Creation of runtime internal objects","36.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">nis</span></code> \u2014 Interface to Sun\u2019s NIS (Yellow Pages)","20.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">nntplib</span></code> \u2014 NNTP protocol client","9.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">numbers</span></code> \u2014 Numeric abstract base classes","9. Numeric and Mathematical Modules","9.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">operator</span></code> \u2014 Standard operators as functions","15.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">optparse</span></code> \u2014 Parser for command line options","15.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">os</span></code> \u2014 Miscellaneous operating system interfaces","10.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">os.path</span></code> \u2014 Common pathname manipulations","21.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">ossaudiodev</span></code> \u2014 Access to OSS-compatible audio devices","24.7. Other Graphical User Interface Packages","32.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">parser</span></code> \u2014 Access Python parse trees","26.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">pdb</span></code> \u2014 The Python Debugger","11. Data Persistence","11.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">pickle</span></code> \u2014 Python object serialization","32.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">pickletools</span></code> \u2014 Tools for pickle developers","36.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">pipes</span></code> \u2014 Interface to shell pipelines","31.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">pkgutil</span></code> \u2014 Package extension utility","15.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">platform</span></code> \u2014  Access to underlying platform\u2019s identifying data","13.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">plistlib</span></code> \u2014 Generate and parse Mac OS X <code class=\"docutils literal notranslate\"><span class=\"pre\">.plist</span></code> files","17.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">popen2</span></code> \u2014 Subprocesses with accessible I/O streams","20.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">poplib</span></code> \u2014 POP3 protocol client","36.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">posix</span></code> \u2014 The most common POSIX system calls","36.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">posixfile</span></code> \u2014 File-like objects with locking support","8.18. <code class=\"docutils literal notranslate\"><span class=\"pre\">pprint</span></code> \u2014 Data pretty printer","26.4. The Python Profilers","36.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">pty</span></code> \u2014 Pseudo-terminal utilities","36.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">pwd</span></code> \u2014 The password database","32.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">py_compile</span></code> \u2014 Compile Python source files","32.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">pyclbr</span></code> \u2014 Python class browser support","25.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">pydoc</span></code> \u2014 Documentation generator and online help system","19.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.parsers.expat</span></code> \u2014 Fast XML parsing using Expat","28. Python Runtime Services","8.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">Queue</span></code> \u2014 A synchronized queue class","18.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">quopri</span></code> \u2014 Encode and decode MIME quoted-printable data","9.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">random</span></code> \u2014 Generate pseudo-random numbers","7.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">re</span></code> \u2014 Regular expression operations","16.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">readline</span></code> \u2014 GNU readline interface","8.19. <code class=\"docutils literal notranslate\"><span class=\"pre\">repr</span></code> \u2014 Alternate <code class=\"docutils literal notranslate\"><span class=\"pre\">repr()</span></code> implementation","36.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">resource</span></code> \u2014 Resource usage information","30. Restricted Execution","30.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">rexec</span></code> \u2014 Restricted execution framework","18.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">rfc822</span></code> \u2014 Parse RFC 2822 mail headers","16.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">rlcompleter</span></code> \u2014 Completion function for GNU readline","13.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">robotparser</span></code> \u2014  Parser for robots.txt","31.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">runpy</span></code> \u2014 Locating and executing Python modules","8.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">sched</span></code> \u2014 Event scheduler","24.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">ScrolledText</span></code> \u2014 Scrolled Text Widget","16.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">select</span></code> \u2014 Waiting for I/O completion","8.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">sets</span></code> \u2014 Unordered collections of unique elements","39. SGI IRIX Specific Services","19.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">sgmllib</span></code> \u2014 Simple SGML parser","14.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">sha</span></code> \u2014 SHA-1 message digest algorithm","11.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">shelve</span></code> \u2014 Python object persistence","23.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">shlex</span></code> \u2014 Simple lexical analysis","10.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">shutil</span></code> \u2014 High-level file operations","17.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">signal</span></code> \u2014 Set handlers for asynchronous events","20.19. <code class=\"docutils literal notranslate\"><span class=\"pre\">SimpleHTTPServer</span></code> \u2014 Simple HTTP request handler","20.24. <code class=\"docutils literal notranslate\"><span class=\"pre\">SimpleXMLRPCServer</span></code> \u2014 Basic XML-RPC server","28.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">site</span></code> \u2014 Site-specific configuration hook","20.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">smtpd</span></code> \u2014 SMTP Server","20.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">smtplib</span></code> \u2014 SMTP protocol client","21.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">sndhdr</span></code> \u2014 Determine type of sound file","17.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">socket</span></code> \u2014 Low-level networking interface","20.17. <code class=\"docutils literal notranslate\"><span class=\"pre\">SocketServer</span></code> \u2014 A framework for network servers","16. Optional Operating System Services","36.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">spwd</span></code> \u2014 The shadow password database","11.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">sqlite3</span></code> \u2014 DB-API 2.0 interface for SQLite databases","17.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">ssl</span></code> \u2014 TLS/SSL wrapper for socket objects","10.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">stat</span></code> \u2014 Interpreting <code class=\"docutils literal notranslate\"><span class=\"pre\">stat()</span></code> results","10.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">statvfs</span></code> \u2014 Constants used with <code class=\"docutils literal notranslate\"><span class=\"pre\">os.statvfs()</span></code>","5. Built-in Types","7.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">string</span></code> \u2014 Common string operations","7.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">StringIO</span></code> \u2014 Read and write strings as files","7.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">stringprep</span></code> \u2014 Internet String Preparation","7. String Services","7.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">struct</span></code> \u2014 Interpret strings as packed binary data","17.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">subprocess</span></code> \u2014 Subprocess management","40. SunOS Specific Services","21.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">sunau</span></code> \u2014 Read and write Sun AU files","40.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">sunaudiodev</span></code> \u2014 Access to Sun audio hardware","32.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">symbol</span></code> \u2014 Constants used with Python parse trees","32.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">symtable</span></code> \u2014 Access to the compiler\u2019s symbol tables","28.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">sys</span></code> \u2014 System-specific parameters and functions","28.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">sysconfig</span></code> \u2014 Provide access to Python\u2019s configuration information","36.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">syslog</span></code> \u2014 Unix syslog library routines","32.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">tabnanny</span></code> \u2014 Detection of ambiguous indentation","12.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">tarfile</span></code> \u2014 Read and write tar archive files","20.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">telnetlib</span></code> \u2014 Telnet client","10.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">tempfile</span></code> \u2014 Generate temporary files and directories","36.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">termios</span></code> \u2014 POSIX style tty control","25.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">test</span></code> \u2014 Regression tests package for Python","7.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">textwrap</span></code> \u2014 Text wrapping and filling","16.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">thread</span></code> \u2014 Multiple threads of control","16.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">threading</span></code> \u2014 Higher-level threading interface","15.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">time</span></code> \u2014 Time access and conversions","26.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">timeit</span></code> \u2014 Measure execution time of small code snippets","24.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">Tix</span></code> \u2014 Extension widgets for Tk","24. Graphical User Interfaces with Tk","24.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">Tkinter</span></code> \u2014 Python interface to Tcl/Tk","32.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">token</span></code> \u2014 Constants used with Python parse trees","32.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">tokenize</span></code> \u2014 Tokenizer for Python source","26.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">trace</span></code> \u2014 Trace or track Python statement execution","28.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">traceback</span></code> \u2014 Print or retrieve a stack traceback","24.2. <code class=\"docutils literal notranslate\"><span class=\"pre\">ttk</span></code> \u2014 Tk themed widgets","36.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">tty</span></code> \u2014 Terminal control functions","24.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">turtle</span></code> \u2014 Turtle graphics for Tk","8.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">types</span></code> \u2014 Names for built-in types","41. Undocumented Modules","7.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">unicodedata</span></code> \u2014 Unicode Database","25.3. <code class=\"docutils literal notranslate\"><span class=\"pre\">unittest</span></code> \u2014 Unit testing framework","36. Unix Specific Services","20.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">urllib</span></code> \u2014 Open arbitrary resources by URL","20.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">urllib2</span></code> \u2014 extensible library for opening URLs","20.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">urlparse</span></code> \u2014 Parse URLs into components","28.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">user</span></code> \u2014 User-specific configuration hook","8.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">UserDict</span></code> \u2014 Class wrapper for dictionary objects","18.16. <code class=\"docutils literal notranslate\"><span class=\"pre\">uu</span></code> \u2014 Encode and decode uuencode files","20.15. <code class=\"docutils literal notranslate\"><span class=\"pre\">uuid</span></code> \u2014 UUID objects according to RFC 4122","28.6. <code class=\"docutils literal notranslate\"><span class=\"pre\">warnings</span></code> \u2014 Warning control","21.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">wave</span></code> \u2014 Read and write WAV files","8.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">weakref</span></code> \u2014 Weak references","20.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">webbrowser</span></code> \u2014 Convenient Web-browser controller","11.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">whichdb</span></code> \u2014 Guess which DBM module created a database","35. MS Windows Specific Services","35.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">winsound</span></code> \u2014 Sound-playing interface for Windows","20.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">wsgiref</span></code> \u2014 WSGI Utilities and Reference Implementation","13.5. <code class=\"docutils literal notranslate\"><span class=\"pre\">xdrlib</span></code> \u2014 Encode and decode XDR data","19.5. XML Processing Modules","19.8. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.dom</span></code> \u2014 The Document Object Model API","19.9. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.dom.minidom</span></code> \u2014 Minimal DOM implementation","19.10. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.dom.pulldom</span></code> \u2014 Support for building partial DOM trees","19.7. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.etree.ElementTree</span></code> \u2014 The ElementTree XML API","19.11. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.sax</span></code> \u2014 Support for SAX2 parsers","19.12. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.sax.handler</span></code> \u2014 Base classes for SAX handlers","19.14. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.sax.xmlreader</span></code> \u2014 Interface for XML parsers","19.13. <code class=\"docutils literal notranslate\"><span class=\"pre\">xml.sax.saxutils</span></code> \u2014 SAX Utilities","20.23. <code class=\"docutils literal notranslate\"><span class=\"pre\">xmlrpclib</span></code> \u2014 XML-RPC client access","12.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">zipfile</span></code> \u2014 Work with ZIP archives","31.4. <code class=\"docutils literal notranslate\"><span class=\"pre\">zipimport</span></code> \u2014 Import modules from Zip archives","12.1. <code class=\"docutils literal notranslate\"><span class=\"pre\">zlib</span></code> \u2014 Compression compatible with <strong class=\"program\">gzip</strong>","History and License","7. Compound statements","3. Data model","4. Execution model","5. Expressions","9. Full Grammar specification","The Python Language Reference","1. Introduction","2. Lexical analysis","6. Simple statements","8. Top-level components","15. Appendix","1. Whetting Your Appetite","9. Classes","4. More Control Flow Tools","5. Data Structures","8. Errors and Exceptions","14. Floating Point Arithmetic:  Issues and Limitations","The Python Tutorial","7. Input and Output","13. Interactive Input Editing and History Substitution","2. Using the Python Interpreter","3. An Informal Introduction to Python","6. Modules","10. Brief Tour of the Standard Library","11. Brief Tour of the Standard Library \u2014 Part II","12. What Now?","1. Command line and environment","Python Setup and Usage","4. Using Python on a Macintosh","2. Using Python on Unix platforms","3. Using Python on Windows","What\u2019s New in Python 2.0","What\u2019s New in Python 2.1","What\u2019s New in Python 2.2","What\u2019s New in Python 2.3","What\u2019s New in Python 2.4","What\u2019s New in Python 2.5","What\u2019s New in Python 2.6","What\u2019s New in Python 2.7","What\u2019s New in Python"],titleterms:{"2to3":109,"abstract":[2,63,79,92,93,94,95,100,101,102,106,114,125,152,157,300,476],"boolean":[5,303,368,434,442,473],"break":[447,452],"byte":[7,50,156,168,373,476],"case":[81,106,107,407,471],"catch":82,"class":[10,63,81,82,88,94,114,123,125,126,143,149,150,152,196,202,208,230,253,256,273,290,293,300,311,322,326,330,368,373,403,407,413,423,431,439,440,446,451,472,475,476],"const":123,"default":[88,123,303,364,365,416,452,477],"export":168,"final":[28,79,475],"float":[22,81,178,216,217,368,438,446,455,463,474],"function":[6,7,13,23,52,56,63,77,81,82,88,94,95,96,101,103,119,140,143,147,152,156,164,165,168,169,171,185,212,222,223,253,258,265,266,272,277,291,302,304,326,340,364,365,368,369,373,374,380,381,388,402,403,407,409,416,429,434,438,439,452,453,461,470,471,474,475,476],"goto":81,"import":[26,82,88,95,249,251,265,266,267,289,391,436,447,461,471,473,474,475,476],"int":[92,368],"long":[34,89,92,368,446,472,474],"new":[6,63,68,79,83,96,107,297,303,416,440,470,471,472,473,474,475,476,477,478],"null":[77,368],"public":[156,403],"return":[81,88,168,447],"short":[91,100],"static":[88,94,100],"switch":81,"try":[88,439,475],"while":[81,84,439],Added:477,Adding:[68,79,99,123,300,303,477],And:87,Are:[83,87,88,186,451],FOR:438,For:[93,264,333,416,477],IDE:467,IDEs:468,Ice:77,Its:459,NIS:298,Not:95,One:139,Res:141,TLS:365,That:96,The:[6,37,40,58,63,64,71,73,77,79,91,93,96,100,101,103,104,106,107,123,157,207,208,215,230,233,252,253,271,293,300,303,309,311,319,322,324,363,368,396,403,416,426,429,432,439,440,442,444,447,449,452,453,456,459,461,467,472,473,474,475,476,477],Use:[95,100,101,106,396],Used:374,Useful:[98,291],Using:[1,80,95,98,99,101,102,103,105,107,109,143,157,238,293,322,364,374,391,394,401,403,453,459,460,467,468,469,475,476],With:440,__builtin__:110,__builtin_new:82,__del__:88,__future__:[111,471],__import__:[88,250],__index__:475,__main__:112,__pure_virtu:82,__slots__:440,__spam:88,_pyimport_fixupextens:82,_someclassname__spam:88,_winreg:113,a_tupl:88,abbrevi:123,abc:[114,300],about:[0,83,88,143,186,403,451,470],absolut:475,abstractbasicauthhandl:410,abstractdigestauthhandl:410,access:[64,82,87,113,121,133,142,168,211,243,249,263,264,266,269,279,306,308,315,317,364,377,379,381,392,434,438,440,462,472],accessor:426,accord:415,accssor:141,acknowledg:[96,104,230,438,470,471,472,473,474,475,476,477],across:[88,99],action:[123,303,454],adapt:364,add_argu:123,add_help:123,added:[82,159],addit:[71,72,88,202,244,280,364,368,429,440,467,469],address:293,addresslist:339,advanc:[28,91,98,186,256,476],adverb:333,aepack:115,aeserv:284,aetool:116,aetyp:117,agreement:438,aifc:118,aiff:118,algorithm:[137,236,278,349,438],alias:407,align:[168,373],all:[63,81,88,293,303,333,477],alloc:[3,37,79,473],allow:81,alon:88,also:88,altern:[82,107,335,445,458,469],ambigu:383,among:87,analysi:[88,351,446],angular:277,ani:[63,82,83,87],anim:403,anoth:[76,88],anti:95,anydbm:[87,121],anyth:82,api:[7,13,27,28,63,77,92,186,202,204,230,364,426,429,473,474,475,476,477],app:141,appear:[88,141,403],appendix:449,appetit:450,appl:[141,271],appleev:[115,117],applesingl:405,appli:88,applic:[76,83,84,87,89,93,150,219,230,240,467,475],approach:80,arbitrari:[77,82,98,303,409,452],architectur:284,archiv:[63,122,352,384,435,436,473],archive_util:63,area:63,argpars:[91,123,477],argument:[4,87,88,91,123,168,303,374,452,459,462],argument_default:123,argumentpars:123,argv:123,arithmet:[81,178,300,442,455,463],around:63,arrai:[7,88,124,137,168,260],articl:[83,105],ascend:103,ascii:[56,88,135,170],ask:85,assert:[101,447],assign:[81,157,447,470],ast:[125,157,476],asynchat:126,asynchron:[28,126,127,353,361,438],asyncor:127,atexit:128,atom:442,attr:426,attribut:[79,81,88,93,265,303,368,432,440,442,471,472],attributesn:432,au_read:376,au_writ:376,audio:[119,129,306,377],audioop:129,augment:[447,470],authent:[105,237,293],autogil:130,autom:109,automat:[244,346],auxiliari:126,avail:[174,403,416],avoid:87,awar:104,babyl:273,babylmessag:273,back:[77,106],background:[264,303],backport:477,backquot:374,backslash:[81,95,101],base16:131,base32:131,base64:131,base:[63,88,99,114,149,150,152,230,256,293,300,423,431,476,477],basehandl:410,basehttpserv:132,basic:[79,91,98,103,105,108,127,132,157,174,186,191,236,260,355,393,394,396,407,440],bastion:133,batteri:[95,462],bcppcompil:63,bdb:134,bdist:63,bdist_dumb:63,bdist_msi:63,bdist_packag:63,bdist_rpm:63,bdist_wininst:63,been:83,befor:83,begin:83,behavior:174,beopen:438,berkelei:[87,138],best:[88,107,365],beta:83,between:[72,80,88,100,115,135,154,293,303,446],beyond:[76,123],bin:374,binari:[62,63,87,88,100,102,108,135,256,373,434,442,463],binascii:135,bind:[84,396,441,458],binhex4:136,binhex:136,bisect:137,bit:[113,168],bitwis:[368,442],blank:446,block:[87,89,100,102,365],bom:[99,150],book:83,bootstrap:[204,477],borland:[63,107],both:87,branch:477,breakpoint:88,brief:[462,463],browser:[162,326,419],bsd:175,bsddb185:83,bsddb:[87,138],btree:138,buffer:[6,42,55,99,256,334,368,476],bug:[1,28,83,88,401],build:[4,30,63,75,77,80,107,184,428,429,468,471,473,474,475,476,477],build_clib:63,build_ext:63,build_pi:63,build_script:63,buildapplet:405,buildtool:405,built:[56,64,96,110,159,206,222,346,368,404,405,470,474],builtin:224,bunch:87,bundl:469,bytearrai:368,bytecod:[157,182],bz2:139,bzip2:139,cab:290,cach:181,cacheftphandl:410,calcul:[81,460],calendar:140,calibr:322,call:[77,81,82,83,88,96,168,185,207,303,319,405,438,442],callabl:[223,364,440],callback:[168,303,473],calltip:244,can:[81,82,83,84,86,87,88,89,311],capabl:144,capsul:[8,92,477],captur:101,carbon:141,carbonev:141,carbonevt:141,care:143,catalog:[230,264],categori:[20,416],caveat:[28,264],ccompil:63,cdatasect:426,cell:[9,169],certif:[365,477],cfmfile:405,cgi:[87,106,143,144,145],cgihttpserv:144,cgitb:145,cgixmlrpcrequesthandl:355,chain:365,chang:[83,88,92,98,230,470,471,472,473,474,475,476,477],charact:[56,101,104,169,170,194,260,373],charset:194,check:[7,63,88,89,100,165,186,303,333,440],checker:423,choic:123,chomp:88,choos:62,chunk:146,cipher:365,circu:83,classic:440,classif:147,claus:452,clean:[63,454],cleanup:[293,303],client:[116,127,162,221,241,246,293,299,318,358,365,385,434,477],close:87,cmath:147,cmd:[63,148],cmp:103,cnri:438,cobject:[11,92],code:[12,28,81,88,100,104,105,109,123,149,151,244,253,368,391,393,405,407,416,452,459,473],codec:[13,56,150,473],codegear:107,codeop:151,coercion:[440,471],collabor:62,collect:[24,79,152,346,470,477],collector:225,colon:81,color:[93,153,154,244,403],colorpick:153,colorsi:154,column:[364,401],com:438,combin:[91,365],combobox:401,come:87,comma:[81,88,473],command:[63,65,68,71,73,123,126,148,155,156,180,204,228,244,303,309,388,393,394,399,407,435,462,465,477],comment:[426,446],common:[51,87,101,106,108,143,305,319,364,369],commun:257,compar:453,comparison:[79,208,346,368,442,471],compat:[100,139,306,401,437],compil:[63,64,76,77,81,82,92,101,107,151,156,157,308,325,379,461,469],compileal:156,complain:83,complet:[244,334,340,345,448],complex:[14,103,147,368],complianc:260,complic:88,compon:[87,141,411,448],compos:96,compound:[403,439],comprehens:[96,453,470],compress:[122,139,437,462],comput:[86,180],concaten:446,concept:[70,91],conclus:91,concret:15,condit:[92,303,391,438,442,453,475],condition:99,config:[63,107,243,266,405],configpars:158,configur:[63,66,98,99,107,119,158,266,356,381,403,412,467,469,477],conflict:[91,303],conflict_handl:123,conform:[423,426],connect:[87,266,293,364],consid:100,consider:[216,365],consist:88,consol:[149,244,291],constant:[113,119,141,147,159,169,212,231,277,304,328,364,365,367,369,374,377,378,397],construct:95,constructor:[88,230,374],contain:[81,115,123,152,292,440],content:[60,81,82,83,84,87,88,89,94,167,319,328,333,426],contenthandl:431,context:[99,160,178,186,244,364,365,368,416,440,474,475,476],contextlib:[160,475,476],contextu:99,continu:[95,100,168,447,452],contribut:1,contributor:0,control:[20,52,64,79,106,141,216,317,364,387,390,402,403,416,419,438,452,462],controlaccessor:141,controlswindow:219,conveni:[250,271,419,434],convers:[16,115,147,154,168,217,277,346,392,442,474],convert:[88,135,308,364,374],cookbook:[80,99],cooki:[161,162,438],cookiejar:162,cookielib:[162,474],cookiepolici:162,coordin:147,copi:[83,87,88,163],copy_reg:164,copyright:[61,83],copytre:352,core:[63,88,141,256,470],corefoun:141,coregraph:141,correspond:403,corrupt:87,count:[30,45,77],counter:152,coupl:396,coverag:100,cpickl:[87,311],cprofil:322,cpython:81,crash:87,creat:[28,62,63,64,73,82,83,87,88,96,102,123,201,258,303,308,420],creation:[297,304,361,365,440],cross:[64,315],crypt:165,cryptograph:166,cstringio:370,csv:167,ctl:141,ctype:[168,293,475,476],current:[88,108],curs:[87,93,169,170,171],cursor:364,custom:[98,99,107,123,168,172,266,293,322,364,369,440,449],cwi:438,cycl:470,cyclic:[24,79],cygwin:[63,107],cygwincompil:63,data:[36,63,72,79,81,87,88,96,98,100,102,104,105,106,115,122,129,131,146,168,173,238,245,295,310,311,315,321,331,373,396,424,440,453,457,462,463,474],databas:[87,121,175,176,233,290,324,363,364,406,420],datagramhandl:267,datatyp:[152,473],date:[98,174,462,473],datetim:[17,174,434],dbhash:175,dbm:[121,175,176,188,226,420],debug:[30,63,72,82,96,143,177,186,244,465,477],debugg:[28,88,134,309],debuggingserv:357,decim:[178,463,474],declar:446,decod:[88,136,260,331,405,414,424],decor:[103,474,476],deep:163,def:81,defaultcookiepolici:162,defaultdict:152,defect:196,defer:230,defin:[79,88,212,266,303,338,452,454],definit:[81,94,95,104,111,239,439,451],defus:425,del:[447,453],deleg:88,delet:[86,87,88,470],delimit:446,delta:180,demo:403,denot:100,dep_util:63,depend:[63,100],deprec:[273,369,407,470,473,474,476,477],dequ:152,deriv:[88,235],descend:103,describ:72,descript:[123,328],descriptor:[18,94,141,304,440,472],design:[81,212],dest:123,destin:99,detail:[30,100,264,266],detect:[100,383],determin:[248,359],determinist:322,develop:[83,179,312,470,476],devic:[231,306,377],devot:83,dialect:167,dialog:[141,153,191],dialogwindow:219,diamond:472,dict:[99,368],dictconfig:99,dictionari:[19,81,88,99,266,368,413,442,453,477],did:88,die:102,differ:[80,88,100,180,192,244,403],difflib:180,digest:[235,278,349,438],dir:461,dir_util:63,dircach:181,dircmp:208,direct:[7,186,471],directori:[63,181,208,211,290,304,352,386,461,476],dis:182,disassembl:182,disconnect:102,discov:88,discoveri:407,displai:[71,88,93,98,169,442,471],dist:63,distinct:292,distribut:[62,63,64,67,68,69,72,73,75,183,467],distutil:[63,68,70,71,75,107,184,470,473],divis:[100,472],django:106,dlg:141,dll:[80,89,168],doc:87,doccgixmlrpcrequesthandl:187,docstr:[186,403],doctest:[186,474],doctestfind:186,doctestpars:186,doctestrunn:186,document:[0,1,60,83,87,89,96,187,197,239,327,426,429,452,476,477],documenttyp:426,docxmlrpcserv:187,doe:[81,82,83,88,89],doesn:[81,87],dom:[426,427,428,470],domain:150,domeventstream:428,domimplement:426,don:[87,88],done:83,download:89,drag:141,dragconst:141,draw:403,drop:[100,141,189,190],dtdhandler:431,dtoa:438,dumb:[63,64],dumbdbm:188,dummi:293,dummy_thread:[189,190],duplic:88,dure:98,dynam:[168,441],each:88,eas:96,easi:470,easier:88,easydialog:191,echo:127,edg:345,edit:[88,244,458],editor:[89,141,244,468],effici:[124,258,364],element:[96,346,426,429],elementtre:[429,475,477],ellipsi:[49,368],els:452,email:[192,193,194,195,196,197,198,199,200,201,202,203],emb:[89,264],embed:[30,76,78,82,470],emul:[81,89,308,440],emx:63,emxccompil:63,enabl:477,encod:[13,88,104,131,136,150,195,260,331,414,424,446,459,473],end:[81,93,103,451],enforc:81,enhanc:[473,476,477],ensurepip:[204,477],entiti:239,entityresolv:431,enumer:473,environ:[112,338,423,459,465,469,477],epilog:123,epol:345,equival:[87,88],errno:205,error:[13,63,77,87,88,105,178,196,290,303,308,328,405,449,454,455,462,473],errorhandl:431,escap:56,essenti:222,etc:[87,88],etre:429,evalu:[82,442],event:[84,99,130,141,271,343,353,391,396,401,403],evt:141,examin:[186,379],exampl:[37,67,70,77,79,94,98,99,123,126,127,128,132,137,152,157,158,161,162,164,167,180,186,193,216,234,236,238,240,241,246,249,251,273,288,292,293,303,308,311,316,318,321,328,333,334,338,346,350,352,353,355,358,360,361,365,369,373,382,384,385,387,391,393,400,407,409,410,415,418,423,427,429,434,436],except:[20,30,63,77,81,88,95,98,99,105,186,196,206,216,273,293,308,328,365,373,374,424,426,438,441,451,454,475,476,477],exchang:293,exclus:[123,294],excursu:[403,469],exec:[95,447],execfil:95,execut:[82,87,89,186,244,337,338,342,393,399,438,441,449,461,469,475],exist:84,exit:[81,123,128],expans:232,expat:[328,438],expaterror:328,expect:[83,407],explan:100,explicit:[446,476],explicitli:81,express:[81,82,96,101,333,442,447,448,451,452,474,475],extend:[68,76,77,78,82,303,470,473],extens:[28,62,63,67,72,75,77,80,82,87,92,107,108,171,244,264,311,314,394,405,410],extern:[266,311],extract:[77,82,89],facil:265,factori:152,fail:82,failur:407,famili:[65,374],fancier:457,fancy_getopt:63,faq:[81,82,83,84,86,87,88,89,178],fast:[81,328],fastcgi:106,faster:[311,370],fault:434,fcntl:207,featur:[100,269,290,441,475,477],feedback:101,feedpars:202,fetch:105,field:[152,168],file:[21,30,63,66,71,72,73,82,87,88,89,98,99,100,107,118,123,136,139,141,158,167,186,208,209,211,234,244,247,256,259,266,271,274,282,287,290,291,292,296,304,316,319,320,325,334,352,359,368,370,376,384,386,394,396,414,417,429,448,449,457,461,462,468,473],file_util:63,filecmp:208,filecookiejar:162,filehandl:[267,410],fileinput:210,filelist:63,filenam:[104,214,281],filetyp:123,fill:[389,403],filter:[99,265,399,416],find:[82,87,88,168,288,333,429,469],finder:271,findertool:271,fine:95,finer:79,first:[83,451,460],fix:[178,303,471,472,473,477],fixer:109,fixtur:407,flag:[101,107,123,186,303,304],flow:[98,317,452],flp:212,fltk:84,fly:[83,230],fnmatch:214,folder:[141,279],font:[141,213],footnot:105,foreign:168,form:[87,212,394,442],formal:96,format:[16,98,99,167,209,215,244,266,273,293,311,368,369,373,384,457,463,476,477],formatt:[98,99,215,265],formatter_class:123,foundat:[83,141],fpectl:216,fpformat:217,fraction:[218,476],fragment:405,framework:[106,134,219,220,338,361,405,407,471],freebsd:[468,477],freed:81,freez:84,frequent:[85,374],friend:[95,405],from:[28,63,77,82,87,88,89,95,98,99,147,168,192,201,210,291,374,403,436,461,473,476],fromfile_prefix_char:123,frozenset:368,ftp:221,ftp_tl:221,ftphandler:410,ftplib:221,full:443,functool:[96,223],fundament:[15,168],futur:[83,111,447,477],future_builtin:[224,476],garbag:[24,79,225,470],gatewai:[106,143,423],gdbm:226,gener:[25,56,70,79,83,87,88,96,120,121,140,141,157,197,215,227,239,282,303,316,327,332,365,368,379,386,442,451,465,472,473,474,475],gensuitemodul:227,geometri:394,get:[1,81,82,83,84,87,88,91,467,468],getopt:[63,228],getpass:229,gettext:230,geturl:105,gil:28,given:88,glob:232,global:[28,87,88,130,447],glossari:90,gmt:99,gnu:[107,226,230,334,340],gnutransl:230,good:[83,100],grammar:[125,443],graphic:[84,141,212,231,307,395,403],greedi:101,group:[81,96,101,123,233,303,407],grp:233,gtk:84,guess:420,gui:[84,290,467],guid:[62,88,94,303],guidelin:293,gzip:[234,437],handi:396,handl:[20,84,105,113,130,141,162,169,192,274,295,303,308,365,407,449,454,473,476,477],handler:[13,87,98,99,105,126,127,128,144,265,267,353,354,361,396,423,431],happen:[88,98],hard:82,hardwar:377,has:88,hash:[138,235,237],hashlib:[235,475],have:[81,83,84,88,100],header:[63,105,198,339,423],heap:[3,236],heapq:236,hello:396,help:[87,88,123,141,244,303,327,403],helper:[125,180,374,405],hexadecim:88,hierarch:394,hierarchi:[206,440,476],high:[28,58,76,152,238,352,409],higher:[88,143,223,391],hint:264,histori:[81,96,102,104,192,334,438,458],hkey_:113,hmac:237,home:107,hook:[334,356,412,471,473],hotshot:238,how:[62,81,82,83,84,87,88,89,103,107,108,186,303,396,403,467],howto:[94,96,97,98,101,102,104,105,106],html:[87,239,240],htmlentitydef:239,htmllib:239,htmlparser:[239,240],http:[127,132,144,161,162,241,354,423,477],httpbasicauthhandl:410,httpconnect:241,httpcookieprocessor:410,httpdigestauthhandl:410,httperror:105,httperrorprocessor:410,httphandler:[267,410],httplib:241,httppasswordmgr:410,httpredirecthandl:410,httprespons:241,httpshandler:410,hyperbol:[147,277],ibcarbon:141,ibcarbonruntim:141,icn:141,icon:141,icopen:405,ident:442,identifi:[315,401,442,446],idiom:95,idl:[244,470,477],idna:150,iff:146,imag:[245,248,394,396],imageop:245,imaginari:446,imap4:246,imaplib:246,imgfil:247,imghdr:248,imglib:247,immut:[81,346],imp:249,impart:99,implement:[44,81,82,87,99,188,215,236,260,300,335,423,427,440,445],implementor:300,implicit:446,importlib:[250,477],improv:[470,471,472,473,474,475,476,477],imputil:251,inaccur:81,includ:[30,462],incompat:83,incomplet:[82,168],incorpor:438,increas:178,increment:266,incrementaldecod:150,incrementalencod:150,incrementalpars:432,indent:[81,244,383,446],independ:[84,474],index:[63,71,74,81,88,364,396,473,475],individu:[63,72],infinit:260,info:105,inform:[63,83,93,99,290,304,336,381,460],ingredi:106,inherit:[82,403,451,472],init:334,initi:[28,77,92],input:[82,87,93,169,210,229,448,457,458],inputsourc:432,insensit:471,insert:[89,99],insid:95,inspect:253,instal:[62,63,64,65,72,86,107,108,143,184,204,290,381,467,468,469,470],install_data:[63,65],install_head:63,install_lib:63,install_script:[63,65],instanc:[10,88,311,368,440,451],instant:322,instead:[81,100,364],instruct:182,integ:[29,34,88,368,446,472,474,476],integr:[68,100,265],interact:[149,186,219,441,448,449,458,459,471,475],interest:429,interfac:[37,81,82,84,87,106,138,141,143,157,175,176,180,204,212,213,215,225,231,256,271,293,298,304,307,313,334,360,364,388,391,393,395,396,399,407,409,422,432,435,462,465],interfacebuild:141,intermezzo:[77,452],intern:[249,266,276,297,368],internation:[150,198,230,242,264],internet:[87,105,243,254,295,371,405,462],interoper:260,interpret:[28,78,81,87,130,148,149,172,253,269,366,373,458,459,472,475,476,477],interprocess:257,intra:461,introduc:91,introduct:[30,70,94,96,101,104,105,107,143,255,293,322,364,403,445,460,470,471,472],invalid:[82,87,123],invok:[94,440,459],ioctl:207,ipc:102,irix:[347,476],isn:81,issu:[1,108,317,364,384,455,476],item:[88,401],iter:[31,32,88,96,199,210,258,368,442,451,472,474],itertool:[96,258],its:88,itself:364,java:315,javascript:476,job:107,join:[81,446],jpeg:259,json:[260,457,476],just:[95,108],keep:[83,89],kei:[62,81,84,88,103,108,235,237,293,365,458],kevent:345,keypress:[87,89],keyword:[77,88,261,446,452],kill:89,kind:87,kqueue:[345,438],label:401,lambda:[81,88,96,442,452],languag:[81,83,88,95,230,262,369,403,444,470,473,474,475,476,477],larg:319,latest:468,latin:56,launch:141,launchservic:141,layer:[2,15,58,105],layout:[401,463],learn:100,legaci:[69,107],len:81,length:82,let:364,level:[28,58,76,88,95,98,101,106,112,143,260,265,345,352,360,391,409,448],lexic:[351,446],lgettext:230,lib2to3:109,libffi:438,librari:[63,72,87,98,109,138,156,168,175,212,231,252,382,410,462,463,476],libressl:365,licens:[62,438],life:396,like:[76,83,320],limit:[157,216,260,322,336,455],line:[123,148,156,180,204,210,228,244,263,303,334,388,393,399,407,435,446,458,462,465,474,477],linecach:263,liner:88,link:[76,168,472],linkag:77,linker:107,linux:[82,108,468],list:[33,72,81,83,88,96,137,141,181,334,368,413,442,452,453,460,463,470,476],listbox:394,listen:293,liter:[104,442,446,476],littl:91,live:253,load:[82,168,212,407],load_test:407,local:[88,230,264,451,474],locat:[83,107,342,405,432],lock:[28,87,130,320,391],log:[63,98,99,238,265,266,267,293,463,473,477],logarithm:[147,277],logger:[98,265],loggeradapt:[99,265],logic:[178,446],logrecord:265,look:[396,451],lookahead:101,lookup:[13,440],loop:[88,130,258,452,453],low:[28,106,360],mac:[141,243,268,269,272,315,316,405,467,476,477],macerror:405,machelp:141,machin:[81,86],macintosh:[191,467],maco:269,macostool:271,macpath:272,macpython:[270,467],macresourc:405,macro:7,mail:[83,87,283,339],mailbox:[273,279],mailcap:274,maildir:273,maildirmessag:273,mailmanproxi:357,main:[399,476],mainten:477,make:[82,87,88,89,100,333,470,477],manag:[37,79,81,99,141,145,161,213,293,304,364,368,374,394,396,416,438,440,475,476],mani:83,manifest:73,manipul:[129,245,271,272,273,303,305],manual:[27,322,365],map:[15,35,55,56,281,287,302,368,396,426],markup:275,marshal:[36,276],match:[101,123,214,333,462],math:[87,277],mathemat:[87,147,277,301,462],mbc:56,mbox:273,mboxmessag:273,md5:[278,438],mean:[82,88],measur:[393,403,462],media:141,mediadescr:141,member:253,membership:442,memori:[37,81,287],memoryhandl:267,memoryview:[6,368,477],menu:[141,244],mersenn:438,messag:[98,99,200,202,230,235,237,264,273,278,279,280,283,339,349,438],meta:[63,72],metacharact:101,metadata:[471,473,475],metavar:123,method:[38,56,77,79,81,82,87,88,94,101,123,240,273,280,303,364,368,403,426,440,442,451,457,470,474,475],mhlib:279,mhmessag:273,microsoft:[63,107,290],migrat:477,mime:[192,197,201,280,281,282,283,331],mimelib:192,mimetool:280,mimetyp:281,mimewrit:282,mimic:87,mimifi:283,mingw:107,mini:369,miniaefram:284,minidom:427,minim:427,minor:470,miscellan:[63,203,285,293,304,394,405,465,468],miss:82,mitig:178,mixer:306,mixin:361,mlte:141,mmap:287,mmdf:273,mmdfmessag:273,mod_python:106,mod_wsgi:106,mode:[63,449,459,465,477],model:[106,328,426,440,441,471],modifi:[88,101,107,399,429],modul:[26,39,62,63,65,67,69,72,75,77,82,83,87,88,92,93,95,96,98,99,101,103,107,108,119,141,143,159,167,184,189,190,204,212,230,231,256,265,270,288,289,293,301,311,319,322,333,342,364,368,374,396,403,405,407,420,425,426,436,449,461,469,470,471,472,473,474,475,476,477],modular:96,modulefind:288,moinmoin:106,monti:83,more:[79,91,93,101,132,300,403,440,452,453,461],morsel:161,most:319,motion:403,movi:405,msilib:290,msvccompil:63,msvcrt:291,multi:[256,365,463,474],multical:434,multidimension:88,multifil:292,multilingu:[141,230],multimedia:[286,405],multipl:[98,99,108,210,390,451,461,472],multiprocess:[293,476],multithread:364,mung:333,must:81,mutabl:368,mutat:87,mutex:294,mutual:[88,123,294],name1:95,name2:95,name:[62,72,88,101,107,123,150,152,260,364,404,440,441,442,451,473],namednodemap:426,namedtupl:152,namespac:[123,429,451],nan:260,narg:123,nav:405,navig:244,navservic:405,need:474,neg:88,nest:[453,471,472],netrc:296,network:[87,99,257,360,361,477],never:83,newlin:[88,473],newsgroup:83,next:98,nis:298,nntp:299,nntplib:299,node:[125,157,426],nodelist:426,non:[28,101,102,107,222,260,365],none:[40,87],normal:311,notabl:[106,319],notat:[333,445,476],note:[136,178,202,236,300,361,365,374,401],notebook:401,notif:28,notimpl:368,now:464,nteventloghandl:267,nullhandl:267,nulltransl:230,number:[14,41,55,63,83,87,88,105,147,218,260,277,300,332,460,476],numer:[15,87,124,300,301,368,440,446],obfusc:88,object:[2,3,5,6,7,9,10,12,14,15,17,18,19,20,21,22,23,25,29,30,32,33,34,37,38,39,40,43,44,48,49,50,51,53,54,55,56,59,79,82,87,88,92,98,99,110,113,117,119,123,133,138,142,148,149,150,152,158,161,162,167,169,171,174,175,178,180,185,186,187,188,191,201,212,219,221,223,238,239,241,243,246,253,260,265,266,273,276,279,280,281,282,284,290,292,293,294,296,297,299,304,306,308,311,313,317,318,320,321,326,328,330,333,335,338,339,340,343,345,346,350,351,355,357,358,360,361,364,365,368,374,376,377,384,385,391,405,409,410,413,415,417,418,419,424,426,427,428,429,430,431,432,434,435,436,440,451,457,473,474,476,477],obsolet:405,obtain:83,octal:88,odd:[103,451],off:178,offscreen:141,old:[6,42,103,143,407,440,457,472],older:[100,107,374],one:88,onexit:87,onli:244,onlin:327,open:[62,87,105,284,304,405,409,410],openbsd:468,openerdirector:410,opengl:84,opensolari:468,openssl:438,oper:[52,63,81,88,96,103,120,162,163,223,291,300,302,304,333,352,362,365,368,369,442,446,462,472],operand:178,optim:[98,473,474,475,476,477],option:[71,72,73,88,91,92,100,123,186,228,244,303,362,396,399,401,407,435,465],optpars:[123,303,473],order:[88,168,223,303,373,442,477],ordereddict:152,ordin:88,org:83,organ:[88,407],orient:148,osa:[116,141,227,270],osaconst:141,oss:306,ossaudiodev:306,other:[15,63,72,79,81,82,87,88,92,99,106,123,137,216,291,303,307,311,368,381,446,453,467,469,470,471,472,473,474,475,476,477],otherwis:438,out:87,output:[82,87,88,99,215,457,462,463],outputcheck:186,over:[79,88,210,403],overload:88,overrid:88,overview:[37,71,76,403],own:[82,106,168],ownership:77,pack:373,packag:[63,64,67,71,72,74,87,108,157,183,192,227,307,314,388,425,461,467,471,473,475,476],packer:[396,424],pad:93,page:298,pair:333,panel:171,parallel:108,paramet:[28,77,88,103,167,168,304,380,396],parcel:87,parent:123,parenthes:442,pars:[4,123,202,280,303,308,316,328,339,351,378,397,411,429,477],parse_arg:123,parser:[123,141,142,158,202,228,239,240,303,308,328,341,348,430,432,476],part:[292,463],partial:[123,223,428,475],pass:[88,96,99,168,447,452,459],password:[165,229,324,363],patch:83,path:[107,272,305,381,461,468],pathnam:[232,305],pattern:[101,214,232,462],pdb:309,pen:403,peopl:83,pep:[63,471,472,473,474,475,476,477],per:476,perform:[63,87,88,101,102,152,238,256,462],perl:88,persist:[87,106,310,350],phonebook:333,physic:446,pickl:[164,311,312,473],pickletool:312,pip:[108,204,477],pipe:[87,293,313],pipelin:[313,374],pixmap:405,pixmapwrapp:405,pkgutil:314,place:[83,88],plagu:101,plai:422,plain:[29,56],platform:[84,107,293,315,401,405,468,471],player:142,plist:316,plistlib:[316,476],point:[22,81,178,216,217,438,446,455,463],pointer:[77,168],polar:147,poll:345,pool:293,pop3:318,popen2:[317,374],popen3:[317,374],popen4:317,popen:[87,374],poplib:318,popul:303,port:[87,92,100,119,470,473,474,475,476,477],portabl:[188,229],posit:[91,303,333],posix:[319,387],posixfil:320,possibl:88,post:87,postinstal:64,power:[101,147,277,442],pprint:321,practic:[80,88],preced:[88,442],precis:178,precomput:290,predefin:454,prefer:244,prefix:[107,123],prefix_char:123,prepar:371,preprocessor:72,present:79,preserv:396,pretti:321,prettyprint:321,prevent:100,primari:442,primit:293,principl:73,print:[82,123,303,400,447,476],printabl:331,printer:321,prior:108,prioriti:236,privat:451,problem:[101,106,143],procedur:438,process:[28,52,63,99,275,283,293,296,304,365,425,470,476],processinginstruct:426,produc:87,profil:[28,177,238,322],prog:123,program:[83,87,88,89,93,96,102,104,169,220,230,264,293,396,448,453,460,462,467],programm:83,programmat:399,progressbar:[191,401],project:[62,83],proper:100,properti:[56,94,104,476],propos:83,protocol:[31,35,41,42,43,47,79,94,221,241,246,254,299,311,318,346,358,365,407,476],protocolerror:434,prototyp:168,provabl:96,provid:[77,79,98,381],proxi:[105,293],proxybasicauthhandl:410,proxydigestauthhandl:410,proxyhandl:410,pseudo:[323,332],psf:438,pty:323,publish:83,pulldom:428,pure:[67,76],pureproxi:357,put:303,pwd:324,py2ex:469,py_buff:6,py_buildvalu:82,py_compil:325,py_unicod:56,pyc:[63,88],pyclbr:326,pyd:89,pydoc:327,pyerr_print:82,pymalloc:[37,473],pypi:71,pypirc:71,python:[0,1,14,27,28,30,60,62,63,67,69,70,71,76,77,78,81,82,83,84,85,86,87,88,89,92,93,95,96,97,100,104,106,107,108,109,115,150,151,156,157,168,172,182,184,186,224,244,252,261,262,264,265,276,308,309,311,322,325,326,329,342,350,364,378,381,388,393,396,397,398,399,416,438,444,448,449,451,456,459,460,461,466,467,468,469,470,471,472,473,474,475,476,477,478],pyunicodeucs2:82,pywin32:469,pyxml:470,pyzipfil:435,qdoff:141,qdoffscreen:141,qname:429,qualiti:462,queri:[303,308],question:[84,85,87,88],queue:[236,293,330,453],quick:[178,396],quickdraw:141,quicktim:[141,405],quopri:331,quot:331,rais:[88,98,303,447,454],random:[87,263,332,365,451],rang:[88,452],ration:218,raw:[56,81,129,245,256,333],rawconfigpars:158,rawturtl:403,read:[62,87,104,118,146,167,259,290,370,376,384,405,417,457],reader:167,readlin:[334,340],real:83,realli:87,reason:83,receiv:99,recip:[152,178,258],recogn:186,record:[138,290,463],recurs:20,redhat:63,redirect:462,reentranc:256,refer:[27,30,45,59,63,65,77,79,83,88,96,104,168,293,303,322,396,418,423,429,442,444,451,461,463,471],reflect:46,regen:477,regex:87,regist:[63,71,164,364],registri:[13,113,150],regress:[100,388],regular:[101,333],reimport:88,reinterpret:226,rel:[475,476],relat:[6,73,105,140,396,468,472],relationship:[72,311,470],releas:[28,477],reli:81,remark:451,remot:[293,438],remov:[88,475,476,477],repeat:[101,260],replac:[92,101,189,190,374,405],report:[1,83],repr:335,repres:[194,200],represent:[277,455],request:[144,354,361,410],requir:[81,123,168],reserv:446,resolut:266,resourc:[105,141,336,405,409,429,467,469],respons:[126,423],restor:87,restrict:[83,133,337,338,350,409],restructuredtext:476,result:[81,88,366,411],retriev:[253,400],revers:[88,474],revis:[96,104,476],rexec:338,rfc822:339,rfc:[131,339,415],rich:471,rid:87,right:113,rlcomplet:340,rlock:391,robot:341,robotpars:341,rom:142,rotat:99,rotatingfilehandl:267,round:178,roundup:476,routin:[271,291,382],row:364,rpc:[187,355,434],rpm:[63,64],rs232:87,rule:[77,88,351,440,472],run:[87,89,155,244,388,407,467],runpi:342,runtim:[291,297,329],safe:87,safeconfigpars:158,safeti:265,same:[88,89],save:457,sax2:[430,470],sax:[430,431,432,433],saxexcept:430,saxutil:433,scanf:[88,333],scgi:106,sched:343,schedul:343,schema:266,scheme:[83,107],schwartzian:88,scientif:108,scope:[451,471,472],scrap:141,scratch:201,screen:403,script:[63,64,72,87,88,89,106,112,143,145,284,288,403,405,449,461,467,469,475],scroll:344,scrollabl:401,scrolledtext:344,scrolledwindow:219,sdist:63,search:[101,107,137,333,461],section:396,secur:[143,235,365,374,477],seem:87,select:[96,99,153,345,365,438],selector:394,self:[81,88,187,365],semaphor:391,send:[87,99],sent:99,separ:[81,401,473,477],sequenc:[15,47,55,88,368,374,440,453],sequencematch:180,sequenti:139,serial:[87,276,311],server:[99,106,127,132,187,284,355,357,361,365,423,434],serverproxi:434,servic:[120,141,166,230,262,264,268,285,286,329,347,362,372,375,408,421,438],set:[48,106,194,244,346,353,365,368,396,403,442,453,469,473,474],setup:[66,72,82,100,466],setupclass:407,setupmodul:407,sgi:[119,142,247,347,405],sgml:348,sgmllib:348,sha:349,shadow:363,shallow:163,shape:403,share:[88,168,185,293],sharedctyp:293,shell:[244,313,374],shelv:350,shift:442,shlex:351,shortcut:364,shot:139,should:[87,95],shouldn:465,show:88,shutil:352,side:365,sign:365,signal:[87,178,353,407],signatur:150,signific:83,simpl:[63,70,77,81,98,101,106,176,186,240,348,351,354,382,396,423,447,472,473],simple_serv:423,simplehttpserv:354,simpler:474,simplexmlrpcserv:355,simul:333,singl:[63,67,87,88,99],site:[159,356,476],size:[168,373],sizegrip:401,skip:407,slice:[49,442,473],slot:56,slow:[87,88],small:[96,393],smtp:[357,358],smtpd:357,smtphandler:267,smtplib:358,smtpserver:357,snd:141,sndhdr:359,snippet:393,soapbox:186,socket:[87,102,105,126,127,360,365,438],sockethandl:267,socketserv:361,softwar:[83,183,438,475],solari:230,solut:143,some:[81,82,106],sometim:89,sort:[81,88,103,137],sound:[141,359,422],sourc:[62,63,72,73,83,87,88,89,104,244,253,325,398,459,473],spawn:[63,374],speak:99,spec:81,special:[178,277,368,403,440,473],specif:[70,79,81,84,96,113,150,268,315,347,356,369,375,380,401,403,405,408,412,421,443,473,474,475,476,477],specifi:[73,81,88,100,168,477],speed:88,sphinx:476,split:[101,107],spwd:363,sqlite3:[364,475],sqlite:364,srpm:63,sscanf:88,ssize_t:475,ssl:[365,476],stabil:103,stabl:83,stack:[171,253,400,453],stai:100,stand:88,standard:[20,63,88,107,150,205,252,260,302,303,401,427,440,461,462,463,473],start:[1,89,93,178],startup:[244,334,449],stat:[322,366],state:[28,92,161,293,401,403],statement:[81,82,95,111,160,391,399,439,440,447,452,453,475,476],statvf:367,stderr:[82,87],stdin:87,stdlib:477,stdout:[82,87],step:[88,98,106,460],store:[212,303,364],str:[92,368],strang:81,stream:[210,256,311,317],streamhandl:267,streamread:150,streamreaderwrit:150,streamrecod:150,streamwrit:150,strftime:174,string:[16,20,50,81,87,88,101,303,333,368,369,370,371,372,373,374,413,442,446,452,457,460,462,470,473,474,476],stringio:370,stringprep:371,strptime:174,strtod:438,struct:[6,373],structur:[14,51,55,99,168,275,446,453,457],stub:227,studi:106,style:[6,63,88,121,175,228,232,387,401,440,452,475],sub:[28,63,123],subclass:[79,88,162,311,335,440],submiss:87,submit:83,subprocess:[87,244,317,374,474],subscript:442,substitut:[458,474],suggest:79,summari:290,sun:[298,376,377],sunau:376,sunaudiodev:377,suno:375,support:[13,24,28,36,44,56,79,96,100,104,116,143,148,164,230,234,247,254,284,287,292,294,319,320,326,365,384,388,428,429,430,470,473,476],suppress:416,sure:100,surpris:168,symbol:[82,205,378,379],symtabl:379,synchron:[293,330],syntax:[107,123,125,157,333,369,429,451,454,476],sys:[87,123,380],sysconfig:[63,381,477],syslog:382,sysloghandl:[99,267],system:[52,63,76,82,108,120,142,143,154,205,207,304,319,327,362,374,380,462,471],systemerror:82,tab:[89,401],tabl:[77,290,379],tabnanni:383,tabular:394,tag:401,take:89,tar:384,tarfil:384,target:477,tarinfo:384,task:87,tcl:396,tcpserver:361,teardownclass:407,teardownmodul:407,techniqu:453,tell:[82,403],telnet:385,telnetlib:385,tempfil:386,templat:[73,106,313,369,463],temporari:386,temporarili:416,term:[62,108,438],termcap:87,termin:[169,323,402,462],terminolog:[70,303],termio:387,ternari:88,test:[83,87,96,100,106,143,186,261,365,368,388,407,416,442],test_epol:438,text:[93,100,141,169,186,244,256,263,333,344,389,426],text_fil:63,textbox:169,textedit:141,textfil:63,textpad:169,textwrap:389,than:99,them:99,theme:[401,477],theoret:277,theori:236,thi:[83,88,396],thin:77,thing:101,thousand:477,thread:[28,81,87,99,178,189,190,256,265,293,390,391,463],through:[82,438],time:[87,98,99,174,392,393,462,473],timedelta:174,timedrotatingfilehandl:267,timeit:393,timer:[322,391],tip:[104,107,264],tix:394,tkinter:[84,396],togeth:303,token:[397,398,446],too:[88,451],tool:[62,87,88,179,256,275,280,312,423,452,453,463,477],toolbox:141,toolkit:84,top:[112,260,448],topic:256,touch:477,tour:[462,463],toward:460,tower:300,trace:[28,399,438],traceback:[145,400],track:399,tracker:[1,476],trail:88,transact:364,transform:88,transit:100,translat:[109,230,403],tree:[63,125,308,378,397,428,429],treebuild:429,treeview:401,tri:87,trick:107,trigger:345,trigonometr:[147,277],trivial:[107,303],truth:368,ttk:[401,477],tty:[387,402],tupl:[53,81,82,88,152,368,453],turbogear:106,turtl:403,turtlescreen:403,tutori:[83,91,98,123,168,178,303,429,456],tweak:107,twister:438,two:477,txt:341,type:[7,30,54,55,56,68,79,81,96,100,104,113,123,168,173,174,248,253,281,300,303,311,346,359,364,368,394,396,404,426,440,453,472,473,474,475,476],tzinfo:174,uac:64,udpserv:361,unadorn:95,unari:442,unboundlocalerror:88,undecor:103,undefin:82,under:[76,89],underli:315,understand:303,undocu:405,unicod:[13,20,56,92,104,150,368,384,406,460,470,472,473],unicodedata:406,unicodeerror:88,unif:92,unifi:[472,474,475],union:168,uniqu:[88,346],unit:[388,407],unittest:[186,407,477],univers:473,unix:[63,76,80,87,107,143,165,214,232,315,382,408,468],unixccompil:63,unknownhandl:410,unord:346,unpack:[424,452],unpickl:311,updat:[100,416,477],upgrad:[83,123],upload:[71,74],url:[105,409,410,411],urlerror:105,urllib2:[105,410],urllib:409,urlpars:411,urlsplit:411,usag:[108,123,186,234,238,244,260,288,311,336,399,434,466],use:[81,82,83,87,88,98,156,403,465],used:[81,119,212,231,288,367,377,378,397],useful:405,user:[64,84,93,107,108,212,266,307,322,395,412,454,476],userdict:413,userlist:413,userstr:413,using:[82,83,87,88,99,100,328,388,407,438],utc:99,utf:[56,150],utf_8_sig:150,util:[52,57,63,123,155,160,168,170,203,251,314,323,388,405,409,423,433],uudecod:438,uuencod:[414,438],uuid:415,valid:423,valu:[4,77,82,87,88,96,113,123,124,168,178,260,303,364,368,440,442,452],variabl:[88,98,115,168,303,381,396,451,465,469,477],variat:107,variou:273,verbos:101,veri:[58,76,396],verif:477,verifi:365,version:[63,69,83,100,107,108,303,365,370,416,468],versu:[100,101],via:99,videoread:405,view:[106,290,368,477],virtual:401,visibl:403,visitor:157,vista:64,vulner:425,wai:103,wait:[84,345],walk:157,want:[82,88],warn:[20,186,265,416,471,477],watchedfilehandl:267,wav:417,wave:417,wave_read:417,wave_writ:417,wchar_t:56,wconio:469,weak:[59,79,418,463,471],weakref:418,web:[106,162,419],webbrows:419,websit:106,what:[82,83,84,86,87,88,93,98,186,303,311,322,464,470,471,472,473,474,475,476,477,478],when:[81,82,88,95,98,102],where:[83,87],whet:450,which:[100,186,420],whichdb:420,whitespac:446,whole:72,why:[81,82,83,84,86,87,88,89,474],wide:28,widget:[169,344,394,396,401,405,477],wildcard:462,win95:315,win:141,window:[56,63,64,80,89,93,107,113,141,169,219,244,293,315,374,396,403,421,422,469,473,476,477],winsound:422,within:260,without:[89,244],word:451,work:[83,84,87,88,107,108,178,186,256,435,463],worker:[87,293],world:[83,396],wrap:[105,389],wrapper:[63,250,365,405,413],write:[66,72,77,82,87,88,104,118,167,259,290,370,376,384,388,417,457,475,476],writer:[167,215,264,282],written:82,wsgi:[106,423],wsgiref:[423,475],www:[83,87],wxwidget:84,xdr:424,xdrlib:424,xhtml:240,xml:[187,328,355,425,426,427,428,429,430,431,432,433,434,438,470],xmlparser:[328,429],xmlreader:432,xmlrpclib:434,xpath:429,xrang:368,yellow:298,yield:[442,447],you:[81,87,88,95,100,465],your:[75,99,100,106,143,168,230,303,364,450],yourmodul:82,yourself:1,zip:[435,436,473],zipfil:435,zipimport:436,zipinfo:435,zlib:[437,438],zope:106}})PK
%�\,U7U7html/howto/argparse.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Argparse Tutorial &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python Frequently Asked Questions" href="../faq/index.html" />
    <link rel="prev" title="HOWTO Use Python in the web" href="webservers.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/argparse.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../faq/index.html" title="Python Frequently Asked Questions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="webservers.html" title="HOWTO Use Python in the web"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="argparse-tutorial">
<h1>Argparse Tutorial<a class="headerlink" href="#argparse-tutorial" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">author:</th><td class="field-body">Tshepang Lekhonkhobe</td>
</tr>
</tbody>
</table>
<p id="id1">This tutorial is intended to be a gentle introduction to <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>, the
recommended command-line parsing module in the Python standard library.
This was written for argparse in Python 3. A few details are different in 2.x,
especially some exception messages, which were improved in 3.x.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There are two other modules that fulfill the same task, namely
<a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> (an equivalent for <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> from the C
language) and the deprecated <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>.
Note also that <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> is based on <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>,
and therefore very similar in terms of usage.</p>
</div>
<div class="section" id="concepts">
<h2>Concepts<a class="headerlink" href="#concepts" title="Permalink to this headline">¶</a></h2>
<p>Let’s show the sort of functionality that we are going to explore in this
introductory tutorial by making use of the <strong class="command">ls</strong> command:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ ls
cpython  devguide  prog.py  pypy  rm-unused-function.patch
$ ls pypy
ctypes_configure  demo  dotviewer  include  lib_pypy  lib-python ...
$ ls -l
total <span class="m">20</span>
drwxr-xr-x <span class="m">19</span> wena wena <span class="m">4096</span> Feb <span class="m">18</span> <span class="m">18</span>:51 cpython
drwxr-xr-x  <span class="m">4</span> wena wena <span class="m">4096</span> Feb  <span class="m">8</span> <span class="m">12</span>:04 devguide
-rwxr-xr-x  <span class="m">1</span> wena wena  <span class="m">535</span> Feb <span class="m">19</span> <span class="m">00</span>:05 prog.py
drwxr-xr-x <span class="m">14</span> wena wena <span class="m">4096</span> Feb  <span class="m">7</span> <span class="m">00</span>:59 pypy
-rw-r--r--  <span class="m">1</span> wena wena  <span class="m">741</span> Feb <span class="m">18</span> <span class="m">01</span>:01 rm-unused-function.patch
$ ls --help
Usage: ls <span class="o">[</span>OPTION<span class="o">]</span>... <span class="o">[</span>FILE<span class="o">]</span>...
List information about the FILEs <span class="o">(</span>the current directory by default<span class="o">)</span>.
Sort entries alphabetically <span class="k">if</span> none of -cftuvSUX nor --sort is specified.
...
</pre></div>
</div>
<p>A few concepts we can learn from the four commands:</p>
<ul class="simple">
<li>The <strong class="command">ls</strong> command is useful when run without any options at all. It defaults
to displaying the contents of the current directory.</li>
<li>If we want beyond what it provides by default, we tell it a bit more. In
this case, we want it to display a different directory, <code class="docutils literal notranslate"><span class="pre">pypy</span></code>.
What we did is specify what is known as a positional argument. It’s named so
because the program should know what to do with the value, solely based on
where it appears on the command line. This concept is more relevant
to a command like <strong class="command">cp</strong>, whose most basic usage is <code class="docutils literal notranslate"><span class="pre">cp</span> <span class="pre">SRC</span> <span class="pre">DEST</span></code>.
The first position is <em>what you want copied,</em> and the second
position is <em>where you want it copied to</em>.</li>
<li>Now, say we want to change behaviour of the program. In our example,
we display more info for each file instead of just showing the file names.
The <code class="docutils literal notranslate"><span class="pre">-l</span></code> in that case is known as an optional argument.</li>
<li>That’s a snippet of the help text. It’s very useful in that you can
come across a program you have never used before, and can figure out
how it works simply by reading its help text.</li>
</ul>
</div>
<div class="section" id="the-basics">
<h2>The basics<a class="headerlink" href="#the-basics" title="Permalink to this headline">¶</a></h2>
<p>Let us start with a very simple example which does (almost) nothing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>Following is a result of running the code:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py
$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span>

optional arguments:
  -h, --help  show this <span class="nb">help</span> message and <span class="nb">exit</span>
$ python prog.py --verbose
usage: prog.py <span class="o">[</span>-h<span class="o">]</span>
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py <span class="o">[</span>-h<span class="o">]</span>
prog.py: error: unrecognized arguments: foo
</pre></div>
</div>
<p>Here is what is happening:</p>
<ul class="simple">
<li>Running the script without any options results in nothing displayed to
stdout. Not so useful.</li>
<li>The second one starts to display the usefulness of the <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>
module. We have done almost nothing, but already we get a nice help message.</li>
<li>The <code class="docutils literal notranslate"><span class="pre">--help</span></code> option, which can also be shortened to <code class="docutils literal notranslate"><span class="pre">-h</span></code>, is the only
option we get for free (i.e. no need to specify it). Specifying anything
else results in an error. But even then, we do get a useful usage message,
also for free.</li>
</ul>
</div>
<div class="section" id="introducing-positional-arguments">
<h2>Introducing Positional arguments<a class="headerlink" href="#introducing-positional-arguments" title="Permalink to this headline">¶</a></h2>
<p>An example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;echo&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">echo</span>
</pre></div>
</div>
<p>And running the code:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="nb">echo</span>
prog.py: error: the following arguments are required: <span class="nb">echo</span>
$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="nb">echo</span>

positional arguments:
  <span class="nb">echo</span>

optional arguments:
  -h, --help  show this <span class="nb">help</span> message and <span class="nb">exit</span>
$ python prog.py foo
foo
</pre></div>
</div>
<p>Here is what’s happening:</p>
<ul class="simple">
<li>We’ve added the <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code> method, which is what we use to specify
which command-line options the program is willing to accept. In this case,
I’ve named it <code class="docutils literal notranslate"><span class="pre">echo</span></code> so that it’s in line with its function.</li>
<li>Calling our program now requires us to specify an option.</li>
<li>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> method actually returns some data from the
options specified, in this case, <code class="docutils literal notranslate"><span class="pre">echo</span></code>.</li>
<li>The variable is some form of ‘magic’ that <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> performs for free
(i.e. no need to specify which variable that value is stored in).
You will also notice that its name matches the string argument given
to the method, <code class="docutils literal notranslate"><span class="pre">echo</span></code>.</li>
</ul>
<p>Note however that, although the help display looks nice and all, it currently
is not as helpful as it can be. For example we see that we got <code class="docutils literal notranslate"><span class="pre">echo</span></code> as a
positional argument, but we don’t know what it does, other than by guessing or
by reading the source code. So, let’s make it a bit more useful:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;echo the string you use here&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">echo</span>
</pre></div>
</div>
<p>And we get:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py -h
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="nb">echo</span>

positional arguments:
  <span class="nb">echo</span>        <span class="nb">echo</span> the string you use here

optional arguments:
  -h, --help  show this <span class="nb">help</span> message and <span class="nb">exit</span>
</pre></div>
</div>
<p>Now, how about doing something even more useful:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
</pre></div>
</div>
<p>Following is a result of running the code:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span>
Traceback <span class="o">(</span>most recent call last<span class="o">)</span>:
  File <span class="s2">&quot;prog.py&quot;</span>, line <span class="m">5</span>, in &lt;module&gt;
    print args.square**2
TypeError: unsupported operand type<span class="o">(</span>s<span class="o">)</span> <span class="k">for</span> ** or pow<span class="o">()</span>: <span class="s1">&#39;str&#39;</span> and <span class="s1">&#39;int&#39;</span>
</pre></div>
</div>
<p>That didn’t go so well. That’s because <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> treats the options we
give it as strings, unless we tell it otherwise. So, let’s tell
<a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> to treat that input as an integer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">,</span>
                    <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
</pre></div>
</div>
<p>Following is a result of running the code:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span>
<span class="m">16</span>
$ python prog.py four
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> square
prog.py: error: argument square: invalid int value: <span class="s1">&#39;four&#39;</span>
</pre></div>
</div>
<p>That went well. The program now even helpfully quits on bad illegal input
before proceeding.</p>
</div>
<div class="section" id="introducing-optional-arguments">
<h2>Introducing Optional arguments<a class="headerlink" href="#introducing-optional-arguments" title="Permalink to this headline">¶</a></h2>
<p>So far we have been playing with positional arguments. Let us
have a look on how to add optional ones:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;verbosity turned on&quot;</span>
</pre></div>
</div>
<p>And the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py --verbosity <span class="m">1</span>
verbosity turned on
$ python prog.py
$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>--verbosity VERBOSITY<span class="o">]</span>

optional arguments:
  -h, --help            show this <span class="nb">help</span> message and <span class="nb">exit</span>
  --verbosity VERBOSITY
                        increase output verbosity
$ python prog.py --verbosity
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>--verbosity VERBOSITY<span class="o">]</span>
prog.py: error: argument --verbosity: expected one argument
</pre></div>
</div>
<p>Here is what is happening:</p>
<ul class="simple">
<li>The program is written so as to display something when <code class="docutils literal notranslate"><span class="pre">--verbosity</span></code> is
specified and display nothing when not.</li>
<li>To show that the option is actually optional, there is no error when running
the program without it. Note that by default, if an optional argument isn’t
used, the relevant variable, in this case <code class="xref py py-attr docutils literal notranslate"><span class="pre">args.verbosity</span></code>, is
given <code class="docutils literal notranslate"><span class="pre">None</span></code> as a value, which is the reason it fails the truth
test of the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement.</li>
<li>The help message is a bit different.</li>
<li>When using the <code class="docutils literal notranslate"><span class="pre">--verbosity</span></code> option, one must also specify some value,
any value.</li>
</ul>
<p>The above example accepts arbitrary integer values for <code class="docutils literal notranslate"><span class="pre">--verbosity</span></code>, but for
our simple program, only two values are actually useful, <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.
Let’s modify the code accordingly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;--verbose&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">,</span>
                    <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
   <span class="nb">print</span> <span class="s2">&quot;verbosity turned on&quot;</span>
</pre></div>
</div>
<p>And the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py --verbose
verbosity turned on
$ python prog.py --verbose <span class="m">1</span>
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>--verbose<span class="o">]</span>
prog.py: error: unrecognized arguments: <span class="m">1</span>
$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>--verbose<span class="o">]</span>

optional arguments:
  -h, --help  show this <span class="nb">help</span> message and <span class="nb">exit</span>
  --verbose   increase output verbosity
</pre></div>
</div>
<p>Here is what is happening:</p>
<ul class="simple">
<li>The option is now more of a flag than something that requires a value.
We even changed the name of the option to match that idea.
Note that we now specify a new keyword, <code class="docutils literal notranslate"><span class="pre">action</span></code>, and give it the value
<code class="docutils literal notranslate"><span class="pre">&quot;store_true&quot;</span></code>. This means that, if the option is specified,
assign the value <code class="docutils literal notranslate"><span class="pre">True</span></code> to <code class="xref py py-data docutils literal notranslate"><span class="pre">args.verbose</span></code>.
Not specifying it implies <code class="docutils literal notranslate"><span class="pre">False</span></code>.</li>
<li>It complains when you specify a value, in true spirit of what flags
actually are.</li>
<li>Notice the different help text.</li>
</ul>
<div class="section" id="short-options">
<h3>Short options<a class="headerlink" href="#short-options" title="Permalink to this headline">¶</a></h3>
<p>If you are familiar with command line usage,
you will notice that I haven’t yet touched on the topic of short
versions of the options. It’s quite simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">,</span>
                    <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;verbosity turned on&quot;</span>
</pre></div>
</div>
<p>And here goes:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py -v
verbosity turned on
$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span>

optional arguments:
  -h, --help     show this <span class="nb">help</span> message and <span class="nb">exit</span>
  -v, --verbose  increase output verbosity
</pre></div>
</div>
<p>Note that the new ability is also reflected in the help text.</p>
</div>
</div>
<div class="section" id="combining-positional-and-optional-arguments">
<h2>Combining Positional and Optional arguments<a class="headerlink" href="#combining-positional-and-optional-arguments" title="Permalink to this headline">¶</a></h2>
<p>Our program keeps growing in complexity:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>And now the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> square
prog.py: error: the following arguments are required: square
$ python prog.py <span class="m">4</span>
<span class="m">16</span>
$ python prog.py <span class="m">4</span> --verbose
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py --verbose <span class="m">4</span>
the square of <span class="m">4</span> equals <span class="m">16</span>
</pre></div>
</div>
<ul class="simple">
<li>We’ve brought back a positional argument, hence the complaint.</li>
<li>Note that the order does not matter.</li>
</ul>
<p>How about we give this program of ours back the ability to have
multiple verbosity values, and actually get to use them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^2 == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>And the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span>
<span class="m">16</span>
$ python prog.py <span class="m">4</span> -v
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v VERBOSITY<span class="o">]</span> square
prog.py: error: argument -v/--verbosity: expected one argument
$ python prog.py <span class="m">4</span> -v <span class="m">1</span>
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
$ python prog.py <span class="m">4</span> -v <span class="m">2</span>
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span> -v <span class="m">3</span>
<span class="m">16</span>
</pre></div>
</div>
<p>These all look good except the last one, which exposes a bug in our program.
Let’s fix it by restricting the values the <code class="docutils literal notranslate"><span class="pre">--verbosity</span></code> option can accept:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^2 == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>And the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span> -v <span class="m">3</span>
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v <span class="o">{</span><span class="m">0</span>,1,2<span class="o">}]</span> square
prog.py: error: argument -v/--verbosity: invalid choice: <span class="m">3</span> <span class="o">(</span>choose from <span class="m">0</span>, <span class="m">1</span>, <span class="m">2</span><span class="o">)</span>
$ python prog.py <span class="m">4</span> -h
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v <span class="o">{</span><span class="m">0</span>,1,2<span class="o">}]</span> square

positional arguments:
  square                display a square of a given number

optional arguments:
  -h, --help            show this <span class="nb">help</span> message and <span class="nb">exit</span>
  -v <span class="o">{</span><span class="m">0</span>,1,2<span class="o">}</span>, --verbosity <span class="o">{</span><span class="m">0</span>,1,2<span class="o">}</span>
                        increase output verbosity
</pre></div>
</div>
<p>Note that the change also reflects both in the error message as well as the
help string.</p>
<p>Now, let’s use a different approach of playing with verbosity, which is pretty
common. It also matches the way the CPython executable handles its own
verbosity argument (check the output of <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">--help</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display the square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^2 == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>We have introduced another action, “count”,
to count the number of occurrences of a specific optional arguments:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span>
<span class="m">16</span>
$ python prog.py <span class="m">4</span> -v
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
$ python prog.py <span class="m">4</span> -vv
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span> --verbosity --verbosity
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span> -v <span class="m">1</span>
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> square
prog.py: error: unrecognized arguments: <span class="m">1</span>
$ python prog.py <span class="m">4</span> -h
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> square

positional arguments:
  square           display a square of a given number

optional arguments:
  -h, --help       show this <span class="nb">help</span> message and <span class="nb">exit</span>
  -v, --verbosity  increase output verbosity
$ python prog.py <span class="m">4</span> -vvv
<span class="m">16</span>
</pre></div>
</div>
<ul class="simple">
<li>Yes, it’s now more of a flag (similar to <code class="docutils literal notranslate"><span class="pre">action=&quot;store_true&quot;</span></code>) in the
previous version of our script. That should explain the complaint.</li>
<li>It also behaves similar to “store_true” action.</li>
<li>Now here’s a demonstration of what the “count” action gives. You’ve probably
seen this sort of usage before.</li>
<li>And, just like the “store_true” action, if you don’t specify the <code class="docutils literal notranslate"><span class="pre">-v</span></code> flag,
that flag is considered to have <code class="docutils literal notranslate"><span class="pre">None</span></code> value.</li>
<li>As should be expected, specifying the long form of the flag, we should get
the same output.</li>
<li>Sadly, our help output isn’t very informative on the new ability our script
has acquired, but that can always be fixed by improving the documentation for
our script (e.g. via the <code class="docutils literal notranslate"><span class="pre">help</span></code> keyword argument).</li>
<li>That last output exposes a bug in our program.</li>
</ul>
<p>Let’s fix:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>

<span class="c1"># bugfix: replace == with &gt;=</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^2 == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>And this is what it gives:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span> -vvv
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span> -vvvv
the square of <span class="m">4</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span>
Traceback <span class="o">(</span>most recent call last<span class="o">)</span>:
  File <span class="s2">&quot;prog.py&quot;</span>, line <span class="m">11</span>, in &lt;module&gt;
    <span class="k">if</span> args.verbosity &gt;<span class="o">=</span> <span class="m">2</span>:
TypeError: unorderable types: NoneType<span class="o">()</span> &gt;<span class="o">=</span> int<span class="o">()</span>
</pre></div>
</div>
<ul class="simple">
<li>First output went well, and fixes the bug we had before.
That is, we want any value &gt;= 2 to be as verbose as possible.</li>
<li>Third output not so good.</li>
</ul>
<p>Let’s fix that bug:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;square&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;display a square of a given number&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s2">&quot;increase output verbosity&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="o">**</span><span class="mi">2</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;the square of </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^2 == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">square</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>We’ve just introduced yet another keyword, <code class="docutils literal notranslate"><span class="pre">default</span></code>.
We’ve set it to <code class="docutils literal notranslate"><span class="pre">0</span></code> in order to make it comparable to the other int values.
Remember that by default,
if an optional argument isn’t specified,
it gets the <code class="docutils literal notranslate"><span class="pre">None</span></code> value, and that cannot be compared to an int value
(hence the <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception).</p>
<p>And:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span>
<span class="m">16</span>
</pre></div>
</div>
<p>You can go quite far just with what we’ve learned so far,
and we have only scratched the surface.
The <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module is very powerful,
and we’ll explore a bit more of it before we end this tutorial.</p>
</div>
<div class="section" id="getting-a-little-more-advanced">
<h2>Getting a little more advanced<a class="headerlink" href="#getting-a-little-more-advanced" title="Permalink to this headline">¶</a></h2>
<p>What if we wanted to expand our tiny program to perform other powers,
not just squares:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the base&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the exponent&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="o">**</span><span class="n">args</span><span class="o">.</span><span class="n">y</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> to the power </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^</span><span class="si">{}</span><span class="s2"> == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> x y
prog.py: error: the following arguments are required: x, y
$ python prog.py -h
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v<span class="o">]</span> x y

positional arguments:
  x                the base
  y                the exponent

optional arguments:
  -h, --help       show this <span class="nb">help</span> message and <span class="nb">exit</span>
  -v, --verbosity
$ python prog.py <span class="m">4</span> <span class="m">2</span> -v
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
</pre></div>
</div>
<p>Notice that so far we’ve been using verbosity level to <em>change</em> the text
that gets displayed. The following example instead uses verbosity level
to display <em>more</em> text instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the base&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the exponent&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbosity&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="o">**</span><span class="n">args</span><span class="o">.</span><span class="n">y</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">2</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Running &#39;</span><span class="si">{}</span><span class="s2">&#39;&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="vm">__file__</span><span class="p">)</span>
<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">&gt;=</span> <span class="mi">1</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^</span><span class="si">{}</span><span class="s2"> ==&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">),</span>
<span class="nb">print</span> <span class="n">answer</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span> <span class="m">2</span>
<span class="m">16</span>
$ python prog.py <span class="m">4</span> <span class="m">2</span> -v
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
$ python prog.py <span class="m">4</span> <span class="m">2</span> -vv
Running <span class="s1">&#39;prog.py&#39;</span>
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
</pre></div>
</div>
<div class="section" id="conflicting-options">
<h3>Conflicting options<a class="headerlink" href="#conflicting-options" title="Permalink to this headline">¶</a></h3>
<p>So far, we have been working with two methods of an
<a class="reference internal" href="../library/argparse.html#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">argparse.ArgumentParser</span></code></a> instance. Let’s introduce a third one,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">add_mutually_exclusive_group()</span></code>. It allows for us to specify options that
conflict with each other. Let’s also change the rest of the program so that
the new functionality makes more sense:
we’ll introduce the <code class="docutils literal notranslate"><span class="pre">--quiet</span></code> option,
which will be the opposite of the <code class="docutils literal notranslate"><span class="pre">--verbose</span></code> one:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">()</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the base&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the exponent&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="o">**</span><span class="n">args</span><span class="o">.</span><span class="n">y</span>

<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">quiet</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> to the power </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^</span><span class="si">{}</span><span class="s2"> == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
</pre></div>
</div>
<p>Our program is now simpler, and we’ve lost some functionality for the sake of
demonstration. Anyways, here’s the output:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py <span class="m">4</span> <span class="m">2</span>
<span class="m">4</span>^2 <span class="o">==</span> <span class="m">16</span>
$ python prog.py <span class="m">4</span> <span class="m">2</span> -q
<span class="m">16</span>
$ python prog.py <span class="m">4</span> <span class="m">2</span> -v
<span class="m">4</span> to the power <span class="m">2</span> equals <span class="m">16</span>
$ python prog.py <span class="m">4</span> <span class="m">2</span> -vq
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v <span class="p">|</span> -q<span class="o">]</span> x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
$ python prog.py <span class="m">4</span> <span class="m">2</span> -v --quiet
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v <span class="p">|</span> -q<span class="o">]</span> x y
prog.py: error: argument -q/--quiet: not allowed with argument -v/--verbose
</pre></div>
</div>
<p>That should be easy to follow. I’ve added that last output so you can see the
sort of flexibility you get, i.e. mixing long form options with short form
ones.</p>
<p>Before we conclude, you probably want to tell your users the main purpose of
your program, just in case they don’t know:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">&quot;calculate X to the power of Y&quot;</span><span class="p">)</span>
<span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">()</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the base&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;the exponent&quot;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="n">answer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="o">**</span><span class="n">args</span><span class="o">.</span><span class="n">y</span>

<span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">quiet</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">answer</span>
<span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> to the power </span><span class="si">{}</span><span class="s2"> equals </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">^</span><span class="si">{}</span><span class="s2"> == </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">answer</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that slight difference in the usage text. Note the <code class="docutils literal notranslate"><span class="pre">[-v</span> <span class="pre">|</span> <span class="pre">-q]</span></code>,
which tells us that we can either use <code class="docutils literal notranslate"><span class="pre">-v</span></code> or <code class="docutils literal notranslate"><span class="pre">-q</span></code>,
but not both at the same time:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python prog.py --help
usage: prog.py <span class="o">[</span>-h<span class="o">]</span> <span class="o">[</span>-v <span class="p">|</span> -q<span class="o">]</span> x y

calculate X to the power of Y

positional arguments:
  x              the base
  y              the exponent

optional arguments:
  -h, --help     show this <span class="nb">help</span> message and <span class="nb">exit</span>
  -v, --verbose
  -q, --quiet
</pre></div>
</div>
</div>
</div>
<div class="section" id="conclusion">
<h2>Conclusion<a class="headerlink" href="#conclusion" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module offers a lot more than shown here.
Its docs are quite detailed and thorough, and full of examples.
Having gone through this tutorial, you should easily digest them
without feeling overwhelmed.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Argparse Tutorial</a><ul>
<li><a class="reference internal" href="#concepts">Concepts</a></li>
<li><a class="reference internal" href="#the-basics">The basics</a></li>
<li><a class="reference internal" href="#introducing-positional-arguments">Introducing Positional arguments</a></li>
<li><a class="reference internal" href="#introducing-optional-arguments">Introducing Optional arguments</a><ul>
<li><a class="reference internal" href="#short-options">Short options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#combining-positional-and-optional-arguments">Combining Positional and Optional arguments</a></li>
<li><a class="reference internal" href="#getting-a-little-more-advanced">Getting a little more advanced</a><ul>
<li><a class="reference internal" href="#conflicting-options">Conflicting options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#conclusion">Conclusion</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="webservers.html"
                        title="previous chapter">HOWTO Use Python in the web</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../faq/index.html"
                        title="next chapter">Python Frequently Asked Questions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/argparse.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../faq/index.html" title="Python Frequently Asked Questions"
             >next</a> |</li>
        <li class="right" >
          <a href="webservers.html" title="HOWTO Use Python in the web"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\^�`員��html/howto/cporting.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Porting Extension Modules to Python 3 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Curses Programming with Python" href="curses.html" />
    <link rel="prev" title="Porting Python 2 Code to Python 3" href="pyporting.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/cporting.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.html" title="Curses Programming with Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pyporting.html" title="Porting Python 2 Code to Python 3"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="porting-extension-modules-to-python-3">
<span id="cporting-howto"></span><h1>Porting Extension Modules to Python 3<a class="headerlink" href="#porting-extension-modules-to-python-3" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">author:</th><td class="field-body">Benjamin Peterson</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>Although changing the C-API was not one of Python 3’s objectives,
the many Python-level changes made leaving Python 2’s API intact
impossible.  In fact, some changes such as <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> unification are more obvious on the C level.  This
document endeavors to document incompatibilities and how they can
be worked around.</p>
</div>
<div class="section" id="conditional-compilation">
<h2>Conditional compilation<a class="headerlink" href="#conditional-compilation" title="Permalink to this headline">¶</a></h2>
<p>The easiest way to compile only some code for Python 3 is to check
if <code class="xref c c-macro docutils literal notranslate"><span class="pre">PY_MAJOR_VERSION</span></code> is greater than or equal to 3.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#if PY_MAJOR_VERSION &gt;= 3</span>
<span class="cp">#define IS_PY3K</span>
<span class="cp">#endif</span>
</pre></div>
</div>
<p>API functions that are not present can be aliased to their equivalents within
conditional blocks.</p>
</div>
<div class="section" id="changes-to-object-apis">
<h2>Changes to Object APIs<a class="headerlink" href="#changes-to-object-apis" title="Permalink to this headline">¶</a></h2>
<p>Python 3 merged together some types with similar functions while cleanly
separating others.</p>
<div class="section" id="str-unicode-unification">
<h3>str/unicode Unification<a class="headerlink" href="#str-unicode-unification" title="Permalink to this headline">¶</a></h3>
<p>Python 3’s <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> type is equivalent to Python 2’s <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a>; the C
functions are called <code class="docutils literal notranslate"><span class="pre">PyUnicode_*</span></code> for both.  The old 8-bit string type has become
<code class="xref py py-func docutils literal notranslate"><span class="pre">bytes()</span></code>, with C functions called <code class="docutils literal notranslate"><span class="pre">PyBytes_*</span></code>.  Python 2.6 and later provide a compatibility header,
<code class="file docutils literal notranslate"><span class="pre">bytesobject.h</span></code>, mapping <code class="docutils literal notranslate"><span class="pre">PyBytes</span></code> names to <code class="docutils literal notranslate"><span class="pre">PyString</span></code> ones.  For best
compatibility with Python 3, <code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicode</span></code> should be used for textual data and
<code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytes</span></code> for binary data.  It’s also important to remember that
<code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytes</span></code> and <code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicode</span></code> in Python 3 are not interchangeable like
<code class="xref c c-type docutils literal notranslate"><span class="pre">PyString</span></code> and <code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicode</span></code> are in Python 2.  The following example
shows best practices with regards to <code class="xref c c-type docutils literal notranslate"><span class="pre">PyUnicode</span></code>, <code class="xref c c-type docutils literal notranslate"><span class="pre">PyString</span></code>,
and <code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytes</span></code>.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;stdlib.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;Python.h&quot;</span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf">&quot;bytesobject.h&quot;</span><span class="cp"></span>

<span class="cm">/* text example */</span>
<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">say_hello</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">name</span><span class="p">,</span> <span class="o">*</span><span class="n">result</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;U:say_hello&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">name</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">PyUnicode_FromFormat</span><span class="p">(</span><span class="s">&quot;Hello, %S!&quot;</span><span class="p">,</span> <span class="n">name</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="cm">/* just a forward */</span>
<span class="k">static</span> <span class="kt">char</span> <span class="o">*</span> <span class="nf">do_encode</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="p">);</span>

<span class="cm">/* bytes example */</span>
<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">encode_object</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">self</span><span class="p">,</span> <span class="n">PyObject</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="p">{</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">encoded</span><span class="p">;</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">result</span><span class="p">,</span> <span class="o">*</span><span class="n">myobj</span><span class="p">;</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyArg_ParseTuple</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&quot;O:encode_object&quot;</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">myobj</span><span class="p">))</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>

    <span class="n">encoded</span> <span class="o">=</span> <span class="n">do_encode</span><span class="p">(</span><span class="n">myobj</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">encoded</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">PyBytes_FromString</span><span class="p">(</span><span class="n">encoded</span><span class="p">);</span>
    <span class="n">free</span><span class="p">(</span><span class="n">encoded</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="long-int-unification">
<h3>long/int Unification<a class="headerlink" href="#long-int-unification" title="Permalink to this headline">¶</a></h3>
<p>Python 3 has only one integer type, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>.  But it actually
corresponds to Python 2’s <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> type—the <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type
used in Python 2 was removed.  In the C-API, <code class="docutils literal notranslate"><span class="pre">PyInt_*</span></code> functions
are replaced by their <code class="docutils literal notranslate"><span class="pre">PyLong_*</span></code> equivalents.</p>
</div>
</div>
<div class="section" id="module-initialization-and-state">
<h2>Module initialization and state<a class="headerlink" href="#module-initialization-and-state" title="Permalink to this headline">¶</a></h2>
<p>Python 3 has a revamped extension module initialization system.  (See
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3121"><strong>PEP 3121</strong></a>.)  Instead of storing module state in globals, they should
be stored in an interpreter specific structure.  Creating modules that
act correctly in both Python 2 and Python 3 is tricky.  The following
simple example demonstrates how.</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#include</span> <span class="cpf">&quot;Python.h&quot;</span><span class="cp"></span>

<span class="k">struct</span> <span class="n">module_state</span> <span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">error</span><span class="p">;</span>
<span class="p">};</span>

<span class="cp">#if PY_MAJOR_VERSION &gt;= 3</span>
<span class="cp">#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))</span>
<span class="cp">#else</span>
<span class="cp">#define GETSTATE(m) (&amp;_state)</span>
<span class="k">static</span> <span class="k">struct</span> <span class="n">module_state</span> <span class="n">_state</span><span class="p">;</span>
<span class="cp">#endif</span>

<span class="k">static</span> <span class="n">PyObject</span> <span class="o">*</span>
<span class="nf">error_out</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">struct</span> <span class="n">module_state</span> <span class="o">*</span><span class="n">st</span> <span class="o">=</span> <span class="n">GETSTATE</span><span class="p">(</span><span class="n">m</span><span class="p">);</span>
    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">st</span><span class="o">-&gt;</span><span class="n">error</span><span class="p">,</span> <span class="s">&quot;something bad happened&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="n">PyMethodDef</span> <span class="n">myextension_methods</span><span class="p">[]</span> <span class="o">=</span> <span class="p">{</span>
    <span class="p">{</span><span class="s">&quot;error_out&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">PyCFunction</span><span class="p">)</span><span class="n">error_out</span><span class="p">,</span> <span class="n">METH_NOARGS</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">},</span>
    <span class="p">{</span><span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">}</span>
<span class="p">};</span>

<span class="cp">#if PY_MAJOR_VERSION &gt;= 3</span>

<span class="k">static</span> <span class="kt">int</span> <span class="nf">myextension_traverse</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">,</span> <span class="n">visitproc</span> <span class="n">visit</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">arg</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">Py_VISIT</span><span class="p">(</span><span class="n">GETSTATE</span><span class="p">(</span><span class="n">m</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">error</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">static</span> <span class="kt">int</span> <span class="nf">myextension_clear</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">m</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">Py_CLEAR</span><span class="p">(</span><span class="n">GETSTATE</span><span class="p">(</span><span class="n">m</span><span class="p">)</span><span class="o">-&gt;</span><span class="n">error</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>


<span class="k">static</span> <span class="k">struct</span> <span class="n">PyModuleDef</span> <span class="n">moduledef</span> <span class="o">=</span> <span class="p">{</span>
        <span class="n">PyModuleDef_HEAD_INIT</span><span class="p">,</span>
        <span class="s">&quot;myextension&quot;</span><span class="p">,</span>
        <span class="nb">NULL</span><span class="p">,</span>
        <span class="k">sizeof</span><span class="p">(</span><span class="k">struct</span> <span class="n">module_state</span><span class="p">),</span>
        <span class="n">myextension_methods</span><span class="p">,</span>
        <span class="nb">NULL</span><span class="p">,</span>
        <span class="n">myextension_traverse</span><span class="p">,</span>
        <span class="n">myextension_clear</span><span class="p">,</span>
        <span class="nb">NULL</span>
<span class="p">};</span>

<span class="cp">#define INITERROR return NULL</span>

<span class="n">PyMODINIT_FUNC</span>
<span class="nf">PyInit_myextension</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>

<span class="cp">#else</span>
<span class="cp">#define INITERROR return</span>

<span class="kt">void</span>
<span class="n">initmyextension</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="cp">#endif</span>
<span class="p">{</span>
<span class="cp">#if PY_MAJOR_VERSION &gt;= 3</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">module</span> <span class="o">=</span> <span class="n">PyModule_Create</span><span class="p">(</span><span class="o">&amp;</span><span class="n">moduledef</span><span class="p">);</span>
<span class="cp">#else</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">module</span> <span class="o">=</span> <span class="n">Py_InitModule</span><span class="p">(</span><span class="s">&quot;myextension&quot;</span><span class="p">,</span> <span class="n">myextension_methods</span><span class="p">);</span>
<span class="cp">#endif</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">module</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span>
        <span class="n">INITERROR</span><span class="p">;</span>
    <span class="k">struct</span> <span class="n">module_state</span> <span class="o">*</span><span class="n">st</span> <span class="o">=</span> <span class="n">GETSTATE</span><span class="p">(</span><span class="n">module</span><span class="p">);</span>

    <span class="n">st</span><span class="o">-&gt;</span><span class="n">error</span> <span class="o">=</span> <span class="n">PyErr_NewException</span><span class="p">(</span><span class="s">&quot;myextension.Error&quot;</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">,</span> <span class="nb">NULL</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">st</span><span class="o">-&gt;</span><span class="n">error</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">module</span><span class="p">);</span>
        <span class="n">INITERROR</span><span class="p">;</span>
    <span class="p">}</span>

<span class="cp">#if PY_MAJOR_VERSION &gt;= 3</span>
    <span class="k">return</span> <span class="n">module</span><span class="p">;</span>
<span class="cp">#endif</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="cobject-replaced-with-capsule">
<h2>CObject replaced with Capsule<a class="headerlink" href="#cobject-replaced-with-capsule" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref c c-type docutils literal notranslate"><span class="pre">Capsule</span></code> object was introduced in Python 3.1 and 2.7 to replace
<code class="xref c c-type docutils literal notranslate"><span class="pre">CObject</span></code>.  CObjects were useful,
but the <code class="xref c c-type docutils literal notranslate"><span class="pre">CObject</span></code> API was problematic: it didn’t permit distinguishing
between valid CObjects, which allowed mismatched CObjects to crash the
interpreter, and some of its APIs relied on undefined behavior in C.
(For further reading on the rationale behind Capsules, please see <a class="reference external" href="https://bugs.python.org/issue5630">bpo-5630</a>.)</p>
<p>If you’re currently using CObjects, and you want to migrate to 3.1 or newer,
you’ll need to switch to Capsules.
<code class="xref c c-type docutils literal notranslate"><span class="pre">CObject</span></code> was deprecated in 3.1 and 2.7 and completely removed in
Python 3.2.  If you only support 2.7, or 3.1 and above, you
can simply switch to <code class="xref c c-type docutils literal notranslate"><span class="pre">Capsule</span></code>.  If you need to support Python 3.0,
or versions of Python earlier than 2.7,
you’ll have to support both CObjects and Capsules.
(Note that Python 3.0 is no longer supported, and it is not recommended
for production use.)</p>
<p>The following example header file <code class="file docutils literal notranslate"><span class="pre">capsulethunk.h</span></code> may
solve the problem for you.  Simply write your code against the
<code class="xref c c-type docutils literal notranslate"><span class="pre">Capsule</span></code> API and include this header file after
<code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>.  Your code will automatically use Capsules
in versions of Python with Capsules, and switch to CObjects
when Capsules are unavailable.</p>
<p><code class="file docutils literal notranslate"><span class="pre">capsulethunk.h</span></code> simulates Capsules using CObjects.  However,
<code class="xref c c-type docutils literal notranslate"><span class="pre">CObject</span></code> provides no place to store the capsule’s “name”.  As a
result the simulated <code class="xref c c-type docutils literal notranslate"><span class="pre">Capsule</span></code> objects created by <code class="file docutils literal notranslate"><span class="pre">capsulethunk.h</span></code>
behave slightly differently from real Capsules.  Specifically:</p>
<blockquote>
<div><ul class="simple">
<li>The name parameter passed in to <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_New" title="PyCapsule_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_New()</span></code></a> is ignored.</li>
<li>The name parameter passed in to <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> and
<a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_GetPointer" title="PyCapsule_GetPointer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_GetPointer()</span></code></a> is ignored, and no error checking
of the name is performed.</li>
<li><a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_GetName" title="PyCapsule_GetName"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_GetName()</span></code></a> always returns NULL.</li>
<li><a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_SetName" title="PyCapsule_SetName"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_SetName()</span></code></a> always raises an exception and
returns failure.  (Since there’s no way to store a name
in a CObject, noisy failure of <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_SetName" title="PyCapsule_SetName"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_SetName()</span></code></a>
was deemed preferable to silent failure here.  If this is
inconvenient, feel free to modify your local
copy as you see fit.)</li>
</ul>
</div></blockquote>
<p>You can find <code class="file docutils literal notranslate"><span class="pre">capsulethunk.h</span></code> in the Python source distribution
as <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Doc/includes/capsulethunk.h">Doc/includes/capsulethunk.h</a>.  We also include it here for
your convenience:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="cp">#ifndef __CAPSULETHUNK_H</span>
<span class="cp">#define __CAPSULETHUNK_H</span>

<span class="cp">#if (    (PY_VERSION_HEX &lt;  0x02070000) \</span>
<span class="cp">     || ((PY_VERSION_HEX &gt;= 0x03000000) \</span>
<span class="cp">      &amp;&amp; (PY_VERSION_HEX &lt;  0x03010000)) )</span>

<span class="cp">#define __PyCapsule_GetField(capsule, field, default_value) \</span>
<span class="cp">    ( PyCapsule_CheckExact(capsule) \</span>
<span class="cp">        ? (((PyCObject *)capsule)-&gt;field) \</span>
<span class="cp">        : (default_value) \</span>
<span class="cp">    ) \</span>

<span class="cp">#define __PyCapsule_SetField(capsule, field, value) \</span>
<span class="cp">    ( PyCapsule_CheckExact(capsule) \</span>
<span class="cp">        ? (((PyCObject *)capsule)-&gt;field = value), 1 \</span>
<span class="cp">        : 0 \</span>
<span class="cp">    ) \</span>


<span class="cp">#define PyCapsule_Type PyCObject_Type</span>

<span class="cp">#define PyCapsule_CheckExact(capsule) (PyCObject_Check(capsule))</span>
<span class="cp">#define PyCapsule_IsValid(capsule, name) (PyCObject_Check(capsule))</span>


<span class="cp">#define PyCapsule_New(pointer, name, destructor) \</span>
<span class="cp">    (PyCObject_FromVoidPtr(pointer, destructor))</span>


<span class="cp">#define PyCapsule_GetPointer(capsule, name) \</span>
<span class="cp">    (PyCObject_AsVoidPtr(capsule))</span>

<span class="cm">/* Don&#39;t call PyCObject_SetPointer here, it fails if there&#39;s a destructor */</span>
<span class="cp">#define PyCapsule_SetPointer(capsule, pointer) \</span>
<span class="cp">    __PyCapsule_SetField(capsule, cobject, pointer)</span>


<span class="cp">#define PyCapsule_GetDestructor(capsule) \</span>
<span class="cp">    __PyCapsule_GetField(capsule, destructor)</span>

<span class="cp">#define PyCapsule_SetDestructor(capsule, dtor) \</span>
<span class="cp">    __PyCapsule_SetField(capsule, destructor, dtor)</span>


<span class="cm">/*</span>
<span class="cm"> * Sorry, there&#39;s simply no place</span>
<span class="cm"> * to store a Capsule &quot;name&quot; in a CObject.</span>
<span class="cm"> */</span>
<span class="cp">#define PyCapsule_GetName(capsule) NULL</span>

<span class="k">static</span> <span class="kt">int</span>
<span class="nf">PyCapsule_SetName</span><span class="p">(</span><span class="n">PyObject</span> <span class="o">*</span><span class="n">capsule</span><span class="p">,</span> <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">unused</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">unused</span> <span class="o">=</span> <span class="n">unused</span><span class="p">;</span>
    <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_NotImplementedError</span><span class="p">,</span>
        <span class="s">&quot;can&#39;t use PyCapsule_SetName with CObjects&quot;</span><span class="p">);</span>
    <span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>



<span class="cp">#define PyCapsule_GetContext(capsule) \</span>
<span class="cp">    __PyCapsule_GetField(capsule, descr)</span>

<span class="cp">#define PyCapsule_SetContext(capsule, context) \</span>
<span class="cp">    __PyCapsule_SetField(capsule, descr, context)</span>


<span class="k">static</span> <span class="kt">void</span> <span class="o">*</span>
<span class="nf">PyCapsule_Import</span><span class="p">(</span><span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">name</span><span class="p">,</span> <span class="kt">int</span> <span class="n">no_block</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">PyObject</span> <span class="o">*</span><span class="n">object</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="kt">void</span> <span class="o">*</span><span class="n">return_value</span> <span class="o">=</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">trace</span><span class="p">;</span>
    <span class="kt">size_t</span> <span class="n">name_length</span> <span class="o">=</span> <span class="p">(</span><span class="n">strlen</span><span class="p">(</span><span class="n">name</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="k">sizeof</span><span class="p">(</span><span class="kt">char</span><span class="p">);</span>
    <span class="kt">char</span> <span class="o">*</span><span class="n">name_dup</span> <span class="o">=</span> <span class="p">(</span><span class="kt">char</span> <span class="o">*</span><span class="p">)</span><span class="n">PyMem_MALLOC</span><span class="p">(</span><span class="n">name_length</span><span class="p">);</span>

    <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">name_dup</span><span class="p">)</span> <span class="p">{</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="n">memcpy</span><span class="p">(</span><span class="n">name_dup</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">name_length</span><span class="p">);</span>

    <span class="n">trace</span> <span class="o">=</span> <span class="n">name_dup</span><span class="p">;</span>
    <span class="k">while</span> <span class="p">(</span><span class="n">trace</span><span class="p">)</span> <span class="p">{</span>
        <span class="kt">char</span> <span class="o">*</span><span class="n">dot</span> <span class="o">=</span> <span class="n">strchr</span><span class="p">(</span><span class="n">trace</span><span class="p">,</span> <span class="sc">&#39;.&#39;</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">dot</span><span class="p">)</span> <span class="p">{</span>
            <span class="o">*</span><span class="n">dot</span><span class="o">++</span> <span class="o">=</span> <span class="sc">&#39;\0&#39;</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="k">if</span> <span class="p">(</span><span class="n">object</span> <span class="o">==</span> <span class="nb">NULL</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">no_block</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">object</span> <span class="o">=</span> <span class="n">PyImport_ImportModuleNoBlock</span><span class="p">(</span><span class="n">trace</span><span class="p">);</span>
            <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
                <span class="n">object</span> <span class="o">=</span> <span class="n">PyImport_ImportModule</span><span class="p">(</span><span class="n">trace</span><span class="p">);</span>
                <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">object</span><span class="p">)</span> <span class="p">{</span>
                    <span class="n">PyErr_Format</span><span class="p">(</span><span class="n">PyExc_ImportError</span><span class="p">,</span>
                        <span class="s">&quot;PyCapsule_Import could not &quot;</span>
                        <span class="s">&quot;import module </span><span class="se">\&quot;</span><span class="s">%s</span><span class="se">\&quot;</span><span class="s">&quot;</span><span class="p">,</span> <span class="n">trace</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>
        <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
            <span class="n">PyObject</span> <span class="o">*</span><span class="n">object2</span> <span class="o">=</span> <span class="n">PyObject_GetAttrString</span><span class="p">(</span><span class="n">object</span><span class="p">,</span> <span class="n">trace</span><span class="p">);</span>
            <span class="n">Py_DECREF</span><span class="p">(</span><span class="n">object</span><span class="p">);</span>
            <span class="n">object</span> <span class="o">=</span> <span class="n">object2</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">object</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">goto</span> <span class="n">EXIT</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">trace</span> <span class="o">=</span> <span class="n">dot</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">if</span> <span class="p">(</span><span class="n">PyCObject_Check</span><span class="p">(</span><span class="n">object</span><span class="p">))</span> <span class="p">{</span>
        <span class="n">PyCObject</span> <span class="o">*</span><span class="n">cobject</span> <span class="o">=</span> <span class="p">(</span><span class="n">PyCObject</span> <span class="o">*</span><span class="p">)</span><span class="n">object</span><span class="p">;</span>
        <span class="n">return_value</span> <span class="o">=</span> <span class="n">cobject</span><span class="o">-&gt;</span><span class="n">cobject</span><span class="p">;</span>
    <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
        <span class="n">PyErr_Format</span><span class="p">(</span><span class="n">PyExc_AttributeError</span><span class="p">,</span>
            <span class="s">&quot;PyCapsule_Import </span><span class="se">\&quot;</span><span class="s">%s</span><span class="se">\&quot;</span><span class="s"> is not valid&quot;</span><span class="p">,</span>
            <span class="n">name</span><span class="p">);</span>
    <span class="p">}</span>

<span class="nl">EXIT</span><span class="p">:</span>
    <span class="n">Py_XDECREF</span><span class="p">(</span><span class="n">object</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">name_dup</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyMem_FREE</span><span class="p">(</span><span class="n">name_dup</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="n">return_value</span><span class="p">;</span>
<span class="p">}</span>

<span class="cp">#endif </span><span class="cm">/* #if PY_VERSION_HEX &lt; 0x02070000 */</span><span class="cp"></span>

<span class="cp">#endif </span><span class="cm">/* __CAPSULETHUNK_H */</span><span class="cp"></span>
</pre></div>
</div>
</div>
<div class="section" id="other-options">
<h2>Other options<a class="headerlink" href="#other-options" title="Permalink to this headline">¶</a></h2>
<p>If you are writing a new extension module, you might consider <a class="reference external" href="http://cython.org/">Cython</a>.  It translates a Python-like language to C.  The
extension modules it creates are compatible with Python 3 and Python 2.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Porting Extension Modules to Python 3</a><ul>
<li><a class="reference internal" href="#conditional-compilation">Conditional compilation</a></li>
<li><a class="reference internal" href="#changes-to-object-apis">Changes to Object APIs</a><ul>
<li><a class="reference internal" href="#str-unicode-unification">str/unicode Unification</a></li>
<li><a class="reference internal" href="#long-int-unification">long/int Unification</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-initialization-and-state">Module initialization and state</a></li>
<li><a class="reference internal" href="#cobject-replaced-with-capsule">CObject replaced with Capsule</a></li>
<li><a class="reference internal" href="#other-options">Other options</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pyporting.html"
                        title="previous chapter">Porting Python 2 Code to Python 3</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="curses.html"
                        title="next chapter">Curses Programming with Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/cporting.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.html" title="Curses Programming with Python"
             >next</a> |</li>
        <li class="right" >
          <a href="pyporting.html" title="Porting Python 2 Code to Python 3"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��ͰͰhtml/howto/curses.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Curses Programming with Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Descriptor HowTo Guide" href="descriptor.html" />
    <link rel="prev" title="Porting Extension Modules to Python 3" href="cporting.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/curses.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="curses-programming-with-python">
<span id="curses-howto"></span><h1>Curses Programming with Python<a class="headerlink" href="#curses-programming-with-python" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling, Eric S. Raymond</td>
</tr>
<tr class="field-even field"><th class="field-name">Release:</th><td class="field-body">2.03</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document describes how to write text-mode programs with Python 2.x, using
the <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> extension module to control the display.</p>
</div>
<div class="section" id="what-is-curses">
<h2>What is curses?<a class="headerlink" href="#what-is-curses" title="Permalink to this headline">¶</a></h2>
<p>The curses library supplies a terminal-independent screen-painting and
keyboard-handling facility for text-based terminals; such terminals include
VT100s, the Linux console, and the simulated terminal provided by X11 programs
such as xterm and rxvt.  Display terminals support various control codes to
perform common operations such as moving the cursor, scrolling the screen, and
erasing areas.  Different terminals use widely differing codes, and often have
their own minor quirks.</p>
<p>In a world of X displays, one might ask “why bother”?  It’s true that
character-cell display terminals are an obsolete technology, but there are
niches in which being able to do fancy things with them are still valuable.  One
is on small-footprint or embedded Unixes that don’t carry an X server.  Another
is for tools like OS installers and kernel configurators that may have to run
before X is available.</p>
<p>The curses library hides all the details of different terminals, and provides
the programmer with an abstraction of a display, containing multiple
non-overlapping windows.  The contents of a window can be changed in various
ways—adding text, erasing it, changing its appearance—and the curses library
will automagically figure out what control codes need to be sent to the terminal
to produce the right output.</p>
<p>The curses library was originally written for BSD Unix; the later System V
versions of Unix from AT&amp;T added many enhancements and new functions. BSD curses
is no longer maintained, having been replaced by ncurses, which is an
open-source implementation of the AT&amp;T interface.  If you’re using an
open-source Unix such as Linux or FreeBSD, your system almost certainly uses
ncurses.  Since most current commercial Unix versions are based on System V
code, all the functions described here will probably be available.  The older
versions of curses carried by some proprietary Unixes may not support
everything, though.</p>
<p>No one has made a Windows port of the curses module.  On a Windows platform, try
the Console module written by Fredrik Lundh.  The Console module provides
cursor-addressable text output, plus full support for mouse and keyboard input,
and is available from <a class="reference external" href="http://effbot.org/zone/console-index.htm">http://effbot.org/zone/console-index.htm</a>.</p>
<div class="section" id="the-python-curses-module">
<h3>The Python curses module<a class="headerlink" href="#the-python-curses-module" title="Permalink to this headline">¶</a></h3>
<p>Thy Python module is a fairly simple wrapper over the C functions provided by
curses; if you’re already familiar with curses programming in C, it’s really
easy to transfer that knowledge to Python.  The biggest difference is that the
Python interface makes things simpler, by merging different C functions such as
<code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">mvaddstr()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">mvwaddstr()</span></code>, into a single
<code class="xref py py-meth docutils literal notranslate"><span class="pre">addstr()</span></code> method.  You’ll see this covered in more detail later.</p>
<p>This HOWTO is simply an introduction to writing text-mode programs with curses
and Python. It doesn’t attempt to be a complete guide to the curses API; for
that, see the Python library guide’s section on ncurses, and the C manual pages
for ncurses.  It will, however, give you the basic ideas.</p>
</div>
</div>
<div class="section" id="starting-and-ending-a-curses-application">
<h2>Starting and ending a curses application<a class="headerlink" href="#starting-and-ending-a-curses-application" title="Permalink to this headline">¶</a></h2>
<p>Before doing anything, curses must be initialized.  This is done by calling the
<code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> function, which will determine the terminal type, send any
required setup codes to the terminal, and create various internal data
structures.  If successful, <code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> returns a window object representing
the entire screen; this is usually called <code class="docutils literal notranslate"><span class="pre">stdscr</span></code>, after the name of the
corresponding C variable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">curses</span>
<span class="n">stdscr</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">initscr</span><span class="p">()</span>
</pre></div>
</div>
<p>Usually curses applications turn off automatic echoing of keys to the screen, in
order to be able to read keys and only display them under certain circumstances.
This requires calling the <code class="xref py py-func docutils literal notranslate"><span class="pre">noecho()</span></code> function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">noecho</span><span class="p">()</span>
</pre></div>
</div>
<p>Applications will also commonly need to react to keys instantly, without
requiring the Enter key to be pressed; this is called cbreak mode, as opposed to
the usual buffered input mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">cbreak</span><span class="p">()</span>
</pre></div>
</div>
<p>Terminals usually return special keys, such as the cursor keys or navigation
keys such as Page Up and Home, as a multibyte escape sequence.  While you could
write your application to expect such sequences and process them accordingly,
curses can do it for you, returning a special value such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_LEFT</span></code>.  To get curses to do the job, you’ll have to enable
keypad mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">keypad</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Terminating a curses application is much easier than starting one. You’ll need
to call</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">nocbreak</span><span class="p">();</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">keypad</span><span class="p">(</span><span class="mi">0</span><span class="p">);</span> <span class="n">curses</span><span class="o">.</span><span class="n">echo</span><span class="p">()</span>
</pre></div>
</div>
<p>to reverse the curses-friendly terminal settings. Then call the <code class="xref py py-func docutils literal notranslate"><span class="pre">endwin()</span></code>
function to restore the terminal to its original operating mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">endwin</span><span class="p">()</span>
</pre></div>
</div>
<p>A common problem when debugging a curses application is to get your terminal
messed up when the application dies without restoring the terminal to its
previous state.  In Python this commonly happens when your code is buggy and
raises an uncaught exception.  Keys are no longer echoed to the screen when
you type them, for example, which makes using the shell difficult.</p>
<p>In Python you can avoid these complications and make debugging much easier by
importing the <a class="reference internal" href="../library/curses.html#curses.wrapper" title="curses.wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">curses.wrapper()</span></code></a> function.  It takes a callable and does
the initializations described above, also initializing colors if color support
is present.  It then runs your provided callable and finally deinitializes
appropriately.  The callable is called inside a try-catch clause which catches
exceptions, performs curses deinitialization, and then passes the exception
upwards.  Thus, your terminal won’t be left in a funny state on exception.</p>
</div>
<div class="section" id="windows-and-pads">
<h2>Windows and Pads<a class="headerlink" href="#windows-and-pads" title="Permalink to this headline">¶</a></h2>
<p>Windows are the basic abstraction in curses.  A window object represents a
rectangular area of the screen, and supports various methods to display text,
erase it, allow the user to input strings, and so forth.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> object returned by the <code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code> function is a window
object that covers the entire screen.  Many programs may need only this single
window, but you might wish to divide the screen into smaller windows, in order
to redraw or clear them separately. The <code class="xref py py-func docutils literal notranslate"><span class="pre">newwin()</span></code> function creates a new
window of a given size, returning the new window object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">begin_x</span> <span class="o">=</span> <span class="mi">20</span><span class="p">;</span> <span class="n">begin_y</span> <span class="o">=</span> <span class="mi">7</span>
<span class="n">height</span> <span class="o">=</span> <span class="mi">5</span><span class="p">;</span> <span class="n">width</span> <span class="o">=</span> <span class="mi">40</span>
<span class="n">win</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">newwin</span><span class="p">(</span><span class="n">height</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">begin_y</span><span class="p">,</span> <span class="n">begin_x</span><span class="p">)</span>
</pre></div>
</div>
<p>A word about the coordinate system used in curses: coordinates are always passed
in the order <em>y,x</em>, and the top-left corner of a window is coordinate (0,0).
This breaks a common convention for handling coordinates, where the <em>x</em>
coordinate usually comes first.  This is an unfortunate difference from most
other computer applications, but it’s been part of curses since it was first
written, and it’s too late to change things now.</p>
<p>When you call a method to display or erase text, the effect doesn’t immediately
show up on the display.  This is because curses was originally written with slow
300-baud terminal connections in mind; with these terminals, minimizing the time
required to redraw the screen is very important.  This lets curses accumulate
changes to the screen, and display them in the most efficient manner.  For
example, if your program displays some characters in a window, and then clears
the window, there’s no need to send the original characters because they’d never
be visible.</p>
<p>Accordingly, curses requires that you explicitly tell it to redraw windows,
using the <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> method of window objects.  In practice, this doesn’t
really complicate programming with curses much. Most programs go into a flurry
of activity, and then pause waiting for a keypress or some other action on the
part of the user.  All you have to do is to be sure that the screen has been
redrawn before pausing to wait for user input, by simply calling
<code class="docutils literal notranslate"><span class="pre">stdscr.refresh()</span></code> or the <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> method of some other relevant
window.</p>
<p>A pad is a special case of a window; it can be larger than the actual display
screen, and only a portion of it displayed at a time. Creating a pad simply
requires the pad’s height and width, while refreshing a pad requires giving the
coordinates of the on-screen area where a subsection of the pad will be
displayed.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pad</span> <span class="o">=</span> <span class="n">curses</span><span class="o">.</span><span class="n">newpad</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="c1">#  These loops fill the pad with letters; this is</span>
<span class="c1"># explained in the next section</span>
<span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">pad</span><span class="o">.</span><span class="n">addch</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="n">x</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">*</span><span class="n">y</span><span class="p">)</span> <span class="o">%</span> <span class="mi">26</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">curses</span><span class="o">.</span><span class="n">error</span><span class="p">:</span>
            <span class="k">pass</span>

<span class="c1">#  Displays a section of the pad in the middle of the screen</span>
<span class="n">pad</span><span class="o">.</span><span class="n">refresh</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span><span class="mi">75</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">refresh()</span></code> call displays a section of the pad in the rectangle
extending from coordinate (5,5) to coordinate (20,75) on the screen; the upper
left corner of the displayed section is coordinate (0,0) on the pad.  Beyond
that difference, pads are exactly like ordinary windows and support the same
methods.</p>
<p>If you have multiple windows and pads on screen there is a more efficient way to
go, which will prevent annoying screen flicker at refresh time.  Use the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code> method of each window to update the data structure
representing the desired state of the screen; then change the physical screen to
match the desired state in one go with the function <code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code>.  The
normal <code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code> method calls <code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code> as its last act.</p>
</div>
<div class="section" id="displaying-text">
<h2>Displaying Text<a class="headerlink" href="#displaying-text" title="Permalink to this headline">¶</a></h2>
<p>From a C programmer’s point of view, curses may sometimes look like a twisty
maze of functions, all subtly different.  For example, <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> displays a
string at the current cursor location in the <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> window, while
<code class="xref py py-func docutils literal notranslate"><span class="pre">mvaddstr()</span></code> moves to a given y,x coordinate first before displaying the
string. <code class="xref py py-func docutils literal notranslate"><span class="pre">waddstr()</span></code> is just like <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code>, but allows specifying a
window to use, instead of using <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> by default. <code class="xref py py-func docutils literal notranslate"><span class="pre">mvwaddstr()</span></code> follows
similarly.</p>
<p>Fortunately the Python interface hides all these details; <code class="docutils literal notranslate"><span class="pre">stdscr</span></code> is a window
object like any other, and methods like <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> accept multiple argument
forms.  Usually there are four different forms.</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Form</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>str</em> or <em>ch</em></td>
<td>Display the string <em>str</em> or character <em>ch</em> at
the current position</td>
</tr>
<tr class="row-odd"><td><em>str</em> or <em>ch</em>, <em>attr</em></td>
<td>Display the string <em>str</em> or character <em>ch</em>,
using attribute <em>attr</em> at the current
position</td>
</tr>
<tr class="row-even"><td><em>y</em>, <em>x</em>, <em>str</em> or <em>ch</em></td>
<td>Move to position <em>y,x</em> within the window, and
display <em>str</em> or <em>ch</em></td>
</tr>
<tr class="row-odd"><td><em>y</em>, <em>x</em>, <em>str</em> or <em>ch</em>, <em>attr</em></td>
<td>Move to position <em>y,x</em> within the window, and
display <em>str</em> or <em>ch</em>, using attribute <em>attr</em></td>
</tr>
</tbody>
</table>
<p>Attributes allow displaying text in highlighted forms, such as in boldface,
underline, reverse code, or in color.  They’ll be explained in more detail in
the next subsection.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">addstr()</span></code> function takes a Python string as the value to be displayed,
while the <code class="xref py py-func docutils literal notranslate"><span class="pre">addch()</span></code> functions take a character, which can be either a Python
string of length 1 or an integer.  If it’s a string, you’re limited to
displaying characters between 0 and 255.  SVr4 curses provides constants for
extension characters; these constants are integers greater than 255.  For
example, <code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_PLMINUS</span></code> is a +/- symbol, and <code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_ULCORNER</span></code> is the
upper left corner of a box (handy for drawing borders).</p>
<p>Windows remember where the cursor was left after the last operation, so if you
leave out the <em>y,x</em> coordinates, the string or character will be displayed
wherever the last operation left off.  You can also move the cursor with the
<code class="docutils literal notranslate"><span class="pre">move(y,x)</span></code> method.  Because some terminals always display a flashing cursor,
you may want to ensure that the cursor is positioned in some location where it
won’t be distracting; it can be confusing to have the cursor blinking at some
apparently random location.</p>
<p>If your application doesn’t need a blinking cursor at all, you can call
<code class="docutils literal notranslate"><span class="pre">curs_set(0)</span></code> to make it invisible.  Equivalently, and for compatibility with
older curses versions, there’s a <code class="docutils literal notranslate"><span class="pre">leaveok(bool)</span></code> function.  When <em>bool</em> is
true, the curses library will attempt to suppress the flashing cursor, and you
won’t need to worry about leaving it in odd locations.</p>
<div class="section" id="attributes-and-color">
<h3>Attributes and Color<a class="headerlink" href="#attributes-and-color" title="Permalink to this headline">¶</a></h3>
<p>Characters can be displayed in different ways.  Status lines in a text-based
application are commonly shown in reverse video; a text viewer may need to
highlight certain words.  curses supports this by allowing you to specify an
attribute for each cell on the screen.</p>
<p>An attribute is an integer, each bit representing a different attribute.  You can
try to display text with multiple attribute bits set, but curses doesn’t
guarantee that all the possible combinations are available, or that they’re all
visually distinct.  That depends on the ability of the terminal being used, so
it’s safest to stick to the most commonly available attributes, listed here.</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_BLINK</span></code></td>
<td>Blinking text</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_BOLD</span></code></td>
<td>Extra bright or bold text</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_DIM</span></code></td>
<td>Half bright text</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_REVERSE</span></code></td>
<td>Reverse-video text</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_STANDOUT</span></code></td>
<td>The best highlighting mode available</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">A_UNDERLINE</span></code></td>
<td>Underlined text</td>
</tr>
</tbody>
</table>
<p>So, to display a reverse-video status line on the top line of the screen, you
could code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;Current mode: Typing mode&quot;</span><span class="p">,</span>
              <span class="n">curses</span><span class="o">.</span><span class="n">A_REVERSE</span><span class="p">)</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">refresh</span><span class="p">()</span>
</pre></div>
</div>
<p>The curses library also supports color on those terminals that provide it. The
most common such terminal is probably the Linux console, followed by color
xterms.</p>
<p>To use color, you must call the <code class="xref py py-func docutils literal notranslate"><span class="pre">start_color()</span></code> function soon after calling
<code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code>, to initialize the default color set (the
<code class="xref py py-func docutils literal notranslate"><span class="pre">curses.wrapper.wrapper()</span></code> function does this automatically).  Once that’s
done, the <code class="xref py py-func docutils literal notranslate"><span class="pre">has_colors()</span></code> function returns TRUE if the terminal in use can
actually display color.  (Note: curses uses the American spelling ‘color’,
instead of the Canadian/British spelling ‘colour’.  If you’re used to the
British spelling, you’ll have to resign yourself to misspelling it for the sake
of these functions.)</p>
<p>The curses library maintains a finite number of color pairs, containing a
foreground (or text) color and a background color.  You can get the attribute
value corresponding to a color pair with the <code class="xref py py-func docutils literal notranslate"><span class="pre">color_pair()</span></code> function; this
can be bitwise-OR’ed with other attributes such as <code class="xref py py-const docutils literal notranslate"><span class="pre">A_REVERSE</span></code>, but
again, such combinations are not guaranteed to work on all terminals.</p>
<p>An example, which displays a line of text using color pair 1:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="s2">&quot;Pretty text&quot;</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">color_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">refresh</span><span class="p">()</span>
</pre></div>
</div>
<p>As I said before, a color pair consists of a foreground and background color.
<code class="xref py py-func docutils literal notranslate"><span class="pre">start_color()</span></code> initializes 8 basic colors when it activates color mode.
They are: 0:black, 1:red, 2:green, 3:yellow, 4:blue, 5:magenta, 6:cyan, and
7:white.  The curses module defines named constants for each of these colors:
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.COLOR_BLACK</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.COLOR_RED</span></code>, and so forth.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">init_pair(n,</span> <span class="pre">f,</span> <span class="pre">b)</span></code> function changes the definition of color pair <em>n</em>, to
foreground color f and background color b.  Color pair 0 is hard-wired to white
on black, and cannot be changed.</p>
<p>Let’s put all this together. To change color 1 to red text on a white
background, you would call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">init_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">COLOR_RED</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">COLOR_WHITE</span><span class="p">)</span>
</pre></div>
</div>
<p>When you change a color pair, any text already displayed using that color pair
will change to the new colors.  You can also display new text in this color
with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stdscr</span><span class="o">.</span><span class="n">addstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;RED ALERT!&quot;</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">color_pair</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
</pre></div>
</div>
<p>Very fancy terminals can change the definitions of the actual colors to a given
RGB value.  This lets you change color 1, which is usually red, to purple or
blue or any other color you like.  Unfortunately, the Linux console doesn’t
support this, so I’m unable to try it out, and can’t provide any examples.  You
can check if your terminal can do this by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">can_change_color()</span></code>,
which returns TRUE if the capability is there.  If you’re lucky enough to have
such a talented terminal, consult your system’s man pages for more information.</p>
</div>
</div>
<div class="section" id="user-input">
<h2>User Input<a class="headerlink" href="#user-input" title="Permalink to this headline">¶</a></h2>
<p>The curses library itself offers only very simple input mechanisms. Python’s
support adds a text-input widget that makes up some of the lack.</p>
<p>The most common way to get input to a window is to use its <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> method.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> pauses and waits for the user to hit a key, displaying it if
<code class="xref py py-func docutils literal notranslate"><span class="pre">echo()</span></code> has been called earlier.  You can optionally specify a coordinate
to which the cursor should be moved before pausing.</p>
<p>It’s possible to change this behavior with the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">nodelay()</span></code>. After
<code class="docutils literal notranslate"><span class="pre">nodelay(1)</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> for the window becomes non-blocking and returns
<code class="docutils literal notranslate"><span class="pre">curses.ERR</span></code> (a value of -1) when no input is ready.  There’s also a
<code class="xref py py-func docutils literal notranslate"><span class="pre">halfdelay()</span></code> function, which can be used to (in effect) set a timer on each
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code>; if no input becomes available within a specified
delay (measured in tenths of a second), curses raises an exception.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> method returns an integer; if it’s between 0 and 255, it
represents the ASCII code of the key pressed.  Values greater than 255 are
special keys such as Page Up, Home, or the cursor keys. You can compare the
value returned to constants such as <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_PPAGE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_HOME</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">curses.KEY_LEFT</span></code>.  Usually the main loop of
your program will look something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">c</span> <span class="o">=</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">getch</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">c</span> <span class="o">==</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;p&#39;</span><span class="p">):</span>
        <span class="n">PrintDocument</span><span class="p">()</span>
    <span class="k">elif</span> <span class="n">c</span> <span class="o">==</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;q&#39;</span><span class="p">):</span>
        <span class="k">break</span>  <span class="c1"># Exit the while()</span>
    <span class="k">elif</span> <span class="n">c</span> <span class="o">==</span> <span class="n">curses</span><span class="o">.</span><span class="n">KEY_HOME</span><span class="p">:</span>
        <span class="n">x</span> <span class="o">=</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">0</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/curses.ascii.html#module-curses.ascii" title="curses.ascii: Constants and set-membership functions for ASCII characters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.ascii</span></code></a> module supplies ASCII class membership functions that
take either integer or 1-character-string arguments; these may be useful in
writing more readable tests for your command interpreters.  It also supplies
conversion functions  that take either integer or 1-character-string arguments
and return the same type.  For example, <a class="reference internal" href="../library/curses.ascii.html#curses.ascii.ctrl" title="curses.ascii.ctrl"><code class="xref py py-func docutils literal notranslate"><span class="pre">curses.ascii.ctrl()</span></code></a> returns the
control character corresponding to its argument.</p>
<p>There’s also a method to retrieve an entire string, <code class="xref py py-const docutils literal notranslate"><span class="pre">getstr()</span></code>.  It isn’t
used very often, because its functionality is quite limited; the only editing
keys available are the backspace key and the Enter key, which terminates the
string.  It can optionally be limited to a fixed number of characters.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">curses</span><span class="o">.</span><span class="n">echo</span><span class="p">()</span>            <span class="c1"># Enable echoing of characters</span>

<span class="c1"># Get a 15-character string, with the cursor on the top line</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">stdscr</span><span class="o">.</span><span class="n">getstr</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span> <span class="mi">15</span><span class="p">)</span>
</pre></div>
</div>
<p>The Python <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module supplies something better. With it, you
can turn a window into a text box that supports an Emacs-like set of
keybindings.  Various methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> class support editing with
input validation and gathering the edit results either with or without trailing
spaces.   See the library documentation on <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> for the
details.</p>
</div>
<div class="section" id="for-more-information">
<h2>For More Information<a class="headerlink" href="#for-more-information" title="Permalink to this headline">¶</a></h2>
<p>This HOWTO didn’t cover some advanced topics, such as screen-scraping or
capturing mouse events from an xterm instance.  But the Python library page for
the curses modules is now pretty complete.  You should browse it next.</p>
<p>If you’re in doubt about the detailed behavior of any of the ncurses entry
points, consult the manual pages for your curses implementation, whether it’s
ncurses or a proprietary Unix vendor’s.  The manual pages will document any
quirks, and provide complete lists of all the functions, attributes, and
<code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_*</span></code> characters available to you.</p>
<p>Because the curses API is so large, some functions aren’t supported in the
Python interface, not because they’re difficult to implement, but because no one
has needed them yet.  Feel free to add them and then submit a patch.  Also, we
don’t yet have support for the menu library associated with
ncurses; feel free to add that.</p>
<p>If you write an interesting little program, feel free to contribute it as
another demo.  We can always use more of them!</p>
<p>The ncurses FAQ: <a class="reference external" href="http://invisible-island.net/ncurses/ncurses.faq.html">http://invisible-island.net/ncurses/ncurses.faq.html</a></p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Curses Programming with Python</a><ul>
<li><a class="reference internal" href="#what-is-curses">What is curses?</a><ul>
<li><a class="reference internal" href="#the-python-curses-module">The Python curses module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#starting-and-ending-a-curses-application">Starting and ending a curses application</a></li>
<li><a class="reference internal" href="#windows-and-pads">Windows and Pads</a></li>
<li><a class="reference internal" href="#displaying-text">Displaying Text</a><ul>
<li><a class="reference internal" href="#attributes-and-color">Attributes and Color</a></li>
</ul>
</li>
<li><a class="reference internal" href="#user-input">User Input</a></li>
<li><a class="reference internal" href="#for-more-information">For More Information</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cporting.html"
                        title="previous chapter">Porting Extension Modules to Python 3</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="descriptor.html"
                        title="next chapter">Descriptor HowTo Guide</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/curses.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             >next</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P�����html/howto/descriptor.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Descriptor HowTo Guide &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Idioms and Anti-Idioms in Python" href="doanddont.html" />
    <link rel="prev" title="Curses Programming with Python" href="curses.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/descriptor.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="doanddont.html" title="Idioms and Anti-Idioms in Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="curses.html" title="Curses Programming with Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="descriptor-howto-guide">
<h1><a class="toc-backref" href="#id1">Descriptor HowTo Guide</a><a class="headerlink" href="#descriptor-howto-guide" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Raymond Hettinger</td>
</tr>
<tr class="field-even field"><th class="field-name">Contact:</th><td class="field-body">&lt;python at rcn dot com&gt;</td>
</tr>
</tbody>
</table>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#descriptor-howto-guide" id="id1">Descriptor HowTo Guide</a><ul>
<li><a class="reference internal" href="#abstract" id="id2">Abstract</a></li>
<li><a class="reference internal" href="#definition-and-introduction" id="id3">Definition and Introduction</a></li>
<li><a class="reference internal" href="#descriptor-protocol" id="id4">Descriptor Protocol</a></li>
<li><a class="reference internal" href="#invoking-descriptors" id="id5">Invoking Descriptors</a></li>
<li><a class="reference internal" href="#descriptor-example" id="id6">Descriptor Example</a></li>
<li><a class="reference internal" href="#properties" id="id7">Properties</a></li>
<li><a class="reference internal" href="#functions-and-methods" id="id8">Functions and Methods</a></li>
<li><a class="reference internal" href="#static-methods-and-class-methods" id="id9">Static Methods and Class Methods</a></li>
</ul>
</li>
</ul>
</div>
<div class="section" id="abstract">
<h2><a class="toc-backref" href="#id2">Abstract</a><a class="headerlink" href="#abstract" title="Permalink to this headline">¶</a></h2>
<p>Defines descriptors, summarizes the protocol, and shows how descriptors are
called.  Examines a custom descriptor and several built-in python descriptors
including functions, properties, static methods, and class methods.  Shows how
each works by giving a pure Python equivalent and a sample application.</p>
<p>Learning about descriptors not only provides access to a larger toolset, it
creates a deeper understanding of how Python works and an appreciation for the
elegance of its design.</p>
</div>
<div class="section" id="definition-and-introduction">
<h2><a class="toc-backref" href="#id3">Definition and Introduction</a><a class="headerlink" href="#definition-and-introduction" title="Permalink to this headline">¶</a></h2>
<p>In general, a descriptor is an object attribute with “binding behavior”, one
whose attribute access has been overridden by methods in the descriptor
protocol.  Those methods are <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, and
<a class="reference internal" href="../reference/datamodel.html#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>.  If any of those methods are defined for an object, it is
said to be a descriptor.</p>
<p>The default behavior for attribute access is to get, set, or delete the
attribute from an object’s dictionary.  For instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> has a lookup chain
starting with <code class="docutils literal notranslate"><span class="pre">a.__dict__['x']</span></code>, then <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x']</span></code>, and
continuing through the base classes of <code class="docutils literal notranslate"><span class="pre">type(a)</span></code> excluding metaclasses. If the
looked-up value is an object defining one of the descriptor methods, then Python
may override the default behavior and invoke the descriptor method instead.
Where this occurs in the precedence chain depends on which descriptor methods
were defined.  Note that descriptors are only invoked for new style objects or
classes (a class is new style if it inherits from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> or
<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>).</p>
<p>Descriptors are a powerful, general purpose protocol.  They are the mechanism
behind properties, methods, static methods, class methods, and <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>.
They are used throughout Python itself to implement the new style classes
introduced in version 2.2.  Descriptors simplify the underlying C-code and offer
a flexible set of new tools for everyday Python programs.</p>
</div>
<div class="section" id="descriptor-protocol">
<h2><a class="toc-backref" href="#id4">Descriptor Protocol</a><a class="headerlink" href="#descriptor-protocol" title="Permalink to this headline">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">descr.__get__(self,</span> <span class="pre">obj,</span> <span class="pre">type=None)</span> <span class="pre">--&gt;</span> <span class="pre">value</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">descr.__set__(self,</span> <span class="pre">obj,</span> <span class="pre">value)</span> <span class="pre">--&gt;</span> <span class="pre">None</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">descr.__delete__(self,</span> <span class="pre">obj)</span> <span class="pre">--&gt;</span> <span class="pre">None</span></code></p>
<p>That is all there is to it.  Define any of these methods and an object is
considered a descriptor and can override default behavior upon being looked up
as an attribute.</p>
<p>If an object defines both <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, it is considered
a data descriptor.  Descriptors that only define <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> are called
non-data descriptors (they are typically used for methods but other uses are
possible).</p>
<p>Data and non-data descriptors differ in how overrides are calculated with
respect to entries in an instance’s dictionary.  If an instance’s dictionary
has an entry with the same name as a data descriptor, the data descriptor
takes precedence.  If an instance’s dictionary has an entry with the same
name as a non-data descriptor, the dictionary entry takes precedence.</p>
<p>To make a read-only data descriptor, define both <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> with the <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> raising an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> when
called.  Defining the <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> method with an exception raising
placeholder is enough to make it a data descriptor.</p>
</div>
<div class="section" id="invoking-descriptors">
<h2><a class="toc-backref" href="#id5">Invoking Descriptors</a><a class="headerlink" href="#invoking-descriptors" title="Permalink to this headline">¶</a></h2>
<p>A descriptor can be called directly by its method name.  For example,
<code class="docutils literal notranslate"><span class="pre">d.__get__(obj)</span></code>.</p>
<p>Alternatively, it is more common for a descriptor to be invoked automatically
upon attribute access.  For example, <code class="docutils literal notranslate"><span class="pre">obj.d</span></code> looks up <code class="docutils literal notranslate"><span class="pre">d</span></code> in the dictionary
of <code class="docutils literal notranslate"><span class="pre">obj</span></code>.  If <code class="docutils literal notranslate"><span class="pre">d</span></code> defines the method <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, then <code class="docutils literal notranslate"><span class="pre">d.__get__(obj)</span></code>
is invoked according to the precedence rules listed below.</p>
<p>The details of invocation depend on whether <code class="docutils literal notranslate"><span class="pre">obj</span></code> is an object or a class.
Either way, descriptors only work for new style objects and classes.  A class is
new style if it is a subclass of <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.</p>
<p>For objects, the machinery is in <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__getattribute__()</span></code></a> which
transforms <code class="docutils literal notranslate"><span class="pre">b.x</span></code> into <code class="docutils literal notranslate"><span class="pre">type(b).__dict__['x'].__get__(b,</span> <span class="pre">type(b))</span></code>.  The
implementation works through a precedence chain that gives data descriptors
priority over instance variables, instance variables priority over non-data
descriptors, and assigns lowest priority to <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> if provided.
The full C implementation can be found in <a class="reference internal" href="../c-api/object.html#c.PyObject_GenericGetAttr" title="PyObject_GenericGetAttr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GenericGetAttr()</span></code></a> in
<a class="reference external" href="https://github.com/python/cpython/tree/2.7/Objects/object.c">Objects/object.c</a>.</p>
<p>For classes, the machinery is in <code class="xref py py-meth docutils literal notranslate"><span class="pre">type.__getattribute__()</span></code> which transforms
<code class="docutils literal notranslate"><span class="pre">B.x</span></code> into <code class="docutils literal notranslate"><span class="pre">B.__dict__['x'].__get__(None,</span> <span class="pre">B)</span></code>.  In pure Python, it looks
like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
    <span class="s2">&quot;Emulate type_getattro() in Objects/typeobject.c&quot;</span>
    <span class="n">v</span> <span class="o">=</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">v</span><span class="p">,</span> <span class="s1">&#39;__get__&#39;</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">v</span><span class="o">.</span><span class="fm">__get__</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">v</span>
</pre></div>
</div>
<p>The important points to remember are:</p>
<ul class="simple">
<li>descriptors are invoked by the <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method</li>
<li>overriding <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> prevents automatic descriptor calls</li>
<li><a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> is only available with new style classes and objects</li>
<li><a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__getattribute__()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">type.__getattribute__()</span></code> make
different calls to <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>.</li>
<li>data descriptors always override instance dictionaries.</li>
<li>non-data descriptors may be overridden by instance dictionaries.</li>
</ul>
<p>The object returned by <code class="docutils literal notranslate"><span class="pre">super()</span></code> also has a custom <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>
method for invoking descriptors.  The call <code class="docutils literal notranslate"><span class="pre">super(B,</span> <span class="pre">obj).m()</span></code> searches
<code class="docutils literal notranslate"><span class="pre">obj.__class__.__mro__</span></code> for the base class <code class="docutils literal notranslate"><span class="pre">A</span></code> immediately following <code class="docutils literal notranslate"><span class="pre">B</span></code>
and then returns <code class="docutils literal notranslate"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">B)</span></code>.  If not a descriptor,
<code class="docutils literal notranslate"><span class="pre">m</span></code> is returned unchanged.  If not in the dictionary, <code class="docutils literal notranslate"><span class="pre">m</span></code> reverts to a
search using <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__getattribute__()</span></code></a>.</p>
<p>Note, in Python 2.2, <code class="docutils literal notranslate"><span class="pre">super(B,</span> <span class="pre">obj).m()</span></code> would only invoke <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> if
<code class="docutils literal notranslate"><span class="pre">m</span></code> was a data descriptor.  In Python 2.3, non-data descriptors also get
invoked unless an old-style class is involved.  The implementation details are
in <code class="xref c c-func docutils literal notranslate"><span class="pre">super_getattro()</span></code> in <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Objects/typeobject.c">Objects/typeobject.c</a>.</p>
<p>The details above show that the mechanism for descriptors is embedded in the
<a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> methods for <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>, and
<a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>.  Classes inherit this machinery when they derive from
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> or if they have a meta-class providing similar functionality.
Likewise, classes can turn-off descriptor invocation by overriding
<a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>.</p>
</div>
<div class="section" id="descriptor-example">
<h2><a class="toc-backref" href="#id6">Descriptor Example</a><a class="headerlink" href="#descriptor-example" title="Permalink to this headline">¶</a></h2>
<p>The following code creates a class whose objects are data descriptors which
print a message for each get or set.  Overriding <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> is
alternate approach that could do this for every attribute.  However, this
descriptor is useful for monitoring just a few chosen attributes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">RevealAccess</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;A data descriptor that sets and returns values</span>
<span class="sd">       normally and prints a message logging their access.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">initval</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;var&#39;</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">val</span> <span class="o">=</span> <span class="n">initval</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>

    <span class="k">def</span> <span class="nf">__get__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">objtype</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;Retrieving&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">val</span>

    <span class="k">def</span> <span class="nf">__set__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">val</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;Updating&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">name</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">val</span> <span class="o">=</span> <span class="n">val</span>

<span class="o">&gt;&gt;&gt;</span> <span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="o">...</span>     <span class="n">x</span> <span class="o">=</span> <span class="n">RevealAccess</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="s1">&#39;var &quot;x&quot;&#39;</span><span class="p">)</span>
<span class="o">...</span>     <span class="n">y</span> <span class="o">=</span> <span class="mi">5</span>
<span class="o">...</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">x</span>
<span class="n">Retrieving</span> <span class="n">var</span> <span class="s2">&quot;x&quot;</span>
<span class="mi">10</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">20</span>
<span class="n">Updating</span> <span class="n">var</span> <span class="s2">&quot;x&quot;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">x</span>
<span class="n">Retrieving</span> <span class="n">var</span> <span class="s2">&quot;x&quot;</span>
<span class="mi">20</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">m</span><span class="o">.</span><span class="n">y</span>
<span class="mi">5</span>
</pre></div>
</div>
<p>The protocol is simple and offers exciting possibilities.  Several use cases are
so common that they have been packaged into individual function calls.
Properties, bound and unbound methods, static methods, and class methods are all
based on the descriptor protocol.</p>
</div>
<div class="section" id="properties">
<h2><a class="toc-backref" href="#id7">Properties</a><a class="headerlink" href="#properties" title="Permalink to this headline">¶</a></h2>
<p>Calling <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> is a succinct way of building a data descriptor that
triggers function calls upon access to an attribute.  Its signature is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">property</span><span class="p">(</span><span class="n">fget</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fdel</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">doc</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">property</span> <span class="n">attribute</span>
</pre></div>
</div>
<p>The documentation shows a typical use to define a managed attribute <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">getx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__x</span>
    <span class="k">def</span> <span class="nf">setx</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">__x</span> <span class="o">=</span> <span class="n">value</span>
    <span class="k">def</span> <span class="nf">delx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">__x</span>
    <span class="n">x</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">getx</span><span class="p">,</span> <span class="n">setx</span><span class="p">,</span> <span class="n">delx</span><span class="p">,</span> <span class="s2">&quot;I&#39;m the &#39;x&#39; property.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>To see how <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> is implemented in terms of the descriptor protocol,
here is a pure Python equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Property</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="s2">&quot;Emulate PyProperty_Type() in Objects/descrobject.c&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fget</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fset</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fdel</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">doc</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fget</span> <span class="o">=</span> <span class="n">fget</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fset</span> <span class="o">=</span> <span class="n">fset</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fdel</span> <span class="o">=</span> <span class="n">fdel</span>
        <span class="k">if</span> <span class="n">doc</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">fget</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">doc</span> <span class="o">=</span> <span class="n">fget</span><span class="o">.</span><span class="vm">__doc__</span>
        <span class="bp">self</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="n">doc</span>

    <span class="k">def</span> <span class="nf">__get__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">objtype</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">obj</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">fget</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">AttributeError</span><span class="p">(</span><span class="s2">&quot;unreadable attribute&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">fget</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__set__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">fset</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">AttributeError</span><span class="p">(</span><span class="s2">&quot;can&#39;t set attribute&quot;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fset</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__delete__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">fdel</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">AttributeError</span><span class="p">(</span><span class="s2">&quot;can&#39;t delete attribute&quot;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fdel</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">getter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fget</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)(</span><span class="n">fget</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">fset</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">fdel</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__doc__</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">setter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fset</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)(</span><span class="bp">self</span><span class="o">.</span><span class="n">fget</span><span class="p">,</span> <span class="n">fset</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">fdel</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__doc__</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">deleter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fdel</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">type</span><span class="p">(</span><span class="bp">self</span><span class="p">)(</span><span class="bp">self</span><span class="o">.</span><span class="n">fget</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">fset</span><span class="p">,</span> <span class="n">fdel</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__doc__</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> builtin helps whenever a user interface has granted
attribute access and then subsequent changes require the intervention of a
method.</p>
<p>For instance, a spreadsheet class may grant access to a cell value through
<code class="docutils literal notranslate"><span class="pre">Cell('b10').value</span></code>. Subsequent improvements to the program require the cell
to be recalculated on every access; however, the programmer does not want to
affect existing client code accessing the attribute directly.  The solution is
to wrap access to the value attribute in a property data descriptor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Cell</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="o">.</span> <span class="o">.</span> <span class="o">.</span>
    <span class="k">def</span> <span class="nf">getvalue</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Recalculate the cell before returning value&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">recalc</span><span class="p">()</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_value</span>
    <span class="n">value</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">getvalue</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="functions-and-methods">
<h2><a class="toc-backref" href="#id8">Functions and Methods</a><a class="headerlink" href="#functions-and-methods" title="Permalink to this headline">¶</a></h2>
<p>Python’s object oriented features are built upon a function based environment.
Using non-data descriptors, the two are merged seamlessly.</p>
<p>Class dictionaries store methods as functions.  In a class definition, methods
are written using <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> and <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a>, the usual tools for
creating functions.  The only difference from regular functions is that the
first argument is reserved for the object instance.  By Python convention, the
instance reference is called <em>self</em> but may be called <em>this</em> or any other
variable name.</p>
<p>To support method calls, functions include the <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> method for
binding methods during attribute access.  This means that all functions are
non-data descriptors which return bound or unbound methods depending whether
they are invoked from an object or a class.  In pure python, it works like
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Function</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="o">.</span> <span class="o">.</span> <span class="o">.</span>
    <span class="k">def</span> <span class="nf">__get__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">objtype</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="s2">&quot;Simulate func_descr_get() in Objects/funcobject.c&quot;</span>
        <span class="k">return</span> <span class="n">types</span><span class="o">.</span><span class="n">MethodType</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">objtype</span><span class="p">)</span>
</pre></div>
</div>
<p>Running the interpreter shows how the function descriptor works in practice:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">D</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">D</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">[</span><span class="s1">&#39;f&#39;</span><span class="p">]</span>  <span class="c1"># Stored internally as a function</span>
<span class="go">&lt;function f at 0x00C45070&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">D</span><span class="o">.</span><span class="n">f</span>              <span class="c1"># Get from a class becomes an unbound method</span>
<span class="go">&lt;unbound method D.f&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">f</span>              <span class="c1"># Get from an instance becomes a bound method</span>
<span class="go">&lt;bound method D.f of &lt;__main__.D object at 0x00B18C90&gt;&gt;</span>
</pre></div>
</div>
<p>The output suggests that bound and unbound methods are two different types.
While they could have been implemented that way, the actual C implementation of
<a class="reference internal" href="../c-api/method.html#c.PyMethod_Type" title="PyMethod_Type"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethod_Type</span></code></a> in <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Objects/classobject.c">Objects/classobject.c</a> is a single object
with two different representations depending on whether the <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code>
field is set or is <em>NULL</em> (the C equivalent of <code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
<p>Likewise, the effects of calling a method object depend on the <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code>
field. If set (meaning bound), the original function (stored in the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> field) is called as expected with the first argument set to the
instance.  If unbound, all of the arguments are passed unchanged to the original
function. The actual C implementation of <code class="xref py py-func docutils literal notranslate"><span class="pre">instancemethod_call()</span></code> is only
slightly more complex in that it includes some type checking.</p>
</div>
<div class="section" id="static-methods-and-class-methods">
<h2><a class="toc-backref" href="#id9">Static Methods and Class Methods</a><a class="headerlink" href="#static-methods-and-class-methods" title="Permalink to this headline">¶</a></h2>
<p>Non-data descriptors provide a simple mechanism for variations on the usual
patterns of binding functions into methods.</p>
<p>To recap, functions have a <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> method so that they can be converted
to a method when accessed as attributes.  The non-data descriptor transforms an
<code class="docutils literal notranslate"><span class="pre">obj.f(*args)</span></code> call into <code class="docutils literal notranslate"><span class="pre">f(obj,</span> <span class="pre">*args)</span></code>.  Calling <code class="docutils literal notranslate"><span class="pre">klass.f(*args)</span></code>
becomes <code class="docutils literal notranslate"><span class="pre">f(*args)</span></code>.</p>
<p>This chart summarizes the binding and its two most useful variants:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="39%" />
<col width="32%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Transformation</th>
<th class="head">Called from an
Object</th>
<th class="head">Called from a
Class</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>function</td>
<td>f(obj, *args)</td>
<td>f(*args)</td>
</tr>
<tr class="row-odd"><td>staticmethod</td>
<td>f(*args)</td>
<td>f(*args)</td>
</tr>
<tr class="row-even"><td>classmethod</td>
<td>f(type(obj), *args)</td>
<td>f(klass, *args)</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>Static methods return the underlying function without changes.  Calling either
<code class="docutils literal notranslate"><span class="pre">c.f</span></code> or <code class="docutils literal notranslate"><span class="pre">C.f</span></code> is the equivalent of a direct lookup into
<code class="docutils literal notranslate"><span class="pre">object.__getattribute__(c,</span> <span class="pre">&quot;f&quot;)</span></code> or <code class="docutils literal notranslate"><span class="pre">object.__getattribute__(C,</span> <span class="pre">&quot;f&quot;)</span></code>. As a
result, the function becomes identically accessible from either an object or a
class.</p>
<p>Good candidates for static methods are methods that do not reference the
<code class="docutils literal notranslate"><span class="pre">self</span></code> variable.</p>
<p>For instance, a statistics package may include a container class for
experimental data.  The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However,
there may be useful functions which are conceptually related but do not depend
on the data.  For instance, <code class="docutils literal notranslate"><span class="pre">erf(x)</span></code> is handy conversion routine that comes up
in statistical work but does not directly depend on a particular dataset.
It can be called either from an object or the class:  <code class="docutils literal notranslate"><span class="pre">s.erf(1.5)</span> <span class="pre">--&gt;</span> <span class="pre">.9332</span></code> or
<code class="docutils literal notranslate"><span class="pre">Sample.erf(1.5)</span> <span class="pre">--&gt;</span> <span class="pre">.9332</span></code>.</p>
<p>Since staticmethods return the underlying function with no changes, the example
calls are unexciting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">E</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">f</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">E</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">E</span><span class="p">()</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">3</span>
</pre></div>
</div>
<p>Using the non-data descriptor protocol, a pure Python version of
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">StaticMethod</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="s2">&quot;Emulate PyStaticMethod_Type() in Objects/funcobject.c&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="n">f</span>

    <span class="k">def</span> <span class="nf">__get__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">objtype</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">f</span>
</pre></div>
</div>
<p>Unlike static methods, class methods prepend the class reference to the
argument list before calling the function.  This format is the same
for whether the caller is an object or a class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">E</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>         <span class="k">return</span> <span class="n">klass</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="n">f</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">E</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">(&#39;E&#39;, 3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">E</span><span class="p">()</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">(&#39;E&#39;, 3)</span>
</pre></div>
</div>
<p>This behavior is useful whenever the function only needs to have a class
reference and does not care about any underlying data.  One use for classmethods
is to create alternate class constructors.  In Python 2.3, the classmethod
<a class="reference internal" href="../library/stdtypes.html#dict.fromkeys" title="dict.fromkeys"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict.fromkeys()</span></code></a> creates a new dictionary from a list of keys.  The pure
Python equivalent is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dict</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="o">.</span> <span class="o">.</span> <span class="o">.</span>
    <span class="k">def</span> <span class="nf">fromkeys</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="n">iterable</span><span class="p">,</span> <span class="n">value</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="s2">&quot;Emulate dict_fromkeys() in Objects/dictobject.c&quot;</span>
        <span class="n">d</span> <span class="o">=</span> <span class="n">klass</span><span class="p">()</span>
        <span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
            <span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
        <span class="k">return</span> <span class="n">d</span>
    <span class="n">fromkeys</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">fromkeys</span><span class="p">)</span>
</pre></div>
</div>
<p>Now a new dictionary of unique keys can be constructed like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Dict</span><span class="o">.</span><span class="n">fromkeys</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: None, &#39;r&#39;: None, &#39;b&#39;: None, &#39;c&#39;: None, &#39;d&#39;: None}</span>
</pre></div>
</div>
<p>Using the non-data descriptor protocol, a pure Python version of
<a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ClassMethod</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="s2">&quot;Emulate PyClassMethod_Type() in Objects/funcobject.c&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="n">f</span>

    <span class="k">def</span> <span class="nf">__get__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">klass</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">klass</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">klass</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="k">def</span> <span class="nf">newfunc</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">f</span><span class="p">(</span><span class="n">klass</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">newfunc</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Descriptor HowTo Guide</a><ul>
<li><a class="reference internal" href="#abstract">Abstract</a></li>
<li><a class="reference internal" href="#definition-and-introduction">Definition and Introduction</a></li>
<li><a class="reference internal" href="#descriptor-protocol">Descriptor Protocol</a></li>
<li><a class="reference internal" href="#invoking-descriptors">Invoking Descriptors</a></li>
<li><a class="reference internal" href="#descriptor-example">Descriptor Example</a></li>
<li><a class="reference internal" href="#properties">Properties</a></li>
<li><a class="reference internal" href="#functions-and-methods">Functions and Methods</a></li>
<li><a class="reference internal" href="#static-methods-and-class-methods">Static Methods and Class Methods</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="curses.html"
                        title="previous chapter">Curses Programming with Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="doanddont.html"
                        title="next chapter">Idioms and Anti-Idioms in Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/descriptor.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="doanddont.html" title="Idioms and Anti-Idioms in Python"
             >next</a> |</li>
        <li class="right" >
          <a href="curses.html" title="Curses Programming with Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�?Qy�y�html/howto/doanddont.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Idioms and Anti-Idioms in Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Functional Programming HOWTO" href="functional.html" />
    <link rel="prev" title="Descriptor HowTo Guide" href="descriptor.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/doanddont.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="idioms-and-anti-idioms-in-python">
<h1>Idioms and Anti-Idioms in Python<a class="headerlink" href="#idioms-and-anti-idioms-in-python" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Moshe Zadka</td>
</tr>
</tbody>
</table>
<p>This document is placed in the public domain.</p>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document can be considered a companion to the tutorial. It shows how to use
Python, and even more importantly, how <em>not</em> to use Python.</p>
</div>
<div class="section" id="language-constructs-you-should-not-use">
<h2>Language Constructs You Should Not Use<a class="headerlink" href="#language-constructs-you-should-not-use" title="Permalink to this headline">¶</a></h2>
<p>While Python has relatively few gotchas compared to other languages, it still
has some constructs which are only useful in corner cases, or are plain
dangerous.</p>
<div class="section" id="from-module-import">
<h3>from module import *<a class="headerlink" href="#from-module-import" title="Permalink to this headline">¶</a></h3>
<div class="section" id="inside-function-definitions">
<h4>Inside Function Definitions<a class="headerlink" href="#inside-function-definitions" title="Permalink to this headline">¶</a></h4>
<p><code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> is <em>invalid</em> inside function definitions. While many
versions of Python do not check for the invalidity, it does not make it more
valid, no more than having a smart lawyer makes a man innocent. Do not use it
like that ever. Even in versions where it was accepted, it made the function
execution slower, because the compiler could not be certain which names were
local and which were global. In Python 2.1 this construct causes warnings, and
sometimes even errors.</p>
</div>
<div class="section" id="at-module-level">
<h4>At Module Level<a class="headerlink" href="#at-module-level" title="Permalink to this headline">¶</a></h4>
<p>While it is valid to use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> at module level it is usually
a bad idea. For one, this loses an important property Python otherwise has —
you can know where each toplevel name is defined by a simple “search” function
in your favourite editor. You also open yourself to trouble in the future, if
some module grows additional functions or classes.</p>
<p>One of the most awful questions asked on the newsgroup is why this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;www&quot;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>does not work. Of course, it works just fine (assuming you have a file called
“www”.) But it does not work if somewhere in the module, the statement <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">os</span> <span class="pre">import</span> <span class="pre">*</span></code> is present. The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module has a function called
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> which returns an integer. While it is very useful, shadowing a
builtin is one of its least useful properties.</p>
<p>Remember, you can never know for sure what names a module exports, so either
take what you need — <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">name1,</span> <span class="pre">name2</span></code>, or keep them in the
module and access on a per-need basis —  <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">module;print</span> <span class="pre">module.name</span></code>.</p>
</div>
<div class="section" id="when-it-is-just-fine">
<h4>When It Is Just Fine<a class="headerlink" href="#when-it-is-just-fine" title="Permalink to this headline">¶</a></h4>
<p>There are situations in which <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> is just fine:</p>
<ul class="simple">
<li>The interactive prompt. For example, <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">math</span> <span class="pre">import</span> <span class="pre">*</span></code> makes Python an
amazing scientific calculator.</li>
<li>When extending a module in C with a module in Python.</li>
<li>When the module advertises itself as <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">import</span> <span class="pre">*</span></code> safe.</li>
</ul>
</div>
</div>
<div class="section" id="unadorned-exec-execfile-and-friends">
<h3>Unadorned <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>, <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> and friends<a class="headerlink" href="#unadorned-exec-execfile-and-friends" title="Permalink to this headline">¶</a></h3>
<p>The word “unadorned” refers to the use without an explicit dictionary, in which
case those constructs evaluate code in the <em>current</em> environment. This is
dangerous for the same reasons <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">import</span> <span class="pre">*</span></code> is dangerous — it might step
over variables you are counting on and mess up things for the rest of your code.
Simply do not do that.</p>
<p>Bad examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
<span class="gp">&gt;&gt;&gt; </span>    <span class="n">exec</span> <span class="s2">&quot;</span><span class="si">%s</span><span class="s2">=1&quot;</span> <span class="o">%</span> <span class="n">name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">&gt;&gt;&gt; </span>    <span class="k">for</span> <span class="n">var</span><span class="p">,</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">kw</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">&gt;&gt;&gt; </span>        <span class="n">exec</span> <span class="s2">&quot;s.</span><span class="si">%s</span><span class="s2">=val&quot;</span> <span class="o">%</span> <span class="n">var</span>  <span class="c1"># invalid!</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">execfile</span><span class="p">(</span><span class="s2">&quot;handler.py&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">handle</span><span class="p">()</span>
</pre></div>
</div>
<p>Good examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
<span class="gp">&gt;&gt;&gt; </span>    <span class="n">d</span><span class="p">[</span><span class="n">name</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">&gt;&gt;&gt; </span>    <span class="k">for</span> <span class="n">var</span><span class="p">,</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">kw</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">&gt;&gt;&gt; </span>        <span class="nb">setattr</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">var</span><span class="p">,</span> <span class="n">val</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">=</span><span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">execfile</span><span class="p">(</span><span class="s2">&quot;handle.py&quot;</span><span class="p">,</span> <span class="n">d</span><span class="p">,</span> <span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">handle</span> <span class="o">=</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;handle&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">handle</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="from-module-import-name1-name2">
<h3>from module import name1, name2<a class="headerlink" href="#from-module-import-name1-name2" title="Permalink to this headline">¶</a></h3>
<p>This is a “don’t” which is much weaker than the previous “don’t”s but is still
something you should not do if you don’t have good reasons to do that. The
reason it is usually a bad idea is because you suddenly have an object which lives
in two separate namespaces. When the binding in one namespace changes, the
binding in the other will not, so there will be a discrepancy between them. This
happens when, for example, one module is reloaded, or changes the definition of
a function at runtime.</p>
<p>Bad example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># foo.py</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>

<span class="c1"># bar.py</span>
<span class="kn">from</span> <span class="nn">foo</span> <span class="k">import</span> <span class="n">a</span>
<span class="k">if</span> <span class="n">something</span><span class="p">():</span>
    <span class="n">a</span> <span class="o">=</span> <span class="mi">2</span> <span class="c1"># danger: foo.a != a</span>
</pre></div>
</div>
<p>Good example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># foo.py</span>
<span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>

<span class="c1"># bar.py</span>
<span class="kn">import</span> <span class="nn">foo</span>
<span class="k">if</span> <span class="n">something</span><span class="p">():</span>
    <span class="n">foo</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">2</span>
</pre></div>
</div>
</div>
<div class="section" id="except">
<h3>except:<a class="headerlink" href="#except" title="Permalink to this headline">¶</a></h3>
<p>Python has the <code class="docutils literal notranslate"><span class="pre">except:</span></code> clause, which catches all exceptions. Since <em>every</em>
error in Python raises an exception, using <code class="docutils literal notranslate"><span class="pre">except:</span></code> can make many
programming errors look like runtime problems, which hinders the debugging
process.</p>
<p>The following code shows a great example of why this is bad:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">foo</span> <span class="o">=</span> <span class="n">opne</span><span class="p">(</span><span class="s2">&quot;file&quot;</span><span class="p">)</span> <span class="c1"># misspelled &quot;open&quot;</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="s2">&quot;could not open file!&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The second line triggers a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>, which is caught by the except
clause. The program will exit, and the error message the program prints will
make you think the problem is the readability of <code class="docutils literal notranslate"><span class="pre">&quot;file&quot;</span></code> when in fact
the real error has nothing to do with <code class="docutils literal notranslate"><span class="pre">&quot;file&quot;</span></code>.</p>
<p>A better way to write the above is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">foo</span> <span class="o">=</span> <span class="n">opne</span><span class="p">(</span><span class="s2">&quot;file&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="s2">&quot;could not open file&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>When this is run, Python will produce a traceback showing the <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>,
and it will be immediately apparent what needs to be fixed.</p>
<p id="index-0">Because <code class="docutils literal notranslate"><span class="pre">except:</span></code> catches <em>all</em> exceptions, including <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>,
<a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>, and <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> (which is not an error and
should not normally be caught by user code), using a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> is almost
never a good idea.  In situations where you need to catch all “normal” errors,
such as in a framework that runs callbacks, you can catch the base class for
all normal exceptions, <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.  Unfortunately in Python 2.x it is
possible for third-party code to raise exceptions that do not inherit from
<a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>, so in Python 2.x there are some cases where you may have to
use a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> and manually re-raise the exceptions you don’t want
to catch.</p>
</div>
</div>
<div class="section" id="exceptions">
<h2>Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>Exceptions are a useful feature of Python. You should learn to raise them
whenever something unexpected occurs, and catch them only where you can do
something about them.</p>
<p>The following is a very popular anti-idiom</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_status</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;file not found&quot;</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
<p>Consider the case where the file gets deleted between the time the call to
<a class="reference internal" href="../library/os.path.html#os.path.exists" title="os.path.exists"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.exists()</span></code></a> is made and the time <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> is called. In that
case the last line will raise an <a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.  The same thing would happen
if <em>file</em> exists but has no read permission.  Since testing this on a normal
machine on existent and non-existent files makes it seem bugless, the test
results will seem fine, and the code will get shipped.  Later an unhandled
<a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> (or perhaps some other <a class="reference internal" href="../library/exceptions.html#exceptions.EnvironmentError" title="exceptions.EnvironmentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EnvironmentError</span></code></a>) escapes to the
user, who gets to watch the ugly traceback.</p>
<p>Here is a somewhat better way to do it.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_status</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">EnvironmentError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;Unable to open file: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">err</span><span class="p">)</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>In this version, <em>either</em> the file gets opened and the line is read (so it
works even on flaky NFS or SMB connections), or an error message is printed
that provides all the available information on why the open failed, and the
application is aborted.</p>
<p>However, even this version of <code class="xref py py-func docutils literal notranslate"><span class="pre">get_status()</span></code> makes too many assumptions —
that it will only be used in a short running script, and not, say, in a long
running server. Sure, the caller could do something like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">status</span> <span class="o">=</span> <span class="n">get_status</span><span class="p">(</span><span class="n">log</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">SystemExit</span><span class="p">:</span>
    <span class="n">status</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
<p>But there is a better way.  You should try to use as few <code class="docutils literal notranslate"><span class="pre">except</span></code> clauses in
your code as you can — the ones you do use will usually be inside calls which
should always succeed, or a catch-all in a main function.</p>
<p>So, an even better version of <code class="xref py py-func docutils literal notranslate"><span class="pre">get_status()</span></code> is probably</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_status</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
<p>The caller can deal with the exception if it wants (for example, if it tries
several files in a loop), or just let the exception filter upwards to <em>its</em>
caller.</p>
<p>But the last version still has a serious problem — due to implementation
details in CPython, the file would not be closed when an exception is raised
until the exception handler finishes; and, worse, in other implementations
(e.g., Jython) it might not be closed at all regardless of whether or not
an exception is raised.</p>
<p>The best version of this function uses the <code class="docutils literal notranslate"><span class="pre">open()</span></code> call as a context
manager, which will ensure that the file gets closed as soon as the
function returns:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">get_status</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="using-the-batteries">
<h2>Using the Batteries<a class="headerlink" href="#using-the-batteries" title="Permalink to this headline">¶</a></h2>
<p>Every so often, people seem to be writing stuff in the Python library again,
usually poorly. While the occasional module has a poor interface, it is usually
much better to use the rich standard library and data types that come with
Python than inventing your own.</p>
<p>A useful module very few people know about is <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>. It  always has the
correct path arithmetic for your operating system, and will usually be much
better than whatever you come up with yourself.</p>
<p>Compare:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># ugh!</span>
<span class="k">return</span> <span class="nb">dir</span><span class="o">+</span><span class="s2">&quot;/&quot;</span><span class="o">+</span><span class="n">file</span>
<span class="c1"># better</span>
<span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">dir</span><span class="p">,</span> <span class="n">file</span><span class="p">)</span>
</pre></div>
</div>
<p>More useful functions in <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>: <code class="xref py py-func docutils literal notranslate"><span class="pre">basename()</span></code>,  <code class="xref py py-func docutils literal notranslate"><span class="pre">dirname()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">splitext()</span></code>.</p>
<p>There are also many useful built-in functions people seem not to be aware of
for some reason: <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> can find the minimum/maximum of
any sequence with comparable semantics, for example, yet many people write
their own <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>/<a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>. Another highly useful function is
<a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> which can be used to repeatedly apply a binary operation to a
sequence, reducing it to a single value.  For example, compute a factorial
with a series of multiply operations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">operator</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">n</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span>
<span class="go">24</span>
</pre></div>
</div>
<p>When it comes to parsing numbers, note that <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> all accept string arguments and will reject ill-formed strings
by raising an <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</div>
<div class="section" id="using-backslash-to-continue-statements">
<h2>Using Backslash to Continue Statements<a class="headerlink" href="#using-backslash-to-continue-statements" title="Permalink to this headline">¶</a></h2>
<p>Since Python treats a newline as a statement terminator, and since statements
are often more than is comfortable to put in one line, many people do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">foo</span><span class="o">.</span><span class="n">bar</span><span class="p">()[</span><span class="s1">&#39;first&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">baz</span><span class="o">.</span><span class="n">quux</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)[</span><span class="mi">5</span><span class="p">:</span><span class="mi">9</span><span class="p">]</span> <span class="ow">and</span> \
   <span class="n">calculate_number</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span> <span class="o">!=</span> <span class="n">forbulate</span><span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="mi">360</span><span class="p">):</span>
      <span class="k">pass</span>
</pre></div>
</div>
<p>You should realize that this is dangerous: a stray space after the <code class="docutils literal notranslate"><span class="pre">\</span></code> would
make this line wrong, and stray spaces are notoriously hard to see in editors.
In this case, at least it would be a syntax error, but if the code was:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">value</span> <span class="o">=</span> <span class="n">foo</span><span class="o">.</span><span class="n">bar</span><span class="p">()[</span><span class="s1">&#39;first&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span><span class="o">*</span><span class="n">baz</span><span class="o">.</span><span class="n">quux</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)[</span><span class="mi">5</span><span class="p">:</span><span class="mi">9</span><span class="p">]</span> \
        <span class="o">+</span> <span class="n">calculate_number</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span><span class="o">*</span><span class="n">forbulate</span><span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="mi">360</span><span class="p">)</span>
</pre></div>
</div>
<p>then it would just be subtly wrong.</p>
<p>It is usually much better to use the implicit continuation inside parenthesis:</p>
<p>This version is bulletproof:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="n">foo</span><span class="o">.</span><span class="n">bar</span><span class="p">()[</span><span class="s1">&#39;first&#39;</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span><span class="o">*</span><span class="n">baz</span><span class="o">.</span><span class="n">quux</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)[</span><span class="mi">5</span><span class="p">:</span><span class="mi">9</span><span class="p">]</span>
        <span class="o">+</span> <span class="n">calculate_number</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span><span class="o">*</span><span class="n">forbulate</span><span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="mi">360</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Idioms and Anti-Idioms in Python</a><ul>
<li><a class="reference internal" href="#language-constructs-you-should-not-use">Language Constructs You Should Not Use</a><ul>
<li><a class="reference internal" href="#from-module-import">from module import *</a><ul>
<li><a class="reference internal" href="#inside-function-definitions">Inside Function Definitions</a></li>
<li><a class="reference internal" href="#at-module-level">At Module Level</a></li>
<li><a class="reference internal" href="#when-it-is-just-fine">When It Is Just Fine</a></li>
</ul>
</li>
<li><a class="reference internal" href="#unadorned-exec-execfile-and-friends">Unadorned <code class="docutils literal notranslate"><span class="pre">exec</span></code>, <code class="docutils literal notranslate"><span class="pre">execfile()</span></code> and friends</a></li>
<li><a class="reference internal" href="#from-module-import-name1-name2">from module import name1, name2</a></li>
<li><a class="reference internal" href="#except">except:</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">Exceptions</a></li>
<li><a class="reference internal" href="#using-the-batteries">Using the Batteries</a></li>
<li><a class="reference internal" href="#using-backslash-to-continue-statements">Using Backslash to Continue Statements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="descriptor.html"
                        title="previous chapter">Descriptor HowTo Guide</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="functional.html"
                        title="next chapter">Functional Programming HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/doanddont.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="descriptor.html" title="Descriptor HowTo Guide"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Y@_��html/howto/functional.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Functional Programming HOWTO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Logging HOWTO" href="logging.html" />
    <link rel="prev" title="Idioms and Anti-Idioms in Python" href="doanddont.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/functional.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="doanddont.html" title="Idioms and Anti-Idioms in Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="functional-programming-howto">
<h1>Functional Programming HOWTO<a class="headerlink" href="#functional-programming-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A. M. Kuchling</td>
</tr>
<tr class="field-even field"><th class="field-name">Release:</th><td class="field-body">0.31</td>
</tr>
</tbody>
</table>
<p>In this document, we’ll take a tour of Python’s features suitable for
implementing programs in a functional style.  After an introduction to the
concepts of functional programming, we’ll look at language features such as
<a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>s and <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>s and relevant library modules such as
<a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> and <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a>.</p>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>This section explains the basic concept of functional programming; if you’re
just interested in learning about Python language features, skip to the next
section.</p>
<p>Programming languages support decomposing problems in several different ways:</p>
<ul class="simple">
<li>Most programming languages are <strong>procedural</strong>: programs are lists of
instructions that tell the computer what to do with the program’s input.  C,
Pascal, and even Unix shells are procedural languages.</li>
<li>In <strong>declarative</strong> languages, you write a specification that describes the
problem to be solved, and the language implementation figures out how to
perform the computation efficiently.  SQL is the declarative language you’re
most likely to be familiar with; a SQL query describes the data set you want
to retrieve, and the SQL engine decides whether to scan tables or use indexes,
which subclauses should be performed first, etc.</li>
<li><strong>Object-oriented</strong> programs manipulate collections of objects.  Objects have
internal state and support methods that query or modify this internal state in
some way. Smalltalk and Java are object-oriented languages.  C++ and Python
are languages that support object-oriented programming, but don’t force the
use of object-oriented features.</li>
<li><strong>Functional</strong> programming decomposes a problem into a set of functions.
Ideally, functions only take inputs and produce outputs, and don’t have any
internal state that affects the output produced for a given input.  Well-known
functional languages include the ML family (Standard ML, OCaml, and other
variants) and Haskell.</li>
</ul>
<p>The designers of some computer languages choose to emphasize one particular
approach to programming.  This often makes it difficult to write programs that
use a different approach.  Other languages are multi-paradigm languages that
support several different approaches.  Lisp, C++, and Python are
multi-paradigm; you can write programs or libraries that are largely
procedural, object-oriented, or functional in all of these languages.  In a
large program, different sections might be written using different approaches;
the GUI might be object-oriented while the processing logic is procedural or
functional, for example.</p>
<p>In a functional program, input flows through a set of functions. Each function
operates on its input and produces some output.  Functional style discourages
functions with side effects that modify internal state or make other changes
that aren’t visible in the function’s return value.  Functions that have no side
effects at all are called <strong>purely functional</strong>.  Avoiding side effects means
not using data structures that get updated as a program runs; every function’s
output must only depend on its input.</p>
<p>Some languages are very strict about purity and don’t even have assignment
statements such as <code class="docutils literal notranslate"><span class="pre">a=3</span></code> or <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code>, but it’s difficult to avoid all
side effects.  Printing to the screen or writing to a disk file are side
effects, for example.  For example, in Python a <code class="docutils literal notranslate"><span class="pre">print</span></code> statement or a
<code class="docutils literal notranslate"><span class="pre">time.sleep(1)</span></code> both return no useful value; they’re only called for their
side effects of sending some text to the screen or pausing execution for a
second.</p>
<p>Python programs written in functional style usually won’t go to the extreme of
avoiding all I/O or all assignments; instead, they’ll provide a
functional-appearing interface but will use non-functional features internally.
For example, the implementation of a function will still use assignments to
local variables, but won’t modify global variables or have other side effects.</p>
<p>Functional programming can be considered the opposite of object-oriented
programming.  Objects are little capsules containing some internal state along
with a collection of method calls that let you modify this state, and programs
consist of making the right set of state changes.  Functional programming wants
to avoid state changes as much as possible and works with data flowing between
functions.  In Python you might combine the two approaches by writing functions
that take and return instances representing objects in your application (e-mail
messages, transactions, etc.).</p>
<p>Functional design may seem like an odd constraint to work under.  Why should you
avoid objects and side effects?  There are theoretical and practical advantages
to the functional style:</p>
<ul class="simple">
<li>Formal provability.</li>
<li>Modularity.</li>
<li>Composability.</li>
<li>Ease of debugging and testing.</li>
</ul>
<div class="section" id="formal-provability">
<h3>Formal provability<a class="headerlink" href="#formal-provability" title="Permalink to this headline">¶</a></h3>
<p>A theoretical benefit is that it’s easier to construct a mathematical proof that
a functional program is correct.</p>
<p>For a long time researchers have been interested in finding ways to
mathematically prove programs correct.  This is different from testing a program
on numerous inputs and concluding that its output is usually correct, or reading
a program’s source code and concluding that the code looks right; the goal is
instead a rigorous proof that a program produces the right result for all
possible inputs.</p>
<p>The technique used to prove programs correct is to write down <strong>invariants</strong>,
properties of the input data and of the program’s variables that are always
true.  For each line of code, you then show that if invariants X and Y are true
<strong>before</strong> the line is executed, the slightly different invariants X’ and Y’ are
true <strong>after</strong> the line is executed.  This continues until you reach the end of
the program, at which point the invariants should match the desired conditions
on the program’s output.</p>
<p>Functional programming’s avoidance of assignments arose because assignments are
difficult to handle with this technique; assignments can break invariants that
were true before the assignment without producing any new invariants that can be
propagated onward.</p>
<p>Unfortunately, proving programs correct is largely impractical and not relevant
to Python software. Even trivial programs require proofs that are several pages
long; the proof of correctness for a moderately complicated program would be
enormous, and few or none of the programs you use daily (the Python interpreter,
your XML parser, your web browser) could be proven correct.  Even if you wrote
down or generated a proof, there would then be the question of verifying the
proof; maybe there’s an error in it, and you wrongly believe you’ve proved the
program correct.</p>
</div>
<div class="section" id="modularity">
<h3>Modularity<a class="headerlink" href="#modularity" title="Permalink to this headline">¶</a></h3>
<p>A more practical benefit of functional programming is that it forces you to
break apart your problem into small pieces.  Programs are more modular as a
result.  It’s easier to specify and write a small function that does one thing
than a large function that performs a complicated transformation.  Small
functions are also easier to read and to check for errors.</p>
</div>
<div class="section" id="ease-of-debugging-and-testing">
<h3>Ease of debugging and testing<a class="headerlink" href="#ease-of-debugging-and-testing" title="Permalink to this headline">¶</a></h3>
<p>Testing and debugging a functional-style program is easier.</p>
<p>Debugging is simplified because functions are generally small and clearly
specified.  When a program doesn’t work, each function is an interface point
where you can check that the data are correct.  You can look at the intermediate
inputs and outputs to quickly isolate the function that’s responsible for a bug.</p>
<p>Testing is easier because each function is a potential subject for a unit test.
Functions don’t depend on system state that needs to be replicated before
running a test; instead you only have to synthesize the right input and then
check that the output matches expectations.</p>
</div>
<div class="section" id="composability">
<h3>Composability<a class="headerlink" href="#composability" title="Permalink to this headline">¶</a></h3>
<p>As you work on a functional-style program, you’ll write a number of functions
with varying inputs and outputs.  Some of these functions will be unavoidably
specialized to a particular application, but others will be useful in a wide
variety of programs.  For example, a function that takes a directory path and
returns all the XML files in the directory, or a function that takes a filename
and returns its contents, can be applied to many different situations.</p>
<p>Over time you’ll form a personal library of utilities.  Often you’ll assemble
new programs by arranging existing functions in a new configuration and writing
a few functions specialized for the current task.</p>
</div>
</div>
<div class="section" id="iterators">
<h2>Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline">¶</a></h2>
<p>I’ll start by looking at a Python language feature that’s an important
foundation for writing functional-style programs: iterators.</p>
<p>An iterator is an object representing a stream of data; this object returns the
data one element at a time.  A Python iterator must support a method called
<code class="docutils literal notranslate"><span class="pre">next()</span></code> that takes no arguments and always returns the next element of the
stream.  If there are no more elements in the stream, <code class="docutils literal notranslate"><span class="pre">next()</span></code> must raise the
<code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> exception.  Iterators don’t have to be finite, though; it’s
perfectly reasonable to write an iterator that produces an infinite stream of
data.</p>
<p>The built-in <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> function takes an arbitrary object and tries to return
an iterator that will return the object’s contents or elements, raising
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the object doesn’t support iteration.  Several of Python’s
built-in data types support iteration, the most common being lists and
dictionaries.  An object is called an <strong>iterable</strong> object if you can get an
iterator for it.</p>
<p>You can experiment with the iteration interface manually:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span>
<span class="go">&lt;...iterator object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">StopIteration</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Python expects iterable objects in several different contexts, the most
important being the <code class="docutils literal notranslate"><span class="pre">for</span></code> statement.  In the statement <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code>, Y must
be an iterator or some object for which <code class="docutils literal notranslate"><span class="pre">iter()</span></code> can create an iterator.
These two statements are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">i</span>

<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">obj</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">i</span>
</pre></div>
</div>
<p>Iterators can be materialized as lists or tuples by using the <code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code> or
<a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a> constructor functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterator</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(1, 2, 3)</span>
</pre></div>
</div>
<p>Sequence unpacking also supports iterators: if you know an iterator will return
N elements, you can unpack them into an N-tuple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span> <span class="o">=</span> <span class="n">iterator</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span>
<span class="go">(1, 2, 3)</span>
</pre></div>
</div>
<p>Built-in functions such as <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> and <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> can take a single
iterator argument and will return the largest or smallest element.  The <code class="docutils literal notranslate"><span class="pre">&quot;in&quot;</span></code>
and <code class="docutils literal notranslate"><span class="pre">&quot;not</span> <span class="pre">in&quot;</span></code> operators also support iterators: <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">iterator</span></code> is true if
X is found in the stream returned by the iterator.  You’ll run into obvious
problems if the iterator is infinite; <code class="docutils literal notranslate"><span class="pre">max()</span></code>, <code class="docutils literal notranslate"><span class="pre">min()</span></code>
will never return, and if the element X never appears in the stream, the
<code class="docutils literal notranslate"><span class="pre">&quot;in&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;not</span> <span class="pre">in&quot;</span></code> operators won’t return either.</p>
<p>Note that you can only go forward in an iterator; there’s no way to get the
previous element, reset the iterator, or make a copy of it.  Iterator objects
can optionally provide these additional capabilities, but the iterator protocol
only specifies the <code class="docutils literal notranslate"><span class="pre">next()</span></code> method.  Functions may therefore consume all of
the iterator’s output, and if you need to do something different with the same
stream, you’ll have to create a new iterator.</p>
<div class="section" id="data-types-that-support-iterators">
<h3>Data Types That Support Iterators<a class="headerlink" href="#data-types-that-support-iterators" title="Permalink to this headline">¶</a></h3>
<p>We’ve already seen how lists and tuples support iterators.  In fact, any Python
sequence type, such as strings, will automatically support creation of an
iterator.</p>
<p>Calling <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on a dictionary returns an iterator that will loop over the
dictionary’s keys:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Jan&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;Feb&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;Mar&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;Apr&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;May&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;Jun&#39;</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span>
<span class="gp">... </span>     <span class="s1">&#39;Jul&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;Aug&#39;</span><span class="p">:</span> <span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;Sep&#39;</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="s1">&#39;Oct&#39;</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="s1">&#39;Nov&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;Dec&#39;</span><span class="p">:</span> <span class="mi">12</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">m</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">key</span><span class="p">,</span> <span class="n">m</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="go">Mar 3</span>
<span class="go">Feb 2</span>
<span class="go">Aug 8</span>
<span class="go">Sep 9</span>
<span class="go">Apr 4</span>
<span class="go">Jun 6</span>
<span class="go">Jul 7</span>
<span class="go">Jan 1</span>
<span class="go">May 5</span>
<span class="go">Nov 11</span>
<span class="go">Dec 12</span>
<span class="go">Oct 10</span>
</pre></div>
</div>
<p>Note that the order is essentially random, because it’s based on the hash
ordering of the objects in the dictionary.</p>
<p>Applying <code class="docutils literal notranslate"><span class="pre">iter()</span></code> to a dictionary always loops over the keys, but dictionaries
have methods that return other iterators.  If you want to iterate over keys,
values, or key/value pairs, you can explicitly call the <code class="docutils literal notranslate"><span class="pre">iterkeys()</span></code>,
<code class="docutils literal notranslate"><span class="pre">itervalues()</span></code>, or <code class="docutils literal notranslate"><span class="pre">iteritems()</span></code> methods to get an appropriate iterator.</p>
<p>The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> constructor can accept an iterator that returns a finite stream
of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> tuples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Italy&#39;</span><span class="p">,</span> <span class="s1">&#39;Rome&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;France&#39;</span><span class="p">,</span> <span class="s1">&#39;Paris&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;US&#39;</span><span class="p">,</span> <span class="s1">&#39;Washington DC&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">))</span>
<span class="go">{&#39;Italy&#39;: &#39;Rome&#39;, &#39;US&#39;: &#39;Washington DC&#39;, &#39;France&#39;: &#39;Paris&#39;}</span>
</pre></div>
</div>
<p>Files also support iteration by calling the <code class="docutils literal notranslate"><span class="pre">readline()</span></code> method until there
are no more lines in the file.  This means you can read each line of a file like
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">file</span><span class="p">:</span>
    <span class="c1"># do something for each line</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Sets can take their contents from an iterable and let you iterate over the set’s
elements:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">S</span> <span class="o">=</span> <span class="nb">set</span><span class="p">((</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">))</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">S</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">i</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="generator-expressions-and-list-comprehensions">
<h2>Generator expressions and list comprehensions<a class="headerlink" href="#generator-expressions-and-list-comprehensions" title="Permalink to this headline">¶</a></h2>
<p>Two common operations on an iterator’s output are 1) performing some operation
for every element, 2) selecting a subset of elements that meet some condition.
For example, given a list of strings, you might want to strip off trailing
whitespace from each line or extract all the strings containing a given
substring.</p>
<p>List comprehensions and generator expressions (short form: “listcomps” and
“genexps”) are a concise notation for such operations, borrowed from the
functional programming language Haskell (<a class="reference external" href="https://www.haskell.org/">https://www.haskell.org/</a>).  You can strip
all the whitespace from a stream of strings with the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">line_list</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;  line 1</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;line 2  </span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">]</span>

<span class="c1"># Generator expression -- returns iterator</span>
<span class="n">stripped_iter</span> <span class="o">=</span> <span class="p">(</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">)</span>

<span class="c1"># List comprehension -- returns list</span>
<span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span><span class="p">]</span>
</pre></div>
</div>
<p>You can select only certain elements by adding an <code class="docutils literal notranslate"><span class="pre">&quot;if&quot;</span></code> condition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stripped_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">line_list</span>
                 <span class="k">if</span> <span class="n">line</span> <span class="o">!=</span> <span class="s2">&quot;&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>With a list comprehension, you get back a Python list; <code class="docutils literal notranslate"><span class="pre">stripped_list</span></code> is a
list containing the resulting lines, not an iterator.  Generator expressions
return an iterator that computes the values as necessary, not needing to
materialize all the values at once.  This means that list comprehensions aren’t
useful if you’re working with iterators that return an infinite stream or a very
large amount of data.  Generator expressions are preferable in these situations.</p>
<p>Generator expressions are surrounded by parentheses (“()”) and list
comprehensions are surrounded by square brackets (“[]”).  Generator expressions
have the form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span> <span class="n">expression</span> <span class="k">for</span> <span class="n">expr</span> <span class="ow">in</span> <span class="n">sequence1</span>
             <span class="k">if</span> <span class="n">condition1</span>
             <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span>
             <span class="k">if</span> <span class="n">condition2</span>
             <span class="k">for</span> <span class="n">expr3</span> <span class="ow">in</span> <span class="n">sequence3</span> <span class="o">...</span>
             <span class="k">if</span> <span class="n">condition3</span>
             <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span>
             <span class="k">if</span> <span class="n">conditionN</span> <span class="p">)</span>
</pre></div>
</div>
<p>Again, for a list comprehension only the outside brackets are different (square
brackets instead of parentheses).</p>
<p>The elements of the generated output will be the successive values of
<code class="docutils literal notranslate"><span class="pre">expression</span></code>.  The <code class="docutils literal notranslate"><span class="pre">if</span></code> clauses are all optional; if present, <code class="docutils literal notranslate"><span class="pre">expression</span></code>
is only evaluated and added to the result when <code class="docutils literal notranslate"><span class="pre">condition</span></code> is true.</p>
<p>Generator expressions always have to be written inside parentheses, but the
parentheses signalling a function call also count.  If you want to create an
iterator that will be immediately passed to a function you can write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">obj_total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="n">count</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">list_all_objects</span><span class="p">())</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">for...in</span></code> clauses contain the sequences to be iterated over.  The
sequences do not have to be the same length, because they are iterated over from
left to right, <strong>not</strong> in parallel.  For each element in <code class="docutils literal notranslate"><span class="pre">sequence1</span></code>,
<code class="docutils literal notranslate"><span class="pre">sequence2</span></code> is looped over from the beginning.  <code class="docutils literal notranslate"><span class="pre">sequence3</span></code> is then looped
over for each resulting pair of elements from <code class="docutils literal notranslate"><span class="pre">sequence1</span></code> and <code class="docutils literal notranslate"><span class="pre">sequence2</span></code>.</p>
<p>To put it another way, a list comprehension or generator expression is
equivalent to the following Python code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">expr1</span> <span class="ow">in</span> <span class="n">sequence1</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition1</span><span class="p">):</span>
        <span class="k">continue</span>   <span class="c1"># Skip this element</span>
    <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">condition2</span><span class="p">):</span>
            <span class="k">continue</span>   <span class="c1"># Skip this element</span>
        <span class="o">...</span>
        <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span><span class="p">:</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">conditionN</span><span class="p">):</span>
                <span class="k">continue</span>   <span class="c1"># Skip this element</span>

            <span class="c1"># Output the value of</span>
            <span class="c1"># the expression.</span>
</pre></div>
</div>
<p>This means that when there are multiple <code class="docutils literal notranslate"><span class="pre">for...in</span></code> clauses but no <code class="docutils literal notranslate"><span class="pre">if</span></code>
clauses, the length of the resulting output will be equal to the product of the
lengths of all the sequences.  If you have two lists of length 3, the output
list is 9 elements long:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">seq1</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">seq2</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
<span class="go">[(&#39;a&#39;, 1), (&#39;a&#39;, 2), (&#39;a&#39;, 3),</span>
<span class="go"> (&#39;b&#39;, 1), (&#39;b&#39;, 2), (&#39;b&#39;, 3),</span>
<span class="go"> (&#39;c&#39;, 1), (&#39;c&#39;, 2), (&#39;c&#39;, 3)]</span>
</pre></div>
</div>
<p>To avoid introducing an ambiguity into Python’s grammar, if <code class="docutils literal notranslate"><span class="pre">expression</span></code> is
creating a tuple, it must be surrounded with parentheses.  The first list
comprehension below is a syntax error, while the second one is correct:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Syntax error</span>
<span class="p">[</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
<span class="c1"># Correct</span>
<span class="p">[</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="generators">
<h2>Generators<a class="headerlink" href="#generators" title="Permalink to this headline">¶</a></h2>
<p>Generators are a special class of functions that simplify the task of writing
iterators.  Regular functions compute a value and return it, but generators
return an iterator that returns a stream of values.</p>
<p>You’re doubtless familiar with how regular function calls work in Python or C.
When you call a function, it gets a private namespace where its local variables
are created.  When the function reaches a <code class="docutils literal notranslate"><span class="pre">return</span></code> statement, the local
variables are destroyed and the value is returned to the caller.  A later call
to the same function creates a new private namespace and a fresh set of local
variables. But, what if the local variables weren’t thrown away on exiting a
function?  What if you could later resume the function where it left off?  This
is what generators provide; they can be thought of as resumable functions.</p>
<p>Here’s the simplest example of a generator function:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">i</span>
</pre></div>
</div>
<p>Any function containing a <code class="docutils literal notranslate"><span class="pre">yield</span></code> keyword is a generator function; this is
detected by Python’s <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> compiler which compiles the function
specially as a result.</p>
<p>When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression, the generator outputs the value of <code class="docutils literal notranslate"><span class="pre">i</span></code>, similar to a
<code class="docutils literal notranslate"><span class="pre">return</span></code> statement.  The big difference between <code class="docutils literal notranslate"><span class="pre">yield</span></code> and a <code class="docutils literal notranslate"><span class="pre">return</span></code>
statement is that on reaching a <code class="docutils literal notranslate"><span class="pre">yield</span></code> the generator’s state of execution is
suspended and local variables are preserved.  On the next call to the
generator’s <code class="docutils literal notranslate"><span class="pre">.next()</span></code> method, the function will resume executing.</p>
<p>Here’s a sample usage of the <code class="docutils literal notranslate"><span class="pre">generate_ints()</span></code> generator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span>
<span class="go">&lt;generator object generate_ints at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>You could equally write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></code>, or <code class="docutils literal notranslate"><span class="pre">a,b,c</span> <span class="pre">=</span>
<span class="pre">generate_ints(3)</span></code>.</p>
<p>Inside a generator function, the <code class="docutils literal notranslate"><span class="pre">return</span></code> statement can only be used without a
value, and signals the end of the procession of values; after executing a
<code class="docutils literal notranslate"><span class="pre">return</span></code> the generator cannot return any further values.  <code class="docutils literal notranslate"><span class="pre">return</span></code> with a
value, such as <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">5</span></code>, is a syntax error inside a generator function.  The
end of the generator’s results can also be indicated by raising
<code class="docutils literal notranslate"><span class="pre">StopIteration</span></code> manually, or by just letting the flow of execution fall off
the bottom of the function.</p>
<p>You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting <code class="docutils literal notranslate"><span class="pre">self.count</span></code> to
0, and having the <code class="docutils literal notranslate"><span class="pre">next()</span></code> method increment <code class="docutils literal notranslate"><span class="pre">self.count</span></code> and return it.
However, for a moderately complicated generator, writing a corresponding class
can be much messier.</p>
<p>The test suite included with Python’s library, <code class="docutils literal notranslate"><span class="pre">test_generators.py</span></code>, contains
a number of more interesting examples.  Here’s one generator that implements an
in-order traversal of a tree using generators recursively.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># A recursive generator that generates Tree leaves in in-order.</span>
<span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">t</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>

        <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>

        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
<p>Two other examples in <code class="docutils literal notranslate"><span class="pre">test_generators.py</span></code> produce solutions for the N-Queens
problem (placing N queens on an NxN chess board so that no queen threatens
another) and the Knight’s Tour (finding a route that takes a knight to every
square of an NxN chessboard without visiting any square twice).</p>
<div class="section" id="passing-values-into-a-generator">
<h3>Passing values into a generator<a class="headerlink" href="#passing-values-into-a-generator" title="Permalink to this headline">¶</a></h3>
<p>In Python 2.4 and earlier, generators only produced output.  Once a generator’s
code was invoked to create an iterator, there was no way to pass any new
information into the function when its execution is resumed.  You could hack
together this ability by making the generator look at a global variable or by
passing in some mutable object that callers then modify, but these approaches
are messy.</p>
<p>In Python 2.5 there’s a simple way to pass values into a generator.
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> became an expression, returning a value that can be assigned to
a variable or otherwise operated on:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>I recommend that you <strong>always</strong> put parentheses around a <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression
when you’re doing something with the returned value, as in the above example.
The parentheses aren’t always necessary, but it’s easier to always add them
instead of having to remember when they’re needed.</p>
<p>(PEP 342 explains the exact rules, which are that a <code class="docutils literal notranslate"><span class="pre">yield</span></code>-expression must
always be parenthesized except when it occurs at the top-level expression on the
right-hand side of an assignment.  This means you can write <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></code>
but have to use parentheses when there’s an operation, as in <code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">(yield</span> <span class="pre">i)</span>
<span class="pre">+</span> <span class="pre">12</span></code>.)</p>
<p>Values are sent into a generator by calling its <code class="docutils literal notranslate"><span class="pre">send(value)</span></code> method.  This
method resumes the generator’s code and the <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression returns the
specified value.  If the regular <code class="docutils literal notranslate"><span class="pre">next()</span></code> method is called, the <code class="docutils literal notranslate"><span class="pre">yield</span></code>
returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Here’s a simple counter that increments by 1 and allows changing the value of
the internal counter.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
        <span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
        <span class="c1"># If value provided, change counter</span>
        <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>And here’s an example of changing the counter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;t.py&quot;</span>, line <span class="m">15</span>, in <span class="n">&lt;module&gt;</span>
    <span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>Because <code class="docutils literal notranslate"><span class="pre">yield</span></code> will often be returning <code class="docutils literal notranslate"><span class="pre">None</span></code>, you should always check for
this case.  Don’t just use its value in expressions unless you’re sure that the
<code class="docutils literal notranslate"><span class="pre">send()</span></code> method will be the only method used to resume your generator
function.</p>
<p>In addition to <code class="docutils literal notranslate"><span class="pre">send()</span></code>, there are two other new methods on generators:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></code> is used to raise an exception
inside the generator; the exception is raised by the <code class="docutils literal notranslate"><span class="pre">yield</span></code> expression
where the generator’s execution is paused.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">close()</span></code> raises a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception inside the generator to
terminate the iteration.  On receiving this exception, the generator’s code
must either raise <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>; catching the
exception and doing anything else is illegal and will trigger a
<a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.  <code class="docutils literal notranslate"><span class="pre">close()</span></code> will also be called by Python’s garbage
collector when the generator is garbage-collected.</p>
<p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> occurs, I suggest
using a <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></code> suite instead of catching <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.</p>
</li>
</ul>
<p>The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.</p>
<p>Generators also become <strong>coroutines</strong>, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a <code class="docutils literal notranslate"><span class="pre">return</span></code> statement), but coroutines can be entered, exited,
and resumed at many different points (the <code class="docutils literal notranslate"><span class="pre">yield</span></code> statements).</p>
</div>
</div>
<div class="section" id="built-in-functions">
<h2>Built-in functions<a class="headerlink" href="#built-in-functions" title="Permalink to this headline">¶</a></h2>
<p>Let’s look in more detail at built-in functions often used with iterators.</p>
<p>Two of Python’s built-in functions, <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> and <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a>, are somewhat
obsolete; they duplicate the features of list comprehensions but return actual
lists instead of iterators.</p>
<p><code class="docutils literal notranslate"><span class="pre">map(f,</span> <span class="pre">iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code> returns a list containing <code class="docutils literal notranslate"><span class="pre">f(iterA[0],</span> <span class="pre">iterB[0]),</span>
<span class="pre">f(iterA[1],</span> <span class="pre">iterB[1]),</span> <span class="pre">f(iterA[2],</span> <span class="pre">iterB[2]),</span> <span class="pre">...</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">upper</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">upper</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;sentence&#39;</span><span class="p">,</span> <span class="s1">&#39;fragment&#39;</span><span class="p">])</span>
<span class="go">[&#39;SENTENCE&#39;, &#39;FRAGMENT&#39;]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">upper</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;sentence&#39;</span><span class="p">,</span> <span class="s1">&#39;fragment&#39;</span><span class="p">]]</span>
<span class="go">[&#39;SENTENCE&#39;, &#39;FRAGMENT&#39;]</span>
</pre></div>
</div>
<p>As shown above, you can achieve the same effect with a list comprehension.  The
<a class="reference internal" href="../library/itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a> function does the same thing but can handle infinite
iterators; it’ll be discussed later, in the section on the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module.</p>
<p><code class="docutils literal notranslate"><span class="pre">filter(predicate,</span> <span class="pre">iter)</span></code> returns a list that contains all the sequence
elements that meet a certain condition, and is similarly duplicated by list
comprehensions.  A <strong>predicate</strong> is a function that returns the truth value of
some condition; for use with <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a>, the predicate must take a single
value.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">filter</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p>This can also be written as a list comprehension:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="k">if</span> <span class="n">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">)]</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> also has a counterpart in the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module,
<a class="reference internal" href="../library/itertools.html#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilter()</span></code></a>, that returns an iterator and can therefore handle
infinite sequences just as <a class="reference internal" href="../library/itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a> can.</p>
<p><code class="docutils literal notranslate"><span class="pre">reduce(func,</span> <span class="pre">iter,</span> <span class="pre">[initial_value])</span></code> doesn’t have a counterpart in the
<a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module because it cumulatively performs an operation on all the
iterable’s elements and therefore can’t be applied to infinite iterables.
<code class="docutils literal notranslate"><span class="pre">func</span></code> must be a function that takes two elements and returns a single value.
<a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> takes the first two elements A and B returned by the iterator and
calculates <code class="docutils literal notranslate"><span class="pre">func(A,</span> <span class="pre">B)</span></code>.  It then requests the third element, C, calculates
<code class="docutils literal notranslate"><span class="pre">func(func(A,</span> <span class="pre">B),</span> <span class="pre">C)</span></code>, combines this result with the fourth element returned,
and continues until the iterable is exhausted.  If the iterable returns no
values at all, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.  If the initial value is
supplied, it’s used as a starting point and <code class="docutils literal notranslate"><span class="pre">func(initial_value,</span> <span class="pre">A)</span></code> is the
first calculation.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">operator</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="s1">&#39;BB&#39;</span><span class="p">,</span> <span class="s1">&#39;C&#39;</span><span class="p">])</span>
<span class="go">&#39;ABBC&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">concat</span><span class="p">,</span> <span class="p">[])</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">reduce() of empty sequence with no initial value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[],</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">1</span>
</pre></div>
</div>
<p>If you use <a class="reference internal" href="../library/operator.html#operator.add" title="operator.add"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.add()</span></code></a> with <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a>, you’ll add up all the
elements of the iterable.  This case is so common that there’s a special
built-in called <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> to compute it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">add</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([])</span>
<span class="go">0</span>
</pre></div>
</div>
<p>For many uses of <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a>, though, it can be clearer to just write the
obvious <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Instead of:</span>
<span class="n">product</span> <span class="o">=</span> <span class="n">reduce</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="mi">1</span><span class="p">)</span>

<span class="c1"># You can write:</span>
<span class="n">product</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]:</span>
    <span class="n">product</span> <span class="o">*=</span> <span class="n">i</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">enumerate(iter)</span></code> counts off the elements in the iterable, returning 2-tuples
containing the count and each element.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="s1">&#39;subject&#39;</span><span class="p">,</span> <span class="s1">&#39;verb&#39;</span><span class="p">,</span> <span class="s1">&#39;object&#39;</span><span class="p">]):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">item</span>
<span class="go">(0, &#39;subject&#39;)</span>
<span class="go">(1, &#39;verb&#39;)</span>
<span class="go">(2, &#39;object&#39;)</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> is often used when looping through a list and recording the
indexes at which certain conditions are met:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s1">&#39;Blank line at line #</span><span class="si">%i</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">i</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">sorted(iterable,</span> <span class="pre">[cmp=None],</span> <span class="pre">[key=None],</span> <span class="pre">[reverse=False])</span></code> collects all the
elements of the iterable into a list, sorts the list, and returns the sorted
result.  The <code class="docutils literal notranslate"><span class="pre">cmp</span></code>, <code class="docutils literal notranslate"><span class="pre">key</span></code>, and <code class="docutils literal notranslate"><span class="pre">reverse</span></code> arguments are passed through to
the constructed list’s <code class="docutils literal notranslate"><span class="pre">.sort()</span></code> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">random</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Generate 8 random numbers between [0, 10000)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rand_list</span> <span class="o">=</span> <span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10000</span><span class="p">),</span> <span class="mi">8</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rand_list</span>
<span class="go">[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">)</span>
<span class="go">[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">rand_list</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]</span>
</pre></div>
</div>
<p>(For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the
Python wiki at <a class="reference external" href="https://wiki.python.org/moin/HowTo/Sorting">https://wiki.python.org/moin/HowTo/Sorting</a>.)</p>
<p>The <code class="docutils literal notranslate"><span class="pre">any(iter)</span></code> and <code class="docutils literal notranslate"><span class="pre">all(iter)</span></code> built-ins look at the truth values of an
iterable’s contents.  <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if any element in the iterable is
a true value, and <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if all of the elements are true
values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">any</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">all</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="small-functions-and-the-lambda-expression">
<h2>Small functions and the lambda expression<a class="headerlink" href="#small-functions-and-the-lambda-expression" title="Permalink to this headline">¶</a></h2>
<p>When writing functional-style programs, you’ll often need little functions that
act as predicates or that combine elements in some way.</p>
<p>If there’s a Python built-in or a module function that’s suitable, you don’t
need to define a new function at all:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stripped_lines</span> <span class="o">=</span> <span class="p">[</span><span class="n">line</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">lines</span><span class="p">]</span>
<span class="n">existing_files</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">,</span> <span class="n">file_list</span><span class="p">)</span>
</pre></div>
</div>
<p>If the function you need doesn’t exist, you need to write it.  One way to write
small functions is to use the <code class="docutils literal notranslate"><span class="pre">lambda</span></code> statement.  <code class="docutils literal notranslate"><span class="pre">lambda</span></code> takes a number
of parameters and an expression combining these parameters, and creates a small
function that returns the value of the expression:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lowercase</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>

<span class="n">print_assign</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">name</span> <span class="o">+</span> <span class="s1">&#39;=&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>

<span class="n">adder</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
</pre></div>
</div>
<p>An alternative is to just use the <code class="docutils literal notranslate"><span class="pre">def</span></code> statement and define a function in the
usual way:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">lowercase</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">print_assign</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">name</span> <span class="o">+</span> <span class="s1">&#39;=&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">adder</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
</pre></div>
</div>
<p>Which alternative is preferable?  That’s a style question; my usual course is to
avoid using <code class="docutils literal notranslate"><span class="pre">lambda</span></code>.</p>
<p>One reason for my preference is that <code class="docutils literal notranslate"><span class="pre">lambda</span></code> is quite limited in the
functions it can define.  The result has to be computable as a single
expression, which means you can’t have multiway <code class="docutils literal notranslate"><span class="pre">if...</span> <span class="pre">elif...</span> <span class="pre">else</span></code>
comparisons or <code class="docutils literal notranslate"><span class="pre">try...</span> <span class="pre">except</span></code> statements.  If you try to do too much in a
<code class="docutils literal notranslate"><span class="pre">lambda</span></code> statement, you’ll end up with an overly complicated expression that’s
hard to read.  Quick, what’s the following code doing?</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">total</span> <span class="o">=</span> <span class="n">reduce</span><span class="p">(</span><span class="k">lambda</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">:</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]),</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>You can figure it out, but it takes time to disentangle the expression to figure
out what’s going on.  Using a short nested <code class="docutils literal notranslate"><span class="pre">def</span></code> statements makes things a
little bit better:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">combine</span> <span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="k">return</span> <span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">b</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>

<span class="n">total</span> <span class="o">=</span> <span class="n">reduce</span><span class="p">(</span><span class="n">combine</span><span class="p">,</span> <span class="n">items</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>But it would be best of all if I had simply used a <code class="docutils literal notranslate"><span class="pre">for</span></code> loop:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">total</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">:</span>
    <span class="n">total</span> <span class="o">+=</span> <span class="n">b</span>
</pre></div>
</div>
<p>Or the <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> built-in and a generator expression:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">b</span> <span class="k">for</span> <span class="n">a</span><span class="p">,</span><span class="n">b</span> <span class="ow">in</span> <span class="n">items</span><span class="p">)</span>
</pre></div>
</div>
<p>Many uses of <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> are clearer when written as <code class="docutils literal notranslate"><span class="pre">for</span></code> loops.</p>
<p>Fredrik Lundh once suggested the following set of rules for refactoring uses of
<code class="docutils literal notranslate"><span class="pre">lambda</span></code>:</p>
<ol class="arabic simple">
<li>Write a lambda function.</li>
<li>Write a comment explaining what the heck that lambda does.</li>
<li>Study the comment for a while, and think of a name that captures the essence
of the comment.</li>
<li>Convert the lambda to a def statement, using that name.</li>
<li>Remove the comment.</li>
</ol>
<p>I really like these rules, but you’re free to disagree
about whether this lambda-free style is better.</p>
</div>
<div class="section" id="the-itertools-module">
<h2>The itertools module<a class="headerlink" href="#the-itertools-module" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module contains a number of commonly-used iterators as well
as functions for combining several iterators.  This section will introduce the
module’s contents by showing small examples.</p>
<p>The module’s functions fall into a few broad classes:</p>
<ul class="simple">
<li>Functions that create a new iterator based on an existing iterator.</li>
<li>Functions for treating an iterator’s elements as function arguments.</li>
<li>Functions for selecting portions of an iterator’s output.</li>
<li>A function for grouping an iterator’s output.</li>
</ul>
<div class="section" id="creating-new-iterators">
<h3>Creating new iterators<a class="headerlink" href="#creating-new-iterators" title="Permalink to this headline">¶</a></h3>
<p><code class="docutils literal notranslate"><span class="pre">itertools.count(n)</span></code> returns an infinite stream of integers, increasing by 1
each time.  You can optionally supply the starting number, which defaults to 0:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">17</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.cycle(iter)</span></code> saves a copy of the contents of a provided iterable
and returns a new iterator that returns its elements from first to last.  The
new iterator will repeat these elements infinitely.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">cycle</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.repeat(elem,</span> <span class="pre">[n])</span></code> returns the provided element <code class="docutils literal notranslate"><span class="pre">n</span></code> times, or
returns the element endlessly if <code class="docutils literal notranslate"><span class="pre">n</span></code> is not provided.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="o">...</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span><span class="p">,</span> <span class="n">abc</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.chain(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code> takes an arbitrary number of iterables as
input, and returns all the elements of the first iterator, then all the elements
of the second, and so on, until all of the iterables have been exhausted.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">chain</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.izip(iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code> takes one element from each iterable and
returns them in a tuple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">izip</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>It’s similar to the built-in <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> function, but doesn’t construct an
in-memory list and exhaust all the input iterators before returning; instead
tuples are constructed and returned only if they’re requested.  (The technical
term for this behaviour is <a class="reference external" href="http://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>.)</p>
<p>This iterator is intended to be used with iterables that are all of the same
length.  If the iterables are of different lengths, the resulting stream will be
the same length as the shortest iterable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">izip</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">],</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>You should avoid doing this, though, because an element may be taken from the
longer iterators and discarded.  This means you can’t go on to use the iterators
further because you risk skipping a discarded element.</p>
<p><code class="docutils literal notranslate"><span class="pre">itertools.islice(iter,</span> <span class="pre">[start],</span> <span class="pre">stop,</span> <span class="pre">[step])</span></code> returns a stream that’s a
slice of the iterator.  With a single <code class="docutils literal notranslate"><span class="pre">stop</span></code> argument, it will return the
first <code class="docutils literal notranslate"><span class="pre">stop</span></code> elements.  If you supply a starting index, you’ll get
<code class="docutils literal notranslate"><span class="pre">stop-start</span></code> elements, and if you supply a value for <code class="docutils literal notranslate"><span class="pre">step</span></code>, elements will
be skipped accordingly.  Unlike Python’s string and list slicing, you can’t use
negative values for <code class="docutils literal notranslate"><span class="pre">start</span></code>, <code class="docutils literal notranslate"><span class="pre">stop</span></code>, or <code class="docutils literal notranslate"><span class="pre">step</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">8</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.tee(iter,</span> <span class="pre">[n])</span></code> replicates an iterator; it returns <code class="docutils literal notranslate"><span class="pre">n</span></code>
independent iterators that will all return the contents of the source iterator.
If you don’t supply a value for <code class="docutils literal notranslate"><span class="pre">n</span></code>, the default is 2.  Replicating iterators
requires saving some of the contents of the source iterator, so this can consume
significant memory if the iterator is large and one of the new iterators is
consumed more than the others.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">tee</span><span class="p">(</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="p">)</span> <span class="o">=&gt;</span>
   <span class="n">iterA</span><span class="p">,</span> <span class="n">iterB</span>

<span class="n">where</span> <span class="n">iterA</span> <span class="o">-&gt;</span>
   <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>

<span class="ow">and</span>   <span class="n">iterB</span> <span class="o">-&gt;</span>
   <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions-on-elements">
<h3>Calling functions on elements<a class="headerlink" href="#calling-functions-on-elements" title="Permalink to this headline">¶</a></h3>
<p>Two functions are used for calling other functions on the contents of an
iterable.</p>
<p><code class="docutils literal notranslate"><span class="pre">itertools.imap(f,</span> <span class="pre">iterA,</span> <span class="pre">iterB,</span> <span class="pre">...)</span></code> returns a stream containing
<code class="docutils literal notranslate"><span class="pre">f(iterA[0],</span> <span class="pre">iterB[0]),</span> <span class="pre">f(iterA[1],</span> <span class="pre">iterB[1]),</span> <span class="pre">f(iterA[2],</span> <span class="pre">iterB[2]),</span> <span class="pre">...</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">add</span><span class="p">,</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">8</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">operator</span></code> module contains a set of functions corresponding to Python’s
operators.  Some examples are <code class="docutils literal notranslate"><span class="pre">operator.add(a,</span> <span class="pre">b)</span></code> (adds two values),
<code class="docutils literal notranslate"><span class="pre">operator.ne(a,</span> <span class="pre">b)</span></code> (same as <code class="docutils literal notranslate"><span class="pre">a!=b</span></code>), and <code class="docutils literal notranslate"><span class="pre">operator.attrgetter('id')</span></code>
(returns a callable that fetches the <code class="docutils literal notranslate"><span class="pre">&quot;id&quot;</span></code> attribute).</p>
<p><code class="docutils literal notranslate"><span class="pre">itertools.starmap(func,</span> <span class="pre">iter)</span></code> assumes that the iterable will return a stream
of tuples, and calls <code class="docutils literal notranslate"><span class="pre">f()</span></code> using these tuples as the arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">starmap</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">,</span>
                  <span class="p">[(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;java&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;/bin&#39;</span><span class="p">,</span> <span class="s1">&#39;python&#39;</span><span class="p">),</span>
                   <span class="p">(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;perl&#39;</span><span class="p">),(</span><span class="s1">&#39;/usr&#39;</span><span class="p">,</span> <span class="s1">&#39;bin&#39;</span><span class="p">,</span> <span class="s1">&#39;ruby&#39;</span><span class="p">)])</span>
<span class="o">=&gt;</span>
  <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">java</span><span class="p">,</span> <span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">python</span><span class="p">,</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">perl</span><span class="p">,</span> <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">ruby</span>
</pre></div>
</div>
</div>
<div class="section" id="selecting-elements">
<h3>Selecting elements<a class="headerlink" href="#selecting-elements" title="Permalink to this headline">¶</a></h3>
<p>Another group of functions chooses a subset of an iterator’s elements based on a
predicate.</p>
<p><code class="docutils literal notranslate"><span class="pre">itertools.ifilter(predicate,</span> <span class="pre">iter)</span></code> returns all the elements for which the
predicate returns true:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">ifilter</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.ifilterfalse(predicate,</span> <span class="pre">iter)</span></code> is the opposite, returning all
elements for which the predicate returns false:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">ifilterfalse</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.takewhile(predicate,</span> <span class="pre">iter)</span></code> returns elements for as long as the
predicate returns true.  Once the predicate returns false, the iterator will
signal the end of its results.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">less_than_10</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">)</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">takewhile</span><span class="p">(</span><span class="n">less_than_10</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">takewhile</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">0</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.dropwhile(predicate,</span> <span class="pre">iter)</span></code> discards elements while the predicate
returns true, and then returns the rest of the iterable’s results.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">dropwhile</span><span class="p">(</span><span class="n">less_than_10</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">17</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">19</span><span class="p">,</span> <span class="o">...</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">dropwhile</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">())</span> <span class="o">=&gt;</span>
  <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="grouping-elements">
<h3>Grouping elements<a class="headerlink" href="#grouping-elements" title="Permalink to this headline">¶</a></h3>
<p>The last function I’ll discuss, <code class="docutils literal notranslate"><span class="pre">itertools.groupby(iter,</span> <span class="pre">key_func=None)</span></code>, is
the most complicated.  <code class="docutils literal notranslate"><span class="pre">key_func(elem)</span></code> is a function that can compute a key
value for each element returned by the iterable.  If you don’t supply a key
function, the key is simply each element itself.</p>
<p><code class="docutils literal notranslate"><span class="pre">groupby()</span></code> collects all the consecutive elements from the underlying iterable
that have the same key value, and returns a stream of 2-tuples containing a key
value and an iterator for the elements with that key.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">city_list</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Decatur&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Huntsville&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Selma&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;Anchorage&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Nome&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;Flagstaff&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Phoenix&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Tucson&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span>
             <span class="o">...</span>
            <span class="p">]</span>

<span class="k">def</span> <span class="nf">get_state</span> <span class="p">((</span><span class="n">city</span><span class="p">,</span> <span class="n">state</span><span class="p">)):</span>
    <span class="k">return</span> <span class="n">state</span>

<span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">city_list</span><span class="p">,</span> <span class="n">get_state</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;AL&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">1</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;AK&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">2</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;AZ&#39;</span><span class="p">,</span> <span class="n">iterator</span><span class="o">-</span><span class="mi">3</span><span class="p">),</span> <span class="o">...</span>

<span class="n">where</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">1</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Decatur&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Huntsville&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Selma&#39;</span><span class="p">,</span> <span class="s1">&#39;AL&#39;</span><span class="p">)</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">2</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Anchorage&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Nome&#39;</span><span class="p">,</span> <span class="s1">&#39;AK&#39;</span><span class="p">)</span>
<span class="n">iterator</span><span class="o">-</span><span class="mi">3</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;Flagstaff&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Phoenix&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;Tucson&#39;</span><span class="p">,</span> <span class="s1">&#39;AZ&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">groupby()</span></code> assumes that the underlying iterable’s contents will already be
sorted based on the key.  Note that the returned iterators also use the
underlying iterable, so you have to consume the results of iterator-1 before
requesting iterator-2 and its corresponding key.</p>
</div>
</div>
<div class="section" id="the-functools-module">
<h2>The functools module<a class="headerlink" href="#the-functools-module" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module in Python 2.5 contains some higher-order functions.
A <strong>higher-order function</strong> takes one or more functions as input and returns a
new function.  The most useful tool in this module is the
<a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a> function.</p>
<p>For programs written in a functional style, you’ll sometimes want to construct
variants of existing functions that have some of the parameters filled in.
Consider a Python function <code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>; you may wish to create a new function
<code class="docutils literal notranslate"><span class="pre">g(b,</span> <span class="pre">c)</span></code> that’s equivalent to <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>; you’re filling in a value for
one of <code class="docutils literal notranslate"><span class="pre">f()</span></code>’s parameters.  This is called “partial function application”.</p>
<p>The constructor for <code class="docutils literal notranslate"><span class="pre">partial</span></code> takes the arguments <code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span>
<span class="pre">...</span> <span class="pre">kwarg1=value1,</span> <span class="pre">kwarg2=value2)</span></code>.  The resulting object is callable, so you
can just call it to invoke <code class="docutils literal notranslate"><span class="pre">function</span></code> with the filled-in arguments.</p>
<p>Here’s a small but realistic example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>

<span class="k">def</span> <span class="nf">log</span> <span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span>
    <span class="s2">&quot;Write the contents of &#39;message&#39; to the specified subsystem.&quot;</span>
    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span>
    <span class="o">...</span>

<span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
<span class="n">server_log</span><span class="p">(</span><span class="s1">&#39;Unable to open socket&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="the-operator-module">
<h3>The operator module<a class="headerlink" href="#the-operator-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module was mentioned earlier.  It contains a set of
functions corresponding to Python’s operators.  These functions are often useful
in functional-style code because they save you from writing trivial functions
that perform a single operation.</p>
<p>Some of the functions in this module are:</p>
<ul class="simple">
<li>Math operations: <code class="docutils literal notranslate"><span class="pre">add()</span></code>, <code class="docutils literal notranslate"><span class="pre">sub()</span></code>, <code class="docutils literal notranslate"><span class="pre">mul()</span></code>, <code class="docutils literal notranslate"><span class="pre">div()</span></code>, <code class="docutils literal notranslate"><span class="pre">floordiv()</span></code>,
<code class="docutils literal notranslate"><span class="pre">abs()</span></code>, …</li>
<li>Logical operations: <code class="docutils literal notranslate"><span class="pre">not_()</span></code>, <code class="docutils literal notranslate"><span class="pre">truth()</span></code>.</li>
<li>Bitwise operations: <code class="docutils literal notranslate"><span class="pre">and_()</span></code>, <code class="docutils literal notranslate"><span class="pre">or_()</span></code>, <code class="docutils literal notranslate"><span class="pre">invert()</span></code>.</li>
<li>Comparisons: <code class="docutils literal notranslate"><span class="pre">eq()</span></code>, <code class="docutils literal notranslate"><span class="pre">ne()</span></code>, <code class="docutils literal notranslate"><span class="pre">lt()</span></code>, <code class="docutils literal notranslate"><span class="pre">le()</span></code>, <code class="docutils literal notranslate"><span class="pre">gt()</span></code>, and <code class="docutils literal notranslate"><span class="pre">ge()</span></code>.</li>
<li>Object identity: <code class="docutils literal notranslate"><span class="pre">is_()</span></code>, <code class="docutils literal notranslate"><span class="pre">is_not()</span></code>.</li>
</ul>
<p>Consult the operator module’s documentation for a complete list.</p>
</div>
</div>
<div class="section" id="revision-history-and-acknowledgements">
<h2>Revision History and Acknowledgements<a class="headerlink" href="#revision-history-and-acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Ian Bicking,
Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro
Lameiro, Jussi Salmela, Collin Winter, Blake Winton.</p>
<p>Version 0.1: posted June 30 2006.</p>
<p>Version 0.11: posted July 1 2006.  Typo fixes.</p>
<p>Version 0.2: posted July 10 2006.  Merged genexp and listcomp sections into one.
Typo fixes.</p>
<p>Version 0.21: Added more references suggested on the tutor mailing list.</p>
<p>Version 0.30: Adds a section on the <code class="docutils literal notranslate"><span class="pre">functional</span></code> module written by Collin
Winter; adds short section on the operator module; a few other edits.</p>
</div>
<div class="section" id="references">
<h2>References<a class="headerlink" href="#references" title="Permalink to this headline">¶</a></h2>
<div class="section" id="general">
<h3>General<a class="headerlink" href="#general" title="Permalink to this headline">¶</a></h3>
<p><strong>Structure and Interpretation of Computer Programs</strong>, by Harold Abelson and
Gerald Jay Sussman with Julie Sussman.  Full text at
<a class="reference external" href="https://mitpress.mit.edu/sicp/">https://mitpress.mit.edu/sicp/</a>.  In this classic textbook of computer science,
chapters 2 and 3 discuss the use of sequences and streams to organize the data
flow inside a program.  The book uses Scheme for its examples, but many of the
design approaches described in these chapters are applicable to functional-style
Python code.</p>
<p><a class="reference external" href="http://www.defmacro.org/ramblings/fp.html">http://www.defmacro.org/ramblings/fp.html</a>: A general introduction to functional
programming that uses Java examples and has a lengthy historical introduction.</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Functional_programming">https://en.wikipedia.org/wiki/Functional_programming</a>: General Wikipedia entry
describing functional programming.</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a>: Entry for coroutines.</p>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Currying">https://en.wikipedia.org/wiki/Currying</a>: Entry for the concept of currying.</p>
</div>
<div class="section" id="python-specific">
<h3>Python-specific<a class="headerlink" href="#python-specific" title="Permalink to this headline">¶</a></h3>
<p><a class="reference external" href="http://gnosis.cx/TPiP/">http://gnosis.cx/TPiP/</a>: The first chapter of David Mertz’s book
<cite>Text Processing in Python</cite> discusses functional programming
for text processing, in the section titled “Utilizing Higher-Order Functions in
Text Processing”.</p>
<p>Mertz also wrote a 3-part series of articles on functional programming
for IBM’s DeveloperWorks site; see</p>
<p><a class="reference external" href="https://www.ibm.com/developerworks/linux/library/l-prog/index.html">part 1</a>,
<a class="reference external" href="https://www.ibm.com/developerworks/linux/library/l-prog2/index.html">part 2</a>, and
<a class="reference external" href="https://www.ibm.com/developerworks/linux/library/l-prog3/index.html">part 3</a>,</p>
</div>
<div class="section" id="python-documentation">
<h3>Python documentation<a class="headerlink" href="#python-documentation" title="Permalink to this headline">¶</a></h3>
<p>Documentation for the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module.</p>
<p>Documentation for the <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module.</p>
<p><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a>: “Generator Expressions”</p>
<p><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a>: “Coroutines via Enhanced Generators” describes the new generator
features in Python 2.5.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Functional Programming HOWTO</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a><ul>
<li><a class="reference internal" href="#formal-provability">Formal provability</a></li>
<li><a class="reference internal" href="#modularity">Modularity</a></li>
<li><a class="reference internal" href="#ease-of-debugging-and-testing">Ease of debugging and testing</a></li>
<li><a class="reference internal" href="#composability">Composability</a></li>
</ul>
</li>
<li><a class="reference internal" href="#iterators">Iterators</a><ul>
<li><a class="reference internal" href="#data-types-that-support-iterators">Data Types That Support Iterators</a></li>
</ul>
</li>
<li><a class="reference internal" href="#generator-expressions-and-list-comprehensions">Generator expressions and list comprehensions</a></li>
<li><a class="reference internal" href="#generators">Generators</a><ul>
<li><a class="reference internal" href="#passing-values-into-a-generator">Passing values into a generator</a></li>
</ul>
</li>
<li><a class="reference internal" href="#built-in-functions">Built-in functions</a></li>
<li><a class="reference internal" href="#small-functions-and-the-lambda-expression">Small functions and the lambda expression</a></li>
<li><a class="reference internal" href="#the-itertools-module">The itertools module</a><ul>
<li><a class="reference internal" href="#creating-new-iterators">Creating new iterators</a></li>
<li><a class="reference internal" href="#calling-functions-on-elements">Calling functions on elements</a></li>
<li><a class="reference internal" href="#selecting-elements">Selecting elements</a></li>
<li><a class="reference internal" href="#grouping-elements">Grouping elements</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-functools-module">The functools module</a><ul>
<li><a class="reference internal" href="#the-operator-module">The operator module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#revision-history-and-acknowledgements">Revision History and Acknowledgements</a></li>
<li><a class="reference internal" href="#references">References</a><ul>
<li><a class="reference internal" href="#general">General</a></li>
<li><a class="reference internal" href="#python-specific">Python-specific</a></li>
<li><a class="reference internal" href="#python-documentation">Python documentation</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="doanddont.html"
                        title="previous chapter">Idioms and Anti-Idioms in Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging.html"
                        title="next chapter">Logging HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/functional.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="doanddont.html" title="Idioms and Anti-Idioms in Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�6C���html/howto/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python HOWTOs &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Porting Python 2 Code to Python 3" href="pyporting.html" />
    <link rel="prev" title="Installing Python Modules" href="../installing/index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyporting.html" title="Porting Python 2 Code to Python 3"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../installing/index.html" title="Installing Python Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-howtos">
<h1>Python HOWTOs<a class="headerlink" href="#python-howtos" title="Permalink to this headline">¶</a></h1>
<p>Python HOWTOs are documents that cover a single, specific topic,
and attempt to cover it fairly completely. Modelled on the Linux
Documentation Project’s HOWTO collection, this collection is an
effort to foster documentation that’s more detailed than the
Python Library Reference.</p>
<p>Currently, the HOWTOs are:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="pyporting.html">Porting Python 2 Code to Python 3</a></li>
<li class="toctree-l1"><a class="reference internal" href="cporting.html">Porting Extension Modules to Python 3</a></li>
<li class="toctree-l1"><a class="reference internal" href="curses.html">Curses Programming with Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="descriptor.html">Descriptor HowTo Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="doanddont.html">Idioms and Anti-Idioms in Python</a></li>
<li class="toctree-l1"><a class="reference internal" href="functional.html">Functional Programming HOWTO</a></li>
<li class="toctree-l1"><a class="reference internal" href="logging.html">Logging HOWTO</a></li>
<li class="toctree-l1"><a class="reference internal" href="logging-cookbook.html">Logging Cookbook</a></li>
<li class="toctree-l1"><a class="reference internal" href="regex.html">Regular Expression HOWTO</a></li>
<li class="toctree-l1"><a class="reference internal" href="sockets.html">Socket Programming HOWTO</a></li>
<li class="toctree-l1"><a class="reference internal" href="sorting.html">Sorting HOW TO</a></li>
<li class="toctree-l1"><a class="reference internal" href="unicode.html">Unicode HOWTO</a></li>
<li class="toctree-l1"><a class="reference internal" href="urllib2.html">HOWTO Fetch Internet Resources Using urllib2</a></li>
<li class="toctree-l1"><a class="reference internal" href="webservers.html">HOWTO Use Python in the web</a></li>
<li class="toctree-l1"><a class="reference internal" href="argparse.html">Argparse Tutorial</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../installing/index.html"
                        title="previous chapter">Installing Python Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pyporting.html"
                        title="next chapter">Porting Python 2 Code to Python 3</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyporting.html" title="Porting Python 2 Code to Python 3"
             >next</a> |</li>
        <li class="right" >
          <a href="../installing/index.html" title="Installing Python Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ށ�_�/�/ html/howto/logging-cookbook.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logging Cookbook &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Regular Expression HOWTO" href="regex.html" />
    <link rel="prev" title="Logging HOWTO" href="logging.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/logging-cookbook.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="logging-cookbook">
<span id="id1"></span><h1>Logging Cookbook<a class="headerlink" href="#logging-cookbook" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</td>
</tr>
</tbody>
</table>
<p>This page contains a number of recipes related to logging, which have been found
useful in the past.</p>
<div class="section" id="using-logging-in-multiple-modules">
<h2>Using logging in multiple modules<a class="headerlink" href="#using-logging-in-multiple-modules" title="Permalink to this headline">¶</a></h2>
<p>Multiple calls to <code class="docutils literal notranslate"><span class="pre">logging.getLogger('someLogger')</span></code> return a reference to the
same logger object.  This is true not only within the same module, but also
across modules as long as it is in the same Python interpreter process.  It is
true for references to the same object; additionally, application code can
define and configure a parent logger in one module and create (but not
configure) a child logger in a separate module, and all logger calls to the
child will pass up to the parent.  Here is a main module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">auxiliary_module</span>

<span class="c1"># create logger with &#39;spam_application&#39;</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;spam_application&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create file handler which logs even debug messages</span>
<span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s1">&#39;spam.log&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create console handler with a higher log level</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">)</span>
<span class="c1"># create formatter and add it to the handlers</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c1"># add the handlers to the logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>

<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;creating an instance of auxiliary_module.Auxiliary&#39;</span><span class="p">)</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;created an instance of auxiliary_module.Auxiliary&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;calling auxiliary_module.Auxiliary.do_something&#39;</span><span class="p">)</span>
<span class="n">a</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;finished auxiliary_module.Auxiliary.do_something&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;calling auxiliary_module.some_function()&#39;</span><span class="p">)</span>
<span class="n">auxiliary_module</span><span class="o">.</span><span class="n">some_function</span><span class="p">()</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;done with auxiliary_module.some_function()&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here is the auxiliary module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="c1"># create logger</span>
<span class="n">module_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;spam_application.auxiliary&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Auxiliary</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;spam_application.auxiliary.Auxiliary&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;creating an instance of Auxiliary&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">do_something</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;doing something&#39;</span><span class="p">)</span>
        <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;done doing something&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">some_function</span><span class="p">():</span>
    <span class="n">module_logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;received a call to &quot;some_function&quot;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The output looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">663</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">creating</span> <span class="n">an</span> <span class="n">instance</span> <span class="n">of</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">665</span> <span class="o">-</span> <span class="n">spam_application</span><span class="o">.</span><span class="n">auxiliary</span><span class="o">.</span><span class="n">Auxiliary</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">creating</span> <span class="n">an</span> <span class="n">instance</span> <span class="n">of</span> <span class="n">Auxiliary</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">665</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">created</span> <span class="n">an</span> <span class="n">instance</span> <span class="n">of</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">668</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">calling</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span><span class="o">.</span><span class="n">do_something</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">668</span> <span class="o">-</span> <span class="n">spam_application</span><span class="o">.</span><span class="n">auxiliary</span><span class="o">.</span><span class="n">Auxiliary</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">doing</span> <span class="n">something</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">669</span> <span class="o">-</span> <span class="n">spam_application</span><span class="o">.</span><span class="n">auxiliary</span><span class="o">.</span><span class="n">Auxiliary</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">done</span> <span class="n">doing</span> <span class="n">something</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">670</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">finished</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">Auxiliary</span><span class="o">.</span><span class="n">do_something</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">671</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">calling</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">some_function</span><span class="p">()</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">672</span> <span class="o">-</span> <span class="n">spam_application</span><span class="o">.</span><span class="n">auxiliary</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">received</span> <span class="n">a</span> <span class="n">call</span> <span class="n">to</span> <span class="s1">&#39;some_function&#39;</span>
<span class="mi">2005</span><span class="o">-</span><span class="mi">03</span><span class="o">-</span><span class="mi">23</span> <span class="mi">23</span><span class="p">:</span><span class="mi">47</span><span class="p">:</span><span class="mi">11</span><span class="p">,</span><span class="mi">673</span> <span class="o">-</span> <span class="n">spam_application</span> <span class="o">-</span> <span class="n">INFO</span> <span class="o">-</span>
   <span class="n">done</span> <span class="k">with</span> <span class="n">auxiliary_module</span><span class="o">.</span><span class="n">some_function</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="logging-from-multiple-threads">
<h2>Logging from multiple threads<a class="headerlink" href="#logging-from-multiple-threads" title="Permalink to this headline">¶</a></h2>
<p>Logging from multiple threads requires no special effort. The following example
shows logging from the main (initIal) thread and another thread:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">threading</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span>
    <span class="k">while</span> <span class="ow">not</span> <span class="n">arg</span><span class="p">[</span><span class="s1">&#39;stop&#39;</span><span class="p">]:</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Hi from myfunc&#39;</span><span class="p">)</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(relativeCreated)6d</span><span class="s1"> </span><span class="si">%(threadName)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">info</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;stop&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">}</span>
    <span class="n">thread</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">worker</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">info</span><span class="p">,))</span>
    <span class="n">thread</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Hello from main&#39;</span><span class="p">)</span>
            <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.75</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
            <span class="n">info</span><span class="p">[</span><span class="s1">&#39;stop&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="kc">True</span>
            <span class="k">break</span>
    <span class="n">thread</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>When run, the script should print something like the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>   <span class="mi">0</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
   <span class="mi">3</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
 <span class="mi">505</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
 <span class="mi">755</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">1007</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">1507</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">1508</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">2010</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">2258</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">2512</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">3009</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">3013</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">3515</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">3761</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">4017</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
<span class="mi">4513</span> <span class="n">MainThread</span> <span class="n">Hello</span> <span class="kn">from</span> <span class="nn">main</span>
<span class="mi">4518</span> <span class="n">Thread</span><span class="o">-</span><span class="mi">1</span> <span class="n">Hi</span> <span class="kn">from</span> <span class="nn">myfunc</span>
</pre></div>
</div>
<p>This shows the logging output interspersed as one might expect. This approach
works for more threads than shown here, of course.</p>
</div>
<div class="section" id="multiple-handlers-and-formatters">
<h2>Multiple handlers and formatters<a class="headerlink" href="#multiple-handlers-and-formatters" title="Permalink to this headline">¶</a></h2>
<p>Loggers are plain Python objects.  The <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addHandler()</span></code></a> method has no
minimum or maximum quota for the number of handlers you may add.  Sometimes it
will be beneficial for an application to log all messages of all severities to a
text file while simultaneously logging errors or above to the console.  To set
this up, simply configure the appropriate handlers.  The logging calls in the
application code will remain unchanged.  Here is a slight modification to the
previous simple module-based configuration example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simple_example&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create file handler which logs even debug messages</span>
<span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s1">&#39;spam.log&#39;</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="c1"># create console handler with a higher log level</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">)</span>
<span class="c1"># create formatter and add it to the handlers</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="n">fh</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c1"># add the handlers to logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</span>

<span class="c1"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that the ‘application’ code does not care about multiple handlers.  All
that changed was the addition and configuration of a new handler named <em>fh</em>.</p>
<p>The ability to create new handlers with higher- or lower-severity filters can be
very helpful when writing and testing an application.  Instead of using many
<code class="docutils literal notranslate"><span class="pre">print</span></code> statements for debugging, use <code class="docutils literal notranslate"><span class="pre">logger.debug</span></code>: Unlike the print
statements, which you will have to delete or comment out later, the logger.debug
statements can remain intact in the source code and remain dormant until you
need them again.  At that time, the only change that needs to happen is to
modify the severity level of the logger and/or handler to debug.</p>
</div>
<div class="section" id="logging-to-multiple-destinations">
<span id="multiple-destinations"></span><h2>Logging to multiple destinations<a class="headerlink" href="#logging-to-multiple-destinations" title="Permalink to this headline">¶</a></h2>
<p>Let’s say you want to log to console and file with different message formats and
in differing circumstances. Say you want to log messages with levels of DEBUG
and higher to file, and those messages at level INFO and higher to the console.
Let’s also assume that the file should contain timestamps, but the console
messages should not. Here’s how you can achieve this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="c1"># set up logging to file - see previous section for more details</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span>
                    <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(name)-12s</span><span class="s1"> </span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span>
                    <span class="n">datefmt</span><span class="o">=</span><span class="s1">&#39;%m-</span><span class="si">%d</span><span class="s1"> %H:%M&#39;</span><span class="p">,</span>
                    <span class="n">filename</span><span class="o">=</span><span class="s1">&#39;/temp/myapp.log&#39;</span><span class="p">,</span>
                    <span class="n">filemode</span><span class="o">=</span><span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="c1"># define a Handler which writes INFO messages or higher to the sys.stderr</span>
<span class="n">console</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">console</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
<span class="c1"># set a format which is simpler for console use</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(name)-12s</span><span class="s1">: </span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="c1"># tell the handler to use this format</span>
<span class="n">console</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>
<span class="c1"># add the handler to the root logger</span>
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">console</span><span class="p">)</span>

<span class="c1"># Now, we can log to the root logger, or any other logger. First the root...</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Jackdaws love my big sphinx of quartz.&#39;</span><span class="p">)</span>

<span class="c1"># Now, define a couple of other loggers which might represent areas in your</span>
<span class="c1"># application:</span>

<span class="n">logger1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;myapp.area1&#39;</span><span class="p">)</span>
<span class="n">logger2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;myapp.area2&#39;</span><span class="p">)</span>

<span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Quick zephyrs blow, vexing daft Jim.&#39;</span><span class="p">)</span>
<span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;How quickly daft jumping zebras vex.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Jail zesty vixen who grabbed pay from quack.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;The five boxing wizards jump quickly.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>When you run this, on the console you will see</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">root</span>        <span class="p">:</span> <span class="n">INFO</span>     <span class="n">Jackdaws</span> <span class="n">love</span> <span class="n">my</span> <span class="n">big</span> <span class="n">sphinx</span> <span class="n">of</span> <span class="n">quartz</span><span class="o">.</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">area1</span> <span class="p">:</span> <span class="n">INFO</span>     <span class="n">How</span> <span class="n">quickly</span> <span class="n">daft</span> <span class="n">jumping</span> <span class="n">zebras</span> <span class="n">vex</span><span class="o">.</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">area2</span> <span class="p">:</span> <span class="n">WARNING</span>  <span class="n">Jail</span> <span class="n">zesty</span> <span class="n">vixen</span> <span class="n">who</span> <span class="n">grabbed</span> <span class="n">pay</span> <span class="kn">from</span> <span class="nn">quack.</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">area2</span> <span class="p">:</span> <span class="n">ERROR</span>    <span class="n">The</span> <span class="n">five</span> <span class="n">boxing</span> <span class="n">wizards</span> <span class="n">jump</span> <span class="n">quickly</span><span class="o">.</span>
</pre></div>
</div>
<p>and in the file you will see something like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">10</span><span class="o">-</span><span class="mi">22</span> <span class="mi">22</span><span class="p">:</span><span class="mi">19</span> <span class="n">root</span>         <span class="n">INFO</span>     <span class="n">Jackdaws</span> <span class="n">love</span> <span class="n">my</span> <span class="n">big</span> <span class="n">sphinx</span> <span class="n">of</span> <span class="n">quartz</span><span class="o">.</span>
<span class="mi">10</span><span class="o">-</span><span class="mi">22</span> <span class="mi">22</span><span class="p">:</span><span class="mi">19</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area1</span>  <span class="n">DEBUG</span>    <span class="n">Quick</span> <span class="n">zephyrs</span> <span class="n">blow</span><span class="p">,</span> <span class="n">vexing</span> <span class="n">daft</span> <span class="n">Jim</span><span class="o">.</span>
<span class="mi">10</span><span class="o">-</span><span class="mi">22</span> <span class="mi">22</span><span class="p">:</span><span class="mi">19</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area1</span>  <span class="n">INFO</span>     <span class="n">How</span> <span class="n">quickly</span> <span class="n">daft</span> <span class="n">jumping</span> <span class="n">zebras</span> <span class="n">vex</span><span class="o">.</span>
<span class="mi">10</span><span class="o">-</span><span class="mi">22</span> <span class="mi">22</span><span class="p">:</span><span class="mi">19</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area2</span>  <span class="n">WARNING</span>  <span class="n">Jail</span> <span class="n">zesty</span> <span class="n">vixen</span> <span class="n">who</span> <span class="n">grabbed</span> <span class="n">pay</span> <span class="kn">from</span> <span class="nn">quack.</span>
<span class="mi">10</span><span class="o">-</span><span class="mi">22</span> <span class="mi">22</span><span class="p">:</span><span class="mi">19</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area2</span>  <span class="n">ERROR</span>    <span class="n">The</span> <span class="n">five</span> <span class="n">boxing</span> <span class="n">wizards</span> <span class="n">jump</span> <span class="n">quickly</span><span class="o">.</span>
</pre></div>
</div>
<p>As you can see, the DEBUG message only shows up in the file. The other messages
are sent to both destinations.</p>
<p>This example uses console and file handlers, but you can use any number and
combination of handlers you choose.</p>
</div>
<div class="section" id="configuration-server-example">
<h2>Configuration server example<a class="headerlink" href="#configuration-server-example" title="Permalink to this headline">¶</a></h2>
<p>Here is an example of a module using the logging configuration server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="c1"># read initial config file</span>
<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s1">&#39;logging.conf&#39;</span><span class="p">)</span>

<span class="c1"># create and start listener on port 9999</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">9999</span><span class="p">)</span>
<span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simpleExample&#39;</span><span class="p">)</span>

<span class="k">try</span><span class="p">:</span>
    <span class="c1"># loop through logging calls to see the difference</span>
    <span class="c1"># new configurations make, until Ctrl+C is pressed</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
    <span class="c1"># cleanup</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">stopListening</span><span class="p">()</span>
    <span class="n">t</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>And here is a script that takes a filename and sends that file to the server,
properly preceded with the binary-encoded length, as the new logging
configuration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">struct</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">data_to_send</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;localhost&#39;</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">9999</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;connecting...&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;sending config...&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;&gt;L&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)))</span>
<span class="n">s</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data_to_send</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s1">&#39;complete&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="sending-and-receiving-logging-events-across-a-network">
<span id="network-logging"></span><h2>Sending and receiving logging events across a network<a class="headerlink" href="#sending-and-receiving-logging-events-across-a-network" title="Permalink to this headline">¶</a></h2>
<p>Let’s say you want to send logging events across a network, and handle them at
the receiving end. A simple way of doing this is attaching a
<code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code> instance to the root logger at the sending end:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span><span class="o">,</span> <span class="nn">logging.handlers</span>

<span class="n">rootLogger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="n">rootLogger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">socketHandler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">SocketHandler</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span>
                    <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">)</span>
<span class="c1"># don&#39;t bother with a formatter, since a socket handler sends the event as</span>
<span class="c1"># an unformatted pickle</span>
<span class="n">rootLogger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">socketHandler</span><span class="p">)</span>

<span class="c1"># Now, we can log to the root logger, or any other logger. First the root...</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Jackdaws love my big sphinx of quartz.&#39;</span><span class="p">)</span>

<span class="c1"># Now, define a couple of other loggers which might represent areas in your</span>
<span class="c1"># application:</span>

<span class="n">logger1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;myapp.area1&#39;</span><span class="p">)</span>
<span class="n">logger2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;myapp.area2&#39;</span><span class="p">)</span>

<span class="n">logger1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Quick zephyrs blow, vexing daft Jim.&#39;</span><span class="p">)</span>
<span class="n">logger1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;How quickly daft jumping zebras vex.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Jail zesty vixen who grabbed pay from quack.&#39;</span><span class="p">)</span>
<span class="n">logger2</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;The five boxing wizards jump quickly.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>At the receiving end, you can set up a receiver using the <a class="reference internal" href="../library/socketserver.html#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a>
module. Here is a basic working example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.handlers</span>
<span class="kn">import</span> <span class="nn">SocketServer</span>
<span class="kn">import</span> <span class="nn">struct</span>


<span class="k">class</span> <span class="nc">LogRecordStreamHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">StreamRequestHandler</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Handler for a streaming logging request.</span>

<span class="sd">    This basically logs the record using whatever logging policy is</span>
<span class="sd">    configured locally.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Handle multiple requests - each expected to be a 4-byte length,</span>
<span class="sd">        followed by the LogRecord in pickle format. Logs the record</span>
<span class="sd">        according to whatever policy is configured locally.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
            <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">4</span><span class="p">:</span>
                <span class="k">break</span>
            <span class="n">slen</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;&gt;L&#39;</span><span class="p">,</span> <span class="n">chunk</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span><span class="p">)</span>
            <span class="k">while</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">slen</span><span class="p">:</span>
                <span class="n">chunk</span> <span class="o">=</span> <span class="n">chunk</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">connection</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="n">slen</span> <span class="o">-</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">))</span>
            <span class="n">obj</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">unPickle</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
            <span class="n">record</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">makeLogRecord</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">handleLogRecord</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">unPickle</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">pickle</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">handleLogRecord</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="c1"># if a name is specified, we use the named logger rather than the one</span>
        <span class="c1"># implied by the record.</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">server</span><span class="o">.</span><span class="n">logname</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">name</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">name</span>
        <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
        <span class="c1"># N.B. EVERY record gets logged. This is because Logger.handle</span>
        <span class="c1"># is normally called AFTER logger-level filtering. If you want</span>
        <span class="c1"># to do filtering, do it at the client end to save wasting</span>
        <span class="c1"># cycles and network bandwidth!</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">handle</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">LogRecordSocketReceiver</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Simple TCP socket-based logging receiver suitable for testing.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">allow_reuse_address</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="o">=</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span>
                 <span class="n">port</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">DEFAULT_TCP_LOGGING_PORT</span><span class="p">,</span>
                 <span class="n">handler</span><span class="o">=</span><span class="n">LogRecordStreamHandler</span><span class="p">):</span>
        <span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingTCPServer</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">),</span> <span class="n">handler</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logname</span> <span class="o">=</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">serve_until_stopped</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="kn">import</span> <span class="nn">select</span>
        <span class="n">abort</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">while</span> <span class="ow">not</span> <span class="n">abort</span><span class="p">:</span>
            <span class="n">rd</span><span class="p">,</span> <span class="n">wr</span><span class="p">,</span> <span class="n">ex</span> <span class="o">=</span> <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">socket</span><span class="o">.</span><span class="n">fileno</span><span class="p">()],</span>
                                       <span class="p">[],</span> <span class="p">[],</span>
                                       <span class="bp">self</span><span class="o">.</span><span class="n">timeout</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">rd</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
            <span class="n">abort</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">abort</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span>
        <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(relativeCreated)5d</span><span class="s1"> </span><span class="si">%(name)-15s</span><span class="s1"> </span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">tcpserver</span> <span class="o">=</span> <span class="n">LogRecordSocketReceiver</span><span class="p">()</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;About to start TCP server...&#39;</span><span class="p">)</span>
    <span class="n">tcpserver</span><span class="o">.</span><span class="n">serve_until_stopped</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>First run the server, and then the client. On the client side, nothing is
printed on the console; on the server side, you should see something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">About</span> <span class="n">to</span> <span class="n">start</span> <span class="n">TCP</span> <span class="n">server</span><span class="o">...</span>
   <span class="mi">59</span> <span class="n">root</span>            <span class="n">INFO</span>     <span class="n">Jackdaws</span> <span class="n">love</span> <span class="n">my</span> <span class="n">big</span> <span class="n">sphinx</span> <span class="n">of</span> <span class="n">quartz</span><span class="o">.</span>
   <span class="mi">59</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area1</span>     <span class="n">DEBUG</span>    <span class="n">Quick</span> <span class="n">zephyrs</span> <span class="n">blow</span><span class="p">,</span> <span class="n">vexing</span> <span class="n">daft</span> <span class="n">Jim</span><span class="o">.</span>
   <span class="mi">69</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area1</span>     <span class="n">INFO</span>     <span class="n">How</span> <span class="n">quickly</span> <span class="n">daft</span> <span class="n">jumping</span> <span class="n">zebras</span> <span class="n">vex</span><span class="o">.</span>
   <span class="mi">69</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area2</span>     <span class="n">WARNING</span>  <span class="n">Jail</span> <span class="n">zesty</span> <span class="n">vixen</span> <span class="n">who</span> <span class="n">grabbed</span> <span class="n">pay</span> <span class="kn">from</span> <span class="nn">quack.</span>
   <span class="mi">69</span> <span class="n">myapp</span><span class="o">.</span><span class="n">area2</span>     <span class="n">ERROR</span>    <span class="n">The</span> <span class="n">five</span> <span class="n">boxing</span> <span class="n">wizards</span> <span class="n">jump</span> <span class="n">quickly</span><span class="o">.</span>
</pre></div>
</div>
<p>Note that there are some security issues with pickle in some scenarios. If
these affect you, you can use an alternative serialization scheme by overriding
the <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler.makePickle" title="logging.handlers.SocketHandler.makePickle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makePickle()</span></code></a> method and implementing your
alternative there, as well as adapting the above script to use your alternative
serialization.</p>
</div>
<div class="section" id="adding-contextual-information-to-your-logging-output">
<span id="context-info"></span><h2>Adding contextual information to your logging output<a class="headerlink" href="#adding-contextual-information-to-your-logging-output" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want logging output to contain contextual information in
addition to the parameters passed to the logging call. For example, in a
networked application, it may be desirable to log client-specific information
in the log (e.g. remote client’s username, or IP address). Although you could
use the <em>extra</em> parameter to achieve this, it’s not always convenient to pass
the information in this way. While it might be tempting to create
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instances on a per-connection basis, this is not a good idea
because these instances are not garbage collected. While this is not a problem
in practice, when the number of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instances is dependent on the
level of granularity you want to use in logging an application, it could
be hard to manage if the number of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instances becomes
effectively unbounded.</p>
<div class="section" id="using-loggeradapters-to-impart-contextual-information">
<h3>Using LoggerAdapters to impart contextual information<a class="headerlink" href="#using-loggeradapters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3>
<p>An easy way in which you can pass contextual information to be output along
with logging event information is to use the <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> class.
This class is designed to look like a <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>, so that you can call
<a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-meth docutils literal notranslate"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exception()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-meth docutils literal notranslate"><span class="pre">critical()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.log" title="logging.log"><code class="xref py py-meth docutils literal notranslate"><span class="pre">log()</span></code></a>. These methods have the
same signatures as their counterparts in <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>, so you can use the
two types of instances interchangeably.</p>
<p>When you create an instance of <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a>, you pass it a
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instance and a dict-like object which contains your contextual
information. When you call one of the logging methods on an instance of
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a>, it delegates the call to the underlying instance of
<a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> passed to its constructor, and arranges to pass the contextual
information in the delegated call. Here’s a snippet from the code of
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">debug</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Delegate a debug call to the underlying logger, after adding</span>
<span class="sd">    contextual information from this adapter instance.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">process</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="n">msg</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><code class="xref py py-meth docutils literal notranslate"><span class="pre">process()</span></code></a> method of <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> is where the
contextual information is added to the logging output. It’s passed the message
and keyword arguments of the logging call, and it passes back (potentially)
modified versions of these to use in the call to the underlying logger. The
default implementation of this method leaves the message alone, but inserts
an ‘extra’ key in the keyword argument whose value is the dict-like object
passed to the constructor. Of course, if you had passed an ‘extra’ keyword
argument in the call to the adapter, it will be silently overwritten.</p>
<p>The advantage of using ‘extra’ is that the values in the dict-like object are
merged into the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance’s __dict__, allowing you to use
customized strings with your <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> instances which know about
the keys of the dict-like object. If you need a different method, e.g. if you
want to prepend or append the contextual information to the message string,
you just need to subclass <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> and override
<a class="reference internal" href="../library/logging.html#logging.LoggerAdapter.process" title="logging.LoggerAdapter.process"><code class="xref py py-meth docutils literal notranslate"><span class="pre">process()</span></code></a> to do what you need. Here is a simple example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">CustomAdapter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">LoggerAdapter</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This example adapter expects the passed in dict-like object to have a</span>
<span class="sd">    &#39;connid&#39; key, whose value in brackets is prepended to the log message.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">process</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">,</span> <span class="n">kwargs</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;[</span><span class="si">%s</span><span class="s1">] </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">extra</span><span class="p">[</span><span class="s1">&#39;connid&#39;</span><span class="p">],</span> <span class="n">msg</span><span class="p">),</span> <span class="n">kwargs</span>
</pre></div>
</div>
<p>which you can use like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
<span class="n">adapter</span> <span class="o">=</span> <span class="n">CustomAdapter</span><span class="p">(</span><span class="n">logger</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;connid&#39;</span><span class="p">:</span> <span class="n">some_conn_id</span><span class="p">})</span>
</pre></div>
</div>
<p>Then any events that you log to the adapter will have the value of
<code class="docutils literal notranslate"><span class="pre">some_conn_id</span></code> prepended to the log messages.</p>
<div class="section" id="using-objects-other-than-dicts-to-pass-contextual-information">
<h4>Using objects other than dicts to pass contextual information<a class="headerlink" href="#using-objects-other-than-dicts-to-pass-contextual-information" title="Permalink to this headline">¶</a></h4>
<p>You don’t need to pass an actual dict to a <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> - you could
pass an instance of a class which implements <code class="docutils literal notranslate"><span class="pre">__getitem__</span></code> and <code class="docutils literal notranslate"><span class="pre">__iter__</span></code> so
that it looks like a dict to logging. This would be useful if you want to
generate values dynamically (whereas the values in a dict would be constant).</p>
</div>
</div>
<div class="section" id="using-filters-to-impart-contextual-information">
<span id="filters-contextual"></span><h3>Using Filters to impart contextual information<a class="headerlink" href="#using-filters-to-impart-contextual-information" title="Permalink to this headline">¶</a></h3>
<p>You can also add contextual information to log output using a user-defined
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a>. <code class="docutils literal notranslate"><span class="pre">Filter</span></code> instances are allowed to modify the <code class="docutils literal notranslate"><span class="pre">LogRecords</span></code>
passed to them, including adding additional attributes which can then be output
using a suitable format string, or if needed a custom <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>.</p>
<p>For example in a web application, the request being processed (or at least,
the interesting parts of it) can be stored in a threadlocal
(<a class="reference internal" href="../library/threading.html#threading.local" title="threading.local"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.local</span></code></a>) variable, and then accessed from a <code class="docutils literal notranslate"><span class="pre">Filter</span></code> to
add, say, information from the request - say, the remote IP address and remote
user’s username - to the <code class="docutils literal notranslate"><span class="pre">LogRecord</span></code>, using the attribute names ‘ip’ and
‘user’ as in the <code class="docutils literal notranslate"><span class="pre">LoggerAdapter</span></code> example above. In that case, the same format
string can be used to get similar output to that shown above. Here’s an example
script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">from</span> <span class="nn">random</span> <span class="k">import</span> <span class="n">choice</span>

<span class="k">class</span> <span class="nc">ContextFilter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Filter</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This is a filter which injects contextual information into the log.</span>

<span class="sd">    Rather than use actual contextual information, we just use random</span>
<span class="sd">    data in this demo.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="n">USERS</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;jim&#39;</span><span class="p">,</span> <span class="s1">&#39;fred&#39;</span><span class="p">,</span> <span class="s1">&#39;sheila&#39;</span><span class="p">]</span>
    <span class="n">IPS</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;123.231.231.123&#39;</span><span class="p">,</span> <span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="s1">&#39;192.168.0.1&#39;</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>

        <span class="n">record</span><span class="o">.</span><span class="n">ip</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">IPS</span><span class="p">)</span>
        <span class="n">record</span><span class="o">.</span><span class="n">user</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">ContextFilter</span><span class="o">.</span><span class="n">USERS</span><span class="p">)</span>
        <span class="k">return</span> <span class="kc">True</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">levels</span> <span class="o">=</span> <span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">WARNING</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span><span class="p">,</span> <span class="n">logging</span><span class="o">.</span><span class="n">CRITICAL</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span>
                        <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)-15s</span><span class="s1"> </span><span class="si">%(name)-5s</span><span class="s1"> </span><span class="si">%(levelname)-8s</span><span class="s1"> IP: </span><span class="si">%(ip)-15s</span><span class="s1"> User: </span><span class="si">%(user)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">a1</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;a.b.c&#39;</span><span class="p">)</span>
    <span class="n">a2</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;d.e.f&#39;</span><span class="p">)</span>

    <span class="n">f</span> <span class="o">=</span> <span class="n">ContextFilter</span><span class="p">()</span>
    <span class="n">a1</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="n">a2</span><span class="o">.</span><span class="n">addFilter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="n">a1</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;A debug message&#39;</span><span class="p">)</span>
    <span class="n">a1</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;An info message with </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;some parameters&#39;</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="n">lvl</span> <span class="o">=</span> <span class="n">choice</span><span class="p">(</span><span class="n">levels</span><span class="p">)</span>
        <span class="n">lvlname</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLevelName</span><span class="p">(</span><span class="n">lvl</span><span class="p">)</span>
        <span class="n">a2</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">lvl</span><span class="p">,</span> <span class="s1">&#39;A message at </span><span class="si">%s</span><span class="s1"> level with </span><span class="si">%d</span><span class="s1"> </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">lvlname</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;parameters&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which, when run, produces something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">292</span> <span class="n">a</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">c</span> <span class="n">DEBUG</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">123.231</span><span class="o">.</span><span class="mf">231.123</span> <span class="n">User</span><span class="p">:</span> <span class="n">fred</span>     <span class="n">A</span> <span class="n">debug</span> <span class="n">message</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">a</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">c</span> <span class="n">INFO</span>     <span class="n">IP</span><span class="p">:</span> <span class="mf">192.168</span><span class="o">.</span><span class="mf">0.1</span>     <span class="n">User</span><span class="p">:</span> <span class="n">sheila</span>   <span class="n">An</span> <span class="n">info</span> <span class="n">message</span> <span class="k">with</span> <span class="n">some</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">CRITICAL</span> <span class="n">IP</span><span class="p">:</span> <span class="mf">127.0</span><span class="o">.</span><span class="mf">0.1</span>       <span class="n">User</span><span class="p">:</span> <span class="n">sheila</span>   <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">CRITICAL</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">ERROR</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">127.0</span><span class="o">.</span><span class="mf">0.1</span>       <span class="n">User</span><span class="p">:</span> <span class="n">jim</span>      <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">ERROR</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">DEBUG</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">127.0</span><span class="o">.</span><span class="mf">0.1</span>       <span class="n">User</span><span class="p">:</span> <span class="n">sheila</span>   <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">ERROR</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">123.231</span><span class="o">.</span><span class="mf">231.123</span> <span class="n">User</span><span class="p">:</span> <span class="n">fred</span>     <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">ERROR</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">CRITICAL</span> <span class="n">IP</span><span class="p">:</span> <span class="mf">192.168</span><span class="o">.</span><span class="mf">0.1</span>     <span class="n">User</span><span class="p">:</span> <span class="n">jim</span>      <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">CRITICAL</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">CRITICAL</span> <span class="n">IP</span><span class="p">:</span> <span class="mf">127.0</span><span class="o">.</span><span class="mf">0.1</span>       <span class="n">User</span><span class="p">:</span> <span class="n">sheila</span>   <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">CRITICAL</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">300</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">DEBUG</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">192.168</span><span class="o">.</span><span class="mf">0.1</span>     <span class="n">User</span><span class="p">:</span> <span class="n">jim</span>      <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">301</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">ERROR</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">127.0</span><span class="o">.</span><span class="mf">0.1</span>       <span class="n">User</span><span class="p">:</span> <span class="n">sheila</span>   <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">ERROR</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">301</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">DEBUG</span>    <span class="n">IP</span><span class="p">:</span> <span class="mf">123.231</span><span class="o">.</span><span class="mf">231.123</span> <span class="n">User</span><span class="p">:</span> <span class="n">fred</span>     <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
<span class="mi">2010</span><span class="o">-</span><span class="mi">09</span><span class="o">-</span><span class="mi">06</span> <span class="mi">22</span><span class="p">:</span><span class="mi">38</span><span class="p">:</span><span class="mi">15</span><span class="p">,</span><span class="mi">301</span> <span class="n">d</span><span class="o">.</span><span class="n">e</span><span class="o">.</span><span class="n">f</span> <span class="n">INFO</span>     <span class="n">IP</span><span class="p">:</span> <span class="mf">123.231</span><span class="o">.</span><span class="mf">231.123</span> <span class="n">User</span><span class="p">:</span> <span class="n">fred</span>     <span class="n">A</span> <span class="n">message</span> <span class="n">at</span> <span class="n">INFO</span> <span class="n">level</span> <span class="k">with</span> <span class="mi">2</span> <span class="n">parameters</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="logging-to-a-single-file-from-multiple-processes">
<span id="multiple-processes"></span><h2>Logging to a single file from multiple processes<a class="headerlink" href="#logging-to-a-single-file-from-multiple-processes" title="Permalink to this headline">¶</a></h2>
<p>Although logging is thread-safe, and logging to a single file from multiple
threads in a single process <em>is</em> supported, logging to a single file from
<em>multiple processes</em> is <em>not</em> supported, because there is no standard way to
serialize access to a single file across multiple processes in Python. If you
need to log to a single file from multiple processes, one way of doing this is
to have all the processes log to a <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a>, and have a
separate process which implements a socket server which reads from the socket
and logs to file. (If you prefer, you can dedicate one thread in one of the
existing processes to perform this function.)
<a class="reference internal" href="#network-logging"><span class="std std-ref">This section</span></a> documents this approach in more detail and
includes a working socket receiver which can be used as a starting point for you
to adapt in your own applications.</p>
<p>If you are using a recent version of Python which includes the
<a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module, you could write your own handler which uses the
<a class="reference internal" href="../library/multiprocessing.html#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> class from this module to serialize access to the
file from your processes. The existing <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> and subclasses do
not make use of <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> at present, though they may do so in the
future. Note that at present, the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module does not provide
working lock functionality on all platforms (see
<a class="reference external" href="https://bugs.python.org/issue3770">https://bugs.python.org/issue3770</a>).</p>
</div>
<div class="section" id="using-file-rotation">
<h2>Using file rotation<a class="headerlink" href="#using-file-rotation" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want to let a log file grow to a certain size, then open a new
file and log to that. You may want to keep a certain number of these files, and
when that many files have been created, rotate the files so that the number of
files and the size of the files both remain bounded. For this usage pattern, the
logging package provides a <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">glob</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.handlers</span>

<span class="n">LOG_FILENAME</span> <span class="o">=</span> <span class="s1">&#39;logging_rotatingfile_example.out&#39;</span>

<span class="c1"># Set up a specific logger with our desired output level</span>
<span class="n">my_logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;MyLogger&#39;</span><span class="p">)</span>
<span class="n">my_logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c1"># Add the log message handler to the logger</span>
<span class="n">handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">RotatingFileHandler</span><span class="p">(</span>
              <span class="n">LOG_FILENAME</span><span class="p">,</span> <span class="n">maxBytes</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">backupCount</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="n">my_logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>

<span class="c1"># Log some messages</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">):</span>
    <span class="n">my_logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;i = </span><span class="si">%d</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">i</span><span class="p">)</span>

<span class="c1"># See what files are created</span>
<span class="n">logfiles</span> <span class="o">=</span> <span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1">*&#39;</span> <span class="o">%</span> <span class="n">LOG_FILENAME</span><span class="p">)</span>

<span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">logfiles</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
</pre></div>
</div>
<p>The result should be 6 separate files, each with part of the log history for the
application:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span>
<span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span><span class="o">.</span><span class="mi">1</span>
<span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span><span class="o">.</span><span class="mi">2</span>
<span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span><span class="o">.</span><span class="mi">3</span>
<span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span><span class="o">.</span><span class="mi">4</span>
<span class="n">logging_rotatingfile_example</span><span class="o">.</span><span class="n">out</span><span class="o">.</span><span class="mi">5</span>
</pre></div>
</div>
<p>The most current file is always <code class="file docutils literal notranslate"><span class="pre">logging_rotatingfile_example.out</span></code>,
and each time it reaches the size limit it is renamed with the suffix
<code class="docutils literal notranslate"><span class="pre">.1</span></code>. Each of the existing backup files is renamed to increment the suffix
(<code class="docutils literal notranslate"><span class="pre">.1</span></code> becomes <code class="docutils literal notranslate"><span class="pre">.2</span></code>, etc.)  and the <code class="docutils literal notranslate"><span class="pre">.6</span></code> file is erased.</p>
<p>Obviously this example sets the log length much too small as an extreme
example.  You would want to set <em>maxBytes</em> to an appropriate value.</p>
</div>
<div class="section" id="an-example-dictionary-based-configuration">
<h2>An example dictionary-based configuration<a class="headerlink" href="#an-example-dictionary-based-configuration" title="Permalink to this headline">¶</a></h2>
<p>Below is an example of a logging configuration dictionary - it’s taken from
the <a class="reference external" href="https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging">documentation on the Django project</a>.
This dictionary is passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> to put the configuration into effect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s1">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
    <span class="s1">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;verbose&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(module)s</span><span class="s1"> </span><span class="si">%(process)d</span><span class="s1"> </span><span class="si">%(thread)d</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
        <span class="p">},</span>
        <span class="s1">&#39;simple&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;filters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;special&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="s1">&#39;project.logging.SpecialFilter&#39;</span><span class="p">,</span>
            <span class="s1">&#39;foo&#39;</span><span class="p">:</span> <span class="s1">&#39;bar&#39;</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;null&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span><span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span><span class="s1">&#39;django.utils.log.NullHandler&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s1">&#39;console&#39;</span><span class="p">:{</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span><span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span><span class="s1">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;simple&#39;</span>
        <span class="p">},</span>
        <span class="s1">&#39;mail_admins&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;ERROR&#39;</span><span class="p">,</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;django.utils.log.AdminEmailHandler&#39;</span><span class="p">,</span>
            <span class="s1">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;special&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s1">&#39;loggers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;django&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;handlers&#39;</span><span class="p">:[</span><span class="s1">&#39;null&#39;</span><span class="p">],</span>
            <span class="s1">&#39;propagate&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span><span class="s1">&#39;INFO&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s1">&#39;django.request&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;mail_admins&#39;</span><span class="p">],</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;ERROR&#39;</span><span class="p">,</span>
            <span class="s1">&#39;propagate&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s1">&#39;myproject.custom&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;console&#39;</span><span class="p">,</span> <span class="s1">&#39;mail_admins&#39;</span><span class="p">],</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;INFO&#39;</span><span class="p">,</span>
            <span class="s1">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;special&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>For more information about this configuration, you can see the <a class="reference external" href="https://docs.djangoproject.com/en/1.9/topics/logging/#configuring-logging">relevant
section</a>
of the Django documentation.</p>
</div>
<div class="section" id="inserting-a-bom-into-messages-sent-to-a-sysloghandler">
<h2>Inserting a BOM into messages sent to a SysLogHandler<a class="headerlink" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="https://tools.ietf.org/html/rfc5424">RFC 5424</a> requires that a
Unicode message be sent to a syslog daemon as a set of bytes which have the
following structure: an optional pure-ASCII component, followed by a UTF-8 Byte
Order Mark (BOM), followed by Unicode encoded using UTF-8. (See the <a class="reference external" href="https://tools.ietf.org/html/rfc5424#section-6">relevant
section of the specification</a>.)</p>
<p>In Python 2.6 and 2.7, code was added to
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> to insert a BOM into the message, but
unfortunately, it was implemented incorrectly, with the BOM appearing at the
beginning of the message and hence not allowing any pure-ASCII component to
appear before it.</p>
<p>As this behaviour is broken, the incorrect BOM insertion code is being removed
from Python 2.7.4 and later. However, it is not being replaced, and if you
want to produce RFC 5424-compliant messages which include a BOM, an optional
pure-ASCII sequence before it and arbitrary Unicode after it, encoded using
UTF-8, then you need to do the following:</p>
<ol class="arabic">
<li><p class="first">Attach a <a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> instance to your
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> instance, with a format string
such as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sa">u</span><span class="s1">&#39;ASCII section</span><span class="se">\ufeff</span><span class="s1">Unicode section&#39;</span>
</pre></div>
</div>
<p>The Unicode code point <code class="docutils literal notranslate"><span class="pre">u'\ufeff'</span></code>, when encoded using UTF-8, will be
encoded as a UTF-8 BOM – the byte-string <code class="docutils literal notranslate"><span class="pre">'\xef\xbb\xbf'</span></code>.</p>
</li>
<li><p class="first">Replace the ASCII section with whatever placeholders you like, but make sure
that the data that appears in there after substitution is always ASCII (that
way, it will remain unchanged after UTF-8 encoding).</p>
</li>
<li><p class="first">Replace the Unicode section with whatever placeholders you like; if the data
which appears there after substitution contains characters outside the ASCII
range, that’s fine – it will be encoded using UTF-8.</p>
</li>
</ol>
<p>If the formatted message is Unicode, it <em>will</em> be encoded using UTF-8 encoding
by <code class="docutils literal notranslate"><span class="pre">SysLogHandler</span></code>. If you follow the above rules, you should be able to
produce RFC 5424-compliant messages. If you don’t, logging may not complain,
but your messages will not be RFC 5424-compliant, and your syslog daemon may
complain.</p>
</div>
<div class="section" id="implementing-structured-logging">
<h2>Implementing structured logging<a class="headerlink" href="#implementing-structured-logging" title="Permalink to this headline">¶</a></h2>
<p>Although most logging messages are intended for reading by humans, and thus not
readily machine-parseable, there might be circumstances where you want to output
messages in a structured format which <em>is</em> capable of being parsed by a program
(without needing complex regular expressions to parse the log message). This is
straightforward to achieve using the logging package. There are a number of
ways in which this could be achieved, but the following is a simple approach
which uses JSON to serialise the event in a machine-parseable manner:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> &gt;&gt;&gt; </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">))</span>

<span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span>   <span class="c1"># optional, to improve readability</span>

<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s1">&#39;message 1&#39;</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">bar</span><span class="o">=</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="n">num</span><span class="o">=</span><span class="mi">123</span><span class="p">,</span> <span class="n">fnum</span><span class="o">=</span><span class="mf">123.456</span><span class="p">))</span>
</pre></div>
</div>
<p>If the above script is run, it prints:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">message</span> <span class="mi">1</span> <span class="o">&gt;&gt;&gt;</span> <span class="p">{</span><span class="s2">&quot;fnum&quot;</span><span class="p">:</span> <span class="mf">123.456</span><span class="p">,</span> <span class="s2">&quot;num&quot;</span><span class="p">:</span> <span class="mi">123</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">:</span> <span class="s2">&quot;baz&quot;</span><span class="p">,</span> <span class="s2">&quot;foo&quot;</span><span class="p">:</span> <span class="s2">&quot;bar&quot;</span><span class="p">}</span>
</pre></div>
</div>
<p>Note that the order of items might be different according to the version of
Python used.</p>
<p>If you need more specialised processing, you can use a custom JSON encoder,
as in the following complete example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">unicode_literals</span>

<span class="kn">import</span> <span class="nn">json</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="c1"># This next bit is to ensure the script runs unchanged on 2.x and 3.x</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">unicode</span>
<span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
    <span class="n">unicode</span> <span class="o">=</span> <span class="nb">str</span>

<span class="k">class</span> <span class="nc">Encoder</span><span class="p">(</span><span class="n">json</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">o</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">set</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="n">unicode</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">o</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;unicode_escape&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">Encoder</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">StructuredMessage</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">message</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">message</span> <span class="o">=</span> <span class="n">message</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span> <span class="o">=</span> <span class="n">kwargs</span>

    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">Encoder</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span>
        <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> &gt;&gt;&gt; </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">message</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>

<span class="n">_</span> <span class="o">=</span> <span class="n">StructuredMessage</span>   <span class="c1"># optional, to improve readability</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s1">&#39;message 1&#39;</span><span class="p">,</span> <span class="n">set_value</span><span class="o">=</span><span class="nb">set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]),</span> <span class="n">snowman</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\u2603</span><span class="s1">&#39;</span><span class="p">))</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>When the above script is run, it prints:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">message</span> <span class="mi">1</span> <span class="o">&gt;&gt;&gt;</span> <span class="p">{</span><span class="s2">&quot;snowman&quot;</span><span class="p">:</span> <span class="s2">&quot;</span><span class="se">\u2603</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;set_value&quot;</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]}</span>
</pre></div>
</div>
<p>Note that the order of items might be different according to the version of
Python used.</p>
</div>
<div class="section" id="customizing-handlers-with-dictconfig">
<span id="custom-handlers"></span><h2>Customizing handlers with <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a><a class="headerlink" href="#customizing-handlers-with-dictconfig" title="Permalink to this headline">¶</a></h2>
<p>There are times when you want to customize logging handlers in particular ways,
and if you use <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> you may be able to do this without
subclassing. As an example, consider that you may want to set the ownership of a
log file. On POSIX, this is easily done using <a class="reference internal" href="../library/os.html#os.chown" title="os.chown"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chown()</span></code></a>, but the file
handlers in the stdlib don’t offer built-in support. You can customize handler
creation using a plain function such as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">owned_file_handler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">owner</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">owner</span><span class="p">:</span>
        <span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">pwd</span><span class="o">,</span> <span class="nn">grp</span>
        <span class="c1"># convert user and group names to uid and gid</span>
        <span class="n">uid</span> <span class="o">=</span> <span class="n">pwd</span><span class="o">.</span><span class="n">getpwnam</span><span class="p">(</span><span class="n">owner</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span><span class="o">.</span><span class="n">pw_uid</span>
        <span class="n">gid</span> <span class="o">=</span> <span class="n">grp</span><span class="o">.</span><span class="n">getgrnam</span><span class="p">(</span><span class="n">owner</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span><span class="o">.</span><span class="n">gr_gid</span>
        <span class="n">owner</span> <span class="o">=</span> <span class="p">(</span><span class="n">uid</span><span class="p">,</span> <span class="n">gid</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
            <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">os</span><span class="o">.</span><span class="n">chown</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="o">*</span><span class="n">owner</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">encoding</span><span class="p">)</span>
</pre></div>
</div>
<p>You can then specify, in a logging configuration passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a>,
that a logging handler be created by calling this function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s1">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">,</span>
    <span class="s1">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;file&#39;</span><span class="p">:{</span>
            <span class="c1"># The values below are popped from this dictionary and</span>
            <span class="c1"># used to create the handler, set the handler&#39;s level and</span>
            <span class="c1"># its formatter.</span>
            <span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="n">owned_file_handler</span><span class="p">,</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span><span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;default&#39;</span><span class="p">,</span>
            <span class="c1"># The values below are passed to the handler creator callable</span>
            <span class="c1"># as keyword arguments.</span>
            <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;pulse&#39;</span><span class="p">,</span> <span class="s1">&#39;pulse&#39;</span><span class="p">],</span>
            <span class="s1">&#39;filename&#39;</span><span class="p">:</span> <span class="s1">&#39;chowntest.log&#39;</span><span class="p">,</span>
            <span class="s1">&#39;mode&#39;</span><span class="p">:</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span>
            <span class="s1">&#39;encoding&#39;</span><span class="p">:</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;file&#39;</span><span class="p">],</span>
        <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>
</pre></div>
</div>
<p>In this example I am setting the ownership using the <code class="docutils literal notranslate"><span class="pre">pulse</span></code> user and group,
just for the purposes of illustration. Putting it together into a working
script, <code class="docutils literal notranslate"><span class="pre">chowntest.py</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span><span class="o">,</span> <span class="nn">logging.config</span><span class="o">,</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">shutil</span>

<span class="k">def</span> <span class="nf">owned_file_handler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">owner</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">owner</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
            <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">shutil</span><span class="o">.</span><span class="n">chown</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="o">*</span><span class="n">owner</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">encoding</span><span class="p">)</span>

<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s1">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">,</span>
    <span class="s1">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;default&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(levelname)s</span><span class="s1"> </span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;file&#39;</span><span class="p">:{</span>
            <span class="c1"># The values below are popped from this dictionary and</span>
            <span class="c1"># used to create the handler, set the handler&#39;s level and</span>
            <span class="c1"># its formatter.</span>
            <span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="n">owned_file_handler</span><span class="p">,</span>
            <span class="s1">&#39;level&#39;</span><span class="p">:</span><span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
            <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;default&#39;</span><span class="p">,</span>
            <span class="c1"># The values below are passed to the handler creator callable</span>
            <span class="c1"># as keyword arguments.</span>
            <span class="s1">&#39;owner&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;pulse&#39;</span><span class="p">,</span> <span class="s1">&#39;pulse&#39;</span><span class="p">],</span>
            <span class="s1">&#39;filename&#39;</span><span class="p">:</span> <span class="s1">&#39;chowntest.log&#39;</span><span class="p">,</span>
            <span class="s1">&#39;mode&#39;</span><span class="p">:</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span>
            <span class="s1">&#39;encoding&#39;</span><span class="p">:</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;file&#39;</span><span class="p">],</span>
        <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
    <span class="p">},</span>
<span class="p">}</span>

<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">LOGGING</span><span class="p">)</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;mylogger&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;A debug message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>To run this, you will probably need to run as <code class="docutils literal notranslate"><span class="pre">root</span></code>:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> sudo python3.3 chowntest.py
<span class="gp">$</span> cat chowntest.log
<span class="go">2013-11-05 09:34:51,128 DEBUG mylogger A debug message</span>
<span class="gp">$</span> ls -l chowntest.log
<span class="go">-rw-r--r-- 1 pulse pulse 55 2013-11-05 09:34 chowntest.log</span>
</pre></div>
</div>
<p>Note that this example uses Python 3.3 because that’s where <code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.chown()</span></code>
makes an appearance. This approach should work with any Python version that
supports <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> - namely, Python 2.7, 3.2 or later. With pre-3.3
versions, you would need to implement the actual ownership change using e.g.
<a class="reference internal" href="../library/os.html#os.chown" title="os.chown"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chown()</span></code></a>.</p>
<p>In practice, the handler-creating function may be in a utility module somewhere
in your project. Instead of the line in the configuration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="n">owned_file_handler</span><span class="p">,</span>
</pre></div>
</div>
<p>you could use e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="s1">&#39;ext://project.util.owned_file_handler&#39;</span><span class="p">,</span>
</pre></div>
</div>
<p>where <code class="docutils literal notranslate"><span class="pre">project.util</span></code> can be replaced with the actual name of the package
where the function resides. In the above working script, using
<code class="docutils literal notranslate"><span class="pre">'ext://__main__.owned_file_handler'</span></code> should work. Here, the actual callable
is resolved by <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> from the <code class="docutils literal notranslate"><span class="pre">ext://</span></code> specification.</p>
<p>This example hopefully also points the way to how you could implement other
types of file change - e.g. setting specific POSIX permission bits - in the
same way, using <a class="reference internal" href="../library/os.html#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chmod()</span></code></a>.</p>
<p>Of course, the approach could also be extended to types of handler other than a
<a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> - for example, one of the rotating file handlers,
or a different type of handler altogether.</p>
</div>
<div class="section" id="configuring-filters-with-dictconfig">
<span id="filters-dictconfig"></span><h2>Configuring filters with <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a><a class="headerlink" href="#configuring-filters-with-dictconfig" title="Permalink to this headline">¶</a></h2>
<p>You <em>can</em> configure filters using <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a>, though it
might not be obvious at first glance how to do it (hence this recipe). Since
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> is the only filter class included in the standard
library, and it is unlikely to cater to many requirements (it’s only there as a
base class), you will typically need to define your own <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a>
subclass with an overridden <a class="reference internal" href="../library/logging.html#logging.Filter.filter" title="logging.Filter.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a> method. To do this,
specify the <code class="docutils literal notranslate"><span class="pre">()</span></code> key in the configuration dictionary for the filter,
specifying a callable which will be used to create the filter (a class is the
most obvious, but you can provide any callable which returns a
<a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> instance). Here is a complete example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">MyFilter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Filter</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">param</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="o">=</span> <span class="n">param</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">allow</span> <span class="o">=</span> <span class="kc">True</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">allow</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">param</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">record</span><span class="o">.</span><span class="n">msg</span>
        <span class="k">if</span> <span class="n">allow</span><span class="p">:</span>
            <span class="n">record</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="s1">&#39;changed: &#39;</span> <span class="o">+</span> <span class="n">record</span><span class="o">.</span><span class="n">msg</span>
        <span class="k">return</span> <span class="n">allow</span>

<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s1">&#39;filters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;myfilter&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="n">MyFilter</span><span class="p">,</span>
            <span class="s1">&#39;param&#39;</span><span class="p">:</span> <span class="s1">&#39;noshow&#39;</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;console&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s1">&#39;filters&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;myfilter&#39;</span><span class="p">]</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s1">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;DEBUG&#39;</span><span class="p">,</span>
        <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;console&#39;</span><span class="p">]</span>
    <span class="p">},</span>
<span class="p">}</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">LOGGING</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;hello - noshow&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This example shows how you can pass configuration data to the callable which
constructs the instance, in the form of keyword parameters. When run, the above
script will print:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">changed</span><span class="p">:</span> <span class="n">hello</span>
</pre></div>
</div>
<p>which shows that the filter is working as configured.</p>
<p>A couple of extra points to note:</p>
<ul class="simple">
<li>If you can’t refer to the callable directly in the configuration (e.g. if it
lives in a different module, and you can’t import it directly where the
configuration dictionary is), you can use the form <code class="docutils literal notranslate"><span class="pre">ext://...</span></code> as described
in <a class="reference internal" href="../library/logging.config.html#logging-config-dict-externalobj"><span class="std std-ref">Access to external objects</span></a>. For example, you could have used
the text <code class="docutils literal notranslate"><span class="pre">'ext://__main__.MyFilter'</span></code> instead of <code class="docutils literal notranslate"><span class="pre">MyFilter</span></code> in the above
example.</li>
<li>As well as for filters, this technique can also be used to configure custom
handlers and formatters. See <a class="reference internal" href="../library/logging.config.html#logging-config-dict-userdef"><span class="std std-ref">User-defined objects</span></a> for more
information on how logging supports using user-defined objects in its
configuration, and see the other cookbook recipe <a class="reference internal" href="#custom-handlers"><span class="std std-ref">Customizing handlers with dictConfig()</span></a> above.</li>
</ul>
</div>
<div class="section" id="customized-exception-formatting">
<span id="custom-format-exception"></span><h2>Customized exception formatting<a class="headerlink" href="#customized-exception-formatting" title="Permalink to this headline">¶</a></h2>
<p>There might be times when you want to do customized exception formatting - for
argument’s sake, let’s say you want exactly one line per logged event, even
when exception information is present. You can do this with a custom formatter
class, as shown in the following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="k">class</span> <span class="nc">OneLineExceptionFormatter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">formatException</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_info</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">        Format an exception so that it prints on a single line.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">result</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">OneLineExceptionFormatter</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">formatException</span><span class="p">(</span><span class="n">exc_info</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="n">result</span><span class="p">)</span> <span class="c1"># or format into one line however you want to</span>

    <span class="k">def</span> <span class="nf">format</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">OneLineExceptionFormatter</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">record</span><span class="o">.</span><span class="n">exc_text</span><span class="p">:</span>
            <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;|&#39;</span>
        <span class="k">return</span> <span class="n">s</span>

<span class="k">def</span> <span class="nf">configure_logging</span><span class="p">():</span>
    <span class="n">fh</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">FileHandler</span><span class="p">(</span><span class="s1">&#39;output.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
    <span class="n">f</span> <span class="o">=</span> <span class="n">OneLineExceptionFormatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1">|</span><span class="si">%(levelname)s</span><span class="s1">|</span><span class="si">%(message)s</span><span class="s1">|&#39;</span><span class="p">,</span>
                                  <span class="s1">&#39;</span><span class="si">%d</span><span class="s1">/%m/%Y %H:%M:%S&#39;</span><span class="p">)</span>
    <span class="n">fh</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="n">root</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">()</span>
    <span class="n">root</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
    <span class="n">root</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">fh</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">configure_logging</span><span class="p">()</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Sample message&#39;</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span>
    <span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="n">logging</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="s1">&#39;ZeroDivisionError: </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">e</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>When run, this produces a file with exactly two lines:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">28</span><span class="o">/</span><span class="mi">01</span><span class="o">/</span><span class="mi">2015</span> <span class="mi">07</span><span class="p">:</span><span class="mi">21</span><span class="p">:</span><span class="mi">23</span><span class="o">|</span><span class="n">INFO</span><span class="o">|</span><span class="n">Sample</span> <span class="n">message</span><span class="o">|</span>
<span class="mi">28</span><span class="o">/</span><span class="mi">01</span><span class="o">/</span><span class="mi">2015</span> <span class="mi">07</span><span class="p">:</span><span class="mi">21</span><span class="p">:</span><span class="mi">23</span><span class="o">|</span><span class="n">ERROR</span><span class="o">|</span><span class="ne">ZeroDivisionError</span><span class="p">:</span> <span class="n">integer</span> <span class="n">division</span> <span class="ow">or</span> <span class="n">modulo</span> <span class="n">by</span> <span class="n">zero</span><span class="o">|</span><span class="s1">&#39;Traceback (most recent call last):</span><span class="se">\n</span><span class="s1">  File &quot;logtest7.py&quot;, line 30, in main</span><span class="se">\n</span><span class="s1">    x = 1 / 0</span><span class="se">\n</span><span class="s1">ZeroDivisionError: integer division or modulo by zero&#39;</span><span class="o">|</span>
</pre></div>
</div>
<p>While the above treatment is simplistic, it points the way to how exception
information can be formatted to your liking. The <a class="reference internal" href="../library/traceback.html#module-traceback" title="traceback: Print or retrieve a stack traceback."><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code></a> module may be
helpful for more specialized needs.</p>
</div>
<div class="section" id="speaking-logging-messages">
<span id="spoken-messages"></span><h2>Speaking logging messages<a class="headerlink" href="#speaking-logging-messages" title="Permalink to this headline">¶</a></h2>
<p>There might be situations when it is desirable to have logging messages rendered
in an audible rather than a visible format. This is easy to do if you have
text-to-speech (TTS) functionality available in your system, even if it doesn’t have
a Python binding. Most TTS systems have a command line program you can run, and
this can be invoked from a handler using <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>. It’s assumed here
that TTS command line programs won’t expect to interact with users or take a
long time to complete, and that the frequency of logged messages will be not so
high as to swamp the user with messages, and that it’s acceptable to have the
messages spoken one at a time rather than concurrently, The example implementation
below waits for one message to be spoken before the next is processed, and this
might cause other handlers to be kept waiting. Here is a short example showing
the approach, which assumes that the <code class="docutils literal notranslate"><span class="pre">espeak</span></code> TTS package is available:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">subprocess</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">TTSHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Handler</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">emit</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">record</span><span class="p">):</span>
        <span class="n">msg</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">record</span><span class="p">)</span>
        <span class="c1"># Speak slowly in a female English voice</span>
        <span class="n">cmd</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;espeak&#39;</span><span class="p">,</span> <span class="s1">&#39;-s150&#39;</span><span class="p">,</span> <span class="s1">&#39;-ven+f3&#39;</span><span class="p">,</span> <span class="n">msg</span><span class="p">]</span>
        <span class="n">p</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">Popen</span><span class="p">(</span><span class="n">cmd</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">subprocess</span><span class="o">.</span><span class="n">PIPE</span><span class="p">,</span>
                             <span class="n">stderr</span><span class="o">=</span><span class="n">subprocess</span><span class="o">.</span><span class="n">STDOUT</span><span class="p">)</span>
        <span class="c1"># wait for the program to finish</span>
        <span class="n">p</span><span class="o">.</span><span class="n">communicate</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">configure_logging</span><span class="p">():</span>
    <span class="n">h</span> <span class="o">=</span> <span class="n">TTSHandler</span><span class="p">()</span>
    <span class="n">root</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">()</span>
    <span class="n">root</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">h</span><span class="p">)</span>
    <span class="c1"># the default formatter just returns the message</span>
    <span class="n">root</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Hello&#39;</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Goodbye&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">configure_logging</span><span class="p">()</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="n">main</span><span class="p">())</span>
</pre></div>
</div>
<p>When run, this script should say “Hello” and then “Goodbye” in a female voice.</p>
<p>The above approach can, of course, be adapted to other TTS systems and even
other systems altogether which can process messages via external programs run
from a command line.</p>
</div>
<div class="section" id="buffering-logging-messages-and-outputting-them-conditionally">
<span id="buffered-logging"></span><h2>Buffering logging messages and outputting them conditionally<a class="headerlink" href="#buffering-logging-messages-and-outputting-them-conditionally" title="Permalink to this headline">¶</a></h2>
<p>There might be situations where you want to log messages in a temporary area
and only output them if a certain condition occurs. For example, you may want to
start logging debug events in a function, and if the function completes without
errors, you don’t want to clutter the log with the collected debug information,
but if there is an error, you want all the debug information to be output as well
as the error.</p>
<p>Here is an example which shows how you could do this using a decorator for your
functions where you want logging to behave this way. It makes use of the
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.handlers.MemoryHandler</span></code></a>, which allows buffering of logged events
until some condition occurs, at which point the buffered events are <code class="docutils literal notranslate"><span class="pre">flushed</span></code>
- passed to another handler (the <code class="docutils literal notranslate"><span class="pre">target</span></code> handler) for processing. By default,
the <code class="docutils literal notranslate"><span class="pre">MemoryHandler</span></code> flushed when its buffer gets filled up or an event whose
level is greater than or equal to a specified threshold is seen. You can use this
recipe with a more specialised subclass of <code class="docutils literal notranslate"><span class="pre">MemoryHandler</span></code> if you want custom
flushing behavior.</p>
<p>The example script has a simple function, <code class="docutils literal notranslate"><span class="pre">foo</span></code>, which just cycles through
all the logging levels, writing to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> to say what level it’s about
to log at, and then actually logging a message at that level. You can pass a
parameter to <code class="docutils literal notranslate"><span class="pre">foo</span></code> which, if true, will log at ERROR and CRITICAL levels -
otherwise, it only logs at DEBUG, INFO and WARNING levels.</p>
<p>The script just arranges to decorate <code class="docutils literal notranslate"><span class="pre">foo</span></code> with a decorator which will do the
conditional logging that’s required. The decorator takes a logger as a parameter
and attaches a memory handler for the duration of the call to the decorated
function. The decorator can be additionally parameterised using a target handler,
a level at which flushing should occur, and a capacity for the buffer. These
default to a <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> which writes to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>,
<code class="docutils literal notranslate"><span class="pre">logging.ERROR</span></code> and <code class="docutils literal notranslate"><span class="pre">100</span></code> respectively.</p>
<p>Here’s the script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">from</span> <span class="nn">logging.handlers</span> <span class="k">import</span> <span class="n">MemoryHandler</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">NullHandler</span><span class="p">())</span>

<span class="k">def</span> <span class="nf">log_if_errors</span><span class="p">(</span><span class="n">logger</span><span class="p">,</span> <span class="n">target_handler</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">flush_level</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">capacity</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">target_handler</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">target_handler</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">flush_level</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">flush_level</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">ERROR</span>
    <span class="k">if</span> <span class="n">capacity</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">capacity</span> <span class="o">=</span> <span class="mi">100</span>
    <span class="n">handler</span> <span class="o">=</span> <span class="n">MemoryHandler</span><span class="p">(</span><span class="n">capacity</span><span class="p">,</span> <span class="n">flushLevel</span><span class="o">=</span><span class="n">flush_level</span><span class="p">,</span> <span class="n">target</span><span class="o">=</span><span class="n">target_handler</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">decorator</span><span class="p">(</span><span class="n">fn</span><span class="p">):</span>
        <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
            <span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="k">return</span> <span class="n">fn</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">Exception</span><span class="p">:</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="s1">&#39;call failed&#39;</span><span class="p">)</span>
                <span class="k">raise</span>
            <span class="k">finally</span><span class="p">:</span>
                <span class="nb">super</span><span class="p">(</span><span class="n">MemoryHandler</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
                <span class="n">logger</span><span class="o">.</span><span class="n">removeHandler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">wrapper</span>

    <span class="k">return</span> <span class="n">decorator</span>

<span class="k">def</span> <span class="nf">write_line</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">s</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">fail</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;about to log at DEBUG ...&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Actually logged at DEBUG&#39;</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;about to log at INFO ...&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Actually logged at INFO&#39;</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;about to log at WARNING ...&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Actually logged at WARNING&#39;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">fail</span><span class="p">:</span>
        <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;about to log at ERROR ...&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Actually logged at ERROR&#39;</span><span class="p">)</span>
        <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;about to log at CRITICAL ...&#39;</span><span class="p">)</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Actually logged at CRITICAL&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">fail</span>

<span class="n">decorated_foo</span> <span class="o">=</span> <span class="n">log_if_errors</span><span class="p">(</span><span class="n">logger</span><span class="p">)(</span><span class="n">foo</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;Calling undecorated foo with False&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">foo</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;Calling undecorated foo with True&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">foo</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;Calling decorated foo with False&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="n">decorated_foo</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>
    <span class="n">write_line</span><span class="p">(</span><span class="s1">&#39;Calling decorated foo with True&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="n">decorated_foo</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>When this script is run, the following output should be observed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Calling</span> <span class="n">undecorated</span> <span class="n">foo</span> <span class="k">with</span> <span class="kc">False</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">INFO</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">WARNING</span> <span class="o">...</span>
<span class="n">Calling</span> <span class="n">undecorated</span> <span class="n">foo</span> <span class="k">with</span> <span class="kc">True</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">INFO</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">WARNING</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">ERROR</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">CRITICAL</span> <span class="o">...</span>
<span class="n">Calling</span> <span class="n">decorated</span> <span class="n">foo</span> <span class="k">with</span> <span class="kc">False</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">INFO</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">WARNING</span> <span class="o">...</span>
<span class="n">Calling</span> <span class="n">decorated</span> <span class="n">foo</span> <span class="k">with</span> <span class="kc">True</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">DEBUG</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">INFO</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">WARNING</span> <span class="o">...</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">ERROR</span> <span class="o">...</span>
<span class="n">Actually</span> <span class="n">logged</span> <span class="n">at</span> <span class="n">DEBUG</span>
<span class="n">Actually</span> <span class="n">logged</span> <span class="n">at</span> <span class="n">INFO</span>
<span class="n">Actually</span> <span class="n">logged</span> <span class="n">at</span> <span class="n">WARNING</span>
<span class="n">Actually</span> <span class="n">logged</span> <span class="n">at</span> <span class="n">ERROR</span>
<span class="n">about</span> <span class="n">to</span> <span class="n">log</span> <span class="n">at</span> <span class="n">CRITICAL</span> <span class="o">...</span>
<span class="n">Actually</span> <span class="n">logged</span> <span class="n">at</span> <span class="n">CRITICAL</span>
</pre></div>
</div>
<p>As you can see, actual logging output only occurs when an event is logged whose
severity is ERROR or greater, but in that case, any previous events at lower
severities are also logged.</p>
<p>You can of course use the conventional means of decoration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@log_if_errors</span><span class="p">(</span><span class="n">logger</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">fail</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
</div>
<div class="section" id="formatting-times-using-utc-gmt-via-configuration">
<span id="utc-formatting"></span><h2>Formatting times using UTC (GMT) via configuration<a class="headerlink" href="#formatting-times-using-utc-gmt-via-configuration" title="Permalink to this headline">¶</a></h2>
<p>Sometimes you want to format times using UTC, which can be done using a class
such as <cite>UTCFormatter</cite>, shown below:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">class</span> <span class="nc">UTCFormatter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">):</span>
    <span class="n">converter</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">gmtime</span>
</pre></div>
</div>
<p>and you can then use the <code class="docutils literal notranslate"><span class="pre">UTCFormatter</span></code> in your code instead of
<a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>. If you want to do that via configuration, you can
use the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> API with an approach illustrated by
the following complete example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">class</span> <span class="nc">UTCFormatter</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">):</span>
    <span class="n">converter</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">gmtime</span>

<span class="n">LOGGING</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s1">&#39;disable_existing_loggers&#39;</span><span class="p">:</span> <span class="kc">False</span><span class="p">,</span>
    <span class="s1">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;utc&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;()&#39;</span><span class="p">:</span> <span class="n">UTCFormatter</span><span class="p">,</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s1">&#39;local&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span>
        <span class="p">}</span>
    <span class="p">},</span>
    <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;console1&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;utc&#39;</span><span class="p">,</span>
        <span class="p">},</span>
        <span class="s1">&#39;console2&#39;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;logging.StreamHandler&#39;</span><span class="p">,</span>
            <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;local&#39;</span><span class="p">,</span>
        <span class="p">},</span>
    <span class="p">},</span>
    <span class="s1">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;console1&#39;</span><span class="p">,</span> <span class="s1">&#39;console2&#39;</span><span class="p">],</span>
   <span class="p">}</span>
<span class="p">}</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">LOGGING</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;The local time is </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">asctime</span><span class="p">())</span>
</pre></div>
</div>
<p>When this script is run, it should print something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2015</span><span class="o">-</span><span class="mi">10</span><span class="o">-</span><span class="mi">17</span> <span class="mi">12</span><span class="p">:</span><span class="mi">53</span><span class="p">:</span><span class="mi">29</span><span class="p">,</span><span class="mi">501</span> <span class="n">The</span> <span class="n">local</span> <span class="n">time</span> <span class="ow">is</span> <span class="n">Sat</span> <span class="n">Oct</span> <span class="mi">17</span> <span class="mi">13</span><span class="p">:</span><span class="mi">53</span><span class="p">:</span><span class="mi">29</span> <span class="mi">2015</span>
<span class="mi">2015</span><span class="o">-</span><span class="mi">10</span><span class="o">-</span><span class="mi">17</span> <span class="mi">13</span><span class="p">:</span><span class="mi">53</span><span class="p">:</span><span class="mi">29</span><span class="p">,</span><span class="mi">501</span> <span class="n">The</span> <span class="n">local</span> <span class="n">time</span> <span class="ow">is</span> <span class="n">Sat</span> <span class="n">Oct</span> <span class="mi">17</span> <span class="mi">13</span><span class="p">:</span><span class="mi">53</span><span class="p">:</span><span class="mi">29</span> <span class="mi">2015</span>
</pre></div>
</div>
<p>showing how the time is formatted both as local time and UTC, one for each
handler.</p>
</div>
<div class="section" id="using-a-context-manager-for-selective-logging">
<span id="context-manager"></span><h2>Using a context manager for selective logging<a class="headerlink" href="#using-a-context-manager-for-selective-logging" title="Permalink to this headline">¶</a></h2>
<p>There are times when it would be useful to temporarily change the logging
configuration and revert it back after doing something. For this, a context
manager is the most obvious way of saving and restoring the logging context.
Here is a simple example of such a context manager, which allows you to
optionally change the logging level and add a logging handler purely in the
scope of the context manager:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">LoggingContext</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">logger</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">handler</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">close</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">logger</span> <span class="o">=</span> <span class="n">logger</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">level</span> <span class="o">=</span> <span class="n">level</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">handler</span> <span class="o">=</span> <span class="n">handler</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">close</span> <span class="o">=</span> <span class="n">close</span>

    <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">level</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">old_level</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">level</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">level</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">handler</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">handler</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">et</span><span class="p">,</span> <span class="n">ev</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">level</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">old_level</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">handler</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">logger</span><span class="o">.</span><span class="n">removeHandler</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">handler</span><span class="p">)</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">handler</span> <span class="ow">and</span> <span class="bp">self</span><span class="o">.</span><span class="n">close</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">handler</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="c1"># implicit return of None =&gt; don&#39;t swallow exceptions</span>
</pre></div>
</div>
<p>If you specify a level value, the logger’s level is set to that value in the
scope of the with block covered by the context manager. If you specify a
handler, it is added to the logger on entry to the block and removed on exit
from the block. You can also ask the manager to close the handler for you on
block exit - you could do this if you don’t need the handler any more.</p>
<p>To illustrate how it works, we can add the following block of code to the
above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">())</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;1. This should appear just once on stderr.&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;2. This should not appear.&#39;</span><span class="p">)</span>
    <span class="k">with</span> <span class="n">LoggingContext</span><span class="p">(</span><span class="n">logger</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">):</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;3. This should appear once on stderr.&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;4. This should not appear.&#39;</span><span class="p">)</span>
    <span class="n">h</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
    <span class="k">with</span> <span class="n">LoggingContext</span><span class="p">(</span><span class="n">logger</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">,</span> <span class="n">handler</span><span class="o">=</span><span class="n">h</span><span class="p">,</span> <span class="n">close</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
        <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;5. This should appear twice - once on stderr and once on stdout.&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;6. This should appear just once on stderr.&#39;</span><span class="p">)</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;7. This should not appear.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>We initially set the logger’s level to <code class="docutils literal notranslate"><span class="pre">INFO</span></code>, so message #1 appears and
message #2 doesn’t. We then change the level to <code class="docutils literal notranslate"><span class="pre">DEBUG</span></code> temporarily in the
following <code class="docutils literal notranslate"><span class="pre">with</span></code> block, and so message #3 appears. After the block exits, the
logger’s level is restored to <code class="docutils literal notranslate"><span class="pre">INFO</span></code> and so message #4 doesn’t appear. In the
next <code class="docutils literal notranslate"><span class="pre">with</span></code> block, we set the level to <code class="docutils literal notranslate"><span class="pre">DEBUG</span></code> again but also add a handler
writing to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>. Thus, message #5 appears twice on the console (once
via <code class="docutils literal notranslate"><span class="pre">stderr</span></code> and once via <code class="docutils literal notranslate"><span class="pre">stdout</span></code>). After the <code class="docutils literal notranslate"><span class="pre">with</span></code> statement’s
completion, the status is as it was before so message #6 appears (like message
#1) whereas message #7 doesn’t (just like message #2).</p>
<p>If we run the resulting script, the result is as follows:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python logctx.py
<span class="go">1. This should appear just once on stderr.</span>
<span class="go">3. This should appear once on stderr.</span>
<span class="go">5. This should appear twice - once on stderr and once on stdout.</span>
<span class="go">5. This should appear twice - once on stderr and once on stdout.</span>
<span class="go">6. This should appear just once on stderr.</span>
</pre></div>
</div>
<p>If we run it again, but pipe <code class="docutils literal notranslate"><span class="pre">stderr</span></code> to <code class="docutils literal notranslate"><span class="pre">/dev/null</span></code>, we see the following,
which is the only message written to <code class="docutils literal notranslate"><span class="pre">stdout</span></code>:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python logctx.py <span class="m">2</span>&gt;/dev/null
<span class="go">5. This should appear twice - once on stderr and once on stdout.</span>
</pre></div>
</div>
<p>Once again, but piping <code class="docutils literal notranslate"><span class="pre">stdout</span></code> to <code class="docutils literal notranslate"><span class="pre">/dev/null</span></code>, we get:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python logctx.py &gt;/dev/null
<span class="go">1. This should appear just once on stderr.</span>
<span class="go">3. This should appear once on stderr.</span>
<span class="go">5. This should appear twice - once on stderr and once on stdout.</span>
<span class="go">6. This should appear just once on stderr.</span>
</pre></div>
</div>
<p>In this case, the message #5 printed to <code class="docutils literal notranslate"><span class="pre">stdout</span></code> doesn’t appear, as expected.</p>
<p>Of course, the approach described here can be generalised, for example to attach
logging filters temporarily. Note that the above code works in Python 2 as well
as Python 3.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Logging Cookbook</a><ul>
<li><a class="reference internal" href="#using-logging-in-multiple-modules">Using logging in multiple modules</a></li>
<li><a class="reference internal" href="#logging-from-multiple-threads">Logging from multiple threads</a></li>
<li><a class="reference internal" href="#multiple-handlers-and-formatters">Multiple handlers and formatters</a></li>
<li><a class="reference internal" href="#logging-to-multiple-destinations">Logging to multiple destinations</a></li>
<li><a class="reference internal" href="#configuration-server-example">Configuration server example</a></li>
<li><a class="reference internal" href="#sending-and-receiving-logging-events-across-a-network">Sending and receiving logging events across a network</a></li>
<li><a class="reference internal" href="#adding-contextual-information-to-your-logging-output">Adding contextual information to your logging output</a><ul>
<li><a class="reference internal" href="#using-loggeradapters-to-impart-contextual-information">Using LoggerAdapters to impart contextual information</a><ul>
<li><a class="reference internal" href="#using-objects-other-than-dicts-to-pass-contextual-information">Using objects other than dicts to pass contextual information</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-filters-to-impart-contextual-information">Using Filters to impart contextual information</a></li>
</ul>
</li>
<li><a class="reference internal" href="#logging-to-a-single-file-from-multiple-processes">Logging to a single file from multiple processes</a></li>
<li><a class="reference internal" href="#using-file-rotation">Using file rotation</a></li>
<li><a class="reference internal" href="#an-example-dictionary-based-configuration">An example dictionary-based configuration</a></li>
<li><a class="reference internal" href="#inserting-a-bom-into-messages-sent-to-a-sysloghandler">Inserting a BOM into messages sent to a SysLogHandler</a></li>
<li><a class="reference internal" href="#implementing-structured-logging">Implementing structured logging</a></li>
<li><a class="reference internal" href="#customizing-handlers-with-dictconfig">Customizing handlers with <code class="docutils literal notranslate"><span class="pre">dictConfig()</span></code></a></li>
<li><a class="reference internal" href="#configuring-filters-with-dictconfig">Configuring filters with <code class="docutils literal notranslate"><span class="pre">dictConfig()</span></code></a></li>
<li><a class="reference internal" href="#customized-exception-formatting">Customized exception formatting</a></li>
<li><a class="reference internal" href="#speaking-logging-messages">Speaking logging messages</a></li>
<li><a class="reference internal" href="#buffering-logging-messages-and-outputting-them-conditionally">Buffering logging messages and outputting them conditionally</a></li>
<li><a class="reference internal" href="#formatting-times-using-utc-gmt-via-configuration">Formatting times using UTC (GMT) via configuration</a></li>
<li><a class="reference internal" href="#using-a-context-manager-for-selective-logging">Using a context manager for selective logging</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging.html"
                        title="previous chapter">Logging HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="regex.html"
                        title="next chapter">Regular Expression HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/logging-cookbook.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="Logging HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��p%����html/howto/logging.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Logging HOWTO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Logging Cookbook" href="logging-cookbook.html" />
    <link rel="prev" title="Functional Programming HOWTO" href="functional.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/logging.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="logging-howto">
<h1>Logging HOWTO<a class="headerlink" href="#logging-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Vinay Sajip &lt;vinay_sajip at red-dove dot com&gt;</td>
</tr>
</tbody>
</table>
<div class="section" id="basic-logging-tutorial">
<span id="logging-basic-tutorial"></span><h2>Basic Logging Tutorial<a class="headerlink" href="#basic-logging-tutorial" title="Permalink to this headline">¶</a></h2>
<p>Logging is a means of tracking events that happen when some software runs. The
software’s developer adds logging calls to their code to indicate that certain
events have occurred. An event is described by a descriptive message which can
optionally contain variable data (i.e. data that is potentially different for
each occurrence of the event). Events also have an importance which the
developer ascribes to the event; the importance can also be called the <em>level</em>
or <em>severity</em>.</p>
<div class="section" id="when-to-use-logging">
<h3>When to use logging<a class="headerlink" href="#when-to-use-logging" title="Permalink to this headline">¶</a></h3>
<p>Logging provides a set of convenience functions for simple logging usage. These
are <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">error()</span></code></a> and
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal notranslate"><span class="pre">critical()</span></code></a>. To determine when to use logging, see the table below, which
states, for each of a set of common tasks, the best tool to use for it.</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Task you want to perform</th>
<th class="head">The best tool for the task</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Display console output for ordinary
usage of a command line script or
program</td>
<td><a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a></td>
</tr>
<tr class="row-odd"><td>Report events that occur during
normal operation of a program (e.g.
for status monitoring or fault
investigation)</td>
<td><a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.info()</span></code></a> (or
<a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.debug()</span></code></a> for very
detailed output for diagnostic
purposes)</td>
</tr>
<tr class="row-even"><td>Issue a warning regarding a
particular runtime event</td>
<td><p class="first"><a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.warn()</span></code></a> in library
code if the issue is avoidable and
the client application should be
modified to eliminate the warning</p>
<p class="last"><a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.warning()</span></code></a> if there is
nothing the client application can do
about the situation, but the event
should still be noted</p>
</td>
</tr>
<tr class="row-odd"><td>Report an error regarding a
particular runtime event</td>
<td>Raise an exception</td>
</tr>
<tr class="row-even"><td>Report suppression of an error
without raising an exception (e.g.
error handler in a long-running
server process)</td>
<td><a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.error()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.exception" title="logging.exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.exception()</span></code></a> or
<a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.critical()</span></code></a> as
appropriate for the specific error
and application domain</td>
</tr>
</tbody>
</table>
<p>The logging functions are named after the level or severity of the events
they are used to track. The standard levels and their applicability are
described below (in increasing order of severity):</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">When it’s used</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">DEBUG</span></code></td>
<td>Detailed information, typically of interest
only when diagnosing problems.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INFO</span></code></td>
<td>Confirmation that things are working as
expected.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">WARNING</span></code></td>
<td>An indication that something unexpected
happened, or indicative of some problem in
the near future (e.g. ‘disk space low’).
The software is still working as expected.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ERROR</span></code></td>
<td>Due to a more serious problem, the software
has not been able to perform some function.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code></td>
<td>A serious error, indicating that the program
itself may be unable to continue running.</td>
</tr>
</tbody>
</table>
<p>The default level is <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>, which means that only events of this level
and above will be tracked, unless the logging package is configured to do
otherwise.</p>
<p>Events that are tracked can be handled in different ways. The simplest way of
handling tracked events is to print them to the console. Another common way
is to write them to a disk file.</p>
</div>
<div class="section" id="a-simple-example">
<span id="howto-minimal-example"></span><h3>A simple example<a class="headerlink" href="#a-simple-example" title="Permalink to this headline">¶</a></h3>
<p>A very simple example is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Watch out!&#39;</span><span class="p">)</span>  <span class="c1"># will print a message to the console</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;I told you so&#39;</span><span class="p">)</span>  <span class="c1"># will not print anything</span>
</pre></div>
</div>
<p>If you type these lines into a script and run it, you’ll see:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Watch out!
</pre></div>
</div>
<p>printed out on the console. The <code class="docutils literal notranslate"><span class="pre">INFO</span></code> message doesn’t appear because the
default level is <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>. The printed message includes the indication of
the level and the description of the event provided in the logging call, i.e.
‘Watch out!’. Don’t worry about the ‘root’ part for now: it will be explained
later. The actual output can be formatted quite flexibly if you need that;
formatting options will also be explained later.</p>
</div>
<div class="section" id="logging-to-a-file">
<h3>Logging to a file<a class="headerlink" href="#logging-to-a-file" title="Permalink to this headline">¶</a></h3>
<p>A very common situation is that of recording logging events in a file, so let’s
look at that next. Be sure to try the following in a newly-started Python
interpreter, and don’t just continue from the session described above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span><span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should go to the log file&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>And now if we open the file and look at what we have, we should find the log
messages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">go</span> <span class="n">to</span> <span class="n">the</span> <span class="n">log</span> <span class="n">file</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
<span class="n">WARNING</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
</pre></div>
</div>
<p>This example also shows how you can set the logging level which acts as the
threshold for tracking. In this case, because we set the threshold to
<code class="docutils literal notranslate"><span class="pre">DEBUG</span></code>, all of the messages were printed.</p>
<p>If you want to set the logging level from a command-line option such as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">--</span><span class="n">log</span><span class="o">=</span><span class="n">INFO</span>
</pre></div>
</div>
<p>and you have the value of the parameter passed for <code class="docutils literal notranslate"><span class="pre">--log</span></code> in some variable
<em>loglevel</em>, you can use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
</pre></div>
</div>
<p>to get the value which you’ll pass to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> via the <em>level</em>
argument. You may want to error check any user input value, perhaps as in the
following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># assuming loglevel is bound to the string value obtained from the</span>
<span class="c1"># command line argument. Convert to upper case to allow the user to</span>
<span class="c1"># specify --log=DEBUG or --log=debug</span>
<span class="n">numeric_level</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">logging</span><span class="p">,</span> <span class="n">loglevel</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="kc">None</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">numeric_level</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
    <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;Invalid log level: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">loglevel</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">level</span><span class="o">=</span><span class="n">numeric_level</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The call to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> should come <em>before</em> any calls to <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">info()</span></code></a> etc. As it’s intended as a one-off simple configuration facility,
only the first call will actually do anything: subsequent calls are effectively
no-ops.</p>
<p>If you run the above script several times, the messages from successive runs
are appended to the file <em>example.log</em>. If you want each run to start afresh,
not remembering the messages from earlier runs, you can specify the <em>filemode</em>
argument, by changing the call in the above example to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;example.log&#39;</span><span class="p">,</span> <span class="n">filemode</span><span class="o">=</span><span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
</pre></div>
</div>
<p>The output will be the same as before, but the log file is no longer appended
to, so the messages from earlier runs are lost.</p>
</div>
<div class="section" id="logging-from-multiple-modules">
<h3>Logging from multiple modules<a class="headerlink" href="#logging-from-multiple-modules" title="Permalink to this headline">¶</a></h3>
<p>If your program consists of multiple modules, here’s an example of how you
could organize logging in it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># myapp.py</span>
<span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">mylib</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;myapp.log&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Started&#39;</span><span class="p">)</span>
    <span class="n">mylib</span><span class="o">.</span><span class="n">do_something</span><span class="p">()</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Finished&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># mylib.py</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Doing something&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you run <em>myapp.py</em>, you should see this in <em>myapp.log</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Started</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Doing</span> <span class="n">something</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Finished</span>
</pre></div>
</div>
<p>which is hopefully what you were expecting to see. You can generalize this to
multiple modules, using the pattern in <em>mylib.py</em>. Note that for this simple
usage pattern, you won’t know, by looking in the log file, <em>where</em> in your
application your messages came from, apart from looking at the event
description. If you want to track the location of your messages, you’ll need
to refer to the documentation beyond the tutorial level – see
<a class="reference internal" href="#logging-advanced-tutorial"><span class="std std-ref">Advanced Logging Tutorial</span></a>.</p>
</div>
<div class="section" id="logging-variable-data">
<h3>Logging variable data<a class="headerlink" href="#logging-variable-data" title="Permalink to this headline">¶</a></h3>
<p>To log variable data, use a format string for the event description message and
append the variable data as arguments. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> before you </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;Look&#39;</span><span class="p">,</span> <span class="s1">&#39;leap!&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>will display:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Look before you leap!
</pre></div>
</div>
<p>As you can see, merging of variable data into the event description message
uses the old, %-style of string formatting. This is for backwards
compatibility: the logging package pre-dates newer formatting options such as
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> and <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">string.Template</span></code></a>. These newer formatting
options <em>are</em> supported, but exploring them is outside the scope of this
tutorial.</p>
</div>
<div class="section" id="changing-the-format-of-displayed-messages">
<h3>Changing the format of displayed messages<a class="headerlink" href="#changing-the-format-of-displayed-messages" title="Permalink to this headline">¶</a></h3>
<p>To change the format which is used to display messages, you need to
specify the format you want to use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(levelname)s</span><span class="s1">:</span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">level</span><span class="o">=</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;This message should appear on the console&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;So should this&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;And this, too&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which would print:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DEBUG</span><span class="p">:</span><span class="n">This</span> <span class="n">message</span> <span class="n">should</span> <span class="n">appear</span> <span class="n">on</span> <span class="n">the</span> <span class="n">console</span>
<span class="n">INFO</span><span class="p">:</span><span class="n">So</span> <span class="n">should</span> <span class="n">this</span>
<span class="n">WARNING</span><span class="p">:</span><span class="n">And</span> <span class="n">this</span><span class="p">,</span> <span class="n">too</span>
</pre></div>
</div>
<p>Notice that the ‘root’ which appeared in earlier examples has disappeared. For
a full set of things that can appear in format strings, you can refer to the
documentation for <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>, but for simple usage, you just
need the <em>levelname</em> (severity), <em>message</em> (event description, including
variable data) and perhaps to display when the event occurred. This is
described in the next section.</p>
</div>
<div class="section" id="displaying-the-date-time-in-messages">
<h3>Displaying the date/time in messages<a class="headerlink" href="#displaying-the-date-time-in-messages" title="Permalink to this headline">¶</a></h3>
<p>To display the date and time of an event, you would place ‘%(asctime)s’ in
your format string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which should print something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2010</span><span class="o">-</span><span class="mi">12</span><span class="o">-</span><span class="mi">12</span> <span class="mi">11</span><span class="p">:</span><span class="mi">41</span><span class="p">:</span><span class="mi">42</span><span class="p">,</span><span class="mi">612</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
</pre></div>
</div>
<p>The default format for date/time display (shown above) is ISO8601. If you need
more control over the formatting of the date/time, provide a <em>datefmt</em>
argument to <code class="docutils literal notranslate"><span class="pre">basicConfig</span></code>, as in this example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">datefmt</span><span class="o">=</span><span class="s1">&#39;%m/</span><span class="si">%d</span><span class="s1">/%Y %I:%M:%S %p&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;is when this event was logged.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>which would display something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">12</span><span class="o">/</span><span class="mi">12</span><span class="o">/</span><span class="mi">2010</span> <span class="mi">11</span><span class="p">:</span><span class="mi">46</span><span class="p">:</span><span class="mi">36</span> <span class="n">AM</span> <span class="ow">is</span> <span class="n">when</span> <span class="n">this</span> <span class="n">event</span> <span class="n">was</span> <span class="n">logged</span><span class="o">.</span>
</pre></div>
</div>
<p>The format of the <em>datefmt</em> argument is the same as supported by
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>.</p>
</div>
<div class="section" id="next-steps">
<h3>Next Steps<a class="headerlink" href="#next-steps" title="Permalink to this headline">¶</a></h3>
<p>That concludes the basic tutorial. It should be enough to get you up and
running with logging. There’s a lot more that the logging package offers, but
to get the best out of it, you’ll need to invest a little more of your time in
reading the following sections. If you’re ready for that, grab some of your
favourite beverage and carry on.</p>
<p>If your logging needs are simple, then use the above examples to incorporate
logging into your own scripts, and if you run into problems or don’t
understand something, please post a question on the comp.lang.python Usenet
group (available at <a class="reference external" href="https://groups.google.com/group/comp.lang.python">https://groups.google.com/group/comp.lang.python</a>) and you
should receive help before too long.</p>
<p>Still here? You can carry on reading the next few sections, which provide a
slightly more advanced/in-depth tutorial than the basic one above. After that,
you can take a look at the <a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a>.</p>
</div>
</div>
<div class="section" id="advanced-logging-tutorial">
<span id="logging-advanced-tutorial"></span><h2>Advanced Logging Tutorial<a class="headerlink" href="#advanced-logging-tutorial" title="Permalink to this headline">¶</a></h2>
<p>The logging library takes a modular approach and offers several categories
of components: loggers, handlers, filters, and formatters.</p>
<ul class="simple">
<li>Loggers expose the interface that application code directly uses.</li>
<li>Handlers send the log records (created by loggers) to the appropriate
destination.</li>
<li>Filters provide a finer grained facility for determining which log records
to output.</li>
<li>Formatters specify the layout of log records in the final output.</li>
</ul>
<p>Log event information is passed between loggers, handlers, filters and
formatters in a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance.</p>
<p>Logging is performed by calling methods on instances of the <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>
class (hereafter called <em class="dfn">loggers</em>). Each instance has a name, and they are
conceptually arranged in a namespace hierarchy using dots (periods) as
separators. For example, a logger named ‘scan’ is the parent of loggers
‘scan.text’, ‘scan.html’ and ‘scan.pdf’. Logger names can be anything you want,
and indicate the area of an application in which a logged message originates.</p>
<p>A good convention to use when naming loggers is to use a module-level logger,
in each module which uses logging, named as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
</pre></div>
</div>
<p>This means that logger names track the package/module hierarchy, and it’s
intuitively obvious where events are logged just from the logger name.</p>
<p>The root of the hierarchy of loggers is called the root logger. That’s the
logger used by the functions <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal notranslate"><span class="pre">critical()</span></code></a>, which just call the same-named method of
the root logger. The functions and the methods have the same signatures. The
root logger’s name is printed as ‘root’ in the logged output.</p>
<p>It is, of course, possible to log messages to different destinations. Support
is included in the package for writing log messages to files, HTTP GET/POST
locations, email via SMTP, generic sockets, or OS-specific logging mechanisms
such as syslog or the Windows NT event log. Destinations are served by
<em class="dfn">handler</em> classes. You can create your own log destination class if you
have special requirements not met by any of the built-in handler classes.</p>
<p>By default, no destination is set for any logging messages. You can specify
a destination (such as console or file) by using <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> as in the
tutorial examples. If you call the functions  <a class="reference internal" href="../library/logging.html#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">info()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">error()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal notranslate"><span class="pre">critical()</span></code></a>, they will check to see
if no destination is set; and if one is not set, they will set a destination
of the console (<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>) and a default format for the displayed
message before delegating to the root logger to do the actual message output.</p>
<p>The default format set by <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> for messages is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">severity</span><span class="p">:</span><span class="n">logger</span> <span class="n">name</span><span class="p">:</span><span class="n">message</span>
</pre></div>
</div>
<p>You can change this by passing a format string to <a class="reference internal" href="../library/logging.html#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> with the
<em>format</em> keyword argument. For all options regarding how a format string is
constructed, see <a class="reference internal" href="../library/logging.html#formatter-objects"><span class="std std-ref">Formatter Objects</span></a>.</p>
<div class="section" id="logging-flow">
<h3>Logging Flow<a class="headerlink" href="#logging-flow" title="Permalink to this headline">¶</a></h3>
<p>The flow of log event information in loggers and handlers is illustrated in the
following diagram.</p>
<img alt="../_images/logging_flow.png" src="../_images/logging_flow.png" />
</div>
<div class="section" id="loggers">
<h3>Loggers<a class="headerlink" href="#loggers" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> objects have a threefold job.  First, they expose several
methods to application code so that applications can log messages at runtime.
Second, logger objects determine which log messages to act upon based upon
severity (the default filtering facility) or filter objects.  Third, logger
objects pass along relevant log messages to all interested log handlers.</p>
<p>The most widely used methods on logger objects fall into two categories:
configuration and message sending.</p>
<p>These are the most common configuration methods:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.setLevel" title="logging.Logger.setLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.setLevel()</span></code></a> specifies the lowest-severity log message a logger
will handle, where debug is the lowest built-in severity level and critical
is the highest built-in severity.  For example, if the severity level is
INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages
and will ignore DEBUG messages.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.addHandler()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeHandler" title="logging.Logger.removeHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.removeHandler()</span></code></a> add and remove
handler objects from the logger object.  Handlers are covered in more detail
in <a class="reference internal" href="#handler-basic"><span class="std std-ref">Handlers</span></a>.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.addFilter" title="logging.Logger.addFilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Logger.removeFilter" title="logging.Logger.removeFilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.removeFilter()</span></code></a> add and remove filter
objects from the logger object.  Filters are covered in more detail in
<a class="reference internal" href="../library/logging.html#filter"><span class="std std-ref">Filter Objects</span></a>.</li>
</ul>
<p>You don’t need to always call these methods on every logger you create. See the
last two paragraphs in this section.</p>
<p>With the logger object configured, the following methods create log messages:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/logging.html#logging.Logger.debug" title="logging.Logger.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.debug()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.info" title="logging.Logger.info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.info()</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.Logger.warning" title="logging.Logger.warning"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.warning()</span></code></a>,
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.error()</span></code></a>, and <a class="reference internal" href="../library/logging.html#logging.Logger.critical" title="logging.Logger.critical"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.critical()</span></code></a> all create log records with
a message and a level that corresponds to their respective method names. The
message is actually a format string, which may contain the standard string
substitution syntax of <code class="xref py py-const docutils literal notranslate"><span class="pre">%s</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">%d</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">%f</span></code>, and so on.  The
rest of their arguments is a list of objects that correspond with the
substitution fields in the message.  With regard to <code class="xref py py-const docutils literal notranslate"><span class="pre">**kwargs</span></code>, the
logging methods care only about a keyword of <code class="xref py py-const docutils literal notranslate"><span class="pre">exc_info</span></code> and use it to
determine whether to log exception information.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.exception()</span></code></a> creates a log message similar to
<a class="reference internal" href="../library/logging.html#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.error()</span></code></a>.  The difference is that <a class="reference internal" href="../library/logging.html#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.exception()</span></code></a> dumps a
stack trace along with it.  Call this method only from an exception handler.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger.log" title="logging.Logger.log"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.log()</span></code></a> takes a log level as an explicit argument.  This is a
little more verbose for logging messages than using the log level convenience
methods listed above, but this is how to log at custom log levels.</li>
</ul>
<p><a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal notranslate"><span class="pre">getLogger()</span></code></a> returns a reference to a logger instance with the specified
name if it is provided, or <code class="docutils literal notranslate"><span class="pre">root</span></code> if not.  The names are period-separated
hierarchical structures.  Multiple calls to <a class="reference internal" href="../library/logging.html#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal notranslate"><span class="pre">getLogger()</span></code></a> with the same name
will return a reference to the same logger object.  Loggers that are further
down in the hierarchical list are children of loggers higher up in the list.
For example, given a logger with a name of <code class="docutils literal notranslate"><span class="pre">foo</span></code>, loggers with names of
<code class="docutils literal notranslate"><span class="pre">foo.bar</span></code>, <code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code>, and <code class="docutils literal notranslate"><span class="pre">foo.bam</span></code> are all descendants of <code class="docutils literal notranslate"><span class="pre">foo</span></code>.</p>
<p>Loggers have a concept of <em>effective level</em>. If a level is not explicitly set
on a logger, the level of its parent is used instead as its effective level.
If the parent has no explicit level set, <em>its</em> parent is examined, and so on -
all ancestors are searched until an explicitly set level is found. The root
logger always has an explicit level set (<code class="docutils literal notranslate"><span class="pre">WARNING</span></code> by default). When deciding
whether to process an event, the effective level of the logger is used to
determine whether the event is passed to the logger’s handlers.</p>
<p>Child loggers propagate messages up to the handlers associated with their
ancestor loggers. Because of this, it is unnecessary to define and configure
handlers for all the loggers an application uses. It is sufficient to
configure handlers for a top-level logger and create child loggers as needed.
(You can, however, turn off propagation by setting the <em>propagate</em>
attribute of a logger to <code class="docutils literal notranslate"><span class="pre">False</span></code>.)</p>
</div>
<div class="section" id="handlers">
<span id="handler-basic"></span><h3>Handlers<a class="headerlink" href="#handlers" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> objects are responsible for dispatching the
appropriate log messages (based on the log messages’ severity) to the handler’s
specified destination.  <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> objects can add zero or more handler
objects to themselves with an <a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addHandler()</span></code></a> method.  As an example
scenario, an application may want to send all log messages to a log file, all
log messages of error or higher to stdout, and all messages of critical to an
email address. This scenario requires three individual handlers where each
handler is responsible for sending messages of a specific severity to a specific
location.</p>
<p>The standard library includes quite a few handler types (see
<a class="reference internal" href="#useful-handlers"><span class="std std-ref">Useful Handlers</span></a>); the tutorials use mainly <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> and
<a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> in its examples.</p>
<p>There are very few methods in a handler for application developers to concern
themselves with.  The only handler methods that seem relevant for application
developers who are using the built-in handler objects (that is, not creating
custom handlers) are the following configuration methods:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/logging.html#logging.Handler.setLevel" title="logging.Handler.setLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setLevel()</span></code></a> method, just as in logger objects, specifies the
lowest severity that will be dispatched to the appropriate destination.  Why
are there two <code class="xref py py-func docutils literal notranslate"><span class="pre">setLevel()</span></code> methods?  The level set in the logger
determines which severity of messages it will pass to its handlers.  The level
set in each handler determines which messages that handler will send on.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Handler.setFormatter" title="logging.Handler.setFormatter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setFormatter()</span></code></a> selects a Formatter object for this handler to
use.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addFilter()</span></code></a> and <a class="reference internal" href="../library/logging.html#logging.Handler.removeFilter" title="logging.Handler.removeFilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">removeFilter()</span></code></a> respectively
configure and deconfigure filter objects on handlers.</li>
</ul>
<p>Application code should not directly instantiate and use instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>.  Instead, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> class is a base class that
defines the interface that all handlers should have and establishes some
default behavior that child classes can use (or override).</p>
</div>
<div class="section" id="formatters">
<h3>Formatters<a class="headerlink" href="#formatters" title="Permalink to this headline">¶</a></h3>
<p>Formatter objects configure the final order, structure, and contents of the log
message.  Unlike the base <code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Handler</span></code> class, application code may
instantiate formatter classes, although you could likely subclass the formatter
if your application needs special behavior.  The constructor takes two
optional arguments – a message format string and a date format string.</p>
<dl class="method">
<dt id="logging.logging.Formatter.__init__">
<code class="descclassname">logging.Formatter.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>fmt=None</em>, <em>datefmt=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.logging.Formatter.__init__" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>If there is no message format string, the default is to use the
raw message.  If there is no date format string, the default date format is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="n">Y</span><span class="o">-%</span><span class="n">m</span><span class="o">-%</span><span class="n">d</span> <span class="o">%</span><span class="n">H</span><span class="p">:</span><span class="o">%</span><span class="n">M</span><span class="p">:</span><span class="o">%</span><span class="n">S</span>
</pre></div>
</div>
<p>with the milliseconds tacked on at the end.</p>
<p>The message format string uses <code class="docutils literal notranslate"><span class="pre">%(&lt;dictionary</span> <span class="pre">key&gt;)s</span></code> styled string
substitution; the possible keys are documented in <a class="reference internal" href="../library/logging.html#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>.</p>
<p>The following message format string will log the time in a human-readable
format, the severity of the message, and the contents of the message, in that
order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
</pre></div>
</div>
<p>Formatters use a user-configurable function to convert the creation time of a
record to a tuple. By default, <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> is used; to change this
for a particular formatter instance, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code> attribute of the
instance to a function with the same signature as <a class="reference internal" href="../library/time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> or
<a class="reference internal" href="../library/time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a>. To change it for all formatters, for example if you want
all logging times to be shown in GMT, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code> attribute in the
Formatter class (to <code class="docutils literal notranslate"><span class="pre">time.gmtime</span></code> for GMT display).</p>
</div>
<div class="section" id="configuring-logging">
<h3>Configuring Logging<a class="headerlink" href="#configuring-logging" title="Permalink to this headline">¶</a></h3>
<p>Programmers can configure logging in three ways:</p>
<ol class="arabic simple">
<li>Creating loggers, handlers, and formatters explicitly using Python
code that calls the configuration methods listed above.</li>
<li>Creating a logging config file and reading it using the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a>
function.</li>
<li>Creating a dictionary of configuration information and passing it
to the <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> function.</li>
</ol>
<p>For the reference documentation on the last two options, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.  The following example configures a very simple
logger, a console handler, and a simple formatter using Python code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simple_example&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c1"># create console handler and set level to debug</span>
<span class="n">ch</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span><span class="p">()</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">)</span>

<span class="c1"># create formatter</span>
<span class="n">formatter</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">Formatter</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="c1"># add formatter to ch</span>
<span class="n">ch</span><span class="o">.</span><span class="n">setFormatter</span><span class="p">(</span><span class="n">formatter</span><span class="p">)</span>

<span class="c1"># add ch to logger</span>
<span class="n">logger</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">ch</span><span class="p">)</span>

<span class="c1"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Running this module from the command line produces the following output:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_module.py
<span class="go">2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message</span>
<span class="go">2005-03-19 15:10:26,620 - simple_example - INFO - info message</span>
<span class="go">2005-03-19 15:10:26,695 - simple_example - WARNING - warn message</span>
<span class="go">2005-03-19 15:10:26,697 - simple_example - ERROR - error message</span>
<span class="go">2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message</span>
</pre></div>
</div>
<p>The following Python module creates a logger, handler, and formatter nearly
identical to those in the example listed above, with the only difference being
the names of the objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>

<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">fileConfig</span><span class="p">(</span><span class="s1">&#39;logging.conf&#39;</span><span class="p">)</span>

<span class="c1"># create logger</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;simpleExample&#39;</span><span class="p">)</span>

<span class="c1"># &#39;application&#39; code</span>
<span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;debug message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;info message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s1">&#39;warn message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;error message&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;critical message&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here is the logging.conf file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">loggers</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">root</span><span class="p">,</span><span class="n">simpleExample</span>

<span class="p">[</span><span class="n">handlers</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">consoleHandler</span>

<span class="p">[</span><span class="n">formatters</span><span class="p">]</span>
<span class="n">keys</span><span class="o">=</span><span class="n">simpleFormatter</span>

<span class="p">[</span><span class="n">logger_root</span><span class="p">]</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>

<span class="p">[</span><span class="n">logger_simpleExample</span><span class="p">]</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">handlers</span><span class="o">=</span><span class="n">consoleHandler</span>
<span class="n">qualname</span><span class="o">=</span><span class="n">simpleExample</span>
<span class="n">propagate</span><span class="o">=</span><span class="mi">0</span>

<span class="p">[</span><span class="n">handler_consoleHandler</span><span class="p">]</span>
<span class="n">class</span><span class="o">=</span><span class="n">StreamHandler</span>
<span class="n">level</span><span class="o">=</span><span class="n">DEBUG</span>
<span class="n">formatter</span><span class="o">=</span><span class="n">simpleFormatter</span>
<span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,)</span>

<span class="p">[</span><span class="n">formatter_simpleFormatter</span><span class="p">]</span>
<span class="nb">format</span><span class="o">=%</span><span class="p">(</span><span class="n">asctime</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">name</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">levelname</span><span class="p">)</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="p">(</span><span class="n">message</span><span class="p">)</span><span class="n">s</span>
<span class="n">datefmt</span><span class="o">=</span>
</pre></div>
</div>
<p>The output is nearly identical to that of the non-config-file-based example:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python simple_logging_config.py
<span class="go">2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message</span>
<span class="go">2005-03-19 15:38:55,979 - simpleExample - INFO - info message</span>
<span class="go">2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message</span>
<span class="go">2005-03-19 15:38:56,055 - simpleExample - ERROR - error message</span>
<span class="go">2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message</span>
</pre></div>
</div>
<p>You can see that the config file approach has a few advantages over the Python
code approach, mainly separation of configuration and code and the ability of
noncoders to easily modify the logging properties.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>The <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> function takes a default parameter,
<code class="docutils literal notranslate"><span class="pre">disable_existing_loggers</span></code>, which defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code> for reasons of
backward compatibility. This may or may not be what you want, since it
will cause any loggers existing before the <a class="reference internal" href="../library/logging.config.html#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> call to
be disabled unless they (or an ancestor) are explicitly named in the
configuration.  Please refer to the reference documentation for more
information, and specify <code class="docutils literal notranslate"><span class="pre">False</span></code> for this parameter if you wish.</p>
<p class="last">The dictionary passed to <a class="reference internal" href="../library/logging.config.html#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> can also specify a Boolean
value with key <code class="docutils literal notranslate"><span class="pre">disable_existing_loggers</span></code>, which if not specified
explicitly in the dictionary also defaults to being interpreted as
<code class="docutils literal notranslate"><span class="pre">True</span></code>.  This leads to the logger-disabling behaviour described above,
which may not be what you want - in which case, provide the key
explicitly with a value of <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</div>
<p>Note that the class names referenced in config files need to be either relative
to the logging module, or absolute values which can be resolved using normal
import mechanisms. Thus, you could use either
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> (relative to the logging module) or
<code class="docutils literal notranslate"><span class="pre">mypackage.mymodule.MyHandler</span></code> (for a class defined in package <code class="docutils literal notranslate"><span class="pre">mypackage</span></code>
and module <code class="docutils literal notranslate"><span class="pre">mymodule</span></code>, where <code class="docutils literal notranslate"><span class="pre">mypackage</span></code> is available on the Python import
path).</p>
<p>In Python 2.7, a new means of configuring logging has been introduced, using
dictionaries to hold configuration information. This provides a superset of the
functionality of the config-file-based approach outlined above, and is the
recommended configuration method for new applications and deployments. Because
a Python dictionary is used to hold configuration information, and since you
can populate that dictionary using different means, you have more options for
configuration. For example, you can use a configuration file in JSON format,
or, if you have access to YAML processing functionality, a file in YAML
format, to populate the configuration dictionary. Or, of course, you can
construct the dictionary in Python code, receive it in pickled form over a
socket, or use whatever approach makes sense for your application.</p>
<p>Here’s an example of the same configuration as above, in YAML format for
the new dictionary-based approach:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">version</span><span class="p">:</span> <span class="mi">1</span>
<span class="n">formatters</span><span class="p">:</span>
  <span class="n">simple</span><span class="p">:</span>
    <span class="nb">format</span><span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> - </span><span class="si">%(name)s</span><span class="s1"> - </span><span class="si">%(levelname)s</span><span class="s1"> - </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
<span class="n">handlers</span><span class="p">:</span>
  <span class="n">console</span><span class="p">:</span>
    <span class="n">class</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">StreamHandler</span>
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
    <span class="n">formatter</span><span class="p">:</span> <span class="n">simple</span>
    <span class="n">stream</span><span class="p">:</span> <span class="n">ext</span><span class="p">:</span><span class="o">//</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span>
<span class="n">loggers</span><span class="p">:</span>
  <span class="n">simpleExample</span><span class="p">:</span>
    <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
    <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
    <span class="n">propagate</span><span class="p">:</span> <span class="n">no</span>
<span class="n">root</span><span class="p">:</span>
  <span class="n">level</span><span class="p">:</span> <span class="n">DEBUG</span>
  <span class="n">handlers</span><span class="p">:</span> <span class="p">[</span><span class="n">console</span><span class="p">]</span>
</pre></div>
</div>
<p>For more information about logging using a dictionary, see
<a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.</p>
</div>
<div class="section" id="what-happens-if-no-configuration-is-provided">
<h3>What happens if no configuration is provided<a class="headerlink" href="#what-happens-if-no-configuration-is-provided" title="Permalink to this headline">¶</a></h3>
<p>If no logging configuration is provided, it is possible to have a situation
where a logging event needs to be output, but no handlers can be found to
output the event. The behaviour of the logging package in these
circumstances is dependent on the Python version.</p>
<p>For Python 2.x, the behaviour is as follows:</p>
<ul class="simple">
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> (production mode), the event is
silently dropped.</li>
<li>If <em>logging.raiseExceptions</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (development mode), a message
‘No handlers could be found for logger X.Y.Z’ is printed once.</li>
</ul>
</div>
<div class="section" id="configuring-logging-for-a-library">
<span id="library-config"></span><h3>Configuring Logging for a Library<a class="headerlink" href="#configuring-logging-for-a-library" title="Permalink to this headline">¶</a></h3>
<p>When developing a library which uses logging, you should take care to
document how the library uses logging - for example, the names of loggers
used. Some consideration also needs to be given to its logging configuration.
If the using application does not configure logging, and library code makes
logging calls, then (as described in the previous section) an error message
will be printed to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.</p>
<p>If for some reason you <em>don’t</em> want this message printed in the absence of
any logging configuration, you can attach a do-nothing handler to the top-level
logger for your library. This avoids the message being printed, since a handler
will be always be found for the library’s events: it just doesn’t produce any
output. If the library user configures logging for application use, presumably
that configuration will add some handlers, and if levels are suitably
configured then logging calls made in library code will send output to those
handlers, as normal.</p>
<p>A do-nothing handler is included in the logging package:
<a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> (since Python 2.7). An instance of this handler
could be added to the top-level logger of the logging namespace used by the
library (<em>if</em> you want to prevent an error message being output to
<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> in the absence of logging configuration). If all logging by a
library <em>foo</em> is done using loggers with names matching ‘foo.x’, ‘foo.x.y’,
etc. then the code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">addHandler</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">NullHandler</span><span class="p">())</span>
</pre></div>
</div>
<p>should have the desired effect. If an organisation produces a number of
libraries, then the logger name specified can be ‘orgname.foo’ rather than
just ‘foo’.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is strongly advised that you <em>do not add any handlers other
than</em> <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> <em>to your library’s loggers</em>. This is
because the configuration of handlers is the prerogative of the application
developer who uses your library. The application developer knows their
target audience and what handlers are most appropriate for their
application: if you add handlers ‘under the hood’, you might well interfere
with their ability to carry out unit tests and deliver logs which suit their
requirements.</p>
</div>
</div>
</div>
<div class="section" id="logging-levels">
<h2>Logging Levels<a class="headerlink" href="#logging-levels" title="Permalink to this headline">¶</a></h2>
<p>The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">Numeric value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code></td>
<td>50</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ERROR</span></code></td>
<td>40</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">WARNING</span></code></td>
<td>30</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INFO</span></code></td>
<td>20</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">DEBUG</span></code></td>
<td>10</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">NOTSET</span></code></td>
<td>0</td>
</tr>
</tbody>
</table>
<p>Levels can also be associated with loggers, being set either by the developer or
through loading a saved logging configuration. When a logging method is called
on a logger, the logger compares its own level with the level associated with
the method call. If the logger’s level is higher than the method call’s, no
logging message is actually generated. This is the basic mechanism controlling
the verbosity of logging output.</p>
<p>Logging messages are encoded as instances of the <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>
class. When a logger decides to actually log an event, a
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance is created from the logging message.</p>
<p>Logging messages are subjected to a dispatch mechanism through the use of
<em class="dfn">handlers</em>, which are instances of subclasses of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>
class. Handlers are responsible for ensuring that a logged message (in the form
of a <a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>) ends up in a particular location (or set of locations)
which is useful for the target audience for that message (such as end users,
support desk staff, system administrators, developers). Handlers are passed
<a class="reference internal" href="../library/logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instances intended for particular destinations. Each logger
can have zero, one or more handlers associated with it (via the
<a class="reference internal" href="../library/logging.html#logging.Logger.addHandler" title="logging.Logger.addHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addHandler()</span></code></a> method of <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>). In addition to any
handlers directly associated with a logger, <em>all handlers associated with all
ancestors of the logger</em> are called to dispatch the message (unless the
<em>propagate</em> flag for a logger is set to a false value, at which point the
passing to ancestor handlers stops).</p>
<p>Just as for loggers, handlers can have levels associated with them. A handler’s
level acts as a filter in the same way as a logger’s level does. If a handler
decides to actually dispatch an event, the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a> method is used
to send the message to its destination. Most user-defined subclasses of
<code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> will need to override this <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>.</p>
<div class="section" id="custom-levels">
<span id="id1"></span><h3>Custom Levels<a class="headerlink" href="#custom-levels" title="Permalink to this headline">¶</a></h3>
<p>Defining your own levels is possible, but should not be necessary, as the
existing levels have been chosen on the basis of practical experience.
However, if you are convinced that you need custom levels, great care should
be exercised when doing this, and it is possibly <em>a very bad idea to define
custom levels if you are developing a library</em>. That’s because if multiple
library authors all define their own custom levels, there is a chance that
the logging output from such multiple libraries used together will be
difficult for the using developer to control and/or interpret, because a
given numeric value might mean different things for different libraries.</p>
</div>
</div>
<div class="section" id="useful-handlers">
<span id="id2"></span><h2>Useful Handlers<a class="headerlink" href="#useful-handlers" title="Permalink to this headline">¶</a></h2>
<p>In addition to the base <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> class, many useful subclasses are
provided:</p>
<ol class="arabic simple">
<li><a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> instances send messages to streams (file-like
objects).</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> instances send messages to disk files.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRotatingHandler</span></code> is the base class for handlers that
rotate log files at a certain point. It is not meant to be  instantiated
directly. Instead, use <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> or
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code></a>.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> instances send messages to disk
files, with support for maximum log file sizes and log file rotation.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code></a> instances send messages to
disk files, rotating the log file at certain timed intervals.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> instances send messages to TCP/IP
sockets.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DatagramHandler</span></code></a> instances send messages to UDP
sockets.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPHandler</span></code></a> instances send messages to a designated
email address.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> instances send messages to a Unix
syslog daemon, possibly on a remote machine.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NTEventLogHandler</span></code></a> instances send messages to a
Windows NT/2000/XP event log.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a> instances send messages to a buffer
in memory, which is flushed whenever specific criteria are met.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a> instances send messages to an HTTP
server using either <code class="docutils literal notranslate"><span class="pre">GET</span></code> or <code class="docutils literal notranslate"><span class="pre">POST</span></code> semantics.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> instances watch the file they are
logging to. If the file changes, it is closed and reopened using the file
name. This handler is only useful on Unix-like systems; Windows does not
support the underlying mechanism used.</li>
<li><a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> instances do nothing with error messages. They are used
by library developers who want to use logging, but want to avoid the ‘No
handlers could be found for logger XXX’ message which can be displayed if
the library user has not configured logging. See <a class="reference internal" href="#library-config"><span class="std std-ref">Configuring Logging for a Library</span></a> for
more information.</li>
</ol>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> class.</p>
</div>
<p>The <a class="reference internal" href="../library/logging.handlers.html#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a>, <a class="reference internal" href="../library/logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> and <a class="reference internal" href="../library/logging.handlers.html#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a>
classes are defined in the core logging package. The other handlers are
defined in a sub- module, <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>. (There is also another
sub-module, <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a>, for configuration functionality.)</p>
<p>Logged messages are formatted for presentation through instances of the
<a class="reference internal" href="../library/logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> class. They are initialized with a format string suitable for
use with the % operator and a dictionary.</p>
<p>For formatting multiple messages in a batch, instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferingFormatter</span></code> can be used. In addition to the format
string (which is applied to each message in the batch), there is provision for
header and trailer format strings.</p>
<p>When filtering based on logger level and/or handler level is not enough,
instances of <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> can be added to both <a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> instances (through their <a class="reference internal" href="../library/logging.html#logging.Handler.addFilter" title="logging.Handler.addFilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addFilter()</span></code></a> method).
Before deciding to process a message further, both loggers and handlers consult
all their filters for permission. If any filter returns a false value, the
message is not processed further.</p>
<p>The basic <a class="reference internal" href="../library/logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.</p>
</div>
<div class="section" id="exceptions-raised-during-logging">
<span id="logging-exceptions"></span><h2>Exceptions raised during logging<a class="headerlink" href="#exceptions-raised-during-logging" title="Permalink to this headline">¶</a></h2>
<p>The logging package is designed to swallow exceptions which occur while logging
in production. This is so that errors which occur while handling logging events
- such as logging misconfiguration, network or other similar errors - do not
cause the application using logging to terminate prematurely.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">SystemExit</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code> exceptions are never
swallowed. Other exceptions which occur during the <a class="reference internal" href="../library/logging.html#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a> method
of a <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> subclass are passed to its <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handleError()</span></code></a>
method.</p>
<p>The default implementation of <a class="reference internal" href="../library/logging.html#logging.Handler.handleError" title="logging.Handler.handleError"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handleError()</span></code></a> in <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>
checks to see if a module-level variable, <code class="xref py py-data docutils literal notranslate"><span class="pre">raiseExceptions</span></code>, is set. If
set, a traceback is printed to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>. If not set, the exception is
swallowed.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The default value of <code class="xref py py-data docutils literal notranslate"><span class="pre">raiseExceptions</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>. This is
because during development, you typically want to be notified of any
exceptions that occur. It’s advised that you set <code class="xref py py-data docutils literal notranslate"><span class="pre">raiseExceptions</span></code> to
<code class="docutils literal notranslate"><span class="pre">False</span></code> for production usage.</p>
</div>
</div>
<div class="section" id="using-arbitrary-objects-as-messages">
<span id="arbitrary-object-messages"></span><h2>Using arbitrary objects as messages<a class="headerlink" href="#using-arbitrary-objects-as-messages" title="Permalink to this headline">¶</a></h2>
<p>In the preceding sections and examples, it has been assumed that the message
passed when logging the event is a string. However, this is not the only
possibility. You can pass an arbitrary object as a message, and its
<a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> method will be called when the logging system needs to
convert it to a string representation. In fact, if you want to, you can avoid
computing a string representation altogether - for example, the
<a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> emits an event by pickling it and sending it
over the wire.</p>
</div>
<div class="section" id="optimization">
<h2>Optimization<a class="headerlink" href="#optimization" title="Permalink to this headline">¶</a></h2>
<p>Formatting of message arguments is deferred until it cannot be avoided.
However, computing the arguments passed to the logging method can also be
expensive, and you may want to avoid doing it if the logger will just throw
away your event. To decide what to do, you can call the
<a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code></a> method which takes a level argument and returns
true if the event would be created by the Logger for that level of call.
You can write code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">logger</span><span class="o">.</span><span class="n">isEnabledFor</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">DEBUG</span><span class="p">):</span>
    <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Message with </span><span class="si">%s</span><span class="s1">, </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">expensive_func1</span><span class="p">(),</span>
                                        <span class="n">expensive_func2</span><span class="p">())</span>
</pre></div>
</div>
<p>so that if the logger’s threshold is set above <code class="docutils literal notranslate"><span class="pre">DEBUG</span></code>, the calls to
<code class="xref py py-func docutils literal notranslate"><span class="pre">expensive_func1()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">expensive_func2()</span></code> are never made.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In some cases, <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code></a> can itself be more
expensive than you’d like (e.g. for deeply nested loggers where an explicit
level is only set high up in the logger hierarchy). In such cases (or if you
want to avoid calling a method in tight loops), you can cache the result of a
call to <a class="reference internal" href="../library/logging.html#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code></a> in a local or instance variable, and use
that instead of calling the method each time. Such a cached value would only
need to be recomputed when the logging configuration changes dynamically
while the application is running (which is not all that common).</p>
</div>
<p>There are other optimizations which can be made for specific applications which
need more precise control over what logging information is collected. Here’s a
list of things you can do to avoid processing during logging which you don’t
need:</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">What you don’t want to collect</th>
<th class="head">How to avoid collecting it</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Information about where calls were made from.</td>
<td>Set <code class="docutils literal notranslate"><span class="pre">logging._srcfile</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code>.
This avoids calling
<a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys._getframe()</span></code></a>, which may help
to speed up your code in environments
like PyPy (which can’t speed up code
that uses <a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys._getframe()</span></code></a>).</td>
</tr>
<tr class="row-odd"><td>Threading information.</td>
<td>Set <code class="docutils literal notranslate"><span class="pre">logging.logThreads</span></code> to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</td>
</tr>
<tr class="row-even"><td>Process information.</td>
<td>Set <code class="docutils literal notranslate"><span class="pre">logging.logProcesses</span></code> to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</td>
</tr>
</tbody>
</table>
<p>Also note that the core logging module only includes the basic handlers. If
you don’t import <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> and <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a>, they won’t
take up any memory.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt>Module <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a></dt>
<dd>API reference for the logging module.</dd>
<dt>Module <a class="reference internal" href="../library/logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a></dt>
<dd>Configuration API for the logging module.</dd>
<dt>Module <a class="reference internal" href="../library/logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a></dt>
<dd>Useful handlers included with the logging module.</dd>
</dl>
<p class="last"><a class="reference internal" href="logging-cookbook.html#logging-cookbook"><span class="std std-ref">A logging cookbook</span></a></p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Logging HOWTO</a><ul>
<li><a class="reference internal" href="#basic-logging-tutorial">Basic Logging Tutorial</a><ul>
<li><a class="reference internal" href="#when-to-use-logging">When to use logging</a></li>
<li><a class="reference internal" href="#a-simple-example">A simple example</a></li>
<li><a class="reference internal" href="#logging-to-a-file">Logging to a file</a></li>
<li><a class="reference internal" href="#logging-from-multiple-modules">Logging from multiple modules</a></li>
<li><a class="reference internal" href="#logging-variable-data">Logging variable data</a></li>
<li><a class="reference internal" href="#changing-the-format-of-displayed-messages">Changing the format of displayed messages</a></li>
<li><a class="reference internal" href="#displaying-the-date-time-in-messages">Displaying the date/time in messages</a></li>
<li><a class="reference internal" href="#next-steps">Next Steps</a></li>
</ul>
</li>
<li><a class="reference internal" href="#advanced-logging-tutorial">Advanced Logging Tutorial</a><ul>
<li><a class="reference internal" href="#logging-flow">Logging Flow</a></li>
<li><a class="reference internal" href="#loggers">Loggers</a></li>
<li><a class="reference internal" href="#handlers">Handlers</a></li>
<li><a class="reference internal" href="#formatters">Formatters</a></li>
<li><a class="reference internal" href="#configuring-logging">Configuring Logging</a></li>
<li><a class="reference internal" href="#what-happens-if-no-configuration-is-provided">What happens if no configuration is provided</a></li>
<li><a class="reference internal" href="#configuring-logging-for-a-library">Configuring Logging for a Library</a></li>
</ul>
</li>
<li><a class="reference internal" href="#logging-levels">Logging Levels</a><ul>
<li><a class="reference internal" href="#custom-levels">Custom Levels</a></li>
</ul>
</li>
<li><a class="reference internal" href="#useful-handlers">Useful Handlers</a></li>
<li><a class="reference internal" href="#exceptions-raised-during-logging">Exceptions raised during logging</a></li>
<li><a class="reference internal" href="#using-arbitrary-objects-as-messages">Using arbitrary objects as messages</a></li>
<li><a class="reference internal" href="#optimization">Optimization</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="functional.html"
                        title="previous chapter">Functional Programming HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging-cookbook.html"
                        title="next chapter">Logging Cookbook</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/logging.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             >next</a> |</li>
        <li class="right" >
          <a href="functional.html" title="Functional Programming HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1[��+�+�html/howto/pyporting.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Porting Python 2 Code to Python 3 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Porting Extension Modules to Python 3" href="cporting.html" />
    <link rel="prev" title="Python HOWTOs" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/pyporting.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python HOWTOs"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="porting-python-2-code-to-python-3">
<span id="pyporting-howto"></span><h1>Porting Python 2 Code to Python 3<a class="headerlink" href="#porting-python-2-code-to-python-3" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">author:</th><td class="field-body">Brett Cannon</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>With Python 3 being the future of Python while Python 2 is still in active
use, it is good to have your project available for both major releases of
Python. This guide is meant to help you figure out how best to support both
Python 2 &amp; 3 simultaneously.</p>
<p>If you are looking to port an extension module instead of pure Python code,
please see <a class="reference internal" href="cporting.html#cporting-howto"><span class="std std-ref">Porting Extension Modules to Python 3</span></a>.</p>
<p>If you would like to read one core Python developer’s take on why Python 3
came into existence, you can read Nick Coghlan’s <a class="reference external" href="https://ncoghlan-devs-python-notes.readthedocs.org/en/latest/python3/questions_and_answers.html">Python 3 Q &amp; A</a> or
Brett Cannon’s <a class="reference external" href="http://www.snarky.ca/why-python-3-exists">Why Python 3 exists</a>.</p>
<p>For help with porting, you can email the <a class="reference external" href="https://mail.python.org/mailman/listinfo/python-porting">python-porting</a> mailing list with
questions.</p>
</div>
<div class="section" id="the-short-explanation">
<h2>The Short Explanation<a class="headerlink" href="#the-short-explanation" title="Permalink to this headline">¶</a></h2>
<p>To make your project be single-source Python 2/3 compatible, the basic steps
are:</p>
<ol class="arabic simple">
<li>Only worry about supporting Python 2.7</li>
<li>Make sure you have good test coverage (<a class="reference external" href="https://pypi.org/project/coverage">coverage.py</a> can help;
<code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">coverage</span></code>)</li>
<li>Learn the differences between Python 2 &amp; 3</li>
<li>Use <a class="reference external" href="http://python-future.org/automatic_conversion.html">Futurize</a> (or <a class="reference external" href="https://python-modernize.readthedocs.org/en/latest/">Modernize</a>) to update your code (e.g. <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">future</span></code>)</li>
<li>Use <a class="reference external" href="https://pypi.org/project/pylint">Pylint</a> to help make sure you don’t regress on your Python 3 support
(<code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">pylint</span></code>)</li>
<li>Use <a class="reference external" href="https://pypi.org/project/caniusepython3">caniusepython3</a> to find out which of your dependencies are blocking your
use of Python 3 (<code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">caniusepython3</span></code>)</li>
<li>Once your dependencies are no longer blocking you, use continuous integration
to make sure you stay compatible with Python 2 &amp; 3 (<a class="reference external" href="https://pypi.org/project/tox">tox</a> can help test
against multiple versions of Python; <code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">tox</span></code>)</li>
<li>Consider using optional static type checking to make sure your type usage
works in both Python 2 &amp; 3 (e.g. use <a class="reference external" href="http://mypy-lang.org/">mypy</a> to check your typing under both
Python 2 &amp; Python 3).</li>
</ol>
</div>
<div class="section" id="details">
<h2>Details<a class="headerlink" href="#details" title="Permalink to this headline">¶</a></h2>
<p>A key point about supporting Python 2 &amp; 3 simultaneously is that you can start
<strong>today</strong>! Even if your dependencies are not supporting Python 3 yet that does
not mean you can’t modernize your code <strong>now</strong> to support Python 3. Most changes
required to support Python 3 lead to cleaner code using newer practices even in
Python 2 code.</p>
<p>Another key point is that modernizing your Python 2 code to also support
Python 3 is largely automated for you. While you might have to make some API
decisions thanks to Python 3 clarifying text data versus binary data, the
lower-level work is now mostly done for you and thus can at least benefit from
the automated changes immediately.</p>
<p>Keep those key points in mind while you read on about the details of porting
your code to support Python 2 &amp; 3 simultaneously.</p>
<div class="section" id="drop-support-for-python-2-6-and-older">
<h3>Drop support for Python 2.6 and older<a class="headerlink" href="#drop-support-for-python-2-6-and-older" title="Permalink to this headline">¶</a></h3>
<p>While you can make Python 2.5 work with Python 3, it is <strong>much</strong> easier if you
only have to work with Python 2.7. If dropping Python 2.5 is not an
option then the <a class="reference external" href="https://pypi.org/project/six">six</a> project can help you support Python 2.5 &amp; 3 simultaneously
(<code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">six</span></code>). Do realize, though, that nearly all the projects listed
in this HOWTO will not be available to you.</p>
<p>If you are able to skip Python 2.5 and older, then the required changes
to your code should continue to look and feel like idiomatic Python code. At
worst you will have to use a function instead of a method in some instances or
have to import a function instead of using a built-in one, but otherwise the
overall transformation should not feel foreign to you.</p>
<p>But you should aim for only supporting Python 2.7. Python 2.6 is no longer
freely supported and thus is not receiving bugfixes. This means <strong>you</strong> will have
to work around any issues you come across with Python 2.6. There are also some
tools mentioned in this HOWTO which do not support Python 2.6 (e.g., <a class="reference external" href="https://pypi.org/project/pylint">Pylint</a>),
and this will become more commonplace as time goes on. It will simply be easier
for you if you only support the versions of Python that you have to support.</p>
</div>
<div class="section" id="make-sure-you-specify-the-proper-version-support-in-your-setup-py-file">
<h3>Make sure you specify the proper version support in your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file<a class="headerlink" href="#make-sure-you-specify-the-proper-version-support-in-your-setup-py-file" title="Permalink to this headline">¶</a></h3>
<p>In your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file you should have the proper <a class="reference external" href="https://pypi.org/classifiers">trove classifier</a>
specifying what versions of Python you support. As your project does not support
Python 3 yet you should at least have
<code class="docutils literal notranslate"><span class="pre">Programming</span> <span class="pre">Language</span> <span class="pre">::</span> <span class="pre">Python</span> <span class="pre">::</span> <span class="pre">2</span> <span class="pre">::</span> <span class="pre">Only</span></code> specified. Ideally you should
also specify each major/minor version of Python that you do support, e.g.
<code class="docutils literal notranslate"><span class="pre">Programming</span> <span class="pre">Language</span> <span class="pre">::</span> <span class="pre">Python</span> <span class="pre">::</span> <span class="pre">2.7</span></code>.</p>
</div>
<div class="section" id="have-good-test-coverage">
<h3>Have good test coverage<a class="headerlink" href="#have-good-test-coverage" title="Permalink to this headline">¶</a></h3>
<p>Once you have your code supporting the oldest version of Python 2 you want it
to, you will want to make sure your test suite has good coverage. A good rule of
thumb is that if you want to be confident enough in your test suite that any
failures that appear after having tools rewrite your code are actual bugs in the
tools and not in your code. If you want a number to aim for, try to get over 80%
coverage (and don’t feel bad if you find it hard to get better than 90%
coverage). If you don’t already have a tool to measure test coverage then
<a class="reference external" href="https://pypi.org/project/coverage">coverage.py</a> is recommended.</p>
</div>
<div class="section" id="learn-the-differences-between-python-2-3">
<h3>Learn the differences between Python 2 &amp; 3<a class="headerlink" href="#learn-the-differences-between-python-2-3" title="Permalink to this headline">¶</a></h3>
<p>Once you have your code well-tested you are ready to begin porting your code to
Python 3! But to fully understand how your code is going to change and what
you want to look out for while you code, you will want to learn what changes
Python 3 makes in terms of Python 2. Typically the two best ways of doing that
is reading the <a class="reference external" href="https://docs.python.org/3/whatsnew/index.html">“What’s New”</a> doc for each release of Python 3 and the
<a class="reference external" href="http://python3porting.com/">Porting to Python 3</a> book (which is free online). There is also a handy
<a class="reference external" href="http://python-future.org/compatible_idioms.html">cheat sheet</a> from the Python-Future project.</p>
</div>
<div class="section" id="update-your-code">
<h3>Update your code<a class="headerlink" href="#update-your-code" title="Permalink to this headline">¶</a></h3>
<p>Once you feel like you know what is different in Python 3 compared to Python 2,
it’s time to update your code! You have a choice between two tools in porting
your code automatically: <a class="reference external" href="http://python-future.org/automatic_conversion.html">Futurize</a> and <a class="reference external" href="https://python-modernize.readthedocs.org/en/latest/">Modernize</a>. Which tool you choose will
depend on how much like Python 3 you want your code to be. <a class="reference external" href="http://python-future.org/automatic_conversion.html">Futurize</a> does its
best to make Python 3 idioms and practices exist in Python 2, e.g. backporting
the <code class="docutils literal notranslate"><span class="pre">bytes</span></code> type from Python 3 so that you have semantic parity between the
major versions of Python. <a class="reference external" href="https://python-modernize.readthedocs.org/en/latest/">Modernize</a>,
on the other hand, is more conservative and targets a Python 2/3 subset of
Python, directly relying on <a class="reference external" href="https://pypi.org/project/six">six</a> to help provide compatibility. As Python 3 is
the future, it might be best to consider Futurize to begin adjusting to any new
practices that Python 3 introduces which you are not accustomed to yet.</p>
<p>Regardless of which tool you choose, they will update your code to run under
Python 3 while staying compatible with the version of Python 2 you started with.
Depending on how conservative you want to be, you may want to run the tool over
your test suite first and visually inspect the diff to make sure the
transformation is accurate. After you have transformed your test suite and
verified that all the tests still pass as expected, then you can transform your
application code knowing that any tests which fail is a translation failure.</p>
<p>Unfortunately the tools can’t automate everything to make your code work under
Python 3 and so there are a handful of things you will need to update manually
to get full Python 3 support (which of these steps are necessary vary between
the tools). Read the documentation for the tool you choose to use to see what it
fixes by default and what it can do optionally to know what will (not) be fixed
for you and what you may have to fix on your own (e.g. using <code class="docutils literal notranslate"><span class="pre">io.open()</span></code> over
the built-in <code class="docutils literal notranslate"><span class="pre">open()</span></code> function is off by default in Modernize). Luckily,
though, there are only a couple of things to watch out for which can be
considered large issues that may be hard to debug if not watched for.</p>
<div class="section" id="division">
<h4>Division<a class="headerlink" href="#division" title="Permalink to this headline">¶</a></h4>
<p>In Python 3, <code class="docutils literal notranslate"><span class="pre">5</span> <span class="pre">/</span> <span class="pre">2</span> <span class="pre">==</span> <span class="pre">2.5</span></code> and not <code class="docutils literal notranslate"><span class="pre">2</span></code>; all division between <code class="docutils literal notranslate"><span class="pre">int</span></code> values
result in a <code class="docutils literal notranslate"><span class="pre">float</span></code>. This change has actually been planned since Python 2.2
which was released in 2002. Since then users have been encouraged to add
<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code> to any and all files which use the <code class="docutils literal notranslate"><span class="pre">/</span></code> and
<code class="docutils literal notranslate"><span class="pre">//</span></code> operators or to be running the interpreter with the <code class="docutils literal notranslate"><span class="pre">-Q</span></code> flag. If you
have not been doing this then you will need to go through your code and do two
things:</p>
<ol class="arabic simple">
<li>Add <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code> to your files</li>
<li>Update any division operator as necessary to either use <code class="docutils literal notranslate"><span class="pre">//</span></code> to use floor
division or continue using <code class="docutils literal notranslate"><span class="pre">/</span></code> and expect a float</li>
</ol>
<p>The reason that <code class="docutils literal notranslate"><span class="pre">/</span></code> isn’t simply translated to <code class="docutils literal notranslate"><span class="pre">//</span></code> automatically is that if
an object defines a <code class="docutils literal notranslate"><span class="pre">__truediv__</span></code> method but not <code class="docutils literal notranslate"><span class="pre">__floordiv__</span></code> then your
code would begin to fail (e.g. a user-defined class that uses <code class="docutils literal notranslate"><span class="pre">/</span></code> to
signify some operation but not <code class="docutils literal notranslate"><span class="pre">//</span></code> for the same thing or at all).</p>
</div>
<div class="section" id="text-versus-binary-data">
<h4>Text versus binary data<a class="headerlink" href="#text-versus-binary-data" title="Permalink to this headline">¶</a></h4>
<p>In Python 2 you could use the <code class="docutils literal notranslate"><span class="pre">str</span></code> type for both text and binary data.
Unfortunately this confluence of two different concepts could lead to brittle
code which sometimes worked for either kind of data, sometimes not. It also
could lead to confusing APIs if people didn’t explicitly state that something
that accepted <code class="docutils literal notranslate"><span class="pre">str</span></code> accepted either text or binary data instead of one
specific type. This complicated the situation especially for anyone supporting
multiple languages as APIs wouldn’t bother explicitly supporting <code class="docutils literal notranslate"><span class="pre">unicode</span></code>
when they claimed text data support.</p>
<p>To make the distinction between text and binary data clearer and more
pronounced, Python 3 did what most languages created in the age of the internet
have done and made text and binary data distinct types that cannot blindly be
mixed together (Python predates widespread access to the internet). For any code
that deals only with text or only binary data, this separation doesn’t pose an
issue. But for code that has to deal with both, it does mean you might have to
now care about when you are using text compared to binary data, which is why
this cannot be entirely automated.</p>
<p>To start, you will need to decide which APIs take text and which take binary
(it is <strong>highly</strong> recommended you don’t design APIs that can take both due to
the difficulty of keeping the code working; as stated earlier it is difficult to
do well). In Python 2 this means making sure the APIs that take text can work
with <code class="docutils literal notranslate"><span class="pre">unicode</span></code> and those that work with binary data work with the
<code class="docutils literal notranslate"><span class="pre">bytes</span></code> type from Python 3 (which is a subset of <code class="docutils literal notranslate"><span class="pre">str</span></code> in Python 2 and acts
as an alias for <code class="docutils literal notranslate"><span class="pre">bytes</span></code> type in Python 2). Usually the biggest issue is
realizing which methods exist on which types in Python 2 &amp; 3 simultaneously
(for text that’s <code class="docutils literal notranslate"><span class="pre">unicode</span></code> in Python 2 and <code class="docutils literal notranslate"><span class="pre">str</span></code> in Python 3, for binary
that’s <code class="docutils literal notranslate"><span class="pre">str</span></code>/<code class="docutils literal notranslate"><span class="pre">bytes</span></code> in Python 2 and <code class="docutils literal notranslate"><span class="pre">bytes</span></code> in Python 3). The following
table lists the <strong>unique</strong> methods of each data type across Python 2 &amp; 3
(e.g., the <code class="docutils literal notranslate"><span class="pre">decode()</span></code> method is usable on the equivalent binary data type in
either Python 2 or 3, but it can’t be used by the textual data type consistently
between Python 2 and 3 because <code class="docutils literal notranslate"><span class="pre">str</span></code> in Python 3 doesn’t have the method). Do
note that as of Python 3.5 the <code class="docutils literal notranslate"><span class="pre">__mod__</span></code> method was added to the bytes type.</p>
<table border="1" class="docutils">
<colgroup>
<col width="53%" />
<col width="47%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><strong>Text data</strong></td>
<td><strong>Binary data</strong></td>
</tr>
<tr class="row-even"><td></td>
<td>decode</td>
</tr>
<tr class="row-odd"><td>encode</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>format</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>isdecimal</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>isnumeric</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Making the distinction easier to handle can be accomplished by encoding and
decoding between binary data and text at the edge of your code. This means that
when you receive text in binary data, you should immediately decode it. And if
your code needs to send text as binary data then encode it as late as possible.
This allows your code to work with only text internally and thus eliminates
having to keep track of what type of data you are working with.</p>
<p>The next issue is making sure you know whether the string literals in your code
represent text or binary data. You should add a <code class="docutils literal notranslate"><span class="pre">b</span></code> prefix to any
literal that presents binary data. For text you should add a <code class="docutils literal notranslate"><span class="pre">u</span></code> prefix to
the text literal. (there is a <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> import to force all unspecified
literals to be Unicode, but usage has shown it isn’t as effective as adding a
<code class="docutils literal notranslate"><span class="pre">b</span></code> or <code class="docutils literal notranslate"><span class="pre">u</span></code> prefix to all literals explicitly)</p>
<p>As part of this dichotomy you also need to be careful about opening files.
Unless you have been working on Windows, there is a chance you have not always
bothered to add the <code class="docutils literal notranslate"><span class="pre">b</span></code> mode when opening a binary file (e.g., <code class="docutils literal notranslate"><span class="pre">rb</span></code> for
binary reading).  Under Python 3, binary files and text files are clearly
distinct and mutually incompatible; see the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module for details.
Therefore, you <strong>must</strong> make a decision of whether a file will be used for
binary access (allowing binary data to be read and/or written) or textual access
(allowing text data to be read and/or written). You should also use <a class="reference internal" href="../library/io.html#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">io.open()</span></code></a>
for opening files instead of the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function as the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a>
module is consistent from Python 2 to 3 while the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function
is not (in Python 3 it’s actually <a class="reference internal" href="../library/io.html#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">io.open()</span></code></a>). Do not bother with the
outdated practice of using <a class="reference internal" href="../library/codecs.html#codecs.open" title="codecs.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.open()</span></code></a> as that’s only necessary for
keeping compatibility with Python 2.5.</p>
<p>The constructors of both <code class="docutils literal notranslate"><span class="pre">str</span></code> and <code class="docutils literal notranslate"><span class="pre">bytes</span></code> have different semantics for the
same arguments between Python 2 &amp; 3. Passing an integer to <code class="docutils literal notranslate"><span class="pre">bytes</span></code> in Python 2
will give you the string representation of the integer: <code class="docutils literal notranslate"><span class="pre">bytes(3)</span> <span class="pre">==</span> <span class="pre">'3'</span></code>.
But in Python 3, an integer argument to <code class="docutils literal notranslate"><span class="pre">bytes</span></code> will give you a bytes object
as long as the integer specified, filled with null bytes:
<code class="docutils literal notranslate"><span class="pre">bytes(3)</span> <span class="pre">==</span> <span class="pre">b'\x00\x00\x00'</span></code>. A similar worry is necessary when passing a
bytes object to <code class="docutils literal notranslate"><span class="pre">str</span></code>. In Python 2 you just get the bytes object back:
<code class="docutils literal notranslate"><span class="pre">str(b'3')</span> <span class="pre">==</span> <span class="pre">b'3'</span></code>. But in Python 3 you get the string representation of the
bytes object: <code class="docutils literal notranslate"><span class="pre">str(b'3')</span> <span class="pre">==</span> <span class="pre">&quot;b'3'&quot;</span></code>.</p>
<p>Finally, the indexing of binary data requires careful handling (slicing does
<strong>not</strong> require any special handling). In Python 2,
<code class="docutils literal notranslate"><span class="pre">b'123'[1]</span> <span class="pre">==</span> <span class="pre">b'2'</span></code> while in Python 3 <code class="docutils literal notranslate"><span class="pre">b'123'[1]</span> <span class="pre">==</span> <span class="pre">50</span></code>. Because binary data
is simply a collection of binary numbers, Python 3 returns the integer value for
the byte you index on. But in Python 2 because <code class="docutils literal notranslate"><span class="pre">bytes</span> <span class="pre">==</span> <span class="pre">str</span></code>, indexing
returns a one-item slice of bytes. The <a class="reference external" href="https://pypi.org/project/six">six</a> project has a function
named <code class="docutils literal notranslate"><span class="pre">six.indexbytes()</span></code> which will return an integer like in Python 3:
<code class="docutils literal notranslate"><span class="pre">six.indexbytes(b'123',</span> <span class="pre">1)</span></code>.</p>
<p>To summarize:</p>
<ol class="arabic simple">
<li>Decide which of your APIs take text and which take binary data</li>
<li>Make sure that your code that works with text also works with <code class="docutils literal notranslate"><span class="pre">unicode</span></code> and
code for binary data works with <code class="docutils literal notranslate"><span class="pre">bytes</span></code> in Python 2 (see the table above
for what methods you cannot use for each type)</li>
<li>Mark all binary literals with a <code class="docutils literal notranslate"><span class="pre">b</span></code> prefix, textual literals with a <code class="docutils literal notranslate"><span class="pre">u</span></code>
prefix</li>
<li>Decode binary data to text as soon as possible, encode text as binary data as
late as possible</li>
<li>Open files using <a class="reference internal" href="../library/io.html#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">io.open()</span></code></a> and make sure to specify the <code class="docutils literal notranslate"><span class="pre">b</span></code> mode when
appropriate</li>
<li>Be careful when indexing into binary data</li>
</ol>
</div>
<div class="section" id="use-feature-detection-instead-of-version-detection">
<h4>Use feature detection instead of version detection<a class="headerlink" href="#use-feature-detection-instead-of-version-detection" title="Permalink to this headline">¶</a></h4>
<p>Inevitably you will have code that has to choose what to do based on what
version of Python is running. The best way to do this is with feature detection
of whether the version of Python you’re running under supports what you need.
If for some reason that doesn’t work then you should make the version check be
against Python 2 and not Python 3. To help explain this, let’s look at an
example.</p>
<p>Let’s pretend that you need access to a feature of <a class="reference external" href="https://docs.python.org/3/library/importlib.html#module-importlib">importlib</a> that
is available in Python’s standard library since Python 3.3 and available for
Python 2 through <a class="reference external" href="https://pypi.org/project/importlib2">importlib2</a> on PyPI. You might be tempted to write code to
access e.g. the <code class="docutils literal notranslate"><span class="pre">importlib.abc</span></code> module by doing the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="mi">3</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">abc</span>
<span class="k">else</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib2</span> <span class="k">import</span> <span class="n">abc</span>
</pre></div>
</div>
<p>The problem with this code is what happens when Python 4 comes out? It would
be better to treat Python 2 as the exceptional case instead of Python 3 and
assume that future Python versions will be more compatible with Python 3 than
Python 2:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">&gt;</span> <span class="mi">2</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">abc</span>
<span class="k">else</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib2</span> <span class="k">import</span> <span class="n">abc</span>
</pre></div>
</div>
<p>The best solution, though, is to do no version detection at all and instead rely
on feature detection. That avoids any potential issues of getting the version
detection wrong and helps keep you future-compatible:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">abc</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">importlib2</span> <span class="k">import</span> <span class="n">abc</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="prevent-compatibility-regressions">
<h3>Prevent compatibility regressions<a class="headerlink" href="#prevent-compatibility-regressions" title="Permalink to this headline">¶</a></h3>
<p>Once you have fully translated your code to be compatible with Python 3, you
will want to make sure your code doesn’t regress and stop working under
Python 3. This is especially true if you have a dependency which is blocking you
from actually running under Python 3 at the moment.</p>
<p>To help with staying compatible, any new modules you create should have
at least the following block of code at the top of it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">absolute_import</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">division</span>
<span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">print_function</span>
</pre></div>
</div>
<p>You can also run Python 2 with the <code class="docutils literal notranslate"><span class="pre">-3</span></code> flag to be warned about various
compatibility issues your code triggers during execution. If you turn warnings
into errors with <code class="docutils literal notranslate"><span class="pre">-Werror</span></code> then you can make sure that you don’t accidentally
miss a warning.</p>
<p>You can also use the <a class="reference external" href="https://pypi.org/project/pylint">Pylint</a> project and its <code class="docutils literal notranslate"><span class="pre">--py3k</span></code> flag to lint your code
to receive warnings when your code begins to deviate from Python 3
compatibility. This also prevents you from having to run <a class="reference external" href="https://python-modernize.readthedocs.org/en/latest/">Modernize</a> or <a class="reference external" href="http://python-future.org/automatic_conversion.html">Futurize</a>
over your code regularly to catch compatibility regressions. This does require
you only support Python 2.7 and Python 3.4 or newer as that is Pylint’s
minimum Python version support.</p>
</div>
<div class="section" id="check-which-dependencies-block-your-transition">
<h3>Check which dependencies block your transition<a class="headerlink" href="#check-which-dependencies-block-your-transition" title="Permalink to this headline">¶</a></h3>
<p><strong>After</strong> you have made your code compatible with Python 3 you should begin to
care about whether your dependencies have also been ported. The <a class="reference external" href="https://pypi.org/project/caniusepython3">caniusepython3</a>
project was created to help you determine which projects
– directly or indirectly – are blocking you from supporting Python 3. There
is both a command-line tool as well as a web interface at
<a class="reference external" href="https://caniusepython3.com">https://caniusepython3.com</a>.</p>
<p>The project also provides code which you can integrate into your test suite so
that you will have a failing test when you no longer have dependencies blocking
you from using Python 3. This allows you to avoid having to manually check your
dependencies and to be notified quickly when you can start running on Python 3.</p>
</div>
<div class="section" id="update-your-setup-py-file-to-denote-python-3-compatibility">
<h3>Update your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file to denote Python 3 compatibility<a class="headerlink" href="#update-your-setup-py-file-to-denote-python-3-compatibility" title="Permalink to this headline">¶</a></h3>
<p>Once your code works under Python 3, you should update the classifiers in
your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> to contain <code class="docutils literal notranslate"><span class="pre">Programming</span> <span class="pre">Language</span> <span class="pre">::</span> <span class="pre">Python</span> <span class="pre">::</span> <span class="pre">3</span></code> and to not
specify sole Python 2 support. This will tell anyone using your code that you
support Python 2 <strong>and</strong> 3. Ideally you will also want to add classifiers for
each major/minor version of Python you now support.</p>
</div>
<div class="section" id="use-continuous-integration-to-stay-compatible">
<h3>Use continuous integration to stay compatible<a class="headerlink" href="#use-continuous-integration-to-stay-compatible" title="Permalink to this headline">¶</a></h3>
<p>Once you are able to fully run under Python 3 you will want to make sure your
code always works under both Python 2 &amp; 3. Probably the best tool for running
your tests under multiple Python interpreters is <a class="reference external" href="https://pypi.org/project/tox">tox</a>. You can then integrate
tox with your continuous integration system so that you never accidentally break
Python 2 or 3 support.</p>
<p>You may also want to use the <code class="docutils literal notranslate"><span class="pre">-bb</span></code> flag with the Python 3 interpreter to
trigger an exception when you are comparing bytes to strings or bytes to an int
(the latter is available starting in Python 3.5). By default type-differing
comparisons simply return <code class="docutils literal notranslate"><span class="pre">False</span></code>, but if you made a mistake in your
separation of text/binary data handling or indexing on bytes you wouldn’t easily
find the mistake. This flag will raise an exception when these kinds of
comparisons occur, making the mistake much easier to track down.</p>
<p>And that’s mostly it! At this point your code base is compatible with both
Python 2 and 3 simultaneously. Your testing will also be set up so that you
don’t accidentally break Python 2 or 3 compatibility regardless of which version
you typically run your tests under while developing.</p>
</div>
<div class="section" id="consider-using-optional-static-type-checking">
<h3>Consider using optional static type checking<a class="headerlink" href="#consider-using-optional-static-type-checking" title="Permalink to this headline">¶</a></h3>
<p>Another way to help port your code is to use a static type checker like
<a class="reference external" href="http://mypy-lang.org/">mypy</a> or <a class="reference external" href="https://github.com/google/pytype">pytype</a> on your code. These tools can be used to analyze your code as
if it’s being run under Python 2, then you can run the tool a second time as if
your code is running under Python 3. By running a static type checker twice like
this you can discover if you’re e.g. misusing binary data type in one version
of Python compared to another. If you add optional type hints to your code you
can also explicitly state whether your APIs use textual or binary data, helping
to make sure everything functions as expected in both versions of Python.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Porting Python 2 Code to Python 3</a><ul>
<li><a class="reference internal" href="#the-short-explanation">The Short Explanation</a></li>
<li><a class="reference internal" href="#details">Details</a><ul>
<li><a class="reference internal" href="#drop-support-for-python-2-6-and-older">Drop support for Python 2.6 and older</a></li>
<li><a class="reference internal" href="#make-sure-you-specify-the-proper-version-support-in-your-setup-py-file">Make sure you specify the proper version support in your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file</a></li>
<li><a class="reference internal" href="#have-good-test-coverage">Have good test coverage</a></li>
<li><a class="reference internal" href="#learn-the-differences-between-python-2-3">Learn the differences between Python 2 &amp; 3</a></li>
<li><a class="reference internal" href="#update-your-code">Update your code</a><ul>
<li><a class="reference internal" href="#division">Division</a></li>
<li><a class="reference internal" href="#text-versus-binary-data">Text versus binary data</a></li>
<li><a class="reference internal" href="#use-feature-detection-instead-of-version-detection">Use feature detection instead of version detection</a></li>
</ul>
</li>
<li><a class="reference internal" href="#prevent-compatibility-regressions">Prevent compatibility regressions</a></li>
<li><a class="reference internal" href="#check-which-dependencies-block-your-transition">Check which dependencies block your transition</a></li>
<li><a class="reference internal" href="#update-your-setup-py-file-to-denote-python-3-compatibility">Update your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file to denote Python 3 compatibility</a></li>
<li><a class="reference internal" href="#use-continuous-integration-to-stay-compatible">Use continuous integration to stay compatible</a></li>
<li><a class="reference internal" href="#consider-using-optional-static-type-checking">Consider using optional static type checking</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Python HOWTOs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cporting.html"
                        title="next chapter">Porting Extension Modules to Python 3</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/pyporting.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cporting.html" title="Porting Extension Modules to Python 3"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python HOWTOs"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\?�u9D9Dhtml/howto/regex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Regular Expression HOWTO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Socket Programming HOWTO" href="sockets.html" />
    <link rel="prev" title="Logging Cookbook" href="logging-cookbook.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/regex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="regular-expression-howto">
<span id="regex-howto"></span><h1>Regular Expression HOWTO<a class="headerlink" href="#regular-expression-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling &lt;<a class="reference external" href="mailto:amk&#37;&#52;&#48;amk&#46;ca">amk<span>&#64;</span>amk<span>&#46;</span>ca</a>&gt;</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document is an introductory tutorial to using regular expressions in Python
with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module.  It provides a gentler introduction than the
corresponding section in the Library Reference.</p>
</div>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module was added in Python 1.5, and provides Perl-style regular
expression patterns.  Earlier versions of Python came with the <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code>
module, which provided Emacs-style patterns.  The <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module was
removed completely in Python 2.5.</p>
<p>Regular expressions (called REs, or regexes, or regex patterns) are essentially
a tiny, highly specialized programming language embedded inside Python and made
available through the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module. Using this little language, you specify
the rules for the set of possible strings that you want to match; this set might
contain English sentences, or e-mail addresses, or TeX commands, or anything you
like.  You can then ask questions such as “Does this string match the pattern?”,
or “Is there a match for the pattern anywhere in this string?”.  You can also
use REs to modify a string or to split it apart in various ways.</p>
<p>Regular expression patterns are compiled into a series of bytecodes which are
then executed by a matching engine written in C.  For advanced use, it may be
necessary to pay careful attention to how the engine will execute a given RE,
and write the RE in a certain way in order to produce bytecode that runs faster.
Optimization isn’t covered in this document, because it requires that you have a
good understanding of the matching engine’s internals.</p>
<p>The regular expression language is relatively small and restricted, so not all
possible string processing tasks can be done using regular expressions.  There
are also tasks that <em>can</em> be done with regular expressions, but the expressions
turn out to be very complicated.  In these cases, you may be better off writing
Python code to do the processing; while Python code will be slower than an
elaborate regular expression, it will also probably be more understandable.</p>
</div>
<div class="section" id="simple-patterns">
<h2>Simple Patterns<a class="headerlink" href="#simple-patterns" title="Permalink to this headline">¶</a></h2>
<p>We’ll start by learning about the simplest possible regular expressions.  Since
regular expressions are used to operate on strings, we’ll begin with the most
common task: matching characters.</p>
<p>For a detailed explanation of the computer science underlying regular
expressions (deterministic and non-deterministic finite automata), you can refer
to almost any textbook on writing compilers.</p>
<div class="section" id="matching-characters">
<h3>Matching Characters<a class="headerlink" href="#matching-characters" title="Permalink to this headline">¶</a></h3>
<p>Most letters and characters will simply match themselves.  For example, the
regular expression <code class="docutils literal notranslate"><span class="pre">test</span></code> will match the string <code class="docutils literal notranslate"><span class="pre">test</span></code> exactly.  (You can
enable a case-insensitive mode that would let this RE match <code class="docutils literal notranslate"><span class="pre">Test</span></code> or <code class="docutils literal notranslate"><span class="pre">TEST</span></code>
as well; more about this later.)</p>
<p>There are exceptions to this rule; some characters are special
<em class="dfn">metacharacters</em>, and don’t match themselves.  Instead, they signal that
some out-of-the-ordinary thing should be matched, or they affect other portions
of the RE by repeating them or changing their meaning.  Much of this document is
devoted to discussing various metacharacters and what they do.</p>
<p>Here’s a complete list of the metacharacters; their meanings will be discussed
in the rest of this HOWTO.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>. ^ $ * + ? { } [ ] \ | ( )
</pre></div>
</div>
<p>The first metacharacters we’ll look at are <code class="docutils literal notranslate"><span class="pre">[</span></code> and <code class="docutils literal notranslate"><span class="pre">]</span></code>. They’re used for
specifying a character class, which is a set of characters that you wish to
match.  Characters can be listed individually, or a range of characters can be
indicated by giving two characters and separating them by a <code class="docutils literal notranslate"><span class="pre">'-'</span></code>.  For
example, <code class="docutils literal notranslate"><span class="pre">[abc]</span></code> will match any of the characters <code class="docutils literal notranslate"><span class="pre">a</span></code>, <code class="docutils literal notranslate"><span class="pre">b</span></code>, or <code class="docutils literal notranslate"><span class="pre">c</span></code>; this
is the same as <code class="docutils literal notranslate"><span class="pre">[a-c]</span></code>, which uses a range to express the same set of
characters.  If you wanted to match only lowercase letters, your RE would be
<code class="docutils literal notranslate"><span class="pre">[a-z]</span></code>.</p>
<p>Metacharacters are not active inside classes.  For example, <code class="docutils literal notranslate"><span class="pre">[akm$]</span></code> will
match any of the characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'k'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'$'</span></code>; <code class="docutils literal notranslate"><span class="pre">'$'</span></code> is
usually a metacharacter, but inside a character class it’s stripped of its
special nature.</p>
<p>You can match the characters not listed within the class by <em class="dfn">complementing</em>
the set.  This is indicated by including a <code class="docutils literal notranslate"><span class="pre">'^'</span></code> as the first character of the
class; <code class="docutils literal notranslate"><span class="pre">'^'</span></code> outside a character class will simply match the <code class="docutils literal notranslate"><span class="pre">'^'</span></code>
character.  For example, <code class="docutils literal notranslate"><span class="pre">[^5]</span></code> will match any character except <code class="docutils literal notranslate"><span class="pre">'5'</span></code>.</p>
<p>Perhaps the most important metacharacter is the backslash, <code class="docutils literal notranslate"><span class="pre">\</span></code>.   As in Python
string literals, the backslash can be followed by various characters to signal
various special sequences.  It’s also used to escape all the metacharacters so
you can still match them in patterns; for example, if you need to match a <code class="docutils literal notranslate"><span class="pre">[</span></code>
or  <code class="docutils literal notranslate"><span class="pre">\</span></code>, you can precede them with a backslash to remove their special
meaning: <code class="docutils literal notranslate"><span class="pre">\[</span></code> or <code class="docutils literal notranslate"><span class="pre">\\</span></code>.</p>
<p>Some of the special sequences beginning with <code class="docutils literal notranslate"><span class="pre">'\'</span></code> represent predefined sets
of characters that are often useful, such as the set of digits, the set of
letters, or the set of anything that isn’t whitespace.  The following predefined
special sequences are a subset of those available. The equivalent classes are
for byte string patterns. For a complete list of sequences and expanded class
definitions for Unicode string patterns, see the last part of
<a class="reference internal" href="../library/re.html#re-syntax"><span class="std std-ref">Regular Expression Syntax</span></a>.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">\d</span></code></dt>
<dd>Matches any decimal digit; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\D</span></code></dt>
<dd>Matches any non-digit character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^0-9]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\s</span></code></dt>
<dd>Matches any whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[</span>
<span class="pre">\t\n\r\f\v]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\S</span></code></dt>
<dd>Matches any non-whitespace character; this is equivalent to the class <code class="docutils literal notranslate"><span class="pre">[^</span>
<span class="pre">\t\n\r\f\v]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\w</span></code></dt>
<dd>Matches any alphanumeric character; this is equivalent to the class
<code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\W</span></code></dt>
<dd>Matches any non-alphanumeric character; this is equivalent to the class
<code class="docutils literal notranslate"><span class="pre">[^a-zA-Z0-9_]</span></code>.</dd>
</dl>
<p>These sequences can be included inside a character class.  For example,
<code class="docutils literal notranslate"><span class="pre">[\s,.]</span></code> is a character class that will match any whitespace character, or
<code class="docutils literal notranslate"><span class="pre">','</span></code> or <code class="docutils literal notranslate"><span class="pre">'.'</span></code>.</p>
<p>The final metacharacter in this section is <code class="docutils literal notranslate"><span class="pre">.</span></code>.  It matches anything except a
newline character, and there’s an alternate mode (<code class="docutils literal notranslate"><span class="pre">re.DOTALL</span></code>) where it will
match even a newline.  <code class="docutils literal notranslate"><span class="pre">'.'</span></code> is often used where you want to match “any
character”.</p>
</div>
<div class="section" id="repeating-things">
<h3>Repeating Things<a class="headerlink" href="#repeating-things" title="Permalink to this headline">¶</a></h3>
<p>Being able to match varying sets of characters is the first thing regular
expressions can do that isn’t already possible with the methods available on
strings.  However, if that was the only additional capability of regexes, they
wouldn’t be much of an advance. Another capability is that you can specify that
portions of the RE must be repeated a certain number of times.</p>
<p>The first metacharacter for repeating things that we’ll look at is <code class="docutils literal notranslate"><span class="pre">*</span></code>.  <code class="docutils literal notranslate"><span class="pre">*</span></code>
doesn’t match the literal character <code class="docutils literal notranslate"><span class="pre">*</span></code>; instead, it specifies that the
previous character can be matched zero or more times, instead of exactly once.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">ca*t</span></code> will match <code class="docutils literal notranslate"><span class="pre">ct</span></code> (0 <code class="docutils literal notranslate"><span class="pre">a</span></code> characters), <code class="docutils literal notranslate"><span class="pre">cat</span></code> (1 <code class="docutils literal notranslate"><span class="pre">a</span></code>),
<code class="docutils literal notranslate"><span class="pre">caaat</span></code> (3 <code class="docutils literal notranslate"><span class="pre">a</span></code> characters), and so forth.  The RE engine has various
internal limitations stemming from the size of C’s <code class="docutils literal notranslate"><span class="pre">int</span></code> type that will
prevent it from matching over 2 billion <code class="docutils literal notranslate"><span class="pre">a</span></code> characters; you probably don’t
have enough memory to construct a string that large, so you shouldn’t run into
that limit.</p>
<p>Repetitions such as <code class="docutils literal notranslate"><span class="pre">*</span></code> are <em class="dfn">greedy</em>; when repeating a RE, the matching
engine will try to repeat it as many times as possible. If later portions of the
pattern don’t match, the matching engine will then back up and try again with
fewer repetitions.</p>
<p>A step-by-step example will make this more obvious.  Let’s consider the
expression <code class="docutils literal notranslate"><span class="pre">a[bcd]*b</span></code>.  This matches the letter <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, zero or more letters
from the class <code class="docutils literal notranslate"><span class="pre">[bcd]</span></code>, and finally ends with a <code class="docutils literal notranslate"><span class="pre">'b'</span></code>.  Now imagine matching
this RE against the string <code class="docutils literal notranslate"><span class="pre">abcbd</span></code>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="22%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Step</th>
<th class="head">Matched</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>1</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span></code></td>
<td>The <code class="docutils literal notranslate"><span class="pre">a</span></code> in the RE matches.</td>
</tr>
<tr class="row-odd"><td>2</td>
<td><code class="docutils literal notranslate"><span class="pre">abcbd</span></code></td>
<td>The engine matches <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>,
going as far as it can, which
is to the end of the string.</td>
</tr>
<tr class="row-even"><td>3</td>
<td><em>Failure</em></td>
<td>The engine tries to match
<code class="docutils literal notranslate"><span class="pre">b</span></code>, but the current position
is at the end of the string, so
it fails.</td>
</tr>
<tr class="row-odd"><td>4</td>
<td><code class="docutils literal notranslate"><span class="pre">abcb</span></code></td>
<td>Back up, so that  <code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>
matches one less character.</td>
</tr>
<tr class="row-even"><td>5</td>
<td><em>Failure</em></td>
<td>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again, but the
current position is at the last
character, which is a <code class="docutils literal notranslate"><span class="pre">'d'</span></code>.</td>
</tr>
<tr class="row-odd"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">abc</span></code></td>
<td>Back up again, so that
<code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code> is only matching
<code class="docutils literal notranslate"><span class="pre">bc</span></code>.</td>
</tr>
<tr class="row-even"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">abcb</span></code></td>
<td>Try <code class="docutils literal notranslate"><span class="pre">b</span></code> again.  This time
the character at the
current position is <code class="docutils literal notranslate"><span class="pre">'b'</span></code>, so
it succeeds.</td>
</tr>
</tbody>
</table>
<p>The end of the RE has now been reached, and it has matched <code class="docutils literal notranslate"><span class="pre">abcb</span></code>.  This
demonstrates how the matching engine goes as far as it can at first, and if no
match is found it will then progressively back up and retry the rest of the RE
again and again.  It will back up until it has tried zero matches for
<code class="docutils literal notranslate"><span class="pre">[bcd]*</span></code>, and if that subsequently fails, the engine will conclude that the
string doesn’t match the RE at all.</p>
<p>Another repeating metacharacter is <code class="docutils literal notranslate"><span class="pre">+</span></code>, which matches one or more times.  Pay
careful attention to the difference between <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">+</span></code>; <code class="docutils literal notranslate"><span class="pre">*</span></code> matches
<em>zero</em> or more times, so whatever’s being repeated may not be present at all,
while <code class="docutils literal notranslate"><span class="pre">+</span></code> requires at least <em>one</em> occurrence.  To use a similar example,
<code class="docutils literal notranslate"><span class="pre">ca+t</span></code> will match <code class="docutils literal notranslate"><span class="pre">cat</span></code> (1 <code class="docutils literal notranslate"><span class="pre">a</span></code>), <code class="docutils literal notranslate"><span class="pre">caaat</span></code> (3 <code class="docutils literal notranslate"><span class="pre">a</span></code>’s), but won’t match
<code class="docutils literal notranslate"><span class="pre">ct</span></code>.</p>
<p>There are two more repeating qualifiers.  The question mark character, <code class="docutils literal notranslate"><span class="pre">?</span></code>,
matches either once or zero times; you can think of it as marking something as
being optional.  For example, <code class="docutils literal notranslate"><span class="pre">home-?brew</span></code> matches either <code class="docutils literal notranslate"><span class="pre">homebrew</span></code> or
<code class="docutils literal notranslate"><span class="pre">home-brew</span></code>.</p>
<p>The most complicated repeated qualifier is <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>, where <em>m</em> and <em>n</em> are
decimal integers.  This qualifier means there must be at least <em>m</em> repetitions,
and at most <em>n</em>.  For example, <code class="docutils literal notranslate"><span class="pre">a/{1,3}b</span></code> will match <code class="docutils literal notranslate"><span class="pre">a/b</span></code>, <code class="docutils literal notranslate"><span class="pre">a//b</span></code>, and
<code class="docutils literal notranslate"><span class="pre">a///b</span></code>.  It won’t match <code class="docutils literal notranslate"><span class="pre">ab</span></code>, which has no slashes, or <code class="docutils literal notranslate"><span class="pre">a////b</span></code>, which
has four.</p>
<p>You can omit either <em>m</em> or <em>n</em>; in that case, a reasonable value is assumed for
the missing value.  Omitting <em>m</em> is interpreted as a lower limit of 0, while
omitting <em>n</em> results in an upper bound of infinity — actually, the upper bound
is the 2-billion limit mentioned earlier, but that might as well be infinity.</p>
<p>Readers of a reductionist bent may notice that the three other qualifiers can
all be expressed using this notation.  <code class="docutils literal notranslate"><span class="pre">{0,}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">{1,}</span></code>
is equivalent to <code class="docutils literal notranslate"><span class="pre">+</span></code>, and <code class="docutils literal notranslate"><span class="pre">{0,1}</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">?</span></code>.  It’s better to use
<code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, or <code class="docutils literal notranslate"><span class="pre">?</span></code> when you can, simply because they’re shorter and easier
to read.</p>
</div>
</div>
<div class="section" id="using-regular-expressions">
<h2>Using Regular Expressions<a class="headerlink" href="#using-regular-expressions" title="Permalink to this headline">¶</a></h2>
<p>Now that we’ve looked at some simple regular expressions, how do we actually use
them in Python?  The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides an interface to the regular
expression engine, allowing you to compile REs into objects and then perform
matches with them.</p>
<div class="section" id="compiling-regular-expressions">
<h3>Compiling Regular Expressions<a class="headerlink" href="#compiling-regular-expressions" title="Permalink to this headline">¶</a></h3>
<p>Regular expressions are compiled into pattern objects, which have
methods for various operations such as searching for pattern matches or
performing string substitutions.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;ab*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>  
<span class="go">&lt;_sre.SRE_Pattern object at 0x...&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> also accepts an optional <em>flags</em> argument, used to enable
various special features and syntax variations.  We’ll go over the available
settings later, but for now a single example will do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;ab*&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
</pre></div>
</div>
<p>The RE is passed to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> as a string.  REs are handled as strings
because regular expressions aren’t part of the core Python language, and no
special syntax was created for expressing them.  (There are applications that
don’t need REs at all, so there’s no need to bloat the language specification by
including them.) Instead, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is simply a C extension module
included with Python, just like the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> or <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> modules.</p>
<p>Putting REs in strings keeps the Python language simpler, but has one
disadvantage which is the topic of the next section.</p>
</div>
<div class="section" id="the-backslash-plague">
<h3>The Backslash Plague<a class="headerlink" href="#the-backslash-plague" title="Permalink to this headline">¶</a></h3>
<p>As stated earlier, regular expressions use the backslash character (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) to
indicate special forms or to allow special characters to be used without
invoking their special meaning. This conflicts with Python’s usage of the same
character for the same purpose in string literals.</p>
<p>Let’s say you want to write a RE that matches the string <code class="docutils literal notranslate"><span class="pre">\section</span></code>, which
might be found in a LaTeX file.  To figure out what to write in the program
code, start with the desired string to be matched.  Next, you must escape any
backslashes and other metacharacters by preceding them with a backslash,
resulting in the string <code class="docutils literal notranslate"><span class="pre">\\section</span></code>.  The resulting string that must be passed
to <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> must be <code class="docutils literal notranslate"><span class="pre">\\section</span></code>.  However, to express this as a
Python string literal, both backslashes must be escaped <em>again</em>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Characters</th>
<th class="head">Stage</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\section</span></code></td>
<td>Text string to be matched</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\\section</span></code></td>
<td>Escaped backslash for <a class="reference internal" href="../library/re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;\\\\section&quot;</span></code></td>
<td>Escaped backslashes for a string literal</td>
</tr>
</tbody>
</table>
<p>In short, to match a literal backslash, one has to write <code class="docutils literal notranslate"><span class="pre">'\\\\'</span></code> as the RE
string, because the regular expression must be <code class="docutils literal notranslate"><span class="pre">\\</span></code>, and each backslash must
be expressed as <code class="docutils literal notranslate"><span class="pre">\\</span></code> inside a regular Python string literal.  In REs that
feature backslashes repeatedly, this leads to lots of repeated backslashes and
makes the resulting strings difficult to understand.</p>
<p>The solution is to use Python’s raw string notation for regular expressions;
backslashes are not handled in any special way in a string literal prefixed with
<code class="docutils literal notranslate"><span class="pre">'r'</span></code>, so <code class="docutils literal notranslate"><span class="pre">r&quot;\n&quot;</span></code> is a two-character string containing <code class="docutils literal notranslate"><span class="pre">'\'</span></code> and <code class="docutils literal notranslate"><span class="pre">'n'</span></code>,
while <code class="docutils literal notranslate"><span class="pre">&quot;\n&quot;</span></code> is a one-character string containing a newline. Regular
expressions will often be written in Python code using this raw string notation.</p>
<table border="1" class="docutils">
<colgroup>
<col width="51%" />
<col width="49%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Regular String</th>
<th class="head">Raw string</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;ab*&quot;</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r&quot;ab*&quot;</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&quot;\\\\section&quot;</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r&quot;\\section&quot;</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;\\w+\\s+\\1&quot;</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">r&quot;\w+\s+\1&quot;</span></code></td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="performing-matches">
<h3>Performing Matches<a class="headerlink" href="#performing-matches" title="Permalink to this headline">¶</a></h3>
<p>Once you have an object representing a compiled regular expression, what do you
do with it?  Pattern objects have several methods and attributes.
Only the most significant ones will be covered here; consult the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> docs
for a complete listing.</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">match()</span></code></td>
<td>Determine if the RE matches at the beginning
of the string.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">search()</span></code></td>
<td>Scan through a string, looking for any
location where this RE matches.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">findall()</span></code></td>
<td>Find all substrings where the RE matches, and
returns them as a list.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">finditer()</span></code></td>
<td>Find all substrings where the RE matches, and
returns them as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code> return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no match can be found.  If
they’re successful, a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance is returned,
containing information about the match: where it starts and ends, the substring
it matched, and more.</p>
<p>You can learn about this by interactively experimenting with the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
module.  If you have Tkinter available, you may also want to look at
<a class="reference external" href="https://github.com/python/cpython/tree/2.7/Tools/scripts/redemo.py">Tools/scripts/redemo.py</a>, a demonstration program included with the
Python distribution.  It allows you to enter REs and strings, and displays
whether the RE matches or fails. <code class="file docutils literal notranslate"><span class="pre">redemo.py</span></code> can be quite useful when
trying to debug a complicated RE.  Phil Schwartz’s <a class="reference external" href="http://kodos.sourceforge.net/">Kodos</a> is also an interactive tool for developing and
testing RE patterns.</p>
<p>This HOWTO uses the standard Python interpreter for its examples. First, run the
Python interpreter, import the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module, and compile a RE:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Python</span> <span class="mf">2.2</span><span class="o">.</span><span class="mi">2</span> <span class="p">(</span><span class="c1">#1, Feb 10 2003, 12:57:01)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="kn">import</span> <span class="nn">re</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;[a-z]+&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">p</span>  <span class="c1">#doctest: +ELLIPSIS</span>
<span class="o">&lt;</span><span class="n">_sre</span><span class="o">.</span><span class="n">SRE_Pattern</span> <span class="nb">object</span> <span class="n">at</span> <span class="mi">0</span><span class="n">x</span><span class="o">...&gt;</span>
</pre></div>
</div>
<p>Now, you can try matching various strings against the RE <code class="docutils literal notranslate"><span class="pre">[a-z]+</span></code>.  An empty
string shouldn’t match at all, since <code class="docutils literal notranslate"><span class="pre">+</span></code> means ‘one or more repetitions’.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> should return <code class="docutils literal notranslate"><span class="pre">None</span></code> in this case, which will cause the
interpreter to print no output.  You can explicitly print the result of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> to make this clear.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>Now, let’s try it on a string that it should match, such as <code class="docutils literal notranslate"><span class="pre">tempo</span></code>.  In this
case, <code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> will return a <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a>, so you
should store the result in a variable for later use.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;tempo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p>Now you can query the <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> for information
about the matching string.  <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instances
also have several methods and attributes; the most important ones are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">group()</span></code></td>
<td>Return the string matched by the RE</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">start()</span></code></td>
<td>Return the starting position of the match</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">end()</span></code></td>
<td>Return the ending position of the match</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">span()</span></code></td>
<td>Return a tuple containing the (start, end)
positions  of the match</td>
</tr>
</tbody>
</table>
<p>Trying these methods will soon clarify their meaning:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;tempo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
</pre></div>
</div>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code> returns the substring that was matched by the RE.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code> return the starting and ending index of the match. <code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code>
returns both start and end indexes in a single tuple.  Since the <code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code>
method only checks if the RE matches at the start of a string, <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>
will always be zero.  However, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code> method of patterns
scans through the string, so  the match may not start at zero in that
case.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;::: message&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;::: message&#39;</span><span class="p">);</span> <span class="nb">print</span> <span class="n">m</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;message&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(4, 11)</span>
</pre></div>
</div>
<p>In actual programs, the most common style is to store the
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> in a variable, and then check if it was
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  This usually looks like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
<span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span> <span class="s1">&#39;string goes here&#39;</span> <span class="p">)</span>
<span class="k">if</span> <span class="n">m</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;Match found: &#39;</span><span class="p">,</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;No match&#39;</span>
</pre></div>
</div>
<p>Two pattern methods return all of the matches for a pattern.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code> returns a list of matching strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;\d+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;12 drummers drumming, 11 pipers piping, 10 lords a-leaping&#39;</span><span class="p">)</span>
<span class="go">[&#39;12&#39;, &#39;11&#39;, &#39;10&#39;]</span>
</pre></div>
</div>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code> has to create the entire list before it can be returned as the
result.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">finditer()</span></code> method returns a sequence of
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instances as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>. <a class="footnote-reference" href="#id3" id="id1">[1]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="s1">&#39;12 drummers drumming, 11 ... 10 ...&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">iterator</span>  
<span class="go">&lt;callable-iterator object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">match</span> <span class="ow">in</span> <span class="n">iterator</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">match</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="gp">...</span>
<span class="go">(0, 2)</span>
<span class="go">(22, 24)</span>
<span class="go">(29, 31)</span>
</pre></div>
</div>
</div>
<div class="section" id="module-level-functions">
<h3>Module-Level Functions<a class="headerlink" href="#module-level-functions" title="Permalink to this headline">¶</a></h3>
<p>You don’t have to create a pattern object and call its methods; the
<a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module also provides top-level functions called <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code>, and so forth.  These functions
take the same arguments as the corresponding pattern method, with
the RE string added as the first argument, and still return either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> instance.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;From\s+&#39;</span><span class="p">,</span> <span class="s1">&#39;Fromage amk&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;From\s+&#39;</span><span class="p">,</span> <span class="s1">&#39;From amk Thu May 14 19:12:10 1998&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p>Under the hood, these functions simply create a pattern object for you
and call the appropriate method on it.  They also store the compiled object in a
cache, so future calls using the same RE are faster.</p>
<p>Should you use these module-level functions, or should you get the
pattern and call its methods yourself?  That choice depends on how
frequently the RE will be used, and on your personal coding style.  If the RE is
being used at only one point in the code, then the module functions are probably
more convenient.  If a program contains a lot of regular expressions, or re-uses
the same ones in several locations, then it might be worthwhile to collect all
the definitions in one place, in a section of code that compiles all the REs
ahead of time.  To take an example from the standard library, here’s an extract
from the deprecated <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmllib</span></code> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
<span class="n">entityref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
<span class="n">charref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
<span class="n">starttagopen</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="o">...</span> <span class="p">)</span>
</pre></div>
</div>
<p>I generally prefer to work with the compiled object, even for one-time uses, but
few people will be as much of a purist about this as I am.</p>
</div>
<div class="section" id="compilation-flags">
<h3>Compilation Flags<a class="headerlink" href="#compilation-flags" title="Permalink to this headline">¶</a></h3>
<p>Compilation flags let you modify some aspects of how regular expressions work.
Flags are available in the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module under two names, a long name such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code> and a short, one-letter form such as <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code>.  (If you’re
familiar with Perl’s pattern modifiers, the one-letter forms use the same
letters; the short form of <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a> is <a class="reference internal" href="../library/re.html#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a>, for example.)
Multiple flags can be specified by bitwise OR-ing them; <code class="docutils literal notranslate"><span class="pre">re.I</span> <span class="pre">|</span> <span class="pre">re.M</span></code> sets
both the <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code> flags, for example.</p>
<p>Here’s a table of the available flags, followed by a more detailed explanation
of each one.</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">S</span></code></td>
<td>Make <code class="docutils literal notranslate"><span class="pre">.</span></code> match any character, including
newlines</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">I</span></code></td>
<td>Do case-insensitive matches</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">L</span></code></td>
<td>Do a locale-aware match</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">M</span></code></td>
<td>Multi-line matching, affecting <code class="docutils literal notranslate"><span class="pre">^</span></code> and
<code class="docutils literal notranslate"><span class="pre">$</span></code></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">VERBOSE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">X</span></code></td>
<td>Enable verbose REs, which can be organized
more cleanly and understandably.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">U</span></code></td>
<td>Makes several escapes like <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>,
<code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\d</span></code> dependent on the Unicode
character database.</td>
</tr>
</tbody>
</table>
<dl class="data">
<dt>
<code class="descname">I</code></dt>
<dt>
<code class="descname">IGNORECASE</code></dt>
<dd><p>Perform case-insensitive matching; character class and literal strings will
match letters by ignoring case.  For example, <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> will match lowercase
letters, too, and <code class="docutils literal notranslate"><span class="pre">Spam</span></code> will match <code class="docutils literal notranslate"><span class="pre">Spam</span></code>, <code class="docutils literal notranslate"><span class="pre">spam</span></code>, or <code class="docutils literal notranslate"><span class="pre">spAM</span></code>. This
lowercasing doesn’t take the current locale into account; it will if you also
set the <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code> flag.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">L</code></dt>
<dt>
<code class="descname">LOCALE</code></dt>
<dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, and <code class="docutils literal notranslate"><span class="pre">\B</span></code>, dependent on the current locale.</p>
<p>Locales are a feature of the C library intended to help in writing programs that
take account of language differences.  For example, if you’re processing French
text, you’d want to be able to write <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to match words, but <code class="docutils literal notranslate"><span class="pre">\w</span></code> only
matches the character class <code class="docutils literal notranslate"><span class="pre">[A-Za-z]</span></code>; it won’t match <code class="docutils literal notranslate"><span class="pre">'é'</span></code> or <code class="docutils literal notranslate"><span class="pre">'ç'</span></code>.  If
your system is configured properly and a French locale is selected, certain C
functions will tell the program that <code class="docutils literal notranslate"><span class="pre">'é'</span></code> should also be considered a letter.
Setting the <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code> flag when compiling a regular expression will cause
the resulting compiled object to use these C functions for <code class="docutils literal notranslate"><span class="pre">\w</span></code>; this is
slower, but also enables <code class="docutils literal notranslate"><span class="pre">\w+</span></code> to match French words as you’d expect.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">M</code></dt>
<dt>
<code class="descname">MULTILINE</code></dt>
<dd><p>(<code class="docutils literal notranslate"><span class="pre">^</span></code> and <code class="docutils literal notranslate"><span class="pre">$</span></code> haven’t been explained yet;  they’ll be introduced in section
<a class="reference internal" href="#more-metacharacters"><span class="std std-ref">More Metacharacters</span></a>.)</p>
<p>Usually <code class="docutils literal notranslate"><span class="pre">^</span></code> matches only at the beginning of the string, and <code class="docutils literal notranslate"><span class="pre">$</span></code> matches
only at the end of the string and immediately before the newline (if any) at the
end of the string. When this flag is specified, <code class="docutils literal notranslate"><span class="pre">^</span></code> matches at the beginning
of the string and at the beginning of each line within the string, immediately
following each newline.  Similarly, the <code class="docutils literal notranslate"><span class="pre">$</span></code> metacharacter matches either at
the end of the string and at the end of each line (immediately preceding each
newline).</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">S</code></dt>
<dt>
<code class="descname">DOTALL</code></dt>
<dd><p>Makes the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> special character match any character at all, including a
newline; without this flag, <code class="docutils literal notranslate"><span class="pre">'.'</span></code> will match anything <em>except</em> a newline.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">U</code></dt>
<dt>
<code class="descname">UNICODE</code></dt>
<dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\d</span></code>, <code class="docutils literal notranslate"><span class="pre">\D</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\S</span></code>
dependent on the Unicode character properties database.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">X</code></dt>
<dt>
<code class="descname">VERBOSE</code></dt>
<dd><p>This flag allows you to write regular expressions that are more readable by
granting you more flexibility in how you can format them.  When this flag has
been specified, whitespace within the RE string is ignored, except when the
whitespace is in a character class or preceded by an unescaped backslash; this
lets you organize and indent the RE more clearly.  This flag also lets you put
comments within a RE that will be ignored by the engine; comments are marked by
a <code class="docutils literal notranslate"><span class="pre">'#'</span></code> that’s neither in a character class or preceded by an unescaped
backslash.</p>
<p>For example, here’s a RE that uses <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>; see how much easier it
is to read?</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">charref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2"> &amp;[#]                # Start of a numeric entity reference</span>
<span class="s2"> (</span>
<span class="s2">     0[0-7]+         # Octal form</span>
<span class="s2">   | [0-9]+          # Decimal form</span>
<span class="s2">   | x[0-9a-fA-F]+   # Hexadecimal form</span>
<span class="s2"> )</span>
<span class="s2"> ;                   # Trailing semicolon</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
</pre></div>
</div>
<p>Without the verbose setting, the RE would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">charref</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;&amp;#(0[0-7]+&quot;</span>
                     <span class="s2">&quot;|[0-9]+&quot;</span>
                     <span class="s2">&quot;|x[0-9a-fA-F]+);&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In the above example, Python’s automatic concatenation of string literals has
been used to break up the RE into smaller pieces, but it’s still more difficult
to understand than the version using <a class="reference internal" href="../library/re.html#re.VERBOSE" title="re.VERBOSE"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.VERBOSE</span></code></a>.</p>
</dd></dl>

</div>
</div>
<div class="section" id="more-pattern-power">
<h2>More Pattern Power<a class="headerlink" href="#more-pattern-power" title="Permalink to this headline">¶</a></h2>
<p>So far we’ve only covered a part of the features of regular expressions.  In
this section, we’ll cover some new metacharacters, and how to use groups to
retrieve portions of the text that was matched.</p>
<div class="section" id="more-metacharacters">
<span id="id2"></span><h3>More Metacharacters<a class="headerlink" href="#more-metacharacters" title="Permalink to this headline">¶</a></h3>
<p>There are some metacharacters that we haven’t covered yet.  Most of them will be
covered in this section.</p>
<p>Some of the remaining metacharacters to be discussed are <em class="dfn">zero-width
assertions</em>.  They don’t cause the engine to advance through the string;
instead, they consume no characters at all, and simply succeed or fail.  For
example, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is an assertion that the current position is located at a word
boundary; the position isn’t changed by the <code class="docutils literal notranslate"><span class="pre">\b</span></code> at all.  This means that
zero-width assertions should never be repeated, because if they match once at a
given location, they can obviously be matched an infinite number of times.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">|</span></code></dt>
<dd><p class="first">Alternation, or the “or” operator.   If A and B are regular expressions,
<code class="docutils literal notranslate"><span class="pre">A|B</span></code> will match any string that matches either <code class="docutils literal notranslate"><span class="pre">A</span></code> or <code class="docutils literal notranslate"><span class="pre">B</span></code>. <code class="docutils literal notranslate"><span class="pre">|</span></code> has very
low precedence in order to make it work reasonably when you’re alternating
multi-character strings. <code class="docutils literal notranslate"><span class="pre">Crow|Servo</span></code> will match either <code class="docutils literal notranslate"><span class="pre">Crow</span></code> or <code class="docutils literal notranslate"><span class="pre">Servo</span></code>,
not <code class="docutils literal notranslate"><span class="pre">Cro</span></code>, a <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or an <code class="docutils literal notranslate"><span class="pre">'S'</span></code>, and <code class="docutils literal notranslate"><span class="pre">ervo</span></code>.</p>
<p class="last">To match a literal <code class="docutils literal notranslate"><span class="pre">'|'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\|</span></code>, or enclose it inside a character class,
as in <code class="docutils literal notranslate"><span class="pre">[|]</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">^</span></code></dt>
<dd><p class="first">Matches at the beginning of lines.  Unless the <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> flag has been
set, this will only match at the beginning of the string.  In <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code>
mode, this also matches immediately after each newline within the string.</p>
<p>For example, if you wish to match the word <code class="docutils literal notranslate"><span class="pre">From</span></code> only at the beginning of a
line, the RE to use is <code class="docutils literal notranslate"><span class="pre">^From</span></code>.</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^From&#39;</span><span class="p">,</span> <span class="s1">&#39;From Here to Eternity&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^From&#39;</span><span class="p">,</span> <span class="s1">&#39;Reciting From Memory&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">$</span></code></dt>
<dd><p class="first">Matches at the end of a line, which is defined as either the end of the string,
or any location followed by a newline character.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="s1">&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="s1"> &#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;}$&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">{block}</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p class="last">To match a literal <code class="docutils literal notranslate"><span class="pre">'$'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\$</span></code> or enclose it inside a character class,
as in  <code class="docutils literal notranslate"><span class="pre">[$]</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\A</span></code></dt>
<dd>Matches only at the start of the string.  When not in <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> mode,
<code class="docutils literal notranslate"><span class="pre">\A</span></code> and <code class="docutils literal notranslate"><span class="pre">^</span></code> are effectively the same.  In <code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code> mode, they’re
different: <code class="docutils literal notranslate"><span class="pre">\A</span></code> still matches only at the beginning of the string, but <code class="docutils literal notranslate"><span class="pre">^</span></code>
may match at any location inside the string that follows a newline character.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\Z</span></code></dt>
<dd>Matches only at the end of the string.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\b</span></code></dt>
<dd><p class="first">Word boundary.  This is a zero-width assertion that matches only at the
beginning or end of a word.  A word is defined as a sequence of alphanumeric
characters, so the end of a word is indicated by whitespace or a
non-alphanumeric character.</p>
<p>The following example matches <code class="docutils literal notranslate"><span class="pre">class</span></code> only when it’s a complete word; it won’t
match when it’s contained inside another word.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\bclass\b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;no class at all&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;the declassified algorithm&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;one subclass is&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>There are two subtleties you should remember when using this special sequence.
First, this is the worst collision between Python’s string literals and regular
expression sequences.  In Python’s string literals, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is the backspace
character, ASCII value 8.  If you’re not using raw strings, then Python will
convert the <code class="docutils literal notranslate"><span class="pre">\b</span></code> to a backspace, and your RE won’t match as you expect it to.
The following example looks the same as our previous RE, but omits the <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
in front of the RE string.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\b</span><span class="s1">class</span><span class="se">\b</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;no class at all&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\b</span><span class="s1">&#39;</span> <span class="o">+</span> <span class="s1">&#39;class&#39;</span> <span class="o">+</span> <span class="s1">&#39;</span><span class="se">\b</span><span class="s1">&#39;</span><span class="p">)</span>  
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
<p class="last">Second, inside a character class, where there’s no use for this assertion,
<code class="docutils literal notranslate"><span class="pre">\b</span></code> represents the backspace character, for compatibility with Python’s
string literals.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\B</span></code></dt>
<dd>Another zero-width assertion, this is the opposite of <code class="docutils literal notranslate"><span class="pre">\b</span></code>, only matching when
the current position is not at a word boundary.</dd>
</dl>
</div>
<div class="section" id="grouping">
<h3>Grouping<a class="headerlink" href="#grouping" title="Permalink to this headline">¶</a></h3>
<p>Frequently you need to obtain more information than just whether the RE matched
or not.  Regular expressions are often used to dissect strings by writing a RE
divided into several subgroups which match different components of interest.
For example, an RFC-822 header line is divided into a header name and a value,
separated by a <code class="docutils literal notranslate"><span class="pre">':'</span></code>, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">From</span><span class="p">:</span> <span class="n">author</span><span class="nd">@example</span><span class="o">.</span><span class="n">com</span>
<span class="n">User</span><span class="o">-</span><span class="n">Agent</span><span class="p">:</span> <span class="n">Thunderbird</span> <span class="mf">1.5</span><span class="o">.</span><span class="mf">0.9</span> <span class="p">(</span><span class="n">X11</span><span class="o">/</span><span class="mi">20061227</span><span class="p">)</span>
<span class="n">MIME</span><span class="o">-</span><span class="n">Version</span><span class="p">:</span> <span class="mf">1.0</span>
<span class="n">To</span><span class="p">:</span> <span class="n">editor</span><span class="nd">@example</span><span class="o">.</span><span class="n">com</span>
</pre></div>
</div>
<p>This can be handled by writing a regular expression which matches an entire
header line, and has one group which matches the header name, and another group
which matches the header’s value.</p>
<p>Groups are marked by the <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> metacharacters. <code class="docutils literal notranslate"><span class="pre">'('</span></code> and <code class="docutils literal notranslate"><span class="pre">')'</span></code>
have much the same meaning as they do in mathematical expressions; they group
together the expressions contained inside them, and you can repeat the contents
of a group with a repeating qualifier, such as <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, or
<code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>.  For example, <code class="docutils literal notranslate"><span class="pre">(ab)*</span></code> will match zero or more repetitions of
<code class="docutils literal notranslate"><span class="pre">ab</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(ab)*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;ababababab&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 10)</span>
</pre></div>
</div>
<p>Groups indicated with <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">')'</span></code> also capture the starting and ending
index of the text that they match; this can be retrieved by passing an argument
to <code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">span()</span></code>.  Groups are
numbered starting with 0.  Group 0 is always present; it’s the whole RE, so
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> methods all have group 0 as their default
argument.  Later we’ll see how to express groups that don’t capture the span
of text that they match.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(a)b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;ab&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;ab&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;ab&#39;</span>
</pre></div>
</div>
<p>Subgroups are numbered from left to right, from 1 upward.  Groups can be nested;
to determine the number, just count the opening parenthesis characters, going
from left to right.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(a(b)c)d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;abcd&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;abcd&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;b&#39;</span>
</pre></div>
</div>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code> can be passed multiple group numbers at a time, in which case it
will return a tuple containing the corresponding values for those groups.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="go">(&#39;b&#39;, &#39;abc&#39;, &#39;b&#39;)</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">groups()</span></code> method returns a tuple containing the strings for all the
subgroups, from 1 up to however many there are.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;abc&#39;, &#39;b&#39;)</span>
</pre></div>
</div>
<p>Backreferences in a pattern allow you to specify that the contents of an earlier
capturing group must also be found at the current location in the string.  For
example, <code class="docutils literal notranslate"><span class="pre">\1</span></code> will succeed if the exact contents of group 1 can be found at
the current position, and fails otherwise.  Remember that Python’s string
literals also use a backslash followed by numbers to allow including arbitrary
characters in a string, so be sure to use a raw string when incorporating
backreferences in a RE.</p>
<p>For example, the following RE detects doubled words in a string.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\b(\w+)\s+\1\b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;the the&#39;</span>
</pre></div>
</div>
<p>Backreferences like this aren’t often useful for just searching through a string
— there are few text formats which repeat data in this way — but you’ll soon
find out that they’re <em>very</em> useful when performing string substitutions.</p>
</div>
<div class="section" id="non-capturing-and-named-groups">
<h3>Non-capturing and Named Groups<a class="headerlink" href="#non-capturing-and-named-groups" title="Permalink to this headline">¶</a></h3>
<p>Elaborate REs may use many groups, both to capture substrings of interest, and
to group and structure the RE itself.  In complex REs, it becomes difficult to
keep track of the group numbers.  There are two features which help with this
problem.  Both of them use a common syntax for regular expression extensions, so
we’ll look at that first.</p>
<p>Perl 5 added several additional features to standard regular expressions, and
the Python <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module supports most of them.   It would have been
difficult to choose new single-keystroke metacharacters or new special sequences
beginning with <code class="docutils literal notranslate"><span class="pre">\</span></code> to represent the new features without making Perl’s regular
expressions confusingly different from standard REs.  If you chose <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> as a
new metacharacter, for example, old expressions would be assuming that <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> was
a regular character and wouldn’t have escaped it by writing <code class="docutils literal notranslate"><span class="pre">\&amp;</span></code> or <code class="docutils literal notranslate"><span class="pre">[&amp;]</span></code>.</p>
<p>The solution chosen by the Perl developers was to use <code class="docutils literal notranslate"><span class="pre">(?...)</span></code> as the
extension syntax.  <code class="docutils literal notranslate"><span class="pre">?</span></code> immediately after a parenthesis was a syntax error
because the <code class="docutils literal notranslate"><span class="pre">?</span></code> would have nothing to repeat, so this didn’t introduce any
compatibility problems.  The characters immediately after the <code class="docutils literal notranslate"><span class="pre">?</span></code>  indicate
what extension is being used, so <code class="docutils literal notranslate"><span class="pre">(?=foo)</span></code> is one thing (a positive lookahead
assertion) and <code class="docutils literal notranslate"><span class="pre">(?:foo)</span></code> is something else (a non-capturing group containing
the subexpression <code class="docutils literal notranslate"><span class="pre">foo</span></code>).</p>
<p>Python adds an extension syntax to Perl’s extension syntax.  If the first
character after the question mark is a <code class="docutils literal notranslate"><span class="pre">P</span></code>, you know that it’s an extension
that’s specific to Python.  Currently there are two such extensions:
<code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> defines a named group, and <code class="docutils literal notranslate"><span class="pre">(?P=name)</span></code> is a backreference to
a named group.  If future versions of Perl 5 add similar features using a
different syntax, the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module will be changed to support the new
syntax, while preserving the Python-specific syntax for compatibility’s sake.</p>
<p>Now that we’ve looked at the general extension syntax, we can return to the
features that simplify working with groups in complex REs. Since groups are
numbered from left to right and a complex expression may use many groups, it can
become difficult to keep track of the correct numbering.  Modifying such a
complex RE is annoying, too: insert a new group near the beginning and you
change the numbers of everything that follows it.</p>
<p>Sometimes you’ll want to use a group to collect a part of a regular expression,
but aren’t interested in retrieving the group’s contents. You can make this fact
explicit by using a non-capturing group: <code class="docutils literal notranslate"><span class="pre">(?:...)</span></code>, where you can replace the
<code class="docutils literal notranslate"><span class="pre">...</span></code> with any other regular expression.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;([abc])+&quot;</span><span class="p">,</span> <span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;c&#39;,)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;(?:[abc])+&quot;</span><span class="p">,</span> <span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">()</span>
</pre></div>
</div>
<p>Except for the fact that you can’t retrieve the contents of what the group
matched, a non-capturing group behaves exactly the same as a capturing group;
you can put anything inside it, repeat it with a repetition metacharacter such
as <code class="docutils literal notranslate"><span class="pre">*</span></code>, and nest it within other groups (capturing or non-capturing).
<code class="docutils literal notranslate"><span class="pre">(?:...)</span></code> is particularly useful when modifying an existing pattern, since you
can add new groups without changing how all the other groups are numbered.  It
should be mentioned that there’s no performance difference in searching between
capturing and non-capturing groups; neither form is any faster than the other.</p>
<p>A more significant feature is named groups: instead of referring to them by
numbers, groups can be referenced by a name.</p>
<p>The syntax for a named group is one of the Python-specific extensions:
<code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code>.  <em>name</em> is, obviously, the name of the group.  Named groups
also behave exactly like capturing groups, and additionally associate a name
with a group.  The <a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> methods that deal with
capturing groups all accept either integers that refer to the group by number
or strings that contain the desired group’s name.  Named groups are still
given numbers, so you can retrieve information about a group in two ways:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(?P&lt;word&gt;\b\w+\b)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span> <span class="s1">&#39;(((( Lots of punctuation )))&#39;</span> <span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;word&#39;</span><span class="p">)</span>
<span class="go">&#39;Lots&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;Lots&#39;</span>
</pre></div>
</div>
<p>Named groups are handy because they let you use easily-remembered names, instead
of having to remember numbers.  Here’s an example RE from the <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a>
module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">InternalDate</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;INTERNALDATE &quot;&#39;</span>
        <span class="sa">r</span><span class="s1">&#39;(?P&lt;day&gt;[ 123][0-9])-(?P&lt;mon&gt;[A-Z][a-z][a-z])-&#39;</span>
        <span class="sa">r</span><span class="s1">&#39;(?P&lt;year&gt;[0-9][0-9][0-9][0-9])&#39;</span>
        <span class="sa">r</span><span class="s1">&#39; (?P&lt;hour&gt;[0-9][0-9]):(?P&lt;min&gt;[0-9][0-9]):(?P&lt;sec&gt;[0-9][0-9])&#39;</span>
        <span class="sa">r</span><span class="s1">&#39; (?P&lt;zonen&gt;[-+])(?P&lt;zoneh&gt;[0-9][0-9])(?P&lt;zonem&gt;[0-9][0-9])&#39;</span>
        <span class="sa">r</span><span class="s1">&#39;&quot;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>It’s obviously much easier to retrieve <code class="docutils literal notranslate"><span class="pre">m.group('zonem')</span></code>, instead of having
to remember to retrieve group 9.</p>
<p>The syntax for backreferences in an expression such as <code class="docutils literal notranslate"><span class="pre">(...)\1</span></code> refers to the
number of the group.  There’s naturally a variant that uses the group name
instead of the number. This is another Python extension: <code class="docutils literal notranslate"><span class="pre">(?P=name)</span></code> indicates
that the contents of the group called <em>name</em> should again be matched at the
current point.  The regular expression for finding doubled words,
<code class="docutils literal notranslate"><span class="pre">\b(\w+)\s+\1\b</span></code> can also be written as <code class="docutils literal notranslate"><span class="pre">\b(?P&lt;word&gt;\w+)\s+(?P=word)\b</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\b(?P&lt;word&gt;\w+)\s+(?P=word)\b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;Paris in the the spring&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&#39;the the&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="lookahead-assertions">
<h3>Lookahead Assertions<a class="headerlink" href="#lookahead-assertions" title="Permalink to this headline">¶</a></h3>
<p>Another zero-width assertion is the lookahead assertion.  Lookahead assertions
are available in both positive and negative form, and  look like this:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">(?=...)</span></code></dt>
<dd>Positive lookahead assertion.  This succeeds if the contained regular
expression, represented here by <code class="docutils literal notranslate"><span class="pre">...</span></code>, successfully matches at the current
location, and fails otherwise. But, once the contained expression has been
tried, the matching engine doesn’t advance at all; the rest of the pattern is
tried right where the assertion started.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?!...)</span></code></dt>
<dd>Negative lookahead assertion.  This is the opposite of the positive assertion;
it succeeds if the contained expression <em>doesn’t</em> match at the current position
in the string.</dd>
</dl>
<p>To make this concrete, let’s look at a case where a lookahead is useful.
Consider a simple pattern to match a filename and split it apart into a base
name and an extension, separated by a <code class="docutils literal notranslate"><span class="pre">.</span></code>.  For example, in <code class="docutils literal notranslate"><span class="pre">news.rc</span></code>,
<code class="docutils literal notranslate"><span class="pre">news</span></code> is the base name, and <code class="docutils literal notranslate"><span class="pre">rc</span></code> is the filename’s extension.</p>
<p>The pattern to match this is quite simple:</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.].*$</span></code></p>
<p>Notice that the <code class="docutils literal notranslate"><span class="pre">.</span></code> needs to be treated specially because it’s a
metacharacter; I’ve put it inside a character class.  Also notice the trailing
<code class="docutils literal notranslate"><span class="pre">$</span></code>; this is added to ensure that all the rest of the string must be included
in the extension.  This regular expression matches <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code> and
<code class="docutils literal notranslate"><span class="pre">autoexec.bat</span></code> and <code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code> and <code class="docutils literal notranslate"><span class="pre">printers.conf</span></code>.</p>
<p>Now, consider complicating the problem a bit; what if you want to match
filenames where the extension is not <code class="docutils literal notranslate"><span class="pre">bat</span></code>? Some incorrect attempts:</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.][^b].*$</span></code>  The first attempt above tries to exclude <code class="docutils literal notranslate"><span class="pre">bat</span></code> by requiring
that the first character of the extension is not a <code class="docutils literal notranslate"><span class="pre">b</span></code>.  This is wrong,
because the pattern also doesn’t match <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.]([^b]..|.[^a].|..[^t])$</span></code></p>
<p>The expression gets messier when you try to patch up the first solution by
requiring one of the following cases to match: the first character of the
extension isn’t <code class="docutils literal notranslate"><span class="pre">b</span></code>; the second character isn’t <code class="docutils literal notranslate"><span class="pre">a</span></code>; or the third character
isn’t <code class="docutils literal notranslate"><span class="pre">t</span></code>.  This accepts <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code> and rejects <code class="docutils literal notranslate"><span class="pre">autoexec.bat</span></code>, but it
requires a three-letter extension and won’t accept a filename with a two-letter
extension such as <code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code>.  We’ll complicate the pattern again in an
effort to fix it.</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.]([^b].?.?|.[^a]?.?|..?[^t]?)$</span></code></p>
<p>In the third attempt, the second and third letters are all made optional in
order to allow matching extensions shorter than three characters, such as
<code class="docutils literal notranslate"><span class="pre">sendmail.cf</span></code>.</p>
<p>The pattern’s getting really complicated now, which makes it hard to read and
understand.  Worse, if the problem changes and you want to exclude both <code class="docutils literal notranslate"><span class="pre">bat</span></code>
and <code class="docutils literal notranslate"><span class="pre">exe</span></code> as extensions, the pattern would get even more complicated and
confusing.</p>
<p>A negative lookahead cuts through all this confusion:</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.](?!bat$)[^.]*$</span></code>  The negative lookahead means: if the expression <code class="docutils literal notranslate"><span class="pre">bat</span></code>
doesn’t match at this point, try the rest of the pattern; if <code class="docutils literal notranslate"><span class="pre">bat$</span></code> does
match, the whole pattern will fail.  The trailing <code class="docutils literal notranslate"><span class="pre">$</span></code> is required to ensure
that something like <code class="docutils literal notranslate"><span class="pre">sample.batch</span></code>, where the extension only starts with
<code class="docutils literal notranslate"><span class="pre">bat</span></code>, will be allowed.  The <code class="docutils literal notranslate"><span class="pre">[^.]*</span></code> makes sure that the pattern works
when there are multiple dots in the filename.</p>
<p>Excluding another filename extension is now easy; simply add it as an
alternative inside the assertion.  The following pattern excludes filenames that
end in either <code class="docutils literal notranslate"><span class="pre">bat</span></code> or <code class="docutils literal notranslate"><span class="pre">exe</span></code>:</p>
<p><code class="docutils literal notranslate"><span class="pre">.*[.](?!bat$|exe$)[^.]*$</span></code></p>
</div>
</div>
<div class="section" id="modifying-strings">
<h2>Modifying Strings<a class="headerlink" href="#modifying-strings" title="Permalink to this headline">¶</a></h2>
<p>Up to this point, we’ve simply performed searches against a static string.
Regular expressions are also commonly used to modify strings in various ways,
using the following pattern methods:</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method/Attribute</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">split()</span></code></td>
<td>Split the string into a list, splitting it
wherever the RE matches</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">sub()</span></code></td>
<td>Find all substrings where the RE matches, and
replace them with a different string</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">subn()</span></code></td>
<td>Does the same thing as <code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code>,  but
returns the new string and the number of
replacements</td>
</tr>
</tbody>
</table>
<div class="section" id="splitting-strings">
<h3>Splitting Strings<a class="headerlink" href="#splitting-strings" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> method of a pattern splits a string apart
wherever the RE matches, returning a list of the pieces. It’s similar to the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> method of strings but provides much more generality in the
delimiters that you can split by; <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> only supports splitting by
whitespace or by a fixed string.  As you’d expect, there’s a module-level
<a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.split()</span></code></a> function, too.</p>
<dl class="method">
<dt>
<code class="descclassname">.</code><code class="descname">split</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>maxsplit=0</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Split <em>string</em> by the matches of the regular expression.  If capturing
parentheses are used in the RE, then their contents will also be returned as
part of the resulting list.  If <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits
are performed.</p>
</dd></dl>

<p>You can limit the number of splits made, by passing a value for <em>maxsplit</em>.
When <em>maxsplit</em> is nonzero, at most <em>maxsplit</em> splits will be made, and the
remainder of the string is returned as the final element of the list.  In the
following example, the delimiter is any sequence of non-alphanumeric characters.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;short&#39;, &#39;and&#39;, &#39;sweet&#39;, &#39;of&#39;, &#39;split&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This is a test, short and sweet, of split().&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test, short and sweet, of split().&#39;]</span>
</pre></div>
</div>
<p>Sometimes you’re not only interested in what the text between delimiters is, but
also need to know what the delimiter was.  If capturing parentheses are used in
the RE, then their values are also returned as part of the list.  Compare the
following calls:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\W+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This... is a test.&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;is&#39;, &#39;a&#39;, &#39;test&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;This... is a test.&#39;</span><span class="p">)</span>
<span class="go">[&#39;This&#39;, &#39;... &#39;, &#39;is&#39;, &#39; &#39;, &#39;a&#39;, &#39; &#39;, &#39;test&#39;, &#39;.&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<p>The module-level function <a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.split()</span></code></a> adds the RE to be used as the first
argument, but is otherwise the same.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words&#39;, &#39;words&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;([\W]+)&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;[\W]+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words, words.&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="search-and-replace">
<h3>Search and Replace<a class="headerlink" href="#search-and-replace" title="Permalink to this headline">¶</a></h3>
<p>Another common task is to find all the matches for a pattern, and replace them
with a different string.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code> method takes a replacement value,
which can be either a string or a function, and the string to be processed.</p>
<dl class="method">
<dt>
<code class="descclassname">.</code><code class="descname">sub</code><span class="sig-paren">(</span><em>replacement</em>, <em>string</em><span class="optional">[</span>, <em>count=0</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns the string obtained by replacing the leftmost non-overlapping
occurrences of the RE in <em>string</em> by the replacement <em>replacement</em>.  If the
pattern isn’t found, <em>string</em> is returned unchanged.</p>
<p>The optional argument <em>count</em> is the maximum number of pattern occurrences to be
replaced; <em>count</em> must be a non-negative integer.  The default value of 0 means
to replace all occurrences.</p>
</dd></dl>

<p>Here’s a simple example of using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code> method.  It replaces colour
names with the word <code class="docutils literal notranslate"><span class="pre">colour</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
<span class="go">&#39;colour socks and colour shoes&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">,</span> <span class="n">count</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;colour socks and red shoes&#39;</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">subn()</span></code> method does the same work, but returns a 2-tuple containing the
new string value and the number of replacements  that were performed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;(blue|white|red)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;blue socks and red shoes&#39;</span><span class="p">)</span>
<span class="go">(&#39;colour socks and colour shoes&#39;, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">subn</span><span class="p">(</span><span class="s1">&#39;colour&#39;</span><span class="p">,</span> <span class="s1">&#39;no colours at all&#39;</span><span class="p">)</span>
<span class="go">(&#39;no colours at all&#39;, 0)</span>
</pre></div>
</div>
<p>Empty matches are replaced only when they’re not adjacent to a previous match.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;x*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="s1">&#39;abxd&#39;</span><span class="p">)</span>
<span class="go">&#39;-a-b-d-&#39;</span>
</pre></div>
</div>
<p>If <em>replacement</em> is a string, any backslash escapes in it are processed.  That
is, <code class="docutils literal notranslate"><span class="pre">\n</span></code> is converted to a single newline character, <code class="docutils literal notranslate"><span class="pre">\r</span></code> is converted to a
carriage return, and so forth. Unknown escapes such as <code class="docutils literal notranslate"><span class="pre">\j</span></code> are left alone.
Backreferences, such as <code class="docutils literal notranslate"><span class="pre">\6</span></code>, are replaced with the substring matched by the
corresponding group in the RE.  This lets you incorporate portions of the
original text in the resulting replacement string.</p>
<p>This example matches the word <code class="docutils literal notranslate"><span class="pre">section</span></code> followed by a string enclosed in
<code class="docutils literal notranslate"><span class="pre">{</span></code>, <code class="docutils literal notranslate"><span class="pre">}</span></code>, and changes <code class="docutils literal notranslate"><span class="pre">section</span></code> to <code class="docutils literal notranslate"><span class="pre">subsection</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;section{ ( [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1"> section</span><span class="si">{second}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First} subsection{second}&#39;</span>
</pre></div>
</div>
<p>There’s also a syntax for referring to named groups as defined by the
<code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> syntax.  <code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code> will use the substring matched by the
group named <code class="docutils literal notranslate"><span class="pre">name</span></code>, and  <code class="docutils literal notranslate"><span class="pre">\g&lt;number&gt;</span></code>  uses the corresponding group number.
<code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;</span></code> is therefore equivalent to <code class="docutils literal notranslate"><span class="pre">\2</span></code>,  but isn’t ambiguous in a
replacement string such as <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;0</span></code>.  (<code class="docutils literal notranslate"><span class="pre">\20</span></code> would be interpreted as a
reference to group 20, not a reference to group 2 followed by the literal
character <code class="docutils literal notranslate"><span class="pre">'0'</span></code>.)  The following substitutions are all equivalent, but use all
three variations of the replacement string.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;section{ (?P&lt;name&gt; [^}]* ) }&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\1}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\g&lt;1&gt;}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;subsection{\g&lt;name&gt;}&#39;</span><span class="p">,</span><span class="s1">&#39;section</span><span class="si">{First}</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&#39;subsection{First}&#39;</span>
</pre></div>
</div>
<p><em>replacement</em> can also be a function, which gives you even more control.  If
<em>replacement</em> is a function, the function is called for every non-overlapping
occurrence of <em>pattern</em>.  On each call, the function is passed a
<a class="reference internal" href="../library/re.html#match-objects"><span class="std std-ref">match object</span></a> argument for the match and can use this
information to compute the desired replacement string and return it.</p>
<p>In the following example, the replacement function translates decimals into
hexadecimal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">hexrepl</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
<span class="gp">... </span>    <span class="s2">&quot;Return the hex string for a decimal number&quot;</span>
<span class="gp">... </span>    <span class="n">value</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">())</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="nb">hex</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\d+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="n">hexrepl</span><span class="p">,</span> <span class="s1">&#39;Call 65490 for printing, 49152 for user code.&#39;</span><span class="p">)</span>
<span class="go">&#39;Call 0xffd2 for printing, 0xc000 for user code.&#39;</span>
</pre></div>
</div>
<p>When using the module-level <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.sub()</span></code></a> function, the pattern is passed as
the first argument.  The pattern may be provided as an object or as a string; if
you need to specify regular expression flags, you must either use a
pattern object as the first parameter, or use embedded modifiers in the
pattern string, e.g. <code class="docutils literal notranslate"><span class="pre">sub(&quot;(?i)b+&quot;,</span> <span class="pre">&quot;x&quot;,</span> <span class="pre">&quot;bbbb</span> <span class="pre">BBBB&quot;)</span></code> returns <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">x'</span></code>.</p>
</div>
</div>
<div class="section" id="common-problems">
<h2>Common Problems<a class="headerlink" href="#common-problems" title="Permalink to this headline">¶</a></h2>
<p>Regular expressions are a powerful tool for some applications, but in some ways
their behaviour isn’t intuitive and at times they don’t behave the way you may
expect them to.  This section will point out some of the most common pitfalls.</p>
<div class="section" id="use-string-methods">
<h3>Use String Methods<a class="headerlink" href="#use-string-methods" title="Permalink to this headline">¶</a></h3>
<p>Sometimes using the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is a mistake.  If you’re matching a fixed
string, or a single character class, and you’re not using any <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> features
such as the <code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code> flag, then the full power of regular expressions
may not be required. Strings have several methods for performing operations with
fixed strings and they’re usually much faster, because the implementation is a
single small C loop that’s been optimized for the purpose, instead of the large,
more generalized regular expression engine.</p>
<p>One example might be replacing a single fixed string with another one; for
example, you might replace <code class="docutils literal notranslate"><span class="pre">word</span></code> with <code class="docutils literal notranslate"><span class="pre">deed</span></code>.  <code class="docutils literal notranslate"><span class="pre">re.sub()</span></code> seems like the
function to use for this, but consider the <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code> method.  Note that
<code class="xref py py-func docutils literal notranslate"><span class="pre">replace()</span></code> will also replace <code class="docutils literal notranslate"><span class="pre">word</span></code> inside words, turning <code class="docutils literal notranslate"><span class="pre">swordfish</span></code>
into <code class="docutils literal notranslate"><span class="pre">sdeedfish</span></code>, but the  naive RE <code class="docutils literal notranslate"><span class="pre">word</span></code> would have done that, too.  (To
avoid performing the substitution on parts of words, the pattern would have to
be <code class="docutils literal notranslate"><span class="pre">\bword\b</span></code>, in order to require that <code class="docutils literal notranslate"><span class="pre">word</span></code> have a word boundary on
either side.  This takes the job beyond  <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code>’s abilities.)</p>
<p>Another common task is deleting every occurrence of a single character from a
string or replacing it with another single character.  You might do this with
something like <code class="docutils literal notranslate"><span class="pre">re.sub('\n',</span> <span class="pre">'</span> <span class="pre">',</span> <span class="pre">S)</span></code>, but <code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code> is capable of
doing both tasks and will be faster than any regular expression operation can
be.</p>
<p>In short, before turning to the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module, consider whether your problem
can be solved with a faster and simpler string method.</p>
</div>
<div class="section" id="match-versus-search">
<h3>match() versus search()<a class="headerlink" href="#match-versus-search" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code> function only checks if the RE matches at the beginning of the
string while <code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code> will scan forward through the string for a match.
It’s important to keep this distinction in mind.  Remember,  <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code> will
only report a successful match which will start at 0; if the match wouldn’t
start at zero,  <code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code> will <em>not</em> report it.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;insuperable&#39;</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>On the other hand, <code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code> will scan forward through the string,
reporting the first match it finds.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;superstition&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;super&#39;</span><span class="p">,</span> <span class="s1">&#39;insuperable&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(2, 7)</span>
</pre></div>
</div>
<p>Sometimes you’ll be tempted to keep using <a class="reference internal" href="../library/re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a>, and just add <code class="docutils literal notranslate"><span class="pre">.*</span></code>
to the front of your RE.  Resist this temptation and use <a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a>
instead.  The regular expression compiler does some analysis of REs in order to
speed up the process of looking for a match.  One such analysis figures out what
the first character of a match must be; for example, a pattern starting with
<code class="docutils literal notranslate"><span class="pre">Crow</span></code> must match starting with a <code class="docutils literal notranslate"><span class="pre">'C'</span></code>.  The analysis lets the engine
quickly scan through the string looking for the starting character, only trying
the full match if a <code class="docutils literal notranslate"><span class="pre">'C'</span></code> is found.</p>
<p>Adding <code class="docutils literal notranslate"><span class="pre">.*</span></code> defeats this optimization, requiring scanning to the end of the
string and then backtracking to find a match for the rest of the RE.  Use
<a class="reference internal" href="../library/re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a> instead.</p>
</div>
<div class="section" id="greedy-versus-non-greedy">
<h3>Greedy versus Non-Greedy<a class="headerlink" href="#greedy-versus-non-greedy" title="Permalink to this headline">¶</a></h3>
<p>When repeating a regular expression, as in <code class="docutils literal notranslate"><span class="pre">a*</span></code>, the resulting action is to
consume as much of the pattern as possible.  This fact often bites you when
you’re trying to match a pair of balanced delimiters, such as the angle brackets
surrounding an HTML tag.  The naive pattern for matching a single HTML tag
doesn’t work because of the greedy nature of <code class="docutils literal notranslate"><span class="pre">.*</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">32</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">span</span><span class="p">()</span>
<span class="go">(0, 32)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&lt;html&gt;&lt;head&gt;&lt;title&gt;Title&lt;/title&gt;</span>
</pre></div>
</div>
<p>The RE matches the <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> in <code class="docutils literal notranslate"><span class="pre">&lt;html&gt;</span></code>, and the <code class="docutils literal notranslate"><span class="pre">.*</span></code> consumes the rest of
the string.  There’s still more left in the RE, though, and the <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> can’t
match at the end of the string, so the regular expression engine has to
backtrack character by character until it finds a match for the <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>.   The
final match extends from the <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> in <code class="docutils literal notranslate"><span class="pre">&lt;html&gt;</span></code> to the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> in
<code class="docutils literal notranslate"><span class="pre">&lt;/title&gt;</span></code>, which isn’t what you want.</p>
<p>In this case, the solution is to use the non-greedy qualifiers <code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">+?</span></code>,
<code class="docutils literal notranslate"><span class="pre">??</span></code>, or <code class="docutils literal notranslate"><span class="pre">{m,n}?</span></code>, which match as <em>little</em> text as possible.  In the above
example, the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> is tried immediately after the first <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> matches, and
when it fails, the engine advances a character at a time, retrying the <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>
at every step.  This produces just the right result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;&lt;.*?&gt;&#39;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">()</span>
<span class="go">&lt;html&gt;</span>
</pre></div>
</div>
<p>(Note that parsing HTML or XML with regular expressions is painful.
Quick-and-dirty patterns will handle common cases, but HTML and XML have special
cases that will break the obvious regular expression; by the time you’ve written
a regular expression that handles all of the possible cases, the patterns will
be <em>very</em> complicated.  Use an HTML or XML parser module for such tasks.)</p>
</div>
<div class="section" id="using-re-verbose">
<h3>Using re.VERBOSE<a class="headerlink" href="#using-re-verbose" title="Permalink to this headline">¶</a></h3>
<p>By now you’ve probably noticed that regular expressions are a very compact
notation, but they’re not terribly readable.  REs of moderate complexity can
become lengthy collections of backslashes, parentheses, and metacharacters,
making them difficult to read and understand.</p>
<p>For such REs, specifying the <code class="docutils literal notranslate"><span class="pre">re.VERBOSE</span></code> flag when compiling the regular
expression can be helpful, because it allows you to format the regular
expression more clearly.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">re.VERBOSE</span></code> flag has several effects.  Whitespace in the regular
expression that <em>isn’t</em> inside a character class is ignored.  This means that an
expression such as <code class="docutils literal notranslate"><span class="pre">dog</span> <span class="pre">|</span> <span class="pre">cat</span></code> is equivalent to the less readable <code class="docutils literal notranslate"><span class="pre">dog|cat</span></code>,
but <code class="docutils literal notranslate"><span class="pre">[a</span> <span class="pre">b]</span></code> will still match the characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'b'</span></code>, or a space.  In
addition, you can also put comments inside a RE; comments extend from a <code class="docutils literal notranslate"><span class="pre">#</span></code>
character to the next newline.  When used with triple-quoted strings, this
enables REs to be formatted more neatly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pat</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2"> \s*                 # Skip leading whitespace</span>
<span class="s2"> (?P&lt;header&gt;[^:]+)   # Header name</span>
<span class="s2"> \s* :               # Whitespace, and a colon</span>
<span class="s2"> (?P&lt;value&gt;.*?)      # The header&#39;s value -- *? used to</span>
<span class="s2">                     # lose the following trailing whitespace</span>
<span class="s2"> \s*$                # Trailing whitespace to end-of-line</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">VERBOSE</span><span class="p">)</span>
</pre></div>
</div>
<p>This is far more readable than:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pat</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\s*(?P&lt;header&gt;[^:]+)\s*:(?P&lt;value&gt;.*?)\s*$&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="feedback">
<h2>Feedback<a class="headerlink" href="#feedback" title="Permalink to this headline">¶</a></h2>
<p>Regular expressions are a complicated topic.  Did this document help you
understand them?  Were there parts that were unclear, or Problems you
encountered that weren’t covered here?  If so, please send suggestions for
improvements to the author.</p>
<p>The most complete book on regular expressions is almost certainly Jeffrey
Friedl’s Mastering Regular Expressions, published by O’Reilly.  Unfortunately,
it exclusively concentrates on Perl and Java’s flavours of regular expressions,
and doesn’t contain any Python material at all, so it won’t be useful as a
reference for programming in Python.  (The first edition covered Python’s
now-removed <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module, which won’t help you much.)  Consider checking
it out from your library.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Introduced in Python 2.2.2.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Regular Expression HOWTO</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#simple-patterns">Simple Patterns</a><ul>
<li><a class="reference internal" href="#matching-characters">Matching Characters</a></li>
<li><a class="reference internal" href="#repeating-things">Repeating Things</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-regular-expressions">Using Regular Expressions</a><ul>
<li><a class="reference internal" href="#compiling-regular-expressions">Compiling Regular Expressions</a></li>
<li><a class="reference internal" href="#the-backslash-plague">The Backslash Plague</a></li>
<li><a class="reference internal" href="#performing-matches">Performing Matches</a></li>
<li><a class="reference internal" href="#module-level-functions">Module-Level Functions</a></li>
<li><a class="reference internal" href="#compilation-flags">Compilation Flags</a></li>
</ul>
</li>
<li><a class="reference internal" href="#more-pattern-power">More Pattern Power</a><ul>
<li><a class="reference internal" href="#more-metacharacters">More Metacharacters</a></li>
<li><a class="reference internal" href="#grouping">Grouping</a></li>
<li><a class="reference internal" href="#non-capturing-and-named-groups">Non-capturing and Named Groups</a></li>
<li><a class="reference internal" href="#lookahead-assertions">Lookahead Assertions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#modifying-strings">Modifying Strings</a><ul>
<li><a class="reference internal" href="#splitting-strings">Splitting Strings</a></li>
<li><a class="reference internal" href="#search-and-replace">Search and Replace</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-problems">Common Problems</a><ul>
<li><a class="reference internal" href="#use-string-methods">Use String Methods</a></li>
<li><a class="reference internal" href="#match-versus-search">match() versus search()</a></li>
<li><a class="reference internal" href="#greedy-versus-non-greedy">Greedy versus Non-Greedy</a></li>
<li><a class="reference internal" href="#using-re-verbose">Using re.VERBOSE</a></li>
</ul>
</li>
<li><a class="reference internal" href="#feedback">Feedback</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging-cookbook.html"
                        title="previous chapter">Logging Cookbook</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sockets.html"
                        title="next chapter">Socket Programming HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/regex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="logging-cookbook.html" title="Logging Cookbook"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\)��#�#�html/howto/sockets.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Socket Programming HOWTO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Sorting HOW TO" href="sorting.html" />
    <link rel="prev" title="Regular Expression HOWTO" href="regex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/sockets.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sorting.html" title="Sorting HOW TO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="socket-programming-howto">
<span id="socket-howto"></span><h1>Socket Programming HOWTO<a class="headerlink" href="#socket-programming-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Gordon McMillan</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>Sockets are used nearly everywhere, but are one of the most severely
misunderstood technologies around. This is a 10,000 foot overview of sockets.
It’s not really a tutorial - you’ll still have work to do in getting things
operational. It doesn’t cover the fine points (and there are a lot of them), but
I hope it will give you enough background to begin using them decently.</p>
</div>
<div class="section" id="sockets">
<h2>Sockets<a class="headerlink" href="#sockets" title="Permalink to this headline">¶</a></h2>
<p>I’m only going to talk about INET sockets, but they account for at least 99% of
the sockets in use. And I’ll only talk about STREAM sockets - unless you really
know what you’re doing (in which case this HOWTO isn’t for you!), you’ll get
better behavior and performance from a STREAM socket than anything else. I will
try to clear up the mystery of what a socket is, as well as some hints on how to
work with blocking and non-blocking sockets. But I’ll start by talking about
blocking sockets. You’ll need to know how they work before dealing with
non-blocking sockets.</p>
<p>Part of the trouble with understanding these things is that “socket” can mean a
number of subtly different things, depending on context. So first, let’s make a
distinction between a “client” socket - an endpoint of a conversation, and a
“server” socket, which is more like a switchboard operator. The client
application (your browser, for example) uses “client” sockets exclusively; the
web server it’s talking to uses both “server” sockets and “client” sockets.</p>
<div class="section" id="history">
<h3>History<a class="headerlink" href="#history" title="Permalink to this headline">¶</a></h3>
<p>Of the various forms of <abbr title="Inter Process Communication">IPC</abbr>,
sockets are by far the most popular.  On any given platform, there are
likely to be other forms of IPC that are faster, but for
cross-platform communication, sockets are about the only game in town.</p>
<p>They were invented in Berkeley as part of the BSD flavor of Unix. They spread
like wildfire with the Internet. With good reason — the combination of sockets
with INET makes talking to arbitrary machines around the world unbelievably easy
(at least compared to other schemes).</p>
</div>
</div>
<div class="section" id="creating-a-socket">
<h2>Creating a Socket<a class="headerlink" href="#creating-a-socket" title="Permalink to this headline">¶</a></h2>
<p>Roughly speaking, when you clicked on the link that brought you to this page,
your browser did something like the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#create an INET, STREAMing socket</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span>
    <span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="c1">#now connect to the web server on port 80</span>
<span class="c1"># - the normal http port</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="s2">&quot;www.mcmillan-inc.com&quot;</span><span class="p">,</span> <span class="mi">80</span><span class="p">))</span>
</pre></div>
</div>
<p>When the <code class="docutils literal notranslate"><span class="pre">connect</span></code> completes, the socket <code class="docutils literal notranslate"><span class="pre">s</span></code> can be used to send
in a request for the text of the page. The same socket will read the
reply, and then be destroyed. That’s right, destroyed. Client sockets
are normally only used for one exchange (or a small set of sequential
exchanges).</p>
<p>What happens in the web server is a bit more complex. First, the web server
creates a “server socket”:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#create an INET, STREAMing socket</span>
<span class="n">serversocket</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span>
    <span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="c1">#bind the socket to a public host,</span>
<span class="c1"># and a well-known port</span>
<span class="n">serversocket</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">socket</span><span class="o">.</span><span class="n">gethostname</span><span class="p">(),</span> <span class="mi">80</span><span class="p">))</span>
<span class="c1">#become a server socket</span>
<span class="n">serversocket</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>A couple things to notice: we used <code class="docutils literal notranslate"><span class="pre">socket.gethostname()</span></code> so that the socket
would be visible to the outside world.  If we had used <code class="docutils literal notranslate"><span class="pre">s.bind(('localhost',</span>
<span class="pre">80))</span></code> or <code class="docutils literal notranslate"><span class="pre">s.bind(('127.0.0.1',</span> <span class="pre">80))</span></code> we would still have a “server” socket,
but one that was only visible within the same machine.  <code class="docutils literal notranslate"><span class="pre">s.bind(('',</span> <span class="pre">80))</span></code>
specifies that the socket is reachable by any address the machine happens to
have.</p>
<p>A second thing to note: low number ports are usually reserved for “well known”
services (HTTP, SNMP etc). If you’re playing around, use a nice high number (4
digits).</p>
<p>Finally, the argument to <code class="docutils literal notranslate"><span class="pre">listen</span></code> tells the socket library that we want it to
queue up as many as 5 connect requests (the normal max) before refusing outside
connections. If the rest of the code is written properly, that should be plenty.</p>
<p>Now that we have a “server” socket, listening on port 80, we can enter the
mainloop of the web server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="c1">#accept connections from outside</span>
    <span class="p">(</span><span class="n">clientsocket</span><span class="p">,</span> <span class="n">address</span><span class="p">)</span> <span class="o">=</span> <span class="n">serversocket</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
    <span class="c1">#now do something with the clientsocket</span>
    <span class="c1">#in this case, we&#39;ll pretend this is a threaded server</span>
    <span class="n">ct</span> <span class="o">=</span> <span class="n">client_thread</span><span class="p">(</span><span class="n">clientsocket</span><span class="p">)</span>
    <span class="n">ct</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>
</div>
<p>There’s actually 3 general ways in which this loop could work - dispatching a
thread to handle <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, create a new process to handle
<code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, or restructure this app to use non-blocking sockets, and
multiplex between our “server” socket and any active <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>s using
<code class="docutils literal notranslate"><span class="pre">select</span></code>. More about that later. The important thing to understand now is
this: this is <em>all</em> a “server” socket does. It doesn’t send any data. It doesn’t
receive any data. It just produces “client” sockets. Each <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code> is
created in response to some <em>other</em> “client” socket doing a <code class="docutils literal notranslate"><span class="pre">connect()</span></code> to the
host and port we’re bound to. As soon as we’ve created that <code class="docutils literal notranslate"><span class="pre">clientsocket</span></code>, we
go back to listening for more connections. The two “clients” are free to chat it
up - they are using some dynamically allocated port which will be recycled when
the conversation ends.</p>
<div class="section" id="ipc">
<h3>IPC<a class="headerlink" href="#ipc" title="Permalink to this headline">¶</a></h3>
<p>If you need fast IPC between two processes on one machine, you should look into
whatever form of shared memory the platform offers. A simple protocol based
around shared memory and locks or semaphores is by far the fastest technique.</p>
<p>If you do decide to use sockets, bind the “server” socket to <code class="docutils literal notranslate"><span class="pre">'localhost'</span></code>. On
most platforms, this will take a shortcut around a couple of layers of network
code and be quite a bit faster.</p>
</div>
</div>
<div class="section" id="using-a-socket">
<h2>Using a Socket<a class="headerlink" href="#using-a-socket" title="Permalink to this headline">¶</a></h2>
<p>The first thing to note, is that the web browser’s “client” socket and the web
server’s “client” socket are identical beasts. That is, this is a “peer to peer”
conversation. Or to put it another way, <em>as the designer, you will have to
decide what the rules of etiquette are for a conversation</em>. Normally, the
<code class="docutils literal notranslate"><span class="pre">connect</span></code>ing socket starts the conversation, by sending in a request, or
perhaps a signon. But that’s a design decision - it’s not a rule of sockets.</p>
<p>Now there are two sets of verbs to use for communication. You can use <code class="docutils literal notranslate"><span class="pre">send</span></code>
and <code class="docutils literal notranslate"><span class="pre">recv</span></code>, or you can transform your client socket into a file-like beast and
use <code class="docutils literal notranslate"><span class="pre">read</span></code> and <code class="docutils literal notranslate"><span class="pre">write</span></code>. The latter is the way Java presents its sockets.
I’m not going to talk about it here, except to warn you that you need to use
<code class="docutils literal notranslate"><span class="pre">flush</span></code> on sockets. These are buffered “files”, and a common mistake is to
<code class="docutils literal notranslate"><span class="pre">write</span></code> something, and then <code class="docutils literal notranslate"><span class="pre">read</span></code> for a reply. Without a <code class="docutils literal notranslate"><span class="pre">flush</span></code> in
there, you may wait forever for the reply, because the request may still be in
your output buffer.</p>
<p>Now we come to the major stumbling block of sockets - <code class="docutils literal notranslate"><span class="pre">send</span></code> and <code class="docutils literal notranslate"><span class="pre">recv</span></code> operate
on the network buffers. They do not necessarily handle all the bytes you hand
them (or expect from them), because their major focus is handling the network
buffers. In general, they return when the associated network buffers have been
filled (<code class="docutils literal notranslate"><span class="pre">send</span></code>) or emptied (<code class="docutils literal notranslate"><span class="pre">recv</span></code>). They then tell you how many bytes they
handled. It is <em>your</em> responsibility to call them again until your message has
been completely dealt with.</p>
<p>When a <code class="docutils literal notranslate"><span class="pre">recv</span></code> returns 0 bytes, it means the other side has closed (or is in
the process of closing) the connection.  You will not receive any more data on
this connection. Ever.  You may be able to send data successfully; I’ll talk
more about this later.</p>
<p>A protocol like HTTP uses a socket for only one transfer. The client sends a
request, then reads a reply.  That’s it. The socket is discarded. This means that
a client can detect the end of the reply by receiving 0 bytes.</p>
<p>But if you plan to reuse your socket for further transfers, you need to realize
that <em>there is no</em> <abbr title="End of Transfer">EOT</abbr> <em>on a socket.</em> I repeat: if a socket
<code class="docutils literal notranslate"><span class="pre">send</span></code> or <code class="docutils literal notranslate"><span class="pre">recv</span></code> returns after handling 0 bytes, the connection has been
broken.  If the connection has <em>not</em> been broken, you may wait on a <code class="docutils literal notranslate"><span class="pre">recv</span></code>
forever, because the socket will <em>not</em> tell you that there’s nothing more to
read (for now).  Now if you think about that a bit, you’ll come to realize a
fundamental truth of sockets: <em>messages must either be fixed length</em> (yuck), <em>or
be delimited</em> (shrug), <em>or indicate how long they are</em> (much better), <em>or end by
shutting down the connection</em>. The choice is entirely yours, (but some ways are
righter than others).</p>
<p>Assuming you don’t want to end the connection, the simplest solution is a fixed
length message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">mysocket</span><span class="p">:</span>
    <span class="sd">&#39;&#39;&#39;demonstration class only</span>
<span class="sd">      - coded for clarity, not efficiency</span>
<span class="sd">    &#39;&#39;&#39;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sock</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">sock</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span>
                <span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">sock</span> <span class="o">=</span> <span class="n">sock</span>

    <span class="k">def</span> <span class="nf">connect</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">sock</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">mysend</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">msg</span><span class="p">):</span>
        <span class="n">totalsent</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">while</span> <span class="n">totalsent</span> <span class="o">&lt;</span> <span class="n">MSGLEN</span><span class="p">:</span>
            <span class="n">sent</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">sock</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">msg</span><span class="p">[</span><span class="n">totalsent</span><span class="p">:])</span>
            <span class="k">if</span> <span class="n">sent</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;socket connection broken&quot;</span><span class="p">)</span>
            <span class="n">totalsent</span> <span class="o">=</span> <span class="n">totalsent</span> <span class="o">+</span> <span class="n">sent</span>

    <span class="k">def</span> <span class="nf">myreceive</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">chunks</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="n">bytes_recd</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">while</span> <span class="n">bytes_recd</span> <span class="o">&lt;</span> <span class="n">MSGLEN</span><span class="p">:</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">sock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="nb">min</span><span class="p">(</span><span class="n">MSGLEN</span> <span class="o">-</span> <span class="n">bytes_recd</span><span class="p">,</span> <span class="mi">2048</span><span class="p">))</span>
            <span class="k">if</span> <span class="n">chunk</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">&quot;socket connection broken&quot;</span><span class="p">)</span>
            <span class="n">chunks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
            <span class="n">bytes_recd</span> <span class="o">=</span> <span class="n">bytes_recd</span> <span class="o">+</span> <span class="nb">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
        <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">chunks</span><span class="p">)</span>
</pre></div>
</div>
<p>The sending code here is usable for almost any messaging scheme - in Python you
send strings, and you can use <code class="docutils literal notranslate"><span class="pre">len()</span></code> to determine its length (even if it has
embedded <code class="docutils literal notranslate"><span class="pre">\0</span></code> characters). It’s mostly the receiving code that gets more
complex. (And in C, it’s not much worse, except you can’t use <code class="docutils literal notranslate"><span class="pre">strlen</span></code> if the
message has embedded <code class="docutils literal notranslate"><span class="pre">\0</span></code>s.)</p>
<p>The easiest enhancement is to make the first character of the message an
indicator of message type, and have the type determine the length. Now you have
two <code class="docutils literal notranslate"><span class="pre">recv</span></code>s - the first to get (at least) that first character so you can
look up the length, and the second in a loop to get the rest. If you decide to
go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096
or 8192 is frequently a good match for network buffer sizes), and scanning what
you’ve received for a delimiter.</p>
<p>One complication to be aware of: if your conversational protocol allows multiple
messages to be sent back to back (without some kind of reply), and you pass
<code class="docutils literal notranslate"><span class="pre">recv</span></code> an arbitrary chunk size, you may end up reading the start of a
following message. You’ll need to put that aside and hold onto it, until it’s
needed.</p>
<p>Prefixing the message with its length (say, as 5 numeric characters) gets more
complex, because (believe it or not), you may not get all 5 characters in one
<code class="docutils literal notranslate"><span class="pre">recv</span></code>. In playing around, you’ll get away with it; but in high network loads,
your code will very quickly break unless you use two <code class="docutils literal notranslate"><span class="pre">recv</span></code> loops - the first
to determine the length, the second to get the data part of the message. Nasty.
This is also when you’ll discover that <code class="docutils literal notranslate"><span class="pre">send</span></code> does not always manage to get
rid of everything in one pass. And despite having read this, you will eventually
get bit by it!</p>
<p>In the interests of space, building your character, (and preserving my
competitive position), these enhancements are left as an exercise for the
reader. Lets move on to cleaning up.</p>
<div class="section" id="binary-data">
<h3>Binary Data<a class="headerlink" href="#binary-data" title="Permalink to this headline">¶</a></h3>
<p>It is perfectly possible to send binary data over a socket. The major problem is
that not all machines use the same formats for binary data. For example, a
Motorola chip will represent a 16 bit integer with the value 1 as the two hex
bytes 00 01. Intel and DEC, however, are byte-reversed - that same 1 is 01 00.
Socket libraries have calls for converting 16 and 32 bit integers - <code class="docutils literal notranslate"><span class="pre">ntohl,</span>
<span class="pre">htonl,</span> <span class="pre">ntohs,</span> <span class="pre">htons</span></code> where “n” means <em>network</em> and “h” means <em>host</em>, “s” means
<em>short</em> and “l” means <em>long</em>. Where network order is host order, these do
nothing, but where the machine is byte-reversed, these swap the bytes around
appropriately.</p>
<p>In these days of 32 bit machines, the ascii representation of binary data is
frequently smaller than the binary representation. That’s because a surprising
amount of the time, all those longs have the value 0, or maybe 1. The string “0”
would be two bytes, while binary is four. Of course, this doesn’t fit well with
fixed-length messages. Decisions, decisions.</p>
</div>
</div>
<div class="section" id="disconnecting">
<h2>Disconnecting<a class="headerlink" href="#disconnecting" title="Permalink to this headline">¶</a></h2>
<p>Strictly speaking, you’re supposed to use <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> on a socket before you
<code class="docutils literal notranslate"><span class="pre">close</span></code> it.  The <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> is an advisory to the socket at the other end.
Depending on the argument you pass it, it can mean “I’m not going to send
anymore, but I’ll still listen”, or “I’m not listening, good riddance!”.  Most
socket libraries, however, are so used to programmers neglecting to use this
piece of etiquette that normally a <code class="docutils literal notranslate"><span class="pre">close</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">shutdown();</span>
<span class="pre">close()</span></code>.  So in most situations, an explicit <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> is not needed.</p>
<p>One way to use <code class="docutils literal notranslate"><span class="pre">shutdown</span></code> effectively is in an HTTP-like exchange. The client
sends a request and then does a <code class="docutils literal notranslate"><span class="pre">shutdown(1)</span></code>. This tells the server “This
client is done sending, but can still receive.”  The server can detect “EOF” by
a receive of 0 bytes. It can assume it has the complete request.  The server
sends a reply. If the <code class="docutils literal notranslate"><span class="pre">send</span></code> completes successfully then, indeed, the client
was still receiving.</p>
<p>Python takes the automatic shutdown a step further, and says that when a socket
is garbage collected, it will automatically do a <code class="docutils literal notranslate"><span class="pre">close</span></code> if it’s needed. But
relying on this is a very bad habit. If your socket just disappears without
doing a <code class="docutils literal notranslate"><span class="pre">close</span></code>, the socket at the other end may hang indefinitely, thinking
you’re just being slow. <em>Please</em> <code class="docutils literal notranslate"><span class="pre">close</span></code> your sockets when you’re done.</p>
<div class="section" id="when-sockets-die">
<h3>When Sockets Die<a class="headerlink" href="#when-sockets-die" title="Permalink to this headline">¶</a></h3>
<p>Probably the worst thing about using blocking sockets is what happens when the
other side comes down hard (without doing a <code class="docutils literal notranslate"><span class="pre">close</span></code>). Your socket is likely to
hang. SOCKSTREAM is a reliable protocol, and it will wait a long, long time
before giving up on a connection. If you’re using threads, the entire thread is
essentially dead. There’s not much you can do about it. As long as you aren’t
doing something dumb, like holding a lock while doing a blocking read, the
thread isn’t really consuming much in the way of resources. Do <em>not</em> try to kill
the thread - part of the reason that threads are more efficient than processes
is that they avoid the overhead associated with the automatic recycling of
resources. In other words, if you do manage to kill the thread, your whole
process is likely to be screwed up.</p>
</div>
</div>
<div class="section" id="non-blocking-sockets">
<h2>Non-blocking Sockets<a class="headerlink" href="#non-blocking-sockets" title="Permalink to this headline">¶</a></h2>
<p>If you’ve understood the preceding, you already know most of what you need to
know about the mechanics of using sockets. You’ll still use the same calls, in
much the same ways. It’s just that, if you do it right, your app will be almost
inside-out.</p>
<p>In Python, you use <code class="docutils literal notranslate"><span class="pre">socket.setblocking(0)</span></code> to make it non-blocking. In C, it’s
more complex, (for one thing, you’ll need to choose between the BSD flavor
<code class="docutils literal notranslate"><span class="pre">O_NONBLOCK</span></code> and the almost indistinguishable Posix flavor <code class="docutils literal notranslate"><span class="pre">O_NDELAY</span></code>, which
is completely different from <code class="docutils literal notranslate"><span class="pre">TCP_NODELAY</span></code>), but it’s the exact same idea. You
do this after creating the socket, but before using it. (Actually, if you’re
nuts, you can switch back and forth.)</p>
<p>The major mechanical difference is that <code class="docutils literal notranslate"><span class="pre">send</span></code>, <code class="docutils literal notranslate"><span class="pre">recv</span></code>, <code class="docutils literal notranslate"><span class="pre">connect</span></code> and
<code class="docutils literal notranslate"><span class="pre">accept</span></code> can return without having done anything. You have (of course) a
number of choices. You can check return code and error codes and generally drive
yourself crazy. If you don’t believe me, try it sometime. Your app will grow
large, buggy and suck CPU. So let’s skip the brain-dead solutions and do it
right.</p>
<p>Use <code class="docutils literal notranslate"><span class="pre">select</span></code>.</p>
<p>In C, coding <code class="docutils literal notranslate"><span class="pre">select</span></code> is fairly complex. In Python, it’s a piece of cake, but
it’s close enough to the C version that if you understand <code class="docutils literal notranslate"><span class="pre">select</span></code> in Python,
you’ll have little trouble with it in C:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ready_to_read</span><span class="p">,</span> <span class="n">ready_to_write</span><span class="p">,</span> <span class="n">in_error</span> <span class="o">=</span> \
               <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">(</span>
                  <span class="n">potential_readers</span><span class="p">,</span>
                  <span class="n">potential_writers</span><span class="p">,</span>
                  <span class="n">potential_errs</span><span class="p">,</span>
                  <span class="n">timeout</span><span class="p">)</span>
</pre></div>
</div>
<p>You pass <code class="docutils literal notranslate"><span class="pre">select</span></code> three lists: the first contains all sockets that you might
want to try reading; the second all the sockets you might want to try writing
to, and the last (normally left empty) those that you want to check for errors.
You should note that a socket can go into more than one list. The <code class="docutils literal notranslate"><span class="pre">select</span></code>
call is blocking, but you can give it a timeout. This is generally a sensible
thing to do - give it a nice long timeout (say a minute) unless you have good
reason to do otherwise.</p>
<p>In return, you will get three lists. They contain the sockets that are actually
readable, writable and in error. Each of these lists is a subset (possibly
empty) of the corresponding list you passed in.</p>
<p>If a socket is in the output readable list, you can be
as-close-to-certain-as-we-ever-get-in-this-business that a <code class="docutils literal notranslate"><span class="pre">recv</span></code> on that
socket will return <em>something</em>. Same idea for the writable list. You’ll be able
to send <em>something</em>. Maybe not all you want to, but <em>something</em> is better than
nothing.  (Actually, any reasonably healthy socket will return as writable - it
just means outbound network buffer space is available.)</p>
<p>If you have a “server” socket, put it in the potential_readers list. If it comes
out in the readable list, your <code class="docutils literal notranslate"><span class="pre">accept</span></code> will (almost certainly) work. If you
have created a new socket to <code class="docutils literal notranslate"><span class="pre">connect</span></code> to someone else, put it in the
potential_writers list. If it shows up in the writable list, you have a decent
chance that it has connected.</p>
<p>One very nasty problem with <code class="docutils literal notranslate"><span class="pre">select</span></code>: if somewhere in those input lists of
sockets is one which has died a nasty death, the <code class="docutils literal notranslate"><span class="pre">select</span></code> will fail. You then
need to loop through every single damn socket in all those lists and do a
<code class="docutils literal notranslate"><span class="pre">select([sock],[],[],0)</span></code> until you find the bad one. That timeout of 0 means
it won’t take long, but it’s ugly.</p>
<p>Actually, <code class="docutils literal notranslate"><span class="pre">select</span></code> can be handy even with blocking sockets. It’s one way of
determining whether you will block - the socket returns as readable when there’s
something in the buffers.  However, this still doesn’t help with the problem of
determining whether the other end is done, or just busy with something else.</p>
<p><strong>Portability alert</strong>: On Unix, <code class="docutils literal notranslate"><span class="pre">select</span></code> works both with the sockets and
files. Don’t try this on Windows. On Windows, <code class="docutils literal notranslate"><span class="pre">select</span></code> works with sockets
only. Also note that in C, many of the more advanced socket options are done
differently on Windows. In fact, on Windows I usually use threads (which work
very, very well) with my sockets. Face it, if you want any kind of performance,
your code will look very different on Windows than on Unix.</p>
<div class="section" id="performance">
<h3>Performance<a class="headerlink" href="#performance" title="Permalink to this headline">¶</a></h3>
<p>There’s no question that the fastest sockets code uses non-blocking sockets and
select to multiplex them. You can put together something that will saturate a
LAN connection without putting any strain on the CPU. The trouble is that an app
written this way can’t do much of anything else - it needs to be ready to
shuffle bytes around at all times.</p>
<p>Assuming that your app is actually supposed to do something more than that,
threading is the optimal solution, (and using non-blocking sockets will be
faster than using blocking sockets). Unfortunately, threading support in Unixes
varies both in API and quality. So the normal Unix solution is to fork a
subprocess to deal with each connection. The overhead for this is significant
(and don’t do this on Windows - the overhead of process creation is enormous
there). It also means that unless each subprocess is completely independent,
you’ll need to use another form of IPC, say a pipe, or shared memory and
semaphores, to communicate between the parent and child processes.</p>
<p>Finally, remember that even though blocking sockets are somewhat slower than
non-blocking, in many cases they are the “right” solution. After all, if your
app is driven by the data it receives over a socket, there’s not much sense in
complicating the logic just so your app can wait on <code class="docutils literal notranslate"><span class="pre">select</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">recv</span></code>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Socket Programming HOWTO</a><ul>
<li><a class="reference internal" href="#sockets">Sockets</a><ul>
<li><a class="reference internal" href="#history">History</a></li>
</ul>
</li>
<li><a class="reference internal" href="#creating-a-socket">Creating a Socket</a><ul>
<li><a class="reference internal" href="#ipc">IPC</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-a-socket">Using a Socket</a><ul>
<li><a class="reference internal" href="#binary-data">Binary Data</a></li>
</ul>
</li>
<li><a class="reference internal" href="#disconnecting">Disconnecting</a><ul>
<li><a class="reference internal" href="#when-sockets-die">When Sockets Die</a></li>
</ul>
</li>
<li><a class="reference internal" href="#non-blocking-sockets">Non-blocking Sockets</a><ul>
<li><a class="reference internal" href="#performance">Performance</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="regex.html"
                        title="previous chapter">Regular Expression HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sorting.html"
                        title="next chapter">Sorting HOW TO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/sockets.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sorting.html" title="Sorting HOW TO"
             >next</a> |</li>
        <li class="right" >
          <a href="regex.html" title="Regular Expression HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\a�kR�R�html/howto/sorting.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sorting HOW TO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Unicode HOWTO" href="unicode.html" />
    <link rel="prev" title="Socket Programming HOWTO" href="sockets.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/sorting.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode HOWTO"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="sorting-how-to">
<span id="sortinghowto"></span><h1>Sorting HOW TO<a class="headerlink" href="#sorting-how-to" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Andrew Dalke and Raymond Hettinger</td>
</tr>
<tr class="field-even field"><th class="field-name">Release:</th><td class="field-body">0.1</td>
</tr>
</tbody>
</table>
<p>Python lists have a built-in <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method that modifies the list
in-place.  There is also a <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> built-in function that builds a new
sorted list from an iterable.</p>
<p>In this document, we explore the various techniques for sorting data using Python.</p>
<div class="section" id="sorting-basics">
<h2>Sorting Basics<a class="headerlink" href="#sorting-basics" title="Permalink to this headline">¶</a></h2>
<p>A simple ascending sort is very easy: just call the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function. It
returns a new sorted list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">])</span>
<span class="go">[1, 2, 3, 4, 5]</span>
</pre></div>
</div>
<p>You can also use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method of a list. It modifies the list
in-place (and returns <code class="docutils literal notranslate"><span class="pre">None</span></code> to avoid confusion). Usually it’s less convenient
than <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> - but if you don’t need the original list, it’s slightly
more efficient.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 2, 3, 4, 5]</span>
</pre></div>
</div>
<p>Another difference is that the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method is only defined for
lists. In contrast, the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function accepts any iterable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">({</span><span class="mi">1</span><span class="p">:</span> <span class="s1">&#39;D&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">:</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">:</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">:</span> <span class="s1">&#39;E&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">:</span> <span class="s1">&#39;A&#39;</span><span class="p">})</span>
<span class="go">[1, 2, 3, 4, 5]</span>
</pre></div>
</div>
</div>
<div class="section" id="key-functions">
<h2>Key Functions<a class="headerlink" href="#key-functions" title="Permalink to this headline">¶</a></h2>
<p>Starting with Python 2.4, both <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> and <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> added a
<em>key</em> parameter to specify a function to be called on each list element prior to
making comparisons.</p>
<p>For example, here’s a case-insensitive string comparison:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="s2">&quot;This is a test string from Andrew&quot;</span><span class="o">.</span><span class="n">split</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="o">.</span><span class="n">lower</span><span class="p">)</span>
<span class="go">[&#39;a&#39;, &#39;Andrew&#39;, &#39;from&#39;, &#39;is&#39;, &#39;string&#39;, &#39;test&#39;, &#39;This&#39;]</span>
</pre></div>
</div>
<p>The value of the <em>key</em> parameter should be a function that takes a single argument
and returns a key to use for sorting purposes. This technique is fast because
the key function is called exactly once for each input record.</p>
<p>A common pattern is to sort complex objects using some of the object’s indices
as keys. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">student_tuples</span> <span class="o">=</span> <span class="p">[</span>
<span class="gp">... </span>    <span class="p">(</span><span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="mi">15</span><span class="p">),</span>
<span class="gp">... </span>    <span class="p">(</span><span class="s1">&#39;jane&#39;</span><span class="p">,</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">12</span><span class="p">),</span>
<span class="gp">... </span>    <span class="p">(</span><span class="s1">&#39;dave&#39;</span><span class="p">,</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span>
<span class="gp">... </span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">student</span><span class="p">:</span> <span class="n">student</span><span class="p">[</span><span class="mi">2</span><span class="p">])</span>   <span class="c1"># sort by age</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
<p>The same technique works for objects with named attributes. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Student</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">grade</span><span class="p">,</span> <span class="n">age</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">grade</span> <span class="o">=</span> <span class="n">grade</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">=</span> <span class="n">age</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">repr</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">grade</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span><span class="p">))</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">student_objects</span> <span class="o">=</span> <span class="p">[</span>
<span class="gp">... </span>    <span class="n">Student</span><span class="p">(</span><span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="mi">15</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Student</span><span class="p">(</span><span class="s1">&#39;jane&#39;</span><span class="p">,</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">12</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">Student</span><span class="p">(</span><span class="s1">&#39;dave&#39;</span><span class="p">,</span> <span class="s1">&#39;B&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span>
<span class="gp">... </span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">student</span><span class="p">:</span> <span class="n">student</span><span class="o">.</span><span class="n">age</span><span class="p">)</span>   <span class="c1"># sort by age</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
</div>
<div class="section" id="operator-module-functions">
<h2>Operator Module Functions<a class="headerlink" href="#operator-module-functions" title="Permalink to this headline">¶</a></h2>
<p>The key-function patterns shown above are very common, so Python provides
convenience functions to make accessor functions easier and faster. The operator
module has <a class="reference internal" href="../library/operator.html#operator.itemgetter" title="operator.itemgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.itemgetter()</span></code></a>, <a class="reference internal" href="../library/operator.html#operator.attrgetter" title="operator.attrgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.attrgetter()</span></code></a>, and
starting in Python 2.5 an <a class="reference internal" href="../library/operator.html#operator.methodcaller" title="operator.methodcaller"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.methodcaller()</span></code></a> function.</p>
<p>Using those functions, the above examples become simpler and faster:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">operator</span> <span class="k">import</span> <span class="n">itemgetter</span><span class="p">,</span> <span class="n">attrgetter</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">&#39;age&#39;</span><span class="p">))</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
<p>The operator module functions allow multiple levels of sorting. For example, to
sort by <em>grade</em> then by <em>age</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">))</span>
<span class="go">[(&#39;john&#39;, &#39;A&#39;, 15), (&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12)]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">&#39;grade&#39;</span><span class="p">,</span> <span class="s1">&#39;age&#39;</span><span class="p">))</span>
<span class="go">[(&#39;john&#39;, &#39;A&#39;, 15), (&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12)]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/operator.html#operator.methodcaller" title="operator.methodcaller"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.methodcaller()</span></code></a> function makes method calls with fixed
parameters for each object being sorted.  For example, the <a class="reference internal" href="../library/stdtypes.html#str.count" title="str.count"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.count()</span></code></a>
method could be used to compute message priority by counting the
number of exclamation marks in a message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">operator</span> <span class="k">import</span> <span class="n">methodcaller</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">messages</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;critical!!!&#39;</span><span class="p">,</span> <span class="s1">&#39;hurry!&#39;</span><span class="p">,</span> <span class="s1">&#39;standby&#39;</span><span class="p">,</span> <span class="s1">&#39;immediate!!&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">messages</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">methodcaller</span><span class="p">(</span><span class="s1">&#39;count&#39;</span><span class="p">,</span> <span class="s1">&#39;!&#39;</span><span class="p">))</span>
<span class="go">[&#39;standby&#39;, &#39;hurry!&#39;, &#39;immediate!!&#39;, &#39;critical!!!&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="ascending-and-descending">
<h2>Ascending and Descending<a class="headerlink" href="#ascending-and-descending" title="Permalink to this headline">¶</a></h2>
<p>Both <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> and <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> accept a <em>reverse</em> parameter with a
boolean value. This is used to flag descending sorts. For example, to get the
student data in reverse <em>age</em> order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_tuples</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[(&#39;john&#39;, &#39;A&#39;, 15), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;dave&#39;, &#39;B&#39;, 10)]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">&#39;age&#39;</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[(&#39;john&#39;, &#39;A&#39;, 15), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;dave&#39;, &#39;B&#39;, 10)]</span>
</pre></div>
</div>
</div>
<div class="section" id="sort-stability-and-complex-sorts">
<h2>Sort Stability and Complex Sorts<a class="headerlink" href="#sort-stability-and-complex-sorts" title="Permalink to this headline">¶</a></h2>
<p>Starting with Python 2.2, sorts are guaranteed to be <a class="reference external" href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability">stable</a>. That means that
when multiple records have the same key, their original order is preserved.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span>
<span class="go">[(&#39;blue&#39;, 1), (&#39;blue&#39;, 2), (&#39;red&#39;, 1), (&#39;red&#39;, 2)]</span>
</pre></div>
</div>
<p>Notice how the two records for <em>blue</em> retain their original order so that
<code class="docutils literal notranslate"><span class="pre">('blue',</span> <span class="pre">1)</span></code> is guaranteed to precede <code class="docutils literal notranslate"><span class="pre">('blue',</span> <span class="pre">2)</span></code>.</p>
<p>This wonderful property lets you build complex sorts in a series of sorting
steps. For example, to sort the student data by descending <em>grade</em> and then
ascending <em>age</em>, do the <em>age</em> sort first and then sort again using <em>grade</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">&#39;age&#39;</span><span class="p">))</span>     <span class="c1"># sort on secondary key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">attrgetter</span><span class="p">(</span><span class="s1">&#39;grade&#39;</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>       <span class="c1"># now sort on primary key, descending</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
<p>The <a class="reference external" href="https://en.wikipedia.org/wiki/Timsort">Timsort</a> algorithm used in Python
does multiple sorts efficiently because it can take advantage of any ordering
already present in a dataset.</p>
</div>
<div class="section" id="the-old-way-using-decorate-sort-undecorate">
<h2>The Old Way Using Decorate-Sort-Undecorate<a class="headerlink" href="#the-old-way-using-decorate-sort-undecorate" title="Permalink to this headline">¶</a></h2>
<p>This idiom is called Decorate-Sort-Undecorate after its three steps:</p>
<ul class="simple">
<li>First, the initial list is decorated with new values that control the sort order.</li>
<li>Second, the decorated list is sorted.</li>
<li>Finally, the decorations are removed, creating a list that contains only the
initial values in the new order.</li>
</ul>
<p>For example, to sort the student data by <em>grade</em> using the DSU approach:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">decorated</span> <span class="o">=</span> <span class="p">[(</span><span class="n">student</span><span class="o">.</span><span class="n">grade</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">student_objects</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decorated</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">student</span> <span class="k">for</span> <span class="n">grade</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">student</span> <span class="ow">in</span> <span class="n">decorated</span><span class="p">]</span>               <span class="c1"># undecorate</span>
<span class="go">[(&#39;john&#39;, &#39;A&#39;, 15), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;dave&#39;, &#39;B&#39;, 10)]</span>
</pre></div>
</div>
<p>This idiom works because tuples are compared lexicographically; the first items
are compared; if they are the same then the second items are compared, and so
on.</p>
<p>It is not strictly necessary in all cases to include the index <em>i</em> in the
decorated list, but including it gives two benefits:</p>
<ul class="simple">
<li>The sort is stable – if two items have the same key, their order will be
preserved in the sorted list.</li>
<li>The original items do not have to be comparable because the ordering of the
decorated tuples will be determined by at most the first two items. So for
example the original list could contain complex numbers which cannot be sorted
directly.</li>
</ul>
<p>Another name for this idiom is
<a class="reference external" href="https://en.wikipedia.org/wiki/Schwartzian_transform">Schwartzian transform</a>,
after Randal L. Schwartz, who popularized it among Perl programmers.</p>
<p>For large lists and lists where the comparison information is expensive to
calculate, and Python versions before 2.4, DSU is likely to be the fastest way
to sort the list. For 2.4 and later, key functions provide the same
functionality.</p>
</div>
<div class="section" id="the-old-way-using-the-cmp-parameter">
<h2>The Old Way Using the <em>cmp</em> Parameter<a class="headerlink" href="#the-old-way-using-the-cmp-parameter" title="Permalink to this headline">¶</a></h2>
<p>Many constructs given in this HOWTO assume Python 2.4 or later. Before that,
there was no <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> builtin and <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> took no keyword
arguments. Instead, all of the Py2.x versions supported a <em>cmp</em> parameter to
handle user specified comparison functions.</p>
<p>In Python 3, the <em>cmp</em> parameter was removed entirely (as part of a larger effort to
simplify and unify the language, eliminating the conflict between rich
comparisons and the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> magic method).</p>
<p>In Python 2, <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> allowed an optional function which can be called for doing the
comparisons. That function should take two arguments to be compared and then
return a negative value for less-than, return zero if they are equal, or return
a positive value for greater-than. For example, we can do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">numeric_compare</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">x</span> <span class="o">-</span> <span class="n">y</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="nb">cmp</span><span class="o">=</span><span class="n">numeric_compare</span><span class="p">)</span> 
<span class="go">[1, 2, 3, 4, 5]</span>
</pre></div>
</div>
<p>Or you can reverse the order of comparison with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">reverse_numeric</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">y</span> <span class="o">-</span> <span class="n">x</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="nb">cmp</span><span class="o">=</span><span class="n">reverse_numeric</span><span class="p">)</span> 
<span class="go">[5, 4, 3, 2, 1]</span>
</pre></div>
</div>
<p>When porting code from Python 2.x to 3.x, the situation can arise when you have
the user supplying a comparison function and you need to convert that to a key
function. The following wrapper makes that easy to do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">cmp_to_key</span><span class="p">(</span><span class="n">mycmp</span><span class="p">):</span>
    <span class="s1">&#39;Convert a cmp= function into a key= function&#39;</span>
    <span class="k">class</span> <span class="nc">K</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
        <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">obj</span> <span class="o">=</span> <span class="n">obj</span>
        <span class="k">def</span> <span class="nf">__lt__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">&lt;</span> <span class="mi">0</span>
        <span class="k">def</span> <span class="nf">__gt__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span>
        <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
        <span class="k">def</span> <span class="nf">__le__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">0</span>
        <span class="k">def</span> <span class="nf">__ge__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">0</span>
        <span class="k">def</span> <span class="nf">__ne__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">mycmp</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">obj</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">obj</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">0</span>
    <span class="k">return</span> <span class="n">K</span>
</pre></div>
</div>
<p>To convert to a key function, just wrap the old comparison function:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">([</span><span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="n">key</span><span class="o">=</span><span class="n">cmp_to_key</span><span class="p">(</span><span class="n">reverse_numeric</span><span class="p">))</span>
<span class="go">[5, 4, 3, 2, 1]</span>
</pre></div>
</div>
<p>In Python 2.7, the <a class="reference internal" href="../library/functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.cmp_to_key()</span></code></a> function was added to the
functools module.</p>
</div>
<div class="section" id="odd-and-ends">
<h2>Odd and Ends<a class="headerlink" href="#odd-and-ends" title="Permalink to this headline">¶</a></h2>
<ul>
<li><p class="first">For locale aware sorting, use <a class="reference internal" href="../library/locale.html#locale.strxfrm" title="locale.strxfrm"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strxfrm()</span></code></a> for a key function or
<a class="reference internal" href="../library/locale.html#locale.strcoll" title="locale.strcoll"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.strcoll()</span></code></a> for a comparison function.</p>
</li>
<li><p class="first">The <em>reverse</em> parameter still maintains sort stability (so that records with
equal keys retain their original order). Interestingly, that effect can be
simulated without the parameter by using the builtin <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> function
twice:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">standard_way</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">double_reversed</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">key</span><span class="o">=</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">))))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="n">standard_way</span> <span class="o">==</span> <span class="n">double_reversed</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">standard_way</span>
<span class="go">[(&#39;red&#39;, 1), (&#39;red&#39;, 2), (&#39;blue&#39;, 1), (&#39;blue&#39;, 2)]</span>
</pre></div>
</div>
</li>
<li><p class="first">To create a standard sort order for a class, just add the appropriate rich
comparison methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__eq__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">==</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__ne__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">!=</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__lt__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">&lt;</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__le__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">&lt;=</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__gt__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="fm">__ge__</span> <span class="o">=</span> <span class="k">lambda</span> <span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">:</span> <span class="bp">self</span><span class="o">.</span><span class="n">age</span> <span class="o">&gt;=</span> <span class="n">other</span><span class="o">.</span><span class="n">age</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">student_objects</span><span class="p">)</span>
<span class="go">[(&#39;dave&#39;, &#39;B&#39;, 10), (&#39;jane&#39;, &#39;B&#39;, 12), (&#39;john&#39;, &#39;A&#39;, 15)]</span>
</pre></div>
</div>
<p>For general purpose comparisons, the recommended approach is to define all six
rich comparison operators.  The <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.total_ordering()</span></code></a> class
decorator makes this easy to implement.</p>
</li>
<li><p class="first">Key functions need not depend directly on the objects being sorted. A key
function can also access external resources. For instance, if the student grades
are stored in a dictionary, they can be used to sort a separate list of student
names:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">students</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;dave&#39;</span><span class="p">,</span> <span class="s1">&#39;john&#39;</span><span class="p">,</span> <span class="s1">&#39;jane&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">grades</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;john&#39;</span><span class="p">:</span> <span class="s1">&#39;F&#39;</span><span class="p">,</span> <span class="s1">&#39;jane&#39;</span><span class="p">:</span><span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="s1">&#39;dave&#39;</span><span class="p">:</span> <span class="s1">&#39;C&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">students</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">grades</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">)</span>
<span class="go">[&#39;jane&#39;, &#39;dave&#39;, &#39;john&#39;]</span>
</pre></div>
</div>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Sorting HOW TO</a><ul>
<li><a class="reference internal" href="#sorting-basics">Sorting Basics</a></li>
<li><a class="reference internal" href="#key-functions">Key Functions</a></li>
<li><a class="reference internal" href="#operator-module-functions">Operator Module Functions</a></li>
<li><a class="reference internal" href="#ascending-and-descending">Ascending and Descending</a></li>
<li><a class="reference internal" href="#sort-stability-and-complex-sorts">Sort Stability and Complex Sorts</a></li>
<li><a class="reference internal" href="#the-old-way-using-decorate-sort-undecorate">The Old Way Using Decorate-Sort-Undecorate</a></li>
<li><a class="reference internal" href="#the-old-way-using-the-cmp-parameter">The Old Way Using the <em>cmp</em> Parameter</a></li>
<li><a class="reference internal" href="#odd-and-ends">Odd and Ends</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sockets.html"
                        title="previous chapter">Socket Programming HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unicode.html"
                        title="next chapter">Unicode HOWTO</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/sorting.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode HOWTO"
             >next</a> |</li>
        <li class="right" >
          <a href="sockets.html" title="Socket Programming HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\n�~||html/howto/unicode.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Unicode HOWTO &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="HOWTO Fetch Internet Resources Using urllib2" href="urllib2.html" />
    <link rel="prev" title="Sorting HOW TO" href="sorting.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/unicode.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="HOWTO Fetch Internet Resources Using urllib2"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sorting.html" title="Sorting HOW TO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="unicode-howto">
<h1>Unicode HOWTO<a class="headerlink" href="#unicode-howto" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Release:</th><td class="field-body">1.03</td>
</tr>
</tbody>
</table>
<p>This HOWTO discusses Python 2.x’s support for Unicode, and explains
various problems that people commonly encounter when trying to work
with Unicode.  For the Python 3 version, see
&lt;<a class="reference external" href="https://docs.python.org/3/howto/unicode.html">https://docs.python.org/3/howto/unicode.html</a>&gt;.</p>
<div class="section" id="introduction-to-unicode">
<h2>Introduction to Unicode<a class="headerlink" href="#introduction-to-unicode" title="Permalink to this headline">¶</a></h2>
<div class="section" id="history-of-character-codes">
<h3>History of Character Codes<a class="headerlink" href="#history-of-character-codes" title="Permalink to this headline">¶</a></h3>
<p>In 1968, the American Standard Code for Information Interchange, better known by
its acronym ASCII, was standardized.  ASCII defined numeric codes for various
characters, with the numeric values running from 0 to
127.  For example, the lowercase letter ‘a’ is assigned 97 as its code
value.</p>
<p>ASCII was an American-developed standard, so it only defined unaccented
characters.  There was an ‘e’, but no ‘é’ or ‘Í’.  This meant that languages
which required accented characters couldn’t be faithfully represented in ASCII.
(Actually the missing accents matter for English, too, which contains words such
as ‘naïve’ and ‘café’, and some publications have house styles which require
spellings such as ‘coöperate’.)</p>
<p>For a while people just wrote programs that didn’t display accents.  I remember
looking at Apple ][ BASIC programs, published in French-language publications in
the mid-1980s, that had lines like these:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">PRINT</span> <span class="s2">&quot;MISE A JOUR TERMINEE&quot;</span>
<span class="n">PRINT</span> <span class="s2">&quot;PARAMETRES ENREGISTRES&quot;</span>
</pre></div>
</div>
<p>Those messages should contain accents, and they just look wrong to someone who
can read French.</p>
<p>In the 1980s, almost all personal computers were 8-bit, meaning that bytes could
hold values ranging from 0 to 255.  ASCII codes only went up to 127, so some
machines assigned values between 128 and 255 to accented characters.  Different
machines had different codes, however, which led to problems exchanging files.
Eventually various commonly used sets of values for the 128–255 range emerged.
Some were true standards, defined by the International Organization for
Standardization, and some were <em>de facto</em> conventions that were invented by one
company or another and managed to catch on.</p>
<p>255 characters aren’t very many.  For example, you can’t fit both the accented
characters used in Western Europe and the Cyrillic alphabet used for Russian
into the 128–255 range because there are more than 128 such characters.</p>
<p>You could write files using different codes (all your Russian files in a coding
system called KOI8, all your French files in a different coding system called
Latin1), but what if you wanted to write a French document that quotes some
Russian text?  In the 1980s people began to want to solve this problem, and the
Unicode standardization effort began.</p>
<p>Unicode started out using 16-bit characters instead of 8-bit characters.  16
bits means you have 2^16 = 65,536 distinct values available, making it possible
to represent many different characters from many different alphabets; an initial
goal was to have Unicode contain the alphabets for every single human language.
It turns out that even 16 bits isn’t enough to meet that goal, and the modern
Unicode specification uses a wider range of codes, 0–1,114,111 (0x10ffff in
base-16).</p>
<p>There’s a related ISO standard, ISO 10646.  Unicode and ISO 10646 were
originally separate efforts, but the specifications were merged with the 1.1
revision of Unicode.</p>
<p>(This discussion of Unicode’s history is highly simplified.  I don’t think the
average Python programmer needs to worry about the historical details; consult
the Unicode consortium site listed in the References for more information.)</p>
</div>
<div class="section" id="definitions">
<h3>Definitions<a class="headerlink" href="#definitions" title="Permalink to this headline">¶</a></h3>
<p>A <strong>character</strong> is the smallest possible component of a text.  ‘A’, ‘B’, ‘C’,
etc., are all different characters.  So are ‘È’ and ‘Í’.  Characters are
abstractions, and vary depending on the language or context you’re talking
about.  For example, the symbol for ohms (Ω) is usually drawn much like the
capital letter omega (Ω) in the Greek alphabet (they may even be the same in
some fonts), but these are two different characters that have different
meanings.</p>
<p>The Unicode standard describes how characters are represented by <strong>code
points</strong>.  A code point is an integer value, usually denoted in base 16.  In the
standard, a code point is written using the notation U+12ca to mean the
character with value 0x12ca (4810 decimal).  The Unicode standard contains a lot
of tables listing characters and their corresponding code points:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">0061</span>    <span class="s1">&#39;a&#39;</span><span class="p">;</span> <span class="n">LATIN</span> <span class="n">SMALL</span> <span class="n">LETTER</span> <span class="n">A</span>
<span class="mi">0062</span>    <span class="s1">&#39;b&#39;</span><span class="p">;</span> <span class="n">LATIN</span> <span class="n">SMALL</span> <span class="n">LETTER</span> <span class="n">B</span>
<span class="mi">0063</span>    <span class="s1">&#39;c&#39;</span><span class="p">;</span> <span class="n">LATIN</span> <span class="n">SMALL</span> <span class="n">LETTER</span> <span class="n">C</span>
<span class="o">...</span>
<span class="mi">007</span><span class="n">B</span>    <span class="s1">&#39;{&#39;</span><span class="p">;</span> <span class="n">LEFT</span> <span class="n">CURLY</span> <span class="n">BRACKET</span>
</pre></div>
</div>
<p>Strictly, these definitions imply that it’s meaningless to say ‘this is
character U+12ca’.  U+12ca is a code point, which represents some particular
character; in this case, it represents the character ‘ETHIOPIC SYLLABLE WI’.  In
informal contexts, this distinction between code points and characters will
sometimes be forgotten.</p>
<p>A character is represented on a screen or on paper by a set of graphical
elements that’s called a <strong>glyph</strong>.  The glyph for an uppercase A, for example,
is two diagonal strokes and a horizontal stroke, though the exact details will
depend on the font being used.  Most Python code doesn’t need to worry about
glyphs; figuring out the correct glyph to display is generally the job of a GUI
toolkit or a terminal’s font renderer.</p>
</div>
<div class="section" id="encodings">
<h3>Encodings<a class="headerlink" href="#encodings" title="Permalink to this headline">¶</a></h3>
<p>To summarize the previous section: a Unicode string is a sequence of code
points, which are numbers from 0 to 0x10ffff.  This sequence needs to be
represented as a set of bytes (meaning, values from 0–255) in memory.  The rules
for translating a Unicode string into a sequence of bytes are called an
<strong>encoding</strong>.</p>
<p>The first encoding you might think of is an array of 32-bit integers.  In this
representation, the string “Python” would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>   <span class="n">P</span>           <span class="n">y</span>           <span class="n">t</span>           <span class="n">h</span>           <span class="n">o</span>           <span class="n">n</span>
<span class="mh">0x50</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">79</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">74</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">68</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">6</span><span class="n">f</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">6</span><span class="n">e</span> <span class="mi">00</span> <span class="mi">00</span> <span class="mi">00</span>
   <span class="mi">0</span>  <span class="mi">1</span>  <span class="mi">2</span>  <span class="mi">3</span>  <span class="mi">4</span>  <span class="mi">5</span>  <span class="mi">6</span>  <span class="mi">7</span>  <span class="mi">8</span>  <span class="mi">9</span> <span class="mi">10</span> <span class="mi">11</span> <span class="mi">12</span> <span class="mi">13</span> <span class="mi">14</span> <span class="mi">15</span> <span class="mi">16</span> <span class="mi">17</span> <span class="mi">18</span> <span class="mi">19</span> <span class="mi">20</span> <span class="mi">21</span> <span class="mi">22</span> <span class="mi">23</span>
</pre></div>
</div>
<p>This representation is straightforward but using it presents a number of
problems.</p>
<ol class="arabic simple">
<li>It’s not portable; different processors order the bytes differently.</li>
<li>It’s very wasteful of space.  In most texts, the majority of the code points
are less than 127, or less than 255, so a lot of space is occupied by zero
bytes.  The above string takes 24 bytes compared to the 6 bytes needed for an
ASCII representation.  Increased RAM usage doesn’t matter too much (desktop
computers have megabytes of RAM, and strings aren’t usually that large), but
expanding our usage of disk and network bandwidth by a factor of 4 is
intolerable.</li>
<li>It’s not compatible with existing C functions such as <code class="docutils literal notranslate"><span class="pre">strlen()</span></code>, so a new
family of wide string functions would need to be used.</li>
<li>Many Internet standards are defined in terms of textual data, and can’t
handle content with embedded zero bytes.</li>
</ol>
<p>Generally people don’t use this encoding, instead choosing other
encodings that are more efficient and convenient.  UTF-8 is probably
the most commonly supported encoding; it will be discussed below.</p>
<p>Encodings don’t have to handle every possible Unicode character, and most
encodings don’t.  For example, Python’s default encoding is the ‘ascii’
encoding.  The rules for converting a Unicode string into the ASCII encoding are
simple; for each code point:</p>
<ol class="arabic simple">
<li>If the code point is &lt; 128, each byte is the same as the value of the code
point.</li>
<li>If the code point is 128 or greater, the Unicode string can’t be represented
in this encoding.  (Python raises a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a> exception in this
case.)</li>
</ol>
<p>Latin-1, also known as ISO-8859-1, is a similar encoding.  Unicode code points
0–255 are identical to the Latin-1 values, so converting to this encoding simply
requires converting code points to byte values; if a code point larger than 255
is encountered, the string can’t be encoded into Latin-1.</p>
<p>Encodings don’t have to be simple one-to-one mappings like Latin-1.  Consider
IBM’s EBCDIC, which was used on IBM mainframes.  Letter values weren’t in one
block: ‘a’ through ‘i’ had values from 129 to 137, but ‘j’ through ‘r’ were 145
through 153.  If you wanted to use EBCDIC as an encoding, you’d probably use
some sort of lookup table to perform the conversion, but this is largely an
internal detail.</p>
<p>UTF-8 is one of the most commonly used encodings.  UTF stands for “Unicode
Transformation Format”, and the ‘8’ means that 8-bit numbers are used in the
encoding.  (There’s also a UTF-16 encoding, but it’s less frequently used than
UTF-8.)  UTF-8 uses the following rules:</p>
<ol class="arabic simple">
<li>If the code point is &lt;128, it’s represented by the corresponding byte value.</li>
<li>If the code point is between 128 and 0x7ff, it’s turned into two byte values
between 128 and 255.</li>
<li>Code points &gt;0x7ff are turned into three- or four-byte sequences, where each
byte of the sequence is between 128 and 255.</li>
</ol>
<p>UTF-8 has several convenient properties:</p>
<ol class="arabic simple">
<li>It can handle any Unicode code point.</li>
<li>A Unicode string is turned into a string of bytes containing no embedded zero
bytes.  This avoids byte-ordering issues, and means UTF-8 strings can be
processed by C functions such as <code class="docutils literal notranslate"><span class="pre">strcpy()</span></code> and sent through protocols that
can’t handle zero bytes.</li>
<li>A string of ASCII text is also valid UTF-8 text.</li>
<li>UTF-8 is fairly compact; the majority of code points are turned into two
bytes, and values less than 128 occupy only a single byte.</li>
<li>If bytes are corrupted or lost, it’s possible to determine the start of the
next UTF-8-encoded code point and resynchronize.  It’s also unlikely that
random 8-bit data will look like valid UTF-8.</li>
</ol>
</div>
<div class="section" id="references">
<h3>References<a class="headerlink" href="#references" title="Permalink to this headline">¶</a></h3>
<p>The Unicode Consortium site at &lt;<a class="reference external" href="http://www.unicode.org">http://www.unicode.org</a>&gt; has character charts, a
glossary, and PDF versions of the Unicode specification.  Be prepared for some
difficult reading.  &lt;<a class="reference external" href="http://www.unicode.org/history/">http://www.unicode.org/history/</a>&gt; is a chronology of the
origin and development of Unicode.</p>
<p>To help understand the standard, Jukka Korpela has written an introductory guide
to reading the Unicode character tables, available at
&lt;<a class="reference external" href="https://www.cs.tut.fi/~jkorpela/unicode/guide.html">https://www.cs.tut.fi/~jkorpela/unicode/guide.html</a>&gt;.</p>
<p>Another good introductory article was written by Joel Spolsky
&lt;<a class="reference external" href="http://www.joelonsoftware.com/articles/Unicode.html">http://www.joelonsoftware.com/articles/Unicode.html</a>&gt;.
If this introduction didn’t make things clear to you, you should try reading this
alternate article before continuing.</p>
<p>Wikipedia entries are often helpful; see the entries for “character encoding”
&lt;<a class="reference external" href="http://en.wikipedia.org/wiki/Character_encoding">http://en.wikipedia.org/wiki/Character_encoding</a>&gt; and UTF-8
&lt;<a class="reference external" href="http://en.wikipedia.org/wiki/UTF-8">http://en.wikipedia.org/wiki/UTF-8</a>&gt;, for example.</p>
</div>
</div>
<div class="section" id="python-2-x-s-unicode-support">
<h2>Python 2.x’s Unicode Support<a class="headerlink" href="#python-2-x-s-unicode-support" title="Permalink to this headline">¶</a></h2>
<p>Now that you’ve learned the rudiments of Unicode, we can look at Python’s
Unicode features.</p>
<div class="section" id="the-unicode-type">
<h3>The Unicode Type<a class="headerlink" href="#the-unicode-type" title="Permalink to this headline">¶</a></h3>
<p>Unicode strings are expressed as instances of the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> type, one of
Python’s repertoire of built-in types.  It derives from an abstract type called
<a class="reference internal" href="../library/functions.html#basestring" title="basestring"><code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code></a>, which is also an ancestor of the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type; you can
therefore check if a value is a string type with <code class="docutils literal notranslate"><span class="pre">isinstance(value,</span>
<span class="pre">basestring)</span></code>.  Under the hood, Python represents Unicode strings as either 16-
or 32-bit integers, depending on how the Python interpreter was compiled.</p>
<p>The <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> constructor has the signature <code class="docutils literal notranslate"><span class="pre">unicode(string[,</span> <span class="pre">encoding,</span>
<span class="pre">errors])</span></code>.  All of its arguments should be 8-bit strings.  The first argument
is converted to Unicode using the specified encoding; if you leave off the
<code class="docutils literal notranslate"><span class="pre">encoding</span></code> argument, the ASCII encoding is used for the conversion, so
characters greater than 127 will be treated as errors:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="go">u&#39;abcdef&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&lt;type &#39;unicode&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;abcdef&#39;</span> <span class="o">+</span> <span class="nb">chr</span><span class="p">(</span><span class="mi">255</span><span class="p">))</span>    
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">UnicodeDecodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t decode byte 0xff in position 6:</span>
<span class="go">ordinal not in range(128)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">errors</span></code> argument specifies the response when the input string can’t be
converted according to the encoding’s rules.  Legal values for this argument are
‘strict’ (raise a <code class="docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code> exception), ‘replace’ (add U+FFFD,
‘REPLACEMENT CHARACTER’), or ‘ignore’ (just leave the character out of the
Unicode result).  The following examples show the differences:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\x80</span><span class="s1">abc&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;strict&#39;</span><span class="p">)</span>     
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">UnicodeDecodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t decode byte 0x80 in position 0:</span>
<span class="go">ordinal not in range(128)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\x80</span><span class="s1">abc&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;replace&#39;</span><span class="p">)</span>
<span class="go">u&#39;\ufffdabc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\x80</span><span class="s1">abc&#39;</span><span class="p">,</span> <span class="n">errors</span><span class="o">=</span><span class="s1">&#39;ignore&#39;</span><span class="p">)</span>
<span class="go">u&#39;abc&#39;</span>
</pre></div>
</div>
<p>Encodings are specified as strings containing the encoding’s name.  Python 2.7
comes with roughly 100 different encodings; see the Python Library Reference at
<a class="reference internal" href="../library/codecs.html#standard-encodings"><span class="std std-ref">Standard Encodings</span></a> for a list.  Some encodings
have multiple names; for example, ‘latin-1’, ‘iso_8859_1’ and ‘8859’ are all
synonyms for the same encoding.</p>
<p>One-character Unicode strings can also be created with the <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a>
built-in function, which takes integers and returns a Unicode string of length 1
that contains the corresponding code point.  The reverse operation is the
built-in <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> function that takes a one-character Unicode string and
returns the code point value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">unichr</span><span class="p">(</span><span class="mi">40960</span><span class="p">)</span>
<span class="go">u&#39;\ua000&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">ord</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\ua000</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">40960</span>
</pre></div>
</div>
<p>Instances of the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> type have many of the same methods as the
8-bit string type for operations such as searching and formatting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;Was ever feather so lightly blown to and fro as this multitude?&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;e&#39;</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;feather&#39;</span><span class="p">)</span>
<span class="go">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;bird&#39;</span><span class="p">)</span>
<span class="go">-1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;feather&#39;</span><span class="p">,</span> <span class="s1">&#39;sand&#39;</span><span class="p">)</span>
<span class="go">u&#39;Was ever sand so lightly blown to and fro as this multitude?&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">u&#39;WAS EVER FEATHER SO LIGHTLY BLOWN TO AND FRO AS THIS MULTITUDE?&#39;</span>
</pre></div>
</div>
<p>Note that the arguments to these methods can be Unicode strings or 8-bit
strings.  8-bit strings will be converted to Unicode before carrying out the
operation; Python’s default ASCII encoding will be used, so characters greater
than 127 will cause an exception:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;Was</span><span class="se">\x9f</span><span class="s1">&#39;</span><span class="p">)</span>                   
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">UnicodeDecodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t decode byte 0x9f in position 3:</span>
<span class="go">ordinal not in range(128)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;Was</span><span class="se">\x9f</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">-1</span>
</pre></div>
</div>
<p>Much Python code that operates on strings will therefore work with Unicode
strings without requiring any changes to the code.  (Input and output code needs
more updating for Unicode; more on this later.)</p>
<p>Another important method is <code class="docutils literal notranslate"><span class="pre">.encode([encoding],</span> <span class="pre">[errors='strict'])</span></code>, which
returns an 8-bit string version of the Unicode string, encoded in the requested
encoding.  The <code class="docutils literal notranslate"><span class="pre">errors</span></code> parameter is the same as the parameter of the
<code class="docutils literal notranslate"><span class="pre">unicode()</span></code> constructor, with one additional possibility; as well as ‘strict’,
‘ignore’, and ‘replace’, you can also pass ‘xmlcharrefreplace’ which uses XML’s
character references.  The following example shows the different results:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">40960</span><span class="p">)</span> <span class="o">+</span> <span class="sa">u</span><span class="s1">&#39;abcd&#39;</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">1972</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="go">&#39;\xea\x80\x80abcd\xde\xb4&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">)</span>                       
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">UnicodeEncodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t encode character u&#39;\ua000&#39; in</span>
<span class="go">position 0: ordinal not in range(128)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">,</span> <span class="s1">&#39;ignore&#39;</span><span class="p">)</span>
<span class="go">&#39;abcd&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">,</span> <span class="s1">&#39;replace&#39;</span><span class="p">)</span>
<span class="go">&#39;?abcd?&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;ascii&#39;</span><span class="p">,</span> <span class="s1">&#39;xmlcharrefreplace&#39;</span><span class="p">)</span>
<span class="go">&#39;&amp;#40960;abcd&amp;#1972;&#39;</span>
</pre></div>
</div>
<p>Python’s 8-bit strings have a <code class="docutils literal notranslate"><span class="pre">.decode([encoding],</span> <span class="pre">[errors])</span></code> method that
interprets the string using the given encoding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">40960</span><span class="p">)</span> <span class="o">+</span> <span class="sa">u</span><span class="s1">&#39;abcd&#39;</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">1972</span><span class="p">)</span>   <span class="c1"># Assemble a string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">utf8_version</span> <span class="o">=</span> <span class="n">u</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>             <span class="c1"># Encode as UTF-8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">utf8_version</span><span class="p">),</span> <span class="n">utf8_version</span>
<span class="go">(&lt;type &#39;str&#39;&gt;, &#39;\xea\x80\x80abcd\xde\xb4&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u2</span> <span class="o">=</span> <span class="n">utf8_version</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>            <span class="c1"># Decode using UTF-8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">==</span> <span class="n">u2</span>                                      <span class="c1"># The two strings match</span>
<span class="go">True</span>
</pre></div>
</div>
<p>The low-level routines for registering and accessing the available encodings are
found in the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module.  However, the encoding and decoding functions
returned by this module are usually more low-level than is comfortable, so I’m
not going to describe the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module here.  If you need to implement a
completely new encoding, you’ll need to learn about the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module
interfaces, but implementing encodings is a specialized task that also won’t be
covered here.  Consult the Python documentation to learn more about this module.</p>
<p>The most commonly used part of the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module is the
<a class="reference internal" href="../library/codecs.html#codecs.open" title="codecs.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.open()</span></code></a> function which will be discussed in the section on input and
output.</p>
</div>
<div class="section" id="unicode-literals-in-python-source-code">
<h3>Unicode Literals in Python Source Code<a class="headerlink" href="#unicode-literals-in-python-source-code" title="Permalink to this headline">¶</a></h3>
<p>In Python source code, Unicode literals are written as strings prefixed with the
‘u’ or ‘U’ character: <code class="docutils literal notranslate"><span class="pre">u'abcdefghijk'</span></code>.  Specific code points can be written
using the <code class="docutils literal notranslate"><span class="pre">\u</span></code> escape sequence, which is followed by four hex digits giving
the code point.  The <code class="docutils literal notranslate"><span class="pre">\U</span></code> escape sequence is similar, but expects 8 hex
digits, not 4.</p>
<p>Unicode literals can also use the same escape sequences as 8-bit strings,
including <code class="docutils literal notranslate"><span class="pre">\x</span></code>, but <code class="docutils literal notranslate"><span class="pre">\x</span></code> only takes two hex digits so it can’t express an
arbitrary code point.  Octal escapes can go up to U+01ff, which is octal 777.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="sa">u</span><span class="s2">&quot;a</span><span class="se">\xac\u1234\u20ac\U00008000</span><span class="s2">&quot;</span>
<span class="gp">... </span><span class="c1">#      ^^^^ two-digit hex escape</span>
<span class="gp">... </span><span class="c1">#          ^^^^^^ four-digit Unicode escape</span>
<span class="gp">... </span><span class="c1">#                      ^^^^^^^^^^ eight-digit Unicode escape</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>  <span class="nb">print</span> <span class="nb">ord</span><span class="p">(</span><span class="n">c</span><span class="p">),</span>
<span class="gp">...</span>
<span class="go">97 172 4660 8364 32768</span>
</pre></div>
</div>
<p>Using escape sequences for code points greater than 127 is fine in small doses,
but becomes an annoyance if you’re using many accented characters, as you would
in a program with messages in French or some other accent-using language.  You
can also assemble strings using the <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a> built-in function, but this is
even more tedious.</p>
<p>Ideally, you’d want to be able to write literals in your language’s natural
encoding.  You could then edit Python source code with your favorite editor
which would display the accented characters naturally, and have the right
characters used at runtime.</p>
<p>Python supports writing Unicode literals in any encoding, but you have to
declare the encoding being used.  This is done by including a special comment as
either the first or second line of the source file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: latin-1 -*-</span>

<span class="n">u</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;abcdé&#39;</span>
<span class="nb">print</span> <span class="nb">ord</span><span class="p">(</span><span class="n">u</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>The syntax is inspired by Emacs’s notation for specifying variables local to a
file.  Emacs supports many different variables, but Python only supports
‘coding’.  The <code class="docutils literal notranslate"><span class="pre">-*-</span></code> symbols indicate to Emacs that the comment is special;
they have no significance to Python but are a convention.  Python looks for
<code class="docutils literal notranslate"><span class="pre">coding:</span> <span class="pre">name</span></code> or <code class="docutils literal notranslate"><span class="pre">coding=name</span></code> in the comment.</p>
<p>If you don’t include such a comment, the default encoding used will be ASCII.
Versions of Python before 2.4 were Euro-centric and assumed Latin-1 as a default
encoding for string literals; in Python 2.4, characters greater than 127 still
work but result in a warning.  For example, the following program has no
encoding declaration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="n">u</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;abcdé&#39;</span>
<span class="nb">print</span> <span class="nb">ord</span><span class="p">(</span><span class="n">u</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>When you run it with Python 2.4, it will output the following warning:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>amk:~$ python2.4 p263.py
sys:1: DeprecationWarning: Non-ASCII character &#39;\xe9&#39;
     in file p263.py on line 2, but no encoding declared;
     see https://www.python.org/peps/pep-0263.html for details
</pre></div>
</div>
<p>Python 2.5 and higher are stricter and will produce a syntax error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>amk:~$ python2.5 p263.py
File &quot;/tmp/p263.py&quot;, line 2
SyntaxError: Non-ASCII character &#39;\xc3&#39; in file /tmp/p263.py
  on line 2, but no encoding declared; see
  https://www.python.org/peps/pep-0263.html for details
</pre></div>
</div>
</div>
<div class="section" id="unicode-properties">
<h3>Unicode Properties<a class="headerlink" href="#unicode-properties" title="Permalink to this headline">¶</a></h3>
<p>The Unicode specification includes a database of information about code points.
For each code point that’s defined, the information includes the character’s
name, its category, the numeric value if applicable (Unicode has characters
representing the Roman numerals and fractions such as one-third and
four-fifths).  There are also properties related to the code point’s use in
bidirectional text and other display-related properties.</p>
<p>The following program displays some information about several characters, and
prints the numeric value of one particular character:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unicodedata</span>

<span class="n">u</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">233</span><span class="p">)</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mh">0x0bf2</span><span class="p">)</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">3972</span><span class="p">)</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">6000</span><span class="p">)</span> <span class="o">+</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">13231</span><span class="p">)</span>

<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">c</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">u</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">i</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%04x</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="nb">ord</span><span class="p">(</span><span class="n">c</span><span class="p">),</span> <span class="n">unicodedata</span><span class="o">.</span><span class="n">category</span><span class="p">(</span><span class="n">c</span><span class="p">),</span>
    <span class="nb">print</span> <span class="n">unicodedata</span><span class="o">.</span><span class="n">name</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>

<span class="c1"># Get numeric value of second character</span>
<span class="nb">print</span> <span class="n">unicodedata</span><span class="o">.</span><span class="n">numeric</span><span class="p">(</span><span class="n">u</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>When run, this prints:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">0</span> <span class="mf">00e9</span> <span class="n">Ll</span> <span class="n">LATIN</span> <span class="n">SMALL</span> <span class="n">LETTER</span> <span class="n">E</span> <span class="n">WITH</span> <span class="n">ACUTE</span>
<span class="mi">1</span> <span class="mi">0</span><span class="n">bf2</span> <span class="n">No</span> <span class="n">TAMIL</span> <span class="n">NUMBER</span> <span class="n">ONE</span> <span class="n">THOUSAND</span>
<span class="mi">2</span> <span class="mi">0</span><span class="n">f84</span> <span class="n">Mn</span> <span class="n">TIBETAN</span> <span class="n">MARK</span> <span class="n">HALANTA</span>
<span class="mi">3</span> <span class="mi">1770</span> <span class="n">Lo</span> <span class="n">TAGBANWA</span> <span class="n">LETTER</span> <span class="n">SA</span>
<span class="mi">4</span> <span class="mi">33</span><span class="n">af</span> <span class="n">So</span> <span class="n">SQUARE</span> <span class="n">RAD</span> <span class="n">OVER</span> <span class="n">S</span> <span class="n">SQUARED</span>
<span class="mf">1000.0</span>
</pre></div>
</div>
<p>The category codes are abbreviations describing the nature of the character.
These are grouped into categories such as “Letter”, “Number”, “Punctuation”, or
“Symbol”, which in turn are broken up into subcategories.  To take the codes
from the above output, <code class="docutils literal notranslate"><span class="pre">'Ll'</span></code> means ‘Letter, lowercase’, <code class="docutils literal notranslate"><span class="pre">'No'</span></code> means
“Number, other”, <code class="docutils literal notranslate"><span class="pre">'Mn'</span></code> is “Mark, nonspacing”, and <code class="docutils literal notranslate"><span class="pre">'So'</span></code> is “Symbol,
other”.  See
&lt;<a class="reference external" href="http://www.unicode.org/reports/tr44/#General_Category_Values">http://www.unicode.org/reports/tr44/#General_Category_Values</a>&gt; for a
list of category codes.</p>
</div>
<div class="section" id="id1">
<h3>References<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h3>
<p>The Unicode and 8-bit string types are described in the Python library reference
at <a class="reference internal" href="../library/stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>.</p>
<p>The documentation for the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module.</p>
<p>The documentation for the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module.</p>
<p>Marc-André Lemburg gave a presentation at EuroPython 2002 titled “Python and
Unicode”.  A PDF version of his slides is available at
&lt;<a class="reference external" href="https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf">https://downloads.egenix.com/python/Unicode-EPC2002-Talk.pdf</a>&gt;, and is an
excellent overview of the design of Python’s Unicode features.</p>
</div>
</div>
<div class="section" id="reading-and-writing-unicode-data">
<h2>Reading and Writing Unicode Data<a class="headerlink" href="#reading-and-writing-unicode-data" title="Permalink to this headline">¶</a></h2>
<p>Once you’ve written some code that works with Unicode data, the next problem is
input/output.  How do you get Unicode strings into your program, and how do you
convert Unicode into a form suitable for storage or transmission?</p>
<p>It’s possible that you may not need to do anything depending on your input
sources and output destinations; you should check whether the libraries used in
your application support Unicode natively.  XML parsers often return Unicode
data, for example.  Many relational databases also support Unicode-valued
columns and can return Unicode values from an SQL query.</p>
<p>Unicode data is usually converted to a particular encoding before it gets
written to disk or sent over a socket.  It’s possible to do all the work
yourself: open a file, read an 8-bit string from it, and convert the string with
<code class="docutils literal notranslate"><span class="pre">unicode(str,</span> <span class="pre">encoding)</span></code>.  However, the manual approach is not recommended.</p>
<p>One problem is the multi-byte nature of encodings; one Unicode character can be
represented by several bytes.  If you want to read the file in arbitrary-sized
chunks (say, 1K or 4K), you need to write error-handling code to catch the case
where only part of the bytes encoding a single Unicode character are read at the
end of a chunk.  One solution would be to read the entire file into memory and
then perform the decoding, but that prevents you from working with files that
are extremely large; if you need to read a 2Gb file, you need 2Gb of RAM.
(More, really, since for at least a moment you’d need to have both the encoded
string and its Unicode version in memory.)</p>
<p>The solution would be to use the low-level decoding interface to catch the case
of partial coding sequences.  The work of implementing this has already been
done for you: the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module includes a version of the <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
function that returns a file-like object that assumes the file’s contents are in
a specified encoding and accepts Unicode parameters for methods such as
<code class="docutils literal notranslate"><span class="pre">.read()</span></code> and <code class="docutils literal notranslate"><span class="pre">.write()</span></code>.</p>
<p>The function’s parameters are <code class="docutils literal notranslate"><span class="pre">open(filename,</span> <span class="pre">mode='rb',</span> <span class="pre">encoding=None,</span>
<span class="pre">errors='strict',</span> <span class="pre">buffering=1)</span></code>.  <code class="docutils literal notranslate"><span class="pre">mode</span></code> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'a'</span></code>,
just like the corresponding parameter to the regular built-in <code class="docutils literal notranslate"><span class="pre">open()</span></code>
function; add a <code class="docutils literal notranslate"><span class="pre">'+'</span></code> to update the file.  <code class="docutils literal notranslate"><span class="pre">buffering</span></code> is similarly parallel
to the standard function’s parameter.  <code class="docutils literal notranslate"><span class="pre">encoding</span></code> is a string giving the
encoding to use; if it’s left as <code class="docutils literal notranslate"><span class="pre">None</span></code>, a regular Python file object that
accepts 8-bit strings is returned.  Otherwise, a wrapper object is returned, and
data written to or read from the wrapper object will be converted as needed.
<code class="docutils literal notranslate"><span class="pre">errors</span></code> specifies the action for encoding errors and can be one of the usual
values of ‘strict’, ‘ignore’, and ‘replace’.</p>
<p>Reading Unicode from a file is therefore simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">codecs</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">codecs</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;unicode.rst&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<p>It’s also possible to open files in update mode, allowing both reading and
writing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="n">codecs</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">&#39;w+&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u4500</span><span class="s1"> blah blah blah</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()[:</span><span class="mi">1</span><span class="p">])</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
written as the first character of a file in order to assist with autodetection
of the file’s byte ordering.  Some encodings, such as UTF-16, expect a BOM to be
present at the start of a file; when such an encoding is used, the BOM will be
automatically written as the first character and will be silently dropped when
the file is read.  There are variants of these encodings, such as ‘utf-16-le’
and ‘utf-16-be’ for little-endian and big-endian encodings, that specify one
particular byte ordering and don’t skip the BOM.</p>
<div class="section" id="unicode-filenames">
<h3>Unicode filenames<a class="headerlink" href="#unicode-filenames" title="Permalink to this headline">¶</a></h3>
<p>Most of the operating systems in common use today support filenames that contain
arbitrary Unicode characters.  Usually this is implemented by converting the
Unicode string into some encoding that varies depending on the system.  For
example, Mac OS X uses UTF-8 while Windows uses a configurable encoding; on
Windows, Python uses the name “mbcs” to refer to whatever the currently
configured encoding is.  On Unix systems, there will only be a filesystem
encoding if you’ve set the <code class="docutils literal notranslate"><span class="pre">LANG</span></code> or <code class="docutils literal notranslate"><span class="pre">LC_CTYPE</span></code> environment variables; if
you haven’t, the default encoding is ASCII.</p>
<p>The <a class="reference internal" href="../library/sys.html#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getfilesystemencoding()</span></code></a> function returns the encoding to use on
your current system, in case you want to do the encoding manually, but there’s
not much reason to bother.  When opening a file for reading or writing, you can
usually just provide the Unicode string as the filename, and it will be
automatically converted to the right encoding for you:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">filename</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;filename</span><span class="se">\u4500</span><span class="s1">abc&#39;</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;blah</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Functions in the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module such as <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> will also accept Unicode
filenames.</p>
<p><a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>, which returns filenames, raises an issue: should it return
the Unicode version of filenames, or should it return 8-bit strings containing
the encoded versions?  <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> will do both, depending on whether you
provided the directory path as an 8-bit string or a Unicode string.  If you pass
a Unicode string as the path, filenames will be decoded using the filesystem’s
encoding and a list of Unicode strings will be returned, while passing an 8-bit
path will return the 8-bit versions of the filenames.  For example, assuming the
default filesystem encoding is UTF-8, running the following program:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fn</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;filename</span><span class="se">\u4500</span><span class="s1">abc&#39;</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">fn</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="nb">print</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>will produce the following output:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">amk:~$</span> python t.py
<span class="go">[&#39;.svn&#39;, &#39;filename\xe4\x94\x80abc&#39;, ...]</span>
<span class="go">[u&#39;.svn&#39;, u&#39;filename\u4500abc&#39;, ...]</span>
</pre></div>
</div>
<p>The first list contains UTF-8-encoded filenames, and the second list contains
the Unicode versions.</p>
</div>
<div class="section" id="tips-for-writing-unicode-aware-programs">
<h3>Tips for Writing Unicode-aware Programs<a class="headerlink" href="#tips-for-writing-unicode-aware-programs" title="Permalink to this headline">¶</a></h3>
<p>This section provides some suggestions on writing software that deals with
Unicode.</p>
<p>The most important tip is:</p>
<blockquote>
<div>Software should only work with Unicode strings internally, converting to a
particular encoding on output.</div></blockquote>
<p>If you attempt to write processing functions that accept both Unicode and 8-bit
strings, you will find your program vulnerable to bugs wherever you combine the
two different kinds of strings.  Python’s default encoding is ASCII, so whenever
a character with an ASCII value &gt; 127 is in the input data, you’ll get a
<a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> because that character can’t be handled by the ASCII
encoding.</p>
<p>It’s easy to miss such problems if you only test your software with data that
doesn’t contain any accents; everything will seem to work, but there’s actually
a bug in your program waiting for the first user who attempts to use characters
&gt; 127.  A second tip, therefore, is:</p>
<blockquote>
<div>Include characters &gt; 127 and, even better, characters &gt; 255 in your test
data.</div></blockquote>
<p>When using data coming from a web browser or some other untrusted source, a
common technique is to check for illegal characters in a string before using the
string in a generated command line or storing it in a database.  If you’re doing
this, be careful to check the string once it’s in the form that will be used or
stored; it’s possible for encodings to be used to disguise characters.  This is
especially true if the input data also specifies the encoding; many encodings
leave the commonly checked-for characters alone, but Python includes some
encodings such as <code class="docutils literal notranslate"><span class="pre">'base64'</span></code> that modify every single character.</p>
<p>For example, let’s say you have a content management system that takes a Unicode
filename, and you want to disallow paths with a ‘/’ character.  You might write
this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">read_file</span> <span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">encoding</span><span class="p">):</span>
    <span class="k">if</span> <span class="s1">&#39;/&#39;</span> <span class="ow">in</span> <span class="n">filename</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;&#39;/&#39; not allowed in filenames&quot;</span><span class="p">)</span>
    <span class="n">unicode_name</span> <span class="o">=</span> <span class="n">filename</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="n">encoding</span><span class="p">)</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">unicode_name</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
    <span class="c1"># ... return contents of file ...</span>
</pre></div>
</div>
<p>However, if an attacker could specify the <code class="docutils literal notranslate"><span class="pre">'base64'</span></code> encoding, they could pass
<code class="docutils literal notranslate"><span class="pre">'L2V0Yy9wYXNzd2Q='</span></code>, which is the base-64 encoded form of the string
<code class="docutils literal notranslate"><span class="pre">'/etc/passwd'</span></code>, to read a system file.  The above code looks for <code class="docutils literal notranslate"><span class="pre">'/'</span></code>
characters in the encoded form and misses the dangerous character in the
resulting decoded form.</p>
</div>
<div class="section" id="id2">
<h3>References<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3>
<p>The PDF slides for Marc-André Lemburg’s presentation “Writing Unicode-aware
Applications in Python” are available at
&lt;<a class="reference external" href="https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf">https://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf</a>&gt;
and discuss questions of character encodings as well as how to internationalize
and localize an application.</p>
</div>
</div>
<div class="section" id="revision-history-and-acknowledgements">
<h2>Revision History and Acknowledgements<a class="headerlink" href="#revision-history-and-acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>Thanks to the following people who have noted errors or offered suggestions on
this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
Marc-André Lemburg, Martin von Löwis, Chad Whitacre.</p>
<p>Version 1.0: posted August 5 2005.</p>
<p>Version 1.01: posted August 7 2005.  Corrects factual and markup errors; adds
several links.</p>
<p>Version 1.02: posted August 16 2005.  Corrects factual errors.</p>
<p>Version 1.03: posted June 20 2010.  Notes that Python 3.x is not covered,
and that the HOWTO only covers 2.x.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Unicode HOWTO</a><ul>
<li><a class="reference internal" href="#introduction-to-unicode">Introduction to Unicode</a><ul>
<li><a class="reference internal" href="#history-of-character-codes">History of Character Codes</a></li>
<li><a class="reference internal" href="#definitions">Definitions</a></li>
<li><a class="reference internal" href="#encodings">Encodings</a></li>
<li><a class="reference internal" href="#references">References</a></li>
</ul>
</li>
<li><a class="reference internal" href="#python-2-x-s-unicode-support">Python 2.x’s Unicode Support</a><ul>
<li><a class="reference internal" href="#the-unicode-type">The Unicode Type</a></li>
<li><a class="reference internal" href="#unicode-literals-in-python-source-code">Unicode Literals in Python Source Code</a></li>
<li><a class="reference internal" href="#unicode-properties">Unicode Properties</a></li>
<li><a class="reference internal" href="#id1">References</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reading-and-writing-unicode-data">Reading and Writing Unicode Data</a><ul>
<li><a class="reference internal" href="#unicode-filenames">Unicode filenames</a></li>
<li><a class="reference internal" href="#tips-for-writing-unicode-aware-programs">Tips for Writing Unicode-aware Programs</a></li>
<li><a class="reference internal" href="#id2">References</a></li>
</ul>
</li>
<li><a class="reference internal" href="#revision-history-and-acknowledgements">Revision History and Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sorting.html"
                        title="previous chapter">Sorting HOW TO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="urllib2.html"
                        title="next chapter">HOWTO Fetch Internet Resources Using urllib2</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/unicode.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="HOWTO Fetch Internet Resources Using urllib2"
             >next</a> |</li>
        <li class="right" >
          <a href="sorting.html" title="Sorting HOW TO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�4�����html/howto/urllib2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HOWTO Fetch Internet Resources Using urllib2 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="HOWTO Use Python in the web" href="webservers.html" />
    <link rel="prev" title="Unicode HOWTO" href="unicode.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/urllib2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webservers.html" title="HOWTO Use Python in the web"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode HOWTO"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="howto-fetch-internet-resources-using-urllib2">
<span id="urllib-howto"></span><h1>HOWTO Fetch Internet Resources Using urllib2<a class="headerlink" href="#howto-fetch-internet-resources-using-urllib2" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body"><a class="reference external" href="http://www.voidspace.org.uk/python/index.shtml">Michael Foord</a></td>
</tr>
</tbody>
</table>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There is a French translation of an earlier revision of this
HOWTO, available at <a class="reference external" href="http://www.voidspace.org.uk/python/articles/urllib2_francais.shtml">urllib2 - Le Manuel manquant</a>.</p>
</div>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<div class="sidebar">
<p class="first sidebar-title">Related Articles</p>
<p>You may also find useful the following article on fetching web resources
with Python:</p>
<ul class="last">
<li><p class="first"><a class="reference external" href="http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic Authentication</a></p>
<blockquote>
<div><p>A tutorial on <em>Basic Authentication</em>, with examples in Python.</p>
</div></blockquote>
</li>
</ul>
</div>
<p><strong>urllib2</strong> is a Python module for fetching URLs
(Uniform Resource Locators). It offers a very simple interface, in the form of
the <em>urlopen</em> function. This is capable of fetching URLs using a variety of
different protocols. It also offers a slightly more complex interface for
handling common situations - like basic authentication, cookies, proxies and so
on. These are provided by objects called handlers and openers.</p>
<p>urllib2 supports fetching URLs for many “URL schemes” (identified by the string
before the <code class="docutils literal notranslate"><span class="pre">&quot;:&quot;</span></code> in URL - for example <code class="docutils literal notranslate"><span class="pre">&quot;ftp&quot;</span></code> is the URL scheme of
<code class="docutils literal notranslate"><span class="pre">&quot;ftp://python.org/&quot;</span></code>) using their associated network protocols (e.g. FTP, HTTP).
This tutorial focuses on the most common case, HTTP.</p>
<p>For straightforward situations <em>urlopen</em> is very easy to use. But as soon as you
encounter errors or non-trivial cases when opening HTTP URLs, you will need some
understanding of the HyperText Transfer Protocol. The most comprehensive and
authoritative reference to HTTP is <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>. This is a technical document and
not intended to be easy to read. This HOWTO aims to illustrate using <em>urllib2</em>,
with enough detail about HTTP to help you through. It is not intended to replace
the <a class="reference internal" href="../library/urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> docs, but is supplementary to them.</p>
</div>
<div class="section" id="fetching-urls">
<h2>Fetching URLs<a class="headerlink" href="#fetching-urls" title="Permalink to this headline">¶</a></h2>
<p>The simplest way to use urllib2 is as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://python.org/&#39;</span><span class="p">)</span>
<span class="n">html</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>Many uses of urllib2 will be that simple (note that instead of an ‘http:’ URL we
could have used a URL starting with ‘ftp:’, ‘file:’, etc.).  However, it’s the
purpose of this tutorial to explain the more complicated cases, concentrating on
HTTP.</p>
<p>HTTP is based on requests and responses - the client makes requests and servers
send responses. urllib2 mirrors this with a <code class="docutils literal notranslate"><span class="pre">Request</span></code> object which represents
the HTTP request you are making. In its simplest form you create a Request
object that specifies the URL you want to fetch. Calling <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> with this
Request object returns a response object for the URL requested. This response is
a file-like object, which means you can for example call <code class="docutils literal notranslate"><span class="pre">.read()</span></code> on the
response:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>

<span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.voidspace.org.uk&#39;</span><span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that urllib2 makes use of the same Request interface to handle all URL
schemes.  For example, you can make an FTP request like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;ftp://example.com/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>In the case of HTTP, there are two extra things that Request objects allow you
to do: First, you can pass data to be sent to the server.  Second, you can pass
extra information (“metadata”) <em>about</em> the data or the about request itself, to
the server - this information is sent as HTTP “headers”.  Let’s look at each of
these in turn.</p>
<div class="section" id="data">
<h3>Data<a class="headerlink" href="#data" title="Permalink to this headline">¶</a></h3>
<p>Sometimes you want to send data to a URL (often the URL will refer to a CGI
(Common Gateway Interface) script <a class="footnote-reference" href="#id9" id="id1">[1]</a> or other web application). With HTTP,
this is often done using what’s known as a <strong>POST</strong> request. This is often what
your browser does when you submit a HTML form that you filled in on the web. Not
all POSTs have to come from forms: you can use a POST to transmit arbitrary data
to your own application. In the common case of HTML forms, the data needs to be
encoded in a standard way, and then passed to the Request object as the <code class="docutils literal notranslate"><span class="pre">data</span></code>
argument. The encoding is done using a function from the <code class="docutils literal notranslate"><span class="pre">urllib</span></code> library
<em>not</em> from <code class="docutils literal notranslate"><span class="pre">urllib2</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="kn">import</span> <span class="nn">urllib2</span>

<span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.someserver.com/cgi-bin/register.cgi&#39;</span>
<span class="n">values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span> <span class="p">:</span> <span class="s1">&#39;Michael Foord&#39;</span><span class="p">,</span>
          <span class="s1">&#39;location&#39;</span> <span class="p">:</span> <span class="s1">&#39;Northampton&#39;</span><span class="p">,</span>
          <span class="s1">&#39;language&#39;</span> <span class="p">:</span> <span class="s1">&#39;Python&#39;</span> <span class="p">}</span>

<span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that other encodings are sometimes required (e.g. for file upload from HTML
forms - see <a class="reference external" href="https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13">HTML Specification, Form Submission</a> for more
details).</p>
<p>If you do not pass the <code class="docutils literal notranslate"><span class="pre">data</span></code> argument, urllib2 uses a <strong>GET</strong> request. One
way in which GET and POST requests differ is that POST requests often have
“side-effects”: they change the state of the system in some way (for example by
placing an order with the website for a hundredweight of tinned spam to be
delivered to your door).  Though the HTTP standard makes it clear that POSTs are
intended to <em>always</em> cause side-effects, and GET requests <em>never</em> to cause
side-effects, nothing prevents a GET request from having side-effects, nor a
POST requests from having no side-effects. Data can also be passed in an HTTP
GET request by encoding it in the URL itself.</p>
<p>This is done as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Somebody Here&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;location&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Northampton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="s1">&#39;language&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">url_values</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">url_values</span>  <span class="c1"># The order may differ. </span>
<span class="go">name=Somebody+Here&amp;language=Python&amp;location=Northampton</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.example.com/example.cgi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">full_url</span> <span class="o">=</span> <span class="n">url</span> <span class="o">+</span> <span class="s1">&#39;?&#39;</span> <span class="o">+</span> <span class="n">url_values</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">full_url</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that the full URL is created by adding a <code class="docutils literal notranslate"><span class="pre">?</span></code> to the URL, followed by
the encoded values.</p>
</div>
<div class="section" id="headers">
<h3>Headers<a class="headerlink" href="#headers" title="Permalink to this headline">¶</a></h3>
<p>We’ll discuss here one particular HTTP header, to illustrate how to add headers
to your HTTP request.</p>
<p>Some websites <a class="footnote-reference" href="#id10" id="id2">[2]</a> dislike being browsed by programs, or send different versions
to different browsers <a class="footnote-reference" href="#id11" id="id3">[3]</a>. By default urllib2 identifies itself as
<code class="docutils literal notranslate"><span class="pre">Python-urllib/x.y</span></code> (where <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are the major and minor version
numbers of the Python release,
e.g. <code class="docutils literal notranslate"><span class="pre">Python-urllib/2.5</span></code>), which may confuse the site, or just plain
not work. The way a browser identifies itself is through the
<code class="docutils literal notranslate"><span class="pre">User-Agent</span></code> header <a class="footnote-reference" href="#id12" id="id4">[4]</a>. When you create a Request object you can
pass a dictionary of headers in. The following example makes the same
request as above, but identifies itself as a version of Internet
Explorer <a class="footnote-reference" href="#id13" id="id5">[5]</a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="kn">import</span> <span class="nn">urllib2</span>

<span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.someserver.com/cgi-bin/register.cgi&#39;</span>
<span class="n">user_agent</span> <span class="o">=</span> <span class="s1">&#39;Mozilla/5.0 (Windows NT 6.1; Win64; x64)&#39;</span>
<span class="n">values</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;Michael Foord&#39;</span><span class="p">,</span>
          <span class="s1">&#39;location&#39;</span><span class="p">:</span> <span class="s1">&#39;Northampton&#39;</span><span class="p">,</span>
          <span class="s1">&#39;language&#39;</span><span class="p">:</span> <span class="s1">&#39;Python&#39;</span> <span class="p">}</span>
<span class="n">headers</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">:</span> <span class="n">user_agent</span><span class="p">}</span>

<span class="n">data</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="n">the_page</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>The response also has two useful methods. See the section on <a class="reference internal" href="#info-and-geturl">info and geturl</a>
which comes after we have a look at what happens when things go wrong.</p>
</div>
</div>
<div class="section" id="handling-exceptions">
<h2>Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline">¶</a></h2>
<p><em>urlopen</em> raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code> when it cannot handle a response (though as
usual with Python APIs, built-in exceptions such as <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>,
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> etc. may also be raised).</p>
<p><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code> is the subclass of <code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code> raised in the specific case of
HTTP URLs.</p>
<div class="section" id="urlerror">
<h3>URLError<a class="headerlink" href="#urlerror" title="Permalink to this headline">¶</a></h3>
<p>Often, URLError is raised because there is no network connection (no route to
the specified server), or the specified server doesn’t exist.  In this case, the
exception raised will have a ‘reason’ attribute, which is a tuple containing an
error code and a text error message.</p>
<p>e.g.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.pretend_server.org&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">e</span><span class="o">.</span><span class="n">reason</span>   
<span class="gp">...</span>
<span class="go">(4, &#39;getaddrinfo failed&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="httperror">
<h3>HTTPError<a class="headerlink" href="#httperror" title="Permalink to this headline">¶</a></h3>
<p>Every HTTP response from the server contains a numeric “status code”. Sometimes
the status code indicates that the server is unable to fulfil the request. The
default handlers will handle some of these responses for you (for example, if
the response is a “redirection” that requests the client fetch the document from
a different URL, urllib2 will handle that for you). For those it can’t handle,
urlopen will raise an <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code>. Typical errors include ‘404’ (page not
found), ‘403’ (request forbidden), and ‘401’ (authentication required).</p>
<p>See section 10 of RFC 2616 for a reference on all the HTTP error codes.</p>
<p>The <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code> instance raised will have an integer ‘code’ attribute, which
corresponds to the error sent by the server.</p>
<div class="section" id="error-codes">
<h4>Error Codes<a class="headerlink" href="#error-codes" title="Permalink to this headline">¶</a></h4>
<p>Because the default handlers handle redirects (codes in the 300 range), and
codes in the 100–299 range indicate success, you will usually only see error
codes in the 400–599 range.</p>
<p><code class="docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler.responses</span></code> is a useful dictionary of
response codes in that shows all the response codes used by RFC 2616. The
dictionary is reproduced here for convenience</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Table mapping response codes to messages; entries have the</span>
<span class="c1"># form {code: (shortmessage, longmessage)}.</span>
<span class="n">responses</span> <span class="o">=</span> <span class="p">{</span>
    <span class="mi">100</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Continue&#39;</span><span class="p">,</span> <span class="s1">&#39;Request received, please continue&#39;</span><span class="p">),</span>
    <span class="mi">101</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Switching Protocols&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Switching to new protocol; obey Upgrade header&#39;</span><span class="p">),</span>

    <span class="mi">200</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;OK&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled, document follows&#39;</span><span class="p">),</span>
    <span class="mi">201</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Created&#39;</span><span class="p">,</span> <span class="s1">&#39;Document created, URL follows&#39;</span><span class="p">),</span>
    <span class="mi">202</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Accepted&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Request accepted, processing continues off-line&#39;</span><span class="p">),</span>
    <span class="mi">203</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Non-Authoritative Information&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled from cache&#39;</span><span class="p">),</span>
    <span class="mi">204</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;No Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Request fulfilled, nothing follows&#39;</span><span class="p">),</span>
    <span class="mi">205</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Reset Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Clear input form for further input.&#39;</span><span class="p">),</span>
    <span class="mi">206</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Partial Content&#39;</span><span class="p">,</span> <span class="s1">&#39;Partial content follows.&#39;</span><span class="p">),</span>

    <span class="mi">300</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Multiple Choices&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Object has several resources -- see URI list&#39;</span><span class="p">),</span>
    <span class="mi">301</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Moved Permanently&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved permanently -- see URI list&#39;</span><span class="p">),</span>
    <span class="mi">302</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Found&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved temporarily -- see URI list&#39;</span><span class="p">),</span>
    <span class="mi">303</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;See Other&#39;</span><span class="p">,</span> <span class="s1">&#39;Object moved -- see Method and URL list&#39;</span><span class="p">),</span>
    <span class="mi">304</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Modified&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Document has not changed since given time&#39;</span><span class="p">),</span>
    <span class="mi">305</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Use Proxy&#39;</span><span class="p">,</span>
          <span class="s1">&#39;You must use proxy specified in Location to access this &#39;</span>
          <span class="s1">&#39;resource.&#39;</span><span class="p">),</span>
    <span class="mi">307</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Temporary Redirect&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Object moved temporarily -- see URI list&#39;</span><span class="p">),</span>

    <span class="mi">400</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Bad Request&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Bad request syntax or unsupported method&#39;</span><span class="p">),</span>
    <span class="mi">401</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Unauthorized&#39;</span><span class="p">,</span>
          <span class="s1">&#39;No permission -- see authorization schemes&#39;</span><span class="p">),</span>
    <span class="mi">402</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Payment Required&#39;</span><span class="p">,</span>
          <span class="s1">&#39;No payment -- see charging schemes&#39;</span><span class="p">),</span>
    <span class="mi">403</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Forbidden&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Request forbidden -- authorization will not help&#39;</span><span class="p">),</span>
    <span class="mi">404</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Found&#39;</span><span class="p">,</span> <span class="s1">&#39;Nothing matches the given URI&#39;</span><span class="p">),</span>
    <span class="mi">405</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Method Not Allowed&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Specified method is invalid for this server.&#39;</span><span class="p">),</span>
    <span class="mi">406</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Acceptable&#39;</span><span class="p">,</span> <span class="s1">&#39;URI not available in preferred format.&#39;</span><span class="p">),</span>
    <span class="mi">407</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Proxy Authentication Required&#39;</span><span class="p">,</span> <span class="s1">&#39;You must authenticate with &#39;</span>
          <span class="s1">&#39;this proxy before proceeding.&#39;</span><span class="p">),</span>
    <span class="mi">408</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request Timeout&#39;</span><span class="p">,</span> <span class="s1">&#39;Request timed out; try again later.&#39;</span><span class="p">),</span>
    <span class="mi">409</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Conflict&#39;</span><span class="p">,</span> <span class="s1">&#39;Request conflict.&#39;</span><span class="p">),</span>
    <span class="mi">410</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Gone&#39;</span><span class="p">,</span>
          <span class="s1">&#39;URI no longer exists and has been permanently removed.&#39;</span><span class="p">),</span>
    <span class="mi">411</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Length Required&#39;</span><span class="p">,</span> <span class="s1">&#39;Client must specify Content-Length.&#39;</span><span class="p">),</span>
    <span class="mi">412</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Precondition Failed&#39;</span><span class="p">,</span> <span class="s1">&#39;Precondition in headers is false.&#39;</span><span class="p">),</span>
    <span class="mi">413</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request Entity Too Large&#39;</span><span class="p">,</span> <span class="s1">&#39;Entity is too large.&#39;</span><span class="p">),</span>
    <span class="mi">414</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Request-URI Too Long&#39;</span><span class="p">,</span> <span class="s1">&#39;URI is too long.&#39;</span><span class="p">),</span>
    <span class="mi">415</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Unsupported Media Type&#39;</span><span class="p">,</span> <span class="s1">&#39;Entity body in unsupported format.&#39;</span><span class="p">),</span>
    <span class="mi">416</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Requested Range Not Satisfiable&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Cannot satisfy request range.&#39;</span><span class="p">),</span>
    <span class="mi">417</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Expectation Failed&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Expect condition could not be satisfied.&#39;</span><span class="p">),</span>

    <span class="mi">500</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Internal Server Error&#39;</span><span class="p">,</span> <span class="s1">&#39;Server got itself in trouble&#39;</span><span class="p">),</span>
    <span class="mi">501</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Not Implemented&#39;</span><span class="p">,</span>
          <span class="s1">&#39;Server does not support this operation&#39;</span><span class="p">),</span>
    <span class="mi">502</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Bad Gateway&#39;</span><span class="p">,</span> <span class="s1">&#39;Invalid responses from another server/proxy.&#39;</span><span class="p">),</span>
    <span class="mi">503</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Service Unavailable&#39;</span><span class="p">,</span>
          <span class="s1">&#39;The server cannot process the request due to a high load&#39;</span><span class="p">),</span>
    <span class="mi">504</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;Gateway Timeout&#39;</span><span class="p">,</span>
          <span class="s1">&#39;The gateway server did not receive a timely response&#39;</span><span class="p">),</span>
    <span class="mi">505</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;HTTP Version Not Supported&#39;</span><span class="p">,</span> <span class="s1">&#39;Cannot fulfill request.&#39;</span><span class="p">),</span>
    <span class="p">}</span>
</pre></div>
</div>
<p>When an error is raised the server responds by returning an HTTP error code
<em>and</em> an error page. You can use the <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code> instance as a response on the
page returned. This means that as well as the code attribute, it also has read,
geturl, and info, methods.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.python.org/fish.html&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">e</span><span class="o">.</span><span class="n">code</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">e</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> 
<span class="gp">...</span>
<span class="go">404</span>
<span class="go">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;</span>
<span class="go">&quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;</span>
<span class="gp">...</span>
<span class="go">&lt;title&gt;Page Not Found&lt;/title&gt;</span>
<span class="gp">...</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="wrapping-it-up">
<h3>Wrapping it Up<a class="headerlink" href="#wrapping-it-up" title="Permalink to this headline">¶</a></h3>
<p>So if you want to be prepared for <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code> <em>or</em> <code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code> there are two
basic approaches. I prefer the second approach.</p>
<div class="section" id="number-1">
<h4>Number 1<a class="headerlink" href="#number-1" title="Permalink to this headline">¶</a></h4>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">urllib2</span> <span class="k">import</span> <span class="n">Request</span><span class="p">,</span> <span class="n">urlopen</span><span class="p">,</span> <span class="n">URLError</span><span class="p">,</span> <span class="n">HTTPError</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">someurl</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="k">except</span> <span class="n">HTTPError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;The server couldn</span><span class="se">\&#39;</span><span class="s1">t fulfill the request.&#39;</span>
    <span class="nb">print</span> <span class="s1">&#39;Error code: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">code</span>
<span class="k">except</span> <span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;We failed to reach a server.&#39;</span>
    <span class="nb">print</span> <span class="s1">&#39;Reason: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">reason</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># everything is fine</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">HTTPError</span></code> <em>must</em> come first, otherwise <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">URLError</span></code>
will <em>also</em> catch an <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code>.</p>
</div>
</div>
<div class="section" id="number-2">
<h4>Number 2<a class="headerlink" href="#number-2" title="Permalink to this headline">¶</a></h4>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">urllib2</span> <span class="k">import</span> <span class="n">Request</span><span class="p">,</span> <span class="n">urlopen</span><span class="p">,</span> <span class="n">URLError</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">Request</span><span class="p">(</span><span class="n">someurl</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="k">except</span> <span class="n">URLError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="s1">&#39;reason&#39;</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;We failed to reach a server.&#39;</span>
        <span class="nb">print</span> <span class="s1">&#39;Reason: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">reason</span>
    <span class="k">elif</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">e</span><span class="p">,</span> <span class="s1">&#39;code&#39;</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;The server couldn</span><span class="se">\&#39;</span><span class="s1">t fulfill the request.&#39;</span>
        <span class="nb">print</span> <span class="s1">&#39;Error code: &#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">code</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># everything is fine</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="info-and-geturl">
<h2>info and geturl<a class="headerlink" href="#info-and-geturl" title="Permalink to this headline">¶</a></h2>
<p>The response returned by urlopen (or the <code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code> instance) has two useful
methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code>.</p>
<p><strong>geturl</strong> - this returns the real URL of the page fetched. This is useful
because <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> (or the opener object used) may have followed a
redirect. The URL of the page fetched may not be the same as the URL requested.</p>
<p><strong>info</strong> - this returns a dictionary-like object that describes the page
fetched, particularly the headers sent by the server. It is currently an
<code class="docutils literal notranslate"><span class="pre">httplib.HTTPMessage</span></code> instance.</p>
<p>Typical headers include ‘Content-length’, ‘Content-type’, and so on. See the
<a class="reference external" href="https://www.cs.tut.fi/~jkorpela/http.html">Quick Reference to HTTP Headers</a>
for a useful listing of HTTP headers with brief explanations of their meaning
and use.</p>
</div>
<div class="section" id="openers-and-handlers">
<h2>Openers and Handlers<a class="headerlink" href="#openers-and-handlers" title="Permalink to this headline">¶</a></h2>
<p>When you fetch a URL you use an opener (an instance of the perhaps
confusingly-named <a class="reference internal" href="../library/urllib2.html#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">urllib2.OpenerDirector</span></code></a>). Normally we have been using
the default opener - via <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> - but you can create custom
openers. Openers use handlers. All the “heavy lifting” is done by the
handlers. Each handler knows how to open URLs for a particular URL scheme (http,
ftp, etc.), or how to handle an aspect of URL opening, for example HTTP
redirections or HTTP cookies.</p>
<p>You will want to create openers if you want to fetch URLs with specific handlers
installed, for example to get an opener that handles cookies, or to get an
opener that does not handle redirections.</p>
<p>To create an opener, instantiate an <code class="docutils literal notranslate"><span class="pre">OpenerDirector</span></code>, and then call
<code class="docutils literal notranslate"><span class="pre">.add_handler(some_handler_instance)</span></code> repeatedly.</p>
<p>Alternatively, you can use <code class="docutils literal notranslate"><span class="pre">build_opener</span></code>, which is a convenience function for
creating opener objects with a single function call.  <code class="docutils literal notranslate"><span class="pre">build_opener</span></code> adds
several handlers by default, but provides a quick way to add more and/or
override the default handlers.</p>
<p>Other sorts of handlers you might want to can handle proxies, authentication,
and other common but slightly specialised situations.</p>
<p><code class="docutils literal notranslate"><span class="pre">install_opener</span></code> can be used to make an <code class="docutils literal notranslate"><span class="pre">opener</span></code> object the (global) default
opener. This means that calls to <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> will use the opener you have
installed.</p>
<p>Opener objects have an <code class="docutils literal notranslate"><span class="pre">open</span></code> method, which can be called directly to fetch
urls in the same way as the <code class="docutils literal notranslate"><span class="pre">urlopen</span></code> function: there’s no need to call
<code class="docutils literal notranslate"><span class="pre">install_opener</span></code>, except as a convenience.</p>
</div>
<div class="section" id="id6">
<h2>Basic Authentication<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h2>
<p>To illustrate creating and installing a handler we will use the
<code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code>. For a more detailed discussion of this subject –
including an explanation of how Basic Authentication works - see the <a class="reference external" href="http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic
Authentication Tutorial</a>.</p>
<p>When authentication is required, the server sends a header (as well as the 401
error code) requesting authentication.  This specifies the authentication scheme
and a ‘realm’. The header looks like: <code class="docutils literal notranslate"><span class="pre">WWW-Authenticate:</span> <span class="pre">SCHEME</span>
<span class="pre">realm=&quot;REALM&quot;</span></code>.</p>
<p>e.g.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">WWW</span><span class="o">-</span><span class="n">Authenticate</span><span class="p">:</span> <span class="n">Basic</span> <span class="n">realm</span><span class="o">=</span><span class="s2">&quot;cPanel Users&quot;</span>
</pre></div>
</div>
<p>The client should then retry the request with the appropriate name and password
for the realm included as a header in the request. This is ‘basic
authentication’. In order to simplify this process we can create an instance of
<code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> and an opener to use this handler.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> uses an object called a password manager to handle
the mapping of URLs and realms to passwords and usernames. If you know what the
realm is (from the authentication header sent by the server), then you can use a
<code class="docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code>. Frequently one doesn’t care what the realm is. In that
case, it is convenient to use <code class="docutils literal notranslate"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code>. This allows
you to specify a default username and password for a URL. This will be supplied
in the absence of you providing an alternative combination for a specific
realm. We indicate this by providing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the realm argument to the
<code class="docutils literal notranslate"><span class="pre">add_password</span></code> method.</p>
<p>The top-level URL is the first URL that requires authentication. URLs “deeper”
than the URL you pass to .add_password() will also match.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># create a password manager</span>
<span class="n">password_mgr</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPPasswordMgrWithDefaultRealm</span><span class="p">()</span>

<span class="c1"># Add the username and password.</span>
<span class="c1"># If we knew the realm, we could use it instead of None.</span>
<span class="n">top_level_url</span> <span class="o">=</span> <span class="s2">&quot;http://example.com/foo/&quot;</span>
<span class="n">password_mgr</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="n">top_level_url</span><span class="p">,</span> <span class="n">username</span><span class="p">,</span> <span class="n">password</span><span class="p">)</span>

<span class="n">handler</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPBasicAuthHandler</span><span class="p">(</span><span class="n">password_mgr</span><span class="p">)</span>

<span class="c1"># create &quot;opener&quot; (OpenerDirector instance)</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>

<span class="c1"># use the opener to fetch a URL</span>
<span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">a_url</span><span class="p">)</span>

<span class="c1"># Install the opener.</span>
<span class="c1"># Now all calls to urllib2.urlopen use our opener.</span>
<span class="n">urllib2</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In the above example we only supplied our <code class="docutils literal notranslate"><span class="pre">HTTPBasicAuthHandler</span></code> to
<code class="docutils literal notranslate"><span class="pre">build_opener</span></code>. By default openers have the handlers for normal situations
– <code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code> (if a proxy setting such as an <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">http_proxy</span></code>
environment variable is set), <code class="docutils literal notranslate"><span class="pre">UnknownHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPHandler</span></code>,
<code class="docutils literal notranslate"><span class="pre">HTTPDefaultErrorHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPRedirectHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">FTPHandler</span></code>,
<code class="docutils literal notranslate"><span class="pre">FileHandler</span></code>, <code class="docutils literal notranslate"><span class="pre">HTTPErrorProcessor</span></code>.</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">top_level_url</span></code> is in fact <em>either</em> a full URL (including the ‘http:’ scheme
component and the hostname and optionally the port number)
e.g. <code class="docutils literal notranslate"><span class="pre">&quot;http://example.com/&quot;</span></code> <em>or</em> an “authority” (i.e. the hostname,
optionally including the port number) e.g. <code class="docutils literal notranslate"><span class="pre">&quot;example.com&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;example.com:8080&quot;</span></code>
(the latter example includes a port number).  The authority, if present, must
NOT contain the “userinfo” component - for example <code class="docutils literal notranslate"><span class="pre">&quot;joe:password&#64;example.com&quot;</span></code> is
not correct.</p>
</div>
<div class="section" id="proxies">
<h2>Proxies<a class="headerlink" href="#proxies" title="Permalink to this headline">¶</a></h2>
<p><strong>urllib2</strong> will auto-detect your proxy settings and use those. This is through
the <code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code>, which is part of the normal handler chain when a proxy
setting is detected.  Normally that’s a good thing, but there are occasions
when it may not be helpful <a class="footnote-reference" href="#id14" id="id7">[6]</a>. One way to do this is to setup our own
<code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code>, with no proxies defined. This is done using similar steps to
setting up a <a class="reference external" href="http://www.voidspace.org.uk/python/articles/authentication.shtml">Basic Authentication</a> handler:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">proxy_support</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">ProxyHandler</span><span class="p">({})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">proxy_support</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urllib2</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Currently <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> <em>does not</em> support fetching of <code class="docutils literal notranslate"><span class="pre">https</span></code> locations
through a proxy.  However, this can be enabled by extending urllib2 as
shown in the recipe <a class="footnote-reference" href="#id15" id="id8">[7]</a>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">HTTP_PROXY</span></code> will be ignored if a variable <code class="docutils literal notranslate"><span class="pre">REQUEST_METHOD</span></code> is set; see
the documentation on <a class="reference internal" href="../library/urllib.html#urllib.getproxies" title="urllib.getproxies"><code class="xref py py-func docutils literal notranslate"><span class="pre">getproxies()</span></code></a>.</p>
</div>
</div>
<div class="section" id="sockets-and-layers">
<h2>Sockets and Layers<a class="headerlink" href="#sockets-and-layers" title="Permalink to this headline">¶</a></h2>
<p>The Python support for fetching resources from the web is layered. urllib2 uses
the httplib library, which in turn uses the socket library.</p>
<p>As of Python 2.3 you can specify how long a socket should wait for a response
before timing out. This can be useful in applications which have to fetch web
pages. By default the socket module has <em>no timeout</em> and can hang. Currently,
the socket timeout is not exposed at the httplib or urllib2 levels.  However,
you can set the default timeout globally for all sockets using</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">urllib2</span>

<span class="c1"># timeout in seconds</span>
<span class="n">timeout</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">socket</span><span class="o">.</span><span class="n">setdefaulttimeout</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>

<span class="c1"># this call to urllib2.urlopen now uses the default timeout</span>
<span class="c1"># we have set in the socket module</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.voidspace.org.uk&#39;</span><span class="p">)</span>
<span class="n">response</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
</pre></div>
</div>
</div>
<hr class="docutils" />
<div class="section" id="footnotes">
<h2>Footnotes<a class="headerlink" href="#footnotes" title="Permalink to this headline">¶</a></h2>
<p>This document was reviewed and revised by John Lee.</p>
<table class="docutils footnote" frame="void" id="id9" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>For an introduction to the CGI protocol see
<a class="reference external" href="http://www.pyzine.com/Issue008/Section_Articles/article_CGIOne.html">Writing Web Applications in Python</a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id10" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Google for example.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id11" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>Browser sniffing is a very bad practice for website design - building
sites using web standards is much more sensible. Unfortunately a lot of
sites still send different versions to different browsers.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id12" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[4]</a></td><td>The user agent for MSIE 6 is
<em>‘Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)’</em></td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id13" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id5">[5]</a></td><td>For details of more HTTP request headers, see
<a class="reference external" href="https://www.cs.tut.fi/~jkorpela/http.html">Quick Reference to HTTP Headers</a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id14" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id7">[6]</a></td><td>In my case I have to use a proxy to access the internet at work. If you
attempt to fetch <em>localhost</em> URLs through this proxy it blocks them. IE
is set to use the proxy, which urllib2 picks up on. In order to test
scripts with a localhost server, I have to prevent urllib2 from using
the proxy.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id15" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id8">[7]</a></td><td>urllib2 opener for SSL proxy (CONNECT method): <a class="reference external" href="https://code.activestate.com/recipes/456195/">ASPN Cookbook Recipe</a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">HOWTO Fetch Internet Resources Using urllib2</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#fetching-urls">Fetching URLs</a><ul>
<li><a class="reference internal" href="#data">Data</a></li>
<li><a class="reference internal" href="#headers">Headers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#handling-exceptions">Handling Exceptions</a><ul>
<li><a class="reference internal" href="#urlerror">URLError</a></li>
<li><a class="reference internal" href="#httperror">HTTPError</a><ul>
<li><a class="reference internal" href="#error-codes">Error Codes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#wrapping-it-up">Wrapping it Up</a><ul>
<li><a class="reference internal" href="#number-1">Number 1</a></li>
<li><a class="reference internal" href="#number-2">Number 2</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#info-and-geturl">info and geturl</a></li>
<li><a class="reference internal" href="#openers-and-handlers">Openers and Handlers</a></li>
<li><a class="reference internal" href="#id6">Basic Authentication</a></li>
<li><a class="reference internal" href="#proxies">Proxies</a></li>
<li><a class="reference internal" href="#sockets-and-layers">Sockets and Layers</a></li>
<li><a class="reference internal" href="#footnotes">Footnotes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="unicode.html"
                        title="previous chapter">Unicode HOWTO</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="webservers.html"
                        title="next chapter">HOWTO Use Python in the web</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/urllib2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webservers.html" title="HOWTO Use Python in the web"
             >next</a> |</li>
        <li class="right" >
          <a href="unicode.html" title="Unicode HOWTO"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\;�����html/howto/webservers.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>HOWTO Use Python in the web &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Argparse Tutorial" href="argparse.html" />
    <link rel="prev" title="HOWTO Fetch Internet Resources Using urllib2" href="urllib2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/howto/webservers.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="Argparse Tutorial"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="HOWTO Fetch Internet Resources Using urllib2"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="howto-use-python-in-the-web">
<h1>HOWTO Use Python in the web<a class="headerlink" href="#howto-use-python-in-the-web" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Marek Kubica</td>
</tr>
</tbody>
</table>
<div class="topic">
<p class="topic-title first">Abstract</p>
<p>This document shows how Python fits into the web.  It presents some ways
to integrate Python with a web server, and general practices useful for
developing web sites.</p>
</div>
<p>Programming for the Web has become a hot topic since the rise of “Web 2.0”,
which focuses on user-generated content on web sites.  It has always been
possible to use Python for creating web sites, but it was a rather tedious task.
Therefore, many frameworks and helper tools have been created to assist
developers in creating faster and more robust sites.  This HOWTO describes
some of the methods used to combine Python with a web server to create
dynamic content.  It is not meant as a complete introduction, as this topic is
far too broad to be covered in one single document.  However, a short overview
of the most popular libraries is provided.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">While this HOWTO tries to give an overview of Python in the web, it cannot
always be as up to date as desired.  Web development in Python is rapidly
moving forward, so the wiki page on <a class="reference external" href="https://wiki.python.org/moin/WebProgramming">Web Programming</a> may be more in sync with
recent development.</p>
</div>
<div class="section" id="the-low-level-view">
<h2>The Low-Level View<a class="headerlink" href="#the-low-level-view" title="Permalink to this headline">¶</a></h2>
<p>When a user enters a web site, their browser makes a connection to the site’s
web server (this is called the <em>request</em>).  The server looks up the file in the
file system and sends it back to the user’s browser, which displays it (this is
the <em>response</em>).  This is roughly how the underlying protocol, HTTP, works.</p>
<p>Dynamic web sites are not based on files in the file system, but rather on
programs which are run by the web server when a request comes in, and which
<em>generate</em> the content that is returned to the user.  They can do all sorts of
useful things, like display the postings of a bulletin board, show your email,
configure software, or just display the current time.  These programs can be
written in any programming language the server supports.  Since most servers
support Python, it is easy to use Python to create dynamic web sites.</p>
<p>Most HTTP servers are written in C or C++, so they cannot execute Python code
directly – a bridge is needed between the server and the program.  These
bridges, or rather interfaces, define how programs interact with the server.
There have been numerous attempts to create the best possible interface, but
there are only a few worth mentioning.</p>
<p>Not every web server supports every interface.  Many web servers only support
old, now-obsolete interfaces; however, they can often be extended using
third-party modules to support newer ones.</p>
<div class="section" id="common-gateway-interface">
<h3>Common Gateway Interface<a class="headerlink" href="#common-gateway-interface" title="Permalink to this headline">¶</a></h3>
<p>This interface, most commonly referred to as “CGI”, is the oldest, and is
supported by nearly every web server out of the box.  Programs using CGI to
communicate with their web server need to be started by the server for every
request.  So, every request starts a new Python interpreter – which takes some
time to start up – thus making the whole interface only usable for low load
situations.</p>
<p>The upside of CGI is that it is simple – writing a Python program which uses
CGI is a matter of about three lines of code.  This simplicity comes at a
price: it does very few things to help the developer.</p>
<p>Writing CGI programs, while still possible, is no longer recommended.  With
<a class="reference internal" href="#wsgi"><span class="std std-ref">WSGI</span></a>, a topic covered later in this document, it is possible to write
programs that emulate CGI, so they can be run as CGI if no better option is
available.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>The Python standard library includes some modules that are helpful for
creating plain CGI programs:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> – Handling of user input in CGI scripts</li>
<li><a class="reference internal" href="../library/cgitb.html#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> – Displays nice tracebacks when errors happen in CGI
applications, instead of presenting a “500 Internal Server Error” message</li>
</ul>
<p class="last">The Python wiki features a page on <a class="reference external" href="https://wiki.python.org/moin/CgiScripts">CGI scripts</a> with some additional information
about CGI in Python.</p>
</div>
<div class="section" id="simple-script-for-testing-cgi">
<h4>Simple script for testing CGI<a class="headerlink" href="#simple-script-for-testing-cgi" title="Permalink to this headline">¶</a></h4>
<p>To test whether your web server works with CGI, you can use this short and
simple CGI program:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: UTF-8 -*-</span>

<span class="c1"># enable debugging</span>
<span class="kn">import</span> <span class="nn">cgitb</span>
<span class="n">cgitb</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>

<span class="nb">print</span> <span class="s2">&quot;Content-Type: text/plain;charset=utf-8&quot;</span>
<span class="nb">print</span>

<span class="nb">print</span> <span class="s2">&quot;Hello World!&quot;</span>
</pre></div>
</div>
<p>Depending on your web server configuration, you may need to save this code with
a <code class="docutils literal notranslate"><span class="pre">.py</span></code> or <code class="docutils literal notranslate"><span class="pre">.cgi</span></code> extension.  Additionally, this file may also need to be
in a <code class="docutils literal notranslate"><span class="pre">cgi-bin</span></code> folder, for security reasons.</p>
<p>You might wonder what the <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> line is about.  This line makes it possible
to display a nice traceback instead of just crashing and displaying an “Internal
Server Error” in the user’s browser.  This is useful for debugging, but it might
risk exposing some confidential data to the user.  You should not use <code class="docutils literal notranslate"><span class="pre">cgitb</span></code>
in production code for this reason.  You should <em>always</em> catch exceptions, and
display proper error pages – end-users don’t like to see nondescript “Internal
Server Errors” in their browsers.</p>
</div>
<div class="section" id="setting-up-cgi-on-your-own-server">
<h4>Setting up CGI on your own server<a class="headerlink" href="#setting-up-cgi-on-your-own-server" title="Permalink to this headline">¶</a></h4>
<p>If you don’t have your own web server, this does not apply to you.  You can
check whether it works as-is, and if not you will need to talk to the
administrator of your web server. If it is a big host, you can try filing a
ticket asking for Python support.</p>
<p>If you are your own administrator or want to set up CGI for testing purposes on
your own computers, you have to configure it by yourself.  There is no single
way to configure CGI, as there are many web servers with different
configuration options.  Currently the most widely used free web server is
<a class="reference external" href="http://httpd.apache.org/">Apache HTTPd</a>, or Apache for short. Apache can be
easily installed on nearly every system using the system’s package management
tool.  <a class="reference external" href="http://www.lighttpd.net">lighttpd</a> is another alternative and is
said to have better performance.  On many systems this server can also be
installed using the package management tool, so manually compiling the web
server may not be needed.</p>
<ul class="simple">
<li>On Apache you can take a look at the <a class="reference external" href="http://httpd.apache.org/docs/2.2/howto/cgi.html">Dynamic Content with CGI</a> tutorial, where everything
is described.  Most of the time it is enough just to set <code class="docutils literal notranslate"><span class="pre">+ExecCGI</span></code>.  The
tutorial also describes the most common gotchas that might arise.</li>
<li>On lighttpd you need to use the <a class="reference external" href="http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModCGI">CGI module</a>, which can be configured
in a straightforward way.  It boils down to setting <code class="docutils literal notranslate"><span class="pre">cgi.assign</span></code> properly.</li>
</ul>
</div>
<div class="section" id="common-problems-with-cgi-scripts">
<h4>Common problems with CGI scripts<a class="headerlink" href="#common-problems-with-cgi-scripts" title="Permalink to this headline">¶</a></h4>
<p>Using CGI sometimes leads to small annoyances while trying to get these
scripts to run.  Sometimes a seemingly correct script does not work as
expected, the cause being some small hidden problem that’s difficult to spot.</p>
<p>Some of these potential problems are:</p>
<ul class="simple">
<li>The Python script is not marked as executable.  When CGI scripts are not
executable most web servers will let the user download it, instead of
running it and sending the output to the user.  For CGI scripts to run
properly on Unix-like operating systems, the <code class="docutils literal notranslate"><span class="pre">+x</span></code> bit needs to be set.
Using <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">a+x</span> <span class="pre">your_script.py</span></code> may solve this problem.</li>
<li>On a Unix-like system, The line endings in the program file must be Unix
style line endings.  This is important because the web server checks the
first line of the script (called shebang) and tries to run the program
specified there.  It gets easily confused by Windows line endings (Carriage
Return &amp; Line Feed, also called CRLF), so you have to convert the file to
Unix line endings (only Line Feed, LF).  This can be done automatically by
uploading the file via FTP in text mode instead of binary mode, but the
preferred way is just telling your editor to save the files with Unix line
endings.  Most editors support this.</li>
<li>Your web server must be able to read the file, and you need to make sure the
permissions are correct.  On unix-like systems, the server often runs as user
and group <code class="docutils literal notranslate"><span class="pre">www-data</span></code>, so it might be worth a try to change the file
ownership, or making the file world readable by using <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">a+r</span>
<span class="pre">your_script.py</span></code>.</li>
<li>The web server must know that the file you’re trying to access is a CGI script.
Check the configuration of your web server, as it may be configured
to expect a specific file extension for CGI scripts.</li>
<li>On Unix-like systems, the path to the interpreter in the shebang
(<code class="docutils literal notranslate"><span class="pre">#!/usr/bin/env</span> <span class="pre">python</span></code>) must be correct.  This line calls
<code class="docutils literal notranslate"><span class="pre">/usr/bin/env</span></code> to find Python, but it will fail if there is no
<code class="docutils literal notranslate"><span class="pre">/usr/bin/env</span></code>, or if Python is not in the web server’s path.  If you know
where your Python is installed, you can also use that full path.  The
commands <code class="docutils literal notranslate"><span class="pre">whereis</span> <span class="pre">python</span></code> and <code class="docutils literal notranslate"><span class="pre">type</span> <span class="pre">-p</span> <span class="pre">python</span></code> could help you find
where it is installed.  Once you know the path, you can change the shebang
accordingly: <code class="docutils literal notranslate"><span class="pre">#!/usr/bin/python</span></code>.</li>
<li>The file must not contain a BOM (Byte Order Mark). The BOM is meant for
determining the byte order of UTF-16 and UTF-32 encodings, but some editors
write this also into UTF-8 files.  The BOM interferes with the shebang line,
so be sure to tell your editor not to write the BOM.</li>
<li>If the web server is using <a class="reference internal" href="#mod-python"><span class="std std-ref">mod_python</span></a>, <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> may be having
problems.  <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> is able to handle CGI scripts by itself, but it can
also be a source of issues.</li>
</ul>
</div>
</div>
<div class="section" id="mod-python">
<span id="id1"></span><h3>mod_python<a class="headerlink" href="#mod-python" title="Permalink to this headline">¶</a></h3>
<p>People coming from PHP often find it hard to grasp how to use Python in the web.
Their first thought is mostly <a class="reference external" href="http://modpython.org/">mod_python</a>,
because they think that this is the equivalent to <code class="docutils literal notranslate"><span class="pre">mod_php</span></code>.  Actually, there
are many differences.  What <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> does is embed the interpreter into
the Apache process, thus speeding up requests by not having to start a Python
interpreter for each request.  On the other hand, it is not “Python intermixed
with HTML” in the way that PHP is often intermixed with HTML. The Python
equivalent of that is a template engine.  <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> itself is much more
powerful and provides more access to Apache internals.  It can emulate CGI,
work in a “Python Server Pages” mode (similar to JSP) which is “HTML
intermingled with Python”, and it has a “Publisher” which designates one file
to accept all requests and decide what to do with them.</p>
<p><code class="docutils literal notranslate"><span class="pre">mod_python</span></code> does have some problems.  Unlike the PHP interpreter, the Python
interpreter uses caching when executing files, so changes to a file will
require the web server to be restarted.  Another problem is the basic concept
– Apache starts child processes to handle the requests, and unfortunately
every child process needs to load the whole Python interpreter even if it does
not use it.  This makes the whole web server slower.  Another problem is that,
because <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> is linked against a specific version of <code class="docutils literal notranslate"><span class="pre">libpython</span></code>,
it is not possible to switch from an older version to a newer (e.g. 2.4 to 2.5)
without recompiling <code class="docutils literal notranslate"><span class="pre">mod_python</span></code>.  <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> is also bound to the Apache
web server, so programs written for <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> cannot easily run on other
web servers.</p>
<p>These are the reasons why <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> should be avoided when writing new
programs.  In some circumstances it still might be a good idea to use
<code class="docutils literal notranslate"><span class="pre">mod_python</span></code> for deployment, but WSGI makes it possible to run WSGI programs
under <code class="docutils literal notranslate"><span class="pre">mod_python</span></code> as well.</p>
</div>
<div class="section" id="fastcgi-and-scgi">
<h3>FastCGI and SCGI<a class="headerlink" href="#fastcgi-and-scgi" title="Permalink to this headline">¶</a></h3>
<p>FastCGI and SCGI try to solve the performance problem of CGI in another way.
Instead of embedding the interpreter into the web server, they create
long-running background processes. There is still a module in the web server
which makes it possible for the web server to “speak” with the background
process.  As the background process is independent of the server, it can be
written in any language, including Python.  The language just needs to have a
library which handles the communication with the webserver.</p>
<p>The difference between FastCGI and SCGI is very small, as SCGI is essentially
just a “simpler FastCGI”.  As the web server support for SCGI is limited,
most people use FastCGI instead, which works the same way.  Almost everything
that applies to SCGI also applies to FastCGI as well, so we’ll only cover
the latter.</p>
<p>These days, FastCGI is never used directly.  Just like <code class="docutils literal notranslate"><span class="pre">mod_python</span></code>, it is only
used for the deployment of WSGI applications.</p>
<div class="section" id="setting-up-fastcgi">
<h4>Setting up FastCGI<a class="headerlink" href="#setting-up-fastcgi" title="Permalink to this headline">¶</a></h4>
<p>Each web server requires a specific module.</p>
<ul class="simple">
<li>Apache has both <a class="reference external" href="http://www.fastcgi.com/drupal/">mod_fastcgi</a> and <a class="reference external" href="https://httpd.apache.org/mod_fcgid/">mod_fcgid</a>.  <code class="docutils literal notranslate"><span class="pre">mod_fastcgi</span></code> is the original one, but it
has some licensing issues, which is why it is sometimes considered non-free.
<code class="docutils literal notranslate"><span class="pre">mod_fcgid</span></code> is a smaller, compatible alternative.  One of these modules needs
to be loaded by Apache.</li>
<li>lighttpd ships its own <a class="reference external" href="http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModFastCGI">FastCGI module</a> as well as an
<a class="reference external" href="http://redmine.lighttpd.net/projects/lighttpd/wiki/Docs_ModSCGI">SCGI module</a>.</li>
<li><a class="reference external" href="http://nginx.org/">nginx</a> also supports <a class="reference external" href="https://www.nginx.com/resources/wiki/start/topics/examples/simplepythonfcgi/">FastCGI</a>.</li>
</ul>
<p>Once you have installed and configured the module, you can test it with the
following WSGI-application:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: UTF-8 -*-</span>

<span class="kn">from</span> <span class="nn">cgi</span> <span class="k">import</span> <span class="n">escape</span>
<span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">flup.server.fcgi</span> <span class="k">import</span> <span class="n">WSGIServer</span>

<span class="k">def</span> <span class="nf">app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">start_response</span><span class="p">(</span><span class="s1">&#39;200 OK&#39;</span><span class="p">,</span> <span class="p">[(</span><span class="s1">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s1">&#39;text/html&#39;</span><span class="p">)])</span>

    <span class="k">yield</span> <span class="s1">&#39;&lt;h1&gt;FastCGI Environment&lt;/h1&gt;&#39;</span>
    <span class="k">yield</span> <span class="s1">&#39;&lt;table&gt;&#39;</span>
    <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">environ</span><span class="o">.</span><span class="n">items</span><span class="p">()):</span>
        <span class="k">yield</span> <span class="s1">&#39;&lt;tr&gt;&lt;th&gt;</span><span class="si">%s</span><span class="s1">&lt;/th&gt;&lt;td&gt;</span><span class="si">%s</span><span class="s1">&lt;/td&gt;&lt;/tr&gt;&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">escape</span><span class="p">(</span><span class="n">k</span><span class="p">),</span> <span class="n">escape</span><span class="p">(</span><span class="n">v</span><span class="p">))</span>
    <span class="k">yield</span> <span class="s1">&#39;&lt;/table&gt;&#39;</span>

<span class="n">WSGIServer</span><span class="p">(</span><span class="n">app</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
</pre></div>
</div>
<p>This is a simple WSGI application, but you need to install <a class="reference external" href="https://pypi.org/project/flup/1.0">flup</a> first, as flup handles the low level
FastCGI access.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">There is some documentation on <a class="reference external" href="https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/">setting up Django with WSGI</a>, most of
which can be reused for other WSGI-compliant frameworks and libraries.
Only the <code class="docutils literal notranslate"><span class="pre">manage.py</span></code> part has to be changed, the example used here can be
used instead.  Django does more or less the exact same thing.</p>
</div>
</div>
</div>
<div class="section" id="mod-wsgi">
<h3>mod_wsgi<a class="headerlink" href="#mod-wsgi" title="Permalink to this headline">¶</a></h3>
<p><a class="reference external" href="http://code.google.com/p/modwsgi/">mod_wsgi</a> is an attempt to get rid of the
low level gateways.  Given that FastCGI, SCGI, and mod_python are mostly used to
deploy WSGI applications, mod_wsgi was started to directly embed WSGI applications
into the Apache web server. mod_wsgi is specifically designed to host WSGI
applications.  It makes the deployment of WSGI applications much easier than
deployment using other low level methods, which need glue code.  The downside
is that mod_wsgi is limited to the Apache web server; other servers would need
their own implementations of mod_wsgi.</p>
<p>mod_wsgi supports two modes: embedded mode, in which it integrates with the
Apache process, and daemon mode, which is more FastCGI-like.  Unlike FastCGI,
mod_wsgi handles the worker-processes by itself, which makes administration
easier.</p>
</div>
</div>
<div class="section" id="step-back-wsgi">
<span id="wsgi"></span><h2>Step back: WSGI<a class="headerlink" href="#step-back-wsgi" title="Permalink to this headline">¶</a></h2>
<p>WSGI has already been mentioned several times, so it has to be something
important.  In fact it really is, and now it is time to explain it.</p>
<p>The <em>Web Server Gateway Interface</em>,  or WSGI for short, is defined in
<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> and is currently the best way to do Python web programming.  While
it is great for programmers writing frameworks, a normal web developer does not
need to get in direct contact with it.  When choosing a framework for web
development it is a good idea to choose one which supports WSGI.</p>
<p>The big benefit of WSGI is the unification of the application programming
interface.  When your program is compatible with WSGI – which at the outer
level means that the framework you are using has support for WSGI – your
program can be deployed via any web server interface for which there are WSGI
wrappers.  You do not need to care about whether the application user uses
mod_python or FastCGI or mod_wsgi – with WSGI your application will work on
any gateway interface.  The Python standard library contains its own WSGI
server, <a class="reference internal" href="../library/wsgiref.html#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a>, which is a small web server that can be used for
testing.</p>
<p>A really great WSGI feature is middleware.  Middleware is a layer around your
program which can add various functionality to it.  There is quite a bit of
<a class="reference external" href="https://wsgi.readthedocs.org/en/latest/libraries.html">middleware</a> already
available.  For example, instead of writing your own session management (HTTP
is a stateless protocol, so to associate multiple HTTP requests with a single
user your application must create and manage such state via a session), you can
just download middleware which does that, plug it in, and get on with coding
the unique parts of your application.  The same thing with compression – there
is existing middleware which handles compressing your HTML using gzip to save
on your server’s bandwidth.  Authentication is another problem that is easily
solved using existing middleware.</p>
<p>Although WSGI may seem complex, the initial phase of learning can be very
rewarding because WSGI and the associated middleware already have solutions to
many problems that might arise while developing web sites.</p>
<div class="section" id="wsgi-servers">
<h3>WSGI Servers<a class="headerlink" href="#wsgi-servers" title="Permalink to this headline">¶</a></h3>
<p>The code that is used to connect to various low level gateways like CGI or
mod_python is called a <em>WSGI server</em>.  One of these servers is <code class="docutils literal notranslate"><span class="pre">flup</span></code>, which
supports FastCGI and SCGI, as well as <a class="reference external" href="https://en.wikipedia.org/wiki/Apache_JServ_Protocol">AJP</a>.  Some of these servers
are written in Python, as <code class="docutils literal notranslate"><span class="pre">flup</span></code> is, but there also exist others which are
written in C and can be used as drop-in replacements.</p>
<p>There are many servers already available, so a Python web application
can be deployed nearly anywhere.  This is one big advantage that Python has
compared with other web technologies.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>A good overview of WSGI-related code can be found in the <a class="reference external" href="https://wsgi.readthedocs.org/">WSGI homepage</a>, which contains an extensive list of <a class="reference external" href="https://wsgi.readthedocs.org/en/latest/servers.html">WSGI servers</a> which can be used by <em>any</em> application
supporting WSGI.</p>
<p>You might be interested in some WSGI-supporting modules already contained in
the standard library, namely:</p>
<ul class="last simple">
<li><a class="reference internal" href="../library/wsgiref.html#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a> – some tiny utilities and servers for WSGI</li>
</ul>
</div>
</div>
<div class="section" id="case-study-moinmoin">
<h3>Case study: MoinMoin<a class="headerlink" href="#case-study-moinmoin" title="Permalink to this headline">¶</a></h3>
<p>What does WSGI give the web application developer?  Let’s take a look at
an application that’s been around for a while, which was written in
Python without using WSGI.</p>
<p>One of the most widely used wiki software packages is <a class="reference external" href="https://moinmo.in/">MoinMoin</a>.  It was created in 2000, so it predates WSGI by about
three years.  Older versions needed separate code to run on CGI, mod_python,
FastCGI and standalone.</p>
<p>It now includes support for WSGI.  Using WSGI, it is possible to deploy
MoinMoin on any WSGI compliant server, with no additional glue code.
Unlike the pre-WSGI versions, this could include WSGI servers that the
authors of MoinMoin know nothing about.</p>
</div>
</div>
<div class="section" id="model-view-controller">
<h2>Model-View-Controller<a class="headerlink" href="#model-view-controller" title="Permalink to this headline">¶</a></h2>
<p>The term <em>MVC</em> is often encountered in statements such as “framework <em>foo</em>
supports MVC”.  MVC is more about the overall organization of code, rather than
any particular API.  Many web frameworks use this model to help the developer
bring structure to their program.  Bigger web applications can have lots of
code, so it is a good idea to have an effective structure right from the beginning.
That way, even users of other frameworks (or even other languages, since MVC is
not Python-specific) can easily understand the code, given that they are
already familiar with the MVC structure.</p>
<p>MVC stands for three components:</p>
<ul class="simple">
<li>The <em>model</em>.  This is the data that will be displayed and modified.  In
Python frameworks, this component is often represented by the classes used by
an object-relational mapper.</li>
<li>The <em>view</em>.  This component’s job is to display the data of the model to the
user.  Typically this component is implemented via templates.</li>
<li>The <em>controller</em>.  This is the layer between the user and the model.  The
controller reacts to user actions (like opening some specific URL), tells
the model to modify the data if necessary, and tells the view code what to
display,</li>
</ul>
<p>While one might think that MVC is a complex design pattern, in fact it is not.
It is used in Python because it has turned out to be useful for creating clean,
maintainable web sites.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While not all Python frameworks explicitly support MVC, it is often trivial
to create a web site which uses the MVC pattern by separating the data logic
(the model) from the user interaction logic (the controller) and the
templates (the view).  That’s why it is important not to write unnecessary
Python code in the templates – it works against the MVC model and creates
chaos in the code base, making it harder to understand and modify.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The English Wikipedia has an article about the <a class="reference external" href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">Model-View-Controller pattern</a>.  It includes a long
list of web frameworks for various programming languages.</p>
</div>
</div>
<div class="section" id="ingredients-for-websites">
<h2>Ingredients for Websites<a class="headerlink" href="#ingredients-for-websites" title="Permalink to this headline">¶</a></h2>
<p>Websites are complex constructs, so tools have been created to help web
developers make their code easier to write and more maintainable.  Tools like
these exist for all web frameworks in all languages.  Developers are not forced
to use these tools, and often there is no “best” tool.  It is worth learning
about the available tools because they can greatly simplify the process of
developing a web site.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">There are far more components than can be presented here.  The Python wiki
has a page about these components, called
<a class="reference external" href="https://wiki.python.org/moin/WebComponents">Web Components</a>.</p>
</div>
<div class="section" id="templates">
<h3>Templates<a class="headerlink" href="#templates" title="Permalink to this headline">¶</a></h3>
<p>Mixing of HTML and Python code is made possible by a few libraries.  While
convenient at first, it leads to horribly unmaintainable code.  That’s why
templates exist.  Templates are, in the simplest case, just HTML files with
placeholders.  The HTML is sent to the user’s browser after filling in the
placeholders.</p>
<p>Python already includes two ways to build simple templates:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">template</span> <span class="o">=</span> <span class="s2">&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello </span><span class="si">%s</span><span class="s2">!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">template</span> <span class="o">%</span> <span class="s2">&quot;Reader&quot;</span>
<span class="go">&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello Reader!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">string</span> <span class="k">import</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">template</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s2">&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello $</span><span class="si">{name}</span><span class="s2">&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">template</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;Dinsdale&#39;</span><span class="p">))</span>
<span class="go">&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello Dinsdale!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;</span>
</pre></div>
</div>
<p>To generate complex HTML based on non-trivial model data, conditional
and looping constructs like Python’s <em>for</em> and <em>if</em> are generally needed.
<em>Template engines</em> support templates of this complexity.</p>
<p>There are a lot of template engines available for Python which can be used with
or without a <a class="reference internal" href="#framework">framework</a>.  Some of these define a plain-text programming
language which is easy to learn, partly because it is limited in scope.
Others use XML, and the template output is guaranteed to be always be valid
XML.  There are many other variations.</p>
<p>Some <a class="reference internal" href="#frameworks">frameworks</a> ship their own template engine or recommend one in
particular.  In the absence of a reason to use a different template engine,
using the one provided by or recommended by the framework is a good idea.</p>
<p>Popular template engines include:</p>
<blockquote>
<div><ul class="simple">
<li><a class="reference external" href="http://www.makotemplates.org/">Mako</a></li>
<li><a class="reference external" href="http://genshi.edgewall.org/">Genshi</a></li>
<li><a class="reference external" href="http://jinja.pocoo.org/">Jinja</a></li>
</ul>
</div></blockquote>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">There are many template engines competing for attention, because it is
pretty easy to create them in Python.  The page <a class="reference external" href="https://wiki.python.org/moin/Templating">Templating</a> in the wiki lists a big,
ever-growing number of these.  The three listed above are considered “second
generation” template engines and are a good place to start.</p>
</div>
</div>
<div class="section" id="data-persistence">
<h3>Data persistence<a class="headerlink" href="#data-persistence" title="Permalink to this headline">¶</a></h3>
<p><em>Data persistence</em>, while sounding very complicated, is just about storing data.
This data might be the text of blog entries, the postings on a bulletin board or
the text of a wiki page.  There are, of course, a number of different ways to store
information on a web server.</p>
<p>Often, relational database engines like <a class="reference external" href="http://www.mysql.com/">MySQL</a> or
<a class="reference external" href="http://www.postgresql.org/">PostgreSQL</a> are used because of their good
performance when handling very large databases consisting of millions of
entries.  There is also a small database engine called <a class="reference external" href="http://www.sqlite.org/">SQLite</a>, which is bundled with Python in the <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a>
module, and which uses only one file.  It has no other dependencies.  For
smaller sites SQLite is just enough.</p>
<p>Relational databases are <em>queried</em> using a language called <a class="reference external" href="https://en.wikipedia.org/wiki/SQL">SQL</a>.  Python programmers in general do not
like SQL too much, as they prefer to work with objects.  It is possible to save
Python objects into a database using a technology called <a class="reference external" href="https://en.wikipedia.org/wiki/Object-relational_mapping">ORM</a> (Object Relational
Mapping).  ORM translates all object-oriented access into SQL code under the
hood, so the developer does not need to think about it.  Most <a class="reference internal" href="#frameworks">frameworks</a> use
ORMs, and it works quite well.</p>
<p>A second possibility is storing data in normal, plain text files (some
times called “flat files”).  This is very easy for simple sites,
but can be difficult to get right if the web site is performing many
updates to the stored data.</p>
<p>A third possibility are object oriented databases (also called “object
databases”).  These databases store the object data in a form that closely
parallels the way the objects are structured in memory during program
execution.  (By contrast, ORMs store the object data as rows of data in tables
and relations between those rows.)  Storing the objects directly has the
advantage that nearly all objects can be saved in a straightforward way, unlike
in relational databases where some objects are very hard to represent.</p>
<p><a class="reference internal" href="#frameworks">Frameworks</a> often give hints on which data storage method to choose.  It is
usually a good idea to stick to the data store recommended by the framework
unless the application has special requirements better satisfied by an
alternate storage mechanism.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li><a class="reference external" href="https://wiki.python.org/moin/PersistenceTools">Persistence Tools</a> lists
possibilities on how to save data in the file system.  Some of these
modules are part of the standard library</li>
<li><a class="reference external" href="https://wiki.python.org/moin/DatabaseProgramming">Database Programming</a>
helps with choosing a method for saving data</li>
<li><a class="reference external" href="http://www.sqlalchemy.org/">SQLAlchemy</a>, the most powerful OR-Mapper
for Python, and <a class="reference external" href="https://pypi.org/project/Elixir">Elixir</a>, which makes
SQLAlchemy easier to use</li>
<li><a class="reference external" href="http://www.sqlobject.org/">SQLObject</a>, another popular OR-Mapper</li>
<li><a class="reference external" href="https://launchpad.net/zodb">ZODB</a> and <a class="reference external" href="https://www.mems-exchange.org/software/">Durus</a>, two object oriented
databases</li>
</ul>
</div>
</div>
</div>
<div class="section" id="frameworks">
<span id="framework"></span><h2>Frameworks<a class="headerlink" href="#frameworks" title="Permalink to this headline">¶</a></h2>
<p>The process of creating code to run web sites involves writing code to provide
various services.  The code to provide a particular service often works the
same way regardless of the complexity or purpose of the web site in question.
Abstracting these common solutions into reusable code produces what are called
“frameworks” for web development.  Perhaps the most well-known framework for
web development is Ruby on Rails, but Python has its own frameworks.  Some of
these were partly inspired by Rails, or borrowed ideas from Rails, but many
existed a long time before Rails.</p>
<p>Originally Python web frameworks tended to incorporate all of the services
needed to develop web sites as a giant, integrated set of tools.  No two web
frameworks were interoperable:  a program developed for one could not be
deployed on a different one without considerable re-engineering work.  This led
to the development of “minimalist” web frameworks that provided just the tools
to communicate between the Python code and the http protocol, with all other
services to be added on top via separate components.  Some ad hoc standards
were developed that allowed for limited interoperability between frameworks,
such as a standard that allowed different template engines to be used
interchangeably.</p>
<p>Since the advent of WSGI, the Python web framework world has been evolving
toward interoperability based on the WSGI standard.  Now many web frameworks,
whether “full stack” (providing all the tools one needs to deploy the most
complex web sites) or minimalist, or anything in between, are built from
collections of reusable components that can be used with more than one
framework.</p>
<p>The majority of users will probably want to select a “full stack” framework
that has an active community.  These frameworks tend to be well documented,
and provide the easiest path to producing a fully functional web site in
minimal time.</p>
<div class="section" id="some-notable-frameworks">
<h3>Some notable frameworks<a class="headerlink" href="#some-notable-frameworks" title="Permalink to this headline">¶</a></h3>
<p>There are an incredible number of frameworks, so they cannot all be covered
here.  Instead we will briefly touch on some of the most popular.</p>
<div class="section" id="django">
<h4>Django<a class="headerlink" href="#django" title="Permalink to this headline">¶</a></h4>
<p><a class="reference external" href="https://www.djangoproject.com/">Django</a> is a framework consisting of several
tightly coupled elements which were written from scratch and work together very
well.  It includes an ORM which is quite powerful while being simple to use,
and has a great online administration interface which makes it possible to edit
the data in the database with a browser.  The template engine is text-based and
is designed to be usable for page designers who cannot write Python.  It
supports template inheritance and filters (which work like Unix pipes).  Django
has many handy features bundled, such as creation of RSS feeds or generic views,
which make it possible to create web sites almost without writing any Python code.</p>
<p>It has a big, international community, the members of which have created many
web sites.  There are also a lot of add-on projects which extend Django’s normal
functionality.  This is partly due to Django’s well written <a class="reference external" href="https://docs.djangoproject.com/">online
documentation</a> and the <a class="reference external" href="http://www.djangobook.com/">Django book</a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Although Django is an MVC-style framework, it names the elements
differently, which is described in the <a class="reference external" href="https://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names">Django FAQ</a>.</p>
</div>
</div>
<div class="section" id="turbogears">
<h4>TurboGears<a class="headerlink" href="#turbogears" title="Permalink to this headline">¶</a></h4>
<p>Another popular web framework for Python is <a class="reference external" href="http://www.turbogears.org/">TurboGears</a>.  TurboGears takes the approach of using already
existing components and combining them with glue code to create a seamless
experience.  TurboGears gives the user flexibility in choosing components. For
example the ORM and template engine can be changed to use packages different
from those used by default.</p>
<p>The documentation can be found in the <a class="reference external" href="https://turbogears.readthedocs.org/">TurboGears documentation</a>, where links to screencasts can be found.
TurboGears has also an active user community which can respond to most related
questions.  There is also a <a class="reference external" href="http://turbogears.org/1.0/docs/TGBooks.html">TurboGears book</a>
published, which is a good starting point.</p>
<p>The newest version of TurboGears, version 2.0, moves even further in direction
of WSGI support and a component-based architecture.  TurboGears 2 is based on
the WSGI stack of another popular component-based web framework, <a class="reference external" href="http://www.pylonsproject.org/">Pylons</a>.</p>
</div>
<div class="section" id="zope">
<h4>Zope<a class="headerlink" href="#zope" title="Permalink to this headline">¶</a></h4>
<p>The Zope framework is one of the “old original” frameworks.  Its current
incarnation in Zope2 is a tightly integrated full-stack framework.  One of its
most interesting feature is its tight integration with a powerful object
database called the <a class="reference external" href="https://launchpad.net/zodb">ZODB</a> (Zope Object Database).
Because of its highly integrated nature, Zope wound up in a somewhat isolated
ecosystem:  code written for Zope wasn’t very usable outside of Zope, and
vice-versa.  To solve this problem the Zope 3 effort was started.  Zope 3
re-engineers Zope as a set of more cleanly isolated components.  This effort
was started before the advent of the WSGI standard, but there is WSGI support
for Zope 3 from the <a class="reference external" href="http://repoze.org/">Repoze</a> project.  Zope components
have many years of production use behind them, and the Zope 3 project gives
access to these components to the wider Python community.  There is even a
separate framework based on the Zope components: <a class="reference external" href="http://grok.zope.org/">Grok</a>.</p>
<p>Zope is also the infrastructure used by the <a class="reference external" href="https://plone.org/">Plone</a> content
management system, one of the most powerful and popular content management
systems available.</p>
</div>
<div class="section" id="other-notable-frameworks">
<h4>Other notable frameworks<a class="headerlink" href="#other-notable-frameworks" title="Permalink to this headline">¶</a></h4>
<p>Of course these are not the only frameworks that are available.  There are
many other frameworks worth mentioning.</p>
<p>Another framework that’s already been mentioned is <a class="reference external" href="http://www.pylonsproject.org/">Pylons</a>.  Pylons is much
like TurboGears, but with an even stronger emphasis on flexibility, which comes
at the cost of being more difficult to use.  Nearly every component can be
exchanged, which makes it necessary to use the documentation of every single
component, of which there are many.  Pylons builds upon <a class="reference external" href="http://pythonpaste.org/">Paste</a>, an extensive set of tools which are handy for WSGI.</p>
<p>And that’s still not everything.  The most up-to-date information can always be
found in the Python wiki.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>The Python wiki contains an extensive list of <a class="reference external" href="https://wiki.python.org/moin/WebFrameworks">web frameworks</a>.</p>
<p class="last">Most frameworks also have their own mailing lists and IRC channels, look out
for these on the projects’ web sites.</p>
</div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">HOWTO Use Python in the web</a><ul>
<li><a class="reference internal" href="#the-low-level-view">The Low-Level View</a><ul>
<li><a class="reference internal" href="#common-gateway-interface">Common Gateway Interface</a><ul>
<li><a class="reference internal" href="#simple-script-for-testing-cgi">Simple script for testing CGI</a></li>
<li><a class="reference internal" href="#setting-up-cgi-on-your-own-server">Setting up CGI on your own server</a></li>
<li><a class="reference internal" href="#common-problems-with-cgi-scripts">Common problems with CGI scripts</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mod-python">mod_python</a></li>
<li><a class="reference internal" href="#fastcgi-and-scgi">FastCGI and SCGI</a><ul>
<li><a class="reference internal" href="#setting-up-fastcgi">Setting up FastCGI</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mod-wsgi">mod_wsgi</a></li>
</ul>
</li>
<li><a class="reference internal" href="#step-back-wsgi">Step back: WSGI</a><ul>
<li><a class="reference internal" href="#wsgi-servers">WSGI Servers</a></li>
<li><a class="reference internal" href="#case-study-moinmoin">Case study: MoinMoin</a></li>
</ul>
</li>
<li><a class="reference internal" href="#model-view-controller">Model-View-Controller</a></li>
<li><a class="reference internal" href="#ingredients-for-websites">Ingredients for Websites</a><ul>
<li><a class="reference internal" href="#templates">Templates</a></li>
<li><a class="reference internal" href="#data-persistence">Data persistence</a></li>
</ul>
</li>
<li><a class="reference internal" href="#frameworks">Frameworks</a><ul>
<li><a class="reference internal" href="#some-notable-frameworks">Some notable frameworks</a><ul>
<li><a class="reference internal" href="#django">Django</a></li>
<li><a class="reference internal" href="#turbogears">TurboGears</a></li>
<li><a class="reference internal" href="#zope">Zope</a></li>
<li><a class="reference internal" href="#other-notable-frameworks">Other notable frameworks</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="urllib2.html"
                        title="previous chapter">HOWTO Fetch Internet Resources Using urllib2</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="argparse.html"
                        title="next chapter">Argparse Tutorial</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/webservers.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="Argparse Tutorial"
             >next</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="HOWTO Fetch Internet Resources Using urllib2"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�U��o�ohtml/install/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Installing Python Modules (Legacy version) &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="prev" title="10. API Reference" href="../distutils/apiref.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/install/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../distutils/apiref.html" title="10. API Reference"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="installing-python-modules-legacy-version">
<span id="install-index"></span><h1>Installing Python Modules (Legacy version)<a class="headerlink" href="#installing-python-modules-legacy-version" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Greg Ward</td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a></dt>
<dd>The up to date module installation documentations</dd>
</dl>
</div>
<p>This document describes the Python Distribution Utilities (“Distutils”) from the
end-user’s point-of-view, describing how to extend the capabilities of a
standard Python installation by building and installing third-party Python
modules and extensions.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This guide only covers the basic tools for building and distributing
extensions that are provided as part of this version of Python. Third party
tools offer easier to use and more secure alternatives. Refer to the <a class="reference external" href="https://packaging.python.org/en/latest/current/">quick
recommendations section</a>
in the Python Packaging User Guide for more information.</p>
</div>
<div class="section" id="introduction">
<span id="inst-intro"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>Although Python’s extensive standard library covers many programming needs,
there often comes a time when you need to add some new functionality to your
Python installation in the form of third-party modules.  This might be necessary
to support your own programming, or to support an application that you want to
use and that happens to be written in Python.</p>
<p>In the past, there has been little support for adding third-party modules to an
existing Python installation.  With the introduction of the Python Distribution
Utilities (Distutils for short) in Python 2.0, this changed.</p>
<p>This document is aimed primarily at the people who need to install third-party
Python modules: end-users and system administrators who just need to get some
Python application running, and existing Python programmers who want to add some
new goodies to their toolbox.  You don’t need to know Python to read this
document; there will be some brief forays into using Python’s interactive mode
to explore your installation, but that’s it.  If you’re looking for information
on how to distribute your own Python modules so that others may use them, see
the <a class="reference internal" href="../distutils/index.html#distutils-index"><span class="std std-ref">Distributing Python Modules (Legacy version)</span></a> manual.  <a class="reference internal" href="../distutils/setupscript.html#debug-setup-script"><span class="std std-ref">Debugging the setup script</span></a> may also be of
interest.</p>
<div class="section" id="best-case-trivial-installation">
<span id="inst-trivial-install"></span><h3>Best case: trivial installation<a class="headerlink" href="#best-case-trivial-installation" title="Permalink to this headline">¶</a></h3>
<p>In the best case, someone will have prepared a special version of the module
distribution you want to install that is targeted specifically at your platform
and is installed just like any other software on your platform.  For example,
the module developer might make an executable installer available for Windows
users, an RPM package for users of RPM-based Linux systems (Red Hat, SuSE,
Mandrake, and many others), a Debian package for users of Debian-based Linux
systems, and so forth.</p>
<p>In that case, you would download the installer appropriate to your platform and
do the obvious thing with it: run it if it’s an executable installer, <code class="docutils literal notranslate"><span class="pre">rpm</span>
<span class="pre">--install</span></code> it if it’s an RPM, etc.  You don’t need to run Python or a setup
script, you don’t need to compile anything—you might not even need to read any
instructions (although it’s always a good idea to do so anyway).</p>
<p>Of course, things will not always be that easy.  You might be interested in a
module distribution that doesn’t have an easy-to-use installer for your
platform.  In that case, you’ll have to start with the source distribution
released by the module’s author/maintainer.  Installing from a source
distribution is not too hard, as long as the modules are packaged in the
standard way.  The bulk of this document is about building and installing
modules from standard source distributions.</p>
</div>
<div class="section" id="the-new-standard-distutils">
<span id="inst-new-standard"></span><h3>The new standard: Distutils<a class="headerlink" href="#the-new-standard-distutils" title="Permalink to this headline">¶</a></h3>
<p>If you download a module source distribution, you can tell pretty quickly if it
was packaged and distributed in the standard way, i.e. using the Distutils.
First, the distribution’s name and version number will be featured prominently
in the name of the downloaded archive, e.g. <code class="file docutils literal notranslate"><span class="pre">foo-1.0.tar.gz</span></code> or
<code class="file docutils literal notranslate"><span class="pre">widget-0.9.7.zip</span></code>.  Next, the archive will unpack into a similarly-named
directory: <code class="file docutils literal notranslate"><span class="pre">foo-1.0</span></code> or <code class="file docutils literal notranslate"><span class="pre">widget-0.9.7</span></code>.  Additionally, the
distribution will contain a setup script <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>, and a file named
<code class="file docutils literal notranslate"><span class="pre">README.txt</span></code> or possibly just <code class="file docutils literal notranslate"><span class="pre">README</span></code>, which should explain that
building and installing the module distribution is a simple matter of running
one command from a terminal:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install
</pre></div>
</div>
<p>For Windows, this command should be run from a command prompt window
(<span class="menuselection">Start ‣ Accessories</span>):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>setup.py install
</pre></div>
</div>
<p>If all these things are true, then you already know how to build and install the
modules you’ve just downloaded:  Run the command above. Unless you need to
install things in a non-standard way or customize the build process, you don’t
really need this manual.  Or rather, the above command is everything you need to
get out of this manual.</p>
</div>
</div>
<div class="section" id="standard-build-and-install">
<span id="inst-standard-install"></span><h2>Standard Build and Install<a class="headerlink" href="#standard-build-and-install" title="Permalink to this headline">¶</a></h2>
<p>As described in section <a class="reference internal" href="#inst-new-standard"><span class="std std-ref">The new standard: Distutils</span></a>, building and installing a module
distribution using the Distutils is usually one simple command to run from a
terminal:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install
</pre></div>
</div>
<div class="section" id="platform-variations">
<span id="inst-platform-variations"></span><h3>Platform variations<a class="headerlink" href="#platform-variations" title="Permalink to this headline">¶</a></h3>
<p>You should always run the setup command from the distribution root directory,
i.e. the top-level subdirectory that the module source distribution unpacks
into.  For example, if you’ve just downloaded a module source distribution
<code class="file docutils literal notranslate"><span class="pre">foo-1.0.tar.gz</span></code> onto a Unix system, the normal thing to do is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>gunzip -c foo-1.0.tar.gz | tar xf -    # unpacks into directory foo-1.0
cd foo-1.0
python setup.py install
</pre></div>
</div>
<p>On Windows, you’d probably download <code class="file docutils literal notranslate"><span class="pre">foo-1.0.zip</span></code>.  If you downloaded the
archive file to <code class="file docutils literal notranslate"><span class="pre">C:\Temp</span></code>, then it would unpack into
<code class="file docutils literal notranslate"><span class="pre">C:\Temp\foo-1.0</span></code>; you can use either an archive manipulator with a
graphical user interface (such as WinZip) or a command-line tool (such as
<strong class="program">unzip</strong> or <strong class="program">pkunzip</strong>) to unpack the archive.  Then, open a
command prompt window and run:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>cd c:\Temp\foo-1.0
python setup.py install
</pre></div>
</div>
</div>
<div class="section" id="splitting-the-job-up">
<span id="inst-splitting-up"></span><h3>Splitting the job up<a class="headerlink" href="#splitting-the-job-up" title="Permalink to this headline">¶</a></h3>
<p>Running <code class="docutils literal notranslate"><span class="pre">setup.py</span> <span class="pre">install</span></code> builds and installs all modules in one run.  If you
prefer to work incrementally—especially useful if you want to customize the
build process, or if things are going wrong—you can use the setup script to do
one thing at a time.  This is particularly helpful when the build and install
will be done by different users—for example, you might want to build a module
distribution and hand it off to a system administrator for installation (or do
it yourself, with super-user privileges).</p>
<p>For example, you can build everything in one step, and then install everything
in a second step, by invoking the setup script twice:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build
python setup.py install
</pre></div>
</div>
<p>If you do this, you will notice that running the <strong class="command">install</strong> command
first runs the <strong class="command">build</strong> command, which—in this case—quickly notices
that it has nothing to do, since everything in the <code class="file docutils literal notranslate"><span class="pre">build</span></code> directory is
up-to-date.</p>
<p>You may not need this ability to break things down often if all you do is
install modules downloaded off the ‘net, but it’s very handy for more advanced
tasks.  If you get into distributing your own Python modules and extensions,
you’ll run lots of individual Distutils commands on their own.</p>
</div>
<div class="section" id="how-building-works">
<span id="inst-how-build-works"></span><h3>How building works<a class="headerlink" href="#how-building-works" title="Permalink to this headline">¶</a></h3>
<p>As implied above, the <strong class="command">build</strong> command is responsible for putting the
files to install into a <em>build directory</em>.  By default, this is <code class="file docutils literal notranslate"><span class="pre">build</span></code>
under the distribution root; if you’re excessively concerned with speed, or want
to keep the source tree pristine, you can change the build directory with the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--build-base</span></code> option. For example:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --build-base=/path/to/pybuild/foo-1.0
</pre></div>
</div>
<p>(Or you could do this permanently with a directive in your system or personal
Distutils configuration file; see section <a class="reference internal" href="#inst-config-files"><span class="std std-ref">Distutils Configuration Files</span></a>.)  Normally, this
isn’t necessary.</p>
<p>The default layout for the build tree is as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>--- build/ --- lib/
or
--- build/ --- lib.&lt;plat&gt;/
               temp.&lt;plat&gt;/
</pre></div>
</div>
<p>where <code class="docutils literal notranslate"><span class="pre">&lt;plat&gt;</span></code> expands to a brief description of the current OS/hardware
platform and Python version.  The first form, with just a <code class="file docutils literal notranslate"><span class="pre">lib</span></code> directory,
is used for “pure module distributions”—that is, module distributions that
include only pure Python modules.  If a module distribution contains any
extensions (modules written in C/C++), then the second form, with two <code class="docutils literal notranslate"><span class="pre">&lt;plat&gt;</span></code>
directories, is used.  In that case, the <code class="file docutils literal notranslate"><span class="pre">temp.</span><em><span class="pre">plat</span></em></code> directory holds
temporary files generated by the compile/link process that don’t actually get
installed.  In either case, the <code class="file docutils literal notranslate"><span class="pre">lib</span></code> (or <code class="file docutils literal notranslate"><span class="pre">lib.</span><em><span class="pre">plat</span></em></code>) directory
contains all Python modules (pure Python and extensions) that will be installed.</p>
<p>In the future, more directories will be added to handle Python scripts,
documentation, binary executables, and whatever else is needed to handle the job
of installing Python modules and applications.</p>
</div>
<div class="section" id="how-installation-works">
<span id="inst-how-install-works"></span><h3>How installation works<a class="headerlink" href="#how-installation-works" title="Permalink to this headline">¶</a></h3>
<p>After the <strong class="command">build</strong> command runs (whether you run it explicitly, or the
<strong class="command">install</strong> command does it for you), the work of the <strong class="command">install</strong>
command is relatively simple: all it has to do is copy everything under
<code class="file docutils literal notranslate"><span class="pre">build/lib</span></code> (or <code class="file docutils literal notranslate"><span class="pre">build/lib.</span><em><span class="pre">plat</span></em></code>) to your chosen installation
directory.</p>
<p>If you don’t choose an installation directory—i.e., if you just run <code class="docutils literal notranslate"><span class="pre">setup.py</span>
<span class="pre">install</span></code>—then the <strong class="command">install</strong> command installs to the standard
location for third-party Python modules.  This location varies by platform and
by how you built/installed Python itself.  On Unix (and Mac OS X, which is also
Unix-based), it also depends on whether the module distribution being installed
is pure Python or contains extensions (“non-pure”):</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="42%" />
<col width="39%" />
<col width="6%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Platform</th>
<th class="head">Standard installation location</th>
<th class="head">Default value</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Unix (pure)</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
<td><code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td>Unix (non-pure)</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
<td><code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td>Windows</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">\Lib\site-packages</span></code></td>
<td><code class="file docutils literal notranslate"><span class="pre">C:\Python</span><em><span class="pre">XY</span></em><span class="pre">\Lib\site-packages</span></code></td>
<td>(2)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>Most Linux distributions include Python as a standard part of the system, so
<code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and <code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em></code> are usually both <code class="file docutils literal notranslate"><span class="pre">/usr</span></code> on
Linux.  If you build Python yourself on Linux (or any Unix-like system), the
default <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and <code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em></code> are <code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code>.</li>
<li>The default installation directory on Windows was <code class="file docutils literal notranslate"><span class="pre">C:\Program</span>
<span class="pre">Files\Python</span></code> under Python 1.6a1, 1.5.2, and earlier.</li>
</ol>
<p><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and <code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em></code> stand for the directories that Python
is installed to, and where it finds its libraries at run-time.  They are always
the same under Windows, and very often the same under Unix and Mac OS X.  You
can find out what your Python installation uses for <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and
<code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em></code> by running Python in interactive mode and typing a few
simple commands. Under Unix, just type <code class="docutils literal notranslate"><span class="pre">python</span></code> at the shell prompt.  Under
Windows, choose <span class="menuselection">Start ‣ Programs ‣ Python X.Y ‣
Python (command line)</span>.   Once the interpreter is started, you type Python code
at the prompt.  For example, on my Linux system, I type the three Python
statements shown below, and get the output as shown, to find out my
<code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and <code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em></code>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Python 2.4 (#26, Aug  7 2004, 17:19:02)
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.prefix
&#39;/usr&#39;
&gt;&gt;&gt; sys.exec_prefix
&#39;/usr&#39;
</pre></div>
</div>
<p>A few other placeholders are used in this document: <code class="file docutils literal notranslate"><em><span class="pre">X.Y</span></em></code> stands for the
version of Python, for example <code class="docutils literal notranslate"><span class="pre">2.7</span></code>; <code class="file docutils literal notranslate"><em><span class="pre">distname</span></em></code> will be replaced by
the name of the module distribution being installed.  Dots and capitalization
are important in the paths; for example, a value that uses <code class="docutils literal notranslate"><span class="pre">python2.7</span></code> on UNIX
will typically use <code class="docutils literal notranslate"><span class="pre">Python27</span></code> on Windows.</p>
<p>If you don’t want to install modules to the standard location, or if you don’t
have permission to write there, then you need to read about alternate
installations in section <a class="reference internal" href="#inst-alt-install"><span class="std std-ref">Alternate Installation</span></a>.  If you want to customize your
installation directories more heavily, see section <a class="reference internal" href="#inst-custom-install"><span class="std std-ref">Custom Installation</span></a> on
custom installations.</p>
</div>
</div>
<div class="section" id="alternate-installation">
<span id="inst-alt-install"></span><h2>Alternate Installation<a class="headerlink" href="#alternate-installation" title="Permalink to this headline">¶</a></h2>
<p>Often, it is necessary or desirable to install modules to a location other than
the standard location for third-party Python modules.  For example, on a Unix
system you might not have permission to write to the standard third-party module
directory.  Or you might wish to try out a module before making it a standard
part of your local Python installation.  This is especially true when upgrading
a distribution already present: you want to make sure your existing base of
scripts still works with the new version before actually upgrading.</p>
<p>The Distutils <strong class="command">install</strong> command is designed to make installing module
distributions to an alternate location simple and painless.  The basic idea is
that you supply a base directory for the installation, and the
<strong class="command">install</strong> command picks a set of directories (called an <em>installation
scheme</em>) under this base directory in which to install files.  The details
differ across platforms, so read whichever of the following sections applies to
you.</p>
<p>Note that the various alternate installation schemes are mutually exclusive: you
can pass <code class="docutils literal notranslate"><span class="pre">--user</span></code>, or <code class="docutils literal notranslate"><span class="pre">--home</span></code>, or <code class="docutils literal notranslate"><span class="pre">--prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">--exec-prefix</span></code>, or
<code class="docutils literal notranslate"><span class="pre">--install-base</span></code> and <code class="docutils literal notranslate"><span class="pre">--install-platbase</span></code>, but you can’t mix from these
groups.</p>
<div class="section" id="alternate-installation-the-user-scheme">
<span id="inst-alt-install-user"></span><h3>Alternate installation: the user scheme<a class="headerlink" href="#alternate-installation-the-user-scheme" title="Permalink to this headline">¶</a></h3>
<p>This scheme is designed to be the most convenient solution for users that don’t
have write permission to the global site-packages directory or don’t want to
install into it.  It is enabled with a simple option:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --user
</pre></div>
</div>
<p>Files will be installed into subdirectories of <a class="reference internal" href="../library/site.html#site.USER_BASE" title="site.USER_BASE"><code class="xref py py-data docutils literal notranslate"><span class="pre">site.USER_BASE</span></code></a> (written
as <code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em></code> hereafter).  This scheme installs pure Python modules and
extension modules in the same location (also known as <a class="reference internal" href="../library/site.html#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">site.USER_SITE</span></code></a>).
Here are the values for UNIX, including Mac OS X:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Installation directory</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
</tr>
<tr class="row-odd"><td>scripts</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">/bin</span></code></td>
</tr>
<tr class="row-even"><td>data</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em></code></td>
</tr>
<tr class="row-odd"><td>C headers</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">/include/python</span><em><span class="pre">X.Y</span></em><span class="pre">/</span><em><span class="pre">distname</span></em></code></td>
</tr>
</tbody>
</table>
<p>And here are the values used on Windows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Installation directory</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">\Python</span><em><span class="pre">XY</span></em><span class="pre">\site-packages</span></code></td>
</tr>
<tr class="row-odd"><td>scripts</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">\Scripts</span></code></td>
</tr>
<tr class="row-even"><td>data</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em></code></td>
</tr>
<tr class="row-odd"><td>C headers</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">\Python</span><em><span class="pre">XY</span></em><span class="pre">\Include\</span><em><span class="pre">distname</span></em></code></td>
</tr>
</tbody>
</table>
<p>The advantage of using this scheme compared to the other ones described below is
that the user site-packages directory is under normal conditions always included
in <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> (see <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> for more information), which means that
there is no additional step to perform after running the <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script
to finalize the installation.</p>
<p>The <strong class="command">build_ext</strong> command also has a <code class="docutils literal notranslate"><span class="pre">--user</span></code> option to add
<code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">/include</span></code> to the compiler search path for header files and
<code class="file docutils literal notranslate"><em><span class="pre">userbase</span></em><span class="pre">/lib</span></code> to the compiler search path for libraries as well as to
the runtime search path for shared C libraries (rpath).</p>
</div>
<div class="section" id="alternate-installation-the-home-scheme">
<span id="inst-alt-install-home"></span><h3>Alternate installation: the home scheme<a class="headerlink" href="#alternate-installation-the-home-scheme" title="Permalink to this headline">¶</a></h3>
<p>The idea behind the “home scheme” is that you build and maintain a personal
stash of Python modules.  This scheme’s name is derived from the idea of a
“home” directory on Unix, since it’s not unusual for a Unix user to make their
home directory have a layout similar to <code class="file docutils literal notranslate"><span class="pre">/usr/</span></code> or <code class="file docutils literal notranslate"><span class="pre">/usr/local/</span></code>.
This scheme can be used by anyone, regardless of the operating system they
are installing for.</p>
<p>Installing a new module distribution is as simple as</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --home=&lt;dir&gt;
</pre></div>
</div>
<p>where you can supply any directory you like for the <code class="xref std std-option docutils literal notranslate"><span class="pre">--home</span></code> option.  On
Unix, lazy typists can just type a tilde (<code class="docutils literal notranslate"><span class="pre">~</span></code>); the <strong class="command">install</strong> command
will expand this to your home directory:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --home=~
</pre></div>
</div>
<p>To make Python find the distributions installed with this scheme, you may have
to <a class="reference internal" href="#inst-search-path"><span class="std std-ref">modify Python’s search path</span></a> or edit
<code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> (see <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a>) to call <a class="reference internal" href="../library/site.html#site.addsitedir" title="site.addsitedir"><code class="xref py py-func docutils literal notranslate"><span class="pre">site.addsitedir()</span></code></a> or edit
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<p>The <code class="xref std std-option docutils literal notranslate"><span class="pre">--home</span></code> option defines the installation base directory.  Files are
installed to the following directories under the installation base as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Installation directory</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">home</span></em><span class="pre">/lib/python</span></code></td>
</tr>
<tr class="row-odd"><td>scripts</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">home</span></em><span class="pre">/bin</span></code></td>
</tr>
<tr class="row-even"><td>data</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">home</span></em></code></td>
</tr>
<tr class="row-odd"><td>C headers</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">home</span></em><span class="pre">/include/python/</span><em><span class="pre">distname</span></em></code></td>
</tr>
</tbody>
</table>
<p>(Mentally replace slashes with backslashes if you’re on Windows.)</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <code class="xref std std-option docutils literal notranslate"><span class="pre">--home</span></code> option used to be supported only on Unix.</p>
</div>
</div>
<div class="section" id="alternate-installation-unix-the-prefix-scheme">
<span id="inst-alt-install-prefix-unix"></span><h3>Alternate installation: Unix (the prefix scheme)<a class="headerlink" href="#alternate-installation-unix-the-prefix-scheme" title="Permalink to this headline">¶</a></h3>
<p>The “prefix scheme” is useful when you wish to use one Python installation to
perform the build/install (i.e., to run the setup script), but install modules
into the third-party module directory of a different Python installation (or
something that looks like a different Python installation).  If this sounds a
trifle unusual, it is—that’s why the user and home schemes come before.  However,
there are at least two known cases where the prefix scheme will be useful.</p>
<p>First, consider that many Linux distributions put Python in <code class="file docutils literal notranslate"><span class="pre">/usr</span></code>, rather
than the more traditional <code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code>.  This is entirely appropriate,
since in those cases Python is part of “the system” rather than a local add-on.
However, if you are installing Python modules from source, you probably want
them to go in <code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python2.</span><em><span class="pre">X</span></em></code> rather than
<code class="file docutils literal notranslate"><span class="pre">/usr/lib/python2.</span><em><span class="pre">X</span></em></code>.  This can be done with</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>/usr/bin/python setup.py install --prefix=/usr/local
</pre></div>
</div>
<p>Another possibility is a network filesystem where the name used to write to a
remote directory is different from the name used to read it: for example, the
Python interpreter accessed as <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin/python</span></code> might search for
modules in <code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python2.</span><em><span class="pre">X</span></em></code>, but those modules would have to
be installed to, say, <code class="file docutils literal notranslate"><span class="pre">/mnt/</span><em><span class="pre">&#64;server</span></em><span class="pre">/export/lib/python2.</span><em><span class="pre">X</span></em></code>.  This could
be done with</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>/usr/local/bin/python setup.py install --prefix=/mnt/@server/export
</pre></div>
</div>
<p>In either case, the <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code> option defines the installation base, and
the <code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code> option defines the platform-specific installation
base, which is used for platform-specific files.  (Currently, this just means
non-pure module distributions, but could be expanded to C libraries, binary
executables, etc.)  If <code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code> is not supplied, it defaults to
<code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code>.  Files are installed as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="77%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Installation directory</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Python modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
</tr>
<tr class="row-odd"><td>extension modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">exec-prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code></td>
</tr>
<tr class="row-even"><td>scripts</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/bin</span></code></td>
</tr>
<tr class="row-odd"><td>data</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code></td>
</tr>
<tr class="row-even"><td>C headers</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include/python</span><em><span class="pre">X.Y</span></em><span class="pre">/</span><em><span class="pre">distname</span></em></code></td>
</tr>
</tbody>
</table>
<p>There is no requirement that <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code>
actually point to an alternate Python installation; if the directories listed
above do not already exist, they are created at installation time.</p>
<p>Incidentally, the real reason the prefix scheme is important is simply that a
standard Unix installation uses the prefix scheme, but with <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code>
and <code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code> supplied by Python itself as <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code> and
<code class="docutils literal notranslate"><span class="pre">sys.exec_prefix</span></code>.  Thus, you might think you’ll never use the prefix scheme,
but every time you run <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">install</span></code> without any other options,
you’re using it.</p>
<p>Note that installing extensions to an alternate Python installation has no
effect on how those extensions are built: in particular, the Python header files
(<code class="file docutils literal notranslate"><span class="pre">Python.h</span></code> and friends) installed with the Python interpreter used to run
the setup script will be used in compiling extensions.  It is your
responsibility to ensure that the interpreter used to run extensions installed
in this way is compatible with the interpreter used to build them.  The best way
to do this is to ensure that the two interpreters are the same version of Python
(possibly different builds, or possibly copies of the same build).  (Of course,
if your <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code> don’t even point to an
alternate Python installation, this is immaterial.)</p>
</div>
<div class="section" id="alternate-installation-windows-the-prefix-scheme">
<span id="inst-alt-install-prefix-windows"></span><h3>Alternate installation: Windows (the prefix scheme)<a class="headerlink" href="#alternate-installation-windows-the-prefix-scheme" title="Permalink to this headline">¶</a></h3>
<p>Windows has no concept of a user’s home directory, and since the standard Python
installation under Windows is simpler than under Unix, the <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code>
option has traditionally been used to install additional packages in separate
locations on Windows.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --prefix=&quot;\Temp\Python&quot;
</pre></div>
</div>
<p>to install modules to the <code class="file docutils literal notranslate"><span class="pre">\Temp\Python</span></code> directory on the current drive.</p>
<p>The installation base is defined by the <code class="xref std std-option docutils literal notranslate"><span class="pre">--prefix</span></code> option; the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--exec-prefix</span></code> option is not supported under Windows, which means that
pure Python modules and extension modules are installed into the same location.
Files are installed as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="79%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Installation directory</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>modules</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">\Lib\site-packages</span></code></td>
</tr>
<tr class="row-odd"><td>scripts</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">\Scripts</span></code></td>
</tr>
<tr class="row-even"><td>data</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code></td>
</tr>
<tr class="row-odd"><td>C headers</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">\Include\</span><em><span class="pre">distname</span></em></code></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="custom-installation">
<span id="inst-custom-install"></span><h2>Custom Installation<a class="headerlink" href="#custom-installation" title="Permalink to this headline">¶</a></h2>
<p>Sometimes, the alternate installation schemes described in section
<a class="reference internal" href="#inst-alt-install"><span class="std std-ref">Alternate Installation</span></a> just don’t do what you want.  You might want to tweak just
one or two directories while keeping everything under the same base directory,
or you might want to completely redefine the installation scheme.  In either
case, you’re creating a <em>custom installation scheme</em>.</p>
<p>To create a custom installation scheme, you start with one of the alternate
schemes and override some of the installation directories used for the various
types of files, using these options:</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Override option</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Python modules</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-purelib</span></code></td>
</tr>
<tr class="row-odd"><td>extension modules</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-platlib</span></code></td>
</tr>
<tr class="row-even"><td>all modules</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-lib</span></code></td>
</tr>
<tr class="row-odd"><td>scripts</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-scripts</span></code></td>
</tr>
<tr class="row-even"><td>data</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-data</span></code></td>
</tr>
<tr class="row-odd"><td>C headers</td>
<td><code class="docutils literal notranslate"><span class="pre">--install-headers</span></code></td>
</tr>
</tbody>
</table>
<p>These override options can be relative, absolute,
or explicitly defined in terms of one of the installation base directories.
(There are two installation base directories, and they are normally the same—
they only differ when you use the Unix “prefix scheme” and supply different
<code class="docutils literal notranslate"><span class="pre">--prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">--exec-prefix</span></code> options; using <code class="docutils literal notranslate"><span class="pre">--install-lib</span></code> will
override values computed or given for <code class="docutils literal notranslate"><span class="pre">--install-purelib</span></code> and
<code class="docutils literal notranslate"><span class="pre">--install-platlib</span></code>, and is recommended for schemes that don’t make a
difference between Python and extension modules.)</p>
<p>For example, say you’re installing a module distribution to your home directory
under Unix—but you want scripts to go in <code class="file docutils literal notranslate"><span class="pre">~/scripts</span></code> rather than
<code class="file docutils literal notranslate"><span class="pre">~/bin</span></code>. As you might expect, you can override this directory with the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--install-scripts</span></code> option; in this case, it makes most sense to supply
a relative path, which will be interpreted relative to the installation base
directory (your home directory, in this case):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --home=~ --install-scripts=scripts
</pre></div>
</div>
<p>Another Unix example: suppose your Python installation was built and installed
with a prefix of <code class="file docutils literal notranslate"><span class="pre">/usr/local/python</span></code>, so under a standard  installation
scripts will wind up in <code class="file docutils literal notranslate"><span class="pre">/usr/local/python/bin</span></code>.  If you want them in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/bin</span></code> instead, you would supply this absolute directory for the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--install-scripts</span></code> option:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --install-scripts=/usr/local/bin
</pre></div>
</div>
<p>(This performs an installation using the “prefix scheme,” where the prefix is
whatever your Python interpreter was installed with— <code class="file docutils literal notranslate"><span class="pre">/usr/local/python</span></code>
in this case.)</p>
<p>If you maintain Python on Windows, you might want third-party modules to live in
a subdirectory of <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code>, rather than right in <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code>
itself.  This is almost as easy as customizing the script installation directory
—you just have to remember that there are two types of modules to worry about,
Python and extension modules, which can conveniently be both controlled by one
option:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --install-lib=Site
</pre></div>
</div>
<p>The specified installation directory is relative to <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code>.  Of
course, you also have to ensure that this directory is in Python’s module
search path, such as by putting a <code class="file docutils literal notranslate"><span class="pre">.pth</span></code> file in a site directory (see
<a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a>).  See section <a class="reference internal" href="#inst-search-path"><span class="std std-ref">Modifying Python’s Search Path</span></a> to find out how to modify
Python’s search path.</p>
<p>If you want to define an entire installation scheme, you just have to supply all
of the installation directory options.  The recommended way to do this is to
supply relative paths; for example, if you want to maintain all Python
module-related files under <code class="file docutils literal notranslate"><span class="pre">python</span></code> in your home directory, and you want a
separate directory for each platform that you use your home directory from, you
might define the following installation scheme:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --home=~ \
                        --install-purelib=python/lib \
                        --install-platlib=python/lib.$PLAT \
                        --install-scripts=python/scripts
                        --install-data=python/data
</pre></div>
</div>
<p>or, equivalently,</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --home=~/python \
                        --install-purelib=lib \
                        --install-platlib=&#39;lib.$PLAT&#39; \
                        --install-scripts=scripts
                        --install-data=data
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">$PLAT</span></code> is not (necessarily) an environment variable—it will be expanded by
the Distutils as it parses your command line options, just as it does when
parsing your configuration file(s).</p>
<p>Obviously, specifying the entire installation scheme every time you install a
new module distribution would be very tedious.  Thus, you can put these options
into your Distutils config file (see section <a class="reference internal" href="#inst-config-files"><span class="std std-ref">Distutils Configuration Files</span></a>):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-data=python/data
</pre></div>
</div>
<p>or, equivalently,</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>[install]
install-base=$HOME/python
install-purelib=lib
install-platlib=lib.$PLAT
install-scripts=scripts
install-data=data
</pre></div>
</div>
<p>Note that these two are <em>not</em> equivalent if you supply a different installation
base directory when you run the setup script.  For example,</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py install --install-base=/tmp
</pre></div>
</div>
<p>would install pure modules to <code class="file docutils literal notranslate"><span class="pre">/tmp/python/lib</span></code> in the first case, and
to <code class="file docutils literal notranslate"><span class="pre">/tmp/lib</span></code> in the second case.  (For the second case, you probably
want to supply an installation base of <code class="file docutils literal notranslate"><span class="pre">/tmp/python</span></code>.)</p>
<p>You probably noticed the use of <code class="docutils literal notranslate"><span class="pre">$HOME</span></code> and <code class="docutils literal notranslate"><span class="pre">$PLAT</span></code> in the sample
configuration file input.  These are Distutils configuration variables, which
bear a strong resemblance to environment variables. In fact, you can use
environment variables in config files on platforms that have such a notion but
the Distutils additionally define a few extra variables that may not be in your
environment, such as <code class="docutils literal notranslate"><span class="pre">$PLAT</span></code>.  (And of course, on systems that don’t have
environment variables, such as Mac OS 9, the configuration variables supplied by
the Distutils are the only ones you can use.) See section <a class="reference internal" href="#inst-config-files"><span class="std std-ref">Distutils Configuration Files</span></a>
for details.</p>
<div class="section" id="modifying-python-s-search-path">
<span id="inst-search-path"></span><h3>Modifying Python’s Search Path<a class="headerlink" href="#modifying-python-s-search-path" title="Permalink to this headline">¶</a></h3>
<p>When the Python interpreter executes an <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, it searches
for both Python code and extension modules along a search path.  A default value
for the path is configured into the Python binary when the interpreter is built.
You can determine the path by importing the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module and printing the
value of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ python
Python 2.2 (#11, Oct  3 2002, 13:31:27)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-112)] on linux2
Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.
&gt;&gt;&gt; import sys
&gt;&gt;&gt; sys.path
[&#39;&#39;, &#39;/usr/local/lib/python2.3&#39;, &#39;/usr/local/lib/python2.3/plat-linux2&#39;,
 &#39;/usr/local/lib/python2.3/lib-tk&#39;, &#39;/usr/local/lib/python2.3/lib-dynload&#39;,
 &#39;/usr/local/lib/python2.3/site-packages&#39;]
&gt;&gt;&gt;
</pre></div>
</div>
<p>The null string in <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> represents the current working directory.</p>
<p>The expected convention for locally installed packages is to put them in the
<code class="file docutils literal notranslate"><em><span class="pre">…</span></em><span class="pre">/site-packages/</span></code> directory, but you may want to install Python
modules into some arbitrary directory.  For example, your site may have a
convention of keeping all software related to the web server under <code class="file docutils literal notranslate"><span class="pre">/www</span></code>.
Add-on Python modules might then belong in <code class="file docutils literal notranslate"><span class="pre">/www/python</span></code>, and in order to
import them, this directory must be added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  There are several
different ways to add the directory.</p>
<p>The most convenient way is to add a path configuration file to a directory
that’s already on Python’s path, usually to the <code class="file docutils literal notranslate"><span class="pre">.../site-packages/</span></code>
directory.  Path configuration files have an extension of <code class="file docutils literal notranslate"><span class="pre">.pth</span></code>, and each
line must contain a single path that will be appended to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  (Because
the new paths are appended to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, modules in the added directories
will not override standard modules.  This means you can’t use this mechanism for
installing fixed versions of standard modules.)</p>
<p>Paths can be absolute or relative, in which case they’re relative to the
directory containing the <code class="file docutils literal notranslate"><span class="pre">.pth</span></code> file.  See the documentation of
the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module for more information.</p>
<p>A slightly less convenient way is to edit the <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> file in Python’s
standard library, and modify <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> is automatically
imported when the Python interpreter is executed, unless the <a class="reference internal" href="../using/cmdline.html#id2"><code class="xref std std-option docutils literal notranslate"><span class="pre">-S</span></code></a> switch
is supplied to suppress this behaviour.  So you could simply edit
<code class="file docutils literal notranslate"><span class="pre">site.py</span></code> and add two lines to it:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>import sys
sys.path.append(&#39;/www/python/&#39;)
</pre></div>
</div>
<p>However, if you reinstall the same major version of Python (perhaps when
upgrading from 2.2 to 2.2.2, for example) <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> will be overwritten by
the stock version.  You’d have to remember that it was modified and save a copy
before doing the installation.</p>
<p>There are two environment variables that can modify <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.
<span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> sets an alternate value for the prefix of the Python
installation.  For example, if <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> is set to <code class="docutils literal notranslate"><span class="pre">/www/python</span></code>,
the search path will be set to <code class="docutils literal notranslate"><span class="pre">['',</span> <span class="pre">'/www/python/lib/pythonX.Y/',</span>
<span class="pre">'/www/python/lib/pythonX.Y/plat-linux2',</span> <span class="pre">...]</span></code>.</p>
<p>The <span class="target" id="index-2"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> variable can be set to a list of paths that will be
added to the beginning of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  For example, if <span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is
set to <code class="docutils literal notranslate"><span class="pre">/www/python:/opt/py</span></code>, the search path will begin with
<code class="docutils literal notranslate"><span class="pre">['/www/python',</span> <span class="pre">'/opt/py']</span></code>.  (Note that directories must exist in order to
be added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>; the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module removes paths that don’t
exist.)</p>
<p>Finally, <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is just a regular Python list, so any Python application
can modify it by adding or removing entries.</p>
</div>
</div>
<div class="section" id="distutils-configuration-files">
<span id="inst-config-files"></span><h2>Distutils Configuration Files<a class="headerlink" href="#distutils-configuration-files" title="Permalink to this headline">¶</a></h2>
<p>As mentioned above, you can use Distutils configuration files to record personal
or site preferences for any Distutils options.  That is, any option to any
command can be stored in one of two or three (depending on your platform)
configuration files, which will be consulted before the command-line is parsed.
This means that configuration files will override default values, and the
command-line will in turn override configuration files.  Furthermore, if
multiple configuration files apply, values from “earlier” files are overridden
by “later” files.</p>
<div class="section" id="location-and-names-of-config-files">
<span id="inst-config-filenames"></span><h3>Location and names of config files<a class="headerlink" href="#location-and-names-of-config-files" title="Permalink to this headline">¶</a></h3>
<p>The names and locations of the configuration files vary slightly across
platforms.  On Unix and Mac OS X, the three configuration files (in the order
they are processed) are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="73%" />
<col width="9%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Location and filename</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>system</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">ver</span></em><span class="pre">/distutils/distutils.cfg</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td>personal</td>
<td><code class="file docutils literal notranslate"><span class="pre">$HOME/.pydistutils.cfg</span></code></td>
<td>(2)</td>
</tr>
<tr class="row-even"><td>local</td>
<td><code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code></td>
<td>(3)</td>
</tr>
</tbody>
</table>
<p>And on Windows, the configuration files are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="70%" />
<col width="10%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type of file</th>
<th class="head">Location and filename</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>system</td>
<td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">\Lib\distutils\distutils.cfg</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td>personal</td>
<td><code class="file docutils literal notranslate"><span class="pre">%HOME%\pydistutils.cfg</span></code></td>
<td>(5)</td>
</tr>
<tr class="row-even"><td>local</td>
<td><code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code></td>
<td>(3)</td>
</tr>
</tbody>
</table>
<p>On all platforms, the “personal” file can be temporarily disabled by
passing the <cite>–no-user-cfg</cite> option.</p>
<p>Notes:</p>
<ol class="arabic simple">
<li>Strictly speaking, the system-wide configuration file lives in the directory
where the Distutils are installed; under Python 1.6 and later on Unix, this is
as shown. For Python 1.5.2, the Distutils will normally be installed to
<code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python1.5/site-packages/distutils</span></code>, so the system
configuration file should be put there under Python 1.5.2.</li>
<li>On Unix, if the <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code> environment variable is not defined, the user’s
home directory will be determined with the <code class="xref py py-func docutils literal notranslate"><span class="pre">getpwuid()</span></code> function from the
standard <a class="reference internal" href="../library/pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a> module. This is done by the <a class="reference internal" href="../library/os.path.html#os.path.expanduser" title="os.path.expanduser"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expanduser()</span></code></a>
function used by Distutils.</li>
<li>I.e., in the current directory (usually the location of the setup script).</li>
<li>(See also note (1).)  Under Python 1.6 and later, Python’s default “installation
prefix” is <code class="file docutils literal notranslate"><span class="pre">C:\Python</span></code>, so the system configuration file is normally
<code class="file docutils literal notranslate"><span class="pre">C:\Python\Lib\distutils\distutils.cfg</span></code>. Under Python 1.5.2, the
default prefix was <code class="file docutils literal notranslate"><span class="pre">C:\Program</span> <span class="pre">Files\Python</span></code>, and the Distutils were not
part of the standard library—so the system configuration file would be
<code class="file docutils literal notranslate"><span class="pre">C:\Program</span> <span class="pre">Files\Python\distutils\distutils.cfg</span></code> in a standard Python
1.5.2 installation under Windows.</li>
<li>On Windows, if the <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code> environment variable is not defined,
<span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">USERPROFILE</span></code> then <span class="target" id="index-7"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOMEDRIVE</span></code> and <span class="target" id="index-8"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOMEPATH</span></code> will
be tried. This is done by the <a class="reference internal" href="../library/os.path.html#os.path.expanduser" title="os.path.expanduser"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expanduser()</span></code></a> function used
by Distutils.</li>
</ol>
</div>
<div class="section" id="syntax-of-config-files">
<span id="inst-config-syntax"></span><h3>Syntax of config files<a class="headerlink" href="#syntax-of-config-files" title="Permalink to this headline">¶</a></h3>
<p>The Distutils configuration files all have the same syntax.  The config files
are grouped into sections.  There is one section for each Distutils command,
plus a <code class="docutils literal notranslate"><span class="pre">global</span></code> section for global options that affect every command.  Each
section consists of one option per line, specified as <code class="docutils literal notranslate"><span class="pre">option=value</span></code>.</p>
<p>For example, the following is a complete config file that just forces all
commands to run quietly by default:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>[global]
verbose=0
</pre></div>
</div>
<p>If this is installed as the system config file, it will affect all processing of
any Python module distribution by any user on the current system.  If it is
installed as your personal config file (on systems that support them), it will
affect only module distributions processed by you.  And if it is used as the
<code class="file docutils literal notranslate"><span class="pre">setup.cfg</span></code> for a particular module distribution, it affects only that
distribution.</p>
<p>You could override the default “build base” directory and make the
<strong class="command">build*</strong> commands always forcibly rebuild all files with the
following:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>[build]
build-base=blib
force=1
</pre></div>
</div>
<p>which corresponds to the command-line arguments</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --build-base=blib --force
</pre></div>
</div>
<p>except that including the <strong class="command">build</strong> command on the command-line means
that command will be run.  Including a particular command in config files has no
such implication; it only means that if the command is run, the options in the
config file will apply.  (Or if other commands that derive values from it are
run, they will use the values in the config file.)</p>
<p>You can find out the complete list of options for any command using the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code> option, e.g.:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --help
</pre></div>
</div>
<p>and you can find out the complete list of global options by using
<code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code> without a command:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py --help
</pre></div>
</div>
<p>See also the “Reference” section of the “Distributing Python Modules” manual.</p>
</div>
</div>
<div class="section" id="building-extensions-tips-and-tricks">
<span id="inst-building-ext"></span><h2>Building Extensions: Tips and Tricks<a class="headerlink" href="#building-extensions-tips-and-tricks" title="Permalink to this headline">¶</a></h2>
<p>Whenever possible, the Distutils try to use the configuration information made
available by the Python interpreter used to run the <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script.
For example, the same compiler and linker flags used to compile Python will also
be used for compiling extensions.  Usually this will work well, but in
complicated situations this might be inappropriate.  This section discusses how
to override the usual Distutils behaviour.</p>
<div class="section" id="tweaking-compiler-linker-flags">
<span id="inst-tweak-flags"></span><h3>Tweaking compiler/linker flags<a class="headerlink" href="#tweaking-compiler-linker-flags" title="Permalink to this headline">¶</a></h3>
<p>Compiling a Python extension written in C or C++ will sometimes require
specifying custom flags for the compiler and linker in order to use a particular
library or produce a special kind of object code. This is especially true if the
extension hasn’t been tested on your platform, or if you’re trying to
cross-compile Python.</p>
<p>In the most general case, the extension author might have foreseen that
compiling the extensions would be complicated, and provided a <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file
for you to edit.  This will likely only be done if the module distribution
contains many separate extension modules, or if they often require elaborate
sets of compiler flags in order to work.</p>
<p>A <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file, if present, is parsed in order to get a list of extensions
to build.  Each line in a <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> describes a single module.  Lines have
the following structure:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>module ... [sourcefile ...] [cpparg ...] [library ...]
</pre></div>
</div>
<p>Let’s examine each of the fields in turn.</p>
<ul class="simple">
<li><em>module</em> is the name of the extension module to be built, and should be a
valid Python identifier.  You can’t just change this in order to rename a module
(edits to the source code would also be needed), so this should be left alone.</li>
<li><em>sourcefile</em> is anything that’s likely to be a source code file, at least
judging by the filename.  Filenames ending in <code class="file docutils literal notranslate"><span class="pre">.c</span></code> are assumed to be
written in C, filenames ending in <code class="file docutils literal notranslate"><span class="pre">.C</span></code>, <code class="file docutils literal notranslate"><span class="pre">.cc</span></code>, and <code class="file docutils literal notranslate"><span class="pre">.c++</span></code> are
assumed to be C++, and filenames ending in <code class="file docutils literal notranslate"><span class="pre">.m</span></code> or <code class="file docutils literal notranslate"><span class="pre">.mm</span></code> are assumed
to be in Objective C.</li>
<li><em>cpparg</em> is an argument for the C preprocessor,  and is anything starting with
<code class="xref std std-option docutils literal notranslate"><span class="pre">-I</span></code>, <code class="xref std std-option docutils literal notranslate"><span class="pre">-D</span></code>, <code class="xref std std-option docutils literal notranslate"><span class="pre">-U</span></code> or <code class="xref std std-option docutils literal notranslate"><span class="pre">-C</span></code>.</li>
<li><em>library</em> is anything ending in <code class="file docutils literal notranslate"><span class="pre">.a</span></code> or beginning with <code class="xref std std-option docutils literal notranslate"><span class="pre">-l</span></code> or
<code class="xref std std-option docutils literal notranslate"><span class="pre">-L</span></code>.</li>
</ul>
<p>If a particular platform requires a special library on your platform, you can
add it by editing the <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file and running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">build</span></code>.
For example, if the module defined by the line</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>foo foomodule.c
</pre></div>
</div>
<p>must be linked with the math library <code class="file docutils literal notranslate"><span class="pre">libm.a</span></code> on your platform, simply add
<code class="xref std std-option docutils literal notranslate"><span class="pre">-lm</span></code> to the line:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>foo foomodule.c -lm
</pre></div>
</div>
<p>Arbitrary switches intended for the compiler or the linker can be supplied with
the <code class="xref std std-option docutils literal notranslate"><span class="pre">-Xcompiler</span></code> <em>arg</em> and <code class="xref std std-option docutils literal notranslate"><span class="pre">-Xlinker</span></code> <em>arg</em> options:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>foo foomodule.c -Xcompiler -o32 -Xlinker -shared -lm
</pre></div>
</div>
<p>The next option after <code class="xref std std-option docutils literal notranslate"><span class="pre">-Xcompiler</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">-Xlinker</span></code> will be
appended to the proper command line, so in the above example the compiler will
be passed the <code class="xref std std-option docutils literal notranslate"><span class="pre">-o32</span></code> option, and the linker will be passed
<code class="xref std std-option docutils literal notranslate"><span class="pre">-shared</span></code>.  If a compiler option requires an argument, you’ll have to
supply multiple <code class="xref std std-option docutils literal notranslate"><span class="pre">-Xcompiler</span></code> options; for example, to pass <code class="docutils literal notranslate"><span class="pre">-x</span> <span class="pre">c++</span></code>
the <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file would have to contain <code class="docutils literal notranslate"><span class="pre">-Xcompiler</span> <span class="pre">-x</span> <span class="pre">-Xcompiler</span> <span class="pre">c++</span></code>.</p>
<p>Compiler flags can also be supplied through setting the <span class="target" id="index-9"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CFLAGS</span></code>
environment variable.  If set, the contents of <span class="target" id="index-10"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CFLAGS</span></code> will be added to
the compiler flags specified in the  <code class="file docutils literal notranslate"><span class="pre">Setup</span></code> file.</p>
</div>
<div class="section" id="using-non-microsoft-compilers-on-windows">
<span id="inst-non-ms-compilers"></span><h3>Using non-Microsoft compilers on Windows<a class="headerlink" href="#using-non-microsoft-compilers-on-windows" title="Permalink to this headline">¶</a></h3>
<div class="section" id="borland-codegear-c">
<h4>Borland/CodeGear C++<a class="headerlink" href="#borland-codegear-c" title="Permalink to this headline">¶</a></h4>
<p>This subsection describes the necessary steps to use Distutils with the Borland
C++ compiler version 5.5.  First you have to know that Borland’s object file
format (OMF) is different from the format used by the Python version you can
download from the Python or ActiveState Web site.  (Python is built with
Microsoft Visual C++, which uses COFF as the object file format.) For this
reason you have to convert Python’s library <code class="file docutils literal notranslate"><span class="pre">python25.lib</span></code> into the
Borland format.  You can do this as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>coff2omf python25.lib python25_bcpp.lib
</pre></div>
</div>
<p>The <code class="file docutils literal notranslate"><span class="pre">coff2omf</span></code> program comes with the Borland compiler.  The file
<code class="file docutils literal notranslate"><span class="pre">python25.lib</span></code> is in the <code class="file docutils literal notranslate"><span class="pre">Libs</span></code> directory of your Python
installation.  If your extension uses other libraries (zlib, …) you have to
convert them too.</p>
<p>The converted files have to reside in the same directories as the normal
libraries.</p>
<p>How does Distutils manage to use these libraries with their changed names?  If
the extension needs a library (eg. <code class="file docutils literal notranslate"><span class="pre">foo</span></code>) Distutils checks first if it
finds a library with suffix <code class="file docutils literal notranslate"><span class="pre">_bcpp</span></code> (eg. <code class="file docutils literal notranslate"><span class="pre">foo_bcpp.lib</span></code>) and then
uses this library.  In the case it doesn’t find such a special library it uses
the default name (<code class="file docutils literal notranslate"><span class="pre">foo.lib</span></code>.) <a class="footnote-reference" href="#id4" id="id1">[1]</a></p>
<p>To let Distutils compile your extension with Borland C++ you now have to type:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --compiler=bcpp
</pre></div>
</div>
<p>If you want to use the Borland C++ compiler as the default, you could specify
this in your personal or system-wide configuration file for Distutils (see
section <a class="reference internal" href="#inst-config-files"><span class="std std-ref">Distutils Configuration Files</span></a>.)</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.embarcadero.com/products">C++Builder Compiler</a></dt>
<dd>Information about the free C++ compiler from Borland, including links to the
download pages.</dd>
<dt><a class="reference external" href="http://www.cyberus.ca/~g_will/pyExtenDL.shtml">Creating Python Extensions Using Borland’s Free Compiler</a></dt>
<dd>Document describing how to use Borland’s free command-line C++ compiler to build
Python.</dd>
</dl>
</div>
</div>
<div class="section" id="gnu-c-cygwin-mingw">
<h4>GNU C / Cygwin / MinGW<a class="headerlink" href="#gnu-c-cygwin-mingw" title="Permalink to this headline">¶</a></h4>
<p>This section describes the necessary steps to use Distutils with the GNU C/C++
compilers in their Cygwin and MinGW distributions. <a class="footnote-reference" href="#id5" id="id2">[2]</a> For a Python interpreter
that was built with Cygwin, everything should work without any of these
following steps.</p>
<p>Not all extensions can be built with MinGW or Cygwin, but many can.  Extensions
most likely to not work are those that use C++ or depend on Microsoft Visual C
extensions.</p>
<p>To let Distutils compile your extension with Cygwin you have to type:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --compiler=cygwin
</pre></div>
</div>
<p>and for Cygwin in no-cygwin mode <a class="footnote-reference" href="#id6" id="id3">[3]</a> or for MinGW type:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python setup.py build --compiler=mingw32
</pre></div>
</div>
<p>If you want to use any of these options/compilers as default, you should
consider writing it in your personal or system-wide configuration file for
Distutils (see section <a class="reference internal" href="#inst-config-files"><span class="std std-ref">Distutils Configuration Files</span></a>.)</p>
<div class="section" id="older-versions-of-python-and-mingw">
<h5>Older Versions of Python and MinGW<a class="headerlink" href="#older-versions-of-python-and-mingw" title="Permalink to this headline">¶</a></h5>
<p>The following instructions only apply if you’re using a version of Python
inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with
binutils-2.13.90-20030111-1).</p>
<p>These compilers require some special libraries.  This task is more complex than
for Borland’s C++, because there is no program to convert the library.  First
you have to create a list of symbols which the Python DLL exports. (You can find
a good program for this task at
<a class="reference external" href="https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/">https://sourceforge.net/projects/mingw/files/MinGW/Extension/pexports/</a>).</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>pexports python25.dll &gt;python25.def
</pre></div>
</div>
<p>The location of an installed <code class="file docutils literal notranslate"><span class="pre">python25.dll</span></code> will depend on the
installation options and the version and language of Windows.  In a “just for
me” installation, it will appear in the root of the installation directory.  In
a shared installation, it will be located in the system directory.</p>
<p>Then you can create from these information an import library for gcc.</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>/cygwin/bin/dlltool --dllname python25.dll --def python25.def --output-lib libpython25.a
</pre></div>
</div>
<p>The resulting library has to be placed in the same directory as
<code class="file docutils literal notranslate"><span class="pre">python25.lib</span></code>. (Should be the <code class="file docutils literal notranslate"><span class="pre">libs</span></code> directory under your Python
installation directory.)</p>
<p>If your extension uses other libraries (zlib,…) you might  have to convert
them too. The converted files have to reside in the same directories as the
normal libraries do.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://old.zope.org/Members/als/tips/win32_mingw_modules">Building Python modules on MS Windows platform with MinGW</a></dt>
<dd>Information about building the required libraries for the MinGW environment.</dd>
</dl>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This also means you could replace all existing COFF-libraries with OMF-libraries
of the same name.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Check <a class="reference external" href="https://www.sourceware.org/cygwin/">https://www.sourceware.org/cygwin/</a> and <a class="reference external" href="http://www.mingw.org/">http://www.mingw.org/</a> for more
information</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>Then you have no POSIX emulation available, but you also don’t need
<code class="file docutils literal notranslate"><span class="pre">cygwin1.dll</span></code>.</td></tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Installing Python Modules (Legacy version)</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a><ul>
<li><a class="reference internal" href="#best-case-trivial-installation">Best case: trivial installation</a></li>
<li><a class="reference internal" href="#the-new-standard-distutils">The new standard: Distutils</a></li>
</ul>
</li>
<li><a class="reference internal" href="#standard-build-and-install">Standard Build and Install</a><ul>
<li><a class="reference internal" href="#platform-variations">Platform variations</a></li>
<li><a class="reference internal" href="#splitting-the-job-up">Splitting the job up</a></li>
<li><a class="reference internal" href="#how-building-works">How building works</a></li>
<li><a class="reference internal" href="#how-installation-works">How installation works</a></li>
</ul>
</li>
<li><a class="reference internal" href="#alternate-installation">Alternate Installation</a><ul>
<li><a class="reference internal" href="#alternate-installation-the-user-scheme">Alternate installation: the user scheme</a></li>
<li><a class="reference internal" href="#alternate-installation-the-home-scheme">Alternate installation: the home scheme</a></li>
<li><a class="reference internal" href="#alternate-installation-unix-the-prefix-scheme">Alternate installation: Unix (the prefix scheme)</a></li>
<li><a class="reference internal" href="#alternate-installation-windows-the-prefix-scheme">Alternate installation: Windows (the prefix scheme)</a></li>
</ul>
</li>
<li><a class="reference internal" href="#custom-installation">Custom Installation</a><ul>
<li><a class="reference internal" href="#modifying-python-s-search-path">Modifying Python’s Search Path</a></li>
</ul>
</li>
<li><a class="reference internal" href="#distutils-configuration-files">Distutils Configuration Files</a><ul>
<li><a class="reference internal" href="#location-and-names-of-config-files">Location and names of config files</a></li>
<li><a class="reference internal" href="#syntax-of-config-files">Syntax of config files</a></li>
</ul>
</li>
<li><a class="reference internal" href="#building-extensions-tips-and-tricks">Building Extensions: Tips and Tricks</a><ul>
<li><a class="reference internal" href="#tweaking-compiler-linker-flags">Tweaking compiler/linker flags</a></li>
<li><a class="reference internal" href="#using-non-microsoft-compilers-on-windows">Using non-Microsoft compilers on Windows</a><ul>
<li><a class="reference internal" href="#borland-codegear-c">Borland/CodeGear C++</a></li>
<li><a class="reference internal" href="#gnu-c-cygwin-mingw">GNU C / Cygwin / MinGW</a><ul>
<li><a class="reference internal" href="#older-versions-of-python-and-mingw">Older Versions of Python and MinGW</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="../distutils/apiref.html"
                        title="previous chapter">10. API Reference</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/install/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../distutils/apiref.html" title="10. API Reference"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\MR�PUPUhtml/installing/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Installing Python Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python HOWTOs" href="../howto/index.html" />
    <link rel="prev" title="Distributing Python Modules" href="../distributing/index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/installing/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../howto/index.html" title="Python HOWTOs"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../distributing/index.html" title="Distributing Python Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="installing-python-modules">
<span id="installing-index"></span><h1>Installing Python Modules<a class="headerlink" href="#installing-python-modules" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Email:</th><td class="field-body"><a class="reference external" href="mailto:distutils-sig&#37;&#52;&#48;python&#46;org">distutils-sig<span>&#64;</span>python<span>&#46;</span>org</a></td>
</tr>
</tbody>
</table>
<p>As a popular open source development project, Python has an active
supporting community of contributors and users that also make their software
available for other Python developers to use under open source license terms.</p>
<p>This allows Python users to share and collaborate effectively, benefiting
from the solutions others have already created to common (and sometimes
even rare!) problems, as well as potentially contributing their own
solutions to the common pool.</p>
<p>This guide covers the installation part of the process. For a guide to
creating and sharing your own Python projects, refer to the
<a class="reference internal" href="../distributing/index.html#distributing-index"><span class="std std-ref">distribution guide</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For corporate and other institutional users, be aware that many
organisations have their own policies around using and contributing to
open source software. Please take such policies into account when making
use of the distribution and installation tools provided with Python.</p>
</div>
<div class="section" id="key-terms">
<h2>Key terms<a class="headerlink" href="#key-terms" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">pip</span></code> is the preferred installer program. Starting with Python 2.7.9, it
is included by default with the Python binary installers.</li>
<li>a virtual environment is a semi-isolated Python environment that allows
packages to be installed for use by a particular application, rather than
being installed system wide</li>
<li><code class="docutils literal notranslate"><span class="pre">virtualenv</span></code> is a third party tools for creating virtual environments, it
is defaults to installing <code class="docutils literal notranslate"><span class="pre">pip</span></code> into all created virtual environments.</li>
<li>the <a class="reference external" href="https://pypi.org">Python Packaging Index</a> is a public repository of
open source licensed packages made available for use by other Python users</li>
<li>the <a class="reference external" href="https://www.pypa.io/en/latest/">Python Packaging Authority</a> are the group of
developers and documentation authors responsible for the maintenance and
evolution of the standard packaging tools and the associated metadata and
file format standards. They maintain a variety of tools, documentation
and issue trackers on both <a class="reference external" href="https://github.com/pypa">GitHub</a> and
<a class="reference external" href="https://bitbucket.org/pypa/">BitBucket</a>.</li>
<li><code class="docutils literal notranslate"><span class="pre">distutils</span></code> is the original build and distribution system first added to
the Python standard library in 1998. While direct use of <code class="docutils literal notranslate"><span class="pre">distutils</span></code> is
being phased out, it still laid the foundation for the current packaging
and distribution infrastructure, and it not only remains part of the
standard library, but its name lives on in other ways (such as the name
of the mailing list used to coordinate Python packaging standards
development).</li>
</ul>
</div>
<div class="section" id="basic-usage">
<h2>Basic usage<a class="headerlink" href="#basic-usage" title="Permalink to this headline">¶</a></h2>
<p>The standard packaging tools are all designed to be used from the command
line.</p>
<p>The following command will install the latest version of a module and its
dependencies from the Python Packaging Index:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python -m pip install SomePackage
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>For POSIX users (including Mac OS X and Linux users), the examples in
this guide assume the use of a <a class="reference internal" href="../glossary.html#term-virtual-environment"><span class="xref std std-term">virtual environment</span></a>. You may install
<code class="docutils literal notranslate"><span class="pre">virtualenv</span></code> to provide such environments using either pip
(<code class="docutils literal notranslate"><span class="pre">pip</span> <span class="pre">install</span> <span class="pre">virtualenv</span></code>) or through your system package manager
(commonly called <code class="docutils literal notranslate"><span class="pre">virtualenv</span></code> or <code class="docutils literal notranslate"><span class="pre">python-virtualenv</span></code>).</p>
<p class="last">For Windows users, the examples in this guide assume that the option to
adjust the system PATH environment variable was selected when installing
Python.</p>
</div>
<p>It’s also possible to specify an exact or minimum version directly on the
command line. When using comparator operators such as <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> or some other
special character which get interpreted by shell, the package name and the
version should be enclosed within double quotes:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python -m pip install SomePackage==1.0.4    # specific version
python -m pip install &quot;SomePackage&gt;=1.0.4&quot;  # minimum version
</pre></div>
</div>
<p>Normally, if a suitable module is already installed, attempting to install
it again will have no effect. Upgrading existing modules must be requested
explicitly:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python -m pip install --upgrade SomePackage
</pre></div>
</div>
<p>More information and resources regarding <code class="docutils literal notranslate"><span class="pre">pip</span></code> and its capabilities can be
found in the <a class="reference external" href="https://packaging.python.org">Python Packaging User Guide</a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://packaging.python.org/en/latest/installing/">Python Packaging User Guide: Installing Python Distribution Packages</a></p>
</div>
</div>
<div class="section" id="how-do-i">
<h2>How do I …?<a class="headerlink" href="#how-do-i" title="Permalink to this headline">¶</a></h2>
<p>These are quick answers or links for some common tasks.</p>
<div class="section" id="install-pip-in-versions-of-python-prior-to-python-2-7-9">
<h3>… install <code class="docutils literal notranslate"><span class="pre">pip</span></code> in versions of Python prior to Python 2.7.9?<a class="headerlink" href="#install-pip-in-versions-of-python-prior-to-python-2-7-9" title="Permalink to this headline">¶</a></h3>
<p>Python only started bundling <code class="docutils literal notranslate"><span class="pre">pip</span></code> with Python 2.7.9. For earlier versions,
<code class="docutils literal notranslate"><span class="pre">pip</span></code> needs to be “bootstrapped” as described in the Python Packaging
User Guide.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://packaging.python.org/en/latest/installing/#requirements-for-installing-packages">Python Packaging User Guide: Requirements for Installing Packages</a></p>
</div>
</div>
<div class="section" id="install-packages-just-for-the-current-user">
<h3>… install packages just for the current user?<a class="headerlink" href="#install-packages-just-for-the-current-user" title="Permalink to this headline">¶</a></h3>
<p>Passing the <code class="docutils literal notranslate"><span class="pre">--user</span></code> option to <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">install</span></code> will install a
package just for the current user, rather than for all users of the system.</p>
</div>
<div class="section" id="install-scientific-python-packages">
<h3>… install scientific Python packages?<a class="headerlink" href="#install-scientific-python-packages" title="Permalink to this headline">¶</a></h3>
<p>A number of scientific Python packages have complex binary dependencies, and
aren’t currently easy to install using <code class="docutils literal notranslate"><span class="pre">pip</span></code> directly. At this point in
time, it will often be easier for users to install these packages by
<a class="reference external" href="https://packaging.python.org/en/latest/science/">other means</a>
rather than attempting to install them with <code class="docutils literal notranslate"><span class="pre">pip</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://packaging.python.org/en/latest/science/">Python Packaging User Guide: Installing Scientific Packages</a></p>
</div>
</div>
<div class="section" id="work-with-multiple-versions-of-python-installed-in-parallel">
<h3>… work with multiple versions of Python installed in parallel?<a class="headerlink" href="#work-with-multiple-versions-of-python-installed-in-parallel" title="Permalink to this headline">¶</a></h3>
<p>On Linux, Mac OS X and other POSIX systems, use the versioned Python commands
in combination with the <code class="docutils literal notranslate"><span class="pre">-m</span></code> switch to run the appropriate copy of
<code class="docutils literal notranslate"><span class="pre">pip</span></code>:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python2   -m pip install SomePackage  # default Python 2
python2.7 -m pip install SomePackage  # specifically Python 2.7
python3   -m pip install SomePackage  # default Python 3
python3.4 -m pip install SomePackage  # specifically Python 3.4
</pre></div>
</div>
<p>(appropriately versioned <code class="docutils literal notranslate"><span class="pre">pip</span></code> commands may also be available)</p>
<p>On Windows, use the <code class="docutils literal notranslate"><span class="pre">py</span></code> Python launcher in combination with the <code class="docutils literal notranslate"><span class="pre">-m</span></code>
switch:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>py -2   -m pip install SomePackage  # default Python 2
py -2.7 -m pip install SomePackage  # specifically Python 2.7
py -3   -m pip install SomePackage  # default Python 3
py -3.4 -m pip install SomePackage  # specifically Python 3.4
</pre></div>
</div>
</div>
</div>
<div class="section" id="common-installation-issues">
<h2>Common installation issues<a class="headerlink" href="#common-installation-issues" title="Permalink to this headline">¶</a></h2>
<div class="section" id="installing-into-the-system-python-on-linux">
<h3>Installing into the system Python on Linux<a class="headerlink" href="#installing-into-the-system-python-on-linux" title="Permalink to this headline">¶</a></h3>
<p>On Linux systems, a Python installation will typically be included as part
of the distribution. Installing into this Python installation requires
root access to the system, and may interfere with the operation of the
system package manager and other components of the system if a component
is unexpectedly upgraded using <code class="docutils literal notranslate"><span class="pre">pip</span></code>.</p>
<p>On such systems, it is often better to use a virtual environment or a
per-user installation when installing packages with <code class="docutils literal notranslate"><span class="pre">pip</span></code>.</p>
</div>
<div class="section" id="pip-not-installed">
<h3>Pip not installed<a class="headerlink" href="#pip-not-installed" title="Permalink to this headline">¶</a></h3>
<p>It is possible that <code class="docutils literal notranslate"><span class="pre">pip</span></code> does not get installed by default. One potential fix is:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>python -m ensurepip --default-pip
</pre></div>
</div>
<p>There are also additional resources for <a class="reference external" href="https://packaging.python.org/tutorials/installing-packages/#install-pip-setuptools-and-wheel">installing pip.</a></p>
</div>
<div class="section" id="installing-binary-extensions">
<h3>Installing binary extensions<a class="headerlink" href="#installing-binary-extensions" title="Permalink to this headline">¶</a></h3>
<p>Python has typically relied heavily on source based distribution, with end
users being expected to compile extension modules from source as part of
the installation process.</p>
<p>With the introduction of support for the binary <code class="docutils literal notranslate"><span class="pre">wheel</span></code> format, and the
ability to publish wheels for at least Windows and Mac OS X through the
Python Packaging Index, this problem is expected to diminish over time,
as users are more regularly able to install pre-built extensions rather
than needing to build them themselves.</p>
<p>Some of the solutions for installing <a class="reference external" href="https://packaging.python.org/en/latest/science/">scientific software</a>
that is not yet available as pre-built <code class="docutils literal notranslate"><span class="pre">wheel</span></code> files may also help with
obtaining other binary extensions without needing to build them locally.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://packaging.python.org/en/latest/extensions/">Python Packaging User Guide: Binary Extensions</a></p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Installing Python Modules</a><ul>
<li><a class="reference internal" href="#key-terms">Key terms</a></li>
<li><a class="reference internal" href="#basic-usage">Basic usage</a></li>
<li><a class="reference internal" href="#how-do-i">How do I …?</a><ul>
<li><a class="reference internal" href="#install-pip-in-versions-of-python-prior-to-python-2-7-9">… install <code class="docutils literal notranslate"><span class="pre">pip</span></code> in versions of Python prior to Python 2.7.9?</a></li>
<li><a class="reference internal" href="#install-packages-just-for-the-current-user">… install packages just for the current user?</a></li>
<li><a class="reference internal" href="#install-scientific-python-packages">… install scientific Python packages?</a></li>
<li><a class="reference internal" href="#work-with-multiple-versions-of-python-installed-in-parallel">… work with multiple versions of Python installed in parallel?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-installation-issues">Common installation issues</a><ul>
<li><a class="reference internal" href="#installing-into-the-system-python-on-linux">Installing into the system Python on Linux</a></li>
<li><a class="reference internal" href="#pip-not-installed">Pip not installed</a></li>
<li><a class="reference internal" href="#installing-binary-extensions">Installing binary extensions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="../distributing/index.html"
                        title="previous chapter">Distributing Python Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../howto/index.html"
                        title="next chapter">Python HOWTOs</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/installing/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../howto/index.html" title="Python HOWTOs"
             >next</a> |</li>
        <li class="right" >
          <a href="../distributing/index.html" title="Distributing Python Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��o=+=+html/library/__builtin__.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.3. __builtin__ — Built-in objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.4. future_builtins — Python 3 builtins" href="future_builtins.html" />
    <link rel="prev" title="28.2. sysconfig — Provide access to Python’s configuration information" href="sysconfig.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/__builtin__.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="future_builtins.html" title="28.4. future_builtins — Python 3 builtins"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sysconfig.html" title="28.2. sysconfig — Provide access to Python’s configuration information"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-__builtin__">
<span id="builtin-built-in-objects"></span><h1>28.3. <a class="reference internal" href="#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> — Built-in objects<a class="headerlink" href="#module-__builtin__" title="Permalink to this headline">¶</a></h1>
<p>This module provides direct access to all ‘built-in’ identifiers of Python; for
example, <code class="docutils literal notranslate"><span class="pre">__builtin__.open</span></code> is the full name for the built-in function
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.  See <a class="reference internal" href="functions.html#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a> and <a class="reference internal" href="constants.html#built-in-consts"><span class="std std-ref">Built-in Constants</span></a> for
documentation.</p>
<p>This module is not normally accessed explicitly by most applications, but can be
useful in modules that provide objects with the same name as a built-in value,
but in which the built-in of that name is also needed.  For example, in a module
that wants to implement an <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function that wraps the built-in
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, this module can be used directly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">__builtin__</span>

<span class="k">def</span> <span class="nf">open</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
    <span class="n">f</span> <span class="o">=</span> <span class="n">__builtin__</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">UpperCaser</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">UpperCaser</span><span class="p">:</span>
    <span class="sd">&#39;&#39;&#39;Wrapper around a file that converts output to upper-case.&#39;&#39;&#39;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_f</span> <span class="o">=</span> <span class="n">f</span>

    <span class="k">def</span> <span class="nf">read</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">count</span><span class="o">=-</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="n">count</span><span class="p">)</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>

    <span class="c1"># ...</span>
</pre></div>
</div>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Most modules have the name <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> (note the <code class="docutils literal notranslate"><span class="pre">'s'</span></code>) made available
as part of their globals.  The value of <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> is normally either
this module or the value of this modules’s <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute.  Since
this is an implementation detail, it may not be used by alternate
implementations of Python.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="sysconfig.html"
                        title="previous chapter">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="future_builtins.html"
                        title="next chapter">28.4. <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> — Python 3 builtins</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/__builtin__.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="future_builtins.html" title="28.4. future_builtins — Python 3 builtins"
             >next</a> |</li>
        <li class="right" >
          <a href="sysconfig.html" title="28.2. sysconfig — Provide access to Python’s configuration information"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\b�`9`9html/library/__future__.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.11. __future__ — Future statement definitions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.12. gc — Garbage Collector interface" href="gc.html" />
    <link rel="prev" title="28.10. traceback — Print or retrieve a stack traceback" href="traceback.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/__future__.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gc.html" title="28.12. gc — Garbage Collector interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="traceback.html" title="28.10. traceback — Print or retrieve a stack traceback"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-__future__">
<span id="future-future-statement-definitions"></span><h1>28.11. <a class="reference internal" href="#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> — Future statement definitions<a class="headerlink" href="#module-__future__" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/__future__.py">Lib/__future__.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> is a real module, and serves three purposes:</p>
<ul class="simple">
<li>To avoid confusing existing tools that analyze import statements and expect to
find the modules they’re importing.</li>
<li>To ensure that <a class="reference internal" href="../reference/simple_stmts.html#future"><span class="std std-ref">future statements</span></a> run under releases prior to
2.1 at least yield runtime exceptions (the import of <a class="reference internal" href="#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> will
fail, because there was no module of that name prior to 2.1).</li>
<li>To document when incompatible changes were introduced, and when they will be
— or were — made mandatory.  This is a form of executable documentation, and
can be inspected programmatically via importing <a class="reference internal" href="#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> and examining
its contents.</li>
</ul>
<p>Each statement in <code class="file docutils literal notranslate"><span class="pre">__future__.py</span></code> is of the form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">FeatureName</span> <span class="o">=</span> <span class="n">_Feature</span><span class="p">(</span><span class="n">OptionalRelease</span><span class="p">,</span> <span class="n">MandatoryRelease</span><span class="p">,</span>
                       <span class="n">CompilerFlag</span><span class="p">)</span>
</pre></div>
</div>
<p>where, normally, <em>OptionalRelease</em> is less than <em>MandatoryRelease</em>, and both are
5-tuples of the same form as <code class="docutils literal notranslate"><span class="pre">sys.version_info</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">PY_MAJOR_VERSION</span><span class="p">,</span> <span class="c1"># the 2 in 2.1.0a3; an int</span>
 <span class="n">PY_MINOR_VERSION</span><span class="p">,</span> <span class="c1"># the 1; an int</span>
 <span class="n">PY_MICRO_VERSION</span><span class="p">,</span> <span class="c1"># the 0; an int</span>
 <span class="n">PY_RELEASE_LEVEL</span><span class="p">,</span> <span class="c1"># &quot;alpha&quot;, &quot;beta&quot;, &quot;candidate&quot; or &quot;final&quot;; string</span>
 <span class="n">PY_RELEASE_SERIAL</span> <span class="c1"># the 3; an int</span>
<span class="p">)</span>
</pre></div>
</div>
<p><em>OptionalRelease</em> records the first release in which the feature was accepted.</p>
<p>In the case of a <em>MandatoryRelease</em> that has not yet occurred,
<em>MandatoryRelease</em> predicts the release in which the feature will become part of
the language.</p>
<p>Else <em>MandatoryRelease</em> records when the feature became part of the language; in
releases at or after that, modules no longer need a future statement to use the
feature in question, but may continue to use such imports.</p>
<p><em>MandatoryRelease</em> may also be <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning that a planned feature got
dropped.</p>
<p>Instances of class <code class="xref py py-class docutils literal notranslate"><span class="pre">_Feature</span></code> have two corresponding methods,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getOptionalRelease()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">getMandatoryRelease()</span></code>.</p>
<p><em>CompilerFlag</em> is the (bitfield) flag that should be passed in the fourth
argument to the built-in function <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> to enable the feature in
dynamically compiled code.  This flag is stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">compiler_flag</span></code>
attribute on <code class="xref py py-class docutils literal notranslate"><span class="pre">_Feature</span></code> instances.</p>
<p>No feature description will ever be deleted from <a class="reference internal" href="#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a>. Since its
introduction in Python 2.1 the following features have found their way into the
language using this mechanism:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="14%" />
<col width="16%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">feature</th>
<th class="head">optional in</th>
<th class="head">mandatory in</th>
<th class="head">effect</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>nested_scopes</td>
<td>2.1.0b1</td>
<td>2.2</td>
<td><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0227"><strong>PEP 227</strong></a>:
<em>Statically Nested Scopes</em></td>
</tr>
<tr class="row-odd"><td>generators</td>
<td>2.2.0a1</td>
<td>2.3</td>
<td><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a>:
<em>Simple Generators</em></td>
</tr>
<tr class="row-even"><td>division</td>
<td>2.2.0a2</td>
<td>3.0</td>
<td><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a>:
<em>Changing the Division Operator</em></td>
</tr>
<tr class="row-odd"><td>absolute_import</td>
<td>2.5.0a1</td>
<td>3.0</td>
<td><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a>:
<em>Imports: Multi-Line and Absolute/Relative</em></td>
</tr>
<tr class="row-even"><td>with_statement</td>
<td>2.5.0a1</td>
<td>2.6</td>
<td><span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a>:
<em>The “with” Statement</em></td>
</tr>
<tr class="row-odd"><td>print_function</td>
<td>2.6.0a2</td>
<td>3.0</td>
<td><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3105"><strong>PEP 3105</strong></a>:
<em>Make print a function</em></td>
</tr>
<tr class="row-even"><td>unicode_literals</td>
<td>2.6.0a2</td>
<td>3.0</td>
<td><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3112"><strong>PEP 3112</strong></a>:
<em>Bytes literals in Python 3000</em></td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../reference/simple_stmts.html#future"><span class="std std-ref">Future statements</span></a></dt>
<dd>How the compiler treats future imports.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="traceback.html"
                        title="previous chapter">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gc.html"
                        title="next chapter">28.12. <code class="docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/__future__.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gc.html" title="28.12. gc — Garbage Collector interface"
             >next</a> |</li>
        <li class="right" >
          <a href="traceback.html" title="28.10. traceback — Print or retrieve a stack traceback"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\11�XXhtml/library/__main__.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.5. __main__ — Top-level script environment &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.6. warnings — Warning control" href="warnings.html" />
    <link rel="prev" title="28.4. future_builtins — Python 3 builtins" href="future_builtins.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/__main__.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="warnings.html" title="28.6. warnings — Warning control"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="future_builtins.html" title="28.4. future_builtins — Python 3 builtins"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-__main__">
<span id="main-top-level-script-environment"></span><h1>28.5. <a class="reference internal" href="#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> — Top-level script environment<a class="headerlink" href="#module-__main__" title="Permalink to this headline">¶</a></h1>
<p>This module represents the (otherwise anonymous) scope in which the
interpreter’s main program executes — commands read either from standard
input, from a script file, or from an interactive prompt.  It is this
environment in which the idiomatic “conditional script” stanza causes a script
to run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="future_builtins.html"
                        title="previous chapter">28.4. <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> — Python 3 builtins</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="warnings.html"
                        title="next chapter">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/__main__.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="warnings.html" title="28.6. warnings — Warning control"
             >next</a> |</li>
        <li class="right" >
          <a href="future_builtins.html" title="28.4. future_builtins — Python 3 builtins"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ݷ&Bw�w�html/library/_winreg.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>35.3. _winreg — Windows registry access &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="35.4. winsound — Sound-playing interface for Windows" href="winsound.html" />
    <link rel="prev" title="35.2. msvcrt — Useful routines from the MS VC++ runtime" href="msvcrt.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/_winreg.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="winsound.html" title="35.4. winsound — Sound-playing interface for Windows"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="msvcrt.html" title="35.2. msvcrt — Useful routines from the MS VC++ runtime"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" accesskey="U">35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-_winreg">
<span id="winreg-windows-registry-access"></span><h1>35.3. <a class="reference internal" href="#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> — Windows registry access<a class="headerlink" href="#module-_winreg" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">winreg</span></code> in Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>These functions expose the Windows registry API to Python.  Instead of using an
integer as the registry handle, a <a class="reference internal" href="#handle-object"><span class="std std-ref">handle object</span></a> is used
to ensure that the handles are closed correctly, even if the programmer neglects
to explicitly close them.</p>
<p>This module offers the following functions:</p>
<dl class="function">
<dt id="_winreg.CloseKey">
<code class="descclassname">_winreg.</code><code class="descname">CloseKey</code><span class="sig-paren">(</span><em>hkey</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.CloseKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes a previously opened registry key.  The <em>hkey</em> argument specifies a
previously opened key.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <em>hkey</em> is not closed using this method (or via <a class="reference internal" href="#_winreg.PyHKEY.Close" title="_winreg.PyHKEY.Close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">hkey.Close()</span></code></a>),
it is closed when the <em>hkey</em> object is destroyed by Python.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="_winreg.ConnectRegistry">
<code class="descclassname">_winreg.</code><code class="descname">ConnectRegistry</code><span class="sig-paren">(</span><em>computer_name</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.ConnectRegistry" title="Permalink to this definition">¶</a></dt>
<dd><p>Establishes a connection to a predefined registry handle on another computer,
and returns a <a class="reference internal" href="#handle-object"><span class="std std-ref">handle object</span></a>.</p>
<p><em>computer_name</em> is the name of the remote computer, of the form
<code class="docutils literal notranslate"><span class="pre">r&quot;\\computername&quot;</span></code>.  If <code class="docutils literal notranslate"><span class="pre">None</span></code>, the local computer is used.</p>
<p><em>key</em> is the predefined handle to connect to.</p>
<p>The return value is the handle of the opened key. If the function fails, a
<a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.CreateKey">
<code class="descclassname">_winreg.</code><code class="descname">CreateKey</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.CreateKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates or opens the specified key, returning a
<a class="reference internal" href="#handle-object"><span class="std std-ref">handle object</span></a>.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that names the key this method opens or creates.</p>
<p>If <em>key</em> is one of the predefined keys, <em>sub_key</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code>. In that
case, the handle returned is the same key handle passed in to the function.</p>
<p>If the key already exists, this function opens the existing key.</p>
<p>The return value is the handle of the opened key. If the function fails, a
<a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.CreateKeyEx">
<code class="descclassname">_winreg.</code><code class="descname">CreateKeyEx</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="optional">[</span>, <em>res</em><span class="optional">[</span>, <em>sam</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.CreateKeyEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates or opens the specified key, returning a
<a class="reference internal" href="#handle-object"><span class="std std-ref">handle object</span></a>.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that names the key this method opens or creates.</p>
<p><em>res</em> is a reserved integer, and must be zero. The default is zero.</p>
<p><em>sam</em> is an integer that specifies an access mask that describes the desired
security access for the key.  Default is <a class="reference internal" href="#_winreg.KEY_ALL_ACCESS" title="_winreg.KEY_ALL_ACCESS"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_ALL_ACCESS</span></code></a>.  See
<a class="reference internal" href="#access-rights"><span class="std std-ref">Access Rights</span></a> for other allowed values.</p>
<p>If <em>key</em> is one of the predefined keys, <em>sub_key</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code>. In that
case, the handle returned is the same key handle passed in to the function.</p>
<p>If the key already exists, this function opens the existing key.</p>
<p>The return value is the handle of the opened key. If the function fails, a
<a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is raised.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<dl class="function">
<dt id="_winreg.DeleteKey">
<code class="descclassname">_winreg.</code><code class="descname">DeleteKey</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.DeleteKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the specified key.</p>
<p><em>key</em> is an already open key, or any one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that must be a subkey of the key identified by the <em>key</em>
parameter.  This value must not be <code class="docutils literal notranslate"><span class="pre">None</span></code>, and the key may not have subkeys.</p>
<p><em>This method can not delete keys with subkeys.</em></p>
<p>If the method succeeds, the entire key, including all of its values, is removed.
If the method fails, a <a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.DeleteKeyEx">
<code class="descclassname">_winreg.</code><code class="descname">DeleteKeyEx</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="optional">[</span>, <em>sam</em><span class="optional">[</span>, <em>res</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.DeleteKeyEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes the specified key.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#_winreg.DeleteKeyEx" title="_winreg.DeleteKeyEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">DeleteKeyEx()</span></code></a> function is implemented with the RegDeleteKeyEx
Windows API function, which is specific to 64-bit versions of Windows.
See the <a class="reference external" href="http://msdn.microsoft.com/en-us/library/ms724847%28VS.85%29.aspx">RegDeleteKeyEx documentation</a>.</p>
</div>
<p><em>key</em> is an already open key, or any one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that must be a subkey of the key identified by the
<em>key</em> parameter. This value must not be <code class="docutils literal notranslate"><span class="pre">None</span></code>, and the key may not have
subkeys.</p>
<p><em>res</em> is a reserved integer, and must be zero. The default is zero.</p>
<p><em>sam</em> is an integer that specifies an access mask that describes the desired
security access for the key.  Default is <a class="reference internal" href="#_winreg.KEY_WOW64_64KEY" title="_winreg.KEY_WOW64_64KEY"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_WOW64_64KEY</span></code></a>.  See
<a class="reference internal" href="#access-rights"><span class="std std-ref">Access Rights</span></a> for other allowed values.</p>
<p><em>This method can not delete keys with subkeys.</em></p>
<p>If the method succeeds, the entire key, including all of its values, is
removed. If the method fails, a <a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is raised.</p>
<p>On unsupported Windows versions, <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> is raised.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<dl class="function">
<dt id="_winreg.DeleteValue">
<code class="descclassname">_winreg.</code><code class="descname">DeleteValue</code><span class="sig-paren">(</span><em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.DeleteValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes a named value from a registry key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>value</em> is a string that identifies the value to remove.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.EnumKey">
<code class="descclassname">_winreg.</code><code class="descname">EnumKey</code><span class="sig-paren">(</span><em>key</em>, <em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.EnumKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Enumerates subkeys of an open registry key, returning a string.</p>
<p><em>key</em> is an already open key, or any one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>index</em> is an integer that identifies the index of the key to retrieve.</p>
<p>The function retrieves the name of one subkey each time it is called.  It is
typically called repeatedly until a <a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is
raised, indicating, no more values are available.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.EnumValue">
<code class="descclassname">_winreg.</code><code class="descname">EnumValue</code><span class="sig-paren">(</span><em>key</em>, <em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.EnumValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Enumerates values of an open registry key, returning a tuple.</p>
<p><em>key</em> is an already open key, or any one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>index</em> is an integer that identifies the index of the value to retrieve.</p>
<p>The function retrieves the name of one subkey each time it is called. It is
typically called repeatedly, until a <a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> exception is
raised, indicating no more values.</p>
<p>The result is a tuple of 3 items:</p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td>A string that identifies the value name</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td>An object that holds the value data, and
whose type depends on the underlying
registry type</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">2</span></code></td>
<td>An integer that identifies the type of the
value data (see table in docs for
<a class="reference internal" href="#_winreg.SetValueEx" title="_winreg.SetValueEx"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SetValueEx()</span></code></a>)</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="_winreg.ExpandEnvironmentStrings">
<code class="descclassname">_winreg.</code><code class="descname">ExpandEnvironmentStrings</code><span class="sig-paren">(</span><em>unicode</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.ExpandEnvironmentStrings" title="Permalink to this definition">¶</a></dt>
<dd><p>Expands environment variable placeholders <code class="docutils literal notranslate"><span class="pre">%NAME%</span></code> in unicode strings like
<a class="reference internal" href="#_winreg.REG_EXPAND_SZ" title="_winreg.REG_EXPAND_SZ"><code class="xref py py-const docutils literal notranslate"><span class="pre">REG_EXPAND_SZ</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ExpandEnvironmentStrings</span><span class="p">(</span><span class="sa">u</span><span class="s2">&quot;%windir%&quot;</span><span class="p">)</span>
<span class="go">u&quot;C:\\Windows&quot;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="_winreg.FlushKey">
<code class="descclassname">_winreg.</code><code class="descname">FlushKey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.FlushKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes all the attributes of a key to the registry.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p>It is not necessary to call <a class="reference internal" href="#_winreg.FlushKey" title="_winreg.FlushKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">FlushKey()</span></code></a> to change a key. Registry changes are
flushed to disk by the registry using its lazy flusher.  Registry changes are
also flushed to disk at system shutdown.  Unlike <a class="reference internal" href="#_winreg.CloseKey" title="_winreg.CloseKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">CloseKey()</span></code></a>, the
<a class="reference internal" href="#_winreg.FlushKey" title="_winreg.FlushKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">FlushKey()</span></code></a> method returns only when all the data has been written to the
registry. An application should only call <a class="reference internal" href="#_winreg.FlushKey" title="_winreg.FlushKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">FlushKey()</span></code></a> if it requires
absolute certainty that registry changes are on disk.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you don’t know whether a <a class="reference internal" href="#_winreg.FlushKey" title="_winreg.FlushKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">FlushKey()</span></code></a> call is required, it probably
isn’t.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="_winreg.LoadKey">
<code class="descclassname">_winreg.</code><code class="descname">LoadKey</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em>, <em>file_name</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.LoadKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a subkey under the specified key and stores registration information
from a specified file into that subkey.</p>
<p><em>key</em> is a handle returned by <a class="reference internal" href="#_winreg.ConnectRegistry" title="_winreg.ConnectRegistry"><code class="xref py py-func docutils literal notranslate"><span class="pre">ConnectRegistry()</span></code></a> or one of the constants
<a class="reference internal" href="#_winreg.HKEY_USERS" title="_winreg.HKEY_USERS"><code class="xref py py-const docutils literal notranslate"><span class="pre">HKEY_USERS</span></code></a> or <a class="reference internal" href="#_winreg.HKEY_LOCAL_MACHINE" title="_winreg.HKEY_LOCAL_MACHINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">HKEY_LOCAL_MACHINE</span></code></a>.</p>
<p><em>sub_key</em> is a string that identifies the subkey to load.</p>
<p><em>file_name</em> is the name of the file to load registry data from. This file must
have been created with the <a class="reference internal" href="#_winreg.SaveKey" title="_winreg.SaveKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">SaveKey()</span></code></a> function. Under the file allocation
table (FAT) file system, the filename may not have an extension.</p>
<p>A call to <a class="reference internal" href="#_winreg.LoadKey" title="_winreg.LoadKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">LoadKey()</span></code></a> fails if the calling process does not have the
<code class="xref py py-const docutils literal notranslate"><span class="pre">SE_RESTORE_PRIVILEGE</span></code> privilege.  Note that privileges are different
from permissions – see the <a class="reference external" href="http://msdn.microsoft.com/en-us/library/ms724889%28v=VS.85%29.aspx">RegLoadKey documentation</a> for
more details.</p>
<p>If <em>key</em> is a handle returned by <a class="reference internal" href="#_winreg.ConnectRegistry" title="_winreg.ConnectRegistry"><code class="xref py py-func docutils literal notranslate"><span class="pre">ConnectRegistry()</span></code></a>, then the path
specified in <em>file_name</em> is relative to the remote computer.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.OpenKey">
<code class="descclassname">_winreg.</code><code class="descname">OpenKey</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="optional">[</span>, <em>res</em><span class="optional">[</span>, <em>sam</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.OpenKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Opens the specified key, returning a <a class="reference internal" href="#handle-object"><span class="std std-ref">handle object</span></a>.</p>
<p><em>key</em> is an already open key, or any one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that identifies the sub_key to open.</p>
<p><em>res</em> is a reserved integer, and must be zero.  The default is zero.</p>
<p><em>sam</em> is an integer that specifies an access mask that describes the desired
security access for the key.  Default is <a class="reference internal" href="#_winreg.KEY_READ" title="_winreg.KEY_READ"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_READ</span></code></a>.  See
<a class="reference internal" href="#access-rights"><span class="std std-ref">Access Rights</span></a> for other allowed values.</p>
<p>The result is a new handle to the specified key.</p>
<p>If the function fails, <a class="reference internal" href="exceptions.html#exceptions.WindowsError" title="exceptions.WindowsError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WindowsError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.OpenKeyEx">
<code class="descclassname">_winreg.</code><code class="descname">OpenKeyEx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.OpenKeyEx" title="Permalink to this definition">¶</a></dt>
<dd><p>The functionality of <a class="reference internal" href="#_winreg.OpenKeyEx" title="_winreg.OpenKeyEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">OpenKeyEx()</span></code></a> is provided via <a class="reference internal" href="#_winreg.OpenKey" title="_winreg.OpenKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">OpenKey()</span></code></a>,
by the use of default arguments.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.QueryInfoKey">
<code class="descclassname">_winreg.</code><code class="descname">QueryInfoKey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.QueryInfoKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns information about a key, as a tuple.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p>The result is a tuple of 3 items:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td>An integer giving the number of sub keys
this key has.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td>An integer giving the number of values this
key has.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">2</span></code></td>
<td>A long integer giving when the key was last
modified (if available) as 100’s of
nanoseconds since Jan 1, 1601.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="_winreg.QueryValue">
<code class="descclassname">_winreg.</code><code class="descname">QueryValue</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.QueryValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieves the unnamed value for a key, as a string.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that holds the name of the subkey with which the value is
associated.  If this parameter is <code class="docutils literal notranslate"><span class="pre">None</span></code> or empty, the function retrieves the
value set by the <a class="reference internal" href="#_winreg.SetValue" title="_winreg.SetValue"><code class="xref py py-func docutils literal notranslate"><span class="pre">SetValue()</span></code></a> method for the key identified by <em>key</em>.</p>
<p>Values in the registry have name, type, and data components. This method
retrieves the data for a key’s first value that has a NULL name. But the
underlying API call doesn’t return the type, so always use
<a class="reference internal" href="#_winreg.QueryValueEx" title="_winreg.QueryValueEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">QueryValueEx()</span></code></a> if possible.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.QueryValueEx">
<code class="descclassname">_winreg.</code><code class="descname">QueryValueEx</code><span class="sig-paren">(</span><em>key</em>, <em>value_name</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.QueryValueEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieves the type and data for a specified value name associated with
an open registry key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>value_name</em> is a string indicating the value to query.</p>
<p>The result is a tuple of 2 items:</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td>The value of the registry item.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td>An integer giving the registry type for
this value (see table in docs for
<a class="reference internal" href="#_winreg.SetValueEx" title="_winreg.SetValueEx"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SetValueEx()</span></code></a>)</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="_winreg.SaveKey">
<code class="descclassname">_winreg.</code><code class="descname">SaveKey</code><span class="sig-paren">(</span><em>key</em>, <em>file_name</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.SaveKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Saves the specified key, and all its subkeys to the specified file.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>file_name</em> is the name of the file to save registry data to.  This file
cannot already exist. If this filename includes an extension, it cannot be
used on file allocation table (FAT) file systems by the <a class="reference internal" href="#_winreg.LoadKey" title="_winreg.LoadKey"><code class="xref py py-meth docutils literal notranslate"><span class="pre">LoadKey()</span></code></a>
method.</p>
<p>If <em>key</em> represents a key on a remote computer, the path described by
<em>file_name</em> is relative to the remote computer. The caller of this method must
possess the <code class="xref py py-const docutils literal notranslate"><span class="pre">SeBackupPrivilege</span></code> security privilege.  Note that
privileges are different than permissions – see the
<a class="reference external" href="http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx">Conflicts Between User Rights and Permissions documentation</a>
for more details.</p>
<p>This function passes NULL for <em>security_attributes</em> to the API.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.SetValue">
<code class="descclassname">_winreg.</code><code class="descname">SetValue</code><span class="sig-paren">(</span><em>key</em>, <em>sub_key</em>, <em>type</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.SetValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Associates a value with a specified key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>sub_key</em> is a string that names the subkey with which the value is associated.</p>
<p><em>type</em> is an integer that specifies the type of the data. Currently this must be
<a class="reference internal" href="#_winreg.REG_SZ" title="_winreg.REG_SZ"><code class="xref py py-const docutils literal notranslate"><span class="pre">REG_SZ</span></code></a>, meaning only strings are supported.  Use the <a class="reference internal" href="#_winreg.SetValueEx" title="_winreg.SetValueEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">SetValueEx()</span></code></a>
function for support for other data types.</p>
<p><em>value</em> is a string that specifies the new value.</p>
<p>If the key specified by the <em>sub_key</em> parameter does not exist, the SetValue
function creates it.</p>
<p>Value lengths are limited by available memory. Long values (more than 2048
bytes) should be stored as files with the filenames stored in the configuration
registry.  This helps the registry perform efficiently.</p>
<p>The key identified by the <em>key</em> parameter must have been opened with
<a class="reference internal" href="#_winreg.KEY_SET_VALUE" title="_winreg.KEY_SET_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_SET_VALUE</span></code></a> access.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.SetValueEx">
<code class="descclassname">_winreg.</code><code class="descname">SetValueEx</code><span class="sig-paren">(</span><em>key</em>, <em>value_name</em>, <em>reserved</em>, <em>type</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.SetValueEx" title="Permalink to this definition">¶</a></dt>
<dd><p>Stores data in the value field of an open registry key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p><em>value_name</em> is a string that names the subkey with which the value is
associated.</p>
<p><em>type</em> is an integer that specifies the type of the data. See
<a class="reference internal" href="#value-types"><span class="std std-ref">Value Types</span></a> for the available types.</p>
<p><em>reserved</em> can be anything – zero is always passed to the API.</p>
<p><em>value</em> is a string that specifies the new value.</p>
<p>This method can also set additional value and type information for the specified
key.  The key identified by the key parameter must have been opened with
<a class="reference internal" href="#_winreg.KEY_SET_VALUE" title="_winreg.KEY_SET_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_SET_VALUE</span></code></a> access.</p>
<p>To open the key, use the <a class="reference internal" href="#_winreg.CreateKey" title="_winreg.CreateKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">CreateKey()</span></code></a> or <a class="reference internal" href="#_winreg.OpenKey" title="_winreg.OpenKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">OpenKey()</span></code></a> methods.</p>
<p>Value lengths are limited by available memory. Long values (more than 2048
bytes) should be stored as files with the filenames stored in the configuration
registry.  This helps the registry perform efficiently.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.DisableReflectionKey">
<code class="descclassname">_winreg.</code><code class="descname">DisableReflectionKey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.DisableReflectionKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Disables registry reflection for 32-bit processes running on a 64-bit
operating system.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p>Will generally raise <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if executed on a 32-bit
operating system.</p>
<p>If the key is not on the reflection list, the function succeeds but has no
effect. Disabling reflection for a key does not affect reflection of any
subkeys.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.EnableReflectionKey">
<code class="descclassname">_winreg.</code><code class="descname">EnableReflectionKey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.EnableReflectionKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Restores registry reflection for the specified disabled key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p>Will generally raise <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if executed on a 32-bit
operating system.</p>
<p>Restoring reflection for a key does not affect reflection of any subkeys.</p>
</dd></dl>

<dl class="function">
<dt id="_winreg.QueryReflectionKey">
<code class="descclassname">_winreg.</code><code class="descname">QueryReflectionKey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.QueryReflectionKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Determines the reflection state for the specified key.</p>
<p><em>key</em> is an already open key, or one of the predefined
<a class="reference internal" href="#hkey-constants"><span class="std std-ref">HKEY_* constants</span></a>.</p>
<p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if reflection is disabled.</p>
<p>Will generally raise <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if executed on a 32-bit
operating system.</p>
</dd></dl>

<div class="section" id="constants">
<span id="id1"></span><h2>35.3.1. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h2>
<p>The following constants are defined for use in many <a class="reference internal" href="#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> functions.</p>
<div class="section" id="hkey-constants">
<span id="id2"></span><h3>35.3.1.1. HKEY_* Constants<a class="headerlink" href="#hkey-constants" title="Permalink to this headline">¶</a></h3>
<dl class="data">
<dt id="_winreg.HKEY_CLASSES_ROOT">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_CLASSES_ROOT</code><a class="headerlink" href="#_winreg.HKEY_CLASSES_ROOT" title="Permalink to this definition">¶</a></dt>
<dd><p>Registry entries subordinate to this key define types (or classes) of
documents and the properties associated with those types. Shell and
COM applications use the information stored under this key.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_CURRENT_USER">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_CURRENT_USER</code><a class="headerlink" href="#_winreg.HKEY_CURRENT_USER" title="Permalink to this definition">¶</a></dt>
<dd><p>Registry entries subordinate to this key define the preferences of
the current user. These preferences include the settings of
environment variables, data about program groups, colors, printers,
network connections, and application preferences.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_LOCAL_MACHINE">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_LOCAL_MACHINE</code><a class="headerlink" href="#_winreg.HKEY_LOCAL_MACHINE" title="Permalink to this definition">¶</a></dt>
<dd><p>Registry entries subordinate to this key define the physical state
of the computer, including data about the bus type, system memory,
and installed hardware and software.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_USERS">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_USERS</code><a class="headerlink" href="#_winreg.HKEY_USERS" title="Permalink to this definition">¶</a></dt>
<dd><p>Registry entries subordinate to this key define the default user
configuration for new users on the local computer and the user
configuration for the current user.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_PERFORMANCE_DATA">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_PERFORMANCE_DATA</code><a class="headerlink" href="#_winreg.HKEY_PERFORMANCE_DATA" title="Permalink to this definition">¶</a></dt>
<dd><p>Registry entries subordinate to this key allow you to access
performance data. The data is not actually stored in the registry;
the registry functions cause the system to collect the data from
its source.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_CURRENT_CONFIG">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_CURRENT_CONFIG</code><a class="headerlink" href="#_winreg.HKEY_CURRENT_CONFIG" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains information about the current hardware profile of the
local computer system.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.HKEY_DYN_DATA">
<code class="descclassname">_winreg.</code><code class="descname">HKEY_DYN_DATA</code><a class="headerlink" href="#_winreg.HKEY_DYN_DATA" title="Permalink to this definition">¶</a></dt>
<dd><p>This key is not used in versions of Windows after 98.</p>
</dd></dl>

</div>
<div class="section" id="access-rights">
<span id="id3"></span><h3>35.3.1.2. Access Rights<a class="headerlink" href="#access-rights" title="Permalink to this headline">¶</a></h3>
<p>For more information, see <a class="reference external" href="http://msdn.microsoft.com/en-us/library/ms724878%28v=VS.85%29.aspx">Registry Key Security and Access</a>.</p>
<dl class="data">
<dt id="_winreg.KEY_ALL_ACCESS">
<code class="descclassname">_winreg.</code><code class="descname">KEY_ALL_ACCESS</code><a class="headerlink" href="#_winreg.KEY_ALL_ACCESS" title="Permalink to this definition">¶</a></dt>
<dd><p>Combines the STANDARD_RIGHTS_REQUIRED, <a class="reference internal" href="#_winreg.KEY_QUERY_VALUE" title="_winreg.KEY_QUERY_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_QUERY_VALUE</span></code></a>,
<a class="reference internal" href="#_winreg.KEY_SET_VALUE" title="_winreg.KEY_SET_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_SET_VALUE</span></code></a>, <a class="reference internal" href="#_winreg.KEY_CREATE_SUB_KEY" title="_winreg.KEY_CREATE_SUB_KEY"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_CREATE_SUB_KEY</span></code></a>,
<a class="reference internal" href="#_winreg.KEY_ENUMERATE_SUB_KEYS" title="_winreg.KEY_ENUMERATE_SUB_KEYS"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_ENUMERATE_SUB_KEYS</span></code></a>, <a class="reference internal" href="#_winreg.KEY_NOTIFY" title="_winreg.KEY_NOTIFY"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_NOTIFY</span></code></a>,
and <a class="reference internal" href="#_winreg.KEY_CREATE_LINK" title="_winreg.KEY_CREATE_LINK"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_CREATE_LINK</span></code></a> access rights.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_WRITE">
<code class="descclassname">_winreg.</code><code class="descname">KEY_WRITE</code><a class="headerlink" href="#_winreg.KEY_WRITE" title="Permalink to this definition">¶</a></dt>
<dd><p>Combines the STANDARD_RIGHTS_WRITE, <a class="reference internal" href="#_winreg.KEY_SET_VALUE" title="_winreg.KEY_SET_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_SET_VALUE</span></code></a>, and
<a class="reference internal" href="#_winreg.KEY_CREATE_SUB_KEY" title="_winreg.KEY_CREATE_SUB_KEY"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_CREATE_SUB_KEY</span></code></a> access rights.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_READ">
<code class="descclassname">_winreg.</code><code class="descname">KEY_READ</code><a class="headerlink" href="#_winreg.KEY_READ" title="Permalink to this definition">¶</a></dt>
<dd><p>Combines the STANDARD_RIGHTS_READ, <a class="reference internal" href="#_winreg.KEY_QUERY_VALUE" title="_winreg.KEY_QUERY_VALUE"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_QUERY_VALUE</span></code></a>,
<a class="reference internal" href="#_winreg.KEY_ENUMERATE_SUB_KEYS" title="_winreg.KEY_ENUMERATE_SUB_KEYS"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_ENUMERATE_SUB_KEYS</span></code></a>, and <a class="reference internal" href="#_winreg.KEY_NOTIFY" title="_winreg.KEY_NOTIFY"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_NOTIFY</span></code></a> values.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_EXECUTE">
<code class="descclassname">_winreg.</code><code class="descname">KEY_EXECUTE</code><a class="headerlink" href="#_winreg.KEY_EXECUTE" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#_winreg.KEY_READ" title="_winreg.KEY_READ"><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_READ</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_QUERY_VALUE">
<code class="descclassname">_winreg.</code><code class="descname">KEY_QUERY_VALUE</code><a class="headerlink" href="#_winreg.KEY_QUERY_VALUE" title="Permalink to this definition">¶</a></dt>
<dd><p>Required to query the values of a registry key.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_SET_VALUE">
<code class="descclassname">_winreg.</code><code class="descname">KEY_SET_VALUE</code><a class="headerlink" href="#_winreg.KEY_SET_VALUE" title="Permalink to this definition">¶</a></dt>
<dd><p>Required to create, delete, or set a registry value.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_CREATE_SUB_KEY">
<code class="descclassname">_winreg.</code><code class="descname">KEY_CREATE_SUB_KEY</code><a class="headerlink" href="#_winreg.KEY_CREATE_SUB_KEY" title="Permalink to this definition">¶</a></dt>
<dd><p>Required to create a subkey of a registry key.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_ENUMERATE_SUB_KEYS">
<code class="descclassname">_winreg.</code><code class="descname">KEY_ENUMERATE_SUB_KEYS</code><a class="headerlink" href="#_winreg.KEY_ENUMERATE_SUB_KEYS" title="Permalink to this definition">¶</a></dt>
<dd><p>Required to enumerate the subkeys of a registry key.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_NOTIFY">
<code class="descclassname">_winreg.</code><code class="descname">KEY_NOTIFY</code><a class="headerlink" href="#_winreg.KEY_NOTIFY" title="Permalink to this definition">¶</a></dt>
<dd><p>Required to request change notifications for a registry key or for
subkeys of a registry key.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_CREATE_LINK">
<code class="descclassname">_winreg.</code><code class="descname">KEY_CREATE_LINK</code><a class="headerlink" href="#_winreg.KEY_CREATE_LINK" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for system use.</p>
</dd></dl>

<div class="section" id="bit-specific">
<span id="bit-access-rights"></span><h4>35.3.1.2.1. 64-bit Specific<a class="headerlink" href="#bit-specific" title="Permalink to this headline">¶</a></h4>
<p>For more information, see <a class="reference external" href="http://msdn.microsoft.com/en-us/library/aa384129(v=VS.85).aspx">Accessing an Alternate Registry View</a>.</p>
<dl class="data">
<dt id="_winreg.KEY_WOW64_64KEY">
<code class="descclassname">_winreg.</code><code class="descname">KEY_WOW64_64KEY</code><a class="headerlink" href="#_winreg.KEY_WOW64_64KEY" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates that an application on 64-bit Windows should operate on
the 64-bit registry view.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.KEY_WOW64_32KEY">
<code class="descclassname">_winreg.</code><code class="descname">KEY_WOW64_32KEY</code><a class="headerlink" href="#_winreg.KEY_WOW64_32KEY" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates that an application on 64-bit Windows should operate on
the 32-bit registry view.</p>
</dd></dl>

</div>
</div>
<div class="section" id="value-types">
<span id="id4"></span><h3>35.3.1.3. Value Types<a class="headerlink" href="#value-types" title="Permalink to this headline">¶</a></h3>
<p>For more information, see <a class="reference external" href="http://msdn.microsoft.com/en-us/library/ms724884%28v=VS.85%29.aspx">Registry Value Types</a>.</p>
<dl class="data">
<dt id="_winreg.REG_BINARY">
<code class="descclassname">_winreg.</code><code class="descname">REG_BINARY</code><a class="headerlink" href="#_winreg.REG_BINARY" title="Permalink to this definition">¶</a></dt>
<dd><p>Binary data in any form.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_DWORD">
<code class="descclassname">_winreg.</code><code class="descname">REG_DWORD</code><a class="headerlink" href="#_winreg.REG_DWORD" title="Permalink to this definition">¶</a></dt>
<dd><p>32-bit number.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_DWORD_LITTLE_ENDIAN">
<code class="descclassname">_winreg.</code><code class="descname">REG_DWORD_LITTLE_ENDIAN</code><a class="headerlink" href="#_winreg.REG_DWORD_LITTLE_ENDIAN" title="Permalink to this definition">¶</a></dt>
<dd><p>A 32-bit number in little-endian format.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_DWORD_BIG_ENDIAN">
<code class="descclassname">_winreg.</code><code class="descname">REG_DWORD_BIG_ENDIAN</code><a class="headerlink" href="#_winreg.REG_DWORD_BIG_ENDIAN" title="Permalink to this definition">¶</a></dt>
<dd><p>A 32-bit number in big-endian format.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_EXPAND_SZ">
<code class="descclassname">_winreg.</code><code class="descname">REG_EXPAND_SZ</code><a class="headerlink" href="#_winreg.REG_EXPAND_SZ" title="Permalink to this definition">¶</a></dt>
<dd><p>Null-terminated string containing references to environment
variables (<code class="docutils literal notranslate"><span class="pre">%PATH%</span></code>).</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_LINK">
<code class="descclassname">_winreg.</code><code class="descname">REG_LINK</code><a class="headerlink" href="#_winreg.REG_LINK" title="Permalink to this definition">¶</a></dt>
<dd><p>A Unicode symbolic link.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_MULTI_SZ">
<code class="descclassname">_winreg.</code><code class="descname">REG_MULTI_SZ</code><a class="headerlink" href="#_winreg.REG_MULTI_SZ" title="Permalink to this definition">¶</a></dt>
<dd><p>A sequence of null-terminated strings, terminated by two null characters.
(Python handles this termination automatically.)</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_NONE">
<code class="descclassname">_winreg.</code><code class="descname">REG_NONE</code><a class="headerlink" href="#_winreg.REG_NONE" title="Permalink to this definition">¶</a></dt>
<dd><p>No defined value type.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_RESOURCE_LIST">
<code class="descclassname">_winreg.</code><code class="descname">REG_RESOURCE_LIST</code><a class="headerlink" href="#_winreg.REG_RESOURCE_LIST" title="Permalink to this definition">¶</a></dt>
<dd><p>A device-driver resource list.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_FULL_RESOURCE_DESCRIPTOR">
<code class="descclassname">_winreg.</code><code class="descname">REG_FULL_RESOURCE_DESCRIPTOR</code><a class="headerlink" href="#_winreg.REG_FULL_RESOURCE_DESCRIPTOR" title="Permalink to this definition">¶</a></dt>
<dd><p>A hardware setting.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_RESOURCE_REQUIREMENTS_LIST">
<code class="descclassname">_winreg.</code><code class="descname">REG_RESOURCE_REQUIREMENTS_LIST</code><a class="headerlink" href="#_winreg.REG_RESOURCE_REQUIREMENTS_LIST" title="Permalink to this definition">¶</a></dt>
<dd><p>A hardware resource list.</p>
</dd></dl>

<dl class="data">
<dt id="_winreg.REG_SZ">
<code class="descclassname">_winreg.</code><code class="descname">REG_SZ</code><a class="headerlink" href="#_winreg.REG_SZ" title="Permalink to this definition">¶</a></dt>
<dd><p>A null-terminated string.</p>
</dd></dl>

</div>
</div>
<div class="section" id="registry-handle-objects">
<span id="handle-object"></span><h2>35.3.2. Registry Handle Objects<a class="headerlink" href="#registry-handle-objects" title="Permalink to this headline">¶</a></h2>
<p>This object wraps a Windows HKEY object, automatically closing it when the
object is destroyed.  To guarantee cleanup, you can call either the
<a class="reference internal" href="#_winreg.PyHKEY.Close" title="_winreg.PyHKEY.Close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Close()</span></code></a> method on the object, or the <a class="reference internal" href="#_winreg.CloseKey" title="_winreg.CloseKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">CloseKey()</span></code></a> function.</p>
<p>All registry functions in this module return one of these objects.</p>
<p>All registry functions in this module which accept a handle object also accept
an integer, however, use of the handle object is encouraged.</p>
<p>Handle objects provide semantics for <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a> – thus:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">handle</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Yes&quot;</span>
</pre></div>
</div>
<p>will print <code class="docutils literal notranslate"><span class="pre">Yes</span></code> if the handle is currently valid (has not been closed or
detached).</p>
<p>The object also support comparison semantics, so handle objects will compare
true if they both reference the same underlying Windows handle value.</p>
<p>Handle objects can be converted to an integer (e.g., using the built-in
<a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> function), in which case the underlying Windows handle value is
returned.  You can also use the <a class="reference internal" href="#_winreg.PyHKEY.Detach" title="_winreg.PyHKEY.Detach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Detach()</span></code></a> method to return the
integer handle, and also disconnect the Windows handle from the handle object.</p>
<dl class="method">
<dt id="_winreg.PyHKEY.Close">
<code class="descclassname">PyHKEY.</code><code class="descname">Close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.PyHKEY.Close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the underlying Windows handle.</p>
<p>If the handle is already closed, no error is raised.</p>
</dd></dl>

<dl class="method">
<dt id="_winreg.PyHKEY.Detach">
<code class="descclassname">PyHKEY.</code><code class="descname">Detach</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.PyHKEY.Detach" title="Permalink to this definition">¶</a></dt>
<dd><p>Detaches the Windows handle from the handle object.</p>
<p>The result is an integer (or long on 64 bit Windows) that holds the value of the
handle before it is detached.  If the handle is already detached or closed, this
will return zero.</p>
<p>After calling this function, the handle is effectively invalidated, but the
handle is not closed.  You would call this function when you need the
underlying Win32 handle to exist beyond the lifetime of the handle object.</p>
</dd></dl>

<dl class="method">
<dt id="_winreg.PyHKEY.__enter__">
<code class="descclassname">PyHKEY.</code><code class="descname">__enter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.PyHKEY.__enter__" title="Permalink to this definition">¶</a></dt>
<dt id="_winreg.PyHKEY.__exit__">
<code class="descclassname">PyHKEY.</code><code class="descname">__exit__</code><span class="sig-paren">(</span><em>*exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#_winreg.PyHKEY.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>The HKEY object implements <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> and thus supports the context protocol for the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">OpenKey</span><span class="p">(</span><span class="n">HKEY_LOCAL_MACHINE</span><span class="p">,</span> <span class="s2">&quot;foo&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">key</span><span class="p">:</span>
    <span class="o">...</span>  <span class="c1"># work with key</span>
</pre></div>
</div>
<p>will automatically close <em>key</em> when control leaves the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> block.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a><ul>
<li><a class="reference internal" href="#constants">35.3.1. Constants</a><ul>
<li><a class="reference internal" href="#hkey-constants">35.3.1.1. HKEY_* Constants</a></li>
<li><a class="reference internal" href="#access-rights">35.3.1.2. Access Rights</a><ul>
<li><a class="reference internal" href="#bit-specific">35.3.1.2.1. 64-bit Specific</a></li>
</ul>
</li>
<li><a class="reference internal" href="#value-types">35.3.1.3. Value Types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#registry-handle-objects">35.3.2. Registry Handle Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="msvcrt.html"
                        title="previous chapter">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="winsound.html"
                        title="next chapter">35.4. <code class="docutils literal notranslate"><span class="pre">winsound</span></code> — Sound-playing interface for Windows</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/_winreg.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="winsound.html" title="35.4. winsound — Sound-playing interface for Windows"
             >next</a> |</li>
        <li class="right" >
          <a href="msvcrt.html" title="35.2. msvcrt — Useful routines from the MS VC++ runtime"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" >35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\b{�S�d�dhtml/library/abc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.8. abc — Abstract Base Classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.9. atexit — Exit handlers" href="atexit.html" />
    <link rel="prev" title="28.7. contextlib — Utilities for with-statement contexts" href="contextlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/abc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="atexit.html" title="28.9. atexit — Exit handlers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-abc">
<span id="abc-abstract-base-classes"></span><h1>28.8. <a class="reference internal" href="#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> — Abstract Base Classes<a class="headerlink" href="#module-abc" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/abc.py">Lib/abc.py</a></p>
<hr class="docutils" />
<p>This module provides the infrastructure for defining <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base
classes</span></a> (ABCs) in Python, as outlined in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>; see the PEP for why this
was added to Python. (See also <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3141"><strong>PEP 3141</strong></a> and the <a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module
regarding a type hierarchy for numbers based on ABCs.)</p>
<p>The <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module has some concrete classes that derive from
ABCs; these can, of course, be further derived. In addition, the
<a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module has some ABCs that can be used to test whether
a class or instance provides a particular interface, for example, if it is
hashable or if it is a mapping.</p>
<p>This module provides the following class:</p>
<dl class="class">
<dt id="abc.ABCMeta">
<em class="property">class </em><code class="descclassname">abc.</code><code class="descname">ABCMeta</code><a class="headerlink" href="#abc.ABCMeta" title="Permalink to this definition">¶</a></dt>
<dd><p>Metaclass for defining Abstract Base Classes (ABCs).</p>
<p>Use this metaclass to create an ABC.  An ABC can be subclassed directly, and
then acts as a mix-in class.  You can also register unrelated concrete
classes (even built-in classes) and unrelated ABCs as “virtual subclasses” –
these and their descendants will be considered subclasses of the registering
ABC by the built-in <a class="reference internal" href="functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> function, but the registering ABC
won’t show up in their MRO (Method Resolution Order) nor will method
implementations defined by the registering ABC be callable (not even via
<a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>). <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<p>Classes created with a metaclass of <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> have the following method:</p>
<dl class="method">
<dt id="abc.ABCMeta.register">
<code class="descname">register</code><span class="sig-paren">(</span><em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register <em>subclass</em> as a “virtual subclass” of this ABC. For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="k">import</span> <span class="n">ABCMeta</span>

<span class="k">class</span> <span class="nc">MyABC</span><span class="p">:</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>

<span class="n">MyABC</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span>

<span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">MyABC</span><span class="p">)</span>
<span class="k">assert</span> <span class="nb">isinstance</span><span class="p">((),</span> <span class="n">MyABC</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<p>You can also override this method in an abstract base class:</p>
<dl class="method">
<dt id="abc.ABCMeta.__subclasshook__">
<code class="descname">__subclasshook__</code><span class="sig-paren">(</span><em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.ABCMeta.__subclasshook__" title="Permalink to this definition">¶</a></dt>
<dd><p>(Must be defined as a class method.)</p>
<p>Check whether <em>subclass</em> is considered a subclass of this ABC.  This means
that you can customize the behavior of <code class="docutils literal notranslate"><span class="pre">issubclass</span></code> further without the
need to call <a class="reference internal" href="#abc.ABCMeta.register" title="abc.ABCMeta.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> on every class you want to consider a
subclass of the ABC.  (This class method is called from the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code> method of the ABC.)</p>
<p>This method should return <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="docutils literal notranslate"><span class="pre">False</span></code> or <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>.  If
it returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the <em>subclass</em> is considered a subclass of this ABC.
If it returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, the <em>subclass</em> is not considered a subclass of
this ABC, even if it would normally be one.  If it returns
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, the subclass check is continued with the usual
mechanism.</p>
</dd></dl>

<p>For a demonstration of these concepts, look at this example ABC definition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">MyIterable</span><span class="p">:</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>

    <span class="nd">@abstractmethod</span>
    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">while</span> <span class="kc">False</span><span class="p">:</span>
            <span class="k">yield</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">get_iterator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="fm">__iter__</span><span class="p">()</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">__subclasshook__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">C</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">cls</span> <span class="ow">is</span> <span class="n">MyIterable</span><span class="p">:</span>
            <span class="k">if</span> <span class="nb">any</span><span class="p">(</span><span class="s2">&quot;__iter__&quot;</span> <span class="ow">in</span> <span class="n">B</span><span class="o">.</span><span class="vm">__dict__</span> <span class="k">for</span> <span class="n">B</span> <span class="ow">in</span> <span class="n">C</span><span class="o">.</span><span class="vm">__mro__</span><span class="p">):</span>
                <span class="k">return</span> <span class="kc">True</span>
        <span class="k">return</span> <span class="bp">NotImplemented</span>

<span class="n">MyIterable</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span>
</pre></div>
</div>
<p>The ABC <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> defines the standard iterable method,
<a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, as an abstract method.  The implementation given
here can still be called from subclasses.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_iterator()</span></code> method
is also part of the <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> abstract base class, but it does not have
to be overridden in non-abstract derived classes.</p>
<p>The <a class="reference internal" href="#abc.ABCMeta.__subclasshook__" title="abc.ABCMeta.__subclasshook__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasshook__()</span></code></a> class method defined here says that any class
that has an <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method in its
<a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (or in that of one of its base classes, accessed
via the <a class="reference internal" href="stdtypes.html#class.__mro__" title="class.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a> list) is considered a <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code> too.</p>
<p>Finally, the last line makes <code class="docutils literal notranslate"><span class="pre">Foo</span></code> a virtual subclass of <code class="docutils literal notranslate"><span class="pre">MyIterable</span></code>,
even though it does not define an <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method (it uses
the old-style iterable protocol, defined in terms of <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>).  Note that this will not make <code class="docutils literal notranslate"><span class="pre">get_iterator</span></code>
available as a method of <code class="docutils literal notranslate"><span class="pre">Foo</span></code>, so it is provided separately.</p>
</dd></dl>

<p>It also provides the following decorators:</p>
<dl class="function">
<dt id="abc.abstractmethod">
<code class="descclassname">abc.</code><code class="descname">abstractmethod</code><span class="sig-paren">(</span><em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#abc.abstractmethod" title="Permalink to this definition">¶</a></dt>
<dd><p>A decorator indicating abstract methods.</p>
<p>Using this decorator requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> or
is derived from it.
A class that has a metaclass derived from <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a>
cannot be instantiated unless all of its abstract methods and
properties are overridden.
The abstract methods can be called using any of the normal ‘super’ call
mechanisms.</p>
<p>Dynamically adding abstract methods to a class, or attempting to modify the
abstraction status of a method or class once it is created, are not
supported.  The <a class="reference internal" href="#abc.abstractmethod" title="abc.abstractmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">abstractmethod()</span></code></a> only affects subclasses derived using
regular inheritance; “virtual subclasses” registered with the ABC’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method are not affected.</p>
<p>Usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
    <span class="nd">@abstractmethod</span>
    <span class="k">def</span> <span class="nf">my_abstract_method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="o">...</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike Java abstract methods, these abstract
methods may have an implementation. This implementation can be
called via the <a class="reference internal" href="functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> mechanism from the class that
overrides it.  This could be useful as an end-point for a
super-call in a framework that uses cooperative
multiple-inheritance.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="abc.abstractproperty">
<code class="descclassname">abc.</code><code class="descname">abstractproperty</code><span class="sig-paren">(</span><span class="optional">[</span><em>fget</em><span class="optional">[</span>, <em>fset</em><span class="optional">[</span>, <em>fdel</em><span class="optional">[</span>, <em>doc</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#abc.abstractproperty" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of the built-in <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a>, indicating an abstract property.</p>
<p>Using this function requires that the class’s metaclass is <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> or
is derived from it.
A class that has a metaclass derived from <a class="reference internal" href="#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code></a> cannot be
instantiated unless all of its abstract methods and properties are overridden.
The abstract properties can be called using any of the normal
‘super’ call mechanisms.</p>
<p>Usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
    <span class="nd">@abstractproperty</span>
    <span class="k">def</span> <span class="nf">my_abstract_property</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>This defines a read-only property; you can also define a read-write abstract
property using the ‘long’ form of property declaration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>
    <span class="k">def</span> <span class="nf">getx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span>
    <span class="k">def</span> <span class="nf">setx</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="o">...</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">abstractproperty</span><span class="p">(</span><span class="n">getx</span><span class="p">,</span> <span class="n">setx</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>C++ programmers should note that Python’s virtual base class
concept is not the same as C++’s.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="contextlib.html"
                        title="previous chapter">28.7. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="atexit.html"
                        title="next chapter">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/abc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="atexit.html" title="28.9. atexit — Exit handlers"
             >next</a> |</li>
        <li class="right" >
          <a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��dyT7T7html/library/aepack.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38.3. aepack — Conversion between Python variables and AppleEvent data containers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38.4. aetypes — AppleEvent objects" href="aetypes.html" />
    <link rel="prev" title="38.2. aetools — OSA client support" href="aetools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/aepack.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aetypes.html" title="38.4. aetypes — AppleEvent objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="aetools.html" title="38.2. aetools — OSA client support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" accesskey="U">38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-aepack">
<span id="aepack-conversion-between-python-variables-and-appleevent-data-containers"></span><h1>38.3. <a class="reference internal" href="#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a> — Conversion between Python variables and AppleEvent data containers<a class="headerlink" href="#module-aepack" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a> module defines functions for converting (packing) Python
variables to AppleEvent descriptors and back (unpacking). Within Python the
AppleEvent descriptor is handled by Python objects of built-in type
<code class="xref py py-class docutils literal notranslate"><span class="pre">AEDesc</span></code>, defined in module <a class="reference internal" href="carbon.html#module-Carbon.AE" title="Carbon.AE: Interface to the Apple Events toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.AE</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>The <a class="reference internal" href="#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="aepack.pack">
<code class="descclassname">aepack.</code><code class="descname">pack</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>forcetype</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aepack.pack" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an <code class="xref py py-class docutils literal notranslate"><span class="pre">AEDesc</span></code> object  containing a conversion of Python value x. If
<em>forcetype</em> is provided it specifies the descriptor type of the result.
Otherwise, a default mapping of Python types to Apple Event descriptor types is
used, as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="33%" />
<col width="67%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Python type</th>
<th class="head">descriptor type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code></td>
<td>typeFSS</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">FSRef</span></code></td>
<td>typeFSRef</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Alias</span></code></td>
<td>typeAlias</td>
</tr>
<tr class="row-odd"><td>integer</td>
<td>typeLong (32 bit integer)</td>
</tr>
<tr class="row-even"><td>float</td>
<td>typeFloat (64 bit floating point)</td>
</tr>
<tr class="row-odd"><td>string</td>
<td>typeText</td>
</tr>
<tr class="row-even"><td>unicode</td>
<td>typeUnicodeText</td>
</tr>
<tr class="row-odd"><td>list</td>
<td>typeAEList</td>
</tr>
<tr class="row-even"><td>dictionary</td>
<td>typeAERecord</td>
</tr>
<tr class="row-odd"><td>instance</td>
<td><em>see below</em></td>
</tr>
</tbody>
</table>
<p>If <em>x</em> is a Python instance then this function attempts to call an
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__aepack__()</span></code> method.  This method should return an <code class="xref py py-class docutils literal notranslate"><span class="pre">AEDesc</span></code> object.</p>
<p>If the conversion <em>x</em> is not defined above, this function returns the Python
string representation of a value (the repr() function) encoded as a text
descriptor.</p>
</dd></dl>

<dl class="function">
<dt id="aepack.unpack">
<code class="descclassname">aepack.</code><code class="descname">unpack</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>formodulename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aepack.unpack" title="Permalink to this definition">¶</a></dt>
<dd><p><em>x</em> must be an object of type <code class="xref py py-class docutils literal notranslate"><span class="pre">AEDesc</span></code>. This function returns a Python
object representation of the data in the Apple Event descriptor <em>x</em>. Simple
AppleEvent data types (integer, text, float) are returned as their obvious
Python counterparts. Apple Event lists are returned as Python lists, and the
list elements are recursively unpacked.  Object references (ex. <code class="docutils literal notranslate"><span class="pre">line</span> <span class="pre">3</span> <span class="pre">of</span>
<span class="pre">document</span> <span class="pre">1</span></code>) are returned as instances of <a class="reference internal" href="aetypes.html#aetypes.ObjectSpecifier" title="aetypes.ObjectSpecifier"><code class="xref py py-class docutils literal notranslate"><span class="pre">aetypes.ObjectSpecifier</span></code></a>,
unless <code class="docutils literal notranslate"><span class="pre">formodulename</span></code> is specified.  AppleEvent descriptors with descriptor
type typeFSS are returned as <code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code> objects.  AppleEvent record
descriptors are returned as Python dictionaries, with 4-character string keys
and elements recursively unpacked.</p>
<p>The optional <code class="docutils literal notranslate"><span class="pre">formodulename</span></code> argument is used by the stub packages generated
by <a class="reference internal" href="gensuitemodule.html#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a>, and ensures that the OSA classes for object specifiers
are looked up in the correct module. This ensures that if, say, the Finder
returns an object specifier for a window you get an instance of
<code class="docutils literal notranslate"><span class="pre">Finder.Window</span></code> and not a generic <code class="docutils literal notranslate"><span class="pre">aetypes.Window</span></code>. The former knows about
all the properties and elements a window has in the Finder, while the latter
knows no such things.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="carbon.html#module-Carbon.AE" title="Carbon.AE: Interface to the Apple Events toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.AE</span></code></a></dt>
<dd>Built-in access to Apple Event Manager routines.</dd>
<dt>Module <a class="reference internal" href="aetypes.html#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a></dt>
<dd>Python definitions of codes for Apple Event descriptor types.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="aetools.html"
                        title="previous chapter">38.2. <code class="docutils literal notranslate"><span class="pre">aetools</span></code> — OSA client support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="aetypes.html"
                        title="next chapter">38.4. <code class="docutils literal notranslate"><span class="pre">aetypes</span></code> — AppleEvent objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/aepack.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aetypes.html" title="38.4. aetypes — AppleEvent objects"
             >next</a> |</li>
        <li class="right" >
          <a href="aetools.html" title="38.2. aetools — OSA client support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" >38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��Y�@@html/library/aetools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38.2. aetools — OSA client support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers" href="aepack.html" />
    <link rel="prev" title="38.1. gensuitemodule — Generate OSA stub packages" href="gensuitemodule.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/aetools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aepack.html" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gensuitemodule.html" title="38.1. gensuitemodule — Generate OSA stub packages"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" accesskey="U">38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-aetools">
<span id="aetools-osa-client-support"></span><h1>38.2. <a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a> — OSA client support<a class="headerlink" href="#module-aetools" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a> module contains the basic functionality on which Python
AppleScript client support is built. It also imports and re-exports the core
functionality of the <a class="reference internal" href="aetypes.html#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a> and <a class="reference internal" href="aepack.html#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a> modules. The stub packages
generated by <a class="reference internal" href="gensuitemodule.html#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a> import the relevant portions of
<a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a>, so usually you do not need to import it yourself. The exception
to this is when you cannot use a generated suite package and need lower-level
access to scripting.</p>
<p>The <a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a> module itself uses the AppleEvent support provided by the
<a class="reference internal" href="carbon.html#module-Carbon.AE" title="Carbon.AE: Interface to the Apple Events toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.AE</span></code></a> module. This has one drawback: you need access to the window
manager, see section <a class="reference internal" href="../using/mac.html#osx-gui-scripts"><span class="std std-ref">Running scripts with a GUI</span></a> for details. This restriction may be
lifted in future releases.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>The <a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="aetools.packevent">
<code class="descclassname">aetools.</code><code class="descname">packevent</code><span class="sig-paren">(</span><em>ae</em>, <em>parameters</em>, <em>attributes</em><span class="sig-paren">)</span><a class="headerlink" href="#aetools.packevent" title="Permalink to this definition">¶</a></dt>
<dd><p>Stores parameters and attributes in a pre-created <code class="docutils literal notranslate"><span class="pre">Carbon.AE.AEDesc</span></code> object.
<code class="docutils literal notranslate"><span class="pre">parameters</span></code> and <code class="docutils literal notranslate"><span class="pre">attributes</span></code> are  dictionaries mapping 4-character OSA
parameter keys to Python objects. The objects are packed using
<code class="docutils literal notranslate"><span class="pre">aepack.pack()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="aetools.unpackevent">
<code class="descclassname">aetools.</code><code class="descname">unpackevent</code><span class="sig-paren">(</span><em>ae</em><span class="optional">[</span>, <em>formodulename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aetools.unpackevent" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively unpacks a <code class="docutils literal notranslate"><span class="pre">Carbon.AE.AEDesc</span></code> event to Python objects. The function
returns the parameter dictionary and the attribute dictionary. The
<code class="docutils literal notranslate"><span class="pre">formodulename</span></code> argument is used by generated stub packages to control where
AppleScript classes are looked up.</p>
</dd></dl>

<dl class="function">
<dt id="aetools.keysubst">
<code class="descclassname">aetools.</code><code class="descname">keysubst</code><span class="sig-paren">(</span><em>arguments</em>, <em>keydict</em><span class="sig-paren">)</span><a class="headerlink" href="#aetools.keysubst" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts a Python keyword argument dictionary <code class="docutils literal notranslate"><span class="pre">arguments</span></code> to the format
required by <code class="docutils literal notranslate"><span class="pre">packevent</span></code> by replacing the keys, which are Python identifiers,
by the four-character OSA keys according to the mapping specified in
<code class="docutils literal notranslate"><span class="pre">keydict</span></code>. Used by the generated suite packages.</p>
</dd></dl>

<dl class="function">
<dt id="aetools.enumsubst">
<code class="descclassname">aetools.</code><code class="descname">enumsubst</code><span class="sig-paren">(</span><em>arguments</em>, <em>key</em>, <em>edict</em><span class="sig-paren">)</span><a class="headerlink" href="#aetools.enumsubst" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <code class="docutils literal notranslate"><span class="pre">arguments</span></code> dictionary contains an entry for <code class="docutils literal notranslate"><span class="pre">key</span></code> convert the value
for that entry according to dictionary <code class="docutils literal notranslate"><span class="pre">edict</span></code>. This converts human-readable
Python enumeration names to the OSA 4-character codes. Used by the generated
suite packages.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a> module defines the following class:</p>
<dl class="class">
<dt id="aetools.TalkTo">
<em class="property">class </em><code class="descclassname">aetools.</code><code class="descname">TalkTo</code><span class="sig-paren">(</span><span class="optional">[</span><em>signature=None</em>, <em>start=0</em>, <em>timeout=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aetools.TalkTo" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for the proxy used to talk to an application. <code class="docutils literal notranslate"><span class="pre">signature</span></code> overrides
the class attribute <code class="docutils literal notranslate"><span class="pre">_signature</span></code> (which is usually set by subclasses) and is
the 4-char creator code defining the application to talk to. <code class="docutils literal notranslate"><span class="pre">start</span></code> can be
set to true to enable running the application on class instantiation.
<code class="docutils literal notranslate"><span class="pre">timeout</span></code> can be specified to change the default timeout used while waiting
for an AppleEvent reply.</p>
</dd></dl>

<dl class="method">
<dt id="aetools.TalkTo._start">
<code class="descclassname">TalkTo.</code><code class="descname">_start</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aetools.TalkTo._start" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether the application is running, and attempt to start it if not.</p>
</dd></dl>

<dl class="method">
<dt id="aetools.TalkTo.send">
<code class="descclassname">TalkTo.</code><code class="descname">send</code><span class="sig-paren">(</span><em>code</em>, <em>subcode</em><span class="optional">[</span>, <em>parameters</em>, <em>attributes</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aetools.TalkTo.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Create the AppleEvent <code class="docutils literal notranslate"><span class="pre">Carbon.AE.AEDesc</span></code> for the verb with the OSA designation
<code class="docutils literal notranslate"><span class="pre">code,</span> <span class="pre">subcode</span></code> (which are the usual 4-character strings), pack the
<code class="docutils literal notranslate"><span class="pre">parameters</span></code> and <code class="docutils literal notranslate"><span class="pre">attributes</span></code> into it, send it to the target application,
wait for the reply, unpack the reply with <code class="docutils literal notranslate"><span class="pre">unpackevent</span></code> and return the reply
appleevent, the unpacked return values as a dictionary and the return
attributes.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="gensuitemodule.html"
                        title="previous chapter">38.1. <code class="docutils literal notranslate"><span class="pre">gensuitemodule</span></code> — Generate OSA stub packages</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="aepack.html"
                        title="next chapter">38.3. <code class="docutils literal notranslate"><span class="pre">aepack</span></code> — Conversion between Python variables and AppleEvent data containers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/aetools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aepack.html" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers"
             >next</a> |</li>
        <li class="right" >
          <a href="gensuitemodule.html" title="38.1. gensuitemodule — Generate OSA stub packages"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" >38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��wRRhtml/library/aetypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38.4. aetypes — AppleEvent objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38.5. MiniAEFrame — Open Scripting Architecture server support" href="miniaeframe.html" />
    <link rel="prev" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers" href="aepack.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/aetypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="miniaeframe.html" title="38.5. MiniAEFrame — Open Scripting Architecture server support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="aepack.html" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" accesskey="U">38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-aetypes">
<span id="aetypes-appleevent-objects"></span><h1>38.4. <a class="reference internal" href="#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a> — AppleEvent objects<a class="headerlink" href="#module-aetypes" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a> defines classes used to represent Apple Event data
descriptors and Apple Event object specifiers.</p>
<p>Apple Event data is contained in descriptors, and these descriptors are typed.
For many descriptors the Python representation is simply the corresponding
Python type: <code class="docutils literal notranslate"><span class="pre">typeText</span></code> in OSA is a Python string, <code class="docutils literal notranslate"><span class="pre">typeFloat</span></code> is a float,
etc. For OSA types that have no direct Python counterpart this module declares
classes. Packing and unpacking instances of these classes is handled
automatically by <a class="reference internal" href="aepack.html#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a>.</p>
<p>An object specifier is essentially an address of an object implemented in an
Apple Event server. An Apple Event specifier is used as the direct object for an
Apple Event or as the argument of an optional parameter. The <a class="reference internal" href="#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a>
module contains the base classes for OSA classes and properties, which are used
by the packages generated by <a class="reference internal" href="gensuitemodule.html#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a> to populate the classes and
properties in a given suite.</p>
<p>For reasons of backward compatibility, and for cases where you need to script an
application for which you have not generated the stub package this module also
contains object specifiers for a number of common OSA classes such as
<code class="docutils literal notranslate"><span class="pre">Document</span></code>, <code class="docutils literal notranslate"><span class="pre">Window</span></code>, <code class="docutils literal notranslate"><span class="pre">Character</span></code>, etc.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">AEObjects</span></code> module defines the following classes to represent Apple
Event descriptor data:</p>
<dl class="class">
<dt id="aetypes.Unknown">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Unknown</code><span class="sig-paren">(</span><em>type</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Unknown" title="Permalink to this definition">¶</a></dt>
<dd><p>The representation of OSA descriptor data for which the <a class="reference internal" href="aepack.html#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a> and
<a class="reference internal" href="#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a> modules have no support, i.e. anything that is not represented by
the other classes here and that is not equivalent to a simple Python value.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Enum">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Enum</code><span class="sig-paren">(</span><em>enum</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Enum" title="Permalink to this definition">¶</a></dt>
<dd><p>An enumeration value with the given 4-character string value.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.InsertionLoc">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">InsertionLoc</code><span class="sig-paren">(</span><em>of</em>, <em>pos</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.InsertionLoc" title="Permalink to this definition">¶</a></dt>
<dd><p>Position <code class="docutils literal notranslate"><span class="pre">pos</span></code> in object <code class="docutils literal notranslate"><span class="pre">of</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Boolean">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Boolean</code><span class="sig-paren">(</span><em>bool</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Boolean" title="Permalink to this definition">¶</a></dt>
<dd><p>A boolean.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.StyledText">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">StyledText</code><span class="sig-paren">(</span><em>style</em>, <em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.StyledText" title="Permalink to this definition">¶</a></dt>
<dd><p>Text with style information (font, face, etc) included.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.AEText">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">AEText</code><span class="sig-paren">(</span><em>script</em>, <em>style</em>, <em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.AEText" title="Permalink to this definition">¶</a></dt>
<dd><p>Text with script system and style information included.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.IntlText">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">IntlText</code><span class="sig-paren">(</span><em>script</em>, <em>language</em>, <em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.IntlText" title="Permalink to this definition">¶</a></dt>
<dd><p>Text with script system and language information included.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.IntlWritingCode">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">IntlWritingCode</code><span class="sig-paren">(</span><em>script</em>, <em>language</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.IntlWritingCode" title="Permalink to this definition">¶</a></dt>
<dd><p>Script system and language information.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.QDPoint">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">QDPoint</code><span class="sig-paren">(</span><em>v</em>, <em>h</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.QDPoint" title="Permalink to this definition">¶</a></dt>
<dd><p>A quickdraw point.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.QDRectangle">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">QDRectangle</code><span class="sig-paren">(</span><em>v0</em>, <em>h0</em>, <em>v1</em>, <em>h1</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.QDRectangle" title="Permalink to this definition">¶</a></dt>
<dd><p>A quickdraw rectangle.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.RGBColor">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">RGBColor</code><span class="sig-paren">(</span><em>r</em>, <em>g</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.RGBColor" title="Permalink to this definition">¶</a></dt>
<dd><p>A color.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Type">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Type</code><span class="sig-paren">(</span><em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Type" title="Permalink to this definition">¶</a></dt>
<dd><p>An OSA type value with the given 4-character name.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Keyword">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Keyword</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Keyword" title="Permalink to this definition">¶</a></dt>
<dd><p>An OSA keyword with the given 4-character name.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Range">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Range</code><span class="sig-paren">(</span><em>start</em>, <em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Range" title="Permalink to this definition">¶</a></dt>
<dd><p>A range.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Ordinal">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Ordinal</code><span class="sig-paren">(</span><em>abso</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Ordinal" title="Permalink to this definition">¶</a></dt>
<dd><p>Non-numeric absolute positions, such as <code class="docutils literal notranslate"><span class="pre">&quot;firs&quot;</span></code>, first, or <code class="docutils literal notranslate"><span class="pre">&quot;midd&quot;</span></code>,
middle.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Logical">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Logical</code><span class="sig-paren">(</span><em>logc</em>, <em>term</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Logical" title="Permalink to this definition">¶</a></dt>
<dd><p>The logical expression of applying operator <code class="docutils literal notranslate"><span class="pre">logc</span></code> to <code class="docutils literal notranslate"><span class="pre">term</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.Comparison">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">Comparison</code><span class="sig-paren">(</span><em>obj1</em>, <em>relo</em>, <em>obj2</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.Comparison" title="Permalink to this definition">¶</a></dt>
<dd><p>The comparison <code class="docutils literal notranslate"><span class="pre">relo</span></code> of <code class="docutils literal notranslate"><span class="pre">obj1</span></code> to <code class="docutils literal notranslate"><span class="pre">obj2</span></code>.</p>
</dd></dl>

<p>The following classes are used as base classes by the generated stub packages to
represent AppleScript classes and properties in Python:</p>
<dl class="class">
<dt id="aetypes.ComponentItem">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">ComponentItem</code><span class="sig-paren">(</span><em>which</em><span class="optional">[</span>, <em>fr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.ComponentItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract baseclass for an OSA class. The subclass should set the class attribute
<code class="docutils literal notranslate"><span class="pre">want</span></code> to the 4-character OSA class code. Instances of subclasses of this
class are equivalent to AppleScript Object Specifiers. Upon instantiation you
should pass a selector in <code class="docutils literal notranslate"><span class="pre">which</span></code>, and optionally a parent object in <code class="docutils literal notranslate"><span class="pre">fr</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.NProperty">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">NProperty</code><span class="sig-paren">(</span><em>fr</em><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.NProperty" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract baseclass for an OSA property. The subclass should set the class
attributes <code class="docutils literal notranslate"><span class="pre">want</span></code> and <code class="docutils literal notranslate"><span class="pre">which</span></code> to designate which property we are talking
about. Instances of subclasses of this class are Object Specifiers.</p>
</dd></dl>

<dl class="class">
<dt id="aetypes.ObjectSpecifier">
<em class="property">class </em><code class="descclassname">aetypes.</code><code class="descname">ObjectSpecifier</code><span class="sig-paren">(</span><em>want</em>, <em>form</em>, <em>seld</em><span class="optional">[</span>, <em>fr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aetypes.ObjectSpecifier" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class of <code class="docutils literal notranslate"><span class="pre">ComponentItem</span></code> and <code class="docutils literal notranslate"><span class="pre">NProperty</span></code>, a general OSA Object
Specifier. See the Apple Open Scripting Architecture documentation for the
parameters. Note that this class is not abstract.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="aepack.html"
                        title="previous chapter">38.3. <code class="docutils literal notranslate"><span class="pre">aepack</span></code> — Conversion between Python variables and AppleEvent data containers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="miniaeframe.html"
                        title="next chapter">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/aetypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="miniaeframe.html" title="38.5. MiniAEFrame — Open Scripting Architecture server support"
             >next</a> |</li>
        <li class="right" >
          <a href="aepack.html" title="38.3. aepack — Conversion between Python variables and AppleEvent data containers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" >38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�֫��a�ahtml/library/aifc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.3. aifc — Read and write AIFF and AIFC files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.4. sunau — Read and write Sun AU files" href="sunau.html" />
    <link rel="prev" title="21.2. imageop — Manipulate raw image data" href="imageop.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/aifc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sunau.html" title="21.4. sunau — Read and write Sun AU files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imageop.html" title="21.2. imageop — Manipulate raw image data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-aifc">
<span id="aifc-read-and-write-aiff-and-aifc-files"></span><h1>21.3. <a class="reference internal" href="#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a> — Read and write AIFF and AIFC files<a class="headerlink" href="#module-aifc" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/aifc.py">Lib/aifc.py</a></p>
<hr class="docutils" />
<p>This module provides support for reading and writing AIFF and AIFF-C files.
AIFF is Audio Interchange File Format, a format for storing digital audio
samples in a file.  AIFF-C is a newer version of the format that includes the
ability to compress the audio data.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some operations may only work under IRIX; these will raise <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>
when attempting to import the <code class="xref py py-mod docutils literal notranslate"><span class="pre">cl</span></code> module, which is only available on
IRIX.</p>
</div>
<p>Audio files have a number of parameters that describe the audio data. The
sampling rate or frame rate is the number of times per second the sound is
sampled.  The number of channels indicate if the audio is mono, stereo, or
quadro.  Each frame consists of one sample per channel.  The sample size is the
size in bytes of each sample.  Thus a frame consists of
<em>nchannels</em>*<em>samplesize</em> bytes, and a second’s worth of audio consists of
<em>nchannels</em>*<em>samplesize</em>*<em>framerate</em> bytes.</p>
<p>For example, CD quality audio has a sample size of two bytes (16 bits), uses two
channels (stereo) and has a frame rate of 44,100 frames/second.  This gives a
frame size of 4 bytes (2*2), and a second’s worth occupies 2*2*44100 bytes
(176,400 bytes).</p>
<p>Module <a class="reference internal" href="#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a> defines the following function:</p>
<dl class="function">
<dt id="aifc.open">
<code class="descclassname">aifc.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open an AIFF or AIFF-C file and return an object instance with methods that are
described below.  The argument <em>file</em> is either a string naming a file or a file
object.  <em>mode</em> must be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> when the file must be opened for
reading, or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>  or <code class="docutils literal notranslate"><span class="pre">'wb'</span></code> when the file must be opened for writing.  If
omitted, <code class="docutils literal notranslate"><span class="pre">file.mode</span></code> is used if it exists, otherwise <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> is used.  When
used for writing, the file object should be seekable, unless you know ahead of
time how many samples you are going to write in total and use
<code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframesraw()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setnframes()</span></code>.</p>
</dd></dl>

<p>Objects returned by <a class="reference internal" href="#aifc.open" title="aifc.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> when a file is opened for reading have the
following methods:</p>
<dl class="method">
<dt id="aifc.aifc.getnchannels">
<code class="descclassname">aifc.</code><code class="descname">getnchannels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of audio channels (1 for mono, 2 for stereo).</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getsampwidth">
<code class="descclassname">aifc.</code><code class="descname">getsampwidth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size in bytes of individual samples.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getframerate">
<code class="descclassname">aifc.</code><code class="descname">getframerate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sampling rate (number of audio frames per second).</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getnframes">
<code class="descclassname">aifc.</code><code class="descname">getnframes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of audio frames in the file.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getcomptype">
<code class="descclassname">aifc.</code><code class="descname">getcomptype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a four-character string describing the type of compression used in the
audio file.  For AIFF files, the returned value is <code class="docutils literal notranslate"><span class="pre">'NONE'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getcompname">
<code class="descclassname">aifc.</code><code class="descname">getcompname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getcompname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a human-readable description of the type of compression used in the audio
file.  For AIFF files, the returned value is <code class="docutils literal notranslate"><span class="pre">'not</span> <span class="pre">compressed'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getparams">
<code class="descclassname">aifc.</code><code class="descname">getparams</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getparams" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple consisting of all of the above values in the above order.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getmarkers">
<code class="descclassname">aifc.</code><code class="descname">getmarkers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getmarkers" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of markers in the audio file.  A marker consists of a tuple of
three elements.  The first is the mark ID (an integer), the second is the mark
position in frames from the beginning of the data (an integer), the third is the
name of the mark (a string).</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.getmark">
<code class="descclassname">aifc.</code><code class="descname">getmark</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.getmark" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the tuple as described in <a class="reference internal" href="#aifc.aifc.getmarkers" title="aifc.aifc.getmarkers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getmarkers()</span></code></a> for the mark with the given
<em>id</em>.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.readframes">
<code class="descclassname">aifc.</code><code class="descname">readframes</code><span class="sig-paren">(</span><em>nframes</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.readframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return the next <em>nframes</em> frames from the audio file.  The returned
data is a string containing for each frame the uncompressed samples of all
channels.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.rewind">
<code class="descclassname">aifc.</code><code class="descname">rewind</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.rewind" title="Permalink to this definition">¶</a></dt>
<dd><p>Rewind the read pointer.  The next <a class="reference internal" href="#aifc.aifc.readframes" title="aifc.aifc.readframes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readframes()</span></code></a> will start from the
beginning.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setpos">
<code class="descclassname">aifc.</code><code class="descname">setpos</code><span class="sig-paren">(</span><em>pos</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setpos" title="Permalink to this definition">¶</a></dt>
<dd><p>Seek to the specified frame number.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.tell">
<code class="descclassname">aifc.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current frame number.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.close">
<code class="descclassname">aifc.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the AIFF file.  After calling this method, the object can no longer be
used.</p>
</dd></dl>

<p>Objects returned by <a class="reference internal" href="#aifc.open" title="aifc.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> when a file is opened for writing have all the
above methods, except for <code class="xref py py-meth docutils literal notranslate"><span class="pre">readframes()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setpos()</span></code>.  In addition
the following methods exist.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">get*()</span></code> methods can only be called after
the corresponding <code class="xref py py-meth docutils literal notranslate"><span class="pre">set*()</span></code> methods have been called.  Before the first
<code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframes()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframesraw()</span></code>, all parameters except for the
number of frames must be filled in.</p>
<dl class="method">
<dt id="aifc.aifc.aiff">
<code class="descclassname">aifc.</code><code class="descname">aiff</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.aiff" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an AIFF file.  The default is that an AIFF-C file is created, unless the
name of the file ends in <code class="docutils literal notranslate"><span class="pre">'.aiff'</span></code> in which case the default is an AIFF file.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.aifc">
<code class="descclassname">aifc.</code><code class="descname">aifc</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.aifc" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an AIFF-C file.  The default is that an AIFF-C file is created, unless
the name of the file ends in <code class="docutils literal notranslate"><span class="pre">'.aiff'</span></code> in which case the default is an AIFF
file.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setnchannels">
<code class="descclassname">aifc.</code><code class="descname">setnchannels</code><span class="sig-paren">(</span><em>nchannels</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify the number of channels in the audio file.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setsampwidth">
<code class="descclassname">aifc.</code><code class="descname">setsampwidth</code><span class="sig-paren">(</span><em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify the size in bytes of audio samples.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setframerate">
<code class="descclassname">aifc.</code><code class="descname">setframerate</code><span class="sig-paren">(</span><em>rate</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify the sampling frequency in frames per second.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setnframes">
<code class="descclassname">aifc.</code><code class="descname">setnframes</code><span class="sig-paren">(</span><em>nframes</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify the number of frames that are to be written to the audio file. If this
parameter is not set, or not set correctly, the file needs to support seeking.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setcomptype">
<code class="descclassname">aifc.</code><code class="descname">setcomptype</code><span class="sig-paren">(</span><em>type</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Specify the compression type.  If not specified, the audio data will not be
compressed.  In AIFF files, compression is not possible.  The name parameter
should be a human-readable description of the compression type, the type
parameter should be a four-character string.  Currently the following
compression types are supported: NONE, ULAW, ALAW, G722.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setparams">
<code class="descclassname">aifc.</code><code class="descname">setparams</code><span class="sig-paren">(</span><em>nchannels</em>, <em>sampwidth</em>, <em>framerate</em>, <em>comptype</em>, <em>compname</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setparams" title="Permalink to this definition">¶</a></dt>
<dd><p>Set all the above parameters at once.  The argument is a tuple consisting of the
various parameters.  This means that it is possible to use the result of a
<a class="reference internal" href="#aifc.aifc.getparams" title="aifc.aifc.getparams"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getparams()</span></code></a> call as argument to <a class="reference internal" href="#aifc.aifc.setparams" title="aifc.aifc.setparams"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setparams()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.setmark">
<code class="descclassname">aifc.</code><code class="descname">setmark</code><span class="sig-paren">(</span><em>id</em>, <em>pos</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.setmark" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a mark with the given id (larger than 0), and the given name at the given
position.  This method can be called at any time before <a class="reference internal" href="#aifc.aifc.close" title="aifc.aifc.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">aifc.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the current write position in the output file.  Useful in combination
with <a class="reference internal" href="#aifc.aifc.setmark" title="aifc.aifc.setmark"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setmark()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.writeframes">
<code class="descclassname">aifc.</code><code class="descname">writeframes</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.writeframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Write data to the output file.  This method can only be called after the audio
file parameters have been set.</p>
</dd></dl>

<dl class="method">
<dt id="aifc.aifc.writeframesraw">
<code class="descclassname">aifc.</code><code class="descname">writeframesraw</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#aifc.aifc.writeframesraw" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#aifc.aifc.writeframes" title="aifc.aifc.writeframes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframes()</span></code></a>, except that the header of the audio file is not
updated.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">aifc.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Close the AIFF file.  The header of the file is updated to reflect the actual
size of the audio data. After calling this method, the object can no longer be
used.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="imageop.html"
                        title="previous chapter">21.2. <code class="docutils literal notranslate"><span class="pre">imageop</span></code> — Manipulate raw image data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sunau.html"
                        title="next chapter">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/aifc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sunau.html" title="21.4. sunau — Read and write Sun AU files"
             >next</a> |</li>
        <li class="right" >
          <a href="imageop.html" title="21.2. imageop — Manipulate raw image data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���]�H�Hhtml/library/al.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.1. al — Audio functions on the SGI &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.3. cd — CD-ROM access on SGI systems" href="cd.html" />
    <link rel="prev" title="39. SGI IRIX Specific Services" href="sgi.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/al.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cd.html" title="39.3. cd — CD-ROM access on SGI systems"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sgi.html" title="39. SGI IRIX Specific Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-al">
<span id="al-audio-functions-on-the-sgi"></span><h1>39.1. <a class="reference internal" href="#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> — Audio functions on the SGI<a class="headerlink" href="#module-al" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module provides access to the audio facilities of the SGI Indy and Indigo
workstations.  See section 3A of the IRIX man pages for details.  You’ll need to
read those man pages to understand what these functions do!  Some of the
functions are not available in IRIX releases before 4.0.5.  Again, see the
manual to check whether a specific function is available on your platform.</p>
<p>All functions and methods defined in this module are equivalent to the C
functions with <code class="docutils literal notranslate"><span class="pre">AL</span></code> prefixed to their name.</p>
<p id="index-0">Symbolic constants from the C header file <code class="docutils literal notranslate"><span class="pre">&lt;audio.h&gt;</span></code> are defined in the
standard module <a class="reference internal" href="#module-AL" title="AL: Constants used with the al module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code></a>, see below.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The current version of the audio library may dump core when bad argument values
are passed rather than returning an error status.  Unfortunately, since the
precise circumstances under which this may happen are undocumented and hard to
check, the Python interface can provide no protection against this kind of
problems. (One example is specifying an excessive queue size — there is no
documented upper limit.)</p>
</div>
<p>The module defines the following functions:</p>
<dl class="function">
<dt id="al.openport">
<code class="descclassname">al.</code><code class="descname">openport</code><span class="sig-paren">(</span><em>name</em>, <em>direction</em><span class="optional">[</span>, <em>config</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#al.openport" title="Permalink to this definition">¶</a></dt>
<dd><p>The name and direction arguments are strings.  The optional <em>config</em> argument is
a configuration object as returned by <a class="reference internal" href="#al.newconfig" title="al.newconfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">newconfig()</span></code></a>.  The return value is an
<em class="dfn">audio port object</em>; methods of audio port objects are described below.</p>
</dd></dl>

<dl class="function">
<dt id="al.newconfig">
<code class="descclassname">al.</code><code class="descname">newconfig</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#al.newconfig" title="Permalink to this definition">¶</a></dt>
<dd><p>The return value is a new <em class="dfn">audio configuration object</em>; methods of audio
configuration objects are described below.</p>
</dd></dl>

<dl class="function">
<dt id="al.queryparams">
<code class="descclassname">al.</code><code class="descname">queryparams</code><span class="sig-paren">(</span><em>device</em><span class="sig-paren">)</span><a class="headerlink" href="#al.queryparams" title="Permalink to this definition">¶</a></dt>
<dd><p>The device argument is an integer.  The return value is a list of integers
containing the data returned by <code class="xref c c-func docutils literal notranslate"><span class="pre">ALqueryparams()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="al.getparams">
<code class="descclassname">al.</code><code class="descname">getparams</code><span class="sig-paren">(</span><em>device</em>, <em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#al.getparams" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>device</em> argument is an integer.  The list argument is a list such as
returned by <a class="reference internal" href="#al.queryparams" title="al.queryparams"><code class="xref py py-func docutils literal notranslate"><span class="pre">queryparams()</span></code></a>; it is modified in place (!).</p>
</dd></dl>

<dl class="function">
<dt id="al.setparams">
<code class="descclassname">al.</code><code class="descname">setparams</code><span class="sig-paren">(</span><em>device</em>, <em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#al.setparams" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>device</em> argument is an integer.  The <em>list</em> argument is a list such as
returned by <a class="reference internal" href="#al.queryparams" title="al.queryparams"><code class="xref py py-func docutils literal notranslate"><span class="pre">queryparams()</span></code></a>.</p>
</dd></dl>

<div class="section" id="configuration-objects">
<span id="al-config-objects"></span><h2>39.1.1. Configuration Objects<a class="headerlink" href="#configuration-objects" title="Permalink to this headline">¶</a></h2>
<p>Configuration objects returned by <a class="reference internal" href="#al.newconfig" title="al.newconfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">newconfig()</span></code></a> have the following methods:</p>
<dl class="method">
<dt>
<code class="descname">audio configuration.getqueuesize()</code></dt>
<dd><p>Return the queue size.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.setqueuesize(size)</code></dt>
<dd><p>Set the queue size.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.getwidth()</code></dt>
<dd><p>Get the sample width.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.setwidth(width)</code></dt>
<dd><p>Set the sample width.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.getchannels()</code></dt>
<dd><p>Get the channel count.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.setchannels(nchannels)</code></dt>
<dd><p>Set the channel count.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.getsampfmt()</code></dt>
<dd><p>Get the sample format.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.setsampfmt(sampfmt)</code></dt>
<dd><p>Set the sample format.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.getfloatmax()</code></dt>
<dd><p>Get the maximum value for floating sample formats.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio configuration.setfloatmax(floatmax)</code></dt>
<dd><p>Set the maximum value for floating sample formats.</p>
</dd></dl>

</div>
<div class="section" id="port-objects">
<span id="al-port-objects"></span><h2>39.1.2. Port Objects<a class="headerlink" href="#port-objects" title="Permalink to this headline">¶</a></h2>
<p>Port objects, as returned by <a class="reference internal" href="#al.openport" title="al.openport"><code class="xref py py-func docutils literal notranslate"><span class="pre">openport()</span></code></a>, have the following methods:</p>
<dl class="method">
<dt>
<code class="descname">audio port.closeport()</code></dt>
<dd><p>Close the port.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getfd()</code></dt>
<dd><p>Return the file descriptor as an int.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getfilled()</code></dt>
<dd><p>Return the number of filled samples.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getfillable()</code></dt>
<dd><p>Return the number of fillable samples.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.readsamps(nsamples)</code></dt>
<dd><p>Read a number of samples from the queue, blocking if necessary. Return the data
as a string containing the raw data, (e.g., 2 bytes per sample in big-endian
byte order (high byte, low byte) if you have set the sample width to 2 bytes).</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.writesamps(samples)</code></dt>
<dd><p>Write samples into the queue, blocking if necessary.  The samples are encoded as
described for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">readsamps()</span></code> return value.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getfillpoint()</code></dt>
<dd><p>Return the ‘fill point’.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.setfillpoint(fillpoint)</code></dt>
<dd><p>Set the ‘fill point’.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getconfig()</code></dt>
<dd><p>Return a configuration object containing the current configuration of the port.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.setconfig(config)</code></dt>
<dd><p>Set the configuration from the argument, a configuration object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio port.getstatus(list)</code></dt>
<dd><p>Get status information on last error.</p>
</dd></dl>

</div>
</div>
<div class="section" id="module-AL">
<span id="al-constants-used-with-the-al-module"></span><h1>39.2. <a class="reference internal" href="#module-AL" title="AL: Constants used with the al module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code></a> — Constants used with the <a class="reference internal" href="#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> module<a class="headerlink" href="#module-AL" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-AL" title="AL: Constants used with the al module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module defines symbolic constants needed to use the built-in module
<a class="reference internal" href="#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> (see above); they are equivalent to those defined in the C header file
<code class="docutils literal notranslate"><span class="pre">&lt;audio.h&gt;</span></code> except that the name prefix <code class="docutils literal notranslate"><span class="pre">AL_</span></code> is omitted.  Read the module
source for a complete list of the defined names.  Suggested use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">al</span>
<span class="kn">from</span> <span class="nn">AL</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a><ul>
<li><a class="reference internal" href="#configuration-objects">39.1.1. Configuration Objects</a></li>
<li><a class="reference internal" href="#port-objects">39.1.2. Port Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-AL">39.2. <code class="docutils literal notranslate"><span class="pre">AL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">al</span></code> module</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sgi.html"
                        title="previous chapter">39. SGI IRIX Specific Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cd.html"
                        title="next chapter">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/al.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cd.html" title="39.3. cd — CD-ROM access on SGI systems"
             >next</a> |</li>
        <li class="right" >
          <a href="sgi.html" title="39. SGI IRIX Specific Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\H<����html/library/allos.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15. Generic Operating System Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.1. os — Miscellaneous operating system interfaces" href="os.html" />
    <link rel="prev" title="14.4. sha — SHA-1 message digest algorithm" href="sha.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/allos.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="os.html" title="15.1. os — Miscellaneous operating system interfaces"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sha.html" title="14.4. sha — SHA-1 message digest algorithm"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="generic-operating-system-services">
<span id="allos"></span><h1>15. Generic Operating System Services<a class="headerlink" href="#generic-operating-system-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide interfaces to operating system
features that are available on (almost) all operating systems, such as files and
a clock.  The interfaces are generally modeled after the Unix or C interfaces,
but they are available on most other systems as well.  Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="os.html">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a><ul>
<li class="toctree-l2"><a class="reference internal" href="os.html#process-parameters">15.1.1. Process Parameters</a></li>
<li class="toctree-l2"><a class="reference internal" href="os.html#file-object-creation">15.1.2. File Object Creation</a></li>
<li class="toctree-l2"><a class="reference internal" href="os.html#file-descriptor-operations">15.1.3. File Descriptor Operations</a><ul>
<li class="toctree-l3"><a class="reference internal" href="os.html#open-flag-constants">15.1.3.1. <code class="docutils literal notranslate"><span class="pre">open()</span></code> flag constants</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="os.html#files-and-directories">15.1.4. Files and Directories</a></li>
<li class="toctree-l2"><a class="reference internal" href="os.html#process-management">15.1.5. Process Management</a></li>
<li class="toctree-l2"><a class="reference internal" href="os.html#miscellaneous-system-information">15.1.6. Miscellaneous System Information</a></li>
<li class="toctree-l2"><a class="reference internal" href="os.html#miscellaneous-functions">15.1.7. Miscellaneous Functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="io.html">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a><ul>
<li class="toctree-l2"><a class="reference internal" href="io.html#module-interface">15.2.1. Module Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html#i-o-base-classes">15.2.2. I/O Base Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html#raw-file-i-o">15.2.3. Raw File I/O</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html#buffered-streams">15.2.4. Buffered Streams</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html#text-i-o">15.2.5. Text I/O</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html#advanced-topics">15.2.6. Advanced topics</a><ul>
<li class="toctree-l3"><a class="reference internal" href="io.html#performance">15.2.6.1. Performance</a><ul>
<li class="toctree-l4"><a class="reference internal" href="io.html#binary-i-o">15.2.6.1.1. Binary I/O</a></li>
<li class="toctree-l4"><a class="reference internal" href="io.html#id1">15.2.6.1.2. Text I/O</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="io.html#multi-threading">15.2.6.2. Multi-threading</a></li>
<li class="toctree-l3"><a class="reference internal" href="io.html#reentrancy">15.2.6.3. Reentrancy</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="time.html">15.3. <code class="docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a></li>
<li class="toctree-l1"><a class="reference internal" href="argparse.html">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a><ul>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#example">15.4.1. Example</a><ul>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#creating-a-parser">15.4.1.1. Creating a parser</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#adding-arguments">15.4.1.2. Adding arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#parsing-arguments">15.4.1.3. Parsing arguments</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#argumentparser-objects">15.4.2. ArgumentParser objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#prog">15.4.2.1. prog</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#usage">15.4.2.2. usage</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#description">15.4.2.3. description</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#epilog">15.4.2.4. epilog</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#parents">15.4.2.5. parents</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#formatter-class">15.4.2.6. formatter_class</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#prefix-chars">15.4.2.7. prefix_chars</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#fromfile-prefix-chars">15.4.2.8. fromfile_prefix_chars</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#argument-default">15.4.2.9. argument_default</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#conflict-handler">15.4.2.10. conflict_handler</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#add-help">15.4.2.11. add_help</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#the-add-argument-method">15.4.3. The add_argument() method</a><ul>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#name-or-flags">15.4.3.1. name or flags</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#action">15.4.3.2. action</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#nargs">15.4.3.3. nargs</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#const">15.4.3.4. const</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#default">15.4.3.5. default</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#type">15.4.3.6. type</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#choices">15.4.3.7. choices</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#required">15.4.3.8. required</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#help">15.4.3.9. help</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#metavar">15.4.3.10. metavar</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#dest">15.4.3.11. dest</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#action-classes">15.4.3.12. Action classes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#the-parse-args-method">15.4.4. The parse_args() method</a><ul>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#option-value-syntax">15.4.4.1. Option value syntax</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#invalid-arguments">15.4.4.2. Invalid arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#arguments-containing">15.4.4.3. Arguments containing <code class="docutils literal notranslate"><span class="pre">-</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#argument-abbreviations-prefix-matching">15.4.4.4. Argument abbreviations (prefix matching)</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#beyond-sys-argv">15.4.4.5. Beyond <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#the-namespace-object">15.4.4.6. The Namespace object</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#other-utilities">15.4.5. Other utilities</a><ul>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#sub-commands">15.4.5.1. Sub-commands</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#filetype-objects">15.4.5.2. FileType objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#argument-groups">15.4.5.3. Argument groups</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#mutual-exclusion">15.4.5.4. Mutual exclusion</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#parser-defaults">15.4.5.5. Parser defaults</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#printing-help">15.4.5.6. Printing help</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#partial-parsing">15.4.5.7. Partial parsing</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#customizing-file-parsing">15.4.5.8. Customizing file parsing</a></li>
<li class="toctree-l3"><a class="reference internal" href="argparse.html#exiting-methods">15.4.5.9. Exiting methods</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html#upgrading-optparse-code">15.4.6. Upgrading optparse code</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="optparse.html">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a><ul>
<li class="toctree-l2"><a class="reference internal" href="optparse.html#background">15.5.1. Background</a><ul>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#terminology">15.5.1.1. Terminology</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#what-are-options-for">15.5.1.2. What are options for?</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#what-are-positional-arguments-for">15.5.1.3. What are positional arguments for?</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="optparse.html#tutorial">15.5.2. Tutorial</a><ul>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#understanding-option-actions">15.5.2.1. Understanding option actions</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#the-store-action">15.5.2.2. The store action</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#handling-boolean-flag-options">15.5.2.3. Handling boolean (flag) options</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#other-actions">15.5.2.4. Other actions</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#default-values">15.5.2.5. Default values</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#generating-help">15.5.2.6. Generating help</a><ul>
<li class="toctree-l4"><a class="reference internal" href="optparse.html#grouping-options">15.5.2.6.1. Grouping Options</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#printing-a-version-string">15.5.2.7. Printing a version string</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#how-optparse-handles-errors">15.5.2.8. How <code class="docutils literal notranslate"><span class="pre">optparse</span></code> handles errors</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#putting-it-all-together">15.5.2.9. Putting it all together</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="optparse.html#reference-guide">15.5.3. Reference Guide</a><ul>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#creating-the-parser">15.5.3.1. Creating the parser</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#populating-the-parser">15.5.3.2. Populating the parser</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#defining-options">15.5.3.3. Defining options</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#option-attributes">15.5.3.4. Option attributes</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#standard-option-actions">15.5.3.5. Standard option actions</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#standard-option-types">15.5.3.6. Standard option types</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#parsing-arguments">15.5.3.7. Parsing arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#querying-and-manipulating-your-option-parser">15.5.3.8. Querying and manipulating your option parser</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#conflicts-between-options">15.5.3.9. Conflicts between options</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#cleanup">15.5.3.10. Cleanup</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#other-methods">15.5.3.11. Other methods</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="optparse.html#option-callbacks">15.5.4. Option Callbacks</a><ul>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#defining-a-callback-option">15.5.4.1. Defining a callback option</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#how-callbacks-are-called">15.5.4.2. How callbacks are called</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#raising-errors-in-a-callback">15.5.4.3. Raising errors in a callback</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-1-trivial-callback">15.5.4.4. Callback example 1: trivial callback</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-2-check-option-order">15.5.4.5. Callback example 2: check option order</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-3-check-option-order-generalized">15.5.4.6. Callback example 3: check option order (generalized)</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-4-check-arbitrary-condition">15.5.4.7. Callback example 4: check arbitrary condition</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-5-fixed-arguments">15.5.4.8. Callback example 5: fixed arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#callback-example-6-variable-arguments">15.5.4.9. Callback example 6: variable arguments</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="optparse.html#extending-optparse">15.5.5. Extending <code class="docutils literal notranslate"><span class="pre">optparse</span></code></a><ul>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#adding-new-types">15.5.5.1. Adding new types</a></li>
<li class="toctree-l3"><a class="reference internal" href="optparse.html#adding-new-actions">15.5.5.2. Adding new actions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="getopt.html">15.6. <code class="docutils literal notranslate"><span class="pre">getopt</span></code> — C-style parser for command line options</a></li>
<li class="toctree-l1"><a class="reference internal" href="logging.html">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="logging.html#logger-objects">15.7.1. Logger Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#logging-levels">15.7.2. Logging Levels</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#handler-objects">15.7.3. Handler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#formatter-objects">15.7.4. Formatter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#filter-objects">15.7.5. Filter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#logrecord-objects">15.7.6. LogRecord Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#logrecord-attributes">15.7.7. LogRecord attributes</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#loggeradapter-objects">15.7.8. LoggerAdapter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#thread-safety">15.7.9. Thread Safety</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#module-level-functions">15.7.10. Module-Level Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html#integration-with-the-warnings-module">15.7.11. Integration with the warnings module</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="logging.config.html">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a><ul>
<li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-functions">15.8.1. Configuration functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-dictionary-schema">15.8.2. Configuration dictionary schema</a><ul>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#dictionary-schema-details">15.8.2.1. Dictionary Schema Details</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#incremental-configuration">15.8.2.2. Incremental Configuration</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#object-connections">15.8.2.3. Object connections</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#user-defined-objects">15.8.2.4. User-defined objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#access-to-external-objects">15.8.2.5. Access to external objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#access-to-internal-objects">15.8.2.6. Access to internal objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="logging.config.html#import-resolution-and-custom-importers">15.8.2.7. Import resolution and custom importers</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="logging.config.html#configuration-file-format">15.8.3. Configuration file format</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="logging.handlers.html">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#streamhandler">15.9.1. StreamHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#filehandler">15.9.2. FileHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#nullhandler">15.9.3. NullHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#watchedfilehandler">15.9.4. WatchedFileHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#rotatingfilehandler">15.9.5. RotatingFileHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#timedrotatingfilehandler">15.9.6. TimedRotatingFileHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#sockethandler">15.9.7. SocketHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#datagramhandler">15.9.8. DatagramHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#sysloghandler">15.9.9. SysLogHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#nteventloghandler">15.9.10. NTEventLogHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#smtphandler">15.9.11. SMTPHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#memoryhandler">15.9.12. MemoryHandler</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html#httphandler">15.9.13. HTTPHandler</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="getpass.html">15.10. <code class="docutils literal notranslate"><span class="pre">getpass</span></code> — Portable password input</a></li>
<li class="toctree-l1"><a class="reference internal" href="curses.html">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a><ul>
<li class="toctree-l2"><a class="reference internal" href="curses.html#functions">15.11.1. Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.html#window-objects">15.11.2. Window Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.html#constants">15.11.3. Constants</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="curses.html#module-curses.textpad">15.12. <code class="docutils literal notranslate"><span class="pre">curses.textpad</span></code> — Text input widget for curses programs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="curses.html#textbox-objects">15.12.1. Textbox objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="curses.ascii.html">15.13. <code class="docutils literal notranslate"><span class="pre">curses.ascii</span></code> — Utilities for ASCII characters</a></li>
<li class="toctree-l1"><a class="reference internal" href="curses.panel.html">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a><ul>
<li class="toctree-l2"><a class="reference internal" href="curses.panel.html#functions">15.14.1. Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.panel.html#panel-objects">15.14.2. Panel Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="platform.html">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a><ul>
<li class="toctree-l2"><a class="reference internal" href="platform.html#cross-platform">15.15.1. Cross Platform</a></li>
<li class="toctree-l2"><a class="reference internal" href="platform.html#java-platform">15.15.2. Java Platform</a></li>
<li class="toctree-l2"><a class="reference internal" href="platform.html#windows-platform">15.15.3. Windows Platform</a><ul>
<li class="toctree-l3"><a class="reference internal" href="platform.html#win95-98-specific">15.15.3.1. Win95/98 specific</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="platform.html#mac-os-platform">15.15.4. Mac OS Platform</a></li>
<li class="toctree-l2"><a class="reference internal" href="platform.html#unix-platforms">15.15.5. Unix Platforms</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="errno.html">15.16. <code class="docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></li>
<li class="toctree-l1"><a class="reference internal" href="ctypes.html">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ctypes.html#ctypes-tutorial">15.17.1. ctypes tutorial</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#loading-dynamic-link-libraries">15.17.1.1. Loading dynamic link libraries</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#accessing-functions-from-loaded-dlls">15.17.1.2. Accessing functions from loaded dlls</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions">15.17.1.3. Calling functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#fundamental-data-types">15.17.1.4. Fundamental data types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions-continued">15.17.1.5. Calling functions, continued</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#calling-functions-with-your-own-custom-data-types">15.17.1.6. Calling functions with your own custom data types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#specifying-the-required-argument-types-function-prototypes">15.17.1.7. Specifying the required argument types (function prototypes)</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#return-types">15.17.1.8. Return types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#passing-pointers-or-passing-parameters-by-reference">15.17.1.9. Passing pointers (or: passing parameters by reference)</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#structures-and-unions">15.17.1.10. Structures and unions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#structure-union-alignment-and-byte-order">15.17.1.11. Structure/union alignment and byte order</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#bit-fields-in-structures-and-unions">15.17.1.12. Bit fields in structures and unions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#arrays">15.17.1.13. Arrays</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#pointers">15.17.1.14. Pointers</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#type-conversions">15.17.1.15. Type conversions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#incomplete-types">15.17.1.16. Incomplete Types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#callback-functions">15.17.1.17. Callback functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#accessing-values-exported-from-dlls">15.17.1.18. Accessing values exported from dlls</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#surprises">15.17.1.19. Surprises</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#variable-sized-data-types">15.17.1.20. Variable-sized data types</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ctypes.html#ctypes-reference">15.17.2. ctypes reference</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#finding-shared-libraries">15.17.2.1. Finding shared libraries</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#loading-shared-libraries">15.17.2.2. Loading shared libraries</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#foreign-functions">15.17.2.3. Foreign functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#function-prototypes">15.17.2.4. Function prototypes</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#utility-functions">15.17.2.5. Utility functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#data-types">15.17.2.6. Data types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#ctypes-fundamental-data-types-2">15.17.2.7. Fundamental data types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#structured-data-types">15.17.2.8. Structured data types</a></li>
<li class="toctree-l3"><a class="reference internal" href="ctypes.html#arrays-and-pointers">15.17.2.9. Arrays and pointers</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="sha.html"
                        title="previous chapter">14.4. <code class="docutils literal notranslate"><span class="pre">sha</span></code> — SHA-1 message digest algorithm</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="os.html"
                        title="next chapter">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/allos.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="os.html" title="15.1. os — Miscellaneous operating system interfaces"
             >next</a> |</li>
        <li class="right" >
          <a href="sha.html" title="14.4. sha — SHA-1 message digest algorithm"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\2x�x�F�Fhtml/library/anydbm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.6. anydbm — Generic access to DBM-style databases &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.7. whichdb — Guess which DBM module created a database" href="whichdb.html" />
    <link rel="prev" title="11.5. marshal — Internal Python object serialization" href="marshal.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/anydbm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whichdb.html" title="11.7. whichdb — Guess which DBM module created a database"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="11.5. marshal — Internal Python object serialization"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-anydbm">
<span id="anydbm-generic-access-to-dbm-style-databases"></span><h1>11.6. <a class="reference internal" href="#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a> — Generic access to DBM-style databases<a class="headerlink" href="#module-anydbm" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a> module has been renamed to <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p id="index-0"><a class="reference internal" href="#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a> is a generic interface to variants of the DBM database —
<a class="reference internal" href="dbhash.html#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a> (requires <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a>), <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a>, or <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>.  If none of
these modules is installed, the slow-but-simple implementation in module
<a class="reference internal" href="dumbdbm.html#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a> will be used.</p>
<dl class="function">
<dt id="anydbm.open">
<code class="descclassname">anydbm.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#anydbm.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the database file <em>filename</em> and return a corresponding object.</p>
<p>If the database file already exists, the <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a> module is used to
determine its type and the appropriate module is used; if it does not exist,
the first module listed above that can be imported is used.</p>
<p>The optional <em>flag</em> argument must be one of these values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>Open existing database for reading only
(default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span></code></td>
<td>Open existing database for reading and
writing</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Open database for reading and writing,
creating it if it doesn’t exist</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Always create a new, empty database, open
for reading and writing</td>
</tr>
</tbody>
</table>
<p>If not specified, the default value is <code class="docutils literal notranslate"><span class="pre">'r'</span></code>.</p>
<p>The optional <em>mode</em> argument is the Unix mode of the file, used only when the
database has to be created.  It defaults to octal <code class="docutils literal notranslate"><span class="pre">0666</span></code> (and will be
modified by the prevailing umask).</p>
</dd></dl>

<dl class="exception">
<dt id="anydbm.error">
<em class="property">exception </em><code class="descclassname">anydbm.</code><code class="descname">error</code><a class="headerlink" href="#anydbm.error" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple containing the exceptions that can be raised by each of the supported
modules, with a unique exception also named <a class="reference internal" href="#anydbm.error" title="anydbm.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">anydbm.error</span></code></a> as the first
item — the latter is used when <a class="reference internal" href="#anydbm.error" title="anydbm.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">anydbm.error</span></code></a> is raised.</p>
</dd></dl>

<p>The object returned by <a class="reference internal" href="#anydbm.open" title="anydbm.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> supports most of the same functionality as
dictionaries; keys and their corresponding values can be stored, retrieved, and
deleted, and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code> methods are available.  Keys
and values must always be strings.</p>
<p>The following example records some hostnames and a corresponding title,  and
then prints out the contents of the database:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">anydbm</span>

<span class="c1"># Open database, creating it if necessary.</span>
<span class="n">db</span> <span class="o">=</span> <span class="n">anydbm</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;cache&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>

<span class="c1"># Record some values</span>
<span class="n">db</span><span class="p">[</span><span class="s1">&#39;www.python.org&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Python Website&#39;</span>
<span class="n">db</span><span class="p">[</span><span class="s1">&#39;www.cnn.com&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Cable News Network&#39;</span>

<span class="c1"># Loop through contents.  Other dictionary methods</span>
<span class="c1"># such as .keys(), .values() also work.</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">db</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
    <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">v</span>

<span class="c1"># Storing a non-string key or value will raise an exception (most</span>
<span class="c1"># likely a TypeError).</span>
<span class="n">db</span><span class="p">[</span><span class="s1">&#39;www.yahoo.com&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4</span>

<span class="c1"># Close when done.</span>
<span class="n">db</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>In addition to the dictionary-like methods, <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> objects
provide the following method:</p>
<dl class="function">
<dt id="anydbm.close">
<code class="descclassname">anydbm.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#anydbm.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> database.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="dbhash.html#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a></dt>
<dd>BSD <code class="docutils literal notranslate"><span class="pre">db</span></code> database interface.</dd>
<dt>Module <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a></dt>
<dd>Standard Unix database interface.</dd>
<dt>Module <a class="reference internal" href="dumbdbm.html#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a></dt>
<dd>Portable implementation of the <code class="docutils literal notranslate"><span class="pre">dbm</span></code> interface.</dd>
<dt>Module <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a></dt>
<dd>GNU database interface, based on the <code class="docutils literal notranslate"><span class="pre">dbm</span></code> interface.</dd>
<dt>Module <a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a></dt>
<dd>General object persistence built on top of  the Python <code class="docutils literal notranslate"><span class="pre">dbm</span></code> interface.</dd>
<dt>Module <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a></dt>
<dd>Utility module used to determine the type of an existing database.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="marshal.html"
                        title="previous chapter">11.5. <code class="docutils literal notranslate"><span class="pre">marshal</span></code> — Internal Python object serialization</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="whichdb.html"
                        title="next chapter">11.7. <code class="docutils literal notranslate"><span class="pre">whichdb</span></code> — Guess which DBM module created a database</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/anydbm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whichdb.html" title="11.7. whichdb — Guess which DBM module created a database"
             >next</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="11.5. marshal — Internal Python object serialization"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\;�	^'^'html/library/archiving.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12. Data Compression and Archiving &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12.1. zlib — Compression compatible with gzip" href="zlib.html" />
    <link rel="prev" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases" href="sqlite3.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/archiving.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zlib.html" title="12.1. zlib — Compression compatible with gzip"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sqlite3.html" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-compression-and-archiving">
<span id="archiving"></span><h1>12. Data Compression and Archiving<a class="headerlink" href="#data-compression-and-archiving" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter support data compression with the zlib,
gzip, and bzip2 algorithms, and  the creation of ZIP- and tar-format archives.
See also <a class="reference internal" href="shutil.html#archiving-operations"><span class="std std-ref">Archiving operations</span></a> provided by the <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="zlib.html">12.1. <code class="docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></li>
<li class="toctree-l1"><a class="reference internal" href="gzip.html">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="gzip.html#examples-of-usage">12.2.1. Examples of usage</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="bz2.html">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a><ul>
<li class="toctree-l2"><a class="reference internal" href="bz2.html#de-compression-of-files">12.3.1. (De)compression of files</a></li>
<li class="toctree-l2"><a class="reference internal" href="bz2.html#sequential-de-compression">12.3.2. Sequential (de)compression</a></li>
<li class="toctree-l2"><a class="reference internal" href="bz2.html#one-shot-de-compression">12.3.3. One-shot (de)compression</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="zipfile.html">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a><ul>
<li class="toctree-l2"><a class="reference internal" href="zipfile.html#zipfile-objects">12.4.1. ZipFile Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="zipfile.html#pyzipfile-objects">12.4.2. PyZipFile Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="zipfile.html#zipinfo-objects">12.4.3. ZipInfo Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="zipfile.html#command-line-interface">12.4.4. Command-Line Interface</a><ul>
<li class="toctree-l3"><a class="reference internal" href="zipfile.html#command-line-options">12.4.4.1. Command-line options</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tarfile.html">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html#tarfile-objects">12.5.1. TarFile Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html#tarinfo-objects">12.5.2. TarInfo Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html#examples">12.5.3. Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html#supported-tar-formats">12.5.4. Supported tar formats</a></li>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html#unicode-issues">12.5.5. Unicode issues</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="sqlite3.html"
                        title="previous chapter">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="zlib.html"
                        title="next chapter">12.1. <code class="docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/archiving.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zlib.html" title="12.1. zlib — Compression compatible with gzip"
             >next</a> |</li>
        <li class="right" >
          <a href="sqlite3.html" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����html/library/argparse.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.4. argparse — Parser for command-line options, arguments and sub-commands &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.5. optparse — Parser for command line options" href="optparse.html" />
    <link rel="prev" title="15.3. time — Time access and conversions" href="time.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/argparse.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="15.5. optparse — Parser for command line options"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="time.html" title="15.3. time — Time access and conversions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-argparse">
<span id="argparse-parser-for-command-line-options-arguments-and-sub-commands"></span><h1>15.4. <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> — Parser for command-line options, arguments and sub-commands<a class="headerlink" href="#module-argparse" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/argparse.py">Lib/argparse.py</a></p>
<hr class="docutils" />
<div class="sidebar">
<p class="first sidebar-title">Tutorial</p>
<p class="last">This page contains the API reference information. For a more gentle
introduction to Python command-line parsing, have a look at the
<a class="reference internal" href="../howto/argparse.html#id1"><span class="std std-ref">argparse tutorial</span></a>.</p>
</div>
<p>The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module makes it easy to write user-friendly command-line
interfaces. The program defines what arguments it requires, and <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>
will figure out how to parse those out of <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a>.  The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>
module also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.</p>
<div class="section" id="example">
<h2>15.4.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The following code is a Python program that takes a list of integers and
produces either the sum or the max:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;Process some integers.&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;N&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer for the accumulator&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span>
                    <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>

<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">accumulate</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">integers</span><span class="p">)</span>
</pre></div>
</div>
<p>Assuming the Python code above is saved into a file called <code class="docutils literal notranslate"><span class="pre">prog.py</span></code>, it can
be run at the command line and provides useful help messages:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py -h
<span class="go">usage: prog.py [-h] [--sum] N [N ...]</span>

<span class="go">Process some integers.</span>

<span class="go">positional arguments:</span>
<span class="go"> N           an integer for the accumulator</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --sum       sum the integers (default: find the max)</span>
</pre></div>
</div>
<p>When run with the appropriate arguments, it prints either the sum or the max of
the command-line integers:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py <span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span>
<span class="go">4</span>

<span class="gp">$</span> python prog.py <span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span> --sum
<span class="go">10</span>
</pre></div>
</div>
<p>If invalid arguments are passed in, it will issue an error:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python prog.py a b c
<span class="go">usage: prog.py [-h] [--sum] N [N ...]</span>
<span class="go">prog.py: error: argument N: invalid int value: &#39;a&#39;</span>
</pre></div>
</div>
<p>The following sections walk you through this example.</p>
<div class="section" id="creating-a-parser">
<h3>15.4.1.1. Creating a parser<a class="headerlink" href="#creating-a-parser" title="Permalink to this headline">¶</a></h3>
<p>The first step in using the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> is creating an
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;Process some integers.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> object will hold all the information necessary to
parse the command line into Python data types.</p>
</div>
<div class="section" id="adding-arguments">
<h3>15.4.1.2. Adding arguments<a class="headerlink" href="#adding-arguments" title="Permalink to this headline">¶</a></h3>
<p>Filling an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> with information about program arguments is
done by making calls to the <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> method.
Generally, these calls tell the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> how to take the strings
on the command line and turn them into objects.  This information is stored and
used when <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> is called. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;N&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer for the accumulator&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Later, calling <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> will return an object with
two attributes, <code class="docutils literal notranslate"><span class="pre">integers</span></code> and <code class="docutils literal notranslate"><span class="pre">accumulate</span></code>.  The <code class="docutils literal notranslate"><span class="pre">integers</span></code> attribute
will be a list of one or more ints, and the <code class="docutils literal notranslate"><span class="pre">accumulate</span></code> attribute will be
either the <a class="reference internal" href="functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> function, if <code class="docutils literal notranslate"><span class="pre">--sum</span></code> was specified at the command line,
or the <a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> function if it was not.</p>
</div>
<div class="section" id="parsing-arguments">
<h3>15.4.1.3. Parsing arguments<a class="headerlink" href="#parsing-arguments" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> parses arguments through the
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method.  This will inspect the command line,
convert each argument to the appropriate type and then invoke the appropriate action.
In most cases, this means a simple <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> object will be built up from
attributes parsed out of the command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="s1">&#39;7&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;42&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function sum&gt;, integers=[7, -1, 42])</span>
</pre></div>
</div>
<p>In a script, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> will typically be called with no
arguments, and the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> will automatically determine the
command-line arguments from <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a>.</p>
</div>
</div>
<div class="section" id="argumentparser-objects">
<h2>15.4.2. ArgumentParser objects<a class="headerlink" href="#argumentparser-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="argparse.ArgumentParser">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">ArgumentParser</code><span class="sig-paren">(</span><em>prog=None</em>, <em>usage=None</em>, <em>description=None</em>, <em>epilog=None</em>, <em>parents=[]</em>, <em>formatter_class=argparse.HelpFormatter</em>, <em>prefix_chars='-'</em>, <em>fromfile_prefix_chars=None</em>, <em>argument_default=None</em>, <em>conflict_handler='error'</em>, <em>add_help=True</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> object. All parameters should be passed
as keyword arguments. Each parameter has its own more detailed description
below, but in short they are:</p>
<ul class="simple">
<li><a class="reference internal" href="#prog">prog</a> - The name of the program (default: <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>)</li>
<li><a class="reference internal" href="#usage">usage</a> - The string describing the program usage (default: generated from
arguments added to parser)</li>
<li><a class="reference internal" href="#description">description</a> - Text to display before the argument help (default: none)</li>
<li><a class="reference internal" href="#epilog">epilog</a> - Text to display after the argument help (default: none)</li>
<li><a class="reference internal" href="#parents">parents</a> - A list of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects whose arguments should
also be included</li>
<li><a class="reference internal" href="#formatter-class">formatter_class</a> - A class for customizing the help output</li>
<li><a class="reference internal" href="#prefix-chars">prefix_chars</a> - The set of characters that prefix optional arguments
(default: ‘-‘)</li>
<li><a class="reference internal" href="#fromfile-prefix-chars">fromfile_prefix_chars</a> - The set of characters that prefix files from
which additional arguments should be read (default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</li>
<li><a class="reference internal" href="#argument-default">argument_default</a> - The global default value for arguments
(default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</li>
<li><a class="reference internal" href="#conflict-handler">conflict_handler</a> - The strategy for resolving conflicting optionals
(usually unnecessary)</li>
<li><a class="reference internal" href="#add-help">add_help</a> - Add a <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code> option to the parser (default: <code class="docutils literal notranslate"><span class="pre">True</span></code>)</li>
</ul>
</dd></dl>

<p>The following sections describe how each of these are used.</p>
<div class="section" id="prog">
<h3>15.4.2.1. prog<a class="headerlink" href="#prog" title="Permalink to this headline">¶</a></h3>
<p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects use <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> to determine
how to display the name of the program in help messages.  This default is almost
always desirable because it will make the help messages match how the program was
invoked on the command line.  For example, consider a file named
<code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> with the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>The help for this program will display <code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> as the program name
(regardless of where the program was invoked from):</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
<span class="gp">$</span> <span class="nb">cd</span> ..
<span class="gp">$</span> python subdir/myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
</pre></div>
</div>
<p>To change this default behavior, another value can be supplied using the
<code class="docutils literal notranslate"><span class="pre">prog=</span></code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;myprogram&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: myprogram [-h]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p>Note that the program name, whether determined from <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> or from the
<code class="docutils literal notranslate"><span class="pre">prog=</span></code> argument, is available to help messages using the <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> format
specifier.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;myprogram&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo of the </span><span class="si">%(prog)s</span><span class="s1"> program&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: myprogram [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo of the myprogram program</span>
</pre></div>
</div>
</div>
<div class="section" id="usage">
<h3>15.4.2.2. usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h3>
<p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> calculates the usage message from the
arguments it contains:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [--foo [FOO]] bar [bar ...]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar          bar help</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help   show this help message and exit</span>
<span class="go"> --foo [FOO]  foo help</span>
</pre></div>
</div>
<p>The default message can be overridden with the <code class="docutils literal notranslate"><span class="pre">usage=</span></code> keyword argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">usage</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(prog)s</span><span class="s1"> [options]&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [options]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar          bar help</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help   show this help message and exit</span>
<span class="go"> --foo [FOO]  foo help</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> format specifier is available to fill in the program name in
your usage messages.</p>
</div>
<div class="section" id="description">
<h3>15.4.2.3. description<a class="headerlink" href="#description" title="Permalink to this headline">¶</a></h3>
<p>Most calls to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> constructor will use the
<code class="docutils literal notranslate"><span class="pre">description=</span></code> keyword argument.  This argument gives a brief description of
what the program does and how it works.  In help messages, the description is
displayed between the command-line usage string and the help messages for the
various arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;A foo that bars&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: argparse.py [-h]</span>

<span class="go">A foo that bars</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p>By default, the description will be line-wrapped so that it fits within the
given space.  To change this behavior, see the <a class="reference internal" href="#formatter-class">formatter_class</a> argument.</p>
</div>
<div class="section" id="epilog">
<h3>15.4.2.4. epilog<a class="headerlink" href="#epilog" title="Permalink to this headline">¶</a></h3>
<p>Some programs like to display additional description of the program after the
description of the arguments.  Such text can be specified using the <code class="docutils literal notranslate"><span class="pre">epilog=</span></code>
argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="s1">&#39;A foo that bars&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">epilog</span><span class="o">=</span><span class="s2">&quot;And that&#39;s how you&#39;d foo a bar&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: argparse.py [-h]</span>

<span class="go">A foo that bars</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>

<span class="go">And that&#39;s how you&#39;d foo a bar</span>
</pre></div>
</div>
<p>As with the <a class="reference internal" href="#description">description</a> argument, the <code class="docutils literal notranslate"><span class="pre">epilog=</span></code> text is by default
line-wrapped, but this behavior can be adjusted with the <a class="reference internal" href="#formatter-class">formatter_class</a>
argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>.</p>
</div>
<div class="section" id="parents">
<h3>15.4.2.5. parents<a class="headerlink" href="#parents" title="Permalink to this headline">¶</a></h3>
<p>Sometimes, several parsers share a common set of arguments. Rather than
repeating the definitions of these arguments, a single parser with all the
shared arguments and passed to <code class="docutils literal notranslate"><span class="pre">parents=</span></code> argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>
can be used.  The <code class="docutils literal notranslate"><span class="pre">parents=</span></code> argument takes a list of <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>
objects, collects all the positional and optional actions from them, and adds
these actions to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> object being constructed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parent_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parent_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--parent&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">parents</span><span class="o">=</span><span class="p">[</span><span class="n">parent_parser</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--parent&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;XXX&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;XXX&#39;, parent=2)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">parents</span><span class="o">=</span><span class="p">[</span><span class="n">parent_parser</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="s1">&#39;YYY&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;YYY&#39;, parent=None)</span>
</pre></div>
</div>
<p>Note that most parent parsers will specify <code class="docutils literal notranslate"><span class="pre">add_help=False</span></code>.  Otherwise, the
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> will see two <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code> options (one in the parent
and one in the child) and raise an error.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">You must fully initialize the parsers before passing them via <code class="docutils literal notranslate"><span class="pre">parents=</span></code>.
If you change the parent parsers after the child parser, those changes will
not be reflected in the child.</p>
</div>
</div>
<div class="section" id="formatter-class">
<h3>15.4.2.6. formatter_class<a class="headerlink" href="#formatter-class" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects allow the help formatting to be customized by
specifying an alternate formatting class.  Currently, there are three such
classes:</p>
<dl class="class">
<dt id="argparse.RawDescriptionHelpFormatter">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">RawDescriptionHelpFormatter</code><a class="headerlink" href="#argparse.RawDescriptionHelpFormatter" title="Permalink to this definition">¶</a></dt>
<dt id="argparse.RawTextHelpFormatter">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">RawTextHelpFormatter</code><a class="headerlink" href="#argparse.RawTextHelpFormatter" title="Permalink to this definition">¶</a></dt>
<dt id="argparse.ArgumentDefaultsHelpFormatter">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">ArgumentDefaultsHelpFormatter</code><a class="headerlink" href="#argparse.ArgumentDefaultsHelpFormatter" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The first two allow more control over how textual descriptions are displayed,
while the last automatically adds information about argument default values.</p>
<p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects line-wrap the <a class="reference internal" href="#description">description</a> and
<a class="reference internal" href="#epilog">epilog</a> texts in command-line help messages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="s1">&#39;&#39;&#39;this description</span>
<span class="gp">... </span><span class="s1">        was indented weird</span>
<span class="gp">... </span><span class="s1">            but that is okay&#39;&#39;&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">epilog</span><span class="o">=</span><span class="s1">&#39;&#39;&#39;</span>
<span class="gp">... </span><span class="s1">            likewise for this epilog whose whitespace will</span>
<span class="gp">... </span><span class="s1">        be cleaned up and whose words will be wrapped</span>
<span class="gp">... </span><span class="s1">        across a couple lines&#39;&#39;&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h]</span>

<span class="go">this description was indented weird but that is okay</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>

<span class="go">likewise for this epilog whose whitespace will be cleaned up and whose words</span>
<span class="go">will be wrapped across a couple lines</span>
</pre></div>
</div>
<p>Passing <a class="reference internal" href="#argparse.RawDescriptionHelpFormatter" title="argparse.RawDescriptionHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawDescriptionHelpFormatter</span></code></a> as <code class="docutils literal notranslate"><span class="pre">formatter_class=</span></code>
indicates that <a class="reference internal" href="#description">description</a> and <a class="reference internal" href="#epilog">epilog</a> are already correctly formatted and
should not be line-wrapped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">formatter_class</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">RawDescriptionHelpFormatter</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">description</span><span class="o">=</span><span class="n">textwrap</span><span class="o">.</span><span class="n">dedent</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;</span><span class="se">\</span>
<span class="gp">... </span><span class="s1">        Please do not mess up this text!</span>
<span class="gp">... </span><span class="s1">        --------------------------------</span>
<span class="gp">... </span><span class="s1">            I have indented it</span>
<span class="gp">... </span><span class="s1">            exactly the way</span>
<span class="gp">... </span><span class="s1">            I want it</span>
<span class="gp">... </span><span class="s1">        &#39;&#39;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h]</span>

<span class="go">Please do not mess up this text!</span>
<span class="go">--------------------------------</span>
<span class="go">   I have indented it</span>
<span class="go">   exactly the way</span>
<span class="go">   I want it</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p><a class="reference internal" href="#argparse.RawTextHelpFormatter" title="argparse.RawTextHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawTextHelpFormatter</span></code></a> maintains whitespace for all sorts of help text,
including argument descriptions. However, multiple new lines are replaced with
one. If you wish to preserve multiple blank lines, add spaces between the
newlines.</p>
<p>The other formatter class available, <a class="reference internal" href="#argparse.ArgumentDefaultsHelpFormatter" title="argparse.ArgumentDefaultsHelpFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentDefaultsHelpFormatter</span></code></a>,
will add information about the default value of each of the arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">formatter_class</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentDefaultsHelpFormatter</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;FOO!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;BAR!&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar [bar ...]]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar         BAR! (default: [1, 2, 3])</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   FOO! (default: 42)</span>
</pre></div>
</div>
</div>
<div class="section" id="prefix-chars">
<h3>15.4.2.7. prefix_chars<a class="headerlink" href="#prefix-chars" title="Permalink to this headline">¶</a></h3>
<p>Most command-line options will use <code class="docutils literal notranslate"><span class="pre">-</span></code> as the prefix, e.g. <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code>.
Parsers that need to support different or additional prefix
characters, e.g. for options
like <code class="docutils literal notranslate"><span class="pre">+f</span></code> or <code class="docutils literal notranslate"><span class="pre">/foo</span></code>, may specify them using the <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> argument
to the ArgumentParser constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">prefix_chars</span><span class="o">=</span><span class="s1">&#39;-+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;+f&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;++bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;+f X ++bar Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;Y&#39;, f=&#39;X&#39;)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> argument defaults to <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. Supplying a set of
characters that does not include <code class="docutils literal notranslate"><span class="pre">-</span></code> will cause <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code> options to be
disallowed.</p>
</div>
<div class="section" id="fromfile-prefix-chars">
<h3>15.4.2.8. fromfile_prefix_chars<a class="headerlink" href="#fromfile-prefix-chars" title="Permalink to this headline">¶</a></h3>
<p>Sometimes, for example when dealing with a particularly long argument lists, it
may make sense to keep the list of arguments in a file rather than typing it out
at the command line.  If the <code class="docutils literal notranslate"><span class="pre">fromfile_prefix_chars=</span></code> argument is given to the
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> constructor, then arguments that start with any of the
specified characters will be treated as files, and will be replaced by the
arguments they contain.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;args.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;-f</span><span class="se">\n</span><span class="s1">bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">fromfile_prefix_chars</span><span class="o">=</span><span class="s1">&#39;@&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="s1">&#39;@args.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(f=&#39;bar&#39;)</span>
</pre></div>
</div>
<p>Arguments read from a file must by default be one per line (but see also
<a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_arg_line_to_args()</span></code></a>) and are treated as if they
were in the same place as the original file referencing argument on the command
line.  So in the example above, the expression <code class="docutils literal notranslate"><span class="pre">['-f',</span> <span class="pre">'foo',</span> <span class="pre">'&#64;args.txt']</span></code>
is considered equivalent to the expression <code class="docutils literal notranslate"><span class="pre">['-f',</span> <span class="pre">'foo',</span> <span class="pre">'-f',</span> <span class="pre">'bar']</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">fromfile_prefix_chars=</span></code> argument defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning that
arguments will never be treated as file references.</p>
</div>
<div class="section" id="argument-default">
<h3>15.4.2.9. argument_default<a class="headerlink" href="#argument-default" title="Permalink to this headline">¶</a></h3>
<p>Generally, argument defaults are specified either by passing a default to
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> or by calling the
<a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> methods with a specific set of name-value
pairs.  Sometimes however, it may be useful to specify a single parser-wide
default for arguments.  This can be accomplished by passing the
<code class="docutils literal notranslate"><span class="pre">argument_default=</span></code> keyword argument to <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>.  For example,
to globally suppress attribute creation on <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>
calls, we supply <code class="docutils literal notranslate"><span class="pre">argument_default=SUPPRESS</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">argument_default</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=&#39;1&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace()</span>
</pre></div>
</div>
</div>
<div class="section" id="conflict-handler">
<h3>15.4.2.10. conflict_handler<a class="headerlink" href="#conflict-handler" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects do not allow two actions with the same option
string.  By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects raise an exception if an
attempt is made to create an argument with an option string that is already in
use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;old foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;new foo help&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="gr"> ..</span>
<span class="gr">ArgumentError</span>: <span class="n">argument --foo: conflicting option string(s): --foo</span>
</pre></div>
</div>
<p>Sometimes (e.g. when using <a class="reference internal" href="#parents">parents</a>) it may be useful to simply override any
older arguments with the same option string.  To get this behavior, the value
<code class="docutils literal notranslate"><span class="pre">'resolve'</span></code> can be supplied to the <code class="docutils literal notranslate"><span class="pre">conflict_handler=</span></code> argument of
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">conflict_handler</span><span class="o">=</span><span class="s1">&#39;resolve&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;old foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;new foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-f FOO] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> -f FOO      old foo help</span>
<span class="go"> --foo FOO   new foo help</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects only remove an action if all of its
option strings are overridden.  So, in the example above, the old <code class="docutils literal notranslate"><span class="pre">-f/--foo</span></code>
action is retained as the <code class="docutils literal notranslate"><span class="pre">-f</span></code> action, because only the <code class="docutils literal notranslate"><span class="pre">--foo</span></code> option
string was overridden.</p>
</div>
<div class="section" id="add-help">
<h3>15.4.2.11. add_help<a class="headerlink" href="#add-help" title="Permalink to this headline">¶</a></h3>
<p>By default, ArgumentParser objects add an option which simply displays
the parser’s help message. For example, consider a file named
<code class="docutils literal notranslate"><span class="pre">myprogram.py</span></code> containing the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">-h</span></code> or <code class="docutils literal notranslate"><span class="pre">--help</span></code> is supplied at the command line, the ArgumentParser
help will be printed:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python myprogram.py --help
<span class="go">usage: myprogram.py [-h] [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO   foo help</span>
</pre></div>
</div>
<p>Occasionally, it may be useful to disable the addition of this help option.
This can be achieved by passing <code class="docutils literal notranslate"><span class="pre">False</span></code> as the <code class="docutils literal notranslate"><span class="pre">add_help=</span></code> argument to
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--foo FOO]</span>

<span class="go">optional arguments:</span>
<span class="go"> --foo FOO  foo help</span>
</pre></div>
</div>
<p>The help option is typically <code class="docutils literal notranslate"><span class="pre">-h/--help</span></code>. The exception to this is
if the <code class="docutils literal notranslate"><span class="pre">prefix_chars=</span></code> is specified and does not include <code class="docutils literal notranslate"><span class="pre">-</span></code>, in
which case <code class="docutils literal notranslate"><span class="pre">-h</span></code> and <code class="docutils literal notranslate"><span class="pre">--help</span></code> are not valid options.  In
this case, the first character in <code class="docutils literal notranslate"><span class="pre">prefix_chars</span></code> is used to prefix
the help options:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">prefix_chars</span><span class="o">=</span><span class="s1">&#39;+/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [+h]</span>

<span class="go">optional arguments:</span>
<span class="go">  +h, ++help  show this help message and exit</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-add-argument-method">
<h2>15.4.3. The add_argument() method<a class="headerlink" href="#the-add-argument-method" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="argparse.ArgumentParser.add_argument">
<code class="descclassname">ArgumentParser.</code><code class="descname">add_argument</code><span class="sig-paren">(</span><em>name or flags...</em><span class="optional">[</span>, <em>action</em><span class="optional">]</span><span class="optional">[</span>, <em>nargs</em><span class="optional">]</span><span class="optional">[</span>, <em>const</em><span class="optional">]</span><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="optional">[</span>, <em>type</em><span class="optional">]</span><span class="optional">[</span>, <em>choices</em><span class="optional">]</span><span class="optional">[</span>, <em>required</em><span class="optional">]</span><span class="optional">[</span>, <em>help</em><span class="optional">]</span><span class="optional">[</span>, <em>metavar</em><span class="optional">]</span><span class="optional">[</span>, <em>dest</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_argument" title="Permalink to this definition">¶</a></dt>
<dd><p>Define how a single command-line argument should be parsed.  Each parameter
has its own more detailed description below, but in short they are:</p>
<ul class="simple">
<li><a class="reference internal" href="#name-or-flags">name or flags</a> - Either a name or a list of option strings, e.g. <code class="docutils literal notranslate"><span class="pre">foo</span></code>
or <code class="docutils literal notranslate"><span class="pre">-f,</span> <span class="pre">--foo</span></code>.</li>
<li><a class="reference internal" href="#action">action</a> - The basic type of action to be taken when this argument is
encountered at the command line.</li>
<li><a class="reference internal" href="#nargs">nargs</a> - The number of command-line arguments that should be consumed.</li>
<li><a class="reference internal" href="#const">const</a> - A constant value required by some <a class="reference internal" href="#action">action</a> and <a class="reference internal" href="#nargs">nargs</a> selections.</li>
<li><a class="reference internal" href="#default">default</a> - The value produced if the argument is absent from the
command line.</li>
<li><a class="reference internal" href="#type">type</a> - The type to which the command-line argument should be converted.</li>
<li><a class="reference internal" href="#choices">choices</a> - A container of the allowable values for the argument.</li>
<li><a class="reference internal" href="#required">required</a> - Whether or not the command-line option may be omitted
(optionals only).</li>
<li><a class="reference internal" href="#help">help</a> - A brief description of what the argument does.</li>
<li><a class="reference internal" href="#metavar">metavar</a> - A name for the argument in usage messages.</li>
<li><a class="reference internal" href="#dest">dest</a> - The name of the attribute to be added to the object returned by
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>.</li>
</ul>
</dd></dl>

<p>The following sections describe how each of these are used.</p>
<div class="section" id="name-or-flags">
<h3>15.4.3.1. name or flags<a class="headerlink" href="#name-or-flags" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> method must know whether an optional
argument, like <code class="docutils literal notranslate"><span class="pre">-f</span></code> or <code class="docutils literal notranslate"><span class="pre">--foo</span></code>, or a positional argument, like a list of
filenames, is expected.  The first arguments passed to
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> must therefore be either a series of
flags, or a simple argument name.  For example, an optional argument could
be created like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>while a positional argument could be created like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>When <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> is called, optional arguments will be
identified by the <code class="docutils literal notranslate"><span class="pre">-</span></code> prefix, and the remaining arguments will be assumed to
be positional:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;BAR&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;BAR&#39;, foo=&#39;FOO&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-f FOO] bar</span>
<span class="go">PROG: error: too few arguments</span>
</pre></div>
</div>
</div>
<div class="section" id="action">
<h3>15.4.3.2. action<a class="headerlink" href="#action" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects associate command-line arguments with actions.  These
actions can do just about anything with the command-line arguments associated with
them, though most actions simply add an attribute to the object returned by
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>.  The <code class="docutils literal notranslate"><span class="pre">action</span></code> keyword argument specifies
how the command-line arguments should be handled. The supplied actions are:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'store'</span></code> - This just stores the argument’s value.  This is the default
action. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo=&#39;1&#39;)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> - This stores the value specified by the <a class="reference internal" href="#const">const</a> keyword
argument.  The <code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> action is most commonly used with
optional arguments that specify some sort of flag.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'store_true'</span></code> and <code class="docutils literal notranslate"><span class="pre">'store_false'</span></code> - These are special cases of
<code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> using for storing the values <code class="docutils literal notranslate"><span class="pre">True</span></code> and <code class="docutils literal notranslate"><span class="pre">False</span></code>
respectively.  In addition, they create default values of <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>
respectively.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo --bar&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=False, baz=True, foo=True)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'append'</span></code> - This stores a list, and appends each argument value to the
list.  This is useful to allow an option to be specified multiple times.
Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1 --foo 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo=[&#39;1&#39;, &#39;2&#39;])</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'append_const'</span></code> - This stores a list, and appends the value specified by
the <a class="reference internal" href="#const">const</a> keyword argument to the list.  (Note that the <a class="reference internal" href="#const">const</a> keyword
argument defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.)  The <code class="docutils literal notranslate"><span class="pre">'append_const'</span></code> action is typically
useful when multiple arguments need to store constants to the same list. For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--str&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;types&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">str</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--int&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;types&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--str --int&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(types=[&lt;type &#39;str&#39;&gt;, &lt;type &#39;int&#39;&gt;])</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'count'</span></code> - This counts the number of times a keyword argument occurs. For
example, this is useful for increasing verbosity levels:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--verbose&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-vvv&#39;</span><span class="p">])</span>
<span class="go">Namespace(verbose=3)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'help'</span></code> - This prints a complete help message for all the options in the
current parser and then exits. By default a help action is automatically
added to the parser. See <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> for details of how the
output is created.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'version'</span></code> - This expects a <code class="docutils literal notranslate"><span class="pre">version=</span></code> keyword argument in the
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> call, and prints version information
and exits when invoked:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--version&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;version&#39;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s1">&#39;</span><span class="si">%(prog)s</span><span class="s1"> 2.0&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--version&#39;</span><span class="p">])</span>
<span class="go">PROG 2.0</span>
</pre></div>
</div>
</li>
</ul>
<p>You may also specify an arbitrary action by passing an Action subclass or
other object that implements the same interface.  The recommended way to do
this is to extend <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code class="xref py py-class docutils literal notranslate"><span class="pre">Action</span></code></a>, overriding the <code class="docutils literal notranslate"><span class="pre">__call__</span></code> method
and optionally the <code class="docutils literal notranslate"><span class="pre">__init__</span></code> method.</p>
<p>An example of a custom action:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">FooAction</span><span class="p">(</span><span class="n">argparse</span><span class="o">.</span><span class="n">Action</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">option_strings</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">nargs</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;nargs not allowed&quot;</span><span class="p">)</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">FooAction</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">option_strings</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">option_string</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%r</span><span class="s1"> </span><span class="si">%r</span><span class="s1"> </span><span class="si">%r</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">option_string</span><span class="p">)</span>
<span class="gp">... </span>        <span class="nb">setattr</span><span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="n">values</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;1 --foo 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=None, foo=None) &#39;1&#39; None</span>
<span class="go">Namespace(bar=&#39;1&#39;, foo=None) &#39;2&#39; &#39;--foo&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">Namespace(bar=&#39;1&#39;, foo=&#39;2&#39;)</span>
</pre></div>
</div>
<p>For more details, see <a class="reference internal" href="#argparse.Action" title="argparse.Action"><code class="xref py py-class docutils literal notranslate"><span class="pre">Action</span></code></a>.</p>
</div>
<div class="section" id="nargs">
<h3>15.4.3.3. nargs<a class="headerlink" href="#nargs" title="Permalink to this headline">¶</a></h3>
<p>ArgumentParser objects usually associate a single command-line argument with a
single action to be taken.  The <code class="docutils literal notranslate"><span class="pre">nargs</span></code> keyword argument associates a
different number of command-line arguments with a single action.  The supported
values are:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">N</span></code> (an integer).  <code class="docutils literal notranslate"><span class="pre">N</span></code> arguments from the command line will be gathered
together into a list.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;c --foo a b&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=[&#39;c&#39;], foo=[&#39;a&#39;, &#39;b&#39;])</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">nargs=1</span></code> produces a list of one item.  This is different from
the default, in which the item is produced by itself.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'?'</span></code>. One argument will be consumed from the command line if possible, and
produced as a single item.  If no command-line argument is present, the value from
<a class="reference internal" href="#default">default</a> will be produced.  Note that for optional arguments, there is an
additional case - the option string is present but not followed by a
command-line argument.  In this case the value from <a class="reference internal" href="#const">const</a> will be produced.  Some
examples to illustrate this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XX&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;YY&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XX&#39;, foo=&#39;YY&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XX&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XX&#39;, foo=&#39;c&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(bar=&#39;d&#39;, foo=&#39;d&#39;)</span>
</pre></div>
</div>
<p>One of the more common uses of <code class="docutils literal notranslate"><span class="pre">nargs='?'</span></code> is to allow optional input and
output files:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;infile&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;r&#39;</span><span class="p">),</span>
<span class="gp">... </span>                    <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;outfile&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">),</span>
<span class="gp">... </span>                    <span class="n">default</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;input.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;output.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(infile=&lt;open file &#39;input.txt&#39;, mode &#39;r&#39; at 0x...&gt;,</span>
<span class="go">          outfile=&lt;open file &#39;output.txt&#39;, mode &#39;w&#39; at 0x...&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(infile=&lt;open file &#39;&lt;stdin&gt;&#39;, mode &#39;r&#39; at 0x...&gt;,</span>
<span class="go">          outfile=&lt;open file &#39;&lt;stdout&gt;&#39;, mode &#39;w&#39; at 0x...&gt;)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'*'</span></code>.  All command-line arguments present are gathered into a list.  Note that
it generally doesn’t make much sense to have more than one positional argument
with <code class="docutils literal notranslate"><span class="pre">nargs='*'</span></code>, but multiple optional arguments with <code class="docutils literal notranslate"><span class="pre">nargs='*'</span></code> is
possible.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;a b --foo x y --bar 1 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=[&#39;1&#39;, &#39;2&#39;], baz=[&#39;a&#39;, &#39;b&#39;], foo=[&#39;x&#39;, &#39;y&#39;])</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">'+'</span></code>. Just like <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, all command-line args present are gathered into a
list.  Additionally, an error message will be generated if there wasn’t at
least one command-line argument present.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=[&#39;a&#39;, &#39;b&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: PROG [-h] foo [foo ...]</span>
<span class="go">PROG: error: too few arguments</span>
</pre></div>
</div>
</li>
</ul>
<ul id="argparse-remainder">
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">argparse.REMAINDER</span></code>.  All the remaining command-line arguments are gathered
into a list.  This is commonly useful for command line utilities that dispatch
to other command line utilities:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;command&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;args&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">REMAINDER</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo B cmd --arg1 XX ZZ&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(args=[&#39;--arg1&#39;, &#39;XX&#39;, &#39;ZZ&#39;], command=&#39;cmd&#39;, foo=&#39;B&#39;)</span>
</pre></div>
</div>
</li>
</ul>
<p>If the <code class="docutils literal notranslate"><span class="pre">nargs</span></code> keyword argument is not provided, the number of arguments consumed
is determined by the <a class="reference internal" href="#action">action</a>.  Generally this means a single command-line argument
will be consumed and a single item (not a list) will be produced.</p>
</div>
<div class="section" id="const">
<h3>15.4.3.4. const<a class="headerlink" href="#const" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">const</span></code> argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> is used to hold
constant values that are not read from the command line but are required for
the various <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> actions.  The two most common uses of it are:</p>
<ul class="simple">
<li>When <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> is called with
<code class="docutils literal notranslate"><span class="pre">action='store_const'</span></code> or <code class="docutils literal notranslate"><span class="pre">action='append_const'</span></code>.  These actions add the
<code class="docutils literal notranslate"><span class="pre">const</span></code> value to one of the attributes of the object returned by
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>. See the <a class="reference internal" href="#action">action</a> description for examples.</li>
<li>When <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> is called with option strings
(like <code class="docutils literal notranslate"><span class="pre">-f</span></code> or <code class="docutils literal notranslate"><span class="pre">--foo</span></code>) and <code class="docutils literal notranslate"><span class="pre">nargs='?'</span></code>.  This creates an optional
argument that can be followed by zero or one command-line arguments.
When parsing the command line, if the option string is encountered with no
command-line argument following it, the value of <code class="docutils literal notranslate"><span class="pre">const</span></code> will be assumed instead.
See the <a class="reference internal" href="#nargs">nargs</a> description for examples.</li>
</ul>
<p>With the <code class="docutils literal notranslate"><span class="pre">'store_const'</span></code> and <code class="docutils literal notranslate"><span class="pre">'append_const'</span></code> actions, the <code class="docutils literal notranslate"><span class="pre">const</span></code>
keyword argument must be given.  For other actions, it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
<div class="section" id="default">
<h3>15.4.3.5. default<a class="headerlink" href="#default" title="Permalink to this headline">¶</a></h3>
<p>All optional arguments and some positional arguments may be omitted at the
command line.  The <code class="docutils literal notranslate"><span class="pre">default</span></code> keyword argument of
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>, whose value defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>,
specifies what value should be used if the command-line argument is not present.
For optional arguments, the <code class="docutils literal notranslate"><span class="pre">default</span></code> value is used when the option string
was not present at the command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;2&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
<p>If the <code class="docutils literal notranslate"><span class="pre">default</span></code> value is a string, the parser parses the value as if it
were a command-line argument.  In particular, the parser applies any <a class="reference internal" href="#type">type</a>
conversion argument, if provided, before setting the attribute on the
<a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> return value.  Otherwise, the parser uses the value as is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--length&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;10&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--width&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mf">10.5</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="go">Namespace(length=10, width=10.5)</span>
</pre></div>
</div>
<p>For positional arguments with <a class="reference internal" href="#nargs">nargs</a> equal to <code class="docutils literal notranslate"><span class="pre">?</span></code> or <code class="docutils literal notranslate"><span class="pre">*</span></code>, the <code class="docutils literal notranslate"><span class="pre">default</span></code> value
is used when no command-line argument was present:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;a&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=42)</span>
</pre></div>
</div>
<p>Providing <code class="docutils literal notranslate"><span class="pre">default=argparse.SUPPRESS</span></code> causes no attribute to be added if the
command-line argument was not present.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;1&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;1&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="type">
<h3>15.4.3.6. type<a class="headerlink" href="#type" title="Permalink to this headline">¶</a></h3>
<p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> objects read command-line arguments in as simple
strings. However, quite often the command-line string should instead be
interpreted as another type, like a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> or <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.  The
<code class="docutils literal notranslate"><span class="pre">type</span></code> keyword argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> allows any
necessary type-checking and type conversions to be performed.  Common built-in
types and functions can be used directly as the value of the <code class="docutils literal notranslate"><span class="pre">type</span></code> argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">file</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;2 temp.txt&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&lt;open file &#39;temp.txt&#39;, mode &#39;r&#39; at 0x...&gt;, foo=2)</span>
</pre></div>
</div>
<p>See the section on the <a class="reference internal" href="#default">default</a> keyword argument for information on when the
<code class="docutils literal notranslate"><span class="pre">type</span></code> argument is applied to default arguments.</p>
<p>To ease the use of various types of files, the argparse module provides the
factory FileType which takes the <code class="docutils literal notranslate"><span class="pre">mode=</span></code> and <code class="docutils literal notranslate"><span class="pre">bufsize=</span></code> arguments of the
<code class="docutils literal notranslate"><span class="pre">file</span></code> object.  For example, <code class="docutils literal notranslate"><span class="pre">FileType('w')</span></code> can be used to create a
writable file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;out.txt&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&lt;open file &#39;out.txt&#39;, mode &#39;w&#39; at 0x...&gt;)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">type=</span></code> can take any callable that takes a single string argument and returns
the converted value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">perfect_square</span><span class="p">(</span><span class="n">string</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">value</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">sqrt</span> <span class="o">=</span> <span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">sqrt</span> <span class="o">!=</span> <span class="nb">int</span><span class="p">(</span><span class="n">sqrt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">msg</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%r</span><span class="s2"> is not a perfect square&quot;</span> <span class="o">%</span> <span class="n">string</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentTypeError</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">perfect_square</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;9&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=9)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;7&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] foo</span>
<span class="go">PROG: error: argument foo: &#39;7&#39; is not a perfect square</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#choices">choices</a> keyword argument may be more convenient for type checkers that
simply check against a range of values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">xrange</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;7&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=7)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;11&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] {5,6,7,8,9}</span>
<span class="go">PROG: error: argument foo: invalid choice: 11 (choose from 5, 6, 7, 8, 9)</span>
</pre></div>
</div>
<p>See the <a class="reference internal" href="#choices">choices</a> section for more details.</p>
</div>
<div class="section" id="choices">
<h3>15.4.3.7. choices<a class="headerlink" href="#choices" title="Permalink to this headline">¶</a></h3>
<p>Some command-line arguments should be selected from a restricted set of values.
These can be handled by passing a container object as the <em>choices</em> keyword
argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>.  When the command line is
parsed, argument values will be checked, and an error message will be displayed
if the argument was not one of the acceptable values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;game.py&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;move&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;rock&#39;</span><span class="p">,</span> <span class="s1">&#39;paper&#39;</span><span class="p">,</span> <span class="s1">&#39;scissors&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;rock&#39;</span><span class="p">])</span>
<span class="go">Namespace(move=&#39;rock&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;fire&#39;</span><span class="p">])</span>
<span class="go">usage: game.py [-h] {rock,paper,scissors}</span>
<span class="go">game.py: error: argument move: invalid choice: &#39;fire&#39; (choose from &#39;rock&#39;,</span>
<span class="go">&#39;paper&#39;, &#39;scissors&#39;)</span>
</pre></div>
</div>
<p>Note that inclusion in the <em>choices</em> container is checked after any <a class="reference internal" href="#type">type</a>
conversions have been performed, so the type of the objects in the <em>choices</em>
container should match the <a class="reference internal" href="#type">type</a> specified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;doors.py&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;door&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;3&#39;</span><span class="p">]))</span>
<span class="go">Namespace(door=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;4&#39;</span><span class="p">])</span>
<span class="go">usage: doors.py [-h] {1,2,3}</span>
<span class="go">doors.py: error: argument door: invalid choice: 4 (choose from 1, 2, 3)</span>
</pre></div>
</div>
<p>Any object that supports the <code class="docutils literal notranslate"><span class="pre">in</span></code> operator can be passed as the <em>choices</em>
value, so <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> objects, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> objects, custom containers,
etc. are all supported.</p>
</div>
<div class="section" id="required">
<h3>15.4.3.8. required<a class="headerlink" href="#required" title="Permalink to this headline">¶</a></h3>
<p>In general, the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module assumes that flags like <code class="docutils literal notranslate"><span class="pre">-f</span></code> and <code class="docutils literal notranslate"><span class="pre">--bar</span></code>
indicate <em>optional</em> arguments, which can always be omitted at the command line.
To make an option <em>required</em>, <code class="docutils literal notranslate"><span class="pre">True</span></code> can be specified for the <code class="docutils literal notranslate"><span class="pre">required=</span></code>
keyword argument to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;BAR&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: argparse.py [-h] [--foo FOO]</span>
<span class="go">argparse.py: error: option --foo is required</span>
</pre></div>
</div>
<p>As the example shows, if an option is marked as <code class="docutils literal notranslate"><span class="pre">required</span></code>,
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> will report an error if that option is not
present at the command line.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Required options are generally considered bad form because users expect
<em>options</em> to be <em>optional</em>, and thus they should be avoided when possible.</p>
</div>
</div>
<div class="section" id="help">
<h3>15.4.3.9. help<a class="headerlink" href="#help" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">help</span></code> value is a string containing a brief description of the argument.
When a user requests help (usually by using <code class="docutils literal notranslate"><span class="pre">-h</span></code> or <code class="docutils literal notranslate"><span class="pre">--help</span></code> at the
command line), these <code class="docutils literal notranslate"><span class="pre">help</span></code> descriptions will be displayed with each
argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo the bars before frobbling&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;one of the bars to be frobbled&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-h&#39;</span><span class="p">])</span>
<span class="go">usage: frobble [-h] [--foo] bar [bar ...]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar     one of the bars to be frobbled</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo   foo the bars before frobbling</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">help</span></code> strings can include various format specifiers to avoid repetition
of things like the program name or the argument <a class="reference internal" href="#default">default</a>.  The available
specifiers include the program name, <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code> and most keyword arguments to
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>, e.g. <code class="docutils literal notranslate"><span class="pre">%(default)s</span></code>, <code class="docutils literal notranslate"><span class="pre">%(type)s</span></code>, etc.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;the bar to </span><span class="si">%(prog)s</span><span class="s1"> (default: </span><span class="si">%(default)s</span><span class="s1">)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: frobble [-h] [bar]</span>

<span class="go">positional arguments:</span>
<span class="go"> bar     the bar to frobble (default: 42)</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> supports silencing the help entry for certain options, by
setting the <code class="docutils literal notranslate"><span class="pre">help</span></code> value to <code class="docutils literal notranslate"><span class="pre">argparse.SUPPRESS</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;frobble&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: frobble [-h]</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
</pre></div>
</div>
</div>
<div class="section" id="metavar">
<h3>15.4.3.10. metavar<a class="headerlink" href="#metavar" title="Permalink to this headline">¶</a></h3>
<p>When <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> generates help messages, it needs some way to refer
to each expected argument.  By default, ArgumentParser objects use the <a class="reference internal" href="#dest">dest</a>
value as the “name” of each object.  By default, for positional argument
actions, the <a class="reference internal" href="#dest">dest</a> value is used directly, and for optional argument actions,
the <a class="reference internal" href="#dest">dest</a> value is uppercased.  So, a single positional argument with
<code class="docutils literal notranslate"><span class="pre">dest='bar'</span></code> will be referred to as <code class="docutils literal notranslate"><span class="pre">bar</span></code>. A single
optional argument <code class="docutils literal notranslate"><span class="pre">--foo</span></code> that should be followed by a single command-line argument
will be referred to as <code class="docutils literal notranslate"><span class="pre">FOO</span></code>.  An example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;X --foo Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;X&#39;, foo=&#39;Y&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage:  [-h] [--foo FOO] bar</span>

<span class="go">positional arguments:</span>
<span class="go"> bar</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo FOO</span>
</pre></div>
</div>
<p>An alternative name can be specified with <code class="docutils literal notranslate"><span class="pre">metavar</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;YYY&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;XXX&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;X --foo Y&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;X&#39;, foo=&#39;Y&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage:  [-h] [--foo YYY] XXX</span>

<span class="go">positional arguments:</span>
<span class="go"> XXX</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help  show this help message and exit</span>
<span class="go"> --foo YYY</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">metavar</span></code> only changes the <em>displayed</em> name - the name of the
attribute on the <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> object is still determined
by the <a class="reference internal" href="#dest">dest</a> value.</p>
<p>Different values of <code class="docutils literal notranslate"><span class="pre">nargs</span></code> may cause the metavar to be used multiple times.
Providing a tuple to <code class="docutils literal notranslate"><span class="pre">metavar</span></code> specifies a different display for each of the
arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-x X X] [--foo bar baz]</span>

<span class="go">optional arguments:</span>
<span class="go"> -h, --help     show this help message and exit</span>
<span class="go"> -x X X</span>
<span class="go"> --foo bar baz</span>
</pre></div>
</div>
</div>
<div class="section" id="dest">
<h3>15.4.3.11. dest<a class="headerlink" href="#dest" title="Permalink to this headline">¶</a></h3>
<p>Most <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> actions add some value as an attribute of the
object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>.  The name of this
attribute is determined by the <code class="docutils literal notranslate"><span class="pre">dest</span></code> keyword argument of
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>.  For positional argument actions,
<code class="docutils literal notranslate"><span class="pre">dest</span></code> is normally supplied as the first argument to
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;XXX&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=&#39;XXX&#39;)</span>
</pre></div>
</div>
<p>For optional argument actions, the value of <code class="docutils literal notranslate"><span class="pre">dest</span></code> is normally inferred from
the option strings.  <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> generates the value of <code class="docutils literal notranslate"><span class="pre">dest</span></code> by
taking the first long option string and stripping away the initial <code class="docutils literal notranslate"><span class="pre">--</span></code>
string.  If no long option strings were supplied, <code class="docutils literal notranslate"><span class="pre">dest</span></code> will be derived from
the first short option string by stripping the initial <code class="docutils literal notranslate"><span class="pre">-</span></code> character.  Any
internal <code class="docutils literal notranslate"><span class="pre">-</span></code> characters will be converted to <code class="docutils literal notranslate"><span class="pre">_</span></code> characters to make sure
the string is a valid attribute name.  The examples below illustrate this
behavior:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo-bar&#39;</span><span class="p">,</span> <span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-y&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-f 1 -x 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo_bar=&#39;1&#39;, x=&#39;2&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo 1 -y 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(foo_bar=&#39;1&#39;, x=&#39;2&#39;)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">dest</span></code> allows a custom attribute name to be provided:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;--foo XXX&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;XXX&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="action-classes">
<h3>15.4.3.12. Action classes<a class="headerlink" href="#action-classes" title="Permalink to this headline">¶</a></h3>
<p>Action classes implement the Action API, a callable which returns a callable
which processes arguments from the command-line. Any object which follows this
API may be passed as the <code class="docutils literal notranslate"><span class="pre">action</span></code> parameter to <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code>.</p>
<dl class="class">
<dt id="argparse.Action">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">Action</code><span class="sig-paren">(</span><em>option_strings</em>, <em>dest</em>, <em>nargs=None</em>, <em>const=None</em>, <em>default=None</em>, <em>type=None</em>, <em>choices=None</em>, <em>required=False</em>, <em>help=None</em>, <em>metavar=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.Action" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Action objects are used by an ArgumentParser to represent the information needed
to parse a single argument from one or more strings from the command line. The
Action class must accept the two positional arguments plus any keyword arguments
passed to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> except for the <code class="docutils literal notranslate"><span class="pre">action</span></code> itself.</p>
<p>Instances of Action (or return value of any callable to the <code class="docutils literal notranslate"><span class="pre">action</span></code>
parameter) should have attributes “dest”, “option_strings”, “default”, “type”,
“required”, “help”, etc. defined. The easiest way to ensure these attributes
are defined is to call <code class="docutils literal notranslate"><span class="pre">Action.__init__</span></code>.</p>
<p>Action instances should be callable, so subclasses must override the
<code class="docutils literal notranslate"><span class="pre">__call__</span></code> method, which should accept four parameters:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">parser</span></code> - The ArgumentParser object which contains this action.</li>
<li><code class="docutils literal notranslate"><span class="pre">namespace</span></code> - The <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> object that will be returned by
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>.  Most actions add an attribute to this
object using <a class="reference internal" href="functions.html#setattr" title="setattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">setattr()</span></code></a>.</li>
<li><code class="docutils literal notranslate"><span class="pre">values</span></code> - The associated command-line arguments, with any type conversions
applied.  Type conversions are specified with the <a class="reference internal" href="#type">type</a> keyword argument to
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a>.</li>
<li><code class="docutils literal notranslate"><span class="pre">option_string</span></code> - The option string that was used to invoke this action.
The <code class="docutils literal notranslate"><span class="pre">option_string</span></code> argument is optional, and will be absent if the action
is associated with a positional argument.</li>
</ul>
<p>The <code class="docutils literal notranslate"><span class="pre">__call__</span></code> method may perform arbitrary actions, but will typically set
attributes on the <code class="docutils literal notranslate"><span class="pre">namespace</span></code> based on <code class="docutils literal notranslate"><span class="pre">dest</span></code> and <code class="docutils literal notranslate"><span class="pre">values</span></code>.</p>
</div>
</div>
<div class="section" id="the-parse-args-method">
<h2>15.4.4. The parse_args() method<a class="headerlink" href="#the-parse-args-method" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="argparse.ArgumentParser.parse_args">
<code class="descclassname">ArgumentParser.</code><code class="descname">parse_args</code><span class="sig-paren">(</span><em>args=None</em>, <em>namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_args" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert argument strings to objects and assign them as attributes of the
namespace.  Return the populated namespace.</p>
<p>Previous calls to <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> determine exactly what objects are
created and how they are assigned. See the documentation for
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> for details.</p>
<ul class="simple">
<li><a class="reference internal" href="#args">args</a> - List of strings to parse.  The default is taken from
<a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a>.</li>
<li><a class="reference internal" href="#namespace">namespace</a> - An object to take the attributes.  The default is a new empty
<a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> object.</li>
</ul>
</dd></dl>

<div class="section" id="option-value-syntax">
<h3>15.4.4.1. Option value syntax<a class="headerlink" href="#option-value-syntax" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method supports several ways of
specifying the value of an option (if it takes one).  In the simplest case, the
option and its value are passed as two separate arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;X&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;X&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;FOO&#39;, x=None)</span>
</pre></div>
</div>
<p>For long options (options with names longer than a single character), the option
and value can also be passed as a single command-line argument, using <code class="docutils literal notranslate"><span class="pre">=</span></code> to
separate them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo=FOO&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;FOO&#39;, x=None)</span>
</pre></div>
</div>
<p>For short options (options only one character long), the option and its value
can be concatenated:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-xX&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;X&#39;)</span>
</pre></div>
</div>
<p>Several short options can be joined together, using only a single <code class="docutils literal notranslate"><span class="pre">-</span></code> prefix,
as long as only the last option (or none of them) requires a value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-y&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-xyzZ&#39;</span><span class="p">])</span>
<span class="go">Namespace(x=True, y=True, z=&#39;Z&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="invalid-arguments">
<h3>15.4.4.2. Invalid arguments<a class="headerlink" href="#invalid-arguments" title="Permalink to this headline">¶</a></h3>
<p>While parsing the command line, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> checks for a
variety of errors, including ambiguous options, invalid types, invalid options,
wrong number of positional arguments, etc.  When it encounters such an error,
it exits and prints the error along with a usage message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># invalid type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: argument --foo: invalid int value: &#39;spam&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># invalid option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: no such option: --bar</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># wrong number of arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;badger&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo FOO] [bar]</span>
<span class="go">PROG: error: extra arguments found: badger</span>
</pre></div>
</div>
</div>
<div class="section" id="arguments-containing">
<h3>15.4.4.3. Arguments containing <code class="docutils literal notranslate"><span class="pre">-</span></code><a class="headerlink" href="#arguments-containing" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method attempts to give errors whenever
the user has clearly made a mistake, but some situations are inherently
ambiguous.  For example, the command-line argument <code class="docutils literal notranslate"><span class="pre">-1</span></code> could either be an
attempt to specify an option or an attempt to provide a positional argument.
The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method is cautious here: positional
arguments may only begin with <code class="docutils literal notranslate"><span class="pre">-</span></code> if they look like negative numbers and
there are no options in the parser that look like negative numbers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># no negative number options, so -1 is a positional argument</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, x=&#39;-1&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># no negative number options, so -1 and -5 are positional arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;-5&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;-5&#39;, x=&#39;-1&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;one&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;?&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so -1 is an option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;X&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=None, one=&#39;X&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so -2 is an option</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-2&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-1 ONE] [foo]</span>
<span class="go">PROG: error: no such option: -2</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># negative number options present, so both -1s are options</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-1&#39;</span><span class="p">,</span> <span class="s1">&#39;-1&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [-1 ONE] [foo]</span>
<span class="go">PROG: error: argument -1: expected one argument</span>
</pre></div>
</div>
<p>If you have positional arguments that must begin with <code class="docutils literal notranslate"><span class="pre">-</span></code> and don’t look
like negative numbers, you can insert the pseudo-argument <code class="docutils literal notranslate"><span class="pre">'--'</span></code> which tells
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> that everything after that is a positional
argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--&#39;</span><span class="p">,</span> <span class="s1">&#39;-f&#39;</span><span class="p">])</span>
<span class="go">Namespace(foo=&#39;-f&#39;, one=None)</span>
</pre></div>
</div>
</div>
<div class="section" id="argument-abbreviations-prefix-matching">
<span id="prefix-matching"></span><h3>15.4.4.4. Argument abbreviations (prefix matching)<a class="headerlink" href="#argument-abbreviations-prefix-matching" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> method allows long options to be
abbreviated to a prefix, if the abbreviation is unambiguous (the prefix matches
a unique option):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-bacon&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-bac MMM&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bacon=&#39;MMM&#39;, badger=None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-bad WOOD&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bacon=None, badger=&#39;WOOD&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;-ba BA&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">usage: PROG [-h] [-bacon BACON] [-badger BADGER]</span>
<span class="go">PROG: error: ambiguous option: -ba could match -badger, -bacon</span>
</pre></div>
</div>
<p>An error is produced for arguments that could produce more than one options.</p>
</div>
<div class="section" id="beyond-sys-argv">
<span id="args"></span><h3>15.4.4.5. Beyond <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code><a class="headerlink" href="#beyond-sys-argv" title="Permalink to this headline">¶</a></h3>
<p>Sometimes it may be useful to have an ArgumentParser parse arguments other than those
of <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a>.  This can be accomplished by passing a list of strings to
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>.  This is useful for testing at the
interactive prompt:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s1">&#39;integers&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span>
<span class="gp">... </span>    <span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;an integer in the range 0..9&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s1">&#39;--sum&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;accumulate&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">default</span><span class="o">=</span><span class="nb">max</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;sum the integers (default: find the max)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;3&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function max&gt;, integers=[1, 2, 3, 4])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;3&#39;</span><span class="p">,</span> <span class="s1">&#39;4&#39;</span><span class="p">,</span> <span class="s1">&#39;--sum&#39;</span><span class="p">])</span>
<span class="go">Namespace(accumulate=&lt;built-in function sum&gt;, integers=[1, 2, 3, 4])</span>
</pre></div>
</div>
</div>
<div class="section" id="the-namespace-object">
<span id="namespace"></span><h3>15.4.4.6. The Namespace object<a class="headerlink" href="#the-namespace-object" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="argparse.Namespace">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">Namespace</code><a class="headerlink" href="#argparse.Namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Simple class used by default by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> to create
an object holding attributes and return it.</p>
</dd></dl>

<p>This class is deliberately simple, just an <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> subclass with a
readable string representation. If you prefer to have dict-like view of the
attributes, you can use the standard Python idiom, <a class="reference internal" href="functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">vars</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">{&#39;foo&#39;: &#39;BAR&#39;}</span>
</pre></div>
</div>
<p>It may also be useful to have an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> assign attributes to an
already existing object, rather than a new <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> object.  This can
be achieved by specifying the <code class="docutils literal notranslate"><span class="pre">namespace=</span></code> keyword argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">],</span> <span class="n">namespace</span><span class="o">=</span><span class="n">c</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">foo</span>
<span class="go">&#39;BAR&#39;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="other-utilities">
<h2>15.4.5. Other utilities<a class="headerlink" href="#other-utilities" title="Permalink to this headline">¶</a></h2>
<div class="section" id="sub-commands">
<h3>15.4.5.1. Sub-commands<a class="headerlink" href="#sub-commands" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_subparsers">
<code class="descclassname">ArgumentParser.</code><code class="descname">add_subparsers</code><span class="sig-paren">(</span><span class="optional">[</span><em>title</em><span class="optional">]</span><span class="optional">[</span>, <em>description</em><span class="optional">]</span><span class="optional">[</span>, <em>prog</em><span class="optional">]</span><span class="optional">[</span>, <em>parser_class</em><span class="optional">]</span><span class="optional">[</span>, <em>action</em><span class="optional">]</span><span class="optional">[</span>, <em>option_string</em><span class="optional">]</span><span class="optional">[</span>, <em>dest</em><span class="optional">]</span><span class="optional">[</span>, <em>help</em><span class="optional">]</span><span class="optional">[</span>, <em>metavar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_subparsers" title="Permalink to this definition">¶</a></dt>
<dd><p>Many programs split up their functionality into a number of sub-commands,
for example, the <code class="docutils literal notranslate"><span class="pre">svn</span></code> program can invoke sub-commands like <code class="docutils literal notranslate"><span class="pre">svn</span>
<span class="pre">checkout</span></code>, <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">update</span></code>, and <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">commit</span></code>.  Splitting up functionality
this way can be a particularly good idea when a program performs several
different functions which require different kinds of command-line arguments.
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> supports the creation of such sub-commands with the
<a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> method.  The <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> method is normally
called with no arguments and returns a special action object.  This object
has a single method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_parser()</span></code>, which takes a
command name and any <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> constructor arguments, and
returns an <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> object that can be modified as usual.</p>
<p>Description of parameters:</p>
<ul class="simple">
<li>title - title for the sub-parser group in help output; by default
“subcommands” if description is provided, otherwise uses title for
positional arguments</li>
<li>description - description for the sub-parser group in help output, by
default <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>prog - usage information that will be displayed with sub-command help,
by default the name of the program and any positional arguments before the
subparser argument</li>
<li>parser_class - class which will be used to create sub-parser instances, by
default the class of the current parser (e.g. ArgumentParser)</li>
<li><a class="reference internal" href="#action">action</a> - the basic type of action to be taken when this argument is
encountered at the command line</li>
<li><a class="reference internal" href="#dest">dest</a> - name of the attribute under which sub-command name will be
stored; by default <code class="docutils literal notranslate"><span class="pre">None</span></code> and no value is stored</li>
<li><a class="reference internal" href="#help">help</a> - help for sub-parser group in help output, by default <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li><a class="reference internal" href="#metavar">metavar</a> - string presenting available sub-commands in help; by default it
is <code class="docutils literal notranslate"><span class="pre">None</span></code> and presents sub-commands in form {cmd1, cmd2, ..}</li>
</ul>
<p>Some example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the top-level parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">help</span><span class="o">=</span><span class="s1">&#39;sub-command help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;a&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_a</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;a help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_a</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;b&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_b</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;b help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_b</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="s1">&#39;XYZ&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;baz help&#39;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse some argument lists</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;12&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=12, foo=False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;--baz&#39;</span><span class="p">,</span> <span class="s1">&#39;Z&#39;</span><span class="p">])</span>
<span class="go">Namespace(baz=&#39;Z&#39;, foo=True)</span>
</pre></div>
</div>
<p>Note that the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> will only contain
attributes for the main parser and the subparser that was selected by the
command line (and not any other subparsers).  So in the example above, when
the <code class="docutils literal notranslate"><span class="pre">a</span></code> command is specified, only the <code class="docutils literal notranslate"><span class="pre">foo</span></code> and <code class="docutils literal notranslate"><span class="pre">bar</span></code> attributes are
present, and when the <code class="docutils literal notranslate"><span class="pre">b</span></code> command is specified, only the <code class="docutils literal notranslate"><span class="pre">foo</span></code> and
<code class="docutils literal notranslate"><span class="pre">baz</span></code> attributes are present.</p>
<p>Similarly, when a help message is requested from a subparser, only the help
for that particular parser will be printed.  The help message will not
include parent parser or sibling parser messages.  (A help message for each
subparser command, however, can be given by supplying the <code class="docutils literal notranslate"><span class="pre">help=</span></code> argument
to <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_parser()</span></code> as above.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo] {a,b} ...</span>

<span class="go">positional arguments:</span>
<span class="go">  {a,b}   sub-command help</span>
<span class="go">    a     a help</span>
<span class="go">    b     b help</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
<span class="go">  --foo   foo help</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG a [-h] bar</span>

<span class="go">positional arguments:</span>
<span class="go">  bar     bar help</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;--help&#39;</span><span class="p">])</span>
<span class="go">usage: PROG b [-h] [--baz {X,Y,Z}]</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help     show this help message and exit</span>
<span class="go">  --baz {X,Y,Z}  baz help</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> method also supports <code class="docutils literal notranslate"><span class="pre">title</span></code> and <code class="docutils literal notranslate"><span class="pre">description</span></code>
keyword arguments.  When either is present, the subparser’s commands will
appear in their own group in the help output.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">title</span><span class="o">=</span><span class="s1">&#39;subcommands&#39;</span><span class="p">,</span>
<span class="gp">... </span>                                   <span class="n">description</span><span class="o">=</span><span class="s1">&#39;valid subcommands&#39;</span><span class="p">,</span>
<span class="gp">... </span>                                   <span class="n">help</span><span class="o">=</span><span class="s1">&#39;additional help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-h&#39;</span><span class="p">])</span>
<span class="go">usage:  [-h] {foo,bar} ...</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>

<span class="go">subcommands:</span>
<span class="go">  valid subcommands</span>

<span class="go">  {foo,bar}   additional help</span>
</pre></div>
</div>
<p>One particularly effective way of handling sub-commands is to combine the use
of the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> method with calls to <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> so
that each subparser knows which Python function it should execute.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># sub-command functions</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="n">x</span> <span class="o">*</span> <span class="n">args</span><span class="o">.</span><span class="n">y</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">bar</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;((</span><span class="si">%s</span><span class="s1">))&#39;</span> <span class="o">%</span> <span class="n">args</span><span class="o">.</span><span class="n">z</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the top-level parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">()</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;foo&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_foo</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">func</span><span class="o">=</span><span class="n">foo</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create the parser for the &quot;bar&quot; command</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_bar</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">func</span><span class="o">=</span><span class="n">bar</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse the args and call whatever function was selected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;foo 1 -x 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">2.0</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># parse the args and call whatever function was selected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s1">&#39;bar XYZYX&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="go">((XYZYX))</span>
</pre></div>
</div>
<p>This way, you can let <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> do the job of calling the
appropriate function after argument parsing is complete.  Associating
functions with actions like this is typically the easiest way to handle the
different actions for each of your subparsers.  However, if it is necessary
to check the name of the subparser that was invoked, the <code class="docutils literal notranslate"><span class="pre">dest</span></code> keyword
argument to the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> call will work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="s1">&#39;subparser_name&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser1</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;1&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser1</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-x&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser2</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s1">&#39;2&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparser2</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;2&#39;</span><span class="p">,</span> <span class="s1">&#39;frobble&#39;</span><span class="p">])</span>
<span class="go">Namespace(subparser_name=&#39;2&#39;, y=&#39;frobble&#39;)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="filetype-objects">
<h3>15.4.5.2. FileType objects<a class="headerlink" href="#filetype-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="argparse.FileType">
<em class="property">class </em><code class="descclassname">argparse.</code><code class="descname">FileType</code><span class="sig-paren">(</span><em>mode='r'</em>, <em>bufsize=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.FileType" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> factory creates objects that can be passed to the type
argument of <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a>.  Arguments that have
<a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> objects as their type will open command-line arguments as files
with the requested modes and buffer sizes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--output&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;wb&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--output&#39;</span><span class="p">,</span> <span class="s1">&#39;out&#39;</span><span class="p">])</span>
<span class="go">Namespace(output=&lt;open file &#39;out&#39;, mode &#39;wb&#39; at 0x...&gt;)</span>
</pre></div>
</div>
<p>FileType objects understand the pseudo-argument <code class="docutils literal notranslate"><span class="pre">'-'</span></code> and automatically
convert this into <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> for readable <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> objects and
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> for writable <a class="reference internal" href="#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;infile&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">FileType</span><span class="p">(</span><span class="s1">&#39;r&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;-&#39;</span><span class="p">])</span>
<span class="go">Namespace(infile=&lt;open file &#39;&lt;stdin&gt;&#39;, mode &#39;r&#39; at 0x...&gt;)</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="argument-groups">
<h3>15.4.5.3. Argument groups<a class="headerlink" href="#argument-groups" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_argument_group">
<code class="descclassname">ArgumentParser.</code><code class="descname">add_argument_group</code><span class="sig-paren">(</span><em>title=None</em>, <em>description=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_argument_group" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> groups command-line arguments into
“positional arguments” and “optional arguments” when displaying help
messages. When there is a better conceptual grouping of arguments than this
default one, appropriate groups can be created using the
<a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--foo FOO] bar</span>

<span class="go">group:</span>
<span class="go">  bar    bar help</span>
<span class="go">  --foo FOO  foo help</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> method returns an argument group object which
has an <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> method just like a regular
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>.  When an argument is added to the group, the parser
treats it just like a normal argument, but displays the argument in a
separate group for help messages.  The <a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a> method
accepts <em>title</em> and <em>description</em> arguments which can be used to
customize this display:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">add_help</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group1</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group1&#39;</span><span class="p">,</span> <span class="s1">&#39;group1 description&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group1</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;foo help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group2</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_argument_group</span><span class="p">(</span><span class="s1">&#39;group2&#39;</span><span class="p">,</span> <span class="s1">&#39;group2 description&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group2</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s1">&#39;bar help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [--bar BAR] foo</span>

<span class="go">group1:</span>
<span class="go">  group1 description</span>

<span class="go">  foo    foo help</span>

<span class="go">group2:</span>
<span class="go">  group2 description</span>

<span class="go">  --bar BAR  bar help</span>
</pre></div>
</div>
<p>Note that any arguments not in your user-defined groups will end up back
in the usual “positional arguments” and “optional arguments” sections.</p>
</dd></dl>

</div>
<div class="section" id="mutual-exclusion">
<h3>15.4.5.4. Mutual exclusion<a class="headerlink" href="#mutual-exclusion" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.add_mutually_exclusive_group">
<code class="descclassname">ArgumentParser.</code><code class="descname">add_mutually_exclusive_group</code><span class="sig-paren">(</span><em>required=False</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a mutually exclusive group. <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> will make sure that only
one of the arguments in the mutually exclusive group was present on the
command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=True, foo=True)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=False, foo=False)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;--bar&#39;</span><span class="p">])</span>
<span class="go">usage: PROG [-h] [--foo | --bar]</span>
<span class="go">PROG: error: argument --bar: not allowed with argument --foo</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#argparse.ArgumentParser.add_mutually_exclusive_group" title="argparse.ArgumentParser.add_mutually_exclusive_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_mutually_exclusive_group()</span></code></a> method also accepts a <em>required</em>
argument, to indicate that at least one of the mutually exclusive arguments
is required:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s1">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_mutually_exclusive_group</span><span class="p">(</span><span class="n">required</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">group</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--bar&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_false&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">usage: PROG [-h] (--foo | --bar)</span>
<span class="go">PROG: error: one of the arguments --foo --bar is required</span>
</pre></div>
</div>
<p>Note that currently mutually exclusive argument groups do not support the
<em>title</em> and <em>description</em> arguments of
<a class="reference internal" href="#argparse.ArgumentParser.add_argument_group" title="argparse.ArgumentParser.add_argument_group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument_group()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="parser-defaults">
<h3>15.4.5.5. Parser defaults<a class="headerlink" href="#parser-defaults" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.set_defaults">
<code class="descclassname">ArgumentParser.</code><code class="descname">set_defaults</code><span class="sig-paren">(</span><em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.set_defaults" title="Permalink to this definition">¶</a></dt>
<dd><p>Most of the time, the attributes of the object returned by <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a>
will be fully determined by inspecting the command-line arguments and the argument
actions.  <a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> allows some additional
attributes that are determined without any inspection of the command line to
be added:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="mi">42</span><span class="p">,</span> <span class="n">baz</span><span class="o">=</span><span class="s1">&#39;badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;736&#39;</span><span class="p">])</span>
<span class="go">Namespace(bar=42, baz=&#39;badger&#39;, foo=736)</span>
</pre></div>
</div>
<p>Note that parser-level defaults always override argument-level defaults:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">foo</span><span class="o">=</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([])</span>
<span class="go">Namespace(foo=&#39;spam&#39;)</span>
</pre></div>
</div>
<p>Parser-level defaults can be particularly useful when working with multiple
parsers.  See the <a class="reference internal" href="#argparse.ArgumentParser.add_subparsers" title="argparse.ArgumentParser.add_subparsers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_subparsers()</span></code></a> method for an
example of this type.</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.get_default">
<code class="descclassname">ArgumentParser.</code><code class="descname">get_default</code><span class="sig-paren">(</span><em>dest</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.get_default" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the default value for a namespace attribute, as set by either
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_argument()</span></code></a> or by
<a class="reference internal" href="#argparse.ArgumentParser.set_defaults" title="argparse.ArgumentParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="s1">&#39;badger&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">get_default</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">&#39;badger&#39;</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="printing-help">
<h3>15.4.5.6. Printing help<a class="headerlink" href="#printing-help" title="Permalink to this headline">¶</a></h3>
<p>In most typical applications, <a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> will take
care of formatting and printing any usage or error messages.  However, several
formatting methods are available:</p>
<dl class="method">
<dt id="argparse.ArgumentParser.print_usage">
<code class="descclassname">ArgumentParser.</code><code class="descname">print_usage</code><span class="sig-paren">(</span><em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.print_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a brief description of how the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> should be
invoked on the command line.  If <em>file</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> is
assumed.</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.print_help">
<code class="descclassname">ArgumentParser.</code><code class="descname">print_help</code><span class="sig-paren">(</span><em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.print_help" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a help message, including the program usage and information about the
arguments registered with the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>.  If <em>file</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> is assumed.</p>
</dd></dl>

<p>There are also variants of these methods that simply return a string instead of
printing it:</p>
<dl class="method">
<dt id="argparse.ArgumentParser.format_usage">
<code class="descclassname">ArgumentParser.</code><code class="descname">format_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.format_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing a brief description of how the
<a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> should be invoked on the command line.</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.format_help">
<code class="descclassname">ArgumentParser.</code><code class="descname">format_help</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.format_help" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing a help message, including the program usage and
information about the arguments registered with the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="partial-parsing">
<h3>15.4.5.7. Partial parsing<a class="headerlink" href="#partial-parsing" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.parse_known_args">
<code class="descclassname">ArgumentParser.</code><code class="descname">parse_known_args</code><span class="sig-paren">(</span><em>args=None</em>, <em>namespace=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.parse_known_args" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>Sometimes a script may only parse a few of the command-line arguments, passing
the remaining arguments on to another script or program. In these cases, the
<a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code></a> method can be useful.  It works much like
<a class="reference internal" href="#argparse.ArgumentParser.parse_args" title="argparse.ArgumentParser.parse_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code></a> except that it does not produce an error when
extra arguments are present.  Instead, it returns a two item tuple containing
the populated namespace and the list of remaining argument strings.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_known_args</span><span class="p">([</span><span class="s1">&#39;--foo&#39;</span><span class="p">,</span> <span class="s1">&#39;--badger&#39;</span><span class="p">,</span> <span class="s1">&#39;BAR&#39;</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">])</span>
<span class="go">(Namespace(bar=&#39;BAR&#39;, foo=True), [&#39;--badger&#39;, &#39;spam&#39;])</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><a class="reference internal" href="#prefix-matching"><span class="std std-ref">Prefix matching</span></a> rules apply to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code>. The parser may consume an option even if it’s just
a prefix of one of its known options, instead of leaving it in the remaining
arguments list.</p>
</div>
</div>
<div class="section" id="customizing-file-parsing">
<h3>15.4.5.8. Customizing file parsing<a class="headerlink" href="#customizing-file-parsing" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.convert_arg_line_to_args">
<code class="descclassname">ArgumentParser.</code><code class="descname">convert_arg_line_to_args</code><span class="sig-paren">(</span><em>arg_line</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="Permalink to this definition">¶</a></dt>
<dd><p>Arguments that are read from a file (see the <em>fromfile_prefix_chars</em>
keyword argument to the <a class="reference internal" href="#argparse.ArgumentParser" title="argparse.ArgumentParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ArgumentParser</span></code></a> constructor) are read one
argument per line. <a class="reference internal" href="#argparse.ArgumentParser.convert_arg_line_to_args" title="argparse.ArgumentParser.convert_arg_line_to_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_arg_line_to_args()</span></code></a> can be overridden for
fancier reading.</p>
<p>This method takes a single argument <em>arg_line</em> which is a string read from
the argument file.  It returns a list of arguments parsed from this string.
The method is called once per line read from the argument file, in order.</p>
<p>A useful override of this method is one that treats each space-separated word
as an argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">convert_arg_line_to_args</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg_line</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">arg_line</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="exiting-methods">
<h3>15.4.5.9. Exiting methods<a class="headerlink" href="#exiting-methods" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="argparse.ArgumentParser.exit">
<code class="descclassname">ArgumentParser.</code><code class="descname">exit</code><span class="sig-paren">(</span><em>status=0</em>, <em>message=None</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.exit" title="Permalink to this definition">¶</a></dt>
<dd><p>This method terminates the program, exiting with the specified <em>status</em>
and, if given, it prints a <em>message</em> before that.</p>
</dd></dl>

<dl class="method">
<dt id="argparse.ArgumentParser.error">
<code class="descclassname">ArgumentParser.</code><code class="descname">error</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#argparse.ArgumentParser.error" title="Permalink to this definition">¶</a></dt>
<dd><p>This method prints a usage message including the <em>message</em> to the
standard error and terminates the program with a status code of 2.</p>
</dd></dl>

</div>
</div>
<div class="section" id="upgrading-optparse-code">
<span id="argparse-from-optparse"></span><h2>15.4.6. Upgrading optparse code<a class="headerlink" href="#upgrading-optparse-code" title="Permalink to this headline">¶</a></h2>
<p>Originally, the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module had attempted to maintain compatibility
with <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>.  However, <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> was difficult to extend
transparently, particularly with the changes required to support the new
<code class="docutils literal notranslate"><span class="pre">nargs=</span></code> specifiers and better usage messages.  When most everything in
<a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> had either been copy-pasted over or monkey-patched, it no
longer seemed practical to try to maintain the backwards compatibility.</p>
<p>The <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module improves on the standard library <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
module in a number of ways including:</p>
<ul class="simple">
<li>Handling positional arguments.</li>
<li>Supporting sub-commands.</li>
<li>Allowing alternative option prefixes like <code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code>.</li>
<li>Handling zero-or-more and one-or-more style arguments.</li>
<li>Producing more informative usage messages.</li>
<li>Providing a much simpler interface for custom <code class="docutils literal notranslate"><span class="pre">type</span></code> and <code class="docutils literal notranslate"><span class="pre">action</span></code>.</li>
</ul>
<p>A partial upgrade path from <a class="reference internal" href="optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>:</p>
<ul class="simple">
<li>Replace all <a class="reference internal" href="optparse.html#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optparse.OptionParser.add_option()</span></code></a> calls with
<a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a> calls.</li>
<li>Replace <code class="docutils literal notranslate"><span class="pre">(options,</span> <span class="pre">args)</span> <span class="pre">=</span> <span class="pre">parser.parse_args()</span></code> with <code class="docutils literal notranslate"><span class="pre">args</span> <span class="pre">=</span>
<span class="pre">parser.parse_args()</span></code> and add additional <a class="reference internal" href="#argparse.ArgumentParser.add_argument" title="argparse.ArgumentParser.add_argument"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ArgumentParser.add_argument()</span></code></a>
calls for the positional arguments. Keep in mind that what was previously
called <code class="docutils literal notranslate"><span class="pre">options</span></code>, now in the <a class="reference internal" href="#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> context is called <code class="docutils literal notranslate"><span class="pre">args</span></code>.</li>
<li>Replace <a class="reference internal" href="optparse.html#optparse.OptionParser.disable_interspersed_args" title="optparse.OptionParser.disable_interspersed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optparse.OptionParser.disable_interspersed_args()</span></code></a>
by setting <code class="docutils literal notranslate"><span class="pre">nargs</span></code> of a positional argument to <a class="reference internal" href="#argparse-remainder">argparse.REMAINDER</a>, or
use <a class="reference internal" href="#argparse.ArgumentParser.parse_known_args" title="argparse.ArgumentParser.parse_known_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_known_args()</span></code></a> to collect unparsed argument
strings in a separate list.</li>
<li>Replace callback actions and the <code class="docutils literal notranslate"><span class="pre">callback_*</span></code> keyword arguments with
<code class="docutils literal notranslate"><span class="pre">type</span></code> or <code class="docutils literal notranslate"><span class="pre">action</span></code> arguments.</li>
<li>Replace string names for <code class="docutils literal notranslate"><span class="pre">type</span></code> keyword arguments with the corresponding
type objects (e.g. int, float, complex, etc).</li>
<li>Replace <code class="xref py py-class docutils literal notranslate"><span class="pre">optparse.Values</span></code> with <a class="reference internal" href="#argparse.Namespace" title="argparse.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> and
<code class="xref py py-exc docutils literal notranslate"><span class="pre">optparse.OptionError</span></code> and <code class="xref py py-exc docutils literal notranslate"><span class="pre">optparse.OptionValueError</span></code> with
<code class="xref py py-exc docutils literal notranslate"><span class="pre">ArgumentError</span></code>.</li>
<li>Replace strings with implicit arguments such as <code class="docutils literal notranslate"><span class="pre">%default</span></code> or <code class="docutils literal notranslate"><span class="pre">%prog</span></code> with
the standard Python syntax to use dictionaries to format strings, that is,
<code class="docutils literal notranslate"><span class="pre">%(default)s</span></code> and <code class="docutils literal notranslate"><span class="pre">%(prog)s</span></code>.</li>
<li>Replace the OptionParser constructor <code class="docutils literal notranslate"><span class="pre">version</span></code> argument with a call to
<code class="docutils literal notranslate"><span class="pre">parser.add_argument('--version',</span> <span class="pre">action='version',</span> <span class="pre">version='&lt;the</span> <span class="pre">version&gt;')</span></code>.</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a><ul>
<li><a class="reference internal" href="#example">15.4.1. Example</a><ul>
<li><a class="reference internal" href="#creating-a-parser">15.4.1.1. Creating a parser</a></li>
<li><a class="reference internal" href="#adding-arguments">15.4.1.2. Adding arguments</a></li>
<li><a class="reference internal" href="#parsing-arguments">15.4.1.3. Parsing arguments</a></li>
</ul>
</li>
<li><a class="reference internal" href="#argumentparser-objects">15.4.2. ArgumentParser objects</a><ul>
<li><a class="reference internal" href="#prog">15.4.2.1. prog</a></li>
<li><a class="reference internal" href="#usage">15.4.2.2. usage</a></li>
<li><a class="reference internal" href="#description">15.4.2.3. description</a></li>
<li><a class="reference internal" href="#epilog">15.4.2.4. epilog</a></li>
<li><a class="reference internal" href="#parents">15.4.2.5. parents</a></li>
<li><a class="reference internal" href="#formatter-class">15.4.2.6. formatter_class</a></li>
<li><a class="reference internal" href="#prefix-chars">15.4.2.7. prefix_chars</a></li>
<li><a class="reference internal" href="#fromfile-prefix-chars">15.4.2.8. fromfile_prefix_chars</a></li>
<li><a class="reference internal" href="#argument-default">15.4.2.9. argument_default</a></li>
<li><a class="reference internal" href="#conflict-handler">15.4.2.10. conflict_handler</a></li>
<li><a class="reference internal" href="#add-help">15.4.2.11. add_help</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-add-argument-method">15.4.3. The add_argument() method</a><ul>
<li><a class="reference internal" href="#name-or-flags">15.4.3.1. name or flags</a></li>
<li><a class="reference internal" href="#action">15.4.3.2. action</a></li>
<li><a class="reference internal" href="#nargs">15.4.3.3. nargs</a></li>
<li><a class="reference internal" href="#const">15.4.3.4. const</a></li>
<li><a class="reference internal" href="#default">15.4.3.5. default</a></li>
<li><a class="reference internal" href="#type">15.4.3.6. type</a></li>
<li><a class="reference internal" href="#choices">15.4.3.7. choices</a></li>
<li><a class="reference internal" href="#required">15.4.3.8. required</a></li>
<li><a class="reference internal" href="#help">15.4.3.9. help</a></li>
<li><a class="reference internal" href="#metavar">15.4.3.10. metavar</a></li>
<li><a class="reference internal" href="#dest">15.4.3.11. dest</a></li>
<li><a class="reference internal" href="#action-classes">15.4.3.12. Action classes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-parse-args-method">15.4.4. The parse_args() method</a><ul>
<li><a class="reference internal" href="#option-value-syntax">15.4.4.1. Option value syntax</a></li>
<li><a class="reference internal" href="#invalid-arguments">15.4.4.2. Invalid arguments</a></li>
<li><a class="reference internal" href="#arguments-containing">15.4.4.3. Arguments containing <code class="docutils literal notranslate"><span class="pre">-</span></code></a></li>
<li><a class="reference internal" href="#argument-abbreviations-prefix-matching">15.4.4.4. Argument abbreviations (prefix matching)</a></li>
<li><a class="reference internal" href="#beyond-sys-argv">15.4.4.5. Beyond <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code></a></li>
<li><a class="reference internal" href="#the-namespace-object">15.4.4.6. The Namespace object</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-utilities">15.4.5. Other utilities</a><ul>
<li><a class="reference internal" href="#sub-commands">15.4.5.1. Sub-commands</a></li>
<li><a class="reference internal" href="#filetype-objects">15.4.5.2. FileType objects</a></li>
<li><a class="reference internal" href="#argument-groups">15.4.5.3. Argument groups</a></li>
<li><a class="reference internal" href="#mutual-exclusion">15.4.5.4. Mutual exclusion</a></li>
<li><a class="reference internal" href="#parser-defaults">15.4.5.5. Parser defaults</a></li>
<li><a class="reference internal" href="#printing-help">15.4.5.6. Printing help</a></li>
<li><a class="reference internal" href="#partial-parsing">15.4.5.7. Partial parsing</a></li>
<li><a class="reference internal" href="#customizing-file-parsing">15.4.5.8. Customizing file parsing</a></li>
<li><a class="reference internal" href="#exiting-methods">15.4.5.9. Exiting methods</a></li>
</ul>
</li>
<li><a class="reference internal" href="#upgrading-optparse-code">15.4.6. Upgrading optparse code</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="time.html"
                        title="previous chapter">15.3. <code class="docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="optparse.html"
                        title="next chapter">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/argparse.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="15.5. optparse — Parser for command line options"
             >next</a> |</li>
        <li class="right" >
          <a href="time.html" title="15.3. time — Time access and conversions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�v�o|o|html/library/array.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.6. array — Efficient arrays of numeric values &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.7. sets — Unordered collections of unique elements" href="sets.html" />
    <link rel="prev" title="8.5. bisect — Array bisection algorithm" href="bisect.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/array.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sets.html" title="8.7. sets — Unordered collections of unique elements"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bisect.html" title="8.5. bisect — Array bisection algorithm"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-array">
<span id="array-efficient-arrays-of-numeric-values"></span><h1>8.6. <a class="reference internal" href="#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> — Efficient arrays of numeric values<a class="headerlink" href="#module-array" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module defines an object type which can compactly represent an array of
basic values: characters, integers, floating point numbers.  Arrays are sequence
types and behave very much like lists, except that the type of objects stored in
them is constrained.  The type is specified at object creation time by using a
<em class="dfn">type code</em>, which is a single character.  The following type codes are
defined:</p>
<table border="1" class="docutils">
<colgroup>
<col width="16%" />
<col width="23%" />
<col width="28%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type code</th>
<th class="head">C Type</th>
<th class="head">Python Type</th>
<th class="head">Minimum size in bytes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>char</td>
<td>character</td>
<td>1</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'b'</span></code></td>
<td>signed char</td>
<td>int</td>
<td>1</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'B'</span></code></td>
<td>unsigned char</td>
<td>int</td>
<td>1</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'u'</span></code></td>
<td>Py_UNICODE</td>
<td>Unicode character</td>
<td>2 (see note)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'h'</span></code></td>
<td>signed short</td>
<td>int</td>
<td>2</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'H'</span></code></td>
<td>unsigned short</td>
<td>int</td>
<td>2</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'i'</span></code></td>
<td>signed int</td>
<td>int</td>
<td>2</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'I'</span></code></td>
<td>unsigned int</td>
<td>long</td>
<td>2</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'l'</span></code></td>
<td>signed long</td>
<td>int</td>
<td>4</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'L'</span></code></td>
<td>unsigned long</td>
<td>long</td>
<td>4</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'f'</span></code></td>
<td>float</td>
<td>float</td>
<td>4</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'d'</span></code></td>
<td>double</td>
<td>float</td>
<td>8</td>
</tr>
</tbody>
</table>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="docutils literal notranslate"><span class="pre">'u'</span></code> typecode corresponds to Python’s unicode character.  On narrow
Unicode builds this is 2-bytes, on wide builds this is 4-bytes.</p>
</div>
<p>The actual representation of values is determined by the machine architecture
(strictly speaking, by the C implementation).  The actual size can be accessed
through the <code class="xref py py-attr docutils literal notranslate"><span class="pre">itemsize</span></code> attribute.  The values stored  for <code class="docutils literal notranslate"><span class="pre">'L'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'I'</span></code> items will be represented as Python long integers when retrieved,
because Python’s plain integer type cannot represent the full range of C’s
unsigned (long) integers.</p>
<p>The module defines the following type:</p>
<dl class="class">
<dt id="array.array">
<em class="property">class </em><code class="descclassname">array.</code><code class="descname">array</code><span class="sig-paren">(</span><em>typecode</em><span class="optional">[</span>, <em>initializer</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array" title="Permalink to this definition">¶</a></dt>
<dd><p>A new array whose items are restricted by <em>typecode</em>, and initialized
from the optional <em>initializer</em> value, which must be a list, string, or iterable
over elements of the appropriate type.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, only lists or strings were accepted.</p>
</div>
<p>If given a list or string, the initializer is passed to the new array’s
<a class="reference internal" href="#array.array.fromlist" title="array.array.fromlist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromlist()</span></code></a>, <a class="reference internal" href="#array.array.fromstring" title="array.array.fromstring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromstring()</span></code></a>, or <a class="reference internal" href="#array.array.fromunicode" title="array.array.fromunicode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromunicode()</span></code></a> method (see below)
to add initial items to the array.  Otherwise, the iterable initializer is
passed to the <a class="reference internal" href="#array.array.extend" title="array.array.extend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code></a> method.</p>
</dd></dl>

<dl class="data">
<dt id="array.ArrayType">
<code class="descclassname">array.</code><code class="descname">ArrayType</code><a class="headerlink" href="#array.ArrayType" title="Permalink to this definition">¶</a></dt>
<dd><p>Obsolete alias for <a class="reference internal" href="#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array</span></code></a>.</p>
</dd></dl>

<p>Array objects support the ordinary sequence operations of indexing, slicing,
concatenation, and multiplication.  When using slice assignment, the assigned
value must be an array object with the same type code; in all other cases,
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised. Array objects also implement the buffer interface,
and may be used wherever buffer objects are supported.</p>
<p>The following data items and methods are also supported:</p>
<dl class="attribute">
<dt id="array.array.typecode">
<code class="descclassname">array.</code><code class="descname">typecode</code><a class="headerlink" href="#array.array.typecode" title="Permalink to this definition">¶</a></dt>
<dd><p>The typecode character used to create the array.</p>
</dd></dl>

<dl class="attribute">
<dt id="array.array.itemsize">
<code class="descclassname">array.</code><code class="descname">itemsize</code><a class="headerlink" href="#array.array.itemsize" title="Permalink to this definition">¶</a></dt>
<dd><p>The length in bytes of one array item in the internal representation.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.append">
<code class="descclassname">array.</code><code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Append a new item with value <em>x</em> to the end of the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.buffer_info">
<code class="descclassname">array.</code><code class="descname">buffer_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.buffer_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">length)</span></code> giving the current memory address and the
length in elements of the buffer used to hold array’s contents.  The size of the
memory buffer in bytes can be computed as <code class="docutils literal notranslate"><span class="pre">array.buffer_info()[1]</span> <span class="pre">*</span>
<span class="pre">array.itemsize</span></code>.  This is occasionally useful when working with low-level (and
inherently unsafe) I/O interfaces that require memory addresses, such as certain
<code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> operations.  The returned numbers are valid as long as the array
exists and no length-changing operations are applied to it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When using array objects from code written in C or C++ (the only way to
effectively make use of this information), it makes more sense to use the buffer
interface supported by array objects.  This method is maintained for backward
compatibility and should be avoided in new code.  The buffer interface is
documented in <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">Buffers and Memoryview Objects</span></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="array.array.byteswap">
<code class="descclassname">array.</code><code class="descname">byteswap</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.byteswap" title="Permalink to this definition">¶</a></dt>
<dd><p>“Byteswap” all items of the array.  This is only supported for values which are
1, 2, 4, or 8 bytes in size; for other types of values, <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is
raised.  It is useful when reading data from a file written on a machine with a
different byte order.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.count">
<code class="descclassname">array.</code><code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of occurrences of <em>x</em> in the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.extend">
<code class="descclassname">array.</code><code class="descname">extend</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.extend" title="Permalink to this definition">¶</a></dt>
<dd><p>Append items from <em>iterable</em> to the end of the array.  If <em>iterable</em> is another
array, it must have <em>exactly</em> the same type code; if not, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will
be raised.  If <em>iterable</em> is not an array, it must be iterable and its elements
must be the right type to be appended to the array.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, the argument could only be another array.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="array.array.fromfile">
<code class="descclassname">array.</code><code class="descname">fromfile</code><span class="sig-paren">(</span><em>f</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Read <em>n</em> items (as machine values) from the file object <em>f</em> and append them to
the end of the array.  If less than <em>n</em> items are available, <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is
raised, but the items that were available are still inserted into the array.
<em>f</em> must be a real built-in file object; something else with a <a class="reference internal" href="#array.array.read" title="array.array.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>
method won’t do.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.fromlist">
<code class="descclassname">array.</code><code class="descname">fromlist</code><span class="sig-paren">(</span><em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Append items from the list.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">list:</span>
<span class="pre">a.append(x)</span></code> except that if there is a type error, the array is unchanged.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.fromstring">
<code class="descclassname">array.</code><code class="descname">fromstring</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Appends items from the string, interpreting the string as an array of machine
values (as if it had been read from a file using the <a class="reference internal" href="#array.array.fromfile" title="array.array.fromfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromfile()</span></code></a> method).</p>
</dd></dl>

<dl class="method">
<dt id="array.array.fromunicode">
<code class="descclassname">array.</code><code class="descname">fromunicode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.fromunicode" title="Permalink to this definition">¶</a></dt>
<dd><p>Extends this array with data from the given unicode string.  The array must
be a type <code class="docutils literal notranslate"><span class="pre">'u'</span></code> array; otherwise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  Use
<code class="docutils literal notranslate"><span class="pre">array.fromstring(unicodestring.encode(enc))</span></code> to append Unicode data to an
array of some other type.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.index">
<code class="descclassname">array.</code><code class="descname">index</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the smallest <em>i</em> such that <em>i</em> is the index of the first occurrence of
<em>x</em> in the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.insert">
<code class="descclassname">array.</code><code class="descname">insert</code><span class="sig-paren">(</span><em>i</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.insert" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a new item with value <em>x</em> in the array before position <em>i</em>. Negative
values are treated as being relative to the end of the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.pop">
<code class="descclassname">array.</code><code class="descname">pop</code><span class="sig-paren">(</span><span class="optional">[</span><em>i</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the item with the index <em>i</em> from the array and returns it. The optional
argument defaults to <code class="docutils literal notranslate"><span class="pre">-1</span></code>, so that by default the last item is removed and
returned.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.read">
<code class="descclassname">array.</code><code class="descname">read</code><span class="sig-paren">(</span><em>f</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.read" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 1.5.1: </span>Use the <a class="reference internal" href="#array.array.fromfile" title="array.array.fromfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromfile()</span></code></a> method.</p>
</div>
<p>Read <em>n</em> items (as machine values) from the file object <em>f</em> and append them to
the end of the array.  If less than <em>n</em> items are available, <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is
raised, but the items that were available are still inserted into the array.
<em>f</em> must be a real built-in file object; something else with a <a class="reference internal" href="#array.array.read" title="array.array.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>
method won’t do.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.remove">
<code class="descclassname">array.</code><code class="descname">remove</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the first occurrence of <em>x</em> from the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.reverse">
<code class="descclassname">array.</code><code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the order of the items in the array.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.tofile">
<code class="descclassname">array.</code><code class="descname">tofile</code><span class="sig-paren">(</span><em>f</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tofile" title="Permalink to this definition">¶</a></dt>
<dd><p>Write all items (as machine values) to the file object <em>f</em>.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.tolist">
<code class="descclassname">array.</code><code class="descname">tolist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tolist" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the array to an ordinary list with the same items.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.tostring">
<code class="descclassname">array.</code><code class="descname">tostring</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tostring" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the array to an array of machine values and return the string
representation (the same sequence of bytes that would be written to a file by
the <a class="reference internal" href="#array.array.tofile" title="array.array.tofile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tofile()</span></code></a> method.)</p>
</dd></dl>

<dl class="method">
<dt id="array.array.tounicode">
<code class="descclassname">array.</code><code class="descname">tounicode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#array.array.tounicode" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the array to a unicode string.  The array must be a type <code class="docutils literal notranslate"><span class="pre">'u'</span></code> array;
otherwise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised. Use <code class="docutils literal notranslate"><span class="pre">array.tostring().decode(enc)</span></code> to
obtain a unicode string from an array of some other type.</p>
</dd></dl>

<dl class="method">
<dt id="array.array.write">
<code class="descclassname">array.</code><code class="descname">write</code><span class="sig-paren">(</span><em>f</em><span class="sig-paren">)</span><a class="headerlink" href="#array.array.write" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 1.5.1: </span>Use the <a class="reference internal" href="#array.array.tofile" title="array.array.tofile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tofile()</span></code></a> method.</p>
</div>
<p>Write all items (as machine values) to the file object <em>f</em>.</p>
</dd></dl>

<p>When an array object is printed or converted to a string, it is represented as
<code class="docutils literal notranslate"><span class="pre">array(typecode,</span> <span class="pre">initializer)</span></code>.  The <em>initializer</em> is omitted if the array is
empty, otherwise it is a string if the <em>typecode</em> is <code class="docutils literal notranslate"><span class="pre">'c'</span></code>, otherwise it is a
list of numbers.  The string is guaranteed to be able to be converted back to an
array with the same type and value using <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, so long as the
<a class="reference internal" href="#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array</span></code></a> class has been imported using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">array</span> <span class="pre">import</span> <span class="pre">array</span></code>.
Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;l&#39;</span><span class="p">)</span>
<span class="n">array</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;hello world&#39;</span><span class="p">)</span>
<span class="n">array</span><span class="p">(</span><span class="s1">&#39;u&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;hello </span><span class="se">\u2641</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">array</span><span class="p">(</span><span class="s1">&#39;l&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">])</span>
<span class="n">array</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.14</span><span class="p">])</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a></dt>
<dd>Packing and unpacking of heterogeneous binary data.</dd>
<dt>Module <a class="reference internal" href="xdrlib.html#module-xdrlib" title="xdrlib: Encoders and decoders for the External Data Representation (XDR)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xdrlib</span></code></a></dt>
<dd>Packing and unpacking of External Data Representation (XDR) data as used in some
remote procedure call systems.</dd>
<dt><a class="reference external" href="https://docs.scipy.org/doc/">The Numerical Python Documentation</a></dt>
<dd>The Numeric Python extension (NumPy) defines another array type; see
<a class="reference external" href="http://www.numpy.org/">http://www.numpy.org/</a> for further information about Numerical Python.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="bisect.html"
                        title="previous chapter">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sets.html"
                        title="next chapter">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/array.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sets.html" title="8.7. sets — Unordered collections of unique elements"
             >next</a> |</li>
        <li class="right" >
          <a href="bisect.html" title="8.5. bisect — Array bisection algorithm"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��2���html/library/ast.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.2. ast — Abstract Syntax Trees &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.3. symtable — Access to the compiler’s symbol tables" href="symtable.html" />
    <link rel="prev" title="32.1. parser — Access Python parse trees" href="parser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ast.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="symtable.html" title="32.3. symtable — Access to the compiler’s symbol tables"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="parser.html" title="32.1. parser — Access Python parse trees"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ast">
<span id="ast-abstract-syntax-trees"></span><h1>32.2. <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> — Abstract Syntax Trees<a class="headerlink" href="#module-ast" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>The low-level <code class="docutils literal notranslate"><span class="pre">_ast</span></code> module containing only the node classes.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The high-level <code class="docutils literal notranslate"><span class="pre">ast</span></code> module containing all helpers.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/ast.py">Lib/ast.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module helps Python applications to process trees of the Python
abstract syntax grammar.  The abstract syntax itself might change with each
Python release; this module helps to find out programmatically what the current
grammar looks like.</p>
<p>An abstract syntax tree can be generated by passing <code class="xref py py-data docutils literal notranslate"><span class="pre">ast.PyCF_ONLY_AST</span></code> as
a flag to the <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in function, or using the <a class="reference internal" href="#ast.parse" title="ast.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a>
helper provided in this module.  The result will be a tree of objects whose
classes all inherit from <a class="reference internal" href="#ast.AST" title="ast.AST"><code class="xref py py-class docutils literal notranslate"><span class="pre">ast.AST</span></code></a>.  An abstract syntax tree can be
compiled into a Python code object using the built-in <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> function.</p>
<div class="section" id="node-classes">
<h2>32.2.1. Node classes<a class="headerlink" href="#node-classes" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="ast.AST">
<em class="property">class </em><code class="descclassname">ast.</code><code class="descname">AST</code><a class="headerlink" href="#ast.AST" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base of all AST node classes.  The actual node classes are
derived from the <code class="file docutils literal notranslate"><span class="pre">Parser/Python.asdl</span></code> file, which is reproduced
<a class="reference internal" href="#abstract-grammar"><span class="std std-ref">below</span></a>.  They are defined in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_ast</span></code> C
module and re-exported in <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a>.</p>
<p>There is one class defined for each left-hand side symbol in the abstract
grammar (for example, <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.stmt</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.expr</span></code>).  In addition,
there is one class defined for each constructor on the right-hand side; these
classes inherit from the classes for the left-hand side trees.  For example,
<code class="xref py py-class docutils literal notranslate"><span class="pre">ast.BinOp</span></code> inherits from <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.expr</span></code>.  For production rules
with alternatives (aka “sums”), the left-hand side class is abstract: only
instances of specific constructor nodes are ever created.</p>
<dl class="attribute">
<dt id="ast.AST._fields">
<code class="descname">_fields</code><a class="headerlink" href="#ast.AST._fields" title="Permalink to this definition">¶</a></dt>
<dd><p>Each concrete class has an attribute <a class="reference internal" href="#ast.AST._fields" title="ast.AST._fields"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code></a> which gives the names
of all child nodes.</p>
<p>Each instance of a concrete class has one attribute for each child node,
of the type as defined in the grammar.  For example, <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.BinOp</span></code>
instances have an attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code> of type <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.expr</span></code>.</p>
<p>If these attributes are marked as optional in the grammar (using a
question mark), the value might be <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If the attributes can have
zero-or-more values (marked with an asterisk), the values are represented
as Python lists.  All possible attributes must be present and have valid
values when compiling an AST with <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="ast.AST.lineno">
<code class="descname">lineno</code><a class="headerlink" href="#ast.AST.lineno" title="Permalink to this definition">¶</a></dt>
<dt id="ast.AST.col_offset">
<code class="descname">col_offset</code><a class="headerlink" href="#ast.AST.col_offset" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.expr</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.stmt</span></code> subclasses have
<a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code></a> and <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code class="xref py py-attr docutils literal notranslate"><span class="pre">col_offset</span></code></a> attributes.  The <a class="reference internal" href="#ast.AST.lineno" title="ast.AST.lineno"><code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code></a> is
the line number of source text (1-indexed so the first line is line 1) and
the <a class="reference internal" href="#ast.AST.col_offset" title="ast.AST.col_offset"><code class="xref py py-attr docutils literal notranslate"><span class="pre">col_offset</span></code></a> is the UTF-8 byte offset of the first token that
generated the node.  The UTF-8 offset is recorded because the parser uses
UTF-8 internally.</p>
</dd></dl>

<p>The constructor of a class <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.T</span></code> parses its arguments as follows:</p>
<ul class="simple">
<li>If there are positional arguments, there must be as many as there are items
in <code class="xref py py-attr docutils literal notranslate"><span class="pre">T._fields</span></code>; they will be assigned as attributes of these names.</li>
<li>If there are keyword arguments, they will set the attributes of the same
names to the given values.</li>
</ul>
<p>For example, to create and populate an <code class="xref py py-class docutils literal notranslate"><span class="pre">ast.UnaryOp</span></code> node, you could
use</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">node</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">UnaryOp</span><span class="p">()</span>
<span class="n">node</span><span class="o">.</span><span class="n">op</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">USub</span><span class="p">()</span>
<span class="n">node</span><span class="o">.</span><span class="n">operand</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">Num</span><span class="p">()</span>
<span class="n">node</span><span class="o">.</span><span class="n">operand</span><span class="o">.</span><span class="n">n</span> <span class="o">=</span> <span class="mi">5</span>
<span class="n">node</span><span class="o">.</span><span class="n">operand</span><span class="o">.</span><span class="n">lineno</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">node</span><span class="o">.</span><span class="n">operand</span><span class="o">.</span><span class="n">col_offset</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">node</span><span class="o">.</span><span class="n">lineno</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">node</span><span class="o">.</span><span class="n">col_offset</span> <span class="o">=</span> <span class="mi">0</span>
</pre></div>
</div>
<p>or the more compact</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">node</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">UnaryOp</span><span class="p">(</span><span class="n">ast</span><span class="o">.</span><span class="n">USub</span><span class="p">(),</span> <span class="n">ast</span><span class="o">.</span><span class="n">Num</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">lineno</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">col_offset</span><span class="o">=</span><span class="mi">0</span><span class="p">),</span>
                   <span class="n">lineno</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">col_offset</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The constructor as explained above was added.  In Python 2.5 nodes had
to be created by calling the class constructor without arguments and
setting the attributes afterwards.</p>
</div>
</dd></dl>

</div>
<div class="section" id="abstract-grammar">
<span id="id1"></span><h2>32.2.2. Abstract Grammar<a class="headerlink" href="#abstract-grammar" title="Permalink to this headline">¶</a></h2>
<p>The module defines a string constant <code class="docutils literal notranslate"><span class="pre">__version__</span></code> which is the decimal
Subversion revision number of the file shown below.</p>
<p>The abstract grammar is currently defined as follows:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>-- ASDL&#39;s five builtin types are identifier, int, string, object, bool

module Python version &quot;$Revision$&quot;
{
	mod = Module(stmt* body)
	    | Interactive(stmt* body)
	    | Expression(expr body)

	    -- not really an actual node but useful in Jython&#39;s typesystem.
	    | Suite(stmt* body)

	stmt = FunctionDef(identifier name, arguments args, 
                            stmt* body, expr* decorator_list)
	      | ClassDef(identifier name, expr* bases, stmt* body, expr* decorator_list)
	      | Return(expr? value)

	      | Delete(expr* targets)
	      | Assign(expr* targets, expr value)
	      | AugAssign(expr target, operator op, expr value)

	      -- not sure if bool is allowed, can always use int
 	      | Print(expr? dest, expr* values, bool nl)

	      -- use &#39;orelse&#39; because else is a keyword in target languages
	      | For(expr target, expr iter, stmt* body, stmt* orelse)
	      | While(expr test, stmt* body, stmt* orelse)
	      | If(expr test, stmt* body, stmt* orelse)
	      | With(expr context_expr, expr? optional_vars, stmt* body)

	      -- &#39;type&#39; is a bad name
	      | Raise(expr? type, expr? inst, expr? tback)
	      | TryExcept(stmt* body, excepthandler* handlers, stmt* orelse)
	      | TryFinally(stmt* body, stmt* finalbody)
	      | Assert(expr test, expr? msg)

	      | Import(alias* names)
	      | ImportFrom(identifier? module, alias* names, int? level)

	      -- Doesn&#39;t capture requirement that locals must be
	      -- defined if globals is
	      -- still supports use as a function!
	      | Exec(expr body, expr? globals, expr? locals)

	      | Global(identifier* names)
	      | Expr(expr value)
	      | Pass | Break | Continue

	      -- XXX Jython will be different
	      -- col_offset is the byte offset in the utf8 string the parser uses
	      attributes (int lineno, int col_offset)

	      -- BoolOp() can use left &amp; right?
	expr = BoolOp(boolop op, expr* values)
	     | BinOp(expr left, operator op, expr right)
	     | UnaryOp(unaryop op, expr operand)
	     | Lambda(arguments args, expr body)
	     | IfExp(expr test, expr body, expr orelse)
	     | Dict(expr* keys, expr* values)
	     | Set(expr* elts)
	     | ListComp(expr elt, comprehension* generators)
	     | SetComp(expr elt, comprehension* generators)
	     | DictComp(expr key, expr value, comprehension* generators)
	     | GeneratorExp(expr elt, comprehension* generators)
	     -- the grammar constrains where yield expressions can occur
	     | Yield(expr? value)
	     -- need sequences for compare to distinguish between
	     -- x &lt; 4 &lt; 3 and (x &lt; 4) &lt; 3
	     | Compare(expr left, cmpop* ops, expr* comparators)
	     | Call(expr func, expr* args, keyword* keywords,
			 expr? starargs, expr? kwargs)
	     | Repr(expr value)
	     | Num(object n) -- a number as a PyObject.
	     | Str(string s) -- need to specify raw, unicode, etc?
	     -- other literals? bools?

	     -- the following expression can appear in assignment context
	     | Attribute(expr value, identifier attr, expr_context ctx)
	     | Subscript(expr value, slice slice, expr_context ctx)
	     | Name(identifier id, expr_context ctx)
	     | List(expr* elts, expr_context ctx) 
	     | Tuple(expr* elts, expr_context ctx)

	      -- col_offset is the byte offset in the utf8 string the parser uses
	      attributes (int lineno, int col_offset)

	expr_context = Load | Store | Del | AugLoad | AugStore | Param

	slice = Ellipsis | Slice(expr? lower, expr? upper, expr? step) 
	      | ExtSlice(slice* dims) 
	      | Index(expr value) 

	boolop = And | Or 

	operator = Add | Sub | Mult | Div | Mod | Pow | LShift 
                 | RShift | BitOr | BitXor | BitAnd | FloorDiv

	unaryop = Invert | Not | UAdd | USub

	cmpop = Eq | NotEq | Lt | LtE | Gt | GtE | Is | IsNot | In | NotIn

	comprehension = (expr target, expr iter, expr* ifs)

	-- not sure what to call the first argument for raise and except
	excepthandler = ExceptHandler(expr? type, expr? name, stmt* body)
	                attributes (int lineno, int col_offset)

	arguments = (expr* args, identifier? vararg, 
		     identifier? kwarg, expr* defaults)

        -- keyword arguments supplied to call
        keyword = (identifier arg, expr value)

        -- import name with optional &#39;as&#39; alias.
        alias = (identifier name, identifier? asname)
}
</pre></div>
</div>
</div>
<div class="section" id="ast-helpers">
<h2>32.2.3. <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> Helpers<a class="headerlink" href="#ast-helpers" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>Apart from the node classes, <a class="reference internal" href="#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module defines these utility functions
and classes for traversing abstract syntax trees:</p>
<dl class="function">
<dt id="ast.parse">
<code class="descclassname">ast.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>source</em>, <em>filename='&lt;unknown&gt;'</em>, <em>mode='exec'</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse the source into an AST node.  Equivalent to <code class="docutils literal notranslate"><span class="pre">compile(source,</span>
<span class="pre">filename,</span> <span class="pre">mode,</span> <span class="pre">ast.PyCF_ONLY_AST)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="ast.literal_eval">
<code class="descclassname">ast.</code><code class="descname">literal_eval</code><span class="sig-paren">(</span><em>node_or_string</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.literal_eval" title="Permalink to this definition">¶</a></dt>
<dd><p>Safely evaluate an expression node or a Unicode or <em>Latin-1</em> encoded string
containing a Python literal or container display.  The string or node
provided may only consist of the following Python literal structures:
strings, numbers, tuples, lists, dicts, booleans, and <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>This can be used for safely evaluating strings containing Python values from
untrusted sources without the need to parse the values oneself.  It is not
capable of evaluating arbitrarily complex expressions, for example involving
operators or indexing.</p>
</dd></dl>

<dl class="function">
<dt id="ast.get_docstring">
<code class="descclassname">ast.</code><code class="descname">get_docstring</code><span class="sig-paren">(</span><em>node</em>, <em>clean=True</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.get_docstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the docstring of the given <em>node</em> (which must be a
<code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionDef</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">ClassDef</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">Module</span></code> node), or <code class="docutils literal notranslate"><span class="pre">None</span></code>
if it has no docstring.  If <em>clean</em> is true, clean up the docstring’s
indentation with <a class="reference internal" href="inspect.html#inspect.cleandoc" title="inspect.cleandoc"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.cleandoc()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="ast.fix_missing_locations">
<code class="descclassname">ast.</code><code class="descname">fix_missing_locations</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.fix_missing_locations" title="Permalink to this definition">¶</a></dt>
<dd><p>When you compile a node tree with <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>, the compiler expects
<code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">col_offset</span></code> attributes for every node that supports
them.  This is rather tedious to fill in for generated nodes, so this helper
adds these attributes recursively where not already set, by setting them to
the values of the parent node.  It works recursively starting at <em>node</em>.</p>
</dd></dl>

<dl class="function">
<dt id="ast.increment_lineno">
<code class="descclassname">ast.</code><code class="descname">increment_lineno</code><span class="sig-paren">(</span><em>node</em>, <em>n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.increment_lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Increment the line number of each node in the tree starting at <em>node</em> by <em>n</em>.
This is useful to “move code” to a different location in a file.</p>
</dd></dl>

<dl class="function">
<dt id="ast.copy_location">
<code class="descclassname">ast.</code><code class="descname">copy_location</code><span class="sig-paren">(</span><em>new_node</em>, <em>old_node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.copy_location" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy source location (<code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">col_offset</span></code>) from <em>old_node</em>
to <em>new_node</em> if possible, and return <em>new_node</em>.</p>
</dd></dl>

<dl class="function">
<dt id="ast.iter_fields">
<code class="descclassname">ast.</code><code class="descname">iter_fields</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.iter_fields" title="Permalink to this definition">¶</a></dt>
<dd><p>Yield a tuple of <code class="docutils literal notranslate"><span class="pre">(fieldname,</span> <span class="pre">value)</span></code> for each field in <code class="docutils literal notranslate"><span class="pre">node._fields</span></code>
that is present on <em>node</em>.</p>
</dd></dl>

<dl class="function">
<dt id="ast.iter_child_nodes">
<code class="descclassname">ast.</code><code class="descname">iter_child_nodes</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.iter_child_nodes" title="Permalink to this definition">¶</a></dt>
<dd><p>Yield all direct child nodes of <em>node</em>, that is, all fields that are nodes
and all items of fields that are lists of nodes.</p>
</dd></dl>

<dl class="function">
<dt id="ast.walk">
<code class="descclassname">ast.</code><code class="descname">walk</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.walk" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively yield all descendant nodes in the tree starting at <em>node</em>
(including <em>node</em> itself), in no specified order.  This is useful if you only
want to modify nodes in place and don’t care about the context.</p>
</dd></dl>

<dl class="class">
<dt id="ast.NodeVisitor">
<em class="property">class </em><code class="descclassname">ast.</code><code class="descname">NodeVisitor</code><a class="headerlink" href="#ast.NodeVisitor" title="Permalink to this definition">¶</a></dt>
<dd><p>A node visitor base class that walks the abstract syntax tree and calls a
visitor function for every node found.  This function may return a value
which is forwarded by the <a class="reference internal" href="#ast.NodeVisitor.visit" title="ast.NodeVisitor.visit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">visit()</span></code></a> method.</p>
<p>This class is meant to be subclassed, with the subclass adding visitor
methods.</p>
<dl class="method">
<dt id="ast.NodeVisitor.visit">
<code class="descname">visit</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.NodeVisitor.visit" title="Permalink to this definition">¶</a></dt>
<dd><p>Visit a node.  The default implementation calls the method called
<code class="samp docutils literal notranslate"><span class="pre">self.visit_</span><em><span class="pre">classname</span></em></code> where <em>classname</em> is the name of the node
class, or <a class="reference internal" href="#ast.NodeVisitor.generic_visit" title="ast.NodeVisitor.generic_visit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">generic_visit()</span></code></a> if that method doesn’t exist.</p>
</dd></dl>

<dl class="method">
<dt id="ast.NodeVisitor.generic_visit">
<code class="descname">generic_visit</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.NodeVisitor.generic_visit" title="Permalink to this definition">¶</a></dt>
<dd><p>This visitor calls <a class="reference internal" href="#ast.NodeVisitor.visit" title="ast.NodeVisitor.visit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">visit()</span></code></a> on all children of the node.</p>
<p>Note that child nodes of nodes that have a custom visitor method won’t be
visited unless the visitor calls <a class="reference internal" href="#ast.NodeVisitor.generic_visit" title="ast.NodeVisitor.generic_visit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">generic_visit()</span></code></a> or visits them
itself.</p>
</dd></dl>

<p>Don’t use the <a class="reference internal" href="#ast.NodeVisitor" title="ast.NodeVisitor"><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeVisitor</span></code></a> if you want to apply changes to nodes
during traversal.  For this a special visitor exists
(<a class="reference internal" href="#ast.NodeTransformer" title="ast.NodeTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeTransformer</span></code></a>) that allows modifications.</p>
</dd></dl>

<dl class="class">
<dt id="ast.NodeTransformer">
<em class="property">class </em><code class="descclassname">ast.</code><code class="descname">NodeTransformer</code><a class="headerlink" href="#ast.NodeTransformer" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#ast.NodeVisitor" title="ast.NodeVisitor"><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeVisitor</span></code></a> subclass that walks the abstract syntax tree and
allows modification of nodes.</p>
<p>The <a class="reference internal" href="#ast.NodeTransformer" title="ast.NodeTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeTransformer</span></code></a> will walk the AST and use the return value of
the visitor methods to replace or remove the old node.  If the return value
of the visitor method is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the node will be removed from its
location, otherwise it is replaced with the return value.  The return value
may be the original node in which case no replacement takes place.</p>
<p>Here is an example transformer that rewrites all occurrences of name lookups
(<code class="docutils literal notranslate"><span class="pre">foo</span></code>) to <code class="docutils literal notranslate"><span class="pre">data['foo']</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">RewriteName</span><span class="p">(</span><span class="n">NodeTransformer</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">visit_Name</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">node</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">copy_location</span><span class="p">(</span><span class="n">Subscript</span><span class="p">(</span>
            <span class="n">value</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;data&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span>
            <span class="nb">slice</span><span class="o">=</span><span class="n">Index</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="n">node</span><span class="o">.</span><span class="n">id</span><span class="p">)),</span>
            <span class="n">ctx</span><span class="o">=</span><span class="n">node</span><span class="o">.</span><span class="n">ctx</span>
        <span class="p">),</span> <span class="n">node</span><span class="p">)</span>
</pre></div>
</div>
<p>Keep in mind that if the node you’re operating on has child nodes you must
either transform the child nodes yourself or call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">generic_visit()</span></code>
method for the node first.</p>
<p>For nodes that were part of a collection of statements (that applies to all
statement nodes), the visitor may also return a list of nodes rather than
just a single node.</p>
<p>Usually you use the transformer like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">node</span> <span class="o">=</span> <span class="n">YourTransformer</span><span class="p">()</span><span class="o">.</span><span class="n">visit</span><span class="p">(</span><span class="n">node</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="ast.dump">
<code class="descclassname">ast.</code><code class="descname">dump</code><span class="sig-paren">(</span><em>node</em>, <em>annotate_fields=True</em>, <em>include_attributes=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ast.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a formatted dump of the tree in <em>node</em>.  This is mainly useful for
debugging purposes.  The returned string will show the names and the values
for fields.  This makes the code impossible to evaluate, so if evaluation is
wanted <em>annotate_fields</em> must be set to <code class="docutils literal notranslate"><span class="pre">False</span></code>.  Attributes such as line
numbers and column offsets are not dumped by default.  If this is wanted,
<em>include_attributes</em> can be set to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a><ul>
<li><a class="reference internal" href="#node-classes">32.2.1. Node classes</a></li>
<li><a class="reference internal" href="#abstract-grammar">32.2.2. Abstract Grammar</a></li>
<li><a class="reference internal" href="#ast-helpers">32.2.3. <code class="docutils literal notranslate"><span class="pre">ast</span></code> Helpers</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="parser.html"
                        title="previous chapter">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="symtable.html"
                        title="next chapter">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ast.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="symtable.html" title="32.3. symtable — Access to the compiler’s symbol tables"
             >next</a> |</li>
        <li class="right" >
          <a href="parser.html" title="32.1. parser — Access Python parse trees"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�1�؊���html/library/asynchat.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.7. asynchat — Asynchronous socket command/response handler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18. Internet Data Handling" href="netdata.html" />
    <link rel="prev" title="17.6. asyncore — Asynchronous socket handler" href="asyncore.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/asynchat.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="netdata.html" title="18. Internet Data Handling"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="17.6. asyncore — Asynchronous socket handler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-asynchat">
<span id="asynchat-asynchronous-socket-command-response-handler"></span><h1>17.7. <a class="reference internal" href="#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a> — Asynchronous socket command/response handler<a class="headerlink" href="#module-asynchat" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/asynchat.py">Lib/asynchat.py</a></p>
<hr class="docutils" />
<p>This module builds on the <a class="reference internal" href="asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> infrastructure, simplifying
asynchronous clients and servers and making it easier to handle protocols
whose elements are terminated by arbitrary strings, or are of variable length.
<a class="reference internal" href="#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a> defines the abstract class <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> that you
subclass, providing implementations of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">collect_incoming_data()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code> methods. It uses the same asynchronous loop as
<a class="reference internal" href="asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a>, and the two types of channel, <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>
and <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">asynchat.async_chat</span></code></a>, can freely be mixed in the channel map.
Typically an <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a> server channel generates new
<a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">asynchat.async_chat</span></code></a> channel objects as it receives incoming
connection requests.</p>
<dl class="class">
<dt id="asynchat.async_chat">
<em class="property">class </em><code class="descclassname">asynchat.</code><code class="descname">async_chat</code><a class="headerlink" href="#asynchat.async_chat" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is an abstract subclass of <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>. To make
practical use of the code you must subclass <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a>, providing
meaningful <a class="reference internal" href="#asynchat.async_chat.collect_incoming_data" title="asynchat.async_chat.collect_incoming_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">collect_incoming_data()</span></code></a> and <a class="reference internal" href="#asynchat.async_chat.found_terminator" title="asynchat.async_chat.found_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code></a>
methods.
The <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a> methods can be used, although not all make
sense in a message/response context.</p>
<p>Like <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>, <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> defines a set of
events that are generated by an analysis of socket conditions after a
<code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> call. Once the polling loop has been started the
<a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> object’s methods are called by the event-processing
framework with no action on the part of the programmer.</p>
<p>Two class attributes can be modified, to improve performance, or possibly
even to conserve memory.</p>
<dl class="data">
<dt id="asynchat.async_chat.ac_in_buffer_size">
<code class="descname">ac_in_buffer_size</code><a class="headerlink" href="#asynchat.async_chat.ac_in_buffer_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The asynchronous input buffer size (default <code class="docutils literal notranslate"><span class="pre">4096</span></code>).</p>
</dd></dl>

<dl class="data">
<dt id="asynchat.async_chat.ac_out_buffer_size">
<code class="descname">ac_out_buffer_size</code><a class="headerlink" href="#asynchat.async_chat.ac_out_buffer_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The asynchronous output buffer size (default <code class="docutils literal notranslate"><span class="pre">4096</span></code>).</p>
</dd></dl>

<p>Unlike <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>, <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> allows you to
define a first-in-first-out queue (fifo) of <em>producers</em>. A producer need
have only one method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">more()</span></code>, which should return data to be
transmitted on the channel.
The producer indicates exhaustion (<em>i.e.</em> that it contains no more data) by
having its <code class="xref py py-meth docutils literal notranslate"><span class="pre">more()</span></code> method return the empty string. At this point the
<a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> object removes the producer from the fifo and starts
using the next producer, if any. When the producer fifo is empty the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_write()</span></code> method does nothing. You use the channel object’s
<a class="reference internal" href="#asynchat.async_chat.set_terminator" title="asynchat.async_chat.set_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_terminator()</span></code></a> method to describe how to recognize the end of, or
an important breakpoint in, an incoming transmission from the remote
endpoint.</p>
<p>To build a functioning <a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a> subclass your  input methods
<a class="reference internal" href="#asynchat.async_chat.collect_incoming_data" title="asynchat.async_chat.collect_incoming_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">collect_incoming_data()</span></code></a> and <a class="reference internal" href="#asynchat.async_chat.found_terminator" title="asynchat.async_chat.found_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code></a> must handle the
data that the channel receives asynchronously. The methods are described
below.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.close_when_done">
<code class="descclassname">async_chat.</code><code class="descname">close_when_done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.close_when_done" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a <code class="docutils literal notranslate"><span class="pre">None</span></code> on to the producer fifo. When this producer is popped off
the fifo it causes the channel to be closed.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.collect_incoming_data">
<code class="descclassname">async_chat.</code><code class="descname">collect_incoming_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.collect_incoming_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Called with <em>data</em> holding an arbitrary amount of received data.  The
default method, which must be overridden, raises a
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> exception.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.discard_buffers">
<code class="descclassname">async_chat.</code><code class="descname">discard_buffers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.discard_buffers" title="Permalink to this definition">¶</a></dt>
<dd><p>In emergencies this method will discard any data held in the input and/or
output buffers and the producer fifo.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.found_terminator">
<code class="descclassname">async_chat.</code><code class="descname">found_terminator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.found_terminator" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the incoming data stream  matches the termination condition set
by <a class="reference internal" href="#asynchat.async_chat.set_terminator" title="asynchat.async_chat.set_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_terminator()</span></code></a>. The default method, which must be overridden,
raises a <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> exception. The buffered input data
should be available via an instance attribute.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.get_terminator">
<code class="descclassname">async_chat.</code><code class="descname">get_terminator</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.get_terminator" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current terminator for the channel.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.push">
<code class="descclassname">async_chat.</code><code class="descname">push</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.push" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes data on to the channel’s fifo to ensure its transmission.
This is all you need to do to have the channel write the data out to the
network, although it is possible to use your own producers in more complex
schemes to implement encryption and chunking, for example.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.push_with_producer">
<code class="descclassname">async_chat.</code><code class="descname">push_with_producer</code><span class="sig-paren">(</span><em>producer</em><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.push_with_producer" title="Permalink to this definition">¶</a></dt>
<dd><p>Takes a producer object and adds it to the producer fifo associated with
the channel.  When all currently-pushed producers have been exhausted the
channel will consume this producer’s data by calling its <code class="xref py py-meth docutils literal notranslate"><span class="pre">more()</span></code>
method and send the data to the remote endpoint.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.async_chat.set_terminator">
<code class="descclassname">async_chat.</code><code class="descname">set_terminator</code><span class="sig-paren">(</span><em>term</em><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.async_chat.set_terminator" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the terminating condition to be recognized on the channel.  <code class="docutils literal notranslate"><span class="pre">term</span></code>
may be any of three types of value, corresponding to three different ways
to handle incoming protocol data.</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="80%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">term</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>string</em></td>
<td>Will call <a class="reference internal" href="#asynchat.async_chat.found_terminator" title="asynchat.async_chat.found_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code></a> when the
string is found in the input stream</td>
</tr>
<tr class="row-odd"><td><em>integer</em></td>
<td>Will call <a class="reference internal" href="#asynchat.async_chat.found_terminator" title="asynchat.async_chat.found_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code></a> when the
indicated number of characters have been
received</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>The channel continues to collect data
forever</td>
</tr>
</tbody>
</table>
<p>Note that any data following the terminator will be available for reading
by the channel after <a class="reference internal" href="#asynchat.async_chat.found_terminator" title="asynchat.async_chat.found_terminator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">found_terminator()</span></code></a> is called.</p>
</dd></dl>

<div class="section" id="asynchat-auxiliary-classes">
<h2>17.7.1. asynchat - Auxiliary Classes<a class="headerlink" href="#asynchat-auxiliary-classes" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="asynchat.fifo">
<em class="property">class </em><code class="descclassname">asynchat.</code><code class="descname">fifo</code><span class="sig-paren">(</span><span class="optional">[</span><em>list=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.fifo" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#asynchat.fifo" title="asynchat.fifo"><code class="xref py py-class docutils literal notranslate"><span class="pre">fifo</span></code></a> holding data which has been pushed by the application but
not yet popped for writing to the channel.  A <a class="reference internal" href="#asynchat.fifo" title="asynchat.fifo"><code class="xref py py-class docutils literal notranslate"><span class="pre">fifo</span></code></a> is a list used
to hold data and/or producers until they are required.  If the <em>list</em>
argument is provided then it should contain producers or data items to be
written to the channel.</p>
<dl class="method">
<dt id="asynchat.fifo.is_empty">
<code class="descname">is_empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.fifo.is_empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if the fifo is empty.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.fifo.first">
<code class="descname">first</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.fifo.first" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the least-recently <a class="reference internal" href="#asynchat.fifo.push" title="asynchat.fifo.push"><code class="xref py py-meth docutils literal notranslate"><span class="pre">push()</span></code></a>ed item from the fifo.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.fifo.push">
<code class="descname">push</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.fifo.push" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the given data (which may be a string or a producer object) to the
producer fifo.</p>
</dd></dl>

<dl class="method">
<dt id="asynchat.fifo.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asynchat.fifo.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>If the fifo is not empty, returns <code class="docutils literal notranslate"><span class="pre">True,</span> <span class="pre">first()</span></code>, deleting the popped
item.  Returns <code class="docutils literal notranslate"><span class="pre">False,</span> <span class="pre">None</span></code> for an empty fifo.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="asynchat-example">
<span id="id1"></span><h2>17.7.2. asynchat Example<a class="headerlink" href="#asynchat-example" title="Permalink to this headline">¶</a></h2>
<p>The following partial example shows how HTTP requests can be read with
<a class="reference internal" href="#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">async_chat</span></code></a>.  A web server might create an
<code class="xref py py-class docutils literal notranslate"><span class="pre">http_request_handler</span></code> object for each incoming client connection.
Notice that initially the channel terminator is set to match the blank line at
the end of the HTTP headers, and a flag indicates that the headers are being
read.</p>
<p>Once the headers have been read, if the request is of type POST (indicating
that further data are present in the input stream) then the
<code class="docutils literal notranslate"><span class="pre">Content-Length:</span></code> header is used to set a numeric terminator to read the
right amount of data from the channel.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code> method is called once all relevant input has been
marshalled, after setting the channel terminator to <code class="docutils literal notranslate"><span class="pre">None</span></code> to ensure that
any extraneous data sent by the web client are ignored.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">http_request_handler</span><span class="p">(</span><span class="n">asynchat</span><span class="o">.</span><span class="n">async_chat</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sock</span><span class="p">,</span> <span class="n">addr</span><span class="p">,</span> <span class="n">sessions</span><span class="p">,</span> <span class="n">log</span><span class="p">):</span>
        <span class="n">asynchat</span><span class="o">.</span><span class="n">async_chat</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sock</span><span class="o">=</span><span class="n">sock</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">addr</span> <span class="o">=</span> <span class="n">addr</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">sessions</span> <span class="o">=</span> <span class="n">sessions</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">obuffer</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">set_terminator</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\r\n\r\n</span><span class="s2">&quot;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">reading_headers</span> <span class="o">=</span> <span class="kc">True</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">handling</span> <span class="o">=</span> <span class="kc">False</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">cgi_data</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">log</span> <span class="o">=</span> <span class="n">log</span>

    <span class="k">def</span> <span class="nf">collect_incoming_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Buffer the data&quot;&quot;&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">found_terminator</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">reading_headers</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">reading_headers</span> <span class="o">=</span> <span class="kc">False</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">parse_headers</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span><span class="p">))</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">op</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">==</span> <span class="s2">&quot;POST&quot;</span><span class="p">:</span>
                <span class="n">clen</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">headers</span><span class="o">.</span><span class="n">getheader</span><span class="p">(</span><span class="s2">&quot;content-length&quot;</span><span class="p">)</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">set_terminator</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">clen</span><span class="p">))</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">handling</span> <span class="o">=</span> <span class="kc">True</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">set_terminator</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>
                <span class="bp">self</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
        <span class="k">elif</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="n">handling</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">set_terminator</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>  <span class="c1"># browsers sometimes over-send</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">cgi_data</span> <span class="o">=</span> <span class="n">parse</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">headers</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span><span class="p">))</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">handling</span> <span class="o">=</span> <span class="kc">True</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">ibuffer</span> <span class="o">=</span> <span class="p">[]</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a><ul>
<li><a class="reference internal" href="#asynchat-auxiliary-classes">17.7.1. asynchat - Auxiliary Classes</a></li>
<li><a class="reference internal" href="#asynchat-example">17.7.2. asynchat Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="asyncore.html"
                        title="previous chapter">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="netdata.html"
                        title="next chapter">18. Internet Data Handling</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/asynchat.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="netdata.html" title="18. Internet Data Handling"
             >next</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="17.6. asyncore — Asynchronous socket handler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��>�����html/library/asyncore.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.6. asyncore — Asynchronous socket handler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.7. asynchat — Asynchronous socket command/response handler" href="asynchat.html" />
    <link rel="prev" title="17.5. popen2 — Subprocesses with accessible I/O streams" href="popen2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/asyncore.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asynchat.html" title="17.7. asynchat — Asynchronous socket command/response handler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="popen2.html" title="17.5. popen2 — Subprocesses with accessible I/O streams"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-asyncore">
<span id="asyncore-asynchronous-socket-handler"></span><h1>17.6. <a class="reference internal" href="#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> — Asynchronous socket handler<a class="headerlink" href="#module-asyncore" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/asyncore.py">Lib/asyncore.py</a></p>
<hr class="docutils" />
<p>This module provides the basic infrastructure for writing asynchronous  socket
service clients and servers.</p>
<p>There are only two ways to have a program on a single processor do  “more than
one thing at a time.” Multi-threaded programming is the  simplest and most
popular way to do it, but there is another very different technique, that lets
you have nearly all the advantages of  multi-threading, without actually using
multiple threads.  It’s really  only practical if your program is largely I/O
bound.  If your program is processor bound, then pre-emptive scheduled threads
are probably what you really need.  Network servers are rarely processor
bound, however.</p>
<p>If your operating system supports the <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> system call in its I/O
library (and nearly all do), then you can use it to juggle multiple
communication channels at once; doing other work while your I/O is taking
place in the “background.”  Although this strategy can seem strange and
complex, especially at first, it is in many ways easier to understand and
control than multi-threaded programming.  The <a class="reference internal" href="#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> module solves
many of the difficult problems for you, making the task of building
sophisticated high-performance network servers and clients a snap.  For
“conversational” applications and protocols the companion <a class="reference internal" href="asynchat.html#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a>
module is invaluable.</p>
<p>The basic idea behind both modules is to create one or more network
<em>channels</em>, instances of class <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a> and
<a class="reference internal" href="asynchat.html#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">asynchat.async_chat</span></code></a>.  Creating the channels adds them to a global
map, used by the <a class="reference internal" href="#asyncore.loop" title="asyncore.loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">loop()</span></code></a> function if you do not provide it with your own
<em>map</em>.</p>
<p>Once the initial channel(s) is(are) created, calling the <a class="reference internal" href="#asyncore.loop" title="asyncore.loop"><code class="xref py py-func docutils literal notranslate"><span class="pre">loop()</span></code></a> function
activates channel service, which continues until the last channel (including
any that have been added to the map during asynchronous service) is closed.</p>
<dl class="function">
<dt id="asyncore.loop">
<code class="descclassname">asyncore.</code><code class="descname">loop</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">[</span>, <em>use_poll</em><span class="optional">[</span>, <em>map</em><span class="optional">[</span>, <em>count</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.loop" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter a polling loop that terminates after count passes or all open
channels have been closed.  All arguments are optional.  The <em>count</em>
parameter defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, resulting in the loop terminating only when all
channels have been closed.  The <em>timeout</em> argument sets the timeout
parameter for the appropriate <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> or <a class="reference internal" href="select.html#select.poll" title="select.poll"><code class="xref py py-func docutils literal notranslate"><span class="pre">poll()</span></code></a>
call, measured in seconds; the default is 30 seconds.  The <em>use_poll</em>
parameter, if true, indicates that <a class="reference internal" href="select.html#select.poll" title="select.poll"><code class="xref py py-func docutils literal notranslate"><span class="pre">poll()</span></code></a> should be used in
preference to <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> (the default is <code class="docutils literal notranslate"><span class="pre">False</span></code>).</p>
<p>The <em>map</em> parameter is a dictionary whose items are the channels to watch.
As channels are closed they are deleted from their map.  If <em>map</em> is
omitted, a global map is used. Channels (instances of
<a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>, <a class="reference internal" href="asynchat.html#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">asynchat.async_chat</span></code></a> and subclasses
thereof) can freely be mixed in the map.</p>
</dd></dl>

<dl class="class">
<dt id="asyncore.dispatcher">
<em class="property">class </em><code class="descclassname">asyncore.</code><code class="descname">dispatcher</code><a class="headerlink" href="#asyncore.dispatcher" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">dispatcher</span></code></a> class is a thin wrapper around a low-level socket
object. To make it more useful, it has a few methods for event-handling
which are called from the asynchronous loop.   Otherwise, it can be treated
as a normal non-blocking socket object.</p>
<p>The firing of low-level events at certain times or in certain connection
states tells the asynchronous loop that certain higher-level events have
taken place.  For example, if we have asked for a socket to connect to
another host, we know that the connection has been made when the socket
becomes writable for the first time (at this point you know that you may
write to it with the expectation of success).  The implied higher-level
events are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Event</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">handle_connect()</span></code></td>
<td>Implied by the first read or write
event</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">handle_close()</span></code></td>
<td>Implied by a read event with no data
available</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">handle_accept()</span></code></td>
<td>Implied by a read event on a listening
socket</td>
</tr>
</tbody>
</table>
<p>During asynchronous processing, each mapped channel’s <a class="reference internal" href="#asyncore.dispatcher.readable" title="asyncore.dispatcher.readable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readable()</span></code></a> and
<a class="reference internal" href="#asyncore.dispatcher.writable" title="asyncore.dispatcher.writable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writable()</span></code></a> methods are used to determine whether the channel’s socket
should be added to the list of channels <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code>ed or
<code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code>ed for read and write events.</p>
<p>Thus, the set of channel events is larger than the basic socket events.  The
full set of methods that can be overridden in your subclass follows:</p>
<dl class="method">
<dt id="asyncore.dispatcher.handle_read">
<code class="descname">handle_read</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_read" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the asynchronous loop detects that a <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> call on the
channel’s socket will succeed.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_write">
<code class="descname">handle_write</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_write" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the asynchronous loop detects that a writable socket can be
written.  Often this method will implement the necessary buffering for
performance.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">handle_write</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">sent</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">buffer</span><span class="p">)</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">buffer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">buffer</span><span class="p">[</span><span class="n">sent</span><span class="p">:]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_expt">
<code class="descname">handle_expt</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_expt" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when there is out of band (OOB) data for a socket connection.  This
will almost never happen, as OOB is tenuously supported and rarely used.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_connect">
<code class="descname">handle_connect</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the active opener’s socket actually makes a connection.  Might
send a “welcome” banner, or initiate a protocol negotiation with the
remote endpoint, for example.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_close">
<code class="descname">handle_close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_close" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the socket is closed.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_error">
<code class="descname">handle_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an exception is raised and not otherwise handled.  The default
version prints a condensed traceback.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.handle_accept">
<code class="descname">handle_accept</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.handle_accept" title="Permalink to this definition">¶</a></dt>
<dd><p>Called on listening channels (passive openers) when a connection can be
established with a new remote endpoint that has issued a <a class="reference internal" href="#asyncore.dispatcher.connect" title="asyncore.dispatcher.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a>
call for the local endpoint.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.readable">
<code class="descname">readable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.readable" title="Permalink to this definition">¶</a></dt>
<dd><p>Called each time around the asynchronous loop to determine whether a
channel’s socket should be added to the list on which read events can
occur.  The default method simply returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, indicating that by
default, all channels will be interested in read events.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.writable">
<code class="descname">writable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.writable" title="Permalink to this definition">¶</a></dt>
<dd><p>Called each time around the asynchronous loop to determine whether a
channel’s socket should be added to the list on which write events can
occur.  The default method simply returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, indicating that by
default, all channels will be interested in write events.</p>
</dd></dl>

<p>In addition, each channel delegates or extends many of the socket methods.
Most of these are nearly identical to their socket partners.</p>
<dl class="method">
<dt id="asyncore.dispatcher.create_socket">
<code class="descname">create_socket</code><span class="sig-paren">(</span><em>family</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.create_socket" title="Permalink to this definition">¶</a></dt>
<dd><p>This is identical to the creation of a normal socket, and will use the
same options for creation.  Refer to the <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> documentation for
information on creating sockets.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.connect">
<code class="descname">connect</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>As with the normal socket object, <em>address</em> is a tuple with the first
element the host to connect to, and the second the port number.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.send">
<code class="descname">send</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send <em>data</em> to the remote end-point of the socket.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.recv">
<code class="descname">recv</code><span class="sig-paren">(</span><em>buffer_size</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.recv" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at most <em>buffer_size</em> bytes from the socket’s remote end-point.  An
empty string implies that the channel has been closed from the other end.</p>
<p>Note that <a class="reference internal" href="#asyncore.dispatcher.recv" title="asyncore.dispatcher.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> may raise <a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> with
<a class="reference internal" href="errno.html#errno.EAGAIN" title="errno.EAGAIN"><code class="xref py py-data docutils literal notranslate"><span class="pre">EAGAIN</span></code></a> or <a class="reference internal" href="errno.html#errno.EWOULDBLOCK" title="errno.EWOULDBLOCK"><code class="xref py py-data docutils literal notranslate"><span class="pre">EWOULDBLOCK</span></code></a>, even though
<a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select.select()</span></code></a> or <a class="reference internal" href="select.html#select.poll" title="select.poll"><code class="xref py py-func docutils literal notranslate"><span class="pre">select.poll()</span></code></a> has reported the socket
ready for reading.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.listen">
<code class="descname">listen</code><span class="sig-paren">(</span><em>backlog</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.listen" title="Permalink to this definition">¶</a></dt>
<dd><p>Listen for connections made to the socket.  The <em>backlog</em> argument
specifies the maximum number of queued connections and should be at least
1; the maximum value is system-dependent (usually 5).</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.bind">
<code class="descname">bind</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind the socket to <em>address</em>.  The socket must not already be bound.  (The
format of <em>address</em> depends on the address family — refer to the
<a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> documentation for more information.)  To mark
the socket as re-usable (setting the <code class="xref py py-const docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code> option), call
the <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">dispatcher</span></code></a> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_reuse_addr()</span></code> method.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.accept">
<code class="descname">accept</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.accept" title="Permalink to this definition">¶</a></dt>
<dd><p>Accept a connection.  The socket must be bound to an address and listening
for connections.  The return value can be either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a pair
<code class="docutils literal notranslate"><span class="pre">(conn,</span> <span class="pre">address)</span></code> where <em>conn</em> is a <em>new</em> socket object usable to send
and receive data on the connection, and <em>address</em> is the address bound to
the socket on the other end of the connection.
When <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned it means the connection didn’t take place, in
which case the server should just ignore this event and keep listening
for further incoming connections.</p>
</dd></dl>

<dl class="method">
<dt id="asyncore.dispatcher.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncore.dispatcher.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the socket.  All future operations on the socket object will fail.
The remote end-point will receive no more data (after queued data is
flushed).  Sockets are automatically closed when they are
garbage-collected.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="asyncore.dispatcher_with_send">
<em class="property">class </em><code class="descclassname">asyncore.</code><code class="descname">dispatcher_with_send</code><a class="headerlink" href="#asyncore.dispatcher_with_send" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">dispatcher</span></code></a> subclass which adds simple buffered output capability,
useful for simple clients. For more sophisticated usage use
<a class="reference internal" href="asynchat.html#asynchat.async_chat" title="asynchat.async_chat"><code class="xref py py-class docutils literal notranslate"><span class="pre">asynchat.async_chat</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="asyncore.file_dispatcher">
<em class="property">class </em><code class="descclassname">asyncore.</code><code class="descname">file_dispatcher</code><a class="headerlink" href="#asyncore.file_dispatcher" title="Permalink to this definition">¶</a></dt>
<dd><p>A file_dispatcher takes a file descriptor or file object along with an
optional map argument and wraps it for use with the <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code> or
<code class="xref c c-func docutils literal notranslate"><span class="pre">loop()</span></code> functions.  If provided a file object or anything with a
<code class="xref c c-func docutils literal notranslate"><span class="pre">fileno()</span></code> method, that method will be called and passed to the
<a class="reference internal" href="#asyncore.file_wrapper" title="asyncore.file_wrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">file_wrapper</span></code></a> constructor.  Availability: UNIX.</p>
</dd></dl>

<dl class="class">
<dt id="asyncore.file_wrapper">
<em class="property">class </em><code class="descclassname">asyncore.</code><code class="descname">file_wrapper</code><a class="headerlink" href="#asyncore.file_wrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>A file_wrapper takes an integer file descriptor and calls <a class="reference internal" href="os.html#os.dup" title="os.dup"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.dup()</span></code></a> to
duplicate the handle so that the original handle may be closed independently
of the file_wrapper.  This class implements sufficient methods to emulate a
socket for use by the <a class="reference internal" href="#asyncore.file_dispatcher" title="asyncore.file_dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">file_dispatcher</span></code></a> class.  Availability: UNIX.</p>
</dd></dl>

<div class="section" id="asyncore-example-basic-http-client">
<span id="asyncore-example-1"></span><h2>17.6.1. asyncore Example basic HTTP client<a class="headerlink" href="#asyncore-example-basic-http-client" title="Permalink to this headline">¶</a></h2>
<p>Here is a very basic HTTP client that uses the <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">dispatcher</span></code></a> class to
implement its socket handling:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncore</span><span class="o">,</span> <span class="nn">socket</span>

<span class="k">class</span> <span class="nc">HTTPClient</span><span class="p">(</span><span class="n">asyncore</span><span class="o">.</span><span class="n">dispatcher</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
        <span class="n">asyncore</span><span class="o">.</span><span class="n">dispatcher</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">create_socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span> <span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span> <span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">buffer</span> <span class="o">=</span> <span class="s1">&#39;GET </span><span class="si">%s</span><span class="s1"> HTTP/1.0</span><span class="se">\r\n\r\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">path</span>

    <span class="k">def</span> <span class="nf">handle_connect</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">handle_close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">handle_read</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">print</span> <span class="bp">self</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">8192</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">writable</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">buffer</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">handle_write</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">sent</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">buffer</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">buffer</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">buffer</span><span class="p">[</span><span class="n">sent</span><span class="p">:]</span>


<span class="n">client</span> <span class="o">=</span> <span class="n">HTTPClient</span><span class="p">(</span><span class="s1">&#39;www.python.org&#39;</span><span class="p">,</span> <span class="s1">&#39;/&#39;</span><span class="p">)</span>
<span class="n">asyncore</span><span class="o">.</span><span class="n">loop</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="asyncore-example-basic-echo-server">
<span id="asyncore-example-2"></span><h2>17.6.2. asyncore Example basic echo server<a class="headerlink" href="#asyncore-example-basic-echo-server" title="Permalink to this headline">¶</a></h2>
<p>Here is a basic echo server that uses the <a class="reference internal" href="#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">dispatcher</span></code></a> class to accept
connections and dispatches the incoming connections to a handler:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncore</span>
<span class="kn">import</span> <span class="nn">socket</span>

<span class="k">class</span> <span class="nc">EchoHandler</span><span class="p">(</span><span class="n">asyncore</span><span class="o">.</span><span class="n">dispatcher_with_send</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">handle_read</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">8192</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">data</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">EchoServer</span><span class="p">(</span><span class="n">asyncore</span><span class="o">.</span><span class="n">dispatcher</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">):</span>
        <span class="n">asyncore</span><span class="o">.</span><span class="n">dispatcher</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">create_socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">set_reuse_addr</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">handle_accept</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">pair</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">pair</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">sock</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">pair</span>
            <span class="nb">print</span> <span class="s1">&#39;Incoming connection from </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="nb">repr</span><span class="p">(</span><span class="n">addr</span><span class="p">)</span>
            <span class="n">handler</span> <span class="o">=</span> <span class="n">EchoHandler</span><span class="p">(</span><span class="n">sock</span><span class="p">)</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">EchoServer</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span> <span class="mi">8080</span><span class="p">)</span>
<span class="n">asyncore</span><span class="o">.</span><span class="n">loop</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a><ul>
<li><a class="reference internal" href="#asyncore-example-basic-http-client">17.6.1. asyncore Example basic HTTP client</a></li>
<li><a class="reference internal" href="#asyncore-example-basic-echo-server">17.6.2. asyncore Example basic echo server</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="popen2.html"
                        title="previous chapter">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="asynchat.html"
                        title="next chapter">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/asyncore.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asynchat.html" title="17.7. asynchat — Asynchronous socket command/response handler"
             >next</a> |</li>
        <li class="right" >
          <a href="popen2.html" title="17.5. popen2 — Subprocesses with accessible I/O streams"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\v���HHhtml/library/atexit.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.9. atexit — Exit handlers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.10. traceback — Print or retrieve a stack traceback" href="traceback.html" />
    <link rel="prev" title="28.8. abc — Abstract Base Classes" href="abc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/atexit.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="traceback.html" title="28.10. traceback — Print or retrieve a stack traceback"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="abc.html" title="28.8. abc — Abstract Base Classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-atexit">
<span id="atexit-exit-handlers"></span><h1>28.9. <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> — Exit handlers<a class="headerlink" href="#module-atexit" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/atexit.py">Lib/atexit.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module defines a single function to register cleanup
functions.  Functions thus registered are automatically executed upon normal
interpreter termination.  <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> runs these functions in the <em>reverse</em>
order in which they were registered; if you register <code class="docutils literal notranslate"><span class="pre">A</span></code>, <code class="docutils literal notranslate"><span class="pre">B</span></code>, and <code class="docutils literal notranslate"><span class="pre">C</span></code>,
at interpreter termination time they will be run in the order <code class="docutils literal notranslate"><span class="pre">C</span></code>, <code class="docutils literal notranslate"><span class="pre">B</span></code>,
<code class="docutils literal notranslate"><span class="pre">A</span></code>.</p>
<p><strong>Note:</strong> The functions registered via this module are not called when the
program is killed by a signal not handled by Python, when a Python fatal
internal error is detected, or when <a class="reference internal" href="os.html#os._exit" title="os._exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">os._exit()</span></code></a> is called.</p>
<p id="index-0">This is an alternate interface to the functionality provided by the
<a class="reference internal" href="sys.html#sys.exitfunc" title="sys.exitfunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exitfunc()</span></code></a> variable.</p>
<p>Note: This module is unlikely to work correctly when used with other code that
sets <code class="docutils literal notranslate"><span class="pre">sys.exitfunc</span></code>.  In particular, other core Python modules are free to use
<a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> without the programmer’s knowledge.  Authors who use
<code class="docutils literal notranslate"><span class="pre">sys.exitfunc</span></code> should convert their code to use <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> instead.  The
simplest way to convert code that sets <code class="docutils literal notranslate"><span class="pre">sys.exitfunc</span></code> is to import
<a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> and register the function that had been bound to <code class="docutils literal notranslate"><span class="pre">sys.exitfunc</span></code>.</p>
<dl class="function">
<dt id="atexit.register">
<code class="descclassname">atexit.</code><code class="descname">register</code><span class="sig-paren">(</span><em>func</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#atexit.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register <em>func</em> as a function to be executed at termination.  Any optional
arguments that are to be passed to <em>func</em> must be passed as arguments to
<a class="reference internal" href="#atexit.register" title="atexit.register"><code class="xref py py-func docutils literal notranslate"><span class="pre">register()</span></code></a>.  It is possible to register the same function and arguments
more than once.</p>
<p>At normal program termination (for instance, if <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> is called or
the main module’s execution completes), all functions registered are called in
last in, first out order.  The assumption is that lower level modules will
normally be imported before higher level modules and thus must be cleaned up
later.</p>
<p>If an exception is raised during execution of the exit handlers, a traceback is
printed (unless <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> is raised) and the exception information is
saved.  After all exit handlers have had a chance to run the last exception to
be raised is re-raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>This function now returns <em>func</em>, which makes it possible to use it as a
decorator.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a></dt>
<dd>Useful example of <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> to read and write <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> history files.</dd>
</dl>
</div>
<div class="section" id="atexit-example">
<span id="id1"></span><h2>28.9.1. <a class="reference internal" href="#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> Example<a class="headerlink" href="#atexit-example" title="Permalink to this headline">¶</a></h2>
<p>The following simple example demonstrates how a module can initialize a counter
from a file when it is imported and save the counter’s updated value
automatically when the program terminates without relying on the application
making an explicit call into this module at termination.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">_count</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s2">&quot;counter&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
<span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
    <span class="n">_count</span> <span class="o">=</span> <span class="mi">0</span>

<span class="k">def</span> <span class="nf">incrcounter</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="k">global</span> <span class="n">_count</span>
    <span class="n">_count</span> <span class="o">=</span> <span class="n">_count</span> <span class="o">+</span> <span class="n">n</span>

<span class="k">def</span> <span class="nf">savecounter</span><span class="p">():</span>
    <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;counter&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">_count</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">atexit</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">savecounter</span><span class="p">)</span>
</pre></div>
</div>
<p>Positional and keyword arguments may also be passed to <a class="reference internal" href="#atexit.register" title="atexit.register"><code class="xref py py-func docutils literal notranslate"><span class="pre">register()</span></code></a> to be
passed along to the registered function when it is called:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">goodbye</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">adjective</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;Goodbye, </span><span class="si">%s</span><span class="s1">, it was </span><span class="si">%s</span><span class="s1"> to meet you.&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">adjective</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">atexit</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">goodbye</span><span class="p">,</span> <span class="s1">&#39;Donny&#39;</span><span class="p">,</span> <span class="s1">&#39;nice&#39;</span><span class="p">)</span>

<span class="c1"># or:</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">goodbye</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s1">&#39;nice&#39;</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s1">&#39;Donny&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Usage as a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">atexit</span>

<span class="nd">@atexit</span><span class="o">.</span><span class="n">register</span>
<span class="k">def</span> <span class="nf">goodbye</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s2">&quot;You are now leaving the Python sector.&quot;</span>
</pre></div>
</div>
<p>This only works with functions that can be called without arguments.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a><ul>
<li><a class="reference internal" href="#atexit-example">28.9.1. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="abc.html"
                        title="previous chapter">28.8. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="traceback.html"
                        title="next chapter">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/atexit.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="traceback.html" title="28.10. traceback — Print or retrieve a stack traceback"
             >next</a> |</li>
        <li class="right" >
          <a href="abc.html" title="28.8. abc — Abstract Base Classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�s��̅̅html/library/audioop.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.1. audioop — Manipulate raw audio data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.2. imageop — Manipulate raw image data" href="imageop.html" />
    <link rel="prev" title="21. Multimedia Services" href="mm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/audioop.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imageop.html" title="21.2. imageop — Manipulate raw image data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mm.html" title="21. Multimedia Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-audioop">
<span id="audioop-manipulate-raw-audio-data"></span><h1>21.1. <a class="reference internal" href="#module-audioop" title="audioop: Manipulate raw audio data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code></a> — Manipulate raw audio data<a class="headerlink" href="#module-audioop" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-audioop" title="audioop: Manipulate raw audio data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code></a> module contains some useful operations on sound fragments.
It operates on sound fragments consisting of signed integer samples 8, 16 or 32
bits wide, stored in Python strings.  This is the same format as used by the
<a class="reference internal" href="al.html#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> and <a class="reference internal" href="sunaudio.html#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a> modules.  All scalar items are integers, unless
specified otherwise.</p>
<p id="index-0">This module provides support for a-LAW, u-LAW and Intel/DVI ADPCM encodings.</p>
<p>A few of the more complicated operations only take 16-bit samples, otherwise the
sample size (in bytes) is always a parameter of the operation.</p>
<p>The module defines the following variables and functions:</p>
<dl class="exception">
<dt id="audioop.error">
<em class="property">exception </em><code class="descclassname">audioop.</code><code class="descname">error</code><a class="headerlink" href="#audioop.error" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised on all errors, such as unknown number of bytes per
sample, etc.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.add">
<code class="descclassname">audioop.</code><code class="descname">add</code><span class="sig-paren">(</span><em>fragment1</em>, <em>fragment2</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a fragment which is the addition of the two samples passed as parameters.
<em>width</em> is the sample width in bytes, either <code class="docutils literal notranslate"><span class="pre">1</span></code>, <code class="docutils literal notranslate"><span class="pre">2</span></code> or <code class="docutils literal notranslate"><span class="pre">4</span></code>.  Both
fragments should have the same length.  Samples are truncated in case of overflow.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.adpcm2lin">
<code class="descclassname">audioop.</code><code class="descname">adpcm2lin</code><span class="sig-paren">(</span><em>adpcmfragment</em>, <em>width</em>, <em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.adpcm2lin" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode an Intel/DVI ADPCM coded fragment to a linear fragment.  See the
description of <a class="reference internal" href="#audioop.lin2adpcm" title="audioop.lin2adpcm"><code class="xref py py-func docutils literal notranslate"><span class="pre">lin2adpcm()</span></code></a> for details on ADPCM coding. Return a tuple
<code class="docutils literal notranslate"><span class="pre">(sample,</span> <span class="pre">newstate)</span></code> where the sample has the width specified in <em>width</em>.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.alaw2lin">
<code class="descclassname">audioop.</code><code class="descname">alaw2lin</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.alaw2lin" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert sound fragments in a-LAW encoding to linearly encoded sound fragments.
a-LAW encoding always uses 8 bits samples, so <em>width</em> refers only to the sample
width of the output fragment here.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="audioop.avg">
<code class="descclassname">audioop.</code><code class="descname">avg</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.avg" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the average over all samples in the fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.avgpp">
<code class="descclassname">audioop.</code><code class="descname">avgpp</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.avgpp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the average peak-peak value over all samples in the fragment. No
filtering is done, so the usefulness of this routine is questionable.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.bias">
<code class="descclassname">audioop.</code><code class="descname">bias</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>bias</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.bias" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a fragment that is the original fragment with a bias added to each
sample.  Samples wrap around in case of overflow.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.cross">
<code class="descclassname">audioop.</code><code class="descname">cross</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.cross" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of zero crossings in the fragment passed as an argument.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.findfactor">
<code class="descclassname">audioop.</code><code class="descname">findfactor</code><span class="sig-paren">(</span><em>fragment</em>, <em>reference</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.findfactor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a factor <em>F</em> such that <code class="docutils literal notranslate"><span class="pre">rms(add(fragment,</span> <span class="pre">mul(reference,</span> <span class="pre">-F)))</span></code> is
minimal, i.e., return the factor with which you should multiply <em>reference</em> to
make it match as well as possible to <em>fragment</em>.  The fragments should both
contain 2-byte samples.</p>
<p>The time taken by this routine is proportional to <code class="docutils literal notranslate"><span class="pre">len(fragment)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.findfit">
<code class="descclassname">audioop.</code><code class="descname">findfit</code><span class="sig-paren">(</span><em>fragment</em>, <em>reference</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.findfit" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to match <em>reference</em> as well as possible to a portion of <em>fragment</em> (which
should be the longer fragment).  This is (conceptually) done by taking slices
out of <em>fragment</em>, using <a class="reference internal" href="#audioop.findfactor" title="audioop.findfactor"><code class="xref py py-func docutils literal notranslate"><span class="pre">findfactor()</span></code></a> to compute the best match, and
minimizing the result.  The fragments should both contain 2-byte samples.
Return a tuple <code class="docutils literal notranslate"><span class="pre">(offset,</span> <span class="pre">factor)</span></code> where <em>offset</em> is the (integer) offset into
<em>fragment</em> where the optimal match started and <em>factor</em> is the (floating-point)
factor as per <a class="reference internal" href="#audioop.findfactor" title="audioop.findfactor"><code class="xref py py-func docutils literal notranslate"><span class="pre">findfactor()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.findmax">
<code class="descclassname">audioop.</code><code class="descname">findmax</code><span class="sig-paren">(</span><em>fragment</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.findmax" title="Permalink to this definition">¶</a></dt>
<dd><p>Search <em>fragment</em> for a slice of length <em>length</em> samples (not bytes!) with
maximum energy, i.e., return <em>i</em> for which <code class="docutils literal notranslate"><span class="pre">rms(fragment[i*2:(i+length)*2])</span></code>
is maximal.  The fragments should both contain 2-byte samples.</p>
<p>The routine takes time proportional to <code class="docutils literal notranslate"><span class="pre">len(fragment)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.getsample">
<code class="descclassname">audioop.</code><code class="descname">getsample</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.getsample" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of sample <em>index</em> from the fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.lin2adpcm">
<code class="descclassname">audioop.</code><code class="descname">lin2adpcm</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.lin2adpcm" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert samples to 4 bit Intel/DVI ADPCM encoding.  ADPCM coding is an adaptive
coding scheme, whereby each 4 bit number is the difference between one sample
and the next, divided by a (varying) step.  The Intel/DVI ADPCM algorithm has
been selected for use by the IMA, so it may well become a standard.</p>
<p><em>state</em> is a tuple containing the state of the coder.  The coder returns a tuple
<code class="docutils literal notranslate"><span class="pre">(adpcmfrag,</span> <span class="pre">newstate)</span></code>, and the <em>newstate</em> should be passed to the next call
of <a class="reference internal" href="#audioop.lin2adpcm" title="audioop.lin2adpcm"><code class="xref py py-func docutils literal notranslate"><span class="pre">lin2adpcm()</span></code></a>.  In the initial call, <code class="docutils literal notranslate"><span class="pre">None</span></code> can be passed as the state.
<em>adpcmfrag</em> is the ADPCM coded fragment packed 2 4-bit values per byte.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.lin2alaw">
<code class="descclassname">audioop.</code><code class="descname">lin2alaw</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.lin2alaw" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert samples in the audio fragment to a-LAW encoding and return this as a
Python string.  a-LAW is an audio encoding format whereby you get a dynamic
range of about 13 bits using only 8 bit samples.  It is used by the Sun audio
hardware, among others.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="audioop.lin2lin">
<code class="descclassname">audioop.</code><code class="descname">lin2lin</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>newwidth</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.lin2lin" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert samples between 1-, 2- and 4-byte formats.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>In some audio formats, such as .WAV files, 16 and 32 bit samples are
signed, but 8 bit samples are unsigned.  So when converting to 8 bit wide
samples for these formats, you need to also add 128 to the result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">new_frames</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">lin2lin</span><span class="p">(</span><span class="n">frames</span><span class="p">,</span> <span class="n">old_width</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">new_frames</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">bias</span><span class="p">(</span><span class="n">new_frames</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">128</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">The same, in reverse, has to be applied when converting from 8 to 16 or 32
bit width samples.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="audioop.lin2ulaw">
<code class="descclassname">audioop.</code><code class="descname">lin2ulaw</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.lin2ulaw" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert samples in the audio fragment to u-LAW encoding and return this as a
Python string.  u-LAW is an audio encoding format whereby you get a dynamic
range of about 14 bits using only 8 bit samples.  It is used by the Sun audio
hardware, among others.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.max">
<code class="descclassname">audioop.</code><code class="descname">max</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.max" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the maximum of the <em>absolute value</em> of all samples in a fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.maxpp">
<code class="descclassname">audioop.</code><code class="descname">maxpp</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.maxpp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the maximum peak-peak value in the sound fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.minmax">
<code class="descclassname">audioop.</code><code class="descname">minmax</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.minmax" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple consisting of the minimum and maximum values of all samples in
the sound fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.mul">
<code class="descclassname">audioop.</code><code class="descname">mul</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>factor</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.mul" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a fragment that has all samples in the original fragment multiplied by
the floating-point value <em>factor</em>.  Samples are truncated in case of overflow.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.ratecv">
<code class="descclassname">audioop.</code><code class="descname">ratecv</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>nchannels</em>, <em>inrate</em>, <em>outrate</em>, <em>state</em><span class="optional">[</span>, <em>weightA</em><span class="optional">[</span>, <em>weightB</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#audioop.ratecv" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the frame rate of the input fragment.</p>
<p><em>state</em> is a tuple containing the state of the converter.  The converter returns
a tuple <code class="docutils literal notranslate"><span class="pre">(newfragment,</span> <span class="pre">newstate)</span></code>, and <em>newstate</em> should be passed to the next
call of <a class="reference internal" href="#audioop.ratecv" title="audioop.ratecv"><code class="xref py py-func docutils literal notranslate"><span class="pre">ratecv()</span></code></a>.  The initial call should pass <code class="docutils literal notranslate"><span class="pre">None</span></code> as the state.</p>
<p>The <em>weightA</em> and <em>weightB</em> arguments are parameters for a simple digital filter
and default to <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">0</span></code> respectively.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.reverse">
<code class="descclassname">audioop.</code><code class="descname">reverse</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the samples in a fragment and returns the modified fragment.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.rms">
<code class="descclassname">audioop.</code><code class="descname">rms</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.rms" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the root-mean-square of the fragment, i.e. <code class="docutils literal notranslate"><span class="pre">sqrt(sum(S_i^2)/n)</span></code>.</p>
<p>This is a measure of the power in an audio signal.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.tomono">
<code class="descclassname">audioop.</code><code class="descname">tomono</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>lfactor</em>, <em>rfactor</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.tomono" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a stereo fragment to a mono fragment.  The left channel is multiplied by
<em>lfactor</em> and the right channel by <em>rfactor</em> before adding the two channels to
give a mono signal.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.tostereo">
<code class="descclassname">audioop.</code><code class="descname">tostereo</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em>, <em>lfactor</em>, <em>rfactor</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.tostereo" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a stereo fragment from a mono fragment.  Each pair of samples in the
stereo fragment are computed from the mono sample, whereby left channel samples
are multiplied by <em>lfactor</em> and right channel samples by <em>rfactor</em>.</p>
</dd></dl>

<dl class="function">
<dt id="audioop.ulaw2lin">
<code class="descclassname">audioop.</code><code class="descname">ulaw2lin</code><span class="sig-paren">(</span><em>fragment</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#audioop.ulaw2lin" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert sound fragments in u-LAW encoding to linearly encoded sound fragments.
u-LAW encoding always uses 8 bits samples, so <em>width</em> refers only to the sample
width of the output fragment here.</p>
</dd></dl>

<p>Note that operations such as <a class="reference internal" href="#audioop.mul" title="audioop.mul"><code class="xref py py-func docutils literal notranslate"><span class="pre">mul()</span></code></a> or <a class="reference internal" href="#audioop.max" title="audioop.max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> make no distinction
between mono and stereo fragments, i.e. all samples are treated equal.  If this
is a problem the stereo fragment should be split into two mono fragments first
and recombined later.  Here is an example of how to do that:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">mul_stereo</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">lfactor</span><span class="p">,</span> <span class="n">rfactor</span><span class="p">):</span>
    <span class="n">lsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">tomono</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">rsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">tomono</span><span class="p">(</span><span class="n">sample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">lsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="n">lsample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">lfactor</span><span class="p">)</span>
    <span class="n">rsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="n">rsample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="n">rfactor</span><span class="p">)</span>
    <span class="n">lsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">tostereo</span><span class="p">(</span><span class="n">lsample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="n">rsample</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">tostereo</span><span class="p">(</span><span class="n">rsample</span><span class="p">,</span> <span class="n">width</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">audioop</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">lsample</span><span class="p">,</span> <span class="n">rsample</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
</pre></div>
</div>
<p>If you use the ADPCM coder to build network packets and you want your protocol
to be stateless (i.e. to be able to tolerate packet loss) you should not only
transmit the data but also the state.  Note that you should send the <em>initial</em>
state (the one you passed to <a class="reference internal" href="#audioop.lin2adpcm" title="audioop.lin2adpcm"><code class="xref py py-func docutils literal notranslate"><span class="pre">lin2adpcm()</span></code></a>) along to the decoder, not the
final state (as returned by the coder).  If you want to use
<a class="reference internal" href="struct.html#struct.Struct" title="struct.Struct"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct.Struct</span></code></a> to store the state in binary you can code the first
element (the predicted value) in 16 bits and the second (the delta index) in 8.</p>
<p>The ADPCM coders have never been tried against other ADPCM coders, only against
themselves.  It could well be that I misinterpreted the standards in which case
they will not be interoperable with the respective standards.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">find*()</span></code> routines might look a bit funny at first sight. They are
primarily meant to do echo cancellation.  A reasonably fast way to do this is to
pick the most energetic piece of the output sample, locate that in the input
sample and subtract the whole output sample from the input sample:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">echocancel</span><span class="p">(</span><span class="n">outputdata</span><span class="p">,</span> <span class="n">inputdata</span><span class="p">):</span>
    <span class="n">pos</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">findmax</span><span class="p">(</span><span class="n">outputdata</span><span class="p">,</span> <span class="mi">800</span><span class="p">)</span>    <span class="c1"># one tenth second</span>
    <span class="n">out_test</span> <span class="o">=</span> <span class="n">outputdata</span><span class="p">[</span><span class="n">pos</span><span class="o">*</span><span class="mi">2</span><span class="p">:]</span>
    <span class="n">in_test</span> <span class="o">=</span> <span class="n">inputdata</span><span class="p">[</span><span class="n">pos</span><span class="o">*</span><span class="mi">2</span><span class="p">:]</span>
    <span class="n">ipos</span><span class="p">,</span> <span class="n">factor</span> <span class="o">=</span> <span class="n">audioop</span><span class="o">.</span><span class="n">findfit</span><span class="p">(</span><span class="n">in_test</span><span class="p">,</span> <span class="n">out_test</span><span class="p">)</span>
    <span class="c1"># Optional (for better cancellation):</span>
    <span class="c1"># factor = audioop.findfactor(in_test[ipos*2:ipos*2+len(out_test)],</span>
    <span class="c1">#              out_test)</span>
    <span class="n">prefill</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="se">\0</span><span class="s1">&#39;</span><span class="o">*</span><span class="p">(</span><span class="n">pos</span><span class="o">+</span><span class="n">ipos</span><span class="p">)</span><span class="o">*</span><span class="mi">2</span>
    <span class="n">postfill</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="se">\0</span><span class="s1">&#39;</span><span class="o">*</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">inputdata</span><span class="p">)</span><span class="o">-</span><span class="nb">len</span><span class="p">(</span><span class="n">prefill</span><span class="p">)</span><span class="o">-</span><span class="nb">len</span><span class="p">(</span><span class="n">outputdata</span><span class="p">))</span>
    <span class="n">outputdata</span> <span class="o">=</span> <span class="n">prefill</span> <span class="o">+</span> <span class="n">audioop</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="n">outputdata</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="n">factor</span><span class="p">)</span> <span class="o">+</span> <span class="n">postfill</span>
    <span class="k">return</span> <span class="n">audioop</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">inputdata</span><span class="p">,</span> <span class="n">outputdata</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="mm.html"
                        title="previous chapter">21. Multimedia Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imageop.html"
                        title="next chapter">21.2. <code class="docutils literal notranslate"><span class="pre">imageop</span></code> — Manipulate raw image data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/audioop.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imageop.html" title="21.2. imageop — Manipulate raw image data"
             >next</a> |</li>
        <li class="right" >
          <a href="mm.html" title="21. Multimedia Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�M�""html/library/autogil.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.7. autoGIL — Global Interpreter Lock handling in event loops &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.8. Mac OS Toolbox Modules" href="carbon.html" />
    <link rel="prev" title="37.6. FrameWork — Interactive application framework" href="framework.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/autogil.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="carbon.html" title="37.8. Mac OS Toolbox Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="framework.html" title="37.6. FrameWork — Interactive application framework"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-autoGIL">
<span id="autogil-global-interpreter-lock-handling-in-event-loops"></span><h1>37.7. <a class="reference internal" href="#module-autoGIL" title="autoGIL: Global Interpreter Lock handling in event loops. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autoGIL</span></code></a> — Global Interpreter Lock handling in event loops<a class="headerlink" href="#module-autoGIL" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-autoGIL" title="autoGIL: Global Interpreter Lock handling in event loops. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autoGIL</span></code></a> module provides a function <a class="reference internal" href="#autoGIL.installAutoGIL" title="autoGIL.installAutoGIL"><code class="xref py py-func docutils literal notranslate"><span class="pre">installAutoGIL()</span></code></a> that
automatically locks and unlocks Python’s <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">Global Interpreter Lock</span></a> when
running an event loop.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<dl class="exception">
<dt id="autoGIL.AutoGILError">
<em class="property">exception </em><code class="descclassname">autoGIL.</code><code class="descname">AutoGILError</code><a class="headerlink" href="#autoGIL.AutoGILError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised if the observer callback cannot be installed, for example because the
current thread does not have a run loop.</p>
</dd></dl>

<dl class="function">
<dt id="autoGIL.installAutoGIL">
<code class="descclassname">autoGIL.</code><code class="descname">installAutoGIL</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#autoGIL.installAutoGIL" title="Permalink to this definition">¶</a></dt>
<dd><p>Install an observer callback in the event loop (CFRunLoop) for the current
thread, that will lock and unlock the Global Interpreter Lock (GIL) at
appropriate times, allowing other Python threads to run while the event loop is
idle.</p>
<p>Availability: OSX 10.1 or later.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="framework.html"
                        title="previous chapter">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="carbon.html"
                        title="next chapter">37.8. Mac OS Toolbox Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/autogil.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="carbon.html" title="37.8. Mac OS Toolbox Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="framework.html" title="37.6. FrameWork — Interactive application framework"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�MKfUfUhtml/library/base64.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.13. binhex — Encode and decode binhex4 files" href="binhex.html" />
    <link rel="prev" title="18.11. rfc822 — Parse RFC 2822 mail headers" href="rfc822.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/base64.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="binhex.html" title="18.13. binhex — Encode and decode binhex4 files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="rfc822.html" title="18.11. rfc822 — Parse RFC 2822 mail headers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-base64">
<span id="base64-rfc-3548-base16-base32-base64-data-encodings"></span><h1>18.12. <a class="reference internal" href="#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a> — RFC 3548: Base16, Base32, Base64 Data Encodings<a class="headerlink" href="#module-base64" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module provides data encoding and decoding as specified in <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3548.html"><strong>RFC 3548</strong></a>.
This standard defines the Base16, Base32, and Base64 algorithms for encoding and
decoding arbitrary binary strings into text strings that can be safely sent by
email, used as parts of URLs, or included as part of an HTTP POST request.  The
encoding algorithm is not the same as the <strong class="program">uuencode</strong> program.</p>
<p>There are two interfaces provided by this module.  The modern interface supports
encoding and decoding string objects using both base-64 alphabets defined
in <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3548.html"><strong>RFC 3548</strong></a> (normal, and URL- and filesystem-safe).  The legacy
interface provides for encoding and decoding to and from file-like objects as
well as strings, but only using the Base64 standard alphabet.</p>
<p>The modern interface, which was introduced in Python 2.4, provides:</p>
<dl class="function">
<dt id="base64.b64encode">
<code class="descclassname">base64.</code><code class="descname">b64encode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>altchars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#base64.b64encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode a string using Base64.</p>
<p><em>s</em> is the string to encode.  Optional <em>altchars</em> must be a string of at least
length 2 (additional characters are ignored) which specifies an alternative
alphabet for the <code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> characters.  This allows an application to e.g.
generate URL or filesystem safe Base64 strings.  The default is <code class="docutils literal notranslate"><span class="pre">None</span></code>, for
which the standard Base64 alphabet is used.</p>
<p>The encoded string is returned.</p>
</dd></dl>

<dl class="function">
<dt id="base64.b64decode">
<code class="descclassname">base64.</code><code class="descname">b64decode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>altchars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#base64.b64decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a Base64 encoded string.</p>
<p><em>s</em> is the string to decode.  Optional <em>altchars</em> must be a string of at least
length 2 (additional characters are ignored) which specifies the alternative
alphabet used instead of the <code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> characters.</p>
<p>The decoded string is returned.  A <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised if <em>s</em> is
incorrectly padded.  Characters that are neither
in the normal base-64 alphabet nor the alternative alphabet are
discarded prior to the padding check.</p>
</dd></dl>

<dl class="function">
<dt id="base64.standard_b64encode">
<code class="descclassname">base64.</code><code class="descname">standard_b64encode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.standard_b64encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode string <em>s</em> using the standard Base64 alphabet.</p>
</dd></dl>

<dl class="function">
<dt id="base64.standard_b64decode">
<code class="descclassname">base64.</code><code class="descname">standard_b64decode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.standard_b64decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode string <em>s</em> using the standard Base64 alphabet.</p>
</dd></dl>

<dl class="function">
<dt id="base64.urlsafe_b64encode">
<code class="descclassname">base64.</code><code class="descname">urlsafe_b64encode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.urlsafe_b64encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode string <em>s</em> using the URL- and filesystem-safe
alphabet, which substitutes <code class="docutils literal notranslate"><span class="pre">-</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">_</span></code> instead of <code class="docutils literal notranslate"><span class="pre">/</span></code> in the standard Base64 alphabet.  The result
can still contain <code class="docutils literal notranslate"><span class="pre">=</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="base64.urlsafe_b64decode">
<code class="descclassname">base64.</code><code class="descname">urlsafe_b64decode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.urlsafe_b64decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode string <em>s</em> using the URL- and filesystem-safe
alphabet, which substitutes <code class="docutils literal notranslate"><span class="pre">-</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">_</span></code> instead of <code class="docutils literal notranslate"><span class="pre">/</span></code> in the standard Base64 alphabet.</p>
</dd></dl>

<dl class="function">
<dt id="base64.b32encode">
<code class="descclassname">base64.</code><code class="descname">b32encode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.b32encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode a string using Base32.  <em>s</em> is the string to encode.  The encoded string
is returned.</p>
</dd></dl>

<dl class="function">
<dt id="base64.b32decode">
<code class="descclassname">base64.</code><code class="descname">b32decode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>casefold</em><span class="optional">[</span>, <em>map01</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#base64.b32decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a Base32 encoded string.</p>
<p><em>s</em> is the string to decode.  Optional <em>casefold</em> is a flag specifying whether a
lowercase alphabet is acceptable as input.  For security purposes, the default
is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p><span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3548.html"><strong>RFC 3548</strong></a> allows for optional mapping of the digit 0 (zero) to the letter O
(oh), and for optional mapping of the digit 1 (one) to either the letter I (eye)
or letter L (el).  The optional argument <em>map01</em> when not <code class="docutils literal notranslate"><span class="pre">None</span></code>, specifies
which letter the digit 1 should be mapped to (when <em>map01</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the
digit 0 is always mapped to the letter O).  For security purposes the default is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, so that 0 and 1 are not allowed in the input.</p>
<p>The decoded string is returned.  A <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised if <em>s</em> is
incorrectly padded or if there are non-alphabet characters present in the
string.</p>
</dd></dl>

<dl class="function">
<dt id="base64.b16encode">
<code class="descclassname">base64.</code><code class="descname">b16encode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.b16encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode a string using Base16.</p>
<p><em>s</em> is the string to encode.  The encoded string is returned.</p>
</dd></dl>

<dl class="function">
<dt id="base64.b16decode">
<code class="descclassname">base64.</code><code class="descname">b16decode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>casefold</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#base64.b16decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a Base16 encoded string.</p>
<p><em>s</em> is the string to decode.  Optional <em>casefold</em> is a flag specifying whether a
lowercase alphabet is acceptable as input.  For security purposes, the default
is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>The decoded string is returned.  A <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised if <em>s</em> were
incorrectly padded or if there are non-alphabet characters present in the
string.</p>
</dd></dl>

<p>The legacy interface:</p>
<dl class="function">
<dt id="base64.decode">
<code class="descclassname">base64.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode the contents of the <em>input</em> file and write the resulting binary data to
the <em>output</em> file. <em>input</em> and <em>output</em> must either be file objects or objects
that mimic the file object interface. <em>input</em> will be read until
<code class="docutils literal notranslate"><span class="pre">input.read()</span></code> returns an empty string.</p>
</dd></dl>

<dl class="function">
<dt id="base64.decodestring">
<code class="descclassname">base64.</code><code class="descname">decodestring</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.decodestring" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode the string <em>s</em>, which must contain one or more lines of base64 encoded
data, and return a string containing the resulting binary data.</p>
</dd></dl>

<dl class="function">
<dt id="base64.encode">
<code class="descclassname">base64.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the contents of the <em>input</em> file and write the resulting base64 encoded
data to the <em>output</em> file. <em>input</em> and <em>output</em> must either be file objects or
objects that mimic the file object interface. <em>input</em> will be read until
<code class="docutils literal notranslate"><span class="pre">input.read()</span></code> returns an empty string.  <a class="reference internal" href="#base64.encode" title="base64.encode"><code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code></a> returns the encoded
data plus a trailing newline character (<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="base64.encodestring">
<code class="descclassname">base64.</code><code class="descname">encodestring</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#base64.encodestring" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the string <em>s</em>, which can contain arbitrary binary data, and return a
string containing one or more lines of base64-encoded data.
<a class="reference internal" href="#base64.encodestring" title="base64.encodestring"><code class="xref py py-func docutils literal notranslate"><span class="pre">encodestring()</span></code></a> returns a string containing one or more lines of
base64-encoded data always including an extra trailing newline (<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>).</p>
</dd></dl>

<p>An example usage of the module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">base64</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">encoded</span> <span class="o">=</span> <span class="n">base64</span><span class="o">.</span><span class="n">b64encode</span><span class="p">(</span><span class="s1">&#39;data to be encoded&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">encoded</span>
<span class="go">&#39;ZGF0YSB0byBiZSBlbmNvZGVk&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">base64</span><span class="o">.</span><span class="n">b64decode</span><span class="p">(</span><span class="n">encoded</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">&#39;data to be encoded&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="binascii.html#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a></dt>
<dd>Support module containing ASCII-to-binary and binary-to-ASCII conversions.</dd>
<dt><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1521.html"><strong>RFC 1521</strong></a> - MIME (Multipurpose Internet Mail Extensions) Part One: Mechanisms for Specifying and Describing the Format of Internet Message Bodies</dt>
<dd>Section 5.2, “Base64 Content-Transfer-Encoding,” provides the definition of the
base64 encoding.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="rfc822.html"
                        title="previous chapter">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="binhex.html"
                        title="next chapter">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/base64.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="binhex.html" title="18.13. binhex — Encode and decode binhex4 files"
             >next</a> |</li>
        <li class="right" >
          <a href="rfc822.html" title="18.11. rfc822 — Parse RFC 2822 mail headers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�XiA�A� html/library/basehttpserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.18. BaseHTTPServer — Basic HTTP server &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.19. SimpleHTTPServer — Simple HTTP request handler" href="simplehttpserver.html" />
    <link rel="prev" title="20.17. SocketServer — A framework for network servers" href="socketserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/basehttpserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simplehttpserver.html" title="20.19. SimpleHTTPServer — Simple HTTP request handler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="socketserver.html" title="20.17. SocketServer — A framework for network servers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-BaseHTTPServer">
<span id="basehttpserver-basic-http-server"></span><h1>20.18. <a class="reference internal" href="#module-BaseHTTPServer" title="BaseHTTPServer: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code></a> — Basic HTTP server<a class="headerlink" href="#module-BaseHTTPServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-BaseHTTPServer" title="BaseHTTPServer: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code></a> module has been merged into <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.server</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/BaseHTTPServer.py">Lib/BaseHTTPServer.py</a></p>
<hr class="docutils" />
<p>This module defines two classes for implementing HTTP servers (Web servers).
Usually, this module isn’t used directly, but is used as a basis for building
functioning Web servers. See the <a class="reference internal" href="simplehttpserver.html#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> and
<a class="reference internal" href="cgihttpserver.html#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a> modules.</p>
<p>The first class, <a class="reference internal" href="#BaseHTTPServer.HTTPServer" title="BaseHTTPServer.HTTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPServer</span></code></a>, is a <a class="reference internal" href="socketserver.html#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code></a>
subclass, and therefore implements the <a class="reference internal" href="socketserver.html#SocketServer.BaseServer" title="SocketServer.BaseServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.BaseServer</span></code></a>
interface.  It creates and listens at the HTTP socket, dispatching the requests
to a handler.  Code to create and run the server looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="n">server_class</span><span class="o">=</span><span class="n">BaseHTTPServer</span><span class="o">.</span><span class="n">HTTPServer</span><span class="p">,</span>
        <span class="n">handler_class</span><span class="o">=</span><span class="n">BaseHTTPServer</span><span class="o">.</span><span class="n">BaseHTTPRequestHandler</span><span class="p">):</span>
    <span class="n">server_address</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">)</span>
    <span class="n">httpd</span> <span class="o">=</span> <span class="n">server_class</span><span class="p">(</span><span class="n">server_address</span><span class="p">,</span> <span class="n">handler_class</span><span class="p">)</span>
    <span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<dl class="class">
<dt id="BaseHTTPServer.HTTPServer">
<em class="property">class </em><code class="descclassname">BaseHTTPServer.</code><code class="descname">HTTPServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.HTTPServer" title="Permalink to this definition">¶</a></dt>
<dd><p>This class builds on the <code class="xref py py-class docutils literal notranslate"><span class="pre">TCPServer</span></code> class by storing the server
address as instance variables named <code class="xref py py-attr docutils literal notranslate"><span class="pre">server_name</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">server_port</span></code>. The server is accessible by the handler, typically
through the handler’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">server</span></code> instance variable.</p>
</dd></dl>

<dl class="class">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler">
<em class="property">class </em><code class="descclassname">BaseHTTPServer.</code><code class="descname">BaseHTTPRequestHandler</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em>, <em>server</em><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is used to handle the HTTP requests that arrive at the server. By
itself, it cannot respond to any actual HTTP requests; it must be subclassed
to handle each request method (e.g. GET or
POST). <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPRequestHandler</span></code></a> provides a number of class and
instance variables, and methods for use by subclasses.</p>
<p>The handler will parse the request and the headers, then call a method
specific to the request type. The method name is constructed from the
request. For example, for the request method <code class="docutils literal notranslate"><span class="pre">SPAM</span></code>, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_SPAM()</span></code>
method will be called with no arguments. All of the relevant information is
stored in instance variables of the handler.  Subclasses should not need to
override or extend the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method.</p>
<p><a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPRequestHandler</span></code></a> has the following instance variables:</p>
<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.client_address">
<code class="descname">client_address</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.client_address" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains a tuple of the form <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> referring to the client’s
address.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.server">
<code class="descname">server</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.server" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the server instance.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.command">
<code class="descname">command</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.command" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the command (request type). For example, <code class="docutils literal notranslate"><span class="pre">'GET'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.path">
<code class="descname">path</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.path" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the request path.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.request_version">
<code class="descname">request_version</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.request_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the version string from the request. For example, <code class="docutils literal notranslate"><span class="pre">'HTTP/1.0'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.headers">
<code class="descname">headers</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.headers" title="Permalink to this definition">¶</a></dt>
<dd><p>Holds an instance of the class specified by the <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.MessageClass" title="BaseHTTPServer.BaseHTTPRequestHandler.MessageClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">MessageClass</span></code></a> class
variable. This instance parses and manages the headers in the HTTP
request.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.rfile">
<code class="descname">rfile</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.rfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains an input stream, positioned at the start of the optional input
data.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.wfile">
<code class="descname">wfile</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.wfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the output stream for writing a response back to the
client. Proper adherence to the HTTP protocol must be used when writing to
this stream.</p>
</dd></dl>

<p><a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPRequestHandler</span></code></a> has the following class variables:</p>
<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.server_version">
<code class="descname">server_version</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.server_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies the server software version.  You may want to override this. The
format is multiple whitespace-separated strings, where each string is of
the form name[/version]. For example, <code class="docutils literal notranslate"><span class="pre">'BaseHTTP/0.2'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.sys_version">
<code class="descname">sys_version</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.sys_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the Python system version, in a form usable by the
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.version_string" title="BaseHTTPServer.BaseHTTPRequestHandler.version_string"><code class="xref py py-attr docutils literal notranslate"><span class="pre">version_string</span></code></a> method and the <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.server_version" title="BaseHTTPServer.BaseHTTPRequestHandler.server_version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">server_version</span></code></a> class
variable. For example, <code class="docutils literal notranslate"><span class="pre">'Python/1.4'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.error_message_format">
<code class="descname">error_message_format</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.error_message_format" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies a format string for building an error response to the client. It
uses parenthesized, keyed format specifiers, so the format operand must be
a dictionary. The <em>code</em> key should be an integer, specifying the numeric
HTTP error code value. <em>message</em> should be a string containing a
(detailed) error message of what occurred, and <em>explain</em> should be an
explanation of the error code number. Default <em>message</em> and <em>explain</em>
values can found in the <em>responses</em> class variable.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.error_content_type">
<code class="descname">error_content_type</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.error_content_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies the Content-Type HTTP header of error responses sent to the
client.  The default value is <code class="docutils literal notranslate"><span class="pre">'text/html'</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Previously, the content type was always <code class="docutils literal notranslate"><span class="pre">'text/html'</span></code>.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.protocol_version">
<code class="descname">protocol_version</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.protocol_version" title="Permalink to this definition">¶</a></dt>
<dd><p>This specifies the HTTP protocol version used in responses.  If set to
<code class="docutils literal notranslate"><span class="pre">'HTTP/1.1'</span></code>, the server will permit HTTP persistent connections;
however, your server <em>must</em> then include an accurate <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code>
header (using <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.send_header" title="BaseHTTPServer.BaseHTTPRequestHandler.send_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send_header()</span></code></a>) in all of its responses to clients.
For backwards compatibility, the setting defaults to <code class="docutils literal notranslate"><span class="pre">'HTTP/1.0'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.MessageClass">
<code class="descname">MessageClass</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.MessageClass" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Specifies a <a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a>-like class to parse HTTP headers.
Typically, this is not overridden, and it defaults to
<a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.responses">
<code class="descname">responses</code><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.responses" title="Permalink to this definition">¶</a></dt>
<dd><p>This variable contains a mapping of error code integers to two-element tuples
containing a short and long message. For example, <code class="docutils literal notranslate"><span class="pre">{code:</span> <span class="pre">(shortmessage,</span>
<span class="pre">longmessage)}</span></code>. The <em>shortmessage</em> is usually used as the <em>message</em> key in an
error response, and <em>longmessage</em> as the <em>explain</em> key (see the
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.error_message_format" title="BaseHTTPServer.BaseHTTPRequestHandler.error_message_format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">error_message_format</span></code></a> class variable).</p>
</dd></dl>

<p>A <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPRequestHandler</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.handle">
<code class="descname">handle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request" title="BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_one_request()</span></code></a> once (or, if persistent connections are
enabled, multiple times) to handle incoming HTTP requests. You should
never need to override it; instead, implement appropriate <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code>
methods.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request">
<code class="descname">handle_one_request</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request" title="Permalink to this definition">¶</a></dt>
<dd><p>This method will parse and dispatch the request to the appropriate
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code> method.  You should never need to override it.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.send_error">
<code class="descname">send_error</code><span class="sig-paren">(</span><em>code</em><span class="optional">[</span>, <em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.send_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends and logs a complete error reply to the client. The numeric <em>code</em>
specifies the HTTP error code, with <em>message</em> as optional, more specific text. A
complete set of headers is sent, followed by text composed using the
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.error_message_format" title="BaseHTTPServer.BaseHTTPRequestHandler.error_message_format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">error_message_format</span></code></a> class variable. The body will be empty
if the method is HEAD or the response code is one of the following:
<code class="docutils literal notranslate"><span class="pre">1xx</span></code>, <code class="docutils literal notranslate"><span class="pre">204</span> <span class="pre">No</span> <span class="pre">Content</span></code>, <code class="docutils literal notranslate"><span class="pre">205</span> <span class="pre">Reset</span> <span class="pre">Content</span></code>,
<code class="docutils literal notranslate"><span class="pre">304</span> <span class="pre">Not</span> <span class="pre">Modified</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.send_response">
<code class="descname">send_response</code><span class="sig-paren">(</span><em>code</em><span class="optional">[</span>, <em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.send_response" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends a response header and logs the accepted request. The HTTP response
line is sent, followed by <em>Server</em> and <em>Date</em> headers. The values for
these two headers are picked up from the <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.version_string" title="BaseHTTPServer.BaseHTTPRequestHandler.version_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">version_string()</span></code></a> and
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.date_time_string" title="BaseHTTPServer.BaseHTTPRequestHandler.date_time_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">date_time_string()</span></code></a> methods, respectively.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.send_header">
<code class="descname">send_header</code><span class="sig-paren">(</span><em>keyword</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.send_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes a specific HTTP header to the output stream. <em>keyword</em> should
specify the header keyword, with <em>value</em> specifying its value.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.end_headers">
<code class="descname">end_headers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.end_headers" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends a blank line, indicating the end of the HTTP headers in the
response.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.log_request">
<code class="descname">log_request</code><span class="sig-paren">(</span><span class="optional">[</span><em>code</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs an accepted (successful) request. <em>code</em> should specify the numeric
HTTP code associated with the response. If a size of the response is
available, then it should be passed as the <em>size</em> parameter.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.log_error">
<code class="descname">log_error</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs an error when a request cannot be fulfilled. By default, it passes
the message to <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_message" title="BaseHTTPServer.BaseHTTPRequestHandler.log_message"><code class="xref py py-meth docutils literal notranslate"><span class="pre">log_message()</span></code></a>, so it takes the same arguments
(<em>format</em> and additional values).</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.log_message">
<code class="descname">log_message</code><span class="sig-paren">(</span><em>format</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_message" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs an arbitrary message to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>. This is typically overridden
to create custom error logging mechanisms. The <em>format</em> argument is a
standard printf-style format string, where the additional arguments to
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_message" title="BaseHTTPServer.BaseHTTPRequestHandler.log_message"><code class="xref py py-meth docutils literal notranslate"><span class="pre">log_message()</span></code></a> are applied as inputs to the formatting. The client
ip address and current date and time are prefixed to every message logged.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.version_string">
<code class="descname">version_string</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.version_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the server software’s version string. This is a combination of the
<a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.server_version" title="BaseHTTPServer.BaseHTTPRequestHandler.server_version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">server_version</span></code></a> and <a class="reference internal" href="#BaseHTTPServer.BaseHTTPRequestHandler.sys_version" title="BaseHTTPServer.BaseHTTPRequestHandler.sys_version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys_version</span></code></a> class variables.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.date_time_string">
<code class="descname">date_time_string</code><span class="sig-paren">(</span><span class="optional">[</span><em>timestamp</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.date_time_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the date and time given by <em>timestamp</em> (which must be in the
format returned by <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>), formatted for a message header. If
<em>timestamp</em> is omitted, it uses the current date and time.</p>
<p>The result looks like <code class="docutils literal notranslate"><span class="pre">'Sun,</span> <span class="pre">06</span> <span class="pre">Nov</span> <span class="pre">1994</span> <span class="pre">08:49:37</span> <span class="pre">GMT'</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>The <em>timestamp</em> parameter.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.log_date_time_string">
<code class="descname">log_date_time_string</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.log_date_time_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current date and time, formatted for logging.</p>
</dd></dl>

<dl class="method">
<dt id="BaseHTTPServer.BaseHTTPRequestHandler.address_string">
<code class="descname">address_string</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#BaseHTTPServer.BaseHTTPRequestHandler.address_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the client address, formatted for logging. A name lookup is
performed on the client’s IP address.</p>
</dd></dl>

</dd></dl>

<div class="section" id="more-examples">
<h2>20.18.1. More examples<a class="headerlink" href="#more-examples" title="Permalink to this headline">¶</a></h2>
<p>To create a server that doesn’t run forever, but until some condition is
fulfilled:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">run_while_true</span><span class="p">(</span><span class="n">server_class</span><span class="o">=</span><span class="n">BaseHTTPServer</span><span class="o">.</span><span class="n">HTTPServer</span><span class="p">,</span>
                   <span class="n">handler_class</span><span class="o">=</span><span class="n">BaseHTTPServer</span><span class="o">.</span><span class="n">BaseHTTPRequestHandler</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This assumes that keep_running() is a function of no arguments which</span>
<span class="sd">    is tested initially and after each request.  If its return value</span>
<span class="sd">    is true, the server continues.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">server_address</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">)</span>
    <span class="n">httpd</span> <span class="o">=</span> <span class="n">server_class</span><span class="p">(</span><span class="n">server_address</span><span class="p">,</span> <span class="n">handler_class</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">keep_running</span><span class="p">():</span>
        <span class="n">httpd</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="cgihttpserver.html#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a></dt>
<dd>Extended request handler that supports CGI scripts.</dd>
<dt>Module <a class="reference internal" href="simplehttpserver.html#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a></dt>
<dd>Basic request handler that limits response to files actually under the
document root.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a><ul>
<li><a class="reference internal" href="#more-examples">20.18.1. More examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="socketserver.html"
                        title="previous chapter">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="simplehttpserver.html"
                        title="next chapter">20.19. <code class="docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code> — Simple HTTP request handler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/basehttpserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simplehttpserver.html" title="20.19. SimpleHTTPServer — Simple HTTP request handler"
             >next</a> |</li>
        <li class="right" >
          <a href="socketserver.html" title="20.17. SocketServer — A framework for network servers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\mV�..html/library/bastion.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>30.2. Bastion — Restricting access to objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31. Importing Modules" href="modules.html" />
    <link rel="prev" title="30.1. rexec — Restricted execution framework" href="rexec.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/bastion.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modules.html" title="31. Importing Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="rexec.html" title="30.1. rexec — Restricted execution framework"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="restricted.html" accesskey="U">30. Restricted Execution</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-Bastion">
<span id="bastion-restricting-access-to-objects"></span><h1>30.2. <a class="reference internal" href="#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Bastion</span></code></a> — Restricting access to objects<a class="headerlink" href="#module-Bastion" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Bastion</span></code></a> module has been removed in Python 3.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Disabled module.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The documentation has been left in place to help in reading old code that uses
the module.</p>
</div>
<p>According to the dictionary, a bastion is “a fortified area or position”, or
“something that is considered a stronghold.”  It’s a suitable name for this
module, which provides a way to forbid access to certain attributes of an
object.  It must always be used with the <a class="reference internal" href="rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> module, in order to allow
restricted-mode programs access to certain safe attributes of an object, while
denying access to other, unsafe attributes.</p>
<dl class="function">
<dt id="Bastion.Bastion">
<code class="descclassname">Bastion.</code><code class="descname">Bastion</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>filter</em><span class="optional">[</span>, <em>name</em><span class="optional">[</span>, <em>class</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Bastion.Bastion" title="Permalink to this definition">¶</a></dt>
<dd><p>Protect the object <em>object</em>, returning a bastion for the object.  Any attempt to
access one of the object’s attributes will have to be approved by the <em>filter</em>
function; if the access is denied an <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception will be
raised.</p>
<p>If present, <em>filter</em> must be a function that accepts a string containing an
attribute name, and returns true if access to that attribute will be permitted;
if <em>filter</em> returns false, the access is denied.  The default filter denies
access to any function beginning with an underscore (<code class="docutils literal notranslate"><span class="pre">'_'</span></code>).  The bastion’s
string representation will be <code class="docutils literal notranslate"><span class="pre">&lt;Bastion</span> <span class="pre">for</span> <span class="pre">name&gt;</span></code> if a value for <em>name</em> is
provided; otherwise, <code class="docutils literal notranslate"><span class="pre">repr(object)</span></code> will be used.</p>
<p><em>class</em>, if present, should be a subclass of <a class="reference internal" href="#Bastion.BastionClass" title="Bastion.BastionClass"><code class="xref py py-class docutils literal notranslate"><span class="pre">BastionClass</span></code></a>;  see the
code in <code class="file docutils literal notranslate"><span class="pre">bastion.py</span></code> for the details.  Overriding the default
<a class="reference internal" href="#Bastion.BastionClass" title="Bastion.BastionClass"><code class="xref py py-class docutils literal notranslate"><span class="pre">BastionClass</span></code></a> will rarely be required.</p>
</dd></dl>

<dl class="class">
<dt id="Bastion.BastionClass">
<em class="property">class </em><code class="descclassname">Bastion.</code><code class="descname">BastionClass</code><span class="sig-paren">(</span><em>getfunc</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#Bastion.BastionClass" title="Permalink to this definition">¶</a></dt>
<dd><p>Class which actually implements bastion objects.  This is the default class used
by <a class="reference internal" href="#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">Bastion()</span></code></a>.  The <em>getfunc</em> parameter is a function which returns the
value of an attribute which should be exposed to the restricted execution
environment when called with the name of the attribute as the only parameter.
<em>name</em> is used to construct the <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> of the <a class="reference internal" href="#Bastion.BastionClass" title="Bastion.BastionClass"><code class="xref py py-class docutils literal notranslate"><span class="pre">BastionClass</span></code></a>
instance.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="rexec.html"
                        title="previous chapter">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="modules.html"
                        title="next chapter">31. Importing Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/bastion.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modules.html" title="31. Importing Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="rexec.html" title="30.1. rexec — Restricted execution framework"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="restricted.html" >30. Restricted Execution</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Bt����html/library/bdb.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.1. bdb — Debugger framework &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.2. pdb — The Python Debugger" href="pdb.html" />
    <link rel="prev" title="26. Debugging and Profiling" href="debug.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/bdb.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pdb.html" title="26.2. pdb — The Python Debugger"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="debug.html" title="26. Debugging and Profiling"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-bdb">
<span id="bdb-debugger-framework"></span><h1>26.1. <a class="reference internal" href="#module-bdb" title="bdb: Debugger framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdb</span></code></a> — Debugger framework<a class="headerlink" href="#module-bdb" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/bdb.py">Lib/bdb.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-bdb" title="bdb: Debugger framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdb</span></code></a> module handles basic debugger functions, like setting breakpoints
or managing execution via the debugger.</p>
<p>The following exception is defined:</p>
<dl class="exception">
<dt id="bdb.BdbQuit">
<em class="property">exception </em><code class="descclassname">bdb.</code><code class="descname">BdbQuit</code><a class="headerlink" href="#bdb.BdbQuit" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by the <a class="reference internal" href="#bdb.Bdb" title="bdb.Bdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Bdb</span></code></a> class for quitting the debugger.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-bdb" title="bdb: Debugger framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdb</span></code></a> module also defines two classes:</p>
<dl class="class">
<dt id="bdb.Breakpoint">
<em class="property">class </em><code class="descclassname">bdb.</code><code class="descname">Breakpoint</code><span class="sig-paren">(</span><em>self</em>, <em>file</em>, <em>line</em>, <em>temporary=0</em>, <em>cond=None</em>, <em>funcname=None</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Breakpoint" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements temporary breakpoints, ignore counts, disabling and
(re-)enabling, and conditionals.</p>
<p>Breakpoints are indexed by number through a list called <code class="xref py py-attr docutils literal notranslate"><span class="pre">bpbynumber</span></code>
and by <code class="docutils literal notranslate"><span class="pre">(file,</span> <span class="pre">line)</span></code> pairs through <code class="xref py py-attr docutils literal notranslate"><span class="pre">bplist</span></code>.  The former points to a
single instance of class <a class="reference internal" href="#bdb.Breakpoint" title="bdb.Breakpoint"><code class="xref py py-class docutils literal notranslate"><span class="pre">Breakpoint</span></code></a>.  The latter points to a list of
such instances since there may be more than one breakpoint per line.</p>
<p>When creating a breakpoint, its associated filename should be in canonical
form.  If a <em>funcname</em> is defined, a breakpoint hit will be counted when the
first line of that function is executed.  A conditional breakpoint always
counts a hit.</p>
<p><a class="reference internal" href="#bdb.Breakpoint" title="bdb.Breakpoint"><code class="xref py py-class docutils literal notranslate"><span class="pre">Breakpoint</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="bdb.Breakpoint.deleteMe">
<code class="descname">deleteMe</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Breakpoint.deleteMe" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the breakpoint from the list associated to a file/line.  If it is
the last breakpoint in that position, it also deletes the entry for the
file/line.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Breakpoint.enable">
<code class="descname">enable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Breakpoint.enable" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the breakpoint as enabled.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Breakpoint.disable">
<code class="descname">disable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Breakpoint.disable" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the breakpoint as disabled.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Breakpoint.pprint">
<code class="descname">pprint</code><span class="sig-paren">(</span><span class="optional">[</span><em>out</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Breakpoint.pprint" title="Permalink to this definition">¶</a></dt>
<dd><p>Print all the information about the breakpoint:</p>
<ul class="simple">
<li>The breakpoint number.</li>
<li>If it is temporary or not.</li>
<li>Its file,line position.</li>
<li>The condition that causes a break.</li>
<li>If it must be ignored the next N times.</li>
<li>The breakpoint hit count.</li>
</ul>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="bdb.Bdb">
<em class="property">class </em><code class="descclassname">bdb.</code><code class="descname">Bdb</code><span class="sig-paren">(</span><em>skip=None</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#bdb.Bdb" title="bdb.Bdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Bdb</span></code></a> class acts as a generic Python debugger base class.</p>
<p>This class takes care of the details of the trace facility; a derived class
should implement user interaction.  The standard debugger class
(<a class="reference internal" href="pdb.html#pdb.Pdb" title="pdb.Pdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">pdb.Pdb</span></code></a>) is an example.</p>
<p>The <em>skip</em> argument, if given, must be an iterable of glob-style
module name patterns.  The debugger will not step into frames that
originate in a module that matches one of these patterns. Whether a
frame is considered to originate in a certain module is determined
by the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> in the frame globals.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <em>skip</em> argument.</p>
</div>
<p>The following methods of <a class="reference internal" href="#bdb.Bdb" title="bdb.Bdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Bdb</span></code></a> normally don’t need to be overridden.</p>
<dl class="method">
<dt id="bdb.Bdb.canonic">
<code class="descname">canonic</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.canonic" title="Permalink to this definition">¶</a></dt>
<dd><p>Auxiliary method for getting a filename in a canonical form, that is, as a
case-normalized (on case-insensitive filesystems) absolute path, stripped
of surrounding angle brackets.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">botframe</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">stopframe</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">returnframe</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">quitting</span></code> attributes with values ready to start debugging.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.trace_dispatch">
<code class="descname">trace_dispatch</code><span class="sig-paren">(</span><em>frame</em>, <em>event</em>, <em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.trace_dispatch" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is installed as the trace function of debugged frames.  Its
return value is the new trace function (in most cases, that is, itself).</p>
<p>The default implementation decides how to dispatch a frame, depending on
the type of event (passed as a string) that is about to be executed.
<em>event</em> can be one of the following:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">&quot;line&quot;</span></code>: A new line of code is going to be executed.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;call&quot;</span></code>: A function is about to be called, or another code block
entered.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;return&quot;</span></code>: A function or other code block is about to return.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;exception&quot;</span></code>: An exception has occurred.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;c_call&quot;</span></code>: A C function is about to be called.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;c_return&quot;</span></code>: A C function has returned.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;c_exception&quot;</span></code>: A C function has raised an exception.</li>
</ul>
<p>For the Python events, specialized functions (see below) are called.  For
the C events, no action is taken.</p>
<p>The <em>arg</em> parameter depends on the previous event.</p>
<p>See the documentation for <a class="reference internal" href="sys.html#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.settrace()</span></code></a> for more information on the
trace function.  For more information on code and frame objects, refer to
<a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.dispatch_line">
<code class="descname">dispatch_line</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.dispatch_line" title="Permalink to this definition">¶</a></dt>
<dd><p>If the debugger should stop on the current line, invoke the
<a class="reference internal" href="#bdb.Bdb.user_line" title="bdb.Bdb.user_line"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_line()</span></code></a> method (which should be overridden in subclasses).
Raise a <a class="reference internal" href="#bdb.BdbQuit" title="bdb.BdbQuit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BdbQuit</span></code></a> exception if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">Bdb.quitting</span></code> flag is set
(which can be set from <a class="reference internal" href="#bdb.Bdb.user_line" title="bdb.Bdb.user_line"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_line()</span></code></a>).  Return a reference to the
<a class="reference internal" href="#bdb.Bdb.trace_dispatch" title="bdb.Bdb.trace_dispatch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">trace_dispatch()</span></code></a> method for further tracing in that scope.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.dispatch_call">
<code class="descname">dispatch_call</code><span class="sig-paren">(</span><em>frame</em>, <em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.dispatch_call" title="Permalink to this definition">¶</a></dt>
<dd><p>If the debugger should stop on this function call, invoke the
<a class="reference internal" href="#bdb.Bdb.user_call" title="bdb.Bdb.user_call"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_call()</span></code></a> method (which should be overridden in subclasses).
Raise a <a class="reference internal" href="#bdb.BdbQuit" title="bdb.BdbQuit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BdbQuit</span></code></a> exception if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">Bdb.quitting</span></code> flag is set
(which can be set from <a class="reference internal" href="#bdb.Bdb.user_call" title="bdb.Bdb.user_call"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_call()</span></code></a>).  Return a reference to the
<a class="reference internal" href="#bdb.Bdb.trace_dispatch" title="bdb.Bdb.trace_dispatch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">trace_dispatch()</span></code></a> method for further tracing in that scope.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.dispatch_return">
<code class="descname">dispatch_return</code><span class="sig-paren">(</span><em>frame</em>, <em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.dispatch_return" title="Permalink to this definition">¶</a></dt>
<dd><p>If the debugger should stop on this function return, invoke the
<a class="reference internal" href="#bdb.Bdb.user_return" title="bdb.Bdb.user_return"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_return()</span></code></a> method (which should be overridden in subclasses).
Raise a <a class="reference internal" href="#bdb.BdbQuit" title="bdb.BdbQuit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BdbQuit</span></code></a> exception if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">Bdb.quitting</span></code> flag is set
(which can be set from <a class="reference internal" href="#bdb.Bdb.user_return" title="bdb.Bdb.user_return"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_return()</span></code></a>).  Return a reference to the
<a class="reference internal" href="#bdb.Bdb.trace_dispatch" title="bdb.Bdb.trace_dispatch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">trace_dispatch()</span></code></a> method for further tracing in that scope.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.dispatch_exception">
<code class="descname">dispatch_exception</code><span class="sig-paren">(</span><em>frame</em>, <em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.dispatch_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>If the debugger should stop at this exception, invokes the
<a class="reference internal" href="#bdb.Bdb.user_exception" title="bdb.Bdb.user_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_exception()</span></code></a> method (which should be overridden in subclasses).
Raise a <a class="reference internal" href="#bdb.BdbQuit" title="bdb.BdbQuit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BdbQuit</span></code></a> exception if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">Bdb.quitting</span></code> flag is set
(which can be set from <a class="reference internal" href="#bdb.Bdb.user_exception" title="bdb.Bdb.user_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">user_exception()</span></code></a>).  Return a reference to the
<a class="reference internal" href="#bdb.Bdb.trace_dispatch" title="bdb.Bdb.trace_dispatch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">trace_dispatch()</span></code></a> method for further tracing in that scope.</p>
</dd></dl>

<p>Normally derived classes don’t override the following methods, but they may
if they want to redefine the definition of stopping and breakpoints.</p>
<dl class="method">
<dt id="bdb.Bdb.stop_here">
<code class="descname">stop_here</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.stop_here" title="Permalink to this definition">¶</a></dt>
<dd><p>This method checks if the <em>frame</em> is somewhere below <code class="xref py py-attr docutils literal notranslate"><span class="pre">botframe</span></code> in
the call stack.  <code class="xref py py-attr docutils literal notranslate"><span class="pre">botframe</span></code> is the frame in which debugging started.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.break_here">
<code class="descname">break_here</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.break_here" title="Permalink to this definition">¶</a></dt>
<dd><p>This method checks if there is a breakpoint in the filename and line
belonging to <em>frame</em> or, at least, in the current function.  If the
breakpoint is a temporary one, this method deletes it.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.break_anywhere">
<code class="descname">break_anywhere</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.break_anywhere" title="Permalink to this definition">¶</a></dt>
<dd><p>This method checks if there is a breakpoint in the filename of the current
frame.</p>
</dd></dl>

<p>Derived classes should override these methods to gain control over debugger
operation.</p>
<dl class="method">
<dt id="bdb.Bdb.user_call">
<code class="descname">user_call</code><span class="sig-paren">(</span><em>frame</em>, <em>argument_list</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.user_call" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called from <a class="reference internal" href="#bdb.Bdb.dispatch_call" title="bdb.Bdb.dispatch_call"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dispatch_call()</span></code></a> when there is the
possibility that a break might be necessary anywhere inside the called
function.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.user_line">
<code class="descname">user_line</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.user_line" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called from <a class="reference internal" href="#bdb.Bdb.dispatch_line" title="bdb.Bdb.dispatch_line"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dispatch_line()</span></code></a> when either
<a class="reference internal" href="#bdb.Bdb.stop_here" title="bdb.Bdb.stop_here"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop_here()</span></code></a> or <a class="reference internal" href="#bdb.Bdb.break_here" title="bdb.Bdb.break_here"><code class="xref py py-meth docutils literal notranslate"><span class="pre">break_here()</span></code></a> yields <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.user_return">
<code class="descname">user_return</code><span class="sig-paren">(</span><em>frame</em>, <em>return_value</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.user_return" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called from <a class="reference internal" href="#bdb.Bdb.dispatch_return" title="bdb.Bdb.dispatch_return"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dispatch_return()</span></code></a> when <a class="reference internal" href="#bdb.Bdb.stop_here" title="bdb.Bdb.stop_here"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop_here()</span></code></a>
yields <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.user_exception">
<code class="descname">user_exception</code><span class="sig-paren">(</span><em>frame</em>, <em>exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.user_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called from <a class="reference internal" href="#bdb.Bdb.dispatch_exception" title="bdb.Bdb.dispatch_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dispatch_exception()</span></code></a> when
<a class="reference internal" href="#bdb.Bdb.stop_here" title="bdb.Bdb.stop_here"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop_here()</span></code></a> yields <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.do_clear">
<code class="descname">do_clear</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.do_clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle how a breakpoint must be removed when it is a temporary one.</p>
<p>This method must be implemented by derived classes.</p>
</dd></dl>

<p>Derived classes and clients can call the following methods to affect the
stepping state.</p>
<dl class="method">
<dt id="bdb.Bdb.set_step">
<code class="descname">set_step</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_step" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop after one line of code.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_next">
<code class="descname">set_next</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_next" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop on the next line in or below the given frame.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_return">
<code class="descname">set_return</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_return" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop when returning from the given frame.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_until">
<code class="descname">set_until</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_until" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop when the line with the line no greater than the current one is
reached or when returning from current frame.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_trace">
<code class="descname">set_trace</code><span class="sig-paren">(</span><span class="optional">[</span><em>frame</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_trace" title="Permalink to this definition">¶</a></dt>
<dd><p>Start debugging from <em>frame</em>.  If <em>frame</em> is not specified, debugging
starts from caller’s frame.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_continue">
<code class="descname">set_continue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_continue" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop only at breakpoints or when finished.  If there are no breakpoints,
set the system trace function to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.set_quit">
<code class="descname">set_quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">quitting</span></code> attribute to <code class="docutils literal notranslate"><span class="pre">True</span></code>.  This raises <a class="reference internal" href="#bdb.BdbQuit" title="bdb.BdbQuit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BdbQuit</span></code></a> in
the next call to one of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">dispatch_*()</span></code> methods.</p>
</dd></dl>

<p>Derived classes and clients can call the following methods to manipulate
breakpoints.  These methods return a string containing an error message if
something went wrong, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if all is well.</p>
<dl class="method">
<dt id="bdb.Bdb.set_break">
<code class="descname">set_break</code><span class="sig-paren">(</span><em>filename</em>, <em>lineno</em>, <em>temporary=0</em>, <em>cond=None</em>, <em>funcname=None</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.set_break" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a new breakpoint.  If the <em>lineno</em> line doesn’t exist for the
<em>filename</em> passed as argument, return an error message.  The <em>filename</em>
should be in canonical form, as described in the <a class="reference internal" href="#bdb.Bdb.canonic" title="bdb.Bdb.canonic"><code class="xref py py-meth docutils literal notranslate"><span class="pre">canonic()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.clear_break">
<code class="descname">clear_break</code><span class="sig-paren">(</span><em>filename</em>, <em>lineno</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.clear_break" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the breakpoints in <em>filename</em> and <em>lineno</em>.  If none were set, an
error message is returned.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.clear_bpbynumber">
<code class="descname">clear_bpbynumber</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.clear_bpbynumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the breakpoint which has the index <em>arg</em> in the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">Breakpoint.bpbynumber</span></code>.  If <em>arg</em> is not numeric or out of range,
return an error message.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.clear_all_file_breaks">
<code class="descname">clear_all_file_breaks</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.clear_all_file_breaks" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all breakpoints in <em>filename</em>.  If none were set, an error message
is returned.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.clear_all_breaks">
<code class="descname">clear_all_breaks</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.clear_all_breaks" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all existing breakpoints.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.get_break">
<code class="descname">get_break</code><span class="sig-paren">(</span><em>filename</em>, <em>lineno</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.get_break" title="Permalink to this definition">¶</a></dt>
<dd><p>Check if there is a breakpoint for <em>lineno</em> of <em>filename</em>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.get_breaks">
<code class="descname">get_breaks</code><span class="sig-paren">(</span><em>filename</em>, <em>lineno</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.get_breaks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all breakpoints for <em>lineno</em> in <em>filename</em>, or an empty list if
none are set.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.get_file_breaks">
<code class="descname">get_file_breaks</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.get_file_breaks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all breakpoints in <em>filename</em>, or an empty list if none are set.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.get_all_breaks">
<code class="descname">get_all_breaks</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.get_all_breaks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all breakpoints that are set.</p>
</dd></dl>

<p>Derived classes and clients can call the following methods to get a data
structure representing a stack trace.</p>
<dl class="method">
<dt id="bdb.Bdb.get_stack">
<code class="descname">get_stack</code><span class="sig-paren">(</span><em>f</em>, <em>t</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.get_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a list of records for a frame and all higher (calling) and lower
frames, and the size of the higher part.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.format_stack_entry">
<code class="descname">format_stack_entry</code><span class="sig-paren">(</span><em>frame_lineno</em><span class="optional">[</span>, <em>lprefix=': '</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.format_stack_entry" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string with information about a stack entry, identified by a
<code class="docutils literal notranslate"><span class="pre">(frame,</span> <span class="pre">lineno)</span></code> tuple:</p>
<ul class="simple">
<li>The canonical form of the filename which contains the frame.</li>
<li>The function name, or <code class="docutils literal notranslate"><span class="pre">&quot;&lt;lambda&gt;&quot;</span></code>.</li>
<li>The input arguments.</li>
<li>The return value.</li>
<li>The line of code (if it exists).</li>
</ul>
</dd></dl>

<p>The following two methods can be called by clients to use a debugger to debug
a <a class="reference internal" href="../glossary.html#term-statement"><span class="xref std std-term">statement</span></a>, given as a string.</p>
<dl class="method">
<dt id="bdb.Bdb.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Debug a statement executed via the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement.  <em>globals</em>
defaults to <code class="xref py py-attr docutils literal notranslate"><span class="pre">__main__.__dict__</span></code>, <em>locals</em> defaults to <em>globals</em>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.runeval">
<code class="descname">runeval</code><span class="sig-paren">(</span><em>expr</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.runeval" title="Permalink to this definition">¶</a></dt>
<dd><p>Debug an expression executed via the <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> function.  <em>globals</em> and
<em>locals</em> have the same meaning as in <a class="reference internal" href="#bdb.Bdb.run" title="bdb.Bdb.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.runctx">
<code class="descname">runctx</code><span class="sig-paren">(</span><em>cmd</em>, <em>globals</em>, <em>locals</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.runctx" title="Permalink to this definition">¶</a></dt>
<dd><p>For backwards compatibility.  Calls the <a class="reference internal" href="#bdb.Bdb.run" title="bdb.Bdb.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="bdb.Bdb.runcall">
<code class="descname">runcall</code><span class="sig-paren">(</span><em>func</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.Bdb.runcall" title="Permalink to this definition">¶</a></dt>
<dd><p>Debug a single function call, and return its result.</p>
</dd></dl>

</dd></dl>

<p>Finally, the module defines the following functions:</p>
<dl class="function">
<dt id="bdb.checkfuncname">
<code class="descclassname">bdb.</code><code class="descname">checkfuncname</code><span class="sig-paren">(</span><em>b</em>, <em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.checkfuncname" title="Permalink to this definition">¶</a></dt>
<dd><p>Check whether we should break here, depending on the way the breakpoint <em>b</em>
was set.</p>
<p>If it was set via line number, it checks if <code class="docutils literal notranslate"><span class="pre">b.line</span></code> is the same as the one
in the frame also passed as argument.  If the breakpoint was set via function
name, we have to check we are in the right frame (the right function) and if
we are in its first executable line.</p>
</dd></dl>

<dl class="function">
<dt id="bdb.effective">
<code class="descclassname">bdb.</code><code class="descname">effective</code><span class="sig-paren">(</span><em>file</em>, <em>line</em>, <em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#bdb.effective" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if there is an effective (active) breakpoint at this line of code.
Return a tuple of the breakpoint and a boolean that indicates if it is ok
to delete a temporary breakpoint.  Return <code class="docutils literal notranslate"><span class="pre">(None,</span> <span class="pre">None)</span></code> if there is no
matching breakpoint.</p>
</dd></dl>

<dl class="function">
<dt id="bdb.set_trace">
<code class="descclassname">bdb.</code><code class="descname">set_trace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bdb.set_trace" title="Permalink to this definition">¶</a></dt>
<dd><p>Start debugging with a <a class="reference internal" href="#bdb.Bdb" title="bdb.Bdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Bdb</span></code></a> instance from caller’s frame.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="debug.html"
                        title="previous chapter">26. Debugging and Profiling</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pdb.html"
                        title="next chapter">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/bdb.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pdb.html" title="26.2. pdb — The Python Debugger"
             >next</a> |</li>
        <li class="right" >
          <a href="debug.html" title="26. Debugging and Profiling"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��X��Y�Yhtml/library/binascii.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.14. binascii — Convert between binary and ASCII &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.15. quopri — Encode and decode MIME quoted-printable data" href="quopri.html" />
    <link rel="prev" title="18.13. binhex — Encode and decode binhex4 files" href="binhex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/binascii.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="quopri.html" title="18.15. quopri — Encode and decode MIME quoted-printable data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="binhex.html" title="18.13. binhex — Encode and decode binhex4 files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-binascii">
<span id="binascii-convert-between-binary-and-ascii"></span><h1>18.14. <a class="reference internal" href="#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a> — Convert between binary and ASCII<a class="headerlink" href="#module-binascii" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The <a class="reference internal" href="#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a> module contains a number of methods to convert between
binary and various ASCII-encoded binary representations. Normally, you will not
use these functions directly but use wrapper modules like <a class="reference internal" href="uu.html#module-uu" title="uu: Encode and decode files in uuencode format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">uu</span></code></a>,
<a class="reference internal" href="base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a>, or <a class="reference internal" href="binhex.html#module-binhex" title="binhex: Encode and decode files in binhex4 format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binhex</span></code></a> instead. The <a class="reference internal" href="#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a> module contains
low-level functions written in C for greater speed that are used by the
higher-level modules.</p>
<p>The <a class="reference internal" href="#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="binascii.a2b_uu">
<code class="descclassname">binascii.</code><code class="descname">a2b_uu</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.a2b_uu" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a single line of uuencoded data back to binary and return the binary
data. Lines normally contain 45 (binary) bytes, except for the last line. Line
data may be followed by whitespace.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.b2a_uu">
<code class="descclassname">binascii.</code><code class="descname">b2a_uu</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.b2a_uu" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert binary data to a line of ASCII characters, the return value is the
converted line, including a newline char. The length of <em>data</em> should be at most
45.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.a2b_base64">
<code class="descclassname">binascii.</code><code class="descname">a2b_base64</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.a2b_base64" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a block of base64 data back to binary and return the binary data. More
than one line may be passed at a time.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.b2a_base64">
<code class="descclassname">binascii.</code><code class="descname">b2a_base64</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.b2a_base64" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert binary data to a line of ASCII characters in base64 coding. The return
value is the converted line, including a newline char.  The newline is
added because the original use case for this function was to feed it a
series of 57 byte input lines to get output lines that conform to the
MIME-base64 standard.  Otherwise the output conforms to <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3548.html"><strong>RFC 3548</strong></a>.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.a2b_qp">
<code class="descclassname">binascii.</code><code class="descname">a2b_qp</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>header</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#binascii.a2b_qp" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a block of quoted-printable data back to binary and return the binary
data. More than one line may be passed at a time. If the optional argument
<em>header</em> is present and true, underscores will be decoded as spaces.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.b2a_qp">
<code class="descclassname">binascii.</code><code class="descname">b2a_qp</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>quotetabs</em>, <em>istext</em>, <em>header</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#binascii.b2a_qp" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert binary data to a line(s) of ASCII characters in quoted-printable
encoding.  The return value is the converted line(s). If the optional argument
<em>quotetabs</em> is present and true, all tabs and spaces will be encoded.   If the
optional argument <em>istext</em> is present and true, newlines are not encoded but
trailing whitespace will be encoded. If the optional argument <em>header</em> is
present and true, spaces will be encoded as underscores per RFC1522. If the
optional argument <em>header</em> is present and false, newline characters will be
encoded as well; otherwise linefeed conversion might corrupt the binary data
stream.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.a2b_hqx">
<code class="descclassname">binascii.</code><code class="descname">a2b_hqx</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.a2b_hqx" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert binhex4 formatted ASCII data to binary, without doing RLE-decompression.
The string should contain a complete number of binary bytes, or (in case of the
last portion of the binhex4 data) have the remaining bits zero.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.rledecode_hqx">
<code class="descclassname">binascii.</code><code class="descname">rledecode_hqx</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.rledecode_hqx" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform RLE-decompression on the data, as per the binhex4 standard. The
algorithm uses <code class="docutils literal notranslate"><span class="pre">0x90</span></code> after a byte as a repeat indicator, followed by a count.
A count of <code class="docutils literal notranslate"><span class="pre">0</span></code> specifies a byte value of <code class="docutils literal notranslate"><span class="pre">0x90</span></code>. The routine returns the
decompressed data, unless data input data ends in an orphaned repeat indicator,
in which case the <a class="reference internal" href="#binascii.Incomplete" title="binascii.Incomplete"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Incomplete</span></code></a> exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.rlecode_hqx">
<code class="descclassname">binascii.</code><code class="descname">rlecode_hqx</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.rlecode_hqx" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform binhex4 style RLE-compression on <em>data</em> and return the result.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.b2a_hqx">
<code class="descclassname">binascii.</code><code class="descname">b2a_hqx</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.b2a_hqx" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform hexbin4 binary-to-ASCII translation and return the resulting string. The
argument should already be RLE-coded, and have a length divisible by 3 (except
possibly the last fragment).</p>
</dd></dl>

<dl class="function">
<dt id="binascii.crc_hqx">
<code class="descclassname">binascii.</code><code class="descname">crc_hqx</code><span class="sig-paren">(</span><em>data</em>, <em>crc</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.crc_hqx" title="Permalink to this definition">¶</a></dt>
<dd><p>Compute a 16-bit CRC value of <em>data</em>, starting with an initial <em>crc</em> and
returning the result.  This uses the CRC-CCITT polynomial
<em>x</em><sup>16</sup> + <em>x</em><sup>12</sup> + <em>x</em><sup>5</sup> + 1, often represented as
0x1021.  This CRC is used in the binhex4 format.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.crc32">
<code class="descclassname">binascii.</code><code class="descname">crc32</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>crc</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#binascii.crc32" title="Permalink to this definition">¶</a></dt>
<dd><p>Compute CRC-32, the 32-bit checksum of data, starting with an initial crc.  This
is consistent with the ZIP file checksum.  Since the algorithm is designed for
use as a checksum algorithm, it is not suitable for use as a general hash
algorithm.  Use as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="n">binascii</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="s2">&quot;hello world&quot;</span><span class="p">)</span>
<span class="c1"># Or, in two pieces:</span>
<span class="n">crc</span> <span class="o">=</span> <span class="n">binascii</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="s2">&quot;hello&quot;</span><span class="p">)</span>
<span class="n">crc</span> <span class="o">=</span> <span class="n">binascii</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="s2">&quot; world&quot;</span><span class="p">,</span> <span class="n">crc</span><span class="p">)</span> <span class="o">&amp;</span> <span class="mh">0xffffffff</span>
<span class="nb">print</span> <span class="s1">&#39;crc32 = 0x</span><span class="si">%08x</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">crc</span>
</pre></div>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To generate the same numeric value across all Python versions and
platforms use crc32(data) &amp; 0xffffffff.  If you are only using
the checksum in packed binary format this is not necessary as the
return value is the correct 32bit binary representation
regardless of sign.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The return value is in the range [-2**31, 2**31-1]
regardless of platform.  In the past the value would be signed on
some platforms and unsigned on others.  Use &amp; 0xffffffff on the
value if you want it to match Python 3 behavior.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.0: </span>The return value is unsigned and in the range [0, 2**32-1]
regardless of platform.</p>
</div>
<dl class="function">
<dt id="binascii.b2a_hex">
<code class="descclassname">binascii.</code><code class="descname">b2a_hex</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.b2a_hex" title="Permalink to this definition">¶</a></dt>
<dt id="binascii.hexlify">
<code class="descclassname">binascii.</code><code class="descname">hexlify</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.hexlify" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hexadecimal representation of the binary <em>data</em>.  Every byte of
<em>data</em> is converted into the corresponding 2-digit hex representation.  The
resulting string is therefore twice as long as the length of <em>data</em>.</p>
</dd></dl>

<dl class="function">
<dt id="binascii.a2b_hex">
<code class="descclassname">binascii.</code><code class="descname">a2b_hex</code><span class="sig-paren">(</span><em>hexstr</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.a2b_hex" title="Permalink to this definition">¶</a></dt>
<dt id="binascii.unhexlify">
<code class="descclassname">binascii.</code><code class="descname">unhexlify</code><span class="sig-paren">(</span><em>hexstr</em><span class="sig-paren">)</span><a class="headerlink" href="#binascii.unhexlify" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the binary data represented by the hexadecimal string <em>hexstr</em>.  This
function is the inverse of <a class="reference internal" href="#binascii.b2a_hex" title="binascii.b2a_hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">b2a_hex()</span></code></a>. <em>hexstr</em> must contain an even number
of hexadecimal digits (which can be upper or lower case), otherwise a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
</dd></dl>

<dl class="exception">
<dt id="binascii.Error">
<em class="property">exception </em><code class="descclassname">binascii.</code><code class="descname">Error</code><a class="headerlink" href="#binascii.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on errors. These are usually programming errors.</p>
</dd></dl>

<dl class="exception">
<dt id="binascii.Incomplete">
<em class="property">exception </em><code class="descclassname">binascii.</code><code class="descname">Incomplete</code><a class="headerlink" href="#binascii.Incomplete" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on incomplete data. These are usually not programming errors,
but may be handled by reading a little more data and trying again.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a></dt>
<dd>Support for RFC compliant base64-style encoding in base 16, 32, and 64.</dd>
<dt>Module <a class="reference internal" href="binhex.html#module-binhex" title="binhex: Encode and decode files in binhex4 format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binhex</span></code></a></dt>
<dd>Support for the binhex format used on the Macintosh.</dd>
<dt>Module <a class="reference internal" href="uu.html#module-uu" title="uu: Encode and decode files in uuencode format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">uu</span></code></a></dt>
<dd>Support for UU encoding used on Unix.</dd>
<dt>Module <a class="reference internal" href="quopri.html#module-quopri" title="quopri: Encode and decode files using the MIME quoted-printable encoding."><code class="xref py py-mod docutils literal notranslate"><span class="pre">quopri</span></code></a></dt>
<dd>Support for quoted-printable encoding used in MIME email messages.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="binhex.html"
                        title="previous chapter">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="quopri.html"
                        title="next chapter">18.15. <code class="docutils literal notranslate"><span class="pre">quopri</span></code> — Encode and decode MIME quoted-printable data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/binascii.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="quopri.html" title="18.15. quopri — Encode and decode MIME quoted-printable data"
             >next</a> |</li>
        <li class="right" >
          <a href="binhex.html" title="18.13. binhex — Encode and decode binhex4 files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\HWe�-,-,html/library/binhex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.13. binhex — Encode and decode binhex4 files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.14. binascii — Convert between binary and ASCII" href="binascii.html" />
    <link rel="prev" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings" href="base64.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/binhex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="binascii.html" title="18.14. binascii — Convert between binary and ASCII"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="base64.html" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-binhex">
<span id="binhex-encode-and-decode-binhex4-files"></span><h1>18.13. <a class="reference internal" href="#module-binhex" title="binhex: Encode and decode files in binhex4 format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binhex</span></code></a> — Encode and decode binhex4 files<a class="headerlink" href="#module-binhex" title="Permalink to this headline">¶</a></h1>
<p>This module encodes and decodes files in binhex4 format, a format allowing
representation of Macintosh files in ASCII.  On the Macintosh, both forks of a
file and the finder information are encoded (or decoded), on other platforms
only the data fork is handled.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3.x, special Macintosh support has been removed.</p>
</div>
<p>The <a class="reference internal" href="#module-binhex" title="binhex: Encode and decode files in binhex4 format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binhex</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="binhex.binhex">
<code class="descclassname">binhex.</code><code class="descname">binhex</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="sig-paren">)</span><a class="headerlink" href="#binhex.binhex" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a binary file with filename <em>input</em> to binhex file <em>output</em>. The
<em>output</em> parameter can either be a filename or a file-like object (any object
supporting a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method).</p>
</dd></dl>

<dl class="function">
<dt id="binhex.hexbin">
<code class="descclassname">binhex.</code><code class="descname">hexbin</code><span class="sig-paren">(</span><em>input</em><span class="optional">[</span>, <em>output</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#binhex.hexbin" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a binhex file <em>input</em>. <em>input</em> may be a filename or a file-like object
supporting <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> methods. The resulting file is written
to a file named <em>output</em>, unless the argument is omitted in which case the
output filename is read from the binhex file.</p>
</dd></dl>

<p>The following exception is also defined:</p>
<dl class="exception">
<dt id="binhex.Error">
<em class="property">exception </em><code class="descclassname">binhex.</code><code class="descname">Error</code><a class="headerlink" href="#binhex.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when something can’t be encoded using the binhex format (for
example, a filename is too long to fit in the filename field), or when input is
not properly encoded binhex data.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="binascii.html#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a></dt>
<dd>Support module containing ASCII-to-binary and binary-to-ASCII conversions.</dd>
</dl>
</div>
<div class="section" id="notes">
<span id="binhex-notes"></span><h2>18.13.1. Notes<a class="headerlink" href="#notes" title="Permalink to this headline">¶</a></h2>
<p>There is an alternative, more powerful interface to the coder and decoder, see
the source for details.</p>
<p>If you code or decode textfiles on non-Macintosh platforms they will still use
the old Macintosh newline convention (carriage-return as end of line).</p>
<p>As of this writing, <a class="reference internal" href="#binhex.hexbin" title="binhex.hexbin"><code class="xref py py-func docutils literal notranslate"><span class="pre">hexbin()</span></code></a> appears to not work in all cases.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a><ul>
<li><a class="reference internal" href="#notes">18.13.1. Notes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="base64.html"
                        title="previous chapter">18.12. <code class="docutils literal notranslate"><span class="pre">base64</span></code> — RFC 3548: Base16, Base32, Base64 Data Encodings</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="binascii.html"
                        title="next chapter">18.14. <code class="docutils literal notranslate"><span class="pre">binascii</span></code> — Convert between binary and ASCII</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/binhex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="binascii.html" title="18.14. binascii — Convert between binary and ASCII"
             >next</a> |</li>
        <li class="right" >
          <a href="base64.html" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���XZ`Z`html/library/bisect.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.5. bisect — Array bisection algorithm &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.6. array — Efficient arrays of numeric values" href="array.html" />
    <link rel="prev" title="8.4. heapq — Heap queue algorithm" href="heapq.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/bisect.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="array.html" title="8.6. array — Efficient arrays of numeric values"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-bisect">
<span id="bisect-array-bisection-algorithm"></span><h1>8.5. <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> — Array bisection algorithm<a class="headerlink" href="#module-bisect" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/bisect.py">Lib/bisect.py</a></p>
<hr class="docutils" />
<p>This module provides support for maintaining a list in sorted order without
having to sort the list after each insertion.  For long lists of items with
expensive comparison operations, this can be an improvement over the more common
approach.  The module is called <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> because it uses a basic bisection
algorithm to do its work.  The source code may be most useful as a working
example of the algorithm (the boundary conditions are already right!).</p>
<p>The following functions are provided:</p>
<dl class="function">
<dt id="bisect.bisect_left">
<code class="descclassname">bisect.</code><code class="descname">bisect_left</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.bisect_left" title="Permalink to this definition">¶</a></dt>
<dd><p>Locate the insertion point for <em>x</em> in <em>a</em> to maintain sorted order.
The parameters <em>lo</em> and <em>hi</em> may be used to specify a subset of the list
which should be considered; by default the entire list is used.  If <em>x</em> is
already present in <em>a</em>, the insertion point will be before (to the left of)
any existing entries.  The return value is suitable for use as the first
parameter to <code class="docutils literal notranslate"><span class="pre">list.insert()</span></code> assuming that <em>a</em> is already sorted.</p>
<p>The returned insertion point <em>i</em> partitions the array <em>a</em> into two halves so
that <code class="docutils literal notranslate"><span class="pre">all(val</span> <span class="pre">&lt;</span> <span class="pre">x</span> <span class="pre">for</span> <span class="pre">val</span> <span class="pre">in</span> <span class="pre">a[lo:i])</span></code> for the left side and
<code class="docutils literal notranslate"><span class="pre">all(val</span> <span class="pre">&gt;=</span> <span class="pre">x</span> <span class="pre">for</span> <span class="pre">val</span> <span class="pre">in</span> <span class="pre">a[i:hi])</span></code> for the right side.</p>
</dd></dl>

<dl class="function">
<dt id="bisect.bisect_right">
<code class="descclassname">bisect.</code><code class="descname">bisect_right</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.bisect_right" title="Permalink to this definition">¶</a></dt>
<dt id="bisect.bisect">
<code class="descclassname">bisect.</code><code class="descname">bisect</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.bisect" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#bisect.bisect_left" title="bisect.bisect_left"><code class="xref py py-func docutils literal notranslate"><span class="pre">bisect_left()</span></code></a>, but returns an insertion point which comes
after (to the right of) any existing entries of <em>x</em> in <em>a</em>.</p>
<p>The returned insertion point <em>i</em> partitions the array <em>a</em> into two halves so
that <code class="docutils literal notranslate"><span class="pre">all(val</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">for</span> <span class="pre">val</span> <span class="pre">in</span> <span class="pre">a[lo:i])</span></code> for the left side and
<code class="docutils literal notranslate"><span class="pre">all(val</span> <span class="pre">&gt;</span> <span class="pre">x</span> <span class="pre">for</span> <span class="pre">val</span> <span class="pre">in</span> <span class="pre">a[i:hi])</span></code> for the right side.</p>
</dd></dl>

<dl class="function">
<dt id="bisect.insort_left">
<code class="descclassname">bisect.</code><code class="descname">insort_left</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.insort_left" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert <em>x</em> in <em>a</em> in sorted order.  This is equivalent to
<code class="docutils literal notranslate"><span class="pre">a.insert(bisect.bisect_left(a,</span> <span class="pre">x,</span> <span class="pre">lo,</span> <span class="pre">hi),</span> <span class="pre">x)</span></code> assuming that <em>a</em> is
already sorted.  Keep in mind that the O(log n) search is dominated by
the slow O(n) insertion step.</p>
</dd></dl>

<dl class="function">
<dt id="bisect.insort_right">
<code class="descclassname">bisect.</code><code class="descname">insort_right</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.insort_right" title="Permalink to this definition">¶</a></dt>
<dt id="bisect.insort">
<code class="descclassname">bisect.</code><code class="descname">insort</code><span class="sig-paren">(</span><em>a</em>, <em>x</em>, <em>lo=0</em>, <em>hi=len(a)</em><span class="sig-paren">)</span><a class="headerlink" href="#bisect.insort" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#bisect.insort_left" title="bisect.insort_left"><code class="xref py py-func docutils literal notranslate"><span class="pre">insort_left()</span></code></a>, but inserting <em>x</em> in <em>a</em> after any existing
entries of <em>x</em>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://code.activestate.com/recipes/577197-sortedcollection/">SortedCollection recipe</a> that uses
bisect to build a full-featured collection class with straight-forward search
methods and support for a key-function.  The keys are precomputed to save
unnecessary calls to the key function during searches.</p>
</div>
<div class="section" id="searching-sorted-lists">
<h2>8.5.1. Searching Sorted Lists<a class="headerlink" href="#searching-sorted-lists" title="Permalink to this headline">¶</a></h2>
<p>The above <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-func docutils literal notranslate"><span class="pre">bisect()</span></code></a> functions are useful for finding insertion points but
can be tricky or awkward to use for common searching tasks. The following five
functions show how to transform them into the standard lookups for sorted
lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">index</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
    <span class="s1">&#39;Locate the leftmost value exactly equal to x&#39;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_left</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">i</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)</span> <span class="ow">and</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="n">x</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">i</span>
    <span class="k">raise</span> <span class="ne">ValueError</span>

<span class="k">def</span> <span class="nf">find_lt</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
    <span class="s1">&#39;Find rightmost value less than x&#39;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_left</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">i</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">raise</span> <span class="ne">ValueError</span>

<span class="k">def</span> <span class="nf">find_le</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
    <span class="s1">&#39;Find rightmost value less than or equal to x&#39;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_right</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">i</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">raise</span> <span class="ne">ValueError</span>

<span class="k">def</span> <span class="nf">find_gt</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
    <span class="s1">&#39;Find leftmost value greater than x&#39;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_right</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">i</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
    <span class="k">raise</span> <span class="ne">ValueError</span>

<span class="k">def</span> <span class="nf">find_ge</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
    <span class="s1">&#39;Find leftmost item greater than or equal to x&#39;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">bisect_left</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">i</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
    <span class="k">raise</span> <span class="ne">ValueError</span>
</pre></div>
</div>
</div>
<div class="section" id="other-examples">
<h2>8.5.2. Other Examples<a class="headerlink" href="#other-examples" title="Permalink to this headline">¶</a></h2>
<p id="bisect-example">The <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-func docutils literal notranslate"><span class="pre">bisect()</span></code></a> function can be useful for numeric table lookups. This
example uses <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-func docutils literal notranslate"><span class="pre">bisect()</span></code></a> to look up a letter grade for an exam score (say)
based on a set of ordered numeric breakpoints: 90 and up is an ‘A’, 80 to 89 is
a ‘B’, and so on:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">grade</span><span class="p">(</span><span class="n">score</span><span class="p">,</span> <span class="n">breakpoints</span><span class="o">=</span><span class="p">[</span><span class="mi">60</span><span class="p">,</span> <span class="mi">70</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">90</span><span class="p">],</span> <span class="n">grades</span><span class="o">=</span><span class="s1">&#39;FDCBA&#39;</span><span class="p">):</span>
<span class="go">        i = bisect(breakpoints, score)</span>
<span class="go">        return grades[i]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">grade</span><span class="p">(</span><span class="n">score</span><span class="p">)</span> <span class="k">for</span> <span class="n">score</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">33</span><span class="p">,</span> <span class="mi">99</span><span class="p">,</span> <span class="mi">77</span><span class="p">,</span> <span class="mi">70</span><span class="p">,</span> <span class="mi">89</span><span class="p">,</span> <span class="mi">90</span><span class="p">,</span> <span class="mi">100</span><span class="p">]]</span>
<span class="go">[&#39;F&#39;, &#39;A&#39;, &#39;C&#39;, &#39;C&#39;, &#39;B&#39;, &#39;A&#39;, &#39;A&#39;]</span>
</pre></div>
</div>
<p>Unlike the <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function, it does not make sense for the <a class="reference internal" href="#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-func docutils literal notranslate"><span class="pre">bisect()</span></code></a>
functions to have <em>key</em> or <em>reversed</em> arguments because that would lead to an
inefficient design (successive calls to bisect functions would not “remember”
all of the previous key lookups).</p>
<p>Instead, it is better to search a list of precomputed keys to find the index
of the record in question:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">8</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;black&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">r</span><span class="p">:</span> <span class="n">r</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">=</span> <span class="p">[</span><span class="n">r</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">data</span><span class="p">]</span>         <span class="c1"># precomputed list of keys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="n">bisect_left</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="mi">0</span><span class="p">)]</span>
<span class="go">(&#39;black&#39;, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="n">bisect_left</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="go">(&#39;blue&#39;, 1)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="n">bisect_left</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="mi">5</span><span class="p">)]</span>
<span class="go">(&#39;red&#39;, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="p">[</span><span class="n">bisect_left</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="mi">8</span><span class="p">)]</span>
<span class="go">(&#39;yellow&#39;, 8)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a><ul>
<li><a class="reference internal" href="#searching-sorted-lists">8.5.1. Searching Sorted Lists</a></li>
<li><a class="reference internal" href="#other-examples">8.5.2. Other Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="heapq.html"
                        title="previous chapter">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="array.html"
                        title="next chapter">8.6. <code class="docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/bisect.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="array.html" title="8.6. array — Efficient arrays of numeric values"
             >next</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�_��o�ohtml/library/bsddb.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.11. bsddb — Interface to Berkeley DB library &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.12. dumbdbm — Portable DBM implementation" href="dumbdbm.html" />
    <link rel="prev" title="11.10. dbhash — DBM-style interface to the BSD database library" href="dbhash.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/bsddb.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dumbdbm.html" title="11.12. dumbdbm — Portable DBM implementation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dbhash.html" title="11.10. dbhash — DBM-style interface to the BSD database library"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-bsddb">
<span id="bsddb-interface-to-berkeley-db-library"></span><h1>11.11. <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> — Interface to Berkeley DB library<a class="headerlink" href="#module-bsddb" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module provides an interface to the Berkeley DB library.  Users
can create hash, btree or record based library files using the appropriate open
call. Bsddb objects behave generally like dictionaries.  Keys and values must be
strings, however, so to use other objects as keys or to store other kinds of
objects the user must serialize them somehow, typically using
<a class="reference internal" href="marshal.html#marshal.dumps" title="marshal.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">marshal.dumps()</span></code></a> or  <a class="reference internal" href="pickle.html#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.dumps()</span></code></a>.</p>
<p>The <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module requires a Berkeley DB library version from 4.0 thru
4.7.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.jcea.es/programacion/pybsddb.htm">http://www.jcea.es/programacion/pybsddb.htm</a></dt>
<dd>The website with documentation for the <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.db</span></code> Python Berkeley DB
interface that closely mirrors the object oriented interface provided in
Berkeley DB 4.x itself.</dd>
<dt><a class="reference external" href="http://www.oracle.com/database/berkeley-db/">http://www.oracle.com/database/berkeley-db/</a></dt>
<dd>The Berkeley DB library.</dd>
</dl>
</div>
<p>A more modern DB, DBEnv and DBSequence object interface is available in the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.db</span></code> module which closely matches the Berkeley DB C API documented at
the above URLs.  Additional features provided by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.db</span></code> API include
fine tuning, transactions, logging, and multiprocess concurrent database access.</p>
<p>The following is a description of the legacy <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> interface compatible
with the old Python bsddb module.  Starting in Python 2.5 this interface should
be safe for multithreaded access.  The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.db</span></code> API is recommended for
threading users as it provides better control.</p>
<p>The <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module defines the following functions that create objects that
access the appropriate type of Berkeley DB file.  The first two arguments of
each function are the same.  For ease of portability, only the first two
arguments should be used in most instances.</p>
<dl class="function">
<dt id="bsddb.hashopen">
<code class="descclassname">bsddb.</code><code class="descname">hashopen</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>pgsize</em><span class="optional">[</span>, <em>ffactor</em><span class="optional">[</span>, <em>nelem</em><span class="optional">[</span>, <em>cachesize</em><span class="optional">[</span>, <em>lorder</em><span class="optional">[</span>, <em>hflags</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.hashopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the hash format file named <em>filename</em>.  Files never intended to be
preserved on disk may be created by passing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the  <em>filename</em>.  The
optional <em>flag</em> identifies the mode used to open the file.  It may be <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
(read only), <code class="docutils literal notranslate"><span class="pre">'w'</span></code> (read-write), <code class="docutils literal notranslate"><span class="pre">'c'</span></code> (read-write - create if necessary;
the default) or <code class="docutils literal notranslate"><span class="pre">'n'</span></code> (read-write - truncate to zero length).  The other
arguments are rarely used and are just passed to the low-level <code class="xref c c-func docutils literal notranslate"><span class="pre">dbopen()</span></code>
function.  Consult the Berkeley DB documentation for their use and
interpretation.</p>
</dd></dl>

<dl class="function">
<dt id="bsddb.btopen">
<code class="descclassname">bsddb.</code><code class="descname">btopen</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>btflags</em><span class="optional">[</span>, <em>cachesize</em><span class="optional">[</span>, <em>maxkeypage</em><span class="optional">[</span>, <em>minkeypage</em><span class="optional">[</span>, <em>pgsize</em><span class="optional">[</span>, <em>lorder</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.btopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the btree format file named <em>filename</em>.  Files never intended  to be
preserved on disk may be created by passing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the  <em>filename</em>.  The
optional <em>flag</em> identifies the mode used to open the file.  It may be <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
(read only), <code class="docutils literal notranslate"><span class="pre">'w'</span></code> (read-write), <code class="docutils literal notranslate"><span class="pre">'c'</span></code> (read-write - create if necessary;
the default) or <code class="docutils literal notranslate"><span class="pre">'n'</span></code> (read-write - truncate to zero length).  The other
arguments are rarely used and are just passed to the low-level dbopen function.
Consult the Berkeley DB documentation for their use and interpretation.</p>
</dd></dl>

<dl class="function">
<dt id="bsddb.rnopen">
<code class="descclassname">bsddb.</code><code class="descname">rnopen</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>rnflags</em><span class="optional">[</span>, <em>cachesize</em><span class="optional">[</span>, <em>pgsize</em><span class="optional">[</span>, <em>lorder</em><span class="optional">[</span>, <em>rlen</em><span class="optional">[</span>, <em>delim</em><span class="optional">[</span>, <em>source</em><span class="optional">[</span>, <em>pad</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.rnopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a DB record format file named <em>filename</em>.  Files never intended  to be
preserved on disk may be created by passing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the  <em>filename</em>.  The
optional <em>flag</em> identifies the mode used to open the file.  It may be <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
(read only), <code class="docutils literal notranslate"><span class="pre">'w'</span></code> (read-write), <code class="docutils literal notranslate"><span class="pre">'c'</span></code> (read-write - create if necessary;
the default) or <code class="docutils literal notranslate"><span class="pre">'n'</span></code> (read-write - truncate to zero length).  The other
arguments are rarely used and are just passed to the low-level dbopen function.
Consult the Berkeley DB documentation for their use and interpretation.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Beginning in 2.3 some Unix versions of Python may have a <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb185</span></code> module.
This is present <em>only</em> to allow backwards compatibility with systems which ship
with the old Berkeley DB 1.85 database library.  The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb185</span></code> module
should never be used directly in new code. The module has been removed in
Python 3.  If you find you still need it look in PyPI.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="dbhash.html#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a></dt>
<dd>DBM-style interface to the <a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a></dd>
</dl>
</div>
<div class="section" id="hash-btree-and-record-objects">
<span id="bsddb-objects"></span><h2>11.11.1. Hash, BTree and Record Objects<a class="headerlink" href="#hash-btree-and-record-objects" title="Permalink to this headline">¶</a></h2>
<p>Once instantiated, hash, btree and record objects support the same methods as
dictionaries.  In addition, they support the methods listed below.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3.1: </span>Added dictionary methods.</p>
</div>
<dl class="method">
<dt id="bsddb.bsddbobject.close">
<code class="descclassname">bsddbobject.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the underlying file.  The object can no longer be accessed.  Since there
is no open <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> method for these objects, to open the file again a new
<a class="reference internal" href="#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module open function must be called.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.keys">
<code class="descclassname">bsddbobject.</code><code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the list of keys contained in the DB file.  The order of the list is
unspecified and should not be relied on.  In particular, the order of the list
returned is different for different file formats.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.has_key">
<code class="descclassname">bsddbobject.</code><code class="descname">has_key</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.has_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the DB file contains the argument as a key.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.set_location">
<code class="descclassname">bsddbobject.</code><code class="descname">set_location</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.set_location" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor to the item indicated by <em>key</em> and return a tuple containing the
key and its value.  For binary tree databases (opened using <a class="reference internal" href="#bsddb.btopen" title="bsddb.btopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">btopen()</span></code></a>), if
<em>key</em> does not actually exist in the database, the cursor will point to the next
item in sorted order and return that key and value.  For other databases,
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> will be raised if <em>key</em> is not found in the database.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.first">
<code class="descclassname">bsddbobject.</code><code class="descname">first</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.first" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor to the first item in the DB file and return it.  The order of
keys in the file is unspecified, except in the case of B-Tree databases. This
method raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">bsddb.error</span></code> if the database is empty.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.next">
<code class="descclassname">bsddbobject.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor to the next item in the DB file and return it.  The order of
keys in the file is unspecified, except in the case of B-Tree databases.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.previous">
<code class="descclassname">bsddbobject.</code><code class="descname">previous</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.previous" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor to the previous item in the DB file and return it.  The order of
keys in the file is unspecified, except in the case of B-Tree databases.  This
is not supported on hashtable databases (those opened with <a class="reference internal" href="#bsddb.hashopen" title="bsddb.hashopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">hashopen()</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.last">
<code class="descclassname">bsddbobject.</code><code class="descname">last</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.last" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor to the last item in the DB file and return it.  The order of keys
in the file is unspecified.  This is not supported on hashtable databases (those
opened with <a class="reference internal" href="#bsddb.hashopen" title="bsddb.hashopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">hashopen()</span></code></a>). This method raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">bsddb.error</span></code> if the
database is empty.</p>
</dd></dl>

<dl class="method">
<dt id="bsddb.bsddbobject.sync">
<code class="descclassname">bsddbobject.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bsddb.bsddbobject.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>Synchronize the database on disk.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">bsddb</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span> <span class="o">=</span> <span class="n">bsddb</span><span class="o">.</span><span class="n">btopen</span><span class="p">(</span><span class="s1">&#39;spam.db&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span> <span class="n">db</span><span class="p">[</span><span class="s1">&#39;</span><span class="si">%d</span><span class="s1">&#39;</span><span class="o">%</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">%d</span><span class="s1">&#39;</span><span class="o">%</span> <span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="p">[</span><span class="s1">&#39;3&#39;</span><span class="p">]</span>
<span class="go">&#39;9&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="go">[&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="go">(&#39;0&#39;, &#39;0&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">(&#39;1&#39;, &#39;1&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">last</span><span class="p">()</span>
<span class="go">(&#39;9&#39;, &#39;81&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">set_location</span><span class="p">(</span><span class="s1">&#39;2&#39;</span><span class="p">)</span>
<span class="go">(&#39;2&#39;, &#39;4&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">previous</span><span class="p">()</span>
<span class="go">(&#39;1&#39;, &#39;1&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">db</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
<span class="go">0 0</span>
<span class="go">1 1</span>
<span class="go">2 4</span>
<span class="go">3 9</span>
<span class="go">4 16</span>
<span class="go">5 25</span>
<span class="go">6 36</span>
<span class="go">7 49</span>
<span class="go">8 64</span>
<span class="go">9 81</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;8&#39;</span> <span class="ow">in</span> <span class="n">db</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">db</span><span class="o">.</span><span class="n">sync</span><span class="p">()</span>
<span class="go">0</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a><ul>
<li><a class="reference internal" href="#hash-btree-and-record-objects">11.11.1. Hash, BTree and Record Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="dbhash.html"
                        title="previous chapter">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dumbdbm.html"
                        title="next chapter">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/bsddb.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dumbdbm.html" title="11.12. dumbdbm — Portable DBM implementation"
             >next</a> |</li>
        <li class="right" >
          <a href="dbhash.html" title="11.10. dbhash — DBM-style interface to the BSD database library"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\/_�xqxqhtml/library/bz2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12.3. bz2 — Compression compatible with bzip2 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12.4. zipfile — Work with ZIP archives" href="zipfile.html" />
    <link rel="prev" title="12.2. gzip — Support for gzip files" href="gzip.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/bz2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zipfile.html" title="12.4. zipfile — Work with ZIP archives"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gzip.html" title="12.2. gzip — Support for gzip files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" accesskey="U">12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-bz2">
<span id="bz2-compression-compatible-with-bzip2"></span><h1>12.3. <a class="reference internal" href="#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> — Compression compatible with <strong class="program">bzip2</strong><a class="headerlink" href="#module-bz2" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module provides a comprehensive interface for the bz2 compression library.
It implements a complete file interface, one-shot (de)compression functions, and
types for sequential (de)compression.</p>
<p>Here is a summary of the features offered by the bz2 module:</p>
<ul class="simple">
<li><a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class implements a complete file interface, including
<a class="reference internal" href="#bz2.BZ2File.readline" title="bz2.BZ2File.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, <a class="reference internal" href="#bz2.BZ2File.readlines" title="bz2.BZ2File.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a>,
<a class="reference internal" href="#bz2.BZ2File.writelines" title="bz2.BZ2File.writelines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writelines()</span></code></a>, <a class="reference internal" href="#bz2.BZ2File.seek" title="bz2.BZ2File.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a>, etc;</li>
<li><a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class implements emulated <a class="reference internal" href="#bz2.BZ2File.seek" title="bz2.BZ2File.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> support;</li>
<li><a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class implements universal newline support;</li>
<li><a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class offers an optimized line iteration using the readahead
algorithm borrowed from file objects;</li>
<li>Sequential (de)compression supported by <a class="reference internal" href="#bz2.BZ2Compressor" title="bz2.BZ2Compressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Compressor</span></code></a> and
<a class="reference internal" href="#bz2.BZ2Decompressor" title="bz2.BZ2Decompressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Decompressor</span></code></a> classes;</li>
<li>One-shot (de)compression supported by <a class="reference internal" href="#bz2.compress" title="bz2.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a> and <a class="reference internal" href="#bz2.decompress" title="bz2.decompress"><code class="xref py py-func docutils literal notranslate"><span class="pre">decompress()</span></code></a>
functions;</li>
<li>Thread safety uses individual locking mechanism.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Handling of multi-stream bzip2 files is not supported.  Modules such as
<a class="reference external" href="https://github.com/nvawda/bz2file">bz2file</a> let you overcome this.</p>
</div>
<div class="section" id="de-compression-of-files">
<h2>12.3.1. (De)compression of files<a class="headerlink" href="#de-compression-of-files" title="Permalink to this headline">¶</a></h2>
<p>Handling of compressed files is offered by the <a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class.</p>
<span class="target" id="index-0"></span><dl class="class">
<dt id="bz2.BZ2File">
<em class="property">class </em><code class="descclassname">bz2.</code><code class="descname">BZ2File</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>buffering</em><span class="optional">[</span>, <em>compresslevel</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a bz2 file. Mode can be either <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>, for reading (default)
or writing. When opened for writing, the file will be created if it doesn’t
exist, and truncated otherwise. If <em>buffering</em> is given, <code class="docutils literal notranslate"><span class="pre">0</span></code> means
unbuffered, and larger numbers specify the buffer size; the default is
<code class="docutils literal notranslate"><span class="pre">0</span></code>. If <em>compresslevel</em> is given, it must be a number between <code class="docutils literal notranslate"><span class="pre">1</span></code> and
<code class="docutils literal notranslate"><span class="pre">9</span></code>; the default is <code class="docutils literal notranslate"><span class="pre">9</span></code>. Add a <code class="docutils literal notranslate"><span class="pre">'U'</span></code> to mode to open the file for input
in <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode. Any line ending in the input file will be
seen as a <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> in Python.  Also, a file so opened gains the attribute
<code class="xref py py-attr docutils literal notranslate"><span class="pre">newlines</span></code>; the value for this attribute is one of <code class="docutils literal notranslate"><span class="pre">None</span></code> (no newline
read yet), <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code> or a tuple containing all the
newline types seen. Universal newlines are available only when
reading. Instances support iteration in the same way as normal <a class="reference internal" href="functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a>
instances.</p>
<p><a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> supports the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement was added.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This class does not support input files containing multiple streams (such
as those produced by the <strong class="program">pbzip2</strong> tool). When reading such an
input file, only the first stream will be accessible. If you require
support for multi-stream files, consider using the third-party
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2file</span></code> module (available from
<a class="reference external" href="https://pypi.org/project/bz2file">PyPI</a>). This module provides a
backport of Python 3.3’s <a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> class, which does support
multi-stream files.</p>
</div>
<dl class="method">
<dt id="bz2.BZ2File.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the file. Sets data attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">closed</span></code> to true. A closed file
cannot be used for further I/O operations. <a class="reference internal" href="#bz2.BZ2File.close" title="bz2.BZ2File.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> may be called
more than once without error.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at most <em>size</em> uncompressed bytes, returned as a string. If the
<em>size</em> argument is negative or omitted, read until EOF is reached.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next line from the file, as a string, retaining newline. A
non-negative <em>size</em> argument limits the maximum number of bytes to return
(an incomplete line may be returned then). Return an empty string at EOF.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.readlines">
<code class="descname">readlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of lines read. The optional <em>size</em> argument, if given, is an
approximate bound on the total number of bytes in the lines returned.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.xreadlines">
<code class="descname">xreadlines</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.xreadlines" title="Permalink to this definition">¶</a></dt>
<dd><p>For backward compatibility. <a class="reference internal" href="#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> objects now include the
performance optimizations previously implemented in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">xreadlines</span></code>
module.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>This exists only for compatibility with the method by this name on
<a class="reference internal" href="functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> objects, which is deprecated.  Use <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></code>
instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.seek">
<code class="descname">seek</code><span class="sig-paren">(</span><em>offset</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Move to new file position. Argument <em>offset</em> is a byte count. Optional
argument <em>whence</em> defaults to <code class="docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> (offset from start
of file; offset should be <code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">0</span></code>); other values are <code class="docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code> or
<code class="docutils literal notranslate"><span class="pre">1</span></code> (move relative to current position; offset can be positive or
negative), and <code class="docutils literal notranslate"><span class="pre">os.SEEK_END</span></code> or <code class="docutils literal notranslate"><span class="pre">2</span></code> (move relative to end of file;
offset is usually negative, although many platforms allow seeking beyond
the end of a file).</p>
<p>Note that seeking of bz2 files is emulated, and depending on the
parameters the operation may be extremely slow.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.tell">
<code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current file position, an integer (may be a long integer).</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write string <em>data</em> to file. Note that due to buffering, <a class="reference internal" href="#bz2.BZ2File.close" title="bz2.BZ2File.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> may
be needed before the file on disk reflects the data written.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2File.writelines">
<code class="descname">writelines</code><span class="sig-paren">(</span><em>sequence_of_strings</em><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2File.writelines" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the sequence of strings to the file. Note that newlines are not
added. The sequence can be any iterable object producing strings. This is
equivalent to calling write() for each string.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="sequential-de-compression">
<h2>12.3.2. Sequential (de)compression<a class="headerlink" href="#sequential-de-compression" title="Permalink to this headline">¶</a></h2>
<p>Sequential compression and decompression is done using the classes
<a class="reference internal" href="#bz2.BZ2Compressor" title="bz2.BZ2Compressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Compressor</span></code></a> and <a class="reference internal" href="#bz2.BZ2Decompressor" title="bz2.BZ2Decompressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Decompressor</span></code></a>.</p>
<dl class="class">
<dt id="bz2.BZ2Compressor">
<em class="property">class </em><code class="descclassname">bz2.</code><code class="descname">BZ2Compressor</code><span class="sig-paren">(</span><span class="optional">[</span><em>compresslevel</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2Compressor" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new compressor object. This object may be used to compress data
sequentially. If you want to compress data in one shot, use the
<a class="reference internal" href="#bz2.compress" title="bz2.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a> function instead. The <em>compresslevel</em> parameter, if given,
must be a number between <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">9</span></code>; the default is <code class="docutils literal notranslate"><span class="pre">9</span></code>.</p>
<dl class="method">
<dt id="bz2.BZ2Compressor.compress">
<code class="descname">compress</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2Compressor.compress" title="Permalink to this definition">¶</a></dt>
<dd><p>Provide more data to the compressor object. It will return chunks of
compressed data whenever possible. When you’ve finished providing data to
compress, call the <a class="reference internal" href="#bz2.BZ2Compressor.flush" title="bz2.BZ2Compressor.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> method to finish the compression process,
and return what is left in internal buffers.</p>
</dd></dl>

<dl class="method">
<dt id="bz2.BZ2Compressor.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2Compressor.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Finish the compression process and return what is left in internal
buffers. You must not use the compressor object after calling this method.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="bz2.BZ2Decompressor">
<em class="property">class </em><code class="descclassname">bz2.</code><code class="descname">BZ2Decompressor</code><a class="headerlink" href="#bz2.BZ2Decompressor" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new decompressor object. This object may be used to decompress data
sequentially. If you want to decompress data in one shot, use the
<a class="reference internal" href="#bz2.decompress" title="bz2.decompress"><code class="xref py py-func docutils literal notranslate"><span class="pre">decompress()</span></code></a> function instead.</p>
<dl class="method">
<dt id="bz2.BZ2Decompressor.decompress">
<code class="descname">decompress</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#bz2.BZ2Decompressor.decompress" title="Permalink to this definition">¶</a></dt>
<dd><p>Provide more data to the decompressor object. It will return chunks of
decompressed data whenever possible. If you try to decompress data after
the end of stream is found, <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> will be raised. If any data
was found after the end of stream, it’ll be ignored and saved in
<code class="xref py py-attr docutils literal notranslate"><span class="pre">unused_data</span></code> attribute.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="one-shot-de-compression">
<h2>12.3.3. One-shot (de)compression<a class="headerlink" href="#one-shot-de-compression" title="Permalink to this headline">¶</a></h2>
<p>One-shot compression and decompression is provided through the <a class="reference internal" href="#bz2.compress" title="bz2.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a>
and <a class="reference internal" href="#bz2.decompress" title="bz2.decompress"><code class="xref py py-func docutils literal notranslate"><span class="pre">decompress()</span></code></a> functions.</p>
<dl class="function">
<dt id="bz2.compress">
<code class="descclassname">bz2.</code><code class="descname">compress</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>compresslevel</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bz2.compress" title="Permalink to this definition">¶</a></dt>
<dd><p>Compress <em>data</em> in one shot. If you want to compress data sequentially, use
an instance of <a class="reference internal" href="#bz2.BZ2Compressor" title="bz2.BZ2Compressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Compressor</span></code></a> instead. The <em>compresslevel</em> parameter,
if given, must be a number between <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">9</span></code>; the default is <code class="docutils literal notranslate"><span class="pre">9</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="bz2.decompress">
<code class="descclassname">bz2.</code><code class="descname">decompress</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#bz2.decompress" title="Permalink to this definition">¶</a></dt>
<dd><p>Decompress <em>data</em> in one shot. If you want to decompress data sequentially,
use an instance of <a class="reference internal" href="#bz2.BZ2Decompressor" title="bz2.BZ2Decompressor"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2Decompressor</span></code></a> instead.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a><ul>
<li><a class="reference internal" href="#de-compression-of-files">12.3.1. (De)compression of files</a></li>
<li><a class="reference internal" href="#sequential-de-compression">12.3.2. Sequential (de)compression</a></li>
<li><a class="reference internal" href="#one-shot-de-compression">12.3.3. One-shot (de)compression</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gzip.html"
                        title="previous chapter">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="zipfile.html"
                        title="next chapter">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/bz2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zipfile.html" title="12.4. zipfile — Work with ZIP archives"
             >next</a> |</li>
        <li class="right" >
          <a href="gzip.html" title="12.2. gzip — Support for gzip files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" >12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\"�?"�"�html/library/calendar.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.2. calendar — General calendar-related functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.3. collections — High-performance container datatypes" href="collections.html" />
    <link rel="prev" title="8.1. datetime — Basic date and time types" href="datetime.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/calendar.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="collections.html" title="8.3. collections — High-performance container datatypes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="8.1. datetime — Basic date and time types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-calendar">
<span id="calendar-general-calendar-related-functions"></span><h1>8.2. <a class="reference internal" href="#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a> — General calendar-related functions<a class="headerlink" href="#module-calendar" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/calendar.py">Lib/calendar.py</a></p>
<hr class="docutils" />
<p>This module allows you to output calendars like the Unix <strong class="program">cal</strong> program,
and provides additional useful functions related to the calendar. By default,
these calendars have Monday as the first day of the week, and Sunday as the last
(the European convention). Use <a class="reference internal" href="#calendar.setfirstweekday" title="calendar.setfirstweekday"><code class="xref py py-func docutils literal notranslate"><span class="pre">setfirstweekday()</span></code></a> to set the first day of
the week to Sunday (6) or to any other weekday.  Parameters that specify dates
are given as integers. For related
functionality, see also the <a class="reference internal" href="datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> and <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> modules.</p>
<p>Most of these functions and classes rely on the <a class="reference internal" href="datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module which
uses an idealized calendar, the current Gregorian calendar indefinitely extended
in both directions.  This matches the definition of the “proleptic Gregorian”
calendar in Dershowitz and Reingold’s book “Calendrical Calculations”, where
it’s the base calendar for all computations.</p>
<dl class="class">
<dt id="calendar.Calendar">
<em class="property">class </em><code class="descclassname">calendar.</code><code class="descname">Calendar</code><span class="sig-paren">(</span><span class="optional">[</span><em>firstweekday</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a <a class="reference internal" href="#calendar.Calendar" title="calendar.Calendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">Calendar</span></code></a> object. <em>firstweekday</em> is an integer specifying the
first day of the week. <code class="docutils literal notranslate"><span class="pre">0</span></code> is Monday (the default), <code class="docutils literal notranslate"><span class="pre">6</span></code> is Sunday.</p>
<p>A <a class="reference internal" href="#calendar.Calendar" title="calendar.Calendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">Calendar</span></code></a> object provides several methods that can be used for
preparing the calendar data for formatting. This class doesn’t do any formatting
itself. This is the job of subclasses.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#calendar.Calendar" title="calendar.Calendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">Calendar</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="calendar.Calendar.iterweekdays">
<code class="descname">iterweekdays</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.iterweekdays" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator for the week day numbers that will be used for one
week.  The first value from the iterator will be the same as the value of
the <a class="reference internal" href="#calendar.firstweekday" title="calendar.firstweekday"><code class="xref py py-attr docutils literal notranslate"><span class="pre">firstweekday</span></code></a> property.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.itermonthdates">
<code class="descname">itermonthdates</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.itermonthdates" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator for the month <em>month</em> (1–12) in the year <em>year</em>. This
iterator will return all days (as <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> objects) for the
month and all days before the start of the month or after the end of the
month that are required to get a complete week.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.itermonthdays2">
<code class="descname">itermonthdays2</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.itermonthdays2" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator for the month <em>month</em> in the year <em>year</em> similar to
<a class="reference internal" href="#calendar.Calendar.itermonthdates" title="calendar.Calendar.itermonthdates"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itermonthdates()</span></code></a>. Days returned will be tuples consisting of a day
number and a week day number.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.itermonthdays">
<code class="descname">itermonthdays</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.itermonthdays" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator for the month <em>month</em> in the year <em>year</em> similar to
<a class="reference internal" href="#calendar.Calendar.itermonthdates" title="calendar.Calendar.itermonthdates"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itermonthdates()</span></code></a>. Days returned will simply be day numbers.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.monthdatescalendar">
<code class="descname">monthdatescalendar</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.monthdatescalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the weeks in the month <em>month</em> of the <em>year</em> as full
weeks.  Weeks are lists of seven <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> objects.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.monthdays2calendar">
<code class="descname">monthdays2calendar</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.monthdays2calendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the weeks in the month <em>month</em> of the <em>year</em> as full
weeks.  Weeks are lists of seven tuples of day numbers and weekday
numbers.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.monthdayscalendar">
<code class="descname">monthdayscalendar</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.monthdayscalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the weeks in the month <em>month</em> of the <em>year</em> as full
weeks.  Weeks are lists of seven day numbers.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.yeardatescalendar">
<code class="descname">yeardatescalendar</code><span class="sig-paren">(</span><em>year</em><span class="optional">[</span>, <em>width</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.yeardatescalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data for the specified year ready for formatting. The return
value is a list of month rows. Each month row contains up to <em>width</em>
months (defaulting to 3). Each month contains between 4 and 6 weeks and
each week contains 1–7 days. Days are <a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> objects.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.yeardays2calendar">
<code class="descname">yeardays2calendar</code><span class="sig-paren">(</span><em>year</em><span class="optional">[</span>, <em>width</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.yeardays2calendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data for the specified year ready for formatting (similar to
<a class="reference internal" href="#calendar.Calendar.yeardatescalendar" title="calendar.Calendar.yeardatescalendar"><code class="xref py py-meth docutils literal notranslate"><span class="pre">yeardatescalendar()</span></code></a>). Entries in the week lists are tuples of day
numbers and weekday numbers. Day numbers outside this month are zero.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.Calendar.yeardayscalendar">
<code class="descname">yeardayscalendar</code><span class="sig-paren">(</span><em>year</em><span class="optional">[</span>, <em>width</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.Calendar.yeardayscalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data for the specified year ready for formatting (similar to
<a class="reference internal" href="#calendar.Calendar.yeardatescalendar" title="calendar.Calendar.yeardatescalendar"><code class="xref py py-meth docutils literal notranslate"><span class="pre">yeardatescalendar()</span></code></a>). Entries in the week lists are day numbers. Day
numbers outside this month are zero.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="calendar.TextCalendar">
<em class="property">class </em><code class="descclassname">calendar.</code><code class="descname">TextCalendar</code><span class="sig-paren">(</span><span class="optional">[</span><em>firstweekday</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.TextCalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>This class can be used to generate plain text calendars.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#calendar.TextCalendar" title="calendar.TextCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextCalendar</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="calendar.TextCalendar.formatmonth">
<code class="descname">formatmonth</code><span class="sig-paren">(</span><em>theyear</em>, <em>themonth</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.TextCalendar.formatmonth" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a month’s calendar in a multi-line string. If <em>w</em> is provided, it
specifies the width of the date columns, which are centered. If <em>l</em> is
given, it specifies the number of lines that each week will use. Depends
on the first weekday as specified in the constructor or set by the
<a class="reference internal" href="#calendar.setfirstweekday" title="calendar.setfirstweekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setfirstweekday()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.TextCalendar.prmonth">
<code class="descname">prmonth</code><span class="sig-paren">(</span><em>theyear</em>, <em>themonth</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.TextCalendar.prmonth" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a month’s calendar as returned by <a class="reference internal" href="#calendar.TextCalendar.formatmonth" title="calendar.TextCalendar.formatmonth"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formatmonth()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.TextCalendar.formatyear">
<code class="descname">formatyear</code><span class="sig-paren">(</span><em>theyear</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">[</span>, <em>c</em><span class="optional">[</span>, <em>m</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.TextCalendar.formatyear" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <em>m</em>-column calendar for an entire year as a multi-line string.
Optional parameters <em>w</em>, <em>l</em>, and <em>c</em> are for date column width, lines per
week, and number of spaces between month columns, respectively. Depends on
the first weekday as specified in the constructor or set by the
<a class="reference internal" href="#calendar.setfirstweekday" title="calendar.setfirstweekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setfirstweekday()</span></code></a> method.  The earliest year for which a calendar
can be generated is platform-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.TextCalendar.pryear">
<code class="descname">pryear</code><span class="sig-paren">(</span><em>theyear</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">[</span>, <em>c</em><span class="optional">[</span>, <em>m</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.TextCalendar.pryear" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the calendar for an entire year as returned by <a class="reference internal" href="#calendar.TextCalendar.formatyear" title="calendar.TextCalendar.formatyear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formatyear()</span></code></a>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="calendar.HTMLCalendar">
<em class="property">class </em><code class="descclassname">calendar.</code><code class="descname">HTMLCalendar</code><span class="sig-paren">(</span><span class="optional">[</span><em>firstweekday</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.HTMLCalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>This class can be used to generate HTML calendars.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#calendar.HTMLCalendar" title="calendar.HTMLCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLCalendar</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="calendar.HTMLCalendar.formatmonth">
<code class="descname">formatmonth</code><span class="sig-paren">(</span><em>theyear</em>, <em>themonth</em><span class="optional">[</span>, <em>withyear</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.HTMLCalendar.formatmonth" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a month’s calendar as an HTML table. If <em>withyear</em> is true the year
will be included in the header, otherwise just the month name will be
used.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.HTMLCalendar.formatyear">
<code class="descname">formatyear</code><span class="sig-paren">(</span><em>theyear</em><span class="optional">[</span>, <em>width</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.HTMLCalendar.formatyear" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a year’s calendar as an HTML table. <em>width</em> (defaulting to 3)
specifies the number of months per row.</p>
</dd></dl>

<dl class="method">
<dt id="calendar.HTMLCalendar.formatyearpage">
<code class="descname">formatyearpage</code><span class="sig-paren">(</span><em>theyear</em><span class="optional">[</span>, <em>width</em><span class="optional">[</span>, <em>css</em><span class="optional">[</span>, <em>encoding</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.HTMLCalendar.formatyearpage" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a year’s calendar as a complete HTML page. <em>width</em> (defaulting to
3) specifies the number of months per row. <em>css</em> is the name for the
cascading style sheet to be used. <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> can be passed if no style
sheet should be used. <em>encoding</em> specifies the encoding to be used for the
output (defaulting to the system default encoding).</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="calendar.LocaleTextCalendar">
<em class="property">class </em><code class="descclassname">calendar.</code><code class="descname">LocaleTextCalendar</code><span class="sig-paren">(</span><span class="optional">[</span><em>firstweekday</em><span class="optional">[</span>, <em>locale</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.LocaleTextCalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>This subclass of <a class="reference internal" href="#calendar.TextCalendar" title="calendar.TextCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextCalendar</span></code></a> can be passed a locale name in the
constructor and will return month and weekday names in the specified locale.
If this locale includes an encoding all strings containing month and weekday
names will be returned as unicode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="calendar.LocaleHTMLCalendar">
<em class="property">class </em><code class="descclassname">calendar.</code><code class="descname">LocaleHTMLCalendar</code><span class="sig-paren">(</span><span class="optional">[</span><em>firstweekday</em><span class="optional">[</span>, <em>locale</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.LocaleHTMLCalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>This subclass of <a class="reference internal" href="#calendar.HTMLCalendar" title="calendar.HTMLCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLCalendar</span></code></a> can be passed a locale name in the
constructor and will return month and weekday names in the specified
locale. If this locale includes an encoding all strings containing month and
weekday names will be returned as unicode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">formatweekday()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">formatmonthname()</span></code> methods of these two
classes temporarily change the current locale to the given <em>locale</em>.  Because
the current locale is a process-wide setting, they are not thread-safe.</p>
</div>
<p>For simple text calendars this module provides the following functions.</p>
<dl class="function">
<dt id="calendar.setfirstweekday">
<code class="descclassname">calendar.</code><code class="descname">setfirstweekday</code><span class="sig-paren">(</span><em>weekday</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.setfirstweekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the weekday (<code class="docutils literal notranslate"><span class="pre">0</span></code> is Monday, <code class="docutils literal notranslate"><span class="pre">6</span></code> is Sunday) to start each week. The
values <code class="xref py py-const docutils literal notranslate"><span class="pre">MONDAY</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">TUESDAY</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">WEDNESDAY</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">THURSDAY</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">FRIDAY</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SATURDAY</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">SUNDAY</span></code> are provided for
convenience. For example, to set the first weekday to Sunday:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">calendar</span>
<span class="n">calendar</span><span class="o">.</span><span class="n">setfirstweekday</span><span class="p">(</span><span class="n">calendar</span><span class="o">.</span><span class="n">SUNDAY</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="calendar.firstweekday">
<code class="descclassname">calendar.</code><code class="descname">firstweekday</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.firstweekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current setting for the weekday to start each week.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="calendar.isleap">
<code class="descclassname">calendar.</code><code class="descname">isleap</code><span class="sig-paren">(</span><em>year</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.isleap" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>year</em> is a leap year, otherwise <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.leapdays">
<code class="descclassname">calendar.</code><code class="descname">leapdays</code><span class="sig-paren">(</span><em>y1</em>, <em>y2</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.leapdays" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of leap years in the range from <em>y1</em> to <em>y2</em> (exclusive),
where <em>y1</em> and <em>y2</em> are years.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.0: </span>This function didn’t work for ranges spanning a century change in Python
1.5.2.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="calendar.weekday">
<code class="descclassname">calendar.</code><code class="descname">weekday</code><span class="sig-paren">(</span><em>year</em>, <em>month</em>, <em>day</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.weekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the day of the week (<code class="docutils literal notranslate"><span class="pre">0</span></code> is Monday) for <em>year</em> (<code class="docutils literal notranslate"><span class="pre">1970</span></code>–…),
<em>month</em> (<code class="docutils literal notranslate"><span class="pre">1</span></code>–<code class="docutils literal notranslate"><span class="pre">12</span></code>), <em>day</em> (<code class="docutils literal notranslate"><span class="pre">1</span></code>–<code class="docutils literal notranslate"><span class="pre">31</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="calendar.weekheader">
<code class="descclassname">calendar.</code><code class="descname">weekheader</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.weekheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a header containing abbreviated weekday names. <em>n</em> specifies the width in
characters for one weekday.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.monthrange">
<code class="descclassname">calendar.</code><code class="descname">monthrange</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.monthrange" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns weekday of first day of the month and number of days in month,  for the
specified <em>year</em> and <em>month</em>.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.monthcalendar">
<code class="descclassname">calendar.</code><code class="descname">monthcalendar</code><span class="sig-paren">(</span><em>year</em>, <em>month</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.monthcalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a matrix representing a month’s calendar.  Each row represents a week;
days outside of the month a represented by zeros. Each week begins with Monday
unless set by <a class="reference internal" href="#calendar.setfirstweekday" title="calendar.setfirstweekday"><code class="xref py py-func docutils literal notranslate"><span class="pre">setfirstweekday()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.prmonth">
<code class="descclassname">calendar.</code><code class="descname">prmonth</code><span class="sig-paren">(</span><em>theyear</em>, <em>themonth</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.prmonth" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints a month’s calendar as returned by <a class="reference internal" href="#calendar.month" title="calendar.month"><code class="xref py py-func docutils literal notranslate"><span class="pre">month()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.month">
<code class="descclassname">calendar.</code><code class="descname">month</code><span class="sig-paren">(</span><em>theyear</em>, <em>themonth</em><span class="optional">[</span>, <em>w</em><span class="optional">[</span>, <em>l</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#calendar.month" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a month’s calendar in a multi-line string using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">formatmonth()</span></code>
of the <a class="reference internal" href="#calendar.TextCalendar" title="calendar.TextCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextCalendar</span></code></a> class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="calendar.prcal">
<code class="descclassname">calendar.</code><code class="descname">prcal</code><span class="sig-paren">(</span><em>year[, w[, l[c]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.prcal" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints the calendar for an entire year as returned by  <a class="reference internal" href="#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-func docutils literal notranslate"><span class="pre">calendar()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="calendar.calendar">
<code class="descclassname">calendar.</code><code class="descname">calendar</code><span class="sig-paren">(</span><em>year[, w[, l[c]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.calendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a 3-column calendar for an entire year as a multi-line string using the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">formatyear()</span></code> of the <a class="reference internal" href="#calendar.TextCalendar" title="calendar.TextCalendar"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextCalendar</span></code></a> class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="calendar.timegm">
<code class="descclassname">calendar.</code><code class="descname">timegm</code><span class="sig-paren">(</span><em>tuple</em><span class="sig-paren">)</span><a class="headerlink" href="#calendar.timegm" title="Permalink to this definition">¶</a></dt>
<dd><p>An unrelated but handy function that takes a time tuple such as returned by
the <a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> function in the <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module, and returns the
corresponding Unix timestamp value, assuming an epoch of 1970, and the POSIX
encoding.  In fact, <a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a> and <a class="reference internal" href="#calendar.timegm" title="calendar.timegm"><code class="xref py py-func docutils literal notranslate"><span class="pre">timegm()</span></code></a> are each others’
inverse.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a> module exports the following data attributes:</p>
<dl class="data">
<dt id="calendar.day_name">
<code class="descclassname">calendar.</code><code class="descname">day_name</code><a class="headerlink" href="#calendar.day_name" title="Permalink to this definition">¶</a></dt>
<dd><p>An array that represents the days of the week in the current locale.</p>
</dd></dl>

<dl class="data">
<dt id="calendar.day_abbr">
<code class="descclassname">calendar.</code><code class="descname">day_abbr</code><a class="headerlink" href="#calendar.day_abbr" title="Permalink to this definition">¶</a></dt>
<dd><p>An array that represents the abbreviated days of the week in the current locale.</p>
</dd></dl>

<dl class="data">
<dt id="calendar.month_name">
<code class="descclassname">calendar.</code><code class="descname">month_name</code><a class="headerlink" href="#calendar.month_name" title="Permalink to this definition">¶</a></dt>
<dd><p>An array that represents the months of the year in the current locale.  This
follows normal convention of January being month number 1, so it has a length of
13 and  <code class="docutils literal notranslate"><span class="pre">month_name[0]</span></code> is the empty string.</p>
</dd></dl>

<dl class="data">
<dt id="calendar.month_abbr">
<code class="descclassname">calendar.</code><code class="descname">month_abbr</code><a class="headerlink" href="#calendar.month_abbr" title="Permalink to this definition">¶</a></dt>
<dd><p>An array that represents the abbreviated months of the year in the current
locale.  This follows normal convention of January being month number 1, so it
has a length of 13 and  <code class="docutils literal notranslate"><span class="pre">month_abbr[0]</span></code> is the empty string.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a></dt>
<dd>Object-oriented interface to dates and times with similar functionality to the
<a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module.</dd>
<dt>Module <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a></dt>
<dd>Low-level time related functions.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="datetime.html"
                        title="previous chapter">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="collections.html"
                        title="next chapter">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/calendar.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="collections.html" title="8.3. collections — High-performance container datatypes"
             >next</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="8.1. datetime — Basic date and time types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��]��html/library/carbon.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.8. Mac OS Toolbox Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.9. ColorPicker — Color selection dialog" href="colorpicker.html" />
    <link rel="prev" title="37.7. autoGIL — Global Interpreter Lock handling in event loops" href="autogil.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/carbon.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="colorpicker.html" title="37.9. ColorPicker — Color selection dialog"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="autogil.html" title="37.7. autoGIL — Global Interpreter Lock handling in event loops"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="mac-os-toolbox-modules">
<span id="toolbox"></span><h1>37.8. Mac OS Toolbox Modules<a class="headerlink" href="#mac-os-toolbox-modules" title="Permalink to this headline">¶</a></h1>
<p>These are a set of modules that provide interfaces to various legacy Mac OS toolboxes.
If applicable the module will define a number of Python objects for the various
structures declared by the toolbox, and operations will be implemented as
methods of the object.  Other operations will be implemented as functions in the
module.  Not all operations possible in C will also be possible in Python
(callbacks are often a problem), and parameters will occasionally be different
in Python (input and output buffers, especially).  All methods and functions
have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> string describing their arguments and return values, and
for additional description you are referred to <a class="reference external" href="http://developer.apple.com/legacy/mac/library/#documentation/macos8/mac8.html">Inside Macintosh</a> or similar works.</p>
<p>These modules all live in a package called <code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon</span></code>. Despite that name they
are not all part of the Carbon framework: CF is really in the CoreFoundation
framework and Qt is in the QuickTime framework. The normal use pattern is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Carbon</span> <span class="k">import</span> <span class="n">AE</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Most of the OS X APIs that these modules use are deprecated or removed
in recent versions of OS X.  Many are not available when Python is
executing in 64-bit mode.  The Carbon modules have been removed in
Python 3.  You should avoid using them in Python 2.</p>
</div>
<div class="section" id="module-Carbon.AE">
<span id="carbon-ae-apple-events"></span><h2>37.8.1. <a class="reference internal" href="#module-Carbon.AE" title="Carbon.AE: Interface to the Apple Events toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.AE</span></code></a> — Apple Events<a class="headerlink" href="#module-Carbon.AE" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.AH">
<span id="carbon-ah-apple-help"></span><h2>37.8.2. <a class="reference internal" href="#module-Carbon.AH" title="Carbon.AH: Interface to the Apple Help manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.AH</span></code></a> — Apple Help<a class="headerlink" href="#module-Carbon.AH" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.App">
<span id="carbon-app-appearance-manager"></span><h2>37.8.3. <a class="reference internal" href="#module-Carbon.App" title="Carbon.App: Interface to the Appearance Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.App</span></code></a> — Appearance Manager<a class="headerlink" href="#module-Carbon.App" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Appearance">
<span id="carbon-appearance-appearance-manager-constants"></span><h2>37.8.4. <a class="reference internal" href="#module-Carbon.Appearance" title="Carbon.Appearance: Constant definitions for the interface to the Appearance Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Appearance</span></code></a> — Appearance Manager constants<a class="headerlink" href="#module-Carbon.Appearance" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.CF">
<span id="carbon-cf-core-foundation"></span><h2>37.8.5. <a class="reference internal" href="#module-Carbon.CF" title="Carbon.CF: Interface to the Core Foundation. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CF</span></code></a> — Core Foundation<a class="headerlink" href="#module-Carbon.CF" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">CFBase</span></code>, <code class="docutils literal notranslate"><span class="pre">CFArray</span></code>, <code class="docutils literal notranslate"><span class="pre">CFData</span></code>, <code class="docutils literal notranslate"><span class="pre">CFDictionary</span></code>, <code class="docutils literal notranslate"><span class="pre">CFString</span></code> and
<code class="docutils literal notranslate"><span class="pre">CFURL</span></code> objects are supported, some only partially.</p>
</div>
<div class="section" id="module-Carbon.CG">
<span id="carbon-cg-core-graphics"></span><h2>37.8.6. <a class="reference internal" href="#module-Carbon.CG" title="Carbon.CG: Interface to Core Graphics. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CG</span></code></a> — Core Graphics<a class="headerlink" href="#module-Carbon.CG" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.CarbonEvt">
<span id="carbon-carbonevt-carbon-event-manager"></span><h2>37.8.7. <a class="reference internal" href="#module-Carbon.CarbonEvt" title="Carbon.CarbonEvt: Interface to the Carbon Event Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CarbonEvt</span></code></a> — Carbon Event Manager<a class="headerlink" href="#module-Carbon.CarbonEvt" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.CarbonEvents">
<span id="carbon-carbonevents-carbon-event-manager-constants"></span><h2>37.8.8. <a class="reference internal" href="#module-Carbon.CarbonEvents" title="Carbon.CarbonEvents: Constants for the interface to the Carbon Event Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CarbonEvents</span></code></a> — Carbon Event Manager constants<a class="headerlink" href="#module-Carbon.CarbonEvents" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Cm">
<span id="carbon-cm-component-manager"></span><h2>37.8.9. <a class="reference internal" href="#module-Carbon.Cm" title="Carbon.Cm: Interface to the Component Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Cm</span></code></a> — Component Manager<a class="headerlink" href="#module-Carbon.Cm" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Components">
<span id="carbon-components-component-manager-constants"></span><h2>37.8.10. <a class="reference internal" href="#module-Carbon.Components" title="Carbon.Components: Constants for the interface to the Component Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Components</span></code></a> — Component Manager constants<a class="headerlink" href="#module-Carbon.Components" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.ControlAccessor">
<span id="carbon-controlaccessor-control-manager-accssors"></span><h2>37.8.11. <a class="reference internal" href="#module-Carbon.ControlAccessor" title="Carbon.ControlAccessor: Accessor functions for the interface to the Control Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.ControlAccessor</span></code></a> — Control Manager accssors<a class="headerlink" href="#module-Carbon.ControlAccessor" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Controls">
<span id="carbon-controls-control-manager-constants"></span><h2>37.8.12. <a class="reference internal" href="#module-Carbon.Controls" title="Carbon.Controls: Constants for the interface to the Control Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Controls</span></code></a> — Control Manager constants<a class="headerlink" href="#module-Carbon.Controls" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.CoreFounation">
<span id="carbon-corefounation-corefounation-constants"></span><h2>37.8.13. <a class="reference internal" href="#module-Carbon.CoreFounation" title="Carbon.CoreFounation: Constants for the interface to CoreFoundation. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CoreFounation</span></code></a> — CoreFounation constants<a class="headerlink" href="#module-Carbon.CoreFounation" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.CoreGraphics">
<span id="carbon-coregraphics-coregraphics-constants"></span><h2>37.8.14. <a class="reference internal" href="#module-Carbon.CoreGraphics" title="Carbon.CoreGraphics: Constants for the interface to CoreGraphics. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.CoreGraphics</span></code></a> — CoreGraphics constants<a class="headerlink" href="#module-Carbon.CoreGraphics" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Ctl">
<span id="carbon-ctl-control-manager"></span><h2>37.8.15. <a class="reference internal" href="#module-Carbon.Ctl" title="Carbon.Ctl: Interface to the Control Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Ctl</span></code></a> — Control Manager<a class="headerlink" href="#module-Carbon.Ctl" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Dialogs">
<span id="carbon-dialogs-dialog-manager-constants"></span><h2>37.8.16. <a class="reference internal" href="#module-Carbon.Dialogs" title="Carbon.Dialogs: Constants for the interface to the Dialog Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Dialogs</span></code></a> — Dialog Manager constants<a class="headerlink" href="#module-Carbon.Dialogs" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Dlg">
<span id="carbon-dlg-dialog-manager"></span><h2>37.8.17. <a class="reference internal" href="#module-Carbon.Dlg" title="Carbon.Dlg: Interface to the Dialog Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Dlg</span></code></a> — Dialog Manager<a class="headerlink" href="#module-Carbon.Dlg" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Drag">
<span id="carbon-drag-drag-and-drop-manager"></span><h2>37.8.18. <a class="reference internal" href="#module-Carbon.Drag" title="Carbon.Drag: Interface to the Drag and Drop Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Drag</span></code></a> — Drag and Drop Manager<a class="headerlink" href="#module-Carbon.Drag" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Dragconst">
<span id="carbon-dragconst-drag-and-drop-manager-constants"></span><h2>37.8.19. <a class="reference internal" href="#module-Carbon.Dragconst" title="Carbon.Dragconst: Constants for the interface to the Drag and Drop Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Dragconst</span></code></a> — Drag and Drop Manager constants<a class="headerlink" href="#module-Carbon.Dragconst" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Events">
<span id="carbon-events-event-manager-constants"></span><h2>37.8.20. <a class="reference internal" href="#module-Carbon.Events" title="Carbon.Events: Constants for the interface to the classic Event Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Events</span></code></a> — Event Manager constants<a class="headerlink" href="#module-Carbon.Events" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Evt">
<span id="carbon-evt-event-manager"></span><h2>37.8.21. <a class="reference internal" href="#module-Carbon.Evt" title="Carbon.Evt: Interface to the classic Event Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Evt</span></code></a> — Event Manager<a class="headerlink" href="#module-Carbon.Evt" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.File">
<span id="carbon-file-file-manager"></span><h2>37.8.22. <a class="reference internal" href="#module-Carbon.File" title="Carbon.File: Interface to the File Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.File</span></code></a> — File Manager<a class="headerlink" href="#module-Carbon.File" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Files">
<span id="carbon-files-file-manager-constants"></span><h2>37.8.23. <a class="reference internal" href="#module-Carbon.Files" title="Carbon.Files: Constants for the interface to the File Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Files</span></code></a> — File Manager constants<a class="headerlink" href="#module-Carbon.Files" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Fm">
<span id="carbon-fm-font-manager"></span><h2>37.8.24. <a class="reference internal" href="#module-Carbon.Fm" title="Carbon.Fm: Interface to the Font Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Fm</span></code></a> — Font Manager<a class="headerlink" href="#module-Carbon.Fm" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Folder">
<span id="carbon-folder-folder-manager"></span><h2>37.8.25. <a class="reference internal" href="#module-Carbon.Folder" title="Carbon.Folder: Interface to the Folder Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Folder</span></code></a> — Folder Manager<a class="headerlink" href="#module-Carbon.Folder" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Folders">
<span id="carbon-folders-folder-manager-constants"></span><h2>37.8.26. <a class="reference internal" href="#module-Carbon.Folders" title="Carbon.Folders: Constants for the interface to the Folder Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Folders</span></code></a> — Folder Manager constants<a class="headerlink" href="#module-Carbon.Folders" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Fonts">
<span id="carbon-fonts-font-manager-constants"></span><h2>37.8.27. <a class="reference internal" href="#module-Carbon.Fonts" title="Carbon.Fonts: Constants for the interface to the Font Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Fonts</span></code></a> — Font Manager constants<a class="headerlink" href="#module-Carbon.Fonts" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Help">
<span id="carbon-help-help-manager"></span><h2>37.8.28. <a class="reference internal" href="#module-Carbon.Help" title="Carbon.Help: Interface to the Carbon Help Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Help</span></code></a> — Help Manager<a class="headerlink" href="#module-Carbon.Help" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.IBCarbon">
<span id="carbon-ibcarbon-carbon-interfacebuilder"></span><h2>37.8.29. <a class="reference internal" href="#module-Carbon.IBCarbon" title="Carbon.IBCarbon: Interface to the Carbon InterfaceBuilder support libraries. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.IBCarbon</span></code></a> — Carbon InterfaceBuilder<a class="headerlink" href="#module-Carbon.IBCarbon" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.IBCarbonRuntime">
<span id="carbon-ibcarbonruntime-carbon-interfacebuilder-constants"></span><h2>37.8.30. <a class="reference internal" href="#module-Carbon.IBCarbonRuntime" title="Carbon.IBCarbonRuntime: Constants for the interface to the Carbon InterfaceBuilder support libraries. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.IBCarbonRuntime</span></code></a> — Carbon InterfaceBuilder constants<a class="headerlink" href="#module-Carbon.IBCarbonRuntime" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Icns">
<span id="carbon-icn-carbon-icon-manager"></span><h2>37.8.31. <code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Icn</span></code> — Carbon Icon Manager<a class="headerlink" href="#module-Carbon.Icns" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Icons">
<span id="carbon-icons-carbon-icon-manager-constants"></span><h2>37.8.32. <a class="reference internal" href="#module-Carbon.Icons" title="Carbon.Icons: Constants for the interface to the Carbon Icon Manager (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Icons</span></code></a> — Carbon Icon Manager constants<a class="headerlink" href="#module-Carbon.Icons" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Launch">
<span id="carbon-launch-carbon-launch-services"></span><h2>37.8.33. <a class="reference internal" href="#module-Carbon.Launch" title="Carbon.Launch: Interface to the Carbon Launch Services. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Launch</span></code></a> — Carbon Launch Services<a class="headerlink" href="#module-Carbon.Launch" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.LaunchServices">
<span id="carbon-launchservices-carbon-launch-services-constants"></span><h2>37.8.34. <a class="reference internal" href="#module-Carbon.LaunchServices" title="Carbon.LaunchServices: Constants for the interface to the Carbon Launch Services. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.LaunchServices</span></code></a> — Carbon Launch Services constants<a class="headerlink" href="#module-Carbon.LaunchServices" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.List">
<span id="carbon-list-list-manager"></span><h2>37.8.35. <a class="reference internal" href="#module-Carbon.List" title="Carbon.List: Interface to the List Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.List</span></code></a> — List Manager<a class="headerlink" href="#module-Carbon.List" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Lists">
<span id="carbon-lists-list-manager-constants"></span><h2>37.8.36. <a class="reference internal" href="#module-Carbon.Lists" title="Carbon.Lists: Constants for the interface to the List Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Lists</span></code></a> — List Manager constants<a class="headerlink" href="#module-Carbon.Lists" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.MacHelp">
<span id="carbon-machelp-help-manager-constants"></span><h2>37.8.37. <a class="reference internal" href="#module-Carbon.MacHelp" title="Carbon.MacHelp: Constants for the interface to the Carbon Help Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.MacHelp</span></code></a> — Help Manager constants<a class="headerlink" href="#module-Carbon.MacHelp" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.MediaDescr">
<span id="carbon-mediadescr-parsers-and-generators-for-quicktime-media-descriptors"></span><h2>37.8.38. <a class="reference internal" href="#module-Carbon.MediaDescr" title="Carbon.MediaDescr: Parsers and generators for Quicktime Media descriptors (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.MediaDescr</span></code></a> — Parsers and generators for Quicktime Media descriptors<a class="headerlink" href="#module-Carbon.MediaDescr" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Menu">
<span id="carbon-menu-menu-manager"></span><h2>37.8.39. <a class="reference internal" href="#module-Carbon.Menu" title="Carbon.Menu: Interface to the Menu Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Menu</span></code></a> — Menu Manager<a class="headerlink" href="#module-Carbon.Menu" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Menus">
<span id="carbon-menus-menu-manager-constants"></span><h2>37.8.40. <a class="reference internal" href="#module-Carbon.Menus" title="Carbon.Menus: Constants for the interface to the Menu Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Menus</span></code></a> — Menu Manager constants<a class="headerlink" href="#module-Carbon.Menus" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Mlte">
<span id="carbon-mlte-multilingual-text-editor"></span><h2>37.8.41. <a class="reference internal" href="#module-Carbon.Mlte" title="Carbon.Mlte: Interface to the MultiLingual Text Editor. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Mlte</span></code></a> — MultiLingual Text Editor<a class="headerlink" href="#module-Carbon.Mlte" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.OSA">
<span id="carbon-osa-carbon-osa-interface"></span><h2>37.8.42. <a class="reference internal" href="#module-Carbon.OSA" title="Carbon.OSA: Interface to the Carbon OSA Library. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.OSA</span></code></a> — Carbon OSA Interface<a class="headerlink" href="#module-Carbon.OSA" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.OSAconst">
<span id="carbon-osaconst-carbon-osa-interface-constants"></span><h2>37.8.43. <a class="reference internal" href="#module-Carbon.OSAconst" title="Carbon.OSAconst: Constants for the interface to the Carbon OSA Library. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.OSAconst</span></code></a> — Carbon OSA Interface constants<a class="headerlink" href="#module-Carbon.OSAconst" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.QDOffscreen">
<span id="carbon-qdoffscreen-quickdraw-offscreen-constants"></span><h2>37.8.44. <a class="reference internal" href="#module-Carbon.QDOffscreen" title="Carbon.QDOffscreen: Constants for the interface to the QuickDraw Offscreen APIs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.QDOffscreen</span></code></a> — QuickDraw Offscreen constants<a class="headerlink" href="#module-Carbon.QDOffscreen" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Qd">
<span id="carbon-qd-quickdraw"></span><h2>37.8.45. <a class="reference internal" href="#module-Carbon.Qd" title="Carbon.Qd: Interface to the QuickDraw toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Qd</span></code></a> — QuickDraw<a class="headerlink" href="#module-Carbon.Qd" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Qdoffs">
<span id="carbon-qdoffs-quickdraw-offscreen"></span><h2>37.8.46. <a class="reference internal" href="#module-Carbon.Qdoffs" title="Carbon.Qdoffs: Interface to the QuickDraw Offscreen APIs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Qdoffs</span></code></a> — QuickDraw Offscreen<a class="headerlink" href="#module-Carbon.Qdoffs" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Qt">
<span id="carbon-qt-quicktime"></span><h2>37.8.47. <a class="reference internal" href="#module-Carbon.Qt" title="Carbon.Qt: Interface to the QuickTime toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Qt</span></code></a> — QuickTime<a class="headerlink" href="#module-Carbon.Qt" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.QuickDraw">
<span id="carbon-quickdraw-quickdraw-constants"></span><h2>37.8.48. <a class="reference internal" href="#module-Carbon.QuickDraw" title="Carbon.QuickDraw: Constants for the interface to the QuickDraw toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.QuickDraw</span></code></a> — QuickDraw constants<a class="headerlink" href="#module-Carbon.QuickDraw" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.QuickTime">
<span id="carbon-quicktime-quicktime-constants"></span><h2>37.8.49. <a class="reference internal" href="#module-Carbon.QuickTime" title="Carbon.QuickTime: Constants for the interface to the QuickTime toolbox. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.QuickTime</span></code></a> — QuickTime constants<a class="headerlink" href="#module-Carbon.QuickTime" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Res">
<span id="carbon-res-resource-manager-and-handles"></span><h2>37.8.50. <a class="reference internal" href="#module-Carbon.Res" title="Carbon.Res: Interface to the Resource Manager and Handles. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Res</span></code></a> — Resource Manager and Handles<a class="headerlink" href="#module-Carbon.Res" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Resources">
<span id="carbon-resources-resource-manager-and-handles-constants"></span><h2>37.8.51. <a class="reference internal" href="#module-Carbon.Resources" title="Carbon.Resources: Constants for the interface to the Resource Manager and Handles. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Resources</span></code></a> — Resource Manager and Handles constants<a class="headerlink" href="#module-Carbon.Resources" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Scrap">
<span id="carbon-scrap-scrap-manager"></span><h2>37.8.52. <a class="reference internal" href="#module-Carbon.Scrap" title="Carbon.Scrap: The Scrap Manager provides basic services for implementing cut &amp; paste and clipboard operations. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Scrap</span></code></a> — Scrap Manager<a class="headerlink" href="#module-Carbon.Scrap" title="Permalink to this headline">¶</a></h2>
<p>This module is only fully available on Mac OS 9 and earlier under classic PPC
MacPython.  Very limited functionality is available under Carbon MacPython.</p>
<p id="index-0">The Scrap Manager supports the simplest form of cut &amp; paste operations on the
Macintosh.  It can be use for both inter- and intra-application clipboard
operations.</p>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">Scrap</span></code> module provides low-level access to the functions of the Scrap
Manager.  It contains the following functions:</p>
<dl class="function">
<dt id="Carbon.Scrap.InfoScrap">
<code class="descclassname">Carbon.Scrap.</code><code class="descname">InfoScrap</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Carbon.Scrap.InfoScrap" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current information about the scrap.  The information is encoded as a
tuple containing the fields <code class="docutils literal notranslate"><span class="pre">(size,</span> <span class="pre">handle,</span> <span class="pre">count,</span> <span class="pre">state,</span> <span class="pre">path)</span></code>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="82%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>size</em></td>
<td>Size of the scrap in bytes.</td>
</tr>
<tr class="row-odd"><td><em>handle</em></td>
<td>Resource object representing the scrap.</td>
</tr>
<tr class="row-even"><td><em>count</em></td>
<td>Serial number of the scrap contents.</td>
</tr>
<tr class="row-odd"><td><em>state</em></td>
<td>Integer; positive if in memory, <code class="docutils literal notranslate"><span class="pre">0</span></code> if on
disk, negative if uninitialized.</td>
</tr>
<tr class="row-even"><td><em>path</em></td>
<td>Filename of the scrap when stored on disk.</td>
</tr>
</tbody>
</table>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://developer.apple.com/legacy/mac/library/documentation/mac/MoreToolbox/MoreToolbox-109.html">Scrap Manager</a></dt>
<dd>Apple’s documentation for the Scrap Manager gives a lot of useful information
about using the Scrap Manager in applications.</dd>
</dl>
</div>
</div>
<div class="section" id="module-Carbon.Snd">
<span id="carbon-snd-sound-manager"></span><h2>37.8.53. <a class="reference internal" href="#module-Carbon.Snd" title="Carbon.Snd: Interface to the Sound Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Snd</span></code></a> — Sound Manager<a class="headerlink" href="#module-Carbon.Snd" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Sound">
<span id="carbon-sound-sound-manager-constants"></span><h2>37.8.54. <a class="reference internal" href="#module-Carbon.Sound" title="Carbon.Sound: Constants for the interface to the Sound Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Sound</span></code></a> — Sound Manager constants<a class="headerlink" href="#module-Carbon.Sound" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.TE">
<span id="carbon-te-textedit"></span><h2>37.8.55. <a class="reference internal" href="#module-Carbon.TE" title="Carbon.TE: Interface to TextEdit. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.TE</span></code></a> — TextEdit<a class="headerlink" href="#module-Carbon.TE" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.TextEdit">
<span id="carbon-textedit-textedit-constants"></span><h2>37.8.56. <a class="reference internal" href="#module-Carbon.TextEdit" title="Carbon.TextEdit: Constants for the interface to TextEdit. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.TextEdit</span></code></a> — TextEdit constants<a class="headerlink" href="#module-Carbon.TextEdit" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Win">
<span id="carbon-win-window-manager"></span><h2>37.8.57. <a class="reference internal" href="#module-Carbon.Win" title="Carbon.Win: Interface to the Window Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Win</span></code></a> — Window Manager<a class="headerlink" href="#module-Carbon.Win" title="Permalink to this headline">¶</a></h2>
</div>
<div class="section" id="module-Carbon.Windows">
<span id="carbon-windows-window-manager-constants"></span><h2>37.8.58. <a class="reference internal" href="#module-Carbon.Windows" title="Carbon.Windows: Constants for the interface to the Window Manager. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon.Windows</span></code></a> — Window Manager constants<a class="headerlink" href="#module-Carbon.Windows" title="Permalink to this headline">¶</a></h2>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">37.8. Mac OS Toolbox Modules</a><ul>
<li><a class="reference internal" href="#module-Carbon.AE">37.8.1. <code class="docutils literal notranslate"><span class="pre">Carbon.AE</span></code> — Apple Events</a></li>
<li><a class="reference internal" href="#module-Carbon.AH">37.8.2. <code class="docutils literal notranslate"><span class="pre">Carbon.AH</span></code> — Apple Help</a></li>
<li><a class="reference internal" href="#module-Carbon.App">37.8.3. <code class="docutils literal notranslate"><span class="pre">Carbon.App</span></code> — Appearance Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Appearance">37.8.4. <code class="docutils literal notranslate"><span class="pre">Carbon.Appearance</span></code> — Appearance Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.CF">37.8.5. <code class="docutils literal notranslate"><span class="pre">Carbon.CF</span></code> — Core Foundation</a></li>
<li><a class="reference internal" href="#module-Carbon.CG">37.8.6. <code class="docutils literal notranslate"><span class="pre">Carbon.CG</span></code> — Core Graphics</a></li>
<li><a class="reference internal" href="#module-Carbon.CarbonEvt">37.8.7. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvt</span></code> — Carbon Event Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.CarbonEvents">37.8.8. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvents</span></code> — Carbon Event Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Cm">37.8.9. <code class="docutils literal notranslate"><span class="pre">Carbon.Cm</span></code> — Component Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Components">37.8.10. <code class="docutils literal notranslate"><span class="pre">Carbon.Components</span></code> — Component Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.ControlAccessor">37.8.11. <code class="docutils literal notranslate"><span class="pre">Carbon.ControlAccessor</span></code> — Control Manager accssors</a></li>
<li><a class="reference internal" href="#module-Carbon.Controls">37.8.12. <code class="docutils literal notranslate"><span class="pre">Carbon.Controls</span></code> — Control Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.CoreFounation">37.8.13. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreFounation</span></code> — CoreFounation constants</a></li>
<li><a class="reference internal" href="#module-Carbon.CoreGraphics">37.8.14. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreGraphics</span></code> — CoreGraphics constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Ctl">37.8.15. <code class="docutils literal notranslate"><span class="pre">Carbon.Ctl</span></code> — Control Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Dialogs">37.8.16. <code class="docutils literal notranslate"><span class="pre">Carbon.Dialogs</span></code> — Dialog Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Dlg">37.8.17. <code class="docutils literal notranslate"><span class="pre">Carbon.Dlg</span></code> — Dialog Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Drag">37.8.18. <code class="docutils literal notranslate"><span class="pre">Carbon.Drag</span></code> — Drag and Drop Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Dragconst">37.8.19. <code class="docutils literal notranslate"><span class="pre">Carbon.Dragconst</span></code> — Drag and Drop Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Events">37.8.20. <code class="docutils literal notranslate"><span class="pre">Carbon.Events</span></code> — Event Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Evt">37.8.21. <code class="docutils literal notranslate"><span class="pre">Carbon.Evt</span></code> — Event Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.File">37.8.22. <code class="docutils literal notranslate"><span class="pre">Carbon.File</span></code> — File Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Files">37.8.23. <code class="docutils literal notranslate"><span class="pre">Carbon.Files</span></code> — File Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Fm">37.8.24. <code class="docutils literal notranslate"><span class="pre">Carbon.Fm</span></code> — Font Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Folder">37.8.25. <code class="docutils literal notranslate"><span class="pre">Carbon.Folder</span></code> — Folder Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Folders">37.8.26. <code class="docutils literal notranslate"><span class="pre">Carbon.Folders</span></code> — Folder Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Fonts">37.8.27. <code class="docutils literal notranslate"><span class="pre">Carbon.Fonts</span></code> — Font Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Help">37.8.28. <code class="docutils literal notranslate"><span class="pre">Carbon.Help</span></code> — Help Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.IBCarbon">37.8.29. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbon</span></code> — Carbon InterfaceBuilder</a></li>
<li><a class="reference internal" href="#module-Carbon.IBCarbonRuntime">37.8.30. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbonRuntime</span></code> — Carbon InterfaceBuilder constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Icns">37.8.31. <code class="docutils literal notranslate"><span class="pre">Carbon.Icn</span></code> — Carbon Icon Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Icons">37.8.32. <code class="docutils literal notranslate"><span class="pre">Carbon.Icons</span></code> — Carbon Icon Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Launch">37.8.33. <code class="docutils literal notranslate"><span class="pre">Carbon.Launch</span></code> — Carbon Launch Services</a></li>
<li><a class="reference internal" href="#module-Carbon.LaunchServices">37.8.34. <code class="docutils literal notranslate"><span class="pre">Carbon.LaunchServices</span></code> — Carbon Launch Services constants</a></li>
<li><a class="reference internal" href="#module-Carbon.List">37.8.35. <code class="docutils literal notranslate"><span class="pre">Carbon.List</span></code> — List Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Lists">37.8.36. <code class="docutils literal notranslate"><span class="pre">Carbon.Lists</span></code> — List Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.MacHelp">37.8.37. <code class="docutils literal notranslate"><span class="pre">Carbon.MacHelp</span></code> — Help Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.MediaDescr">37.8.38. <code class="docutils literal notranslate"><span class="pre">Carbon.MediaDescr</span></code> — Parsers and generators for Quicktime Media descriptors</a></li>
<li><a class="reference internal" href="#module-Carbon.Menu">37.8.39. <code class="docutils literal notranslate"><span class="pre">Carbon.Menu</span></code> — Menu Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Menus">37.8.40. <code class="docutils literal notranslate"><span class="pre">Carbon.Menus</span></code> — Menu Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Mlte">37.8.41. <code class="docutils literal notranslate"><span class="pre">Carbon.Mlte</span></code> — MultiLingual Text Editor</a></li>
<li><a class="reference internal" href="#module-Carbon.OSA">37.8.42. <code class="docutils literal notranslate"><span class="pre">Carbon.OSA</span></code> — Carbon OSA Interface</a></li>
<li><a class="reference internal" href="#module-Carbon.OSAconst">37.8.43. <code class="docutils literal notranslate"><span class="pre">Carbon.OSAconst</span></code> — Carbon OSA Interface constants</a></li>
<li><a class="reference internal" href="#module-Carbon.QDOffscreen">37.8.44. <code class="docutils literal notranslate"><span class="pre">Carbon.QDOffscreen</span></code> — QuickDraw Offscreen constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Qd">37.8.45. <code class="docutils literal notranslate"><span class="pre">Carbon.Qd</span></code> — QuickDraw</a></li>
<li><a class="reference internal" href="#module-Carbon.Qdoffs">37.8.46. <code class="docutils literal notranslate"><span class="pre">Carbon.Qdoffs</span></code> — QuickDraw Offscreen</a></li>
<li><a class="reference internal" href="#module-Carbon.Qt">37.8.47. <code class="docutils literal notranslate"><span class="pre">Carbon.Qt</span></code> — QuickTime</a></li>
<li><a class="reference internal" href="#module-Carbon.QuickDraw">37.8.48. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickDraw</span></code> — QuickDraw constants</a></li>
<li><a class="reference internal" href="#module-Carbon.QuickTime">37.8.49. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickTime</span></code> — QuickTime constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Res">37.8.50. <code class="docutils literal notranslate"><span class="pre">Carbon.Res</span></code> — Resource Manager and Handles</a></li>
<li><a class="reference internal" href="#module-Carbon.Resources">37.8.51. <code class="docutils literal notranslate"><span class="pre">Carbon.Resources</span></code> — Resource Manager and Handles constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Scrap">37.8.52. <code class="docutils literal notranslate"><span class="pre">Carbon.Scrap</span></code> — Scrap Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Snd">37.8.53. <code class="docutils literal notranslate"><span class="pre">Carbon.Snd</span></code> — Sound Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Sound">37.8.54. <code class="docutils literal notranslate"><span class="pre">Carbon.Sound</span></code> — Sound Manager constants</a></li>
<li><a class="reference internal" href="#module-Carbon.TE">37.8.55. <code class="docutils literal notranslate"><span class="pre">Carbon.TE</span></code> — TextEdit</a></li>
<li><a class="reference internal" href="#module-Carbon.TextEdit">37.8.56. <code class="docutils literal notranslate"><span class="pre">Carbon.TextEdit</span></code> — TextEdit constants</a></li>
<li><a class="reference internal" href="#module-Carbon.Win">37.8.57. <code class="docutils literal notranslate"><span class="pre">Carbon.Win</span></code> — Window Manager</a></li>
<li><a class="reference internal" href="#module-Carbon.Windows">37.8.58. <code class="docutils literal notranslate"><span class="pre">Carbon.Windows</span></code> — Window Manager constants</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="autogil.html"
                        title="previous chapter">37.7. <code class="docutils literal notranslate"><span class="pre">autoGIL</span></code> — Global Interpreter Lock handling in event loops</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="colorpicker.html"
                        title="next chapter">37.9. <code class="docutils literal notranslate"><span class="pre">ColorPicker</span></code> — Color selection dialog</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/carbon.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="colorpicker.html" title="37.9. ColorPicker — Color selection dialog"
             >next</a> |</li>
        <li class="right" >
          <a href="autogil.html" title="37.7. autoGIL — Global Interpreter Lock handling in event loops"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���QuQuhtml/library/cd.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.3. cd — CD-ROM access on SGI systems &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.4. fl — FORMS library for graphical user interfaces" href="fl.html" />
    <link rel="prev" title="39.1. al — Audio functions on the SGI" href="al.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cd.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fl.html" title="39.4. fl — FORMS library for graphical user interfaces"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="al.html" title="39.1. al — Audio functions on the SGI"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cd">
<span id="cd-cd-rom-access-on-sgi-systems"></span><h1>39.3. <a class="reference internal" href="#module-cd" title="cd: Interface to the CD-ROM on Silicon Graphics systems. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code></a> — CD-ROM access on SGI systems<a class="headerlink" href="#module-cd" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-cd" title="cd: Interface to the CD-ROM on Silicon Graphics systems. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module provides an interface to the Silicon Graphics CD library. It is
available only on Silicon Graphics systems.</p>
<p>The way the library works is as follows.  A program opens the CD-ROM device with
<a class="reference internal" href="#cd.open" title="cd.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> and creates a parser to parse the data from the CD with
<a class="reference internal" href="#cd.createparser" title="cd.createparser"><code class="xref py py-func docutils literal notranslate"><span class="pre">createparser()</span></code></a>.  The object returned by <a class="reference internal" href="#cd.open" title="cd.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> can be used to read
data from the CD, but also to get status information for the CD-ROM device, and
to get information about the CD, such as the table of contents.  Data from the
CD is passed to the parser, which parses the frames, and calls any callback
functions that have previously been added.</p>
<p>An audio CD is divided into <em class="dfn">tracks</em> or <em class="dfn">programs</em> (the terms are used
interchangeably).  Tracks can be subdivided into <em class="dfn">indices</em>.  An audio CD
contains a <em class="dfn">table of contents</em> which gives the starts of the tracks on the
CD.  Index 0 is usually the pause before the start of a track.  The start of the
track as given by the table of contents is normally the start of index 1.</p>
<p>Positions on a CD can be represented in two ways.  Either a frame number or a
tuple of three values, minutes, seconds and frames.  Most functions use the
latter representation.  Positions can be both relative to the beginning of the
CD, and to the beginning of the track.</p>
<p>Module <a class="reference internal" href="#module-cd" title="cd: Interface to the CD-ROM on Silicon Graphics systems. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code></a> defines the following functions and constants:</p>
<dl class="function">
<dt id="cd.createparser">
<code class="descclassname">cd.</code><code class="descname">createparser</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cd.createparser" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return an opaque parser object.  The methods of the parser object are
described below.</p>
</dd></dl>

<dl class="function">
<dt id="cd.msftoframe">
<code class="descclassname">cd.</code><code class="descname">msftoframe</code><span class="sig-paren">(</span><em>minutes</em>, <em>seconds</em>, <em>frames</em><span class="sig-paren">)</span><a class="headerlink" href="#cd.msftoframe" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts a <code class="docutils literal notranslate"><span class="pre">(minutes,</span> <span class="pre">seconds,</span> <span class="pre">frames)</span></code> triple representing time in absolute
time code into the corresponding CD frame number.</p>
</dd></dl>

<dl class="function">
<dt id="cd.open">
<code class="descclassname">cd.</code><code class="descname">open</code><span class="sig-paren">(</span><span class="optional">[</span><em>device</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cd.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the CD-ROM device.  The return value is an opaque player object; methods of
the player object are described below.  The device is the name of the SCSI
device file, e.g. <code class="docutils literal notranslate"><span class="pre">'/dev/scsi/sc0d4l0'</span></code>, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>,
the hardware inventory is consulted to locate a CD-ROM drive.  The <em>mode</em>, if
not omitted, should be the string <code class="docutils literal notranslate"><span class="pre">'r'</span></code>.</p>
</dd></dl>

<p>The module defines the following variables:</p>
<dl class="exception">
<dt id="cd.error">
<em class="property">exception </em><code class="descclassname">cd.</code><code class="descname">error</code><a class="headerlink" href="#cd.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on various errors.</p>
</dd></dl>

<dl class="data">
<dt id="cd.DATASIZE">
<code class="descclassname">cd.</code><code class="descname">DATASIZE</code><a class="headerlink" href="#cd.DATASIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of one frame’s worth of audio data.  This is the size of the audio data
as passed to the callback of type <code class="docutils literal notranslate"><span class="pre">audio</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="cd.BLOCKSIZE">
<code class="descclassname">cd.</code><code class="descname">BLOCKSIZE</code><a class="headerlink" href="#cd.BLOCKSIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of one uninterpreted frame of audio data.</p>
</dd></dl>

<p>The following variables are states as returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">getstatus()</span></code>:</p>
<dl class="data">
<dt id="cd.READY">
<code class="descclassname">cd.</code><code class="descname">READY</code><a class="headerlink" href="#cd.READY" title="Permalink to this definition">¶</a></dt>
<dd><p>The drive is ready for operation loaded with an audio CD.</p>
</dd></dl>

<dl class="data">
<dt id="cd.NODISC">
<code class="descclassname">cd.</code><code class="descname">NODISC</code><a class="headerlink" href="#cd.NODISC" title="Permalink to this definition">¶</a></dt>
<dd><p>The drive does not have a CD loaded.</p>
</dd></dl>

<dl class="data">
<dt id="cd.CDROM">
<code class="descclassname">cd.</code><code class="descname">CDROM</code><a class="headerlink" href="#cd.CDROM" title="Permalink to this definition">¶</a></dt>
<dd><p>The drive is loaded with a CD-ROM.  Subsequent play or read operations will
return I/O errors.</p>
</dd></dl>

<dl class="data">
<dt id="cd.ERROR">
<code class="descclassname">cd.</code><code class="descname">ERROR</code><a class="headerlink" href="#cd.ERROR" title="Permalink to this definition">¶</a></dt>
<dd><p>An error occurred while trying to read the disc or its table of contents.</p>
</dd></dl>

<dl class="data">
<dt id="cd.PLAYING">
<code class="descclassname">cd.</code><code class="descname">PLAYING</code><a class="headerlink" href="#cd.PLAYING" title="Permalink to this definition">¶</a></dt>
<dd><p>The drive is in CD player mode playing an audio CD through its audio jacks.</p>
</dd></dl>

<dl class="data">
<dt id="cd.PAUSED">
<code class="descclassname">cd.</code><code class="descname">PAUSED</code><a class="headerlink" href="#cd.PAUSED" title="Permalink to this definition">¶</a></dt>
<dd><p>The drive is in CD layer mode with play paused.</p>
</dd></dl>

<dl class="data">
<dt id="cd.STILL">
<code class="descclassname">cd.</code><code class="descname">STILL</code><a class="headerlink" href="#cd.STILL" title="Permalink to this definition">¶</a></dt>
<dd><p>The equivalent of <a class="reference internal" href="#cd.PAUSED" title="cd.PAUSED"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAUSED</span></code></a> on older (non 3301) model Toshiba CD-ROM
drives.  Such drives have never been shipped by SGI.</p>
</dd></dl>

<dl class="data">
<dt id="cd.audio">
<code class="descclassname">cd.</code><code class="descname">audio</code><a class="headerlink" href="#cd.audio" title="Permalink to this definition">¶</a></dt>
<dt id="cd.pnum">
<code class="descclassname">cd.</code><code class="descname">pnum</code><a class="headerlink" href="#cd.pnum" title="Permalink to this definition">¶</a></dt>
<dt id="cd.index">
<code class="descclassname">cd.</code><code class="descname">index</code><a class="headerlink" href="#cd.index" title="Permalink to this definition">¶</a></dt>
<dt id="cd.ptime">
<code class="descclassname">cd.</code><code class="descname">ptime</code><a class="headerlink" href="#cd.ptime" title="Permalink to this definition">¶</a></dt>
<dt id="cd.atime">
<code class="descclassname">cd.</code><code class="descname">atime</code><a class="headerlink" href="#cd.atime" title="Permalink to this definition">¶</a></dt>
<dt id="cd.catalog">
<code class="descclassname">cd.</code><code class="descname">catalog</code><a class="headerlink" href="#cd.catalog" title="Permalink to this definition">¶</a></dt>
<dt id="cd.ident">
<code class="descclassname">cd.</code><code class="descname">ident</code><a class="headerlink" href="#cd.ident" title="Permalink to this definition">¶</a></dt>
<dt id="cd.control">
<code class="descclassname">cd.</code><code class="descname">control</code><a class="headerlink" href="#cd.control" title="Permalink to this definition">¶</a></dt>
<dd><p>Integer constants describing the various types of parser callbacks that can be
set by the <code class="xref py py-meth docutils literal notranslate"><span class="pre">addcallback()</span></code> method of CD parser objects (see below).</p>
</dd></dl>

<div class="section" id="player-objects">
<span id="id1"></span><h2>39.3.1. Player Objects<a class="headerlink" href="#player-objects" title="Permalink to this headline">¶</a></h2>
<p>Player objects (returned by <a class="reference internal" href="#cd.open" title="cd.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>) have the following methods:</p>
<dl class="method">
<dt>
<code class="descname">CD player.allowremoval()</code></dt>
<dd><p>Unlocks the eject button on the CD-ROM drive permitting the user to eject the
caddy if desired.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.bestreadsize()</code></dt>
<dd><p>Returns the best value to use for the <em>num_frames</em> parameter of the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">readda()</span></code> method.  Best is defined as the value that permits a continuous
flow of data from the CD-ROM drive.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.close()</code></dt>
<dd><p>Frees the resources associated with the player object.  After calling
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>, the methods of the object should no longer be used.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.eject()</code></dt>
<dd><p>Ejects the caddy from the CD-ROM drive.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.getstatus()</code></dt>
<dd><p>Returns information pertaining to the current state of the CD-ROM drive.  The
returned information is a tuple with the following values: <em>state</em>, <em>track</em>,
<em>rtime</em>, <em>atime</em>, <em>ttime</em>, <em>first</em>, <em>last</em>, <em>scsi_audio</em>, <em>cur_block</em>. <em>rtime</em>
is the time relative to the start of the current track; <em>atime</em> is the time
relative to the beginning of the disc; <em>ttime</em> is the total time on the disc.
For more information on the meaning of the values, see the man page
<em class="manpage">CDgetstatus(3dm)</em>. The value of <em>state</em> is one of the following:
<a class="reference internal" href="#cd.ERROR" title="cd.ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code></a>, <a class="reference internal" href="#cd.NODISC" title="cd.NODISC"><code class="xref py py-const docutils literal notranslate"><span class="pre">NODISC</span></code></a>, <a class="reference internal" href="#cd.READY" title="cd.READY"><code class="xref py py-const docutils literal notranslate"><span class="pre">READY</span></code></a>, <a class="reference internal" href="#cd.PLAYING" title="cd.PLAYING"><code class="xref py py-const docutils literal notranslate"><span class="pre">PLAYING</span></code></a>,
<a class="reference internal" href="#cd.PAUSED" title="cd.PAUSED"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAUSED</span></code></a>, <a class="reference internal" href="#cd.STILL" title="cd.STILL"><code class="xref py py-const docutils literal notranslate"><span class="pre">STILL</span></code></a>, or <a class="reference internal" href="#cd.CDROM" title="cd.CDROM"><code class="xref py py-const docutils literal notranslate"><span class="pre">CDROM</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.gettrackinfo(track)</code></dt>
<dd><p>Returns information about the specified track.  The returned information is a
tuple consisting of two elements, the start time of the track and the duration
of the track.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.msftoblock(min, sec, frame)</code></dt>
<dd><p>Converts a minutes, seconds, frames triple representing a time in absolute time
code into the corresponding logical block number for the given CD-ROM drive.
You should use <a class="reference internal" href="#cd.msftoframe" title="cd.msftoframe"><code class="xref py py-func docutils literal notranslate"><span class="pre">msftoframe()</span></code></a> rather than <code class="xref py py-meth docutils literal notranslate"><span class="pre">msftoblock()</span></code> for comparing
times.  The logical block number differs from the frame number by an offset
required by certain CD-ROM drives.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.play(start, play)</code></dt>
<dd><p>Starts playback of an audio CD in the CD-ROM drive at the specified track.  The
audio output appears on the CD-ROM drive’s headphone and audio jacks (if
fitted).  Play stops at the end of the disc. <em>start</em> is the number of the track
at which to start playing the CD; if <em>play</em> is 0, the CD will be set to an
initial paused state.  The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">togglepause()</span></code> can then be used to
commence play.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.playabs(minutes, seconds, frames, play)</code></dt>
<dd><p>Like <code class="xref py py-meth docutils literal notranslate"><span class="pre">play()</span></code>, except that the start is given in minutes, seconds, and
frames instead of a track number.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.playtrack(start, play)</code></dt>
<dd><p>Like <code class="xref py py-meth docutils literal notranslate"><span class="pre">play()</span></code>, except that playing stops at the end of the track.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.playtrackabs(track, minutes, seconds, frames, play)</code></dt>
<dd><p>Like <code class="xref py py-meth docutils literal notranslate"><span class="pre">play()</span></code>, except that playing begins at the specified absolute time and
ends at the end of the specified track.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.preventremoval()</code></dt>
<dd><p>Locks the eject button on the CD-ROM drive thus preventing the user from
arbitrarily ejecting the caddy.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.readda(num_frames)</code></dt>
<dd><p>Reads the specified number of frames from an audio CD mounted in the CD-ROM
drive.  The return value is a string representing the audio frames.  This string
can be passed unaltered to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">parseframe()</span></code> method of the parser object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.seek(minutes, seconds, frames)</code></dt>
<dd><p>Sets the pointer that indicates the starting point of the next read of digital
audio data from a CD-ROM.  The pointer is set to an absolute time code location
specified in <em>minutes</em>, <em>seconds</em>, and <em>frames</em>.  The return value is the
logical block number to which the pointer has been set.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.seekblock(block)</code></dt>
<dd><p>Sets the pointer that indicates the starting point of the next read of digital
audio data from a CD-ROM.  The pointer is set to the specified logical block
number.  The return value is the logical block number to which the pointer has
been set.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.seektrack(track)</code></dt>
<dd><p>Sets the pointer that indicates the starting point of the next read of digital
audio data from a CD-ROM.  The pointer is set to the specified track.  The
return value is the logical block number to which the pointer has been set.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.stop()</code></dt>
<dd><p>Stops the current playing operation.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD player.togglepause()</code></dt>
<dd><p>Pauses the CD if it is playing, and makes it play if it is paused.</p>
</dd></dl>

</div>
<div class="section" id="parser-objects">
<span id="cd-parser-objects"></span><h2>39.3.2. Parser Objects<a class="headerlink" href="#parser-objects" title="Permalink to this headline">¶</a></h2>
<p>Parser objects (returned by <a class="reference internal" href="#cd.createparser" title="cd.createparser"><code class="xref py py-func docutils literal notranslate"><span class="pre">createparser()</span></code></a>) have the following methods:</p>
<dl class="method">
<dt>
<code class="descname">CD parser.addcallback(type, func, arg)</code></dt>
<dd><p>Adds a callback for the parser.  The parser has callbacks for eight different
types of data in the digital audio data stream.  Constants for these types are
defined at the <a class="reference internal" href="#module-cd" title="cd: Interface to the CD-ROM on Silicon Graphics systems. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code></a> module level (see above). The callback is called as
follows: <code class="docutils literal notranslate"><span class="pre">func(arg,</span> <span class="pre">type,</span> <span class="pre">data)</span></code>, where <em>arg</em> is the user supplied argument,
<em>type</em> is the particular type of callback, and <em>data</em> is the data returned for
this <em>type</em> of callback.  The type of the data depends on the <em>type</em> of callback
as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type</th>
<th class="head">Value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">audio</span></code></td>
<td>String which can be passed unmodified to
<code class="xref py py-func docutils literal notranslate"><span class="pre">al.writesamps()</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">pnum</span></code></td>
<td>Integer giving the program (track) number.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">index</span></code></td>
<td>Integer giving the index number.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ptime</span></code></td>
<td>Tuple consisting of the program time in
minutes, seconds, and frames.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">atime</span></code></td>
<td>Tuple consisting of the absolute time in
minutes, seconds, and frames.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">catalog</span></code></td>
<td>String of 13 characters, giving the catalog
number of the CD.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ident</span></code></td>
<td>String of 12 characters, giving the ISRC
identification number of the recording.
The string consists of two characters
country code, three characters owner code,
two characters giving the year, and five
characters giving a serial number.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">control</span></code></td>
<td>Integer giving the control bits from the CD
subcode data</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD parser.deleteparser()</code></dt>
<dd><p>Deletes the parser and frees the memory it was using.  The object should not be
used after this call.  This call is done automatically when the last reference
to the object is removed.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD parser.parseframe(frame)</code></dt>
<dd><p>Parses one or more frames of digital audio data from a CD such as returned by
<code class="xref py py-meth docutils literal notranslate"><span class="pre">readda()</span></code>.  It determines which subcodes are present in the data.  If these
subcodes have changed since the last frame, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">parseframe()</span></code> executes a
callback of the appropriate type passing to it the subcode data found in the
frame. Unlike the C function, more than one frame of digital audio data can be
passed to this method.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD parser.removecallback(type)</code></dt>
<dd><p>Removes the callback for the given <em>type</em>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">CD parser.resetparser()</code></dt>
<dd><p>Resets the fields of the parser used for tracking subcodes to an initial state.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">resetparser()</span></code> should be called after the disc has been changed.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a><ul>
<li><a class="reference internal" href="#player-objects">39.3.1. Player Objects</a></li>
<li><a class="reference internal" href="#parser-objects">39.3.2. Parser Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="al.html"
                        title="previous chapter">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fl.html"
                        title="next chapter">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cd.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fl.html" title="39.4. fl — FORMS library for graphical user interfaces"
             >next</a> |</li>
        <li class="right" >
          <a href="al.html" title="39.1. al — Audio functions on the SGI"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\B�r�r�html/library/cgi.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.2. cgi — Common Gateway Interface support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.3. cgitb — Traceback manager for CGI scripts" href="cgitb.html" />
    <link rel="prev" title="20.1. webbrowser — Convenient Web-browser controller" href="webbrowser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cgi.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgitb.html" title="20.3. cgitb — Traceback manager for CGI scripts"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="webbrowser.html" title="20.1. webbrowser — Convenient Web-browser controller"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cgi">
<span id="cgi-common-gateway-interface-support"></span><h1>20.2. <a class="reference internal" href="#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> — Common Gateway Interface support<a class="headerlink" href="#module-cgi" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/cgi.py">Lib/cgi.py</a></p>
<hr class="docutils" />
<p>Support module for Common Gateway Interface (CGI) scripts.</p>
<p>This module defines a number of utilities for use by CGI scripts written in
Python.</p>
<div class="section" id="introduction">
<h2>20.2.1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p id="cgi-intro">A CGI script is invoked by an HTTP server, usually to process user input
submitted through an HTML <code class="docutils literal notranslate"><span class="pre">&lt;FORM&gt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&lt;ISINDEX&gt;</span></code> element.</p>
<p>Most often, CGI scripts live in the server’s special <code class="file docutils literal notranslate"><span class="pre">cgi-bin</span></code> directory.
The HTTP server places all sorts of information about the request (such as the
client’s hostname, the requested URL, the query string, and lots of other
goodies) in the script’s shell environment, executes the script, and sends the
script’s output back to the client.</p>
<p>The script’s input is connected to the client too, and sometimes the form data
is read this way; at other times the form data is passed via the “query string”
part of the URL.  This module is intended to take care of the different cases
and provide a simpler interface to the Python script.  It also provides a number
of utilities that help in debugging scripts, and the latest addition is support
for file uploads from a form (if your browser supports it).</p>
<p>The output of a CGI script should consist of two sections, separated by a blank
line.  The first section contains a number of headers, telling the client what
kind of data is following.  Python code to generate a minimal header section
looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="s2">&quot;Content-Type: text/html&quot;</span>     <span class="c1"># HTML is following</span>
<span class="nb">print</span>                               <span class="c1"># blank line, end of headers</span>
</pre></div>
</div>
<p>The second section is usually HTML, which allows the client software to display
nicely formatted text with header, in-line images, etc. Here’s Python code that
prints a simple piece of HTML:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="s2">&quot;&lt;TITLE&gt;CGI script output&lt;/TITLE&gt;&quot;</span>
<span class="nb">print</span> <span class="s2">&quot;&lt;H1&gt;This is my first CGI script&lt;/H1&gt;&quot;</span>
<span class="nb">print</span> <span class="s2">&quot;Hello, world!&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="using-the-cgi-module">
<span id="id1"></span><h2>20.2.2. Using the cgi module<a class="headerlink" href="#using-the-cgi-module" title="Permalink to this headline">¶</a></h2>
<p>Begin by writing <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">cgi</span></code>.  Do not use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">cgi</span> <span class="pre">import</span> <span class="pre">*</span></code> — the
module defines all sorts of names for its own use or for backward compatibility
that you don’t want in your namespace.</p>
<p>When you write a new script, consider adding these lines:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cgitb</span>
<span class="n">cgitb</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>
</pre></div>
</div>
<p>This activates a special exception handler that will display detailed reports in
the Web browser if any errors occur.  If you’d rather not show the guts of your
program to users of your script, you can have the reports saved to files
instead, with code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cgitb</span>
<span class="n">cgitb</span><span class="o">.</span><span class="n">enable</span><span class="p">(</span><span class="n">display</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">logdir</span><span class="o">=</span><span class="s2">&quot;/path/to/logdir&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>It’s very helpful to use this feature during script development. The reports
produced by <a class="reference internal" href="cgitb.html#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> provide information that can save you a lot of time in
tracking down bugs.  You can always remove the <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> line later when you
have tested your script and are confident that it works correctly.</p>
<p>To get at submitted form data, it’s best to use the <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> class.
The other classes defined in this module are provided mostly for backward
compatibility. Instantiate it exactly once, without arguments.  This reads the
form contents from standard input or the environment (depending on the value of
various environment variables set according to the CGI standard).  Since it may
consume standard input, it should be instantiated only once.</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> instance can be indexed like a Python dictionary.
It allows membership testing with the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator, and also supports
the standard dictionary method <a class="reference internal" href="stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a> and the built-in function
<a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>.  Form fields containing empty strings are ignored and do not appear
in the dictionary; to keep such values, provide a true value for the optional
<em>keep_blank_values</em> keyword parameter when creating the <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code>
instance.</p>
<p>For instance, the following code (which assumes that the
<em class="mailheader">Content-Type</em> header and blank line have already been printed)
checks that the fields <code class="docutils literal notranslate"><span class="pre">name</span></code> and <code class="docutils literal notranslate"><span class="pre">addr</span></code> are both set to a non-empty
string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">form</span> <span class="o">=</span> <span class="n">cgi</span><span class="o">.</span><span class="n">FieldStorage</span><span class="p">()</span>
<span class="k">if</span> <span class="s2">&quot;name&quot;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">form</span> <span class="ow">or</span> <span class="s2">&quot;addr&quot;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">form</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;H1&gt;Error&lt;/H1&gt;&quot;</span>
    <span class="nb">print</span> <span class="s2">&quot;Please fill in the name and addr fields.&quot;</span>
    <span class="k">return</span>
<span class="nb">print</span> <span class="s2">&quot;&lt;p&gt;name:&quot;</span><span class="p">,</span> <span class="n">form</span><span class="p">[</span><span class="s2">&quot;name&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="nb">print</span> <span class="s2">&quot;&lt;p&gt;addr:&quot;</span><span class="p">,</span> <span class="n">form</span><span class="p">[</span><span class="s2">&quot;addr&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="o">...</span><span class="n">further</span> <span class="n">form</span> <span class="n">processing</span> <span class="n">here</span><span class="o">...</span>
</pre></div>
</div>
<p>Here the fields, accessed through <code class="docutils literal notranslate"><span class="pre">form[key]</span></code>, are themselves instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> (or <code class="xref py py-class docutils literal notranslate"><span class="pre">MiniFieldStorage</span></code>, depending on the form
encoding). The <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> attribute of the instance yields
the string value of the field.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">getvalue()</span></code> method
returns this string value directly; it also accepts an optional second argument
as a default to return if the requested key is not present.</p>
<p>If the submitted form data contains more than one field with the same name, the
object retrieved by <code class="docutils literal notranslate"><span class="pre">form[key]</span></code> is not a <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> or
<code class="xref py py-class docutils literal notranslate"><span class="pre">MiniFieldStorage</span></code> instance but a list of such instances.  Similarly, in
this situation, <code class="docutils literal notranslate"><span class="pre">form.getvalue(key)</span></code> would return a list of strings. If you
expect this possibility (when your HTML form contains multiple fields with the
same name), use the <a class="reference internal" href="#cgi.FieldStorage.getlist" title="cgi.FieldStorage.getlist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getlist()</span></code></a> method, which always returns
a list of values (so that you do not need to special-case the single item
case).  For example, this code concatenates any number of username fields,
separated by commas:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">value</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">getlist</span><span class="p">(</span><span class="s2">&quot;username&quot;</span><span class="p">)</span>
<span class="n">usernames</span> <span class="o">=</span> <span class="s2">&quot;,&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>If a field represents an uploaded file, accessing the value via the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> attribute or the <code class="xref py py-func docutils literal notranslate"><span class="pre">getvalue()</span></code>
method reads the entire file in memory as a string.  This may not be what you
want. You can test for an uploaded file by testing either the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attribute or the <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code>
attribute.  You can then read the data at leisure from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code>
attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fileitem</span> <span class="o">=</span> <span class="n">form</span><span class="p">[</span><span class="s2">&quot;userfile&quot;</span><span class="p">]</span>
<span class="k">if</span> <span class="n">fileitem</span><span class="o">.</span><span class="n">file</span><span class="p">:</span>
    <span class="c1"># It&#39;s an uploaded file; count lines</span>
    <span class="n">linecount</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">line</span> <span class="o">=</span> <span class="n">fileitem</span><span class="o">.</span><span class="n">file</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span> <span class="k">break</span>
        <span class="n">linecount</span> <span class="o">=</span> <span class="n">linecount</span> <span class="o">+</span> <span class="mi">1</span>
</pre></div>
</div>
<p>If an error is encountered when obtaining the contents of an uploaded file
(for example, when the user interrupts the form submission by clicking on
a Back or Cancel button) the <code class="xref py py-attr docutils literal notranslate"><span class="pre">done</span></code> attribute of the
object for the field will be set to the value -1.</p>
<p>The file upload draft standard entertains the possibility of uploading multiple
files from one field (using a recursive <em class="mimetype">multipart/*</em> encoding).
When this occurs, the item will be a dictionary-like <code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> item.
This can be determined by testing its <code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code> attribute, which should be
<em class="mimetype">multipart/form-data</em> (or perhaps another MIME type matching
<em class="mimetype">multipart/*</em>).  In this case, it can be iterated over recursively
just like the top-level form object.</p>
<p>When a form is submitted in the “old” format (as the query string or as a single
data part of type <em class="mimetype">application/x-www-form-urlencoded</em>), the items will
actually be instances of the class <code class="xref py py-class docutils literal notranslate"><span class="pre">MiniFieldStorage</span></code>.  In this case, the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">list</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attributes are always <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>A form submitted via POST that also has a query string will contain both
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">MiniFieldStorage</span></code> items.</p>
</div>
<div class="section" id="higher-level-interface">
<h2>20.2.3. Higher Level Interface<a class="headerlink" href="#higher-level-interface" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>The previous section explains how to read CGI form data using the
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> class.  This section describes a higher level interface
which was added to this class to allow one to do it in a more readable and
intuitive way.  The interface doesn’t make the techniques described in previous
sections obsolete — they are still useful to process file uploads efficiently,
for example.</p>
<p>The interface consists of two simple methods. Using the methods you can process
form data in a generic way, without the need to worry whether only one or more
values were posted under one name.</p>
<p>In the previous section, you learned to write following code anytime you
expected a user to post more than one value under one name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">item</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">getvalue</span><span class="p">(</span><span class="s2">&quot;item&quot;</span><span class="p">)</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="nb">list</span><span class="p">):</span>
    <span class="c1"># The user is requesting more than one item.</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># The user is requesting only one item.</span>
</pre></div>
</div>
<p>This situation is common for example when a form contains a group of multiple
checkboxes with the same name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="nb">input</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;checkbox&quot;</span> <span class="n">name</span><span class="o">=</span><span class="s2">&quot;item&quot;</span> <span class="n">value</span><span class="o">=</span><span class="s2">&quot;1&quot;</span> <span class="o">/&gt;</span>
<span class="o">&lt;</span><span class="nb">input</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;checkbox&quot;</span> <span class="n">name</span><span class="o">=</span><span class="s2">&quot;item&quot;</span> <span class="n">value</span><span class="o">=</span><span class="s2">&quot;2&quot;</span> <span class="o">/&gt;</span>
</pre></div>
</div>
<p>In most situations, however, there’s only one form control with a particular
name in a form and then you expect and need only one value associated with this
name.  So you write a script containing for example this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">user</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">getvalue</span><span class="p">(</span><span class="s2">&quot;user&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>
</div>
<p>The problem with the code is that you should never expect that a client will
provide valid input to your scripts.  For example, if a curious user appends
another <code class="docutils literal notranslate"><span class="pre">user=foo</span></code> pair to the query string, then the script would crash,
because in this situation the <code class="docutils literal notranslate"><span class="pre">getvalue(&quot;user&quot;)</span></code> method call returns a list
instead of a string.  Calling the <a class="reference internal" href="stdtypes.html#str.upper" title="str.upper"><code class="xref py py-meth docutils literal notranslate"><span class="pre">upper()</span></code></a> method on a list is not valid
(since lists do not have a method of this name) and results in an
<a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception.</p>
<p>Therefore, the appropriate way to read form data values was to always use the
code which checks whether the obtained value is a single value or a list of
values.  That’s annoying and leads to less readable scripts.</p>
<p>A more convenient approach is to use the methods <a class="reference internal" href="#cgi.FieldStorage.getfirst" title="cgi.FieldStorage.getfirst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getfirst()</span></code></a>
and <a class="reference internal" href="#cgi.FieldStorage.getlist" title="cgi.FieldStorage.getlist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getlist()</span></code></a> provided by this higher level interface.</p>
<dl class="method">
<dt id="cgi.FieldStorage.getfirst">
<code class="descclassname">FieldStorage.</code><code class="descname">getfirst</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.FieldStorage.getfirst" title="Permalink to this definition">¶</a></dt>
<dd><p>This method always returns only one value associated with form field <em>name</em>.
The method returns only the first value in case that more values were posted
under such name.  Please note that the order in which the values are received
may vary from browser to browser and should not be counted on. <a class="footnote-reference" href="#id3" id="id2">[1]</a>  If no such
form field or value exists then the method returns the value specified by the
optional parameter <em>default</em>.  This parameter defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> if not
specified.</p>
</dd></dl>

<dl class="method">
<dt id="cgi.FieldStorage.getlist">
<code class="descclassname">FieldStorage.</code><code class="descname">getlist</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#cgi.FieldStorage.getlist" title="Permalink to this definition">¶</a></dt>
<dd><p>This method always returns a list of values associated with form field <em>name</em>.
The method returns an empty list if no such form field or value exists for
<em>name</em>.  It returns a list consisting of one item if only one such value exists.</p>
</dd></dl>

<p>Using these methods you can write nice compact code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cgi</span>
<span class="n">form</span> <span class="o">=</span> <span class="n">cgi</span><span class="o">.</span><span class="n">FieldStorage</span><span class="p">()</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">form</span><span class="o">.</span><span class="n">getfirst</span><span class="p">(</span><span class="s2">&quot;user&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>    <span class="c1"># This way it&#39;s safe.</span>
<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">form</span><span class="o">.</span><span class="n">getlist</span><span class="p">(</span><span class="s2">&quot;item&quot;</span><span class="p">):</span>
    <span class="n">do_something</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="old-classes">
<h2>20.2.4. Old classes<a class="headerlink" href="#old-classes" title="Permalink to this headline">¶</a></h2>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>These classes, present in earlier versions of the <a class="reference internal" href="#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module, are
still supported for backward compatibility.  New applications should use the
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> class.</p>
</div>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">SvFormContentDict</span></code> stores single value form content as dictionary; it
assumes each field name occurs in the form only once.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">FormContentDict</span></code> stores multiple value form content as a dictionary (the
form items are lists of values).  Useful if your form contains multiple fields
with the same name.</p>
<p>Other classes (<code class="xref py py-class docutils literal notranslate"><span class="pre">FormContent</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">InterpFormContentDict</span></code>) are present
for backwards compatibility with really old applications only.</p>
</div>
<div class="section" id="functions">
<span id="functions-in-cgi-module"></span><h2>20.2.5. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h2>
<p>These are useful if you want more control, or if you want to employ some of the
algorithms implemented in this module in other circumstances.</p>
<dl class="function">
<dt id="cgi.parse">
<code class="descclassname">cgi.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>environ</em><span class="optional">[</span>, <em>keep_blank_values</em><span class="optional">[</span>, <em>strict_parsing</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a query in the environment or from a file (the file defaults to
<code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> and environment defaults to <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>).  The <em>keep_blank_values</em> and <em>strict_parsing</em> parameters are
passed to <a class="reference internal" href="urlparse.html#urlparse.parse_qs" title="urlparse.parse_qs"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse.parse_qs()</span></code></a> unchanged.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.parse_qs">
<code class="descclassname">cgi.</code><code class="descname">parse_qs</code><span class="sig-paren">(</span><em>qs</em><span class="optional">[</span>, <em>keep_blank_values</em><span class="optional">[</span>, <em>strict_parsing</em><span class="optional">[</span>, <em>max_num_fields</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.parse_qs" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is deprecated in this module. Use <a class="reference internal" href="urlparse.html#urlparse.parse_qs" title="urlparse.parse_qs"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse.parse_qs()</span></code></a>
instead. It is maintained here only for backward compatibility.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.parse_qsl">
<code class="descclassname">cgi.</code><code class="descname">parse_qsl</code><span class="sig-paren">(</span><em>qs</em><span class="optional">[</span>, <em>keep_blank_values</em><span class="optional">[</span>, <em>strict_parsing</em><span class="optional">[</span>, <em>max_num_fields</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.parse_qsl" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is deprecated in this module. Use <a class="reference internal" href="urlparse.html#urlparse.parse_qsl" title="urlparse.parse_qsl"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse.parse_qsl()</span></code></a>
instead. It is maintained here only for backward compatibility.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.parse_multipart">
<code class="descclassname">cgi.</code><code class="descname">parse_multipart</code><span class="sig-paren">(</span><em>fp</em>, <em>pdict</em><span class="sig-paren">)</span><a class="headerlink" href="#cgi.parse_multipart" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse input of type <em class="mimetype">multipart/form-data</em> (for  file uploads).
Arguments are <em>fp</em> for the input file and <em>pdict</em> for a dictionary containing
other parameters in the <em class="mailheader">Content-Type</em> header.</p>
<p>Returns a dictionary just like <a class="reference internal" href="urlparse.html#urlparse.parse_qs" title="urlparse.parse_qs"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse.parse_qs()</span></code></a> keys are the field names, each
value is a list of values for that field.  This is easy to use but not much good
if you are expecting megabytes to be uploaded — in that case, use the
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> class instead which is much more flexible.</p>
<p>Note that this does not parse nested multipart parts — use
<code class="xref py py-class docutils literal notranslate"><span class="pre">FieldStorage</span></code> for that.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.parse_header">
<code class="descclassname">cgi.</code><code class="descname">parse_header</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#cgi.parse_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a MIME header (such as <em class="mailheader">Content-Type</em>) into a main value and a
dictionary of parameters.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.test">
<code class="descclassname">cgi.</code><code class="descname">test</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.test" title="Permalink to this definition">¶</a></dt>
<dd><p>Robust test CGI script, usable as main program. Writes minimal HTTP headers and
formats all information provided to the script in HTML form.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.print_environ">
<code class="descclassname">cgi.</code><code class="descname">print_environ</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.print_environ" title="Permalink to this definition">¶</a></dt>
<dd><p>Format the shell environment in HTML.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.print_form">
<code class="descclassname">cgi.</code><code class="descname">print_form</code><span class="sig-paren">(</span><em>form</em><span class="sig-paren">)</span><a class="headerlink" href="#cgi.print_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Format a form in HTML.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.print_directory">
<code class="descclassname">cgi.</code><code class="descname">print_directory</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.print_directory" title="Permalink to this definition">¶</a></dt>
<dd><p>Format the current directory in HTML.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.print_environ_usage">
<code class="descclassname">cgi.</code><code class="descname">print_environ_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.print_environ_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a list of useful (used by CGI) environment variables in HTML.</p>
</dd></dl>

<dl class="function">
<dt id="cgi.escape">
<code class="descclassname">cgi.</code><code class="descname">escape</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>quote</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgi.escape" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the characters <code class="docutils literal notranslate"><span class="pre">'&amp;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> in string <em>s</em> to HTML-safe
sequences.  Use this if you need to display text that might contain such
characters in HTML.  If the optional flag <em>quote</em> is true, the quotation mark
character (<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>) is also translated; this helps for inclusion in an HTML
attribute value delimited by double quotes, as in <code class="docutils literal notranslate"><span class="pre">&lt;a</span> <span class="pre">href=&quot;...&quot;&gt;</span></code>.  Note
that single quotes are never translated.</p>
<p>If the value to be quoted might include single- or double-quote characters,
or both, consider using the <a class="reference internal" href="xml.sax.utils.html#xml.sax.saxutils.quoteattr" title="xml.sax.saxutils.quoteattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">quoteattr()</span></code></a> function in the
<a class="reference internal" href="xml.sax.utils.html#module-xml.sax.saxutils" title="xml.sax.saxutils: Convenience functions and classes for use with SAX."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code></a> module instead.</p>
</dd></dl>

</div>
<div class="section" id="caring-about-security">
<span id="cgi-security"></span><h2>20.2.6. Caring about security<a class="headerlink" href="#caring-about-security" title="Permalink to this headline">¶</a></h2>
<p id="index-1">There’s one important rule: if you invoke an external program (via the
<a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a> or <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> functions. or others with similar
functionality), make very sure you don’t pass arbitrary strings received from
the client to the shell.  This is a well-known security hole whereby clever
hackers anywhere on the Web can exploit a gullible CGI script to invoke
arbitrary shell commands.  Even parts of the URL or field names cannot be
trusted, since the request doesn’t have to come from your form!</p>
<p>To be on the safe side, if you must pass a string gotten from a form to a shell
command, you should make sure the string contains only alphanumeric characters,
dashes, underscores, and periods.</p>
</div>
<div class="section" id="installing-your-cgi-script-on-a-unix-system">
<h2>20.2.7. Installing your CGI script on a Unix system<a class="headerlink" href="#installing-your-cgi-script-on-a-unix-system" title="Permalink to this headline">¶</a></h2>
<p>Read the documentation for your HTTP server and check with your local system
administrator to find the directory where CGI scripts should be installed;
usually this is in a directory <code class="file docutils literal notranslate"><span class="pre">cgi-bin</span></code> in the server tree.</p>
<p>Make sure that your script is readable and executable by “others”; the Unix file
mode should be <code class="docutils literal notranslate"><span class="pre">0755</span></code> octal (use <code class="docutils literal notranslate"><span class="pre">chmod</span> <span class="pre">0755</span> <span class="pre">filename</span></code>).  Make sure that the
first line of the script contains <code class="docutils literal notranslate"><span class="pre">#!</span></code> starting in column 1 followed by the
pathname of the Python interpreter, for instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>
</pre></div>
</div>
<p>Make sure the Python interpreter exists and is executable by “others”.</p>
<p>Make sure that any files your script needs to read or write are readable or
writable, respectively, by “others” — their mode should be <code class="docutils literal notranslate"><span class="pre">0644</span></code> for
readable and <code class="docutils literal notranslate"><span class="pre">0666</span></code> for writable.  This is because, for security reasons, the
HTTP server executes your script as user “nobody”, without any special
privileges.  It can only read (write, execute) files that everybody can read
(write, execute).  The current directory at execution time is also different (it
is usually the server’s cgi-bin directory) and the set of environment variables
is also different from what you get when you log in.  In particular, don’t count
on the shell’s search path for executables (<span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>) or the Python module
search path (<span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>) to be set to anything interesting.</p>
<p>If you need to load modules from a directory which is not on Python’s default
module search path, you can change the path in your script, before importing
other modules.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;/usr/home/joe/lib/python&quot;</span><span class="p">)</span>
<span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;/usr/local/lib/python&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>(This way, the directory inserted last will be searched first!)</p>
<p>Instructions for non-Unix systems will vary; check your HTTP server’s
documentation (it will usually have a section on CGI scripts).</p>
</div>
<div class="section" id="testing-your-cgi-script">
<h2>20.2.8. Testing your CGI script<a class="headerlink" href="#testing-your-cgi-script" title="Permalink to this headline">¶</a></h2>
<p>Unfortunately, a CGI script will generally not run when you try it from the
command line, and a script that works perfectly from the command line may fail
mysteriously when run from the server.  There’s one reason why you should still
test your script from the command line: if it contains a syntax error, the
Python interpreter won’t execute it at all, and the HTTP server will most likely
send a cryptic error to the client.</p>
<p>Assuming your script has no syntax errors, yet it does not work, you have no
choice but to read the next section.</p>
</div>
<div class="section" id="debugging-cgi-scripts">
<h2>20.2.9. Debugging CGI scripts<a class="headerlink" href="#debugging-cgi-scripts" title="Permalink to this headline">¶</a></h2>
<p id="index-4">First of all, check for trivial installation errors — reading the section
above on installing your CGI script carefully can save you a lot of time.  If
you wonder whether you have understood the installation procedure correctly, try
installing a copy of this module file (<code class="file docutils literal notranslate"><span class="pre">cgi.py</span></code>) as a CGI script.  When
invoked as a script, the file will dump its environment and the contents of the
form in HTML form. Give it the right mode etc, and send it a request.  If it’s
installed in the standard <code class="file docutils literal notranslate"><span class="pre">cgi-bin</span></code> directory, it should be possible to
send it a request by entering a URL into your browser of the form:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>http://yourhostname/cgi-bin/cgi.py?name=Joe+Blow&amp;addr=At+Home
</pre></div>
</div>
<p>If this gives an error of type 404, the server cannot find the script – perhaps
you need to install it in a different directory.  If it gives another error,
there’s an installation problem that you should fix before trying to go any
further.  If you get a nicely formatted listing of the environment and form
content (in this example, the fields should be listed as “addr” with value “At
Home” and “name” with value “Joe Blow”), the <code class="file docutils literal notranslate"><span class="pre">cgi.py</span></code> script has been
installed correctly.  If you follow the same procedure for your own script, you
should now be able to debug it.</p>
<p>The next step could be to call the <a class="reference internal" href="#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module’s <a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-func docutils literal notranslate"><span class="pre">test()</span></code></a> function
from your script: replace its main code with the single statement</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">cgi</span><span class="o">.</span><span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>This should produce the same results as those gotten from installing the
<code class="file docutils literal notranslate"><span class="pre">cgi.py</span></code> file itself.</p>
<p>When an ordinary Python script raises an unhandled exception (for whatever
reason: of a typo in a module name, a file that can’t be opened, etc.), the
Python interpreter prints a nice traceback and exits.  While the Python
interpreter will still do this when your CGI script raises an exception, most
likely the traceback will end up in one of the HTTP server’s log files, or be
discarded altogether.</p>
<p>Fortunately, once you have managed to get your script to execute <em>some</em> code,
you can easily send tracebacks to the Web browser using the <a class="reference internal" href="cgitb.html#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> module.
If you haven’t done so already, just add the lines:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cgitb</span>
<span class="n">cgitb</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>
</pre></div>
</div>
<p>to the top of your script.  Then try running it again; when a problem occurs,
you should see a detailed report that will likely make apparent the cause of the
crash.</p>
<p>If you suspect that there may be a problem in importing the <a class="reference internal" href="cgitb.html#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> module,
you can use an even more robust approach (which only uses built-in modules):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="n">sys</span><span class="o">.</span><span class="n">stderr</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span>
<span class="nb">print</span> <span class="s2">&quot;Content-Type: text/plain&quot;</span>
<span class="nb">print</span>
<span class="o">...</span><span class="n">your</span> <span class="n">code</span> <span class="n">here</span><span class="o">...</span>
</pre></div>
</div>
<p>This relies on the Python interpreter to print the traceback.  The content type
of the output is set to plain text, which disables all HTML processing.  If your
script works, the raw HTML will be displayed by your client.  If it raises an
exception, most likely after the first two lines have been printed, a traceback
will be displayed. Because no HTML interpretation is going on, the traceback
will be readable.</p>
</div>
<div class="section" id="common-problems-and-solutions">
<h2>20.2.10. Common problems and solutions<a class="headerlink" href="#common-problems-and-solutions" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>Most HTTP servers buffer the output from CGI scripts until the script is
completed.  This means that it is not possible to display a progress report on
the client’s display while the script is running.</li>
<li>Check the installation instructions above.</li>
<li>Check the HTTP server’s log files.  (<code class="docutils literal notranslate"><span class="pre">tail</span> <span class="pre">-f</span> <span class="pre">logfile</span></code> in a separate window
may be useful!)</li>
<li>Always check a script for syntax errors first, by doing something like
<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">script.py</span></code>.</li>
<li>If your script does not have any syntax errors, try adding <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">cgitb;</span>
<span class="pre">cgitb.enable()</span></code> to the top of the script.</li>
<li>When invoking external programs, make sure they can be found. Usually, this
means using absolute path names — <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> is usually not set to a very
useful value in a CGI script.</li>
<li>When reading or writing external files, make sure they can be read or written
by the userid under which your CGI script will be running: this is typically the
userid under which the web server is running, or some explicitly specified
userid for a web server’s <code class="docutils literal notranslate"><span class="pre">suexec</span></code> feature.</li>
<li>Don’t try to give a CGI script a set-uid mode.  This doesn’t work on most
systems, and is a security liability as well.</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[1]</a></td><td>Note that some recent versions of the HTML specification do state what order the
field values should be supplied in, but knowing whether a request was
received from a conforming browser, or even from a browser at all, is tedious
and error-prone.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a><ul>
<li><a class="reference internal" href="#introduction">20.2.1. Introduction</a></li>
<li><a class="reference internal" href="#using-the-cgi-module">20.2.2. Using the cgi module</a></li>
<li><a class="reference internal" href="#higher-level-interface">20.2.3. Higher Level Interface</a></li>
<li><a class="reference internal" href="#old-classes">20.2.4. Old classes</a></li>
<li><a class="reference internal" href="#functions">20.2.5. Functions</a></li>
<li><a class="reference internal" href="#caring-about-security">20.2.6. Caring about security</a></li>
<li><a class="reference internal" href="#installing-your-cgi-script-on-a-unix-system">20.2.7. Installing your CGI script on a Unix system</a></li>
<li><a class="reference internal" href="#testing-your-cgi-script">20.2.8. Testing your CGI script</a></li>
<li><a class="reference internal" href="#debugging-cgi-scripts">20.2.9. Debugging CGI scripts</a></li>
<li><a class="reference internal" href="#common-problems-and-solutions">20.2.10. Common problems and solutions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="webbrowser.html"
                        title="previous chapter">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cgitb.html"
                        title="next chapter">20.3. <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> — Traceback manager for CGI scripts</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cgi.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgitb.html" title="20.3. cgitb — Traceback manager for CGI scripts"
             >next</a> |</li>
        <li class="right" >
          <a href="webbrowser.html" title="20.1. webbrowser — Convenient Web-browser controller"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�&�6�6html/library/cgihttpserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.20. CGIHTTPServer — CGI-capable HTTP request handler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.21. cookielib — Cookie handling for HTTP clients" href="cookielib.html" />
    <link rel="prev" title="20.19. SimpleHTTPServer — Simple HTTP request handler" href="simplehttpserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cgihttpserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cookielib.html" title="20.21. cookielib — Cookie handling for HTTP clients"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="simplehttpserver.html" title="20.19. SimpleHTTPServer — Simple HTTP request handler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-CGIHTTPServer">
<span id="cgihttpserver-cgi-capable-http-request-handler"></span><h1>20.20. <a class="reference internal" href="#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a> — CGI-capable HTTP request handler<a class="headerlink" href="#module-CGIHTTPServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a> module has been merged into <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.server</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a> module defines a request-handler class, interface
compatible with <a class="reference internal" href="basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler</span></code></a> and inherits
behavior from <a class="reference internal" href="simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPServer.SimpleHTTPRequestHandler</span></code></a> but can also
run CGI scripts.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module can run CGI scripts on Unix and Windows systems.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">CGI scripts run by the <a class="reference internal" href="#CGIHTTPServer.CGIHTTPRequestHandler" title="CGIHTTPServer.CGIHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHTTPRequestHandler</span></code></a> class cannot execute
redirects (HTTP code 302), because code 200 (script output follows) is sent
prior to execution of the CGI script.  This pre-empts the status code.</p>
</div>
<p>The <a class="reference internal" href="#module-CGIHTTPServer" title="CGIHTTPServer: This module provides a request handler for HTTP servers which can run CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code></a> module defines the following class:</p>
<dl class="class">
<dt id="CGIHTTPServer.CGIHTTPRequestHandler">
<em class="property">class </em><code class="descclassname">CGIHTTPServer.</code><code class="descname">CGIHTTPRequestHandler</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em>, <em>server</em><span class="sig-paren">)</span><a class="headerlink" href="#CGIHTTPServer.CGIHTTPRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is used to serve either files or output of CGI scripts from  the
current directory and below. Note that mapping HTTP hierarchic structure to
local directory structure is exactly as in
<a class="reference internal" href="simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPServer.SimpleHTTPRequestHandler</span></code></a>.</p>
<p>The class will however, run the CGI script, instead of serving it as a file, if
it guesses it to be a CGI script. Only directory-based CGI are used — the
other common server configuration is to treat special extensions as denoting CGI
scripts.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">do_GET()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">do_HEAD()</span></code> functions are modified to run CGI scripts
and serve the output, instead of serving files, if the request leads to
somewhere below the <code class="docutils literal notranslate"><span class="pre">cgi_directories</span></code> path.</p>
<p>The <a class="reference internal" href="#CGIHTTPServer.CGIHTTPRequestHandler" title="CGIHTTPServer.CGIHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHTTPRequestHandler</span></code></a> defines the following data member:</p>
<dl class="attribute">
<dt id="CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories">
<code class="descname">cgi_directories</code><a class="headerlink" href="#CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories" title="Permalink to this definition">¶</a></dt>
<dd><p>This defaults to <code class="docutils literal notranslate"><span class="pre">['/cgi-bin',</span> <span class="pre">'/htbin']</span></code> and describes directories to
treat as containing CGI scripts.</p>
</dd></dl>

<p>The <a class="reference internal" href="#CGIHTTPServer.CGIHTTPRequestHandler" title="CGIHTTPServer.CGIHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHTTPRequestHandler</span></code></a> defines the following methods:</p>
<dl class="method">
<dt id="CGIHTTPServer.CGIHTTPRequestHandler.do_POST">
<code class="descname">do_POST</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#CGIHTTPServer.CGIHTTPRequestHandler.do_POST" title="Permalink to this definition">¶</a></dt>
<dd><p>This method serves the <code class="docutils literal notranslate"><span class="pre">'POST'</span></code> request type, only allowed for CGI
scripts.  Error 501, “Can only POST to CGI scripts”, is output when trying
to POST to a non-CGI url.</p>
</dd></dl>

</dd></dl>

<p>Note that CGI scripts will be run with UID of user nobody, for security reasons.
Problems with the CGI script will be translated to error 403.</p>
<p>For example usage, see the implementation of the <a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-func docutils literal notranslate"><span class="pre">test()</span></code></a> function.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="basehttpserver.html#module-BaseHTTPServer" title="BaseHTTPServer: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code></a></dt>
<dd>Base class implementation for Web server and request handler.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="simplehttpserver.html"
                        title="previous chapter">20.19. <code class="docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code> — Simple HTTP request handler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cookielib.html"
                        title="next chapter">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cgihttpserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cookielib.html" title="20.21. cookielib — Cookie handling for HTTP clients"
             >next</a> |</li>
        <li class="right" >
          <a href="simplehttpserver.html" title="20.19. SimpleHTTPServer — Simple HTTP request handler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��f�/�/html/library/cgitb.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.3. cgitb — Traceback manager for CGI scripts &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.4. wsgiref — WSGI Utilities and Reference Implementation" href="wsgiref.html" />
    <link rel="prev" title="20.2. cgi — Common Gateway Interface support" href="cgi.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cgitb.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="wsgiref.html" title="20.4. wsgiref — WSGI Utilities and Reference Implementation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cgi.html" title="20.2. cgi — Common Gateway Interface support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cgitb">
<span id="cgitb-traceback-manager-for-cgi-scripts"></span><h1>20.3. <a class="reference internal" href="#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> — Traceback manager for CGI scripts<a class="headerlink" href="#module-cgitb" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p id="index-0">The <a class="reference internal" href="#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> module provides a special exception handler for Python scripts.
(Its name is a bit misleading.  It was originally designed to display extensive
traceback information in HTML for CGI scripts.  It was later generalized to also
display this information in plain text.)  After this module is activated, if an
uncaught exception occurs, a detailed, formatted report will be displayed.  The
report includes a traceback showing excerpts of the source code for each level,
as well as the values of the arguments and local variables to currently running
functions, to help you debug the problem.  Optionally, you can save this
information to a file instead of sending it to the browser.</p>
<p>To enable this feature, simply add this to the top of your CGI script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cgitb</span>
<span class="n">cgitb</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>
</pre></div>
</div>
<p>The options to the <a class="reference internal" href="#cgitb.enable" title="cgitb.enable"><code class="xref py py-func docutils literal notranslate"><span class="pre">enable()</span></code></a> function control whether the report is
displayed in the browser and whether the report is logged to a file for later
analysis.</p>
<dl class="function">
<dt id="cgitb.enable">
<code class="descclassname">cgitb.</code><code class="descname">enable</code><span class="sig-paren">(</span><span class="optional">[</span><em>display</em><span class="optional">[</span>, <em>logdir</em><span class="optional">[</span>, <em>context</em><span class="optional">[</span>, <em>format</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgitb.enable" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">This function causes the <a class="reference internal" href="#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a> module to take over the interpreter’s
default handling for exceptions by setting the value of <a class="reference internal" href="sys.html#sys.excepthook" title="sys.excepthook"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.excepthook</span></code></a>.</p>
<p>The optional argument <em>display</em> defaults to <code class="docutils literal notranslate"><span class="pre">1</span></code> and can be set to <code class="docutils literal notranslate"><span class="pre">0</span></code> to
suppress sending the traceback to the browser. If the argument <em>logdir</em> is
present, the traceback reports are written to files.  The value of <em>logdir</em>
should be a directory where these files will be placed. The optional argument
<em>context</em> is the number of lines of context to display around the current line
of source code in the traceback; this defaults to <code class="docutils literal notranslate"><span class="pre">5</span></code>. If the optional
argument <em>format</em> is <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code>, the output is formatted as HTML.  Any other
value forces plain text output.  The default value is <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="cgitb.handler">
<code class="descclassname">cgitb.</code><code class="descname">handler</code><span class="sig-paren">(</span><span class="optional">[</span><em>info</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cgitb.handler" title="Permalink to this definition">¶</a></dt>
<dd><p>This function handles an exception using the default settings (that is, show a
report in the browser, but don’t log to a file). This can be used when you’ve
caught an exception and want to report it using <a class="reference internal" href="#module-cgitb" title="cgitb: Configurable traceback handler for CGI scripts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgitb</span></code></a>.  The optional
<em>info</em> argument should be a 3-tuple containing an exception type, exception
value, and traceback object, exactly like the tuple returned by
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.  If the <em>info</em> argument is not supplied, the current
exception is obtained from <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="cgi.html"
                        title="previous chapter">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="wsgiref.html"
                        title="next chapter">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cgitb.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="wsgiref.html" title="20.4. wsgiref — WSGI Utilities and Reference Implementation"
             >next</a> |</li>
        <li class="right" >
          <a href="cgi.html" title="20.2. cgi — Common Gateway Interface support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�D��>>html/library/chunk.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.6. chunk — Read IFF chunked data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.7. colorsys — Conversions between color systems" href="colorsys.html" />
    <link rel="prev" title="21.5. wave — Read and write WAV files" href="wave.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/chunk.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="colorsys.html" title="21.7. colorsys — Conversions between color systems"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="wave.html" title="21.5. wave — Read and write WAV files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-chunk">
<span id="chunk-read-iff-chunked-data"></span><h1>21.6. <a class="reference internal" href="#module-chunk" title="chunk: Module to read IFF chunks."><code class="xref py py-mod docutils literal notranslate"><span class="pre">chunk</span></code></a> — Read IFF chunked data<a class="headerlink" href="#module-chunk" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module provides an interface for reading files that use EA IFF 85 chunks.
<a class="footnote-reference" href="#id2" id="id1">[1]</a>  This format is used in at least the Audio Interchange File Format
(AIFF/AIFF-C) and the Real Media File Format (RMFF).  The WAVE audio file format
is closely related and can also be read using this module.</p>
<p>A chunk has the following structure:</p>
<table border="1" class="docutils">
<colgroup>
<col width="19%" />
<col width="17%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Offset</th>
<th class="head">Length</th>
<th class="head">Contents</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td>4</td>
<td>Chunk ID</td>
</tr>
<tr class="row-odd"><td>4</td>
<td>4</td>
<td>Size of chunk in big-endian
byte order, not including the
header</td>
</tr>
<tr class="row-even"><td>8</td>
<td><em>n</em></td>
<td>Data bytes, where <em>n</em> is the
size given in the preceding
field</td>
</tr>
<tr class="row-odd"><td>8 + <em>n</em></td>
<td>0 or 1</td>
<td>Pad byte needed if <em>n</em> is odd
and chunk alignment is used</td>
</tr>
</tbody>
</table>
<p>The ID is a 4-byte string which identifies the type of chunk.</p>
<p>The size field (a 32-bit value, encoded using big-endian byte order) gives the
size of the chunk data, not including the 8-byte header.</p>
<p>Usually an IFF-type file consists of one or more chunks.  The proposed usage of
the <a class="reference internal" href="#chunk.Chunk" title="chunk.Chunk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Chunk</span></code></a> class defined here is to instantiate an instance at the start
of each chunk and read from the instance until it reaches the end, after which a
new instance can be instantiated. At the end of the file, creating a new
instance will fail with an <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> exception.</p>
<dl class="class">
<dt id="chunk.Chunk">
<em class="property">class </em><code class="descclassname">chunk.</code><code class="descname">Chunk</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>align</em>, <em>bigendian</em>, <em>inclheader</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk" title="Permalink to this definition">¶</a></dt>
<dd><p>Class which represents a chunk.  The <em>file</em> argument is expected to be a
file-like object.  An instance of this class is specifically allowed.  The
only method that is needed is <a class="reference internal" href="stdtypes.html#file.read" title="file.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>.  If the methods
<a class="reference internal" href="stdtypes.html#file.seek" title="file.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> and <a class="reference internal" href="stdtypes.html#file.tell" title="file.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> are present and don’t
raise an exception, they are also used.
If these methods are present and raise an exception, they are expected to not
have altered the object.  If the optional argument <em>align</em> is true, chunks
are assumed to be aligned on 2-byte boundaries.  If <em>align</em> is false, no
alignment is assumed.  The default value is true.  If the optional argument
<em>bigendian</em> is false, the chunk size is assumed to be in little-endian order.
This is needed for WAVE audio files. The default value is true.  If the
optional argument <em>inclheader</em> is true, the size given in the chunk header
includes the size of the header.  The default value is false.</p>
<p>A <a class="reference internal" href="#chunk.Chunk" title="chunk.Chunk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Chunk</span></code></a> object supports the following methods:</p>
<dl class="method">
<dt id="chunk.Chunk.getname">
<code class="descname">getname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.getname" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name (ID) of the chunk.  This is the first 4 bytes of the
chunk.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.getsize">
<code class="descname">getsize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.getsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the size of the chunk.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close and skip to the end of the chunk.  This does not close the
underlying file.</p>
</dd></dl>

<p>The remaining methods will raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if called after the
<a class="reference internal" href="#chunk.Chunk.close" title="chunk.Chunk.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method has been called.</p>
<dl class="method">
<dt id="chunk.Chunk.isatty">
<code class="descname">isatty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.isatty" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.seek">
<code class="descname">seek</code><span class="sig-paren">(</span><em>pos</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the chunk’s current position.  The <em>whence</em> argument is optional and
defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code> (absolute file positioning); other values are <code class="docutils literal notranslate"><span class="pre">1</span></code>
(seek relative to the current position) and <code class="docutils literal notranslate"><span class="pre">2</span></code> (seek relative to the
file’s end).  There is no return value. If the underlying file does not
allow seek, only forward seeks are allowed.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.tell">
<code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current position into the chunk.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at most <em>size</em> bytes from the chunk (less if the read hits the end of
the chunk before obtaining <em>size</em> bytes).  If the <em>size</em> argument is
negative or omitted, read all data until the end of the chunk.  The bytes
are returned as a string object.  An empty string is returned when the end
of the chunk is encountered immediately.</p>
</dd></dl>

<dl class="method">
<dt id="chunk.Chunk.skip">
<code class="descname">skip</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#chunk.Chunk.skip" title="Permalink to this definition">¶</a></dt>
<dd><p>Skip to the end of the chunk.  All further calls to <a class="reference internal" href="#chunk.Chunk.read" title="chunk.Chunk.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> for the
chunk will return <code class="docutils literal notranslate"><span class="pre">''</span></code>.  If you are not interested in the contents of
the chunk, this method should be called so that the file points to the
start of the next chunk.</p>
</dd></dl>

</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>“EA IFF 85” Standard for Interchange Format Files, Jerry Morrison, Electronic
Arts, January 1985.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="wave.html"
                        title="previous chapter">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="colorsys.html"
                        title="next chapter">21.7. <code class="docutils literal notranslate"><span class="pre">colorsys</span></code> — Conversions between color systems</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/chunk.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="colorsys.html" title="21.7. colorsys — Conversions between color systems"
             >next</a> |</li>
        <li class="right" >
          <a href="wave.html" title="21.5. wave — Read and write WAV files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�y���n�nhtml/library/cmath.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.3. cmath — Mathematical functions for complex numbers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.4. decimal — Decimal fixed point and floating point arithmetic" href="decimal.html" />
    <link rel="prev" title="9.2. math — Mathematical functions" href="math.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cmath.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="decimal.html" title="9.4. decimal — Decimal fixed point and floating point arithmetic"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="math.html" title="9.2. math — Mathematical functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cmath">
<span id="cmath-mathematical-functions-for-complex-numbers"></span><h1>9.3. <a class="reference internal" href="#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> — Mathematical functions for complex numbers<a class="headerlink" href="#module-cmath" title="Permalink to this headline">¶</a></h1>
<p>This module is always available.  It provides access to mathematical functions
for complex numbers.  The functions in this module accept integers,
floating-point numbers or complex numbers as arguments. They will also accept
any Python object that has either a <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> or a <a class="reference internal" href="../reference/datamodel.html#object.__float__" title="object.__float__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__float__()</span></code></a>
method: these methods are used to convert the object to a complex or
floating-point number, respectively, and the function is then applied to the
result of the conversion.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On platforms with hardware and system-level support for signed
zeros, functions involving branch cuts are continuous on <em>both</em>
sides of the branch cut: the sign of the zero distinguishes one
side of the branch cut from the other.  On platforms that do not
support signed zeros the continuity is as specified below.</p>
</div>
<div class="section" id="conversions-to-and-from-polar-coordinates">
<h2>9.3.1. Conversions to and from polar coordinates<a class="headerlink" href="#conversions-to-and-from-polar-coordinates" title="Permalink to this headline">¶</a></h2>
<p>A Python complex number <code class="docutils literal notranslate"><span class="pre">z</span></code> is stored internally using <em>rectangular</em>
or <em>Cartesian</em> coordinates.  It is completely determined by its <em>real
part</em> <code class="docutils literal notranslate"><span class="pre">z.real</span></code> and its <em>imaginary part</em> <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>.  In other
words:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">z</span> <span class="o">==</span> <span class="n">z</span><span class="o">.</span><span class="n">real</span> <span class="o">+</span> <span class="n">z</span><span class="o">.</span><span class="n">imag</span><span class="o">*</span><span class="mi">1</span><span class="n">j</span>
</pre></div>
</div>
<p><em>Polar coordinates</em> give an alternative way to represent a complex
number.  In polar coordinates, a complex number <em>z</em> is defined by the
modulus <em>r</em> and the phase angle <em>phi</em>. The modulus <em>r</em> is the distance
from <em>z</em> to the origin, while the phase <em>phi</em> is the counterclockwise
angle, measured in radians, from the positive x-axis to the line
segment that joins the origin to <em>z</em>.</p>
<p>The following functions can be used to convert from the native
rectangular coordinates to polar coordinates and back.</p>
<dl class="function">
<dt id="cmath.phase">
<code class="descclassname">cmath.</code><code class="descname">phase</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.phase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the phase of <em>x</em> (also known as the <em>argument</em> of <em>x</em>), as a
float.  <code class="docutils literal notranslate"><span class="pre">phase(x)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">math.atan2(x.imag,</span>
<span class="pre">x.real)</span></code>.  The result lies in the range [-π, π], and the branch
cut for this operation lies along the negative real axis,
continuous from above.  On systems with support for signed zeros
(which includes most systems in current use), this means that the
sign of the result is the same as the sign of <code class="docutils literal notranslate"><span class="pre">x.imag</span></code>, even when
<code class="docutils literal notranslate"><span class="pre">x.imag</span></code> is zero:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">phase</span><span class="p">(</span><span class="nb">complex</span><span class="p">(</span><span class="o">-</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">))</span>
<span class="go">3.1415926535897931</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">phase</span><span class="p">(</span><span class="nb">complex</span><span class="p">(</span><span class="o">-</span><span class="mf">1.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.0</span><span class="p">))</span>
<span class="go">-3.1415926535897931</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The modulus (absolute value) of a complex number <em>x</em> can be
computed using the built-in <a class="reference internal" href="functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function.  There is no
separate <a class="reference internal" href="#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module function for this operation.</p>
</div>
<dl class="function">
<dt id="cmath.polar">
<code class="descclassname">cmath.</code><code class="descname">polar</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.polar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the representation of <em>x</em> in polar coordinates.  Returns a
pair <code class="docutils literal notranslate"><span class="pre">(r,</span> <span class="pre">phi)</span></code> where <em>r</em> is the modulus of <em>x</em> and phi is the
phase of <em>x</em>.  <code class="docutils literal notranslate"><span class="pre">polar(x)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">(abs(x),</span>
<span class="pre">phase(x))</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.rect">
<code class="descclassname">cmath.</code><code class="descname">rect</code><span class="sig-paren">(</span><em>r</em>, <em>phi</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.rect" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the complex number <em>x</em> with polar coordinates <em>r</em> and <em>phi</em>.
Equivalent to <code class="docutils literal notranslate"><span class="pre">r</span> <span class="pre">*</span> <span class="pre">(math.cos(phi)</span> <span class="pre">+</span> <span class="pre">math.sin(phi)*1j)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="power-and-logarithmic-functions">
<h2>9.3.2. Power and logarithmic functions<a class="headerlink" href="#power-and-logarithmic-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="cmath.exp">
<code class="descclassname">cmath.</code><code class="descname">exp</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.exp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the exponential value <code class="docutils literal notranslate"><span class="pre">e**x</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.log">
<code class="descclassname">cmath.</code><code class="descname">log</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>base</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cmath.log" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the logarithm of <em>x</em> to the given <em>base</em>. If the <em>base</em> is not
specified, returns the natural logarithm of <em>x</em>. There is one branch cut, from 0
along the negative real axis to -∞, continuous from above.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>base</em> argument added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.log10">
<code class="descclassname">cmath.</code><code class="descname">log10</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.log10" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the base-10 logarithm of <em>x</em>. This has the same branch cut as
<a class="reference internal" href="#cmath.log" title="cmath.log"><code class="xref py py-func docutils literal notranslate"><span class="pre">log()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.sqrt">
<code class="descclassname">cmath.</code><code class="descname">sqrt</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.sqrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the square root of <em>x</em>. This has the same branch cut as <a class="reference internal" href="#cmath.log" title="cmath.log"><code class="xref py py-func docutils literal notranslate"><span class="pre">log()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="trigonometric-functions">
<h2>9.3.3. Trigonometric functions<a class="headerlink" href="#trigonometric-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="cmath.acos">
<code class="descclassname">cmath.</code><code class="descname">acos</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.acos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc cosine of <em>x</em>. There are two branch cuts: One extends right from
1 along the real axis to ∞, continuous from below. The other extends left from
-1 along the real axis to -∞, continuous from above.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.asin">
<code class="descclassname">cmath.</code><code class="descname">asin</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.asin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc sine of <em>x</em>. This has the same branch cuts as <a class="reference internal" href="#cmath.acos" title="cmath.acos"><code class="xref py py-func docutils literal notranslate"><span class="pre">acos()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.atan">
<code class="descclassname">cmath.</code><code class="descname">atan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.atan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc tangent of <em>x</em>. There are two branch cuts: One extends from
<code class="docutils literal notranslate"><span class="pre">1j</span></code> along the imaginary axis to <code class="docutils literal notranslate"><span class="pre">∞j</span></code>, continuous from the right. The
other extends from <code class="docutils literal notranslate"><span class="pre">-1j</span></code> along the imaginary axis to <code class="docutils literal notranslate"><span class="pre">-∞j</span></code>, continuous
from the left.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>direction of continuity of upper cut reversed</p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.cos">
<code class="descclassname">cmath.</code><code class="descname">cos</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.cos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the cosine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.sin">
<code class="descclassname">cmath.</code><code class="descname">sin</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.sin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.tan">
<code class="descclassname">cmath.</code><code class="descname">tan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.tan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the tangent of <em>x</em>.</p>
</dd></dl>

</div>
<div class="section" id="hyperbolic-functions">
<h2>9.3.4. Hyperbolic functions<a class="headerlink" href="#hyperbolic-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="cmath.acosh">
<code class="descclassname">cmath.</code><code class="descname">acosh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.acosh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic cosine of <em>x</em>. There is one branch cut,
extending left from 1 along the real axis to -∞, continuous from above.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.asinh">
<code class="descclassname">cmath.</code><code class="descname">asinh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.asinh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic sine of <em>x</em>. There are two branch cuts:
One extends from <code class="docutils literal notranslate"><span class="pre">1j</span></code> along the imaginary axis to <code class="docutils literal notranslate"><span class="pre">∞j</span></code>,
continuous from the right.  The other extends from <code class="docutils literal notranslate"><span class="pre">-1j</span></code> along
the imaginary axis to <code class="docutils literal notranslate"><span class="pre">-∞j</span></code>, continuous from the left.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>branch cuts moved to match those recommended by the C99 standard</p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.atanh">
<code class="descclassname">cmath.</code><code class="descname">atanh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.atanh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic tangent of <em>x</em>. There are two branch cuts: One
extends from <code class="docutils literal notranslate"><span class="pre">1</span></code> along the real axis to <code class="docutils literal notranslate"><span class="pre">∞</span></code>, continuous from below. The
other extends from <code class="docutils literal notranslate"><span class="pre">-1</span></code> along the real axis to <code class="docutils literal notranslate"><span class="pre">-∞</span></code>, continuous from
above.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>direction of continuity of right cut reversed</p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.cosh">
<code class="descclassname">cmath.</code><code class="descname">cosh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.cosh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic cosine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.sinh">
<code class="descclassname">cmath.</code><code class="descname">sinh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.sinh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic sine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="cmath.tanh">
<code class="descclassname">cmath.</code><code class="descname">tanh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.tanh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic tangent of <em>x</em>.</p>
</dd></dl>

</div>
<div class="section" id="classification-functions">
<h2>9.3.5. Classification functions<a class="headerlink" href="#classification-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="cmath.isinf">
<code class="descclassname">cmath.</code><code class="descname">isinf</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.isinf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the real or the imaginary part of x is positive
or negative infinity.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmath.isnan">
<code class="descclassname">cmath.</code><code class="descname">isnan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#cmath.isnan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the real or imaginary part of x is not a number (NaN).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="constants">
<h2>9.3.6. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h2>
<dl class="data">
<dt id="cmath.pi">
<code class="descclassname">cmath.</code><code class="descname">pi</code><a class="headerlink" href="#cmath.pi" title="Permalink to this definition">¶</a></dt>
<dd><p>The mathematical constant <em>π</em>, as a float.</p>
</dd></dl>

<dl class="data">
<dt id="cmath.e">
<code class="descclassname">cmath.</code><code class="descname">e</code><a class="headerlink" href="#cmath.e" title="Permalink to this definition">¶</a></dt>
<dd><p>The mathematical constant <em>e</em>, as a float.</p>
</dd></dl>

<p id="index-0">Note that the selection of functions is similar, but not identical, to that in
module <a class="reference internal" href="math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a>.  The reason for having two modules is that some users aren’t
interested in complex numbers, and perhaps don’t even know what they are.  They
would rather have <code class="docutils literal notranslate"><span class="pre">math.sqrt(-1)</span></code> raise an exception than return a complex
number. Also note that the functions defined in <a class="reference internal" href="#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> always return a
complex number, even if the answer can be expressed as a real number (in which
case the complex number has an imaginary part of zero).</p>
<p>A note on branch cuts: They are curves along which the given function fails to
be continuous.  They are a necessary feature of many complex functions.  It is
assumed that if you need to compute with complex functions, you will understand
about branch cuts.  Consult almost any (not too elementary) book on complex
variables for enlightenment.  For information of the proper choice of branch
cuts for numerical purposes, a good reference should be the following:</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">Kahan, W:  Branch cuts for complex elementary functions; or, Much ado about
nothing’s sign bit.  In Iserles, A., and Powell, M. (eds.), The state of the art
in numerical analysis. Clarendon Press (1987) pp165–211.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a><ul>
<li><a class="reference internal" href="#conversions-to-and-from-polar-coordinates">9.3.1. Conversions to and from polar coordinates</a></li>
<li><a class="reference internal" href="#power-and-logarithmic-functions">9.3.2. Power and logarithmic functions</a></li>
<li><a class="reference internal" href="#trigonometric-functions">9.3.3. Trigonometric functions</a></li>
<li><a class="reference internal" href="#hyperbolic-functions">9.3.4. Hyperbolic functions</a></li>
<li><a class="reference internal" href="#classification-functions">9.3.5. Classification functions</a></li>
<li><a class="reference internal" href="#constants">9.3.6. Constants</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="math.html"
                        title="previous chapter">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="decimal.html"
                        title="next chapter">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cmath.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="decimal.html" title="9.4. decimal — Decimal fixed point and floating point arithmetic"
             >next</a> |</li>
        <li class="right" >
          <a href="math.html" title="9.2. math — Mathematical functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\<�D'rqrqhtml/library/cmd.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>23.1. cmd — Support for line-oriented command interpreters &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="23.2. shlex — Simple lexical analysis" href="shlex.html" />
    <link rel="prev" title="23. Program Frameworks" href="frameworks.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cmd.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shlex.html" title="23.2. shlex — Simple lexical analysis"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="frameworks.html" title="23. Program Frameworks"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="frameworks.html" accesskey="U">23. Program Frameworks</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cmd">
<span id="cmd-support-for-line-oriented-command-interpreters"></span><h1>23.1. <a class="reference internal" href="#module-cmd" title="cmd: Build line-oriented command interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmd</span></code></a> — Support for line-oriented command interpreters<a class="headerlink" href="#module-cmd" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/cmd.py">Lib/cmd.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> class provides a simple framework for writing line-oriented
command interpreters.  These are often useful for test harnesses, administrative
tools, and prototypes that will later be wrapped in a more sophisticated
interface.</p>
<dl class="class">
<dt id="cmd.Cmd">
<em class="property">class </em><code class="descclassname">cmd.</code><code class="descname">Cmd</code><span class="sig-paren">(</span><span class="optional">[</span><em>completekey</em><span class="optional">[</span>, <em>stdin</em><span class="optional">[</span>, <em>stdout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> instance or subclass instance is a line-oriented interpreter
framework.  There is no good reason to instantiate <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> itself; rather,
it’s useful as a superclass of an interpreter class you define yourself in order
to inherit <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a>’s methods and encapsulate action methods.</p>
<p>The optional argument <em>completekey</em> is the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> name of a completion
key; it defaults to <kbd class="kbd docutils literal notranslate">Tab</kbd>. If <em>completekey</em> is not <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and
<a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> is available, command completion is done automatically.</p>
<p>The optional arguments <em>stdin</em> and <em>stdout</em> specify the  input and output file
objects that the Cmd instance or subclass  instance will use for input and
output. If not specified, they will default to <a class="reference internal" href="sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a> and
<a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>.</p>
<p>If you want a given <em>stdin</em> to be used, make sure to set the instance’s
<a class="reference internal" href="#cmd.Cmd.use_rawinput" title="cmd.Cmd.use_rawinput"><code class="xref py py-attr docutils literal notranslate"><span class="pre">use_rawinput</span></code></a> attribute to <code class="docutils literal notranslate"><span class="pre">False</span></code>, otherwise <em>stdin</em> will be
ignored.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The <em>stdin</em> and <em>stdout</em> parameters were added.</p>
</div>
</dd></dl>

<div class="section" id="cmd-objects">
<span id="id1"></span><h2>23.1.1. Cmd Objects<a class="headerlink" href="#cmd-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="cmd.Cmd.cmdloop">
<code class="descclassname">Cmd.</code><code class="descname">cmdloop</code><span class="sig-paren">(</span><span class="optional">[</span><em>intro</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.cmdloop" title="Permalink to this definition">¶</a></dt>
<dd><p>Repeatedly issue a prompt, accept input, parse an initial prefix off the
received input, and dispatch to action methods, passing them the remainder of
the line as argument.</p>
<p>The optional argument is a banner or intro string to be issued before the first
prompt (this overrides the <a class="reference internal" href="#cmd.Cmd.intro" title="cmd.Cmd.intro"><code class="xref py py-attr docutils literal notranslate"><span class="pre">intro</span></code></a> class attribute).</p>
<p>If the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module is loaded, input will automatically inherit
<strong class="program">bash</strong>-like history-list editing (e.g. <kbd class="kbd docutils literal notranslate">Control-P</kbd> scrolls back
to the last command, <kbd class="kbd docutils literal notranslate">Control-N</kbd> forward to the next one, <kbd class="kbd docutils literal notranslate">Control-F</kbd>
moves the cursor to the right non-destructively, <kbd class="kbd docutils literal notranslate">Control-B</kbd> moves the
cursor to the left non-destructively, etc.).</p>
<p>An end-of-file on input is passed back as the string <code class="docutils literal notranslate"><span class="pre">'EOF'</span></code>.</p>
<p>An interpreter instance will recognize a command name <code class="docutils literal notranslate"><span class="pre">foo</span></code> if and only if it
has a method <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_foo()</span></code>.  As a special case, a line beginning with the
character <code class="docutils literal notranslate"><span class="pre">'?'</span></code> is dispatched to the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_help()</span></code>.  As another
special case, a line beginning with the character <code class="docutils literal notranslate"><span class="pre">'!'</span></code> is dispatched to the
method <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_shell()</span></code> (if such a method is defined).</p>
<p>This method will return when the <a class="reference internal" href="#cmd.Cmd.postcmd" title="cmd.Cmd.postcmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">postcmd()</span></code></a> method returns a true value.
The <em>stop</em> argument to <a class="reference internal" href="#cmd.Cmd.postcmd" title="cmd.Cmd.postcmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">postcmd()</span></code></a> is the return value from the command’s
corresponding <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code> method.</p>
<p>If completion is enabled, completing commands will be done automatically, and
completing of commands args is done by calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">complete_foo()</span></code> with
arguments <em>text</em>, <em>line</em>, <em>begidx</em>, and <em>endidx</em>.  <em>text</em> is the string prefix
we are attempting to match: all returned matches must begin with it. <em>line</em> is
the current input line with leading whitespace removed, <em>begidx</em> and <em>endidx</em>
are the beginning and ending indexes of the prefix text, which could be used to
provide different completion depending upon which position the argument is in.</p>
<p>All subclasses of <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> inherit a predefined <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_help()</span></code>.  This
method, called with an argument <code class="docutils literal notranslate"><span class="pre">'bar'</span></code>, invokes the corresponding method
<code class="xref py py-meth docutils literal notranslate"><span class="pre">help_bar()</span></code>, and if that is not present, prints the docstring of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_bar()</span></code>, if available.  With no argument, <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_help()</span></code> lists all
available help topics (that is, all commands with corresponding
<code class="xref py py-meth docutils literal notranslate"><span class="pre">help_*()</span></code> methods or commands that have docstrings), and also lists any
undocumented commands.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.onecmd">
<code class="descclassname">Cmd.</code><code class="descname">onecmd</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.onecmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Interpret the argument as though it had been typed in response to the prompt.
This may be overridden, but should not normally need to be; see the
<a class="reference internal" href="#cmd.Cmd.precmd" title="cmd.Cmd.precmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">precmd()</span></code></a> and <a class="reference internal" href="#cmd.Cmd.postcmd" title="cmd.Cmd.postcmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">postcmd()</span></code></a> methods for useful execution hooks.  The
return value is a flag indicating whether interpretation of commands by the
interpreter should stop.  If there is a <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code> method for the command
<em>str</em>, the return value of that method is returned, otherwise the return value
from the <a class="reference internal" href="#cmd.Cmd.default" title="cmd.Cmd.default"><code class="xref py py-meth docutils literal notranslate"><span class="pre">default()</span></code></a> method is returned.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.emptyline">
<code class="descclassname">Cmd.</code><code class="descname">emptyline</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.emptyline" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called when an empty line is entered in response to the prompt. If this
method is not overridden, it repeats the last nonempty command entered.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.default">
<code class="descclassname">Cmd.</code><code class="descname">default</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.default" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called on an input line when the command prefix is not recognized. If
this method is not overridden, it prints an error message and returns.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.completedefault">
<code class="descclassname">Cmd.</code><code class="descname">completedefault</code><span class="sig-paren">(</span><em>text</em>, <em>line</em>, <em>begidx</em>, <em>endidx</em><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.completedefault" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called to complete an input line when no command-specific
<code class="xref py py-meth docutils literal notranslate"><span class="pre">complete_*()</span></code> method is available.  By default, it returns an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.precmd">
<code class="descclassname">Cmd.</code><code class="descname">precmd</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.precmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Hook method executed just before the command line <em>line</em> is interpreted, but
after the input prompt is generated and issued.  This method is a stub in
<a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a>; it exists to be overridden by subclasses.  The return value is
used as the command which will be executed by the <a class="reference internal" href="#cmd.Cmd.onecmd" title="cmd.Cmd.onecmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">onecmd()</span></code></a> method; the
<a class="reference internal" href="#cmd.Cmd.precmd" title="cmd.Cmd.precmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">precmd()</span></code></a> implementation may re-write the command or simply return <em>line</em>
unchanged.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.postcmd">
<code class="descclassname">Cmd.</code><code class="descname">postcmd</code><span class="sig-paren">(</span><em>stop</em>, <em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.postcmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Hook method executed just after a command dispatch is finished.  This method is
a stub in <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a>; it exists to be overridden by subclasses.  <em>line</em> is the
command line which was executed, and <em>stop</em> is a flag which indicates whether
execution will be terminated after the call to <a class="reference internal" href="#cmd.Cmd.postcmd" title="cmd.Cmd.postcmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">postcmd()</span></code></a>; this will be the
return value of the <a class="reference internal" href="#cmd.Cmd.onecmd" title="cmd.Cmd.onecmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">onecmd()</span></code></a> method.  The return value of this method will
be used as the new value for the internal flag which corresponds to <em>stop</em>;
returning false will cause interpretation to continue.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.preloop">
<code class="descclassname">Cmd.</code><code class="descname">preloop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.preloop" title="Permalink to this definition">¶</a></dt>
<dd><p>Hook method executed once when <a class="reference internal" href="#cmd.Cmd.cmdloop" title="cmd.Cmd.cmdloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cmdloop()</span></code></a> is called.  This method is a stub
in <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a>; it exists to be overridden by subclasses.</p>
</dd></dl>

<dl class="method">
<dt id="cmd.Cmd.postloop">
<code class="descclassname">Cmd.</code><code class="descname">postloop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cmd.Cmd.postloop" title="Permalink to this definition">¶</a></dt>
<dd><p>Hook method executed once when <a class="reference internal" href="#cmd.Cmd.cmdloop" title="cmd.Cmd.cmdloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cmdloop()</span></code></a> is about to return. This method
is a stub in <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a>; it exists to be overridden by subclasses.</p>
</dd></dl>

<p>Instances of <a class="reference internal" href="#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cmd</span></code></a> subclasses have some public instance variables:</p>
<dl class="attribute">
<dt id="cmd.Cmd.prompt">
<code class="descclassname">Cmd.</code><code class="descname">prompt</code><a class="headerlink" href="#cmd.Cmd.prompt" title="Permalink to this definition">¶</a></dt>
<dd><p>The prompt issued to solicit input.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.identchars">
<code class="descclassname">Cmd.</code><code class="descname">identchars</code><a class="headerlink" href="#cmd.Cmd.identchars" title="Permalink to this definition">¶</a></dt>
<dd><p>The string of characters accepted for the command prefix.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.lastcmd">
<code class="descclassname">Cmd.</code><code class="descname">lastcmd</code><a class="headerlink" href="#cmd.Cmd.lastcmd" title="Permalink to this definition">¶</a></dt>
<dd><p>The last nonempty command prefix seen.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.cmdqueue">
<code class="descclassname">Cmd.</code><code class="descname">cmdqueue</code><a class="headerlink" href="#cmd.Cmd.cmdqueue" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of queued input lines.  The cmdqueue list is checked in
<a class="reference internal" href="#cmd.Cmd.cmdloop" title="cmd.Cmd.cmdloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cmdloop()</span></code></a> when new input is needed; if it is nonempty, its elements
will be processed in order, as if entered at the prompt.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.intro">
<code class="descclassname">Cmd.</code><code class="descname">intro</code><a class="headerlink" href="#cmd.Cmd.intro" title="Permalink to this definition">¶</a></dt>
<dd><p>A string to issue as an intro or banner.  May be overridden by giving the
<a class="reference internal" href="#cmd.Cmd.cmdloop" title="cmd.Cmd.cmdloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cmdloop()</span></code></a> method an argument.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.doc_header">
<code class="descclassname">Cmd.</code><code class="descname">doc_header</code><a class="headerlink" href="#cmd.Cmd.doc_header" title="Permalink to this definition">¶</a></dt>
<dd><p>The header to issue if the help output has a section for documented commands.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.misc_header">
<code class="descclassname">Cmd.</code><code class="descname">misc_header</code><a class="headerlink" href="#cmd.Cmd.misc_header" title="Permalink to this definition">¶</a></dt>
<dd><p>The header to issue if the help output has a section for miscellaneous  help
topics (that is, there are <code class="xref py py-meth docutils literal notranslate"><span class="pre">help_*()</span></code> methods without corresponding
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code> methods).</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.undoc_header">
<code class="descclassname">Cmd.</code><code class="descname">undoc_header</code><a class="headerlink" href="#cmd.Cmd.undoc_header" title="Permalink to this definition">¶</a></dt>
<dd><p>The header to issue if the help output has a section for undocumented  commands
(that is, there are <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_*()</span></code> methods without corresponding <code class="xref py py-meth docutils literal notranslate"><span class="pre">help_*()</span></code>
methods).</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.ruler">
<code class="descclassname">Cmd.</code><code class="descname">ruler</code><a class="headerlink" href="#cmd.Cmd.ruler" title="Permalink to this definition">¶</a></dt>
<dd><p>The character used to draw separator lines under the help-message headers.  If
empty, no ruler line is drawn.  It defaults to <code class="docutils literal notranslate"><span class="pre">'='</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cmd.Cmd.use_rawinput">
<code class="descclassname">Cmd.</code><code class="descname">use_rawinput</code><a class="headerlink" href="#cmd.Cmd.use_rawinput" title="Permalink to this definition">¶</a></dt>
<dd><p>A flag, defaulting to true.  If true, <a class="reference internal" href="#cmd.Cmd.cmdloop" title="cmd.Cmd.cmdloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cmdloop()</span></code></a> uses <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> to
display a prompt and read the next command; if false, <code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.stdout.write()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.stdin.readline()</span></code> are used. (This means that by importing
<a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a>, on systems that support it, the interpreter will automatically
support <strong class="program">Emacs</strong>-like line editing  and command-history keystrokes.)</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a><ul>
<li><a class="reference internal" href="#cmd-objects">23.1.1. Cmd Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="frameworks.html"
                        title="previous chapter">23. Program Frameworks</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="shlex.html"
                        title="next chapter">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cmd.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shlex.html" title="23.2. shlex — Simple lexical analysis"
             >next</a> |</li>
        <li class="right" >
          <a href="frameworks.html" title="23. Program Frameworks"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="frameworks.html" >23. Program Frameworks</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\v�[`OiOihtml/library/code.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>29.1. code — Interpreter base classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="29.2. codeop — Compile Python code" href="codeop.html" />
    <link rel="prev" title="29. Custom Python Interpreters" href="custominterp.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/code.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codeop.html" title="29.2. codeop — Compile Python code"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="custominterp.html" title="29. Custom Python Interpreters"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="custominterp.html" accesskey="U">29. Custom Python Interpreters</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-code">
<span id="code-interpreter-base-classes"></span><h1>29.1. <a class="reference internal" href="#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> — Interpreter base classes<a class="headerlink" href="#module-code" title="Permalink to this headline">¶</a></h1>
<p>The <code class="docutils literal notranslate"><span class="pre">code</span></code> module provides facilities to implement read-eval-print loops in
Python.  Two classes and convenience functions are included which can be used to
build applications which provide an interactive interpreter prompt.</p>
<dl class="class">
<dt id="code.InteractiveInterpreter">
<em class="property">class </em><code class="descclassname">code.</code><code class="descname">InteractiveInterpreter</code><span class="sig-paren">(</span><span class="optional">[</span><em>locals</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter" title="Permalink to this definition">¶</a></dt>
<dd><p>This class deals with parsing and interpreter state (the user’s namespace); it
does not deal with input buffering or prompting or input file naming (the
filename is always passed in explicitly). The optional <em>locals</em> argument
specifies the dictionary in which code will be executed; it defaults to a newly
created dictionary with key <code class="docutils literal notranslate"><span class="pre">'__name__'</span></code> set to <code class="docutils literal notranslate"><span class="pre">'__console__'</span></code> and key
<code class="docutils literal notranslate"><span class="pre">'__doc__'</span></code> set to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="code.InteractiveConsole">
<em class="property">class </em><code class="descclassname">code.</code><code class="descname">InteractiveConsole</code><span class="sig-paren">(</span><span class="optional">[</span><em>locals</em><span class="optional">[</span>, <em>filename</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole" title="Permalink to this definition">¶</a></dt>
<dd><p>Closely emulate the behavior of the interactive Python interpreter. This class
builds on <a class="reference internal" href="#code.InteractiveInterpreter" title="code.InteractiveInterpreter"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveInterpreter</span></code></a> and adds prompting using the familiar
<code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>, and input buffering.</p>
</dd></dl>

<dl class="function">
<dt id="code.interact">
<code class="descclassname">code.</code><code class="descname">interact</code><span class="sig-paren">(</span><span class="optional">[</span><em>banner</em><span class="optional">[</span>, <em>readfunc</em><span class="optional">[</span>, <em>local</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.interact" title="Permalink to this definition">¶</a></dt>
<dd><p>Convenience function to run a read-eval-print loop.  This creates a new instance
of <a class="reference internal" href="#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code></a> and sets <em>readfunc</em> to be used as the
<a class="reference internal" href="#code.InteractiveConsole.raw_input" title="code.InteractiveConsole.raw_input"><code class="xref py py-meth docutils literal notranslate"><span class="pre">InteractiveConsole.raw_input()</span></code></a> method, if provided.  If <em>local</em> is
provided, it is passed to the <a class="reference internal" href="#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code></a> constructor for
use as the default namespace for the interpreter loop.  The <a class="reference internal" href="#code.interact" title="code.interact"><code class="xref py py-meth docutils literal notranslate"><span class="pre">interact()</span></code></a>
method of the instance is then run with <em>banner</em> passed as the banner to
use, if provided.  The console object is discarded after use.</p>
</dd></dl>

<dl class="function">
<dt id="code.compile_command">
<code class="descclassname">code.</code><code class="descname">compile_command</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>symbol</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.compile_command" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is useful for programs that want to emulate Python’s interpreter
main loop (a.k.a. the read-eval-print loop).  The tricky part is to determine
when the user has entered an incomplete command that can be completed by
entering more text (as opposed to a complete command or a syntax error).  This
function <em>almost</em> always makes the same decision as the real interpreter main
loop.</p>
<p><em>source</em> is the source string; <em>filename</em> is the optional filename from which
source was read, defaulting to <code class="docutils literal notranslate"><span class="pre">'&lt;input&gt;'</span></code>; and <em>symbol</em> is the optional
grammar start symbol, which should be either <code class="docutils literal notranslate"><span class="pre">'single'</span></code> (the default) or
<code class="docutils literal notranslate"><span class="pre">'eval'</span></code>.</p>
<p>Returns a code object (the same as <code class="docutils literal notranslate"><span class="pre">compile(source,</span> <span class="pre">filename,</span> <span class="pre">symbol)</span></code>) if the
command is complete and valid; <code class="docutils literal notranslate"><span class="pre">None</span></code> if the command is incomplete; raises
<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if the command is complete and contains a syntax error, or
raises <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if the command contains an
invalid literal.</p>
</dd></dl>

<div class="section" id="interactive-interpreter-objects">
<span id="interpreter-objects"></span><h2>29.1.1. Interactive Interpreter Objects<a class="headerlink" href="#interactive-interpreter-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="code.InteractiveInterpreter.runsource">
<code class="descclassname">InteractiveInterpreter.</code><code class="descname">runsource</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>symbol</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.runsource" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile and run some source in the interpreter. Arguments are the same as for
<a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a>; the default for <em>filename</em> is <code class="docutils literal notranslate"><span class="pre">'&lt;input&gt;'</span></code>, and for
<em>symbol</em> is <code class="docutils literal notranslate"><span class="pre">'single'</span></code>.  One several things can happen:</p>
<ul class="simple">
<li>The input is incorrect; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a> raised an exception
(<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>).  A syntax traceback will be
printed by calling the <a class="reference internal" href="#code.InteractiveInterpreter.showsyntaxerror" title="code.InteractiveInterpreter.showsyntaxerror"><code class="xref py py-meth docutils literal notranslate"><span class="pre">showsyntaxerror()</span></code></a> method.  <a class="reference internal" href="#code.InteractiveInterpreter.runsource" title="code.InteractiveInterpreter.runsource"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code></a>
returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</li>
<li>The input is incomplete, and more input is required; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a>
returned <code class="docutils literal notranslate"><span class="pre">None</span></code>. <a class="reference internal" href="#code.InteractiveInterpreter.runsource" title="code.InteractiveInterpreter.runsource"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>.</li>
<li>The input is complete; <a class="reference internal" href="#code.compile_command" title="code.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a> returned a code object.  The
code is executed by calling the <a class="reference internal" href="#code.InteractiveInterpreter.runcode" title="code.InteractiveInterpreter.runcode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runcode()</span></code></a> (which also handles run-time
exceptions, except for <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>). <a class="reference internal" href="#code.InteractiveInterpreter.runsource" title="code.InteractiveInterpreter.runsource"><code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</li>
</ul>
<p>The return value can be used to decide whether to use <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> or <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code>
to prompt the next line.</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveInterpreter.runcode">
<code class="descclassname">InteractiveInterpreter.</code><code class="descname">runcode</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.runcode" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute a code object. When an exception occurs, <a class="reference internal" href="#code.InteractiveInterpreter.showtraceback" title="code.InteractiveInterpreter.showtraceback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">showtraceback()</span></code></a> is called
to display a traceback.  All exceptions are caught except <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>,
which is allowed to propagate.</p>
<p>A note about <a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>: this exception may occur elsewhere in
this code, and may not always be caught.  The caller should be prepared to deal
with it.</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveInterpreter.showsyntaxerror">
<code class="descclassname">InteractiveInterpreter.</code><code class="descname">showsyntaxerror</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.showsyntaxerror" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the syntax error that just occurred.  This does not display a stack
trace because there isn’t one for syntax errors. If <em>filename</em> is given, it is
stuffed into the exception instead of the default filename provided by Python’s
parser, because it always uses <code class="docutils literal notranslate"><span class="pre">'&lt;string&gt;'</span></code> when reading from a string. The
output is written by the <a class="reference internal" href="#code.InteractiveInterpreter.write" title="code.InteractiveInterpreter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveInterpreter.showtraceback">
<code class="descclassname">InteractiveInterpreter.</code><code class="descname">showtraceback</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.showtraceback" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the exception that just occurred.  We remove the first stack item
because it is within the interpreter object implementation. The output is
written by the <a class="reference internal" href="#code.InteractiveInterpreter.write" title="code.InteractiveInterpreter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveInterpreter.write">
<code class="descclassname">InteractiveInterpreter.</code><code class="descname">write</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveInterpreter.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a string to the standard error stream (<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>). Derived classes
should override this to provide the appropriate output handling as needed.</p>
</dd></dl>

</div>
<div class="section" id="interactive-console-objects">
<span id="console-objects"></span><h2>29.1.2. Interactive Console Objects<a class="headerlink" href="#interactive-console-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveConsole</span></code></a> class is a subclass of
<a class="reference internal" href="#code.InteractiveInterpreter" title="code.InteractiveInterpreter"><code class="xref py py-class docutils literal notranslate"><span class="pre">InteractiveInterpreter</span></code></a>, and so offers all the methods of the
interpreter objects as well as the following additions.</p>
<dl class="method">
<dt id="code.InteractiveConsole.interact">
<code class="descclassname">InteractiveConsole.</code><code class="descname">interact</code><span class="sig-paren">(</span><span class="optional">[</span><em>banner</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.interact" title="Permalink to this definition">¶</a></dt>
<dd><p>Closely emulate the interactive Python console. The optional banner argument
specify the banner to print before the first interaction; by default it prints a
banner similar to the one printed by the standard Python interpreter, followed
by the class name of the console object in parentheses (so as not to confuse
this with the real interpreter – since it’s so close!).</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveConsole.push">
<code class="descclassname">InteractiveConsole.</code><code class="descname">push</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.push" title="Permalink to this definition">¶</a></dt>
<dd><p>Push a line of source text to the interpreter. The line should not have a
trailing newline; it may have internal newlines.  The line is appended to a
buffer and the interpreter’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code> method is called with the
concatenated contents of the buffer as source.  If this indicates that the
command was executed or invalid, the buffer is reset; otherwise, the command is
incomplete, and the buffer is left as it was after the line was appended.  The
return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> if more input is required, <code class="docutils literal notranslate"><span class="pre">False</span></code> if the line was
dealt with in some way (this is the same as <code class="xref py py-meth docutils literal notranslate"><span class="pre">runsource()</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveConsole.resetbuffer">
<code class="descclassname">InteractiveConsole.</code><code class="descname">resetbuffer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.resetbuffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove any unhandled source text from the input buffer.</p>
</dd></dl>

<dl class="method">
<dt id="code.InteractiveConsole.raw_input">
<code class="descclassname">InteractiveConsole.</code><code class="descname">raw_input</code><span class="sig-paren">(</span><span class="optional">[</span><em>prompt</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#code.InteractiveConsole.raw_input" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a prompt and read a line.  The returned line does not include the trailing
newline.  When the user enters the EOF key sequence, <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is raised.
The base implementation uses the built-in function <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a>; a subclass
may replace this with a different implementation.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a><ul>
<li><a class="reference internal" href="#interactive-interpreter-objects">29.1.1. Interactive Interpreter Objects</a></li>
<li><a class="reference internal" href="#interactive-console-objects">29.1.2. Interactive Console Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="custominterp.html"
                        title="previous chapter">29. Custom Python Interpreters</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="codeop.html"
                        title="next chapter">29.2. <code class="docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/code.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codeop.html" title="29.2. codeop — Compile Python code"
             >next</a> |</li>
        <li class="right" >
          <a href="custominterp.html" title="29. Custom Python Interpreters"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="custominterp.html" >29. Custom Python Interpreters</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�v�����html/library/codecs.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.8. codecs — Codec registry and base classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.9. unicodedata — Unicode Database" href="unicodedata.html" />
    <link rel="prev" title="7.7. textwrap — Text wrapping and filling" href="textwrap.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/codecs.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicodedata.html" title="7.9. unicodedata — Unicode Database"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="textwrap.html" title="7.7. textwrap — Text wrapping and filling"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-codecs">
<span id="codecs-codec-registry-and-base-classes"></span><h1>7.8. <a class="reference internal" href="#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> — Codec registry and base classes<a class="headerlink" href="#module-codecs" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module defines base classes for standard Python codecs (encoders and
decoders) and provides access to the internal Python codec registry which
manages the codec and error handling lookup process.</p>
<p>It defines the following functions:</p>
<dl class="function">
<dt id="codecs.encode">
<code class="descclassname">codecs.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes <em>obj</em> using the codec registered for <em>encoding</em>. The default
encoding is <code class="docutils literal notranslate"><span class="pre">'ascii'</span></code>.</p>
<p><em>Errors</em> may be given to set the desired error handling scheme. The
default error handler is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> meaning that encoding errors raise
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a more codec specific subclass, such as
<a class="reference internal" href="exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>). Refer to <a class="reference internal" href="#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a> for more
information on codec error handling.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="codecs.decode">
<code class="descclassname">codecs.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decodes <em>obj</em> using the codec registered for <em>encoding</em>. The default
encoding is <code class="docutils literal notranslate"><span class="pre">'ascii'</span></code>.</p>
<p><em>Errors</em> may be given to set the desired error handling scheme. The
default error handler is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> meaning that decoding errors raise
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a more codec specific subclass, such as
<a class="reference internal" href="exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a>). Refer to <a class="reference internal" href="#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a> for more
information on codec error handling.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="codecs.register">
<code class="descclassname">codecs.</code><code class="descname">register</code><span class="sig-paren">(</span><em>search_function</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a codec search function. Search functions are expected to take one
argument, the encoding name in all lower case letters, and return a
<code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> object having the following attributes:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">name</span></code> The name of the encoding;</li>
<li><code class="docutils literal notranslate"><span class="pre">encode</span></code> The stateless encoding function;</li>
<li><code class="docutils literal notranslate"><span class="pre">decode</span></code> The stateless decoding function;</li>
<li><code class="docutils literal notranslate"><span class="pre">incrementalencoder</span></code> An incremental encoder class or factory function;</li>
<li><code class="docutils literal notranslate"><span class="pre">incrementaldecoder</span></code> An incremental decoder class or factory function;</li>
<li><code class="docutils literal notranslate"><span class="pre">streamwriter</span></code> A stream writer class or factory function;</li>
<li><code class="docutils literal notranslate"><span class="pre">streamreader</span></code> A stream reader class or factory function.</li>
</ul>
<p>The various functions or classes take the following arguments:</p>
<p><em>encode</em> and <em>decode</em>: These must be functions or methods which have the same
interface as the <a class="reference internal" href="#codecs.Codec.encode" title="codecs.Codec.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a>/<a class="reference internal" href="#codecs.Codec.decode" title="codecs.Codec.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> methods of Codec
instances (see <a class="reference internal" href="#codec-objects"><span class="std std-ref">Codec Interface</span></a>). The functions/methods
are expected to work in a stateless mode.</p>
<p><em>incrementalencoder</em> and <em>incrementaldecoder</em>: These have to be factory
functions providing the following interface:</p>
<blockquote>
<div><code class="docutils literal notranslate"><span class="pre">factory(errors='strict')</span></code></div></blockquote>
<p>The factory functions must return objects providing the interfaces defined by
the base classes <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> and <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a>,
respectively. Incremental codecs can maintain state.</p>
<p><em>streamreader</em> and <em>streamwriter</em>: These have to be factory functions providing
the following interface:</p>
<blockquote>
<div><code class="docutils literal notranslate"><span class="pre">factory(stream,</span> <span class="pre">errors='strict')</span></code></div></blockquote>
<p>The factory functions must return objects providing the interfaces defined by
the base classes <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a>, respectively.
Stream codecs can maintain state.</p>
<p>Possible values for errors are</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'strict'</span></code>: raise an exception in case of an encoding error</li>
<li><code class="docutils literal notranslate"><span class="pre">'replace'</span></code>: replace malformed data with a suitable replacement marker,
such as <code class="docutils literal notranslate"><span class="pre">'?'</span></code> or <code class="docutils literal notranslate"><span class="pre">'\ufffd'</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>: ignore malformed data and continue without further notice</li>
<li><code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code>: replace with the appropriate XML character
reference (for encoding only)</li>
<li><code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code>: replace with backslashed escape sequences (for
encoding only)</li>
</ul>
<p>as well as any other error handling name defined via <a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<p>In case a search function cannot find a given encoding, it should return
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.lookup">
<code class="descclassname">codecs.</code><code class="descname">lookup</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.lookup" title="Permalink to this definition">¶</a></dt>
<dd><p>Looks up the codec info in the Python codec registry and returns a
<code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> object as defined above.</p>
<p>Encodings are first looked up in the registry’s cache. If not found, the list of
registered search functions is scanned. If no <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> object is
found, a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> is raised. Otherwise, the <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> object
is stored in the cache and returned to the caller.</p>
</dd></dl>

<p>To simplify access to the various codecs, the module provides these additional
functions which use <a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> for the codec lookup:</p>
<dl class="function">
<dt id="codecs.getencoder">
<code class="descclassname">codecs.</code><code class="descname">getencoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getencoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its encoder function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.getdecoder">
<code class="descclassname">codecs.</code><code class="descname">getdecoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getdecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its decoder function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.getincrementalencoder">
<code class="descclassname">codecs.</code><code class="descname">getincrementalencoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getincrementalencoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its incremental encoder
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found or the codec
doesn’t support an incremental encoder.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="codecs.getincrementaldecoder">
<code class="descclassname">codecs.</code><code class="descname">getincrementaldecoder</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getincrementaldecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its incremental decoder
class or factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found or the codec
doesn’t support an incremental decoder.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="codecs.getreader">
<code class="descclassname">codecs.</code><code class="descname">getreader</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getreader" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its StreamReader class or
factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.getwriter">
<code class="descclassname">codecs.</code><code class="descname">getwriter</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.getwriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the codec for the given encoding and return its StreamWriter class or
factory function.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the encoding cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.register_error">
<code class="descclassname">codecs.</code><code class="descname">register_error</code><span class="sig-paren">(</span><em>name</em>, <em>error_handler</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.register_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the error handling function <em>error_handler</em> under the name <em>name</em>.
<em>error_handler</em> will be called during encoding and decoding in case of an error,
when <em>name</em> is specified as the errors parameter.</p>
<p>For encoding <em>error_handler</em> will be called with a <a class="reference internal" href="exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>
instance, which contains information about the location of the error. The error
handler must either raise this or a different exception or return a tuple with a
replacement for the unencodable part of the input and a position where encoding
should continue. The encoder will encode the replacement and continue encoding
the original input at the specified position. Negative position values will be
treated as being relative to the end of the input string. If the resulting
position is out of bound an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> will be raised.</p>
<p>Decoding and translating works similar, except <a class="reference internal" href="exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a> or
<a class="reference internal" href="exceptions.html#exceptions.UnicodeTranslateError" title="exceptions.UnicodeTranslateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeTranslateError</span></code></a> will be passed to the handler and that the
replacement from the error handler will be put into the output directly.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.lookup_error">
<code class="descclassname">codecs.</code><code class="descname">lookup_error</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.lookup_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the error handler previously registered under the name <em>name</em>.</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> in case the handler cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.strict_errors">
<code class="descclassname">codecs.</code><code class="descname">strict_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.strict_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">strict</span></code> error handling: each encoding or decoding error
raises a <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.replace_errors">
<code class="descclassname">codecs.</code><code class="descname">replace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.replace_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">replace</span></code> error handling: malformed data is replaced with a
suitable replacement character such as <code class="docutils literal notranslate"><span class="pre">'?'</span></code> in bytestrings and
<code class="docutils literal notranslate"><span class="pre">'\ufffd'</span></code> in Unicode strings.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.ignore_errors">
<code class="descclassname">codecs.</code><code class="descname">ignore_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.ignore_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">ignore</span></code> error handling: malformed data is ignored and
encoding or decoding is continued without further notice.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.xmlcharrefreplace_errors">
<code class="descclassname">codecs.</code><code class="descname">xmlcharrefreplace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.xmlcharrefreplace_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">xmlcharrefreplace</span></code> error handling (for encoding only): the
unencodable character is replaced by an appropriate XML character reference.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.backslashreplace_errors">
<code class="descclassname">codecs.</code><code class="descname">backslashreplace_errors</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.backslashreplace_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the <code class="docutils literal notranslate"><span class="pre">backslashreplace</span></code> error handling (for encoding only): the
unencodable character is replaced by a backslashed escape sequence.</p>
</dd></dl>

<p>To simplify working with encoded files or stream, the module also defines these
utility functions:</p>
<dl class="function">
<dt id="codecs.open">
<code class="descclassname">codecs.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em>, <em>mode</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">[</span>, <em>buffering</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open an encoded file using the given <em>mode</em> and return a wrapped version
providing transparent encoding/decoding.  The default file mode is <code class="docutils literal notranslate"><span class="pre">'r'</span></code>
meaning to open the file in read mode.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The wrapped version will only accept the object format defined by the codecs,
i.e. Unicode objects for most built-in codecs.  Output is also codec-dependent
and will usually be Unicode as well.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Files are always opened in binary mode, even if no binary mode was
specified.  This is done to avoid data loss due to encodings using 8-bit
values.  This means that no automatic conversion of <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> is done
on reading and writing.</p>
</div>
<p><em>encoding</em> specifies the encoding which is to be used for the file.</p>
<p><em>errors</em> may be given to define the error handling. It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>
which causes a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to be raised in case an encoding error occurs.</p>
<p><em>buffering</em> has the same meaning as for the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.  It
defaults to line buffered.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.EncodedFile">
<code class="descclassname">codecs.</code><code class="descname">EncodedFile</code><span class="sig-paren">(</span><em>file</em>, <em>input</em><span class="optional">[</span>, <em>output</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.EncodedFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a wrapped version of file which provides transparent encoding
translation.</p>
<p>Strings written to the wrapped file are interpreted according to the given
<em>input</em> encoding and then written to the original file as strings using the
<em>output</em> encoding. The intermediate encoding will usually be Unicode but depends
on the specified codecs.</p>
<p>If <em>output</em> is not given, it defaults to <em>input</em>.</p>
<p><em>errors</em> may be given to define the error handling. It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>,
which causes <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to be raised in case an encoding error occurs.</p>
</dd></dl>

<dl class="function">
<dt id="codecs.iterencode">
<code class="descclassname">codecs.</code><code class="descname">iterencode</code><span class="sig-paren">(</span><em>iterable</em>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.iterencode" title="Permalink to this definition">¶</a></dt>
<dd><p>Uses an incremental encoder to iteratively encode the input provided by
<em>iterable</em>. This function is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>.  <em>errors</em> (as well as any
other keyword argument) is passed through to the incremental encoder.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="codecs.iterdecode">
<code class="descclassname">codecs.</code><code class="descname">iterdecode</code><span class="sig-paren">(</span><em>iterable</em>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.iterdecode" title="Permalink to this definition">¶</a></dt>
<dd><p>Uses an incremental decoder to iteratively decode the input provided by
<em>iterable</em>. This function is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>.  <em>errors</em> (as well as any
other keyword argument) is passed through to the incremental decoder.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>The module also provides the following constants which are useful for reading
and writing to platform dependent files:</p>
<dl class="data">
<dt id="codecs.BOM">
<code class="descclassname">codecs.</code><code class="descname">BOM</code><a class="headerlink" href="#codecs.BOM" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_BE</code><a class="headerlink" href="#codecs.BOM_BE" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_LE</code><a class="headerlink" href="#codecs.BOM_LE" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF8">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF8</code><a class="headerlink" href="#codecs.BOM_UTF8" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF16">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16</code><a class="headerlink" href="#codecs.BOM_UTF16" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF16_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16_BE</code><a class="headerlink" href="#codecs.BOM_UTF16_BE" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF16_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF16_LE</code><a class="headerlink" href="#codecs.BOM_UTF16_LE" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF32">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32</code><a class="headerlink" href="#codecs.BOM_UTF32" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF32_BE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32_BE</code><a class="headerlink" href="#codecs.BOM_UTF32_BE" title="Permalink to this definition">¶</a></dt>
<dt id="codecs.BOM_UTF32_LE">
<code class="descclassname">codecs.</code><code class="descname">BOM_UTF32_LE</code><a class="headerlink" href="#codecs.BOM_UTF32_LE" title="Permalink to this definition">¶</a></dt>
<dd><p>These constants define various encodings of the Unicode byte order mark (BOM)
used in UTF-16 and UTF-32 data streams to indicate the byte order used in the
stream or file and in UTF-8 as a Unicode signature. <a class="reference internal" href="#codecs.BOM_UTF16" title="codecs.BOM_UTF16"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16</span></code></a> is either
<a class="reference internal" href="#codecs.BOM_UTF16_BE" title="codecs.BOM_UTF16_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_BE</span></code></a> or <a class="reference internal" href="#codecs.BOM_UTF16_LE" title="codecs.BOM_UTF16_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_LE</span></code></a> depending on the platform’s
native byte order, <a class="reference internal" href="#codecs.BOM" title="codecs.BOM"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM</span></code></a> is an alias for <a class="reference internal" href="#codecs.BOM_UTF16" title="codecs.BOM_UTF16"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16</span></code></a>,
<a class="reference internal" href="#codecs.BOM_LE" title="codecs.BOM_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_LE</span></code></a> for <a class="reference internal" href="#codecs.BOM_UTF16_LE" title="codecs.BOM_UTF16_LE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_LE</span></code></a> and <a class="reference internal" href="#codecs.BOM_BE" title="codecs.BOM_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_BE</span></code></a> for
<a class="reference internal" href="#codecs.BOM_UTF16_BE" title="codecs.BOM_UTF16_BE"><code class="xref py py-const docutils literal notranslate"><span class="pre">BOM_UTF16_BE</span></code></a>. The others represent the BOM in UTF-8 and UTF-32
encodings.</p>
</dd></dl>

<div class="section" id="codec-base-classes">
<span id="id1"></span><h2>7.8.1. Codec Base Classes<a class="headerlink" href="#codec-base-classes" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module defines a set of base classes which define the
interface and can also be used to easily write your own codecs for use in
Python.</p>
<p>Each codec has to define four interfaces to make it usable as codec in Python:
stateless encoder, stateless decoder, stream reader and stream writer. The
stream reader and writers typically reuse the stateless encoder/decoder to
implement the file protocols.</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> class defines the interface for stateless encoders/decoders.</p>
<p>To simplify and standardize error handling, the <a class="reference internal" href="#codecs.Codec.encode" title="codecs.Codec.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a> and
<a class="reference internal" href="#codecs.Codec.decode" title="codecs.Codec.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> methods may implement different error handling schemes by
providing the <em>errors</em> string argument.  The following string values are defined
and implemented by all standard Python codecs:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'strict'</span></code></td>
<td>Raise <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> (or a subclass);
this is the default.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code></td>
<td>Ignore the character and continue with the
next.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'replace'</span></code></td>
<td>Replace with a suitable replacement
character; Python will use the official
U+FFFD REPLACEMENT CHARACTER for the built-in
Unicode codecs on decoding and ‘?’ on
encoding.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code></td>
<td>Replace with the appropriate XML character
reference (only for encoding).</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code></td>
<td>Replace with backslashed escape sequences
(only for encoding).</td>
</tr>
</tbody>
</table>
<p>The set of allowed values can be extended via <a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<div class="section" id="codec-objects">
<span id="id2"></span><h3>7.8.1.1. Codec Objects<a class="headerlink" href="#codec-objects" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> class defines these methods which also define the function
interfaces of the stateless encoder and decoder:</p>
<dl class="method">
<dt id="codecs.Codec.encode">
<code class="descclassname">Codec.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>input</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.Codec.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes the object <em>input</em> and returns a tuple (output object, length consumed).
While codecs are not restricted to use with Unicode, in a Unicode context,
encoding converts a Unicode object to a plain string using a particular
character set encoding (e.g., <code class="docutils literal notranslate"><span class="pre">cp1252</span></code> or <code class="docutils literal notranslate"><span class="pre">iso-8859-1</span></code>).</p>
<p><em>errors</em> defines the error handling to apply. It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>
handling.</p>
<p>The method may not store state in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> instance. Use
<a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> for codecs which have to keep state in order to make
encoding efficient.</p>
<p>The encoder must be able to handle zero length input and return an empty object
of the output object type in this situation.</p>
</dd></dl>

<dl class="method">
<dt id="codecs.Codec.decode">
<code class="descclassname">Codec.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>input</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.Codec.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decodes the object <em>input</em> and returns a tuple (output object, length consumed).
In a Unicode context, decoding converts a plain string encoded using a
particular character set encoding to a Unicode object.</p>
<p><em>input</em> must be an object which provides the <code class="docutils literal notranslate"><span class="pre">bf_getreadbuf</span></code> buffer slot.
Python strings, buffer objects and memory mapped files are examples of objects
providing this slot.</p>
<p><em>errors</em> defines the error handling to apply. It defaults to <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>
handling.</p>
<p>The method may not store state in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> instance. Use
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> for codecs which have to keep state in order to make
decoding efficient.</p>
<p>The decoder must be able to handle zero length input and return an empty object
of the output object type in this situation.</p>
</dd></dl>

<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> and <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> classes provide
the basic interface for incremental encoding and decoding. Encoding/decoding the
input isn’t done with one call to the stateless encoder/decoder function, but
with multiple calls to the
<a class="reference internal" href="#codecs.IncrementalEncoder.encode" title="codecs.IncrementalEncoder.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a>/<a class="reference internal" href="#codecs.IncrementalDecoder.decode" title="codecs.IncrementalDecoder.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method of
the incremental encoder/decoder. The incremental encoder/decoder keeps track of
the encoding/decoding process during method calls.</p>
<p>The joined output of calls to the
<a class="reference internal" href="#codecs.IncrementalEncoder.encode" title="codecs.IncrementalEncoder.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a>/<a class="reference internal" href="#codecs.IncrementalDecoder.decode" title="codecs.IncrementalDecoder.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method is
the same as if all the single inputs were joined into one, and this input was
encoded/decoded with the stateless encoder/decoder.</p>
</div>
<div class="section" id="incrementalencoder-objects">
<span id="incremental-encoder-objects"></span><h3>7.8.1.2. IncrementalEncoder Objects<a class="headerlink" href="#incrementalencoder-objects" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> class is used for encoding an input in multiple
steps. It defines the following methods which every incremental encoder must
define in order to be compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.IncrementalEncoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">IncrementalEncoder</code><span class="sig-paren">(</span><span class="optional">[</span><em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for an <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> instance.</p>
<p>All incremental encoders must provide this constructor interface. They are free
to add additional keyword arguments, but only the ones defined here are used by
the Python codec registry.</p>
<p>The <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a> may implement different error handling schemes
by providing the <em>errors</em> keyword argument. These parameters are predefined:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'strict'</span></code> Raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a subclass); this is the default.</li>
<li><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> Ignore the character and continue with the next.</li>
<li><code class="docutils literal notranslate"><span class="pre">'replace'</span></code> Replace with a suitable replacement character</li>
<li><code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code> Replace with the appropriate XML character reference</li>
<li><code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> Replace with backslashed escape sequences.</li>
</ul>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.IncrementalEncoder" title="codecs.IncrementalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalEncoder</span></code></a>
object.</p>
<p>The set of allowed values for the <em>errors</em> argument can be extended with
<a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<dl class="method">
<dt id="codecs.IncrementalEncoder.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>final</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes <em>object</em> (taking the current state of the encoder into account)
and returns the resulting encoded object. If this is the last call to
<a class="reference internal" href="#codecs.encode" title="codecs.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code></a> <em>final</em> must be true (the default is false).</p>
</dd></dl>

<dl class="method">
<dt id="codecs.IncrementalEncoder.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalEncoder.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the encoder to the initial state.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="incrementaldecoder-objects">
<span id="incremental-decoder-objects"></span><h3>7.8.1.3. IncrementalDecoder Objects<a class="headerlink" href="#incrementaldecoder-objects" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> class is used for decoding an input in multiple
steps. It defines the following methods which every incremental decoder must
define in order to be compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.IncrementalDecoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">IncrementalDecoder</code><span class="sig-paren">(</span><span class="optional">[</span><em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for an <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> instance.</p>
<p>All incremental decoders must provide this constructor interface. They are free
to add additional keyword arguments, but only the ones defined here are used by
the Python codec registry.</p>
<p>The <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a> may implement different error handling schemes
by providing the <em>errors</em> keyword argument. These parameters are predefined:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'strict'</span></code> Raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a subclass); this is the default.</li>
<li><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> Ignore the character and continue with the next.</li>
<li><code class="docutils literal notranslate"><span class="pre">'replace'</span></code> Replace with a suitable replacement character.</li>
</ul>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalDecoder</span></code></a>
object.</p>
<p>The set of allowed values for the <em>errors</em> argument can be extended with
<a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<dl class="method">
<dt id="codecs.IncrementalDecoder.decode">
<code class="descname">decode</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>final</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decodes <em>object</em> (taking the current state of the decoder into account)
and returns the resulting decoded object. If this is the last call to
<a class="reference internal" href="#codecs.decode" title="codecs.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> <em>final</em> must be true (the default is false). If <em>final</em> is
true the decoder must decode the input completely and must flush all
buffers. If this isn’t possible (e.g. because of incomplete byte sequences
at the end of the input) it must initiate error handling just like in the
stateless case (which might raise an exception).</p>
</dd></dl>

<dl class="method">
<dt id="codecs.IncrementalDecoder.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.IncrementalDecoder.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the decoder to the initial state.</p>
</dd></dl>

</dd></dl>

<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> and <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> classes provide generic
working interfaces which can be used to implement new encoding submodules very
easily. See <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.utf_8</span></code> for an example of how this is done.</p>
</div>
<div class="section" id="streamwriter-objects">
<span id="stream-writer-objects"></span><h3>7.8.1.4. StreamWriter Objects<a class="headerlink" href="#streamwriter-objects" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> class is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> and defines the
following methods which every stream writer must define in order to be
compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.StreamWriter">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamWriter</code><span class="sig-paren">(</span><em>stream</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for a <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> instance.</p>
<p>All stream writers must provide this constructor interface. They are free to add
additional keyword arguments, but only the ones defined here are used by the
Python codec registry.</p>
<p><em>stream</em> must be a file-like object open for writing binary data.</p>
<p>The <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> may implement different error handling schemes by
providing the <em>errors</em> keyword argument. These parameters are predefined:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'strict'</span></code> Raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a subclass); this is the default.</li>
<li><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> Ignore the character and continue with the next.</li>
<li><code class="docutils literal notranslate"><span class="pre">'replace'</span></code> Replace with a suitable replacement character</li>
<li><code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code> Replace with the appropriate XML character reference</li>
<li><code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> Replace with backslashed escape sequences.</li>
</ul>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> object.</p>
<p>The set of allowed values for the <em>errors</em> argument can be extended with
<a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<dl class="method">
<dt id="codecs.StreamWriter.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes the object’s contents encoded to the stream.</p>
</dd></dl>

<dl class="method">
<dt id="codecs.StreamWriter.writelines">
<code class="descname">writelines</code><span class="sig-paren">(</span><em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.writelines" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes the concatenated list of strings to the stream (possibly by reusing
the <a class="reference internal" href="#codecs.StreamWriter.write" title="codecs.StreamWriter.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method).</p>
</dd></dl>

<dl class="method">
<dt id="codecs.StreamWriter.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamWriter.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Flushes and resets the codec buffers used for keeping state.</p>
<p>Calling this method should ensure that the data on the output is put into
a clean state that allows appending of new fresh data without having to
rescan the whole stream to recover state.</p>
</dd></dl>

</dd></dl>

<p>In addition to the above methods, the <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> must also inherit
all other methods and attributes from the underlying stream.</p>
</div>
<div class="section" id="streamreader-objects">
<span id="stream-reader-objects"></span><h3>7.8.1.5. StreamReader Objects<a class="headerlink" href="#streamreader-objects" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> class is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> and defines the
following methods which every stream reader must define in order to be
compatible with the Python codec registry.</p>
<dl class="class">
<dt id="codecs.StreamReader">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamReader</code><span class="sig-paren">(</span><em>stream</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for a <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> instance.</p>
<p>All stream readers must provide this constructor interface. They are free to add
additional keyword arguments, but only the ones defined here are used by the
Python codec registry.</p>
<p><em>stream</em> must be a file-like object open for reading (binary) data.</p>
<p>The <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> may implement different error handling schemes by
providing the <em>errors</em> keyword argument. These parameters are defined:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">'strict'</span></code> Raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> (or a subclass); this is the default.</li>
<li><code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> Ignore the character and continue with the next.</li>
<li><code class="docutils literal notranslate"><span class="pre">'replace'</span></code> Replace with a suitable replacement character.</li>
</ul>
<p>The <em>errors</em> argument will be assigned to an attribute of the same name.
Assigning to this attribute makes it possible to switch between different error
handling strategies during the lifetime of the <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> object.</p>
<p>The set of allowed values for the <em>errors</em> argument can be extended with
<a class="reference internal" href="#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_error()</span></code></a>.</p>
<dl class="method">
<dt id="codecs.StreamReader.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">[</span>, <em>chars</em><span class="optional">[</span>, <em>firstline</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Decodes data from the stream and returns the resulting object.</p>
<p><em>chars</em> indicates the number of characters to read from the
stream. <a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">read()</span></code></a> will never return more than <em>chars</em> characters, but
it might return less, if there are not enough characters available.</p>
<p><em>size</em> indicates the approximate maximum number of bytes to read from the
stream for decoding purposes. The decoder can modify this setting as
appropriate. The default value -1 indicates to read and decode as much as
possible.  <em>size</em> is intended to prevent having to decode huge files in
one step.</p>
<p><em>firstline</em> indicates that it would be sufficient to only return the first
line, if there are decoding errors on later lines.</p>
<p>The method should use a greedy read strategy meaning that it should read
as much data as is allowed within the definition of the encoding and the
given size, e.g.  if optional encoding endings or state markers are
available on the stream, these should be read too.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>chars</em> argument added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4.2: </span><em>firstline</em> argument added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="codecs.StreamReader.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">[</span>, <em>keepends</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read one line from the input stream and return the decoded data.</p>
<p><em>size</em>, if given, is passed as size argument to the stream’s
<a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method.</p>
<p>If <em>keepends</em> is false line-endings will be stripped from the lines
returned.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>keepends</em> argument added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="codecs.StreamReader.readlines">
<code class="descname">readlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>sizehint</em><span class="optional">[</span>, <em>keepends</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Read all lines available on the input stream and return them as a list of
lines.</p>
<p>Line-endings are implemented using the codec’s decoder method and are
included in the list entries if <em>keepends</em> is true.</p>
<p><em>sizehint</em>, if given, is passed as the <em>size</em> argument to the stream’s
<a class="reference internal" href="#codecs.StreamReader.read" title="codecs.StreamReader.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="codecs.StreamReader.reset">
<code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReader.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the codec buffers used for keeping state.</p>
<p>Note that no stream repositioning should take place.  This method is
primarily intended to be able to recover from decoding errors.</p>
</dd></dl>

</dd></dl>

<p>In addition to the above methods, the <a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> must also inherit
all other methods and attributes from the underlying stream.</p>
<p>The next two base classes are included for convenience. They are not needed by
the codec registry, but may provide useful in practice.</p>
</div>
<div class="section" id="streamreaderwriter-objects">
<span id="stream-reader-writer"></span><h3>7.8.1.6. StreamReaderWriter Objects<a class="headerlink" href="#streamreaderwriter-objects" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> allows wrapping streams which work in both read
and write modes.</p>
<p>The design is such that one can use the factory functions returned by the
<a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> function to construct the instance.</p>
<dl class="class">
<dt id="codecs.StreamReaderWriter">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamReaderWriter</code><span class="sig-paren">(</span><em>stream</em>, <em>Reader</em>, <em>Writer</em>, <em>errors</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamReaderWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a <a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> instance. <em>stream</em> must be a file-like
object. <em>Reader</em> and <em>Writer</em> must be factory functions or classes providing the
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> interface resp. Error handling
is done in the same way as defined for the stream readers and writers.</p>
</dd></dl>

<p><a class="reference internal" href="#codecs.StreamReaderWriter" title="codecs.StreamReaderWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReaderWriter</span></code></a> instances define the combined interfaces of
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes. They inherit all other
methods and attributes from the underlying stream.</p>
</div>
<div class="section" id="streamrecoder-objects">
<span id="stream-recoder-objects"></span><h3>7.8.1.7. StreamRecoder Objects<a class="headerlink" href="#streamrecoder-objects" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> provide a frontend - backend view of encoding data
which is sometimes useful when dealing with different encoding environments.</p>
<p>The design is such that one can use the factory functions returned by the
<a class="reference internal" href="#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">lookup()</span></code></a> function to construct the instance.</p>
<dl class="class">
<dt id="codecs.StreamRecoder">
<em class="property">class </em><code class="descclassname">codecs.</code><code class="descname">StreamRecoder</code><span class="sig-paren">(</span><em>stream</em>, <em>encode</em>, <em>decode</em>, <em>Reader</em>, <em>Writer</em>, <em>errors</em><span class="sig-paren">)</span><a class="headerlink" href="#codecs.StreamRecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a <a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> instance which implements a two-way conversion:
<em>encode</em> and <em>decode</em> work on the frontend (the input to <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and output
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>) while <em>Reader</em> and <em>Writer</em> work on the backend (reading and
writing to the stream).</p>
<p>You can use these objects to do transparent direct recodings from e.g. Latin-1
to UTF-8 and back.</p>
<p><em>stream</em> must be a file-like object.</p>
<p><em>encode</em>, <em>decode</em> must adhere to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Codec</span></code> interface. <em>Reader</em>,
<em>Writer</em> must be factory functions or classes providing objects of the
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> interface respectively.</p>
<p><em>encode</em> and <em>decode</em> are needed for the frontend translation, <em>Reader</em> and
<em>Writer</em> for the backend translation.  The intermediate format used is
determined by the two sets of codecs, e.g. the Unicode codecs will use Unicode
as the intermediate encoding.</p>
<p>Error handling is done in the same way as defined for the stream readers and
writers.</p>
</dd></dl>

<p><a class="reference internal" href="#codecs.StreamRecoder" title="codecs.StreamRecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRecoder</span></code></a> instances define the combined interfaces of
<a class="reference internal" href="#codecs.StreamReader" title="codecs.StreamReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code></a> and <a class="reference internal" href="#codecs.StreamWriter" title="codecs.StreamWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamWriter</span></code></a> classes. They inherit all other
methods and attributes from the underlying stream.</p>
</div>
</div>
<div class="section" id="encodings-and-unicode">
<span id="encodings-overview"></span><h2>7.8.2. Encodings and Unicode<a class="headerlink" href="#encodings-and-unicode" title="Permalink to this headline">¶</a></h2>
<p>Unicode strings are stored internally as sequences of code points (to be precise
as <a class="reference internal" href="../c-api/unicode.html#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> arrays). Depending on the way Python is compiled (either
via <code class="docutils literal notranslate"><span class="pre">--enable-unicode=ucs2</span></code> or <code class="docutils literal notranslate"><span class="pre">--enable-unicode=ucs4</span></code>, with the
former being the default) <a class="reference internal" href="../c-api/unicode.html#c.Py_UNICODE" title="Py_UNICODE"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_UNICODE</span></code></a> is either a 16-bit or 32-bit data
type. Once a Unicode object is used outside of CPU and memory, CPU endianness
and how these arrays are stored as bytes become an issue.  Transforming a
unicode object into a sequence of bytes is called encoding and recreating the
unicode object from the sequence of bytes is known as decoding.  There are many
different methods for how this transformation can be done (these methods are
also called encodings). The simplest method is to map the code points 0–255 to
the bytes <code class="docutils literal notranslate"><span class="pre">0x0</span></code>–<code class="docutils literal notranslate"><span class="pre">0xff</span></code>. This means that a unicode object that contains
code points above <code class="docutils literal notranslate"><span class="pre">U+00FF</span></code> can’t be encoded with this method (which is called
<code class="docutils literal notranslate"><span class="pre">'latin-1'</span></code> or <code class="docutils literal notranslate"><span class="pre">'iso-8859-1'</span></code>). <code class="xref py py-func docutils literal notranslate"><span class="pre">unicode.encode()</span></code> will raise a
<a class="reference internal" href="exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a> that looks like this: <code class="docutils literal notranslate"><span class="pre">UnicodeEncodeError:</span> <span class="pre">'latin-1'</span>
<span class="pre">codec</span> <span class="pre">can't</span> <span class="pre">encode</span> <span class="pre">character</span> <span class="pre">u'\u1234'</span> <span class="pre">in</span> <span class="pre">position</span> <span class="pre">3:</span> <span class="pre">ordinal</span> <span class="pre">not</span> <span class="pre">in</span>
<span class="pre">range(256)</span></code>.</p>
<p>There’s another group of encodings (the so called charmap encodings) that choose
a different subset of all unicode code points and how these code points are
mapped to the bytes <code class="docutils literal notranslate"><span class="pre">0x0</span></code>–<code class="docutils literal notranslate"><span class="pre">0xff</span></code>. To see how this is done simply open
e.g. <code class="file docutils literal notranslate"><span class="pre">encodings/cp1252.py</span></code> (which is an encoding that is used primarily on
Windows). There’s a string constant with 256 characters that shows you which
character is mapped to which byte value.</p>
<p>All of these encodings can only encode 256 of the 1114112 code points
defined in unicode. A simple and straightforward way that can store each Unicode
code point, is to store each code point as four consecutive bytes. There are two
possibilities: store the bytes in big endian or in little endian order. These
two encodings are called <code class="docutils literal notranslate"><span class="pre">UTF-32-BE</span></code> and <code class="docutils literal notranslate"><span class="pre">UTF-32-LE</span></code> respectively. Their
disadvantage is that if e.g. you use <code class="docutils literal notranslate"><span class="pre">UTF-32-BE</span></code> on a little endian machine you
will always have to swap bytes on encoding and decoding. <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> avoids this
problem: bytes will always be in natural endianness. When these bytes are read
by a CPU with a different endianness, then bytes have to be swapped though. To
be able to detect the endianness of a <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> byte sequence,
there’s the so called BOM (“Byte Order Mark”). This is the Unicode character
<code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code>. This character can be prepended to every <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code>
byte sequence. The byte swapped version of this character (<code class="docutils literal notranslate"><span class="pre">0xFFFE</span></code>) is an
illegal character that may not appear in a Unicode text. So when the
first character in an <code class="docutils literal notranslate"><span class="pre">UTF-16</span></code> or <code class="docutils literal notranslate"><span class="pre">UTF-32</span></code> byte sequence
appears to be a <code class="docutils literal notranslate"><span class="pre">U+FFFE</span></code> the bytes have to be swapped on decoding.
Unfortunately the character <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> had a second purpose as
a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code>: a character that has no width and doesn’t allow
a word to be split. It can e.g. be used to give hints to a ligature algorithm.
With Unicode 4.0 using <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> as a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code> has been
deprecated (with <code class="docutils literal notranslate"><span class="pre">U+2060</span></code> (<code class="docutils literal notranslate"><span class="pre">WORD</span> <span class="pre">JOINER</span></code>) assuming this role). Nevertheless
Unicode software still must be able to handle <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> in both roles: as a BOM
it’s a device to determine the storage layout of the encoded bytes, and vanishes
once the byte sequence has been decoded into a Unicode string; as a <code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span>
<span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code> it’s a normal character that will be decoded like any other.</p>
<p>There’s another encoding that is able to encoding the full range of Unicode
characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues
with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two
parts: marker bits (the most significant bits) and payload bits. The marker bits
are a sequence of zero to four <code class="docutils literal notranslate"><span class="pre">1</span></code> bits followed by a <code class="docutils literal notranslate"><span class="pre">0</span></code> bit. Unicode characters are
encoded like this (with x being payload bits, which when concatenated give the
Unicode character):</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Range</th>
<th class="head">Encoding</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">U-00000000</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0000007F</span></code></td>
<td>0xxxxxxx</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">U-00000080</span></code> … <code class="docutils literal notranslate"><span class="pre">U-000007FF</span></code></td>
<td>110xxxxx 10xxxxxx</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">U-00000800</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0000FFFF</span></code></td>
<td>1110xxxx 10xxxxxx 10xxxxxx</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">U-00010000</span></code> … <code class="docutils literal notranslate"><span class="pre">U-0010FFFF</span></code></td>
<td>11110xxx 10xxxxxx 10xxxxxx 10xxxxxx</td>
</tr>
</tbody>
</table>
<p>The least significant bit of the Unicode character is the rightmost x bit.</p>
<p>As UTF-8 is an 8-bit encoding no BOM is required and any <code class="docutils literal notranslate"><span class="pre">U+FEFF</span></code> character in
the decoded Unicode string (even if it’s the first character) is treated as a
<code class="docutils literal notranslate"><span class="pre">ZERO</span> <span class="pre">WIDTH</span> <span class="pre">NO-BREAK</span> <span class="pre">SPACE</span></code>.</p>
<p>Without external information it’s impossible to reliably determine which
encoding was used for encoding a Unicode string. Each charmap encoding can
decode any random byte sequence. However that’s not possible with UTF-8, as
UTF-8 byte sequences have a structure that doesn’t allow arbitrary byte
sequences. To increase the reliability with which a UTF-8 encoding can be
detected, Microsoft invented a variant of UTF-8 (that Python 2.5 calls
<code class="docutils literal notranslate"><span class="pre">&quot;utf-8-sig&quot;</span></code>) for its Notepad program: Before any of the Unicode characters
is written to the file, a UTF-8 encoded BOM (which looks like this as a byte
sequence: <code class="docutils literal notranslate"><span class="pre">0xef</span></code>, <code class="docutils literal notranslate"><span class="pre">0xbb</span></code>, <code class="docutils literal notranslate"><span class="pre">0xbf</span></code>) is written. As it’s rather improbable
that any charmap encoded file starts with these byte values (which would e.g.
map to</p>
<blockquote>
<div><div class="line-block">
<div class="line">LATIN SMALL LETTER I WITH DIAERESIS</div>
<div class="line">RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK</div>
<div class="line">INVERTED QUESTION MARK</div>
</div>
</div></blockquote>
<p>in iso-8859-1), this increases the probability that a <code class="docutils literal notranslate"><span class="pre">utf-8-sig</span></code> encoding can be
correctly guessed from the byte sequence. So here the BOM is not used to be able
to determine the byte order used for generating the byte sequence, but as a
signature that helps in guessing the encoding. On encoding the utf-8-sig codec
will write <code class="docutils literal notranslate"><span class="pre">0xef</span></code>, <code class="docutils literal notranslate"><span class="pre">0xbb</span></code>, <code class="docutils literal notranslate"><span class="pre">0xbf</span></code> as the first three bytes to the file. On
decoding <code class="docutils literal notranslate"><span class="pre">utf-8-sig</span></code> will skip those three bytes if they appear as the first
three bytes in the file.  In UTF-8, the use of the BOM is discouraged and
should generally be avoided.</p>
</div>
<div class="section" id="standard-encodings">
<span id="id3"></span><h2>7.8.3. Standard Encodings<a class="headerlink" href="#standard-encodings" title="Permalink to this headline">¶</a></h2>
<p>Python comes with a number of codecs built-in, either implemented as C functions
or with dictionaries as mapping tables. The following table lists the codecs by
name, together with a few common aliases, and the languages for which the
encoding is likely used. Neither the list of aliases nor the list of languages
is meant to be exhaustive. Notice that spelling alternatives that only differ in
case or use a hyphen instead of an underscore are also valid aliases; therefore,
e.g. <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> is a valid alias for the <code class="docutils literal notranslate"><span class="pre">'utf_8'</span></code> codec.</p>
<p>Many of the character sets support the same languages. They vary in individual
characters (e.g. whether the EURO SIGN is supported or not), and in the
assignment of characters to code positions. For the European languages in
particular, the following variants typically exist:</p>
<ul class="simple">
<li>an ISO 8859 codeset</li>
<li>a Microsoft Windows code page, which is typically derived from an 8859 codeset,
but replaces control characters with additional graphic characters</li>
<li>an IBM EBCDIC code page</li>
<li>an IBM PC code page, which is ASCII compatible</li>
</ul>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="40%" />
<col width="40%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Codec</th>
<th class="head">Aliases</th>
<th class="head">Languages</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>ascii</td>
<td>646, us-ascii</td>
<td>English</td>
</tr>
<tr class="row-odd"><td>big5</td>
<td>big5-tw, csbig5</td>
<td>Traditional Chinese</td>
</tr>
<tr class="row-even"><td>big5hkscs</td>
<td>big5-hkscs, hkscs</td>
<td>Traditional Chinese</td>
</tr>
<tr class="row-odd"><td>cp037</td>
<td>IBM037, IBM039</td>
<td>English</td>
</tr>
<tr class="row-even"><td>cp424</td>
<td>EBCDIC-CP-HE, IBM424</td>
<td>Hebrew</td>
</tr>
<tr class="row-odd"><td>cp437</td>
<td>437, IBM437</td>
<td>English</td>
</tr>
<tr class="row-even"><td>cp500</td>
<td>EBCDIC-CP-BE, EBCDIC-CP-CH,
IBM500</td>
<td>Western Europe</td>
</tr>
<tr class="row-odd"><td>cp720</td>
<td>&#160;</td>
<td>Arabic</td>
</tr>
<tr class="row-even"><td>cp737</td>
<td>&#160;</td>
<td>Greek</td>
</tr>
<tr class="row-odd"><td>cp775</td>
<td>IBM775</td>
<td>Baltic languages</td>
</tr>
<tr class="row-even"><td>cp850</td>
<td>850, IBM850</td>
<td>Western Europe</td>
</tr>
<tr class="row-odd"><td>cp852</td>
<td>852, IBM852</td>
<td>Central and Eastern Europe</td>
</tr>
<tr class="row-even"><td>cp855</td>
<td>855, IBM855</td>
<td>Bulgarian, Byelorussian,
Macedonian, Russian, Serbian</td>
</tr>
<tr class="row-odd"><td>cp856</td>
<td>&#160;</td>
<td>Hebrew</td>
</tr>
<tr class="row-even"><td>cp857</td>
<td>857, IBM857</td>
<td>Turkish</td>
</tr>
<tr class="row-odd"><td>cp858</td>
<td>858, IBM858</td>
<td>Western Europe</td>
</tr>
<tr class="row-even"><td>cp860</td>
<td>860, IBM860</td>
<td>Portuguese</td>
</tr>
<tr class="row-odd"><td>cp861</td>
<td>861, CP-IS, IBM861</td>
<td>Icelandic</td>
</tr>
<tr class="row-even"><td>cp862</td>
<td>862, IBM862</td>
<td>Hebrew</td>
</tr>
<tr class="row-odd"><td>cp863</td>
<td>863, IBM863</td>
<td>Canadian</td>
</tr>
<tr class="row-even"><td>cp864</td>
<td>IBM864</td>
<td>Arabic</td>
</tr>
<tr class="row-odd"><td>cp865</td>
<td>865, IBM865</td>
<td>Danish, Norwegian</td>
</tr>
<tr class="row-even"><td>cp866</td>
<td>866, IBM866</td>
<td>Russian</td>
</tr>
<tr class="row-odd"><td>cp869</td>
<td>869, CP-GR, IBM869</td>
<td>Greek</td>
</tr>
<tr class="row-even"><td>cp874</td>
<td>&#160;</td>
<td>Thai</td>
</tr>
<tr class="row-odd"><td>cp875</td>
<td>&#160;</td>
<td>Greek</td>
</tr>
<tr class="row-even"><td>cp932</td>
<td>932, ms932, mskanji, ms-kanji</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>cp949</td>
<td>949, ms949, uhc</td>
<td>Korean</td>
</tr>
<tr class="row-even"><td>cp950</td>
<td>950, ms950</td>
<td>Traditional Chinese</td>
</tr>
<tr class="row-odd"><td>cp1006</td>
<td>&#160;</td>
<td>Urdu</td>
</tr>
<tr class="row-even"><td>cp1026</td>
<td>ibm1026</td>
<td>Turkish</td>
</tr>
<tr class="row-odd"><td>cp1140</td>
<td>ibm1140</td>
<td>Western Europe</td>
</tr>
<tr class="row-even"><td>cp1250</td>
<td>windows-1250</td>
<td>Central and Eastern Europe</td>
</tr>
<tr class="row-odd"><td>cp1251</td>
<td>windows-1251</td>
<td>Bulgarian, Byelorussian,
Macedonian, Russian, Serbian</td>
</tr>
<tr class="row-even"><td>cp1252</td>
<td>windows-1252</td>
<td>Western Europe</td>
</tr>
<tr class="row-odd"><td>cp1253</td>
<td>windows-1253</td>
<td>Greek</td>
</tr>
<tr class="row-even"><td>cp1254</td>
<td>windows-1254</td>
<td>Turkish</td>
</tr>
<tr class="row-odd"><td>cp1255</td>
<td>windows-1255</td>
<td>Hebrew</td>
</tr>
<tr class="row-even"><td>cp1256</td>
<td>windows-1256</td>
<td>Arabic</td>
</tr>
<tr class="row-odd"><td>cp1257</td>
<td>windows-1257</td>
<td>Baltic languages</td>
</tr>
<tr class="row-even"><td>cp1258</td>
<td>windows-1258</td>
<td>Vietnamese</td>
</tr>
<tr class="row-odd"><td>euc_jp</td>
<td>eucjp, ujis, u-jis</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>euc_jis_2004</td>
<td>jisx0213, eucjis2004</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>euc_jisx0213</td>
<td>eucjisx0213</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>euc_kr</td>
<td>euckr, korean, ksc5601,
ks_c-5601, ks_c-5601-1987,
ksx1001, ks_x-1001</td>
<td>Korean</td>
</tr>
<tr class="row-odd"><td>gb2312</td>
<td>chinese, csiso58gb231280, euc-
cn, euccn, eucgb2312-cn,
gb2312-1980, gb2312-80, iso-
ir-58</td>
<td>Simplified Chinese</td>
</tr>
<tr class="row-even"><td>gbk</td>
<td>936, cp936, ms936</td>
<td>Unified Chinese</td>
</tr>
<tr class="row-odd"><td>gb18030</td>
<td>gb18030-2000</td>
<td>Unified Chinese</td>
</tr>
<tr class="row-even"><td>hz</td>
<td>hzgb, hz-gb, hz-gb-2312</td>
<td>Simplified Chinese</td>
</tr>
<tr class="row-odd"><td>iso2022_jp</td>
<td>csiso2022jp, iso2022jp,
iso-2022-jp</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>iso2022_jp_1</td>
<td>iso2022jp-1, iso-2022-jp-1</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>iso2022_jp_2</td>
<td>iso2022jp-2, iso-2022-jp-2</td>
<td>Japanese, Korean, Simplified
Chinese, Western Europe, Greek</td>
</tr>
<tr class="row-even"><td>iso2022_jp_2004</td>
<td>iso2022jp-2004,
iso-2022-jp-2004</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>iso2022_jp_3</td>
<td>iso2022jp-3, iso-2022-jp-3</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>iso2022_jp_ext</td>
<td>iso2022jp-ext, iso-2022-jp-ext</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>iso2022_kr</td>
<td>csiso2022kr, iso2022kr,
iso-2022-kr</td>
<td>Korean</td>
</tr>
<tr class="row-even"><td>latin_1</td>
<td>iso-8859-1, iso8859-1, 8859,
cp819, latin, latin1, L1</td>
<td>West Europe</td>
</tr>
<tr class="row-odd"><td>iso8859_2</td>
<td>iso-8859-2, latin2, L2</td>
<td>Central and Eastern Europe</td>
</tr>
<tr class="row-even"><td>iso8859_3</td>
<td>iso-8859-3, latin3, L3</td>
<td>Esperanto, Maltese</td>
</tr>
<tr class="row-odd"><td>iso8859_4</td>
<td>iso-8859-4, latin4, L4</td>
<td>Baltic languages</td>
</tr>
<tr class="row-even"><td>iso8859_5</td>
<td>iso-8859-5, cyrillic</td>
<td>Bulgarian, Byelorussian,
Macedonian, Russian, Serbian</td>
</tr>
<tr class="row-odd"><td>iso8859_6</td>
<td>iso-8859-6, arabic</td>
<td>Arabic</td>
</tr>
<tr class="row-even"><td>iso8859_7</td>
<td>iso-8859-7, greek, greek8</td>
<td>Greek</td>
</tr>
<tr class="row-odd"><td>iso8859_8</td>
<td>iso-8859-8, hebrew</td>
<td>Hebrew</td>
</tr>
<tr class="row-even"><td>iso8859_9</td>
<td>iso-8859-9, latin5, L5</td>
<td>Turkish</td>
</tr>
<tr class="row-odd"><td>iso8859_10</td>
<td>iso-8859-10, latin6, L6</td>
<td>Nordic languages</td>
</tr>
<tr class="row-even"><td>iso8859_11</td>
<td>iso-8859-11, thai</td>
<td>Thai languages</td>
</tr>
<tr class="row-odd"><td>iso8859_13</td>
<td>iso-8859-13, latin7, L7</td>
<td>Baltic languages</td>
</tr>
<tr class="row-even"><td>iso8859_14</td>
<td>iso-8859-14, latin8, L8</td>
<td>Celtic languages</td>
</tr>
<tr class="row-odd"><td>iso8859_15</td>
<td>iso-8859-15, latin9, L9</td>
<td>Western Europe</td>
</tr>
<tr class="row-even"><td>iso8859_16</td>
<td>iso-8859-16, latin10, L10</td>
<td>South-Eastern Europe</td>
</tr>
<tr class="row-odd"><td>johab</td>
<td>cp1361, ms1361</td>
<td>Korean</td>
</tr>
<tr class="row-even"><td>koi8_r</td>
<td>&#160;</td>
<td>Russian</td>
</tr>
<tr class="row-odd"><td>koi8_u</td>
<td>&#160;</td>
<td>Ukrainian</td>
</tr>
<tr class="row-even"><td>mac_cyrillic</td>
<td>maccyrillic</td>
<td>Bulgarian, Byelorussian,
Macedonian, Russian, Serbian</td>
</tr>
<tr class="row-odd"><td>mac_greek</td>
<td>macgreek</td>
<td>Greek</td>
</tr>
<tr class="row-even"><td>mac_iceland</td>
<td>maciceland</td>
<td>Icelandic</td>
</tr>
<tr class="row-odd"><td>mac_latin2</td>
<td>maclatin2, maccentraleurope</td>
<td>Central and Eastern Europe</td>
</tr>
<tr class="row-even"><td>mac_roman</td>
<td>macroman</td>
<td>Western Europe</td>
</tr>
<tr class="row-odd"><td>mac_turkish</td>
<td>macturkish</td>
<td>Turkish</td>
</tr>
<tr class="row-even"><td>ptcp154</td>
<td>csptcp154, pt154, cp154,
cyrillic-asian</td>
<td>Kazakh</td>
</tr>
<tr class="row-odd"><td>shift_jis</td>
<td>csshiftjis, shiftjis, sjis,
s_jis</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>shift_jis_2004</td>
<td>shiftjis2004, sjis_2004,
sjis2004</td>
<td>Japanese</td>
</tr>
<tr class="row-odd"><td>shift_jisx0213</td>
<td>shiftjisx0213, sjisx0213,
s_jisx0213</td>
<td>Japanese</td>
</tr>
<tr class="row-even"><td>utf_32</td>
<td>U32, utf32</td>
<td>all languages</td>
</tr>
<tr class="row-odd"><td>utf_32_be</td>
<td>UTF-32BE</td>
<td>all languages</td>
</tr>
<tr class="row-even"><td>utf_32_le</td>
<td>UTF-32LE</td>
<td>all languages</td>
</tr>
<tr class="row-odd"><td>utf_16</td>
<td>U16, utf16</td>
<td>all languages</td>
</tr>
<tr class="row-even"><td>utf_16_be</td>
<td>UTF-16BE</td>
<td>all languages (BMP only)</td>
</tr>
<tr class="row-odd"><td>utf_16_le</td>
<td>UTF-16LE</td>
<td>all languages (BMP only)</td>
</tr>
<tr class="row-even"><td>utf_7</td>
<td>U7, unicode-1-1-utf-7</td>
<td>all languages</td>
</tr>
<tr class="row-odd"><td>utf_8</td>
<td>U8, UTF, utf8</td>
<td>all languages</td>
</tr>
<tr class="row-even"><td>utf_8_sig</td>
<td>&#160;</td>
<td>all languages</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="python-specific-encodings">
<h2>7.8.4. Python Specific Encodings<a class="headerlink" href="#python-specific-encodings" title="Permalink to this headline">¶</a></h2>
<p>A number of predefined codecs are specific to Python, so their codec names have
no meaning outside Python.  These are listed in the tables below based on the
expected input and output types (note that while text encodings are the most
common use case for codecs, the underlying codec infrastructure supports
arbitrary data transforms rather than just text encodings).  For asymmetric
codecs, the stated purpose describes the encoding direction.</p>
<p>The following codecs provide unicode-to-str encoding <a class="footnote-reference" href="#encoding-note" id="id4">[1]</a> and
str-to-unicode decoding <a class="footnote-reference" href="#decoding-note" id="id5">[2]</a>, similar to the Unicode text
encodings.</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="36%" />
<col width="36%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Codec</th>
<th class="head">Aliases</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>idna</td>
<td>&#160;</td>
<td>Implements <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3490.html"><strong>RFC 3490</strong></a>,
see also
<a class="reference internal" href="#module-encodings.idna" title="encodings.idna: Internationalized Domain Names implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.idna</span></code></a></td>
</tr>
<tr class="row-odd"><td>mbcs</td>
<td>dbcs</td>
<td>Windows only: Encode
operand according to the
ANSI codepage (CP_ACP)</td>
</tr>
<tr class="row-even"><td>palmos</td>
<td>&#160;</td>
<td>Encoding of PalmOS 3.5</td>
</tr>
<tr class="row-odd"><td>punycode</td>
<td>&#160;</td>
<td>Implements <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3492.html"><strong>RFC 3492</strong></a></td>
</tr>
<tr class="row-even"><td>raw_unicode_escape</td>
<td>&#160;</td>
<td>Produce a string that is
suitable as raw Unicode
literal in Python source
code</td>
</tr>
<tr class="row-odd"><td>rot_13</td>
<td>rot13</td>
<td>Returns the Caesar-cypher
encryption of the operand</td>
</tr>
<tr class="row-even"><td>undefined</td>
<td>&#160;</td>
<td>Raise an exception for
all conversions. Can be
used as the system
encoding if no automatic
<a class="reference internal" href="../glossary.html#term-coercion"><span class="xref std std-term">coercion</span></a> between
byte and Unicode strings
is desired.</td>
</tr>
<tr class="row-odd"><td>unicode_escape</td>
<td>&#160;</td>
<td>Produce a string that is
suitable as Unicode
literal in Python source
code</td>
</tr>
<tr class="row-even"><td>unicode_internal</td>
<td>&#160;</td>
<td>Return the internal
representation of the
operand</td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3: </span>The <code class="docutils literal notranslate"><span class="pre">idna</span></code> and <code class="docutils literal notranslate"><span class="pre">punycode</span></code> encodings.</p>
</div>
<p>The following codecs provide str-to-str encoding and decoding
<a class="footnote-reference" href="#decoding-note" id="id6">[2]</a>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="19%" />
<col width="26%" />
<col width="26%" />
<col width="29%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Codec</th>
<th class="head">Aliases</th>
<th class="head">Purpose</th>
<th class="head">Encoder/decoder</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>base64_codec</td>
<td>base64, base-64</td>
<td>Convert operand to
multiline MIME base64 (the
result always includes a
trailing <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>)</td>
<td><a class="reference internal" href="base64.html#base64.encodestring" title="base64.encodestring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">base64.encodestring()</span></code></a>,
<a class="reference internal" href="base64.html#base64.decodestring" title="base64.decodestring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">base64.decodestring()</span></code></a></td>
</tr>
<tr class="row-odd"><td>bz2_codec</td>
<td>bz2</td>
<td>Compress the operand
using bz2</td>
<td><a class="reference internal" href="bz2.html#bz2.compress" title="bz2.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bz2.compress()</span></code></a>,
<a class="reference internal" href="bz2.html#bz2.decompress" title="bz2.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bz2.decompress()</span></code></a></td>
</tr>
<tr class="row-even"><td>hex_codec</td>
<td>hex</td>
<td>Convert operand to
hexadecimal
representation, with two
digits per byte</td>
<td><a class="reference internal" href="binascii.html#binascii.b2a_hex" title="binascii.b2a_hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">binascii.b2a_hex()</span></code></a>,
<a class="reference internal" href="binascii.html#binascii.a2b_hex" title="binascii.a2b_hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">binascii.a2b_hex()</span></code></a></td>
</tr>
<tr class="row-odd"><td>quopri_codec</td>
<td>quopri, quoted-printable,
quotedprintable</td>
<td>Convert operand to MIME
quoted printable</td>
<td><a class="reference internal" href="quopri.html#quopri.encode" title="quopri.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">quopri.encode()</span></code></a> with
<code class="docutils literal notranslate"><span class="pre">quotetabs=True</span></code>,
<a class="reference internal" href="quopri.html#quopri.decode" title="quopri.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">quopri.decode()</span></code></a></td>
</tr>
<tr class="row-even"><td>string_escape</td>
<td>&#160;</td>
<td>Produce a string that is
suitable as string
literal in Python source
code</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>uu_codec</td>
<td>uu</td>
<td>Convert the operand using
uuencode</td>
<td><a class="reference internal" href="uu.html#uu.encode" title="uu.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uu.encode()</span></code></a>,
<a class="reference internal" href="uu.html#uu.decode" title="uu.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">uu.decode()</span></code></a></td>
</tr>
<tr class="row-even"><td>zlib_codec</td>
<td>zip, zlib</td>
<td>Compress the operand
using gzip</td>
<td><a class="reference internal" href="zlib.html#zlib.compress" title="zlib.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">zlib.compress()</span></code></a>,
<a class="reference internal" href="zlib.html#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">zlib.decompress()</span></code></a></td>
</tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="encoding-note" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[1]</a></td><td>str objects are also accepted as input in place of unicode
objects.  They are implicitly converted to unicode by decoding them using
the default encoding.  If this conversion fails, it may lead to encoding
operations raising <a class="reference internal" href="exceptions.html#exceptions.UnicodeDecodeError" title="exceptions.UnicodeDecodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code></a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="decoding-note" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[2]</td><td><em>(<a class="fn-backref" href="#id5">1</a>, <a class="fn-backref" href="#id6">2</a>)</em> unicode objects are also accepted as input in place of str
objects.  They are implicitly converted to str by encoding them using the
default encoding.  If this conversion fails, it may lead to decoding
operations raising <a class="reference internal" href="exceptions.html#exceptions.UnicodeEncodeError" title="exceptions.UnicodeEncodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeEncodeError</span></code></a>.</td></tr>
</tbody>
</table>
</div>
<div class="section" id="module-encodings.idna">
<span id="encodings-idna-internationalized-domain-names-in-applications"></span><h2>7.8.5. <a class="reference internal" href="#module-encodings.idna" title="encodings.idna: Internationalized Domain Names implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.idna</span></code></a> — Internationalized Domain Names in Applications<a class="headerlink" href="#module-encodings.idna" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module implements <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3490.html"><strong>RFC 3490</strong></a> (Internationalized Domain Names in
Applications) and <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3492.html"><strong>RFC 3492</strong></a> (Nameprep: A Stringprep Profile for
Internationalized Domain Names (IDN)). It builds upon the <code class="docutils literal notranslate"><span class="pre">punycode</span></code> encoding
and <a class="reference internal" href="stringprep.html#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a>.</p>
<p>These RFCs together define a protocol to support non-ASCII characters in domain
names. A domain name containing non-ASCII characters (such as
<code class="docutils literal notranslate"><span class="pre">www.Alliancefrançaise.nu</span></code>) is converted into an ASCII-compatible encoding
(ACE, such as <code class="docutils literal notranslate"><span class="pre">www.xn--alliancefranaise-npb.nu</span></code>). The ACE form of the domain
name is then used in all places where arbitrary characters are not allowed by
the protocol, such as DNS queries, HTTP <em class="mailheader">Host</em> fields, and so
on. This conversion is carried out in the application; if possible invisible to
the user: The application should transparently convert Unicode domain labels to
IDNA on the wire, and convert back ACE labels to Unicode before presenting them
to the user.</p>
<p>Python supports this conversion in several ways:  the <code class="docutils literal notranslate"><span class="pre">idna</span></code> codec performs
conversion between Unicode and ACE, separating an input string into labels
based on the separator characters defined in <a class="reference external" href="https://tools.ietf.org/html/rfc3490#section-3.1">section 3.1</a> (1) of <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3490.html"><strong>RFC 3490</strong></a>
and converting each label to ACE as required, and conversely separating an input
byte string into labels based on the <code class="docutils literal notranslate"><span class="pre">.</span></code> separator and converting any ACE
labels found into unicode.  Furthermore, the <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module
transparently converts Unicode host names to ACE, so that applications need not
be concerned about converting host names themselves when they pass them to the
socket module. On top of that, modules that have host names as function
parameters, such as <a class="reference internal" href="httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> and <a class="reference internal" href="ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a>, accept Unicode host names
(<a class="reference internal" href="httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> then also transparently sends an IDNA hostname in the
<em class="mailheader">Host</em> field if it sends that field at all).</p>
<p>When receiving host names from the wire (such as in reverse name lookup), no
automatic conversion to Unicode is performed: Applications wishing to present
such host names to the user should decode them to Unicode.</p>
<p>The module <a class="reference internal" href="#module-encodings.idna" title="encodings.idna: Internationalized Domain Names implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.idna</span></code></a> also implements the nameprep procedure, which
performs certain normalizations on host names, to achieve case-insensitivity of
international domain names, and to unify similar characters. The nameprep
functions can be used directly if desired.</p>
<dl class="function">
<dt id="encodings.idna.nameprep">
<code class="descclassname">encodings.idna.</code><code class="descname">nameprep</code><span class="sig-paren">(</span><em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#encodings.idna.nameprep" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the nameprepped version of <em>label</em>. The implementation currently assumes
query strings, so <code class="docutils literal notranslate"><span class="pre">AllowUnassigned</span></code> is true.</p>
</dd></dl>

<dl class="function">
<dt id="encodings.idna.ToASCII">
<code class="descclassname">encodings.idna.</code><code class="descname">ToASCII</code><span class="sig-paren">(</span><em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#encodings.idna.ToASCII" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a label to ASCII, as specified in <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3490.html"><strong>RFC 3490</strong></a>. <code class="docutils literal notranslate"><span class="pre">UseSTD3ASCIIRules</span></code> is
assumed to be false.</p>
</dd></dl>

<dl class="function">
<dt id="encodings.idna.ToUnicode">
<code class="descclassname">encodings.idna.</code><code class="descname">ToUnicode</code><span class="sig-paren">(</span><em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#encodings.idna.ToUnicode" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a label to Unicode, as specified in <span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3490.html"><strong>RFC 3490</strong></a>.</p>
</dd></dl>

</div>
<div class="section" id="module-encodings.utf_8_sig">
<span id="encodings-utf-8-sig-utf-8-codec-with-bom-signature"></span><h2>7.8.6. <a class="reference internal" href="#module-encodings.utf_8_sig" title="encodings.utf_8_sig: UTF-8 codec with BOM signature"><code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.utf_8_sig</span></code></a> — UTF-8 codec with BOM signature<a class="headerlink" href="#module-encodings.utf_8_sig" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>This module implements a variant of the UTF-8 codec: On encoding a UTF-8 encoded
BOM will be prepended to the UTF-8 encoded bytes. For the stateful encoder this
is only done once (on the first write to the byte stream).  For decoding an
optional UTF-8 encoded BOM at the start of the data will be skipped.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a><ul>
<li><a class="reference internal" href="#codec-base-classes">7.8.1. Codec Base Classes</a><ul>
<li><a class="reference internal" href="#codec-objects">7.8.1.1. Codec Objects</a></li>
<li><a class="reference internal" href="#incrementalencoder-objects">7.8.1.2. IncrementalEncoder Objects</a></li>
<li><a class="reference internal" href="#incrementaldecoder-objects">7.8.1.3. IncrementalDecoder Objects</a></li>
<li><a class="reference internal" href="#streamwriter-objects">7.8.1.4. StreamWriter Objects</a></li>
<li><a class="reference internal" href="#streamreader-objects">7.8.1.5. StreamReader Objects</a></li>
<li><a class="reference internal" href="#streamreaderwriter-objects">7.8.1.6. StreamReaderWriter Objects</a></li>
<li><a class="reference internal" href="#streamrecoder-objects">7.8.1.7. StreamRecoder Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#encodings-and-unicode">7.8.2. Encodings and Unicode</a></li>
<li><a class="reference internal" href="#standard-encodings">7.8.3. Standard Encodings</a></li>
<li><a class="reference internal" href="#python-specific-encodings">7.8.4. Python Specific Encodings</a></li>
<li><a class="reference internal" href="#module-encodings.idna">7.8.5. <code class="docutils literal notranslate"><span class="pre">encodings.idna</span></code> — Internationalized Domain Names in Applications</a></li>
<li><a class="reference internal" href="#module-encodings.utf_8_sig">7.8.6. <code class="docutils literal notranslate"><span class="pre">encodings.utf_8_sig</span></code> — UTF-8 codec with BOM signature</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="textwrap.html"
                        title="previous chapter">7.7. <code class="docutils literal notranslate"><span class="pre">textwrap</span></code> — Text wrapping and filling</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unicodedata.html"
                        title="next chapter">7.9. <code class="docutils literal notranslate"><span class="pre">unicodedata</span></code> — Unicode Database</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/codecs.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unicodedata.html" title="7.9. unicodedata — Unicode Database"
             >next</a> |</li>
        <li class="right" >
          <a href="textwrap.html" title="7.7. textwrap — Text wrapping and filling"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��$>>html/library/codeop.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>29.2. codeop — Compile Python code &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="30. Restricted Execution" href="restricted.html" />
    <link rel="prev" title="29.1. code — Interpreter base classes" href="code.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/codeop.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="restricted.html" title="30. Restricted Execution"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="code.html" title="29.1. code — Interpreter base classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="custominterp.html" accesskey="U">29. Custom Python Interpreters</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-codeop">
<span id="codeop-compile-python-code"></span><h1>29.2. <a class="reference internal" href="#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> — Compile Python code<a class="headerlink" href="#module-codeop" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> module provides utilities upon which the Python
read-eval-print loop can be emulated, as is done in the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> module.  As
a result, you probably don’t want to use the module directly; if you want to
include such a loop in your program you probably want to use the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a>
module instead.</p>
<p>There are two parts to this job:</p>
<ol class="arabic simple">
<li>Being able to tell if a line of input completes a Python  statement: in
short, telling whether to print ‘<code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>’ or ‘<code class="docutils literal notranslate"><span class="pre">...</span></code>’ next.</li>
<li>Remembering which future statements the user has entered, so  subsequent
input can be compiled with these in effect.</li>
</ol>
<p>The <a class="reference internal" href="#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> module provides a way of doing each of these things, and a way
of doing them both.</p>
<p>To do just the former:</p>
<dl class="function">
<dt id="codeop.compile_command">
<code class="descclassname">codeop.</code><code class="descname">compile_command</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>symbol</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#codeop.compile_command" title="Permalink to this definition">¶</a></dt>
<dd><p>Tries to compile <em>source</em>, which should be a string of Python code and return a
code object if <em>source</em> is valid Python code. In that case, the filename
attribute of the code object will be <em>filename</em>, which defaults to
<code class="docutils literal notranslate"><span class="pre">'&lt;input&gt;'</span></code>. Returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if <em>source</em> is <em>not</em> valid Python code, but is a
prefix of valid Python code.</p>
<p>If there is a problem with <em>source</em>, an exception will be raised.
<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> is raised if there is invalid Python syntax, and
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if there is an invalid literal.</p>
<p>The <em>symbol</em> argument determines whether <em>source</em> is compiled as a statement
(<code class="docutils literal notranslate"><span class="pre">'single'</span></code>, the default) or as an <a class="reference internal" href="../glossary.html#term-expression"><span class="xref std std-term">expression</span></a> (<code class="docutils literal notranslate"><span class="pre">'eval'</span></code>).  Any
other value will cause <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to  be raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is possible (but not likely) that the parser stops parsing with a
successful outcome before reaching the end of the source; in this case,
trailing symbols may be ignored instead of causing an error.  For example,
a backslash followed by two newlines may be followed by arbitrary garbage.
This will be fixed once the API for the parser is better.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="codeop.Compile">
<em class="property">class </em><code class="descclassname">codeop.</code><code class="descname">Compile</code><a class="headerlink" href="#codeop.Compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class have <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> methods identical in signature to
the built-in function <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>, but with the difference that if the
instance compiles program text containing a <a class="reference internal" href="__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> statement, the
instance ‘remembers’ and compiles all subsequent program texts with the
statement in force.</p>
</dd></dl>

<dl class="class">
<dt id="codeop.CommandCompiler">
<em class="property">class </em><code class="descclassname">codeop.</code><code class="descname">CommandCompiler</code><a class="headerlink" href="#codeop.CommandCompiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class have <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> methods identical in signature to
<a class="reference internal" href="#codeop.compile_command" title="codeop.compile_command"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_command()</span></code></a>; the difference is that if the instance compiles program
text containing a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> statement, the instance ‘remembers’ and
compiles all subsequent program texts with the statement in force.</p>
</dd></dl>

<p>A note on version compatibility: the <a class="reference internal" href="#codeop.Compile" title="codeop.Compile"><code class="xref py py-class docutils literal notranslate"><span class="pre">Compile</span></code></a> and
<a class="reference internal" href="#codeop.CommandCompiler" title="codeop.CommandCompiler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CommandCompiler</span></code></a> are new in Python 2.2.  If you want to enable the
future-tracking features of 2.2 but also retain compatibility with 2.1 and
earlier versions of Python you can either write</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">codeop</span> <span class="k">import</span> <span class="n">CommandCompiler</span>
    <span class="n">compile_command</span> <span class="o">=</span> <span class="n">CommandCompiler</span><span class="p">()</span>
    <span class="k">del</span> <span class="n">CommandCompiler</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">codeop</span> <span class="k">import</span> <span class="n">compile_command</span>
</pre></div>
</div>
<p>which is a low-impact change, but introduces possibly unwanted global state into
your program, or you can write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">from</span> <span class="nn">codeop</span> <span class="k">import</span> <span class="n">CommandCompiler</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">CommandCompiler</span><span class="p">():</span>
        <span class="kn">from</span> <span class="nn">codeop</span> <span class="k">import</span> <span class="n">compile_command</span>
        <span class="k">return</span> <span class="n">compile_command</span>
</pre></div>
</div>
<p>and then call <code class="docutils literal notranslate"><span class="pre">CommandCompiler</span></code> every time you need a fresh compiler object.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="code.html"
                        title="previous chapter">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="restricted.html"
                        title="next chapter">30. Restricted Execution</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/codeop.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="restricted.html" title="30. Restricted Execution"
             >next</a> |</li>
        <li class="right" >
          <a href="code.html" title="29.1. code — Interpreter base classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="custominterp.html" >29. Custom Python Interpreters</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\l�*�@�@html/library/collections.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.3. collections — High-performance container datatypes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.4. heapq — Heap queue algorithm" href="heapq.html" />
    <link rel="prev" title="8.2. calendar — General calendar-related functions" href="calendar.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/collections.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-collections">
<span id="collections-high-performance-container-datatypes"></span><h1>8.3. <a class="reference internal" href="#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> — High-performance container datatypes<a class="headerlink" href="#module-collections" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/collections.py">Lib/collections.py</a> and <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/_abcoll.py">Lib/_abcoll.py</a></p>
<hr class="docutils" />
<p>This module implements specialized container datatypes providing alternatives to
Python’s general purpose built-in containers, <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="59%" />
<col width="23%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a></td>
<td>factory function for creating tuple subclasses with named fields</td>
<td><div class="first last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a></td>
<td>list-like container with fast appends and pops on either end</td>
<td><div class="first last versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a></td>
<td>dict subclass for counting hashable objects</td>
<td><div class="first last versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a></td>
<td>dict subclass that remembers the order entries were added</td>
<td><div class="first last versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a></td>
<td>dict subclass that calls a factory function to supply missing values</td>
<td><div class="first last versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</td>
</tr>
</tbody>
</table>
<p>In addition to the concrete container classes, the collections module provides
<a class="reference internal" href="#collections-abstract-base-classes"><span class="std std-ref">abstract base classes</span></a> that can be
used to test whether a class provides a particular interface, for example,
whether it is hashable or a mapping.</p>
<div class="section" id="counter-objects">
<h2>8.3.1. <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects<a class="headerlink" href="#counter-objects" title="Permalink to this headline">¶</a></h2>
<p>A counter tool is provided to support convenient and rapid tallies.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tally occurrences of words in a list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="s1">&#39;green&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="n">cnt</span><span class="p">[</span><span class="n">word</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cnt</span>
<span class="go">Counter({&#39;blue&#39;: 3, &#39;red&#39;: 2, &#39;green&#39;: 1})</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Find the ten most common words in Hamlet</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\w+&#39;</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;hamlet.txt&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="n">words</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[(&#39;the&#39;, 1143), (&#39;and&#39;, 966), (&#39;to&#39;, 762), (&#39;of&#39;, 669), (&#39;i&#39;, 631),</span>
<span class="go"> (&#39;you&#39;, 554),  (&#39;a&#39;, 546), (&#39;my&#39;, 514), (&#39;hamlet&#39;, 471), (&#39;in&#39;, 451)]</span>
</pre></div>
</div>
<dl class="class">
<dt id="collections.Counter">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Counter</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> is a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> subclass for counting hashable objects.
It is an unordered collection where elements are stored as dictionary keys
and their counts are stored as dictionary values.  Counts are allowed to be
any integer value including zero or negative counts.  The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
class is similar to bags or multisets in other languages.</p>
<p>Elements are counted from an <em>iterable</em> or initialized from another
<em>mapping</em> (or counter):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>                           <span class="c1"># a new, empty counter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;gallahad&#39;</span><span class="p">)</span>                 <span class="c1"># a new counter from an iterable</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">({</span><span class="s1">&#39;red&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>      <span class="c1"># a new counter from a mapping</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">cats</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">dogs</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>             <span class="c1"># a new counter from keyword args</span>
</pre></div>
</div>
<p>Counter objects have a dictionary interface except that they return a zero
count for missing items instead of raising a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">([</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;ham&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;bacon&#39;</span><span class="p">]</span>                              <span class="c1"># count of a missing element is zero</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Setting a count to zero does not remove an element from a counter.
Use <code class="docutils literal notranslate"><span class="pre">del</span></code> to remove it entirely:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">0</span>                        <span class="c1"># counter entry with a zero count</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">c</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span>                        <span class="c1"># del actually removes the entry</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>Counter objects support three methods beyond those available for all
dictionaries:</p>
<dl class="method">
<dt id="collections.Counter.elements">
<code class="descname">elements</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.elements" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over elements repeating each as many times as its
count.  Elements are returned in arbitrary order.  If an element’s count
is less than one, <a class="reference internal" href="#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a> will ignore it.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">())</span>
<span class="go">[&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.most_common">
<code class="descname">most_common</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.most_common" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the <em>n</em> most common elements and their counts from the
most common to the least.  If <em>n</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>,
<a class="reference internal" href="#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-func docutils literal notranslate"><span class="pre">most_common()</span></code></a> returns <em>all</em> elements in the counter.
Elements with equal counts are ordered arbitrarily:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Counter</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">[(&#39;a&#39;, 5), (&#39;r&#39;, 2), (&#39;b&#39;, 2)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.subtract">
<code class="descname">subtract</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.subtract" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are subtracted from an <em>iterable</em> or from another <em>mapping</em>
(or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but subtracts counts instead
of replacing them.  Both inputs and outputs may be zero or negative.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">d</span><span class="o">=-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">c</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">d</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 0, &#39;c&#39;: -3, &#39;d&#39;: -6})</span>
</pre></div>
</div>
</dd></dl>

<p>The usual dictionary methods are available for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects
except for two which work differently for counters.</p>
<dl class="method">
<dt id="collections.Counter.fromkeys">
<code class="descname">fromkeys</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.fromkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>This class method is not implemented for <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects.</p>
</dd></dl>

<dl class="method">
<dt id="collections.Counter.update">
<code class="descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable-or-mapping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.Counter.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Elements are counted from an <em>iterable</em> or added-in from another
<em>mapping</em> (or counter).  Like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> but adds counts
instead of replacing them.  Also, the <em>iterable</em> is expected to be a
sequence of elements, not a sequence of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p>
</dd></dl>

</dd></dl>

<p>Common patterns for working with <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">sum</span><span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">values</span><span class="p">())</span>                 <span class="c1"># total of all counts</span>
<span class="n">c</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                       <span class="c1"># reset all counts</span>
<span class="nb">list</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># list unique elements</span>
<span class="nb">set</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                          <span class="c1"># convert to a set</span>
<span class="nb">dict</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                         <span class="c1"># convert to a regular dictionary</span>
<span class="n">c</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>                       <span class="c1"># convert to a list of (elem, cnt) pairs</span>
<span class="n">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">(</span><span class="n">list_of_pairs</span><span class="p">))</span>    <span class="c1"># convert from a list of (elem, cnt) pairs</span>
<span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">()[:</span><span class="o">-</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>       <span class="c1"># n least common elements</span>
<span class="n">c</span> <span class="o">+=</span> <span class="n">Counter</span><span class="p">()</span>                  <span class="c1"># remove zero and negative counts</span>
</pre></div>
</div>
<p>Several mathematical operations are provided for combining <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a>
objects to produce multisets (counters that have counts greater than zero).
Addition and subtraction combine counters by adding or subtracting the counts
of corresponding elements.  Intersection and union return the minimum and
maximum of corresponding counts.  Each operation can accept inputs with signed
counts, but the output will exclude results with counts of zero or less.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">+</span> <span class="n">d</span>                       <span class="c1"># add two counters together:  c[x] + d[x]</span>
<span class="go">Counter({&#39;a&#39;: 4, &#39;b&#39;: 3})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">-</span> <span class="n">d</span>                       <span class="c1"># subtract (keeping only positive counts)</span>
<span class="go">Counter({&#39;a&#39;: 2})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">&amp;</span> <span class="n">d</span>                       <span class="c1"># intersection:  min(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 1, &#39;b&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">|</span> <span class="n">d</span>                       <span class="c1"># union:  max(c[x], d[x])</span>
<span class="go">Counter({&#39;a&#39;: 3, &#39;b&#39;: 2})</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Counters were primarily designed to work with positive integers to represent
running counts; however, care was taken to not unnecessarily preclude use
cases needing other types or negative values.  To help with those use cases,
this section documents the minimum range and type restrictions.</p>
<ul class="last simple">
<li>The <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class itself is a dictionary subclass with no
restrictions on its keys and values.  The values are intended to be numbers
representing counts, but you <em>could</em> store anything in the value field.</li>
<li>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code> method requires only that the values be orderable.</li>
<li>For in-place operations such as <code class="docutils literal notranslate"><span class="pre">c[key]</span> <span class="pre">+=</span> <span class="pre">1</span></code>, the value type need only
support addition and subtraction.  So fractions, floats, and decimals would
work and negative values are supported.  The same is also true for
<code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code> which allow negative and zero values
for both inputs and outputs.</li>
<li>The multiset methods are designed only for use cases with positive values.
The inputs may be negative or zero, but only outputs with positive values
are created.  There are no type restrictions, but the value type needs to
support addition, subtraction, and comparison.</li>
<li>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code> method requires integer counts.  It ignores zero and
negative counts.</li>
</ul>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last">
<li><p class="first"><a class="reference external" href="https://code.activestate.com/recipes/576611/">Counter class</a>
adapted for Python 2.5 and an early <a class="reference external" href="https://code.activestate.com/recipes/259174/">Bag recipe</a> for Python 2.4.</p>
</li>
<li><p class="first"><a class="reference external" href="https://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html">Bag class</a>
in Smalltalk.</p>
</li>
<li><p class="first">Wikipedia entry for <a class="reference external" href="https://en.wikipedia.org/wiki/Multiset">Multisets</a>.</p>
</li>
<li><p class="first"><a class="reference external" href="http://www.java2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm">C++ multisets</a>
tutorial with examples.</p>
</li>
<li><p class="first">For mathematical operations on multisets and their use cases, see
<em>Knuth, Donald. The Art of Computer Programming Volume II,
Section 4.6.3, Exercise 19</em>.</p>
</li>
<li><p class="first">To enumerate all distinct multisets of a given size over a given set of
elements, see <a class="reference internal" href="itertools.html#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement()</span></code></a>.</p>
<blockquote>
<div><p>map(Counter, combinations_with_replacement(‘ABC’, 2)) –&gt; AA AB AC BB BC CC</p>
</div></blockquote>
</li>
</ul>
</div>
</div>
<div class="section" id="deque-objects">
<h2>8.3.2. <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> objects<a class="headerlink" href="#deque-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.deque">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">deque</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">[</span>, <em>maxlen</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new deque object initialized left-to-right (using <a class="reference internal" href="#collections.deque.append" title="collections.deque.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a>) with
data from <em>iterable</em>.  If <em>iterable</em> is not specified, the new deque is empty.</p>
<p>Deques are a generalization of stacks and queues (the name is pronounced “deck”
and is short for “double-ended queue”).  Deques support thread-safe, memory
efficient appends and pops from either side of the deque with approximately the
same O(1) performance in either direction.</p>
<p>Though <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> objects support similar operations, they are optimized for
fast fixed-length operations and incur O(n) memory movement costs for
<code class="docutils literal notranslate"><span class="pre">pop(0)</span></code> and <code class="docutils literal notranslate"><span class="pre">insert(0,</span> <span class="pre">v)</span></code> operations which change both the size and
position of the underlying data representation.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>If <em>maxlen</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, deques may grow to an
arbitrary length.  Otherwise, the deque is bounded to the specified maximum
length.  Once a bounded length deque is full, when new items are added, a
corresponding number of items are discarded from the opposite end.  Bounded
length deques provide functionality similar to the <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter in
Unix. They are also useful for tracking transactions and other pools of data
where only the most recent activity is of interest.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <em>maxlen</em> parameter.</p>
</div>
<p>Deque objects support the following methods:</p>
<dl class="method">
<dt id="collections.deque.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the right side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.appendleft">
<code class="descname">appendleft</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.appendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>x</em> to the left side of the deque.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all elements from the deque leaving it with length 0.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.count">
<code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Count the number of deque elements equal to <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extend">
<code class="descname">extend</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extend" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the right side of the deque by appending elements from the iterable
argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.extendleft">
<code class="descname">extendleft</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.extendleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the left side of the deque by appending elements from <em>iterable</em>.
Note, the series of left appends results in reversing the order of
elements in the iterable argument.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the right side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.popleft">
<code class="descname">popleft</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.popleft" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an element from the left side of the deque. If no
elements are present, raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="collections.deque.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the first occurrence of <em>value</em>.  If not found, raises a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.reverse">
<code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.reverse" title="Permalink to this definition">¶</a></dt>
<dd><p>Reverse the elements of the deque in-place and then return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.deque.rotate">
<code class="descname">rotate</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.deque.rotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Rotate the deque <em>n</em> steps to the right.  If <em>n</em> is negative, rotate to
the left.</p>
<p>When the deque is not empty, rotating one step to the right is equivalent to
<code class="docutils literal notranslate"><span class="pre">d.appendleft(d.pop())</span></code>, and rotating one step to the left is
equivalent to <code class="docutils literal notranslate"><span class="pre">d.append(d.popleft())</span></code>.</p>
</dd></dl>

<p>Deque objects also provide one read-only attribute:</p>
<dl class="attribute">
<dt id="collections.deque.maxlen">
<code class="descname">maxlen</code><a class="headerlink" href="#collections.deque.maxlen" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum size of a deque or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unbounded.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>In addition to the above, deques support iteration, pickling, <code class="docutils literal notranslate"><span class="pre">len(d)</span></code>,
<code class="docutils literal notranslate"><span class="pre">reversed(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.copy(d)</span></code>, <code class="docutils literal notranslate"><span class="pre">copy.deepcopy(d)</span></code>, membership testing with
the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator, and subscript references such as <code class="docutils literal notranslate"><span class="pre">d[-1]</span></code>.  Indexed
access is O(1) at both ends but slows to O(n) in the middle.  For fast random
access, use lists instead.</p>
<p>Example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">&#39;ghi&#39;</span><span class="p">)</span>                 <span class="c1"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">d</span><span class="p">:</span>                   <span class="c1"># iterate over the deque&#39;s elements</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="n">elem</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
<span class="go">G</span>
<span class="go">H</span>
<span class="go">I</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;j&#39;</span><span class="p">)</span>                    <span class="c1"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">&#39;f&#39;</span><span class="p">)</span>                <span class="c1"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                                <span class="c1"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                      <span class="c1"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                          <span class="c1"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>                             <span class="c1"># peek at leftmost item</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>                            <span class="c1"># peek at rightmost item</span>
<span class="go">&#39;i&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>                <span class="c1"># list the contents of a deque in reverse</span>
<span class="go">[&#39;i&#39;, &#39;h&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                         <span class="c1"># search the deque</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="s1">&#39;jkl&#39;</span><span class="p">)</span>                  <span class="c1"># add multiple elements at once</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                      <span class="c1"># right rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;l&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>                     <span class="c1"># left rotation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">deque</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">d</span><span class="p">))</span>               <span class="c1"># make a new deque in reverse order</span>
<span class="go">deque([&#39;l&#39;, &#39;k&#39;, &#39;j&#39;, &#39;i&#39;, &#39;h&#39;, &#39;g&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>                        <span class="c1"># empty the deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                          <span class="c1"># cannot pop from an empty deque</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#6&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">-toplevel-</span>
    <span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="gr">IndexError</span>: <span class="n">pop from an empty deque</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">extendleft</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>              <span class="c1"># extendleft() reverses the input order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">deque([&#39;c&#39;, &#39;b&#39;, &#39;a&#39;])</span>
</pre></div>
</div>
<div class="section" id="deque-recipes">
<h3>8.3.2.1. <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> Recipes<a class="headerlink" href="#deque-recipes" title="Permalink to this headline">¶</a></h3>
<p>This section shows various approaches to working with deques.</p>
<p>Bounded length deques provide functionality similar to the <code class="docutils literal notranslate"><span class="pre">tail</span></code> filter
in Unix:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">tail</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">10</span><span class="p">):</span>
    <span class="s1">&#39;Return the last n lines of a file&#39;</span>
    <span class="k">return</span> <span class="n">deque</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">),</span> <span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>Another approach to using deques is to maintain a sequence of recently
added elements by appending to the right and popping to the left:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">moving_average</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">3</span><span class="p">):</span>
    <span class="c1"># moving_average([40, 30, 50, 46, 39, 44]) --&gt; 40.0 42.0 45.0 43.0</span>
    <span class="c1"># http://en.wikipedia.org/wiki/Moving_average</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
    <span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">elem</span> <span class="o">-</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
        <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem</span><span class="p">)</span>
        <span class="k">yield</span> <span class="n">s</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method provides a way to implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing and
deletion.  For example, a pure Python implementation of <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">d[n]</span></code> relies on
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> method to position elements to be popped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">delete_nth</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="o">-</span><span class="n">n</span><span class="p">)</span>
    <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="n">d</span><span class="o">.</span><span class="n">rotate</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
<p>To implement <a class="reference internal" href="#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> slicing, use a similar approach applying
<code class="xref py py-meth docutils literal notranslate"><span class="pre">rotate()</span></code> to bring a target element to the left side of the deque. Remove
old entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">popleft()</span></code>, add new entries with <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, and then
reverse the rotation.
With minor variations on that approach, it is easy to implement Forth style
stack manipulations such as <code class="docutils literal notranslate"><span class="pre">dup</span></code>, <code class="docutils literal notranslate"><span class="pre">drop</span></code>, <code class="docutils literal notranslate"><span class="pre">swap</span></code>, <code class="docutils literal notranslate"><span class="pre">over</span></code>, <code class="docutils literal notranslate"><span class="pre">pick</span></code>,
<code class="docutils literal notranslate"><span class="pre">rot</span></code>, and <code class="docutils literal notranslate"><span class="pre">roll</span></code>.</p>
</div>
</div>
<div class="section" id="defaultdict-objects">
<h2>8.3.3. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects<a class="headerlink" href="#defaultdict-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="collections.defaultdict">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">defaultdict</code><span class="sig-paren">(</span><span class="optional">[</span><em>default_factory</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new dictionary-like object.  <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> is a subclass of the
built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class.  It overrides one method and adds one writable
instance variable.  The remaining functionality is the same as for the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class and is not documented here.</p>
<p>The first argument provides the initial value for the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>
attribute; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>. All remaining arguments are treated the same
as if they were passed to the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor, including keyword
arguments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following method in addition to the
standard <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> operations:</p>
<dl class="method">
<dt id="collections.defaultdict.__missing__">
<code class="descname">__missing__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.defaultdict.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code>, this raises a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception with the <em>key</em> as argument.</p>
<p>If <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is called without arguments
to provide a default value for the given <em>key</em>, this value is inserted in
the dictionary for the <em>key</em>, and returned.</p>
<p>If calling <a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a> raises an exception this exception is
propagated unchanged.</p>
<p>This method is called by the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method of the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> class when the requested key is not found; whatever it
returns or raises is then returned or raised by <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
<p>Note that <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> is <em>not</em> called for any operations besides
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. This means that <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> will, like normal
dictionaries, return <code class="docutils literal notranslate"><span class="pre">None</span></code> as a default rather than using
<a class="reference internal" href="#collections.defaultdict.default_factory" title="collections.defaultdict.default_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code></a>.</p>
</dd></dl>

<p><a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> objects support the following instance variable:</p>
<dl class="attribute">
<dt id="collections.defaultdict.default_factory">
<code class="descname">default_factory</code><a class="headerlink" href="#collections.defaultdict.default_factory" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is used by the <a class="reference internal" href="#collections.defaultdict.__missing__" title="collections.defaultdict.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> method; it is
initialized from the first argument to the constructor, if present, or to
<code class="docutils literal notranslate"><span class="pre">None</span></code>, if absent.</p>
</dd></dl>

</dd></dl>

<div class="section" id="defaultdict-examples">
<h3>8.3.3.1. <a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> Examples<a class="headerlink" href="#defaultdict-examples" title="Permalink to this headline">¶</a></h3>
<p>Using <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code>, it is easy to group a
sequence of key-value pairs into a dictionary of lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;yellow&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>When each key is encountered for the first time, it is not already in the
mapping; so an entry is automatically created using the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code>
function which returns an empty <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code>
operation then attaches the value to the new list.  When keys are encountered
again, the look-up proceeds normally (returning the list for that key) and the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> operation adds another value to the list. This technique is
simpler and faster than an equivalent technique using <a class="reference internal" href="stdtypes.html#dict.setdefault" title="dict.setdefault"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.setdefault()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="o">.</span><span class="n">setdefault</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, [2, 4]), (&#39;red&#39;, [1]), (&#39;yellow&#39;, [1, 3])]</span>
</pre></div>
</div>
<p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for counting (like a bag or multiset in other
languages):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;mississippi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;i&#39;, 4), (&#39;p&#39;, 2), (&#39;s&#39;, 4), (&#39;m&#39;, 1)]</span>
</pre></div>
</div>
<p>When a letter is first encountered, it is missing from the mapping, so the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> function calls <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> to supply a default count of
zero.  The increment operation then builds up the count for each letter.</p>
<p>The function <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> which always returns zero is just a special case of
constant functions.  A faster and more flexible way to create constant functions
is to use <a class="reference internal" href="itertools.html#itertools.repeat" title="itertools.repeat"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.repeat()</span></code></a> which can supply any constant value (not just
zero):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">constant_factory</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">itertools</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">value</span><span class="p">)</span><span class="o">.</span><span class="n">next</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="n">constant_factory</span><span class="p">(</span><span class="s1">&#39;&lt;missing&gt;&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;ran&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">%(name)s</span><span class="s1"> </span><span class="si">%(action)s</span><span class="s1"> to </span><span class="si">%(object)s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">d</span>
<span class="go">&#39;John ran to &lt;missing&gt;&#39;</span>
</pre></div>
</div>
<p>Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_factory</span></code> to <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> makes the
<a class="reference internal" href="#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code></a> useful for building a dictionary of sets:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;red&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;blue&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">set</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">s</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="p">]</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">v</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;blue&#39;, set([2, 4])), (&#39;red&#39;, set([1, 3]))]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="namedtuple-factory-function-for-tuples-with-named-fields">
<h2>8.3.4. <a class="reference internal" href="#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuple()</span></code></a> Factory Function for Tuples with Named Fields<a class="headerlink" href="#namedtuple-factory-function-for-tuples-with-named-fields" title="Permalink to this headline">¶</a></h2>
<p>Named tuples assign meaning to each position in a tuple and allow for more readable,
self-documenting code.  They can be used wherever regular tuples are used, and
they add the ability to access fields by name instead of position index.</p>
<dl class="function">
<dt id="collections.namedtuple">
<code class="descclassname">collections.</code><code class="descname">namedtuple</code><span class="sig-paren">(</span><em>typename</em>, <em>field_names</em><span class="optional">[</span>, <em>verbose=False</em><span class="optional">]</span><span class="optional">[</span>, <em>rename=False</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.namedtuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new tuple subclass named <em>typename</em>.  The new subclass is used to
create tuple-like objects that have fields accessible by attribute lookup as
well as being indexable and iterable.  Instances of the subclass also have a
helpful docstring (with typename and field_names) and a helpful <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>
method which lists the tuple contents in a <code class="docutils literal notranslate"><span class="pre">name=value</span></code> format.</p>
<p>The <em>field_names</em> are a sequence of strings such as <code class="docutils literal notranslate"><span class="pre">['x',</span> <span class="pre">'y']</span></code>.
Alternatively, <em>field_names</em> can be a single string with each fieldname
separated by whitespace and/or commas, for example <code class="docutils literal notranslate"><span class="pre">'x</span> <span class="pre">y'</span></code> or <code class="docutils literal notranslate"><span class="pre">'x,</span> <span class="pre">y'</span></code>.</p>
<p>Any valid Python identifier may be used for a fieldname except for names
starting with an underscore.  Valid identifiers consist of letters, digits,
and underscores but do not start with a digit or underscore and cannot be
a <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> such as <em>class</em>, <em>for</em>, <em>return</em>, <em>global</em>, <em>pass</em>, <em>print</em>,
or <em>raise</em>.</p>
<p>If <em>rename</em> is true, invalid fieldnames are automatically replaced
with positional names.  For example, <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'def',</span> <span class="pre">'ghi',</span> <span class="pre">'abc']</span></code> is
converted to <code class="docutils literal notranslate"><span class="pre">['abc',</span> <span class="pre">'_1',</span> <span class="pre">'ghi',</span> <span class="pre">'_3']</span></code>, eliminating the keyword
<code class="docutils literal notranslate"><span class="pre">def</span></code> and the duplicate fieldname <code class="docutils literal notranslate"><span class="pre">abc</span></code>.</p>
<p>If <em>verbose</em> is true, the class definition is printed just before being built.</p>
<p>Named tuple instances do not have per-instance dictionaries, so they are
lightweight and require no more memory than regular tuples.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>added support for <em>rename</em>.</p>
</div>
</dd></dl>

<p>Example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">],</span> <span class="n">verbose</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="go">class Point(tuple):</span>
<span class="go">    &#39;Point(x, y)&#39;</span>

<span class="go">    __slots__ = ()</span>

<span class="go">    _fields = (&#39;x&#39;, &#39;y&#39;)</span>

<span class="go">    def __new__(_cls, x, y):</span>
<span class="go">        &#39;Create new instance of Point(x, y)&#39;</span>
<span class="go">        return _tuple.__new__(_cls, (x, y))</span>

<span class="go">    @classmethod</span>
<span class="go">    def _make(cls, iterable, new=tuple.__new__, len=len):</span>
<span class="go">        &#39;Make a new Point object from a sequence or iterable&#39;</span>
<span class="go">        result = new(cls, iterable)</span>
<span class="go">        if len(result) != 2:</span>
<span class="go">            raise TypeError(&#39;Expected 2 arguments, got %d&#39; % len(result))</span>
<span class="go">        return result</span>

<span class="go">    def __repr__(self):</span>
<span class="go">        &#39;Return a nicely formatted representation string&#39;</span>
<span class="go">        return &#39;Point(x=%r, y=%r)&#39; % self</span>

<span class="go">    def _asdict(self):</span>
<span class="go">        &#39;Return a new OrderedDict which maps field names to their values&#39;</span>
<span class="go">        return OrderedDict(zip(self._fields, self))</span>

<span class="go">    def _replace(_self, **kwds):</span>
<span class="go">        &#39;Return a new Point object replacing specified fields with new values&#39;</span>
<span class="go">        result = _self._make(map(kwds.pop, (&#39;x&#39;, &#39;y&#39;), _self))</span>
<span class="go">        if kwds:</span>
<span class="go">            raise ValueError(&#39;Got unexpected field names: %r&#39; % kwds.keys())</span>
<span class="go">        return result</span>

<span class="go">    def __getnewargs__(self):</span>
<span class="go">        &#39;Return self as a plain tuple.  Used by copy and pickle.&#39;</span>
<span class="go">        return tuple(self)</span>

<span class="go">    __dict__ = _property(_asdict)</span>

<span class="go">    def __getstate__(self):</span>
<span class="go">        &#39;Exclude the OrderedDict from pickling&#39;</span>
<span class="go">        pass</span>

<span class="go">    x = _property(_itemgetter(0), doc=&#39;Alias for field number 0&#39;)</span>

<span class="go">    y = _property(_itemgetter(1), doc=&#39;Alias for field number 1&#39;)</span>



<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>     <span class="c1"># instantiate with positional or keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">+</span> <span class="n">p</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>             <span class="c1"># indexable like the plain tuple (11, 22)</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">p</span>                <span class="c1"># unpack like a regular tuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="go">(11, 22)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="n">p</span><span class="o">.</span><span class="n">y</span>               <span class="c1"># fields also accessible by name</span>
<span class="go">33</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>                       <span class="c1"># readable __repr__ with a name=value style</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Named tuples are especially useful for assigning field names to result tuples returned
by the <a class="reference internal" href="csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> or <a class="reference internal" href="sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> modules:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">EmployeeRecord</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;EmployeeRecord&#39;</span><span class="p">,</span> <span class="s1">&#39;name, age, title, department, paygrade&#39;</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s2">&quot;employees.csv&quot;</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">))):</span>
    <span class="nb">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;/companydata&#39;</span><span class="p">)</span>
<span class="n">cursor</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;SELECT name, age, title, department, paygrade FROM employees&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">emp</span> <span class="ow">in</span> <span class="nb">map</span><span class="p">(</span><span class="n">EmployeeRecord</span><span class="o">.</span><span class="n">_make</span><span class="p">,</span> <span class="n">cursor</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()):</span>
    <span class="nb">print</span> <span class="n">emp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">emp</span><span class="o">.</span><span class="n">title</span>
</pre></div>
</div>
<p>In addition to the methods inherited from tuples, named tuples support
three additional methods and one attribute.  To prevent conflicts with
field names, the method and attribute names start with an underscore.</p>
<dl class="classmethod">
<dt id="collections.somenamedtuple._make">
<em class="property">classmethod </em><code class="descclassname">somenamedtuple.</code><code class="descname">_make</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._make" title="Permalink to this definition">¶</a></dt>
<dd><p>Class method that makes a new instance from an existing sequence or iterable.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._asdict">
<code class="descclassname">somenamedtuple.</code><code class="descname">_asdict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._asdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> which maps field names to their corresponding
values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">OrderedDict([(&#39;x&#39;, 11), (&#39;y&#39;, 22)])</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Returns an <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> instead of a regular <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.somenamedtuple._replace">
<code class="descclassname">somenamedtuple.</code><code class="descname">_replace</code><span class="sig-paren">(</span><em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.somenamedtuple._replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the named tuple replacing specified fields with new
values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">11</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mi">33</span><span class="p">)</span>
<span class="go">Point(x=33, y=22)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">partnum</span><span class="p">,</span> <span class="n">record</span> <span class="ow">in</span> <span class="n">inventory</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">inventory</span><span class="p">[</span><span class="n">partnum</span><span class="p">]</span> <span class="o">=</span> <span class="n">record</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">price</span><span class="o">=</span><span class="n">newprices</span><span class="p">[</span><span class="n">partnum</span><span class="p">],</span> <span class="n">timestamp</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="collections.somenamedtuple._fields">
<code class="descclassname">somenamedtuple.</code><code class="descname">_fields</code><a class="headerlink" href="#collections.somenamedtuple._fields" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple of strings listing the field names.  Useful for introspection
and for creating new named tuple types from existing named tuples.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">_fields</span>            <span class="c1"># view the field names</span>
<span class="go">(&#39;x&#39;, &#39;y&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">Color</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Color&#39;</span><span class="p">,</span> <span class="s1">&#39;red green blue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Pixel&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="n">Color</span><span class="o">.</span><span class="n">_fields</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Pixel</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">22</span><span class="p">,</span> <span class="mi">128</span><span class="p">,</span> <span class="mi">255</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">Pixel(x=11, y=22, red=128, green=255, blue=0)</span>
</pre></div>
</div>
</dd></dl>

<p>To retrieve a field whose name is stored in a string, use the <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>
function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">p</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">)</span>
<span class="go">11</span>
</pre></div>
</div>
<p>To convert a dictionary to a named tuple, use the double-star-operator
(as described in <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;x&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;y&#39;</span><span class="p">:</span> <span class="mi">22</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Point</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">Point(x=11, y=22)</span>
</pre></div>
</div>
<p>Since a named tuple is a regular Python class, it is easy to add or change
functionality with a subclass.  Here is how to add a calculated field and
a fixed-width print format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point&#39;</span><span class="p">,</span> <span class="s1">&#39;x y&#39;</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">... </span>    <span class="nd">@property</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">hypot</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">**</span> <span class="mi">2</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">**</span> <span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="mf">0.5</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;Point: x=</span><span class="si">%6.3f</span><span class="s1">  y=</span><span class="si">%6.3f</span><span class="s1">  hypot=</span><span class="si">%6.3f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">hypot</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">Point</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="n">Point</span><span class="p">(</span><span class="mi">14</span><span class="p">,</span> <span class="mi">5</span><span class="o">/</span><span class="mf">7.</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">p</span>
<span class="go">Point: x= 3.000  y= 4.000  hypot= 5.000</span>
<span class="go">Point: x=14.000  y= 0.714  hypot=14.018</span>
</pre></div>
</div>
<p>The subclass shown above sets <code class="docutils literal notranslate"><span class="pre">__slots__</span></code> to an empty tuple.  This helps
keep memory requirements low by preventing the creation of instance dictionaries.</p>
<p>Subclassing is not useful for adding new, stored fields.  Instead, simply
create a new named tuple type from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields</span></code> attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Point3D</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Point3D&#39;</span><span class="p">,</span> <span class="n">Point</span><span class="o">.</span><span class="n">_fields</span> <span class="o">+</span> <span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">,))</span>
</pre></div>
</div>
<p>Default values can be implemented by using <code class="xref py py-meth docutils literal notranslate"><span class="pre">_replace()</span></code> to
customize a prototype instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Account</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Account&#39;</span><span class="p">,</span> <span class="s1">&#39;owner balance transaction_count&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">default_account</span> <span class="o">=</span> <span class="n">Account</span><span class="p">(</span><span class="s1">&#39;&lt;owner name&gt;&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">johns_account</span> <span class="o">=</span> <span class="n">default_account</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">owner</span><span class="o">=</span><span class="s1">&#39;John&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Enumerated constants can be implemented with named tuples, but it is simpler
and more efficient to use a simple class declaration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Status&#39;</span><span class="p">,</span> <span class="s1">&#39;open pending closed&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Status</span><span class="o">.</span><span class="n">open</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">pending</span><span class="p">,</span> <span class="n">Status</span><span class="o">.</span><span class="n">closed</span>
<span class="go">(0, 1, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Status</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">open</span><span class="p">,</span> <span class="n">pending</span><span class="p">,</span> <span class="n">closed</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://code.activestate.com/recipes/500261/">Named tuple recipe</a>
adapted for Python 2.4.</p>
</div>
</div>
<div class="section" id="ordereddict-objects">
<h2>8.3.5. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects<a class="headerlink" href="#ordereddict-objects" title="Permalink to this headline">¶</a></h2>
<p>Ordered dictionaries are just like regular dictionaries but they remember the
order that items were inserted.  When iterating over an ordered dictionary,
the items are returned in the order their keys were first added.</p>
<dl class="class">
<dt id="collections.OrderedDict">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">OrderedDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>items</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an instance of a dict subclass, supporting the usual <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>
methods.  An <em>OrderedDict</em> is a dict that remembers the order that keys
were first inserted. If a new entry overwrites an existing entry, the
original insertion position is left unchanged.  Deleting an entry and
reinserting it will move it to the end.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="collections.OrderedDict.popitem">
<code class="descclassname">OrderedDict.</code><code class="descname">popitem</code><span class="sig-paren">(</span><em>last=True</em><span class="sig-paren">)</span><a class="headerlink" href="#collections.OrderedDict.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> method for ordered dictionaries returns and removes
a (key, value) pair.  The pairs are returned in LIFO order if <em>last</em> is
true or FIFO order if false.</p>
</dd></dl>

<p>In addition to the usual mapping methods, ordered dictionaries also support
reverse iteration using <a class="reference internal" href="functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p>
<p>Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects are order-sensitive
and are implemented as <code class="docutils literal notranslate"><span class="pre">list(od1.items())==list(od2.items())</span></code>.
Equality tests between <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects and other
<a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> objects are order-insensitive like regular
dictionaries.  This allows <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> objects to be substituted
anywhere a regular dictionary is used.</p>
<p>The <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> constructor and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method both accept
keyword arguments, but their order is lost because Python’s function call
semantics pass-in keyword arguments using a regular unordered dictionary.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://code.activestate.com/recipes/576693/">Equivalent OrderedDict recipe</a>
that runs on Python 2.4 or later.</p>
</div>
<div class="section" id="ordereddict-examples-and-recipes">
<h3>8.3.5.1. <a class="reference internal" href="#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> Examples and Recipes<a class="headerlink" href="#ordereddict-examples-and-recipes" title="Permalink to this headline">¶</a></h3>
<p>Since an ordered dictionary remembers its insertion order, it can be used
in conjunction with sorting to make a sorted dictionary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># regular unsorted dictionary</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;banana&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by key</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;apple&#39;, 4), (&#39;banana&#39;, 3), (&#39;orange&#39;, 2), (&#39;pear&#39;, 1)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="n">t</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3), (&#39;apple&#39;, 4)])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dictionary sorted by length of the key string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">OrderedDict</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">(),</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">t</span><span class="p">:</span> <span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">])))</span>
<span class="go">OrderedDict([(&#39;pear&#39;, 1), (&#39;apple&#39;, 4), (&#39;orange&#39;, 2), (&#39;banana&#39;, 3)])</span>
</pre></div>
</div>
<p>The new sorted dictionaries maintain their sort order when entries
are deleted.  But when new keys are added, the keys are appended
to the end and the sort is not maintained.</p>
<p>It is also straight-forward to create an ordered dictionary variant
that remembers the order the keys were <em>last</em> inserted.
If a new entry overwrites an existing entry, the
original insertion position is changed and moved to the end:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LastUpdatedOrderedDict</span><span class="p">(</span><span class="n">OrderedDict</span><span class="p">):</span>
    <span class="s1">&#39;Store items in the order the keys were last added&#39;</span>

    <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">in</span> <span class="bp">self</span><span class="p">:</span>
            <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
        <span class="n">OrderedDict</span><span class="o">.</span><span class="fm">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>An ordered dictionary can be combined with the <a class="reference internal" href="#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class
so that the counter remembers the order elements are first encountered:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">OrderedCounter</span><span class="p">(</span><span class="n">Counter</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">):</span>
     <span class="s1">&#39;Counter that remembers the order elements are first encountered&#39;</span>

     <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">(</span><span class="si">%r</span><span class="s1">)&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>

     <span class="k">def</span> <span class="nf">__reduce__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">,</span> <span class="p">(</span><span class="n">OrderedDict</span><span class="p">(</span><span class="bp">self</span><span class="p">),)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="collections-abstract-base-classes">
<span id="id1"></span><h2>8.3.6. Collections Abstract Base Classes<a class="headerlink" href="#collections-abstract-base-classes" title="Permalink to this headline">¶</a></h2>
<p>The collections module offers the following <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">ABCs</span></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="18%" />
<col width="18%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">ABC</th>
<th class="head">Inherits from</th>
<th class="head">Abstract Methods</th>
<th class="head">Mixin Methods</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__hash__</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Iterator" title="collections.Iterator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterator</span></code></a></td>
<td><a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">next</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">__iter__</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.Callable" title="collections.Callable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Callable</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__call__</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code>, <code class="docutils literal notranslate"><span class="pre">__reversed__</span></code>,
<code class="docutils literal notranslate"><span class="pre">index</span></code>, and <code class="docutils literal notranslate"><span class="pre">count</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableSequence" title="collections.MutableSequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSequence</span></code></a></td>
<td><a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code>,
<code class="docutils literal notranslate"><span class="pre">insert</span></code></td>
<td>Inherited <a class="reference internal" href="#collections.Sequence" title="collections.Sequence"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sequence</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">append</span></code>, <code class="docutils literal notranslate"><span class="pre">reverse</span></code>, <code class="docutils literal notranslate"><span class="pre">extend</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>,
<code class="docutils literal notranslate"><span class="pre">remove</span></code>, and <code class="docutils literal notranslate"><span class="pre">__iadd__</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">__le__</span></code>, <code class="docutils literal notranslate"><span class="pre">__lt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ne__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__gt__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ge__</span></code>, <code class="docutils literal notranslate"><span class="pre">__and__</span></code>, <code class="docutils literal notranslate"><span class="pre">__or__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__sub__</span></code>, <code class="docutils literal notranslate"><span class="pre">__xor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">isdisjoint</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a></td>
<td><a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code>,
<code class="docutils literal notranslate"><span class="pre">add</span></code>,
<code class="docutils literal notranslate"><span class="pre">discard</span></code></td>
<td>Inherited <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code>, <code class="docutils literal notranslate"><span class="pre">__ior__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iand__</span></code>, <code class="docutils literal notranslate"><span class="pre">__ixor__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__isub__</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a>,
<a class="reference internal" href="#collections.Iterable" title="collections.Iterable"><code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code></a>,
<a class="reference internal" href="#collections.Container" title="collections.Container"><code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">keys</span></code>, <code class="docutils literal notranslate"><span class="pre">items</span></code>, <code class="docutils literal notranslate"><span class="pre">values</span></code>,
<code class="docutils literal notranslate"><span class="pre">get</span></code>, <code class="docutils literal notranslate"><span class="pre">__eq__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__ne__</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a></td>
<td><a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">__getitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__setitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__delitem__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
<td>Inherited <a class="reference internal" href="#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> methods and
<code class="docutils literal notranslate"><span class="pre">pop</span></code>, <code class="docutils literal notranslate"><span class="pre">popitem</span></code>, <code class="docutils literal notranslate"><span class="pre">clear</span></code>, <code class="docutils literal notranslate"><span class="pre">update</span></code>,
and <code class="docutils literal notranslate"><span class="pre">setdefault</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></td>
<td><a class="reference internal" href="#collections.Sized" title="collections.Sized"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sized</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__len__</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.ItemsView" title="collections.ItemsView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ItemsView</span></code></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#collections.KeysView" title="collections.KeysView"><code class="xref py py-class docutils literal notranslate"><span class="pre">KeysView</span></code></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a>,
<a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__iter__</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#collections.ValuesView" title="collections.ValuesView"><code class="xref py py-class docutils literal notranslate"><span class="pre">ValuesView</span></code></a></td>
<td><a class="reference internal" href="#collections.MappingView" title="collections.MappingView"><code class="xref py py-class docutils literal notranslate"><span class="pre">MappingView</span></code></a></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">__contains__</span></code>, <code class="docutils literal notranslate"><span class="pre">__iter__</span></code></td>
</tr>
</tbody>
</table>
<dl class="class">
<dt id="collections.Container">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Container</code><a class="headerlink" href="#collections.Container" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Hashable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Hashable</code><a class="headerlink" href="#collections.Hashable" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Sized">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Sized</code><a class="headerlink" href="#collections.Sized" title="Permalink to this definition">¶</a></dt>
<dt id="collections.Callable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Callable</code><a class="headerlink" href="#collections.Callable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for classes that provide respectively the methods <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterable">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Iterable</code><a class="headerlink" href="#collections.Iterable" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method.
See also the definition of <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Iterator">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Iterator</code><a class="headerlink" href="#collections.Iterator" title="Permalink to this definition">¶</a></dt>
<dd><p>ABC for classes that provide the <a class="reference internal" href="stdtypes.html#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and
<a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods.  See also the definition of <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Sequence">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Sequence</code><a class="headerlink" href="#collections.Sequence" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSequence">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableSequence</code><a class="headerlink" href="#collections.MutableSequence" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequences</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Set">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Set</code><a class="headerlink" href="#collections.Set" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableSet">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableSet</code><a class="headerlink" href="#collections.MutableSet" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable sets.</p>
</dd></dl>

<dl class="class">
<dt id="collections.Mapping">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">Mapping</code><a class="headerlink" href="#collections.Mapping" title="Permalink to this definition">¶</a></dt>
<dt id="collections.MutableMapping">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MutableMapping</code><a class="headerlink" href="#collections.MutableMapping" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for read-only and mutable <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mappings</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="collections.MappingView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">MappingView</code><a class="headerlink" href="#collections.MappingView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ItemsView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">ItemsView</code><a class="headerlink" href="#collections.ItemsView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.KeysView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">KeysView</code><a class="headerlink" href="#collections.KeysView" title="Permalink to this definition">¶</a></dt>
<dt id="collections.ValuesView">
<em class="property">class </em><code class="descclassname">collections.</code><code class="descname">ValuesView</code><a class="headerlink" href="#collections.ValuesView" title="Permalink to this definition">¶</a></dt>
<dd><p>ABCs for mapping, items, keys, and values <a class="reference internal" href="../glossary.html#term-dictionary-view"><span class="xref std std-term">views</span></a>.</p>
</dd></dl>

<p>These ABCs allow us to ask classes or instances if they provide
particular functionality, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">size</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">myvar</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">Sized</span><span class="p">):</span>
    <span class="n">size</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">myvar</span><span class="p">)</span>
</pre></div>
</div>
<p>Several of the ABCs are also useful as mixins that make it easier to develop
classes supporting container APIs.  For example, to write a class supporting
the full <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> API, it only necessary to supply the three underlying
abstract methods: <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>.
The ABC supplies the remaining methods such as <a class="reference internal" href="../reference/datamodel.html#object.__and__" title="object.__and__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__and__()</span></code></a> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isdisjoint()</span></code></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ListBasedSet</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">Set</span><span class="p">):</span>
     <span class="sd">&#39;&#39;&#39; Alternate set implementation favoring space over speed</span>
<span class="sd">         and not requiring the set elements to be hashable. &#39;&#39;&#39;</span>
     <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
         <span class="bp">self</span><span class="o">.</span><span class="n">elements</span> <span class="o">=</span> <span class="n">lst</span> <span class="o">=</span> <span class="p">[]</span>
         <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
             <span class="k">if</span> <span class="n">value</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">lst</span><span class="p">:</span>
                 <span class="n">lst</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>

     <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

     <span class="k">def</span> <span class="nf">__contains__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
         <span class="k">return</span> <span class="n">value</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">elements</span>

     <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
         <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">elements</span><span class="p">)</span>

<span class="n">s1</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="n">s2</span> <span class="o">=</span> <span class="n">ListBasedSet</span><span class="p">(</span><span class="s1">&#39;defghi&#39;</span><span class="p">)</span>
<span class="n">overlap</span> <span class="o">=</span> <span class="n">s1</span> <span class="o">&amp;</span> <span class="n">s2</span>            <span class="c1"># The __and__() method is supported automatically</span>
</pre></div>
</div>
<p>Notes on using <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a> as a mixin:</p>
<ol class="arabic simple">
<li>Since some set operations create new sets, the default mixin methods need
a way to create new instances from an iterable. The class constructor is
assumed to have a signature in the form <code class="docutils literal notranslate"><span class="pre">ClassName(iterable)</span></code>.
That assumption is factored-out to an internal classmethod called
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code> which calls <code class="docutils literal notranslate"><span class="pre">cls(iterable)</span></code> to produce a new set.
If the <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin is being used in a class with a different
constructor signature, you will need to override <code class="xref py py-meth docutils literal notranslate"><span class="pre">_from_iterable()</span></code>
with a classmethod that can construct new instances from
an iterable argument.</li>
<li>To override the comparisons (presumably for speed, as the
semantics are fixed), redefine <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a>,
then the other operations will automatically follow suit.</li>
<li>The <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> mixin provides a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_hash()</span></code> method to compute a hash value
for the set; however, <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> is not defined because not all sets
are hashable or immutable.  To add set hashability using mixins,
inherit from both <a class="reference internal" href="#collections.Set" title="collections.Set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Set()</span></code></a> and <a class="reference internal" href="#collections.Hashable" title="collections.Hashable"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Hashable()</span></code></a>, then define
<code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">Set._hash</span></code>.</li>
</ol>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li><a class="reference external" href="https://code.activestate.com/recipes/576694/">OrderedSet recipe</a> for an
example built on <a class="reference internal" href="#collections.MutableSet" title="collections.MutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableSet</span></code></a>.</li>
<li>For more about ABCs, see the <a class="reference internal" href="abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module and <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a>.</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a><ul>
<li><a class="reference internal" href="#counter-objects">8.3.1. <code class="docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li>
<li><a class="reference internal" href="#deque-objects">8.3.2. <code class="docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul>
<li><a class="reference internal" href="#deque-recipes">8.3.2.1. <code class="docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#defaultdict-objects">8.3.3. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul>
<li><a class="reference internal" href="#defaultdict-examples">8.3.3.1. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <code class="docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li>
<li><a class="reference internal" href="#ordereddict-objects">8.3.5. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul>
<li><a class="reference internal" href="#ordereddict-examples-and-recipes">8.3.5.1. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> Examples and Recipes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#collections-abstract-base-classes">8.3.6. Collections Abstract Base Classes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="calendar.html"
                        title="previous chapter">8.2. <code class="docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="heapq.html"
                        title="next chapter">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/collections.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="heapq.html" title="8.4. heapq — Heap queue algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��rcchtml/library/colorpicker.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.9. ColorPicker — Color selection dialog &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38. MacPython OSA Modules" href="macosa.html" />
    <link rel="prev" title="37.8. Mac OS Toolbox Modules" href="carbon.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/colorpicker.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macosa.html" title="38. MacPython OSA Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="carbon.html" title="37.8. Mac OS Toolbox Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ColorPicker">
<span id="colorpicker-color-selection-dialog"></span><h1>37.9. <a class="reference internal" href="#module-ColorPicker" title="ColorPicker: Interface to the standard color selection dialog. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ColorPicker</span></code></a> — Color selection dialog<a class="headerlink" href="#module-ColorPicker" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-ColorPicker" title="ColorPicker: Interface to the standard color selection dialog. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ColorPicker</span></code></a> module provides access to the standard color picker
dialog.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<dl class="function">
<dt id="ColorPicker.GetColor">
<code class="descclassname">ColorPicker.</code><code class="descname">GetColor</code><span class="sig-paren">(</span><em>prompt</em>, <em>rgb</em><span class="sig-paren">)</span><a class="headerlink" href="#ColorPicker.GetColor" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a standard color selection dialog and allow the user to select a color.
The user is given instruction by the <em>prompt</em> string, and the default color is
set to <em>rgb</em>.  <em>rgb</em> must be a tuple giving the red, green, and blue components
of the color. <a class="reference internal" href="#ColorPicker.GetColor" title="ColorPicker.GetColor"><code class="xref py py-func docutils literal notranslate"><span class="pre">GetColor()</span></code></a> returns a tuple giving the user’s selected color
and a flag indicating whether they accepted the selection of cancelled.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="carbon.html"
                        title="previous chapter">37.8. Mac OS Toolbox Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="macosa.html"
                        title="next chapter">38. MacPython OSA Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/colorpicker.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macosa.html" title="38. MacPython OSA Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="carbon.html" title="37.8. Mac OS Toolbox Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�pҏ.�.html/library/colorsys.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.7. colorsys — Conversions between color systems &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.8. imghdr — Determine the type of an image" href="imghdr.html" />
    <link rel="prev" title="21.6. chunk — Read IFF chunked data" href="chunk.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/colorsys.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imghdr.html" title="21.8. imghdr — Determine the type of an image"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="chunk.html" title="21.6. chunk — Read IFF chunked data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-colorsys">
<span id="colorsys-conversions-between-color-systems"></span><h1>21.7. <a class="reference internal" href="#module-colorsys" title="colorsys: Conversion functions between RGB and other color systems."><code class="xref py py-mod docutils literal notranslate"><span class="pre">colorsys</span></code></a> — Conversions between color systems<a class="headerlink" href="#module-colorsys" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/colorsys.py">Lib/colorsys.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-colorsys" title="colorsys: Conversion functions between RGB and other color systems."><code class="xref py py-mod docutils literal notranslate"><span class="pre">colorsys</span></code></a> module defines bidirectional conversions of color values
between colors expressed in the RGB (Red Green Blue) color space used in
computer monitors and three other coordinate systems: YIQ, HLS (Hue Lightness
Saturation) and HSV (Hue Saturation Value).  Coordinates in all of these color
spaces are floating point values.  In the YIQ space, the Y coordinate is between
0 and 1, but the I and Q coordinates can be positive or negative.  In all other
spaces, the coordinates are all between 0 and 1.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">More information about color spaces can be found at
<a class="reference external" href="http://www.poynton.com/ColorFAQ.html">http://www.poynton.com/ColorFAQ.html</a> and
<a class="reference external" href="https://www.cambridgeincolour.com/tutorials/color-spaces.htm">https://www.cambridgeincolour.com/tutorials/color-spaces.htm</a>.</p>
</div>
<p>The <a class="reference internal" href="#module-colorsys" title="colorsys: Conversion functions between RGB and other color systems."><code class="xref py py-mod docutils literal notranslate"><span class="pre">colorsys</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="colorsys.rgb_to_yiq">
<code class="descclassname">colorsys.</code><code class="descname">rgb_to_yiq</code><span class="sig-paren">(</span><em>r</em>, <em>g</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.rgb_to_yiq" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from RGB coordinates to YIQ coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="colorsys.yiq_to_rgb">
<code class="descclassname">colorsys.</code><code class="descname">yiq_to_rgb</code><span class="sig-paren">(</span><em>y</em>, <em>i</em>, <em>q</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.yiq_to_rgb" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from YIQ coordinates to RGB coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="colorsys.rgb_to_hls">
<code class="descclassname">colorsys.</code><code class="descname">rgb_to_hls</code><span class="sig-paren">(</span><em>r</em>, <em>g</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.rgb_to_hls" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from RGB coordinates to HLS coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="colorsys.hls_to_rgb">
<code class="descclassname">colorsys.</code><code class="descname">hls_to_rgb</code><span class="sig-paren">(</span><em>h</em>, <em>l</em>, <em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.hls_to_rgb" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from HLS coordinates to RGB coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="colorsys.rgb_to_hsv">
<code class="descclassname">colorsys.</code><code class="descname">rgb_to_hsv</code><span class="sig-paren">(</span><em>r</em>, <em>g</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.rgb_to_hsv" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from RGB coordinates to HSV coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="colorsys.hsv_to_rgb">
<code class="descclassname">colorsys.</code><code class="descname">hsv_to_rgb</code><span class="sig-paren">(</span><em>h</em>, <em>s</em>, <em>v</em><span class="sig-paren">)</span><a class="headerlink" href="#colorsys.hsv_to_rgb" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the color from HSV coordinates to RGB coordinates.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">colorsys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">colorsys</span><span class="o">.</span><span class="n">rgb_to_hsv</span><span class="p">(</span><span class="mf">0.2</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">)</span>
<span class="go">(0.5, 0.5, 0.4)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">colorsys</span><span class="o">.</span><span class="n">hsv_to_rgb</span><span class="p">(</span><span class="mf">0.5</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">)</span>
<span class="go">(0.2, 0.4, 0.4)</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="chunk.html"
                        title="previous chapter">21.6. <code class="docutils literal notranslate"><span class="pre">chunk</span></code> — Read IFF chunked data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imghdr.html"
                        title="next chapter">21.8. <code class="docutils literal notranslate"><span class="pre">imghdr</span></code> — Determine the type of an image</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/colorsys.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imghdr.html" title="21.8. imghdr — Determine the type of an image"
             >next</a> |</li>
        <li class="right" >
          <a href="chunk.html" title="21.6. chunk — Read IFF chunked data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�O9?�<�<html/library/commands.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.16. commands — Utilities for running commands &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37. Mac OS X specific services" href="mac.html" />
    <link rel="prev" title="36.15. syslog — Unix syslog library routines" href="syslog.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/commands.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mac.html" title="37. Mac OS X specific services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="syslog.html" title="36.15. syslog — Unix syslog library routines"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-commands">
<span id="commands-utilities-for-running-commands"></span><h1>36.16. <a class="reference internal" href="#module-commands" title="commands: Utility functions for running external commands. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">commands</span></code></a> — Utilities for running commands<a class="headerlink" href="#module-commands" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-commands" title="commands: Utility functions for running external commands. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">commands</span></code></a> module has been removed in Python 3.  Use the
<a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module instead.</p>
</div>
<p>The <a class="reference internal" href="#module-commands" title="commands: Utility functions for running external commands. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">commands</span></code></a> module contains wrapper functions for <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> which
take a system command as a string and return any output generated by the command
and, optionally, the exit status.</p>
<p>The <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module provides more powerful facilities for spawning new
processes and retrieving their results.  Using the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module is
preferable to using the <a class="reference internal" href="#module-commands" title="commands: Utility functions for running external commands. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">commands</span></code></a> module.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3.x, <a class="reference internal" href="#commands.getstatus" title="commands.getstatus"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstatus()</span></code></a> and two undocumented functions
(<code class="xref py py-func docutils literal notranslate"><span class="pre">mk2arg()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">mkarg()</span></code>) have been removed.  Also,
<a class="reference internal" href="#commands.getstatusoutput" title="commands.getstatusoutput"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstatusoutput()</span></code></a> and <a class="reference internal" href="#commands.getoutput" title="commands.getoutput"><code class="xref py py-func docutils literal notranslate"><span class="pre">getoutput()</span></code></a> have been moved to the
<a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.</p>
</div>
<p>The <a class="reference internal" href="#module-commands" title="commands: Utility functions for running external commands. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">commands</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="commands.getstatusoutput">
<code class="descclassname">commands.</code><code class="descname">getstatusoutput</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#commands.getstatusoutput" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the string <em>cmd</em> in a shell with <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> and return a 2-tuple
<code class="docutils literal notranslate"><span class="pre">(status,</span> <span class="pre">output)</span></code>.  <em>cmd</em> is actually run as <code class="docutils literal notranslate"><span class="pre">{</span> <span class="pre">cmd</span> <span class="pre">;</span> <span class="pre">}</span> <span class="pre">2&gt;&amp;1</span></code>, so that the
returned output will contain output or error messages. A trailing newline is
stripped from the output. The exit status for the command can be interpreted
according to the rules for the C function <code class="xref c c-func docutils literal notranslate"><span class="pre">wait()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="commands.getoutput">
<code class="descclassname">commands.</code><code class="descname">getoutput</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#commands.getoutput" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#commands.getstatusoutput" title="commands.getstatusoutput"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstatusoutput()</span></code></a>, except the exit status is ignored and the return
value is a string containing the command’s output.</p>
</dd></dl>

<dl class="function">
<dt id="commands.getstatus">
<code class="descclassname">commands.</code><code class="descname">getstatus</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#commands.getstatus" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the output of <code class="docutils literal notranslate"><span class="pre">ls</span> <span class="pre">-ld</span> <span class="pre">file</span></code> as a string.  This function uses the
<a class="reference internal" href="#commands.getoutput" title="commands.getoutput"><code class="xref py py-func docutils literal notranslate"><span class="pre">getoutput()</span></code></a> function, and properly escapes backslashes and dollar signs in
the argument.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is nonobvious and useless.  The name is also misleading in the
presence of <a class="reference internal" href="#commands.getstatusoutput" title="commands.getstatusoutput"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstatusoutput()</span></code></a>.</p>
</div>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">commands</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">commands</span><span class="o">.</span><span class="n">getstatusoutput</span><span class="p">(</span><span class="s1">&#39;ls /bin/ls&#39;</span><span class="p">)</span>
<span class="go">(0, &#39;/bin/ls&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">commands</span><span class="o">.</span><span class="n">getstatusoutput</span><span class="p">(</span><span class="s1">&#39;cat /bin/junk&#39;</span><span class="p">)</span>
<span class="go">(256, &#39;cat: /bin/junk: No such file or directory&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">commands</span><span class="o">.</span><span class="n">getstatusoutput</span><span class="p">(</span><span class="s1">&#39;/bin/junk&#39;</span><span class="p">)</span>
<span class="go">(256, &#39;sh: /bin/junk: not found&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">commands</span><span class="o">.</span><span class="n">getoutput</span><span class="p">(</span><span class="s1">&#39;ls /bin/ls&#39;</span><span class="p">)</span>
<span class="go">&#39;/bin/ls&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">commands</span><span class="o">.</span><span class="n">getstatus</span><span class="p">(</span><span class="s1">&#39;/bin/ls&#39;</span><span class="p">)</span>
<span class="go">&#39;-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a></dt>
<dd>Module for spawning and managing subprocesses.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="syslog.html"
                        title="previous chapter">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mac.html"
                        title="next chapter">37. Mac OS X specific services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/commands.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mac.html" title="37. Mac OS X specific services"
             >next</a> |</li>
        <li class="right" >
          <a href="syslog.html" title="36.15. syslog — Unix syslog library routines"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�)>�H�Hhtml/library/compileall.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.11. compileall — Byte-compile Python libraries &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.12. dis — Disassembler for Python bytecode" href="dis.html" />
    <link rel="prev" title="32.10. py_compile — Compile Python source files" href="py_compile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/compileall.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dis.html" title="32.12. dis — Disassembler for Python bytecode"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="py_compile.html" title="32.10. py_compile — Compile Python source files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-compileall">
<span id="compileall-byte-compile-python-libraries"></span><h1>32.11. <a class="reference internal" href="#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> — Byte-compile Python libraries<a class="headerlink" href="#module-compileall" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/compileall.py">Lib/compileall.py</a></p>
<hr class="docutils" />
<p>This module provides some utility functions to support installing Python
libraries.  These functions compile Python source files in a directory tree.
This module can be used to create the cached byte-code files at library
installation time, which makes them available for use even by users who don’t
have write permission to the library directories.</p>
<div class="section" id="command-line-use">
<h2>32.11.1. Command-line use<a class="headerlink" href="#command-line-use" title="Permalink to this headline">¶</a></h2>
<p>This module can work as a script (using <strong class="program">python -m compileall</strong>) to
compile Python sources.</p>
<dl class="cmdoption">
<dt id="cmdoption-compileall-arg-directory">
<code class="descname">directory</code><code class="descclassname"> ...</code><a class="headerlink" href="#cmdoption-compileall-arg-directory" title="Permalink to this definition">¶</a></dt>
<dt id="cmdoption-compileall-arg-file">
<code class="descname">file</code><code class="descclassname"> ...</code><a class="headerlink" href="#cmdoption-compileall-arg-file" title="Permalink to this definition">¶</a></dt>
<dd><p>Positional arguments are files to compile or directories that contain
source files, traversed recursively.  If no argument is given, behave as if
the command line was <code class="docutils literal notranslate"><span class="pre">-l</span> <span class="pre">&lt;directories</span> <span class="pre">from</span> <span class="pre">sys.path&gt;</span></code>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-l">
<code class="descname">-l</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-compileall-l" title="Permalink to this definition">¶</a></dt>
<dd><p>Do not recurse into subdirectories, only compile source code files directly
contained in the named or implied directories.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-f">
<code class="descname">-f</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-compileall-f" title="Permalink to this definition">¶</a></dt>
<dd><p>Force rebuild even if timestamps are up-to-date.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-q">
<code class="descname">-q</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-compileall-q" title="Permalink to this definition">¶</a></dt>
<dd><p>Do not print the list of files compiled, print only error messages.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-d">
<code class="descname">-d</code><code class="descclassname"> destdir</code><a class="headerlink" href="#cmdoption-compileall-d" title="Permalink to this definition">¶</a></dt>
<dd><p>Directory prepended to the path to each file being compiled.  This will
appear in compilation time tracebacks, and is also compiled in to the
byte-code file, where it will be used in tracebacks and other messages in
cases where the source file does not exist at the time the byte-code file is
executed.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-x">
<code class="descname">-x</code><code class="descclassname"> regex</code><a class="headerlink" href="#cmdoption-compileall-x" title="Permalink to this definition">¶</a></dt>
<dd><p>regex is used to search the full path to each file considered for
compilation, and if the regex produces a match, the file is skipped.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-compileall-i">
<code class="descname">-i</code><code class="descclassname"> list</code><a class="headerlink" href="#cmdoption-compileall-i" title="Permalink to this definition">¶</a></dt>
<dd><p>Read the file <code class="docutils literal notranslate"><span class="pre">list</span></code> and add each line that it contains to the list of
files and directories to compile.  If <code class="docutils literal notranslate"><span class="pre">list</span></code> is <code class="docutils literal notranslate"><span class="pre">-</span></code>, read lines from
<code class="docutils literal notranslate"><span class="pre">stdin</span></code>.</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the <code class="docutils literal notranslate"><span class="pre">-i</span></code>  option.</p>
</div>
</div>
<div class="section" id="public-functions">
<h2>32.11.2. Public functions<a class="headerlink" href="#public-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="compileall.compile_dir">
<code class="descclassname">compileall.</code><code class="descname">compile_dir</code><span class="sig-paren">(</span><em>dir</em><span class="optional">[</span>, <em>maxlevels</em><span class="optional">[</span>, <em>ddir</em><span class="optional">[</span>, <em>force</em><span class="optional">[</span>, <em>rx</em><span class="optional">[</span>, <em>quiet</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compileall.compile_dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively descend the directory tree named by <em>dir</em>, compiling all <code class="file docutils literal notranslate"><span class="pre">.py</span></code>
files along the way.</p>
<p>The <em>maxlevels</em> parameter is used to limit the depth of the recursion; it
defaults to <code class="docutils literal notranslate"><span class="pre">10</span></code>.</p>
<p>If <em>ddir</em> is given, it is prepended to the path to each file being compiled
for use in compilation time tracebacks, and is also compiled in to the
byte-code file, where it will be used in tracebacks and other messages in
cases where the source file does not exist at the time the byte-code file is
executed.</p>
<p>If <em>force</em> is true, modules are re-compiled even if the timestamps are up to
date.</p>
<p>If <em>rx</em> is given, its search method is called on the complete path to each
file considered for compilation, and if it returns a true value, the file
is skipped.</p>
<p>If <em>quiet</em> is true, nothing is printed to the standard output unless errors
occur.</p>
</dd></dl>

<dl class="function">
<dt id="compileall.compile_file">
<code class="descclassname">compileall.</code><code class="descname">compile_file</code><span class="sig-paren">(</span><em>fullname</em><span class="optional">[</span>, <em>ddir</em><span class="optional">[</span>, <em>force</em><span class="optional">[</span>, <em>rx</em><span class="optional">[</span>, <em>quiet</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compileall.compile_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile the file with path <em>fullname</em>.</p>
<p>If <em>ddir</em> is given, it is prepended to the path to the file being compiled
for use in compilation time tracebacks, and is also compiled in to the
byte-code file, where it will be used in tracebacks and other messages in
cases where the source file does not exist at the time the byte-code file is
executed.</p>
<p>If <em>rx</em> is given, its search method is passed the full path name to the
file being compiled, and if it returns a true value, the file is not
compiled and <code class="docutils literal notranslate"><span class="pre">True</span></code> is returned.</p>
<p>If <em>quiet</em> is true, nothing is printed to the standard output unless errors
occur.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="compileall.compile_path">
<code class="descclassname">compileall.</code><code class="descname">compile_path</code><span class="sig-paren">(</span><span class="optional">[</span><em>skip_curdir</em><span class="optional">[</span>, <em>maxlevels</em><span class="optional">[</span>, <em>force</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compileall.compile_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Byte-compile all the <code class="file docutils literal notranslate"><span class="pre">.py</span></code> files found along <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>. If
<em>skip_curdir</em> is true (the default), the current directory is not included
in the search.  All other parameters are passed to the <a class="reference internal" href="#compileall.compile_dir" title="compileall.compile_dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile_dir()</span></code></a>
function.  Note that unlike the other compile functions, <code class="docutils literal notranslate"><span class="pre">maxlevels</span></code>
defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<p>To force a recompile of all the <code class="file docutils literal notranslate"><span class="pre">.py</span></code> files in the <code class="file docutils literal notranslate"><span class="pre">Lib/</span></code>
subdirectory and all its subdirectories:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">compileall</span>

<span class="n">compileall</span><span class="o">.</span><span class="n">compile_dir</span><span class="p">(</span><span class="s1">&#39;Lib/&#39;</span><span class="p">,</span> <span class="n">force</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

<span class="c1"># Perform same compilation, excluding files in .svn directories.</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="n">compileall</span><span class="o">.</span><span class="n">compile_dir</span><span class="p">(</span><span class="s1">&#39;Lib/&#39;</span><span class="p">,</span> <span class="n">rx</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;[/</span><span class="se">\\</span><span class="s1">][.]svn&#39;</span><span class="p">),</span> <span class="n">force</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="py_compile.html#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a></dt>
<dd>Byte-compile a single source file.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a><ul>
<li><a class="reference internal" href="#command-line-use">32.11.1. Command-line use</a></li>
<li><a class="reference internal" href="#public-functions">32.11.2. Public functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="py_compile.html"
                        title="previous chapter">32.10. <code class="docutils literal notranslate"><span class="pre">py_compile</span></code> — Compile Python source files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dis.html"
                        title="next chapter">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/compileall.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dis.html" title="32.12. dis — Disassembler for Python bytecode"
             >next</a> |</li>
        <li class="right" >
          <a href="py_compile.html" title="32.10. py_compile — Compile Python source files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�0�yy(y(html/library/compiler.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>33. Python compiler package &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="34. Miscellaneous Services" href="misc.html" />
    <link rel="prev" title="32.13. pickletools — Tools for pickle developers" href="pickletools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/compiler.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="misc.html" title="34. Miscellaneous Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pickletools.html" title="32.13. pickletools — Tools for pickle developers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-compiler-package">
<span id="compiler"></span><h1>33. Python compiler package<a class="headerlink" href="#python-compiler-package" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a> package has been removed in Python 3.</p>
</div>
<p>The Python compiler package is a tool for analyzing Python source code and
generating Python bytecode.  The compiler contains libraries to generate an
abstract syntax tree from Python source code and to generate Python
<a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> from the tree.</p>
<p>The <a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a> package is a Python source to bytecode translator written in
Python.  It uses the built-in parser and standard <a class="reference internal" href="parser.html#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module to
generate a concrete syntax tree.  This tree is used to generate an abstract
syntax tree (AST) and then Python bytecode.</p>
<p>The full functionality of the package duplicates the built-in compiler provided
with the Python interpreter.  It is intended to match its behavior almost
exactly.  Why implement another compiler that does the same thing?  The package
is useful for a variety of purposes.  It can be modified more easily than the
built-in compiler.  The AST it generates is useful for analyzing Python source
code.</p>
<p>This chapter explains how the various components of the <a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a> package
work.  It blends reference material with a tutorial.</p>
<div class="section" id="module-compiler">
<span id="the-basic-interface"></span><h2>33.1. The basic interface<a class="headerlink" href="#module-compiler" title="Permalink to this headline">¶</a></h2>
<p>The top-level of the package defines four functions.  If you import
<a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a>, you will get these functions and a collection of modules
contained in the package.</p>
<dl class="function">
<dt id="compiler.parse">
<code class="descclassname">compiler.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>buf</em><span class="sig-paren">)</span><a class="headerlink" href="#compiler.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an abstract syntax tree for the Python source code in <em>buf</em>. The
function raises <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if there is an error in the source code.  The
return value is a <code class="xref py py-class docutils literal notranslate"><span class="pre">compiler.ast.Module</span></code> instance that contains the tree.</p>
</dd></dl>

<dl class="function">
<dt id="compiler.parseFile">
<code class="descclassname">compiler.</code><code class="descname">parseFile</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#compiler.parseFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an abstract syntax tree for the Python source code in the file specified
by <em>path</em>.  It is equivalent to <code class="docutils literal notranslate"><span class="pre">parse(open(path).read())</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="compiler.walk">
<code class="descclassname">compiler.</code><code class="descname">walk</code><span class="sig-paren">(</span><em>ast</em>, <em>visitor</em><span class="optional">[</span>, <em>verbose</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.walk" title="Permalink to this definition">¶</a></dt>
<dd><p>Do a pre-order walk over the abstract syntax tree <em>ast</em>.  Call the appropriate
method on the <em>visitor</em> instance for each node encountered.</p>
</dd></dl>

<dl class="function">
<dt id="compiler.compile">
<code class="descclassname">compiler.</code><code class="descname">compile</code><span class="sig-paren">(</span><em>source</em>, <em>filename</em>, <em>mode</em>, <em>flags=None</em>, <em>dont_inherit=None</em><span class="sig-paren">)</span><a class="headerlink" href="#compiler.compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile the string <em>source</em>, a Python module, statement or expression, into a
code object that can be executed by the exec statement or <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>. This
function is a replacement for the built-in <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> function.</p>
<p>The <em>filename</em> will be used for run-time error messages.</p>
<p>The <em>mode</em> must be ‘exec’ to compile a module, ‘single’ to compile a single
(interactive) statement, or ‘eval’ to compile an expression.</p>
<p>The <em>flags</em> and <em>dont_inherit</em> arguments affect future-related statements, but
are not supported yet.</p>
</dd></dl>

<dl class="function">
<dt id="compiler.compileFile">
<code class="descclassname">compiler.</code><code class="descname">compileFile</code><span class="sig-paren">(</span><em>source</em><span class="sig-paren">)</span><a class="headerlink" href="#compiler.compileFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compiles the file <em>source</em> and generates a .pyc file.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a> package contains the following modules: <a class="reference internal" href="ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">consts</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">future</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">misc</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyassem</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">pycodegen</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">symbols</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">transformer</span></code>, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">visitor</span></code>.</p>
</div>
<div class="section" id="limitations">
<h2>33.2. Limitations<a class="headerlink" href="#limitations" title="Permalink to this headline">¶</a></h2>
<p>There are some problems with the error checking of the compiler package.  The
interpreter detects syntax errors in two distinct phases.  One set of errors is
detected by the interpreter’s parser, the other set by the compiler.  The
compiler package relies on the interpreter’s parser, so it get the first phases
of error checking for free.  It implements the second phase itself, and that
implementation is incomplete.  For example, the compiler package does not raise
an error if a name appears more than once in an argument list:  <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">f(x,</span> <span class="pre">x):</span>
<span class="pre">...</span></code></p>
<p>A future version of the compiler should fix these problems.</p>
</div>
<div class="section" id="python-abstract-syntax">
<h2>33.3. Python Abstract Syntax<a class="headerlink" href="#python-abstract-syntax" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-compiler.ast" title="compiler.ast"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler.ast</span></code></a> module defines an abstract syntax for Python.  In the
abstract syntax tree, each node represents a syntactic construct.  The root of
the tree is <code class="xref py py-class docutils literal notranslate"><span class="pre">Module</span></code> object.</p>
<p>The abstract syntax offers a higher level interface to parsed Python source
code.  The <a class="reference internal" href="parser.html#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module and the compiler written in C for the Python
interpreter use a concrete syntax tree.  The concrete syntax is tied closely to
the grammar description used for the Python parser.  Instead of a single node
for a construct, there are often several levels of nested nodes that are
introduced by Python’s precedence rules.</p>
<p>The abstract syntax tree is created by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler.transformer</span></code> module.
The transformer relies on the built-in Python parser to generate a concrete
syntax tree.  It generates an abstract syntax tree from the concrete tree.</p>
<p id="index-0">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">transformer</span></code> module was created by Greg Stein and Bill Tutt for an
experimental Python-to-C compiler.  The current version contains a number of
modifications and improvements, but the basic form of the abstract syntax and of
the transformer are due to Stein and Tutt.</p>
<div class="section" id="module-compiler.ast">
<span id="ast-nodes"></span><h3>33.3.1. AST Nodes<a class="headerlink" href="#module-compiler.ast" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#module-compiler.ast" title="compiler.ast"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler.ast</span></code></a> module is generated from a text file that describes each
node type and its elements.  Each node type is represented as a class that
inherits from the abstract base class <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">compiler.ast.Node</span></code></a> and defines a
set of named attributes for child nodes.</p>
<dl class="class">
<dt id="compiler.ast.Node">
<em class="property">class </em><code class="descclassname">compiler.ast.</code><code class="descname">Node</code><a class="headerlink" href="#compiler.ast.Node" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> instances are created automatically by the parser generator.
The recommended interface for specific <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> instances is to use the
public attributes to access child nodes.  A public attribute may be bound to a
single node or to a sequence of nodes, depending on the <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> type.  For
example, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">bases</span></code> attribute of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code> node, is bound to a
list of base class nodes, and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">doc</span></code> attribute is bound to a single
node.</p>
<p>Each <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> instance has a <code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code> attribute which may be
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  XXX Not sure what the rules are for which nodes will have a useful
lineno.</p>
<p>All <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> objects offer the following methods:</p>
<dl class="method">
<dt id="compiler.ast.Node.getChildren">
<code class="descname">getChildren</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.ast.Node.getChildren" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a flattened list of the child nodes and objects in the order they
occur.  Specifically, the order of the nodes is the order in which they
appear in the Python grammar.  Not all of the children are <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a>
instances.  The names of functions and classes, for example, are plain
strings.</p>
</dd></dl>

<dl class="method">
<dt id="compiler.ast.Node.getChildNodes">
<code class="descname">getChildNodes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.ast.Node.getChildNodes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a flattened list of the child nodes in the order they occur.  This
method is like <a class="reference internal" href="#compiler.ast.Node.getChildren" title="compiler.ast.Node.getChildren"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getChildren()</span></code></a>, except that it only returns those
children that are <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> instances.</p>
</dd></dl>

</dd></dl>

<p>Two examples illustrate the general structure of <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> classes.  The
<a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement is defined by the following grammar production:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">while_stmt</span><span class="p">:</span>     <span class="s2">&quot;while&quot;</span> <span class="n">expression</span> <span class="s2">&quot;:&quot;</span> <span class="n">suite</span>
               <span class="p">[</span><span class="s2">&quot;else&quot;</span> <span class="s2">&quot;:&quot;</span> <span class="n">suite</span><span class="p">]</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">While</span></code> node has three attributes: <a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-attr docutils literal notranslate"><span class="pre">test</span></code></a>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code>, and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code>.  (If the natural name for an attribute is also a Python reserved
word, it can’t be used as an attribute name.  An underscore is appended to the
word to make it a legal identifier, hence <code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code> instead of
<a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>.)</p>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is more complicated because it can include several
tests.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">if_stmt</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">(</span><span class="s1">&#39;elif&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">If</span></code> node only defines two attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">tests</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code>.  The <code class="xref py py-attr docutils literal notranslate"><span class="pre">tests</span></code> attribute is a sequence of test expression,
consequent body pairs.  There is one pair for each <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a>
clause.  The first element of the pair is the test expression.  The second
elements is a <code class="xref py py-class docutils literal notranslate"><span class="pre">Stmt</span></code> node that contains the code to execute if the test
is true.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">getChildren()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">If</span></code> returns a flat list of child
nodes.  If there are three <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> clauses and no
<a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">getChildren()</span></code> will return a list of six
elements: the first test expression, the first <code class="xref py py-class docutils literal notranslate"><span class="pre">Stmt</span></code>, the second text
expression, etc.</p>
<p>The following table lists each of the <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> subclasses defined in
<a class="reference internal" href="#module-compiler.ast" title="compiler.ast"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler.ast</span></code></a> and each of the public attributes available on their
instances.  The values of most of the attributes are themselves <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a>
instances or sequences of instances.  When the value is something other than an
instance, the type is noted in the comment.  The attributes are listed in the
order in which they are returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">getChildren()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getChildNodes()</span></code>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="26%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Node type</th>
<th class="head">Attribute</th>
<th class="head">Value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Add</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>left operand</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>right operand</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">And</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>list of operands</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">AssAttr</span></code></td>
<td>&#160;</td>
<td><em>attribute as target of
assignment</em></td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>expression on the left-hand
side of the dot</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">attrname</span></code></td>
<td>the attribute name, a string</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>XXX</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">AssList</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>list of list elements being
assigned to</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">AssName</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>name being assigned to</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>XXX</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">AssTuple</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>list of tuple elements being
assigned to</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Assert</span></code></td>
<td><a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-attr docutils literal notranslate"><span class="pre">test</span></code></a></td>
<td>the expression to be tested</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">fail</span></code></td>
<td>the value of the
<a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Assign</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>a list of assignment targets,
one per equal sign</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>the value being assigned</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">AugAssign</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">node</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">op</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Backquote</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Bitand</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Bitor</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Bitxor</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Break</span></code></td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">CallFunc</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">node</span></code></td>
<td>expression for the callee</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code></td>
<td>a list of arguments</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">star_args</span></code></td>
<td>the extended *-arg value</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">dstar_args</span></code></td>
<td>the extended **-arg value</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>the name of the class, a string</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">bases</span></code></td>
<td>a list of base classes</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">doc</span></code></td>
<td>doc string, a string or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a></td>
<td>the body of the class statement</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Compare</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ops</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Const</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Continue</span></code></td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Decorators</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>List of function decorator
expressions</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Dict</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">items</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Discard</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Div</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-class docutils literal notranslate"><span class="pre">Ellipsis</span></code></a></td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Expression</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">node</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Exec</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><a class="reference internal" href="functions.html#locals" title="locals"><code class="xref py py-attr docutils literal notranslate"><span class="pre">locals</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><a class="reference internal" href="functions.html#globals" title="globals"><code class="xref py py-attr docutils literal notranslate"><span class="pre">globals</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">FloorDiv</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">For</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">assign</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">list</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">From</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">modname</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">names</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">decorators</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Decorators</span></code> or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>name used in def, a string</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">argnames</span></code></td>
<td>list of argument names, as
strings</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">defaults</span></code></td>
<td>list of default values</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>xxx</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">doc</span></code></td>
<td>doc string, a string or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a></td>
<td>the body of the function</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenExpr</span></code></td>
<td><a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenExprFor</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">assign</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><a class="reference internal" href="functions.html#iter" title="iter"><code class="xref py py-attr docutils literal notranslate"><span class="pre">iter</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ifs</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenExprIf</span></code></td>
<td><a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-attr docutils literal notranslate"><span class="pre">test</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenExprInner</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">quals</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Getattr</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">attrname</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Global</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">names</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">If</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tests</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Import</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">names</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Invert</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Keyword</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Lambda</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">argnames</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">defaults</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">LeftShift</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">List</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">ListComp</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">quals</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">ListCompFor</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">assign</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">list</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ifs</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">ListCompIf</span></code></td>
<td><a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-attr docutils literal notranslate"><span class="pre">test</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Mod</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Module</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">doc</span></code></td>
<td>doc string, a string or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">node</span></code></td>
<td>body of the module, a
<code class="xref py py-class docutils literal notranslate"><span class="pre">Stmt</span></code></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Mul</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Name</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Not</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Or</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Pass</span></code></td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Power</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Print</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Printnl</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Raise</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr1</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr2</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr3</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Return</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">RightShift</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Slice</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">lower</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">upper</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Sliceobj</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>list of statements</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Stmt</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Sub</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">left</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">right</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Subscript</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">subs</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">TryExcept</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">handlers</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">TryFinally</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">final</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Tuple</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">UnaryAdd</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">UnarySub</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">While</span></code></td>
<td><a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-attr docutils literal notranslate"><span class="pre">test</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">else_</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">With</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><a class="reference internal" href="functions.html#vars" title="vars"><code class="xref py py-attr docutils literal notranslate"><span class="pre">vars</span></code></a></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">body</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Yield</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="assignment-nodes">
<h3>33.3.2. Assignment nodes<a class="headerlink" href="#assignment-nodes" title="Permalink to this headline">¶</a></h3>
<p>There is a collection of nodes used to represent assignments.  Each assignment
statement in the source code becomes a single <code class="xref py py-class docutils literal notranslate"><span class="pre">Assign</span></code> node in the AST.
The <code class="xref py py-attr docutils literal notranslate"><span class="pre">nodes</span></code> attribute is a list that contains a node for each assignment
target.  This is necessary because assignment can be chained, e.g. <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">b</span> <span class="pre">=</span>
<span class="pre">2</span></code>. Each <a class="reference internal" href="#compiler.ast.Node" title="compiler.ast.Node"><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></a> in the list will be one of the following classes:
<code class="xref py py-class docutils literal notranslate"><span class="pre">AssAttr</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">AssList</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">AssName</span></code>, or <code class="xref py py-class docutils literal notranslate"><span class="pre">AssTuple</span></code>.</p>
<p>Each target assignment node will describe the kind of object being assigned to:
<code class="xref py py-class docutils literal notranslate"><span class="pre">AssName</span></code> for a simple name, e.g. <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1</span></code>. <code class="xref py py-class docutils literal notranslate"><span class="pre">AssAttr</span></code> for an
attribute assigned, e.g. <code class="docutils literal notranslate"><span class="pre">a.x</span> <span class="pre">=</span> <span class="pre">1</span></code>. <code class="xref py py-class docutils literal notranslate"><span class="pre">AssList</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">AssTuple</span></code> for
list and tuple expansion respectively, e.g. <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span> <span class="pre">=</span> <span class="pre">a_tuple</span></code>.</p>
<p>The target assignment nodes also have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">flags</span></code> attribute that indicates
whether the node is being used for assignment or in a delete statement.  The
<code class="xref py py-class docutils literal notranslate"><span class="pre">AssName</span></code> is also used to represent a delete statement, e.g. <code class="xref py py-class docutils literal notranslate"><span class="pre">del</span>
<span class="pre">x</span></code>.</p>
<p>When an expression contains several attribute references, an assignment or
delete statement will contain only one <code class="xref py py-class docutils literal notranslate"><span class="pre">AssAttr</span></code> node – for the final
attribute reference.  The other attribute references will be represented as
<code class="xref py py-class docutils literal notranslate"><span class="pre">Getattr</span></code> nodes in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">expr</span></code> attribute of the <code class="xref py py-class docutils literal notranslate"><span class="pre">AssAttr</span></code>
instance.</p>
</div>
<div class="section" id="examples">
<h3>33.3.3. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<p>This section shows several simple examples of ASTs for Python source code.  The
examples demonstrate how to use the <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code> function, what the repr of an
AST looks like, and how to access attributes of an AST node.</p>
<p>The first module defines a single function.  Assume it is stored in
<code class="file docutils literal notranslate"><span class="pre">doublelib.py</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;This is an example module.</span>

<span class="sd">This is the docstring.</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="k">def</span> <span class="nf">double</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="s2">&quot;Return twice the argument&quot;</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="mi">2</span>
</pre></div>
</div>
<p>In the interactive interpreter session below, I have reformatted the long AST
reprs for readability.  The AST reprs use unqualified class names.  If you want
to create an instance from a repr, you must import the class names from the
<a class="reference internal" href="#module-compiler.ast" title="compiler.ast"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler.ast</span></code></a> module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">compiler</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span> <span class="o">=</span> <span class="n">compiler</span><span class="o">.</span><span class="n">parseFile</span><span class="p">(</span><span class="s2">&quot;doublelib.py&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span>
<span class="go">Module(&#39;This is an example module.\n\nThis is the docstring.\n&#39;,</span>
<span class="go">       Stmt([Function(None, &#39;double&#39;, [&#39;x&#39;], [], 0,</span>
<span class="go">                      &#39;Return twice the argument&#39;,</span>
<span class="go">                      Stmt([Return(Mul((Name(&#39;x&#39;), Const(2))))]))]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">compiler.ast</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Module</span><span class="p">(</span><span class="s1">&#39;This is an example module.</span><span class="se">\n\n</span><span class="s1">This is the docstring.</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
<span class="gp">... </span>   <span class="n">Stmt</span><span class="p">([</span><span class="n">Function</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;double&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;x&#39;</span><span class="p">],</span> <span class="p">[],</span> <span class="mi">0</span><span class="p">,</span>
<span class="gp">... </span>                  <span class="s1">&#39;Return twice the argument&#39;</span><span class="p">,</span>
<span class="gp">... </span>                  <span class="n">Stmt</span><span class="p">([</span><span class="n">Return</span><span class="p">(</span><span class="n">Mul</span><span class="p">((</span><span class="n">Name</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">),</span> <span class="n">Const</span><span class="p">(</span><span class="mi">2</span><span class="p">))))]))]))</span>
<span class="go">Module(&#39;This is an example module.\n\nThis is the docstring.\n&#39;,</span>
<span class="go">       Stmt([Function(None, &#39;double&#39;, [&#39;x&#39;], [], 0,</span>
<span class="go">                      &#39;Return twice the argument&#39;,</span>
<span class="go">                      Stmt([Return(Mul((Name(&#39;x&#39;), Const(2))))]))]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mod</span><span class="o">.</span><span class="n">doc</span>
<span class="go">&#39;This is an example module.\n\nThis is the docstring.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="n">mod</span><span class="o">.</span><span class="n">node</span><span class="o">.</span><span class="n">nodes</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">node</span>
<span class="gp">...</span>
<span class="go">Function(None, &#39;double&#39;, [&#39;x&#39;], [], 0, &#39;Return twice the argument&#39;,</span>
<span class="go">         Stmt([Return(Mul((Name(&#39;x&#39;), Const(2))))]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">func</span> <span class="o">=</span> <span class="n">mod</span><span class="o">.</span><span class="n">node</span><span class="o">.</span><span class="n">nodes</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">func</span><span class="o">.</span><span class="n">code</span>
<span class="go">Stmt([Return(Mul((Name(&#39;x&#39;), Const(2))))])</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="module-compiler.visitor">
<span id="using-visitors-to-walk-asts"></span><h2>33.4. Using Visitors to Walk ASTs<a class="headerlink" href="#module-compiler.visitor" title="Permalink to this headline">¶</a></h2>
<p>The visitor pattern is …  The <a class="reference internal" href="#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a> package uses a variant on the
visitor pattern that takes advantage of Python’s introspection features to
eliminate the need for much of the visitor’s infrastructure.</p>
<p>The classes being visited do not need to be programmed to accept visitors.  The
visitor need only define visit methods for classes it is specifically interested
in; a default visit method can handle the rest.</p>
<p>XXX The magic <code class="xref py py-meth docutils literal notranslate"><span class="pre">visit()</span></code> method for visitors.</p>
<dl class="function">
<dt id="compiler.visitor.walk">
<code class="descclassname">compiler.visitor.</code><code class="descname">walk</code><span class="sig-paren">(</span><em>tree</em>, <em>visitor</em><span class="optional">[</span>, <em>verbose</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.visitor.walk" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="class">
<dt id="compiler.visitor.ASTVisitor">
<em class="property">class </em><code class="descclassname">compiler.visitor.</code><code class="descname">ASTVisitor</code><a class="headerlink" href="#compiler.visitor.ASTVisitor" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#compiler.visitor.ASTVisitor" title="compiler.visitor.ASTVisitor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ASTVisitor</span></code></a> is responsible for walking over the tree in the correct
order.  A walk begins with a call to <a class="reference internal" href="#compiler.visitor.ASTVisitor.preorder" title="compiler.visitor.ASTVisitor.preorder"><code class="xref py py-meth docutils literal notranslate"><span class="pre">preorder()</span></code></a>.  For each node, it checks
the <em>visitor</em> argument to <a class="reference internal" href="#compiler.visitor.ASTVisitor.preorder" title="compiler.visitor.ASTVisitor.preorder"><code class="xref py py-meth docutils literal notranslate"><span class="pre">preorder()</span></code></a> for a method named ‘visitNodeType,’
where NodeType is the name of the node’s class, e.g. for a <code class="xref py py-class docutils literal notranslate"><span class="pre">While</span></code> node a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">visitWhile()</span></code> would be called.  If the method exists, it is called with the
node as its first argument.</p>
<p>The visitor method for a particular node type can control how child nodes are
visited during the walk.  The <a class="reference internal" href="#compiler.visitor.ASTVisitor" title="compiler.visitor.ASTVisitor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ASTVisitor</span></code></a> modifies the visitor argument
by adding a visit method to the visitor; this method can be used to visit a
particular child node.  If no visitor is found for a particular node type, the
<a class="reference internal" href="#compiler.visitor.ASTVisitor.default" title="compiler.visitor.ASTVisitor.default"><code class="xref py py-meth docutils literal notranslate"><span class="pre">default()</span></code></a> method is called.</p>
<p><a class="reference internal" href="#compiler.visitor.ASTVisitor" title="compiler.visitor.ASTVisitor"><code class="xref py py-class docutils literal notranslate"><span class="pre">ASTVisitor</span></code></a> objects have the following methods:</p>
<p>XXX describe extra arguments</p>
<dl class="method">
<dt id="compiler.visitor.ASTVisitor.default">
<code class="descname">default</code><span class="sig-paren">(</span><em>node</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.visitor.ASTVisitor.default" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="compiler.visitor.ASTVisitor.dispatch">
<code class="descname">dispatch</code><span class="sig-paren">(</span><em>node</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compiler.visitor.ASTVisitor.dispatch" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="compiler.visitor.ASTVisitor.preorder">
<code class="descname">preorder</code><span class="sig-paren">(</span><em>tree</em>, <em>visitor</em><span class="sig-paren">)</span><a class="headerlink" href="#compiler.visitor.ASTVisitor.preorder" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

</dd></dl>

</div>
<div class="section" id="bytecode-generation">
<h2>33.5. Bytecode Generation<a class="headerlink" href="#bytecode-generation" title="Permalink to this headline">¶</a></h2>
<p>The code generator is a visitor that emits bytecodes.  Each visit method can
call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code> method to emit a new bytecode.  The basic code generator
is specialized for modules, classes, and functions.  An assembler converts that
emitted instructions to the low-level bytecode format.  It handles things like
generation of constant lists of code objects and calculation of jump offsets.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">33. Python compiler package</a><ul>
<li><a class="reference internal" href="#module-compiler">33.1. The basic interface</a></li>
<li><a class="reference internal" href="#limitations">33.2. Limitations</a></li>
<li><a class="reference internal" href="#python-abstract-syntax">33.3. Python Abstract Syntax</a><ul>
<li><a class="reference internal" href="#module-compiler.ast">33.3.1. AST Nodes</a></li>
<li><a class="reference internal" href="#assignment-nodes">33.3.2. Assignment nodes</a></li>
<li><a class="reference internal" href="#examples">33.3.3. Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-compiler.visitor">33.4. Using Visitors to Walk ASTs</a></li>
<li><a class="reference internal" href="#bytecode-generation">33.5. Bytecode Generation</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pickletools.html"
                        title="previous chapter">32.13. <code class="docutils literal notranslate"><span class="pre">pickletools</span></code> — Tools for pickle developers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="misc.html"
                        title="next chapter">34. Miscellaneous Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/compiler.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="misc.html" title="34. Miscellaneous Services"
             >next</a> |</li>
        <li class="right" >
          <a href="pickletools.html" title="32.13. pickletools — Tools for pickle developers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��r��html/library/configparser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.2. ConfigParser — Configuration file parser &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.3. robotparser — Parser for robots.txt" href="robotparser.html" />
    <link rel="prev" title="13.1. csv — CSV File Reading and Writing" href="csv.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/configparser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="robotparser.html" title="13.3. robotparser — Parser for robots.txt"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="csv.html" title="13.1. csv — CSV File Reading and Writing"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ConfigParser">
<span id="configparser-configuration-file-parser"></span><h1>13.2. <a class="reference internal" href="#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> — Configuration file parser<a class="headerlink" href="#module-ConfigParser" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<p id="index-0">This module defines the class <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>.   The <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>
class implements a basic configuration file parser language which provides a
structure similar to what you would find on Microsoft Windows INI files.  You
can use this to write Python programs which can be customized by end users
easily.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This library does <em>not</em> interpret or write the value-type prefixes used in
the Windows Registry extended version of INI syntax.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="shlex.html#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a></dt>
<dd>Support for creating Unix shell-like mini-languages which can be used as
an alternate format for application configuration files.</dd>
<dt>Module <a class="reference internal" href="json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></dt>
<dd>The json module implements a subset of JavaScript syntax which can also
be used for this purpose.</dd>
</dl>
</div>
<p>The configuration file consists of sections, led by a <code class="docutils literal notranslate"><span class="pre">[section]</span></code> header and
followed by <code class="docutils literal notranslate"><span class="pre">name:</span> <span class="pre">value</span></code> entries, with continuations in the style of
<span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> (see section 3.1.1, “LONG HEADER FIELDS”); <code class="docutils literal notranslate"><span class="pre">name=value</span></code> is also
accepted.  Note that leading whitespace is removed from values. The optional
values can contain format strings which refer to other values in the same
section, or values in a special <code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> section.  Additional defaults can be
provided on initialization and retrieval.  Lines beginning with <code class="docutils literal notranslate"><span class="pre">'#'</span></code> or
<code class="docutils literal notranslate"><span class="pre">';'</span></code> are ignored and may be used to provide comments.</p>
<p>Configuration files may include comments, prefixed by specific characters (<code class="docutils literal notranslate"><span class="pre">#</span></code>
and <code class="docutils literal notranslate"><span class="pre">;</span></code>).  Comments may appear on their own in an otherwise empty line, or may
be entered in lines holding values or section names.  In the latter case, they
need to be preceded by a whitespace character to be recognized as a comment.
(For backwards compatibility, only <code class="docutils literal notranslate"><span class="pre">;</span></code> starts an inline comment, while <code class="docutils literal notranslate"><span class="pre">#</span></code>
does not.)</p>
<p>On top of the core functionality, <a class="reference internal" href="#ConfigParser.SafeConfigParser" title="ConfigParser.SafeConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SafeConfigParser</span></code></a> supports
interpolation.  This means values can contain format strings which refer to
other values in the same section, or values in a special <code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> section.
Additional defaults can be provided on initialization.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">My</span> <span class="n">Section</span><span class="p">]</span>
<span class="n">foodir</span><span class="p">:</span> <span class="o">%</span><span class="p">(</span><span class="nb">dir</span><span class="p">)</span><span class="n">s</span><span class="o">/</span><span class="n">whatever</span>
<span class="nb">dir</span><span class="o">=</span><span class="n">frob</span>
<span class="n">long</span><span class="p">:</span> <span class="n">this</span> <span class="n">value</span> <span class="n">continues</span>
   <span class="ow">in</span> <span class="n">the</span> <span class="nb">next</span> <span class="n">line</span>
</pre></div>
</div>
<p>would resolve the <code class="docutils literal notranslate"><span class="pre">%(dir)s</span></code> to the value of <code class="docutils literal notranslate"><span class="pre">dir</span></code> (<code class="docutils literal notranslate"><span class="pre">frob</span></code> in this case).
All reference expansions are done on demand.</p>
<p>Default values can be specified by passing them into the <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>
constructor as a dictionary.  Additional defaults  may be passed into the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> method which will override all others.</p>
<p>Sections are normally stored in a built-in dictionary. An alternative dictionary
type can be passed to the <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> constructor. For example, if a
dictionary type is passed that sorts its keys, the sections will be sorted on
write-back, as will be the keys within each section.</p>
<dl class="class">
<dt id="ConfigParser.RawConfigParser">
<em class="property">class </em><code class="descclassname">ConfigParser.</code><code class="descname">RawConfigParser</code><span class="sig-paren">(</span><span class="optional">[</span><em>defaults</em><span class="optional">[</span>, <em>dict_type</em><span class="optional">[</span>, <em>allow_no_value</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser" title="Permalink to this definition">¶</a></dt>
<dd><p>The basic configuration object.  When <em>defaults</em> is given, it is initialized
into the dictionary of intrinsic defaults.  When <em>dict_type</em> is given, it will
be used to create the dictionary objects for the list of sections, for the
options within a section, and for the default values.  When <em>allow_no_value</em>
is true (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>), options without values are accepted; the value
presented for these is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>This class does not
support the magical interpolation behavior.</p>
<p>All option names are passed through the <a class="reference internal" href="#ConfigParser.RawConfigParser.optionxform" title="ConfigParser.RawConfigParser.optionxform"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code></a> method.  Its
default implementation converts option names to lower case.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>dict_type</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The default <em>dict_type</em> is <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a>.
<em>allow_no_value</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="ConfigParser.ConfigParser">
<em class="property">class </em><code class="descclassname">ConfigParser.</code><code class="descname">ConfigParser</code><span class="sig-paren">(</span><span class="optional">[</span><em>defaults</em><span class="optional">[</span>, <em>dict_type</em><span class="optional">[</span>, <em>allow_no_value</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.ConfigParser" title="Permalink to this definition">¶</a></dt>
<dd><p>Derived class of <a class="reference internal" href="#ConfigParser.RawConfigParser" title="ConfigParser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> that implements the magical
interpolation feature and adds optional arguments to the <a class="reference internal" href="#ConfigParser.ConfigParser.get" title="ConfigParser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> and
<a class="reference internal" href="#ConfigParser.ConfigParser.items" title="ConfigParser.ConfigParser.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a> methods.  The values in <em>defaults</em> must be appropriate for the
<code class="docutils literal notranslate"><span class="pre">%()s</span></code> string interpolation.  Note that <em>__name__</em> is an intrinsic default;
its value is the section name, and will override any value provided in
<em>defaults</em>.</p>
<p>All option names used in interpolation will be passed through the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code> method just like any other option name reference.  Using
the default implementation of <code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code>, the values <code class="docutils literal notranslate"><span class="pre">foo</span> <span class="pre">%(bar)s</span></code>
and <code class="docutils literal notranslate"><span class="pre">foo</span> <span class="pre">%(BAR)s</span></code> are equivalent.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>dict_type</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The default <em>dict_type</em> is <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a>.
<em>allow_no_value</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="ConfigParser.SafeConfigParser">
<em class="property">class </em><code class="descclassname">ConfigParser.</code><code class="descname">SafeConfigParser</code><span class="sig-paren">(</span><span class="optional">[</span><em>defaults</em><span class="optional">[</span>, <em>dict_type</em><span class="optional">[</span>, <em>allow_no_value</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.SafeConfigParser" title="Permalink to this definition">¶</a></dt>
<dd><p>Derived class of <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> that implements a more-sane variant of
the magical interpolation feature.  This implementation is more predictable as
well. New applications should prefer this version if they don’t need to be
compatible with older versions of Python.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>dict_type</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The default <em>dict_type</em> is <a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a>.
<em>allow_no_value</em> was added.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.Error">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">Error</code><a class="headerlink" href="#ConfigParser.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for all other configparser exceptions.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.NoSectionError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">NoSectionError</code><a class="headerlink" href="#ConfigParser.NoSectionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a specified section is not found.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.DuplicateSectionError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">DuplicateSectionError</code><a class="headerlink" href="#ConfigParser.DuplicateSectionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised if <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_section()</span></code> is called with the name of a section
that is already present.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.NoOptionError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">NoOptionError</code><a class="headerlink" href="#ConfigParser.NoOptionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a specified option is not found in the specified  section.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.InterpolationError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">InterpolationError</code><a class="headerlink" href="#ConfigParser.InterpolationError" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for exceptions raised when problems occur performing string
interpolation.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.InterpolationDepthError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">InterpolationDepthError</code><a class="headerlink" href="#ConfigParser.InterpolationDepthError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when string interpolation cannot be completed because the
number of iterations exceeds <a class="reference internal" href="#ConfigParser.MAX_INTERPOLATION_DEPTH" title="ConfigParser.MAX_INTERPOLATION_DEPTH"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAX_INTERPOLATION_DEPTH</span></code></a>. Subclass of
<a class="reference internal" href="#ConfigParser.InterpolationError" title="ConfigParser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.InterpolationMissingOptionError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">InterpolationMissingOptionError</code><a class="headerlink" href="#ConfigParser.InterpolationMissingOptionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an option referenced from a value does not exist. Subclass
of <a class="reference internal" href="#ConfigParser.InterpolationError" title="ConfigParser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.InterpolationSyntaxError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">InterpolationSyntaxError</code><a class="headerlink" href="#ConfigParser.InterpolationSyntaxError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when the source text into which substitutions are made does not
conform to the required syntax. Subclass of <a class="reference internal" href="#ConfigParser.InterpolationError" title="ConfigParser.InterpolationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InterpolationError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.MissingSectionHeaderError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">MissingSectionHeaderError</code><a class="headerlink" href="#ConfigParser.MissingSectionHeaderError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when attempting to parse a file which has no section headers.</p>
</dd></dl>

<dl class="exception">
<dt id="ConfigParser.ParsingError">
<em class="property">exception </em><code class="descclassname">ConfigParser.</code><code class="descname">ParsingError</code><a class="headerlink" href="#ConfigParser.ParsingError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when errors occur attempting to parse a file.</p>
</dd></dl>

<dl class="data">
<dt id="ConfigParser.MAX_INTERPOLATION_DEPTH">
<code class="descclassname">ConfigParser.</code><code class="descname">MAX_INTERPOLATION_DEPTH</code><a class="headerlink" href="#ConfigParser.MAX_INTERPOLATION_DEPTH" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum depth for recursive interpolation for <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> when the <em>raw</em>
parameter is false.  This is relevant only for the <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> class.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="shlex.html#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a></dt>
<dd>Support for a creating Unix shell-like mini-languages which can be used as an
alternate format for application configuration files.</dd>
</dl>
</div>
<div class="section" id="rawconfigparser-objects">
<span id="id1"></span><h2>13.2.1. RawConfigParser Objects<a class="headerlink" href="#rawconfigparser-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#ConfigParser.RawConfigParser" title="ConfigParser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="ConfigParser.RawConfigParser.defaults">
<code class="descclassname">RawConfigParser.</code><code class="descname">defaults</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.defaults" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary containing the instance-wide defaults.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.sections">
<code class="descclassname">RawConfigParser.</code><code class="descname">sections</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.sections" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the sections available; <code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> is not included in the
list.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.add_section">
<code class="descclassname">RawConfigParser.</code><code class="descname">add_section</code><span class="sig-paren">(</span><em>section</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.add_section" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a section named <em>section</em> to the instance.  If a section by the given name
already exists, <a class="reference internal" href="#ConfigParser.DuplicateSectionError" title="ConfigParser.DuplicateSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DuplicateSectionError</span></code></a> is raised. If the name
<code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> (or any of it’s case-insensitive variants) is passed,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.has_section">
<code class="descclassname">RawConfigParser.</code><code class="descname">has_section</code><span class="sig-paren">(</span><em>section</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.has_section" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates whether the named section is present in the configuration. The
<code class="docutils literal notranslate"><span class="pre">DEFAULT</span></code> section is not acknowledged.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.options">
<code class="descclassname">RawConfigParser.</code><code class="descname">options</code><span class="sig-paren">(</span><em>section</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.options" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of options available in the specified <em>section</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.has_option">
<code class="descclassname">RawConfigParser.</code><code class="descname">has_option</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.has_option" title="Permalink to this definition">¶</a></dt>
<dd><p>If the given section exists, and contains the given option, return
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>; otherwise return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.read">
<code class="descclassname">RawConfigParser.</code><code class="descname">read</code><span class="sig-paren">(</span><em>filenames</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Attempt to read and parse a list of filenames, returning a list of filenames
which were successfully parsed.  If <em>filenames</em> is a string or Unicode string,
it is treated as a single filename. If a file named in <em>filenames</em> cannot be
opened, that file will be ignored.  This is designed so that you can specify a
list of potential configuration file locations (for example, the current
directory, the user’s home directory, and some system-wide directory), and all
existing configuration files in the list will be read.  If none of the named
files exist, the <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> instance will contain an empty dataset.
An application which requires initial values to be loaded from a file should
load the required file or files using <a class="reference internal" href="#ConfigParser.RawConfigParser.readfp" title="ConfigParser.RawConfigParser.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a> before calling <a class="reference internal" href="#ConfigParser.RawConfigParser.read" title="ConfigParser.RawConfigParser.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>
for any optional files:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ConfigParser</span><span class="o">,</span> <span class="nn">os</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="n">config</span><span class="o">.</span><span class="n">readfp</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;defaults.cfg&#39;</span><span class="p">))</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">([</span><span class="s1">&#39;site.cfg&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s1">&#39;~/.myapp.cfg&#39;</span><span class="p">)])</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Returns list of successfully parsed filenames.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.readfp">
<code class="descclassname">RawConfigParser.</code><code class="descname">readfp</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.readfp" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and parse configuration data from the file or file-like object in <em>fp</em>
(only the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method is used).  If <em>filename</em> is omitted and <em>fp</em>
has a <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute, that is used for <em>filename</em>; the default is
<code class="docutils literal notranslate"><span class="pre">&lt;???&gt;</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.get">
<code class="descclassname">RawConfigParser.</code><code class="descname">get</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Get an <em>option</em> value for the named <em>section</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.getint">
<code class="descclassname">RawConfigParser.</code><code class="descname">getint</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.getint" title="Permalink to this definition">¶</a></dt>
<dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to an
integer.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.getfloat">
<code class="descclassname">RawConfigParser.</code><code class="descname">getfloat</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.getfloat" title="Permalink to this definition">¶</a></dt>
<dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to a
floating point number.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.getboolean">
<code class="descclassname">RawConfigParser.</code><code class="descname">getboolean</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.getboolean" title="Permalink to this definition">¶</a></dt>
<dd><p>A convenience method which coerces the <em>option</em> in the specified <em>section</em> to a
Boolean value.  Note that the accepted values for the option are <code class="docutils literal notranslate"><span class="pre">&quot;1&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;yes&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;true&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;on&quot;</span></code>, which cause this method to return <code class="docutils literal notranslate"><span class="pre">True</span></code>,
and <code class="docutils literal notranslate"><span class="pre">&quot;0&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;no&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;false&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;off&quot;</span></code>, which cause it to return
<code class="docutils literal notranslate"><span class="pre">False</span></code>.  These string values are checked in a case-insensitive manner.  Any
other value will cause it to raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.items">
<code class="descclassname">RawConfigParser.</code><code class="descname">items</code><span class="sig-paren">(</span><em>section</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> pairs for each option in the given <em>section</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.set">
<code class="descclassname">RawConfigParser.</code><code class="descname">set</code><span class="sig-paren">(</span><em>section</em>, <em>option</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.set" title="Permalink to this definition">¶</a></dt>
<dd><p>If the given section exists, set the given option to the specified value;
otherwise raise <a class="reference internal" href="#ConfigParser.NoSectionError" title="ConfigParser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>.  While it is possible to use
<a class="reference internal" href="#ConfigParser.RawConfigParser" title="ConfigParser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> (or <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> with <em>raw</em> parameters set to
true) for <em>internal</em> storage of non-string values, full functionality (including
interpolation and output to files) can only be achieved using string values.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.write">
<code class="descclassname">RawConfigParser.</code><code class="descname">write</code><span class="sig-paren">(</span><em>fileobject</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a representation of the configuration to the specified file object.  This
representation can be parsed by a future <a class="reference internal" href="#ConfigParser.RawConfigParser.read" title="ConfigParser.RawConfigParser.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> call.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.remove_option">
<code class="descclassname">RawConfigParser.</code><code class="descname">remove_option</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.remove_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the specified <em>option</em> from the specified <em>section</em>. If the section does
not exist, raise <a class="reference internal" href="#ConfigParser.NoSectionError" title="ConfigParser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>.  If the option existed to be removed,
return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>; otherwise return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.remove_section">
<code class="descclassname">RawConfigParser.</code><code class="descname">remove_section</code><span class="sig-paren">(</span><em>section</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.remove_section" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the specified <em>section</em> from the configuration. If the section in fact
existed, return <code class="docutils literal notranslate"><span class="pre">True</span></code>. Otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.RawConfigParser.optionxform">
<code class="descclassname">RawConfigParser.</code><code class="descname">optionxform</code><span class="sig-paren">(</span><em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.RawConfigParser.optionxform" title="Permalink to this definition">¶</a></dt>
<dd><p>Transforms the option name <em>option</em> as found in an input file or as passed in
by client code to the form that should be used in the internal structures.
The default implementation returns a lower-case version of <em>option</em>;
subclasses may override this or client code can set an attribute of this name
on instances to affect this behavior.</p>
<p>You don’t necessarily need to subclass a ConfigParser to use this method, you
can also re-set it on an instance, to a function that takes a string
argument.  Setting it to <code class="docutils literal notranslate"><span class="pre">str</span></code>, for example, would make option names case
sensitive:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">cfgparser</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="p">()</span>
<span class="o">...</span>
<span class="n">cfgparser</span><span class="o">.</span><span class="n">optionxform</span> <span class="o">=</span> <span class="nb">str</span>
</pre></div>
</div>
<p>Note that when reading configuration files, whitespace around the
option names are stripped before <a class="reference internal" href="#ConfigParser.RawConfigParser.optionxform" title="ConfigParser.RawConfigParser.optionxform"><code class="xref py py-meth docutils literal notranslate"><span class="pre">optionxform()</span></code></a> is called.</p>
</dd></dl>

</div>
<div class="section" id="configparser-objects">
<span id="id2"></span><h2>13.2.2. ConfigParser Objects<a class="headerlink" href="#configparser-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> class extends some methods of the
<a class="reference internal" href="#ConfigParser.RawConfigParser" title="ConfigParser.RawConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawConfigParser</span></code></a> interface, adding some optional arguments.</p>
<dl class="method">
<dt id="ConfigParser.ConfigParser.get">
<code class="descclassname">ConfigParser.</code><code class="descname">get</code><span class="sig-paren">(</span><em>section</em>, <em>option</em><span class="optional">[</span>, <em>raw</em><span class="optional">[</span>, <em>vars</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.ConfigParser.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Get an <em>option</em> value for the named <em>section</em>.  If <em>vars</em> is provided, it
must be a dictionary.  The <em>option</em> is looked up in <em>vars</em> (if provided),
<em>section</em>, and in <em>defaults</em> in that order.</p>
<p>All the <code class="docutils literal notranslate"><span class="pre">'%'</span></code> interpolations are expanded in the return values, unless the
<em>raw</em> argument is true.  Values for interpolation keys are looked up in the
same manner as the option.</p>
</dd></dl>

<dl class="method">
<dt id="ConfigParser.ConfigParser.items">
<code class="descclassname">ConfigParser.</code><code class="descname">items</code><span class="sig-paren">(</span><em>section</em><span class="optional">[</span>, <em>raw</em><span class="optional">[</span>, <em>vars</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.ConfigParser.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> pairs for each option in the given <em>section</em>.
Optional arguments have the same meaning as for the <a class="reference internal" href="#ConfigParser.ConfigParser.get" title="ConfigParser.ConfigParser.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="safeconfigparser-objects">
<span id="id3"></span><h2>13.2.3. SafeConfigParser Objects<a class="headerlink" href="#safeconfigparser-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#ConfigParser.SafeConfigParser" title="ConfigParser.SafeConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SafeConfigParser</span></code></a> class implements the same extended interface as
<a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>, with the following addition:</p>
<dl class="method">
<dt id="ConfigParser.SafeConfigParser.set">
<code class="descclassname">SafeConfigParser.</code><code class="descname">set</code><span class="sig-paren">(</span><em>section</em>, <em>option</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#ConfigParser.SafeConfigParser.set" title="Permalink to this definition">¶</a></dt>
<dd><p>If the given section exists, set the given option to the specified value;
otherwise raise <a class="reference internal" href="#ConfigParser.NoSectionError" title="ConfigParser.NoSectionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSectionError</span></code></a>.  <em>value</em> must be a string (<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>
or <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>); if not, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="examples">
<h2>13.2.4. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>An example of writing to a configuration file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ConfigParser</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span>

<span class="c1"># When adding sections or items, add them in the reverse order of</span>
<span class="c1"># how you want them to be displayed in the actual file.</span>
<span class="c1"># In addition, please note that using RawConfigParser&#39;s and the raw</span>
<span class="c1"># mode of ConfigParser&#39;s respective set functions, you can assign</span>
<span class="c1"># non-string values to keys internally, but will receive an error</span>
<span class="c1"># when attempting to write to a file or when you get it in non-raw</span>
<span class="c1"># mode. SafeConfigParser does not allow such assignments to take place.</span>
<span class="n">config</span><span class="o">.</span><span class="n">add_section</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;an_int&#39;</span><span class="p">,</span> <span class="s1">&#39;15&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_bool&#39;</span><span class="p">,</span> <span class="s1">&#39;true&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_float&#39;</span><span class="p">,</span> <span class="s1">&#39;3.1415&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="s1">&#39;fun&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">,</span> <span class="s1">&#39;Python&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="si">%(bar)s</span><span class="s1"> is </span><span class="si">%(baz)s</span><span class="s1">!&#39;</span><span class="p">)</span>

<span class="c1"># Writing our configuration file to &#39;example.cfg&#39;</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">configfile</span><span class="p">:</span>
    <span class="n">config</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">configfile</span><span class="p">)</span>
</pre></div>
</div>
<p>An example of reading the configuration file again:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ConfigParser</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">()</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="c1"># getfloat() raises an exception if the value is not a float</span>
<span class="c1"># getint() and getboolean() also do this for their respective types</span>
<span class="n">a_float</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getfloat</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_float&#39;</span><span class="p">)</span>
<span class="n">an_int</span> <span class="o">=</span> <span class="n">config</span><span class="o">.</span><span class="n">getint</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;an_int&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">a_float</span> <span class="o">+</span> <span class="n">an_int</span>

<span class="c1"># Notice that the next output does not interpolate &#39;%(bar)s&#39; or &#39;%(baz)s&#39;.</span>
<span class="c1"># This is because we are using a RawConfigParser().</span>
<span class="k">if</span> <span class="n">config</span><span class="o">.</span><span class="n">getboolean</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;a_bool&#39;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>To get interpolation, you will need to use a <a class="reference internal" href="#ConfigParser.ConfigParser" title="ConfigParser.ConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> or
<a class="reference internal" href="#ConfigParser.SafeConfigParser" title="ConfigParser.SafeConfigParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SafeConfigParser</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ConfigParser</span>

<span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">ConfigParser</span><span class="p">()</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="c1"># Set the third, optional argument of get to 1 if you wish to use raw mode.</span>
<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>  <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>
<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>  <span class="c1"># -&gt; &quot;%(bar)s is %(baz)s!&quot;</span>

<span class="c1"># The optional fourth argument is a dict with members that will take</span>
<span class="c1"># precedence in interpolation.</span>
<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="s1">&#39;Documentation&#39;</span><span class="p">,</span>
                                        <span class="s1">&#39;baz&#39;</span><span class="p">:</span> <span class="s1">&#39;evil&#39;</span><span class="p">})</span>
</pre></div>
</div>
<p>Defaults are available in all three types of ConfigParsers. They are used in
interpolation if an option used is not defined elsewhere.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ConfigParser</span>

<span class="c1"># New instance with &#39;bar&#39; and &#39;baz&#39; defaulting to &#39;Life&#39; and &#39;hard&#39; each</span>
<span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">SafeConfigParser</span><span class="p">({</span><span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="s1">&#39;Life&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">:</span> <span class="s1">&#39;hard&#39;</span><span class="p">})</span>
<span class="n">config</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="s1">&#39;example.cfg&#39;</span><span class="p">)</span>

<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>  <span class="c1"># -&gt; &quot;Python is fun!&quot;</span>
<span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;bar&#39;</span><span class="p">)</span>
<span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;baz&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;Section1&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>  <span class="c1"># -&gt; &quot;Life is hard!&quot;</span>
</pre></div>
</div>
<p>The function <code class="docutils literal notranslate"><span class="pre">opt_move</span></code> below can be used to move options between sections:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">opt_move</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">section1</span><span class="p">,</span> <span class="n">section2</span><span class="p">,</span> <span class="n">option</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">config</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="n">section2</span><span class="p">,</span> <span class="n">option</span><span class="p">,</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">section1</span><span class="p">,</span> <span class="n">option</span><span class="p">,</span> <span class="mi">1</span><span class="p">))</span>
    <span class="k">except</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">NoSectionError</span><span class="p">:</span>
        <span class="c1"># Create non-existent section</span>
        <span class="n">config</span><span class="o">.</span><span class="n">add_section</span><span class="p">(</span><span class="n">section2</span><span class="p">)</span>
        <span class="n">opt_move</span><span class="p">(</span><span class="n">config</span><span class="p">,</span> <span class="n">section1</span><span class="p">,</span> <span class="n">section2</span><span class="p">,</span> <span class="n">option</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">config</span><span class="o">.</span><span class="n">remove_option</span><span class="p">(</span><span class="n">section1</span><span class="p">,</span> <span class="n">option</span><span class="p">)</span>
</pre></div>
</div>
<p>Some configuration files are known to include settings without values, but which
otherwise conform to the syntax supported by <a class="reference internal" href="#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>.  The
<em>allow_no_value</em> parameter to the constructor can be used to indicate that such
values should be accepted:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">ConfigParser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">io</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">sample_config</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[mysqld]</span>
<span class="gp">... </span><span class="s2">user = mysql</span>
<span class="gp">... </span><span class="s2">pid-file = /var/run/mysqld/mysqld.pid</span>
<span class="gp">... </span><span class="s2">skip-external-locking</span>
<span class="gp">... </span><span class="s2">old_passwords = 1</span>
<span class="gp">... </span><span class="s2">skip-bdb</span>
<span class="gp">... </span><span class="s2">skip-innodb</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">(</span><span class="n">allow_no_value</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">readfp</span><span class="p">(</span><span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">(</span><span class="n">sample_config</span><span class="p">))</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings with values are treated as before:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;mysqld&quot;</span><span class="p">,</span> <span class="s2">&quot;user&quot;</span><span class="p">)</span>
<span class="go">&#39;mysql&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings without values provide None:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;mysqld&quot;</span><span class="p">,</span> <span class="s2">&quot;skip-bdb&quot;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Settings which aren&#39;t specified still raise an error:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s2">&quot;mysqld&quot;</span><span class="p">,</span> <span class="s2">&quot;does-not-exist&quot;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">ConfigParser.NoOptionError</span>: <span class="n">No option &#39;does-not-exist&#39; in section: &#39;mysqld&#39;</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a><ul>
<li><a class="reference internal" href="#rawconfigparser-objects">13.2.1. RawConfigParser Objects</a></li>
<li><a class="reference internal" href="#configparser-objects">13.2.2. ConfigParser Objects</a></li>
<li><a class="reference internal" href="#safeconfigparser-objects">13.2.3. SafeConfigParser Objects</a></li>
<li><a class="reference internal" href="#examples">13.2.4. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="csv.html"
                        title="previous chapter">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="robotparser.html"
                        title="next chapter">13.3. <code class="docutils literal notranslate"><span class="pre">robotparser</span></code> —  Parser for robots.txt</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/configparser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="robotparser.html" title="13.3. robotparser — Parser for robots.txt"
             >next</a> |</li>
        <li class="right" >
          <a href="csv.html" title="13.1. csv — CSV File Reading and Writing"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�#�6�6html/library/constants.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. Built-in Constants &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="5. Built-in Types" href="stdtypes.html" />
    <link rel="prev" title="2. Built-in Functions" href="functions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/constants.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdtypes.html" title="5. Built-in Types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="functions.html" title="2. Built-in Functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="built-in-constants">
<span id="built-in-consts"></span><h1>4. Built-in Constants<a class="headerlink" href="#built-in-constants" title="Permalink to this headline">¶</a></h1>
<p>A small number of constants live in the built-in namespace.  They are:</p>
<dl class="data">
<dt id="False">
<code class="descname">False</code><a class="headerlink" href="#False" title="Permalink to this definition">¶</a></dt>
<dd><p>The false value of the <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="True">
<code class="descname">True</code><a class="headerlink" href="#True" title="Permalink to this definition">¶</a></dt>
<dd><p>The true value of the <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="None">
<code class="descname">None</code><a class="headerlink" href="#None" title="Permalink to this definition">¶</a></dt>
<dd><p>The sole value of <a class="reference internal" href="types.html#types.NoneType" title="types.NoneType"><code class="xref py py-attr docutils literal notranslate"><span class="pre">types.NoneType</span></code></a>.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is frequently used to
represent the absence of a value, as when default arguments are not passed to a
function.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Assignments to <code class="docutils literal notranslate"><span class="pre">None</span></code> are illegal and raise a <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="NotImplemented">
<code class="descname">NotImplemented</code><a class="headerlink" href="#NotImplemented" title="Permalink to this definition">¶</a></dt>
<dd><p>Special value which can be returned by the “rich comparison” special methods
(<a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, and friends), to indicate that the comparison
is not implemented with respect to the other type.</p>
</dd></dl>

<dl class="data">
<dt id="Ellipsis">
<code class="descname">Ellipsis</code><a class="headerlink" href="#Ellipsis" title="Permalink to this definition">¶</a></dt>
<dd><p>Special value used in conjunction with extended slicing syntax.</p>
</dd></dl>

<dl class="data">
<dt id="__debug__">
<code class="descname">__debug__</code><a class="headerlink" href="#__debug__" title="Permalink to this definition">¶</a></dt>
<dd><p>This constant is true if Python was not started with an <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> option.
See also the <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The names <a class="reference internal" href="#None" title="None"><code class="xref py py-data docutils literal notranslate"><span class="pre">None</span></code></a> and <a class="reference internal" href="#__debug__" title="__debug__"><code class="xref py py-data docutils literal notranslate"><span class="pre">__debug__</span></code></a> cannot be reassigned
(assignments to them, even as an attribute name, raise <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>),
so they can be considered “true” constants.</p>
<div class="last versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Assignments to <code class="docutils literal notranslate"><span class="pre">__debug__</span></code> as an attribute became illegal.</p>
</div>
</div>
<div class="section" id="constants-added-by-the-site-module">
<h2>4.1. Constants added by the <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module<a class="headerlink" href="#constants-added-by-the-site-module" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module (which is imported automatically during startup, except
if the <a class="reference internal" href="../using/cmdline.html#id2"><code class="xref std std-option docutils literal notranslate"><span class="pre">-S</span></code></a> command-line option is given) adds several constants to the
built-in namespace.  They are useful for the interactive interpreter shell and
should not be used in programs.</p>
<dl class="data">
<dt id="quit">
<code class="descname">quit</code><span class="sig-paren">(</span><span class="optional">[</span><em>code=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#quit" title="Permalink to this definition">¶</a></dt>
<dt id="exit">
<code class="descname">exit</code><span class="sig-paren">(</span><span class="optional">[</span><em>code=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#exit" title="Permalink to this definition">¶</a></dt>
<dd><p>Objects that when printed, print a message like “Use quit() or Ctrl-D
(i.e. EOF) to exit”, and when called, raise <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> with the
specified exit code.</p>
</dd></dl>

<dl class="data">
<dt id="copyright">
<code class="descname">copyright</code><a class="headerlink" href="#copyright" title="Permalink to this definition">¶</a></dt>
<dt id="credits">
<code class="descname">credits</code><a class="headerlink" href="#credits" title="Permalink to this definition">¶</a></dt>
<dd><p>Objects that when printed or called, print the text of copyright or
credits, respectively.</p>
</dd></dl>

<dl class="data">
<dt id="license">
<code class="descname">license</code><a class="headerlink" href="#license" title="Permalink to this definition">¶</a></dt>
<dd><p>Object that when printed, prints the message “Type license() to see the
full license text”, and when called, displays the full license text in a
pager-like fashion (one screen at a time).</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Built-in Constants</a><ul>
<li><a class="reference internal" href="#constants-added-by-the-site-module">4.1. Constants added by the <code class="docutils literal notranslate"><span class="pre">site</span></code> module</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="functions.html"
                        title="previous chapter">2. Built-in Functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stdtypes.html"
                        title="next chapter">5. Built-in Types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/constants.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdtypes.html" title="5. Built-in Types"
             >next</a> |</li>
        <li class="right" >
          <a href="functions.html" title="2. Built-in Functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��3�X�Xhtml/library/contextlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.7. contextlib — Utilities for with-statement contexts &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.8. abc — Abstract Base Classes" href="abc.html" />
    <link rel="prev" title="28.6. warnings — Warning control" href="warnings.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/contextlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="abc.html" title="28.8. abc — Abstract Base Classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="warnings.html" title="28.6. warnings — Warning control"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-contextlib">
<span id="contextlib-utilities-for-with-statement-contexts"></span><h1>28.7. <a class="reference internal" href="#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> — Utilities for <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>-statement contexts<a class="headerlink" href="#module-contextlib" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/contextlib.py">Lib/contextlib.py</a></p>
<hr class="docutils" />
<p>This module provides utilities for common tasks involving the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement. For more information see also <a class="reference internal" href="stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a> and
<a class="reference internal" href="../reference/datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>.</p>
<p>Functions provided:</p>
<dl class="function">
<dt id="contextlib.contextmanager">
<code class="descclassname">contextlib.</code><code class="descname">contextmanager</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.contextmanager" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> that can be used to define a factory
function for <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement context managers, without needing to
create a class or separate <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods.</p>
<p>While many objects natively support use in with statements, sometimes a
resource needs to be managed that isn’t a context manager in its own right,
and doesn’t implement a <code class="docutils literal notranslate"><span class="pre">close()</span></code> method for use with <code class="docutils literal notranslate"><span class="pre">contextlib.closing</span></code></p>
<p>An abstract example would be the following to ensure correct resource
management:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">managed_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
    <span class="c1"># Code to acquire resource, e.g.:</span>
    <span class="n">resource</span> <span class="o">=</span> <span class="n">acquire_resource</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">resource</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="c1"># Code to release resource, e.g.:</span>
        <span class="n">release_resource</span><span class="p">(</span><span class="n">resource</span><span class="p">)</span>

<span class="o">&gt;&gt;&gt;</span> <span class="k">with</span> <span class="n">managed_resource</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">3600</span><span class="p">)</span> <span class="k">as</span> <span class="n">resource</span><span class="p">:</span>
<span class="o">...</span>     <span class="c1"># Resource is released at the end of this block,</span>
<span class="o">...</span>     <span class="c1"># even if code in the block raises an exception</span>
</pre></div>
</div>
<p>The function being decorated must return a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>-iterator when
called. This iterator must yield exactly one value, which will be bound to
the targets in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement’s <a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause, if any.</p>
<p>At the point where the generator yields, the block nested in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement is executed.  The generator is then resumed after the block is exited.
If an unhandled exception occurs in the block, it is reraised inside the
generator at the point where the yield occurred.  Thus, you can use a
<a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement to trap
the error (if any), or ensure that some cleanup takes place. If an exception is
trapped merely in order to log it or to perform some action (rather than to
suppress it entirely), the generator must reraise that exception. Otherwise the
generator context manager will indicate to the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement that
the exception has been handled, and execution will resume with the statement
immediately following the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
</dd></dl>

<dl class="function">
<dt id="contextlib.nested">
<code class="descclassname">contextlib.</code><code class="descname">nested</code><span class="sig-paren">(</span><em>mgr1</em><span class="optional">[</span>, <em>mgr2</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.nested" title="Permalink to this definition">¶</a></dt>
<dd><p>Combine multiple context managers into a single nested context manager.</p>
<p>This function has been deprecated in favour of the multiple manager form
of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>The one advantage of this function over the multiple manager form of the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is that argument unpacking allows it to be
used with a variable number of context managers as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">nested</span>

<span class="k">with</span> <span class="n">nested</span><span class="p">(</span><span class="o">*</span><span class="n">managers</span><span class="p">):</span>
    <span class="n">do_something</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that if the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method of one of the nested context managers
indicates an exception should be suppressed, no exception information will be
passed to any remaining outer context managers. Similarly, if the
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method of one of the nested managers raises an exception, any
previous exception state will be lost; the new exception will be passed to the
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods of any remaining outer context managers. In general,
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods should avoid raising exceptions, and in particular they
should not re-raise a passed-in exception.</p>
<p>This function has two major quirks that have led to it being deprecated. Firstly,
as the context managers are all constructed before the function is invoked, the
<a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> methods of the inner context managers are
not actually covered by the scope of the outer context managers. That means, for
example, that using <a class="reference internal" href="#contextlib.nested" title="contextlib.nested"><code class="xref py py-func docutils literal notranslate"><span class="pre">nested()</span></code></a> to open two files is a programming error as the
first file will not be closed promptly if an exception is thrown when opening
the second file.</p>
<p>Secondly, if the <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method of one of the inner context managers
raises an exception that is caught and suppressed by the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method
of one of the outer context managers, this construct will raise
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> rather than skipping the body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</p>
<p>Developers that need to support nesting of a variable number of context managers
can either use the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module to suppress the DeprecationWarning
raised by this function or else use this function as a model for an application
specific implementation.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>The with-statement now supports this functionality directly (without the
confusing error prone quirks).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="contextlib.closing">
<code class="descclassname">contextlib.</code><code class="descname">closing</code><span class="sig-paren">(</span><em>thing</em><span class="sig-paren">)</span><a class="headerlink" href="#contextlib.closing" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a context manager that closes <em>thing</em> upon completion of the block.  This
is basically equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">closing</span><span class="p">(</span><span class="n">thing</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">thing</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">thing</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>And lets you write code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">closing</span>
<span class="kn">import</span> <span class="nn">urllib</span>

<span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.python.org&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">page</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span>
</pre></div>
</div>
<p>without needing to explicitly close <code class="docutils literal notranslate"><span class="pre">page</span></code>.  Even if an error occurs,
<code class="docutils literal notranslate"><span class="pre">page.close()</span></code> will be called when the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> block is exited.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
<dd>The specification, background, and examples for the Python <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="warnings.html"
                        title="previous chapter">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="abc.html"
                        title="next chapter">28.8. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/contextlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="abc.html" title="28.8. abc — Abstract Base Classes"
             >next</a> |</li>
        <li class="right" >
          <a href="warnings.html" title="28.6. warnings — Warning control"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���~�~�html/library/cookie.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.22. Cookie — HTTP state management &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.23. xmlrpclib — XML-RPC client access" href="xmlrpclib.html" />
    <link rel="prev" title="20.21. cookielib — Cookie handling for HTTP clients" href="cookielib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cookie.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xmlrpclib.html" title="20.23. xmlrpclib — XML-RPC client access"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cookielib.html" title="20.21. cookielib — Cookie handling for HTTP clients"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-Cookie">
<span id="cookie-http-state-management"></span><h1>20.22. <a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> — HTTP state management<a class="headerlink" href="#module-Cookie" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.cookies</span></code> in Python
3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/Cookie.py">Lib/Cookie.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module defines classes for abstracting the concept of
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.</p>
<p>The module formerly strictly applied the parsing rules described in the
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> and <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2068.html"><strong>RFC 2068</strong></a> specifications.  It has since been discovered that
MSIE 3.0x doesn’t follow the character rules outlined in those specs and also
many current day browsers and servers have relaxed parsing rules when comes to
Cookie handling.  As a result, the parsing rules used are a bit less strict.</p>
<p>The character set, <a class="reference internal" href="string.html#string.ascii_letters" title="string.ascii_letters"><code class="xref py py-data docutils literal notranslate"><span class="pre">string.ascii_letters</span></code></a>, <a class="reference internal" href="string.html#string.digits" title="string.digits"><code class="xref py py-data docutils literal notranslate"><span class="pre">string.digits</span></code></a> and
<code class="docutils literal notranslate"><span class="pre">!#$%&amp;'*+-.^_`|~</span></code> denote the set of valid characters allowed by this module
in Cookie name (as <a class="reference internal" href="#Cookie.Morsel.key" title="Cookie.Morsel.key"><code class="xref py py-attr docutils literal notranslate"><span class="pre">key</span></code></a>).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On encountering an invalid cookie, <a class="reference internal" href="#Cookie.CookieError" title="Cookie.CookieError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CookieError</span></code></a> is raised, so if your
cookie data comes from a browser you should always prepare for invalid data
and catch <a class="reference internal" href="#Cookie.CookieError" title="Cookie.CookieError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CookieError</span></code></a> on parsing.</p>
</div>
<dl class="exception">
<dt id="Cookie.CookieError">
<em class="property">exception </em><code class="descclassname">Cookie.</code><code class="descname">CookieError</code><a class="headerlink" href="#Cookie.CookieError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception failing because of <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> invalidity: incorrect attributes,
incorrect <em class="mailheader">Set-Cookie</em> header, etc.</p>
</dd></dl>

<dl class="class">
<dt id="Cookie.BaseCookie">
<em class="property">class </em><code class="descclassname">Cookie.</code><code class="descname">BaseCookie</code><span class="sig-paren">(</span><span class="optional">[</span><em>input</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is a dictionary-like object whose keys are strings and whose values
are <a class="reference internal" href="#Cookie.Morsel" title="Cookie.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a> instances. Note that upon setting a key to a value, the
value is first converted to a <a class="reference internal" href="#Cookie.Morsel" title="Cookie.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a> containing the key and the value.</p>
<p>If <em>input</em> is given, it is passed to the <a class="reference internal" href="#Cookie.BaseCookie.load" title="Cookie.BaseCookie.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> method.</p>
</dd></dl>

<dl class="class">
<dt id="Cookie.SimpleCookie">
<em class="property">class </em><code class="descclassname">Cookie.</code><code class="descname">SimpleCookie</code><span class="sig-paren">(</span><span class="optional">[</span><em>input</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.SimpleCookie" title="Permalink to this definition">¶</a></dt>
<dd><p>This class derives from <a class="reference internal" href="#Cookie.BaseCookie" title="Cookie.BaseCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCookie</span></code></a> and overrides <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_decode()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_encode()</span></code> to be the identity and <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> respectively.</p>
</dd></dl>

<dl class="class">
<dt id="Cookie.SerialCookie">
<em class="property">class </em><code class="descclassname">Cookie.</code><code class="descname">SerialCookie</code><span class="sig-paren">(</span><span class="optional">[</span><em>input</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.SerialCookie" title="Permalink to this definition">¶</a></dt>
<dd><p>This class derives from <a class="reference internal" href="#Cookie.BaseCookie" title="Cookie.BaseCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCookie</span></code></a> and overrides <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_decode()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_encode()</span></code> to be the <a class="reference internal" href="pickle.html#pickle.loads" title="pickle.loads"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.loads()</span></code></a> and
<a class="reference internal" href="pickle.html#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.dumps()</span></code></a>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>Reading pickled values from untrusted cookie data is a huge security hole, as
pickle strings can be crafted to cause arbitrary code to execute on your server.
It is supported for backwards compatibility only, and may eventually go away.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="Cookie.SmartCookie">
<em class="property">class </em><code class="descclassname">Cookie.</code><code class="descname">SmartCookie</code><span class="sig-paren">(</span><span class="optional">[</span><em>input</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.SmartCookie" title="Permalink to this definition">¶</a></dt>
<dd><p>This class derives from <a class="reference internal" href="#Cookie.BaseCookie" title="Cookie.BaseCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCookie</span></code></a>. It overrides <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_decode()</span></code>
to be <a class="reference internal" href="pickle.html#pickle.loads" title="pickle.loads"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.loads()</span></code></a> if it is a valid pickle, and otherwise the value
itself. It overrides <code class="xref py py-meth docutils literal notranslate"><span class="pre">value_encode()</span></code> to be <a class="reference internal" href="pickle.html#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.dumps()</span></code></a> unless it
is a string, in which case it returns the value itself.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The same security warning from <a class="reference internal" href="#Cookie.SerialCookie" title="Cookie.SerialCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">SerialCookie</span></code></a> applies here.</p>
</div>
</dd></dl>

<p>A further security note is warranted.  For backwards compatibility, the
<a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module exports a class named <code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code> which is
just an alias for <a class="reference internal" href="#Cookie.SmartCookie" title="Cookie.SmartCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">SmartCookie</span></code></a>.  This is probably a mistake and will
likely be removed in a future version.  You should not use the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code> class in your applications, for the same reason why
you should not use the <a class="reference internal" href="#Cookie.SerialCookie" title="Cookie.SerialCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">SerialCookie</span></code></a> class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a></dt>
<dd>HTTP cookie handling for web <em>clients</em>.  The <a class="reference internal" href="cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> and <a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a>
modules do not depend on each other.</dd>
<dt><span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> - HTTP State Management Mechanism</dt>
<dd>This is the state management specification implemented by this module.</dd>
</dl>
</div>
<div class="section" id="cookie-objects">
<span id="id1"></span><h2>20.22.1. Cookie Objects<a class="headerlink" href="#cookie-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="Cookie.BaseCookie.value_decode">
<code class="descclassname">BaseCookie.</code><code class="descname">value_decode</code><span class="sig-paren">(</span><em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie.value_decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a decoded value from a string representation. Return value can be any
type. This method does nothing in <a class="reference internal" href="#Cookie.BaseCookie" title="Cookie.BaseCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCookie</span></code></a> — it exists so it can be
overridden.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.BaseCookie.value_encode">
<code class="descclassname">BaseCookie.</code><code class="descname">value_encode</code><span class="sig-paren">(</span><em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie.value_encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an encoded value. <em>val</em> can be any type, but return value must be a
string. This method does nothing in <a class="reference internal" href="#Cookie.BaseCookie" title="Cookie.BaseCookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCookie</span></code></a> — it exists so it can
be overridden.</p>
<p>In general, it should be the case that <a class="reference internal" href="#Cookie.BaseCookie.value_encode" title="Cookie.BaseCookie.value_encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_encode()</span></code></a> and
<a class="reference internal" href="#Cookie.BaseCookie.value_decode" title="Cookie.BaseCookie.value_decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">value_decode()</span></code></a> are inverses on the range of <em>value_decode</em>.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.BaseCookie.output">
<code class="descclassname">BaseCookie.</code><code class="descname">output</code><span class="sig-paren">(</span><span class="optional">[</span><em>attrs</em><span class="optional">[</span>, <em>header</em><span class="optional">[</span>, <em>sep</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie.output" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representation suitable to be sent as HTTP headers. <em>attrs</em> and
<em>header</em> are sent to each <a class="reference internal" href="#Cookie.Morsel" title="Cookie.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a>’s <a class="reference internal" href="#Cookie.BaseCookie.output" title="Cookie.BaseCookie.output"><code class="xref py py-meth docutils literal notranslate"><span class="pre">output()</span></code></a> method. <em>sep</em> is used
to join the headers together, and is by default the combination <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>
(CRLF).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The default separator has been changed from <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> to match the cookie
specification.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="Cookie.BaseCookie.js_output">
<code class="descclassname">BaseCookie.</code><code class="descname">js_output</code><span class="sig-paren">(</span><span class="optional">[</span><em>attrs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie.js_output" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an embeddable JavaScript snippet, which, if run on a browser which
supports JavaScript, will act the same as if the HTTP headers was sent.</p>
<p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#Cookie.BaseCookie.output" title="Cookie.BaseCookie.output"><code class="xref py py-meth docutils literal notranslate"><span class="pre">output()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.BaseCookie.load">
<code class="descclassname">BaseCookie.</code><code class="descname">load</code><span class="sig-paren">(</span><em>rawdata</em><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.BaseCookie.load" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>rawdata</em> is a string, parse it as an <code class="docutils literal notranslate"><span class="pre">HTTP_COOKIE</span></code> and add the values
found there as <a class="reference internal" href="#Cookie.Morsel" title="Cookie.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a>s. If it is a dictionary, it is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">rawdata</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
    <span class="n">cookie</span><span class="p">[</span><span class="n">k</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="morsel-objects">
<span id="id2"></span><h2>20.22.2. Morsel Objects<a class="headerlink" href="#morsel-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="Cookie.Morsel">
<em class="property">class </em><code class="descclassname">Cookie.</code><code class="descname">Morsel</code><a class="headerlink" href="#Cookie.Morsel" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract a key/value pair, which has some <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> attributes.</p>
<p>Morsels are dictionary-like objects, whose set of keys is constant — the valid
<span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> attributes, which are</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">expires</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">path</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">comment</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">domain</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">max-age</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">secure</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">version</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">httponly</span></code></li>
</ul>
<p>The attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">httponly</span></code> specifies that the cookie is only transferred
in HTTP requests, and is not accessible through JavaScript. This is intended
to mitigate some forms of cross-site scripting.</p>
<p>The keys are case-insensitive.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">httponly</span></code> attribute was added.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="Cookie.Morsel.value">
<code class="descclassname">Morsel.</code><code class="descname">value</code><a class="headerlink" href="#Cookie.Morsel.value" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of the cookie.</p>
</dd></dl>

<dl class="attribute">
<dt id="Cookie.Morsel.coded_value">
<code class="descclassname">Morsel.</code><code class="descname">coded_value</code><a class="headerlink" href="#Cookie.Morsel.coded_value" title="Permalink to this definition">¶</a></dt>
<dd><p>The encoded value of the cookie — this is what should be sent.</p>
</dd></dl>

<dl class="attribute">
<dt id="Cookie.Morsel.key">
<code class="descclassname">Morsel.</code><code class="descname">key</code><a class="headerlink" href="#Cookie.Morsel.key" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the cookie.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.Morsel.set">
<code class="descclassname">Morsel.</code><code class="descname">set</code><span class="sig-paren">(</span><em>key</em>, <em>value</em>, <em>coded_value</em><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.Morsel.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>key</em>, <em>value</em> and <em>coded_value</em> attributes.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.Morsel.isReservedKey">
<code class="descclassname">Morsel.</code><code class="descname">isReservedKey</code><span class="sig-paren">(</span><em>K</em><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.Morsel.isReservedKey" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether <em>K</em> is a member of the set of keys of a <a class="reference internal" href="#Cookie.Morsel" title="Cookie.Morsel"><code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.Morsel.output">
<code class="descclassname">Morsel.</code><code class="descname">output</code><span class="sig-paren">(</span><span class="optional">[</span><em>attrs</em><span class="optional">[</span>, <em>header</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.Morsel.output" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representation of the Morsel, suitable to be sent as an HTTP
header. By default, all the attributes are included, unless <em>attrs</em> is given, in
which case it should be a list of attributes to use. <em>header</em> is by default
<code class="docutils literal notranslate"><span class="pre">&quot;Set-Cookie:&quot;</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.Morsel.js_output">
<code class="descclassname">Morsel.</code><code class="descname">js_output</code><span class="sig-paren">(</span><span class="optional">[</span><em>attrs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.Morsel.js_output" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an embeddable JavaScript snippet, which, if run on a browser which
supports JavaScript, will act the same as if the HTTP header was sent.</p>
<p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#Cookie.Morsel.output" title="Cookie.Morsel.output"><code class="xref py py-meth docutils literal notranslate"><span class="pre">output()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="Cookie.Morsel.OutputString">
<code class="descclassname">Morsel.</code><code class="descname">OutputString</code><span class="sig-paren">(</span><span class="optional">[</span><em>attrs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Cookie.Morsel.OutputString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the Morsel, without any surrounding HTTP or
JavaScript.</p>
<p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#Cookie.Morsel.output" title="Cookie.Morsel.output"><code class="xref py py-meth docutils literal notranslate"><span class="pre">output()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="example">
<span id="cookie-example"></span><h2>20.22.3. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The following example demonstrates how to use the <a class="reference internal" href="#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">Cookie</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;fig&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;newton&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;sugar&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;wafer&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span> <span class="c1"># generate HTTP headers</span>
<span class="go">Set-Cookie: fig=newton</span>
<span class="go">Set-Cookie: sugar=wafer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span><span class="o">.</span><span class="n">output</span><span class="p">()</span> <span class="c1"># same thing</span>
<span class="go">Set-Cookie: fig=newton</span>
<span class="go">Set-Cookie: sugar=wafer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;rocky&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;road&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;rocky&quot;</span><span class="p">][</span><span class="s2">&quot;path&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;/cookie&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span><span class="o">.</span><span class="n">output</span><span class="p">(</span><span class="n">header</span><span class="o">=</span><span class="s2">&quot;Cookie:&quot;</span><span class="p">)</span>
<span class="go">Cookie: rocky=road; Path=/cookie</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span><span class="o">.</span><span class="n">output</span><span class="p">(</span><span class="n">attrs</span><span class="o">=</span><span class="p">[],</span> <span class="n">header</span><span class="o">=</span><span class="s2">&quot;Cookie:&quot;</span><span class="p">)</span>
<span class="go">Cookie: rocky=road</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="s2">&quot;chips=ahoy; vienna=finger&quot;</span><span class="p">)</span> <span class="c1"># load from a string (HTTP header)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: chips=ahoy</span>
<span class="go">Set-Cookie: vienna=finger</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="s1">&#39;keebler=&quot;E=everybody; L=</span><span class="se">\\</span><span class="s1">&quot;Loves</span><span class="se">\\</span><span class="s1">&quot;; fudge=</span><span class="se">\\</span><span class="s1">012;&quot;;&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: keebler=&quot;E=everybody; L=\&quot;Loves\&quot;; fudge=\012;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;oreo&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;doublestuff&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;oreo&quot;</span><span class="p">][</span><span class="s2">&quot;path&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;/&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: oreo=doublestuff; Path=/</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;twix&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;none for you&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;twix&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;none for you&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">7</span> <span class="c1"># equivalent to C[&quot;number&quot;] = str(7)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;seven&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;7&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;seven&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: number=7</span>
<span class="go">Set-Cookie: string=seven</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># SerialCookie and SmartCookie are deprecated</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># using it can cause security loopholes in your code.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SerialCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;seven&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;seven&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: number=&quot;I7\012.&quot;</span>
<span class="go">Set-Cookie: string=&quot;S&#39;seven&#39;\012p1\012.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SmartCookie</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;seven&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;number&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">[</span><span class="s2">&quot;string&quot;</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;seven&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">C</span>
<span class="go">Set-Cookie: number=&quot;I7\012.&quot;</span>
<span class="go">Set-Cookie: string=seven</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a><ul>
<li><a class="reference internal" href="#cookie-objects">20.22.1. Cookie Objects</a></li>
<li><a class="reference internal" href="#morsel-objects">20.22.2. Morsel Objects</a></li>
<li><a class="reference internal" href="#example">20.22.3. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cookielib.html"
                        title="previous chapter">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xmlrpclib.html"
                        title="next chapter">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cookie.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xmlrpclib.html" title="20.23. xmlrpclib — XML-RPC client access"
             >next</a> |</li>
        <li class="right" >
          <a href="cookielib.html" title="20.21. cookielib — Cookie handling for HTTP clients"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\(�u�c�chtml/library/cookielib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.21. cookielib — Cookie handling for HTTP clients &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.22. Cookie — HTTP state management" href="cookie.html" />
    <link rel="prev" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler" href="cgihttpserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/cookielib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cookie.html" title="20.22. Cookie — HTTP state management"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cgihttpserver.html" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-cookielib">
<span id="cookielib-cookie-handling-for-http-clients"></span><h1>20.21. <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> — Cookie handling for HTTP clients<a class="headerlink" href="#module-cookielib" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.cookiejar</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/cookielib.py">Lib/cookielib.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> module defines classes for automatic handling of HTTP
cookies.  It is useful for accessing web sites that require small pieces of data
– <em class="dfn">cookies</em> – to be set on the client machine by an HTTP response from a
web server, and then returned to the server in later HTTP requests.</p>
<p>Both the regular Netscape cookie protocol and the protocol defined by
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2965.html"><strong>RFC 2965</strong></a> are handled.  RFC 2965 handling is switched off by default.
<span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> cookies are parsed as Netscape cookies and subsequently treated
either as Netscape or RFC 2965 cookies according to the ‘policy’ in effect.
Note that the great majority of cookies on the Internet are Netscape cookies.
<a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> attempts to follow the de-facto Netscape cookie protocol (which
differs substantially from that set out in the original Netscape specification),
including taking note of the <code class="docutils literal notranslate"><span class="pre">max-age</span></code> and <code class="docutils literal notranslate"><span class="pre">port</span></code> cookie-attributes
introduced with RFC 2965.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The various named parameters found in <em class="mailheader">Set-Cookie</em> and
<em class="mailheader">Set-Cookie2</em> headers (eg. <code class="docutils literal notranslate"><span class="pre">domain</span></code> and <code class="docutils literal notranslate"><span class="pre">expires</span></code>) are
conventionally referred to as <em class="dfn">attributes</em>.  To distinguish them from
Python attributes, the documentation for this module uses the term
<em class="dfn">cookie-attribute</em> instead.</p>
</div>
<p>The module defines the following exception:</p>
<dl class="exception">
<dt id="cookielib.LoadError">
<em class="property">exception </em><code class="descclassname">cookielib.</code><code class="descname">LoadError</code><a class="headerlink" href="#cookielib.LoadError" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of <a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> raise this exception on failure to load
cookies from a file.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For backwards-compatibility with Python 2.4 (which raised an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>),
<a class="reference internal" href="#cookielib.LoadError" title="cookielib.LoadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LoadError</span></code></a> is a subclass of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</div>
</dd></dl>

<p>The following classes are provided:</p>
<dl class="class">
<dt id="cookielib.CookieJar">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">CookieJar</code><span class="sig-paren">(</span><em>policy=None</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar" title="Permalink to this definition">¶</a></dt>
<dd><p><em>policy</em> is an object implementing the <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> interface.</p>
<p>The <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> class stores HTTP cookies.  It extracts cookies from HTTP
requests, and returns them in HTTP responses. <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> instances
automatically expire contained cookies when necessary.  Subclasses are also
responsible for storing and retrieving cookies from a file or database.</p>
</dd></dl>

<dl class="class">
<dt id="cookielib.FileCookieJar">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">FileCookieJar</code><span class="sig-paren">(</span><em>filename</em>, <em>delayload=None</em>, <em>policy=None</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.FileCookieJar" title="Permalink to this definition">¶</a></dt>
<dd><p><em>policy</em> is an object implementing the <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> interface.  For the
other arguments, see the documentation for the corresponding attributes.</p>
<p>A <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> which can load cookies from, and perhaps save cookies to, a
file on disk.  Cookies are <strong>NOT</strong> loaded from the named file until either the
<a class="reference internal" href="#cookielib.FileCookieJar.load" title="cookielib.FileCookieJar.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> or <a class="reference internal" href="#cookielib.FileCookieJar.revert" title="cookielib.FileCookieJar.revert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">revert()</span></code></a> method is called.  Subclasses of this class are
documented in section <a class="reference internal" href="#file-cookie-jar-classes"><span class="std std-ref">FileCookieJar subclasses and co-operation with web browsers</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="cookielib.CookiePolicy">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">CookiePolicy</code><a class="headerlink" href="#cookielib.CookiePolicy" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is responsible for deciding whether each cookie should be accepted
from / returned to the server.</p>
</dd></dl>

<dl class="class">
<dt id="cookielib.DefaultCookiePolicy">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">DefaultCookiePolicy</code><span class="sig-paren">(</span><em>blocked_domains=None</em>, <em>allowed_domains=None</em>, <em>netscape=True</em>, <em>rfc2965=False</em>, <em>rfc2109_as_netscape=None</em>, <em>hide_cookie2=False</em>, <em>strict_domain=False</em>, <em>strict_rfc2965_unverifiable=True</em>, <em>strict_ns_unverifiable=False</em>, <em>strict_ns_domain=DefaultCookiePolicy.DomainLiberal</em>, <em>strict_ns_set_initial_dollar=False</em>, <em>strict_ns_set_path=False</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor arguments should be passed as keyword arguments only.
<em>blocked_domains</em> is a sequence of domain names that we never accept cookies
from, nor return cookies to. <em>allowed_domains</em> if not <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, this is a
sequence of the only domains for which we accept and return cookies.  For all
other arguments, see the documentation for <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> and
<a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> objects.</p>
<p><a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> implements the standard accept / reject rules for
Netscape and RFC 2965 cookies.  By default, RFC 2109 cookies (ie. cookies
received in a <em class="mailheader">Set-Cookie</em> header with a version cookie-attribute of
1) are treated according to the RFC 2965 rules.  However, if RFC 2965 handling
is turned off or <a class="reference internal" href="#cookielib.DefaultCookiePolicy.rfc2109_as_netscape" title="cookielib.DefaultCookiePolicy.rfc2109_as_netscape"><code class="xref py py-attr docutils literal notranslate"><span class="pre">rfc2109_as_netscape</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, RFC 2109 cookies are
‘downgraded’ by the <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> instance to Netscape cookies, by
setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">version</span></code> attribute of the <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> instance to 0.
<a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> also provides some parameters to allow some
fine-tuning of policy.</p>
</dd></dl>

<dl class="class">
<dt id="cookielib.Cookie">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">Cookie</code><a class="headerlink" href="#cookielib.Cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>This class represents Netscape, RFC 2109 and RFC 2965 cookies.  It is not
expected that users of <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> construct their own <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a>
instances.  Instead, if necessary, call <code class="xref py py-meth docutils literal notranslate"><span class="pre">make_cookies()</span></code> on a
<a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> instance.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt>Module <a class="reference internal" href="urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a></dt>
<dd>URL opening with automatic cookie handling.</dd>
<dt>Module <a class="reference internal" href="cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a></dt>
<dd>HTTP cookie classes, principally useful for server-side code.  The
<a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> and <a class="reference internal" href="cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> modules do not depend on each other.</dd>
<dt><a class="reference external" href="https://curl.haxx.se/rfc/cookie_spec.html">https://curl.haxx.se/rfc/cookie_spec.html</a></dt>
<dd>The specification of the original Netscape cookie protocol.  Though this is
still the dominant protocol, the ‘Netscape cookie protocol’ implemented by all
the major browsers (and <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a>) only bears a passing resemblance to
the one sketched out in <code class="docutils literal notranslate"><span class="pre">cookie_spec.html</span></code>.</dd>
<dt><span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a> - HTTP State Management Mechanism</dt>
<dd>Obsoleted by RFC 2965. Uses <em class="mailheader">Set-Cookie</em> with version=1.</dd>
<dt><span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2965.html"><strong>RFC 2965</strong></a> - HTTP State Management Mechanism</dt>
<dd>The Netscape protocol with the bugs fixed.  Uses <em class="mailheader">Set-Cookie2</em> in
place of <em class="mailheader">Set-Cookie</em>.  Not widely used.</dd>
<dt><a class="reference external" href="http://kristol.org/cookie/errata.html">http://kristol.org/cookie/errata.html</a></dt>
<dd>Unfinished errata to RFC 2965.</dd>
</dl>
<p class="last"><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2964.html"><strong>RFC 2964</strong></a> - Use of HTTP State Management</p>
</div>
<div class="section" id="cookiejar-and-filecookiejar-objects">
<span id="cookie-jar-objects"></span><h2>20.21.1. CookieJar and FileCookieJar Objects<a class="headerlink" href="#cookiejar-and-filecookiejar-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> objects support the <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> protocol for iterating over
contained <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> objects.</p>
<p><a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> has the following methods:</p>
<dl class="method">
<dt id="cookielib.CookieJar.add_cookie_header">
<code class="descclassname">CookieJar.</code><code class="descname">add_cookie_header</code><span class="sig-paren">(</span><em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.add_cookie_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Add correct <em class="mailheader">Cookie</em> header to <em>request</em>.</p>
<p>If policy allows (ie. the <code class="xref py py-attr docutils literal notranslate"><span class="pre">rfc2965</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">hide_cookie2</span></code> attributes of
the <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a>’s <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> instance are true and false
respectively), the <em class="mailheader">Cookie2</em> header is also added when appropriate.</p>
<p>The <em>request</em> object (usually a <a class="reference internal" href="urllib2.html#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">urllib2.Request</span></code></a> instance) must support
the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_full_url()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_host()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_type()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">unverifiable()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_origin_req_host()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">has_header()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_header()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">header_items()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_unredirected_header()</span></code>,as
documented by <a class="reference internal" href="urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.extract_cookies">
<code class="descclassname">CookieJar.</code><code class="descname">extract_cookies</code><span class="sig-paren">(</span><em>response</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.extract_cookies" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract cookies from HTTP <em>response</em> and store them in the <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a>,
where allowed by policy.</p>
<p>The <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> will look for allowable <em class="mailheader">Set-Cookie</em> and
<em class="mailheader">Set-Cookie2</em> headers in the <em>response</em> argument, and store cookies
as appropriate (subject to the <a class="reference internal" href="#cookielib.CookiePolicy.set_ok" title="cookielib.CookiePolicy.set_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">CookiePolicy.set_ok()</span></code></a> method’s approval).</p>
<p>The <em>response</em> object (usually the result of a call to <a class="reference internal" href="urllib2.html#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">urllib2.urlopen()</span></code></a>,
or similar) should support an <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> method, which returns an object with
a <code class="xref py py-meth docutils literal notranslate"><span class="pre">getallmatchingheaders()</span></code> method (usually a <a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a>
instance).</p>
<p>The <em>request</em> object (usually a <a class="reference internal" href="urllib2.html#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">urllib2.Request</span></code></a> instance) must support
the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_full_url()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_host()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">unverifiable()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_origin_req_host()</span></code>, as documented by <a class="reference internal" href="urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a>.  The request is
used to set default values for cookie-attributes as well as for checking that
the cookie is allowed to be set.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.set_policy">
<code class="descclassname">CookieJar.</code><code class="descname">set_policy</code><span class="sig-paren">(</span><em>policy</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.set_policy" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> instance to be used.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.make_cookies">
<code class="descclassname">CookieJar.</code><code class="descname">make_cookies</code><span class="sig-paren">(</span><em>response</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.make_cookies" title="Permalink to this definition">¶</a></dt>
<dd><p>Return sequence of <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> objects extracted from <em>response</em> object.</p>
<p>See the documentation for <a class="reference internal" href="#cookielib.CookieJar.extract_cookies" title="cookielib.CookieJar.extract_cookies"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extract_cookies()</span></code></a> for the interfaces required of
the <em>response</em> and <em>request</em> arguments.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.set_cookie_if_ok">
<code class="descclassname">CookieJar.</code><code class="descname">set_cookie_if_ok</code><span class="sig-paren">(</span><em>cookie</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.set_cookie_if_ok" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> if policy says it’s OK to do so.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.set_cookie">
<code class="descclassname">CookieJar.</code><code class="descname">set_cookie</code><span class="sig-paren">(</span><em>cookie</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.set_cookie" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a>, without checking with policy to see whether or not it
should be set.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.clear">
<code class="descclassname">CookieJar.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="optional">[</span><em>domain</em><span class="optional">[</span>, <em>path</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear some cookies.</p>
<p>If invoked without arguments, clear all cookies.  If given a single argument,
only cookies belonging to that <em>domain</em> will be removed. If given two arguments,
cookies belonging to the specified <em>domain</em> and URL <em>path</em> are removed.  If
given three arguments, then the cookie with the specified <em>domain</em>, <em>path</em> and
<em>name</em> is removed.</p>
<p>Raises <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if no matching cookie exists.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookieJar.clear_session_cookies">
<code class="descclassname">CookieJar.</code><code class="descname">clear_session_cookies</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookieJar.clear_session_cookies" title="Permalink to this definition">¶</a></dt>
<dd><p>Discard all session cookies.</p>
<p>Discards all contained cookies that have a true <code class="xref py py-attr docutils literal notranslate"><span class="pre">discard</span></code> attribute
(usually because they had either no <code class="docutils literal notranslate"><span class="pre">max-age</span></code> or <code class="docutils literal notranslate"><span class="pre">expires</span></code> cookie-attribute,
or an explicit <code class="docutils literal notranslate"><span class="pre">discard</span></code> cookie-attribute).  For interactive browsers, the end
of a session usually corresponds to closing the browser window.</p>
<p>Note that the <code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code> method won’t save session cookies anyway, unless you
ask otherwise by passing a true <em>ignore_discard</em> argument.</p>
</dd></dl>

<p><a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> implements the following additional methods:</p>
<dl class="method">
<dt id="cookielib.FileCookieJar.save">
<code class="descclassname">FileCookieJar.</code><code class="descname">save</code><span class="sig-paren">(</span><em>filename=None</em>, <em>ignore_discard=False</em>, <em>ignore_expires=False</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.FileCookieJar.save" title="Permalink to this definition">¶</a></dt>
<dd><p>Save cookies to a file.</p>
<p>This base class raises <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.  Subclasses may leave this
method unimplemented.</p>
<p><em>filename</em> is the name of file in which to save cookies.  If <em>filename</em> is not
specified, <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.filename</span></code> is used (whose default is the value passed to
the constructor, if any); if <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.filename</span></code> is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
<p><em>ignore_discard</em>: save even cookies set to be discarded. <em>ignore_expires</em>: save
even cookies that have expired</p>
<p>The file is overwritten if it already exists, thus wiping all the cookies it
contains.  Saved cookies can be restored later using the <a class="reference internal" href="#cookielib.FileCookieJar.load" title="cookielib.FileCookieJar.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> or
<a class="reference internal" href="#cookielib.FileCookieJar.revert" title="cookielib.FileCookieJar.revert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">revert()</span></code></a> methods.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.FileCookieJar.load">
<code class="descclassname">FileCookieJar.</code><code class="descname">load</code><span class="sig-paren">(</span><em>filename=None</em>, <em>ignore_discard=False</em>, <em>ignore_expires=False</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.FileCookieJar.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Load cookies from a file.</p>
<p>Old cookies are kept unless overwritten by newly loaded ones.</p>
<p>Arguments are as for <a class="reference internal" href="#cookielib.FileCookieJar.save" title="cookielib.FileCookieJar.save"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code></a>.</p>
<p>The named file must be in the format understood by the class, or
<a class="reference internal" href="#cookielib.LoadError" title="cookielib.LoadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LoadError</span></code></a> will be raised.  Also, <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> may be raised, for
example if the file does not exist.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For backwards-compatibility with Python 2.4 (which raised an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>),
<a class="reference internal" href="#cookielib.LoadError" title="cookielib.LoadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LoadError</span></code></a> is a subclass of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="cookielib.FileCookieJar.revert">
<code class="descclassname">FileCookieJar.</code><code class="descname">revert</code><span class="sig-paren">(</span><em>filename=None</em>, <em>ignore_discard=False</em>, <em>ignore_expires=False</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.FileCookieJar.revert" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear all cookies and reload cookies from a saved file.</p>
<p><a class="reference internal" href="#cookielib.FileCookieJar.revert" title="cookielib.FileCookieJar.revert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">revert()</span></code></a> can raise the same exceptions as <a class="reference internal" href="#cookielib.FileCookieJar.load" title="cookielib.FileCookieJar.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a>. If there is a
failure, the object’s state will not be altered.</p>
</dd></dl>

<p><a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> instances have the following public attributes:</p>
<dl class="attribute">
<dt id="cookielib.FileCookieJar.filename">
<code class="descclassname">FileCookieJar.</code><code class="descname">filename</code><a class="headerlink" href="#cookielib.FileCookieJar.filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Filename of default file in which to keep cookies.  This attribute may be
assigned to.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.FileCookieJar.delayload">
<code class="descclassname">FileCookieJar.</code><code class="descname">delayload</code><a class="headerlink" href="#cookielib.FileCookieJar.delayload" title="Permalink to this definition">¶</a></dt>
<dd><p>If true, load cookies lazily from disk.  This attribute should not be assigned
to.  This is only a hint, since this only affects performance, not behaviour
(unless the cookies on disk are changing). A <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> object may
ignore it.  None of the <a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> classes included in the standard
library lazily loads cookies.</p>
</dd></dl>

</div>
<div class="section" id="filecookiejar-subclasses-and-co-operation-with-web-browsers">
<span id="file-cookie-jar-classes"></span><h2>20.21.2. FileCookieJar subclasses and co-operation with web browsers<a class="headerlink" href="#filecookiejar-subclasses-and-co-operation-with-web-browsers" title="Permalink to this headline">¶</a></h2>
<p>The following <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> subclasses are provided for reading and
writing.</p>
<dl class="class">
<dt id="cookielib.MozillaCookieJar">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">MozillaCookieJar</code><span class="sig-paren">(</span><em>filename</em>, <em>delayload=None</em>, <em>policy=None</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.MozillaCookieJar" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> that can load from and save cookies to disk in the
Mozilla <code class="docutils literal notranslate"><span class="pre">cookies.txt</span></code> file format (which is also used by the Lynx and Netscape
browsers).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Version 3 of the Firefox web browser no longer writes cookies in the
<code class="docutils literal notranslate"><span class="pre">cookies.txt</span></code> file format.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This loses information about RFC 2965 cookies, and also about newer or
non-standard cookie-attributes such as <code class="docutils literal notranslate"><span class="pre">port</span></code>.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Back up your cookies before saving if you have cookies whose loss / corruption
would be inconvenient (there are some subtleties which may lead to slight
changes in the file over a load / save round-trip).</p>
</div>
<p>Also note that cookies saved while Mozilla is running will get clobbered by
Mozilla.</p>
</dd></dl>

<dl class="class">
<dt id="cookielib.LWPCookieJar">
<em class="property">class </em><code class="descclassname">cookielib.</code><code class="descname">LWPCookieJar</code><span class="sig-paren">(</span><em>filename</em>, <em>delayload=None</em>, <em>policy=None</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.LWPCookieJar" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#cookielib.FileCookieJar" title="cookielib.FileCookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileCookieJar</span></code></a> that can load from and save cookies to disk in format
compatible with the libwww-perl library’s <code class="docutils literal notranslate"><span class="pre">Set-Cookie3</span></code> file format.  This is
convenient if you want to store cookies in a human-readable file.</p>
</dd></dl>

</div>
<div class="section" id="cookiepolicy-objects">
<span id="cookie-policy-objects"></span><h2>20.21.3. CookiePolicy Objects<a class="headerlink" href="#cookiepolicy-objects" title="Permalink to this headline">¶</a></h2>
<p>Objects implementing the <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> interface have the following
methods:</p>
<dl class="method">
<dt id="cookielib.CookiePolicy.set_ok">
<code class="descclassname">CookiePolicy.</code><code class="descname">set_ok</code><span class="sig-paren">(</span><em>cookie</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookiePolicy.set_ok" title="Permalink to this definition">¶</a></dt>
<dd><p>Return boolean value indicating whether cookie should be accepted from server.</p>
<p><em>cookie</em> is a <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">cookielib.Cookie</span></code></a> instance.  <em>request</em> is an object
implementing the interface defined by the documentation for
<a class="reference internal" href="#cookielib.CookieJar.extract_cookies" title="cookielib.CookieJar.extract_cookies"><code class="xref py py-meth docutils literal notranslate"><span class="pre">CookieJar.extract_cookies()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookiePolicy.return_ok">
<code class="descclassname">CookiePolicy.</code><code class="descname">return_ok</code><span class="sig-paren">(</span><em>cookie</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookiePolicy.return_ok" title="Permalink to this definition">¶</a></dt>
<dd><p>Return boolean value indicating whether cookie should be returned to server.</p>
<p><em>cookie</em> is a <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">cookielib.Cookie</span></code></a> instance.  <em>request</em> is an object
implementing the interface defined by the documentation for
<a class="reference internal" href="#cookielib.CookieJar.add_cookie_header" title="cookielib.CookieJar.add_cookie_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">CookieJar.add_cookie_header()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookiePolicy.domain_return_ok">
<code class="descclassname">CookiePolicy.</code><code class="descname">domain_return_ok</code><span class="sig-paren">(</span><em>domain</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookiePolicy.domain_return_ok" title="Permalink to this definition">¶</a></dt>
<dd><p>Return false if cookies should not be returned, given cookie domain.</p>
<p>This method is an optimization.  It removes the need for checking every cookie
with a particular domain (which might involve reading many files).  Returning
true from <a class="reference internal" href="#cookielib.CookiePolicy.domain_return_ok" title="cookielib.CookiePolicy.domain_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">domain_return_ok()</span></code></a> and <a class="reference internal" href="#cookielib.CookiePolicy.path_return_ok" title="cookielib.CookiePolicy.path_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path_return_ok()</span></code></a> leaves all the
work to <a class="reference internal" href="#cookielib.CookiePolicy.return_ok" title="cookielib.CookiePolicy.return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">return_ok()</span></code></a>.</p>
<p>If <a class="reference internal" href="#cookielib.CookiePolicy.domain_return_ok" title="cookielib.CookiePolicy.domain_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">domain_return_ok()</span></code></a> returns true for the cookie domain,
<a class="reference internal" href="#cookielib.CookiePolicy.path_return_ok" title="cookielib.CookiePolicy.path_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path_return_ok()</span></code></a> is called for the cookie path.  Otherwise,
<a class="reference internal" href="#cookielib.CookiePolicy.path_return_ok" title="cookielib.CookiePolicy.path_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path_return_ok()</span></code></a> and <a class="reference internal" href="#cookielib.CookiePolicy.return_ok" title="cookielib.CookiePolicy.return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">return_ok()</span></code></a> are never called for that cookie
domain.  If <a class="reference internal" href="#cookielib.CookiePolicy.path_return_ok" title="cookielib.CookiePolicy.path_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path_return_ok()</span></code></a> returns true, <a class="reference internal" href="#cookielib.CookiePolicy.return_ok" title="cookielib.CookiePolicy.return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">return_ok()</span></code></a> is called
with the <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> object itself for a full check.  Otherwise,
<a class="reference internal" href="#cookielib.CookiePolicy.return_ok" title="cookielib.CookiePolicy.return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">return_ok()</span></code></a> is never called for that cookie path.</p>
<p>Note that <a class="reference internal" href="#cookielib.CookiePolicy.domain_return_ok" title="cookielib.CookiePolicy.domain_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">domain_return_ok()</span></code></a> is called for every <em>cookie</em> domain, not just
for the <em>request</em> domain.  For example, the function might be called with both
<code class="docutils literal notranslate"><span class="pre">&quot;.example.com&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;www.example.com&quot;</span></code> if the request domain is
<code class="docutils literal notranslate"><span class="pre">&quot;www.example.com&quot;</span></code>.  The same goes for <a class="reference internal" href="#cookielib.CookiePolicy.path_return_ok" title="cookielib.CookiePolicy.path_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">path_return_ok()</span></code></a>.</p>
<p>The <em>request</em> argument is as documented for <a class="reference internal" href="#cookielib.CookiePolicy.return_ok" title="cookielib.CookiePolicy.return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">return_ok()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.CookiePolicy.path_return_ok">
<code class="descclassname">CookiePolicy.</code><code class="descname">path_return_ok</code><span class="sig-paren">(</span><em>path</em>, <em>request</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.CookiePolicy.path_return_ok" title="Permalink to this definition">¶</a></dt>
<dd><p>Return false if cookies should not be returned, given cookie path.</p>
<p>See the documentation for <a class="reference internal" href="#cookielib.CookiePolicy.domain_return_ok" title="cookielib.CookiePolicy.domain_return_ok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">domain_return_ok()</span></code></a>.</p>
</dd></dl>

<p>In addition to implementing the methods above, implementations of the
<a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> interface must also supply the following attributes,
indicating which protocols should be used, and how.  All of these attributes may
be assigned to.</p>
<dl class="attribute">
<dt id="cookielib.CookiePolicy.netscape">
<code class="descclassname">CookiePolicy.</code><code class="descname">netscape</code><a class="headerlink" href="#cookielib.CookiePolicy.netscape" title="Permalink to this definition">¶</a></dt>
<dd><p>Implement Netscape protocol.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.CookiePolicy.rfc2965">
<code class="descclassname">CookiePolicy.</code><code class="descname">rfc2965</code><a class="headerlink" href="#cookielib.CookiePolicy.rfc2965" title="Permalink to this definition">¶</a></dt>
<dd><p>Implement RFC 2965 protocol.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.CookiePolicy.hide_cookie2">
<code class="descclassname">CookiePolicy.</code><code class="descname">hide_cookie2</code><a class="headerlink" href="#cookielib.CookiePolicy.hide_cookie2" title="Permalink to this definition">¶</a></dt>
<dd><p>Don’t add <em class="mailheader">Cookie2</em> header to requests (the presence of this header
indicates to the server that we understand RFC 2965 cookies).</p>
</dd></dl>

<p>The most useful way to define a <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> class is by subclassing
from <a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> and overriding some or all of the methods
above.  <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> itself may be used as a ‘null policy’ to allow
setting and receiving any and all cookies (this is unlikely to be useful).</p>
</div>
<div class="section" id="defaultcookiepolicy-objects">
<span id="default-cookie-policy-objects"></span><h2>20.21.4. DefaultCookiePolicy Objects<a class="headerlink" href="#defaultcookiepolicy-objects" title="Permalink to this headline">¶</a></h2>
<p>Implements the standard rules for accepting and returning cookies.</p>
<p>Both RFC 2965 and Netscape cookies are covered.  RFC 2965 handling is switched
off by default.</p>
<p>The easiest way to provide your own policy is to override this class and call
its methods in your overridden implementations before adding your own additional
checks:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cookielib</span>
<span class="k">class</span> <span class="nc">MyCookiePolicy</span><span class="p">(</span><span class="n">cookielib</span><span class="o">.</span><span class="n">DefaultCookiePolicy</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">set_ok</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">cookie</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">cookielib</span><span class="o">.</span><span class="n">DefaultCookiePolicy</span><span class="o">.</span><span class="n">set_ok</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">cookie</span><span class="p">,</span> <span class="n">request</span><span class="p">):</span>
            <span class="k">return</span> <span class="kc">False</span>
        <span class="k">if</span> <span class="n">i_dont_want_to_store_this_cookie</span><span class="p">(</span><span class="n">cookie</span><span class="p">):</span>
            <span class="k">return</span> <span class="kc">False</span>
        <span class="k">return</span> <span class="kc">True</span>
</pre></div>
</div>
<p>In addition to the features required to implement the <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a>
interface, this class allows you to block and allow domains from setting and
receiving cookies.  There are also some strictness switches that allow you to
tighten up the rather loose Netscape protocol rules a little bit (at the cost of
blocking some benign cookies).</p>
<p>A domain blacklist and whitelist is provided (both off by default). Only domains
not in the blacklist and present in the whitelist (if the whitelist is active)
participate in cookie setting and returning.  Use the <em>blocked_domains</em>
constructor argument, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">blocked_domains()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_blocked_domains()</span></code> methods (and the corresponding argument and methods
for <em>allowed_domains</em>).  If you set a whitelist, you can turn it off again by
setting it to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>Domains in block or allow lists that do not start with a dot must equal the
cookie domain to be matched.  For example, <code class="docutils literal notranslate"><span class="pre">&quot;example.com&quot;</span></code> matches a blacklist
entry of <code class="docutils literal notranslate"><span class="pre">&quot;example.com&quot;</span></code>, but <code class="docutils literal notranslate"><span class="pre">&quot;www.example.com&quot;</span></code> does not.  Domains that do
start with a dot are matched by more specific domains too. For example, both
<code class="docutils literal notranslate"><span class="pre">&quot;www.example.com&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;www.coyote.example.com&quot;</span></code> match <code class="docutils literal notranslate"><span class="pre">&quot;.example.com&quot;</span></code>
(but <code class="docutils literal notranslate"><span class="pre">&quot;example.com&quot;</span></code> itself does not).  IP addresses are an exception, and
must match exactly.  For example, if blocked_domains contains <code class="docutils literal notranslate"><span class="pre">&quot;192.168.1.2&quot;</span></code>
and <code class="docutils literal notranslate"><span class="pre">&quot;.168.1.2&quot;</span></code>, 192.168.1.2 is blocked, but 193.168.1.2 is not.</p>
<p><a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> implements the following additional methods:</p>
<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.blocked_domains">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">blocked_domains</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.blocked_domains" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sequence of blocked domains (as a tuple).</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.set_blocked_domains">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">set_blocked_domains</code><span class="sig-paren">(</span><em>blocked_domains</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.set_blocked_domains" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the sequence of blocked domains.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.is_blocked">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">is_blocked</code><span class="sig-paren">(</span><em>domain</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.is_blocked" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether <em>domain</em> is on the blacklist for setting or receiving cookies.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.allowed_domains">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">allowed_domains</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.allowed_domains" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, or the sequence of allowed domains (as a tuple).</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.set_allowed_domains">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">set_allowed_domains</code><span class="sig-paren">(</span><em>allowed_domains</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.set_allowed_domains" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the sequence of allowed domains, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.DefaultCookiePolicy.is_not_allowed">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">is_not_allowed</code><span class="sig-paren">(</span><em>domain</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.DefaultCookiePolicy.is_not_allowed" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether <em>domain</em> is not on the whitelist for setting or receiving
cookies.</p>
</dd></dl>

<p><a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a> instances have the following attributes, which are
all initialised from the constructor arguments of the same name, and which may
all be assigned to.</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.rfc2109_as_netscape">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">rfc2109_as_netscape</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.rfc2109_as_netscape" title="Permalink to this definition">¶</a></dt>
<dd><p>If true, request that the <a class="reference internal" href="#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookieJar</span></code></a> instance downgrade RFC 2109 cookies
(ie. cookies received in a <em class="mailheader">Set-Cookie</em> header with a version
cookie-attribute of 1) to Netscape cookies by setting the version attribute of
the <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> instance to 0.  The default value is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, in which
case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned
off.  Therefore, RFC 2109 cookies are downgraded by default.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>General strictness switches:</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_domain">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_domain</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_domain" title="Permalink to this definition">¶</a></dt>
<dd><p>Don’t allow sites to set two-component domains with country-code top-level
domains like <code class="docutils literal notranslate"><span class="pre">.co.uk</span></code>, <code class="docutils literal notranslate"><span class="pre">.gov.uk</span></code>, <code class="docutils literal notranslate"><span class="pre">.co.nz</span></code>.etc.  This is far from perfect
and isn’t guaranteed to work!</p>
</dd></dl>

<p>RFC 2965 protocol strictness switches:</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_rfc2965_unverifiable">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_rfc2965_unverifiable</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_rfc2965_unverifiable" title="Permalink to this definition">¶</a></dt>
<dd><p>Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable
transaction is one resulting from a redirect or a request for an image hosted on
another site).  If this is false, cookies are <em>never</em> blocked on the basis of
verifiability</p>
</dd></dl>

<p>Netscape protocol strictness switches:</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_ns_unverifiable">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_ns_unverifiable</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_ns_unverifiable" title="Permalink to this definition">¶</a></dt>
<dd><p>Apply RFC 2965 rules on unverifiable transactions even to Netscape cookies.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_ns_domain">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_ns_domain</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_ns_domain" title="Permalink to this definition">¶</a></dt>
<dd><p>Flags indicating how strict to be with domain-matching rules for Netscape
cookies.  See below for acceptable values.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_ns_set_initial_dollar">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_ns_set_initial_dollar</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_ns_set_initial_dollar" title="Permalink to this definition">¶</a></dt>
<dd><p>Ignore cookies in Set-Cookie: headers that have names starting with <code class="docutils literal notranslate"><span class="pre">'$'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.strict_ns_set_path">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">strict_ns_set_path</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.strict_ns_set_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Don’t allow setting cookies whose path doesn’t path-match request URI.</p>
</dd></dl>

<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">strict_ns_domain</span></code> is a collection of flags.  Its value is constructed by
or-ing together (for example, <code class="docutils literal notranslate"><span class="pre">DomainStrictNoDots|DomainStrictNonDomain</span></code> means
both flags are set).</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.DomainStrictNoDots">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">DomainStrictNoDots</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.DomainStrictNoDots" title="Permalink to this definition">¶</a></dt>
<dd><p>When setting cookies, the ‘host prefix’ must not contain a dot (eg.
<code class="docutils literal notranslate"><span class="pre">www.foo.bar.com</span></code> can’t set a cookie for <code class="docutils literal notranslate"><span class="pre">.bar.com</span></code>, because <code class="docutils literal notranslate"><span class="pre">www.foo</span></code>
contains a dot).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.DomainStrictNonDomain">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">DomainStrictNonDomain</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.DomainStrictNonDomain" title="Permalink to this definition">¶</a></dt>
<dd><p>Cookies that did not explicitly specify a <code class="docutils literal notranslate"><span class="pre">domain</span></code> cookie-attribute can only
be returned to a domain equal to the domain that set the cookie (eg.
<code class="docutils literal notranslate"><span class="pre">spam.example.com</span></code> won’t be returned cookies from <code class="docutils literal notranslate"><span class="pre">example.com</span></code> that had no
<code class="docutils literal notranslate"><span class="pre">domain</span></code> cookie-attribute).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.DomainRFC2965Match">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">DomainRFC2965Match</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.DomainRFC2965Match" title="Permalink to this definition">¶</a></dt>
<dd><p>When setting cookies, require a full RFC 2965 domain-match.</p>
</dd></dl>

<p>The following attributes are provided for convenience, and are the most useful
combinations of the above flags:</p>
<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.DomainLiberal">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">DomainLiberal</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.DomainLiberal" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched
off).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.DefaultCookiePolicy.DomainStrict">
<code class="descclassname">DefaultCookiePolicy.</code><code class="descname">DomainStrict</code><a class="headerlink" href="#cookielib.DefaultCookiePolicy.DomainStrict" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">DomainStrictNoDots|DomainStrictNonDomain</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="cookie-objects">
<span id="cookielib-cookie-objects"></span><h2>20.21.5. Cookie Objects<a class="headerlink" href="#cookie-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> instances have Python attributes roughly corresponding to the
standard cookie-attributes specified in the various cookie standards.  The
correspondence is not one-to-one, because there are complicated rules for
assigning default values, because the <code class="docutils literal notranslate"><span class="pre">max-age</span></code> and <code class="docutils literal notranslate"><span class="pre">expires</span></code>
cookie-attributes contain equivalent information, and because RFC 2109 cookies
may be ‘downgraded’ by <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> from version 1 to version 0 (Netscape)
cookies.</p>
<p>Assignment to these attributes should not be necessary other than in rare
circumstances in a <a class="reference internal" href="#cookielib.CookiePolicy" title="cookielib.CookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">CookiePolicy</span></code></a> method.  The class does not enforce
internal consistency, so you should know what you’re doing if you do that.</p>
<dl class="attribute">
<dt id="cookielib.Cookie.version">
<code class="descclassname">Cookie.</code><code class="descname">version</code><a class="headerlink" href="#cookielib.Cookie.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Integer or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.  Netscape cookies have <a class="reference internal" href="#cookielib.Cookie.version" title="cookielib.Cookie.version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">version</span></code></a> 0. RFC 2965 and
RFC 2109 cookies have a <code class="docutils literal notranslate"><span class="pre">version</span></code> cookie-attribute of 1.  However, note that
<a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which
case <a class="reference internal" href="#cookielib.Cookie.version" title="cookielib.Cookie.version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">version</span></code></a> is 0.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.name">
<code class="descclassname">Cookie.</code><code class="descname">name</code><a class="headerlink" href="#cookielib.Cookie.name" title="Permalink to this definition">¶</a></dt>
<dd><p>Cookie name (a string).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.value">
<code class="descclassname">Cookie.</code><code class="descname">value</code><a class="headerlink" href="#cookielib.Cookie.value" title="Permalink to this definition">¶</a></dt>
<dd><p>Cookie value (a string), or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.port">
<code class="descclassname">Cookie.</code><code class="descname">port</code><a class="headerlink" href="#cookielib.Cookie.port" title="Permalink to this definition">¶</a></dt>
<dd><p>String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.path">
<code class="descclassname">Cookie.</code><code class="descname">path</code><a class="headerlink" href="#cookielib.Cookie.path" title="Permalink to this definition">¶</a></dt>
<dd><p>Cookie path (a string, eg. <code class="docutils literal notranslate"><span class="pre">'/acme/rocket_launchers'</span></code>).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.secure">
<code class="descclassname">Cookie.</code><code class="descname">secure</code><a class="headerlink" href="#cookielib.Cookie.secure" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if cookie should only be returned over a secure connection.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.expires">
<code class="descclassname">Cookie.</code><code class="descname">expires</code><a class="headerlink" href="#cookielib.Cookie.expires" title="Permalink to this definition">¶</a></dt>
<dd><p>Integer expiry date in seconds since epoch, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.  See also the
<a class="reference internal" href="#cookielib.Cookie.is_expired" title="cookielib.Cookie.is_expired"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_expired()</span></code></a> method.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.discard">
<code class="descclassname">Cookie.</code><code class="descname">discard</code><a class="headerlink" href="#cookielib.Cookie.discard" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if this is a session cookie.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.comment">
<code class="descclassname">Cookie.</code><code class="descname">comment</code><a class="headerlink" href="#cookielib.Cookie.comment" title="Permalink to this definition">¶</a></dt>
<dd><p>String comment from the server explaining the function of this cookie, or
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.comment_url">
<code class="descclassname">Cookie.</code><code class="descname">comment_url</code><a class="headerlink" href="#cookielib.Cookie.comment_url" title="Permalink to this definition">¶</a></dt>
<dd><p>URL linking to a comment from the server explaining the function of this cookie,
or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.rfc2109">
<code class="descclassname">Cookie.</code><code class="descname">rfc2109</code><a class="headerlink" href="#cookielib.Cookie.rfc2109" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if this cookie was received as an RFC 2109 cookie (ie. the cookie
arrived in a <em class="mailheader">Set-Cookie</em> header, and the value of the Version
cookie-attribute in that header was 1).  This attribute is provided because
<a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in
which case <a class="reference internal" href="#cookielib.Cookie.version" title="cookielib.Cookie.version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">version</span></code></a> is 0.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.port_specified">
<code class="descclassname">Cookie.</code><code class="descname">port_specified</code><a class="headerlink" href="#cookielib.Cookie.port_specified" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if a port or set of ports was explicitly specified by the server (in the
<em class="mailheader">Set-Cookie</em> / <em class="mailheader">Set-Cookie2</em> header).</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.domain_specified">
<code class="descclassname">Cookie.</code><code class="descname">domain_specified</code><a class="headerlink" href="#cookielib.Cookie.domain_specified" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if a domain was explicitly specified by the server.</p>
</dd></dl>

<dl class="attribute">
<dt id="cookielib.Cookie.domain_initial_dot">
<code class="descclassname">Cookie.</code><code class="descname">domain_initial_dot</code><a class="headerlink" href="#cookielib.Cookie.domain_initial_dot" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if the domain explicitly specified by the server began with a dot
(<code class="docutils literal notranslate"><span class="pre">'.'</span></code>).</p>
</dd></dl>

<p>Cookies may have additional non-standard cookie-attributes.  These may be
accessed using the following methods:</p>
<dl class="method">
<dt id="cookielib.Cookie.has_nonstandard_attr">
<code class="descclassname">Cookie.</code><code class="descname">has_nonstandard_attr</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.Cookie.has_nonstandard_attr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if cookie has the named cookie-attribute.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.Cookie.get_nonstandard_attr">
<code class="descclassname">Cookie.</code><code class="descname">get_nonstandard_attr</code><span class="sig-paren">(</span><em>name</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.Cookie.get_nonstandard_attr" title="Permalink to this definition">¶</a></dt>
<dd><p>If cookie has the named cookie-attribute, return its value. Otherwise, return
<em>default</em>.</p>
</dd></dl>

<dl class="method">
<dt id="cookielib.Cookie.set_nonstandard_attr">
<code class="descclassname">Cookie.</code><code class="descname">set_nonstandard_attr</code><span class="sig-paren">(</span><em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.Cookie.set_nonstandard_attr" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of the named cookie-attribute.</p>
</dd></dl>

<p>The <a class="reference internal" href="#cookielib.Cookie" title="cookielib.Cookie"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cookie</span></code></a> class also defines the following method:</p>
<dl class="method">
<dt id="cookielib.Cookie.is_expired">
<code class="descclassname">Cookie.</code><code class="descname">is_expired</code><span class="sig-paren">(</span><span class="optional">[</span><em>now=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cookielib.Cookie.is_expired" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if cookie has passed the time at which the server requested it should
expire.  If <em>now</em> is given (in seconds since the epoch), return whether the
cookie has expired at the specified time.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="cookielib-examples"></span><h2>20.21.6. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>The first example shows the most common usage of <a class="reference internal" href="#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cookielib</span><span class="o">,</span> <span class="nn">urllib2</span>
<span class="n">cj</span> <span class="o">=</span> <span class="n">cookielib</span><span class="o">.</span><span class="n">CookieJar</span><span class="p">()</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPCookieProcessor</span><span class="p">(</span><span class="n">cj</span><span class="p">))</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;http://example.com/&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
cookies (assumes Unix/Netscape convention for location of the cookies file):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">cookielib</span><span class="o">,</span> <span class="nn">urllib2</span>
<span class="n">cj</span> <span class="o">=</span> <span class="n">cookielib</span><span class="o">.</span><span class="n">MozillaCookieJar</span><span class="p">()</span>
<span class="n">cj</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s2">&quot;~&quot;</span><span class="p">),</span> <span class="s2">&quot;.netscape&quot;</span><span class="p">,</span> <span class="s2">&quot;cookies.txt&quot;</span><span class="p">))</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPCookieProcessor</span><span class="p">(</span><span class="n">cj</span><span class="p">))</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;http://example.com/&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The next example illustrates the use of <a class="reference internal" href="#cookielib.DefaultCookiePolicy" title="cookielib.DefaultCookiePolicy"><code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultCookiePolicy</span></code></a>. Turn on
RFC 2965 cookies, be more strict about domains when setting and returning
Netscape cookies, and block some domains from setting cookies or having them
returned:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="kn">from</span> <span class="nn">cookielib</span> <span class="k">import</span> <span class="n">CookieJar</span><span class="p">,</span> <span class="n">DefaultCookiePolicy</span>
<span class="n">policy</span> <span class="o">=</span> <span class="n">DefaultCookiePolicy</span><span class="p">(</span>
    <span class="n">rfc2965</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">strict_ns_domain</span><span class="o">=</span><span class="n">DefaultCookiePolicy</span><span class="o">.</span><span class="n">DomainStrict</span><span class="p">,</span>
    <span class="n">blocked_domains</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;ads.net&quot;</span><span class="p">,</span> <span class="s2">&quot;.ads.net&quot;</span><span class="p">])</span>
<span class="n">cj</span> <span class="o">=</span> <span class="n">CookieJar</span><span class="p">(</span><span class="n">policy</span><span class="p">)</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPCookieProcessor</span><span class="p">(</span><span class="n">cj</span><span class="p">))</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;http://example.com/&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a><ul>
<li><a class="reference internal" href="#cookiejar-and-filecookiejar-objects">20.21.1. CookieJar and FileCookieJar Objects</a></li>
<li><a class="reference internal" href="#filecookiejar-subclasses-and-co-operation-with-web-browsers">20.21.2. FileCookieJar subclasses and co-operation with web browsers</a></li>
<li><a class="reference internal" href="#cookiepolicy-objects">20.21.3. CookiePolicy Objects</a></li>
<li><a class="reference internal" href="#defaultcookiepolicy-objects">20.21.4. DefaultCookiePolicy Objects</a></li>
<li><a class="reference internal" href="#cookie-objects">20.21.5. Cookie Objects</a></li>
<li><a class="reference internal" href="#examples">20.21.6. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cgihttpserver.html"
                        title="previous chapter">20.20. <code class="docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code> — CGI-capable HTTP request handler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cookie.html"
                        title="next chapter">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/cookielib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cookie.html" title="20.22. Cookie — HTTP state management"
             >next</a> |</li>
        <li class="right" >
          <a href="cgihttpserver.html" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P�2�2html/library/copy.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.17. copy — Shallow and deep copy operations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.18. pprint — Data pretty printer" href="pprint.html" />
    <link rel="prev" title="8.16. new — Creation of runtime internal objects" href="new.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/copy.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pprint.html" title="8.18. pprint — Data pretty printer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="new.html" title="8.16. new — Creation of runtime internal objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-copy">
<span id="copy-shallow-and-deep-copy-operations"></span><h1>8.17. <a class="reference internal" href="#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> — Shallow and deep copy operations<a class="headerlink" href="#module-copy" title="Permalink to this headline">¶</a></h1>
<p>Assignment statements in Python do not copy objects, they create bindings
between a target and an object. For collections that are mutable or contain
mutable items, a copy is sometimes needed so one can change one copy without
changing the other. This module provides generic shallow and deep copy
operations (explained below).</p>
<p>Interface summary:</p>
<dl class="function">
<dt id="copy.copy">
<code class="descclassname">copy.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#copy.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a shallow copy of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="copy.deepcopy">
<code class="descclassname">copy.</code><code class="descname">deepcopy</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#copy.deepcopy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a deep copy of <em>x</em>.</p>
</dd></dl>

<dl class="exception">
<dt id="copy.error">
<em class="property">exception </em><code class="descclassname">copy.</code><code class="descname">error</code><a class="headerlink" href="#copy.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised for module specific errors.</p>
</dd></dl>

<p>The difference between shallow and deep copying is only relevant for compound
objects (objects that contain other objects, like lists or class instances):</p>
<ul class="simple">
<li>A <em>shallow copy</em> constructs a new compound object and then (to the extent
possible) inserts <em>references</em> into it to the objects found in the original.</li>
<li>A <em>deep copy</em> constructs a new compound object and then, recursively, inserts
<em>copies</em> into it of the objects found in the original.</li>
</ul>
<p>Two problems often exist with deep copy operations that don’t exist with shallow
copy operations:</p>
<ul class="simple">
<li>Recursive objects (compound objects that, directly or indirectly, contain a
reference to themselves) may cause a recursive loop.</li>
<li>Because deep copy copies everything it may copy too much, such as data
which is intended to be shared between copies.</li>
</ul>
<p>The <a class="reference internal" href="#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">deepcopy()</span></code></a> function avoids these problems by:</p>
<ul class="simple">
<li>keeping a “memo” dictionary of objects already copied during the current
copying pass; and</li>
<li>letting user-defined classes override the copying operation or the set of
components copied.</li>
</ul>
<p>This module does not copy types like module, method, stack trace, stack frame,
file, socket, window, array, or any similar types.  It does “copy” functions and
classes (shallow and deeply), by returning the original object unchanged; this
is compatible with the way these are treated by the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module.</p>
<p>Shallow copies of dictionaries can be made using <a class="reference internal" href="stdtypes.html#dict.copy" title="dict.copy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.copy()</span></code></a>, and
of lists by assigning a slice of the entire list, for example,
<code class="docutils literal notranslate"><span class="pre">copied_list</span> <span class="pre">=</span> <span class="pre">original_list[:]</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added copying functions.</p>
</div>
<p id="index-0">Classes can use the same interfaces to control copying that they use to control
pickling.  See the description of module <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> for information on these
methods.  The <a class="reference internal" href="#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> module does not use the <a class="reference internal" href="copy_reg.html#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a> registration
module.</p>
<p id="index-1">In order for a class to define its own copy implementation, it can define
special methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">__copy__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__deepcopy__()</span></code>.  The former is called
to implement the shallow copy operation; no additional arguments are passed.
The latter is called to implement the deep copy operation; it is passed one
argument, the memo dictionary.  If the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__deepcopy__()</span></code> implementation needs
to make a deep copy of a component, it should call the <a class="reference internal" href="#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">deepcopy()</span></code></a> function
with the component as first argument and the memo dictionary as second argument.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a></dt>
<dd>Discussion of the special methods used to support object state retrieval and
restoration.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="new.html"
                        title="previous chapter">8.16. <code class="docutils literal notranslate"><span class="pre">new</span></code> — Creation of runtime internal objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pprint.html"
                        title="next chapter">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/copy.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pprint.html" title="8.18. pprint — Data pretty printer"
             >next</a> |</li>
        <li class="right" >
          <a href="new.html" title="8.16. new — Creation of runtime internal objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P�[c9c9html/library/copy_reg.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.3. copy_reg — Register pickle support functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.4. shelve — Python object persistence" href="shelve.html" />
    <link rel="prev" title="11.1. pickle — Python object serialization" href="pickle.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/copy_reg.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shelve.html" title="11.4. shelve — Python object persistence"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pickle.html" title="11.1. pickle — Python object serialization"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-copy_reg">
<span id="copy-reg-register-pickle-support-functions"></span><h1>11.3. <a class="reference internal" href="#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a> — Register <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> support functions<a class="headerlink" href="#module-copy_reg" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">copyreg</span></code> in Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p id="index-0">The <a class="reference internal" href="#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a> module offers a way to define functions used while pickling
specific objects.  The <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>, <a class="reference internal" href="pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>, and <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> modules
use those functions when pickling/copying those objects.  The module provides
configuration information about object constructors which are not classes.
Such constructors may be factory functions or class instances.</p>
<dl class="function">
<dt id="copy_reg.constructor">
<code class="descclassname">copy_reg.</code><code class="descname">constructor</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#copy_reg.constructor" title="Permalink to this definition">¶</a></dt>
<dd><p>Declares <em>object</em> to be a valid constructor.  If <em>object</em> is not callable (and
hence not valid as a constructor), raises <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="copy_reg.pickle">
<code class="descclassname">copy_reg.</code><code class="descname">pickle</code><span class="sig-paren">(</span><em>type</em>, <em>function</em><span class="optional">[</span>, <em>constructor</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#copy_reg.pickle" title="Permalink to this definition">¶</a></dt>
<dd><p>Declares that <em>function</em> should be used as a “reduction” function for objects of
type <em>type</em>; <em>type</em> must not be a “classic” class object.  (Classic classes are
handled differently; see the documentation for the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module for
details.)  <em>function</em> should return either a string or a tuple containing two or
three elements.</p>
<p>The optional <em>constructor</em> parameter, if provided, is a callable object which
can be used to reconstruct the object when called with the tuple of arguments
returned by <em>function</em> at pickling time.  <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised if
<em>object</em> is a class or <em>constructor</em> is not callable.</p>
<p>See the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module for more details on the interface expected of
<em>function</em> and <em>constructor</em>.</p>
</dd></dl>

<div class="section" id="example">
<h2>11.3.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The example below would like to show how to register a pickle function and how
it will be used:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">copy_reg</span><span class="o">,</span> <span class="nn">copy</span><span class="o">,</span> <span class="nn">pickle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">a</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="n">a</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">pickle_c</span><span class="p">(</span><span class="n">c</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;pickling a C instance...&quot;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">C</span><span class="p">,</span> <span class="p">(</span><span class="n">c</span><span class="o">.</span><span class="n">a</span><span class="p">,)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">copy_reg</span><span class="o">.</span><span class="n">pickle</span><span class="p">(</span><span class="n">C</span><span class="p">,</span> <span class="n">pickle_c</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">copy</span><span class="o">.</span><span class="n">copy</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">pickling a C instance...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">pickling a C instance...</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a><ul>
<li><a class="reference internal" href="#example">11.3.1. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pickle.html"
                        title="previous chapter">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="shelve.html"
                        title="next chapter">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/copy_reg.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shelve.html" title="11.4. shelve — Python object persistence"
             >next</a> |</li>
        <li class="right" >
          <a href="pickle.html" title="11.1. pickle — Python object serialization"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��a �)�)html/library/crypt.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.5. crypt — Function to check Unix passwords &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.6. dl — Call C functions in shared objects" href="dl.html" />
    <link rel="prev" title="36.4. grp — The group database" href="grp.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/crypt.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dl.html" title="36.6. dl — Call C functions in shared objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="grp.html" title="36.4. grp — The group database"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-crypt">
<span id="crypt-function-to-check-unix-passwords"></span><h1>36.5. <a class="reference internal" href="#module-crypt" title="crypt: The crypt() function used to check Unix passwords. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">crypt</span></code></a> — Function to check Unix passwords<a class="headerlink" href="#module-crypt" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module implements an interface to the <em class="manpage">crypt(3)</em> routine, which is
a one-way hash function based upon a modified DES algorithm; see the Unix man
page for further details.  Possible uses include allowing Python scripts to
accept typed passwords from the user, or attempting to crack Unix passwords with
a dictionary.</p>
<p id="index-1">Notice that the behavior of this module depends on the actual implementation  of
the <em class="manpage">crypt(3)</em> routine in the running system.  Therefore, any
extensions available on the current implementation will also  be available on
this module.</p>
<dl class="function">
<dt id="crypt.crypt">
<code class="descclassname">crypt.</code><code class="descname">crypt</code><span class="sig-paren">(</span><em>word</em>, <em>salt</em><span class="sig-paren">)</span><a class="headerlink" href="#crypt.crypt" title="Permalink to this definition">¶</a></dt>
<dd><p><em>word</em> will usually be a user’s password as typed at a prompt or  in a graphical
interface.  <em>salt</em> is usually a random two-character string which will be used
to perturb the DES algorithm in one of 4096 ways.  The characters in <em>salt</em> must
be in the set <code class="docutils literal notranslate"><span class="pre">[./a-zA-Z0-9]</span></code>.  Returns the hashed password as a string, which
will be composed of characters from the same alphabet as the salt (the first two
characters represent the salt itself).</p>
<p id="index-2">Since a few <em class="manpage">crypt(3)</em> extensions allow different values, with
different sizes in the <em>salt</em>, it is recommended to use  the full crypted
password as salt when checking for a password.</p>
</dd></dl>

<p>A simple example illustrating typical use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">crypt</span><span class="o">,</span> <span class="nn">getpass</span><span class="o">,</span> <span class="nn">pwd</span>

<span class="k">def</span> <span class="nf">login</span><span class="p">():</span>
    <span class="n">username</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s1">&#39;Python login:&#39;</span><span class="p">)</span>
    <span class="n">cryptedpasswd</span> <span class="o">=</span> <span class="n">pwd</span><span class="o">.</span><span class="n">getpwnam</span><span class="p">(</span><span class="n">username</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span>
    <span class="k">if</span> <span class="n">cryptedpasswd</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">cryptedpasswd</span> <span class="o">==</span> <span class="s1">&#39;x&#39;</span> <span class="ow">or</span> <span class="n">cryptedpasswd</span> <span class="o">==</span> <span class="s1">&#39;*&#39;</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">NotImplementedError</span><span class="p">(</span>
                <span class="s2">&quot;Sorry, currently no support for shadow passwords&quot;</span><span class="p">)</span>
        <span class="n">cleartext</span> <span class="o">=</span> <span class="n">getpass</span><span class="o">.</span><span class="n">getpass</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">crypt</span><span class="o">.</span><span class="n">crypt</span><span class="p">(</span><span class="n">cleartext</span><span class="p">,</span> <span class="n">cryptedpasswd</span><span class="p">)</span> <span class="o">==</span> <span class="n">cryptedpasswd</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="mi">1</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="grp.html"
                        title="previous chapter">36.4. <code class="docutils literal notranslate"><span class="pre">grp</span></code> — The group database</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dl.html"
                        title="next chapter">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/crypt.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dl.html" title="36.6. dl — Call C functions in shared objects"
             >next</a> |</li>
        <li class="right" >
          <a href="grp.html" title="36.4. grp — The group database"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�a<�QQhtml/library/crypto.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14. Cryptographic Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14.1. hashlib — Secure hashes and message digests" href="hashlib.html" />
    <link rel="prev" title="13.6. plistlib — Generate and parse Mac OS X .plist files" href="plistlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/crypto.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hashlib.html" title="14.1. hashlib — Secure hashes and message digests"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="plistlib.html" title="13.6. plistlib — Generate and parse Mac OS X .plist files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="cryptographic-services">
<span id="crypto"></span><h1>14. Cryptographic Services<a class="headerlink" href="#cryptographic-services" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The modules described in this chapter implement various algorithms of a
cryptographic nature.  They are available at the discretion of the installation.
Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="hashlib.html">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a><ul>
<li class="toctree-l2"><a class="reference internal" href="hashlib.html#key-derivation">14.1.1. Key derivation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="hmac.html">14.2. <code class="docutils literal notranslate"><span class="pre">hmac</span></code> — Keyed-Hashing for Message Authentication</a></li>
<li class="toctree-l1"><a class="reference internal" href="md5.html">14.3. <code class="docutils literal notranslate"><span class="pre">md5</span></code> — MD5 message digest algorithm</a></li>
<li class="toctree-l1"><a class="reference internal" href="sha.html">14.4. <code class="docutils literal notranslate"><span class="pre">sha</span></code> — SHA-1 message digest algorithm</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="plistlib.html"
                        title="previous chapter">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="hashlib.html"
                        title="next chapter">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/crypto.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hashlib.html" title="14.1. hashlib — Secure hashes and message digests"
             >next</a> |</li>
        <li class="right" >
          <a href="plistlib.html" title="13.6. plistlib — Generate and parse Mac OS X .plist files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\)��T�*�*html/library/csv.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.1. csv — CSV File Reading and Writing &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.2. ConfigParser — Configuration file parser" href="configparser.html" />
    <link rel="prev" title="13. File Formats" href="fileformats.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/csv.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="configparser.html" title="13.2. ConfigParser — Configuration file parser"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fileformats.html" title="13. File Formats"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-csv">
<span id="csv-csv-file-reading-and-writing"></span><h1>13.1. <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> — CSV File Reading and Writing<a class="headerlink" href="#module-csv" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p id="index-0">The so-called CSV (Comma Separated Values) format is the most common import and
export format for spreadsheets and databases.  There is no “CSV standard”, so
the format is operationally defined by the many applications which read and
write it.  The lack of a standard means that subtle differences often exist in
the data produced and consumed by different applications.  These differences can
make it annoying to process CSV files from multiple sources.  Still, while the
delimiters and quoting characters vary, the overall format is similar enough
that it is possible to write a single module which can efficiently manipulate
such data, hiding the details of reading and writing the data from the
programmer.</p>
<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module implements classes to read and write tabular data in CSV
format.  It allows programmers to say, “write this data in the format preferred
by Excel,” or “read data from this file which was generated by Excel,” without
knowing the precise details of the CSV format used by Excel.  Programmers can
also describe the CSV formats understood by other applications or define their
own special-purpose CSV formats.</p>
<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module’s <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> and <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects read and
write sequences.  Programmers can also read and write data in dictionary form
using the <a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> and <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> classes.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This version of the <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module doesn’t support Unicode input.  Also,
there are currently some issues regarding ASCII NUL characters.  Accordingly,
all input should be UTF-8 or printable ASCII to be safe; see the examples in
section <a class="reference internal" href="#csv-examples"><span class="std std-ref">Examples</span></a>.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0305"><strong>PEP 305</strong></a> - CSV File API</dt>
<dd>The Python Enhancement Proposal which proposed this addition to Python.</dd>
</dl>
</div>
<div class="section" id="module-contents">
<span id="csv-contents"></span><h2>13.1.1. Module Contents<a class="headerlink" href="#module-contents" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="csv.reader">
<code class="descclassname">csv.</code><code class="descname">reader</code><span class="sig-paren">(</span><em>csvfile</em>, <em>dialect='excel'</em>, <em>**fmtparams</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.reader" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a reader object which will iterate over lines in the given <em>csvfile</em>.
<em>csvfile</em> can be any object which supports the <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> protocol and returns a
string each time its <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method is called — file objects and list
objects are both suitable.   If <em>csvfile</em> is a file object, it must be opened
with the ‘b’ flag on platforms where that makes a difference.  An optional
<em>dialect</em> parameter can be given which is used to define a set of parameters
specific to a particular CSV dialect.  It may be an instance of a subclass of
the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class or one of the strings returned by the
<a class="reference internal" href="#csv.list_dialects" title="csv.list_dialects"><code class="xref py py-func docutils literal notranslate"><span class="pre">list_dialects()</span></code></a> function.  The other optional <em>fmtparams</em> keyword arguments
can be given to override individual formatting parameters in the current
dialect.  For full details about the dialect and formatting parameters, see
section <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a>.</p>
<p>Each row read from the csv file is returned as a list of strings.  No
automatic data type conversion is performed.</p>
<p>A short usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">csv</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;eggs.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">spamreader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="n">quotechar</span><span class="o">=</span><span class="s1">&#39;|&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">spamreader</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s1">&#39;, &#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
<span class="go">Spam, Spam, Spam, Spam, Spam, Baked Beans</span>
<span class="go">Spam, Lovely Spam, Wonderful Spam</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The parser is now stricter with respect to multi-line quoted fields. Previously,
if a line ended within a quoted field without a terminating newline character, a
newline would be inserted into the returned field. This behavior caused problems
when reading files which contained carriage return characters within fields.
The behavior was changed to return the field without inserting newlines. As a
consequence, if newlines embedded within fields are important, the input should
be split into lines in a manner which preserves the newline characters.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="csv.writer">
<code class="descclassname">csv.</code><code class="descname">writer</code><span class="sig-paren">(</span><em>csvfile</em>, <em>dialect='excel'</em>, <em>**fmtparams</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.writer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a writer object responsible for converting the user’s data into delimited
strings on the given file-like object.  <em>csvfile</em> can be any object with a
<code class="xref py py-func docutils literal notranslate"><span class="pre">write()</span></code> method.  If <em>csvfile</em> is a file object, it must be opened with the
‘b’ flag on platforms where that makes a difference.  An optional <em>dialect</em>
parameter can be given which is used to define a set of parameters specific to a
particular CSV dialect.  It may be an instance of a subclass of the
<a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class or one of the strings returned by the
<a class="reference internal" href="#csv.list_dialects" title="csv.list_dialects"><code class="xref py py-func docutils literal notranslate"><span class="pre">list_dialects()</span></code></a> function.  The other optional <em>fmtparams</em> keyword arguments
can be given to override individual formatting parameters in the current
dialect.  For full details about the dialect and formatting parameters, see
section <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a>. To make it
as easy as possible to interface with modules which implement the DB API, the
value <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is written as the empty string.  While this isn’t a
reversible transformation, it makes it easier to dump SQL NULL data values to
CSV files without preprocessing the data returned from a <code class="docutils literal notranslate"><span class="pre">cursor.fetch*</span></code> call.
Floats are stringified with <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> before being written.
All other non-string data are stringified with <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> before being written.</p>
<p>A short usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;eggs.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
    <span class="n">spamwriter</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span>
                            <span class="n">quotechar</span><span class="o">=</span><span class="s1">&#39;|&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_MINIMAL</span><span class="p">)</span>
    <span class="n">spamwriter</span><span class="o">.</span><span class="n">writerow</span><span class="p">([</span><span class="s1">&#39;Spam&#39;</span><span class="p">]</span> <span class="o">*</span> <span class="mi">5</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;Baked Beans&#39;</span><span class="p">])</span>
    <span class="n">spamwriter</span><span class="o">.</span><span class="n">writerow</span><span class="p">([</span><span class="s1">&#39;Spam&#39;</span><span class="p">,</span> <span class="s1">&#39;Lovely Spam&#39;</span><span class="p">,</span> <span class="s1">&#39;Wonderful Spam&#39;</span><span class="p">])</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="csv.register_dialect">
<code class="descclassname">csv.</code><code class="descname">register_dialect</code><span class="sig-paren">(</span><em>name</em>, <span class="optional">[</span><em>dialect</em>, <span class="optional">]</span><em>**fmtparams</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.register_dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>Associate <em>dialect</em> with <em>name</em>.  <em>name</em> must be a string or Unicode object. The
dialect can be specified either by passing a sub-class of <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>, or
by <em>fmtparams</em> keyword arguments, or both, with keyword arguments overriding
parameters of the dialect. For full details about the dialect and formatting
parameters, see section <a class="reference internal" href="#csv-fmt-params"><span class="std std-ref">Dialects and Formatting Parameters</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="csv.unregister_dialect">
<code class="descclassname">csv.</code><code class="descname">unregister_dialect</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.unregister_dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the dialect associated with <em>name</em> from the dialect registry.  An
<a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if <em>name</em> is not a registered dialect name.</p>
</dd></dl>

<dl class="function">
<dt id="csv.get_dialect">
<code class="descclassname">csv.</code><code class="descname">get_dialect</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.get_dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the dialect associated with <em>name</em>.  An <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if <em>name</em>
is not a registered dialect name.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>This function now returns an immutable <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a>.  Previously an
instance of the requested dialect was returned.  Users could modify the
underlying class, changing the behavior of active readers and writers.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="csv.list_dialects">
<code class="descclassname">csv.</code><code class="descname">list_dialects</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.list_dialects" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the names of all registered dialects.</p>
</dd></dl>

<dl class="function">
<dt id="csv.field_size_limit">
<code class="descclassname">csv.</code><code class="descname">field_size_limit</code><span class="sig-paren">(</span><span class="optional">[</span><em>new_limit</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.field_size_limit" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current maximum field size allowed by the parser. If <em>new_limit</em> is
given, this becomes the new limit.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following classes:</p>
<dl class="class">
<dt id="csv.DictReader">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">DictReader</code><span class="sig-paren">(</span><em>f</em>, <em>fieldnames=None</em>, <em>restkey=None</em>, <em>restval=None</em>, <em>dialect='excel'</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictReader" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an object which operates like a regular reader but maps the
information read into a dict whose keys are given by the optional
<em>fieldnames</em> parameter.  The <em>fieldnames</em> parameter is a <a class="reference internal" href="collections.html#collections-abstract-base-classes"><span class="std std-ref">sequence</span></a> whose elements are associated with the
fields of the input data in order. These elements become the keys of the
resulting dictionary.  If the <em>fieldnames</em> parameter is omitted, the values
in the first row of the file <em>f</em> will be used as the fieldnames.  If the
row read has more fields than the fieldnames sequence, the remaining data is
added as a sequence keyed by the value of <em>restkey</em>.  If the row read has
fewer fields than the fieldnames sequence, the remaining keys take the value
of the optional <em>restval</em> parameter.  Any other optional or keyword
arguments are passed to the underlying <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> instance.</p>
<p>A short usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">csv</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;names.csv&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">DictReader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="s1">&#39;first_name&#39;</span><span class="p">],</span> <span class="n">row</span><span class="p">[</span><span class="s1">&#39;last_name&#39;</span><span class="p">])</span>
<span class="gp">...</span>
<span class="go">Baked Beans</span>
<span class="go">Lovely Spam</span>
<span class="go">Wonderful Spam</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="csv.DictWriter">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">DictWriter</code><span class="sig-paren">(</span><em>f</em>, <em>fieldnames</em>, <em>restval=''</em>, <em>extrasaction='raise'</em>, <em>dialect='excel'</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an object which operates like a regular writer but maps dictionaries
onto output rows.  The <em>fieldnames</em> parameter is a <a class="reference internal" href="collections.html#collections-abstract-base-classes"><span class="std std-ref">sequence</span></a> of keys that identify the order in
which values in the dictionary passed to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">writerow()</span></code> method are
written to the file <em>f</em>.  The optional <em>restval</em> parameter specifies the
value to be written if the dictionary is missing a key in <em>fieldnames</em>.  If
the dictionary passed to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">writerow()</span></code> method contains a key not
found in <em>fieldnames</em>, the optional <em>extrasaction</em> parameter indicates what
action to take.  If it is set to <code class="docutils literal notranslate"><span class="pre">'raise'</span></code> a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.
If it is set to <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, extra values in the dictionary are ignored.
Any other optional or keyword arguments are passed to the underlying
<a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> instance.</p>
<p>Note that unlike the <a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> class, the <em>fieldnames</em> parameter
of the <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> is not optional.  Since Python’s <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>
objects are not ordered, there is not enough information available to deduce
the order in which the row should be written to the file <em>f</em>.</p>
<p>A short usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;names.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
    <span class="n">fieldnames</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;first_name&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">]</span>
    <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">DictWriter</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">fieldnames</span><span class="o">=</span><span class="n">fieldnames</span><span class="p">)</span>

    <span class="n">writer</span><span class="o">.</span><span class="n">writeheader</span><span class="p">()</span>
    <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Baked&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Beans&#39;</span><span class="p">})</span>
    <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Lovely&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Spam&#39;</span><span class="p">})</span>
    <span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">({</span><span class="s1">&#39;first_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Wonderful&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">:</span> <span class="s1">&#39;Spam&#39;</span><span class="p">})</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="csv.Dialect">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">Dialect</code><a class="headerlink" href="#csv.Dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class is a container class relied on primarily for its
attributes, which are used to define the parameters for a specific
<a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> or <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> instance.</p>
</dd></dl>

<dl class="class">
<dt id="csv.excel">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">excel</code><a class="headerlink" href="#csv.excel" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#csv.excel" title="csv.excel"><code class="xref py py-class docutils literal notranslate"><span class="pre">excel</span></code></a> class defines the usual properties of an Excel-generated CSV
file.  It is registered with the dialect name <code class="docutils literal notranslate"><span class="pre">'excel'</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="csv.excel_tab">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">excel_tab</code><a class="headerlink" href="#csv.excel_tab" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#csv.excel_tab" title="csv.excel_tab"><code class="xref py py-class docutils literal notranslate"><span class="pre">excel_tab</span></code></a> class defines the usual properties of an Excel-generated
TAB-delimited file.  It is registered with the dialect name <code class="docutils literal notranslate"><span class="pre">'excel-tab'</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="csv.Sniffer">
<em class="property">class </em><code class="descclassname">csv.</code><code class="descname">Sniffer</code><a class="headerlink" href="#csv.Sniffer" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> class is used to deduce the format of a CSV file.</p>
<p>The <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> class provides two methods:</p>
<dl class="method">
<dt id="csv.Sniffer.sniff">
<code class="descname">sniff</code><span class="sig-paren">(</span><em>sample</em>, <em>delimiters=None</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.Sniffer.sniff" title="Permalink to this definition">¶</a></dt>
<dd><p>Analyze the given <em>sample</em> and return a <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> subclass
reflecting the parameters found.  If the optional <em>delimiters</em> parameter
is given, it is interpreted as a string containing possible valid
delimiter characters.</p>
</dd></dl>

<dl class="method">
<dt id="csv.Sniffer.has_header">
<code class="descname">has_header</code><span class="sig-paren">(</span><em>sample</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.Sniffer.has_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Analyze the sample text (presumed to be in CSV format) and return
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the first row appears to be a series of column headers.</p>
</dd></dl>

</dd></dl>

<p>An example for <a class="reference internal" href="#csv.Sniffer" title="csv.Sniffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sniffer</span></code></a> use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;example.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">csvfile</span><span class="p">:</span>
    <span class="n">dialect</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">Sniffer</span><span class="p">()</span><span class="o">.</span><span class="n">sniff</span><span class="p">(</span><span class="n">csvfile</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1024</span><span class="p">))</span>
    <span class="n">csvfile</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">csvfile</span><span class="p">,</span> <span class="n">dialect</span><span class="p">)</span>
    <span class="c1"># ... process CSV file contents here ...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following constants:</p>
<dl class="data">
<dt id="csv.QUOTE_ALL">
<code class="descclassname">csv.</code><code class="descname">QUOTE_ALL</code><a class="headerlink" href="#csv.QUOTE_ALL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to quote all fields.</p>
</dd></dl>

<dl class="data">
<dt id="csv.QUOTE_MINIMAL">
<code class="descclassname">csv.</code><code class="descname">QUOTE_MINIMAL</code><a class="headerlink" href="#csv.QUOTE_MINIMAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to only quote those fields which contain
special characters such as <em>delimiter</em>, <em>quotechar</em> or any of the characters in
<em>lineterminator</em>.</p>
</dd></dl>

<dl class="data">
<dt id="csv.QUOTE_NONNUMERIC">
<code class="descclassname">csv.</code><code class="descname">QUOTE_NONNUMERIC</code><a class="headerlink" href="#csv.QUOTE_NONNUMERIC" title="Permalink to this definition">¶</a></dt>
<dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to quote all non-numeric fields.</p>
<p>Instructs the reader to convert all non-quoted fields to type <em>float</em>.</p>
</dd></dl>

<dl class="data">
<dt id="csv.QUOTE_NONE">
<code class="descclassname">csv.</code><code class="descname">QUOTE_NONE</code><a class="headerlink" href="#csv.QUOTE_NONE" title="Permalink to this definition">¶</a></dt>
<dd><p>Instructs <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects to never quote fields.  When the current
<em>delimiter</em> occurs in output data it is preceded by the current <em>escapechar</em>
character.  If <em>escapechar</em> is not set, the writer will raise <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> if
any characters that require escaping are encountered.</p>
<p>Instructs <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> to perform no special processing of quote characters.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module defines the following exception:</p>
<dl class="exception">
<dt id="csv.Error">
<em class="property">exception </em><code class="descclassname">csv.</code><code class="descname">Error</code><a class="headerlink" href="#csv.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised by any of the functions when an error is detected.</p>
</dd></dl>

</div>
<div class="section" id="dialects-and-formatting-parameters">
<span id="csv-fmt-params"></span><h2>13.1.2. Dialects and Formatting Parameters<a class="headerlink" href="#dialects-and-formatting-parameters" title="Permalink to this headline">¶</a></h2>
<p>To make it easier to specify the format of input and output records, specific
formatting parameters are grouped together into dialects.  A dialect is a
subclass of the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class having a set of specific methods and a
single <code class="xref py py-meth docutils literal notranslate"><span class="pre">validate()</span></code> method.  When creating <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> or
<a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a> objects, the programmer can specify a string or a subclass of
the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class as the dialect parameter.  In addition to, or instead
of, the <em>dialect</em> parameter, the programmer can also specify individual
formatting parameters, which have the same names as the attributes defined below
for the <a class="reference internal" href="#csv.Dialect" title="csv.Dialect"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialect</span></code></a> class.</p>
<p>Dialects support the following attributes:</p>
<dl class="attribute">
<dt id="csv.Dialect.delimiter">
<code class="descclassname">Dialect.</code><code class="descname">delimiter</code><a class="headerlink" href="#csv.Dialect.delimiter" title="Permalink to this definition">¶</a></dt>
<dd><p>A one-character string used to separate fields.  It defaults to <code class="docutils literal notranslate"><span class="pre">','</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.doublequote">
<code class="descclassname">Dialect.</code><code class="descname">doublequote</code><a class="headerlink" href="#csv.Dialect.doublequote" title="Permalink to this definition">¶</a></dt>
<dd><p>Controls how instances of <em>quotechar</em> appearing inside a field should
themselves be quoted.  When <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, the character is doubled. When
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, the <em>escapechar</em> is used as a prefix to the <em>quotechar</em>.  It
defaults to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<p>On output, if <em>doublequote</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> and no <em>escapechar</em> is set,
<a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if a <em>quotechar</em> is found in a field.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.escapechar">
<code class="descclassname">Dialect.</code><code class="descname">escapechar</code><a class="headerlink" href="#csv.Dialect.escapechar" title="Permalink to this definition">¶</a></dt>
<dd><p>A one-character string used by the writer to escape the <em>delimiter</em> if <em>quoting</em>
is set to <a class="reference internal" href="#csv.QUOTE_NONE" title="csv.QUOTE_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">QUOTE_NONE</span></code></a> and the <em>quotechar</em> if <em>doublequote</em> is
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. On reading, the <em>escapechar</em> removes any special meaning from
the following character. It defaults to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, which disables escaping.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.lineterminator">
<code class="descclassname">Dialect.</code><code class="descname">lineterminator</code><a class="headerlink" href="#csv.Dialect.lineterminator" title="Permalink to this definition">¶</a></dt>
<dd><p>The string used to terminate lines produced by the <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">writer</span></code></a>. It defaults
to <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code></a> is hard-coded to recognise either <code class="docutils literal notranslate"><span class="pre">'\r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> as
end-of-line, and ignores <em>lineterminator</em>. This behavior may change in the
future.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.quotechar">
<code class="descclassname">Dialect.</code><code class="descname">quotechar</code><a class="headerlink" href="#csv.Dialect.quotechar" title="Permalink to this definition">¶</a></dt>
<dd><p>A one-character string used to quote fields containing special characters, such
as the <em>delimiter</em> or <em>quotechar</em>, or which contain new-line characters.  It
defaults to <code class="docutils literal notranslate"><span class="pre">'&quot;'</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.quoting">
<code class="descclassname">Dialect.</code><code class="descname">quoting</code><a class="headerlink" href="#csv.Dialect.quoting" title="Permalink to this definition">¶</a></dt>
<dd><p>Controls when quotes should be generated by the writer and recognised by the
reader.  It can take on any of the <code class="xref py py-const docutils literal notranslate"><span class="pre">QUOTE_*</span></code> constants (see section
<a class="reference internal" href="#csv-contents"><span class="std std-ref">Module Contents</span></a>) and defaults to <a class="reference internal" href="#csv.QUOTE_MINIMAL" title="csv.QUOTE_MINIMAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">QUOTE_MINIMAL</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.skipinitialspace">
<code class="descclassname">Dialect.</code><code class="descname">skipinitialspace</code><a class="headerlink" href="#csv.Dialect.skipinitialspace" title="Permalink to this definition">¶</a></dt>
<dd><p>When <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, whitespace immediately following the <em>delimiter</em> is ignored.
The default is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.Dialect.strict">
<code class="descclassname">Dialect.</code><code class="descname">strict</code><a class="headerlink" href="#csv.Dialect.strict" title="Permalink to this definition">¶</a></dt>
<dd><p>When <code class="docutils literal notranslate"><span class="pre">True</span></code>, raise exception <a class="reference internal" href="#csv.Error" title="csv.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> on bad CSV input.
The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="reader-objects">
<h2>13.1.3. Reader Objects<a class="headerlink" href="#reader-objects" title="Permalink to this headline">¶</a></h2>
<p>Reader objects (<a class="reference internal" href="#csv.DictReader" title="csv.DictReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictReader</span></code></a> instances and objects returned by the
<a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-func docutils literal notranslate"><span class="pre">reader()</span></code></a> function) have the following public methods:</p>
<dl class="method">
<dt id="csv.csvreader.next">
<code class="descclassname">csvreader.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvreader.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next row of the reader’s iterable object as a list, parsed according
to the current dialect.</p>
</dd></dl>

<p>Reader objects have the following public attributes:</p>
<dl class="attribute">
<dt id="csv.csvreader.dialect">
<code class="descclassname">csvreader.</code><code class="descname">dialect</code><a class="headerlink" href="#csv.csvreader.dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>A read-only description of the dialect in use by the parser.</p>
</dd></dl>

<dl class="attribute">
<dt id="csv.csvreader.line_num">
<code class="descclassname">csvreader.</code><code class="descname">line_num</code><a class="headerlink" href="#csv.csvreader.line_num" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of lines read from the source iterator. This is not the same as the
number of records returned, as records can span multiple lines.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>DictReader objects have the following public attribute:</p>
<dl class="attribute">
<dt id="csv.csvreader.fieldnames">
<code class="descclassname">csvreader.</code><code class="descname">fieldnames</code><a class="headerlink" href="#csv.csvreader.fieldnames" title="Permalink to this definition">¶</a></dt>
<dd><p>If not passed as a parameter when creating the object, this attribute is
initialized upon first access or when the first record is read from the
file.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="writer-objects">
<h2>13.1.4. Writer Objects<a class="headerlink" href="#writer-objects" title="Permalink to this headline">¶</a></h2>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Writer</span></code> objects (<a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> instances and objects returned by
the <a class="reference internal" href="#csv.writer" title="csv.writer"><code class="xref py py-func docutils literal notranslate"><span class="pre">writer()</span></code></a> function) have the following public methods.  A <em>row</em> must be
a sequence of strings or numbers for <code class="xref py py-class docutils literal notranslate"><span class="pre">Writer</span></code> objects and a dictionary
mapping fieldnames to strings or numbers (by passing them through <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>
first) for <a class="reference internal" href="#csv.DictWriter" title="csv.DictWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictWriter</span></code></a> objects.  Note that complex numbers are written
out surrounded by parens. This may cause some problems for other programs which
read CSV files (assuming they support complex numbers at all).</p>
<dl class="method">
<dt id="csv.csvwriter.writerow">
<code class="descclassname">csvwriter.</code><code class="descname">writerow</code><span class="sig-paren">(</span><em>row</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvwriter.writerow" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the <em>row</em> parameter to the writer’s file object, formatted according to
the current dialect.</p>
</dd></dl>

<dl class="method">
<dt id="csv.csvwriter.writerows">
<code class="descclassname">csvwriter.</code><code class="descname">writerows</code><span class="sig-paren">(</span><em>rows</em><span class="sig-paren">)</span><a class="headerlink" href="#csv.csvwriter.writerows" title="Permalink to this definition">¶</a></dt>
<dd><p>Write all elements in <em>rows</em> (an iterable of <em>row</em> objects as described
above) to the writer’s file object, formatted according to the current
dialect.</p>
</dd></dl>

<p>Writer objects have the following public attribute:</p>
<dl class="attribute">
<dt id="csv.csvwriter.dialect">
<code class="descclassname">csvwriter.</code><code class="descname">dialect</code><a class="headerlink" href="#csv.csvwriter.dialect" title="Permalink to this definition">¶</a></dt>
<dd><p>A read-only description of the dialect in use by the writer.</p>
</dd></dl>

<p>DictWriter objects have the following public method:</p>
<dl class="method">
<dt id="csv.DictWriter.writeheader">
<code class="descclassname">DictWriter.</code><code class="descname">writeheader</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#csv.DictWriter.writeheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a row with the field names (as specified in the constructor).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="csv-examples"></span><h2>13.1.5. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>The simplest example of reading a CSV file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;some.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">row</span>
</pre></div>
</div>
<p>Reading a file with an alternate format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39;:&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_NONE</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">row</span>
</pre></div>
</div>
<p>The corresponding simplest possible writing example is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;some.csv&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="n">writer</span><span class="o">.</span><span class="n">writerows</span><span class="p">(</span><span class="n">someiterable</span><span class="p">)</span>
</pre></div>
</div>
<p>Registering a new dialect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="n">csv</span><span class="o">.</span><span class="n">register_dialect</span><span class="p">(</span><span class="s1">&#39;unixpwd&#39;</span><span class="p">,</span> <span class="n">delimiter</span><span class="o">=</span><span class="s1">&#39;:&#39;</span><span class="p">,</span> <span class="n">quoting</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">QUOTE_NONE</span><span class="p">)</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s1">&#39;unixpwd&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>A slightly more advanced use of the reader — catching and reporting errors:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span><span class="o">,</span> <span class="nn">sys</span>
<span class="n">filename</span> <span class="o">=</span> <span class="s1">&#39;some.csv&#39;</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
            <span class="nb">print</span> <span class="n">row</span>
    <span class="k">except</span> <span class="n">csv</span><span class="o">.</span><span class="n">Error</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="s1">&#39;file </span><span class="si">%s</span><span class="s1">, line </span><span class="si">%d</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">reader</span><span class="o">.</span><span class="n">line_num</span><span class="p">,</span> <span class="n">e</span><span class="p">))</span>
</pre></div>
</div>
<p>And while the module doesn’t directly support parsing strings, it can easily be
done:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">([</span><span class="s1">&#39;one,two,three&#39;</span><span class="p">]):</span>
    <span class="nb">print</span> <span class="n">row</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module doesn’t directly support reading and writing Unicode, but
it is 8-bit-clean save for some problems with ASCII NUL characters.  So you can
write functions or classes that handle the encoding and decoding for you as long
as you avoid encodings like UTF-16 that use NULs.  UTF-8 is recommended.</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode_csv_reader()</span></code> below is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> that wraps <a class="reference internal" href="#csv.reader" title="csv.reader"><code class="xref py py-class docutils literal notranslate"><span class="pre">csv.reader</span></code></a>
to handle Unicode CSV data (a list of Unicode strings).  <code class="xref py py-func docutils literal notranslate"><span class="pre">utf_8_encoder()</span></code>
is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> that encodes the Unicode strings as UTF-8, one string (or row) at
a time.  The encoded strings are parsed by the CSV reader, and
<code class="xref py py-func docutils literal notranslate"><span class="pre">unicode_csv_reader()</span></code> decodes the UTF-8-encoded cells back into Unicode:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>

<span class="k">def</span> <span class="nf">unicode_csv_reader</span><span class="p">(</span><span class="n">unicode_csv_data</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">excel</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="c1"># csv.py doesn&#39;t do Unicode; encode temporarily as UTF-8:</span>
    <span class="n">csv_reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">utf_8_encoder</span><span class="p">(</span><span class="n">unicode_csv_data</span><span class="p">),</span>
                            <span class="n">dialect</span><span class="o">=</span><span class="n">dialect</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">csv_reader</span><span class="p">:</span>
        <span class="c1"># decode UTF-8 back to Unicode, cell by cell:</span>
        <span class="k">yield</span> <span class="p">[</span><span class="n">unicode</span><span class="p">(</span><span class="n">cell</span><span class="p">,</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span> <span class="k">for</span> <span class="n">cell</span> <span class="ow">in</span> <span class="n">row</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">utf_8_encoder</span><span class="p">(</span><span class="n">unicode_csv_data</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">unicode_csv_data</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">line</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>For all other encodings the following <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeReader</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWriter</span></code> classes can be used. They take an additional <em>encoding</em>
parameter in their constructor and make sure that the data passes the real
reader or writer encoded as UTF-8:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span><span class="o">,</span> <span class="nn">codecs</span><span class="o">,</span> <span class="nn">cStringIO</span>

<span class="k">class</span> <span class="nc">UTF8Recoder</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    Iterator that reads an encoded stream and reencodes the input to UTF-8</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">encoding</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">reader</span> <span class="o">=</span> <span class="n">codecs</span><span class="o">.</span><span class="n">getreader</span><span class="p">(</span><span class="n">encoding</span><span class="p">)(</span><span class="n">f</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">reader</span><span class="o">.</span><span class="n">next</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">UnicodeReader</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    A CSV reader which will iterate over lines in the CSV file &quot;f&quot;,</span>
<span class="sd">    which is encoded in the given encoding.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">excel</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">&quot;utf-8&quot;</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="n">f</span> <span class="o">=</span> <span class="n">UTF8Recoder</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">encoding</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="n">dialect</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">row</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">reader</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
        <span class="k">return</span> <span class="p">[</span><span class="n">unicode</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="s2">&quot;utf-8&quot;</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">row</span><span class="p">]</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

<span class="k">class</span> <span class="nc">UnicodeWriter</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    A CSV writer which will write rows to CSV file &quot;f&quot;,</span>
<span class="sd">    which is encoded in the given encoding.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">f</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="n">csv</span><span class="o">.</span><span class="n">excel</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">&quot;utf-8&quot;</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="c1"># Redirect output to a queue</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">queue</span> <span class="o">=</span> <span class="n">cStringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">writer</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">writer</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">queue</span><span class="p">,</span> <span class="n">dialect</span><span class="o">=</span><span class="n">dialect</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stream</span> <span class="o">=</span> <span class="n">f</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">encoder</span> <span class="o">=</span> <span class="n">codecs</span><span class="o">.</span><span class="n">getincrementalencoder</span><span class="p">(</span><span class="n">encoding</span><span class="p">)()</span>

    <span class="k">def</span> <span class="nf">writerow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">row</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">writer</span><span class="o">.</span><span class="n">writerow</span><span class="p">([</span><span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">row</span><span class="p">])</span>
        <span class="c1"># Fetch UTF-8 output from the queue ...</span>
        <span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">queue</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>
        <span class="c1"># ... and reencode it into the target encoding</span>
        <span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">encoder</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
        <span class="c1"># write to the target stream</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stream</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
        <span class="c1"># empty queue</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">queue</span><span class="o">.</span><span class="n">truncate</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">writerows</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">rows</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">rows</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">writerow</span><span class="p">(</span><span class="n">row</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a><ul>
<li><a class="reference internal" href="#module-contents">13.1.1. Module Contents</a></li>
<li><a class="reference internal" href="#dialects-and-formatting-parameters">13.1.2. Dialects and Formatting Parameters</a></li>
<li><a class="reference internal" href="#reader-objects">13.1.3. Reader Objects</a></li>
<li><a class="reference internal" href="#writer-objects">13.1.4. Writer Objects</a></li>
<li><a class="reference internal" href="#examples">13.1.5. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="fileformats.html"
                        title="previous chapter">13. File Formats</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="configparser.html"
                        title="next chapter">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/csv.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="configparser.html" title="13.2. ConfigParser — Configuration file parser"
             >next</a> |</li>
        <li class="right" >
          <a href="fileformats.html" title="13. File Formats"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��T		html/library/ctypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.17. ctypes — A foreign function library for Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16. Optional Operating System Services" href="someos.html" />
    <link rel="prev" title="15.16. errno — Standard errno system symbols" href="errno.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ctypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ctypes">
<span id="ctypes-a-foreign-function-library-for-python"></span><h1>15.17. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> — A foreign function library for Python<a class="headerlink" href="#module-ctypes" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> is a foreign function library for Python.  It provides C compatible
data types, and allows calling functions in DLLs or shared libraries.  It can be
used to wrap these libraries in pure Python.</p>
<div class="section" id="ctypes-tutorial">
<span id="ctypes-ctypes-tutorial"></span><h2>15.17.1. ctypes tutorial<a class="headerlink" href="#ctypes-tutorial" title="Permalink to this headline">¶</a></h2>
<p>Note: The code samples in this tutorial use <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> to make sure that
they actually work.  Since some code samples behave differently under Linux,
Windows, or Mac OS X, they contain doctest directives in comments.</p>
<p>Note: Some code samples reference the ctypes <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a> type. This type is
an alias for the <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_long</span></code></a> type on 32-bit systems.  So, you should not be
confused if <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_long</span></code></a> is printed if you would expect <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a> —
they are actually the same type.</p>
<div class="section" id="loading-dynamic-link-libraries">
<span id="ctypes-loading-dynamic-link-libraries"></span><h3>15.17.1.1. Loading dynamic link libraries<a class="headerlink" href="#loading-dynamic-link-libraries" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> exports the <em>cdll</em>, and on Windows <em>windll</em> and <em>oledll</em>
objects, for loading dynamic link libraries.</p>
<p>You load libraries by accessing them as attributes of these objects. <em>cdll</em>
loads libraries which export functions using the standard <code class="docutils literal notranslate"><span class="pre">cdecl</span></code> calling
convention, while <em>windll</em> libraries call functions using the <code class="docutils literal notranslate"><span class="pre">stdcall</span></code>
calling convention. <em>oledll</em> also uses the <code class="docutils literal notranslate"><span class="pre">stdcall</span></code> calling convention, and
assumes the functions return a Windows <code class="xref c c-type docutils literal notranslate"><span class="pre">HRESULT</span></code> error code. The error
code is used to automatically raise a <code class="xref py py-class docutils literal notranslate"><span class="pre">WindowsError</span></code> exception when the
function call fails.</p>
<p>Here are some examples for Windows. Note that <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> is the MS standard C
library containing most standard C functions, and uses the cdecl calling
convention:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span>  
<span class="go">&lt;WinDLL &#39;kernel32&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span>      
<span class="go">&lt;CDLL &#39;msvcrt&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span> <span class="o">=</span> <span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span>     
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Windows appends the usual <code class="docutils literal notranslate"><span class="pre">.dll</span></code> file suffix automatically.</p>
<p>On Linux, it is required to specify the filename <em>including</em> the extension to
load a library, so attribute access can not be used to load libraries. Either the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">LoadLibrary()</span></code> method of the dll loaders should be used, or you should load
the library by creating an instance of CDLL by calling the constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">LoadLibrary</span><span class="p">(</span><span class="s2">&quot;libc.so.6&quot;</span><span class="p">)</span>  
<span class="go">&lt;CDLL &#39;libc.so.6&#39;, handle ... at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span> <span class="o">=</span> <span class="n">CDLL</span><span class="p">(</span><span class="s2">&quot;libc.so.6&quot;</span><span class="p">)</span>       
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span>                           
<span class="go">&lt;CDLL &#39;libc.so.6&#39;, handle ... at ...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="accessing-functions-from-loaded-dlls">
<span id="ctypes-accessing-functions-from-loaded-dlls"></span><h3>15.17.1.2. Accessing functions from loaded dlls<a class="headerlink" href="#accessing-functions-from-loaded-dlls" title="Permalink to this headline">¶</a></h3>
<p>Functions are accessed as attributes of dll objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">printf</span>
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span>  
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">MyOwnFunction</span>     
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;ctypes.py&quot;</span>, line <span class="m">239</span>, in <span class="n">__getattr__</span>
    <span class="n">func</span> <span class="o">=</span> <span class="n">_StdcallFuncPtr</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">function &#39;MyOwnFunction&#39; not found</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that win32 system dlls like <code class="docutils literal notranslate"><span class="pre">kernel32</span></code> and <code class="docutils literal notranslate"><span class="pre">user32</span></code> often export ANSI
as well as UNICODE versions of a function. The UNICODE version is exported with
an <code class="docutils literal notranslate"><span class="pre">W</span></code> appended to the name, while the ANSI version is exported with an <code class="docutils literal notranslate"><span class="pre">A</span></code>
appended to the name. The win32 <code class="docutils literal notranslate"><span class="pre">GetModuleHandle</span></code> function, which returns a
<em>module handle</em> for a given module name, has the following C prototype, and a
macro is used to expose one of them as <code class="docutils literal notranslate"><span class="pre">GetModuleHandle</span></code> depending on whether
UNICODE is defined or not:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">/*</span> <span class="n">ANSI</span> <span class="n">version</span> <span class="o">*/</span>
<span class="n">HMODULE</span> <span class="n">GetModuleHandleA</span><span class="p">(</span><span class="n">LPCSTR</span> <span class="n">lpModuleName</span><span class="p">);</span>
<span class="o">/*</span> <span class="n">UNICODE</span> <span class="n">version</span> <span class="o">*/</span>
<span class="n">HMODULE</span> <span class="n">GetModuleHandleW</span><span class="p">(</span><span class="n">LPCWSTR</span> <span class="n">lpModuleName</span><span class="p">);</span>
</pre></div>
</div>
<p><em>windll</em> does not try to select one of them by magic, you must access the
version you need by specifying <code class="docutils literal notranslate"><span class="pre">GetModuleHandleA</span></code> or <code class="docutils literal notranslate"><span class="pre">GetModuleHandleW</span></code>
explicitly, and then call it with strings or unicode strings
respectively.</p>
<p>Sometimes, dlls export functions with names which aren’t valid Python
identifiers, like <code class="docutils literal notranslate"><span class="pre">&quot;??2&#64;YAPAXI&#64;Z&quot;</span></code>. In this case you have to use
<a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> to retrieve the function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">getattr</span><span class="p">(</span><span class="n">cdll</span><span class="o">.</span><span class="n">msvcrt</span><span class="p">,</span> <span class="s2">&quot;??2@YAPAXI@Z&quot;</span><span class="p">)</span>  
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On Windows, some dlls export functions not by name but by ordinal. These
functions can be accessed by indexing the dll object with the ordinal number:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>  
<span class="go">&lt;_FuncPtr object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;ctypes.py&quot;</span>, line <span class="m">310</span>, in <span class="n">__getitem__</span>
    <span class="n">func</span> <span class="o">=</span> <span class="n">_StdcallFuncPtr</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">function ordinal 0 not found</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions">
<span id="ctypes-calling-functions"></span><h3>15.17.1.3. Calling functions<a class="headerlink" href="#calling-functions" title="Permalink to this headline">¶</a></h3>
<p>You can call these functions like any other Python callable. This example uses
the <code class="docutils literal notranslate"><span class="pre">time()</span></code> function, which returns system time in seconds since the Unix
epoch, and the <code class="docutils literal notranslate"><span class="pre">GetModuleHandleA()</span></code> function, which returns a win32 module
handle.</p>
<p>This example calls both functions with a NULL pointer (<code class="docutils literal notranslate"><span class="pre">None</span></code> should be used
as the NULL pointer):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">libc</span><span class="o">.</span><span class="n">time</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>  
<span class="go">1150640792</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">hex</span><span class="p">(</span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="kc">None</span><span class="p">))</span>  
<span class="go">0x1d000000</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> tries to protect you from calling functions with the wrong number
of arguments or the wrong calling convention.  Unfortunately this only works on
Windows.  It does this by examining the stack after the function returns, so
although an error is raised the function <em>has</em> been called:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">()</span>      
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">Procedure probably called with not enough arguments (4 bytes missing)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">Procedure probably called with too many arguments (4 bytes in excess)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The same exception is raised when you call an <code class="docutils literal notranslate"><span class="pre">stdcall</span></code> function with the
<code class="docutils literal notranslate"><span class="pre">cdecl</span></code> calling convention, or vice versa:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cdll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">Procedure probably called with not enough arguments (4 bytes missing)</span>
<span class="go">&gt;&gt;&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">msvcrt</span><span class="o">.</span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;spam&quot;</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">Procedure probably called with too many arguments (4 bytes in excess)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>To find out the correct calling convention you have to look into the C header
file or the documentation for the function you want to call.</p>
<p>On Windows, <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> uses win32 structured exception handling to prevent
crashes from general protection faults when functions are called with invalid
argument values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span><span class="p">(</span><span class="mi">32</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">WindowsError</span>: <span class="n">exception: access violation reading 0x00000020</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>There are, however, enough ways to crash Python with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>, so you
should be careful anyway.</p>
<p><code class="docutils literal notranslate"><span class="pre">None</span></code>, integers, longs, byte strings and unicode strings are the only native
Python objects that can directly be used as parameters in these function calls.
<code class="docutils literal notranslate"><span class="pre">None</span></code> is passed as a C <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointer, byte strings and unicode strings are
passed as pointer to the memory block that contains their data (<code class="xref c c-type docutils literal notranslate"><span class="pre">char</span> <span class="pre">*</span></code>
or <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span> <span class="pre">*</span></code>).  Python integers and Python longs are passed as the
platforms default C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type, their value is masked to fit into the C
type.</p>
<p>Before we move on calling functions with other parameter types, we have to learn
more about <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> data types.</p>
</div>
<div class="section" id="fundamental-data-types">
<span id="ctypes-fundamental-data-types"></span><h3>15.17.1.4. Fundamental data types<a class="headerlink" href="#fundamental-data-types" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> defines a number of primitive C compatible data types:</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="46%" />
<col width="30%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">ctypes type</th>
<th class="head">C type</th>
<th class="head">Python type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_bool" title="ctypes.c_bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_bool</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code></td>
<td>bool (1)</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_char" title="ctypes.c_char"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code></td>
<td>1-character string</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_wchar" title="ctypes.c_wchar"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_wchar</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code></td>
<td>1-character unicode string</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_byte" title="ctypes.c_byte"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_byte</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_ubyte" title="ctypes.c_ubyte"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ubyte</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_short" title="ctypes.c_short"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_short</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">short</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_ushort" title="ctypes.c_ushort"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ushort</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">short</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_uint" title="ctypes.c_uint"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_uint</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_long</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_ulong" title="ctypes.c_ulong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ulong</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_longlong" title="ctypes.c_longlong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_longlong</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">__int64</span></code> or <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_ulonglong" title="ctypes.c_ulonglong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ulonglong</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">__int64</span></code> or
<code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code></td>
<td>int/long</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_float" title="ctypes.c_float"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_float</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">float</span></code></td>
<td>float</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_double" title="ctypes.c_double"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_double</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code></td>
<td>float</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_longdouble" title="ctypes.c_longdouble"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_longdouble</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">double</span></code></td>
<td>float</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char_p</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char</span> <span class="pre">*</span></code> (NUL terminated)</td>
<td>string or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#ctypes.c_wchar_p" title="ctypes.c_wchar_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_wchar_p</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span> <span class="pre">*</span></code> (NUL terminated)</td>
<td>unicode or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_void_p</span></code></a></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code></td>
<td>int/long or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
</tbody>
</table>
<ol class="arabic simple">
<li>The constructor accepts any object with a truth value.</li>
</ol>
<p>All these types can be created by calling them with an optional initializer of
the correct type and value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c_int</span><span class="p">()</span>
<span class="go">c_long(0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_char_p</span><span class="p">(</span><span class="s2">&quot;Hello, World&quot;</span><span class="p">)</span>
<span class="go">c_char_p(&#39;Hello, World&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_ushort</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">)</span>
<span class="go">c_ushort(65533)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Since these types are mutable, their value can also be changed afterwards:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span>
<span class="go">c_long(42)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span><span class="o">.</span><span class="n">value</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="o">-</span><span class="mi">99</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span><span class="o">.</span><span class="n">value</span>
<span class="go">-99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning a new value to instances of the pointer types <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char_p</span></code></a>,
<a class="reference internal" href="#ctypes.c_wchar_p" title="ctypes.c_wchar_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_wchar_p</span></code></a>, and <a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_void_p</span></code></a> changes the <em>memory location</em> they
point to, <em>not the contents</em> of the memory block (of course not, because Python
strings are immutable):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;Hello, World&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_s</span> <span class="o">=</span> <span class="n">c_char_p</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">c_s</span>
<span class="go">c_char_p(&#39;Hello, World&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c_s</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="s2">&quot;Hi, there&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">c_s</span>
<span class="go">c_char_p(&#39;Hi, there&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">s</span>                 <span class="c1"># first string is unchanged</span>
<span class="go">Hello, World</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You should be careful, however, not to pass them to functions expecting pointers
to mutable memory. If you need mutable memory blocks, ctypes has a
<a class="reference internal" href="#ctypes.create_string_buffer" title="ctypes.create_string_buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_string_buffer()</span></code></a> function which creates these in various ways.  The
current memory block contents can be accessed (or changed) with the <code class="docutils literal notranslate"><span class="pre">raw</span></code>
property; if you want to access it as NUL terminated string, use the <code class="docutils literal notranslate"><span class="pre">value</span></code>
property:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>      <span class="c1"># create a 3 byte buffer, initialized to NUL bytes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">)</span>
<span class="go">3 &#39;\x00\x00\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="s2">&quot;Hello&quot;</span><span class="p">)</span>      <span class="c1"># create a buffer containing a NUL terminated string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">)</span>
<span class="go">6 &#39;Hello\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="go">&#39;Hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="s2">&quot;Hello&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>  <span class="c1"># create a 10 byte buffer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">)</span>
<span class="go">10 &#39;Hello\x00\x00\x00\x00\x00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="s2">&quot;Hi&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">p</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">raw</span><span class="p">)</span>
<span class="go">10 &#39;Hi\x00lo\x00\x00\x00\x00\x00&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#ctypes.create_string_buffer" title="ctypes.create_string_buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_string_buffer()</span></code></a> function replaces the <code class="xref py py-func docutils literal notranslate"><span class="pre">c_buffer()</span></code> function
(which is still available as an alias), as well as the <code class="xref py py-func docutils literal notranslate"><span class="pre">c_string()</span></code> function
from earlier ctypes releases.  To create a mutable memory block containing
unicode characters of the C type <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> use the
<a class="reference internal" href="#ctypes.create_unicode_buffer" title="ctypes.create_unicode_buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_unicode_buffer()</span></code></a> function.</p>
</div>
<div class="section" id="calling-functions-continued">
<span id="ctypes-calling-functions-continued"></span><h3>15.17.1.5. Calling functions, continued<a class="headerlink" href="#calling-functions-continued" title="Permalink to this headline">¶</a></h3>
<p>Note that printf prints to the real standard output channel, <em>not</em> to
<a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a>, so these examples will only work at the console prompt, not
from within <em>IDLE</em> or <em>PythonWin</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">printf</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;Hello, </span><span class="si">%s</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;World!&quot;</span><span class="p">)</span>
<span class="go">Hello, World!</span>
<span class="go">14</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;Hello, %S</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="sa">u</span><span class="s2">&quot;World!&quot;</span><span class="p">)</span>
<span class="go">Hello, World!</span>
<span class="go">14</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2"> bottles of beer</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="go">42 bottles of beer</span>
<span class="go">19</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%f</span><span class="s2"> bottles of beer</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="mf">42.5</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ArgumentError</span>: <span class="n">argument 2: exceptions.TypeError: Don&#39;t know how to convert parameter 2</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>As has been mentioned before, all Python types except integers, strings, and
unicode strings have to be wrapped in their corresponding <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> type, so
that they can be converted to the required C data type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;An int </span><span class="si">%d</span><span class="s2">, a double </span><span class="si">%f</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="mi">1234</span><span class="p">,</span> <span class="n">c_double</span><span class="p">(</span><span class="mf">3.14</span><span class="p">))</span>
<span class="go">An int 1234, a double 3.140000</span>
<span class="go">31</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="calling-functions-with-your-own-custom-data-types">
<span id="ctypes-calling-functions-with-own-custom-data-types"></span><h3>15.17.1.6. Calling functions with your own custom data types<a class="headerlink" href="#calling-functions-with-your-own-custom-data-types" title="Permalink to this headline">¶</a></h3>
<p>You can also customize <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> argument conversion to allow instances of
your own classes be used as function arguments.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> looks for an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">_as_parameter_</span></code> attribute and uses this as the function argument.  Of
course, it must be one of integer, string, or unicode:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Bottles</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">_as_parameter_</span> <span class="o">=</span> <span class="n">number</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bottles</span> <span class="o">=</span> <span class="n">Bottles</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2"> bottles of beer</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">bottles</span><span class="p">)</span>
<span class="go">42 bottles of beer</span>
<span class="go">19</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you don’t want to store the instance’s data in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_as_parameter_</span></code>
instance variable, you could define a <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> which makes the data
available.</p>
</div>
<div class="section" id="specifying-the-required-argument-types-function-prototypes">
<span id="ctypes-specifying-required-argument-types"></span><h3>15.17.1.7. Specifying the required argument types (function prototypes)<a class="headerlink" href="#specifying-the-required-argument-types-function-prototypes" title="Permalink to this headline">¶</a></h3>
<p>It is possible to specify the required argument types of functions exported from
DLLs by setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> attribute.</p>
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> must be a sequence of C data types (the <code class="docutils literal notranslate"><span class="pre">printf</span></code> function is
probably not a good example here, because it takes a variable number and
different types of parameters depending on the format string, on the other hand
this is quite handy to experiment with this feature):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="o">.</span><span class="n">argtypes</span> <span class="o">=</span> <span class="p">[</span><span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="n">c_double</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;String &#39;</span><span class="si">%s</span><span class="s2">&#39;, Int </span><span class="si">%d</span><span class="s2">, Double </span><span class="si">%f</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;Hi&quot;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mf">2.2</span><span class="p">)</span>
<span class="go">String &#39;Hi&#39;, Int 10, Double 2.200000</span>
<span class="go">37</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Specifying a format protects against incompatible argument types (just as a
prototype for a C function), and tries to convert the arguments to valid types:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2"> </span><span class="si">%d</span><span class="s2"> </span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ArgumentError</span>: <span class="n">argument 2: exceptions.TypeError: wrong type</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> </span><span class="si">%d</span><span class="s2"> </span><span class="si">%f</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;X&quot;</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">X 2 3.000000</span>
<span class="go">13</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you have defined your own classes which you pass to function calls, you have
to implement a <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_param()</span></code> class method for them to be able to use them
in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> sequence. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_param()</span></code> class method receives
the Python object passed to the function call, it should do a typecheck or
whatever is needed to make sure this object is acceptable, and then return the
object itself, its <code class="xref py py-attr docutils literal notranslate"><span class="pre">_as_parameter_</span></code> attribute, or whatever you want to
pass as the C function argument in this case. Again, the result should be an
integer, string, unicode, a <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> instance, or an object with an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">_as_parameter_</span></code> attribute.</p>
</div>
<div class="section" id="return-types">
<span id="ctypes-return-types"></span><h3>15.17.1.8. Return types<a class="headerlink" href="#return-types" title="Permalink to this headline">¶</a></h3>
<p>By default functions are assumed to return the C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type.  Other
return types can be specified by setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code> attribute of the
function object.</p>
<p>Here is a more advanced example, it uses the <code class="docutils literal notranslate"><span class="pre">strchr</span></code> function, which expects
a string pointer and a char, and returns a pointer to a string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">strchr</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s2">&quot;d&quot;</span><span class="p">))</span>  
<span class="go">8059983</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">c_char_p</span>   <span class="c1"># c_char_p is a pointer to a string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s2">&quot;d&quot;</span><span class="p">))</span>
<span class="go">&#39;def&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="nb">ord</span><span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">))</span>
<span class="go">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If you want to avoid the <code class="docutils literal notranslate"><span class="pre">ord(&quot;x&quot;)</span></code> calls above, you can set the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> attribute, and the second argument will be converted from a
single character Python string into a C char:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">c_char_p</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="o">.</span><span class="n">argtypes</span> <span class="o">=</span> <span class="p">[</span><span class="n">c_char_p</span><span class="p">,</span> <span class="n">c_char</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="s2">&quot;d&quot;</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="s2">&quot;def&quot;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ArgumentError</span>: <span class="n">argument 2: exceptions.TypeError: one character string expected</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="s2">&quot;x&quot;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strchr</span><span class="p">(</span><span class="s2">&quot;abcdef&quot;</span><span class="p">,</span> <span class="s2">&quot;d&quot;</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You can also use a callable Python object (a function or a class for example) as
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code> attribute, if the foreign function returns an integer.  The
callable will be called with the <em>integer</em> the C function returns, and the
result of this call will be used as the result of your function call. This is
useful to check for error return values and automatically raise an exception:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span> <span class="o">=</span> <span class="n">windll</span><span class="o">.</span><span class="n">kernel32</span><span class="o">.</span><span class="n">GetModuleHandleA</span>  
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">ValidHandle</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">value</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">value</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">ValidHandle</span>  
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="p">(</span><span class="kc">None</span><span class="p">)</span>  
<span class="go">486539264</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetModuleHandle</span><span class="p">(</span><span class="s2">&quot;something silly&quot;</span><span class="p">)</span>  
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n">ValidHandle</span>
<span class="gr">WindowsError</span>: <span class="n">[Errno 126] The specified module could not be found.</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">WinError</span></code> is a function which will call Windows <code class="docutils literal notranslate"><span class="pre">FormatMessage()</span></code> api to
get the string representation of an error code, and <em>returns</em> an exception.
<code class="docutils literal notranslate"><span class="pre">WinError</span></code> takes an optional error code parameter, if no one is used, it calls
<a class="reference internal" href="#ctypes.GetLastError" title="ctypes.GetLastError"><code class="xref py py-func docutils literal notranslate"><span class="pre">GetLastError()</span></code></a> to retrieve it.</p>
<p>Please note that a much more powerful error checking mechanism is available
through the <code class="xref py py-attr docutils literal notranslate"><span class="pre">errcheck</span></code> attribute; see the reference manual for details.</p>
</div>
<div class="section" id="passing-pointers-or-passing-parameters-by-reference">
<span id="ctypes-passing-pointers"></span><h3>15.17.1.9. Passing pointers (or: passing parameters by reference)<a class="headerlink" href="#passing-pointers-or-passing-parameters-by-reference" title="Permalink to this headline">¶</a></h3>
<p>Sometimes a C api function expects a <em>pointer</em> to a data type as parameter,
probably to write into the corresponding location, or if the data is too large
to be passed by value. This is also known as <em>passing parameters by reference</em>.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> exports the <a class="reference internal" href="#ctypes.byref" title="ctypes.byref"><code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code></a> function which is used to pass
parameters by reference.  The same effect can be achieved with the
<a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><code class="xref py py-func docutils literal notranslate"><span class="pre">pointer()</span></code></a> function, although <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><code class="xref py py-func docutils literal notranslate"><span class="pre">pointer()</span></code></a> does a lot more work since it
constructs a real pointer object, so it is faster to use <a class="reference internal" href="#ctypes.byref" title="ctypes.byref"><code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code></a> if you
don’t need the pointer object in Python itself:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">c_float</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">create_string_buffer</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\000</span><span class="s1">&#39;</span> <span class="o">*</span> <span class="mi">32</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="go">0 0.0 &#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">sscanf</span><span class="p">(</span><span class="s2">&quot;1 3.14 Hello&quot;</span><span class="p">,</span> <span class="s2">&quot;</span><span class="si">%d</span><span class="s2"> </span><span class="si">%f</span><span class="s2"> </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span>
<span class="gp">... </span>            <span class="n">byref</span><span class="p">(</span><span class="n">i</span><span class="p">),</span> <span class="n">byref</span><span class="p">(</span><span class="n">f</span><span class="p">),</span> <span class="n">s</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="n">f</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="go">1 3.1400001049 &#39;Hello&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="structures-and-unions">
<span id="ctypes-structures-unions"></span><h3>15.17.1.10. Structures and unions<a class="headerlink" href="#structures-and-unions" title="Permalink to this headline">¶</a></h3>
<p>Structures and unions must derive from the <a class="reference internal" href="#ctypes.Structure" title="ctypes.Structure"><code class="xref py py-class docutils literal notranslate"><span class="pre">Structure</span></code></a> and <a class="reference internal" href="#ctypes.Union" title="ctypes.Union"><code class="xref py py-class docutils literal notranslate"><span class="pre">Union</span></code></a>
base classes which are defined in the <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module. Each subclass must
define a <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code> attribute.  <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code> must be a list of
<em>2-tuples</em>, containing a <em>field name</em> and a <em>field type</em>.</p>
<p>The field type must be a <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> type like <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a>, or any other
derived <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> type: structure, union, array, pointer.</p>
<p>Here is a simple example of a POINT structure, which contains two integers named
<em>x</em> and <em>y</em>, and also shows how to initialize a structure in the constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span>
<span class="go">10 20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">point</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="n">y</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span>
<span class="go">0 5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">too many initializers</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>You can, however, build much more complicated structures.  A structure can
itself contain other structures by using a structure as a field type.</p>
<p>Here is a RECT structure which contains two POINTs named <em>upperleft</em> and
<em>lowerright</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">RECT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;upperleft&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;lowerright&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">rc</span><span class="o">.</span><span class="n">upperleft</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">upperleft</span><span class="o">.</span><span class="n">y</span>
<span class="go">0 5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">rc</span><span class="o">.</span><span class="n">lowerright</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">lowerright</span><span class="o">.</span><span class="n">y</span>
<span class="go">0 0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Nested structures can also be initialized in the constructor in several ways:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">((</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">))</span>
</pre></div>
</div>
<p>Field <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a>s can be retrieved from the <em>class</em>, they are useful
for debugging because they can provide useful information:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">POINT</span><span class="o">.</span><span class="n">x</span>
<span class="go">&lt;Field type=c_long, ofs=0, size=4&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">POINT</span><span class="o">.</span><span class="n">y</span>
<span class="go">&lt;Field type=c_long, ofs=4, size=4&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition warning" id="ctypes-structureunion-alignment-byte-order">
<p class="first admonition-title">Warning</p>
<p class="last"><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> does not support passing unions or structures with bit-fields
to functions by value.  While this may work on 32-bit x86, it’s not
guaranteed by the library to work in the general case.  Unions and
structures with bit-fields should always be passed to functions by pointer.</p>
</div>
</div>
<div class="section" id="structure-union-alignment-and-byte-order">
<h3>15.17.1.11. Structure/union alignment and byte order<a class="headerlink" href="#structure-union-alignment-and-byte-order" title="Permalink to this headline">¶</a></h3>
<p>By default, Structure and Union fields are aligned in the same way the C
compiler does it. It is possible to override this behavior be specifying a
<code class="xref py py-attr docutils literal notranslate"><span class="pre">_pack_</span></code> class attribute in the subclass definition. This must be set to a
positive integer and specifies the maximum alignment for the fields. This is
what <code class="docutils literal notranslate"><span class="pre">#pragma</span> <span class="pre">pack(n)</span></code> also does in MSVC.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> uses the native byte order for Structures and Unions.  To build
structures with non-native byte order, you can use one of the
<a class="reference internal" href="#ctypes.BigEndianStructure" title="ctypes.BigEndianStructure"><code class="xref py py-class docutils literal notranslate"><span class="pre">BigEndianStructure</span></code></a>, <a class="reference internal" href="#ctypes.LittleEndianStructure" title="ctypes.LittleEndianStructure"><code class="xref py py-class docutils literal notranslate"><span class="pre">LittleEndianStructure</span></code></a>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">BigEndianUnion</span></code>, and <code class="xref py py-class docutils literal notranslate"><span class="pre">LittleEndianUnion</span></code> base classes.  These
classes cannot contain pointer fields.</p>
</div>
<div class="section" id="bit-fields-in-structures-and-unions">
<span id="ctypes-bit-fields-in-structures-unions"></span><h3>15.17.1.12. Bit fields in structures and unions<a class="headerlink" href="#bit-fields-in-structures-and-unions" title="Permalink to this headline">¶</a></h3>
<p>It is possible to create structures and unions containing bit fields. Bit fields
are only possible for integer fields, the bit width is specified as the third
item in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code> tuples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Int</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;first_16&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="mi">16</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;second_16&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">,</span> <span class="mi">16</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">Int</span><span class="o">.</span><span class="n">first_16</span>
<span class="go">&lt;Field type=c_long, ofs=0:0, bits=16&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">Int</span><span class="o">.</span><span class="n">second_16</span>
<span class="go">&lt;Field type=c_long, ofs=0:16, bits=16&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="arrays">
<span id="ctypes-arrays"></span><h3>15.17.1.13. Arrays<a class="headerlink" href="#arrays" title="Permalink to this headline">¶</a></h3>
<p>Arrays are sequences, containing a fixed number of instances of the same type.</p>
<p>The recommended way to create array types is by multiplying a data type with a
positive integer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">TenPointsArrayType</span> <span class="o">=</span> <span class="n">POINT</span> <span class="o">*</span> <span class="mi">10</span>
</pre></div>
</div>
<p>Here is an example of a somewhat artificial data type, a structure containing 4
POINTs among other stuff:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyStruct</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="n">c_float</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;point_array&quot;</span><span class="p">,</span> <span class="n">POINT</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">len</span><span class="p">(</span><span class="n">MyStruct</span><span class="p">()</span><span class="o">.</span><span class="n">point_array</span><span class="p">)</span>
<span class="go">4</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Instances are created in the usual way, by calling the class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">arr</span> <span class="o">=</span> <span class="n">TenPointsArrayType</span><span class="p">()</span>
<span class="k">for</span> <span class="n">pt</span> <span class="ow">in</span> <span class="n">arr</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">pt</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">pt</span><span class="o">.</span><span class="n">y</span>
</pre></div>
</div>
<p>The above code print a series of <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">0</span></code> lines, because the array contents is
initialized to zeros.</p>
<p>Initializers of the correct type can also be specified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">TenIntegers</span> <span class="o">=</span> <span class="n">c_int</span> <span class="o">*</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ii</span> <span class="o">=</span> <span class="n">TenIntegers</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ii</span>
<span class="go">&lt;c_long_Array_10 object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ii</span><span class="p">:</span> <span class="nb">print</span> <span class="n">i</span><span class="p">,</span>
<span class="gp">...</span>
<span class="go">1 2 3 4 5 6 7 8 9 10</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="pointers">
<span id="ctypes-pointers"></span><h3>15.17.1.14. Pointers<a class="headerlink" href="#pointers" title="Permalink to this headline">¶</a></h3>
<p>Pointer instances are created by calling the <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><code class="xref py py-func docutils literal notranslate"><span class="pre">pointer()</span></code></a> function on a
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Pointer instances have a <a class="reference internal" href="#ctypes._Pointer.contents" title="ctypes._Pointer.contents"><code class="xref py py-attr docutils literal notranslate"><span class="pre">contents</span></code></a> attribute which
returns the object to which the pointer points, the <code class="docutils literal notranslate"><span class="pre">i</span></code> object above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">c_long(42)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> does not have OOR (original object return), it constructs a
new, equivalent object each time you retrieve an attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="ow">is</span> <span class="n">i</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="ow">is</span> <span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning another <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a> instance to the pointer’s contents attribute
would cause the pointer to point to the memory location where this is stored:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="n">c_int</span><span class="p">(</span><span class="mi">99</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span> <span class="o">=</span> <span class="n">i</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="o">.</span><span class="n">contents</span>
<span class="go">c_long(99)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Pointer instances can also be indexed with integers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Assigning to an integer index changes the pointed to value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span>
<span class="go">c_long(99)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pi</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">22</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span>
<span class="go">c_long(22)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is also possible to use indexes different from 0, but you must know what
you’re doing, just as in C: You can access or change arbitrary memory locations.
Generally you only use this feature if you receive a pointer from a C function,
and you <em>know</em> that the pointer actually points to an array instead of a single
item.</p>
<p>Behind the scenes, the <a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><code class="xref py py-func docutils literal notranslate"><span class="pre">pointer()</span></code></a> function does more than simply create
pointer instances, it has to create pointer <em>types</em> first.  This is done with
the <a class="reference internal" href="#ctypes.POINTER" title="ctypes.POINTER"><code class="xref py py-func docutils literal notranslate"><span class="pre">POINTER()</span></code></a> function, which accepts any <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> type, and returns
a new type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span>
<span class="go">&lt;class &#39;ctypes.LP_c_long&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">expected c_long instead of int</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">PI</span><span class="p">(</span><span class="n">c_int</span><span class="p">(</span><span class="mi">42</span><span class="p">))</span>
<span class="go">&lt;ctypes.LP_c_long object at 0x...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Calling the pointer type without an argument creates a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointer.
<code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointers have a <code class="docutils literal notranslate"><span class="pre">False</span></code> boolean value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">bool</span><span class="p">(</span><span class="n">null_ptr</span><span class="p">)</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> checks for <code class="docutils literal notranslate"><span class="pre">NULL</span></code> when dereferencing pointers (but dereferencing
invalid non-<code class="docutils literal notranslate"><span class="pre">NULL</span></code> pointers would crash Python):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">....</span>
<span class="gr">ValueError</span>: <span class="n">NULL pointer access</span>
<span class="go">&gt;&gt;&gt;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">null_ptr</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1234</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">....</span>
<span class="gr">ValueError</span>: <span class="n">NULL pointer access</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="type-conversions">
<span id="ctypes-type-conversions"></span><h3>15.17.1.15. Type conversions<a class="headerlink" href="#type-conversions" title="Permalink to this headline">¶</a></h3>
<p>Usually, ctypes does strict type checking.  This means, if you have
<code class="docutils literal notranslate"><span class="pre">POINTER(c_int)</span></code> in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> list of a function or as the type of
a member field in a structure definition, only instances of exactly the same
type are accepted.  There are some exceptions to this rule, where ctypes accepts
other objects.  For example, you can pass compatible array instances instead of
pointer types.  So, for <code class="docutils literal notranslate"><span class="pre">POINTER(c_int)</span></code>, ctypes accepts an array of c_int:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Bar</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;count&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s2">&quot;values&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span> <span class="o">=</span> <span class="n">Bar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_int</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">bar</span><span class="o">.</span><span class="n">count</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">bar</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>In addition, if a function argument is explicitly declared to be a pointer type
(such as <code class="docutils literal notranslate"><span class="pre">POINTER(c_int)</span></code>) in <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code>, an object of the pointed
type (<code class="docutils literal notranslate"><span class="pre">c_int</span></code> in this case) can be passed to the function.  ctypes will apply
the required <a class="reference internal" href="#ctypes.byref" title="ctypes.byref"><code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code></a> conversion in this case automatically.</p>
<p>To set a POINTER type field to <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, you can assign <code class="docutils literal notranslate"><span class="pre">None</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="kc">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Sometimes you have instances of incompatible types.  In C, you can cast one type
into another type.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> provides a <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><code class="xref py py-func docutils literal notranslate"><span class="pre">cast()</span></code></a> function which can be
used in the same way.  The <code class="docutils literal notranslate"><span class="pre">Bar</span></code> structure defined above accepts
<code class="docutils literal notranslate"><span class="pre">POINTER(c_int)</span></code> pointers or <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a> arrays for its <code class="docutils literal notranslate"><span class="pre">values</span></code> field,
but not instances of other types:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">incompatible types, c_byte_Array_4 instance instead of LP_c_long instance</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For these cases, the <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><code class="xref py py-func docutils literal notranslate"><span class="pre">cast()</span></code></a> function is handy.</p>
<p>The <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><code class="xref py py-func docutils literal notranslate"><span class="pre">cast()</span></code></a> function can be used to cast a ctypes instance into a pointer
to a different ctypes data type.  <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><code class="xref py py-func docutils literal notranslate"><span class="pre">cast()</span></code></a> takes two parameters, a ctypes
object that is or can be converted to a pointer of some kind, and a ctypes
pointer type.  It returns an instance of the second argument, which references
the same memory block as the first argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cast</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="go">&lt;ctypes.LP_c_long object at ...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>So, <a class="reference internal" href="#ctypes.cast" title="ctypes.cast"><code class="xref py py-func docutils literal notranslate"><span class="pre">cast()</span></code></a> can be used to assign to the <code class="docutils literal notranslate"><span class="pre">values</span></code> field of <code class="docutils literal notranslate"><span class="pre">Bar</span></code> the
structure:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span> <span class="o">=</span> <span class="n">Bar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar</span><span class="o">.</span><span class="n">values</span> <span class="o">=</span> <span class="n">cast</span><span class="p">((</span><span class="n">c_byte</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)(),</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">bar</span><span class="o">.</span><span class="n">values</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="incomplete-types">
<span id="ctypes-incomplete-types"></span><h3>15.17.1.16. Incomplete Types<a class="headerlink" href="#incomplete-types" title="Permalink to this headline">¶</a></h3>
<p><em>Incomplete Types</em> are structures, unions or arrays whose members are not yet
specified. In C, they are specified by forward declarations, which are defined
later:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">struct</span> <span class="n">cell</span><span class="p">;</span> <span class="o">/*</span> <span class="n">forward</span> <span class="n">declaration</span> <span class="o">*/</span>

<span class="n">struct</span> <span class="n">cell</span> <span class="p">{</span>
    <span class="n">char</span> <span class="o">*</span><span class="n">name</span><span class="p">;</span>
    <span class="n">struct</span> <span class="n">cell</span> <span class="o">*</span><span class="nb">next</span><span class="p">;</span>
<span class="p">};</span>
</pre></div>
</div>
<p>The straightforward translation into ctypes code would be this, but it does not
work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">cell</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;next&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">cell</span><span class="p">))]</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">cell</span>
<span class="gr">NameError</span>: <span class="n">name &#39;cell&#39; is not defined</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>because the new <code class="docutils literal notranslate"><span class="pre">class</span> <span class="pre">cell</span></code> is not available in the class statement itself.
In <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>, we can define the <code class="docutils literal notranslate"><span class="pre">cell</span></code> class and set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code>
attribute later, after the class statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">cell</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cell</span><span class="o">.</span><span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                 <span class="p">(</span><span class="s2">&quot;next&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">cell</span><span class="p">))]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Lets try it. We create two instances of <code class="docutils literal notranslate"><span class="pre">cell</span></code>, and let them point to each
other, and finally follow the pointer chain a few times:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span> <span class="o">=</span> <span class="n">cell</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;foo&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span> <span class="o">=</span> <span class="n">cell</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;bar&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">c2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="n">pointer</span><span class="p">(</span><span class="n">c1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">c1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">p</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">p</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">next</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">foo bar foo bar foo bar foo bar</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-functions">
<span id="ctypes-callback-functions"></span><h3>15.17.1.17. Callback functions<a class="headerlink" href="#callback-functions" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> allows creating C callable function pointers from Python callables.
These are sometimes called <em>callback functions</em>.</p>
<p>First, you must create a class for the callback function, the class knows the
calling convention, the return type, and the number and types of arguments this
function will receive.</p>
<p>The CFUNCTYPE factory function creates types for callback functions using the
normal cdecl calling convention, and, on Windows, the WINFUNCTYPE factory
function creates types for callback functions using the stdcall calling
convention.</p>
<p>Both of these factory functions are called with the result type as first
argument, and the callback functions expected argument types as the remaining
arguments.</p>
<p>I will present an example here which uses the standard C library’s <code class="xref py py-func docutils literal notranslate"><span class="pre">qsort()</span></code>
function, this is used to sort items with the help of a callback function.
<code class="xref py py-func docutils literal notranslate"><span class="pre">qsort()</span></code> will be used to sort an array of integers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">IntArray5</span> <span class="o">=</span> <span class="n">c_int</span> <span class="o">*</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ia</span> <span class="o">=</span> <span class="n">IntArray5</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">33</span><span class="p">,</span> <span class="mi">99</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">qsort</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="kc">None</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">qsort()</span></code> must be called with a pointer to the data to sort, the number of
items in the data array, the size of one item, and a pointer to the comparison
function, the callback. The callback will then be called with two pointers to
items, and it must return a negative integer if the first item is smaller than
the second, a zero if they are equal, and a positive integer else.</p>
<p>So our callback function receives pointers to integers, and must return an
integer. First we create the <code class="docutils literal notranslate"><span class="pre">type</span></code> for the callback function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">CMPFUNC</span> <span class="o">=</span> <span class="n">CFUNCTYPE</span><span class="p">(</span><span class="n">c_int</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_int</span><span class="p">))</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For the first implementation of the callback function, we simply print the
arguments we get, and return 0 (incremental development ;-):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="mi">0</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Create the C callable callback:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cmp_func</span> <span class="o">=</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>And we’re ready to go:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span> 
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">py_cmp_func &lt;ctypes.LP_c_long object at 0x00...&gt; &lt;ctypes.LP_c_long object at 0x00...&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>We know how to access the contents of a pointer, so lets redefine our callback:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cmp_func</span> <span class="o">=</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Here is what we get on Windows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span> 
<span class="go">py_cmp_func 7 1</span>
<span class="go">py_cmp_func 33 1</span>
<span class="go">py_cmp_func 99 1</span>
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 7 5</span>
<span class="go">py_cmp_func 33 5</span>
<span class="go">py_cmp_func 99 5</span>
<span class="go">py_cmp_func 7 99</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is funny to see that on linux the sort function seems to work much more
efficiently, it is doing less comparisons:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">cmp_func</span><span class="p">)</span>  
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Ah, we’re nearly done! The last step is to actually compare the two items and
return a useful result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">py_cmp_func</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;py_cmp_func&quot;</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-</span> <span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Final run on Windows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">))</span> 
<span class="go">py_cmp_func 33 7</span>
<span class="go">py_cmp_func 99 33</span>
<span class="go">py_cmp_func 5 99</span>
<span class="go">py_cmp_func 1 99</span>
<span class="go">py_cmp_func 33 7</span>
<span class="go">py_cmp_func 1 33</span>
<span class="go">py_cmp_func 5 33</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">py_cmp_func 5 1</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>and on Linux:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">qsort</span><span class="p">(</span><span class="n">ia</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">ia</span><span class="p">),</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">c_int</span><span class="p">),</span> <span class="n">CMPFUNC</span><span class="p">(</span><span class="n">py_cmp_func</span><span class="p">))</span> 
<span class="go">py_cmp_func 5 1</span>
<span class="go">py_cmp_func 33 99</span>
<span class="go">py_cmp_func 7 33</span>
<span class="go">py_cmp_func 1 7</span>
<span class="go">py_cmp_func 5 7</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It is quite interesting to see that the Windows <code class="xref py py-func docutils literal notranslate"><span class="pre">qsort()</span></code> function needs
more comparisons than the linux version!</p>
<p>As we can easily check, our array is sorted now:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ia</span><span class="p">:</span> <span class="nb">print</span> <span class="n">i</span><span class="p">,</span>
<span class="gp">...</span>
<span class="go">1 5 7 33 99</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Make sure you keep references to <a class="reference internal" href="#ctypes.CFUNCTYPE" title="ctypes.CFUNCTYPE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CFUNCTYPE()</span></code></a> objects as long as they
are used from C code. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> doesn’t, and if you don’t, they may be
garbage collected, crashing your program when a callback is made.</p>
<p class="last">Also, note that if the callback function is called in a thread created
outside of Python’s control (e.g. by the foreign code that calls the
callback), ctypes creates a new dummy Python thread on every invocation. This
behavior is correct for most purposes, but it means that values stored with
<a class="reference internal" href="threading.html#threading.local" title="threading.local"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.local</span></code></a> will <em>not</em> survive across different callbacks, even when
those calls are made from the same C thread.</p>
</div>
</div>
<div class="section" id="accessing-values-exported-from-dlls">
<span id="ctypes-accessing-values-exported-from-dlls"></span><h3>15.17.1.18. Accessing values exported from dlls<a class="headerlink" href="#accessing-values-exported-from-dlls" title="Permalink to this headline">¶</a></h3>
<p>Some shared libraries not only export functions, they also export variables. An
example in the Python library itself is the <code class="docutils literal notranslate"><span class="pre">Py_OptimizeFlag</span></code>, an integer set
to 0, 1, or 2, depending on the <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-oo"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a> flag given on
startup.</p>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> can access values like this with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">in_dll()</span></code> class methods of
the type.  <em>pythonapi</em> is a predefined symbol giving access to the Python C
api:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">opt_flag</span> <span class="o">=</span> <span class="n">c_int</span><span class="o">.</span><span class="n">in_dll</span><span class="p">(</span><span class="n">pythonapi</span><span class="p">,</span> <span class="s2">&quot;Py_OptimizeFlag&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">opt_flag</span>
<span class="go">c_long(0)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If the interpreter would have been started with <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a>, the sample would
have printed <code class="docutils literal notranslate"><span class="pre">c_long(1)</span></code>, or <code class="docutils literal notranslate"><span class="pre">c_long(2)</span></code> if <a class="reference internal" href="../using/cmdline.html#cmdoption-oo"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a> would have been
specified.</p>
<p>An extended example which also demonstrates the use of pointers accesses the
<code class="docutils literal notranslate"><span class="pre">PyImport_FrozenModules</span></code> pointer exported by Python.</p>
<p>Quoting the Python docs: <em>This pointer is initialized to point to an array of
“struct _frozen” records, terminated by one whose members are all NULL or zero.
When a frozen module is imported, it is searched in this table. Third-party code
could play tricks with this to provide a dynamically created collection of
frozen modules.</em></p>
<p>So manipulating this pointer could even prove useful. To restrict the example
size, we show only how this table can be read with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">struct_frozen</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;name&quot;</span><span class="p">,</span> <span class="n">c_char_p</span><span class="p">),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;code&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">c_ubyte</span><span class="p">)),</span>
<span class="gp">... </span>                <span class="p">(</span><span class="s2">&quot;size&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)]</span>
<span class="gp">...</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>We have defined the <code class="docutils literal notranslate"><span class="pre">struct</span> <span class="pre">_frozen</span></code> data type, so we can get the pointer to
the table:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">FrozenTable</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">struct_frozen</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="n">FrozenTable</span><span class="o">.</span><span class="n">in_dll</span><span class="p">(</span><span class="n">pythonapi</span><span class="p">,</span> <span class="s2">&quot;PyImport_FrozenModules&quot;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Since <code class="docutils literal notranslate"><span class="pre">table</span></code> is a <code class="docutils literal notranslate"><span class="pre">pointer</span></code> to the array of <code class="docutils literal notranslate"><span class="pre">struct_frozen</span></code> records, we
can iterate over it, but we just have to make sure that our loop terminates,
because pointers have no size. Sooner or later it would probably crash with an
access violation or whatever, so it’s better to break out of the loop when we
hit the NULL entry:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">table</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">item</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">item</span><span class="o">.</span><span class="n">size</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">item</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">break</span>
<span class="gp">...</span>
<span class="go">__hello__ 104</span>
<span class="go">__phello__ -104</span>
<span class="go">__phello__.spam 104</span>
<span class="go">None 0</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The fact that standard Python has a frozen module and a frozen package
(indicated by the negative size member) is not well known, it is only used for
testing. Try it out with <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">__hello__</span></code> for example.</p>
</div>
<div class="section" id="surprises">
<span id="ctypes-surprises"></span><h3>15.17.1.19. Surprises<a class="headerlink" href="#surprises" title="Permalink to this headline">¶</a></h3>
<p>There are some edge cases in <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> where you might expect something
other than what actually happens.</p>
<p>Consider the following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">POINT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;x&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">),</span> <span class="p">(</span><span class="s2">&quot;y&quot;</span><span class="p">,</span> <span class="n">c_int</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">RECT</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">),</span> <span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,</span> <span class="n">POINT</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p1</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p2</span> <span class="o">=</span> <span class="n">POINT</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span> <span class="o">=</span> <span class="n">RECT</span><span class="p">(</span><span class="n">p1</span><span class="p">,</span> <span class="n">p2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">y</span>
<span class="go">1 2 3 4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># now swap the two points</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span><span class="o">.</span><span class="n">y</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="o">.</span><span class="n">y</span>
<span class="go">3 4 3 4</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Hm. We certainly expected the last statement to print <code class="docutils literal notranslate"><span class="pre">3</span> <span class="pre">4</span> <span class="pre">1</span> <span class="pre">2</span></code>. What
happened? Here are the steps of the <code class="docutils literal notranslate"><span class="pre">rc.a,</span> <span class="pre">rc.b</span> <span class="pre">=</span> <span class="pre">rc.b,</span> <span class="pre">rc.a</span></code> line above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">temp0</span><span class="p">,</span> <span class="n">temp1</span> <span class="o">=</span> <span class="n">rc</span><span class="o">.</span><span class="n">b</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">a</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="n">temp0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rc</span><span class="o">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">temp1</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">temp0</span></code> and <code class="docutils literal notranslate"><span class="pre">temp1</span></code> are objects still using the internal buffer of
the <code class="docutils literal notranslate"><span class="pre">rc</span></code> object above. So executing <code class="docutils literal notranslate"><span class="pre">rc.a</span> <span class="pre">=</span> <span class="pre">temp0</span></code> copies the buffer
contents of <code class="docutils literal notranslate"><span class="pre">temp0</span></code> into <code class="docutils literal notranslate"><span class="pre">rc</span></code> ‘s buffer.  This, in turn, changes the
contents of <code class="docutils literal notranslate"><span class="pre">temp1</span></code>. So, the last assignment <code class="docutils literal notranslate"><span class="pre">rc.b</span> <span class="pre">=</span> <span class="pre">temp1</span></code>, doesn’t have
the expected effect.</p>
<p>Keep in mind that retrieving sub-objects from Structure, Unions, and Arrays
doesn’t <em>copy</em> the sub-object, instead it retrieves a wrapper object accessing
the root-object’s underlying buffer.</p>
<p>Another example that may behave different from what one would expect is this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">c_char_p</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="s2">&quot;abc def ghi&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span>
<span class="go">&#39;abc def ghi&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">value</span> <span class="ow">is</span> <span class="n">s</span><span class="o">.</span><span class="n">value</span>
<span class="go">False</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Why is it printing <code class="docutils literal notranslate"><span class="pre">False</span></code>?  ctypes instances are objects containing a memory
block plus some <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a>s accessing the contents of the memory.
Storing a Python object in the memory block does not store the object itself,
instead the <code class="docutils literal notranslate"><span class="pre">contents</span></code> of the object is stored.  Accessing the contents again
constructs a new Python object each time!</p>
</div>
<div class="section" id="variable-sized-data-types">
<span id="ctypes-variable-sized-data-types"></span><h3>15.17.1.20. Variable-sized data types<a class="headerlink" href="#variable-sized-data-types" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> provides some support for variable-sized arrays and structures.</p>
<p>The <a class="reference internal" href="#ctypes.resize" title="ctypes.resize"><code class="xref py py-func docutils literal notranslate"><span class="pre">resize()</span></code></a> function can be used to resize the memory buffer of an
existing ctypes object.  The function takes the object as first argument, and
the requested size in bytes as the second argument.  The memory block cannot be
made smaller than the natural memory block specified by the objects type, a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised if this is tried:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span> <span class="o">=</span> <span class="p">(</span><span class="n">c_short</span> <span class="o">*</span> <span class="mi">4</span><span class="p">)()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sizeof</span><span class="p">(</span><span class="n">short_array</span><span class="p">)</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resize</span><span class="p">(</span><span class="n">short_array</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">ValueError</span>: <span class="n">minimum size is 8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resize</span><span class="p">(</span><span class="n">short_array</span><span class="p">,</span> <span class="mi">32</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sizeof</span><span class="p">(</span><span class="n">short_array</span><span class="p">)</span>
<span class="go">32</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sizeof</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">short_array</span><span class="p">))</span>
<span class="go">8</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>This is nice and fine, but how would one access the additional elements
contained in this array?  Since the type still only knows about 4 elements, we
get errors accessing other elements:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span><span class="p">[:]</span>
<span class="go">[0, 0, 0, 0]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">short_array</span><span class="p">[</span><span class="mi">7</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">IndexError</span>: <span class="n">invalid index</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Another way to use variable-sized data types with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> is to use the
dynamic nature of Python, and (re-)define the data type after the required size
is already known, on a case by case basis.</p>
</div>
</div>
<div class="section" id="ctypes-reference">
<span id="ctypes-ctypes-reference"></span><h2>15.17.2. ctypes reference<a class="headerlink" href="#ctypes-reference" title="Permalink to this headline">¶</a></h2>
<div class="section" id="finding-shared-libraries">
<span id="ctypes-finding-shared-libraries"></span><h3>15.17.2.1. Finding shared libraries<a class="headerlink" href="#finding-shared-libraries" title="Permalink to this headline">¶</a></h3>
<p>When programming in a compiled language, shared libraries are accessed when
compiling/linking a program, and when the program is run.</p>
<p>The purpose of the <code class="xref py py-func docutils literal notranslate"><span class="pre">find_library()</span></code> function is to locate a library in a way
similar to what the compiler does (on platforms with several versions of a
shared library the most recent should be loaded), while the ctypes library
loaders act like when a program is run, and call the runtime loader directly.</p>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes.util</span></code> module provides a function which can help to determine the
library to load.</p>
<dl class="data">
<dt>
<code class="descclassname">ctypes.util.</code><code class="descname">find_library</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span></dt>
<dd><p>Try to find a library and return a pathname.  <em>name</em> is the library name without
any prefix like <em>lib</em>, suffix like <code class="docutils literal notranslate"><span class="pre">.so</span></code>, <code class="docutils literal notranslate"><span class="pre">.dylib</span></code> or version number (this
is the form used for the posix linker option <code class="xref std std-option docutils literal notranslate"><span class="pre">-l</span></code>).  If no library can
be found, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<p>The exact functionality is system dependent.</p>
<p>On Linux, <code class="xref py py-func docutils literal notranslate"><span class="pre">find_library()</span></code> tries to run external programs
(<code class="docutils literal notranslate"><span class="pre">/sbin/ldconfig</span></code>, <code class="docutils literal notranslate"><span class="pre">gcc</span></code>, and <code class="docutils literal notranslate"><span class="pre">objdump</span></code>) to find the library file.  It
returns the filename of the library file.  Here are some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.util</span> <span class="k">import</span> <span class="n">find_library</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;m&quot;</span><span class="p">)</span>
<span class="go">&#39;libm.so.6&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">)</span>
<span class="go">&#39;libc.so.6&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;bz2&quot;</span><span class="p">)</span>
<span class="go">&#39;libbz2.so.1.0&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On OS X, <code class="xref py py-func docutils literal notranslate"><span class="pre">find_library()</span></code> tries several predefined naming schemes and paths
to locate the library, and returns a full pathname if successful:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.util</span> <span class="k">import</span> <span class="n">find_library</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libc.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;m&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libm.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;bz2&quot;</span><span class="p">)</span>
<span class="go">&#39;/usr/lib/libbz2.dylib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">find_library</span><span class="p">(</span><span class="s2">&quot;AGL&quot;</span><span class="p">)</span>
<span class="go">&#39;/System/Library/Frameworks/AGL.framework/AGL&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>On Windows, <code class="xref py py-func docutils literal notranslate"><span class="pre">find_library()</span></code> searches along the system search path, and
returns the full pathname, but since there is no predefined naming scheme a call
like <code class="docutils literal notranslate"><span class="pre">find_library(&quot;c&quot;)</span></code> will fail and return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>If wrapping a shared library with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>, it <em>may</em> be better to determine
the shared library name at development time, and hardcode that into the wrapper
module instead of using <code class="xref py py-func docutils literal notranslate"><span class="pre">find_library()</span></code> to locate the library at runtime.</p>
</div>
<div class="section" id="loading-shared-libraries">
<span id="ctypes-loading-shared-libraries"></span><h3>15.17.2.2. Loading shared libraries<a class="headerlink" href="#loading-shared-libraries" title="Permalink to this headline">¶</a></h3>
<p>There are several ways to load shared libraries into the Python process.  One
way is to instantiate one of the following classes:</p>
<dl class="class">
<dt id="ctypes.CDLL">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">CDLL</code><span class="sig-paren">(</span><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.CDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class represent loaded shared libraries. Functions in these
libraries use the standard C calling convention, and are assumed to return
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.OleDLL">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">OleDLL</code><span class="sig-paren">(</span><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.OleDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Instances of this class represent loaded shared libraries,
functions in these libraries use the <code class="docutils literal notranslate"><span class="pre">stdcall</span></code> calling convention, and are
assumed to return the windows specific <a class="reference internal" href="#ctypes.HRESULT" title="ctypes.HRESULT"><code class="xref py py-class docutils literal notranslate"><span class="pre">HRESULT</span></code></a> code.  <a class="reference internal" href="#ctypes.HRESULT" title="ctypes.HRESULT"><code class="xref py py-class docutils literal notranslate"><span class="pre">HRESULT</span></code></a>
values contain information specifying whether the function call failed or
succeeded, together with additional error code.  If the return value signals a
failure, an <code class="xref py py-class docutils literal notranslate"><span class="pre">WindowsError</span></code> is automatically raised.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.WinDLL">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">WinDLL</code><span class="sig-paren">(</span><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.WinDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Instances of this class represent loaded shared libraries,
functions in these libraries use the <code class="docutils literal notranslate"><span class="pre">stdcall</span></code> calling convention, and are
assumed to return <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> by default.</p>
<p>On Windows CE only the standard calling convention is used, for convenience the
<a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">WinDLL</span></code></a> and <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">OleDLL</span></code></a> use the standard calling convention on this
platform.</p>
</dd></dl>

<p>The Python <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">global interpreter lock</span></a> is released before calling any
function exported by these libraries, and reacquired afterwards.</p>
<dl class="class">
<dt id="ctypes.PyDLL">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">PyDLL</code><span class="sig-paren">(</span><em>name</em>, <em>mode=DEFAULT_MODE</em>, <em>handle=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.PyDLL" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of this class behave like <a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code></a> instances, except that the
Python GIL is <em>not</em> released during the function call, and after the function
execution the Python error flag is checked. If the error flag is set, a Python
exception is raised.</p>
<p>Thus, this is only useful to call Python C api functions directly.</p>
</dd></dl>

<p>All these classes can be instantiated by calling them with at least one
argument, the pathname of the shared library.  If you have an existing handle to
an already loaded shared library, it can be passed as the <code class="docutils literal notranslate"><span class="pre">handle</span></code> named
parameter, otherwise the underlying platforms <code class="docutils literal notranslate"><span class="pre">dlopen</span></code> or <code class="docutils literal notranslate"><span class="pre">LoadLibrary</span></code>
function is used to load the library into the process, and to get a handle to
it.</p>
<p>The <em>mode</em> parameter can be used to specify how the library is loaded.  For
details, consult the <em class="manpage">dlopen(3)</em> manpage.  On Windows, <em>mode</em> is
ignored.  On posix systems, RTLD_NOW is always added, and is not
configurable.</p>
<p>The <em>use_errno</em> parameter, when set to true, enables a ctypes mechanism that
allows accessing the system <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a> error number in a safe way.
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> maintains a thread-local copy of the systems <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a>
variable; if you call foreign functions created with <code class="docutils literal notranslate"><span class="pre">use_errno=True</span></code> then the
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a> value before the function call is swapped with the ctypes private
copy, the same happens immediately after the function call.</p>
<p>The function <a class="reference internal" href="#ctypes.get_errno" title="ctypes.get_errno"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctypes.get_errno()</span></code></a> returns the value of the ctypes private
copy, and the function <a class="reference internal" href="#ctypes.set_errno" title="ctypes.set_errno"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctypes.set_errno()</span></code></a> changes the ctypes private copy
to a new value and returns the former value.</p>
<p>The <em>use_last_error</em> parameter, when set to true, enables the same mechanism for
the Windows error code which is managed by the <a class="reference internal" href="#ctypes.GetLastError" title="ctypes.GetLastError"><code class="xref py py-func docutils literal notranslate"><span class="pre">GetLastError()</span></code></a> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">SetLastError()</span></code> Windows API functions; <a class="reference internal" href="#ctypes.get_last_error" title="ctypes.get_last_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctypes.get_last_error()</span></code></a> and
<a class="reference internal" href="#ctypes.set_last_error" title="ctypes.set_last_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctypes.set_last_error()</span></code></a> are used to request and change the ctypes private
copy of the windows error code.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The <em>use_last_error</em> and <em>use_errno</em> optional parameters were added.</p>
</div>
<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">RTLD_GLOBAL</code></dt>
<dd><p>Flag to use as <em>mode</em> parameter.  On platforms where this flag is not available,
it is defined as the integer zero.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">RTLD_LOCAL</code></dt>
<dd><p>Flag to use as <em>mode</em> parameter.  On platforms where this is not available, it
is the same as <em>RTLD_GLOBAL</em>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">DEFAULT_MODE</code></dt>
<dd><p>The default mode which is used to load shared libraries.  On OSX 10.3, this is
<em>RTLD_GLOBAL</em>, otherwise it is the same as <em>RTLD_LOCAL</em>.</p>
</dd></dl>

<p>Instances of these classes have no public methods.  Functions exported by the
shared library can be accessed as attributes or by index.  Please note that
accessing the function through an attribute caches the result and therefore
accessing it repeatedly returns the same object each time.  On the other hand,
accessing it through an index returns a new object each time:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">time</span> <span class="o">==</span> <span class="n">libc</span><span class="o">.</span><span class="n">time</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="p">[</span><span class="s1">&#39;time&#39;</span><span class="p">]</span> <span class="o">==</span> <span class="n">libc</span><span class="p">[</span><span class="s1">&#39;time&#39;</span><span class="p">]</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The following public attributes are available, their name starts with an
underscore to not clash with exported function names:</p>
<dl class="attribute">
<dt id="ctypes.PyDLL._handle">
<code class="descclassname">PyDLL.</code><code class="descname">_handle</code><a class="headerlink" href="#ctypes.PyDLL._handle" title="Permalink to this definition">¶</a></dt>
<dd><p>The system handle used to access the library.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.PyDLL._name">
<code class="descclassname">PyDLL.</code><code class="descname">_name</code><a class="headerlink" href="#ctypes.PyDLL._name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the library passed in the constructor.</p>
</dd></dl>

<p>Shared libraries can also be loaded by using one of the prefabricated objects,
which are instances of the <a class="reference internal" href="#ctypes.LibraryLoader" title="ctypes.LibraryLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">LibraryLoader</span></code></a> class, either by calling the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">LoadLibrary()</span></code> method, or by retrieving the library as attribute of the
loader instance.</p>
<dl class="class">
<dt id="ctypes.LibraryLoader">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">LibraryLoader</code><span class="sig-paren">(</span><em>dlltype</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.LibraryLoader" title="Permalink to this definition">¶</a></dt>
<dd><p>Class which loads shared libraries.  <em>dlltype</em> should be one of the
<a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code></a>, <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">PyDLL</span></code></a>, <a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">WinDLL</span></code></a>, or <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">OleDLL</span></code></a> types.</p>
<p><a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> has special behavior: It allows loading a shared library by
accessing it as attribute of a library loader instance.  The result is cached,
so repeated attribute accesses return the same library each time.</p>
<dl class="method">
<dt id="ctypes.LibraryLoader.LoadLibrary">
<code class="descname">LoadLibrary</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.LibraryLoader.LoadLibrary" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a shared library into the process and return it.  This method always
returns a new instance of the library.</p>
</dd></dl>

</dd></dl>

<p>These prefabricated library loaders are available:</p>
<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">cdll</code></dt>
<dd><p>Creates <a class="reference internal" href="#ctypes.CDLL" title="ctypes.CDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">windll</code></dt>
<dd><p>Windows only: Creates <a class="reference internal" href="#ctypes.WinDLL" title="ctypes.WinDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">WinDLL</span></code></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">oledll</code></dt>
<dd><p>Windows only: Creates <a class="reference internal" href="#ctypes.OleDLL" title="ctypes.OleDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">OleDLL</span></code></a> instances.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">pydll</code></dt>
<dd><p>Creates <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">PyDLL</span></code></a> instances.</p>
</dd></dl>

<p>For accessing the C Python api directly, a ready-to-use Python shared library
object is available:</p>
<dl class="data">
<dt>
<code class="descclassname">ctypes.</code><code class="descname">pythonapi</code></dt>
<dd><p>An instance of <a class="reference internal" href="#ctypes.PyDLL" title="ctypes.PyDLL"><code class="xref py py-class docutils literal notranslate"><span class="pre">PyDLL</span></code></a> that exposes Python C API functions as
attributes.  Note that all these functions are assumed to return C
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>, which is of course not always the truth, so you have to assign
the correct <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code> attribute to use these functions.</p>
</dd></dl>

</div>
<div class="section" id="foreign-functions">
<span id="ctypes-foreign-functions"></span><h3>15.17.2.3. Foreign functions<a class="headerlink" href="#foreign-functions" title="Permalink to this headline">¶</a></h3>
<p>As explained in the previous section, foreign functions can be accessed as
attributes of loaded shared libraries.  The function objects created in this way
by default accept any number of arguments, accept any ctypes data instances as
arguments, and return the default result type specified by the library loader.
They are instances of a private class:</p>
<dl class="class">
<dt id="ctypes._FuncPtr">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">_FuncPtr</code><a class="headerlink" href="#ctypes._FuncPtr" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for C callable foreign functions.</p>
<p>Instances of foreign functions are also C compatible data types; they
represent C function pointers.</p>
<p>This behavior can be customized by assigning to special attributes of the
foreign function object.</p>
<dl class="attribute">
<dt id="ctypes._FuncPtr.restype">
<code class="descname">restype</code><a class="headerlink" href="#ctypes._FuncPtr.restype" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a ctypes type to specify the result type of the foreign function.
Use <code class="docutils literal notranslate"><span class="pre">None</span></code> for <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span></code>, a function not returning anything.</p>
<p>It is possible to assign a callable Python object that is not a ctypes
type, in this case the function is assumed to return a C <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>, and
the callable will be called with this integer, allowing further
processing or error checking.  Using this is deprecated, for more flexible
post processing or error checking use a ctypes data type as
<a class="reference internal" href="#ctypes._FuncPtr.restype" title="ctypes._FuncPtr.restype"><code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code></a> and assign a callable to the <a class="reference internal" href="#ctypes._FuncPtr.errcheck" title="ctypes._FuncPtr.errcheck"><code class="xref py py-attr docutils literal notranslate"><span class="pre">errcheck</span></code></a> attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._FuncPtr.argtypes">
<code class="descname">argtypes</code><a class="headerlink" href="#ctypes._FuncPtr.argtypes" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a tuple of ctypes types to specify the argument types that the
function accepts.  Functions using the <code class="docutils literal notranslate"><span class="pre">stdcall</span></code> calling convention can
only be called with the same number of arguments as the length of this
tuple; functions using the C calling convention accept additional,
unspecified arguments as well.</p>
<p>When a foreign function is called, each actual argument is passed to the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">from_param()</span></code> class method of the items in the <a class="reference internal" href="#ctypes._FuncPtr.argtypes" title="ctypes._FuncPtr.argtypes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code></a>
tuple, this method allows adapting the actual argument to an object that
the foreign function accepts.  For example, a <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char_p</span></code></a> item in
the <a class="reference internal" href="#ctypes._FuncPtr.argtypes" title="ctypes._FuncPtr.argtypes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code></a> tuple will convert a unicode string passed as
argument into a byte string using ctypes conversion rules.</p>
<p>New: It is now possible to put items in argtypes which are not ctypes
types, but each item must have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_param()</span></code> method which returns a
value usable as argument (integer, string, ctypes instance).  This allows
defining adapters that can adapt custom objects as function parameters.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._FuncPtr.errcheck">
<code class="descname">errcheck</code><a class="headerlink" href="#ctypes._FuncPtr.errcheck" title="Permalink to this definition">¶</a></dt>
<dd><p>Assign a Python function or another callable to this attribute. The
callable will be called with three or more arguments:</p>
<dl class="function">
<dt>
<code class="descname">callable</code><span class="sig-paren">(</span><em>result</em>, <em>func</em>, <em>arguments</em><span class="sig-paren">)</span></dt>
<dd><p><em>result</em> is what the foreign function returns, as specified by the
<a class="reference internal" href="#ctypes._FuncPtr.restype" title="ctypes._FuncPtr.restype"><code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code></a> attribute.</p>
<p><em>func</em> is the foreign function object itself, this allows reusing the
same callable object to check or post process the results of several
functions.</p>
<p><em>arguments</em> is a tuple containing the parameters originally passed to
the function call, this allows specializing the behavior on the
arguments used.</p>
</dd></dl>

<p>The object that this function returns will be returned from the
foreign function call, but it can also check the result value
and raise an exception if the foreign function call failed.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="ctypes.ArgumentError">
<em class="property">exception </em><code class="descclassname">ctypes.</code><code class="descname">ArgumentError</code><a class="headerlink" href="#ctypes.ArgumentError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a foreign function call cannot convert one of the
passed arguments.</p>
</dd></dl>

</div>
<div class="section" id="function-prototypes">
<span id="ctypes-function-prototypes"></span><h3>15.17.2.4. Function prototypes<a class="headerlink" href="#function-prototypes" title="Permalink to this headline">¶</a></h3>
<p>Foreign functions can also be created by instantiating function prototypes.
Function prototypes are similar to function prototypes in C; they describe a
function (return type, argument types, calling convention) without defining an
implementation.  The factory functions must be called with the desired result
type and the argument types of the function.</p>
<dl class="function">
<dt id="ctypes.CFUNCTYPE">
<code class="descclassname">ctypes.</code><code class="descname">CFUNCTYPE</code><span class="sig-paren">(</span><em>restype</em>, <em>*argtypes</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.CFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>The returned function prototype creates functions that use the standard C
calling convention.  The function will release the GIL during the call.  If
<em>use_errno</em> is set to true, the ctypes private copy of the system
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a> variable is exchanged with the real <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a> value before
and after the call; <em>use_last_error</em> does the same for the Windows error
code.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The optional <em>use_errno</em> and <em>use_last_error</em> parameters were added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.WINFUNCTYPE">
<code class="descclassname">ctypes.</code><code class="descname">WINFUNCTYPE</code><span class="sig-paren">(</span><em>restype</em>, <em>*argtypes</em>, <em>use_errno=False</em>, <em>use_last_error=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.WINFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: The returned function prototype creates functions that use the
<code class="docutils literal notranslate"><span class="pre">stdcall</span></code> calling convention, except on Windows CE where
<a class="reference internal" href="#ctypes.WINFUNCTYPE" title="ctypes.WINFUNCTYPE"><code class="xref py py-func docutils literal notranslate"><span class="pre">WINFUNCTYPE()</span></code></a> is the same as <a class="reference internal" href="#ctypes.CFUNCTYPE" title="ctypes.CFUNCTYPE"><code class="xref py py-func docutils literal notranslate"><span class="pre">CFUNCTYPE()</span></code></a>.  The function will
release the GIL during the call.  <em>use_errno</em> and <em>use_last_error</em> have the
same meaning as above.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.PYFUNCTYPE">
<code class="descclassname">ctypes.</code><code class="descname">PYFUNCTYPE</code><span class="sig-paren">(</span><em>restype</em>, <em>*argtypes</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.PYFUNCTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>The returned function prototype creates functions that use the Python calling
convention.  The function will <em>not</em> release the GIL during the call.</p>
</dd></dl>

<p>Function prototypes created by these factory functions can be instantiated in
different ways, depending on the type and number of the parameters in the call:</p>
<blockquote>
<div><dl class="function">
<dt>
<code class="descname">prototype</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span></dt>
<dd><p>Returns a foreign function at the specified address which must be an integer.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descname">prototype</code><span class="sig-paren">(</span><em>callable</em><span class="sig-paren">)</span></dt>
<dd><p>Create a C callable function (a callback function) from a Python <em>callable</em>.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descname">prototype</code><span class="sig-paren">(</span><em>func_spec</em><span class="optional">[</span>, <em>paramflags</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a foreign function exported by a shared library. <em>func_spec</em> must be a
2-tuple <code class="docutils literal notranslate"><span class="pre">(name_or_ordinal,</span> <span class="pre">library)</span></code>. The first item is the name of the
exported function as string, or the ordinal of the exported function as small
integer.  The second item is the shared library instance.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descname">prototype</code><span class="sig-paren">(</span><em>vtbl_index</em>, <em>name</em><span class="optional">[</span>, <em>paramflags</em><span class="optional">[</span>, <em>iid</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Returns a foreign function that will call a COM method. <em>vtbl_index</em> is the
index into the virtual function table, a small non-negative integer. <em>name</em> is
name of the COM method. <em>iid</em> is an optional pointer to the interface identifier
which is used in extended error reporting.</p>
<p>COM methods use a special calling convention: They require a pointer to the COM
interface as first argument, in addition to those parameters that are specified
in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> tuple.</p>
</dd></dl>

<p>The optional <em>paramflags</em> parameter creates foreign function wrappers with much
more functionality than the features described above.</p>
<p><em>paramflags</em> must be a tuple of the same length as <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code>.</p>
<p>Each item in this tuple contains further information about a parameter, it must
be a tuple containing one, two, or three items.</p>
<p>The first item is an integer containing a combination of direction
flags for the parameter:</p>
<blockquote>
<div><dl class="docutils">
<dt>1</dt>
<dd>Specifies an input parameter to the function.</dd>
<dt>2</dt>
<dd>Output parameter.  The foreign function fills in a value.</dd>
<dt>4</dt>
<dd>Input parameter which defaults to the integer zero.</dd>
</dl>
</div></blockquote>
<p>The optional second item is the parameter name as string.  If this is specified,
the foreign function can be called with named parameters.</p>
<p>The optional third item is the default value for this parameter.</p>
</div></blockquote>
<p>This example demonstrates how to wrap the Windows <code class="docutils literal notranslate"><span class="pre">MessageBoxA</span></code> function so
that it supports default parameters and named arguments. The C declaration from
the windows header file is this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">WINUSERAPI</span> <span class="nb">int</span> <span class="n">WINAPI</span>
<span class="n">MessageBoxA</span><span class="p">(</span>
    <span class="n">HWND</span> <span class="n">hWnd</span><span class="p">,</span>
    <span class="n">LPCSTR</span> <span class="n">lpText</span><span class="p">,</span>
    <span class="n">LPCSTR</span> <span class="n">lpCaption</span><span class="p">,</span>
    <span class="n">UINT</span> <span class="n">uType</span><span class="p">);</span>
</pre></div>
</div>
<p>Here is the wrapping with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">c_int</span><span class="p">,</span> <span class="n">WINFUNCTYPE</span><span class="p">,</span> <span class="n">windll</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.wintypes</span> <span class="k">import</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">UINT</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prototype</span> <span class="o">=</span> <span class="n">WINFUNCTYPE</span><span class="p">(</span><span class="n">c_int</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">LPCSTR</span><span class="p">,</span> <span class="n">UINT</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paramflags</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;hwnd&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;text&quot;</span><span class="p">,</span> <span class="s2">&quot;Hi&quot;</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;caption&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">),</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;flags&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span> <span class="o">=</span> <span class="n">prototype</span><span class="p">((</span><span class="s2">&quot;MessageBoxA&quot;</span><span class="p">,</span> <span class="n">windll</span><span class="o">.</span><span class="n">user32</span><span class="p">),</span> <span class="n">paramflags</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The MessageBox foreign function can now be called in these ways:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Spam, spam, spam&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">MessageBox</span><span class="p">(</span><span class="n">flags</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">text</span><span class="o">=</span><span class="s2">&quot;foo bar&quot;</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>A second example demonstrates output parameters.  The win32 <code class="docutils literal notranslate"><span class="pre">GetWindowRect</span></code>
function retrieves the dimensions of a specified window by copying them into
<code class="docutils literal notranslate"><span class="pre">RECT</span></code> structure that the caller has to supply.  Here is the C declaration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">WINUSERAPI</span> <span class="n">BOOL</span> <span class="n">WINAPI</span>
<span class="n">GetWindowRect</span><span class="p">(</span>
     <span class="n">HWND</span> <span class="n">hWnd</span><span class="p">,</span>
     <span class="n">LPRECT</span> <span class="n">lpRect</span><span class="p">);</span>
</pre></div>
</div>
<p>Here is the wrapping with <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">POINTER</span><span class="p">,</span> <span class="n">WINFUNCTYPE</span><span class="p">,</span> <span class="n">windll</span><span class="p">,</span> <span class="n">WinError</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ctypes.wintypes</span> <span class="k">import</span> <span class="n">BOOL</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">RECT</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prototype</span> <span class="o">=</span> <span class="n">WINFUNCTYPE</span><span class="p">(</span><span class="n">BOOL</span><span class="p">,</span> <span class="n">HWND</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">RECT</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paramflags</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;hwnd&quot;</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s2">&quot;lprect&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span> <span class="o">=</span> <span class="n">prototype</span><span class="p">((</span><span class="s2">&quot;GetWindowRect&quot;</span><span class="p">,</span> <span class="n">windll</span><span class="o">.</span><span class="n">user32</span><span class="p">),</span> <span class="n">paramflags</span><span class="p">)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Functions with output parameters will automatically return the output parameter
value if there is a single one, or a tuple containing the output parameter
values when there are more than one, so the GetWindowRect function now returns a
RECT instance, when called.</p>
<p>Output parameters can be combined with the <code class="xref py py-attr docutils literal notranslate"><span class="pre">errcheck</span></code> protocol to do
further output processing and error checking.  The win32 <code class="docutils literal notranslate"><span class="pre">GetWindowRect</span></code> api
function returns a <code class="docutils literal notranslate"><span class="pre">BOOL</span></code> to signal success or failure, so this function could
do the error checking, and raises an exception when the api call failed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">errcheck</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">result</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">args</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span><span class="o">.</span><span class="n">errcheck</span> <span class="o">=</span> <span class="n">errcheck</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>If the <code class="xref py py-attr docutils literal notranslate"><span class="pre">errcheck</span></code> function returns the argument tuple it receives
unchanged, <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> continues the normal processing it does on the output
parameters.  If you want to return a tuple of window coordinates instead of a
<code class="docutils literal notranslate"><span class="pre">RECT</span></code> instance, you can retrieve the fields in the function and return them
instead, the normal processing will no longer take place:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">errcheck</span><span class="p">(</span><span class="n">result</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">result</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">raise</span> <span class="n">WinError</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">rc</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">rc</span><span class="o">.</span><span class="n">left</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">top</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">bottom</span><span class="p">,</span> <span class="n">rc</span><span class="o">.</span><span class="n">right</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">GetWindowRect</span><span class="o">.</span><span class="n">errcheck</span> <span class="o">=</span> <span class="n">errcheck</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="utility-functions">
<span id="ctypes-utility-functions"></span><h3>15.17.2.5. Utility functions<a class="headerlink" href="#utility-functions" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="ctypes.addressof">
<code class="descclassname">ctypes.</code><code class="descname">addressof</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.addressof" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the address of the memory buffer as integer.  <em>obj</em> must be an
instance of a ctypes type.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.alignment">
<code class="descclassname">ctypes.</code><code class="descname">alignment</code><span class="sig-paren">(</span><em>obj_or_type</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.alignment" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the alignment requirements of a ctypes type. <em>obj_or_type</em> must be a
ctypes type or instance.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.byref">
<code class="descclassname">ctypes.</code><code class="descname">byref</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.byref" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a light-weight pointer to <em>obj</em>, which must be an instance of a
ctypes type.  <em>offset</em> defaults to zero, and must be an integer that will be
added to the internal pointer value.</p>
<p><code class="docutils literal notranslate"><span class="pre">byref(obj,</span> <span class="pre">offset)</span></code> corresponds to this C code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(((</span><span class="n">char</span> <span class="o">*</span><span class="p">)</span><span class="o">&amp;</span><span class="n">obj</span><span class="p">)</span> <span class="o">+</span> <span class="n">offset</span><span class="p">)</span>
</pre></div>
</div>
<p>The returned object can only be used as a foreign function call
parameter.  It behaves similar to <code class="docutils literal notranslate"><span class="pre">pointer(obj)</span></code>, but the
construction is a lot faster.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The <em>offset</em> optional argument was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.cast">
<code class="descclassname">ctypes.</code><code class="descname">cast</code><span class="sig-paren">(</span><em>obj</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.cast" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to the cast operator in C.  It returns a new
instance of <em>type</em> which points to the same memory block as <em>obj</em>.  <em>type</em>
must be a pointer type, and <em>obj</em> must be an object that can be interpreted
as a pointer.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.create_string_buffer">
<code class="descclassname">ctypes.</code><code class="descname">create_string_buffer</code><span class="sig-paren">(</span><em>init_or_size</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.create_string_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a mutable character buffer. The returned object is a
ctypes array of <a class="reference internal" href="#ctypes.c_char" title="ctypes.c_char"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char</span></code></a>.</p>
<p><em>init_or_size</em> must be an integer which specifies the size of the array, or a
string which will be used to initialize the array items.</p>
<p>If a string is specified as first argument, the buffer is made one item larger
than the length of the string so that the last element in the array is a NUL
termination character. An integer can be passed as second argument which allows
specifying the size of the array if the length of the string should not be used.</p>
<p>If the first parameter is a unicode string, it is converted into an 8-bit string
according to ctypes conversion rules.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.create_unicode_buffer">
<code class="descclassname">ctypes.</code><code class="descname">create_unicode_buffer</code><span class="sig-paren">(</span><em>init_or_size</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.create_unicode_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a mutable unicode character buffer. The returned object is
a ctypes array of <a class="reference internal" href="#ctypes.c_wchar" title="ctypes.c_wchar"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_wchar</span></code></a>.</p>
<p><em>init_or_size</em> must be an integer which specifies the size of the array, or a
unicode string which will be used to initialize the array items.</p>
<p>If a unicode string is specified as first argument, the buffer is made one item
larger than the length of the string so that the last element in the array is a
NUL termination character. An integer can be passed as second argument which
allows specifying the size of the array if the length of the string should not
be used.</p>
<p>If the first parameter is an 8-bit string, it is converted into a unicode string
according to ctypes conversion rules.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.DllCanUnloadNow">
<code class="descclassname">ctypes.</code><code class="descname">DllCanUnloadNow</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.DllCanUnloadNow" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: This function is a hook which allows implementing in-process
COM servers with ctypes.  It is called from the DllCanUnloadNow function that
the _ctypes extension dll exports.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.DllGetClassObject">
<code class="descclassname">ctypes.</code><code class="descname">DllGetClassObject</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.DllGetClassObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: This function is a hook which allows implementing in-process
COM servers with ctypes.  It is called from the DllGetClassObject function
that the <code class="docutils literal notranslate"><span class="pre">_ctypes</span></code> extension dll exports.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.util.find_library">
<code class="descclassname">ctypes.util.</code><code class="descname">find_library</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.util.find_library" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to find a library and return a pathname.  <em>name</em> is the library name
without any prefix like <code class="docutils literal notranslate"><span class="pre">lib</span></code>, suffix like <code class="docutils literal notranslate"><span class="pre">.so</span></code>, <code class="docutils literal notranslate"><span class="pre">.dylib</span></code> or version
number (this is the form used for the posix linker option <code class="xref std std-option docutils literal notranslate"><span class="pre">-l</span></code>).  If
no library can be found, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>The exact functionality is system dependent.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Windows only: <code class="docutils literal notranslate"><span class="pre">find_library(&quot;m&quot;)</span></code> or <code class="docutils literal notranslate"><span class="pre">find_library(&quot;c&quot;)</span></code> return the
result of a call to <code class="docutils literal notranslate"><span class="pre">find_msvcrt()</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.util.find_msvcrt">
<code class="descclassname">ctypes.util.</code><code class="descname">find_msvcrt</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.util.find_msvcrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: return the filename of the VC runtime library used by Python,
and by the extension modules.  If the name of the library cannot be
determined, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
<p>If you need to free memory, for example, allocated by an extension module
with a call to the <code class="docutils literal notranslate"><span class="pre">free(void</span> <span class="pre">*)</span></code>, it is important that you use the
function in the same library that allocated the memory.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.FormatError">
<code class="descclassname">ctypes.</code><code class="descname">FormatError</code><span class="sig-paren">(</span><span class="optional">[</span><em>code</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.FormatError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Returns a textual description of the error code <em>code</em>.  If no
error code is specified, the last error code is used by calling the Windows
api function GetLastError.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.GetLastError">
<code class="descclassname">ctypes.</code><code class="descname">GetLastError</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.GetLastError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Returns the last error code set by Windows in the calling thread.
This function calls the Windows <cite>GetLastError()</cite> function directly,
it does not return the ctypes-private copy of the error code.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.get_errno">
<code class="descclassname">ctypes.</code><code class="descname">get_errno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.get_errno" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current value of the ctypes-private copy of the system
<a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a> variable in the calling thread.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.get_last_error">
<code class="descclassname">ctypes.</code><code class="descname">get_last_error</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.get_last_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: returns the current value of the ctypes-private copy of the system
<code class="xref py py-data docutils literal notranslate"><span class="pre">LastError</span></code> variable in the calling thread.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.memmove">
<code class="descclassname">ctypes.</code><code class="descname">memmove</code><span class="sig-paren">(</span><em>dst</em>, <em>src</em>, <em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.memmove" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as the standard C memmove library function: copies <em>count</em> bytes from
<em>src</em> to <em>dst</em>. <em>dst</em> and <em>src</em> must be integers or ctypes instances that can
be converted to pointers.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.memset">
<code class="descclassname">ctypes.</code><code class="descname">memset</code><span class="sig-paren">(</span><em>dst</em>, <em>c</em>, <em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.memset" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as the standard C memset library function: fills the memory block at
address <em>dst</em> with <em>count</em> bytes of value <em>c</em>. <em>dst</em> must be an integer
specifying an address, or a ctypes instance.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.POINTER">
<code class="descclassname">ctypes.</code><code class="descname">POINTER</code><span class="sig-paren">(</span><em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.POINTER" title="Permalink to this definition">¶</a></dt>
<dd><p>This factory function creates and returns a new ctypes pointer type. Pointer
types are cached and reused internally, so calling this function repeatedly is
cheap. <em>type</em> must be a ctypes type.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.pointer">
<code class="descclassname">ctypes.</code><code class="descname">pointer</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.pointer" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates a new pointer instance, pointing to <em>obj</em>. The returned
object is of the type <code class="docutils literal notranslate"><span class="pre">POINTER(type(obj))</span></code>.</p>
<p>Note: If you just want to pass a pointer to an object to a foreign function
call, you should use <code class="docutils literal notranslate"><span class="pre">byref(obj)</span></code> which is much faster.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.resize">
<code class="descclassname">ctypes.</code><code class="descname">resize</code><span class="sig-paren">(</span><em>obj</em>, <em>size</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.resize" title="Permalink to this definition">¶</a></dt>
<dd><p>This function resizes the internal memory buffer of <em>obj</em>, which must be an
instance of a ctypes type.  It is not possible to make the buffer smaller
than the native size of the objects type, as given by <code class="docutils literal notranslate"><span class="pre">sizeof(type(obj))</span></code>,
but it is possible to enlarge the buffer.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.set_conversion_mode">
<code class="descclassname">ctypes.</code><code class="descname">set_conversion_mode</code><span class="sig-paren">(</span><em>encoding</em>, <em>errors</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.set_conversion_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>This function sets the rules that ctypes objects use when converting between
8-bit strings and unicode strings.  <em>encoding</em> must be a string specifying an
encoding, like <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> or <code class="docutils literal notranslate"><span class="pre">'mbcs'</span></code>, <em>errors</em> must be a string
specifying the error handling on encoding/decoding errors.  Examples of
possible values are <code class="docutils literal notranslate"><span class="pre">&quot;strict&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;replace&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;ignore&quot;</span></code>.</p>
<p><a class="reference internal" href="#ctypes.set_conversion_mode" title="ctypes.set_conversion_mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_conversion_mode()</span></code></a> returns a 2-tuple containing the previous
conversion rules.  On windows, the initial conversion rules are <code class="docutils literal notranslate"><span class="pre">('mbcs',</span>
<span class="pre">'ignore')</span></code>, on other systems <code class="docutils literal notranslate"><span class="pre">('ascii',</span> <span class="pre">'strict')</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.set_errno">
<code class="descclassname">ctypes.</code><code class="descname">set_errno</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.set_errno" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current value of the ctypes-private copy of the system <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-data docutils literal notranslate"><span class="pre">errno</span></code></a>
variable in the calling thread to <em>value</em> and return the previous value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.set_last_error">
<code class="descclassname">ctypes.</code><code class="descname">set_last_error</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.set_last_error" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: set the current value of the ctypes-private copy of the system
<code class="xref py py-data docutils literal notranslate"><span class="pre">LastError</span></code> variable in the calling thread to <em>value</em> and return the
previous value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ctypes.sizeof">
<code class="descclassname">ctypes.</code><code class="descname">sizeof</code><span class="sig-paren">(</span><em>obj_or_type</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.sizeof" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the size in bytes of a ctypes type or instance memory buffer.
Does the same as the C <code class="docutils literal notranslate"><span class="pre">sizeof</span></code> operator.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.string_at">
<code class="descclassname">ctypes.</code><code class="descname">string_at</code><span class="sig-paren">(</span><em>address</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.string_at" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns the string starting at memory address <em>address</em>. If size
is specified, it is used as size, otherwise the string is assumed to be
zero-terminated.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.WinError">
<code class="descclassname">ctypes.</code><code class="descname">WinError</code><span class="sig-paren">(</span><em>code=None</em>, <em>descr=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.WinError" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: this function is probably the worst-named thing in ctypes.  It
creates an instance of WindowsError.  If <em>code</em> is not specified,
<code class="docutils literal notranslate"><span class="pre">GetLastError</span></code> is called to determine the error code.  If <code class="docutils literal notranslate"><span class="pre">descr</span></code> is not
specified, <a class="reference internal" href="#ctypes.FormatError" title="ctypes.FormatError"><code class="xref py py-func docutils literal notranslate"><span class="pre">FormatError()</span></code></a> is called to get a textual description of the
error.</p>
</dd></dl>

<dl class="function">
<dt id="ctypes.wstring_at">
<code class="descclassname">ctypes.</code><code class="descname">wstring_at</code><span class="sig-paren">(</span><em>address</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.wstring_at" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns the wide character string starting at memory address
<em>address</em> as unicode string.  If <em>size</em> is specified, it is used as the
number of characters of the string, otherwise the string is assumed to be
zero-terminated.</p>
</dd></dl>

</div>
<div class="section" id="data-types">
<span id="ctypes-data-types"></span><h3>15.17.2.6. Data types<a class="headerlink" href="#data-types" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes._CData">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">_CData</code><a class="headerlink" href="#ctypes._CData" title="Permalink to this definition">¶</a></dt>
<dd><p>This non-public class is the common base class of all ctypes data types.
Among other things, all ctypes type instances contain a memory block that
hold C compatible data; the address of the memory block is returned by the
<a class="reference internal" href="#ctypes.addressof" title="ctypes.addressof"><code class="xref py py-func docutils literal notranslate"><span class="pre">addressof()</span></code></a> helper function.  Another instance variable is exposed as
<a class="reference internal" href="#ctypes._CData._objects" title="ctypes._CData._objects"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_objects</span></code></a>; this contains other Python objects that need to be kept
alive in case the memory block contains pointers.</p>
<p>Common methods of ctypes data types, these are all class methods (to be
exact, they are methods of the <a class="reference internal" href="../glossary.html#term-metaclass"><span class="xref std std-term">metaclass</span></a>):</p>
<dl class="method">
<dt id="ctypes._CData.from_buffer">
<code class="descname">from_buffer</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes._CData.from_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes instance that shares the buffer of the
<em>source</em> object.  The <em>source</em> object must support the writeable buffer
interface.  The optional <em>offset</em> parameter specifies an offset into the
source buffer in bytes; the default is zero.  If the source buffer is not
large enough a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_buffer_copy">
<code class="descname">from_buffer_copy</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ctypes._CData.from_buffer_copy" title="Permalink to this definition">¶</a></dt>
<dd><p>This method creates a ctypes instance, copying the buffer from the
<em>source</em> object buffer which must be readable.  The optional <em>offset</em>
parameter specifies an offset into the source buffer in bytes; the default
is zero.  If the source buffer is not large enough a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is
raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_address">
<code class="descname">from_address</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes._CData.from_address" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes type instance using the memory specified by
<em>address</em> which must be an integer.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.from_param">
<code class="descname">from_param</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes._CData.from_param" title="Permalink to this definition">¶</a></dt>
<dd><p>This method adapts <em>obj</em> to a ctypes type.  It is called with the actual
object used in a foreign function call when the type is present in the
foreign function’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">argtypes</span></code> tuple; it must return an object that
can be used as a function call parameter.</p>
<p>All ctypes data types have a default implementation of this classmethod
that normally returns <em>obj</em> if that is an instance of the type.  Some
types accept other objects as well.</p>
</dd></dl>

<dl class="method">
<dt id="ctypes._CData.in_dll">
<code class="descname">in_dll</code><span class="sig-paren">(</span><em>library</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes._CData.in_dll" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a ctypes type instance exported by a shared
library. <em>name</em> is the name of the symbol that exports the data, <em>library</em>
is the loaded shared library.</p>
</dd></dl>

<p>Common instance variables of ctypes data types:</p>
<dl class="attribute">
<dt id="ctypes._CData._b_base_">
<code class="descname">_b_base_</code><a class="headerlink" href="#ctypes._CData._b_base_" title="Permalink to this definition">¶</a></dt>
<dd><p>Sometimes ctypes data instances do not own the memory block they contain,
instead they share part of the memory block of a base object.  The
<a class="reference internal" href="#ctypes._CData._b_base_" title="ctypes._CData._b_base_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_b_base_</span></code></a> read-only member is the root ctypes object that owns the
memory block.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._CData._b_needsfree_">
<code class="descname">_b_needsfree_</code><a class="headerlink" href="#ctypes._CData._b_needsfree_" title="Permalink to this definition">¶</a></dt>
<dd><p>This read-only variable is true when the ctypes data instance has
allocated the memory block itself, false otherwise.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._CData._objects">
<code class="descname">_objects</code><a class="headerlink" href="#ctypes._CData._objects" title="Permalink to this definition">¶</a></dt>
<dd><p>This member is either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a dictionary containing Python objects
that need to be kept alive so that the memory block contents is kept
valid.  This object is only exposed for debugging; never modify the
contents of this dictionary.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="ctypes-fundamental-data-types-2">
<span id="id1"></span><h3>15.17.2.7. Fundamental data types<a class="headerlink" href="#ctypes-fundamental-data-types-2" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes._SimpleCData">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">_SimpleCData</code><a class="headerlink" href="#ctypes._SimpleCData" title="Permalink to this definition">¶</a></dt>
<dd><p>This non-public class is the base class of all fundamental ctypes data
types. It is mentioned here because it contains the common attributes of the
fundamental ctypes data types.  <a class="reference internal" href="#ctypes._SimpleCData" title="ctypes._SimpleCData"><code class="xref py py-class docutils literal notranslate"><span class="pre">_SimpleCData</span></code></a> is a subclass of
<a class="reference internal" href="#ctypes._CData" title="ctypes._CData"><code class="xref py py-class docutils literal notranslate"><span class="pre">_CData</span></code></a>, so it inherits their methods and attributes.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>ctypes data types that are not and do not contain pointers can now be
pickled.</p>
</div>
<p>Instances have a single attribute:</p>
<dl class="attribute">
<dt id="ctypes._SimpleCData.value">
<code class="descname">value</code><a class="headerlink" href="#ctypes._SimpleCData.value" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute contains the actual value of the instance. For integer and
pointer types, it is an integer, for character types, it is a single
character string, for character pointer types it is a Python string or
unicode string.</p>
<p>When the <code class="docutils literal notranslate"><span class="pre">value</span></code> attribute is retrieved from a ctypes instance, usually
a new object is returned each time.  <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> does <em>not</em> implement
original object return, always a new object is constructed.  The same is
true for all other ctypes object instances.</p>
</dd></dl>

</dd></dl>

<p>Fundamental data types, when returned as foreign function call results, or, for
example, by retrieving structure field members or array items, are transparently
converted to native Python types.  In other words, if a foreign function has a
<code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code> of <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char_p</span></code></a>, you will always receive a Python string,
<em>not</em> a <a class="reference internal" href="#ctypes.c_char_p" title="ctypes.c_char_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_char_p</span></code></a> instance.</p>
<p>Subclasses of fundamental data types do <em>not</em> inherit this behavior. So, if a
foreign functions <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code> is a subclass of <a class="reference internal" href="#ctypes.c_void_p" title="ctypes.c_void_p"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_void_p</span></code></a>, you will
receive an instance of this subclass from the function call. Of course, you can
get the value of the pointer by accessing the <code class="docutils literal notranslate"><span class="pre">value</span></code> attribute.</p>
<p>These are the fundamental ctypes data types:</p>
<dl class="class">
<dt id="ctypes.c_byte">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_byte</code><a class="headerlink" href="#ctypes.c_byte" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">char</span></code> datatype, and interprets the value as
small integer.  The constructor accepts an optional integer initializer; no
overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_char">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_char</code><a class="headerlink" href="#ctypes.c_char" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code> datatype, and interprets the value as a single
character.  The constructor accepts an optional string initializer, the
length of the string must be exactly one character.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_char_p">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_char_p</code><a class="headerlink" href="#ctypes.c_char_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span> <span class="pre">*</span></code> datatype when it points to a zero-terminated
string.  For a general character pointer that may also point to binary data,
<code class="docutils literal notranslate"><span class="pre">POINTER(c_char)</span></code> must be used.  The constructor accepts an integer
address, or a string.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_double">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_double</code><a class="headerlink" href="#ctypes.c_double" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> datatype.  The constructor accepts an
optional float initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_longdouble">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_longdouble</code><a class="headerlink" href="#ctypes.c_longdouble" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">double</span></code> datatype.  The constructor accepts an
optional float initializer.  On platforms where <code class="docutils literal notranslate"><span class="pre">sizeof(long</span> <span class="pre">double)</span> <span class="pre">==</span>
<span class="pre">sizeof(double)</span></code> it is an alias to <a class="reference internal" href="#ctypes.c_double" title="ctypes.c_double"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_double</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_float">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_float</code><a class="headerlink" href="#ctypes.c_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">float</span></code> datatype.  The constructor accepts an
optional float initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_int</code><a class="headerlink" href="#ctypes.c_int" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">int</span></code> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.  On platforms
where <code class="docutils literal notranslate"><span class="pre">sizeof(int)</span> <span class="pre">==</span> <span class="pre">sizeof(long)</span></code> it is an alias to <a class="reference internal" href="#ctypes.c_long" title="ctypes.c_long"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_long</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int8">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_int8</code><a class="headerlink" href="#ctypes.c_int8" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 8-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_byte" title="ctypes.c_byte"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_byte</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int16">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_int16</code><a class="headerlink" href="#ctypes.c_int16" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 16-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_short" title="ctypes.c_short"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_short</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int32">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_int32</code><a class="headerlink" href="#ctypes.c_int32" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 32-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_int64">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_int64</code><a class="headerlink" href="#ctypes.c_int64" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 64-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_longlong" title="ctypes.c_longlong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_longlong</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_long">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_long</code><a class="headerlink" href="#ctypes.c_long" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">long</span></code> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_longlong">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_longlong</code><a class="headerlink" href="#ctypes.c_longlong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">long</span> <span class="pre">long</span></code> datatype.  The constructor accepts
an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_short">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_short</code><a class="headerlink" href="#ctypes.c_short" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">short</span></code> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_size_t">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_size_t</code><a class="headerlink" href="#ctypes.c_size_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">size_t</span></code> datatype.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ssize_t">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_ssize_t</code><a class="headerlink" href="#ctypes.c_ssize_t" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">ssize_t</span></code> datatype.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ubyte">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_ubyte</code><a class="headerlink" href="#ctypes.c_ubyte" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code> datatype, it interprets the value as
small integer.  The constructor accepts an optional integer initializer; no
overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_uint</code><a class="headerlink" href="#ctypes.c_uint" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.  On platforms
where <code class="docutils literal notranslate"><span class="pre">sizeof(int)</span> <span class="pre">==</span> <span class="pre">sizeof(long)</span></code> it is an alias for <a class="reference internal" href="#ctypes.c_ulong" title="ctypes.c_ulong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ulong</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint8">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_uint8</code><a class="headerlink" href="#ctypes.c_uint8" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 8-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ubyte" title="ctypes.c_ubyte"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ubyte</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint16">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_uint16</code><a class="headerlink" href="#ctypes.c_uint16" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 16-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ushort" title="ctypes.c_ushort"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ushort</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint32">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_uint32</code><a class="headerlink" href="#ctypes.c_uint32" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 32-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_uint" title="ctypes.c_uint"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_uint</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_uint64">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_uint64</code><a class="headerlink" href="#ctypes.c_uint64" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C 64-bit <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code> datatype.  Usually an alias for
<a class="reference internal" href="#ctypes.c_ulonglong" title="ctypes.c_ulonglong"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_ulonglong</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ulong">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_ulong</code><a class="headerlink" href="#ctypes.c_ulong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code> datatype.  The constructor accepts an
optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ulonglong">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_ulonglong</code><a class="headerlink" href="#ctypes.c_ulonglong" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code> datatype.  The constructor
accepts an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_ushort">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_ushort</code><a class="headerlink" href="#ctypes.c_ushort" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">short</span></code> datatype.  The constructor accepts
an optional integer initializer; no overflow checking is done.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_void_p">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_void_p</code><a class="headerlink" href="#ctypes.c_void_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> type.  The value is represented as integer.
The constructor accepts an optional integer initializer.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_wchar">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_wchar</code><a class="headerlink" href="#ctypes.c_wchar" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span></code> datatype, and interprets the value as a
single character unicode string.  The constructor accepts an optional string
initializer, the length of the string must be exactly one character.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_wchar_p">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_wchar_p</code><a class="headerlink" href="#ctypes.c_wchar_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <code class="xref c c-type docutils literal notranslate"><span class="pre">wchar_t</span> <span class="pre">*</span></code> datatype, which must be a pointer to a
zero-terminated wide character string.  The constructor accepts an integer
address, or a string.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.c_bool">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">c_bool</code><a class="headerlink" href="#ctypes.c_bool" title="Permalink to this definition">¶</a></dt>
<dd><p>Represent the C <code class="xref c c-type docutils literal notranslate"><span class="pre">bool</span></code> datatype (more accurately, <code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code> from
C99).  Its value can be <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, and the constructor accepts any object
that has a truth value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="ctypes.HRESULT">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">HRESULT</code><a class="headerlink" href="#ctypes.HRESULT" title="Permalink to this definition">¶</a></dt>
<dd><p>Windows only: Represents a <code class="xref c c-type docutils literal notranslate"><span class="pre">HRESULT</span></code> value, which contains success or
error information for a function or method call.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.py_object">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">py_object</code><a class="headerlink" href="#ctypes.py_object" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents the C <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code></a> datatype.  Calling this without an
argument creates a <code class="docutils literal notranslate"><span class="pre">NULL</span></code> <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code></a> pointer.</p>
</dd></dl>

<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes.wintypes</span></code> module provides quite some other Windows specific
data types, for example <code class="xref c c-type docutils literal notranslate"><span class="pre">HWND</span></code>, <code class="xref c c-type docutils literal notranslate"><span class="pre">WPARAM</span></code>, or <code class="xref c c-type docutils literal notranslate"><span class="pre">DWORD</span></code>.  Some
useful structures like <code class="xref c c-type docutils literal notranslate"><span class="pre">MSG</span></code> or <code class="xref c c-type docutils literal notranslate"><span class="pre">RECT</span></code> are also defined.</p>
</div>
<div class="section" id="structured-data-types">
<span id="ctypes-structured-data-types"></span><h3>15.17.2.8. Structured data types<a class="headerlink" href="#structured-data-types" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes.Union">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">Union</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.Union" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for unions in native byte order.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.BigEndianStructure">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">BigEndianStructure</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.BigEndianStructure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>big endian</em> byte order.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes.LittleEndianStructure">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">LittleEndianStructure</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.LittleEndianStructure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>little endian</em> byte order.</p>
</dd></dl>

<p>Structures with non-native byte order cannot contain pointer type fields, or any
other data types containing pointer type fields.</p>
<dl class="class">
<dt id="ctypes.Structure">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">Structure</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.Structure" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for structures in <em>native</em> byte order.</p>
<p>Concrete structure and union types must be created by subclassing one of these
types, and at least define a <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> class variable. <a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> will
create <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a>s which allow reading and writing the fields by direct
attribute accesses.  These are the</p>
<dl class="attribute">
<dt id="ctypes.Structure._fields_">
<code class="descname">_fields_</code><a class="headerlink" href="#ctypes.Structure._fields_" title="Permalink to this definition">¶</a></dt>
<dd><p>A sequence defining the structure fields.  The items must be 2-tuples or
3-tuples.  The first item is the name of the field, the second item
specifies the type of the field; it can be any ctypes data type.</p>
<p>For integer type fields like <a class="reference internal" href="#ctypes.c_int" title="ctypes.c_int"><code class="xref py py-class docutils literal notranslate"><span class="pre">c_int</span></code></a>, a third optional item can be
given.  It must be a small positive integer defining the bit width of the
field.</p>
<p>Field names must be unique within one structure or union.  This is not
checked, only one field can be accessed when names are repeated.</p>
<p>It is possible to define the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> class variable <em>after</em> the
class statement that defines the Structure subclass, this allows creating
data types that directly or indirectly reference themselves:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">List</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
    <span class="k">pass</span>
<span class="n">List</span><span class="o">.</span><span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;pnext&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">List</span><span class="p">)),</span>
                 <span class="o">...</span>
                <span class="p">]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> class variable must, however, be defined before the
type is first used (an instance is created, <code class="docutils literal notranslate"><span class="pre">sizeof()</span></code> is called on it,
and so on).  Later assignments to the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> class variable will
raise an AttributeError.</p>
<p>It is possible to defined sub-subclasses of structure types, they inherit
the fields of the base class plus the <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> defined in the
sub-subclass, if any.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.Structure._pack_">
<code class="descname">_pack_</code><a class="headerlink" href="#ctypes.Structure._pack_" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional small integer that allows overriding the alignment of
structure fields in the instance.  <a class="reference internal" href="#ctypes.Structure._pack_" title="ctypes.Structure._pack_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_pack_</span></code></a> must already be defined
when <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> is assigned, otherwise it will have no effect.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.Structure._anonymous_">
<code class="descname">_anonymous_</code><a class="headerlink" href="#ctypes.Structure._anonymous_" title="Permalink to this definition">¶</a></dt>
<dd><p>An optional sequence that lists the names of unnamed (anonymous) fields.
<a class="reference internal" href="#ctypes.Structure._anonymous_" title="ctypes.Structure._anonymous_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_anonymous_</span></code></a> must be already defined when <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> is
assigned, otherwise it will have no effect.</p>
<p>The fields listed in this variable must be structure or union type fields.
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> will create descriptors in the structure type that allow
accessing the nested fields directly, without the need to create the
structure or union field.</p>
<p>Here is an example type (Windows):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">_U</span><span class="p">(</span><span class="n">Union</span><span class="p">):</span>
    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;lptdesc&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">TYPEDESC</span><span class="p">)),</span>
                <span class="p">(</span><span class="s2">&quot;lpadesc&quot;</span><span class="p">,</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">ARRAYDESC</span><span class="p">)),</span>
                <span class="p">(</span><span class="s2">&quot;hreftype&quot;</span><span class="p">,</span> <span class="n">HREFTYPE</span><span class="p">)]</span>

<span class="k">class</span> <span class="nc">TYPEDESC</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
    <span class="n">_anonymous_</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;u&quot;</span><span class="p">,)</span>
    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s2">&quot;u&quot;</span><span class="p">,</span> <span class="n">_U</span><span class="p">),</span>
                <span class="p">(</span><span class="s2">&quot;vt&quot;</span><span class="p">,</span> <span class="n">VARTYPE</span><span class="p">)]</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">TYPEDESC</span></code> structure describes a COM data type, the <code class="docutils literal notranslate"><span class="pre">vt</span></code> field
specifies which one of the union fields is valid.  Since the <code class="docutils literal notranslate"><span class="pre">u</span></code> field
is defined as anonymous field, it is now possible to access the members
directly off the TYPEDESC instance. <code class="docutils literal notranslate"><span class="pre">td.lptdesc</span></code> and <code class="docutils literal notranslate"><span class="pre">td.u.lptdesc</span></code>
are equivalent, but the former is faster since it does not need to create
a temporary union instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">td</span> <span class="o">=</span> <span class="n">TYPEDESC</span><span class="p">()</span>
<span class="n">td</span><span class="o">.</span><span class="n">vt</span> <span class="o">=</span> <span class="n">VT_PTR</span>
<span class="n">td</span><span class="o">.</span><span class="n">lptdesc</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">some_type</span><span class="p">)</span>
<span class="n">td</span><span class="o">.</span><span class="n">u</span><span class="o">.</span><span class="n">lptdesc</span> <span class="o">=</span> <span class="n">POINTER</span><span class="p">(</span><span class="n">some_type</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<p>It is possible to defined sub-subclasses of structures, they inherit the
fields of the base class.  If the subclass definition has a separate
<a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> variable, the fields specified in this are appended to the
fields of the base class.</p>
<p>Structure and union constructors accept both positional and keyword
arguments.  Positional arguments are used to initialize member fields in the
same order as they are appear in <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a>.  Keyword arguments in the
constructor are interpreted as attribute assignments, so they will initialize
<a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a> with the same name, or create new attributes for names not
present in <a class="reference internal" href="#ctypes.Structure._fields_" title="ctypes.Structure._fields_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_fields_</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="arrays-and-pointers">
<span id="ctypes-arrays-pointers"></span><h3>15.17.2.9. Arrays and pointers<a class="headerlink" href="#arrays-and-pointers" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ctypes.Array">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">Array</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#ctypes.Array" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract base class for arrays.</p>
<p>The recommended way to create concrete array types is by multiplying any
<a class="reference internal" href="#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> data type with a positive integer.  Alternatively, you can subclass
this type and define <a class="reference internal" href="#ctypes.Array._length_" title="ctypes.Array._length_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_length_</span></code></a> and <a class="reference internal" href="#ctypes.Array._type_" title="ctypes.Array._type_"><code class="xref py py-attr docutils literal notranslate"><span class="pre">_type_</span></code></a> class variables.
Array elements can be read and written using standard
subscript and slice accesses; for slice reads, the resulting object is
<em>not</em> itself an <a class="reference internal" href="#ctypes.Array" title="ctypes.Array"><code class="xref py py-class docutils literal notranslate"><span class="pre">Array</span></code></a>.</p>
<dl class="attribute">
<dt id="ctypes.Array._length_">
<code class="descname">_length_</code><a class="headerlink" href="#ctypes.Array._length_" title="Permalink to this definition">¶</a></dt>
<dd><p>A positive integer specifying the number of elements in the array.
Out-of-range subscripts result in an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>. Will be
returned by <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes.Array._type_">
<code class="descname">_type_</code><a class="headerlink" href="#ctypes.Array._type_" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies the type of each element in the array.</p>
</dd></dl>

<p>Array subclass constructors accept positional arguments, used to
initialize the elements in order.</p>
</dd></dl>

<dl class="class">
<dt id="ctypes._Pointer">
<em class="property">class </em><code class="descclassname">ctypes.</code><code class="descname">_Pointer</code><a class="headerlink" href="#ctypes._Pointer" title="Permalink to this definition">¶</a></dt>
<dd><p>Private, abstract base class for pointers.</p>
<p>Concrete pointer types are created by calling <a class="reference internal" href="#ctypes.POINTER" title="ctypes.POINTER"><code class="xref py py-func docutils literal notranslate"><span class="pre">POINTER()</span></code></a> with the
type that will be pointed to; this is done automatically by
<a class="reference internal" href="#ctypes.pointer" title="ctypes.pointer"><code class="xref py py-func docutils literal notranslate"><span class="pre">pointer()</span></code></a>.</p>
<p>If a pointer points to an array, its elements can be read and
written using standard subscript and slice accesses.  Pointer objects
have no size, so <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> will raise <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  Negative
subscripts will read from the memory <em>before</em> the pointer (as in C), and
out-of-range subscripts will probably crash with an access violation (if
you’re lucky).</p>
<dl class="attribute">
<dt id="ctypes._Pointer._type_">
<code class="descname">_type_</code><a class="headerlink" href="#ctypes._Pointer._type_" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies the type pointed to.</p>
</dd></dl>

<dl class="attribute">
<dt id="ctypes._Pointer.contents">
<code class="descname">contents</code><a class="headerlink" href="#ctypes._Pointer.contents" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the object to which to pointer points.  Assigning to this
attribute changes the pointer to point to the assigned object.</p>
</dd></dl>

</dd></dl>

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a><ul>
<li><a class="reference internal" href="#ctypes-tutorial">15.17.1. ctypes tutorial</a><ul>
<li><a class="reference internal" href="#loading-dynamic-link-libraries">15.17.1.1. Loading dynamic link libraries</a></li>
<li><a class="reference internal" href="#accessing-functions-from-loaded-dlls">15.17.1.2. Accessing functions from loaded dlls</a></li>
<li><a class="reference internal" href="#calling-functions">15.17.1.3. Calling functions</a></li>
<li><a class="reference internal" href="#fundamental-data-types">15.17.1.4. Fundamental data types</a></li>
<li><a class="reference internal" href="#calling-functions-continued">15.17.1.5. Calling functions, continued</a></li>
<li><a class="reference internal" href="#calling-functions-with-your-own-custom-data-types">15.17.1.6. Calling functions with your own custom data types</a></li>
<li><a class="reference internal" href="#specifying-the-required-argument-types-function-prototypes">15.17.1.7. Specifying the required argument types (function prototypes)</a></li>
<li><a class="reference internal" href="#return-types">15.17.1.8. Return types</a></li>
<li><a class="reference internal" href="#passing-pointers-or-passing-parameters-by-reference">15.17.1.9. Passing pointers (or: passing parameters by reference)</a></li>
<li><a class="reference internal" href="#structures-and-unions">15.17.1.10. Structures and unions</a></li>
<li><a class="reference internal" href="#structure-union-alignment-and-byte-order">15.17.1.11. Structure/union alignment and byte order</a></li>
<li><a class="reference internal" href="#bit-fields-in-structures-and-unions">15.17.1.12. Bit fields in structures and unions</a></li>
<li><a class="reference internal" href="#arrays">15.17.1.13. Arrays</a></li>
<li><a class="reference internal" href="#pointers">15.17.1.14. Pointers</a></li>
<li><a class="reference internal" href="#type-conversions">15.17.1.15. Type conversions</a></li>
<li><a class="reference internal" href="#incomplete-types">15.17.1.16. Incomplete Types</a></li>
<li><a class="reference internal" href="#callback-functions">15.17.1.17. Callback functions</a></li>
<li><a class="reference internal" href="#accessing-values-exported-from-dlls">15.17.1.18. Accessing values exported from dlls</a></li>
<li><a class="reference internal" href="#surprises">15.17.1.19. Surprises</a></li>
<li><a class="reference internal" href="#variable-sized-data-types">15.17.1.20. Variable-sized data types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#ctypes-reference">15.17.2. ctypes reference</a><ul>
<li><a class="reference internal" href="#finding-shared-libraries">15.17.2.1. Finding shared libraries</a></li>
<li><a class="reference internal" href="#loading-shared-libraries">15.17.2.2. Loading shared libraries</a></li>
<li><a class="reference internal" href="#foreign-functions">15.17.2.3. Foreign functions</a></li>
<li><a class="reference internal" href="#function-prototypes">15.17.2.4. Function prototypes</a></li>
<li><a class="reference internal" href="#utility-functions">15.17.2.5. Utility functions</a></li>
<li><a class="reference internal" href="#data-types">15.17.2.6. Data types</a></li>
<li><a class="reference internal" href="#ctypes-fundamental-data-types-2">15.17.2.7. Fundamental data types</a></li>
<li><a class="reference internal" href="#structured-data-types">15.17.2.8. Structured data types</a></li>
<li><a class="reference internal" href="#arrays-and-pointers">15.17.2.9. Arrays and pointers</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="errno.html"
                        title="previous chapter">15.16. <code class="docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="someos.html"
                        title="next chapter">16. Optional Operating System Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ctypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             >next</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P�)a)ahtml/library/curses.ascii.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.13. curses.ascii — Utilities for ASCII characters &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.14. curses.panel — A panel stack extension for curses" href="curses.panel.html" />
    <link rel="prev" title="15.11. curses — Terminal handling for character-cell displays" href="curses.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/curses.ascii.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.panel.html" title="15.14. curses.panel — A panel stack extension for curses"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="curses.html" title="15.11. curses — Terminal handling for character-cell displays"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-curses.ascii">
<span id="curses-ascii-utilities-for-ascii-characters"></span><h1>15.13. <a class="reference internal" href="#module-curses.ascii" title="curses.ascii: Constants and set-membership functions for ASCII characters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.ascii</span></code></a> — Utilities for ASCII characters<a class="headerlink" href="#module-curses.ascii" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<p>The <a class="reference internal" href="#module-curses.ascii" title="curses.ascii: Constants and set-membership functions for ASCII characters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.ascii</span></code></a> module supplies name constants for ASCII characters and
functions to test membership in various ASCII character classes.  The constants
supplied are names for control characters as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="77%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NUL</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SOH</span></code></td>
<td>Start of heading, console interrupt</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">STX</span></code></td>
<td>Start of text</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ETX</span></code></td>
<td>End of text</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EOT</span></code></td>
<td>End of transmission</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ENQ</span></code></td>
<td>Enquiry, goes with <code class="xref py py-const docutils literal notranslate"><span class="pre">ACK</span></code> flow control</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACK</span></code></td>
<td>Acknowledgement</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">BEL</span></code></td>
<td>Bell</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">BS</span></code></td>
<td>Backspace</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">TAB</span></code></td>
<td>Tab</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">HT</span></code></td>
<td>Alias for <code class="xref py py-const docutils literal notranslate"><span class="pre">TAB</span></code>: “Horizontal tab”</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">LF</span></code></td>
<td>Line feed</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NL</span></code></td>
<td>Alias for <code class="xref py py-const docutils literal notranslate"><span class="pre">LF</span></code>: “New line”</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">VT</span></code></td>
<td>Vertical tab</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FF</span></code></td>
<td>Form feed</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">CR</span></code></td>
<td>Carriage return</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SO</span></code></td>
<td>Shift-out, begin alternate character set</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SI</span></code></td>
<td>Shift-in, resume default character set</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DLE</span></code></td>
<td>Data-link escape</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DC1</span></code></td>
<td>XON, for flow control</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DC2</span></code></td>
<td>Device control 2, block-mode flow control</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DC3</span></code></td>
<td>XOFF, for flow control</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DC4</span></code></td>
<td>Device control 4</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NAK</span></code></td>
<td>Negative acknowledgement</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SYN</span></code></td>
<td>Synchronous idle</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ETB</span></code></td>
<td>End transmission block</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">CAN</span></code></td>
<td>Cancel</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EM</span></code></td>
<td>End of medium</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SUB</span></code></td>
<td>Substitute</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ESC</span></code></td>
<td>Escape</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FS</span></code></td>
<td>File separator</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">GS</span></code></td>
<td>Group separator</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">RS</span></code></td>
<td>Record separator, block-mode terminator</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">US</span></code></td>
<td>Unit separator</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SP</span></code></td>
<td>Space</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DEL</span></code></td>
<td>Delete</td>
</tr>
</tbody>
</table>
<p>Note that many of these have little practical significance in modern usage.  The
mnemonics derive from teleprinter conventions that predate digital computers.</p>
<p>The module supplies the following functions, patterned on those in the standard
C library:</p>
<dl class="function">
<dt id="curses.ascii.isalnum">
<code class="descclassname">curses.ascii.</code><code class="descname">isalnum</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isalnum" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII alphanumeric character; it is equivalent to <code class="docutils literal notranslate"><span class="pre">isalpha(c)</span> <span class="pre">or</span>
<span class="pre">isdigit(c)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isalpha">
<code class="descclassname">curses.ascii.</code><code class="descname">isalpha</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isalpha" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII alphabetic character; it is equivalent to <code class="docutils literal notranslate"><span class="pre">isupper(c)</span> <span class="pre">or</span>
<span class="pre">islower(c)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isascii">
<code class="descclassname">curses.ascii.</code><code class="descname">isascii</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isascii" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for a character value that fits in the 7-bit ASCII set.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isblank">
<code class="descclassname">curses.ascii.</code><code class="descname">isblank</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isblank" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII whitespace character; space or horizontal tab.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.iscntrl">
<code class="descclassname">curses.ascii.</code><code class="descname">iscntrl</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.iscntrl" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII control character (in the range 0x00 to 0x1f or 0x7f).</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isdigit">
<code class="descclassname">curses.ascii.</code><code class="descname">isdigit</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isdigit" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII decimal digit, <code class="docutils literal notranslate"><span class="pre">'0'</span></code> through <code class="docutils literal notranslate"><span class="pre">'9'</span></code>.  This is equivalent
to <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">in</span> <span class="pre">string.digits</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isgraph">
<code class="descclassname">curses.ascii.</code><code class="descname">isgraph</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isgraph" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for ASCII any printable character except space.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.islower">
<code class="descclassname">curses.ascii.</code><code class="descname">islower</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.islower" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII lower-case character.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isprint">
<code class="descclassname">curses.ascii.</code><code class="descname">isprint</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isprint" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for any ASCII printable character including space.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.ispunct">
<code class="descclassname">curses.ascii.</code><code class="descname">ispunct</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.ispunct" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for any printable ASCII character which is not a space or an alphanumeric
character.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isspace">
<code class="descclassname">curses.ascii.</code><code class="descname">isspace</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isspace" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for ASCII white-space characters; space, line feed, carriage return, form
feed, horizontal tab, vertical tab.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isupper">
<code class="descclassname">curses.ascii.</code><code class="descname">isupper</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isupper" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII uppercase letter.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isxdigit">
<code class="descclassname">curses.ascii.</code><code class="descname">isxdigit</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isxdigit" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII hexadecimal digit.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">in</span>
<span class="pre">string.hexdigits</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.isctrl">
<code class="descclassname">curses.ascii.</code><code class="descname">isctrl</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.isctrl" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for an ASCII control character (ordinal values 0 to 31).</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.ismeta">
<code class="descclassname">curses.ascii.</code><code class="descname">ismeta</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.ismeta" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for a non-ASCII character (ordinal values 0x80 and above).</p>
</dd></dl>

<p>These functions accept either integers or strings; when the argument is a
string, it is first converted using the built-in function <a class="reference internal" href="functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>.</p>
<p>Note that all these functions check ordinal bit values derived from the  first
character of the string you pass in; they do not actually know anything about
the host machine’s character encoding.  For functions  that know about the
character encoding (and handle internationalization properly) see the
<a class="reference internal" href="string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module.</p>
<p>The following two functions take either a single-character string or integer
byte value; they return a value of the same type.</p>
<dl class="function">
<dt id="curses.ascii.ascii">
<code class="descclassname">curses.ascii.</code><code class="descname">ascii</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.ascii" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the ASCII value corresponding to the low 7 bits of <em>c</em>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.ctrl">
<code class="descclassname">curses.ascii.</code><code class="descname">ctrl</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.ctrl" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the control character corresponding to the given character (the character
bit value is bitwise-anded with 0x1f).</p>
</dd></dl>

<dl class="function">
<dt id="curses.ascii.alt">
<code class="descclassname">curses.ascii.</code><code class="descname">alt</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.alt" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the 8-bit character corresponding to the given ASCII character (the
character bit value is bitwise-ored with 0x80).</p>
</dd></dl>

<p>The following function takes either a single-character string or integer value;
it returns a string.</p>
<dl class="function">
<dt id="curses.ascii.unctrl">
<code class="descclassname">curses.ascii.</code><code class="descname">unctrl</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ascii.unctrl" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representation of the ASCII character <em>c</em>.  If <em>c</em> is printable,
this string is the character itself.  If the character is a control character
(0x00–0x1f) the string consists of a caret (<code class="docutils literal notranslate"><span class="pre">'^'</span></code>) followed by the
corresponding uppercase letter. If the character is an ASCII delete (0x7f) the
string is <code class="docutils literal notranslate"><span class="pre">'^?'</span></code>.  If the character has its meta bit (0x80) set, the meta bit
is stripped, the preceding rules applied, and <code class="docutils literal notranslate"><span class="pre">'!'</span></code> prepended to the result.</p>
</dd></dl>

<dl class="data">
<dt id="curses.ascii.controlnames">
<code class="descclassname">curses.ascii.</code><code class="descname">controlnames</code><a class="headerlink" href="#curses.ascii.controlnames" title="Permalink to this definition">¶</a></dt>
<dd><p>A 33-element string array that contains the ASCII mnemonics for the thirty-two
ASCII control characters from 0 (NUL) to 0x1f (US), in order, plus the mnemonic
<code class="docutils literal notranslate"><span class="pre">SP</span></code> for the space character.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="curses.html"
                        title="previous chapter">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="curses.panel.html"
                        title="next chapter">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/curses.ascii.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.panel.html" title="15.14. curses.panel — A panel stack extension for curses"
             >next</a> |</li>
        <li class="right" >
          <a href="curses.html" title="15.11. curses — Terminal handling for character-cell displays"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�M�M�html/library/curses.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.11. curses — Terminal handling for character-cell displays &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.13. curses.ascii — Utilities for ASCII characters" href="curses.ascii.html" />
    <link rel="prev" title="15.10. getpass — Portable password input" href="getpass.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/curses.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.ascii.html" title="15.13. curses.ascii — Utilities for ASCII characters"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="getpass.html" title="15.10. getpass — Portable password input"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-curses">
<span id="curses-terminal-handling-for-character-cell-displays"></span><h1>15.11. <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> — Terminal handling for character-cell displays<a class="headerlink" href="#module-curses" title="Permalink to this headline">¶</a></h1>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 1.6: </span>Added support for the <code class="docutils literal notranslate"><span class="pre">ncurses</span></code> library and converted to a package.</p>
</div>
<p>The <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module provides an interface to the curses library, the
de-facto standard for portable advanced terminal handling.</p>
<p>While curses is most widely used in the Unix environment, versions are available
for DOS, OS/2, and possibly other systems as well.  This extension module is
designed to match the API of ncurses, an open-source curses library hosted on
Linux and the BSD variants of Unix.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Since version 5.4, the ncurses library decides how to interpret non-ASCII data
using the <code class="docutils literal notranslate"><span class="pre">nl_langinfo</span></code> function.  That means that you have to call
<a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.setlocale()</span></code></a> in the application and encode Unicode strings
using one of the system’s available encodings.  This example uses the
system’s default encoding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">locale</span>
<span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="n">code</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">getpreferredencoding</span><span class="p">()</span>
</pre></div>
</div>
<p class="last">Then use <em>code</em> as the encoding for <a class="reference internal" href="stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> calls.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt>Module <a class="reference internal" href="curses.ascii.html#module-curses.ascii" title="curses.ascii: Constants and set-membership functions for ASCII characters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.ascii</span></code></a></dt>
<dd>Utilities for working with ASCII characters, regardless of your locale settings.</dd>
<dt>Module <a class="reference internal" href="curses.panel.html#module-curses.panel" title="curses.panel: A panel stack extension that adds depth to  curses windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.panel</span></code></a></dt>
<dd>A panel stack extension that adds depth to  curses windows.</dd>
<dt>Module <a class="reference internal" href="#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a></dt>
<dd>Editable text widget for curses supporting  <strong class="program">Emacs</strong>-like bindings.</dd>
<dt><a class="reference internal" href="../howto/curses.html#curses-howto"><span class="std std-ref">Curses Programming with Python</span></a></dt>
<dd>Tutorial material on using curses with Python, by Andrew Kuchling and Eric
Raymond.</dd>
</dl>
<p class="last">The <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Demo/curses/">Demo/curses/</a> directory in the Python source distribution contains
some example programs using the curses bindings provided by this module.</p>
</div>
<div class="section" id="functions">
<span id="curses-functions"></span><h2>15.11.1. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h2>
<p>The module <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> defines the following exception:</p>
<dl class="exception">
<dt id="curses.error">
<em class="property">exception </em><code class="descclassname">curses.</code><code class="descname">error</code><a class="headerlink" href="#curses.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a curses library function returns an error.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Whenever <em>x</em> or <em>y</em> arguments to a function or a method are optional, they
default to the current cursor location. Whenever <em>attr</em> is optional, it defaults
to <code class="xref py py-const docutils literal notranslate"><span class="pre">A_NORMAL</span></code>.</p>
</div>
<p>The module <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> defines the following functions:</p>
<dl class="function">
<dt id="curses.baudrate">
<code class="descclassname">curses.</code><code class="descname">baudrate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.baudrate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the output speed of the terminal in bits per second.  On software
terminal emulators it will have a fixed high value. Included for historical
reasons; in former times, it was used to  write output loops for time delays and
occasionally to change interfaces depending on the line speed.</p>
</dd></dl>

<dl class="function">
<dt id="curses.beep">
<code class="descclassname">curses.</code><code class="descname">beep</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.beep" title="Permalink to this definition">¶</a></dt>
<dd><p>Emit a short attention sound.</p>
</dd></dl>

<dl class="function">
<dt id="curses.can_change_color">
<code class="descclassname">curses.</code><code class="descname">can_change_color</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.can_change_color" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, depending on whether the programmer can change the colors
displayed by the terminal.</p>
</dd></dl>

<dl class="function">
<dt id="curses.cbreak">
<code class="descclassname">curses.</code><code class="descname">cbreak</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.cbreak" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter cbreak mode.  In cbreak mode (sometimes called “rare” mode) normal tty
line buffering is turned off and characters are available to be read one by one.
However, unlike raw mode, special characters (interrupt, quit, suspend, and flow
control) retain their effects on the tty driver and calling program.  Calling
first <a class="reference internal" href="#curses.raw" title="curses.raw"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw()</span></code></a> then <a class="reference internal" href="#curses.cbreak" title="curses.cbreak"><code class="xref py py-func docutils literal notranslate"><span class="pre">cbreak()</span></code></a> leaves the terminal in cbreak mode.</p>
</dd></dl>

<dl class="function">
<dt id="curses.color_content">
<code class="descclassname">curses.</code><code class="descname">color_content</code><span class="sig-paren">(</span><em>color_number</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.color_content" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the intensity of the red, green, and blue (RGB) components in the color
<em>color_number</em>, which must be between <code class="docutils literal notranslate"><span class="pre">0</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">COLORS</span></code>.  A 3-tuple is
returned, containing the R,G,B values for the given color, which will be between
<code class="docutils literal notranslate"><span class="pre">0</span></code> (no component) and <code class="docutils literal notranslate"><span class="pre">1000</span></code> (maximum amount of component).</p>
</dd></dl>

<dl class="function">
<dt id="curses.color_pair">
<code class="descclassname">curses.</code><code class="descname">color_pair</code><span class="sig-paren">(</span><em>color_number</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.color_pair" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the attribute value for displaying text in the specified color.  This
attribute value can be combined with <code class="xref py py-const docutils literal notranslate"><span class="pre">A_STANDOUT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">A_REVERSE</span></code>,
and the other <code class="xref py py-const docutils literal notranslate"><span class="pre">A_*</span></code> attributes.  <a class="reference internal" href="#curses.pair_number" title="curses.pair_number"><code class="xref py py-func docutils literal notranslate"><span class="pre">pair_number()</span></code></a> is the counterpart
to this function.</p>
</dd></dl>

<dl class="function">
<dt id="curses.curs_set">
<code class="descclassname">curses.</code><code class="descname">curs_set</code><span class="sig-paren">(</span><em>visibility</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.curs_set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the cursor state.  <em>visibility</em> can be set to 0, 1, or 2, for invisible,
normal, or very visible.  If the terminal supports the visibility requested, the
previous cursor state is returned; otherwise, an exception is raised.  On many
terminals, the “visible” mode is an underline cursor and the “very visible” mode
is a block cursor.</p>
</dd></dl>

<dl class="function">
<dt id="curses.def_prog_mode">
<code class="descclassname">curses.</code><code class="descname">def_prog_mode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.def_prog_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Save the current terminal mode as the “program” mode, the mode when the running
program is using curses.  (Its counterpart is the “shell” mode, for when the
program is not in curses.)  Subsequent calls to <a class="reference internal" href="#curses.reset_prog_mode" title="curses.reset_prog_mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">reset_prog_mode()</span></code></a> will
restore this mode.</p>
</dd></dl>

<dl class="function">
<dt id="curses.def_shell_mode">
<code class="descclassname">curses.</code><code class="descname">def_shell_mode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.def_shell_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Save the current terminal mode as the “shell” mode, the mode when the running
program is not using curses.  (Its counterpart is the “program” mode, when the
program is using curses capabilities.) Subsequent calls to
<a class="reference internal" href="#curses.reset_shell_mode" title="curses.reset_shell_mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">reset_shell_mode()</span></code></a> will restore this mode.</p>
</dd></dl>

<dl class="function">
<dt id="curses.delay_output">
<code class="descclassname">curses.</code><code class="descname">delay_output</code><span class="sig-paren">(</span><em>ms</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.delay_output" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert an <em>ms</em> millisecond pause in output.</p>
</dd></dl>

<dl class="function">
<dt id="curses.doupdate">
<code class="descclassname">curses.</code><code class="descname">doupdate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.doupdate" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the physical screen.  The curses library keeps two data structures, one
representing the current physical screen contents and a virtual screen
representing the desired next state.  The <a class="reference internal" href="#curses.doupdate" title="curses.doupdate"><code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code></a> ground updates the
physical screen to match the virtual screen.</p>
<p>The virtual screen may be updated by a <code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code> call after write
operations such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">addstr()</span></code> have been performed on a window.  The normal
<code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code> call is simply <code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code> followed by <a class="reference internal" href="#curses.doupdate" title="curses.doupdate"><code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code></a>;
if you have to update multiple windows, you can speed performance and perhaps
reduce screen flicker by issuing <code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code> calls on all windows,
followed by a single <a class="reference internal" href="#curses.doupdate" title="curses.doupdate"><code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.echo">
<code class="descclassname">curses.</code><code class="descname">echo</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.echo" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter echo mode.  In echo mode, each character input is echoed to the screen as
it is entered.</p>
</dd></dl>

<dl class="function">
<dt id="curses.endwin">
<code class="descclassname">curses.</code><code class="descname">endwin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.endwin" title="Permalink to this definition">¶</a></dt>
<dd><p>De-initialize the library, and return terminal to normal status.</p>
</dd></dl>

<dl class="function">
<dt id="curses.erasechar">
<code class="descclassname">curses.</code><code class="descname">erasechar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.erasechar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the user’s current erase character.  Under Unix operating systems this
is a property of the controlling tty of the curses program, and is not set by
the curses library itself.</p>
</dd></dl>

<dl class="function">
<dt id="curses.filter">
<code class="descclassname">curses.</code><code class="descname">filter</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#curses.filter" title="curses.filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> routine, if used, must be called before <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a> is
called.  The effect is that, during those calls, <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LINES</span></code> is set to 1; the
capabilities clear, cup, cud, cud1, cuu1, cuu, vpa are disabled; and the home
string is set to the value of cr. The effect is that the cursor is confined to
the current line, and so are screen updates.  This may be used for enabling
character-at-a-time  line editing without touching the rest of the screen.</p>
</dd></dl>

<dl class="function">
<dt id="curses.flash">
<code class="descclassname">curses.</code><code class="descname">flash</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.flash" title="Permalink to this definition">¶</a></dt>
<dd><p>Flash the screen.  That is, change it to reverse-video and then change it back
in a short interval.  Some people prefer such as ‘visible bell’ to the audible
attention signal produced by <a class="reference internal" href="#curses.beep" title="curses.beep"><code class="xref py py-func docutils literal notranslate"><span class="pre">beep()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.flushinp">
<code class="descclassname">curses.</code><code class="descname">flushinp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.flushinp" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush all input buffers.  This throws away any  typeahead  that  has been typed
by the user and has not yet been processed by the program.</p>
</dd></dl>

<dl class="function">
<dt id="curses.getmouse">
<code class="descclassname">curses.</code><code class="descname">getmouse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.getmouse" title="Permalink to this definition">¶</a></dt>
<dd><p>After <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> returns <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_MOUSE</span></code> to signal a mouse event, this
method should be call to retrieve the queued mouse event, represented as a
5-tuple <code class="docutils literal notranslate"><span class="pre">(id,</span> <span class="pre">x,</span> <span class="pre">y,</span> <span class="pre">z,</span> <span class="pre">bstate)</span></code>. <em>id</em> is an ID value used to distinguish
multiple devices, and <em>x</em>, <em>y</em>, <em>z</em> are the event’s coordinates.  (<em>z</em> is
currently unused.)  <em>bstate</em> is an integer value whose bits will be set to
indicate the type of event, and will be the bitwise OR of one or more of the
following constants, where <em>n</em> is the button number from 1 to 4:
<code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTONn_PRESSED</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTONn_RELEASED</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTONn_CLICKED</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTONn_DOUBLE_CLICKED</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTONn_TRIPLE_CLICKED</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTON_SHIFT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTON_CTRL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BUTTON_ALT</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.getsyx">
<code class="descclassname">curses.</code><code class="descname">getsyx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.getsyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current coordinates of the virtual screen cursor in y and x.  If
leaveok is currently true, then -1,-1 is returned.</p>
</dd></dl>

<dl class="function">
<dt id="curses.getwin">
<code class="descclassname">curses.</code><code class="descname">getwin</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.getwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Read window related data stored in the file by an earlier <code class="xref py py-func docutils literal notranslate"><span class="pre">putwin()</span></code> call.
The routine then creates and initializes a new window using that data, returning
the new window object.</p>
</dd></dl>

<dl class="function">
<dt id="curses.has_colors">
<code class="descclassname">curses.</code><code class="descname">has_colors</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.has_colors" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the terminal can display colors; otherwise, return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.has_ic">
<code class="descclassname">curses.</code><code class="descname">has_ic</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.has_ic" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the terminal has insert- and delete-character capabilities.
This function is included for historical reasons only, as all modern software
terminal emulators have such capabilities.</p>
</dd></dl>

<dl class="function">
<dt id="curses.has_il">
<code class="descclassname">curses.</code><code class="descname">has_il</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.has_il" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the terminal has insert- and delete-line capabilities, or can
simulate  them  using scrolling regions. This function is included for
historical reasons only, as all modern software terminal emulators have such
capabilities.</p>
</dd></dl>

<dl class="function">
<dt id="curses.has_key">
<code class="descclassname">curses.</code><code class="descname">has_key</code><span class="sig-paren">(</span><em>ch</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.has_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Take a key value <em>ch</em>, and return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the current terminal type recognizes
a key with that value.</p>
</dd></dl>

<dl class="function">
<dt id="curses.halfdelay">
<code class="descclassname">curses.</code><code class="descname">halfdelay</code><span class="sig-paren">(</span><em>tenths</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.halfdelay" title="Permalink to this definition">¶</a></dt>
<dd><p>Used for half-delay mode, which is similar to cbreak mode in that characters
typed by the user are immediately available to the program. However, after
blocking for <em>tenths</em> tenths of seconds, an exception is raised if nothing has
been typed.  The value of <em>tenths</em> must be a number between <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">255</span></code>.  Use
<a class="reference internal" href="#curses.nocbreak" title="curses.nocbreak"><code class="xref py py-func docutils literal notranslate"><span class="pre">nocbreak()</span></code></a> to leave half-delay mode.</p>
</dd></dl>

<dl class="function">
<dt id="curses.init_color">
<code class="descclassname">curses.</code><code class="descname">init_color</code><span class="sig-paren">(</span><em>color_number</em>, <em>r</em>, <em>g</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.init_color" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the definition of a color, taking the number of the color to be changed
followed by three RGB values (for the amounts of red, green, and blue
components).  The value of <em>color_number</em> must be between <code class="docutils literal notranslate"><span class="pre">0</span></code> and
<code class="xref py py-const docutils literal notranslate"><span class="pre">COLORS</span></code>.  Each of <em>r</em>, <em>g</em>, <em>b</em>, must be a value between <code class="docutils literal notranslate"><span class="pre">0</span></code> and
<code class="docutils literal notranslate"><span class="pre">1000</span></code>.  When <a class="reference internal" href="#curses.init_color" title="curses.init_color"><code class="xref py py-func docutils literal notranslate"><span class="pre">init_color()</span></code></a> is used, all occurrences of that color on the
screen immediately change to the new definition.  This function is a no-op on
most terminals; it is active only if <a class="reference internal" href="#curses.can_change_color" title="curses.can_change_color"><code class="xref py py-func docutils literal notranslate"><span class="pre">can_change_color()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.init_pair">
<code class="descclassname">curses.</code><code class="descname">init_pair</code><span class="sig-paren">(</span><em>pair_number</em>, <em>fg</em>, <em>bg</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.init_pair" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the definition of a color-pair.  It takes three arguments: the number of
the color-pair to be changed, the foreground color number, and the background
color number.  The value of <em>pair_number</em> must be between <code class="docutils literal notranslate"><span class="pre">1</span></code> and
<code class="docutils literal notranslate"><span class="pre">COLOR_PAIRS</span> <span class="pre">-</span> <span class="pre">1</span></code> (the <code class="docutils literal notranslate"><span class="pre">0</span></code> color pair is wired to white on black and cannot
be changed).  The value of <em>fg</em> and <em>bg</em> arguments must be between <code class="docutils literal notranslate"><span class="pre">0</span></code> and
<code class="xref py py-const docutils literal notranslate"><span class="pre">COLORS</span></code>.  If the color-pair was previously initialized, the screen is
refreshed and all occurrences of that color-pair are changed to the new
definition.</p>
</dd></dl>

<dl class="function">
<dt id="curses.initscr">
<code class="descclassname">curses.</code><code class="descname">initscr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.initscr" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the library. Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">WindowObject</span></code> which represents the
whole screen.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If there is an error opening the terminal, the underlying curses library may
cause the interpreter to exit.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="curses.is_term_resized">
<code class="descclassname">curses.</code><code class="descname">is_term_resized</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.is_term_resized" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <a class="reference internal" href="#curses.resize_term" title="curses.resize_term"><code class="xref py py-func docutils literal notranslate"><span class="pre">resize_term()</span></code></a> would modify the window structure,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="function">
<dt id="curses.isendwin">
<code class="descclassname">curses.</code><code class="descname">isendwin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.isendwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <a class="reference internal" href="#curses.endwin" title="curses.endwin"><code class="xref py py-func docutils literal notranslate"><span class="pre">endwin()</span></code></a> has been called (that is, the  curses library has
been deinitialized).</p>
</dd></dl>

<dl class="function">
<dt id="curses.keyname">
<code class="descclassname">curses.</code><code class="descname">keyname</code><span class="sig-paren">(</span><em>k</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.keyname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the key numbered <em>k</em>.  The name of a key generating printable
ASCII character is the key’s character.  The name of a control-key combination
is a two-character string consisting of a caret followed by the corresponding
printable ASCII character.  The name of an alt-key combination (128–255) is a
string consisting of the prefix ‘M-‘ followed by the name of the corresponding
ASCII character.</p>
</dd></dl>

<dl class="function">
<dt id="curses.killchar">
<code class="descclassname">curses.</code><code class="descname">killchar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.killchar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the user’s current line kill character. Under Unix operating systems
this is a property of the controlling tty of the curses program, and is not set
by the curses library itself.</p>
</dd></dl>

<dl class="function">
<dt id="curses.longname">
<code class="descclassname">curses.</code><code class="descname">longname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.longname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing the terminfo long name field describing the current
terminal.  The maximum length of a verbose description is 128 characters.  It is
defined only after the call to <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.meta">
<code class="descclassname">curses.</code><code class="descname">meta</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.meta" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is 1, allow 8-bit characters to be input. If <em>yes</em> is 0,  allow only
7-bit chars.</p>
</dd></dl>

<dl class="function">
<dt id="curses.mouseinterval">
<code class="descclassname">curses.</code><code class="descname">mouseinterval</code><span class="sig-paren">(</span><em>interval</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.mouseinterval" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the maximum time in milliseconds that can elapse between press and release
events in order for them to be recognized as a click, and return the previous
interval value.  The default value is 200 msec, or one fifth of a second.</p>
</dd></dl>

<dl class="function">
<dt id="curses.mousemask">
<code class="descclassname">curses.</code><code class="descname">mousemask</code><span class="sig-paren">(</span><em>mousemask</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.mousemask" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the mouse events to be reported, and return a tuple <code class="docutils literal notranslate"><span class="pre">(availmask,</span>
<span class="pre">oldmask)</span></code>.   <em>availmask</em> indicates which of the specified mouse events can be
reported; on complete failure it returns 0.  <em>oldmask</em> is the previous value of
the given window’s mouse event mask.  If this function is never called, no mouse
events are ever reported.</p>
</dd></dl>

<dl class="function">
<dt id="curses.napms">
<code class="descclassname">curses.</code><code class="descname">napms</code><span class="sig-paren">(</span><em>ms</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.napms" title="Permalink to this definition">¶</a></dt>
<dd><p>Sleep for <em>ms</em> milliseconds.</p>
</dd></dl>

<dl class="function">
<dt id="curses.newpad">
<code class="descclassname">curses.</code><code class="descname">newpad</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.newpad" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a pointer to a new pad data structure with the given number
of lines and columns.  A pad is returned as a window object.</p>
<p>A pad is like a window, except that it is not restricted by the screen size, and
is not necessarily associated with a particular part of the screen.  Pads can be
used when a large window is needed, and only a part of the window will be on the
screen at one time.  Automatic refreshes of pads (such as from scrolling or
echoing of input) do not occur.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">noutrefresh()</span></code>
methods of a pad require 6 arguments to specify the part of the pad to be
displayed and the location on the screen to be used for the display. The
arguments are <em>pminrow</em>, <em>pmincol</em>, <em>sminrow</em>, <em>smincol</em>, <em>smaxrow</em>, <em>smaxcol</em>; the <em>p</em>
arguments refer to the upper left corner of the pad region to be displayed and
the <em>s</em> arguments define a clipping box on the screen within which the pad region
is to be displayed.</p>
</dd></dl>

<dl class="function">
<dt id="curses.newwin">
<code class="descclassname">curses.</code><code class="descname">newwin</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.newwin" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">curses.</code><code class="descname">newwin</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em>, <em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span></dt>
<dd><p>Return a new window, whose left-upper corner is at  <code class="docutils literal notranslate"><span class="pre">(begin_y,</span> <span class="pre">begin_x)</span></code>, and
whose height/width is  <em>nlines</em>/<em>ncols</em>.</p>
<p>By default, the window will extend from the  specified position to the lower
right corner of the screen.</p>
</dd></dl>

<dl class="function">
<dt id="curses.nl">
<code class="descclassname">curses.</code><code class="descname">nl</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.nl" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter newline mode.  This mode translates the return key into newline on input,
and translates newline into return and line-feed on output. Newline mode is
initially on.</p>
</dd></dl>

<dl class="function">
<dt id="curses.nocbreak">
<code class="descclassname">curses.</code><code class="descname">nocbreak</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.nocbreak" title="Permalink to this definition">¶</a></dt>
<dd><p>Leave cbreak mode.  Return to normal “cooked” mode with line buffering.</p>
</dd></dl>

<dl class="function">
<dt id="curses.noecho">
<code class="descclassname">curses.</code><code class="descname">noecho</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.noecho" title="Permalink to this definition">¶</a></dt>
<dd><p>Leave echo mode.  Echoing of input characters is turned off.</p>
</dd></dl>

<dl class="function">
<dt id="curses.nonl">
<code class="descclassname">curses.</code><code class="descname">nonl</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.nonl" title="Permalink to this definition">¶</a></dt>
<dd><p>Leave newline mode.  Disable translation of return into newline on input, and
disable low-level translation of newline into newline/return on output (but this
does not change the behavior of <code class="docutils literal notranslate"><span class="pre">addch('\n')</span></code>, which always does the
equivalent of return and line feed on the virtual screen).  With translation
off, curses can sometimes speed up vertical motion a little; also, it will be
able to detect the return key on input.</p>
</dd></dl>

<dl class="function">
<dt id="curses.noqiflush">
<code class="descclassname">curses.</code><code class="descname">noqiflush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.noqiflush" title="Permalink to this definition">¶</a></dt>
<dd><p>When the <a class="reference internal" href="#curses.noqiflush" title="curses.noqiflush"><code class="xref py py-func docutils literal notranslate"><span class="pre">noqiflush()</span></code></a> routine is used, normal flush of input and output queues
associated with the INTR, QUIT and SUSP characters will not be done.  You may
want to call <a class="reference internal" href="#curses.noqiflush" title="curses.noqiflush"><code class="xref py py-func docutils literal notranslate"><span class="pre">noqiflush()</span></code></a> in a signal handler if you want output to
continue as though the interrupt had not occurred, after the handler exits.</p>
</dd></dl>

<dl class="function">
<dt id="curses.noraw">
<code class="descclassname">curses.</code><code class="descname">noraw</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.noraw" title="Permalink to this definition">¶</a></dt>
<dd><p>Leave raw mode. Return to normal “cooked” mode with line buffering.</p>
</dd></dl>

<dl class="function">
<dt id="curses.pair_content">
<code class="descclassname">curses.</code><code class="descname">pair_content</code><span class="sig-paren">(</span><em>pair_number</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.pair_content" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(fg,</span> <span class="pre">bg)</span></code> containing the colors for the requested color pair.
The value of <em>pair_number</em> must be between <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">COLOR_PAIRS</span> <span class="pre">-</span> <span class="pre">1</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.pair_number">
<code class="descclassname">curses.</code><code class="descname">pair_number</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.pair_number" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of the color-pair set by the attribute value <em>attr</em>.
<a class="reference internal" href="#curses.color_pair" title="curses.color_pair"><code class="xref py py-func docutils literal notranslate"><span class="pre">color_pair()</span></code></a> is the counterpart to this function.</p>
</dd></dl>

<dl class="function">
<dt id="curses.putp">
<code class="descclassname">curses.</code><code class="descname">putp</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.putp" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">tputs(str,</span> <span class="pre">1,</span> <span class="pre">putchar)</span></code>; emit the value of a specified
terminfo capability for the current terminal.  Note that the output of <a class="reference internal" href="#curses.putp" title="curses.putp"><code class="xref py py-func docutils literal notranslate"><span class="pre">putp()</span></code></a>
always goes to standard output.</p>
</dd></dl>

<dl class="function">
<dt id="curses.qiflush">
<code class="descclassname">curses.</code><code class="descname">qiflush</code><span class="sig-paren">(</span><span class="optional">[</span><em>flag</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.qiflush" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the effect is the same as calling <a class="reference internal" href="#curses.noqiflush" title="curses.noqiflush"><code class="xref py py-func docutils literal notranslate"><span class="pre">noqiflush()</span></code></a>. If
<em>flag</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, or no argument is provided, the queues will be flushed when
these control characters are read.</p>
</dd></dl>

<dl class="function">
<dt id="curses.raw">
<code class="descclassname">curses.</code><code class="descname">raw</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.raw" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter raw mode.  In raw mode, normal line buffering and  processing of
interrupt, quit, suspend, and flow control keys are turned off; characters are
presented to curses input functions one by one.</p>
</dd></dl>

<dl class="function">
<dt id="curses.reset_prog_mode">
<code class="descclassname">curses.</code><code class="descname">reset_prog_mode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.reset_prog_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the  terminal  to “program” mode, as previously saved  by
<a class="reference internal" href="#curses.def_prog_mode" title="curses.def_prog_mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">def_prog_mode()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.reset_shell_mode">
<code class="descclassname">curses.</code><code class="descname">reset_shell_mode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.reset_shell_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the  terminal  to “shell” mode, as previously saved  by
<a class="reference internal" href="#curses.def_shell_mode" title="curses.def_shell_mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">def_shell_mode()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.resetty">
<code class="descclassname">curses.</code><code class="descname">resetty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.resetty" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the state of the terminal modes to what it was at the last call to
<a class="reference internal" href="#curses.savetty" title="curses.savetty"><code class="xref py py-func docutils literal notranslate"><span class="pre">savetty()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.resize_term">
<code class="descclassname">curses.</code><code class="descname">resize_term</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.resize_term" title="Permalink to this definition">¶</a></dt>
<dd><p>Backend function used by <a class="reference internal" href="#curses.resizeterm" title="curses.resizeterm"><code class="xref py py-func docutils literal notranslate"><span class="pre">resizeterm()</span></code></a>, performing most of the work;
when resizing the windows, <a class="reference internal" href="#curses.resize_term" title="curses.resize_term"><code class="xref py py-func docutils literal notranslate"><span class="pre">resize_term()</span></code></a> blank-fills the areas that are
extended.  The calling application should fill in these areas with
appropriate data.  The <a class="reference internal" href="#curses.resize_term" title="curses.resize_term"><code class="xref py py-func docutils literal notranslate"><span class="pre">resize_term()</span></code></a> function attempts to resize all
windows.  However, due to the calling convention of pads, it is not possible
to resize these without additional interaction with the application.</p>
</dd></dl>

<dl class="function">
<dt id="curses.resizeterm">
<code class="descclassname">curses.</code><code class="descname">resizeterm</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.resizeterm" title="Permalink to this definition">¶</a></dt>
<dd><p>Resize the standard and current windows to the specified dimensions, and
adjusts other bookkeeping data used by the curses library that record the
window dimensions (in particular the SIGWINCH handler).</p>
</dd></dl>

<dl class="function">
<dt id="curses.savetty">
<code class="descclassname">curses.</code><code class="descname">savetty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.savetty" title="Permalink to this definition">¶</a></dt>
<dd><p>Save the current state of the terminal modes in a buffer, usable by
<a class="reference internal" href="#curses.resetty" title="curses.resetty"><code class="xref py py-func docutils literal notranslate"><span class="pre">resetty()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="curses.setsyx">
<code class="descclassname">curses.</code><code class="descname">setsyx</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.setsyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the virtual screen cursor to <em>y</em>, <em>x</em>. If <em>y</em> and <em>x</em> are both -1, then
leaveok is set.</p>
</dd></dl>

<dl class="function">
<dt id="curses.setupterm">
<code class="descclassname">curses.</code><code class="descname">setupterm</code><span class="sig-paren">(</span><span class="optional">[</span><em>termstr</em>, <em>fd</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.setupterm" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the terminal.  <em>termstr</em> is a string giving the terminal name; if
omitted, the value of the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TERM</span></code> environment variable will be used.  <em>fd</em> is the
file descriptor to which any initialization sequences will be sent; if not
supplied, the file descriptor for <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> will be used.</p>
</dd></dl>

<dl class="function">
<dt id="curses.start_color">
<code class="descclassname">curses.</code><code class="descname">start_color</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.start_color" title="Permalink to this definition">¶</a></dt>
<dd><p>Must be called if the programmer wants to use colors, and before any other color
manipulation routine is called.  It is good practice to call this routine right
after <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a>.</p>
<p><a class="reference internal" href="#curses.start_color" title="curses.start_color"><code class="xref py py-func docutils literal notranslate"><span class="pre">start_color()</span></code></a> initializes eight basic colors (black, red,  green, yellow,
blue, magenta, cyan, and white), and two global variables in the <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a>
module, <code class="xref py py-const docutils literal notranslate"><span class="pre">COLORS</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">COLOR_PAIRS</span></code>, containing the maximum number
of colors and color-pairs the terminal can support.  It also restores the colors
on the terminal to the values they had when the terminal was just turned on.</p>
</dd></dl>

<dl class="function">
<dt id="curses.termattrs">
<code class="descclassname">curses.</code><code class="descname">termattrs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.termattrs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a logical OR of all video attributes supported by the terminal.  This
information is useful when a curses program needs complete control over the
appearance of the screen.</p>
</dd></dl>

<dl class="function">
<dt id="curses.termname">
<code class="descclassname">curses.</code><code class="descname">termname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.termname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the environment variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TERM</span></code>, truncated to 14 characters.</p>
</dd></dl>

<dl class="function">
<dt id="curses.tigetflag">
<code class="descclassname">curses.</code><code class="descname">tigetflag</code><span class="sig-paren">(</span><em>capname</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.tigetflag" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the Boolean capability corresponding to the terminfo
capability name <em>capname</em>.  The value <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned if <em>capname</em> is not a
Boolean capability, or <code class="docutils literal notranslate"><span class="pre">0</span></code> if it is canceled or absent from the terminal
description.</p>
</dd></dl>

<dl class="function">
<dt id="curses.tigetnum">
<code class="descclassname">curses.</code><code class="descname">tigetnum</code><span class="sig-paren">(</span><em>capname</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.tigetnum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the numeric capability corresponding to the terminfo
capability name <em>capname</em>.  The value <code class="docutils literal notranslate"><span class="pre">-2</span></code> is returned if <em>capname</em> is not a
numeric capability, or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if it is canceled or absent from the terminal
description.</p>
</dd></dl>

<dl class="function">
<dt id="curses.tigetstr">
<code class="descclassname">curses.</code><code class="descname">tigetstr</code><span class="sig-paren">(</span><em>capname</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.tigetstr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the string capability corresponding to the terminfo
capability name <em>capname</em>.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned if <em>capname</em> is not a string
capability, or is canceled or absent from the terminal description.</p>
</dd></dl>

<dl class="function">
<dt id="curses.tparm">
<code class="descclassname">curses.</code><code class="descname">tparm</code><span class="sig-paren">(</span><em>str</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.tparm" title="Permalink to this definition">¶</a></dt>
<dd><p>Instantiate the string <em>str</em> with the supplied parameters, where <em>str</em> should
be a parameterized string obtained from the terminfo database.  E.g.
<code class="docutils literal notranslate"><span class="pre">tparm(tigetstr(&quot;cup&quot;),</span> <span class="pre">5,</span> <span class="pre">3)</span></code> could result in <code class="docutils literal notranslate"><span class="pre">'\033[6;4H'</span></code>, the exact
result depending on terminal type.</p>
</dd></dl>

<dl class="function">
<dt id="curses.typeahead">
<code class="descclassname">curses.</code><code class="descname">typeahead</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.typeahead" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify that the file descriptor <em>fd</em> be used for typeahead checking.  If <em>fd</em>
is <code class="docutils literal notranslate"><span class="pre">-1</span></code>, then no typeahead checking is done.</p>
<p>The curses library does “line-breakout optimization” by looking for typeahead
periodically while updating the screen.  If input is found, and it is coming
from a tty, the current update is postponed until refresh or doupdate is called
again, allowing faster response to commands typed in advance. This function
allows specifying a different file descriptor for typeahead checking.</p>
</dd></dl>

<dl class="function">
<dt id="curses.unctrl">
<code class="descclassname">curses.</code><code class="descname">unctrl</code><span class="sig-paren">(</span><em>ch</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.unctrl" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string which is a printable representation of the character <em>ch</em>.
Control characters are displayed as a caret followed by the character, for
example as <code class="docutils literal notranslate"><span class="pre">^C</span></code>. Printing characters are left as they are.</p>
</dd></dl>

<dl class="function">
<dt id="curses.ungetch">
<code class="descclassname">curses.</code><code class="descname">ungetch</code><span class="sig-paren">(</span><em>ch</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ungetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Push <em>ch</em> so the next <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> will return it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Only one <em>ch</em> can be pushed before <code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code> is called.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="curses.ungetmouse">
<code class="descclassname">curses.</code><code class="descname">ungetmouse</code><span class="sig-paren">(</span><em>id</em>, <em>x</em>, <em>y</em>, <em>z</em>, <em>bstate</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.ungetmouse" title="Permalink to this definition">¶</a></dt>
<dd><p>Push a <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_MOUSE</span></code> event onto the input queue, associating the given
state data with it.</p>
</dd></dl>

<dl class="function">
<dt id="curses.use_env">
<code class="descclassname">curses.</code><code class="descname">use_env</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.use_env" title="Permalink to this definition">¶</a></dt>
<dd><p>If used, this function should be called before <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a> or newterm are
called.  When <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the values of lines and columns specified in the
terminfo database will be used, even if environment variables <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LINES</span></code>
and <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">COLUMNS</span></code> (used by default) are set, or if curses is running in a
window (in which case default behavior would be to use the window size if
<span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LINES</span></code> and <span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">COLUMNS</span></code> are not set).</p>
</dd></dl>

<dl class="function">
<dt id="curses.use_default_colors">
<code class="descclassname">curses.</code><code class="descname">use_default_colors</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.use_default_colors" title="Permalink to this definition">¶</a></dt>
<dd><p>Allow use of default values for colors on terminals supporting this feature. Use
this to support transparency in your application.  The default color is assigned
to the color number -1. After calling this function,  <code class="docutils literal notranslate"><span class="pre">init_pair(x,</span>
<span class="pre">curses.COLOR_RED,</span> <span class="pre">-1)</span></code> initializes, for instance, color pair <em>x</em> to a red
foreground color on the default background.</p>
</dd></dl>

<dl class="function">
<dt id="curses.wrapper">
<code class="descclassname">curses.</code><code class="descname">wrapper</code><span class="sig-paren">(</span><em>func</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.wrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize curses and call another callable object, <em>func</em>, which should be the
rest of your curses-using application.  If the application raises an exception,
this function will restore the terminal to a sane state before re-raising the
exception and generating a traceback.  The callable object <em>func</em> is then passed
the main window ‘stdscr’ as its first argument, followed by any other arguments
passed to <a class="reference internal" href="#curses.wrapper" title="curses.wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrapper()</span></code></a>.  Before calling <em>func</em>, <a class="reference internal" href="#curses.wrapper" title="curses.wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrapper()</span></code></a> turns on
cbreak mode, turns off echo, enables the terminal keypad, and initializes colors
if the terminal has color support.  On exit (whether normally or by exception)
it restores cooked mode, turns on echo, and disables the terminal keypad.</p>
</dd></dl>

</div>
<div class="section" id="window-objects">
<span id="curses-window-objects"></span><h2>15.11.2. Window Objects<a class="headerlink" href="#window-objects" title="Permalink to this headline">¶</a></h2>
<p>Window objects, as returned by <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a> and <a class="reference internal" href="#curses.newwin" title="curses.newwin"><code class="xref py py-func docutils literal notranslate"><span class="pre">newwin()</span></code></a> above, have
the following methods:</p>
<dl class="method">
<dt id="curses.window.addch">
<code class="descclassname">window.</code><code class="descname">addch</code><span class="sig-paren">(</span><em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.addch" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">addch</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">A <em>character</em> means a C character (an ASCII code), rather than a Python
character (a string of length 1). (This note is true whenever the
documentation mentions a character.) The built-in <a class="reference internal" href="functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> is handy for
conveying strings to codes.</p>
</div>
<p>Paint character <em>ch</em> at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with attributes <em>attr</em>, overwriting any
character previously painter at that location.  By default, the character
position and attributes are the current settings for the window object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Writing outside the window, subwindow, or pad raises a <a class="reference internal" href="#curses.error" title="curses.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">curses.error</span></code></a>.
Attempting to write to the lower right corner of a window, subwindow,
or pad will cause an exception to be raised after the character is printed.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="curses.window.addnstr">
<code class="descclassname">window.</code><code class="descname">addnstr</code><span class="sig-paren">(</span><em>str</em>, <em>n</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.addnstr" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">addnstr</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>str</em>, <em>n</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Paint at most <em>n</em> characters of the  string <em>str</em> at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with attributes
<em>attr</em>, overwriting anything previously on the display.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.addstr">
<code class="descclassname">window.</code><code class="descname">addstr</code><span class="sig-paren">(</span><em>str</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.addstr" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">addstr</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>str</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Paint the string <em>str</em> at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with attributes <em>attr</em>, overwriting
anything previously on the display.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Writing outside the window, subwindow, or pad raises <a class="reference internal" href="#curses.error" title="curses.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">curses.error</span></code></a>.
Attempting to write to the lower right corner of a window, subwindow,
or pad will cause an exception to be raised after the string is printed.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="curses.window.attroff">
<code class="descclassname">window.</code><code class="descname">attroff</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.attroff" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove attribute <em>attr</em> from the “background” set applied to all writes to the
current window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.attron">
<code class="descclassname">window.</code><code class="descname">attron</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.attron" title="Permalink to this definition">¶</a></dt>
<dd><p>Add attribute <em>attr</em> from the “background” set applied to all writes to the
current window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.attrset">
<code class="descclassname">window.</code><code class="descname">attrset</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.attrset" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the “background” set of attributes to <em>attr</em>.  This set is initially 0 (no
attributes).</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.bkgd">
<code class="descclassname">window.</code><code class="descname">bkgd</code><span class="sig-paren">(</span><em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.bkgd" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the background property of the window to the character <em>ch</em>, with
attributes <em>attr</em>.  The change is then applied to every character position in
that window:</p>
<ul class="simple">
<li>The attribute of every character in the window  is changed to the new
background attribute.</li>
<li>Wherever  the  former background character appears, it is changed to the new
background character.</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="curses.window.bkgdset">
<code class="descclassname">window.</code><code class="descname">bkgdset</code><span class="sig-paren">(</span><em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.bkgdset" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the window’s background.  A window’s background consists of a character and
any combination of attributes.  The attribute part of the background is combined
(OR’ed) with all non-blank characters that are written into the window.  Both
the character and attribute parts of the background are combined with the blank
characters.  The background becomes a property of the character and moves with
the character through any scrolling and insert/delete line/character operations.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.border">
<code class="descclassname">window.</code><code class="descname">border</code><span class="sig-paren">(</span><span class="optional">[</span><em>ls</em><span class="optional">[</span>, <em>rs</em><span class="optional">[</span>, <em>ts</em><span class="optional">[</span>, <em>bs</em><span class="optional">[</span>, <em>tl</em><span class="optional">[</span>, <em>tr</em><span class="optional">[</span>, <em>bl</em><span class="optional">[</span>, <em>br</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.border" title="Permalink to this definition">¶</a></dt>
<dd><p>Draw a border around the edges of the window. Each parameter specifies  the
character to use for a specific part of the border; see the table below for more
details.  The characters can be specified as integers or as one-character
strings.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">A <code class="docutils literal notranslate"><span class="pre">0</span></code> value for any parameter will cause the default character to be used for
that parameter.  Keyword parameters can <em>not</em> be used.  The defaults are listed
in this table:</p>
</div>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="38%" />
<col width="42%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Parameter</th>
<th class="head">Description</th>
<th class="head">Default value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>ls</em></td>
<td>Left side</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_VLINE</span></code></td>
</tr>
<tr class="row-odd"><td><em>rs</em></td>
<td>Right side</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_VLINE</span></code></td>
</tr>
<tr class="row-even"><td><em>ts</em></td>
<td>Top</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_HLINE</span></code></td>
</tr>
<tr class="row-odd"><td><em>bs</em></td>
<td>Bottom</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_HLINE</span></code></td>
</tr>
<tr class="row-even"><td><em>tl</em></td>
<td>Upper-left corner</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_ULCORNER</span></code></td>
</tr>
<tr class="row-odd"><td><em>tr</em></td>
<td>Upper-right corner</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_URCORNER</span></code></td>
</tr>
<tr class="row-even"><td><em>bl</em></td>
<td>Bottom-left corner</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_LLCORNER</span></code></td>
</tr>
<tr class="row-odd"><td><em>br</em></td>
<td>Bottom-right corner</td>
<td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACS_LRCORNER</span></code></td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="curses.window.box">
<code class="descclassname">window.</code><code class="descname">box</code><span class="sig-paren">(</span><span class="optional">[</span><em>vertch</em>, <em>horch</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.box" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#curses.window.border" title="curses.window.border"><code class="xref py py-meth docutils literal notranslate"><span class="pre">border()</span></code></a>, but both <em>ls</em> and <em>rs</em> are <em>vertch</em> and both <em>ts</em> and
<em>bs</em> are <em>horch</em>.  The default corner characters are always used by this function.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.chgat">
<code class="descclassname">window.</code><code class="descname">chgat</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.chgat" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">chgat</code><span class="sig-paren">(</span><em>num</em>, <em>attr</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">chgat</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>attr</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">chgat</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>num</em>, <em>attr</em><span class="sig-paren">)</span></dt>
<dd><p>Set the attributes of <em>num</em> characters at the current cursor position, or at
position <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> if supplied. If <em>num</em> is not given or is <code class="docutils literal notranslate"><span class="pre">-1</span></code>,
the attribute will be set on all the characters to the end of the line.  This
function moves cursor to position <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> if supplied. The changed line
will be touched using the <a class="reference internal" href="#curses.window.touchline" title="curses.window.touchline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">touchline()</span></code></a> method so that the contents will
be redisplayed by the next window refresh.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.clear">
<code class="descclassname">window.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#curses.window.erase" title="curses.window.erase"><code class="xref py py-meth docutils literal notranslate"><span class="pre">erase()</span></code></a>, but also cause the whole window to be repainted upon next
call to <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.clearok">
<code class="descclassname">window.</code><code class="descname">clearok</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.clearok" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is 1, the next call to <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a> will clear the window
completely.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.clrtobot">
<code class="descclassname">window.</code><code class="descname">clrtobot</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.clrtobot" title="Permalink to this definition">¶</a></dt>
<dd><p>Erase from cursor to the end of the window: all lines below the cursor are
deleted, and then the equivalent of <a class="reference internal" href="#curses.window.clrtoeol" title="curses.window.clrtoeol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clrtoeol()</span></code></a> is performed.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.clrtoeol">
<code class="descclassname">window.</code><code class="descname">clrtoeol</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.clrtoeol" title="Permalink to this definition">¶</a></dt>
<dd><p>Erase from cursor to the end of the line.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.cursyncup">
<code class="descclassname">window.</code><code class="descname">cursyncup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.cursyncup" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the current cursor position of all the ancestors of the window to
reflect the current cursor position of the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.delch">
<code class="descclassname">window.</code><code class="descname">delch</code><span class="sig-paren">(</span><span class="optional">[</span><em>y</em>, <em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.delch" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete any character at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.deleteln">
<code class="descclassname">window.</code><code class="descname">deleteln</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.deleteln" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the line under the cursor. All following lines are moved up by one line.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.derwin">
<code class="descclassname">window.</code><code class="descname">derwin</code><span class="sig-paren">(</span><em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.derwin" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">derwin</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em>, <em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span></dt>
<dd><p>An abbreviation for “derive window”, <a class="reference internal" href="#curses.window.derwin" title="curses.window.derwin"><code class="xref py py-meth docutils literal notranslate"><span class="pre">derwin()</span></code></a> is the same as calling
<a class="reference internal" href="#curses.window.subwin" title="curses.window.subwin"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subwin()</span></code></a>, except that <em>begin_y</em> and <em>begin_x</em> are relative to the origin
of the window, rather than relative to the entire screen.  Return a window
object for the derived window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.echochar">
<code class="descclassname">window.</code><code class="descname">echochar</code><span class="sig-paren">(</span><em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.echochar" title="Permalink to this definition">¶</a></dt>
<dd><p>Add character <em>ch</em> with attribute <em>attr</em>, and immediately  call <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>
on the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.enclose">
<code class="descclassname">window.</code><code class="descname">enclose</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.enclose" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether the given pair of screen-relative character-cell coordinates are
enclosed by the given window, returning <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.  It is useful for
determining what subset of the screen windows enclose the location of a mouse
event.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.erase">
<code class="descclassname">window.</code><code class="descname">erase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.erase" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getbegyx">
<code class="descclassname">window.</code><code class="descname">getbegyx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getbegyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> of co-ordinates of upper-left corner.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getbkgd">
<code class="descclassname">window.</code><code class="descname">getbkgd</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getbkgd" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the given window’s current background character/attribute pair.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getch">
<code class="descclassname">window.</code><code class="descname">getch</code><span class="sig-paren">(</span><span class="optional">[</span><em>y</em>, <em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getch" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a character. Note that the integer returned does <em>not</em> have to be in ASCII
range: function keys, keypad keys and so on return numbers higher than 256. In
no-delay mode, -1 is returned if there is no input, else <a class="reference internal" href="#curses.window.getch" title="curses.window.getch"><code class="xref py py-func docutils literal notranslate"><span class="pre">getch()</span></code></a> waits
until a key is pressed.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getkey">
<code class="descclassname">window.</code><code class="descname">getkey</code><span class="sig-paren">(</span><span class="optional">[</span><em>y</em>, <em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getkey" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a character, returning a string instead of an integer, as <a class="reference internal" href="#curses.window.getch" title="curses.window.getch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code></a>
does. Function keys, keypad keys and so on return a multibyte string containing
the key name.  In no-delay mode, an exception is raised if there is no input.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getmaxyx">
<code class="descclassname">window.</code><code class="descname">getmaxyx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getmaxyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> of the height and width of the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getparyx">
<code class="descclassname">window.</code><code class="descname">getparyx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getparyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the beginning coordinates of this window relative to its parent window
into two integer variables y and x.  Return <code class="docutils literal notranslate"><span class="pre">-1,</span> <span class="pre">-1</span></code> if this window has no
parent.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getstr">
<code class="descclassname">window.</code><code class="descname">getstr</code><span class="sig-paren">(</span><span class="optional">[</span><em>y</em>, <em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getstr" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a string from the user, with primitive line editing capacity.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.getyx">
<code class="descclassname">window.</code><code class="descname">getyx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.getyx" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> of current cursor position  relative to the window’s
upper-left corner.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.hline">
<code class="descclassname">window.</code><code class="descname">hline</code><span class="sig-paren">(</span><em>ch</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.hline" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">hline</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>ch</em>, <em>n</em><span class="sig-paren">)</span></dt>
<dd><p>Display a horizontal line starting at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with length <em>n</em> consisting of
the character <em>ch</em>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.idcok">
<code class="descclassname">window.</code><code class="descname">idcok</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.idcok" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, curses no longer considers using the hardware insert/delete
character feature of the terminal; if <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, use of character insertion
and deletion is enabled.  When curses is first initialized, use of character
insert/delete is enabled by default.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.idlok">
<code class="descclassname">window.</code><code class="descname">idlok</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.idlok" title="Permalink to this definition">¶</a></dt>
<dd><p>If called with <em>yes</em> equal to 1, <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> will try and use hardware line
editing facilities. Otherwise, line insertion/deletion are disabled.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.immedok">
<code class="descclassname">window.</code><code class="descname">immedok</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.immedok" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, any change in the window image automatically causes the
window to be refreshed; you no longer have to call <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a> yourself.
However, it may degrade performance considerably, due to repeated calls to
wrefresh.  This option is disabled by default.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.inch">
<code class="descclassname">window.</code><code class="descname">inch</code><span class="sig-paren">(</span><span class="optional">[</span><em>y</em>, <em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.inch" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the character at the given position in the window. The bottom 8 bits are
the character proper, and upper bits are the attributes.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.insch">
<code class="descclassname">window.</code><code class="descname">insch</code><span class="sig-paren">(</span><em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.insch" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">insch</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>ch</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Paint character <em>ch</em> at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with attributes <em>attr</em>, moving the line from
position <em>x</em> right by one character.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.insdelln">
<code class="descclassname">window.</code><code class="descname">insdelln</code><span class="sig-paren">(</span><em>nlines</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.insdelln" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert <em>nlines</em> lines into the specified window above the current line.  The
<em>nlines</em> bottom lines are lost.  For negative <em>nlines</em>, delete <em>nlines</em> lines
starting with the one under the cursor, and move the remaining lines up.  The
bottom <em>nlines</em> lines are cleared.  The current cursor position remains the
same.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.insertln">
<code class="descclassname">window.</code><code class="descname">insertln</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.insertln" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a blank line under the cursor. All following lines are moved down by one
line.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.insnstr">
<code class="descclassname">window.</code><code class="descname">insnstr</code><span class="sig-paren">(</span><em>str</em>, <em>n</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.insnstr" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">insnstr</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>str</em>, <em>n</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Insert a character string (as many characters as will fit on the line) before
the character under the cursor, up to <em>n</em> characters.   If <em>n</em> is zero or
negative, the entire string is inserted. All characters to the right of the
cursor are shifted right, with the rightmost characters on the line being lost.
The cursor position does not change (after moving to <em>y</em>, <em>x</em>, if specified).</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.insstr">
<code class="descclassname">window.</code><code class="descname">insstr</code><span class="sig-paren">(</span><em>str</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.insstr" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">insstr</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>str</em><span class="optional">[</span>, <em>attr</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Insert a character string (as many characters as will fit on the line) before
the character under the cursor.  All characters to the right of the cursor are
shifted right, with the rightmost characters on the line being lost.  The cursor
position does not change (after moving to <em>y</em>, <em>x</em>, if specified).</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.instr">
<code class="descclassname">window.</code><code class="descname">instr</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.instr" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">instr</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="optional">[</span>, <em>n</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a string of characters, extracted from the window starting at the
current cursor position, or at <em>y</em>, <em>x</em> if specified. Attributes are stripped
from the characters.  If <em>n</em> is specified, <a class="reference internal" href="#curses.window.instr" title="curses.window.instr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">instr()</span></code></a> returns a string
at most <em>n</em> characters long (exclusive of the trailing NUL).</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.is_linetouched">
<code class="descclassname">window.</code><code class="descname">is_linetouched</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.is_linetouched" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the specified line was modified since the last call to
<a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>; otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.  Raise a <a class="reference internal" href="#curses.error" title="curses.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">curses.error</span></code></a>
exception if <em>line</em> is not valid for the given window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.is_wintouched">
<code class="descclassname">window.</code><code class="descname">is_wintouched</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.is_wintouched" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the specified window was modified since the last call to
<a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>; otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.keypad">
<code class="descclassname">window.</code><code class="descname">keypad</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.keypad" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is 1, escape sequences generated by some keys (keypad,  function keys)
will be interpreted by <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a>. If <em>yes</em> is 0, escape sequences will be
left as is in the input stream.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.leaveok">
<code class="descclassname">window.</code><code class="descname">leaveok</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.leaveok" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is 1, cursor is left where it is on update, instead of being at “cursor
position.”  This reduces cursor movement where possible. If possible the cursor
will be made invisible.</p>
<p>If <em>yes</em> is 0, cursor will always be at “cursor position” after an update.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.move">
<code class="descclassname">window.</code><code class="descname">move</code><span class="sig-paren">(</span><em>new_y</em>, <em>new_x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Move cursor to <code class="docutils literal notranslate"><span class="pre">(new_y,</span> <span class="pre">new_x)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.mvderwin">
<code class="descclassname">window.</code><code class="descname">mvderwin</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.mvderwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Move the window inside its parent window.  The screen-relative parameters of
the window are not changed.  This routine is used to display different parts of
the parent window at the same physical position on the screen.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.mvwin">
<code class="descclassname">window.</code><code class="descname">mvwin</code><span class="sig-paren">(</span><em>new_y</em>, <em>new_x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.mvwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Move the window so its upper-left corner is at <code class="docutils literal notranslate"><span class="pre">(new_y,</span> <span class="pre">new_x)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.nodelay">
<code class="descclassname">window.</code><code class="descname">nodelay</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.nodelay" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is <code class="docutils literal notranslate"><span class="pre">1</span></code>, <a class="reference internal" href="#curses.window.getch" title="curses.window.getch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code></a> will be non-blocking.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.notimeout">
<code class="descclassname">window.</code><code class="descname">notimeout</code><span class="sig-paren">(</span><em>yes</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.notimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>yes</em> is <code class="docutils literal notranslate"><span class="pre">1</span></code>, escape sequences will not be timed out.</p>
<p>If <em>yes</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, after a few milliseconds, an escape sequence will not be
interpreted, and will be left in the input stream as is.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.noutrefresh">
<code class="descclassname">window.</code><code class="descname">noutrefresh</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.noutrefresh" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark for refresh but wait.  This function updates the data structure
representing the desired state of the window, but does not force an update of
the physical screen.  To accomplish that, call  <a class="reference internal" href="#curses.doupdate" title="curses.doupdate"><code class="xref py py-func docutils literal notranslate"><span class="pre">doupdate()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.overlay">
<code class="descclassname">window.</code><code class="descname">overlay</code><span class="sig-paren">(</span><em>destwin</em><span class="optional">[</span>, <em>sminrow</em>, <em>smincol</em>, <em>dminrow</em>, <em>dmincol</em>, <em>dmaxrow</em>, <em>dmaxcol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.overlay" title="Permalink to this definition">¶</a></dt>
<dd><p>Overlay the window on top of <em>destwin</em>. The windows need not be the same size,
only the overlapping region is copied. This copy is non-destructive, which means
that the current background character does not overwrite the old contents of
<em>destwin</em>.</p>
<p>To get fine-grained control over the copied region, the second form of
<a class="reference internal" href="#curses.window.overlay" title="curses.window.overlay"><code class="xref py py-meth docutils literal notranslate"><span class="pre">overlay()</span></code></a> can be used. <em>sminrow</em> and <em>smincol</em> are the upper-left
coordinates of the source window, and the other variables mark a rectangle in
the destination window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.overwrite">
<code class="descclassname">window.</code><code class="descname">overwrite</code><span class="sig-paren">(</span><em>destwin</em><span class="optional">[</span>, <em>sminrow</em>, <em>smincol</em>, <em>dminrow</em>, <em>dmincol</em>, <em>dmaxrow</em>, <em>dmaxcol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.overwrite" title="Permalink to this definition">¶</a></dt>
<dd><p>Overwrite the window on top of <em>destwin</em>. The windows need not be the same size,
in which case only the overlapping region is copied. This copy is destructive,
which means that the current background character overwrites the old contents of
<em>destwin</em>.</p>
<p>To get fine-grained control over the copied region, the second form of
<a class="reference internal" href="#curses.window.overwrite" title="curses.window.overwrite"><code class="xref py py-meth docutils literal notranslate"><span class="pre">overwrite()</span></code></a> can be used. <em>sminrow</em> and <em>smincol</em> are the upper-left
coordinates of the source window, the other variables mark a rectangle in the
destination window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.putwin">
<code class="descclassname">window.</code><code class="descname">putwin</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.putwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Write all data associated with the window into the provided file object.  This
information can be later retrieved using the <a class="reference internal" href="#curses.getwin" title="curses.getwin"><code class="xref py py-func docutils literal notranslate"><span class="pre">getwin()</span></code></a> function.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.redrawln">
<code class="descclassname">window.</code><code class="descname">redrawln</code><span class="sig-paren">(</span><em>beg</em>, <em>num</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.redrawln" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicate that the <em>num</em> screen lines, starting at line <em>beg</em>, are corrupted and
should be completely redrawn on the next <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a> call.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.redrawwin">
<code class="descclassname">window.</code><code class="descname">redrawwin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.redrawwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Touch the entire window, causing it to be completely redrawn on the next
<a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a> call.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.refresh">
<code class="descclassname">window.</code><code class="descname">refresh</code><span class="sig-paren">(</span><span class="optional">[</span><em>pminrow</em>, <em>pmincol</em>, <em>sminrow</em>, <em>smincol</em>, <em>smaxrow</em>, <em>smaxcol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.refresh" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the display immediately (sync actual screen with previous
drawing/deleting methods).</p>
<p>The 6 optional arguments can only be specified when the window is a pad created
with <a class="reference internal" href="#curses.newpad" title="curses.newpad"><code class="xref py py-func docutils literal notranslate"><span class="pre">newpad()</span></code></a>.  The additional parameters are needed to indicate what part
of the pad and screen are involved. <em>pminrow</em> and <em>pmincol</em> specify the upper
left-hand corner of the rectangle to be displayed in the pad.  <em>sminrow</em>,
<em>smincol</em>, <em>smaxrow</em>, and <em>smaxcol</em> specify the edges of the rectangle to be
displayed on the screen.  The lower right-hand corner of the rectangle to be
displayed in the pad is calculated from the screen coordinates, since the
rectangles must be the same size.  Both rectangles must be entirely contained
within their respective structures.  Negative values of <em>pminrow</em>, <em>pmincol</em>,
<em>sminrow</em>, or <em>smincol</em> are treated as if they were zero.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.resize">
<code class="descclassname">window.</code><code class="descname">resize</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Reallocate storage for a curses window to adjust its dimensions to the
specified values.  If either dimension is larger than the current values, the
window’s data is filled with blanks that have the current background
rendition (as set by <a class="reference internal" href="#curses.window.bkgdset" title="curses.window.bkgdset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bkgdset()</span></code></a>) merged into them.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.scroll">
<code class="descclassname">window.</code><code class="descname">scroll</code><span class="sig-paren">(</span><span class="optional">[</span><em>lines=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.scroll" title="Permalink to this definition">¶</a></dt>
<dd><p>Scroll the screen or scrolling region upward by <em>lines</em> lines.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.scrollok">
<code class="descclassname">window.</code><code class="descname">scrollok</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.scrollok" title="Permalink to this definition">¶</a></dt>
<dd><p>Control what happens when the cursor of a window is moved off the edge of the
window or scrolling region, either as a result of a newline action on the bottom
line, or typing the last character of the last line.  If <em>flag</em> is false, the
cursor is left on the bottom line.  If <em>flag</em> is true, the window is scrolled up
one line.  Note that in order to get the physical scrolling effect on the
terminal, it is also necessary to call <a class="reference internal" href="#curses.window.idlok" title="curses.window.idlok"><code class="xref py py-meth docutils literal notranslate"><span class="pre">idlok()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.setscrreg">
<code class="descclassname">window.</code><code class="descname">setscrreg</code><span class="sig-paren">(</span><em>top</em>, <em>bottom</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.setscrreg" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the scrolling region from line <em>top</em> to line <em>bottom</em>. All scrolling actions
will take place in this region.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.standend">
<code class="descclassname">window.</code><code class="descname">standend</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.standend" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn off the standout attribute.  On some terminals this has the side effect of
turning off all attributes.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.standout">
<code class="descclassname">window.</code><code class="descname">standout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.standout" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn on attribute <em>A_STANDOUT</em>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.subpad">
<code class="descclassname">window.</code><code class="descname">subpad</code><span class="sig-paren">(</span><em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.subpad" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">subpad</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em>, <em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span></dt>
<dd><p>Return a sub-window, whose upper-left corner is at <code class="docutils literal notranslate"><span class="pre">(begin_y,</span> <span class="pre">begin_x)</span></code>, and
whose width/height is <em>ncols</em>/<em>nlines</em>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.subwin">
<code class="descclassname">window.</code><code class="descname">subwin</code><span class="sig-paren">(</span><em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.subwin" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">subwin</code><span class="sig-paren">(</span><em>nlines</em>, <em>ncols</em>, <em>begin_y</em>, <em>begin_x</em><span class="sig-paren">)</span></dt>
<dd><p>Return a sub-window, whose upper-left corner is at <code class="docutils literal notranslate"><span class="pre">(begin_y,</span> <span class="pre">begin_x)</span></code>, and
whose width/height is <em>ncols</em>/<em>nlines</em>.</p>
<p>By default, the sub-window will extend from the specified position to the lower
right corner of the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.syncdown">
<code class="descclassname">window.</code><code class="descname">syncdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.syncdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Touch each location in the window that has been touched in any of its ancestor
windows.  This routine is called by <a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>, so it should almost never
be necessary to call it manually.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.syncok">
<code class="descclassname">window.</code><code class="descname">syncok</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.syncok" title="Permalink to this definition">¶</a></dt>
<dd><p>If called with <em>flag</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, then <a class="reference internal" href="#curses.window.syncup" title="curses.window.syncup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">syncup()</span></code></a> is called automatically
whenever there is a change in the window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.syncup">
<code class="descclassname">window.</code><code class="descname">syncup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.syncup" title="Permalink to this definition">¶</a></dt>
<dd><p>Touch all locations in ancestors of the window that have been changed in  the
window.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.timeout">
<code class="descclassname">window.</code><code class="descname">timeout</code><span class="sig-paren">(</span><em>delay</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.timeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Set blocking or non-blocking read behavior for the window.  If <em>delay</em> is
negative, blocking read is used (which will wait indefinitely for input).  If
<em>delay</em> is zero, then non-blocking read is used, and -1 will be returned by
<a class="reference internal" href="#curses.window.getch" title="curses.window.getch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code></a> if no input is waiting.  If <em>delay</em> is positive, then
<a class="reference internal" href="#curses.window.getch" title="curses.window.getch"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getch()</span></code></a> will block for <em>delay</em> milliseconds, and return -1 if there is
still no input at the end of that time.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.touchline">
<code class="descclassname">window.</code><code class="descname">touchline</code><span class="sig-paren">(</span><em>start</em>, <em>count</em><span class="optional">[</span>, <em>changed</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.touchline" title="Permalink to this definition">¶</a></dt>
<dd><p>Pretend <em>count</em> lines have been changed, starting with line <em>start</em>.  If
<em>changed</em> is supplied, it specifies whether the affected lines are marked as
having been changed (<em>changed</em>=1) or unchanged (<em>changed</em>=0).</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.touchwin">
<code class="descclassname">window.</code><code class="descname">touchwin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.touchwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Pretend the whole window has been changed, for purposes of drawing
optimizations.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.untouchwin">
<code class="descclassname">window.</code><code class="descname">untouchwin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.untouchwin" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark all lines in  the  window  as unchanged since the last call to
<a class="reference internal" href="#curses.window.refresh" title="curses.window.refresh"><code class="xref py py-meth docutils literal notranslate"><span class="pre">refresh()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.window.vline">
<code class="descclassname">window.</code><code class="descname">vline</code><span class="sig-paren">(</span><em>ch</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.window.vline" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">window.</code><code class="descname">vline</code><span class="sig-paren">(</span><em>y</em>, <em>x</em>, <em>ch</em>, <em>n</em><span class="sig-paren">)</span></dt>
<dd><p>Display a vertical line starting at <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code> with length <em>n</em> consisting of the
character <em>ch</em>.</p>
</dd></dl>

</div>
<div class="section" id="constants">
<h2>15.11.3. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module defines the following data members:</p>
<dl class="data">
<dt id="curses.ERR">
<code class="descclassname">curses.</code><code class="descname">ERR</code><a class="headerlink" href="#curses.ERR" title="Permalink to this definition">¶</a></dt>
<dd><p>Some curses routines  that  return  an integer, such as  <code class="xref py py-func docutils literal notranslate"><span class="pre">getch()</span></code>, return
<a class="reference internal" href="#curses.ERR" title="curses.ERR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ERR</span></code></a> upon failure.</p>
</dd></dl>

<dl class="data">
<dt id="curses.OK">
<code class="descclassname">curses.</code><code class="descname">OK</code><a class="headerlink" href="#curses.OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Some curses routines  that  return  an integer, such as  <a class="reference internal" href="#curses.napms" title="curses.napms"><code class="xref py py-func docutils literal notranslate"><span class="pre">napms()</span></code></a>, return
<a class="reference internal" href="#curses.OK" title="curses.OK"><code class="xref py py-const docutils literal notranslate"><span class="pre">OK</span></code></a> upon success.</p>
</dd></dl>

<dl class="data">
<dt id="curses.version">
<code class="descclassname">curses.</code><code class="descname">version</code><a class="headerlink" href="#curses.version" title="Permalink to this definition">¶</a></dt>
<dd><p>A string representing the current version of the module.  Also available as
<code class="xref py py-const docutils literal notranslate"><span class="pre">__version__</span></code>.</p>
</dd></dl>

<p>Some constants are available to specify character cell attributes.
The exact constants available are system dependent.</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_ALTCHARSET</span></code></td>
<td>Alternate character set mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_BLINK</span></code></td>
<td>Blink mode</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_BOLD</span></code></td>
<td>Bold mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_DIM</span></code></td>
<td>Dim mode</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_INVIS</span></code></td>
<td>Invisible or blank mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_NORMAL</span></code></td>
<td>Normal attribute</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_PROTECT</span></code></td>
<td>Protected mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_REVERSE</span></code></td>
<td>Reverse background and
foreground colors</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_STANDOUT</span></code></td>
<td>Standout mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_UNDERLINE</span></code></td>
<td>Underline mode</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_HORIZONTAL</span></code></td>
<td>Horizontal highlight</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_LEFT</span></code></td>
<td>Left highlight</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_LOW</span></code></td>
<td>Low highlight</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_RIGHT</span></code></td>
<td>Right highlight</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_TOP</span></code></td>
<td>Top highlight</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_VERTICAL</span></code></td>
<td>Vertical highlight</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_CHARTEXT</span></code></td>
<td>Bit-mask to extract a
character</td>
</tr>
</tbody>
</table>
<p>Several constants are available to extract corresponding attributes returned
by some methods.</p>
<table border="1" class="docutils">
<colgroup>
<col width="37%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Bit-mask</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_ATTRIBUTES</span></code></td>
<td>Bit-mask to extract
attributes</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">A_CHARTEXT</span></code></td>
<td>Bit-mask to extract a
character</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">A_COLOR</span></code></td>
<td>Bit-mask to extract
color-pair field information</td>
</tr>
</tbody>
</table>
<p>Keys are referred to by integer constants with names starting with  <code class="docutils literal notranslate"><span class="pre">KEY_</span></code>.
The exact keycaps available are system dependent.</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Key constant</th>
<th class="head">Key</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_MIN</span></code></td>
<td>Minimum key value</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_BREAK</span></code></td>
<td>Break key (unreliable)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_DOWN</span></code></td>
<td>Down-arrow</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_UP</span></code></td>
<td>Up-arrow</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_LEFT</span></code></td>
<td>Left-arrow</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_RIGHT</span></code></td>
<td>Right-arrow</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_HOME</span></code></td>
<td>Home key (upward+left arrow)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_BACKSPACE</span></code></td>
<td>Backspace (unreliable)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_F0</span></code></td>
<td>Function keys.  Up to 64 function keys are
supported.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_Fn</span></code></td>
<td>Value of function key <em>n</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_DL</span></code></td>
<td>Delete line</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_IL</span></code></td>
<td>Insert line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_DC</span></code></td>
<td>Delete character</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_IC</span></code></td>
<td>Insert char or enter insert mode</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_EIC</span></code></td>
<td>Exit insert char mode</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_CLEAR</span></code></td>
<td>Clear screen</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_EOS</span></code></td>
<td>Clear to end of screen</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_EOL</span></code></td>
<td>Clear to end of line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SF</span></code></td>
<td>Scroll 1 line forward</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SR</span></code></td>
<td>Scroll 1 line backward (reverse)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_NPAGE</span></code></td>
<td>Next page</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_PPAGE</span></code></td>
<td>Previous page</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_STAB</span></code></td>
<td>Set tab</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_CTAB</span></code></td>
<td>Clear tab</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_CATAB</span></code></td>
<td>Clear all tabs</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_ENTER</span></code></td>
<td>Enter or send (unreliable)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SRESET</span></code></td>
<td>Soft (partial) reset (unreliable)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_RESET</span></code></td>
<td>Reset or hard reset (unreliable)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_PRINT</span></code></td>
<td>Print</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_LL</span></code></td>
<td>Home down or bottom (lower left)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_A1</span></code></td>
<td>Upper left of keypad</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_A3</span></code></td>
<td>Upper right of keypad</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_B2</span></code></td>
<td>Center of keypad</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_C1</span></code></td>
<td>Lower left of keypad</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_C3</span></code></td>
<td>Lower right of keypad</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_BTAB</span></code></td>
<td>Back tab</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_BEG</span></code></td>
<td>Beg (beginning)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_CANCEL</span></code></td>
<td>Cancel</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_CLOSE</span></code></td>
<td>Close</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_COMMAND</span></code></td>
<td>Cmd (command)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_COPY</span></code></td>
<td>Copy</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_CREATE</span></code></td>
<td>Create</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_END</span></code></td>
<td>End</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_EXIT</span></code></td>
<td>Exit</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_FIND</span></code></td>
<td>Find</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_HELP</span></code></td>
<td>Help</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_MARK</span></code></td>
<td>Mark</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_MESSAGE</span></code></td>
<td>Message</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_MOVE</span></code></td>
<td>Move</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_NEXT</span></code></td>
<td>Next</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_OPEN</span></code></td>
<td>Open</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_OPTIONS</span></code></td>
<td>Options</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_PREVIOUS</span></code></td>
<td>Prev (previous)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_REDO</span></code></td>
<td>Redo</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_REFERENCE</span></code></td>
<td>Ref (reference)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_REFRESH</span></code></td>
<td>Refresh</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_REPLACE</span></code></td>
<td>Replace</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_RESTART</span></code></td>
<td>Restart</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_RESUME</span></code></td>
<td>Resume</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SAVE</span></code></td>
<td>Save</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SBEG</span></code></td>
<td>Shifted Beg (beginning)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SCANCEL</span></code></td>
<td>Shifted Cancel</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SCOMMAND</span></code></td>
<td>Shifted Command</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SCOPY</span></code></td>
<td>Shifted Copy</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SCREATE</span></code></td>
<td>Shifted Create</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SDC</span></code></td>
<td>Shifted Delete char</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SDL</span></code></td>
<td>Shifted Delete line</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SELECT</span></code></td>
<td>Select</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SEND</span></code></td>
<td>Shifted End</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SEOL</span></code></td>
<td>Shifted Clear line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SEXIT</span></code></td>
<td>Shifted Exit</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SFIND</span></code></td>
<td>Shifted Find</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SHELP</span></code></td>
<td>Shifted Help</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SHOME</span></code></td>
<td>Shifted Home</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SIC</span></code></td>
<td>Shifted Input</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SLEFT</span></code></td>
<td>Shifted Left arrow</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SMESSAGE</span></code></td>
<td>Shifted Message</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SMOVE</span></code></td>
<td>Shifted Move</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SNEXT</span></code></td>
<td>Shifted Next</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SOPTIONS</span></code></td>
<td>Shifted Options</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SPREVIOUS</span></code></td>
<td>Shifted Prev</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SPRINT</span></code></td>
<td>Shifted Print</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SREDO</span></code></td>
<td>Shifted Redo</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SREPLACE</span></code></td>
<td>Shifted Replace</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SRIGHT</span></code></td>
<td>Shifted Right arrow</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SRSUME</span></code></td>
<td>Shifted Resume</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SSAVE</span></code></td>
<td>Shifted Save</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SSUSPEND</span></code></td>
<td>Shifted Suspend</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_SUNDO</span></code></td>
<td>Shifted Undo</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_SUSPEND</span></code></td>
<td>Suspend</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_UNDO</span></code></td>
<td>Undo</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_MOUSE</span></code></td>
<td>Mouse event has occurred</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">KEY_RESIZE</span></code></td>
<td>Terminal resize event</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">KEY_MAX</span></code></td>
<td>Maximum key value</td>
</tr>
</tbody>
</table>
<p>On VT100s and their software emulations, such as X terminal emulators, there are
normally at least four function keys (<code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_F1</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_F2</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_F3</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_F4</span></code>) available, and the arrow keys mapped to
<code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_UP</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_DOWN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_LEFT</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_RIGHT</span></code> in
the obvious way.  If your machine has a PC keyboard, it is safe to expect arrow
keys and twelve function keys (older PC keyboards may have only ten function
keys); also, the following keypad mappings are standard:</p>
<table border="1" class="docutils">
<colgroup>
<col width="62%" />
<col width="38%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Keycap</th>
<th class="head">Constant</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Insert</kbd></td>
<td>KEY_IC</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Delete</kbd></td>
<td>KEY_DC</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Home</kbd></td>
<td>KEY_HOME</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">End</kbd></td>
<td>KEY_END</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Page Up</kbd></td>
<td>KEY_PPAGE</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Page Down</kbd></td>
<td>KEY_NPAGE</td>
</tr>
</tbody>
</table>
<p>The following table lists characters from the alternate character set. These are
inherited from the VT100 terminal, and will generally be  available on software
emulations such as X terminals.  When there is no graphic available, curses
falls back on a crude printable ASCII approximation.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">These are available only after <a class="reference internal" href="#curses.initscr" title="curses.initscr"><code class="xref py py-func docutils literal notranslate"><span class="pre">initscr()</span></code></a> has  been called.</p>
</div>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">ACS code</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_BBSS</span></code></td>
<td>alternate name for upper right corner</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_BLOCK</span></code></td>
<td>solid square block</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_BOARD</span></code></td>
<td>board of squares</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_BSBS</span></code></td>
<td>alternate name for horizontal line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_BSSB</span></code></td>
<td>alternate name for upper left corner</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_BSSS</span></code></td>
<td>alternate name for top tee</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_BTEE</span></code></td>
<td>bottom tee</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_BULLET</span></code></td>
<td>bullet</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_CKBOARD</span></code></td>
<td>checker board (stipple)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_DARROW</span></code></td>
<td>arrow pointing down</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_DEGREE</span></code></td>
<td>degree symbol</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_DIAMOND</span></code></td>
<td>diamond</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_GEQUAL</span></code></td>
<td>greater-than-or-equal-to</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_HLINE</span></code></td>
<td>horizontal line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_LANTERN</span></code></td>
<td>lantern symbol</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_LARROW</span></code></td>
<td>left arrow</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_LEQUAL</span></code></td>
<td>less-than-or-equal-to</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_LLCORNER</span></code></td>
<td>lower left-hand corner</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_LRCORNER</span></code></td>
<td>lower right-hand corner</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_LTEE</span></code></td>
<td>left tee</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_NEQUAL</span></code></td>
<td>not-equal sign</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_PI</span></code></td>
<td>letter pi</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_PLMINUS</span></code></td>
<td>plus-or-minus sign</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_PLUS</span></code></td>
<td>big plus sign</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_RARROW</span></code></td>
<td>right arrow</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_RTEE</span></code></td>
<td>right tee</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_S1</span></code></td>
<td>scan line 1</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_S3</span></code></td>
<td>scan line 3</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_S7</span></code></td>
<td>scan line 7</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_S9</span></code></td>
<td>scan line 9</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_SBBS</span></code></td>
<td>alternate name for lower right corner</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_SBSB</span></code></td>
<td>alternate name for vertical line</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_SBSS</span></code></td>
<td>alternate name for right tee</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_SSBB</span></code></td>
<td>alternate name for lower left corner</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_SSBS</span></code></td>
<td>alternate name for bottom tee</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_SSSB</span></code></td>
<td>alternate name for left tee</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_SSSS</span></code></td>
<td>alternate name for crossover or big plus</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_STERLING</span></code></td>
<td>pound sterling</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_TTEE</span></code></td>
<td>top tee</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_UARROW</span></code></td>
<td>up arrow</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_ULCORNER</span></code></td>
<td>upper left corner</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ACS_URCORNER</span></code></td>
<td>upper right corner</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ACS_VLINE</span></code></td>
<td>vertical line</td>
</tr>
</tbody>
</table>
<p>The following table lists the predefined colors:</p>
<table border="1" class="docutils">
<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Color</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">COLOR_BLACK</span></code></td>
<td>Black</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">COLOR_BLUE</span></code></td>
<td>Blue</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">COLOR_CYAN</span></code></td>
<td>Cyan (light greenish blue)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">COLOR_GREEN</span></code></td>
<td>Green</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">COLOR_MAGENTA</span></code></td>
<td>Magenta (purplish red)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">COLOR_RED</span></code></td>
<td>Red</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">COLOR_WHITE</span></code></td>
<td>White</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">COLOR_YELLOW</span></code></td>
<td>Yellow</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="module-curses.textpad">
<span id="curses-textpad-text-input-widget-for-curses-programs"></span><h1>15.12. <a class="reference internal" href="#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> — Text input widget for curses programs<a class="headerlink" href="#module-curses.textpad" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<p>The <a class="reference internal" href="#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module provides a <a class="reference internal" href="#curses.textpad.Textbox" title="curses.textpad.Textbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code></a> class that handles
elementary text editing in a curses window, supporting a set of keybindings
resembling those of Emacs (thus, also of Netscape Navigator, BBedit 6.x,
FrameMaker, and many other programs).  The module also provides a
rectangle-drawing function useful for framing text boxes or for other purposes.</p>
<p>The module <a class="reference internal" href="#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> defines the following function:</p>
<dl class="function">
<dt id="curses.textpad.rectangle">
<code class="descclassname">curses.textpad.</code><code class="descname">rectangle</code><span class="sig-paren">(</span><em>win</em>, <em>uly</em>, <em>ulx</em>, <em>lry</em>, <em>lrx</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.textpad.rectangle" title="Permalink to this definition">¶</a></dt>
<dd><p>Draw a rectangle.  The first argument must be a window object; the remaining
arguments are coordinates relative to that window.  The second and third
arguments are the y and x coordinates of the upper left hand corner of the
rectangle to be drawn; the fourth and fifth arguments are the y and x
coordinates of the lower right hand corner. The rectangle will be drawn using
VT100/IBM PC forms characters on terminals that make this possible (including
xterm and most other software terminal emulators).  Otherwise it will be drawn
with ASCII  dashes, vertical bars, and plus signs.</p>
</dd></dl>

<div class="section" id="textbox-objects">
<span id="curses-textpad-objects"></span><h2>15.12.1. Textbox objects<a class="headerlink" href="#textbox-objects" title="Permalink to this headline">¶</a></h2>
<p>You can instantiate a <a class="reference internal" href="#curses.textpad.Textbox" title="curses.textpad.Textbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code></a> object as follows:</p>
<dl class="class">
<dt id="curses.textpad.Textbox">
<em class="property">class </em><code class="descclassname">curses.textpad.</code><code class="descname">Textbox</code><span class="sig-paren">(</span><em>win</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.textpad.Textbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a textbox widget object.  The <em>win</em> argument should be a curses
<code class="xref py py-class docutils literal notranslate"><span class="pre">WindowObject</span></code> in which the textbox is to be contained. The edit cursor
of the textbox is initially located at the upper left hand corner of the
containing window, with coordinates <code class="docutils literal notranslate"><span class="pre">(0,</span> <span class="pre">0)</span></code>. The instance’s
<a class="reference internal" href="#curses.textpad.Textbox.stripspaces" title="curses.textpad.Textbox.stripspaces"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stripspaces</span></code></a> flag is initially on.</p>
<p><a class="reference internal" href="#curses.textpad.Textbox" title="curses.textpad.Textbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code></a> objects have the following methods:</p>
<dl class="method">
<dt id="curses.textpad.Textbox.edit">
<code class="descname">edit</code><span class="sig-paren">(</span><span class="optional">[</span><em>validator</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.textpad.Textbox.edit" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the entry point you will normally use.  It accepts editing
keystrokes until one of the termination keystrokes is entered.  If
<em>validator</em> is supplied, it must be a function.  It will be called for
each keystroke entered with the keystroke as a parameter; command dispatch
is done on the result. This method returns the window contents as a
string; whether blanks in the window are included is affected by the
<a class="reference internal" href="#curses.textpad.Textbox.stripspaces" title="curses.textpad.Textbox.stripspaces"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stripspaces</span></code></a> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="curses.textpad.Textbox.do_command">
<code class="descname">do_command</code><span class="sig-paren">(</span><em>ch</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.textpad.Textbox.do_command" title="Permalink to this definition">¶</a></dt>
<dd><p>Process a single command keystroke.  Here are the supported special
keystrokes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Keystroke</th>
<th class="head">Action</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-A</kbd></td>
<td>Go to left edge of window.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-B</kbd></td>
<td>Cursor left, wrapping to previous line if
appropriate.</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-D</kbd></td>
<td>Delete character under cursor.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-E</kbd></td>
<td>Go to right edge (stripspaces off) or end
of line (stripspaces on).</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-F</kbd></td>
<td>Cursor right, wrapping to next line when
appropriate.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-G</kbd></td>
<td>Terminate, returning the window contents.</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-H</kbd></td>
<td>Delete character backward.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-J</kbd></td>
<td>Terminate if the window is 1 line,
otherwise insert newline.</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-K</kbd></td>
<td>If line is blank, delete it, otherwise
clear to end of line.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-L</kbd></td>
<td>Refresh screen.</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-N</kbd></td>
<td>Cursor down; move down one line.</td>
</tr>
<tr class="row-odd"><td><kbd class="kbd docutils literal notranslate">Control-O</kbd></td>
<td>Insert a blank line at cursor location.</td>
</tr>
<tr class="row-even"><td><kbd class="kbd docutils literal notranslate">Control-P</kbd></td>
<td>Cursor up; move up one line.</td>
</tr>
</tbody>
</table>
<p>Move operations do nothing if the cursor is at an edge where the movement
is not possible.  The following synonyms are supported where possible:</p>
<table border="1" class="docutils">
<colgroup>
<col width="57%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Keystroke</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_LEFT</span></code></td>
<td><kbd class="kbd docutils literal notranslate">Control-B</kbd></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_RIGHT</span></code></td>
<td><kbd class="kbd docutils literal notranslate">Control-F</kbd></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_UP</span></code></td>
<td><kbd class="kbd docutils literal notranslate">Control-P</kbd></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_DOWN</span></code></td>
<td><kbd class="kbd docutils literal notranslate">Control-N</kbd></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KEY_BACKSPACE</span></code></td>
<td><kbd class="kbd docutils literal notranslate">Control-h</kbd></td>
</tr>
</tbody>
</table>
<p>All other keystrokes are treated as a command to insert the given
character and move right (with line wrapping).</p>
</dd></dl>

<dl class="method">
<dt id="curses.textpad.Textbox.gather">
<code class="descname">gather</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.textpad.Textbox.gather" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the window contents as a string; whether blanks in the
window are included is affected by the <a class="reference internal" href="#curses.textpad.Textbox.stripspaces" title="curses.textpad.Textbox.stripspaces"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stripspaces</span></code></a> member.</p>
</dd></dl>

<dl class="attribute">
<dt id="curses.textpad.Textbox.stripspaces">
<code class="descname">stripspaces</code><a class="headerlink" href="#curses.textpad.Textbox.stripspaces" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is a flag which controls the interpretation of blanks in
the window.  When it is on, trailing blanks on each line are ignored; any
cursor motion that would land the cursor on a trailing blank goes to the
end of that line instead, and trailing blanks are stripped when the window
contents are gathered.</p>
</dd></dl>

</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a><ul>
<li><a class="reference internal" href="#functions">15.11.1. Functions</a></li>
<li><a class="reference internal" href="#window-objects">15.11.2. Window Objects</a></li>
<li><a class="reference internal" href="#constants">15.11.3. Constants</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-curses.textpad">15.12. <code class="docutils literal notranslate"><span class="pre">curses.textpad</span></code> — Text input widget for curses programs</a><ul>
<li><a class="reference internal" href="#textbox-objects">15.12.1. Textbox objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="getpass.html"
                        title="previous chapter">15.10. <code class="docutils literal notranslate"><span class="pre">getpass</span></code> — Portable password input</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="curses.ascii.html"
                        title="next chapter">15.13. <code class="docutils literal notranslate"><span class="pre">curses.ascii</span></code> — Utilities for ASCII characters</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/curses.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.ascii.html" title="15.13. curses.ascii — Utilities for ASCII characters"
             >next</a> |</li>
        <li class="right" >
          <a href="getpass.html" title="15.10. getpass — Portable password input"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\^ro��=�=html/library/curses.panel.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.14. curses.panel — A panel stack extension for curses &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.15. platform — Access to underlying platform’s identifying data" href="platform.html" />
    <link rel="prev" title="15.13. curses.ascii — Utilities for ASCII characters" href="curses.ascii.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/curses.panel.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="platform.html" title="15.15. platform — Access to underlying platform’s identifying data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="curses.ascii.html" title="15.13. curses.ascii — Utilities for ASCII characters"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-curses.panel">
<span id="curses-panel-a-panel-stack-extension-for-curses"></span><h1>15.14. <a class="reference internal" href="#module-curses.panel" title="curses.panel: A panel stack extension that adds depth to  curses windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.panel</span></code></a> — A panel stack extension for curses<a class="headerlink" href="#module-curses.panel" title="Permalink to this headline">¶</a></h1>
<p>Panels are windows with the added feature of depth, so they can be stacked on
top of each other, and only the visible portions of each window will be
displayed.  Panels can be added, moved up or down in the stack, and removed.</p>
<div class="section" id="functions">
<span id="cursespanel-functions"></span><h2>15.14.1. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h2>
<p>The module <a class="reference internal" href="#module-curses.panel" title="curses.panel: A panel stack extension that adds depth to  curses windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.panel</span></code></a> defines the following functions:</p>
<dl class="function">
<dt id="curses.panel.bottom_panel">
<code class="descclassname">curses.panel.</code><code class="descname">bottom_panel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.bottom_panel" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the bottom panel in the panel stack.</p>
</dd></dl>

<dl class="function">
<dt id="curses.panel.new_panel">
<code class="descclassname">curses.panel.</code><code class="descname">new_panel</code><span class="sig-paren">(</span><em>win</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.new_panel" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a panel object, associating it with the given window <em>win</em>. Be aware
that you need to keep the returned panel object referenced explicitly.  If you
don’t, the panel object is garbage collected and removed from the panel stack.</p>
</dd></dl>

<dl class="function">
<dt id="curses.panel.top_panel">
<code class="descclassname">curses.panel.</code><code class="descname">top_panel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.top_panel" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the top panel in the panel stack.</p>
</dd></dl>

<dl class="function">
<dt id="curses.panel.update_panels">
<code class="descclassname">curses.panel.</code><code class="descname">update_panels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.update_panels" title="Permalink to this definition">¶</a></dt>
<dd><p>Updates the virtual screen after changes in the panel stack. This does not call
<a class="reference internal" href="curses.html#curses.doupdate" title="curses.doupdate"><code class="xref py py-func docutils literal notranslate"><span class="pre">curses.doupdate()</span></code></a>, so you’ll have to do this yourself.</p>
</dd></dl>

</div>
<div class="section" id="panel-objects">
<span id="curses-panel-objects"></span><h2>15.14.2. Panel Objects<a class="headerlink" href="#panel-objects" title="Permalink to this headline">¶</a></h2>
<p>Panel objects, as returned by <a class="reference internal" href="#curses.panel.new_panel" title="curses.panel.new_panel"><code class="xref py py-func docutils literal notranslate"><span class="pre">new_panel()</span></code></a> above, are windows with a
stacking order. There’s always a window associated with a panel which determines
the content, while the panel methods are responsible for the window’s depth in
the panel stack.</p>
<p>Panel objects have the following methods:</p>
<dl class="method">
<dt id="curses.panel.Panel.above">
<code class="descclassname">Panel.</code><code class="descname">above</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.above" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the panel above the current panel.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.below">
<code class="descclassname">Panel.</code><code class="descname">below</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.below" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the panel below the current panel.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.bottom">
<code class="descclassname">Panel.</code><code class="descname">bottom</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.bottom" title="Permalink to this definition">¶</a></dt>
<dd><p>Push the panel to the bottom of the stack.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.hidden">
<code class="descclassname">Panel.</code><code class="descname">hidden</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.hidden" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the panel is hidden (not visible), false otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.hide">
<code class="descclassname">Panel.</code><code class="descname">hide</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.hide" title="Permalink to this definition">¶</a></dt>
<dd><p>Hide the panel. This does not delete the object, it just makes the window on
screen invisible.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.move">
<code class="descclassname">Panel.</code><code class="descname">move</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Move the panel to the screen coordinates <code class="docutils literal notranslate"><span class="pre">(y,</span> <span class="pre">x)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.replace">
<code class="descclassname">Panel.</code><code class="descname">replace</code><span class="sig-paren">(</span><em>win</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the window associated with the panel to the window <em>win</em>.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.set_userptr">
<code class="descclassname">Panel.</code><code class="descname">set_userptr</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.set_userptr" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the panel’s user pointer to <em>obj</em>. This is used to associate an arbitrary
piece of data with the panel, and can be any Python object.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.show">
<code class="descclassname">Panel.</code><code class="descname">show</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.show" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the panel (which might have been hidden).</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.top">
<code class="descclassname">Panel.</code><code class="descname">top</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.top" title="Permalink to this definition">¶</a></dt>
<dd><p>Push panel to the top of the stack.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.userptr">
<code class="descclassname">Panel.</code><code class="descname">userptr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.userptr" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the user pointer for the panel.  This might be any Python object.</p>
</dd></dl>

<dl class="method">
<dt id="curses.panel.Panel.window">
<code class="descclassname">Panel.</code><code class="descname">window</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#curses.panel.Panel.window" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the window object associated with the panel.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a><ul>
<li><a class="reference internal" href="#functions">15.14.1. Functions</a></li>
<li><a class="reference internal" href="#panel-objects">15.14.2. Panel Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="curses.ascii.html"
                        title="previous chapter">15.13. <code class="docutils literal notranslate"><span class="pre">curses.ascii</span></code> — Utilities for ASCII characters</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="platform.html"
                        title="next chapter">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/curses.panel.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="platform.html" title="15.15. platform — Access to underlying platform’s identifying data"
             >next</a> |</li>
        <li class="right" >
          <a href="curses.ascii.html" title="15.13. curses.ascii — Utilities for ASCII characters"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�ZZhtml/library/custominterp.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>29. Custom Python Interpreters &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="29.1. code — Interpreter base classes" href="code.html" />
    <link rel="prev" title="28.16. fpectl — Floating point exception control" href="fpectl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/custominterp.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="code.html" title="29.1. code — Interpreter base classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fpectl.html" title="28.16. fpectl — Floating point exception control"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="custom-python-interpreters">
<span id="custominterp"></span><h1>29. Custom Python Interpreters<a class="headerlink" href="#custom-python-interpreters" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter allow writing interfaces similar to
Python’s interactive interpreter.  If you want a Python interpreter that
supports some special feature in addition to the Python language, you should
look at the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> module.  (The <a class="reference internal" href="codeop.html#module-codeop" title="codeop: Compile (possibly incomplete) Python code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codeop</span></code></a> module is lower-level, used
to support compiling a possibly-incomplete chunk of Python code.)</p>
<p>The full list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="code.html">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="code.html#interactive-interpreter-objects">29.1.1. Interactive Interpreter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="code.html#interactive-console-objects">29.1.2. Interactive Console Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="codeop.html">29.2. <code class="docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fpectl.html"
                        title="previous chapter">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="code.html"
                        title="next chapter">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/custominterp.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="code.html" title="29.1. code — Interpreter base classes"
             >next</a> |</li>
        <li class="right" >
          <a href="fpectl.html" title="28.16. fpectl — Floating point exception control"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\2���_F_Fhtml/library/datatypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8. Data Types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.1. datetime — Basic date and time types" href="datetime.html" />
    <link rel="prev" title="7.11. fpformat — Floating point conversions" href="fpformat.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/datatypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="8.1. datetime — Basic date and time types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fpformat.html" title="7.11. fpformat — Floating point conversions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-types">
<span id="datatypes"></span><h1>8. Data Types<a class="headerlink" href="#data-types" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide a variety of specialized data
types such as dates and times, fixed-type arrays, heap queues, synchronized
queues, and sets.</p>
<p>Python also provides some built-in data types, in particular,
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> (which along with
<a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, replaces the deprecated <a class="reference internal" href="sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module), and
<a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>. The <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> class can be used to handle binary data
and 8-bit text, and the <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> class to handle Unicode text.</p>
<p>The following modules are documented in this chapter:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="datetime.html">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#available-types">8.1.1. Available Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#timedelta-objects">8.1.2. <code class="docutils literal notranslate"><span class="pre">timedelta</span></code> Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#date-objects">8.1.3. <code class="docutils literal notranslate"><span class="pre">date</span></code> Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#datetime-objects">8.1.4. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#time-objects">8.1.5. <code class="docutils literal notranslate"><span class="pre">time</span></code> Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#tzinfo-objects">8.1.6. <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="datetime.html#strftime-and-strptime-behavior">8.1.7. <code class="docutils literal notranslate"><span class="pre">strftime()</span></code> and <code class="docutils literal notranslate"><span class="pre">strptime()</span></code> Behavior</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="calendar.html">8.2. <code class="docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="collections.html">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="collections.html#counter-objects">8.3.1. <code class="docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="collections.html#deque-objects">8.3.2. <code class="docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="collections.html#deque-recipes">8.3.2.1. <code class="docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="collections.html#defaultdict-objects">8.3.3. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="collections.html#defaultdict-examples">8.3.3.1. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="collections.html#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <code class="docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li>
<li class="toctree-l2"><a class="reference internal" href="collections.html#ordereddict-objects">8.3.5. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="collections.html#ordereddict-examples-and-recipes">8.3.5.1. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> Examples and Recipes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="collections.html#collections-abstract-base-classes">8.3.6. Collections Abstract Base Classes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="heapq.html">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a><ul>
<li class="toctree-l2"><a class="reference internal" href="heapq.html#basic-examples">8.4.1. Basic Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="heapq.html#priority-queue-implementation-notes">8.4.2. Priority Queue Implementation Notes</a></li>
<li class="toctree-l2"><a class="reference internal" href="heapq.html#theory">8.4.3. Theory</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="bisect.html">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a><ul>
<li class="toctree-l2"><a class="reference internal" href="bisect.html#searching-sorted-lists">8.5.1. Searching Sorted Lists</a></li>
<li class="toctree-l2"><a class="reference internal" href="bisect.html#other-examples">8.5.2. Other Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="array.html">8.6. <code class="docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></li>
<li class="toctree-l1"><a class="reference internal" href="sets.html">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sets.html#set-objects">8.7.1. Set Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="sets.html#example">8.7.2. Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="sets.html#protocol-for-automatic-conversion-to-immutable">8.7.3. Protocol for automatic conversion to immutable</a></li>
<li class="toctree-l2"><a class="reference internal" href="sets.html#comparison-to-the-built-in-set-types">8.7.4. Comparison to the built-in <code class="docutils literal notranslate"><span class="pre">set</span></code> types</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sched.html">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sched.html#scheduler-objects">8.8.1. Scheduler Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mutex.html">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mutex.html#mutex-objects">8.9.1. Mutex Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="queue.html">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a><ul>
<li class="toctree-l2"><a class="reference internal" href="queue.html#queue-objects">8.10.1. Queue Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="weakref.html">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a><ul>
<li class="toctree-l2"><a class="reference internal" href="weakref.html#weak-reference-objects">8.11.1. Weak Reference Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="weakref.html#example">8.11.2. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="userdict.html">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="userdict.html#module-UserList">8.13. <code class="docutils literal notranslate"><span class="pre">UserList</span></code> — Class wrapper for list objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="userdict.html#module-UserString">8.14. <code class="docutils literal notranslate"><span class="pre">UserString</span></code> — Class wrapper for string objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="types.html">8.15. <code class="docutils literal notranslate"><span class="pre">types</span></code> — Names for built-in types</a></li>
<li class="toctree-l1"><a class="reference internal" href="new.html">8.16. <code class="docutils literal notranslate"><span class="pre">new</span></code> — Creation of runtime internal objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="copy.html">8.17. <code class="docutils literal notranslate"><span class="pre">copy</span></code> — Shallow and deep copy operations</a></li>
<li class="toctree-l1"><a class="reference internal" href="pprint.html">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pprint.html#prettyprinter-objects">8.18.1. PrettyPrinter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="pprint.html#pprint-example">8.18.2. pprint Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="repr.html">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="repr.html#repr-objects">8.19.1. Repr Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="repr.html#subclassing-repr-objects">8.19.2. Subclassing Repr Objects</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fpformat.html"
                        title="previous chapter">7.11. <code class="docutils literal notranslate"><span class="pre">fpformat</span></code> — Floating point conversions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datetime.html"
                        title="next chapter">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/datatypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datetime.html" title="8.1. datetime — Basic date and time types"
             >next</a> |</li>
        <li class="right" >
          <a href="fpformat.html" title="7.11. fpformat — Floating point conversions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\HX.����html/library/datetime.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.1. datetime — Basic date and time types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.2. calendar — General calendar-related functions" href="calendar.html" />
    <link rel="prev" title="8. Data Types" href="datatypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/datetime.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="datatypes.html" title="8. Data Types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-datetime">
<span id="datetime-basic-date-and-time-types"></span><h1>8.1. <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> — Basic date and time types<a class="headerlink" href="#module-datetime" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module supplies classes for manipulating dates and times in
both simple and complex ways.  While date and time arithmetic is supported, the
focus of the implementation is on efficient attribute extraction for output
formatting and manipulation. For related functionality, see also the
<a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> and <a class="reference internal" href="calendar.html#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a> modules.</p>
<p>There are two kinds of date and time objects: “naive” and “aware”.</p>
<p>An aware object has sufficient knowledge of applicable algorithmic and
political time adjustments, such as time zone and daylight saving time
information, to locate itself relative to other aware objects.  An aware object
is used to represent a specific moment in time that is not open to
interpretation <a class="footnote-reference" href="#id2" id="id1">[1]</a>.</p>
<p>A naive object does not contain enough information to unambiguously locate
itself relative to other date/time objects.  Whether a naive object represents
Coordinated Universal Time (UTC), local time, or time in some other timezone is
purely up to the program, just like it’s up to the program whether a particular
number represents metres, miles, or mass.  Naive objects are easy to understand
and to work with, at the cost of ignoring some aspects of reality.</p>
<p>For applications requiring aware objects, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>
objects have an optional time zone information attribute, <code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code>, that
can be set to an instance of a subclass of the abstract <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> class.
These <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> objects capture information about the offset from UTC
time, the time zone name, and whether Daylight Saving Time is in effect.  Note
that no concrete <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> classes are supplied by the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a>
module.  Supporting timezones at whatever level of detail is required is up to
the application.  The rules for time adjustment across the world are more
political than rational, and there is no standard suitable for every
application.</p>
<p>The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module exports the following constants:</p>
<dl class="data">
<dt id="datetime.MINYEAR">
<code class="descclassname">datetime.</code><code class="descname">MINYEAR</code><a class="headerlink" href="#datetime.MINYEAR" title="Permalink to this definition">¶</a></dt>
<dd><p>The smallest year number allowed in a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object.
<a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a> is <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="datetime.MAXYEAR">
<code class="descclassname">datetime.</code><code class="descname">MAXYEAR</code><a class="headerlink" href="#datetime.MAXYEAR" title="Permalink to this definition">¶</a></dt>
<dd><p>The largest year number allowed in a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object.
<a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a> is <code class="docutils literal notranslate"><span class="pre">9999</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="calendar.html#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a></dt>
<dd>General calendar related functions.</dd>
<dt>Module <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a></dt>
<dd>Time access and conversions.</dd>
</dl>
</div>
<div class="section" id="available-types">
<h2>8.1.1. Available Types<a class="headerlink" href="#available-types" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">date</code></dt>
<dd><p>An idealized naive date, assuming the current Gregorian calendar always was, and
always will be, in effect. Attributes: <a class="reference internal" href="#datetime.date.year" title="datetime.date.year"><code class="xref py py-attr docutils literal notranslate"><span class="pre">year</span></code></a>, <a class="reference internal" href="#datetime.date.month" title="datetime.date.month"><code class="xref py py-attr docutils literal notranslate"><span class="pre">month</span></code></a>, and
<a class="reference internal" href="#datetime.date.day" title="datetime.date.day"><code class="xref py py-attr docutils literal notranslate"><span class="pre">day</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">time</code></dt>
<dd><p>An idealized time, independent of any particular day, assuming that every day
has exactly 24*60*60 seconds (there is no notion of “leap seconds” here).
Attributes: <a class="reference internal" href="#datetime.time.hour" title="datetime.time.hour"><code class="xref py py-attr docutils literal notranslate"><span class="pre">hour</span></code></a>, <a class="reference internal" href="#datetime.time.minute" title="datetime.time.minute"><code class="xref py py-attr docutils literal notranslate"><span class="pre">minute</span></code></a>, <a class="reference internal" href="#datetime.time.second" title="datetime.time.second"><code class="xref py py-attr docutils literal notranslate"><span class="pre">second</span></code></a>, <a class="reference internal" href="#datetime.time.microsecond" title="datetime.time.microsecond"><code class="xref py py-attr docutils literal notranslate"><span class="pre">microsecond</span></code></a>,
and <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">datetime</code></dt>
<dd><p>A combination of a date and a time. Attributes: <a class="reference internal" href="#datetime.datetime.year" title="datetime.datetime.year"><code class="xref py py-attr docutils literal notranslate"><span class="pre">year</span></code></a>, <a class="reference internal" href="#datetime.datetime.month" title="datetime.datetime.month"><code class="xref py py-attr docutils literal notranslate"><span class="pre">month</span></code></a>,
<a class="reference internal" href="#datetime.datetime.day" title="datetime.datetime.day"><code class="xref py py-attr docutils literal notranslate"><span class="pre">day</span></code></a>, <a class="reference internal" href="#datetime.datetime.hour" title="datetime.datetime.hour"><code class="xref py py-attr docutils literal notranslate"><span class="pre">hour</span></code></a>, <a class="reference internal" href="#datetime.datetime.minute" title="datetime.datetime.minute"><code class="xref py py-attr docutils literal notranslate"><span class="pre">minute</span></code></a>, <a class="reference internal" href="#datetime.datetime.second" title="datetime.datetime.second"><code class="xref py py-attr docutils literal notranslate"><span class="pre">second</span></code></a>, <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code class="xref py py-attr docutils literal notranslate"><span class="pre">microsecond</span></code></a>,
and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">timedelta</code></dt>
<dd><p>A duration expressing the difference between two <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>, <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>,
or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instances to microsecond resolution.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">tzinfo</code></dt>
<dd><p>An abstract base class for time zone information objects.  These are used by the
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> classes to provide a customizable notion of
time adjustment (for example, to account for time zone and/or daylight saving
time).</p>
</dd></dl>

<p>Objects of these types are immutable.</p>
<p>Objects of the <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> type are always naive.</p>
<p>An object of type <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> or <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> may be naive or aware.
A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object <em>d</em> is aware if <code class="docutils literal notranslate"><span class="pre">d.tzinfo</span></code> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> and
<code class="docutils literal notranslate"><span class="pre">d.tzinfo.utcoffset(d)</span></code> does not return <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If <code class="docutils literal notranslate"><span class="pre">d.tzinfo</span></code> is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, or if <code class="docutils literal notranslate"><span class="pre">d.tzinfo</span></code> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> but <code class="docutils literal notranslate"><span class="pre">d.tzinfo.utcoffset(d)</span></code>
returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>d</em> is naive.  A <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object <em>t</em> is aware
if <code class="docutils literal notranslate"><span class="pre">t.tzinfo</span></code> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> and <code class="docutils literal notranslate"><span class="pre">t.tzinfo.utcoffset(None)</span></code> does not return
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  Otherwise, <em>t</em> is naive.</p>
<p>The distinction between naive and aware doesn’t apply to <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a>
objects.</p>
<p>Subclass relationships:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">object</span>
    <span class="n">timedelta</span>
    <span class="n">tzinfo</span>
    <span class="n">time</span>
    <span class="n">date</span>
        <span class="n">datetime</span>
</pre></div>
</div>
</div>
<div class="section" id="timedelta-objects">
<span id="datetime-timedelta"></span><h2>8.1.2. <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> Objects<a class="headerlink" href="#timedelta-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object represents a duration, the difference between two
dates or times.</p>
<dl class="class">
<dt id="datetime.timedelta">
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">timedelta</code><span class="sig-paren">(</span><span class="optional">[</span><em>days</em><span class="optional">[</span>, <em>seconds</em><span class="optional">[</span>, <em>microseconds</em><span class="optional">[</span>, <em>milliseconds</em><span class="optional">[</span>, <em>minutes</em><span class="optional">[</span>, <em>hours</em><span class="optional">[</span>, <em>weeks</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.timedelta" title="Permalink to this definition">¶</a></dt>
<dd><p>All arguments are optional and default to <code class="docutils literal notranslate"><span class="pre">0</span></code>.  Arguments may be ints, longs,
or floats, and may be positive or negative.</p>
<p>Only <em>days</em>, <em>seconds</em> and <em>microseconds</em> are stored internally.  Arguments are
converted to those units:</p>
<ul class="simple">
<li>A millisecond is converted to 1000 microseconds.</li>
<li>A minute is converted to 60 seconds.</li>
<li>An hour is converted to 3600 seconds.</li>
<li>A week is converted to 7 days.</li>
</ul>
<p>and days, seconds and microseconds are then normalized so that the
representation is unique, with</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">microseconds</span> <span class="pre">&lt;</span> <span class="pre">1000000</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">seconds</span> <span class="pre">&lt;</span> <span class="pre">3600*24</span></code> (the number of seconds in one day)</li>
<li><code class="docutils literal notranslate"><span class="pre">-999999999</span> <span class="pre">&lt;=</span> <span class="pre">days</span> <span class="pre">&lt;=</span> <span class="pre">999999999</span></code></li>
</ul>
<p>If any argument is a float and there are fractional microseconds, the fractional
microseconds left over from all arguments are combined and their sum is rounded
to the nearest microsecond.  If no argument is a float, the conversion and
normalization processes are exact (no information is lost).</p>
<p>If the normalized value of days lies outside the indicated range,
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised.</p>
<p>Note that normalization of negative values may be surprising at first. For
example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">microseconds</span><span class="o">=-</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">days</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">seconds</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">microseconds</span><span class="p">)</span>
<span class="go">(-1, 86399, 999999)</span>
</pre></div>
</div>
</dd></dl>

<p>Class attributes are:</p>
<dl class="attribute">
<dt id="datetime.timedelta.min">
<code class="descclassname">timedelta.</code><code class="descname">min</code><a class="headerlink" href="#datetime.timedelta.min" title="Permalink to this definition">¶</a></dt>
<dd><p>The most negative <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object, <code class="docutils literal notranslate"><span class="pre">timedelta(-999999999)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.timedelta.max">
<code class="descclassname">timedelta.</code><code class="descname">max</code><a class="headerlink" href="#datetime.timedelta.max" title="Permalink to this definition">¶</a></dt>
<dd><p>The most positive <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object, <code class="docutils literal notranslate"><span class="pre">timedelta(days=999999999,</span>
<span class="pre">hours=23,</span> <span class="pre">minutes=59,</span> <span class="pre">seconds=59,</span> <span class="pre">microseconds=999999)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.timedelta.resolution">
<code class="descclassname">timedelta.</code><code class="descname">resolution</code><a class="headerlink" href="#datetime.timedelta.resolution" title="Permalink to this definition">¶</a></dt>
<dd><p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> objects,
<code class="docutils literal notranslate"><span class="pre">timedelta(microseconds=1)</span></code>.</p>
</dd></dl>

<p>Note that, because of normalization, <code class="docutils literal notranslate"><span class="pre">timedelta.max</span></code> &gt; <code class="docutils literal notranslate"><span class="pre">-timedelta.min</span></code>.
<code class="docutils literal notranslate"><span class="pre">-timedelta.max</span></code> is not representable as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object.</p>
<p>Instance attributes (read-only):</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">days</span></code></td>
<td>Between -999999999 and 999999999 inclusive</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">seconds</span></code></td>
<td>Between 0 and 86399 inclusive</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">microseconds</span></code></td>
<td>Between 0 and 999999 inclusive</td>
</tr>
</tbody>
</table>
<p>Supported operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">t1</span> <span class="pre">=</span> <span class="pre">t2</span> <span class="pre">+</span> <span class="pre">t3</span></code></td>
<td>Sum of <em>t2</em> and <em>t3</em>. Afterwards <em>t1</em>-<em>t2</em> ==
<em>t3</em> and <em>t1</em>-<em>t3</em> == <em>t2</em> are true. (1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">t1</span> <span class="pre">=</span> <span class="pre">t2</span> <span class="pre">-</span> <span class="pre">t3</span></code></td>
<td>Difference of <em>t2</em> and <em>t3</em>. Afterwards <em>t1</em>
== <em>t2</em> - <em>t3</em> and <em>t2</em> == <em>t1</em> + <em>t3</em> are
true. (1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">t1</span> <span class="pre">=</span> <span class="pre">t2</span> <span class="pre">*</span> <span class="pre">i</span> <span class="pre">or</span> <span class="pre">t1</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">*</span> <span class="pre">t2</span></code></td>
<td>Delta multiplied by an integer or long.
Afterwards <em>t1</em> // i == <em>t2</em> is true,
provided <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">!=</span> <span class="pre">0</span></code>.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>In general, <em>t1</em> * i == <em>t1</em> * (i-1) + <em>t1</em>
is true. (1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">t1</span> <span class="pre">=</span> <span class="pre">t2</span> <span class="pre">//</span> <span class="pre">i</span></code></td>
<td>The floor is computed and the remainder (if
any) is thrown away. (3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">+t1</span></code></td>
<td>Returns a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object with the
same value. (2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">-t1</span></code></td>
<td>equivalent to <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a>(-<em>t1.days</em>, -<em>t1.seconds</em>,
-<em>t1.microseconds</em>), and to <em>t1</em>* -1. (1)(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">abs(t)</span></code></td>
<td>equivalent to +<em>t</em> when <code class="docutils literal notranslate"><span class="pre">t.days</span> <span class="pre">&gt;=</span> <span class="pre">0</span></code>, and
to -<em>t</em> when <code class="docutils literal notranslate"><span class="pre">t.days</span> <span class="pre">&lt;</span> <span class="pre">0</span></code>. (2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">str(t)</span></code></td>
<td>Returns a string in the form
<code class="docutils literal notranslate"><span class="pre">[D</span> <span class="pre">day[s],</span> <span class="pre">][H]H:MM:SS[.UUUUUU]</span></code>, where D
is negative for negative <code class="docutils literal notranslate"><span class="pre">t</span></code>. (5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">repr(t)</span></code></td>
<td>Returns a string in the form
<code class="docutils literal notranslate"><span class="pre">datetime.timedelta(D[,</span> <span class="pre">S[,</span> <span class="pre">U]])</span></code>, where D
is negative for negative <code class="docutils literal notranslate"><span class="pre">t</span></code>. (5)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">This is exact, but may overflow.</p>
</li>
<li><p class="first">This is exact, and cannot overflow.</p>
</li>
<li><p class="first">Division by 0 raises <a class="reference internal" href="exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>.</p>
</li>
<li><p class="first">-<em>timedelta.max</em> is not representable as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object.</p>
</li>
<li><p class="first">String representations of <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> objects are normalized
similarly to their internal representation.  This leads to somewhat
unusual results for negative timedeltas.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=-</span><span class="mi">5</span><span class="p">)</span>
<span class="go">datetime.timedelta(-1, 68400)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">_</span><span class="p">)</span>
<span class="go">-1 day, 19:00:00</span>
</pre></div>
</div>
</li>
</ol>
<p>In addition to the operations listed above <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> objects support
certain additions and subtractions with <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> and <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>
objects (see below).</p>
<p>Comparisons of <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> objects are supported with the
<a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object representing the smaller duration considered to be the
smaller timedelta. In order to stop mixed-type comparisons from falling back to
the default comparison by object address, when a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object is
compared to an object of a different type, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised unless the
comparison is <code class="docutils literal notranslate"><span class="pre">==</span></code> or <code class="docutils literal notranslate"><span class="pre">!=</span></code>.  The latter cases return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> or
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, respectively.</p>
<p><a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> objects are <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> (usable as dictionary keys), support
efficient pickling, and in Boolean contexts, a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object is
considered to be true if and only if it isn’t equal to <code class="docutils literal notranslate"><span class="pre">timedelta(0)</span></code>.</p>
<p>Instance methods:</p>
<dl class="method">
<dt id="datetime.timedelta.total_seconds">
<code class="descclassname">timedelta.</code><code class="descname">total_seconds</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.timedelta.total_seconds" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the total number of seconds contained in the duration.
Equivalent to <code class="docutils literal notranslate"><span class="pre">(td.microseconds</span> <span class="pre">+</span> <span class="pre">(td.seconds</span> <span class="pre">+</span> <span class="pre">td.days</span> <span class="pre">*</span> <span class="pre">24</span> <span class="pre">*</span>
<span class="pre">3600)</span> <span class="pre">*</span> <span class="pre">10**6)</span> <span class="pre">/</span> <span class="pre">10**6</span></code> computed with true division enabled.</p>
<p>Note that for very large time intervals (greater than 270 years on
most platforms) this method will lose microsecond accuracy.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">year</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="mi">365</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">another_year</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">weeks</span><span class="o">=</span><span class="mi">40</span><span class="p">,</span> <span class="n">days</span><span class="o">=</span><span class="mi">84</span><span class="p">,</span> <span class="n">hours</span><span class="o">=</span><span class="mi">23</span><span class="p">,</span>
<span class="gp">... </span>                         <span class="n">minutes</span><span class="o">=</span><span class="mi">50</span><span class="p">,</span> <span class="n">seconds</span><span class="o">=</span><span class="mi">600</span><span class="p">)</span>  <span class="c1"># adds up to 365 days</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">year</span><span class="o">.</span><span class="n">total_seconds</span><span class="p">()</span>
<span class="go">31536000.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">year</span> <span class="o">==</span> <span class="n">another_year</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ten_years</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="n">year</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ten_years</span><span class="p">,</span> <span class="n">ten_years</span><span class="o">.</span><span class="n">days</span> <span class="o">//</span> <span class="mi">365</span>
<span class="go">(datetime.timedelta(3650), 10)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">nine_years</span> <span class="o">=</span> <span class="n">ten_years</span> <span class="o">-</span> <span class="n">year</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">nine_years</span><span class="p">,</span> <span class="n">nine_years</span><span class="o">.</span><span class="n">days</span> <span class="o">//</span> <span class="mi">365</span>
<span class="go">(datetime.timedelta(3285), 9)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">three_years</span> <span class="o">=</span> <span class="n">nine_years</span> <span class="o">//</span> <span class="mi">3</span><span class="p">;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">three_years</span><span class="p">,</span> <span class="n">three_years</span><span class="o">.</span><span class="n">days</span> <span class="o">//</span> <span class="mi">365</span>
<span class="go">(datetime.timedelta(1095), 3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">abs</span><span class="p">(</span><span class="n">three_years</span> <span class="o">-</span> <span class="n">ten_years</span><span class="p">)</span> <span class="o">==</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">three_years</span> <span class="o">+</span> <span class="n">year</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="date-objects">
<span id="datetime-date"></span><h2>8.1.3. <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> Objects<a class="headerlink" href="#date-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object represents a date (year, month and day) in an idealized
calendar, the current Gregorian calendar indefinitely extended in both
directions.  January 1 of year 1 is called day number 1, January 2 of year 1 is
called day number 2, and so on.  This matches the definition of the “proleptic
Gregorian” calendar in Dershowitz and Reingold’s book Calendrical Calculations,
where it’s the base calendar for all computations.  See the book for algorithms
for converting between proleptic Gregorian ordinals and many other calendar
systems.</p>
<dl class="class">
<dt id="datetime.date">
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">date</code><span class="sig-paren">(</span><em>year</em>, <em>month</em>, <em>day</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date" title="Permalink to this definition">¶</a></dt>
<dd><p>All arguments are required.  Arguments may be ints or longs, in the following
ranges:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">MINYEAR</span> <span class="pre">&lt;=</span> <span class="pre">year</span> <span class="pre">&lt;=</span> <span class="pre">MAXYEAR</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">&lt;=</span> <span class="pre">month</span> <span class="pre">&lt;=</span> <span class="pre">12</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">&lt;=</span> <span class="pre">day</span> <span class="pre">&lt;=</span> <span class="pre">number</span> <span class="pre">of</span> <span class="pre">days</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">given</span> <span class="pre">month</span> <span class="pre">and</span> <span class="pre">year</span></code></li>
</ul>
<p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<p>Other constructors, all class methods:</p>
<dl class="classmethod">
<dt id="datetime.date.today">
<em class="property">classmethod </em><code class="descclassname">date.</code><code class="descname">today</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.today" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current local date.  This is equivalent to
<code class="docutils literal notranslate"><span class="pre">date.fromtimestamp(time.time())</span></code>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.date.fromtimestamp">
<em class="property">classmethod </em><code class="descclassname">date.</code><code class="descname">fromtimestamp</code><span class="sig-paren">(</span><em>timestamp</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.fromtimestamp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the local date corresponding to the POSIX timestamp, such as is returned
by <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>.  This may raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, if the timestamp is out
of the range of values supported by the platform C <code class="xref c c-func docutils literal notranslate"><span class="pre">localtime()</span></code> function.
It’s common for this to be restricted to years from 1970 through 2038.  Note
that on non-POSIX systems that include leap seconds in their notion of a
timestamp, leap seconds are ignored by <a class="reference internal" href="#datetime.date.fromtimestamp" title="datetime.date.fromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.date.fromordinal">
<em class="property">classmethod </em><code class="descclassname">date.</code><code class="descname">fromordinal</code><span class="sig-paren">(</span><em>ordinal</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.fromordinal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the date corresponding to the proleptic Gregorian ordinal, where January
1 of year 1 has ordinal 1.  <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised unless <code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">&lt;=</span> <span class="pre">ordinal</span> <span class="pre">&lt;=</span>
<span class="pre">date.max.toordinal()</span></code>. For any date <em>d</em>, <code class="docutils literal notranslate"><span class="pre">date.fromordinal(d.toordinal())</span> <span class="pre">==</span>
<span class="pre">d</span></code>.</p>
</dd></dl>

<p>Class attributes:</p>
<dl class="attribute">
<dt id="datetime.date.min">
<code class="descclassname">date.</code><code class="descname">min</code><a class="headerlink" href="#datetime.date.min" title="Permalink to this definition">¶</a></dt>
<dd><p>The earliest representable date, <code class="docutils literal notranslate"><span class="pre">date(MINYEAR,</span> <span class="pre">1,</span> <span class="pre">1)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.date.max">
<code class="descclassname">date.</code><code class="descname">max</code><a class="headerlink" href="#datetime.date.max" title="Permalink to this definition">¶</a></dt>
<dd><p>The latest representable date, <code class="docutils literal notranslate"><span class="pre">date(MAXYEAR,</span> <span class="pre">12,</span> <span class="pre">31)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.date.resolution">
<code class="descclassname">date.</code><code class="descname">resolution</code><a class="headerlink" href="#datetime.date.resolution" title="Permalink to this definition">¶</a></dt>
<dd><p>The smallest possible difference between non-equal date objects,
<code class="docutils literal notranslate"><span class="pre">timedelta(days=1)</span></code>.</p>
</dd></dl>

<p>Instance attributes (read-only):</p>
<dl class="attribute">
<dt id="datetime.date.year">
<code class="descclassname">date.</code><code class="descname">year</code><a class="headerlink" href="#datetime.date.year" title="Permalink to this definition">¶</a></dt>
<dd><p>Between <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a> and <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a> inclusive.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.date.month">
<code class="descclassname">date.</code><code class="descname">month</code><a class="headerlink" href="#datetime.date.month" title="Permalink to this definition">¶</a></dt>
<dd><p>Between 1 and 12 inclusive.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.date.day">
<code class="descclassname">date.</code><code class="descname">day</code><a class="headerlink" href="#datetime.date.day" title="Permalink to this definition">¶</a></dt>
<dd><p>Between 1 and the number of days in the given month of the given year.</p>
</dd></dl>

<p>Supported operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">date2</span> <span class="pre">=</span> <span class="pre">date1</span> <span class="pre">+</span> <span class="pre">timedelta</span></code></td>
<td><em>date2</em> is <code class="docutils literal notranslate"><span class="pre">timedelta.days</span></code> days removed
from <em>date1</em>.  (1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">date2</span> <span class="pre">=</span> <span class="pre">date1</span> <span class="pre">-</span> <span class="pre">timedelta</span></code></td>
<td>Computes <em>date2</em> such that <code class="docutils literal notranslate"><span class="pre">date2</span> <span class="pre">+</span>
<span class="pre">timedelta</span> <span class="pre">==</span> <span class="pre">date1</span></code>. (2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">timedelta</span> <span class="pre">=</span> <span class="pre">date1</span> <span class="pre">-</span> <span class="pre">date2</span></code></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">date1</span> <span class="pre">&lt;</span> <span class="pre">date2</span></code></td>
<td><em>date1</em> is considered less than <em>date2</em> when
<em>date1</em> precedes <em>date2</em> in time. (4)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li><em>date2</em> is moved forward in time if <code class="docutils literal notranslate"><span class="pre">timedelta.days</span> <span class="pre">&gt;</span> <span class="pre">0</span></code>, or backward if
<code class="docutils literal notranslate"><span class="pre">timedelta.days</span> <span class="pre">&lt;</span> <span class="pre">0</span></code>.  Afterward <code class="docutils literal notranslate"><span class="pre">date2</span> <span class="pre">-</span> <span class="pre">date1</span> <span class="pre">==</span> <span class="pre">timedelta.days</span></code>.
<code class="docutils literal notranslate"><span class="pre">timedelta.seconds</span></code> and <code class="docutils literal notranslate"><span class="pre">timedelta.microseconds</span></code> are ignored.
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised if <code class="docutils literal notranslate"><span class="pre">date2.year</span></code> would be smaller than
<a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a> or larger than <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a>.</li>
<li>This isn’t quite equivalent to date1 + (-timedelta), because -timedelta in
isolation can overflow in cases where date1 - timedelta does not.
<code class="docutils literal notranslate"><span class="pre">timedelta.seconds</span></code> and <code class="docutils literal notranslate"><span class="pre">timedelta.microseconds</span></code> are ignored.</li>
<li>This is exact, and cannot overflow.  timedelta.seconds and
timedelta.microseconds are 0, and date2 + timedelta == date1 after.</li>
<li>In other words, <code class="docutils literal notranslate"><span class="pre">date1</span> <span class="pre">&lt;</span> <span class="pre">date2</span></code> if and only if <code class="docutils literal notranslate"><span class="pre">date1.toordinal()</span> <span class="pre">&lt;</span>
<span class="pre">date2.toordinal()</span></code>. In order to stop comparison from falling back to the
default scheme of comparing object addresses, date comparison normally raises
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the other comparand isn’t also a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object.
However, <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> is returned instead if the other comparand has a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">timetuple()</span></code> attribute.  This hook gives other kinds of date objects a
chance at implementing mixed-type comparison. If not, when a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>
object is compared to an object of a different type, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised
unless the comparison is <code class="docutils literal notranslate"><span class="pre">==</span></code> or <code class="docutils literal notranslate"><span class="pre">!=</span></code>.  The latter cases return
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> or <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, respectively.</li>
</ol>
<p>Dates can be used as dictionary keys. In Boolean contexts, all <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>
objects are considered to be true.</p>
<p>Instance methods:</p>
<dl class="method">
<dt id="datetime.date.replace">
<code class="descclassname">date.</code><code class="descname">replace</code><span class="sig-paren">(</span><em>year</em>, <em>month</em>, <em>day</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a date with the same value, except for those parameters given new
values by whichever keyword arguments are specified.  For example, if <code class="docutils literal notranslate"><span class="pre">d</span> <span class="pre">==</span>
<span class="pre">date(2002,</span> <span class="pre">12,</span> <span class="pre">31)</span></code>, then <code class="docutils literal notranslate"><span class="pre">d.replace(day=26)</span> <span class="pre">==</span> <span class="pre">date(2002,</span> <span class="pre">12,</span> <span class="pre">26)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.timetuple">
<code class="descclassname">date.</code><code class="descname">timetuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.timetuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> such as returned by <a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a>.
The hours, minutes and seconds are 0, and the DST flag is -1. <code class="docutils literal notranslate"><span class="pre">d.timetuple()</span></code>
is equivalent to <code class="docutils literal notranslate"><span class="pre">time.struct_time((d.year,</span> <span class="pre">d.month,</span> <span class="pre">d.day,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">0,</span>
<span class="pre">d.weekday(),</span> <span class="pre">yday,</span> <span class="pre">-1))</span></code>, where <code class="docutils literal notranslate"><span class="pre">yday</span> <span class="pre">=</span> <span class="pre">d.toordinal()</span> <span class="pre">-</span> <span class="pre">date(d.year,</span> <span class="pre">1,</span>
<span class="pre">1).toordinal()</span> <span class="pre">+</span> <span class="pre">1</span></code> is the day number within the current year starting with
<code class="docutils literal notranslate"><span class="pre">1</span></code> for January 1st.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.toordinal">
<code class="descclassname">date.</code><code class="descname">toordinal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.toordinal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the proleptic Gregorian ordinal of the date, where January 1 of year 1
has ordinal 1.  For any <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object <em>d</em>,
<code class="docutils literal notranslate"><span class="pre">date.fromordinal(d.toordinal())</span> <span class="pre">==</span> <span class="pre">d</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.weekday">
<code class="descclassname">date.</code><code class="descname">weekday</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.weekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
For example, <code class="docutils literal notranslate"><span class="pre">date(2002,</span> <span class="pre">12,</span> <span class="pre">4).weekday()</span> <span class="pre">==</span> <span class="pre">2</span></code>, a Wednesday. See also
<a class="reference internal" href="#datetime.date.isoweekday" title="datetime.date.isoweekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isoweekday()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.isoweekday">
<code class="descclassname">date.</code><code class="descname">isoweekday</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.isoweekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
For example, <code class="docutils literal notranslate"><span class="pre">date(2002,</span> <span class="pre">12,</span> <span class="pre">4).isoweekday()</span> <span class="pre">==</span> <span class="pre">3</span></code>, a Wednesday. See also
<a class="reference internal" href="#datetime.date.weekday" title="datetime.date.weekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">weekday()</span></code></a>, <a class="reference internal" href="#datetime.date.isocalendar" title="datetime.date.isocalendar"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isocalendar()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.isocalendar">
<code class="descclassname">date.</code><code class="descname">isocalendar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.isocalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a 3-tuple, (ISO year, ISO week number, ISO weekday).</p>
<p>The ISO calendar is a widely used variant of the Gregorian calendar. See
<a class="reference external" href="https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm">https://www.staff.science.uu.nl/~gent0113/calendar/isocalendar.htm</a> for a good
explanation.</p>
<p>The ISO year consists of 52 or 53 full weeks, and where a week starts on a
Monday and ends on a Sunday.  The first week of an ISO year is the first
(Gregorian) calendar week of a year containing a Thursday. This is called week
number 1, and the ISO year of that Thursday is the same as its Gregorian year.</p>
<p>For example, 2004 begins on a Thursday, so the first week of ISO year 2004
begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan 2004, so that
<code class="docutils literal notranslate"><span class="pre">date(2003,</span> <span class="pre">12,</span> <span class="pre">29).isocalendar()</span> <span class="pre">==</span> <span class="pre">(2004,</span> <span class="pre">1,</span> <span class="pre">1)</span></code> and <code class="docutils literal notranslate"><span class="pre">date(2004,</span> <span class="pre">1,</span>
<span class="pre">4).isocalendar()</span> <span class="pre">==</span> <span class="pre">(2004,</span> <span class="pre">1,</span> <span class="pre">7)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.isoformat">
<code class="descclassname">date.</code><code class="descname">isoformat</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.isoformat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date in ISO 8601 format, ‘YYYY-MM-DD’.  For
example, <code class="docutils literal notranslate"><span class="pre">date(2002,</span> <span class="pre">12,</span> <span class="pre">4).isoformat()</span> <span class="pre">==</span> <span class="pre">'2002-12-04'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.__str__">
<code class="descclassname">date.</code><code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>For a date <em>d</em>, <code class="docutils literal notranslate"><span class="pre">str(d)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">d.isoformat()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.ctime">
<code class="descclassname">date.</code><code class="descname">ctime</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.ctime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date, for example <code class="docutils literal notranslate"><span class="pre">date(2002,</span> <span class="pre">12,</span>
<span class="pre">4).ctime()</span> <span class="pre">==</span> <span class="pre">'Wed</span> <span class="pre">Dec</span> <span class="pre">4</span> <span class="pre">00:00:00</span> <span class="pre">2002'</span></code>. <code class="docutils literal notranslate"><span class="pre">d.ctime()</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">time.ctime(time.mktime(d.timetuple()))</span></code> on platforms where the native C
<code class="xref c c-func docutils literal notranslate"><span class="pre">ctime()</span></code> function (which <a class="reference internal" href="time.html#time.ctime" title="time.ctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.ctime()</span></code></a> invokes, but which
<a class="reference internal" href="#datetime.date.ctime" title="datetime.date.ctime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">date.ctime()</span></code></a> does not invoke) conforms to the C standard.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.strftime">
<code class="descclassname">date.</code><code class="descname">strftime</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.strftime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date, controlled by an explicit format string.
Format codes referring to hours, minutes or seconds will see 0 values. For a
complete list of formatting directives, see section
<a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.date.__format__">
<code class="descclassname">date.</code><code class="descname">__format__</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.date.__format__" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#datetime.date.strftime" title="datetime.date.strftime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">date.strftime()</span></code></a>. This makes it possible to specify a format
string for a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object when using <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.
See section <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<p>Example of counting days to an event:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">today</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">today</span>
<span class="go">datetime.date(2007, 12, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">today</span> <span class="o">==</span> <span class="n">date</span><span class="o">.</span><span class="n">fromtimestamp</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">())</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">my_birthday</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="n">today</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">24</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">my_birthday</span> <span class="o">&lt;</span> <span class="n">today</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">my_birthday</span> <span class="o">=</span> <span class="n">my_birthday</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="n">today</span><span class="o">.</span><span class="n">year</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">my_birthday</span>
<span class="go">datetime.date(2008, 6, 24)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time_to_birthday</span> <span class="o">=</span> <span class="nb">abs</span><span class="p">(</span><span class="n">my_birthday</span> <span class="o">-</span> <span class="n">today</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time_to_birthday</span><span class="o">.</span><span class="n">days</span>
<span class="go">202</span>
</pre></div>
</div>
<p>Example of working with <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">fromordinal</span><span class="p">(</span><span class="mi">730920</span><span class="p">)</span> <span class="c1"># 730920th day after 1. 1. 0001</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">datetime.date(2002, 3, 11)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">timetuple</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">t</span><span class="p">:</span>     
<span class="gp">... </span>    <span class="k">print</span> <span class="n">i</span>
<span class="go">2002                # year</span>
<span class="go">3                   # month</span>
<span class="go">11                  # day</span>
<span class="go">0</span>
<span class="go">0</span>
<span class="go">0</span>
<span class="go">0                   # weekday (0 = Monday)</span>
<span class="go">70                  # 70th day in the year</span>
<span class="go">-1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ic</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">isocalendar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">ic</span><span class="p">:</span>    
<span class="gp">... </span>    <span class="k">print</span> <span class="n">i</span>
<span class="go">2002                # ISO year</span>
<span class="go">11                  # ISO week number</span>
<span class="go">1                   # ISO day number ( 1 = Monday )</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
<span class="go">&#39;2002-03-11&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2">/%m/%y&quot;</span><span class="p">)</span>
<span class="go">&#39;11/03/02&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%A </span><span class="si">%d</span><span class="s2">. %B %Y&quot;</span><span class="p">)</span>
<span class="go">&#39;Monday 11. March 2002&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;The {1} is {0:</span><span class="si">%d</span><span class="s1">}, the {2} is {0:%B}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="s2">&quot;day&quot;</span><span class="p">,</span> <span class="s2">&quot;month&quot;</span><span class="p">)</span>
<span class="go">&#39;The day is 11, the month is March.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="datetime-objects">
<span id="datetime-datetime"></span><h2>8.1.4. <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> Objects<a class="headerlink" href="#datetime-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object is a single object containing all the information
from a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object and a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object.  Like a <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>
object, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> assumes the current Gregorian calendar extended in
both directions; like a time object, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> assumes there are exactly
3600*24 seconds in every day.</p>
<p>Constructor:</p>
<dl class="class">
<dt id="datetime.datetime">
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">datetime</code><span class="sig-paren">(</span><em>year</em>, <em>month</em>, <em>day</em><span class="optional">[</span>, <em>hour</em><span class="optional">[</span>, <em>minute</em><span class="optional">[</span>, <em>second</em><span class="optional">[</span>, <em>microsecond</em><span class="optional">[</span>, <em>tzinfo</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime" title="Permalink to this definition">¶</a></dt>
<dd><p>The year, month and day arguments are required.  <em>tzinfo</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code>, or an
instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass.  The remaining arguments may be ints or
longs, in the following ranges:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">MINYEAR</span> <span class="pre">&lt;=</span> <span class="pre">year</span> <span class="pre">&lt;=</span> <span class="pre">MAXYEAR</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">&lt;=</span> <span class="pre">month</span> <span class="pre">&lt;=</span> <span class="pre">12</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">&lt;=</span> <span class="pre">day</span> <span class="pre">&lt;=</span> <span class="pre">number</span> <span class="pre">of</span> <span class="pre">days</span> <span class="pre">in</span> <span class="pre">the</span> <span class="pre">given</span> <span class="pre">month</span> <span class="pre">and</span> <span class="pre">year</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">hour</span> <span class="pre">&lt;</span> <span class="pre">24</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">minute</span> <span class="pre">&lt;</span> <span class="pre">60</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">second</span> <span class="pre">&lt;</span> <span class="pre">60</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">microsecond</span> <span class="pre">&lt;</span> <span class="pre">1000000</span></code></li>
</ul>
<p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<p>Other constructors, all class methods:</p>
<dl class="classmethod">
<dt id="datetime.datetime.today">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">today</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.today" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current local datetime, with <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is
equivalent to <code class="docutils literal notranslate"><span class="pre">datetime.fromtimestamp(time.time())</span></code>. See also <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code class="xref py py-meth docutils literal notranslate"><span class="pre">now()</span></code></a>,
<a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.now">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">now</code><span class="sig-paren">(</span><span class="optional">[</span><em>tz</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.now" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current local date and time.  If optional argument <em>tz</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>
or not specified, this is like <a class="reference internal" href="#datetime.datetime.today" title="datetime.datetime.today"><code class="xref py py-meth docutils literal notranslate"><span class="pre">today()</span></code></a>, but, if possible, supplies more
precision than can be gotten from going through a <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a> timestamp
(for example, this may be possible on platforms supplying the C
<code class="xref c c-func docutils literal notranslate"><span class="pre">gettimeofday()</span></code> function).</p>
<p>If <em>tz</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass, and the
current date and time are converted to <em>tz</em>’s time zone.  In this case the
result is equivalent to <code class="docutils literal notranslate"><span class="pre">tz.fromutc(datetime.utcnow().replace(tzinfo=tz))</span></code>.
See also <a class="reference internal" href="#datetime.datetime.today" title="datetime.datetime.today"><code class="xref py py-meth docutils literal notranslate"><span class="pre">today()</span></code></a>, <a class="reference internal" href="#datetime.datetime.utcnow" title="datetime.datetime.utcnow"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcnow()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.utcnow">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">utcnow</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.utcnow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current UTC date and time, with <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is like
<a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code class="xref py py-meth docutils literal notranslate"><span class="pre">now()</span></code></a>, but returns the current UTC date and time, as a naive
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object. See also <a class="reference internal" href="#datetime.datetime.now" title="datetime.datetime.now"><code class="xref py py-meth docutils literal notranslate"><span class="pre">now()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.fromtimestamp">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">fromtimestamp</code><span class="sig-paren">(</span><em>timestamp</em><span class="optional">[</span>, <em>tz</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.fromtimestamp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the local date and time corresponding to the POSIX timestamp, such as is
returned by <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>. If optional argument <em>tz</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> or not
specified, the timestamp is converted to the platform’s local date and time, and
the returned <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object is naive.</p>
<p>If <em>tz</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass, and the
timestamp is converted to <em>tz</em>’s time zone.  In this case the result is
equivalent to
<code class="docutils literal notranslate"><span class="pre">tz.fromutc(datetime.utcfromtimestamp(timestamp).replace(tzinfo=tz))</span></code>.</p>
<p><a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a> may raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, if the timestamp is out of
the range of values supported by the platform C <code class="xref c c-func docutils literal notranslate"><span class="pre">localtime()</span></code> or
<code class="xref c c-func docutils literal notranslate"><span class="pre">gmtime()</span></code> functions.  It’s common for this to be restricted to years in
1970 through 2038. Note that on non-POSIX systems that include leap seconds in
their notion of a timestamp, leap seconds are ignored by <a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a>,
and then it’s possible to have two timestamps differing by a second that yield
identical <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects. See also <a class="reference internal" href="#datetime.datetime.utcfromtimestamp" title="datetime.datetime.utcfromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcfromtimestamp()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.utcfromtimestamp">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">utcfromtimestamp</code><span class="sig-paren">(</span><em>timestamp</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.utcfromtimestamp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the UTC <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> corresponding to the POSIX timestamp, with
<a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> <code class="docutils literal notranslate"><span class="pre">None</span></code>. This may raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, if the timestamp is
out of the range of values supported by the platform C <code class="xref c c-func docutils literal notranslate"><span class="pre">gmtime()</span></code> function.
It’s common for this to be restricted to years in 1970 through 2038. See also
<a class="reference internal" href="#datetime.datetime.fromtimestamp" title="datetime.datetime.fromtimestamp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromtimestamp()</span></code></a>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.fromordinal">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">fromordinal</code><span class="sig-paren">(</span><em>ordinal</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.fromordinal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> corresponding to the proleptic Gregorian ordinal,
where January 1 of year 1 has ordinal 1. <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised unless <code class="docutils literal notranslate"><span class="pre">1</span>
<span class="pre">&lt;=</span> <span class="pre">ordinal</span> <span class="pre">&lt;=</span> <span class="pre">datetime.max.toordinal()</span></code>.  The hour, minute, second and
microsecond of the result are all 0, and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.combine">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">combine</code><span class="sig-paren">(</span><em>date</em>, <em>time</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.combine" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object whose date components are equal to the
given <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object’s, and whose time components and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
attributes are equal to the given <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object’s. For any
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object <em>d</em>,
<code class="docutils literal notranslate"><span class="pre">d</span> <span class="pre">==</span> <span class="pre">datetime.combine(d.date(),</span> <span class="pre">d.timetz())</span></code>.  If date is a
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object, its time components and <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attributes
are ignored.</p>
</dd></dl>

<dl class="classmethod">
<dt id="datetime.datetime.strptime">
<em class="property">classmethod </em><code class="descclassname">datetime.</code><code class="descname">strptime</code><span class="sig-paren">(</span><em>date_string</em>, <em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.strptime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> corresponding to <em>date_string</em>, parsed according to
<em>format</em>.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">datetime(*(time.strptime(date_string,</span>
<span class="pre">format)[0:6]))</span></code>. <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised if the date_string and format
can’t be parsed by <a class="reference internal" href="time.html#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strptime()</span></code></a> or if it returns a value which isn’t a
time tuple. For a complete list of formatting directives, see section
<a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>Class attributes:</p>
<dl class="attribute">
<dt id="datetime.datetime.min">
<code class="descclassname">datetime.</code><code class="descname">min</code><a class="headerlink" href="#datetime.datetime.min" title="Permalink to this definition">¶</a></dt>
<dd><p>The earliest representable <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>, <code class="docutils literal notranslate"><span class="pre">datetime(MINYEAR,</span> <span class="pre">1,</span> <span class="pre">1,</span>
<span class="pre">tzinfo=None)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.max">
<code class="descclassname">datetime.</code><code class="descname">max</code><a class="headerlink" href="#datetime.datetime.max" title="Permalink to this definition">¶</a></dt>
<dd><p>The latest representable <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>, <code class="docutils literal notranslate"><span class="pre">datetime(MAXYEAR,</span> <span class="pre">12,</span> <span class="pre">31,</span> <span class="pre">23,</span> <span class="pre">59,</span>
<span class="pre">59,</span> <span class="pre">999999,</span> <span class="pre">tzinfo=None)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.resolution">
<code class="descclassname">datetime.</code><code class="descname">resolution</code><a class="headerlink" href="#datetime.datetime.resolution" title="Permalink to this definition">¶</a></dt>
<dd><p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects,
<code class="docutils literal notranslate"><span class="pre">timedelta(microseconds=1)</span></code>.</p>
</dd></dl>

<p>Instance attributes (read-only):</p>
<dl class="attribute">
<dt id="datetime.datetime.year">
<code class="descclassname">datetime.</code><code class="descname">year</code><a class="headerlink" href="#datetime.datetime.year" title="Permalink to this definition">¶</a></dt>
<dd><p>Between <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a> and <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a> inclusive.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.month">
<code class="descclassname">datetime.</code><code class="descname">month</code><a class="headerlink" href="#datetime.datetime.month" title="Permalink to this definition">¶</a></dt>
<dd><p>Between 1 and 12 inclusive.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.day">
<code class="descclassname">datetime.</code><code class="descname">day</code><a class="headerlink" href="#datetime.datetime.day" title="Permalink to this definition">¶</a></dt>
<dd><p>Between 1 and the number of days in the given month of the given year.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.hour">
<code class="descclassname">datetime.</code><code class="descname">hour</code><a class="headerlink" href="#datetime.datetime.hour" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(24)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.minute">
<code class="descclassname">datetime.</code><code class="descname">minute</code><a class="headerlink" href="#datetime.datetime.minute" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(60)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.second">
<code class="descclassname">datetime.</code><code class="descname">second</code><a class="headerlink" href="#datetime.datetime.second" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(60)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.microsecond">
<code class="descclassname">datetime.</code><code class="descname">microsecond</code><a class="headerlink" href="#datetime.datetime.microsecond" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(1000000)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.datetime.tzinfo">
<code class="descclassname">datetime.</code><code class="descname">tzinfo</code><a class="headerlink" href="#datetime.datetime.tzinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>The object passed as the <em>tzinfo</em> argument to the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> constructor,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if none was passed.</p>
</dd></dl>

<p>Supported operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="55%" />
<col width="45%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">datetime2</span> <span class="pre">=</span> <span class="pre">datetime1</span> <span class="pre">+</span> <span class="pre">timedelta</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">datetime2</span> <span class="pre">=</span> <span class="pre">datetime1</span> <span class="pre">-</span> <span class="pre">timedelta</span></code></td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">timedelta</span> <span class="pre">=</span> <span class="pre">datetime1</span> <span class="pre">-</span> <span class="pre">datetime2</span></code></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">datetime1</span> <span class="pre">&lt;</span> <span class="pre">datetime2</span></code></td>
<td>Compares <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> to
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>. (4)</td>
</tr>
</tbody>
</table>
<ol class="arabic">
<li><p class="first">datetime2 is a duration of timedelta removed from datetime1, moving forward in
time if <code class="docutils literal notranslate"><span class="pre">timedelta.days</span></code> &gt; 0, or backward if <code class="docutils literal notranslate"><span class="pre">timedelta.days</span></code> &lt; 0.  The
result has the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute as the input datetime, and
datetime2 - datetime1 == timedelta after. <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised if
datetime2.year would be smaller than <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a> or larger than
<a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a>. Note that no time zone adjustments are done even if the
input is an aware object.</p>
</li>
<li><p class="first">Computes the datetime2 such that datetime2 + timedelta == datetime1. As for
addition, the result has the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute as the input
datetime, and no time zone adjustments are done even if the input is aware.
This isn’t quite equivalent to datetime1 + (-timedelta), because -timedelta
in isolation can overflow in cases where datetime1 - timedelta does not.</p>
</li>
<li><p class="first">Subtraction of a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> from a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> is defined only if
both operands are naive, or if both are aware.  If one is aware and the other is
naive, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>If both are naive, or both are aware and have the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute,
the <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attributes are ignored, and the result is a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a>
object <em>t</em> such that <code class="docutils literal notranslate"><span class="pre">datetime2</span> <span class="pre">+</span> <span class="pre">t</span> <span class="pre">==</span> <span class="pre">datetime1</span></code>.  No time zone adjustments
are done in this case.</p>
<p>If both are aware and have different <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attributes, <code class="docutils literal notranslate"><span class="pre">a-b</span></code> acts
as if <em>a</em> and <em>b</em> were first converted to naive UTC datetimes first.  The
result is <code class="docutils literal notranslate"><span class="pre">(a.replace(tzinfo=None)</span> <span class="pre">-</span> <span class="pre">a.utcoffset())</span> <span class="pre">-</span> <span class="pre">(b.replace(tzinfo=None)</span>
<span class="pre">-</span> <span class="pre">b.utcoffset())</span></code> except that the implementation never overflows.</p>
</li>
<li><p class="first"><em>datetime1</em> is considered less than <em>datetime2</em> when <em>datetime1</em> precedes
<em>datetime2</em> in time.</p>
<p>If one comparand is naive and the other is aware, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.
If both comparands are aware, and have the same <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute, the
common <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute is ignored and the base datetimes are
compared.  If both comparands are aware and have different <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
attributes, the comparands are first adjusted by subtracting their UTC
offsets (obtained from <code class="docutils literal notranslate"><span class="pre">self.utcoffset()</span></code>).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In order to stop comparison from falling back to the default scheme of comparing
object addresses, datetime comparison normally raises <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the
other comparand isn’t also a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object.  However,
<code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> is returned instead if the other comparand has a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">timetuple()</span></code> attribute.  This hook gives other kinds of date objects a
chance at implementing mixed-type comparison.  If not, when a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>
object is compared to an object of a different type, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised
unless the comparison is <code class="docutils literal notranslate"><span class="pre">==</span></code> or <code class="docutils literal notranslate"><span class="pre">!=</span></code>.  The latter cases return
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> or <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, respectively.</p>
</div>
</li>
</ol>
<p><a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects can be used as dictionary keys. In Boolean contexts,
all <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects are considered to be true.</p>
<p>Instance methods:</p>
<dl class="method">
<dt id="datetime.datetime.date">
<code class="descclassname">datetime.</code><code class="descname">date</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.date" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> object with same year, month and day.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.time">
<code class="descclassname">datetime.</code><code class="descname">time</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.time" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object with same hour, minute, second and microsecond.
<a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.  See also method <a class="reference internal" href="#datetime.datetime.timetz" title="datetime.datetime.timetz"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timetz()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.timetz">
<code class="descclassname">datetime.</code><code class="descname">timetz</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.timetz" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object with same hour, minute, second, microsecond, and
tzinfo attributes.  See also method <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-meth docutils literal notranslate"><span class="pre">time()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.replace">
<code class="descclassname">datetime.</code><code class="descname">replace</code><span class="sig-paren">(</span><span class="optional">[</span><em>year</em><span class="optional">[</span>, <em>month</em><span class="optional">[</span>, <em>day</em><span class="optional">[</span>, <em>hour</em><span class="optional">[</span>, <em>minute</em><span class="optional">[</span>, <em>second</em><span class="optional">[</span>, <em>microsecond</em><span class="optional">[</span>, <em>tzinfo</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a datetime with the same attributes, except for those attributes given
new values by whichever keyword arguments are specified.  Note that
<code class="docutils literal notranslate"><span class="pre">tzinfo=None</span></code> can be specified to create a naive datetime from an aware
datetime with no conversion of date and time data.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.astimezone">
<code class="descclassname">datetime.</code><code class="descname">astimezone</code><span class="sig-paren">(</span><em>tz</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.astimezone" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object with new <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute <em>tz</em>,
adjusting the date and time data so the result is the same UTC time as
<em>self</em>, but in <em>tz</em>’s local time.</p>
<p><em>tz</em> must be an instance of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass, and its
<a class="reference internal" href="#datetime.datetime.utcoffset" title="datetime.datetime.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> and <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> methods must not return <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <em>self</em> must
be aware (<code class="docutils literal notranslate"><span class="pre">self.tzinfo</span></code> must not be <code class="docutils literal notranslate"><span class="pre">None</span></code>, and <code class="docutils literal notranslate"><span class="pre">self.utcoffset()</span></code> must
not return <code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
<p>If <code class="docutils literal notranslate"><span class="pre">self.tzinfo</span></code> is <em>tz</em>, <code class="docutils literal notranslate"><span class="pre">self.astimezone(tz)</span></code> is equal to <em>self</em>:  no
adjustment of date or time data is performed. Else the result is local
time in time zone <em>tz</em>, representing the same UTC time as <em>self</em>:  after
<code class="docutils literal notranslate"><span class="pre">astz</span> <span class="pre">=</span> <span class="pre">dt.astimezone(tz)</span></code>, <code class="docutils literal notranslate"><span class="pre">astz</span> <span class="pre">-</span> <span class="pre">astz.utcoffset()</span></code> will usually have
the same date and time data as <code class="docutils literal notranslate"><span class="pre">dt</span> <span class="pre">-</span> <span class="pre">dt.utcoffset()</span></code>. The discussion
of class <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> explains the cases at Daylight Saving Time transition
boundaries where this cannot be achieved (an issue only if <em>tz</em> models both
standard and daylight time).</p>
<p>If you merely want to attach a time zone object <em>tz</em> to a datetime <em>dt</em> without
adjustment of date and time data, use <code class="docutils literal notranslate"><span class="pre">dt.replace(tzinfo=tz)</span></code>.  If you
merely want to remove the time zone object from an aware datetime <em>dt</em> without
conversion of date and time data, use <code class="docutils literal notranslate"><span class="pre">dt.replace(tzinfo=None)</span></code>.</p>
<p>Note that the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tzinfo.fromutc()</span></code></a> method can be overridden in a
<a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass to affect the result returned by <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code></a>.
Ignoring error cases, <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code></a> acts like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">astimezone</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tz</span><span class="p">):</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">tzinfo</span> <span class="ow">is</span> <span class="n">tz</span><span class="p">:</span>
        <span class="k">return</span> <span class="bp">self</span>
    <span class="c1"># Convert self to UTC, and attach the new time zone object.</span>
    <span class="n">utc</span> <span class="o">=</span> <span class="p">(</span><span class="bp">self</span> <span class="o">-</span> <span class="bp">self</span><span class="o">.</span><span class="n">utcoffset</span><span class="p">())</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="n">tz</span><span class="p">)</span>
    <span class="c1"># Convert from UTC to tz&#39;s local time.</span>
    <span class="k">return</span> <span class="n">tz</span><span class="o">.</span><span class="n">fromutc</span><span class="p">(</span><span class="n">utc</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.utcoffset">
<code class="descclassname">datetime.</code><code class="descname">utcoffset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.utcoffset" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.utcoffset(self)</span></code>, and raises an exception if the latter doesn’t
return <code class="docutils literal notranslate"><span class="pre">None</span></code>, or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object representing a whole number of
minutes with magnitude less than one day.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.dst">
<code class="descclassname">datetime.</code><code class="descname">dst</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.dst" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.dst(self)</span></code>, and raises an exception if the latter doesn’t return
<code class="docutils literal notranslate"><span class="pre">None</span></code>, or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object representing a whole number of minutes
with magnitude less than one day.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.tzname">
<code class="descclassname">datetime.</code><code class="descname">tzname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.tzname" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.tzname(self)</span></code>, raises an exception if the latter doesn’t return
<code class="docutils literal notranslate"><span class="pre">None</span></code> or a string object,</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.timetuple">
<code class="descclassname">datetime.</code><code class="descname">timetuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.timetuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> such as returned by <a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a>.
<code class="docutils literal notranslate"><span class="pre">d.timetuple()</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">time.struct_time((d.year,</span> <span class="pre">d.month,</span> <span class="pre">d.day,</span>
<span class="pre">d.hour,</span> <span class="pre">d.minute,</span> <span class="pre">d.second,</span> <span class="pre">d.weekday(),</span> <span class="pre">yday,</span> <span class="pre">dst))</span></code>, where <code class="docutils literal notranslate"><span class="pre">yday</span> <span class="pre">=</span>
<span class="pre">d.toordinal()</span> <span class="pre">-</span> <span class="pre">date(d.year,</span> <span class="pre">1,</span> <span class="pre">1).toordinal()</span> <span class="pre">+</span> <span class="pre">1</span></code> is the day number within
the current year starting with <code class="docutils literal notranslate"><span class="pre">1</span></code> for January 1st. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> flag
of the result is set according to the <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> method: <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is
<code class="docutils literal notranslate"><span class="pre">None</span></code> or <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> is set to <code class="docutils literal notranslate"><span class="pre">-1</span></code>;
else if <a class="reference internal" href="#datetime.datetime.dst" title="datetime.datetime.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> returns a non-zero value, <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> is set to <code class="docutils literal notranslate"><span class="pre">1</span></code>;
else <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> is set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.utctimetuple">
<code class="descclassname">datetime.</code><code class="descname">utctimetuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.utctimetuple" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instance <em>d</em> is naive, this is the same as
<code class="docutils literal notranslate"><span class="pre">d.timetuple()</span></code> except that <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> is forced to 0 regardless of what
<code class="docutils literal notranslate"><span class="pre">d.dst()</span></code> returns.  DST is never in effect for a UTC time.</p>
<p>If <em>d</em> is aware, <em>d</em> is normalized to UTC time, by subtracting
<code class="docutils literal notranslate"><span class="pre">d.utcoffset()</span></code>, and a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> for the normalized time is
returned.  <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> is forced to 0. Note that the result’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_year</span></code> member may be <a class="reference internal" href="#datetime.MINYEAR" title="datetime.MINYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MINYEAR</span></code></a>-1 or <a class="reference internal" href="#datetime.MAXYEAR" title="datetime.MAXYEAR"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXYEAR</span></code></a>+1, if
<em>d</em>.year was <code class="docutils literal notranslate"><span class="pre">MINYEAR</span></code> or <code class="docutils literal notranslate"><span class="pre">MAXYEAR</span></code> and UTC adjustment spills over a year
boundary.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.toordinal">
<code class="descclassname">datetime.</code><code class="descname">toordinal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.toordinal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the proleptic Gregorian ordinal of the date.  The same as
<code class="docutils literal notranslate"><span class="pre">self.date().toordinal()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.weekday">
<code class="descclassname">datetime.</code><code class="descname">weekday</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.weekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
The same as <code class="docutils literal notranslate"><span class="pre">self.date().weekday()</span></code>. See also <a class="reference internal" href="#datetime.datetime.isoweekday" title="datetime.datetime.isoweekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isoweekday()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.isoweekday">
<code class="descclassname">datetime.</code><code class="descname">isoweekday</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.isoweekday" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the day of the week as an integer, where Monday is 1 and Sunday is 7.
The same as <code class="docutils literal notranslate"><span class="pre">self.date().isoweekday()</span></code>. See also <a class="reference internal" href="#datetime.datetime.weekday" title="datetime.datetime.weekday"><code class="xref py py-meth docutils literal notranslate"><span class="pre">weekday()</span></code></a>,
<a class="reference internal" href="#datetime.datetime.isocalendar" title="datetime.datetime.isocalendar"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isocalendar()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.isocalendar">
<code class="descclassname">datetime.</code><code class="descname">isocalendar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.isocalendar" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a 3-tuple, (ISO year, ISO week number, ISO weekday).  The same as
<code class="docutils literal notranslate"><span class="pre">self.date().isocalendar()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.isoformat">
<code class="descclassname">datetime.</code><code class="descname">isoformat</code><span class="sig-paren">(</span><span class="optional">[</span><em>sep</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.isoformat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date and time in ISO 8601 format,
YYYY-MM-DDTHH:MM:SS.mmmmmm or, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code class="xref py py-attr docutils literal notranslate"><span class="pre">microsecond</span></code></a> is 0,
YYYY-MM-DDTHH:MM:SS</p>
<p>If <a class="reference internal" href="#datetime.datetime.utcoffset" title="datetime.datetime.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> does not return <code class="docutils literal notranslate"><span class="pre">None</span></code>, a 6-character string is
appended, giving the UTC offset in (signed) hours and minutes:
YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if <a class="reference internal" href="#datetime.datetime.microsecond" title="datetime.datetime.microsecond"><code class="xref py py-attr docutils literal notranslate"><span class="pre">microsecond</span></code></a> is 0
YYYY-MM-DDTHH:MM:SS+HH:MM</p>
<p>The optional argument <em>sep</em> (default <code class="docutils literal notranslate"><span class="pre">'T'</span></code>) is a one-character separator,
placed between the date and time portions of the result.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">tzinfo</span><span class="p">,</span> <span class="n">timedelta</span><span class="p">,</span> <span class="n">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">TZ</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span> <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">minutes</span><span class="o">=-</span><span class="mi">399</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">datetime</span><span class="p">(</span><span class="mi">2002</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="n">TZ</span><span class="p">())</span><span class="o">.</span><span class="n">isoformat</span><span class="p">(</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
<span class="go">&#39;2002-12-25 00:00:00-06:39&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.__str__">
<code class="descclassname">datetime.</code><code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>For a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instance <em>d</em>, <code class="docutils literal notranslate"><span class="pre">str(d)</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">d.isoformat('</span> <span class="pre">')</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.ctime">
<code class="descclassname">datetime.</code><code class="descname">ctime</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.ctime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date and time, for example <code class="docutils literal notranslate"><span class="pre">datetime(2002,</span> <span class="pre">12,</span>
<span class="pre">4,</span> <span class="pre">20,</span> <span class="pre">30,</span> <span class="pre">40).ctime()</span> <span class="pre">==</span> <span class="pre">'Wed</span> <span class="pre">Dec</span>&#160; <span class="pre">4</span> <span class="pre">20:30:40</span> <span class="pre">2002'</span></code>. <code class="docutils literal notranslate"><span class="pre">d.ctime()</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">time.ctime(time.mktime(d.timetuple()))</span></code> on platforms where the
native C <code class="xref c c-func docutils literal notranslate"><span class="pre">ctime()</span></code> function (which <a class="reference internal" href="time.html#time.ctime" title="time.ctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.ctime()</span></code></a> invokes, but which
<a class="reference internal" href="#datetime.datetime.ctime" title="datetime.datetime.ctime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.ctime()</span></code></a> does not invoke) conforms to the C standard.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.strftime">
<code class="descclassname">datetime.</code><code class="descname">strftime</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.strftime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the date and time, controlled by an explicit format
string.  For a complete list of formatting directives, see section
<a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.datetime.__format__">
<code class="descclassname">datetime.</code><code class="descname">__format__</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.datetime.__format__" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#datetime.datetime.strftime" title="datetime.datetime.strftime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.strftime()</span></code></a>.  This makes it possible to specify a format
string for a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object when using <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.
See section <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<p>Examples of working with datetime objects:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span><span class="p">,</span> <span class="n">date</span><span class="p">,</span> <span class="n">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Using datetime.combine()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="mi">2005</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">14</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">datetime</span><span class="o">.</span><span class="n">combine</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
<span class="go">datetime.datetime(2005, 7, 14, 12, 30)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Using datetime.now() or datetime.utcnow()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>   
<span class="go">datetime.datetime(2007, 12, 6, 16, 29, 43, 79043)   # GMT +1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">datetime</span><span class="o">.</span><span class="n">utcnow</span><span class="p">()</span>   
<span class="go">datetime.datetime(2007, 12, 6, 15, 29, 43, 79060)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Using datetime.strptime()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="s2">&quot;21/11/06 16:30&quot;</span><span class="p">,</span> <span class="s2">&quot;</span><span class="si">%d</span><span class="s2">/%m/%y %H:%M&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt</span>
<span class="go">datetime.datetime(2006, 11, 21, 16, 30)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Using datetime.timetuple() to get tuple of all attributes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tt</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">timetuple</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">tt</span><span class="p">:</span>   
<span class="gp">... </span>    <span class="k">print</span> <span class="n">it</span>
<span class="gp">...</span>
<span class="go">2006    # year</span>
<span class="go">11      # month</span>
<span class="go">21      # day</span>
<span class="go">16      # hour</span>
<span class="go">30      # minute</span>
<span class="go">0       # second</span>
<span class="go">1       # weekday (0 = Monday)</span>
<span class="go">325     # number of days since 1st January</span>
<span class="go">-1      # dst - method tzinfo.dst() returned None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Date in ISO format</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ic</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">isocalendar</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">ic</span><span class="p">:</span>   
<span class="gp">... </span>    <span class="k">print</span> <span class="n">it</span>
<span class="gp">...</span>
<span class="go">2006    # ISO year</span>
<span class="go">47      # ISO week</span>
<span class="go">2       # ISO weekday</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Formatting datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%A, </span><span class="si">%d</span><span class="s2">. %B %Y %I:%M%p&quot;</span><span class="p">)</span>
<span class="go">&#39;Tuesday, 21. November 2006 04:30PM&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;The {1} is {0:</span><span class="si">%d</span><span class="s1">}, the {2} is {0:%B}, the {3} is {0:%I:%M%p}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">dt</span><span class="p">,</span> <span class="s2">&quot;day&quot;</span><span class="p">,</span> <span class="s2">&quot;month&quot;</span><span class="p">,</span> <span class="s2">&quot;time&quot;</span><span class="p">)</span>
<span class="go">&#39;The day is 21, the month is November, the time is 04:30PM.&#39;</span>
</pre></div>
</div>
<p>Using datetime with tzinfo:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">timedelta</span><span class="p">,</span> <span class="n">datetime</span><span class="p">,</span> <span class="n">tzinfo</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">GMT1</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">dst</span><span class="p">(</span><span class="n">dt</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="c1"># DST starts last Sunday in March</span>
<span class="gp">... </span>        <span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>   <span class="c1"># ends last Sunday in October</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">dston</span> <span class="o">=</span> <span class="n">d</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="n">d</span><span class="o">.</span><span class="n">weekday</span><span class="p">()</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">dstoff</span> <span class="o">=</span> <span class="n">d</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="n">d</span><span class="o">.</span><span class="n">weekday</span><span class="p">()</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">dston</span> <span class="o">&lt;=</span>  <span class="n">dt</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="o">&lt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">dstoff</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>         <span class="k">return</span> <span class="s2">&quot;GMT +1&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">GMT2</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">dst</span><span class="p">(</span><span class="n">dt</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">dston</span> <span class="o">=</span> <span class="n">d</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="n">d</span><span class="o">.</span><span class="n">weekday</span><span class="p">()</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">dstoff</span> <span class="o">=</span> <span class="n">d</span> <span class="o">-</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days</span><span class="o">=</span><span class="n">d</span><span class="o">.</span><span class="n">weekday</span><span class="p">()</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">dston</span> <span class="o">&lt;=</span>  <span class="n">dt</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="o">&lt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">dstoff</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s2">&quot;GMT +2&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gmt1</span> <span class="o">=</span> <span class="n">GMT1</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Daylight Saving Time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt1</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">2006</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="n">gmt1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt1</span><span class="o">.</span><span class="n">dst</span><span class="p">()</span>
<span class="go">datetime.timedelta(0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt1</span><span class="o">.</span><span class="n">utcoffset</span><span class="p">()</span>
<span class="go">datetime.timedelta(0, 3600)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt2</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">2006</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">13</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="n">gmt1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt2</span><span class="o">.</span><span class="n">dst</span><span class="p">()</span>
<span class="go">datetime.timedelta(0, 3600)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt2</span><span class="o">.</span><span class="n">utcoffset</span><span class="p">()</span>
<span class="go">datetime.timedelta(0, 7200)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Convert datetime to another time zone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt3</span> <span class="o">=</span> <span class="n">dt2</span><span class="o">.</span><span class="n">astimezone</span><span class="p">(</span><span class="n">GMT2</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt3</span>     
<span class="go">datetime.datetime(2006, 6, 14, 14, 0, tzinfo=&lt;GMT2 object at 0x...&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt2</span>     
<span class="go">datetime.datetime(2006, 6, 14, 13, 0, tzinfo=&lt;GMT1 object at 0x...&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dt2</span><span class="o">.</span><span class="n">utctimetuple</span><span class="p">()</span> <span class="o">==</span> <span class="n">dt3</span><span class="o">.</span><span class="n">utctimetuple</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
<div class="section" id="time-objects">
<span id="datetime-time"></span><h2>8.1.5. <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> Objects<a class="headerlink" href="#time-objects" title="Permalink to this headline">¶</a></h2>
<p>A time object represents a (local) time of day, independent of any particular
day, and subject to adjustment via a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> object.</p>
<dl class="class">
<dt id="datetime.time">
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">time</code><span class="sig-paren">(</span><span class="optional">[</span><em>hour</em><span class="optional">[</span>, <em>minute</em><span class="optional">[</span>, <em>second</em><span class="optional">[</span>, <em>microsecond</em><span class="optional">[</span>, <em>tzinfo</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time" title="Permalink to this definition">¶</a></dt>
<dd><p>All arguments are optional.  <em>tzinfo</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code>, or an instance of a
<a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass.  The remaining arguments may be ints or longs, in the
following ranges:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">hour</span> <span class="pre">&lt;</span> <span class="pre">24</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">minute</span> <span class="pre">&lt;</span> <span class="pre">60</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">second</span> <span class="pre">&lt;</span> <span class="pre">60</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">microsecond</span> <span class="pre">&lt;</span> <span class="pre">1000000</span></code>.</li>
</ul>
<p>If an argument outside those ranges is given, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  All
default to <code class="docutils literal notranslate"><span class="pre">0</span></code> except <em>tzinfo</em>, which defaults to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<p>Class attributes:</p>
<dl class="attribute">
<dt id="datetime.time.min">
<code class="descclassname">time.</code><code class="descname">min</code><a class="headerlink" href="#datetime.time.min" title="Permalink to this definition">¶</a></dt>
<dd><p>The earliest representable <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, <code class="docutils literal notranslate"><span class="pre">time(0,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">0)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.max">
<code class="descclassname">time.</code><code class="descname">max</code><a class="headerlink" href="#datetime.time.max" title="Permalink to this definition">¶</a></dt>
<dd><p>The latest representable <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, <code class="docutils literal notranslate"><span class="pre">time(23,</span> <span class="pre">59,</span> <span class="pre">59,</span> <span class="pre">999999)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.resolution">
<code class="descclassname">time.</code><code class="descname">resolution</code><a class="headerlink" href="#datetime.time.resolution" title="Permalink to this definition">¶</a></dt>
<dd><p>The smallest possible difference between non-equal <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> objects,
<code class="docutils literal notranslate"><span class="pre">timedelta(microseconds=1)</span></code>, although note that arithmetic on
<a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> objects is not supported.</p>
</dd></dl>

<p>Instance attributes (read-only):</p>
<dl class="attribute">
<dt id="datetime.time.hour">
<code class="descclassname">time.</code><code class="descname">hour</code><a class="headerlink" href="#datetime.time.hour" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(24)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.minute">
<code class="descclassname">time.</code><code class="descname">minute</code><a class="headerlink" href="#datetime.time.minute" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(60)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.second">
<code class="descclassname">time.</code><code class="descname">second</code><a class="headerlink" href="#datetime.time.second" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(60)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.microsecond">
<code class="descclassname">time.</code><code class="descname">microsecond</code><a class="headerlink" href="#datetime.time.microsecond" title="Permalink to this definition">¶</a></dt>
<dd><p>In <code class="docutils literal notranslate"><span class="pre">range(1000000)</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="datetime.time.tzinfo">
<code class="descclassname">time.</code><code class="descname">tzinfo</code><a class="headerlink" href="#datetime.time.tzinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>The object passed as the tzinfo argument to the <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> constructor, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if none was passed.</p>
</dd></dl>

<p>Supported operations:</p>
<ul class="simple">
<li>comparison of <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> to <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, where <em>a</em> is considered less
than <em>b</em> when <em>a</em> precedes <em>b</em> in time.  If one comparand is naive and the other
is aware, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.  If both comparands are aware, and have
the same <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute, the common <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attribute is
ignored and the base times are compared.  If both comparands are aware and
have different <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> attributes, the comparands are first adjusted by
subtracting their UTC offsets (obtained from <code class="docutils literal notranslate"><span class="pre">self.utcoffset()</span></code>). In order
to stop mixed-type comparisons from falling back to the default comparison by
object address, when a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object is compared to an object of a
different type, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised unless the comparison is <code class="docutils literal notranslate"><span class="pre">==</span></code> or
<code class="docutils literal notranslate"><span class="pre">!=</span></code>.  The latter cases return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> or <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, respectively.</li>
<li>hash, use as dict key</li>
<li>efficient pickling</li>
<li>in Boolean contexts, a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object is considered to be true if and
only if, after converting it to minutes and subtracting <code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code> (or
<code class="docutils literal notranslate"><span class="pre">0</span></code> if that’s <code class="docutils literal notranslate"><span class="pre">None</span></code>), the result is non-zero.</li>
</ul>
<p>Instance methods:</p>
<dl class="method">
<dt id="datetime.time.replace">
<code class="descclassname">time.</code><code class="descname">replace</code><span class="sig-paren">(</span><span class="optional">[</span><em>hour</em><span class="optional">[</span>, <em>minute</em><span class="optional">[</span>, <em>second</em><span class="optional">[</span>, <em>microsecond</em><span class="optional">[</span>, <em>tzinfo</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> with the same value, except for those attributes given
new values by whichever keyword arguments are specified.  Note that
<code class="docutils literal notranslate"><span class="pre">tzinfo=None</span></code> can be specified to create a naive <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> from an
aware <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, without conversion of the time data.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.isoformat">
<code class="descclassname">time.</code><code class="descname">isoformat</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.isoformat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm or, if
self.microsecond is 0, HH:MM:SS If <a class="reference internal" href="#datetime.time.utcoffset" title="datetime.time.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> does not return <code class="docutils literal notranslate"><span class="pre">None</span></code>, a
6-character string is appended, giving the UTC offset in (signed) hours and
minutes: HH:MM:SS.mmmmmm+HH:MM or, if self.microsecond is 0, HH:MM:SS+HH:MM</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.__str__">
<code class="descclassname">time.</code><code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>For a time <em>t</em>, <code class="docutils literal notranslate"><span class="pre">str(t)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">t.isoformat()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.strftime">
<code class="descclassname">time.</code><code class="descname">strftime</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.strftime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the time, controlled by an explicit format string.
For a complete list of formatting directives, see section
<a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.__format__">
<code class="descclassname">time.</code><code class="descname">__format__</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.__format__" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#datetime.time.strftime" title="datetime.time.strftime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>. This makes it possible to specify a format string
for a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object when using <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.
See section <a class="reference internal" href="#strftime-strptime-behavior"><span class="std std-ref">strftime() and strptime() Behavior</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.utcoffset">
<code class="descclassname">time.</code><code class="descname">utcoffset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.utcoffset" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.utcoffset(None)</span></code>, and raises an exception if the latter doesn’t
return <code class="docutils literal notranslate"><span class="pre">None</span></code> or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object representing a whole number of
minutes with magnitude less than one day.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.dst">
<code class="descclassname">time.</code><code class="descname">dst</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.dst" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.dst(None)</span></code>, and raises an exception if the latter doesn’t return
<code class="docutils literal notranslate"><span class="pre">None</span></code>, or a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object representing a whole number of minutes
with magnitude less than one day.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.time.tzname">
<code class="descclassname">time.</code><code class="descname">tzname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#datetime.time.tzname" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#datetime.time.tzinfo" title="datetime.time.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, else returns
<code class="docutils literal notranslate"><span class="pre">self.tzinfo.tzname(None)</span></code>, or raises an exception if the latter doesn’t
return <code class="docutils literal notranslate"><span class="pre">None</span></code> or a string object.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">time</span><span class="p">,</span> <span class="n">tzinfo</span><span class="p">,</span> <span class="n">timedelta</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">GMT1</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">dt</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s2">&quot;Europe/Prague&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="p">(</span><span class="mi">12</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="n">tzinfo</span><span class="o">=</span><span class="n">GMT1</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>                               
<span class="go">datetime.time(12, 10, 30, tzinfo=&lt;GMT1 object at 0x...&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gmt</span> <span class="o">=</span> <span class="n">GMT1</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
<span class="go">&#39;12:10:30+01:00&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">dst</span><span class="p">()</span>
<span class="go">datetime.timedelta(0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">tzname</span><span class="p">()</span>
<span class="go">&#39;Europe/Prague&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%H:%M:%S %Z&quot;</span><span class="p">)</span>
<span class="go">&#39;12:10:30 Europe/Prague&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;The </span><span class="si">{}</span><span class="s1"> is {:%H:%M}.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;time&quot;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
<span class="go">&#39;The time is 12:10.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="tzinfo-objects">
<span id="datetime-tzinfo"></span><h2>8.1.6. <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> Objects<a class="headerlink" href="#tzinfo-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="datetime.tzinfo">
<em class="property">class </em><code class="descclassname">datetime.</code><code class="descname">tzinfo</code><a class="headerlink" href="#datetime.tzinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an abstract base class, meaning that this class should not be
instantiated directly.  You need to derive a concrete subclass, and (at least)
supply implementations of the standard <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> methods needed by the
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> methods you use.  The <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module does not supply
any concrete subclasses of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a>.</p>
<p>An instance of (a concrete subclass of) <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> can be passed to the
constructors for <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> and <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> objects. The latter objects
view their attributes as being in local time, and the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> object
supports methods revealing offset of local time from UTC, the name of the time
zone, and DST offset, all relative to a date or time object passed to them.</p>
<p>Special requirement for pickling:  A <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass must have an
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method that can be called with no arguments, else it can be
pickled but possibly not unpickled again.  This is a technical requirement that
may be relaxed in the future.</p>
<p>A concrete subclass of <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> may need to implement the following
methods.  Exactly which methods are needed depends on the uses made of aware
<a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> objects.  If in doubt, simply implement all of them.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.tzinfo.utcoffset">
<code class="descclassname">tzinfo.</code><code class="descname">utcoffset</code><span class="sig-paren">(</span><em>self</em>, <em>dt</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.tzinfo.utcoffset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return offset of local time from UTC, in minutes east of UTC.  If local time is
west of UTC, this should be negative.  Note that this is intended to be the
total offset from UTC; for example, if a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> object represents both
time zone and DST adjustments, <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> should return their sum.  If
the UTC offset isn’t known, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Else the value returned must be a
<a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object specifying a whole number of minutes in the range
-1439 to 1439 inclusive (1440 = 24*60; the magnitude of the offset must be less
than one day).  Most implementations of <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> will probably look
like one of these two:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">return</span> <span class="n">CONSTANT</span>                 <span class="c1"># fixed-offset class</span>
<span class="k">return</span> <span class="n">CONSTANT</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">dst</span><span class="p">(</span><span class="n">dt</span><span class="p">)</span>  <span class="c1"># daylight-aware class</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> does not return <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> should not return
<code class="docutils literal notranslate"><span class="pre">None</span></code> either.</p>
<p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> raises
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.tzinfo.dst">
<code class="descclassname">tzinfo.</code><code class="descname">dst</code><span class="sig-paren">(</span><em>self</em>, <em>dt</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.tzinfo.dst" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the daylight saving time (DST) adjustment, in minutes east of UTC, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if DST information isn’t known.  Return <code class="docutils literal notranslate"><span class="pre">timedelta(0)</span></code> if DST is not
in effect. If DST is in effect, return the offset as a <a class="reference internal" href="#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> object
(see <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a> for details). Note that DST offset, if applicable, has
already been added to the UTC offset returned by <a class="reference internal" href="#datetime.tzinfo.utcoffset" title="datetime.tzinfo.utcoffset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code></a>, so there’s
no need to consult <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> unless you’re interested in obtaining DST info
separately.  For example, <a class="reference internal" href="#datetime.datetime.timetuple" title="datetime.datetime.timetuple"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.timetuple()</span></code></a> calls its <a class="reference internal" href="#datetime.datetime.tzinfo" title="datetime.datetime.tzinfo"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
attribute’s <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> method to determine how the <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> flag
should be set, and <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tzinfo.fromutc()</span></code></a> calls <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> to account for
DST changes when crossing time zones.</p>
<p>An instance <em>tz</em> of a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass that models both standard and
daylight times must be consistent in this sense:</p>
<p><code class="docutils literal notranslate"><span class="pre">tz.utcoffset(dt)</span> <span class="pre">-</span> <span class="pre">tz.dst(dt)</span></code></p>
<p>must return the same result for every <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> <em>dt</em> with <code class="docutils literal notranslate"><span class="pre">dt.tzinfo</span> <span class="pre">==</span>
<span class="pre">tz</span></code>  For sane <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclasses, this expression yields the time
zone’s “standard offset”, which should not depend on the date or the time, but
only on geographic location.  The implementation of <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.astimezone()</span></code></a>
relies on this, but cannot detect violations; it’s the programmer’s
responsibility to ensure it.  If a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass cannot guarantee
this, it may be able to override the default implementation of
<a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tzinfo.fromutc()</span></code></a> to work correctly with <code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code> regardless.</p>
<p>Most implementations of <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> will probably look like one of these two:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
    <span class="c1"># a fixed-offset class:  doesn&#39;t account for DST</span>
    <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>or</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
    <span class="c1"># Code to set dston and dstoff to the time zone&#39;s DST</span>
    <span class="c1"># transition times based on the input dt.year, and expressed</span>
    <span class="c1"># in standard local time.  Then</span>

    <span class="k">if</span> <span class="n">dston</span> <span class="o">&lt;=</span> <span class="n">dt</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">dstoff</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dst()</span></code></a> raises <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="datetime.tzinfo.tzname">
<code class="descclassname">tzinfo.</code><code class="descname">tzname</code><span class="sig-paren">(</span><em>self</em>, <em>dt</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.tzinfo.tzname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the time zone name corresponding to the <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object <em>dt</em>, as
a string. Nothing about string names is defined by the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module,
and there’s no requirement that it mean anything in particular.  For example,
“GMT”, “UTC”, “-500”, “-5:00”, “EDT”, “US/Eastern”, “America/New York” are all
valid replies.  Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if a string name isn’t known.  Note that this is
a method rather than a fixed string primarily because some <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
subclasses will wish to return different names depending on the specific value
of <em>dt</em> passed, especially if the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> class is accounting for
daylight time.</p>
<p>The default implementation of <a class="reference internal" href="#datetime.tzinfo.tzname" title="datetime.tzinfo.tzname"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tzname()</span></code></a> raises <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.</p>
</dd></dl>

<p>These methods are called by a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> or <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object, in
response to their methods of the same names.  A <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object passes
itself as the argument, and a <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> object passes <code class="docutils literal notranslate"><span class="pre">None</span></code> as the
argument.  A <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass’s methods should therefore be prepared to
accept a <em>dt</em> argument of <code class="docutils literal notranslate"><span class="pre">None</span></code>, or of class <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>.</p>
<p>When <code class="docutils literal notranslate"><span class="pre">None</span></code> is passed, it’s up to the class designer to decide the best
response.  For example, returning <code class="docutils literal notranslate"><span class="pre">None</span></code> is appropriate if the class wishes to
say that time objects don’t participate in the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> protocols.  It
may be more useful for <code class="docutils literal notranslate"><span class="pre">utcoffset(None)</span></code> to return the standard UTC offset, as
there is no other convention for discovering the standard offset.</p>
<p>When a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object is passed in response to a <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>
method, <code class="docutils literal notranslate"><span class="pre">dt.tzinfo</span></code> is the same object as <em>self</em>.  <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> methods can
rely on this, unless user code calls <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> methods directly.  The
intent is that the <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> methods interpret <em>dt</em> as being in local
time, and not need worry about objects in other timezones.</p>
<p>There is one more <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> method that a subclass may wish to override:</p>
<dl class="method">
<dt id="datetime.tzinfo.fromutc">
<code class="descclassname">tzinfo.</code><code class="descname">fromutc</code><span class="sig-paren">(</span><em>self</em>, <em>dt</em><span class="sig-paren">)</span><a class="headerlink" href="#datetime.tzinfo.fromutc" title="Permalink to this definition">¶</a></dt>
<dd><p>This is called from the default <a class="reference internal" href="#datetime.datetime.astimezone" title="datetime.datetime.astimezone"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.astimezone()</span></code></a>
implementation.  When called from that, <code class="docutils literal notranslate"><span class="pre">dt.tzinfo</span></code> is <em>self</em>, and <em>dt</em>’s
date and time data are to be viewed as expressing a UTC time.  The purpose
of <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromutc()</span></code></a> is to adjust the date and time data, returning an
equivalent datetime in <em>self</em>’s local time.</p>
<p>Most <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclasses should be able to inherit the default
<a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromutc()</span></code></a> implementation without problems.  It’s strong enough to handle
fixed-offset time zones, and time zones accounting for both standard and
daylight time, and the latter even if the DST transition times differ in
different years.  An example of a time zone the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromutc()</span></code></a>
implementation may not handle correctly in all cases is one where the standard
offset (from UTC) depends on the specific date and time passed, which can happen
for political reasons. The default implementations of <code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code> and
<a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromutc()</span></code></a> may not produce the result you want if the result is one of the
hours straddling the moment the standard offset changes.</p>
<p>Skipping code for error cases, the default <a class="reference internal" href="#datetime.tzinfo.fromutc" title="datetime.tzinfo.fromutc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fromutc()</span></code></a> implementation acts
like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">fromutc</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
    <span class="c1"># raise ValueError error if dt.tzinfo is not self</span>
    <span class="n">dtoff</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">utcoffset</span><span class="p">()</span>
    <span class="n">dtdst</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">dst</span><span class="p">()</span>
    <span class="c1"># raise ValueError if dtoff is None or dtdst is None</span>
    <span class="n">delta</span> <span class="o">=</span> <span class="n">dtoff</span> <span class="o">-</span> <span class="n">dtdst</span>  <span class="c1"># this is self&#39;s standard offset</span>
    <span class="k">if</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">dt</span> <span class="o">+=</span> <span class="n">delta</span>   <span class="c1"># convert to standard local time</span>
        <span class="n">dtdst</span> <span class="o">=</span> <span class="n">dt</span><span class="o">.</span><span class="n">dst</span><span class="p">()</span>
        <span class="c1"># raise ValueError if dtdst is None</span>
    <span class="k">if</span> <span class="n">dtdst</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">dt</span> <span class="o">+</span> <span class="n">dtdst</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">dt</span>
</pre></div>
</div>
</dd></dl>

<p>Example <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> classes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">tzinfo</span><span class="p">,</span> <span class="n">timedelta</span><span class="p">,</span> <span class="n">datetime</span>

<span class="n">ZERO</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">HOUR</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="c1"># A UTC class.</span>

<span class="k">class</span> <span class="nc">UTC</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;UTC&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">ZERO</span>

    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="s2">&quot;UTC&quot;</span>

    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">ZERO</span>

<span class="n">utc</span> <span class="o">=</span> <span class="n">UTC</span><span class="p">()</span>

<span class="c1"># A class building tzinfo objects for fixed-offset time zones.</span>
<span class="c1"># Note that FixedOffset(0, &quot;UTC&quot;) is a different way to build a</span>
<span class="c1"># UTC tzinfo object.</span>

<span class="k">class</span> <span class="nc">FixedOffset</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Fixed offset in minutes east from UTC.&quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">offset</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__offset</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">minutes</span> <span class="o">=</span> <span class="n">offset</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__name</span> <span class="o">=</span> <span class="n">name</span>

    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__offset</span>

    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">__name</span>

    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">ZERO</span>

<span class="c1"># A class capturing the platform&#39;s idea of local time.</span>

<span class="kn">import</span> <span class="nn">time</span> <span class="k">as</span> <span class="nn">_time</span>

<span class="n">STDOFFSET</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span> <span class="o">=</span> <span class="o">-</span><span class="n">_time</span><span class="o">.</span><span class="n">timezone</span><span class="p">)</span>
<span class="k">if</span> <span class="n">_time</span><span class="o">.</span><span class="n">daylight</span><span class="p">:</span>
    <span class="n">DSTOFFSET</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">seconds</span> <span class="o">=</span> <span class="o">-</span><span class="n">_time</span><span class="o">.</span><span class="n">altzone</span><span class="p">)</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">DSTOFFSET</span> <span class="o">=</span> <span class="n">STDOFFSET</span>

<span class="n">DSTDIFF</span> <span class="o">=</span> <span class="n">DSTOFFSET</span> <span class="o">-</span> <span class="n">STDOFFSET</span>

<span class="k">class</span> <span class="nc">LocalTimezone</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_isdst</span><span class="p">(</span><span class="n">dt</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">DSTOFFSET</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">STDOFFSET</span>

    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">_isdst</span><span class="p">(</span><span class="n">dt</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">DSTDIFF</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">ZERO</span>

    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">_time</span><span class="o">.</span><span class="n">tzname</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">_isdst</span><span class="p">(</span><span class="n">dt</span><span class="p">)]</span>

    <span class="k">def</span> <span class="nf">_isdst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="n">tt</span> <span class="o">=</span> <span class="p">(</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">,</span> <span class="n">dt</span><span class="o">.</span><span class="n">month</span><span class="p">,</span> <span class="n">dt</span><span class="o">.</span><span class="n">day</span><span class="p">,</span>
              <span class="n">dt</span><span class="o">.</span><span class="n">hour</span><span class="p">,</span> <span class="n">dt</span><span class="o">.</span><span class="n">minute</span><span class="p">,</span> <span class="n">dt</span><span class="o">.</span><span class="n">second</span><span class="p">,</span>
              <span class="n">dt</span><span class="o">.</span><span class="n">weekday</span><span class="p">(),</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
        <span class="n">stamp</span> <span class="o">=</span> <span class="n">_time</span><span class="o">.</span><span class="n">mktime</span><span class="p">(</span><span class="n">tt</span><span class="p">)</span>
        <span class="n">tt</span> <span class="o">=</span> <span class="n">_time</span><span class="o">.</span><span class="n">localtime</span><span class="p">(</span><span class="n">stamp</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">tt</span><span class="o">.</span><span class="n">tm_isdst</span> <span class="o">&gt;</span> <span class="mi">0</span>

<span class="n">Local</span> <span class="o">=</span> <span class="n">LocalTimezone</span><span class="p">()</span>


<span class="c1"># A complete implementation of current DST rules for major US time zones.</span>

<span class="k">def</span> <span class="nf">first_sunday_on_or_after</span><span class="p">(</span><span class="n">dt</span><span class="p">):</span>
    <span class="n">days_to_go</span> <span class="o">=</span> <span class="mi">6</span> <span class="o">-</span> <span class="n">dt</span><span class="o">.</span><span class="n">weekday</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">days_to_go</span><span class="p">:</span>
        <span class="n">dt</span> <span class="o">+=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">days_to_go</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">dt</span>


<span class="c1"># US DST Rules</span>
<span class="c1">#</span>
<span class="c1"># This is a simplified (i.e., wrong for a few cases) set of rules for US</span>
<span class="c1"># DST start and end times. For a complete and up-to-date set of DST rules</span>
<span class="c1"># and timezone definitions, visit the Olson Database (or try pytz):</span>
<span class="c1"># http://www.twinsun.com/tz/tz-link.htm</span>
<span class="c1"># http://sourceforge.net/projects/pytz/ (might not be up-to-date)</span>
<span class="c1">#</span>
<span class="c1"># In the US, since 2007, DST starts at 2am (standard time) on the second</span>
<span class="c1"># Sunday in March, which is the first Sunday on or after Mar 8.</span>
<span class="n">DSTSTART_2007</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="c1"># and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov.</span>
<span class="n">DSTEND_2007</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="c1"># From 1987 to 2006, DST used to start at 2am (standard time) on the first</span>
<span class="c1"># Sunday in April and to end at 2am (DST time; 1am standard time) on the last</span>
<span class="c1"># Sunday of October, which is the first Sunday on or after Oct 25.</span>
<span class="n">DSTSTART_1987_2006</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="n">DSTEND_1987_2006</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="c1"># From 1967 to 1986, DST used to start at 2am (standard time) on the last</span>
<span class="c1"># Sunday in April (the one on or after April 24) and to end at 2am (DST time;</span>
<span class="c1"># 1am standard time) on the last Sunday of October, which is the first Sunday</span>
<span class="c1"># on or after Oct 25.</span>
<span class="n">DSTSTART_1967_1986</span> <span class="o">=</span> <span class="n">datetime</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">24</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="n">DSTEND_1967_1986</span> <span class="o">=</span> <span class="n">DSTEND_1987_2006</span>

<span class="k">class</span> <span class="nc">USTimeZone</span><span class="p">(</span><span class="n">tzinfo</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">hours</span><span class="p">,</span> <span class="n">reprname</span><span class="p">,</span> <span class="n">stdname</span><span class="p">,</span> <span class="n">dstname</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stdoffset</span> <span class="o">=</span> <span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="n">hours</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">reprname</span> <span class="o">=</span> <span class="n">reprname</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">stdname</span> <span class="o">=</span> <span class="n">stdname</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">dstname</span> <span class="o">=</span> <span class="n">dstname</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">reprname</span>

    <span class="k">def</span> <span class="nf">tzname</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">dst</span><span class="p">(</span><span class="n">dt</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">dstname</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">stdname</span>

    <span class="k">def</span> <span class="nf">utcoffset</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">stdoffset</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">dst</span><span class="p">(</span><span class="n">dt</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">dst</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">dt</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">dt</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="n">dt</span><span class="o">.</span><span class="n">tzinfo</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="c1"># An exception may be sensible here, in one or both cases.</span>
            <span class="c1"># It depends on how you want to treat them.  The default</span>
            <span class="c1"># fromutc() implementation (called by the default astimezone()</span>
            <span class="c1"># implementation) passes a datetime with dt.tzinfo is self.</span>
            <span class="k">return</span> <span class="n">ZERO</span>
        <span class="k">assert</span> <span class="n">dt</span><span class="o">.</span><span class="n">tzinfo</span> <span class="ow">is</span> <span class="bp">self</span>

        <span class="c1"># Find start and end times for US DST. For years before 1967, return</span>
        <span class="c1"># ZERO for no DST.</span>
        <span class="k">if</span> <span class="mi">2006</span> <span class="o">&lt;</span> <span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">:</span>
            <span class="n">dststart</span><span class="p">,</span> <span class="n">dstend</span> <span class="o">=</span> <span class="n">DSTSTART_2007</span><span class="p">,</span> <span class="n">DSTEND_2007</span>
        <span class="k">elif</span> <span class="mi">1986</span> <span class="o">&lt;</span> <span class="n">dt</span><span class="o">.</span><span class="n">year</span> <span class="o">&lt;</span> <span class="mi">2007</span><span class="p">:</span>
            <span class="n">dststart</span><span class="p">,</span> <span class="n">dstend</span> <span class="o">=</span> <span class="n">DSTSTART_1987_2006</span><span class="p">,</span> <span class="n">DSTEND_1987_2006</span>
        <span class="k">elif</span> <span class="mi">1966</span> <span class="o">&lt;</span> <span class="n">dt</span><span class="o">.</span><span class="n">year</span> <span class="o">&lt;</span> <span class="mi">1987</span><span class="p">:</span>
            <span class="n">dststart</span><span class="p">,</span> <span class="n">dstend</span> <span class="o">=</span> <span class="n">DSTSTART_1967_1986</span><span class="p">,</span> <span class="n">DSTEND_1967_1986</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">ZERO</span>

        <span class="n">start</span> <span class="o">=</span> <span class="n">first_sunday_on_or_after</span><span class="p">(</span><span class="n">dststart</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">))</span>
        <span class="n">end</span> <span class="o">=</span> <span class="n">first_sunday_on_or_after</span><span class="p">(</span><span class="n">dstend</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="n">dt</span><span class="o">.</span><span class="n">year</span><span class="p">))</span>

        <span class="c1"># Can&#39;t compare naive to aware objects, so strip the timezone from</span>
        <span class="c1"># dt first.</span>
        <span class="k">if</span> <span class="n">start</span> <span class="o">&lt;=</span> <span class="n">dt</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">tzinfo</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">end</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">HOUR</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="n">ZERO</span>

<span class="n">Eastern</span>  <span class="o">=</span> <span class="n">USTimeZone</span><span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="s2">&quot;Eastern&quot;</span><span class="p">,</span>  <span class="s2">&quot;EST&quot;</span><span class="p">,</span> <span class="s2">&quot;EDT&quot;</span><span class="p">)</span>
<span class="n">Central</span>  <span class="o">=</span> <span class="n">USTimeZone</span><span class="p">(</span><span class="o">-</span><span class="mi">6</span><span class="p">,</span> <span class="s2">&quot;Central&quot;</span><span class="p">,</span>  <span class="s2">&quot;CST&quot;</span><span class="p">,</span> <span class="s2">&quot;CDT&quot;</span><span class="p">)</span>
<span class="n">Mountain</span> <span class="o">=</span> <span class="n">USTimeZone</span><span class="p">(</span><span class="o">-</span><span class="mi">7</span><span class="p">,</span> <span class="s2">&quot;Mountain&quot;</span><span class="p">,</span> <span class="s2">&quot;MST&quot;</span><span class="p">,</span> <span class="s2">&quot;MDT&quot;</span><span class="p">)</span>
<span class="n">Pacific</span>  <span class="o">=</span> <span class="n">USTimeZone</span><span class="p">(</span><span class="o">-</span><span class="mi">8</span><span class="p">,</span> <span class="s2">&quot;Pacific&quot;</span><span class="p">,</span>  <span class="s2">&quot;PST&quot;</span><span class="p">,</span> <span class="s2">&quot;PDT&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that there are unavoidable subtleties twice per year in a <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a>
subclass accounting for both standard and daylight time, at the DST transition
points.  For concreteness, consider US Eastern (UTC -0500), where EDT begins the
minute after 1:59 (EST) on the second Sunday in March, and ends the minute after
1:59 (EDT) on the first Sunday in November:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>  <span class="n">UTC</span>   <span class="mi">3</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">4</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">5</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">6</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">7</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">8</span><span class="p">:</span><span class="n">MM</span>
  <span class="n">EST</span>  <span class="mi">22</span><span class="p">:</span><span class="n">MM</span> <span class="mi">23</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">0</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">1</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">2</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">3</span><span class="p">:</span><span class="n">MM</span>
  <span class="n">EDT</span>  <span class="mi">23</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">0</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">1</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">2</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">3</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">4</span><span class="p">:</span><span class="n">MM</span>

<span class="n">start</span>  <span class="mi">22</span><span class="p">:</span><span class="n">MM</span> <span class="mi">23</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">0</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">1</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">3</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">4</span><span class="p">:</span><span class="n">MM</span>

  <span class="n">end</span>  <span class="mi">23</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">0</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">1</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">1</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">2</span><span class="p">:</span><span class="n">MM</span>  <span class="mi">3</span><span class="p">:</span><span class="n">MM</span>
</pre></div>
</div>
<p>When DST starts (the “start” line), the local wall clock leaps from 1:59 to
3:00.  A wall time of the form 2:MM doesn’t really make sense on that day, so
<code class="docutils literal notranslate"><span class="pre">astimezone(Eastern)</span></code> won’t deliver a result with <code class="docutils literal notranslate"><span class="pre">hour</span> <span class="pre">==</span> <span class="pre">2</span></code> on the day DST
begins.  In order for <code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code> to make this guarantee, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">rzinfo.dst()</span></code> method must consider times in the “missing hour” (2:MM for
Eastern) to be in daylight time.</p>
<p>When DST ends (the “end” line), there’s a potentially worse problem: there’s an
hour that can’t be spelled unambiguously in local wall time: the last hour of
daylight time.  In Eastern, that’s times of the form 5:MM UTC on the day
daylight time ends.  The local wall clock leaps from 1:59 (daylight time) back
to 1:00 (standard time) again. Local times of the form 1:MM are ambiguous.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code> mimics the local clock’s behavior by mapping two adjacent UTC
hours into the same local hour then.  In the Eastern example, UTC times of the
form 5:MM and 6:MM both map to 1:MM when converted to Eastern.  In order for
<code class="xref py py-meth docutils literal notranslate"><span class="pre">astimezone()</span></code> to make this guarantee, the <a class="reference internal" href="#datetime.tzinfo.dst" title="datetime.tzinfo.dst"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tzinfo.dst()</span></code></a> method must
consider times in the “repeated hour” to be in standard time.  This is easily
arranged, as in the example, by expressing DST switch times in the time zone’s
standard local time.</p>
<p>Applications that can’t bear such ambiguities should avoid using hybrid
<a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclasses; there are no ambiguities when using UTC, or any
other fixed-offset <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> subclass (such as a class representing only
EST (fixed offset -5 hours), or only EDT (fixed offset -4 hours)).</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://pypi.org/project/pytz/">pytz</a></dt>
<dd><p class="first">The standard library has no <a class="reference internal" href="#datetime.tzinfo" title="datetime.tzinfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code></a> instances, but
there exists a third-party library which brings the <em>IANA timezone
database</em> (also known as the Olson database) to Python: <em>pytz</em>.</p>
<p class="last"><em>pytz</em> contains up-to-date information and its usage is recommended.</p>
</dd>
<dt><a class="reference external" href="https://www.iana.org/time-zones">IANA timezone database</a></dt>
<dd>The Time Zone Database (often called tz or zoneinfo) contains code and
data that represent the history of local time for many representative
locations around the globe. It is updated periodically to reflect changes
made by political bodies to time zone boundaries, UTC offsets, and
daylight-saving rules.</dd>
</dl>
</div>
</div>
<div class="section" id="strftime-and-strptime-behavior">
<span id="strftime-strptime-behavior"></span><h2>8.1.7. <code class="xref py py-meth docutils literal notranslate"><span class="pre">strftime()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">strptime()</span></code> Behavior<a class="headerlink" href="#strftime-and-strptime-behavior" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a>, <a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>, and <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> objects all support a
<code class="docutils literal notranslate"><span class="pre">strftime(format)</span></code> method, to create a string representing the time under the
control of an explicit format string.  Broadly speaking, <code class="docutils literal notranslate"><span class="pre">d.strftime(fmt)</span></code>
acts like the <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module’s <code class="docutils literal notranslate"><span class="pre">time.strftime(fmt,</span> <span class="pre">d.timetuple())</span></code>
although not all objects support a <code class="xref py py-meth docutils literal notranslate"><span class="pre">timetuple()</span></code> method.</p>
<p>Conversely, the <a class="reference internal" href="#datetime.datetime.strptime" title="datetime.datetime.strptime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">datetime.strptime()</span></code></a> class method creates a
<a class="reference internal" href="#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> object from a string representing a date and time and a
corresponding format string. <code class="docutils literal notranslate"><span class="pre">datetime.strptime(date_string,</span> <span class="pre">format)</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">datetime(*(time.strptime(date_string,</span> <span class="pre">format)[0:6]))</span></code>, except
when the format includes sub-second components or timezone offset information,
which are supported in <code class="docutils literal notranslate"><span class="pre">datetime.strptime</span></code> but are discarded by <code class="docutils literal notranslate"><span class="pre">time.strptime</span></code>.</p>
<p>For <a class="reference internal" href="#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> objects, the format codes for year, month, and day should not
be used, as time objects have no such values.  If they’re used anyway, <code class="docutils literal notranslate"><span class="pre">1900</span></code>
is substituted for the year, and <code class="docutils literal notranslate"><span class="pre">1</span></code> for the month and day.</p>
<p>For <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> objects, the format codes for hours, minutes, seconds, and
microseconds should not be used, as <a class="reference internal" href="#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a> objects have no such
values.  If they’re used anyway, <code class="docutils literal notranslate"><span class="pre">0</span></code> is substituted for them.</p>
<p>The full set of format codes supported varies across platforms, because Python
calls the platform C library’s <code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code> function, and platform
variations are common.  To see the full set of format codes supported on your
platform, consult the <em class="manpage">strftime(3)</em> documentation.</p>
<p>For the same reason, handling of format strings containing Unicode code points
that can’t be represented in the charset of the current locale is also
platform-dependent. On some platforms such code points are preserved intact in
the output, while on others <code class="docutils literal notranslate"><span class="pre">strftime</span></code> may raise <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> or return
an empty string instead.</p>
<p>The following is a list of all the format codes that the C standard (1989
version) requires, and these work on all platforms with a standard C
implementation.  Note that the 1999 version of the C standard added additional
format codes.</p>
<p>The exact range of years for which <code class="xref py py-meth docutils literal notranslate"><span class="pre">strftime()</span></code> works also varies across
platforms.  Regardless of platform, years before 1900 cannot be used.</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="43%" />
<col width="32%" />
<col width="9%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Directive</th>
<th class="head">Meaning</th>
<th class="head">Example</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%a</span></code></td>
<td>Weekday as locale’s
abbreviated name.</td>
<td><div class="first last line-block">
<div class="line">Sun, Mon, …, Sat
(en_US);</div>
<div class="line">So, Mo, …, Sa
(de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%A</span></code></td>
<td>Weekday as locale’s full name.</td>
<td><div class="first last line-block">
<div class="line">Sunday, Monday, …,
Saturday (en_US);</div>
<div class="line">Sonntag, Montag, …,
Samstag (de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%w</span></code></td>
<td>Weekday as a decimal number,
where 0 is Sunday and 6 is
Saturday.</td>
<td>0, 1, …, 6</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%d</span></code></td>
<td>Day of the month as a
zero-padded decimal number.</td>
<td>01, 02, …, 31</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%b</span></code></td>
<td>Month as locale’s abbreviated
name.</td>
<td><div class="first last line-block">
<div class="line">Jan, Feb, …, Dec
(en_US);</div>
<div class="line">Jan, Feb, …, Dez
(de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%B</span></code></td>
<td>Month as locale’s full name.</td>
<td><div class="first last line-block">
<div class="line">January, February,
…, December (en_US);</div>
<div class="line">Januar, Februar, …,
Dezember (de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%m</span></code></td>
<td>Month as a zero-padded
decimal number.</td>
<td>01, 02, …, 12</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%y</span></code></td>
<td>Year without century as a
zero-padded decimal number.</td>
<td>00, 01, …, 99</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%Y</span></code></td>
<td>Year with century as a decimal
number.</td>
<td>1970, 1988, 2001, 2013</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%H</span></code></td>
<td>Hour (24-hour clock) as a
zero-padded decimal number.</td>
<td>00, 01, …, 23</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%I</span></code></td>
<td>Hour (12-hour clock) as a
zero-padded decimal number.</td>
<td>01, 02, …, 12</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%p</span></code></td>
<td>Locale’s equivalent of either
AM or PM.</td>
<td><div class="first last line-block">
<div class="line">AM, PM (en_US);</div>
<div class="line">am, pm (de_DE)</div>
</div>
</td>
<td>(1),
(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%M</span></code></td>
<td>Minute as a zero-padded
decimal number.</td>
<td>00, 01, …, 59</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%S</span></code></td>
<td>Second as a zero-padded
decimal number.</td>
<td>00, 01, …, 59</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%f</span></code></td>
<td>Microsecond as a decimal
number, zero-padded on the
left.</td>
<td>000000, 000001, …,
999999</td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%z</span></code></td>
<td>UTC offset in the form +HHMM
or -HHMM (empty string if the
the object is naive).</td>
<td>(empty), +0000, -0400,
+1030</td>
<td>(5)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%Z</span></code></td>
<td>Time zone name (empty string
if the object is naive).</td>
<td>(empty), UTC, EST, CST</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%j</span></code></td>
<td>Day of the year as a
zero-padded decimal number.</td>
<td>001, 002, …, 366</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%U</span></code></td>
<td>Week number of the year
(Sunday as the first day of
the week) as a zero padded
decimal number. All days in a
new year preceding the first
Sunday are considered to be in
week 0.</td>
<td>00, 01, …, 53</td>
<td>(6)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%W</span></code></td>
<td>Week number of the year
(Monday as the first day of
the week) as a decimal number.
All days in a new year
preceding the first Monday
are considered to be in
week 0.</td>
<td>00, 01, …, 53</td>
<td>(6)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%c</span></code></td>
<td>Locale’s appropriate date and
time representation.</td>
<td><div class="first last line-block">
<div class="line">Tue Aug 16 21:30:00
1988 (en_US);</div>
<div class="line">Di 16 Aug 21:30:00
1988 (de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%x</span></code></td>
<td>Locale’s appropriate date
representation.</td>
<td><div class="first last line-block">
<div class="line">08/16/88 (None);</div>
<div class="line">08/16/1988 (en_US);</div>
<div class="line">16.08.1988 (de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%X</span></code></td>
<td>Locale’s appropriate time
representation.</td>
<td><div class="first last line-block">
<div class="line">21:30:00 (en_US);</div>
<div class="line">21:30:00 (de_DE)</div>
</div>
</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%%</span></code></td>
<td>A literal <code class="docutils literal notranslate"><span class="pre">'%'</span></code> character.</td>
<td>%</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">Because the format depends on the current locale, care should be taken when
making assumptions about the output value. Field orderings will vary (for
example, “month/day/year” versus “day/month/year”), and the output may
contain Unicode characters encoded using the locale’s default encoding (for
example, if the current locale is <code class="docutils literal notranslate"><span class="pre">ja_JP</span></code>, the default encoding could be
any one of <code class="docutils literal notranslate"><span class="pre">eucJP</span></code>, <code class="docutils literal notranslate"><span class="pre">SJIS</span></code>, or <code class="docutils literal notranslate"><span class="pre">utf-8</span></code>; use <a class="reference internal" href="locale.html#locale.getlocale" title="locale.getlocale"><code class="xref py py-meth docutils literal notranslate"><span class="pre">locale.getlocale()</span></code></a>
to determine the current locale’s encoding).</p>
</li>
<li><p class="first">When used with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">strptime()</span></code> method, the <code class="docutils literal notranslate"><span class="pre">%p</span></code> directive only affects
the output hour field if the <code class="docutils literal notranslate"><span class="pre">%I</span></code> directive is used to parse the hour.</p>
</li>
<li><p class="first">Unlike the <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module, the <a class="reference internal" href="#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module does not support
leap seconds.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">%f</span></code> is an extension to the set of format characters in the C standard
(but implemented separately in datetime objects, and therefore always
available).  When used with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">strptime()</span></code> method, the <code class="docutils literal notranslate"><span class="pre">%f</span></code>
directive accepts from one to six digits and zero pads on the right.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</li>
<li><p class="first">For a naive object, the <code class="docutils literal notranslate"><span class="pre">%z</span></code> and <code class="docutils literal notranslate"><span class="pre">%Z</span></code> format codes are replaced by empty
strings.</p>
<p>For an aware object:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">%z</span></code></dt>
<dd><p class="first last"><code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code> is transformed into a 5-character string of the form
+HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC
offset hours, and MM is a 2-digit string giving the number of UTC offset
minutes.  For example, if <code class="xref py py-meth docutils literal notranslate"><span class="pre">utcoffset()</span></code> returns
<code class="docutils literal notranslate"><span class="pre">timedelta(hours=-3,</span> <span class="pre">minutes=-30)</span></code>, <code class="docutils literal notranslate"><span class="pre">%z</span></code> is replaced with the string
<code class="docutils literal notranslate"><span class="pre">'-0330'</span></code>.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">%Z</span></code></dt>
<dd><p class="first last">If <code class="xref py py-meth docutils literal notranslate"><span class="pre">tzname()</span></code> returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">%Z</span></code> is replaced by an empty
string.  Otherwise <code class="docutils literal notranslate"><span class="pre">%Z</span></code> is replaced by the returned value, which must
be a string.</p>
</dd>
</dl>
</li>
<li><p class="first">When used with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">strptime()</span></code> method, <code class="docutils literal notranslate"><span class="pre">%U</span></code> and <code class="docutils literal notranslate"><span class="pre">%W</span></code> are only used
in calculations when the day of the week and the year are specified.</p>
</li>
</ol>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>If, that is, we ignore the effects of Relativity</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a><ul>
<li><a class="reference internal" href="#available-types">8.1.1. Available Types</a></li>
<li><a class="reference internal" href="#timedelta-objects">8.1.2. <code class="docutils literal notranslate"><span class="pre">timedelta</span></code> Objects</a></li>
<li><a class="reference internal" href="#date-objects">8.1.3. <code class="docutils literal notranslate"><span class="pre">date</span></code> Objects</a></li>
<li><a class="reference internal" href="#datetime-objects">8.1.4. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> Objects</a></li>
<li><a class="reference internal" href="#time-objects">8.1.5. <code class="docutils literal notranslate"><span class="pre">time</span></code> Objects</a></li>
<li><a class="reference internal" href="#tzinfo-objects">8.1.6. <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> Objects</a></li>
<li><a class="reference internal" href="#strftime-and-strptime-behavior">8.1.7. <code class="docutils literal notranslate"><span class="pre">strftime()</span></code> and <code class="docutils literal notranslate"><span class="pre">strptime()</span></code> Behavior</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="datatypes.html"
                        title="previous chapter">8. Data Types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="calendar.html"
                        title="next chapter">8.2. <code class="docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/datetime.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="calendar.html" title="8.2. calendar — General calendar-related functions"
             >next</a> |</li>
        <li class="right" >
          <a href="datatypes.html" title="8. Data Types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�_`��A�Ahtml/library/dbhash.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.10. dbhash — DBM-style interface to the BSD database library &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.11. bsddb — Interface to Berkeley DB library" href="bsddb.html" />
    <link rel="prev" title="11.9. gdbm — GNU’s reinterpretation of dbm" href="gdbm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dbhash.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bsddb.html" title="11.11. bsddb — Interface to Berkeley DB library"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gdbm.html" title="11.9. gdbm — GNU’s reinterpretation of dbm"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dbhash">
<span id="dbhash-dbm-style-interface-to-the-bsd-database-library"></span><h1>11.10. <a class="reference internal" href="#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a> — DBM-style interface to the BSD database library<a class="headerlink" href="#module-dbhash" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">The <a class="reference internal" href="#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a> module provides a function to open databases using the BSD
<code class="docutils literal notranslate"><span class="pre">db</span></code> library.  This module mirrors the interface of the other Python database
modules that provide access to DBM-style databases.  The <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module is
required  to use <a class="reference internal" href="#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a>.</p>
<p>This module provides an exception and a function:</p>
<dl class="exception">
<dt id="dbhash.error">
<em class="property">exception </em><code class="descclassname">dbhash.</code><code class="descname">error</code><a class="headerlink" href="#dbhash.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on database errors other than <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.  It is a synonym
for <code class="xref py py-exc docutils literal notranslate"><span class="pre">bsddb.error</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="dbhash.open">
<code class="descclassname">dbhash.</code><code class="descname">open</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a <code class="docutils literal notranslate"><span class="pre">db</span></code> database and return the database object.  The <em>path</em> argument is
the name of the database file.</p>
<p>The <em>flag</em> argument can be:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>Open existing database for reading only
(default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span></code></td>
<td>Open existing database for reading and
writing</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Open database for reading and writing,
creating it if it doesn’t exist</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Always create a new, empty database, open
for reading and writing</td>
</tr>
</tbody>
</table>
<p>For platforms on which the BSD <code class="docutils literal notranslate"><span class="pre">db</span></code> library supports locking, an <code class="docutils literal notranslate"><span class="pre">'l'</span></code>
can be appended to indicate that locking should be used.</p>
<p>The optional <em>mode</em> parameter is used to indicate the Unix permission bits that
should be set if a new database must be created; this will be masked by the
current umask value for the process.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a></dt>
<dd>Generic interface to <code class="docutils literal notranslate"><span class="pre">dbm</span></code>-style databases.</dd>
<dt>Module <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a></dt>
<dd>Lower-level interface to the BSD <code class="docutils literal notranslate"><span class="pre">db</span></code> library.</dd>
<dt>Module <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a></dt>
<dd>Utility module used to determine the type of an existing database.</dd>
</dl>
</div>
<div class="section" id="database-objects">
<span id="dbhash-objects"></span><h2>11.10.1. Database Objects<a class="headerlink" href="#database-objects" title="Permalink to this headline">¶</a></h2>
<p>The database objects returned by <a class="reference internal" href="#dbhash.open" title="dbhash.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> provide the methods  common to all
the DBM-style databases and mapping objects.  The following methods are
available in addition to the standard methods.</p>
<dl class="method">
<dt id="dbhash.dbhash.first">
<code class="descclassname">dbhash.</code><code class="descname">first</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.dbhash.first" title="Permalink to this definition">¶</a></dt>
<dd><p>It’s possible to loop over every key/value pair in the database using this
method and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method.  The traversal is ordered by the databases
internal hash values, and won’t be sorted by the key values.  This method
returns the starting key.</p>
</dd></dl>

<dl class="method">
<dt id="dbhash.dbhash.last">
<code class="descclassname">dbhash.</code><code class="descname">last</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.dbhash.last" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the last key/value pair in a database traversal.  This may be used to
begin a reverse-order traversal; see <a class="reference internal" href="#dbhash.dbhash.previous" title="dbhash.dbhash.previous"><code class="xref py py-meth docutils literal notranslate"><span class="pre">previous()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dbhash.dbhash.next">
<code class="descclassname">dbhash.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.dbhash.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the key next key/value pair in a database traversal.  The following code
prints every key in the database <code class="docutils literal notranslate"><span class="pre">db</span></code>, without having to create a list in
memory that contains them all:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="n">db</span><span class="o">.</span><span class="n">first</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">db</span><span class="p">)):</span>
    <span class="nb">print</span> <span class="n">db</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="dbhash.dbhash.previous">
<code class="descclassname">dbhash.</code><code class="descname">previous</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.dbhash.previous" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the previous key/value pair in a forward-traversal of the database. In
conjunction with <a class="reference internal" href="#dbhash.dbhash.last" title="dbhash.dbhash.last"><code class="xref py py-meth docutils literal notranslate"><span class="pre">last()</span></code></a>, this may be used to implement a reverse-order
traversal.</p>
</dd></dl>

<dl class="method">
<dt id="dbhash.dbhash.sync">
<code class="descclassname">dbhash.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbhash.dbhash.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>This method forces any unwritten data to be written to the disk.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a><ul>
<li><a class="reference internal" href="#database-objects">11.10.1. Database Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gdbm.html"
                        title="previous chapter">11.9. <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> — GNU’s reinterpretation of dbm</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bsddb.html"
                        title="next chapter">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dbhash.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bsddb.html" title="11.11. bsddb — Interface to Berkeley DB library"
             >next</a> |</li>
        <li class="right" >
          <a href="gdbm.html" title="11.9. gdbm — GNU’s reinterpretation of dbm"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����4�4html/library/dbm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.8. dbm — Simple “database” interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.9. gdbm — GNU’s reinterpretation of dbm" href="gdbm.html" />
    <link rel="prev" title="11.7. whichdb — Guess which DBM module created a database" href="whichdb.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dbm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gdbm.html" title="11.9. gdbm — GNU’s reinterpretation of dbm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="whichdb.html" title="11.7. whichdb — Guess which DBM module created a database"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dbm">
<span id="dbm-simple-database-interface"></span><h1>11.8. <a class="reference internal" href="#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a> — Simple “database” interface<a class="headerlink" href="#module-dbm" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.ndbm</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a> module provides an interface to the Unix “(n)dbm” library.  Dbm
objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a dbm object doesn’t print the keys and values, and the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code> methods are not supported.</p>
<p>This module can be used with the “classic” ndbm interface, the BSD DB
compatibility interface, or the GNU GDBM compatibility interface. On Unix, the
<strong class="program">configure</strong> script will attempt to locate the appropriate header file
to simplify building this module.</p>
<p>The module defines the following:</p>
<dl class="exception">
<dt id="dbm.error">
<em class="property">exception </em><code class="descclassname">dbm.</code><code class="descname">error</code><a class="headerlink" href="#dbm.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised on dbm-specific errors, such as I/O errors. <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised for
general mapping errors like specifying an incorrect key.</p>
</dd></dl>

<dl class="data">
<dt id="dbm.library">
<code class="descclassname">dbm.</code><code class="descname">library</code><a class="headerlink" href="#dbm.library" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the <code class="docutils literal notranslate"><span class="pre">ndbm</span></code> implementation library used.</p>
</dd></dl>

<dl class="function">
<dt id="dbm.open">
<code class="descclassname">dbm.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dbm.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a dbm database and return a dbm object.  The <em>filename</em> argument is the
name of the database file (without the <code class="file docutils literal notranslate"><span class="pre">.dir</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pag</span></code> extensions;
note that the BSD DB implementation of the interface will append the extension
<code class="file docutils literal notranslate"><span class="pre">.db</span></code> and only create one file).</p>
<p>The optional <em>flag</em> argument must be one of these values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>Open existing database for reading only
(default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span></code></td>
<td>Open existing database for reading and
writing</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Open database for reading and writing,
creating it if it doesn’t exist</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Always create a new, empty database, open
for reading and writing</td>
</tr>
</tbody>
</table>
<p>The optional <em>mode</em> argument is the Unix mode of the file, used only when the
database has to be created.  It defaults to octal <code class="docutils literal notranslate"><span class="pre">0666</span></code> (and will be
modified by the prevailing umask).</p>
<p>In addition to the dictionary-like methods, <code class="docutils literal notranslate"><span class="pre">dbm</span></code> objects
provide the following method:</p>
<dl class="function">
<dt id="dbm.close">
<code class="descclassname">dbm.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dbm.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the <code class="docutils literal notranslate"><span class="pre">dbm</span></code> database.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a></dt>
<dd>Generic interface to <code class="docutils literal notranslate"><span class="pre">dbm</span></code>-style databases.</dd>
<dt>Module <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a></dt>
<dd>Similar interface to the GNU GDBM library.</dd>
<dt>Module <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a></dt>
<dd>Utility module used to determine the type of an existing database.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="whichdb.html"
                        title="previous chapter">11.7. <code class="docutils literal notranslate"><span class="pre">whichdb</span></code> — Guess which DBM module created a database</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gdbm.html"
                        title="next chapter">11.9. <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> — GNU’s reinterpretation of dbm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dbm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gdbm.html" title="11.9. gdbm — GNU’s reinterpretation of dbm"
             >next</a> |</li>
        <li class="right" >
          <a href="whichdb.html" title="11.7. whichdb — Guess which DBM module created a database"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\:����)�)html/library/debug.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26. Debugging and Profiling &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.1. bdb — Debugger framework" href="bdb.html" />
    <link rel="prev" title="25.5. test — Regression tests package for Python" href="test.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/debug.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bdb.html" title="26.1. bdb — Debugger framework"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="test.html" title="25.5. test — Regression tests package for Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="debugging-and-profiling">
<h1>26. Debugging and Profiling<a class="headerlink" href="#debugging-and-profiling" title="Permalink to this headline">¶</a></h1>
<p>These libraries help you with Python development: the debugger enables you to
step through code, analyze stack frames and set breakpoints etc., and the
profilers run code and give you a detailed breakdown of execution times,
allowing you to identify bottlenecks in your programs.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="bdb.html">26.1. <code class="docutils literal notranslate"><span class="pre">bdb</span></code> — Debugger framework</a></li>
<li class="toctree-l1"><a class="reference internal" href="pdb.html">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></li>
<li class="toctree-l1"><a class="reference internal" href="pdb.html#debugger-commands">26.3. Debugger Commands</a></li>
<li class="toctree-l1"><a class="reference internal" href="profile.html">26.4. The Python Profilers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="profile.html#introduction-to-the-profilers">26.4.1. Introduction to the profilers</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#instant-user-s-manual">26.4.2. Instant User’s Manual</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#module-cProfile">26.4.3. <code class="docutils literal notranslate"><span class="pre">profile</span></code> and <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> Module Reference</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#the-stats-class">26.4.4. The <code class="docutils literal notranslate"><span class="pre">Stats</span></code> Class</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#what-is-deterministic-profiling">26.4.5. What Is Deterministic Profiling?</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#limitations">26.4.6. Limitations</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#calibration">26.4.7. Calibration</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html#using-a-custom-timer">26.4.8. Using a custom timer</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="hotshot.html">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a><ul>
<li class="toctree-l2"><a class="reference internal" href="hotshot.html#profile-objects">26.5.1. Profile Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="hotshot.html#module-hotshot.stats">26.5.2. Using hotshot data</a></li>
<li class="toctree-l2"><a class="reference internal" href="hotshot.html#example-usage">26.5.3. Example Usage</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="timeit.html">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a><ul>
<li class="toctree-l2"><a class="reference internal" href="timeit.html#basic-examples">26.6.1. Basic Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="timeit.html#python-interface">26.6.2. Python Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="timeit.html#command-line-interface">26.6.3. Command-Line Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="timeit.html#examples">26.6.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="trace.html">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="trace.html#command-line-usage">26.7.1. Command-Line Usage</a><ul>
<li class="toctree-l3"><a class="reference internal" href="trace.html#main-options">26.7.1.1. Main options</a></li>
<li class="toctree-l3"><a class="reference internal" href="trace.html#modifiers">26.7.1.2. Modifiers</a></li>
<li class="toctree-l3"><a class="reference internal" href="trace.html#filters">26.7.1.3. Filters</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="trace.html#programmatic-interface">26.7.2. Programmatic Interface</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="test.html"
                        title="previous chapter">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bdb.html"
                        title="next chapter">26.1. <code class="docutils literal notranslate"><span class="pre">bdb</span></code> — Debugger framework</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/debug.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bdb.html" title="26.1. bdb — Debugger framework"
             >next</a> |</li>
        <li class="right" >
          <a href="test.html" title="25.5. test — Regression tests package for Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\M�ukdkdhtml/library/decimal.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.4. decimal — Decimal fixed point and floating point arithmetic &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.5. fractions — Rational numbers" href="fractions.html" />
    <link rel="prev" title="9.3. cmath — Mathematical functions for complex numbers" href="cmath.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/decimal.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fractions.html" title="9.5. fractions — Rational numbers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cmath.html" title="9.3. cmath — Mathematical functions for complex numbers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-decimal">
<span id="decimal-decimal-fixed-point-and-floating-point-arithmetic"></span><h1>9.4. <a class="reference internal" href="#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> — Decimal fixed point and floating point arithmetic<a class="headerlink" href="#module-decimal" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>The <a class="reference internal" href="#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides support for decimal floating point
arithmetic.  It offers several advantages over the <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> datatype:</p>
<ul>
<li><p class="first">Decimal “is based on a floating-point model which was designed with people
in mind, and necessarily has a paramount guiding principle – computers must
provide an arithmetic that works in the same way as the arithmetic that
people learn at school.” – excerpt from the decimal arithmetic specification.</p>
</li>
<li><p class="first">Decimal numbers can be represented exactly.  In contrast, numbers like
<code class="xref py py-const docutils literal notranslate"><span class="pre">1.1</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">2.2</span></code> do not have exact representations in binary
floating point.  End users typically would not expect <code class="docutils literal notranslate"><span class="pre">1.1</span> <span class="pre">+</span> <span class="pre">2.2</span></code> to display
as <code class="xref py py-const docutils literal notranslate"><span class="pre">3.3000000000000003</span></code> as it does with binary floating point.</p>
</li>
<li><p class="first">The exactness carries over into arithmetic.  In decimal floating point, <code class="docutils literal notranslate"><span class="pre">0.1</span>
<span class="pre">+</span> <span class="pre">0.1</span> <span class="pre">+</span> <span class="pre">0.1</span> <span class="pre">-</span> <span class="pre">0.3</span></code> is exactly equal to zero.  In binary floating point, the result
is <code class="xref py py-const docutils literal notranslate"><span class="pre">5.5511151231257827e-017</span></code>.  While near to zero, the differences
prevent reliable equality testing and differences can accumulate. For this
reason, decimal is preferred in accounting applications which have strict
equality invariants.</p>
</li>
<li><p class="first">The decimal module incorporates a notion of significant places so that <code class="docutils literal notranslate"><span class="pre">1.30</span>
<span class="pre">+</span> <span class="pre">1.20</span></code> is <code class="xref py py-const docutils literal notranslate"><span class="pre">2.50</span></code>.  The trailing zero is kept to indicate significance.
This is the customary presentation for monetary applications. For
multiplication, the “schoolbook” approach uses all the figures in the
multiplicands.  For instance, <code class="docutils literal notranslate"><span class="pre">1.3</span> <span class="pre">*</span> <span class="pre">1.2</span></code> gives <code class="xref py py-const docutils literal notranslate"><span class="pre">1.56</span></code> while <code class="docutils literal notranslate"><span class="pre">1.30</span> <span class="pre">*</span>
<span class="pre">1.20</span></code> gives <code class="xref py py-const docutils literal notranslate"><span class="pre">1.5600</span></code>.</p>
</li>
<li><p class="first">Unlike hardware based binary floating point, the decimal module has a user
alterable precision (defaulting to 28 places) which can be as large as needed for
a given problem:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.142857&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">28</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.1428571428571428571428571429&#39;)</span>
</pre></div>
</div>
</li>
<li><p class="first">Both binary and decimal floating point are implemented in terms of published
standards.  While the built-in float type exposes only a modest portion of its
capabilities, the decimal module exposes all required parts of the standard.
When needed, the programmer has full control over rounding and signal handling.
This includes an option to enforce exact arithmetic by using exceptions
to block any inexact operations.</p>
</li>
<li><p class="first">The decimal module was designed to support “without prejudice, both exact
unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
and rounded floating-point arithmetic.”  – excerpt from the decimal
arithmetic specification.</p>
</li>
</ul>
<p>The module design is centered around three concepts:  the decimal number, the
context for arithmetic, and signals.</p>
<p>A decimal number is immutable.  It has a sign, coefficient digits, and an
exponent.  To preserve significance, the coefficient digits do not truncate
trailing zeros.  Decimals also include special values such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">-Infinity</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>.  The standard also
differentiates <code class="xref py py-const docutils literal notranslate"><span class="pre">-0</span></code> from <code class="xref py py-const docutils literal notranslate"><span class="pre">+0</span></code>.</p>
<p>The context for arithmetic is an environment specifying precision, rounding
rules, limits on exponents, flags indicating the results of operations, and trap
enablers which determine whether signals are treated as exceptions.  Rounding
options include <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_CEILING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_DOWN</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_FLOOR</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_DOWN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_UP</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_UP</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_05UP</span></code>.</p>
<p>Signals are groups of exceptional conditions arising during the course of
computation.  Depending on the needs of the application, signals may be ignored,
considered as informational, or treated as exceptions. The signals in the
decimal module are: <a class="reference internal" href="#decimal.Clamped" title="decimal.Clamped"><code class="xref py py-const docutils literal notranslate"><span class="pre">Clamped</span></code></a>, <a class="reference internal" href="#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-const docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a>,
<a class="reference internal" href="#decimal.DivisionByZero" title="decimal.DivisionByZero"><code class="xref py py-const docutils literal notranslate"><span class="pre">DivisionByZero</span></code></a>, <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-const docutils literal notranslate"><span class="pre">Inexact</span></code></a>, <a class="reference internal" href="#decimal.Rounded" title="decimal.Rounded"><code class="xref py py-const docutils literal notranslate"><span class="pre">Rounded</span></code></a>, <a class="reference internal" href="#decimal.Subnormal" title="decimal.Subnormal"><code class="xref py py-const docutils literal notranslate"><span class="pre">Subnormal</span></code></a>,
<a class="reference internal" href="#decimal.Overflow" title="decimal.Overflow"><code class="xref py py-const docutils literal notranslate"><span class="pre">Overflow</span></code></a>, and <a class="reference internal" href="#decimal.Underflow" title="decimal.Underflow"><code class="xref py py-const docutils literal notranslate"><span class="pre">Underflow</span></code></a>.</p>
<p>For each signal there is a flag and a trap enabler.  When a signal is
encountered, its flag is set to one, then, if the trap enabler is
set to one, an exception is raised.  Flags are sticky, so the user needs to
reset them before monitoring a calculation.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li>IBM’s General Decimal Arithmetic Specification, <a class="reference external" href="http://speleotrove.com/decimal/">The General Decimal Arithmetic
Specification</a>.</li>
</ul>
</div>
<div class="section" id="quick-start-tutorial">
<span id="decimal-tutorial"></span><h2>9.4.1. Quick-start Tutorial<a class="headerlink" href="#quick-start-tutorial" title="Permalink to this headline">¶</a></h2>
<p>The usual start to using decimals is importing the module, viewing the current
context with <a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a> and, if necessary, setting new values for
precision, rounding, or enabled traps:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span>
<span class="go">Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,</span>
<span class="go">        capitals=1, flags=[], traps=[Overflow, DivisionByZero,</span>
<span class="go">        InvalidOperation])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">7</span>       <span class="c1"># Set a new precision</span>
</pre></div>
</div>
<p>Decimal instances can be constructed from integers, strings, floats, or tuples.
Construction from an integer or a float performs an exact conversion of the
value of that integer or float.  Decimal numbers include special values such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> which stands for “Not a number”, positive and negative
<code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">-0</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">28</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">Decimal(&#39;10&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.14&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.14&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mf">3.14</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.140000000000000124344978758017532527446746826171875&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">((</span><span class="mi">0</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="o">-</span><span class="mi">2</span><span class="p">))</span>
<span class="go">Decimal(&#39;3.14&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="mf">2.0</span> <span class="o">**</span> <span class="mf">0.5</span><span class="p">))</span>
<span class="go">Decimal(&#39;1.41421356237&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">**</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.5&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;1.414213562373095048801688724&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;NaN&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;-Infinity&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;-Infinity&#39;)</span>
</pre></div>
</div>
<p>The significance of a new Decimal is determined solely by the number of digits
input.  Context precision and rounding only come into play during arithmetic
operations.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.0&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.0&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.1415926535&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.1415926535&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.1415926535&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;2.7182818285&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;5.85987&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">rounding</span> <span class="o">=</span> <span class="n">ROUND_UP</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.1415926535&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;2.7182818285&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;5.85988&#39;)</span>
</pre></div>
</div>
<p>Decimals interact well with much of the rest of Python.  Here is a small decimal
floating point flying circus:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">Decimal</span><span class="p">,</span> <span class="s1">&#39;1.34 1.87 3.45 2.35 1.00 0.03 9.25&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">max</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">Decimal(&#39;9.25&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">min</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.03&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">[Decimal(&#39;0.03&#39;), Decimal(&#39;1.00&#39;), Decimal(&#39;1.34&#39;), Decimal(&#39;1.87&#39;),</span>
<span class="go"> Decimal(&#39;2.35&#39;), Decimal(&#39;3.45&#39;), Decimal(&#39;9.25&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">Decimal(&#39;19.29&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span> <span class="o">=</span> <span class="n">data</span><span class="p">[:</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">&#39;1.34&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">1.34</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>     <span class="c1"># round() first converts to binary floating point</span>
<span class="go">1.3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">*</span> <span class="mi">5</span>
<span class="go">Decimal(&#39;6.70&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">*</span> <span class="n">b</span>
<span class="go">Decimal(&#39;2.5058&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">%</span> <span class="n">a</span>
<span class="go">Decimal(&#39;0.77&#39;)</span>
</pre></div>
</div>
<p>And some mathematical functions are also available to Decimal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">28</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
<span class="go">Decimal(&#39;1.414213562373095048801688724&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">exp</span><span class="p">()</span>
<span class="go">Decimal(&#39;2.718281828459045235360287471&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;10&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">ln</span><span class="p">()</span>
<span class="go">Decimal(&#39;2.302585092994045684017991455&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;10&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">log10</span><span class="p">()</span>
<span class="go">Decimal(&#39;1&#39;)</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">quantize()</span></code> method rounds a number to a fixed exponent.  This method is
useful for monetary applications that often round results to a fixed number of
places:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;7.325&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;.01&#39;</span><span class="p">),</span> <span class="n">rounding</span><span class="o">=</span><span class="n">ROUND_DOWN</span><span class="p">)</span>
<span class="go">Decimal(&#39;7.32&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;7.325&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.&#39;</span><span class="p">),</span> <span class="n">rounding</span><span class="o">=</span><span class="n">ROUND_UP</span><span class="p">)</span>
<span class="go">Decimal(&#39;8&#39;)</span>
</pre></div>
</div>
<p>As shown above, the <a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a> function accesses the current context and
allows the settings to be changed.  This approach meets the needs of most
applications.</p>
<p>For more advanced work, it may be useful to create alternate contexts using the
Context() constructor.  To make an alternate active, use the <a class="reference internal" href="#decimal.setcontext" title="decimal.setcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">setcontext()</span></code></a>
function.</p>
<p>In accordance with the standard, the <a class="reference internal" href="#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides two ready to
use standard contexts, <a class="reference internal" href="#decimal.BasicContext" title="decimal.BasicContext"><code class="xref py py-const docutils literal notranslate"><span class="pre">BasicContext</span></code></a> and <a class="reference internal" href="#decimal.ExtendedContext" title="decimal.ExtendedContext"><code class="xref py py-const docutils literal notranslate"><span class="pre">ExtendedContext</span></code></a>. The
former is especially useful for debugging because many of the traps are
enabled:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">myothercontext</span> <span class="o">=</span> <span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">60</span><span class="p">,</span> <span class="n">rounding</span><span class="o">=</span><span class="n">ROUND_HALF_DOWN</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">setcontext</span><span class="p">(</span><span class="n">myothercontext</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.142857142857142857142857142857142857142857142857142857142857&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">ExtendedContext</span>
<span class="go">Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,</span>
<span class="go">        capitals=1, flags=[], traps=[])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">setcontext</span><span class="p">(</span><span class="n">ExtendedContext</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.142857143&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">Decimal(&#39;Infinity&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">setcontext</span><span class="p">(</span><span class="n">BasicContext</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#143&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">-toplevel-</span>
    <span class="n">Decimal</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gr">DivisionByZero</span>: <span class="n">x / 0</span>
</pre></div>
</div>
<p>Contexts also have signal flags for monitoring exceptional conditions
encountered during computations.  The flags remain set until explicitly cleared,
so it is best to clear the flags before each set of monitored computations by
using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_flags()</span></code> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">setcontext</span><span class="p">(</span><span class="n">ExtendedContext</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">clear_flags</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">355</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">113</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.14159292&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span>
<span class="go">Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,</span>
<span class="go">        capitals=1, flags=[Rounded, Inexact], traps=[])</span>
</pre></div>
</div>
<p>The <em>flags</em> entry shows that the rational approximation to <code class="xref py py-const docutils literal notranslate"><span class="pre">Pi</span></code> was
rounded (digits beyond the context precision were thrown away) and that the
result is inexact (some of the discarded digits were non-zero).</p>
<p>Individual traps are set using the dictionary in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">traps</span></code> field of a
context:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">setcontext</span><span class="p">(</span><span class="n">ExtendedContext</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">Decimal(&#39;Infinity&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">traps</span><span class="p">[</span><span class="n">DivisionByZero</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#112&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">-toplevel-</span>
    <span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gr">DivisionByZero</span>: <span class="n">x / 0</span>
</pre></div>
</div>
<p>Most programs adjust the current context only once, at the beginning of the
program.  And, in many applications, data is converted to <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> with
a single cast inside a loop.  With context set and decimals created, the bulk of
the program manipulates the data no differently than with other Python numeric
types.</p>
</div>
<div class="section" id="decimal-objects">
<span id="decimal-decimal"></span><h2>9.4.2. Decimal objects<a class="headerlink" href="#decimal-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="decimal.Decimal">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Decimal</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> object based from <em>value</em>.</p>
<p><em>value</em> can be an integer, string, tuple, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, or another <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>
object. If no <em>value</em> is given, returns <code class="docutils literal notranslate"><span class="pre">Decimal('0')</span></code>.  If <em>value</em> is a
string, it should conform to the decimal numeric string syntax after leading
and trailing whitespace characters are removed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sign</span>           <span class="p">::</span><span class="o">=</span>  <span class="s1">&#39;+&#39;</span> <span class="o">|</span> <span class="s1">&#39;-&#39;</span>
<span class="n">digit</span>          <span class="p">::</span><span class="o">=</span>  <span class="s1">&#39;0&#39;</span> <span class="o">|</span> <span class="s1">&#39;1&#39;</span> <span class="o">|</span> <span class="s1">&#39;2&#39;</span> <span class="o">|</span> <span class="s1">&#39;3&#39;</span> <span class="o">|</span> <span class="s1">&#39;4&#39;</span> <span class="o">|</span> <span class="s1">&#39;5&#39;</span> <span class="o">|</span> <span class="s1">&#39;6&#39;</span> <span class="o">|</span> <span class="s1">&#39;7&#39;</span> <span class="o">|</span> <span class="s1">&#39;8&#39;</span> <span class="o">|</span> <span class="s1">&#39;9&#39;</span>
<span class="n">indicator</span>      <span class="p">::</span><span class="o">=</span>  <span class="s1">&#39;e&#39;</span> <span class="o">|</span> <span class="s1">&#39;E&#39;</span>
<span class="n">digits</span>         <span class="p">::</span><span class="o">=</span>  <span class="n">digit</span> <span class="p">[</span><span class="n">digit</span><span class="p">]</span><span class="o">...</span>
<span class="n">decimal</span><span class="o">-</span><span class="n">part</span>   <span class="p">::</span><span class="o">=</span>  <span class="n">digits</span> <span class="s1">&#39;.&#39;</span> <span class="p">[</span><span class="n">digits</span><span class="p">]</span> <span class="o">|</span> <span class="p">[</span><span class="s1">&#39;.&#39;</span><span class="p">]</span> <span class="n">digits</span>
<span class="n">exponent</span><span class="o">-</span><span class="n">part</span>  <span class="p">::</span><span class="o">=</span>  <span class="n">indicator</span> <span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="n">digits</span>
<span class="n">infinity</span>       <span class="p">::</span><span class="o">=</span>  <span class="s1">&#39;Infinity&#39;</span> <span class="o">|</span> <span class="s1">&#39;Inf&#39;</span>
<span class="n">nan</span>            <span class="p">::</span><span class="o">=</span>  <span class="s1">&#39;NaN&#39;</span> <span class="p">[</span><span class="n">digits</span><span class="p">]</span> <span class="o">|</span> <span class="s1">&#39;sNaN&#39;</span> <span class="p">[</span><span class="n">digits</span><span class="p">]</span>
<span class="n">numeric</span><span class="o">-</span><span class="n">value</span>  <span class="p">::</span><span class="o">=</span>  <span class="n">decimal</span><span class="o">-</span><span class="n">part</span> <span class="p">[</span><span class="n">exponent</span><span class="o">-</span><span class="n">part</span><span class="p">]</span> <span class="o">|</span> <span class="n">infinity</span>
<span class="n">numeric</span><span class="o">-</span><span class="n">string</span> <span class="p">::</span><span class="o">=</span>  <span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="n">numeric</span><span class="o">-</span><span class="n">value</span> <span class="o">|</span> <span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="n">nan</span>
</pre></div>
</div>
<p>If <em>value</em> is a unicode string then other Unicode decimal digits
are also permitted where <code class="docutils literal notranslate"><span class="pre">digit</span></code> appears above.  These include
decimal digits from various other alphabets (for example,
Arabic-Indic and Devanāgarī digits) along with the fullwidth digits
<code class="docutils literal notranslate"><span class="pre">u'\uff10'</span></code> through <code class="docutils literal notranslate"><span class="pre">u'\uff19'</span></code>.</p>
<p>If <em>value</em> is a <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, it should have three components, a sign
(<code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> for positive or <code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code> for negative), a <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> of
digits, and an integer exponent. For example, <code class="docutils literal notranslate"><span class="pre">Decimal((0,</span> <span class="pre">(1,</span> <span class="pre">4,</span> <span class="pre">1,</span> <span class="pre">4),</span> <span class="pre">-3))</span></code>
returns <code class="docutils literal notranslate"><span class="pre">Decimal('1.414')</span></code>.</p>
<p>If <em>value</em> is a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, the binary floating point value is losslessly
converted to its exact decimal equivalent.  This conversion can often require
53 or more digits of precision.  For example, <code class="docutils literal notranslate"><span class="pre">Decimal(float('1.1'))</span></code>
converts to
<code class="docutils literal notranslate"><span class="pre">Decimal('1.100000000000000088817841970012523233890533447265625')</span></code>.</p>
<p>The <em>context</em> precision does not affect how many digits are stored. That is
determined exclusively by the number of digits in <em>value</em>. For example,
<code class="docutils literal notranslate"><span class="pre">Decimal('3.00000')</span></code> records all five zeros even if the context precision is
only three.</p>
<p>The purpose of the <em>context</em> argument is determining what to do if <em>value</em> is a
malformed string.  If the context traps <a class="reference internal" href="#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-const docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a>, an exception
is raised; otherwise, the constructor returns a new Decimal with the value of
<code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>.</p>
<p>Once constructed, <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> objects are immutable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>leading and trailing whitespace characters are permitted when
creating a Decimal instance from a string.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The argument to the constructor is now permitted to be a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> instance.</p>
</div>
<p>Decimal floating point objects share many properties with the other built-in
numeric types such as <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> and <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.  All of the usual math
operations and special methods apply.  Likewise, decimal objects can be
copied, pickled, printed, used as dictionary keys, used as set elements,
compared, sorted, and coerced to another type (such as <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> or
<a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>).</p>
<p>There are some small differences between arithmetic on Decimal objects and
arithmetic on integers and floats.  When the remainder operator <code class="docutils literal notranslate"><span class="pre">%</span></code> is
applied to Decimal objects, the sign of the result is the sign of the
<em>dividend</em> rather than the sign of the divisor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mi">7</span><span class="p">)</span> <span class="o">%</span> <span class="mi">4</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">7</span><span class="p">)</span> <span class="o">%</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">Decimal(&#39;-3&#39;)</span>
</pre></div>
</div>
<p>The integer division operator <code class="docutils literal notranslate"><span class="pre">//</span></code> behaves analogously, returning the
integer part of the true quotient (truncating towards zero) rather than its
floor, so as to preserve the usual identity <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">(x</span> <span class="pre">//</span> <span class="pre">y)</span> <span class="pre">*</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="o">-</span><span class="mi">7</span> <span class="o">//</span> <span class="mi">4</span>
<span class="go">-2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">7</span><span class="p">)</span> <span class="o">//</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">Decimal(&#39;-1&#39;)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">%</span></code> and <code class="docutils literal notranslate"><span class="pre">//</span></code> operators implement the <code class="docutils literal notranslate"><span class="pre">remainder</span></code> and
<code class="docutils literal notranslate"><span class="pre">divide-integer</span></code> operations (respectively) as described in the
specification.</p>
<p>Decimal objects cannot generally be combined with floats in
arithmetic operations: an attempt to add a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> to a
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, for example, will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
There’s one exception to this rule: it’s possible to use Python’s
comparison operators to compare a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">x</span></code>
with a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">y</span></code>.  Without this exception,
comparisons between <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> and <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> instances
would follow the general rules for comparing objects of different
types described in the <a class="reference internal" href="../reference/expressions.html#expressions"><span class="std std-ref">Expressions</span></a> section of the reference
manual, leading to confusing results.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>A comparison between a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">x</span></code> and a
<a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">y</span></code> now returns a result based on
the values of <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code>.  In earlier versions <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code>
returned the same (arbitrary) result for any <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>
instance <code class="docutils literal notranslate"><span class="pre">x</span></code> and any <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">y</span></code>.</p>
</div>
<p>In addition to the standard numeric properties, decimal floating point
objects also have a number of specialized methods:</p>
<dl class="method">
<dt id="decimal.Decimal.adjusted">
<code class="descname">adjusted</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.adjusted" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the adjusted exponent after shifting out the coefficient’s
rightmost digits until only the lead digit remains:
<code class="docutils literal notranslate"><span class="pre">Decimal('321e+5').adjusted()</span></code> returns seven.  Used for determining the
position of the most significant digit with respect to the decimal point.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.as_tuple">
<code class="descname">as_tuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.as_tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> representation of the number:
<code class="docutils literal notranslate"><span class="pre">DecimalTuple(sign,</span> <span class="pre">digits,</span> <span class="pre">exponent)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Use a named tuple.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.canonical">
<code class="descname">canonical</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.canonical" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the canonical encoding of the argument.  Currently, the encoding of
a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance is always canonical, so this operation returns
its argument unchanged.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.compare">
<code class="descname">compare</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.compare" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare the values of two Decimal instances.  This operation behaves in
the same way as the usual comparison method <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>, except that
<a class="reference internal" href="#decimal.Decimal.compare" title="decimal.Decimal.compare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compare()</span></code></a> returns a Decimal instance rather than an integer, and if
either operand is a NaN then the result is a NaN:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="ow">or</span> <span class="n">b</span> <span class="ow">is</span> <span class="n">a</span> <span class="n">NaN</span> <span class="o">==&gt;</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">)</span>
<span class="n">a</span> <span class="o">&lt;</span> <span class="n">b</span>           <span class="o">==&gt;</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;-1&#39;</span><span class="p">)</span>
<span class="n">a</span> <span class="o">==</span> <span class="n">b</span>          <span class="o">==&gt;</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0&#39;</span><span class="p">)</span>
<span class="n">a</span> <span class="o">&gt;</span> <span class="n">b</span>           <span class="o">==&gt;</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.compare_signal">
<code class="descname">compare_signal</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.compare_signal" title="Permalink to this definition">¶</a></dt>
<dd><p>This operation is identical to the <a class="reference internal" href="#decimal.Decimal.compare" title="decimal.Decimal.compare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compare()</span></code></a> method, except that all
NaNs signal.  That is, if neither operand is a signaling NaN then any
quiet NaN operand is treated as though it were a signaling NaN.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.compare_total">
<code class="descname">compare_total</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.compare_total" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare two operands using their abstract representation rather than their
numerical value.  Similar to the <a class="reference internal" href="#decimal.Decimal.compare" title="decimal.Decimal.compare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compare()</span></code></a> method, but the result
gives a total ordering on <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances.  Two
<a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances with the same numeric value but different
representations compare unequal in this ordering:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;12.0&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">compare_total</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;12&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;-1&#39;)</span>
</pre></div>
</div>
<p>Quiet and signaling NaNs are also included in the total ordering.  The
result of this function is <code class="docutils literal notranslate"><span class="pre">Decimal('0')</span></code> if both operands have the same
representation, <code class="docutils literal notranslate"><span class="pre">Decimal('-1')</span></code> if the first operand is lower in the
total order than the second, and <code class="docutils literal notranslate"><span class="pre">Decimal('1')</span></code> if the first operand is
higher in the total order than the second operand.  See the specification
for details of the total order.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.compare_total_mag">
<code class="descname">compare_total_mag</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.compare_total_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare two operands using their abstract representation rather than their
value as in <a class="reference internal" href="#decimal.Decimal.compare_total" title="decimal.Decimal.compare_total"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compare_total()</span></code></a>, but ignoring the sign of each operand.
<code class="docutils literal notranslate"><span class="pre">x.compare_total_mag(y)</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x.copy_abs().compare_total(y.copy_abs())</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.conjugate">
<code class="descname">conjugate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.conjugate" title="Permalink to this definition">¶</a></dt>
<dd><p>Just returns self, this method is only to comply with the Decimal
Specification.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.copy_abs">
<code class="descname">copy_abs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.copy_abs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the absolute value of the argument.  This operation is unaffected
by the context and is quiet: no flags are changed and no rounding is
performed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.copy_negate">
<code class="descname">copy_negate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.copy_negate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the negation of the argument.  This operation is unaffected by the
context and is quiet: no flags are changed and no rounding is performed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.copy_sign">
<code class="descname">copy_sign</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.copy_sign" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the first operand with the sign set to be the same as the
sign of the second operand.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;2.3&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">copy_sign</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;-1.5&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;-2.3&#39;)</span>
</pre></div>
</div>
<p>This operation is unaffected by the context and is quiet: no flags are
changed and no rounding is performed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.exp">
<code class="descname">exp</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.exp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the (natural) exponential function <code class="docutils literal notranslate"><span class="pre">e**x</span></code> at the
given number.  The result is correctly rounded using the
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code> rounding mode.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">exp</span><span class="p">()</span>
<span class="go">Decimal(&#39;2.718281828459045235360287471&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">321</span><span class="p">)</span><span class="o">.</span><span class="n">exp</span><span class="p">()</span>
<span class="go">Decimal(&#39;2.561702493119680037517373933E+139&#39;)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.from_float">
<code class="descname">from_float</code><span class="sig-paren">(</span><em>f</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.from_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Classmethod that converts a float to a decimal number, exactly.</p>
<p>Note <cite>Decimal.from_float(0.1)</cite> is not the same as <cite>Decimal(‘0.1’)</cite>.
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
<cite>0x1.999999999999ap-4</cite>.  That equivalent value in decimal is
<cite>0.1000000000000000055511151231257827021181583404541015625</cite>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">From Python 2.7 onwards, a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance
can also be constructed directly from a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.</p>
</div>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.1000000000000000055511151231257827021181583404541015625&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="s1">&#39;nan&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;NaN&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="s1">&#39;inf&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;Infinity&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;-Infinity&#39;)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.fma">
<code class="descname">fma</code><span class="sig-paren">(</span><em>other</em>, <em>third</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.fma" title="Permalink to this definition">¶</a></dt>
<dd><p>Fused multiply-add.  Return self*other+third with no rounding of the
intermediate product self*other.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">fma</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="go">Decimal(&#39;11&#39;)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_canonical">
<code class="descname">is_canonical</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_canonical" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is canonical and <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>
otherwise.  Currently, a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance is always canonical, so
this operation always returns <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_finite">
<code class="descname">is_finite</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_finite" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a finite number, and
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> if the argument is an infinity or a NaN.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_infinite">
<code class="descname">is_infinite</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_infinite" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is either positive or negative
infinity and <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_nan">
<code class="descname">is_nan</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_nan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a (quiet or signaling) NaN and
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_normal">
<code class="descname">is_normal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_normal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a <em>normal</em> finite non-zero
number with an adjusted exponent greater than or equal to <em>Emin</em>.
Return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> if the argument is zero, subnormal, infinite or a
NaN.  Note, the term <em>normal</em> is used here in a different sense with
the <a class="reference internal" href="#decimal.Decimal.normalize" title="decimal.Decimal.normalize"><code class="xref py py-meth docutils literal notranslate"><span class="pre">normalize()</span></code></a> method which is used to create canonical values.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_qnan">
<code class="descname">is_qnan</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_qnan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a quiet NaN, and
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_signed">
<code class="descname">is_signed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_signed" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument has a negative sign and
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.  Note that zeros and NaNs can both carry signs.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_snan">
<code class="descname">is_snan</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_snan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a signaling NaN and <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>
otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_subnormal">
<code class="descname">is_subnormal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_subnormal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is subnormal, and <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>
otherwise. A number is subnormal is if it is nonzero, finite, and has an
adjusted exponent less than <em>Emin</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.is_zero">
<code class="descname">is_zero</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.is_zero" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the argument is a (positive or negative) zero and
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.ln">
<code class="descname">ln</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.ln" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the natural (base e) logarithm of the operand.  The result is
correctly rounded using the <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code> rounding mode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.log10">
<code class="descname">log10</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.log10" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the base ten logarithm of the operand.  The result is correctly
rounded using the <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code> rounding mode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.logb">
<code class="descname">logb</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.logb" title="Permalink to this definition">¶</a></dt>
<dd><p>For a nonzero number, return the adjusted exponent of its operand as a
<a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance.  If the operand is a zero then
<code class="docutils literal notranslate"><span class="pre">Decimal('-Infinity')</span></code> is returned and the <a class="reference internal" href="#decimal.DivisionByZero" title="decimal.DivisionByZero"><code class="xref py py-const docutils literal notranslate"><span class="pre">DivisionByZero</span></code></a> flag
is raised.  If the operand is an infinity then <code class="docutils literal notranslate"><span class="pre">Decimal('Infinity')</span></code> is
returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.logical_and">
<code class="descname">logical_and</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.logical_and" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#decimal.Decimal.logical_and" title="decimal.Decimal.logical_and"><code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_and()</span></code></a> is a logical operation which takes two <em>logical
operands</em> (see <a class="reference internal" href="#logical-operands-label"><span class="std std-ref">Logical operands</span></a>).  The result is the
digit-wise <code class="docutils literal notranslate"><span class="pre">and</span></code> of the two operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.logical_invert">
<code class="descname">logical_invert</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.logical_invert" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#decimal.Decimal.logical_invert" title="decimal.Decimal.logical_invert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_invert()</span></code></a> is a logical operation.  The
result is the digit-wise inversion of the operand.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.logical_or">
<code class="descname">logical_or</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.logical_or" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#decimal.Decimal.logical_or" title="decimal.Decimal.logical_or"><code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_or()</span></code></a> is a logical operation which takes two <em>logical
operands</em> (see <a class="reference internal" href="#logical-operands-label"><span class="std std-ref">Logical operands</span></a>).  The result is the
digit-wise <code class="docutils literal notranslate"><span class="pre">or</span></code> of the two operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.logical_xor">
<code class="descname">logical_xor</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.logical_xor" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#decimal.Decimal.logical_xor" title="decimal.Decimal.logical_xor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_xor()</span></code></a> is a logical operation which takes two <em>logical
operands</em> (see <a class="reference internal" href="#logical-operands-label"><span class="std std-ref">Logical operands</span></a>).  The result is the
digit-wise exclusive or of the two operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.max">
<code class="descname">max</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.max" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">max(self,</span> <span class="pre">other)</span></code> except that the context rounding rule is applied
before returning and that <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> values are either signaled or
ignored (depending on the context and whether they are signaling or
quiet).</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.max_mag">
<code class="descname">max_mag</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.max_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#decimal.Decimal.max" title="decimal.Decimal.max"><code class="xref py py-meth docutils literal notranslate"><span class="pre">max()</span></code></a> method, but the comparison is done using the
absolute values of the operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.min">
<code class="descname">min</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.min" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">min(self,</span> <span class="pre">other)</span></code> except that the context rounding rule is applied
before returning and that <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> values are either signaled or
ignored (depending on the context and whether they are signaling or
quiet).</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.min_mag">
<code class="descname">min_mag</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.min_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#decimal.Decimal.min" title="decimal.Decimal.min"><code class="xref py py-meth docutils literal notranslate"><span class="pre">min()</span></code></a> method, but the comparison is done using the
absolute values of the operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.next_minus">
<code class="descname">next_minus</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.next_minus" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the largest number representable in the given context (or in the
current thread’s context if no context is given) that is smaller than the
given operand.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.next_plus">
<code class="descname">next_plus</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.next_plus" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the smallest number representable in the given context (or in the
current thread’s context if no context is given) that is larger than the
given operand.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.next_toward">
<code class="descname">next_toward</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.next_toward" title="Permalink to this definition">¶</a></dt>
<dd><p>If the two operands are unequal, return the number closest to the first
operand in the direction of the second operand.  If both operands are
numerically equal, return a copy of the first operand with the sign set to
be the same as the sign of the second operand.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.normalize">
<code class="descname">normalize</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.normalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Normalize the number by stripping the rightmost trailing zeros and
converting any result equal to <code class="xref py py-const docutils literal notranslate"><span class="pre">Decimal('0')</span></code> to
<code class="xref py py-const docutils literal notranslate"><span class="pre">Decimal('0e0')</span></code>. Used for producing canonical values for attributes
of an equivalence class. For example, <code class="docutils literal notranslate"><span class="pre">Decimal('32.100')</span></code> and
<code class="docutils literal notranslate"><span class="pre">Decimal('0.321000e+2')</span></code> both normalize to the equivalent value
<code class="docutils literal notranslate"><span class="pre">Decimal('32.1')</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.number_class">
<code class="descname">number_class</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.number_class" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string describing the <em>class</em> of the operand.  The returned value
is one of the following ten strings.</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">&quot;-Infinity&quot;</span></code>, indicating that the operand is negative infinity.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;-Normal&quot;</span></code>, indicating that the operand is a negative normal number.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;-Subnormal&quot;</span></code>, indicating that the operand is negative and subnormal.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;-Zero&quot;</span></code>, indicating that the operand is a negative zero.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;+Zero&quot;</span></code>, indicating that the operand is a positive zero.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;+Subnormal&quot;</span></code>, indicating that the operand is positive and subnormal.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;+Normal&quot;</span></code>, indicating that the operand is a positive normal number.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;+Infinity&quot;</span></code>, indicating that the operand is positive infinity.</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;NaN&quot;</span></code>, indicating that the operand is a quiet NaN (Not a Number).</li>
<li><code class="docutils literal notranslate"><span class="pre">&quot;sNaN&quot;</span></code>, indicating that the operand is a signaling NaN.</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.quantize">
<code class="descname">quantize</code><span class="sig-paren">(</span><em>exp</em><span class="optional">[</span>, <em>rounding</em><span class="optional">[</span>, <em>context</em><span class="optional">[</span>, <em>watchexp</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.quantize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a value equal to the first operand after rounding and having the
exponent of the second operand.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.41421356&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.000&#39;</span><span class="p">))</span>
<span class="go">Decimal(&#39;1.414&#39;)</span>
</pre></div>
</div>
<p>Unlike other operations, if the length of the coefficient after the
quantize operation would be greater than precision, then an
<a class="reference internal" href="#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-const docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a> is signaled. This guarantees that, unless there
is an error condition, the quantized exponent is always equal to that of
the right-hand operand.</p>
<p>Also unlike other operations, quantize never signals Underflow, even if
the result is subnormal and inexact.</p>
<p>If the exponent of the second operand is larger than that of the first
then rounding may be necessary.  In this case, the rounding mode is
determined by the <code class="docutils literal notranslate"><span class="pre">rounding</span></code> argument if given, else by the given
<code class="docutils literal notranslate"><span class="pre">context</span></code> argument; if neither argument is given the rounding mode of
the current thread’s context is used.</p>
<p>If <em>watchexp</em> is set (default), then an error is returned whenever the
resulting exponent is greater than <code class="xref py py-attr docutils literal notranslate"><span class="pre">Emax</span></code> or less than
<code class="xref py py-attr docutils literal notranslate"><span class="pre">Etiny</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.radix">
<code class="descname">radix</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.radix" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">Decimal(10)</span></code>, the radix (base) in which the <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>
class does all its arithmetic.  Included for compatibility with the
specification.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.remainder_near">
<code class="descname">remainder_near</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.remainder_near" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the remainder from dividing <em>self</em> by <em>other</em>.  This differs from
<code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">%</span> <span class="pre">other</span></code> in that the sign of the remainder is chosen so as to
minimize its absolute value.  More precisely, the return value is
<code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">-</span> <span class="pre">n</span> <span class="pre">*</span> <span class="pre">other</span></code> where <code class="docutils literal notranslate"><span class="pre">n</span></code> is the integer nearest to the exact
value of <code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">/</span> <span class="pre">other</span></code>, and if two integers are equally near then the
even one is chosen.</p>
<p>If the result is zero then its sign will be the sign of <em>self</em>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">18</span><span class="p">)</span><span class="o">.</span><span class="n">remainder_near</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">Decimal(&#39;-2&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">25</span><span class="p">)</span><span class="o">.</span><span class="n">remainder_near</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">Decimal(&#39;5&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">35</span><span class="p">)</span><span class="o">.</span><span class="n">remainder_near</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="go">Decimal(&#39;-5&#39;)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.rotate">
<code class="descname">rotate</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.rotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the result of rotating the digits of the first operand by an amount
specified by the second operand.  The second operand must be an integer in
the range -precision through precision.  The absolute value of the second
operand gives the number of places to rotate.  If the second operand is
positive then rotation is to the left; otherwise rotation is to the right.
The coefficient of the first operand is padded on the left with zeros to
length precision if necessary.  The sign and exponent of the first operand
are unchanged.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.same_quantum">
<code class="descname">same_quantum</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.same_quantum" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether self and other have the same exponent or whether both are
<code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.scaleb">
<code class="descname">scaleb</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.scaleb" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the first operand with exponent adjusted by the second.
Equivalently, return the first operand multiplied by <code class="docutils literal notranslate"><span class="pre">10**other</span></code>.  The
second operand must be an integer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.shift">
<code class="descname">shift</code><span class="sig-paren">(</span><em>other</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.shift" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the result of shifting the digits of the first operand by an amount
specified by the second operand.  The second operand must be an integer in
the range -precision through precision.  The absolute value of the second
operand gives the number of places to shift.  If the second operand is
positive then the shift is to the left; otherwise the shift is to the
right.  Digits shifted into the coefficient are zeros.  The sign and
exponent of the first operand are unchanged.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.sqrt">
<code class="descname">sqrt</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.sqrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the square root of the argument to full precision.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.to_eng_string">
<code class="descname">to_eng_string</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.to_eng_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert to a string, using engineering notation if an exponent is needed.</p>
<p>Engineering notation has an exponent which is a multiple of 3.  This
can leave up to 3 digits to the left of the decimal place and may
require the addition of either one or two trailing zeros.</p>
<p>For example, this converts <code class="docutils literal notranslate"><span class="pre">Decimal('123E+1')</span></code> to <code class="docutils literal notranslate"><span class="pre">Decimal('1.23E+3')</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.to_integral">
<code class="descname">to_integral</code><span class="sig-paren">(</span><span class="optional">[</span><em>rounding</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.to_integral" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#decimal.Decimal.to_integral_value" title="decimal.Decimal.to_integral_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">to_integral_value()</span></code></a> method.  The <code class="docutils literal notranslate"><span class="pre">to_integral</span></code>
name has been kept for compatibility with older versions.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.to_integral_exact">
<code class="descname">to_integral_exact</code><span class="sig-paren">(</span><span class="optional">[</span><em>rounding</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.to_integral_exact" title="Permalink to this definition">¶</a></dt>
<dd><p>Round to the nearest integer, signaling <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-const docutils literal notranslate"><span class="pre">Inexact</span></code></a> or
<a class="reference internal" href="#decimal.Rounded" title="decimal.Rounded"><code class="xref py py-const docutils literal notranslate"><span class="pre">Rounded</span></code></a> as appropriate if rounding occurs.  The rounding mode is
determined by the <code class="docutils literal notranslate"><span class="pre">rounding</span></code> parameter if given, else by the given
<code class="docutils literal notranslate"><span class="pre">context</span></code>.  If neither parameter is given then the rounding mode of the
current context is used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Decimal.to_integral_value">
<code class="descname">to_integral_value</code><span class="sig-paren">(</span><span class="optional">[</span><em>rounding</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Decimal.to_integral_value" title="Permalink to this definition">¶</a></dt>
<dd><p>Round to the nearest integer without signaling <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-const docutils literal notranslate"><span class="pre">Inexact</span></code></a> or
<a class="reference internal" href="#decimal.Rounded" title="decimal.Rounded"><code class="xref py py-const docutils literal notranslate"><span class="pre">Rounded</span></code></a>.  If given, applies <em>rounding</em>; otherwise, uses the
rounding method in either the supplied <em>context</em> or the current context.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>renamed from <code class="docutils literal notranslate"><span class="pre">to_integral</span></code> to <code class="docutils literal notranslate"><span class="pre">to_integral_value</span></code>.  The old name
remains valid for compatibility.</p>
</div>
</dd></dl>

</dd></dl>

<div class="section" id="logical-operands">
<span id="logical-operands-label"></span><h3>9.4.2.1. Logical operands<a class="headerlink" href="#logical-operands" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_and()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_invert()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_or()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">logical_xor()</span></code> methods expect their arguments to be <em>logical
operands</em>.  A <em>logical operand</em> is a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance whose
exponent and sign are both zero, and whose digits are all either
<code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code>.</p>
</div>
</div>
<div class="section" id="context-objects">
<span id="decimal-context"></span><h2>9.4.3. Context objects<a class="headerlink" href="#context-objects" title="Permalink to this headline">¶</a></h2>
<p>Contexts are environments for arithmetic operations.  They govern precision, set
rules for rounding, determine which signals are treated as exceptions, and limit
the range for exponents.</p>
<p>Each thread has its own current context which is accessed or changed using the
<a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a> and <a class="reference internal" href="#decimal.setcontext" title="decimal.setcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">setcontext()</span></code></a> functions:</p>
<dl class="function">
<dt id="decimal.getcontext">
<code class="descclassname">decimal.</code><code class="descname">getcontext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.getcontext" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current context for the active thread.</p>
</dd></dl>

<dl class="function">
<dt id="decimal.setcontext">
<code class="descclassname">decimal.</code><code class="descname">setcontext</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.setcontext" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current context for the active thread to <em>c</em>.</p>
</dd></dl>

<p>Beginning with Python 2.5, you can also use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement and
the <a class="reference internal" href="#decimal.localcontext" title="decimal.localcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code></a> function to temporarily change the active context.</p>
<dl class="function">
<dt id="decimal.localcontext">
<code class="descclassname">decimal.</code><code class="descname">localcontext</code><span class="sig-paren">(</span><span class="optional">[</span><em>c</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.localcontext" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a context manager that will set the current context for the active thread
to a copy of <em>c</em> on entry to the with-statement and restore the previous context
when exiting the with-statement. If no context is specified, a copy of the
current context is used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>For example, the following code sets the current decimal precision to 42 places,
performs a calculation, and then automatically restores the previous context:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">localcontext</span>

<span class="k">with</span> <span class="n">localcontext</span><span class="p">()</span> <span class="k">as</span> <span class="n">ctx</span><span class="p">:</span>
    <span class="n">ctx</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">42</span>   <span class="c1"># Perform a high precision calculation</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">calculate_something</span><span class="p">()</span>
<span class="n">s</span> <span class="o">=</span> <span class="o">+</span><span class="n">s</span>  <span class="c1"># Round the final result back to the default precision</span>

<span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">BasicContext</span><span class="p">):</span>      <span class="c1"># temporarily use the BasicContext</span>
    <span class="nb">print</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
    <span class="nb">print</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">355</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">113</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<p>New contexts can also be created using the <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> constructor
described below. In addition, the module provides three pre-made contexts:</p>
<dl class="class">
<dt id="decimal.BasicContext">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">BasicContext</code><a class="headerlink" href="#decimal.BasicContext" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a standard context defined by the General Decimal Arithmetic
Specification.  Precision is set to nine.  Rounding is set to
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_UP</span></code>.  All flags are cleared.  All traps are enabled (treated
as exceptions) except <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-const docutils literal notranslate"><span class="pre">Inexact</span></code></a>, <a class="reference internal" href="#decimal.Rounded" title="decimal.Rounded"><code class="xref py py-const docutils literal notranslate"><span class="pre">Rounded</span></code></a>, and
<a class="reference internal" href="#decimal.Subnormal" title="decimal.Subnormal"><code class="xref py py-const docutils literal notranslate"><span class="pre">Subnormal</span></code></a>.</p>
<p>Because many of the traps are enabled, this context is useful for debugging.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.ExtendedContext">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">ExtendedContext</code><a class="headerlink" href="#decimal.ExtendedContext" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a standard context defined by the General Decimal Arithmetic
Specification.  Precision is set to nine.  Rounding is set to
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code>.  All flags are cleared.  No traps are enabled (so that
exceptions are not raised during computations).</p>
<p>Because the traps are disabled, this context is useful for applications that
prefer to have result value of <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code> instead of
raising exceptions.  This allows an application to complete a run in the
presence of conditions that would otherwise halt the program.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.DefaultContext">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">DefaultContext</code><a class="headerlink" href="#decimal.DefaultContext" title="Permalink to this definition">¶</a></dt>
<dd><p>This context is used by the <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> constructor as a prototype for new
contexts.  Changing a field (such a precision) has the effect of changing the
default for new contexts created by the <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> constructor.</p>
<p>This context is most useful in multi-threaded environments.  Changing one of the
fields before threads are started has the effect of setting system-wide
defaults.  Changing the fields after threads have started is not recommended as
it would require thread synchronization to prevent race conditions.</p>
<p>In single threaded environments, it is preferable to not use this context at
all.  Instead, simply create contexts explicitly as described below.</p>
<p>The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
for Overflow, InvalidOperation, and DivisionByZero.</p>
</dd></dl>

<p>In addition to the three supplied contexts, new contexts can be created with the
<a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> constructor.</p>
<dl class="class">
<dt id="decimal.Context">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Context</code><span class="sig-paren">(</span><em>prec=None</em>, <em>rounding=None</em>, <em>traps=None</em>, <em>flags=None</em>, <em>Emin=None</em>, <em>Emax=None</em>, <em>capitals=1</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new context.  If a field is not specified or is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the
default values are copied from the <a class="reference internal" href="#decimal.DefaultContext" title="decimal.DefaultContext"><code class="xref py py-const docutils literal notranslate"><span class="pre">DefaultContext</span></code></a>.  If the <em>flags</em>
field is not specified or is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, all flags are cleared.</p>
<p>The <em>prec</em> field is a positive integer that sets the precision for arithmetic
operations in the context.</p>
<p>The <em>rounding</em> option is one of:</p>
<ul class="simple">
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_CEILING</span></code> (towards <code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code>),</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_DOWN</span></code> (towards zero),</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_FLOOR</span></code> (towards <code class="xref py py-const docutils literal notranslate"><span class="pre">-Infinity</span></code>),</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_DOWN</span></code> (to nearest with ties going towards zero),</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code> (to nearest with ties going to nearest even integer),</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_UP</span></code> (to nearest with ties going away from zero), or</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_UP</span></code> (away from zero).</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_05UP</span></code> (away from zero if last digit after rounding towards zero
would have been 0 or 5; otherwise towards zero)</li>
</ul>
<p>The <em>traps</em> and <em>flags</em> fields list any signals to be set. Generally, new
contexts should only set traps and leave the flags clear.</p>
<p>The <em>Emin</em> and <em>Emax</em> fields are integers specifying the outer limits allowable
for exponents.</p>
<p>The <em>capitals</em> field is either <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code> (the default). If set to
<code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code>, exponents are printed with a capital <code class="xref py py-const docutils literal notranslate"><span class="pre">E</span></code>; otherwise, a
lowercase <code class="xref py py-const docutils literal notranslate"><span class="pre">e</span></code> is used: <code class="xref py py-const docutils literal notranslate"><span class="pre">Decimal('6.02e+23')</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_05UP</span></code> rounding mode was added.</p>
</div>
<p>The <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> class defines several general purpose methods as well as
a large number of methods for doing arithmetic directly in a given context.
In addition, for each of the <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> methods described above (with
the exception of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">adjusted()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_tuple()</span></code> methods) there is
a corresponding <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> method.  For example, for a <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a>
instance <code class="docutils literal notranslate"><span class="pre">C</span></code> and <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance <code class="docutils literal notranslate"><span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">C.exp(x)</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">x.exp(context=C)</span></code>.  Each <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> method accepts a
Python integer (an instance of <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>) anywhere that a
Decimal instance is accepted.</p>
<dl class="method">
<dt id="decimal.Context.clear_flags">
<code class="descname">clear_flags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.clear_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets all of the flags to <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.copy">
<code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a duplicate of the context.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.copy_decimal">
<code class="descname">copy_decimal</code><span class="sig-paren">(</span><em>num</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.copy_decimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the Decimal instance num.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.create_decimal">
<code class="descname">create_decimal</code><span class="sig-paren">(</span><em>num</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.create_decimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new Decimal instance from <em>num</em> but using <em>self</em> as
context. Unlike the <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> constructor, the context precision,
rounding method, flags, and traps are applied to the conversion.</p>
<p>This is useful because constants are often given to a greater precision
than is needed by the application.  Another benefit is that rounding
immediately eliminates unintended effects from digits beyond the current
precision. In the following example, using unrounded inputs means that
adding zero to a sum can change the result:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.4445&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.0023&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;4.45&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.4445&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.0023&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;4.44&#39;)</span>
</pre></div>
</div>
<p>This method implements the to-number operation of the IBM specification.
If the argument is a string, no leading or trailing whitespace is
permitted.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.create_decimal_from_float">
<code class="descname">create_decimal_from_float</code><span class="sig-paren">(</span><em>f</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.create_decimal_from_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new Decimal instance from a float <em>f</em> but rounding using <em>self</em>
as the context.  Unlike the <a class="reference internal" href="#decimal.Decimal.from_float" title="decimal.Decimal.from_float"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Decimal.from_float()</span></code></a> class method,
the context precision, rounding method, flags, and traps are applied to
the conversion.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">context</span> <span class="o">=</span> <span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">rounding</span><span class="o">=</span><span class="n">ROUND_DOWN</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">create_decimal_from_float</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.1415&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span> <span class="o">=</span> <span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">traps</span><span class="o">=</span><span class="p">[</span><span class="n">Inexact</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">create_decimal_from_float</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">Inexact</span>: <span class="n">None</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.Etiny">
<code class="descname">Etiny</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.Etiny" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a value equal to <code class="docutils literal notranslate"><span class="pre">Emin</span> <span class="pre">-</span> <span class="pre">prec</span> <span class="pre">+</span> <span class="pre">1</span></code> which is the minimum exponent
value for subnormal results.  When underflow occurs, the exponent is set
to <a class="reference internal" href="#decimal.Context.Etiny" title="decimal.Context.Etiny"><code class="xref py py-const docutils literal notranslate"><span class="pre">Etiny</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.Etop">
<code class="descname">Etop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.Etop" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a value equal to <code class="docutils literal notranslate"><span class="pre">Emax</span> <span class="pre">-</span> <span class="pre">prec</span> <span class="pre">+</span> <span class="pre">1</span></code>.</p>
</dd></dl>

<p>The usual approach to working with decimals is to create <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>
instances and then apply arithmetic operations which take place within the
current context for the active thread.  An alternative approach is to use
context methods for calculating within a specific context.  The methods are
similar to those for the <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class and are only briefly
recounted here.</p>
<dl class="method">
<dt id="decimal.Context.abs">
<code class="descname">abs</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.abs" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the absolute value of <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sum of <em>x</em> and <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.canonical">
<code class="descname">canonical</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.canonical" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the same Decimal object <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.compare">
<code class="descname">compare</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.compare" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares <em>x</em> and <em>y</em> numerically.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.compare_signal">
<code class="descname">compare_signal</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.compare_signal" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares the values of the two operands numerically.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.compare_total">
<code class="descname">compare_total</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.compare_total" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares two operands using their abstract representation.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.compare_total_mag">
<code class="descname">compare_total_mag</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.compare_total_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares two operands using their abstract representation, ignoring sign.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.copy_abs">
<code class="descname">copy_abs</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.copy_abs" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a copy of <em>x</em> with the sign set to 0.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.copy_negate">
<code class="descname">copy_negate</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.copy_negate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a copy of <em>x</em> with the sign inverted.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.copy_sign">
<code class="descname">copy_sign</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.copy_sign" title="Permalink to this definition">¶</a></dt>
<dd><p>Copies the sign from <em>y</em> to <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.divide">
<code class="descname">divide</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.divide" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>x</em> divided by <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.divide_int">
<code class="descname">divide_int</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.divide_int" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>x</em> divided by <em>y</em>, truncated to an integer.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.divmod">
<code class="descname">divmod</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.divmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Divides two numbers and returns the integer part of the result.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.exp">
<code class="descname">exp</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.exp" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <cite>e ** x</cite>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.fma">
<code class="descname">fma</code><span class="sig-paren">(</span><em>x</em>, <em>y</em>, <em>z</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.fma" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <em>x</em> multiplied by <em>y</em>, plus <em>z</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_canonical">
<code class="descname">is_canonical</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_canonical" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is canonical; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_finite">
<code class="descname">is_finite</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_finite" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is finite; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_infinite">
<code class="descname">is_infinite</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_infinite" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is infinite; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_nan">
<code class="descname">is_nan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_nan" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a qNaN or sNaN; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_normal">
<code class="descname">is_normal</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_normal" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a normal number; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_qnan">
<code class="descname">is_qnan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_qnan" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a quiet NaN; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_signed">
<code class="descname">is_signed</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_signed" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is negative; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_snan">
<code class="descname">is_snan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_snan" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a signaling NaN; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_subnormal">
<code class="descname">is_subnormal</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_subnormal" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is subnormal; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.is_zero">
<code class="descname">is_zero</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.is_zero" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a zero; otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.ln">
<code class="descname">ln</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.ln" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the natural (base e) logarithm of <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.log10">
<code class="descname">log10</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.log10" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the base 10 logarithm of <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.logb">
<code class="descname">logb</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.logb" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the exponent of the magnitude of the operand’s MSD.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.logical_and">
<code class="descname">logical_and</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.logical_and" title="Permalink to this definition">¶</a></dt>
<dd><p>Applies the logical operation <em>and</em> between each operand’s digits.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.logical_invert">
<code class="descname">logical_invert</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.logical_invert" title="Permalink to this definition">¶</a></dt>
<dd><p>Invert all the digits in <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.logical_or">
<code class="descname">logical_or</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.logical_or" title="Permalink to this definition">¶</a></dt>
<dd><p>Applies the logical operation <em>or</em> between each operand’s digits.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.logical_xor">
<code class="descname">logical_xor</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.logical_xor" title="Permalink to this definition">¶</a></dt>
<dd><p>Applies the logical operation <em>xor</em> between each operand’s digits.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.max">
<code class="descname">max</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.max" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares two values numerically and returns the maximum.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.max_mag">
<code class="descname">max_mag</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.max_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares the values numerically with their sign ignored.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.min">
<code class="descname">min</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.min" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares two values numerically and returns the minimum.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.min_mag">
<code class="descname">min_mag</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.min_mag" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares the values numerically with their sign ignored.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.minus">
<code class="descname">minus</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.minus" title="Permalink to this definition">¶</a></dt>
<dd><p>Minus corresponds to the unary prefix minus operator in Python.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.multiply">
<code class="descname">multiply</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.multiply" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the product of <em>x</em> and <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.next_minus">
<code class="descname">next_minus</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.next_minus" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the largest representable number smaller than <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.next_plus">
<code class="descname">next_plus</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.next_plus" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the smallest representable number larger than <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.next_toward">
<code class="descname">next_toward</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.next_toward" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number closest to <em>x</em>, in direction towards <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.normalize">
<code class="descname">normalize</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.normalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Reduces <em>x</em> to its simplest form.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.number_class">
<code class="descname">number_class</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.number_class" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an indication of the class of <em>x</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.plus">
<code class="descname">plus</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.plus" title="Permalink to this definition">¶</a></dt>
<dd><p>Plus corresponds to the unary prefix plus operator in Python.  This
operation applies the context precision and rounding, so it is <em>not</em> an
identity operation.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.power">
<code class="descname">power</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.power" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">x</span></code> to the power of <code class="docutils literal notranslate"><span class="pre">y</span></code>, reduced modulo <code class="docutils literal notranslate"><span class="pre">modulo</span></code> if given.</p>
<p>With two arguments, compute <code class="docutils literal notranslate"><span class="pre">x**y</span></code>.  If <code class="docutils literal notranslate"><span class="pre">x</span></code> is negative then <code class="docutils literal notranslate"><span class="pre">y</span></code>
must be integral.  The result will be inexact unless <code class="docutils literal notranslate"><span class="pre">y</span></code> is integral and
the result is finite and can be expressed exactly in ‘precision’ digits.
The result should always be correctly rounded, using the rounding mode of
the current thread’s context.</p>
<p>With three arguments, compute <code class="docutils literal notranslate"><span class="pre">(x**y)</span> <span class="pre">%</span> <span class="pre">modulo</span></code>.  For the three argument
form, the following restrictions on the arguments hold:</p>
<blockquote>
<div><ul class="simple">
<li>all three arguments must be integral</li>
<li><code class="docutils literal notranslate"><span class="pre">y</span></code> must be nonnegative</li>
<li>at least one of <code class="docutils literal notranslate"><span class="pre">x</span></code> or <code class="docutils literal notranslate"><span class="pre">y</span></code> must be nonzero</li>
<li><code class="docutils literal notranslate"><span class="pre">modulo</span></code> must be nonzero and have at most ‘precision’ digits</li>
</ul>
</div></blockquote>
<p>The value resulting from <code class="docutils literal notranslate"><span class="pre">Context.power(x,</span> <span class="pre">y,</span> <span class="pre">modulo)</span></code> is
equal to the value that would be obtained by computing <code class="docutils literal notranslate"><span class="pre">(x**y)</span>
<span class="pre">%</span> <span class="pre">modulo</span></code> with unbounded precision, but is computed more
efficiently.  The exponent of the result is zero, regardless of
the exponents of <code class="docutils literal notranslate"><span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">modulo</span></code>.  The result is
always exact.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><code class="docutils literal notranslate"><span class="pre">y</span></code> may now be nonintegral in <code class="docutils literal notranslate"><span class="pre">x**y</span></code>.
Stricter requirements for the three-argument version.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.quantize">
<code class="descname">quantize</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.quantize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a value equal to <em>x</em> (rounded), having the exponent of <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.radix">
<code class="descname">radix</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.radix" title="Permalink to this definition">¶</a></dt>
<dd><p>Just returns 10, as this is Decimal, :)</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.remainder">
<code class="descname">remainder</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.remainder" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the remainder from integer division.</p>
<p>The sign of the result, if non-zero, is the same as that of the original
dividend.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.remainder_near">
<code class="descname">remainder_near</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.remainder_near" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span> <span class="pre">*</span> <span class="pre">n</span></code>, where <em>n</em> is the integer nearest the exact value
of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></code> (if the result is 0 then its sign will be the sign of <em>x</em>).</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.rotate">
<code class="descname">rotate</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.rotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a rotated copy of <em>x</em>, <em>y</em> times.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.same_quantum">
<code class="descname">same_quantum</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.same_quantum" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the two operands have the same exponent.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.scaleb">
<code class="descname">scaleb</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.scaleb" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the first operand after adding the second value its exp.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.shift">
<code class="descname">shift</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.shift" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a shifted copy of <em>x</em>, <em>y</em> times.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.sqrt">
<code class="descname">sqrt</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.sqrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Square root of a non-negative number to context precision.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.subtract">
<code class="descname">subtract</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.subtract" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the difference between <em>x</em> and <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.to_eng_string">
<code class="descname">to_eng_string</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.to_eng_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert to a string, using engineering notation if an exponent is needed.</p>
<p>Engineering notation has an exponent which is a multiple of 3.  This
can leave up to 3 digits to the left of the decimal place and may
require the addition of either one or two trailing zeros.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.to_integral_exact">
<code class="descname">to_integral_exact</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.to_integral_exact" title="Permalink to this definition">¶</a></dt>
<dd><p>Rounds to an integer.</p>
</dd></dl>

<dl class="method">
<dt id="decimal.Context.to_sci_string">
<code class="descname">to_sci_string</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#decimal.Context.to_sci_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts a number to a string using scientific notation.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="signals">
<span id="decimal-signals"></span><h2>9.4.4. Signals<a class="headerlink" href="#signals" title="Permalink to this headline">¶</a></h2>
<p>Signals represent conditions that arise during computation. Each corresponds to
one context flag and one context trap enabler.</p>
<p>The context flag is set whenever the condition is encountered. After the
computation, flags may be checked for informational purposes (for instance, to
determine whether a computation was exact). After checking the flags, be sure to
clear all flags before starting the next computation.</p>
<p>If the context’s trap enabler is set for the signal, then the condition causes a
Python exception to be raised.  For example, if the <a class="reference internal" href="#decimal.DivisionByZero" title="decimal.DivisionByZero"><code class="xref py py-class docutils literal notranslate"><span class="pre">DivisionByZero</span></code></a> trap
is set, then a <a class="reference internal" href="#decimal.DivisionByZero" title="decimal.DivisionByZero"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DivisionByZero</span></code></a> exception is raised upon encountering the
condition.</p>
<dl class="class">
<dt id="decimal.Clamped">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Clamped</code><a class="headerlink" href="#decimal.Clamped" title="Permalink to this definition">¶</a></dt>
<dd><p>Altered an exponent to fit representation constraints.</p>
<p>Typically, clamping occurs when an exponent falls outside the context’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">Emin</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">Emax</span></code> limits.  If possible, the exponent is reduced to
fit by adding zeros to the coefficient.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.DecimalException">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">DecimalException</code><a class="headerlink" href="#decimal.DecimalException" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for other signals and a subclass of <a class="reference internal" href="exceptions.html#exceptions.ArithmeticError" title="exceptions.ArithmeticError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ArithmeticError</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.DivisionByZero">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">DivisionByZero</code><a class="headerlink" href="#decimal.DivisionByZero" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals the division of a non-infinite number by zero.</p>
<p>Can occur with division, modulo division, or when raising a number to a negative
power.  If this signal is not trapped, returns <code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code> or
<code class="xref py py-const docutils literal notranslate"><span class="pre">-Infinity</span></code> with the sign determined by the inputs to the calculation.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.Inexact">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Inexact</code><a class="headerlink" href="#decimal.Inexact" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates that rounding occurred and the result is not exact.</p>
<p>Signals when non-zero digits were discarded during rounding. The rounded result
is returned.  The signal flag or trap is used to detect when results are
inexact.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.InvalidOperation">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">InvalidOperation</code><a class="headerlink" href="#decimal.InvalidOperation" title="Permalink to this definition">¶</a></dt>
<dd><p>An invalid operation was performed.</p>
<p>Indicates that an operation was requested that does not make sense. If not
trapped, returns <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>.  Possible causes include:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Infinity</span> <span class="o">-</span> <span class="n">Infinity</span>
<span class="mi">0</span> <span class="o">*</span> <span class="n">Infinity</span>
<span class="n">Infinity</span> <span class="o">/</span> <span class="n">Infinity</span>
<span class="n">x</span> <span class="o">%</span> <span class="mi">0</span>
<span class="n">Infinity</span> <span class="o">%</span> <span class="n">x</span>
<span class="n">x</span><span class="o">.</span><span class="n">_rescale</span><span class="p">(</span> <span class="n">non</span><span class="o">-</span><span class="n">integer</span> <span class="p">)</span>
<span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">x</span><span class="p">)</span> <span class="ow">and</span> <span class="n">x</span> <span class="o">&gt;</span> <span class="mi">0</span>
<span class="mi">0</span> <span class="o">**</span> <span class="mi">0</span>
<span class="n">x</span> <span class="o">**</span> <span class="p">(</span><span class="n">non</span><span class="o">-</span><span class="n">integer</span><span class="p">)</span>
<span class="n">x</span> <span class="o">**</span> <span class="n">Infinity</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="decimal.Overflow">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Overflow</code><a class="headerlink" href="#decimal.Overflow" title="Permalink to this definition">¶</a></dt>
<dd><p>Numerical overflow.</p>
<p>Indicates the exponent is larger than <code class="xref py py-attr docutils literal notranslate"><span class="pre">Emax</span></code> after rounding has
occurred.  If not trapped, the result depends on the rounding mode, either
pulling inward to the largest representable finite number or rounding outward
to <code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code>.  In either case, <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-class docutils literal notranslate"><span class="pre">Inexact</span></code></a> and <a class="reference internal" href="#decimal.Rounded" title="decimal.Rounded"><code class="xref py py-class docutils literal notranslate"><span class="pre">Rounded</span></code></a>
are also signaled.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.Rounded">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Rounded</code><a class="headerlink" href="#decimal.Rounded" title="Permalink to this definition">¶</a></dt>
<dd><p>Rounding occurred though possibly no information was lost.</p>
<p>Signaled whenever rounding discards digits; even if those digits are zero
(such as rounding <code class="xref py py-const docutils literal notranslate"><span class="pre">5.00</span></code> to <code class="xref py py-const docutils literal notranslate"><span class="pre">5.0</span></code>).  If not trapped, returns
the result unchanged.  This signal is used to detect loss of significant
digits.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.Subnormal">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Subnormal</code><a class="headerlink" href="#decimal.Subnormal" title="Permalink to this definition">¶</a></dt>
<dd><p>Exponent was lower than <code class="xref py py-attr docutils literal notranslate"><span class="pre">Emin</span></code> prior to rounding.</p>
<p>Occurs when an operation result is subnormal (the exponent is too small). If
not trapped, returns the result unchanged.</p>
</dd></dl>

<dl class="class">
<dt id="decimal.Underflow">
<em class="property">class </em><code class="descclassname">decimal.</code><code class="descname">Underflow</code><a class="headerlink" href="#decimal.Underflow" title="Permalink to this definition">¶</a></dt>
<dd><p>Numerical underflow with result rounded to zero.</p>
<p>Occurs when a subnormal result is pushed to zero by rounding. <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-class docutils literal notranslate"><span class="pre">Inexact</span></code></a>
and <a class="reference internal" href="#decimal.Subnormal" title="decimal.Subnormal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Subnormal</span></code></a> are also signaled.</p>
</dd></dl>

<p>The following table summarizes the hierarchy of signals:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">exceptions</span><span class="o">.</span><span class="n">ArithmeticError</span><span class="p">(</span><span class="n">exceptions</span><span class="o">.</span><span class="n">StandardError</span><span class="p">)</span>
    <span class="n">DecimalException</span>
        <span class="n">Clamped</span>
        <span class="n">DivisionByZero</span><span class="p">(</span><span class="n">DecimalException</span><span class="p">,</span> <span class="n">exceptions</span><span class="o">.</span><span class="n">ZeroDivisionError</span><span class="p">)</span>
        <span class="n">Inexact</span>
            <span class="n">Overflow</span><span class="p">(</span><span class="n">Inexact</span><span class="p">,</span> <span class="n">Rounded</span><span class="p">)</span>
            <span class="n">Underflow</span><span class="p">(</span><span class="n">Inexact</span><span class="p">,</span> <span class="n">Rounded</span><span class="p">,</span> <span class="n">Subnormal</span><span class="p">)</span>
        <span class="n">InvalidOperation</span>
        <span class="n">Rounded</span>
        <span class="n">Subnormal</span>
</pre></div>
</div>
</div>
<div class="section" id="floating-point-notes">
<span id="decimal-notes"></span><h2>9.4.5. Floating Point Notes<a class="headerlink" href="#floating-point-notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="mitigating-round-off-error-with-increased-precision">
<h3>9.4.5.1. Mitigating round-off error with increased precision<a class="headerlink" href="#mitigating-round-off-error-with-increased-precision" title="Permalink to this headline">¶</a></h3>
<p>The use of decimal floating point eliminates decimal representation error
(making it possible to represent <code class="xref py py-const docutils literal notranslate"><span class="pre">0.1</span></code> exactly); however, some operations
can still incur round-off error when non-zero digits exceed the fixed precision.</p>
<p>The effects of round-off error can be amplified by the addition or subtraction
of nearly offsetting quantities resulting in loss of significance.  Knuth
provides two instructive examples where rounded floating point arithmetic with
insufficient precision causes the breakdown of the associative and distributive
properties of addition:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="go"># Examples from Seminumerical Algorithms, Section 4.2.2.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">getcontext</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">8</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="p">,</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">11111113</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">11111111</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;7.51111111&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">u</span> <span class="o">+</span> <span class="n">v</span><span class="p">)</span> <span class="o">+</span> <span class="n">w</span>
<span class="go">Decimal(&#39;9.5111111&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">+</span> <span class="p">(</span><span class="n">v</span> <span class="o">+</span> <span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;10&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="p">,</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">20000</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">6</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;6.0000003&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">u</span><span class="o">*</span><span class="n">v</span><span class="p">)</span> <span class="o">+</span> <span class="p">(</span><span class="n">u</span><span class="o">*</span><span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.01&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">*</span> <span class="p">(</span><span class="n">v</span><span class="o">+</span><span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.0060000&#39;)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module makes it possible to restore the identities by
expanding the precision sufficiently to avoid loss of significance:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="p">,</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">11111113</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">11111111</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;7.51111111&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">u</span> <span class="o">+</span> <span class="n">v</span><span class="p">)</span> <span class="o">+</span> <span class="n">w</span>
<span class="go">Decimal(&#39;9.51111111&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">+</span> <span class="p">(</span><span class="n">v</span> <span class="o">+</span> <span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;9.51111111&#39;)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span><span class="p">,</span> <span class="n">v</span><span class="p">,</span> <span class="n">w</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">20000</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="o">-</span><span class="mi">6</span><span class="p">),</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;6.0000003&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">u</span><span class="o">*</span><span class="n">v</span><span class="p">)</span> <span class="o">+</span> <span class="p">(</span><span class="n">u</span><span class="o">*</span><span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.0060000&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">*</span> <span class="p">(</span><span class="n">v</span><span class="o">+</span><span class="n">w</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.0060000&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="special-values">
<h3>9.4.5.2. Special values<a class="headerlink" href="#special-values" title="Permalink to this headline">¶</a></h3>
<p>The number system for the <a class="reference internal" href="#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides special values
including <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">sNaN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">-Infinity</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">Infinity</span></code>,
and two zeros, <code class="xref py py-const docutils literal notranslate"><span class="pre">+0</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">-0</span></code>.</p>
<p>Infinities can be constructed directly with:  <code class="docutils literal notranslate"><span class="pre">Decimal('Infinity')</span></code>. Also,
they can arise from dividing by zero when the <a class="reference internal" href="#decimal.DivisionByZero" title="decimal.DivisionByZero"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DivisionByZero</span></code></a> signal is
not trapped.  Likewise, when the <a class="reference internal" href="#decimal.Overflow" title="decimal.Overflow"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Overflow</span></code></a> signal is not trapped, infinity
can result from rounding beyond the limits of the largest representable number.</p>
<p>The infinities are signed (affine) and can be used in arithmetic operations
where they get treated as very large, indeterminate numbers.  For instance,
adding a constant to infinity gives another infinite result.</p>
<p>Some operations are indeterminate and return <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>, or if the
<a class="reference internal" href="#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a> signal is trapped, raise an exception.  For example,
<code class="docutils literal notranslate"><span class="pre">0/0</span></code> returns <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> which means “not a number”.  This variety of
<code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> is quiet and, once created, will flow through other computations
always resulting in another <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>.  This behavior can be useful for a
series of computations that occasionally have missing inputs — it allows the
calculation to proceed while flagging specific results as invalid.</p>
<p>A variant is <code class="xref py py-const docutils literal notranslate"><span class="pre">sNaN</span></code> which signals rather than remaining quiet after every
operation.  This is a useful return value when an invalid result needs to
interrupt a calculation for special handling.</p>
<p>The behavior of Python’s comparison operators can be a little surprising where a
<code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> is involved.  A test for equality where one of the operands is a
quiet or signaling <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> always returns <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> (even when doing
<code class="docutils literal notranslate"><span class="pre">Decimal('NaN')==Decimal('NaN')</span></code>), while a test for inequality always returns
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.  An attempt to compare two Decimals using any of the <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> operators will raise the <a class="reference internal" href="#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a> signal
if either operand is a <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code>, and return <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> if this signal is
not trapped.  Note that the General Decimal Arithmetic specification does not
specify the behavior of direct comparisons; these rules for comparisons
involving a <code class="xref py py-const docutils literal notranslate"><span class="pre">NaN</span></code> were taken from the IEEE 854 standard (see Table 3 in
section 5.7).  To ensure strict standards-compliance, use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">compare()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">compare-signal()</span></code> methods instead.</p>
<p>The signed zeros can result from calculations that underflow. They keep the sign
that would have resulted if the calculation had been carried out to greater
precision.  Since their magnitude is zero, both positive and negative zeros are
treated as equal and their sign is informational.</p>
<p>In addition to the two signed zeros which are distinct yet equal, there are
various representations of zero with differing precisions yet equivalent in
value.  This takes a bit of getting used to.  For an eye accustomed to
normalized floating point representations, it is not immediately obvious that
the following calculation returns a value equal to zero:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;Infinity&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;0E-1000000026&#39;)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="working-with-threads">
<span id="decimal-threads"></span><h2>9.4.6. Working with threads<a class="headerlink" href="#working-with-threads" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a> function accesses a different <a class="reference internal" href="#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> object for
each thread.  Having separate thread contexts means that threads may make
changes (such as <code class="docutils literal notranslate"><span class="pre">getcontext.prec=10</span></code>) without interfering with other threads.</p>
<p>Likewise, the <a class="reference internal" href="#decimal.setcontext" title="decimal.setcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">setcontext()</span></code></a> function automatically assigns its target to
the current thread.</p>
<p>If <a class="reference internal" href="#decimal.setcontext" title="decimal.setcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">setcontext()</span></code></a> has not been called before <a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a>, then
<a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a> will automatically create a new context for use in the
current thread.</p>
<p>The new context is copied from a prototype context called <em>DefaultContext</em>. To
control the defaults so that each thread will use the same values throughout the
application, directly modify the <em>DefaultContext</em> object. This should be done
<em>before</em> any threads are started so that there won’t be a race condition between
threads calling <a class="reference internal" href="#decimal.getcontext" title="decimal.getcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code></a>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Set applicationwide defaults for all threads about to be launched</span>
<span class="n">DefaultContext</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">12</span>
<span class="n">DefaultContext</span><span class="o">.</span><span class="n">rounding</span> <span class="o">=</span> <span class="n">ROUND_DOWN</span>
<span class="n">DefaultContext</span><span class="o">.</span><span class="n">traps</span> <span class="o">=</span> <span class="n">ExtendedContext</span><span class="o">.</span><span class="n">traps</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
<span class="n">DefaultContext</span><span class="o">.</span><span class="n">traps</span><span class="p">[</span><span class="n">InvalidOperation</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">setcontext</span><span class="p">(</span><span class="n">DefaultContext</span><span class="p">)</span>

<span class="c1"># Afterwards, the threads can be started</span>
<span class="n">t1</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">t2</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="n">t3</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
 <span class="o">.</span> <span class="o">.</span> <span class="o">.</span>
</pre></div>
</div>
</div>
<div class="section" id="recipes">
<span id="decimal-recipes"></span><h2>9.4.7. Recipes<a class="headerlink" href="#recipes" title="Permalink to this headline">¶</a></h2>
<p>Here are a few recipes that serve as utility functions and that demonstrate ways
to work with the <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">moneyfmt</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">places</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">curr</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="n">dp</span><span class="o">=</span><span class="s1">&#39;.&#39;</span><span class="p">,</span>
             <span class="n">pos</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="n">neg</span><span class="o">=</span><span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="n">trailneg</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Convert Decimal to a money formatted string.</span>

<span class="sd">    places:  required number of places after the decimal point</span>
<span class="sd">    curr:    optional currency symbol before the sign (may be blank)</span>
<span class="sd">    sep:     optional grouping separator (comma, period, space, or blank)</span>
<span class="sd">    dp:      decimal point indicator (comma or period)</span>
<span class="sd">             only specify as blank when places is zero</span>
<span class="sd">    pos:     optional sign for positive numbers: &#39;+&#39;, space or blank</span>
<span class="sd">    neg:     optional sign for negative numbers: &#39;-&#39;, &#39;(&#39;, space or blank</span>
<span class="sd">    trailneg:optional trailing minus indicator:  &#39;-&#39;, &#39;)&#39;, space or blank</span>

<span class="sd">    &gt;&gt;&gt; d = Decimal(&#39;-1234567.8901&#39;)</span>
<span class="sd">    &gt;&gt;&gt; moneyfmt(d, curr=&#39;$&#39;)</span>
<span class="sd">    &#39;-$1,234,567.89&#39;</span>
<span class="sd">    &gt;&gt;&gt; moneyfmt(d, places=0, sep=&#39;.&#39;, dp=&#39;&#39;, neg=&#39;&#39;, trailneg=&#39;-&#39;)</span>
<span class="sd">    &#39;1.234.568-&#39;</span>
<span class="sd">    &gt;&gt;&gt; moneyfmt(d, curr=&#39;$&#39;, neg=&#39;(&#39;, trailneg=&#39;)&#39;)</span>
<span class="sd">    &#39;($1,234,567.89)&#39;</span>
<span class="sd">    &gt;&gt;&gt; moneyfmt(Decimal(123456789), sep=&#39; &#39;)</span>
<span class="sd">    &#39;123 456 789.00&#39;</span>
<span class="sd">    &gt;&gt;&gt; moneyfmt(Decimal(&#39;-0.02&#39;), neg=&#39;&lt;&#39;, trailneg=&#39;&gt;&#39;)</span>
<span class="sd">    &#39;&lt;0.02&gt;&#39;</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">q</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="o">**</span> <span class="o">-</span><span class="n">places</span>      <span class="c1"># 2 places --&gt; &#39;0.01&#39;</span>
    <span class="n">sign</span><span class="p">,</span> <span class="n">digits</span><span class="p">,</span> <span class="n">exp</span> <span class="o">=</span> <span class="n">value</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">q</span><span class="p">)</span><span class="o">.</span><span class="n">as_tuple</span><span class="p">()</span>
    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">digits</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">str</span><span class="p">,</span> <span class="n">digits</span><span class="p">)</span>
    <span class="n">build</span><span class="p">,</span> <span class="nb">next</span> <span class="o">=</span> <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">,</span> <span class="n">digits</span><span class="o">.</span><span class="n">pop</span>
    <span class="k">if</span> <span class="n">sign</span><span class="p">:</span>
        <span class="n">build</span><span class="p">(</span><span class="n">trailneg</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">places</span><span class="p">):</span>
        <span class="n">build</span><span class="p">(</span><span class="nb">next</span><span class="p">()</span> <span class="k">if</span> <span class="n">digits</span> <span class="k">else</span> <span class="s1">&#39;0&#39;</span><span class="p">)</span>
    <span class="n">build</span><span class="p">(</span><span class="n">dp</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">digits</span><span class="p">:</span>
        <span class="n">build</span><span class="p">(</span><span class="s1">&#39;0&#39;</span><span class="p">)</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">digits</span><span class="p">:</span>
        <span class="n">build</span><span class="p">(</span><span class="nb">next</span><span class="p">())</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">3</span> <span class="ow">and</span> <span class="n">digits</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
            <span class="n">build</span><span class="p">(</span><span class="n">sep</span><span class="p">)</span>
    <span class="n">build</span><span class="p">(</span><span class="n">curr</span><span class="p">)</span>
    <span class="n">build</span><span class="p">(</span><span class="n">neg</span> <span class="k">if</span> <span class="n">sign</span> <span class="k">else</span> <span class="n">pos</span><span class="p">)</span>
    <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">reversed</span><span class="p">(</span><span class="n">result</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">pi</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Compute Pi to the current precision.</span>

<span class="sd">    &gt;&gt;&gt; print pi()</span>
<span class="sd">    3.141592653589793238462643383</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">+=</span> <span class="mi">2</span>  <span class="c1"># extra digits for intermediate steps</span>
    <span class="n">three</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>      <span class="c1"># substitute &quot;three=3.0&quot; for regular floats</span>
    <span class="n">lasts</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">na</span><span class="p">,</span> <span class="n">d</span><span class="p">,</span> <span class="n">da</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="n">three</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">24</span>
    <span class="k">while</span> <span class="n">s</span> <span class="o">!=</span> <span class="n">lasts</span><span class="p">:</span>
        <span class="n">lasts</span> <span class="o">=</span> <span class="n">s</span>
        <span class="n">n</span><span class="p">,</span> <span class="n">na</span> <span class="o">=</span> <span class="n">n</span><span class="o">+</span><span class="n">na</span><span class="p">,</span> <span class="n">na</span><span class="o">+</span><span class="mi">8</span>
        <span class="n">d</span><span class="p">,</span> <span class="n">da</span> <span class="o">=</span> <span class="n">d</span><span class="o">+</span><span class="n">da</span><span class="p">,</span> <span class="n">da</span><span class="o">+</span><span class="mi">32</span>
        <span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="n">t</span> <span class="o">*</span> <span class="n">n</span><span class="p">)</span> <span class="o">/</span> <span class="n">d</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">t</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">-=</span> <span class="mi">2</span>
    <span class="k">return</span> <span class="o">+</span><span class="n">s</span>               <span class="c1"># unary plus applies the new precision</span>

<span class="k">def</span> <span class="nf">exp</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return e raised to the power of x.  Result type matches input type.</span>

<span class="sd">    &gt;&gt;&gt; print exp(Decimal(1))</span>
<span class="sd">    2.718281828459045235360287471</span>
<span class="sd">    &gt;&gt;&gt; print exp(Decimal(2))</span>
<span class="sd">    7.389056098930650227230427461</span>
<span class="sd">    &gt;&gt;&gt; print exp(2.0)</span>
<span class="sd">    7.38905609893</span>
<span class="sd">    &gt;&gt;&gt; print exp(2+0j)</span>
<span class="sd">    (7.38905609893+0j)</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">+=</span> <span class="mi">2</span>
    <span class="n">i</span><span class="p">,</span> <span class="n">lasts</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">fact</span><span class="p">,</span> <span class="n">num</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">s</span> <span class="o">!=</span> <span class="n">lasts</span><span class="p">:</span>
        <span class="n">lasts</span> <span class="o">=</span> <span class="n">s</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">fact</span> <span class="o">*=</span> <span class="n">i</span>
        <span class="n">num</span> <span class="o">*=</span> <span class="n">x</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">num</span> <span class="o">/</span> <span class="n">fact</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">-=</span> <span class="mi">2</span>
    <span class="k">return</span> <span class="o">+</span><span class="n">s</span>

<span class="k">def</span> <span class="nf">cos</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return the cosine of x as measured in radians.</span>

<span class="sd">    &gt;&gt;&gt; print cos(Decimal(&#39;0.5&#39;))</span>
<span class="sd">    0.8775825618903727161162815826</span>
<span class="sd">    &gt;&gt;&gt; print cos(0.5)</span>
<span class="sd">    0.87758256189</span>
<span class="sd">    &gt;&gt;&gt; print cos(0.5+0j)</span>
<span class="sd">    (0.87758256189+0j)</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">+=</span> <span class="mi">2</span>
    <span class="n">i</span><span class="p">,</span> <span class="n">lasts</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">fact</span><span class="p">,</span> <span class="n">num</span><span class="p">,</span> <span class="n">sign</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">s</span> <span class="o">!=</span> <span class="n">lasts</span><span class="p">:</span>
        <span class="n">lasts</span> <span class="o">=</span> <span class="n">s</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">2</span>
        <span class="n">fact</span> <span class="o">*=</span> <span class="n">i</span> <span class="o">*</span> <span class="p">(</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">num</span> <span class="o">*=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span>
        <span class="n">sign</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">num</span> <span class="o">/</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">sign</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">-=</span> <span class="mi">2</span>
    <span class="k">return</span> <span class="o">+</span><span class="n">s</span>

<span class="k">def</span> <span class="nf">sin</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return the sine of x as measured in radians.</span>

<span class="sd">    &gt;&gt;&gt; print sin(Decimal(&#39;0.5&#39;))</span>
<span class="sd">    0.4794255386042030002732879352</span>
<span class="sd">    &gt;&gt;&gt; print sin(0.5)</span>
<span class="sd">    0.479425538604</span>
<span class="sd">    &gt;&gt;&gt; print sin(0.5+0j)</span>
<span class="sd">    (0.479425538604+0j)</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">+=</span> <span class="mi">2</span>
    <span class="n">i</span><span class="p">,</span> <span class="n">lasts</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">fact</span><span class="p">,</span> <span class="n">num</span><span class="p">,</span> <span class="n">sign</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">s</span> <span class="o">!=</span> <span class="n">lasts</span><span class="p">:</span>
        <span class="n">lasts</span> <span class="o">=</span> <span class="n">s</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">2</span>
        <span class="n">fact</span> <span class="o">*=</span> <span class="n">i</span> <span class="o">*</span> <span class="p">(</span><span class="n">i</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">num</span> <span class="o">*=</span> <span class="n">x</span> <span class="o">*</span> <span class="n">x</span>
        <span class="n">sign</span> <span class="o">*=</span> <span class="o">-</span><span class="mi">1</span>
        <span class="n">s</span> <span class="o">+=</span> <span class="n">num</span> <span class="o">/</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">sign</span>
    <span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">-=</span> <span class="mi">2</span>
    <span class="k">return</span> <span class="o">+</span><span class="n">s</span>
</pre></div>
</div>
</div>
<div class="section" id="decimal-faq">
<span id="id1"></span><h2>9.4.8. Decimal FAQ<a class="headerlink" href="#decimal-faq" title="Permalink to this headline">¶</a></h2>
<p>Q. It is cumbersome to type <code class="docutils literal notranslate"><span class="pre">decimal.Decimal('1234.5')</span></code>.  Is there a way to
minimize typing when using the interactive interpreter?</p>
<p>A. Some users abbreviate the constructor to just a single letter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">D</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">D</span><span class="p">(</span><span class="s1">&#39;1.23&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">D</span><span class="p">(</span><span class="s1">&#39;3.45&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;4.68&#39;)</span>
</pre></div>
</div>
<p>Q. In a fixed-point application with two decimal places, some inputs have many
places and need to be rounded.  Others are not supposed to have excess digits
and need to be validated.  What methods should be used?</p>
<p>A. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">quantize()</span></code> method rounds to a fixed number of decimal places. If
the <a class="reference internal" href="#decimal.Inexact" title="decimal.Inexact"><code class="xref py py-const docutils literal notranslate"><span class="pre">Inexact</span></code></a> trap is set, it is also useful for validation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">TWOPLACES</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="o">**</span> <span class="o">-</span><span class="mi">2</span>       <span class="c1"># same as Decimal(&#39;0.01&#39;)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Round to two places</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.214&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">TWOPLACES</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.21&#39;)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Validate that a number does not exceed two places</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.21&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">TWOPLACES</span><span class="p">,</span> <span class="n">context</span><span class="o">=</span><span class="n">Context</span><span class="p">(</span><span class="n">traps</span><span class="o">=</span><span class="p">[</span><span class="n">Inexact</span><span class="p">]))</span>
<span class="go">Decimal(&#39;3.21&#39;)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.214&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">TWOPLACES</span><span class="p">,</span> <span class="n">context</span><span class="o">=</span><span class="n">Context</span><span class="p">(</span><span class="n">traps</span><span class="o">=</span><span class="p">[</span><span class="n">Inexact</span><span class="p">]))</span>
<span class="gt">Traceback (most recent call last):</span>
   <span class="c">...</span>
<span class="gr">Inexact</span>: <span class="n">None</span>
</pre></div>
</div>
<p>Q. Once I have valid two place inputs, how do I maintain that invariant
throughout an application?</p>
<p>A. Some operations like addition, subtraction, and multiplication by an integer
will automatically preserve fixed point.  Others operations, like division and
non-integer multiplication, will change the number of decimal places and need to
be followed-up with a <code class="xref py py-meth docutils literal notranslate"><span class="pre">quantize()</span></code> step:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;102.72&#39;</span><span class="p">)</span>           <span class="c1"># Initial fixed-point values</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.17&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">+</span> <span class="n">b</span>                           <span class="c1"># Addition preserves fixed-point</span>
<span class="go">Decimal(&#39;105.89&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span>
<span class="go">Decimal(&#39;99.55&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">*</span> <span class="mi">42</span>                          <span class="c1"># So does integer multiplication</span>
<span class="go">Decimal(&#39;4314.24&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">a</span> <span class="o">*</span> <span class="n">b</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">TWOPLACES</span><span class="p">)</span>     <span class="c1"># Must quantize non-integer multiplication</span>
<span class="go">Decimal(&#39;325.62&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">b</span> <span class="o">/</span> <span class="n">a</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">TWOPLACES</span><span class="p">)</span>     <span class="c1"># And quantize division</span>
<span class="go">Decimal(&#39;0.03&#39;)</span>
</pre></div>
</div>
<p>In developing fixed-point applications, it is convenient to define functions
to handle the <code class="xref py py-meth docutils literal notranslate"><span class="pre">quantize()</span></code> step:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">mul</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">fp</span><span class="o">=</span><span class="n">TWOPLACES</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">*</span> <span class="n">y</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">div</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">fp</span><span class="o">=</span><span class="n">TWOPLACES</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="p">(</span><span class="n">x</span> <span class="o">/</span> <span class="n">y</span><span class="p">)</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mul</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>                       <span class="c1"># Automatically preserve fixed-point</span>
<span class="go">Decimal(&#39;325.62&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">div</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.03&#39;)</span>
</pre></div>
</div>
<p>Q. There are many ways to express the same value.  The numbers <code class="xref py py-const docutils literal notranslate"><span class="pre">200</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">200.000</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">2E2</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">02E+4</span></code> all have the same value at
various precisions. Is there a way to transform them to a single recognizable
canonical value?</p>
<p>A. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">normalize()</span></code> method maps all equivalent values to a single
representative:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">Decimal</span><span class="p">,</span> <span class="s1">&#39;200 200.000 2E2 .02E+4&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">v</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span> <span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">values</span><span class="p">]</span>
<span class="go">[Decimal(&#39;2E+2&#39;), Decimal(&#39;2E+2&#39;), Decimal(&#39;2E+2&#39;), Decimal(&#39;2E+2&#39;)]</span>
</pre></div>
</div>
<p>Q. Some decimal values always print with exponential notation.  Is there a way
to get a non-exponential representation?</p>
<p>A. For some values, exponential notation is the only way to express the number
of significant places in the coefficient.  For example, expressing
<code class="xref py py-const docutils literal notranslate"><span class="pre">5.0E+3</span></code> as <code class="xref py py-const docutils literal notranslate"><span class="pre">5000</span></code> keeps the value constant but cannot show the
original’s two-place significance.</p>
<p>If an application does not care about tracking significance, it is easy to
remove the exponent and trailing zeros, losing significance, but keeping the
value unchanged:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">remove_exponent</span><span class="p">(</span><span class="n">d</span><span class="p">):</span>
    <span class="sd">&#39;&#39;&#39;Remove exponent and trailing zeros.</span>

<span class="sd">    &gt;&gt;&gt; remove_exponent(Decimal(&#39;5E+3&#39;))</span>
<span class="sd">    Decimal(&#39;5000&#39;)</span>

<span class="sd">    &#39;&#39;&#39;</span>
    <span class="k">return</span> <span class="n">d</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="k">if</span> <span class="n">d</span> <span class="o">==</span> <span class="n">d</span><span class="o">.</span><span class="n">to_integral</span><span class="p">()</span> <span class="k">else</span> <span class="n">d</span><span class="o">.</span><span class="n">normalize</span><span class="p">()</span>
</pre></div>
</div>
<p>Q. Is there a way to convert a regular float to a <a class="reference internal" href="#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>?</p>
<p>A. Yes, any binary floating point number can be exactly expressed as a
Decimal though an exact conversion may take more precision than intuition would
suggest:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">Decimal(&#39;3.141592653589793115997963468544185161590576171875&#39;)</span>
</pre></div>
</div>
<p>Q. Within a complex calculation, how can I make sure that I haven’t gotten a
spurious result because of insufficient precision or rounding anomalies.</p>
<p>A. The decimal module makes it easy to test results.  A best practice is to
re-run calculations using greater precision and with various rounding modes.
Widely differing results indicate insufficient precision, rounding mode issues,
ill-conditioned inputs, or a numerically unstable algorithm.</p>
<p>Q. I noticed that context precision is applied to the results of operations but
not to the inputs.  Is there anything to watch out for when mixing values of
different precisions?</p>
<p>A. Yes.  The principle is that all values are considered to be exact and so is
the arithmetic on those values.  Only the results are rounded.  The advantage
for inputs is that “what you type is what you get”.  A disadvantage is that the
results can look odd if you forget that the inputs haven’t been rounded:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.104&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;2.104&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;5.21&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;3.104&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.000&#39;</span><span class="p">)</span> <span class="o">+</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;2.104&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;5.20&#39;)</span>
</pre></div>
</div>
<p>The solution is either to increase precision or to force rounding of inputs
using the unary plus operation:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="o">+</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.23456789&#39;</span><span class="p">)</span>      <span class="c1"># unary plus triggers rounding</span>
<span class="go">Decimal(&#39;1.23&#39;)</span>
</pre></div>
</div>
<p>Alternatively, inputs can be rounded upon creation using the
<a class="reference internal" href="#decimal.Context.create_decimal" title="decimal.Context.create_decimal"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Context.create_decimal()</span></code></a> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">5</span><span class="p">,</span> <span class="n">rounding</span><span class="o">=</span><span class="n">ROUND_DOWN</span><span class="p">)</span><span class="o">.</span><span class="n">create_decimal</span><span class="p">(</span><span class="s1">&#39;1.2345678&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;1.2345&#39;)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a><ul>
<li><a class="reference internal" href="#quick-start-tutorial">9.4.1. Quick-start Tutorial</a></li>
<li><a class="reference internal" href="#decimal-objects">9.4.2. Decimal objects</a><ul>
<li><a class="reference internal" href="#logical-operands">9.4.2.1. Logical operands</a></li>
</ul>
</li>
<li><a class="reference internal" href="#context-objects">9.4.3. Context objects</a></li>
<li><a class="reference internal" href="#signals">9.4.4. Signals</a></li>
<li><a class="reference internal" href="#floating-point-notes">9.4.5. Floating Point Notes</a><ul>
<li><a class="reference internal" href="#mitigating-round-off-error-with-increased-precision">9.4.5.1. Mitigating round-off error with increased precision</a></li>
<li><a class="reference internal" href="#special-values">9.4.5.2. Special values</a></li>
</ul>
</li>
<li><a class="reference internal" href="#working-with-threads">9.4.6. Working with threads</a></li>
<li><a class="reference internal" href="#recipes">9.4.7. Recipes</a></li>
<li><a class="reference internal" href="#decimal-faq">9.4.8. Decimal FAQ</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cmath.html"
                        title="previous chapter">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fractions.html"
                        title="next chapter">9.5. <code class="docutils literal notranslate"><span class="pre">fractions</span></code> — Rational numbers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/decimal.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fractions.html" title="9.5. fractions — Rational numbers"
             >next</a> |</li>
        <li class="right" >
          <a href="cmath.html" title="9.3. cmath — Mathematical functions for complex numbers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����9�9html/library/development.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25. Development Tools &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25.1. pydoc — Documentation generator and online help system" href="pydoc.html" />
    <link rel="prev" title="24.7. Other Graphical User Interface Packages" href="othergui.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/development.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pydoc.html" title="25.1. pydoc — Documentation generator and online help system"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="othergui.html" title="24.7. Other Graphical User Interface Packages"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="development-tools">
<span id="development"></span><h1>25. Development Tools<a class="headerlink" href="#development-tools" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter help you write software.  For example, the
<a class="reference internal" href="pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module takes a module and generates documentation based on the
module’s contents.  The <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> and <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> modules contains
frameworks for writing unit tests that automatically exercise code and verify
that the expected output is produced.  <strong class="program">2to3</strong> can translate Python 2.x
source code into valid Python 3.x code.</p>
<p>The list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="pydoc.html">25.1. <code class="docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></li>
<li class="toctree-l1"><a class="reference internal" href="doctest.html">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a><ul>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#simple-usage-checking-examples-in-docstrings">25.2.1. Simple Usage: Checking Examples in Docstrings</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#simple-usage-checking-examples-in-a-text-file">25.2.2. Simple Usage: Checking Examples in a Text File</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#how-it-works">25.2.3. How It Works</a><ul>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#which-docstrings-are-examined">25.2.3.1. Which Docstrings Are Examined?</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#how-are-docstring-examples-recognized">25.2.3.2. How are Docstring Examples Recognized?</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#what-s-the-execution-context">25.2.3.3. What’s the Execution Context?</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#what-about-exceptions">25.2.3.4. What About Exceptions?</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#option-flags">25.2.3.5. Option Flags</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#directives">25.2.3.6. Directives</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#warnings">25.2.3.7. Warnings</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#basic-api">25.2.4. Basic API</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#unittest-api">25.2.5. Unittest API</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#advanced-api">25.2.6. Advanced API</a><ul>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#doctest-objects">25.2.6.1. DocTest Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#example-objects">25.2.6.2. Example Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#doctestfinder-objects">25.2.6.3. DocTestFinder objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#doctestparser-objects">25.2.6.4. DocTestParser objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#doctestrunner-objects">25.2.6.5. DocTestRunner objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="doctest.html#outputchecker-objects">25.2.6.6. OutputChecker objects</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#debugging">25.2.7. Debugging</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html#soapbox">25.2.8. Soapbox</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="unittest.html">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a><ul>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#basic-example">25.3.1. Basic example</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#command-line-interface">25.3.2. Command-Line Interface</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#command-line-options">25.3.2.1. Command-line options</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#test-discovery">25.3.3. Test Discovery</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#organizing-test-code">25.3.4. Organizing test code</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#re-using-old-test-code">25.3.5. Re-using old test code</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#skipping-tests-and-expected-failures">25.3.6. Skipping tests and expected failures</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#classes-and-functions">25.3.7. Classes and functions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#test-cases">25.3.7.1. Test cases</a><ul>
<li class="toctree-l4"><a class="reference internal" href="unittest.html#deprecated-aliases">25.3.7.1.1. Deprecated aliases</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#grouping-tests">25.3.7.2. Grouping tests</a></li>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#loading-and-running-tests">25.3.7.3. Loading and running tests</a><ul>
<li class="toctree-l4"><a class="reference internal" href="unittest.html#load-tests-protocol">25.3.7.3.1. load_tests Protocol</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#class-and-module-fixtures">25.3.8. Class and Module Fixtures</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#setupclass-and-teardownclass">25.3.8.1. setUpClass and tearDownClass</a></li>
<li class="toctree-l3"><a class="reference internal" href="unittest.html#setupmodule-and-teardownmodule">25.3.8.2. setUpModule and tearDownModule</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html#signal-handling">25.3.9. Signal Handling</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2to3.html">25.4. 2to3 - Automated Python 2 to 3 code translation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2to3.html#using-2to3">25.4.1. Using 2to3</a></li>
<li class="toctree-l2"><a class="reference internal" href="2to3.html#fixers">25.4.2. Fixers</a></li>
<li class="toctree-l2"><a class="reference internal" href="2to3.html#module-lib2to3">25.4.3. <code class="docutils literal notranslate"><span class="pre">lib2to3</span></code> - 2to3’s library</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="test.html">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="test.html#writing-unit-tests-for-the-test-package">25.5.1. Writing Unit Tests for the <code class="docutils literal notranslate"><span class="pre">test</span></code> package</a></li>
<li class="toctree-l2"><a class="reference internal" href="test.html#running-tests-using-the-command-line-interface">25.5.2. Running tests using the command-line interface</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="test.html#module-test.support">25.6. <code class="docutils literal notranslate"><span class="pre">test.support</span></code> — Utility functions for tests</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="othergui.html"
                        title="previous chapter">24.7. Other Graphical User Interface Packages</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pydoc.html"
                        title="next chapter">25.1. <code class="docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/development.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pydoc.html" title="25.1. pydoc — Documentation generator and online help system"
             >next</a> |</li>
        <li class="right" >
          <a href="othergui.html" title="24.7. Other Graphical User Interface Packages"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�;�GgGghtml/library/difflib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.4. difflib — Helpers for computing deltas &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.5. StringIO — Read and write strings as files" href="stringio.html" />
    <link rel="prev" title="7.3. struct — Interpret strings as packed binary data" href="struct.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/difflib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stringio.html" title="7.5. StringIO — Read and write strings as files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="struct.html" title="7.3. struct — Interpret strings as packed binary data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-difflib">
<span id="difflib-helpers-for-computing-deltas"></span><h1>7.4. <a class="reference internal" href="#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> — Helpers for computing deltas<a class="headerlink" href="#module-difflib" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p>This module provides classes and functions for comparing sequences. It
can be used for example, for comparing files, and can produce difference
information in various formats, including HTML and context and unified
diffs. For comparing directories and files, see also, the <a class="reference internal" href="filecmp.html#module-filecmp" title="filecmp: Compare files efficiently."><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code></a> module.</p>
<dl class="class">
<dt id="difflib.SequenceMatcher">
<em class="property">class </em><code class="descclassname">difflib.</code><code class="descname">SequenceMatcher</code><a class="headerlink" href="#difflib.SequenceMatcher" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a flexible class for comparing pairs of sequences of any type, so long
as the sequence elements are <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>.  The basic algorithm predates, and is a
little fancier than, an algorithm published in the late 1980’s by Ratcliff and
Obershelp under the hyperbolic name “gestalt pattern matching.”  The idea is to
find the longest contiguous matching subsequence that contains no “junk”
elements (the Ratcliff and Obershelp algorithm doesn’t address junk).  The same
idea is then applied recursively to the pieces of the sequences to the left and
to the right of the matching subsequence.  This does not yield minimal edit
sequences, but does tend to yield matches that “look right” to people.</p>
<p><strong>Timing:</strong> The basic Ratcliff-Obershelp algorithm is cubic time in the worst
case and quadratic time in the expected case. <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> is
quadratic time for the worst case and has expected-case behavior dependent in a
complicated way on how many elements the sequences have in common; best case
time is linear.</p>
<p><strong>Automatic junk heuristic:</strong> <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> supports a heuristic that
automatically treats certain sequence items as junk. The heuristic counts how many
times each individual item appears in the sequence. If an item’s duplicates (after
the first one) account for more than 1% of the sequence and the sequence is at least
200 items long, this item is marked as “popular” and is treated as junk for
the purpose of sequence matching. This heuristic can be turned off by setting
the <code class="docutils literal notranslate"><span class="pre">autojunk</span></code> argument to <code class="docutils literal notranslate"><span class="pre">False</span></code> when creating the <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.1: </span>The <em>autojunk</em> parameter.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="difflib.Differ">
<em class="property">class </em><code class="descclassname">difflib.</code><code class="descname">Differ</code><a class="headerlink" href="#difflib.Differ" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a class for comparing sequences of lines of text, and producing
human-readable differences or deltas.  Differ uses <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a>
both to compare sequences of lines, and to compare sequences of characters
within similar (near-matching) lines.</p>
<p>Each line of a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a> delta begins with a two-letter code:</p>
<table border="1" class="docutils">
<colgroup>
<col width="19%" />
<col width="81%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Code</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'-</span> <span class="pre">'</span></code></td>
<td>line unique to sequence 1</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'+</span> <span class="pre">'</span></code></td>
<td>line unique to sequence 2</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'</span>&#160; <span class="pre">'</span></code></td>
<td>line common to both sequences</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'?</span> <span class="pre">'</span></code></td>
<td>line not present in either input sequence</td>
</tr>
</tbody>
</table>
<p>Lines beginning with ‘<code class="docutils literal notranslate"><span class="pre">?</span></code>’ attempt to guide the eye to intraline differences,
and were not present in either input sequence. These lines can be confusing if
the sequences contain tab characters.</p>
</dd></dl>

<dl class="class">
<dt id="difflib.HtmlDiff">
<em class="property">class </em><code class="descclassname">difflib.</code><code class="descname">HtmlDiff</code><a class="headerlink" href="#difflib.HtmlDiff" title="Permalink to this definition">¶</a></dt>
<dd><p>This class can be used to create an HTML table (or a complete HTML file
containing the table) showing a side by side, line by line comparison of text
with inter-line and intra-line change highlights.  The table can be generated in
either full or contextual difference mode.</p>
<p>The constructor for this class is:</p>
<dl class="function">
<dt id="difflib.HtmlDiff.__init__">
<code class="descname">__init__</code><span class="sig-paren">(</span><em>tabsize=8</em>, <em>wrapcolumn=None</em>, <em>linejunk=None</em>, <em>charjunk=IS_CHARACTER_JUNK</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.HtmlDiff.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Initializes instance of <a class="reference internal" href="#difflib.HtmlDiff" title="difflib.HtmlDiff"><code class="xref py py-class docutils literal notranslate"><span class="pre">HtmlDiff</span></code></a>.</p>
<p><em>tabsize</em> is an optional keyword argument to specify tab stop spacing and
defaults to <code class="docutils literal notranslate"><span class="pre">8</span></code>.</p>
<p><em>wrapcolumn</em> is an optional keyword to specify column number where lines are
broken and wrapped, defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> where lines are not wrapped.</p>
<p><em>linejunk</em> and <em>charjunk</em> are optional keyword arguments passed into <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code></a>
(used by <a class="reference internal" href="#difflib.HtmlDiff" title="difflib.HtmlDiff"><code class="xref py py-class docutils literal notranslate"><span class="pre">HtmlDiff</span></code></a> to generate the side by side HTML differences).  See
<a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code></a> documentation for argument default values and descriptions.</p>
</dd></dl>

<p>The following methods are public:</p>
<dl class="function">
<dt id="difflib.HtmlDiff.make_file">
<code class="descname">make_file</code><span class="sig-paren">(</span><em>fromlines, tolines [, fromdesc][, todesc][, context][, numlines]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.HtmlDiff.make_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares <em>fromlines</em> and <em>tolines</em> (lists of strings) and returns a string which
is a complete HTML file containing a table showing line by line differences with
inter-line and intra-line changes highlighted.</p>
<p><em>fromdesc</em> and <em>todesc</em> are optional keyword arguments to specify from/to file
column header strings (both default to an empty string).</p>
<p><em>context</em> and <em>numlines</em> are both optional keyword arguments. Set <em>context</em> to
<code class="docutils literal notranslate"><span class="pre">True</span></code> when contextual differences are to be shown, else the default is
<code class="docutils literal notranslate"><span class="pre">False</span></code> to show the full files. <em>numlines</em> defaults to <code class="docutils literal notranslate"><span class="pre">5</span></code>.  When <em>context</em>
is <code class="docutils literal notranslate"><span class="pre">True</span></code> <em>numlines</em> controls the number of context lines which surround the
difference highlights.  When <em>context</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> <em>numlines</em> controls the
number of lines which are shown before a difference highlight when using the
“next” hyperlinks (setting to zero would cause the “next” hyperlinks to place
the next difference highlight at the top of the browser without any leading
context).</p>
</dd></dl>

<dl class="function">
<dt id="difflib.HtmlDiff.make_table">
<code class="descname">make_table</code><span class="sig-paren">(</span><em>fromlines, tolines [, fromdesc][, todesc][, context][, numlines]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.HtmlDiff.make_table" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares <em>fromlines</em> and <em>tolines</em> (lists of strings) and returns a string which
is a complete HTML table showing line by line differences with inter-line and
intra-line changes highlighted.</p>
<p>The arguments for this method are the same as those for the <a class="reference internal" href="#difflib.HtmlDiff.make_file" title="difflib.HtmlDiff.make_file"><code class="xref py py-meth docutils literal notranslate"><span class="pre">make_file()</span></code></a>
method.</p>
</dd></dl>

<p><code class="file docutils literal notranslate"><span class="pre">Tools/scripts/diff.py</span></code> is a command-line front-end to this class and
contains a good example of its use.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.context_diff">
<code class="descclassname">difflib.</code><code class="descname">context_diff</code><span class="sig-paren">(</span><em>a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.context_diff" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare <em>a</em> and <em>b</em> (lists of strings); return a delta (a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>
generating the delta lines) in context diff format.</p>
<p>Context diffs are a compact way of showing just the lines that have changed plus
a few lines of context.  The changes are shown in a before/after style.  The
number of context lines is set by <em>n</em> which defaults to three.</p>
<p>By default, the diff control lines (those with <code class="docutils literal notranslate"><span class="pre">***</span></code> or <code class="docutils literal notranslate"><span class="pre">---</span></code>) are created
with a trailing newline.  This is helpful so that inputs created from
<a class="reference internal" href="stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-func docutils literal notranslate"><span class="pre">file.readlines()</span></code></a> result in diffs that are suitable for use with
<a class="reference internal" href="stdtypes.html#file.writelines" title="file.writelines"><code class="xref py py-func docutils literal notranslate"><span class="pre">file.writelines()</span></code></a> since both the inputs and outputs have trailing
newlines.</p>
<p>For inputs that do not have trailing newlines, set the <em>lineterm</em> argument to
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code> so that the output will be uniformly newline free.</p>
<p>The context diff format normally has a header for filenames and modification
times.  Any or all of these may be specified using strings for <em>fromfile</em>,
<em>tofile</em>, <em>fromfiledate</em>, and <em>tofiledate</em>.  The modification times are normally
expressed in the ISO 8601 format. If not specified, the
strings default to blanks.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s1</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;bacon</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;ham</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;guido</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s2</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;python</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;eggy</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;hamster</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;guido</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">context_diff</span><span class="p">(</span><span class="n">s1</span><span class="p">,</span> <span class="n">s2</span><span class="p">,</span> <span class="n">fromfile</span><span class="o">=</span><span class="s1">&#39;before.py&#39;</span><span class="p">,</span> <span class="n">tofile</span><span class="o">=</span><span class="s1">&#39;after.py&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>  
<span class="go">*** before.py</span>
<span class="go">--- after.py</span>
<span class="go">***************</span>
<span class="go">*** 1,4 ****</span>
<span class="go">! bacon</span>
<span class="go">! eggs</span>
<span class="go">! ham</span>
<span class="go">  guido</span>
<span class="go">--- 1,4 ----</span>
<span class="go">! python</span>
<span class="go">! eggy</span>
<span class="go">! hamster</span>
<span class="go">  guido</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#difflib-interface"><span class="std std-ref">A command-line interface to difflib</span></a> for a more detailed example.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.get_close_matches">
<code class="descclassname">difflib.</code><code class="descname">get_close_matches</code><span class="sig-paren">(</span><em>word, possibilities[, n][, cutoff]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.get_close_matches" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the best “good enough” matches.  <em>word</em> is a sequence for which
close matches are desired (typically a string), and <em>possibilities</em> is a list of
sequences against which to match <em>word</em> (typically a list of strings).</p>
<p>Optional argument <em>n</em> (default <code class="docutils literal notranslate"><span class="pre">3</span></code>) is the maximum number of close matches to
return; <em>n</em> must be greater than <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<p>Optional argument <em>cutoff</em> (default <code class="docutils literal notranslate"><span class="pre">0.6</span></code>) is a float in the range [0, 1].
Possibilities that don’t score at least that similar to <em>word</em> are ignored.</p>
<p>The best (no more than <em>n</em>) matches among the possibilities are returned in a
list, sorted by similarity score, most similar first.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">get_close_matches</span><span class="p">(</span><span class="s1">&#39;appel&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;ape&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;peach&#39;</span><span class="p">,</span> <span class="s1">&#39;puppy&#39;</span><span class="p">])</span>
<span class="go">[&#39;apple&#39;, &#39;ape&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">keyword</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_close_matches</span><span class="p">(</span><span class="s1">&#39;wheel&#39;</span><span class="p">,</span> <span class="n">keyword</span><span class="o">.</span><span class="n">kwlist</span><span class="p">)</span>
<span class="go">[&#39;while&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_close_matches</span><span class="p">(</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="n">keyword</span><span class="o">.</span><span class="n">kwlist</span><span class="p">)</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">get_close_matches</span><span class="p">(</span><span class="s1">&#39;accept&#39;</span><span class="p">,</span> <span class="n">keyword</span><span class="o">.</span><span class="n">kwlist</span><span class="p">)</span>
<span class="go">[&#39;except&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.ndiff">
<code class="descclassname">difflib.</code><code class="descname">ndiff</code><span class="sig-paren">(</span><em>a, b[, linejunk][, charjunk]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.ndiff" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare <em>a</em> and <em>b</em> (lists of strings); return a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a>-style
delta (a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> generating the delta lines).</p>
<p>Optional keyword parameters <em>linejunk</em> and <em>charjunk</em> are for filter functions
(or <code class="docutils literal notranslate"><span class="pre">None</span></code>):</p>
<p><em>linejunk</em>: A function that accepts a single string argument, and returns true
if the string is junk, or false if not. The default is (<code class="docutils literal notranslate"><span class="pre">None</span></code>), starting with
Python 2.3.  Before then, the default was the module-level function
<a class="reference internal" href="#difflib.IS_LINE_JUNK" title="difflib.IS_LINE_JUNK"><code class="xref py py-func docutils literal notranslate"><span class="pre">IS_LINE_JUNK()</span></code></a>, which filters out lines without visible characters, except
for at most one pound character (<code class="docutils literal notranslate"><span class="pre">'#'</span></code>). As of Python 2.3, the underlying
<a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> class does a dynamic analysis of which lines are so
frequent as to constitute noise, and this usually works better than the pre-2.3
default.</p>
<p><em>charjunk</em>: A function that accepts a character (a string of length 1), and
returns if the character is junk, or false if not. The default is module-level
function <a class="reference internal" href="#difflib.IS_CHARACTER_JUNK" title="difflib.IS_CHARACTER_JUNK"><code class="xref py py-func docutils literal notranslate"><span class="pre">IS_CHARACTER_JUNK()</span></code></a>, which filters out whitespace characters (a
blank or tab; note: bad idea to include newline in this!).</p>
<p><code class="file docutils literal notranslate"><span class="pre">Tools/scripts/ndiff.py</span></code> is a command-line front-end to this function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">diff</span> <span class="o">=</span> <span class="n">ndiff</span><span class="p">(</span><span class="s1">&#39;one</span><span class="se">\n</span><span class="s1">two</span><span class="se">\n</span><span class="s1">three</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>             <span class="s1">&#39;ore</span><span class="se">\n</span><span class="s1">tree</span><span class="se">\n</span><span class="s1">emu</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">diff</span><span class="p">),</span>
<span class="go">- one</span>
<span class="go">?  ^</span>
<span class="go">+ ore</span>
<span class="go">?  ^</span>
<span class="go">- two</span>
<span class="go">- three</span>
<span class="go">?  -</span>
<span class="go">+ tree</span>
<span class="go">+ emu</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.restore">
<code class="descclassname">difflib.</code><code class="descname">restore</code><span class="sig-paren">(</span><em>sequence</em>, <em>which</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.restore" title="Permalink to this definition">¶</a></dt>
<dd><p>Return one of the two sequences that generated a delta.</p>
<p>Given a <em>sequence</em> produced by <a class="reference internal" href="#difflib.Differ.compare" title="difflib.Differ.compare"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Differ.compare()</span></code></a> or <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code></a>, extract
lines originating from file 1 or 2 (parameter <em>which</em>), stripping off line
prefixes.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">diff</span> <span class="o">=</span> <span class="n">ndiff</span><span class="p">(</span><span class="s1">&#39;one</span><span class="se">\n</span><span class="s1">two</span><span class="se">\n</span><span class="s1">three</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>             <span class="s1">&#39;ore</span><span class="se">\n</span><span class="s1">tree</span><span class="se">\n</span><span class="s1">emu</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">diff</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">diff</span><span class="p">)</span> <span class="c1"># materialize the generated delta into a list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">restore</span><span class="p">(</span><span class="n">diff</span><span class="p">,</span> <span class="mi">1</span><span class="p">)),</span>
<span class="go">one</span>
<span class="go">two</span>
<span class="go">three</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">restore</span><span class="p">(</span><span class="n">diff</span><span class="p">,</span> <span class="mi">2</span><span class="p">)),</span>
<span class="go">ore</span>
<span class="go">tree</span>
<span class="go">emu</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.unified_diff">
<code class="descclassname">difflib.</code><code class="descname">unified_diff</code><span class="sig-paren">(</span><em>a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm]</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.unified_diff" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare <em>a</em> and <em>b</em> (lists of strings); return a delta (a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>
generating the delta lines) in unified diff format.</p>
<p>Unified diffs are a compact way of showing just the lines that have changed plus
a few lines of context.  The changes are shown in an inline style (instead of
separate before/after blocks).  The number of context lines is set by <em>n</em> which
defaults to three.</p>
<p>By default, the diff control lines (those with <code class="docutils literal notranslate"><span class="pre">---</span></code>, <code class="docutils literal notranslate"><span class="pre">+++</span></code>, or <code class="docutils literal notranslate"><span class="pre">&#64;&#64;</span></code>) are
created with a trailing newline.  This is helpful so that inputs created from
<a class="reference internal" href="stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-func docutils literal notranslate"><span class="pre">file.readlines()</span></code></a> result in diffs that are suitable for use with
<a class="reference internal" href="stdtypes.html#file.writelines" title="file.writelines"><code class="xref py py-func docutils literal notranslate"><span class="pre">file.writelines()</span></code></a> since both the inputs and outputs have trailing
newlines.</p>
<p>For inputs that do not have trailing newlines, set the <em>lineterm</em> argument to
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code> so that the output will be uniformly newline free.</p>
<p>The context diff format normally has a header for filenames and modification
times.  Any or all of these may be specified using strings for <em>fromfile</em>,
<em>tofile</em>, <em>fromfiledate</em>, and <em>tofiledate</em>.  The modification times are normally
expressed in the ISO 8601 format. If not specified, the
strings default to blanks.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s1</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;bacon</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;ham</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;guido</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s2</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;python</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;eggy</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;hamster</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;guido</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">unified_diff</span><span class="p">(</span><span class="n">s1</span><span class="p">,</span> <span class="n">s2</span><span class="p">,</span> <span class="n">fromfile</span><span class="o">=</span><span class="s1">&#39;before.py&#39;</span><span class="p">,</span> <span class="n">tofile</span><span class="o">=</span><span class="s1">&#39;after.py&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>   
<span class="go">--- before.py</span>
<span class="go">+++ after.py</span>
<span class="go">@@ -1,4 +1,4 @@</span>
<span class="go">-bacon</span>
<span class="go">-eggs</span>
<span class="go">-ham</span>
<span class="go">+python</span>
<span class="go">+eggy</span>
<span class="go">+hamster</span>
<span class="go"> guido</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#difflib-interface"><span class="std std-ref">A command-line interface to difflib</span></a> for a more detailed example.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="difflib.IS_LINE_JUNK">
<code class="descclassname">difflib.</code><code class="descname">IS_LINE_JUNK</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.IS_LINE_JUNK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true for ignorable lines.  The line <em>line</em> is ignorable if <em>line</em> is
blank or contains a single <code class="docutils literal notranslate"><span class="pre">'#'</span></code>, otherwise it is not ignorable.  Used as a
default for parameter <em>linejunk</em> in <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code></a> before Python 2.3.</p>
</dd></dl>

<dl class="function">
<dt id="difflib.IS_CHARACTER_JUNK">
<code class="descclassname">difflib.</code><code class="descname">IS_CHARACTER_JUNK</code><span class="sig-paren">(</span><em>ch</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.IS_CHARACTER_JUNK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true for ignorable characters.  The character <em>ch</em> is ignorable if <em>ch</em>
is a space or tab, otherwise it is not ignorable.  Used as a default for
parameter <em>charjunk</em> in <a class="reference internal" href="#difflib.ndiff" title="difflib.ndiff"><code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970">Pattern Matching: The Gestalt Approach</a></dt>
<dd>Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
was published in <a class="reference external" href="http://www.drdobbs.com/">Dr. Dobb’s Journal</a> in July, 1988.</dd>
</dl>
</div>
<div class="section" id="sequencematcher-objects">
<span id="sequence-matcher"></span><h2>7.4.1. SequenceMatcher Objects<a class="headerlink" href="#sequencematcher-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> class has this constructor:</p>
<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">difflib.</code><code class="descname">SequenceMatcher</code><span class="sig-paren">(</span><em>isjunk=None</em>, <em>a=''</em>, <em>b=''</em>, <em>autojunk=True</em><span class="sig-paren">)</span></dt>
<dd><p>Optional argument <em>isjunk</em> must be <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) or a one-argument
function that takes a sequence element and returns true if and only if the
element is “junk” and should be ignored. Passing <code class="docutils literal notranslate"><span class="pre">None</span></code> for <em>isjunk</em> is
equivalent to passing <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">x:</span> <span class="pre">0</span></code>; in other words, no elements are ignored.
For example, pass:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="ow">in</span> <span class="s2">&quot; </span><span class="se">\t</span><span class="s2">&quot;</span>
</pre></div>
</div>
<p>if you’re comparing lines as sequences of characters, and don’t want to synch up
on blanks or hard tabs.</p>
<p>The optional arguments <em>a</em> and <em>b</em> are sequences to be compared; both default to
empty strings.  The elements of both sequences must be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>.</p>
<p>The optional argument <em>autojunk</em> can be used to disable the automatic junk
heuristic.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.1: </span>The <em>autojunk</em> parameter.</p>
</div>
<p><a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> objects have the following methods:</p>
<dl class="method">
<dt id="difflib.SequenceMatcher.set_seqs">
<code class="descname">set_seqs</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.set_seqs" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the two sequences to be compared.</p>
</dd></dl>

<p><a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> computes and caches detailed information about the
second sequence, so if you want to compare one sequence against many
sequences, use <a class="reference internal" href="#difflib.SequenceMatcher.set_seq2" title="difflib.SequenceMatcher.set_seq2"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_seq2()</span></code></a> to set the commonly used sequence once and
call <a class="reference internal" href="#difflib.SequenceMatcher.set_seq1" title="difflib.SequenceMatcher.set_seq1"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_seq1()</span></code></a> repeatedly, once for each of the other sequences.</p>
<dl class="method">
<dt id="difflib.SequenceMatcher.set_seq1">
<code class="descname">set_seq1</code><span class="sig-paren">(</span><em>a</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.set_seq1" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the first sequence to be compared.  The second sequence to be compared
is not changed.</p>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.set_seq2">
<code class="descname">set_seq2</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.set_seq2" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the second sequence to be compared.  The first sequence to be compared
is not changed.</p>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.find_longest_match">
<code class="descname">find_longest_match</code><span class="sig-paren">(</span><em>alo</em>, <em>ahi</em>, <em>blo</em>, <em>bhi</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.find_longest_match" title="Permalink to this definition">¶</a></dt>
<dd><p>Find longest matching block in <code class="docutils literal notranslate"><span class="pre">a[alo:ahi]</span></code> and <code class="docutils literal notranslate"><span class="pre">b[blo:bhi]</span></code>.</p>
<p>If <em>isjunk</em> was omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#difflib.SequenceMatcher.find_longest_match" title="difflib.SequenceMatcher.find_longest_match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find_longest_match()</span></code></a> returns
<code class="docutils literal notranslate"><span class="pre">(i,</span> <span class="pre">j,</span> <span class="pre">k)</span></code> such that <code class="docutils literal notranslate"><span class="pre">a[i:i+k]</span></code> is equal to <code class="docutils literal notranslate"><span class="pre">b[j:j+k]</span></code>, where <code class="docutils literal notranslate"><span class="pre">alo</span>
<span class="pre">&lt;=</span> <span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">i+k</span> <span class="pre">&lt;=</span> <span class="pre">ahi</span></code> and <code class="docutils literal notranslate"><span class="pre">blo</span> <span class="pre">&lt;=</span> <span class="pre">j</span> <span class="pre">&lt;=</span> <span class="pre">j+k</span> <span class="pre">&lt;=</span> <span class="pre">bhi</span></code>. For all <code class="docutils literal notranslate"><span class="pre">(i',</span> <span class="pre">j',</span>
<span class="pre">k')</span></code> meeting those conditions, the additional conditions <code class="docutils literal notranslate"><span class="pre">k</span> <span class="pre">&gt;=</span> <span class="pre">k'</span></code>, <code class="docutils literal notranslate"><span class="pre">i</span>
<span class="pre">&lt;=</span> <span class="pre">i'</span></code>, and if <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">==</span> <span class="pre">i'</span></code>, <code class="docutils literal notranslate"><span class="pre">j</span> <span class="pre">&lt;=</span> <span class="pre">j'</span></code> are also met. In other words, of
all maximal matching blocks, return one that starts earliest in <em>a</em>, and
of all those maximal matching blocks that start earliest in <em>a</em>, return
the one that starts earliest in <em>b</em>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s2">&quot; abcd&quot;</span><span class="p">,</span> <span class="s2">&quot;abcd abcd&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find_longest_match</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
<span class="go">Match(a=0, b=4, size=5)</span>
</pre></div>
</div>
<p>If <em>isjunk</em> was provided, first the longest matching block is determined
as above, but with the additional restriction that no junk element appears
in the block.  Then that block is extended as far as possible by matching
(only) junk elements on both sides. So the resulting block never matches
on junk except as identical junk happens to be adjacent to an interesting
match.</p>
<p>Here’s the same example as before, but considering blanks to be junk. That
prevents <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">abcd'</span></code> from matching the <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">abcd'</span></code> at the tail end of the
second sequence directly.  Instead only the <code class="docutils literal notranslate"><span class="pre">'abcd'</span></code> can match, and
matches the leftmost <code class="docutils literal notranslate"><span class="pre">'abcd'</span></code> in the second sequence:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">==</span><span class="s2">&quot; &quot;</span><span class="p">,</span> <span class="s2">&quot; abcd&quot;</span><span class="p">,</span> <span class="s2">&quot;abcd abcd&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">find_longest_match</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
<span class="go">Match(a=1, b=0, size=4)</span>
</pre></div>
</div>
<p>If no blocks match, this returns <code class="docutils literal notranslate"><span class="pre">(alo,</span> <span class="pre">blo,</span> <span class="pre">0)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>This method returns a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">Match(a,</span> <span class="pre">b,</span> <span class="pre">size)</span></code>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.get_matching_blocks">
<code class="descname">get_matching_blocks</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.get_matching_blocks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return list of triples describing non-overlapping matching subsequences.
Each triple is of the form <code class="docutils literal notranslate"><span class="pre">(i,</span> <span class="pre">j,</span> <span class="pre">n)</span></code>,
and means that <code class="docutils literal notranslate"><span class="pre">a[i:i+n]</span> <span class="pre">==</span> <span class="pre">b[j:j+n]</span></code>.  The
triples are monotonically increasing in <em>i</em> and <em>j</em>.</p>
<p>The last triple is a dummy, and has the value <code class="docutils literal notranslate"><span class="pre">(len(a),</span> <span class="pre">len(b),</span> <span class="pre">0)</span></code>.  It
is the only triple with <code class="docutils literal notranslate"><span class="pre">n</span> <span class="pre">==</span> <span class="pre">0</span></code>.  If <code class="docutils literal notranslate"><span class="pre">(i,</span> <span class="pre">j,</span> <span class="pre">n)</span></code> and <code class="docutils literal notranslate"><span class="pre">(i',</span> <span class="pre">j',</span> <span class="pre">n')</span></code>
are adjacent triples in the list, and the second is not the last triple in
the list, then <code class="docutils literal notranslate"><span class="pre">i+n</span> <span class="pre">&lt;</span> <span class="pre">i'</span></code> or <code class="docutils literal notranslate"><span class="pre">j+n</span> <span class="pre">&lt;</span> <span class="pre">j'</span></code>; in other words, adjacent
triples always describe non-adjacent equal blocks.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The guarantee that adjacent triples always describe non-adjacent blocks
was implemented.</p>
</div>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="s2">&quot;abxcd&quot;</span><span class="p">,</span> <span class="s2">&quot;abcd&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">get_matching_blocks</span><span class="p">()</span>
<span class="go">[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.get_opcodes">
<code class="descname">get_opcodes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.get_opcodes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return list of 5-tuples describing how to turn <em>a</em> into <em>b</em>. Each tuple is
of the form <code class="docutils literal notranslate"><span class="pre">(tag,</span> <span class="pre">i1,</span> <span class="pre">i2,</span> <span class="pre">j1,</span> <span class="pre">j2)</span></code>.  The first tuple has <code class="docutils literal notranslate"><span class="pre">i1</span> <span class="pre">==</span> <span class="pre">j1</span> <span class="pre">==</span>
<span class="pre">0</span></code>, and remaining tuples have <em>i1</em> equal to the <em>i2</em> from the preceding
tuple, and, likewise, <em>j1</em> equal to the previous <em>j2</em>.</p>
<p>The <em>tag</em> values are strings, with these meanings:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'replace'</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">a[i1:i2]</span></code> should be replaced by
<code class="docutils literal notranslate"><span class="pre">b[j1:j2]</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'delete'</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">a[i1:i2]</span></code> should be deleted.  Note that
<code class="docutils literal notranslate"><span class="pre">j1</span> <span class="pre">==</span> <span class="pre">j2</span></code> in this case.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'insert'</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">b[j1:j2]</span></code> should be inserted at
<code class="docutils literal notranslate"><span class="pre">a[i1:i1]</span></code>. Note that <code class="docutils literal notranslate"><span class="pre">i1</span> <span class="pre">==</span> <span class="pre">i2</span></code> in
this case.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'equal'</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">a[i1:i2]</span> <span class="pre">==</span> <span class="pre">b[j1:j2]</span></code> (the sub-sequences
are equal).</td>
</tr>
</tbody>
</table>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="s2">&quot;qabxcd&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="s2">&quot;abycdf&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">tag</span><span class="p">,</span> <span class="n">i1</span><span class="p">,</span> <span class="n">i2</span><span class="p">,</span> <span class="n">j1</span><span class="p">,</span> <span class="n">j2</span> <span class="ow">in</span> <span class="n">s</span><span class="o">.</span><span class="n">get_opcodes</span><span class="p">():</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="p">(</span><span class="s2">&quot;</span><span class="si">%7s</span><span class="s2"> a[</span><span class="si">%d</span><span class="s2">:</span><span class="si">%d</span><span class="s2">] (</span><span class="si">%s</span><span class="s2">) b[</span><span class="si">%d</span><span class="s2">:</span><span class="si">%d</span><span class="s2">] (</span><span class="si">%s</span><span class="s2">)&quot;</span> <span class="o">%</span>
<span class="gp">... </span>          <span class="p">(</span><span class="n">tag</span><span class="p">,</span> <span class="n">i1</span><span class="p">,</span> <span class="n">i2</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="n">i1</span><span class="p">:</span><span class="n">i2</span><span class="p">],</span> <span class="n">j1</span><span class="p">,</span> <span class="n">j2</span><span class="p">,</span> <span class="n">b</span><span class="p">[</span><span class="n">j1</span><span class="p">:</span><span class="n">j2</span><span class="p">]))</span>
<span class="go"> delete a[0:1] (q) b[0:0] ()</span>
<span class="go">  equal a[1:3] (ab) b[0:2] (ab)</span>
<span class="go">replace a[3:4] (x) b[2:3] (y)</span>
<span class="go">  equal a[4:6] (cd) b[3:5] (cd)</span>
<span class="go"> insert a[6:6] () b[5:6] (f)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.get_grouped_opcodes">
<code class="descname">get_grouped_opcodes</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.get_grouped_opcodes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a> of groups with up to <em>n</em> lines of context.</p>
<p>Starting with the groups returned by <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_opcodes()</span></code></a>, this method
splits out smaller change clusters and eliminates intervening ranges which
have no changes.</p>
<p>The groups are returned in the same format as <a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_opcodes()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.ratio">
<code class="descname">ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.ratio" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a measure of the sequences’ similarity as a float in the range [0,
1].</p>
<p>Where T is the total number of elements in both sequences, and M is the
number of matches, this is 2.0*M / T. Note that this is <code class="docutils literal notranslate"><span class="pre">1.0</span></code> if the
sequences are identical, and <code class="docutils literal notranslate"><span class="pre">0.0</span></code> if they have nothing in common.</p>
<p>This is expensive to compute if <a class="reference internal" href="#difflib.SequenceMatcher.get_matching_blocks" title="difflib.SequenceMatcher.get_matching_blocks"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_matching_blocks()</span></code></a> or
<a class="reference internal" href="#difflib.SequenceMatcher.get_opcodes" title="difflib.SequenceMatcher.get_opcodes"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_opcodes()</span></code></a> hasn’t already been called, in which case you may want
to try <a class="reference internal" href="#difflib.SequenceMatcher.quick_ratio" title="difflib.SequenceMatcher.quick_ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">quick_ratio()</span></code></a> or <a class="reference internal" href="#difflib.SequenceMatcher.real_quick_ratio" title="difflib.SequenceMatcher.real_quick_ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">real_quick_ratio()</span></code></a> first to get an
upper bound.</p>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.quick_ratio">
<code class="descname">quick_ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.quick_ratio" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an upper bound on <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ratio()</span></code></a> relatively quickly.</p>
</dd></dl>

<dl class="method">
<dt id="difflib.SequenceMatcher.real_quick_ratio">
<code class="descname">real_quick_ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#difflib.SequenceMatcher.real_quick_ratio" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an upper bound on <a class="reference internal" href="#difflib.SequenceMatcher.ratio" title="difflib.SequenceMatcher.ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ratio()</span></code></a> very quickly.</p>
</dd></dl>

</dd></dl>

<p>The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although
<code class="xref py py-meth docutils literal notranslate"><span class="pre">quick_ratio()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">real_quick_ratio()</span></code> are always at least as large as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">ratio()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s2">&quot;abcd&quot;</span><span class="p">,</span> <span class="s2">&quot;bcde&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">ratio</span><span class="p">()</span>
<span class="go">0.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">quick_ratio</span><span class="p">()</span>
<span class="go">0.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">real_quick_ratio</span><span class="p">()</span>
<span class="go">1.0</span>
</pre></div>
</div>
</div>
<div class="section" id="sequencematcher-examples">
<span id="id1"></span><h2>7.4.2. SequenceMatcher Examples<a class="headerlink" href="#sequencematcher-examples" title="Permalink to this headline">¶</a></h2>
<p>This example compares two strings, considering blanks to be “junk:”</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SequenceMatcher</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">==</span> <span class="s2">&quot; &quot;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="s2">&quot;private Thread currentThread;&quot;</span><span class="p">,</span>
<span class="gp">... </span>                    <span class="s2">&quot;private volatile Thread currentThread;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">ratio()</span></code> returns a float in [0, 1], measuring the similarity of the
sequences.  As a rule of thumb, a <code class="xref py py-meth docutils literal notranslate"><span class="pre">ratio()</span></code> value over 0.6 means the
sequences are close matches:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">round</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">ratio</span><span class="p">(),</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">0.866</span>
</pre></div>
</div>
<p>If you’re only interested in where the sequences match,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_matching_blocks()</span></code> is handy:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">block</span> <span class="ow">in</span> <span class="n">s</span><span class="o">.</span><span class="n">get_matching_blocks</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;a[</span><span class="si">%d</span><span class="s2">] and b[</span><span class="si">%d</span><span class="s2">] match for </span><span class="si">%d</span><span class="s2"> elements&quot;</span> <span class="o">%</span> <span class="n">block</span>
<span class="go">a[0] and b[0] match for 8 elements</span>
<span class="go">a[8] and b[17] match for 21 elements</span>
<span class="go">a[29] and b[38] match for 0 elements</span>
</pre></div>
</div>
<p>Note that the last tuple returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_matching_blocks()</span></code> is always a
dummy, <code class="docutils literal notranslate"><span class="pre">(len(a),</span> <span class="pre">len(b),</span> <span class="pre">0)</span></code>, and this is the only case in which the last
tuple element (number of elements matched) is <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<p>If you want to know how to change the first sequence into the second, use
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_opcodes()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">opcode</span> <span class="ow">in</span> <span class="n">s</span><span class="o">.</span><span class="n">get_opcodes</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">%6s</span><span class="s2"> a[</span><span class="si">%d</span><span class="s2">:</span><span class="si">%d</span><span class="s2">] b[</span><span class="si">%d</span><span class="s2">:</span><span class="si">%d</span><span class="s2">]&quot;</span> <span class="o">%</span> <span class="n">opcode</span>
<span class="go"> equal a[0:8] b[0:8]</span>
<span class="go">insert a[8:8] b[8:17]</span>
<span class="go"> equal a[8:29] b[17:38]</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li>The <a class="reference internal" href="#difflib.get_close_matches" title="difflib.get_close_matches"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_close_matches()</span></code></a> function in this module which shows how
simple code building on <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a> can be used to do useful
work.</li>
<li><a class="reference external" href="https://code.activestate.com/recipes/576729/">Simple version control recipe</a> for a small application
built with <a class="reference internal" href="#difflib.SequenceMatcher" title="difflib.SequenceMatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code></a>.</li>
</ul>
</div>
</div>
<div class="section" id="differ-objects">
<span id="id2"></span><h2>7.4.3. Differ Objects<a class="headerlink" href="#differ-objects" title="Permalink to this headline">¶</a></h2>
<p>Note that <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a>-generated deltas make no claim to be <strong>minimal</strong>
diffs. To the contrary, minimal diffs are often counter-intuitive, because they
synch up anywhere possible, sometimes accidental matches 100 pages apart.
Restricting synch points to contiguous matches preserves some notion of
locality, at the occasional cost of producing a longer diff.</p>
<p>The <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a> class has this constructor:</p>
<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">difflib.</code><code class="descname">Differ</code><span class="sig-paren">(</span><span class="optional">[</span><em>linejunk</em><span class="optional">[</span>, <em>charjunk</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Optional keyword parameters <em>linejunk</em> and <em>charjunk</em> are for filter functions
(or <code class="docutils literal notranslate"><span class="pre">None</span></code>):</p>
<p><em>linejunk</em>: A function that accepts a single string argument, and returns true
if the string is junk.  The default is <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning that no line is
considered junk.</p>
<p><em>charjunk</em>: A function that accepts a single character argument (a string of
length 1), and returns true if the character is junk. The default is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
meaning that no character is considered junk.</p>
<p><a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a> objects are used (deltas generated) via a single method:</p>
<dl class="method">
<dt id="difflib.Differ.compare">
<code class="descname">compare</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#difflib.Differ.compare" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare two sequences of lines, and generate the delta (a sequence of lines).</p>
<p>Each sequence must contain individual single-line strings ending with
newlines.  Such sequences can be obtained from the
<a class="reference internal" href="stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a> method of file-like objects.  The delta
generated also consists of newline-terminated strings, ready to be
printed as-is via the <a class="reference internal" href="stdtypes.html#file.writelines" title="file.writelines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writelines()</span></code></a> method of a
file-like object.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="differ-example">
<span id="differ-examples"></span><h2>7.4.4. Differ Example<a class="headerlink" href="#differ-example" title="Permalink to this headline">¶</a></h2>
<p>This example compares two texts. First we set up the texts, sequences of
individual single-line strings ending with newlines (such sequences can also be
obtained from the <a class="reference internal" href="stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a> method of file-like objects):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text1</span> <span class="o">=</span> <span class="s1">&#39;&#39;&#39;  1. Beautiful is better than ugly.</span>
<span class="gp">... </span><span class="s1">  2. Explicit is better than implicit.</span>
<span class="gp">... </span><span class="s1">  3. Simple is better than complex.</span>
<span class="gp">... </span><span class="s1">  4. Complex is better than complicated.</span>
<span class="gp">... </span><span class="s1">&#39;&#39;&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">text1</span><span class="p">)</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text1</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text2</span> <span class="o">=</span> <span class="s1">&#39;&#39;&#39;  1. Beautiful is better than ugly.</span>
<span class="gp">... </span><span class="s1">  3.   Simple is better than complex.</span>
<span class="gp">... </span><span class="s1">  4. Complicated is better than complex.</span>
<span class="gp">... </span><span class="s1">  5. Flat is better than nested.</span>
<span class="gp">... </span><span class="s1">&#39;&#39;&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Next we instantiate a Differ object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">Differ</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that when instantiating a <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code></a> object we may pass functions to
filter out line and character “junk.”  See the <a class="reference internal" href="#difflib.Differ" title="difflib.Differ"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Differ()</span></code></a> constructor for
details.</p>
<p>Finally, we compare the two:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">result</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">compare</span><span class="p">(</span><span class="n">text1</span><span class="p">,</span> <span class="n">text2</span><span class="p">))</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">result</span></code> is a list of strings, so let’s pretty-print it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pprint</span> <span class="k">import</span> <span class="n">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
<span class="go">[&#39;    1. Beautiful is better than ugly.\n&#39;,</span>
<span class="go"> &#39;-   2. Explicit is better than implicit.\n&#39;,</span>
<span class="go"> &#39;-   3. Simple is better than complex.\n&#39;,</span>
<span class="go"> &#39;+   3.   Simple is better than complex.\n&#39;,</span>
<span class="go"> &#39;?     ++\n&#39;,</span>
<span class="go"> &#39;-   4. Complex is better than complicated.\n&#39;,</span>
<span class="go"> &#39;?            ^                     ---- ^\n&#39;,</span>
<span class="go"> &#39;+   4. Complicated is better than complex.\n&#39;,</span>
<span class="go"> &#39;?           ++++ ^                      ^\n&#39;,</span>
<span class="go"> &#39;+   5. Flat is better than nested.\n&#39;]</span>
</pre></div>
</div>
<p>As a single multi-line string it looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">writelines</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
<span class="go">    1. Beautiful is better than ugly.</span>
<span class="go">-   2. Explicit is better than implicit.</span>
<span class="go">-   3. Simple is better than complex.</span>
<span class="go">+   3.   Simple is better than complex.</span>
<span class="go">?     ++</span>
<span class="go">-   4. Complex is better than complicated.</span>
<span class="go">?            ^                     ---- ^</span>
<span class="go">+   4. Complicated is better than complex.</span>
<span class="go">?           ++++ ^                      ^</span>
<span class="go">+   5. Flat is better than nested.</span>
</pre></div>
</div>
</div>
<div class="section" id="a-command-line-interface-to-difflib">
<span id="difflib-interface"></span><h2>7.4.5. A command-line interface to difflib<a class="headerlink" href="#a-command-line-interface-to-difflib" title="Permalink to this headline">¶</a></h2>
<p>This example shows how to use difflib to create a <code class="docutils literal notranslate"><span class="pre">diff</span></code>-like utility.
It is also contained in the Python source distribution, as
<code class="file docutils literal notranslate"><span class="pre">Tools/scripts/diff.py</span></code>.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot; Command line interface to difflib.py providing diffs in four formats:</span>

<span class="sd">* ndiff:    lists every line and highlights interline changes.</span>
<span class="sd">* context:  highlights clusters of changes in a before/after format.</span>
<span class="sd">* unified:  highlights clusters of changes in an inline format.</span>
<span class="sd">* html:     generates side by side comparison with change highlights.</span>

<span class="sd">&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">difflib</span><span class="o">,</span> <span class="nn">optparse</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
     <span class="c1"># Configure the option parser</span>
    <span class="n">usage</span> <span class="o">=</span> <span class="s2">&quot;usage: %prog [options] fromfile tofile&quot;</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">optparse</span><span class="o">.</span><span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;Produce a context format diff (default)&#39;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-u&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;Produce a unified format diff&#39;</span><span class="p">)</span>
    <span class="n">hlp</span> <span class="o">=</span> <span class="s1">&#39;Produce HTML side by side diff (can use -c and -l in conjunction)&#39;</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-m&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">hlp</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;Produce a ndiff format diff&#39;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-l&quot;</span><span class="p">,</span> <span class="s2">&quot;--lines&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;int&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;Set number of context lines (default 3)&#39;</span><span class="p">)</span>
    <span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">2</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&quot;need to specify both a fromfile and tofile&quot;</span><span class="p">)</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">options</span><span class="o">.</span><span class="n">lines</span>
    <span class="n">fromfile</span><span class="p">,</span> <span class="n">tofile</span> <span class="o">=</span> <span class="n">args</span> <span class="c1"># as specified in the usage string</span>

    <span class="c1"># we&#39;re passing these as arguments to the diff function</span>
    <span class="n">fromdate</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">ctime</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="n">fromfile</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span><span class="p">)</span>
    <span class="n">todate</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">ctime</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="n">tofile</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span><span class="p">)</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">fromfile</span><span class="p">,</span> <span class="s1">&#39;U&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">fromlines</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">tofile</span><span class="p">,</span> <span class="s1">&#39;U&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">tolines</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">options</span><span class="o">.</span><span class="n">u</span><span class="p">:</span>
        <span class="n">diff</span> <span class="o">=</span> <span class="n">difflib</span><span class="o">.</span><span class="n">unified_diff</span><span class="p">(</span><span class="n">fromlines</span><span class="p">,</span> <span class="n">tolines</span><span class="p">,</span> <span class="n">fromfile</span><span class="p">,</span> <span class="n">tofile</span><span class="p">,</span>
                                    <span class="n">fromdate</span><span class="p">,</span> <span class="n">todate</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">n</span><span class="p">)</span>
    <span class="k">elif</span> <span class="n">options</span><span class="o">.</span><span class="n">n</span><span class="p">:</span>
        <span class="n">diff</span> <span class="o">=</span> <span class="n">difflib</span><span class="o">.</span><span class="n">ndiff</span><span class="p">(</span><span class="n">fromlines</span><span class="p">,</span> <span class="n">tolines</span><span class="p">)</span>
    <span class="k">elif</span> <span class="n">options</span><span class="o">.</span><span class="n">m</span><span class="p">:</span>
        <span class="n">diff</span> <span class="o">=</span> <span class="n">difflib</span><span class="o">.</span><span class="n">HtmlDiff</span><span class="p">()</span><span class="o">.</span><span class="n">make_file</span><span class="p">(</span><span class="n">fromlines</span><span class="p">,</span> <span class="n">tolines</span><span class="p">,</span> <span class="n">fromfile</span><span class="p">,</span>
                                            <span class="n">tofile</span><span class="p">,</span> <span class="n">context</span><span class="o">=</span><span class="n">options</span><span class="o">.</span><span class="n">c</span><span class="p">,</span>
                                            <span class="n">numlines</span><span class="o">=</span><span class="n">n</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">diff</span> <span class="o">=</span> <span class="n">difflib</span><span class="o">.</span><span class="n">context_diff</span><span class="p">(</span><span class="n">fromlines</span><span class="p">,</span> <span class="n">tolines</span><span class="p">,</span> <span class="n">fromfile</span><span class="p">,</span> <span class="n">tofile</span><span class="p">,</span>
                                    <span class="n">fromdate</span><span class="p">,</span> <span class="n">todate</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">n</span><span class="p">)</span>

    <span class="c1"># we&#39;re using writelines because diff is a generator</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">writelines</span><span class="p">(</span><span class="n">diff</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a><ul>
<li><a class="reference internal" href="#sequencematcher-objects">7.4.1. SequenceMatcher Objects</a></li>
<li><a class="reference internal" href="#sequencematcher-examples">7.4.2. SequenceMatcher Examples</a></li>
<li><a class="reference internal" href="#differ-objects">7.4.3. Differ Objects</a></li>
<li><a class="reference internal" href="#differ-example">7.4.4. Differ Example</a></li>
<li><a class="reference internal" href="#a-command-line-interface-to-difflib">7.4.5. A command-line interface to difflib</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="struct.html"
                        title="previous chapter">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stringio.html"
                        title="next chapter">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/difflib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stringio.html" title="7.5. StringIO — Read and write strings as files"
             >next</a> |</li>
        <li class="right" >
          <a href="struct.html" title="7.3. struct — Interpret strings as packed binary data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����00html/library/dircache.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.11. dircache — Cached directory listings &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.12. macpath — Mac OS 9 path manipulation functions" href="macpath.html" />
    <link rel="prev" title="10.10. shutil — High-level file operations" href="shutil.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dircache.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macpath.html" title="10.12. macpath — Mac OS 9 path manipulation functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="shutil.html" title="10.10. shutil — High-level file operations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dircache">
<span id="dircache-cached-directory-listings"></span><h1>10.11. <a class="reference internal" href="#module-dircache" title="dircache: Return directory listing, with cache mechanism. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code></a> — Cached directory listings<a class="headerlink" href="#module-dircache" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-dircache" title="dircache: Return directory listing, with cache mechanism. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-dircache" title="dircache: Return directory listing, with cache mechanism. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code></a> module defines a function for reading directory listing
using a cache, and cache invalidation using the <em>mtime</em> of the directory.
Additionally, it defines a function to annotate directories by appending a
slash.</p>
<p>The <a class="reference internal" href="#module-dircache" title="dircache: Return directory listing, with cache mechanism. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="dircache.reset">
<code class="descclassname">dircache.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dircache.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the directory cache.</p>
</dd></dl>

<dl class="function">
<dt id="dircache.listdir">
<code class="descclassname">dircache.</code><code class="descname">listdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#dircache.listdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a directory listing of <em>path</em>, as gotten from <a class="reference internal" href="os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>. Note
that unless <em>path</em> changes, further call to <a class="reference internal" href="#dircache.listdir" title="dircache.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">listdir()</span></code></a> will not re-read the
directory structure.</p>
<p>Note that the list returned should be regarded as read-only. (Perhaps a future
version should change it to return a tuple?)</p>
</dd></dl>

<dl class="function">
<dt id="dircache.opendir">
<code class="descclassname">dircache.</code><code class="descname">opendir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#dircache.opendir" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#dircache.listdir" title="dircache.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">listdir()</span></code></a>. Defined for backwards compatibility.</p>
</dd></dl>

<dl class="function">
<dt id="dircache.annotate">
<code class="descclassname">dircache.</code><code class="descname">annotate</code><span class="sig-paren">(</span><em>head</em>, <em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#dircache.annotate" title="Permalink to this definition">¶</a></dt>
<dd><p>Assume <em>list</em> is a list of paths relative to <em>head</em>, and append, in place, a
<code class="docutils literal notranslate"><span class="pre">'/'</span></code> to each path which points to a directory.</p>
</dd></dl>

<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">dircache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">dircache</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">a</span><span class="p">[:]</span> <span class="c1"># Copy the return value so we can change &#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[&#39;bin&#39;, &#39;boot&#39;, &#39;cdrom&#39;, &#39;dev&#39;, &#39;etc&#39;, &#39;floppy&#39;, &#39;home&#39;, &#39;initrd&#39;, &#39;lib&#39;, &#39;lost+</span>
<span class="go">found&#39;, &#39;mnt&#39;, &#39;proc&#39;, &#39;root&#39;, &#39;sbin&#39;, &#39;tmp&#39;, &#39;usr&#39;, &#39;var&#39;, &#39;vmlinuz&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dircache</span><span class="o">.</span><span class="n">annotate</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[&#39;bin/&#39;, &#39;boot/&#39;, &#39;cdrom/&#39;, &#39;dev/&#39;, &#39;etc/&#39;, &#39;floppy/&#39;, &#39;home/&#39;, &#39;initrd/&#39;, &#39;lib/</span>
<span class="go">&#39;, &#39;lost+found/&#39;, &#39;mnt/&#39;, &#39;proc/&#39;, &#39;root/&#39;, &#39;sbin/&#39;, &#39;tmp/&#39;, &#39;usr/&#39;, &#39;var/&#39;, &#39;vm</span>
<span class="go">linuz&#39;]</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="shutil.html"
                        title="previous chapter">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="macpath.html"
                        title="next chapter">10.12. <code class="docutils literal notranslate"><span class="pre">macpath</span></code> — Mac OS 9 path manipulation functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dircache.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macpath.html" title="10.12. macpath — Mac OS 9 path manipulation functions"
             >next</a> |</li>
        <li class="right" >
          <a href="shutil.html" title="10.10. shutil — High-level file operations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\oԝ�H�Hhtml/library/dis.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.12. dis — Disassembler for Python bytecode &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.13. pickletools — Tools for pickle developers" href="pickletools.html" />
    <link rel="prev" title="32.11. compileall — Byte-compile Python libraries" href="compileall.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dis.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pickletools.html" title="32.13. pickletools — Tools for pickle developers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="compileall.html" title="32.11. compileall — Byte-compile Python libraries"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dis">
<span id="dis-disassembler-for-python-bytecode"></span><h1>32.12. <a class="reference internal" href="#module-dis" title="dis: Disassembler for Python bytecode."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dis</span></code></a> — Disassembler for Python bytecode<a class="headerlink" href="#module-dis" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/dis.py">Lib/dis.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-dis" title="dis: Disassembler for Python bytecode."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dis</span></code></a> module supports the analysis of CPython <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> by
disassembling it. The CPython bytecode which this module takes as an input is
defined in the file <code class="file docutils literal notranslate"><span class="pre">Include/opcode.h</span></code> and used by the compiler and the
interpreter.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Bytecode is an implementation detail of the CPython interpreter!  No
guarantees are made that bytecode will not be added, removed, or changed
between versions of Python.  Use of this module should not be considered to
work across Python VMs or Python releases.</p>
</div>
<p>Example: Given the function <code class="xref py py-func docutils literal notranslate"><span class="pre">myfunc()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">myfunc</span><span class="p">(</span><span class="n">alist</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">alist</span><span class="p">)</span>
</pre></div>
</div>
<p>the following command can be used to get the disassembly of <code class="xref py py-func docutils literal notranslate"><span class="pre">myfunc()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">dis</span><span class="o">.</span><span class="n">dis</span><span class="p">(</span><span class="n">myfunc</span><span class="p">)</span>
<span class="go">  2           0 LOAD_GLOBAL              0 (len)</span>
<span class="go">              3 LOAD_FAST                0 (alist)</span>
<span class="go">              6 CALL_FUNCTION            1</span>
<span class="go">              9 RETURN_VALUE</span>
</pre></div>
</div>
<p>(The “2” is a line number).</p>
<p>The <a class="reference internal" href="#module-dis" title="dis: Disassembler for Python bytecode."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dis</span></code></a> module defines the following functions and constants:</p>
<dl class="function">
<dt id="dis.dis">
<code class="descclassname">dis.</code><code class="descname">dis</code><span class="sig-paren">(</span><span class="optional">[</span><em>bytesource</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dis.dis" title="Permalink to this definition">¶</a></dt>
<dd><p>Disassemble the <em>bytesource</em> object. <em>bytesource</em> can denote either a module,
a class, a method, a function, or a code object.  For a module, it
disassembles all functions.  For a class, it disassembles all methods.  For a
single code sequence, it prints one line per bytecode instruction.  If no
object is provided, it disassembles the last traceback.</p>
</dd></dl>

<dl class="function">
<dt id="dis.distb">
<code class="descclassname">dis.</code><code class="descname">distb</code><span class="sig-paren">(</span><span class="optional">[</span><em>tb</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dis.distb" title="Permalink to this definition">¶</a></dt>
<dd><p>Disassembles the top-of-stack function of a traceback, using the last
traceback if none was passed.  The instruction causing the exception is
indicated.</p>
</dd></dl>

<dl class="function">
<dt id="dis.disassemble">
<code class="descclassname">dis.</code><code class="descname">disassemble</code><span class="sig-paren">(</span><em>code</em><span class="optional">[</span>, <em>lasti</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dis.disassemble" title="Permalink to this definition">¶</a></dt>
<dd><p>Disassembles a code object, indicating the last instruction if <em>lasti</em> was
provided.  The output is divided in the following columns:</p>
<ol class="arabic simple">
<li>the line number, for the first instruction of each line</li>
<li>the current instruction, indicated as <code class="docutils literal notranslate"><span class="pre">--&gt;</span></code>,</li>
<li>a labelled instruction, indicated with <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>,</li>
<li>the address of the instruction,</li>
<li>the operation code name,</li>
<li>operation parameters, and</li>
<li>interpretation of the parameters in parentheses.</li>
</ol>
<p>The parameter interpretation recognizes local and global variable names,
constant values, branch targets, and compare operators.</p>
</dd></dl>

<dl class="function">
<dt id="dis.disco">
<code class="descclassname">dis.</code><code class="descname">disco</code><span class="sig-paren">(</span><em>code</em><span class="optional">[</span>, <em>lasti</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dis.disco" title="Permalink to this definition">¶</a></dt>
<dd><p>A synonym for <a class="reference internal" href="#dis.disassemble" title="dis.disassemble"><code class="xref py py-func docutils literal notranslate"><span class="pre">disassemble()</span></code></a>.  It is more convenient to type, and kept
for compatibility with earlier Python releases.</p>
</dd></dl>

<dl class="function">
<dt id="dis.findlinestarts">
<code class="descclassname">dis.</code><code class="descname">findlinestarts</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#dis.findlinestarts" title="Permalink to this definition">¶</a></dt>
<dd><p>This generator function uses the <code class="docutils literal notranslate"><span class="pre">co_firstlineno</span></code> and <code class="docutils literal notranslate"><span class="pre">co_lnotab</span></code>
attributes of the code object <em>code</em> to find the offsets which are starts of
lines in the source code.  They are generated as <code class="docutils literal notranslate"><span class="pre">(offset,</span> <span class="pre">lineno)</span></code> pairs.</p>
</dd></dl>

<dl class="function">
<dt id="dis.findlabels">
<code class="descclassname">dis.</code><code class="descname">findlabels</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#dis.findlabels" title="Permalink to this definition">¶</a></dt>
<dd><p>Detect all offsets in the code object <em>code</em> which are jump targets, and
return a list of these offsets.</p>
</dd></dl>

<dl class="data">
<dt id="dis.opname">
<code class="descclassname">dis.</code><code class="descname">opname</code><a class="headerlink" href="#dis.opname" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of operation names, indexable using the bytecode.</p>
</dd></dl>

<dl class="data">
<dt id="dis.opmap">
<code class="descclassname">dis.</code><code class="descname">opmap</code><a class="headerlink" href="#dis.opmap" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping operation names to bytecodes.</p>
</dd></dl>

<dl class="data">
<dt id="dis.cmp_op">
<code class="descclassname">dis.</code><code class="descname">cmp_op</code><a class="headerlink" href="#dis.cmp_op" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of all compare operation names.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hasconst">
<code class="descclassname">dis.</code><code class="descname">hasconst</code><a class="headerlink" href="#dis.hasconst" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that access a constant.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hasfree">
<code class="descclassname">dis.</code><code class="descname">hasfree</code><a class="headerlink" href="#dis.hasfree" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that access a free variable.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hasname">
<code class="descclassname">dis.</code><code class="descname">hasname</code><a class="headerlink" href="#dis.hasname" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that access an attribute by name.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hasjrel">
<code class="descclassname">dis.</code><code class="descname">hasjrel</code><a class="headerlink" href="#dis.hasjrel" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that have a relative jump target.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hasjabs">
<code class="descclassname">dis.</code><code class="descname">hasjabs</code><a class="headerlink" href="#dis.hasjabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that have an absolute jump target.</p>
</dd></dl>

<dl class="data">
<dt id="dis.haslocal">
<code class="descclassname">dis.</code><code class="descname">haslocal</code><a class="headerlink" href="#dis.haslocal" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes that access a local variable.</p>
</dd></dl>

<dl class="data">
<dt id="dis.hascompare">
<code class="descclassname">dis.</code><code class="descname">hascompare</code><a class="headerlink" href="#dis.hascompare" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence of bytecodes of Boolean operations.</p>
</dd></dl>

<div class="section" id="python-bytecode-instructions">
<span id="bytecodes"></span><h2>32.12.1. Python Bytecode Instructions<a class="headerlink" href="#python-bytecode-instructions" title="Permalink to this headline">¶</a></h2>
<p>The Python compiler currently generates the following bytecode instructions.</p>
<dl class="opcode">
<dt id="opcode-STOP_CODE">
<code class="descname">STOP_CODE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STOP_CODE" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates end-of-code to the compiler, not used by the interpreter.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-NOP">
<code class="descname">NOP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-NOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Do nothing code.  Used as a placeholder by the bytecode optimizer.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-POP_TOP">
<code class="descname">POP_TOP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-POP_TOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the top-of-stack (TOS) item.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-ROT_TWO">
<code class="descname">ROT_TWO</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-ROT_TWO" title="Permalink to this definition">¶</a></dt>
<dd><p>Swaps the two top-most stack items.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-ROT_THREE">
<code class="descname">ROT_THREE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-ROT_THREE" title="Permalink to this definition">¶</a></dt>
<dd><p>Lifts second and third stack item one position up, moves top down to position
three.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-ROT_FOUR">
<code class="descname">ROT_FOUR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-ROT_FOUR" title="Permalink to this definition">¶</a></dt>
<dd><p>Lifts second, third and forth stack item one position up, moves top down to
position four.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DUP_TOP">
<code class="descname">DUP_TOP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DUP_TOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicates the reference on top of the stack.</p>
</dd></dl>

<p>Unary Operations take the top of the stack, apply the operation, and push the
result back on the stack.</p>
<dl class="opcode">
<dt id="opcode-UNARY_POSITIVE">
<code class="descname">UNARY_POSITIVE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNARY_POSITIVE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">+TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-UNARY_NEGATIVE">
<code class="descname">UNARY_NEGATIVE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNARY_NEGATIVE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">-TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-UNARY_NOT">
<code class="descname">UNARY_NOT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNARY_NOT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">not</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-UNARY_CONVERT">
<code class="descname">UNARY_CONVERT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNARY_CONVERT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">`TOS`</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-UNARY_INVERT">
<code class="descname">UNARY_INVERT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNARY_INVERT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">~TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-GET_ITER">
<code class="descname">GET_ITER</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-GET_ITER" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">iter(TOS)</span></code>.</p>
</dd></dl>

<p>Binary operations remove the top of the stack (TOS) and the second top-most
stack item (TOS1) from the stack.  They perform the operation, and put the
result back on the stack.</p>
<dl class="opcode">
<dt id="opcode-BINARY_POWER">
<code class="descname">BINARY_POWER</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_POWER" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">**</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_MULTIPLY">
<code class="descname">BINARY_MULTIPLY</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_MULTIPLY" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">*</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_DIVIDE">
<code class="descname">BINARY_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">/</span> <span class="pre">TOS</span></code> when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code> is
not in effect.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_FLOOR_DIVIDE">
<code class="descname">BINARY_FLOOR_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_FLOOR_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">//</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_TRUE_DIVIDE">
<code class="descname">BINARY_TRUE_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_TRUE_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">/</span> <span class="pre">TOS</span></code> when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code> is
in effect.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_MODULO">
<code class="descname">BINARY_MODULO</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_MODULO" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">%</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_ADD">
<code class="descname">BINARY_ADD</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_ADD" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">+</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_SUBTRACT">
<code class="descname">BINARY_SUBTRACT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_SUBTRACT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">-</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_SUBSCR">
<code class="descname">BINARY_SUBSCR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_SUBSCR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1[TOS]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_LSHIFT">
<code class="descname">BINARY_LSHIFT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_LSHIFT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&lt;&lt;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_RSHIFT">
<code class="descname">BINARY_RSHIFT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_RSHIFT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&gt;&gt;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_AND">
<code class="descname">BINARY_AND</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_AND" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&amp;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_XOR">
<code class="descname">BINARY_XOR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_XOR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">^</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BINARY_OR">
<code class="descname">BINARY_OR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BINARY_OR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">|</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<p>In-place operations are like binary operations, in that they remove TOS and
TOS1, and push the result back on the stack, but the operation is done in-place
when TOS1 supports it, and the resulting TOS may be (but does not have to be)
the original TOS1.</p>
<dl class="opcode">
<dt id="opcode-INPLACE_POWER">
<code class="descname">INPLACE_POWER</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_POWER" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">**</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_MULTIPLY">
<code class="descname">INPLACE_MULTIPLY</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_MULTIPLY" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">*</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_DIVIDE">
<code class="descname">INPLACE_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">/</span> <span class="pre">TOS</span></code> when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span>
<span class="pre">division</span></code> is not in effect.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_FLOOR_DIVIDE">
<code class="descname">INPLACE_FLOOR_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_FLOOR_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">//</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_TRUE_DIVIDE">
<code class="descname">INPLACE_TRUE_DIVIDE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_TRUE_DIVIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">/</span> <span class="pre">TOS</span></code> when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span>
<span class="pre">division</span></code> is in effect.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_MODULO">
<code class="descname">INPLACE_MODULO</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_MODULO" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">%</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_ADD">
<code class="descname">INPLACE_ADD</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_ADD" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">+</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_SUBTRACT">
<code class="descname">INPLACE_SUBTRACT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_SUBTRACT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">-</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_LSHIFT">
<code class="descname">INPLACE_LSHIFT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_LSHIFT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&lt;&lt;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_RSHIFT">
<code class="descname">INPLACE_RSHIFT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_RSHIFT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&gt;&gt;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_AND">
<code class="descname">INPLACE_AND</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_AND" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">&amp;</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_XOR">
<code class="descname">INPLACE_XOR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_XOR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">^</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-INPLACE_OR">
<code class="descname">INPLACE_OR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-INPLACE_OR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements in-place <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1</span> <span class="pre">|</span> <span class="pre">TOS</span></code>.</p>
</dd></dl>

<p>The slice opcodes take up to three parameters.</p>
<dl class="opcode">
<dt id="opcode-SLICE+0">
<code class="descname">SLICE+0</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SLICE+0" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS[:]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SLICE+1">
<code class="descname">SLICE+1</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SLICE+1" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1[TOS:]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SLICE+2">
<code class="descname">SLICE+2</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SLICE+2" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS1[:TOS]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SLICE+3">
<code class="descname">SLICE+3</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SLICE+3" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS</span> <span class="pre">=</span> <span class="pre">TOS2[TOS1:TOS]</span></code>.</p>
</dd></dl>

<p>Slice assignment needs even an additional parameter.  As any statement, they put
nothing on the stack.</p>
<dl class="opcode">
<dt id="opcode-STORE_SLICE+0">
<code class="descname">STORE_SLICE+0</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_SLICE+0" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS[:]</span> <span class="pre">=</span> <span class="pre">TOS1</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_SLICE+1">
<code class="descname">STORE_SLICE+1</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_SLICE+1" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS1[TOS:]</span> <span class="pre">=</span> <span class="pre">TOS2</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_SLICE+2">
<code class="descname">STORE_SLICE+2</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_SLICE+2" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS1[:TOS]</span> <span class="pre">=</span> <span class="pre">TOS2</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_SLICE+3">
<code class="descname">STORE_SLICE+3</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_SLICE+3" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS2[TOS1:TOS]</span> <span class="pre">=</span> <span class="pre">TOS3</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_SLICE+0">
<code class="descname">DELETE_SLICE+0</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_SLICE+0" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS[:]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_SLICE+1">
<code class="descname">DELETE_SLICE+1</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_SLICE+1" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS1[TOS:]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_SLICE+2">
<code class="descname">DELETE_SLICE+2</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_SLICE+2" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS1[:TOS]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_SLICE+3">
<code class="descname">DELETE_SLICE+3</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_SLICE+3" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS2[TOS1:TOS]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_SUBSCR">
<code class="descname">STORE_SUBSCR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_SUBSCR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS1[TOS]</span> <span class="pre">=</span> <span class="pre">TOS2</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_SUBSCR">
<code class="descname">DELETE_SUBSCR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_SUBSCR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS1[TOS]</span></code>.</p>
</dd></dl>

<p>Miscellaneous opcodes.</p>
<dl class="opcode">
<dt id="opcode-PRINT_EXPR">
<code class="descname">PRINT_EXPR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-PRINT_EXPR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements the expression statement for the interactive mode.  TOS is removed
from the stack and printed.  In non-interactive mode, an expression statement
is terminated with <a class="reference internal" href="#opcode-POP_TOP"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">POP_TOP</span></code></a>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-PRINT_ITEM">
<code class="descname">PRINT_ITEM</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-PRINT_ITEM" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints TOS to the file-like object bound to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.  There is one
such instruction for each item in the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-PRINT_ITEM_TO">
<code class="descname">PRINT_ITEM_TO</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-PRINT_ITEM_TO" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">PRINT_ITEM</span></code>, but prints the item second from TOS to the file-like
object at TOS.  This is used by the extended print statement.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-PRINT_NEWLINE">
<code class="descname">PRINT_NEWLINE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-PRINT_NEWLINE" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints a new line on <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.  This is generated as the last operation
of a <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement, unless the statement ends with a comma.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-PRINT_NEWLINE_TO">
<code class="descname">PRINT_NEWLINE_TO</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-PRINT_NEWLINE_TO" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">PRINT_NEWLINE</span></code>, but prints the new line on the file-like object on
the TOS.  This is used by the extended print statement.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BREAK_LOOP">
<code class="descname">BREAK_LOOP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BREAK_LOOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Terminates a loop due to a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-CONTINUE_LOOP">
<code class="descname">CONTINUE_LOOP</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-CONTINUE_LOOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Continues a loop due to a <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement.  <em>target</em> is the
address to jump to (which should be a <a class="reference internal" href="#opcode-FOR_ITER"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">FOR_ITER</span></code></a> instruction).</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LIST_APPEND">
<code class="descname">LIST_APPEND</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LIST_APPEND" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls <code class="docutils literal notranslate"><span class="pre">list.append(TOS[-i],</span> <span class="pre">TOS)</span></code>.  Used to implement list comprehensions.
While the appended value is popped off, the list object remains on the stack
so that it is available for further iterations of the loop.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_LOCALS">
<code class="descname">LOAD_LOCALS</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_LOCALS" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a reference to the locals of the current scope on the stack. This is
used in the code for a class definition: After the class body is evaluated,
the locals are passed to the class definition.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-RETURN_VALUE">
<code class="descname">RETURN_VALUE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-RETURN_VALUE" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns with TOS to the caller of the function.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-YIELD_VALUE">
<code class="descname">YIELD_VALUE</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-YIELD_VALUE" title="Permalink to this definition">¶</a></dt>
<dd><p>Pops <code class="docutils literal notranslate"><span class="pre">TOS</span></code> and yields it from a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-IMPORT_STAR">
<code class="descname">IMPORT_STAR</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-IMPORT_STAR" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads all symbols not starting with <code class="docutils literal notranslate"><span class="pre">'_'</span></code> directly from the module TOS to
the local namespace. The module is popped after loading all names. This
opcode implements <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-EXEC_STMT">
<code class="descname">EXEC_STMT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-EXEC_STMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">exec</span> <span class="pre">TOS2,TOS1,TOS</span></code>.  The compiler fills missing optional
parameters with <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-POP_BLOCK">
<code class="descname">POP_BLOCK</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-POP_BLOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes one block from the block stack.  Per frame, there is a stack of
blocks, denoting nested loops, try statements, and such.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-END_FINALLY">
<code class="descname">END_FINALLY</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-END_FINALLY" title="Permalink to this definition">¶</a></dt>
<dd><p>Terminates a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.  The interpreter recalls whether the
exception has to be re-raised, or whether the function returns, and continues
with the outer-next block.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_CLASS">
<code class="descname">BUILD_CLASS</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_CLASS" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new class object.  TOS is the methods dictionary, TOS1 the tuple of
the names of the base classes, and TOS2 the class name.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SETUP_WITH">
<code class="descname">SETUP_WITH</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SETUP_WITH" title="Permalink to this definition">¶</a></dt>
<dd><p>This opcode performs several operations before a with block starts.  First,
it loads <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> from the context manager and pushes it onto
the stack for later use by <a class="reference internal" href="#opcode-WITH_CLEANUP"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">WITH_CLEANUP</span></code></a>.  Then,
<a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is called, and a finally block pointing to <em>delta</em>
is pushed.  Finally, the result of calling the enter method is pushed onto
the stack.  The next opcode will either ignore it (<a class="reference internal" href="#opcode-POP_TOP"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">POP_TOP</span></code></a>), or
store it in (a) variable(s) (<a class="reference internal" href="#opcode-STORE_FAST"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">STORE_FAST</span></code></a>, <a class="reference internal" href="#opcode-STORE_NAME"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">STORE_NAME</span></code></a>, or
<a class="reference internal" href="#opcode-UNPACK_SEQUENCE"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">UNPACK_SEQUENCE</span></code></a>).</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-WITH_CLEANUP">
<code class="descname">WITH_CLEANUP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-WITH_CLEANUP" title="Permalink to this definition">¶</a></dt>
<dd><p>Cleans up the stack when a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement block exits.  On top of
the stack are 1–3 values indicating how/why the finally clause was entered:</p>
<ul class="simple">
<li>TOP = <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>(TOP, SECOND) = (<code class="docutils literal notranslate"><span class="pre">WHY_{RETURN,CONTINUE}</span></code>), retval</li>
<li>TOP = <code class="docutils literal notranslate"><span class="pre">WHY_*</span></code>; no retval below it</li>
<li>(TOP, SECOND, THIRD) = exc_info()</li>
</ul>
<p>Under them is EXIT, the context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> bound method.</p>
<p>In the last case, <code class="docutils literal notranslate"><span class="pre">EXIT(TOP,</span> <span class="pre">SECOND,</span> <span class="pre">THIRD)</span></code> is called, otherwise
<code class="docutils literal notranslate"><span class="pre">EXIT(None,</span> <span class="pre">None,</span> <span class="pre">None)</span></code>.</p>
<p>EXIT is removed from the stack, leaving the values above it in the same
order. In addition, if the stack represents an exception, <em>and</em> the function
call returns a ‘true’ value, this information is “zapped”, to prevent
<code class="docutils literal notranslate"><span class="pre">END_FINALLY</span></code> from re-raising the exception.  (But non-local gotos should
still be resumed.)</p>
</dd></dl>

<p>All of the following opcodes expect arguments.  An argument is two bytes, with
the more significant byte last.</p>
<dl class="opcode">
<dt id="opcode-STORE_NAME">
<code class="descname">STORE_NAME</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_NAME" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">name</span> <span class="pre">=</span> <span class="pre">TOS</span></code>. <em>namei</em> is the index of <em>name</em> in the attribute
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code> of the code object. The compiler tries to use <code class="docutils literal notranslate"><span class="pre">STORE_FAST</span></code>
or <code class="docutils literal notranslate"><span class="pre">STORE_GLOBAL</span></code> if possible.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_NAME">
<code class="descname">DELETE_NAME</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_NAME" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">name</span></code>, where <em>namei</em> is the index into <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code>
attribute of the code object.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-UNPACK_SEQUENCE">
<code class="descname">UNPACK_SEQUENCE</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-UNPACK_SEQUENCE" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks TOS into <em>count</em> individual values, which are put onto the stack
right-to-left.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DUP_TOPX">
<code class="descname">DUP_TOPX</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DUP_TOPX" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicate <em>count</em> items, keeping them in the same order. Due to
implementation limits, <em>count</em> should be between 1 and 5 inclusive.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_ATTR">
<code class="descname">STORE_ATTR</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_ATTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">TOS.name</span> <span class="pre">=</span> <span class="pre">TOS1</span></code>, where <em>namei</em> is the index of name in
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_ATTR">
<code class="descname">DELETE_ATTR</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_ATTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Implements <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">TOS.name</span></code>, using <em>namei</em> as index into <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_GLOBAL">
<code class="descname">STORE_GLOBAL</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_GLOBAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Works as <code class="docutils literal notranslate"><span class="pre">STORE_NAME</span></code>, but stores the name as a global.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_GLOBAL">
<code class="descname">DELETE_GLOBAL</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_GLOBAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Works as <code class="docutils literal notranslate"><span class="pre">DELETE_NAME</span></code>, but deletes a global name.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_CONST">
<code class="descname">LOAD_CONST</code><span class="sig-paren">(</span><em>consti</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_CONST" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes <code class="docutils literal notranslate"><span class="pre">co_consts[consti]</span></code> onto the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_NAME">
<code class="descname">LOAD_NAME</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_NAME" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes the value associated with <code class="docutils literal notranslate"><span class="pre">co_names[namei]</span></code> onto the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_TUPLE">
<code class="descname">BUILD_TUPLE</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_TUPLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a tuple consuming <em>count</em> items from the stack, and pushes the
resulting tuple onto the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_LIST">
<code class="descname">BUILD_LIST</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_LIST" title="Permalink to this definition">¶</a></dt>
<dd><p>Works as <code class="docutils literal notranslate"><span class="pre">BUILD_TUPLE</span></code>, but creates a list.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_SET">
<code class="descname">BUILD_SET</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_SET" title="Permalink to this definition">¶</a></dt>
<dd><p>Works as <code class="docutils literal notranslate"><span class="pre">BUILD_TUPLE</span></code>, but creates a set.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_MAP">
<code class="descname">BUILD_MAP</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_MAP" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a new dictionary object onto the stack.  The dictionary is pre-sized
to hold <em>count</em> entries.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_ATTR">
<code class="descname">LOAD_ATTR</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_ATTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces TOS with <code class="docutils literal notranslate"><span class="pre">getattr(TOS,</span> <span class="pre">co_names[namei])</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-COMPARE_OP">
<code class="descname">COMPARE_OP</code><span class="sig-paren">(</span><em>opname</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-COMPARE_OP" title="Permalink to this definition">¶</a></dt>
<dd><p>Performs a Boolean operation.  The operation name can be found in
<code class="docutils literal notranslate"><span class="pre">cmp_op[opname]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-IMPORT_NAME">
<code class="descname">IMPORT_NAME</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-IMPORT_NAME" title="Permalink to this definition">¶</a></dt>
<dd><p>Imports the module <code class="docutils literal notranslate"><span class="pre">co_names[namei]</span></code>.  TOS and TOS1 are popped and provide
the <em>fromlist</em> and <em>level</em> arguments of <a class="reference internal" href="functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>.  The module
object is pushed onto the stack.  The current namespace is not affected: for
a proper import statement, a subsequent <code class="docutils literal notranslate"><span class="pre">STORE_FAST</span></code> instruction modifies
the namespace.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-IMPORT_FROM">
<code class="descname">IMPORT_FROM</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-IMPORT_FROM" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads the attribute <code class="docutils literal notranslate"><span class="pre">co_names[namei]</span></code> from the module found in TOS. The
resulting object is pushed onto the stack, to be subsequently stored by a
<code class="docutils literal notranslate"><span class="pre">STORE_FAST</span></code> instruction.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-JUMP_FORWARD">
<code class="descname">JUMP_FORWARD</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-JUMP_FORWARD" title="Permalink to this definition">¶</a></dt>
<dd><p>Increments bytecode counter by <em>delta</em>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-POP_JUMP_IF_TRUE">
<code class="descname">POP_JUMP_IF_TRUE</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-POP_JUMP_IF_TRUE" title="Permalink to this definition">¶</a></dt>
<dd><p>If TOS is true, sets the bytecode counter to <em>target</em>.  TOS is popped.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-POP_JUMP_IF_FALSE">
<code class="descname">POP_JUMP_IF_FALSE</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-POP_JUMP_IF_FALSE" title="Permalink to this definition">¶</a></dt>
<dd><p>If TOS is false, sets the bytecode counter to <em>target</em>.  TOS is popped.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-JUMP_IF_TRUE_OR_POP">
<code class="descname">JUMP_IF_TRUE_OR_POP</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-JUMP_IF_TRUE_OR_POP" title="Permalink to this definition">¶</a></dt>
<dd><p>If TOS is true, sets the bytecode counter to <em>target</em> and leaves TOS on the
stack.  Otherwise (TOS is false), TOS is popped.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-JUMP_IF_FALSE_OR_POP">
<code class="descname">JUMP_IF_FALSE_OR_POP</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-JUMP_IF_FALSE_OR_POP" title="Permalink to this definition">¶</a></dt>
<dd><p>If TOS is false, sets the bytecode counter to <em>target</em> and leaves TOS on the
stack.  Otherwise (TOS is true), TOS is popped.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-JUMP_ABSOLUTE">
<code class="descname">JUMP_ABSOLUTE</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-JUMP_ABSOLUTE" title="Permalink to this definition">¶</a></dt>
<dd><p>Set bytecode counter to <em>target</em>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-FOR_ITER">
<code class="descname">FOR_ITER</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-FOR_ITER" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">TOS</span></code> is an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.  Call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method.  If this
yields a new value, push it on the stack (leaving the iterator below it).  If
the iterator indicates it is exhausted <code class="docutils literal notranslate"><span class="pre">TOS</span></code> is popped, and the bytecode
counter is incremented by <em>delta</em>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_GLOBAL">
<code class="descname">LOAD_GLOBAL</code><span class="sig-paren">(</span><em>namei</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_GLOBAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads the global named <code class="docutils literal notranslate"><span class="pre">co_names[namei]</span></code> onto the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SETUP_LOOP">
<code class="descname">SETUP_LOOP</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SETUP_LOOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a block for a loop onto the block stack.  The block spans from the
current instruction with a size of <em>delta</em> bytes.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SETUP_EXCEPT">
<code class="descname">SETUP_EXCEPT</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SETUP_EXCEPT" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a try block from a try-except clause onto the block stack. <em>delta</em>
points to the first except block.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SETUP_FINALLY">
<code class="descname">SETUP_FINALLY</code><span class="sig-paren">(</span><em>delta</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SETUP_FINALLY" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a try block from a try-except clause onto the block stack. <em>delta</em>
points to the finally block.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_MAP">
<code class="descname">STORE_MAP</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_MAP" title="Permalink to this definition">¶</a></dt>
<dd><p>Store a key and value pair in a dictionary.  Pops the key and value while
leaving the dictionary on the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_FAST">
<code class="descname">LOAD_FAST</code><span class="sig-paren">(</span><em>var_num</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_FAST" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a reference to the local <code class="docutils literal notranslate"><span class="pre">co_varnames[var_num]</span></code> onto the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_FAST">
<code class="descname">STORE_FAST</code><span class="sig-paren">(</span><em>var_num</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_FAST" title="Permalink to this definition">¶</a></dt>
<dd><p>Stores TOS into the local <code class="docutils literal notranslate"><span class="pre">co_varnames[var_num]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-DELETE_FAST">
<code class="descname">DELETE_FAST</code><span class="sig-paren">(</span><em>var_num</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-DELETE_FAST" title="Permalink to this definition">¶</a></dt>
<dd><p>Deletes local <code class="docutils literal notranslate"><span class="pre">co_varnames[var_num]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_CLOSURE">
<code class="descname">LOAD_CLOSURE</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_CLOSURE" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a reference to the cell contained in slot <em>i</em> of the cell and free
variable storage.  The name of the variable is <code class="docutils literal notranslate"><span class="pre">co_cellvars[i]</span></code> if <em>i</em> is
less than the length of <em>co_cellvars</em>.  Otherwise it is <code class="docutils literal notranslate"><span class="pre">co_freevars[i</span> <span class="pre">-</span>
<span class="pre">len(co_cellvars)]</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-LOAD_DEREF">
<code class="descname">LOAD_DEREF</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-LOAD_DEREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads the cell contained in slot <em>i</em> of the cell and free variable storage.
Pushes a reference to the object the cell contains on the stack.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-STORE_DEREF">
<code class="descname">STORE_DEREF</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-STORE_DEREF" title="Permalink to this definition">¶</a></dt>
<dd><p>Stores TOS into the cell contained in slot <em>i</em> of the cell and free variable
storage.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-SET_LINENO">
<code class="descname">SET_LINENO</code><span class="sig-paren">(</span><em>lineno</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-SET_LINENO" title="Permalink to this definition">¶</a></dt>
<dd><p>This opcode is obsolete.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-RAISE_VARARGS">
<code class="descname">RAISE_VARARGS</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-RAISE_VARARGS" title="Permalink to this definition">¶</a></dt>
<dd><p>Raises an exception. <em>argc</em> indicates the number of arguments to the raise
statement, ranging from 0 to 3.  The handler will find the traceback as TOS2,
the parameter as TOS1, and the exception as TOS.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-CALL_FUNCTION">
<code class="descname">CALL_FUNCTION</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-CALL_FUNCTION" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls a callable object.  The low byte of <em>argc</em> indicates the number of
positional arguments, the high byte the number of keyword arguments.
The stack contains keyword arguments on top (if any), then the positional
arguments below that (if any), then the callable object to call below that.
Each keyword argument is represented with two values on the stack:
the argument’s name, and its value, with the argument’s value above the
name on the stack.
The positional arguments are pushed in the order that they are passed in
to the callable object, with the right-most positional argument on top.
<code class="docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code> pops all arguments and the callable object off the stack,
calls the callable object with those arguments, and pushes the return value
returned by the callable object.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-MAKE_FUNCTION">
<code class="descname">MAKE_FUNCTION</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-MAKE_FUNCTION" title="Permalink to this definition">¶</a></dt>
<dd><p>Pushes a new function object on the stack.  TOS is the code associated with
the function.  The function object is defined to have <em>argc</em> default
parameters, which are found below TOS.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-MAKE_CLOSURE">
<code class="descname">MAKE_CLOSURE</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-MAKE_CLOSURE" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new function object, sets its <em>func_closure</em> slot, and pushes it on
the stack.  TOS is the code associated with the function, TOS1 the tuple
containing cells for the closure’s free variables.  The function also has
<em>argc</em> default parameters, which are found below the cells.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-BUILD_SLICE">
<code class="descname">BUILD_SLICE</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-BUILD_SLICE" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Pushes a slice object on the stack.  <em>argc</em> must be 2 or 3.  If it is 2,
<code class="docutils literal notranslate"><span class="pre">slice(TOS1,</span> <span class="pre">TOS)</span></code> is pushed; if it is 3, <code class="docutils literal notranslate"><span class="pre">slice(TOS2,</span> <span class="pre">TOS1,</span> <span class="pre">TOS)</span></code> is
pushed. See the <a class="reference internal" href="functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a> built-in function for more information.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-EXTENDED_ARG">
<code class="descname">EXTENDED_ARG</code><span class="sig-paren">(</span><em>ext</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-EXTENDED_ARG" title="Permalink to this definition">¶</a></dt>
<dd><p>Prefixes any opcode which has an argument too big to fit into the default two
bytes.  <em>ext</em> holds two additional bytes which, taken together with the
subsequent opcode’s argument, comprise a four-byte argument, <em>ext</em> being the
two most-significant bytes.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-CALL_FUNCTION_VAR">
<code class="descname">CALL_FUNCTION_VAR</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-CALL_FUNCTION_VAR" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls a callable object, similarly to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
<em>argc</em> represents the number of keyword and positional
arguments, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
The top of the stack contains an iterable object containing
additional positional arguments.
Below that are keyword arguments (if any), positional arguments (if any)
and a callable object, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
Before the callable object is called, the iterable object
is “unpacked” and its contents are appended to the positional
arguments passed in.
The iterable object is ignored when computing
the value of <code class="docutils literal notranslate"><span class="pre">argc</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-CALL_FUNCTION_KW">
<code class="descname">CALL_FUNCTION_KW</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-CALL_FUNCTION_KW" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls a callable object, similarly to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
<em>argc</em> represents the number of keyword and positional
arguments, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
The top of the stack contains a mapping object containing additional keyword
arguments.
Below that are keyword arguments (if any), positional arguments (if any)
and a callable object, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
Before the callable is called, the mapping object at the top of the stack is
“unpacked” and its contents are appended to the keyword arguments passed in.
The mapping object at the top of the stack is ignored when computing
the value of <code class="docutils literal notranslate"><span class="pre">argc</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-CALL_FUNCTION_VAR_KW">
<code class="descname">CALL_FUNCTION_VAR_KW</code><span class="sig-paren">(</span><em>argc</em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-CALL_FUNCTION_VAR_KW" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls a callable object, similarly to <a class="reference internal" href="#opcode-CALL_FUNCTION_VAR"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_VAR</span></code></a> and
<a class="reference internal" href="#opcode-CALL_FUNCTION_KW"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_KW</span></code></a>.
<em>argc</em> represents the number of keyword and positional
arguments, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
The top of the stack contains a mapping object, as per
<a class="reference internal" href="#opcode-CALL_FUNCTION_KW"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_KW</span></code></a>.
Below that is an iterable object, as per
<a class="reference internal" href="#opcode-CALL_FUNCTION_VAR"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_VAR</span></code></a>.
Below that are keyword arguments (if any), positional arguments (if any)
and a callable object, identically to <a class="reference internal" href="#opcode-CALL_FUNCTION"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION</span></code></a>.
Before the callable is called, the mapping object and iterable object
are each “unpacked” and their contents passed in as keyword and
positional arguments respectively,
identically to <a class="reference internal" href="#opcode-CALL_FUNCTION_VAR"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_VAR</span></code></a> and <a class="reference internal" href="#opcode-CALL_FUNCTION_KW"><code class="xref std std-opcode docutils literal notranslate"><span class="pre">CALL_FUNCTION_KW</span></code></a>.
The mapping object and iterable object are both ignored when computing
the value of <code class="docutils literal notranslate"><span class="pre">argc</span></code>.</p>
</dd></dl>

<dl class="opcode">
<dt id="opcode-HAVE_ARGUMENT">
<code class="descname">HAVE_ARGUMENT</code><span class="sig-paren">(</span><em></em><span class="sig-paren">)</span><a class="headerlink" href="#opcode-HAVE_ARGUMENT" title="Permalink to this definition">¶</a></dt>
<dd><p>This is not really an opcode.  It identifies the dividing line between
opcodes which don’t take arguments <code class="docutils literal notranslate"><span class="pre">&lt;</span> <span class="pre">HAVE_ARGUMENT</span></code> and those which do
<code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">HAVE_ARGUMENT</span></code>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a><ul>
<li><a class="reference internal" href="#python-bytecode-instructions">32.12.1. Python Bytecode Instructions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="compileall.html"
                        title="previous chapter">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pickletools.html"
                        title="next chapter">32.13. <code class="docutils literal notranslate"><span class="pre">pickletools</span></code> — Tools for pickle developers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dis.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pickletools.html" title="32.13. pickletools — Tools for pickle developers"
             >next</a> |</li>
        <li class="right" >
          <a href="compileall.html" title="32.11. compileall — Byte-compile Python libraries"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ZHn���html/library/distribution.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>27. Software Packaging and Distribution &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="27.1. distutils — Building and installing Python modules" href="distutils.html" />
    <link rel="prev" title="26.7. trace — Trace or track Python statement execution" href="trace.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/distribution.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distutils.html" title="27.1. distutils — Building and installing Python modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="trace.html" title="26.7. trace — Trace or track Python statement execution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="software-packaging-and-distribution">
<h1>27. Software Packaging and Distribution<a class="headerlink" href="#software-packaging-and-distribution" title="Permalink to this headline">¶</a></h1>
<p>These libraries help you with publishing and installing Python software.
While these modules are designed to work in conjunction with the
<a class="reference external" href="https://pypi.org">Python Package Index</a>, they can also be used
with a local index server, or without any index server at all.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="distutils.html">27.1. <code class="docutils literal notranslate"><span class="pre">distutils</span></code> — Building and installing Python modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="ensurepip.html">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ensurepip.html#command-line-interface">27.2.1. Command line interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="ensurepip.html#module-api">27.2.2. Module API</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="trace.html"
                        title="previous chapter">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="distutils.html"
                        title="next chapter">27.1. <code class="docutils literal notranslate"><span class="pre">distutils</span></code> — Building and installing Python modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/distribution.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distutils.html" title="27.1. distutils — Building and installing Python modules"
             >next</a> |</li>
        <li class="right" >
          <a href="trace.html" title="26.7. trace — Trace or track Python statement execution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P^�'�'html/library/distutils.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>27.1. distutils — Building and installing Python modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="27.2. ensurepip — Bootstrapping the pip installer" href="ensurepip.html" />
    <link rel="prev" title="27. Software Packaging and Distribution" href="distribution.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/distutils.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ensurepip.html" title="27.2. ensurepip — Bootstrapping the pip installer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="distribution.html" title="27. Software Packaging and Distribution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="distribution.html" accesskey="U">27. Software Packaging and Distribution</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-distutils">
<span id="distutils-building-and-installing-python-modules"></span><h1>27.1. <a class="reference internal" href="#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> — Building and installing Python modules<a class="headerlink" href="#module-distutils" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> package provides support for building and installing
additional modules into a Python installation.  The new modules may be either
100%-pure Python, or may be extension modules written in C, or may be
collections of Python packages which include modules coded in both Python and C.</p>
<p>Most Python users will <em>not</em> want to use this module directly, but instead
use the cross-version tools maintained by the Python Packaging Authority. In
particular,
<a class="reference external" href="https://setuptools.readthedocs.io/en/latest/">setuptools</a> is an
enhanced alternative to <a class="reference internal" href="#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> that provides:</p>
<ul class="simple">
<li>support for declaring project dependencies</li>
<li>additional mechanisms for configuring which files to include in source
releases (including plugins for integration with version control systems)</li>
<li>the ability to declare project “entry points”, which can be used as the
basis for application plugin systems</li>
<li>the ability to automatically generate Windows command line executables at
installation time rather than needing to prebuild them</li>
<li>consistent behaviour across all supported Python versions</li>
</ul>
<p>The recommended <a class="reference external" href="https://pip.pypa.io/">pip</a> installer runs all
<code class="docutils literal notranslate"><span class="pre">setup.py</span></code> scripts with <code class="docutils literal notranslate"><span class="pre">setuptools</span></code>, even if the script itself only
imports <code class="docutils literal notranslate"><span class="pre">distutils</span></code>. Refer to the
<a class="reference external" href="https://packaging.python.org">Python Packaging User Guide</a> for more
information.</p>
<p>For the benefits of packaging tool authors and users seeking a deeper
understanding of the details of the current packaging and distribution
system, the legacy <a class="reference internal" href="#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> based user documentation and API
reference remain available:</p>
<ul class="simple">
<li><a class="reference internal" href="../install/index.html#install-index"><span class="std std-ref">Installing Python Modules (Legacy version)</span></a></li>
<li><a class="reference internal" href="../distutils/index.html#distutils-index"><span class="std std-ref">Distributing Python Modules (Legacy version)</span></a></li>
</ul>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="distribution.html"
                        title="previous chapter">27. Software Packaging and Distribution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ensurepip.html"
                        title="next chapter">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/distutils.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ensurepip.html" title="27.2. ensurepip — Bootstrapping the pip installer"
             >next</a> |</li>
        <li class="right" >
          <a href="distribution.html" title="27. Software Packaging and Distribution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="distribution.html" >27. Software Packaging and Distribution</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\(�EEhtml/library/dl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.6. dl — Call C functions in shared objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.7. termios — POSIX style tty control" href="termios.html" />
    <link rel="prev" title="36.5. crypt — Function to check Unix passwords" href="crypt.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="termios.html" title="36.7. termios — POSIX style tty control"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="crypt.html" title="36.5. crypt — Function to check Unix passwords"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dl">
<span id="dl-call-c-functions-in-shared-objects"></span><h1>36.6. <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> — Call C functions in shared objects<a class="headerlink" href="#module-dl" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module has been removed in Python 3. Use the <a class="reference internal" href="ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>
module instead.</p>
</div>
<p>The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module defines an interface to the <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> function, which
is the most common interface on Unix platforms for handling dynamically linked
libraries. It allows the program to call arbitrary functions in such a library.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module bypasses the Python type system and  error handling. If
used incorrectly it may cause segmentation faults, crashes or other incorrect
behaviour.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module will not work unless <code class="docutils literal notranslate"><span class="pre">sizeof(int)</span> <span class="pre">==</span> <span class="pre">sizeof(long)</span> <span class="pre">==</span> <span class="pre">sizeof(char</span>
<span class="pre">*)</span></code> If this is not the case, <a class="reference internal" href="exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a> will be raised on import.</p>
</div>
<p>The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module defines the following function:</p>
<dl class="function">
<dt id="dl.open">
<code class="descclassname">dl.</code><code class="descname">open</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode=RTLD_LAZY</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dl.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a shared object file, and return a handle. Mode signifies late binding
(<a class="reference internal" href="#dl.RTLD_LAZY" title="dl.RTLD_LAZY"><code class="xref py py-const docutils literal notranslate"><span class="pre">RTLD_LAZY</span></code></a>) or immediate binding (<a class="reference internal" href="#dl.RTLD_NOW" title="dl.RTLD_NOW"><code class="xref py py-const docutils literal notranslate"><span class="pre">RTLD_NOW</span></code></a>). Default is
<a class="reference internal" href="#dl.RTLD_LAZY" title="dl.RTLD_LAZY"><code class="xref py py-const docutils literal notranslate"><span class="pre">RTLD_LAZY</span></code></a>. Note that some systems do not support <a class="reference internal" href="#dl.RTLD_NOW" title="dl.RTLD_NOW"><code class="xref py py-const docutils literal notranslate"><span class="pre">RTLD_NOW</span></code></a>.</p>
<p>Return value is a <code class="xref py py-class docutils literal notranslate"><span class="pre">dlobject</span></code>.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module defines the following constants:</p>
<dl class="data">
<dt id="dl.RTLD_LAZY">
<code class="descclassname">dl.</code><code class="descname">RTLD_LAZY</code><a class="headerlink" href="#dl.RTLD_LAZY" title="Permalink to this definition">¶</a></dt>
<dd><p>Useful as an argument to <a class="reference internal" href="#dl.open" title="dl.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="dl.RTLD_NOW">
<code class="descclassname">dl.</code><code class="descname">RTLD_NOW</code><a class="headerlink" href="#dl.RTLD_NOW" title="Permalink to this definition">¶</a></dt>
<dd><p>Useful as an argument to <a class="reference internal" href="#dl.open" title="dl.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.  Note that on systems which do not
support immediate binding, this constant will not appear in the module. For
maximum portability, use <a class="reference internal" href="functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> to determine if the system supports
immediate binding.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module defines the following exception:</p>
<dl class="exception">
<dt id="dl.error">
<em class="property">exception </em><code class="descclassname">dl.</code><code class="descname">error</code><a class="headerlink" href="#dl.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error has occurred inside the dynamic loading and
linking routines.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">dl</span><span class="o">,</span> <span class="nn">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">=</span><span class="n">dl</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;/lib/libc.so.6&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">),</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="go">(929723914, 929723914.498)</span>
</pre></div>
</div>
<p>This example was tried on a Debian GNU/Linux system, and is a good example of
the fact that using this module is usually a bad alternative.</p>
<div class="section" id="dl-objects">
<span id="id1"></span><h2>36.6.1. Dl Objects<a class="headerlink" href="#dl-objects" title="Permalink to this headline">¶</a></h2>
<p>Dl objects, as returned by <a class="reference internal" href="#dl.open" title="dl.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> above, have the following methods:</p>
<dl class="method">
<dt id="dl.dl.close">
<code class="descclassname">dl.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dl.dl.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Free all resources, except the memory.</p>
</dd></dl>

<dl class="method">
<dt id="dl.dl.sym">
<code class="descclassname">dl.</code><code class="descname">sym</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#dl.dl.sym" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the pointer for the function named <em>name</em>, as a number, if it exists in
the referenced shared object, otherwise <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is useful in code like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">a</span><span class="o">.</span><span class="n">sym</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">a</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
</pre></div>
</div>
<p>(Note that this function will return a non-zero number, as zero is the <em>NULL</em>
pointer)</p>
</dd></dl>

<dl class="method">
<dt id="dl.dl.call">
<code class="descclassname">dl.</code><code class="descname">call</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>arg1</em><span class="optional">[</span>, <em>arg2...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dl.dl.call" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the function named <em>name</em> in the referenced shared object. The arguments
must be either Python integers, which will be  passed as is, Python strings, to
which a pointer will be passed,  or <code class="docutils literal notranslate"><span class="pre">None</span></code>, which will be passed as <em>NULL</em>.
Note that  strings should only be passed to functions as <code class="xref c c-type docutils literal notranslate"><span class="pre">const</span> <span class="pre">char*</span></code>,
as Python will not like its string mutated.</p>
<p>There must be at most 10 arguments, and arguments not given will be treated as
<code class="docutils literal notranslate"><span class="pre">None</span></code>. The function’s return value must be a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code>, which is a
Python integer.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a><ul>
<li><a class="reference internal" href="#dl-objects">36.6.1. Dl Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="crypt.html"
                        title="previous chapter">36.5. <code class="docutils literal notranslate"><span class="pre">crypt</span></code> — Function to check Unix passwords</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="termios.html"
                        title="next chapter">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="termios.html" title="36.7. termios — POSIX style tty control"
             >next</a> |</li>
        <li class="right" >
          <a href="crypt.html" title="36.5. crypt — Function to check Unix passwords"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\d�z-��html/library/doctest.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25.2. doctest — Test interactive Python examples &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25.3. unittest — Unit testing framework" href="unittest.html" />
    <link rel="prev" title="25.1. pydoc — Documentation generator and online help system" href="pydoc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/doctest.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unittest.html" title="25.3. unittest — Unit testing framework"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pydoc.html" title="25.1. pydoc — Documentation generator and online help system"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">25. Development Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-doctest">
<span id="doctest-test-interactive-python-examples"></span><h1>25.2. <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> — Test interactive Python examples<a class="headerlink" href="#module-doctest" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module searches for pieces of text that look like interactive
Python sessions, and then executes those sessions to verify that they work
exactly as shown.  There are several common ways to use doctest:</p>
<ul class="simple">
<li>To check that a module’s docstrings are up-to-date by verifying that all
interactive examples still work as documented.</li>
<li>To perform regression testing by verifying that interactive examples from a
test file or a test object work as expected.</li>
<li>To write tutorial documentation for a package, liberally illustrated with
input-output examples.  Depending on whether the examples or the expository text
are emphasized, this has the flavor of “literate testing” or “executable
documentation”.</li>
</ul>
<p>Here’s a complete but small example module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">This is the &quot;example&quot; module.</span>

<span class="sd">The example module supplies one function, factorial().  For example,</span>

<span class="sd">&gt;&gt;&gt; factorial(5)</span>
<span class="sd">120</span>
<span class="sd">&quot;&quot;&quot;</span>

<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return the factorial of n, an exact integer &gt;= 0.</span>

<span class="sd">    If the result is small enough to fit in an int, return an int.</span>
<span class="sd">    Else return a long.</span>

<span class="sd">    &gt;&gt;&gt; [factorial(n) for n in range(6)]</span>
<span class="sd">    [1, 1, 2, 6, 24, 120]</span>
<span class="sd">    &gt;&gt;&gt; [factorial(long(n)) for n in range(6)]</span>
<span class="sd">    [1, 1, 2, 6, 24, 120]</span>
<span class="sd">    &gt;&gt;&gt; factorial(30)</span>
<span class="sd">    265252859812191058636308480000000L</span>
<span class="sd">    &gt;&gt;&gt; factorial(30L)</span>
<span class="sd">    265252859812191058636308480000000L</span>
<span class="sd">    &gt;&gt;&gt; factorial(-1)</span>
<span class="sd">    Traceback (most recent call last):</span>
<span class="sd">        ...</span>
<span class="sd">    ValueError: n must be &gt;= 0</span>

<span class="sd">    Factorials of floats are OK, but the float must be an exact integer:</span>
<span class="sd">    &gt;&gt;&gt; factorial(30.1)</span>
<span class="sd">    Traceback (most recent call last):</span>
<span class="sd">        ...</span>
<span class="sd">    ValueError: n must be exact integer</span>
<span class="sd">    &gt;&gt;&gt; factorial(30.0)</span>
<span class="sd">    265252859812191058636308480000000L</span>

<span class="sd">    It must also not be ridiculously large:</span>
<span class="sd">    &gt;&gt;&gt; factorial(1e100)</span>
<span class="sd">    Traceback (most recent call last):</span>
<span class="sd">        ...</span>
<span class="sd">    OverflowError: n too large</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="kn">import</span> <span class="nn">math</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">n</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;n must be &gt;= 0&quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">math</span><span class="o">.</span><span class="n">floor</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="o">!=</span> <span class="n">n</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;n must be exact integer&quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">n</span><span class="o">+</span><span class="mi">1</span> <span class="o">==</span> <span class="n">n</span><span class="p">:</span>  <span class="c1"># catch a value like 1e300</span>
        <span class="k">raise</span> <span class="ne">OverflowError</span><span class="p">(</span><span class="s2">&quot;n too large&quot;</span><span class="p">)</span>
    <span class="n">result</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="n">factor</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="k">while</span> <span class="n">factor</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="p">:</span>
        <span class="n">result</span> <span class="o">*=</span> <span class="n">factor</span>
        <span class="n">factor</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="k">return</span> <span class="n">result</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">doctest</span>
    <span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">()</span>
</pre></div>
</div>
<p>If you run <code class="file docutils literal notranslate"><span class="pre">example.py</span></code> directly from the command line, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>
works its magic:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python example.py
<span class="gp">$</span>
</pre></div>
</div>
<p>There’s no output!  That’s normal, and it means all the examples worked.  Pass
<code class="docutils literal notranslate"><span class="pre">-v</span></code> to the script, and <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> prints a detailed log of what
it’s trying, and prints a summary at the end:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python example.py -v
<span class="go">Trying:</span>
<span class="go">    factorial(5)</span>
<span class="go">Expecting:</span>
<span class="go">    120</span>
<span class="go">ok</span>
<span class="go">Trying:</span>
<span class="go">    [factorial(n) for n in range(6)]</span>
<span class="go">Expecting:</span>
<span class="go">    [1, 1, 2, 6, 24, 120]</span>
<span class="go">ok</span>
<span class="go">Trying:</span>
<span class="go">    [factorial(long(n)) for n in range(6)]</span>
<span class="go">Expecting:</span>
<span class="go">    [1, 1, 2, 6, 24, 120]</span>
<span class="go">ok</span>
</pre></div>
</div>
<p>And so on, eventually ending with:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Trying:
    factorial(1e100)
Expecting:
    Traceback (most recent call last):
        ...
    OverflowError: n too large
ok
2 items passed all tests:
   1 tests in __main__
   8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$
</pre></div>
</div>
<p>That’s all you need to know to start making productive use of <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>!
Jump in.  The following sections provide full details.  Note that there are many
examples of doctests in the standard Python test suite and libraries.
Especially useful examples can be found in the standard test file
<code class="file docutils literal notranslate"><span class="pre">Lib/test/test_doctest.py</span></code>.</p>
<div class="section" id="simple-usage-checking-examples-in-docstrings">
<span id="doctest-simple-testmod"></span><h2>25.2.1. Simple Usage: Checking Examples in Docstrings<a class="headerlink" href="#simple-usage-checking-examples-in-docstrings" title="Permalink to this headline">¶</a></h2>
<p>The simplest way to start using doctest (but not necessarily the way you’ll
continue to do it) is to end each module <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code> with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">doctest</span>
    <span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">()</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> then examines docstrings in module <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code>.</p>
<p>Running the module as a script causes the examples in the docstrings to get
executed and verified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">M</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This won’t display anything unless an example fails, in which case the failing
example(s) and the cause(s) of the failure(s) are printed to stdout, and the
final line of output is <code class="docutils literal notranslate"><span class="pre">***Test</span> <span class="pre">Failed***</span> <span class="pre">N</span> <span class="pre">failures.</span></code>, where <em>N</em> is the
number of examples that failed.</p>
<p>Run it with the <code class="docutils literal notranslate"><span class="pre">-v</span></code> switch instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">M</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">v</span>
</pre></div>
</div>
<p>and a detailed report of all examples tried is printed to standard output, along
with assorted summaries at the end.</p>
<p>You can force verbose mode by passing <code class="docutils literal notranslate"><span class="pre">verbose=True</span></code> to <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>, or
prohibit it by passing <code class="docutils literal notranslate"><span class="pre">verbose=False</span></code>.  In either of those cases,
<code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> is not examined by <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> (so passing <code class="docutils literal notranslate"><span class="pre">-v</span></code> or not
has no effect).</p>
<p>Since Python 2.6, there is also a command line shortcut for running
<a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>.  You can instruct the Python interpreter to run the doctest
module directly from the standard library and pass the module name(s) on the
command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">doctest</span> <span class="o">-</span><span class="n">v</span> <span class="n">example</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This will import <code class="file docutils literal notranslate"><span class="pre">example.py</span></code> as a standalone module and run
<a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> on it.  Note that this may not work correctly if the file is
part of a package and imports other submodules from that package.</p>
<p>For more information on <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>, see section <a class="reference internal" href="#doctest-basic-api"><span class="std std-ref">Basic API</span></a>.</p>
</div>
<div class="section" id="simple-usage-checking-examples-in-a-text-file">
<span id="doctest-simple-testfile"></span><h2>25.2.2. Simple Usage: Checking Examples in a Text File<a class="headerlink" href="#simple-usage-checking-examples-in-a-text-file" title="Permalink to this headline">¶</a></h2>
<p>Another simple application of doctest is testing interactive examples in a text
file.  This can be done with the <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">doctest</span>
<span class="n">doctest</span><span class="o">.</span><span class="n">testfile</span><span class="p">(</span><span class="s2">&quot;example.txt&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>That short script executes and verifies any interactive Python examples
contained in the file <code class="file docutils literal notranslate"><span class="pre">example.txt</span></code>.  The file content is treated as if it
were a single giant docstring; the file doesn’t need to contain a Python
program!   For example, perhaps <code class="file docutils literal notranslate"><span class="pre">example.txt</span></code> contains this:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>The ``example`` module
======================

Using ``factorial``
-------------------

This is an example text file in reStructuredText format.  First import
``factorial`` from the ``example`` module:

    &gt;&gt;&gt; from example import factorial

Now use it:

    &gt;&gt;&gt; factorial(6)
    120
</pre></div>
</div>
<p>Running <code class="docutils literal notranslate"><span class="pre">doctest.testfile(&quot;example.txt&quot;)</span></code> then finds the error in this
documentation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">File</span> <span class="s2">&quot;./example.txt&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">14</span><span class="p">,</span> <span class="ow">in</span> <span class="n">example</span><span class="o">.</span><span class="n">txt</span>
<span class="n">Failed</span> <span class="n">example</span><span class="p">:</span>
    <span class="n">factorial</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="n">Expected</span><span class="p">:</span>
    <span class="mi">120</span>
<span class="n">Got</span><span class="p">:</span>
    <span class="mi">720</span>
</pre></div>
</div>
<p>As with <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>, <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> won’t display anything unless an
example fails.  If an example does fail, then the failing example(s) and the
cause(s) of the failure(s) are printed to stdout, using the same format as
<a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>.</p>
<p>By default, <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> looks for files in the calling module’s directory.
See section <a class="reference internal" href="#doctest-basic-api"><span class="std std-ref">Basic API</span></a> for a description of the optional arguments
that can be used to tell it to look for files in other locations.</p>
<p>Like <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>, <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a>’s verbosity can be set with the
<code class="docutils literal notranslate"><span class="pre">-v</span></code> command-line switch or with the optional keyword argument
<em>verbose</em>.</p>
<p>Since Python 2.6, there is also a command line shortcut for running
<a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a>.  You can instruct the Python interpreter to run the doctest
module directly from the standard library and pass the file name(s) on the
command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">doctest</span> <span class="o">-</span><span class="n">v</span> <span class="n">example</span><span class="o">.</span><span class="n">txt</span>
</pre></div>
</div>
<p>Because the file name does not end with <code class="file docutils literal notranslate"><span class="pre">.py</span></code>, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> infers that
it must be run with <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a>, not <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>.</p>
<p>For more information on <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a>, see section <a class="reference internal" href="#doctest-basic-api"><span class="std std-ref">Basic API</span></a>.</p>
</div>
<div class="section" id="how-it-works">
<span id="doctest-how-it-works"></span><h2>25.2.3. How It Works<a class="headerlink" href="#how-it-works" title="Permalink to this headline">¶</a></h2>
<p>This section examines in detail how doctest works: which docstrings it looks at,
how it finds interactive examples, what execution context it uses, how it
handles exceptions, and how option flags can be used to control its behavior.
This is the information that you need to know to write doctest examples; for
information about actually running doctest on these examples, see the following
sections.</p>
<div class="section" id="which-docstrings-are-examined">
<span id="doctest-which-docstrings"></span><h3>25.2.3.1. Which Docstrings Are Examined?<a class="headerlink" href="#which-docstrings-are-examined" title="Permalink to this headline">¶</a></h3>
<p>The module docstring, and all function, class and method docstrings are
searched.  Objects imported into the module are not searched.</p>
<p>In addition, if <code class="docutils literal notranslate"><span class="pre">M.__test__</span></code> exists and “is true”, it must be a dict, and each
entry maps a (string) name to a function object, class object, or string.
Function and class object docstrings found from <code class="docutils literal notranslate"><span class="pre">M.__test__</span></code> are searched, and
strings are treated as if they were docstrings.  In output, a key <code class="docutils literal notranslate"><span class="pre">K</span></code> in
<code class="docutils literal notranslate"><span class="pre">M.__test__</span></code> appears with name</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">name</span> <span class="n">of</span> <span class="n">M</span><span class="o">&gt;.</span><span class="n">__test__</span><span class="o">.</span><span class="n">K</span>
</pre></div>
</div>
<p>Any classes found are recursively searched similarly, to test docstrings in
their contained methods and nested classes.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>A “private name” concept is deprecated and no longer documented.</p>
</div>
</div>
<div class="section" id="how-are-docstring-examples-recognized">
<span id="doctest-finding-examples"></span><h3>25.2.3.2. How are Docstring Examples Recognized?<a class="headerlink" href="#how-are-docstring-examples-recognized" title="Permalink to this headline">¶</a></h3>
<p>In most cases a copy-and-paste of an interactive console session works fine,
but doctest isn’t trying to do an exact emulation of any specific Python shell.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># comments are ignored</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">12</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">13</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;yes&quot;</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;no&quot;</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;NO&quot;</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;NO!!!&quot;</span>
<span class="gp">...</span>
<span class="go">no</span>
<span class="go">NO</span>
<span class="go">NO!!!</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Any expected output must immediately follow the final <code class="docutils literal notranslate"><span class="pre">'&gt;&gt;&gt;</span> <span class="pre">'</span></code> or <code class="docutils literal notranslate"><span class="pre">'...</span> <span class="pre">'</span></code>
line containing the code, and the expected output (if any) extends to the next
<code class="docutils literal notranslate"><span class="pre">'&gt;&gt;&gt;</span> <span class="pre">'</span></code> or all-whitespace line.</p>
<p>The fine print:</p>
<ul>
<li><p class="first">Expected output cannot contain an all-whitespace line, since such a line is
taken to signal the end of expected output.  If expected output does contain a
blank line, put <code class="docutils literal notranslate"><span class="pre">&lt;BLANKLINE&gt;</span></code> in your doctest example each place a blank line
is expected.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span><code class="docutils literal notranslate"><span class="pre">&lt;BLANKLINE&gt;</span></code> was added; there was no way to use expected output containing
empty lines in previous versions.</p>
</div>
</li>
<li><p class="first">All hard tab characters are expanded to spaces, using 8-column tab stops.
Tabs in output generated by the tested code are not modified.  Because any
hard tabs in the sample output <em>are</em> expanded, this means that if the code
output includes hard tabs, the only way the doctest can pass is if the
<a class="reference internal" href="#doctest.NORMALIZE_WHITESPACE" title="doctest.NORMALIZE_WHITESPACE"><code class="xref py py-const docutils literal notranslate"><span class="pre">NORMALIZE_WHITESPACE</span></code></a> option or <a class="reference internal" href="#doctest-directives"><span class="std std-ref">directive</span></a>
is in effect.
Alternatively, the test can be rewritten to capture the output and compare it
to an expected value as part of the test.  This handling of tabs in the
source was arrived at through trial and error, and has proven to be the least
error prone way of handling them.  It is possible to use a different
algorithm for handling tabs by writing a custom <a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> class.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Expanding tabs to spaces is new; previous versions tried to preserve hard tabs,
with confusing results.</p>
</div>
</li>
<li><p class="first">Output to stdout is captured, but not output to stderr (exception tracebacks
are captured via a different means).</p>
</li>
<li><p class="first">If you continue a line via backslashing in an interactive session, or for any
other reason use a backslash, you should use a raw docstring, which will
preserve your backslashes exactly as you type them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>    <span class="sa">r</span><span class="sd">&#39;&#39;&#39;Backslashes in a raw docstring: m\n&#39;&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="vm">__doc__</span>
<span class="go">Backslashes in a raw docstring: m\n</span>
</pre></div>
</div>
<p>Otherwise, the backslash will be interpreted as part of the string. For example,
the <code class="docutils literal notranslate"><span class="pre">\n</span></code> above would be interpreted as a newline character.  Alternatively, you
can double each backslash in the doctest version (and not use a raw string):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>    <span class="sd">&#39;&#39;&#39;Backslashes in a raw docstring: m\\n&#39;&#39;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="vm">__doc__</span>
<span class="go">Backslashes in a raw docstring: m\n</span>
</pre></div>
</div>
</li>
<li><p class="first">The starting column doesn’t matter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="s2">&quot;Easy!&quot;</span>
<span class="go">      &gt;&gt;&gt; import math</span>
<span class="go">          &gt;&gt;&gt; math.floor(1.9)</span>
<span class="go">          1.0</span>
</pre></div>
</div>
<p>and as many leading whitespace characters are stripped from the expected output
as appeared in the initial <code class="docutils literal notranslate"><span class="pre">'&gt;&gt;&gt;</span> <span class="pre">'</span></code> line that started the example.</p>
</li>
</ul>
</div>
<div class="section" id="what-s-the-execution-context">
<span id="doctest-execution-context"></span><h3>25.2.3.3. What’s the Execution Context?<a class="headerlink" href="#what-s-the-execution-context" title="Permalink to this headline">¶</a></h3>
<p>By default, each time <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> finds a docstring to test, it uses a
<em>shallow copy</em> of <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code>’s globals, so that running tests doesn’t change the
module’s real globals, and so that one test in <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code> can’t leave behind
crumbs that accidentally allow another test to work.  This means examples can
freely use any names defined at top-level in <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code>, and names defined earlier
in the docstring being run. Examples cannot see names defined in other
docstrings.</p>
<p>You can force use of your own dict as the execution context by passing
<code class="docutils literal notranslate"><span class="pre">globs=your_dict</span></code> to <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> or <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> instead.</p>
</div>
<div class="section" id="what-about-exceptions">
<span id="doctest-exceptions"></span><h3>25.2.3.4. What About Exceptions?<a class="headerlink" href="#what-about-exceptions" title="Permalink to this headline">¶</a></h3>
<p>No problem, provided that the traceback is the only output produced by the
example:  just paste in the traceback. <a class="footnote-reference" href="#id2" id="id1">[1]</a> Since tracebacks contain details
that are likely to change rapidly (for example, exact file paths and line
numbers), this is one case where doctest works hard to be flexible in what it
accepts.</p>
<p>Simple example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">list.remove(x): x not in list</span>
</pre></div>
</div>
<p>That doctest succeeds if <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised, with the <code class="docutils literal notranslate"><span class="pre">list.remove(x):</span>
<span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">list</span></code> detail as shown.</p>
<p>The expected output for an exception must start with a traceback header, which
may be either of the following two lines, indented the same as the first line of
the example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">innermost</span> <span class="n">last</span><span class="p">):</span>
</pre></div>
</div>
<p>The traceback header is followed by an optional traceback stack, whose contents
are ignored by doctest.  The traceback stack is typically omitted, or copied
verbatim from an interactive session.</p>
<p>The traceback stack is followed by the most interesting part: the line(s)
containing the exception type and detail.  This is usually the last line of a
traceback, but can extend across multiple lines if the exception has a
multi-line detail:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;multi</span><span class="se">\n</span><span class="s1">    line</span><span class="se">\n</span><span class="s1">detail&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">multi</span>
<span class="go">    line</span>
<span class="go">detail</span>
</pre></div>
</div>
<p>The last three lines (starting with <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>) are compared against the
exception’s type and detail, and the rest are ignored.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Previous versions were unable to handle multi-line exception details.</p>
</div>
<p>Best practice is to omit the traceback stack, unless it adds significant
documentation value to the example.  So the last example is probably better as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;multi</span><span class="se">\n</span><span class="s1">    line</span><span class="se">\n</span><span class="s1">detail&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
    <span class="o">...</span>
<span class="gr">ValueError</span>: <span class="n">multi</span>
<span class="go">    line</span>
<span class="go">detail</span>
</pre></div>
</div>
<p>Note that tracebacks are treated very specially.  In particular, in the
rewritten example, the use of <code class="docutils literal notranslate"><span class="pre">...</span></code> is independent of doctest’s
<a class="reference internal" href="#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><code class="xref py py-const docutils literal notranslate"><span class="pre">ELLIPSIS</span></code></a> option.  The ellipsis in that example could be left out, or
could just as well be three (or three hundred) commas or digits, or an indented
transcript of a Monty Python skit.</p>
<p>Some details you should read once, but won’t need to remember:</p>
<ul>
<li><p class="first">Doctest can’t guess whether your expected output came from an exception
traceback or from ordinary printing.  So, e.g., an example that expects
<code class="docutils literal notranslate"><span class="pre">ValueError:</span> <span class="pre">42</span> <span class="pre">is</span> <span class="pre">prime</span></code> will pass whether <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is actually
raised or if the example merely prints that traceback text.  In practice,
ordinary output rarely begins with a traceback header line, so this doesn’t
create real problems.</p>
</li>
<li><p class="first">Each line of the traceback stack (if present) must be indented further than
the first line of the example, <em>or</em> start with a non-alphanumeric character.
The first line following the traceback header indented the same and starting
with an alphanumeric is taken to be the start of the exception detail.  Of
course this does the right thing for genuine tracebacks.</p>
</li>
<li><p class="first">When the <a class="reference internal" href="#doctest.IGNORE_EXCEPTION_DETAIL" title="doctest.IGNORE_EXCEPTION_DETAIL"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORE_EXCEPTION_DETAIL</span></code></a> doctest option is specified,
everything following the leftmost colon and any module information in the
exception name is ignored.</p>
</li>
<li><p class="first">The interactive shell omits the traceback header line for some
<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>s.  But doctest uses the traceback header line to
distinguish exceptions from non-exceptions.  So in the rare case where you need
to test a <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> that omits the traceback header, you will need to
manually add the traceback header line to your test example.</p>
</li>
<li><p class="first">For some <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>s, Python displays the character position of the
syntax error, using a <code class="docutils literal notranslate"><span class="pre">^</span></code> marker:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="mi">1</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
    <span class="mi">1</span> <span class="mi">1</span>
      <span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
</pre></div>
</div>
<p>Since the lines showing the position of the error come before the exception type
and detail, they are not checked by doctest.  For example, the following test
would pass, even though it puts the <code class="docutils literal notranslate"><span class="pre">^</span></code> marker in the wrong location:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="mi">1</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
    <span class="mi">1</span> <span class="mi">1</span>
    <span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
</pre></div>
</div>
</li>
</ul>
</div>
<div class="section" id="option-flags">
<span id="doctest-options"></span><span id="option-flags-and-directives"></span><h3>25.2.3.5. Option Flags<a class="headerlink" href="#option-flags" title="Permalink to this headline">¶</a></h3>
<p>A number of option flags control various aspects of doctest’s behavior.
Symbolic names for the flags are supplied as module constants, which can be
<a class="reference internal" href="../reference/expressions.html#bitwise"><span class="std std-ref">bitwise ORed</span></a> together and passed to various functions.
The names can also be used in <a class="reference internal" href="#doctest-directives"><span class="std std-ref">doctest directives</span></a>.</p>
<p>The first group of options define test semantics, controlling aspects of how
doctest decides whether actual output matches an example’s expected output:</p>
<dl class="data">
<dt id="doctest.DONT_ACCEPT_TRUE_FOR_1">
<code class="descclassname">doctest.</code><code class="descname">DONT_ACCEPT_TRUE_FOR_1</code><a class="headerlink" href="#doctest.DONT_ACCEPT_TRUE_FOR_1" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, if an expected output block contains just <code class="docutils literal notranslate"><span class="pre">1</span></code>, an actual output
block containing just <code class="docutils literal notranslate"><span class="pre">1</span></code> or just <code class="docutils literal notranslate"><span class="pre">True</span></code> is considered to be a match, and
similarly for <code class="docutils literal notranslate"><span class="pre">0</span></code> versus <code class="docutils literal notranslate"><span class="pre">False</span></code>.  When <a class="reference internal" href="#doctest.DONT_ACCEPT_TRUE_FOR_1" title="doctest.DONT_ACCEPT_TRUE_FOR_1"><code class="xref py py-const docutils literal notranslate"><span class="pre">DONT_ACCEPT_TRUE_FOR_1</span></code></a> is
specified, neither substitution is allowed.  The default behavior caters to that
Python changed the return type of many functions from integer to boolean;
doctests expecting “little integer” output still work in these cases.  This
option will probably go away, but not for several years.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.DONT_ACCEPT_BLANKLINE">
<code class="descclassname">doctest.</code><code class="descname">DONT_ACCEPT_BLANKLINE</code><a class="headerlink" href="#doctest.DONT_ACCEPT_BLANKLINE" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, if an expected output block contains a line containing only the
string <code class="docutils literal notranslate"><span class="pre">&lt;BLANKLINE&gt;</span></code>, then that line will match a blank line in the actual
output.  Because a genuinely blank line delimits the expected output, this is
the only way to communicate that a blank line is expected.  When
<a class="reference internal" href="#doctest.DONT_ACCEPT_BLANKLINE" title="doctest.DONT_ACCEPT_BLANKLINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DONT_ACCEPT_BLANKLINE</span></code></a> is specified, this substitution is not allowed.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.NORMALIZE_WHITESPACE">
<code class="descclassname">doctest.</code><code class="descname">NORMALIZE_WHITESPACE</code><a class="headerlink" href="#doctest.NORMALIZE_WHITESPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, all sequences of whitespace (blanks and newlines) are treated as
equal.  Any sequence of whitespace within the expected output will match any
sequence of whitespace within the actual output. By default, whitespace must
match exactly. <a class="reference internal" href="#doctest.NORMALIZE_WHITESPACE" title="doctest.NORMALIZE_WHITESPACE"><code class="xref py py-const docutils literal notranslate"><span class="pre">NORMALIZE_WHITESPACE</span></code></a> is especially useful when a line of
expected output is very long, and you want to wrap it across multiple lines in
your source.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.ELLIPSIS">
<code class="descclassname">doctest.</code><code class="descname">ELLIPSIS</code><a class="headerlink" href="#doctest.ELLIPSIS" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, an ellipsis marker (<code class="docutils literal notranslate"><span class="pre">...</span></code>) in the expected output can match
any substring in the actual output.  This includes substrings that span line
boundaries, and empty substrings, so it’s best to keep usage of this simple.
Complicated uses can lead to the same kinds of “oops, it matched too much!”
surprises that <code class="docutils literal notranslate"><span class="pre">.*</span></code> is prone to in regular expressions.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.IGNORE_EXCEPTION_DETAIL">
<code class="descclassname">doctest.</code><code class="descname">IGNORE_EXCEPTION_DETAIL</code><a class="headerlink" href="#doctest.IGNORE_EXCEPTION_DETAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, an example that expects an exception passes if an exception of
the expected type is raised, even if the exception detail does not match.  For
example, an example expecting <code class="docutils literal notranslate"><span class="pre">ValueError:</span> <span class="pre">42</span></code> will pass if the actual
exception raised is <code class="docutils literal notranslate"><span class="pre">ValueError:</span> <span class="pre">3*14</span></code>, but will fail, e.g., if
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>It will also ignore the module name used in Python 3 doctest reports. Hence
both of these variations will work with the flag specified, regardless of
whether the test is run under Python 2.7 or Python 3.2 (or later versions):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="n">CustomError</span><span class="p">(</span><span class="s1">&#39;message&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="gr">CustomError</span>: <span class="n">message</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="n">CustomError</span><span class="p">(</span><span class="s1">&#39;message&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="gr">my_module.CustomError</span>: <span class="n">message</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><code class="xref py py-const docutils literal notranslate"><span class="pre">ELLIPSIS</span></code></a> can also be used to ignore the
details of the exception message, but such a test may still fail based
on whether or not the module details are printed as part of the
exception name. Using <a class="reference internal" href="#doctest.IGNORE_EXCEPTION_DETAIL" title="doctest.IGNORE_EXCEPTION_DETAIL"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORE_EXCEPTION_DETAIL</span></code></a> and the details
from Python 2.3 is also the only clear way to write a doctest that doesn’t
care about the exception detail yet continues to pass under Python 2.3 or
earlier (those releases do not support <a class="reference internal" href="#doctest-directives"><span class="std std-ref">doctest directives</span></a> and ignore them as irrelevant comments). For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;moo&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">object doesn&#39;t support item assignment</span>
</pre></div>
</div>
<p>passes under Python 2.3 and later Python versions with the flag specified,
even though the detail
changed in Python 2.4 to say “does not” instead of “doesn’t”.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><a class="reference internal" href="#doctest.IGNORE_EXCEPTION_DETAIL" title="doctest.IGNORE_EXCEPTION_DETAIL"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORE_EXCEPTION_DETAIL</span></code></a> now also ignores any information
relating to the module containing the exception under test</p>
</div>
</dd></dl>

<dl class="data">
<dt id="doctest.SKIP">
<code class="descclassname">doctest.</code><code class="descname">SKIP</code><a class="headerlink" href="#doctest.SKIP" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, do not run the example at all.  This can be useful in contexts
where doctest examples serve as both documentation and test cases, and an
example should be included for documentation purposes, but should not be
checked.  E.g., the example’s output might be random; or the example might
depend on resources which would be unavailable to the test driver.</p>
<p>The SKIP flag can also be used for temporarily “commenting out” examples.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<dl class="data">
<dt id="doctest.COMPARISON_FLAGS">
<code class="descclassname">doctest.</code><code class="descname">COMPARISON_FLAGS</code><a class="headerlink" href="#doctest.COMPARISON_FLAGS" title="Permalink to this definition">¶</a></dt>
<dd><p>A bitmask or’ing together all the comparison flags above.</p>
</dd></dl>

<p>The second group of options controls how test failures are reported:</p>
<dl class="data">
<dt id="doctest.REPORT_UDIFF">
<code class="descclassname">doctest.</code><code class="descname">REPORT_UDIFF</code><a class="headerlink" href="#doctest.REPORT_UDIFF" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, failures that involve multi-line expected and actual outputs are
displayed using a unified diff.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.REPORT_CDIFF">
<code class="descclassname">doctest.</code><code class="descname">REPORT_CDIFF</code><a class="headerlink" href="#doctest.REPORT_CDIFF" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, failures that involve multi-line expected and actual outputs
will be displayed using a context diff.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.REPORT_NDIFF">
<code class="descclassname">doctest.</code><code class="descname">REPORT_NDIFF</code><a class="headerlink" href="#doctest.REPORT_NDIFF" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, differences are computed by <code class="docutils literal notranslate"><span class="pre">difflib.Differ</span></code>, using the same
algorithm as the popular <code class="file docutils literal notranslate"><span class="pre">ndiff.py</span></code> utility. This is the only method that
marks differences within lines as well as across lines.  For example, if a line
of expected output contains digit <code class="docutils literal notranslate"><span class="pre">1</span></code> where actual output contains letter
<code class="docutils literal notranslate"><span class="pre">l</span></code>, a line is inserted with a caret marking the mismatching column positions.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.REPORT_ONLY_FIRST_FAILURE">
<code class="descclassname">doctest.</code><code class="descname">REPORT_ONLY_FIRST_FAILURE</code><a class="headerlink" href="#doctest.REPORT_ONLY_FIRST_FAILURE" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, display the first failing example in each doctest, but suppress
output for all remaining examples.  This will prevent doctest from reporting
correct examples that break because of earlier failures; but it might also hide
incorrect examples that fail independently of the first failure.  When
<a class="reference internal" href="#doctest.REPORT_ONLY_FIRST_FAILURE" title="doctest.REPORT_ONLY_FIRST_FAILURE"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORT_ONLY_FIRST_FAILURE</span></code></a> is specified, the remaining examples are
still run, and still count towards the total number of failures reported; only
the output is suppressed.</p>
</dd></dl>

<dl class="data">
<dt id="doctest.REPORTING_FLAGS">
<code class="descclassname">doctest.</code><code class="descname">REPORTING_FLAGS</code><a class="headerlink" href="#doctest.REPORTING_FLAGS" title="Permalink to this definition">¶</a></dt>
<dd><p>A bitmask or’ing together all the reporting flags above.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>The constants
<a class="reference internal" href="#doctest.DONT_ACCEPT_BLANKLINE" title="doctest.DONT_ACCEPT_BLANKLINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DONT_ACCEPT_BLANKLINE</span></code></a>, <a class="reference internal" href="#doctest.NORMALIZE_WHITESPACE" title="doctest.NORMALIZE_WHITESPACE"><code class="xref py py-const docutils literal notranslate"><span class="pre">NORMALIZE_WHITESPACE</span></code></a>,
<a class="reference internal" href="#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><code class="xref py py-const docutils literal notranslate"><span class="pre">ELLIPSIS</span></code></a>, <a class="reference internal" href="#doctest.IGNORE_EXCEPTION_DETAIL" title="doctest.IGNORE_EXCEPTION_DETAIL"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORE_EXCEPTION_DETAIL</span></code></a>, <a class="reference internal" href="#doctest.REPORT_UDIFF" title="doctest.REPORT_UDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORT_UDIFF</span></code></a>,
<a class="reference internal" href="#doctest.REPORT_CDIFF" title="doctest.REPORT_CDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORT_CDIFF</span></code></a>, <a class="reference internal" href="#doctest.REPORT_NDIFF" title="doctest.REPORT_NDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORT_NDIFF</span></code></a>,
<a class="reference internal" href="#doctest.REPORT_ONLY_FIRST_FAILURE" title="doctest.REPORT_ONLY_FIRST_FAILURE"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORT_ONLY_FIRST_FAILURE</span></code></a>, <a class="reference internal" href="#doctest.COMPARISON_FLAGS" title="doctest.COMPARISON_FLAGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">COMPARISON_FLAGS</span></code></a> and
<a class="reference internal" href="#doctest.REPORTING_FLAGS" title="doctest.REPORTING_FLAGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">REPORTING_FLAGS</span></code></a> were added.</p>
</div>
<p>There’s also a way to register new option flag names, although this isn’t useful
unless you intend to extend <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> internals via subclassing:</p>
<dl class="function">
<dt id="doctest.register_optionflag">
<code class="descclassname">doctest.</code><code class="descname">register_optionflag</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.register_optionflag" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new option flag with a given name, and return the new flag’s integer
value.  <a class="reference internal" href="#doctest.register_optionflag" title="doctest.register_optionflag"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_optionflag()</span></code></a> can be used when subclassing
<a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a> or <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to create new options that are
supported by your subclasses.  <a class="reference internal" href="#doctest.register_optionflag" title="doctest.register_optionflag"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_optionflag()</span></code></a> should always be
called using the following idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">MY_FLAG</span> <span class="o">=</span> <span class="n">register_optionflag</span><span class="p">(</span><span class="s1">&#39;MY_FLAG&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="directives">
<span id="doctest-directives"></span><h3>25.2.3.6. Directives<a class="headerlink" href="#directives" title="Permalink to this headline">¶</a></h3>
<p>Doctest directives may be used to modify the <a class="reference internal" href="#doctest-options"><span class="std std-ref">option flags</span></a> for an individual example.  Doctest directives are
special Python comments following an example’s source code:</p>
<pre>
<strong id="grammar-token-directive">directive            </strong> ::=  &quot;#&quot; &quot;doctest:&quot; <a class="reference internal" href="#grammar-token-directive_options"><code class="xref docutils literal notranslate"><span class="pre">directive_options</span></code></a>
<strong id="grammar-token-directive_options">directive_options    </strong> ::=  <a class="reference internal" href="#grammar-token-directive_option"><code class="xref docutils literal notranslate"><span class="pre">directive_option</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-directive_option"><code class="xref docutils literal notranslate"><span class="pre">directive_option</span></code></a>)\*
<strong id="grammar-token-directive_option">directive_option     </strong> ::=  <a class="reference internal" href="#grammar-token-on_or_off"><code class="xref docutils literal notranslate"><span class="pre">on_or_off</span></code></a> <a class="reference internal" href="#grammar-token-directive_option_name"><code class="xref docutils literal notranslate"><span class="pre">directive_option_name</span></code></a>
<strong id="grammar-token-on_or_off">on_or_off            </strong> ::=  &quot;+&quot; \| &quot;-&quot;
<strong id="grammar-token-directive_option_name">directive_option_name</strong> ::=  &quot;DONT_ACCEPT_BLANKLINE&quot; \| &quot;NORMALIZE_WHITESPACE&quot; \| ...
</pre>
<p>Whitespace is not allowed between the <code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code> and the directive option
name.  The directive option name can be any of the option flag names explained
above.</p>
<p>An example’s doctest directives modify doctest’s behavior for that single
example.  Use <code class="docutils literal notranslate"><span class="pre">+</span></code> to enable the named behavior, or <code class="docutils literal notranslate"><span class="pre">-</span></code> to disable it.</p>
<p>For example, this test passes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span> <span class="c1"># doctest: +NORMALIZE_WHITESPACE</span>
<span class="go">[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,</span>
<span class="go">10,  11, 12, 13, 14, 15, 16, 17, 18, 19]</span>
</pre></div>
</div>
<p>Without the directive it would fail, both because the actual output doesn’t have
two blanks before the single-digit list elements, and because the actual output
is on a single line.  This test also passes, and also requires a directive to do
so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span> <span class="c1"># doctest: +ELLIPSIS</span>
<span class="go">[0, 1, ..., 18, 19]</span>
</pre></div>
</div>
<p>Multiple directives can be used on a single physical line, separated by
commas:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span> <span class="c1"># doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE</span>
<span class="go">[0,    1, ...,   18,    19]</span>
</pre></div>
</div>
<p>If multiple directive comments are used for a single example, then they are
combined:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span> <span class="c1"># doctest: +ELLIPSIS</span>
<span class="gp">... </span>                <span class="c1"># doctest: +NORMALIZE_WHITESPACE</span>
<span class="go">[0,    1, ...,   18,    19]</span>
</pre></div>
</div>
<p>As the previous example shows, you can add <code class="docutils literal notranslate"><span class="pre">...</span></code> lines to your example
containing only directives.  This can be useful when an example is too long for
a directive to comfortably fit on the same line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="o">+</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span><span class="mi">20</span><span class="p">)</span> <span class="o">+</span> <span class="nb">range</span><span class="p">(</span><span class="mi">30</span><span class="p">,</span><span class="mi">40</span><span class="p">)</span> <span class="o">+</span> <span class="nb">range</span><span class="p">(</span><span class="mi">50</span><span class="p">,</span><span class="mi">60</span><span class="p">)</span>
<span class="gp">... </span><span class="c1"># doctest: +ELLIPSIS</span>
<span class="go">[0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]</span>
</pre></div>
</div>
<p>Note that since all options are disabled by default, and directives apply only
to the example they appear in, enabling options (via <code class="docutils literal notranslate"><span class="pre">+</span></code> in a directive) is
usually the only meaningful choice.  However, option flags can also be passed to
functions that run doctests, establishing different defaults.  In such cases,
disabling an option via <code class="docutils literal notranslate"><span class="pre">-</span></code> in a directive can be useful.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>Support for doctest directives was added.</p>
</div>
</div>
<div class="section" id="warnings">
<span id="doctest-warnings"></span><h3>25.2.3.7. Warnings<a class="headerlink" href="#warnings" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> is serious about requiring exact matches in expected output.  If
even a single character doesn’t match, the test fails.  This will probably
surprise you a few times, as you learn exactly what Python does and doesn’t
guarantee about output.  For example, when printing a dict, Python doesn’t
guarantee that the key-value pairs will be printed in any particular order, so a
test like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="go">{&quot;Hermione&quot;: &quot;hippogryph&quot;, &quot;Harry&quot;: &quot;broomstick&quot;}</span>
</pre></div>
</div>
<p>is vulnerable!  One workaround is to do</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span> <span class="o">==</span> <span class="p">{</span><span class="s2">&quot;Hermione&quot;</span><span class="p">:</span> <span class="s2">&quot;hippogryph&quot;</span><span class="p">,</span> <span class="s2">&quot;Harry&quot;</span><span class="p">:</span> <span class="s2">&quot;broomstick&quot;</span><span class="p">}</span>
<span class="go">True</span>
</pre></div>
</div>
<p>instead.  Another is to do</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">foo</span><span class="p">()</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">[(&#39;Harry&#39;, &#39;broomstick&#39;), (&#39;Hermione&#39;, &#39;hippogryph&#39;)]</span>
</pre></div>
</div>
<p>There are others, but you get the idea.</p>
<p>Another bad idea is to print things that embed an object address, like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">id</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span> <span class="c1"># certain to fail some of the time</span>
<span class="go">7948648</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">()</span>   <span class="c1"># the default repr() for instances embeds an address</span>
<span class="go">&lt;__main__.C instance at 0x00AC18F0&gt;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><code class="xref py py-const docutils literal notranslate"><span class="pre">ELLIPSIS</span></code></a> directive gives a nice approach for the last example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">C</span><span class="p">()</span> <span class="c1">#doctest: +ELLIPSIS</span>
<span class="go">&lt;__main__.C instance at 0x...&gt;</span>
</pre></div>
</div>
<p>Floating-point numbers are also subject to small output variations across
platforms, because Python defers to the platform C library for float formatting,
and C libraries vary widely in quality here.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.</span><span class="o">/</span><span class="mi">7</span>  <span class="c1"># risky</span>
<span class="go">0.14285714285714285</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="mf">1.</span><span class="o">/</span><span class="mi">7</span> <span class="c1"># safer</span>
<span class="go">0.142857142857</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">round</span><span class="p">(</span><span class="mf">1.</span><span class="o">/</span><span class="mi">7</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span> <span class="c1"># much safer</span>
<span class="go">0.142857</span>
</pre></div>
</div>
<p>Numbers of the form <code class="docutils literal notranslate"><span class="pre">I/2.**J</span></code> are safe across all platforms, and I often
contrive doctest examples to produce numbers of that form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">3.</span><span class="o">/</span><span class="mi">4</span>  <span class="c1"># utterly safe</span>
<span class="go">0.75</span>
</pre></div>
</div>
<p>Simple fractions are also easier for people to understand, and that makes for
better documentation.</p>
</div>
</div>
<div class="section" id="basic-api">
<span id="doctest-basic-api"></span><h2>25.2.4. Basic API<a class="headerlink" href="#basic-api" title="Permalink to this headline">¶</a></h2>
<p>The functions <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> and <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> provide a simple interface to
doctest that should be sufficient for most basic uses.  For a less formal
introduction to these two functions, see sections <a class="reference internal" href="#doctest-simple-testmod"><span class="std std-ref">Simple Usage: Checking Examples in Docstrings</span></a>
and <a class="reference internal" href="#doctest-simple-testfile"><span class="std std-ref">Simple Usage: Checking Examples in a Text File</span></a>.</p>
<dl class="function">
<dt id="doctest.testfile">
<code class="descclassname">doctest.</code><code class="descname">testfile</code><span class="sig-paren">(</span><em>filename[, module_relative][, name][, package][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, parser][, encoding]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.testfile" title="Permalink to this definition">¶</a></dt>
<dd><p>All arguments except <em>filename</em> are optional, and should be specified in keyword
form.</p>
<p>Test examples in the file named <em>filename</em>.  Return <code class="docutils literal notranslate"><span class="pre">(failure_count,</span>
<span class="pre">test_count)</span></code>.</p>
<p>Optional argument <em>module_relative</em> specifies how the filename should be
interpreted:</p>
<ul class="simple">
<li>If <em>module_relative</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), then <em>filename</em> specifies an
OS-independent module-relative path.  By default, this path is relative to the
calling module’s directory; but if the <em>package</em> argument is specified, then it
is relative to that package.  To ensure OS-independence, <em>filename</em> should use
<code class="docutils literal notranslate"><span class="pre">/</span></code> characters to separate path segments, and may not be an absolute path
(i.e., it may not begin with <code class="docutils literal notranslate"><span class="pre">/</span></code>).</li>
<li>If <em>module_relative</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, then <em>filename</em> specifies an OS-specific
path.  The path may be absolute or relative; relative paths are resolved with
respect to the current working directory.</li>
</ul>
<p>Optional argument <em>name</em> gives the name of the test; by default, or if <code class="docutils literal notranslate"><span class="pre">None</span></code>,
<code class="docutils literal notranslate"><span class="pre">os.path.basename(filename)</span></code> is used.</p>
<p>Optional argument <em>package</em> is a Python package or the name of a Python package
whose directory should be used as the base directory for a module-relative
filename.  If no package is specified, then the calling module’s directory is
used as the base directory for module-relative filenames.  It is an error to
specify <em>package</em> if <em>module_relative</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Optional argument <em>globs</em> gives a dict to be used as the globals when executing
examples.  A new shallow copy of this dict is created for the doctest, so its
examples start with a clean slate. By default, or if <code class="docutils literal notranslate"><span class="pre">None</span></code>, a new empty dict
is used.</p>
<p>Optional argument <em>extraglobs</em> gives a dict merged into the globals used to
execute examples.  This works like <a class="reference internal" href="stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a>:  if <em>globs</em> and
<em>extraglobs</em> have a common key, the associated value in <em>extraglobs</em> appears in
the combined dict.  By default, or if <code class="docutils literal notranslate"><span class="pre">None</span></code>, no extra globals are used.  This
is an advanced feature that allows parameterization of doctests.  For example, a
doctest can be written for a base class, using a generic name for the class,
then reused to test any number of subclasses by passing an <em>extraglobs</em> dict
mapping the generic name to the subclass to be tested.</p>
<p>Optional argument <em>verbose</em> prints lots of stuff if true, and prints only
failures if false; by default, or if <code class="docutils literal notranslate"><span class="pre">None</span></code>, it’s true if and only if <code class="docutils literal notranslate"><span class="pre">'-v'</span></code>
is in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>.</p>
<p>Optional argument <em>report</em> prints a summary at the end when true, else prints
nothing at the end.  In verbose mode, the summary is detailed, else the summary
is very brief (in fact, empty if all tests passed).</p>
<p>Optional argument <em>optionflags</em> or’s together option flags.  See section
<a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a>.</p>
<p>Optional argument <em>raise_on_error</em> defaults to false.  If true, an exception is
raised upon the first failure or unexpected exception in an example.  This
allows failures to be post-mortem debugged. Default behavior is to continue
running examples.</p>
<p>Optional argument <em>parser</em> specifies a <a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> (or subclass) that
should be used to extract tests from the files.  It defaults to a normal parser
(i.e., <code class="docutils literal notranslate"><span class="pre">DocTestParser()</span></code>).</p>
<p>Optional argument <em>encoding</em> specifies an encoding that should be used to
convert the file to unicode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The parameter <em>encoding</em> was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.testmod">
<code class="descclassname">doctest.</code><code class="descname">testmod</code><span class="sig-paren">(</span><em>[m][, name][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, exclude_empty]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.testmod" title="Permalink to this definition">¶</a></dt>
<dd><p>All arguments are optional, and all except for <em>m</em> should be specified in
keyword form.</p>
<p>Test examples in docstrings in functions and classes reachable from module <em>m</em>
(or module <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> if <em>m</em> is not supplied or is <code class="docutils literal notranslate"><span class="pre">None</span></code>), starting with
<code class="docutils literal notranslate"><span class="pre">m.__doc__</span></code>.</p>
<p>Also test examples reachable from dict <code class="docutils literal notranslate"><span class="pre">m.__test__</span></code>, if it exists and is not
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  <code class="docutils literal notranslate"><span class="pre">m.__test__</span></code> maps names (strings) to functions, classes and
strings; function and class docstrings are searched for examples; strings are
searched directly, as if they were docstrings.</p>
<p>Only docstrings attached to objects belonging to module <em>m</em> are searched.</p>
<p>Return <code class="docutils literal notranslate"><span class="pre">(failure_count,</span> <span class="pre">test_count)</span></code>.</p>
<p>Optional argument <em>name</em> gives the name of the module; by default, or if
<code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">m.__name__</span></code> is used.</p>
<p>Optional argument <em>exclude_empty</em> defaults to false.  If true, objects for which
no doctests are found are excluded from consideration. The default is a backward
compatibility hack, so that code still using <code class="xref py py-meth docutils literal notranslate"><span class="pre">doctest.master.summarize()</span></code> in
conjunction with <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> continues to get output for objects with no
tests. The <em>exclude_empty</em> argument to the newer <a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a>
constructor defaults to true.</p>
<p>Optional arguments <em>extraglobs</em>, <em>verbose</em>, <em>report</em>, <em>optionflags</em>,
<em>raise_on_error</em>, and <em>globs</em> are the same as for function <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a>
above, except that <em>globs</em> defaults to <code class="docutils literal notranslate"><span class="pre">m.__dict__</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The parameter <em>optionflags</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The parameters <em>extraglobs</em>, <em>raise_on_error</em> and <em>exclude_empty</em> were added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The optional argument <em>isprivate</em>, deprecated in 2.4, was removed.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.run_docstring_examples">
<code class="descclassname">doctest.</code><code class="descname">run_docstring_examples</code><span class="sig-paren">(</span><em>f, globs[, verbose][, name][, compileflags][, optionflags]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.run_docstring_examples" title="Permalink to this definition">¶</a></dt>
<dd><p>Test examples associated with object <em>f</em>; for example, <em>f</em> may be a string,
a module, a function, or a class object.</p>
<p>A shallow copy of dictionary argument <em>globs</em> is used for the execution context.</p>
<p>Optional argument <em>name</em> is used in failure messages, and defaults to
<code class="docutils literal notranslate"><span class="pre">&quot;NoName&quot;</span></code>.</p>
<p>If optional argument <em>verbose</em> is true, output is generated even if there are no
failures.  By default, output is generated only in case of an example failure.</p>
<p>Optional argument <em>compileflags</em> gives the set of flags that should be used by
the Python compiler when running the examples.  By default, or if <code class="docutils literal notranslate"><span class="pre">None</span></code>,
flags are deduced corresponding to the set of future features found in <em>globs</em>.</p>
<p>Optional argument <em>optionflags</em> works as for function <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> above.</p>
</dd></dl>

</div>
<div class="section" id="unittest-api">
<span id="doctest-unittest-api"></span><h2>25.2.5. Unittest API<a class="headerlink" href="#unittest-api" title="Permalink to this headline">¶</a></h2>
<p>As your collection of doctest’ed modules grows, you’ll want a way to run all
their doctests systematically.  Prior to Python 2.4, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> had a barely
documented <code class="xref py py-class docutils literal notranslate"><span class="pre">Tester</span></code> class that supplied a rudimentary way to combine
doctests from multiple modules. <code class="xref py py-class docutils literal notranslate"><span class="pre">Tester</span></code> was feeble, and in practice most
serious Python testing frameworks build on the <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module, which
supplies many flexible ways to combine tests from multiple sources.  So, in
Python 2.4, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Tester</span></code> class is deprecated, and
<a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> provides two functions that can be used to create <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>
test suites from modules and text files containing doctests.  To integrate with
<a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> test discovery, include a <code class="xref py py-func docutils literal notranslate"><span class="pre">load_tests()</span></code> function in your
test module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="kn">import</span> <span class="nn">doctest</span>
<span class="kn">import</span> <span class="nn">my_module_with_doctests</span>

<span class="k">def</span> <span class="nf">load_tests</span><span class="p">(</span><span class="n">loader</span><span class="p">,</span> <span class="n">tests</span><span class="p">,</span> <span class="n">ignore</span><span class="p">):</span>
    <span class="n">tests</span><span class="o">.</span><span class="n">addTests</span><span class="p">(</span><span class="n">doctest</span><span class="o">.</span><span class="n">DocTestSuite</span><span class="p">(</span><span class="n">my_module_with_doctests</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">tests</span>
</pre></div>
</div>
<p>There are two main functions for creating <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> instances
from text files and modules with doctests:</p>
<dl class="function">
<dt id="doctest.DocFileSuite">
<code class="descclassname">doctest.</code><code class="descname">DocFileSuite</code><span class="sig-paren">(</span><em>*paths, [module_relative][, package][, setUp][, tearDown][, globs][, optionflags][, parser][, encoding]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocFileSuite" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert doctest tests from one or more text files to a
<a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a>.</p>
<p>The returned <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> is to be run by the unittest framework
and runs the interactive examples in each file.  If an example in any file
fails, then the synthesized unit test fails, and a <code class="xref py py-exc docutils literal notranslate"><span class="pre">failureException</span></code>
exception is raised showing the name of the file containing the test and a
(sometimes approximate) line number.</p>
<p>Pass one or more paths (as strings) to text files to be examined.</p>
<p>Options may be provided as keyword arguments:</p>
<p>Optional argument <em>module_relative</em> specifies how the filenames in <em>paths</em>
should be interpreted:</p>
<ul class="simple">
<li>If <em>module_relative</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), then each filename in
<em>paths</em> specifies an OS-independent module-relative path.  By default, this
path is relative to the calling module’s directory; but if the <em>package</em>
argument is specified, then it is relative to that package.  To ensure
OS-independence, each filename should use <code class="docutils literal notranslate"><span class="pre">/</span></code> characters to separate path
segments, and may not be an absolute path (i.e., it may not begin with
<code class="docutils literal notranslate"><span class="pre">/</span></code>).</li>
<li>If <em>module_relative</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, then each filename in <em>paths</em> specifies
an OS-specific path.  The path may be absolute or relative; relative paths
are resolved with respect to the current working directory.</li>
</ul>
<p>Optional argument <em>package</em> is a Python package or the name of a Python
package whose directory should be used as the base directory for
module-relative filenames in <em>paths</em>.  If no package is specified, then the
calling module’s directory is used as the base directory for module-relative
filenames.  It is an error to specify <em>package</em> if <em>module_relative</em> is
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Optional argument <em>setUp</em> specifies a set-up function for the test suite.
This is called before running the tests in each file.  The <em>setUp</em> function
will be passed a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object.  The setUp function can access the
test globals as the <em>globs</em> attribute of the test passed.</p>
<p>Optional argument <em>tearDown</em> specifies a tear-down function for the test
suite.  This is called after running the tests in each file.  The <em>tearDown</em>
function will be passed a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object.  The setUp function can
access the test globals as the <em>globs</em> attribute of the test passed.</p>
<p>Optional argument <em>globs</em> is a dictionary containing the initial global
variables for the tests.  A new copy of this dictionary is created for each
test.  By default, <em>globs</em> is a new empty dictionary.</p>
<p>Optional argument <em>optionflags</em> specifies the default doctest options for the
tests, created by or-ing together individual option flags.  See section
<a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a>. See function <a class="reference internal" href="#doctest.set_unittest_reportflags" title="doctest.set_unittest_reportflags"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_unittest_reportflags()</span></code></a> below
for a better way to set reporting options.</p>
<p>Optional argument <em>parser</em> specifies a <a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> (or subclass)
that should be used to extract tests from the files.  It defaults to a normal
parser (i.e., <code class="docutils literal notranslate"><span class="pre">DocTestParser()</span></code>).</p>
<p>Optional argument <em>encoding</em> specifies an encoding that should be used to
convert the file to unicode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The global <code class="docutils literal notranslate"><span class="pre">__file__</span></code> was added to the globals provided to doctests
loaded from a text file using <a class="reference internal" href="#doctest.DocFileSuite" title="doctest.DocFileSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocFileSuite()</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The parameter <em>encoding</em> was added.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Unlike <a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a> and <a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a>, this function raises
a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>module</em> contains no docstrings.  You can prevent
this error by passing a <a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a> instance as the
<em>test_finder</em> argument with its <em>exclude_empty</em> keyword argument set
to <code class="docutils literal notranslate"><span class="pre">False</span></code>:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">finder</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestFinder</span><span class="p">(</span><span class="n">exclude_empty</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">suite</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestSuite</span><span class="p">(</span><span class="n">test_finder</span><span class="o">=</span><span class="n">finder</span><span class="p">)</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.DocTestSuite">
<code class="descclassname">doctest.</code><code class="descname">DocTestSuite</code><span class="sig-paren">(</span><em>[module][, globs][, extraglobs][, test_finder][, setUp][, tearDown][, checker]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestSuite" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert doctest tests for a module to a <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a>.</p>
<p>The returned <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> is to be run by the unittest framework
and runs each doctest in the module.  If any of the doctests fail, then the
synthesized unit test fails, and a <code class="xref py py-exc docutils literal notranslate"><span class="pre">failureException</span></code> exception is raised
showing the name of the file containing the test and a (sometimes approximate)
line number.</p>
<p>Optional argument <em>module</em> provides the module to be tested.  It can be a module
object or a (possibly dotted) module name.  If not specified, the module calling
this function is used.</p>
<p>Optional argument <em>globs</em> is a dictionary containing the initial global
variables for the tests.  A new copy of this dictionary is created for each
test.  By default, <em>globs</em> is a new empty dictionary.</p>
<p>Optional argument <em>extraglobs</em> specifies an extra set of global variables, which
is merged into <em>globs</em>.  By default, no extra globals are used.</p>
<p>Optional argument <em>test_finder</em> is the <a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a> object (or a
drop-in replacement) that is used to extract doctests from the module.</p>
<p>Optional arguments <em>setUp</em>, <em>tearDown</em>, and <em>optionflags</em> are the same as for
function <a class="reference internal" href="#doctest.DocFileSuite" title="doctest.DocFileSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocFileSuite()</span></code></a> above.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The parameters <em>globs</em>, <em>extraglobs</em>, <em>test_finder</em>, <em>setUp</em>, <em>tearDown</em>, and
<em>optionflags</em> were added; this function now uses the same search technique as
<a class="reference internal" href="#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">testmod()</span></code></a>.</p>
</div>
</dd></dl>

<p>Under the covers, <a class="reference internal" href="#doctest.DocTestSuite" title="doctest.DocTestSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocTestSuite()</span></code></a> creates a <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> out
of <code class="xref py py-class docutils literal notranslate"><span class="pre">doctest.DocTestCase</span></code> instances, and <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code> is a
subclass of <a class="reference internal" href="unittest.html#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a>. <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code> isn’t documented
here (it’s an internal detail), but studying its code can answer questions about
the exact details of <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> integration.</p>
<p>Similarly, <a class="reference internal" href="#doctest.DocFileSuite" title="doctest.DocFileSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocFileSuite()</span></code></a> creates a <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> out of
<code class="xref py py-class docutils literal notranslate"><span class="pre">doctest.DocFileCase</span></code> instances, and <code class="xref py py-class docutils literal notranslate"><span class="pre">DocFileCase</span></code> is a subclass
of <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code>.</p>
<p>So both ways of creating a <a class="reference internal" href="unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> run instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code>.  This is important for a subtle reason: when you run
<a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> functions yourself, you can control the <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> options in
use directly, by passing option flags to <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> functions.  However, if
you’re writing a <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> framework, <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> ultimately controls
when and how tests get run.  The framework author typically wants to control
<a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> reporting options (perhaps, e.g., specified by command line
options), but there’s no way to pass options through <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> to
<a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> test runners.</p>
<p>For this reason, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> also supports a notion of <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>
reporting flags specific to <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> support, via this function:</p>
<dl class="function">
<dt id="doctest.set_unittest_reportflags">
<code class="descclassname">doctest.</code><code class="descname">set_unittest_reportflags</code><span class="sig-paren">(</span><em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.set_unittest_reportflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> reporting flags to use.</p>
<p>Argument <em>flags</em> or’s together option flags.  See section
<a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a>.  Only “reporting flags” can be used.</p>
<p>This is a module-global setting, and affects all future doctests run by module
<a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>:  the <code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code> looks at
the option flags specified for the test case when the <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code>
instance was constructed.  If no reporting flags were specified (which is the
typical and expected case), <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>’s <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> reporting flags are
<a class="reference internal" href="../reference/expressions.html#bitwise"><span class="std std-ref">bitwise ORed</span></a> into the option flags, and the option flags
so augmented are passed to the <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> instance created to
run the doctest.  If any reporting flags were specified when the
<code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestCase</span></code> instance was constructed, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>’s
<a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> reporting flags are ignored.</p>
<p>The value of the <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> reporting flags in effect before the function
was called is returned by the function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="advanced-api">
<span id="doctest-advanced-api"></span><h2>25.2.6. Advanced API<a class="headerlink" href="#advanced-api" title="Permalink to this headline">¶</a></h2>
<p>The basic API is a simple wrapper that’s intended to make doctest easy to use.
It is fairly flexible, and should meet most users’ needs; however, if you
require more fine-grained control over testing, or wish to extend doctest’s
capabilities, then you should use the advanced API.</p>
<p>The advanced API revolves around two container classes, which are used to store
the interactive examples extracted from doctest cases:</p>
<ul class="simple">
<li><a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a>: A single Python <a class="reference internal" href="../glossary.html#term-statement"><span class="xref std std-term">statement</span></a>, paired with its expected
output.</li>
<li><a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>: A collection of <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a>s, typically extracted
from a single docstring or text file.</li>
</ul>
<p>Additional processing classes are defined to find, parse, and run, and check
doctest examples:</p>
<ul class="simple">
<li><a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a>: Finds all docstrings in a given module, and uses a
<a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> to create a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> from every docstring that
contains interactive examples.</li>
<li><a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a>: Creates a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object from a string (such
as an object’s docstring).</li>
<li><a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a>: Executes the examples in a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>, and uses
an <a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a> to verify their output.</li>
<li><a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a>: Compares the actual output from a doctest example with
the expected output, and decides whether they match.</li>
</ul>
<p>The relationships among these processing classes are summarized in the following
diagram:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>                            <span class="nb">list</span> <span class="n">of</span><span class="p">:</span>
<span class="o">+------+</span>                   <span class="o">+---------+</span>
<span class="o">|</span><span class="n">module</span><span class="o">|</span> <span class="o">--</span><span class="n">DocTestFinder</span><span class="o">-&gt;</span> <span class="o">|</span> <span class="n">DocTest</span> <span class="o">|</span> <span class="o">--</span><span class="n">DocTestRunner</span><span class="o">-&gt;</span> <span class="n">results</span>
<span class="o">+------+</span>    <span class="o">|</span>        <span class="o">^</span>     <span class="o">+---------+</span>     <span class="o">|</span>       <span class="o">^</span>    <span class="p">(</span><span class="n">printed</span><span class="p">)</span>
            <span class="o">|</span>        <span class="o">|</span>     <span class="o">|</span> <span class="n">Example</span> <span class="o">|</span>     <span class="o">|</span>       <span class="o">|</span>
            <span class="n">v</span>        <span class="o">|</span>     <span class="o">|</span>   <span class="o">...</span>   <span class="o">|</span>     <span class="n">v</span>       <span class="o">|</span>
           <span class="n">DocTestParser</span>   <span class="o">|</span> <span class="n">Example</span> <span class="o">|</span>   <span class="n">OutputChecker</span>
                           <span class="o">+---------+</span>
</pre></div>
</div>
<div class="section" id="doctest-objects">
<span id="doctest-doctest"></span><h3>25.2.6.1. DocTest Objects<a class="headerlink" href="#doctest-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.DocTest">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">DocTest</code><span class="sig-paren">(</span><em>examples</em>, <em>globs</em>, <em>name</em>, <em>filename</em>, <em>lineno</em>, <em>docstring</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTest" title="Permalink to this definition">¶</a></dt>
<dd><p>A collection of doctest examples that should be run in a single namespace.  The
constructor arguments are used to initialize the attributes of the same names.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> defines the following attributes.  They are initialized by
the constructor, and should not be modified directly.</p>
<dl class="attribute">
<dt id="doctest.DocTest.examples">
<code class="descname">examples</code><a class="headerlink" href="#doctest.DocTest.examples" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a> objects encoding the individual interactive Python
examples that should be run by this test.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTest.globs">
<code class="descname">globs</code><a class="headerlink" href="#doctest.DocTest.globs" title="Permalink to this definition">¶</a></dt>
<dd><p>The namespace (aka globals) that the examples should be run in. This is a
dictionary mapping names to values.  Any changes to the namespace made by the
examples (such as binding new variables) will be reflected in <a class="reference internal" href="#doctest.DocTest.globs" title="doctest.DocTest.globs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">globs</span></code></a>
after the test is run.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTest.name">
<code class="descname">name</code><a class="headerlink" href="#doctest.DocTest.name" title="Permalink to this definition">¶</a></dt>
<dd><p>A string name identifying the <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>.  Typically, this is the name
of the object or file that the test was extracted from.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTest.filename">
<code class="descname">filename</code><a class="headerlink" href="#doctest.DocTest.filename" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the file that this <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> was extracted from; or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the filename is unknown, or if the <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> was not
extracted from a file.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTest.lineno">
<code class="descname">lineno</code><a class="headerlink" href="#doctest.DocTest.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>The line number within <a class="reference internal" href="#doctest.DocTest.filename" title="doctest.DocTest.filename"><code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code></a> where this <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> begins, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the line number is unavailable.  This line number is zero-based
with respect to the beginning of the file.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTest.docstring">
<code class="descname">docstring</code><a class="headerlink" href="#doctest.DocTest.docstring" title="Permalink to this definition">¶</a></dt>
<dd><p>The string that the test was extracted from, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the string is
unavailable, or if the test was not extracted from a string.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="example-objects">
<span id="doctest-example"></span><h3>25.2.6.2. Example Objects<a class="headerlink" href="#example-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.Example">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">Example</code><span class="sig-paren">(</span><em>source, want[, exc_msg][, lineno][, indent][, options]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.Example" title="Permalink to this definition">¶</a></dt>
<dd><p>A single interactive example, consisting of a Python statement and its expected
output.  The constructor arguments are used to initialize the attributes of the
same names.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a> defines the following attributes.  They are initialized by
the constructor, and should not be modified directly.</p>
<dl class="attribute">
<dt id="doctest.Example.source">
<code class="descname">source</code><a class="headerlink" href="#doctest.Example.source" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the example’s source code.  This source code consists of a
single Python statement, and always ends with a newline; the constructor adds
a newline when necessary.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.Example.want">
<code class="descname">want</code><a class="headerlink" href="#doctest.Example.want" title="Permalink to this definition">¶</a></dt>
<dd><p>The expected output from running the example’s source code (either from
stdout, or a traceback in case of exception).  <a class="reference internal" href="#doctest.Example.want" title="doctest.Example.want"><code class="xref py py-attr docutils literal notranslate"><span class="pre">want</span></code></a> ends with a
newline unless no output is expected, in which case it’s an empty string.  The
constructor adds a newline when necessary.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.Example.exc_msg">
<code class="descname">exc_msg</code><a class="headerlink" href="#doctest.Example.exc_msg" title="Permalink to this definition">¶</a></dt>
<dd><p>The exception message generated by the example, if the example is expected to
generate an exception; or <code class="docutils literal notranslate"><span class="pre">None</span></code> if it is not expected to generate an
exception.  This exception message is compared against the return value of
<a class="reference internal" href="traceback.html#traceback.format_exception_only" title="traceback.format_exception_only"><code class="xref py py-func docutils literal notranslate"><span class="pre">traceback.format_exception_only()</span></code></a>.  <a class="reference internal" href="#doctest.Example.exc_msg" title="doctest.Example.exc_msg"><code class="xref py py-attr docutils literal notranslate"><span class="pre">exc_msg</span></code></a> ends with a newline
unless it’s <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The constructor adds a newline if needed.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.Example.lineno">
<code class="descname">lineno</code><a class="headerlink" href="#doctest.Example.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>The line number within the string containing this example where the example
begins.  This line number is zero-based with respect to the beginning of the
containing string.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.Example.indent">
<code class="descname">indent</code><a class="headerlink" href="#doctest.Example.indent" title="Permalink to this definition">¶</a></dt>
<dd><p>The example’s indentation in the containing string, i.e., the number of space
characters that precede the example’s first prompt.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.Example.options">
<code class="descname">options</code><a class="headerlink" href="#doctest.Example.options" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping from option flags to <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>, which is used
to override default options for this example.  Any option flags not contained
in this dictionary are left at their default value (as specified by the
<a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a>’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">optionflags</span></code>). By default, no options are set.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="doctestfinder-objects">
<span id="doctest-doctestfinder"></span><h3>25.2.6.3. DocTestFinder objects<a class="headerlink" href="#doctestfinder-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.DocTestFinder">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">DocTestFinder</code><span class="sig-paren">(</span><em>[verbose][, parser][, recurse][, exclude_empty]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestFinder" title="Permalink to this definition">¶</a></dt>
<dd><p>A processing class used to extract the <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>s that are relevant to
a given object, from its docstring and the docstrings of its contained objects.
<a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>s can currently be extracted from the following object types:
modules, functions, classes, methods, staticmethods, classmethods, and
properties.</p>
<p>The optional argument <em>verbose</em> can be used to display the objects searched by
the finder.  It defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code> (no output).</p>
<p>The optional argument <em>parser</em> specifies the <a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> object (or a
drop-in replacement) that is used to extract doctests from docstrings.</p>
<p>If the optional argument <em>recurse</em> is false, then <a class="reference internal" href="#doctest.DocTestFinder.find" title="doctest.DocTestFinder.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestFinder.find()</span></code></a>
will only examine the given object, and not any contained objects.</p>
<p>If the optional argument <em>exclude_empty</em> is false, then
<a class="reference internal" href="#doctest.DocTestFinder.find" title="doctest.DocTestFinder.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestFinder.find()</span></code></a> will include tests for objects with empty docstrings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.DocTestFinder" title="doctest.DocTestFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code></a> defines the following method:</p>
<dl class="method">
<dt id="doctest.DocTestFinder.find">
<code class="descname">find</code><span class="sig-paren">(</span><em>obj[, name][, module][, globs][, extraglobs]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestFinder.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>s that are defined by <em>obj</em>’s
docstring, or by any of its contained objects’ docstrings.</p>
<p>The optional argument <em>name</em> specifies the object’s name; this name will be
used to construct names for the returned <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>s.  If <em>name</em> is
not specified, then <code class="docutils literal notranslate"><span class="pre">obj.__name__</span></code> is used.</p>
<p>The optional parameter <em>module</em> is the module that contains the given object.
If the module is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then the test finder will attempt
to automatically determine the correct module.  The object’s module is used:</p>
<ul class="simple">
<li>As a default namespace, if <em>globs</em> is not specified.</li>
<li>To prevent the DocTestFinder from extracting DocTests from objects that are
imported from other modules.  (Contained objects with modules other than
<em>module</em> are ignored.)</li>
<li>To find the name of the file containing the object.</li>
<li>To help find the line number of the object within its file.</li>
</ul>
<p>If <em>module</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, no attempt to find the module will be made.  This is
obscure, of use mostly in testing doctest itself: if <em>module</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, or
is <code class="docutils literal notranslate"><span class="pre">None</span></code> but cannot be found automatically, then all objects are considered
to belong to the (non-existent) module, so all contained objects will
(recursively) be searched for doctests.</p>
<p>The globals for each <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> is formed by combining <em>globs</em> and
<em>extraglobs</em> (bindings in <em>extraglobs</em> override bindings in <em>globs</em>).  A new
shallow copy of the globals dictionary is created for each <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>.
If <em>globs</em> is not specified, then it defaults to the module’s <em>__dict__</em>, if
specified, or <code class="docutils literal notranslate"><span class="pre">{}</span></code> otherwise.  If <em>extraglobs</em> is not specified, then it
defaults to <code class="docutils literal notranslate"><span class="pre">{}</span></code>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="doctestparser-objects">
<span id="doctest-doctestparser"></span><h3>25.2.6.4. DocTestParser objects<a class="headerlink" href="#doctestparser-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.DocTestParser">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">DocTestParser</code><a class="headerlink" href="#doctest.DocTestParser" title="Permalink to this definition">¶</a></dt>
<dd><p>A processing class used to extract interactive examples from a string, and use
them to create a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> defines the following methods:</p>
<dl class="method">
<dt id="doctest.DocTestParser.get_doctest">
<code class="descname">get_doctest</code><span class="sig-paren">(</span><em>string</em>, <em>globs</em>, <em>name</em>, <em>filename</em>, <em>lineno</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestParser.get_doctest" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract all doctest examples from the given string, and collect them into a
<a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object.</p>
<p><em>globs</em>, <em>name</em>, <em>filename</em>, and <em>lineno</em> are attributes for the new
<a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object.  See the documentation for <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> for more
information.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestParser.get_examples">
<code class="descname">get_examples</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestParser.get_examples" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract all doctest examples from the given string, and return them as a list
of <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a> objects.  Line numbers are 0-based.  The optional argument
<em>name</em> is a name identifying this string, and is only used for error messages.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestParser.parse">
<code class="descname">parse</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestParser.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Divide the given string into examples and intervening text, and return them as
a list of alternating <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a>s and strings. Line numbers for the
<a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a>s are 0-based.  The optional argument <em>name</em> is a name
identifying this string, and is only used for error messages.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="doctestrunner-objects">
<span id="doctest-doctestrunner"></span><h3>25.2.6.5. DocTestRunner objects<a class="headerlink" href="#doctestrunner-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.DocTestRunner">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">DocTestRunner</code><span class="sig-paren">(</span><em>[checker][, verbose][, optionflags]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner" title="Permalink to this definition">¶</a></dt>
<dd><p>A processing class used to execute and verify the interactive examples in a
<a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a>.</p>
<p>The comparison between expected outputs and actual outputs is done by an
<a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a>.  This comparison may be customized with a number of
option flags; see section <a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a> for more information.  If the
option flags are insufficient, then the comparison may also be customized by
passing a subclass of <a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a> to the constructor.</p>
<p>The test runner’s display output can be controlled in two ways. First, an output
function can be passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">TestRunner.run()</span></code>; this function will be called
with strings that should be displayed.  It defaults to <code class="docutils literal notranslate"><span class="pre">sys.stdout.write</span></code>.  If
capturing the output is not sufficient, then the display output can be also
customized by subclassing DocTestRunner, and overriding the methods
<a class="reference internal" href="#doctest.DocTestRunner.report_start" title="doctest.DocTestRunner.report_start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">report_start()</span></code></a>, <a class="reference internal" href="#doctest.DocTestRunner.report_success" title="doctest.DocTestRunner.report_success"><code class="xref py py-meth docutils literal notranslate"><span class="pre">report_success()</span></code></a>,
<a class="reference internal" href="#doctest.DocTestRunner.report_unexpected_exception" title="doctest.DocTestRunner.report_unexpected_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">report_unexpected_exception()</span></code></a>, and <a class="reference internal" href="#doctest.DocTestRunner.report_failure" title="doctest.DocTestRunner.report_failure"><code class="xref py py-meth docutils literal notranslate"><span class="pre">report_failure()</span></code></a>.</p>
<p>The optional keyword argument <em>checker</em> specifies the <a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a>
object (or drop-in replacement) that should be used to compare the expected
outputs to the actual outputs of doctest examples.</p>
<p>The optional keyword argument <em>verbose</em> controls the <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a>’s
verbosity.  If <em>verbose</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, then information is printed about each
example, as it is run.  If <em>verbose</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, then only failures are
printed.  If <em>verbose</em> is unspecified, or <code class="docutils literal notranslate"><span class="pre">None</span></code>, then verbose output is used
iff the command-line switch <code class="docutils literal notranslate"><span class="pre">-v</span></code> is used.</p>
<p>The optional keyword argument <em>optionflags</em> can be used to control how the test
runner compares expected output to actual output, and how it displays failures.
For more information, see section <a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.DocTestParser" title="doctest.DocTestParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestParser</span></code></a> defines the following methods:</p>
<dl class="method">
<dt id="doctest.DocTestRunner.report_start">
<code class="descname">report_start</code><span class="sig-paren">(</span><em>out</em>, <em>test</em>, <em>example</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.report_start" title="Permalink to this definition">¶</a></dt>
<dd><p>Report that the test runner is about to process the given example. This method
is provided to allow subclasses of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to customize their
output; it should not be called directly.</p>
<p><em>example</em> is the example about to be processed.  <em>test</em> is the test
<em>containing example</em>.  <em>out</em> is the output function that was passed to
<a class="reference internal" href="#doctest.DocTestRunner.run" title="doctest.DocTestRunner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestRunner.run()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestRunner.report_success">
<code class="descname">report_success</code><span class="sig-paren">(</span><em>out</em>, <em>test</em>, <em>example</em>, <em>got</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.report_success" title="Permalink to this definition">¶</a></dt>
<dd><p>Report that the given example ran successfully.  This method is provided to
allow subclasses of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to customize their output; it
should not be called directly.</p>
<p><em>example</em> is the example about to be processed.  <em>got</em> is the actual output
from the example.  <em>test</em> is the test containing <em>example</em>.  <em>out</em> is the
output function that was passed to <a class="reference internal" href="#doctest.DocTestRunner.run" title="doctest.DocTestRunner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestRunner.run()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestRunner.report_failure">
<code class="descname">report_failure</code><span class="sig-paren">(</span><em>out</em>, <em>test</em>, <em>example</em>, <em>got</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.report_failure" title="Permalink to this definition">¶</a></dt>
<dd><p>Report that the given example failed.  This method is provided to allow
subclasses of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to customize their output; it should not
be called directly.</p>
<p><em>example</em> is the example about to be processed.  <em>got</em> is the actual output
from the example.  <em>test</em> is the test containing <em>example</em>.  <em>out</em> is the
output function that was passed to <a class="reference internal" href="#doctest.DocTestRunner.run" title="doctest.DocTestRunner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestRunner.run()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestRunner.report_unexpected_exception">
<code class="descname">report_unexpected_exception</code><span class="sig-paren">(</span><em>out</em>, <em>test</em>, <em>example</em>, <em>exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.report_unexpected_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Report that the given example raised an unexpected exception. This method is
provided to allow subclasses of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to customize their
output; it should not be called directly.</p>
<p><em>example</em> is the example about to be processed. <em>exc_info</em> is a tuple
containing information about the unexpected exception (as returned by
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>). <em>test</em> is the test containing <em>example</em>.  <em>out</em> is the
output function that was passed to <a class="reference internal" href="#doctest.DocTestRunner.run" title="doctest.DocTestRunner.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestRunner.run()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestRunner.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>test[, compileflags][, out][, clear_globs]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the examples in <em>test</em> (a <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object), and display the
results using the writer function <em>out</em>.</p>
<p>The examples are run in the namespace <code class="docutils literal notranslate"><span class="pre">test.globs</span></code>.  If <em>clear_globs</em> is
true (the default), then this namespace will be cleared after the test runs,
to help with garbage collection. If you would like to examine the namespace
after the test completes, then use <em>clear_globs=False</em>.</p>
<p><em>compileflags</em> gives the set of flags that should be used by the Python
compiler when running the examples.  If not specified, then it will default to
the set of future-import flags that apply to <em>globs</em>.</p>
<p>The output of each example is checked using the <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a>’s
output checker, and the results are formatted by the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">DocTestRunner.report_*()</span></code> methods.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.DocTestRunner.summarize">
<code class="descname">summarize</code><span class="sig-paren">(</span><span class="optional">[</span><em>verbose</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestRunner.summarize" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a summary of all the test cases that have been run by this DocTestRunner,
and return a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">TestResults(failed,</span> <span class="pre">attempted)</span></code>.</p>
<p>The optional <em>verbose</em> argument controls how detailed the summary is.  If the
verbosity is not specified, then the <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a>’s verbosity is
used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Use a named tuple.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="outputchecker-objects">
<span id="doctest-outputchecker"></span><h3>25.2.6.6. OutputChecker objects<a class="headerlink" href="#outputchecker-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="doctest.OutputChecker">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">OutputChecker</code><a class="headerlink" href="#doctest.OutputChecker" title="Permalink to this definition">¶</a></dt>
<dd><p>A class used to check the whether the actual output from a doctest example
matches the expected output.  <a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a> defines two methods:
<a class="reference internal" href="#doctest.OutputChecker.check_output" title="doctest.OutputChecker.check_output"><code class="xref py py-meth docutils literal notranslate"><span class="pre">check_output()</span></code></a>, which compares a given pair of outputs, and returns true
if they match; and <a class="reference internal" href="#doctest.OutputChecker.output_difference" title="doctest.OutputChecker.output_difference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">output_difference()</span></code></a>, which returns a string describing
the differences between two outputs.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#doctest.OutputChecker" title="doctest.OutputChecker"><code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code></a> defines the following methods:</p>
<dl class="method">
<dt id="doctest.OutputChecker.check_output">
<code class="descname">check_output</code><span class="sig-paren">(</span><em>want</em>, <em>got</em>, <em>optionflags</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.OutputChecker.check_output" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> iff the actual output from an example (<em>got</em>) matches the
expected output (<em>want</em>).  These strings are always considered to match if
they are identical; but depending on what option flags the test runner is
using, several non-exact match types are also possible.  See section
<a class="reference internal" href="#doctest-options"><span class="std std-ref">Option Flags</span></a> for more information about option flags.</p>
</dd></dl>

<dl class="method">
<dt id="doctest.OutputChecker.output_difference">
<code class="descname">output_difference</code><span class="sig-paren">(</span><em>example</em>, <em>got</em>, <em>optionflags</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.OutputChecker.output_difference" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string describing the differences between the expected output for a
given example (<em>example</em>) and the actual output (<em>got</em>).  <em>optionflags</em> is the
set of option flags used to compare <em>want</em> and <em>got</em>.</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="debugging">
<span id="doctest-debugging"></span><h2>25.2.7. Debugging<a class="headerlink" href="#debugging" title="Permalink to this headline">¶</a></h2>
<p>Doctest provides several mechanisms for debugging doctest examples:</p>
<ul>
<li><p class="first">Several functions convert doctests to executable Python programs, which can be
run under the Python debugger, <a class="reference internal" href="pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="#doctest.DebugRunner" title="doctest.DebugRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DebugRunner</span></code></a> class is a subclass of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> that
raises an exception for the first failing example, containing information about
that example. This information can be used to perform post-mortem debugging on
the example.</p>
</li>
<li><p class="first">The <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> cases generated by <a class="reference internal" href="#doctest.DocTestSuite" title="doctest.DocTestSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocTestSuite()</span></code></a> support the
<a class="reference internal" href="#doctest.debug" title="doctest.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a> method defined by <a class="reference internal" href="unittest.html#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a>.</p>
</li>
<li><p class="first">You can add a call to <a class="reference internal" href="pdb.html#pdb.set_trace" title="pdb.set_trace"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.set_trace()</span></code></a> in a doctest example, and you’ll
drop into the Python debugger when that line is executed.  Then you can inspect
current values of variables, and so on.  For example, suppose <code class="file docutils literal notranslate"><span class="pre">a.py</span></code>
contains just this module docstring:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="sd">&quot;&quot;&quot;</span>
<span class="sd">&gt;&gt;&gt; def f(x):</span>
<span class="sd">...     g(x*2)</span>
<span class="sd">&gt;&gt;&gt; def g(x):</span>
<span class="sd">...     print x+3</span>
<span class="sd">...     import pdb; pdb.set_trace()</span>
<span class="sd">&gt;&gt;&gt; f(3)</span>
<span class="sd">9</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>Then an interactive Python session may look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">a</span><span class="o">,</span> <span class="nn">doctest</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">--Return--</span>
<span class="go">&gt; &lt;doctest a[1]&gt;(3)g()-&gt;None</span>
<span class="go">-&gt; import pdb; pdb.set_trace()</span>
<span class="go">(Pdb) list</span>
<span class="go">  1     def g(x):</span>
<span class="go">  2         print x+3</span>
<span class="go">  3  -&gt;     import pdb; pdb.set_trace()</span>
<span class="go">[EOF]</span>
<span class="go">(Pdb) print x</span>
<span class="go">6</span>
<span class="go">(Pdb) step</span>
<span class="go">--Return--</span>
<span class="go">&gt; &lt;doctest a[0]&gt;(2)f()-&gt;None</span>
<span class="go">-&gt; g(x*2)</span>
<span class="go">(Pdb) list</span>
<span class="go">  1     def f(x):</span>
<span class="go">  2  -&gt;     g(x*2)</span>
<span class="go">[EOF]</span>
<span class="go">(Pdb) print x</span>
<span class="go">3</span>
<span class="go">(Pdb) step</span>
<span class="go">--Return--</span>
<span class="go">&gt; &lt;doctest a[2]&gt;(1)?()-&gt;None</span>
<span class="go">-&gt; f(3)</span>
<span class="go">(Pdb) cont</span>
<span class="go">(0, 3)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The ability to use <a class="reference internal" href="pdb.html#pdb.set_trace" title="pdb.set_trace"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.set_trace()</span></code></a> usefully inside doctests was added.</p>
</div>
</li>
</ul>
<p>Functions that convert doctests to Python code, and possibly run the synthesized
code under the debugger:</p>
<dl class="function">
<dt id="doctest.script_from_examples">
<code class="descclassname">doctest.</code><code class="descname">script_from_examples</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.script_from_examples" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert text with examples to a script.</p>
<p>Argument <em>s</em> is a string containing doctest examples.  The string is converted
to a Python script, where doctest examples in <em>s</em> are converted to regular code,
and everything else is converted to Python comments.  The generated script is
returned as a string. For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">doctest</span>
<span class="nb">print</span> <span class="n">doctest</span><span class="o">.</span><span class="n">script_from_examples</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2">    Set x and y to 1 and 2.</span>
<span class="s2">    &gt;&gt;&gt; x, y = 1, 2</span>

<span class="s2">    Print their sum:</span>
<span class="s2">    &gt;&gt;&gt; print x+y</span>
<span class="s2">    3</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>displays:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Set x and y to 1 and 2.</span>
<span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span>
<span class="c1">#</span>
<span class="c1"># Print their sum:</span>
<span class="nb">print</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
<span class="c1"># Expected:</span>
<span class="c1">## 3</span>
</pre></div>
</div>
<p>This function is used internally by other functions (see below), but can also be
useful when you want to transform an interactive Python session into a Python
script.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.testsource">
<code class="descclassname">doctest.</code><code class="descname">testsource</code><span class="sig-paren">(</span><em>module</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.testsource" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the doctest for an object to a script.</p>
<p>Argument <em>module</em> is a module object, or dotted name of a module, containing the
object whose doctests are of interest.  Argument <em>name</em> is the name (within the
module) of the object with the doctests of interest.  The result is a string,
containing the object’s docstring converted to a Python script, as described for
<a class="reference internal" href="#doctest.script_from_examples" title="doctest.script_from_examples"><code class="xref py py-func docutils literal notranslate"><span class="pre">script_from_examples()</span></code></a> above.  For example, if module <code class="file docutils literal notranslate"><span class="pre">a.py</span></code>
contains a top-level function <code class="xref py py-func docutils literal notranslate"><span class="pre">f()</span></code>, then</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">a</span><span class="o">,</span> <span class="nn">doctest</span>
<span class="nb">print</span> <span class="n">doctest</span><span class="o">.</span><span class="n">testsource</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="s2">&quot;a.f&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>prints a script version of function <code class="xref py py-func docutils literal notranslate"><span class="pre">f()</span></code>’s docstring, with doctests
converted to code, and the rest placed in comments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.debug">
<code class="descclassname">doctest.</code><code class="descname">debug</code><span class="sig-paren">(</span><em>module</em>, <em>name</em><span class="optional">[</span>, <em>pm</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#doctest.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Debug the doctests for an object.</p>
<p>The <em>module</em> and <em>name</em> arguments are the same as for function
<a class="reference internal" href="#doctest.testsource" title="doctest.testsource"><code class="xref py py-func docutils literal notranslate"><span class="pre">testsource()</span></code></a> above.  The synthesized Python script for the named object’s
docstring is written to a temporary file, and then that file is run under the
control of the Python debugger, <a class="reference internal" href="pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a>.</p>
<p>A shallow copy of <code class="docutils literal notranslate"><span class="pre">module.__dict__</span></code> is used for both local and global
execution context.</p>
<p>Optional argument <em>pm</em> controls whether post-mortem debugging is used.  If <em>pm</em>
has a true value, the script file is run directly, and the debugger gets
involved only if the script terminates via raising an unhandled exception.  If
it does, then post-mortem debugging is invoked, via <a class="reference internal" href="pdb.html#pdb.post_mortem" title="pdb.post_mortem"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.post_mortem()</span></code></a>,
passing the traceback object from the unhandled exception.  If <em>pm</em> is not
specified, or is false, the script is run under the debugger from the start, via
passing an appropriate <a class="reference internal" href="functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> call to <a class="reference internal" href="pdb.html#pdb.run" title="pdb.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.run()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <em>pm</em> argument was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="doctest.debug_src">
<code class="descclassname">doctest.</code><code class="descname">debug_src</code><span class="sig-paren">(</span><em>src[, pm][, globs]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.debug_src" title="Permalink to this definition">¶</a></dt>
<dd><p>Debug the doctests in a string.</p>
<p>This is like function <a class="reference internal" href="#doctest.debug" title="doctest.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a> above, except that a string containing
doctest examples is specified directly, via the <em>src</em> argument.</p>
<p>Optional argument <em>pm</em> has the same meaning as in function <a class="reference internal" href="#doctest.debug" title="doctest.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a> above.</p>
<p>Optional argument <em>globs</em> gives a dictionary to use as both local and global
execution context.  If not specified, or <code class="docutils literal notranslate"><span class="pre">None</span></code>, an empty dictionary is used.
If specified, a shallow copy of the dictionary is used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#doctest.DebugRunner" title="doctest.DebugRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DebugRunner</span></code></a> class, and the special exceptions it may raise, are of
most interest to testing framework authors, and will only be sketched here.  See
the source code, and especially <a class="reference internal" href="#doctest.DebugRunner" title="doctest.DebugRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DebugRunner</span></code></a>’s docstring (which is a
doctest!) for more details:</p>
<dl class="class">
<dt id="doctest.DebugRunner">
<em class="property">class </em><code class="descclassname">doctest.</code><code class="descname">DebugRunner</code><span class="sig-paren">(</span><em>[checker][, verbose][, optionflags]</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DebugRunner" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> that raises an exception as soon as a
failure is encountered.  If an unexpected exception occurs, an
<a class="reference internal" href="#doctest.UnexpectedException" title="doctest.UnexpectedException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnexpectedException</span></code></a> exception is raised, containing the test, the
example, and the original exception.  If the output doesn’t match, then a
<a class="reference internal" href="#doctest.DocTestFailure" title="doctest.DocTestFailure"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DocTestFailure</span></code></a> exception is raised, containing the test, the example, and
the actual output.</p>
<p>For information about the constructor parameters and methods, see the
documentation for <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> in section <a class="reference internal" href="#doctest-advanced-api"><span class="std std-ref">Advanced API</span></a>.</p>
</dd></dl>

<p>There are two exceptions that may be raised by <a class="reference internal" href="#doctest.DebugRunner" title="doctest.DebugRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DebugRunner</span></code></a> instances:</p>
<dl class="exception">
<dt id="doctest.DocTestFailure">
<em class="property">exception </em><code class="descclassname">doctest.</code><code class="descname">DocTestFailure</code><span class="sig-paren">(</span><em>test</em>, <em>example</em>, <em>got</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.DocTestFailure" title="Permalink to this definition">¶</a></dt>
<dd><p>An exception raised by <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to signal that a doctest example’s
actual output did not match its expected output. The constructor arguments are
used to initialize the attributes of the same names.</p>
</dd></dl>

<p><a class="reference internal" href="#doctest.DocTestFailure" title="doctest.DocTestFailure"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DocTestFailure</span></code></a> defines the following attributes:</p>
<dl class="attribute">
<dt id="doctest.DocTestFailure.test">
<code class="descclassname">DocTestFailure.</code><code class="descname">test</code><a class="headerlink" href="#doctest.DocTestFailure.test" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object that was being run when the example failed.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTestFailure.example">
<code class="descclassname">DocTestFailure.</code><code class="descname">example</code><a class="headerlink" href="#doctest.DocTestFailure.example" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a> that failed.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.DocTestFailure.got">
<code class="descclassname">DocTestFailure.</code><code class="descname">got</code><a class="headerlink" href="#doctest.DocTestFailure.got" title="Permalink to this definition">¶</a></dt>
<dd><p>The example’s actual output.</p>
</dd></dl>

<dl class="exception">
<dt id="doctest.UnexpectedException">
<em class="property">exception </em><code class="descclassname">doctest.</code><code class="descname">UnexpectedException</code><span class="sig-paren">(</span><em>test</em>, <em>example</em>, <em>exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#doctest.UnexpectedException" title="Permalink to this definition">¶</a></dt>
<dd><p>An exception raised by <a class="reference internal" href="#doctest.DocTestRunner" title="doctest.DocTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code></a> to signal that a doctest
example raised an unexpected exception.  The constructor arguments are used
to initialize the attributes of the same names.</p>
</dd></dl>

<p><a class="reference internal" href="#doctest.UnexpectedException" title="doctest.UnexpectedException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnexpectedException</span></code></a> defines the following attributes:</p>
<dl class="attribute">
<dt id="doctest.UnexpectedException.test">
<code class="descclassname">UnexpectedException.</code><code class="descname">test</code><a class="headerlink" href="#doctest.UnexpectedException.test" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#doctest.DocTest" title="doctest.DocTest"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTest</span></code></a> object that was being run when the example failed.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.UnexpectedException.example">
<code class="descclassname">UnexpectedException.</code><code class="descname">example</code><a class="headerlink" href="#doctest.UnexpectedException.example" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#doctest.Example" title="doctest.Example"><code class="xref py py-class docutils literal notranslate"><span class="pre">Example</span></code></a> that failed.</p>
</dd></dl>

<dl class="attribute">
<dt id="doctest.UnexpectedException.exc_info">
<code class="descclassname">UnexpectedException.</code><code class="descname">exc_info</code><a class="headerlink" href="#doctest.UnexpectedException.exc_info" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple containing information about the unexpected exception, as returned by
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="soapbox">
<span id="doctest-soapbox"></span><h2>25.2.8. Soapbox<a class="headerlink" href="#soapbox" title="Permalink to this headline">¶</a></h2>
<p>As mentioned in the introduction, <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> has grown to have three primary
uses:</p>
<ol class="arabic simple">
<li>Checking examples in docstrings.</li>
<li>Regression testing.</li>
<li>Executable documentation / literate testing.</li>
</ol>
<p>These uses have different requirements, and it is important to distinguish them.
In particular, filling your docstrings with obscure test cases makes for bad
documentation.</p>
<p>When writing a docstring, choose docstring examples with care. There’s an art to
this that needs to be learned—it may not be natural at first.  Examples should
add genuine value to the documentation.  A good example can often be worth many
words. If done with care, the examples will be invaluable for your users, and
will pay back the time it takes to collect them many times over as the years go
by and things change.  I’m still amazed at how often one of my <a class="reference internal" href="#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>
examples stops working after a “harmless” change.</p>
<p>Doctest also makes an excellent tool for regression testing, especially if you
don’t skimp on explanatory text.  By interleaving prose and examples, it becomes
much easier to keep track of what’s actually being tested, and why.  When a test
fails, good prose can make it much easier to figure out what the problem is, and
how it should be fixed.  It’s true that you could write extensive comments in
code-based testing, but few programmers do. Many have found that using doctest
approaches instead leads to much clearer tests.  Perhaps this is simply because
doctest makes writing prose a little easier than writing code, while writing
comments in code is a little harder.  I think it goes deeper than just that:
the natural attitude when writing a doctest-based test is that you want to
explain the fine points of your software, and illustrate them with examples.
This in turn naturally leads to test files that start with the simplest
features, and logically progress to complications and edge cases.  A coherent
narrative is the result, instead of a collection of isolated functions that test
isolated bits of functionality seemingly at random.  It’s a different attitude,
and produces different results, blurring the distinction between testing and
explaining.</p>
<p>Regression testing is best confined to dedicated objects or files.  There are
several options for organizing tests:</p>
<ul class="simple">
<li>Write text files containing test cases as interactive examples, and test the
files using <a class="reference internal" href="#doctest.testfile" title="doctest.testfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code></a> or <a class="reference internal" href="#doctest.DocFileSuite" title="doctest.DocFileSuite"><code class="xref py py-func docutils literal notranslate"><span class="pre">DocFileSuite()</span></code></a>.  This is recommended,
although is easiest to do for new projects, designed from the start to use
doctest.</li>
<li>Define functions named <code class="docutils literal notranslate"><span class="pre">_regrtest_topic</span></code> that consist of single docstrings,
containing test cases for the named topics.  These functions can be included in
the same file as the module, or separated out into a separate test file.</li>
<li>Define a <code class="docutils literal notranslate"><span class="pre">__test__</span></code> dictionary mapping from regression test topics to
docstrings containing test cases.</li>
</ul>
<p>When you have placed your tests in a module, the module can itself be the test
runner.  When a test fails, you can arrange for your test runner to re-run only
the failing doctest while you debug the problem.  Here is a minimal example of
such a test runner:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">doctest</span>
    <span class="n">flags</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">REPORT_NDIFF</span><span class="o">|</span><span class="n">doctest</span><span class="o">.</span><span class="n">REPORT_ONLY_FIRST_FAILURE</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">name</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">name</span> <span class="ow">in</span> <span class="nb">globals</span><span class="p">():</span>
            <span class="n">obj</span> <span class="o">=</span> <span class="nb">globals</span><span class="p">()[</span><span class="n">name</span><span class="p">]</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">obj</span> <span class="o">=</span> <span class="n">__test__</span><span class="p">[</span><span class="n">name</span><span class="p">]</span>
        <span class="n">doctest</span><span class="o">.</span><span class="n">run_docstring_examples</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">globals</span><span class="p">(),</span> <span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">,</span>
                                       <span class="n">optionflags</span><span class="o">=</span><span class="n">flags</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">fail</span><span class="p">,</span> <span class="n">total</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">(</span><span class="n">optionflags</span><span class="o">=</span><span class="n">flags</span><span class="p">)</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> failures out of </span><span class="si">{}</span><span class="s2"> tests&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">fail</span><span class="p">,</span> <span class="n">total</span><span class="p">))</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Examples containing both expected output and an exception are not supported.
Trying to guess where one ends and the other begins is too error-prone, and that
also makes for a confusing test.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a><ul>
<li><a class="reference internal" href="#simple-usage-checking-examples-in-docstrings">25.2.1. Simple Usage: Checking Examples in Docstrings</a></li>
<li><a class="reference internal" href="#simple-usage-checking-examples-in-a-text-file">25.2.2. Simple Usage: Checking Examples in a Text File</a></li>
<li><a class="reference internal" href="#how-it-works">25.2.3. How It Works</a><ul>
<li><a class="reference internal" href="#which-docstrings-are-examined">25.2.3.1. Which Docstrings Are Examined?</a></li>
<li><a class="reference internal" href="#how-are-docstring-examples-recognized">25.2.3.2. How are Docstring Examples Recognized?</a></li>
<li><a class="reference internal" href="#what-s-the-execution-context">25.2.3.3. What’s the Execution Context?</a></li>
<li><a class="reference internal" href="#what-about-exceptions">25.2.3.4. What About Exceptions?</a></li>
<li><a class="reference internal" href="#option-flags">25.2.3.5. Option Flags</a></li>
<li><a class="reference internal" href="#directives">25.2.3.6. Directives</a></li>
<li><a class="reference internal" href="#warnings">25.2.3.7. Warnings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#basic-api">25.2.4. Basic API</a></li>
<li><a class="reference internal" href="#unittest-api">25.2.5. Unittest API</a></li>
<li><a class="reference internal" href="#advanced-api">25.2.6. Advanced API</a><ul>
<li><a class="reference internal" href="#doctest-objects">25.2.6.1. DocTest Objects</a></li>
<li><a class="reference internal" href="#example-objects">25.2.6.2. Example Objects</a></li>
<li><a class="reference internal" href="#doctestfinder-objects">25.2.6.3. DocTestFinder objects</a></li>
<li><a class="reference internal" href="#doctestparser-objects">25.2.6.4. DocTestParser objects</a></li>
<li><a class="reference internal" href="#doctestrunner-objects">25.2.6.5. DocTestRunner objects</a></li>
<li><a class="reference internal" href="#outputchecker-objects">25.2.6.6. OutputChecker objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#debugging">25.2.7. Debugging</a></li>
<li><a class="reference internal" href="#soapbox">25.2.8. Soapbox</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pydoc.html"
                        title="previous chapter">25.1. <code class="docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unittest.html"
                        title="next chapter">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/doctest.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unittest.html" title="25.3. unittest — Unit testing framework"
             >next</a> |</li>
        <li class="right" >
          <a href="pydoc.html" title="25.1. pydoc — Documentation generator and online help system"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" >25. Development Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\M :�D�D!html/library/docxmlrpcserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.25. DocXMLRPCServer — Self-documenting XML-RPC server &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21. Multimedia Services" href="mm.html" />
    <link rel="prev" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server" href="simplexmlrpcserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/docxmlrpcserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mm.html" title="21. Multimedia Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="simplexmlrpcserver.html" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-DocXMLRPCServer">
<span id="docxmlrpcserver-self-documenting-xml-rpc-server"></span><h1>20.25. <a class="reference internal" href="#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> — Self-documenting XML-RPC server<a class="headerlink" href="#module-DocXMLRPCServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> module has been merged into <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.server</span></code>
in Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>The <a class="reference internal" href="#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> module extends the classes found in
<a class="reference internal" href="simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> to serve HTML documentation in response to HTTP GET
requests. Servers can either be free standing, using <a class="reference internal" href="#DocXMLRPCServer.DocXMLRPCServer" title="DocXMLRPCServer.DocXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a>,
or embedded in a CGI environment, using <a class="reference internal" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler" title="DocXMLRPCServer.DocCGIXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocCGIXMLRPCRequestHandler</span></code></a>.</p>
<dl class="class">
<dt id="DocXMLRPCServer.DocXMLRPCServer">
<em class="property">class </em><code class="descclassname">DocXMLRPCServer.</code><code class="descname">DocXMLRPCServer</code><span class="sig-paren">(</span><em>addr</em><span class="optional">[</span>, <em>requestHandler</em><span class="optional">[</span>, <em>logRequests</em><span class="optional">[</span>, <em>allow_none</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>bind_and_activate</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocXMLRPCServer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new server instance. All parameters have the same meaning as for
<a class="reference internal" href="simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer.SimpleXMLRPCServer</span></code></a>; <em>requestHandler</em> defaults to
<a class="reference internal" href="#DocXMLRPCServer.DocXMLRPCRequestHandler" title="DocXMLRPCServer.DocXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCRequestHandler</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="DocXMLRPCServer.DocCGIXMLRPCRequestHandler">
<em class="property">class </em><code class="descclassname">DocXMLRPCServer.</code><code class="descname">DocCGIXMLRPCRequestHandler</code><a class="headerlink" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new instance to handle XML-RPC requests in a CGI environment.</p>
</dd></dl>

<dl class="class">
<dt id="DocXMLRPCServer.DocXMLRPCRequestHandler">
<em class="property">class </em><code class="descclassname">DocXMLRPCServer.</code><code class="descname">DocXMLRPCRequestHandler</code><a class="headerlink" href="#DocXMLRPCServer.DocXMLRPCRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new request handler instance. This request handler supports XML-RPC
POST requests, documentation GET requests, and modifies logging so that the
<em>logRequests</em> parameter to the <a class="reference internal" href="#DocXMLRPCServer.DocXMLRPCServer" title="DocXMLRPCServer.DocXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> constructor parameter is
honored.</p>
</dd></dl>

<div class="section" id="docxmlrpcserver-objects">
<span id="doc-xmlrpc-servers"></span><h2>20.25.1. DocXMLRPCServer Objects<a class="headerlink" href="#docxmlrpcserver-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#DocXMLRPCServer.DocXMLRPCServer" title="DocXMLRPCServer.DocXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> class is derived from
<a class="reference internal" href="simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer.SimpleXMLRPCServer</span></code></a> and provides a means of creating
self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as
XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style
HTML documentation. This allows a server to provide its own web-based
documentation.</p>
<dl class="method">
<dt id="DocXMLRPCServer.DocXMLRPCServer.set_server_title">
<code class="descclassname">DocXMLRPCServer.</code><code class="descname">set_server_title</code><span class="sig-paren">(</span><em>server_title</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocXMLRPCServer.set_server_title" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the title used in the generated HTML documentation. This title will be used
inside the HTML “title” element.</p>
</dd></dl>

<dl class="method">
<dt id="DocXMLRPCServer.DocXMLRPCServer.set_server_name">
<code class="descclassname">DocXMLRPCServer.</code><code class="descname">set_server_name</code><span class="sig-paren">(</span><em>server_name</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocXMLRPCServer.set_server_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the name used in the generated HTML documentation. This name will appear at
the top of the generated documentation inside a “h1” element.</p>
</dd></dl>

<dl class="method">
<dt id="DocXMLRPCServer.DocXMLRPCServer.set_server_documentation">
<code class="descclassname">DocXMLRPCServer.</code><code class="descname">set_server_documentation</code><span class="sig-paren">(</span><em>server_documentation</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocXMLRPCServer.set_server_documentation" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the description used in the generated HTML documentation. This description
will appear as a paragraph, below the server name, in the documentation.</p>
</dd></dl>

</div>
<div class="section" id="doccgixmlrpcrequesthandler">
<h2>20.25.2. DocCGIXMLRPCRequestHandler<a class="headerlink" href="#doccgixmlrpcrequesthandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler" title="DocXMLRPCServer.DocCGIXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocCGIXMLRPCRequestHandler</span></code></a> class is derived from
<a class="reference internal" href="simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler" title="SimpleXMLRPCServer.CGIXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer.CGIXMLRPCRequestHandler</span></code></a> and provides a means of
creating self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled
as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style
HTML documentation. This allows a server to provide its own web-based
documentation.</p>
<dl class="method">
<dt id="DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_title">
<code class="descclassname">DocCGIXMLRPCRequestHandler.</code><code class="descname">set_server_title</code><span class="sig-paren">(</span><em>server_title</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_title" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the title used in the generated HTML documentation. This title will be used
inside the HTML “title” element.</p>
</dd></dl>

<dl class="method">
<dt id="DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_name">
<code class="descclassname">DocCGIXMLRPCRequestHandler.</code><code class="descname">set_server_name</code><span class="sig-paren">(</span><em>server_name</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the name used in the generated HTML documentation. This name will appear at
the top of the generated documentation inside a “h1” element.</p>
</dd></dl>

<dl class="method">
<dt id="DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_documentation">
<code class="descclassname">DocCGIXMLRPCRequestHandler.</code><code class="descname">set_server_documentation</code><span class="sig-paren">(</span><em>server_documentation</em><span class="sig-paren">)</span><a class="headerlink" href="#DocXMLRPCServer.DocCGIXMLRPCRequestHandler.set_server_documentation" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the description used in the generated HTML documentation. This description
will appear as a paragraph, below the server name, in the documentation.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a><ul>
<li><a class="reference internal" href="#docxmlrpcserver-objects">20.25.1. DocXMLRPCServer Objects</a></li>
<li><a class="reference internal" href="#doccgixmlrpcrequesthandler">20.25.2. DocCGIXMLRPCRequestHandler</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="simplexmlrpcserver.html"
                        title="previous chapter">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mm.html"
                        title="next chapter">21. Multimedia Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/docxmlrpcserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mm.html" title="21. Multimedia Services"
             >next</a> |</li>
        <li class="right" >
          <a href="simplexmlrpcserver.html" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\s�u�<�<html/library/dumbdbm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.12. dumbdbm — Portable DBM implementation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases" href="sqlite3.html" />
    <link rel="prev" title="11.11. bsddb — Interface to Berkeley DB library" href="bsddb.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dumbdbm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sqlite3.html" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bsddb.html" title="11.11. bsddb — Interface to Berkeley DB library"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dumbdbm">
<span id="dumbdbm-portable-dbm-implementation"></span><h1>11.12. <a class="reference internal" href="#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a> — Portable DBM implementation<a class="headerlink" href="#module-dumbdbm" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.dumb</span></code> in Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<div class="admonition note" id="index-0">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a> module is intended as a last resort fallback for the
<a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a> module when no more robust module is available. The <a class="reference internal" href="#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a>
module is not written for speed and is not nearly as heavily used as the other
database modules.</p>
</div>
<p>The <a class="reference internal" href="#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a> module provides a persistent dictionary-like interface which
is written entirely in Python.  Unlike other modules such as <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a> and
<a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a>, no external library is required.  As with other persistent
mappings, the keys and values must always be strings.</p>
<p>The module defines the following:</p>
<dl class="exception">
<dt id="dumbdbm.error">
<em class="property">exception </em><code class="descclassname">dumbdbm.</code><code class="descname">error</code><a class="headerlink" href="#dumbdbm.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised on dumbdbm-specific errors, such as I/O errors.  <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is
raised for general mapping errors like specifying an incorrect key.</p>
</dd></dl>

<dl class="function">
<dt id="dumbdbm.open">
<code class="descclassname">dumbdbm.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dumbdbm.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a dumbdbm database and return a dumbdbm object.  The <em>filename</em> argument is
the basename of the database file (without any specific extensions).  When a
dumbdbm database is created, files with <code class="file docutils literal notranslate"><span class="pre">.dat</span></code> and <code class="file docutils literal notranslate"><span class="pre">.dir</span></code> extensions
are created.</p>
<p>The optional <em>flag</em> argument is currently ignored; the database is always opened
for update, and will be created if it does not exist.</p>
<p>The optional <em>mode</em> argument is the Unix mode of the file, used only when the
database has to be created.  It defaults to octal <code class="docutils literal notranslate"><span class="pre">0666</span></code> (and will be modified
by the prevailing umask).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>The <em>mode</em> argument was ignored in earlier versions.</p>
</div>
</dd></dl>

<p>In addition to the dictionary-like methods, <code class="docutils literal notranslate"><span class="pre">dumbdm</span></code> objects
provide the following method:</p>
<dl class="function">
<dt id="dumbdbm.close">
<code class="descclassname">dumbdbm.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dumbdbm.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the <code class="docutils literal notranslate"><span class="pre">dumbdm</span></code> database.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a></dt>
<dd>Generic interface to <code class="docutils literal notranslate"><span class="pre">dbm</span></code>-style databases.</dd>
<dt>Module <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a></dt>
<dd>Similar interface to the DBM/NDBM library.</dd>
<dt>Module <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a></dt>
<dd>Similar interface to the GNU GDBM library.</dd>
<dt>Module <a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a></dt>
<dd>Persistence module which stores non-string data.</dd>
<dt>Module <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a></dt>
<dd>Utility module used to determine the type of an existing database.</dd>
</dl>
</div>
<div class="section" id="dumbdbm-objects">
<span id="id1"></span><h2>11.12.1. Dumbdbm Objects<a class="headerlink" href="#dumbdbm-objects" title="Permalink to this headline">¶</a></h2>
<p>In addition to the methods provided by the <a class="reference internal" href="userdict.html#UserDict.DictMixin" title="UserDict.DictMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict.DictMixin</span></code></a> class,
<code class="xref py py-class docutils literal notranslate"><span class="pre">dumbdbm</span></code> objects provide the following methods.</p>
<dl class="method">
<dt id="dumbdbm.dumbdbm.sync">
<code class="descclassname">dumbdbm.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dumbdbm.dumbdbm.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>Synchronize the on-disk directory and data files.  This method is called by the
<a class="reference internal" href="#dumbdbm.dumbdbm.sync" title="dumbdbm.dumbdbm.sync"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sync()</span></code></a> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Shelve</span></code> objects.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a><ul>
<li><a class="reference internal" href="#dumbdbm-objects">11.12.1. Dumbdbm Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="bsddb.html"
                        title="previous chapter">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sqlite3.html"
                        title="next chapter">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dumbdbm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sqlite3.html" title="11.13. sqlite3 — DB-API 2.0 interface for SQLite databases"
             >next</a> |</li>
        <li class="right" >
          <a href="bsddb.html" title="11.11. bsddb — Interface to Berkeley DB library"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\t�y�Q'Q'html/library/dummy_thread.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.5. dummy_thread — Drop-in replacement for the thread module &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.6. multiprocessing — Process-based “threading” interface" href="multiprocessing.html" />
    <link rel="prev" title="16.4. dummy_threading — Drop-in replacement for the threading module" href="dummy_threading.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dummy_thread.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="16.6. multiprocessing — Process-based “threading” interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dummy_threading.html" title="16.4. dummy_threading — Drop-in replacement for the threading module"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dummy_thread">
<span id="dummy-thread-drop-in-replacement-for-the-thread-module"></span><h1>16.5. <a class="reference internal" href="#module-dummy_thread" title="dummy_thread: Drop-in replacement for the thread module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_thread</span></code></a> — Drop-in replacement for the <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module<a class="headerlink" href="#module-dummy_thread" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-dummy_thread" title="dummy_thread: Drop-in replacement for the thread module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_thread</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">_dummy_thread</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3; however, you should consider using the
high-lever <a class="reference internal" href="dummy_threading.html#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_threading</span></code></a> module instead.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/dummy_thread.py">Lib/dummy_thread.py</a></p>
<hr class="docutils" />
<p>This module provides a duplicate interface to the <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module.  It is
meant to be imported when the <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module is not provided on a
platform.</p>
<p>Suggested usage is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">thread</span> <span class="k">as</span> <span class="nn">_thread</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">dummy_thread</span> <span class="k">as</span> <span class="nn">_thread</span>
</pre></div>
</div>
<p>Be careful to not use this module where deadlock might occur from a thread
being created that blocks waiting for another thread to be created.  This  often
occurs with blocking I/O.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="dummy_threading.html"
                        title="previous chapter">16.4. <code class="docutils literal notranslate"><span class="pre">dummy_threading</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">threading</span></code> module</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="multiprocessing.html"
                        title="next chapter">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dummy_thread.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="16.6. multiprocessing — Process-based “threading” interface"
             >next</a> |</li>
        <li class="right" >
          <a href="dummy_threading.html" title="16.4. dummy_threading — Drop-in replacement for the threading module"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\>���"�"!html/library/dummy_threading.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.4. dummy_threading — Drop-in replacement for the threading module &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.5. dummy_thread — Drop-in replacement for the thread module" href="dummy_thread.html" />
    <link rel="prev" title="16.3. thread — Multiple threads of control" href="thread.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/dummy_threading.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dummy_thread.html" title="16.5. dummy_thread — Drop-in replacement for the thread module"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="thread.html" title="16.3. thread — Multiple threads of control"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-dummy_threading">
<span id="dummy-threading-drop-in-replacement-for-the-threading-module"></span><h1>16.4. <a class="reference internal" href="#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_threading</span></code></a> — Drop-in replacement for the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module<a class="headerlink" href="#module-dummy_threading" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/dummy_threading.py">Lib/dummy_threading.py</a></p>
<hr class="docutils" />
<p>This module provides a duplicate interface to the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.  It
is meant to be imported when the <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module is not provided on a
platform.</p>
<p>Suggested usage is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">threading</span> <span class="k">as</span> <span class="nn">_threading</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">dummy_threading</span> <span class="k">as</span> <span class="nn">_threading</span>
</pre></div>
</div>
<p>Be careful to not use this module where deadlock might occur from a thread
being created that blocks waiting for another thread to be created.  This  often
occurs with blocking I/O.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="thread.html"
                        title="previous chapter">16.3. <code class="docutils literal notranslate"><span class="pre">thread</span></code> — Multiple threads of control</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dummy_thread.html"
                        title="next chapter">16.5. <code class="docutils literal notranslate"><span class="pre">dummy_thread</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">thread</span></code> module</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/dummy_threading.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dummy_thread.html" title="16.5. dummy_thread — Drop-in replacement for the thread module"
             >next</a> |</li>
        <li class="right" >
          <a href="thread.html" title="16.3. thread — Multiple threads of control"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�p��d�d�html/library/easydialogs.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.5. EasyDialogs — Basic Macintosh dialogs &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.6. FrameWork — Interactive application framework" href="framework.html" />
    <link rel="prev" title="37.3. macostools — Convenience routines for file manipulation" href="macostools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/easydialogs.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="framework.html" title="37.6. FrameWork — Interactive application framework"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="macostools.html" title="37.3. macostools — Convenience routines for file manipulation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-EasyDialogs">
<span id="easydialogs-basic-macintosh-dialogs"></span><h1>37.5. <a class="reference internal" href="#module-EasyDialogs" title="EasyDialogs: Basic Macintosh dialogs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code></a> — Basic Macintosh dialogs<a class="headerlink" href="#module-EasyDialogs" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-EasyDialogs" title="EasyDialogs: Basic Macintosh dialogs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code></a> module contains some simple dialogs for the Macintosh.
The dialogs get launched in a separate application which appears in the dock and
must be clicked on for the dialogs be displayed.  All routines take an optional
resource ID parameter <em>id</em> with which one can override the <code class="xref py py-const docutils literal notranslate"><span class="pre">DLOG</span></code>
resource used for the dialog, provided that the dialog items correspond (both
type and item number) to those in the default <code class="xref py py-const docutils literal notranslate"><span class="pre">DLOG</span></code> resource. See source
code for details.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>The <a class="reference internal" href="#module-EasyDialogs" title="EasyDialogs: Basic Macintosh dialogs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="EasyDialogs.Message">
<code class="descclassname">EasyDialogs.</code><code class="descname">Message</code><span class="sig-paren">(</span><em>str</em><span class="optional">[</span>, <em>id</em><span class="optional">[</span>, <em>ok</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.Message" title="Permalink to this definition">¶</a></dt>
<dd><p>Displays a modal dialog with the message text <em>str</em>, which should be at most 255
characters long. The button text defaults to “OK”, but is set to the string
argument <em>ok</em> if the latter is supplied. Control is returned when the user
clicks the “OK” button.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskString">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskString</code><span class="sig-paren">(</span><em>prompt</em><span class="optional">[</span>, <em>default</em><span class="optional">[</span>, <em>id</em><span class="optional">[</span>, <em>ok</em><span class="optional">[</span>, <em>cancel</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskString" title="Permalink to this definition">¶</a></dt>
<dd><p>Asks the user to input a string value via a modal dialog. <em>prompt</em> is the prompt
message, and the optional <em>default</em> supplies the initial value for the string
(otherwise <code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code> is used). The text of the “OK” and “Cancel” buttons can be
changed with the <em>ok</em> and <em>cancel</em> arguments. All strings can be at most 255
bytes long. <a class="reference internal" href="#EasyDialogs.AskString" title="EasyDialogs.AskString"><code class="xref py py-func docutils literal notranslate"><span class="pre">AskString()</span></code></a> returns the string entered or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> in
case the user cancelled.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskPassword">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskPassword</code><span class="sig-paren">(</span><em>prompt</em><span class="optional">[</span>, <em>default</em><span class="optional">[</span>, <em>id</em><span class="optional">[</span>, <em>ok</em><span class="optional">[</span>, <em>cancel</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskPassword" title="Permalink to this definition">¶</a></dt>
<dd><p>Asks the user to input a string value via a modal dialog. Like
<a class="reference internal" href="#EasyDialogs.AskString" title="EasyDialogs.AskString"><code class="xref py py-func docutils literal notranslate"><span class="pre">AskString()</span></code></a>, but with the text shown as bullets. The arguments have the
same meaning as for <a class="reference internal" href="#EasyDialogs.AskString" title="EasyDialogs.AskString"><code class="xref py py-func docutils literal notranslate"><span class="pre">AskString()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskYesNoCancel">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskYesNoCancel</code><span class="sig-paren">(</span><em>question</em><span class="optional">[</span>, <em>default</em><span class="optional">[</span>, <em>yes</em><span class="optional">[</span>, <em>no</em><span class="optional">[</span>, <em>cancel</em><span class="optional">[</span>, <em>id</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskYesNoCancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Presents a dialog with prompt <em>question</em> and three buttons labelled “Yes”, “No”,
and “Cancel”. Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> for “Yes”, <code class="docutils literal notranslate"><span class="pre">0</span></code> for “No” and <code class="docutils literal notranslate"><span class="pre">-1</span></code> for “Cancel”.
The value of <em>default</em> (or <code class="docutils literal notranslate"><span class="pre">0</span></code> if <em>default</em> is not supplied) is returned when
the <kbd class="kbd docutils literal notranslate">RETURN</kbd> key is pressed. The text of the buttons can be changed with
the <em>yes</em>, <em>no</em>, and <em>cancel</em> arguments; to prevent a button from appearing,
supply <code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code> for the corresponding argument.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.ProgressBar">
<code class="descclassname">EasyDialogs.</code><code class="descname">ProgressBar</code><span class="sig-paren">(</span><span class="optional">[</span><em>title</em><span class="optional">[</span>, <em>maxval</em><span class="optional">[</span>, <em>label</em><span class="optional">[</span>, <em>id</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.ProgressBar" title="Permalink to this definition">¶</a></dt>
<dd><p>Displays a modeless progress-bar dialog. This is the constructor for the
<a class="reference internal" href="#EasyDialogs.ProgressBar" title="EasyDialogs.ProgressBar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProgressBar</span></code></a> class described below. <em>title</em> is the text string displayed
(default “Working…”), <em>maxval</em> is the value at which progress is complete
(default <code class="docutils literal notranslate"><span class="pre">0</span></code>, indicating that an indeterminate amount of work remains to be
done), and <em>label</em> is the text that is displayed above the progress bar itself.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.GetArgv">
<code class="descclassname">EasyDialogs.</code><code class="descname">GetArgv</code><span class="sig-paren">(</span><em>[optionlist[ commandlist[, addoldfile[, addnewfile[, addfolder[, id]]]]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.GetArgv" title="Permalink to this definition">¶</a></dt>
<dd><p>Displays a dialog which aids the user in constructing a command-line argument
list.  Returns the list in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> format, suitable for passing as an
argument to <a class="reference internal" href="getopt.html#getopt.getopt" title="getopt.getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt.getopt()</span></code></a>.  <em>addoldfile</em>, <em>addnewfile</em>, and <em>addfolder</em>
are boolean arguments.  When nonzero, they enable the user to insert into the
command line paths to an existing file, a (possibly) not-yet-existent file, and
a folder, respectively.  (Note: Option arguments must appear in the command line
before file and folder arguments in order to be recognized by
<a class="reference internal" href="getopt.html#getopt.getopt" title="getopt.getopt"><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt.getopt()</span></code></a>.)  Arguments containing spaces can be specified by
enclosing them within single or double quotes.  A <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> exception is
raised if the user presses the “Cancel” button.</p>
<p><em>optionlist</em> is a list that determines a popup menu from which the allowed
options are selected.  Its items can take one of two forms: <em>optstr</em> or
<code class="docutils literal notranslate"><span class="pre">(optstr,</span> <span class="pre">descr)</span></code>.  When present, <em>descr</em> is a short descriptive string that
is displayed in the dialog while this option is selected in the popup menu.  The
correspondence between <em>optstr</em>s and command-line arguments is:</p>
<table border="1" class="docutils">
<colgroup>
<col width="34%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"><em>optstr</em> format</th>
<th class="head">Command-line format</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span></code></td>
<td><code class="xref std std-option docutils literal notranslate"><span class="pre">-x</span></code> (short option)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x:</span></code> or <code class="docutils literal notranslate"><span class="pre">x=</span></code></td>
<td><code class="xref std std-option docutils literal notranslate"><span class="pre">-x</span></code> (short option with value)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">xyz</span></code></td>
<td><code class="xref std std-option docutils literal notranslate"><span class="pre">--xyz</span></code> (long option)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">xyz:</span></code> or <code class="docutils literal notranslate"><span class="pre">xyz=</span></code></td>
<td><code class="xref std std-option docutils literal notranslate"><span class="pre">--xyz</span></code> (long option with value)</td>
</tr>
</tbody>
</table>
<p><em>commandlist</em> is a list of items of the form <em>cmdstr</em> or <code class="docutils literal notranslate"><span class="pre">(cmdstr,</span> <span class="pre">descr)</span></code>,
where <em>descr</em> is as above.  The <em>cmdstr</em>s will appear in a popup menu.  When
chosen, the text of <em>cmdstr</em> will be appended to the command line as is, except
that a trailing <code class="docutils literal notranslate"><span class="pre">':'</span></code> or <code class="docutils literal notranslate"><span class="pre">'='</span></code> (if present) will be trimmed off.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskFileForOpen">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskFileForOpen</code><span class="sig-paren">(</span><em>[message] [, typeList] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, eventProc] [, previewProc] [, filterProc] [, wanted] </em><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskFileForOpen" title="Permalink to this definition">¶</a></dt>
<dd><p>Post a dialog asking the user for a file to open, and return the file selected
or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the user cancelled. <em>message</em> is a text message to display,
<em>typeList</em> is a list of 4-char filetypes allowable, <em>defaultLocation</em> is the
pathname, <code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">FSRef</span></code> of the folder to show initially,
<em>location</em> is the <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code> position on the screen where the dialog is shown,
<em>actionButtonLabel</em> is a string to show instead of “Open” in the OK button,
<em>cancelButtonLabel</em> is a string to show instead of “Cancel” in the cancel
button, <em>wanted</em> is the type of value wanted as a return: <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>,
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">FSRef</span></code> and subtypes thereof are
acceptable.</p>
<p id="index-0">For a description of the other arguments please see the Apple Navigation
Services documentation and the <a class="reference internal" href="#module-EasyDialogs" title="EasyDialogs: Basic Macintosh dialogs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code></a> source code.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskFileForSave">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskFileForSave</code><span class="sig-paren">(</span><em>[message] [, savedFileName] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, fileType] [, fileCreator] [, eventProc] [, wanted] </em><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskFileForSave" title="Permalink to this definition">¶</a></dt>
<dd><p>Post a dialog asking the user for a file to save to, and return the file
selected or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the user cancelled. <em>savedFileName</em> is the default
for the file name to save to (the return value). See <a class="reference internal" href="#EasyDialogs.AskFileForOpen" title="EasyDialogs.AskFileForOpen"><code class="xref py py-func docutils literal notranslate"><span class="pre">AskFileForOpen()</span></code></a> for
a description of the other arguments.</p>
</dd></dl>

<dl class="function">
<dt id="EasyDialogs.AskFolder">
<code class="descclassname">EasyDialogs.</code><code class="descname">AskFolder</code><span class="sig-paren">(</span><em>[message] [, defaultLocation] [, defaultOptionFlags] [, location] [, clientName] [, windowTitle] [, actionButtonLabel] [, cancelButtonLabel] [, preferenceKey] [, popupExtension] [, eventProc] [, filterProc] [, wanted] </em><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.AskFolder" title="Permalink to this definition">¶</a></dt>
<dd><p>Post a dialog asking the user to select a folder, and return the folder selected
or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the user cancelled. See <a class="reference internal" href="#EasyDialogs.AskFileForOpen" title="EasyDialogs.AskFileForOpen"><code class="xref py py-func docutils literal notranslate"><span class="pre">AskFileForOpen()</span></code></a> for a
description of the arguments.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://developer.apple.com/legacy/mac/library/#documentation/Carbon/Conceptual/NavServicesIntro/ns_intro_carb/ns_into_carb.html">Navigation Services Reference</a></dt>
<dd>Programmer’s reference documentation for the Navigation Services, a part of the
Carbon framework.</dd>
</dl>
</div>
<div class="section" id="progressbar-objects">
<span id="id1"></span><h2>37.5.1. ProgressBar Objects<a class="headerlink" href="#progressbar-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#EasyDialogs.ProgressBar" title="EasyDialogs.ProgressBar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProgressBar</span></code></a> objects provide support for modeless progress-bar dialogs.
Both determinate (thermometer style) and indeterminate (barber-pole style)
progress bars are supported.  The bar will be determinate if its maximum value
is greater than zero; otherwise it will be indeterminate.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Support for indeterminate-style progress bars was added.</p>
</div>
<p>The dialog is displayed immediately after creation. If the dialog’s “Cancel”
button is pressed, or if <kbd class="kbd docutils literal notranslate">Cmd-.</kbd> or <kbd class="kbd docutils literal notranslate">ESC</kbd> is typed, the dialog window
is hidden and <a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> is raised (but note that this response
does not occur until the progress bar is next updated, typically via a call to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">inc()</span></code> or <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a>).  Otherwise, the bar remains visible until the
<a class="reference internal" href="#EasyDialogs.ProgressBar" title="EasyDialogs.ProgressBar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProgressBar</span></code></a> object is discarded.</p>
<p><a class="reference internal" href="#EasyDialogs.ProgressBar" title="EasyDialogs.ProgressBar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProgressBar</span></code></a> objects possess the following attributes and methods:</p>
<dl class="attribute">
<dt id="EasyDialogs.ProgressBar.curval">
<code class="descclassname">ProgressBar.</code><code class="descname">curval</code><a class="headerlink" href="#EasyDialogs.ProgressBar.curval" title="Permalink to this definition">¶</a></dt>
<dd><p>The current value (of type integer or long integer) of the progress bar.  The
normal access methods coerce <a class="reference internal" href="#EasyDialogs.ProgressBar.curval" title="EasyDialogs.ProgressBar.curval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">curval</span></code></a> between <code class="docutils literal notranslate"><span class="pre">0</span></code> and <a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a>.
This attribute should not be altered directly.</p>
</dd></dl>

<dl class="attribute">
<dt id="EasyDialogs.ProgressBar.maxval">
<code class="descclassname">ProgressBar.</code><code class="descname">maxval</code><a class="headerlink" href="#EasyDialogs.ProgressBar.maxval" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum value (of type integer or long integer) of the progress bar; the
progress bar (thermometer style) is full when <a class="reference internal" href="#EasyDialogs.ProgressBar.curval" title="EasyDialogs.ProgressBar.curval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">curval</span></code></a> equals
<a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a>.  If <a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the bar will be indeterminate
(barber-pole).  This attribute should not be altered directly.</p>
</dd></dl>

<dl class="method">
<dt id="EasyDialogs.ProgressBar.title">
<code class="descclassname">ProgressBar.</code><code class="descname">title</code><span class="sig-paren">(</span><span class="optional">[</span><em>newstr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.ProgressBar.title" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the text in the title bar of the progress dialog to <em>newstr</em>.</p>
</dd></dl>

<dl class="method">
<dt id="EasyDialogs.ProgressBar.label">
<code class="descclassname">ProgressBar.</code><code class="descname">label</code><span class="sig-paren">(</span><span class="optional">[</span><em>newstr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.ProgressBar.label" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the text in the progress box of the progress dialog to <em>newstr</em>.</p>
</dd></dl>

<dl class="method">
<dt id="EasyDialogs.ProgressBar.set">
<code class="descclassname">ProgressBar.</code><code class="descname">set</code><span class="sig-paren">(</span><em>value</em><span class="optional">[</span>, <em>max</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.ProgressBar.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the progress bar’s <a class="reference internal" href="#EasyDialogs.ProgressBar.curval" title="EasyDialogs.ProgressBar.curval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">curval</span></code></a> to <em>value</em>, and also <a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a> to
<em>max</em> if the latter is provided.  <em>value</em> is first coerced between 0 and
<a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a>.  The thermometer bar is updated to reflect the changes,
including a change from indeterminate to determinate or vice versa.</p>
</dd></dl>

<dl class="method">
<dt id="EasyDialogs.ProgressBar.inc">
<code class="descclassname">ProgressBar.</code><code class="descname">inc</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#EasyDialogs.ProgressBar.inc" title="Permalink to this definition">¶</a></dt>
<dd><p>Increments the progress bar’s <a class="reference internal" href="#EasyDialogs.ProgressBar.curval" title="EasyDialogs.ProgressBar.curval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">curval</span></code></a> by <em>n</em>, or by <code class="docutils literal notranslate"><span class="pre">1</span></code> if <em>n</em> is not
provided.  (Note that <em>n</em> may be negative, in which case the effect is a
decrement.)  The progress bar is updated to reflect the change.  If the bar is
indeterminate, this causes one “spin” of the barber pole.  The resulting
<a class="reference internal" href="#EasyDialogs.ProgressBar.curval" title="EasyDialogs.ProgressBar.curval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">curval</span></code></a> is coerced between 0 and <a class="reference internal" href="#EasyDialogs.ProgressBar.maxval" title="EasyDialogs.ProgressBar.maxval"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxval</span></code></a> if incrementing causes it
to fall outside this range.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a><ul>
<li><a class="reference internal" href="#progressbar-objects">37.5.1. ProgressBar Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="macostools.html"
                        title="previous chapter">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="framework.html"
                        title="next chapter">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/easydialogs.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="framework.html" title="37.6. FrameWork — Interactive application framework"
             >next</a> |</li>
        <li class="right" >
          <a href="macostools.html" title="37.3. macostools — Convenience routines for file manipulation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Xe�@�@� html/library/email-examples.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.11. email: Examples &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.2. json — JSON encoder and decoder" href="json.html" />
    <link rel="prev" title="18.1.10. email.iterators: Iterators" href="email.iterators.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email-examples.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="json.html" title="18.2. json — JSON encoder and decoder"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="18.1.10. email.iterators: Iterators"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="email-examples">
<span id="id1"></span><h1>18.1.11. <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>: Examples<a class="headerlink" href="#email-examples" title="Permalink to this headline">¶</a></h1>
<p>Here are a few examples of how to use the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package to read, write,
and send simple email messages, as well as more complex MIME messages.</p>
<p>First, let’s see how to create and send a simple text message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import smtplib for the actual sending function</span>
<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="c1"># Import the email modules we&#39;ll need</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="k">import</span> <span class="n">MIMEText</span>

<span class="c1"># Open a plain text file for reading.  For this example, assume that</span>
<span class="c1"># the text file contains only ASCII characters.</span>
<span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">textfile</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
<span class="c1"># Create a text/plain message</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
<span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="c1"># me == the sender&#39;s email address</span>
<span class="c1"># you == the recipient&#39;s email address</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;The contents of </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">textfile</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">you</span>

<span class="c1"># Send the message via our own SMTP server, but don&#39;t include the</span>
<span class="c1"># envelope header.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="p">[</span><span class="n">you</span><span class="p">],</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>And parsing RFC822 headers can easily be done by the parse(filename) or
parsestr(message_as_string) methods of the Parser() class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import the email modules we&#39;ll need</span>
<span class="kn">from</span> <span class="nn">email.parser</span> <span class="k">import</span> <span class="n">Parser</span>

<span class="c1">#  If the e-mail headers are in a file, uncomment this line:</span>
<span class="c1">#headers = Parser().parse(open(messagefile, &#39;r&#39;))</span>

<span class="c1">#  Or for parsing headers in a string, use:</span>
<span class="n">headers</span> <span class="o">=</span> <span class="n">Parser</span><span class="p">()</span><span class="o">.</span><span class="n">parsestr</span><span class="p">(</span><span class="s1">&#39;From: &lt;user@example.com&gt;</span><span class="se">\n</span><span class="s1">&#39;</span>
        <span class="s1">&#39;To: &lt;someone_else@example.com&gt;</span><span class="se">\n</span><span class="s1">&#39;</span>
        <span class="s1">&#39;Subject: Test message</span><span class="se">\n</span><span class="s1">&#39;</span>
        <span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span>
        <span class="s1">&#39;Body would go here</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="c1">#  Now the header items can be accessed as a dictionary:</span>
<span class="nb">print</span> <span class="s1">&#39;To: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">headers</span><span class="p">[</span><span class="s1">&#39;to&#39;</span><span class="p">]</span>
<span class="nb">print</span> <span class="s1">&#39;From: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">headers</span><span class="p">[</span><span class="s1">&#39;from&#39;</span><span class="p">]</span>
<span class="nb">print</span> <span class="s1">&#39;Subject: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">headers</span><span class="p">[</span><span class="s1">&#39;subject&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>Here’s an example of how to send a MIME message containing a bunch of family
pictures that may be residing in a directory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import smtplib for the actual sending function</span>
<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="c1"># Here are the email package modules we&#39;ll need</span>
<span class="kn">from</span> <span class="nn">email.mime.image</span> <span class="k">import</span> <span class="n">MIMEImage</span>
<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="k">import</span> <span class="n">MIMEMultipart</span>

<span class="n">COMMASPACE</span> <span class="o">=</span> <span class="s1">&#39;, &#39;</span>

<span class="c1"># Create the container (outer) email message.</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">()</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Our family reunion&#39;</span>
<span class="c1"># me == the sender&#39;s email address</span>
<span class="c1"># family = the list of all recipients&#39; email addresses</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">COMMASPACE</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">family</span><span class="p">)</span>
<span class="n">msg</span><span class="o">.</span><span class="n">preamble</span> <span class="o">=</span> <span class="s1">&#39;Our family reunion&#39;</span>

<span class="c1"># Assume we know that the image files are all in PNG format</span>
<span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">pngfiles</span><span class="p">:</span>
    <span class="c1"># Open the files in binary mode.  Let the MIMEImage class automatically</span>
    <span class="c1"># guess the specific image type.</span>
    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
    <span class="n">img</span> <span class="o">=</span> <span class="n">MIMEImage</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
    <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">img</span><span class="p">)</span>

<span class="c1"># Send the email via our own SMTP server.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="n">family</span><span class="p">,</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>Here’s an example of how to send the entire contents of a directory as an email
message: <a class="footnote-reference" href="#id4" id="id2">[1]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>

<span class="sd">&quot;&quot;&quot;Send the contents of a directory as a MIME message.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">smtplib</span>
<span class="c1"># For guessing MIME type based on file name extension</span>
<span class="kn">import</span> <span class="nn">mimetypes</span>

<span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>

<span class="kn">from</span> <span class="nn">email</span> <span class="k">import</span> <span class="n">encoders</span>
<span class="kn">from</span> <span class="nn">email.message</span> <span class="k">import</span> <span class="n">Message</span>
<span class="kn">from</span> <span class="nn">email.mime.audio</span> <span class="k">import</span> <span class="n">MIMEAudio</span>
<span class="kn">from</span> <span class="nn">email.mime.base</span> <span class="k">import</span> <span class="n">MIMEBase</span>
<span class="kn">from</span> <span class="nn">email.mime.image</span> <span class="k">import</span> <span class="n">MIMEImage</span>
<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="k">import</span> <span class="n">MIMEMultipart</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="k">import</span> <span class="n">MIMEText</span>

<span class="n">COMMASPACE</span> <span class="o">=</span> <span class="s1">&#39;, &#39;</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">Send the contents of a directory as a MIME message.</span>

<span class="s2">Usage: %prog [options]</span>

<span class="s2">Unless the -o option is given, the email is sent by forwarding to your local</span>
<span class="s2">SMTP server, which then does the normal delivery process.  Your local machine</span>
<span class="s2">must be running an SMTP server.</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-d&#39;</span><span class="p">,</span> <span class="s1">&#39;--directory&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s2">&quot;&quot;&quot;Mail the contents of the specified directory,</span>
<span class="s2">                      otherwise use the current directory.  Only the regular</span>
<span class="s2">                      files in the directory are sent, and we don&#39;t recurse to</span>
<span class="s2">                      subdirectories.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-o&#39;</span><span class="p">,</span> <span class="s1">&#39;--output&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;FILE&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s2">&quot;&quot;&quot;Print the composed message to FILE instead of</span>
<span class="s2">                      sending the message to the SMTP server.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-s&#39;</span><span class="p">,</span> <span class="s1">&#39;--sender&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;SENDER&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;The value of the From: header (required)&#39;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-r&#39;</span><span class="p">,</span> <span class="s1">&#39;--recipient&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;append&#39;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;RECIPIENT&#39;</span><span class="p">,</span>
                      <span class="n">default</span><span class="o">=</span><span class="p">[],</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;recipients&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s1">&#39;A To: header value (at least one required)&#39;</span><span class="p">)</span>
    <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">sender</span> <span class="ow">or</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">directory</span> <span class="o">=</span> <span class="n">opts</span><span class="o">.</span><span class="n">directory</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">directory</span><span class="p">:</span>
        <span class="n">directory</span> <span class="o">=</span> <span class="s1">&#39;.&#39;</span>
    <span class="c1"># Create the enclosing (outer) message</span>
    <span class="n">outer</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">()</span>
    <span class="n">outer</span><span class="p">[</span><span class="s1">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Contents of directory </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">abspath</span><span class="p">(</span><span class="n">directory</span><span class="p">)</span>
    <span class="n">outer</span><span class="p">[</span><span class="s1">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">COMMASPACE</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">)</span>
    <span class="n">outer</span><span class="p">[</span><span class="s1">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">opts</span><span class="o">.</span><span class="n">sender</span>
    <span class="n">outer</span><span class="o">.</span><span class="n">preamble</span> <span class="o">=</span> <span class="s1">&#39;You will not see this in a MIME-aware mail reader.</span><span class="se">\n</span><span class="s1">&#39;</span>

    <span class="k">for</span> <span class="n">filename</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">directory</span><span class="p">):</span>
        <span class="n">path</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">directory</span><span class="p">,</span> <span class="n">filename</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">path</span><span class="p">):</span>
            <span class="k">continue</span>
        <span class="c1"># Guess the content type based on the file&#39;s extension.  Encoding</span>
        <span class="c1"># will be ignored, although we should check for simple things like</span>
        <span class="c1"># gzip&#39;d or compressed files.</span>
        <span class="n">ctype</span><span class="p">,</span> <span class="n">encoding</span> <span class="o">=</span> <span class="n">mimetypes</span><span class="o">.</span><span class="n">guess_type</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">ctype</span> <span class="ow">is</span> <span class="kc">None</span> <span class="ow">or</span> <span class="n">encoding</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="c1"># No guess could be made, or the file is encoded (compressed), so</span>
            <span class="c1"># use a generic bag-of-bits type.</span>
            <span class="n">ctype</span> <span class="o">=</span> <span class="s1">&#39;application/octet-stream&#39;</span>
        <span class="n">maintype</span><span class="p">,</span> <span class="n">subtype</span> <span class="o">=</span> <span class="n">ctype</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s1">&#39;text&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
            <span class="c1"># Note: we should handle calculating the charset</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s1">&#39;image&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEImage</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">maintype</span> <span class="o">==</span> <span class="s1">&#39;audio&#39;</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEAudio</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">_subtype</span><span class="o">=</span><span class="n">subtype</span><span class="p">)</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
            <span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEBase</span><span class="p">(</span><span class="n">maintype</span><span class="p">,</span> <span class="n">subtype</span><span class="p">)</span>
            <span class="n">msg</span><span class="o">.</span><span class="n">set_payload</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
            <span class="c1"># Encode the payload using Base64</span>
            <span class="n">encoders</span><span class="o">.</span><span class="n">encode_base64</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
        <span class="c1"># Set the filename parameter</span>
        <span class="n">msg</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;Content-Disposition&#39;</span><span class="p">,</span> <span class="s1">&#39;attachment&#39;</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="n">filename</span><span class="p">)</span>
        <span class="n">outer</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
    <span class="c1"># Now send or store the message</span>
    <span class="n">composed</span> <span class="o">=</span> <span class="n">outer</span><span class="o">.</span><span class="n">as_string</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">opts</span><span class="o">.</span><span class="n">output</span><span class="p">:</span>
        <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">output</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">composed</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
        <span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">sender</span><span class="p">,</span> <span class="n">opts</span><span class="o">.</span><span class="n">recipients</span><span class="p">,</span> <span class="n">composed</span><span class="p">)</span>
        <span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Here’s an example of how to unpack a MIME message like the one
above, into a directory of files:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>

<span class="sd">&quot;&quot;&quot;Unpack a MIME message into a directory of files.&quot;&quot;&quot;</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">email</span>
<span class="kn">import</span> <span class="nn">errno</span>
<span class="kn">import</span> <span class="nn">mimetypes</span>

<span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">Unpack a MIME message into a directory of files.</span>

<span class="s2">Usage: %prog [options] msgfile</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-d&#39;</span><span class="p">,</span> <span class="s1">&#39;--directory&#39;</span><span class="p">,</span>
                      <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s2">&quot;&quot;&quot;Unpack the MIME message into the named</span>
<span class="s2">                      directory, which will be created if it doesn&#39;t already</span>
<span class="s2">                      exist.&quot;&quot;&quot;</span><span class="p">)</span>
    <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">msgfile</span> <span class="o">=</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
        <span class="c1"># Ignore directory exists error</span>
        <span class="k">if</span> <span class="n">e</span><span class="o">.</span><span class="n">errno</span> <span class="o">!=</span> <span class="n">errno</span><span class="o">.</span><span class="n">EEXIST</span><span class="p">:</span>
            <span class="k">raise</span>

    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">msgfile</span><span class="p">)</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_file</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
    <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="n">counter</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="k">for</span> <span class="n">part</span> <span class="ow">in</span> <span class="n">msg</span><span class="o">.</span><span class="n">walk</span><span class="p">():</span>
        <span class="c1"># multipart/* are just containers</span>
        <span class="k">if</span> <span class="n">part</span><span class="o">.</span><span class="n">get_content_maintype</span><span class="p">()</span> <span class="o">==</span> <span class="s1">&#39;multipart&#39;</span><span class="p">:</span>
            <span class="k">continue</span>
        <span class="c1"># Applications should really sanitize the given filename so that an</span>
        <span class="c1"># email message can&#39;t be used to overwrite important files</span>
        <span class="n">filename</span> <span class="o">=</span> <span class="n">part</span><span class="o">.</span><span class="n">get_filename</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">filename</span><span class="p">:</span>
            <span class="n">ext</span> <span class="o">=</span> <span class="n">mimetypes</span><span class="o">.</span><span class="n">guess_extension</span><span class="p">(</span><span class="n">part</span><span class="o">.</span><span class="n">get_content_type</span><span class="p">())</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">ext</span><span class="p">:</span>
                <span class="c1"># Use a generic bag-of-bits extension</span>
                <span class="n">ext</span> <span class="o">=</span> <span class="s1">&#39;.bin&#39;</span>
            <span class="n">filename</span> <span class="o">=</span> <span class="s1">&#39;part-</span><span class="si">%03d%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">counter</span><span class="p">,</span> <span class="n">ext</span><span class="p">)</span>
        <span class="n">counter</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">opts</span><span class="o">.</span><span class="n">directory</span><span class="p">,</span> <span class="n">filename</span><span class="p">),</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">part</span><span class="o">.</span><span class="n">get_payload</span><span class="p">(</span><span class="n">decode</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
        <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Here’s an example of how to create an HTML message with an alternative plain
text version: <a class="footnote-reference" href="#id5" id="id3">[2]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>

<span class="kn">import</span> <span class="nn">smtplib</span>

<span class="kn">from</span> <span class="nn">email.mime.multipart</span> <span class="k">import</span> <span class="n">MIMEMultipart</span>
<span class="kn">from</span> <span class="nn">email.mime.text</span> <span class="k">import</span> <span class="n">MIMEText</span>

<span class="c1"># me == my email address</span>
<span class="c1"># you == recipient&#39;s email address</span>
<span class="n">me</span> <span class="o">=</span> <span class="s2">&quot;my@email.com&quot;</span>
<span class="n">you</span> <span class="o">=</span> <span class="s2">&quot;your@email.com&quot;</span>

<span class="c1"># Create message container - the correct MIME type is multipart/alternative.</span>
<span class="n">msg</span> <span class="o">=</span> <span class="n">MIMEMultipart</span><span class="p">(</span><span class="s1">&#39;alternative&#39;</span><span class="p">)</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;Link&quot;</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;From&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">me</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;To&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">you</span>

<span class="c1"># Create the body of the message (a plain-text and an HTML version).</span>
<span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;Hi!</span><span class="se">\n</span><span class="s2">How are you?</span><span class="se">\n</span><span class="s2">Here is the link you wanted:</span><span class="se">\n</span><span class="s2">https://www.python.org&quot;</span>
<span class="n">html</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">&lt;html&gt;</span>
<span class="s2">  &lt;head&gt;&lt;/head&gt;</span>
<span class="s2">  &lt;body&gt;</span>
<span class="s2">    &lt;p&gt;Hi!&lt;br&gt;</span>
<span class="s2">       How are you?&lt;br&gt;</span>
<span class="s2">       Here is the &lt;a href=&quot;https://www.python.org&quot;&gt;link&lt;/a&gt; you wanted.</span>
<span class="s2">    &lt;/p&gt;</span>
<span class="s2">  &lt;/body&gt;</span>
<span class="s2">&lt;/html&gt;</span>
<span class="s2">&quot;&quot;&quot;</span>

<span class="c1"># Record the MIME types of both parts - text/plain and text/html.</span>
<span class="n">part1</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="s1">&#39;plain&#39;</span><span class="p">)</span>
<span class="n">part2</span> <span class="o">=</span> <span class="n">MIMEText</span><span class="p">(</span><span class="n">html</span><span class="p">,</span> <span class="s1">&#39;html&#39;</span><span class="p">)</span>

<span class="c1"># Attach parts into message container.</span>
<span class="c1"># According to RFC 2046, the last part of a multipart message, in this case</span>
<span class="c1"># the HTML message, is best and preferred.</span>
<span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">part1</span><span class="p">)</span>
<span class="n">msg</span><span class="o">.</span><span class="n">attach</span><span class="p">(</span><span class="n">part2</span><span class="p">)</span>

<span class="c1"># Send the message via local SMTP server.</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="c1"># sendmail function takes 3 arguments: sender&#39;s address, recipient&#39;s address</span>
<span class="c1"># and message to send - here it is sent as one string.</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">me</span><span class="p">,</span> <span class="n">you</span><span class="p">,</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">())</span>
<span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[1]</a></td><td>Thanks to Matthew Dixon Cowles for the original inspiration and examples.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[2]</a></td><td>Contributed by Martin Matejek.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.iterators.html"
                        title="previous chapter">18.1.10. <code class="docutils literal notranslate"><span class="pre">email.iterators</span></code>: Iterators</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="json.html"
                        title="next chapter">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email-examples.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="json.html" title="18.2. json — JSON encoder and decoder"
             >next</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="18.1.10. email.iterators: Iterators"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\K�?�r�rhtml/library/email.charset.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.6. email.charset: Representing character sets &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.7. email.encoders: Encoders" href="email.encoders.html" />
    <link rel="prev" title="18.1.5. email.header: Internationalized headers" href="email.header.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.charset.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.encoders.html" title="18.1.7. email.encoders: Encoders"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.header.html" title="18.1.5. email.header: Internationalized headers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.charset">
<span id="email-charset-representing-character-sets"></span><h1>18.1.6. <a class="reference internal" href="#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a>: Representing character sets<a class="headerlink" href="#module-email.charset" title="Permalink to this headline">¶</a></h1>
<p>This module provides a class <a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> for representing character sets
and character set conversions in email messages, as well as a character set
registry and several convenience methods for manipulating this registry.
Instances of <a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> are used in several other modules within the
<a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package.</p>
<p>Import this class from the <a class="reference internal" href="#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a> module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
<dl class="class">
<dt id="email.charset.Charset">
<em class="property">class </em><code class="descclassname">email.charset.</code><code class="descname">Charset</code><span class="sig-paren">(</span><span class="optional">[</span><em>input_charset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Map character sets to their email properties.</p>
<p>This class provides information about the requirements imposed on email for a
specific character set.  It also provides convenience routines for converting
between character sets, given the availability of the applicable codecs.  Given
a character set, it will do its best to provide information on how to use that
character set in an email message in an RFC-compliant way.</p>
<p>Certain character sets must be encoded with quoted-printable or base64 when used
in email headers or bodies.  Certain character sets must be converted outright,
and are not allowed in email.</p>
<p>Optional <em>input_charset</em> is as described below; it is always coerced to lower
case.  After being alias normalized it is also used as a lookup into the
registry of character sets to find out the header encoding, body encoding, and
output conversion codec to be used for the character set.  For example, if
<em>input_charset</em> is <code class="docutils literal notranslate"><span class="pre">iso-8859-1</span></code>, then headers and bodies will be encoded using
quoted-printable and no output conversion codec is necessary.  If
<em>input_charset</em> is <code class="docutils literal notranslate"><span class="pre">euc-jp</span></code>, then headers will be encoded with base64, bodies
will not be encoded, but output text will be converted from the <code class="docutils literal notranslate"><span class="pre">euc-jp</span></code>
character set to the <code class="docutils literal notranslate"><span class="pre">iso-2022-jp</span></code> character set.</p>
<p><a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instances have the following data attributes:</p>
<dl class="attribute">
<dt id="email.charset.Charset.input_charset">
<code class="descname">input_charset</code><a class="headerlink" href="#email.charset.Charset.input_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>The initial character set specified.  Common aliases are converted to
their <em>official</em> email names (e.g. <code class="docutils literal notranslate"><span class="pre">latin_1</span></code> is converted to
<code class="docutils literal notranslate"><span class="pre">iso-8859-1</span></code>).  Defaults to 7-bit <code class="docutils literal notranslate"><span class="pre">us-ascii</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.charset.Charset.header_encoding">
<code class="descname">header_encoding</code><a class="headerlink" href="#email.charset.Charset.header_encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>If the character set must be encoded before it can be used in an email
header, this attribute will be set to <code class="docutils literal notranslate"><span class="pre">Charset.QP</span></code> (for
quoted-printable), <code class="docutils literal notranslate"><span class="pre">Charset.BASE64</span></code> (for base64 encoding), or
<code class="docutils literal notranslate"><span class="pre">Charset.SHORTEST</span></code> for the shortest of QP or BASE64 encoding. Otherwise,
it will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.charset.Charset.body_encoding">
<code class="descname">body_encoding</code><a class="headerlink" href="#email.charset.Charset.body_encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <em>header_encoding</em>, but describes the encoding for the mail
message’s body, which indeed may be different than the header encoding.
<code class="docutils literal notranslate"><span class="pre">Charset.SHORTEST</span></code> is not allowed for <em>body_encoding</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.charset.Charset.output_charset">
<code class="descname">output_charset</code><a class="headerlink" href="#email.charset.Charset.output_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Some character sets must be converted before they can be used in email headers
or bodies.  If the <em>input_charset</em> is one of them, this attribute will
contain the name of the character set output will be converted to.  Otherwise, it will
be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.charset.Charset.input_codec">
<code class="descname">input_codec</code><a class="headerlink" href="#email.charset.Charset.input_codec" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the Python codec used to convert the <em>input_charset</em> to
Unicode.  If no conversion codec is necessary, this attribute will be
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.charset.Charset.output_codec">
<code class="descname">output_codec</code><a class="headerlink" href="#email.charset.Charset.output_codec" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the Python codec used to convert Unicode to the
<em>output_charset</em>.  If no conversion codec is necessary, this attribute
will have the same value as the <em>input_codec</em>.</p>
</dd></dl>

<p><a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instances also have the following methods:</p>
<dl class="method">
<dt id="email.charset.Charset.get_body_encoding">
<code class="descname">get_body_encoding</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.get_body_encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the content transfer encoding used for body encoding.</p>
<p>This is either the string <code class="docutils literal notranslate"><span class="pre">quoted-printable</span></code> or <code class="docutils literal notranslate"><span class="pre">base64</span></code> depending on
the encoding used, or it is a function, in which case you should call the
function with a single argument, the Message object being encoded.  The
function should then set the <em class="mailheader">Content-Transfer-Encoding</em>
header itself to whatever is appropriate.</p>
<p>Returns the string <code class="docutils literal notranslate"><span class="pre">quoted-printable</span></code> if <em>body_encoding</em> is <code class="docutils literal notranslate"><span class="pre">QP</span></code>,
returns the string <code class="docutils literal notranslate"><span class="pre">base64</span></code> if <em>body_encoding</em> is <code class="docutils literal notranslate"><span class="pre">BASE64</span></code>, and
returns the string <code class="docutils literal notranslate"><span class="pre">7bit</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.convert">
<code class="descname">convert</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.convert" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the string <em>s</em> from the <em>input_codec</em> to the <em>output_codec</em>.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.to_splittable">
<code class="descname">to_splittable</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.to_splittable" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a possibly multibyte string to a safely splittable format. <em>s</em> is
the string to split.</p>
<p>Uses the <em>input_codec</em> to try and convert the string to Unicode, so it can
be safely split on character boundaries (even for multibyte characters).</p>
<p>Returns the string as-is if it isn’t known how to convert <em>s</em> to Unicode
with the <em>input_charset</em>.</p>
<p>Characters that could not be converted to Unicode will be replaced with
the Unicode replacement character <code class="docutils literal notranslate"><span class="pre">'U+FFFD'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.from_splittable">
<code class="descname">from_splittable</code><span class="sig-paren">(</span><em>ustr</em><span class="optional">[</span>, <em>to_output</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.from_splittable" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a splittable string back into an encoded string.  <em>ustr</em> is a
Unicode string to “unsplit”.</p>
<p>This method uses the proper codec to try and convert the string from
Unicode back into an encoded format.  Return the string as-is if it is not
Unicode, or if it could not be converted from Unicode.</p>
<p>Characters that could not be converted from Unicode will be replaced with
an appropriate character (usually <code class="docutils literal notranslate"><span class="pre">'?'</span></code>).</p>
<p>If <em>to_output</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), uses <em>output_codec</em> to convert
to an encoded format.  If <em>to_output</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, it uses <em>input_codec</em>.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.get_output_charset">
<code class="descname">get_output_charset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.get_output_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the output character set.</p>
<p>This is the <em>output_charset</em> attribute if that is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, otherwise
it is <em>input_charset</em>.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.encoded_header_len">
<code class="descname">encoded_header_len</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.encoded_header_len" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the length of the encoded header string, properly calculating for
quoted-printable or base64 encoding.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.header_encode">
<code class="descname">header_encode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>convert</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.header_encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Header-encode the string <em>s</em>.</p>
<p>If <em>convert</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the string will be converted from the input
charset to the output charset automatically.  This is not useful for
multibyte character sets, which have line length issues (multibyte
characters must be split on a character, not a byte boundary); use the
higher-level <a class="reference internal" href="email.header.html#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class to deal with these issues
(see <a class="reference internal" href="email.header.html#module-email.header" title="email.header: Representing non-ASCII headers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.header</span></code></a>).  <em>convert</em> defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>The type of encoding (base64 or quoted-printable) will be based on the
<em>header_encoding</em> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.body_encode">
<code class="descname">body_encode</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>convert</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.body_encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Body-encode the string <em>s</em>.</p>
<p>If <em>convert</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), the string will be converted from
the input charset to output charset automatically. Unlike
<a class="reference internal" href="#email.charset.Charset.header_encode" title="email.charset.Charset.header_encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">header_encode()</span></code></a>, there are no issues with byte boundaries and
multibyte charsets in email bodies, so this is usually pretty safe.</p>
<p>The type of encoding (base64 or quoted-printable) will be based on the
<em>body_encoding</em> attribute.</p>
</dd></dl>

<p>The <a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> class also provides a number of methods to support
standard operations and built-in functions.</p>
<dl class="method">
<dt id="email.charset.Charset.__str__">
<code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <em>input_charset</em> as a string coerced to lower
case. <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> is an alias for <a class="reference internal" href="#email.charset.Charset.__str__" title="email.charset.Charset.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.__eq__">
<code class="descname">__eq__</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.__eq__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method allows you to compare two <a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instances for
equality.</p>
</dd></dl>

<dl class="method">
<dt id="email.charset.Charset.__ne__">
<code class="descname">__ne__</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.Charset.__ne__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method allows you to compare two <a class="reference internal" href="#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instances for
inequality.</p>
</dd></dl>

</dd></dl>

<p>The <a class="reference internal" href="#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a> module also provides the following functions for adding
new entries to the global character set, alias, and codec registries:</p>
<dl class="function">
<dt id="email.charset.add_charset">
<code class="descclassname">email.charset.</code><code class="descname">add_charset</code><span class="sig-paren">(</span><em>charset</em><span class="optional">[</span>, <em>header_enc</em><span class="optional">[</span>, <em>body_enc</em><span class="optional">[</span>, <em>output_charset</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.add_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Add character properties to the global registry.</p>
<p><em>charset</em> is the input character set, and must be the canonical name of a
character set.</p>
<p>Optional <em>header_enc</em> and <em>body_enc</em> is either <code class="docutils literal notranslate"><span class="pre">Charset.QP</span></code> for
quoted-printable, <code class="docutils literal notranslate"><span class="pre">Charset.BASE64</span></code> for base64 encoding,
<code class="docutils literal notranslate"><span class="pre">Charset.SHORTEST</span></code> for the shortest of quoted-printable or base64 encoding,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> for no encoding.  <code class="docutils literal notranslate"><span class="pre">SHORTEST</span></code> is only valid for
<em>header_enc</em>. The default is <code class="docutils literal notranslate"><span class="pre">None</span></code> for no encoding.</p>
<p>Optional <em>output_charset</em> is the character set that the output should be in.
Conversions will proceed from input charset, to Unicode, to the output charset
when the method <a class="reference internal" href="#email.charset.Charset.convert" title="email.charset.Charset.convert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Charset.convert()</span></code></a> is called.  The default is to output in
the same character set as the input.</p>
<p>Both <em>input_charset</em> and <em>output_charset</em> must have Unicode codec entries in the
module’s character set-to-codec mapping; use <a class="reference internal" href="#email.charset.add_codec" title="email.charset.add_codec"><code class="xref py py-func docutils literal notranslate"><span class="pre">add_codec()</span></code></a> to add codecs the
module does not know about.  See the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module’s documentation for
more information.</p>
<p>The global character set registry is kept in the module global dictionary
<code class="docutils literal notranslate"><span class="pre">CHARSETS</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="email.charset.add_alias">
<code class="descclassname">email.charset.</code><code class="descname">add_alias</code><span class="sig-paren">(</span><em>alias</em>, <em>canonical</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.add_alias" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a character set alias.  <em>alias</em> is the alias name, e.g. <code class="docutils literal notranslate"><span class="pre">latin-1</span></code>.
<em>canonical</em> is the character set’s canonical name, e.g. <code class="docutils literal notranslate"><span class="pre">iso-8859-1</span></code>.</p>
<p>The global charset alias registry is kept in the module global dictionary
<code class="docutils literal notranslate"><span class="pre">ALIASES</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="email.charset.add_codec">
<code class="descclassname">email.charset.</code><code class="descname">add_codec</code><span class="sig-paren">(</span><em>charset</em>, <em>codecname</em><span class="sig-paren">)</span><a class="headerlink" href="#email.charset.add_codec" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a codec that map characters in the given character set to and from Unicode.</p>
<p><em>charset</em> is the canonical name of a character set. <em>codecname</em> is the name of a
Python codec, as appropriate for the second argument to the <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a>
built-in, or to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method of a Unicode string.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.header.html"
                        title="previous chapter">18.1.5. <code class="docutils literal notranslate"><span class="pre">email.header</span></code>: Internationalized headers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.encoders.html"
                        title="next chapter">18.1.7. <code class="docutils literal notranslate"><span class="pre">email.encoders</span></code>: Encoders</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.charset.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.encoders.html" title="18.1.7. email.encoders: Encoders"
             >next</a> |</li>
        <li class="right" >
          <a href="email.header.html" title="18.1.5. email.header: Internationalized headers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\U&A\/2/2 html/library/email.encoders.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.7. email.encoders: Encoders &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.8. email.errors: Exception and Defect classes" href="email.errors.html" />
    <link rel="prev" title="18.1.6. email.charset: Representing character sets" href="email.charset.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.encoders.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.errors.html" title="18.1.8. email.errors: Exception and Defect classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.charset.html" title="18.1.6. email.charset: Representing character sets"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.encoders">
<span id="email-encoders-encoders"></span><h1>18.1.7. <a class="reference internal" href="#module-email.encoders" title="email.encoders: Encoders for email message payloads."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.encoders</span></code></a>: Encoders<a class="headerlink" href="#module-email.encoders" title="Permalink to this headline">¶</a></h1>
<p>When creating <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects from scratch, you often
need to encode the payloads for transport through compliant mail servers. This
is especially true for <em class="mimetype">image/*</em> and <em class="mimetype">text/*</em> type messages
containing binary data.</p>
<p>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package provides some convenient encodings in its
<code class="xref py py-mod docutils literal notranslate"><span class="pre">encoders</span></code> module.  These encoders are actually used by the
<a class="reference internal" href="email.mime.html#email.mime.audio.MIMEAudio" title="email.mime.audio.MIMEAudio"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEAudio</span></code></a> and <a class="reference internal" href="email.mime.html#email.mime.image.MIMEImage" title="email.mime.image.MIMEImage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEImage</span></code></a>
class constructors to provide default encodings.  All encoder functions take
exactly one argument, the message object to encode.  They usually extract the
payload, encode it, and reset the payload to this newly encoded value.  They
should also set the <em class="mailheader">Content-Transfer-Encoding</em> header as appropriate.</p>
<p>Note that these functions are not meaningful for a multipart message.  They
must be applied to individual subparts instead, and will raise a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if passed a message whose type is multipart.</p>
<p>Here are the encoding functions provided:</p>
<dl class="function">
<dt id="email.encoders.encode_quopri">
<code class="descclassname">email.encoders.</code><code class="descname">encode_quopri</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#email.encoders.encode_quopri" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes the payload into quoted-printable form and sets the
<em class="mailheader">Content-Transfer-Encoding</em> header to <code class="docutils literal notranslate"><span class="pre">quoted-printable</span></code> <a class="footnote-reference" href="#id2" id="id1">[1]</a>.
This is a good encoding to use when most of your payload is normal printable
data, but contains a few unprintable characters.</p>
</dd></dl>

<dl class="function">
<dt id="email.encoders.encode_base64">
<code class="descclassname">email.encoders.</code><code class="descname">encode_base64</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#email.encoders.encode_base64" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes the payload into base64 form and sets the
<em class="mailheader">Content-Transfer-Encoding</em> header to <code class="docutils literal notranslate"><span class="pre">base64</span></code>.  This is a good
encoding to use when most of your payload is unprintable data since it is a more
compact form than quoted-printable.  The drawback of base64 encoding is that it
renders the text non-human readable.</p>
</dd></dl>

<dl class="function">
<dt id="email.encoders.encode_7or8bit">
<code class="descclassname">email.encoders.</code><code class="descname">encode_7or8bit</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#email.encoders.encode_7or8bit" title="Permalink to this definition">¶</a></dt>
<dd><p>This doesn’t actually modify the message’s payload, but it does set the
<em class="mailheader">Content-Transfer-Encoding</em> header to either <code class="docutils literal notranslate"><span class="pre">7bit</span></code> or <code class="docutils literal notranslate"><span class="pre">8bit</span></code> as
appropriate, based on the payload data.</p>
</dd></dl>

<dl class="function">
<dt id="email.encoders.encode_noop">
<code class="descclassname">email.encoders.</code><code class="descname">encode_noop</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#email.encoders.encode_noop" title="Permalink to this definition">¶</a></dt>
<dd><p>This does nothing; it doesn’t even set the
<em class="mailheader">Content-Transfer-Encoding</em> header.</p>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Note that encoding with <a class="reference internal" href="#email.encoders.encode_quopri" title="email.encoders.encode_quopri"><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode_quopri()</span></code></a> also encodes all tabs and space
characters in the data.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.charset.html"
                        title="previous chapter">18.1.6. <code class="docutils literal notranslate"><span class="pre">email.charset</span></code>: Representing character sets</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.errors.html"
                        title="next chapter">18.1.8. <code class="docutils literal notranslate"><span class="pre">email.errors</span></code>: Exception and Defect classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.encoders.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.errors.html" title="18.1.8. email.errors: Exception and Defect classes"
             >next</a> |</li>
        <li class="right" >
          <a href="email.charset.html" title="18.1.6. email.charset: Representing character sets"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1�j� F Fhtml/library/email.errors.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.8. email.errors: Exception and Defect classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.9. email.utils: Miscellaneous utilities" href="email.utils.html" />
    <link rel="prev" title="18.1.7. email.encoders: Encoders" href="email.encoders.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.errors.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.utils.html" title="18.1.9. email.utils: Miscellaneous utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.encoders.html" title="18.1.7. email.encoders: Encoders"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.errors">
<span id="email-errors-exception-and-defect-classes"></span><h1>18.1.8. <a class="reference internal" href="#module-email.errors" title="email.errors: The exception classes used by the email package."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.errors</span></code></a>: Exception and Defect classes<a class="headerlink" href="#module-email.errors" title="Permalink to this headline">¶</a></h1>
<p>The following exception classes are defined in the <a class="reference internal" href="#module-email.errors" title="email.errors: The exception classes used by the email package."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.errors</span></code></a> module:</p>
<dl class="exception">
<dt id="email.errors.MessageError">
<em class="property">exception </em><code class="descclassname">email.errors.</code><code class="descname">MessageError</code><a class="headerlink" href="#email.errors.MessageError" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base class for all exceptions that the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package can
raise.  It is derived from the standard <a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class and defines no
additional methods.</p>
</dd></dl>

<dl class="exception">
<dt id="email.errors.MessageParseError">
<em class="property">exception </em><code class="descclassname">email.errors.</code><code class="descname">MessageParseError</code><a class="headerlink" href="#email.errors.MessageParseError" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base class for exceptions raised by the <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a>
class.  It is derived from <a class="reference internal" href="#email.errors.MessageError" title="email.errors.MessageError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MessageError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="email.errors.HeaderParseError">
<em class="property">exception </em><code class="descclassname">email.errors.</code><code class="descname">HeaderParseError</code><a class="headerlink" href="#email.errors.HeaderParseError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised under some error conditions when parsing the <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> headers of a
message, this class is derived from <a class="reference internal" href="#email.errors.MessageParseError" title="email.errors.MessageParseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MessageParseError</span></code></a>. It can be raised
from the <a class="reference internal" href="email.parser.html#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Parser.parse</span></code></a> or
<a class="reference internal" href="email.parser.html#email.parser.Parser.parsestr" title="email.parser.Parser.parsestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Parser.parsestr</span></code></a> methods.</p>
<p>Situations where it can be raised include finding an envelope header after the
first <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> header of the message, finding a continuation line before the
first <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> header is found, or finding a line in the headers which is
neither a header or a continuation line.</p>
</dd></dl>

<dl class="exception">
<dt id="email.errors.BoundaryError">
<em class="property">exception </em><code class="descclassname">email.errors.</code><code class="descname">BoundaryError</code><a class="headerlink" href="#email.errors.BoundaryError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised under some error conditions when parsing the <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> headers of a
message, this class is derived from <a class="reference internal" href="#email.errors.MessageParseError" title="email.errors.MessageParseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MessageParseError</span></code></a>. It can be raised
from the <a class="reference internal" href="email.parser.html#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Parser.parse</span></code></a> or
<a class="reference internal" href="email.parser.html#email.parser.Parser.parsestr" title="email.parser.Parser.parsestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Parser.parsestr</span></code></a> methods.</p>
<p>Situations where it can be raised include not being able to find the starting or
terminating boundary in a <em class="mimetype">multipart/*</em> message when strict parsing
is used.</p>
</dd></dl>

<dl class="exception">
<dt id="email.errors.MultipartConversionError">
<em class="property">exception </em><code class="descclassname">email.errors.</code><code class="descname">MultipartConversionError</code><a class="headerlink" href="#email.errors.MultipartConversionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a payload is added to a <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> object
using <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_payload()</span></code>, but the payload is already a scalar and the
message’s <em class="mailheader">Content-Type</em> main type is not either
<em class="mimetype">multipart</em> or missing.  <a class="reference internal" href="#email.errors.MultipartConversionError" title="email.errors.MultipartConversionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipartConversionError</span></code></a> multiply
inherits from <a class="reference internal" href="#email.errors.MessageError" title="email.errors.MessageError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MessageError</span></code></a> and the built-in <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<p>Since <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.add_payload()</span></code> is deprecated, this exception is rarely
raised in practice.  However the exception may also be raised if the
<a class="reference internal" href="email.message.html#email.message.Message.attach" title="email.message.Message.attach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">attach()</span></code></a>
method is called on an instance of a class derived from
<a class="reference internal" href="email.mime.html#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a> (e.g.
<a class="reference internal" href="email.mime.html#email.mime.image.MIMEImage" title="email.mime.image.MIMEImage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEImage</span></code></a>).</p>
</dd></dl>

<p>Here’s the list of the defects that the <a class="reference internal" href="email.parser.html#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>
can find while parsing messages.  Note that the defects are added to the message
where the problem was found, so for example, if a message nested inside a
<em class="mimetype">multipart/alternative</em> had a malformed header, that nested message
object would have a defect, but the containing messages would not.</p>
<p>All defect classes are subclassed from <code class="xref py py-class docutils literal notranslate"><span class="pre">email.errors.MessageDefect</span></code>, but
this class is <em>not</em> an exception!</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>All the defect classes were added.</p>
</div>
<ul class="simple">
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">NoBoundaryInMultipartDefect</span></code> – A message claimed to be a multipart,
but had no <em class="mimetype">boundary</em> parameter.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">StartBoundaryNotFoundDefect</span></code> – The start boundary claimed in the
<em class="mailheader">Content-Type</em> header was never found.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">FirstHeaderLineIsContinuationDefect</span></code> – The message had a continuation
line as its first header line.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">MisplacedEnvelopeHeaderDefect</span></code> - A “Unix From” header was found in the
middle of a header block.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">MalformedHeaderDefect</span></code> – A header was found that was missing a colon,
or was otherwise malformed.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">MultipartInvariantViolationDefect</span></code> – A message claimed to be a
<em class="mimetype">multipart</em>, but no subparts were found.  Note that when a message
has this defect, its <a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> method may
return false even though its content type claims to be <em class="mimetype">multipart</em>.</li>
</ul>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.encoders.html"
                        title="previous chapter">18.1.7. <code class="docutils literal notranslate"><span class="pre">email.encoders</span></code>: Encoders</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.utils.html"
                        title="next chapter">18.1.9. <code class="docutils literal notranslate"><span class="pre">email.utils</span></code>: Miscellaneous utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.errors.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.utils.html" title="18.1.9. email.utils: Miscellaneous utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="email.encoders.html" title="18.1.7. email.encoders: Encoders"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\(eZeZ!html/library/email.generator.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.3. email.generator: Generating MIME documents &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.4. email.mime: Creating email and MIME objects from scratch" href="email.mime.html" />
    <link rel="prev" title="18.1.2. email.parser: Parsing email messages" href="email.parser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.generator.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.mime.html" title="18.1.4. email.mime: Creating email and MIME objects from scratch"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.parser.html" title="18.1.2. email.parser: Parsing email messages"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.generator">
<span id="email-generator-generating-mime-documents"></span><h1>18.1.3. <a class="reference internal" href="#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a>: Generating MIME documents<a class="headerlink" href="#module-email.generator" title="Permalink to this headline">¶</a></h1>
<p>One of the most common tasks is to generate the flat text of the email message
represented by a message object structure.  You will need to do this if you want
to send your message via the <a class="reference internal" href="smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module or the <a class="reference internal" href="nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a> module,
or print the message on the console.  Taking a message object structure and
producing a flat text document is the job of the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class.</p>
<p>Again, as with the <a class="reference internal" href="email.parser.html#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a> module, you aren’t limited to the
functionality of the bundled generator; you could write one from scratch
yourself.  However the bundled generator knows how to generate most email in a
standards-compliant way, should handle MIME and non-MIME email messages just
fine, and is designed so that the transformation from flat text, to a message
structure via the <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class, and back to flat text,
is idempotent (the input is identical to the output) <a class="footnote-reference" href="#id2" id="id1">[1]</a>.  On the other hand,
using the Generator on a <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructed by program
may result in changes to the <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> object as defaults
are filled in.</p>
<p>Here are the public methods of the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class, imported from the
<a class="reference internal" href="#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> module:</p>
<dl class="class">
<dt id="email.generator.Generator">
<em class="property">class </em><code class="descclassname">email.generator.</code><code class="descname">Generator</code><span class="sig-paren">(</span><em>outfp</em><span class="optional">[</span>, <em>mangle_from_</em><span class="optional">[</span>, <em>maxheaderlen</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator" title="Permalink to this definition">¶</a></dt>
<dd><p>The constructor for the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class takes a file-like object called
<em>outfp</em> for an argument.  <em>outfp</em> must support the <a class="reference internal" href="#email.generator.Generator.write" title="email.generator.Generator.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method and be
usable as the output file in a Python extended print statement.</p>
<p>Optional <em>mangle_from_</em> is a flag that, when <code class="docutils literal notranslate"><span class="pre">True</span></code>, puts a <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> character in
front of any line in the body that starts exactly as <code class="docutils literal notranslate"><span class="pre">From</span></code>, i.e. <code class="docutils literal notranslate"><span class="pre">From</span></code>
followed by a space at the beginning of the line.  This is the only guaranteed
portable way to avoid having such lines be mistaken for a Unix mailbox format
envelope header separator (see <a class="reference external" href="https://www.jwz.org/doc/content-length.html">WHY THE CONTENT-LENGTH FORMAT IS BAD</a> for details).  <em>mangle_from_</em>
defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>, but you might want to set this to <code class="docutils literal notranslate"><span class="pre">False</span></code> if you are not
writing Unix mailbox format files.</p>
<p>Optional <em>maxheaderlen</em> specifies the longest length for a non-continued header.
When a header line is longer than <em>maxheaderlen</em> (in characters, with tabs
expanded to 8 spaces), the header will be split as defined in the
<a class="reference internal" href="email.header.html#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class.  Set to zero to disable header wrapping.
The default is 78, as recommended (but not required) by <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>.</p>
<p>The other public <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> methods are:</p>
<dl class="method">
<dt id="email.generator.Generator.flatten">
<code class="descname">flatten</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>unixfrom</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.flatten" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the textual representation of the message object structure rooted at
<em>msg</em> to the output file specified when the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> instance
was created.  Subparts are visited depth-first and the resulting text will
be properly MIME encoded.</p>
<p>Optional <em>unixfrom</em> is a flag that forces the printing of the envelope
header delimiter before the first <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> header of the root message
object.  If the root object has no envelope header, a standard one is
crafted.  By default, this is set to <code class="docutils literal notranslate"><span class="pre">False</span></code> to inhibit the printing of
the envelope delimiter.</p>
<p>Note that for subparts, no envelope header is ever printed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.generator.Generator.clone">
<code class="descname">clone</code><span class="sig-paren">(</span><em>fp</em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.clone" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an independent clone of this <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> instance with the
exact same options.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.generator.Generator.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.Generator.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the string <em>s</em> to the underlying file object, i.e. <em>outfp</em> passed to
<a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a>’s constructor.  This provides just enough file-like API
for <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> instances to be used in extended print statements.</p>
</dd></dl>

</dd></dl>

<p>As a convenience, see the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.as_string()</span></code> and
<code class="docutils literal notranslate"><span class="pre">str(aMessage)</span></code>, a.k.a. <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.__str__()</span></code>, which simplify the generation
of a formatted string representation of a message object.  For more detail, see
<a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a>.</p>
<p>The <a class="reference internal" href="#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> module also provides a derived class, called
<a class="reference internal" href="#email.generator.DecodedGenerator" title="email.generator.DecodedGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecodedGenerator</span></code></a> which is like the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> base class,
except that non-<em class="mimetype">text</em> parts are substituted with a format string
representing the part.</p>
<dl class="class">
<dt id="email.generator.DecodedGenerator">
<em class="property">class </em><code class="descclassname">email.generator.</code><code class="descname">DecodedGenerator</code><span class="sig-paren">(</span><em>outfp</em><span class="optional">[</span>, <em>mangle_from_</em><span class="optional">[</span>, <em>maxheaderlen</em><span class="optional">[</span>, <em>fmt</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.generator.DecodedGenerator" title="Permalink to this definition">¶</a></dt>
<dd><p>This class, derived from <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> walks through all the subparts of a
message.  If the subpart is of main type <em class="mimetype">text</em>, then it prints the
decoded payload of the subpart. Optional <em>_mangle_from_</em> and <em>maxheaderlen</em> are
as with the <a class="reference internal" href="#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> base class.</p>
<p>If the subpart is not of main type <em class="mimetype">text</em>, optional <em>fmt</em> is a format
string that is used instead of the message payload. <em>fmt</em> is expanded with the
following keywords, <code class="docutils literal notranslate"><span class="pre">%(keyword)s</span></code> format:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">type</span></code> – Full MIME type of the non-<em class="mimetype">text</em> part</li>
<li><code class="docutils literal notranslate"><span class="pre">maintype</span></code> – Main MIME type of the non-<em class="mimetype">text</em> part</li>
<li><code class="docutils literal notranslate"><span class="pre">subtype</span></code> – Sub-MIME type of the non-<em class="mimetype">text</em> part</li>
<li><code class="docutils literal notranslate"><span class="pre">filename</span></code> – Filename of the non-<em class="mimetype">text</em> part</li>
<li><code class="docutils literal notranslate"><span class="pre">description</span></code> – Description associated with the non-<em class="mimetype">text</em> part</li>
<li><code class="docutils literal notranslate"><span class="pre">encoding</span></code> – Content transfer encoding of the non-<em class="mimetype">text</em> part</li>
</ul>
<p>The default value for <em>fmt</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">Non</span><span class="o">-</span><span class="n">text</span> <span class="p">(</span><span class="o">%</span><span class="p">(</span><span class="nb">type</span><span class="p">)</span><span class="n">s</span><span class="p">)</span> <span class="n">part</span> <span class="n">of</span> <span class="n">message</span> <span class="n">omitted</span><span class="p">,</span> <span class="n">filename</span> <span class="o">%</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span><span class="n">s</span><span class="p">]</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The previously deprecated method <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> was removed.</p>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This statement assumes that you use the appropriate setting for the
<code class="docutils literal notranslate"><span class="pre">unixfrom</span></code> argument, and that you set maxheaderlen=0 (which will
preserve whatever the input line lengths were).  It is also not strictly
true, since in many cases runs of whitespace in headers are collapsed
into single blanks.  The latter is a bug that will eventually be fixed.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.parser.html"
                        title="previous chapter">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.mime.html"
                        title="next chapter">18.1.4. <code class="docutils literal notranslate"><span class="pre">email.mime</span></code>: Creating email and MIME objects from scratch</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.generator.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.mime.html" title="18.1.4. email.mime: Creating email and MIME objects from scratch"
             >next</a> |</li>
        <li class="right" >
          <a href="email.parser.html" title="18.1.2. email.parser: Parsing email messages"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\,��޴q�qhtml/library/email.header.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.5. email.header: Internationalized headers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.6. email.charset: Representing character sets" href="email.charset.html" />
    <link rel="prev" title="18.1.4. email.mime: Creating email and MIME objects from scratch" href="email.mime.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.header.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.charset.html" title="18.1.6. email.charset: Representing character sets"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.mime.html" title="18.1.4. email.mime: Creating email and MIME objects from scratch"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.header">
<span id="email-header-internationalized-headers"></span><h1>18.1.5. <a class="reference internal" href="#module-email.header" title="email.header: Representing non-ASCII headers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.header</span></code></a>: Internationalized headers<a class="headerlink" href="#module-email.header" title="Permalink to this headline">¶</a></h1>
<p><span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> is the base standard that describes the format of email messages.
It derives from the older <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> standard which came into widespread use at
a time when most email was composed of ASCII characters only.  <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> is a
specification written assuming email contains only 7-bit ASCII characters.</p>
<p>Of course, as email has been deployed worldwide, it has become
internationalized, such that language specific character sets can now be used in
email messages.  The base standard still requires email messages to be
transferred using only 7-bit ASCII characters, so a slew of RFCs have been
written describing how to encode email containing non-ASCII characters into
<span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-compliant format. These RFCs include <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a>, <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2046.html"><strong>RFC 2046</strong></a>,
<span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2047.html"><strong>RFC 2047</strong></a>, and <span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>. The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package supports these standards
in its <a class="reference internal" href="#module-email.header" title="email.header: Representing non-ASCII headers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.header</span></code></a> and <a class="reference internal" href="email.charset.html#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a> modules.</p>
<p>If you want to include non-ASCII characters in your email headers, say in the
<em class="mailheader">Subject</em> or <em class="mailheader">To</em> fields, you should use the
<a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class and assign the field in the <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>
object to an instance of <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> instead of using a string for the header
value.  Import the <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class from the <a class="reference internal" href="#module-email.header" title="email.header: Representing non-ASCII headers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.header</span></code></a> module.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">email.message</span> <span class="k">import</span> <span class="n">Message</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">email.header</span> <span class="k">import</span> <span class="n">Header</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">msg</span> <span class="o">=</span> <span class="n">Message</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h</span> <span class="o">=</span> <span class="n">Header</span><span class="p">(</span><span class="s1">&#39;p</span><span class="se">\xf6</span><span class="s1">stal&#39;</span><span class="p">,</span> <span class="s1">&#39;iso-8859-1&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">msg</span><span class="p">[</span><span class="s1">&#39;Subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">h</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">msg</span><span class="o">.</span><span class="n">as_string</span><span class="p">()</span>
<span class="go">Subject: =?iso-8859-1?q?p=F6stal?=</span>
</pre></div>
</div>
<p>Notice here how we wanted the <em class="mailheader">Subject</em> field to contain a non-ASCII
character?  We did this by creating a <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> instance and passing in
the character set that the byte string was encoded in.  When the subsequent
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance was flattened, the <em class="mailheader">Subject</em>
field was properly <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2047.html"><strong>RFC 2047</strong></a> encoded.  MIME-aware mail readers would show this
header using the embedded ISO-8859-1 character.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
<p>Here is the <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class description:</p>
<dl class="class">
<dt id="email.header.Header">
<em class="property">class </em><code class="descclassname">email.header.</code><code class="descname">Header</code><span class="sig-paren">(</span><span class="optional">[</span><em>s</em><span class="optional">[</span>, <em>charset</em><span class="optional">[</span>, <em>maxlinelen</em><span class="optional">[</span>, <em>header_name</em><span class="optional">[</span>, <em>continuation_ws</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a MIME-compliant header that can contain strings in different character
sets.</p>
<p>Optional <em>s</em> is the initial header value.  If <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), the
initial header value is not set.  You can later append to the header with
<a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> method calls.  <em>s</em> may be a byte string or a Unicode string, but
see the <a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> documentation for semantics.</p>
<p>Optional <em>charset</em> serves two purposes: it has the same meaning as the <em>charset</em>
argument to the <a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> method.  It also sets the default character set
for all subsequent <a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> calls that omit the <em>charset</em> argument.  If
<em>charset</em> is not provided in the constructor (the default), the <code class="docutils literal notranslate"><span class="pre">us-ascii</span></code>
character set is used both as <em>s</em>’s initial charset and as the default for
subsequent <a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> calls.</p>
<p>The maximum line length can be specified explicitly via <em>maxlinelen</em>.  For
splitting the first line to a shorter value (to account for the field header
which isn’t included in <em>s</em>, e.g. <em class="mailheader">Subject</em>) pass in the name of the
field in <em>header_name</em>.  The default <em>maxlinelen</em> is 76, and the default value
for <em>header_name</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning it is not taken into account for the
first line of a long, split header.</p>
<p>Optional <em>continuation_ws</em> must be <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-compliant folding whitespace,
and is usually either a space or a hard tab character. This character will be
prepended to continuation lines.  <em>continuation_ws</em> defaults to a single
space character (” “).</p>
<p>Optional <em>errors</em> is passed straight through to the <a class="reference internal" href="#email.header.Header.append" title="email.header.Header.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> method.</p>
<dl class="method">
<dt id="email.header.Header.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>charset</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Append the string <em>s</em> to the MIME header.</p>
<p>Optional <em>charset</em>, if given, should be a <a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a>
instance (see <a class="reference internal" href="email.charset.html#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a>) or the name of a character set, which
will be converted to a <a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instance.  A value
of <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) means that the <em>charset</em> given in the constructor
is used.</p>
<p><em>s</em> may be a byte string or a Unicode string.  If it is a byte string
(i.e.  <code class="docutils literal notranslate"><span class="pre">isinstance(s,</span> <span class="pre">str)</span></code> is true), then <em>charset</em> is the encoding of
that byte string, and a <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> will be raised if the string
cannot be decoded with that character set.</p>
<p>If <em>s</em> is a Unicode string, then <em>charset</em> is a hint specifying the
character set of the characters in the string.  In this case, when
producing an <span class="target" id="index-10"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-compliant header using <span class="target" id="index-11"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2047.html"><strong>RFC 2047</strong></a> rules, the
Unicode string will be encoded using the following charsets in order:
<code class="docutils literal notranslate"><span class="pre">us-ascii</span></code>, the <em>charset</em> hint, <code class="docutils literal notranslate"><span class="pre">utf-8</span></code>.  The first character set to
not provoke a <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> is used.</p>
<p>Optional <em>errors</em> is passed through to any <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> or
<code class="xref py py-meth docutils literal notranslate"><span class="pre">unicode.encode()</span></code> call, and defaults to “strict”.</p>
</dd></dl>

<dl class="method">
<dt id="email.header.Header.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><span class="optional">[</span><em>splitchars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode a message header into an RFC-compliant format, possibly wrapping
long lines and encapsulating non-ASCII parts in base64 or quoted-printable
encodings.  Optional <em>splitchars</em> is a string containing characters to
split long ASCII lines on, in rough support of <span class="target" id="index-12"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>’s <em>highest
level syntactic breaks</em>.  This doesn’t affect <span class="target" id="index-13"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2047.html"><strong>RFC 2047</strong></a> encoded lines.</p>
</dd></dl>

<p>The <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> class also provides a number of methods to support
standard operators and built-in functions.</p>
<dl class="method">
<dt id="email.header.Header.__str__">
<code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>A synonym for <a class="reference internal" href="#email.header.Header.encode" title="email.header.Header.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Header.encode()</span></code></a>.  Useful for <code class="docutils literal notranslate"><span class="pre">str(aHeader)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="email.header.Header.__unicode__">
<code class="descname">__unicode__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.__unicode__" title="Permalink to this definition">¶</a></dt>
<dd><p>A helper for the built-in <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> function.  Returns the header as
a Unicode string.</p>
</dd></dl>

<dl class="method">
<dt id="email.header.Header.__eq__">
<code class="descname">__eq__</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.__eq__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method allows you to compare two <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> instances for
equality.</p>
</dd></dl>

<dl class="method">
<dt id="email.header.Header.__ne__">
<code class="descname">__ne__</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#email.header.Header.__ne__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method allows you to compare two <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> instances for
inequality.</p>
</dd></dl>

</dd></dl>

<p>The <a class="reference internal" href="#module-email.header" title="email.header: Representing non-ASCII headers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.header</span></code></a> module also provides the following convenient functions.</p>
<dl class="function">
<dt id="email.header.decode_header">
<code class="descclassname">email.header.</code><code class="descname">decode_header</code><span class="sig-paren">(</span><em>header</em><span class="sig-paren">)</span><a class="headerlink" href="#email.header.decode_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a message header value without converting the character set. The header
value is in <em>header</em>.</p>
<p>This function returns a list of <code class="docutils literal notranslate"><span class="pre">(decoded_string,</span> <span class="pre">charset)</span></code> pairs containing
each of the decoded parts of the header.  <em>charset</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> for non-encoded
parts of the header, otherwise a lower case string containing the name of the
character set specified in the encoded string.</p>
<p>Here’s an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">email.header</span> <span class="k">import</span> <span class="n">decode_header</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decode_header</span><span class="p">(</span><span class="s1">&#39;=?iso-8859-1?q?p=F6stal?=&#39;</span><span class="p">)</span>
<span class="go">[(&#39;p\xf6stal&#39;, &#39;iso-8859-1&#39;)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="email.header.make_header">
<code class="descclassname">email.header.</code><code class="descname">make_header</code><span class="sig-paren">(</span><em>decoded_seq</em><span class="optional">[</span>, <em>maxlinelen</em><span class="optional">[</span>, <em>header_name</em><span class="optional">[</span>, <em>continuation_ws</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.header.make_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> instance from a sequence of pairs as returned by
<a class="reference internal" href="#email.header.decode_header" title="email.header.decode_header"><code class="xref py py-func docutils literal notranslate"><span class="pre">decode_header()</span></code></a>.</p>
<p><a class="reference internal" href="#email.header.decode_header" title="email.header.decode_header"><code class="xref py py-func docutils literal notranslate"><span class="pre">decode_header()</span></code></a> takes a header value string and returns a sequence of
pairs of the format <code class="docutils literal notranslate"><span class="pre">(decoded_string,</span> <span class="pre">charset)</span></code> where <em>charset</em> is the name of
the character set.</p>
<p>This function takes one of those sequence of pairs and returns a <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a>
instance.  Optional <em>maxlinelen</em>, <em>header_name</em>, and <em>continuation_ws</em> are as in
the <a class="reference internal" href="#email.header.Header" title="email.header.Header"><code class="xref py py-class docutils literal notranslate"><span class="pre">Header</span></code></a> constructor.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.mime.html"
                        title="previous chapter">18.1.4. <code class="docutils literal notranslate"><span class="pre">email.mime</span></code>: Creating email and MIME objects from scratch</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.charset.html"
                        title="next chapter">18.1.6. <code class="docutils literal notranslate"><span class="pre">email.charset</span></code>: Representing character sets</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.header.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.charset.html" title="18.1.6. email.charset: Representing character sets"
             >next</a> |</li>
        <li class="right" >
          <a href="email.mime.html" title="18.1.4. email.mime: Creating email and MIME objects from scratch"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\K|����html/library/email.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1. email — An email and MIME handling package &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.1. email.message: Representing an email message" href="email.message.html" />
    <link rel="prev" title="18. Internet Data Handling" href="netdata.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.message.html" title="18.1.1. email.message: Representing an email message"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="netdata.html" title="18. Internet Data Handling"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email">
<span id="email-an-email-and-mime-handling-package"></span><h1>18.1. <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> — An email and MIME handling package<a class="headerlink" href="#module-email" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>The <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is a library for managing email messages, including
MIME and other <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-based message documents.  It subsumes most of the
functionality in several older standard modules such as <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a>,
<a class="reference internal" href="mimetools.html#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a>, <a class="reference internal" href="multifile.html#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a>, and other non-standard packages such as
<code class="xref py py-mod docutils literal notranslate"><span class="pre">mimecntl</span></code>.  It is specifically <em>not</em> designed to do any sending of email
messages to SMTP (<span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2821.html"><strong>RFC 2821</strong></a>), NNTP, or other servers; those are functions of
modules such as <a class="reference internal" href="smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> and <a class="reference internal" href="nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a>. The <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package
attempts to be as RFC-compliant as possible, supporting in addition to
<span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>, such MIME-related RFCs as <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a>, <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2046.html"><strong>RFC 2046</strong></a>, <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2047.html"><strong>RFC 2047</strong></a>,
and <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>.</p>
<p>The primary distinguishing feature of the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is that it splits
the parsing and generating of email messages from the internal <em>object model</em>
representation of email.  Applications using the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package deal
primarily with objects; you can add sub-objects to messages, remove sub-objects
from messages, completely re-arrange the contents, etc.  There is a separate
parser and a separate generator which handles the transformation from flat text
to the object model, and then back to flat text again.  There are also handy
subclasses for some common MIME object types, and a few miscellaneous utilities
that help with such common tasks as extracting and parsing message field values,
creating RFC-compliant dates, etc.</p>
<p>The following sections describe the functionality of the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package.
The ordering follows a progression that should be common in applications: an
email message is read as flat text from a file or other source, the text is
parsed to produce the object structure of the email message, this structure is
manipulated, and finally, the object tree is rendered back into flat text.</p>
<p>It is perfectly feasible to create the object structure out of whole cloth —
i.e. completely from scratch.  From there, a similar progression can be taken as
above.</p>
<p>Also included are detailed specifications of all the classes and modules that
the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package provides, the exception classes you might encounter
while using the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package, some auxiliary utilities, and a few
examples.  For users of the older <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> package, or previous versions
of the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package, a section on differences and porting is provided.</p>
<p>Contents of the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package documentation:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="email.message.html">18.1.1. <code class="docutils literal notranslate"><span class="pre">email.message</span></code>: Representing an email message</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.parser.html">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a><ul>
<li class="toctree-l2"><a class="reference internal" href="email.parser.html#feedparser-api">18.1.2.1. FeedParser API</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.parser.html#parser-class-api">18.1.2.2. Parser class API</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.parser.html#additional-notes">18.1.2.3. Additional notes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="email.generator.html">18.1.3. <code class="docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.mime.html">18.1.4. <code class="docutils literal notranslate"><span class="pre">email.mime</span></code>: Creating email and MIME objects from scratch</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.header.html">18.1.5. <code class="docutils literal notranslate"><span class="pre">email.header</span></code>: Internationalized headers</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.charset.html">18.1.6. <code class="docutils literal notranslate"><span class="pre">email.charset</span></code>: Representing character sets</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.encoders.html">18.1.7. <code class="docutils literal notranslate"><span class="pre">email.encoders</span></code>: Encoders</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.errors.html">18.1.8. <code class="docutils literal notranslate"><span class="pre">email.errors</span></code>: Exception and Defect classes</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.utils.html">18.1.9. <code class="docutils literal notranslate"><span class="pre">email.utils</span></code>: Miscellaneous utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="email.iterators.html">18.1.10. <code class="docutils literal notranslate"><span class="pre">email.iterators</span></code>: Iterators</a></li>
<li class="toctree-l1"><a class="reference internal" href="email-examples.html">18.1.11. <code class="docutils literal notranslate"><span class="pre">email</span></code>: Examples</a></li>
</ul>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a></dt>
<dd>SMTP protocol client</dd>
<dt>Module <a class="reference internal" href="nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a></dt>
<dd>NNTP protocol client</dd>
</dl>
</div>
<div class="section" id="package-history">
<span id="email-pkg-history"></span><h2>18.1.12. Package History<a class="headerlink" href="#package-history" title="Permalink to this headline">¶</a></h2>
<p>This table describes the release history of the email package, corresponding to
the version of Python that the package was released with.  For purposes of this
document, when you see a note about change or added versions, these refer to the
Python version the change was made in, <em>not</em> the email package version.  This
table also describes the Python compatibility of each version of the package.</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="44%" />
<col width="34%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">email version</th>
<th class="head">distributed with</th>
<th class="head">compatible with</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">1.x</span></code></td>
<td>Python 2.2.0 to Python 2.2.1</td>
<td><em>no longer supported</em></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">2.5</span></code></td>
<td>Python 2.2.2+ and Python 2.3</td>
<td>Python 2.1 to 2.5</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">3.0</span></code></td>
<td>Python 2.4</td>
<td>Python 2.3 to 2.5</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">4.0</span></code></td>
<td>Python 2.5</td>
<td>Python 2.3 to 2.5</td>
</tr>
</tbody>
</table>
<p>Here are the major differences between <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 4 and version 3:</p>
<ul>
<li><p class="first">All modules have been renamed according to <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> standards.  For example,
the version 3 module <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.Message</span></code> was renamed to <a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a> in
version 4.</p>
</li>
<li><p class="first">A new subpackage <a class="reference internal" href="email.mime.html#module-email.mime" title="email.mime: Build MIME messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime</span></code></a> was added and all the version 3
<code class="xref py py-mod docutils literal notranslate"><span class="pre">email.MIME*</span></code> modules were renamed and situated into the <a class="reference internal" href="email.mime.html#module-email.mime" title="email.mime: Build MIME messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime</span></code></a>
subpackage.  For example, the version 3 module <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.MIMEText</span></code> was renamed
to <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.text</span></code>.</p>
<p><em>Note that the version 3 names will continue to work until Python 2.6</em>.</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.application</span></code> module was added, which contains the
<a class="reference internal" href="email.mime.html#email.mime.application.MIMEApplication" title="email.mime.application.MIMEApplication"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEApplication</span></code></a> class.</p>
</li>
<li><p class="first">Methods that were deprecated in version 3 have been removed.  These include
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Generator.__call__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_type()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_main_type()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_subtype()</span></code>.</p>
</li>
<li><p class="first">Fixes have been added for <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a> support which can change some of the
return types for <a class="reference internal" href="email.message.html#email.message.Message.get_param" title="email.message.Message.get_param"><code class="xref py py-func docutils literal notranslate"><span class="pre">Message.get_param</span></code></a>
and friends.  Under some
circumstances, values which used to return a 3-tuple now return simple strings
(specifically, if all extended parameter segments were unencoded, there is no
language and charset designation expected, so the return type is now a simple
string).  Also, %-decoding used to be done for both encoded and unencoded
segments; this decoding is now done only for encoded segments.</p>
</li>
</ul>
<p>Here are the major differences between <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 3 and version 2:</p>
<ul class="simple">
<li>The <a class="reference internal" href="email.parser.html#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> class was introduced, and the
<a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class was implemented in terms of the
<a class="reference internal" href="email.parser.html#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>.  All parsing therefore is
non-strict, and parsing will make a best effort never to raise an exception.
Problems found while parsing messages are stored in the message’s <em>defect</em>
attribute.</li>
<li>All aspects of the API which raised <a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a>s in version 2
have been removed.  These include the <em>_encoder</em> argument to the
<a class="reference internal" href="email.mime.html#email.mime.text.MIMEText" title="email.mime.text.MIMEText"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEText</span></code></a> constructor, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.add_payload()</span></code> method, the <code class="xref py py-func docutils literal notranslate"><span class="pre">Utils.dump_address_pair()</span></code>
function, and the functions <code class="xref py py-func docutils literal notranslate"><span class="pre">Utils.decode()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">Utils.encode()</span></code>.</li>
<li>New <a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a>s have been added to:
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Generator.__call__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_type()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_main_type()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_subtype()</span></code>, and the <em>strict</em>
argument to the <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class.  These are expected to
be removed in future versions.</li>
<li>Support for Pythons earlier than 2.3 has been removed.</li>
</ul>
<p>Here are the differences between <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 2 and version 1:</p>
<ul>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.Header</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.Charset</span></code> modules have been added.</p>
</li>
<li><p class="first">The pickle format for <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances has changed.
Since this was never (and still isn’t) formally defined, this isn’t
considered a backward incompatibility.  However if your application pickles
and unpickles <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances, be aware that in
<a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 2, <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances now have
private variables <em>_charset</em> and <em>_default_type</em>.</p>
</li>
<li><p class="first">Several methods in the <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class have been
deprecated, or their signatures changed.  Also, many new methods have been
added.  See the documentation for the <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class
for details.  The changes should be completely backward compatible.</p>
</li>
<li><p class="first">The object structure has changed in the face of <em class="mimetype">message/rfc822</em>
content types.  In <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 1, such a type would be represented
by a scalar payload, i.e. the container message’s
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> returned false,
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> was not a list object, but a
single <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance.</p>
<p>This structure was inconsistent with the rest of the package, so the object
representation for <em class="mimetype">message/rfc822</em> content types was changed.  In
<a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> version 2, the container <em>does</em> return <code class="docutils literal notranslate"><span class="pre">True</span></code> from
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a>, and
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> returns a list containing a single
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> item.</p>
<p>Note that this is one place that backward compatibility could not be
completely maintained.  However, if you’re already testing the return type of
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a>, you should be fine.  You just need
to make sure your code doesn’t do a <a class="reference internal" href="email.message.html#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a>
with a <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance on a container with a content
type of <em class="mimetype">message/rfc822</em>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> constructor’s <em>strict</em> argument was added,
and its <a class="reference internal" href="email.parser.html#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> and
<a class="reference internal" href="email.parser.html#email.parser.Parser.parsestr" title="email.parser.Parser.parsestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parsestr()</span></code></a> methods grew a <em>headersonly</em> argument.
The <em>strict</em> flag was also added to functions <a class="reference internal" href="email.parser.html#email.message_from_file" title="email.message_from_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">email.message_from_file()</span></code></a>
and <a class="reference internal" href="email.parser.html#email.message_from_string" title="email.message_from_string"><code class="xref py py-func docutils literal notranslate"><span class="pre">email.message_from_string()</span></code></a>.</p>
</li>
<li><p class="first"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Generator.__call__()</span></code> is deprecated; use <a class="reference internal" href="email.generator.html#email.generator.Generator.flatten" title="email.generator.Generator.flatten"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Generator.flatten</span></code></a> instead.  The
<a class="reference internal" href="email.generator.html#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class has also grown the
<a class="reference internal" href="email.generator.html#email.generator.Generator.clone" title="email.generator.Generator.clone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clone()</span></code></a> method.</p>
</li>
<li><p class="first">The <a class="reference internal" href="email.generator.html#email.generator.DecodedGenerator" title="email.generator.DecodedGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecodedGenerator</span></code></a> class in the
<a class="reference internal" href="email.generator.html#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> module was added.</p>
</li>
<li><p class="first">The intermediate base classes
<a class="reference internal" href="email.mime.html#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a> and
<a class="reference internal" href="email.mime.html#email.mime.multipart.MIMEMultipart" title="email.mime.multipart.MIMEMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEMultipart</span></code></a> have been added, and interposed
in the class hierarchy for most of the other MIME-related derived classes.</p>
</li>
<li><p class="first">The <em>_encoder</em> argument to the <a class="reference internal" href="email.mime.html#email.mime.text.MIMEText" title="email.mime.text.MIMEText"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEText</span></code></a> constructor
has been deprecated.  Encoding  now happens implicitly based on the
<em>_charset</em> argument.</p>
</li>
<li><p class="first">The following functions in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.Utils</span></code> module have been deprecated:
<code class="xref py py-func docutils literal notranslate"><span class="pre">dump_address_pairs()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">decode()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code>.  The following
functions have been added to the module: <code class="xref py py-func docutils literal notranslate"><span class="pre">make_msgid()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">decode_rfc2231()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">encode_rfc2231()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">decode_params()</span></code>.</p>
</li>
<li><p class="first">The non-public function <code class="xref py py-func docutils literal notranslate"><span class="pre">email.Iterators._structure()</span></code> was added.</p>
</li>
</ul>
</div>
<div class="section" id="differences-from-mimelib">
<h2>18.1.13. Differences from <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code><a class="headerlink" href="#differences-from-mimelib" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package was originally prototyped as a separate library called
<a class="reference external" href="http://mimelib.sourceforge.net/">mimelib</a>. Changes have been made so that method names
are more consistent, and some methods or modules have either been added or
removed.  The semantics of some of the methods have also changed.  For the most
part, any functionality available in <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> is still available in the
<a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package, albeit often in a different way.  Backward compatibility
between the <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> package and the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package was not a
priority.</p>
<p>Here is a brief description of the differences between the <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> and
the <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> packages, along with hints on how to port your applications.</p>
<p>Of course, the most visible difference between the two packages is that the
package name has been changed to <a class="reference internal" href="#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>.  In addition, the top-level
package has the following differences:</p>
<ul class="simple">
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">messageFromString()</span></code> has been renamed to <a class="reference internal" href="email.parser.html#email.message_from_string" title="email.message_from_string"><code class="xref py py-func docutils literal notranslate"><span class="pre">message_from_string()</span></code></a>.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">messageFromFile()</span></code> has been renamed to <a class="reference internal" href="email.parser.html#email.message_from_file" title="email.message_from_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">message_from_file()</span></code></a>.</li>
</ul>
<p>The <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class has the following differences:</p>
<ul class="simple">
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">asString()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.as_string" title="email.message.Message.as_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">as_string()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">ismultipart()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a>.</li>
<li>The <a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> method has grown a <em>decode</em>
optional argument.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getall()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_all" title="email.message.Message.get_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_all()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">addheader()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.add_header" title="email.message.Message.add_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_header()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">gettype()</span></code> was renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_type()</span></code>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getmaintype()</span></code> was renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_main_type()</span></code>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getsubtype()</span></code> was renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_subtype()</span></code>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getparams()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_params" title="email.message.Message.get_params"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_params()</span></code></a>. Also, whereas <code class="xref py py-meth docutils literal notranslate"><span class="pre">getparams()</span></code>
returned a list of strings, <a class="reference internal" href="email.message.html#email.message.Message.get_params" title="email.message.Message.get_params"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_params()</span></code></a> returns
a list of 2-tuples, effectively the key/value pairs of the parameters, split
on the <code class="docutils literal notranslate"><span class="pre">'='</span></code> sign.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getparam()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_param" title="email.message.Message.get_param"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_param()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getcharsets()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_charsets" title="email.message.Message.get_charsets"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_charsets()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getfilename()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_filename" title="email.message.Message.get_filename"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_filename()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getboundary()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.get_boundary" title="email.message.Message.get_boundary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_boundary()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">setboundary()</span></code> was renamed to
<a class="reference internal" href="email.message.html#email.message.Message.set_boundary" title="email.message.Message.set_boundary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_boundary()</span></code></a>.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getdecodedpayload()</span></code> was removed.  To get similar
functionality, pass the value 1 to the <em>decode</em> flag of the
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> method.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getpayloadastext()</span></code> was removed.  Similar functionality is
supported by the <a class="reference internal" href="email.generator.html#email.generator.DecodedGenerator" title="email.generator.DecodedGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecodedGenerator</span></code></a> class in the
<a class="reference internal" href="email.generator.html#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> module.</li>
<li>The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">getbodyastext()</span></code> was removed.  You can get similar
functionality by creating an iterator with
<a class="reference internal" href="email.iterators.html#email.iterators.typed_subpart_iterator" title="email.iterators.typed_subpart_iterator"><code class="xref py py-func docutils literal notranslate"><span class="pre">typed_subpart_iterator()</span></code></a> in the <a class="reference internal" href="email.iterators.html#module-email.iterators" title="email.iterators: Iterate over a  message object tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.iterators</span></code></a>
module.</li>
</ul>
<p>The <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class has no differences in its public
interface. It does have some additional smarts to recognize
<em class="mimetype">message/delivery-status</em> type messages, which it represents as a
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance containing separate
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subparts for each header block in the delivery
status notification <a class="footnote-reference" href="#id2" id="id1">[1]</a>.</p>
<p>The <a class="reference internal" href="email.generator.html#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> class has no differences in its public
interface.  There is a new class in the <a class="reference internal" href="email.generator.html#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> module though,
called <a class="reference internal" href="email.generator.html#email.generator.DecodedGenerator" title="email.generator.DecodedGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">DecodedGenerator</span></code></a> which provides most of the
functionality previously available in the <code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.getpayloadastext()</span></code>
method.</p>
<p>The following modules and classes have been changed:</p>
<ul>
<li><p class="first">The <a class="reference internal" href="email.mime.html#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a> class constructor arguments <em>_major</em>
and <em>_minor</em> have changed to <em>_maintype</em> and <em>_subtype</em> respectively.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">Image</span></code> class/module has been renamed to <code class="docutils literal notranslate"><span class="pre">MIMEImage</span></code>.  The <em>_minor</em>
argument has been renamed to <em>_subtype</em>.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">Text</span></code> class/module has been renamed to <code class="docutils literal notranslate"><span class="pre">MIMEText</span></code>.  The <em>_minor</em>
argument has been renamed to <em>_subtype</em>.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">MessageRFC822</span></code> class/module has been renamed to <code class="docutils literal notranslate"><span class="pre">MIMEMessage</span></code>.  Note
that an earlier version of <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> called this class/module <code class="docutils literal notranslate"><span class="pre">RFC822</span></code>,
but that clashed with the Python standard library module <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> on some
case-insensitive file systems.</p>
<p>Also, the <a class="reference internal" href="email.mime.html#email.mime.message.MIMEMessage" title="email.mime.message.MIMEMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEMessage</span></code></a> class now represents any
kind of MIME message
with main type <em class="mimetype">message</em>.  It takes an optional argument <em>_subtype</em>
which is used to set the MIME subtype.  <em>_subtype</em> defaults to
<em class="mimetype">rfc822</em>.</p>
</li>
</ul>
<p><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> provided some utility functions in its <code class="xref py py-mod docutils literal notranslate"><span class="pre">address</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">date</span></code> modules.  All of these functions have been moved to the
<a class="reference internal" href="email.utils.html#module-email.utils" title="email.utils: Miscellaneous email package utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.utils</span></code></a> module.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">MsgReader</span></code> class/module has been removed.  Its functionality is most
closely supported in the <a class="reference internal" href="email.iterators.html#email.iterators.body_line_iterator" title="email.iterators.body_line_iterator"><code class="xref py py-func docutils literal notranslate"><span class="pre">body_line_iterator()</span></code></a> function
in the <a class="reference internal" href="email.iterators.html#module-email.iterators" title="email.iterators: Iterate over a  message object tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.iterators</span></code></a> module.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Delivery Status Notifications (DSN) are defined in <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1894.html"><strong>RFC 1894</strong></a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a><ul>
<li><a class="reference internal" href="#package-history">18.1.12. Package History</a></li>
<li><a class="reference internal" href="#differences-from-mimelib">18.1.13. Differences from <code class="docutils literal notranslate"><span class="pre">mimelib</span></code></a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="netdata.html"
                        title="previous chapter">18. Internet Data Handling</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.message.html"
                        title="next chapter">18.1.1. <code class="docutils literal notranslate"><span class="pre">email.message</span></code>: Representing an email message</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.message.html" title="18.1.1. email.message: Representing an email message"
             >next</a> |</li>
        <li class="right" >
          <a href="netdata.html" title="18. Internet Data Handling"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�>LRO1O1!html/library/email.iterators.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.10. email.iterators: Iterators &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.11. email: Examples" href="email-examples.html" />
    <link rel="prev" title="18.1.9. email.utils: Miscellaneous utilities" href="email.utils.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.iterators.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email-examples.html" title="18.1.11. email: Examples"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.utils.html" title="18.1.9. email.utils: Miscellaneous utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.iterators">
<span id="email-iterators-iterators"></span><h1>18.1.10. <a class="reference internal" href="#module-email.iterators" title="email.iterators: Iterate over a  message object tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.iterators</span></code></a>: Iterators<a class="headerlink" href="#module-email.iterators" title="Permalink to this headline">¶</a></h1>
<p>Iterating over a message object tree is fairly easy with the
<a class="reference internal" href="email.message.html#email.message.Message.walk" title="email.message.Message.walk"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.walk</span></code></a> method.  The
<a class="reference internal" href="#module-email.iterators" title="email.iterators: Iterate over a  message object tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.iterators</span></code></a> module provides some useful higher level iterations over
message object trees.</p>
<dl class="function">
<dt id="email.iterators.body_line_iterator">
<code class="descclassname">email.iterators.</code><code class="descname">body_line_iterator</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>decode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.iterators.body_line_iterator" title="Permalink to this definition">¶</a></dt>
<dd><p>This iterates over all the payloads in all the subparts of <em>msg</em>, returning the
string payloads line-by-line.  It skips over all the subpart headers, and it
skips over any subpart with a payload that isn’t a Python string.  This is
somewhat equivalent to reading the flat text representation of the message from
a file using <a class="reference internal" href="io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, skipping over all the
intervening headers.</p>
<p>Optional <em>decode</em> is passed through to <a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_payload</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="email.iterators.typed_subpart_iterator">
<code class="descclassname">email.iterators.</code><code class="descname">typed_subpart_iterator</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>maintype</em><span class="optional">[</span>, <em>subtype</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.iterators.typed_subpart_iterator" title="Permalink to this definition">¶</a></dt>
<dd><p>This iterates over all the subparts of <em>msg</em>, returning only those subparts that
match the MIME type specified by <em>maintype</em> and <em>subtype</em>.</p>
<p>Note that <em>subtype</em> is optional; if omitted, then subpart MIME type matching is
done only with the main type.  <em>maintype</em> is optional too; it defaults to
<em class="mimetype">text</em>.</p>
<p>Thus, by default <a class="reference internal" href="#email.iterators.typed_subpart_iterator" title="email.iterators.typed_subpart_iterator"><code class="xref py py-func docutils literal notranslate"><span class="pre">typed_subpart_iterator()</span></code></a> returns each subpart that has a
MIME type of <em class="mimetype">text/*</em>.</p>
</dd></dl>

<p>The following function has been added as a useful debugging tool.  It should
<em>not</em> be considered part of the supported public interface for the package.</p>
<dl class="function">
<dt id="email.iterators._structure">
<code class="descclassname">email.iterators.</code><code class="descname">_structure</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>fp</em><span class="optional">[</span>, <em>level</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.iterators._structure" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints an indented representation of the content types of the message object
structure.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">msg</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_file</span><span class="p">(</span><span class="n">somefile</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">_structure</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="go">multipart/mixed</span>
<span class="go">    text/plain</span>
<span class="go">    text/plain</span>
<span class="go">    multipart/digest</span>
<span class="go">        message/rfc822</span>
<span class="go">            text/plain</span>
<span class="go">        message/rfc822</span>
<span class="go">            text/plain</span>
<span class="go">        message/rfc822</span>
<span class="go">            text/plain</span>
<span class="go">        message/rfc822</span>
<span class="go">            text/plain</span>
<span class="go">        message/rfc822</span>
<span class="go">            text/plain</span>
<span class="go">    text/plain</span>
</pre></div>
</div>
<p>Optional <em>fp</em> is a file-like object to print the output to.  It must be suitable
for Python’s extended print statement.  <em>level</em> is used internally.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.utils.html"
                        title="previous chapter">18.1.9. <code class="docutils literal notranslate"><span class="pre">email.utils</span></code>: Miscellaneous utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email-examples.html"
                        title="next chapter">18.1.11. <code class="docutils literal notranslate"><span class="pre">email</span></code>: Examples</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.iterators.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email-examples.html" title="18.1.11. email: Examples"
             >next</a> |</li>
        <li class="right" >
          <a href="email.utils.html" title="18.1.9. email.utils: Miscellaneous utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�t--html/library/email.message.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.1. email.message: Representing an email message &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.2. email.parser: Parsing email messages" href="email.parser.html" />
    <link rel="prev" title="18.1. email — An email and MIME handling package" href="email.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.message.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.parser.html" title="18.1.2. email.parser: Parsing email messages"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.html" title="18.1. email — An email and MIME handling package"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.message">
<span id="email-message-representing-an-email-message"></span><h1>18.1.1. <a class="reference internal" href="#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a>: Representing an email message<a class="headerlink" href="#module-email.message" title="Permalink to this headline">¶</a></h1>
<p>The central class in the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is the <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class,
imported from the <a class="reference internal" href="#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a> module.  It is the base class for the
<a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> object model.  <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> provides the core functionality for
setting and querying header fields, and for accessing message bodies.</p>
<p>Conceptually, a <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> object consists of <em>headers</em> and <em>payloads</em>.
Headers are <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> style field names and values where the field name and
value are separated by a colon.  The colon is not part of either the field name
or the field value.</p>
<p>Headers are stored and returned in case-preserving form but are matched
case-insensitively.  There may also be a single envelope header, also known as
the <em>Unix-From</em> header or the <code class="docutils literal notranslate"><span class="pre">From_</span></code> header.  The payload is either a string
in the case of simple message objects or a list of <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects for
MIME container documents (e.g. <em class="mimetype">multipart/*</em> and
<em class="mimetype">message/rfc822</em>).</p>
<p><a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects provide a mapping style interface for accessing the
message headers, and an explicit interface for accessing both the headers and
the payload.  It provides convenience methods for generating a flat text
representation of the message object tree, for accessing commonly used header
parameters, and for recursively walking over the object tree.</p>
<p>Here are the methods of the <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class:</p>
<dl class="class">
<dt id="email.message.Message">
<em class="property">class </em><code class="descclassname">email.message.</code><code class="descname">Message</code><a class="headerlink" href="#email.message.Message" title="Permalink to this definition">¶</a></dt>
<dd><p>The constructor takes no arguments.</p>
<dl class="method">
<dt id="email.message.Message.as_string">
<code class="descname">as_string</code><span class="sig-paren">(</span><span class="optional">[</span><em>unixfrom</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.as_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the entire message flattened as a string.  When optional <em>unixfrom</em>
is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the envelope header is included in the returned string.
<em>unixfrom</em> defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>.  Flattening the message may trigger
changes to the <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> if defaults need to be filled in to
complete the transformation to a string (for example, MIME boundaries may
be generated or modified).</p>
<p>Note that this method is provided as a convenience and may not always
format the message the way you want.  For example, by default it mangles
lines that begin with <code class="docutils literal notranslate"><span class="pre">From</span></code>.  For more flexibility, instantiate a
<a class="reference internal" href="email.generator.html#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> instance and use its
<a class="reference internal" href="email.generator.html#email.generator.Generator.flatten" title="email.generator.Generator.flatten"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flatten()</span></code></a> method directly.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">cStringIO</span> <span class="k">import</span> <span class="n">StringIO</span>
<span class="kn">from</span> <span class="nn">email.generator</span> <span class="k">import</span> <span class="n">Generator</span>
<span class="n">fp</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
<span class="n">g</span> <span class="o">=</span> <span class="n">Generator</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="n">mangle_from_</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">maxheaderlen</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
<span class="n">g</span><span class="o">.</span><span class="n">flatten</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
<span class="n">text</span> <span class="o">=</span> <span class="n">fp</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.__str__">
<code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">as_string(unixfrom=True)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.is_multipart">
<code class="descname">is_multipart</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.is_multipart" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the message’s payload is a list of sub-<a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects, otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.  When
<a class="reference internal" href="#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, the payload should be a string object.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_unixfrom">
<code class="descname">set_unixfrom</code><span class="sig-paren">(</span><em>unixfrom</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_unixfrom" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the message’s envelope header to <em>unixfrom</em>, which should be a string.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_unixfrom">
<code class="descname">get_unixfrom</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_unixfrom" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message’s envelope header.  Defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> if the
envelope header was never set.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.attach">
<code class="descname">attach</code><span class="sig-paren">(</span><em>payload</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.attach" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the given <em>payload</em> to the current payload, which must be <code class="docutils literal notranslate"><span class="pre">None</span></code> or
a list of <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects before the call. After the call, the
payload will always be a list of <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects.  If you want to
set the payload to a scalar object (e.g. a string), use
<a class="reference internal" href="#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a> instead.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_payload">
<code class="descname">get_payload</code><span class="sig-paren">(</span><span class="optional">[</span><em>i</em><span class="optional">[</span>, <em>decode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_payload" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current payload, which will be a list of
<a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects when <a class="reference internal" href="#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, or a
string when <a class="reference internal" href="#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.  If the payload is a list
and you mutate the list object, you modify the message’s payload in place.</p>
<p>With optional argument <em>i</em>, <a class="reference internal" href="#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> will return the <em>i</em>-th
element of the payload, counting from zero, if <a class="reference internal" href="#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> is
<code class="docutils literal notranslate"><span class="pre">True</span></code>.  An <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> will be raised if <em>i</em> is less than 0 or
greater than or equal to the number of items in the payload.  If the
payload is a string (i.e.  <a class="reference internal" href="#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code>) and <em>i</em> is
given, a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>Optional <em>decode</em> is a flag indicating whether the payload should be
decoded or not, according to the <em class="mailheader">Content-Transfer-Encoding</em>
header. When <code class="docutils literal notranslate"><span class="pre">True</span></code> and the message is not a multipart, the payload will
be decoded if this header’s value is <code class="docutils literal notranslate"><span class="pre">quoted-printable</span></code> or <code class="docutils literal notranslate"><span class="pre">base64</span></code>.
If some other encoding is used, or <em class="mailheader">Content-Transfer-Encoding</em>
header is missing, or if the payload has bogus base64 data, the payload is
returned as-is (undecoded).  If the message is a multipart and the
<em>decode</em> flag is <code class="docutils literal notranslate"><span class="pre">True</span></code>, then <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.  The default for
<em>decode</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_payload">
<code class="descname">set_payload</code><span class="sig-paren">(</span><em>payload</em><span class="optional">[</span>, <em>charset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_payload" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the entire message object’s payload to <em>payload</em>.  It is the client’s
responsibility to ensure the payload invariants.  Optional <em>charset</em> sets
the message’s default character set; see <a class="reference internal" href="#email.message.Message.set_charset" title="email.message.Message.set_charset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_charset()</span></code></a> for details.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span><em>charset</em> argument added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_charset">
<code class="descname">set_charset</code><span class="sig-paren">(</span><em>charset</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the character set of the payload to <em>charset</em>, which can either be a
<a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instance (see <a class="reference internal" href="email.charset.html#module-email.charset" title="email.charset: Character Sets"><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.charset</span></code></a>), a
string naming a character set, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If it is a string, it will
be converted to a <a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instance.  If <em>charset</em>
is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter will be removed from the
<em class="mailheader">Content-Type</em> header (the message will not be otherwise
modified).  Anything else will generate a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<p>If there is no existing <em class="mailheader">MIME-Version</em> header one will be
added.  If there is no existing <em class="mailheader">Content-Type</em> header, one
will be added with a value of <em class="mimetype">text/plain</em>.  Whether the
<em class="mailheader">Content-Type</em> header already exists or not, its <code class="docutils literal notranslate"><span class="pre">charset</span></code>
parameter will be set to <em>charset.output_charset</em>.   If
<em>charset.input_charset</em> and <em>charset.output_charset</em> differ, the payload
will be re-encoded to the <em>output_charset</em>.  If there is no existing
<em class="mailheader">Content-Transfer-Encoding</em> header, then the payload will be
transfer-encoded, if needed, using the specified
<a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a>, and a header with the appropriate value
will be added.  If a <em class="mailheader">Content-Transfer-Encoding</em> header
already exists, the payload is assumed to already be correctly encoded
using that <em class="mailheader">Content-Transfer-Encoding</em> and is not modified.</p>
<p>The message will be assumed to be of type <em class="mimetype">text/*</em>, with the
payload either in unicode or encoded with <em>charset.input_charset</em>.
It will be encoded or converted to <em>charset.output_charset</em>
and transfer encoded properly, if needed, when generating the plain text
representation of the message.  MIME headers (<em class="mailheader">MIME-Version</em>,
<em class="mailheader">Content-Type</em>, <em class="mailheader">Content-Transfer-Encoding</em>) will
be added as needed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_charset">
<code class="descname">get_charset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instance associated with the
message’s payload.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<p>The following methods implement a mapping-like interface for accessing the
message’s <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> headers.  Note that there are some semantic differences
between these methods and a normal mapping (i.e. dictionary) interface.  For
example, in a dictionary there are no duplicate keys, but here there may be
duplicate message headers.  Also, in dictionaries there is no guaranteed
order to the keys returned by <a class="reference internal" href="#email.message.Message.keys" title="email.message.Message.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>, but in a <a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> object,
headers are always returned in the order they appeared in the original
message, or were added to the message later.  Any header deleted and then
re-added are always appended to the end of the header list.</p>
<p>These semantic differences are intentional and are biased toward maximal
convenience.</p>
<p>Note that in all cases, any envelope header present in the message is not
included in the mapping interface.</p>
<dl class="method">
<dt id="email.message.Message.__len__">
<code class="descname">__len__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the total number of headers, including duplicates.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.__contains__">
<code class="descname">__contains__</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the message object has a field named <em>name</em>. Matching is
done case-insensitively and <em>name</em> should not include the trailing colon.
Used for the <code class="docutils literal notranslate"><span class="pre">in</span></code> operator, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="s1">&#39;message-id&#39;</span> <span class="ow">in</span> <span class="n">myMessage</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;Message-ID:&#39;</span><span class="p">,</span> <span class="n">myMessage</span><span class="p">[</span><span class="s1">&#39;message-id&#39;</span><span class="p">]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.__getitem__">
<code class="descname">__getitem__</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the named header field.  <em>name</em> should not include the
colon field separator.  If the header is missing, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned; a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is never raised.</p>
<p>Note that if the named field appears more than once in the message’s
headers, exactly which of those field values will be returned is
undefined.  Use the <a class="reference internal" href="#email.message.Message.get_all" title="email.message.Message.get_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_all()</span></code></a> method to get the values of all the
extant named headers.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.__setitem__">
<code class="descname">__setitem__</code><span class="sig-paren">(</span><em>name</em>, <em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a header to the message with field name <em>name</em> and value <em>val</em>.  The
field is appended to the end of the message’s existing fields.</p>
<p>Note that this does <em>not</em> overwrite or delete any existing header with the same
name.  If you want to ensure that the new header is the only one present in the
message with field name <em>name</em>, delete the field first, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">del</span> <span class="n">msg</span><span class="p">[</span><span class="s1">&#39;subject&#39;</span><span class="p">]</span>
<span class="n">msg</span><span class="p">[</span><span class="s1">&#39;subject&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Python roolz!&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.__delitem__">
<code class="descname">__delitem__</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all occurrences of the field with name <em>name</em> from the message’s
headers.  No exception is raised if the named field isn’t present in the headers.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.has_key">
<code class="descname">has_key</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.has_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the message contains a header field named <em>name</em>, otherwise
return false.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.keys">
<code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all the message’s header field names.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.values">
<code class="descname">values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.values" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all the message’s field values.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.items">
<code class="descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of 2-tuples containing all the message’s field headers and
values.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get">
<code class="descname">get</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the named header field.  This is identical to
<a class="reference internal" href="#email.message.Message.__getitem__" title="email.message.Message.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> except that optional <em>failobj</em> is returned if the
named header is missing (defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
</dd></dl>

<p>Here are some additional useful methods:</p>
<dl class="method">
<dt id="email.message.Message.get_all">
<code class="descname">get_all</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all the values for the field named <em>name</em>. If there are
no such named headers in the message, <em>failobj</em> is returned (defaults to
<code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.add_header">
<code class="descname">add_header</code><span class="sig-paren">(</span><em>_name</em>, <em>_value</em>, <em>**_params</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.add_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Extended header setting.  This method is similar to <a class="reference internal" href="#email.message.Message.__setitem__" title="email.message.Message.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>
except that additional header parameters can be provided as keyword
arguments.  <em>_name</em> is the header field to add and <em>_value</em> is the
<em>primary</em> value for the header.</p>
<p>For each item in the keyword argument dictionary <em>_params</em>, the key is
taken as the parameter name, with underscores converted to dashes (since
dashes are illegal in Python identifiers).  Normally, the parameter will
be added as <code class="docutils literal notranslate"><span class="pre">key=&quot;value&quot;</span></code> unless the value is <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case
only the key will be added.  If the value contains non-ASCII characters,
it must be specified as a three tuple in the format
<code class="docutils literal notranslate"><span class="pre">(CHARSET,</span> <span class="pre">LANGUAGE,</span> <span class="pre">VALUE)</span></code>, where <code class="docutils literal notranslate"><span class="pre">CHARSET</span></code> is a string naming the
charset to be used to encode the value, <code class="docutils literal notranslate"><span class="pre">LANGUAGE</span></code> can usually be set
to <code class="docutils literal notranslate"><span class="pre">None</span></code> or the empty string (see <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a> for other possibilities),
and <code class="docutils literal notranslate"><span class="pre">VALUE</span></code> is the string value containing non-ASCII code points.</p>
<p>Here’s an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">msg</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;Content-Disposition&#39;</span><span class="p">,</span> <span class="s1">&#39;attachment&#39;</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s1">&#39;bud.gif&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will add a header that looks like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Content</span><span class="o">-</span><span class="n">Disposition</span><span class="p">:</span> <span class="n">attachment</span><span class="p">;</span> <span class="n">filename</span><span class="o">=</span><span class="s2">&quot;bud.gif&quot;</span>
</pre></div>
</div>
<p>An example with non-ASCII characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">msg</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;Content-Disposition&#39;</span><span class="p">,</span> <span class="s1">&#39;attachment&#39;</span><span class="p">,</span>
               <span class="n">filename</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;iso-8859-1&#39;</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;Fußballer.ppt&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>Which produces</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Content</span><span class="o">-</span><span class="n">Disposition</span><span class="p">:</span> <span class="n">attachment</span><span class="p">;</span> <span class="n">filename</span><span class="o">*=</span><span class="s2">&quot;iso-8859-1&#39;&#39;Fu%DFballer.ppt&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.replace_header">
<code class="descname">replace_header</code><span class="sig-paren">(</span><em>_name</em>, <em>_value</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.replace_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace a header.  Replace the first header found in the message that
matches <em>_name</em>, retaining header order and field name case.  If no
matching header was found, a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_content_type">
<code class="descname">get_content_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_content_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message’s content type.  The returned string is coerced to
lower case of the form <em class="mimetype">maintype/subtype</em>.  If there was no
<em class="mailheader">Content-Type</em> header in the message the default type as given
by <a class="reference internal" href="#email.message.Message.get_default_type" title="email.message.Message.get_default_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_default_type()</span></code></a> will be returned.  Since according to
<span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a>, messages always have a default type, <a class="reference internal" href="#email.message.Message.get_content_type" title="email.message.Message.get_content_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_content_type()</span></code></a>
will always return a value.</p>
<p><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a> defines a message’s default type to be <em class="mimetype">text/plain</em>
unless it appears inside a <em class="mimetype">multipart/digest</em> container, in
which case it would be <em class="mimetype">message/rfc822</em>.  If the
<em class="mailheader">Content-Type</em> header has an invalid type specification,
<span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a> mandates that the default type be <em class="mimetype">text/plain</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_content_maintype">
<code class="descname">get_content_maintype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_content_maintype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message’s main content type.  This is the <em class="mimetype">maintype</em>
part of the string returned by <a class="reference internal" href="#email.message.Message.get_content_type" title="email.message.Message.get_content_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_content_type()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_content_subtype">
<code class="descname">get_content_subtype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_content_subtype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message’s sub-content type.  This is the <em class="mimetype">subtype</em>
part of the string returned by <a class="reference internal" href="#email.message.Message.get_content_type" title="email.message.Message.get_content_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_content_type()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_default_type">
<code class="descname">get_default_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_default_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the default content type.  Most messages have a default content
type of <em class="mimetype">text/plain</em>, except for messages that are subparts of
<em class="mimetype">multipart/digest</em> containers.  Such subparts have a default
content type of <em class="mimetype">message/rfc822</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_default_type">
<code class="descname">set_default_type</code><span class="sig-paren">(</span><em>ctype</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_default_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the default content type.  <em>ctype</em> should either be
<em class="mimetype">text/plain</em> or <em class="mimetype">message/rfc822</em>, although this is not
enforced.  The default content type is not stored in the
<em class="mailheader">Content-Type</em> header.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_params">
<code class="descname">get_params</code><span class="sig-paren">(</span><span class="optional">[</span><em>failobj</em><span class="optional">[</span>, <em>header</em><span class="optional">[</span>, <em>unquote</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_params" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message’s <em class="mailheader">Content-Type</em> parameters, as a list.
The elements of the returned list are 2-tuples of key/value pairs, as
split on the <code class="docutils literal notranslate"><span class="pre">'='</span></code> sign.  The left hand side of the <code class="docutils literal notranslate"><span class="pre">'='</span></code> is the key,
while the right hand side is the value.  If there is no <code class="docutils literal notranslate"><span class="pre">'='</span></code> sign in
the parameter the value is the empty string, otherwise the value is as
described in <a class="reference internal" href="#email.message.Message.get_param" title="email.message.Message.get_param"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_param()</span></code></a> and is unquoted if optional <em>unquote</em> is
<code class="docutils literal notranslate"><span class="pre">True</span></code> (the default).</p>
<p>Optional <em>failobj</em> is the object to return if there is no
<em class="mailheader">Content-Type</em> header.  Optional <em>header</em> is the header to
search instead of <em class="mailheader">Content-Type</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span><em>unquote</em> argument added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_param">
<code class="descname">get_param</code><span class="sig-paren">(</span><em>param</em><span class="optional">[</span>, <em>failobj</em><span class="optional">[</span>, <em>header</em><span class="optional">[</span>, <em>unquote</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_param" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the <em class="mailheader">Content-Type</em> header’s parameter
<em>param</em> as a string.  If the message has no <em class="mailheader">Content-Type</em>
header or if there is no such parameter, then <em>failobj</em> is returned
(defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>).</p>
<p>Optional <em>header</em> if given, specifies the message header to use instead of
<em class="mailheader">Content-Type</em>.</p>
<p>Parameter keys are always compared case insensitively.  The return value
can either be a string, or a 3-tuple if the parameter was <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>
encoded.  When it’s a 3-tuple, the elements of the value are of the form
<code class="docutils literal notranslate"><span class="pre">(CHARSET,</span> <span class="pre">LANGUAGE,</span> <span class="pre">VALUE)</span></code>.  Note that both <code class="docutils literal notranslate"><span class="pre">CHARSET</span></code> and
<code class="docutils literal notranslate"><span class="pre">LANGUAGE</span></code> can be <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case you should consider <code class="docutils literal notranslate"><span class="pre">VALUE</span></code>
to be encoded in the <code class="docutils literal notranslate"><span class="pre">us-ascii</span></code> charset.  You can usually ignore
<code class="docutils literal notranslate"><span class="pre">LANGUAGE</span></code>.</p>
<p>If your application doesn’t care whether the parameter was encoded as in
<span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>, you can collapse the parameter value by calling
<a class="reference internal" href="email.utils.html#email.utils.collapse_rfc2231_value" title="email.utils.collapse_rfc2231_value"><code class="xref py py-func docutils literal notranslate"><span class="pre">email.utils.collapse_rfc2231_value()</span></code></a>, passing in the return value
from <a class="reference internal" href="#email.message.Message.get_param" title="email.message.Message.get_param"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_param()</span></code></a>.  This will return a suitably decoded Unicode
string when the value is a tuple, or the original string unquoted if it
isn’t.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">rawparam</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">get_param</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="n">param</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">collapse_rfc2231_value</span><span class="p">(</span><span class="n">rawparam</span><span class="p">)</span>
</pre></div>
</div>
<p>In any case, the parameter value (either the returned string, or the
<code class="docutils literal notranslate"><span class="pre">VALUE</span></code> item in the 3-tuple) is always unquoted, unless <em>unquote</em> is set
to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span><em>unquote</em> argument added, and 3-tuple return value possible.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_param">
<code class="descname">set_param</code><span class="sig-paren">(</span><em>param</em>, <em>value</em><span class="optional">[</span>, <em>header</em><span class="optional">[</span>, <em>requote</em><span class="optional">[</span>, <em>charset</em><span class="optional">[</span>, <em>language</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_param" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a parameter in the <em class="mailheader">Content-Type</em> header.  If the
parameter already exists in the header, its value will be replaced with
<em>value</em>.  If the <em class="mailheader">Content-Type</em> header as not yet been defined
for this message, it will be set to <em class="mimetype">text/plain</em> and the new
parameter value will be appended as per <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a>.</p>
<p>Optional <em>header</em> specifies an alternative header to
<em class="mailheader">Content-Type</em>, and all parameters will be quoted as necessary
unless optional <em>requote</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> (the default is <code class="docutils literal notranslate"><span class="pre">True</span></code>).</p>
<p>If optional <em>charset</em> is specified, the parameter will be encoded
according to <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>. Optional <em>language</em> specifies the RFC 2231
language, defaulting to the empty string.  Both <em>charset</em> and <em>language</em>
should be strings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.del_param">
<code class="descname">del_param</code><span class="sig-paren">(</span><em>param</em><span class="optional">[</span>, <em>header</em><span class="optional">[</span>, <em>requote</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.del_param" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the given parameter completely from the <em class="mailheader">Content-Type</em>
header.  The header will be re-written in place without the parameter or
its value.  All values will be quoted as necessary unless <em>requote</em> is
<code class="docutils literal notranslate"><span class="pre">False</span></code> (the default is <code class="docutils literal notranslate"><span class="pre">True</span></code>).  Optional <em>header</em> specifies an
alternative to <em class="mailheader">Content-Type</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_type">
<code class="descname">set_type</code><span class="sig-paren">(</span><em>type[, header][, requote]</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the main type and subtype for the <em class="mailheader">Content-Type</em>
header. <em>type</em> must be a string in the form <em class="mimetype">maintype/subtype</em>,
otherwise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
<p>This method replaces the <em class="mailheader">Content-Type</em> header, keeping all
the parameters in place.  If <em>requote</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, this leaves the
existing header’s quoting as is, otherwise the parameters will be quoted
(the default).</p>
<p>An alternative header can be specified in the <em>header</em> argument. When the
<em class="mailheader">Content-Type</em> header is set a <em class="mailheader">MIME-Version</em>
header is also added.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_filename">
<code class="descname">get_filename</code><span class="sig-paren">(</span><span class="optional">[</span><em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the <code class="docutils literal notranslate"><span class="pre">filename</span></code> parameter of the
<em class="mailheader">Content-Disposition</em> header of the message.  If the header
does not have a <code class="docutils literal notranslate"><span class="pre">filename</span></code> parameter, this method falls back to looking
for the <code class="docutils literal notranslate"><span class="pre">name</span></code> parameter on the <em class="mailheader">Content-Type</em> header.  If
neither is found, or the header is missing, then <em>failobj</em> is returned.
The returned string will always be unquoted as per
<a class="reference internal" href="email.utils.html#email.utils.unquote" title="email.utils.unquote"><code class="xref py py-func docutils literal notranslate"><span class="pre">email.utils.unquote()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_boundary">
<code class="descname">get_boundary</code><span class="sig-paren">(</span><span class="optional">[</span><em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_boundary" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the <code class="docutils literal notranslate"><span class="pre">boundary</span></code> parameter of the
<em class="mailheader">Content-Type</em> header of the message, or <em>failobj</em> if either
the header is missing, or has no <code class="docutils literal notranslate"><span class="pre">boundary</span></code> parameter.  The returned
string will always be unquoted as per <a class="reference internal" href="email.utils.html#email.utils.unquote" title="email.utils.unquote"><code class="xref py py-func docutils literal notranslate"><span class="pre">email.utils.unquote()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.set_boundary">
<code class="descname">set_boundary</code><span class="sig-paren">(</span><em>boundary</em><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.set_boundary" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <code class="docutils literal notranslate"><span class="pre">boundary</span></code> parameter of the <em class="mailheader">Content-Type</em> header to
<em>boundary</em>.  <a class="reference internal" href="#email.message.Message.set_boundary" title="email.message.Message.set_boundary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_boundary()</span></code></a> will always quote <em>boundary</em> if
necessary.  A <a class="reference internal" href="email.errors.html#email.errors.HeaderParseError" title="email.errors.HeaderParseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HeaderParseError</span></code></a> is raised if the
message object has no <em class="mailheader">Content-Type</em> header.</p>
<p>Note that using this method is subtly different than deleting the old
<em class="mailheader">Content-Type</em> header and adding a new one with the new
boundary via <a class="reference internal" href="#email.message.Message.add_header" title="email.message.Message.add_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_header()</span></code></a>, because <a class="reference internal" href="#email.message.Message.set_boundary" title="email.message.Message.set_boundary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_boundary()</span></code></a> preserves
the order of the <em class="mailheader">Content-Type</em> header in the list of
headers. However, it does <em>not</em> preserve any continuation lines which may
have been present in the original <em class="mailheader">Content-Type</em> header.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_content_charset">
<code class="descname">get_content_charset</code><span class="sig-paren">(</span><span class="optional">[</span><em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_content_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter of the <em class="mailheader">Content-Type</em> header,
coerced to lower case.  If there is no <em class="mailheader">Content-Type</em> header, or if
that header has no <code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter, <em>failobj</em> is returned.</p>
<p>Note that this method differs from <a class="reference internal" href="#email.message.Message.get_charset" title="email.message.Message.get_charset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_charset()</span></code></a> which returns the
<a class="reference internal" href="email.charset.html#email.charset.Charset" title="email.charset.Charset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Charset</span></code></a> instance for the default encoding of the message body.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.get_charsets">
<code class="descname">get_charsets</code><span class="sig-paren">(</span><span class="optional">[</span><em>failobj</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.get_charsets" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list containing the character set names in the message.  If the
message is a <em class="mimetype">multipart</em>, then the list will contain one element
for each subpart in the payload, otherwise, it will be a list of length 1.</p>
<p>Each item in the list will be a string which is the value of the
<code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter in the <em class="mailheader">Content-Type</em> header for the
represented subpart.  However, if the subpart has no
<em class="mailheader">Content-Type</em> header, no <code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter, or is not of
the <em class="mimetype">text</em> main MIME type, then that item in the returned list
will be <em>failobj</em>.</p>
</dd></dl>

<dl class="method">
<dt id="email.message.Message.walk">
<code class="descname">walk</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message.Message.walk" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#email.message.Message.walk" title="email.message.Message.walk"><code class="xref py py-meth docutils literal notranslate"><span class="pre">walk()</span></code></a> method is an all-purpose generator which can be used to
iterate over all the parts and subparts of a message object tree, in
depth-first traversal order.  You will typically use <a class="reference internal" href="#email.message.Message.walk" title="email.message.Message.walk"><code class="xref py py-meth docutils literal notranslate"><span class="pre">walk()</span></code></a> as the
iterator in a <code class="docutils literal notranslate"><span class="pre">for</span></code> loop; each iteration returns the next subpart.</p>
<p>Here’s an example that prints the MIME type of every part of a multipart
message structure:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">part</span> <span class="ow">in</span> <span class="n">msg</span><span class="o">.</span><span class="n">walk</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">part</span><span class="o">.</span><span class="n">get_content_type</span><span class="p">()</span>
<span class="go">multipart/report</span>
<span class="go">text/plain</span>
<span class="go">message/delivery-status</span>
<span class="go">text/plain</span>
<span class="go">text/plain</span>
<span class="go">message/rfc822</span>
</pre></div>
</div>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The previously deprecated methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_type()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_main_type()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_subtype()</span></code> were removed.</p>
</div>
<p><a class="reference internal" href="#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects can also optionally contain two instance attributes,
which can be used when generating the plain text of a MIME message.</p>
<dl class="attribute">
<dt id="email.message.Message.preamble">
<code class="descname">preamble</code><a class="headerlink" href="#email.message.Message.preamble" title="Permalink to this definition">¶</a></dt>
<dd><p>The format of a MIME document allows for some text between the blank line
following the headers, and the first multipart boundary string. Normally,
this text is never visible in a MIME-aware mail reader because it falls
outside the standard MIME armor.  However, when viewing the raw text of
the message, or when viewing the message in a non-MIME aware reader, this
text can become visible.</p>
<p>The <em>preamble</em> attribute contains this leading extra-armor text for MIME
documents.  When the <a class="reference internal" href="email.parser.html#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> discovers some text
after the headers but before the first boundary string, it assigns this
text to the message’s <em>preamble</em> attribute.  When the
<a class="reference internal" href="email.generator.html#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> is writing out the plain text
representation of a MIME message, and it finds the
message has a <em>preamble</em> attribute, it will write this text in the area
between the headers and the first boundary.  See <a class="reference internal" href="email.parser.html#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a> and
<a class="reference internal" href="email.generator.html#module-email.generator" title="email.generator: Generate flat text email messages from a message structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.generator</span></code></a> for details.</p>
<p>Note that if the message object has no preamble, the <em>preamble</em> attribute
will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="email.message.Message.epilogue">
<code class="descname">epilogue</code><a class="headerlink" href="#email.message.Message.epilogue" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>epilogue</em> attribute acts the same way as the <em>preamble</em> attribute,
except that it contains text that appears between the last boundary and
the end of the message.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>You do not need to set the epilogue to the empty string in order for the
<a class="reference internal" href="email.generator.html#email.generator.Generator" title="email.generator.Generator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Generator</span></code></a> to print a newline at the end of the
file.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="email.message.Message.defects">
<code class="descname">defects</code><a class="headerlink" href="#email.message.Message.defects" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>defects</em> attribute contains a list of all the problems found when
parsing this message.  See <a class="reference internal" href="email.errors.html#module-email.errors" title="email.errors: The exception classes used by the email package."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.errors</span></code></a> for a detailed description
of the possible parsing defects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.html"
                        title="previous chapter">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.parser.html"
                        title="next chapter">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.message.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.parser.html" title="18.1.2. email.parser: Parsing email messages"
             >next</a> |</li>
        <li class="right" >
          <a href="email.html" title="18.1. email — An email and MIME handling package"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�i+�{�{html/library/email.mime.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.4. email.mime: Creating email and MIME objects from scratch &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.5. email.header: Internationalized headers" href="email.header.html" />
    <link rel="prev" title="18.1.3. email.generator: Generating MIME documents" href="email.generator.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.mime.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.header.html" title="18.1.5. email.header: Internationalized headers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.generator.html" title="18.1.3. email.generator: Generating MIME documents"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.mime">
<span id="email-mime-creating-email-and-mime-objects-from-scratch"></span><h1>18.1.4. <a class="reference internal" href="#module-email.mime" title="email.mime: Build MIME messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime</span></code></a>: Creating email and MIME objects from scratch<a class="headerlink" href="#module-email.mime" title="Permalink to this headline">¶</a></h1>
<p>Ordinarily, you get a message object structure by passing a file or some text to
a parser, which parses the text and returns the root message object.  However
you can also build a complete message structure from scratch, or even individual
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects by hand.  In fact, you can also take an
existing structure and add new <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects, move them
around, etc.  This makes a very convenient interface for slicing-and-dicing MIME
messages.</p>
<p>You can create a new object structure by creating <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>
instances, adding attachments and all the appropriate headers manually.  For MIME
messages though, the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package provides some convenient subclasses to
make things easier.</p>
<p>Here are the classes:</p>
<dl class="class">
<dt id="email.mime.base.MIMEBase">
<em class="property">class </em><code class="descclassname">email.mime.base.</code><code class="descname">MIMEBase</code><span class="sig-paren">(</span><em>_maintype</em>, <em>_subtype</em>, <em>**_params</em><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.base.MIMEBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.base</span></code></p>
<p>This is the base class for all the MIME-specific subclasses of
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>.  Ordinarily you won’t create instances
specifically of <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a>, although you could.  <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a>
is provided primarily as a convenient base class for more specific
MIME-aware subclasses.</p>
<p><em>_maintype</em> is the <em class="mailheader">Content-Type</em> major type (e.g. <em class="mimetype">text</em>
or <em class="mimetype">image</em>), and <em>_subtype</em> is the <em class="mailheader">Content-Type</em> minor
type  (e.g. <em class="mimetype">plain</em> or <em class="mimetype">gif</em>).  <em>_params</em> is a parameter
key/value dictionary and is passed directly to <a class="reference internal" href="email.message.html#email.message.Message.add_header" title="email.message.Message.add_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.add_header</span></code></a>.</p>
<p>The <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a> class always adds a <em class="mailheader">Content-Type</em> header
(based on <em>_maintype</em>, <em>_subtype</em>, and <em>_params</em>), and a
<em class="mailheader">MIME-Version</em> header (always set to <code class="docutils literal notranslate"><span class="pre">1.0</span></code>).</p>
</dd></dl>

<dl class="class">
<dt id="email.mime.nonmultipart.MIMENonMultipart">
<em class="property">class </em><code class="descclassname">email.mime.nonmultipart.</code><code class="descname">MIMENonMultipart</code><a class="headerlink" href="#email.mime.nonmultipart.MIMENonMultipart" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.nonmultipart</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a>, this is an intermediate base
class for MIME messages that are not <em class="mimetype">multipart</em>.  The primary
purpose of this class is to prevent the use of the
<a class="reference internal" href="email.message.html#email.message.Message.attach" title="email.message.Message.attach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">attach()</span></code></a> method, which only makes sense for
<em class="mimetype">multipart</em> messages.  If <a class="reference internal" href="email.message.html#email.message.Message.attach" title="email.message.Message.attach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">attach()</span></code></a>
is called, a <a class="reference internal" href="email.errors.html#email.errors.MultipartConversionError" title="email.errors.MultipartConversionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MultipartConversionError</span></code></a> exception is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="email.mime.multipart.MIMEMultipart">
<em class="property">class </em><code class="descclassname">email.mime.multipart.</code><code class="descname">MIMEMultipart</code><span class="sig-paren">(</span><span class="optional">[</span><em>_subtype</em><span class="optional">[</span>, <em>boundary</em><span class="optional">[</span>, <em>_subparts</em><span class="optional">[</span>, <em>_params</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.multipart.MIMEMultipart" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.multipart</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a>, this is an intermediate base
class for MIME messages that are <em class="mimetype">multipart</em>.  Optional <em>_subtype</em>
defaults to <em class="mimetype">mixed</em>, but can be used to specify the subtype of the
message.  A <em class="mailheader">Content-Type</em> header of <em class="mimetype">multipart/_subtype</em>
will be added to the message object.  A <em class="mailheader">MIME-Version</em> header will
also be added.</p>
<p>Optional <em>boundary</em> is the multipart boundary string.  When <code class="docutils literal notranslate"><span class="pre">None</span></code> (the
default), the boundary is calculated when needed (for example, when the
message is serialized).</p>
<p><em>_subparts</em> is a sequence of initial subparts for the payload.  It must be
possible to convert this sequence to a list.  You can always attach new subparts
to the message by using the <a class="reference internal" href="email.message.html#email.message.Message.attach" title="email.message.Message.attach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.attach</span></code></a> method.</p>
<p>Additional parameters for the <em class="mailheader">Content-Type</em> header are taken from
the keyword arguments, or passed into the <em>_params</em> argument, which is a keyword
dictionary.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="email.mime.application.MIMEApplication">
<em class="property">class </em><code class="descclassname">email.mime.application.</code><code class="descname">MIMEApplication</code><span class="sig-paren">(</span><em>_data</em><span class="optional">[</span>, <em>_subtype</em><span class="optional">[</span>, <em>_encoder</em><span class="optional">[</span>, <em>**_params</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.application.MIMEApplication" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.application</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a>, the
<a class="reference internal" href="#email.mime.application.MIMEApplication" title="email.mime.application.MIMEApplication"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEApplication</span></code></a> class is used to represent MIME message objects of
major type <em class="mimetype">application</em>.  <em>_data</em> is a string containing the raw
byte data.  Optional <em>_subtype</em> specifies the MIME subtype and defaults to
<em class="mimetype">octet-stream</em>.</p>
<p>Optional <em>_encoder</em> is a callable (i.e. function) which will perform the actual
encoding of the data for transport.  This callable takes one argument, which is
the <a class="reference internal" href="#email.mime.application.MIMEApplication" title="email.mime.application.MIMEApplication"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEApplication</span></code></a> instance. It should use
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> and
<a class="reference internal" href="email.message.html#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a> to change the payload to encoded
form.  It should also add
any <em class="mailheader">Content-Transfer-Encoding</em> or other headers to the message
object as necessary.  The default encoding is base64.  See the
<a class="reference internal" href="email.encoders.html#module-email.encoders" title="email.encoders: Encoders for email message payloads."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.encoders</span></code></a> module for a list of the built-in encoders.</p>
<p><em>_params</em> are passed straight through to the base class constructor.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="email.mime.audio.MIMEAudio">
<em class="property">class </em><code class="descclassname">email.mime.audio.</code><code class="descname">MIMEAudio</code><span class="sig-paren">(</span><em>_audiodata</em><span class="optional">[</span>, <em>_subtype</em><span class="optional">[</span>, <em>_encoder</em><span class="optional">[</span>, <em>**_params</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.audio.MIMEAudio" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.audio</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a>, the
<a class="reference internal" href="#email.mime.audio.MIMEAudio" title="email.mime.audio.MIMEAudio"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEAudio</span></code></a> class is used to create MIME message objects of major type
<em class="mimetype">audio</em>. <em>_audiodata</em> is a string containing the raw audio data.  If
this data can be decoded by the standard Python module <a class="reference internal" href="sndhdr.html#module-sndhdr" title="sndhdr: Determine type of a sound file."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sndhdr</span></code></a>, then the
subtype will be automatically included in the <em class="mailheader">Content-Type</em> header.
Otherwise you can explicitly specify the audio subtype via the <em>_subtype</em>
parameter.  If the minor type could not be guessed and <em>_subtype</em> was not given,
then <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>Optional <em>_encoder</em> is a callable (i.e. function) which will perform the actual
encoding of the audio data for transport.  This callable takes one argument,
which is the <a class="reference internal" href="#email.mime.audio.MIMEAudio" title="email.mime.audio.MIMEAudio"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEAudio</span></code></a> instance. It should use
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> and
<a class="reference internal" href="email.message.html#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a> to change the payload to encoded
form.  It should also add
any <em class="mailheader">Content-Transfer-Encoding</em> or other headers to the message
object as necessary.  The default encoding is base64.  See the
<a class="reference internal" href="email.encoders.html#module-email.encoders" title="email.encoders: Encoders for email message payloads."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.encoders</span></code></a> module for a list of the built-in encoders.</p>
<p><em>_params</em> are passed straight through to the base class constructor.</p>
</dd></dl>

<dl class="class">
<dt id="email.mime.image.MIMEImage">
<em class="property">class </em><code class="descclassname">email.mime.image.</code><code class="descname">MIMEImage</code><span class="sig-paren">(</span><em>_imagedata</em><span class="optional">[</span>, <em>_subtype</em><span class="optional">[</span>, <em>_encoder</em><span class="optional">[</span>, <em>**_params</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.image.MIMEImage" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.image</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a>, the
<a class="reference internal" href="#email.mime.image.MIMEImage" title="email.mime.image.MIMEImage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEImage</span></code></a> class is used to create MIME message objects of major type
<em class="mimetype">image</em>. <em>_imagedata</em> is a string containing the raw image data.  If
this data can be decoded by the standard Python module <a class="reference internal" href="imghdr.html#module-imghdr" title="imghdr: Determine the type of image contained in a file or byte stream."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imghdr</span></code></a>, then the
subtype will be automatically included in the <em class="mailheader">Content-Type</em> header.
Otherwise you can explicitly specify the image subtype via the <em>_subtype</em>
parameter.  If the minor type could not be guessed and <em>_subtype</em> was not given,
then <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>Optional <em>_encoder</em> is a callable (i.e. function) which will perform the actual
encoding of the image data for transport.  This callable takes one argument,
which is the <a class="reference internal" href="#email.mime.image.MIMEImage" title="email.mime.image.MIMEImage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEImage</span></code></a> instance. It should use
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> and
<a class="reference internal" href="email.message.html#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a> to change the payload to encoded
form.  It should also add
any <em class="mailheader">Content-Transfer-Encoding</em> or other headers to the message
object as necessary.  The default encoding is base64.  See the
<a class="reference internal" href="email.encoders.html#module-email.encoders" title="email.encoders: Encoders for email message payloads."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.encoders</span></code></a> module for a list of the built-in encoders.</p>
<p><em>_params</em> are passed straight through to the <a class="reference internal" href="#email.mime.base.MIMEBase" title="email.mime.base.MIMEBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEBase</span></code></a>
constructor.</p>
</dd></dl>

<dl class="class">
<dt id="email.mime.message.MIMEMessage">
<em class="property">class </em><code class="descclassname">email.mime.message.</code><code class="descname">MIMEMessage</code><span class="sig-paren">(</span><em>_msg</em><span class="optional">[</span>, <em>_subtype</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.message.MIMEMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.message</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a>, the
<a class="reference internal" href="#email.mime.message.MIMEMessage" title="email.mime.message.MIMEMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEMessage</span></code></a> class is used to create MIME objects of main type
<em class="mimetype">message</em>. <em>_msg</em> is used as the payload, and must be an instance
of class <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> (or a subclass thereof), otherwise
a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>Optional <em>_subtype</em> sets the subtype of the message; it defaults to
<em class="mimetype">rfc822</em>.</p>
</dd></dl>

<dl class="class">
<dt id="email.mime.text.MIMEText">
<em class="property">class </em><code class="descclassname">email.mime.text.</code><code class="descname">MIMEText</code><span class="sig-paren">(</span><em>_text</em><span class="optional">[</span>, <em>_subtype</em><span class="optional">[</span>, <em>_charset</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.mime.text.MIMEText" title="Permalink to this definition">¶</a></dt>
<dd><p>Module: <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.mime.text</span></code></p>
<p>A subclass of <a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a>, the
<a class="reference internal" href="#email.mime.text.MIMEText" title="email.mime.text.MIMEText"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMEText</span></code></a> class is used to create MIME objects of major type
<em class="mimetype">text</em>. <em>_text</em> is the string for the payload.  <em>_subtype</em> is the
minor type and defaults to <em class="mimetype">plain</em>.  <em>_charset</em> is the character
set of the text and is passed as a parameter to the
<a class="reference internal" href="#email.mime.nonmultipart.MIMENonMultipart" title="email.mime.nonmultipart.MIMENonMultipart"><code class="xref py py-class docutils literal notranslate"><span class="pre">MIMENonMultipart</span></code></a> constructor; it defaults
to <code class="docutils literal notranslate"><span class="pre">us-ascii</span></code>.  If <em>_text</em> is unicode, it is encoded using the
<em>output_charset</em> of <em>_charset</em>, otherwise it is used as-is.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The previously deprecated <em>_encoding</em> argument has been removed.  Content
Transfer Encoding now happens implicitly based on the <em>_charset</em>
argument.</p>
</div>
<p>Unless the <code class="docutils literal notranslate"><span class="pre">_charset</span></code> parameter is explicitly set to <code class="docutils literal notranslate"><span class="pre">None</span></code>, the
MIMEText object created will have both a <em class="mailheader">Content-Type</em> header
with a <code class="docutils literal notranslate"><span class="pre">charset</span></code> parameter, and a <em class="mailheader">Content-Transfer-Encoding</em>
header.  This means that a subsequent <code class="docutils literal notranslate"><span class="pre">set_payload</span></code> call will not result
in an encoded payload, even if a charset is passed in the <code class="docutils literal notranslate"><span class="pre">set_payload</span></code>
command.  You can “reset” this behavior by deleting the
<code class="docutils literal notranslate"><span class="pre">Content-Transfer-Encoding</span></code> header, after which a <code class="docutils literal notranslate"><span class="pre">set_payload</span></code> call
will automatically encode the new payload (and add a new
<em class="mailheader">Content-Transfer-Encoding</em> header).</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.generator.html"
                        title="previous chapter">18.1.3. <code class="docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.header.html"
                        title="next chapter">18.1.5. <code class="docutils literal notranslate"><span class="pre">email.header</span></code>: Internationalized headers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.mime.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.header.html" title="18.1.5. email.header: Internationalized headers"
             >next</a> |</li>
        <li class="right" >
          <a href="email.generator.html" title="18.1.3. email.generator: Generating MIME documents"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\b�5F�F�html/library/email.parser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.2. email.parser: Parsing email messages &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.3. email.generator: Generating MIME documents" href="email.generator.html" />
    <link rel="prev" title="18.1.1. email.message: Representing an email message" href="email.message.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.parser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.generator.html" title="18.1.3. email.generator: Generating MIME documents"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.message.html" title="18.1.1. email.message: Representing an email message"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.parser">
<span id="email-parser-parsing-email-messages"></span><h1>18.1.2. <a class="reference internal" href="#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a>: Parsing email messages<a class="headerlink" href="#module-email.parser" title="Permalink to this headline">¶</a></h1>
<p>Message object structures can be created in one of two ways: they can be created
from whole cloth by instantiating <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects and
stringing them together via <a class="reference internal" href="email.message.html#email.message.Message.attach" title="email.message.Message.attach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">attach()</span></code></a> and
<a class="reference internal" href="email.message.html#email.message.Message.set_payload" title="email.message.Message.set_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_payload()</span></code></a> calls, or they
can be created by parsing a flat text representation of the email message.</p>
<p>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package provides a standard parser that understands most email
document structures, including MIME documents.  You can pass the parser a string
or a file object, and the parser will return to you the root
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance of the object structure.  For simple,
non-MIME messages the payload of this root object will likely be a string
containing the text of the message.  For MIME messages, the root object will
return <code class="docutils literal notranslate"><span class="pre">True</span></code> from its <a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> method, and
the subparts can be accessed via the <a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a>
and <a class="reference internal" href="email.message.html#email.message.Message.walk" title="email.message.Message.walk"><code class="xref py py-meth docutils literal notranslate"><span class="pre">walk()</span></code></a> methods.</p>
<p>There are actually two parser interfaces available for use, the classic
<a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> API and the incremental <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> API.  The classic
<a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> API is fine if you have the entire text of the message in memory
as a string, or if the entire message lives in a file on the file system.
<a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> is more appropriate for when you’re reading the message from
a stream which might block waiting for more input (e.g. reading an email message
from a socket).  The <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> can consume and parse the message
incrementally, and only returns the root object when you close the parser <a class="footnote-reference" href="#id2" id="id1">[1]</a>.</p>
<p>Note that the parser can be extended in limited ways, and of course you can
implement your own parser completely from scratch.  There is no magical
connection between the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package’s bundled parser and the
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class, so your custom parser can create message
object trees any way it finds necessary.</p>
<div class="section" id="feedparser-api">
<h2>18.1.2.1. FeedParser API<a class="headerlink" href="#feedparser-api" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>The <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>, imported from the <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.feedparser</span></code> module,
provides an API that is conducive to incremental parsing of email messages, such
as would be necessary when reading the text of an email message from a source
that can block (e.g. a socket).  The <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> can of course be used
to parse an email message fully contained in a string or a file, but the classic
<a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> API may be more convenient for such use cases.  The semantics
and results of the two parser APIs are identical.</p>
<p>The <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>’s API is simple; you create an instance, feed it a bunch
of text until there’s no more to feed it, then close the parser to retrieve the
root message object.  The <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> is extremely accurate when parsing
standards-compliant messages, and it does a very good job of parsing
non-compliant messages, providing information about how a message was deemed
broken.  It will populate a message object’s <em>defects</em> attribute with a list of
any problems it found in a message.  See the <a class="reference internal" href="email.errors.html#module-email.errors" title="email.errors: The exception classes used by the email package."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.errors</span></code></a> module for the
list of defects that it can find.</p>
<p>Here is the API for the <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>:</p>
<dl class="class">
<dt id="email.parser.FeedParser">
<em class="property">class </em><code class="descclassname">email.parser.</code><code class="descname">FeedParser</code><span class="sig-paren">(</span><span class="optional">[</span><em>_factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.FeedParser" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> instance.  Optional <em>_factory</em> is a no-argument
callable that will be called whenever a new message object is needed.  It
defaults to the <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">email.message.Message</span></code></a> class.</p>
<dl class="method">
<dt id="email.parser.FeedParser.feed">
<code class="descname">feed</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.FeedParser.feed" title="Permalink to this definition">¶</a></dt>
<dd><p>Feed the <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> some more data.  <em>data</em> should be a string
containing one or more lines.  The lines can be partial and the
<a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> will stitch such partial lines together properly.  The
lines in the string can have any of the common three line endings,
carriage return, newline, or carriage return and newline (they can even be
mixed).</p>
</dd></dl>

<dl class="method">
<dt id="email.parser.FeedParser.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.FeedParser.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closing a <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a> completes the parsing of all previously fed
data, and returns the root message object.  It is undefined what happens
if you feed more data to a closed <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="parser-class-api">
<h2>18.1.2.2. Parser class API<a class="headerlink" href="#parser-class-api" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class, imported from the <a class="reference internal" href="#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a> module,
provides an API that can be used to parse a message when the complete contents
of the message are available in a string or file.  The <a class="reference internal" href="#module-email.parser" title="email.parser: Parse flat text email messages to produce a message object structure."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.parser</span></code></a>
module also provides a second class, called <code class="xref py py-class docutils literal notranslate"><span class="pre">HeaderParser</span></code> which can be
used if you’re only interested in the headers of the message.
<code class="xref py py-class docutils literal notranslate"><span class="pre">HeaderParser</span></code> can be much faster in these situations, since it does not
attempt to parse the message body, instead setting the payload to the raw body
as a string. <code class="xref py py-class docutils literal notranslate"><span class="pre">HeaderParser</span></code> has the same API as the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a>
class.</p>
<dl class="class">
<dt id="email.parser.Parser">
<em class="property">class </em><code class="descclassname">email.parser.</code><code class="descname">Parser</code><span class="sig-paren">(</span><span class="optional">[</span><em>_class</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.Parser" title="Permalink to this definition">¶</a></dt>
<dd><p>The constructor for the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class takes an optional argument
<em>_class</em>.  This must be a callable factory (such as a function or a class), and
it is used whenever a sub-message object needs to be created.  It defaults to
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> (see <a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a>).  The factory will
be called without arguments.</p>
<p>The optional <em>strict</em> flag is ignored.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.4: </span>Because the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class is a backward compatible API wrapper
around the new-in-Python 2.4 <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>, <em>all</em> parsing is
effectively non-strict.  You should simply stop passing a <em>strict</em> flag to
the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> constructor.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>The <em>strict</em> flag was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <em>strict</em> flag was deprecated.</p>
</div>
<p>The other public <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> methods are:</p>
<dl class="method">
<dt id="email.parser.Parser.parse">
<code class="descname">parse</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>headersonly</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.Parser.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Read all the data from the file-like object <em>fp</em>, parse the resulting
text, and return the root message object.  <em>fp</em> must support both the
<a class="reference internal" href="io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> and the <a class="reference internal" href="io.html#io.TextIOBase.read" title="io.TextIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>
methods on file-like objects.</p>
<p>The text contained in <em>fp</em> must be formatted as a block of <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>
style headers and header continuation lines, optionally preceded by an
envelope header.  The header block is terminated either by the end of the
data or by a blank line.  Following the header block is the body of the
message (which may contain MIME-encoded subparts).</p>
<p>Optional <em>headersonly</em> is a flag specifying whether to stop parsing after
reading the headers or not.  The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>, meaning it parses
the entire contents of the file.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>The <em>headersonly</em> flag was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="email.parser.Parser.parsestr">
<code class="descname">parsestr</code><span class="sig-paren">(</span><em>text</em><span class="optional">[</span>, <em>headersonly</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.parser.Parser.parsestr" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> method, except it takes a string object
instead of a file-like object.  Calling this method on a string is exactly
equivalent to wrapping <em>text</em> in a <a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> instance first and
calling <a class="reference internal" href="#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a>.</p>
<p>Optional <em>headersonly</em> is as with the <a class="reference internal" href="#email.parser.Parser.parse" title="email.parser.Parser.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> method.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>The <em>headersonly</em> flag was added.</p>
</div>
</dd></dl>

</dd></dl>

<p>Since creating a message object structure from a string or a file object is such
a common task, two functions are provided as a convenience.  They are available
in the top-level <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package namespace.</p>
<dl class="function">
<dt id="email.message_from_string">
<code class="descclassname">email.</code><code class="descname">message_from_string</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>_class</em><span class="optional">[</span>, <em>strict</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message_from_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a message object structure from a string.  This is exactly equivalent to
<code class="docutils literal notranslate"><span class="pre">Parser().parsestr(s)</span></code>.  Optional <em>_class</em> and <em>strict</em> are interpreted as
with the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class constructor.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>The <em>strict</em> flag was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="email.message_from_file">
<code class="descclassname">email.</code><code class="descname">message_from_file</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>_class</em><span class="optional">[</span>, <em>strict</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.message_from_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a message object structure tree from an open file object.  This is
exactly equivalent to <code class="docutils literal notranslate"><span class="pre">Parser().parse(fp)</span></code>.  Optional <em>_class</em> and <em>strict</em>
are interpreted as with the <a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> class constructor.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>The <em>strict</em> flag was added.</p>
</div>
</dd></dl>

<p>Here’s an example of how you might use this at an interactive Python prompt:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">email</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">msg</span> <span class="o">=</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_string</span><span class="p">(</span><span class="n">myString</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="additional-notes">
<h2>18.1.2.3. Additional notes<a class="headerlink" href="#additional-notes" title="Permalink to this headline">¶</a></h2>
<p>Here are some notes on the parsing semantics:</p>
<ul class="simple">
<li>Most non-<em class="mimetype">multipart</em> type messages are parsed as a single message
object with a string payload.  These objects will return <code class="docutils literal notranslate"><span class="pre">False</span></code> for
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a>.  Their
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> method will return a string object.</li>
<li>All <em class="mimetype">multipart</em> type messages will be parsed as a container message
object with a list of sub-message objects for their payload.  The outer
container message will return <code class="docutils literal notranslate"><span class="pre">True</span></code> for
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> and their
<a class="reference internal" href="email.message.html#email.message.Message.get_payload" title="email.message.Message.get_payload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_payload()</span></code></a> method will return the list of
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subparts.</li>
<li>Most messages with a content type of <em class="mimetype">message/*</em> (e.g.
<em class="mimetype">message/delivery-status</em> and <em class="mimetype">message/rfc822</em>) will also be
parsed as container object containing a list payload of length 1.  Their
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> method will return <code class="docutils literal notranslate"><span class="pre">True</span></code>.
The single element in the list payload will be a sub-message object.</li>
<li>Some non-standards compliant messages may not be internally consistent about
their <em class="mimetype">multipart</em>-edness.  Such messages may have a
<em class="mailheader">Content-Type</em> header of type <em class="mimetype">multipart</em>, but their
<a class="reference internal" href="email.message.html#email.message.Message.is_multipart" title="email.message.Message.is_multipart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_multipart()</span></code></a> method may return <code class="docutils literal notranslate"><span class="pre">False</span></code>.
If such messages were parsed with the <a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>,
they will have an instance of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">MultipartInvariantViolationDefect</span></code> class in their
<em>defects</em> attribute list.  See <a class="reference internal" href="email.errors.html#module-email.errors" title="email.errors: The exception classes used by the email package."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.errors</span></code></a> for details.</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>As of email package version 3.0, introduced in Python 2.4, the classic
<a class="reference internal" href="#email.parser.Parser" title="email.parser.Parser"><code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code></a> was re-implemented in terms of the
<a class="reference internal" href="#email.parser.FeedParser" title="email.parser.FeedParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">FeedParser</span></code></a>, so the semantics and results are
identical between the two parsers.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a><ul>
<li><a class="reference internal" href="#feedparser-api">18.1.2.1. FeedParser API</a></li>
<li><a class="reference internal" href="#parser-class-api">18.1.2.2. Parser class API</a></li>
<li><a class="reference internal" href="#additional-notes">18.1.2.3. Additional notes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="email.message.html"
                        title="previous chapter">18.1.1. <code class="docutils literal notranslate"><span class="pre">email.message</span></code>: Representing an email message</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.generator.html"
                        title="next chapter">18.1.3. <code class="docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.parser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.generator.html" title="18.1.3. email.generator: Generating MIME documents"
             >next</a> |</li>
        <li class="right" >
          <a href="email.message.html" title="18.1.1. email.message: Representing an email message"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�;I�i�ihtml/library/email.utils.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.1.9. email.utils: Miscellaneous utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1.10. email.iterators: Iterators" href="email.iterators.html" />
    <link rel="prev" title="18.1.8. email.errors: Exception and Defect classes" href="email.errors.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/email.utils.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="18.1.10. email.iterators: Iterators"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email.errors.html" title="18.1.8. email.errors: Exception and Defect classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" accesskey="U">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-email.utils">
<span id="email-utils-miscellaneous-utilities"></span><h1>18.1.9. <a class="reference internal" href="#module-email.utils" title="email.utils: Miscellaneous email package utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.utils</span></code></a>: Miscellaneous utilities<a class="headerlink" href="#module-email.utils" title="Permalink to this headline">¶</a></h1>
<p>There are several useful utilities provided in the <a class="reference internal" href="#module-email.utils" title="email.utils: Miscellaneous email package utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.utils</span></code></a> module:</p>
<dl class="function">
<dt id="email.utils.quote">
<code class="descclassname">email.utils.</code><code class="descname">quote</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.quote" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new string with backslashes in <em>str</em> replaced by two backslashes, and
double quotes replaced by backslash-double quote.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.unquote">
<code class="descclassname">email.utils.</code><code class="descname">unquote</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.unquote" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new string which is an <em>unquoted</em> version of <em>str</em>. If <em>str</em> ends and
begins with double quotes, they are stripped off.  Likewise if <em>str</em> ends and
begins with angle brackets, they are stripped off.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.parseaddr">
<code class="descclassname">email.utils.</code><code class="descname">parseaddr</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.parseaddr" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse address – which should be the value of some address-containing field such
as <em class="mailheader">To</em> or <em class="mailheader">Cc</em> – into its constituent <em>realname</em> and
<em>email address</em> parts.  Returns a tuple of that information, unless the parse
fails, in which case a 2-tuple of <code class="docutils literal notranslate"><span class="pre">('',</span> <span class="pre">'')</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.formataddr">
<code class="descclassname">email.utils.</code><code class="descname">formataddr</code><span class="sig-paren">(</span><em>pair</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.formataddr" title="Permalink to this definition">¶</a></dt>
<dd><p>The inverse of <a class="reference internal" href="#email.utils.parseaddr" title="email.utils.parseaddr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parseaddr()</span></code></a>, this takes a 2-tuple of the form <code class="docutils literal notranslate"><span class="pre">(realname,</span>
<span class="pre">email_address)</span></code> and returns the string value suitable for a <em class="mailheader">To</em> or
<em class="mailheader">Cc</em> header.  If the first element of <em>pair</em> is false, then the
second element is returned unmodified.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.getaddresses">
<code class="descclassname">email.utils.</code><code class="descname">getaddresses</code><span class="sig-paren">(</span><em>fieldvalues</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.getaddresses" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a list of 2-tuples of the form returned by <code class="docutils literal notranslate"><span class="pre">parseaddr()</span></code>.
<em>fieldvalues</em> is a sequence of header field values as might be returned by
<a class="reference internal" href="email.message.html#email.message.Message.get_all" title="email.message.Message.get_all"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_all</span></code></a>.  Here’s a simple
example that gets all the recipients of a message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">email.utils</span> <span class="k">import</span> <span class="n">getaddresses</span>

<span class="n">tos</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">get_all</span><span class="p">(</span><span class="s1">&#39;to&#39;</span><span class="p">,</span> <span class="p">[])</span>
<span class="n">ccs</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">get_all</span><span class="p">(</span><span class="s1">&#39;cc&#39;</span><span class="p">,</span> <span class="p">[])</span>
<span class="n">resent_tos</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">get_all</span><span class="p">(</span><span class="s1">&#39;resent-to&#39;</span><span class="p">,</span> <span class="p">[])</span>
<span class="n">resent_ccs</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">get_all</span><span class="p">(</span><span class="s1">&#39;resent-cc&#39;</span><span class="p">,</span> <span class="p">[])</span>
<span class="n">all_recipients</span> <span class="o">=</span> <span class="n">getaddresses</span><span class="p">(</span><span class="n">tos</span> <span class="o">+</span> <span class="n">ccs</span> <span class="o">+</span> <span class="n">resent_tos</span> <span class="o">+</span> <span class="n">resent_ccs</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="email.utils.parsedate">
<code class="descclassname">email.utils.</code><code class="descname">parsedate</code><span class="sig-paren">(</span><em>date</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.parsedate" title="Permalink to this definition">¶</a></dt>
<dd><p>Attempts to parse a date according to the rules in <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>. however, some
mailers don’t follow that format as specified, so <a class="reference internal" href="#email.utils.parsedate" title="email.utils.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a> tries to
guess correctly in such cases.  <em>date</em> is a string containing an <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>
date, such as  <code class="docutils literal notranslate"><span class="pre">&quot;Mon,</span> <span class="pre">20</span> <span class="pre">Nov</span> <span class="pre">1995</span> <span class="pre">19:12:08</span> <span class="pre">-0500&quot;</span></code>.  If it succeeds in parsing
the date, <a class="reference internal" href="#email.utils.parsedate" title="email.utils.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a> returns a 9-tuple that can be passed directly to
<a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>; otherwise <code class="docutils literal notranslate"><span class="pre">None</span></code> will be returned.  Note that indexes 6,
7, and 8 of the result tuple are not usable.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.parsedate_tz">
<code class="descclassname">email.utils.</code><code class="descname">parsedate_tz</code><span class="sig-paren">(</span><em>date</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.parsedate_tz" title="Permalink to this definition">¶</a></dt>
<dd><p>Performs the same function as <a class="reference internal" href="#email.utils.parsedate" title="email.utils.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a>, but returns either <code class="docutils literal notranslate"><span class="pre">None</span></code> or
a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
<a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>, and the tenth is the offset of the date’s timezone from UTC
(which is the official term for Greenwich Mean Time) <a class="footnote-reference" href="#id2" id="id1">[1]</a>.  If the input string
has no timezone, the last element of the tuple returned is <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Note that
indexes 6, 7, and 8 of the result tuple are not usable.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.mktime_tz">
<code class="descclassname">email.utils.</code><code class="descname">mktime_tz</code><span class="sig-paren">(</span><em>tuple</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.mktime_tz" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn a 10-tuple as returned by <a class="reference internal" href="#email.utils.parsedate_tz" title="email.utils.parsedate_tz"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate_tz()</span></code></a> into a UTC
timestamp (seconds since the Epoch).  If the timezone item in the
tuple is <code class="docutils literal notranslate"><span class="pre">None</span></code>, assume local time.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.formatdate">
<code class="descclassname">email.utils.</code><code class="descname">formatdate</code><span class="sig-paren">(</span><em>[timeval[, localtime][, usegmt]]</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.formatdate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a date string as per <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Fri</span><span class="p">,</span> <span class="mi">09</span> <span class="n">Nov</span> <span class="mi">2001</span> <span class="mi">01</span><span class="p">:</span><span class="mi">08</span><span class="p">:</span><span class="mi">47</span> <span class="o">-</span><span class="mi">0000</span>
</pre></div>
</div>
<p>Optional <em>timeval</em> if given is a floating point time value as accepted by
<a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a> and <a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a>, otherwise the current time is
used.</p>
<p>Optional <em>localtime</em> is a flag that when <code class="docutils literal notranslate"><span class="pre">True</span></code>, interprets <em>timeval</em>, and
returns a date relative to the local timezone instead of UTC, properly taking
daylight savings time into account. The default is <code class="docutils literal notranslate"><span class="pre">False</span></code> meaning UTC is
used.</p>
<p>Optional <em>usegmt</em> is a flag that when <code class="docutils literal notranslate"><span class="pre">True</span></code>, outputs a  date string with the
timezone as an ascii string <code class="docutils literal notranslate"><span class="pre">GMT</span></code>, rather than a numeric <code class="docutils literal notranslate"><span class="pre">-0000</span></code>. This is
needed for some protocols (such as HTTP). This only applies when <em>localtime</em> is
<code class="docutils literal notranslate"><span class="pre">False</span></code>.  The default is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="email.utils.make_msgid">
<code class="descclassname">email.utils.</code><code class="descname">make_msgid</code><span class="sig-paren">(</span><span class="optional">[</span><em>idstring</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.make_msgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string suitable for an <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-compliant
<em class="mailheader">Message-ID</em> header.  Optional <em>idstring</em> if given, is a string used
to strengthen the uniqueness of the message id.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.decode_rfc2231">
<code class="descclassname">email.utils.</code><code class="descname">decode_rfc2231</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.decode_rfc2231" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode the string <em>s</em> according to <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.encode_rfc2231">
<code class="descclassname">email.utils.</code><code class="descname">encode_rfc2231</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>charset</em><span class="optional">[</span>, <em>language</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.encode_rfc2231" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the string <em>s</em> according to <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>.  Optional <em>charset</em> and
<em>language</em>, if given is the character set name and language name to use.  If
neither is given, <em>s</em> is returned as-is.  If <em>charset</em> is given but <em>language</em>
is not, the string is encoded using the empty string for <em>language</em>.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.collapse_rfc2231_value">
<code class="descclassname">email.utils.</code><code class="descname">collapse_rfc2231_value</code><span class="sig-paren">(</span><em>value</em><span class="optional">[</span>, <em>errors</em><span class="optional">[</span>, <em>fallback_charset</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.collapse_rfc2231_value" title="Permalink to this definition">¶</a></dt>
<dd><p>When a header parameter is encoded in <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a> format,
<a class="reference internal" href="email.message.html#email.message.Message.get_param" title="email.message.Message.get_param"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Message.get_param</span></code></a> may return a
3-tuple containing the character set,
language, and value.  <a class="reference internal" href="#email.utils.collapse_rfc2231_value" title="email.utils.collapse_rfc2231_value"><code class="xref py py-func docutils literal notranslate"><span class="pre">collapse_rfc2231_value()</span></code></a> turns this into a unicode
string.  Optional <em>errors</em> is passed to the <em>errors</em> argument of the built-in
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> function; it defaults to <code class="docutils literal notranslate"><span class="pre">replace</span></code>.  Optional
<em>fallback_charset</em> specifies the character set to use if the one in the
<span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a> header is not known by Python; it defaults to <code class="docutils literal notranslate"><span class="pre">us-ascii</span></code>.</p>
<p>For convenience, if the <em>value</em> passed to <a class="reference internal" href="#email.utils.collapse_rfc2231_value" title="email.utils.collapse_rfc2231_value"><code class="xref py py-func docutils literal notranslate"><span class="pre">collapse_rfc2231_value()</span></code></a> is not
a tuple, it should be a string and it is returned unquoted.</p>
</dd></dl>

<dl class="function">
<dt id="email.utils.decode_params">
<code class="descclassname">email.utils.</code><code class="descname">decode_params</code><span class="sig-paren">(</span><em>params</em><span class="sig-paren">)</span><a class="headerlink" href="#email.utils.decode_params" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode parameters list according to <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2231.html"><strong>RFC 2231</strong></a>.  <em>params</em> is a sequence of
2-tuples containing elements of the form <code class="docutils literal notranslate"><span class="pre">(content-type,</span> <span class="pre">string-value)</span></code>.</p>
</dd></dl>

<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <code class="xref py py-func docutils literal notranslate"><span class="pre">dump_address_pair()</span></code> function has been removed; use <a class="reference internal" href="#email.utils.formataddr" title="email.utils.formataddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">formataddr()</span></code></a>
instead.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <code class="xref py py-func docutils literal notranslate"><span class="pre">decode()</span></code> function has been removed; use the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Header.decode_header</span></code> method
instead.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code> function has been removed; use the <a class="reference internal" href="email.header.html#email.header.Header.encode" title="email.header.Header.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Header.encode</span></code></a> method instead.</p>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Note that the sign of the timezone offset is the opposite of the sign of the
<code class="docutils literal notranslate"><span class="pre">time.timezone</span></code> variable for the same timezone; the latter variable follows
the POSIX standard while this module follows <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="email.errors.html"
                        title="previous chapter">18.1.8. <code class="docutils literal notranslate"><span class="pre">email.errors</span></code>: Exception and Defect classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.iterators.html"
                        title="next chapter">18.1.10. <code class="docutils literal notranslate"><span class="pre">email.iterators</span></code>: Iterators</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/email.utils.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.iterators.html" title="18.1.10. email.iterators: Iterators"
             >next</a> |</li>
        <li class="right" >
          <a href="email.errors.html" title="18.1.8. email.errors: Exception and Defect classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="email.html" >18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��?��G�Ghtml/library/ensurepip.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>27.2. ensurepip — Bootstrapping the pip installer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28. Python Runtime Services" href="python.html" />
    <link rel="prev" title="27.1. distutils — Building and installing Python modules" href="distutils.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ensurepip.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="python.html" title="28. Python Runtime Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="distutils.html" title="27.1. distutils — Building and installing Python modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="distribution.html" accesskey="U">27. Software Packaging and Distribution</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ensurepip">
<span id="ensurepip-bootstrapping-the-pip-installer"></span><h1>27.2. <a class="reference internal" href="#module-ensurepip" title="ensurepip: Bootstrapping the ``pip`` installer into an existing Python installation or virtual environment."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ensurepip</span></code></a> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer<a class="headerlink" href="#module-ensurepip" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
<p>The <a class="reference internal" href="#module-ensurepip" title="ensurepip: Bootstrapping the ``pip`` installer into an existing Python installation or virtual environment."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ensurepip</span></code></a> package provides support for bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code>
installer into an existing Python installation or virtual environment. This
bootstrapping approach reflects the fact that <code class="docutils literal notranslate"><span class="pre">pip</span></code> is an independent
project with its own release cycle, and the latest available stable version
is bundled with maintenance and feature releases of the CPython reference
interpreter.</p>
<p>In most cases, end users of Python shouldn’t need to invoke this module
directly (as <code class="docutils literal notranslate"><span class="pre">pip</span></code> should be bootstrapped by default), but it may be
needed if installing <code class="docutils literal notranslate"><span class="pre">pip</span></code> was skipped when installing Python (or
when creating a virtual environment) or after explicitly uninstalling <code class="docutils literal notranslate"><span class="pre">pip</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module <em>does not</em> access the internet. All of the components
needed to bootstrap <code class="docutils literal notranslate"><span class="pre">pip</span></code> are included as internal parts of the
package.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a></dt>
<dd>The end user guide for installing Python packages</dd>
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0453"><strong>PEP 453</strong></a>: Explicit bootstrapping of pip in Python installations</dt>
<dd>The original rationale and specification for this module.</dd>
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0477"><strong>PEP 477</strong></a>: Backport ensurepip (PEP 453) to Python 2.7</dt>
<dd>The rationale and specification for backporting PEP 453 to Python 2.7.</dd>
</dl>
</div>
<div class="section" id="command-line-interface">
<h2>27.2.1. Command line interface<a class="headerlink" href="#command-line-interface" title="Permalink to this headline">¶</a></h2>
<p>The command line interface is invoked using the interpreter’s <code class="docutils literal notranslate"><span class="pre">-m</span></code> switch.</p>
<p>The simplest possible invocation is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">ensurepip</span>
</pre></div>
</div>
<p>This invocation will install <code class="docutils literal notranslate"><span class="pre">pip</span></code> if it is not already installed,
but otherwise does nothing. To ensure the installed version of <code class="docutils literal notranslate"><span class="pre">pip</span></code>
is at least as recent as the one bundled with <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code>, pass the
<code class="docutils literal notranslate"><span class="pre">--upgrade</span></code> option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">ensurepip</span> <span class="o">--</span><span class="n">upgrade</span>
</pre></div>
</div>
<p>By default, <code class="docutils literal notranslate"><span class="pre">pip</span></code> is installed into the current virtual environment
(if one is active) or into the system site packages (if there is no
active virtual environment). The installation location can be controlled
through two additional command line options:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">--root</span> <span class="pre">&lt;dir&gt;</span></code>: Installs <code class="docutils literal notranslate"><span class="pre">pip</span></code> relative to the given root directory
rather than the root of the currently active virtual environment (if any)
or the default root for the current Python installation.</li>
<li><code class="docutils literal notranslate"><span class="pre">--user</span></code>: Installs <code class="docutils literal notranslate"><span class="pre">pip</span></code> into the user site packages directory rather
than globally for the current Python installation (this option is not
permitted inside an active virtual environment).</li>
</ul>
<p>By default, the scripts <code class="docutils literal notranslate"><span class="pre">pip</span></code>, <code class="docutils literal notranslate"><span class="pre">pipX</span></code>, and <code class="docutils literal notranslate"><span class="pre">pipX.Y</span></code> will be installed
(where X.Y stands for the version of Python used to invoke <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code>). The
scripts installed can be controlled through two additional command line
options:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">--altinstall</span></code>: if an alternate installation is requested, the <code class="docutils literal notranslate"><span class="pre">pip</span></code> and
<code class="docutils literal notranslate"><span class="pre">pipX</span></code> script will <em>not</em> be installed.</li>
<li><code class="docutils literal notranslate"><span class="pre">--no-default-pip</span></code>: if a non-default installation is request, the <code class="docutils literal notranslate"><span class="pre">pip</span></code>
script will <em>not</em> be installed.</li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.15: </span>The exit status is non-zero if the command fails.</p>
</div>
</div>
<div class="section" id="module-api">
<h2>27.2.2. Module API<a class="headerlink" href="#module-api" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#module-ensurepip" title="ensurepip: Bootstrapping the ``pip`` installer into an existing Python installation or virtual environment."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ensurepip</span></code></a> exposes two functions for programmatic use:</p>
<dl class="function">
<dt id="ensurepip.version">
<code class="descclassname">ensurepip.</code><code class="descname">version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ensurepip.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string specifying the bundled version of pip that will be
installed when bootstrapping an environment.</p>
</dd></dl>

<dl class="function">
<dt id="ensurepip.bootstrap">
<code class="descclassname">ensurepip.</code><code class="descname">bootstrap</code><span class="sig-paren">(</span><em>root=None</em>, <em>upgrade=False</em>, <em>user=False</em>, <em>altinstall=False</em>, <em>default_pip=True</em>, <em>verbosity=0</em><span class="sig-paren">)</span><a class="headerlink" href="#ensurepip.bootstrap" title="Permalink to this definition">¶</a></dt>
<dd><p>Bootstraps <code class="docutils literal notranslate"><span class="pre">pip</span></code> into the current or designated environment.</p>
<p><em>root</em> specifies an alternative root directory to install relative to.
If <em>root</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then installation uses the default install location
for the current environment.</p>
<p><em>upgrade</em> indicates whether or not to upgrade an existing installation
of an earlier version of <code class="docutils literal notranslate"><span class="pre">pip</span></code> to the bundled version.</p>
<p><em>user</em> indicates whether to use the user scheme rather than installing
globally.</p>
<p>By default, the scripts <code class="docutils literal notranslate"><span class="pre">pip</span></code>, <code class="docutils literal notranslate"><span class="pre">pipX</span></code>, and <code class="docutils literal notranslate"><span class="pre">pipX.Y</span></code> will be installed
(where X.Y stands for the current version of Python).</p>
<p>If <em>altinstall</em> is set, then <code class="docutils literal notranslate"><span class="pre">pip</span></code> and <code class="docutils literal notranslate"><span class="pre">pipX</span></code> will <em>not</em> be installed.</p>
<p>If <em>default_pip</em> is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, then <code class="docutils literal notranslate"><span class="pre">pip</span></code> will <em>not</em> be installed.</p>
<p>Setting both <em>altinstall</em> and <em>default_pip</em> will trigger
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p><em>verbosity</em> controls the level of output to <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> from the
bootstrapping operation.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The bootstrapping process has side effects on both <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and
<code class="docutils literal notranslate"><span class="pre">os.environ</span></code>. Invoking the command line interface in a subprocess
instead allows these side effects to be avoided.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The bootstrapping process may install additional modules required by
<code class="docutils literal notranslate"><span class="pre">pip</span></code>, but other software should not assume those dependencies will
always be present by default (as the dependencies may be removed in a
future version of <code class="docutils literal notranslate"><span class="pre">pip</span></code>).</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a><ul>
<li><a class="reference internal" href="#command-line-interface">27.2.1. Command line interface</a></li>
<li><a class="reference internal" href="#module-api">27.2.2. Module API</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="distutils.html"
                        title="previous chapter">27.1. <code class="docutils literal notranslate"><span class="pre">distutils</span></code> — Building and installing Python modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="python.html"
                        title="next chapter">28. Python Runtime Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ensurepip.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="python.html" title="28. Python Runtime Services"
             >next</a> |</li>
        <li class="right" >
          <a href="distutils.html" title="27.1. distutils — Building and installing Python modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="distribution.html" >27. Software Packaging and Distribution</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\~��6�6�html/library/errno.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.16. errno — Standard errno system symbols &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.17. ctypes — A foreign function library for Python" href="ctypes.html" />
    <link rel="prev" title="15.15. platform — Access to underlying platform’s identifying data" href="platform.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/errno.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ctypes.html" title="15.17. ctypes — A foreign function library for Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="platform.html" title="15.15. platform — Access to underlying platform’s identifying data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-errno">
<span id="errno-standard-errno-system-symbols"></span><h1>15.16. <a class="reference internal" href="#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">errno</span></code></a> — Standard errno system symbols<a class="headerlink" href="#module-errno" title="Permalink to this headline">¶</a></h1>
<p>This module makes available standard <code class="docutils literal notranslate"><span class="pre">errno</span></code> system symbols. The value of each
symbol is the corresponding integer value. The names and descriptions are
borrowed from <code class="file docutils literal notranslate"><span class="pre">linux/include/errno.h</span></code>, which should be pretty
all-inclusive.</p>
<dl class="data">
<dt id="errno.errorcode">
<code class="descclassname">errno.</code><code class="descname">errorcode</code><a class="headerlink" href="#errno.errorcode" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary providing a mapping from the errno value to the string name in the
underlying system.  For instance, <code class="docutils literal notranslate"><span class="pre">errno.errorcode[errno.EPERM]</span></code> maps to
<code class="docutils literal notranslate"><span class="pre">'EPERM'</span></code>.</p>
</dd></dl>

<p>To translate a numeric error code to an error message, use <a class="reference internal" href="os.html#os.strerror" title="os.strerror"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.strerror()</span></code></a>.</p>
<p>Of the following list, symbols that are not used on the current platform are not
defined by the module.  The specific list of defined symbols is available as
<code class="docutils literal notranslate"><span class="pre">errno.errorcode.keys()</span></code>.  Symbols available can include:</p>
<dl class="data">
<dt id="errno.EPERM">
<code class="descclassname">errno.</code><code class="descname">EPERM</code><a class="headerlink" href="#errno.EPERM" title="Permalink to this definition">¶</a></dt>
<dd><p>Operation not permitted</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOENT">
<code class="descclassname">errno.</code><code class="descname">ENOENT</code><a class="headerlink" href="#errno.ENOENT" title="Permalink to this definition">¶</a></dt>
<dd><p>No such file or directory</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESRCH">
<code class="descclassname">errno.</code><code class="descname">ESRCH</code><a class="headerlink" href="#errno.ESRCH" title="Permalink to this definition">¶</a></dt>
<dd><p>No such process</p>
</dd></dl>

<dl class="data">
<dt id="errno.EINTR">
<code class="descclassname">errno.</code><code class="descname">EINTR</code><a class="headerlink" href="#errno.EINTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Interrupted system call</p>
</dd></dl>

<dl class="data">
<dt id="errno.EIO">
<code class="descclassname">errno.</code><code class="descname">EIO</code><a class="headerlink" href="#errno.EIO" title="Permalink to this definition">¶</a></dt>
<dd><p>I/O error</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENXIO">
<code class="descclassname">errno.</code><code class="descname">ENXIO</code><a class="headerlink" href="#errno.ENXIO" title="Permalink to this definition">¶</a></dt>
<dd><p>No such device or address</p>
</dd></dl>

<dl class="data">
<dt id="errno.E2BIG">
<code class="descclassname">errno.</code><code class="descname">E2BIG</code><a class="headerlink" href="#errno.E2BIG" title="Permalink to this definition">¶</a></dt>
<dd><p>Arg list too long</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOEXEC">
<code class="descclassname">errno.</code><code class="descname">ENOEXEC</code><a class="headerlink" href="#errno.ENOEXEC" title="Permalink to this definition">¶</a></dt>
<dd><p>Exec format error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADF">
<code class="descclassname">errno.</code><code class="descname">EBADF</code><a class="headerlink" href="#errno.EBADF" title="Permalink to this definition">¶</a></dt>
<dd><p>Bad file number</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECHILD">
<code class="descclassname">errno.</code><code class="descname">ECHILD</code><a class="headerlink" href="#errno.ECHILD" title="Permalink to this definition">¶</a></dt>
<dd><p>No child processes</p>
</dd></dl>

<dl class="data">
<dt id="errno.EAGAIN">
<code class="descclassname">errno.</code><code class="descname">EAGAIN</code><a class="headerlink" href="#errno.EAGAIN" title="Permalink to this definition">¶</a></dt>
<dd><p>Try again</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOMEM">
<code class="descclassname">errno.</code><code class="descname">ENOMEM</code><a class="headerlink" href="#errno.ENOMEM" title="Permalink to this definition">¶</a></dt>
<dd><p>Out of memory</p>
</dd></dl>

<dl class="data">
<dt id="errno.EACCES">
<code class="descclassname">errno.</code><code class="descname">EACCES</code><a class="headerlink" href="#errno.EACCES" title="Permalink to this definition">¶</a></dt>
<dd><p>Permission denied</p>
</dd></dl>

<dl class="data">
<dt id="errno.EFAULT">
<code class="descclassname">errno.</code><code class="descname">EFAULT</code><a class="headerlink" href="#errno.EFAULT" title="Permalink to this definition">¶</a></dt>
<dd><p>Bad address</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTBLK">
<code class="descclassname">errno.</code><code class="descname">ENOTBLK</code><a class="headerlink" href="#errno.ENOTBLK" title="Permalink to this definition">¶</a></dt>
<dd><p>Block device required</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBUSY">
<code class="descclassname">errno.</code><code class="descname">EBUSY</code><a class="headerlink" href="#errno.EBUSY" title="Permalink to this definition">¶</a></dt>
<dd><p>Device or resource busy</p>
</dd></dl>

<dl class="data">
<dt id="errno.EEXIST">
<code class="descclassname">errno.</code><code class="descname">EEXIST</code><a class="headerlink" href="#errno.EEXIST" title="Permalink to this definition">¶</a></dt>
<dd><p>File exists</p>
</dd></dl>

<dl class="data">
<dt id="errno.EXDEV">
<code class="descclassname">errno.</code><code class="descname">EXDEV</code><a class="headerlink" href="#errno.EXDEV" title="Permalink to this definition">¶</a></dt>
<dd><p>Cross-device link</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENODEV">
<code class="descclassname">errno.</code><code class="descname">ENODEV</code><a class="headerlink" href="#errno.ENODEV" title="Permalink to this definition">¶</a></dt>
<dd><p>No such device</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTDIR">
<code class="descclassname">errno.</code><code class="descname">ENOTDIR</code><a class="headerlink" href="#errno.ENOTDIR" title="Permalink to this definition">¶</a></dt>
<dd><p>Not a directory</p>
</dd></dl>

<dl class="data">
<dt id="errno.EISDIR">
<code class="descclassname">errno.</code><code class="descname">EISDIR</code><a class="headerlink" href="#errno.EISDIR" title="Permalink to this definition">¶</a></dt>
<dd><p>Is a directory</p>
</dd></dl>

<dl class="data">
<dt id="errno.EINVAL">
<code class="descclassname">errno.</code><code class="descname">EINVAL</code><a class="headerlink" href="#errno.EINVAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalid argument</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENFILE">
<code class="descclassname">errno.</code><code class="descname">ENFILE</code><a class="headerlink" href="#errno.ENFILE" title="Permalink to this definition">¶</a></dt>
<dd><p>File table overflow</p>
</dd></dl>

<dl class="data">
<dt id="errno.EMFILE">
<code class="descclassname">errno.</code><code class="descname">EMFILE</code><a class="headerlink" href="#errno.EMFILE" title="Permalink to this definition">¶</a></dt>
<dd><p>Too many open files</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTTY">
<code class="descclassname">errno.</code><code class="descname">ENOTTY</code><a class="headerlink" href="#errno.ENOTTY" title="Permalink to this definition">¶</a></dt>
<dd><p>Not a typewriter</p>
</dd></dl>

<dl class="data">
<dt id="errno.ETXTBSY">
<code class="descclassname">errno.</code><code class="descname">ETXTBSY</code><a class="headerlink" href="#errno.ETXTBSY" title="Permalink to this definition">¶</a></dt>
<dd><p>Text file busy</p>
</dd></dl>

<dl class="data">
<dt id="errno.EFBIG">
<code class="descclassname">errno.</code><code class="descname">EFBIG</code><a class="headerlink" href="#errno.EFBIG" title="Permalink to this definition">¶</a></dt>
<dd><p>File too large</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOSPC">
<code class="descclassname">errno.</code><code class="descname">ENOSPC</code><a class="headerlink" href="#errno.ENOSPC" title="Permalink to this definition">¶</a></dt>
<dd><p>No space left on device</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESPIPE">
<code class="descclassname">errno.</code><code class="descname">ESPIPE</code><a class="headerlink" href="#errno.ESPIPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Illegal seek</p>
</dd></dl>

<dl class="data">
<dt id="errno.EROFS">
<code class="descclassname">errno.</code><code class="descname">EROFS</code><a class="headerlink" href="#errno.EROFS" title="Permalink to this definition">¶</a></dt>
<dd><p>Read-only file system</p>
</dd></dl>

<dl class="data">
<dt id="errno.EMLINK">
<code class="descclassname">errno.</code><code class="descname">EMLINK</code><a class="headerlink" href="#errno.EMLINK" title="Permalink to this definition">¶</a></dt>
<dd><p>Too many links</p>
</dd></dl>

<dl class="data">
<dt id="errno.EPIPE">
<code class="descclassname">errno.</code><code class="descname">EPIPE</code><a class="headerlink" href="#errno.EPIPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Broken pipe</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDOM">
<code class="descclassname">errno.</code><code class="descname">EDOM</code><a class="headerlink" href="#errno.EDOM" title="Permalink to this definition">¶</a></dt>
<dd><p>Math argument out of domain of func</p>
</dd></dl>

<dl class="data">
<dt id="errno.ERANGE">
<code class="descclassname">errno.</code><code class="descname">ERANGE</code><a class="headerlink" href="#errno.ERANGE" title="Permalink to this definition">¶</a></dt>
<dd><p>Math result not representable</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDEADLK">
<code class="descclassname">errno.</code><code class="descname">EDEADLK</code><a class="headerlink" href="#errno.EDEADLK" title="Permalink to this definition">¶</a></dt>
<dd><p>Resource deadlock would occur</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENAMETOOLONG">
<code class="descclassname">errno.</code><code class="descname">ENAMETOOLONG</code><a class="headerlink" href="#errno.ENAMETOOLONG" title="Permalink to this definition">¶</a></dt>
<dd><p>File name too long</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOLCK">
<code class="descclassname">errno.</code><code class="descname">ENOLCK</code><a class="headerlink" href="#errno.ENOLCK" title="Permalink to this definition">¶</a></dt>
<dd><p>No record locks available</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOSYS">
<code class="descclassname">errno.</code><code class="descname">ENOSYS</code><a class="headerlink" href="#errno.ENOSYS" title="Permalink to this definition">¶</a></dt>
<dd><p>Function not implemented</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTEMPTY">
<code class="descclassname">errno.</code><code class="descname">ENOTEMPTY</code><a class="headerlink" href="#errno.ENOTEMPTY" title="Permalink to this definition">¶</a></dt>
<dd><p>Directory not empty</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELOOP">
<code class="descclassname">errno.</code><code class="descname">ELOOP</code><a class="headerlink" href="#errno.ELOOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Too many symbolic links encountered</p>
</dd></dl>

<dl class="data">
<dt id="errno.EWOULDBLOCK">
<code class="descclassname">errno.</code><code class="descname">EWOULDBLOCK</code><a class="headerlink" href="#errno.EWOULDBLOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Operation would block</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOMSG">
<code class="descclassname">errno.</code><code class="descname">ENOMSG</code><a class="headerlink" href="#errno.ENOMSG" title="Permalink to this definition">¶</a></dt>
<dd><p>No message of desired type</p>
</dd></dl>

<dl class="data">
<dt id="errno.EIDRM">
<code class="descclassname">errno.</code><code class="descname">EIDRM</code><a class="headerlink" href="#errno.EIDRM" title="Permalink to this definition">¶</a></dt>
<dd><p>Identifier removed</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECHRNG">
<code class="descclassname">errno.</code><code class="descname">ECHRNG</code><a class="headerlink" href="#errno.ECHRNG" title="Permalink to this definition">¶</a></dt>
<dd><p>Channel number out of range</p>
</dd></dl>

<dl class="data">
<dt id="errno.EL2NSYNC">
<code class="descclassname">errno.</code><code class="descname">EL2NSYNC</code><a class="headerlink" href="#errno.EL2NSYNC" title="Permalink to this definition">¶</a></dt>
<dd><p>Level 2 not synchronized</p>
</dd></dl>

<dl class="data">
<dt id="errno.EL3HLT">
<code class="descclassname">errno.</code><code class="descname">EL3HLT</code><a class="headerlink" href="#errno.EL3HLT" title="Permalink to this definition">¶</a></dt>
<dd><p>Level 3 halted</p>
</dd></dl>

<dl class="data">
<dt id="errno.EL3RST">
<code class="descclassname">errno.</code><code class="descname">EL3RST</code><a class="headerlink" href="#errno.EL3RST" title="Permalink to this definition">¶</a></dt>
<dd><p>Level 3 reset</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELNRNG">
<code class="descclassname">errno.</code><code class="descname">ELNRNG</code><a class="headerlink" href="#errno.ELNRNG" title="Permalink to this definition">¶</a></dt>
<dd><p>Link number out of range</p>
</dd></dl>

<dl class="data">
<dt id="errno.EUNATCH">
<code class="descclassname">errno.</code><code class="descname">EUNATCH</code><a class="headerlink" href="#errno.EUNATCH" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol driver not attached</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOCSI">
<code class="descclassname">errno.</code><code class="descname">ENOCSI</code><a class="headerlink" href="#errno.ENOCSI" title="Permalink to this definition">¶</a></dt>
<dd><p>No CSI structure available</p>
</dd></dl>

<dl class="data">
<dt id="errno.EL2HLT">
<code class="descclassname">errno.</code><code class="descname">EL2HLT</code><a class="headerlink" href="#errno.EL2HLT" title="Permalink to this definition">¶</a></dt>
<dd><p>Level 2 halted</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADE">
<code class="descclassname">errno.</code><code class="descname">EBADE</code><a class="headerlink" href="#errno.EBADE" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalid exchange</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADR">
<code class="descclassname">errno.</code><code class="descname">EBADR</code><a class="headerlink" href="#errno.EBADR" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalid request descriptor</p>
</dd></dl>

<dl class="data">
<dt id="errno.EXFULL">
<code class="descclassname">errno.</code><code class="descname">EXFULL</code><a class="headerlink" href="#errno.EXFULL" title="Permalink to this definition">¶</a></dt>
<dd><p>Exchange full</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOANO">
<code class="descclassname">errno.</code><code class="descname">ENOANO</code><a class="headerlink" href="#errno.ENOANO" title="Permalink to this definition">¶</a></dt>
<dd><p>No anode</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADRQC">
<code class="descclassname">errno.</code><code class="descname">EBADRQC</code><a class="headerlink" href="#errno.EBADRQC" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalid request code</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADSLT">
<code class="descclassname">errno.</code><code class="descname">EBADSLT</code><a class="headerlink" href="#errno.EBADSLT" title="Permalink to this definition">¶</a></dt>
<dd><p>Invalid slot</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDEADLOCK">
<code class="descclassname">errno.</code><code class="descname">EDEADLOCK</code><a class="headerlink" href="#errno.EDEADLOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>File locking deadlock error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBFONT">
<code class="descclassname">errno.</code><code class="descname">EBFONT</code><a class="headerlink" href="#errno.EBFONT" title="Permalink to this definition">¶</a></dt>
<dd><p>Bad font file format</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOSTR">
<code class="descclassname">errno.</code><code class="descname">ENOSTR</code><a class="headerlink" href="#errno.ENOSTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Device not a stream</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENODATA">
<code class="descclassname">errno.</code><code class="descname">ENODATA</code><a class="headerlink" href="#errno.ENODATA" title="Permalink to this definition">¶</a></dt>
<dd><p>No data available</p>
</dd></dl>

<dl class="data">
<dt id="errno.ETIME">
<code class="descclassname">errno.</code><code class="descname">ETIME</code><a class="headerlink" href="#errno.ETIME" title="Permalink to this definition">¶</a></dt>
<dd><p>Timer expired</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOSR">
<code class="descclassname">errno.</code><code class="descname">ENOSR</code><a class="headerlink" href="#errno.ENOSR" title="Permalink to this definition">¶</a></dt>
<dd><p>Out of streams resources</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENONET">
<code class="descclassname">errno.</code><code class="descname">ENONET</code><a class="headerlink" href="#errno.ENONET" title="Permalink to this definition">¶</a></dt>
<dd><p>Machine is not on the network</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOPKG">
<code class="descclassname">errno.</code><code class="descname">ENOPKG</code><a class="headerlink" href="#errno.ENOPKG" title="Permalink to this definition">¶</a></dt>
<dd><p>Package not installed</p>
</dd></dl>

<dl class="data">
<dt id="errno.EREMOTE">
<code class="descclassname">errno.</code><code class="descname">EREMOTE</code><a class="headerlink" href="#errno.EREMOTE" title="Permalink to this definition">¶</a></dt>
<dd><p>Object is remote</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOLINK">
<code class="descclassname">errno.</code><code class="descname">ENOLINK</code><a class="headerlink" href="#errno.ENOLINK" title="Permalink to this definition">¶</a></dt>
<dd><p>Link has been severed</p>
</dd></dl>

<dl class="data">
<dt id="errno.EADV">
<code class="descclassname">errno.</code><code class="descname">EADV</code><a class="headerlink" href="#errno.EADV" title="Permalink to this definition">¶</a></dt>
<dd><p>Advertise error</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESRMNT">
<code class="descclassname">errno.</code><code class="descname">ESRMNT</code><a class="headerlink" href="#errno.ESRMNT" title="Permalink to this definition">¶</a></dt>
<dd><p>Srmount error</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECOMM">
<code class="descclassname">errno.</code><code class="descname">ECOMM</code><a class="headerlink" href="#errno.ECOMM" title="Permalink to this definition">¶</a></dt>
<dd><p>Communication error on send</p>
</dd></dl>

<dl class="data">
<dt id="errno.EPROTO">
<code class="descclassname">errno.</code><code class="descname">EPROTO</code><a class="headerlink" href="#errno.EPROTO" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EMULTIHOP">
<code class="descclassname">errno.</code><code class="descname">EMULTIHOP</code><a class="headerlink" href="#errno.EMULTIHOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Multihop attempted</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDOTDOT">
<code class="descclassname">errno.</code><code class="descname">EDOTDOT</code><a class="headerlink" href="#errno.EDOTDOT" title="Permalink to this definition">¶</a></dt>
<dd><p>RFS specific error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADMSG">
<code class="descclassname">errno.</code><code class="descname">EBADMSG</code><a class="headerlink" href="#errno.EBADMSG" title="Permalink to this definition">¶</a></dt>
<dd><p>Not a data message</p>
</dd></dl>

<dl class="data">
<dt id="errno.EOVERFLOW">
<code class="descclassname">errno.</code><code class="descname">EOVERFLOW</code><a class="headerlink" href="#errno.EOVERFLOW" title="Permalink to this definition">¶</a></dt>
<dd><p>Value too large for defined data type</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTUNIQ">
<code class="descclassname">errno.</code><code class="descname">ENOTUNIQ</code><a class="headerlink" href="#errno.ENOTUNIQ" title="Permalink to this definition">¶</a></dt>
<dd><p>Name not unique on network</p>
</dd></dl>

<dl class="data">
<dt id="errno.EBADFD">
<code class="descclassname">errno.</code><code class="descname">EBADFD</code><a class="headerlink" href="#errno.EBADFD" title="Permalink to this definition">¶</a></dt>
<dd><p>File descriptor in bad state</p>
</dd></dl>

<dl class="data">
<dt id="errno.EREMCHG">
<code class="descclassname">errno.</code><code class="descname">EREMCHG</code><a class="headerlink" href="#errno.EREMCHG" title="Permalink to this definition">¶</a></dt>
<dd><p>Remote address changed</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELIBACC">
<code class="descclassname">errno.</code><code class="descname">ELIBACC</code><a class="headerlink" href="#errno.ELIBACC" title="Permalink to this definition">¶</a></dt>
<dd><p>Can not access a needed shared library</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELIBBAD">
<code class="descclassname">errno.</code><code class="descname">ELIBBAD</code><a class="headerlink" href="#errno.ELIBBAD" title="Permalink to this definition">¶</a></dt>
<dd><p>Accessing a corrupted shared library</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELIBSCN">
<code class="descclassname">errno.</code><code class="descname">ELIBSCN</code><a class="headerlink" href="#errno.ELIBSCN" title="Permalink to this definition">¶</a></dt>
<dd><p>.lib section in a.out corrupted</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELIBMAX">
<code class="descclassname">errno.</code><code class="descname">ELIBMAX</code><a class="headerlink" href="#errno.ELIBMAX" title="Permalink to this definition">¶</a></dt>
<dd><p>Attempting to link in too many shared libraries</p>
</dd></dl>

<dl class="data">
<dt id="errno.ELIBEXEC">
<code class="descclassname">errno.</code><code class="descname">ELIBEXEC</code><a class="headerlink" href="#errno.ELIBEXEC" title="Permalink to this definition">¶</a></dt>
<dd><p>Cannot exec a shared library directly</p>
</dd></dl>

<dl class="data">
<dt id="errno.EILSEQ">
<code class="descclassname">errno.</code><code class="descname">EILSEQ</code><a class="headerlink" href="#errno.EILSEQ" title="Permalink to this definition">¶</a></dt>
<dd><p>Illegal byte sequence</p>
</dd></dl>

<dl class="data">
<dt id="errno.ERESTART">
<code class="descclassname">errno.</code><code class="descname">ERESTART</code><a class="headerlink" href="#errno.ERESTART" title="Permalink to this definition">¶</a></dt>
<dd><p>Interrupted system call should be restarted</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESTRPIPE">
<code class="descclassname">errno.</code><code class="descname">ESTRPIPE</code><a class="headerlink" href="#errno.ESTRPIPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Streams pipe error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EUSERS">
<code class="descclassname">errno.</code><code class="descname">EUSERS</code><a class="headerlink" href="#errno.EUSERS" title="Permalink to this definition">¶</a></dt>
<dd><p>Too many users</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTSOCK">
<code class="descclassname">errno.</code><code class="descname">ENOTSOCK</code><a class="headerlink" href="#errno.ENOTSOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Socket operation on non-socket</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDESTADDRREQ">
<code class="descclassname">errno.</code><code class="descname">EDESTADDRREQ</code><a class="headerlink" href="#errno.EDESTADDRREQ" title="Permalink to this definition">¶</a></dt>
<dd><p>Destination address required</p>
</dd></dl>

<dl class="data">
<dt id="errno.EMSGSIZE">
<code class="descclassname">errno.</code><code class="descname">EMSGSIZE</code><a class="headerlink" href="#errno.EMSGSIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Message too long</p>
</dd></dl>

<dl class="data">
<dt id="errno.EPROTOTYPE">
<code class="descclassname">errno.</code><code class="descname">EPROTOTYPE</code><a class="headerlink" href="#errno.EPROTOTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol wrong type for socket</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOPROTOOPT">
<code class="descclassname">errno.</code><code class="descname">ENOPROTOOPT</code><a class="headerlink" href="#errno.ENOPROTOOPT" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol not available</p>
</dd></dl>

<dl class="data">
<dt id="errno.EPROTONOSUPPORT">
<code class="descclassname">errno.</code><code class="descname">EPROTONOSUPPORT</code><a class="headerlink" href="#errno.EPROTONOSUPPORT" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol not supported</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESOCKTNOSUPPORT">
<code class="descclassname">errno.</code><code class="descname">ESOCKTNOSUPPORT</code><a class="headerlink" href="#errno.ESOCKTNOSUPPORT" title="Permalink to this definition">¶</a></dt>
<dd><p>Socket type not supported</p>
</dd></dl>

<dl class="data">
<dt id="errno.EOPNOTSUPP">
<code class="descclassname">errno.</code><code class="descname">EOPNOTSUPP</code><a class="headerlink" href="#errno.EOPNOTSUPP" title="Permalink to this definition">¶</a></dt>
<dd><p>Operation not supported on transport endpoint</p>
</dd></dl>

<dl class="data">
<dt id="errno.EPFNOSUPPORT">
<code class="descclassname">errno.</code><code class="descname">EPFNOSUPPORT</code><a class="headerlink" href="#errno.EPFNOSUPPORT" title="Permalink to this definition">¶</a></dt>
<dd><p>Protocol family not supported</p>
</dd></dl>

<dl class="data">
<dt id="errno.EAFNOSUPPORT">
<code class="descclassname">errno.</code><code class="descname">EAFNOSUPPORT</code><a class="headerlink" href="#errno.EAFNOSUPPORT" title="Permalink to this definition">¶</a></dt>
<dd><p>Address family not supported by protocol</p>
</dd></dl>

<dl class="data">
<dt id="errno.EADDRINUSE">
<code class="descclassname">errno.</code><code class="descname">EADDRINUSE</code><a class="headerlink" href="#errno.EADDRINUSE" title="Permalink to this definition">¶</a></dt>
<dd><p>Address already in use</p>
</dd></dl>

<dl class="data">
<dt id="errno.EADDRNOTAVAIL">
<code class="descclassname">errno.</code><code class="descname">EADDRNOTAVAIL</code><a class="headerlink" href="#errno.EADDRNOTAVAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>Cannot assign requested address</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENETDOWN">
<code class="descclassname">errno.</code><code class="descname">ENETDOWN</code><a class="headerlink" href="#errno.ENETDOWN" title="Permalink to this definition">¶</a></dt>
<dd><p>Network is down</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENETUNREACH">
<code class="descclassname">errno.</code><code class="descname">ENETUNREACH</code><a class="headerlink" href="#errno.ENETUNREACH" title="Permalink to this definition">¶</a></dt>
<dd><p>Network is unreachable</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENETRESET">
<code class="descclassname">errno.</code><code class="descname">ENETRESET</code><a class="headerlink" href="#errno.ENETRESET" title="Permalink to this definition">¶</a></dt>
<dd><p>Network dropped connection because of reset</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECONNABORTED">
<code class="descclassname">errno.</code><code class="descname">ECONNABORTED</code><a class="headerlink" href="#errno.ECONNABORTED" title="Permalink to this definition">¶</a></dt>
<dd><p>Software caused connection abort</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECONNRESET">
<code class="descclassname">errno.</code><code class="descname">ECONNRESET</code><a class="headerlink" href="#errno.ECONNRESET" title="Permalink to this definition">¶</a></dt>
<dd><p>Connection reset by peer</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOBUFS">
<code class="descclassname">errno.</code><code class="descname">ENOBUFS</code><a class="headerlink" href="#errno.ENOBUFS" title="Permalink to this definition">¶</a></dt>
<dd><p>No buffer space available</p>
</dd></dl>

<dl class="data">
<dt id="errno.EISCONN">
<code class="descclassname">errno.</code><code class="descname">EISCONN</code><a class="headerlink" href="#errno.EISCONN" title="Permalink to this definition">¶</a></dt>
<dd><p>Transport endpoint is already connected</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTCONN">
<code class="descclassname">errno.</code><code class="descname">ENOTCONN</code><a class="headerlink" href="#errno.ENOTCONN" title="Permalink to this definition">¶</a></dt>
<dd><p>Transport endpoint is not connected</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESHUTDOWN">
<code class="descclassname">errno.</code><code class="descname">ESHUTDOWN</code><a class="headerlink" href="#errno.ESHUTDOWN" title="Permalink to this definition">¶</a></dt>
<dd><p>Cannot send after transport endpoint shutdown</p>
</dd></dl>

<dl class="data">
<dt id="errno.ETOOMANYREFS">
<code class="descclassname">errno.</code><code class="descname">ETOOMANYREFS</code><a class="headerlink" href="#errno.ETOOMANYREFS" title="Permalink to this definition">¶</a></dt>
<dd><p>Too many references: cannot splice</p>
</dd></dl>

<dl class="data">
<dt id="errno.ETIMEDOUT">
<code class="descclassname">errno.</code><code class="descname">ETIMEDOUT</code><a class="headerlink" href="#errno.ETIMEDOUT" title="Permalink to this definition">¶</a></dt>
<dd><p>Connection timed out</p>
</dd></dl>

<dl class="data">
<dt id="errno.ECONNREFUSED">
<code class="descclassname">errno.</code><code class="descname">ECONNREFUSED</code><a class="headerlink" href="#errno.ECONNREFUSED" title="Permalink to this definition">¶</a></dt>
<dd><p>Connection refused</p>
</dd></dl>

<dl class="data">
<dt id="errno.EHOSTDOWN">
<code class="descclassname">errno.</code><code class="descname">EHOSTDOWN</code><a class="headerlink" href="#errno.EHOSTDOWN" title="Permalink to this definition">¶</a></dt>
<dd><p>Host is down</p>
</dd></dl>

<dl class="data">
<dt id="errno.EHOSTUNREACH">
<code class="descclassname">errno.</code><code class="descname">EHOSTUNREACH</code><a class="headerlink" href="#errno.EHOSTUNREACH" title="Permalink to this definition">¶</a></dt>
<dd><p>No route to host</p>
</dd></dl>

<dl class="data">
<dt id="errno.EALREADY">
<code class="descclassname">errno.</code><code class="descname">EALREADY</code><a class="headerlink" href="#errno.EALREADY" title="Permalink to this definition">¶</a></dt>
<dd><p>Operation already in progress</p>
</dd></dl>

<dl class="data">
<dt id="errno.EINPROGRESS">
<code class="descclassname">errno.</code><code class="descname">EINPROGRESS</code><a class="headerlink" href="#errno.EINPROGRESS" title="Permalink to this definition">¶</a></dt>
<dd><p>Operation now in progress</p>
</dd></dl>

<dl class="data">
<dt id="errno.ESTALE">
<code class="descclassname">errno.</code><code class="descname">ESTALE</code><a class="headerlink" href="#errno.ESTALE" title="Permalink to this definition">¶</a></dt>
<dd><p>Stale NFS file handle</p>
</dd></dl>

<dl class="data">
<dt id="errno.EUCLEAN">
<code class="descclassname">errno.</code><code class="descname">EUCLEAN</code><a class="headerlink" href="#errno.EUCLEAN" title="Permalink to this definition">¶</a></dt>
<dd><p>Structure needs cleaning</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENOTNAM">
<code class="descclassname">errno.</code><code class="descname">ENOTNAM</code><a class="headerlink" href="#errno.ENOTNAM" title="Permalink to this definition">¶</a></dt>
<dd><p>Not a XENIX named type file</p>
</dd></dl>

<dl class="data">
<dt id="errno.ENAVAIL">
<code class="descclassname">errno.</code><code class="descname">ENAVAIL</code><a class="headerlink" href="#errno.ENAVAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>No XENIX semaphores available</p>
</dd></dl>

<dl class="data">
<dt id="errno.EISNAM">
<code class="descclassname">errno.</code><code class="descname">EISNAM</code><a class="headerlink" href="#errno.EISNAM" title="Permalink to this definition">¶</a></dt>
<dd><p>Is a named type file</p>
</dd></dl>

<dl class="data">
<dt id="errno.EREMOTEIO">
<code class="descclassname">errno.</code><code class="descname">EREMOTEIO</code><a class="headerlink" href="#errno.EREMOTEIO" title="Permalink to this definition">¶</a></dt>
<dd><p>Remote I/O error</p>
</dd></dl>

<dl class="data">
<dt id="errno.EDQUOT">
<code class="descclassname">errno.</code><code class="descname">EDQUOT</code><a class="headerlink" href="#errno.EDQUOT" title="Permalink to this definition">¶</a></dt>
<dd><p>Quota exceeded</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="platform.html"
                        title="previous chapter">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ctypes.html"
                        title="next chapter">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/errno.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ctypes.html" title="15.17. ctypes — A foreign function library for Python"
             >next</a> |</li>
        <li class="right" >
          <a href="platform.html" title="15.15. platform — Access to underlying platform’s identifying data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�5��html/library/exceptions.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>6. Built-in Exceptions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7. String Services" href="strings.html" />
    <link rel="prev" title="5. Built-in Types" href="stdtypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/exceptions.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="strings.html" title="7. String Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stdtypes.html" title="5. Built-in Types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-exceptions">
<span id="built-in-exceptions"></span><span id="bltin-exceptions"></span><h1>6. Built-in Exceptions<a class="headerlink" href="#module-exceptions" title="Permalink to this headline">¶</a></h1>
<p>Exceptions should be class objects.   The exceptions are defined in the module
<a class="reference internal" href="#module-exceptions" title="exceptions: Standard exception classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">exceptions</span></code></a>.  This module never needs to be imported explicitly: the
exceptions are provided in the built-in namespace as well as the
<a class="reference internal" href="#module-exceptions" title="exceptions: Standard exception classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">exceptions</span></code></a> module.</p>
<p id="index-0">For class exceptions, in a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
clause that mentions a particular class, that clause also handles any exception
classes derived from that class (but not exception classes from which <em>it</em> is
derived).  Two exception classes that are not related via subclassing are never
equivalent, even if they have the same name.</p>
<p id="index-1">The built-in exceptions listed below can be generated by the interpreter or
built-in functions.  Except where mentioned, they have an “associated value”
indicating the detailed cause of the error.  This may be a string or a tuple
containing several items of information (e.g., an error code and a string
explaining the code). The associated value is the second argument to the
<a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement.  If the exception class is derived from the standard
root class <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>, the associated value is present as the
exception instance’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> attribute.</p>
<p>User code can raise built-in exceptions.  This can be used to test an exception
handler or to report an error condition “just like” the situation in which the
interpreter raises the same exception; but beware that there is nothing to
prevent user code from raising an inappropriate error.</p>
<p>The built-in exception classes can be subclassed to define new exceptions;
programmers are encouraged to derive new exceptions from the <a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>
class or one of its subclasses, and not from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.  More
information on defining exceptions is available in the Python Tutorial under
<a class="reference internal" href="../tutorial/errors.html#tut-userexceptions"><span class="std std-ref">User-defined Exceptions</span></a>.</p>
<p>The following exceptions are only used as base classes for other exceptions.</p>
<dl class="exception">
<dt id="exceptions.BaseException">
<em class="property">exception </em><code class="descname">BaseException</code><a class="headerlink" href="#exceptions.BaseException" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class for all built-in exceptions.  It is not meant to be directly
inherited by user-defined classes (for that, use <a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>).  If
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> or <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> is called on an instance of this class, the
representation of the argument(s) to the instance are returned, or the empty
string when there were no arguments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<dl class="attribute">
<dt id="exceptions.BaseException.args">
<code class="descname">args</code><a class="headerlink" href="#exceptions.BaseException.args" title="Permalink to this definition">¶</a></dt>
<dd><p>The tuple of arguments given to the exception constructor.  Some built-in
exceptions (like <a class="reference internal" href="#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>) expect a certain number of arguments and
assign a special meaning to the elements of this tuple, while others are
usually called only with a single string giving an error message.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="exceptions.Exception">
<em class="property">exception </em><code class="descname">Exception</code><a class="headerlink" href="#exceptions.Exception" title="Permalink to this definition">¶</a></dt>
<dd><p>All built-in, non-system-exiting exceptions are derived from this class.  All
user-defined exceptions should also be derived from this class.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Changed to inherit from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.StandardError">
<em class="property">exception </em><code class="descname">StandardError</code><a class="headerlink" href="#exceptions.StandardError" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class for all built-in exceptions except <a class="reference internal" href="#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>,
<a class="reference internal" href="#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>, <a class="reference internal" href="#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>.
<a class="reference internal" href="#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a> itself is derived from <a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ArithmeticError">
<em class="property">exception </em><code class="descname">ArithmeticError</code><a class="headerlink" href="#exceptions.ArithmeticError" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class for those built-in exceptions that are raised for various
arithmetic errors: <a class="reference internal" href="#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>, <a class="reference internal" href="#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>,
<a class="reference internal" href="#exceptions.FloatingPointError" title="exceptions.FloatingPointError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FloatingPointError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.BufferError">
<em class="property">exception </em><code class="descname">BufferError</code><a class="headerlink" href="#exceptions.BufferError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">buffer</span></a> related operation cannot be
performed.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.LookupError">
<em class="property">exception </em><code class="descname">LookupError</code><a class="headerlink" href="#exceptions.LookupError" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class for the exceptions that are raised when a key or index used on
a mapping or sequence is invalid: <a class="reference internal" href="#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>, <a class="reference internal" href="#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.  This
can be raised directly by <a class="reference internal" href="codecs.html#codecs.lookup" title="codecs.lookup"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.lookup()</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.EnvironmentError">
<em class="property">exception </em><code class="descname">EnvironmentError</code><a class="headerlink" href="#exceptions.EnvironmentError" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class for exceptions that can occur outside the Python system:
<a class="reference internal" href="#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>, <a class="reference internal" href="#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>.  When exceptions of this type are created with a
2-tuple, the first item is available on the instance’s <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-attr docutils literal notranslate"><span class="pre">errno</span></code></a> attribute
(it is assumed to be an error number), and the second item is available on the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">strerror</span></code> attribute (it is usually the associated error message).  The
tuple itself is also available on the <code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> attribute.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<p>When an <a class="reference internal" href="#exceptions.EnvironmentError" title="exceptions.EnvironmentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EnvironmentError</span></code></a> exception is instantiated with a 3-tuple, the
first two items are available as above, while the third item is available on the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attribute.  However, for backwards compatibility, the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> attribute contains only a 2-tuple of the first two constructor
arguments.</p>
<p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code> when this exception is created with
other than 3 arguments.  The <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-attr docutils literal notranslate"><span class="pre">errno</span></code></a> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">strerror</span></code> attributes are
also <code class="docutils literal notranslate"><span class="pre">None</span></code> when the instance was created with other than 2 or 3 arguments.
In this last case, <code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> contains the verbatim constructor arguments as a
tuple.</p>
</dd></dl>

<p>The following exceptions are the exceptions that are actually raised.</p>
<dl class="exception">
<dt id="exceptions.AssertionError">
<em class="property">exception </em><code class="descname">AssertionError</code><a class="headerlink" href="#exceptions.AssertionError" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Raised when an <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement fails.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.AttributeError">
<em class="property">exception </em><code class="descname">AttributeError</code><a class="headerlink" href="#exceptions.AttributeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an attribute reference (see <a class="reference internal" href="../reference/expressions.html#attribute-references"><span class="std std-ref">Attribute references</span></a>) or
assignment fails.  (When an object does not support attribute references or
attribute assignments at all, <a class="reference internal" href="#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.)</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.EOFError">
<em class="property">exception </em><code class="descname">EOFError</code><a class="headerlink" href="#exceptions.EOFError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when one of the built-in functions (<a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> or <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a>)
hits an end-of-file condition (EOF) without reading any data. (N.B.: the
<a class="reference internal" href="stdtypes.html#file.read" title="file.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.read()</span></code></a> and <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.readline()</span></code></a> methods return an empty string
when they hit EOF.)</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.FloatingPointError">
<em class="property">exception </em><code class="descname">FloatingPointError</code><a class="headerlink" href="#exceptions.FloatingPointError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a floating point operation fails.  This exception is always defined,
but can only be raised when Python is configured with the
<code class="docutils literal notranslate"><span class="pre">--with-fpectl</span></code> option, or the <code class="xref py py-const docutils literal notranslate"><span class="pre">WANT_SIGFPE_HANDLER</span></code> symbol is
defined in the <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code> file.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.GeneratorExit">
<em class="property">exception </em><code class="descname">GeneratorExit</code><a class="headerlink" href="#exceptions.GeneratorExit" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method is called.  It
directly inherits from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> instead of <a class="reference internal" href="#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a>
since it is technically not an error.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Changed to inherit from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.IOError">
<em class="property">exception </em><code class="descname">IOError</code><a class="headerlink" href="#exceptions.IOError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an I/O operation (such as a <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement, the built-in
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function or a method of a file object) fails for an I/O-related
reason, e.g., “file not found” or “disk full”.</p>
<p>This class is derived from <a class="reference internal" href="#exceptions.EnvironmentError" title="exceptions.EnvironmentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EnvironmentError</span></code></a>.  See the discussion above
for more information on exception instance attributes.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Changed <a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> to use this as a base class.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ImportError">
<em class="property">exception </em><code class="descname">ImportError</code><a class="headerlink" href="#exceptions.ImportError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement fails to find the module definition
or when a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> fails to find a name that is to be imported.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.IndexError">
<em class="property">exception </em><code class="descname">IndexError</code><a class="headerlink" href="#exceptions.IndexError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a sequence subscript is out of range.  (Slice indices are silently
truncated to fall in the allowed range; if an index is not a plain integer,
<a class="reference internal" href="#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.)</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.KeyError">
<em class="property">exception </em><code class="descname">KeyError</code><a class="headerlink" href="#exceptions.KeyError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a mapping (dictionary) key is not found in the set of existing keys.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.KeyboardInterrupt">
<em class="property">exception </em><code class="descname">KeyboardInterrupt</code><a class="headerlink" href="#exceptions.KeyboardInterrupt" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the user hits the interrupt key (normally <kbd class="kbd docutils literal notranslate">Control-C</kbd> or
<kbd class="kbd docutils literal notranslate">Delete</kbd>).  During execution, a check for interrupts is made regularly.
Interrupts typed when a built-in function <a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> or <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> is
waiting for input also raise this exception. The exception inherits from
<a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> so as to not be accidentally caught by code that catches
<a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> and thus prevent the interpreter from exiting.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Changed to inherit from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.MemoryError">
<em class="property">exception </em><code class="descname">MemoryError</code><a class="headerlink" href="#exceptions.MemoryError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an operation runs out of memory but the situation may still be
rescued (by deleting some objects).  The associated value is a string indicating
what kind of (internal) operation ran out of memory. Note that because of the
underlying memory management architecture (C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> function), the
interpreter may not always be able to completely recover from this situation; it
nevertheless raises an exception so that a stack traceback can be printed, in
case a run-away program was the cause.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.NameError">
<em class="property">exception </em><code class="descname">NameError</code><a class="headerlink" href="#exceptions.NameError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a local or global name is not found.  This applies only to
unqualified names.  The associated value is an error message that includes the
name that could not be found.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.NotImplementedError">
<em class="property">exception </em><code class="descname">NotImplementedError</code><a class="headerlink" href="#exceptions.NotImplementedError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is derived from <a class="reference internal" href="#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.  In user defined base
classes, abstract methods should raise this exception when they require derived
classes to override the method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.OSError">
<em class="property">exception </em><code class="descname">OSError</code><a class="headerlink" href="#exceptions.OSError" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">This exception is derived from <a class="reference internal" href="#exceptions.EnvironmentError" title="exceptions.EnvironmentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EnvironmentError</span></code></a>.  It is raised when a
function returns a system-related error (not for illegal argument types or
other incidental errors).  The <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-attr docutils literal notranslate"><span class="pre">errno</span></code></a> attribute is a numeric error
code from <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code>, and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">strerror</span></code> attribute is the
corresponding string, as would be printed by the C function <code class="xref c c-func docutils literal notranslate"><span class="pre">perror()</span></code>.
See the module <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">errno</span></code></a>, which contains names for the error codes defined
by the underlying operating system.</p>
<p>For exceptions that involve a file system path (such as <code class="xref py py-func docutils literal notranslate"><span class="pre">chdir()</span></code> or
<code class="xref py py-func docutils literal notranslate"><span class="pre">unlink()</span></code>), the exception instance will contain a third attribute,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code>, which is the file name passed to the function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.OverflowError">
<em class="property">exception </em><code class="descname">OverflowError</code><a class="headerlink" href="#exceptions.OverflowError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the result of an arithmetic operation is too large to be
represented.  This cannot occur for long integers (which would rather raise
<a class="reference internal" href="#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> than give up) and for most operations with plain integers,
which return a long integer instead.  Because of the lack of standardization
of floating point exception handling in C, most floating point operations
also aren’t checked.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ReferenceError">
<em class="property">exception </em><code class="descname">ReferenceError</code><a class="headerlink" href="#exceptions.ReferenceError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a weak reference proxy, created by the
<a class="reference internal" href="weakref.html#weakref.proxy" title="weakref.proxy"><code class="xref py py-func docutils literal notranslate"><span class="pre">weakref.proxy()</span></code></a> function, is used to access an attribute of the referent
after it has been garbage collected. For more information on weak references,
see the <a class="reference internal" href="weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2: </span>Previously known as the <a class="reference internal" href="weakref.html#weakref.ReferenceError" title="weakref.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">weakref.ReferenceError</span></code></a> exception.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.RuntimeError">
<em class="property">exception </em><code class="descname">RuntimeError</code><a class="headerlink" href="#exceptions.RuntimeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an error is detected that doesn’t fall in any of the other
categories.  The associated value is a string indicating what precisely went
wrong.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.StopIteration">
<em class="property">exception </em><code class="descname">StopIteration</code><a class="headerlink" href="#exceptions.StopIteration" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised by an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>’s <a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method to signal that
there are no further values.  This is derived from <a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> rather
than <a class="reference internal" href="#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a>, since this is not considered an error in its
normal application.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.SyntaxError">
<em class="property">exception </em><code class="descname">SyntaxError</code><a class="headerlink" href="#exceptions.SyntaxError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the parser encounters a syntax error.  This may occur in an
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, in an <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement, in a call to the
built-in function <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> or <a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a>, or when reading the initial
script or standard input (also interactively).</p>
<p>Instances of this class have attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">offset</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">text</span></code> for easier access to the details.  <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>
of the exception instance returns only the message.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.IndentationError">
<em class="property">exception </em><code class="descname">IndentationError</code><a class="headerlink" href="#exceptions.IndentationError" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for syntax errors related to incorrect indentation.  This is a
subclass of <a class="reference internal" href="#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.TabError">
<em class="property">exception </em><code class="descname">TabError</code><a class="headerlink" href="#exceptions.TabError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when indentation contains an inconsistent use of tabs and spaces.
This is a subclass of <a class="reference internal" href="#exceptions.IndentationError" title="exceptions.IndentationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndentationError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.SystemError">
<em class="property">exception </em><code class="descname">SystemError</code><a class="headerlink" href="#exceptions.SystemError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the interpreter finds an internal error, but the situation does not
look so serious to cause it to abandon all hope. The associated value is a
string indicating what went wrong (in low-level terms).</p>
<p>You should report this to the author or maintainer of your Python interpreter.
Be sure to report the version of the Python interpreter (<code class="docutils literal notranslate"><span class="pre">sys.version</span></code>; it is
also printed at the start of an interactive Python session), the exact error
message (the exception’s associated value) and if possible the source of the
program that triggered the error.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.SystemExit">
<em class="property">exception </em><code class="descname">SystemExit</code><a class="headerlink" href="#exceptions.SystemExit" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised by the <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> function.  When it is not
handled, the Python interpreter exits; no stack traceback is printed.  If the
associated value is a plain integer, it specifies the system exit status (passed
to C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">exit()</span></code> function); if it is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the exit status is zero; if
it has another type (such as a string), the object’s value is printed and the
exit status is one.</p>
<p>Instances have an attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code> which is set to the proposed exit
status or error message (defaulting to <code class="docutils literal notranslate"><span class="pre">None</span></code>). Also, this exception derives
directly from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> and not <a class="reference internal" href="#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a>, since it is not
technically an error.</p>
<p>A call to <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> is translated into an exception so that clean-up
handlers (<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses of <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statements) can be
executed, and so that a debugger can execute a script without running the risk
of losing control.  The <a class="reference internal" href="os.html#os._exit" title="os._exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">os._exit()</span></code></a> function can be used if it is
absolutely positively necessary to exit immediately (for example, in the child
process after a call to <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a>).</p>
<p>The exception inherits from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> instead of <a class="reference internal" href="#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a>
or <a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> so that it is not accidentally caught by code that catches
<a class="reference internal" href="#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.  This allows the exception to properly propagate up and cause
the interpreter to exit.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Changed to inherit from <a class="reference internal" href="#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.TypeError">
<em class="property">exception </em><code class="descname">TypeError</code><a class="headerlink" href="#exceptions.TypeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an operation or function is applied to an object of inappropriate
type.  The associated value is a string giving details about the type mismatch.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnboundLocalError">
<em class="property">exception </em><code class="descname">UnboundLocalError</code><a class="headerlink" href="#exceptions.UnboundLocalError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a reference is made to a local variable in a function or method, but
no value has been bound to that variable.  This is a subclass of
<a class="reference internal" href="#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnicodeError">
<em class="property">exception </em><code class="descname">UnicodeError</code><a class="headerlink" href="#exceptions.UnicodeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a Unicode-related encoding or decoding error occurs.  It is a
subclass of <a class="reference internal" href="#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p><a class="reference internal" href="#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> has attributes that describe the encoding or decoding
error.  For example, <code class="docutils literal notranslate"><span class="pre">err.object[err.start:err.end]</span></code> gives the particular
invalid input that the codec failed on.</p>
<dl class="attribute">
<dt id="exceptions.UnicodeError.encoding">
<code class="descname">encoding</code><a class="headerlink" href="#exceptions.UnicodeError.encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the encoding that raised the error.</p>
</dd></dl>

<dl class="attribute">
<dt id="exceptions.UnicodeError.reason">
<code class="descname">reason</code><a class="headerlink" href="#exceptions.UnicodeError.reason" title="Permalink to this definition">¶</a></dt>
<dd><p>A string describing the specific codec error.</p>
</dd></dl>

<dl class="attribute">
<dt id="exceptions.UnicodeError.object">
<code class="descname">object</code><a class="headerlink" href="#exceptions.UnicodeError.object" title="Permalink to this definition">¶</a></dt>
<dd><p>The object the codec was attempting to encode or decode.</p>
</dd></dl>

<dl class="attribute">
<dt id="exceptions.UnicodeError.start">
<code class="descname">start</code><a class="headerlink" href="#exceptions.UnicodeError.start" title="Permalink to this definition">¶</a></dt>
<dd><p>The first index of invalid data in <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-attr docutils literal notranslate"><span class="pre">object</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="exceptions.UnicodeError.end">
<code class="descname">end</code><a class="headerlink" href="#exceptions.UnicodeError.end" title="Permalink to this definition">¶</a></dt>
<dd><p>The index after the last invalid data in <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-attr docutils literal notranslate"><span class="pre">object</span></code></a>.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnicodeEncodeError">
<em class="property">exception </em><code class="descname">UnicodeEncodeError</code><a class="headerlink" href="#exceptions.UnicodeEncodeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a Unicode-related error occurs during encoding.  It is a subclass of
<a class="reference internal" href="#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnicodeDecodeError">
<em class="property">exception </em><code class="descname">UnicodeDecodeError</code><a class="headerlink" href="#exceptions.UnicodeDecodeError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a Unicode-related error occurs during decoding.  It is a subclass of
<a class="reference internal" href="#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnicodeTranslateError">
<em class="property">exception </em><code class="descname">UnicodeTranslateError</code><a class="headerlink" href="#exceptions.UnicodeTranslateError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a Unicode-related error occurs during translating.  It is a subclass
of <a class="reference internal" href="#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ValueError">
<em class="property">exception </em><code class="descname">ValueError</code><a class="headerlink" href="#exceptions.ValueError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an operation or function receives an argument that has the
right type but an inappropriate value, and the situation is not described by a
more precise exception such as <a class="reference internal" href="#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.VMSError">
<em class="property">exception </em><code class="descname">VMSError</code><a class="headerlink" href="#exceptions.VMSError" title="Permalink to this definition">¶</a></dt>
<dd><p>Only available on VMS.  Raised when a VMS-specific error occurs.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.WindowsError">
<em class="property">exception </em><code class="descname">WindowsError</code><a class="headerlink" href="#exceptions.WindowsError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a Windows-specific error occurs or when the error number does not
correspond to an <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> value.  The <code class="xref py py-attr docutils literal notranslate"><span class="pre">winerror</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">strerror</span></code> values are created from the return values of the
<code class="xref c c-func docutils literal notranslate"><span class="pre">GetLastError()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">FormatMessage()</span></code> functions from the Windows
Platform API. The <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-attr docutils literal notranslate"><span class="pre">errno</span></code></a> value maps the <code class="xref py py-attr docutils literal notranslate"><span class="pre">winerror</span></code> value to
corresponding <code class="docutils literal notranslate"><span class="pre">errno.h</span></code> values. This is a subclass of <a class="reference internal" href="#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Previous versions put the <code class="xref c c-func docutils literal notranslate"><span class="pre">GetLastError()</span></code> codes into <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-attr docutils literal notranslate"><span class="pre">errno</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ZeroDivisionError">
<em class="property">exception </em><code class="descname">ZeroDivisionError</code><a class="headerlink" href="#exceptions.ZeroDivisionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the second argument of a division or modulo operation is zero.  The
associated value is a string indicating the type of the operands and the
operation.</p>
</dd></dl>

<p>The following exceptions are used as warning categories; see the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a>
module for more information.</p>
<dl class="exception">
<dt id="exceptions.Warning">
<em class="property">exception </em><code class="descname">Warning</code><a class="headerlink" href="#exceptions.Warning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warning categories.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UserWarning">
<em class="property">exception </em><code class="descname">UserWarning</code><a class="headerlink" href="#exceptions.UserWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings generated by user code.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.DeprecationWarning">
<em class="property">exception </em><code class="descname">DeprecationWarning</code><a class="headerlink" href="#exceptions.DeprecationWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about deprecated features.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.PendingDeprecationWarning">
<em class="property">exception </em><code class="descname">PendingDeprecationWarning</code><a class="headerlink" href="#exceptions.PendingDeprecationWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about features which will be deprecated in the future.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.SyntaxWarning">
<em class="property">exception </em><code class="descname">SyntaxWarning</code><a class="headerlink" href="#exceptions.SyntaxWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about dubious syntax.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.RuntimeWarning">
<em class="property">exception </em><code class="descname">RuntimeWarning</code><a class="headerlink" href="#exceptions.RuntimeWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about dubious runtime behavior.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.FutureWarning">
<em class="property">exception </em><code class="descname">FutureWarning</code><a class="headerlink" href="#exceptions.FutureWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about constructs that will change semantically in the
future.</p>
</dd></dl>

<dl class="exception">
<dt id="exceptions.ImportWarning">
<em class="property">exception </em><code class="descname">ImportWarning</code><a class="headerlink" href="#exceptions.ImportWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings about probable mistakes in module imports.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="exceptions.UnicodeWarning">
<em class="property">exception </em><code class="descname">UnicodeWarning</code><a class="headerlink" href="#exceptions.UnicodeWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for warnings related to Unicode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<div class="section" id="exception-hierarchy">
<h2>6.1. Exception hierarchy<a class="headerlink" href="#exception-hierarchy" title="Permalink to this headline">¶</a></h2>
<p>The class hierarchy for built-in exceptions is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ne">BaseException</span>
 <span class="o">+--</span> <span class="ne">SystemExit</span>
 <span class="o">+--</span> <span class="ne">KeyboardInterrupt</span>
 <span class="o">+--</span> <span class="ne">GeneratorExit</span>
 <span class="o">+--</span> <span class="ne">Exception</span>
      <span class="o">+--</span> <span class="ne">StopIteration</span>
      <span class="o">+--</span> <span class="n">StandardError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">BufferError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">ArithmeticError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">FloatingPointError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">OverflowError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">ZeroDivisionError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">AssertionError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">AttributeError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">EnvironmentError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">IOError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">OSError</span>
      <span class="o">|</span>    <span class="o">|</span>         <span class="o">+--</span> <span class="ne">WindowsError</span> <span class="p">(</span><span class="n">Windows</span><span class="p">)</span>
      <span class="o">|</span>    <span class="o">|</span>         <span class="o">+--</span> <span class="ne">VMSError</span> <span class="p">(</span><span class="n">VMS</span><span class="p">)</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">EOFError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">ImportError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">LookupError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">IndexError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">KeyError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">MemoryError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">NameError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">UnboundLocalError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">ReferenceError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">RuntimeError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">NotImplementedError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">SyntaxError</span>
      <span class="o">|</span>    <span class="o">|</span>    <span class="o">+--</span> <span class="ne">IndentationError</span>
      <span class="o">|</span>    <span class="o">|</span>         <span class="o">+--</span> <span class="ne">TabError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">SystemError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">TypeError</span>
      <span class="o">|</span>    <span class="o">+--</span> <span class="ne">ValueError</span>
      <span class="o">|</span>         <span class="o">+--</span> <span class="ne">UnicodeError</span>
      <span class="o">|</span>              <span class="o">+--</span> <span class="ne">UnicodeDecodeError</span>
      <span class="o">|</span>              <span class="o">+--</span> <span class="ne">UnicodeEncodeError</span>
      <span class="o">|</span>              <span class="o">+--</span> <span class="ne">UnicodeTranslateError</span>
      <span class="o">+--</span> <span class="ne">Warning</span>
           <span class="o">+--</span> <span class="ne">DeprecationWarning</span>
           <span class="o">+--</span> <span class="ne">PendingDeprecationWarning</span>
           <span class="o">+--</span> <span class="ne">RuntimeWarning</span>
           <span class="o">+--</span> <span class="ne">SyntaxWarning</span>
           <span class="o">+--</span> <span class="ne">UserWarning</span>
           <span class="o">+--</span> <span class="ne">FutureWarning</span>
	   <span class="o">+--</span> <span class="ne">ImportWarning</span>
	   <span class="o">+--</span> <span class="ne">UnicodeWarning</span>
	   <span class="o">+--</span> <span class="ne">BytesWarning</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">6. Built-in Exceptions</a><ul>
<li><a class="reference internal" href="#exception-hierarchy">6.1. Exception hierarchy</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="stdtypes.html"
                        title="previous chapter">5. Built-in Types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="strings.html"
                        title="next chapter">7. String Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/exceptions.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="strings.html" title="7. String Services"
             >next</a> |</li>
        <li class="right" >
          <a href="stdtypes.html" title="5. Built-in Types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\bZ�N�f�fhtml/library/fcntl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.10. fcntl — The fcntl and ioctl system calls &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.11. pipes — Interface to shell pipelines" href="pipes.html" />
    <link rel="prev" title="36.9. pty — Pseudo-terminal utilities" href="pty.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fcntl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pipes.html" title="36.11. pipes — Interface to shell pipelines"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pty.html" title="36.9. pty — Pseudo-terminal utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fcntl">
<span id="fcntl-the-fcntl-and-ioctl-system-calls"></span><h1>36.10. <a class="reference internal" href="#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fcntl</span></code></a> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls<a class="headerlink" href="#module-fcntl" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module performs file control and I/O control on file descriptors. It is an
interface to the <code class="xref c c-func docutils literal notranslate"><span class="pre">fcntl()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> Unix routines.  For a
complete description of these calls, see <em class="manpage">fcntl(2)</em> and
<em class="manpage">ioctl(2)</em> Unix manual pages.</p>
<p>All functions in this module take a file descriptor <em>fd</em> as their first
argument.  This can be an integer file descriptor, such as returned by
<code class="docutils literal notranslate"><span class="pre">sys.stdin.fileno()</span></code>, or a file object, such as <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> itself, which
provides a <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> which returns a genuine file descriptor.</p>
<p>The module defines the following functions:</p>
<dl class="function">
<dt id="fcntl.fcntl">
<code class="descclassname">fcntl.</code><code class="descname">fcntl</code><span class="sig-paren">(</span><em>fd</em>, <em>op</em><span class="optional">[</span>, <em>arg</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fcntl.fcntl" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the operation <em>op</em> on file descriptor <em>fd</em> (file objects providing
a <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method are accepted as well).  The values used
for for <em>op</em> are operating system dependent, and are available as constants
in the <a class="reference internal" href="#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fcntl</span></code></a> module, using the same names as used in the relevant C
header files.  The argument <em>arg</em> is optional, and defaults to the integer
value <code class="docutils literal notranslate"><span class="pre">0</span></code>.  When present, it can either be an integer value, or a string.
With the argument missing or an integer value, the return value of this function
is the integer return value of the C <code class="xref c c-func docutils literal notranslate"><span class="pre">fcntl()</span></code> call.  When the argument is
a string it represents a binary structure, e.g. created by <a class="reference internal" href="struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">struct.pack()</span></code></a>.
The binary data is copied to a buffer whose address is passed to the C
<code class="xref c c-func docutils literal notranslate"><span class="pre">fcntl()</span></code> call.  The return value after a successful call is the contents
of the buffer, converted to a string object.  The length of the returned string
will be the same as the length of the <em>arg</em> argument.  This is limited to 1024
bytes.  If the information returned in the buffer by the operating system is
larger than 1024 bytes, this is most likely to result in a segmentation
violation or a more subtle data corruption.</p>
<p>If the <code class="xref c c-func docutils literal notranslate"><span class="pre">fcntl()</span></code> fails, an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="fcntl.ioctl">
<code class="descclassname">fcntl.</code><code class="descname">ioctl</code><span class="sig-paren">(</span><em>fd</em>, <em>op</em><span class="optional">[</span>, <em>arg</em><span class="optional">[</span>, <em>mutate_flag</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fcntl.ioctl" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is identical to the <a class="reference internal" href="#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl()</span></code></a> function, except that the
operations are typically defined in the library module <a class="reference internal" href="termios.html#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> and the
argument handling is even more complicated.</p>
<p>The op parameter is limited to values that can fit in 32-bits.
Additional constants of interest for use as the <em>op</em> argument can be
found in the <a class="reference internal" href="termios.html#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> module, under the same names as used in
the relevant C header files.</p>
<p>The parameter <em>arg</em> can be one of an integer, absent (treated identically to the
integer <code class="docutils literal notranslate"><span class="pre">0</span></code>), an object supporting the read-only buffer interface (most likely
a plain Python string) or an object supporting the read-write buffer interface.</p>
<p>In all but the last case, behaviour is as for the <a class="reference internal" href="#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl()</span></code></a>
function.</p>
<p>If a mutable buffer is passed, then the behaviour is determined by the value of
the <em>mutate_flag</em> parameter.</p>
<p>If it is false, the buffer’s mutability is ignored and behaviour is as for a
read-only buffer, except that the 1024 byte limit mentioned above is avoided –
so long as the buffer you pass is as least as long as what the operating system
wants to put there, things should work.</p>
<p>If <em>mutate_flag</em> is true, then the buffer is (in effect) passed to the
underlying <a class="reference internal" href="#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">ioctl()</span></code></a> system call, the latter’s return code is passed back to
the calling Python, and the buffer’s new contents reflect the action of the
<a class="reference internal" href="#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">ioctl()</span></code></a>.  This is a slight simplification, because if the supplied buffer
is less than 1024 bytes long it is first copied into a static buffer 1024 bytes
long which is then passed to <a class="reference internal" href="#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">ioctl()</span></code></a> and copied back into the supplied
buffer.</p>
<p>If <em>mutate_flag</em> is not supplied, then from Python 2.5 it defaults to true,
which is a change from versions 2.3 and 2.4. Supply the argument explicitly if
version portability is a priority.</p>
<p>If the <code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> fails, an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception is raised.</p>
<p>An example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span><span class="o">,</span> <span class="nn">fcntl</span><span class="o">,</span> <span class="nn">struct</span><span class="o">,</span> <span class="nn">termios</span><span class="o">,</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">getpgrp</span><span class="p">()</span>
<span class="go">13341</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;h&#39;</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TIOCGPGRP</span><span class="p">,</span> <span class="s2">&quot;  &quot;</span><span class="p">))[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">13341</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;h&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fcntl</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TIOCGPGRP</span><span class="p">,</span> <span class="n">buf</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">buf</span>
<span class="go">array(&#39;h&#39;, [13341])</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="fcntl.flock">
<code class="descclassname">fcntl.</code><code class="descname">flock</code><span class="sig-paren">(</span><em>fd</em>, <em>op</em><span class="sig-paren">)</span><a class="headerlink" href="#fcntl.flock" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the lock operation <em>op</em> on file descriptor <em>fd</em> (file objects providing
a <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method are accepted as well). See the Unix manual
<em class="manpage">flock(2)</em> for details.  (On some systems, this function is emulated
using <code class="xref c c-func docutils literal notranslate"><span class="pre">fcntl()</span></code>.)</p>
<p>If the <code class="xref c c-func docutils literal notranslate"><span class="pre">flock()</span></code> fails, an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="fcntl.lockf">
<code class="descclassname">fcntl.</code><code class="descname">lockf</code><span class="sig-paren">(</span><em>fd</em>, <em>operation</em><span class="optional">[</span>, <em>length</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fcntl.lockf" title="Permalink to this definition">¶</a></dt>
<dd><p>This is essentially a wrapper around the <a class="reference internal" href="#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl()</span></code></a> locking calls.
<em>fd</em> is the file descriptor of the file to lock or unlock, and <em>operation</em>
is one of the following values:</p>
<ul class="simple">
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_UN</span></code> – unlock</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_SH</span></code> – acquire a shared lock</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_EX</span></code> – acquire an exclusive lock</li>
</ul>
<p>When <em>operation</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_SH</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_EX</span></code>, it can also be
bitwise ORed with <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_NB</span></code> to avoid blocking on lock acquisition.
If <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_NB</span></code> is used and the lock cannot be acquired, an
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> will be raised and the exception will have an <em>errno</em>
attribute set to <code class="xref py py-const docutils literal notranslate"><span class="pre">EACCES</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">EAGAIN</span></code> (depending on the
operating system; for portability, check for both values).  On at least some
systems, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOCK_EX</span></code> can only be used if the file descriptor refers to a
file opened for writing.</p>
<p><em>length</em> is the number of bytes to lock, <em>start</em> is the byte offset at
which the lock starts, relative to <em>whence</em>, and <em>whence</em> is as with
<a class="reference internal" href="io.html#io.IOBase.seek" title="io.IOBase.seek"><code class="xref py py-func docutils literal notranslate"><span class="pre">io.IOBase.seek()</span></code></a>, specifically:</p>
<ul class="simple">
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> – relative to the start of the file (<a class="reference internal" href="os.html#os.SEEK_SET" title="os.SEEK_SET"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code></a>)</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code> – relative to the current buffer position (<a class="reference internal" href="os.html#os.SEEK_CUR" title="os.SEEK_CUR"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code></a>)</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">2</span></code> – relative to the end of the file (<a class="reference internal" href="os.html#os.SEEK_END" title="os.SEEK_END"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.SEEK_END</span></code></a>)</li>
</ul>
<p>The default for <em>start</em> is 0, which means to start at the beginning of the file.
The default for <em>length</em> is 0 which means to lock to the end of the file.  The
default for <em>whence</em> is also 0.</p>
</dd></dl>

<p>Examples (all on a SVR4 compliant system):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span><span class="o">,</span> <span class="nn">fcntl</span><span class="o">,</span> <span class="nn">os</span>

<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="n">rv</span> <span class="o">=</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">fcntl</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_SETFL</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">O_NDELAY</span><span class="p">)</span>

<span class="n">lockdata</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;hhllhh&#39;</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_WRLCK</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="n">rv</span> <span class="o">=</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">fcntl</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">F_SETLKW</span><span class="p">,</span> <span class="n">lockdata</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that in the first example the return value variable <em>rv</em> will hold an
integer value; in the second example it will hold a string value.  The structure
lay-out for the <em>lockdata</em> variable is system dependent — therefore using the
<a class="reference internal" href="#fcntl.flock" title="fcntl.flock"><code class="xref py py-func docutils literal notranslate"><span class="pre">flock()</span></code></a> call may be better.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a></dt>
<dd>If the locking flags <a class="reference internal" href="os.html#os.O_SHLOCK" title="os.O_SHLOCK"><code class="xref py py-data docutils literal notranslate"><span class="pre">O_SHLOCK</span></code></a> and <a class="reference internal" href="os.html#os.O_EXLOCK" title="os.O_EXLOCK"><code class="xref py py-data docutils literal notranslate"><span class="pre">O_EXLOCK</span></code></a> are
present in the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module (on BSD only), the <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>
function provides an alternative to the <a class="reference internal" href="#fcntl.lockf" title="fcntl.lockf"><code class="xref py py-func docutils literal notranslate"><span class="pre">lockf()</span></code></a> and <a class="reference internal" href="#fcntl.flock" title="fcntl.flock"><code class="xref py py-func docutils literal notranslate"><span class="pre">flock()</span></code></a>
functions.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="pty.html"
                        title="previous chapter">36.9. <code class="docutils literal notranslate"><span class="pre">pty</span></code> — Pseudo-terminal utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pipes.html"
                        title="next chapter">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fcntl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pipes.html" title="36.11. pipes — Interface to shell pipelines"
             >next</a> |</li>
        <li class="right" >
          <a href="pty.html" title="36.9. pty — Pseudo-terminal utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\L��O�]�]html/library/filecmp.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.5. filecmp — File and Directory Comparisons &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.6. tempfile — Generate temporary files and directories" href="tempfile.html" />
    <link rel="prev" title="10.4. statvfs — Constants used with os.statvfs()" href="statvfs.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/filecmp.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tempfile.html" title="10.6. tempfile — Generate temporary files and directories"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="statvfs.html" title="10.4. statvfs — Constants used with os.statvfs()"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-filecmp">
<span id="filecmp-file-and-directory-comparisons"></span><h1>10.5. <a class="reference internal" href="#module-filecmp" title="filecmp: Compare files efficiently."><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code></a> — File and Directory Comparisons<a class="headerlink" href="#module-filecmp" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/filecmp.py">Lib/filecmp.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-filecmp" title="filecmp: Compare files efficiently."><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code></a> module defines functions to compare files and directories,
with various optional time/correctness trade-offs. For comparing files,
see also the <a class="reference internal" href="difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module.</p>
<p>The <a class="reference internal" href="#module-filecmp" title="filecmp: Compare files efficiently."><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="filecmp.cmp">
<code class="descclassname">filecmp.</code><code class="descname">cmp</code><span class="sig-paren">(</span><em>f1</em>, <em>f2</em><span class="optional">[</span>, <em>shallow</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.cmp" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare the files named <em>f1</em> and <em>f2</em>, returning <code class="docutils literal notranslate"><span class="pre">True</span></code> if they seem equal,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<p>Unless <em>shallow</em> is given and is false, files with identical <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>
signatures are taken to be equal.</p>
<p>Files that were compared using this function will not be compared again unless
their <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> signature changes.</p>
<p>Note that no external programs are called from this function, giving it
portability and efficiency.</p>
</dd></dl>

<dl class="function">
<dt id="filecmp.cmpfiles">
<code class="descclassname">filecmp.</code><code class="descname">cmpfiles</code><span class="sig-paren">(</span><em>dir1</em>, <em>dir2</em>, <em>common</em><span class="optional">[</span>, <em>shallow</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.cmpfiles" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare the files in the two directories <em>dir1</em> and <em>dir2</em> whose names are
given by <em>common</em>.</p>
<p>Returns three lists of file names: <em>match</em>, <em>mismatch</em>,
<em>errors</em>.  <em>match</em> contains the list of files that match, <em>mismatch</em> contains
the names of those that don’t, and <em>errors</em> lists the names of files which
could not be compared.  Files are listed in <em>errors</em> if they don’t exist in
one of the directories, the user lacks permission to read them or if the
comparison could not be done for some other reason.</p>
<p>The <em>shallow</em> parameter has the same meaning and default value as for
<a class="reference internal" href="#filecmp.cmp" title="filecmp.cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">filecmp.cmp()</span></code></a>.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">cmpfiles('a',</span> <span class="pre">'b',</span> <span class="pre">['c',</span> <span class="pre">'d/e'])</span></code> will compare <code class="docutils literal notranslate"><span class="pre">a/c</span></code> with
<code class="docutils literal notranslate"><span class="pre">b/c</span></code> and <code class="docutils literal notranslate"><span class="pre">a/d/e</span></code> with <code class="docutils literal notranslate"><span class="pre">b/d/e</span></code>.  <code class="docutils literal notranslate"><span class="pre">'c'</span></code> and <code class="docutils literal notranslate"><span class="pre">'d/e'</span></code> will each be in
one of the three returned lists.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">filecmp</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filecmp</span><span class="o">.</span><span class="n">cmp</span><span class="p">(</span><span class="s1">&#39;undoc.rst&#39;</span><span class="p">,</span> <span class="s1">&#39;undoc.rst&#39;</span><span class="p">)</span> 
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filecmp</span><span class="o">.</span><span class="n">cmp</span><span class="p">(</span><span class="s1">&#39;undoc.rst&#39;</span><span class="p">,</span> <span class="s1">&#39;index.rst&#39;</span><span class="p">)</span> 
<span class="go">False</span>
</pre></div>
</div>
<div class="section" id="the-dircmp-class">
<span id="dircmp-objects"></span><h2>10.5.1. The <a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> class<a class="headerlink" href="#the-dircmp-class" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> instances are built using this constructor:</p>
<dl class="class">
<dt id="filecmp.dircmp">
<em class="property">class </em><code class="descclassname">filecmp.</code><code class="descname">dircmp</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="optional">[</span>, <em>ignore</em><span class="optional">[</span>, <em>hide</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.dircmp" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a new directory comparison object, to compare the directories <em>a</em> and
<em>b</em>. <em>ignore</em> is a list of names to ignore, and defaults to <code class="docutils literal notranslate"><span class="pre">['RCS',</span> <span class="pre">'CVS',</span>
<span class="pre">'tags']</span></code>. <em>hide</em> is a list of names to hide, and defaults to <code class="docutils literal notranslate"><span class="pre">[os.curdir,</span>
<span class="pre">os.pardir]</span></code>.</p>
<p>The <a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> class compares files by doing <em>shallow</em> comparisons
as described for <a class="reference internal" href="#filecmp.cmp" title="filecmp.cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">filecmp.cmp()</span></code></a>.</p>
<p>The <a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> class provides the following methods:</p>
<dl class="method">
<dt id="filecmp.dircmp.report">
<code class="descname">report</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.dircmp.report" title="Permalink to this definition">¶</a></dt>
<dd><p>Print (to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>) a comparison between <em>a</em> and <em>b</em>.</p>
</dd></dl>

<dl class="method">
<dt id="filecmp.dircmp.report_partial_closure">
<code class="descname">report_partial_closure</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.dircmp.report_partial_closure" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a comparison between <em>a</em> and <em>b</em> and common immediate
subdirectories.</p>
</dd></dl>

<dl class="method">
<dt id="filecmp.dircmp.report_full_closure">
<code class="descname">report_full_closure</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#filecmp.dircmp.report_full_closure" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a comparison between <em>a</em> and <em>b</em> and common subdirectories
(recursively).</p>
</dd></dl>

<p>The <a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> class offers a number of interesting attributes that may be
used to get various bits of information about the directory trees being
compared.</p>
<p>Note that via <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> hooks, all attributes are computed lazily,
so there is no speed penalty if only those attributes which are lightweight
to compute are used.</p>
<dl class="attribute">
<dt id="filecmp.dircmp.left">
<code class="descname">left</code><a class="headerlink" href="#filecmp.dircmp.left" title="Permalink to this definition">¶</a></dt>
<dd><p>The directory <em>a</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.right">
<code class="descname">right</code><a class="headerlink" href="#filecmp.dircmp.right" title="Permalink to this definition">¶</a></dt>
<dd><p>The directory <em>b</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.left_list">
<code class="descname">left_list</code><a class="headerlink" href="#filecmp.dircmp.left_list" title="Permalink to this definition">¶</a></dt>
<dd><p>Files and subdirectories in <em>a</em>, filtered by <em>hide</em> and <em>ignore</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.right_list">
<code class="descname">right_list</code><a class="headerlink" href="#filecmp.dircmp.right_list" title="Permalink to this definition">¶</a></dt>
<dd><p>Files and subdirectories in <em>b</em>, filtered by <em>hide</em> and <em>ignore</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.common">
<code class="descname">common</code><a class="headerlink" href="#filecmp.dircmp.common" title="Permalink to this definition">¶</a></dt>
<dd><p>Files and subdirectories in both <em>a</em> and <em>b</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.left_only">
<code class="descname">left_only</code><a class="headerlink" href="#filecmp.dircmp.left_only" title="Permalink to this definition">¶</a></dt>
<dd><p>Files and subdirectories only in <em>a</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.right_only">
<code class="descname">right_only</code><a class="headerlink" href="#filecmp.dircmp.right_only" title="Permalink to this definition">¶</a></dt>
<dd><p>Files and subdirectories only in <em>b</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.common_dirs">
<code class="descname">common_dirs</code><a class="headerlink" href="#filecmp.dircmp.common_dirs" title="Permalink to this definition">¶</a></dt>
<dd><p>Subdirectories in both <em>a</em> and <em>b</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.common_files">
<code class="descname">common_files</code><a class="headerlink" href="#filecmp.dircmp.common_files" title="Permalink to this definition">¶</a></dt>
<dd><p>Files in both <em>a</em> and <em>b</em></p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.common_funny">
<code class="descname">common_funny</code><a class="headerlink" href="#filecmp.dircmp.common_funny" title="Permalink to this definition">¶</a></dt>
<dd><p>Names in both <em>a</em> and <em>b</em>, such that the type differs between the
directories, or names for which <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> reports an error.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.same_files">
<code class="descname">same_files</code><a class="headerlink" href="#filecmp.dircmp.same_files" title="Permalink to this definition">¶</a></dt>
<dd><p>Files which are identical in both <em>a</em> and <em>b</em>, using the class’s
file comparison operator.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.diff_files">
<code class="descname">diff_files</code><a class="headerlink" href="#filecmp.dircmp.diff_files" title="Permalink to this definition">¶</a></dt>
<dd><p>Files which are in both <em>a</em> and <em>b</em>, whose contents differ according
to the class’s file comparison operator.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.funny_files">
<code class="descname">funny_files</code><a class="headerlink" href="#filecmp.dircmp.funny_files" title="Permalink to this definition">¶</a></dt>
<dd><p>Files which are in both <em>a</em> and <em>b</em>, but could not be compared.</p>
</dd></dl>

<dl class="attribute">
<dt id="filecmp.dircmp.subdirs">
<code class="descname">subdirs</code><a class="headerlink" href="#filecmp.dircmp.subdirs" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping names in <a class="reference internal" href="#filecmp.dircmp.common_dirs" title="filecmp.dircmp.common_dirs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">common_dirs</span></code></a> to <a class="reference internal" href="#filecmp.dircmp" title="filecmp.dircmp"><code class="xref py py-class docutils literal notranslate"><span class="pre">dircmp</span></code></a> objects.</p>
</dd></dl>

</dd></dl>

<p>Here is a simplified example of using the <code class="docutils literal notranslate"><span class="pre">subdirs</span></code> attribute to search
recursively through two directories to show common different files:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">filecmp</span> <span class="k">import</span> <span class="n">dircmp</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">print_diff_files</span><span class="p">(</span><span class="n">dcmp</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">dcmp</span><span class="o">.</span><span class="n">diff_files</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;diff_file </span><span class="si">%s</span><span class="s2"> found in </span><span class="si">%s</span><span class="s2"> and </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">dcmp</span><span class="o">.</span><span class="n">left</span><span class="p">,</span>
<span class="gp">... </span>              <span class="n">dcmp</span><span class="o">.</span><span class="n">right</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">sub_dcmp</span> <span class="ow">in</span> <span class="n">dcmp</span><span class="o">.</span><span class="n">subdirs</span><span class="o">.</span><span class="n">values</span><span class="p">():</span>
<span class="gp">... </span>        <span class="n">print_diff_files</span><span class="p">(</span><span class="n">sub_dcmp</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dcmp</span> <span class="o">=</span> <span class="n">dircmp</span><span class="p">(</span><span class="s1">&#39;dir1&#39;</span><span class="p">,</span> <span class="s1">&#39;dir2&#39;</span><span class="p">)</span> 
<span class="gp">&gt;&gt;&gt; </span><span class="n">print_diff_files</span><span class="p">(</span><span class="n">dcmp</span><span class="p">)</span> 
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a><ul>
<li><a class="reference internal" href="#the-dircmp-class">10.5.1. The <code class="docutils literal notranslate"><span class="pre">dircmp</span></code> class</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="statvfs.html"
                        title="previous chapter">10.4. <code class="docutils literal notranslate"><span class="pre">statvfs</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tempfile.html"
                        title="next chapter">10.6. <code class="docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/filecmp.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tempfile.html" title="10.6. tempfile — Generate temporary files and directories"
             >next</a> |</li>
        <li class="right" >
          <a href="statvfs.html" title="10.4. statvfs — Constants used with os.statvfs()"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\l�R��%�%html/library/fileformats.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13. File Formats &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.1. csv — CSV File Reading and Writing" href="csv.html" />
    <link rel="prev" title="12.5. tarfile — Read and write tar archive files" href="tarfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fileformats.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="csv.html" title="13.1. csv — CSV File Reading and Writing"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tarfile.html" title="12.5. tarfile — Read and write tar archive files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="file-formats">
<span id="fileformats"></span><h1>13. File Formats<a class="headerlink" href="#file-formats" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter parse various miscellaneous file formats
that aren’t markup languages or are related to e-mail.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="csv.html">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a><ul>
<li class="toctree-l2"><a class="reference internal" href="csv.html#module-contents">13.1.1. Module Contents</a></li>
<li class="toctree-l2"><a class="reference internal" href="csv.html#dialects-and-formatting-parameters">13.1.2. Dialects and Formatting Parameters</a></li>
<li class="toctree-l2"><a class="reference internal" href="csv.html#reader-objects">13.1.3. Reader Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="csv.html#writer-objects">13.1.4. Writer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="csv.html#examples">13.1.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="configparser.html">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a><ul>
<li class="toctree-l2"><a class="reference internal" href="configparser.html#rawconfigparser-objects">13.2.1. RawConfigParser Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="configparser.html#configparser-objects">13.2.2. ConfigParser Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="configparser.html#safeconfigparser-objects">13.2.3. SafeConfigParser Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="configparser.html#examples">13.2.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="robotparser.html">13.3. <code class="docutils literal notranslate"><span class="pre">robotparser</span></code> —  Parser for robots.txt</a></li>
<li class="toctree-l1"><a class="reference internal" href="netrc.html">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a><ul>
<li class="toctree-l2"><a class="reference internal" href="netrc.html#netrc-objects">13.4.1. netrc Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xdrlib.html">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xdrlib.html#packer-objects">13.5.1. Packer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xdrlib.html#unpacker-objects">13.5.2. Unpacker Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xdrlib.html#exceptions">13.5.3. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="plistlib.html">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="plistlib.html#examples">13.6.1. Examples</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tarfile.html"
                        title="previous chapter">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="csv.html"
                        title="next chapter">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fileformats.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="csv.html" title="13.1. csv — CSV File Reading and Writing"
             >next</a> |</li>
        <li class="right" >
          <a href="tarfile.html" title="12.5. tarfile — Read and write tar archive files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\~	\�i�ihtml/library/fileinput.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.2. fileinput — Iterate over lines from multiple input streams &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.3. stat — Interpreting stat() results" href="stat.html" />
    <link rel="prev" title="10.1. os.path — Common pathname manipulations" href="os.path.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fileinput.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stat.html" title="10.3. stat — Interpreting stat() results"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="os.path.html" title="10.1. os.path — Common pathname manipulations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fileinput">
<span id="fileinput-iterate-over-lines-from-multiple-input-streams"></span><h1>10.2. <a class="reference internal" href="#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a> — Iterate over lines from multiple input streams<a class="headerlink" href="#module-fileinput" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/fileinput.py">Lib/fileinput.py</a></p>
<hr class="docutils" />
<p>This module implements a helper class and functions to quickly write a
loop over standard input or a list of files. If you just want to read or
write one file see <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>
<p>The typical use is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">fileinput</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">fileinput</span><span class="o">.</span><span class="n">input</span><span class="p">():</span>
    <span class="n">process</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<p>This iterates over the lines of all files listed in <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>, defaulting
to <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> if the list is empty.  If a filename is <code class="docutils literal notranslate"><span class="pre">'-'</span></code>, it is also
replaced by <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>.  To specify an alternative list of filenames, pass it
as the first argument to <a class="reference internal" href="#fileinput.input" title="fileinput.input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a>.  A single file name is also allowed.</p>
<p>All files are opened in text mode by default, but you can override this by
specifying the <em>mode</em> parameter in the call to <a class="reference internal" href="#fileinput.input" title="fileinput.input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> or
<a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput()</span></code></a>.  If an I/O error occurs during opening or reading a file,
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> is used more than once, the second and further use will return
no lines, except perhaps for interactive use, or if it has been explicitly reset
(e.g. using <code class="docutils literal notranslate"><span class="pre">sys.stdin.seek(0)</span></code>).</p>
<p>Empty files are opened and immediately closed; the only time their presence in
the list of filenames is noticeable at all is when the last file opened is
empty.</p>
<p>Lines are returned with any newlines intact, which means that the last line in
a file may not have one.</p>
<p>You can control how files are opened by providing an opening hook via the
<em>openhook</em> parameter to <a class="reference internal" href="#fileinput.input" title="fileinput.input"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileinput.input()</span></code></a> or <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput()</span></code></a>. The
hook must be a function that takes two arguments, <em>filename</em> and <em>mode</em>, and
returns an accordingly opened file-like object. Two useful hooks are already
provided by this module.</p>
<p>The following function is the primary interface of this module:</p>
<dl class="function">
<dt id="fileinput.input">
<code class="descclassname">fileinput.</code><code class="descname">input</code><span class="sig-paren">(</span><span class="optional">[</span><em>files</em><span class="optional">[</span>, <em>inplace</em><span class="optional">[</span>, <em>backup</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>openhook</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.input" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an instance of the <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code></a> class.  The instance will be used
as global state for the functions of this module, and is also returned to use
during iteration.  The parameters to this function will be passed along to the
constructor of the <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code></a> class.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>mode</em> and <em>openhook</em> parameters.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.12: </span>The <em>bufsize</em> parameter is no longer used.</p>
</div>
</dd></dl>

<p>The following functions use the global state created by <a class="reference internal" href="#fileinput.input" title="fileinput.input"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileinput.input()</span></code></a>;
if there is no active state, <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<dl class="function">
<dt id="fileinput.filename">
<code class="descclassname">fileinput.</code><code class="descname">filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the file currently being read.  Before the first line has
been read, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.fileno">
<code class="descclassname">fileinput.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the integer “file descriptor” for the current file. When no file is
opened (before the first line and between files), returns <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="fileinput.lineno">
<code class="descclassname">fileinput.</code><code class="descname">lineno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the cumulative line number of the line that has just been read.  Before
the first line has been read, returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.  After the last line of the last
file has been read, returns the line number of that line.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.filelineno">
<code class="descclassname">fileinput.</code><code class="descname">filelineno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.filelineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the line number in the current file.  Before the first line has been
read, returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.  After the last line of the last file has been read,
returns the line number of that line within the file.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.isfirstline">
<code class="descclassname">fileinput.</code><code class="descname">isfirstline</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.isfirstline" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the line just read is the first line of its file, otherwise
returns false.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.isstdin">
<code class="descclassname">fileinput.</code><code class="descname">isstdin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.isstdin" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the last line was read from <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, otherwise returns
false.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.nextfile">
<code class="descclassname">fileinput.</code><code class="descname">nextfile</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.nextfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the current file so that the next iteration will read the first line from
the next file (if any); lines not read from the file will not count towards the
cumulative line count.  The filename is not changed until after the first line
of the next file has been read.  Before the first line has been read, this
function has no effect; it cannot be used to skip the first file.  After the
last line of the last file has been read, this function has no effect.</p>
</dd></dl>

<dl class="function">
<dt id="fileinput.close">
<code class="descclassname">fileinput.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the sequence.</p>
</dd></dl>

<p>The class which implements the sequence behavior provided by the module is
available for subclassing as well:</p>
<dl class="class">
<dt id="fileinput.FileInput">
<em class="property">class </em><code class="descclassname">fileinput.</code><code class="descname">FileInput</code><span class="sig-paren">(</span><span class="optional">[</span><em>files</em><span class="optional">[</span>, <em>inplace</em><span class="optional">[</span>, <em>backup</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>openhook</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.FileInput" title="Permalink to this definition">¶</a></dt>
<dd><p>Class <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code></a> is the implementation; its methods <a class="reference internal" href="#fileinput.filename" title="fileinput.filename"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filename()</span></code></a>,
<a class="reference internal" href="#fileinput.fileno" title="fileinput.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a>, <a class="reference internal" href="#fileinput.lineno" title="fileinput.lineno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">lineno()</span></code></a>, <a class="reference internal" href="#fileinput.filelineno" title="fileinput.filelineno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filelineno()</span></code></a>, <a class="reference internal" href="#fileinput.isfirstline" title="fileinput.isfirstline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isfirstline()</span></code></a>,
<a class="reference internal" href="#fileinput.isstdin" title="fileinput.isstdin"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isstdin()</span></code></a>, <a class="reference internal" href="#fileinput.nextfile" title="fileinput.nextfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">nextfile()</span></code></a> and <a class="reference internal" href="#fileinput.close" title="fileinput.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> correspond to the
functions of the same name in the module. In addition it has a
<a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method which returns the next input line,
and a <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method which implements the sequence behavior.
The sequence must be accessed in strictly sequential order; random access
and <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> cannot be mixed.</p>
<p>With <em>mode</em> you can specify which file mode will be passed to <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>. It
must be one of <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'rU'</span></code>, <code class="docutils literal notranslate"><span class="pre">'U'</span></code> and <code class="docutils literal notranslate"><span class="pre">'rb'</span></code>.</p>
<p>The <em>openhook</em>, when given, must be a function that takes two arguments,
<em>filename</em> and <em>mode</em>, and returns an accordingly opened file-like object. You
cannot use <em>inplace</em> and <em>openhook</em> together.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>mode</em> and <em>openhook</em> parameters.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.12: </span>The <em>bufsize</em> parameter is no longer used.</p>
</div>
</dd></dl>

<p><strong>Optional in-place filtering:</strong> if the keyword argument <code class="docutils literal notranslate"><span class="pre">inplace=1</span></code> is passed
to <a class="reference internal" href="#fileinput.input" title="fileinput.input"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileinput.input()</span></code></a> or to the <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code></a> constructor, the file is
moved to a backup file and standard output is directed to the input file (if a
file of the same name as the backup file already exists, it will be replaced
silently).  This makes it possible to write a filter that rewrites its input
file in place.  If the <em>backup</em> parameter is given (typically as
<code class="docutils literal notranslate"><span class="pre">backup='.&lt;some</span> <span class="pre">extension&gt;'</span></code>), it specifies the extension for the backup file,
and the backup file remains around; by default, the extension is <code class="docutils literal notranslate"><span class="pre">'.bak'</span></code> and
it is deleted when the output file is closed.  In-place filtering is disabled
when standard input is read.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The current implementation does not work for MS-DOS 8+3 filesystems.</p>
</div>
<p>The two following opening hooks are provided by this module:</p>
<dl class="function">
<dt id="fileinput.hook_compressed">
<code class="descclassname">fileinput.</code><code class="descname">hook_compressed</code><span class="sig-paren">(</span><em>filename</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.hook_compressed" title="Permalink to this definition">¶</a></dt>
<dd><p>Transparently opens files compressed with gzip and bzip2 (recognized by the
extensions <code class="docutils literal notranslate"><span class="pre">'.gz'</span></code> and <code class="docutils literal notranslate"><span class="pre">'.bz2'</span></code>) using the <a class="reference internal" href="gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> and <a class="reference internal" href="bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a>
modules.  If the filename extension is not <code class="docutils literal notranslate"><span class="pre">'.gz'</span></code> or <code class="docutils literal notranslate"><span class="pre">'.bz2'</span></code>, the file is
opened normally (ie, using <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> without any decompression).</p>
<p>Usage example:  <code class="docutils literal notranslate"><span class="pre">fi</span> <span class="pre">=</span> <span class="pre">fileinput.FileInput(openhook=fileinput.hook_compressed)</span></code></p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="fileinput.hook_encoded">
<code class="descclassname">fileinput.</code><code class="descname">hook_encoded</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#fileinput.hook_encoded" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a hook which opens each file with <a class="reference internal" href="io.html#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">io.open()</span></code></a>, using the given
<em>encoding</em> to read the file.</p>
<p>Usage example: <code class="docutils literal notranslate"><span class="pre">fi</span> <span class="pre">=</span>
<span class="pre">fileinput.FileInput(openhook=fileinput.hook_encoded(&quot;iso-8859-1&quot;))</span></code></p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">With this hook, <a class="reference internal" href="#fileinput.FileInput" title="fileinput.FileInput"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code></a> might return Unicode strings depending on the
specified <em>encoding</em>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="os.path.html"
                        title="previous chapter">10.1. <code class="docutils literal notranslate"><span class="pre">os.path</span></code> — Common pathname manipulations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stat.html"
                        title="next chapter">10.3. <code class="docutils literal notranslate"><span class="pre">stat</span></code> — Interpreting <code class="docutils literal notranslate"><span class="pre">stat()</span></code> results</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fileinput.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stat.html" title="10.3. stat — Interpreting stat() results"
             >next</a> |</li>
        <li class="right" >
          <a href="os.path.html" title="10.1. os.path — Common pathname manipulations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\$��r*r*html/library/filesys.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10. File and Directory Access &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.1. os.path — Common pathname manipulations" href="os.path.html" />
    <link rel="prev" title="9.9. operator — Standard operators as functions" href="operator.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/filesys.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="os.path.html" title="10.1. os.path — Common pathname manipulations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="operator.html" title="9.9. operator — Standard operators as functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="file-and-directory-access">
<span id="filesys"></span><h1>10. File and Directory Access<a class="headerlink" href="#file-and-directory-access" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter deal with disk files and directories.  For
example, there are modules for reading the properties of files, manipulating
paths in a portable way, and creating temporary files.  The full list of modules
in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="os.path.html">10.1. <code class="docutils literal notranslate"><span class="pre">os.path</span></code> — Common pathname manipulations</a></li>
<li class="toctree-l1"><a class="reference internal" href="fileinput.html">10.2. <code class="docutils literal notranslate"><span class="pre">fileinput</span></code> — Iterate over lines from multiple input streams</a></li>
<li class="toctree-l1"><a class="reference internal" href="stat.html">10.3. <code class="docutils literal notranslate"><span class="pre">stat</span></code> — Interpreting <code class="docutils literal notranslate"><span class="pre">stat()</span></code> results</a></li>
<li class="toctree-l1"><a class="reference internal" href="statvfs.html">10.4. <code class="docutils literal notranslate"><span class="pre">statvfs</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a></li>
<li class="toctree-l1"><a class="reference internal" href="filecmp.html">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a><ul>
<li class="toctree-l2"><a class="reference internal" href="filecmp.html#the-dircmp-class">10.5.1. The <code class="docutils literal notranslate"><span class="pre">dircmp</span></code> class</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tempfile.html">10.6. <code class="docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></li>
<li class="toctree-l1"><a class="reference internal" href="glob.html">10.7. <code class="docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></li>
<li class="toctree-l1"><a class="reference internal" href="fnmatch.html">10.8. <code class="docutils literal notranslate"><span class="pre">fnmatch</span></code> — Unix filename pattern matching</a></li>
<li class="toctree-l1"><a class="reference internal" href="linecache.html">10.9. <code class="docutils literal notranslate"><span class="pre">linecache</span></code> — Random access to text lines</a></li>
<li class="toctree-l1"><a class="reference internal" href="shutil.html">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a><ul>
<li class="toctree-l2"><a class="reference internal" href="shutil.html#directory-and-files-operations">10.10.1. Directory and files operations</a><ul>
<li class="toctree-l3"><a class="reference internal" href="shutil.html#copytree-example">10.10.1.1. copytree example</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="shutil.html#archiving-operations">10.10.2. Archiving operations</a><ul>
<li class="toctree-l3"><a class="reference internal" href="shutil.html#archiving-example">10.10.2.1. Archiving example</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="dircache.html">10.11. <code class="docutils literal notranslate"><span class="pre">dircache</span></code> — Cached directory listings</a></li>
<li class="toctree-l1"><a class="reference internal" href="macpath.html">10.12. <code class="docutils literal notranslate"><span class="pre">macpath</span></code> — Mac OS 9 path manipulation functions</a></li>
</ul>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Section <a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a></dt>
<dd>A description of Python’s built-in file objects.</dd>
<dt>Module <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a></dt>
<dd>Operating system interfaces, including functions to work with files at a lower
level than the built-in file object.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="operator.html"
                        title="previous chapter">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="os.path.html"
                        title="next chapter">10.1. <code class="docutils literal notranslate"><span class="pre">os.path</span></code> — Common pathname manipulations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/filesys.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="os.path.html" title="10.1. os.path — Common pathname manipulations"
             >next</a> |</li>
        <li class="right" >
          <a href="operator.html" title="9.9. operator — Standard operators as functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��������html/library/fl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.4. fl — FORMS library for graphical user interfaces &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.7. fm — Font Manager interface" href="fm.html" />
    <link rel="prev" title="39.3. cd — CD-ROM access on SGI systems" href="cd.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fm.html" title="39.7. fm — Font Manager interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cd.html" title="39.3. cd — CD-ROM access on SGI systems"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fl">
<span id="fl-forms-library-for-graphical-user-interfaces"></span><h1>39.4. <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> — FORMS library for graphical user interfaces<a class="headerlink" href="#module-fl" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">This module provides an interface to the FORMS Library by Mark Overmars.  The
source for the library can be retrieved by anonymous FTP from host
<code class="docutils literal notranslate"><span class="pre">ftp.cs.ruu.nl</span></code>, directory <code class="file docutils literal notranslate"><span class="pre">SGI/FORMS</span></code>.  It was last tested with version
2.0b.</p>
<p>Most functions are literal translations of their C equivalents, dropping the
initial <code class="docutils literal notranslate"><span class="pre">fl_</span></code> from their name.  Constants used by the library are defined in
module <a class="reference internal" href="#module-FL" title="FL: Constants used with the fl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code></a> described below.</p>
<p>The creation of objects is a little different in Python than in C: instead of
the ‘current form’ maintained by the library to which new FORMS objects are
added, all functions that add a FORMS object to a form are methods of the Python
object representing the form. Consequently, there are no Python equivalents for
the C functions <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_addto_form()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_end_form()</span></code>, and the
equivalent of <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_bgn_form()</span></code> is called <a class="reference internal" href="#fl.make_form" title="fl.make_form"><code class="xref py py-func docutils literal notranslate"><span class="pre">fl.make_form()</span></code></a>.</p>
<p>Watch out for the somewhat confusing terminology: FORMS uses the word
<em class="dfn">object</em> for the buttons, sliders etc. that you can place in a form. In
Python, ‘object’ means any value.  The Python interface to FORMS introduces two
new Python object types: form objects (representing an entire form) and FORMS
objects (representing one button, slider etc.). Hopefully this isn’t too
confusing.</p>
<p>There are no ‘free objects’ in the Python interface to FORMS, nor is there an
easy way to add object classes written in Python.  The FORMS interface to GL
event handling is available, though, so you can mix FORMS with pure GL windows.</p>
<p><strong>Please note:</strong> importing <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> implies a call to the GL function
<code class="xref c c-func docutils literal notranslate"><span class="pre">foreground()</span></code> and to the FORMS routine <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_init()</span></code>.</p>
<div class="section" id="functions-defined-in-module-fl">
<span id="fl-functions"></span><h2>39.4.1. Functions Defined in Module <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a><a class="headerlink" href="#functions-defined-in-module-fl" title="Permalink to this headline">¶</a></h2>
<p>Module <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> defines the following functions.  For more information about
what they do, see the description of the equivalent C function in the FORMS
documentation:</p>
<dl class="function">
<dt id="fl.make_form">
<code class="descclassname">fl.</code><code class="descname">make_form</code><span class="sig-paren">(</span><em>type</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.make_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a form with given type, width and height.  This returns a <em class="dfn">form</em>
object, whose methods are described below.</p>
</dd></dl>

<dl class="function">
<dt id="fl.do_forms">
<code class="descclassname">fl.</code><code class="descname">do_forms</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.do_forms" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard FORMS main loop.  Returns a Python object representing the FORMS
object needing interaction, or the special value <code class="xref py py-const docutils literal notranslate"><span class="pre">FL.EVENT</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fl.check_forms">
<code class="descclassname">fl.</code><code class="descname">check_forms</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.check_forms" title="Permalink to this definition">¶</a></dt>
<dd><p>Check for FORMS events.  Returns what <a class="reference internal" href="#fl.do_forms" title="fl.do_forms"><code class="xref py py-func docutils literal notranslate"><span class="pre">do_forms()</span></code></a> above returns, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if there is no event that immediately needs interaction.</p>
</dd></dl>

<dl class="function">
<dt id="fl.set_event_call_back">
<code class="descclassname">fl.</code><code class="descname">set_event_call_back</code><span class="sig-paren">(</span><em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.set_event_call_back" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the event callback function.</p>
</dd></dl>

<dl class="function">
<dt id="fl.set_graphics_mode">
<code class="descclassname">fl.</code><code class="descname">set_graphics_mode</code><span class="sig-paren">(</span><em>rgbmode</em>, <em>doublebuffering</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.set_graphics_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the graphics modes.</p>
</dd></dl>

<dl class="function">
<dt id="fl.get_rgbmode">
<code class="descclassname">fl.</code><code class="descname">get_rgbmode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.get_rgbmode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current rgb mode.  This is the value of the C global variable
<code class="xref c c-data docutils literal notranslate"><span class="pre">fl_rgbmode</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fl.show_message">
<code class="descclassname">fl.</code><code class="descname">show_message</code><span class="sig-paren">(</span><em>str1</em>, <em>str2</em>, <em>str3</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.show_message" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a dialog box with a three-line message and an OK button.</p>
</dd></dl>

<dl class="function">
<dt id="fl.show_question">
<code class="descclassname">fl.</code><code class="descname">show_question</code><span class="sig-paren">(</span><em>str1</em>, <em>str2</em>, <em>str3</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.show_question" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a dialog box with a three-line message and YES and NO buttons. It returns
<code class="docutils literal notranslate"><span class="pre">1</span></code> if the user pressed YES, <code class="docutils literal notranslate"><span class="pre">0</span></code> if NO.</p>
</dd></dl>

<dl class="function">
<dt id="fl.show_choice">
<code class="descclassname">fl.</code><code class="descname">show_choice</code><span class="sig-paren">(</span><em>str1</em>, <em>str2</em>, <em>str3</em>, <em>but1</em><span class="optional">[</span>, <em>but2</em><span class="optional">[</span>, <em>but3</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.show_choice" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a dialog box with a three-line message and up to three buttons. It returns
the number of the button clicked by the user (<code class="docutils literal notranslate"><span class="pre">1</span></code>, <code class="docutils literal notranslate"><span class="pre">2</span></code> or <code class="docutils literal notranslate"><span class="pre">3</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="fl.show_input">
<code class="descclassname">fl.</code><code class="descname">show_input</code><span class="sig-paren">(</span><em>prompt</em>, <em>default</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.show_input" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a dialog box with a one-line prompt message and text field in which the
user can enter a string.  The second argument is the default input string.  It
returns the string value as edited by the user.</p>
</dd></dl>

<dl class="function">
<dt id="fl.show_file_selector">
<code class="descclassname">fl.</code><code class="descname">show_file_selector</code><span class="sig-paren">(</span><em>message</em>, <em>directory</em>, <em>pattern</em>, <em>default</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.show_file_selector" title="Permalink to this definition">¶</a></dt>
<dd><p>Show a dialog box in which the user can select a file.  It returns the absolute
filename selected by the user, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the user presses Cancel.</p>
</dd></dl>

<dl class="function">
<dt id="fl.get_directory">
<code class="descclassname">fl.</code><code class="descname">get_directory</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.get_directory" title="Permalink to this definition">¶</a></dt>
<dt id="fl.get_pattern">
<code class="descclassname">fl.</code><code class="descname">get_pattern</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.get_pattern" title="Permalink to this definition">¶</a></dt>
<dt id="fl.get_filename">
<code class="descclassname">fl.</code><code class="descname">get_filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.get_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions return the directory, pattern and filename (the tail part only)
selected by the user in the last <a class="reference internal" href="#fl.show_file_selector" title="fl.show_file_selector"><code class="xref py py-func docutils literal notranslate"><span class="pre">show_file_selector()</span></code></a> call.</p>
</dd></dl>

<dl class="function">
<dt id="fl.qdevice">
<code class="descclassname">fl.</code><code class="descname">qdevice</code><span class="sig-paren">(</span><em>dev</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.qdevice" title="Permalink to this definition">¶</a></dt>
<dt id="fl.unqdevice">
<code class="descclassname">fl.</code><code class="descname">unqdevice</code><span class="sig-paren">(</span><em>dev</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.unqdevice" title="Permalink to this definition">¶</a></dt>
<dt id="fl.isqueued">
<code class="descclassname">fl.</code><code class="descname">isqueued</code><span class="sig-paren">(</span><em>dev</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.isqueued" title="Permalink to this definition">¶</a></dt>
<dt id="fl.qtest">
<code class="descclassname">fl.</code><code class="descname">qtest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.qtest" title="Permalink to this definition">¶</a></dt>
<dt id="fl.qread">
<code class="descclassname">fl.</code><code class="descname">qread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.qread" title="Permalink to this definition">¶</a></dt>
<dt id="fl.qreset">
<code class="descclassname">fl.</code><code class="descname">qreset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.qreset" title="Permalink to this definition">¶</a></dt>
<dt id="fl.qenter">
<code class="descclassname">fl.</code><code class="descname">qenter</code><span class="sig-paren">(</span><em>dev</em>, <em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.qenter" title="Permalink to this definition">¶</a></dt>
<dt id="fl.get_mouse">
<code class="descclassname">fl.</code><code class="descname">get_mouse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.get_mouse" title="Permalink to this definition">¶</a></dt>
<dt id="fl.tie">
<code class="descclassname">fl.</code><code class="descname">tie</code><span class="sig-paren">(</span><em>button</em>, <em>valuator1</em>, <em>valuator2</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.tie" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions are the FORMS interfaces to the corresponding GL functions.  Use
these if you want to handle some GL events yourself when using
<code class="xref py py-func docutils literal notranslate"><span class="pre">fl.do_events()</span></code>.  When a GL event is detected that FORMS cannot handle,
<a class="reference internal" href="#fl.do_forms" title="fl.do_forms"><code class="xref py py-func docutils literal notranslate"><span class="pre">fl.do_forms()</span></code></a> returns the special value <code class="xref py py-const docutils literal notranslate"><span class="pre">FL.EVENT</span></code> and you should
call <a class="reference internal" href="#fl.qread" title="fl.qread"><code class="xref py py-func docutils literal notranslate"><span class="pre">fl.qread()</span></code></a> to read the event from the queue.  Don’t use the
equivalent GL functions!</p>
</dd></dl>

<dl class="function">
<dt id="fl.color">
<code class="descclassname">fl.</code><code class="descname">color</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.color" title="Permalink to this definition">¶</a></dt>
<dt id="fl.mapcolor">
<code class="descclassname">fl.</code><code class="descname">mapcolor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.mapcolor" title="Permalink to this definition">¶</a></dt>
<dt id="fl.getmcolor">
<code class="descclassname">fl.</code><code class="descname">getmcolor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.getmcolor" title="Permalink to this definition">¶</a></dt>
<dd><p>See the description in the FORMS documentation of <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_color()</span></code>,
<code class="xref c c-func docutils literal notranslate"><span class="pre">fl_mapcolor()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">fl_getmcolor()</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="form-objects">
<span id="id1"></span><h2>39.4.2. Form Objects<a class="headerlink" href="#form-objects" title="Permalink to this headline">¶</a></h2>
<p>Form objects (returned by <a class="reference internal" href="#fl.make_form" title="fl.make_form"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_form()</span></code></a> above) have the following methods.
Each method corresponds to a C function whose name is prefixed with <code class="docutils literal notranslate"><span class="pre">fl_</span></code>; and
whose first argument is a form pointer; please refer to the official FORMS
documentation for descriptions.</p>
<p>All the <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_*()</span></code> methods return a Python object representing the FORMS
object.  Methods of FORMS objects are described below.  Most kinds of FORMS
object also have some methods specific to that kind; these methods are listed
here.</p>
<dl class="method">
<dt id="fl.form.show_form">
<code class="descclassname">form.</code><code class="descname">show_form</code><span class="sig-paren">(</span><em>placement</em>, <em>bordertype</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.show_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Show the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.hide_form">
<code class="descclassname">form.</code><code class="descname">hide_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.hide_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Hide the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.redraw_form">
<code class="descclassname">form.</code><code class="descname">redraw_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.redraw_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Redraw the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.set_form_position">
<code class="descclassname">form.</code><code class="descname">set_form_position</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.set_form_position" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the form’s position.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.freeze_form">
<code class="descclassname">form.</code><code class="descname">freeze_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.freeze_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Freeze the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.unfreeze_form">
<code class="descclassname">form.</code><code class="descname">unfreeze_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.unfreeze_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Unfreeze the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.activate_form">
<code class="descclassname">form.</code><code class="descname">activate_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.activate_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Activate the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.deactivate_form">
<code class="descclassname">form.</code><code class="descname">deactivate_form</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.deactivate_form" title="Permalink to this definition">¶</a></dt>
<dd><p>Deactivate the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.bgn_group">
<code class="descclassname">form.</code><code class="descname">bgn_group</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.bgn_group" title="Permalink to this definition">¶</a></dt>
<dd><p>Begin a new group of objects; return a group object.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.end_group">
<code class="descclassname">form.</code><code class="descname">end_group</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.end_group" title="Permalink to this definition">¶</a></dt>
<dd><p>End the current group of objects.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.find_first">
<code class="descclassname">form.</code><code class="descname">find_first</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.find_first" title="Permalink to this definition">¶</a></dt>
<dd><p>Find the first object in the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.find_last">
<code class="descclassname">form.</code><code class="descname">find_last</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.find_last" title="Permalink to this definition">¶</a></dt>
<dd><p>Find the last object in the form.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_box">
<code class="descclassname">form.</code><code class="descname">add_box</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_box" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a box object to the form. No extra methods.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_text">
<code class="descclassname">form.</code><code class="descname">add_text</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a text object to the form. No extra methods.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_clock">
<code class="descclassname">form.</code><code class="descname">add_clock</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_clock" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a clock object to the form.  —  Method: <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_clock()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_button">
<code class="descclassname">form.</code><code class="descname">add_button</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_button" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a button object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_button()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_button()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_lightbutton">
<code class="descclassname">form.</code><code class="descname">add_lightbutton</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_lightbutton" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a lightbutton object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_button()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_button()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_roundbutton">
<code class="descclassname">form.</code><code class="descname">add_roundbutton</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_roundbutton" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a roundbutton object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_button()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_button()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_slider">
<code class="descclassname">form.</code><code class="descname">add_slider</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_slider" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a slider object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_value()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_slider_value()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_bounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_slider_bounds()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_return()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_size()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_precision()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_step()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_valslider">
<code class="descclassname">form.</code><code class="descname">add_valslider</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_valslider" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a valslider object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_value()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_slider_value()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_bounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_slider_bounds()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_return()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_size()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_precision()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_slider_step()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_dial">
<code class="descclassname">form.</code><code class="descname">add_dial</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_dial" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a dial object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_dial_value()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_dial_value()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_dial_bounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_dial_bounds()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_positioner">
<code class="descclassname">form.</code><code class="descname">add_positioner</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_positioner" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a positioner object to the form.  —  Methods:
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_positioner_xvalue()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_positioner_yvalue()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_positioner_xbounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_positioner_ybounds()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_positioner_xvalue()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_positioner_yvalue()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_positioner_xbounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_positioner_ybounds()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_counter">
<code class="descclassname">form.</code><code class="descname">add_counter</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_counter" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a counter object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_counter_value()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_counter_value()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_counter_bounds()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_counter_step()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_counter_precision()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_counter_return()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_input">
<code class="descclassname">form.</code><code class="descname">add_input</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_input" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an input object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_input()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_input()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_input_color()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_input_return()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_menu">
<code class="descclassname">form.</code><code class="descname">add_menu</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_menu" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a menu object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_menu()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_menu()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">addto_menu()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_choice">
<code class="descclassname">form.</code><code class="descname">add_choice</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_choice" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a choice object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_choice()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_choice()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_choice()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">addto_choice()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">replace_choice()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">delete_choice()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_choice_text()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_choice_fontsize()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_choice_fontstyle()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_browser">
<code class="descclassname">form.</code><code class="descname">add_browser</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_browser" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a browser object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_browser_topline()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_browser()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">addto_browser()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">insert_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">delete_browser_line()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">replace_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">load_browser()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_browser_maxline()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">select_browser_line()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">deselect_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">deselect_browser()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isselected_browser_line()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_browser()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_browser_fontsize()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_browser_fontstyle()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_browser_specialkey()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="fl.form.add_timer">
<code class="descclassname">form.</code><code class="descname">add_timer</code><span class="sig-paren">(</span><em>type</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#fl.form.add_timer" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a timer object to the form.  —  Methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_timer()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_timer()</span></code>.</p>
</dd></dl>

<p>Form objects have the following data attributes; see the FORMS documentation:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="24%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name</th>
<th class="head">C Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">window</span></code></td>
<td>int (read-only)</td>
<td>GL window id</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">w</span></code></td>
<td>float</td>
<td>form width</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">h</span></code></td>
<td>float</td>
<td>form height</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">x</span></code></td>
<td>float</td>
<td>form x origin</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">y</span></code></td>
<td>float</td>
<td>form y origin</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">deactivated</span></code></td>
<td>int</td>
<td>nonzero if form is deactivated</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">visible</span></code></td>
<td>int</td>
<td>nonzero if form is visible</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">frozen</span></code></td>
<td>int</td>
<td>nonzero if form is frozen</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">doublebuf</span></code></td>
<td>int</td>
<td>nonzero if double buffering on</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="forms-objects">
<span id="id2"></span><h2>39.4.3. FORMS Objects<a class="headerlink" href="#forms-objects" title="Permalink to this headline">¶</a></h2>
<p>Besides methods specific to particular kinds of FORMS objects, all FORMS objects
also have the following methods:</p>
<dl class="method">
<dt>
<code class="descname">FORMS object.set_call_back(function, argument)</code></dt>
<dd><p>Set the object’s callback function and argument.  When the object needs
interaction, the callback function will be called with two arguments: the
object, and the callback argument.  (FORMS objects without a callback function
are returned by <a class="reference internal" href="#fl.do_forms" title="fl.do_forms"><code class="xref py py-func docutils literal notranslate"><span class="pre">fl.do_forms()</span></code></a> or <a class="reference internal" href="#fl.check_forms" title="fl.check_forms"><code class="xref py py-func docutils literal notranslate"><span class="pre">fl.check_forms()</span></code></a> when they need
interaction.)  Call this method without arguments to remove the callback
function.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.delete_object()</code></dt>
<dd><p>Delete the object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.show_object()</code></dt>
<dd><p>Show the object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.hide_object()</code></dt>
<dd><p>Hide the object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.redraw_object()</code></dt>
<dd><p>Redraw the object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.freeze_object()</code></dt>
<dd><p>Freeze the object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">FORMS object.unfreeze_object()</code></dt>
<dd><p>Unfreeze the object.</p>
</dd></dl>

<p>FORMS objects have these data attributes; see the FORMS documentation:</p>
<table border="1" class="docutils">
<colgroup>
<col width="36%" />
<col width="31%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name</th>
<th class="head">C Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">objclass</span></code></td>
<td>int (read-only)</td>
<td>object class</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#type" title="type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a></td>
<td>int (read-only)</td>
<td>object type</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">boxtype</span></code></td>
<td>int</td>
<td>box type</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">x</span></code></td>
<td>float</td>
<td>x origin</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">y</span></code></td>
<td>float</td>
<td>y origin</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">w</span></code></td>
<td>float</td>
<td>width</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">h</span></code></td>
<td>float</td>
<td>height</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">col1</span></code></td>
<td>int</td>
<td>primary color</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">col2</span></code></td>
<td>int</td>
<td>secondary color</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">align</span></code></td>
<td>int</td>
<td>alignment</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">lcol</span></code></td>
<td>int</td>
<td>label color</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">lsize</span></code></td>
<td>float</td>
<td>label font size</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">label</span></code></td>
<td>string</td>
<td>label string</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">lstyle</span></code></td>
<td>int</td>
<td>label style</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">pushed</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">focus</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">belowmouse</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">frozen</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">active</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-attr docutils literal notranslate"><span class="pre">input</span></code></a></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">visible</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">radio</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">automatic</span></code></td>
<td>int (read-only)</td>
<td>(see FORMS docs)</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="module-FL">
<span id="fl-constants-used-with-the-fl-module"></span><h1>39.5. <a class="reference internal" href="#module-FL" title="FL: Constants used with the fl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code></a> — Constants used with the <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> module<a class="headerlink" href="#module-FL" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-FL" title="FL: Constants used with the fl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module defines symbolic constants needed to use the built-in module
<a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> (see above); they are equivalent to those defined in the C header file
<code class="docutils literal notranslate"><span class="pre">&lt;forms.h&gt;</span></code> except that the name prefix <code class="docutils literal notranslate"><span class="pre">FL_</span></code> is omitted.  Read the module
source for a complete list of the defined names.  Suggested use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">fl</span>
<span class="kn">from</span> <span class="nn">FL</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
</div>
<div class="section" id="module-flp">
<span id="flp-functions-for-loading-stored-forms-designs"></span><h1>39.6. <a class="reference internal" href="#module-flp" title="flp: Functions for loading stored FORMS designs. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">flp</span></code></a> — Functions for loading stored FORMS designs<a class="headerlink" href="#module-flp" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-flp" title="flp: Functions for loading stored FORMS designs. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">flp</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module defines functions that can read form definitions created by the
‘form designer’ (<strong class="program">fdesign</strong>) program that comes with the FORMS library
(see module <a class="reference internal" href="#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a> above).</p>
<p>For now, see the file <code class="file docutils literal notranslate"><span class="pre">flp.doc</span></code> in the Python library source directory for
a description.</p>
<p>XXX A complete description should be inserted here!</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a><ul>
<li><a class="reference internal" href="#functions-defined-in-module-fl">39.4.1. Functions Defined in Module <code class="docutils literal notranslate"><span class="pre">fl</span></code></a></li>
<li><a class="reference internal" href="#form-objects">39.4.2. Form Objects</a></li>
<li><a class="reference internal" href="#forms-objects">39.4.3. FORMS Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-FL">39.5. <code class="docutils literal notranslate"><span class="pre">FL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">fl</span></code> module</a></li>
<li><a class="reference internal" href="#module-flp">39.6. <code class="docutils literal notranslate"><span class="pre">flp</span></code> — Functions for loading stored FORMS designs</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cd.html"
                        title="previous chapter">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fm.html"
                        title="next chapter">39.7. <code class="docutils literal notranslate"><span class="pre">fm</span></code> — <em>Font Manager</em> interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fm.html" title="39.7. fm — Font Manager interface"
             >next</a> |</li>
        <li class="right" >
          <a href="cd.html" title="39.3. cd — CD-ROM access on SGI systems"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\T(��2�2html/library/fm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.7. fm — Font Manager interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.8. gl — Graphics Library interface" href="gl.html" />
    <link rel="prev" title="39.4. fl — FORMS library for graphical user interfaces" href="fl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gl.html" title="39.8. gl — Graphics Library interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fl.html" title="39.4. fl — FORMS library for graphical user interfaces"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fm">
<span id="fm-font-manager-interface"></span><h1>39.7. <a class="reference internal" href="#module-fm" title="fm: Font Manager interface for SGI workstations. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code></a> — <em>Font Manager</em> interface<a class="headerlink" href="#module-fm" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-fm" title="fm: Font Manager interface for SGI workstations. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">This module provides access to the IRIS <em>Font Manager</em> library.   It is
available only on Silicon Graphics machines. See also: <em>4Sight User’s Guide</em>,
section 1, chapter 5: “Using the IRIS Font Manager.”</p>
<p>This is not yet a full interface to the IRIS Font Manager. Among the unsupported
features are: matrix operations; cache operations; character operations (use
string operations instead); some details of font info; individual glyph metrics;
and printer matching.</p>
<p>It supports the following operations:</p>
<dl class="function">
<dt id="fm.init">
<code class="descclassname">fm.</code><code class="descname">init</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fm.init" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialization function. Calls <code class="xref c c-func docutils literal notranslate"><span class="pre">fminit()</span></code>. It is normally not necessary to
call this function, since it is called automatically the first time the
<a class="reference internal" href="#module-fm" title="fm: Font Manager interface for SGI workstations. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code></a> module is imported.</p>
</dd></dl>

<dl class="function">
<dt id="fm.findfont">
<code class="descclassname">fm.</code><code class="descname">findfont</code><span class="sig-paren">(</span><em>fontname</em><span class="sig-paren">)</span><a class="headerlink" href="#fm.findfont" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a font handle object. Calls <code class="docutils literal notranslate"><span class="pre">fmfindfont(fontname)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fm.enumerate">
<code class="descclassname">fm.</code><code class="descname">enumerate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fm.enumerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of available font names. This is an interface to
<code class="xref c c-func docutils literal notranslate"><span class="pre">fmenumerate()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fm.prstr">
<code class="descclassname">fm.</code><code class="descname">prstr</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#fm.prstr" title="Permalink to this definition">¶</a></dt>
<dd><p>Render a string using the current font (see the <code class="xref py py-func docutils literal notranslate"><span class="pre">setfont()</span></code> font handle
method below). Calls <code class="docutils literal notranslate"><span class="pre">fmprstr(string)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="fm.setpath">
<code class="descclassname">fm.</code><code class="descname">setpath</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#fm.setpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the font search path. Calls <code class="docutils literal notranslate"><span class="pre">fmsetpath(string)</span></code>. (XXX Does not work!?!)</p>
</dd></dl>

<dl class="function">
<dt id="fm.fontpath">
<code class="descclassname">fm.</code><code class="descname">fontpath</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fm.fontpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current font search path.</p>
</dd></dl>

<p>Font handle objects support the following operations:</p>
<dl class="method">
<dt>
<code class="descname">font handle.scalefont(factor)</code></dt>
<dd><p>Returns a handle for a scaled version of this font. Calls <code class="docutils literal notranslate"><span class="pre">fmscalefont(fh,</span>
<span class="pre">factor)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">font handle.setfont()</code></dt>
<dd><p>Makes this font the current font. Note: the effect is undone silently when the
font handle object is deleted. Calls <code class="docutils literal notranslate"><span class="pre">fmsetfont(fh)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">font handle.getfontname()</code></dt>
<dd><p>Returns this font’s name. Calls <code class="docutils literal notranslate"><span class="pre">fmgetfontname(fh)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">font handle.getcomment()</code></dt>
<dd><p>Returns the comment string associated with this font. Raises an exception if
there is none. Calls <code class="docutils literal notranslate"><span class="pre">fmgetcomment(fh)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">font handle.getfontinfo()</code></dt>
<dd><p>Returns a tuple giving some pertinent data about this font. This is an interface
to <code class="docutils literal notranslate"><span class="pre">fmgetfontinfo()</span></code>. The returned tuple contains the following numbers:
<code class="docutils literal notranslate"><span class="pre">(printermatched,</span> <span class="pre">fixed_width,</span> <span class="pre">xorig,</span> <span class="pre">yorig,</span> <span class="pre">xsize,</span> <span class="pre">ysize,</span> <span class="pre">height,</span> <span class="pre">nglyphs)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">font handle.getstrwidth(string)</code></dt>
<dd><p>Returns the width, in pixels, of <em>string</em> when drawn in this font. Calls
<code class="docutils literal notranslate"><span class="pre">fmgetstrwidth(fh,</span> <span class="pre">string)</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fl.html"
                        title="previous chapter">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gl.html"
                        title="next chapter">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gl.html" title="39.8. gl — Graphics Library interface"
             >next</a> |</li>
        <li class="right" >
          <a href="fl.html" title="39.4. fl — FORMS library for graphical user interfaces"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��t�?�?html/library/fnmatch.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.8. fnmatch — Unix filename pattern matching &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.9. linecache — Random access to text lines" href="linecache.html" />
    <link rel="prev" title="10.7. glob — Unix style pathname pattern expansion" href="glob.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fnmatch.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="linecache.html" title="10.9. linecache — Random access to text lines"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="glob.html" title="10.7. glob — Unix style pathname pattern expansion"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fnmatch">
<span id="fnmatch-unix-filename-pattern-matching"></span><h1>10.8. <a class="reference internal" href="#module-fnmatch" title="fnmatch: Unix shell style filename pattern matching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fnmatch</span></code></a> — Unix filename pattern matching<a class="headerlink" href="#module-fnmatch" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><p id="index-1"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/fnmatch.py">Lib/fnmatch.py</a></p>
<hr class="docutils" />
<p>This module provides support for Unix shell-style wildcards, which are <em>not</em> the
same as regular expressions (which are documented in the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module).  The
special characters used in shell-style wildcards are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Pattern</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">*</span></code></td>
<td>matches everything</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">?</span></code></td>
<td>matches any single character</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">[seq]</span></code></td>
<td>matches any character in <em>seq</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">[!seq]</span></code></td>
<td>matches any character not in <em>seq</em></td>
</tr>
</tbody>
</table>
<p>For a literal match, wrap the meta-characters in brackets.
For example, <code class="docutils literal notranslate"><span class="pre">'[?]'</span></code> matches the character <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.</p>
<p id="index-2">Note that the filename separator (<code class="docutils literal notranslate"><span class="pre">'/'</span></code> on Unix) is <em>not</em> special to this
module.  See module <a class="reference internal" href="glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> for pathname expansion (<a class="reference internal" href="glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> uses
<a class="reference internal" href="#fnmatch.filter" title="fnmatch.filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> to match pathname segments).  Similarly, filenames starting with
a period are not special for this module, and are matched by the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">?</span></code>
patterns.</p>
<dl class="function">
<dt id="fnmatch.fnmatch">
<code class="descclassname">fnmatch.</code><code class="descname">fnmatch</code><span class="sig-paren">(</span><em>filename</em>, <em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#fnmatch.fnmatch" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether the <em>filename</em> string matches the <em>pattern</em> string, returning
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.  Both parameters are case-normalized
using <a class="reference internal" href="os.path.html#os.path.normcase" title="os.path.normcase"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.normcase()</span></code></a>. <a class="reference internal" href="#fnmatch.fnmatchcase" title="fnmatch.fnmatchcase"><code class="xref py py-func docutils literal notranslate"><span class="pre">fnmatchcase()</span></code></a> can be used to perform a
case-sensitive comparison, regardless of whether that’s standard for the
operating system.</p>
<p>This example will print all file names in the current directory with the
extension <code class="docutils literal notranslate"><span class="pre">.txt</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">fnmatch</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">for</span> <span class="n">file</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">fnmatch</span><span class="o">.</span><span class="n">fnmatch</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="s1">&#39;*.txt&#39;</span><span class="p">):</span>
        <span class="nb">print</span> <span class="n">file</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="fnmatch.fnmatchcase">
<code class="descclassname">fnmatch.</code><code class="descname">fnmatchcase</code><span class="sig-paren">(</span><em>filename</em>, <em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#fnmatch.fnmatchcase" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether <em>filename</em> matches <em>pattern</em>, returning <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>; the comparison is case-sensitive and does not apply
<a class="reference internal" href="os.path.html#os.path.normcase" title="os.path.normcase"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.normcase()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="fnmatch.filter">
<code class="descclassname">fnmatch.</code><code class="descname">filter</code><span class="sig-paren">(</span><em>names</em>, <em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#fnmatch.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the subset of the list of <em>names</em> that match <em>pattern</em>. It is the same as
<code class="docutils literal notranslate"><span class="pre">[n</span> <span class="pre">for</span> <span class="pre">n</span> <span class="pre">in</span> <span class="pre">names</span> <span class="pre">if</span> <span class="pre">fnmatch(n,</span> <span class="pre">pattern)]</span></code>, but implemented more efficiently.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="fnmatch.translate">
<code class="descclassname">fnmatch.</code><code class="descname">translate</code><span class="sig-paren">(</span><em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#fnmatch.translate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the shell-style <em>pattern</em> converted to a regular expression for
using with <a class="reference internal" href="re.html#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a>.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fnmatch</span><span class="o">,</span> <span class="nn">re</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regex</span> <span class="o">=</span> <span class="n">fnmatch</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="s1">&#39;*.txt&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">regex</span>
<span class="go">&#39;.*\\.txt\\Z(?ms)&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reobj</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">regex</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reobj</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;foobar.txt&#39;</span><span class="p">)</span>
<span class="go">&lt;_sre.SRE_Match object at 0x...&gt;</span>
</pre></div>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a></dt>
<dd>Unix shell-style path expansion.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="glob.html"
                        title="previous chapter">10.7. <code class="docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="linecache.html"
                        title="next chapter">10.9. <code class="docutils literal notranslate"><span class="pre">linecache</span></code> — Random access to text lines</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fnmatch.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="linecache.html" title="10.9. linecache — Random access to text lines"
             >next</a> |</li>
        <li class="right" >
          <a href="glob.html" title="10.7. glob — Unix style pathname pattern expansion"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\`�c�����html/library/formatter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>34.1. formatter — Generic output formatting &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="35. MS Windows Specific Services" href="windows.html" />
    <link rel="prev" title="34. Miscellaneous Services" href="misc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/formatter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="35. MS Windows Specific Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="misc.html" title="34. Miscellaneous Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="misc.html" accesskey="U">34. Miscellaneous Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-formatter">
<span id="formatter-generic-output-formatting"></span><h1>34.1. <a class="reference internal" href="#module-formatter" title="formatter: Generic output formatter and device interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">formatter</span></code></a> — Generic output formatting<a class="headerlink" href="#module-formatter" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module supports two interface definitions, each with multiple
implementations.  The <em>formatter</em> interface is used by the <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a>
class of the <a class="reference internal" href="htmllib.html#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> module, and the <em>writer</em> interface is required by
the formatter interface.</p>
<p>Formatter objects transform an abstract flow of formatting events into specific
output events on writer objects.  Formatters manage several stack structures to
allow various properties of a writer object to be changed and restored; writers
need not be able to handle relative changes nor any sort of “change back”
operation.  Specific writer properties which may be controlled via formatter
objects are horizontal alignment, font, and left margin indentations.  A
mechanism is provided which supports providing arbitrary, non-exclusive style
settings to a writer as well.  Additional interfaces facilitate formatting
events which are not reversible, such as paragraph separation.</p>
<p>Writer objects encapsulate device interfaces.  Abstract devices, such as file
formats, are supported as well as physical devices.  The provided
implementations all work with abstract devices.  The interface makes available
mechanisms for setting the properties which formatter objects manage and
inserting data into the output.</p>
<div class="section" id="the-formatter-interface">
<span id="formatter-interface"></span><h2>34.1.1. The Formatter Interface<a class="headerlink" href="#the-formatter-interface" title="Permalink to this headline">¶</a></h2>
<p>Interfaces to create formatters are dependent on the specific formatter class
being instantiated.  The interfaces described below are the required interfaces
which all formatters must support once initialized.</p>
<p>One data element is defined at the module level:</p>
<dl class="data">
<dt id="formatter.AS_IS">
<code class="descclassname">formatter.</code><code class="descname">AS_IS</code><a class="headerlink" href="#formatter.AS_IS" title="Permalink to this definition">¶</a></dt>
<dd><p>Value which can be used in the font specification passed to the <code class="docutils literal notranslate"><span class="pre">push_font()</span></code>
method described below, or as the new value to any other <code class="docutils literal notranslate"><span class="pre">push_property()</span></code>
method.  Pushing the <code class="docutils literal notranslate"><span class="pre">AS_IS</span></code> value allows the corresponding <code class="docutils literal notranslate"><span class="pre">pop_property()</span></code>
method to be called without having to track whether the property was changed.</p>
</dd></dl>

<p>The following attributes are defined for formatter instance objects:</p>
<dl class="attribute">
<dt id="formatter.formatter.writer">
<code class="descclassname">formatter.</code><code class="descname">writer</code><a class="headerlink" href="#formatter.formatter.writer" title="Permalink to this definition">¶</a></dt>
<dd><p>The writer instance with which the formatter interacts.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.end_paragraph">
<code class="descclassname">formatter.</code><code class="descname">end_paragraph</code><span class="sig-paren">(</span><em>blanklines</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.end_paragraph" title="Permalink to this definition">¶</a></dt>
<dd><p>Close any open paragraphs and insert at least <em>blanklines</em> before the next
paragraph.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.add_line_break">
<code class="descclassname">formatter.</code><code class="descname">add_line_break</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.add_line_break" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a hard line break if one does not already exist.  This does not break the
logical paragraph.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.add_hor_rule">
<code class="descclassname">formatter.</code><code class="descname">add_hor_rule</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.add_hor_rule" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a horizontal rule in the output.  A hard break is inserted if there is
data in the current paragraph, but the logical paragraph is not broken.  The
arguments and keywords are passed on to the writer’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_line_break()</span></code>
method.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.add_flowing_data">
<code class="descclassname">formatter.</code><code class="descname">add_flowing_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.add_flowing_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Provide data which should be formatted with collapsed whitespace. Whitespace
from preceding and successive calls to <a class="reference internal" href="#formatter.formatter.add_flowing_data" title="formatter.formatter.add_flowing_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_flowing_data()</span></code></a> is considered as
well when the whitespace collapse is performed.  The data which is passed to
this method is expected to be word-wrapped by the output device.  Note that any
word-wrapping still must be performed by the writer object due to the need to
rely on device and font information.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.add_literal_data">
<code class="descclassname">formatter.</code><code class="descname">add_literal_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.add_literal_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Provide data which should be passed to the writer unchanged. Whitespace,
including newline and tab characters, are considered legal in the value of
<em>data</em>.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.add_label_data">
<code class="descclassname">formatter.</code><code class="descname">add_label_data</code><span class="sig-paren">(</span><em>format</em>, <em>counter</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.add_label_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a label which should be placed to the left of the current left margin.
This should be used for constructing bulleted or numbered lists.  If the
<em>format</em> value is a string, it is interpreted as a format specification for
<em>counter</em>, which should be an integer. The result of this formatting becomes the
value of the label; if <em>format</em> is not a string it is used as the label value
directly. The label value is passed as the only argument to the writer’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">send_label_data()</span></code> method.  Interpretation of non-string label values is
dependent on the associated writer.</p>
<p>Format specifications are strings which, in combination with a counter value,
are used to compute label values.  Each character in the format string is copied
to the label value, with some characters recognized to indicate a transform on
the counter value.  Specifically, the character <code class="docutils literal notranslate"><span class="pre">'1'</span></code> represents the counter
value formatter as an Arabic number, the characters <code class="docutils literal notranslate"><span class="pre">'A'</span></code> and <code class="docutils literal notranslate"><span class="pre">'a'</span></code>
represent alphabetic representations of the counter value in upper and lower
case, respectively, and <code class="docutils literal notranslate"><span class="pre">'I'</span></code> and <code class="docutils literal notranslate"><span class="pre">'i'</span></code> represent the counter value in Roman
numerals, in upper and lower case.  Note that the alphabetic and roman
transforms require that the counter value be greater than zero.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.flush_softspace">
<code class="descclassname">formatter.</code><code class="descname">flush_softspace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.flush_softspace" title="Permalink to this definition">¶</a></dt>
<dd><p>Send any pending whitespace buffered from a previous call to
<a class="reference internal" href="#formatter.formatter.add_flowing_data" title="formatter.formatter.add_flowing_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_flowing_data()</span></code></a> to the associated writer object.  This should be called
before any direct manipulation of the writer object.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.push_alignment">
<code class="descclassname">formatter.</code><code class="descname">push_alignment</code><span class="sig-paren">(</span><em>align</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.push_alignment" title="Permalink to this definition">¶</a></dt>
<dd><p>Push a new alignment setting onto the alignment stack.  This may be
<a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> if no change is desired.  If the alignment value is changed from
the previous setting, the writer’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">new_alignment()</span></code> method is called with
the <em>align</em> value.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.pop_alignment">
<code class="descclassname">formatter.</code><code class="descname">pop_alignment</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.pop_alignment" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the previous alignment.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.push_font">
<code class="descclassname">formatter.</code><code class="descname">push_font</code><span class="sig-paren">(</span><em>(size</em>, <em>italic</em>, <em>bold</em>, <em>teletype)</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.push_font" title="Permalink to this definition">¶</a></dt>
<dd><p>Change some or all font properties of the writer object.  Properties which are
not set to <a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> are set to the values passed in while others are
maintained at their current settings.  The writer’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">new_font()</span></code> method is
called with the fully resolved font specification.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.pop_font">
<code class="descclassname">formatter.</code><code class="descname">pop_font</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.pop_font" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the previous font.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.push_margin">
<code class="descclassname">formatter.</code><code class="descname">push_margin</code><span class="sig-paren">(</span><em>margin</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.push_margin" title="Permalink to this definition">¶</a></dt>
<dd><p>Increase the number of left margin indentations by one, associating the logical
tag <em>margin</em> with the new indentation.  The initial margin level is <code class="docutils literal notranslate"><span class="pre">0</span></code>.
Changed values of the logical tag must be true values; false values other than
<a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> are not sufficient to change the margin.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.pop_margin">
<code class="descclassname">formatter.</code><code class="descname">pop_margin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.pop_margin" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the previous margin.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.push_style">
<code class="descclassname">formatter.</code><code class="descname">push_style</code><span class="sig-paren">(</span><em>*styles</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.push_style" title="Permalink to this definition">¶</a></dt>
<dd><p>Push any number of arbitrary style specifications.  All styles are pushed onto
the styles stack in order.  A tuple representing the entire stack, including
<a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> values, is passed to the writer’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">new_styles()</span></code> method.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.pop_style">
<code class="descclassname">formatter.</code><code class="descname">pop_style</code><span class="sig-paren">(</span><span class="optional">[</span><em>n=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.pop_style" title="Permalink to this definition">¶</a></dt>
<dd><p>Pop the last <em>n</em> style specifications passed to <a class="reference internal" href="#formatter.formatter.push_style" title="formatter.formatter.push_style"><code class="xref py py-meth docutils literal notranslate"><span class="pre">push_style()</span></code></a>.  A tuple
representing the revised stack, including <a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> values, is passed to
the writer’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">new_styles()</span></code> method.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.set_spacing">
<code class="descclassname">formatter.</code><code class="descname">set_spacing</code><span class="sig-paren">(</span><em>spacing</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.set_spacing" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the spacing style for the writer.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.formatter.assert_line_data">
<code class="descclassname">formatter.</code><code class="descname">assert_line_data</code><span class="sig-paren">(</span><span class="optional">[</span><em>flag=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.formatter.assert_line_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Inform the formatter that data has been added to the current paragraph
out-of-band.  This should be used when the writer has been manipulated
directly.  The optional <em>flag</em> argument can be set to false if the writer
manipulations produced a hard line break at the end of the output.</p>
</dd></dl>

</div>
<div class="section" id="formatter-implementations">
<span id="formatter-impls"></span><h2>34.1.2. Formatter Implementations<a class="headerlink" href="#formatter-implementations" title="Permalink to this headline">¶</a></h2>
<p>Two implementations of formatter objects are provided by this module. Most
applications may use one of these classes without modification or subclassing.</p>
<dl class="class">
<dt id="formatter.NullFormatter">
<em class="property">class </em><code class="descclassname">formatter.</code><code class="descname">NullFormatter</code><span class="sig-paren">(</span><span class="optional">[</span><em>writer</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.NullFormatter" title="Permalink to this definition">¶</a></dt>
<dd><p>A formatter which does nothing.  If <em>writer</em> is omitted, a <a class="reference internal" href="#formatter.NullWriter" title="formatter.NullWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullWriter</span></code></a>
instance is created.  No methods of the writer are called by
<a class="reference internal" href="#formatter.NullFormatter" title="formatter.NullFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullFormatter</span></code></a> instances.  Implementations should inherit from this
class if implementing a writer interface but don’t need to inherit any
implementation.</p>
</dd></dl>

<dl class="class">
<dt id="formatter.AbstractFormatter">
<em class="property">class </em><code class="descclassname">formatter.</code><code class="descname">AbstractFormatter</code><span class="sig-paren">(</span><em>writer</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.AbstractFormatter" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard formatter.  This implementation has demonstrated wide applicability
to many writers, and may be used directly in most circumstances.  It has been
used to implement a full-featured World Wide Web browser.</p>
</dd></dl>

</div>
<div class="section" id="the-writer-interface">
<span id="writer-interface"></span><h2>34.1.3. The Writer Interface<a class="headerlink" href="#the-writer-interface" title="Permalink to this headline">¶</a></h2>
<p>Interfaces to create writers are dependent on the specific writer class being
instantiated.  The interfaces described below are the required interfaces which
all writers must support once initialized. Note that while most applications can
use the <a class="reference internal" href="#formatter.AbstractFormatter" title="formatter.AbstractFormatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">AbstractFormatter</span></code></a> class as a formatter, the writer must
typically be provided by the application.</p>
<dl class="method">
<dt id="formatter.writer.flush">
<code class="descclassname">writer.</code><code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush any buffered output or device control events.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.new_alignment">
<code class="descclassname">writer.</code><code class="descname">new_alignment</code><span class="sig-paren">(</span><em>align</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.new_alignment" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the alignment style.  The <em>align</em> value can be any object, but by convention
is a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>, where <code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that the writer’s “preferred”
alignment should be used. Conventional <em>align</em> values are <code class="docutils literal notranslate"><span class="pre">'left'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'center'</span></code>, <code class="docutils literal notranslate"><span class="pre">'right'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'justify'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.new_font">
<code class="descclassname">writer.</code><code class="descname">new_font</code><span class="sig-paren">(</span><em>font</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.new_font" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the font style.  The value of <em>font</em> will be <code class="docutils literal notranslate"><span class="pre">None</span></code>, indicating that the
device’s default font should be used, or a tuple of the form <code class="docutils literal notranslate"><span class="pre">(size,</span>
<span class="pre">italic,</span> <span class="pre">bold,</span> <span class="pre">teletype)</span></code>.  Size will be a string indicating the size of
font that should be used; specific strings and their interpretation must be
defined by the application.  The <em>italic</em>, <em>bold</em>, and <em>teletype</em> values are
Boolean values specifying which of those font attributes should be used.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.new_margin">
<code class="descclassname">writer.</code><code class="descname">new_margin</code><span class="sig-paren">(</span><em>margin</em>, <em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.new_margin" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the margin level to the integer <em>level</em> and the logical tag to <em>margin</em>.
Interpretation of the logical tag is at the writer’s discretion; the only
restriction on the value of the logical tag is that it not be a false value for
non-zero values of <em>level</em>.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.new_spacing">
<code class="descclassname">writer.</code><code class="descname">new_spacing</code><span class="sig-paren">(</span><em>spacing</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.new_spacing" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the spacing style to <em>spacing</em>.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.new_styles">
<code class="descclassname">writer.</code><code class="descname">new_styles</code><span class="sig-paren">(</span><em>styles</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.new_styles" title="Permalink to this definition">¶</a></dt>
<dd><p>Set additional styles.  The <em>styles</em> value is a tuple of arbitrary values; the
value <a class="reference internal" href="#formatter.AS_IS" title="formatter.AS_IS"><code class="xref py py-const docutils literal notranslate"><span class="pre">AS_IS</span></code></a> should be ignored.  The <em>styles</em> tuple may be interpreted
either as a set or as a stack depending on the requirements of the application
and writer implementation.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_line_break">
<code class="descclassname">writer.</code><code class="descname">send_line_break</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_line_break" title="Permalink to this definition">¶</a></dt>
<dd><p>Break the current line.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_paragraph">
<code class="descclassname">writer.</code><code class="descname">send_paragraph</code><span class="sig-paren">(</span><em>blankline</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_paragraph" title="Permalink to this definition">¶</a></dt>
<dd><p>Produce a paragraph separation of at least <em>blankline</em> blank lines, or the
equivalent.  The <em>blankline</em> value will be an integer.  Note that the
implementation will receive a call to <a class="reference internal" href="#formatter.writer.send_line_break" title="formatter.writer.send_line_break"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send_line_break()</span></code></a> before this call
if a line break is needed;  this method should not include ending the last line
of the paragraph. It is only responsible for vertical spacing between
paragraphs.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_hor_rule">
<code class="descclassname">writer.</code><code class="descname">send_hor_rule</code><span class="sig-paren">(</span><em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_hor_rule" title="Permalink to this definition">¶</a></dt>
<dd><p>Display a horizontal rule on the output device.  The arguments to this method
are entirely application- and writer-specific, and should be interpreted with
care.  The method implementation may assume that a line break has already been
issued via <a class="reference internal" href="#formatter.writer.send_line_break" title="formatter.writer.send_line_break"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send_line_break()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_flowing_data">
<code class="descclassname">writer.</code><code class="descname">send_flowing_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_flowing_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Output character data which may be word-wrapped and re-flowed as needed.  Within
any sequence of calls to this method, the writer may assume that spans of
multiple whitespace characters have been collapsed to single space characters.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_literal_data">
<code class="descclassname">writer.</code><code class="descname">send_literal_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_literal_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Output character data which has already been formatted for display.  Generally,
this should be interpreted to mean that line breaks indicated by newline
characters should be preserved and no new line breaks should be introduced.  The
data may contain embedded newline and tab characters, unlike data provided to
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_formatted_data()</span></code> interface.</p>
</dd></dl>

<dl class="method">
<dt id="formatter.writer.send_label_data">
<code class="descclassname">writer.</code><code class="descname">send_label_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.writer.send_label_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>data</em> to the left of the current left margin, if possible. The value of
<em>data</em> is not restricted; treatment of non-string values is entirely
application- and writer-dependent.  This method will only be called at the
beginning of a line.</p>
</dd></dl>

</div>
<div class="section" id="writer-implementations">
<span id="writer-impls"></span><h2>34.1.4. Writer Implementations<a class="headerlink" href="#writer-implementations" title="Permalink to this headline">¶</a></h2>
<p>Three implementations of the writer object interface are provided as examples by
this module.  Most applications will need to derive new writer classes from the
<a class="reference internal" href="#formatter.NullWriter" title="formatter.NullWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullWriter</span></code></a> class.</p>
<dl class="class">
<dt id="formatter.NullWriter">
<em class="property">class </em><code class="descclassname">formatter.</code><code class="descname">NullWriter</code><a class="headerlink" href="#formatter.NullWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>A writer which only provides the interface definition; no actions are taken on
any methods.  This should be the base class for all writers which do not need to
inherit any implementation methods.</p>
</dd></dl>

<dl class="class">
<dt id="formatter.AbstractWriter">
<em class="property">class </em><code class="descclassname">formatter.</code><code class="descname">AbstractWriter</code><a class="headerlink" href="#formatter.AbstractWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>A writer which can be used in debugging formatters, but not much else.  Each
method simply announces itself by printing its name and arguments on standard
output.</p>
</dd></dl>

<dl class="class">
<dt id="formatter.DumbWriter">
<em class="property">class </em><code class="descclassname">formatter.</code><code class="descname">DumbWriter</code><span class="sig-paren">(</span><em>file=None</em>, <em>maxcol=72</em><span class="sig-paren">)</span><a class="headerlink" href="#formatter.DumbWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Simple writer class which writes output on the file object passed in as <em>file</em>
or, if <em>file</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, on standard output.  The output is simply word-wrapped
to the number of columns specified by <em>maxcol</em>.  This class is suitable for
reflowing a sequence of paragraphs.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a><ul>
<li><a class="reference internal" href="#the-formatter-interface">34.1.1. The Formatter Interface</a></li>
<li><a class="reference internal" href="#formatter-implementations">34.1.2. Formatter Implementations</a></li>
<li><a class="reference internal" href="#the-writer-interface">34.1.3. The Writer Interface</a></li>
<li><a class="reference internal" href="#writer-implementations">34.1.4. Writer Implementations</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="misc.html"
                        title="previous chapter">34. Miscellaneous Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="windows.html"
                        title="next chapter">35. MS Windows Specific Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/formatter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="35. MS Windows Specific Services"
             >next</a> |</li>
        <li class="right" >
          <a href="misc.html" title="34. Miscellaneous Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="misc.html" >34. Miscellaneous Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�[z�A�Ahtml/library/fpectl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.16. fpectl — Floating point exception control &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="29. Custom Python Interpreters" href="custominterp.html" />
    <link rel="prev" title="28.15. user — User-specific configuration hook" href="user.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fpectl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="custominterp.html" title="29. Custom Python Interpreters"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="user.html" title="28.15. user — User-specific configuration hook"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fpectl">
<span id="fpectl-floating-point-exception-control"></span><h1>28.16. <a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> — Floating point exception control<a class="headerlink" href="#module-fpectl" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module is not built by default, and its usage is discouraged
and may be dangerous except in the hands of experts.  See also the section
<a class="reference internal" href="#fpectl-limitations"><span class="std std-ref">Limitations and other considerations</span></a> on limitations for more details.</p>
</div>
<p id="index-0">Most computers carry out floating point operations in conformance with the
so-called IEEE-754 standard. On any real computer, some floating point
operations produce results that cannot be expressed as a normal floating point
value. For example, try</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="go">inf</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="o">/</span> <span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="go">nan</span>
</pre></div>
</div>
<p>(The example above will work on many platforms. DEC Alpha may be one exception.)
“Inf” is a special, non-numeric value in IEEE-754 that stands for “infinity”,
and “nan” means “not a number.” Note that, other than the non-numeric results,
nothing special happened when you asked Python to carry out those calculations.
That is in fact the default behaviour prescribed in the IEEE-754 standard, and
if it works for you, stop reading now.</p>
<p>In some circumstances, it would be better to raise an exception and stop
processing at the point where the faulty operation was attempted. The
<a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module is for use in that situation. It provides control over
floating point units from several hardware manufacturers, allowing the user to
turn on the generation of <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code> whenever any of the IEEE-754
exceptions Division by Zero, Overflow, or Invalid Operation occurs. In tandem
with a pair of wrapper macros that are inserted into the C code comprising your
python system, <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code> is trapped and converted into the Python
<a class="reference internal" href="#fpectl.FloatingPointError" title="fpectl.FloatingPointError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FloatingPointError</span></code></a> exception.</p>
<p>The <a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module defines the following functions and may raise the given
exception:</p>
<dl class="function">
<dt id="fpectl.turnon_sigfpe">
<code class="descclassname">fpectl.</code><code class="descname">turnon_sigfpe</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fpectl.turnon_sigfpe" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn on the generation of <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code>, and set up an appropriate signal
handler.</p>
</dd></dl>

<dl class="function">
<dt id="fpectl.turnoff_sigfpe">
<code class="descclassname">fpectl.</code><code class="descname">turnoff_sigfpe</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#fpectl.turnoff_sigfpe" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset default handling of floating point exceptions.</p>
</dd></dl>

<dl class="exception">
<dt id="fpectl.FloatingPointError">
<em class="property">exception </em><code class="descclassname">fpectl.</code><code class="descname">FloatingPointError</code><a class="headerlink" href="#fpectl.FloatingPointError" title="Permalink to this definition">¶</a></dt>
<dd><p>After <a class="reference internal" href="#fpectl.turnon_sigfpe" title="fpectl.turnon_sigfpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">turnon_sigfpe()</span></code></a> has been executed, a floating point operation that
raises one of the IEEE-754 exceptions Division by Zero, Overflow, or Invalid
operation will in turn raise this standard Python exception.</p>
</dd></dl>

<div class="section" id="example">
<span id="fpectl-example"></span><h2>28.16.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The following example demonstrates how to start up and test operation of the
<a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fpectl</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fpetest</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fpectl</span><span class="o">.</span><span class="n">turnon_sigfpe</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fpetest</span><span class="o">.</span><span class="n">test</span><span class="p">()</span>
<span class="go">overflow        PASS</span>
<span class="go">FloatingPointError: Overflow</span>

<span class="go">div by 0        PASS</span>
<span class="go">FloatingPointError: Division by zero</span>
<span class="go">  [ more output from test elided ]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">FloatingPointError</span>: <span class="n">in math_1</span>
</pre></div>
</div>
</div>
<div class="section" id="limitations-and-other-considerations">
<span id="fpectl-limitations"></span><h2>28.16.2. Limitations and other considerations<a class="headerlink" href="#limitations-and-other-considerations" title="Permalink to this headline">¶</a></h2>
<p>Setting up a given processor to trap IEEE-754 floating point errors currently
requires custom code on a per-architecture basis. You may have to modify
<a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> to control your particular hardware.</p>
<p>Conversion of an IEEE-754 exception to a Python exception requires that the
wrapper macros <code class="docutils literal notranslate"><span class="pre">PyFPE_START_PROTECT</span></code> and <code class="docutils literal notranslate"><span class="pre">PyFPE_END_PROTECT</span></code> be inserted
into your code in an appropriate fashion.  Python itself has been modified to
support the <a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module, but many other codes of interest to numerical
analysts have not.</p>
<p>The <a class="reference internal" href="#module-fpectl" title="fpectl: Provide control for floating point exception handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpectl</span></code></a> module is not thread-safe.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">Some files in the source distribution may be interesting in learning more about
how this module operates. The include file <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Include/pyfpe.h">Include/pyfpe.h</a> discusses the
implementation of this module at some length. <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Modules/fpetestmodule.c">Modules/fpetestmodule.c</a>
gives several examples of use. Many additional examples can be found in
<a class="reference external" href="https://github.com/python/cpython/tree/2.7/Objects/floatobject.c">Objects/floatobject.c</a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a><ul>
<li><a class="reference internal" href="#example">28.16.1. Example</a></li>
<li><a class="reference internal" href="#limitations-and-other-considerations">28.16.2. Limitations and other considerations</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="user.html"
                        title="previous chapter">28.15. <code class="docutils literal notranslate"><span class="pre">user</span></code> — User-specific configuration hook</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="custominterp.html"
                        title="next chapter">29. Custom Python Interpreters</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fpectl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="custominterp.html" title="29. Custom Python Interpreters"
             >next</a> |</li>
        <li class="right" >
          <a href="user.html" title="28.15. user — User-specific configuration hook"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\~��H�,�,html/library/fpformat.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.11. fpformat — Floating point conversions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8. Data Types" href="datatypes.html" />
    <link rel="prev" title="7.10. stringprep — Internet String Preparation" href="stringprep.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fpformat.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datatypes.html" title="8. Data Types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stringprep.html" title="7.10. stringprep — Internet String Preparation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fpformat">
<span id="fpformat-floating-point-conversions"></span><h1>7.11. <a class="reference internal" href="#module-fpformat" title="fpformat: General floating point formatting functions. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code></a> — Floating point conversions<a class="headerlink" href="#module-fpformat" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-fpformat" title="fpformat: General floating point formatting functions. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-fpformat" title="fpformat: General floating point formatting functions. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code></a> module defines functions for dealing with floating point
numbers representations in 100% pure Python.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module is unnecessary: everything here can be done using the <code class="docutils literal notranslate"><span class="pre">%</span></code> string
interpolation operator described in the <a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section.</p>
</div>
<p>The <a class="reference internal" href="#module-fpformat" title="fpformat: General floating point formatting functions. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code></a> module defines the following functions and an exception:</p>
<dl class="function">
<dt id="fpformat.fix">
<code class="descclassname">fpformat.</code><code class="descname">fix</code><span class="sig-paren">(</span><em>x</em>, <em>digs</em><span class="sig-paren">)</span><a class="headerlink" href="#fpformat.fix" title="Permalink to this definition">¶</a></dt>
<dd><p>Format <em>x</em> as <code class="docutils literal notranslate"><span class="pre">[-]ddd.ddd</span></code> with <em>digs</em> digits after the point and at least one
digit before. If <code class="docutils literal notranslate"><span class="pre">digs</span> <span class="pre">&lt;=</span> <span class="pre">0</span></code>, the decimal point is suppressed.</p>
<p><em>x</em> can be either a number or a string that looks like one. <em>digs</em> is an
integer.</p>
<p>Return value is a string.</p>
</dd></dl>

<dl class="function">
<dt id="fpformat.sci">
<code class="descclassname">fpformat.</code><code class="descname">sci</code><span class="sig-paren">(</span><em>x</em>, <em>digs</em><span class="sig-paren">)</span><a class="headerlink" href="#fpformat.sci" title="Permalink to this definition">¶</a></dt>
<dd><p>Format <em>x</em> as <code class="docutils literal notranslate"><span class="pre">[-]d.dddE[+-]ddd</span></code> with <em>digs</em> digits after the  point and
exactly one digit before. If <code class="docutils literal notranslate"><span class="pre">digs</span> <span class="pre">&lt;=</span> <span class="pre">0</span></code>, one digit is kept and the point is
suppressed.</p>
<p><em>x</em> can be either a real number, or a string that looks like one. <em>digs</em> is an
integer.</p>
<p>Return value is a string.</p>
</dd></dl>

<dl class="exception">
<dt id="fpformat.NotANumber">
<em class="property">exception </em><code class="descclassname">fpformat.</code><code class="descname">NotANumber</code><a class="headerlink" href="#fpformat.NotANumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a string passed to <a class="reference internal" href="#fpformat.fix" title="fpformat.fix"><code class="xref py py-func docutils literal notranslate"><span class="pre">fix()</span></code></a> or <a class="reference internal" href="#fpformat.sci" title="fpformat.sci"><code class="xref py py-func docutils literal notranslate"><span class="pre">sci()</span></code></a> as the <em>x</em>
parameter does not look like a number. This is a subclass of <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
when the standard exceptions are strings.  The exception value is the improperly
formatted string that caused the exception to be raised.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fpformat</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fpformat</span><span class="o">.</span><span class="n">fix</span><span class="p">(</span><span class="mf">1.23</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;1.2&#39;</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="stringprep.html"
                        title="previous chapter">7.10. <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> — Internet String Preparation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datatypes.html"
                        title="next chapter">8. Data Types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fpformat.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datatypes.html" title="8. Data Types"
             >next</a> |</li>
        <li class="right" >
          <a href="stringprep.html" title="7.10. stringprep — Internet String Preparation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��Y�8a8ahtml/library/fractions.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.5. fractions — Rational numbers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.6. random — Generate pseudo-random numbers" href="random.html" />
    <link rel="prev" title="9.4. decimal — Decimal fixed point and floating point arithmetic" href="decimal.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/fractions.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="random.html" title="9.6. random — Generate pseudo-random numbers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="decimal.html" title="9.4. decimal — Decimal fixed point and floating point arithmetic"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-fractions">
<span id="fractions-rational-numbers"></span><h1>9.5. <a class="reference internal" href="#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> — Rational numbers<a class="headerlink" href="#module-fractions" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/fractions.py">Lib/fractions.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module provides support for rational number arithmetic.</p>
<p>A Fraction instance can be constructed from a pair of integers, from
another rational number, or from a string.</p>
<dl class="class">
<dt id="fractions.Fraction">
<em class="property">class </em><code class="descclassname">fractions.</code><code class="descname">Fraction</code><span class="sig-paren">(</span><em>numerator=0</em>, <em>denominator=1</em><span class="sig-paren">)</span><a class="headerlink" href="#fractions.Fraction" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descclassname">fractions.</code><code class="descname">Fraction</code><span class="sig-paren">(</span><em>other_fraction</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descclassname">fractions.</code><code class="descname">Fraction</code><span class="sig-paren">(</span><em>float</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descclassname">fractions.</code><code class="descname">Fraction</code><span class="sig-paren">(</span><em>decimal</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descclassname">fractions.</code><code class="descname">Fraction</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span></dt>
<dd><p>The first version requires that <em>numerator</em> and <em>denominator</em> are instances
of <a class="reference internal" href="numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a> and returns a new <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instance
with value <code class="docutils literal notranslate"><span class="pre">numerator/denominator</span></code>. If <em>denominator</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code>, it
raises a <a class="reference internal" href="exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>. The second version requires that
<em>other_fraction</em> is an instance of <a class="reference internal" href="numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a> and returns a
<a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instance with the same value.  The next two versions accept
either a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> or a <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> instance, and return a
<a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instance with exactly the same value.  Note that due to the
usual issues with binary floating-point (see <a class="reference internal" href="../tutorial/floatingpoint.html#tut-fp-issues"><span class="std std-ref">Floating Point Arithmetic:  Issues and Limitations</span></a>), the
argument to <code class="docutils literal notranslate"><span class="pre">Fraction(1.1)</span></code> is not exactly equal to 11/10, and so
<code class="docutils literal notranslate"><span class="pre">Fraction(1.1)</span></code> does <em>not</em> return <code class="docutils literal notranslate"><span class="pre">Fraction(11,</span> <span class="pre">10)</span></code> as one might expect.
(But see the documentation for the <a class="reference internal" href="#fractions.Fraction.limit_denominator" title="fractions.Fraction.limit_denominator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">limit_denominator()</span></code></a> method below.)
The last version of the constructor expects a string or unicode instance.
The usual form for this instance is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="n">numerator</span> <span class="p">[</span><span class="s1">&#39;/&#39;</span> <span class="n">denominator</span><span class="p">]</span>
</pre></div>
</div>
<p>where the optional <code class="docutils literal notranslate"><span class="pre">sign</span></code> may be either ‘+’ or ‘-‘ and
<code class="docutils literal notranslate"><span class="pre">numerator</span></code> and <code class="docutils literal notranslate"><span class="pre">denominator</span></code> (if present) are strings of
decimal digits.  In addition, any string that represents a finite
value and is accepted by the <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> constructor is also
accepted by the <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> constructor.  In either form the
input string may also have leading and/or trailing whitespace.
Here are some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="k">import</span> <span class="n">Fraction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="mi">16</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">)</span>
<span class="go">Fraction(-8, 5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="mi">123</span><span class="p">)</span>
<span class="go">Fraction(123, 1)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">()</span>
<span class="go">Fraction(0, 1)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39;3/7&#39;</span><span class="p">)</span>
<span class="go">Fraction(3, 7)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39; -3/7 &#39;</span><span class="p">)</span>
<span class="go">Fraction(-3, 7)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39;1.414213 </span><span class="se">\t\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">Fraction(1414213, 1000000)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39;-.125&#39;</span><span class="p">)</span>
<span class="go">Fraction(-1, 8)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39;7e-6&#39;</span><span class="p">)</span>
<span class="go">Fraction(7, 1000000)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="mf">2.25</span><span class="p">)</span>
<span class="go">Fraction(9, 4)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="mf">1.1</span><span class="p">)</span>
<span class="go">Fraction(2476979795053773, 2251799813685248)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.1&#39;</span><span class="p">))</span>
<span class="go">Fraction(11, 10)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> class inherits from the abstract base class
<a class="reference internal" href="numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a>, and implements all of the methods and
operations from that class.  <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instances are hashable,
and should be treated as immutable.  In addition,
<a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> has the following methods:</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> constructor now accepts <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> and
<a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> instances.</p>
</div>
<dl class="method">
<dt id="fractions.Fraction.from_float">
<code class="descname">from_float</code><span class="sig-paren">(</span><em>flt</em><span class="sig-paren">)</span><a class="headerlink" href="#fractions.Fraction.from_float" title="Permalink to this definition">¶</a></dt>
<dd><p>This class method constructs a <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> representing the exact
value of <em>flt</em>, which must be a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>. Beware that
<code class="docutils literal notranslate"><span class="pre">Fraction.from_float(0.3)</span></code> is not the same value as <code class="docutils literal notranslate"><span class="pre">Fraction(3,</span> <span class="pre">10)</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">From Python 2.7 onwards, you can also construct a
<a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instance directly from a <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="fractions.Fraction.from_decimal">
<code class="descname">from_decimal</code><span class="sig-paren">(</span><em>dec</em><span class="sig-paren">)</span><a class="headerlink" href="#fractions.Fraction.from_decimal" title="Permalink to this definition">¶</a></dt>
<dd><p>This class method constructs a <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> representing the exact
value of <em>dec</em>, which must be a <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">From Python 2.7 onwards, you can also construct a
<a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> instance directly from a <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a>
instance.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="fractions.Fraction.limit_denominator">
<code class="descname">limit_denominator</code><span class="sig-paren">(</span><em>max_denominator=1000000</em><span class="sig-paren">)</span><a class="headerlink" href="#fractions.Fraction.limit_denominator" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds and returns the closest <a class="reference internal" href="#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> to <code class="docutils literal notranslate"><span class="pre">self</span></code> that has
denominator at most max_denominator.  This method is useful for finding
rational approximations to a given floating-point number:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="k">import</span> <span class="n">Fraction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="s1">&#39;3.1415926535897932&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">limit_denominator</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="go">Fraction(355, 113)</span>
</pre></div>
</div>
<p>or for recovering a rational number that’s represented as a float:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">pi</span><span class="p">,</span> <span class="n">cos</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="n">cos</span><span class="p">(</span><span class="n">pi</span><span class="o">/</span><span class="mi">3</span><span class="p">))</span>
<span class="go">Fraction(4503599627370497, 9007199254740992)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="n">cos</span><span class="p">(</span><span class="n">pi</span><span class="o">/</span><span class="mi">3</span><span class="p">))</span><span class="o">.</span><span class="n">limit_denominator</span><span class="p">()</span>
<span class="go">Fraction(1, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Fraction</span><span class="p">(</span><span class="mf">1.1</span><span class="p">)</span><span class="o">.</span><span class="n">limit_denominator</span><span class="p">()</span>
<span class="go">Fraction(11, 10)</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

<dl class="function">
<dt id="fractions.gcd">
<code class="descclassname">fractions.</code><code class="descname">gcd</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#fractions.gcd" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the greatest common divisor of the integers <em>a</em> and <em>b</em>.  If either
<em>a</em> or <em>b</em> is nonzero, then the absolute value of <code class="docutils literal notranslate"><span class="pre">gcd(a,</span> <span class="pre">b)</span></code> is the
largest integer that divides both <em>a</em> and <em>b</em>.  <code class="docutils literal notranslate"><span class="pre">gcd(a,b)</span></code> has the same
sign as <em>b</em> if <em>b</em> is nonzero; otherwise it takes the sign of <em>a</em>.  <code class="docutils literal notranslate"><span class="pre">gcd(0,</span>
<span class="pre">0)</span></code> returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a></dt>
<dd>The abstract base classes making up the numeric tower.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="decimal.html"
                        title="previous chapter">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="random.html"
                        title="next chapter">9.6. <code class="docutils literal notranslate"><span class="pre">random</span></code> — Generate pseudo-random numbers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/fractions.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="random.html" title="9.6. random — Generate pseudo-random numbers"
             >next</a> |</li>
        <li class="right" >
          <a href="decimal.html" title="9.4. decimal — Decimal fixed point and floating point arithmetic"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\2�WF�F�html/library/framework.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.6. FrameWork — Interactive application framework &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.7. autoGIL — Global Interpreter Lock handling in event loops" href="autogil.html" />
    <link rel="prev" title="37.5. EasyDialogs — Basic Macintosh dialogs" href="easydialogs.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/framework.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="autogil.html" title="37.7. autoGIL — Global Interpreter Lock handling in event loops"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="easydialogs.html" title="37.5. EasyDialogs — Basic Macintosh dialogs"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-FrameWork">
<span id="framework-interactive-application-framework"></span><h1>37.6. <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> — Interactive application framework<a class="headerlink" href="#module-FrameWork" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> module contains classes that together provide a framework
for an interactive Macintosh application. The programmer builds an application
by creating subclasses that override various methods of the bases classes,
thereby implementing the functionality wanted. Overriding functionality can
often be done on various different levels, i.e. to handle clicks in a single
dialog window in a non-standard way it is not necessary to override the complete
event handling.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>Work on the <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> has pretty much stopped, now that <code class="xref py py-mod docutils literal notranslate"><span class="pre">PyObjC</span></code> is
available for full Cocoa access from Python, and the documentation describes
only the most important functionality, and not in the most logical manner at
that. Examine the source or the examples for more details.  The following are
some comments posted on the MacPython newsgroup about the strengths and
limitations of <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a>:</p>
<blockquote class="epigraph">
<div>The strong point of <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> is that it allows you to break into the
control-flow at many different places. <a class="reference internal" href="undoc.html#module-W" title="W: Widgets for the Mac, built on top of FrameWork. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">W</span></code></a>, for instance, uses a different
way to enable/disable menus and that plugs right in leaving the rest intact.
The weak points of <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> are that it has no abstract command
interface (but that shouldn’t be difficult), that its dialog support is minimal
and that its control/toolbar support is non-existent.</div></blockquote>
<p>The <a class="reference internal" href="#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="FrameWork.Application">
<code class="descclassname">FrameWork.</code><code class="descname">Application</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application" title="Permalink to this definition">¶</a></dt>
<dd><p>An object representing the complete application. See below for a description of
the methods. The default <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> routine creates an empty window
dictionary and a menu bar with an apple menu.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.MenuBar">
<code class="descclassname">FrameWork.</code><code class="descname">MenuBar</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.MenuBar" title="Permalink to this definition">¶</a></dt>
<dd><p>An object representing the menubar. This object is usually not created by the
user.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.Menu">
<code class="descclassname">FrameWork.</code><code class="descname">Menu</code><span class="sig-paren">(</span><em>bar</em>, <em>title</em><span class="optional">[</span>, <em>after</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Menu" title="Permalink to this definition">¶</a></dt>
<dd><p>An object representing a menu. Upon creation you pass the <code class="docutils literal notranslate"><span class="pre">MenuBar</span></code> the menu
appears in, the <em>title</em> string and a position (1-based) <em>after</em> where the menu
should appear (default: at the end).</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.MenuItem">
<code class="descclassname">FrameWork.</code><code class="descname">MenuItem</code><span class="sig-paren">(</span><em>menu</em>, <em>title</em><span class="optional">[</span>, <em>shortcut</em>, <em>callback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.MenuItem" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a menu item object. The arguments are the menu to create, the item title
string and optionally the keyboard shortcut and a callback routine. The callback
is called with the arguments menu-id, item number within menu (1-based), current
front window and the event record.</p>
<p>Instead of a callable object the callback can also be a string. In this case
menu selection causes the lookup of a method in the topmost window and the
application. The method name is the callback string with <code class="docutils literal notranslate"><span class="pre">'domenu_'</span></code>
prepended.</p>
<p>Calling the <code class="docutils literal notranslate"><span class="pre">MenuBar</span></code> <code class="xref py py-meth docutils literal notranslate"><span class="pre">fixmenudimstate()</span></code> method sets the correct dimming
for all menu items based on the current front window.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.Separator">
<code class="descclassname">FrameWork.</code><code class="descname">Separator</code><span class="sig-paren">(</span><em>menu</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Separator" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a separator to the end of a menu.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.SubMenu">
<code class="descclassname">FrameWork.</code><code class="descname">SubMenu</code><span class="sig-paren">(</span><em>menu</em>, <em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.SubMenu" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a submenu named <em>label</em> under menu <em>menu</em>. The menu object is returned.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.Window">
<code class="descclassname">FrameWork.</code><code class="descname">Window</code><span class="sig-paren">(</span><em>parent</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a (modeless) window. <em>Parent</em> is the application object to which the
window belongs. The window is not displayed until later.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.DialogWindow">
<code class="descclassname">FrameWork.</code><code class="descname">DialogWindow</code><span class="sig-paren">(</span><em>parent</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.DialogWindow" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a modeless dialog window.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.windowbounds">
<code class="descclassname">FrameWork.</code><code class="descname">windowbounds</code><span class="sig-paren">(</span><em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.windowbounds" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <code class="docutils literal notranslate"><span class="pre">(left,</span> <span class="pre">top,</span> <span class="pre">right,</span> <span class="pre">bottom)</span></code> tuple suitable for creation of a window
of given width and height. The window will be staggered with respect to previous
windows, and an attempt is made to keep the whole window on-screen. However, the
window will however always be the exact size given, so parts may be offscreen.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.setwatchcursor">
<code class="descclassname">FrameWork.</code><code class="descname">setwatchcursor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.setwatchcursor" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the mouse cursor to a watch.</p>
</dd></dl>

<dl class="function">
<dt id="FrameWork.setarrowcursor">
<code class="descclassname">FrameWork.</code><code class="descname">setarrowcursor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.setarrowcursor" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the mouse cursor to an arrow.</p>
</dd></dl>

<div class="section" id="application-objects">
<span id="id1"></span><h2>37.6.1. Application Objects<a class="headerlink" href="#application-objects" title="Permalink to this headline">¶</a></h2>
<p>Application objects have the following methods, among others:</p>
<dl class="method">
<dt id="FrameWork.Application.makeusermenus">
<code class="descclassname">Application.</code><code class="descname">makeusermenus</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.makeusermenus" title="Permalink to this definition">¶</a></dt>
<dd><p>Override this method if you need menus in your application. Append the menus to
the attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">menubar</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.getabouttext">
<code class="descclassname">Application.</code><code class="descname">getabouttext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.getabouttext" title="Permalink to this definition">¶</a></dt>
<dd><p>Override this method to return a text string describing your application.
Alternatively, override the <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_about()</span></code> method for more elaborate “about”
messages.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.mainloop">
<code class="descclassname">Application.</code><code class="descname">mainloop</code><span class="sig-paren">(</span><span class="optional">[</span><em>mask</em><span class="optional">[</span>, <em>wait</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.mainloop" title="Permalink to this definition">¶</a></dt>
<dd><p>This routine is the main event loop, call it to set your application rolling.
<em>Mask</em> is the mask of events you want to handle, <em>wait</em> is the number of ticks
you want to leave to other concurrent application (default 0, which is probably
not a good idea). While raising <em>self</em> to exit the mainloop is still supported
it is not recommended: call <code class="docutils literal notranslate"><span class="pre">self._quit()</span></code> instead.</p>
<p>The event loop is split into many small parts, each of which can be overridden.
The default methods take care of dispatching events to windows and dialogs,
handling drags and resizes, Apple Events, events for non-FrameWork windows, etc.</p>
<p>In general, all event handlers should return <code class="docutils literal notranslate"><span class="pre">1</span></code> if the event is fully handled
and <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise (because the front window was not a FrameWork window, for
instance). This is needed so that update events and such can be passed on to
other windows like the Sioux console window. Calling <code class="xref py py-func docutils literal notranslate"><span class="pre">MacOS.HandleEvent()</span></code>
is not allowed within <em>our_dispatch</em> or its callees, since this may result in an
infinite loop if the code is called through the Python inner-loop event handler.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.asyncevents">
<code class="descclassname">Application.</code><code class="descname">asyncevents</code><span class="sig-paren">(</span><em>onoff</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.asyncevents" title="Permalink to this definition">¶</a></dt>
<dd><p>Call this method with a nonzero parameter to enable asynchronous event handling.
This will tell the inner interpreter loop to call the application event handler
<em>async_dispatch</em> whenever events are available. This will cause FrameWork window
updates and the user interface to remain working during long computations, but
will slow the interpreter down and may cause surprising results in non-reentrant
code (such as FrameWork itself). By default <em>async_dispatch</em> will immediately
call <em>our_dispatch</em> but you may override this to handle only certain events
asynchronously. Events you do not handle will be passed to Sioux and such.</p>
<p>The old on/off value is returned.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application._quit">
<code class="descclassname">Application.</code><code class="descname">_quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application._quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Terminate the running <a class="reference internal" href="#FrameWork.Application.mainloop" title="FrameWork.Application.mainloop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mainloop()</span></code></a> call at the next convenient moment.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.do_char">
<code class="descclassname">Application.</code><code class="descname">do_char</code><span class="sig-paren">(</span><em>c</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.do_char" title="Permalink to this definition">¶</a></dt>
<dd><p>The user typed character <em>c</em>. The complete details of the event can be found in
the <em>event</em> structure. This method can also be provided in a <code class="docutils literal notranslate"><span class="pre">Window</span></code> object,
which overrides the application-wide handler if the window is frontmost.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.do_dialogevent">
<code class="descclassname">Application.</code><code class="descname">do_dialogevent</code><span class="sig-paren">(</span><em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.do_dialogevent" title="Permalink to this definition">¶</a></dt>
<dd><p>Called early in the event loop to handle modeless dialog events. The default
method simply dispatches the event to the relevant dialog (not through the
<code class="docutils literal notranslate"><span class="pre">DialogWindow</span></code> object involved). Override if you need special handling of
dialog events (keyboard shortcuts, etc).</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Application.idle">
<code class="descclassname">Application.</code><code class="descname">idle</code><span class="sig-paren">(</span><em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Application.idle" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the main event loop when no events are available. The null-event is
passed (so you can look at mouse position, etc).</p>
</dd></dl>

</div>
<div class="section" id="window-objects">
<span id="id2"></span><h2>37.6.2. Window Objects<a class="headerlink" href="#window-objects" title="Permalink to this headline">¶</a></h2>
<p>Window objects have the following methods, among others:</p>
<dl class="method">
<dt id="FrameWork.Window.open">
<code class="descclassname">Window.</code><code class="descname">open</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Override this method to open a window. Store the Mac OS window-id in
<code class="xref py py-attr docutils literal notranslate"><span class="pre">self.wid</span></code> and call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_postopen()</span></code> method to register the window
with the parent application.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Window.close">
<code class="descclassname">Window.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Override this method to do any special processing on window close. Call the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_postclose()</span></code> method to cleanup the parent state.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Window.do_postresize">
<code class="descclassname">Window.</code><code class="descname">do_postresize</code><span class="sig-paren">(</span><em>width</em>, <em>height</em>, <em>macoswindowid</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.do_postresize" title="Permalink to this definition">¶</a></dt>
<dd><p>Called after the window is resized. Override if more needs to be done than
calling <code class="docutils literal notranslate"><span class="pre">InvalRect</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Window.do_contentclick">
<code class="descclassname">Window.</code><code class="descname">do_contentclick</code><span class="sig-paren">(</span><em>local</em>, <em>modifiers</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.do_contentclick" title="Permalink to this definition">¶</a></dt>
<dd><p>The user clicked in the content part of a window. The arguments are the
coordinates (window-relative), the key modifiers and the raw event.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Window.do_update">
<code class="descclassname">Window.</code><code class="descname">do_update</code><span class="sig-paren">(</span><em>macoswindowid</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.do_update" title="Permalink to this definition">¶</a></dt>
<dd><p>An update event for the window was received. Redraw the window.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.Window.do_activate">
<code class="descclassname">Window.</code><code class="descname">do_activate</code><span class="sig-paren">(</span><em>activate</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.Window.do_activate" title="Permalink to this definition">¶</a></dt>
<dd><p>The window was activated (<code class="docutils literal notranslate"><span class="pre">activate</span> <span class="pre">==</span> <span class="pre">1</span></code>) or deactivated (<code class="docutils literal notranslate"><span class="pre">activate</span> <span class="pre">==</span> <span class="pre">0</span></code>).
Handle things like focus highlighting, etc.</p>
</dd></dl>

</div>
<div class="section" id="controlswindow-object">
<span id="id3"></span><h2>37.6.3. ControlsWindow Object<a class="headerlink" href="#controlswindow-object" title="Permalink to this headline">¶</a></h2>
<p>ControlsWindow objects have the following methods besides those of <code class="docutils literal notranslate"><span class="pre">Window</span></code>
objects:</p>
<dl class="method">
<dt id="FrameWork.ControlsWindow.do_controlhit">
<code class="descclassname">ControlsWindow.</code><code class="descname">do_controlhit</code><span class="sig-paren">(</span><em>window</em>, <em>control</em>, <em>pcode</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ControlsWindow.do_controlhit" title="Permalink to this definition">¶</a></dt>
<dd><p>Part <em>pcode</em> of control <em>control</em> was hit by the user. Tracking and such has
already been taken care of.</p>
</dd></dl>

</div>
<div class="section" id="scrolledwindow-object">
<span id="id4"></span><h2>37.6.4. ScrolledWindow Object<a class="headerlink" href="#scrolledwindow-object" title="Permalink to this headline">¶</a></h2>
<p>ScrolledWindow objects are ControlsWindow objects with the following extra
methods:</p>
<dl class="method">
<dt id="FrameWork.ScrolledWindow.scrollbars">
<code class="descclassname">ScrolledWindow.</code><code class="descname">scrollbars</code><span class="sig-paren">(</span><span class="optional">[</span><em>wantx</em><span class="optional">[</span>, <em>wanty</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.scrollbars" title="Permalink to this definition">¶</a></dt>
<dd><p>Create (or destroy) horizontal and vertical scrollbars. The arguments specify
which you want (default: both). The scrollbars always have minimum <code class="docutils literal notranslate"><span class="pre">0</span></code> and
maximum <code class="docutils literal notranslate"><span class="pre">32767</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.getscrollbarvalues">
<code class="descclassname">ScrolledWindow.</code><code class="descname">getscrollbarvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.getscrollbarvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>You must supply this method. It should return a tuple <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code> giving the
current position of the scrollbars (between <code class="docutils literal notranslate"><span class="pre">0</span></code> and <code class="docutils literal notranslate"><span class="pre">32767</span></code>). You can return
<code class="docutils literal notranslate"><span class="pre">None</span></code> for either to indicate the whole document is visible in that direction.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.updatescrollbars">
<code class="descclassname">ScrolledWindow.</code><code class="descname">updatescrollbars</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.updatescrollbars" title="Permalink to this definition">¶</a></dt>
<dd><p>Call this method when the document has changed. It will call
<a class="reference internal" href="#FrameWork.ScrolledWindow.getscrollbarvalues" title="FrameWork.ScrolledWindow.getscrollbarvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getscrollbarvalues()</span></code></a> and update the scrollbars.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.scrollbar_callback">
<code class="descclassname">ScrolledWindow.</code><code class="descname">scrollbar_callback</code><span class="sig-paren">(</span><em>which</em>, <em>what</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.scrollbar_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Supplied by you and called after user interaction. <em>which</em> will be <code class="docutils literal notranslate"><span class="pre">'x'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'y'</span></code>, <em>what</em> will be <code class="docutils literal notranslate"><span class="pre">'-'</span></code>, <code class="docutils literal notranslate"><span class="pre">'--'</span></code>, <code class="docutils literal notranslate"><span class="pre">'set'</span></code>, <code class="docutils literal notranslate"><span class="pre">'++'</span></code> or <code class="docutils literal notranslate"><span class="pre">'+'</span></code>. For
<code class="docutils literal notranslate"><span class="pre">'set'</span></code>, <em>value</em> will contain the new scrollbar position.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.scalebarvalues">
<code class="descclassname">ScrolledWindow.</code><code class="descname">scalebarvalues</code><span class="sig-paren">(</span><em>absmin</em>, <em>absmax</em>, <em>curmin</em>, <em>curmax</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.scalebarvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>Auxiliary method to help you calculate values to return from
<a class="reference internal" href="#FrameWork.ScrolledWindow.getscrollbarvalues" title="FrameWork.ScrolledWindow.getscrollbarvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getscrollbarvalues()</span></code></a>. You pass document minimum and maximum value and
topmost (leftmost) and bottommost (rightmost) visible values and it returns the
correct number or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.do_activate">
<code class="descclassname">ScrolledWindow.</code><code class="descname">do_activate</code><span class="sig-paren">(</span><em>onoff</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.do_activate" title="Permalink to this definition">¶</a></dt>
<dd><p>Takes care of dimming/highlighting scrollbars when a window becomes frontmost.
If you override this method, call this one at the end of your method.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.do_postresize">
<code class="descclassname">ScrolledWindow.</code><code class="descname">do_postresize</code><span class="sig-paren">(</span><em>width</em>, <em>height</em>, <em>window</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.do_postresize" title="Permalink to this definition">¶</a></dt>
<dd><p>Moves scrollbars to the correct position. Call this method initially if you
override it.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.ScrolledWindow.do_controlhit">
<code class="descclassname">ScrolledWindow.</code><code class="descname">do_controlhit</code><span class="sig-paren">(</span><em>window</em>, <em>control</em>, <em>pcode</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.ScrolledWindow.do_controlhit" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles scrollbar interaction. If you override it call this method first, a
nonzero return value indicates the hit was in the scrollbars and has been
handled.</p>
</dd></dl>

</div>
<div class="section" id="dialogwindow-objects">
<span id="id5"></span><h2>37.6.5. DialogWindow Objects<a class="headerlink" href="#dialogwindow-objects" title="Permalink to this headline">¶</a></h2>
<p>DialogWindow objects have the following methods besides those of <code class="docutils literal notranslate"><span class="pre">Window</span></code>
objects:</p>
<dl class="method">
<dt id="FrameWork.DialogWindow.open">
<code class="descclassname">DialogWindow.</code><code class="descname">open</code><span class="sig-paren">(</span><em>resid</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.DialogWindow.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Create the dialog window, from the DLOG resource with id <em>resid</em>. The dialog
object is stored in <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.wid</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="FrameWork.DialogWindow.do_itemhit">
<code class="descclassname">DialogWindow.</code><code class="descname">do_itemhit</code><span class="sig-paren">(</span><em>item</em>, <em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#FrameWork.DialogWindow.do_itemhit" title="Permalink to this definition">¶</a></dt>
<dd><p>Item number <em>item</em> was hit. You are responsible for redrawing toggle buttons,
etc.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a><ul>
<li><a class="reference internal" href="#application-objects">37.6.1. Application Objects</a></li>
<li><a class="reference internal" href="#window-objects">37.6.2. Window Objects</a></li>
<li><a class="reference internal" href="#controlswindow-object">37.6.3. ControlsWindow Object</a></li>
<li><a class="reference internal" href="#scrolledwindow-object">37.6.4. ScrolledWindow Object</a></li>
<li><a class="reference internal" href="#dialogwindow-objects">37.6.5. DialogWindow Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="easydialogs.html"
                        title="previous chapter">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="autogil.html"
                        title="next chapter">37.7. <code class="docutils literal notranslate"><span class="pre">autoGIL</span></code> — Global Interpreter Lock handling in event loops</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/framework.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="autogil.html" title="37.7. autoGIL — Global Interpreter Lock handling in event loops"
             >next</a> |</li>
        <li class="right" >
          <a href="easydialogs.html" title="37.5. EasyDialogs — Basic Macintosh dialogs"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\(��html/library/frameworks.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>23. Program Frameworks &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="23.1. cmd — Support for line-oriented command interpreters" href="cmd.html" />
    <link rel="prev" title="22.2. locale — Internationalization services" href="locale.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/frameworks.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmd.html" title="23.1. cmd — Support for line-oriented command interpreters"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="locale.html" title="22.2. locale — Internationalization services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="program-frameworks">
<span id="frameworks"></span><h1>23. Program Frameworks<a class="headerlink" href="#program-frameworks" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter are frameworks that will largely dictate
the structure of your program.  Currently the modules described  here are all
oriented toward writing command-line interfaces.</p>
<p>The full list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="cmd.html">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cmd.html#cmd-objects">23.1.1. Cmd Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="shlex.html">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a><ul>
<li class="toctree-l2"><a class="reference internal" href="shlex.html#shlex-objects">23.2.1. shlex Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="shlex.html#parsing-rules">23.2.2. Parsing Rules</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="locale.html"
                        title="previous chapter">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cmd.html"
                        title="next chapter">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/frameworks.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmd.html" title="23.1. cmd — Support for line-oriented command interpreters"
             >next</a> |</li>
        <li class="right" >
          <a href="locale.html" title="22.2. locale — Internationalization services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�A�	����html/library/ftplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.8. ftplib — FTP protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.9. poplib — POP3 protocol client" href="poplib.html" />
    <link rel="prev" title="20.7. httplib — HTTP protocol client" href="httplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ftplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="poplib.html" title="20.9. poplib — POP3 protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="httplib.html" title="20.7. httplib — HTTP protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ftplib">
<span id="ftplib-ftp-protocol-client"></span><h1>20.8. <a class="reference internal" href="#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> — FTP protocol client<a class="headerlink" href="#module-ftplib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/ftplib.py">Lib/ftplib.py</a></p>
<hr class="docutils" />
<p>This module defines the class <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> and a few related items. The
<a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> class implements the client side of the FTP protocol.  You can use
this to write Python programs that perform a variety of automated FTP jobs, such
as mirroring other FTP servers.  It is also used by the module <a class="reference internal" href="urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> to
handle URLs that use FTP.  For more information on FTP (File Transfer Protocol),
see Internet <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc959.html"><strong>RFC 959</strong></a>.</p>
<p>Here’s a sample session using the <a class="reference internal" href="#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ftplib</span> <span class="k">import</span> <span class="n">FTP</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span> <span class="o">=</span> <span class="n">FTP</span><span class="p">(</span><span class="s1">&#39;ftp.debian.org&#39;</span><span class="p">)</span>     <span class="c1"># connect to host, default port</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span><span class="o">.</span><span class="n">login</span><span class="p">()</span>                     <span class="c1"># user anonymous, passwd anonymous@</span>
<span class="go">&#39;230 Login successful.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span><span class="o">.</span><span class="n">cwd</span><span class="p">(</span><span class="s1">&#39;debian&#39;</span><span class="p">)</span>               <span class="c1"># change into &quot;debian&quot; directory</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span><span class="o">.</span><span class="n">retrlines</span><span class="p">(</span><span class="s1">&#39;LIST&#39;</span><span class="p">)</span>           <span class="c1"># list directory contents</span>
<span class="go">-rw-rw-r--    1 1176     1176         1063 Jun 15 10:18 README</span>
<span class="gp">...</span>
<span class="go">drwxr-sr-x    5 1176     1176         4096 Dec 19  2000 pool</span>
<span class="go">drwxr-sr-x    4 1176     1176         4096 Nov 17  2008 project</span>
<span class="go">drwxr-xr-x    3 1176     1176         4096 Oct 10  2012 tools</span>
<span class="go">&#39;226 Directory send OK.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span><span class="o">.</span><span class="n">retrbinary</span><span class="p">(</span><span class="s1">&#39;RETR README&#39;</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;README&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">write</span><span class="p">)</span>
<span class="go">&#39;226 Transfer complete.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftp</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>The module defines the following items:</p>
<dl class="class">
<dt id="ftplib.FTP">
<em class="property">class </em><code class="descclassname">ftplib.</code><code class="descname">FTP</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>user</em><span class="optional">[</span>, <em>passwd</em><span class="optional">[</span>, <em>acct</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> class.  When <em>host</em> is given, the
method call <code class="docutils literal notranslate"><span class="pre">connect(host)</span></code> is made.  When <em>user</em> is given, additionally
the method call <code class="docutils literal notranslate"><span class="pre">login(user,</span> <span class="pre">passwd,</span> <span class="pre">acct)</span></code> is made (where <em>passwd</em> and
<em>acct</em> default to the empty string when not given).  The optional <em>timeout</em>
parameter specifies a timeout in seconds for blocking operations like the
connection attempt (if is not specified, the global default timeout setting
will be used).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="ftplib.FTP_TLS">
<em class="property">class </em><code class="descclassname">ftplib.</code><code class="descname">FTP_TLS</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>user</em><span class="optional">[</span>, <em>passwd</em><span class="optional">[</span>, <em>acct</em><span class="optional">[</span>, <em>keyfile</em><span class="optional">[</span>, <em>certfile</em><span class="optional">[</span>, <em>context</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP_TLS" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> subclass which adds TLS support to FTP as described in
<span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4217.html"><strong>RFC 4217</strong></a>.
Connect as usual to port 21 implicitly securing the FTP control connection
before authenticating. Securing the data connection requires the user to
explicitly ask for it by calling the <a class="reference internal" href="#ftplib.FTP_TLS.prot_p" title="ftplib.FTP_TLS.prot_p"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prot_p()</span></code></a> method.  <em>context</em>
is a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> object which allows bundling SSL configuration
options, certificates and private keys into a single (potentially
long-lived) structure.  Please read <a class="reference internal" href="ssl.html#ssl-security"><span class="std std-ref">Security considerations</span></a> for best practices.</p>
<p><em>keyfile</em> and <em>certfile</em> are a legacy alternative to <em>context</em> – they
can point to PEM-formatted private key and certificate chain files
(respectively) for the SSL connection.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.10: </span>The <em>context</em> parameter was added.</p>
</div>
<p>Here’s a sample session using the <a class="reference internal" href="#ftplib.FTP_TLS" title="ftplib.FTP_TLS"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP_TLS</span></code></a> class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">ftplib</span> <span class="k">import</span> <span class="n">FTP_TLS</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftps</span> <span class="o">=</span> <span class="n">FTP_TLS</span><span class="p">(</span><span class="s1">&#39;ftp.python.org&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftps</span><span class="o">.</span><span class="n">login</span><span class="p">()</span>           <span class="c1"># login anonymously before securing control channel</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftps</span><span class="o">.</span><span class="n">prot_p</span><span class="p">()</span>          <span class="c1"># switch to secure data connection</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftps</span><span class="o">.</span><span class="n">retrlines</span><span class="p">(</span><span class="s1">&#39;LIST&#39;</span><span class="p">)</span> <span class="c1"># list directory content securely</span>
<span class="go">total 9</span>
<span class="go">drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 .</span>
<span class="go">drwxr-xr-x   8 root     wheel        1024 Jan  3  1994 ..</span>
<span class="go">drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 bin</span>
<span class="go">drwxr-xr-x   2 root     wheel        1024 Jan  3  1994 etc</span>
<span class="go">d-wxrwxr-x   2 ftp      wheel        1024 Sep  5 13:43 incoming</span>
<span class="go">drwxr-xr-x   2 root     wheel        1024 Nov 17  1993 lib</span>
<span class="go">drwxr-xr-x   6 1094     wheel        1024 Sep 13 19:07 pub</span>
<span class="go">drwxr-xr-x   3 root     wheel        1024 Jan  3  1994 usr</span>
<span class="go">-rw-r--r--   1 root     root          312 Aug  1  1994 welcome.msg</span>
<span class="go">&#39;226 Transfer complete.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ftps</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
</dd></dl>

<dl class="exception">
<dt id="ftplib.error_reply">
<em class="property">exception </em><code class="descclassname">ftplib.</code><code class="descname">error_reply</code><a class="headerlink" href="#ftplib.error_reply" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an unexpected reply is received from the server.</p>
</dd></dl>

<dl class="exception">
<dt id="ftplib.error_temp">
<em class="property">exception </em><code class="descclassname">ftplib.</code><code class="descname">error_temp</code><a class="headerlink" href="#ftplib.error_temp" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error code signifying a temporary error (response
codes in the range 400–499) is received.</p>
</dd></dl>

<dl class="exception">
<dt id="ftplib.error_perm">
<em class="property">exception </em><code class="descclassname">ftplib.</code><code class="descname">error_perm</code><a class="headerlink" href="#ftplib.error_perm" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error code signifying a permanent error (response
codes in the range 500–599) is received.</p>
</dd></dl>

<dl class="exception">
<dt id="ftplib.error_proto">
<em class="property">exception </em><code class="descclassname">ftplib.</code><code class="descname">error_proto</code><a class="headerlink" href="#ftplib.error_proto" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a reply is received from the server that does not fit
the response specifications of the File Transfer Protocol, i.e. begin with a
digit in the range 1–5.</p>
</dd></dl>

<dl class="data">
<dt id="ftplib.all_errors">
<code class="descclassname">ftplib.</code><code class="descname">all_errors</code><a class="headerlink" href="#ftplib.all_errors" title="Permalink to this definition">¶</a></dt>
<dd><p>The set of all exceptions (as a tuple) that methods of <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a>
instances may raise as a result of problems with the FTP connection (as
opposed to programming errors made by the caller).  This set includes the
four exceptions listed above as well as <a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> and
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt>Module <a class="reference internal" href="netrc.html#module-netrc" title="netrc: Loading of .netrc files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">netrc</span></code></a></dt>
<dd>Parser for the <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code> file format.  The file <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code> is
typically used by FTP clients to load user authentication information
before prompting the user.</dd>
</dl>
<p class="last" id="index-3">The file <code class="file docutils literal notranslate"><span class="pre">Tools/scripts/ftpmirror.py</span></code> in the Python source distribution is
a script that can mirror FTP sites, or portions thereof, using the <a class="reference internal" href="#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a>
module. It can be used as an extended example that applies this module.</p>
</div>
<div class="section" id="ftp-objects">
<span id="id1"></span><h2>20.8.1. FTP Objects<a class="headerlink" href="#ftp-objects" title="Permalink to this headline">¶</a></h2>
<p>Several methods are available in two flavors: one for handling text files and
another for binary files.  These are named for the command which is used
followed by <code class="docutils literal notranslate"><span class="pre">lines</span></code> for the text version or <code class="docutils literal notranslate"><span class="pre">binary</span></code> for the binary version.</p>
<p><a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="ftplib.FTP.set_debuglevel">
<code class="descclassname">FTP.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the instance’s debugging level.  This controls the amount of debugging
output printed.  The default, <code class="docutils literal notranslate"><span class="pre">0</span></code>, produces no debugging output.  A value of
<code class="docutils literal notranslate"><span class="pre">1</span></code> produces a moderate amount of debugging output, generally a single line
per request.  A value of <code class="docutils literal notranslate"><span class="pre">2</span></code> or higher produces the maximum amount of
debugging output, logging each line sent and received on the control connection.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.connect">
<code class="descclassname">FTP.</code><code class="descname">connect</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to the given host and port.  The default port number is <code class="docutils literal notranslate"><span class="pre">21</span></code>, as
specified by the FTP protocol specification.  It is rarely needed to specify a
different port number.  This function should be called only once for each
instance; it should not be called at all if a host was given when the instance
was created.  All other methods can only be used after a connection has been
made.</p>
<p>The optional <em>timeout</em> parameter specifies a timeout in seconds for the
connection attempt. If no <em>timeout</em> is passed, the global default timeout
setting will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.getwelcome">
<code class="descclassname">FTP.</code><code class="descname">getwelcome</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.getwelcome" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the welcome message sent by the server in reply to the initial
connection.  (This message sometimes contains disclaimers or help information
that may be relevant to the user.)</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.login">
<code class="descclassname">FTP.</code><code class="descname">login</code><span class="sig-paren">(</span><span class="optional">[</span><em>user</em><span class="optional">[</span>, <em>passwd</em><span class="optional">[</span>, <em>acct</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.login" title="Permalink to this definition">¶</a></dt>
<dd><p>Log in as the given <em>user</em>.  The <em>passwd</em> and <em>acct</em> parameters are optional and
default to the empty string.  If no <em>user</em> is specified, it defaults to
<code class="docutils literal notranslate"><span class="pre">'anonymous'</span></code>.  If <em>user</em> is <code class="docutils literal notranslate"><span class="pre">'anonymous'</span></code>, the default <em>passwd</em> is
<code class="docutils literal notranslate"><span class="pre">'anonymous&#64;'</span></code>.  This function should be called only once for each instance,
after a connection has been established; it should not be called at all if a
host and user were given when the instance was created.  Most FTP commands are
only allowed after the client has logged in.  The <em>acct</em> parameter supplies
“accounting information”; few systems implement this.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.abort">
<code class="descclassname">FTP.</code><code class="descname">abort</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.abort" title="Permalink to this definition">¶</a></dt>
<dd><p>Abort a file transfer that is in progress.  Using this does not always work, but
it’s worth a try.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.sendcmd">
<code class="descclassname">FTP.</code><code class="descname">sendcmd</code><span class="sig-paren">(</span><em>command</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.sendcmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a simple command string to the server and return the response string.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.voidcmd">
<code class="descclassname">FTP.</code><code class="descname">voidcmd</code><span class="sig-paren">(</span><em>command</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.voidcmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a simple command string to the server and handle the response.  Return
nothing if a response code corresponding to success (codes in the range
200–299) is received.  Raise <a class="reference internal" href="#ftplib.error_reply" title="ftplib.error_reply"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error_reply</span></code></a> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.retrbinary">
<code class="descclassname">FTP.</code><code class="descname">retrbinary</code><span class="sig-paren">(</span><em>command</em>, <em>callback</em><span class="optional">[</span>, <em>maxblocksize</em><span class="optional">[</span>, <em>rest</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.retrbinary" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a file in binary transfer mode.  <em>command</em> should be an appropriate
<code class="docutils literal notranslate"><span class="pre">RETR</span></code> command: <code class="docutils literal notranslate"><span class="pre">'RETR</span> <span class="pre">filename'</span></code>. The <em>callback</em> function is called for
each block of data received, with a single string argument giving the data
block. The optional <em>maxblocksize</em> argument specifies the maximum chunk size to
read on the low-level socket object created to do the actual transfer (which
will also be the largest size of the data blocks passed to <em>callback</em>).  A
reasonable default is chosen. <em>rest</em> means the same thing as in the
<a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.retrlines">
<code class="descclassname">FTP.</code><code class="descname">retrlines</code><span class="sig-paren">(</span><em>command</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.retrlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a file or directory listing in ASCII transfer mode.  <em>command</em>
should be an appropriate <code class="docutils literal notranslate"><span class="pre">RETR</span></code> command (see <a class="reference internal" href="#ftplib.FTP.retrbinary" title="ftplib.FTP.retrbinary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">retrbinary()</span></code></a>) or a
command such as <code class="docutils literal notranslate"><span class="pre">LIST</span></code>, <code class="docutils literal notranslate"><span class="pre">NLST</span></code> or <code class="docutils literal notranslate"><span class="pre">MLSD</span></code> (usually just the string
<code class="docutils literal notranslate"><span class="pre">'LIST'</span></code>).  <code class="docutils literal notranslate"><span class="pre">LIST</span></code> retrieves a list of files and information about those files.
<code class="docutils literal notranslate"><span class="pre">NLST</span></code> retrieves a list of file names.  On some servers, <code class="docutils literal notranslate"><span class="pre">MLSD</span></code> retrieves
a machine readable list of files and information about those files.  The <em>callback</em>
function is called for each line with a string argument containing the line with
the trailing CRLF stripped.  The default <em>callback</em> prints the line to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.set_pasv">
<code class="descclassname">FTP.</code><code class="descname">set_pasv</code><span class="sig-paren">(</span><em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.set_pasv" title="Permalink to this definition">¶</a></dt>
<dd><p>Enable “passive” mode if <em>val</em> is true, otherwise disable passive mode.  (In
Python 2.0 and before, passive mode was off by default; in Python 2.1 and later,
it is on by default.)</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.storbinary">
<code class="descclassname">FTP.</code><code class="descname">storbinary</code><span class="sig-paren">(</span><em>command</em>, <em>fp</em><span class="optional">[</span>, <em>blocksize</em>, <em>callback</em>, <em>rest</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.storbinary" title="Permalink to this definition">¶</a></dt>
<dd><p>Store a file in binary transfer mode.  <em>command</em> should be an appropriate
<code class="docutils literal notranslate"><span class="pre">STOR</span></code> command: <code class="docutils literal notranslate"><span class="pre">&quot;STOR</span> <span class="pre">filename&quot;</span></code>. <em>fp</em> is an open file object which is
read until EOF using its <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method in blocks of size <em>blocksize</em> to
provide the data to be stored.  The <em>blocksize</em> argument defaults to 8192.
<em>callback</em> is an optional single parameter callable that is called
on each block of data after it is sent. <em>rest</em> means the same thing as in
the <a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a> method.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>default for <em>blocksize</em> added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>callback</em> parameter added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>rest</em> parameter added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.storlines">
<code class="descclassname">FTP.</code><code class="descname">storlines</code><span class="sig-paren">(</span><em>command</em>, <em>fp</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.storlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Store a file in ASCII transfer mode.  <em>command</em> should be an appropriate
<code class="docutils literal notranslate"><span class="pre">STOR</span></code> command (see <a class="reference internal" href="#ftplib.FTP.storbinary" title="ftplib.FTP.storbinary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">storbinary()</span></code></a>).  Lines are read until EOF from the
open file object <em>fp</em> using its <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method to provide
the data to be stored.  <em>callback</em> is an optional single parameter callable
that is called on each line after it is sent.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>callback</em> parameter added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.transfercmd">
<code class="descclassname">FTP.</code><code class="descname">transfercmd</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>rest</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.transfercmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Initiate a transfer over the data connection.  If the transfer is active, send an
<code class="docutils literal notranslate"><span class="pre">EPRT</span></code> or  <code class="docutils literal notranslate"><span class="pre">PORT</span></code> command and the transfer command specified by <em>cmd</em>, and
accept the connection.  If the server is passive, send an <code class="docutils literal notranslate"><span class="pre">EPSV</span></code> or <code class="docutils literal notranslate"><span class="pre">PASV</span></code>
command, connect to it, and start the transfer command.  Either way, return the
socket for the connection.</p>
<p>If optional <em>rest</em> is given, a <code class="docutils literal notranslate"><span class="pre">REST</span></code> command is sent to the server, passing
<em>rest</em> as an argument.  <em>rest</em> is usually a byte offset into the requested file,
telling the server to restart sending the file’s bytes at the requested offset,
skipping over the initial bytes.  Note however that RFC 959 requires only that
<em>rest</em> be a string containing characters in the printable range from ASCII code
33 to ASCII code 126.  The <a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a> method, therefore, converts
<em>rest</em> to a string, but no check is performed on the string’s contents.  If the
server does not recognize the <code class="docutils literal notranslate"><span class="pre">REST</span></code> command, an <a class="reference internal" href="#ftplib.error_reply" title="ftplib.error_reply"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error_reply</span></code></a> exception
will be raised.  If this happens, simply call <a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a> without a
<em>rest</em> argument.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.ntransfercmd">
<code class="descclassname">FTP.</code><code class="descname">ntransfercmd</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>rest</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.ntransfercmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a>, but returns a tuple of the data connection and the
expected size of the data.  If the expected size could not be computed, <code class="docutils literal notranslate"><span class="pre">None</span></code>
will be returned as the expected size.  <em>cmd</em> and <em>rest</em> means the same thing as
in <a class="reference internal" href="#ftplib.FTP.transfercmd" title="ftplib.FTP.transfercmd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">transfercmd()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.nlst">
<code class="descclassname">FTP.</code><code class="descname">nlst</code><span class="sig-paren">(</span><em>argument</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.nlst" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of file names as returned by the <code class="docutils literal notranslate"><span class="pre">NLST</span></code> command.  The
optional <em>argument</em> is a directory to list (default is the current server
directory).  Multiple arguments can be used to pass non-standard options to
the <code class="docutils literal notranslate"><span class="pre">NLST</span></code> command.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.dir">
<code class="descclassname">FTP.</code><code class="descname">dir</code><span class="sig-paren">(</span><em>argument</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Produce a directory listing as returned by the <code class="docutils literal notranslate"><span class="pre">LIST</span></code> command, printing it to
standard output.  The optional <em>argument</em> is a directory to list (default is the
current server directory).  Multiple arguments can be used to pass non-standard
options to the <code class="docutils literal notranslate"><span class="pre">LIST</span></code> command.  If the last argument is a function, it is used
as a <em>callback</em> function as for <a class="reference internal" href="#ftplib.FTP.retrlines" title="ftplib.FTP.retrlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">retrlines()</span></code></a>; the default prints to
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.  This method returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.rename">
<code class="descclassname">FTP.</code><code class="descname">rename</code><span class="sig-paren">(</span><em>fromname</em>, <em>toname</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.rename" title="Permalink to this definition">¶</a></dt>
<dd><p>Rename file <em>fromname</em> on the server to <em>toname</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.delete">
<code class="descclassname">FTP.</code><code class="descname">delete</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the file named <em>filename</em> from the server.  If successful, returns the
text of the response, otherwise raises <a class="reference internal" href="#ftplib.error_perm" title="ftplib.error_perm"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error_perm</span></code></a> on permission errors or
<a class="reference internal" href="#ftplib.error_reply" title="ftplib.error_reply"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error_reply</span></code></a> on other errors.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.cwd">
<code class="descclassname">FTP.</code><code class="descname">cwd</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.cwd" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current directory on the server.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.mkd">
<code class="descclassname">FTP.</code><code class="descname">mkd</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.mkd" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new directory on the server.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.pwd">
<code class="descclassname">FTP.</code><code class="descname">pwd</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.pwd" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the pathname of the current directory on the server.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.rmd">
<code class="descclassname">FTP.</code><code class="descname">rmd</code><span class="sig-paren">(</span><em>dirname</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.rmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the directory named <em>dirname</em> on the server.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.size">
<code class="descclassname">FTP.</code><code class="descname">size</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.size" title="Permalink to this definition">¶</a></dt>
<dd><p>Request the size of the file named <em>filename</em> on the server.  On success, the
size of the file is returned as an integer, otherwise <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.
Note that the <code class="docutils literal notranslate"><span class="pre">SIZE</span></code> command is not  standardized, but is supported by many
common server implementations.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.quit">
<code class="descclassname">FTP.</code><code class="descname">quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">QUIT</span></code> command to the server and close the connection. This is the
“polite” way to close a connection, but it may raise an exception if the server
responds with an error to the <code class="docutils literal notranslate"><span class="pre">QUIT</span></code> command.  This implies a call to the
<a class="reference internal" href="#ftplib.FTP.close" title="ftplib.FTP.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method which renders the <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> instance useless for
subsequent calls (see below).</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP.close">
<code class="descclassname">FTP.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the connection unilaterally.  This should not be applied to an already
closed connection such as after a successful call to <a class="reference internal" href="#ftplib.FTP.quit" title="ftplib.FTP.quit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">quit()</span></code></a>.
After this call the <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a> instance should not be used any more (after
a call to <a class="reference internal" href="#ftplib.FTP.close" title="ftplib.FTP.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> or <a class="reference internal" href="#ftplib.FTP.quit" title="ftplib.FTP.quit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">quit()</span></code></a> you cannot reopen the
connection by issuing another <a class="reference internal" href="#ftplib.FTP.login" title="ftplib.FTP.login"><code class="xref py py-meth docutils literal notranslate"><span class="pre">login()</span></code></a> method).</p>
</dd></dl>

</div>
<div class="section" id="ftp-tls-objects">
<h2>20.8.2. FTP_TLS Objects<a class="headerlink" href="#ftp-tls-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#ftplib.FTP_TLS" title="ftplib.FTP_TLS"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP_TLS</span></code></a> class inherits from <a class="reference internal" href="#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code></a>, defining these additional objects:</p>
<dl class="attribute">
<dt id="ftplib.FTP_TLS.ssl_version">
<code class="descclassname">FTP_TLS.</code><code class="descname">ssl_version</code><a class="headerlink" href="#ftplib.FTP_TLS.ssl_version" title="Permalink to this definition">¶</a></dt>
<dd><p>The SSL version to use (defaults to <a class="reference internal" href="ssl.html#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ssl.PROTOCOL_SSLv23</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP_TLS.auth">
<code class="descclassname">FTP_TLS.</code><code class="descname">auth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP_TLS.auth" title="Permalink to this definition">¶</a></dt>
<dd><p>Set up secure control connection by using TLS or SSL, depending on what
specified in <a class="reference internal" href="#ftplib.FTP_TLS.ssl_version" title="ftplib.FTP_TLS.ssl_version"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ssl_version()</span></code></a> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP_TLS.prot_p">
<code class="descclassname">FTP_TLS.</code><code class="descname">prot_p</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP_TLS.prot_p" title="Permalink to this definition">¶</a></dt>
<dd><p>Set up secure data connection.</p>
</dd></dl>

<dl class="method">
<dt id="ftplib.FTP_TLS.prot_c">
<code class="descclassname">FTP_TLS.</code><code class="descname">prot_c</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ftplib.FTP_TLS.prot_c" title="Permalink to this definition">¶</a></dt>
<dd><p>Set up clear text data connection.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a><ul>
<li><a class="reference internal" href="#ftp-objects">20.8.1. FTP Objects</a></li>
<li><a class="reference internal" href="#ftp-tls-objects">20.8.2. FTP_TLS Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="httplib.html"
                        title="previous chapter">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="poplib.html"
                        title="next chapter">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ftplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="poplib.html" title="20.9. poplib — POP3 protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="httplib.html" title="20.7. httplib — HTTP protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\᭙BH#H#html/library/functions.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Built-in Functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. Built-in Constants" href="constants.html" />
    <link rel="prev" title="1. Introduction" href="intro.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/functions.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="constants.html" title="4. Built-in Constants"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="intro.html" title="1. Introduction"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="built-in-functions">
<span id="built-in-funcs"></span><h1>2. Built-in Functions<a class="headerlink" href="#built-in-functions" title="Permalink to this headline">¶</a></h1>
<p>The Python interpreter has a number of functions built into it that are always
available.  They are listed here in alphabetical order.</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="19%" />
<col width="20%" />
<col width="19%" />
<col width="22%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"></th>
<th class="head"></th>
<th class="head">Built-in Functions</th>
<th class="head"></th>
<th class="head"></th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a></td>
<td><a class="reference internal" href="#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a></td>
<td><a class="reference internal" href="#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a></td>
<td><a class="reference internal" href="#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a></td>
<td><a class="reference internal" href="#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a></td>
<td><a class="reference internal" href="#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a></td>
<td><a class="reference internal" href="#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a></td>
<td><a class="reference internal" href="#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a></td>
<td><a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a></td>
<td><a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a></td>
<td><a class="reference internal" href="#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a></td>
<td><a class="reference internal" href="#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a></td>
<td><a class="reference internal" href="#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#basestring" title="basestring"><code class="xref py py-func docutils literal notranslate"><span class="pre">basestring()</span></code></a></td>
<td><a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a></td>
<td><a class="reference internal" href="#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a></td>
<td><a class="reference internal" href="#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a></td>
<td><a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a></td>
<td><a class="reference internal" href="#file" title="file"><code class="xref py py-func docutils literal notranslate"><span class="pre">file()</span></code></a></td>
<td><a class="reference internal" href="#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a></td>
<td><a class="reference internal" href="#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a></td>
<td><a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a></td>
<td><a class="reference internal" href="#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a></td>
<td><a class="reference internal" href="#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a></td>
<td><a class="reference internal" href="#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a></td>
<td><a class="reference internal" href="#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a></td>
<td><a class="reference internal" href="#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a></td>
<td><a class="reference internal" href="#func-list"><code class="docutils literal notranslate"><span class="pre">list()</span></code></a></td>
<td><a class="reference internal" href="#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a></td>
<td><a class="reference internal" href="#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#callable" title="callable"><code class="xref py py-func docutils literal notranslate"><span class="pre">callable()</span></code></a></td>
<td><a class="reference internal" href="#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a></td>
<td><a class="reference internal" href="#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a></td>
<td><a class="reference internal" href="#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a></td>
<td><a class="reference internal" href="#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a></td>
<td><a class="reference internal" href="#func-frozenset"><code class="docutils literal notranslate"><span class="pre">frozenset()</span></code></a></td>
<td><a class="reference internal" href="#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a></td>
<td><a class="reference internal" href="#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a></td>
<td><a class="reference internal" href="#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a></td>
<td><a class="reference internal" href="#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a></td>
<td><a class="reference internal" href="#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a></td>
<td><a class="reference internal" href="#func-repr"><code class="docutils literal notranslate"><span class="pre">repr()</span></code></a></td>
<td><a class="reference internal" href="#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a></td>
<td><a class="reference internal" href="#globals" title="globals"><code class="xref py py-func docutils literal notranslate"><span class="pre">globals()</span></code></a></td>
<td><a class="reference internal" href="#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a></td>
<td><a class="reference internal" href="#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a></td>
<td><a class="reference internal" href="#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a></td>
<td><a class="reference internal" href="#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a></td>
<td><a class="reference internal" href="#func-memoryview"><code class="docutils literal notranslate"><span class="pre">memoryview()</span></code></a></td>
<td><a class="reference internal" href="#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a></td>
<td><a class="reference internal" href="#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a></td>
<td><a class="reference internal" href="#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a></td>
<td><a class="reference internal" href="#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a></td>
<td><a class="reference internal" href="#func-set"><code class="docutils literal notranslate"><span class="pre">set()</span></code></a></td>
<td></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#delattr" title="delattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">delattr()</span></code></a></td>
<td><a class="reference internal" href="#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a></td>
<td><a class="reference internal" href="#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a></td>
<td><a class="reference internal" href="#setattr" title="setattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">setattr()</span></code></a></td>
<td></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#func-dict"><code class="docutils literal notranslate"><span class="pre">dict()</span></code></a></td>
<td><a class="reference internal" href="#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a></td>
<td><a class="reference internal" href="#object" title="object"><code class="xref py py-func docutils literal notranslate"><span class="pre">object()</span></code></a></td>
<td><a class="reference internal" href="#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a></td>
<td></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a></td>
<td><a class="reference internal" href="#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a></td>
<td><a class="reference internal" href="#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a></td>
<td><a class="reference internal" href="#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a></td>
<td></td>
</tr>
</tbody>
</table>
<p>In addition, there are other four built-in functions that are no longer
considered essential: <a class="reference internal" href="#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a>, <a class="reference internal" href="#buffer" title="buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">buffer()</span></code></a>, <a class="reference internal" href="#coerce" title="coerce"><code class="xref py py-func docutils literal notranslate"><span class="pre">coerce()</span></code></a>, and
<a class="reference internal" href="#intern" title="intern"><code class="xref py py-func docutils literal notranslate"><span class="pre">intern()</span></code></a>.  They are documented in the <a class="reference internal" href="#non-essential-built-in-funcs"><span class="std std-ref">Non-essential Built-in Functions</span></a>
section.</p>
<dl class="function">
<dt id="abs">
<code class="descname">abs</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#abs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the absolute value of a number.  The argument may be a plain or long
integer or a floating point number.  If the argument is a complex number, its
magnitude is returned.</p>
</dd></dl>

<dl class="function">
<dt id="all">
<code class="descname">all</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#all" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all elements of the <em>iterable</em> are true (or if the iterable
is empty).  Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">all</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">element</span><span class="p">:</span>
            <span class="k">return</span> <span class="kc">False</span>
    <span class="k">return</span> <span class="kc">True</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="any">
<code class="descname">any</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#any" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if any element of the <em>iterable</em> is true.  If the iterable
is empty, return <code class="docutils literal notranslate"><span class="pre">False</span></code>.  Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">any</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">element</span><span class="p">:</span>
            <span class="k">return</span> <span class="kc">True</span>
    <span class="k">return</span> <span class="kc">False</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="basestring">
<code class="descname">basestring</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#basestring" title="Permalink to this definition">¶</a></dt>
<dd><p>This abstract type is the superclass for <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>. It
cannot be called or instantiated, but it can be used to test whether an object
is an instance of <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>. <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span>
<span class="pre">basestring)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">(str,</span> <span class="pre">unicode))</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="bin">
<code class="descname">bin</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#bin" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an integer number to a binary string. The result is a valid Python
expression.  If <em>x</em> is not a Python <a class="reference internal" href="#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> object, it has to define an
<a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method that returns an integer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="bool">
<em class="property">class </em><code class="descname">bool</code><span class="sig-paren">(</span><span class="optional">[</span><em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bool" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a Boolean value, i.e. one of <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.  <em>x</em> is converted
using the standard truth testing procedure.  If <em>x</em> is false or omitted, this
returns <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>; otherwise it returns <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>. <a class="reference internal" href="#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> is
also a class, which is a subclass of <a class="reference internal" href="#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>. Class <a class="reference internal" href="#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> cannot
be subclassed further.  Its only instances are <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> and
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<div class="versionadded" id="index-0">
<p><span class="versionmodified">New in version 2.2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>If no argument is given, this function returns <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="bytearray">
<em class="property">class </em><code class="descname">bytearray</code><span class="sig-paren">(</span><span class="optional">[</span><em>source</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#bytearray" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new array of bytes.  The <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> class is a mutable
sequence of integers in the range 0 &lt;= x &lt; 256.  It has most of the usual
methods of mutable sequences, described in <a class="reference internal" href="stdtypes.html#typesseq-mutable"><span class="std std-ref">Mutable Sequence Types</span></a>, as well
as most methods that the <a class="reference internal" href="#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type has, see <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a>.</p>
<p>The optional <em>source</em> parameter can be used to initialize the array in a few
different ways:</p>
<ul class="simple">
<li>If it is <em>unicode</em>, you must also give the <em>encoding</em> (and optionally,
<em>errors</em>) parameters; <a class="reference internal" href="#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a> then converts the unicode to
bytes using <code class="xref py py-meth docutils literal notranslate"><span class="pre">unicode.encode()</span></code>.</li>
<li>If it is an <em>integer</em>, the array will have that size and will be
initialized with null bytes.</li>
<li>If it is an object conforming to the <em>buffer</em> interface, a read-only buffer
of the object will be used to initialize the bytes array.</li>
<li>If it is an <em>iterable</em>, it must be an iterable of integers in the range
<code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">256</span></code>, which are used as the initial contents of the array.</li>
</ul>
<p>Without an argument, an array of size 0 is created.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="callable">
<code class="descname">callable</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#callable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the <em>object</em> argument appears callable,
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> if not.  If this
returns true, it is still possible that a call fails, but if it is false,
calling <em>object</em> will never succeed.  Note that classes are callable (calling a
class returns a new instance); class instances are callable if they have a
<a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method.</p>
</dd></dl>

<dl class="function">
<dt id="chr">
<code class="descname">chr</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#chr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string of one character whose ASCII code is the integer <em>i</em>.  For
example, <code class="docutils literal notranslate"><span class="pre">chr(97)</span></code> returns the string <code class="docutils literal notranslate"><span class="pre">'a'</span></code>. This is the inverse of
<a class="reference internal" href="#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>.  The argument must be in the range [0..255], inclusive;
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised if <em>i</em> is outside that range. See
also <a class="reference internal" href="#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="classmethod">
<code class="descname">classmethod</code><span class="sig-paren">(</span><em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#classmethod" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a class method for <em>function</em>.</p>
<p>A class method receives the class as implicit first argument, just like an
instance method receives the instance. To declare a class method, use this
idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="o">...</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">&#64;classmethod</span></code> form is a function <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> – see the description
of function definitions in <a class="reference internal" href="../reference/compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for details.</p>
<p>It can be called either on the class (such as <code class="docutils literal notranslate"><span class="pre">C.f()</span></code>) or on an instance (such
as <code class="docutils literal notranslate"><span class="pre">C().f()</span></code>).  The instance is ignored except for its class. If a class
method is called for a derived class, the derived class object is passed as the
implied first argument.</p>
<p>Class methods are different than C++ or Java static methods. If you want those,
see <a class="reference internal" href="#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> in this section.</p>
<p>For more information on class methods, consult the documentation on the standard
type hierarchy in <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Function decorator syntax added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="cmp">
<code class="descname">cmp</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#cmp" title="Permalink to this definition">¶</a></dt>
<dd><p>Compare the two objects <em>x</em> and <em>y</em> and return an integer according to the
outcome.  The return value is negative if <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code>, zero if <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and
strictly positive if <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="compile">
<code class="descname">compile</code><span class="sig-paren">(</span><em>source</em>, <em>filename</em>, <em>mode</em><span class="optional">[</span>, <em>flags</em><span class="optional">[</span>, <em>dont_inherit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile the <em>source</em> into a code or AST object.  Code objects can be executed
by an <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement or evaluated by a call to <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.
<em>source</em> can either be a Unicode string, a <em>Latin-1</em> encoded string or an
AST object.
Refer to the <a class="reference internal" href="ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module documentation for information on how to work
with AST objects.</p>
<p>The <em>filename</em> argument should give the file from which the code was read;
pass some recognizable value if it wasn’t read from a file (<code class="docutils literal notranslate"><span class="pre">'&lt;string&gt;'</span></code> is
commonly used).</p>
<p>The <em>mode</em> argument specifies what kind of code must be compiled; it can be
<code class="docutils literal notranslate"><span class="pre">'exec'</span></code> if <em>source</em> consists of a sequence of statements, <code class="docutils literal notranslate"><span class="pre">'eval'</span></code> if it
consists of a single expression, or <code class="docutils literal notranslate"><span class="pre">'single'</span></code> if it consists of a single
interactive statement (in the latter case, expression statements that
evaluate to something other than <code class="docutils literal notranslate"><span class="pre">None</span></code> will be printed).</p>
<p>The optional arguments <em>flags</em> and <em>dont_inherit</em> control which future
statements (see <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0236"><strong>PEP 236</strong></a>) affect the compilation of <em>source</em>.  If neither
is present (or both are zero) the code is compiled with those future
statements that are in effect in the code that is calling <a class="reference internal" href="#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>.  If the
<em>flags</em> argument is given and <em>dont_inherit</em> is not (or is zero) then the
future statements specified by the <em>flags</em> argument are used in addition to
those that would be used anyway. If <em>dont_inherit</em> is a non-zero integer then
the <em>flags</em> argument is it – the future statements in effect around the call
to compile are ignored.</p>
<p>Future statements are specified by bits which can be bitwise ORed together to
specify multiple statements.  The bitfield required to specify a given feature
can be found as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">compiler_flag</span></code> attribute on
the <code class="xref py py-class docutils literal notranslate"><span class="pre">_Feature</span></code> instance in the <a class="reference internal" href="__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> module.</p>
<p>This function raises <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if the compiled source is invalid,
and <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the source contains null bytes.</p>
<p>If you want to parse Python code into its AST representation, see
<a class="reference internal" href="ast.html#ast.parse" title="ast.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">ast.parse()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When compiling a string with multi-line code in <code class="docutils literal notranslate"><span class="pre">'single'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'eval'</span></code> mode, input must be terminated by at least one newline
character.  This is to facilitate detection of incomplete and complete
statements in the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> module.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The <em>flags</em> and <em>dont_inherit</em> arguments were added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Support for compiling AST objects.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Allowed use of Windows and Mac newlines.  Also input in <code class="docutils literal notranslate"><span class="pre">'exec'</span></code> mode
does not have to end in a newline anymore.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="complex">
<em class="property">class </em><code class="descname">complex</code><span class="sig-paren">(</span><span class="optional">[</span><em>real</em><span class="optional">[</span>, <em>imag</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#complex" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a complex number with the value <em>real</em> + <em>imag</em>*1j or convert a string or
number to a complex number.  If the first parameter is a string, it will be
interpreted as a complex number and the function must be called without a second
parameter.  The second parameter can never be a string. Each argument may be any
numeric type (including complex). If <em>imag</em> is omitted, it defaults to zero and
the function serves as a numeric conversion function like <a class="reference internal" href="#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>,
<a class="reference internal" href="#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> and <a class="reference internal" href="#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>.  If both arguments are omitted, returns <code class="docutils literal notranslate"><span class="pre">0j</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When converting from a string, the string must not contain whitespace
around the central <code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code> operator.  For example,
<code class="docutils literal notranslate"><span class="pre">complex('1+2j')</span></code> is fine, but <code class="docutils literal notranslate"><span class="pre">complex('1</span> <span class="pre">+</span> <span class="pre">2j')</span></code> raises
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</div>
<p>The complex type is described in <a class="reference internal" href="stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, long, complex</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="delattr">
<code class="descname">delattr</code><span class="sig-paren">(</span><em>object</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#delattr" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a relative of <a class="reference internal" href="#setattr" title="setattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">setattr()</span></code></a>.  The arguments are an object and a
string.  The string must be the name of one of the object’s attributes.  The
function deletes the named attribute, provided the object allows it.  For
example, <code class="docutils literal notranslate"><span class="pre">delattr(x,</span> <span class="pre">'foobar')</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x.foobar</span></code>.</p>
</dd></dl>

<span class="target" id="func-dict"></span><dl class="class">
<dt>
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>**kwarg</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>mapping</em>, <em>**kwarg</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>iterable</em>, <em>**kwarg</em><span class="sig-paren">)</span></dt>
<dd><p>Create a new dictionary.  The <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> object is the dictionary class.
See <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> and <a class="reference internal" href="stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a> for documentation about this class.</p>
<p>For other containers see the built-in <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and
<a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> classes, as well as the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
</dd></dl>

<dl class="function">
<dt id="dir">
<code class="descname">dir</code><span class="sig-paren">(</span><span class="optional">[</span><em>object</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Without arguments, return the list of names in the current local scope.  With an
argument, attempt to return a list of valid attributes for that object.</p>
<p>If the object has a method named <code class="xref py py-meth docutils literal notranslate"><span class="pre">__dir__()</span></code>, this method will be called and
must return the list of attributes. This allows objects that implement a custom
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> function to customize the way
<a class="reference internal" href="#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> reports their attributes.</p>
<p>If the object does not provide <code class="xref py py-meth docutils literal notranslate"><span class="pre">__dir__()</span></code>, the function tries its best to
gather information from the object’s <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute, if defined, and
from its type object.  The resulting list is not necessarily complete, and may
be inaccurate when the object has a custom <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>.</p>
<p>The default <a class="reference internal" href="#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> mechanism behaves differently with different types of
objects, as it attempts to produce the most relevant, rather than complete,
information:</p>
<ul class="simple">
<li>If the object is a module object, the list contains the names of the module’s
attributes.</li>
<li>If the object is a type or class object, the list contains the names of its
attributes, and recursively of the attributes of its bases.</li>
<li>Otherwise, the list contains the object’s attributes’ names, the names of its
class’s attributes, and recursively of the attributes of its class’s base
classes.</li>
</ul>
<p>The resulting list is sorted alphabetically.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">struct</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">()</span>   <span class="c1"># show the names in the module namespace</span>
<span class="go">[&#39;__builtins__&#39;, &#39;__doc__&#39;, &#39;__name__&#39;, &#39;struct&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">struct</span><span class="p">)</span>   <span class="c1"># show the names in the struct module</span>
<span class="go">[&#39;Struct&#39;, &#39;__builtins__&#39;, &#39;__doc__&#39;, &#39;__file__&#39;, &#39;__name__&#39;,</span>
<span class="go"> &#39;__package__&#39;, &#39;_clearcache&#39;, &#39;calcsize&#39;, &#39;error&#39;, &#39;pack&#39;, &#39;pack_into&#39;,</span>
<span class="go"> &#39;unpack&#39;, &#39;unpack_from&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Shape</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="go">        def __dir__(self):</span>
<span class="go">            return [&#39;area&#39;, &#39;perimeter&#39;, &#39;location&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Shape</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">[&#39;area&#39;, &#39;perimeter&#39;, &#39;location&#39;]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Because <a class="reference internal" href="#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> is supplied primarily as a convenience for use at an
interactive prompt, it tries to supply an interesting set of names more than it
tries to supply a rigorously or consistently defined set of names, and its
detailed behavior may change across releases.  For example, metaclass attributes
are not in the result list when the argument is a class.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="divmod">
<code class="descname">divmod</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#divmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Take two (non complex) numbers as arguments and return a pair of numbers
consisting of their quotient and remainder when using long division.  With mixed
operand types, the rules for binary arithmetic operators apply.  For plain and
long integers, the result is the same as <code class="docutils literal notranslate"><span class="pre">(a</span> <span class="pre">//</span> <span class="pre">b,</span> <span class="pre">a</span> <span class="pre">%</span> <span class="pre">b)</span></code>. For floating point
numbers the result is <code class="docutils literal notranslate"><span class="pre">(q,</span> <span class="pre">a</span> <span class="pre">%</span> <span class="pre">b)</span></code>, where <em>q</em> is usually <code class="docutils literal notranslate"><span class="pre">math.floor(a</span> <span class="pre">/</span> <span class="pre">b)</span></code>
but may be 1 less than that.  In any case <code class="docutils literal notranslate"><span class="pre">q</span> <span class="pre">*</span> <span class="pre">b</span> <span class="pre">+</span> <span class="pre">a</span> <span class="pre">%</span> <span class="pre">b</span></code> is very close to
<em>a</em>, if <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">%</span> <span class="pre">b</span></code> is non-zero it has the same sign as <em>b</em>, and <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">abs(a</span> <span class="pre">%</span> <span class="pre">b)</span>
<span class="pre">&lt;</span> <span class="pre">abs(b)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Using <a class="reference internal" href="#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a> with complex numbers is deprecated.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="enumerate">
<code class="descname">enumerate</code><span class="sig-paren">(</span><em>sequence</em>, <em>start=0</em><span class="sig-paren">)</span><a class="headerlink" href="#enumerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an enumerate object. <em>sequence</em> must be a sequence, an
<a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>, or some other object which supports iteration.  The
<code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method of the iterator returned by <a class="reference internal" href="#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> returns a
tuple containing a count (from <em>start</em> which defaults to 0) and the
values obtained from iterating over <em>sequence</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">seasons</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Spring&#39;</span><span class="p">,</span> <span class="s1">&#39;Summer&#39;</span><span class="p">,</span> <span class="s1">&#39;Fall&#39;</span><span class="p">,</span> <span class="s1">&#39;Winter&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">enumerate</span><span class="p">(</span><span class="n">seasons</span><span class="p">))</span>
<span class="go">[(0, &#39;Spring&#39;), (1, &#39;Summer&#39;), (2, &#39;Fall&#39;), (3, &#39;Winter&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="nb">enumerate</span><span class="p">(</span><span class="n">seasons</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="mi">1</span><span class="p">))</span>
<span class="go">[(1, &#39;Spring&#39;), (2, &#39;Summer&#39;), (3, &#39;Fall&#39;), (4, &#39;Winter&#39;)]</span>
</pre></div>
</div>
<p>Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">enumerate</span><span class="p">(</span><span class="n">sequence</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">start</span>
    <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">sequence</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">n</span><span class="p">,</span> <span class="n">elem</span>
        <span class="n">n</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <em>start</em> parameter was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="eval">
<code class="descname">eval</code><span class="sig-paren">(</span><em>expression</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#eval" title="Permalink to this definition">¶</a></dt>
<dd><p>The arguments are a Unicode or <em>Latin-1</em> encoded string and optional
globals and locals.  If provided, <em>globals</em> must be a dictionary.
If provided, <em>locals</em> can be any mapping object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>formerly <em>locals</em> was required to be a dictionary.</p>
</div>
<p>The <em>expression</em> argument is parsed and evaluated as a Python expression
(technically speaking, a condition list) using the <em>globals</em> and <em>locals</em>
dictionaries as global and local namespace.  If the <em>globals</em> dictionary is
present and lacks ‘__builtins__’, the current globals are copied into <em>globals</em>
before <em>expression</em> is parsed.  This means that <em>expression</em> normally has full
access to the standard <a class="reference internal" href="__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module and restricted environments are
propagated.  If the <em>locals</em> dictionary is omitted it defaults to the <em>globals</em>
dictionary.  If both dictionaries are omitted, the expression is executed in the
environment where <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> is called.  The return value is the result of
the evaluated expression. Syntax errors are reported as exceptions.  Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">eval</span><span class="p">(</span><span class="s1">&#39;x+1&#39;</span><span class="p">)</span>
<span class="go">2</span>
</pre></div>
</div>
<p>This function can also be used to execute arbitrary code objects (such as
those created by <a class="reference internal" href="#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>).  In this case pass a code object instead
of a string.  If the code object has been compiled with <code class="docutils literal notranslate"><span class="pre">'exec'</span></code> as the
<em>mode</em> argument, <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>’s return value will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Hints: dynamic execution of statements is supported by the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>
statement.  Execution of statements from a file is supported by the
<a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> function.  The <a class="reference internal" href="#globals" title="globals"><code class="xref py py-func docutils literal notranslate"><span class="pre">globals()</span></code></a> and <a class="reference internal" href="#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> functions
returns the current global and local dictionary, respectively, which may be
useful to pass around for use by <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> or <a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a>.</p>
<p>See <a class="reference internal" href="ast.html#ast.literal_eval" title="ast.literal_eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">ast.literal_eval()</span></code></a> for a function that can safely evaluate strings
with expressions containing only literals.</p>
</dd></dl>

<dl class="function">
<dt id="execfile">
<code class="descname">execfile</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#execfile" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement, but parses a file
instead of a string.  It is different from the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement in
that it does not use the module administration — it reads the file
unconditionally and does not create a new module. <a class="footnote-reference" href="#id3" id="id1">[1]</a></p>
<p>The arguments are a file name and two optional dictionaries.  The file is parsed
and evaluated as a sequence of Python statements (similarly to a module) using
the <em>globals</em> and <em>locals</em> dictionaries as global and local namespace. If
provided, <em>locals</em> can be any mapping object.  Remember that at module level,
globals and locals are the same dictionary. If two separate objects are
passed as <em>globals</em> and <em>locals</em>, the code will be executed as if it were
embedded in a class definition.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>formerly <em>locals</em> was required to be a dictionary.</p>
</div>
<p>If the <em>locals</em> dictionary is omitted it defaults to the <em>globals</em> dictionary.
If both dictionaries are omitted, the expression is executed in the environment
where <a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> is called.  The return value is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The default <em>locals</em> act as described for function <a class="reference internal" href="#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> below:
modifications to the default <em>locals</em> dictionary should not be attempted.  Pass
an explicit <em>locals</em> dictionary if you need to see effects of the code on
<em>locals</em> after function <a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> returns.  <a class="reference internal" href="#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> cannot be
used reliably to modify a function’s locals.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="file">
<code class="descname">file</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>buffering</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor function for the <a class="reference internal" href="#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> type, described further in section
<a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>.  The constructor’s arguments are the same as those
of the <a class="reference internal" href="#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function described below.</p>
<p>When opening a file, it’s preferable to use <a class="reference internal" href="#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> instead of  invoking
this constructor directly.  <a class="reference internal" href="#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> is more suited to type testing (for
example, writing <code class="docutils literal notranslate"><span class="pre">isinstance(f,</span> <span class="pre">file)</span></code>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="filter">
<code class="descname">filter</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a list from those elements of <em>iterable</em> for which <em>function</em> returns
true.  <em>iterable</em> may be either a sequence, a container which supports
iteration, or an iterator.  If <em>iterable</em> is a string or a tuple, the result
also has that type; otherwise it is always a list.  If <em>function</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
the identity function is assumed, that is, all elements of <em>iterable</em> that are
false are removed.</p>
<p>Note that <code class="docutils literal notranslate"><span class="pre">filter(function,</span> <span class="pre">iterable)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">[item</span> <span class="pre">for</span> <span class="pre">item</span> <span class="pre">in</span>
<span class="pre">iterable</span> <span class="pre">if</span> <span class="pre">function(item)]</span></code> if function is not <code class="docutils literal notranslate"><span class="pre">None</span></code> and <code class="docutils literal notranslate"><span class="pre">[item</span> <span class="pre">for</span> <span class="pre">item</span>
<span class="pre">in</span> <span class="pre">iterable</span> <span class="pre">if</span> <span class="pre">item]</span></code> if function is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>See <a class="reference internal" href="itertools.html#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilter()</span></code></a> and <a class="reference internal" href="itertools.html#itertools.ifilterfalse" title="itertools.ifilterfalse"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilterfalse()</span></code></a> for iterator
versions of this function, including a variation that filters for elements
where the <em>function</em> returns false.</p>
</dd></dl>

<dl class="class">
<dt id="float">
<em class="property">class </em><code class="descname">float</code><span class="sig-paren">(</span><span class="optional">[</span><em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#float" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a floating point number constructed from a number or string <em>x</em>.</p>
<p>If the argument is a string, it
must contain a possibly signed decimal or floating point number, possibly
embedded in whitespace. The argument may also be [+|-]nan or [+|-]inf.
Otherwise, the argument may be a plain or long integer
or a floating point number, and a floating point number with the same value
(within Python’s floating point precision) is returned.  If no argument is
given, returns <code class="docutils literal notranslate"><span class="pre">0.0</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last" id="index-2">When passing in a string, values for NaN and Infinity may be returned, depending
on the underlying C library.  Float accepts the strings nan, inf and -inf for
NaN and positive or negative infinity. The case and a leading + are ignored as
well as a leading - is ignored for NaN. Float always represents NaN and infinity
as nan, inf or -inf.</p>
</div>
<p>The float type is described in <a class="reference internal" href="stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, long, complex</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="format">
<code class="descname">format</code><span class="sig-paren">(</span><em>value</em><span class="optional">[</span>, <em>format_spec</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#format" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Convert a <em>value</em> to a “formatted” representation, as controlled by
<em>format_spec</em>.  The interpretation of <em>format_spec</em> will depend on the type
of the <em>value</em> argument, however there is a standard formatting syntax that
is used by most built-in types: <a class="reference internal" href="string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">format(value,</span> <span class="pre">format_spec)</span></code> merely calls
<code class="docutils literal notranslate"><span class="pre">value.__format__(format_spec)</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<span class="target" id="func-frozenset"></span><dl class="class">
<dt>
<em class="property">class </em><code class="descname">frozenset</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a new <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> object, optionally with elements taken from
<em>iterable</em>.  <code class="docutils literal notranslate"><span class="pre">frozenset</span></code> is a built-in class.  See <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> and
<a class="reference internal" href="stdtypes.html#types-set"><span class="std std-ref">Set Types — set, frozenset</span></a> for documentation about this class.</p>
<p>For other containers see the built-in <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, and <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> classes, as well as the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="getattr">
<code class="descname">getattr</code><span class="sig-paren">(</span><em>object</em>, <em>name</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#getattr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the named attribute of <em>object</em>.  <em>name</em> must be a string.
If the string is the name of one of the object’s attributes, the result is the
value of that attribute.  For example, <code class="docutils literal notranslate"><span class="pre">getattr(x,</span> <span class="pre">'foobar')</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x.foobar</span></code>.  If the named attribute does not exist, <em>default</em> is returned if
provided, otherwise <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="globals">
<code class="descname">globals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#globals" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary representing the current global symbol table. This is always
the dictionary of the current module (inside a function or method, this is the
module where it is defined, not the module from which it is called).</p>
</dd></dl>

<dl class="function">
<dt id="hasattr">
<code class="descname">hasattr</code><span class="sig-paren">(</span><em>object</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#hasattr" title="Permalink to this definition">¶</a></dt>
<dd><p>The arguments are an object and a string.  The result is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the string
is the name of one of the object’s attributes, <code class="docutils literal notranslate"><span class="pre">False</span></code> if not. (This is
implemented by calling <code class="docutils literal notranslate"><span class="pre">getattr(object,</span> <span class="pre">name)</span></code> and seeing whether it raises an
exception or not.)</p>
</dd></dl>

<dl class="function">
<dt id="hash">
<code class="descname">hash</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#hash" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hash value of the object (if it has one).  Hash values are integers.
They are used to quickly compare dictionary keys during a dictionary lookup.
Numeric values that compare equal have the same hash value (even if they are of
different types, as is the case for 1 and 1.0).</p>
</dd></dl>

<dl class="function">
<dt id="help">
<code class="descname">help</code><span class="sig-paren">(</span><span class="optional">[</span><em>object</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#help" title="Permalink to this definition">¶</a></dt>
<dd><p>Invoke the built-in help system.  (This function is intended for interactive
use.)  If no argument is given, the interactive help system starts on the
interpreter console.  If the argument is a string, then the string is looked up
as the name of a module, function, class, method, keyword, or documentation
topic, and a help page is printed on the console.  If the argument is any other
kind of object, a help page on the object is generated.</p>
<p>This function is added to the built-in namespace by the <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="hex">
<code class="descname">hex</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#hex" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an integer number (of any size) to a lowercase hexadecimal string
prefixed with “0x”, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span>
<span class="go">&#39;0xff&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="o">-</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;-0x2a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="mi">1</span><span class="n">L</span><span class="p">)</span>
<span class="go">&#39;0x1L&#39;</span>
</pre></div>
</div>
<p>If x is not a Python <a class="reference internal" href="#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or <a class="reference internal" href="#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a> object, it has to
define a __hex__() method that returns a string.</p>
<p>See also <a class="reference internal" href="#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> for converting a hexadecimal string to an
integer using a base of 16.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To obtain a hexadecimal string representation for a float, use the
<a class="reference internal" href="stdtypes.html#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> method.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly only returned an unsigned literal.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="id">
<code class="descname">id</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#id" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the “identity” of an object.  This is an integer (or long integer) which
is guaranteed to be unique and constant for this object during its lifetime.
Two objects with non-overlapping lifetimes may have the same <a class="reference internal" href="#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a>
value.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> This is the address of the object in memory.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="input">
<code class="descname">input</code><span class="sig-paren">(</span><span class="optional">[</span><em>prompt</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#input" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">eval(raw_input(prompt))</span></code>.</p>
<p>This function does not catch user errors. If the input is not syntactically
valid, a <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> will be raised. Other exceptions may be raised if
there is an error during evaluation.</p>
<p>If the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module was loaded, then <a class="reference internal" href="#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> will use it to
provide elaborate line editing and history features.</p>
<p>Consider using the <a class="reference internal" href="#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> function for general input from users.</p>
</dd></dl>

<dl class="class">
<dt id="int">
<em class="property">class </em><code class="descname">int</code><span class="sig-paren">(</span><em>x=0</em><span class="sig-paren">)</span><a class="headerlink" href="#int" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descname">int</code><span class="sig-paren">(</span><em>x</em>, <em>base=10</em><span class="sig-paren">)</span></dt>
<dd><p>Return an integer object constructed from a number or string <em>x</em>, or return <code class="docutils literal notranslate"><span class="pre">0</span></code> if no
arguments are given.  If <em>x</em> is a number, it can be a plain integer, a long
integer, or a floating point number.  If <em>x</em> is floating point, the conversion
truncates towards zero.  If the argument is outside the integer range, the
function returns a long object instead.</p>
<p>If <em>x</em> is not a number or if <em>base</em> is given, then <em>x</em> must be a string or
Unicode object representing an <a class="reference internal" href="../reference/lexical_analysis.html#integers"><span class="std std-ref">integer literal</span></a> in radix
<em>base</em>.  Optionally, the literal can be
preceded by <code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code> (with no space in between) and surrounded by
whitespace.  A base-n literal consists of the digits 0 to n-1, with <code class="docutils literal notranslate"><span class="pre">a</span></code>
to <code class="docutils literal notranslate"><span class="pre">z</span></code> (or <code class="docutils literal notranslate"><span class="pre">A</span></code> to <code class="docutils literal notranslate"><span class="pre">Z</span></code>) having
values 10 to 35.  The default <em>base</em> is 10. The allowed values are 0 and 2–36.
Base-2, -8, and -16 literals can be optionally prefixed with <code class="docutils literal notranslate"><span class="pre">0b</span></code>/<code class="docutils literal notranslate"><span class="pre">0B</span></code>,
<code class="docutils literal notranslate"><span class="pre">0o</span></code>/<code class="docutils literal notranslate"><span class="pre">0O</span></code>/<code class="docutils literal notranslate"><span class="pre">0</span></code>, or <code class="docutils literal notranslate"><span class="pre">0x</span></code>/<code class="docutils literal notranslate"><span class="pre">0X</span></code>, as with integer literals in code.
Base 0 means to interpret the string exactly as an integer literal, so that
the actual base is 2, 8, 10, or 16.</p>
<p>The integer type is described in <a class="reference internal" href="stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, long, complex</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="isinstance">
<code class="descname">isinstance</code><span class="sig-paren">(</span><em>object</em>, <em>classinfo</em><span class="sig-paren">)</span><a class="headerlink" href="#isinstance" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the <em>object</em> argument is an instance of the <em>classinfo</em> argument,
or of a (direct, indirect or <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">virtual</span></a>) subclass
thereof.  Also return true if <em>classinfo</em>
is a type object (new-style class) and <em>object</em> is an object of that type or of
a (direct, indirect or <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">virtual</span></a>) subclass
thereof.  If <em>object</em> is not a class instance or
an object of the given type, the function always returns false.
If <em>classinfo</em> is a tuple of class or type objects (or recursively, other
such tuples), return true if <em>object</em> is an instance of any of the classes
or types.  If <em>classinfo</em> is not a class, type, or tuple of classes, types,
and such tuples, a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Support for a tuple of type information was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="issubclass">
<code class="descname">issubclass</code><span class="sig-paren">(</span><em>class</em>, <em>classinfo</em><span class="sig-paren">)</span><a class="headerlink" href="#issubclass" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>class</em> is a subclass (direct, indirect or <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">virtual</span></a>) of <em>classinfo</em>.  A
class is considered a subclass of itself. <em>classinfo</em> may be a tuple of class
objects, in which case every entry in <em>classinfo</em> will be checked. In any other
case, a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Support for a tuple of type information was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="iter">
<code class="descname">iter</code><span class="sig-paren">(</span><em>o</em><span class="optional">[</span>, <em>sentinel</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#iter" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> object.  The first argument is interpreted very differently
depending on the presence of the second argument. Without a second argument, <em>o</em>
must be a collection object which supports the iteration protocol (the
<a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method), or it must support the sequence protocol (the
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method with integer arguments starting at <code class="docutils literal notranslate"><span class="pre">0</span></code>).  If it
does not support either of those protocols, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised. If the
second argument, <em>sentinel</em>, is given, then <em>o</em> must be a callable object.  The
iterator created in this case will call <em>o</em> with no arguments for each call to
its <a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method; if the value returned is equal to <em>sentinel</em>,
<a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> will be raised, otherwise the value will be returned.</p>
<p>One useful application of the second form of <a class="reference internal" href="#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> is to read lines of
a file until a certain line is reached.  The following example reads a file
until the <a class="reference internal" href="io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method returns an empty string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;mydata.txt&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">readline</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">):</span>
        <span class="n">process_line</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="len">
<code class="descname">len</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#len" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the length (the number of items) of an object.  The argument may be a
sequence (such as a string, bytes, tuple, list, or range) or a collection
(such as a dictionary, set, or frozen set).</p>
</dd></dl>

<span class="target" id="func-list"></span><dl class="class">
<dt>
<em class="property">class </em><code class="descname">list</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a list whose items are the same and in the same order as <em>iterable</em>’s
items.  <em>iterable</em> may be either a sequence, a container that supports
iteration, or an iterator object.  If <em>iterable</em> is already a list, a copy is
made and returned, similar to <code class="docutils literal notranslate"><span class="pre">iterable[:]</span></code>.  For instance, <code class="docutils literal notranslate"><span class="pre">list('abc')</span></code>
returns <code class="docutils literal notranslate"><span class="pre">['a',</span> <span class="pre">'b',</span> <span class="pre">'c']</span></code> and <code class="docutils literal notranslate"><span class="pre">list(</span> <span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span> <span class="pre">)</span></code> returns <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code>.  If
no argument is given, returns a new empty list, <code class="docutils literal notranslate"><span class="pre">[]</span></code>.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> is a mutable sequence type, as documented in
<a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>. For other containers see the built in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>,
<a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
</dd></dl>

<dl class="function">
<dt id="locals">
<code class="descname">locals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#locals" title="Permalink to this definition">¶</a></dt>
<dd><p>Update and return a dictionary representing the current local symbol table.
Free variables are returned by <a class="reference internal" href="#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> when it is called in function
blocks, but not in class blocks.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The contents of this dictionary should not be modified; changes may not
affect the values of local and free variables used by the interpreter.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="long">
<em class="property">class </em><code class="descname">long</code><span class="sig-paren">(</span><em>x=0</em><span class="sig-paren">)</span><a class="headerlink" href="#long" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descname">long</code><span class="sig-paren">(</span><em>x</em>, <em>base=10</em><span class="sig-paren">)</span></dt>
<dd><p>Return a long integer object constructed from a string or number <em>x</em>.
If the argument is a string, it
must contain a possibly signed number of arbitrary size, possibly embedded in
whitespace. The <em>base</em> argument is interpreted in the same way as for
<a class="reference internal" href="#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, and may only be given when <em>x</em> is a string. Otherwise, the argument
may be a plain or long integer or a floating point number, and a long integer
with the same value is returned.    Conversion of floating point numbers to
integers truncates (towards zero).  If no arguments are given, returns <code class="docutils literal notranslate"><span class="pre">0L</span></code>.</p>
<p>The long type is described in <a class="reference internal" href="stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, long, complex</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="map">
<code class="descname">map</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#map" title="Permalink to this definition">¶</a></dt>
<dd><p>Apply <em>function</em> to every item of <em>iterable</em> and return a list of the results.
If additional <em>iterable</em> arguments are passed, <em>function</em> must take that many
arguments and is applied to the items from all iterables in parallel.  If one
iterable is shorter than another it is assumed to be extended with <code class="docutils literal notranslate"><span class="pre">None</span></code>
items.  If <em>function</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, the identity function is assumed; if there
are multiple arguments, <a class="reference internal" href="#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> returns a list consisting of tuples
containing the corresponding items from all iterables (a kind of transpose
operation).  The <em>iterable</em> arguments may be a sequence  or any iterable object;
the result is always a list.</p>
</dd></dl>

<dl class="function">
<dt id="max">
<code class="descname">max</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#max" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">max</code><span class="sig-paren">(</span><em>arg1</em>, <em>arg2</em>, <em>*args</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return the largest item in an iterable or the largest of two or more
arguments.</p>
<p>If one positional argument is provided, <em>iterable</em> must be a non-empty
iterable (such as a non-empty string, tuple or list).  The largest item
in the iterable is returned.  If two or more positional arguments are
provided, the largest of the positional arguments is returned.</p>
<p>The optional <em>key</em> argument specifies a one-argument ordering function like that
used for <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code>.  The <em>key</em> argument, if supplied, must be in keyword
form (for example, <code class="docutils literal notranslate"><span class="pre">max(a,b,c,key=func)</span></code>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added support for the optional <em>key</em> argument.</p>
</div>
</dd></dl>

<span class="target" id="func-memoryview"></span><dl class="function">
<dt>
<code class="descname">memoryview</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span></dt>
<dd><p>Return a “memory view” object created from the given argument.  See
<a class="reference internal" href="stdtypes.html#typememoryview"><span class="std std-ref">memoryview type</span></a> for more information.</p>
</dd></dl>

<dl class="function">
<dt id="min">
<code class="descname">min</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#min" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">min</code><span class="sig-paren">(</span><em>arg1</em>, <em>arg2</em>, <em>*args</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return the smallest item in an iterable or the smallest of two or more
arguments.</p>
<p>If one positional argument is provided, <em>iterable</em> must be a non-empty
iterable (such as a non-empty string, tuple or list).  The smallest item
in the iterable is returned.  If two or more positional arguments are
provided, the smallest of the positional arguments is returned.</p>
<p>The optional <em>key</em> argument specifies a one-argument ordering function like that
used for <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code>.  The <em>key</em> argument, if supplied, must be in keyword
form (for example, <code class="docutils literal notranslate"><span class="pre">min(a,b,c,key=func)</span></code>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added support for the optional <em>key</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="next">
<code class="descname">next</code><span class="sig-paren">(</span><em>iterator</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#next" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the next item from the <em>iterator</em> by calling its
<a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method.  If <em>default</em> is given, it is returned if the
iterator is exhausted, otherwise <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="object">
<em class="property">class </em><code class="descname">object</code><a class="headerlink" href="#object" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new featureless object.  <a class="reference internal" href="#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> is a base for all new style
classes.  It has the methods that are common to all instances of new style
classes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>This function does not accept any arguments. Formerly, it accepted arguments but
ignored them.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="oct">
<code class="descname">oct</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#oct" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an integer number (of any size) to an octal string.  The result is a
valid Python expression.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly only returned an unsigned literal.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="open">
<code class="descname">open</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>buffering</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a file, returning an object of the <a class="reference internal" href="#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> type described in
section <a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>.  If the file cannot be opened,
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.  When opening a file, it’s preferable to use
<a class="reference internal" href="#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> instead of invoking the <a class="reference internal" href="#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> constructor directly.</p>
<p>The first two arguments are the same as for <code class="docutils literal notranslate"><span class="pre">stdio</span></code>’s <code class="xref c c-func docutils literal notranslate"><span class="pre">fopen()</span></code>:
<em>name</em> is the file name to be opened, and <em>mode</em> is a string indicating how
the file is to be opened.</p>
<p>The most commonly-used values of <em>mode</em> are <code class="docutils literal notranslate"><span class="pre">'r'</span></code> for reading, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> for
writing (truncating the file if it already exists), and <code class="docutils literal notranslate"><span class="pre">'a'</span></code> for appending
(which on <em>some</em> Unix systems means that <em>all</em> writes append to the end of the
file regardless of the current seek position).  If <em>mode</em> is omitted, it
defaults to <code class="docutils literal notranslate"><span class="pre">'r'</span></code>.  The default is to use text mode, which may convert
<code class="docutils literal notranslate"><span class="pre">'\n'</span></code> characters to a platform-specific representation on writing and back
on reading.  Thus, when opening a binary file, you should append <code class="docutils literal notranslate"><span class="pre">'b'</span></code> to
the <em>mode</em> value to open the file in binary mode, which will improve
portability.  (Appending <code class="docutils literal notranslate"><span class="pre">'b'</span></code> is useful even on systems that don’t treat
binary and text files differently, where it serves as documentation.)  See below
for more possible values of <em>mode</em>.</p>
<p id="index-4">The optional <em>buffering</em> argument specifies the file’s desired buffer size: 0
means unbuffered, 1 means line buffered, any other positive value means use a
buffer of (approximately) that size (in bytes).  A negative <em>buffering</em> means
to use the system default, which is usually line buffered for tty devices and
fully buffered for other files.  If omitted, the system default is used. <a class="footnote-reference" href="#id4" id="id2">[2]</a></p>
<p>Modes <code class="docutils literal notranslate"><span class="pre">'r+'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w+'</span></code> and <code class="docutils literal notranslate"><span class="pre">'a+'</span></code> open the file for updating (reading and writing);
note that <code class="docutils literal notranslate"><span class="pre">'w+'</span></code> truncates the file.  Append <code class="docutils literal notranslate"><span class="pre">'b'</span></code> to the mode to open the file in
binary mode, on systems that differentiate between binary and text files; on
systems that don’t have this distinction, adding the <code class="docutils literal notranslate"><span class="pre">'b'</span></code> has no effect.</p>
<p id="index-5">In addition to the standard <code class="xref c c-func docutils literal notranslate"><span class="pre">fopen()</span></code> values <em>mode</em> may be <code class="docutils literal notranslate"><span class="pre">'U'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'rU'</span></code>.  Python is usually built with <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> support;
supplying <code class="docutils literal notranslate"><span class="pre">'U'</span></code> opens the file as a text file, but lines may be terminated
by any of the following: the Unix end-of-line convention <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>,  the
Macintosh convention <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, or the Windows convention <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>. All of
these external representations are seen as <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> by the Python program.
If Python is built without universal newlines support a <em>mode</em> with <code class="docutils literal notranslate"><span class="pre">'U'</span></code>
is the same as normal text mode.  Note that file objects so opened also have
an attribute called <code class="xref py py-attr docutils literal notranslate"><span class="pre">newlines</span></code> which has a value of <code class="docutils literal notranslate"><span class="pre">None</span></code> (if no
newlines have yet been seen), <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>, or a tuple
containing all the newline types seen.</p>
<p>Python enforces that the mode, after stripping <code class="docutils literal notranslate"><span class="pre">'U'</span></code>, begins with <code class="docutils literal notranslate"><span class="pre">'r'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'w'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a'</span></code>.</p>
<p>Python provides many file handling modules including
<a class="reference internal" href="fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a>, <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>, <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>, <a class="reference internal" href="tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a>, and
<a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Restriction on first letter of mode string introduced.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ord">
<code class="descname">ord</code><span class="sig-paren">(</span><em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#ord" title="Permalink to this definition">¶</a></dt>
<dd><p>Given a string of length one, return an integer representing the Unicode code
point of the character when the argument is a unicode object, or the value of
the byte when the argument is an 8-bit string. For example, <code class="docutils literal notranslate"><span class="pre">ord('a')</span></code> returns
the integer <code class="docutils literal notranslate"><span class="pre">97</span></code>, <code class="docutils literal notranslate"><span class="pre">ord(u'\u2020')</span></code> returns <code class="docutils literal notranslate"><span class="pre">8224</span></code>.  This is the inverse of
<a class="reference internal" href="#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> for 8-bit strings and of <a class="reference internal" href="#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a> for unicode objects.  If a
unicode argument is given and Python was built with UCS2 Unicode, then the
character’s code point must be in the range [0..65535] inclusive; otherwise the
string length is two, and a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised.</p>
</dd></dl>

<dl class="function">
<dt id="pow">
<code class="descname">pow</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="optional">[</span>, <em>z</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>x</em> to the power <em>y</em>; if <em>z</em> is present, return <em>x</em> to the power <em>y</em>,
modulo <em>z</em> (computed more efficiently than <code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y)</span> <span class="pre">%</span> <span class="pre">z</span></code>). The two-argument
form <code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y)</span></code> is equivalent to using the power operator: <code class="docutils literal notranslate"><span class="pre">x**y</span></code>.</p>
<p>The arguments must have numeric types.  With mixed operand types, the coercion
rules for binary arithmetic operators apply.  For int and long int operands, the
result has the same type as the operands (after coercion) unless the second
argument is negative; in that case, all arguments are converted to float and a
float result is delivered.  For example, <code class="docutils literal notranslate"><span class="pre">10**2</span></code> returns <code class="docutils literal notranslate"><span class="pre">100</span></code>, but
<code class="docutils literal notranslate"><span class="pre">10**-2</span></code> returns <code class="docutils literal notranslate"><span class="pre">0.01</span></code>.  (This last feature was added in Python 2.2.  In
Python 2.1 and before, if both arguments were of integer types and the second
argument was negative, an exception was raised.) If the second argument is
negative, the third argument must be omitted. If <em>z</em> is present, <em>x</em> and <em>y</em>
must be of integer types, and <em>y</em> must be non-negative.  (This restriction was
added in Python 2.2.  In Python 2.1 and before, floating 3-argument <code class="docutils literal notranslate"><span class="pre">pow()</span></code>
returned platform-dependent results depending on floating-point rounding
accidents.)</p>
</dd></dl>

<dl class="function">
<dt id="print">
<code class="descname">print</code><span class="sig-paren">(</span><em>*objects</em>, <em>sep=' '</em>, <em>end='\n'</em>, <em>file=sys.stdout</em><span class="sig-paren">)</span><a class="headerlink" href="#print" title="Permalink to this definition">¶</a></dt>
<dd><p>Print <em>objects</em> to the stream <em>file</em>, separated by <em>sep</em> and followed by
<em>end</em>.  <em>sep</em>, <em>end</em> and <em>file</em>, if present, must be given as keyword
arguments.</p>
<p>All non-keyword arguments are converted to strings like <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> does and
written to the stream, separated by <em>sep</em> and followed by <em>end</em>.  Both <em>sep</em>
and <em>end</em> must be strings; they can also be <code class="docutils literal notranslate"><span class="pre">None</span></code>, which means to use the
default values.  If no <em>objects</em> are given, <a class="reference internal" href="#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> will just write
<em>end</em>.</p>
<p>The <em>file</em> argument must be an object with a <code class="docutils literal notranslate"><span class="pre">write(string)</span></code> method; if it
is not present or <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> will be used.  Output buffering
is determined by <em>file</em>.  Use <code class="docutils literal notranslate"><span class="pre">file.flush()</span></code> to ensure, for instance,
immediate appearance on a screen.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>This function is not normally available as a built-in since the name
<code class="docutils literal notranslate"><span class="pre">print</span></code> is recognized as the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.  To disable the
statement and use the <a class="reference internal" href="#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function, use this future statement at
the top of your module:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">print_function</span>
</pre></div>
</div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="property">
<em class="property">class </em><code class="descname">property</code><span class="sig-paren">(</span><span class="optional">[</span><em>fget</em><span class="optional">[</span>, <em>fset</em><span class="optional">[</span>, <em>fdel</em><span class="optional">[</span>, <em>doc</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#property" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a property attribute for <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es (classes that
derive from <a class="reference internal" href="#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>).</p>
<p><em>fget</em> is a function for getting an attribute value.  <em>fset</em> is a function
for setting an attribute value. <em>fdel</em> is a function for deleting an attribute
value.  And <em>doc</em> creates a docstring for the attribute.</p>
<p>A typical use is to define a managed attribute <code class="docutils literal notranslate"><span class="pre">x</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">getx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>

    <span class="k">def</span> <span class="nf">setx</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span>

    <span class="k">def</span> <span class="nf">delx</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>

    <span class="n">x</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">getx</span><span class="p">,</span> <span class="n">setx</span><span class="p">,</span> <span class="n">delx</span><span class="p">,</span> <span class="s2">&quot;I&#39;m the &#39;x&#39; property.&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <em>c</em> is an instance of <em>C</em>, <code class="docutils literal notranslate"><span class="pre">c.x</span></code> will invoke the getter,
<code class="docutils literal notranslate"><span class="pre">c.x</span> <span class="pre">=</span> <span class="pre">value</span></code> will invoke the setter and <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">c.x</span></code> the deleter.</p>
<p>If given, <em>doc</em> will be the docstring of the property attribute. Otherwise, the
property will copy <em>fget</em>’s docstring (if it exists).  This makes it possible to
create read-only properties easily using <a class="reference internal" href="#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> as a <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Parrot</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_voltage</span> <span class="o">=</span> <span class="mi">100000</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">voltage</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Get the current voltage.&quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_voltage</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">&#64;property</span></code> decorator turns the <code class="xref py py-meth docutils literal notranslate"><span class="pre">voltage()</span></code> method into a “getter”
for a read-only attribute with the same name, and it sets the docstring for
<em>voltage</em> to “Get the current voltage.”</p>
<p>A property object has <code class="xref py py-attr docutils literal notranslate"><span class="pre">getter</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">setter</span></code>,
and <code class="xref py py-attr docutils literal notranslate"><span class="pre">deleter</span></code> methods usable as decorators that create a
copy of the property with the corresponding accessor function set to the
decorated function.  This is best explained with an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="kc">None</span>

    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;I&#39;m the &#39;x&#39; property.&quot;&quot;&quot;</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>

    <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span>

    <span class="nd">@x</span><span class="o">.</span><span class="n">deleter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
</pre></div>
</div>
<p>This code is exactly equivalent to the first example.  Be sure to give the
additional functions the same name as the original property (<code class="docutils literal notranslate"><span class="pre">x</span></code> in this
case.)</p>
<p>The returned property object also has the attributes <code class="docutils literal notranslate"><span class="pre">fget</span></code>, <code class="docutils literal notranslate"><span class="pre">fset</span></code>, and
<code class="docutils literal notranslate"><span class="pre">fdel</span></code> corresponding to the constructor arguments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Use <em>fget</em>’s docstring if no <em>doc</em> given.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <code class="docutils literal notranslate"><span class="pre">getter</span></code>, <code class="docutils literal notranslate"><span class="pre">setter</span></code>, and <code class="docutils literal notranslate"><span class="pre">deleter</span></code> attributes were added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="range">
<code class="descname">range</code><span class="sig-paren">(</span><em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#range" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">range</code><span class="sig-paren">(</span><em>start</em>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>This is a versatile function to create lists containing arithmetic progressions.
It is most often used in <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loops.  The arguments must be plain
integers.  If the <em>step</em> argument is omitted, it defaults to <code class="docutils literal notranslate"><span class="pre">1</span></code>.  If the
<em>start</em> argument is omitted, it defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code>.  The full form returns a list
of plain integers <code class="docutils literal notranslate"><span class="pre">[start,</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">step,</span> <span class="pre">start</span> <span class="pre">+</span> <span class="pre">2</span> <span class="pre">*</span> <span class="pre">step,</span> <span class="pre">...]</span></code>.  If <em>step</em>
is positive, the last element is the largest <code class="docutils literal notranslate"><span class="pre">start</span> <span class="pre">+</span> <span class="pre">i</span> <span class="pre">*</span> <span class="pre">step</span></code> less than
<em>stop</em>; if <em>step</em> is negative, the last element is the smallest <code class="docutils literal notranslate"><span class="pre">start</span> <span class="pre">+</span> <span class="pre">i</span> <span class="pre">*</span>
<span class="pre">step</span></code> greater than <em>stop</em>.  <em>step</em> must not be zero (or else <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
is raised).  Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">)</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="go">[0, 5, 10, 15, 20, 25]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">[0, 3, 6, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="go">[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">[]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="raw_input">
<code class="descname">raw_input</code><span class="sig-paren">(</span><span class="optional">[</span><em>prompt</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#raw_input" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>prompt</em> argument is present, it is written to standard output without a
trailing newline.  The function then reads a line from input, converts it to a
string (stripping a trailing newline), and returns that. When EOF is read,
<a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> is raised. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s1">&#39;--&gt; &#39;</span><span class="p">)</span>
<span class="go">--&gt; Monty Python&#39;s Flying Circus</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>
<span class="go">&quot;Monty Python&#39;s Flying Circus&quot;</span>
</pre></div>
</div>
<p>If the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module was loaded, then <a class="reference internal" href="#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> will use it to
provide elaborate line editing and history features.</p>
</dd></dl>

<dl class="function">
<dt id="reduce">
<code class="descname">reduce</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em><span class="optional">[</span>, <em>initializer</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#reduce" title="Permalink to this definition">¶</a></dt>
<dd><p>Apply <em>function</em> of two arguments cumulatively to the items of <em>iterable</em>, from
left to right, so as to reduce the iterable to a single value.  For example,
<code class="docutils literal notranslate"><span class="pre">reduce(lambda</span> <span class="pre">x,</span> <span class="pre">y:</span> <span class="pre">x+y,</span> <span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">3,</span> <span class="pre">4,</span> <span class="pre">5])</span></code> calculates <code class="docutils literal notranslate"><span class="pre">((((1+2)+3)+4)+5)</span></code>.
The left argument, <em>x</em>, is the accumulated value and the right argument, <em>y</em>, is
the update value from the <em>iterable</em>.  If the optional <em>initializer</em> is present,
it is placed before the items of the iterable in the calculation, and serves as
a default when the iterable is empty.  If <em>initializer</em> is not given and
<em>iterable</em> contains only one item, the first item is returned.
Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">reduce</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="n">iterable</span><span class="p">,</span> <span class="n">initializer</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">initializer</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">initializer</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">&#39;reduce() of empty sequence with no initial value&#39;</span><span class="p">)</span>
    <span class="n">accum_value</span> <span class="o">=</span> <span class="n">initializer</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="n">accum_value</span> <span class="o">=</span> <span class="n">function</span><span class="p">(</span><span class="n">accum_value</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">accum_value</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="reload">
<code class="descname">reload</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#reload" title="Permalink to this definition">¶</a></dt>
<dd><p>Reload a previously imported <em>module</em>.  The argument must be a module object, so
it must have been successfully imported before.  This is useful if you have
edited the module source file using an external editor and want to try out the
new version without leaving the Python interpreter.  The return value is the
module object (the same as the <em>module</em> argument).</p>
<p>When <code class="docutils literal notranslate"><span class="pre">reload(module)</span></code> is executed:</p>
<ul class="simple">
<li>Python modules’ code is recompiled and the module-level code reexecuted,
defining a new set of objects which are bound to names in the module’s
dictionary.  The <code class="docutils literal notranslate"><span class="pre">init</span></code> function of extension modules is not called a second
time.</li>
<li>As with all other objects in Python the old objects are only reclaimed after
their reference counts drop to zero.</li>
<li>The names in the module namespace are updated to point to any new or changed
objects.</li>
<li>Other references to the old objects (such as names external to the module) are
not rebound to refer to the new objects and must be updated in each namespace
where they occur if that is desired.</li>
</ul>
<p>There are a number of other caveats:</p>
<p>When a module is reloaded, its dictionary (containing the module’s global
variables) is retained.  Redefinitions of names will override the old
definitions, so this is generally not a problem.  If the new version of a module
does not define a name that was defined by the old version, the old definition
remains.  This feature can be used to the module’s advantage if it maintains a
global table or cache of objects — with a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement it can test
for the table’s presence and skip its initialization if desired:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">cache</span>
<span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
    <span class="n">cache</span> <span class="o">=</span> <span class="p">{}</span>
</pre></div>
</div>
<p>It is generally not very useful to reload built-in or dynamically loaded
modules.  Reloading <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code> and other
key modules is not recommended.  In many cases extension modules are not
designed to be initialized more than once, and may fail in arbitrary ways
when reloaded.</p>
<p>If a module imports objects from another module using <a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> …
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> …, calling <a class="reference internal" href="#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> for the other module does not
redefine the objects imported from it — one way around this is to re-execute
the <a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> statement, another is to use <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> and qualified
names (<em>module</em>.*name*) instead.</p>
<p>If a module instantiates instances of a class, reloading the module that defines
the class does not affect the method definitions of the instances — they
continue to use the old class definition.  The same is true for derived classes.</p>
</dd></dl>

<span class="target" id="func-repr"></span><dl class="function">
<dt id="repr">
<code class="descname">repr</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#repr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing a printable representation of an object.  This is
the same value yielded by conversions (reverse quotes).  It is sometimes
useful to be able to access this operation as an ordinary function.  For many
types, this function makes an attempt to return a string that would yield an
object with the same value when passed to <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, otherwise the
representation is a string enclosed in angle brackets that contains the name
of the type of the object together with additional information often
including the name and address of the object.  A class can control what this
function returns for its instances by defining a <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> method.</p>
</dd></dl>

<dl class="function">
<dt id="reversed">
<code class="descname">reversed</code><span class="sig-paren">(</span><em>seq</em><span class="sig-paren">)</span><a class="headerlink" href="#reversed" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a reverse <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.  <em>seq</em> must be an object which has
a <a class="reference internal" href="../reference/datamodel.html#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> method or supports the sequence protocol (the
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> method and the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method with integer
arguments starting at <code class="docutils literal notranslate"><span class="pre">0</span></code>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the possibility to write a custom <a class="reference internal" href="../reference/datamodel.html#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> method.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="round">
<code class="descname">round</code><span class="sig-paren">(</span><em>number</em><span class="optional">[</span>, <em>ndigits</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#round" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the floating point value <em>number</em> rounded to <em>ndigits</em> digits after
the decimal point.  If <em>ndigits</em> is omitted, it defaults to zero. The result
is a floating point number.  Values are rounded to the closest multiple of
10 to the power minus <em>ndigits</em>; if two multiples are equally close,
rounding is done away from 0 (so, for example, <code class="docutils literal notranslate"><span class="pre">round(0.5)</span></code> is <code class="docutils literal notranslate"><span class="pre">1.0</span></code> and
<code class="docutils literal notranslate"><span class="pre">round(-0.5)</span></code> is <code class="docutils literal notranslate"><span class="pre">-1.0</span></code>).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The behavior of <a class="reference internal" href="#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> for floats can be surprising: for example,
<code class="docutils literal notranslate"><span class="pre">round(2.675,</span> <span class="pre">2)</span></code> gives <code class="docutils literal notranslate"><span class="pre">2.67</span></code> instead of the expected <code class="docutils literal notranslate"><span class="pre">2.68</span></code>.
This is not a bug: it’s a result of the fact that most decimal fractions
can’t be represented exactly as a float.  See <a class="reference internal" href="../tutorial/floatingpoint.html#tut-fp-issues"><span class="std std-ref">Floating Point Arithmetic:  Issues and Limitations</span></a> for
more information.</p>
</div>
</dd></dl>

<span class="target" id="func-set"></span><dl class="class">
<dt>
<em class="property">class </em><code class="descname">set</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a new <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> object, optionally with elements taken from
<em>iterable</em>.  <code class="docutils literal notranslate"><span class="pre">set</span></code> is a built-in class.  See <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and
<a class="reference internal" href="stdtypes.html#types-set"><span class="std std-ref">Set Types — set, frozenset</span></a> for documentation about this class.</p>
<p>For other containers see the built-in <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, and <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> classes, as well as the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="setattr">
<code class="descname">setattr</code><span class="sig-paren">(</span><em>object</em>, <em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#setattr" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the counterpart of <a class="reference internal" href="#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>.  The arguments are an object, a
string and an arbitrary value.  The string may name an existing attribute or a
new attribute.  The function assigns the value to the attribute, provided the
object allows it.  For example, <code class="docutils literal notranslate"><span class="pre">setattr(x,</span> <span class="pre">'foobar',</span> <span class="pre">123)</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x.foobar</span> <span class="pre">=</span> <span class="pre">123</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="slice">
<em class="property">class </em><code class="descname">slice</code><span class="sig-paren">(</span><em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#slice" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descname">slice</code><span class="sig-paren">(</span><em>start</em>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p id="index-6">Return a <a class="reference internal" href="../glossary.html#term-slice"><span class="xref std std-term">slice</span></a> object representing the set of indices specified by
<code class="docutils literal notranslate"><span class="pre">range(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code>.  The <em>start</em> and <em>step</em> arguments default to
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  Slice objects have read-only data attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> which merely return the argument
values (or their default).  They have no other explicit functionality;
however they are used by Numerical Python and other third party extensions.
Slice objects are also generated when extended indexing syntax is used.  For
example: <code class="docutils literal notranslate"><span class="pre">a[start:stop:step]</span></code> or <code class="docutils literal notranslate"><span class="pre">a[start:stop,</span> <span class="pre">i]</span></code>.  See
<a class="reference internal" href="itertools.html#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.islice()</span></code></a> for an alternate version that returns an iterator.</p>
</dd></dl>

<dl class="function">
<dt id="sorted">
<code class="descname">sorted</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>cmp</em><span class="optional">[</span>, <em>key</em><span class="optional">[</span>, <em>reverse</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sorted" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new sorted list from the items in <em>iterable</em>.</p>
<p>The optional arguments <em>cmp</em>, <em>key</em>, and <em>reverse</em> have the same meaning as
those for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method (described in section
<a class="reference internal" href="stdtypes.html#typesseq-mutable"><span class="std std-ref">Mutable Sequence Types</span></a>).</p>
<p><em>cmp</em> specifies a custom comparison function of two arguments (iterable
elements) which should return a negative, zero or positive number depending on
whether the first argument is considered smaller than, equal to, or larger than
the second argument: <code class="docutils literal notranslate"><span class="pre">cmp=lambda</span> <span class="pre">x,y:</span> <span class="pre">cmp(x.lower(),</span> <span class="pre">y.lower())</span></code>.  The default
value is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p><em>key</em> specifies a function of one argument that is used to extract a comparison
key from each list element: <code class="docutils literal notranslate"><span class="pre">key=str.lower</span></code>.  The default value is <code class="docutils literal notranslate"><span class="pre">None</span></code>
(compare the elements directly).</p>
<p><em>reverse</em> is a boolean value.  If set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, then the list elements are
sorted as if each comparison were reversed.</p>
<p>In general, the <em>key</em> and <em>reverse</em> conversion processes are much faster
than specifying an equivalent <em>cmp</em> function.  This is because <em>cmp</em> is
called multiple times for each list element while <em>key</em> and <em>reverse</em> touch
each element only once.  Use <a class="reference internal" href="functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.cmp_to_key()</span></code></a> to convert an
old-style <em>cmp</em> function to a <em>key</em> function.</p>
<p>The built-in <a class="reference internal" href="#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function is guaranteed to be stable. A sort is
stable if it guarantees not to change the relative order of elements that
compare equal — this is helpful for sorting in multiple passes (for
example, sort by department, then by salary grade).</p>
<p>For sorting examples and a brief sorting tutorial, see <a class="reference internal" href="../howto/sorting.html#sortinghowto"><span class="std std-ref">Sorting HOW TO</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="staticmethod">
<code class="descname">staticmethod</code><span class="sig-paren">(</span><em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#staticmethod" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a static method for <em>function</em>.</p>
<p>A static method does not receive an implicit first argument. To declare a static
method, use this idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="nd">@staticmethod</span>
    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">,</span> <span class="o">...</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">&#64;staticmethod</span></code> form is a function <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> – see the
description of function definitions in <a class="reference internal" href="../reference/compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for details.</p>
<p>It can be called either on the class (such as <code class="docutils literal notranslate"><span class="pre">C.f()</span></code>) or on an instance (such
as <code class="docutils literal notranslate"><span class="pre">C().f()</span></code>).  The instance is ignored except for its class.</p>
<p>Static methods in Python are similar to those found in Java or C++. Also see
<a class="reference internal" href="#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> for a variant that is useful for creating alternate
class constructors.</p>
<p>For more information on static methods, consult the documentation on the
standard type hierarchy in <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Function decorator syntax added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="str">
<em class="property">class </em><code class="descname">str</code><span class="sig-paren">(</span><em>object=''</em><span class="sig-paren">)</span><a class="headerlink" href="#str" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing a nicely printable representation of an object.  For
strings, this returns the string itself.  The difference with <code class="docutils literal notranslate"><span class="pre">repr(object)</span></code>
is that <code class="docutils literal notranslate"><span class="pre">str(object)</span></code> does not always attempt to return a string that is
acceptable to <a class="reference internal" href="#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>; its goal is to return a printable string.  If no
argument is given, returns the empty string, <code class="docutils literal notranslate"><span class="pre">''</span></code>.</p>
<p>For more information on strings see <a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a> which describes sequence
functionality (strings are sequences), and also the string-specific methods
described in the <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a> section. To output formatted strings
use template strings or the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator described in the
<a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section. In addition see the <a class="reference internal" href="strings.html#stringservices"><span class="std std-ref">String Services</span></a>
section. See also <a class="reference internal" href="#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sum">
<code class="descname">sum</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>start</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sum" title="Permalink to this definition">¶</a></dt>
<dd><p>Sums <em>start</em> and the items of an <em>iterable</em> from left to right and returns the
total.  <em>start</em> defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code>. The <em>iterable</em>’s items are normally numbers,
and the start value is not allowed to be a string.</p>
<p>For some use cases, there are good alternatives to <a class="reference internal" href="#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a>.
The preferred, fast way to concatenate a sequence of strings is by calling
<code class="docutils literal notranslate"><span class="pre">''.join(sequence)</span></code>.  To add floating point values with extended precision,
see <a class="reference internal" href="math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fsum()</span></code></a>.  To concatenate a series of iterables, consider using
<a class="reference internal" href="itertools.html#itertools.chain" title="itertools.chain"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.chain()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="super">
<code class="descname">super</code><span class="sig-paren">(</span><em>type</em><span class="optional">[</span>, <em>object-or-type</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#super" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a proxy object that delegates method calls to a parent or sibling
class of <em>type</em>.  This is useful for accessing inherited methods that have
been overridden in a class. The search order is same as that used by
<a class="reference internal" href="#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> except that the <em>type</em> itself is skipped.</p>
<p>The <a class="reference internal" href="stdtypes.html#class.__mro__" title="class.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a> attribute of the <em>type</em> lists the method
resolution search order used by both <a class="reference internal" href="#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> and <a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>.  The
attribute is dynamic and can change whenever the inheritance hierarchy is
updated.</p>
<p>If the second argument is omitted, the super object returned is unbound.  If
the second argument is an object, <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">type)</span></code> must be true.  If
the second argument is a type, <code class="docutils literal notranslate"><span class="pre">issubclass(type2,</span> <span class="pre">type)</span></code> must be true (this
is useful for classmethods).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> only works for <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es.</p>
</div>
<p>There are two typical use cases for <em>super</em>.  In a class hierarchy with
single inheritance, <em>super</em> can be used to refer to parent classes without
naming them explicitly, thus making the code more maintainable.  This use
closely parallels the use of <em>super</em> in other programming languages.</p>
<p>The second use case is to support cooperative multiple inheritance in a
dynamic execution environment.  This use case is unique to Python and is
not found in statically compiled languages or languages that only support
single inheritance.  This makes it possible to implement “diamond diagrams”
where multiple base classes implement the same method.  Good design dictates
that this method have the same calling signature in every case (because the
order of calls is determined at runtime, because that order adapts
to changes in the class hierarchy, and because that order can include
sibling classes that are unknown prior to runtime).</p>
<p>For both use cases, a typical superclass call looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">C</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> is implemented as part of the binding process for
explicit dotted attribute lookups such as <code class="docutils literal notranslate"><span class="pre">super().__getitem__(name)</span></code>.
It does so by implementing its own <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method for searching
classes in a predictable order that supports cooperative multiple inheritance.
Accordingly, <a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> is undefined for implicit lookups using statements or
operators such as <code class="docutils literal notranslate"><span class="pre">super()[name]</span></code>.</p>
<p>Also note that <a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> is not limited to use inside methods.  The two
argument form specifies the arguments exactly and makes the appropriate
references.</p>
<p>For practical suggestions on how to design cooperative classes using
<a class="reference internal" href="#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>, see <a class="reference external" href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/">guide to using super()</a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="tuple">
<code class="descname">tuple</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple whose items are the same and in the same order as <em>iterable</em>’s
items.  <em>iterable</em> may be a sequence, a container that supports iteration, or an
iterator object. If <em>iterable</em> is already a tuple, it is returned unchanged.
For instance, <code class="docutils literal notranslate"><span class="pre">tuple('abc')</span></code> returns <code class="docutils literal notranslate"><span class="pre">('a',</span> <span class="pre">'b',</span> <span class="pre">'c')</span></code> and <code class="docutils literal notranslate"><span class="pre">tuple([1,</span> <span class="pre">2,</span>
<span class="pre">3])</span></code> returns <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3)</span></code>.  If no argument is given, returns a new empty
tuple, <code class="docutils literal notranslate"><span class="pre">()</span></code>.</p>
<p><a class="reference internal" href="#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> is an immutable sequence type, as documented in
<a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>. For other containers see the built in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, and <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
</dd></dl>

<dl class="class">
<dt id="type">
<em class="property">class </em><code class="descname">type</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#type" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descname">type</code><span class="sig-paren">(</span><em>name</em>, <em>bases</em>, <em>dict</em><span class="sig-paren">)</span></dt>
<dd><p id="index-7">With one argument, return the type of an <em>object</em>.  The return value is a
type object.  The <a class="reference internal" href="#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> built-in function is recommended for
testing the type of an object.</p>
<p>With three arguments, return a new type object.  This is essentially a
dynamic form of the <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statement. The <em>name</em> string is the
class name and becomes the <a class="reference internal" href="stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute; the <em>bases</em> tuple
itemizes the base classes and becomes the <a class="reference internal" href="stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> attribute;
and the <em>dict</em> dictionary is the namespace containing definitions for class
body and becomes the <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>  attribute.  For example, the
following two statements create identical <a class="reference internal" href="#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">X</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="s1">&#39;X&#39;</span><span class="p">,</span> <span class="p">(</span><span class="nb">object</span><span class="p">,),</span> <span class="nb">dict</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unichr">
<code class="descname">unichr</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#unichr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Unicode string of one character whose Unicode code is the integer
<em>i</em>.  For example, <code class="docutils literal notranslate"><span class="pre">unichr(97)</span></code> returns the string <code class="docutils literal notranslate"><span class="pre">u'a'</span></code>.  This is the
inverse of <a class="reference internal" href="#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> for Unicode strings.  The valid range for the argument
depends how Python was configured – it may be either UCS2 [0..0xFFFF] or UCS4
[0..0x10FFFF]. <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised otherwise. For ASCII and 8-bit
strings see <a class="reference internal" href="#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unicode">
<code class="descname">unicode</code><span class="sig-paren">(</span><em>object=''</em><span class="sig-paren">)</span><a class="headerlink" href="#unicode" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">unicode</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return the Unicode string version of <em>object</em> using one of the following modes:</p>
<p>If <em>encoding</em> and/or <em>errors</em> are given, <code class="docutils literal notranslate"><span class="pre">unicode()</span></code> will decode the object
which can either be an 8-bit string or a character buffer using the codec for
<em>encoding</em>. The <em>encoding</em> parameter is a string giving the name of an encoding;
if the encoding is not known, <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> is raised. Error handling is
done according to <em>errors</em>; this specifies the treatment of characters which are
invalid in the input encoding.  If <em>errors</em> is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> (the default), a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised on errors, while a value of <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> causes
errors to be silently ignored, and a value of <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> causes the official
Unicode replacement character, <code class="docutils literal notranslate"><span class="pre">U+FFFD</span></code>, to be used to replace input
characters which cannot be decoded.  See also the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module.</p>
<p>If no optional parameters are given, <code class="docutils literal notranslate"><span class="pre">unicode()</span></code> will mimic the behaviour of
<code class="docutils literal notranslate"><span class="pre">str()</span></code> except that it returns Unicode strings instead of 8-bit strings. More
precisely, if <em>object</em> is a Unicode string or subclass it will return that
Unicode string without any additional decoding applied.</p>
<p>For objects which provide a <a class="reference internal" href="../reference/datamodel.html#object.__unicode__" title="object.__unicode__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__unicode__()</span></code></a> method, it will call this method
without arguments to create a Unicode string. For all other objects, the 8-bit
string version or representation is requested and then converted to a Unicode
string using the codec for the default encoding in <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> mode.</p>
<p>For more information on Unicode strings see <a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a> which describes
sequence functionality (Unicode strings are sequences), and also the
string-specific methods described in the <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a> section. To
output formatted strings use template strings or the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator described
in the <a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section. In addition see the
<a class="reference internal" href="strings.html#stringservices"><span class="std std-ref">String Services</span></a> section. See also <a class="reference internal" href="#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Support for <a class="reference internal" href="../reference/datamodel.html#object.__unicode__" title="object.__unicode__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__unicode__()</span></code></a> added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="vars">
<code class="descname">vars</code><span class="sig-paren">(</span><span class="optional">[</span><em>object</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#vars" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute for a module, class, instance,
or any other object with a <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute.</p>
<p>Objects such as modules and instances have an updateable <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>
attribute; however, other objects may have write restrictions on their
<a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attributes (for example, new-style classes use a
dictproxy to prevent direct dictionary updates).</p>
<p>Without an argument, <a class="reference internal" href="#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a> acts like <a class="reference internal" href="#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a>.  Note, the
locals dictionary is only useful for reads since updates to the locals
dictionary are ignored.</p>
</dd></dl>

<dl class="function">
<dt id="xrange">
<code class="descname">xrange</code><span class="sig-paren">(</span><em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#xrange" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">xrange</code><span class="sig-paren">(</span><em>start</em>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>This function is very similar to <a class="reference internal" href="#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a>, but returns an <a class="reference internal" href="stdtypes.html#typesseq-xrange"><span class="std std-ref">xrange
object</span></a>
instead of a list.  This is an opaque sequence type which yields the same values
as the corresponding list, without actually storing them all simultaneously.
The advantage of <a class="reference internal" href="#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> over <a class="reference internal" href="#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> is minimal (since
<a class="reference internal" href="#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> still has to create the values when asked for them) except when a
very large range is used on a memory-starved machine or when all of the range’s
elements are never used (such as when the loop is usually terminated with
<a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>).  For more information on xrange objects, see
<a class="reference internal" href="stdtypes.html#typesseq-xrange"><span class="std std-ref">XRange Type</span></a> and <a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> <a class="reference internal" href="#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> is intended to be simple and fast.  Implementations may
impose restrictions to achieve this.  The C implementation of Python
restricts all arguments to native C longs (“short” Python integers), and
also requires that the number of elements fit in a native C long.  If a
larger range is needed, an alternate version can be crafted using the
<a class="reference internal" href="itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module: <code class="docutils literal notranslate"><span class="pre">islice(count(start,</span> <span class="pre">step),</span>
<span class="pre">(stop-start+step-1+2*(step&lt;0))//step)</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="zip">
<code class="descname">zip</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zip" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns a list of tuples, where the <em>i</em>-th tuple contains the
<em>i</em>-th element from each of the argument sequences or iterables. The returned
list is truncated in length to the length of the shortest argument sequence.
When there are multiple arguments which are all of the same length, <a class="reference internal" href="#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>
is similar to <a class="reference internal" href="#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> with an initial argument of <code class="docutils literal notranslate"><span class="pre">None</span></code>. With a single
sequence argument, it returns a list of 1-tuples. With no arguments, it returns
an empty list.</p>
<p>The left-to-right evaluation order of the iterables is guaranteed. This
makes possible an idiom for clustering a data series into n-length groups
using <code class="docutils literal notranslate"><span class="pre">zip(*[iter(s)]*n)</span></code>.</p>
<p><a class="reference internal" href="#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> in conjunction with the <code class="docutils literal notranslate"><span class="pre">*</span></code> operator can be used to unzip a
list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zipped</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zipped</span>
<span class="go">[(1, 4), (2, 5), (3, 6)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x2</span><span class="p">,</span> <span class="n">y2</span> <span class="o">=</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">zipped</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">==</span> <span class="nb">list</span><span class="p">(</span><span class="n">x2</span><span class="p">)</span> <span class="ow">and</span> <span class="n">y</span> <span class="o">==</span> <span class="nb">list</span><span class="p">(</span><span class="n">y2</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, <a class="reference internal" href="#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> required at least one argument and <code class="docutils literal notranslate"><span class="pre">zip()</span></code> raised a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> instead of returning an empty list.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="__import__">
<code class="descname">__import__</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">[</span>, <em>fromlist</em><span class="optional">[</span>, <em>level</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#__import__" title="Permalink to this definition">¶</a></dt>
<dd><div class="admonition note" id="index-8">
<p class="first admonition-title">Note</p>
<p class="last">This is an advanced function that is not needed in everyday Python
programming, unlike <a class="reference internal" href="importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a>.</p>
</div>
<p>This function is invoked by the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.  It can be
replaced (by importing the <a class="reference internal" href="__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module and assigning to
<code class="docutils literal notranslate"><span class="pre">__builtin__.__import__</span></code>) in order to change semantics of the
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, but nowadays it is usually simpler to use import
hooks (see <span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>).  Direct use of <a class="reference internal" href="#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> is rare, except in
cases where you want to import a module whose name is only known at runtime.</p>
<p>The function imports the module <em>name</em>, potentially using the given <em>globals</em>
and <em>locals</em> to determine how to interpret the name in a package context.
The <em>fromlist</em> gives the names of objects or submodules that should be
imported from the module given by <em>name</em>.  The standard implementation does
not use its <em>locals</em> argument at all, and uses its <em>globals</em> only to
determine the package context of the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.</p>
<p><em>level</em> specifies whether to use absolute or relative imports.  The default
is <code class="docutils literal notranslate"><span class="pre">-1</span></code> which indicates both absolute and relative imports will be
attempted.  <code class="docutils literal notranslate"><span class="pre">0</span></code> means only perform absolute imports.  Positive values for
<em>level</em> indicate the number of parent directories to search relative to the
directory of the module calling <a class="reference internal" href="#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>.</p>
<p>When the <em>name</em> variable is of the form <code class="docutils literal notranslate"><span class="pre">package.module</span></code>, normally, the
top-level package (the name up till the first dot) is returned, <em>not</em> the
module named by <em>name</em>.  However, when a non-empty <em>fromlist</em> argument is
given, the module named by <em>name</em> is returned.</p>
<p>For example, the statement <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">spam</span></code> results in bytecode resembling the
following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">spam</span> <span class="o">=</span> <span class="nb">__import__</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="nb">globals</span><span class="p">(),</span> <span class="nb">locals</span><span class="p">(),</span> <span class="p">[],</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>The statement <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">spam.ham</span></code> results in this call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">spam</span> <span class="o">=</span> <span class="nb">__import__</span><span class="p">(</span><span class="s1">&#39;spam.ham&#39;</span><span class="p">,</span> <span class="nb">globals</span><span class="p">(),</span> <span class="nb">locals</span><span class="p">(),</span> <span class="p">[],</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>Note how <a class="reference internal" href="#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> returns the toplevel module here because this is
the object that is bound to a name by the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.</p>
<p>On the other hand, the statement <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">spam.ham</span> <span class="pre">import</span> <span class="pre">eggs,</span> <span class="pre">sausage</span> <span class="pre">as</span>
<span class="pre">saus</span></code> results in</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">_temp</span> <span class="o">=</span> <span class="nb">__import__</span><span class="p">(</span><span class="s1">&#39;spam.ham&#39;</span><span class="p">,</span> <span class="nb">globals</span><span class="p">(),</span> <span class="nb">locals</span><span class="p">(),</span> <span class="p">[</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;sausage&#39;</span><span class="p">],</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="n">eggs</span> <span class="o">=</span> <span class="n">_temp</span><span class="o">.</span><span class="n">eggs</span>
<span class="n">saus</span> <span class="o">=</span> <span class="n">_temp</span><span class="o">.</span><span class="n">sausage</span>
</pre></div>
</div>
<p>Here, the <code class="docutils literal notranslate"><span class="pre">spam.ham</span></code> module is returned from <a class="reference internal" href="#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>.  From this
object, the names to import are retrieved and assigned to their respective
names.</p>
<p>If you simply want to import a module (potentially within a package) by name,
use <a class="reference internal" href="importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The level parameter was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Keyword support for parameters was added.</p>
</div>
</dd></dl>

</div>
<div class="section" id="non-essential-built-in-functions">
<span id="non-essential-built-in-funcs"></span><h1>3. Non-essential Built-in Functions<a class="headerlink" href="#non-essential-built-in-functions" title="Permalink to this headline">¶</a></h1>
<p>There are several built-in functions that are no longer essential to learn, know
or use in modern Python programming.  They have been kept here to maintain
backwards compatibility with programs written for older versions of Python.</p>
<p>Python programmers, trainers, students and book writers should feel free to
bypass these functions without concerns about missing something important.</p>
<dl class="function">
<dt id="apply">
<code class="descname">apply</code><span class="sig-paren">(</span><em>function</em>, <em>args</em><span class="optional">[</span>, <em>keywords</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#apply" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>function</em> argument must be a callable object (a user-defined or built-in
function or method, or a class object) and the <em>args</em> argument must be a
sequence.  The <em>function</em> is called with <em>args</em> as the argument list; the number
of arguments is the length of the tuple. If the optional <em>keywords</em> argument is
present, it must be a dictionary whose keys are strings.  It specifies keyword
arguments to be added to the end of the argument list. Calling <a class="reference internal" href="#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a> is
different from just calling <code class="docutils literal notranslate"><span class="pre">function(args)</span></code>, since in that case there is
always exactly one argument.  The use of <a class="reference internal" href="#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a> is equivalent to
<code class="docutils literal notranslate"><span class="pre">function(*args,</span> <span class="pre">**keywords)</span></code>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>Use <code class="docutils literal notranslate"><span class="pre">function(*args,</span> <span class="pre">**keywords)</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">apply(function,</span> <span class="pre">args,</span> <span class="pre">keywords)</span></code> (see <a class="reference internal" href="../tutorial/controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a>).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="buffer">
<code class="descname">buffer</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>offset</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>object</em> argument must be an object that supports the buffer call interface
(such as strings, arrays, and buffers).  A new buffer object will be created
which references the <em>object</em> argument. The buffer object will be a slice from
the beginning of <em>object</em> (or from the specified <em>offset</em>). The slice will
extend to the end of <em>object</em> (or will have a length given by the <em>size</em>
argument).</p>
</dd></dl>

<dl class="function">
<dt id="coerce">
<code class="descname">coerce</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#coerce" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple consisting of the two numeric arguments converted to a common
type, using the same rules as used by arithmetic operations. If coercion is not
possible, raise <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="intern">
<code class="descname">intern</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#intern" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter <em>string</em> in the table of “interned” strings and return the interned string
– which is <em>string</em> itself or a copy. Interning strings is useful to gain a
little performance on dictionary lookup – if the keys in a dictionary are
interned, and the lookup key is interned, the key comparisons (after hashing)
can be done by a pointer compare instead of a string compare.  Normally, the
names used in Python programs are automatically interned, and the dictionaries
used to hold module, class or instance attributes have interned keys.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Interned strings are not immortal (like they used to be in Python 2.2 and
before); you must keep a reference to the return value of <a class="reference internal" href="#intern" title="intern"><code class="xref py py-func docutils literal notranslate"><span class="pre">intern()</span></code></a> around
to benefit from it.</p>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>It is used relatively rarely so does not warrant being made into a statement.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Specifying a buffer size currently has no effect on systems that don’t have
<code class="xref c c-func docutils literal notranslate"><span class="pre">setvbuf()</span></code>.  The interface to specify the buffer size is not done using a
method that calls <code class="xref c c-func docutils literal notranslate"><span class="pre">setvbuf()</span></code>, because that may dump core when called after
any I/O has been performed, and there’s no reliable way to determine whether
this is the case.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[3]</td><td>In the current implementation, local variable bindings cannot normally be
affected this way, but variables retrieved from other scopes (such as modules)
can be.  This may change.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Built-in Functions</a></li>
<li><a class="reference internal" href="#non-essential-built-in-functions">3. Non-essential Built-in Functions</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="intro.html"
                        title="previous chapter">1. Introduction</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="constants.html"
                        title="next chapter">4. Built-in Constants</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/functions.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="constants.html" title="4. Built-in Constants"
             >next</a> |</li>
        <li class="right" >
          <a href="intro.html" title="1. Introduction"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����s�shtml/library/functools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.8. functools — Higher-order functions and operations on callable objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.9. operator — Standard operators as functions" href="operator.html" />
    <link rel="prev" title="9.7. itertools — Functions creating iterators for efficient looping" href="itertools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/functools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="operator.html" title="9.9. operator — Standard operators as functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="itertools.html" title="9.7. itertools — Functions creating iterators for efficient looping"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-functools">
<span id="functools-higher-order-functions-and-operations-on-callable-objects"></span><h1>9.8. <a class="reference internal" href="#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> — Higher-order functions and operations on callable objects<a class="headerlink" href="#module-functools" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/functools.py">Lib/functools.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module is for higher-order functions: functions that act on
or return other functions. In general, any callable object can be treated as a
function for the purposes of this module.</p>
<p>The <a class="reference internal" href="#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="functools.cmp_to_key">
<code class="descclassname">functools.</code><code class="descname">cmp_to_key</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#functools.cmp_to_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Transform an old-style comparison function to a <a class="reference internal" href="../glossary.html#term-key-function"><span class="xref std std-term">key function</span></a>.  Used
with tools that accept key functions (such as <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>, <a class="reference internal" href="functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>,
<a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>, <a class="reference internal" href="heapq.html#heapq.nlargest" title="heapq.nlargest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nlargest()</span></code></a>, <a class="reference internal" href="heapq.html#heapq.nsmallest" title="heapq.nsmallest"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapq.nsmallest()</span></code></a>,
<a class="reference internal" href="itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.groupby()</span></code></a>).  This function is primarily used as a transition
tool for programs being converted to Python 3 where comparison functions are
no longer supported.</p>
<p>A comparison function is any callable that accept two arguments, compares them,
and returns a negative number for less-than, zero for equality, or a positive
number for greater-than.  A key function is a callable that accepts one
argument and returns another value to be used as the sort key.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">sorted</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">cmp_to_key</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">strcoll</span><span class="p">))</span>  <span class="c1"># locale-aware sort order</span>
</pre></div>
</div>
<p>For sorting examples and a brief sorting tutorial, see <a class="reference internal" href="../howto/sorting.html#sortinghowto"><span class="std std-ref">Sorting HOW TO</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="functools.total_ordering">
<code class="descclassname">functools.</code><code class="descname">total_ordering</code><span class="sig-paren">(</span><em>cls</em><span class="sig-paren">)</span><a class="headerlink" href="#functools.total_ordering" title="Permalink to this definition">¶</a></dt>
<dd><p>Given a class defining one or more rich comparison ordering methods, this
class decorator supplies the rest.  This simplifies the effort involved
in specifying all of the possible rich comparison operations:</p>
<p>The class must define one of <a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a>, or <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a>.
In addition, the class should supply an <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@total_ordering</span>
<span class="k">class</span> <span class="nc">Student</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">lastname</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="bp">self</span><span class="o">.</span><span class="n">firstname</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span> <span class="o">==</span>
                <span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">lastname</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">other</span><span class="o">.</span><span class="n">firstname</span><span class="o">.</span><span class="n">lower</span><span class="p">()))</span>
    <span class="k">def</span> <span class="nf">__lt__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">lastname</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="bp">self</span><span class="o">.</span><span class="n">firstname</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span> <span class="o">&lt;</span>
                <span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">lastname</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">other</span><span class="o">.</span><span class="n">firstname</span><span class="o">.</span><span class="n">lower</span><span class="p">()))</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="functools.reduce">
<code class="descclassname">functools.</code><code class="descname">reduce</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em><span class="optional">[</span>, <em>initializer</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#functools.reduce" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the same function as <a class="reference internal" href="functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a>.  It is made available in this module
to allow writing code more forward-compatible with Python 3.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="functools.partial">
<code class="descclassname">functools.</code><code class="descname">partial</code><span class="sig-paren">(</span><em>func[,*args][, **keywords]</em><span class="sig-paren">)</span><a class="headerlink" href="#functools.partial" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#partial-objects"><span class="std std-ref">partial object</span></a> which when called will behave
like <em>func</em> called with the positional arguments <em>args</em> and keyword arguments <em>keywords</em>.
If more arguments are supplied to the call, they are appended to <em>args</em>. If
additional keyword arguments are supplied, they extend and override <em>keywords</em>.
Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">partial</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">keywords</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">newfunc</span><span class="p">(</span><span class="o">*</span><span class="n">fargs</span><span class="p">,</span> <span class="o">**</span><span class="n">fkeywords</span><span class="p">):</span>
        <span class="n">newkeywords</span> <span class="o">=</span> <span class="n">keywords</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span>
        <span class="n">newkeywords</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">fkeywords</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="p">(</span><span class="n">args</span> <span class="o">+</span> <span class="n">fargs</span><span class="p">),</span> <span class="o">**</span><span class="n">newkeywords</span><span class="p">)</span>
    <span class="n">newfunc</span><span class="o">.</span><span class="n">func</span> <span class="o">=</span> <span class="n">func</span>
    <span class="n">newfunc</span><span class="o">.</span><span class="n">args</span> <span class="o">=</span> <span class="n">args</span>
    <span class="n">newfunc</span><span class="o">.</span><span class="n">keywords</span> <span class="o">=</span> <span class="n">keywords</span>
    <span class="k">return</span> <span class="n">newfunc</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code></a> is used for partial function application which “freezes”
some portion of a function’s arguments and/or keywords resulting in a new object
with a simplified signature.  For example, <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code></a> can be used to create
a callable that behaves like the <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> function where the <em>base</em> argument
defaults to two:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">functools</span> <span class="k">import</span> <span class="n">partial</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">basetwo</span> <span class="o">=</span> <span class="n">partial</span><span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="n">base</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">basetwo</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="s1">&#39;Convert base 2 string to an int.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">basetwo</span><span class="p">(</span><span class="s1">&#39;10010&#39;</span><span class="p">)</span>
<span class="go">18</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="functools.update_wrapper">
<code class="descclassname">functools.</code><code class="descname">update_wrapper</code><span class="sig-paren">(</span><em>wrapper, wrapped[, assigned][, updated]</em><span class="sig-paren">)</span><a class="headerlink" href="#functools.update_wrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>Update a <em>wrapper</em> function to look like the <em>wrapped</em> function. The optional
arguments are tuples to specify which attributes of the original function are
assigned directly to the matching attributes on the wrapper function and which
attributes of the wrapper function are updated with the corresponding attributes
from the original function. The default values for these arguments are the
module level constants <em>WRAPPER_ASSIGNMENTS</em> (which assigns to the wrapper
function’s <em>__name__</em>, <em>__module__</em> and <em>__doc__</em>, the documentation string) and
<em>WRAPPER_UPDATES</em> (which updates the wrapper function’s <em>__dict__</em>, i.e. the
instance dictionary).</p>
<p>The main intended use for this function is in <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> functions which
wrap the decorated function and return the wrapper. If the wrapper function is
not updated, the metadata of the returned function will reflect the wrapper
definition rather than the original function definition, which is typically less
than helpful.</p>
</dd></dl>

<dl class="function">
<dt id="functools.wraps">
<code class="descclassname">functools.</code><code class="descname">wraps</code><span class="sig-paren">(</span><em>wrapped[, assigned][, updated]</em><span class="sig-paren">)</span><a class="headerlink" href="#functools.wraps" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a convenience function for invoking <a class="reference internal" href="#functools.update_wrapper" title="functools.update_wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">update_wrapper()</span></code></a> as a
function decorator when defining a wrapper function.  It is equivalent to
<code class="docutils literal notranslate"><span class="pre">partial(update_wrapper,</span> <span class="pre">wrapped=wrapped,</span> <span class="pre">assigned=assigned,</span> <span class="pre">updated=updated)</span></code>.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">functools</span> <span class="k">import</span> <span class="n">wraps</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nd">@wraps</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s1">&#39;Calling decorated function&#39;</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">wrapper</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nd">@my_decorator</span>
<span class="gp">... </span><span class="k">def</span> <span class="nf">example</span><span class="p">():</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Docstring&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Called example function&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">example</span><span class="p">()</span>
<span class="go">Calling decorated function</span>
<span class="go">Called example function</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">example</span><span class="o">.</span><span class="vm">__name__</span>
<span class="go">&#39;example&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">example</span><span class="o">.</span><span class="vm">__doc__</span>
<span class="go">&#39;Docstring&#39;</span>
</pre></div>
</div>
<p>Without the use of this decorator factory, the name of the example function
would have been <code class="docutils literal notranslate"><span class="pre">'wrapper'</span></code>, and the docstring of the original <code class="xref py py-func docutils literal notranslate"><span class="pre">example()</span></code>
would have been lost.</p>
</dd></dl>

<div class="section" id="partial-objects">
<span id="id1"></span><h2>9.8.1. <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> Objects<a class="headerlink" href="#partial-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> objects are callable objects created by <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code></a>. They
have three read-only attributes:</p>
<dl class="attribute">
<dt id="functools.partial.func">
<code class="descclassname">partial.</code><code class="descname">func</code><a class="headerlink" href="#functools.partial.func" title="Permalink to this definition">¶</a></dt>
<dd><p>A callable object or function.  Calls to the <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> object will be
forwarded to <a class="reference internal" href="#functools.partial.func" title="functools.partial.func"><code class="xref py py-attr docutils literal notranslate"><span class="pre">func</span></code></a> with new arguments and keywords.</p>
</dd></dl>

<dl class="attribute">
<dt id="functools.partial.args">
<code class="descclassname">partial.</code><code class="descname">args</code><a class="headerlink" href="#functools.partial.args" title="Permalink to this definition">¶</a></dt>
<dd><p>The leftmost positional arguments that will be prepended to the positional
arguments provided to a <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> object call.</p>
</dd></dl>

<dl class="attribute">
<dt id="functools.partial.keywords">
<code class="descclassname">partial.</code><code class="descname">keywords</code><a class="headerlink" href="#functools.partial.keywords" title="Permalink to this definition">¶</a></dt>
<dd><p>The keyword arguments that will be supplied when the <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> object is
called.</p>
</dd></dl>

<p><a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> objects are like <code class="xref py py-class docutils literal notranslate"><span class="pre">function</span></code> objects in that they are
callable, weak referencable, and can have attributes.  There are some important
differences.  For instance, the <a class="reference internal" href="stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attributes
are not created automatically.  Also, <a class="reference internal" href="#functools.partial" title="functools.partial"><code class="xref py py-class docutils literal notranslate"><span class="pre">partial</span></code></a> objects defined in
classes behave like static methods and do not transform into bound methods
during instance attribute look-up.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a><ul>
<li><a class="reference internal" href="#partial-objects">9.8.1. <code class="docutils literal notranslate"><span class="pre">partial</span></code> Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="itertools.html"
                        title="previous chapter">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="operator.html"
                        title="next chapter">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/functools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="operator.html" title="9.9. operator — Standard operators as functions"
             >next</a> |</li>
        <li class="right" >
          <a href="itertools.html" title="9.7. itertools — Functions creating iterators for efficient looping"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\q���8�8!html/library/future_builtins.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.4. future_builtins — Python 3 builtins &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.5. __main__ — Top-level script environment" href="__main__.html" />
    <link rel="prev" title="28.3. __builtin__ — Built-in objects" href="__builtin__.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/future_builtins.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__main__.html" title="28.5. __main__ — Top-level script environment"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="__builtin__.html" title="28.3. __builtin__ — Built-in objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-future_builtins">
<span id="future-builtins-python-3-builtins"></span><h1>28.4. <a class="reference internal" href="#module-future_builtins" title="future_builtins"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code></a> — Python 3 builtins<a class="headerlink" href="#module-future_builtins" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>This module provides functions that exist in 2.x, but have different behavior in
Python 3, so they cannot be put into the 2.x builtins namespace.</p>
<p>Instead, if you want to write code compatible with Python 3 builtins, import
them from this module, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">future_builtins</span> <span class="k">import</span> <span class="nb">map</span><span class="p">,</span> <span class="nb">filter</span>

<span class="o">...</span> <span class="n">code</span> <span class="n">using</span> <span class="n">Python</span> <span class="mi">3</span><span class="o">-</span><span class="n">style</span> <span class="nb">map</span> <span class="ow">and</span> <span class="nb">filter</span> <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool that ports Python 2 code to Python 3 will recognize
this usage and leave the new builtins alone.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The Python 3 <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function is already in the builtins, but cannot be
accessed from Python 2 code unless you use the appropriate future statement:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">print_function</span>
</pre></div>
</div>
</div>
<p>Available builtins are:</p>
<dl class="function">
<dt id="future_builtins.ascii">
<code class="descclassname">future_builtins.</code><code class="descname">ascii</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.ascii" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the same as <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  In Python 3, <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> will return
printable Unicode characters unescaped, while <a class="reference internal" href="#future_builtins.ascii" title="future_builtins.ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a> will always
backslash-escape them.  Using <a class="reference internal" href="#future_builtins.ascii" title="future_builtins.ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">future_builtins.ascii()</span></code></a> instead of
<a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> in 2.6 code makes it clear that you need a pure ASCII return
value.</p>
</dd></dl>

<dl class="function">
<dt id="future_builtins.filter">
<code class="descclassname">future_builtins.</code><code class="descname">filter</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Works like <a class="reference internal" href="itertools.html#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilter()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="future_builtins.hex">
<code class="descclassname">future_builtins.</code><code class="descname">hex</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.hex" title="Permalink to this definition">¶</a></dt>
<dd><p>Works like the built-in <a class="reference internal" href="functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a>, but instead of <a class="reference internal" href="../reference/datamodel.html#object.__hex__" title="object.__hex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hex__()</span></code></a> it will
use the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method on its argument to get an integer that is
then converted to hexadecimal.</p>
</dd></dl>

<dl class="function">
<dt id="future_builtins.map">
<code class="descclassname">future_builtins.</code><code class="descname">map</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.map" title="Permalink to this definition">¶</a></dt>
<dd><p>Works like <a class="reference internal" href="itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3, <a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> does not accept <code class="docutils literal notranslate"><span class="pre">None</span></code> for the
function argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="future_builtins.oct">
<code class="descclassname">future_builtins.</code><code class="descname">oct</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.oct" title="Permalink to this definition">¶</a></dt>
<dd><p>Works like the built-in <a class="reference internal" href="functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a>, but instead of <a class="reference internal" href="../reference/datamodel.html#object.__oct__" title="object.__oct__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__oct__()</span></code></a> it will
use the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method on its argument to get an integer that is
then converted to octal.</p>
</dd></dl>

<dl class="function">
<dt id="future_builtins.zip">
<code class="descclassname">future_builtins.</code><code class="descname">zip</code><span class="sig-paren">(</span><em>*iterables</em><span class="sig-paren">)</span><a class="headerlink" href="#future_builtins.zip" title="Permalink to this definition">¶</a></dt>
<dd><p>Works like <a class="reference internal" href="itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="__builtin__.html"
                        title="previous chapter">28.3. <code class="docutils literal notranslate"><span class="pre">__builtin__</span></code> — Built-in objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="__main__.html"
                        title="next chapter">28.5. <code class="docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level script environment</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/future_builtins.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__main__.html" title="28.5. __main__ — Top-level script environment"
             >next</a> |</li>
        <li class="right" >
          <a href="__builtin__.html" title="28.3. __builtin__ — Built-in objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Nݱoohtml/library/gc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.12. gc — Garbage Collector interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.13. inspect — Inspect live objects" href="inspect.html" />
    <link rel="prev" title="28.11. __future__ — Future statement definitions" href="__future__.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="inspect.html" title="28.13. inspect — Inspect live objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="__future__.html" title="28.11. __future__ — Future statement definitions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gc">
<span id="gc-garbage-collector-interface"></span><h1>28.12. <a class="reference internal" href="#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> — Garbage Collector interface<a class="headerlink" href="#module-gc" title="Permalink to this headline">¶</a></h1>
<p>This module provides an interface to the optional garbage collector.  It
provides the ability to disable the collector, tune the collection frequency,
and set debugging options.  It also provides access to unreachable objects that
the collector found but cannot free.  Since the collector supplements the
reference counting already used in Python, you can disable the collector if you
are sure your program does not create reference cycles.  Automatic collection
can be disabled by calling <code class="docutils literal notranslate"><span class="pre">gc.disable()</span></code>.  To debug a leaking program call
<code class="docutils literal notranslate"><span class="pre">gc.set_debug(gc.DEBUG_LEAK)</span></code>. Notice that this includes
<code class="docutils literal notranslate"><span class="pre">gc.DEBUG_SAVEALL</span></code>, causing garbage-collected objects to be saved in
gc.garbage for inspection.</p>
<p>The <a class="reference internal" href="#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module provides the following functions:</p>
<dl class="function">
<dt id="gc.enable">
<code class="descclassname">gc.</code><code class="descname">enable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.enable" title="Permalink to this definition">¶</a></dt>
<dd><p>Enable automatic garbage collection.</p>
</dd></dl>

<dl class="function">
<dt id="gc.disable">
<code class="descclassname">gc.</code><code class="descname">disable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.disable" title="Permalink to this definition">¶</a></dt>
<dd><p>Disable automatic garbage collection.</p>
</dd></dl>

<dl class="function">
<dt id="gc.isenabled">
<code class="descclassname">gc.</code><code class="descname">isenabled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.isenabled" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if automatic collection is enabled.</p>
</dd></dl>

<dl class="function">
<dt id="gc.collect">
<code class="descclassname">gc.</code><code class="descname">collect</code><span class="sig-paren">(</span><span class="optional">[</span><em>generation</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.collect" title="Permalink to this definition">¶</a></dt>
<dd><p>With no arguments, run a full collection.  The optional argument <em>generation</em>
may be an integer specifying which generation to collect (from 0 to 2).  A
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised if the generation number  is invalid. The number of
unreachable objects found is returned.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The optional <em>generation</em> argument was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The free lists maintained for a number of built-in types are cleared
whenever a full collection or collection of the highest generation (2)
is run.  Not all items in some free lists may be freed due to the
particular implementation, in particular <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> and <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="gc.set_debug">
<code class="descclassname">gc.</code><code class="descname">set_debug</code><span class="sig-paren">(</span><em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#gc.set_debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the garbage collection debugging flags. Debugging information will be
written to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.  See below for a list of debugging flags which can be
combined using bit operations to control debugging.</p>
</dd></dl>

<dl class="function">
<dt id="gc.get_debug">
<code class="descclassname">gc.</code><code class="descname">get_debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the debugging flags currently set.</p>
</dd></dl>

<dl class="function">
<dt id="gc.get_objects">
<code class="descclassname">gc.</code><code class="descname">get_objects</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_objects" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of all objects tracked by the collector, excluding the list
returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gc.set_threshold">
<code class="descclassname">gc.</code><code class="descname">set_threshold</code><span class="sig-paren">(</span><em>threshold0</em><span class="optional">[</span>, <em>threshold1</em><span class="optional">[</span>, <em>threshold2</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.set_threshold" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the garbage collection thresholds (the collection frequency). Setting
<em>threshold0</em> to zero disables collection.</p>
<p>The GC classifies objects into three generations depending on how many
collection sweeps they have survived.  New objects are placed in the youngest
generation (generation <code class="docutils literal notranslate"><span class="pre">0</span></code>).  If an object survives a collection it is moved
into the next older generation.  Since generation <code class="docutils literal notranslate"><span class="pre">2</span></code> is the oldest
generation, objects in that generation remain there after a collection.  In
order to decide when to run, the collector keeps track of the number object
allocations and deallocations since the last collection.  When the number of
allocations minus the number of deallocations exceeds <em>threshold0</em>, collection
starts.  Initially only generation <code class="docutils literal notranslate"><span class="pre">0</span></code> is examined.  If generation <code class="docutils literal notranslate"><span class="pre">0</span></code> has
been examined more than <em>threshold1</em> times since generation <code class="docutils literal notranslate"><span class="pre">1</span></code> has been
examined, then generation <code class="docutils literal notranslate"><span class="pre">1</span></code> is examined as well.  Similarly, <em>threshold2</em>
controls the number of collections of generation <code class="docutils literal notranslate"><span class="pre">1</span></code> before collecting
generation <code class="docutils literal notranslate"><span class="pre">2</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="gc.get_count">
<code class="descclassname">gc.</code><code class="descname">get_count</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current collection  counts as a tuple of <code class="docutils literal notranslate"><span class="pre">(count0,</span> <span class="pre">count1,</span>
<span class="pre">count2)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gc.get_threshold">
<code class="descclassname">gc.</code><code class="descname">get_threshold</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_threshold" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current collection thresholds as a tuple of <code class="docutils literal notranslate"><span class="pre">(threshold0,</span>
<span class="pre">threshold1,</span> <span class="pre">threshold2)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="gc.get_referrers">
<code class="descclassname">gc.</code><code class="descname">get_referrers</code><span class="sig-paren">(</span><em>*objs</em><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_referrers" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the list of objects that directly refer to any of objs. This function
will only locate those containers which support garbage collection; extension
types which do refer to other objects but do not support garbage collection will
not be found.</p>
<p>Note that objects which have already been dereferenced, but which live in cycles
and have not yet been collected by the garbage collector can be listed among the
resulting referrers.  To get only currently live objects, call <a class="reference internal" href="#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">collect()</span></code></a>
before calling <a class="reference internal" href="#gc.get_referrers" title="gc.get_referrers"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_referrers()</span></code></a>.</p>
<p>Care must be taken when using objects returned by <a class="reference internal" href="#gc.get_referrers" title="gc.get_referrers"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_referrers()</span></code></a> because
some of them could still be under construction and hence in a temporarily
invalid state. Avoid using <a class="reference internal" href="#gc.get_referrers" title="gc.get_referrers"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_referrers()</span></code></a> for any purpose other than
debugging.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gc.get_referents">
<code class="descclassname">gc.</code><code class="descname">get_referents</code><span class="sig-paren">(</span><em>*objs</em><span class="sig-paren">)</span><a class="headerlink" href="#gc.get_referents" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of objects directly referred to by any of the arguments. The
referents returned are those objects visited by the arguments’ C-level
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> methods (if any), and may not be all objects actually
directly reachable.  <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_traverse</span></code></a> methods are supported only by objects
that support garbage collection, and are only required to visit objects that may
be involved in a cycle.  So, for example, if an integer is directly reachable
from an argument, that integer object may or may not appear in the result list.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gc.is_tracked">
<code class="descclassname">gc.</code><code class="descname">is_tracked</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#gc.is_tracked" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the object is currently tracked by the garbage collector,
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  As a general rule, instances of atomic types aren’t
tracked and instances of non-atomic types (containers, user-defined
objects…) are.  However, some type-specific optimizations can be present
in order to suppress the garbage collector footprint of simple instances
(e.g. dicts containing only atomic keys and values):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">([])</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">({})</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">({</span><span class="s2">&quot;a&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">})</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">is_tracked</span><span class="p">({</span><span class="s2">&quot;a&quot;</span><span class="p">:</span> <span class="p">[]})</span>
<span class="go">True</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>The following variable is provided for read-only access (you can mutate its
value but should not rebind it):</p>
<dl class="data">
<dt id="gc.garbage">
<code class="descclassname">gc.</code><code class="descname">garbage</code><a class="headerlink" href="#gc.garbage" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of objects which the collector found to be unreachable but could not be
freed (uncollectable objects).  By default, this list contains only objects with
<a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods. <a class="footnote-reference" href="#id2" id="id1">[1]</a> Objects that have <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods and are
part of a reference cycle cause the entire reference cycle to be uncollectable,
including objects not necessarily in the cycle but reachable only from it.
Python doesn’t collect such cycles automatically because, in general, it isn’t
possible for Python to guess a safe order in which to run the <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a>
methods.  If you know a safe order, you can force the issue by examining the
<em>garbage</em> list, and explicitly breaking cycles due to your objects within the
list.  Note that these objects are kept alive even so by virtue of being in the
<em>garbage</em> list, so they should be removed from <em>garbage</em> too.  For example,
after breaking cycles, do <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">gc.garbage[:]</span></code> to empty the list.  It’s
generally better to avoid the issue by not creating cycles containing objects
with <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods, and <em>garbage</em> can be examined in that case to
verify that no such cycles are being created.</p>
<p>If <a class="reference internal" href="#gc.DEBUG_SAVEALL" title="gc.DEBUG_SAVEALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG_SAVEALL</span></code></a> is set, then all unreachable objects will be added to
this list rather than freed.</p>
</dd></dl>

<p>The following constants are provided for use with <a class="reference internal" href="#gc.set_debug" title="gc.set_debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_debug()</span></code></a>:</p>
<dl class="data">
<dt id="gc.DEBUG_STATS">
<code class="descclassname">gc.</code><code class="descname">DEBUG_STATS</code><a class="headerlink" href="#gc.DEBUG_STATS" title="Permalink to this definition">¶</a></dt>
<dd><p>Print statistics during collection.  This information can be useful when tuning
the collection frequency.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_COLLECTABLE">
<code class="descclassname">gc.</code><code class="descname">DEBUG_COLLECTABLE</code><a class="headerlink" href="#gc.DEBUG_COLLECTABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Print information on collectable objects found.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_UNCOLLECTABLE">
<code class="descclassname">gc.</code><code class="descname">DEBUG_UNCOLLECTABLE</code><a class="headerlink" href="#gc.DEBUG_UNCOLLECTABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Print information of uncollectable objects found (objects which are not
reachable but cannot be freed by the collector).  These objects will be added to
the <code class="docutils literal notranslate"><span class="pre">garbage</span></code> list.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_INSTANCES">
<code class="descclassname">gc.</code><code class="descname">DEBUG_INSTANCES</code><a class="headerlink" href="#gc.DEBUG_INSTANCES" title="Permalink to this definition">¶</a></dt>
<dd><p>When <a class="reference internal" href="#gc.DEBUG_COLLECTABLE" title="gc.DEBUG_COLLECTABLE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG_COLLECTABLE</span></code></a> or <a class="reference internal" href="#gc.DEBUG_UNCOLLECTABLE" title="gc.DEBUG_UNCOLLECTABLE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG_UNCOLLECTABLE</span></code></a> is set, print
information about instance objects found.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_OBJECTS">
<code class="descclassname">gc.</code><code class="descname">DEBUG_OBJECTS</code><a class="headerlink" href="#gc.DEBUG_OBJECTS" title="Permalink to this definition">¶</a></dt>
<dd><p>When <a class="reference internal" href="#gc.DEBUG_COLLECTABLE" title="gc.DEBUG_COLLECTABLE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG_COLLECTABLE</span></code></a> or <a class="reference internal" href="#gc.DEBUG_UNCOLLECTABLE" title="gc.DEBUG_UNCOLLECTABLE"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG_UNCOLLECTABLE</span></code></a> is set, print
information about objects other than instance objects found.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_SAVEALL">
<code class="descclassname">gc.</code><code class="descname">DEBUG_SAVEALL</code><a class="headerlink" href="#gc.DEBUG_SAVEALL" title="Permalink to this definition">¶</a></dt>
<dd><p>When set, all unreachable objects found will be appended to <em>garbage</em> rather
than being freed.  This can be useful for debugging a leaking program.</p>
</dd></dl>

<dl class="data">
<dt id="gc.DEBUG_LEAK">
<code class="descclassname">gc.</code><code class="descname">DEBUG_LEAK</code><a class="headerlink" href="#gc.DEBUG_LEAK" title="Permalink to this definition">¶</a></dt>
<dd><p>The debugging flags necessary for the collector to print information about a
leaking program (equal to <code class="docutils literal notranslate"><span class="pre">DEBUG_COLLECTABLE</span> <span class="pre">|</span> <span class="pre">DEBUG_UNCOLLECTABLE</span> <span class="pre">|</span>
<span class="pre">DEBUG_INSTANCES</span> <span class="pre">|</span> <span class="pre">DEBUG_OBJECTS</span> <span class="pre">|</span> <span class="pre">DEBUG_SAVEALL</span></code>).</p>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Prior to Python 2.2, the list contained all instance objects in unreachable
cycles,  not only those with <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="__future__.html"
                        title="previous chapter">28.11. <code class="docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="inspect.html"
                        title="next chapter">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="inspect.html" title="28.13. inspect — Inspect live objects"
             >next</a> |</li>
        <li class="right" >
          <a href="__future__.html" title="28.11. __future__ — Future statement definitions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\h�j��E�Ehtml/library/gdbm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.9. gdbm — GNU’s reinterpretation of dbm &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.10. dbhash — DBM-style interface to the BSD database library" href="dbhash.html" />
    <link rel="prev" title="11.8. dbm — Simple “database” interface" href="dbm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gdbm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dbhash.html" title="11.10. dbhash — DBM-style interface to the BSD database library"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dbm.html" title="11.8. dbm — Simple “database” interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gdbm">
<span id="gdbm-gnu-s-reinterpretation-of-dbm"></span><h1>11.9. <a class="reference internal" href="#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a> — GNU’s reinterpretation of dbm<a class="headerlink" href="#module-gdbm" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.gnu</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p id="index-0">This module is quite similar to the <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a> module, but uses <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> instead
to provide some additional functionality.  Please note that the file formats
created by <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> and <code class="docutils literal notranslate"><span class="pre">dbm</span></code> are incompatible.</p>
<p>The <a class="reference internal" href="#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a> module provides an interface to the GNU DBM library.  <code class="docutils literal notranslate"><span class="pre">gdbm</span></code>
objects behave like mappings (dictionaries), except that keys and values are
always strings. Printing a <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> object doesn’t print the keys and values,
and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code> methods are not supported.</p>
<p>The module defines the following constant and functions:</p>
<dl class="exception">
<dt id="gdbm.error">
<em class="property">exception </em><code class="descclassname">gdbm.</code><code class="descname">error</code><a class="headerlink" href="#gdbm.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised on <code class="docutils literal notranslate"><span class="pre">gdbm</span></code>-specific errors, such as I/O errors. <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is
raised for general mapping errors like specifying an incorrect key.</p>
</dd></dl>

<dl class="function">
<dt id="gdbm.open">
<code class="descclassname">gdbm.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>flag</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> database and return a <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> object.  The <em>filename</em> argument
is the name of the database file.</p>
<p>The optional <em>flag</em> argument can be:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>Open existing database for reading only
(default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span></code></td>
<td>Open existing database for reading and
writing</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Open database for reading and writing,
creating it if it doesn’t exist</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Always create a new, empty database, open
for reading and writing</td>
</tr>
</tbody>
</table>
<p>The following additional characters may be appended to the flag to control
how the database is opened:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'f'</span></code></td>
<td>Open the database in fast mode.  Writes
to the database will not be synchronized.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'s'</span></code></td>
<td>Synchronized mode. This will cause changes
to the database to be immediately written
to the file.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'u'</span></code></td>
<td>Do not lock database.</td>
</tr>
</tbody>
</table>
<p>Not all flags are valid for all versions of <code class="docutils literal notranslate"><span class="pre">gdbm</span></code>.  The module constant
<code class="xref py py-const docutils literal notranslate"><span class="pre">open_flags</span></code> is a string of supported flag characters.  The exception
<a class="reference internal" href="#gdbm.error" title="gdbm.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> is raised if an invalid flag is specified.</p>
<p>The optional <em>mode</em> argument is the Unix mode of the file, used only when the
database has to be created.  It defaults to octal <code class="docutils literal notranslate"><span class="pre">0666</span></code>.</p>
</dd></dl>

<p>In addition to the dictionary-like methods, <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> objects have the following
methods:</p>
<dl class="function">
<dt id="gdbm.firstkey">
<code class="descclassname">gdbm.</code><code class="descname">firstkey</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.firstkey" title="Permalink to this definition">¶</a></dt>
<dd><p>It’s possible to loop over every key in the database using this method  and the
<a class="reference internal" href="#gdbm.nextkey" title="gdbm.nextkey"><code class="xref py py-meth docutils literal notranslate"><span class="pre">nextkey()</span></code></a> method.  The traversal is ordered by <code class="docutils literal notranslate"><span class="pre">gdbm</span></code>’s internal hash
values, and won’t be sorted by the key values.  This method returns the starting
key.</p>
</dd></dl>

<dl class="function">
<dt id="gdbm.nextkey">
<code class="descclassname">gdbm.</code><code class="descname">nextkey</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.nextkey" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the key that follows <em>key</em> in the traversal.  The following code prints
every key in the database <code class="docutils literal notranslate"><span class="pre">db</span></code>, without having to create a list in memory that
contains them all:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">k</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">firstkey</span><span class="p">()</span>
<span class="k">while</span> <span class="n">k</span> <span class="o">!=</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">k</span>
    <span class="n">k</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">nextkey</span><span class="p">(</span><span class="n">k</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="gdbm.reorganize">
<code class="descclassname">gdbm.</code><code class="descname">reorganize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.reorganize" title="Permalink to this definition">¶</a></dt>
<dd><p>If you have carried out a lot of deletions and would like to shrink the space
used by the <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> file, this routine will reorganize the database.  <code class="docutils literal notranslate"><span class="pre">gdbm</span></code>
will not shorten the length of a database file except by using this
reorganization; otherwise, deleted file space will be kept and reused as new
(key, value) pairs are added.</p>
</dd></dl>

<dl class="function">
<dt id="gdbm.sync">
<code class="descclassname">gdbm.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>When the database has been opened in fast mode, this method forces any
unwritten data to be written to the disk.</p>
</dd></dl>

<dl class="function">
<dt id="gdbm.close">
<code class="descclassname">gdbm.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gdbm.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> database.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a></dt>
<dd>Generic interface to <code class="docutils literal notranslate"><span class="pre">dbm</span></code>-style databases.</dd>
<dt>Module <a class="reference internal" href="whichdb.html#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a></dt>
<dd>Utility module used to determine the type of an existing database.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="dbm.html"
                        title="previous chapter">11.8. <code class="docutils literal notranslate"><span class="pre">dbm</span></code> — Simple “database” interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dbhash.html"
                        title="next chapter">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gdbm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dbhash.html" title="11.10. dbhash — DBM-style interface to the BSD database library"
             >next</a> |</li>
        <li class="right" >
          <a href="dbm.html" title="11.8. dbm — Simple “database” interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�j��11 html/library/gensuitemodule.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38.1. gensuitemodule — Generate OSA stub packages &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38.2. aetools — OSA client support" href="aetools.html" />
    <link rel="prev" title="38. MacPython OSA Modules" href="macosa.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gensuitemodule.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aetools.html" title="38.2. aetools — OSA client support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="macosa.html" title="38. MacPython OSA Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" accesskey="U">38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gensuitemodule">
<span id="gensuitemodule-generate-osa-stub-packages"></span><h1>38.1. <a class="reference internal" href="#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a> — Generate OSA stub packages<a class="headerlink" href="#module-gensuitemodule" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a> module creates a Python package implementing stub code
for the AppleScript suites that are implemented by a specific application,
according to its AppleScript dictionary.</p>
<p>It is usually invoked by the user through the <strong class="program">PythonIDE</strong>, but it can
also be run as a script from the command line (pass <a class="reference internal" href="../using/cmdline.html#cmdoption-help"><code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code></a> for help on
the options) or imported from Python code. For an example of its use see
<code class="file docutils literal notranslate"><span class="pre">Mac/scripts/genallsuites.py</span></code> in a source distribution, which generates
the stub packages that are included in the standard library.</p>
<p>It defines the following public functions:</p>
<dl class="function">
<dt id="gensuitemodule.is_scriptable">
<code class="descclassname">gensuitemodule.</code><code class="descname">is_scriptable</code><span class="sig-paren">(</span><em>application</em><span class="sig-paren">)</span><a class="headerlink" href="#gensuitemodule.is_scriptable" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if <code class="docutils literal notranslate"><span class="pre">application</span></code>, which should be passed as a pathname, appears
to be scriptable. Take the return value with a grain of salt: <strong class="program">Internet
Explorer</strong> appears not to be scriptable but definitely is.</p>
</dd></dl>

<dl class="function">
<dt id="gensuitemodule.processfile">
<code class="descclassname">gensuitemodule.</code><code class="descname">processfile</code><span class="sig-paren">(</span><em>application</em><span class="optional">[</span>, <em>output</em>, <em>basepkgname</em>, <em>edit_modnames</em>, <em>creatorsignature</em>, <em>dump</em>, <em>verbose</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gensuitemodule.processfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a stub package for <code class="docutils literal notranslate"><span class="pre">application</span></code>, which should be passed as a full
pathname. For a <code class="file docutils literal notranslate"><span class="pre">.app</span></code> bundle this is the pathname to the bundle, not to
the executable inside the bundle; for an unbundled CFM application you pass the
filename of the application binary.</p>
<p>This function asks the application for its OSA terminology resources, decodes
these resources and uses the resultant data to create the Python code for the
package implementing the client stubs.</p>
<p><code class="docutils literal notranslate"><span class="pre">output</span></code> is the pathname where the resulting package is stored, if not
specified a standard “save file as” dialog is presented to the user.
<code class="docutils literal notranslate"><span class="pre">basepkgname</span></code> is the base package on which this package will build, and
defaults to <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code>. Only when generating <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code> itself do
you need to specify this. <code class="docutils literal notranslate"><span class="pre">edit_modnames</span></code> is a dictionary that can be used to
change modulenames that are too ugly after name mangling. <code class="docutils literal notranslate"><span class="pre">creator_signature</span></code>
can be used to override the 4-char creator code, which is normally obtained from
the <code class="file docutils literal notranslate"><span class="pre">PkgInfo</span></code> file in the package or from the CFM file creator signature.
When <code class="docutils literal notranslate"><span class="pre">dump</span></code> is given it should refer to a file object, and <code class="docutils literal notranslate"><span class="pre">processfile</span></code>
will stop after decoding the resources and dump the Python representation of the
terminology resources to this file. <code class="docutils literal notranslate"><span class="pre">verbose</span></code> should also be a file object,
and specifying it will cause <code class="docutils literal notranslate"><span class="pre">processfile</span></code> to tell you what it is doing.</p>
</dd></dl>

<dl class="function">
<dt id="gensuitemodule.processfile_fromresource">
<code class="descclassname">gensuitemodule.</code><code class="descname">processfile_fromresource</code><span class="sig-paren">(</span><em>application</em><span class="optional">[</span>, <em>output</em>, <em>basepkgname</em>, <em>edit_modnames</em>, <em>creatorsignature</em>, <em>dump</em>, <em>verbose</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gensuitemodule.processfile_fromresource" title="Permalink to this definition">¶</a></dt>
<dd><p>This function does the same as <code class="docutils literal notranslate"><span class="pre">processfile</span></code>, except that it uses a different
method to get the terminology resources. It opens <code class="docutils literal notranslate"><span class="pre">application</span></code> as a resource
file and reads all <code class="docutils literal notranslate"><span class="pre">&quot;aete&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;aeut&quot;</span></code> resources from this file.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="macosa.html"
                        title="previous chapter">38. MacPython OSA Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="aetools.html"
                        title="next chapter">38.2. <code class="docutils literal notranslate"><span class="pre">aetools</span></code> — OSA client support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gensuitemodule.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aetools.html" title="38.2. aetools — OSA client support"
             >next</a> |</li>
        <li class="right" >
          <a href="macosa.html" title="38. MacPython OSA Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" >38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��c��b�bhtml/library/getopt.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.6. getopt — C-style parser for command line options &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.7. logging — Logging facility for Python" href="logging.html" />
    <link rel="prev" title="15.5. optparse — Parser for command line options" href="optparse.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/getopt.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="15.7. logging — Logging facility for Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="15.5. optparse — Parser for command line options"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-getopt">
<span id="getopt-c-style-parser-for-command-line-options"></span><h1>15.6. <a class="reference internal" href="#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> — C-style parser for command line options<a class="headerlink" href="#module-getopt" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/getopt.py">Lib/getopt.py</a></p>
<hr class="docutils" />
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module is a parser for command line options whose API is
designed to be familiar to users of the C <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> function. Users who
are unfamiliar with the C <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> function or who would like to write
less code and get better help and error messages should consider using the
<a class="reference internal" href="argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module instead.</p>
</div>
<p>This module helps scripts to parse the command line arguments in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code>.
It supports the same conventions as the Unix <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> function (including
the special meanings of arguments of the form ‘<code class="docutils literal notranslate"><span class="pre">-</span></code>‘ and ‘<code class="docutils literal notranslate"><span class="pre">--</span></code>‘).  Long
options similar to those supported by GNU software may be used as well via an
optional third argument.</p>
<p>This module provides two functions and an
exception:</p>
<dl class="function">
<dt id="getopt.getopt">
<code class="descclassname">getopt.</code><code class="descname">getopt</code><span class="sig-paren">(</span><em>args</em>, <em>options</em><span class="optional">[</span>, <em>long_options</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#getopt.getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses command line options and parameter list.  <em>args</em> is the argument list to
be parsed, without the leading reference to the running program. Typically, this
means <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>. <em>options</em> is the string of option letters that the
script wants to recognize, with options that require an argument followed by a
colon (<code class="docutils literal notranslate"><span class="pre">':'</span></code>; i.e., the same format that Unix <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> uses).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike GNU <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code>, after a non-option argument, all further
arguments are considered also non-options. This is similar to the way
non-GNU Unix systems work.</p>
</div>
<p><em>long_options</em>, if specified, must be a list of strings with the names of the
long options which should be supported.  The leading <code class="docutils literal notranslate"><span class="pre">'--'</span></code>
characters should not be included in the option name.  Long options which
require an argument should be followed by an equal sign (<code class="docutils literal notranslate"><span class="pre">'='</span></code>).  Optional
arguments are not supported.  To accept only long options, <em>options</em> should
be an empty string.  Long options on the command line can be recognized so
long as they provide a prefix of the option name that matches exactly one of
the accepted options.  For example, if <em>long_options</em> is <code class="docutils literal notranslate"><span class="pre">['foo',</span> <span class="pre">'frob']</span></code>,
the option <code class="docutils literal notranslate"><span class="pre">--fo</span></code> will match as <code class="docutils literal notranslate"><span class="pre">--foo</span></code>, but <code class="docutils literal notranslate"><span class="pre">--f</span></code>
will not match uniquely, so <a class="reference internal" href="#getopt.GetoptError" title="getopt.GetoptError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GetoptError</span></code></a> will be raised.</p>
<p>The return value consists of two elements: the first is a list of <code class="docutils literal notranslate"><span class="pre">(option,</span>
<span class="pre">value)</span></code> pairs; the second is the list of program arguments left after the
option list was stripped (this is a trailing slice of <em>args</em>).  Each
option-and-value pair returned has the option as its first element, prefixed
with a hyphen for short options (e.g., <code class="docutils literal notranslate"><span class="pre">'-x'</span></code>) or two hyphens for long
options (e.g., <code class="docutils literal notranslate"><span class="pre">'--long-option'</span></code>), and the option argument as its
second element, or an empty string if the option has no argument.  The
options occur in the list in the same order in which they were found, thus
allowing multiple occurrences.  Long and short options may be mixed.</p>
</dd></dl>

<dl class="function">
<dt id="getopt.gnu_getopt">
<code class="descclassname">getopt.</code><code class="descname">gnu_getopt</code><span class="sig-paren">(</span><em>args</em>, <em>options</em><span class="optional">[</span>, <em>long_options</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#getopt.gnu_getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>This function works like <a class="reference internal" href="#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a>, except that GNU style scanning mode is
used by default. This means that option and non-option arguments may be
intermixed. The <a class="reference internal" href="#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> function stops processing options as soon as a
non-option argument is encountered.</p>
<p>If the first character of the option string is <code class="docutils literal notranslate"><span class="pre">'+'</span></code>, or if the environment
variable <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">POSIXLY_CORRECT</span></code> is set, then option processing stops as
soon as a non-option argument is encountered.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="getopt.GetoptError">
<em class="property">exception </em><code class="descclassname">getopt.</code><code class="descname">GetoptError</code><a class="headerlink" href="#getopt.GetoptError" title="Permalink to this definition">¶</a></dt>
<dd><p>This is raised when an unrecognized option is found in the argument list or when
an option requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error.  For long options, an argument given
to an option which does not require one will also cause this exception to be
raised.  The attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">msg</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">opt</span></code> give the error message and
related option; if there is no specific option to which the exception relates,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">opt</span></code> is an empty string.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 1.6: </span>Introduced <a class="reference internal" href="#getopt.GetoptError" title="getopt.GetoptError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GetoptError</span></code></a> as a synonym for <a class="reference internal" href="#getopt.error" title="getopt.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="getopt.error">
<em class="property">exception </em><code class="descclassname">getopt.</code><code class="descname">error</code><a class="headerlink" href="#getopt.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Alias for <a class="reference internal" href="#getopt.GetoptError" title="getopt.GetoptError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GetoptError</span></code></a>; for backward compatibility.</p>
</dd></dl>

<p>An example using only Unix style options:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">getopt</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="s1">&#39;-a -b -cfoo -d bar a1 a2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;-a&#39;, &#39;-b&#39;, &#39;-cfoo&#39;, &#39;-d&#39;, &#39;bar&#39;, &#39;a1&#39;, &#39;a2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s1">&#39;abc:d:&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span>
<span class="go">[(&#39;-a&#39;, &#39;&#39;), (&#39;-b&#39;, &#39;&#39;), (&#39;-c&#39;, &#39;foo&#39;), (&#39;-d&#39;, &#39;bar&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;a1&#39;, &#39;a2&#39;]</span>
</pre></div>
</div>
<p>Using long option names is equally easy:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;--condition=foo --testing --output-file abc.def -x a1 a2&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;--condition=foo&#39;, &#39;--testing&#39;, &#39;--output-file&#39;, &#39;abc.def&#39;, &#39;-x&#39;, &#39;a1&#39;, &#39;a2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="p">[</span>
<span class="gp">... </span>    <span class="s1">&#39;condition=&#39;</span><span class="p">,</span> <span class="s1">&#39;output-file=&#39;</span><span class="p">,</span> <span class="s1">&#39;testing&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span>
<span class="go">[(&#39;--condition&#39;, &#39;foo&#39;), (&#39;--testing&#39;, &#39;&#39;), (&#39;--output-file&#39;, &#39;abc.def&#39;), (&#39;-x&#39;, &#39;&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;a1&#39;, &#39;a2&#39;]</span>
</pre></div>
</div>
<p>In a script, typical usage is something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">getopt</span><span class="o">,</span> <span class="nn">sys</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="s2">&quot;ho:v&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s2">&quot;help&quot;</span><span class="p">,</span> <span class="s2">&quot;output=&quot;</span><span class="p">])</span>
    <span class="k">except</span> <span class="n">getopt</span><span class="o">.</span><span class="n">GetoptError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
        <span class="c1"># print help information and exit:</span>
        <span class="nb">print</span> <span class="nb">str</span><span class="p">(</span><span class="n">err</span><span class="p">)</span>  <span class="c1"># will print something like &quot;option -a not recognized&quot;</span>
        <span class="n">usage</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
    <span class="n">output</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">verbose</span> <span class="o">=</span> <span class="kc">False</span>
    <span class="k">for</span> <span class="n">o</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">opts</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">o</span> <span class="o">==</span> <span class="s2">&quot;-v&quot;</span><span class="p">:</span>
            <span class="n">verbose</span> <span class="o">=</span> <span class="kc">True</span>
        <span class="k">elif</span> <span class="n">o</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&quot;-h&quot;</span><span class="p">,</span> <span class="s2">&quot;--help&quot;</span><span class="p">):</span>
            <span class="n">usage</span><span class="p">()</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">o</span> <span class="ow">in</span> <span class="p">(</span><span class="s2">&quot;-o&quot;</span><span class="p">,</span> <span class="s2">&quot;--output&quot;</span><span class="p">):</span>
            <span class="n">output</span> <span class="o">=</span> <span class="n">a</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">assert</span> <span class="kc">False</span><span class="p">,</span> <span class="s2">&quot;unhandled option&quot;</span>
    <span class="c1"># ...</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that an equivalent command line interface could be produced with less code
and more informative help and error messages by using the <a class="reference internal" href="argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-o&#39;</span><span class="p">,</span> <span class="s1">&#39;--output&#39;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-v&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;verbose&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">)</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="c1"># ... do something with args.output ...</span>
    <span class="c1"># ... do something with args.verbose ..</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a></dt>
<dd>Alternative command line option and argument parsing library.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="optparse.html"
                        title="previous chapter">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging.html"
                        title="next chapter">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/getopt.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="15.7. logging — Logging facility for Python"
             >next</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="15.5. optparse — Parser for command line options"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�"��,�,html/library/getpass.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.10. getpass — Portable password input &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.11. curses — Terminal handling for character-cell displays" href="curses.html" />
    <link rel="prev" title="15.9. logging.handlers — Logging handlers" href="logging.handlers.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/getpass.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.html" title="15.11. curses — Terminal handling for character-cell displays"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging.handlers.html" title="15.9. logging.handlers — Logging handlers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-getpass">
<span id="getpass-portable-password-input"></span><h1>15.10. <a class="reference internal" href="#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> — Portable password input<a class="headerlink" href="#module-getpass" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> module provides two functions:</p>
<dl class="function">
<dt id="getpass.getpass">
<code class="descclassname">getpass.</code><code class="descname">getpass</code><span class="sig-paren">(</span><span class="optional">[</span><em>prompt</em><span class="optional">[</span>, <em>stream</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#getpass.getpass" title="Permalink to this definition">¶</a></dt>
<dd><p>Prompt the user for a password without echoing.  The user is prompted using the
string <em>prompt</em>, which defaults to <code class="docutils literal notranslate"><span class="pre">'Password:</span> <span class="pre">'</span></code>. On Unix, the prompt is
written to the file-like object <em>stream</em>.  <em>stream</em> defaults to the
controlling terminal (/dev/tty) or if that is unavailable to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>
(this argument is ignored on Windows).</p>
<p>If echo free input is unavailable getpass() falls back to printing
a warning message to <em>stream</em> and reading from <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> and
issuing a <a class="reference internal" href="#getpass.GetPassWarning" title="getpass.GetPassWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GetPassWarning</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>stream</em> parameter was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>On Unix it defaults to using /dev/tty before falling back
to <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you call getpass from within IDLE, the input may be done in the
terminal you launched IDLE from rather than the idle window itself.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="getpass.GetPassWarning">
<em class="property">exception </em><code class="descclassname">getpass.</code><code class="descname">GetPassWarning</code><a class="headerlink" href="#getpass.GetPassWarning" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="exceptions.html#exceptions.UserWarning" title="exceptions.UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a> subclass issued when password input may be echoed.</p>
</dd></dl>

<dl class="function">
<dt id="getpass.getuser">
<code class="descclassname">getpass.</code><code class="descname">getuser</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#getpass.getuser" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the “login name” of the user.</p>
<p>This function checks the environment variables <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LOGNAME</span></code>,
<span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">USER</span></code>, <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LNAME</span></code> and <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">USERNAME</span></code>, in order, and returns
the value of the first one which is set to a non-empty string.  If none are set,
the login name from the password database is returned on systems which support
the <a class="reference internal" href="pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a> module, otherwise, an exception is raised.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="logging.handlers.html"
                        title="previous chapter">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="curses.html"
                        title="next chapter">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/getpass.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="curses.html" title="15.11. curses — Terminal handling for character-cell displays"
             >next</a> |</li>
        <li class="right" >
          <a href="logging.handlers.html" title="15.9. logging.handlers — Logging handlers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��i�K�Khtml/library/gettext.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>22.1. gettext — Multilingual internationalization services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="22.2. locale — Internationalization services" href="locale.html" />
    <link rel="prev" title="22. Internationalization" href="i18n.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gettext.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="locale.html" title="22.2. locale — Internationalization services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="i18n.html" title="22. Internationalization"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="i18n.html" accesskey="U">22. Internationalization</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gettext">
<span id="gettext-multilingual-internationalization-services"></span><h1>22.1. <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> — Multilingual internationalization services<a class="headerlink" href="#module-gettext" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/gettext.py">Lib/gettext.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module provides internationalization (I18N) and localization
(L10N) services for your Python modules and applications. It supports both the
GNU <code class="docutils literal notranslate"><span class="pre">gettext</span></code> message catalog API and a higher level, class-based API that may
be more appropriate for Python files.  The interface described below allows you
to write your module and application messages in one natural language, and
provide a catalog of translated messages for running under different natural
languages.</p>
<p>Some hints on localizing your Python modules and applications are also given.</p>
<div class="section" id="gnu-gettext-api">
<h2>22.1.1. GNU <strong class="program">gettext</strong> API<a class="headerlink" href="#gnu-gettext-api" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module defines the following API, which is very similar to
the GNU <strong class="program">gettext</strong> API.  If you use this API you will affect the
translation of your entire application globally.  Often this is what you want if
your application is monolingual, with the choice of language dependent on the
locale of your user.  If you are localizing a Python module, or if your
application needs to switch languages on the fly, you probably want to use the
class-based API instead.</p>
<dl class="function">
<dt id="gettext.bindtextdomain">
<code class="descclassname">gettext.</code><code class="descname">bindtextdomain</code><span class="sig-paren">(</span><em>domain</em><span class="optional">[</span>, <em>localedir</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.bindtextdomain" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind the <em>domain</em> to the locale directory <em>localedir</em>.  More concretely,
<a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> will look for binary <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> files for the given domain using
the path (on Unix): <code class="file docutils literal notranslate"><span class="pre">localedir/language/LC_MESSAGES/domain.mo</span></code>, where
<em>languages</em> is searched for in the environment variables <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANGUAGE</span></code>,
<span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LC_ALL</span></code>, <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LC_MESSAGES</span></code>, and <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANG</span></code> respectively.</p>
<p>If <em>localedir</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, then the current binding for <em>domain</em> is
returned. <a class="footnote-reference" href="#id6" id="id1">[1]</a></p>
</dd></dl>

<dl class="function">
<dt id="gettext.bind_textdomain_codeset">
<code class="descclassname">gettext.</code><code class="descname">bind_textdomain_codeset</code><span class="sig-paren">(</span><em>domain</em><span class="optional">[</span>, <em>codeset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.bind_textdomain_codeset" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind the <em>domain</em> to <em>codeset</em>, changing the encoding of strings returned by the
<a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a> family of functions. If <em>codeset</em> is omitted, then the current
binding is returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.textdomain">
<code class="descclassname">gettext.</code><code class="descname">textdomain</code><span class="sig-paren">(</span><span class="optional">[</span><em>domain</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.textdomain" title="Permalink to this definition">¶</a></dt>
<dd><p>Change or query the current global domain.  If <em>domain</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then the
current global domain is returned, otherwise the global domain is set to
<em>domain</em>, which is returned.</p>
</dd></dl>

<dl class="function">
<dt id="gettext.gettext">
<code class="descclassname">gettext.</code><code class="descname">gettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.gettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the localized translation of <em>message</em>, based on the current global
domain, language, and locale directory.  This function is usually aliased as
<code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> in the local namespace (see examples below).</p>
</dd></dl>

<dl class="function">
<dt id="gettext.lgettext">
<code class="descclassname">gettext.</code><code class="descname">lgettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.lgettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a>, but the translation is returned in the preferred
system encoding, if no other encoding was explicitly set with
<a class="reference internal" href="#gettext.bind_textdomain_codeset" title="gettext.bind_textdomain_codeset"><code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.dgettext">
<code class="descclassname">gettext.</code><code class="descname">dgettext</code><span class="sig-paren">(</span><em>domain</em>, <em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.dgettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a>, but look the message up in the specified <em>domain</em>.</p>
</dd></dl>

<dl class="function">
<dt id="gettext.ldgettext">
<code class="descclassname">gettext.</code><code class="descname">ldgettext</code><span class="sig-paren">(</span><em>domain</em>, <em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.ldgettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#gettext.dgettext" title="gettext.dgettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">dgettext()</span></code></a>, but the translation is returned in the preferred
system encoding, if no other encoding was explicitly set with
<a class="reference internal" href="#gettext.bind_textdomain_codeset" title="gettext.bind_textdomain_codeset"><code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.ngettext">
<code class="descclassname">gettext.</code><code class="descname">ngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.ngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a>, but consider plural forms. If a translation is found,
apply the plural formula to <em>n</em>, and return the resulting message (some
languages have more than two plural forms). If no translation is found, return
<em>singular</em> if <em>n</em> is 1; return <em>plural</em> otherwise.</p>
<p>The Plural formula is taken from the catalog header. It is a C or Python
expression that has a free variable <em>n</em>; the expression evaluates to the index
of the plural in the catalog. See the GNU gettext documentation for the precise
syntax to be used in <code class="file docutils literal notranslate"><span class="pre">.po</span></code> files and the formulas for a variety of
languages.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.lngettext">
<code class="descclassname">gettext.</code><code class="descname">lngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.lngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#gettext.ngettext" title="gettext.ngettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">ngettext()</span></code></a>, but the translation is returned in the preferred
system encoding, if no other encoding was explicitly set with
<a class="reference internal" href="#gettext.bind_textdomain_codeset" title="gettext.bind_textdomain_codeset"><code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.dngettext">
<code class="descclassname">gettext.</code><code class="descname">dngettext</code><span class="sig-paren">(</span><em>domain</em>, <em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.dngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#gettext.ngettext" title="gettext.ngettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">ngettext()</span></code></a>, but look the message up in the specified <em>domain</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.ldngettext">
<code class="descclassname">gettext.</code><code class="descname">ldngettext</code><span class="sig-paren">(</span><em>domain</em>, <em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.ldngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#gettext.dngettext" title="gettext.dngettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">dngettext()</span></code></a>, but the translation is returned in the
preferred system encoding, if no other encoding was explicitly set with
<a class="reference internal" href="#gettext.bind_textdomain_codeset" title="gettext.bind_textdomain_codeset"><code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Note that GNU <strong class="program">gettext</strong> also defines a <code class="xref py py-func docutils literal notranslate"><span class="pre">dcgettext()</span></code> method, but
this was deemed not useful and so it is currently unimplemented.</p>
<p>Here’s an example of typical usage for this API:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">gettext</span><span class="o">.</span><span class="n">bindtextdomain</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">,</span> <span class="s1">&#39;/path/to/my/language/directory&#39;</span><span class="p">)</span>
<span class="n">gettext</span><span class="o">.</span><span class="n">textdomain</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">gettext</span>
<span class="c1"># ...</span>
<span class="nb">print</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;This is a translatable string.&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="class-based-api">
<h2>22.1.2. Class-based API<a class="headerlink" href="#class-based-api" title="Permalink to this headline">¶</a></h2>
<p>The class-based API of the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module gives you more flexibility and
greater convenience than the GNU <strong class="program">gettext</strong> API.  It is the recommended
way of localizing your Python applications and modules.  <code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code> defines
a “translations” class which implements the parsing of GNU <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> format
files, and has methods for returning either standard 8-bit strings or Unicode
strings. Instances of this “translations” class can also install themselves  in
the built-in namespace as the function <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>.</p>
<dl class="function">
<dt id="gettext.find">
<code class="descclassname">gettext.</code><code class="descname">find</code><span class="sig-paren">(</span><em>domain</em><span class="optional">[</span>, <em>localedir</em><span class="optional">[</span>, <em>languages</em><span class="optional">[</span>, <em>all</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.find" title="Permalink to this definition">¶</a></dt>
<dd><p>This function implements the standard <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file search algorithm.  It
takes a <em>domain</em>, identical to what <a class="reference internal" href="#gettext.textdomain" title="gettext.textdomain"><code class="xref py py-func docutils literal notranslate"><span class="pre">textdomain()</span></code></a> takes.  Optional
<em>localedir</em> is as in <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code class="xref py py-func docutils literal notranslate"><span class="pre">bindtextdomain()</span></code></a>  Optional <em>languages</em> is a list of
strings, where each string is a language code.</p>
<p>If <em>localedir</em> is not given, then the default system locale directory is used.
<a class="footnote-reference" href="#id7" id="id2">[2]</a>  If <em>languages</em> is not given, then the following environment variables are
searched: <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANGUAGE</span></code>, <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LC_ALL</span></code>, <span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LC_MESSAGES</span></code>, and
<span class="target" id="index-7"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANG</span></code>.  The first one returning a non-empty value is used for the
<em>languages</em> variable. The environment variables should contain a colon separated
list of languages, which will be split on the colon to produce the expected list
of language code strings.</p>
<p><a class="reference internal" href="#gettext.find" title="gettext.find"><code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code></a> then expands and normalizes the languages, and then iterates
through them, searching for an existing file built of these components:</p>
<p><code class="file docutils literal notranslate"><span class="pre">localedir/language/LC_MESSAGES/domain.mo</span></code></p>
<p>The first such file name that exists is returned by <a class="reference internal" href="#gettext.find" title="gettext.find"><code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code></a>. If no such
file is found, then <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned. If <em>all</em> is given, it returns a list
of all file names, in the order in which they appear in the languages list or
the environment variables.</p>
</dd></dl>

<dl class="function">
<dt id="gettext.translation">
<code class="descclassname">gettext.</code><code class="descname">translation</code><span class="sig-paren">(</span><em>domain</em><span class="optional">[</span>, <em>localedir</em><span class="optional">[</span>, <em>languages</em><span class="optional">[</span>, <em>class_</em><span class="optional">[</span>, <em>fallback</em><span class="optional">[</span>, <em>codeset</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.translation" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Translations</span></code> instance based on the <em>domain</em>, <em>localedir</em>, and
<em>languages</em>, which are first passed to <a class="reference internal" href="#gettext.find" title="gettext.find"><code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code></a> to get a list of the
associated <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file paths.  Instances with identical <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file
names are cached.  The actual class instantiated is either <em>class_</em> if provided,
otherwise <code class="xref py py-class docutils literal notranslate"><span class="pre">GNUTranslations</span></code>.  The class’s constructor must take a single
file object argument. If provided, <em>codeset</em> will change the charset used to
encode translated strings.</p>
<p>If multiple files are found, later files are used as fallbacks for earlier ones.
To allow setting the fallback, <a class="reference internal" href="copy.html#copy.copy" title="copy.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.copy()</span></code></a> is used to clone each
translation object from the cache; the actual instance data is still shared with
the cache.</p>
<p>If no <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file is found, this function raises <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if
<em>fallback</em> is false (which is the default), and returns a
<a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullTranslations</span></code></a> instance if <em>fallback</em> is true.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Added the <em>codeset</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="gettext.install">
<code class="descclassname">gettext.</code><code class="descname">install</code><span class="sig-paren">(</span><em>domain</em><span class="optional">[</span>, <em>localedir</em><span class="optional">[</span>, <em>unicode</em><span class="optional">[</span>, <em>codeset</em><span class="optional">[</span>, <em>names</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.install" title="Permalink to this definition">¶</a></dt>
<dd><p>This installs the function <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> in Python’s builtins namespace, based on
<em>domain</em>, <em>localedir</em>, and <em>codeset</em> which are passed to the function
<a class="reference internal" href="#gettext.translation" title="gettext.translation"><code class="xref py py-func docutils literal notranslate"><span class="pre">translation()</span></code></a>.  The <em>unicode</em> flag is passed to the resulting translation
object’s <a class="reference internal" href="#gettext.NullTranslations.install" title="gettext.NullTranslations.install"><code class="xref py py-meth docutils literal notranslate"><span class="pre">install()</span></code></a> method.</p>
<p>For the <em>names</em> parameter, please see the description of the translation
object’s <a class="reference internal" href="#gettext.NullTranslations.install" title="gettext.NullTranslations.install"><code class="xref py py-meth docutils literal notranslate"><span class="pre">install()</span></code></a> method.</p>
<p>As seen below, you usually mark the strings in your application that are
candidates for translation, by wrapping them in a call to the <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>
function, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;This string will be translated.&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>For convenience, you want the <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> function to be installed in Python’s
builtins namespace, so it is easily accessible in all modules of your
application.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Added the <em>codeset</em> parameter.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>names</em> parameter.</p>
</div>
</dd></dl>

<div class="section" id="the-nulltranslations-class">
<h3>22.1.2.1. The <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullTranslations</span></code></a> class<a class="headerlink" href="#the-nulltranslations-class" title="Permalink to this headline">¶</a></h3>
<p>Translation classes are what actually implement the translation of original
source file message strings to translated message strings. The base class used
by all translation classes is <a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullTranslations</span></code></a>; this provides the basic
interface you can use to write your own specialized translation classes.  Here
are the methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">NullTranslations</span></code>:</p>
<dl class="class">
<dt id="gettext.NullTranslations">
<em class="property">class </em><code class="descclassname">gettext.</code><code class="descname">NullTranslations</code><span class="sig-paren">(</span><span class="optional">[</span><em>fp</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations" title="Permalink to this definition">¶</a></dt>
<dd><p>Takes an optional file object <em>fp</em>, which is ignored by the base class.
Initializes “protected” instance variables <em>_info</em> and <em>_charset</em> which are set
by derived classes, as well as <em>_fallback</em>, which is set through
<a class="reference internal" href="#gettext.NullTranslations.add_fallback" title="gettext.NullTranslations.add_fallback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_fallback()</span></code></a>.  It then calls <code class="docutils literal notranslate"><span class="pre">self._parse(fp)</span></code> if <em>fp</em> is not
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<dl class="method">
<dt id="gettext.NullTranslations._parse">
<code class="descname">_parse</code><span class="sig-paren">(</span><em>fp</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations._parse" title="Permalink to this definition">¶</a></dt>
<dd><p>No-op’d in the base class, this method takes file object <em>fp</em>, and reads
the data from the file, initializing its message catalog.  If you have an
unsupported message catalog file format, you should override this method
to parse your format.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.add_fallback">
<code class="descname">add_fallback</code><span class="sig-paren">(</span><em>fallback</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.add_fallback" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>fallback</em> as the fallback object for the current translation
object. A translation object should consult the fallback if it cannot provide a
translation for a given message.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.gettext">
<code class="descname">gettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.gettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">gettext()</span></code> to the
fallback. Otherwise, return the translated message.  Overridden in derived
classes.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.lgettext">
<code class="descname">lgettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.lgettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">lgettext()</span></code> to the
fallback. Otherwise, return the translated message.  Overridden in derived
classes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.ugettext">
<code class="descname">ugettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.ugettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">ugettext()</span></code> to the
fallback. Otherwise, return the translated message as a Unicode
string. Overridden in derived classes.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.ngettext">
<code class="descname">ngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.ngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">ngettext()</span></code> to the
fallback. Otherwise, return the translated message.  Overridden in derived
classes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.lngettext">
<code class="descname">lngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.lngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">lngettext()</span></code> to the
fallback. Otherwise, return the translated message.  Overridden in derived
classes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.ungettext">
<code class="descname">ungettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.ungettext" title="Permalink to this definition">¶</a></dt>
<dd><p>If a fallback has been set, forward <code class="xref py py-meth docutils literal notranslate"><span class="pre">ungettext()</span></code> to the fallback.
Otherwise, return the translated message as a Unicode string. Overridden
in derived classes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.info">
<code class="descname">info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.info" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the “protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_info</span></code> variable.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.charset">
<code class="descname">charset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the “protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_charset</span></code> variable.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.output_charset">
<code class="descname">output_charset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.output_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the “protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_output_charset</span></code> variable, which defines the
encoding used to return translated messages.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.set_output_charset">
<code class="descname">set_output_charset</code><span class="sig-paren">(</span><em>charset</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.set_output_charset" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the “protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_output_charset</span></code> variable, which defines the
encoding used to return translated messages.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.NullTranslations.install">
<code class="descname">install</code><span class="sig-paren">(</span><span class="optional">[</span><em>unicode</em><span class="optional">[</span>, <em>names</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gettext.NullTranslations.install" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>unicode</em> flag is false, this method installs <code class="xref py py-meth docutils literal notranslate"><span class="pre">self.gettext()</span></code>
into the built-in namespace, binding it to <code class="docutils literal notranslate"><span class="pre">_</span></code>.  If <em>unicode</em> is true,
it binds <code class="xref py py-meth docutils literal notranslate"><span class="pre">self.ugettext()</span></code> instead.  By default, <em>unicode</em> is false.</p>
<p>If the <em>names</em> parameter is given, it must be a sequence containing the
names of functions you want to install in the builtins namespace in
addition to <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>.  Supported names are <code class="docutils literal notranslate"><span class="pre">'gettext'</span></code> (bound to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">self.gettext()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">self.ugettext()</span></code> according to the <em>unicode</em>
flag), <code class="docutils literal notranslate"><span class="pre">'ngettext'</span></code> (bound to <code class="xref py py-meth docutils literal notranslate"><span class="pre">self.ngettext()</span></code> or
<code class="xref py py-meth docutils literal notranslate"><span class="pre">self.ungettext()</span></code> according to the <em>unicode</em> flag), <code class="docutils literal notranslate"><span class="pre">'lgettext'</span></code>
and <code class="docutils literal notranslate"><span class="pre">'lngettext'</span></code>.</p>
<p>Note that this is only one way, albeit the most convenient way, to make
the <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> function available to your application.  Because it affects
the entire application globally, and specifically the built-in namespace,
localized modules should never install <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>. Instead, they should use
this code to make <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> available to their module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;mymodule&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">gettext</span>
</pre></div>
</div>
<p>This puts <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> only in the module’s global namespace and so only
affects calls within this module.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>names</em> parameter.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="the-gnutranslations-class">
<h3>22.1.2.2. The <code class="xref py py-class docutils literal notranslate"><span class="pre">GNUTranslations</span></code> class<a class="headerlink" href="#the-gnutranslations-class" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module provides one additional class derived from
<a class="reference internal" href="#gettext.NullTranslations" title="gettext.NullTranslations"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullTranslations</span></code></a>: <code class="xref py py-class docutils literal notranslate"><span class="pre">GNUTranslations</span></code>.  This class overrides
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_parse()</span></code> to enable reading GNU <strong class="program">gettext</strong> format <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> files
in both big-endian and little-endian format. It also coerces both message ids
and message strings to Unicode.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">GNUTranslations</span></code> parses optional meta-data out of the translation
catalog.  It is convention with GNU <strong class="program">gettext</strong> to include meta-data as
the translation for the empty string.  This meta-data is in <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>-style
<code class="docutils literal notranslate"><span class="pre">key:</span> <span class="pre">value</span></code> pairs, and should contain the <code class="docutils literal notranslate"><span class="pre">Project-Id-Version</span></code> key.  If the
key <code class="docutils literal notranslate"><span class="pre">Content-Type</span></code> is found, then the <code class="docutils literal notranslate"><span class="pre">charset</span></code> property is used to
initialize the “protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_charset</span></code> instance variable, defaulting to
<code class="docutils literal notranslate"><span class="pre">None</span></code> if not found.  If the charset encoding is specified, then all message
ids and message strings read from the catalog are converted to Unicode using
this encoding.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">ugettext()</span></code> method always returns a Unicode, while the
<a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettext()</span></code></a> returns an encoded 8-bit string.  For the message id arguments
of both methods, either Unicode strings or 8-bit strings containing only
US-ASCII characters are acceptable.  Note that the Unicode version of the
methods (i.e. <code class="xref py py-meth docutils literal notranslate"><span class="pre">ugettext()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">ungettext()</span></code>) are the recommended
interface to use for internationalized Python programs.</p>
<p>The entire set of key/value pairs are placed into a dictionary and set as the
“protected” <code class="xref py py-attr docutils literal notranslate"><span class="pre">_info</span></code> instance variable.</p>
<p>If the <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file’s magic number is invalid, or if other problems occur
while reading the file, instantiating a <code class="xref py py-class docutils literal notranslate"><span class="pre">GNUTranslations</span></code> class can raise
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
<p>The following methods are overridden from the base class implementation:</p>
<dl class="method">
<dt id="gettext.GNUTranslations.gettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">gettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.gettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the <em>message</em> id in the catalog and return the corresponding message
string, as an 8-bit string encoded with the catalog’s charset encoding, if
known.  If there is no entry in the catalog for the <em>message</em> id, and a fallback
has been set, the look up is forwarded to the fallback’s <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettext()</span></code></a> method.
Otherwise, the <em>message</em> id is returned.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.GNUTranslations.lgettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">lgettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.lgettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettext()</span></code></a>, but the translation is returned in the preferred
system encoding, if no other encoding was explicitly set with
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_output_charset()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.GNUTranslations.ugettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">ugettext</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.ugettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up the <em>message</em> id in the catalog and return the corresponding message
string, as a Unicode string.  If there is no entry in the catalog for the
<em>message</em> id, and a fallback has been set, the look up is forwarded to the
fallback’s <a class="reference internal" href="#gettext.GNUTranslations.ugettext" title="gettext.GNUTranslations.ugettext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ugettext()</span></code></a> method.  Otherwise, the <em>message</em> id is returned.</p>
</dd></dl>

<dl class="method">
<dt id="gettext.GNUTranslations.ngettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">ngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.ngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Do a plural-forms lookup of a message id.  <em>singular</em> is used as the message id
for purposes of lookup in the catalog, while <em>n</em> is used to determine which
plural form to use.  The returned message string is an 8-bit string encoded with
the catalog’s charset encoding, if known.</p>
<p>If the message id is not found in the catalog, and a fallback is specified, the
request is forwarded to the fallback’s <a class="reference internal" href="#gettext.ngettext" title="gettext.ngettext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ngettext()</span></code></a> method.  Otherwise, when
<em>n</em> is 1 <em>singular</em> is returned, and <em>plural</em> is returned in all other cases.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.GNUTranslations.lngettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">lngettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.lngettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettext()</span></code></a>, but the translation is returned in the preferred
system encoding, if no other encoding was explicitly set with
<code class="xref py py-meth docutils literal notranslate"><span class="pre">set_output_charset()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="gettext.GNUTranslations.ungettext">
<code class="descclassname">GNUTranslations.</code><code class="descname">ungettext</code><span class="sig-paren">(</span><em>singular</em>, <em>plural</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gettext.GNUTranslations.ungettext" title="Permalink to this definition">¶</a></dt>
<dd><p>Do a plural-forms lookup of a message id.  <em>singular</em> is used as the message id
for purposes of lookup in the catalog, while <em>n</em> is used to determine which
plural form to use.  The returned message string is a Unicode string.</p>
<p>If the message id is not found in the catalog, and a fallback is specified, the
request is forwarded to the fallback’s <a class="reference internal" href="#gettext.GNUTranslations.ungettext" title="gettext.GNUTranslations.ungettext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ungettext()</span></code></a> method.  Otherwise,
when <em>n</em> is 1 <em>singular</em> is returned, and <em>plural</em> is returned in all other
cases.</p>
<p>Here is an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">))</span>
<span class="n">cat</span> <span class="o">=</span> <span class="n">GNUTranslations</span><span class="p">(</span><span class="n">somefile</span><span class="p">)</span>
<span class="n">message</span> <span class="o">=</span> <span class="n">cat</span><span class="o">.</span><span class="n">ungettext</span><span class="p">(</span>
    <span class="s1">&#39;There is </span><span class="si">%(num)d</span><span class="s1"> file in this directory&#39;</span><span class="p">,</span>
    <span class="s1">&#39;There are </span><span class="si">%(num)d</span><span class="s1"> files in this directory&#39;</span><span class="p">,</span>
    <span class="n">n</span><span class="p">)</span> <span class="o">%</span> <span class="p">{</span><span class="s1">&#39;num&#39;</span><span class="p">:</span> <span class="n">n</span><span class="p">}</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="solaris-message-catalog-support">
<h3>22.1.2.3. Solaris message catalog support<a class="headerlink" href="#solaris-message-catalog-support" title="Permalink to this headline">¶</a></h3>
<p>The Solaris operating system defines its own binary <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> file format, but
since no documentation can be found on this format, it is not supported at this
time.</p>
</div>
<div class="section" id="the-catalog-constructor">
<h3>22.1.2.4. The Catalog constructor<a class="headerlink" href="#the-catalog-constructor" title="Permalink to this headline">¶</a></h3>
<p id="index-9">GNOME uses a version of the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module by James Henstridge, but this
version has a slightly different API.  Its documented usage was:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">cat</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">Catalog</span><span class="p">(</span><span class="n">domain</span><span class="p">,</span> <span class="n">localedir</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">cat</span><span class="o">.</span><span class="n">gettext</span>
<span class="nb">print</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;hello world&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>For compatibility with this older module, the function <code class="xref py py-func docutils literal notranslate"><span class="pre">Catalog()</span></code> is an
alias for the <a class="reference internal" href="#gettext.translation" title="gettext.translation"><code class="xref py py-func docutils literal notranslate"><span class="pre">translation()</span></code></a> function described above.</p>
<p>One difference between this module and Henstridge’s: his catalog objects
supported access through a mapping API, but this appears to be unused and so is
not currently supported.</p>
</div>
</div>
<div class="section" id="internationalizing-your-programs-and-modules">
<h2>22.1.3. Internationalizing your programs and modules<a class="headerlink" href="#internationalizing-your-programs-and-modules" title="Permalink to this headline">¶</a></h2>
<p>Internationalization (I18N) refers to the operation by which a program is made
aware of multiple languages.  Localization (L10N) refers to the adaptation of
your program, once internationalized, to the local language and cultural habits.
In order to provide multilingual messages for your Python programs, you need to
take the following steps:</p>
<ol class="arabic simple">
<li>prepare your program or module by specially marking translatable strings</li>
<li>run a suite of tools over your marked files to generate raw messages catalogs</li>
<li>create language specific translations of the message catalogs</li>
<li>use the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module so that message strings are properly translated</li>
</ol>
<p>In order to prepare your code for I18N, you need to look at all the strings in
your files.  Any string that needs to be translated should be marked by wrapping
it in <code class="docutils literal notranslate"><span class="pre">_('...')</span></code> — that is, a call to the function <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">filename</span> <span class="o">=</span> <span class="s1">&#39;mylog.txt&#39;</span>
<span class="n">message</span> <span class="o">=</span> <span class="n">_</span><span class="p">(</span><span class="s1">&#39;writing a log message&#39;</span><span class="p">)</span>
<span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
<span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, the string <code class="docutils literal notranslate"><span class="pre">'writing</span> <span class="pre">a</span> <span class="pre">log</span> <span class="pre">message'</span></code> is marked as a candidate
for translation, while the strings <code class="docutils literal notranslate"><span class="pre">'mylog.txt'</span></code> and <code class="docutils literal notranslate"><span class="pre">'w'</span></code> are not.</p>
<p>The Python distribution comes with two tools which help you generate the message
catalogs once you’ve prepared your source code.  These may or may not be
available from a binary distribution, but they can be found in a source
distribution, in the <code class="file docutils literal notranslate"><span class="pre">Tools/i18n</span></code> directory.</p>
<p>The <strong class="program">pygettext</strong> <a class="footnote-reference" href="#id8" id="id3">[3]</a> program scans all your Python source code looking
for the strings you previously marked as translatable.  It is similar to the GNU
<strong class="program">gettext</strong> program except that it understands all the intricacies of
Python source code, but knows nothing about C or C++ source code.  You don’t
need GNU <code class="docutils literal notranslate"><span class="pre">gettext</span></code> unless you’re also going to be translating C code (such as
C extension modules).</p>
<p><strong class="program">pygettext</strong> generates textual Uniforum-style human readable message
catalog <code class="file docutils literal notranslate"><span class="pre">.pot</span></code> files, essentially structured human readable files which
contain every marked string in the source code, along with a placeholder for the
translation strings. <strong class="program">pygettext</strong> is a command line script that supports
a similar command line interface as <strong class="program">xgettext</strong>; for details on its use,
run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pygettext</span><span class="o">.</span><span class="n">py</span> <span class="o">--</span><span class="n">help</span>
</pre></div>
</div>
<p>Copies of these <code class="file docutils literal notranslate"><span class="pre">.pot</span></code> files are then handed over to the individual human
translators who write language-specific versions for every supported natural
language.  They send you back the filled in language-specific versions as a
<code class="file docutils literal notranslate"><span class="pre">.po</span></code> file.  Using the <strong class="program">msgfmt.py</strong> <a class="footnote-reference" href="#id9" id="id4">[4]</a> program (in the
<code class="file docutils literal notranslate"><span class="pre">Tools/i18n</span></code> directory), you take the <code class="file docutils literal notranslate"><span class="pre">.po</span></code> files from your
translators and generate the machine-readable <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> binary catalog files.
The <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> files are what the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module uses for the actual
translation processing during run-time.</p>
<p>How you use the <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module in your code depends on whether you are
internationalizing a single module or your entire application. The next two
sections will discuss each case.</p>
<div class="section" id="localizing-your-module">
<h3>22.1.3.1. Localizing your module<a class="headerlink" href="#localizing-your-module" title="Permalink to this headline">¶</a></h3>
<p>If you are localizing your module, you must take care not to make global
changes, e.g. to the built-in namespace.  You should not use the GNU <code class="docutils literal notranslate"><span class="pre">gettext</span></code>
API but instead the class-based API.</p>
<p>Let’s say your module is called “spam” and the module’s various natural language
translation <code class="file docutils literal notranslate"><span class="pre">.mo</span></code> files reside in <code class="file docutils literal notranslate"><span class="pre">/usr/share/locale</span></code> in GNU
<strong class="program">gettext</strong> format.  Here’s what you would put at the top of your
module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;/usr/share/locale&#39;</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">lgettext</span>
</pre></div>
</div>
<p>If your translators were providing you with Unicode strings in their <code class="file docutils literal notranslate"><span class="pre">.po</span></code>
files, you’d instead do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;/usr/share/locale&#39;</span><span class="p">)</span>
<span class="n">_</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">ugettext</span>
</pre></div>
</div>
</div>
<div class="section" id="localizing-your-application">
<h3>22.1.3.2. Localizing your application<a class="headerlink" href="#localizing-your-application" title="Permalink to this headline">¶</a></h3>
<p>If you are localizing your application, you can install the <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> function
globally into the built-in namespace, usually in the main driver file of your
application.  This will let all your application-specific files just use
<code class="docutils literal notranslate"><span class="pre">_('...')</span></code> without having to explicitly install it in each file.</p>
<p>In the simple case then, you need only add the following bit of code to the main
driver file of your application:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">gettext</span><span class="o">.</span><span class="n">install</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you need to set the locale directory or the <em>unicode</em> flag, you can pass
these into the <a class="reference internal" href="#gettext.install" title="gettext.install"><code class="xref py py-func docutils literal notranslate"><span class="pre">install()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>
<span class="n">gettext</span><span class="o">.</span><span class="n">install</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">,</span> <span class="s1">&#39;/usr/share/locale&#39;</span><span class="p">,</span> <span class="n">unicode</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="changing-languages-on-the-fly">
<h3>22.1.3.3. Changing languages on the fly<a class="headerlink" href="#changing-languages-on-the-fly" title="Permalink to this headline">¶</a></h3>
<p>If your program needs to support many languages at the same time, you may want
to create multiple translation instances and then switch between them
explicitly, like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gettext</span>

<span class="n">lang1</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">,</span> <span class="n">languages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;en&#39;</span><span class="p">])</span>
<span class="n">lang2</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">,</span> <span class="n">languages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;fr&#39;</span><span class="p">])</span>
<span class="n">lang3</span> <span class="o">=</span> <span class="n">gettext</span><span class="o">.</span><span class="n">translation</span><span class="p">(</span><span class="s1">&#39;myapplication&#39;</span><span class="p">,</span> <span class="n">languages</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;de&#39;</span><span class="p">])</span>

<span class="c1"># start by using language1</span>
<span class="n">lang1</span><span class="o">.</span><span class="n">install</span><span class="p">()</span>

<span class="c1"># ... time goes by, user selects language 2</span>
<span class="n">lang2</span><span class="o">.</span><span class="n">install</span><span class="p">()</span>

<span class="c1"># ... more time goes by, user selects language 3</span>
<span class="n">lang3</span><span class="o">.</span><span class="n">install</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="deferred-translations">
<h3>22.1.3.4. Deferred translations<a class="headerlink" href="#deferred-translations" title="Permalink to this headline">¶</a></h3>
<p>In most coding situations, strings are translated where they are coded.
Occasionally however, you need to mark strings for translation, but defer actual
translation until later.  A classic example is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">animals</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;mollusk&#39;</span><span class="p">,</span>
           <span class="s1">&#39;albatross&#39;</span><span class="p">,</span>
           <span class="s1">&#39;rat&#39;</span><span class="p">,</span>
           <span class="s1">&#39;penguin&#39;</span><span class="p">,</span>
           <span class="s1">&#39;python&#39;</span><span class="p">,</span> <span class="p">]</span>
<span class="c1"># ...</span>
<span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">animals</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">a</span>
</pre></div>
</div>
<p>Here, you want to mark the strings in the <code class="docutils literal notranslate"><span class="pre">animals</span></code> list as being
translatable, but you don’t actually want to translate them until they are
printed.</p>
<p>Here is one way you can handle this situation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">_</span><span class="p">(</span><span class="n">message</span><span class="p">):</span> <span class="k">return</span> <span class="n">message</span>

<span class="n">animals</span> <span class="o">=</span> <span class="p">[</span><span class="n">_</span><span class="p">(</span><span class="s1">&#39;mollusk&#39;</span><span class="p">),</span>
           <span class="n">_</span><span class="p">(</span><span class="s1">&#39;albatross&#39;</span><span class="p">),</span>
           <span class="n">_</span><span class="p">(</span><span class="s1">&#39;rat&#39;</span><span class="p">),</span>
           <span class="n">_</span><span class="p">(</span><span class="s1">&#39;penguin&#39;</span><span class="p">),</span>
           <span class="n">_</span><span class="p">(</span><span class="s1">&#39;python&#39;</span><span class="p">),</span> <span class="p">]</span>

<span class="k">del</span> <span class="n">_</span>

<span class="c1"># ...</span>
<span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">animals</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">_</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
</pre></div>
</div>
<p>This works because the dummy definition of <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> simply returns the string
unchanged.  And this dummy definition will temporarily override any definition
of <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> in the built-in namespace (until the <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> command). Take
care, though if you have a previous definition of <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> in the local
namespace.</p>
<p>Note that the second use of <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code> will not identify “a” as being
translatable to the <strong class="program">pygettext</strong> program, since it is not a string.</p>
<p>Another way to handle this is with the following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">N_</span><span class="p">(</span><span class="n">message</span><span class="p">):</span> <span class="k">return</span> <span class="n">message</span>

<span class="n">animals</span> <span class="o">=</span> <span class="p">[</span><span class="n">N_</span><span class="p">(</span><span class="s1">&#39;mollusk&#39;</span><span class="p">),</span>
           <span class="n">N_</span><span class="p">(</span><span class="s1">&#39;albatross&#39;</span><span class="p">),</span>
           <span class="n">N_</span><span class="p">(</span><span class="s1">&#39;rat&#39;</span><span class="p">),</span>
           <span class="n">N_</span><span class="p">(</span><span class="s1">&#39;penguin&#39;</span><span class="p">),</span>
           <span class="n">N_</span><span class="p">(</span><span class="s1">&#39;python&#39;</span><span class="p">),</span> <span class="p">]</span>

<span class="c1"># ...</span>
<span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">animals</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">_</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
</pre></div>
</div>
<p>In this case, you are marking translatable strings with the function <code class="xref py py-func docutils literal notranslate"><span class="pre">N_()</span></code>,
<a class="footnote-reference" href="#id10" id="id5">[5]</a> which won’t conflict with any definition of <code class="xref py py-func docutils literal notranslate"><span class="pre">_()</span></code>.  However, you will
need to teach your message extraction program to look for translatable strings
marked with <code class="xref py py-func docutils literal notranslate"><span class="pre">N_()</span></code>. <strong class="program">pygettext</strong> and <strong class="program">xpot</strong> both support
this through the use of command line switches.</p>
</div>
<div class="section" id="gettext-vs-lgettext">
<h3>22.1.3.5. <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a> vs. <a class="reference internal" href="#gettext.lgettext" title="gettext.lgettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">lgettext()</span></code></a><a class="headerlink" href="#gettext-vs-lgettext" title="Permalink to this headline">¶</a></h3>
<p>In Python 2.4 the <a class="reference internal" href="#gettext.lgettext" title="gettext.lgettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">lgettext()</span></code></a> family of functions were introduced. The
intention of these functions is to provide an alternative which is more
compliant with the current implementation of GNU gettext. Unlike
<a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code></a>, which returns strings encoded with the same codeset used in the
translation file, <a class="reference internal" href="#gettext.lgettext" title="gettext.lgettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">lgettext()</span></code></a> will return strings encoded with the
preferred system encoding, as returned by <a class="reference internal" href="locale.html#locale.getpreferredencoding" title="locale.getpreferredencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.getpreferredencoding()</span></code></a>.
Also notice that Python 2.4 introduces new functions to explicitly choose the
codeset used in translated strings. If a codeset is explicitly set, even
<a class="reference internal" href="#gettext.lgettext" title="gettext.lgettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">lgettext()</span></code></a> will return translated strings in the requested codeset, as
would be expected in the GNU gettext implementation.</p>
</div>
</div>
<div class="section" id="acknowledgements">
<h2>22.1.4. Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The following people contributed code, feedback, design suggestions, previous
implementations, and valuable experience to the creation of this module:</p>
<ul class="simple">
<li>Peter Funk</li>
<li>James Henstridge</li>
<li>Juan David Ibáñez Palomar</li>
<li>Marc-André Lemburg</li>
<li>Martin von Löwis</li>
<li>François Pinard</li>
<li>Barry Warsaw</li>
<li>Gustavo Niemeyer</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The default locale directory is system dependent; for example, on RedHat Linux
it is <code class="file docutils literal notranslate"><span class="pre">/usr/share/locale</span></code>, but on Solaris it is <code class="file docutils literal notranslate"><span class="pre">/usr/lib/locale</span></code>.
The <a class="reference internal" href="#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module does not try to support these system dependent
defaults; instead its default is <code class="file docutils literal notranslate"><span class="pre">sys.prefix/share/locale</span></code>. For this
reason, it is always best to call <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code class="xref py py-func docutils literal notranslate"><span class="pre">bindtextdomain()</span></code></a> with an explicit
absolute path at the start of your application.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id7" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>See the footnote for <a class="reference internal" href="#gettext.bindtextdomain" title="gettext.bindtextdomain"><code class="xref py py-func docutils literal notranslate"><span class="pre">bindtextdomain()</span></code></a> above.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id8" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>François Pinard has written a program called <strong class="program">xpot</strong> which does a
similar job.  It is available as part of his
<a class="reference external" href="https://github.com/pinard/po-utils">po-utils package</a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id9" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[4]</a></td><td><strong class="program">msgfmt.py</strong> is binary compatible with GNU <strong class="program">msgfmt</strong> except that
it provides a simpler, all-Python implementation.  With this and
<strong class="program">pygettext.py</strong>, you generally won’t need to install the GNU
<strong class="program">gettext</strong> package to internationalize your Python applications.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id10" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id5">[5]</a></td><td>The choice of <code class="xref py py-func docutils literal notranslate"><span class="pre">N_()</span></code> here is totally arbitrary; it could have just as easily
been <code class="xref py py-func docutils literal notranslate"><span class="pre">MarkThisStringForTranslation()</span></code>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a><ul>
<li><a class="reference internal" href="#gnu-gettext-api">22.1.1. GNU <strong class="program">gettext</strong> API</a></li>
<li><a class="reference internal" href="#class-based-api">22.1.2. Class-based API</a><ul>
<li><a class="reference internal" href="#the-nulltranslations-class">22.1.2.1. The <code class="docutils literal notranslate"><span class="pre">NullTranslations</span></code> class</a></li>
<li><a class="reference internal" href="#the-gnutranslations-class">22.1.2.2. The <code class="docutils literal notranslate"><span class="pre">GNUTranslations</span></code> class</a></li>
<li><a class="reference internal" href="#solaris-message-catalog-support">22.1.2.3. Solaris message catalog support</a></li>
<li><a class="reference internal" href="#the-catalog-constructor">22.1.2.4. The Catalog constructor</a></li>
</ul>
</li>
<li><a class="reference internal" href="#internationalizing-your-programs-and-modules">22.1.3. Internationalizing your programs and modules</a><ul>
<li><a class="reference internal" href="#localizing-your-module">22.1.3.1. Localizing your module</a></li>
<li><a class="reference internal" href="#localizing-your-application">22.1.3.2. Localizing your application</a></li>
<li><a class="reference internal" href="#changing-languages-on-the-fly">22.1.3.3. Changing languages on the fly</a></li>
<li><a class="reference internal" href="#deferred-translations">22.1.3.4. Deferred translations</a></li>
<li><a class="reference internal" href="#gettext-vs-lgettext">22.1.3.5. <code class="docutils literal notranslate"><span class="pre">gettext()</span></code> vs. <code class="docutils literal notranslate"><span class="pre">lgettext()</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#acknowledgements">22.1.4. Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="i18n.html"
                        title="previous chapter">22. Internationalization</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="locale.html"
                        title="next chapter">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gettext.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="locale.html" title="22.2. locale — Internationalization services"
             >next</a> |</li>
        <li class="right" >
          <a href="i18n.html" title="22. Internationalization"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="i18n.html" >22. Internationalization</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�-��__html/library/gl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.8. gl — Graphics Library interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.11. imgfile — Support for SGI imglib files" href="imgfile.html" />
    <link rel="prev" title="39.7. fm — Font Manager interface" href="fm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imgfile.html" title="39.11. imgfile — Support for SGI imglib files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fm.html" title="39.7. fm — Font Manager interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gl">
<span id="gl-graphics-library-interface"></span><h1>39.8. <a class="reference internal" href="#module-gl" title="gl: Functions from the Silicon Graphics Graphics Library. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code></a> — <em>Graphics Library</em> interface<a class="headerlink" href="#module-gl" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-gl" title="gl: Functions from the Silicon Graphics Graphics Library. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module provides access to the Silicon Graphics <em>Graphics Library</em>. It is
available only on Silicon Graphics machines.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Some illegal calls to the GL library cause the Python interpreter to dump
core.  In particular, the use of most GL calls is unsafe before the first
window is opened.</p>
</div>
<p>The module is too large to document here in its entirety, but the following
should help you to get started. The parameter conventions for the C functions
are translated to Python as follows:</p>
<ul>
<li><p class="first">All (short, long, unsigned) int values are represented by Python integers.</p>
</li>
<li><p class="first">All float and double values are represented by Python floating point numbers.
In most cases, Python integers are also allowed.</p>
</li>
<li><p class="first">All arrays are represented by one-dimensional Python lists. In most cases,
tuples are also allowed.</p>
</li>
<li><p class="first">All string and character arguments are represented by Python strings, for
instance, <code class="docutils literal notranslate"><span class="pre">winopen('Hi</span> <span class="pre">There!')</span></code> and <code class="docutils literal notranslate"><span class="pre">rotate(900,</span> <span class="pre">'z')</span></code>.</p>
</li>
<li><p class="first">All (short, long, unsigned) integer arguments or return values that are only
used to specify the length of an array argument are omitted. For example, the C
call</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lmdef</span><span class="p">(</span><span class="n">deftype</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">np</span><span class="p">,</span> <span class="n">props</span><span class="p">)</span>
</pre></div>
</div>
<p>is translated to Python as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lmdef</span><span class="p">(</span><span class="n">deftype</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">props</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">Output arguments are omitted from the argument list; they are transmitted as
function return values instead. If more than one value must be returned, the
return value is a tuple. If the C function has both a regular return value (that
is not omitted because of the previous rule) and an output argument, the return
value comes first in the tuple. Examples: the C call</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">getmcolor</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">red</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">green</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">blue</span><span class="p">)</span>
</pre></div>
</div>
<p>is translated to Python as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">red</span><span class="p">,</span> <span class="n">green</span><span class="p">,</span> <span class="n">blue</span> <span class="o">=</span> <span class="n">getmcolor</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
<p>The following functions are non-standard or have special argument conventions:</p>
<dl class="function">
<dt id="gl.varray">
<code class="descclassname">gl.</code><code class="descname">varray</code><span class="sig-paren">(</span><em>argument</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.varray" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to but faster than a number of <code class="docutils literal notranslate"><span class="pre">v3d()</span></code> calls. The <em>argument</em> is a
list (or tuple) of points. Each point must be a tuple of coordinates <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y,</span>
<span class="pre">z)</span></code> or <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code>. The points may be 2- or 3-dimensional but must all have the
same dimension. Float and int values may be mixed however. The points are always
converted to 3D double precision points by assuming <code class="docutils literal notranslate"><span class="pre">z</span> <span class="pre">=</span> <span class="pre">0.0</span></code> if necessary (as
indicated in the man page), and for each point <code class="docutils literal notranslate"><span class="pre">v3d()</span></code> is called.</p>
</dd></dl>

<dl class="function">
<dt id="gl.nvarray">
<code class="descclassname">gl.</code><code class="descname">nvarray</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gl.nvarray" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to but faster than a number of <code class="docutils literal notranslate"><span class="pre">n3f</span></code> and <code class="docutils literal notranslate"><span class="pre">v3f</span></code> calls. The
argument is an array (list or tuple) of pairs of normals and points. Each pair
is a tuple of a point and a normal for that point. Each point or normal must be
a tuple of coordinates <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y,</span> <span class="pre">z)</span></code>. Three coordinates must be given. Float and
int values may be mixed. For each pair, <code class="docutils literal notranslate"><span class="pre">n3f()</span></code> is called for the normal, and
then <code class="docutils literal notranslate"><span class="pre">v3f()</span></code> is called for the point.</p>
</dd></dl>

<dl class="function">
<dt id="gl.vnarray">
<code class="descclassname">gl.</code><code class="descname">vnarray</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gl.vnarray" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to  <code class="docutils literal notranslate"><span class="pre">nvarray()</span></code> but the pairs have the point first and the normal
second.</p>
</dd></dl>

<dl class="function">
<dt id="gl.nurbssurface">
<code class="descclassname">gl.</code><code class="descname">nurbssurface</code><span class="sig-paren">(</span><em>s_k</em>, <em>t_k</em>, <em>ctl</em>, <em>s_ord</em>, <em>t_ord</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.nurbssurface" title="Permalink to this definition">¶</a></dt>
<dd><p>Defines a nurbs surface. The dimensions of <code class="docutils literal notranslate"><span class="pre">ctl[][]</span></code> are computed as follows:
<code class="docutils literal notranslate"><span class="pre">[len(s_k)</span> <span class="pre">-</span> <span class="pre">s_ord]</span></code>, <code class="docutils literal notranslate"><span class="pre">[len(t_k)</span> <span class="pre">-</span> <span class="pre">t_ord]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="gl.nurbscurve">
<code class="descclassname">gl.</code><code class="descname">nurbscurve</code><span class="sig-paren">(</span><em>knots</em>, <em>ctlpoints</em>, <em>order</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.nurbscurve" title="Permalink to this definition">¶</a></dt>
<dd><p>Defines a nurbs curve. The length of ctlpoints is <code class="docutils literal notranslate"><span class="pre">len(knots)</span> <span class="pre">-</span> <span class="pre">order</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="gl.pwlcurve">
<code class="descclassname">gl.</code><code class="descname">pwlcurve</code><span class="sig-paren">(</span><em>points</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.pwlcurve" title="Permalink to this definition">¶</a></dt>
<dd><p>Defines a piecewise-linear curve. <em>points</em> is a list of points. <em>type</em> must be
<code class="docutils literal notranslate"><span class="pre">N_ST</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="gl.pick">
<code class="descclassname">gl.</code><code class="descname">pick</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.pick" title="Permalink to this definition">¶</a></dt>
<dt id="gl.select">
<code class="descclassname">gl.</code><code class="descname">select</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#gl.select" title="Permalink to this definition">¶</a></dt>
<dd><p>The only argument to these functions specifies the desired size of the pick or
select buffer.</p>
</dd></dl>

<dl class="function">
<dt id="gl.endpick">
<code class="descclassname">gl.</code><code class="descname">endpick</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gl.endpick" title="Permalink to this definition">¶</a></dt>
<dt id="gl.endselect">
<code class="descclassname">gl.</code><code class="descname">endselect</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#gl.endselect" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions have no arguments. They return a list of integers representing
the used part of the pick/select buffer. No method is provided to detect buffer
overrun.</p>
</dd></dl>

<p>Here is a tiny but complete example GL program in Python:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gl</span><span class="o">,</span> <span class="nn">GL</span><span class="o">,</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">foreground</span><span class="p">()</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">prefposition</span><span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="mi">900</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mi">900</span><span class="p">)</span>
    <span class="n">w</span> <span class="o">=</span> <span class="n">gl</span><span class="o">.</span><span class="n">winopen</span><span class="p">(</span><span class="s1">&#39;CrissCross&#39;</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">ortho2</span><span class="p">(</span><span class="mf">0.0</span><span class="p">,</span> <span class="mf">400.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">,</span> <span class="mf">400.0</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="n">GL</span><span class="o">.</span><span class="n">WHITE</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="n">GL</span><span class="o">.</span><span class="n">RED</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">bgnline</span><span class="p">()</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">v2f</span><span class="p">(</span><span class="mf">0.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">v2f</span><span class="p">(</span><span class="mf">400.0</span><span class="p">,</span> <span class="mf">400.0</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">endline</span><span class="p">()</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">bgnline</span><span class="p">()</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">v2f</span><span class="p">(</span><span class="mf">400.0</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">v2f</span><span class="p">(</span><span class="mf">0.0</span><span class="p">,</span> <span class="mf">400.0</span><span class="p">)</span>
    <span class="n">gl</span><span class="o">.</span><span class="n">endline</span><span class="p">()</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>

<span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://pyopengl.sourceforge.net/">PyOpenGL: The Python OpenGL Binding</a></dt>
<dd><p class="first last" id="index-0">An interface to OpenGL is also available; see information about the <strong>PyOpenGL</strong>
project online at <a class="reference external" href="http://pyopengl.sourceforge.net/">http://pyopengl.sourceforge.net/</a>.  This may be a better option
if support for SGI hardware from before about 1996 is not required.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="module-DEVICE">
<span id="device-constants-used-with-the-gl-module"></span><h1>39.9. <a class="reference internal" href="#module-DEVICE" title="DEVICE: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">DEVICE</span></code></a> — Constants used with the <a class="reference internal" href="#module-gl" title="gl: Functions from the Silicon Graphics Graphics Library. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code></a> module<a class="headerlink" href="#module-DEVICE" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-DEVICE" title="DEVICE: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">DEVICE</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This modules defines the constants used by the Silicon Graphics <em>Graphics
Library</em> that C programmers find in the header file <code class="docutils literal notranslate"><span class="pre">&lt;gl/device.h&gt;</span></code>. Read the
module source file for details.</p>
</div>
<div class="section" id="module-GL">
<span id="gl-constants-used-with-the-gl-module"></span><h1>39.10. <a class="reference internal" href="#module-GL" title="GL: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">GL</span></code></a> — Constants used with the <a class="reference internal" href="#module-gl" title="gl: Functions from the Silicon Graphics Graphics Library. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code></a> module<a class="headerlink" href="#module-GL" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-GL" title="GL: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">GL</span></code></a> module has been removed in Python 3.</p>
</div>
<p>This module contains constants used by the Silicon Graphics <em>Graphics Library</em>
from the C header file <code class="docutils literal notranslate"><span class="pre">&lt;gl/gl.h&gt;</span></code>. Read the module source file for details.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></li>
<li><a class="reference internal" href="#module-DEVICE">39.9. <code class="docutils literal notranslate"><span class="pre">DEVICE</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li><a class="reference internal" href="#module-GL">39.10. <code class="docutils literal notranslate"><span class="pre">GL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="fm.html"
                        title="previous chapter">39.7. <code class="docutils literal notranslate"><span class="pre">fm</span></code> — <em>Font Manager</em> interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imgfile.html"
                        title="next chapter">39.11. <code class="docutils literal notranslate"><span class="pre">imgfile</span></code> — Support for SGI imglib files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imgfile.html" title="39.11. imgfile — Support for SGI imglib files"
             >next</a> |</li>
        <li class="right" >
          <a href="fm.html" title="39.7. fm — Font Manager interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ē{^8^8html/library/glob.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.7. glob — Unix style pathname pattern expansion &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.8. fnmatch — Unix filename pattern matching" href="fnmatch.html" />
    <link rel="prev" title="10.6. tempfile — Generate temporary files and directories" href="tempfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/glob.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fnmatch.html" title="10.8. fnmatch — Unix filename pattern matching"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tempfile.html" title="10.6. tempfile — Generate temporary files and directories"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-glob">
<span id="glob-unix-style-pathname-pattern-expansion"></span><h1>10.7. <a class="reference internal" href="#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> — Unix style pathname pattern expansion<a class="headerlink" href="#module-glob" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/glob.py">Lib/glob.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> module finds all the pathnames matching a specified pattern
according to the rules used by the Unix shell, although results are returned in
arbitrary order.  No tilde expansion is done, but <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, and character
ranges expressed with <code class="docutils literal notranslate"><span class="pre">[]</span></code> will be correctly matched.  This is done by using
the <a class="reference internal" href="os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> and <a class="reference internal" href="fnmatch.html#fnmatch.fnmatch" title="fnmatch.fnmatch"><code class="xref py py-func docutils literal notranslate"><span class="pre">fnmatch.fnmatch()</span></code></a> functions in concert, and
not by actually invoking a subshell.  Note that unlike <a class="reference internal" href="fnmatch.html#fnmatch.fnmatch" title="fnmatch.fnmatch"><code class="xref py py-func docutils literal notranslate"><span class="pre">fnmatch.fnmatch()</span></code></a>,
<a class="reference internal" href="#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> treats filenames beginning with a dot (<code class="docutils literal notranslate"><span class="pre">.</span></code>) as special cases.
(For tilde and shell variable expansion, use <a class="reference internal" href="os.path.html#os.path.expanduser" title="os.path.expanduser"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expanduser()</span></code></a> and
<a class="reference internal" href="os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a>.)</p>
<p>For a literal match, wrap the meta-characters in brackets.
For example, <code class="docutils literal notranslate"><span class="pre">'[?]'</span></code> matches the character <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.</p>
<dl class="function">
<dt id="glob.glob">
<code class="descclassname">glob.</code><code class="descname">glob</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#glob.glob" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a possibly-empty list of path names that match <em>pathname</em>, which must be
a string containing a path specification. <em>pathname</em> can be either absolute
(like <code class="file docutils literal notranslate"><span class="pre">/usr/src/Python-1.5/Makefile</span></code>) or relative (like
<code class="file docutils literal notranslate"><span class="pre">../../Tools/*/*.gif</span></code>), and can contain shell-style wildcards. Broken
symlinks are included in the results (as in the shell).</p>
</dd></dl>

<dl class="function">
<dt id="glob.iglob">
<code class="descclassname">glob.</code><code class="descname">iglob</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#glob.iglob" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> which yields the same values as <a class="reference internal" href="#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-func docutils literal notranslate"><span class="pre">glob()</span></code></a>
without actually storing them all simultaneously.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>For example, consider a directory containing only the following files:
<code class="file docutils literal notranslate"><span class="pre">1.gif</span></code>, <code class="file docutils literal notranslate"><span class="pre">2.txt</span></code>, and <code class="file docutils literal notranslate"><span class="pre">card.gif</span></code>.  <a class="reference internal" href="#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-func docutils literal notranslate"><span class="pre">glob()</span></code></a> will produce
the following results.  Notice how any leading components of the path are
preserved.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">glob</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;./[0-9].*&#39;</span><span class="p">)</span>
<span class="go">[&#39;./1.gif&#39;, &#39;./2.txt&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;*.gif&#39;</span><span class="p">)</span>
<span class="go">[&#39;1.gif&#39;, &#39;card.gif&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;?.gif&#39;</span><span class="p">)</span>
<span class="go">[&#39;1.gif&#39;]</span>
</pre></div>
</div>
<p>If the directory contains files starting with <code class="docutils literal notranslate"><span class="pre">.</span></code> they won’t be matched by
default. For example, consider a directory containing <code class="file docutils literal notranslate"><span class="pre">card.gif</span></code> and
<code class="file docutils literal notranslate"><span class="pre">.card.gif</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">glob</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;*.gif&#39;</span><span class="p">)</span>
<span class="go">[&#39;card.gif&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;.c*&#39;</span><span class="p">)</span>
<span class="go">[&#39;.card.gif&#39;]</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="fnmatch.html#module-fnmatch" title="fnmatch: Unix shell style filename pattern matching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fnmatch</span></code></a></dt>
<dd>Shell-style filename (not path) expansion</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tempfile.html"
                        title="previous chapter">10.6. <code class="docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fnmatch.html"
                        title="next chapter">10.8. <code class="docutils literal notranslate"><span class="pre">fnmatch</span></code> — Unix filename pattern matching</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/glob.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fnmatch.html" title="10.8. fnmatch — Unix filename pattern matching"
             >next</a> |</li>
        <li class="right" >
          <a href="tempfile.html" title="10.6. tempfile — Generate temporary files and directories"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�i!�4,4,html/library/grp.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.4. grp — The group database &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.5. crypt — Function to check Unix passwords" href="crypt.html" />
    <link rel="prev" title="36.3. spwd — The shadow password database" href="spwd.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/grp.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="crypt.html" title="36.5. crypt — Function to check Unix passwords"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="spwd.html" title="36.3. spwd — The shadow password database"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-grp">
<span id="grp-the-group-database"></span><h1>36.4. <a class="reference internal" href="#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">grp</span></code></a> — The group database<a class="headerlink" href="#module-grp" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to the Unix group database. It is available on all
Unix versions.</p>
<p>Group database entries are reported as a tuple-like object, whose attributes
correspond to the members of the <code class="docutils literal notranslate"><span class="pre">group</span></code> structure (Attribute field below, see
<code class="docutils literal notranslate"><span class="pre">&lt;pwd.h&gt;</span></code>):</p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="22%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Attribute</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td>gr_name</td>
<td>the name of the group</td>
</tr>
<tr class="row-odd"><td>1</td>
<td>gr_passwd</td>
<td>the (encrypted) group password;
often empty</td>
</tr>
<tr class="row-even"><td>2</td>
<td>gr_gid</td>
<td>the numerical group ID</td>
</tr>
<tr class="row-odd"><td>3</td>
<td>gr_mem</td>
<td>all the group member’s  user
names</td>
</tr>
</tbody>
</table>
<p>The gid is an integer, name and password are strings, and the member list is a
list of strings. (Note that most users are not explicitly listed as members of
the group they are in according to the password database.  Check both databases
to get complete membership information.  Also note that a <code class="docutils literal notranslate"><span class="pre">gr_name</span></code> that
starts with a <code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code> is likely to be a YP/NIS reference and may not be
accessible via <a class="reference internal" href="#grp.getgrnam" title="grp.getgrnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgrnam()</span></code></a> or <a class="reference internal" href="#grp.getgrgid" title="grp.getgrgid"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgrgid()</span></code></a>.)</p>
<p>It defines the following items:</p>
<dl class="function">
<dt id="grp.getgrgid">
<code class="descclassname">grp.</code><code class="descname">getgrgid</code><span class="sig-paren">(</span><em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#grp.getgrgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the group database entry for the given numeric group ID. <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>
is raised if the entry asked for cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="grp.getgrnam">
<code class="descclassname">grp.</code><code class="descname">getgrnam</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#grp.getgrnam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the group database entry for the given group name. <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is
raised if the entry asked for cannot be found.</p>
</dd></dl>

<dl class="function">
<dt id="grp.getgrall">
<code class="descclassname">grp.</code><code class="descname">getgrall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#grp.getgrall" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all available group entries, in arbitrary order.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a></dt>
<dd>An interface to the user database, similar to this.</dd>
<dt>Module <a class="reference internal" href="spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a></dt>
<dd>An interface to the shadow password database, similar to this.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="spwd.html"
                        title="previous chapter">36.3. <code class="docutils literal notranslate"><span class="pre">spwd</span></code> — The shadow password database</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="crypt.html"
                        title="next chapter">36.5. <code class="docutils literal notranslate"><span class="pre">crypt</span></code> — Function to check Unix passwords</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/grp.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="crypt.html" title="36.5. crypt — Function to check Unix passwords"
             >next</a> |</li>
        <li class="right" >
          <a href="spwd.html" title="36.3. spwd — The shadow password database"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\(�/`P`Phtml/library/gzip.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12.2. gzip — Support for gzip files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12.3. bz2 — Compression compatible with bzip2" href="bz2.html" />
    <link rel="prev" title="12.1. zlib — Compression compatible with gzip" href="zlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/gzip.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bz2.html" title="12.3. bz2 — Compression compatible with bzip2"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="zlib.html" title="12.1. zlib — Compression compatible with gzip"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" accesskey="U">12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-gzip">
<span id="gzip-support-for-gzip-files"></span><h1>12.2. <a class="reference internal" href="#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> — Support for <strong class="program">gzip</strong> files<a class="headerlink" href="#module-gzip" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/gzip.py">Lib/gzip.py</a></p>
<hr class="docutils" />
<p>This module provides a simple interface to compress and decompress files just
like the GNU programs <strong class="program">gzip</strong> and <strong class="program">gunzip</strong> would.</p>
<p>The data compression is provided by the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module.</p>
<p>The <a class="reference internal" href="#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module provides the <a class="reference internal" href="#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> class which is modeled
after Python’s File Object. The <a class="reference internal" href="#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> class reads and writes
<strong class="program">gzip</strong>-format files, automatically compressing or decompressing the
data so that it looks like an ordinary file object.</p>
<p>Note that additional file formats which can be decompressed by the
<strong class="program">gzip</strong> and <strong class="program">gunzip</strong> programs, such  as those produced by
<strong class="program">compress</strong> and <strong class="program">pack</strong>, are not supported by this module.</p>
<p>The module defines the following items:</p>
<dl class="class">
<dt id="gzip.GzipFile">
<em class="property">class </em><code class="descclassname">gzip.</code><code class="descname">GzipFile</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>compresslevel</em><span class="optional">[</span>, <em>fileobj</em><span class="optional">[</span>, <em>mtime</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gzip.GzipFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for the <a class="reference internal" href="#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> class, which simulates most of the methods
of a file object, with the exception of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code> methods.  At least one of <em>fileobj</em> and <em>filename</em> must be
given a non-trivial value.</p>
<p>The new class instance is based on <em>fileobj</em>, which can be a regular file, a
<a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object, or any other object which simulates a file.  It
defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case <em>filename</em> is opened to provide a file
object.</p>
<p>When <em>fileobj</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <em>filename</em> argument is only used to be
included in the <strong class="program">gzip</strong> file header, which may include the original
filename of the uncompressed file.  It defaults to the filename of <em>fileobj</em>, if
discernible; otherwise, it defaults to the empty string, and in this case the
original filename is not included in the header.</p>
<p>The <em>mode</em> argument can be any of <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'rb'</span></code>, <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>,
or <code class="docutils literal notranslate"><span class="pre">'wb'</span></code>, depending on whether the file will be read or written.  The default
is the mode of <em>fileobj</em> if discernible; otherwise, the default is <code class="docutils literal notranslate"><span class="pre">'rb'</span></code>. If
not given, the ‘b’ flag will be added to the mode to ensure the file is opened
in binary mode for cross-platform portability.</p>
<p>The <em>compresslevel</em> argument is an integer from <code class="docutils literal notranslate"><span class="pre">0</span></code> to <code class="docutils literal notranslate"><span class="pre">9</span></code> controlling
the level of compression; <code class="docutils literal notranslate"><span class="pre">1</span></code> is fastest and produces the least
compression, and <code class="docutils literal notranslate"><span class="pre">9</span></code> is slowest and produces the most compression. <code class="docutils literal notranslate"><span class="pre">0</span></code>
is no compression. The default is <code class="docutils literal notranslate"><span class="pre">9</span></code>.</p>
<p>The <em>mtime</em> argument is an optional numeric timestamp to be written to
the stream when compressing.  All <strong class="program">gzip</strong> compressed streams are
required to contain a timestamp.  If omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the current
time is used.  This module ignores the timestamp when decompressing;
however, some programs, such as <strong class="program">gunzip</strong>, make use of it.
The format of the timestamp is the same as that of the return value of
<code class="docutils literal notranslate"><span class="pre">time.time()</span></code> and of the <code class="docutils literal notranslate"><span class="pre">st_mtime</span></code> attribute of the object returned
by <code class="docutils literal notranslate"><span class="pre">os.stat()</span></code>.</p>
<p>Calling a <a class="reference internal" href="#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method does not close
<em>fileobj</em>, since you might wish to append more material after the compressed
data.  This also allows you to pass a <a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object opened for
writing as <em>fileobj</em>, and retrieve the resulting memory buffer using the
<a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object’s <a class="reference internal" href="stringio.html#StringIO.StringIO.getvalue" title="StringIO.StringIO.getvalue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getvalue()</span></code></a> method.</p>
<p><a class="reference internal" href="#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> supports iteration and the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for zero-padded files was added.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <em>mtime</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="gzip.open">
<code class="descclassname">gzip.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>compresslevel</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#gzip.open" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">GzipFile(filename,</span></code> <code class="docutils literal notranslate"><span class="pre">mode,</span></code> <code class="docutils literal notranslate"><span class="pre">compresslevel)</span></code>.
The <em>filename</em> argument is required; <em>mode</em> defaults to <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> and
<em>compresslevel</em> defaults to <code class="docutils literal notranslate"><span class="pre">9</span></code>.</p>
</dd></dl>

<div class="section" id="examples-of-usage">
<span id="gzip-usage-examples"></span><h2>12.2.1. Examples of usage<a class="headerlink" href="#examples-of-usage" title="Permalink to this headline">¶</a></h2>
<p>Example of how to read a compressed file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gzip</span>
<span class="k">with</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;file.txt.gz&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">file_content</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>Example of how to create a compressed GZIP file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gzip</span>
<span class="n">content</span> <span class="o">=</span> <span class="s2">&quot;Lots of content here&quot;</span>
<span class="k">with</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;file.txt.gz&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">content</span><span class="p">)</span>
</pre></div>
</div>
<p>Example of how to GZIP compress an existing file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">gzip</span>
<span class="kn">import</span> <span class="nn">shutil</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;file.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f_in</span><span class="p">,</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;file.txt.gz&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f_out</span><span class="p">:</span>
    <span class="n">shutil</span><span class="o">.</span><span class="n">copyfileobj</span><span class="p">(</span><span class="n">f_in</span><span class="p">,</span> <span class="n">f_out</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a></dt>
<dd>The basic data compression module needed to support the <strong class="program">gzip</strong> file
format.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a><ul>
<li><a class="reference internal" href="#examples-of-usage">12.2.1. Examples of usage</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="zlib.html"
                        title="previous chapter">12.1. <code class="docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bz2.html"
                        title="next chapter">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/gzip.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bz2.html" title="12.3. bz2 — Compression compatible with bzip2"
             >next</a> |</li>
        <li class="right" >
          <a href="zlib.html" title="12.1. zlib — Compression compatible with gzip"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" >12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�&��{c{chtml/library/hashlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14.1. hashlib — Secure hashes and message digests &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14.2. hmac — Keyed-Hashing for Message Authentication" href="hmac.html" />
    <link rel="prev" title="14. Cryptographic Services" href="crypto.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/hashlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="14.2. hmac — Keyed-Hashing for Message Authentication"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="crypto.html" title="14. Cryptographic Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" accesskey="U">14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-hashlib">
<span id="hashlib-secure-hashes-and-message-digests"></span><h1>14.1. <a class="reference internal" href="#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> — Secure hashes and message digests<a class="headerlink" href="#module-hashlib" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/hashlib.py">Lib/hashlib.py</a></p>
<hr class="docutils" />
<p>This module implements a common interface to many different secure hash and
message digest algorithms.  Included are the FIPS secure hash algorithms SHA1,
SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA’s MD5
algorithm (defined in Internet <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1321.html"><strong>RFC 1321</strong></a>). The terms secure hash and message
digest are interchangeable.  Older algorithms were called message digests.  The
modern term is secure hash.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you want the adler32 or crc32 hash functions, they are available in
the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Some algorithms have known hash collision weaknesses, refer to the “See
also” section at the end.</p>
</div>
<p>There is one constructor method named for each type of <em class="dfn">hash</em>.  All return
a hash object with the same simple interface. For example: use <code class="xref py py-func docutils literal notranslate"><span class="pre">sha1()</span></code> to
create a SHA1 hash object. You can now feed this object with arbitrary strings
using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method.  At any point you can ask it for the
<em class="dfn">digest</em> of the concatenation of the strings fed to it so far using the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">hexdigest()</span></code> methods.</p>
<p id="index-2">Constructors for hash algorithms that are always present in this module are
<a class="reference internal" href="md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">md5()</span></code></a>, <code class="xref py py-func docutils literal notranslate"><span class="pre">sha1()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">sha224()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">sha256()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">sha384()</span></code>, and
<code class="xref py py-func docutils literal notranslate"><span class="pre">sha512()</span></code>.  Additional algorithms may also be available depending upon the
OpenSSL library that Python uses on your platform.</p>
<p>For example, to obtain the digest of the string <code class="docutils literal notranslate"><span class="pre">'Nobody</span> <span class="pre">inspects</span> <span class="pre">the</span> <span class="pre">spammish</span>
<span class="pre">repetition'</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">hashlib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">md5</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">&quot;Nobody inspects&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">&quot; the spammish repetition&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">digest</span><span class="p">()</span>
<span class="go">&#39;\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">digest_size</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">block_size</span>
<span class="go">64</span>
</pre></div>
</div>
<p>More condensed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">hashlib</span><span class="o">.</span><span class="n">sha224</span><span class="p">(</span><span class="s2">&quot;Nobody inspects the spammish repetition&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()</span>
<span class="go">&#39;a4337bc45a8fc544c03f52dc550cd6e1e87021bc896588bd79e901e2&#39;</span>
</pre></div>
</div>
<p>A generic <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a> constructor that takes the string name of the desired
algorithm as its first parameter also exists to allow access to the above listed
hashes as well as any other algorithms that your OpenSSL library may offer.  The
named constructors are much faster than <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a> and should be preferred.</p>
<p>Using <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a> with an algorithm provided by OpenSSL:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s1">&#39;ripemd160&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">&quot;Nobody inspects the spammish repetition&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()</span>
<span class="go">&#39;cc4a5ce1b3df48aec5d22d1f16b894a0b894eccc&#39;</span>
</pre></div>
</div>
<p>This module provides the following constant attribute:</p>
<dl class="data">
<dt id="hashlib.hashlib.algorithms">
<code class="descclassname">hashlib.</code><code class="descname">algorithms</code><a class="headerlink" href="#hashlib.hashlib.algorithms" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple providing the names of the hash algorithms guaranteed to be
supported by this module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="hashlib.algorithms_guaranteed">
<code class="descclassname">hashlib.</code><code class="descname">algorithms_guaranteed</code><a class="headerlink" href="#hashlib.algorithms_guaranteed" title="Permalink to this definition">¶</a></dt>
<dd><p>A set containing the names of the hash algorithms guaranteed to be supported
by this module on all platforms.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="hashlib.algorithms_available">
<code class="descclassname">hashlib.</code><code class="descname">algorithms_available</code><a class="headerlink" href="#hashlib.algorithms_available" title="Permalink to this definition">¶</a></dt>
<dd><p>A set containing the names of the hash algorithms that are available in the
running Python interpreter.  These names will be recognized when passed to
<a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a>.  <a class="reference internal" href="#hashlib.algorithms_guaranteed" title="hashlib.algorithms_guaranteed"><code class="xref py py-attr docutils literal notranslate"><span class="pre">algorithms_guaranteed</span></code></a> will always be a subset.  The
same algorithm may appear multiple times in this set under different names
(thanks to OpenSSL).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<p>The following values are provided as constant attributes of the hash objects
returned by the constructors:</p>
<dl class="data">
<dt id="hashlib.hash.digest_size">
<code class="descclassname">hash.</code><code class="descname">digest_size</code><a class="headerlink" href="#hashlib.hash.digest_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the resulting hash in bytes.</p>
</dd></dl>

<dl class="data">
<dt id="hashlib.hash.block_size">
<code class="descclassname">hash.</code><code class="descname">block_size</code><a class="headerlink" href="#hashlib.hash.block_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The internal block size of the hash algorithm in bytes.</p>
</dd></dl>

<p>A hash object has the following methods:</p>
<dl class="method">
<dt id="hashlib.hash.update">
<code class="descclassname">hash.</code><code class="descname">update</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#hashlib.hash.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the hash object with the string <em>arg</em>.  Repeated calls are equivalent to
a single call with the concatenation of all the arguments: <code class="docutils literal notranslate"><span class="pre">m.update(a);</span>
<span class="pre">m.update(b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.update(a+b)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The Python GIL is released to allow other threads to run while
hash updates on data larger than 2048 bytes is taking place when
using hash algorithms supplied by OpenSSL.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="hashlib.hash.digest">
<code class="descclassname">hash.</code><code class="descname">digest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hashlib.hash.digest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the digest of the strings passed to the <a class="reference internal" href="#hashlib.hash.update" title="hashlib.hash.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> method so far.
This is a string of <a class="reference internal" href="#hashlib.hash.digest_size" title="hashlib.hash.digest_size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">digest_size</span></code></a> bytes which may contain non-ASCII
characters, including null bytes.</p>
</dd></dl>

<dl class="method">
<dt id="hashlib.hash.hexdigest">
<code class="descclassname">hash.</code><code class="descname">hexdigest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hashlib.hash.hexdigest" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#hashlib.hash.digest" title="hashlib.hash.digest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code></a> except the digest is returned as a string of double length,
containing only hexadecimal digits.  This may  be used to exchange the value
safely in email or other non-binary environments.</p>
</dd></dl>

<dl class="method">
<dt id="hashlib.hash.copy">
<code class="descclassname">hash.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hashlib.hash.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy (“clone”) of the hash object.  This can be used to efficiently
compute the digests of strings that share a common initial substring.</p>
</dd></dl>

<div class="section" id="key-derivation">
<h2>14.1.1. Key derivation<a class="headerlink" href="#key-derivation" title="Permalink to this headline">¶</a></h2>
<p>Key derivation and key stretching algorithms are designed for secure password
hashing. Naive algorithms such as <code class="docutils literal notranslate"><span class="pre">sha1(password)</span></code> are not resistant against
brute-force attacks. A good password hashing function must be tunable, slow, and
include a <a class="reference external" href="https://en.wikipedia.org/wiki/Salt_%28cryptography%29">salt</a>.</p>
<dl class="function">
<dt id="hashlib.pbkdf2_hmac">
<code class="descclassname">hashlib.</code><code class="descname">pbkdf2_hmac</code><span class="sig-paren">(</span><em>name</em>, <em>password</em>, <em>salt</em>, <em>rounds</em>, <em>dklen=None</em><span class="sig-paren">)</span><a class="headerlink" href="#hashlib.pbkdf2_hmac" title="Permalink to this definition">¶</a></dt>
<dd><p>The function provides PKCS#5 password-based key derivation function 2. It
uses HMAC as pseudorandom function.</p>
<p>The string <em>name</em> is the desired name of the hash digest algorithm for
HMAC, e.g. ‘sha1’ or ‘sha256’. <em>password</em> and <em>salt</em> are interpreted as
buffers of bytes. Applications and libraries should limit <em>password</em> to
a sensible value (e.g. 1024). <em>salt</em> should be about 16 or more bytes from
a proper source, e.g. <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a>.</p>
<p>The number of <em>rounds</em> should be chosen based on the hash algorithm and
computing power. As of 2013, at least 100,000 rounds of SHA-256 is suggested.</p>
<p><em>dklen</em> is the length of the derived key. If <em>dklen</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then the
digest size of the hash algorithm <em>name</em> is used, e.g. 64 for SHA-512.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">hashlib</span><span class="o">,</span> <span class="nn">binascii</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dk</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">pbkdf2_hmac</span><span class="p">(</span><span class="s1">&#39;sha256&#39;</span><span class="p">,</span> <span class="sa">b</span><span class="s1">&#39;password&#39;</span><span class="p">,</span> <span class="sa">b</span><span class="s1">&#39;salt&#39;</span><span class="p">,</span> <span class="mi">100000</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">binascii</span><span class="o">.</span><span class="n">hexlify</span><span class="p">(</span><span class="n">dk</span><span class="p">)</span>
<span class="go">b&#39;0394a2ede332c9a13eb82e9b24631604c31df978b4e2f0fbd2c549944f9d79a5&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.8.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">A fast implementation of <em>pbkdf2_hmac</em> is available with OpenSSL.  The
Python implementation uses an inline version of <a class="reference internal" href="hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a>. It is about
three times slower and doesn’t release the GIL.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a></dt>
<dd>A module to generate message authentication codes using hashes.</dd>
<dt>Module <a class="reference internal" href="base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a></dt>
<dd>Another way to encode binary hashes for non-binary environments.</dd>
<dt><a class="reference external" href="http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf">http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf</a></dt>
<dd>The FIPS 180-2 publication on Secure Hash Algorithms.</dd>
<dt><a class="reference external" href="https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms">https://en.wikipedia.org/wiki/Cryptographic_hash_function#Cryptographic_hash_algorithms</a></dt>
<dd>Wikipedia article with information on which algorithms have known issues and
what that means regarding their use.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a><ul>
<li><a class="reference internal" href="#key-derivation">14.1.1. Key derivation</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="crypto.html"
                        title="previous chapter">14. Cryptographic Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="hmac.html"
                        title="next chapter">14.2. <code class="docutils literal notranslate"><span class="pre">hmac</span></code> — Keyed-Hashing for Message Authentication</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/hashlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="14.2. hmac — Keyed-Hashing for Message Authentication"
             >next</a> |</li>
        <li class="right" >
          <a href="crypto.html" title="14. Cryptographic Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" >14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��%3J�J�html/library/heapq.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.4. heapq — Heap queue algorithm &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.5. bisect — Array bisection algorithm" href="bisect.html" />
    <link rel="prev" title="8.3. collections — High-performance container datatypes" href="collections.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/heapq.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bisect.html" title="8.5. bisect — Array bisection algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="collections.html" title="8.3. collections — High-performance container datatypes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-heapq">
<span id="heapq-heap-queue-algorithm"></span><h1>8.4. <a class="reference internal" href="#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> — Heap queue algorithm<a class="headerlink" href="#module-heapq" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/heapq.py">Lib/heapq.py</a></p>
<hr class="docutils" />
<p>This module provides an implementation of the heap queue algorithm, also known
as the priority queue algorithm.</p>
<p>Heaps are binary trees for which every parent node has a value less than or
equal to any of its children.  This implementation uses arrays for which
<code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span> <span class="pre">heap[2*k+1]</span></code> and <code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span> <span class="pre">heap[2*k+2]</span></code> for all <em>k</em>, counting
elements from zero.  For the sake of comparison, non-existing elements are
considered to be infinite.  The interesting property of a heap is that its
smallest element is always the root, <code class="docutils literal notranslate"><span class="pre">heap[0]</span></code>.</p>
<p>The API below differs from textbook heap algorithms in two aspects: (a) We use
zero-based indexing.  This makes the relationship between the index for a node
and the indexes for its children slightly less obvious, but is more suitable
since Python uses zero-based indexing. (b) Our pop method returns the smallest
item, not the largest (called a “min heap” in textbooks; a “max heap” is more
common in texts because of its suitability for in-place sorting).</p>
<p>These two make it possible to view the heap as a regular Python list without
surprises: <code class="docutils literal notranslate"><span class="pre">heap[0]</span></code> is the smallest item, and <code class="docutils literal notranslate"><span class="pre">heap.sort()</span></code> maintains the
heap invariant!</p>
<p>To create a heap, use a list initialized to <code class="docutils literal notranslate"><span class="pre">[]</span></code>, or you can transform a
populated list into a heap via function <a class="reference internal" href="#heapq.heapify" title="heapq.heapify"><code class="xref py py-func docutils literal notranslate"><span class="pre">heapify()</span></code></a>.</p>
<p>The following functions are provided:</p>
<dl class="function">
<dt id="heapq.heappush">
<code class="descclassname">heapq.</code><code class="descname">heappush</code><span class="sig-paren">(</span><em>heap</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.heappush" title="Permalink to this definition">¶</a></dt>
<dd><p>Push the value <em>item</em> onto the <em>heap</em>, maintaining the heap invariant.</p>
</dd></dl>

<dl class="function">
<dt id="heapq.heappop">
<code class="descclassname">heapq.</code><code class="descname">heappop</code><span class="sig-paren">(</span><em>heap</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.heappop" title="Permalink to this definition">¶</a></dt>
<dd><p>Pop and return the smallest item from the <em>heap</em>, maintaining the heap
invariant.  If the heap is empty, <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is raised.  To access the
smallest item without popping it, use <code class="docutils literal notranslate"><span class="pre">heap[0]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="heapq.heappushpop">
<code class="descclassname">heapq.</code><code class="descname">heappushpop</code><span class="sig-paren">(</span><em>heap</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.heappushpop" title="Permalink to this definition">¶</a></dt>
<dd><p>Push <em>item</em> on the heap, then pop and return the smallest item from the
<em>heap</em>.  The combined action runs more efficiently than <a class="reference internal" href="#heapq.heappush" title="heapq.heappush"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code></a>
followed by a separate call to <a class="reference internal" href="#heapq.heappop" title="heapq.heappop"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="heapq.heapify">
<code class="descclassname">heapq.</code><code class="descname">heapify</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.heapify" title="Permalink to this definition">¶</a></dt>
<dd><p>Transform list <em>x</em> into a heap, in-place, in linear time.</p>
</dd></dl>

<dl class="function">
<dt id="heapq.heapreplace">
<code class="descclassname">heapq.</code><code class="descname">heapreplace</code><span class="sig-paren">(</span><em>heap</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.heapreplace" title="Permalink to this definition">¶</a></dt>
<dd><p>Pop and return the smallest item from the <em>heap</em>, and also push the new <em>item</em>.
The heap size doesn’t change. If the heap is empty, <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is raised.</p>
<p>This one step operation is more efficient than a <a class="reference internal" href="#heapq.heappop" title="heapq.heappop"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code></a> followed by
<a class="reference internal" href="#heapq.heappush" title="heapq.heappush"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code></a> and can be more appropriate when using a fixed-size heap.
The pop/push combination always returns an element from the heap and replaces
it with <em>item</em>.</p>
<p>The value returned may be larger than the <em>item</em> added.  If that isn’t
desired, consider using <a class="reference internal" href="#heapq.heappushpop" title="heapq.heappushpop"><code class="xref py py-func docutils literal notranslate"><span class="pre">heappushpop()</span></code></a> instead.  Its push/pop
combination returns the smaller of the two values, leaving the larger value
on the heap.</p>
</dd></dl>

<p>The module also offers three general purpose functions based on heaps.</p>
<dl class="function">
<dt id="heapq.merge">
<code class="descclassname">heapq.</code><code class="descname">merge</code><span class="sig-paren">(</span><em>*iterables</em><span class="sig-paren">)</span><a class="headerlink" href="#heapq.merge" title="Permalink to this definition">¶</a></dt>
<dd><p>Merge multiple sorted inputs into a single sorted output (for example, merge
timestamped entries from multiple log files).  Returns an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>
over the sorted values.</p>
<p>Similar to <code class="docutils literal notranslate"><span class="pre">sorted(itertools.chain(*iterables))</span></code> but returns an iterable, does
not pull the data into memory all at once, and assumes that each of the input
streams is already sorted (smallest to largest).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="heapq.nlargest">
<code class="descclassname">heapq.</code><code class="descname">nlargest</code><span class="sig-paren">(</span><em>n</em>, <em>iterable</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#heapq.nlargest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list with the <em>n</em> largest elements from the dataset defined by
<em>iterable</em>.  <em>key</em>, if provided, specifies a function of one argument that is
used to extract a comparison key from each element in the iterable:
<code class="docutils literal notranslate"><span class="pre">key=str.lower</span></code> Equivalent to:  <code class="docutils literal notranslate"><span class="pre">sorted(iterable,</span> <span class="pre">key=key,</span>
<span class="pre">reverse=True)[:n]</span></code></p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the optional <em>key</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="heapq.nsmallest">
<code class="descclassname">heapq.</code><code class="descname">nsmallest</code><span class="sig-paren">(</span><em>n</em>, <em>iterable</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#heapq.nsmallest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list with the <em>n</em> smallest elements from the dataset defined by
<em>iterable</em>.  <em>key</em>, if provided, specifies a function of one argument that is
used to extract a comparison key from each element in the iterable:
<code class="docutils literal notranslate"><span class="pre">key=str.lower</span></code> Equivalent to:  <code class="docutils literal notranslate"><span class="pre">sorted(iterable,</span> <span class="pre">key=key)[:n]</span></code></p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the optional <em>key</em> argument.</p>
</div>
</dd></dl>

<p>The latter two functions perform best for smaller values of <em>n</em>.  For larger
values, it is more efficient to use the <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function.  Also, when
<code class="docutils literal notranslate"><span class="pre">n==1</span></code>, it is more efficient to use the built-in <a class="reference internal" href="functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>
functions.  If repeated usage of these functions is required, consider turning
the iterable into an actual heap.</p>
<div class="section" id="basic-examples">
<h2>8.4.1. Basic Examples<a class="headerlink" href="#basic-examples" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference external" href="https://en.wikipedia.org/wiki/Heapsort">heapsort</a> can be implemented by
pushing all values onto a heap and then popping off the smallest values one at a
time:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">heapsort</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">h</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">heappush</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="p">[</span><span class="n">heappop</span><span class="p">(</span><span class="n">h</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">h</span><span class="p">))]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapsort</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<p>This is similar to <code class="docutils literal notranslate"><span class="pre">sorted(iterable)</span></code>, but unlike <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>, this
implementation is not stable.</p>
<p>Heap elements can be tuples.  This is useful for assigning comparison values
(such as task priorities) alongside the main record being tracked:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">h</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;write code&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;release product&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;write spec&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">h</span><span class="p">,</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;create tests&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappop</span><span class="p">(</span><span class="n">h</span><span class="p">)</span>
<span class="go">(1, &#39;write spec&#39;)</span>
</pre></div>
</div>
</div>
<div class="section" id="priority-queue-implementation-notes">
<h2>8.4.2. Priority Queue Implementation Notes<a class="headerlink" href="#priority-queue-implementation-notes" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference external" href="https://en.wikipedia.org/wiki/Priority_queue">priority queue</a> is common use
for a heap, and it presents several implementation challenges:</p>
<ul class="simple">
<li>Sort stability:  how do you get two tasks with equal priorities to be returned
in the order they were originally added?</li>
<li>In the future with Python 3, tuple comparison breaks for (priority, task)
pairs if the priorities are equal and the tasks do not have a default
comparison order.</li>
<li>If the priority of a task changes, how do you move it to a new position in
the heap?</li>
<li>Or if a pending task needs to be deleted, how do you find it and remove it
from the queue?</li>
</ul>
<p>A solution to the first two challenges is to store entries as 3-element list
including the priority, an entry count, and the task.  The entry count serves as
a tie-breaker so that two tasks with the same priority are returned in the order
they were added. And since no two entry counts are the same, the tuple
comparison will never attempt to directly compare two tasks.</p>
<p>The remaining challenges revolve around finding a pending task and making
changes to its priority or removing it entirely.  Finding a task can be done
with a dictionary pointing to an entry in the queue.</p>
<p>Removing the entry or changing its priority is more difficult because it would
break the heap structure invariants.  So, a possible solution is to mark the
existing entry as removed and add a new entry with the revised priority:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pq</span> <span class="o">=</span> <span class="p">[]</span>                         <span class="c1"># list of entries arranged in a heap</span>
<span class="n">entry_finder</span> <span class="o">=</span> <span class="p">{}</span>               <span class="c1"># mapping of tasks to entries</span>
<span class="n">REMOVED</span> <span class="o">=</span> <span class="s1">&#39;&lt;removed-task&gt;&#39;</span>      <span class="c1"># placeholder for a removed task</span>
<span class="n">counter</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">count</span><span class="p">()</span>     <span class="c1"># unique sequence count</span>

<span class="k">def</span> <span class="nf">add_task</span><span class="p">(</span><span class="n">task</span><span class="p">,</span> <span class="n">priority</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
    <span class="s1">&#39;Add a new task or update the priority of an existing task&#39;</span>
    <span class="k">if</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">entry_finder</span><span class="p">:</span>
        <span class="n">remove_task</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
    <span class="n">count</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">counter</span><span class="p">)</span>
    <span class="n">entry</span> <span class="o">=</span> <span class="p">[</span><span class="n">priority</span><span class="p">,</span> <span class="n">count</span><span class="p">,</span> <span class="n">task</span><span class="p">]</span>
    <span class="n">entry_finder</span><span class="p">[</span><span class="n">task</span><span class="p">]</span> <span class="o">=</span> <span class="n">entry</span>
    <span class="n">heappush</span><span class="p">(</span><span class="n">pq</span><span class="p">,</span> <span class="n">entry</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">remove_task</span><span class="p">(</span><span class="n">task</span><span class="p">):</span>
    <span class="s1">&#39;Mark an existing task as REMOVED.  Raise KeyError if not found.&#39;</span>
    <span class="n">entry</span> <span class="o">=</span> <span class="n">entry_finder</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>
    <span class="n">entry</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">REMOVED</span>

<span class="k">def</span> <span class="nf">pop_task</span><span class="p">():</span>
    <span class="s1">&#39;Remove and return the lowest priority task. Raise KeyError if empty.&#39;</span>
    <span class="k">while</span> <span class="n">pq</span><span class="p">:</span>
        <span class="n">priority</span><span class="p">,</span> <span class="n">count</span><span class="p">,</span> <span class="n">task</span> <span class="o">=</span> <span class="n">heappop</span><span class="p">(</span><span class="n">pq</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">task</span> <span class="ow">is</span> <span class="ow">not</span> <span class="n">REMOVED</span><span class="p">:</span>
            <span class="k">del</span> <span class="n">entry_finder</span><span class="p">[</span><span class="n">task</span><span class="p">]</span>
            <span class="k">return</span> <span class="n">task</span>
    <span class="k">raise</span> <span class="ne">KeyError</span><span class="p">(</span><span class="s1">&#39;pop from an empty priority queue&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="theory">
<h2>8.4.3. Theory<a class="headerlink" href="#theory" title="Permalink to this headline">¶</a></h2>
<p>Heaps are arrays for which <code class="docutils literal notranslate"><span class="pre">a[k]</span> <span class="pre">&lt;=</span> <span class="pre">a[2*k+1]</span></code> and <code class="docutils literal notranslate"><span class="pre">a[k]</span> <span class="pre">&lt;=</span> <span class="pre">a[2*k+2]</span></code> for all
<em>k</em>, counting elements from 0.  For the sake of comparison, non-existing
elements are considered to be infinite.  The interesting property of a heap is
that <code class="docutils literal notranslate"><span class="pre">a[0]</span></code> is always its smallest element.</p>
<p>The strange invariant above is meant to be an efficient memory representation
for a tournament.  The numbers below are <em>k</em>, not <code class="docutils literal notranslate"><span class="pre">a[k]</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>                               <span class="mi">0</span>

              <span class="mi">1</span>                                 <span class="mi">2</span>

      <span class="mi">3</span>               <span class="mi">4</span>                <span class="mi">5</span>               <span class="mi">6</span>

  <span class="mi">7</span>       <span class="mi">8</span>       <span class="mi">9</span>       <span class="mi">10</span>      <span class="mi">11</span>      <span class="mi">12</span>      <span class="mi">13</span>      <span class="mi">14</span>

<span class="mi">15</span> <span class="mi">16</span>   <span class="mi">17</span> <span class="mi">18</span>   <span class="mi">19</span> <span class="mi">20</span>   <span class="mi">21</span> <span class="mi">22</span>   <span class="mi">23</span> <span class="mi">24</span>   <span class="mi">25</span> <span class="mi">26</span>   <span class="mi">27</span> <span class="mi">28</span>   <span class="mi">29</span> <span class="mi">30</span>
</pre></div>
</div>
<p>In the tree above, each cell <em>k</em> is topping <code class="docutils literal notranslate"><span class="pre">2*k+1</span></code> and <code class="docutils literal notranslate"><span class="pre">2*k+2</span></code>. In a usual
binary tournament we see in sports, each cell is the winner over the two cells
it tops, and we can trace the winner down the tree to see all opponents s/he
had.  However, in many computer applications of such tournaments, we do not need
to trace the history of a winner. To be more memory efficient, when a winner is
promoted, we try to replace it by something else at a lower level, and the rule
becomes that a cell and the two cells it tops contain three different items, but
the top cell “wins” over the two topped cells.</p>
<p>If this heap invariant is protected at all time, index 0 is clearly the overall
winner.  The simplest algorithmic way to remove it and find the “next” winner is
to move some loser (let’s say cell 30 in the diagram above) into the 0 position,
and then percolate this new 0 down the tree, exchanging values, until the
invariant is re-established. This is clearly logarithmic on the total number of
items in the tree. By iterating over all items, you get an O(n log n) sort.</p>
<p>A nice feature of this sort is that you can efficiently insert new items while
the sort is going on, provided that the inserted items are not “better” than the
last 0’th element you extracted.  This is especially useful in simulation
contexts, where the tree holds all incoming events, and the “win” condition
means the smallest scheduled time.  When an event schedules other events for
execution, they are scheduled into the future, so they can easily go into the
heap.  So, a heap is a good structure for implementing schedulers (this is what
I used for my MIDI sequencer :-).</p>
<p>Various structures for implementing schedulers have been extensively studied,
and heaps are good for this, as they are reasonably speedy, the speed is almost
constant, and the worst case is not much different than the average case.
However, there are other representations which are more efficient overall, yet
the worst cases might be terrible.</p>
<p>Heaps are also very useful in big disk sorts.  You most probably all know that a
big sort implies producing “runs” (which are pre-sorted sequences, whose size is
usually related to the amount of CPU memory), followed by a merging passes for
these runs, which merging is often very cleverly organised <a class="footnote-reference" href="#id2" id="id1">[1]</a>. It is very
important that the initial sort produces the longest runs possible.  Tournaments
are a good way to achieve that.  If, using all the memory available to hold a
tournament, you replace and percolate items that happen to fit the current run,
you’ll produce runs which are twice the size of the memory for random input, and
much better for input fuzzily ordered.</p>
<p>Moreover, if you output the 0’th item on disk and get an input which may not fit
in the current tournament (because the value “wins” over the last output value),
it cannot fit in the heap, so the size of the heap decreases.  The freed memory
could be cleverly reused immediately for progressively building a second heap,
which grows at exactly the same rate the first heap is melting.  When the first
heap completely vanishes, you switch heaps and start a new run.  Clever and
quite effective!</p>
<p>In a word, heaps are useful memory structures to know.  I use them in a few
applications, and I think it is good to keep a ‘heap’ module around. :-)</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The disk balancing algorithms which are current, nowadays, are more annoying
than clever, and this is a consequence of the seeking capabilities of the disks.
On devices which cannot seek, like big tape drives, the story was quite
different, and one had to be very clever to ensure (far in advance) that each
tape movement will be the most effective possible (that is, will best
participate at “progressing” the merge).  Some tapes were even able to read
backwards, and this was also used to avoid the rewinding time. Believe me, real
good tape sorts were quite spectacular to watch! From all times, sorting has
always been a Great Art! :-)</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a><ul>
<li><a class="reference internal" href="#basic-examples">8.4.1. Basic Examples</a></li>
<li><a class="reference internal" href="#priority-queue-implementation-notes">8.4.2. Priority Queue Implementation Notes</a></li>
<li><a class="reference internal" href="#theory">8.4.3. Theory</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="collections.html"
                        title="previous chapter">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bisect.html"
                        title="next chapter">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/heapq.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bisect.html" title="8.5. bisect — Array bisection algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="collections.html" title="8.3. collections — High-performance container datatypes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\a�&8&8html/library/hmac.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14.2. hmac — Keyed-Hashing for Message Authentication &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14.3. md5 — MD5 message digest algorithm" href="md5.html" />
    <link rel="prev" title="14.1. hashlib — Secure hashes and message digests" href="hashlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/hmac.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="md5.html" title="14.3. md5 — MD5 message digest algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="hashlib.html" title="14.1. hashlib — Secure hashes and message digests"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" accesskey="U">14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-hmac">
<span id="hmac-keyed-hashing-for-message-authentication"></span><h1>14.2. <a class="reference internal" href="#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a> — Keyed-Hashing for Message Authentication<a class="headerlink" href="#module-hmac" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/hmac.py">Lib/hmac.py</a></p>
<hr class="docutils" />
<p>This module implements the HMAC algorithm as described by <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2104.html"><strong>RFC 2104</strong></a>.</p>
<dl class="function">
<dt id="hmac.new">
<code class="descclassname">hmac.</code><code class="descname">new</code><span class="sig-paren">(</span><em>key</em><span class="optional">[</span>, <em>msg</em><span class="optional">[</span>, <em>digestmod</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#hmac.new" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new hmac object.  If <em>msg</em> is present, the method call <code class="docutils literal notranslate"><span class="pre">update(msg)</span></code>
is made. <em>digestmod</em> is the digest constructor or module for the HMAC object to
use. It defaults to  the <code class="xref py py-data docutils literal notranslate"><span class="pre">hashlib.md5</span></code> constructor.</p>
</dd></dl>

<p>An HMAC object has the following methods:</p>
<dl class="method">
<dt id="hmac.HMAC.update">
<code class="descclassname">HMAC.</code><code class="descname">update</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#hmac.HMAC.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the hmac object with the string <em>msg</em>.  Repeated calls are equivalent to
a single call with the concatenation of all the arguments: <code class="docutils literal notranslate"><span class="pre">m.update(a);</span>
<span class="pre">m.update(b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.update(a</span> <span class="pre">+</span> <span class="pre">b)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="hmac.HMAC.digest">
<code class="descclassname">HMAC.</code><code class="descname">digest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hmac.HMAC.digest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the digest of the strings passed to the <a class="reference internal" href="#hmac.HMAC.update" title="hmac.HMAC.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> method so far.
This string will be the same length as the <em>digest_size</em> of the digest given to
the constructor.  It may contain non-ASCII characters, including NUL bytes.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">When comparing the output of <a class="reference internal" href="#hmac.HMAC.digest" title="hmac.HMAC.digest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code></a> to an externally-supplied
digest during a verification routine, it is recommended to use the
<a class="reference internal" href="#hmac.compare_digest" title="hmac.compare_digest"><code class="xref py py-func docutils literal notranslate"><span class="pre">compare_digest()</span></code></a> function instead of the <code class="docutils literal notranslate"><span class="pre">==</span></code> operator
to reduce the vulnerability to timing attacks.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="hmac.HMAC.hexdigest">
<code class="descclassname">HMAC.</code><code class="descname">hexdigest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hmac.HMAC.hexdigest" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#hmac.HMAC.digest" title="hmac.HMAC.digest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code></a> except the digest is returned as a string twice the length
containing only hexadecimal digits.  This may be used to exchange the value
safely in email or other non-binary environments.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">When comparing the output of <a class="reference internal" href="#hmac.HMAC.hexdigest" title="hmac.HMAC.hexdigest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">hexdigest()</span></code></a> to an externally-supplied
digest during a verification routine, it is recommended to use the
<a class="reference internal" href="#hmac.compare_digest" title="hmac.compare_digest"><code class="xref py py-func docutils literal notranslate"><span class="pre">compare_digest()</span></code></a> function instead of the <code class="docutils literal notranslate"><span class="pre">==</span></code> operator
to reduce the vulnerability to timing attacks.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="hmac.HMAC.copy">
<code class="descclassname">HMAC.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hmac.HMAC.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy (“clone”) of the hmac object.  This can be used to efficiently
compute the digests of strings that share a common initial substring.</p>
</dd></dl>

<p>This module also provides the following helper function:</p>
<dl class="function">
<dt id="hmac.compare_digest">
<code class="descclassname">hmac.</code><code class="descname">compare_digest</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#hmac.compare_digest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code>.  This function uses an approach designed to prevent
timing analysis by avoiding content-based short circuiting behaviour,
making it appropriate for cryptography.  <em>a</em> and <em>b</em> must both be of the
same type: either <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> or a <a class="reference internal" href="../glossary.html#term-bytes-like-object"><span class="xref std std-term">bytes-like object</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <em>a</em> and <em>b</em> are of different lengths, or if an error occurs,
a timing attack could theoretically reveal information about the
types and lengths of <em>a</em> and <em>b</em>—but not their values.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.7.</span></p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a></dt>
<dd>The Python module providing secure hash functions.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="hashlib.html"
                        title="previous chapter">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="md5.html"
                        title="next chapter">14.3. <code class="docutils literal notranslate"><span class="pre">md5</span></code> — MD5 message digest algorithm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/hmac.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="md5.html" title="14.3. md5 — MD5 message digest algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="hashlib.html" title="14.1. hashlib — Secure hashes and message digests"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" >14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�-�K�N�Nhtml/library/hotshot.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.5. hotshot — High performance logging profiler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.6. timeit — Measure execution time of small code snippets" href="timeit.html" />
    <link rel="prev" title="26.4. The Python Profilers" href="profile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/hotshot.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="timeit.html" title="26.6. timeit — Measure execution time of small code snippets"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="profile.html" title="26.4. The Python Profilers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-hotshot">
<span id="hotshot-high-performance-logging-profiler"></span><h1>26.5. <a class="reference internal" href="#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> — High performance logging profiler<a class="headerlink" href="#module-hotshot" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>This module provides a nicer interface to the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_hotshot</span></code> C module. Hotshot
is a replacement for the existing <a class="reference internal" href="profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module. As it’s written mostly
in C, it should result in a much smaller performance impact than the existing
<a class="reference internal" href="profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> module focuses on minimizing the overhead while profiling, at
the expense of long data post-processing times. For common usage it is
recommended to use <a class="reference internal" href="profile.html#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> instead. <a class="reference internal" href="#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> is not maintained and
might be removed from the standard library in the future.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The results should be more meaningful than in the past: the timing core
contained a critical bug.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> profiler does not yet work well with threads. It is useful to
use an unthreaded script to run the profiler over the code you’re interested in
measuring if at all possible.</p>
</div>
<dl class="class">
<dt id="hotshot.Profile">
<em class="property">class </em><code class="descclassname">hotshot.</code><code class="descname">Profile</code><span class="sig-paren">(</span><em>logfile</em><span class="optional">[</span>, <em>lineevents</em><span class="optional">[</span>, <em>linetimings</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile" title="Permalink to this definition">¶</a></dt>
<dd><p>The profiler object. The argument <em>logfile</em> is the name of a log file to use for
logged profile data. The argument <em>lineevents</em> specifies whether to generate
events for every source line, or just on function call/return. It defaults to
<code class="docutils literal notranslate"><span class="pre">0</span></code> (only log function call/return). The argument <em>linetimings</em> specifies
whether to record timing information. It defaults to <code class="docutils literal notranslate"><span class="pre">1</span></code> (store timing
information).</p>
</dd></dl>

<div class="section" id="profile-objects">
<span id="hotshot-objects"></span><h2>26.5.1. Profile Objects<a class="headerlink" href="#profile-objects" title="Permalink to this headline">¶</a></h2>
<p>Profile objects have the following methods:</p>
<dl class="method">
<dt id="hotshot.Profile.addinfo">
<code class="descclassname">Profile.</code><code class="descname">addinfo</code><span class="sig-paren">(</span><em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.addinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an arbitrary labelled value to the profile output.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.close">
<code class="descclassname">Profile.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the logfile and terminate the profiler.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.fileno">
<code class="descclassname">Profile.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor of the profiler’s log file.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.run">
<code class="descclassname">Profile.</code><code class="descname">run</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Profile an <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>-compatible string in the script environment. The
globals from the <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module are used as both the globals and locals
for the script.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.runcall">
<code class="descclassname">Profile.</code><code class="descname">runcall</code><span class="sig-paren">(</span><em>func</em>, <em>*args</em>, <em>**keywords</em><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.runcall" title="Permalink to this definition">¶</a></dt>
<dd><p>Profile a single call of a callable. Additional positional and keyword arguments
may be passed along; the result of the call is returned, and exceptions are
allowed to propagate cleanly, while ensuring that profiling is disabled on the
way out.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.runctx">
<code class="descclassname">Profile.</code><code class="descname">runctx</code><span class="sig-paren">(</span><em>cmd</em>, <em>globals</em>, <em>locals</em><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.runctx" title="Permalink to this definition">¶</a></dt>
<dd><p>Evaluate an <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>-compatible string in a specific environment. The
string is compiled before profiling begins.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.start">
<code class="descclassname">Profile.</code><code class="descname">start</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Start the profiler.</p>
</dd></dl>

<dl class="method">
<dt id="hotshot.Profile.stop">
<code class="descclassname">Profile.</code><code class="descname">stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.Profile.stop" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the profiler.</p>
</dd></dl>

</div>
<div class="section" id="module-hotshot.stats">
<span id="using-hotshot-data"></span><h2>26.5.2. Using hotshot data<a class="headerlink" href="#module-hotshot.stats" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>This module loads hotshot profiling data into the standard <a class="reference internal" href="profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> Stats
objects.</p>
<dl class="function">
<dt id="hotshot.stats.load">
<code class="descclassname">hotshot.stats.</code><code class="descname">load</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#hotshot.stats.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Load hotshot data from <em>filename</em>. Returns an instance of the
<a class="reference internal" href="profile.html#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a> class.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a></dt>
<dd>The <a class="reference internal" href="profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> class</dd>
</dl>
</div>
</div>
<div class="section" id="example-usage">
<span id="hotshot-example"></span><h2>26.5.3. Example Usage<a class="headerlink" href="#example-usage" title="Permalink to this headline">¶</a></h2>
<p>Note that this example runs the Python “benchmark” pystones.  It can take some
time to run, and will produce large output files.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">hotshot</span><span class="o">,</span> <span class="nn">hotshot.stats</span><span class="o">,</span> <span class="nn">test.pystone</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prof</span> <span class="o">=</span> <span class="n">hotshot</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="s2">&quot;stones.prof&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">benchtime</span><span class="p">,</span> <span class="n">stones</span> <span class="o">=</span> <span class="n">prof</span><span class="o">.</span><span class="n">runcall</span><span class="p">(</span><span class="n">test</span><span class="o">.</span><span class="n">pystone</span><span class="o">.</span><span class="n">pystones</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prof</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span> <span class="o">=</span> <span class="n">hotshot</span><span class="o">.</span><span class="n">stats</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="s2">&quot;stones.prof&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="o">.</span><span class="n">strip_dirs</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">,</span> <span class="s1">&#39;calls&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span>
<span class="go">         850004 function calls in 10.090 CPU seconds</span>

<span class="go">   Ordered by: internal time, call count</span>

<span class="go">   ncalls  tottime  percall  cumtime  percall filename:lineno(function)</span>
<span class="go">        1    3.295    3.295   10.090   10.090 pystone.py:79(Proc0)</span>
<span class="go">   150000    1.315    0.000    1.315    0.000 pystone.py:203(Proc7)</span>
<span class="go">    50000    1.313    0.000    1.463    0.000 pystone.py:229(Func2)</span>
<span class="go"> .</span>
<span class="go"> .</span>
<span class="go"> .</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a><ul>
<li><a class="reference internal" href="#profile-objects">26.5.1. Profile Objects</a></li>
<li><a class="reference internal" href="#module-hotshot.stats">26.5.2. Using hotshot data</a></li>
<li><a class="reference internal" href="#example-usage">26.5.3. Example Usage</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="profile.html"
                        title="previous chapter">26.4. The Python Profilers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="timeit.html"
                        title="next chapter">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/hotshot.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="timeit.html" title="26.6. timeit — Measure execution time of small code snippets"
             >next</a> |</li>
        <li class="right" >
          <a href="profile.html" title="26.4. The Python Profilers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�蒙"l"lhtml/library/htmllib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.3. htmllib — A parser for HTML documents &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.5. XML Processing Modules" href="xml.html" />
    <link rel="prev" title="19.2. sgmllib — Simple SGML parser" href="sgmllib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/htmllib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.html" title="19.5. XML Processing Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sgmllib.html" title="19.2. sgmllib — Simple SGML parser"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-htmllib">
<span id="htmllib-a-parser-for-html-documents"></span><h1>19.3. <a class="reference internal" href="#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> — A parser for HTML documents<a class="headerlink" href="#module-htmllib" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> module has been removed in Python 3.
Use <a class="reference internal" href="htmlparser.html#module-HTMLParser" title="HTMLParser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> instead in Python 2, and the equivalent,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">html.parser</span></code>, in Python 3.</p>
</div>
<span class="target" id="index-0"></span><p id="index-1">This module defines a class which can serve as a base for parsing text files
formatted in the HyperText Mark-up Language (HTML).  The class is not directly
concerned with I/O — it must be provided with input in string form via a
method, and makes calls to methods of a “formatter” object in order to produce
output.  The <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class is designed to be used as a base class
for other classes in order to add functionality, and allows most of its methods
to be extended or overridden.  In turn, this class is derived from and extends
the <code class="xref py py-class docutils literal notranslate"><span class="pre">SGMLParser</span></code> class defined in module <a class="reference internal" href="sgmllib.html#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a>.  The
<a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> implementation supports the HTML 2.0 language as described
in <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1866.html"><strong>RFC 1866</strong></a>.  Two implementations of formatter objects are provided in the
<a class="reference internal" href="formatter.html#module-formatter" title="formatter: Generic output formatter and device interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">formatter</span></code></a> module; refer to the documentation for that module for
information on the formatter interface.</p>
<p>The following is a summary of the interface defined by
<a class="reference internal" href="sgmllib.html#sgmllib.SGMLParser" title="sgmllib.SGMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">sgmllib.SGMLParser</span></code></a>:</p>
<ul>
<li><p class="first">The interface to feed data to an instance is through the <code class="xref py py-meth docutils literal notranslate"><span class="pre">feed()</span></code> method,
which takes a string argument.  This can be called with as little or as much
text at a time as desired; <code class="docutils literal notranslate"><span class="pre">p.feed(a);</span> <span class="pre">p.feed(b)</span></code> has the same effect as
<code class="docutils literal notranslate"><span class="pre">p.feed(a+b)</span></code>.  When the data contains complete HTML markup constructs, these
are processed immediately; incomplete constructs are saved in a buffer.  To
force processing of all unprocessed data, call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method.</p>
<p>For example, to parse the entire contents of a file, use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.html&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
<span class="n">parser</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</li>
<li><p class="first">The interface to define semantics for HTML tags is very simple: derive a class
and define methods called <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code>, or <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code>.
The parser will call these at appropriate moments: <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> or
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code> is called when an opening tag of the form <code class="docutils literal notranslate"><span class="pre">&lt;tag</span> <span class="pre">...&gt;</span></code> is
encountered; <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code> is called when a closing tag of the form <code class="docutils literal notranslate"><span class="pre">&lt;tag&gt;</span></code>
is encountered.  If an opening tag requires a corresponding closing tag, like
<code class="docutils literal notranslate"><span class="pre">&lt;H1&gt;</span></code> … <code class="docutils literal notranslate"><span class="pre">&lt;/H1&gt;</span></code>, the class should define the <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> method; if
a tag requires no closing tag, like <code class="docutils literal notranslate"><span class="pre">&lt;P&gt;</span></code>, the class should define the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code> method.</p>
</li>
</ul>
<p>The module defines a parser class and an exception:</p>
<dl class="class">
<dt id="htmllib.HTMLParser">
<em class="property">class </em><code class="descclassname">htmllib.</code><code class="descname">HTMLParser</code><span class="sig-paren">(</span><em>formatter</em><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the basic HTML parser class.  It supports all entity names required by
the XHTML 1.0 Recommendation (<a class="reference external" href="https://www.w3.org/TR/xhtml1">https://www.w3.org/TR/xhtml1</a>).   It also defines
handlers for all HTML 2.0 and many HTML 3.0 and 3.2 elements.</p>
</dd></dl>

<dl class="exception">
<dt id="htmllib.HTMLParseError">
<em class="property">exception </em><code class="descclassname">htmllib.</code><code class="descname">HTMLParseError</code><a class="headerlink" href="#htmllib.HTMLParseError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by the <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class when it encounters an error
while parsing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="formatter.html#module-formatter" title="formatter: Generic output formatter and device interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">formatter</span></code></a></dt>
<dd>Interface definition for transforming an abstract flow of formatting events into
specific output events on writer objects.</dd>
<dt>Module <a class="reference internal" href="htmlparser.html#module-HTMLParser" title="HTMLParser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal notranslate"><span class="pre">HTMLParser</span></code></a></dt>
<dd>Alternate HTML parser that offers a slightly lower-level view of the input, but
is designed to work with XHTML, and does not implement some of the SGML syntax
not used in “HTML as deployed” and which isn’t legal for XHTML.</dd>
<dt>Module <a class="reference internal" href="#module-htmlentitydefs" title="htmlentitydefs: Definitions of HTML general entities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmlentitydefs</span></code></a></dt>
<dd>Definition of replacement text for XHTML 1.0  entities.</dd>
<dt>Module <a class="reference internal" href="sgmllib.html#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a></dt>
<dd>Base class for <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a>.</dd>
</dl>
</div>
<div class="section" id="htmlparser-objects">
<span id="html-parser-objects"></span><h2>19.3.1. HTMLParser Objects<a class="headerlink" href="#htmlparser-objects" title="Permalink to this headline">¶</a></h2>
<p>In addition to tag methods, the <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class provides some
additional methods and instance variables for use within tag methods.</p>
<dl class="attribute">
<dt id="htmllib.HTMLParser.formatter">
<code class="descclassname">HTMLParser.</code><code class="descname">formatter</code><a class="headerlink" href="#htmllib.HTMLParser.formatter" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the formatter instance associated with the parser.</p>
</dd></dl>

<dl class="attribute">
<dt id="htmllib.HTMLParser.nofill">
<code class="descclassname">HTMLParser.</code><code class="descname">nofill</code><a class="headerlink" href="#htmllib.HTMLParser.nofill" title="Permalink to this definition">¶</a></dt>
<dd><p>Boolean flag which should be true when whitespace should not be collapsed, or
false when it should be.  In general, this should only be true when character
data is to be treated as “preformatted” text, as within a <code class="docutils literal notranslate"><span class="pre">&lt;PRE&gt;</span></code> element.
The default value is false.  This affects the operation of <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_data()</span></code>
and <a class="reference internal" href="#htmllib.HTMLParser.save_end" title="htmllib.HTMLParser.save_end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_end()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="htmllib.HTMLParser.anchor_bgn">
<code class="descclassname">HTMLParser.</code><code class="descname">anchor_bgn</code><span class="sig-paren">(</span><em>href</em>, <em>name</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser.anchor_bgn" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called at the start of an anchor region.  The arguments
correspond to the attributes of the <code class="docutils literal notranslate"><span class="pre">&lt;A&gt;</span></code> tag with the same names.  The
default implementation maintains a list of hyperlinks (defined by the <code class="docutils literal notranslate"><span class="pre">HREF</span></code>
attribute for <code class="docutils literal notranslate"><span class="pre">&lt;A&gt;</span></code> tags) within the document.  The list of hyperlinks is
available as the data attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">anchorlist</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="htmllib.HTMLParser.anchor_end">
<code class="descclassname">HTMLParser.</code><code class="descname">anchor_end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser.anchor_end" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called at the end of an anchor region.  The default
implementation adds a textual footnote marker using an index into the list of
hyperlinks created by <a class="reference internal" href="#htmllib.HTMLParser.anchor_bgn" title="htmllib.HTMLParser.anchor_bgn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">anchor_bgn()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="htmllib.HTMLParser.handle_image">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_image</code><span class="sig-paren">(</span><em>source</em>, <em>alt</em><span class="optional">[</span>, <em>ismap</em><span class="optional">[</span>, <em>align</em><span class="optional">[</span>, <em>width</em><span class="optional">[</span>, <em>height</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser.handle_image" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle images.  The default implementation simply
passes the <em>alt</em> value to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_data()</span></code> method.</p>
</dd></dl>

<dl class="method">
<dt id="htmllib.HTMLParser.save_bgn">
<code class="descclassname">HTMLParser.</code><code class="descname">save_bgn</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser.save_bgn" title="Permalink to this definition">¶</a></dt>
<dd><p>Begins saving character data in a buffer instead of sending it to the formatter
object.  Retrieve the stored data via <a class="reference internal" href="#htmllib.HTMLParser.save_end" title="htmllib.HTMLParser.save_end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_end()</span></code></a>. Use of the
<a class="reference internal" href="#htmllib.HTMLParser.save_bgn" title="htmllib.HTMLParser.save_bgn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_bgn()</span></code></a> / <a class="reference internal" href="#htmllib.HTMLParser.save_end" title="htmllib.HTMLParser.save_end"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_end()</span></code></a> pair may not be nested.</p>
</dd></dl>

<dl class="method">
<dt id="htmllib.HTMLParser.save_end">
<code class="descclassname">HTMLParser.</code><code class="descname">save_end</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#htmllib.HTMLParser.save_end" title="Permalink to this definition">¶</a></dt>
<dd><p>Ends buffering character data and returns all data saved since the preceding
call to <a class="reference internal" href="#htmllib.HTMLParser.save_bgn" title="htmllib.HTMLParser.save_bgn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_bgn()</span></code></a>.  If the <a class="reference internal" href="#htmllib.HTMLParser.nofill" title="htmllib.HTMLParser.nofill"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nofill</span></code></a> flag is false, whitespace is
collapsed to single spaces.  A call to this method without a preceding call to
<a class="reference internal" href="#htmllib.HTMLParser.save_bgn" title="htmllib.HTMLParser.save_bgn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">save_bgn()</span></code></a> will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</dd></dl>

</div>
</div>
<div class="section" id="module-htmlentitydefs">
<span id="htmlentitydefs-definitions-of-html-general-entities"></span><h1>19.4. <a class="reference internal" href="#module-htmlentitydefs" title="htmlentitydefs: Definitions of HTML general entities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmlentitydefs</span></code></a> — Definitions of HTML general entities<a class="headerlink" href="#module-htmlentitydefs" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-htmlentitydefs" title="htmlentitydefs: Definitions of HTML general entities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmlentitydefs</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">html.entities</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/htmlentitydefs.py">Lib/htmlentitydefs.py</a></p>
<hr class="docutils" />
<p>This module defines three dictionaries, <code class="docutils literal notranslate"><span class="pre">name2codepoint</span></code>, <code class="docutils literal notranslate"><span class="pre">codepoint2name</span></code>,
and <code class="docutils literal notranslate"><span class="pre">entitydefs</span></code>. <code class="docutils literal notranslate"><span class="pre">entitydefs</span></code> is used by the <a class="reference internal" href="#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> module to
provide the <a class="reference internal" href="#htmlentitydefs.entitydefs" title="htmlentitydefs.entitydefs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">entitydefs</span></code></a> attribute of the <a class="reference internal" href="htmlparser.html#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class.  The
definition provided here contains all the entities defined by XHTML 1.0  that
can be handled using simple textual substitution in the Latin-1 character set
(ISO-8859-1).</p>
<dl class="data">
<dt id="htmlentitydefs.entitydefs">
<code class="descclassname">htmlentitydefs.</code><code class="descname">entitydefs</code><a class="headerlink" href="#htmlentitydefs.entitydefs" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping XHTML 1.0 entity definitions to their replacement text in
ISO Latin-1.</p>
</dd></dl>

<dl class="data">
<dt id="htmlentitydefs.name2codepoint">
<code class="descclassname">htmlentitydefs.</code><code class="descname">name2codepoint</code><a class="headerlink" href="#htmlentitydefs.name2codepoint" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary that maps HTML entity names to the Unicode code points.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="htmlentitydefs.codepoint2name">
<code class="descclassname">htmlentitydefs.</code><code class="descname">codepoint2name</code><a class="headerlink" href="#htmlentitydefs.codepoint2name" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary that maps Unicode code points to HTML entity names.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a><ul>
<li><a class="reference internal" href="#htmlparser-objects">19.3.1. HTMLParser Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-htmlentitydefs">19.4. <code class="docutils literal notranslate"><span class="pre">htmlentitydefs</span></code> — Definitions of HTML general entities</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sgmllib.html"
                        title="previous chapter">19.2. <code class="docutils literal notranslate"><span class="pre">sgmllib</span></code> — Simple SGML parser</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.html"
                        title="next chapter">19.5. XML Processing Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/htmllib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.html" title="19.5. XML Processing Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="sgmllib.html" title="19.2. sgmllib — Simple SGML parser"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\������html/library/htmlparser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.1. HTMLParser — Simple HTML and XHTML parser &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.2. sgmllib — Simple SGML parser" href="sgmllib.html" />
    <link rel="prev" title="19. Structured Markup Processing Tools" href="markup.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/htmlparser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sgmllib.html" title="19.2. sgmllib — Simple SGML parser"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="markup.html" title="19. Structured Markup Processing Tools"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-HTMLParser">
<span id="htmlparser-simple-html-and-xhtml-parser"></span><h1>19.1. <a class="reference internal" href="#module-HTMLParser" title="HTMLParser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> — Simple HTML and XHTML parser<a class="headerlink" href="#module-HTMLParser" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-HTMLParser" title="HTMLParser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">html.parser</span></code> in Python
3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/HTMLParser.py">Lib/HTMLParser.py</a></p>
<hr class="docutils" />
<p>This module defines a class <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> which serves as the basis for
parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
Unlike the parser in <a class="reference internal" href="htmllib.html#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a>, this parser is not based on the SGML parser
in <a class="reference internal" href="sgmllib.html#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a>.</p>
<dl class="class">
<dt id="HTMLParser.HTMLParser">
<em class="property">class </em><code class="descclassname">HTMLParser.</code><code class="descname">HTMLParser</code><a class="headerlink" href="#HTMLParser.HTMLParser" title="Permalink to this definition">¶</a></dt>
<dd><p>An <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> instance is fed HTML data and calls handler methods
when start tags, end tags, text, comments, and other markup elements are
encountered.  The user should subclass <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> and override its
methods to implement the desired behavior.</p>
<p>The <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class is instantiated without arguments.</p>
<p>Unlike the parser in <a class="reference internal" href="htmllib.html#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a>, this parser does not check that end tags
match start tags or call the end-tag handler for elements which are closed
implicitly by closing an outer element.</p>
</dd></dl>

<p>An exception is defined as well:</p>
<dl class="exception">
<dt id="HTMLParser.HTMLParseError">
<em class="property">exception </em><code class="descclassname">HTMLParser.</code><code class="descname">HTMLParseError</code><a class="headerlink" href="#HTMLParser.HTMLParseError" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> is able to handle broken markup, but in some cases it
might raise this exception when it encounters an error while parsing.
This exception provides three attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">msg</span></code> is a brief
message explaining the error, <code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code> is the number of the line on
which the broken construct was detected, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">offset</span></code> is the number of
characters into the line at which the construct starts.</p>
</dd></dl>

<div class="section" id="example-html-parser-application">
<h2>19.1.1. Example HTML Parser Application<a class="headerlink" href="#example-html-parser-application" title="Permalink to this headline">¶</a></h2>
<p>As a basic example, below is a simple HTML parser that uses the
<a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class to print out start tags, end tags and data
as they are encountered:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">HTMLParser</span> <span class="k">import</span> <span class="n">HTMLParser</span>

<span class="c1"># create a subclass and override the handler methods</span>
<span class="k">class</span> <span class="nc">MyHTMLParser</span><span class="p">(</span><span class="n">HTMLParser</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">handle_starttag</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Encountered a start tag:&quot;</span><span class="p">,</span> <span class="n">tag</span>

    <span class="k">def</span> <span class="nf">handle_endtag</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Encountered an end tag :&quot;</span><span class="p">,</span> <span class="n">tag</span>

    <span class="k">def</span> <span class="nf">handle_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Encountered some data  :&quot;</span><span class="p">,</span> <span class="n">data</span>

<span class="c1"># instantiate the parser and fed it some HTML</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">MyHTMLParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;html&gt;&lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt;&#39;</span>
            <span class="s1">&#39;&lt;body&gt;&lt;h1&gt;Parse me!&lt;/h1&gt;&lt;/body&gt;&lt;/html&gt;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The output will then be:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>Encountered a start tag: html
Encountered a start tag: head
Encountered a start tag: title
Encountered some data  : Test
Encountered an end tag : title
Encountered an end tag : head
Encountered a start tag: body
Encountered a start tag: h1
Encountered some data  : Parse me!
Encountered an end tag : h1
Encountered an end tag : body
Encountered an end tag : html
</pre></div>
</div>
</div>
<div class="section" id="htmlparser-methods">
<h2>19.1.2. <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> Methods<a class="headerlink" href="#htmlparser-methods" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="HTMLParser.HTMLParser.feed">
<code class="descclassname">HTMLParser.</code><code class="descname">feed</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.feed" title="Permalink to this definition">¶</a></dt>
<dd><p>Feed some text to the parser.  It is processed insofar as it consists of
complete elements; incomplete data is buffered until more data is fed or
<a class="reference internal" href="#HTMLParser.HTMLParser.close" title="HTMLParser.HTMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> is called.  <em>data</em> can be either <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> or
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, but passing <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> is advised.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.close">
<code class="descclassname">HTMLParser.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Force processing of all buffered data as if it were followed by an end-of-file
mark.  This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
the <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> base class method <a class="reference internal" href="#HTMLParser.HTMLParser.close" title="HTMLParser.HTMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.reset">
<code class="descclassname">HTMLParser.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the instance.  Loses all unprocessed data.  This is called implicitly at
instantiation time.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.getpos">
<code class="descclassname">HTMLParser.</code><code class="descname">getpos</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.getpos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current line number and offset.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.get_starttag_text">
<code class="descclassname">HTMLParser.</code><code class="descname">get_starttag_text</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.get_starttag_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the text of the most recently opened start tag.  This should not normally
be needed for structured processing, but may be useful in dealing with HTML “as
deployed” or for re-generating input with minimal changes (whitespace between
attributes can be preserved, etc.).</p>
</dd></dl>

<p>The following methods are called when data or markup elements are encountered
and they are meant to be overridden in a subclass.  The base class
implementations do nothing (except for <a class="reference internal" href="#HTMLParser.HTMLParser.handle_startendtag" title="HTMLParser.HTMLParser.handle_startendtag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_startendtag()</span></code></a>):</p>
<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_starttag">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_starttag</code><span class="sig-paren">(</span><em>tag</em>, <em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_starttag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle the start of a tag (e.g. <code class="docutils literal notranslate"><span class="pre">&lt;div</span> <span class="pre">id=&quot;main&quot;&gt;</span></code>).</p>
<p>The <em>tag</em> argument is the name of the tag converted to lower case. The <em>attrs</em>
argument is a list of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> pairs containing the attributes found
inside the tag’s <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> brackets.  The <em>name</em> will be translated to lower case,
and quotes in the <em>value</em> have been removed, and character and entity references
have been replaced.</p>
<p>For instance, for the tag <code class="docutils literal notranslate"><span class="pre">&lt;A</span> <span class="pre">HREF=&quot;https://www.cwi.nl/&quot;&gt;</span></code>, this method
would be called as <code class="docutils literal notranslate"><span class="pre">handle_starttag('a',</span> <span class="pre">[('href',</span> <span class="pre">'https://www.cwi.nl/')])</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>All entity references from <a class="reference internal" href="htmllib.html#module-htmlentitydefs" title="htmlentitydefs: Definitions of HTML general entities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmlentitydefs</span></code></a> are now replaced in the
attribute values.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_endtag">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_endtag</code><span class="sig-paren">(</span><em>tag</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_endtag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle the end tag of an element (e.g. <code class="docutils literal notranslate"><span class="pre">&lt;/div&gt;</span></code>).</p>
<p>The <em>tag</em> argument is the name of the tag converted to lower case.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_startendtag">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_startendtag</code><span class="sig-paren">(</span><em>tag</em>, <em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_startendtag" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#HTMLParser.HTMLParser.handle_starttag" title="HTMLParser.HTMLParser.handle_starttag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_starttag()</span></code></a>, but called when the parser encounters an
XHTML-style empty tag (<code class="docutils literal notranslate"><span class="pre">&lt;img</span> <span class="pre">...</span> <span class="pre">/&gt;</span></code>).  This method may be overridden by
subclasses which require this particular lexical information; the default
implementation simply calls <a class="reference internal" href="#HTMLParser.HTMLParser.handle_starttag" title="HTMLParser.HTMLParser.handle_starttag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_starttag()</span></code></a> and <a class="reference internal" href="#HTMLParser.HTMLParser.handle_endtag" title="HTMLParser.HTMLParser.handle_endtag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_endtag()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_data">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_data" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process arbitrary data (e.g. text nodes and the
content of <code class="docutils literal notranslate"><span class="pre">&lt;script&gt;...&lt;/script&gt;</span></code> and <code class="docutils literal notranslate"><span class="pre">&lt;style&gt;...&lt;/style&gt;</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_entityref">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_entityref</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_entityref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process a named character reference of the form
<code class="docutils literal notranslate"><span class="pre">&amp;name;</span></code> (e.g. <code class="docutils literal notranslate"><span class="pre">&amp;gt;</span></code>), where <em>name</em> is a general entity reference
(e.g. <code class="docutils literal notranslate"><span class="pre">'gt'</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_charref">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_charref</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_charref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process decimal and hexadecimal numeric character
references of the form <code class="docutils literal notranslate"><span class="pre">&amp;#NNN;</span></code> and <code class="docutils literal notranslate"><span class="pre">&amp;#xNNN;</span></code>.  For example, the decimal
equivalent for <code class="docutils literal notranslate"><span class="pre">&amp;gt;</span></code> is <code class="docutils literal notranslate"><span class="pre">&amp;#62;</span></code>, whereas the hexadecimal is <code class="docutils literal notranslate"><span class="pre">&amp;#x3E;</span></code>;
in this case the method will receive <code class="docutils literal notranslate"><span class="pre">'62'</span></code> or <code class="docutils literal notranslate"><span class="pre">'x3E'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_comment">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_comment</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_comment" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when a comment is encountered (e.g. <code class="docutils literal notranslate"><span class="pre">&lt;!--comment--&gt;</span></code>).</p>
<p>For example, the comment <code class="docutils literal notranslate"><span class="pre">&lt;!--</span> <span class="pre">comment</span> <span class="pre">--&gt;</span></code> will cause this method to be
called with the argument <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">comment</span> <span class="pre">'</span></code>.</p>
<p>The content of Internet Explorer conditional comments (condcoms) will also be
sent to this method, so, for <code class="docutils literal notranslate"><span class="pre">&lt;!--[if</span> <span class="pre">IE</span> <span class="pre">9]&gt;IE9-specific</span> <span class="pre">content&lt;![endif]--&gt;</span></code>,
this method will receive <code class="docutils literal notranslate"><span class="pre">'[if</span> <span class="pre">IE</span> <span class="pre">9]&gt;IE9-specific</span> <span class="pre">content&lt;![endif]'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_decl">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_decl</code><span class="sig-paren">(</span><em>decl</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_decl" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle an HTML doctype declaration (e.g.
<code class="docutils literal notranslate"><span class="pre">&lt;!DOCTYPE</span> <span class="pre">html&gt;</span></code>).</p>
<p>The <em>decl</em> parameter will be the entire contents of the declaration inside
the <code class="docutils literal notranslate"><span class="pre">&lt;!...&gt;</span></code> markup (e.g. <code class="docutils literal notranslate"><span class="pre">'DOCTYPE</span> <span class="pre">html'</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.handle_pi">
<code class="descclassname">HTMLParser.</code><code class="descname">handle_pi</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.handle_pi" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when a processing instruction is encountered.  The <em>data</em>
parameter will contain the entire processing instruction.  For example, for the
processing instruction <code class="docutils literal notranslate"><span class="pre">&lt;?proc</span> <span class="pre">color='red'&gt;</span></code>, this method would be called as
<code class="docutils literal notranslate"><span class="pre">handle_pi(&quot;proc</span> <span class="pre">color='red'&quot;)</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#HTMLParser.HTMLParser" title="HTMLParser.HTMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> class uses the SGML syntactic rules for processing
instructions.  An XHTML processing instruction using the trailing <code class="docutils literal notranslate"><span class="pre">'?'</span></code> will
cause the <code class="docutils literal notranslate"><span class="pre">'?'</span></code> to be included in <em>data</em>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="HTMLParser.HTMLParser.unknown_decl">
<code class="descclassname">HTMLParser.</code><code class="descname">unknown_decl</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#HTMLParser.HTMLParser.unknown_decl" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when an unrecognized declaration is read by the parser.</p>
<p>The <em>data</em> parameter will be the entire contents of the declaration inside
the <code class="docutils literal notranslate"><span class="pre">&lt;![...]&gt;</span></code> markup.  It is sometimes useful to be overridden by a
derived class.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="htmlparser-examples"></span><h2>19.1.3. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>The following class implements a parser that will be used to illustrate more
examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">HTMLParser</span> <span class="k">import</span> <span class="n">HTMLParser</span>
<span class="kn">from</span> <span class="nn">htmlentitydefs</span> <span class="k">import</span> <span class="n">name2codepoint</span>

<span class="k">class</span> <span class="nc">MyHTMLParser</span><span class="p">(</span><span class="n">HTMLParser</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">handle_starttag</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Start tag:&quot;</span><span class="p">,</span> <span class="n">tag</span>
        <span class="k">for</span> <span class="n">attr</span> <span class="ow">in</span> <span class="n">attrs</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s2">&quot;     attr:&quot;</span><span class="p">,</span> <span class="n">attr</span>

    <span class="k">def</span> <span class="nf">handle_endtag</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;End tag  :&quot;</span><span class="p">,</span> <span class="n">tag</span>

    <span class="k">def</span> <span class="nf">handle_data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Data     :&quot;</span><span class="p">,</span> <span class="n">data</span>

    <span class="k">def</span> <span class="nf">handle_comment</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Comment  :&quot;</span><span class="p">,</span> <span class="n">data</span>

    <span class="k">def</span> <span class="nf">handle_entityref</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="n">c</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="n">name2codepoint</span><span class="p">[</span><span class="n">name</span><span class="p">])</span>
        <span class="nb">print</span> <span class="s2">&quot;Named ent:&quot;</span><span class="p">,</span> <span class="n">c</span>

    <span class="k">def</span> <span class="nf">handle_charref</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">name</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">):</span>
            <span class="n">c</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">name</span><span class="p">[</span><span class="mi">1</span><span class="p">:],</span> <span class="mi">16</span><span class="p">))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">c</span> <span class="o">=</span> <span class="n">unichr</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">name</span><span class="p">))</span>
        <span class="nb">print</span> <span class="s2">&quot;Num ent  :&quot;</span><span class="p">,</span> <span class="n">c</span>

    <span class="k">def</span> <span class="nf">handle_decl</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;Decl     :&quot;</span><span class="p">,</span> <span class="n">data</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">MyHTMLParser</span><span class="p">()</span>
</pre></div>
</div>
<p>Parsing a doctype:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &#39;</span>
<span class="gp">... </span>            <span class="s1">&#39;&quot;http://www.w3.org/TR/html4/strict.dtd&quot;&gt;&#39;</span><span class="p">)</span>
<span class="go">Decl     : DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01//EN&quot; &quot;http://www.w3.org/TR/html4/strict.dtd&quot;</span>
</pre></div>
</div>
<p>Parsing an element with a few attributes and a title:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;img src=&quot;python-logo.png&quot; alt=&quot;The Python logo&quot;&gt;&#39;</span><span class="p">)</span>
<span class="go">Start tag: img</span>
<span class="go">     attr: (&#39;src&#39;, &#39;python-logo.png&#39;)</span>
<span class="go">     attr: (&#39;alt&#39;, &#39;The Python logo&#39;)</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;h1&gt;Python&lt;/h1&gt;&#39;</span><span class="p">)</span>
<span class="go">Start tag: h1</span>
<span class="go">Data     : Python</span>
<span class="go">End tag  : h1</span>
</pre></div>
</div>
<p>The content of <code class="docutils literal notranslate"><span class="pre">script</span></code> and <code class="docutils literal notranslate"><span class="pre">style</span></code> elements is returned as is, without
further parsing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;style type=&quot;text/css&quot;&gt;#python { color: green }&lt;/style&gt;&#39;</span><span class="p">)</span>
<span class="go">Start tag: style</span>
<span class="go">     attr: (&#39;type&#39;, &#39;text/css&#39;)</span>
<span class="go">Data     : #python { color: green }</span>
<span class="go">End tag  : style</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;script type=&quot;text/javascript&quot;&gt;&#39;</span>
<span class="gp">... </span>            <span class="s1">&#39;alert(&quot;&lt;strong&gt;hello!&lt;/strong&gt;&quot;);&lt;/script&gt;&#39;</span><span class="p">)</span>
<span class="go">Start tag: script</span>
<span class="go">     attr: (&#39;type&#39;, &#39;text/javascript&#39;)</span>
<span class="go">Data     : alert(&quot;&lt;strong&gt;hello!&lt;/strong&gt;&quot;);</span>
<span class="go">End tag  : script</span>
</pre></div>
</div>
<p>Parsing comments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;!-- a comment --&gt;&#39;</span>
<span class="gp">... </span>            <span class="s1">&#39;&lt;!--[if IE 9]&gt;IE-specific content&lt;![endif]--&gt;&#39;</span><span class="p">)</span>
<span class="go">Comment  :  a comment</span>
<span class="go">Comment  : [if IE 9]&gt;IE-specific content&lt;![endif]</span>
</pre></div>
</div>
<p>Parsing named and numeric character references and converting them to the
correct char (note: these 3 references are all equivalent to <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&amp;gt;&amp;#62;&amp;#x3E;&#39;</span><span class="p">)</span>
<span class="go">Named ent: &gt;</span>
<span class="go">Num ent  : &gt;</span>
<span class="go">Num ent  : &gt;</span>
</pre></div>
</div>
<p>Feeding incomplete chunks to <a class="reference internal" href="#HTMLParser.HTMLParser.feed" title="HTMLParser.HTMLParser.feed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">feed()</span></code></a> works, but
<a class="reference internal" href="#HTMLParser.HTMLParser.handle_data" title="HTMLParser.HTMLParser.handle_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_data()</span></code></a> might be called more than once:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;&lt;sp&#39;</span><span class="p">,</span> <span class="s1">&#39;an&gt;buff&#39;</span><span class="p">,</span> <span class="s1">&#39;ered &#39;</span><span class="p">,</span> <span class="s1">&#39;text&lt;/s&#39;</span><span class="p">,</span> <span class="s1">&#39;pan&gt;&#39;</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Start tag: span</span>
<span class="go">Data     : buff</span>
<span class="go">Data     : ered</span>
<span class="go">Data     : text</span>
<span class="go">End tag  : span</span>
</pre></div>
</div>
<p>Parsing invalid HTML (e.g. unquoted attributes) also works:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="s1">&#39;&lt;p&gt;&lt;a class=link href=#main&gt;tag soup&lt;/p &gt;&lt;/a&gt;&#39;</span><span class="p">)</span>
<span class="go">Start tag: p</span>
<span class="go">Start tag: a</span>
<span class="go">     attr: (&#39;class&#39;, &#39;link&#39;)</span>
<span class="go">     attr: (&#39;href&#39;, &#39;#main&#39;)</span>
<span class="go">Data     : tag soup</span>
<span class="go">End tag  : p</span>
<span class="go">End tag  : a</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a><ul>
<li><a class="reference internal" href="#example-html-parser-application">19.1.1. Example HTML Parser Application</a></li>
<li><a class="reference internal" href="#htmlparser-methods">19.1.2. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> Methods</a></li>
<li><a class="reference internal" href="#examples">19.1.3. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="markup.html"
                        title="previous chapter">19. Structured Markup Processing Tools</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sgmllib.html"
                        title="next chapter">19.2. <code class="docutils literal notranslate"><span class="pre">sgmllib</span></code> — Simple SGML parser</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/htmlparser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sgmllib.html" title="19.2. sgmllib — Simple SGML parser"
             >next</a> |</li>
        <li class="right" >
          <a href="markup.html" title="19. Structured Markup Processing Tools"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\#
�html/library/httplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.7. httplib — HTTP protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.8. ftplib — FTP protocol client" href="ftplib.html" />
    <link rel="prev" title="20.6. urllib2 — extensible library for opening URLs" href="urllib2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/httplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ftplib.html" title="20.8. ftplib — FTP protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="20.6. urllib2 — extensible library for opening URLs"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-httplib">
<span id="httplib-http-protocol-client"></span><h1>20.7. <a class="reference internal" href="#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> — HTTP protocol client<a class="headerlink" href="#module-httplib" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.client</span></code> in Python
3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<span class="target" id="index-0"></span><p id="index-1"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/httplib.py">Lib/httplib.py</a></p>
<hr class="docutils" />
<p>This module defines classes which implement the client side of the HTTP and
HTTPS protocols.  It is normally not used directly — the module <a class="reference internal" href="urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a>
uses it to handle URLs that use HTTP and HTTPS.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference external" href="http://requests.readthedocs.org/">Requests package</a>
is recommended for a higher-level HTTP client interface.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">HTTPS support is only available if the <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module was compiled with
SSL support.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The public interface for this module changed substantially in Python 2.0.  The
<code class="xref py py-class docutils literal notranslate"><span class="pre">HTTP</span></code> class is retained only for backward compatibility with 1.5.2.  It
should not be used in new code.  Refer to the online docstrings for usage.</p>
</div>
<p>The module provides the following classes:</p>
<dl class="class">
<dt id="httplib.HTTPConnection">
<em class="property">class </em><code class="descclassname">httplib.</code><code class="descname">HTTPConnection</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>strict</em><span class="optional">[</span>, <em>timeout</em><span class="optional">[</span>, <em>source_address</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection" title="Permalink to this definition">¶</a></dt>
<dd><p>An <a class="reference internal" href="#httplib.HTTPConnection" title="httplib.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPConnection</span></code></a> instance represents one transaction with an HTTP
server.  It should be instantiated passing it a host and optional port
number.  If no port number is passed, the port is extracted from the host
string if it has the form <code class="docutils literal notranslate"><span class="pre">host:port</span></code>, else the default HTTP port (80) is
used.  When true, the optional parameter <em>strict</em> (which defaults to a false
value) causes <code class="docutils literal notranslate"><span class="pre">BadStatusLine</span></code> to
be raised if the status line can’t be parsed as a valid HTTP/1.0 or 1.1
status line.  If the optional <em>timeout</em> parameter is given, blocking
operations (like connection attempts) will timeout after that many seconds
(if it is not given, the global default timeout setting is used).
The optional <em>source_address</em> parameter may be a tuple of a (host, port)
to use as the source address the HTTP connection is made from.</p>
<p>For example, the following calls all create instances that connect to the server
at the same host and port:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">h1</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s1">&#39;www.cwi.nl&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h2</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s1">&#39;www.cwi.nl:80&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h3</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s1">&#39;www.cwi.nl&#39;</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">h3</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s1">&#39;www.cwi.nl&#39;</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>source_address</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="httplib.HTTPSConnection">
<em class="property">class </em><code class="descclassname">httplib.</code><code class="descname">HTTPSConnection</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>key_file</em><span class="optional">[</span>, <em>cert_file</em><span class="optional">[</span>, <em>strict</em><span class="optional">[</span>, <em>timeout</em><span class="optional">[</span>, <em>source_address</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPSConnection" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPConnection" title="httplib.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPConnection</span></code></a> that uses SSL for communication with
secure servers.  Default port is <code class="docutils literal notranslate"><span class="pre">443</span></code>.  If <em>context</em> is specified, it must
be a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> instance describing the various SSL options.</p>
<p><em>key_file</em> and <em>cert_file</em> are deprecated, please use
<a class="reference internal" href="ssl.html#ssl.SSLContext.load_cert_chain" title="ssl.SSLContext.load_cert_chain"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ssl.SSLContext.load_cert_chain()</span></code></a> instead, or let
<a class="reference internal" href="ssl.html#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.create_default_context()</span></code></a> select the system’s trusted CA
certificates for you.</p>
<p>Please read <a class="reference internal" href="ssl.html#ssl-security"><span class="std std-ref">Security considerations</span></a> for more information on best practices.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>source_address</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span><em>context</em> was added.</p>
<p>This class now performs all the necessary certificate and hostname checks
by default. To revert to the previous, unverified, behavior
<code class="xref py py-func docutils literal notranslate"><span class="pre">ssl._create_unverified_context()</span></code> can be passed to the <em>context</em>
parameter.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="httplib.HTTPResponse">
<em class="property">class </em><code class="descclassname">httplib.</code><code class="descname">HTTPResponse</code><span class="sig-paren">(</span><em>sock</em>, <em>debuglevel=0</em>, <em>strict=0</em><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPResponse" title="Permalink to this definition">¶</a></dt>
<dd><p>Class whose instances are returned upon successful connection.  Not instantiated
directly by user.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="httplib.HTTPMessage">
<em class="property">class </em><code class="descclassname">httplib.</code><code class="descname">HTTPMessage</code><a class="headerlink" href="#httplib.HTTPMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>An <a class="reference internal" href="#httplib.HTTPMessage" title="httplib.HTTPMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPMessage</span></code></a> instance is used to hold the headers from an HTTP
response. It is implemented using the <a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a> class and
provides utility functions to deal with HTTP Headers. It is not directly
instantiated by the users.</p>
</dd></dl>

<p>The following exceptions are raised as appropriate:</p>
<dl class="exception">
<dt id="httplib.HTTPException">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">HTTPException</code><a class="headerlink" href="#httplib.HTTPException" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class of the other exceptions in this module.  It is a subclass of
<a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.NotConnected">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">NotConnected</code><a class="headerlink" href="#httplib.NotConnected" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.InvalidURL">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">InvalidURL</code><a class="headerlink" href="#httplib.InvalidURL" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>, raised if a port is given and is either
non-numeric or empty.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.UnknownProtocol">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">UnknownProtocol</code><a class="headerlink" href="#httplib.UnknownProtocol" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.UnknownTransferEncoding">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">UnknownTransferEncoding</code><a class="headerlink" href="#httplib.UnknownTransferEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.UnimplementedFileMode">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">UnimplementedFileMode</code><a class="headerlink" href="#httplib.UnimplementedFileMode" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.IncompleteRead">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">IncompleteRead</code><a class="headerlink" href="#httplib.IncompleteRead" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.ImproperConnectionState">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">ImproperConnectionState</code><a class="headerlink" href="#httplib.ImproperConnectionState" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.CannotSendRequest">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">CannotSendRequest</code><a class="headerlink" href="#httplib.CannotSendRequest" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.ImproperConnectionState" title="httplib.ImproperConnectionState"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperConnectionState</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.CannotSendHeader">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">CannotSendHeader</code><a class="headerlink" href="#httplib.CannotSendHeader" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.ImproperConnectionState" title="httplib.ImproperConnectionState"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperConnectionState</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.ResponseNotReady">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">ResponseNotReady</code><a class="headerlink" href="#httplib.ResponseNotReady" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.ImproperConnectionState" title="httplib.ImproperConnectionState"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImproperConnectionState</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="httplib.BadStatusLine">
<em class="property">exception </em><code class="descclassname">httplib.</code><code class="descname">BadStatusLine</code><a class="headerlink" href="#httplib.BadStatusLine" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#httplib.HTTPException" title="httplib.HTTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPException</span></code></a>.  Raised if a server responds with a HTTP
status code that we don’t understand.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<p>The constants defined in this module are:</p>
<dl class="data">
<dt id="httplib.HTTP_PORT">
<code class="descclassname">httplib.</code><code class="descname">HTTP_PORT</code><a class="headerlink" href="#httplib.HTTP_PORT" title="Permalink to this definition">¶</a></dt>
<dd><p>The default port for the HTTP protocol (always <code class="docutils literal notranslate"><span class="pre">80</span></code>).</p>
</dd></dl>

<dl class="data">
<dt id="httplib.HTTPS_PORT">
<code class="descclassname">httplib.</code><code class="descname">HTTPS_PORT</code><a class="headerlink" href="#httplib.HTTPS_PORT" title="Permalink to this definition">¶</a></dt>
<dd><p>The default port for the HTTPS protocol (always <code class="docutils literal notranslate"><span class="pre">443</span></code>).</p>
</dd></dl>

<p>and also the following constants for integer status codes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="34%" />
<col width="7%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Value</th>
<th class="head">Definition</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">CONTINUE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">100</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.1">RFC 2616, Section
10.1.1</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SWITCHING_PROTOCOLS</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">101</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.1.2">RFC 2616, Section
10.1.2</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PROCESSING</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">102</span></code></td>
<td>WEBDAV, <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_102">RFC 2518, Section 10.1</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">OK</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">200</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.1">RFC 2616, Section
10.2.1</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">CREATED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">201</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2">RFC 2616, Section
10.2.2</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ACCEPTED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">202</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.3">RFC 2616, Section
10.2.3</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NON_AUTHORITATIVE_INFORMATION</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">203</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.4">RFC 2616, Section
10.2.4</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NO_CONTENT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">204</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5">RFC 2616, Section
10.2.5</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">RESET_CONTENT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">205</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.6">RFC 2616, Section
10.2.6</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PARTIAL_CONTENT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">206</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.7">RFC 2616, Section
10.2.7</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTI_STATUS</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">207</span></code></td>
<td>WEBDAV <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_207">RFC 2518, Section 10.2</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">IM_USED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">226</span></code></td>
<td>Delta encoding in HTTP,
<span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3229.html"><strong>RFC 3229</strong></a>, Section 10.4.1</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTIPLE_CHOICES</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">300</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.1">RFC 2616, Section
10.3.1</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">MOVED_PERMANENTLY</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">301</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2">RFC 2616, Section
10.3.2</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FOUND</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">302</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3">RFC 2616, Section
10.3.3</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SEE_OTHER</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">303</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4">RFC 2616, Section
10.3.4</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_MODIFIED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">304</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5">RFC 2616, Section
10.3.5</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">USE_PROXY</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">305</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.6">RFC 2616, Section
10.3.6</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">TEMPORARY_REDIRECT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">307</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.8">RFC 2616, Section
10.3.8</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">BAD_REQUEST</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">400</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.1">RFC 2616, Section
10.4.1</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">UNAUTHORIZED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">401</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2">RFC 2616, Section
10.4.2</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PAYMENT_REQUIRED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">402</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.3">RFC 2616, Section
10.4.3</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FORBIDDEN</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">403</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4">RFC 2616, Section
10.4.4</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_FOUND</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">404</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5">RFC 2616, Section
10.4.5</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">METHOD_NOT_ALLOWED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">405</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6">RFC 2616, Section
10.4.6</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_ACCEPTABLE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">406</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.7">RFC 2616, Section
10.4.7</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PROXY_AUTHENTICATION_REQUIRED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">407</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.8">RFC 2616, Section
10.4.8</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">REQUEST_TIMEOUT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">408</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.9">RFC 2616, Section
10.4.9</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">CONFLICT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">409</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.10">RFC 2616, Section
10.4.10</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">GONE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">410</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.11">RFC 2616, Section
10.4.11</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">LENGTH_REQUIRED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">411</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.12">RFC 2616, Section
10.4.12</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">PRECONDITION_FAILED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">412</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.13">RFC 2616, Section
10.4.13</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">REQUEST_ENTITY_TOO_LARGE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">413</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.14">RFC 2616, Section
10.4.14</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">REQUEST_URI_TOO_LONG</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">414</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.15">RFC 2616, Section
10.4.15</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">UNSUPPORTED_MEDIA_TYPE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">415</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.16">RFC 2616, Section
10.4.16</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">REQUESTED_RANGE_NOT_SATISFIABLE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">416</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.17">RFC 2616, Section
10.4.17</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EXPECTATION_FAILED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">417</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.18">RFC 2616, Section
10.4.18</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">UNPROCESSABLE_ENTITY</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">422</span></code></td>
<td>WEBDAV, <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_422">RFC 2518, Section 10.3</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCKED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">423</span></code></td>
<td>WEBDAV <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_423">RFC 2518, Section 10.4</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">FAILED_DEPENDENCY</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">424</span></code></td>
<td>WEBDAV, <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_424">RFC 2518, Section 10.5</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">UPGRADE_REQUIRED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">426</span></code></td>
<td>HTTP Upgrade to TLS,
<span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2817.html"><strong>RFC 2817</strong></a>, Section 6</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INTERNAL_SERVER_ERROR</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">500</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.1">RFC 2616, Section
10.5.1</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_IMPLEMENTED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">501</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.2">RFC 2616, Section
10.5.2</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">BAD_GATEWAY</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">502</span></code></td>
<td>HTTP/1.1 <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.3">RFC 2616, Section
10.5.3</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SERVICE_UNAVAILABLE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">503</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.4">RFC 2616, Section
10.5.4</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">GATEWAY_TIMEOUT</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">504</span></code></td>
<td>HTTP/1.1 <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.5">RFC 2616, Section
10.5.5</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">HTTP_VERSION_NOT_SUPPORTED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">505</span></code></td>
<td>HTTP/1.1, <a class="reference external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.5.6">RFC 2616, Section
10.5.6</a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INSUFFICIENT_STORAGE</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">507</span></code></td>
<td>WEBDAV, <a class="reference external" href="http://www.webdav.org/specs/rfc2518.html#STATUS_507">RFC 2518, Section 10.6</a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_EXTENDED</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">510</span></code></td>
<td>An HTTP Extension Framework,
<span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2774.html"><strong>RFC 2774</strong></a>, Section 7</td>
</tr>
</tbody>
</table>
<dl class="data">
<dt id="httplib.responses">
<code class="descclassname">httplib.</code><code class="descname">responses</code><a class="headerlink" href="#httplib.responses" title="Permalink to this definition">¶</a></dt>
<dd><p>This dictionary maps the HTTP 1.1 status codes to the W3C names.</p>
<p>Example: <code class="docutils literal notranslate"><span class="pre">httplib.responses[httplib.NOT_FOUND]</span></code> is <code class="docutils literal notranslate"><span class="pre">'Not</span> <span class="pre">Found'</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<div class="section" id="httpconnection-objects">
<span id="id1"></span><h2>20.7.1. HTTPConnection Objects<a class="headerlink" href="#httpconnection-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#httplib.HTTPConnection" title="httplib.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPConnection</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="httplib.HTTPConnection.request">
<code class="descclassname">HTTPConnection.</code><code class="descname">request</code><span class="sig-paren">(</span><em>method</em>, <em>url</em><span class="optional">[</span>, <em>body</em><span class="optional">[</span>, <em>headers</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.request" title="Permalink to this definition">¶</a></dt>
<dd><p>This will send a request to the server using the HTTP request method <em>method</em>
and the selector <em>url</em>.  If the <em>body</em> argument is present, it should be a
string of data to send after the headers are finished. Alternatively, it may
be an open file object, in which case the contents of the file is sent; this
file object should support <code class="docutils literal notranslate"><span class="pre">fileno()</span></code> and <code class="docutils literal notranslate"><span class="pre">read()</span></code> methods. The
<em>headers</em> argument should be a mapping of extra HTTP headers to send with
the request.</p>
<p>If one is not provided in <em>headers</em>, a <code class="docutils literal notranslate"><span class="pre">Content-Length</span></code> header is added
automatically for all methods if the length of the body can be determined,
either from the length of the <code class="docutils literal notranslate"><span class="pre">str</span></code> representation, or from the reported
size of the file on disk. If <em>body</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> the header is not set except
for methods that expect a body (<code class="docutils literal notranslate"><span class="pre">PUT</span></code>, <code class="docutils literal notranslate"><span class="pre">POST</span></code>, and <code class="docutils literal notranslate"><span class="pre">PATCH</span></code>) in which
case it is set to <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>body</em> can be a file object.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.getresponse">
<code class="descclassname">HTTPConnection.</code><code class="descname">getresponse</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.getresponse" title="Permalink to this definition">¶</a></dt>
<dd><p>Should be called after a request is sent to get the response from the server.
Returns an <a class="reference internal" href="#httplib.HTTPResponse" title="httplib.HTTPResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPResponse</span></code></a> instance.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Note that you must have read the whole response before you can send a new
request to the server.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.set_debuglevel">
<code class="descclassname">HTTPConnection.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the debugging level (the amount of debugging output printed). The default
debug level is <code class="docutils literal notranslate"><span class="pre">0</span></code>, meaning no debugging output is printed.</p>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.set_tunnel">
<code class="descclassname">HTTPConnection.</code><code class="descname">set_tunnel</code><span class="sig-paren">(</span><em>host</em>, <em>port=None</em>, <em>headers=None</em><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.set_tunnel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the host and the port for HTTP Connect Tunnelling. Normally used when
it is required to do HTTPS Connection through a proxy server.</p>
<p>The headers argument should be a mapping of extra HTTP headers to send
with the CONNECT request.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.connect">
<code class="descclassname">HTTPConnection.</code><code class="descname">connect</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to the server specified when the object was created.</p>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.close">
<code class="descclassname">HTTPConnection.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the connection to the server.</p>
</dd></dl>

<p>As an alternative to using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">request()</span></code> method described above, you can
also send your request step by step, by using the four functions below.</p>
<dl class="method">
<dt id="httplib.HTTPConnection.putrequest">
<code class="descclassname">HTTPConnection.</code><code class="descname">putrequest</code><span class="sig-paren">(</span><em>request</em>, <em>selector</em><span class="optional">[</span>, <em>skip_host</em><span class="optional">[</span>, <em>skip_accept_encoding</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.putrequest" title="Permalink to this definition">¶</a></dt>
<dd><p>This should be the first call after the connection to the server has been made.
It sends a line to the server consisting of the <em>request</em> string, the <em>selector</em>
string, and the HTTP version (<code class="docutils literal notranslate"><span class="pre">HTTP/1.1</span></code>).  To disable automatic sending of
<code class="docutils literal notranslate"><span class="pre">Host:</span></code> or <code class="docutils literal notranslate"><span class="pre">Accept-Encoding:</span></code> headers (for example to accept additional
content encodings), specify <em>skip_host</em> or <em>skip_accept_encoding</em> with non-False
values.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>skip_accept_encoding</em> argument added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.putheader">
<code class="descclassname">HTTPConnection.</code><code class="descname">putheader</code><span class="sig-paren">(</span><em>header</em>, <em>argument</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.putheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>-style header to the server.  It sends a line to the server
consisting of the header, a colon and a space, and the first argument.  If more
arguments are given, continuation lines are sent, each consisting of a tab and
an argument.</p>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.endheaders">
<code class="descclassname">HTTPConnection.</code><code class="descname">endheaders</code><span class="sig-paren">(</span><em>message_body=None</em><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.endheaders" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a blank line to the server, signalling the end of the headers. The
optional <em>message_body</em> argument can be used to pass a message body
associated with the request.  The message body will be sent in the same
packet as the message headers if it is string, otherwise it is sent in a
separate packet.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>message_body</em> was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPConnection.send">
<code class="descclassname">HTTPConnection.</code><code class="descname">send</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPConnection.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send data to the server.  This should be used directly only after the
<a class="reference internal" href="#httplib.HTTPConnection.endheaders" title="httplib.HTTPConnection.endheaders"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endheaders()</span></code></a> method has been called and before <a class="reference internal" href="#httplib.HTTPConnection.getresponse" title="httplib.HTTPConnection.getresponse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getresponse()</span></code></a> is
called.</p>
</dd></dl>

</div>
<div class="section" id="httpresponse-objects">
<span id="id2"></span><h2>20.7.2. HTTPResponse Objects<a class="headerlink" href="#httpresponse-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#httplib.HTTPResponse" title="httplib.HTTPResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPResponse</span></code></a> instances have the following methods and attributes:</p>
<dl class="method">
<dt id="httplib.HTTPResponse.read">
<code class="descclassname">HTTPResponse.</code><code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>amt</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPResponse.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads and returns the response body, or up to the next <em>amt</em> bytes.</p>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPResponse.getheader">
<code class="descclassname">HTTPResponse.</code><code class="descname">getheader</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPResponse.getheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the contents of the header <em>name</em>, or <em>default</em> if there is no matching
header.</p>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPResponse.getheaders">
<code class="descclassname">HTTPResponse.</code><code class="descname">getheaders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPResponse.getheaders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of (header, value) tuples.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="httplib.HTTPResponse.fileno">
<code class="descclassname">HTTPResponse.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#httplib.HTTPResponse.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the <code class="docutils literal notranslate"><span class="pre">fileno</span></code> of the underlying socket.</p>
</dd></dl>

<dl class="attribute">
<dt id="httplib.HTTPResponse.msg">
<code class="descclassname">HTTPResponse.</code><code class="descname">msg</code><a class="headerlink" href="#httplib.HTTPResponse.msg" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a> instance containing the response headers.</p>
</dd></dl>

<dl class="attribute">
<dt id="httplib.HTTPResponse.version">
<code class="descclassname">HTTPResponse.</code><code class="descname">version</code><a class="headerlink" href="#httplib.HTTPResponse.version" title="Permalink to this definition">¶</a></dt>
<dd><p>HTTP protocol version used by server.  10 for HTTP/1.0, 11 for HTTP/1.1.</p>
</dd></dl>

<dl class="attribute">
<dt id="httplib.HTTPResponse.status">
<code class="descclassname">HTTPResponse.</code><code class="descname">status</code><a class="headerlink" href="#httplib.HTTPResponse.status" title="Permalink to this definition">¶</a></dt>
<dd><p>Status code returned by server.</p>
</dd></dl>

<dl class="attribute">
<dt id="httplib.HTTPResponse.reason">
<code class="descclassname">HTTPResponse.</code><code class="descname">reason</code><a class="headerlink" href="#httplib.HTTPResponse.reason" title="Permalink to this definition">¶</a></dt>
<dd><p>Reason phrase returned by server.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="httplib-examples"></span><h2>20.7.3. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Here is an example session that uses the <code class="docutils literal notranslate"><span class="pre">GET</span></code> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">httplib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPSConnection</span><span class="p">(</span><span class="s2">&quot;www.python.org&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s2">&quot;GET&quot;</span><span class="p">,</span> <span class="s2">&quot;/&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r1</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getresponse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">r1</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">r1</span><span class="o">.</span><span class="n">reason</span>
<span class="go">200 OK</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data1</span> <span class="o">=</span> <span class="n">r1</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s2">&quot;GET&quot;</span><span class="p">,</span> <span class="s2">&quot;/&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r2</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getresponse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">r2</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">r2</span><span class="o">.</span><span class="n">reason</span>
<span class="go">404 Not Found</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data2</span> <span class="o">=</span> <span class="n">r2</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Here is an example session that uses the <code class="docutils literal notranslate"><span class="pre">HEAD</span></code> method.  Note that the
<code class="docutils literal notranslate"><span class="pre">HEAD</span></code> method never returns any data.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">httplib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPSConnection</span><span class="p">(</span><span class="s2">&quot;www.python.org&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s2">&quot;HEAD&quot;</span><span class="p">,</span><span class="s2">&quot;/&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">res</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getresponse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">res</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">res</span><span class="o">.</span><span class="n">reason</span>
<span class="go">200 OK</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">res</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">==</span> <span class="s1">&#39;&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Here is an example session that shows how to <code class="docutils literal notranslate"><span class="pre">POST</span></code> requests:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">httplib</span><span class="o">,</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">params</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">&#39;@number&#39;</span><span class="p">:</span> <span class="mi">12524</span><span class="p">,</span> <span class="s1">&#39;@type&#39;</span><span class="p">:</span> <span class="s1">&#39;issue&#39;</span><span class="p">,</span> <span class="s1">&#39;@action&#39;</span><span class="p">:</span> <span class="s1">&#39;show&#39;</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">headers</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;Content-type&quot;</span><span class="p">:</span> <span class="s2">&quot;application/x-www-form-urlencoded&quot;</span><span class="p">,</span>
<span class="gp">... </span>           <span class="s2">&quot;Accept&quot;</span><span class="p">:</span> <span class="s2">&quot;text/plain&quot;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s2">&quot;bugs.python.org&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s2">&quot;POST&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="n">params</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getresponse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">response</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">response</span><span class="o">.</span><span class="n">reason</span>
<span class="go">302 Found</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">response</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">&#39;Redirecting to &lt;a href=&quot;http://bugs.python.org/issue12524&quot;&gt;http://bugs.python.org/issue12524&lt;/a&gt;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Client side <code class="docutils literal notranslate"><span class="pre">HTTP</span> <span class="pre">PUT</span></code> requests are very similar to <code class="docutils literal notranslate"><span class="pre">POST</span></code> requests. The
difference lies only the server side where HTTP server will allow resources to
be created via <code class="docutils literal notranslate"><span class="pre">PUT</span></code> request. Here is an example session that shows how to do
<code class="docutils literal notranslate"><span class="pre">PUT</span></code> request using httplib:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># This creates an HTTP message</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># with the content of BODY as the enclosed representation</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># for the resource http://localhost:8080/foobar</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">httplib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">BODY</span> <span class="o">=</span> <span class="s2">&quot;***filecontents***&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8080</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">request</span><span class="p">(</span><span class="s2">&quot;PUT&quot;</span><span class="p">,</span> <span class="s2">&quot;/file&quot;</span><span class="p">,</span> <span class="n">BODY</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">response</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getresponse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">response</span><span class="o">.</span><span class="n">status</span><span class="p">,</span> <span class="n">response</span><span class="o">.</span><span class="n">reason</span>
<span class="go">200, OK</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a><ul>
<li><a class="reference internal" href="#httpconnection-objects">20.7.1. HTTPConnection Objects</a></li>
<li><a class="reference internal" href="#httpresponse-objects">20.7.2. HTTPResponse Objects</a></li>
<li><a class="reference internal" href="#examples">20.7.3. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="urllib2.html"
                        title="previous chapter">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ftplib.html"
                        title="next chapter">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/httplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ftplib.html" title="20.8. ftplib — FTP protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="20.6. urllib2 — extensible library for opening URLs"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�V�&?'?'html/library/i18n.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>22. Internationalization &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="22.1. gettext — Multilingual internationalization services" href="gettext.html" />
    <link rel="prev" title="21.10. ossaudiodev — Access to OSS-compatible audio devices" href="ossaudiodev.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/i18n.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gettext.html" title="22.1. gettext — Multilingual internationalization services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ossaudiodev.html" title="21.10. ossaudiodev — Access to OSS-compatible audio devices"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="internationalization">
<span id="i18n"></span><h1>22. Internationalization<a class="headerlink" href="#internationalization" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter help you write software that is
independent of language and locale by providing mechanisms for selecting a
language to be used in  program messages or by tailoring output to match local
conventions.</p>
<p>The list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="gettext.html">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="gettext.html#gnu-gettext-api">22.1.1. GNU <strong class="program">gettext</strong> API</a></li>
<li class="toctree-l2"><a class="reference internal" href="gettext.html#class-based-api">22.1.2. Class-based API</a><ul>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#the-nulltranslations-class">22.1.2.1. The <code class="docutils literal notranslate"><span class="pre">NullTranslations</span></code> class</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#the-gnutranslations-class">22.1.2.2. The <code class="docutils literal notranslate"><span class="pre">GNUTranslations</span></code> class</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#solaris-message-catalog-support">22.1.2.3. Solaris message catalog support</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#the-catalog-constructor">22.1.2.4. The Catalog constructor</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="gettext.html#internationalizing-your-programs-and-modules">22.1.3. Internationalizing your programs and modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#localizing-your-module">22.1.3.1. Localizing your module</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#localizing-your-application">22.1.3.2. Localizing your application</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#changing-languages-on-the-fly">22.1.3.3. Changing languages on the fly</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#deferred-translations">22.1.3.4. Deferred translations</a></li>
<li class="toctree-l3"><a class="reference internal" href="gettext.html#gettext-vs-lgettext">22.1.3.5. <code class="docutils literal notranslate"><span class="pre">gettext()</span></code> vs. <code class="docutils literal notranslate"><span class="pre">lgettext()</span></code></a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="gettext.html#acknowledgements">22.1.4. Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="locale.html">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="locale.html#background-details-hints-tips-and-caveats">22.2.1. Background, details, hints, tips and caveats</a></li>
<li class="toctree-l2"><a class="reference internal" href="locale.html#for-extension-writers-and-programs-that-embed-python">22.2.2. For extension writers and programs that embed Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="locale.html#access-to-message-catalogs">22.2.3. Access to message catalogs</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="ossaudiodev.html"
                        title="previous chapter">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gettext.html"
                        title="next chapter">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/i18n.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gettext.html" title="22.1. gettext — Multilingual internationalization services"
             >next</a> |</li>
        <li class="right" >
          <a href="ossaudiodev.html" title="21.10. ossaudiodev — Access to OSS-compatible audio devices"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����H�Hhtml/library/ic.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.1. ic — Access to the Mac OS X Internet Config &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.2. MacOS — Access to Mac OS interpreter features" href="macos.html" />
    <link rel="prev" title="37. Mac OS X specific services" href="mac.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ic.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macos.html" title="37.2. MacOS — Access to Mac OS interpreter features"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mac.html" title="37. Mac OS X specific services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ic">
<span id="ic-access-to-the-mac-os-x-internet-config"></span><h1>37.1. <a class="reference internal" href="#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a> — Access to the Mac OS X Internet Config<a class="headerlink" href="#module-ic" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to various internet-related preferences set through
<strong class="program">System Preferences</strong> or the <strong class="program">Finder</strong>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p id="index-0">There is a low-level companion module <code class="xref py py-mod docutils literal notranslate"><span class="pre">icglue</span></code> which provides the basic
Internet Config access functionality.  This low-level module is not documented,
but the docstrings of the routines document the parameters and the routine names
are the same as for the Pascal or C API to Internet Config, so the standard IC
programmers’ documentation can be used if this module is needed.</p>
<p>The <a class="reference internal" href="#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a> module defines the <a class="reference internal" href="#ic.error" title="ic.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception and symbolic names for
all error codes Internet Config can produce; see the source for details.</p>
<dl class="exception">
<dt id="ic.error">
<em class="property">exception </em><code class="descclassname">ic.</code><code class="descname">error</code><a class="headerlink" href="#ic.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on errors in the <a class="reference internal" href="#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a> module.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a> module defines the following class and function:</p>
<dl class="class">
<dt id="ic.IC">
<em class="property">class </em><code class="descclassname">ic.</code><code class="descname">IC</code><span class="sig-paren">(</span><span class="optional">[</span><em>signature</em><span class="optional">[</span>, <em>ic</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an Internet Config object. The signature is a 4-character creator code of
the current application (default <code class="docutils literal notranslate"><span class="pre">'Pyth'</span></code>) which may influence some of ICs
settings. The optional <em>ic</em> argument is a low-level <code class="docutils literal notranslate"><span class="pre">icglue.icinstance</span></code>
created beforehand, this may be useful if you want to get preferences from a
different config file, etc.</p>
</dd></dl>

<dl class="function">
<dt id="ic.launchurl">
<code class="descclassname">ic.</code><code class="descname">launchurl</code><span class="sig-paren">(</span><em>url</em><span class="optional">[</span>, <em>hint</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.launchurl" title="Permalink to this definition">¶</a></dt>
<dt id="ic.parseurl">
<code class="descclassname">ic.</code><code class="descname">parseurl</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">[</span>, <em>hint</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.parseurl" title="Permalink to this definition">¶</a></dt>
<dt id="ic.mapfile">
<code class="descclassname">ic.</code><code class="descname">mapfile</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#ic.mapfile" title="Permalink to this definition">¶</a></dt>
<dt id="ic.maptypecreator">
<code class="descclassname">ic.</code><code class="descname">maptypecreator</code><span class="sig-paren">(</span><em>type</em>, <em>creator</em><span class="optional">[</span>, <em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.maptypecreator" title="Permalink to this definition">¶</a></dt>
<dt id="ic.settypecreator">
<code class="descclassname">ic.</code><code class="descname">settypecreator</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#ic.settypecreator" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions are “shortcuts” to the methods of the same name, described
below.</p>
</dd></dl>

<div class="section" id="ic-objects">
<h2>37.1.1. IC Objects<a class="headerlink" href="#ic-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#ic.IC" title="ic.IC"><code class="xref py py-class docutils literal notranslate"><span class="pre">IC</span></code></a> objects have a mapping interface, hence to obtain the mail address
you simply get <code class="docutils literal notranslate"><span class="pre">ic['MailAddress']</span></code>. Assignment also works, and changes the
option in the configuration file.</p>
<p>The module knows about various datatypes, and converts the internal IC
representation to a “logical” Python data structure. Running the <a class="reference internal" href="#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a>
module standalone will run a test program that lists all keys and values in your
IC database, this will have to serve as documentation.</p>
<p>If the module does not know how to represent the data it returns an instance of
the <code class="docutils literal notranslate"><span class="pre">ICOpaqueData</span></code> type, with the raw data in its <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code> attribute.
Objects of this type are also acceptable values for assignment.</p>
<p>Besides the dictionary interface, <a class="reference internal" href="#ic.IC" title="ic.IC"><code class="xref py py-class docutils literal notranslate"><span class="pre">IC</span></code></a> objects have the following
methods:</p>
<dl class="method">
<dt id="ic.IC.launchurl">
<code class="descclassname">IC.</code><code class="descname">launchurl</code><span class="sig-paren">(</span><em>url</em><span class="optional">[</span>, <em>hint</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC.launchurl" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse the given URL, launch the correct application and pass it the URL. The
optional <em>hint</em> can be a scheme name such as <code class="docutils literal notranslate"><span class="pre">'mailto:'</span></code>, in which case
incomplete URLs are completed with this scheme.  If <em>hint</em> is not provided,
incomplete URLs are invalid.</p>
</dd></dl>

<dl class="method">
<dt id="ic.IC.parseurl">
<code class="descclassname">IC.</code><code class="descname">parseurl</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">[</span>, <em>hint</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC.parseurl" title="Permalink to this definition">¶</a></dt>
<dd><p>Find a URL somewhere in <em>data</em> and return start position, end position and the
URL. The optional <em>start</em> and <em>end</em> can be used to limit the search, so for
instance if a user clicks in a long text field you can pass the whole text field
and the click-position in <em>start</em> and this routine will return the whole URL in
which the user clicked.  As above, <em>hint</em> is an optional scheme used to complete
incomplete URLs.</p>
</dd></dl>

<dl class="method">
<dt id="ic.IC.mapfile">
<code class="descclassname">IC.</code><code class="descname">mapfile</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC.mapfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mapping entry for the given <em>file</em>, which can be passed as either a
filename or an <code class="xref py py-func docutils literal notranslate"><span class="pre">FSSpec()</span></code> result, and which need not exist.</p>
<p>The mapping entry is returned as a tuple <code class="docutils literal notranslate"><span class="pre">(version,</span> <span class="pre">type,</span> <span class="pre">creator,</span> <span class="pre">postcreator,</span>
<span class="pre">flags,</span> <span class="pre">extension,</span> <span class="pre">appname,</span> <span class="pre">postappname,</span> <span class="pre">mimetype,</span> <span class="pre">entryname)</span></code>, where <em>version</em>
is the entry version number, <em>type</em> is the 4-character filetype, <em>creator</em> is
the 4-character creator type, <em>postcreator</em> is the 4-character creator code of
an optional application to post-process the file after downloading, <em>flags</em> are
various bits specifying whether to transfer in binary or ascii and such,
<em>extension</em> is the filename extension for this file type, <em>appname</em> is the
printable name of the application to which this file belongs, <em>postappname</em> is
the name of the postprocessing application, <em>mimetype</em> is the MIME type of this
file and <em>entryname</em> is the name of this entry.</p>
</dd></dl>

<dl class="method">
<dt id="ic.IC.maptypecreator">
<code class="descclassname">IC.</code><code class="descname">maptypecreator</code><span class="sig-paren">(</span><em>type</em>, <em>creator</em><span class="optional">[</span>, <em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC.maptypecreator" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mapping entry for files with given 4-character <em>type</em> and <em>creator</em>
codes. The optional <em>filename</em> may be specified to further help finding the
correct entry (if the creator code is <code class="docutils literal notranslate"><span class="pre">'????'</span></code>, for instance).</p>
<p>The mapping entry is returned in the same format as for <em>mapfile</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ic.IC.settypecreator">
<code class="descclassname">IC.</code><code class="descname">settypecreator</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#ic.IC.settypecreator" title="Permalink to this definition">¶</a></dt>
<dd><p>Given an existing <em>file</em>, specified either as a filename or as an <code class="xref py py-func docutils literal notranslate"><span class="pre">FSSpec()</span></code>
result, set its creator and type correctly based on its extension.  The finder
is told about the change, so the finder icon will be updated quickly.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a><ul>
<li><a class="reference internal" href="#ic-objects">37.1.1. IC Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mac.html"
                        title="previous chapter">37. Mac OS X specific services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="macos.html"
                        title="next chapter">37.2. <code class="docutils literal notranslate"><span class="pre">MacOS</span></code> — Access to Mac OS interpreter features</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ic.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macos.html" title="37.2. MacOS — Access to Mac OS interpreter features"
             >next</a> |</li>
        <li class="right" >
          <a href="mac.html" title="37. Mac OS X specific services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�*,����html/library/idle.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.6. IDLE &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.7. Other Graphical User Interface Packages" href="othergui.html" />
    <link rel="prev" title="24.5. turtle — Turtle graphics for Tk" href="turtle.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/idle.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="othergui.html" title="24.7. Other Graphical User Interface Packages"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="turtle.html" title="24.5. turtle — Turtle graphics for Tk"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="idle">
<span id="id1"></span><h1>24.6. IDLE<a class="headerlink" href="#idle" title="Permalink to this headline">¶</a></h1>
<p id="index-0">IDLE is Python’s Integrated Development and Learning Environment.</p>
<p>IDLE has the following features:</p>
<ul class="simple">
<li>coded in 100% pure Python, using the <code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter</span></code> GUI toolkit</li>
<li>cross-platform: works mostly the same on Windows, Unix, and Mac OS X</li>
<li>Python shell window (interactive interpreter) with colorizing
of code input, output, and error messages</li>
<li>multi-window text editor with multiple undo, Python colorizing,
smart indent, call tips, auto completion, and other features</li>
<li>search within any window, replace within editor windows, and search
through multiple files (grep)</li>
<li>debugger with persistent breakpoints, stepping, and viewing
of global and local namespaces</li>
<li>configuration, browsers, and other dialogs</li>
</ul>
<div class="section" id="menus">
<h2>24.6.1. Menus<a class="headerlink" href="#menus" title="Permalink to this headline">¶</a></h2>
<p>IDLE has two main window types, the Shell window and the Editor window.  It is
possible to have multiple editor windows simultaneously.  Output windows, such
as used for Edit / Find in Files, are a subtype of edit window.  They currently
have the same top menu as Editor windows but a different default title and
context menu.</p>
<p>IDLE’s menus dynamically change based on which window is currently selected.
Each menu documented below indicates which window type it is associated with.</p>
<div class="section" id="file-menu-shell-and-editor">
<h3>24.6.1.1. File menu (Shell and Editor)<a class="headerlink" href="#file-menu-shell-and-editor" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>New File</dt>
<dd>Create a new file editing window.</dd>
<dt>Open…</dt>
<dd>Open an existing file with an Open dialog.</dd>
<dt>Recent Files</dt>
<dd>Open a list of recent files.  Click one to open it.</dd>
<dt>Open Module…</dt>
<dd>Open an existing module (searches sys.path).</dd>
</dl>
<dl class="docutils" id="index-1">
<dt>Class Browser</dt>
<dd>Show functions, classes, and methods in the current Editor file in a
tree structure.  In the shell, open a module first.</dd>
<dt>Path Browser</dt>
<dd>Show sys.path directories, modules, functions, classes and methods in a
tree structure.</dd>
<dt>Save</dt>
<dd>Save the current window to the associated file, if there is one.  Windows
that have been changed since being opened or last saved have a * before
and after the window title.  If there is no associated file,
do Save As instead.</dd>
<dt>Save As…</dt>
<dd>Save the current window with a Save As dialog.  The file saved becomes the
new associated file for the window.</dd>
<dt>Save Copy As…</dt>
<dd>Save the current window to different file without changing the associated
file.</dd>
<dt>Print Window</dt>
<dd>Print the current window to the default printer.</dd>
<dt>Close</dt>
<dd>Close the current window (ask to save if unsaved).</dd>
<dt>Exit</dt>
<dd>Close all windows and quit IDLE (ask to save unsaved windows).</dd>
</dl>
</div>
<div class="section" id="edit-menu-shell-and-editor">
<h3>24.6.1.2. Edit menu (Shell and Editor)<a class="headerlink" href="#edit-menu-shell-and-editor" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Undo</dt>
<dd>Undo the last change to the current window.  A maximum of 1000 changes may
be undone.</dd>
<dt>Redo</dt>
<dd>Redo the last undone change to the current window.</dd>
<dt>Cut</dt>
<dd>Copy selection into the system-wide clipboard; then delete the selection.</dd>
<dt>Copy</dt>
<dd>Copy selection into the system-wide clipboard.</dd>
<dt>Paste</dt>
<dd>Insert contents of the system-wide clipboard into the current window.</dd>
</dl>
<p>The clipboard functions are also available in context menus.</p>
<dl class="docutils">
<dt>Select All</dt>
<dd>Select the entire contents of the current window.</dd>
<dt>Find…</dt>
<dd>Open a search dialog with many options</dd>
<dt>Find Again</dt>
<dd>Repeat the last search, if there is one.</dd>
<dt>Find Selection</dt>
<dd>Search for the currently selected string, if there is one.</dd>
<dt>Find in Files…</dt>
<dd>Open a file search dialog.  Put results in a new output window.</dd>
<dt>Replace…</dt>
<dd>Open a search-and-replace dialog.</dd>
<dt>Go to Line</dt>
<dd>Move cursor to the line number requested and make that line visible.</dd>
<dt>Show Completions</dt>
<dd>Open a scrollable list allowing selection of keywords and attributes. See
Completions in the Tips sections below.</dd>
<dt>Expand Word</dt>
<dd>Expand a prefix you have typed to match a full word in the same window;
repeat to get a different expansion.</dd>
<dt>Show call tip</dt>
<dd>After an unclosed parenthesis for a function, open a small window with
function parameter hints.</dd>
<dt>Show surrounding parens</dt>
<dd>Highlight the surrounding parenthesis.</dd>
</dl>
</div>
<div class="section" id="format-menu-editor-window-only">
<h3>24.6.1.3. Format menu (Editor window only)<a class="headerlink" href="#format-menu-editor-window-only" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Indent Region</dt>
<dd>Shift selected lines right by the indent width (default 4 spaces).</dd>
<dt>Dedent Region</dt>
<dd>Shift selected lines left by the indent width (default 4 spaces).</dd>
<dt>Comment Out Region</dt>
<dd>Insert ## in front of selected lines.</dd>
<dt>Uncomment Region</dt>
<dd>Remove leading # or ## from selected lines.</dd>
<dt>Tabify Region</dt>
<dd>Turn <em>leading</em> stretches of spaces into tabs. (Note: We recommend using
4 space blocks to indent Python code.)</dd>
<dt>Untabify Region</dt>
<dd>Turn <em>all</em> tabs into the correct number of spaces.</dd>
<dt>Toggle Tabs</dt>
<dd>Open a dialog to switch between indenting with spaces and tabs.</dd>
<dt>New Indent Width</dt>
<dd>Open a dialog to change indent width. The accepted default by the Python
community is 4 spaces.</dd>
<dt>Format Paragraph</dt>
<dd>Reformat the current blank-line-delimited paragraph in comment block or
multiline string or selected line in a string.  All lines in the
paragraph will be formatted to less than N columns, where N defaults to 72.</dd>
<dt>Strip trailing whitespace</dt>
<dd>Remove any space characters after the last non-space character of a line.</dd>
</dl>
</div>
<div class="section" id="run-menu-editor-window-only">
<span id="index-2"></span><h3>24.6.1.4. Run menu (Editor window only)<a class="headerlink" href="#run-menu-editor-window-only" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Python Shell</dt>
<dd>Open or wake up the Python Shell window.</dd>
<dt>Check Module</dt>
<dd>Check the syntax of the module currently open in the Editor window. If the
module has not been saved IDLE will either prompt the user to save or
autosave, as selected in the General tab of the Idle Settings dialog.  If
there is a syntax error, the approximate location is indicated in the
Editor window.</dd>
<dt>Run Module</dt>
<dd>Do Check Module (above).  If no error, restart the shell to clean the
environment, then execute the module.  Output is displayed in the Shell
window.  Note that output requires use of <code class="docutils literal notranslate"><span class="pre">print</span></code> or <code class="docutils literal notranslate"><span class="pre">write</span></code>.
When execution is complete, the Shell retains focus and displays a prompt.
At this point, one may interactively explore the result of execution.
This is similar to executing a file with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-i</span> <span class="pre">file</span></code> at a command
line.</dd>
</dl>
</div>
<div class="section" id="shell-menu-shell-window-only">
<h3>24.6.1.5. Shell menu (Shell window only)<a class="headerlink" href="#shell-menu-shell-window-only" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>View Last Restart</dt>
<dd>Scroll the shell window to the last Shell restart.</dd>
<dt>Restart Shell</dt>
<dd>Restart the shell to clean the environment.</dd>
<dt>Interrupt Execution</dt>
<dd>Stop a running program.</dd>
</dl>
</div>
<div class="section" id="debug-menu-shell-window-only">
<h3>24.6.1.6. Debug menu (Shell window only)<a class="headerlink" href="#debug-menu-shell-window-only" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Go to File/Line</dt>
<dd>Look on the current line. with the cursor, and the line above for a filename
and line number.  If found, open the file if not already open, and show the
line.  Use this to view source lines referenced in an exception traceback
and lines found by Find in Files. Also available in the context menu of
the Shell window and Output windows.</dd>
</dl>
<dl class="docutils" id="index-3">
<dt>Debugger (toggle)</dt>
<dd>When activated, code entered in the Shell or run from an Editor will run
under the debugger.  In the Editor, breakpoints can be set with the context
menu.  This feature is still incomplete and somewhat experimental.</dd>
<dt>Stack Viewer</dt>
<dd>Show the stack traceback of the last exception in a tree widget, with
access to locals and globals.</dd>
<dt>Auto-open Stack Viewer</dt>
<dd>Toggle automatically opening the stack viewer on an unhandled exception.</dd>
</dl>
</div>
<div class="section" id="options-menu-shell-and-editor">
<h3>24.6.1.7. Options menu (Shell and Editor)<a class="headerlink" href="#options-menu-shell-and-editor" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Configure IDLE</dt>
<dd><p class="first">Open a configuration dialog and change preferences for the following:
fonts, indentation, keybindings, text color themes, startup windows and
size, additional help sources, and extensions (see below).  On OS X,
open the configuration dialog by selecting Preferences in the application
menu.  To use a new built-in color theme (IDLE Dark) with older IDLEs,
save it as a new custom theme.</p>
<p class="last">Non-default user settings are saved in a .idlerc directory in the user’s
home directory.  Problems caused by bad user configuration files are solved
by editing or deleting one or more of the files in .idlerc.</p>
</dd>
<dt>Code Context (toggle)(Editor Window only)</dt>
<dd>Open a pane at the top of the edit window which shows the block context
of the code which has scrolled above the top of the window.</dd>
</dl>
</div>
<div class="section" id="window-menu-shell-and-editor">
<h3>24.6.1.8. Window menu (Shell and Editor)<a class="headerlink" href="#window-menu-shell-and-editor" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Zoom Height</dt>
<dd>Toggles the window between normal size and maximum height. The initial size
defaults to 40 lines by 80 chars unless changed on the General tab of the
Configure IDLE dialog.</dd>
</dl>
<p>The rest of this menu lists the names of all open windows; select one to bring
it to the foreground (deiconifying it if necessary).</p>
</div>
<div class="section" id="help-menu-shell-and-editor">
<h3>24.6.1.9. Help menu (Shell and Editor)<a class="headerlink" href="#help-menu-shell-and-editor" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>About IDLE</dt>
<dd>Display version, copyright, license, credits, and more.</dd>
<dt>IDLE Help</dt>
<dd>Display a help file for IDLE detailing the menu options, basic editing and
navigation, and other tips.</dd>
<dt>Python Docs</dt>
<dd>Access local Python documentation, if installed, or start a web browser
and open docs.python.org showing the latest Python documentation.</dd>
<dt>Turtle Demo</dt>
<dd>Run the turtledemo module with example python code and turtle drawings.</dd>
</dl>
<p>Additional help sources may be added here with the Configure IDLE dialog under
the General tab.</p>
</div>
<div class="section" id="context-menus">
<span id="index-4"></span><h3>24.6.1.10. Context Menus<a class="headerlink" href="#context-menus" title="Permalink to this headline">¶</a></h3>
<p>Open a context menu by right-clicking in a window (Control-click on OS X).
Context menus have the standard clipboard functions also on the Edit menu.</p>
<dl class="docutils">
<dt>Cut</dt>
<dd>Copy selection into the system-wide clipboard; then delete the selection.</dd>
<dt>Copy</dt>
<dd>Copy selection into the system-wide clipboard.</dd>
<dt>Paste</dt>
<dd>Insert contents of the system-wide clipboard into the current window.</dd>
</dl>
<p>Editor windows also have breakpoint functions.  Lines with a breakpoint set are
specially marked.  Breakpoints only have an effect when running under the
debugger.  Breakpoints for a file are saved in the user’s .idlerc directory.</p>
<dl class="docutils">
<dt>Set Breakpoint</dt>
<dd>Set a breakpoint on the current line.</dd>
<dt>Clear Breakpoint</dt>
<dd>Clear the breakpoint on that line.</dd>
</dl>
<p>Shell and Output windows have the following.</p>
<dl class="docutils">
<dt>Go to file/line</dt>
<dd>Same as in Debug menu.</dd>
</dl>
</div>
</div>
<div class="section" id="editing-and-navigation">
<h2>24.6.2. Editing and navigation<a class="headerlink" href="#editing-and-navigation" title="Permalink to this headline">¶</a></h2>
<p>In this section, ‘C’ refers to the <kbd class="kbd docutils literal notranslate">Control</kbd> key on Windows and Unix and
the <kbd class="kbd docutils literal notranslate">Command</kbd> key on Mac OSX.</p>
<ul>
<li><p class="first"><kbd class="kbd docutils literal notranslate">Backspace</kbd> deletes to the left; <kbd class="kbd docutils literal notranslate">Del</kbd> deletes to the right</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">C-Backspace</kbd> delete word left; <kbd class="kbd docutils literal notranslate">C-Del</kbd> delete word to the right</p>
</li>
<li><p class="first">Arrow keys and <kbd class="kbd docutils literal notranslate">Page Up</kbd>/<kbd class="kbd docutils literal notranslate">Page Down</kbd> to move around</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">C-LeftArrow</kbd> and <kbd class="kbd docutils literal notranslate">C-RightArrow</kbd> moves by words</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">Home</kbd>/<kbd class="kbd docutils literal notranslate">End</kbd> go to begin/end of line</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">C-Home</kbd>/<kbd class="kbd docutils literal notranslate">C-End</kbd> go to begin/end of file</p>
</li>
<li><p class="first">Some useful Emacs bindings are inherited from Tcl/Tk:</p>
<blockquote>
<div><ul class="simple">
<li><kbd class="kbd docutils literal notranslate">C-a</kbd> beginning of line</li>
<li><kbd class="kbd docutils literal notranslate">C-e</kbd> end of line</li>
<li><kbd class="kbd docutils literal notranslate">C-k</kbd> kill line (but doesn’t put it in clipboard)</li>
<li><kbd class="kbd docutils literal notranslate">C-l</kbd> center window around the insertion point</li>
<li><kbd class="kbd docutils literal notranslate">C-b</kbd> go backward one character without deleting (usually you can
also use the cursor key for this)</li>
<li><kbd class="kbd docutils literal notranslate">C-f</kbd> go forward one character without deleting (usually you can
also use the cursor key for this)</li>
<li><kbd class="kbd docutils literal notranslate">C-p</kbd> go up one line (usually you can also use the cursor key for
this)</li>
<li><kbd class="kbd docutils literal notranslate">C-d</kbd> delete next character</li>
</ul>
</div></blockquote>
</li>
</ul>
<p>Standard keybindings (like <kbd class="kbd docutils literal notranslate">C-c</kbd> to copy and <kbd class="kbd docutils literal notranslate">C-v</kbd> to paste)
may work.  Keybindings are selected in the Configure IDLE dialog.</p>
<div class="section" id="automatic-indentation">
<h3>24.6.2.1. Automatic indentation<a class="headerlink" href="#automatic-indentation" title="Permalink to this headline">¶</a></h3>
<p>After a block-opening statement, the next line is indented by 4 spaces (in the
Python Shell window by one tab).  After certain keywords (break, return etc.)
the next line is dedented.  In leading indentation, <kbd class="kbd docutils literal notranslate">Backspace</kbd> deletes up
to 4 spaces if they are there. <kbd class="kbd docutils literal notranslate">Tab</kbd> inserts spaces (in the Python
Shell window one tab), number depends on Indent width. Currently, tabs
are restricted to four spaces due to Tcl/Tk limitations.</p>
<p>See also the indent/dedent region commands in the edit menu.</p>
</div>
<div class="section" id="completions">
<h3>24.6.2.2. Completions<a class="headerlink" href="#completions" title="Permalink to this headline">¶</a></h3>
<p>Completions are supplied for functions, classes, and attributes of classes,
both built-in and user-defined. Completions are also provided for
filenames.</p>
<p>The AutoCompleteWindow (ACW) will open after a predefined delay (default is
two seconds) after a ‘.’ or (in a string) an os.sep is typed. If after one
of those characters (plus zero or more other characters) a tab is typed
the ACW will open immediately if a possible continuation is found.</p>
<p>If there is only one possible completion for the characters entered, a
<kbd class="kbd docutils literal notranslate">Tab</kbd> will supply that completion without opening the ACW.</p>
<p>‘Show Completions’ will force open a completions window, by default the
<kbd class="kbd docutils literal notranslate">C-space</kbd> will open a completions window. In an empty
string, this will contain the files in the current directory. On a
blank line, it will contain the built-in and user-defined functions and
classes in the current namespaces, plus any modules imported. If some
characters have been entered, the ACW will attempt to be more specific.</p>
<p>If a string of characters is typed, the ACW selection will jump to the
entry most closely matching those characters.  Entering a <kbd class="kbd docutils literal notranslate">tab</kbd> will
cause the longest non-ambiguous match to be entered in the Editor window or
Shell.  Two <kbd class="kbd docutils literal notranslate">tab</kbd> in a row will supply the current ACW selection, as
will return or a double click.  Cursor keys, Page Up/Down, mouse selection,
and the scroll wheel all operate on the ACW.</p>
<p>“Hidden” attributes can be accessed by typing the beginning of hidden
name after a ‘.’, e.g. ‘_’. This allows access to modules with
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> set, or to class-private attributes.</p>
<p>Completions and the ‘Expand Word’ facility can save a lot of typing!</p>
<p>Completions are currently limited to those in the namespaces. Names in
an Editor window which are not via <code class="docutils literal notranslate"><span class="pre">__main__</span></code> and <a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> will
not be found.  Run the module once with your imports to correct this situation.
Note that IDLE itself places quite a few modules in sys.modules, so
much can be found by default, e.g. the re module.</p>
<p>If you don’t like the ACW popping up unbidden, simply make the delay
longer or disable the extension.</p>
</div>
<div class="section" id="calltips">
<h3>24.6.2.3. Calltips<a class="headerlink" href="#calltips" title="Permalink to this headline">¶</a></h3>
<p>A calltip is shown when one types <kbd class="kbd docutils literal notranslate">(</kbd> after the name of an <em>accessible</em>
function.  A name expression may include dots and subscripts.  A calltip
remains until it is clicked, the cursor is moved out of the argument area,
or <kbd class="kbd docutils literal notranslate">)</kbd> is typed.  When the cursor is in the argument part of a definition,
the menu or shortcut display a calltip.</p>
<p>A calltip consists of the function signature and the first line of the
docstring.  For builtins without an accessible signature, the calltip
consists of all lines up the fifth line or the first blank line.  These
details may change.</p>
<p>The set of <em>accessible</em> functions depends on what modules have been imported
into the user process, including those imported by Idle itself,
and what definitions have been run, all since the last restart.</p>
<p>For example, restart the Shell and enter <code class="docutils literal notranslate"><span class="pre">itertools.count(</span></code>.  A calltip
appears because Idle imports itertools into the user process for its own use.
(This could change.)  Enter <code class="docutils literal notranslate"><span class="pre">turtle.write(</span></code> and nothing appears.  Idle does
not import turtle.  The menu or shortcut do nothing either.  Enter
<code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">turtle</span></code> and then <code class="docutils literal notranslate"><span class="pre">turtle.write(</span></code> will work.</p>
<p>In an editor, import statements have no effect until one runs the file.  One
might want to run a file after writing the import statements at the top,
or immediately run an existing file before editing.</p>
</div>
<div class="section" id="python-shell-window">
<h3>24.6.2.4. Python Shell window<a class="headerlink" href="#python-shell-window" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first"><kbd class="kbd docutils literal notranslate">C-c</kbd> interrupts executing command</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">C-d</kbd> sends end-of-file; closes window if typed at a <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code> prompt</p>
</li>
<li><p class="first"><kbd class="kbd docutils literal notranslate">Alt-/</kbd> (Expand word) is also useful to reduce typing</p>
<p>Command history</p>
<ul class="simple">
<li><kbd class="kbd docutils literal notranslate">Alt-p</kbd> retrieves previous command matching what you have typed. On
OS X use <kbd class="kbd docutils literal notranslate">C-p</kbd>.</li>
<li><kbd class="kbd docutils literal notranslate">Alt-n</kbd> retrieves next. On OS X use <kbd class="kbd docutils literal notranslate">C-n</kbd>.</li>
<li><kbd class="kbd docutils literal notranslate">Return</kbd> while on any previous command retrieves that command</li>
</ul>
</li>
</ul>
</div>
<div class="section" id="text-colors">
<h3>24.6.2.5. Text colors<a class="headerlink" href="#text-colors" title="Permalink to this headline">¶</a></h3>
<p>Idle defaults to black on white text, but colors text with special meanings.
For the shell, these are shell output, shell error, user output, and
user error.  For Python code, at the shell prompt or in an editor, these are
keywords, builtin class and function names, names following <code class="docutils literal notranslate"><span class="pre">class</span></code> and
<code class="docutils literal notranslate"><span class="pre">def</span></code>, strings, and comments. For any text window, these are the cursor (when
present), found text (when possible), and selected text.</p>
<p>Text coloring is done in the background, so uncolorized text is occasionally
visible.  To change the color scheme, use the Configure IDLE dialog
Highlighting tab.  The marking of debugger breakpoint lines in the editor and
text in popups and dialogs is not user-configurable.</p>
</div>
</div>
<div class="section" id="startup-and-code-execution">
<h2>24.6.3. Startup and code execution<a class="headerlink" href="#startup-and-code-execution" title="Permalink to this headline">¶</a></h2>
<p>Upon startup with the <code class="docutils literal notranslate"><span class="pre">-s</span></code> option, IDLE will execute the file referenced by
the environment variables <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> or <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a>.
IDLE first checks for <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code>; if <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> is present the file
referenced is run.  If <code class="docutils literal notranslate"><span class="pre">IDLESTARTUP</span></code> is not present, IDLE checks for
<code class="docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code>.  Files referenced by these environment variables are
convenient places to store functions that are used frequently from the IDLE
shell, or for executing import statements to import common modules.</p>
<p>In addition, <code class="docutils literal notranslate"><span class="pre">Tk</span></code> also loads a startup file if it is present.  Note that the
Tk file is loaded unconditionally.  This additional file is <code class="docutils literal notranslate"><span class="pre">.Idle.py</span></code> and is
looked for in the user’s home directory.  Statements in this file will be
executed in the Tk namespace, so this file is not useful for importing
functions to be used from IDLE’s Python shell.</p>
<div class="section" id="command-line-usage">
<h3>24.6.3.1. Command line usage<a class="headerlink" href="#command-line-usage" title="Permalink to this headline">¶</a></h3>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>idle.py [-c command] [-d] [-e] [-h] [-i] [-r file] [-s] [-t title] [-] [arg] ...

-c command  run command in the shell window
-d          enable debugger and open shell window
-e          open editor window
-h          print help message with legal combinations and exit
-i          open shell window
-r file     run file in shell window
-s          run $IDLESTARTUP or $PYTHONSTARTUP first, in shell window
-t title    set title of shell window
-           run stdin in shell (- must be last option before args)
</pre></div>
</div>
<p>If there are arguments:</p>
<ul class="simple">
<li>If <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">-c</span></code>, or <code class="docutils literal notranslate"><span class="pre">r</span></code> is used, all arguments are placed in
<code class="docutils literal notranslate"><span class="pre">sys.argv[1:...]</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>,
or <code class="docutils literal notranslate"><span class="pre">'-r'</span></code>.  No editor window is opened, even if that is the default
set in the Options dialog.</li>
<li>Otherwise, arguments are files opened for editing and
<code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> reflects the arguments passed to IDLE itself.</li>
</ul>
</div>
<div class="section" id="idle-console-differences">
<h3>24.6.3.2. IDLE-console differences<a class="headerlink" href="#idle-console-differences" title="Permalink to this headline">¶</a></h3>
<p>As much as possible, the result of executing Python code with IDLE is the
same as executing the same code in a console window.  However, the different
interface and operation occasionally affect visible results.  For instance,
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> starts with more entries.</p>
<p>IDLE also replaces <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>, and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> with
objects that get input from and send output to the Shell window.
When this window has the focus, it controls the keyboard and screen.
This is normally transparent, but functions that directly access the keyboard
and screen will not work.  If <code class="docutils literal notranslate"><span class="pre">sys</span></code> is reset with <code class="docutils literal notranslate"><span class="pre">reload(sys)</span></code>,
IDLE’s changes are lost and things like <code class="docutils literal notranslate"><span class="pre">input</span></code>, <code class="docutils literal notranslate"><span class="pre">raw_input</span></code>, and
<code class="docutils literal notranslate"><span class="pre">print</span></code> will not work correctly.</p>
<p>With IDLE’s Shell, one enters, edits, and recalls complete statements.
Some consoles only work with a single physical line at a time.  IDLE uses
<code class="docutils literal notranslate"><span class="pre">exec</span></code> to run each statement.  As a result, <code class="docutils literal notranslate"><span class="pre">'__builtins__'</span></code> is always
defined for each statement.</p>
</div>
<div class="section" id="running-without-a-subprocess">
<h3>24.6.3.3. Running without a subprocess<a class="headerlink" href="#running-without-a-subprocess" title="Permalink to this headline">¶</a></h3>
<p>By default, IDLE executes user code in a separate subprocess via a socket,
which uses the internal loopback interface.  This connection is not
externally visible and no data is sent to or received from the Internet.
If firewall software complains anyway, you can ignore it.</p>
<p>If the attempt to make the socket connection fails, Idle will notify you.
Such failures are sometimes transient, but if persistent, the problem
may be either a firewall blocking the connection or misconfiguration of
a particular system.  Until the problem is fixed, one can run Idle with
the -n command line switch.</p>
<p>If IDLE is started with the -n command line switch it will run in a
single process and will not create the subprocess which runs the RPC
Python execution server.  This can be useful if Python cannot create
the subprocess or the RPC socket interface on your platform.  However,
in this mode user code is not isolated from IDLE itself.  Also, the
environment is not restarted when Run/Run Module (F5) is selected.  If
your code has been modified, you must reload() the affected modules and
re-import any specific items (e.g. from foo import baz) if the changes
are to take effect.  For these reasons, it is preferable to run IDLE
with the default subprocess if at all possible.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 3.4.</span></p>
</div>
</div>
</div>
<div class="section" id="help-and-preferences">
<h2>24.6.4. Help and preferences<a class="headerlink" href="#help-and-preferences" title="Permalink to this headline">¶</a></h2>
<div class="section" id="additional-help-sources">
<h3>24.6.4.1. Additional help sources<a class="headerlink" href="#additional-help-sources" title="Permalink to this headline">¶</a></h3>
<p>IDLE includes a help menu entry called “Python Docs” that will open the
extensive sources of help, including tutorials, available at docs.python.org.
Selected URLs can be added or removed from the help menu at any time using the
Configure IDLE dialog. See the IDLE help option in the help menu of IDLE for
more information.</p>
</div>
<div class="section" id="setting-preferences">
<h3>24.6.4.2. Setting preferences<a class="headerlink" href="#setting-preferences" title="Permalink to this headline">¶</a></h3>
<p>The font preferences, highlighting, keys, and general preferences can be
changed via Configure IDLE on the Option menu.  Keys can be user defined;
IDLE ships with four built-in key sets. In addition, a user can create a
custom key set in the Configure IDLE dialog under the keys tab.</p>
</div>
<div class="section" id="extensions">
<h3>24.6.4.3. Extensions<a class="headerlink" href="#extensions" title="Permalink to this headline">¶</a></h3>
<p>IDLE contains an extension facility.  Preferences for extensions can be
changed with Configure Extensions. See the beginning of config-extensions.def
in the idlelib directory for further information.  The default extensions
are currently:</p>
<ul class="simple">
<li>FormatParagraph</li>
<li>AutoExpand</li>
<li>ZoomHeight</li>
<li>ScriptBinding</li>
<li>CallTips</li>
<li>ParenMatch</li>
<li>AutoComplete</li>
<li>CodeContext</li>
<li>RstripExtension</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">24.6. IDLE</a><ul>
<li><a class="reference internal" href="#menus">24.6.1. Menus</a><ul>
<li><a class="reference internal" href="#file-menu-shell-and-editor">24.6.1.1. File menu (Shell and Editor)</a></li>
<li><a class="reference internal" href="#edit-menu-shell-and-editor">24.6.1.2. Edit menu (Shell and Editor)</a></li>
<li><a class="reference internal" href="#format-menu-editor-window-only">24.6.1.3. Format menu (Editor window only)</a></li>
<li><a class="reference internal" href="#run-menu-editor-window-only">24.6.1.4. Run menu (Editor window only)</a></li>
<li><a class="reference internal" href="#shell-menu-shell-window-only">24.6.1.5. Shell menu (Shell window only)</a></li>
<li><a class="reference internal" href="#debug-menu-shell-window-only">24.6.1.6. Debug menu (Shell window only)</a></li>
<li><a class="reference internal" href="#options-menu-shell-and-editor">24.6.1.7. Options menu (Shell and Editor)</a></li>
<li><a class="reference internal" href="#window-menu-shell-and-editor">24.6.1.8. Window menu (Shell and Editor)</a></li>
<li><a class="reference internal" href="#help-menu-shell-and-editor">24.6.1.9. Help menu (Shell and Editor)</a></li>
<li><a class="reference internal" href="#context-menus">24.6.1.10. Context Menus</a></li>
</ul>
</li>
<li><a class="reference internal" href="#editing-and-navigation">24.6.2. Editing and navigation</a><ul>
<li><a class="reference internal" href="#automatic-indentation">24.6.2.1. Automatic indentation</a></li>
<li><a class="reference internal" href="#completions">24.6.2.2. Completions</a></li>
<li><a class="reference internal" href="#calltips">24.6.2.3. Calltips</a></li>
<li><a class="reference internal" href="#python-shell-window">24.6.2.4. Python Shell window</a></li>
<li><a class="reference internal" href="#text-colors">24.6.2.5. Text colors</a></li>
</ul>
</li>
<li><a class="reference internal" href="#startup-and-code-execution">24.6.3. Startup and code execution</a><ul>
<li><a class="reference internal" href="#command-line-usage">24.6.3.1. Command line usage</a></li>
<li><a class="reference internal" href="#idle-console-differences">24.6.3.2. IDLE-console differences</a></li>
<li><a class="reference internal" href="#running-without-a-subprocess">24.6.3.3. Running without a subprocess</a></li>
</ul>
</li>
<li><a class="reference internal" href="#help-and-preferences">24.6.4. Help and preferences</a><ul>
<li><a class="reference internal" href="#additional-help-sources">24.6.4.1. Additional help sources</a></li>
<li><a class="reference internal" href="#setting-preferences">24.6.4.2. Setting preferences</a></li>
<li><a class="reference internal" href="#extensions">24.6.4.3. Extensions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="turtle.html"
                        title="previous chapter">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="othergui.html"
                        title="next chapter">24.7. Other Graphical User Interface Packages</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/idle.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="othergui.html" title="24.7. Other Graphical User Interface Packages"
             >next</a> |</li>
        <li class="right" >
          <a href="turtle.html" title="24.5. turtle — Turtle graphics for Tk"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�nj�>�>html/library/imageop.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.2. imageop — Manipulate raw image data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.3. aifc — Read and write AIFF and AIFC files" href="aifc.html" />
    <link rel="prev" title="21.1. audioop — Manipulate raw audio data" href="audioop.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imageop.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aifc.html" title="21.3. aifc — Read and write AIFF and AIFC files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="audioop.html" title="21.1. audioop — Manipulate raw audio data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imageop">
<span id="imageop-manipulate-raw-image-data"></span><h1>21.2. <a class="reference internal" href="#module-imageop" title="imageop: Manipulate raw image data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code></a> — Manipulate raw image data<a class="headerlink" href="#module-imageop" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-imageop" title="imageop: Manipulate raw image data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-imageop" title="imageop: Manipulate raw image data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code></a> module contains some useful operations on images. It operates
on images consisting of 8 or 32 bit pixels stored in Python strings.  This is
the same format as used by <code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectwrite()</span></code> and the <a class="reference internal" href="imgfile.html#module-imgfile" title="imgfile: Support for SGI imglib files. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code></a> module.</p>
<p>The module defines the following variables and functions:</p>
<dl class="exception">
<dt id="imageop.error">
<em class="property">exception </em><code class="descclassname">imageop.</code><code class="descname">error</code><a class="headerlink" href="#imageop.error" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised on all errors, such as unknown number of bits per
pixel, etc.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.crop">
<code class="descclassname">imageop.</code><code class="descname">crop</code><span class="sig-paren">(</span><em>image</em>, <em>psize</em>, <em>width</em>, <em>height</em>, <em>x0</em>, <em>y0</em>, <em>x1</em>, <em>y1</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.crop" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the selected part of <em>image</em>, which should be <em>width</em> by <em>height</em> in size
and consist of pixels of <em>psize</em> bytes. <em>x0</em>, <em>y0</em>, <em>x1</em> and <em>y1</em> are like the
<code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectread()</span></code> parameters, i.e. the boundary is included in the new image.
The new boundaries need not be inside the picture.  Pixels that fall outside the
old image will have their value set to zero.  If <em>x0</em> is bigger than <em>x1</em> the
new image is mirrored.  The same holds for the y coordinates.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.scale">
<code class="descclassname">imageop.</code><code class="descname">scale</code><span class="sig-paren">(</span><em>image</em>, <em>psize</em>, <em>width</em>, <em>height</em>, <em>newwidth</em>, <em>newheight</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.scale" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>image</em> scaled to size <em>newwidth</em> by <em>newheight</em>. No interpolation is
done, scaling is done by simple-minded pixel duplication or removal.  Therefore,
computer-generated images or dithered images will not look nice after scaling.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.tovideo">
<code class="descclassname">imageop.</code><code class="descname">tovideo</code><span class="sig-paren">(</span><em>image</em>, <em>psize</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.tovideo" title="Permalink to this definition">¶</a></dt>
<dd><p>Run a vertical low-pass filter over an image.  It does so by computing each
destination pixel as the average of two vertically-aligned source pixels.  The
main use of this routine is to forestall excessive flicker if the image is
displayed on a video device that uses interlacing, hence the name.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.grey2mono">
<code class="descclassname">imageop.</code><code class="descname">grey2mono</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em>, <em>threshold</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.grey2mono" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an 8-bit deep greyscale image to a 1-bit deep image by thresholding all
the pixels.  The resulting image is tightly packed and is probably only useful
as an argument to <a class="reference internal" href="#imageop.mono2grey" title="imageop.mono2grey"><code class="xref py py-func docutils literal notranslate"><span class="pre">mono2grey()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.dither2mono">
<code class="descclassname">imageop.</code><code class="descname">dither2mono</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.dither2mono" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an 8-bit greyscale image to a 1-bit monochrome image using a
(simple-minded) dithering algorithm.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.mono2grey">
<code class="descclassname">imageop.</code><code class="descname">mono2grey</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em>, <em>p0</em>, <em>p1</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.mono2grey" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a 1-bit monochrome image to an 8 bit greyscale or color image. All
pixels that are zero-valued on input get value <em>p0</em> on output and all one-value
input pixels get value <em>p1</em> on output.  To convert a monochrome black-and-white
image to greyscale pass the values <code class="docutils literal notranslate"><span class="pre">0</span></code> and <code class="docutils literal notranslate"><span class="pre">255</span></code> respectively.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.grey2grey4">
<code class="descclassname">imageop.</code><code class="descname">grey2grey4</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.grey2grey4" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an 8-bit greyscale image to a 4-bit greyscale image without dithering.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.grey2grey2">
<code class="descclassname">imageop.</code><code class="descname">grey2grey2</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.grey2grey2" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an 8-bit greyscale image to a 2-bit greyscale image without dithering.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.dither2grey2">
<code class="descclassname">imageop.</code><code class="descname">dither2grey2</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.dither2grey2" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an 8-bit greyscale image to a 2-bit greyscale image with dithering.  As
for <a class="reference internal" href="#imageop.dither2mono" title="imageop.dither2mono"><code class="xref py py-func docutils literal notranslate"><span class="pre">dither2mono()</span></code></a>, the dithering algorithm is currently very simple.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.grey42grey">
<code class="descclassname">imageop.</code><code class="descname">grey42grey</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.grey42grey" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a 4-bit greyscale image to an 8-bit greyscale image.</p>
</dd></dl>

<dl class="function">
<dt id="imageop.grey22grey">
<code class="descclassname">imageop.</code><code class="descname">grey22grey</code><span class="sig-paren">(</span><em>image</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#imageop.grey22grey" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a 2-bit greyscale image to an 8-bit greyscale image.</p>
</dd></dl>

<dl class="data">
<dt id="imageop.backward_compatible">
<code class="descclassname">imageop.</code><code class="descname">backward_compatible</code><a class="headerlink" href="#imageop.backward_compatible" title="Permalink to this definition">¶</a></dt>
<dd><p>If set to 0, the functions in this module use a non-backward compatible way
of representing multi-byte pixels on little-endian systems.  The SGI for
which this module was originally written is a big-endian system, so setting
this variable will have no effect. However, the code wasn’t originally
intended to run on anything else, so it made assumptions about byte order
which are not universal.  Setting this variable to 0 will cause the byte
order to be reversed on little-endian systems, so that it then is the same as
on big-endian systems.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="audioop.html"
                        title="previous chapter">21.1. <code class="docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="aifc.html"
                        title="next chapter">21.3. <code class="docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imageop.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="aifc.html" title="21.3. aifc — Read and write AIFF and AIFC files"
             >next</a> |</li>
        <li class="right" >
          <a href="audioop.html" title="21.1. audioop — Manipulate raw audio data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\@
X����html/library/imaplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.10. imaplib — IMAP4 protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.11. nntplib — NNTP protocol client" href="nntplib.html" />
    <link rel="prev" title="20.9. poplib — POP3 protocol client" href="poplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imaplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="nntplib.html" title="20.11. nntplib — NNTP protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="poplib.html" title="20.9. poplib — POP3 protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imaplib">
<span id="imaplib-imap4-protocol-client"></span><h1>20.10. <a class="reference internal" href="#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> — IMAP4 protocol client<a class="headerlink" href="#module-imaplib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/imaplib.py">Lib/imaplib.py</a></p>
<hr class="docutils" />
<p>This module defines three classes, <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a>, <a class="reference internal" href="#imaplib.IMAP4_SSL" title="imaplib.IMAP4_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4_SSL</span></code></a> and
<a class="reference internal" href="#imaplib.IMAP4_stream" title="imaplib.IMAP4_stream"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4_stream</span></code></a>, which encapsulate a connection to an IMAP4 server and
implement a large subset of the IMAP4rev1 client protocol as defined in
<span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2060.html"><strong>RFC 2060</strong></a>. It is backward compatible with IMAP4 (<span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1730.html"><strong>RFC 1730</strong></a>) servers, but
note that the <code class="docutils literal notranslate"><span class="pre">STATUS</span></code> command is not supported in IMAP4.</p>
<p>Three classes are provided by the <a class="reference internal" href="#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module, <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> is the
base class:</p>
<dl class="class">
<dt id="imaplib.IMAP4">
<em class="property">class </em><code class="descclassname">imaplib.</code><code class="descname">IMAP4</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements the actual IMAP4 protocol.  The connection is created and
protocol version (IMAP4 or IMAP4rev1) is determined when the instance is
initialized. If <em>host</em> is not specified, <code class="docutils literal notranslate"><span class="pre">''</span></code> (the local host) is used. If
<em>port</em> is omitted, the standard IMAP4 port (143) is used.</p>
</dd></dl>

<p>Three exceptions are defined as attributes of the <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> class:</p>
<dl class="exception">
<dt id="imaplib.IMAP4.error">
<em class="property">exception </em><code class="descclassname">IMAP4.</code><code class="descname">error</code><a class="headerlink" href="#imaplib.IMAP4.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on any errors.  The reason for the exception is passed to the
constructor as a string.</p>
</dd></dl>

<dl class="exception">
<dt id="imaplib.IMAP4.abort">
<em class="property">exception </em><code class="descclassname">IMAP4.</code><code class="descname">abort</code><a class="headerlink" href="#imaplib.IMAP4.abort" title="Permalink to this definition">¶</a></dt>
<dd><p>IMAP4 server errors cause this exception to be raised.  This is a sub-class of
<a class="reference internal" href="#imaplib.IMAP4.error" title="imaplib.IMAP4.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IMAP4.error</span></code></a>.  Note that closing the instance and instantiating a new one
will usually allow recovery from this exception.</p>
</dd></dl>

<dl class="exception">
<dt id="imaplib.IMAP4.readonly">
<em class="property">exception </em><code class="descclassname">IMAP4.</code><code class="descname">readonly</code><a class="headerlink" href="#imaplib.IMAP4.readonly" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a writable mailbox has its status changed by the
server.  This is a sub-class of <a class="reference internal" href="#imaplib.IMAP4.error" title="imaplib.IMAP4.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IMAP4.error</span></code></a>.  Some other client now has
write permission, and the mailbox will need to be re-opened to re-obtain write
permission.</p>
</dd></dl>

<p>There’s also a subclass for secure connections:</p>
<dl class="class">
<dt id="imaplib.IMAP4_SSL">
<em class="property">class </em><code class="descclassname">imaplib.</code><code class="descname">IMAP4_SSL</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>keyfile</em><span class="optional">[</span>, <em>certfile</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4_SSL" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a subclass derived from <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> that connects over an SSL
encrypted socket (to use this class you need a socket module that was compiled
with SSL support).  If <em>host</em> is not specified, <code class="docutils literal notranslate"><span class="pre">''</span></code> (the local host) is used.
If <em>port</em> is omitted, the standard IMAP4-over-SSL port (993) is used.  <em>keyfile</em>
and <em>certfile</em> are also optional - they can contain a PEM formatted private key
and certificate chain file for the SSL connection.</p>
</dd></dl>

<p>The second subclass allows for connections created by a child process:</p>
<dl class="class">
<dt id="imaplib.IMAP4_stream">
<em class="property">class </em><code class="descclassname">imaplib.</code><code class="descname">IMAP4_stream</code><span class="sig-paren">(</span><em>command</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4_stream" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a subclass derived from <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> that connects to the
<code class="docutils literal notranslate"><span class="pre">stdin/stdout</span></code> file descriptors created by passing <em>command</em> to
<code class="docutils literal notranslate"><span class="pre">os.popen2()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>The following utility functions are defined:</p>
<dl class="function">
<dt id="imaplib.Internaldate2tuple">
<code class="descclassname">imaplib.</code><code class="descname">Internaldate2tuple</code><span class="sig-paren">(</span><em>datestr</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.Internaldate2tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse an IMAP4 <code class="docutils literal notranslate"><span class="pre">INTERNALDATE</span></code> string and return corresponding local
time.  The return value is a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> instance or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the string has wrong format.</p>
</dd></dl>

<dl class="function">
<dt id="imaplib.Int2AP">
<code class="descclassname">imaplib.</code><code class="descname">Int2AP</code><span class="sig-paren">(</span><em>num</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.Int2AP" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts an integer into a string representation using characters from the set
[<code class="docutils literal notranslate"><span class="pre">A</span></code> .. <code class="docutils literal notranslate"><span class="pre">P</span></code>].</p>
</dd></dl>

<dl class="function">
<dt id="imaplib.ParseFlags">
<code class="descclassname">imaplib.</code><code class="descname">ParseFlags</code><span class="sig-paren">(</span><em>flagstr</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.ParseFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts an IMAP4 <code class="docutils literal notranslate"><span class="pre">FLAGS</span></code> response to a tuple of individual flags.</p>
</dd></dl>

<dl class="function">
<dt id="imaplib.Time2Internaldate">
<code class="descclassname">imaplib.</code><code class="descname">Time2Internaldate</code><span class="sig-paren">(</span><em>date_time</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.Time2Internaldate" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert <em>date_time</em> to an IMAP4 <code class="docutils literal notranslate"><span class="pre">INTERNALDATE</span></code> representation.  The
return value is a string in the form: <code class="docutils literal notranslate"><span class="pre">&quot;DD-Mmm-YYYY</span> <span class="pre">HH:MM:SS</span>
<span class="pre">+HHMM&quot;</span></code> (including double-quotes).  The <em>date_time</em> argument can be a
number (int or float) representing seconds since epoch (as returned
by <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>), a 9-tuple representing local time (as returned by
<a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a>), or a double-quoted string.  In the last case, it
is assumed to already be in the correct format.</p>
</dd></dl>

<p>Note that IMAP4 message numbers change as the mailbox changes; in particular,
after an <code class="docutils literal notranslate"><span class="pre">EXPUNGE</span></code> command performs deletions the remaining messages are
renumbered. So it is highly advisable to use UIDs instead, with the UID command.</p>
<p>At the end of the module, there is a test section that contains a more extensive
example of usage.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">Documents describing the protocol, and sources and binaries  for servers
implementing it, can all be found at the University of Washington’s <em>IMAP
Information Center</em> (<a class="reference external" href="https://www.washington.edu/imap/">https://www.washington.edu/imap/</a>).</p>
</div>
<div class="section" id="imap4-objects">
<span id="id1"></span><h2>20.10.1. IMAP4 Objects<a class="headerlink" href="#imap4-objects" title="Permalink to this headline">¶</a></h2>
<p>All IMAP4rev1 commands are represented by methods of the same name, either
upper-case or lower-case.</p>
<p>All arguments to commands are converted to strings, except for <code class="docutils literal notranslate"><span class="pre">AUTHENTICATE</span></code>,
and the last argument to <code class="docutils literal notranslate"><span class="pre">APPEND</span></code> which is passed as an IMAP4 literal.  If
necessary (the string contains IMAP4 protocol-sensitive characters and isn’t
enclosed with either parentheses or double quotes) each string is quoted.
However, the <em>password</em> argument to the <code class="docutils literal notranslate"><span class="pre">LOGIN</span></code> command is always quoted. If
you want to avoid having an argument string quoted (eg: the <em>flags</em> argument to
<code class="docutils literal notranslate"><span class="pre">STORE</span></code>) then enclose the string in parentheses (eg: <code class="docutils literal notranslate"><span class="pre">r'(\Deleted)'</span></code>).</p>
<p>Each command returns a tuple: <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">[data,</span> <span class="pre">...])</span></code> where <em>type</em> is usually
<code class="docutils literal notranslate"><span class="pre">'OK'</span></code> or <code class="docutils literal notranslate"><span class="pre">'NO'</span></code>, and <em>data</em> is either the text from the command response,
or mandated results from the command. Each <em>data</em> is either a string, or a
tuple. If a tuple, then the first part is the header of the response, and the
second part contains the data (ie: ‘literal’ value).</p>
<p>The <em>message_set</em> options to commands below is a string specifying one or more
messages to be acted upon.  It may be a simple message number (<code class="docutils literal notranslate"><span class="pre">'1'</span></code>), a range
of message numbers (<code class="docutils literal notranslate"><span class="pre">'2:4'</span></code>), or a group of non-contiguous ranges separated by
commas (<code class="docutils literal notranslate"><span class="pre">'1:3,6:9'</span></code>).  A range can contain an asterisk to indicate an infinite
upper bound (<code class="docutils literal notranslate"><span class="pre">'3:*'</span></code>).</p>
<p>An <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="imaplib.IMAP4.append">
<code class="descclassname">IMAP4.</code><code class="descname">append</code><span class="sig-paren">(</span><em>mailbox</em>, <em>flags</em>, <em>date_time</em>, <em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Append <em>message</em> to named mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.authenticate">
<code class="descclassname">IMAP4.</code><code class="descname">authenticate</code><span class="sig-paren">(</span><em>mechanism</em>, <em>authobject</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.authenticate" title="Permalink to this definition">¶</a></dt>
<dd><p>Authenticate command — requires response processing.</p>
<p><em>mechanism</em> specifies which authentication mechanism is to be used - it should
appear in the instance variable <code class="docutils literal notranslate"><span class="pre">capabilities</span></code> in the form <code class="docutils literal notranslate"><span class="pre">AUTH=mechanism</span></code>.</p>
<p><em>authobject</em> must be a callable object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">data</span> <span class="o">=</span> <span class="n">authobject</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
</pre></div>
</div>
<p>It will be called to process server continuation responses. It should return
<code class="docutils literal notranslate"><span class="pre">data</span></code> that will be encoded and sent to server. It should return <code class="docutils literal notranslate"><span class="pre">None</span></code> if
the client abort response <code class="docutils literal notranslate"><span class="pre">*</span></code> should be sent instead.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.check">
<code class="descclassname">IMAP4.</code><code class="descname">check</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.check" title="Permalink to this definition">¶</a></dt>
<dd><p>Checkpoint mailbox on server.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.close">
<code class="descclassname">IMAP4.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close currently selected mailbox. Deleted messages are removed from writable
mailbox. This is the recommended command before <code class="docutils literal notranslate"><span class="pre">LOGOUT</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.copy">
<code class="descclassname">IMAP4.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>message_set</em>, <em>new_mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy <em>message_set</em> messages onto end of <em>new_mailbox</em>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.create">
<code class="descclassname">IMAP4.</code><code class="descname">create</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create new mailbox named <em>mailbox</em>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.delete">
<code class="descclassname">IMAP4.</code><code class="descname">delete</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete old mailbox named <em>mailbox</em>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.deleteacl">
<code class="descclassname">IMAP4.</code><code class="descname">deleteacl</code><span class="sig-paren">(</span><em>mailbox</em>, <em>who</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.deleteacl" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the ACLs (remove any rights) set for who on mailbox.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.expunge">
<code class="descclassname">IMAP4.</code><code class="descname">expunge</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.expunge" title="Permalink to this definition">¶</a></dt>
<dd><p>Permanently remove deleted items from selected mailbox. Generates an <code class="docutils literal notranslate"><span class="pre">EXPUNGE</span></code>
response for each deleted message. Returned data contains a list of <code class="docutils literal notranslate"><span class="pre">EXPUNGE</span></code>
message numbers in order received.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.fetch">
<code class="descclassname">IMAP4.</code><code class="descname">fetch</code><span class="sig-paren">(</span><em>message_set</em>, <em>message_parts</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.fetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Fetch (parts of) messages.  <em>message_parts</em> should be a string of message part
names enclosed within parentheses, eg: <code class="docutils literal notranslate"><span class="pre">&quot;(UID</span> <span class="pre">BODY[TEXT])&quot;</span></code>.  Returned data
are tuples of message part envelope and data.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.getacl">
<code class="descclassname">IMAP4.</code><code class="descname">getacl</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.getacl" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the <code class="docutils literal notranslate"><span class="pre">ACL</span></code>s for <em>mailbox</em>. The method is non-standard, but is supported
by the <code class="docutils literal notranslate"><span class="pre">Cyrus</span></code> server.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.getannotation">
<code class="descclassname">IMAP4.</code><code class="descname">getannotation</code><span class="sig-paren">(</span><em>mailbox</em>, <em>entry</em>, <em>attribute</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.getannotation" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the specified <code class="docutils literal notranslate"><span class="pre">ANNOTATION</span></code>s for <em>mailbox</em>. The method is
non-standard, but is supported by the <code class="docutils literal notranslate"><span class="pre">Cyrus</span></code> server.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.getquota">
<code class="descclassname">IMAP4.</code><code class="descname">getquota</code><span class="sig-paren">(</span><em>root</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.getquota" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the <code class="docutils literal notranslate"><span class="pre">quota</span></code> <em>root</em>’s resource usage and limits. This method is part of the
IMAP4 QUOTA extension defined in rfc2087.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.getquotaroot">
<code class="descclassname">IMAP4.</code><code class="descname">getquotaroot</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.getquotaroot" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the list of <code class="docutils literal notranslate"><span class="pre">quota</span></code> <code class="docutils literal notranslate"><span class="pre">roots</span></code> for the named <em>mailbox</em>. This method is part
of the IMAP4 QUOTA extension defined in rfc2087.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.list">
<code class="descclassname">IMAP4.</code><code class="descname">list</code><span class="sig-paren">(</span><span class="optional">[</span><em>directory</em><span class="optional">[</span>, <em>pattern</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.list" title="Permalink to this definition">¶</a></dt>
<dd><p>List mailbox names in <em>directory</em> matching <em>pattern</em>.  <em>directory</em> defaults to
the top-level mail folder, and <em>pattern</em> defaults to match anything.  Returned
data contains a list of <code class="docutils literal notranslate"><span class="pre">LIST</span></code> responses.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.login">
<code class="descclassname">IMAP4.</code><code class="descname">login</code><span class="sig-paren">(</span><em>user</em>, <em>password</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.login" title="Permalink to this definition">¶</a></dt>
<dd><p>Identify the client using a plaintext password. The <em>password</em> will be quoted.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.login_cram_md5">
<code class="descclassname">IMAP4.</code><code class="descname">login_cram_md5</code><span class="sig-paren">(</span><em>user</em>, <em>password</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.login_cram_md5" title="Permalink to this definition">¶</a></dt>
<dd><p>Force use of <code class="docutils literal notranslate"><span class="pre">CRAM-MD5</span></code> authentication when identifying the client to protect
the password.  Will only work if the server <code class="docutils literal notranslate"><span class="pre">CAPABILITY</span></code> response includes the
phrase <code class="docutils literal notranslate"><span class="pre">AUTH=CRAM-MD5</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.logout">
<code class="descclassname">IMAP4.</code><code class="descname">logout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.logout" title="Permalink to this definition">¶</a></dt>
<dd><p>Shutdown connection to server. Returns server <code class="docutils literal notranslate"><span class="pre">BYE</span></code> response.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.lsub">
<code class="descclassname">IMAP4.</code><code class="descname">lsub</code><span class="sig-paren">(</span><span class="optional">[</span><em>directory</em><span class="optional">[</span>, <em>pattern</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.lsub" title="Permalink to this definition">¶</a></dt>
<dd><p>List subscribed mailbox names in directory matching pattern. <em>directory</em>
defaults to the top level directory and <em>pattern</em> defaults to match any mailbox.
Returned data are tuples of message part envelope and data.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.myrights">
<code class="descclassname">IMAP4.</code><code class="descname">myrights</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.myrights" title="Permalink to this definition">¶</a></dt>
<dd><p>Show my ACLs for a mailbox (i.e. the rights that I have on mailbox).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.namespace">
<code class="descclassname">IMAP4.</code><code class="descname">namespace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns IMAP namespaces as defined in RFC2342.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.noop">
<code class="descclassname">IMAP4.</code><code class="descname">noop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.noop" title="Permalink to this definition">¶</a></dt>
<dd><p>Send <code class="docutils literal notranslate"><span class="pre">NOOP</span></code> to server.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.open">
<code class="descclassname">IMAP4.</code><code class="descname">open</code><span class="sig-paren">(</span><em>host</em>, <em>port</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Opens socket to <em>port</em> at <em>host</em>.  This method is implicitly called by
the <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a> constructor.  The connection objects established by this
method will be used in the <a class="reference internal" href="#imaplib.IMAP4.read" title="imaplib.IMAP4.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">IMAP4.read()</span></code></a>, <a class="reference internal" href="#imaplib.IMAP4.readline" title="imaplib.IMAP4.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">IMAP4.readline()</span></code></a>,
<a class="reference internal" href="#imaplib.IMAP4.send" title="imaplib.IMAP4.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">IMAP4.send()</span></code></a>, and <a class="reference internal" href="#imaplib.IMAP4.shutdown" title="imaplib.IMAP4.shutdown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">IMAP4.shutdown()</span></code></a> methods.  You may override
this method.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.partial">
<code class="descclassname">IMAP4.</code><code class="descname">partial</code><span class="sig-paren">(</span><em>message_num</em>, <em>message_part</em>, <em>start</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.partial" title="Permalink to this definition">¶</a></dt>
<dd><p>Fetch truncated part of a message. Returned data is a tuple of message part
envelope and data.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.proxyauth">
<code class="descclassname">IMAP4.</code><code class="descname">proxyauth</code><span class="sig-paren">(</span><em>user</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.proxyauth" title="Permalink to this definition">¶</a></dt>
<dd><p>Assume authentication as <em>user</em>. Allows an authorised administrator to proxy
into any user’s mailbox.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.read">
<code class="descclassname">IMAP4.</code><code class="descname">read</code><span class="sig-paren">(</span><em>size</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads <em>size</em> bytes from the remote server. You may override this method.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.readline">
<code class="descclassname">IMAP4.</code><code class="descname">readline</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads one line from the remote server. You may override this method.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.recent">
<code class="descclassname">IMAP4.</code><code class="descname">recent</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.recent" title="Permalink to this definition">¶</a></dt>
<dd><p>Prompt server for an update. Returned data is <code class="docutils literal notranslate"><span class="pre">None</span></code> if no new messages, else
value of <code class="docutils literal notranslate"><span class="pre">RECENT</span></code> response.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.rename">
<code class="descclassname">IMAP4.</code><code class="descname">rename</code><span class="sig-paren">(</span><em>oldmailbox</em>, <em>newmailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.rename" title="Permalink to this definition">¶</a></dt>
<dd><p>Rename mailbox named <em>oldmailbox</em> to <em>newmailbox</em>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.response">
<code class="descclassname">IMAP4.</code><code class="descname">response</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.response" title="Permalink to this definition">¶</a></dt>
<dd><p>Return data for response <em>code</em> if received, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. Returns the given
code, instead of the usual type.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.search">
<code class="descclassname">IMAP4.</code><code class="descname">search</code><span class="sig-paren">(</span><em>charset</em>, <em>criterion</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.search" title="Permalink to this definition">¶</a></dt>
<dd><p>Search mailbox for matching messages.  <em>charset</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case
no <code class="docutils literal notranslate"><span class="pre">CHARSET</span></code> will be specified in the request to the server.  The IMAP
protocol requires that at least one criterion be specified; an exception will be
raised when the server returns an error.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># M is a connected IMAP4 instance...</span>
<span class="n">typ</span><span class="p">,</span> <span class="n">msgnums</span> <span class="o">=</span> <span class="n">M</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;FROM&#39;</span><span class="p">,</span> <span class="s1">&#39;&quot;LDJ&quot;&#39;</span><span class="p">)</span>

<span class="c1"># or:</span>
<span class="n">typ</span><span class="p">,</span> <span class="n">msgnums</span> <span class="o">=</span> <span class="n">M</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;(FROM &quot;LDJ&quot;)&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.select">
<code class="descclassname">IMAP4.</code><code class="descname">select</code><span class="sig-paren">(</span><span class="optional">[</span><em>mailbox</em><span class="optional">[</span>, <em>readonly</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.select" title="Permalink to this definition">¶</a></dt>
<dd><p>Select a mailbox. Returned data is the count of messages in <em>mailbox</em>
(<code class="docutils literal notranslate"><span class="pre">EXISTS</span></code> response).  The default <em>mailbox</em> is <code class="docutils literal notranslate"><span class="pre">'INBOX'</span></code>.  If the <em>readonly</em>
flag is set, modifications to the mailbox are not allowed.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.send">
<code class="descclassname">IMAP4.</code><code class="descname">send</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends <code class="docutils literal notranslate"><span class="pre">data</span></code> to the remote server. You may override this method.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.setacl">
<code class="descclassname">IMAP4.</code><code class="descname">setacl</code><span class="sig-paren">(</span><em>mailbox</em>, <em>who</em>, <em>what</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.setacl" title="Permalink to this definition">¶</a></dt>
<dd><p>Set an <code class="docutils literal notranslate"><span class="pre">ACL</span></code> for <em>mailbox</em>. The method is non-standard, but is supported by
the <code class="docutils literal notranslate"><span class="pre">Cyrus</span></code> server.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.setannotation">
<code class="descclassname">IMAP4.</code><code class="descname">setannotation</code><span class="sig-paren">(</span><em>mailbox</em>, <em>entry</em>, <em>attribute</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.setannotation" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <code class="docutils literal notranslate"><span class="pre">ANNOTATION</span></code>s for <em>mailbox</em>. The method is non-standard, but is
supported by the <code class="docutils literal notranslate"><span class="pre">Cyrus</span></code> server.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.setquota">
<code class="descclassname">IMAP4.</code><code class="descname">setquota</code><span class="sig-paren">(</span><em>root</em>, <em>limits</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.setquota" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <code class="docutils literal notranslate"><span class="pre">quota</span></code> <em>root</em>’s resource <em>limits</em>. This method is part of the IMAP4
QUOTA extension defined in rfc2087.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.shutdown">
<code class="descclassname">IMAP4.</code><code class="descname">shutdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Close connection established in <code class="docutils literal notranslate"><span class="pre">open</span></code>.  This method is implicitly
called by <a class="reference internal" href="#imaplib.IMAP4.logout" title="imaplib.IMAP4.logout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">IMAP4.logout()</span></code></a>.  You may override this method.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.socket">
<code class="descclassname">IMAP4.</code><code class="descname">socket</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.socket" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns socket instance used to connect to server.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.sort">
<code class="descclassname">IMAP4.</code><code class="descname">sort</code><span class="sig-paren">(</span><em>sort_criteria</em>, <em>charset</em>, <em>search_criterion</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.sort" title="Permalink to this definition">¶</a></dt>
<dd><p>The <code class="docutils literal notranslate"><span class="pre">sort</span></code> command is a variant of <code class="docutils literal notranslate"><span class="pre">search</span></code> with sorting semantics for the
results.  Returned data contains a space separated list of matching message
numbers.</p>
<p>Sort has two arguments before the <em>search_criterion</em> argument(s); a
parenthesized list of <em>sort_criteria</em>, and the searching <em>charset</em>.  Note that
unlike <code class="docutils literal notranslate"><span class="pre">search</span></code>, the searching <em>charset</em> argument is mandatory.  There is also
a <code class="docutils literal notranslate"><span class="pre">uid</span> <span class="pre">sort</span></code> command which corresponds to <code class="docutils literal notranslate"><span class="pre">sort</span></code> the way that <code class="docutils literal notranslate"><span class="pre">uid</span> <span class="pre">search</span></code>
corresponds to <code class="docutils literal notranslate"><span class="pre">search</span></code>.  The <code class="docutils literal notranslate"><span class="pre">sort</span></code> command first searches the mailbox for
messages that match the given searching criteria using the charset argument for
the interpretation of strings in the searching criteria.  It then returns the
numbers of matching messages.</p>
<p>This is an <code class="docutils literal notranslate"><span class="pre">IMAP4rev1</span></code> extension command.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.status">
<code class="descclassname">IMAP4.</code><code class="descname">status</code><span class="sig-paren">(</span><em>mailbox</em>, <em>names</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.status" title="Permalink to this definition">¶</a></dt>
<dd><p>Request named status conditions for <em>mailbox</em>.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.store">
<code class="descclassname">IMAP4.</code><code class="descname">store</code><span class="sig-paren">(</span><em>message_set</em>, <em>command</em>, <em>flag_list</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.store" title="Permalink to this definition">¶</a></dt>
<dd><p>Alters flag dispositions for messages in mailbox.  <em>command</em> is specified by
section 6.4.6 of <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2060.html"><strong>RFC 2060</strong></a> as being one of “FLAGS”, “+FLAGS”, or “-FLAGS”,
optionally with a suffix of “.SILENT”.</p>
<p>For example, to set the delete flag on all messages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">typ</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">M</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;ALL&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">data</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">split</span><span class="p">():</span>
   <span class="n">M</span><span class="o">.</span><span class="n">store</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="s1">&#39;+FLAGS&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="se">\\</span><span class="s1">Deleted&#39;</span><span class="p">)</span>
<span class="n">M</span><span class="o">.</span><span class="n">expunge</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.subscribe">
<code class="descclassname">IMAP4.</code><code class="descname">subscribe</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.subscribe" title="Permalink to this definition">¶</a></dt>
<dd><p>Subscribe to new mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.thread">
<code class="descclassname">IMAP4.</code><code class="descname">thread</code><span class="sig-paren">(</span><em>threading_algorithm</em>, <em>charset</em>, <em>search_criterion</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.thread" title="Permalink to this definition">¶</a></dt>
<dd><p>The <code class="docutils literal notranslate"><span class="pre">thread</span></code> command is a variant of <code class="docutils literal notranslate"><span class="pre">search</span></code> with threading semantics for
the results.  Returned data contains a space separated list of thread members.</p>
<p>Thread members consist of zero or more messages numbers, delimited by spaces,
indicating successive parent and child.</p>
<p>Thread has two arguments before the <em>search_criterion</em> argument(s); a
<em>threading_algorithm</em>, and the searching <em>charset</em>.  Note that unlike
<code class="docutils literal notranslate"><span class="pre">search</span></code>, the searching <em>charset</em> argument is mandatory.  There is also a
<code class="docutils literal notranslate"><span class="pre">uid</span> <span class="pre">thread</span></code> command which corresponds to <code class="docutils literal notranslate"><span class="pre">thread</span></code> the way that <code class="docutils literal notranslate"><span class="pre">uid</span>
<span class="pre">search</span></code> corresponds to <code class="docutils literal notranslate"><span class="pre">search</span></code>.  The <code class="docutils literal notranslate"><span class="pre">thread</span></code> command first searches the
mailbox for messages that match the given searching criteria using the charset
argument for the interpretation of strings in the searching criteria. It then
returns the matching messages threaded according to the specified threading
algorithm.</p>
<p>This is an <code class="docutils literal notranslate"><span class="pre">IMAP4rev1</span></code> extension command.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.uid">
<code class="descclassname">IMAP4.</code><code class="descname">uid</code><span class="sig-paren">(</span><em>command</em>, <em>arg</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.uid" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute command args with messages identified by UID, rather than message
number.  Returns response appropriate to command.  At least one argument must be
supplied; if none are provided, the server will return an error and an exception
will be raised.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.unsubscribe">
<code class="descclassname">IMAP4.</code><code class="descname">unsubscribe</code><span class="sig-paren">(</span><em>mailbox</em><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.unsubscribe" title="Permalink to this definition">¶</a></dt>
<dd><p>Unsubscribe from old mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="imaplib.IMAP4.xatom">
<code class="descclassname">IMAP4.</code><code class="descname">xatom</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>arg</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4.xatom" title="Permalink to this definition">¶</a></dt>
<dd><p>Allow simple extension commands notified by server in <code class="docutils literal notranslate"><span class="pre">CAPABILITY</span></code> response.</p>
</dd></dl>

<p>Instances of <a class="reference internal" href="#imaplib.IMAP4_SSL" title="imaplib.IMAP4_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4_SSL</span></code></a> have just one additional method:</p>
<dl class="method">
<dt id="imaplib.IMAP4_SSL.ssl">
<code class="descclassname">IMAP4_SSL.</code><code class="descname">ssl</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imaplib.IMAP4_SSL.ssl" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns SSLObject instance used for the secure connection with the server.</p>
</dd></dl>

<p>The following attributes are defined on instances of <a class="reference internal" href="#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">IMAP4</span></code></a>:</p>
<dl class="attribute">
<dt id="imaplib.IMAP4.PROTOCOL_VERSION">
<code class="descclassname">IMAP4.</code><code class="descname">PROTOCOL_VERSION</code><a class="headerlink" href="#imaplib.IMAP4.PROTOCOL_VERSION" title="Permalink to this definition">¶</a></dt>
<dd><p>The most recent supported protocol in the <code class="docutils literal notranslate"><span class="pre">CAPABILITY</span></code> response from the
server.</p>
</dd></dl>

<dl class="attribute">
<dt id="imaplib.IMAP4.debug">
<code class="descclassname">IMAP4.</code><code class="descname">debug</code><a class="headerlink" href="#imaplib.IMAP4.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Integer value to control debugging output.  The initialize value is taken from
the module variable <code class="docutils literal notranslate"><span class="pre">Debug</span></code>.  Values greater than three trace each command.</p>
</dd></dl>

</div>
<div class="section" id="imap4-example">
<span id="id2"></span><h2>20.10.2. IMAP4 Example<a class="headerlink" href="#imap4-example" title="Permalink to this headline">¶</a></h2>
<p>Here is a minimal example (without error checking) that opens a mailbox and
retrieves and prints all messages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">getpass</span><span class="o">,</span> <span class="nn">imaplib</span>

<span class="n">M</span> <span class="o">=</span> <span class="n">imaplib</span><span class="o">.</span><span class="n">IMAP4</span><span class="p">()</span>
<span class="n">M</span><span class="o">.</span><span class="n">login</span><span class="p">(</span><span class="n">getpass</span><span class="o">.</span><span class="n">getuser</span><span class="p">(),</span> <span class="n">getpass</span><span class="o">.</span><span class="n">getpass</span><span class="p">())</span>
<span class="n">M</span><span class="o">.</span><span class="n">select</span><span class="p">()</span>
<span class="n">typ</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">M</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;ALL&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">data</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">split</span><span class="p">():</span>
    <span class="n">typ</span><span class="p">,</span> <span class="n">data</span> <span class="o">=</span> <span class="n">M</span><span class="o">.</span><span class="n">fetch</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="s1">&#39;(RFC822)&#39;</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s1">&#39;Message </span><span class="si">%s</span><span class="se">\n</span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">])</span>
<span class="n">M</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">M</span><span class="o">.</span><span class="n">logout</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a><ul>
<li><a class="reference internal" href="#imap4-objects">20.10.1. IMAP4 Objects</a></li>
<li><a class="reference internal" href="#imap4-example">20.10.2. IMAP4 Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="poplib.html"
                        title="previous chapter">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="nntplib.html"
                        title="next chapter">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imaplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="nntplib.html" title="20.11. nntplib — NNTP protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="poplib.html" title="20.9. poplib — POP3 protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�k�s�1�1html/library/imgfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.11. imgfile — Support for SGI imglib files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.12. jpeg — Read and write JPEG files" href="jpeg.html" />
    <link rel="prev" title="39.8. gl — Graphics Library interface" href="gl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imgfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="jpeg.html" title="39.12. jpeg — Read and write JPEG files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gl.html" title="39.8. gl — Graphics Library interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imgfile">
<span id="imgfile-support-for-sgi-imglib-files"></span><h1>39.11. <a class="reference internal" href="#module-imgfile" title="imgfile: Support for SGI imglib files. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code></a> — Support for SGI imglib files<a class="headerlink" href="#module-imgfile" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-imgfile" title="imgfile: Support for SGI imglib files. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-imgfile" title="imgfile: Support for SGI imglib files. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code></a> module allows Python programs to access SGI imglib image
files (also known as <code class="file docutils literal notranslate"><span class="pre">.rgb</span></code> files).  The module is far from complete, but
is provided anyway since the functionality that there is enough in some cases.
Currently, colormap files are not supported.</p>
<p>The module defines the following variables and functions:</p>
<dl class="exception">
<dt id="imgfile.error">
<em class="property">exception </em><code class="descclassname">imgfile.</code><code class="descname">error</code><a class="headerlink" href="#imgfile.error" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised on all errors, such as unsupported file type, etc.</p>
</dd></dl>

<dl class="function">
<dt id="imgfile.getsizes">
<code class="descclassname">imgfile.</code><code class="descname">getsizes</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#imgfile.getsizes" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns a tuple <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y,</span> <span class="pre">z)</span></code> where <em>x</em> and <em>y</em> are the size of
the image in pixels and <em>z</em> is the number of bytes per pixel. Only 3 byte RGB
pixels and 1 byte greyscale pixels are currently supported.</p>
</dd></dl>

<dl class="function">
<dt id="imgfile.read">
<code class="descclassname">imgfile.</code><code class="descname">read</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#imgfile.read" title="Permalink to this definition">¶</a></dt>
<dd><p>This function reads and decodes the image on the specified file, and returns it
as a Python string. The string has either 1 byte greyscale pixels or 4 byte RGBA
pixels. The bottom left pixel is the first in the string. This format is
suitable to pass to <code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectwrite()</span></code>, for instance.</p>
</dd></dl>

<dl class="function">
<dt id="imgfile.readscaled">
<code class="descclassname">imgfile.</code><code class="descname">readscaled</code><span class="sig-paren">(</span><em>file</em>, <em>x</em>, <em>y</em>, <em>filter</em><span class="optional">[</span>, <em>blur</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imgfile.readscaled" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is identical to read but it returns an image that is scaled to the
given <em>x</em> and <em>y</em> sizes. If the <em>filter</em> and <em>blur</em> parameters are omitted
scaling is done by simply dropping or duplicating pixels, so the result will be
less than perfect, especially for computer-generated images.</p>
<p>Alternatively, you can specify a filter to use to smooth the image after
scaling. The filter forms supported are <code class="docutils literal notranslate"><span class="pre">'impulse'</span></code>, <code class="docutils literal notranslate"><span class="pre">'box'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'triangle'</span></code>, <code class="docutils literal notranslate"><span class="pre">'quadratic'</span></code> and <code class="docutils literal notranslate"><span class="pre">'gaussian'</span></code>. If a filter is specified
<em>blur</em> is an optional parameter specifying the blurriness of the filter. It
defaults to <code class="docutils literal notranslate"><span class="pre">1.0</span></code>.</p>
<p><a class="reference internal" href="#imgfile.readscaled" title="imgfile.readscaled"><code class="xref py py-func docutils literal notranslate"><span class="pre">readscaled()</span></code></a> makes no attempt to keep the aspect ratio correct, so that is
the users’ responsibility.</p>
</dd></dl>

<dl class="function">
<dt id="imgfile.ttob">
<code class="descclassname">imgfile.</code><code class="descname">ttob</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#imgfile.ttob" title="Permalink to this definition">¶</a></dt>
<dd><p>This function sets a global flag which defines whether the scan lines of the
image are read or written from bottom to top (flag is zero, compatible with SGI
GL) or from top to bottom(flag is one, compatible with X).  The default is zero.</p>
</dd></dl>

<dl class="function">
<dt id="imgfile.write">
<code class="descclassname">imgfile.</code><code class="descname">write</code><span class="sig-paren">(</span><em>file</em>, <em>data</em>, <em>x</em>, <em>y</em>, <em>z</em><span class="sig-paren">)</span><a class="headerlink" href="#imgfile.write" title="Permalink to this definition">¶</a></dt>
<dd><p>This function writes the RGB or greyscale data in <em>data</em> to image file <em>file</em>.
<em>x</em> and <em>y</em> give the size of the image, <em>z</em> is 1 for 1 byte greyscale images or
3 for RGB images (which are stored as 4 byte values of which only the lower
three bytes are used). These are the formats returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectread()</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="gl.html"
                        title="previous chapter">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="jpeg.html"
                        title="next chapter">39.12. <code class="docutils literal notranslate"><span class="pre">jpeg</span></code> — Read and write JPEG files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imgfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="jpeg.html" title="39.12. jpeg — Read and write JPEG files"
             >next</a> |</li>
        <li class="right" >
          <a href="gl.html" title="39.8. gl — Graphics Library interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����/�/html/library/imghdr.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.8. imghdr — Determine the type of an image &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.9. sndhdr — Determine type of sound file" href="sndhdr.html" />
    <link rel="prev" title="21.7. colorsys — Conversions between color systems" href="colorsys.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imghdr.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sndhdr.html" title="21.9. sndhdr — Determine type of sound file"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="colorsys.html" title="21.7. colorsys — Conversions between color systems"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imghdr">
<span id="imghdr-determine-the-type-of-an-image"></span><h1>21.8. <a class="reference internal" href="#module-imghdr" title="imghdr: Determine the type of image contained in a file or byte stream."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imghdr</span></code></a> — Determine the type of an image<a class="headerlink" href="#module-imghdr" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/imghdr.py">Lib/imghdr.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-imghdr" title="imghdr: Determine the type of image contained in a file or byte stream."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imghdr</span></code></a> module determines the type of image contained in a file or
byte stream.</p>
<p>The <a class="reference internal" href="#module-imghdr" title="imghdr: Determine the type of image contained in a file or byte stream."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imghdr</span></code></a> module defines the following function:</p>
<dl class="function">
<dt id="imghdr.what">
<code class="descclassname">imghdr.</code><code class="descname">what</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>h</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imghdr.what" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests the image data contained in the file named by <em>filename</em>, and returns a
string describing the image type.  If optional <em>h</em> is provided, the <em>filename</em>
is ignored and <em>h</em> is assumed to contain the byte stream to test.</p>
</dd></dl>

<p>The following image types are recognized, as listed below with the return value
from <a class="reference internal" href="#imghdr.what" title="imghdr.what"><code class="xref py py-func docutils literal notranslate"><span class="pre">what()</span></code></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="26%" />
<col width="74%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Image format</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'rgb'</span></code></td>
<td>SGI ImgLib Files</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'gif'</span></code></td>
<td>GIF 87a and 89a Files</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'pbm'</span></code></td>
<td>Portable Bitmap Files</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'pgm'</span></code></td>
<td>Portable Graymap Files</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'ppm'</span></code></td>
<td>Portable Pixmap Files</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'tiff'</span></code></td>
<td>TIFF Files</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'rast'</span></code></td>
<td>Sun Raster Files</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'xbm'</span></code></td>
<td>X Bitmap Files</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'jpeg'</span></code></td>
<td>JPEG data in JFIF or Exif formats</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'bmp'</span></code></td>
<td>BMP files</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'png'</span></code></td>
<td>Portable Network Graphics</td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>Exif detection.</p>
</div>
<p>You can extend the list of file types <a class="reference internal" href="#module-imghdr" title="imghdr: Determine the type of image contained in a file or byte stream."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imghdr</span></code></a> can recognize by appending
to this variable:</p>
<dl class="data">
<dt id="imghdr.tests">
<code class="descclassname">imghdr.</code><code class="descname">tests</code><a class="headerlink" href="#imghdr.tests" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of functions performing the individual tests.  Each function takes two
arguments: the byte-stream and an open file-like object. When <a class="reference internal" href="#imghdr.what" title="imghdr.what"><code class="xref py py-func docutils literal notranslate"><span class="pre">what()</span></code></a> is
called with a byte-stream, the file-like object will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>The test function should return a string describing the image type if the test
succeeded, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if it failed.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">imghdr</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">imghdr</span><span class="o">.</span><span class="n">what</span><span class="p">(</span><span class="s1">&#39;bass.gif&#39;</span><span class="p">)</span>
<span class="go">&#39;gif&#39;</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="colorsys.html"
                        title="previous chapter">21.7. <code class="docutils literal notranslate"><span class="pre">colorsys</span></code> — Conversions between color systems</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sndhdr.html"
                        title="next chapter">21.9. <code class="docutils literal notranslate"><span class="pre">sndhdr</span></code> — Determine type of sound file</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imghdr.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sndhdr.html" title="21.9. sndhdr — Determine type of sound file"
             >next</a> |</li>
        <li class="right" >
          <a href="colorsys.html" title="21.7. colorsys — Conversions between color systems"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\$�a��html/library/imp.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.1. imp — Access the import internals &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.2. importlib — Convenience wrappers for __import__()" href="importlib.html" />
    <link rel="prev" title="31. Importing Modules" href="modules.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imp.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.2. importlib — Convenience wrappers for __import__()"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="31. Importing Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imp">
<span id="imp-access-the-import-internals"></span><h1>31.1. <a class="reference internal" href="#module-imp" title="imp: Access the implementation of the import statement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imp</span></code></a> — Access the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> internals<a class="headerlink" href="#module-imp" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module provides an interface to the mechanisms used to implement the
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.  It defines the following constants and functions:</p>
<dl class="function">
<dt id="imp.get_magic">
<code class="descclassname">imp.</code><code class="descname">get_magic</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.get_magic" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Return the magic string value used to recognize byte-compiled code files
(<code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files).  (This value may be different for each Python version.)</p>
</dd></dl>

<dl class="function">
<dt id="imp.get_suffixes">
<code class="descclassname">imp.</code><code class="descname">get_suffixes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.get_suffixes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of 3-element tuples, each describing a particular type of
module. Each triple has the form <code class="docutils literal notranslate"><span class="pre">(suffix,</span> <span class="pre">mode,</span> <span class="pre">type)</span></code>, where <em>suffix</em> is
a string to be appended to the module name to form the filename to search
for, <em>mode</em> is the mode string to pass to the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function
to open the file (this can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> for text files or <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> for binary
files), and <em>type</em> is the file type, which has one of the values
<a class="reference internal" href="#imp.PY_SOURCE" title="imp.PY_SOURCE"><code class="xref py py-const docutils literal notranslate"><span class="pre">PY_SOURCE</span></code></a>, <a class="reference internal" href="#imp.PY_COMPILED" title="imp.PY_COMPILED"><code class="xref py py-const docutils literal notranslate"><span class="pre">PY_COMPILED</span></code></a>, or <a class="reference internal" href="#imp.C_EXTENSION" title="imp.C_EXTENSION"><code class="xref py py-const docutils literal notranslate"><span class="pre">C_EXTENSION</span></code></a>, described
below.</p>
</dd></dl>

<dl class="function">
<dt id="imp.find_module">
<code class="descclassname">imp.</code><code class="descname">find_module</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>path</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.find_module" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to find the module <em>name</em>.  If <em>path</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the list of
directory names given by <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is searched, but first a few special
places are searched: the function tries to find a built-in module with the
given name (<a class="reference internal" href="#imp.C_BUILTIN" title="imp.C_BUILTIN"><code class="xref py py-const docutils literal notranslate"><span class="pre">C_BUILTIN</span></code></a>), then a frozen module (<a class="reference internal" href="#imp.PY_FROZEN" title="imp.PY_FROZEN"><code class="xref py py-const docutils literal notranslate"><span class="pre">PY_FROZEN</span></code></a>),
and on some systems some other places are looked in as well (on Windows, it
looks in the registry which may point to a specific file).</p>
<p>Otherwise, <em>path</em> must be a list of directory names; each directory is
searched for files with any of the suffixes returned by <a class="reference internal" href="#imp.get_suffixes" title="imp.get_suffixes"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_suffixes()</span></code></a>
above.  Invalid names in the list are silently ignored (but all list items
must be strings).</p>
<p>If search is successful, the return value is a 3-element tuple <code class="docutils literal notranslate"><span class="pre">(file,</span>
<span class="pre">pathname,</span> <span class="pre">description)</span></code>:</p>
<p><em>file</em> is an open file object positioned at the beginning, <em>pathname</em> is the
pathname of the file found, and <em>description</em> is a 3-element tuple as
contained in the list returned by <a class="reference internal" href="#imp.get_suffixes" title="imp.get_suffixes"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_suffixes()</span></code></a> describing the kind of
module found.</p>
<p>If the module does not live in a file, the returned <em>file</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
<em>pathname</em> is the empty string, and the <em>description</em> tuple contains empty
strings for its suffix and mode; the module type is indicated as given in
parentheses above.  If the search is unsuccessful, <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is
raised.  Other exceptions indicate problems with the arguments or
environment.</p>
<p>If the module is a package, <em>file</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>pathname</em> is the package
path and the last item in the <em>description</em> tuple is <a class="reference internal" href="#imp.PKG_DIRECTORY" title="imp.PKG_DIRECTORY"><code class="xref py py-const docutils literal notranslate"><span class="pre">PKG_DIRECTORY</span></code></a>.</p>
<p>This function does not handle hierarchical module names (names containing
dots).  In order to find <em>P.M</em>, that is, submodule <em>M</em> of package <em>P</em>, use
<a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a> and <a class="reference internal" href="#imp.load_module" title="imp.load_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">load_module()</span></code></a> to find and load package <em>P</em>, and
then use <a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a> with the <em>path</em> argument set to <code class="docutils literal notranslate"><span class="pre">P.__path__</span></code>.
When <em>P</em> itself has a dotted name, apply this recipe recursively.</p>
</dd></dl>

<dl class="function">
<dt id="imp.load_module">
<code class="descclassname">imp.</code><code class="descname">load_module</code><span class="sig-paren">(</span><em>name</em>, <em>file</em>, <em>pathname</em>, <em>description</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.load_module" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Load a module that was previously found by <a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a> (or by an
otherwise conducted search yielding compatible results).  This function does
more than importing the module: if the module was already imported, it is
equivalent to a <a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a>!  The <em>name</em> argument indicates the full
module name (including the package name, if this is a submodule of a
package).  The <em>file</em> argument is an open file, and <em>pathname</em> is the
corresponding file name; these can be <code class="docutils literal notranslate"><span class="pre">None</span></code> and <code class="docutils literal notranslate"><span class="pre">''</span></code>, respectively, when
the module is a package or not being loaded from a file.  The <em>description</em>
argument is a tuple, as would be returned by <a class="reference internal" href="#imp.get_suffixes" title="imp.get_suffixes"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_suffixes()</span></code></a>, describing
what kind of module must be loaded.</p>
<p>If the load is successful, the return value is the module object; otherwise,
an exception (usually <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>) is raised.</p>
<p><strong>Important:</strong> the caller is responsible for closing the <em>file</em> argument, if
it was not <code class="docutils literal notranslate"><span class="pre">None</span></code>, even when an exception is raised.  This is best done
using a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement.</p>
</dd></dl>

<dl class="function">
<dt id="imp.new_module">
<code class="descclassname">imp.</code><code class="descname">new_module</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.new_module" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new empty module object called <em>name</em>.  This object is <em>not</em> inserted
in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="imp.lock_held">
<code class="descclassname">imp.</code><code class="descname">lock_held</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.lock_held" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the import lock is currently held, else <code class="docutils literal notranslate"><span class="pre">False</span></code>. On
platforms without threads, always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>On platforms with threads, a thread executing an import holds an internal lock
until the import is complete. This lock blocks other threads from doing an
import until the original import completes, which in turn prevents other threads
from seeing incomplete module objects constructed by the original thread while
in the process of completing its import (and the imports, if any, triggered by
that).</p>
</dd></dl>

<dl class="function">
<dt id="imp.acquire_lock">
<code class="descclassname">imp.</code><code class="descname">acquire_lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.acquire_lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the interpreter’s import lock for the current thread.  This lock should
be used by import hooks to ensure thread-safety when importing modules.</p>
<p>Once a thread has acquired the import lock, the same thread may acquire it
again without blocking; the thread must release it once for each time it has
acquired it.</p>
<p>On platforms without threads, this function does nothing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="imp.release_lock">
<code class="descclassname">imp.</code><code class="descname">release_lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.release_lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the interpreter’s import lock. On platforms without threads, this
function does nothing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>The following constants with integer values, defined in this module, are used to
indicate the search result of <a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a>.</p>
<dl class="data">
<dt id="imp.PY_SOURCE">
<code class="descclassname">imp.</code><code class="descname">PY_SOURCE</code><a class="headerlink" href="#imp.PY_SOURCE" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as a source file.</p>
</dd></dl>

<dl class="data">
<dt id="imp.PY_COMPILED">
<code class="descclassname">imp.</code><code class="descname">PY_COMPILED</code><a class="headerlink" href="#imp.PY_COMPILED" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as a compiled code object file.</p>
</dd></dl>

<dl class="data">
<dt id="imp.C_EXTENSION">
<code class="descclassname">imp.</code><code class="descname">C_EXTENSION</code><a class="headerlink" href="#imp.C_EXTENSION" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as dynamically loadable shared library.</p>
</dd></dl>

<dl class="data">
<dt id="imp.PKG_DIRECTORY">
<code class="descclassname">imp.</code><code class="descname">PKG_DIRECTORY</code><a class="headerlink" href="#imp.PKG_DIRECTORY" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as a package directory.</p>
</dd></dl>

<dl class="data">
<dt id="imp.C_BUILTIN">
<code class="descclassname">imp.</code><code class="descname">C_BUILTIN</code><a class="headerlink" href="#imp.C_BUILTIN" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as a built-in module.</p>
</dd></dl>

<dl class="data">
<dt id="imp.PY_FROZEN">
<code class="descclassname">imp.</code><code class="descname">PY_FROZEN</code><a class="headerlink" href="#imp.PY_FROZEN" title="Permalink to this definition">¶</a></dt>
<dd><p>The module was found as a frozen module (see <a class="reference internal" href="#imp.init_frozen" title="imp.init_frozen"><code class="xref py py-func docutils literal notranslate"><span class="pre">init_frozen()</span></code></a>).</p>
</dd></dl>

<p>The following constant and functions are obsolete; their functionality is
available through <a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a> or <a class="reference internal" href="#imp.load_module" title="imp.load_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">load_module()</span></code></a>. They are kept
around for backward compatibility:</p>
<dl class="data">
<dt id="imp.SEARCH_ERROR">
<code class="descclassname">imp.</code><code class="descname">SEARCH_ERROR</code><a class="headerlink" href="#imp.SEARCH_ERROR" title="Permalink to this definition">¶</a></dt>
<dd><p>Unused.</p>
</dd></dl>

<dl class="function">
<dt id="imp.init_builtin">
<code class="descclassname">imp.</code><code class="descname">init_builtin</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.init_builtin" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the built-in module called <em>name</em> and return its module object along
with storing it in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.  If the module was already initialized, it
will be initialized <em>again</em>.  Re-initialization involves the copying of the
built-in module’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> from the cached module over the module’s entry in
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.  If there is no built-in module called <em>name</em>, <code class="docutils literal notranslate"><span class="pre">None</span></code> is
returned.</p>
</dd></dl>

<dl class="function">
<dt id="imp.init_frozen">
<code class="descclassname">imp.</code><code class="descname">init_frozen</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.init_frozen" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the frozen module called <em>name</em> and return its module object.  If
the module was already initialized, it will be initialized <em>again</em>.  If there
is no frozen module called <em>name</em>, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.  (Frozen modules are
modules written in Python whose compiled byte-code object is incorporated
into a custom-built Python interpreter by Python’s <strong class="program">freeze</strong>
utility. See <code class="file docutils literal notranslate"><span class="pre">Tools/freeze/</span></code> for now.)</p>
</dd></dl>

<dl class="function">
<dt id="imp.is_builtin">
<code class="descclassname">imp.</code><code class="descname">is_builtin</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.is_builtin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">1</span></code> if there is a built-in module called <em>name</em> which can be
initialized again.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if there is a built-in module called <em>name</em>
which cannot be initialized again (see <a class="reference internal" href="#imp.init_builtin" title="imp.init_builtin"><code class="xref py py-func docutils literal notranslate"><span class="pre">init_builtin()</span></code></a>).  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> if
there is no built-in module called <em>name</em>.</p>
</dd></dl>

<dl class="function">
<dt id="imp.is_frozen">
<code class="descclassname">imp.</code><code class="descname">is_frozen</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.is_frozen" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there is a frozen module (see <a class="reference internal" href="#imp.init_frozen" title="imp.init_frozen"><code class="xref py py-func docutils literal notranslate"><span class="pre">init_frozen()</span></code></a>) called
<em>name</em>, or <code class="docutils literal notranslate"><span class="pre">False</span></code> if there is no such module.</p>
</dd></dl>

<dl class="function">
<dt id="imp.load_compiled">
<code class="descclassname">imp.</code><code class="descname">load_compiled</code><span class="sig-paren">(</span><em>name</em>, <em>pathname</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.load_compiled" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Load and initialize a module implemented as a byte-compiled code file and return
its module object.  If the module was already initialized, it will be
initialized <em>again</em>.  The <em>name</em> argument is used to create or access a module
object.  The <em>pathname</em> argument points to the byte-compiled code file.  The
<em>file</em> argument is the byte-compiled code file, open for reading in binary mode,
from the beginning. It must currently be a real file object, not a user-defined
class emulating a file.</p>
</dd></dl>

<dl class="function">
<dt id="imp.load_dynamic">
<code class="descclassname">imp.</code><code class="descname">load_dynamic</code><span class="sig-paren">(</span><em>name</em>, <em>pathname</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.load_dynamic" title="Permalink to this definition">¶</a></dt>
<dd><p>Load and initialize a module implemented as a dynamically loadable shared
library and return its module object.  If the module was already initialized, it
will be initialized <em>again</em>. Re-initialization involves copying the <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>
attribute of the cached instance of the module over the value used in the module
cached in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.  The <em>pathname</em> argument must point to the shared
library.  The <em>name</em> argument is used to construct the name of the
initialization function: an external C function called <code class="docutils literal notranslate"><span class="pre">initname()</span></code> in the
shared library is called.  The optional <em>file</em> argument is ignored.  (Note:
using shared libraries is highly system dependent, and not all systems support
it.)</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> The import internals identify extension modules by filename, so doing
<code class="docutils literal notranslate"><span class="pre">foo</span> <span class="pre">=</span> <span class="pre">load_dynamic(&quot;foo&quot;,</span> <span class="pre">&quot;mod.so&quot;)</span></code> and
<code class="docutils literal notranslate"><span class="pre">bar</span> <span class="pre">=</span> <span class="pre">load_dynamic(&quot;bar&quot;,</span> <span class="pre">&quot;mod.so&quot;)</span></code> will result in both foo and bar
referring to the same module, regardless of whether or not
<code class="docutils literal notranslate"><span class="pre">mod.so</span></code> exports an <code class="docutils literal notranslate"><span class="pre">initbar</span></code> function. On systems which
support them, symlinks can be used to import multiple modules from
the same shared library, as each reference to the module will use
a different file name.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="imp.load_source">
<code class="descclassname">imp.</code><code class="descname">load_source</code><span class="sig-paren">(</span><em>name</em>, <em>pathname</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.load_source" title="Permalink to this definition">¶</a></dt>
<dd><p>Load and initialize a module implemented as a Python source file and return its
module object.  If the module was already initialized, it will be initialized
<em>again</em>.  The <em>name</em> argument is used to create or access a module object.  The
<em>pathname</em> argument points to the source file.  The <em>file</em> argument is the
source file, open for reading as text, from the beginning. It must currently be
a real file object, not a user-defined class emulating a file.  Note that if a
properly matching byte-compiled file (with suffix <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code>)
exists, it will be used instead of parsing the given source file.</p>
</dd></dl>

<dl class="class">
<dt id="imp.NullImporter">
<em class="property">class </em><code class="descclassname">imp.</code><code class="descname">NullImporter</code><span class="sig-paren">(</span><em>path_string</em><span class="sig-paren">)</span><a class="headerlink" href="#imp.NullImporter" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#imp.NullImporter" title="imp.NullImporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullImporter</span></code></a> type is a <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> import hook that handles
non-directory path strings by failing to find any modules.  Calling this type
with an existing directory or empty string raises <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.
Otherwise, a <a class="reference internal" href="#imp.NullImporter" title="imp.NullImporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullImporter</span></code></a> instance is returned.</p>
<p>Python adds instances of this type to <code class="docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code> for any path
entries that are not directories and are not handled by any other path hooks on
<code class="docutils literal notranslate"><span class="pre">sys.path_hooks</span></code>.  Instances have only one method:</p>
<dl class="method">
<dt id="imp.NullImporter.find_module">
<code class="descname">find_module</code><span class="sig-paren">(</span><em>fullname</em><span class="optional">[</span>, <em>path</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imp.NullImporter.find_module" title="Permalink to this definition">¶</a></dt>
<dd><p>This method always returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, indicating that the requested module could
not be found.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<div class="section" id="examples">
<span id="examples-imp"></span><h2>31.1.1. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>The following function emulates what was the standard import statement up to
Python 1.4 (no hierarchical module names).  (This <em>implementation</em> wouldn’t work
in that version, since <a class="reference internal" href="#imp.find_module" title="imp.find_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">find_module()</span></code></a> has been extended and
<a class="reference internal" href="#imp.load_module" title="imp.load_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">load_module()</span></code></a> has been added in 1.4.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">imp</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">def</span> <span class="nf">__import__</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="nb">globals</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="nb">locals</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fromlist</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="c1"># Fast path: see if the module has already been imported.</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">name</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
        <span class="k">pass</span>

    <span class="c1"># If any of the following calls raises an exception,</span>
    <span class="c1"># there&#39;s a problem we can&#39;t handle -- let the caller handle it.</span>

    <span class="n">fp</span><span class="p">,</span> <span class="n">pathname</span><span class="p">,</span> <span class="n">description</span> <span class="o">=</span> <span class="n">imp</span><span class="o">.</span><span class="n">find_module</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">imp</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">fp</span><span class="p">,</span> <span class="n">pathname</span><span class="p">,</span> <span class="n">description</span><span class="p">)</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="c1"># Since we may exit via an exception, close fp explicitly.</span>
        <span class="k">if</span> <span class="n">fp</span><span class="p">:</span>
            <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p id="index-5">A more complete example that implements hierarchical module names and includes a
<a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> function can be found in the module <code class="xref py py-mod docutils literal notranslate"><span class="pre">knee</span></code>.  The <code class="xref py py-mod docutils literal notranslate"><span class="pre">knee</span></code>
module can be found in <code class="file docutils literal notranslate"><span class="pre">Demo/imputil/</span></code> in the Python source distribution.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a><ul>
<li><a class="reference internal" href="#examples">31.1.1. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="modules.html"
                        title="previous chapter">31. Importing Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="importlib.html"
                        title="next chapter">31.2. <code class="docutils literal notranslate"><span class="pre">importlib</span></code> — Convenience wrappers for <code class="docutils literal notranslate"><span class="pre">__import__()</span></code></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imp.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.2. importlib — Convenience wrappers for __import__()"
             >next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="31. Importing Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�-�O�"�"html/library/importlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.2. importlib — Convenience wrappers for __import__() &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.3. imputil — Import utilities" href="imputil.html" />
    <link rel="prev" title="31.1. imp — Access the import internals" href="imp.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/importlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imputil.html" title="31.3. imputil — Import utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imp.html" title="31.1. imp — Access the import internals"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-importlib">
<span id="importlib-convenience-wrappers-for-import"></span><h1>31.2. <a class="reference internal" href="#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> — Convenience wrappers for <a class="reference internal" href="functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a><a class="headerlink" href="#module-importlib" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>This module is a minor subset of what is available in the more full-featured
package of the same name from Python 3.1 that provides a complete
implementation of <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>. What is here has been provided to
help ease in transitioning from 2.7 to 3.1.</p>
<dl class="function">
<dt id="importlib.import_module">
<code class="descclassname">importlib.</code><code class="descname">import_module</code><span class="sig-paren">(</span><em>name</em>, <em>package=None</em><span class="sig-paren">)</span><a class="headerlink" href="#importlib.import_module" title="Permalink to this definition">¶</a></dt>
<dd><p>Import a module. The <em>name</em> argument specifies what module to
import in absolute or relative terms
(e.g. either <code class="docutils literal notranslate"><span class="pre">pkg.mod</span></code> or <code class="docutils literal notranslate"><span class="pre">..mod</span></code>). If the name is
specified in relative terms, then the <em>package</em> argument must be
specified to the package which is to act as the anchor for resolving the
package name (e.g. <code class="docutils literal notranslate"><span class="pre">import_module('..mod',</span> <span class="pre">'pkg.subpkg')</span></code> will import
<code class="docutils literal notranslate"><span class="pre">pkg.mod</span></code>).  The specified module will be inserted into
<a class="reference internal" href="sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> and returned.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="imp.html"
                        title="previous chapter">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imputil.html"
                        title="next chapter">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/importlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imputil.html" title="31.3. imputil — Import utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="imp.html" title="31.1. imp — Access the import internals"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��
��html/library/imputil.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.3. imputil — Import utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.4. zipimport — Import modules from Zip archives" href="zipimport.html" />
    <link rel="prev" title="31.2. importlib — Convenience wrappers for __import__()" href="importlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/imputil.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zipimport.html" title="31.4. zipimport — Import modules from Zip archives"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.2. importlib — Convenience wrappers for __import__()"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-imputil">
<span id="imputil-import-utilities"></span><h1>31.3. <a class="reference internal" href="#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a> — Import utilities<a class="headerlink" href="#module-imputil" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">This module provides a very handy and useful mechanism for custom
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> hooks. Compared to the older <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> module,
<a class="reference internal" href="#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a> takes a dramatically simpler and more straight-forward
approach to custom <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> functions.</p>
<dl class="class">
<dt id="imputil.ImportManager">
<em class="property">class </em><code class="descclassname">imputil.</code><code class="descname">ImportManager</code><span class="sig-paren">(</span><span class="optional">[</span><em>fs_imp</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imputil.ImportManager" title="Permalink to this definition">¶</a></dt>
<dd><p>Manage the import process.</p>
<dl class="method">
<dt id="imputil.ImportManager.install">
<code class="descname">install</code><span class="sig-paren">(</span><span class="optional">[</span><em>namespace</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imputil.ImportManager.install" title="Permalink to this definition">¶</a></dt>
<dd><p>Install this ImportManager into the specified namespace.</p>
</dd></dl>

<dl class="method">
<dt id="imputil.ImportManager.uninstall">
<code class="descname">uninstall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#imputil.ImportManager.uninstall" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore the previous import mechanism.</p>
</dd></dl>

<dl class="method">
<dt id="imputil.ImportManager.add_suffix">
<code class="descname">add_suffix</code><span class="sig-paren">(</span><em>suffix</em>, <em>importFunc</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.ImportManager.add_suffix" title="Permalink to this definition">¶</a></dt>
<dd><p>Undocumented.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="imputil.Importer">
<em class="property">class </em><code class="descclassname">imputil.</code><code class="descname">Importer</code><a class="headerlink" href="#imputil.Importer" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for replacing standard import functions.</p>
<dl class="method">
<dt id="imputil.Importer.import_top">
<code class="descname">import_top</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.Importer.import_top" title="Permalink to this definition">¶</a></dt>
<dd><p>Import a top-level module.</p>
</dd></dl>

<dl class="method">
<dt id="imputil.Importer.get_code">
<code class="descname">get_code</code><span class="sig-paren">(</span><em>parent</em>, <em>modname</em>, <em>fqname</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.Importer.get_code" title="Permalink to this definition">¶</a></dt>
<dd><p>Find and retrieve the code for the given module.</p>
<p><em>parent</em> specifies a parent module to define a context for importing.
It may be <code class="docutils literal notranslate"><span class="pre">None</span></code>, indicating no particular context for the search.</p>
<p><em>modname</em> specifies a single module (not dotted) within the parent.</p>
<p><em>fqname</em> specifies the fully-qualified module name. This is a
(potentially) dotted name from the “root” of the module namespace
down to the modname.</p>
<p>If there is no parent, then modname==fqname.</p>
<p>This method should return <code class="docutils literal notranslate"><span class="pre">None</span></code>, or a 3-tuple.</p>
<blockquote>
<div><ul class="simple">
<li>If the module was not found, then <code class="docutils literal notranslate"><span class="pre">None</span></code> should be returned.</li>
<li>The first item of the 2- or 3-tuple should be the integer 0 or 1,
specifying whether the module that was found is a package or not.</li>
<li>The second item is the code object for the module (it will be
executed within the new module’s namespace). This item can also
be a fully-loaded module object (e.g. loaded from a shared lib).</li>
<li>The third item is a dictionary of name/value pairs that will be
inserted into new module before the code object is executed. This
is provided in case the module’s code expects certain values (such
as where the module was found). When the second item is a module
object, then these names/values will be inserted <em>after</em> the module
has been loaded/initialized.</li>
</ul>
</div></blockquote>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="imputil.BuiltinImporter">
<em class="property">class </em><code class="descclassname">imputil.</code><code class="descname">BuiltinImporter</code><a class="headerlink" href="#imputil.BuiltinImporter" title="Permalink to this definition">¶</a></dt>
<dd><p>Emulate the import mechanism for built-in and frozen modules.  This is a
sub-class of the <a class="reference internal" href="#imputil.Importer" title="imputil.Importer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Importer</span></code></a> class.</p>
<dl class="method">
<dt id="imputil.BuiltinImporter.get_code">
<code class="descname">get_code</code><span class="sig-paren">(</span><em>parent</em>, <em>modname</em>, <em>fqname</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.BuiltinImporter.get_code" title="Permalink to this definition">¶</a></dt>
<dd><p>Undocumented.</p>
</dd></dl>

</dd></dl>

<dl class="function">
<dt id="imputil.py_suffix_importer">
<code class="descclassname">imputil.</code><code class="descname">py_suffix_importer</code><span class="sig-paren">(</span><em>filename</em>, <em>finfo</em>, <em>fqname</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.py_suffix_importer" title="Permalink to this definition">¶</a></dt>
<dd><p>Undocumented.</p>
</dd></dl>

<dl class="class">
<dt id="imputil.DynLoadSuffixImporter">
<em class="property">class </em><code class="descclassname">imputil.</code><code class="descname">DynLoadSuffixImporter</code><span class="sig-paren">(</span><span class="optional">[</span><em>desc</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#imputil.DynLoadSuffixImporter" title="Permalink to this definition">¶</a></dt>
<dd><p>Undocumented.</p>
<dl class="method">
<dt id="imputil.DynLoadSuffixImporter.import_file">
<code class="descname">import_file</code><span class="sig-paren">(</span><em>filename</em>, <em>finfo</em>, <em>fqname</em><span class="sig-paren">)</span><a class="headerlink" href="#imputil.DynLoadSuffixImporter.import_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Undocumented.</p>
</dd></dl>

</dd></dl>

<div class="section" id="examples">
<span id="examples-imputil"></span><h2>31.3.1. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>This is a re-implementation of hierarchical module import.</p>
<p>This code is intended to be read, not executed.  However, it does work
– all you need to do to enable it is “import knee”.</p>
<p>(The name is a pun on the clunkier predecessor of this module, “ni”.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">imp</span><span class="o">,</span> <span class="nn">__builtin__</span>

<span class="c1"># Replacement for __import__()</span>
<span class="k">def</span> <span class="nf">import_hook</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="nb">globals</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="nb">locals</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">fromlist</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="n">parent</span> <span class="o">=</span> <span class="n">determine_parent</span><span class="p">(</span><span class="nb">globals</span><span class="p">)</span>
    <span class="n">q</span><span class="p">,</span> <span class="n">tail</span> <span class="o">=</span> <span class="n">find_head_package</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">load_tail</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">tail</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">fromlist</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">q</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="s2">&quot;__path__&quot;</span><span class="p">):</span>
        <span class="n">ensure_fromlist</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">fromlist</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">m</span>

<span class="k">def</span> <span class="nf">determine_parent</span><span class="p">(</span><span class="nb">globals</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">globals</span> <span class="ow">or</span>  <span class="ow">not</span> <span class="nb">globals</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span><span class="s2">&quot;__name__&quot;</span><span class="p">):</span>
        <span class="k">return</span> <span class="kc">None</span>
    <span class="n">pname</span> <span class="o">=</span> <span class="nb">globals</span><span class="p">[</span><span class="s1">&#39;__name__&#39;</span><span class="p">]</span>
    <span class="k">if</span> <span class="nb">globals</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span><span class="s2">&quot;__path__&quot;</span><span class="p">):</span>
        <span class="n">parent</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">pname</span><span class="p">]</span>
        <span class="k">assert</span> <span class="nb">globals</span> <span class="ow">is</span> <span class="n">parent</span><span class="o">.</span><span class="vm">__dict__</span>
        <span class="k">return</span> <span class="n">parent</span>
    <span class="k">if</span> <span class="s1">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">pname</span><span class="p">:</span>
        <span class="n">i</span> <span class="o">=</span> <span class="n">pname</span><span class="o">.</span><span class="n">rfind</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
        <span class="n">pname</span> <span class="o">=</span> <span class="n">pname</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span>
        <span class="n">parent</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">pname</span><span class="p">]</span>
        <span class="k">assert</span> <span class="n">parent</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">==</span> <span class="n">pname</span>
        <span class="k">return</span> <span class="n">parent</span>
    <span class="k">return</span> <span class="kc">None</span>

<span class="k">def</span> <span class="nf">find_head_package</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
    <span class="k">if</span> <span class="s1">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">name</span><span class="p">:</span>
        <span class="n">i</span> <span class="o">=</span> <span class="n">name</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
        <span class="n">head</span> <span class="o">=</span> <span class="n">name</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span>
        <span class="n">tail</span> <span class="o">=</span> <span class="n">name</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">head</span> <span class="o">=</span> <span class="n">name</span>
        <span class="n">tail</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>
    <span class="k">if</span> <span class="n">parent</span><span class="p">:</span>
        <span class="n">qname</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">parent</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">head</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">qname</span> <span class="o">=</span> <span class="n">head</span>
    <span class="n">q</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">head</span><span class="p">,</span> <span class="n">qname</span><span class="p">,</span> <span class="n">parent</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">q</span><span class="p">:</span> <span class="k">return</span> <span class="n">q</span><span class="p">,</span> <span class="n">tail</span>
    <span class="k">if</span> <span class="n">parent</span><span class="p">:</span>
        <span class="n">qname</span> <span class="o">=</span> <span class="n">head</span>
        <span class="n">parent</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="n">q</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">head</span><span class="p">,</span> <span class="n">qname</span><span class="p">,</span> <span class="n">parent</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">q</span><span class="p">:</span> <span class="k">return</span> <span class="n">q</span><span class="p">,</span> <span class="n">tail</span>
    <span class="k">raise</span> <span class="ne">ImportError</span><span class="p">(</span><span class="s2">&quot;No module named &quot;</span> <span class="o">+</span> <span class="n">qname</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">load_tail</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">tail</span><span class="p">):</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">q</span>
    <span class="k">while</span> <span class="n">tail</span><span class="p">:</span>
        <span class="n">i</span> <span class="o">=</span> <span class="n">tail</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span> <span class="n">i</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">tail</span><span class="p">)</span>
        <span class="n">head</span><span class="p">,</span> <span class="n">tail</span> <span class="o">=</span> <span class="n">tail</span><span class="p">[:</span><span class="n">i</span><span class="p">],</span> <span class="n">tail</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
        <span class="n">mname</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">head</span><span class="p">)</span>
        <span class="n">m</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">head</span><span class="p">,</span> <span class="n">mname</span><span class="p">,</span> <span class="n">m</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">m</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">ImportError</span><span class="p">(</span><span class="s2">&quot;No module named &quot;</span> <span class="o">+</span> <span class="n">mname</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">m</span>

<span class="k">def</span> <span class="nf">ensure_fromlist</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">fromlist</span><span class="p">,</span> <span class="n">recursive</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">sub</span> <span class="ow">in</span> <span class="n">fromlist</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">sub</span> <span class="o">==</span> <span class="s2">&quot;*&quot;</span><span class="p">:</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">recursive</span><span class="p">:</span>
                <span class="k">try</span><span class="p">:</span>
                    <span class="nb">all</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">__all__</span>
                <span class="k">except</span> <span class="ne">AttributeError</span><span class="p">:</span>
                    <span class="k">pass</span>
                <span class="k">else</span><span class="p">:</span>
                    <span class="n">ensure_fromlist</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="nb">all</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
            <span class="k">continue</span>
        <span class="k">if</span> <span class="n">sub</span> <span class="o">!=</span> <span class="s2">&quot;*&quot;</span> <span class="ow">and</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">m</span><span class="p">,</span> <span class="n">sub</span><span class="p">):</span>
            <span class="n">subname</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%s</span><span class="s2">.</span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">sub</span><span class="p">)</span>
            <span class="n">submod</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="n">sub</span><span class="p">,</span> <span class="n">subname</span><span class="p">,</span> <span class="n">m</span><span class="p">)</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">submod</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">ImportError</span><span class="p">(</span><span class="s2">&quot;No module named &quot;</span> <span class="o">+</span> <span class="n">subname</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">import_module</span><span class="p">(</span><span class="n">partname</span><span class="p">,</span> <span class="n">fqname</span><span class="p">,</span> <span class="n">parent</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">fqname</span><span class="p">]</span>
    <span class="k">except</span> <span class="ne">KeyError</span><span class="p">:</span>
        <span class="k">pass</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">fp</span><span class="p">,</span> <span class="n">pathname</span><span class="p">,</span> <span class="n">stuff</span> <span class="o">=</span> <span class="n">imp</span><span class="o">.</span><span class="n">find_module</span><span class="p">(</span><span class="n">partname</span><span class="p">,</span>
                                              <span class="n">parent</span> <span class="ow">and</span> <span class="n">parent</span><span class="o">.</span><span class="n">__path__</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
        <span class="k">return</span> <span class="kc">None</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">m</span> <span class="o">=</span> <span class="n">imp</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">fqname</span><span class="p">,</span> <span class="n">fp</span><span class="p">,</span> <span class="n">pathname</span><span class="p">,</span> <span class="n">stuff</span><span class="p">)</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">fp</span><span class="p">:</span> <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">parent</span><span class="p">:</span>
        <span class="nb">setattr</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">partname</span><span class="p">,</span> <span class="n">m</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">m</span>


<span class="c1"># Replacement for reload()</span>
<span class="k">def</span> <span class="nf">reload_hook</span><span class="p">(</span><span class="n">module</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">module</span><span class="o">.</span><span class="vm">__name__</span>
    <span class="k">if</span> <span class="s1">&#39;.&#39;</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">name</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">import_module</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">name</span><span class="o">.</span><span class="n">rfind</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
    <span class="n">pname</span> <span class="o">=</span> <span class="n">name</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span>
    <span class="n">parent</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">pname</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">import_module</span><span class="p">(</span><span class="n">name</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:],</span> <span class="n">name</span><span class="p">,</span> <span class="n">parent</span><span class="p">)</span>


<span class="c1"># Save the original hooks</span>
<span class="n">original_import</span> <span class="o">=</span> <span class="n">__builtin__</span><span class="o">.</span><span class="fm">__import__</span>
<span class="n">original_reload</span> <span class="o">=</span> <span class="n">__builtin__</span><span class="o">.</span><span class="n">reload</span>

<span class="c1"># Now install our hooks</span>
<span class="n">__builtin__</span><span class="o">.</span><span class="fm">__import__</span> <span class="o">=</span> <span class="n">import_hook</span>
<span class="n">__builtin__</span><span class="o">.</span><span class="n">reload</span> <span class="o">=</span> <span class="n">reload_hook</span>
</pre></div>
</div>
<p id="index-1">Also see the <code class="xref py py-mod docutils literal notranslate"><span class="pre">importers</span></code> module (which can be found
in <code class="file docutils literal notranslate"><span class="pre">Demo/imputil/</span></code> in the Python source distribution) for additional
examples.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a><ul>
<li><a class="reference internal" href="#examples">31.3.1. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="importlib.html"
                        title="previous chapter">31.2. <code class="docutils literal notranslate"><span class="pre">importlib</span></code> — Convenience wrappers for <code class="docutils literal notranslate"><span class="pre">__import__()</span></code></a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="zipimport.html"
                        title="next chapter">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/imputil.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="zipimport.html" title="31.4. zipimport — Import modules from Zip archives"
             >next</a> |</li>
        <li class="right" >
          <a href="importlib.html" title="31.2. importlib — Convenience wrappers for __import__()"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����4�4html/library/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>The Python Standard Library &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. Introduction" href="intro.html" />
    <link rel="prev" title="9. Full Grammar specification" href="../reference/grammar.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="intro.html" title="1. Introduction"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../reference/grammar.html" title="9. Full Grammar specification"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-python-standard-library">
<span id="library-index"></span><h1>The Python Standard Library<a class="headerlink" href="#the-python-standard-library" title="Permalink to this headline">¶</a></h1>
<p>While <a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a> describes the exact syntax and
semantics of the Python language, this library reference manual
describes the standard library that is distributed with Python. It also
describes some of the optional components that are commonly included
in Python distributions.</p>
<p>Python’s standard library is very extensive, offering a wide range of
facilities as indicated by the long table of contents listed below. The
library contains built-in modules (written in C) that provide access to
system functionality such as file I/O that would otherwise be
inaccessible to Python programmers, as well as modules written in Python
that provide standardized solutions for many problems that occur in
everyday programming. Some of these modules are explicitly designed to
encourage and enhance the portability of Python programs by abstracting
away platform-specifics into platform-neutral APIs.</p>
<p>The Python installers for the Windows platform usually include
the entire standard library and often also include many additional
components. For Unix-like operating systems Python is normally provided
as a collection of packages, so it may be necessary to use the packaging
tools provided with the operating system to obtain some or all of the
optional components.</p>
<p>In addition to the standard library, there is a growing collection of
several thousand components (from individual programs and modules to
packages and entire application development frameworks), available from
the <a class="reference external" href="https://pypi.org">Python Package Index</a>.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="intro.html">1. Introduction</a></li>
<li class="toctree-l1"><a class="reference internal" href="functions.html">2. Built-in Functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="functions.html#non-essential-built-in-functions">3. Non-essential Built-in Functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="constants.html">4. Built-in Constants</a><ul>
<li class="toctree-l2"><a class="reference internal" href="constants.html#constants-added-by-the-site-module">4.1. Constants added by the <code class="docutils literal notranslate"><span class="pre">site</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdtypes.html">5. Built-in Types</a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#truth-value-testing">5.1. Truth Value Testing</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#boolean-operations-and-or-not">5.2. Boolean Operations — <code class="docutils literal notranslate"><span class="pre">and</span></code>, <code class="docutils literal notranslate"><span class="pre">or</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#comparisons">5.3. Comparisons</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#numeric-types-int-float-long-complex">5.4. Numeric Types — <code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">float</span></code>, <code class="docutils literal notranslate"><span class="pre">long</span></code>, <code class="docutils literal notranslate"><span class="pre">complex</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#iterator-types">5.5. Iterator Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange">5.6. Sequence Types — <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">unicode</span></code>, <code class="docutils literal notranslate"><span class="pre">list</span></code>, <code class="docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="docutils literal notranslate"><span class="pre">bytearray</span></code>, <code class="docutils literal notranslate"><span class="pre">buffer</span></code>, <code class="docutils literal notranslate"><span class="pre">xrange</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#set-types-set-frozenset">5.7. Set Types — <code class="docutils literal notranslate"><span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">frozenset</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#mapping-types-dict">5.8. Mapping Types — <code class="docutils literal notranslate"><span class="pre">dict</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#file-objects">5.9. File Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#memoryview-type">5.10. memoryview type</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#context-manager-types">5.11. Context Manager Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#other-built-in-types">5.12. Other Built-in Types</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdtypes.html#special-attributes">5.13. Special Attributes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="exceptions.html">6. Built-in Exceptions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="exceptions.html#exception-hierarchy">6.1. Exception hierarchy</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="strings.html">7. String Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="string.html">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="re.html">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="struct.html">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a></li>
<li class="toctree-l2"><a class="reference internal" href="difflib.html">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a></li>
<li class="toctree-l2"><a class="reference internal" href="stringio.html">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></li>
<li class="toctree-l2"><a class="reference internal" href="stringio.html#module-cStringIO">7.6. <code class="docutils literal notranslate"><span class="pre">cStringIO</span></code> — Faster version of <code class="docutils literal notranslate"><span class="pre">StringIO</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="textwrap.html">7.7. <code class="docutils literal notranslate"><span class="pre">textwrap</span></code> — Text wrapping and filling</a></li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="unicodedata.html">7.9. <code class="docutils literal notranslate"><span class="pre">unicodedata</span></code> — Unicode Database</a></li>
<li class="toctree-l2"><a class="reference internal" href="stringprep.html">7.10. <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> — Internet String Preparation</a></li>
<li class="toctree-l2"><a class="reference internal" href="fpformat.html">7.11. <code class="docutils literal notranslate"><span class="pre">fpformat</span></code> — Floating point conversions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="datatypes.html">8. Data Types</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datetime.html">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a></li>
<li class="toctree-l2"><a class="reference internal" href="calendar.html">8.2. <code class="docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="collections.html">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a></li>
<li class="toctree-l2"><a class="reference internal" href="heapq.html">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a></li>
<li class="toctree-l2"><a class="reference internal" href="bisect.html">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a></li>
<li class="toctree-l2"><a class="reference internal" href="array.html">8.6. <code class="docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></li>
<li class="toctree-l2"><a class="reference internal" href="sets.html">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a></li>
<li class="toctree-l2"><a class="reference internal" href="sched.html">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a></li>
<li class="toctree-l2"><a class="reference internal" href="mutex.html">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a></li>
<li class="toctree-l2"><a class="reference internal" href="queue.html">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a></li>
<li class="toctree-l2"><a class="reference internal" href="weakref.html">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></li>
<li class="toctree-l2"><a class="reference internal" href="userdict.html">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="userdict.html#module-UserList">8.13. <code class="docutils literal notranslate"><span class="pre">UserList</span></code> — Class wrapper for list objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="userdict.html#module-UserString">8.14. <code class="docutils literal notranslate"><span class="pre">UserString</span></code> — Class wrapper for string objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="types.html">8.15. <code class="docutils literal notranslate"><span class="pre">types</span></code> — Names for built-in types</a></li>
<li class="toctree-l2"><a class="reference internal" href="new.html">8.16. <code class="docutils literal notranslate"><span class="pre">new</span></code> — Creation of runtime internal objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="copy.html">8.17. <code class="docutils literal notranslate"><span class="pre">copy</span></code> — Shallow and deep copy operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="pprint.html">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a></li>
<li class="toctree-l2"><a class="reference internal" href="repr.html">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="numeric.html">9. Numeric and Mathematical Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="numbers.html">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a></li>
<li class="toctree-l2"><a class="reference internal" href="fractions.html">9.5. <code class="docutils literal notranslate"><span class="pre">fractions</span></code> — Rational numbers</a></li>
<li class="toctree-l2"><a class="reference internal" href="random.html">9.6. <code class="docutils literal notranslate"><span class="pre">random</span></code> — Generate pseudo-random numbers</a></li>
<li class="toctree-l2"><a class="reference internal" href="itertools.html">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a></li>
<li class="toctree-l2"><a class="reference internal" href="functools.html">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="operator.html">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="filesys.html">10. File and Directory Access</a><ul>
<li class="toctree-l2"><a class="reference internal" href="os.path.html">10.1. <code class="docutils literal notranslate"><span class="pre">os.path</span></code> — Common pathname manipulations</a></li>
<li class="toctree-l2"><a class="reference internal" href="fileinput.html">10.2. <code class="docutils literal notranslate"><span class="pre">fileinput</span></code> — Iterate over lines from multiple input streams</a></li>
<li class="toctree-l2"><a class="reference internal" href="stat.html">10.3. <code class="docutils literal notranslate"><span class="pre">stat</span></code> — Interpreting <code class="docutils literal notranslate"><span class="pre">stat()</span></code> results</a></li>
<li class="toctree-l2"><a class="reference internal" href="statvfs.html">10.4. <code class="docutils literal notranslate"><span class="pre">statvfs</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="filecmp.html">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a></li>
<li class="toctree-l2"><a class="reference internal" href="tempfile.html">10.6. <code class="docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></li>
<li class="toctree-l2"><a class="reference internal" href="glob.html">10.7. <code class="docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></li>
<li class="toctree-l2"><a class="reference internal" href="fnmatch.html">10.8. <code class="docutils literal notranslate"><span class="pre">fnmatch</span></code> — Unix filename pattern matching</a></li>
<li class="toctree-l2"><a class="reference internal" href="linecache.html">10.9. <code class="docutils literal notranslate"><span class="pre">linecache</span></code> — Random access to text lines</a></li>
<li class="toctree-l2"><a class="reference internal" href="shutil.html">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="dircache.html">10.11. <code class="docutils literal notranslate"><span class="pre">dircache</span></code> — Cached directory listings</a></li>
<li class="toctree-l2"><a class="reference internal" href="macpath.html">10.12. <code class="docutils literal notranslate"><span class="pre">macpath</span></code> — Mac OS 9 path manipulation functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="persistence.html">11. Data Persistence</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pickle.html">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#module-cPickle">11.2. <code class="docutils literal notranslate"><span class="pre">cPickle</span></code> — A faster <code class="docutils literal notranslate"><span class="pre">pickle</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="copy_reg.html">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="shelve.html">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a></li>
<li class="toctree-l2"><a class="reference internal" href="marshal.html">11.5. <code class="docutils literal notranslate"><span class="pre">marshal</span></code> — Internal Python object serialization</a></li>
<li class="toctree-l2"><a class="reference internal" href="anydbm.html">11.6. <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> — Generic access to DBM-style databases</a></li>
<li class="toctree-l2"><a class="reference internal" href="whichdb.html">11.7. <code class="docutils literal notranslate"><span class="pre">whichdb</span></code> — Guess which DBM module created a database</a></li>
<li class="toctree-l2"><a class="reference internal" href="dbm.html">11.8. <code class="docutils literal notranslate"><span class="pre">dbm</span></code> — Simple “database” interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="gdbm.html">11.9. <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> — GNU’s reinterpretation of dbm</a></li>
<li class="toctree-l2"><a class="reference internal" href="dbhash.html">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a></li>
<li class="toctree-l2"><a class="reference internal" href="bsddb.html">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a></li>
<li class="toctree-l2"><a class="reference internal" href="dumbdbm.html">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="archiving.html">12. Data Compression and Archiving</a><ul>
<li class="toctree-l2"><a class="reference internal" href="zlib.html">12.1. <code class="docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></li>
<li class="toctree-l2"><a class="reference internal" href="gzip.html">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a></li>
<li class="toctree-l2"><a class="reference internal" href="bz2.html">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a></li>
<li class="toctree-l2"><a class="reference internal" href="zipfile.html">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a></li>
<li class="toctree-l2"><a class="reference internal" href="tarfile.html">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="fileformats.html">13. File Formats</a><ul>
<li class="toctree-l2"><a class="reference internal" href="csv.html">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a></li>
<li class="toctree-l2"><a class="reference internal" href="configparser.html">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a></li>
<li class="toctree-l2"><a class="reference internal" href="robotparser.html">13.3. <code class="docutils literal notranslate"><span class="pre">robotparser</span></code> —  Parser for robots.txt</a></li>
<li class="toctree-l2"><a class="reference internal" href="netrc.html">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a></li>
<li class="toctree-l2"><a class="reference internal" href="xdrlib.html">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a></li>
<li class="toctree-l2"><a class="reference internal" href="plistlib.html">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="crypto.html">14. Cryptographic Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="hashlib.html">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a></li>
<li class="toctree-l2"><a class="reference internal" href="hmac.html">14.2. <code class="docutils literal notranslate"><span class="pre">hmac</span></code> — Keyed-Hashing for Message Authentication</a></li>
<li class="toctree-l2"><a class="reference internal" href="md5.html">14.3. <code class="docutils literal notranslate"><span class="pre">md5</span></code> — MD5 message digest algorithm</a></li>
<li class="toctree-l2"><a class="reference internal" href="sha.html">14.4. <code class="docutils literal notranslate"><span class="pre">sha</span></code> — SHA-1 message digest algorithm</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="allos.html">15. Generic Operating System Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="os.html">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="io.html">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a></li>
<li class="toctree-l2"><a class="reference internal" href="time.html">15.3. <code class="docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a></li>
<li class="toctree-l2"><a class="reference internal" href="argparse.html">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="optparse.html">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a></li>
<li class="toctree-l2"><a class="reference internal" href="getopt.html">15.6. <code class="docutils literal notranslate"><span class="pre">getopt</span></code> — C-style parser for command line options</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.html">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.config.html">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a></li>
<li class="toctree-l2"><a class="reference internal" href="logging.handlers.html">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a></li>
<li class="toctree-l2"><a class="reference internal" href="getpass.html">15.10. <code class="docutils literal notranslate"><span class="pre">getpass</span></code> — Portable password input</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.html">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.html#module-curses.textpad">15.12. <code class="docutils literal notranslate"><span class="pre">curses.textpad</span></code> — Text input widget for curses programs</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.ascii.html">15.13. <code class="docutils literal notranslate"><span class="pre">curses.ascii</span></code> — Utilities for ASCII characters</a></li>
<li class="toctree-l2"><a class="reference internal" href="curses.panel.html">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a></li>
<li class="toctree-l2"><a class="reference internal" href="platform.html">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a></li>
<li class="toctree-l2"><a class="reference internal" href="errno.html">15.16. <code class="docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></li>
<li class="toctree-l2"><a class="reference internal" href="ctypes.html">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="someos.html">16. Optional Operating System Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="select.html">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="thread.html">16.3. <code class="docutils literal notranslate"><span class="pre">thread</span></code> — Multiple threads of control</a></li>
<li class="toctree-l2"><a class="reference internal" href="dummy_threading.html">16.4. <code class="docutils literal notranslate"><span class="pre">dummy_threading</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">threading</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="dummy_thread.html">16.5. <code class="docutils literal notranslate"><span class="pre">dummy_thread</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">thread</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="multiprocessing.html">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="mmap.html">16.7. <code class="docutils literal notranslate"><span class="pre">mmap</span></code> — Memory-mapped file support</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="rlcompleter.html">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="ipc.html">17. Interprocess Communication and Networking</a><ul>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a></li>
<li class="toctree-l2"><a class="reference internal" href="socket.html">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="signal.html">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a></li>
<li class="toctree-l2"><a class="reference internal" href="popen2.html">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a></li>
<li class="toctree-l2"><a class="reference internal" href="asyncore.html">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></li>
<li class="toctree-l2"><a class="reference internal" href="asynchat.html">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="netdata.html">18. Internet Data Handling</a><ul>
<li class="toctree-l2"><a class="reference internal" href="email.html">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a></li>
<li class="toctree-l2"><a class="reference internal" href="json.html">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a></li>
<li class="toctree-l2"><a class="reference internal" href="mailcap.html">18.3. <code class="docutils literal notranslate"><span class="pre">mailcap</span></code> — Mailcap file handling</a></li>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a></li>
<li class="toctree-l2"><a class="reference internal" href="mhlib.html">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a></li>
<li class="toctree-l2"><a class="reference internal" href="mimetools.html">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a></li>
<li class="toctree-l2"><a class="reference internal" href="mimetypes.html">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a></li>
<li class="toctree-l2"><a class="reference internal" href="mimewriter.html">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a></li>
<li class="toctree-l2"><a class="reference internal" href="mimify.html">18.9. <code class="docutils literal notranslate"><span class="pre">mimify</span></code> — MIME processing of mail messages</a></li>
<li class="toctree-l2"><a class="reference internal" href="multifile.html">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a></li>
<li class="toctree-l2"><a class="reference internal" href="rfc822.html">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a></li>
<li class="toctree-l2"><a class="reference internal" href="base64.html">18.12. <code class="docutils literal notranslate"><span class="pre">base64</span></code> — RFC 3548: Base16, Base32, Base64 Data Encodings</a></li>
<li class="toctree-l2"><a class="reference internal" href="binhex.html">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a></li>
<li class="toctree-l2"><a class="reference internal" href="binascii.html">18.14. <code class="docutils literal notranslate"><span class="pre">binascii</span></code> — Convert between binary and ASCII</a></li>
<li class="toctree-l2"><a class="reference internal" href="quopri.html">18.15. <code class="docutils literal notranslate"><span class="pre">quopri</span></code> — Encode and decode MIME quoted-printable data</a></li>
<li class="toctree-l2"><a class="reference internal" href="uu.html">18.16. <code class="docutils literal notranslate"><span class="pre">uu</span></code> — Encode and decode uuencode files</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="markup.html">19. Structured Markup Processing Tools</a><ul>
<li class="toctree-l2"><a class="reference internal" href="htmlparser.html">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a></li>
<li class="toctree-l2"><a class="reference internal" href="sgmllib.html">19.2. <code class="docutils literal notranslate"><span class="pre">sgmllib</span></code> — Simple SGML parser</a></li>
<li class="toctree-l2"><a class="reference internal" href="htmllib.html">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a></li>
<li class="toctree-l2"><a class="reference internal" href="htmllib.html#module-htmlentitydefs">19.4. <code class="docutils literal notranslate"><span class="pre">htmlentitydefs</span></code> — Definitions of HTML general entities</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.html">19.5. XML Processing Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.html#xml-vulnerabilities">19.6. XML vulnerabilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.etree.elementtree.html">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.html">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.minidom.html">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.pulldom.html">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.html">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.handler.html">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.utils.html">19.13. <code class="docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code> — SAX Utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="internet.html">20. Internet Protocols and Support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="webbrowser.html">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgitb.html">20.3. <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> — Traceback manager for CGI scripts</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib.html">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a></li>
<li class="toctree-l2"><a class="reference internal" href="httplib.html">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="ftplib.html">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="poplib.html">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="imaplib.html">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="nntplib.html">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtplib.html">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtpd.html">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a></li>
<li class="toctree-l2"><a class="reference internal" href="telnetlib.html">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a></li>
<li class="toctree-l2"><a class="reference internal" href="uuid.html">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a></li>
<li class="toctree-l2"><a class="reference internal" href="urlparse.html">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a></li>
<li class="toctree-l2"><a class="reference internal" href="socketserver.html">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a></li>
<li class="toctree-l2"><a class="reference internal" href="basehttpserver.html">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a></li>
<li class="toctree-l2"><a class="reference internal" href="simplehttpserver.html">20.19. <code class="docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code> — Simple HTTP request handler</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgihttpserver.html">20.20. <code class="docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code> — CGI-capable HTTP request handler</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookie.html">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a></li>
<li class="toctree-l2"><a class="reference internal" href="simplexmlrpcserver.html">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a></li>
<li class="toctree-l2"><a class="reference internal" href="docxmlrpcserver.html">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mm.html">21. Multimedia Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="audioop.html">21.1. <code class="docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></li>
<li class="toctree-l2"><a class="reference internal" href="imageop.html">21.2. <code class="docutils literal notranslate"><span class="pre">imageop</span></code> — Manipulate raw image data</a></li>
<li class="toctree-l2"><a class="reference internal" href="aifc.html">21.3. <code class="docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></li>
<li class="toctree-l2"><a class="reference internal" href="sunau.html">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a></li>
<li class="toctree-l2"><a class="reference internal" href="wave.html">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a></li>
<li class="toctree-l2"><a class="reference internal" href="chunk.html">21.6. <code class="docutils literal notranslate"><span class="pre">chunk</span></code> — Read IFF chunked data</a></li>
<li class="toctree-l2"><a class="reference internal" href="colorsys.html">21.7. <code class="docutils literal notranslate"><span class="pre">colorsys</span></code> — Conversions between color systems</a></li>
<li class="toctree-l2"><a class="reference internal" href="imghdr.html">21.8. <code class="docutils literal notranslate"><span class="pre">imghdr</span></code> — Determine the type of an image</a></li>
<li class="toctree-l2"><a class="reference internal" href="sndhdr.html">21.9. <code class="docutils literal notranslate"><span class="pre">sndhdr</span></code> — Determine type of sound file</a></li>
<li class="toctree-l2"><a class="reference internal" href="ossaudiodev.html">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="i18n.html">22. Internationalization</a><ul>
<li class="toctree-l2"><a class="reference internal" href="gettext.html">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a></li>
<li class="toctree-l2"><a class="reference internal" href="locale.html">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="frameworks.html">23. Program Frameworks</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cmd.html">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a></li>
<li class="toctree-l2"><a class="reference internal" href="shlex.html">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tk.html">24. Graphical User Interfaces with Tk</a><ul>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a></li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a></li>
<li class="toctree-l2"><a class="reference internal" href="tix.html">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a></li>
<li class="toctree-l2"><a class="reference internal" href="scrolledtext.html">24.4. <code class="docutils literal notranslate"><span class="pre">ScrolledText</span></code> — Scrolled Text Widget</a></li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a></li>
<li class="toctree-l2"><a class="reference internal" href="idle.html">24.6. IDLE</a></li>
<li class="toctree-l2"><a class="reference internal" href="othergui.html">24.7. Other Graphical User Interface Packages</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="development.html">25. Development Tools</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pydoc.html">25.1. <code class="docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></li>
<li class="toctree-l2"><a class="reference internal" href="doctest.html">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="unittest.html">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="2to3.html">25.4. 2to3 - Automated Python 2 to 3 code translation</a></li>
<li class="toctree-l2"><a class="reference internal" href="test.html">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="test.html#module-test.support">25.6. <code class="docutils literal notranslate"><span class="pre">test.support</span></code> — Utility functions for tests</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="debug.html">26. Debugging and Profiling</a><ul>
<li class="toctree-l2"><a class="reference internal" href="bdb.html">26.1. <code class="docutils literal notranslate"><span class="pre">bdb</span></code> — Debugger framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="pdb.html">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></li>
<li class="toctree-l2"><a class="reference internal" href="pdb.html#debugger-commands">26.3. Debugger Commands</a></li>
<li class="toctree-l2"><a class="reference internal" href="profile.html">26.4. The Python Profilers</a></li>
<li class="toctree-l2"><a class="reference internal" href="hotshot.html">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a></li>
<li class="toctree-l2"><a class="reference internal" href="timeit.html">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a></li>
<li class="toctree-l2"><a class="reference internal" href="trace.html">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="distribution.html">27. Software Packaging and Distribution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="distutils.html">27.1. <code class="docutils literal notranslate"><span class="pre">distutils</span></code> — Building and installing Python modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="ensurepip.html">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="python.html">28. Python Runtime Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sys.html">28.1. <code class="docutils literal notranslate"><span class="pre">sys</span></code> — System-specific parameters and functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="sysconfig.html">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a></li>
<li class="toctree-l2"><a class="reference internal" href="__builtin__.html">28.3. <code class="docutils literal notranslate"><span class="pre">__builtin__</span></code> — Built-in objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="future_builtins.html">28.4. <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> — Python 3 builtins</a></li>
<li class="toctree-l2"><a class="reference internal" href="__main__.html">28.5. <code class="docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level script environment</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a></li>
<li class="toctree-l2"><a class="reference internal" href="contextlib.html">28.7. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></li>
<li class="toctree-l2"><a class="reference internal" href="abc.html">28.8. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="atexit.html">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></li>
<li class="toctree-l2"><a class="reference internal" href="traceback.html">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a></li>
<li class="toctree-l2"><a class="reference internal" href="__future__.html">28.11. <code class="docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></li>
<li class="toctree-l2"><a class="reference internal" href="gc.html">28.12. <code class="docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="inspect.html">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="site.html">28.14. <code class="docutils literal notranslate"><span class="pre">site</span></code> — Site-specific configuration hook</a></li>
<li class="toctree-l2"><a class="reference internal" href="user.html">28.15. <code class="docutils literal notranslate"><span class="pre">user</span></code> — User-specific configuration hook</a></li>
<li class="toctree-l2"><a class="reference internal" href="fpectl.html">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="custominterp.html">29. Custom Python Interpreters</a><ul>
<li class="toctree-l2"><a class="reference internal" href="code.html">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="codeop.html">29.2. <code class="docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="restricted.html">30. Restricted Execution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="rexec.html">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="bastion.html">30.2. <code class="docutils literal notranslate"><span class="pre">Bastion</span></code> — Restricting access to objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="modules.html">31. Importing Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="imp.html">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a></li>
<li class="toctree-l2"><a class="reference internal" href="importlib.html">31.2. <code class="docutils literal notranslate"><span class="pre">importlib</span></code> — Convenience wrappers for <code class="docutils literal notranslate"><span class="pre">__import__()</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="imputil.html">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="zipimport.html">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a></li>
<li class="toctree-l2"><a class="reference internal" href="pkgutil.html">31.5. <code class="docutils literal notranslate"><span class="pre">pkgutil</span></code> — Package extension utility</a></li>
<li class="toctree-l2"><a class="reference internal" href="modulefinder.html">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></li>
<li class="toctree-l2"><a class="reference internal" href="runpy.html">31.7. <code class="docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="language.html">32. Python Language Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="parser.html">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a></li>
<li class="toctree-l2"><a class="reference internal" href="ast.html">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a></li>
<li class="toctree-l2"><a class="reference internal" href="symtable.html">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a></li>
<li class="toctree-l2"><a class="reference internal" href="symbol.html">32.4. <code class="docutils literal notranslate"><span class="pre">symbol</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l2"><a class="reference internal" href="token.html">32.5. <code class="docutils literal notranslate"><span class="pre">token</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l2"><a class="reference internal" href="keyword.html">32.6. <code class="docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></li>
<li class="toctree-l2"><a class="reference internal" href="tokenize.html">32.7. <code class="docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></li>
<li class="toctree-l2"><a class="reference internal" href="tabnanny.html">32.8. <code class="docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyclbr.html">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a></li>
<li class="toctree-l2"><a class="reference internal" href="py_compile.html">32.10. <code class="docutils literal notranslate"><span class="pre">py_compile</span></code> — Compile Python source files</a></li>
<li class="toctree-l2"><a class="reference internal" href="compileall.html">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a></li>
<li class="toctree-l2"><a class="reference internal" href="dis.html">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickletools.html">32.13. <code class="docutils literal notranslate"><span class="pre">pickletools</span></code> — Tools for pickle developers</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="compiler.html">33. Python compiler package</a><ul>
<li class="toctree-l2"><a class="reference internal" href="compiler.html#module-compiler">33.1. The basic interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="compiler.html#limitations">33.2. Limitations</a></li>
<li class="toctree-l2"><a class="reference internal" href="compiler.html#python-abstract-syntax">33.3. Python Abstract Syntax</a></li>
<li class="toctree-l2"><a class="reference internal" href="compiler.html#module-compiler.visitor">33.4. Using Visitors to Walk ASTs</a></li>
<li class="toctree-l2"><a class="reference internal" href="compiler.html#bytecode-generation">33.5. Bytecode Generation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="misc.html">34. Miscellaneous Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="formatter.html">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="windows.html">35. MS Windows Specific Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="msilib.html">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a></li>
<li class="toctree-l2"><a class="reference internal" href="msvcrt.html">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a></li>
<li class="toctree-l2"><a class="reference internal" href="_winreg.html">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a></li>
<li class="toctree-l2"><a class="reference internal" href="winsound.html">35.4. <code class="docutils literal notranslate"><span class="pre">winsound</span></code> — Sound-playing interface for Windows</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="unix.html">36. Unix Specific Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="posix.html">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a></li>
<li class="toctree-l2"><a class="reference internal" href="pwd.html">36.2. <code class="docutils literal notranslate"><span class="pre">pwd</span></code> — The password database</a></li>
<li class="toctree-l2"><a class="reference internal" href="spwd.html">36.3. <code class="docutils literal notranslate"><span class="pre">spwd</span></code> — The shadow password database</a></li>
<li class="toctree-l2"><a class="reference internal" href="grp.html">36.4. <code class="docutils literal notranslate"><span class="pre">grp</span></code> — The group database</a></li>
<li class="toctree-l2"><a class="reference internal" href="crypt.html">36.5. <code class="docutils literal notranslate"><span class="pre">crypt</span></code> — Function to check Unix passwords</a></li>
<li class="toctree-l2"><a class="reference internal" href="dl.html">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="termios.html">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a></li>
<li class="toctree-l2"><a class="reference internal" href="tty.html">36.8. <code class="docutils literal notranslate"><span class="pre">tty</span></code> — Terminal control functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="pty.html">36.9. <code class="docutils literal notranslate"><span class="pre">pty</span></code> — Pseudo-terminal utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="fcntl.html">36.10. <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls</a></li>
<li class="toctree-l2"><a class="reference internal" href="pipes.html">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a></li>
<li class="toctree-l2"><a class="reference internal" href="posixfile.html">36.12. <code class="docutils literal notranslate"><span class="pre">posixfile</span></code> — File-like objects with locking support</a></li>
<li class="toctree-l2"><a class="reference internal" href="resource.html">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a></li>
<li class="toctree-l2"><a class="reference internal" href="nis.html">36.14. <code class="docutils literal notranslate"><span class="pre">nis</span></code> — Interface to Sun’s NIS (Yellow Pages)</a></li>
<li class="toctree-l2"><a class="reference internal" href="syslog.html">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a></li>
<li class="toctree-l2"><a class="reference internal" href="commands.html">36.16. <code class="docutils literal notranslate"><span class="pre">commands</span></code> — Utilities for running commands</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mac.html">37. Mac OS X specific services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ic.html">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a></li>
<li class="toctree-l2"><a class="reference internal" href="macos.html">37.2. <code class="docutils literal notranslate"><span class="pre">MacOS</span></code> — Access to Mac OS interpreter features</a></li>
<li class="toctree-l2"><a class="reference internal" href="macostools.html">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></li>
<li class="toctree-l2"><a class="reference internal" href="macostools.html#module-findertools">37.4. <code class="docutils literal notranslate"><span class="pre">findertools</span></code> — The <strong class="program">finder</strong>’s Apple Events interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="easydialogs.html">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a></li>
<li class="toctree-l2"><a class="reference internal" href="framework.html">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="autogil.html">37.7. <code class="docutils literal notranslate"><span class="pre">autoGIL</span></code> — Global Interpreter Lock handling in event loops</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html">37.8. Mac OS Toolbox Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="colorpicker.html">37.9. <code class="docutils literal notranslate"><span class="pre">ColorPicker</span></code> — Color selection dialog</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="macosa.html">38. MacPython OSA Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="gensuitemodule.html">38.1. <code class="docutils literal notranslate"><span class="pre">gensuitemodule</span></code> — Generate OSA stub packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="aetools.html">38.2. <code class="docutils literal notranslate"><span class="pre">aetools</span></code> — OSA client support</a></li>
<li class="toctree-l2"><a class="reference internal" href="aepack.html">38.3. <code class="docutils literal notranslate"><span class="pre">aepack</span></code> — Conversion between Python variables and AppleEvent data containers</a></li>
<li class="toctree-l2"><a class="reference internal" href="aetypes.html">38.4. <code class="docutils literal notranslate"><span class="pre">aetypes</span></code> — AppleEvent objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="miniaeframe.html">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sgi.html">39. SGI IRIX Specific Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="al.html">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a></li>
<li class="toctree-l2"><a class="reference internal" href="al.html#module-AL">39.2. <code class="docutils literal notranslate"><span class="pre">AL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">al</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="cd.html">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a></li>
<li class="toctree-l2"><a class="reference internal" href="fl.html">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="fl.html#module-FL">39.5. <code class="docutils literal notranslate"><span class="pre">FL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">fl</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="fl.html#module-flp">39.6. <code class="docutils literal notranslate"><span class="pre">flp</span></code> — Functions for loading stored FORMS designs</a></li>
<li class="toctree-l2"><a class="reference internal" href="fm.html">39.7. <code class="docutils literal notranslate"><span class="pre">fm</span></code> — <em>Font Manager</em> interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="gl.html">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="gl.html#module-DEVICE">39.9. <code class="docutils literal notranslate"><span class="pre">DEVICE</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="gl.html#module-GL">39.10. <code class="docutils literal notranslate"><span class="pre">GL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l2"><a class="reference internal" href="imgfile.html">39.11. <code class="docutils literal notranslate"><span class="pre">imgfile</span></code> — Support for SGI imglib files</a></li>
<li class="toctree-l2"><a class="reference internal" href="jpeg.html">39.12. <code class="docutils literal notranslate"><span class="pre">jpeg</span></code> — Read and write JPEG files</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sun.html">40. SunOS Specific Services</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sunaudio.html">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a></li>
<li class="toctree-l2"><a class="reference internal" href="sunaudio.html#module-SUNAUDIODEV">40.2. <code class="docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="undoc.html">41. Undocumented Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#miscellaneous-useful-utilities">41.1. Miscellaneous useful utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#platform-specific-modules">41.2. Platform specific modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#multimedia">41.3. Multimedia</a></li>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#undocumented-mac-os-modules">41.4. Undocumented Mac OS modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#obsolete">41.5. Obsolete</a></li>
<li class="toctree-l2"><a class="reference internal" href="undoc.html#sgi-specific-extension-modules">41.6. SGI-specific Extension modules</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../reference/grammar.html"
                        title="previous chapter">9. Full Grammar specification</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="intro.html"
                        title="next chapter">1. Introduction</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="intro.html" title="1. Introduction"
             >next</a> |</li>
        <li class="right" >
          <a href="../reference/grammar.html" title="9. Full Grammar specification"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�1)����html/library/inspect.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.13. inspect — Inspect live objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.14. site — Site-specific configuration hook" href="site.html" />
    <link rel="prev" title="28.12. gc — Garbage Collector interface" href="gc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/inspect.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="site.html" title="28.14. site — Site-specific configuration hook"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gc.html" title="28.12. gc — Garbage Collector interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-inspect">
<span id="inspect-inspect-live-objects"></span><h1>28.13. <a class="reference internal" href="#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> — Inspect live objects<a class="headerlink" href="#module-inspect" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/inspect.py">Lib/inspect.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module provides several useful functions to help get
information about live objects such as modules, classes, methods, functions,
tracebacks, frame objects, and code objects.  For example, it can help you
examine the contents of a class, retrieve the source code of a method, extract
and format the argument list for a function, or get all the information you need
to display a detailed traceback.</p>
<p>There are four main kinds of services provided by this module: type checking,
getting source code, inspecting classes and functions, and examining the
interpreter stack.</p>
<div class="section" id="types-and-members">
<span id="inspect-types"></span><h2>28.13.1. Types and members<a class="headerlink" href="#types-and-members" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#inspect.getmembers" title="inspect.getmembers"><code class="xref py py-func docutils literal notranslate"><span class="pre">getmembers()</span></code></a> function retrieves the members of an object such as a
class or module. The sixteen functions whose names begin with “is” are mainly
provided as convenient choices for the second argument to <a class="reference internal" href="#inspect.getmembers" title="inspect.getmembers"><code class="xref py py-func docutils literal notranslate"><span class="pre">getmembers()</span></code></a>.
They also help you determine when you can expect to find the following special
attributes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="27%" />
<col width="44%" />
<col width="11%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type</th>
<th class="head">Attribute</th>
<th class="head">Description</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>module</td>
<td>__doc__</td>
<td>documentation string</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>__file__</td>
<td>filename (missing for
built-in modules)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>class</td>
<td>__doc__</td>
<td>documentation string</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>__module__</td>
<td>name of module in which
this class was defined</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>method</td>
<td>__doc__</td>
<td>documentation string</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>__name__</td>
<td>name with which this
method was defined</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>im_class</td>
<td>class object that asked
for this method</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>im_func or
__func__</td>
<td>function object
containing implementation
of method</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>im_self or
__self__</td>
<td>instance to which this
method is bound, or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>function</td>
<td>__doc__</td>
<td>documentation string</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>__name__</td>
<td>name with which this
function was defined</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>func_code</td>
<td>code object containing
compiled function
<a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>func_defaults</td>
<td>tuple of any default
values for arguments</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>func_doc</td>
<td>(same as __doc__)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>func_globals</td>
<td>global namespace in which
this function was defined</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>func_name</td>
<td>(same as __name__)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>generator</td>
<td>__iter__</td>
<td>defined to support
iteration over container</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>close</td>
<td>raises new GeneratorExit
exception inside the
generator to terminate
the iteration</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>gi_code</td>
<td>code object</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>gi_frame</td>
<td>frame object or possibly
<code class="docutils literal notranslate"><span class="pre">None</span></code> once the
generator has been
exhausted</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>gi_running</td>
<td>set to 1 when generator
is executing, 0 otherwise</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>next</td>
<td>return the next item from
the container</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>send</td>
<td>resumes the generator and
“sends” a value that
becomes the result of the
current yield-expression</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>throw</td>
<td>used to raise an
exception inside the
generator</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>traceback</td>
<td>tb_frame</td>
<td>frame object at this
level</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>tb_lasti</td>
<td>index of last attempted
instruction in bytecode</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>tb_lineno</td>
<td>current line number in
Python source code</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>tb_next</td>
<td>next inner traceback
object (called by this
level)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>frame</td>
<td>f_back</td>
<td>next outer frame object
(this frame’s caller)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_builtins</td>
<td>builtins namespace seen
by this frame</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>f_code</td>
<td>code object being
executed in this frame</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_exc_traceback</td>
<td>traceback if raised in
this frame, or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>f_exc_type</td>
<td>exception type if raised
in this frame, or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_exc_value</td>
<td>exception value if raised
in this frame, or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>f_globals</td>
<td>global namespace seen by
this frame</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_lasti</td>
<td>index of last attempted
instruction in bytecode</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>f_lineno</td>
<td>current line number in
Python source code</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_locals</td>
<td>local namespace seen by
this frame</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>f_restricted</td>
<td>0 or 1 if frame is in
restricted execution mode</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>f_trace</td>
<td>tracing function for this
frame, or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>code</td>
<td>co_argcount</td>
<td>number of arguments (not
including * or **
args)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_code</td>
<td>string of raw compiled
bytecode</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>co_consts</td>
<td>tuple of constants used
in the bytecode</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_filename</td>
<td>name of file in which
this code object was
created</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>co_firstlineno</td>
<td>number of first line in
Python source code</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_flags</td>
<td>bitmap: 1=optimized <code class="docutils literal notranslate"><span class="pre">|</span></code>
2=newlocals <code class="docutils literal notranslate"><span class="pre">|</span></code> 4=*arg
<code class="docutils literal notranslate"><span class="pre">|</span></code> 8=**arg</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>co_lnotab</td>
<td>encoded mapping of line
numbers to bytecode
indices</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_name</td>
<td>name with which this code
object was defined</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>co_names</td>
<td>tuple of names of local
variables</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_nlocals</td>
<td>number of local variables</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>co_stacksize</td>
<td>virtual machine stack
space required</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>co_varnames</td>
<td>tuple of names of
arguments and local
variables</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>builtin</td>
<td>__doc__</td>
<td>documentation string</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td>__name__</td>
<td>original name of this
function or method</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td>__self__</td>
<td>instance to which a
method is bound, or
<code class="docutils literal notranslate"><span class="pre">None</span></code></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Note:</p>
<ol class="arabic">
<li><div class="first versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span><code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code> used to refer to the class that defined the method.</p>
</div>
</li>
</ol>
<dl class="function">
<dt id="inspect.getmembers">
<code class="descclassname">inspect.</code><code class="descname">getmembers</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>predicate</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getmembers" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all the members of an object in a list of (name, value) pairs sorted by
name.  If the optional <em>predicate</em> argument is supplied, only members for which
the predicate returns a true value are included.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#inspect.getmembers" title="inspect.getmembers"><code class="xref py py-func docutils literal notranslate"><span class="pre">getmembers()</span></code></a> does not return metaclass attributes when the argument
is a class (this behavior is inherited from the <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> function).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.getmoduleinfo">
<code class="descclassname">inspect.</code><code class="descname">getmoduleinfo</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getmoduleinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple of values that describe how Python will interpret the file
identified by <em>path</em> if it is a module, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if it would not be
identified as a module.  The return tuple is <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">suffix,</span> <span class="pre">mode,</span>
<span class="pre">module_type)</span></code>, where <em>name</em> is the name of the module without the name of
any enclosing package, <em>suffix</em> is the trailing part of the file name (which
may not be a dot-delimited extension), <em>mode</em> is the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> mode that
would be used (<code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'rb'</span></code>), and <em>module_type</em> is an integer giving
the type of the module.  <em>module_type</em> will have a value which can be
compared to the constants defined in the <a class="reference internal" href="imp.html#module-imp" title="imp: Access the implementation of the import statement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imp</span></code></a> module; see the
documentation for that module for more information on module types.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Returns a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">ModuleInfo(name,</span> <span class="pre">suffix,</span> <span class="pre">mode,</span>
<span class="pre">module_type)</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.getmodulename">
<code class="descclassname">inspect.</code><code class="descname">getmodulename</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getmodulename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the module named by the file <em>path</em>, without including the
names of enclosing packages.  This uses the same algorithm as the interpreter
uses when searching for modules.  If the name cannot be matched according to the
interpreter’s rules, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.ismodule">
<code class="descclassname">inspect.</code><code class="descname">ismodule</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.ismodule" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a module.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isclass">
<code class="descclassname">inspect.</code><code class="descname">isclass</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isclass" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a class, whether built-in or created in Python
code.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.ismethod">
<code class="descclassname">inspect.</code><code class="descname">ismethod</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.ismethod" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a bound or unbound method written in Python.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isfunction">
<code class="descclassname">inspect.</code><code class="descname">isfunction</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isfunction" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a Python function, which includes functions
created by a <a class="reference internal" href="../glossary.html#term-lambda"><span class="xref std std-term">lambda</span></a> expression.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isgeneratorfunction">
<code class="descclassname">inspect.</code><code class="descname">isgeneratorfunction</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isgeneratorfunction" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a Python generator function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.isgenerator">
<code class="descclassname">inspect.</code><code class="descname">isgenerator</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isgenerator" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a generator.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.istraceback">
<code class="descclassname">inspect.</code><code class="descname">istraceback</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.istraceback" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a traceback.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isframe">
<code class="descclassname">inspect.</code><code class="descname">isframe</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isframe" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a frame.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.iscode">
<code class="descclassname">inspect.</code><code class="descname">iscode</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.iscode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a code.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isbuiltin">
<code class="descclassname">inspect.</code><code class="descname">isbuiltin</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isbuiltin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a built-in function or a bound built-in method.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isroutine">
<code class="descclassname">inspect.</code><code class="descname">isroutine</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isroutine" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a user-defined or built-in function or method.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isabstract">
<code class="descclassname">inspect.</code><code class="descname">isabstract</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isabstract" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is an abstract base class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.ismethoddescriptor">
<code class="descclassname">inspect.</code><code class="descname">ismethoddescriptor</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.ismethoddescriptor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a method descriptor, but not if
<a class="reference internal" href="#inspect.ismethod" title="inspect.ismethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">ismethod()</span></code></a>, <a class="reference internal" href="#inspect.isclass" title="inspect.isclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">isclass()</span></code></a>, <a class="reference internal" href="#inspect.isfunction" title="inspect.isfunction"><code class="xref py py-func docutils literal notranslate"><span class="pre">isfunction()</span></code></a> or <a class="reference internal" href="#inspect.isbuiltin" title="inspect.isbuiltin"><code class="xref py py-func docutils literal notranslate"><span class="pre">isbuiltin()</span></code></a>
are true.</p>
<p>This is new as of Python 2.2, and, for example, is true of
<code class="docutils literal notranslate"><span class="pre">int.__add__</span></code>. An object passing this test
has a <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> method but not a <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>
method, but beyond that the set of attributes varies.  A
<a class="reference internal" href="stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attribute is usually
sensible, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> often is.</p>
<p>Methods implemented via descriptors that also pass one of the other tests
return false from the <a class="reference internal" href="#inspect.ismethoddescriptor" title="inspect.ismethoddescriptor"><code class="xref py py-func docutils literal notranslate"><span class="pre">ismethoddescriptor()</span></code></a> test, simply because the
other tests promise more – you can, e.g., count on having the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> attribute (etc) when an object passes <a class="reference internal" href="#inspect.ismethod" title="inspect.ismethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">ismethod()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.isdatadescriptor">
<code class="descclassname">inspect.</code><code class="descname">isdatadescriptor</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isdatadescriptor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a data descriptor.</p>
<p>Data descriptors have both a <a class="reference internal" href="../reference/datamodel.html#object.__get__" title="object.__get__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__get__</span></code></a> and a <a class="reference internal" href="../reference/datamodel.html#object.__set__" title="object.__set__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__set__</span></code></a> method.
Examples are properties (defined in Python), getsets, and members.  The
latter two are defined in C and there are more specific tests available for
those types, which is robust across Python implementations.  Typically, data
descriptors will also have <a class="reference internal" href="stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attributes
(properties, getsets, and members have both of these attributes), but this is
not guaranteed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.isgetsetdescriptor">
<code class="descclassname">inspect.</code><code class="descname">isgetsetdescriptor</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.isgetsetdescriptor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a getset descriptor.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> getsets are attributes defined in extension modules via
<a class="reference internal" href="../c-api/structures.html#c.PyGetSetDef" title="PyGetSetDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyGetSetDef</span></code></a> structures.  For Python implementations without such
types, this method will always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.ismemberdescriptor">
<code class="descclassname">inspect.</code><code class="descname">ismemberdescriptor</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.ismemberdescriptor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the object is a member descriptor.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Member descriptors are attributes defined in extension modules via
<a class="reference internal" href="../c-api/structures.html#c.PyMemberDef" title="PyMemberDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMemberDef</span></code></a> structures.  For Python implementations without such
types, this method will always return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="retrieving-source-code">
<span id="inspect-source"></span><h2>28.13.2. Retrieving source code<a class="headerlink" href="#retrieving-source-code" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="inspect.getdoc">
<code class="descclassname">inspect.</code><code class="descname">getdoc</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getdoc" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the documentation string for an object, cleaned up with <a class="reference internal" href="#inspect.cleandoc" title="inspect.cleandoc"><code class="xref py py-func docutils literal notranslate"><span class="pre">cleandoc()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getcomments">
<code class="descclassname">inspect.</code><code class="descname">getcomments</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getcomments" title="Permalink to this definition">¶</a></dt>
<dd><p>Return in a single string any lines of comments immediately preceding the
object’s source code (for a class, function, or method), or at the top of the
Python source file (if the object is a module).</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getfile">
<code class="descclassname">inspect.</code><code class="descname">getfile</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the (text or binary) file in which an object was defined.
This will fail with a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the object is a built-in module,
class, or function.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getmodule">
<code class="descclassname">inspect.</code><code class="descname">getmodule</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getmodule" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to guess which module an object was defined in.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getsourcefile">
<code class="descclassname">inspect.</code><code class="descname">getsourcefile</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getsourcefile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the Python source file in which an object was defined.  This
will fail with a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if the object is a built-in module, class, or
function.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getsourcelines">
<code class="descclassname">inspect.</code><code class="descname">getsourcelines</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getsourcelines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of source lines and starting line number for an object. The
argument may be a module, class, method, function, traceback, frame, or code
object.  The source code is returned as a list of the lines corresponding to the
object and the line number indicates where in the original source file the first
line of code was found.  An <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised if the source code cannot
be retrieved.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getsource">
<code class="descclassname">inspect.</code><code class="descname">getsource</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getsource" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the text of the source code for an object. The argument may be a module,
class, method, function, traceback, frame, or code object.  The source code is
returned as a single string.  An <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised if the source code
cannot be retrieved.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.cleandoc">
<code class="descclassname">inspect.</code><code class="descname">cleandoc</code><span class="sig-paren">(</span><em>doc</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.cleandoc" title="Permalink to this definition">¶</a></dt>
<dd><p>Clean up indentation from docstrings that are indented to line up with blocks
of code.</p>
<p>All leading whitespace is removed from the first line.  Any leading whitespace
that can be uniformly removed from the second line onwards is removed.  Empty
lines at the beginning and end are subsequently removed.  Also, all tabs are
expanded to spaces.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="classes-and-functions">
<span id="inspect-classes-functions"></span><h2>28.13.3. Classes and functions<a class="headerlink" href="#classes-and-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="inspect.getclasstree">
<code class="descclassname">inspect.</code><code class="descname">getclasstree</code><span class="sig-paren">(</span><em>classes</em><span class="optional">[</span>, <em>unique</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getclasstree" title="Permalink to this definition">¶</a></dt>
<dd><p>Arrange the given list of classes into a hierarchy of nested lists. Where a
nested list appears, it contains classes derived from the class whose entry
immediately precedes the list.  Each entry is a 2-tuple containing a class and a
tuple of its base classes.  If the <em>unique</em> argument is true, exactly one entry
appears in the returned structure for each class in the given list.  Otherwise,
classes using multiple inheritance and their descendants will appear multiple
times.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getargspec">
<code class="descclassname">inspect.</code><code class="descname">getargspec</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getargspec" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the names and default values of a Python function’s arguments. A tuple of
four things is returned: <code class="docutils literal notranslate"><span class="pre">(args,</span> <span class="pre">varargs,</span> <span class="pre">keywords,</span> <span class="pre">defaults)</span></code>. <em>args</em> is a
list of the argument names (it may contain nested lists). <em>varargs</em> and
<em>keywords</em> are the names of the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> arguments or
<code class="docutils literal notranslate"><span class="pre">None</span></code>. <em>defaults</em> is a tuple of default argument values or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there
are no default arguments; if this tuple has <em>n</em> elements, they correspond to
the last <em>n</em> elements listed in <em>args</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Returns a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">ArgSpec(args,</span> <span class="pre">varargs,</span> <span class="pre">keywords,</span>
<span class="pre">defaults)</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.getargvalues">
<code class="descclassname">inspect.</code><code class="descname">getargvalues</code><span class="sig-paren">(</span><em>frame</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getargvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>Get information about arguments passed into a particular frame. A tuple of
four things is returned: <code class="docutils literal notranslate"><span class="pre">(args,</span> <span class="pre">varargs,</span> <span class="pre">keywords,</span> <span class="pre">locals)</span></code>. <em>args</em> is a
list of the argument names (it may contain nested lists). <em>varargs</em> and
<em>keywords</em> are the names of the <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">**</span></code> arguments or <code class="docutils literal notranslate"><span class="pre">None</span></code>.
<em>locals</em> is the locals dictionary of the given frame.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Returns a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">ArgInfo(args,</span> <span class="pre">varargs,</span> <span class="pre">keywords,</span>
<span class="pre">locals)</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.formatargspec">
<code class="descclassname">inspect.</code><code class="descname">formatargspec</code><span class="sig-paren">(</span><em>args</em><span class="optional">[</span>, <em>varargs</em>, <em>varkw</em>, <em>defaults</em>, <em>formatarg</em>, <em>formatvarargs</em>, <em>formatvarkw</em>, <em>formatvalue</em>, <em>join</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.formatargspec" title="Permalink to this definition">¶</a></dt>
<dd><p>Format a pretty argument spec from the four values returned by
<a class="reference internal" href="#inspect.getargspec" title="inspect.getargspec"><code class="xref py py-func docutils literal notranslate"><span class="pre">getargspec()</span></code></a>.  The format* arguments are the corresponding optional
formatting functions that are called to turn names and values into strings.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.formatargvalues">
<code class="descclassname">inspect.</code><code class="descname">formatargvalues</code><span class="sig-paren">(</span><em>args</em><span class="optional">[</span>, <em>varargs</em>, <em>varkw</em>, <em>locals</em>, <em>formatarg</em>, <em>formatvarargs</em>, <em>formatvarkw</em>, <em>formatvalue</em>, <em>join</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.formatargvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>Format a pretty argument spec from the four values returned by
<a class="reference internal" href="#inspect.getargvalues" title="inspect.getargvalues"><code class="xref py py-func docutils literal notranslate"><span class="pre">getargvalues()</span></code></a>.  The format* arguments are the corresponding optional
formatting functions that are called to turn names and values into strings.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getmro">
<code class="descclassname">inspect.</code><code class="descname">getmro</code><span class="sig-paren">(</span><em>cls</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getmro" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple of class cls’s base classes, including cls, in method resolution
order.  No class appears more than once in this tuple. Note that the method
resolution order depends on cls’s type.  Unless a very peculiar user-defined
metatype is in use, cls will be the first element of the tuple.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getcallargs">
<code class="descclassname">inspect.</code><code class="descname">getcallargs</code><span class="sig-paren">(</span><em>func[, *args][, **kwds]</em><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getcallargs" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind the <em>args</em> and <em>kwds</em> to the argument names of the Python function or
method <em>func</em>, as if it was called with them. For bound methods, bind also the
first argument (typically named <code class="docutils literal notranslate"><span class="pre">self</span></code>) to the associated instance. A dict
is returned, mapping the argument names (including the names of the <code class="docutils literal notranslate"><span class="pre">*</span></code> and
<code class="docutils literal notranslate"><span class="pre">**</span></code> arguments, if any) to their values from <em>args</em> and <em>kwds</em>. In case of
invoking <em>func</em> incorrectly, i.e. whenever <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwds)</span></code> would raise
an exception because of incompatible signature, an exception of the same type
and the same or similar message is raised. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">inspect</span> <span class="k">import</span> <span class="n">getcallargs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="n">pos</span><span class="p">,</span> <span class="o">**</span><span class="n">named</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: 1, &#39;named&#39;: {}, &#39;b&#39;: 2, &#39;pos&#39;: (3,)}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: 2, &#39;named&#39;: {&#39;x&#39;: 4}, &#39;b&#39;: 1, &#39;pos&#39;: ()}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">f() takes at least 1 argument (0 given)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="the-interpreter-stack">
<span id="inspect-stack"></span><h2>28.13.4. The interpreter stack<a class="headerlink" href="#the-interpreter-stack" title="Permalink to this headline">¶</a></h2>
<p>When the following functions return “frame records,” each record is a tuple of
six items: the frame object, the filename, the line number of the current line,
the function name, a list of lines of context from the source code, and the
index of the current line within that list.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Keeping references to frame objects, as found in the first element of the frame
records these functions return, can cause your program to create reference
cycles.  Once a reference cycle has been created, the lifespan of all objects
which can be accessed from the objects which form the cycle can become much
longer even if Python’s optional cycle detector is enabled.  If such cycles must
be created, it is important to ensure they are explicitly broken to avoid the
delayed destruction of objects and increased memory consumption which occurs.</p>
<p>Though the cycle detector will catch these, destruction of the frames (and local
variables) can be made deterministic by removing the cycle in a
<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.  This is also important if the cycle detector was
disabled when Python was compiled or using <a class="reference internal" href="gc.html#gc.disable" title="gc.disable"><code class="xref py py-func docutils literal notranslate"><span class="pre">gc.disable()</span></code></a>.  For example:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">handle_stackframe_without_leak</span><span class="p">():</span>
    <span class="n">frame</span> <span class="o">=</span> <span class="n">inspect</span><span class="o">.</span><span class="n">currentframe</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c1"># do something with the frame</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="k">del</span> <span class="n">frame</span>
</pre></div>
</div>
</div>
<p>The optional <em>context</em> argument supported by most of these functions specifies
the number of lines of context to return, which are centered around the current
line.</p>
<dl class="function">
<dt id="inspect.getframeinfo">
<code class="descclassname">inspect.</code><code class="descname">getframeinfo</code><span class="sig-paren">(</span><em>frame</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getframeinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Get information about a frame or traceback object.  A 5-tuple is returned, the
last five elements of the frame’s frame record.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Returns a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">Traceback(filename,</span> <span class="pre">lineno,</span> <span class="pre">function,</span>
<span class="pre">code_context,</span> <span class="pre">index)</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.getouterframes">
<code class="descclassname">inspect.</code><code class="descname">getouterframes</code><span class="sig-paren">(</span><em>frame</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getouterframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a list of frame records for a frame and all outer frames.  These frames
represent the calls that lead to the creation of <em>frame</em>. The first entry in the
returned list represents <em>frame</em>; the last entry represents the outermost call
on <em>frame</em>’s stack.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.getinnerframes">
<code class="descclassname">inspect.</code><code class="descname">getinnerframes</code><span class="sig-paren">(</span><em>traceback</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.getinnerframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a list of frame records for a traceback’s frame and all inner frames.  These
frames represent calls made as a consequence of <em>frame</em>.  The first entry in the
list represents <em>traceback</em>; the last entry represents where the exception was
raised.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.currentframe">
<code class="descclassname">inspect.</code><code class="descname">currentframe</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.currentframe" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the frame object for the caller’s stack frame.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> This function relies on Python stack frame support in the interpreter,
which isn’t guaranteed to exist in all implementations of Python.  If
running in an implementation without Python stack frame support this
function returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="inspect.stack">
<code class="descclassname">inspect.</code><code class="descname">stack</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of frame records for the caller’s stack.  The first entry in the
returned list represents the caller; the last entry represents the outermost
call on the stack.</p>
</dd></dl>

<dl class="function">
<dt id="inspect.trace">
<code class="descclassname">inspect.</code><code class="descname">trace</code><span class="sig-paren">(</span><span class="optional">[</span><em>context</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#inspect.trace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of frame records for the stack between the current frame and the
frame in which an exception currently being handled was raised in.  The first
entry in the list represents the caller; the last entry represents where the
exception was raised.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a><ul>
<li><a class="reference internal" href="#types-and-members">28.13.1. Types and members</a></li>
<li><a class="reference internal" href="#retrieving-source-code">28.13.2. Retrieving source code</a></li>
<li><a class="reference internal" href="#classes-and-functions">28.13.3. Classes and functions</a></li>
<li><a class="reference internal" href="#the-interpreter-stack">28.13.4. The interpreter stack</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gc.html"
                        title="previous chapter">28.12. <code class="docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="site.html"
                        title="next chapter">28.14. <code class="docutils literal notranslate"><span class="pre">site</span></code> — Site-specific configuration hook</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/inspect.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="site.html" title="28.14. site — Site-specific configuration hook"
             >next</a> |</li>
        <li class="right" >
          <a href="gc.html" title="28.12. gc — Garbage Collector interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\mǷpffhtml/library/internet.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20. Internet Protocols and Support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.1. webbrowser — Convenient Web-browser controller" href="webbrowser.html" />
    <link rel="prev" title="19.15. xml.parsers.expat — Fast XML parsing using Expat" href="pyexpat.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/internet.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webbrowser.html" title="20.1. webbrowser — Convenient Web-browser controller"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pyexpat.html" title="19.15. xml.parsers.expat — Fast XML parsing using Expat"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="internet-protocols-and-support">
<span id="internet"></span><h1>20. Internet Protocols and Support<a class="headerlink" href="#internet-protocols-and-support" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><p id="index-1">The modules described in this chapter implement Internet protocols and  support
for related technology.  They are all implemented in Python. Most of these
modules require the presence of the system-dependent module <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a>, which
is currently supported on most popular platforms.  Here is an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="webbrowser.html">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a><ul>
<li class="toctree-l2"><a class="reference internal" href="webbrowser.html#browser-controller-objects">20.1.1. Browser Controller Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="cgi.html">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#introduction">20.2.1. Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#using-the-cgi-module">20.2.2. Using the cgi module</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#higher-level-interface">20.2.3. Higher Level Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#old-classes">20.2.4. Old classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#functions">20.2.5. Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#caring-about-security">20.2.6. Caring about security</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#installing-your-cgi-script-on-a-unix-system">20.2.7. Installing your CGI script on a Unix system</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#testing-your-cgi-script">20.2.8. Testing your CGI script</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#debugging-cgi-scripts">20.2.9. Debugging CGI scripts</a></li>
<li class="toctree-l2"><a class="reference internal" href="cgi.html#common-problems-and-solutions">20.2.10. Common problems and solutions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="cgitb.html">20.3. <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> — Traceback manager for CGI scripts</a></li>
<li class="toctree-l1"><a class="reference internal" href="wsgiref.html">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#module-wsgiref.util">20.4.1. <code class="docutils literal notranslate"><span class="pre">wsgiref.util</span></code> – WSGI environment utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#module-wsgiref.headers">20.4.2. <code class="docutils literal notranslate"><span class="pre">wsgiref.headers</span></code> – WSGI response header tools</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#module-wsgiref.simple_server">20.4.3. <code class="docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code> – a simple WSGI HTTP server</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#module-wsgiref.validate">20.4.4. <code class="docutils literal notranslate"><span class="pre">wsgiref.validate</span></code> — WSGI conformance checker</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#module-wsgiref.handlers">20.4.5. <code class="docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code> – server/gateway base classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="wsgiref.html#examples">20.4.6. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="urllib.html">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a><ul>
<li class="toctree-l2"><a class="reference internal" href="urllib.html#high-level-interface">20.5.1. High-level interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib.html#utility-functions">20.5.2. Utility functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib.html#url-opener-objects">20.5.3. URL Opener objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib.html#urllib-restrictions">20.5.4. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> Restrictions</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib.html#examples">20.5.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="urllib2.html">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#request-objects">20.6.1. Request Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#openerdirector-objects">20.6.2. OpenerDirector Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#basehandler-objects">20.6.3. BaseHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httpredirecthandler-objects">20.6.4. HTTPRedirectHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httpcookieprocessor-objects">20.6.5. HTTPCookieProcessor Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#proxyhandler-objects">20.6.6. ProxyHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httppasswordmgr-objects">20.6.7. HTTPPasswordMgr Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#abstractbasicauthhandler-objects">20.6.8. AbstractBasicAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httpbasicauthhandler-objects">20.6.9. HTTPBasicAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#proxybasicauthhandler-objects">20.6.10. ProxyBasicAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#abstractdigestauthhandler-objects">20.6.11. AbstractDigestAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httpdigestauthhandler-objects">20.6.12. HTTPDigestAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#proxydigestauthhandler-objects">20.6.13. ProxyDigestAuthHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httphandler-objects">20.6.14. HTTPHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httpshandler-objects">20.6.15. HTTPSHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#filehandler-objects">20.6.16. FileHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#ftphandler-objects">20.6.17. FTPHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#cacheftphandler-objects">20.6.18. CacheFTPHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#unknownhandler-objects">20.6.19. UnknownHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#httperrorprocessor-objects">20.6.20. HTTPErrorProcessor Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="urllib2.html#examples">20.6.21. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="httplib.html">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="httplib.html#httpconnection-objects">20.7.1. HTTPConnection Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="httplib.html#httpresponse-objects">20.7.2. HTTPResponse Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="httplib.html#examples">20.7.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="ftplib.html">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ftplib.html#ftp-objects">20.8.1. FTP Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="ftplib.html#ftp-tls-objects">20.8.2. FTP_TLS Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="poplib.html">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="poplib.html#pop3-objects">20.9.1. POP3 Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="poplib.html#pop3-example">20.9.2. POP3 Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="imaplib.html">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="imaplib.html#imap4-objects">20.10.1. IMAP4 Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="imaplib.html#imap4-example">20.10.2. IMAP4 Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="nntplib.html">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="nntplib.html#nntp-objects">20.11.1. NNTP Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="smtplib.html">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="smtplib.html#smtp-objects">20.12.1. SMTP Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtplib.html#smtp-example">20.12.2. SMTP Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="smtpd.html">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a><ul>
<li class="toctree-l2"><a class="reference internal" href="smtpd.html#smtpserver-objects">20.13.1. SMTPServer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtpd.html#debuggingserver-objects">20.13.2. DebuggingServer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtpd.html#pureproxy-objects">20.13.3. PureProxy Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="smtpd.html#mailmanproxy-objects">20.13.4. MailmanProxy Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="telnetlib.html">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a><ul>
<li class="toctree-l2"><a class="reference internal" href="telnetlib.html#telnet-objects">20.14.1. Telnet Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="telnetlib.html#telnet-example">20.14.2. Telnet Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="uuid.html">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a><ul>
<li class="toctree-l2"><a class="reference internal" href="uuid.html#example">20.15.1. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="urlparse.html">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a><ul>
<li class="toctree-l2"><a class="reference internal" href="urlparse.html#results-of-urlparse-and-urlsplit">20.16.1. Results of <code class="docutils literal notranslate"><span class="pre">urlparse()</span></code> and <code class="docutils literal notranslate"><span class="pre">urlsplit()</span></code></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="socketserver.html">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="socketserver.html#server-creation-notes">20.17.1. Server Creation Notes</a></li>
<li class="toctree-l2"><a class="reference internal" href="socketserver.html#server-objects">20.17.2. Server Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="socketserver.html#request-handler-objects">20.17.3. Request Handler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="socketserver.html#examples">20.17.4. Examples</a><ul>
<li class="toctree-l3"><a class="reference internal" href="socketserver.html#socketserver-tcpserver-example">20.17.4.1. <code class="docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code> Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="socketserver.html#socketserver-udpserver-example">20.17.4.2. <code class="docutils literal notranslate"><span class="pre">SocketServer.UDPServer</span></code> Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="socketserver.html#asynchronous-mixins">20.17.4.3. Asynchronous Mixins</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="basehttpserver.html">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a><ul>
<li class="toctree-l2"><a class="reference internal" href="basehttpserver.html#more-examples">20.18.1. More examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="simplehttpserver.html">20.19. <code class="docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code> — Simple HTTP request handler</a></li>
<li class="toctree-l1"><a class="reference internal" href="cgihttpserver.html">20.20. <code class="docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code> — CGI-capable HTTP request handler</a></li>
<li class="toctree-l1"><a class="reference internal" href="cookielib.html">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#cookiejar-and-filecookiejar-objects">20.21.1. CookieJar and FileCookieJar Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#filecookiejar-subclasses-and-co-operation-with-web-browsers">20.21.2. FileCookieJar subclasses and co-operation with web browsers</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#cookiepolicy-objects">20.21.3. CookiePolicy Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#defaultcookiepolicy-objects">20.21.4. DefaultCookiePolicy Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#cookie-objects">20.21.5. Cookie Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookielib.html#examples">20.21.6. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="cookie.html">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cookie.html#cookie-objects">20.22.1. Cookie Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookie.html#morsel-objects">20.22.2. Morsel Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cookie.html#example">20.22.3. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xmlrpclib.html">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#serverproxy-objects">20.23.1. ServerProxy Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#boolean-objects">20.23.2. Boolean Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#datetime-objects">20.23.3. DateTime Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#binary-objects">20.23.4. Binary Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#fault-objects">20.23.5. Fault Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#protocolerror-objects">20.23.6. ProtocolError Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#multicall-objects">20.23.7. MultiCall Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#convenience-functions">20.23.8. Convenience Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#example-of-client-usage">20.23.9. Example of Client Usage</a></li>
<li class="toctree-l2"><a class="reference internal" href="xmlrpclib.html#example-of-client-and-server-usage">20.23.10. Example of Client and Server Usage</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="simplexmlrpcserver.html">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a><ul>
<li class="toctree-l2"><a class="reference internal" href="simplexmlrpcserver.html#simplexmlrpcserver-objects">20.24.1. SimpleXMLRPCServer Objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="simplexmlrpcserver.html#simplexmlrpcserver-example">20.24.1.1. SimpleXMLRPCServer Example</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="simplexmlrpcserver.html#cgixmlrpcrequesthandler">20.24.2. CGIXMLRPCRequestHandler</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="docxmlrpcserver.html">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a><ul>
<li class="toctree-l2"><a class="reference internal" href="docxmlrpcserver.html#docxmlrpcserver-objects">20.25.1. DocXMLRPCServer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="docxmlrpcserver.html#doccgixmlrpcrequesthandler">20.25.2. DocCGIXMLRPCRequestHandler</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="pyexpat.html"
                        title="previous chapter">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="webbrowser.html"
                        title="next chapter">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/internet.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="webbrowser.html" title="20.1. webbrowser — Convenient Web-browser controller"
             >next</a> |</li>
        <li class="right" >
          <a href="pyexpat.html" title="19.15. xml.parsers.expat — Fast XML parsing using Expat"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�$��$�$html/library/intro.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. Introduction &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Built-in Functions" href="functions.html" />
    <link rel="prev" title="The Python Standard Library" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/intro.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functions.html" title="2. Built-in Functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Standard Library"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="introduction">
<span id="library-intro"></span><h1>1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h1>
<p>The “Python library” contains several different kinds of components.</p>
<p>It contains data types that would normally be considered part of the “core” of a
language, such as numbers and lists.  For these types, the Python language core
defines the form of literals and places some constraints on their semantics, but
does not fully define the semantics.  (On the other hand, the language core does
define syntactic properties like the spelling and priorities of operators.)</p>
<p>The library also contains built-in functions and exceptions — objects that can
be used by all Python code without the need of an <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.
Some of these are defined by the core language, but many are not essential for
the core semantics and are only described here.</p>
<p>The bulk of the library, however, consists of a collection of modules. There are
many ways to dissect this collection.  Some modules are written in C and built
in to the Python interpreter; others are written in Python and imported in
source form.  Some modules provide interfaces that are highly specific to
Python, like printing a stack trace; some provide interfaces that are specific
to particular operating systems, such as access to specific hardware; others
provide interfaces that are specific to a particular application domain, like
the World Wide Web. Some modules are available in all versions and ports of
Python; others are only available when the underlying system supports or
requires them; yet others are available only when a particular configuration
option was chosen at the time when Python was compiled and installed.</p>
<p>This manual is organized “from the inside out:” it first describes the built-in
data types, then the built-in functions and exceptions, and finally the modules,
grouped in chapters of related modules.  The ordering of the chapters as well as
the ordering of the modules within each chapter is roughly from most relevant to
least important.</p>
<p>This means that if you start reading this manual from the start, and skip to the
next chapter when you get bored, you will get a reasonable overview of the
available modules and application areas that are supported by the Python
library.  Of course, you don’t <em>have</em> to read it like a novel — you can also
browse the table of contents (in front of the manual), or look for a specific
function, module or term in the index (in the back).  And finally, if you enjoy
learning about random subjects, you choose a random page number (see module
<a class="reference internal" href="random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a>) and read a section or two.  Regardless of the order in which you
read the sections of this manual, it helps to start with chapter
<a class="reference internal" href="functions.html#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a>, as the remainder of the manual assumes familiarity with
this material.</p>
<p>Let the show begin!</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">The Python Standard Library</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="functions.html"
                        title="next chapter">2. Built-in Functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/intro.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functions.html" title="2. Built-in Functions"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Standard Library"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\"��%�%�html/library/io.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.2. io — Core tools for working with streams &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.3. time — Time access and conversions" href="time.html" />
    <link rel="prev" title="15.1. os — Miscellaneous operating system interfaces" href="os.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/io.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="time.html" title="15.3. time — Time access and conversions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="os.html" title="15.1. os — Miscellaneous operating system interfaces"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-io">
<span id="io-core-tools-for-working-with-streams"></span><h1>15.2. <a class="reference internal" href="#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> — Core tools for working with streams<a class="headerlink" href="#module-io" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The <a class="reference internal" href="#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module provides the Python interfaces to stream handling.
Under Python 2.x, this is proposed as an alternative to the built-in
<a class="reference internal" href="functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> object, but in Python 3.x it is the default interface to
access files and streams.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since this module has been designed primarily for Python 3.x, you have to
be aware that all uses of “bytes” in this document refer to the
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type (of which <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> is an alias), and all uses
of “text” refer to the <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> type.  Furthermore, those two
types are not interchangeable in the <a class="reference internal" href="#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> APIs.</p>
</div>
<p>At the top of the I/O hierarchy is the abstract base class <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>.  It
defines the basic interface to a stream.  Note, however, that there is no
separation between reading and writing to streams; implementations are allowed
to raise an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if they do not support a given operation.</p>
<p>Extending <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> is <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> which deals simply with the
reading and writing of raw bytes to a stream.  <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a> subclasses
<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> to provide an interface to files in the machine’s
file system.</p>
<p><a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> deals with buffering on a raw byte stream
(<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a>).  Its subclasses, <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a>,
<a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a>, and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code></a> buffer streams that are
readable, writable, and both readable and writable.
<a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> provides a buffered interface to random access
streams.  <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a> is a simple stream of in-memory bytes.</p>
<p>Another <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> subclass, <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a>, deals with
streams whose bytes represent text, and handles encoding and decoding
from and to <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> strings.  <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a>, which extends
it, is a buffered text interface to a buffered raw stream
(<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>). Finally, <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> is an in-memory
stream for unicode text.</p>
<p>Argument names are not part of the specification, and only the arguments of
<a class="reference internal" href="#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> are intended to be used as keyword arguments.</p>
<div class="section" id="module-interface">
<h2>15.2.1. Module Interface<a class="headerlink" href="#module-interface" title="Permalink to this headline">¶</a></h2>
<dl class="data">
<dt id="io.DEFAULT_BUFFER_SIZE">
<code class="descclassname">io.</code><code class="descname">DEFAULT_BUFFER_SIZE</code><a class="headerlink" href="#io.DEFAULT_BUFFER_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>An int containing the default buffer size used by the module’s buffered I/O
classes.  <a class="reference internal" href="#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> uses the file’s blksize (as obtained by
<a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>) if possible.</p>
</dd></dl>

<dl class="function">
<dt id="io.open">
<code class="descclassname">io.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em>, <em>mode='r'</em>, <em>buffering=-1</em>, <em>encoding=None</em>, <em>errors=None</em>, <em>newline=None</em>, <em>closefd=True</em><span class="sig-paren">)</span><a class="headerlink" href="#io.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>file</em> and return a corresponding stream.  If the file cannot be opened,
an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.</p>
<p><em>file</em> is either a string giving the pathname (absolute or
relative to the current working directory) of the file to be opened or
an integer file descriptor of the file to be wrapped.  (If a file descriptor
is given, it is closed when the returned I/O object is closed, unless
<em>closefd</em> is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>.)</p>
<p><em>mode</em> is an optional string that specifies the mode in which the file is
opened.  It defaults to <code class="docutils literal notranslate"><span class="pre">'r'</span></code> which means open for reading in text mode.
Other common values are <code class="docutils literal notranslate"><span class="pre">'w'</span></code> for writing (truncating the file if it
already exists), and <code class="docutils literal notranslate"><span class="pre">'a'</span></code> for appending (which on <em>some</em> Unix systems,
means that <em>all</em> writes append to the end of the file regardless of the
current seek position).  In text mode, if <em>encoding</em> is not specified the
encoding used is platform dependent. (For reading and writing raw bytes use
binary mode and leave <em>encoding</em> unspecified.)  The available modes are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="88%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td>Character</td>
<td>Meaning</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>open for reading (default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span></code></td>
<td>open for writing, truncating the file first</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'a'</span></code></td>
<td>open for writing, appending to the end of the file if it exists</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'b'</span></code></td>
<td>binary mode</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'t'</span></code></td>
<td>text mode (default)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'+'</span></code></td>
<td>open a disk file for updating (reading and writing)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'U'</span></code></td>
<td>universal newlines mode (for backwards compatibility; should
not be used in new code)</td>
</tr>
</tbody>
</table>
<p>The default mode is <code class="docutils literal notranslate"><span class="pre">'rt'</span></code> (open for reading text).  For binary random
access, the mode <code class="docutils literal notranslate"><span class="pre">'w+b'</span></code> opens and truncates the file to 0 bytes, while
<code class="docutils literal notranslate"><span class="pre">'r+b'</span></code> opens the file without truncation.</p>
<p>Python distinguishes between files opened in binary and text modes, even when
the underlying operating system doesn’t.  Files opened in binary mode
(including <code class="docutils literal notranslate"><span class="pre">'b'</span></code> in the <em>mode</em> argument) return contents as <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>
objects without any decoding.  In text mode (the default, or when <code class="docutils literal notranslate"><span class="pre">'t'</span></code> is
included in the <em>mode</em> argument), the contents of the file are returned as
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified <em>encoding</em> if given.</p>
<p><em>buffering</em> is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer &gt; 1 to indicate
the size of a fixed-size chunk buffer.  When no <em>buffering</em> argument is
given, the default buffering policy works as follows:</p>
<ul class="simple">
<li>Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device’s
“block size” and falling back on <a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code class="xref py py-attr docutils literal notranslate"><span class="pre">DEFAULT_BUFFER_SIZE</span></code></a>.
On many systems, the buffer will typically be 4096 or 8192 bytes long.</li>
<li>“Interactive” text files (files for which <code class="xref py py-meth docutils literal notranslate"><span class="pre">isatty()</span></code> returns True)
use line buffering.  Other text files use the policy described above
for binary files.</li>
</ul>
<p><em>encoding</em> is the name of the encoding used to decode or encode the file.
This should only be used in text mode.  The default encoding is platform
dependent (whatever <a class="reference internal" href="locale.html#locale.getpreferredencoding" title="locale.getpreferredencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.getpreferredencoding()</span></code></a> returns), but any
encoding supported by Python can be used.  See the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module for
the list of supported encodings.</p>
<p><em>errors</em> is an optional string that specifies how encoding and decoding
errors are to be handled—this cannot be used in binary mode.  Pass
<code class="docutils literal notranslate"><span class="pre">'strict'</span></code> to raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception if there is an encoding
error (the default of <code class="docutils literal notranslate"><span class="pre">None</span></code> has the same effect), or pass <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> to
ignore errors.  (Note that ignoring encoding errors can lead to data loss.)
<code class="docutils literal notranslate"><span class="pre">'replace'</span></code> causes a replacement marker (such as <code class="docutils literal notranslate"><span class="pre">'?'</span></code>) to be inserted
where there is malformed data.  When writing, <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code>
(replace with the appropriate XML character reference) or
<code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> (replace with backslashed escape sequences) can be
used.  Any other error handling name that has been registered with
<a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a> is also valid.</p>
<p id="index-0"><em>newline</em> controls how <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> works (it only applies to
text mode).  It can be <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>.
It works as follows:</p>
<ul class="simple">
<li>On input, if <em>newline</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, universal newlines mode is enabled.
Lines in the input can end in <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>, and these
are translated into <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> before being returned to the caller.  If it is
<code class="docutils literal notranslate"><span class="pre">''</span></code>, universal newlines mode is enabled, but line endings are returned to
the caller untranslated.  If it has any of the other legal values, input
lines are only terminated by the given string, and the line ending is
returned to the caller untranslated.</li>
<li>On output, if <em>newline</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, any <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> characters written are
translated to the system default line separator, <a class="reference internal" href="os.html#os.linesep" title="os.linesep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.linesep</span></code></a>.  If
<em>newline</em> is <code class="docutils literal notranslate"><span class="pre">''</span></code>, no translation takes place.  If <em>newline</em> is any of
the other legal values, any <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> characters written are translated to
the given string.</li>
</ul>
<p>If <em>closefd</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> and a file descriptor rather than a filename was
given, the underlying file descriptor will be kept open when the file is
closed.  If a filename is given <em>closefd</em> has no effect and must be <code class="docutils literal notranslate"><span class="pre">True</span></code>
(the default).</p>
<p>The type of file object returned by the <a class="reference internal" href="#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function depends on the
mode.  When <a class="reference internal" href="#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> is used to open a file in a text mode (<code class="docutils literal notranslate"><span class="pre">'w'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'wt'</span></code>, <code class="docutils literal notranslate"><span class="pre">'rt'</span></code>, etc.), it returns a subclass of
<a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> (specifically <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a>).  When used to open
a file in a binary mode with buffering, the returned class is a subclass of
<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>.  The exact class varies: in read binary mode, it
returns a <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a>; in write binary and append binary modes,
it returns a <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a>, and in read/write mode, it returns a
<a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a>.  When buffering is disabled, the raw stream, a
subclass of <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a>, <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a>, is returned.</p>
<p>It is also possible to use an <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> or <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> string
as a file for both reading and writing.  For <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> strings
<a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> can be used like a file opened in text mode,
and for <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> a <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a> can be used like a
file opened in a binary mode.</p>
</dd></dl>

<dl class="exception">
<dt id="io.BlockingIOError">
<em class="property">exception </em><code class="descclassname">io.</code><code class="descname">BlockingIOError</code><a class="headerlink" href="#io.BlockingIOError" title="Permalink to this definition">¶</a></dt>
<dd><p>Error raised when blocking would occur on a non-blocking stream.  It inherits
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
<p>In addition to those of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>, <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> has one
attribute:</p>
<dl class="attribute">
<dt id="io.BlockingIOError.characters_written">
<code class="descname">characters_written</code><a class="headerlink" href="#io.BlockingIOError.characters_written" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer containing the number of characters written to the stream
before it blocked.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="io.UnsupportedOperation">
<em class="property">exception </em><code class="descclassname">io.</code><code class="descname">UnsupportedOperation</code><a class="headerlink" href="#io.UnsupportedOperation" title="Permalink to this definition">¶</a></dt>
<dd><p>An exception inheriting <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> and <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> that is raised
when an unsupported operation is called on a stream.</p>
</dd></dl>

</div>
<div class="section" id="i-o-base-classes">
<h2>15.2.2. I/O Base Classes<a class="headerlink" href="#i-o-base-classes" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="io.IOBase">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">IOBase</code><a class="headerlink" href="#io.IOBase" title="Permalink to this definition">¶</a></dt>
<dd><p>The abstract base class for all I/O classes, acting on streams of bytes.
There is no public constructor.</p>
<p>This class provides empty abstract implementations for many methods
that derived classes can override selectively; the default
implementations represent a file that cannot be read, written or
seeked.</p>
<p>Even though <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> does not declare <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>,
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> because their signatures will vary, implementations and
clients should consider those methods part of the interface.  Also,
implementations may raise an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> when operations they do not
support are called.</p>
<p>The basic type used for binary data read from or written to a file is
<code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> (also known as <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>).  Method arguments may
also be <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> or <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> of arrays of bytes.
In some cases, such as <a class="reference internal" href="#io.RawIOBase.readinto" title="io.RawIOBase.readinto"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code></a>, a writable object
such as <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> is required.
Text I/O classes work with <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> data.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Implementations should support <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> arguments.</p>
</div>
<p>Note that calling any method (even inquiries) on a closed stream is
undefined.  Implementations may raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> in this case.</p>
<p>IOBase (and its subclasses) support the iterator protocol, meaning that an
<a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> object can be iterated over yielding the lines in a stream.
Lines are defined slightly differently depending on whether the stream is
a binary stream (yielding <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>), or a text stream (yielding
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> strings).  See <a class="reference internal" href="#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> below.</p>
<p>IOBase is also a context manager and therefore supports the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  In this example, <em>file</em> is closed after the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement’s suite is finished—even if an exception occurs:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">io</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;spam.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">file</span><span class="p">:</span>
    <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;Spam and eggs!&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> provides these data attributes and methods:</p>
<dl class="method">
<dt id="io.IOBase.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush and close this stream. This method has no effect if the file is
already closed. Once the file is closed, any operation on the file
(e.g. reading or writing) will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p>As a convenience, it is allowed to call this method more than once;
only the first call, however, will have an effect.</p>
</dd></dl>

<dl class="attribute">
<dt id="io.IOBase.closed">
<code class="descname">closed</code><a class="headerlink" href="#io.IOBase.closed" title="Permalink to this definition">¶</a></dt>
<dd><p>True if the stream is closed.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.fileno">
<code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the underlying file descriptor (an integer) of the stream if it
exists.  An <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised if the IO object does not use a file
descriptor.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush the write buffers of the stream if applicable.  This does nothing
for read-only and non-blocking streams.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.isatty">
<code class="descname">isatty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.isatty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stream is interactive (i.e., connected to
a terminal/tty device).</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.readable">
<code class="descname">readable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.readable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stream can be read from.  If <code class="docutils literal notranslate"><span class="pre">False</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>
will raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><em>limit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return one line from the stream.  If <em>limit</em> is specified, at
most <em>limit</em> bytes will be read.</p>
<p>The line terminator is always <code class="docutils literal notranslate"><span class="pre">b'\n'</span></code> for binary files; for text files,
the <em>newline</em> argument to <a class="reference internal" href="#io.open" title="io.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> can be used to select the line
terminator(s) recognized.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.readlines">
<code class="descname">readlines</code><span class="sig-paren">(</span><em>hint=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return a list of lines from the stream.  <em>hint</em> can be specified
to control the number of lines read: no more lines will be read if the
total size (in bytes/characters) of all lines so far exceeds <em>hint</em>.</p>
<p>Note that it’s already possible to iterate on file objects using <code class="docutils literal notranslate"><span class="pre">for</span>
<span class="pre">line</span> <span class="pre">in</span> <span class="pre">file:</span> <span class="pre">...</span></code> without calling <code class="docutils literal notranslate"><span class="pre">file.readlines()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.seek">
<code class="descname">seek</code><span class="sig-paren">(</span><em>offset</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the stream position to the given byte <em>offset</em>.  <em>offset</em> is
interpreted relative to the position indicated by <em>whence</em>.  The default
value for <em>whence</em> is <code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_SET</span></code>.  Values for <em>whence</em> are:</p>
<ul class="simple">
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_SET</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> – start of the stream (the default);
<em>offset</em> should be zero or positive</li>
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_CUR</span></code> or <code class="docutils literal notranslate"><span class="pre">1</span></code> – current stream position; <em>offset</em> may
be negative</li>
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_END</span></code> or <code class="docutils literal notranslate"><span class="pre">2</span></code> – end of the stream; <em>offset</em> is usually
negative</li>
</ul>
<p>Return the new absolute position.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <code class="docutils literal notranslate"><span class="pre">SEEK_*</span></code> constants</p>
</div>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.seekable">
<code class="descname">seekable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.seekable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stream supports random access.  If <code class="docutils literal notranslate"><span class="pre">False</span></code>,
<a class="reference internal" href="#io.IOBase.seek" title="io.IOBase.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a>, <a class="reference internal" href="#io.IOBase.tell" title="io.IOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> and <a class="reference internal" href="#io.IOBase.truncate" title="io.IOBase.truncate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code></a> will raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.tell">
<code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current stream position.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.truncate">
<code class="descname">truncate</code><span class="sig-paren">(</span><em>size=None</em><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.truncate" title="Permalink to this definition">¶</a></dt>
<dd><p>Resize the stream to the given <em>size</em> in bytes (or the current position
if <em>size</em> is not specified).  The current stream position isn’t changed.
This resizing can extend or reduce the current file size.  In case of
extension, the contents of the new file area depend on the platform
(on most systems, additional bytes are zero-filled, on Windows they’re
undetermined).  The new file size is returned.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.writable">
<code class="descname">writable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.writable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stream supports writing.  If <code class="docutils literal notranslate"><span class="pre">False</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> and <a class="reference internal" href="#io.IOBase.truncate" title="io.IOBase.truncate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code></a> will raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.writelines">
<code class="descname">writelines</code><span class="sig-paren">(</span><em>lines</em><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.writelines" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a list of lines to the stream.  Line separators are not added, so it
is usual for each of the lines provided to have a line separator at the
end.</p>
</dd></dl>

<dl class="method">
<dt id="io.IOBase.__del__">
<code class="descname">__del__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.IOBase.__del__" title="Permalink to this definition">¶</a></dt>
<dd><p>Prepare for object destruction. <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> provides a default
implementation of this method that calls the instance’s
<a class="reference internal" href="#io.IOBase.close" title="io.IOBase.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.RawIOBase">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">RawIOBase</code><a class="headerlink" href="#io.RawIOBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for raw binary I/O.  It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>.  There is no
public constructor.</p>
<p>Raw binary I/O typically provides low-level access to an underlying OS
device or API, and does not try to encapsulate it in high-level primitives
(this is left to Buffered I/O and Text I/O, described later in this page).</p>
<p>In addition to the attributes and methods from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>,
RawIOBase provides the following methods:</p>
<dl class="method">
<dt id="io.RawIOBase.read">
<code class="descname">read</code><span class="sig-paren">(</span><em>n=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.RawIOBase.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read up to <em>n</em> bytes from the object and return them.  As a convenience,
if <em>n</em> is unspecified or -1, <a class="reference internal" href="#io.RawIOBase.readall" title="io.RawIOBase.readall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readall()</span></code></a> is called.  Otherwise,
only one system call is ever made.  Fewer than <em>n</em> bytes may be
returned if the operating system call returns fewer than <em>n</em> bytes.</p>
<p>If 0 bytes are returned, and <em>n</em> was not 0, this indicates end of file.
If the object is in non-blocking mode and no bytes are available,
<code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
</dd></dl>

<dl class="method">
<dt id="io.RawIOBase.readall">
<code class="descname">readall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.RawIOBase.readall" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return all the bytes from the stream until EOF, using multiple
calls to the stream if necessary.</p>
</dd></dl>

<dl class="method">
<dt id="io.RawIOBase.readinto">
<code class="descname">readinto</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#io.RawIOBase.readinto" title="Permalink to this definition">¶</a></dt>
<dd><p>Read up to len(b) bytes into <em>b</em>, and return the number
of bytes read.  The object <em>b</em> should be a pre-allocated, writable
array of bytes, either <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> or <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.
If the object is in non-blocking mode and no
bytes are available, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
</dd></dl>

<dl class="method">
<dt id="io.RawIOBase.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#io.RawIOBase.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write <em>b</em> to the underlying raw stream, and return the
number of bytes written.  The object <em>b</em> should be an array
of bytes, either <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, or
<a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.  The return value can be less than
<code class="docutils literal notranslate"><span class="pre">len(b)</span></code>, depending on specifics of the underlying raw stream, and
especially if it is in non-blocking mode.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned if the
raw stream is set not to block and no single byte could be readily
written to it.  The caller may release or mutate <em>b</em> after
this method returns, so the implementation should only access <em>b</em>
during the method call.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.BufferedIOBase">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BufferedIOBase</code><a class="headerlink" href="#io.BufferedIOBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for binary streams that support some kind of buffering.
It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>. There is no public constructor.</p>
<p>The main difference with <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> is that methods <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>,
<a class="reference internal" href="#io.BufferedIOBase.readinto" title="io.BufferedIOBase.readinto"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code></a> and <a class="reference internal" href="#io.BufferedIOBase.write" title="io.BufferedIOBase.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> will try (respectively) to read as much
input as requested or to consume all given output, at the expense of
making perhaps more than one system call.</p>
<p>In addition, those methods can raise <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> if the
underlying raw stream is in non-blocking mode and cannot take or give
enough data; unlike their <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> counterparts, they will
never return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Besides, the <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method does not have a default
implementation that defers to <a class="reference internal" href="#io.BufferedIOBase.readinto" title="io.BufferedIOBase.readinto"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code></a>.</p>
<p>A typical <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> implementation should not inherit from a
<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> implementation, but wrap one, like
<a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a> and <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a> do.</p>
<p><a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> provides or overrides these methods and attribute in
addition to those from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>:</p>
<dl class="attribute">
<dt id="io.BufferedIOBase.raw">
<code class="descname">raw</code><a class="headerlink" href="#io.BufferedIOBase.raw" title="Permalink to this definition">¶</a></dt>
<dd><p>The underlying raw stream (a <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> instance) that
<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> deals with.  This is not part of the
<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> API and may not exist on some implementations.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedIOBase.detach">
<code class="descname">detach</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedIOBase.detach" title="Permalink to this definition">¶</a></dt>
<dd><p>Separate the underlying raw stream from the buffer and return it.</p>
<p>After the raw stream has been detached, the buffer is in an unusable
state.</p>
<p>Some buffers, like <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a>, do not have the concept of a single
raw stream to return from this method.  They raise
<a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnsupportedOperation</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="io.BufferedIOBase.read">
<code class="descname">read</code><span class="sig-paren">(</span><em>n=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedIOBase.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return up to <em>n</em> bytes.  If the argument is omitted, <code class="docutils literal notranslate"><span class="pre">None</span></code>, or
negative, data is read and returned until EOF is reached.  An empty bytes
object is returned if the stream is already at EOF.</p>
<p>If the argument is positive, and the underlying raw stream is not
interactive, multiple raw reads may be issued to satisfy the byte count
(unless EOF is reached first).  But for interactive raw streams, at most
one raw read will be issued, and a short result does not imply that EOF is
imminent.</p>
<p>A <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> is raised if the underlying raw stream is in
non blocking-mode, and has no data available at the moment.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedIOBase.read1">
<code class="descname">read1</code><span class="sig-paren">(</span><em>n=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedIOBase.read1" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return up to <em>n</em> bytes, with at most one call to the underlying
raw stream’s <a class="reference internal" href="#io.RawIOBase.read" title="io.RawIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method.  This can be useful if you
are implementing your own buffering on top of a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>
object.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedIOBase.readinto">
<code class="descname">readinto</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedIOBase.readinto" title="Permalink to this definition">¶</a></dt>
<dd><p>Read up to len(b) bytes into <em>b</em>, and return the number of bytes read.
The object <em>b</em> should be a pre-allocated, writable array of bytes,
either <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> or <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.</p>
<p>Like <a class="reference internal" href="#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>, multiple reads may be issued to the underlying raw
stream, unless the latter is ‘interactive’.</p>
<p>A <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> is raised if the underlying raw stream is in
non blocking-mode, and has no data available at the moment.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedIOBase.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedIOBase.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write <em>b</em>, and return the number of bytes written
(always equal to <code class="docutils literal notranslate"><span class="pre">len(b)</span></code>, since if the write fails
an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> will be raised).  The object <em>b</em> should be
an array of bytes, either <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>,
or <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.  Depending on the actual
implementation, these bytes may be readily written to the underlying
stream, or held in a buffer for performance and latency reasons.</p>
<p>When in non-blocking mode, a <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> is raised if the
data needed to be written to the raw stream but it couldn’t accept
all the data without blocking.</p>
<p>The caller may release or mutate <em>b</em> after this method returns,
so the implementation should only access <em>b</em> during the method call.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="raw-file-i-o">
<h2>15.2.3. Raw File I/O<a class="headerlink" href="#raw-file-i-o" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="io.FileIO">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">FileIO</code><span class="sig-paren">(</span><em>name</em>, <em>mode='r'</em>, <em>closefd=True</em><span class="sig-paren">)</span><a class="headerlink" href="#io.FileIO" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a> represents an OS-level file containing bytes data.
It implements the <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> interface (and therefore the
<a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> interface, too).</p>
<p>The <em>name</em> can be one of two things:</p>
<ul class="simple">
<li>a string representing the path to the file which will be opened;</li>
<li>an integer representing the number of an existing OS-level file descriptor
to which the resulting <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a> object will give access.</li>
</ul>
<p>The <em>mode</em> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a'</span></code> for reading (default), writing,
or appending.  The file will be created if it doesn’t exist when opened for
writing or appending; it will be truncated when opened for writing.  Add a
<code class="docutils literal notranslate"><span class="pre">'+'</span></code> to the mode to allow simultaneous reading and writing.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> (when called with a positive argument), <code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> methods on this class will only make one system call.</p>
<p>In addition to the attributes and methods from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a> and
<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a>, <a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a> provides the following data
attributes and methods:</p>
<dl class="attribute">
<dt id="io.FileIO.mode">
<code class="descname">mode</code><a class="headerlink" href="#io.FileIO.mode" title="Permalink to this definition">¶</a></dt>
<dd><p>The mode as given in the constructor.</p>
</dd></dl>

<dl class="attribute">
<dt id="io.FileIO.name">
<code class="descname">name</code><a class="headerlink" href="#io.FileIO.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The file name.  This is the file descriptor of the file when no name is
given in the constructor.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="buffered-streams">
<h2>15.2.4. Buffered Streams<a class="headerlink" href="#buffered-streams" title="Permalink to this headline">¶</a></h2>
<p>Buffered I/O streams provide a higher-level interface to an I/O device
than raw I/O does.</p>
<dl class="class">
<dt id="io.BytesIO">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BytesIO</code><span class="sig-paren">(</span><span class="optional">[</span><em>initial_bytes</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BytesIO" title="Permalink to this definition">¶</a></dt>
<dd><p>A stream implementation using an in-memory bytes buffer.  It inherits
<a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>.</p>
<p>The optional argument <em>initial_bytes</em> is a <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> object that
contains initial data.</p>
<p><a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a> provides or overrides these methods in addition to those
from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>:</p>
<dl class="method">
<dt id="io.BytesIO.getvalue">
<code class="descname">getvalue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BytesIO.getvalue" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">bytes</span></code> containing the entire contents of the buffer.</p>
</dd></dl>

<dl class="method">
<dt id="io.BytesIO.read1">
<code class="descname">read1</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BytesIO.read1" title="Permalink to this definition">¶</a></dt>
<dd><p>In <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a>, this is the same as <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.BufferedReader">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BufferedReader</code><span class="sig-paren">(</span><em>raw</em>, <em>buffer_size=DEFAULT_BUFFER_SIZE</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedReader" title="Permalink to this definition">¶</a></dt>
<dd><p>A buffer providing higher-level access to a readable, sequential
<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> object.  It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>.
When reading data from this object, a larger amount of data may be
requested from the underlying raw stream, and kept in an internal buffer.
The buffered data can then be returned directly on subsequent reads.</p>
<p>The constructor creates a <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a> for the given readable
<em>raw</em> stream and <em>buffer_size</em>.  If <em>buffer_size</em> is omitted,
<a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT_BUFFER_SIZE</span></code></a> is used.</p>
<p><a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a> provides or overrides these methods in addition to
those from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>:</p>
<dl class="method">
<dt id="io.BufferedReader.peek">
<code class="descname">peek</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedReader.peek" title="Permalink to this definition">¶</a></dt>
<dd><p>Return bytes from the stream without advancing the position.  At most one
single read on the raw stream is done to satisfy the call. The number of
bytes returned may be less or more than requested.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedReader.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>n</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedReader.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return <em>n</em> bytes, or if <em>n</em> is not given or negative, until EOF
or if the read call would block in non-blocking mode.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedReader.read1">
<code class="descname">read1</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedReader.read1" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return up to <em>n</em> bytes with only one call on the raw stream.  If
at least one byte is buffered, only buffered bytes are returned.
Otherwise, one raw stream read call is made.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.BufferedWriter">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BufferedWriter</code><span class="sig-paren">(</span><em>raw</em>, <em>buffer_size=DEFAULT_BUFFER_SIZE</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>A buffer providing higher-level access to a writeable, sequential
<a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> object.  It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>.
When writing to this object, data is normally held into an internal
buffer.  The buffer will be written out to the underlying <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a>
object under various conditions, including:</p>
<ul class="simple">
<li>when the buffer gets too small for all pending data;</li>
<li>when <a class="reference internal" href="#io.BufferedWriter.flush" title="io.BufferedWriter.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> is called;</li>
<li>when a <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code> is requested (for <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> objects);</li>
<li>when the <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a> object is closed or destroyed.</li>
</ul>
<p>The constructor creates a <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a> for the given writeable
<em>raw</em> stream.  If the <em>buffer_size</em> is not given, it defaults to
<a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT_BUFFER_SIZE</span></code></a>.</p>
<p>A third argument, <em>max_buffer_size</em>, is supported, but unused and deprecated.</p>
<p><a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a> provides or overrides these methods in addition to
those from <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> and <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>:</p>
<dl class="method">
<dt id="io.BufferedWriter.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedWriter.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Force bytes held in the buffer into the raw stream.  A
<a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> should be raised if the raw stream blocks.</p>
</dd></dl>

<dl class="method">
<dt id="io.BufferedWriter.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedWriter.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write <em>b</em>, and return the number of bytes written.
The object <em>b</em> should be an array of bytes, either
<code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, or <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.
When in non-blocking mode, a <a class="reference internal" href="#io.BlockingIOError" title="io.BlockingIOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BlockingIOError</span></code></a> is raised
if the buffer needs to be written out but the raw stream blocks.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.BufferedRandom">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BufferedRandom</code><span class="sig-paren">(</span><em>raw</em>, <em>buffer_size=DEFAULT_BUFFER_SIZE</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedRandom" title="Permalink to this definition">¶</a></dt>
<dd><p>A buffered interface to random access streams.  It inherits
<a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a> and <a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a>, and further supports
<code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code> functionality.</p>
<p>The constructor creates a reader and writer for a seekable raw stream, given
in the first argument.  If the <em>buffer_size</em> is omitted it defaults to
<a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT_BUFFER_SIZE</span></code></a>.</p>
<p>A third argument, <em>max_buffer_size</em>, is supported, but unused and deprecated.</p>
<p><a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> is capable of anything <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a> or
<a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a> can do.</p>
</dd></dl>

<dl class="class">
<dt id="io.BufferedRWPair">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">BufferedRWPair</code><span class="sig-paren">(</span><em>reader</em>, <em>writer</em>, <em>buffer_size=DEFAULT_BUFFER_SIZE</em><span class="sig-paren">)</span><a class="headerlink" href="#io.BufferedRWPair" title="Permalink to this definition">¶</a></dt>
<dd><p>A buffered I/O object combining two unidirectional <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a>
objects – one readable, the other writeable – into a single bidirectional
endpoint.  It inherits <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>.</p>
<p><em>reader</em> and <em>writer</em> are <a class="reference internal" href="#io.RawIOBase" title="io.RawIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code></a> objects that are readable and
writeable respectively.  If the <em>buffer_size</em> is omitted it defaults to
<a class="reference internal" href="#io.DEFAULT_BUFFER_SIZE" title="io.DEFAULT_BUFFER_SIZE"><code class="xref py py-data docutils literal notranslate"><span class="pre">DEFAULT_BUFFER_SIZE</span></code></a>.</p>
<p>A fourth argument, <em>max_buffer_size</em>, is supported, but unused and
deprecated.</p>
<p><a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code></a> implements all of <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a>’s methods
except for <a class="reference internal" href="#io.BufferedIOBase.detach" title="io.BufferedIOBase.detach"><code class="xref py py-meth docutils literal notranslate"><span class="pre">detach()</span></code></a>, which raises
<a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnsupportedOperation</span></code></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code></a> does not attempt to synchronize accesses to
its underlying raw streams.  You should not pass it the same object
as reader and writer; use <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> instead.</p>
</div>
</dd></dl>

</div>
<div class="section" id="text-i-o">
<h2>15.2.5. Text I/O<a class="headerlink" href="#text-i-o" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="io.TextIOBase">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">TextIOBase</code><a class="headerlink" href="#io.TextIOBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for text streams.  This class provides a unicode character
and line based interface to stream I/O.  There is no <code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>
method because Python’s <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> strings are immutable.
It inherits <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>.  There is no public constructor.</p>
<p><a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> provides or overrides these data attributes and
methods in addition to those from <a class="reference internal" href="#io.IOBase" title="io.IOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">IOBase</span></code></a>:</p>
<dl class="attribute">
<dt id="io.TextIOBase.encoding">
<code class="descname">encoding</code><a class="headerlink" href="#io.TextIOBase.encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the encoding used to decode the stream’s bytes into
strings, and to encode strings into bytes.</p>
</dd></dl>

<dl class="attribute">
<dt id="io.TextIOBase.errors">
<code class="descname">errors</code><a class="headerlink" href="#io.TextIOBase.errors" title="Permalink to this definition">¶</a></dt>
<dd><p>The error setting of the decoder or encoder.</p>
</dd></dl>

<dl class="attribute">
<dt id="io.TextIOBase.newlines">
<code class="descname">newlines</code><a class="headerlink" href="#io.TextIOBase.newlines" title="Permalink to this definition">¶</a></dt>
<dd><p>A string, a tuple of strings, or <code class="docutils literal notranslate"><span class="pre">None</span></code>, indicating the newlines
translated so far.  Depending on the implementation and the initial
constructor flags, this may not be available.</p>
</dd></dl>

<dl class="attribute">
<dt id="io.TextIOBase.buffer">
<code class="descname">buffer</code><a class="headerlink" href="#io.TextIOBase.buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>The underlying binary buffer (a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> instance) that
<a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> deals with.  This is not part of the
<a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> API and may not exist on some implementations.</p>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.detach">
<code class="descname">detach</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.detach" title="Permalink to this definition">¶</a></dt>
<dd><p>Separate the underlying binary buffer from the <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> and
return it.</p>
<p>After the underlying buffer has been detached, the <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> is
in an unusable state.</p>
<p>Some <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> implementations, like <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a>, may not
have the concept of an underlying buffer and calling this method will
raise <a class="reference internal" href="#io.UnsupportedOperation" title="io.UnsupportedOperation"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnsupportedOperation</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.read">
<code class="descname">read</code><span class="sig-paren">(</span><em>n=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read and return at most <em>n</em> characters from the stream as a single
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.  If <em>n</em> is negative or <code class="docutils literal notranslate"><span class="pre">None</span></code>, reads until EOF.</p>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><em>limit=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read until newline or EOF and return a single <code class="docutils literal notranslate"><span class="pre">unicode</span></code>.  If the
stream is already at EOF, an empty string is returned.</p>
<p>If <em>limit</em> is specified, at most <em>limit</em> characters will be read.</p>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.seek">
<code class="descname">seek</code><span class="sig-paren">(</span><em>offset</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the stream position to the given <em>offset</em>.  Behaviour depends on
the <em>whence</em> parameter.  The default value for <em>whence</em> is
<code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_SET</span></code>.</p>
<ul class="simple">
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_SET</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code>: seek from the start of the stream
(the default); <em>offset</em> must either be a number returned by
<a class="reference internal" href="#io.TextIOBase.tell" title="io.TextIOBase.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TextIOBase.tell()</span></code></a>, or zero.  Any other <em>offset</em> value
produces undefined behaviour.</li>
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_CUR</span></code> or <code class="docutils literal notranslate"><span class="pre">1</span></code>: “seek” to the current position;
<em>offset</em> must be zero, which is a no-operation (all other values
are unsupported).</li>
<li><code class="xref py py-data docutils literal notranslate"><span class="pre">SEEK_END</span></code> or <code class="docutils literal notranslate"><span class="pre">2</span></code>: seek to the end of the stream;
<em>offset</em> must be zero (all other values are unsupported).</li>
</ul>
<p>Return the new absolute position as an opaque number.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <code class="docutils literal notranslate"><span class="pre">SEEK_*</span></code> constants.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.tell">
<code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current stream position as an opaque number.  The number
does not usually represent a number of bytes in the underlying
binary storage.</p>
</dd></dl>

<dl class="method">
<dt id="io.TextIOBase.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOBase.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> string <em>s</em> to the stream and return the
number of characters written.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.TextIOWrapper">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">TextIOWrapper</code><span class="sig-paren">(</span><em>buffer</em>, <em>encoding=None</em>, <em>errors=None</em>, <em>newline=None</em>, <em>line_buffering=False</em><span class="sig-paren">)</span><a class="headerlink" href="#io.TextIOWrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>A buffered text stream over a <a class="reference internal" href="#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> binary stream.
It inherits <a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a>.</p>
<p><em>encoding</em> gives the name of the encoding that the stream will be decoded or
encoded with.  It defaults to <a class="reference internal" href="locale.html#locale.getpreferredencoding" title="locale.getpreferredencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.getpreferredencoding()</span></code></a>.</p>
<p><em>errors</em> is an optional string that specifies how encoding and decoding
errors are to be handled.  Pass <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> to raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
exception if there is an encoding error (the default of <code class="docutils literal notranslate"><span class="pre">None</span></code> has the same
effect), or pass <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> to ignore errors.  (Note that ignoring encoding
errors can lead to data loss.)  <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> causes a replacement marker
(such as <code class="docutils literal notranslate"><span class="pre">'?'</span></code>) to be inserted where there is malformed data.  When
writing, <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code> (replace with the appropriate XML character
reference) or <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> (replace with backslashed escape
sequences) can be used.  Any other error handling name that has been
registered with <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a> is also valid.</p>
<p id="index-1"><em>newline</em> controls how line endings are handled.  It can be <code class="docutils literal notranslate"><span class="pre">None</span></code>,
<code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>.  It works as follows:</p>
<ul class="simple">
<li>On input, if <em>newline</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode is
enabled.  Lines in the input can end in <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>,
and these are translated into <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> before being returned to the
caller.  If it is <code class="docutils literal notranslate"><span class="pre">''</span></code>, universal newlines mode is enabled, but line
endings are returned to the caller untranslated.  If it has any of the
other legal values, input lines are only terminated by the given string,
and the line ending is returned to the caller untranslated.</li>
<li>On output, if <em>newline</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, any <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> characters written are
translated to the system default line separator, <a class="reference internal" href="os.html#os.linesep" title="os.linesep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.linesep</span></code></a>.  If
<em>newline</em> is <code class="docutils literal notranslate"><span class="pre">''</span></code>, no translation takes place.  If <em>newline</em> is any of
the other legal values, any <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> characters written are translated to
the given string.</li>
</ul>
<p>If <em>line_buffering</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code> is implied when a call to
write contains a newline character or a carriage return.</p>
<p><a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a> provides one attribute in addition to those of
<a class="reference internal" href="#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a> and its parents:</p>
<dl class="attribute">
<dt id="io.TextIOWrapper.line_buffering">
<code class="descname">line_buffering</code><a class="headerlink" href="#io.TextIOWrapper.line_buffering" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether line buffering is enabled.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="io.StringIO">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">StringIO</code><span class="sig-paren">(</span><em>initial_value=u''</em>, <em>newline=u'\n'</em><span class="sig-paren">)</span><a class="headerlink" href="#io.StringIO" title="Permalink to this definition">¶</a></dt>
<dd><p>An in-memory stream for unicode text.  It inherits <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a>.</p>
<p>The initial value of the buffer can be set by providing <em>initial_value</em>.
If newline translation is enabled, newlines will be encoded as if by
<a class="reference internal" href="#io.TextIOBase.write" title="io.TextIOBase.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a>.  The stream is positioned at the start of
the buffer.</p>
<p>The <em>newline</em> argument works like that of <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a>.
The default is to consider only <code class="docutils literal notranslate"><span class="pre">\n</span></code> characters as ends of lines and
to do no newline translation.  If <em>newline</em> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code>,
newlines are written as <code class="docutils literal notranslate"><span class="pre">\n</span></code> on all platforms, but universal
newline decoding is still performed when reading.</p>
<p><a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> provides this method in addition to those from
<a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a> and its parents:</p>
<dl class="method">
<dt id="io.StringIO.getvalue">
<code class="descname">getvalue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#io.StringIO.getvalue" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <code class="docutils literal notranslate"><span class="pre">unicode</span></code> containing the entire contents of the buffer at any
time before the <a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method is
called.  Newlines are decoded as if by <a class="reference internal" href="#io.TextIOBase.read" title="io.TextIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>,
although the stream position is not changed.</p>
</dd></dl>

<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">io</span>

<span class="n">output</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
<span class="n">output</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;First line.</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">output</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;Second line.</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="c1"># Retrieve file contents -- this will be</span>
<span class="c1"># u&#39;First line.\nSecond line.\n&#39;</span>
<span class="n">contents</span> <span class="o">=</span> <span class="n">output</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>

<span class="c1"># Close object and discard memory buffer --</span>
<span class="c1"># .getvalue() will now raise an exception.</span>
<span class="n">output</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<span class="target" id="index-2"></span><dl class="class">
<dt id="io.IncrementalNewlineDecoder">
<em class="property">class </em><code class="descclassname">io.</code><code class="descname">IncrementalNewlineDecoder</code><a class="headerlink" href="#io.IncrementalNewlineDecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>A helper codec that decodes newlines for <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode.
It inherits <a class="reference internal" href="codecs.html#codecs.IncrementalDecoder" title="codecs.IncrementalDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">codecs.IncrementalDecoder</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="advanced-topics">
<h2>15.2.6. Advanced topics<a class="headerlink" href="#advanced-topics" title="Permalink to this headline">¶</a></h2>
<p>Here we will discuss several advanced topics pertaining to the concrete
I/O implementations described above.</p>
<div class="section" id="performance">
<h3>15.2.6.1. Performance<a class="headerlink" href="#performance" title="Permalink to this headline">¶</a></h3>
<div class="section" id="binary-i-o">
<h4>15.2.6.1.1. Binary I/O<a class="headerlink" href="#binary-i-o" title="Permalink to this headline">¶</a></h4>
<p>By reading and writing only large chunks of data even when the user asks
for a single byte, buffered I/O is designed to hide any inefficiency in
calling and executing the operating system’s unbuffered I/O routines.  The
gain will vary very much depending on the OS and the kind of I/O which is
performed (for example, on some contemporary OSes such as Linux, unbuffered
disk I/O can be as fast as buffered I/O).  The bottom line, however, is
that buffered I/O will offer you predictable performance regardless of the
platform and the backing device.  Therefore, it is most always preferable to
use buffered I/O rather than unbuffered I/O.</p>
</div>
<div class="section" id="id1">
<h4>15.2.6.1.2. Text I/O<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h4>
<p>Text I/O over a binary storage (such as a file) is significantly slower than
binary I/O over the same storage, because it implies conversions from
unicode to binary data using a character codec.  This can become noticeable
if you handle huge amounts of text data (for example very large log files).
Also, <code class="xref py py-meth docutils literal notranslate"><span class="pre">TextIOWrapper.tell()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">TextIOWrapper.seek()</span></code> are both
quite slow due to the reconstruction algorithm used.</p>
<p><a class="reference internal" href="#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a>, however, is a native in-memory unicode container and will
exhibit similar speed to <a class="reference internal" href="#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code></a>.</p>
</div>
</div>
<div class="section" id="multi-threading">
<h3>15.2.6.2. Multi-threading<a class="headerlink" href="#multi-threading" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileIO</span></code></a> objects are thread-safe to the extent that the operating
system calls (such as <code class="docutils literal notranslate"><span class="pre">read(2)</span></code> under Unix) they are wrapping are thread-safe
too.</p>
<p>Binary buffered objects (instances of <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a>,
<a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a>, <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code></a>)
protect their internal structures using a lock; it is therefore safe to call
them from multiple threads at once.</p>
<p><a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a> objects are not thread-safe.</p>
</div>
<div class="section" id="reentrancy">
<h3>15.2.6.3. Reentrancy<a class="headerlink" href="#reentrancy" title="Permalink to this headline">¶</a></h3>
<p>Binary buffered objects (instances of <a class="reference internal" href="#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code></a>,
<a class="reference internal" href="#io.BufferedWriter" title="io.BufferedWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code></a>, <a class="reference internal" href="#io.BufferedRandom" title="io.BufferedRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code></a> and <a class="reference internal" href="#io.BufferedRWPair" title="io.BufferedRWPair"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code></a>)
are not reentrant.  While reentrant calls will not happen in normal situations,
they can arise if you are doing I/O in a <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> handler.  If it is
attempted to enter a buffered object again while already being accessed
<em>from the same thread</em>, then a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<p>The above implicitly extends to text files, since the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
function will wrap a buffered object inside a <a class="reference internal" href="#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code></a>.  This
includes standard streams and therefore affects the built-in function
<a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> as well.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a><ul>
<li><a class="reference internal" href="#module-interface">15.2.1. Module Interface</a></li>
<li><a class="reference internal" href="#i-o-base-classes">15.2.2. I/O Base Classes</a></li>
<li><a class="reference internal" href="#raw-file-i-o">15.2.3. Raw File I/O</a></li>
<li><a class="reference internal" href="#buffered-streams">15.2.4. Buffered Streams</a></li>
<li><a class="reference internal" href="#text-i-o">15.2.5. Text I/O</a></li>
<li><a class="reference internal" href="#advanced-topics">15.2.6. Advanced topics</a><ul>
<li><a class="reference internal" href="#performance">15.2.6.1. Performance</a><ul>
<li><a class="reference internal" href="#binary-i-o">15.2.6.1.1. Binary I/O</a></li>
<li><a class="reference internal" href="#id1">15.2.6.1.2. Text I/O</a></li>
</ul>
</li>
<li><a class="reference internal" href="#multi-threading">15.2.6.2. Multi-threading</a></li>
<li><a class="reference internal" href="#reentrancy">15.2.6.3. Reentrancy</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="os.html"
                        title="previous chapter">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="time.html"
                        title="next chapter">15.3. <code class="docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/io.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="time.html" title="15.3. time — Time access and conversions"
             >next</a> |</li>
        <li class="right" >
          <a href="os.html" title="15.1. os — Miscellaneous operating system interfaces"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���G�@�@html/library/ipc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17. Interprocess Communication and Networking &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.1. subprocess — Subprocess management" href="subprocess.html" />
    <link rel="prev" title="16.9. rlcompleter — Completion function for GNU readline" href="rlcompleter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ipc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="subprocess.html" title="17.1. subprocess — Subprocess management"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="rlcompleter.html" title="16.9. rlcompleter — Completion function for GNU readline"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="interprocess-communication-and-networking">
<span id="ipc"></span><h1>17. Interprocess Communication and Networking<a class="headerlink" href="#interprocess-communication-and-networking" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide mechanisms for different processes
to communicate.</p>
<p>Some modules only work for two processes that are on the same machine, e.g.
<a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> and <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>.  Other modules support networking protocols
that two or more processes can use to communicate across machines.</p>
<p>The list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="subprocess.html">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a><ul>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html#using-the-subprocess-module">17.1.1. Using the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#frequently-used-arguments">17.1.1.1. Frequently Used Arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#popen-constructor">17.1.1.2. Popen Constructor</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#exceptions">17.1.1.3. Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#security">17.1.1.4. Security</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html#popen-objects">17.1.2. Popen Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html#windows-popen-helpers">17.1.3. Windows Popen Helpers</a><ul>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#constants">17.1.3.1. Constants</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html#replacing-older-functions-with-the-subprocess-module">17.1.4. Replacing Older Functions with the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-bin-sh-shell-backquote">17.1.4.1. Replacing /bin/sh shell backquote</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-shell-pipeline">17.1.4.2. Replacing shell pipeline</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-os-system">17.1.4.3. Replacing <code class="docutils literal notranslate"><span class="pre">os.system()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-the-os-spawn-family">17.1.4.4. Replacing the <code class="docutils literal notranslate"><span class="pre">os.spawn</span></code> family</a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-os-popen-os-popen2-os-popen3">17.1.4.5. Replacing <code class="docutils literal notranslate"><span class="pre">os.popen()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen2()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen3()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#replacing-functions-from-the-popen2-module">17.1.4.6. Replacing functions from the <code class="docutils literal notranslate"><span class="pre">popen2</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="subprocess.html#notes">17.1.5. Notes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="subprocess.html#converting-an-argument-sequence-to-a-string-on-windows">17.1.5.1. Converting an argument sequence to a string on Windows</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="socket.html">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a><ul>
<li class="toctree-l2"><a class="reference internal" href="socket.html#socket-objects">17.2.1. Socket Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="socket.html#example">17.2.2. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="ssl.html">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#functions-constants-and-exceptions">17.3.1. Functions, Constants, and Exceptions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#socket-creation">17.3.1.1. Socket creation</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#context-creation">17.3.1.2. Context creation</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#random-generation">17.3.1.3. Random generation</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#certificate-handling">17.3.1.4. Certificate handling</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#constants">17.3.1.5. Constants</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#ssl-sockets">17.3.2. SSL Sockets</a></li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#ssl-contexts">17.3.3. SSL Contexts</a></li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#certificates">17.3.4. Certificates</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#certificate-chains">17.3.4.1. Certificate chains</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#ca-certificates">17.3.4.2. CA certificates</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#combined-key-and-certificate">17.3.4.3. Combined key and certificate</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#self-signed-certificates">17.3.4.4. Self-signed certificates</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#examples">17.3.5. Examples</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#testing-for-ssl-support">17.3.5.1. Testing for SSL support</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#client-side-operation">17.3.5.2. Client-side operation</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#server-side-operation">17.3.5.3. Server-side operation</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#notes-on-non-blocking-sockets">17.3.6. Notes on non-blocking sockets</a></li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#security-considerations">17.3.7. Security considerations</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#best-defaults">17.3.7.1. Best defaults</a></li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#manual-settings">17.3.7.2. Manual settings</a><ul>
<li class="toctree-l4"><a class="reference internal" href="ssl.html#verifying-certificates">17.3.7.2.1. Verifying certificates</a></li>
<li class="toctree-l4"><a class="reference internal" href="ssl.html#protocol-versions">17.3.7.2.2. Protocol versions</a></li>
<li class="toctree-l4"><a class="reference internal" href="ssl.html#cipher-selection">17.3.7.2.3. Cipher selection</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="ssl.html#multi-processing">17.3.7.3. Multi-processing</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ssl.html#libressl-support">17.3.8. LibreSSL support</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="signal.html">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a><ul>
<li class="toctree-l2"><a class="reference internal" href="signal.html#example">17.4.1. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="popen2.html">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a><ul>
<li class="toctree-l2"><a class="reference internal" href="popen2.html#popen3-and-popen4-objects">17.5.1. Popen3 and Popen4 Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="popen2.html#flow-control-issues">17.5.2. Flow Control Issues</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="asyncore.html">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a><ul>
<li class="toctree-l2"><a class="reference internal" href="asyncore.html#asyncore-example-basic-http-client">17.6.1. asyncore Example basic HTTP client</a></li>
<li class="toctree-l2"><a class="reference internal" href="asyncore.html#asyncore-example-basic-echo-server">17.6.2. asyncore Example basic echo server</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="asynchat.html">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a><ul>
<li class="toctree-l2"><a class="reference internal" href="asynchat.html#asynchat-auxiliary-classes">17.7.1. asynchat - Auxiliary Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="asynchat.html#asynchat-example">17.7.2. asynchat Example</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="rlcompleter.html"
                        title="previous chapter">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="subprocess.html"
                        title="next chapter">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ipc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="subprocess.html" title="17.1. subprocess — Subprocess management"
             >next</a> |</li>
        <li class="right" >
          <a href="rlcompleter.html" title="16.9. rlcompleter — Completion function for GNU readline"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\g�]�����html/library/itertools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.7. itertools — Functions creating iterators for efficient looping &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.8. functools — Higher-order functions and operations on callable objects" href="functools.html" />
    <link rel="prev" title="9.6. random — Generate pseudo-random numbers" href="random.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/itertools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functools.html" title="9.8. functools — Higher-order functions and operations on callable objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="random.html" title="9.6. random — Generate pseudo-random numbers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-itertools">
<span id="itertools-functions-creating-iterators-for-efficient-looping"></span><h1>9.7. <a class="reference internal" href="#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> — Functions creating iterators for efficient looping<a class="headerlink" href="#module-itertools" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module implements a number of <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> building blocks inspired
by constructs from APL, Haskell, and SML.  Each has been recast in a form
suitable for Python.</p>
<p>The module standardizes a core set of fast, memory efficient tools that are
useful by themselves or in combination.  Together, they form an “iterator
algebra” making it possible to construct specialized tools succinctly and
efficiently in pure Python.</p>
<p>For instance, SML provides a tabulation tool: <code class="docutils literal notranslate"><span class="pre">tabulate(f)</span></code> which produces a
sequence <code class="docutils literal notranslate"><span class="pre">f(0),</span> <span class="pre">f(1),</span> <span class="pre">...</span></code>.  The same effect can be achieved in Python
by combining <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> and <a class="reference internal" href="#itertools.count" title="itertools.count"><code class="xref py py-func docutils literal notranslate"><span class="pre">count()</span></code></a> to form <code class="docutils literal notranslate"><span class="pre">imap(f,</span> <span class="pre">count())</span></code>.</p>
<p>These tools and their built-in counterparts also work well with the high-speed
functions in the <a class="reference internal" href="operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module.  For example, the multiplication
operator can be mapped across two vectors to form an efficient dot-product:
<code class="docutils literal notranslate"><span class="pre">sum(imap(operator.mul,</span> <span class="pre">vector1,</span> <span class="pre">vector2))</span></code>.</p>
<p><strong>Infinite Iterators:</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="14%" />
<col width="39%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Iterator</th>
<th class="head">Arguments</th>
<th class="head">Results</th>
<th class="head">Example</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#itertools.count" title="itertools.count"><code class="xref py py-func docutils literal notranslate"><span class="pre">count()</span></code></a></td>
<td>start, [step]</td>
<td>start, start+step, start+2*step, …</td>
<td><code class="docutils literal notranslate"><span class="pre">count(10)</span> <span class="pre">--&gt;</span> <span class="pre">10</span> <span class="pre">11</span> <span class="pre">12</span> <span class="pre">13</span> <span class="pre">14</span> <span class="pre">...</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.cycle" title="itertools.cycle"><code class="xref py py-func docutils literal notranslate"><span class="pre">cycle()</span></code></a></td>
<td>p</td>
<td>p0, p1, … plast, p0, p1, …</td>
<td><code class="docutils literal notranslate"><span class="pre">cycle('ABCD')</span> <span class="pre">--&gt;</span> <span class="pre">A</span> <span class="pre">B</span> <span class="pre">C</span> <span class="pre">D</span> <span class="pre">A</span> <span class="pre">B</span> <span class="pre">C</span> <span class="pre">D</span> <span class="pre">...</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.repeat" title="itertools.repeat"><code class="xref py py-func docutils literal notranslate"><span class="pre">repeat()</span></code></a></td>
<td>elem [,n]</td>
<td>elem, elem, elem, … endlessly or up to n times</td>
<td><code class="docutils literal notranslate"><span class="pre">repeat(10,</span> <span class="pre">3)</span> <span class="pre">--&gt;</span> <span class="pre">10</span> <span class="pre">10</span> <span class="pre">10</span></code></td>
</tr>
</tbody>
</table>
<p><strong>Iterators terminating on the shortest input sequence:</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="18%" />
<col width="31%" />
<col width="39%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Iterator</th>
<th class="head">Arguments</th>
<th class="head">Results</th>
<th class="head">Example</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#itertools.chain" title="itertools.chain"><code class="xref py py-func docutils literal notranslate"><span class="pre">chain()</span></code></a></td>
<td>p, q, …</td>
<td>p0, p1, … plast, q0, q1, …</td>
<td><code class="docutils literal notranslate"><span class="pre">chain('ABC',</span> <span class="pre">'DEF')</span> <span class="pre">--&gt;</span> <span class="pre">A</span> <span class="pre">B</span> <span class="pre">C</span> <span class="pre">D</span> <span class="pre">E</span> <span class="pre">F</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.compress" title="itertools.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a></td>
<td>data, selectors</td>
<td>(d[0] if s[0]), (d[1] if s[1]), …</td>
<td><code class="docutils literal notranslate"><span class="pre">compress('ABCDEF',</span> <span class="pre">[1,0,1,0,1,1])</span> <span class="pre">--&gt;</span> <span class="pre">A</span> <span class="pre">C</span> <span class="pre">E</span> <span class="pre">F</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.dropwhile" title="itertools.dropwhile"><code class="xref py py-func docutils literal notranslate"><span class="pre">dropwhile()</span></code></a></td>
<td>pred, seq</td>
<td>seq[n], seq[n+1], starting when pred fails</td>
<td><code class="docutils literal notranslate"><span class="pre">dropwhile(lambda</span> <span class="pre">x:</span> <span class="pre">x&lt;5,</span> <span class="pre">[1,4,6,4,1])</span> <span class="pre">--&gt;</span> <span class="pre">6</span> <span class="pre">4</span> <span class="pre">1</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a></td>
<td>iterable[, keyfunc]</td>
<td>sub-iterators grouped by value of keyfunc(v)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">ifilter()</span></code></a></td>
<td>pred, seq</td>
<td>elements of seq where pred(elem) is true</td>
<td><code class="docutils literal notranslate"><span class="pre">ifilter(lambda</span> <span class="pre">x:</span> <span class="pre">x%2,</span> <span class="pre">range(10))</span> <span class="pre">--&gt;</span> <span class="pre">1</span> <span class="pre">3</span> <span class="pre">5</span> <span class="pre">7</span> <span class="pre">9</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.ifilterfalse" title="itertools.ifilterfalse"><code class="xref py py-func docutils literal notranslate"><span class="pre">ifilterfalse()</span></code></a></td>
<td>pred, seq</td>
<td>elements of seq where pred(elem) is false</td>
<td><code class="docutils literal notranslate"><span class="pre">ifilterfalse(lambda</span> <span class="pre">x:</span> <span class="pre">x%2,</span> <span class="pre">range(10))</span> <span class="pre">--&gt;</span> <span class="pre">0</span> <span class="pre">2</span> <span class="pre">4</span> <span class="pre">6</span> <span class="pre">8</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">islice()</span></code></a></td>
<td>seq, [start,] stop [, step]</td>
<td>elements from seq[start:stop:step]</td>
<td><code class="docutils literal notranslate"><span class="pre">islice('ABCDEFG',</span> <span class="pre">2,</span> <span class="pre">None)</span> <span class="pre">--&gt;</span> <span class="pre">C</span> <span class="pre">D</span> <span class="pre">E</span> <span class="pre">F</span> <span class="pre">G</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a></td>
<td>func, p, q, …</td>
<td>func(p0, q0), func(p1, q1), …</td>
<td><code class="docutils literal notranslate"><span class="pre">imap(pow,</span> <span class="pre">(2,3,10),</span> <span class="pre">(5,2,3))</span> <span class="pre">--&gt;</span> <span class="pre">32</span> <span class="pre">9</span> <span class="pre">1000</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.starmap" title="itertools.starmap"><code class="xref py py-func docutils literal notranslate"><span class="pre">starmap()</span></code></a></td>
<td>func, seq</td>
<td>func(*seq[0]), func(*seq[1]), …</td>
<td><code class="docutils literal notranslate"><span class="pre">starmap(pow,</span> <span class="pre">[(2,5),</span> <span class="pre">(3,2),</span> <span class="pre">(10,3)])</span> <span class="pre">--&gt;</span> <span class="pre">32</span> <span class="pre">9</span> <span class="pre">1000</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.tee" title="itertools.tee"><code class="xref py py-func docutils literal notranslate"><span class="pre">tee()</span></code></a></td>
<td>it, n</td>
<td>it1, it2, … itn  splits one iterator into n</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.takewhile" title="itertools.takewhile"><code class="xref py py-func docutils literal notranslate"><span class="pre">takewhile()</span></code></a></td>
<td>pred, seq</td>
<td>seq[0], seq[1], until pred fails</td>
<td><code class="docutils literal notranslate"><span class="pre">takewhile(lambda</span> <span class="pre">x:</span> <span class="pre">x&lt;5,</span> <span class="pre">[1,4,6,4,1])</span> <span class="pre">--&gt;</span> <span class="pre">1</span> <span class="pre">4</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip()</span></code></a></td>
<td>p, q, …</td>
<td>(p[0], q[0]), (p[1], q[1]), …</td>
<td><code class="docutils literal notranslate"><span class="pre">izip('ABCD',</span> <span class="pre">'xy')</span> <span class="pre">--&gt;</span> <span class="pre">Ax</span> <span class="pre">By</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.izip_longest" title="itertools.izip_longest"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip_longest()</span></code></a></td>
<td>p, q, …</td>
<td>(p[0], q[0]), (p[1], q[1]), …</td>
<td><code class="docutils literal notranslate"><span class="pre">izip_longest('ABCD',</span> <span class="pre">'xy',</span> <span class="pre">fillvalue='-')</span> <span class="pre">--&gt;</span> <span class="pre">Ax</span> <span class="pre">By</span> <span class="pre">C-</span> <span class="pre">D-</span></code></td>
</tr>
</tbody>
</table>
<p><strong>Combinatoric generators:</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="36%" />
<col width="16%" />
<col width="48%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Iterator</th>
<th class="head">Arguments</th>
<th class="head">Results</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#itertools.product" title="itertools.product"><code class="xref py py-func docutils literal notranslate"><span class="pre">product()</span></code></a></td>
<td>p, q, … [repeat=1]</td>
<td>cartesian product, equivalent to a nested for-loop</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.permutations" title="itertools.permutations"><code class="xref py py-func docutils literal notranslate"><span class="pre">permutations()</span></code></a></td>
<td>p[, r]</td>
<td>r-length tuples, all possible orderings, no repeated elements</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#itertools.combinations" title="itertools.combinations"><code class="xref py py-func docutils literal notranslate"><span class="pre">combinations()</span></code></a></td>
<td>p, r</td>
<td>r-length tuples, in sorted order, no repeated elements</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">combinations_with_replacement()</span></code></a></td>
<td>p, r</td>
<td>r-length tuples, in sorted order, with repeated elements</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">product('ABCD',</span> <span class="pre">repeat=2)</span></code></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">AA</span> <span class="pre">AB</span> <span class="pre">AC</span> <span class="pre">AD</span> <span class="pre">BA</span> <span class="pre">BB</span> <span class="pre">BC</span> <span class="pre">BD</span> <span class="pre">CA</span> <span class="pre">CB</span> <span class="pre">CC</span> <span class="pre">CD</span> <span class="pre">DA</span> <span class="pre">DB</span> <span class="pre">DC</span> <span class="pre">DD</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">permutations('ABCD',</span> <span class="pre">2)</span></code></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">AB</span> <span class="pre">AC</span> <span class="pre">AD</span> <span class="pre">BA</span> <span class="pre">BC</span> <span class="pre">BD</span> <span class="pre">CA</span> <span class="pre">CB</span> <span class="pre">CD</span> <span class="pre">DA</span> <span class="pre">DB</span> <span class="pre">DC</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">combinations('ABCD',</span> <span class="pre">2)</span></code></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">AB</span> <span class="pre">AC</span> <span class="pre">AD</span> <span class="pre">BC</span> <span class="pre">BD</span> <span class="pre">CD</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">combinations_with_replacement('ABCD',</span> <span class="pre">2)</span></code></td>
<td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">AA</span> <span class="pre">AB</span> <span class="pre">AC</span> <span class="pre">AD</span> <span class="pre">BB</span> <span class="pre">BC</span> <span class="pre">BD</span> <span class="pre">CC</span> <span class="pre">CD</span> <span class="pre">DD</span></code></td>
</tr>
</tbody>
</table>
<div class="section" id="itertool-functions">
<span id="itertools-functions"></span><h2>9.7.1. Itertool functions<a class="headerlink" href="#itertool-functions" title="Permalink to this headline">¶</a></h2>
<p>The following module functions all construct and return iterators. Some provide
streams of infinite length, so they should only be accessed by functions or
loops that truncate the stream.</p>
<dl class="function">
<dt id="itertools.chain">
<code class="descclassname">itertools.</code><code class="descname">chain</code><span class="sig-paren">(</span><em>*iterables</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.chain" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that returns elements from the first iterable until it is
exhausted, then proceeds to the next iterable, until all of the iterables are
exhausted.  Used for treating consecutive sequences as a single sequence.
Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">chain</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
    <span class="c1"># chain(&#39;ABC&#39;, &#39;DEF&#39;) --&gt; A B C D E F</span>
    <span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">iterables</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">element</span>
</pre></div>
</div>
</dd></dl>

<dl class="classmethod">
<dt id="itertools.chain.from_iterable">
<em class="property">classmethod </em><code class="descclassname">chain.</code><code class="descname">from_iterable</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.chain.from_iterable" title="Permalink to this definition">¶</a></dt>
<dd><p>Alternate constructor for <a class="reference internal" href="#itertools.chain" title="itertools.chain"><code class="xref py py-func docutils literal notranslate"><span class="pre">chain()</span></code></a>.  Gets chained inputs from a
single iterable argument that is evaluated lazily.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">from_iterable</span><span class="p">(</span><span class="n">iterables</span><span class="p">):</span>
    <span class="c1"># chain.from_iterable([&#39;ABC&#39;, &#39;DEF&#39;]) --&gt; A B C D E F</span>
    <span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">iterables</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">element</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.combinations">
<code class="descclassname">itertools.</code><code class="descname">combinations</code><span class="sig-paren">(</span><em>iterable</em>, <em>r</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.combinations" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>r</em> length subsequences of elements from the input <em>iterable</em>.</p>
<p>Combinations are emitted in lexicographic sort order.  So, if the
input <em>iterable</em> is sorted, the combination tuples will be produced
in sorted order.</p>
<p>Elements are treated as unique based on their position, not on their
value.  So if the input elements are unique, there will be no repeat
values in each combination.</p>
<p>Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">combinations</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="c1"># combinations(&#39;ABCD&#39;, 2) --&gt; AB AC AD BC BD CD</span>
    <span class="c1"># combinations(range(4), 3) --&gt; 012 013 023 123</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">r</span> <span class="o">&gt;</span> <span class="n">n</span><span class="p">:</span>
        <span class="k">return</span>
    <span class="n">indices</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="n">r</span><span class="p">)</span>
    <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">r</span><span class="p">)):</span>
            <span class="k">if</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">!=</span> <span class="n">i</span> <span class="o">+</span> <span class="n">n</span> <span class="o">-</span> <span class="n">r</span><span class="p">:</span>
                <span class="k">break</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span>
        <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
            <span class="n">indices</span><span class="p">[</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">indices</span><span class="p">[</span><span class="n">j</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
</pre></div>
</div>
<p>The code for <a class="reference internal" href="#itertools.combinations" title="itertools.combinations"><code class="xref py py-func docutils literal notranslate"><span class="pre">combinations()</span></code></a> can be also expressed as a subsequence
of <a class="reference internal" href="#itertools.permutations" title="itertools.permutations"><code class="xref py py-func docutils literal notranslate"><span class="pre">permutations()</span></code></a> after filtering entries where the elements are not
in sorted order (according to their position in the input pool):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">combinations</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">indices</span> <span class="ow">in</span> <span class="n">permutations</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">),</span> <span class="n">r</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">indices</span><span class="p">)</span> <span class="o">==</span> <span class="nb">list</span><span class="p">(</span><span class="n">indices</span><span class="p">):</span>
            <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
</pre></div>
</div>
<p>The number of items returned is <code class="docutils literal notranslate"><span class="pre">n!</span> <span class="pre">/</span> <span class="pre">r!</span> <span class="pre">/</span> <span class="pre">(n-r)!</span></code> when <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">r</span> <span class="pre">&lt;=</span> <span class="pre">n</span></code>
or zero when <code class="docutils literal notranslate"><span class="pre">r</span> <span class="pre">&gt;</span> <span class="pre">n</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.combinations_with_replacement">
<code class="descclassname">itertools.</code><code class="descname">combinations_with_replacement</code><span class="sig-paren">(</span><em>iterable</em>, <em>r</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.combinations_with_replacement" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>r</em> length subsequences of elements from the input <em>iterable</em>
allowing individual elements to be repeated more than once.</p>
<p>Combinations are emitted in lexicographic sort order.  So, if the
input <em>iterable</em> is sorted, the combination tuples will be produced
in sorted order.</p>
<p>Elements are treated as unique based on their position, not on their
value.  So if the input elements are unique, the generated combinations
will also be unique.</p>
<p>Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">combinations_with_replacement</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="c1"># combinations_with_replacement(&#39;ABC&#39;, 2) --&gt; AA AB AC BB BC CC</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">n</span> <span class="ow">and</span> <span class="n">r</span><span class="p">:</span>
        <span class="k">return</span>
    <span class="n">indices</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="n">r</span>
    <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">r</span><span class="p">)):</span>
            <span class="k">if</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">!=</span> <span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">:</span>
                <span class="k">break</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span>
        <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">:]</span> <span class="o">=</span> <span class="p">[</span><span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span><span class="p">]</span> <span class="o">*</span> <span class="p">(</span><span class="n">r</span> <span class="o">-</span> <span class="n">i</span><span class="p">)</span>
        <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
</pre></div>
</div>
<p>The code for <a class="reference internal" href="#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code class="xref py py-func docutils literal notranslate"><span class="pre">combinations_with_replacement()</span></code></a> can be also expressed as
a subsequence of <a class="reference internal" href="#itertools.product" title="itertools.product"><code class="xref py py-func docutils literal notranslate"><span class="pre">product()</span></code></a> after filtering entries where the elements
are not in sorted order (according to their position in the input pool):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">combinations_with_replacement</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">indices</span> <span class="ow">in</span> <span class="n">product</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">),</span> <span class="n">repeat</span><span class="o">=</span><span class="n">r</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">indices</span><span class="p">)</span> <span class="o">==</span> <span class="nb">list</span><span class="p">(</span><span class="n">indices</span><span class="p">):</span>
            <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
</pre></div>
</div>
<p>The number of items returned is <code class="docutils literal notranslate"><span class="pre">(n+r-1)!</span> <span class="pre">/</span> <span class="pre">r!</span> <span class="pre">/</span> <span class="pre">(n-1)!</span></code> when <code class="docutils literal notranslate"><span class="pre">n</span> <span class="pre">&gt;</span> <span class="pre">0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.compress">
<code class="descclassname">itertools.</code><code class="descname">compress</code><span class="sig-paren">(</span><em>data</em>, <em>selectors</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.compress" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that filters elements from <em>data</em> returning only those that
have a corresponding element in <em>selectors</em> that evaluates to <code class="docutils literal notranslate"><span class="pre">True</span></code>.
Stops when either the <em>data</em> or <em>selectors</em> iterables has been exhausted.
Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">compress</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">selectors</span><span class="p">):</span>
    <span class="c1"># compress(&#39;ABCDEF&#39;, [1,0,1,0,1,1]) --&gt; A C E F</span>
    <span class="k">return</span> <span class="p">(</span><span class="n">d</span> <span class="k">for</span> <span class="n">d</span><span class="p">,</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">izip</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">selectors</span><span class="p">)</span> <span class="k">if</span> <span class="n">s</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.count">
<code class="descclassname">itertools.</code><code class="descname">count</code><span class="sig-paren">(</span><em>start=0</em>, <em>step=1</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that returns evenly spaced values starting with <em>n</em>. Often
used as an argument to <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> to generate consecutive data points.
Also, used with <a class="reference internal" href="#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip()</span></code></a> to add sequence numbers.  Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">count</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">step</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
    <span class="c1"># count(10) --&gt; 10 11 12 13 14 ...</span>
    <span class="c1"># count(2.5, 0.5) -&gt; 2.5 3.0 3.5 ...</span>
    <span class="n">n</span> <span class="o">=</span> <span class="n">start</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">n</span>
        <span class="n">n</span> <span class="o">+=</span> <span class="n">step</span>
</pre></div>
</div>
<p>When counting with floating point numbers, better accuracy can sometimes be
achieved by substituting multiplicative code such as: <code class="docutils literal notranslate"><span class="pre">(start</span> <span class="pre">+</span> <span class="pre">step</span> <span class="pre">*</span> <span class="pre">i</span>
<span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">count())</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>added <em>step</em> argument and allowed non-integer arguments.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.cycle">
<code class="descclassname">itertools.</code><code class="descname">cycle</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.cycle" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator returning elements from the iterable and saving a copy of each.
When the iterable is exhausted, return elements from the saved copy.  Repeats
indefinitely.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">cycle</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># cycle(&#39;ABCD&#39;) --&gt; A B C D A B C D A B C D ...</span>
    <span class="n">saved</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">element</span>
        <span class="n">saved</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">saved</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">saved</span><span class="p">:</span>
              <span class="k">yield</span> <span class="n">element</span>
</pre></div>
</div>
<p>Note, this member of the toolkit may require significant auxiliary storage
(depending on the length of the iterable).</p>
</dd></dl>

<dl class="function">
<dt id="itertools.dropwhile">
<code class="descclassname">itertools.</code><code class="descname">dropwhile</code><span class="sig-paren">(</span><em>predicate</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.dropwhile" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that drops elements from the iterable as long as the predicate
is true; afterwards, returns every element.  Note, the iterator does not produce
<em>any</em> output until the predicate first becomes false, so it may have a lengthy
start-up time.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">dropwhile</span><span class="p">(</span><span class="n">predicate</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># dropwhile(lambda x: x&lt;5, [1,4,6,4,1]) --&gt; 6 4 1</span>
    <span class="n">iterable</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">predicate</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
            <span class="k">break</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.groupby">
<code class="descclassname">itertools.</code><code class="descname">groupby</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>key</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.groupby" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that returns consecutive keys and groups from the <em>iterable</em>.
The <em>key</em> is a function computing a key value for each element.  If not
specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>key</em> defaults to an identity function and returns
the element unchanged.  Generally, the iterable needs to already be sorted on
the same key function.</p>
<p>The operation of <a class="reference internal" href="#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a> is similar to the <code class="docutils literal notranslate"><span class="pre">uniq</span></code> filter in Unix.  It
generates a break or new group every time the value of the key function changes
(which is why it is usually necessary to have sorted the data using the same key
function).  That behavior differs from SQL’s GROUP BY which aggregates common
elements regardless of their input order.</p>
<p>The returned group is itself an iterator that shares the underlying iterable
with <a class="reference internal" href="#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a>.  Because the source is shared, when the <a class="reference internal" href="#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a>
object is advanced, the previous group is no longer visible.  So, if that data
is needed later, it should be stored as a list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">groups</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">uniquekeys</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">data</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">keyfunc</span><span class="p">)</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groupby</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="n">keyfunc</span><span class="p">):</span>
    <span class="n">groups</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">g</span><span class="p">))</span>      <span class="c1"># Store group iterator as a list</span>
    <span class="n">uniquekeys</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">k</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#itertools.groupby" title="itertools.groupby"><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code></a> is roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">groupby</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="c1"># [k for k, g in groupby(&#39;AAAABBBCCDAABBB&#39;)] --&gt; A B C D A B</span>
    <span class="c1"># [list(g) for k, g in groupby(&#39;AAAABBBCCD&#39;)] --&gt; AAAA BBB CC D</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">key</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">key</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">keyfunc</span> <span class="o">=</span> <span class="n">key</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tgtkey</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span> <span class="o">=</span> <span class="nb">object</span><span class="p">()</span>
    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>
    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">tgtkey</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">it</span><span class="p">)</span>    <span class="c1"># Exit on StopIteration</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keyfunc</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tgtkey</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span>
        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">currkey</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">_grouper</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">tgtkey</span><span class="p">))</span>
    <span class="k">def</span> <span class="nf">_grouper</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tgtkey</span><span class="p">):</span>
        <span class="k">while</span> <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span> <span class="o">==</span> <span class="n">tgtkey</span><span class="p">:</span>
            <span class="k">yield</span> <span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">it</span><span class="p">)</span>    <span class="c1"># Exit on StopIteration</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">currkey</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keyfunc</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">currvalue</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.ifilter">
<code class="descclassname">itertools.</code><code class="descname">ifilter</code><span class="sig-paren">(</span><em>predicate</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.ifilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that filters elements from iterable returning only those for
which the predicate is <code class="docutils literal notranslate"><span class="pre">True</span></code>. If <em>predicate</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, return the items
that are true. Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">ifilter</span><span class="p">(</span><span class="n">predicate</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># ifilter(lambda x: x%2, range(10)) --&gt; 1 3 5 7 9</span>
    <span class="k">if</span> <span class="n">predicate</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">predicate</span> <span class="o">=</span> <span class="nb">bool</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">predicate</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.ifilterfalse">
<code class="descclassname">itertools.</code><code class="descname">ifilterfalse</code><span class="sig-paren">(</span><em>predicate</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.ifilterfalse" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that filters elements from iterable returning only those for
which the predicate is <code class="docutils literal notranslate"><span class="pre">False</span></code>. If <em>predicate</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, return the items
that are false. Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">ifilterfalse</span><span class="p">(</span><span class="n">predicate</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># ifilterfalse(lambda x: x%2, range(10)) --&gt; 0 2 4 6 8</span>
    <span class="k">if</span> <span class="n">predicate</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">predicate</span> <span class="o">=</span> <span class="nb">bool</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">predicate</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.imap">
<code class="descclassname">itertools.</code><code class="descname">imap</code><span class="sig-paren">(</span><em>function</em>, <em>*iterables</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.imap" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that computes the function using arguments from each of the
iterables.  If <em>function</em> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code>, then <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> returns the
arguments as a tuple.  Like <a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> but stops when the shortest iterable is
exhausted instead of filling in <code class="docutils literal notranslate"><span class="pre">None</span></code> for shorter iterables.  The reason for
the difference is that infinite iterator arguments are typically an error for
<a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> (because the output is fully evaluated) but represent a common and
useful way of supplying arguments to <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a>. Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">imap</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
    <span class="c1"># imap(pow, (2,3,10), (5,2,3)) --&gt; 32 9 1000</span>
    <span class="n">iterables</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">iter</span><span class="p">,</span> <span class="n">iterables</span><span class="p">)</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span> <span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">iterables</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">function</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">function</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.islice">
<code class="descclassname">itertools.</code><code class="descname">islice</code><span class="sig-paren">(</span><em>iterable</em>, <em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.islice" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">itertools.</code><code class="descname">islice</code><span class="sig-paren">(</span><em>iterable</em>, <em>start</em>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Make an iterator that returns selected elements from the iterable. If <em>start</em> is
non-zero, then elements from the iterable are skipped until start is reached.
Afterward, elements are returned consecutively unless <em>step</em> is set higher than
one which results in items being skipped.  If <em>stop</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then iteration
continues until the iterator is exhausted, if at all; otherwise, it stops at the
specified position.  Unlike regular slicing, <a class="reference internal" href="#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">islice()</span></code></a> does not support
negative values for <em>start</em>, <em>stop</em>, or <em>step</em>.  Can be used to extract related
fields from data where the internal structure has been flattened (for example, a
multi-line report may list a name field on every third line).  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">islice</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="c1"># islice(&#39;ABCDEFG&#39;, 2) --&gt; A B</span>
    <span class="c1"># islice(&#39;ABCDEFG&#39;, 2, 4) --&gt; C D</span>
    <span class="c1"># islice(&#39;ABCDEFG&#39;, 2, None) --&gt; C D E F G</span>
    <span class="c1"># islice(&#39;ABCDEFG&#39;, 0, None, 2) --&gt; A C E G</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">slice</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
    <span class="n">start</span><span class="p">,</span> <span class="n">stop</span><span class="p">,</span> <span class="n">step</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">start</span> <span class="ow">or</span> <span class="mi">0</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">stop</span> <span class="ow">or</span> <span class="n">sys</span><span class="o">.</span><span class="n">maxint</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">step</span> <span class="ow">or</span> <span class="mi">1</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">stop</span><span class="p">,</span> <span class="n">step</span><span class="p">)))</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">nexti</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
        <span class="c1"># Consume *iterable* up to the *start* position.</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">izip</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="n">start</span><span class="p">),</span> <span class="n">iterable</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="k">return</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
            <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="n">nexti</span><span class="p">:</span>
                <span class="k">yield</span> <span class="n">element</span>
                <span class="n">nexti</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
        <span class="c1"># Consume to *stop*.</span>
        <span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">izip</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">stop</span><span class="p">),</span> <span class="n">iterable</span><span class="p">):</span>
            <span class="k">pass</span>
</pre></div>
</div>
<p>If <em>start</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then iteration starts at zero. If <em>step</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
then the step defaults to one.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>accept <code class="docutils literal notranslate"><span class="pre">None</span></code> values for default <em>start</em> and <em>step</em>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.izip">
<code class="descclassname">itertools.</code><code class="descname">izip</code><span class="sig-paren">(</span><em>*iterables</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.izip" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that aggregates elements from each of the iterables. Like
<a class="reference internal" href="functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> except that it returns an iterator instead of a list.  Used for
lock-step iteration over several iterables at a time.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">izip</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
    <span class="c1"># izip(&#39;ABCD&#39;, &#39;xy&#39;) --&gt; Ax By</span>
    <span class="n">iterators</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">iter</span><span class="p">,</span> <span class="n">iterables</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">iterators</span><span class="p">:</span>
        <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">next</span><span class="p">,</span> <span class="n">iterators</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>When no iterables are specified, returns a zero length iterator instead of
raising a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</div>
<p>The left-to-right evaluation order of the iterables is guaranteed. This
makes possible an idiom for clustering a data series into n-length groups
using <code class="docutils literal notranslate"><span class="pre">izip(*[iter(s)]*n)</span></code>.</p>
<p><a class="reference internal" href="#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip()</span></code></a> should only be used with unequal length inputs when you don’t
care about trailing, unmatched values from the longer iterables.  If those
values are important, use <a class="reference internal" href="#itertools.izip_longest" title="itertools.izip_longest"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip_longest()</span></code></a> instead.</p>
</dd></dl>

<dl class="function">
<dt id="itertools.izip_longest">
<code class="descclassname">itertools.</code><code class="descname">izip_longest</code><span class="sig-paren">(</span><em>*iterables</em><span class="optional">[</span>, <em>fillvalue</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.izip_longest" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that aggregates elements from each of the iterables. If the
iterables are of uneven length, missing values are filled-in with <em>fillvalue</em>.
Iteration continues until the longest iterable is exhausted.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ZipExhausted</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">izip_longest</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
    <span class="c1"># izip_longest(&#39;ABCD&#39;, &#39;xy&#39;, fillvalue=&#39;-&#39;) --&gt; Ax By C- D-</span>
    <span class="n">fillvalue</span> <span class="o">=</span> <span class="n">kwds</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;fillvalue&#39;</span><span class="p">)</span>
    <span class="n">counter</span> <span class="o">=</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span><span class="p">]</span>
    <span class="k">def</span> <span class="nf">sentinel</span><span class="p">():</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">counter</span><span class="p">[</span><span class="mi">0</span><span class="p">]:</span>
            <span class="k">raise</span> <span class="n">ZipExhausted</span>
        <span class="n">counter</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">-=</span> <span class="mi">1</span>
        <span class="k">yield</span> <span class="n">fillvalue</span>
    <span class="n">fillers</span> <span class="o">=</span> <span class="n">repeat</span><span class="p">(</span><span class="n">fillvalue</span><span class="p">)</span>
    <span class="n">iterators</span> <span class="o">=</span> <span class="p">[</span><span class="n">chain</span><span class="p">(</span><span class="n">it</span><span class="p">,</span> <span class="n">sentinel</span><span class="p">(),</span> <span class="n">fillers</span><span class="p">)</span> <span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">args</span><span class="p">]</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">while</span> <span class="n">iterators</span><span class="p">:</span>
            <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="nb">next</span><span class="p">,</span> <span class="n">iterators</span><span class="p">))</span>
    <span class="k">except</span> <span class="n">ZipExhausted</span><span class="p">:</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>If one of the iterables is potentially infinite, then the
<a class="reference internal" href="#itertools.izip_longest" title="itertools.izip_longest"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip_longest()</span></code></a> function should be wrapped with something that limits
the number of calls (for example <a class="reference internal" href="#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">islice()</span></code></a> or <a class="reference internal" href="#itertools.takewhile" title="itertools.takewhile"><code class="xref py py-func docutils literal notranslate"><span class="pre">takewhile()</span></code></a>).  If
not specified, <em>fillvalue</em> defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.permutations">
<code class="descclassname">itertools.</code><code class="descname">permutations</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>r</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.permutations" title="Permalink to this definition">¶</a></dt>
<dd><p>Return successive <em>r</em> length permutations of elements in the <em>iterable</em>.</p>
<p>If <em>r</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then <em>r</em> defaults to the length
of the <em>iterable</em> and all possible full-length permutations
are generated.</p>
<p>Permutations are emitted in lexicographic sort order.  So, if the
input <em>iterable</em> is sorted, the permutation tuples will be produced
in sorted order.</p>
<p>Elements are treated as unique based on their position, not on their
value.  So if the input elements are unique, there will be no repeat
values in each permutation.</p>
<p>Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">permutations</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="c1"># permutations(&#39;ABCD&#39;, 2) --&gt; AB AC AD BA BC BD CA CB CD DA DB DC</span>
    <span class="c1"># permutations(range(3)) --&gt; 012 021 102 120 201 210</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="n">r</span> <span class="o">=</span> <span class="n">n</span> <span class="k">if</span> <span class="n">r</span> <span class="ow">is</span> <span class="kc">None</span> <span class="k">else</span> <span class="n">r</span>
    <span class="k">if</span> <span class="n">r</span> <span class="o">&gt;</span> <span class="n">n</span><span class="p">:</span>
        <span class="k">return</span>
    <span class="n">indices</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
    <span class="n">cycles</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="o">-</span><span class="n">r</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">[:</span><span class="n">r</span><span class="p">])</span>
    <span class="k">while</span> <span class="n">n</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">r</span><span class="p">)):</span>
            <span class="n">cycles</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">-=</span> <span class="mi">1</span>
            <span class="k">if</span> <span class="n">cycles</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">:]</span> <span class="o">=</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span> <span class="o">+</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span>
                <span class="n">cycles</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">n</span> <span class="o">-</span> <span class="n">i</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">j</span> <span class="o">=</span> <span class="n">cycles</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
                <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">indices</span><span class="p">[</span><span class="o">-</span><span class="n">j</span><span class="p">]</span> <span class="o">=</span> <span class="n">indices</span><span class="p">[</span><span class="o">-</span><span class="n">j</span><span class="p">],</span> <span class="n">indices</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
                <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">[:</span><span class="n">r</span><span class="p">])</span>
                <span class="k">break</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span>
</pre></div>
</div>
<p>The code for <a class="reference internal" href="#itertools.permutations" title="itertools.permutations"><code class="xref py py-func docutils literal notranslate"><span class="pre">permutations()</span></code></a> can be also expressed as a subsequence of
<a class="reference internal" href="#itertools.product" title="itertools.product"><code class="xref py py-func docutils literal notranslate"><span class="pre">product()</span></code></a>, filtered to exclude entries with repeated elements (those
from the same position in the input pool):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">permutations</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="n">r</span> <span class="o">=</span> <span class="n">n</span> <span class="k">if</span> <span class="n">r</span> <span class="ow">is</span> <span class="kc">None</span> <span class="k">else</span> <span class="n">r</span>
    <span class="k">for</span> <span class="n">indices</span> <span class="ow">in</span> <span class="n">product</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">),</span> <span class="n">repeat</span><span class="o">=</span><span class="n">r</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">indices</span><span class="p">))</span> <span class="o">==</span> <span class="n">r</span><span class="p">:</span>
            <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>
</pre></div>
</div>
<p>The number of items returned is <code class="docutils literal notranslate"><span class="pre">n!</span> <span class="pre">/</span> <span class="pre">(n-r)!</span></code> when <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">r</span> <span class="pre">&lt;=</span> <span class="pre">n</span></code>
or zero when <code class="docutils literal notranslate"><span class="pre">r</span> <span class="pre">&gt;</span> <span class="pre">n</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.product">
<code class="descclassname">itertools.</code><code class="descname">product</code><span class="sig-paren">(</span><em>*iterables</em><span class="optional">[</span>, <em>repeat</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.product" title="Permalink to this definition">¶</a></dt>
<dd><p>Cartesian product of input iterables.</p>
<p>Roughly equivalent to nested for-loops in a generator expression. For example,
<code class="docutils literal notranslate"><span class="pre">product(A,</span> <span class="pre">B)</span></code> returns the same as <code class="docutils literal notranslate"><span class="pre">((x,y)</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">A</span> <span class="pre">for</span> <span class="pre">y</span> <span class="pre">in</span> <span class="pre">B)</span></code>.</p>
<p>The nested loops cycle like an odometer with the rightmost element advancing
on every iteration.  This pattern creates a lexicographic ordering so that if
the input’s iterables are sorted, the product tuples are emitted in sorted
order.</p>
<p>To compute the product of an iterable with itself, specify the number of
repetitions with the optional <em>repeat</em> keyword argument.  For example,
<code class="docutils literal notranslate"><span class="pre">product(A,</span> <span class="pre">repeat=4)</span></code> means the same as <code class="docutils literal notranslate"><span class="pre">product(A,</span> <span class="pre">A,</span> <span class="pre">A,</span> <span class="pre">A)</span></code>.</p>
<p>This function is roughly equivalent to the following code, except that the
actual implementation does not build up intermediate results in memory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">product</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
    <span class="c1"># product(&#39;ABCD&#39;, &#39;xy&#39;) --&gt; Ax Ay Bx By Cx Cy Dx Dy</span>
    <span class="c1"># product(range(2), repeat=3) --&gt; 000 001 010 011 100 101 110 111</span>
    <span class="n">pools</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">*</span> <span class="n">kwds</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;repeat&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">result</span> <span class="o">=</span> <span class="p">[[]]</span>
    <span class="k">for</span> <span class="n">pool</span> <span class="ow">in</span> <span class="n">pools</span><span class="p">:</span>
        <span class="n">result</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="o">+</span><span class="p">[</span><span class="n">y</span><span class="p">]</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">result</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">pool</span><span class="p">]</span>
    <span class="k">for</span> <span class="n">prod</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
        <span class="k">yield</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">prod</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.repeat">
<code class="descclassname">itertools.</code><code class="descname">repeat</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>times</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.repeat" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that returns <em>object</em> over and over again. Runs indefinitely
unless the <em>times</em> argument is specified. Used as argument to <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> for
invariant function parameters.  Also used with <a class="reference internal" href="#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">izip()</span></code></a> to create constant
fields in a tuple record.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">repeat</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="n">times</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="c1"># repeat(10, 3) --&gt; 10 10 10</span>
    <span class="k">if</span> <span class="n">times</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
            <span class="k">yield</span> <span class="nb">object</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="n">times</span><span class="p">):</span>
            <span class="k">yield</span> <span class="nb">object</span>
</pre></div>
</div>
<p>A common use for <em>repeat</em> is to supply a stream of constant values to <em>imap</em>
or <em>zip</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">imap</span><span class="p">(</span><span class="nb">pow</span><span class="p">,</span> <span class="n">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="n">repeat</span><span class="p">(</span><span class="mi">2</span><span class="p">)))</span>
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.starmap">
<code class="descclassname">itertools.</code><code class="descname">starmap</code><span class="sig-paren">(</span><em>function</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.starmap" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that computes the function using arguments obtained from
the iterable.  Used instead of <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> when argument parameters are already
grouped in tuples from a single iterable (the data has been “pre-zipped”).  The
difference between <a class="reference internal" href="#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">imap()</span></code></a> and <a class="reference internal" href="#itertools.starmap" title="itertools.starmap"><code class="xref py py-func docutils literal notranslate"><span class="pre">starmap()</span></code></a> parallels the distinction
between <code class="docutils literal notranslate"><span class="pre">function(a,b)</span></code> and <code class="docutils literal notranslate"><span class="pre">function(*c)</span></code>. Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">starmap</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># starmap(pow, [(2,5), (3,2), (10,3)]) --&gt; 32 9 1000</span>
    <span class="k">for</span> <span class="n">args</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">function</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Previously, <a class="reference internal" href="#itertools.starmap" title="itertools.starmap"><code class="xref py py-func docutils literal notranslate"><span class="pre">starmap()</span></code></a> required the function arguments to be tuples.
Now, any iterable is allowed.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.takewhile">
<code class="descclassname">itertools.</code><code class="descname">takewhile</code><span class="sig-paren">(</span><em>predicate</em>, <em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#itertools.takewhile" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an iterator that returns elements from the iterable as long as the
predicate is true.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">takewhile</span><span class="p">(</span><span class="n">predicate</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="c1"># takewhile(lambda x: x&lt;5, [1,4,6,4,1]) --&gt; 1 4</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">predicate</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">break</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="itertools.tee">
<code class="descclassname">itertools.</code><code class="descname">tee</code><span class="sig-paren">(</span><em>iterable</em><span class="optional">[</span>, <em>n=2</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#itertools.tee" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>n</em> independent iterators from a single iterable.  Roughly equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">tee</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="mi">2</span><span class="p">):</span>
    <span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">deques</span> <span class="o">=</span> <span class="p">[</span><span class="n">collections</span><span class="o">.</span><span class="n">deque</span><span class="p">()</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="p">)]</span>
    <span class="k">def</span> <span class="nf">gen</span><span class="p">(</span><span class="n">mydeque</span><span class="p">):</span>
        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
            <span class="k">if</span> <span class="ow">not</span> <span class="n">mydeque</span><span class="p">:</span>             <span class="c1"># when the local deque is empty</span>
                <span class="n">newval</span> <span class="o">=</span> <span class="nb">next</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>       <span class="c1"># fetch a new value and</span>
                <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">deques</span><span class="p">:</span>        <span class="c1"># load it to all the deques</span>
                    <span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">newval</span><span class="p">)</span>
            <span class="k">yield</span> <span class="n">mydeque</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">gen</span><span class="p">(</span><span class="n">d</span><span class="p">)</span> <span class="k">for</span> <span class="n">d</span> <span class="ow">in</span> <span class="n">deques</span><span class="p">)</span>
</pre></div>
</div>
<p>Once <a class="reference internal" href="#itertools.tee" title="itertools.tee"><code class="xref py py-func docutils literal notranslate"><span class="pre">tee()</span></code></a> has made a split, the original <em>iterable</em> should not be
used anywhere else; otherwise, the <em>iterable</em> could get advanced without
the tee objects being informed.</p>
<p>This itertool may require significant auxiliary storage (depending on how
much temporary data needs to be stored). In general, if one iterator uses
most or all of the data before another iterator starts, it is faster to use
<code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code> instead of <a class="reference internal" href="#itertools.tee" title="itertools.tee"><code class="xref py py-func docutils literal notranslate"><span class="pre">tee()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="recipes">
<span id="itertools-recipes"></span><h2>9.7.2. Recipes<a class="headerlink" href="#recipes" title="Permalink to this headline">¶</a></h2>
<p>This section shows recipes for creating an extended toolset using the existing
itertools as building blocks.</p>
<p>The extended tools offer the same high performance as the underlying toolset.
The superior memory performance is kept by processing elements one at a time
rather than bringing the whole iterable into memory all at once. Code volume is
kept small by linking the tools together in a functional style which helps
eliminate temporary variables.  High speed is retained by preferring
“vectorized” building blocks over the use of for-loops and <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>s
which incur interpreter overhead.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">take</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
    <span class="s2">&quot;Return first n items of the iterable as a list&quot;</span>
    <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">tabulate</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
    <span class="s2">&quot;Return function(0), function(1), ...&quot;</span>
    <span class="k">return</span> <span class="n">imap</span><span class="p">(</span><span class="n">function</span><span class="p">,</span> <span class="n">count</span><span class="p">(</span><span class="n">start</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">consume</span><span class="p">(</span><span class="n">iterator</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;Advance the iterator n-steps ahead. If n is None, consume entirely.&quot;</span>
    <span class="c1"># Use functions that consume iterators at C speed.</span>
    <span class="k">if</span> <span class="n">n</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="c1"># feed the entire iterator into a zero-length deque</span>
        <span class="n">collections</span><span class="o">.</span><span class="n">deque</span><span class="p">(</span><span class="n">iterator</span><span class="p">,</span> <span class="n">maxlen</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># advance to the empty slice starting at position n</span>
        <span class="nb">next</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">iterator</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">),</span> <span class="bp">None</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">nth</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;Returns the nth item or a default value&quot;</span>
    <span class="k">return</span> <span class="nb">next</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="bp">None</span><span class="p">),</span> <span class="n">default</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">all_equal</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="s2">&quot;Returns True if all the elements are equal to each other&quot;</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">groupby</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">next</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="bp">True</span><span class="p">)</span> <span class="ow">and</span> <span class="ow">not</span> <span class="nb">next</span><span class="p">(</span><span class="n">g</span><span class="p">,</span> <span class="bp">False</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">quantify</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">pred</span><span class="o">=</span><span class="nb">bool</span><span class="p">):</span>
    <span class="s2">&quot;Count how many times the predicate is true&quot;</span>
    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">imap</span><span class="p">(</span><span class="n">pred</span><span class="p">,</span> <span class="n">iterable</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">padnone</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Returns the sequence elements and then returns None indefinitely.</span>

<span class="sd">    Useful for emulating the behavior of the built-in map() function.</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">chain</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">repeat</span><span class="p">(</span><span class="bp">None</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">ncycles</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
    <span class="s2">&quot;Returns the sequence elements n times&quot;</span>
    <span class="k">return</span> <span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</span><span class="p">(</span><span class="n">repeat</span><span class="p">(</span><span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">),</span> <span class="n">n</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">dotproduct</span><span class="p">(</span><span class="n">vec1</span><span class="p">,</span> <span class="n">vec2</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">imap</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">,</span> <span class="n">vec1</span><span class="p">,</span> <span class="n">vec2</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">flatten</span><span class="p">(</span><span class="n">listOfLists</span><span class="p">):</span>
    <span class="s2">&quot;Flatten one level of nesting&quot;</span>
    <span class="k">return</span> <span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</span><span class="p">(</span><span class="n">listOfLists</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">repeatfunc</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">times</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Repeat calls to func with specified arguments.</span>

<span class="sd">    Example:  repeatfunc(random.random)</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">if</span> <span class="n">times</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">starmap</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">repeat</span><span class="p">(</span><span class="n">args</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">starmap</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">repeat</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">times</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">pairwise</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="s2">&quot;s -&gt; (s0,s1), (s1,s2), (s2, s3), ...&quot;</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">tee</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="nb">next</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="bp">None</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">izip</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">grouper</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">fillvalue</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;Collect data into fixed-length chunks or blocks&quot;</span>
    <span class="c1"># grouper(&#39;ABCDEFG&#39;, 3, &#39;x&#39;) --&gt; ABC DEF Gxx</span>
    <span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="nb">iter</span><span class="p">(</span><span class="n">iterable</span><span class="p">)]</span> <span class="o">*</span> <span class="n">n</span>
    <span class="k">return</span> <span class="n">izip_longest</span><span class="p">(</span><span class="n">fillvalue</span><span class="o">=</span><span class="n">fillvalue</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">roundrobin</span><span class="p">(</span><span class="o">*</span><span class="n">iterables</span><span class="p">):</span>
    <span class="s2">&quot;roundrobin(&#39;ABC&#39;, &#39;D&#39;, &#39;EF&#39;) --&gt; A D E B F C&quot;</span>
    <span class="c1"># Recipe credited to George Sakkis</span>
    <span class="n">pending</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">iterables</span><span class="p">)</span>
    <span class="n">nexts</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">(</span><span class="nb">iter</span><span class="p">(</span><span class="n">it</span><span class="p">)</span><span class="o">.</span><span class="n">next</span> <span class="k">for</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">iterables</span><span class="p">)</span>
    <span class="k">while</span> <span class="n">pending</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">for</span> <span class="nb">next</span> <span class="ow">in</span> <span class="n">nexts</span><span class="p">:</span>
                <span class="k">yield</span> <span class="nb">next</span><span class="p">()</span>
        <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
            <span class="n">pending</span> <span class="o">-=</span> <span class="mi">1</span>
            <span class="n">nexts</span> <span class="o">=</span> <span class="n">cycle</span><span class="p">(</span><span class="n">islice</span><span class="p">(</span><span class="n">nexts</span><span class="p">,</span> <span class="n">pending</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">powerset</span><span class="p">(</span><span class="n">iterable</span><span class="p">):</span>
    <span class="s2">&quot;powerset([1,2,3]) --&gt; () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)&quot;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</span><span class="p">(</span><span class="n">combinations</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">r</span><span class="p">)</span> <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">unique_everseen</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;List unique elements, preserving order. Remember all elements ever seen.&quot;</span>
    <span class="c1"># unique_everseen(&#39;AAAABBBCCDAABBB&#39;) --&gt; A B C D</span>
    <span class="c1"># unique_everseen(&#39;ABBCcAD&#39;, str.lower) --&gt; A B C D</span>
    <span class="n">seen</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>
    <span class="n">seen_add</span> <span class="o">=</span> <span class="n">seen</span><span class="o">.</span><span class="n">add</span>
    <span class="k">if</span> <span class="n">key</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">ifilterfalse</span><span class="p">(</span><span class="n">seen</span><span class="o">.</span><span class="fm">__contains__</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
            <span class="n">seen_add</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
            <span class="k">yield</span> <span class="n">element</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
            <span class="n">k</span> <span class="o">=</span> <span class="n">key</span><span class="p">(</span><span class="n">element</span><span class="p">)</span>
            <span class="k">if</span> <span class="n">k</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">seen</span><span class="p">:</span>
                <span class="n">seen_add</span><span class="p">(</span><span class="n">k</span><span class="p">)</span>
                <span class="k">yield</span> <span class="n">element</span>

<span class="k">def</span> <span class="nf">unique_justseen</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;List unique elements, preserving order. Remember only the element just seen.&quot;</span>
    <span class="c1"># unique_justseen(&#39;AAAABBBCCDAABBB&#39;) --&gt; A B C D A B</span>
    <span class="c1"># unique_justseen(&#39;ABBCcAD&#39;, str.lower) --&gt; A B C A D</span>
    <span class="k">return</span> <span class="n">imap</span><span class="p">(</span><span class="nb">next</span><span class="p">,</span> <span class="n">imap</span><span class="p">(</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">groupby</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">key</span><span class="p">)))</span>

<span class="k">def</span> <span class="nf">iter_except</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">exception</span><span class="p">,</span> <span class="n">first</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot; Call a function repeatedly until an exception is raised.</span>

<span class="sd">    Converts a call-until-exception interface to an iterator interface.</span>
<span class="sd">    Like __builtin__.iter(func, sentinel) but uses an exception instead</span>
<span class="sd">    of a sentinel to end the loop.</span>

<span class="sd">    Examples:</span>
<span class="sd">        bsddbiter = iter_except(db.next, bsddb.error, db.first)</span>
<span class="sd">        heapiter = iter_except(functools.partial(heappop, h), IndexError)</span>
<span class="sd">        dictiter = iter_except(d.popitem, KeyError)</span>
<span class="sd">        dequeiter = iter_except(d.popleft, IndexError)</span>
<span class="sd">        queueiter = iter_except(q.get_nowait, Queue.Empty)</span>
<span class="sd">        setiter = iter_except(s.pop, KeyError)</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">first</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">first</span><span class="p">()</span>
        <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">func</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">exception</span><span class="p">:</span>
        <span class="k">pass</span>

<span class="k">def</span> <span class="nf">random_product</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
    <span class="s2">&quot;Random selection from itertools.product(*args, **kwds)&quot;</span>
    <span class="n">pools</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">tuple</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">*</span> <span class="n">kwds</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;repeat&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span> <span class="k">for</span> <span class="n">pool</span> <span class="ow">in</span> <span class="n">pools</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">random_permutation</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="s2">&quot;Random selection from itertools.permutations(iterable, r)&quot;</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">r</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span> <span class="k">if</span> <span class="n">r</span> <span class="ow">is</span> <span class="bp">None</span> <span class="k">else</span> <span class="n">r</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">pool</span><span class="p">,</span> <span class="n">r</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">random_combination</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="s2">&quot;Random selection from itertools.combinations(iterable, r)&quot;</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="n">indices</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">xrange</span><span class="p">(</span><span class="n">n</span><span class="p">),</span> <span class="n">r</span><span class="p">))</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">random_combination_with_replacement</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">r</span><span class="p">):</span>
    <span class="s2">&quot;Random selection from itertools.combinations_with_replacement(iterable, r)&quot;</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
    <span class="n">n</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">pool</span><span class="p">)</span>
    <span class="n">indices</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="n">n</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">r</span><span class="p">))</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">pool</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">tee_lookahead</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Inspect the i-th upcomping value from a tee object</span>
<span class="sd">       while leaving the tee object at its current position.</span>

<span class="sd">       Raise an IndexError if the underlying iterator doesn&#39;t</span>
<span class="sd">       have enough values.</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">islice</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">__copy__</span><span class="p">(),</span> <span class="n">i</span><span class="p">,</span> <span class="bp">None</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">value</span>
    <span class="k">raise</span> <span class="ne">IndexError</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>Note, many of the above recipes can be optimized by replacing global lookups
with local variables defined as default values.  For example, the
<em>dotproduct</em> recipe can be written as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">dotproduct</span><span class="p">(</span><span class="n">vec1</span><span class="p">,</span> <span class="n">vec2</span><span class="p">,</span> <span class="nb">sum</span><span class="o">=</span><span class="nb">sum</span><span class="p">,</span> <span class="n">imap</span><span class="o">=</span><span class="n">imap</span><span class="p">,</span> <span class="n">mul</span><span class="o">=</span><span class="n">operator</span><span class="o">.</span><span class="n">mul</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">imap</span><span class="p">(</span><span class="n">mul</span><span class="p">,</span> <span class="n">vec1</span><span class="p">,</span> <span class="n">vec2</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a><ul>
<li><a class="reference internal" href="#itertool-functions">9.7.1. Itertool functions</a></li>
<li><a class="reference internal" href="#recipes">9.7.2. Recipes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="random.html"
                        title="previous chapter">9.6. <code class="docutils literal notranslate"><span class="pre">random</span></code> — Generate pseudo-random numbers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="functools.html"
                        title="next chapter">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/itertools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="functools.html" title="9.8. functools — Higher-order functions and operations on callable objects"
             >next</a> |</li>
        <li class="right" >
          <a href="random.html" title="9.6. random — Generate pseudo-random numbers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\љc߽5�5html/library/jpeg.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39.12. jpeg — Read and write JPEG files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="40. SunOS Specific Services" href="sun.html" />
    <link rel="prev" title="39.11. imgfile — Support for SGI imglib files" href="imgfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/jpeg.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sun.html" title="40. SunOS Specific Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imgfile.html" title="39.11. imgfile — Support for SGI imglib files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" accesskey="U">39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-jpeg">
<span id="jpeg-read-and-write-jpeg-files"></span><h1>39.12. <a class="reference internal" href="#module-jpeg" title="jpeg: Read and write image files in compressed JPEG format. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code></a> — Read and write JPEG files<a class="headerlink" href="#module-jpeg" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-jpeg" title="jpeg: Read and write image files in compressed JPEG format. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">The module <a class="reference internal" href="#module-jpeg" title="jpeg: Read and write image files in compressed JPEG format. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code></a> provides access to the jpeg compressor and decompressor
written by the Independent JPEG Group (IJG). JPEG is a standard for compressing
pictures; it is defined in ISO 10918.  For details on JPEG or the Independent
JPEG Group software refer to the JPEG standard or the documentation provided
with the software.</p>
<p id="index-1">A portable interface to JPEG image files is available with the Python Imaging
Library (PIL) by Fredrik Lundh.  Information on PIL is available at
<a class="reference external" href="http://www.pythonware.com/products/pil/">http://www.pythonware.com/products/pil/</a>.</p>
<p>The <a class="reference internal" href="#module-jpeg" title="jpeg: Read and write image files in compressed JPEG format. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code></a> module defines an exception and some functions.</p>
<dl class="exception">
<dt id="jpeg.error">
<em class="property">exception </em><code class="descclassname">jpeg.</code><code class="descname">error</code><a class="headerlink" href="#jpeg.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by <a class="reference internal" href="#jpeg.compress" title="jpeg.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a> and <a class="reference internal" href="#jpeg.decompress" title="jpeg.decompress"><code class="xref py py-func docutils literal notranslate"><span class="pre">decompress()</span></code></a> in case of errors.</p>
</dd></dl>

<dl class="function">
<dt id="jpeg.compress">
<code class="descclassname">jpeg.</code><code class="descname">compress</code><span class="sig-paren">(</span><em>data</em>, <em>w</em>, <em>h</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#jpeg.compress" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Treat data as a pixmap of width <em>w</em> and height <em>h</em>, with <em>b</em> bytes per pixel.
The data is in SGI GL order, so the first pixel is in the lower-left corner.
This means that <code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectread()</span></code> return data can immediately be passed to
<a class="reference internal" href="#jpeg.compress" title="jpeg.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a>. Currently only 1 byte and 4 byte pixels are allowed, the
former being treated as greyscale and the latter as RGB color. <a class="reference internal" href="#jpeg.compress" title="jpeg.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a>
returns a string that contains the compressed picture, in JFIF format.</p>
</dd></dl>

<dl class="function">
<dt id="jpeg.decompress">
<code class="descclassname">jpeg.</code><code class="descname">decompress</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#jpeg.decompress" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Data is a string containing a picture in JFIF format. It returns a tuple
<code class="docutils literal notranslate"><span class="pre">(data,</span> <span class="pre">width,</span> <span class="pre">height,</span> <span class="pre">bytesperpixel)</span></code>.  Again, the data is suitable to pass
to <code class="xref py py-func docutils literal notranslate"><span class="pre">gl.lrectwrite()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="jpeg.setoption">
<code class="descclassname">jpeg.</code><code class="descname">setoption</code><span class="sig-paren">(</span><em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#jpeg.setoption" title="Permalink to this definition">¶</a></dt>
<dd><p>Set various options.  Subsequent <a class="reference internal" href="#jpeg.compress" title="jpeg.compress"><code class="xref py py-func docutils literal notranslate"><span class="pre">compress()</span></code></a> and <a class="reference internal" href="#jpeg.decompress" title="jpeg.decompress"><code class="xref py py-func docutils literal notranslate"><span class="pre">decompress()</span></code></a> calls
will use these options.  The following options are available:</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="73%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Option</th>
<th class="head">Effect</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'forcegray'</span></code></td>
<td>Force output to be grayscale, even if input
is RGB.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'quality'</span></code></td>
<td>Set the quality of the compressed image to
a value between <code class="docutils literal notranslate"><span class="pre">0</span></code> and <code class="docutils literal notranslate"><span class="pre">100</span></code> (default
is <code class="docutils literal notranslate"><span class="pre">75</span></code>).  This only affects compression.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'optimize'</span></code></td>
<td>Perform Huffman table optimization.  Takes
longer, but results in smaller compressed
image.  This only affects compression.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'smooth'</span></code></td>
<td>Perform inter-block smoothing on
uncompressed image.  Only useful for low-
quality images.  This only affects
decompression.</td>
</tr>
</tbody>
</table>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>JPEG Still Image Data Compression Standard</dt>
<dd>The canonical reference for the JPEG image format, by Pennebaker and Mitchell.</dd>
<dt><a class="reference external" href="http://www.w3.org/Graphics/JPEG/itu-t81.pdf">Information Technology - Digital Compression and Coding of Continuous-tone Still Images - Requirements and Guidelines</a></dt>
<dd>The ISO standard for JPEG is also published as ITU T.81.  This is available
online in PDF form.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="imgfile.html"
                        title="previous chapter">39.11. <code class="docutils literal notranslate"><span class="pre">imgfile</span></code> — Support for SGI imglib files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sun.html"
                        title="next chapter">40. SunOS Specific Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/jpeg.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sun.html" title="40. SunOS Specific Services"
             >next</a> |</li>
        <li class="right" >
          <a href="imgfile.html" title="39.11. imgfile — Support for SGI imglib files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sgi.html" >39. SGI IRIX Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\>V����html/library/json.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.2. json — JSON encoder and decoder &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.3. mailcap — Mailcap file handling" href="mailcap.html" />
    <link rel="prev" title="18.1.11. email: Examples" href="email-examples.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/json.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mailcap.html" title="18.3. mailcap — Mailcap file handling"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="email-examples.html" title="18.1.11. email: Examples"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-json">
<span id="json-json-encoder-and-decoder"></span><h1>18.2. <a class="reference internal" href="#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> — JSON encoder and decoder<a class="headerlink" href="#module-json" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p><a class="reference external" href="http://json.org">JSON (JavaScript Object Notation)</a>, specified by
<span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7159.html"><strong>RFC 7159</strong></a> (which obsoletes <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4627.html"><strong>RFC 4627</strong></a>) and by
<a class="reference external" href="http://www.ecma-international.org/publications/standards/Ecma-404.htm">ECMA-404</a>,
is a lightweight data interchange format inspired by
<a class="reference external" href="https://en.wikipedia.org/wiki/JavaScript">JavaScript</a> object literal syntax
(although it is not a strict subset of JavaScript <a class="footnote-reference" href="#rfc-errata" id="id1">[1]</a> ).</p>
<p><a class="reference internal" href="#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> exposes an API familiar to users of the standard library
<a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> and <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> modules.</p>
<p>Encoding basic Python object hierarchies:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="s1">&#39;foo&#39;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;bar&#39;</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="mf">1.0</span><span class="p">,</span> <span class="mi">2</span><span class="p">)}])</span>
<span class="go">&#39;[&quot;foo&quot;, {&quot;bar&quot;: [&quot;baz&quot;, null, 1.0, 2]}]&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\&quot;</span><span class="s2">foo</span><span class="se">\b</span><span class="s2">ar&quot;</span><span class="p">)</span>
<span class="go">&quot;\&quot;foo\bar&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u1234</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&quot;\u1234&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\\</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">&quot;\\&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">({</span><span class="s2">&quot;c&quot;</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;b&quot;</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;a&quot;</span><span class="p">:</span> <span class="mi">0</span><span class="p">},</span> <span class="n">sort_keys</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">{&quot;a&quot;: 0, &quot;b&quot;: 0, &quot;c&quot;: 0}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">StringIO</span> <span class="k">import</span> <span class="n">StringIO</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">io</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dump</span><span class="p">([</span><span class="s1">&#39;streaming API&#39;</span><span class="p">],</span> <span class="n">io</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">io</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
<span class="go">&#39;[&quot;streaming API&quot;]&#39;</span>
</pre></div>
</div>
<p>Compact encoding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,{</span><span class="s1">&#39;4&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;6&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">}],</span> <span class="n">separators</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">,</span><span class="s1">&#39;:&#39;</span><span class="p">))</span>
<span class="go">&#39;[1,2,3,{&quot;4&quot;:5,&quot;6&quot;:7}]&#39;</span>
</pre></div>
</div>
<p>Pretty printing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">({</span><span class="s1">&#39;4&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;6&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">},</span> <span class="n">sort_keys</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
<span class="gp">... </span>                 <span class="n">indent</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">separators</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;,&#39;</span><span class="p">,</span> <span class="s1">&#39;: &#39;</span><span class="p">))</span>
<span class="go">{</span>
<span class="go">    &quot;4&quot;: 5,</span>
<span class="go">    &quot;6&quot;: 7</span>
<span class="go">}</span>
</pre></div>
</div>
<p>Decoding JSON:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;[&quot;foo&quot;, {&quot;bar&quot;:[&quot;baz&quot;, null, 1.0, 2]}]&#39;</span><span class="p">)</span>
<span class="go">[u&#39;foo&#39;, {u&#39;bar&#39;: [u&#39;baz&#39;, None, 1.0, 2]}]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;&quot;</span><span class="se">\\</span><span class="s1">&quot;foo</span><span class="se">\\</span><span class="s1">bar&quot;&#39;</span><span class="p">)</span>
<span class="go">u&#39;&quot;foo\x08ar&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">StringIO</span> <span class="k">import</span> <span class="n">StringIO</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">io</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">(</span><span class="s1">&#39;[&quot;streaming API&quot;]&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">io</span><span class="p">)</span>
<span class="go">[u&#39;streaming API&#39;]</span>
</pre></div>
</div>
<p>Specializing JSON object decoding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">as_complex</span><span class="p">(</span><span class="n">dct</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="s1">&#39;__complex__&#39;</span> <span class="ow">in</span> <span class="n">dct</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">complex</span><span class="p">(</span><span class="n">dct</span><span class="p">[</span><span class="s1">&#39;real&#39;</span><span class="p">],</span> <span class="n">dct</span><span class="p">[</span><span class="s1">&#39;imag&#39;</span><span class="p">])</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">dct</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;{&quot;__complex__&quot;: true, &quot;real&quot;: 1, &quot;imag&quot;: 2}&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">object_hook</span><span class="o">=</span><span class="n">as_complex</span><span class="p">)</span>
<span class="go">(1+2j)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;1.1&#39;</span><span class="p">,</span> <span class="n">parse_float</span><span class="o">=</span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">)</span>
<span class="go">Decimal(&#39;1.1&#39;)</span>
</pre></div>
</div>
<p>Extending <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONEncoder</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">ComplexEncoder</span><span class="p">(</span><span class="n">json</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">complex</span><span class="p">):</span>
<span class="gp">... </span>            <span class="k">return</span> <span class="p">[</span><span class="n">obj</span><span class="o">.</span><span class="n">real</span><span class="p">,</span> <span class="n">obj</span><span class="o">.</span><span class="n">imag</span><span class="p">]</span>
<span class="gp">... </span>        <span class="c1"># Let the base class default method raise the TypeError</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="n">json</span><span class="o">.</span><span class="n">JSONEncoder</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="mi">2</span> <span class="o">+</span> <span class="mi">1</span><span class="n">j</span><span class="p">,</span> <span class="bp">cls</span><span class="o">=</span><span class="n">ComplexEncoder</span><span class="p">)</span>
<span class="go">&#39;[2.0, 1.0]&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ComplexEncoder</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="mi">2</span> <span class="o">+</span> <span class="mi">1</span><span class="n">j</span><span class="p">)</span>
<span class="go">&#39;[2.0, 1.0]&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">ComplexEncoder</span><span class="p">()</span><span class="o">.</span><span class="n">iterencode</span><span class="p">(</span><span class="mi">2</span> <span class="o">+</span> <span class="mi">1</span><span class="n">j</span><span class="p">))</span>
<span class="go">[&#39;[&#39;, &#39;2.0&#39;, &#39;, &#39;, &#39;1.0&#39;, &#39;]&#39;]</span>
</pre></div>
</div>
<p>Using <code class="xref py py-mod docutils literal notranslate"><span class="pre">json.tool</span></code> from the shell to validate and pretty-print:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$ echo &#39;{&quot;json&quot;:&quot;obj&quot;}&#39; | python -m json.tool
{
    &quot;json&quot;: &quot;obj&quot;
}
$ echo &#39;{1.2:3.4}&#39; | python -mjson.tool
Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">JSON is a subset of <a class="reference external" href="http://yaml.org/">YAML</a> 1.2.  The JSON produced by
this module’s default settings (in particular, the default <em>separators</em>
value) is also a subset of YAML 1.0 and 1.1.  This module can thus also be
used as a YAML serializer.</p>
</div>
<div class="section" id="basic-usage">
<h2>18.2.1. Basic Usage<a class="headerlink" href="#basic-usage" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="json.dump">
<code class="descclassname">json.</code><code class="descname">dump</code><span class="sig-paren">(</span><em>obj</em>, <em>fp</em>, <em>skipkeys=False</em>, <em>ensure_ascii=True</em>, <em>check_circular=True</em>, <em>allow_nan=True</em>, <em>cls=None</em>, <em>indent=None</em>, <em>separators=None</em>, <em>encoding=&quot;utf-8&quot;</em>, <em>default=None</em>, <em>sort_keys=False</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#json.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Serialize <em>obj</em> as a JSON formatted stream to <em>fp</em> (a <code class="docutils literal notranslate"><span class="pre">.write()</span></code>-supporting
<a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a>) using this <a class="reference internal" href="#py-to-json-table"><span class="std std-ref">conversion table</span></a>.</p>
<p>If <em>skipkeys</em> is true (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>), then dict keys that are not
of a basic type (<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>, <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>,
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>, <code class="docutils literal notranslate"><span class="pre">None</span></code>) will be skipped instead of raising a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<p>If <em>ensure_ascii</em> is true (the default), all non-ASCII characters in the
output are escaped with <code class="docutils literal notranslate"><span class="pre">\uXXXX</span></code> sequences, and the result is a
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> instance consisting of ASCII characters only.  If
<em>ensure_ascii</em> is false, some chunks written to <em>fp</em> may be
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> instances.  This usually happens because the input contains
unicode strings or the <em>encoding</em> parameter is used.  Unless <code class="docutils literal notranslate"><span class="pre">fp.write()</span></code>
explicitly understands <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> (as in <a class="reference internal" href="codecs.html#codecs.getwriter" title="codecs.getwriter"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.getwriter()</span></code></a>)
this is likely to cause an error.</p>
<p>If <em>check_circular</em> is false (default: <code class="docutils literal notranslate"><span class="pre">True</span></code>), then the circular
reference check for container types will be skipped and a circular reference
will result in an <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> (or worse).</p>
<p>If <em>allow_nan</em> is false (default: <code class="docutils literal notranslate"><span class="pre">True</span></code>), then it will be a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to serialize out of range <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> values (<code class="docutils literal notranslate"><span class="pre">nan</span></code>,
<code class="docutils literal notranslate"><span class="pre">inf</span></code>, <code class="docutils literal notranslate"><span class="pre">-inf</span></code>) in strict compliance of the JSON specification.
If <em>allow_nan</em> is true, their JavaScript equivalents (<code class="docutils literal notranslate"><span class="pre">NaN</span></code>,
<code class="docutils literal notranslate"><span class="pre">Infinity</span></code>, <code class="docutils literal notranslate"><span class="pre">-Infinity</span></code>) will be used.</p>
<p>If <em>indent</em> is a non-negative integer, then JSON array elements and object
members will be pretty-printed with that indent level.  An indent level of 0,
or negative, will only insert newlines.  <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) selects the
most compact representation.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since the default item separator is <code class="docutils literal notranslate"><span class="pre">',</span> <span class="pre">'</span></code>,  the output might include
trailing whitespace when <em>indent</em> is specified.  You can use
<code class="docutils literal notranslate"><span class="pre">separators=(',',</span> <span class="pre">':</span> <span class="pre">')</span></code> to avoid this.</p>
</div>
<p>If specified, <em>separators</em> should be an <code class="docutils literal notranslate"><span class="pre">(item_separator,</span> <span class="pre">key_separator)</span></code>
tuple.  By default, <code class="docutils literal notranslate"><span class="pre">(',</span> <span class="pre">',</span> <span class="pre">':</span> <span class="pre">')</span></code> are used.  To get the most compact JSON
representation, you should specify <code class="docutils literal notranslate"><span class="pre">(',',</span> <span class="pre">':')</span></code> to eliminate whitespace.</p>
<p><em>encoding</em> is the character encoding for str instances, default is UTF-8.</p>
<p>If specified, <em>default</em> should be a function that gets called for objects that
can’t otherwise be serialized.  It should return a JSON encodable version of
the object or raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  If not specified, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
is raised.</p>
<p>If <em>sort_keys</em> is true (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>), then the output of
dictionaries will be sorted by key.</p>
<p>To use a custom <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONEncoder</span></code></a> subclass (e.g. one that overrides the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">default()</span></code> method to serialize additional types), specify it with the
<em>cls</em> kwarg; otherwise <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONEncoder</span></code></a> is used.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a>, JSON is not a framed protocol so
trying to serialize more objects with repeated calls to <a class="reference internal" href="#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a> and
the same <em>fp</em> will result in an invalid JSON file.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="json.dumps">
<code class="descclassname">json.</code><code class="descname">dumps</code><span class="sig-paren">(</span><em>obj</em>, <em>skipkeys=False</em>, <em>ensure_ascii=True</em>, <em>check_circular=True</em>, <em>allow_nan=True</em>, <em>cls=None</em>, <em>indent=None</em>, <em>separators=None</em>, <em>encoding=&quot;utf-8&quot;</em>, <em>default=None</em>, <em>sort_keys=False</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#json.dumps" title="Permalink to this definition">¶</a></dt>
<dd><p>Serialize <em>obj</em> to a JSON formatted <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> using this <a class="reference internal" href="#py-to-json-table"><span class="std std-ref">conversion
table</span></a>.  If <em>ensure_ascii</em> is false, the result may
contain non-ASCII characters and the return value may be a <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>
instance.</p>
<p>The arguments have the same meaning as in <a class="reference internal" href="#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Keys in key/value pairs of JSON are always of the type <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>. When
a dictionary is converted into JSON, all the keys of the dictionary are
coerced to strings. As a result of this, if a dictionary is converted
into JSON and then back into a dictionary, the dictionary may not equal
the original one. That is, <code class="docutils literal notranslate"><span class="pre">loads(dumps(x))</span> <span class="pre">!=</span> <span class="pre">x</span></code> if x has non-string
keys.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="json.load">
<code class="descclassname">json.</code><code class="descname">load</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>cls</em><span class="optional">[</span>, <em>object_hook</em><span class="optional">[</span>, <em>parse_float</em><span class="optional">[</span>, <em>parse_int</em><span class="optional">[</span>, <em>parse_constant</em><span class="optional">[</span>, <em>object_pairs_hook</em><span class="optional">[</span>, <em>**kw</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#json.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Deserialize <em>fp</em> (a <code class="docutils literal notranslate"><span class="pre">.read()</span></code>-supporting <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a>
containing a JSON document) to a Python object using this <a class="reference internal" href="#json-to-py-table"><span class="std std-ref">conversion
table</span></a>.</p>
<p>If the contents of <em>fp</em> are encoded with an ASCII based encoding other than
UTF-8 (e.g. latin-1), then an appropriate <em>encoding</em> name must be specified.
Encodings that are not ASCII based (such as UCS-2) are not allowed, and
should be wrapped with <code class="docutils literal notranslate"><span class="pre">codecs.getreader(encoding)(fp)</span></code>, or simply decoded
to a <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> object and passed to <a class="reference internal" href="#json.loads" title="json.loads"><code class="xref py py-func docutils literal notranslate"><span class="pre">loads()</span></code></a>.</p>
<p><em>object_hook</em> is an optional function that will be called with the result of
any object literal decoded (a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>).  The return value of
<em>object_hook</em> will be used instead of the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  This feature can be used
to implement custom decoders (e.g. <a class="reference external" href="http://www.jsonrpc.org">JSON-RPC</a>
class hinting).</p>
<p><em>object_pairs_hook</em> is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs.  The
return value of <em>object_pairs_hook</em> will be used instead of the
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  This feature can be used to implement custom decoders that
rely on the order that the key and value pairs are decoded (for example,
<a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.OrderedDict()</span></code></a> will remember the order of insertion). If
<em>object_hook</em> is also defined, the <em>object_pairs_hook</em> takes priority.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added support for <em>object_pairs_hook</em>.</p>
</div>
<p><em>parse_float</em>, if specified, will be called with the string of every JSON
float to be decoded.  By default, this is equivalent to <code class="docutils literal notranslate"><span class="pre">float(num_str)</span></code>.
This can be used to use another datatype or parser for JSON floats
(e.g. <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a>).</p>
<p><em>parse_int</em>, if specified, will be called with the string of every JSON int
to be decoded.  By default, this is equivalent to <code class="docutils literal notranslate"><span class="pre">int(num_str)</span></code>.  This can
be used to use another datatype or parser for JSON integers
(e.g. <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>).</p>
<p><em>parse_constant</em>, if specified, will be called with one of the following
strings: <code class="docutils literal notranslate"><span class="pre">'-Infinity'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Infinity'</span></code>, <code class="docutils literal notranslate"><span class="pre">'NaN'</span></code>.
This can be used to raise an exception if invalid JSON numbers
are encountered.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>parse_constant</em> doesn’t get called on ‘null’, ‘true’, ‘false’ anymore.</p>
</div>
<p>To use a custom <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONDecoder</span></code></a> subclass, specify it with the <code class="docutils literal notranslate"><span class="pre">cls</span></code>
kwarg; otherwise <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONDecoder</span></code></a> is used.  Additional keyword arguments
will be passed to the constructor of the class.</p>
</dd></dl>

<dl class="function">
<dt id="json.loads">
<code class="descclassname">json.</code><code class="descname">loads</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>cls</em><span class="optional">[</span>, <em>object_hook</em><span class="optional">[</span>, <em>parse_float</em><span class="optional">[</span>, <em>parse_int</em><span class="optional">[</span>, <em>parse_constant</em><span class="optional">[</span>, <em>object_pairs_hook</em><span class="optional">[</span>, <em>**kw</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#json.loads" title="Permalink to this definition">¶</a></dt>
<dd><p>Deserialize <em>s</em> (a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> instance containing a JSON
document) to a Python object using this <a class="reference internal" href="#json-to-py-table"><span class="std std-ref">conversion table</span></a>.</p>
<p>If <em>s</em> is a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> instance and is encoded with an ASCII based encoding
other than UTF-8 (e.g. latin-1), then an appropriate <em>encoding</em> name must be
specified.  Encodings that are not ASCII based (such as UCS-2) are not
allowed and should be decoded to <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> first.</p>
<p>The other arguments have the same meaning as in <a class="reference internal" href="#json.load" title="json.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="encoders-and-decoders">
<h2>18.2.2. Encoders and Decoders<a class="headerlink" href="#encoders-and-decoders" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="json.JSONDecoder">
<em class="property">class </em><code class="descclassname">json.</code><code class="descname">JSONDecoder</code><span class="sig-paren">(</span><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>object_hook</em><span class="optional">[</span>, <em>parse_float</em><span class="optional">[</span>, <em>parse_int</em><span class="optional">[</span>, <em>parse_constant</em><span class="optional">[</span>, <em>strict</em><span class="optional">[</span>, <em>object_pairs_hook</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONDecoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Simple JSON decoder.</p>
<p>Performs the following translations in decoding by default:</p>
<table border="1" class="docutils" id="json-to-py-table">
<colgroup>
<col width="44%" />
<col width="56%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">JSON</th>
<th class="head">Python</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>object</td>
<td>dict</td>
</tr>
<tr class="row-odd"><td>array</td>
<td>list</td>
</tr>
<tr class="row-even"><td>string</td>
<td>unicode</td>
</tr>
<tr class="row-odd"><td>number (int)</td>
<td>int, long</td>
</tr>
<tr class="row-even"><td>number (real)</td>
<td>float</td>
</tr>
<tr class="row-odd"><td>true</td>
<td>True</td>
</tr>
<tr class="row-even"><td>false</td>
<td>False</td>
</tr>
<tr class="row-odd"><td>null</td>
<td>None</td>
</tr>
</tbody>
</table>
<p>It also understands <code class="docutils literal notranslate"><span class="pre">NaN</span></code>, <code class="docutils literal notranslate"><span class="pre">Infinity</span></code>, and <code class="docutils literal notranslate"><span class="pre">-Infinity</span></code> as their
corresponding <code class="docutils literal notranslate"><span class="pre">float</span></code> values, which is outside the JSON spec.</p>
<p><em>encoding</em> determines the encoding used to interpret any <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> objects
decoded by this instance (UTF-8 by default).  It has no effect when decoding
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> objects.</p>
<p>Note that currently only encodings that are a superset of ASCII work, strings
of other encodings should be passed in as <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.</p>
<p><em>object_hook</em>, if specified, will be called with the result of every JSON
object decoded and its return value will be used in place of the given
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  This can be used to provide custom deserializations (e.g. to
support JSON-RPC class hinting).</p>
<p><em>object_pairs_hook</em>, if specified will be called with the result of every
JSON object decoded with an ordered list of pairs.  The return value of
<em>object_pairs_hook</em> will be used instead of the <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  This
feature can be used to implement custom decoders that rely on the order
that the key and value pairs are decoded (for example,
<a class="reference internal" href="collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.OrderedDict()</span></code></a> will remember the order of insertion). If
<em>object_hook</em> is also defined, the <em>object_pairs_hook</em> takes priority.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added support for <em>object_pairs_hook</em>.</p>
</div>
<p><em>parse_float</em>, if specified, will be called with the string of every JSON
float to be decoded.  By default, this is equivalent to <code class="docutils literal notranslate"><span class="pre">float(num_str)</span></code>.
This can be used to use another datatype or parser for JSON floats
(e.g. <a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a>).</p>
<p><em>parse_int</em>, if specified, will be called with the string of every JSON int
to be decoded.  By default, this is equivalent to <code class="docutils literal notranslate"><span class="pre">int(num_str)</span></code>.  This can
be used to use another datatype or parser for JSON integers
(e.g. <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>).</p>
<p><em>parse_constant</em>, if specified, will be called with one of the following
strings: <code class="docutils literal notranslate"><span class="pre">'-Infinity'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Infinity'</span></code>, <code class="docutils literal notranslate"><span class="pre">'NaN'</span></code>.
This can be used to raise an exception if invalid JSON numbers
are encountered.</p>
<p>If <em>strict</em> is false (<code class="docutils literal notranslate"><span class="pre">True</span></code> is the default), then control characters
will be allowed inside strings.  Control characters in this context are
those with character codes in the 0–31 range, including <code class="docutils literal notranslate"><span class="pre">'\t'</span></code> (tab),
<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code> and <code class="docutils literal notranslate"><span class="pre">'\0'</span></code>.</p>
<p>If the data being deserialized is not a valid JSON document, a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised.</p>
<dl class="method">
<dt id="json.JSONDecoder.decode">
<code class="descname">decode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONDecoder.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Python representation of <em>s</em> (a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> instance containing a JSON document).</p>
</dd></dl>

<dl class="method">
<dt id="json.JSONDecoder.raw_decode">
<code class="descname">raw_decode</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONDecoder.raw_decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode a JSON document from <em>s</em> (a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>
beginning with a JSON document) and return a 2-tuple of the Python
representation and the index in <em>s</em> where the document ended.</p>
<p>This can be used to decode a JSON document from a string that may have
extraneous data at the end.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="json.JSONEncoder">
<em class="property">class </em><code class="descclassname">json.</code><code class="descname">JSONEncoder</code><span class="sig-paren">(</span><span class="optional">[</span><em>skipkeys</em><span class="optional">[</span>, <em>ensure_ascii</em><span class="optional">[</span>, <em>check_circular</em><span class="optional">[</span>, <em>allow_nan</em><span class="optional">[</span>, <em>sort_keys</em><span class="optional">[</span>, <em>indent</em><span class="optional">[</span>, <em>separators</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONEncoder" title="Permalink to this definition">¶</a></dt>
<dd><p>Extensible JSON encoder for Python data structures.</p>
<p>Supports the following objects and types by default:</p>
<table border="1" class="docutils" id="py-to-json-table">
<colgroup>
<col width="56%" />
<col width="44%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Python</th>
<th class="head">JSON</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>dict</td>
<td>object</td>
</tr>
<tr class="row-odd"><td>list, tuple</td>
<td>array</td>
</tr>
<tr class="row-even"><td>str, unicode</td>
<td>string</td>
</tr>
<tr class="row-odd"><td>int, long, float</td>
<td>number</td>
</tr>
<tr class="row-even"><td>True</td>
<td>true</td>
</tr>
<tr class="row-odd"><td>False</td>
<td>false</td>
</tr>
<tr class="row-even"><td>None</td>
<td>null</td>
</tr>
</tbody>
</table>
<p>To extend this to recognize other objects, subclass and implement a
<a class="reference internal" href="#json.JSONEncoder.default" title="json.JSONEncoder.default"><code class="xref py py-meth docutils literal notranslate"><span class="pre">default()</span></code></a> method with another method that returns a serializable object
for <code class="docutils literal notranslate"><span class="pre">o</span></code> if possible, otherwise it should call the superclass implementation
(to raise <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>).</p>
<p>If <em>skipkeys</em> is false (the default), then it is a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to
attempt encoding of keys that are not str, int, long, float or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If
<em>skipkeys</em> is true, such items are simply skipped.</p>
<p>If <em>ensure_ascii</em> is true (the default), all non-ASCII characters in the
output are escaped with <code class="docutils literal notranslate"><span class="pre">\uXXXX</span></code> sequences, and the results are
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> instances consisting of ASCII characters only. If
<em>ensure_ascii</em> is false, a result may be a <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>
instance. This usually happens if the input contains unicode strings or the
<em>encoding</em> parameter is used.</p>
<p>If <em>check_circular</em> is true (the default), then lists, dicts, and custom
encoded objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>).
Otherwise, no such check takes place.</p>
<p>If <em>allow_nan</em> is true (the default), then <code class="docutils literal notranslate"><span class="pre">NaN</span></code>, <code class="docutils literal notranslate"><span class="pre">Infinity</span></code>, and
<code class="docutils literal notranslate"><span class="pre">-Infinity</span></code> will be encoded as such.  This behavior is not JSON
specification compliant, but is consistent with most JavaScript based
encoders and decoders.  Otherwise, it will be a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to encode
such floats.</p>
<p>If <em>sort_keys</em> is true (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>), then the output of dictionaries
will be sorted by key; this is useful for regression tests to ensure that
JSON serializations can be compared on a day-to-day basis.</p>
<p>If <em>indent</em> is a non-negative integer (it is <code class="docutils literal notranslate"><span class="pre">None</span></code> by default), then JSON
array elements and object members will be pretty-printed with that indent
level.  An indent level of 0 will only insert newlines.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is the most
compact representation.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since the default item separator is <code class="docutils literal notranslate"><span class="pre">',</span> <span class="pre">'</span></code>,  the output might include
trailing whitespace when <em>indent</em> is specified.  You can use
<code class="docutils literal notranslate"><span class="pre">separators=(',',</span> <span class="pre">':</span> <span class="pre">')</span></code> to avoid this.</p>
</div>
<p>If specified, <em>separators</em> should be an <code class="docutils literal notranslate"><span class="pre">(item_separator,</span> <span class="pre">key_separator)</span></code>
tuple.  By default, <code class="docutils literal notranslate"><span class="pre">(',</span> <span class="pre">',</span> <span class="pre">':</span> <span class="pre">')</span></code> are used.  To get the most compact JSON
representation, you should specify <code class="docutils literal notranslate"><span class="pre">(',',</span> <span class="pre">':')</span></code> to eliminate whitespace.</p>
<p>If specified, <em>default</em> should be a function that gets called for objects that
can’t otherwise be serialized.  It should return a JSON encodable version of
the object or raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  If not specified, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
is raised.</p>
<p>If <em>encoding</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, then all input strings will be transformed
into unicode using that encoding prior to JSON-encoding.  The default is
UTF-8.</p>
<dl class="method">
<dt id="json.JSONEncoder.default">
<code class="descname">default</code><span class="sig-paren">(</span><em>o</em><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONEncoder.default" title="Permalink to this definition">¶</a></dt>
<dd><p>Implement this method in a subclass such that it returns a serializable
object for <em>o</em>, or calls the base implementation (to raise a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>).</p>
<p>For example, to support arbitrary iterators, you could implement default
like this:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">o</span><span class="p">):</span>
   <span class="k">try</span><span class="p">:</span>
       <span class="n">iterable</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>
   <span class="k">except</span> <span class="ne">TypeError</span><span class="p">:</span>
       <span class="k">pass</span>
   <span class="k">else</span><span class="p">:</span>
       <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>
   <span class="c1"># Let the base class default method raise the TypeError</span>
   <span class="k">return</span> <span class="n">JSONEncoder</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">o</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="json.JSONEncoder.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><em>o</em><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONEncoder.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a JSON string representation of a Python data structure, <em>o</em>.  For
example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">JSONEncoder</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">({</span><span class="s2">&quot;foo&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;bar&quot;</span><span class="p">,</span> <span class="s2">&quot;baz&quot;</span><span class="p">]})</span>
<span class="go">&#39;{&quot;foo&quot;: [&quot;bar&quot;, &quot;baz&quot;]}&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="json.JSONEncoder.iterencode">
<code class="descname">iterencode</code><span class="sig-paren">(</span><em>o</em><span class="sig-paren">)</span><a class="headerlink" href="#json.JSONEncoder.iterencode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the given object, <em>o</em>, and yield each string representation as
available.  For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">JSONEncoder</span><span class="p">()</span><span class="o">.</span><span class="n">iterencode</span><span class="p">(</span><span class="n">bigobject</span><span class="p">):</span>
    <span class="n">mysocket</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="standard-compliance-and-interoperability">
<h2>18.2.3. Standard Compliance and Interoperability<a class="headerlink" href="#standard-compliance-and-interoperability" title="Permalink to this headline">¶</a></h2>
<p>The JSON format is specified by <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7159.html"><strong>RFC 7159</strong></a> and by
<a class="reference external" href="http://www.ecma-international.org/publications/standards/Ecma-404.htm">ECMA-404</a>.
This section details this module’s level of compliance with the RFC.
For simplicity, <a class="reference internal" href="#json.JSONEncoder" title="json.JSONEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONEncoder</span></code></a> and <a class="reference internal" href="#json.JSONDecoder" title="json.JSONDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONDecoder</span></code></a> subclasses, and
parameters other than those explicitly mentioned, are not considered.</p>
<p>This module does not comply with the RFC in a strict fashion, implementing some
extensions that are valid JavaScript but not valid JSON.  In particular:</p>
<ul class="simple">
<li>Infinite and NaN number values are accepted and output;</li>
<li>Repeated names within an object are accepted, and only the value of the last
name-value pair is used.</li>
</ul>
<p>Since the RFC permits RFC-compliant parsers to accept input texts that are not
RFC-compliant, this module’s deserializer is technically RFC-compliant under
default settings.</p>
<div class="section" id="character-encodings">
<h3>18.2.3.1. Character Encodings<a class="headerlink" href="#character-encodings" title="Permalink to this headline">¶</a></h3>
<p>The RFC requires that JSON be represented using either UTF-8, UTF-16, or
UTF-32, with UTF-8 being the recommended default for maximum interoperability.
Accordingly, this module uses UTF-8 as the default for its <em>encoding</em> parameter.</p>
<p>This module’s deserializer only directly works with ASCII-compatible encodings;
UTF-16, UTF-32, and other ASCII-incompatible encodings require the use of
workarounds described in the documentation for the deserializer’s <em>encoding</em>
parameter.</p>
<p>As permitted, though not required, by the RFC, this module’s serializer sets
<em>ensure_ascii=True</em> by default, thus escaping the output so that the resulting
strings only contain ASCII characters.</p>
<p>The RFC prohibits adding a byte order mark (BOM) to the start of a JSON text,
and this module’s serializer does not add a BOM to its output.
The RFC permits, but does not require, JSON deserializers to ignore an initial
BOM in their input.  This module’s deserializer raises a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
when an initial BOM is present.</p>
<p>The RFC does not explicitly forbid JSON strings which contain byte sequences
that don’t correspond to valid Unicode characters (e.g. unpaired UTF-16
surrogates), but it does note that they may cause interoperability problems.
By default, this module accepts and outputs (when present in the original
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>) code points for such sequences.</p>
</div>
<div class="section" id="infinite-and-nan-number-values">
<h3>18.2.3.2. Infinite and NaN Number Values<a class="headerlink" href="#infinite-and-nan-number-values" title="Permalink to this headline">¶</a></h3>
<p>The RFC does not permit the representation of infinite or NaN number values.
Despite that, by default, this module accepts and outputs <code class="docutils literal notranslate"><span class="pre">Infinity</span></code>,
<code class="docutils literal notranslate"><span class="pre">-Infinity</span></code>, and <code class="docutils literal notranslate"><span class="pre">NaN</span></code> as if they were valid JSON number literal values:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Neither of these calls raises an exception, but the results are not valid JSON</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="s1">&#39;-inf&#39;</span><span class="p">))</span>
<span class="go">&#39;-Infinity&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="s1">&#39;nan&#39;</span><span class="p">))</span>
<span class="go">&#39;NaN&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Same when deserializing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;-Infinity&#39;</span><span class="p">)</span>
<span class="go">-inf</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">)</span>
<span class="go">nan</span>
</pre></div>
</div>
<p>In the serializer, the <em>allow_nan</em> parameter can be used to alter this
behavior.  In the deserializer, the <em>parse_constant</em> parameter can be used to
alter this behavior.</p>
</div>
<div class="section" id="repeated-names-within-an-object">
<h3>18.2.3.3. Repeated Names Within an Object<a class="headerlink" href="#repeated-names-within-an-object" title="Permalink to this headline">¶</a></h3>
<p>The RFC specifies that the names within a JSON object should be unique, but
does not mandate how repeated names in JSON objects should be handled.  By
default, this module does not raise an exception; instead, it ignores all but
the last name-value pair for a given name:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">weird_json</span> <span class="o">=</span> <span class="s1">&#39;{&quot;x&quot;: 1, &quot;x&quot;: 2, &quot;x&quot;: 3}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">weird_json</span><span class="p">)</span>
<span class="go">{u&#39;x&#39;: 3}</span>
</pre></div>
</div>
<p>The <em>object_pairs_hook</em> parameter can be used to alter this behavior.</p>
</div>
<div class="section" id="top-level-non-object-non-array-values">
<h3>18.2.3.4. Top-level Non-Object, Non-Array Values<a class="headerlink" href="#top-level-non-object-non-array-values" title="Permalink to this headline">¶</a></h3>
<p>The old version of JSON specified by the obsolete <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4627.html"><strong>RFC 4627</strong></a> required that
the top-level value of a JSON text must be either a JSON object or array
(Python <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> or <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>), and could not be a JSON null,
boolean, number, or string value.  <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7159.html"><strong>RFC 7159</strong></a> removed that restriction, and
this module does not and has never implemented that restriction in either its
serializer or its deserializer.</p>
<p>Regardless, for maximum interoperability, you may wish to voluntarily adhere
to the restriction yourself.</p>
</div>
<div class="section" id="implementation-limitations">
<h3>18.2.3.5. Implementation Limitations<a class="headerlink" href="#implementation-limitations" title="Permalink to this headline">¶</a></h3>
<p>Some JSON deserializer implementations may set limits on:</p>
<ul class="simple">
<li>the size of accepted JSON texts</li>
<li>the maximum level of nesting of JSON objects and arrays</li>
<li>the range and precision of JSON numbers</li>
<li>the content and maximum length of JSON strings</li>
</ul>
<p>This module does not impose any such limits beyond those of the relevant
Python datatypes themselves or the Python interpreter itself.</p>
<p>When serializing to JSON, beware any such limitations in applications that may
consume your JSON.  In particular, it is common for JSON numbers to be
deserialized into IEEE 754 double precision numbers and thus subject to that
representation’s range and precision limitations.  This is especially relevant
when serializing Python <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> values of extremely large magnitude, or
when serializing instances of “exotic” numerical types such as
<a class="reference internal" href="decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a>.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="rfc-errata" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>As noted in <a class="reference external" href="https://www.rfc-editor.org/errata_search.php?rfc=7159">the errata for RFC 7159</a>,
JSON permits literal U+2028 (LINE SEPARATOR) and
U+2029 (PARAGRAPH SEPARATOR) characters in strings, whereas JavaScript
(as of ECMAScript Edition 5.1) does not.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a><ul>
<li><a class="reference internal" href="#basic-usage">18.2.1. Basic Usage</a></li>
<li><a class="reference internal" href="#encoders-and-decoders">18.2.2. Encoders and Decoders</a></li>
<li><a class="reference internal" href="#standard-compliance-and-interoperability">18.2.3. Standard Compliance and Interoperability</a><ul>
<li><a class="reference internal" href="#character-encodings">18.2.3.1. Character Encodings</a></li>
<li><a class="reference internal" href="#infinite-and-nan-number-values">18.2.3.2. Infinite and NaN Number Values</a></li>
<li><a class="reference internal" href="#repeated-names-within-an-object">18.2.3.3. Repeated Names Within an Object</a></li>
<li><a class="reference internal" href="#top-level-non-object-non-array-values">18.2.3.4. Top-level Non-Object, Non-Array Values</a></li>
<li><a class="reference internal" href="#implementation-limitations">18.2.3.5. Implementation Limitations</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="email-examples.html"
                        title="previous chapter">18.1.11. <code class="docutils literal notranslate"><span class="pre">email</span></code>: Examples</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mailcap.html"
                        title="next chapter">18.3. <code class="docutils literal notranslate"><span class="pre">mailcap</span></code> — Mailcap file handling</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/json.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mailcap.html" title="18.3. mailcap — Mailcap file handling"
             >next</a> |</li>
        <li class="right" >
          <a href="email-examples.html" title="18.1.11. email: Examples"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���U  html/library/keyword.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.6. keyword — Testing for Python keywords &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.7. tokenize — Tokenizer for Python source" href="tokenize.html" />
    <link rel="prev" title="32.5. token — Constants used with Python parse trees" href="token.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/keyword.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tokenize.html" title="32.7. tokenize — Tokenizer for Python source"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="token.html" title="32.5. token — Constants used with Python parse trees"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-keyword">
<span id="keyword-testing-for-python-keywords"></span><h1>32.6. <a class="reference internal" href="#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> — Testing for Python keywords<a class="headerlink" href="#module-keyword" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/keyword.py">Lib/keyword.py</a></p>
<hr class="docutils" />
<p>This module allows a Python program to determine if a string is a keyword.</p>
<dl class="function">
<dt id="keyword.iskeyword">
<code class="descclassname">keyword.</code><code class="descname">iskeyword</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#keyword.iskeyword" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>s</em> is a Python keyword.</p>
</dd></dl>

<dl class="data">
<dt id="keyword.kwlist">
<code class="descclassname">keyword.</code><code class="descname">kwlist</code><a class="headerlink" href="#keyword.kwlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence containing all the keywords defined for the interpreter.  If any
keywords are defined to only be active when particular <a class="reference internal" href="__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a>
statements are in effect, these will be included as well.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="token.html"
                        title="previous chapter">32.5. <code class="docutils literal notranslate"><span class="pre">token</span></code> — Constants used with Python parse trees</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tokenize.html"
                        title="next chapter">32.7. <code class="docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/keyword.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tokenize.html" title="32.7. tokenize — Tokenizer for Python source"
             >next</a> |</li>
        <li class="right" >
          <a href="token.html" title="32.5. token — Constants used with Python parse trees"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\3�2��-�-html/library/language.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32. Python Language Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.1. parser — Access Python parse trees" href="parser.html" />
    <link rel="prev" title="31.7. runpy — Locating and executing Python modules" href="runpy.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/language.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="parser.html" title="32.1. parser — Access Python parse trees"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="runpy.html" title="31.7. runpy — Locating and executing Python modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-language-services">
<span id="language"></span><h1>32. Python Language Services<a class="headerlink" href="#python-language-services" title="Permalink to this headline">¶</a></h1>
<p>Python provides a number of modules to assist in working with the Python
language.  These modules support tokenizing, parsing, syntax analysis, bytecode
disassembly, and various other facilities.</p>
<p>These modules include:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="parser.html">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a><ul>
<li class="toctree-l2"><a class="reference internal" href="parser.html#creating-st-objects">32.1.1. Creating ST Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="parser.html#converting-st-objects">32.1.2. Converting ST Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="parser.html#queries-on-st-objects">32.1.3. Queries on ST Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="parser.html#exceptions-and-error-handling">32.1.4. Exceptions and Error Handling</a></li>
<li class="toctree-l2"><a class="reference internal" href="parser.html#st-objects">32.1.5. ST Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="parser.html#example-emulation-of-compile">32.1.6. Example: Emulation of <code class="docutils literal notranslate"><span class="pre">compile()</span></code></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="ast.html">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ast.html#node-classes">32.2.1. Node classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="ast.html#abstract-grammar">32.2.2. Abstract Grammar</a></li>
<li class="toctree-l2"><a class="reference internal" href="ast.html#ast-helpers">32.2.3. <code class="docutils literal notranslate"><span class="pre">ast</span></code> Helpers</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="symtable.html">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a><ul>
<li class="toctree-l2"><a class="reference internal" href="symtable.html#generating-symbol-tables">32.3.1. Generating Symbol Tables</a></li>
<li class="toctree-l2"><a class="reference internal" href="symtable.html#examining-symbol-tables">32.3.2. Examining Symbol Tables</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="symbol.html">32.4. <code class="docutils literal notranslate"><span class="pre">symbol</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l1"><a class="reference internal" href="token.html">32.5. <code class="docutils literal notranslate"><span class="pre">token</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l1"><a class="reference internal" href="keyword.html">32.6. <code class="docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></li>
<li class="toctree-l1"><a class="reference internal" href="tokenize.html">32.7. <code class="docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></li>
<li class="toctree-l1"><a class="reference internal" href="tabnanny.html">32.8. <code class="docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="pyclbr.html">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pyclbr.html#class-objects">32.9.1. Class Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyclbr.html#function-objects">32.9.2. Function Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="py_compile.html">32.10. <code class="docutils literal notranslate"><span class="pre">py_compile</span></code> — Compile Python source files</a></li>
<li class="toctree-l1"><a class="reference internal" href="compileall.html">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a><ul>
<li class="toctree-l2"><a class="reference internal" href="compileall.html#command-line-use">32.11.1. Command-line use</a></li>
<li class="toctree-l2"><a class="reference internal" href="compileall.html#public-functions">32.11.2. Public functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="dis.html">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a><ul>
<li class="toctree-l2"><a class="reference internal" href="dis.html#python-bytecode-instructions">32.12.1. Python Bytecode Instructions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="pickletools.html">32.13. <code class="docutils literal notranslate"><span class="pre">pickletools</span></code> — Tools for pickle developers</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="runpy.html"
                        title="previous chapter">31.7. <code class="docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="parser.html"
                        title="next chapter">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/language.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="parser.html" title="32.1. parser — Access Python parse trees"
             >next</a> |</li>
        <li class="right" >
          <a href="runpy.html" title="31.7. runpy — Locating and executing Python modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�d�&�,�,html/library/linecache.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.9. linecache — Random access to text lines &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.10. shutil — High-level file operations" href="shutil.html" />
    <link rel="prev" title="10.8. fnmatch — Unix filename pattern matching" href="fnmatch.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/linecache.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shutil.html" title="10.10. shutil — High-level file operations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fnmatch.html" title="10.8. fnmatch — Unix filename pattern matching"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-linecache">
<span id="linecache-random-access-to-text-lines"></span><h1>10.9. <a class="reference internal" href="#module-linecache" title="linecache: This module provides random access to individual lines from text files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">linecache</span></code></a> — Random access to text lines<a class="headerlink" href="#module-linecache" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/linecache.py">Lib/linecache.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-linecache" title="linecache: This module provides random access to individual lines from text files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">linecache</span></code></a> module allows one to get any line from any file, while
attempting to optimize internally, using a cache, the common case where many
lines are read from a single file.  This is used by the <a class="reference internal" href="traceback.html#module-traceback" title="traceback: Print or retrieve a stack traceback."><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code></a> module
to retrieve source lines for inclusion in  the formatted traceback.</p>
<p>The <a class="reference internal" href="#module-linecache" title="linecache: This module provides random access to individual lines from text files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">linecache</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="linecache.getline">
<code class="descclassname">linecache.</code><code class="descname">getline</code><span class="sig-paren">(</span><em>filename</em>, <em>lineno</em><span class="optional">[</span>, <em>module_globals</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#linecache.getline" title="Permalink to this definition">¶</a></dt>
<dd><p>Get line <em>lineno</em> from file named <em>filename</em>. This function will never raise an
exception — it will return <code class="docutils literal notranslate"><span class="pre">''</span></code> on errors (the terminating newline character
will be included for lines that are found).</p>
<p id="index-0">If a file named <em>filename</em> is not found, the function will look for it in the
module search path, <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, after first checking for a <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>
<code class="docutils literal notranslate"><span class="pre">__loader__</span></code> in <em>module_globals</em>, in case the module was imported from a
zipfile or other non-filesystem import source.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>The <em>module_globals</em> parameter was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="linecache.clearcache">
<code class="descclassname">linecache.</code><code class="descname">clearcache</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#linecache.clearcache" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the cache.  Use this function if you no longer need lines from files
previously read using <a class="reference internal" href="#linecache.getline" title="linecache.getline"><code class="xref py py-func docutils literal notranslate"><span class="pre">getline()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="linecache.checkcache">
<code class="descclassname">linecache.</code><code class="descname">checkcache</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#linecache.checkcache" title="Permalink to this definition">¶</a></dt>
<dd><p>Check the cache for validity.  Use this function if files in the cache  may have
changed on disk, and you require the updated version.  If <em>filename</em> is omitted,
it will check all the entries in the cache.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">linecache</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">linecache</span><span class="o">.</span><span class="n">getline</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">&#39;sys:x:3:3:sys:/dev:/bin/sh\n&#39;</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fnmatch.html"
                        title="previous chapter">10.8. <code class="docutils literal notranslate"><span class="pre">fnmatch</span></code> — Unix filename pattern matching</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="shutil.html"
                        title="next chapter">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/linecache.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="shutil.html" title="10.10. shutil — High-level file operations"
             >next</a> |</li>
        <li class="right" >
          <a href="fnmatch.html" title="10.8. fnmatch — Unix filename pattern matching"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�0&����html/library/locale.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>22.2. locale — Internationalization services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="23. Program Frameworks" href="frameworks.html" />
    <link rel="prev" title="22.1. gettext — Multilingual internationalization services" href="gettext.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/locale.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="frameworks.html" title="23. Program Frameworks"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="gettext.html" title="22.1. gettext — Multilingual internationalization services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="i18n.html" accesskey="U">22. Internationalization</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-locale">
<span id="locale-internationalization-services"></span><h1>22.2. <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> — Internationalization services<a class="headerlink" href="#module-locale" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module opens access to the POSIX locale database and
functionality. The POSIX locale mechanism allows programmers to deal with
certain cultural issues in an application, without requiring the programmer to
know all the specifics of each country where the software is executed.</p>
<p id="index-0">The <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module is implemented on top of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_locale</span></code> module,
which in turn uses an ANSI C locale implementation if available.</p>
<p>The <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module defines the following exception and functions:</p>
<dl class="exception">
<dt id="locale.Error">
<em class="property">exception </em><code class="descclassname">locale.</code><code class="descname">Error</code><a class="headerlink" href="#locale.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when the locale passed to <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> is not
recognized.</p>
</dd></dl>

<dl class="function">
<dt id="locale.setlocale">
<code class="descclassname">locale.</code><code class="descname">setlocale</code><span class="sig-paren">(</span><em>category</em><span class="optional">[</span>, <em>locale</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.setlocale" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>locale</em> is given and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> modifies the locale
setting for the <em>category</em>. The available categories are listed in the data
description below. <em>locale</em> may be a string, or an iterable of two strings
(language code and encoding). If it’s an iterable, it’s converted to a locale
name using the locale aliasing engine. An empty string specifies the user’s
default settings. If the modification of the locale fails, the exception
<a class="reference internal" href="#locale.Error" title="locale.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised. If successful, the new locale setting is returned.</p>
<p>If <em>locale</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the current setting for <em>category</em> is
returned.</p>
<p><a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> is not thread-safe on most systems. Applications typically
start with a call of</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">locale</span>
<span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This sets the locale for all categories to the user’s default setting (typically
specified in the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANG</span></code> environment variable).  If the locale is not
changed thereafter, using multithreading should not cause problems.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.0: </span>Added support for iterable values of the <em>locale</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.localeconv">
<code class="descclassname">locale.</code><code class="descname">localeconv</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.localeconv" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the database of the local conventions as a dictionary. This dictionary
has the following strings as keys:</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="41%" />
<col width="35%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Category</th>
<th class="head">Key</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#locale.LC_NUMERIC" title="locale.LC_NUMERIC"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">'decimal_point'</span></code></td>
<td>Decimal point character.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'grouping'</span></code></td>
<td>Sequence of numbers specifying
which relative positions the
<code class="docutils literal notranslate"><span class="pre">'thousands_sep'</span></code> is
expected.  If the sequence is
terminated with
<a class="reference internal" href="#locale.CHAR_MAX" title="locale.CHAR_MAX"><code class="xref py py-const docutils literal notranslate"><span class="pre">CHAR_MAX</span></code></a>, no further
grouping is performed. If the
sequence terminates with a
<code class="docutils literal notranslate"><span class="pre">0</span></code>,  the last group size is
repeatedly used.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'thousands_sep'</span></code></td>
<td>Character used between groups.</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#locale.LC_MONETARY" title="locale.LC_MONETARY"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_MONETARY</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">'int_curr_symbol'</span></code></td>
<td>International currency symbol.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'currency_symbol'</span></code></td>
<td>Local currency symbol.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'p_cs_precedes/n_cs_precedes'</span></code></td>
<td>Whether the currency symbol
precedes the value (for
positive resp. negative
values).</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'p_sep_by_space/n_sep_by_space'</span></code></td>
<td>Whether the currency symbol is
separated from the value  by a
space (for positive resp.
negative values).</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'mon_decimal_point'</span></code></td>
<td>Decimal point used for
monetary values.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'frac_digits'</span></code></td>
<td>Number of fractional digits
used in local formatting of
monetary values.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'int_frac_digits'</span></code></td>
<td>Number of fractional digits
used in international
formatting of monetary values.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'mon_thousands_sep'</span></code></td>
<td>Group separator used for
monetary values.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'mon_grouping'</span></code></td>
<td>Equivalent to <code class="docutils literal notranslate"><span class="pre">'grouping'</span></code>,
used for monetary values.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'positive_sign'</span></code></td>
<td>Symbol used to annotate a
positive monetary value.</td>
</tr>
<tr class="row-odd"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'negative_sign'</span></code></td>
<td>Symbol used to annotate a
negative monetary value.</td>
</tr>
<tr class="row-even"><td>&#160;</td>
<td><code class="docutils literal notranslate"><span class="pre">'p_sign_posn/n_sign_posn'</span></code></td>
<td>The position of the sign (for
positive resp. negative
values), see below.</td>
</tr>
</tbody>
</table>
<p>All numeric values can be set to <a class="reference internal" href="#locale.CHAR_MAX" title="locale.CHAR_MAX"><code class="xref py py-const docutils literal notranslate"><span class="pre">CHAR_MAX</span></code></a> to indicate that there is no
value specified in this locale.</p>
<p>The possible values for <code class="docutils literal notranslate"><span class="pre">'p_sign_posn'</span></code> and <code class="docutils literal notranslate"><span class="pre">'n_sign_posn'</span></code> are given below.</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td>Currency and value are surrounded by
parentheses.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td>The sign should precede the value and
currency symbol.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">2</span></code></td>
<td>The sign should follow the value and
currency symbol.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">3</span></code></td>
<td>The sign should immediately precede the
value.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">4</span></code></td>
<td>The sign should immediately follow the
value.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">CHAR_MAX</span></code></td>
<td>Nothing is specified in this locale.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="locale.nl_langinfo">
<code class="descclassname">locale.</code><code class="descname">nl_langinfo</code><span class="sig-paren">(</span><em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.nl_langinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return some locale-specific information as a string.  This function is not
available on all systems, and the set of possible options might also vary
across platforms.  The possible argument values are numbers, for which
symbolic constants are available in the locale module.</p>
<p>The <a class="reference internal" href="#locale.nl_langinfo" title="locale.nl_langinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">nl_langinfo()</span></code></a> function accepts one of the following keys.  Most
descriptions are taken from the corresponding description in the GNU C
library.</p>
<dl class="data">
<dt id="locale.CODESET">
<code class="descclassname">locale.</code><code class="descname">CODESET</code><a class="headerlink" href="#locale.CODESET" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a string with the name of the character encoding used in the
selected locale.</p>
</dd></dl>

<dl class="data">
<dt id="locale.D_T_FMT">
<code class="descclassname">locale.</code><code class="descname">D_T_FMT</code><a class="headerlink" href="#locale.D_T_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a string that can be used as a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to
represent date and time in a locale-specific way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.D_FMT">
<code class="descclassname">locale.</code><code class="descname">D_FMT</code><a class="headerlink" href="#locale.D_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a string that can be used as a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to
represent a date in a locale-specific way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.T_FMT">
<code class="descclassname">locale.</code><code class="descname">T_FMT</code><a class="headerlink" href="#locale.T_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a string that can be used as a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to
represent a time in a locale-specific way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.T_FMT_AMPM">
<code class="descclassname">locale.</code><code class="descname">T_FMT_AMPM</code><a class="headerlink" href="#locale.T_FMT_AMPM" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to represent time in the am/pm
format.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">DAY_1 ... DAY_7</code></dt>
<dd><p>Get the name of the n-th day of the week.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This follows the US convention of <code class="xref py py-const docutils literal notranslate"><span class="pre">DAY_1</span></code> being Sunday, not the
international convention (ISO 8601) that Monday is the first day of the
week.</p>
</div>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">ABDAY_1 ... ABDAY_7</code></dt>
<dd><p>Get the abbreviated name of the n-th day of the week.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">MON_1 ... MON_12</code></dt>
<dd><p>Get the name of the n-th month.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">ABMON_1 ... ABMON_12</code></dt>
<dd><p>Get the abbreviated name of the n-th month.</p>
</dd></dl>

<dl class="data">
<dt id="locale.RADIXCHAR">
<code class="descclassname">locale.</code><code class="descname">RADIXCHAR</code><a class="headerlink" href="#locale.RADIXCHAR" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the radix character (decimal dot, decimal comma, etc.).</p>
</dd></dl>

<dl class="data">
<dt id="locale.THOUSEP">
<code class="descclassname">locale.</code><code class="descname">THOUSEP</code><a class="headerlink" href="#locale.THOUSEP" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the separator character for thousands (groups of three digits).</p>
</dd></dl>

<dl class="data">
<dt id="locale.YESEXPR">
<code class="descclassname">locale.</code><code class="descname">YESEXPR</code><a class="headerlink" href="#locale.YESEXPR" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a regular expression that can be used with the regex function to
recognize a positive response to a yes/no question.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The expression is in the syntax suitable for the <code class="xref c c-func docutils literal notranslate"><span class="pre">regex()</span></code> function
from the C library, which might differ from the syntax used in <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="locale.NOEXPR">
<code class="descclassname">locale.</code><code class="descname">NOEXPR</code><a class="headerlink" href="#locale.NOEXPR" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a regular expression that can be used with the regex(3) function to
recognize a negative response to a yes/no question.</p>
</dd></dl>

<dl class="data">
<dt id="locale.CRNCYSTR">
<code class="descclassname">locale.</code><code class="descname">CRNCYSTR</code><a class="headerlink" href="#locale.CRNCYSTR" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the currency symbol, preceded by “-” if the symbol should appear before
the value, “+” if the symbol should appear after the value, or “.” if the
symbol should replace the radix character.</p>
</dd></dl>

<dl class="data">
<dt id="locale.ERA">
<code class="descclassname">locale.</code><code class="descname">ERA</code><a class="headerlink" href="#locale.ERA" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a string that represents the era used in the current locale.</p>
<p>Most locales do not define this value.  An example of a locale which does
define this value is the Japanese one.  In Japan, the traditional
representation of dates includes the name of the era corresponding to the
then-emperor’s reign.</p>
<p>Normally it should not be necessary to use this value directly. Specifying
the <code class="docutils literal notranslate"><span class="pre">E</span></code> modifier in their format strings causes the <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>
function to use this information.  The format of the returned string is not
specified, and therefore you should not assume knowledge of it on different
systems.</p>
</dd></dl>

<dl class="data">
<dt id="locale.ERA_D_T_FMT">
<code class="descclassname">locale.</code><code class="descname">ERA_D_T_FMT</code><a class="headerlink" href="#locale.ERA_D_T_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to represent date and time in a
locale-specific era-based way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.ERA_D_FMT">
<code class="descclassname">locale.</code><code class="descname">ERA_D_FMT</code><a class="headerlink" href="#locale.ERA_D_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to represent a date in a
locale-specific era-based way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.ERA_T_FMT">
<code class="descclassname">locale.</code><code class="descname">ERA_T_FMT</code><a class="headerlink" href="#locale.ERA_T_FMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a format string for <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to represent a time in a
locale-specific era-based way.</p>
</dd></dl>

<dl class="data">
<dt id="locale.ALT_DIGITS">
<code class="descclassname">locale.</code><code class="descname">ALT_DIGITS</code><a class="headerlink" href="#locale.ALT_DIGITS" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a representation of up to 100 values used to represent the values
0 to 99.</p>
</dd></dl>

</dd></dl>

<dl class="function">
<dt id="locale.getdefaultlocale">
<code class="descclassname">locale.</code><code class="descname">getdefaultlocale</code><span class="sig-paren">(</span><span class="optional">[</span><em>envvars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.getdefaultlocale" title="Permalink to this definition">¶</a></dt>
<dd><p>Tries to determine the default locale settings and returns them as a tuple of
the form <code class="docutils literal notranslate"><span class="pre">(language</span> <span class="pre">code,</span> <span class="pre">encoding)</span></code>.</p>
<p>According to POSIX, a program which has not called <code class="docutils literal notranslate"><span class="pre">setlocale(LC_ALL,</span> <span class="pre">'')</span></code>
runs using the portable <code class="docutils literal notranslate"><span class="pre">'C'</span></code> locale.  Calling <code class="docutils literal notranslate"><span class="pre">setlocale(LC_ALL,</span> <span class="pre">'')</span></code> lets
it use the default locale as defined by the <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANG</span></code> variable.  Since we
do not want to interfere with the current locale setting we thus emulate the
behavior in the way described above.</p>
<p>To maintain compatibility with other platforms, not only the <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LANG</span></code>
variable is tested, but a list of variables given as envvars parameter.  The
first found to be defined will be used.  <em>envvars</em> defaults to the search path
used in GNU gettext; it must always contain the variable name <code class="docutils literal notranslate"><span class="pre">LANG</span></code>.  The GNU
gettext search path contains <code class="docutils literal notranslate"><span class="pre">'LANGUAGE'</span></code>, <code class="docutils literal notranslate"><span class="pre">'LC_ALL'</span></code>, <code class="docutils literal notranslate"><span class="pre">'LC_CTYPE'</span></code>, and
<code class="docutils literal notranslate"><span class="pre">'LANG'</span></code>, in that order.</p>
<p>Except for the code <code class="docutils literal notranslate"><span class="pre">'C'</span></code>, the language code corresponds to <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1766.html"><strong>RFC 1766</strong></a>.
<em>language code</em> and <em>encoding</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code> if their values cannot be
determined.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.getlocale">
<code class="descclassname">locale.</code><code class="descname">getlocale</code><span class="sig-paren">(</span><span class="optional">[</span><em>category</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.getlocale" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current setting for the given locale category as sequence containing
<em>language code</em>, <em>encoding</em>. <em>category</em> may be one of the <code class="xref py py-const docutils literal notranslate"><span class="pre">LC_*</span></code> values
except <a class="reference internal" href="#locale.LC_ALL" title="locale.LC_ALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_ALL</span></code></a>.  It defaults to <a class="reference internal" href="#locale.LC_CTYPE" title="locale.LC_CTYPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_CTYPE</span></code></a>.</p>
<p>Except for the code <code class="docutils literal notranslate"><span class="pre">'C'</span></code>, the language code corresponds to <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1766.html"><strong>RFC 1766</strong></a>.
<em>language code</em> and <em>encoding</em> may be <code class="docutils literal notranslate"><span class="pre">None</span></code> if their values cannot be
determined.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.getpreferredencoding">
<code class="descclassname">locale.</code><code class="descname">getpreferredencoding</code><span class="sig-paren">(</span><span class="optional">[</span><em>do_setlocale</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.getpreferredencoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the encoding used for text data, according to user preferences.  User
preferences are expressed differently on different systems, and might not be
available programmatically on some systems, so this function only returns a
guess.</p>
<p>On some systems, it is necessary to invoke <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> to obtain the user
preferences, so this function is not thread-safe. If invoking setlocale is not
necessary or desired, <em>do_setlocale</em> should be set to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.normalize">
<code class="descclassname">locale.</code><code class="descname">normalize</code><span class="sig-paren">(</span><em>localename</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.normalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a normalized locale code for the given locale name.  The returned locale
code is formatted for use with <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a>.  If normalization fails, the
original name is returned unchanged.</p>
<p>If the given encoding is not known, the function defaults to the default
encoding for the locale code just like <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.resetlocale">
<code class="descclassname">locale.</code><code class="descname">resetlocale</code><span class="sig-paren">(</span><span class="optional">[</span><em>category</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.resetlocale" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the locale for <em>category</em> to the default setting.</p>
<p>The default setting is determined by calling <a class="reference internal" href="#locale.getdefaultlocale" title="locale.getdefaultlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">getdefaultlocale()</span></code></a>.
<em>category</em> defaults to <a class="reference internal" href="#locale.LC_ALL" title="locale.LC_ALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_ALL</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.strcoll">
<code class="descclassname">locale.</code><code class="descname">strcoll</code><span class="sig-paren">(</span><em>string1</em>, <em>string2</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.strcoll" title="Permalink to this definition">¶</a></dt>
<dd><p>Compares two strings according to the current <a class="reference internal" href="#locale.LC_COLLATE" title="locale.LC_COLLATE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_COLLATE</span></code></a> setting. As
any other compare function, returns a negative, or a positive value, or <code class="docutils literal notranslate"><span class="pre">0</span></code>,
depending on whether <em>string1</em> collates before or after <em>string2</em> or is equal to
it.</p>
</dd></dl>

<dl class="function">
<dt id="locale.strxfrm">
<code class="descclassname">locale.</code><code class="descname">strxfrm</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.strxfrm" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">Transforms a string to one that can be used for the built-in function
<a class="reference internal" href="functions.html#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a>, and still returns locale-aware results.  This function can be used
when the same string is compared repeatedly, e.g. when collating a sequence of
strings.</p>
</dd></dl>

<dl class="function">
<dt id="locale.format">
<code class="descclassname">locale.</code><code class="descname">format</code><span class="sig-paren">(</span><em>format</em>, <em>val</em><span class="optional">[</span>, <em>grouping</em><span class="optional">[</span>, <em>monetary</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.format" title="Permalink to this definition">¶</a></dt>
<dd><p>Formats a number <em>val</em> according to the current <a class="reference internal" href="#locale.LC_NUMERIC" title="locale.LC_NUMERIC"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code></a> setting.
The format follows the conventions of the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator.  For floating point
values, the decimal point is modified if appropriate.  If <em>grouping</em> is true,
also takes the grouping into account.</p>
<p>If <em>monetary</em> is true, the conversion uses monetary thousands separator and
grouping strings.</p>
<p>Please note that this function will only work for exactly one %char specifier.
For whole format strings, use <a class="reference internal" href="#locale.format_string" title="locale.format_string"><code class="xref py py-func docutils literal notranslate"><span class="pre">format_string()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>monetary</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.format_string">
<code class="descclassname">locale.</code><code class="descname">format_string</code><span class="sig-paren">(</span><em>format</em>, <em>val</em><span class="optional">[</span>, <em>grouping</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.format_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Processes formatting specifiers as in <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">val</span></code>, but takes the current
locale settings into account.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.currency">
<code class="descclassname">locale.</code><code class="descname">currency</code><span class="sig-paren">(</span><em>val</em><span class="optional">[</span>, <em>symbol</em><span class="optional">[</span>, <em>grouping</em><span class="optional">[</span>, <em>international</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#locale.currency" title="Permalink to this definition">¶</a></dt>
<dd><p>Formats a number <em>val</em> according to the current <a class="reference internal" href="#locale.LC_MONETARY" title="locale.LC_MONETARY"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_MONETARY</span></code></a> settings.</p>
<p>The returned string includes the currency symbol if <em>symbol</em> is true, which is
the default. If <em>grouping</em> is true (which is not the default), grouping is done
with the value. If <em>international</em> is true (which is not the default), the
international currency symbol is used.</p>
<p>Note that this function will not work with the ‘C’ locale, so you have to set a
locale via <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> first.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="locale.str">
<code class="descclassname">locale.</code><code class="descname">str</code><span class="sig-paren">(</span><em>float</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.str" title="Permalink to this definition">¶</a></dt>
<dd><p>Formats a floating point number using the same format as the built-in function
<code class="docutils literal notranslate"><span class="pre">str(float)</span></code>, but takes the decimal point into account.</p>
</dd></dl>

<dl class="function">
<dt id="locale.atof">
<code class="descclassname">locale.</code><code class="descname">atof</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.atof" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts a string to a floating point number, following the <a class="reference internal" href="#locale.LC_NUMERIC" title="locale.LC_NUMERIC"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code></a>
settings.</p>
</dd></dl>

<dl class="function">
<dt id="locale.atoi">
<code class="descclassname">locale.</code><code class="descname">atoi</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.atoi" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts a string to an integer, following the <a class="reference internal" href="#locale.LC_NUMERIC" title="locale.LC_NUMERIC"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_NUMERIC</span></code></a> conventions.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_CTYPE">
<code class="descclassname">locale.</code><code class="descname">LC_CTYPE</code><a class="headerlink" href="#locale.LC_CTYPE" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-7">Locale category for the character type functions.  Depending on the settings of
this category, the functions of module <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> dealing with case change
their behaviour.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_COLLATE">
<code class="descclassname">locale.</code><code class="descname">LC_COLLATE</code><a class="headerlink" href="#locale.LC_COLLATE" title="Permalink to this definition">¶</a></dt>
<dd><p>Locale category for sorting strings.  The functions <a class="reference internal" href="#locale.strcoll" title="locale.strcoll"><code class="xref py py-func docutils literal notranslate"><span class="pre">strcoll()</span></code></a> and
<a class="reference internal" href="#locale.strxfrm" title="locale.strxfrm"><code class="xref py py-func docutils literal notranslate"><span class="pre">strxfrm()</span></code></a> of the <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module are affected.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_TIME">
<code class="descclassname">locale.</code><code class="descname">LC_TIME</code><a class="headerlink" href="#locale.LC_TIME" title="Permalink to this definition">¶</a></dt>
<dd><p>Locale category for the formatting of time.  The function <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>
follows these conventions.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_MONETARY">
<code class="descclassname">locale.</code><code class="descname">LC_MONETARY</code><a class="headerlink" href="#locale.LC_MONETARY" title="Permalink to this definition">¶</a></dt>
<dd><p>Locale category for formatting of monetary values.  The available options are
available from the <a class="reference internal" href="#locale.localeconv" title="locale.localeconv"><code class="xref py py-func docutils literal notranslate"><span class="pre">localeconv()</span></code></a> function.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_MESSAGES">
<code class="descclassname">locale.</code><code class="descname">LC_MESSAGES</code><a class="headerlink" href="#locale.LC_MESSAGES" title="Permalink to this definition">¶</a></dt>
<dd><p>Locale category for message display. Python currently does not support
application specific locale-aware messages.  Messages displayed by the operating
system, like those returned by <a class="reference internal" href="os.html#os.strerror" title="os.strerror"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.strerror()</span></code></a> might be affected by this
category.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_NUMERIC">
<code class="descclassname">locale.</code><code class="descname">LC_NUMERIC</code><a class="headerlink" href="#locale.LC_NUMERIC" title="Permalink to this definition">¶</a></dt>
<dd><p>Locale category for formatting numbers.  The functions <a class="reference internal" href="#locale.format" title="locale.format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a>,
<a class="reference internal" href="#locale.atoi" title="locale.atoi"><code class="xref py py-func docutils literal notranslate"><span class="pre">atoi()</span></code></a>, <a class="reference internal" href="#locale.atof" title="locale.atof"><code class="xref py py-func docutils literal notranslate"><span class="pre">atof()</span></code></a> and <a class="reference internal" href="#locale.str" title="locale.str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module are
affected by that category.  All other numeric formatting operations are not
affected.</p>
</dd></dl>

<dl class="data">
<dt id="locale.LC_ALL">
<code class="descclassname">locale.</code><code class="descname">LC_ALL</code><a class="headerlink" href="#locale.LC_ALL" title="Permalink to this definition">¶</a></dt>
<dd><p>Combination of all locale settings.  If this flag is used when the locale is
changed, setting the locale for all categories is attempted. If that fails for
any category, no category is changed at all.  When the locale is retrieved using
this flag, a string indicating the setting for all categories is returned. This
string can be later used to restore the settings.</p>
</dd></dl>

<dl class="data">
<dt id="locale.CHAR_MAX">
<code class="descclassname">locale.</code><code class="descname">CHAR_MAX</code><a class="headerlink" href="#locale.CHAR_MAX" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a symbolic constant used for different values returned by
<a class="reference internal" href="#locale.localeconv" title="locale.localeconv"><code class="xref py py-func docutils literal notranslate"><span class="pre">localeconv()</span></code></a>.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">loc</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">getlocale</span><span class="p">()</span>  <span class="c1"># get current locale</span>
<span class="go"># use German locale; name might vary with platform</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;de_DE&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">strcoll</span><span class="p">(</span><span class="s1">&#39;f</span><span class="se">\xe4</span><span class="s1">n&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>  <span class="c1"># compare a string containing an umlaut</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>   <span class="c1"># use user&#39;s preferred locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;C&#39;</span><span class="p">)</span>  <span class="c1"># use default (C) locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="n">loc</span><span class="p">)</span>  <span class="c1"># restore saved locale</span>
</pre></div>
</div>
<div class="section" id="background-details-hints-tips-and-caveats">
<h2>22.2.1. Background, details, hints, tips and caveats<a class="headerlink" href="#background-details-hints-tips-and-caveats" title="Permalink to this headline">¶</a></h2>
<p>The C standard defines the locale as a program-wide property that may be
relatively expensive to change.  On top of that, some implementation are broken
in such a way that frequent locale changes may cause core dumps.  This makes the
locale somewhat painful to use correctly.</p>
<p>Initially, when a program is started, the locale is the <code class="docutils literal notranslate"><span class="pre">C</span></code> locale, no matter
what the user’s preferred locale is.  The program must explicitly say that it
wants the user’s preferred locale settings by calling <code class="docutils literal notranslate"><span class="pre">setlocale(LC_ALL,</span> <span class="pre">'')</span></code>.</p>
<p>It is generally a bad idea to call <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> in some library routine,
since as a side effect it affects the entire program.  Saving and restoring it
is almost as bad: it is expensive and affects other threads that happen to run
before the settings have been restored.</p>
<p>If, when coding a module for general use, you need a locale independent version
of an operation that is affected by the locale (such as <a class="reference internal" href="string.html#string.lower" title="string.lower"><code class="xref py py-func docutils literal notranslate"><span class="pre">string.lower()</span></code></a>, or
certain formats used with <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>), you will have to find a way to
do it without using the standard library routine.  Even better is convincing
yourself that using locale settings is okay.  Only as a last resort should you
document that your module is not compatible with non-<code class="docutils literal notranslate"><span class="pre">C</span></code> locale settings.</p>
<p id="index-8">The case conversion functions in the <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module are affected by the
locale settings.  When a call to the <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> function changes the
<a class="reference internal" href="#locale.LC_CTYPE" title="locale.LC_CTYPE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LC_CTYPE</span></code></a> settings, the variables <code class="docutils literal notranslate"><span class="pre">string.lowercase</span></code>,
<code class="docutils literal notranslate"><span class="pre">string.uppercase</span></code> and <code class="docutils literal notranslate"><span class="pre">string.letters</span></code> are recalculated.  Note that code
that uses these variable through ‘<a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> … <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> …’,
e.g. <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">string</span> <span class="pre">import</span> <span class="pre">letters</span></code>, is not affected by subsequent
<a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a> calls.</p>
<p>The only way to perform numeric operations according to the locale is to use the
special functions defined by this module: <a class="reference internal" href="#locale.atof" title="locale.atof"><code class="xref py py-func docutils literal notranslate"><span class="pre">atof()</span></code></a>, <a class="reference internal" href="#locale.atoi" title="locale.atoi"><code class="xref py py-func docutils literal notranslate"><span class="pre">atoi()</span></code></a>,
<a class="reference internal" href="#locale.format" title="locale.format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a>, <a class="reference internal" href="#locale.str" title="locale.str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.</p>
</div>
<div class="section" id="for-extension-writers-and-programs-that-embed-python">
<span id="embedding-locale"></span><h2>22.2.2. For extension writers and programs that embed Python<a class="headerlink" href="#for-extension-writers-and-programs-that-embed-python" title="Permalink to this headline">¶</a></h2>
<p>Extension modules should never call <a class="reference internal" href="#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">setlocale()</span></code></a>, except to find out what
the current locale is.  But since the return value can only be used portably to
restore it, that is not very useful (except perhaps to find out whether or not
the locale is <code class="docutils literal notranslate"><span class="pre">C</span></code>).</p>
<p>When Python code uses the <a class="reference internal" href="#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module to change the locale, this also
affects the embedding application.  If the embedding application doesn’t want
this to happen, it should remove the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_locale</span></code> extension module (which does
all the work) from the table of built-in modules in the <code class="file docutils literal notranslate"><span class="pre">config.c</span></code> file,
and make sure that the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_locale</span></code> module is not accessible as a shared
library.</p>
</div>
<div class="section" id="access-to-message-catalogs">
<span id="locale-gettext"></span><h2>22.2.3. Access to message catalogs<a class="headerlink" href="#access-to-message-catalogs" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="locale.gettext">
<code class="descclassname">locale.</code><code class="descname">gettext</code><span class="sig-paren">(</span><em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.gettext" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="locale.dgettext">
<code class="descclassname">locale.</code><code class="descname">dgettext</code><span class="sig-paren">(</span><em>domain</em>, <em>msg</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.dgettext" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="locale.dcgettext">
<code class="descclassname">locale.</code><code class="descname">dcgettext</code><span class="sig-paren">(</span><em>domain</em>, <em>msg</em>, <em>category</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.dcgettext" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="locale.textdomain">
<code class="descclassname">locale.</code><code class="descname">textdomain</code><span class="sig-paren">(</span><em>domain</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.textdomain" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="locale.bindtextdomain">
<code class="descclassname">locale.</code><code class="descname">bindtextdomain</code><span class="sig-paren">(</span><em>domain</em>, <em>dir</em><span class="sig-paren">)</span><a class="headerlink" href="#locale.bindtextdomain" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>The locale module exposes the C library’s gettext interface on systems that
provide this interface.  It consists of the functions <code class="xref py py-func docutils literal notranslate"><span class="pre">gettext()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">dgettext()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">dcgettext()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">textdomain()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">bindtextdomain()</span></code>,
and <code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code>.  These are similar to the same functions in
the <a class="reference internal" href="gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module, but use the C library’s binary format for message
catalogs, and the C library’s search algorithms for locating message catalogs.</p>
<p>Python applications should normally find no need to invoke these functions, and
should use <a class="reference internal" href="gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> instead.  A known exception to this rule are
applications that link with additional C libraries which internally invoke
<code class="xref c c-func docutils literal notranslate"><span class="pre">gettext()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">dcgettext()</span></code>.  For these applications, it may be
necessary to bind the text domain, so that the libraries can properly locate
their message catalogs.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a><ul>
<li><a class="reference internal" href="#background-details-hints-tips-and-caveats">22.2.1. Background, details, hints, tips and caveats</a></li>
<li><a class="reference internal" href="#for-extension-writers-and-programs-that-embed-python">22.2.2. For extension writers and programs that embed Python</a></li>
<li><a class="reference internal" href="#access-to-message-catalogs">22.2.3. Access to message catalogs</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="gettext.html"
                        title="previous chapter">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="frameworks.html"
                        title="next chapter">23. Program Frameworks</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/locale.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="frameworks.html" title="23. Program Frameworks"
             >next</a> |</li>
        <li class="right" >
          <a href="gettext.html" title="22.1. gettext — Multilingual internationalization services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="i18n.html" >22. Internationalization</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\˹�8�8 html/library/logging.config.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.8. logging.config — Logging configuration &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.9. logging.handlers — Logging handlers" href="logging.handlers.html" />
    <link rel="prev" title="15.7. logging — Logging facility for Python" href="logging.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/logging.config.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.handlers.html" title="15.9. logging.handlers — Logging handlers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="15.7. logging — Logging facility for Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-logging.config">
<span id="logging-config-logging-configuration"></span><h1>15.8. <a class="reference internal" href="#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a> — Logging configuration<a class="headerlink" href="#module-logging.config" title="Permalink to this headline">¶</a></h1>
<div class="sidebar">
<p class="first sidebar-title">Important</p>
<p>This page contains only reference information. For tutorials,
please see</p>
<ul class="last simple">
<li><a class="reference internal" href="../howto/logging.html#logging-basic-tutorial"><span class="std std-ref">Basic Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging.html#logging-advanced-tutorial"><span class="std std-ref">Advanced Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a></li>
</ul>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/logging/config.py">Lib/logging/config.py</a></p>
<hr class="docutils" />
<p>This section describes the API for configuring the logging module.</p>
<div class="section" id="configuration-functions">
<span id="logging-config-api"></span><h2>15.8.1. Configuration functions<a class="headerlink" href="#configuration-functions" title="Permalink to this headline">¶</a></h2>
<p>The following functions configure the logging module. They are located in the
<a class="reference internal" href="#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a> module.  Their use is optional — you can configure the
logging module using these functions or by making calls to the main API (defined
in <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> itself) and defining handlers which are declared either in
<a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> or <a class="reference internal" href="logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>.</p>
<dl class="function">
<dt id="logging.config.dictConfig">
<code class="descclassname">logging.config.</code><code class="descname">dictConfig</code><span class="sig-paren">(</span><em>config</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.config.dictConfig" title="Permalink to this definition">¶</a></dt>
<dd><blockquote>
<div><p>Takes the logging configuration from a dictionary.  The contents of
this dictionary are described in <a class="reference internal" href="#logging-config-dictschema"><span class="std std-ref">Configuration dictionary schema</span></a>
below.</p>
<p>If an error is encountered during configuration, this function will
raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>
or <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> with a suitably descriptive message.  The
following is a (possibly incomplete) list of conditions which will
raise an error:</p>
<ul class="simple">
<li>A <code class="docutils literal notranslate"><span class="pre">level</span></code> which is not a string or which is a string not
corresponding to an actual logging level.</li>
<li>A <code class="docutils literal notranslate"><span class="pre">propagate</span></code> value which is not a boolean.</li>
<li>An id which does not have a corresponding destination.</li>
<li>A non-existent handler id found during an incremental call.</li>
<li>An invalid logger name.</li>
<li>Inability to resolve to an internal or external object.</li>
</ul>
<p>Parsing is performed by the <code class="xref py py-class docutils literal notranslate"><span class="pre">DictConfigurator</span></code> class, whose
constructor is passed the dictionary used for configuration, and
has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">configure()</span></code> method.  The <a class="reference internal" href="#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a> module
has a callable attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">dictConfigClass</span></code>
which is initially set to <code class="xref py py-class docutils literal notranslate"><span class="pre">DictConfigurator</span></code>.
You can replace the value of <code class="xref py py-attr docutils literal notranslate"><span class="pre">dictConfigClass</span></code> with a
suitable implementation of your own.</p>
<p><a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> calls <code class="xref py py-attr docutils literal notranslate"><span class="pre">dictConfigClass</span></code> passing
the specified dictionary, and then calls the <code class="xref py py-meth docutils literal notranslate"><span class="pre">configure()</span></code> method on
the returned object to put the configuration into effect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">dictConfig</span><span class="p">(</span><span class="n">config</span><span class="p">):</span>
    <span class="n">dictConfigClass</span><span class="p">(</span><span class="n">config</span><span class="p">)</span><span class="o">.</span><span class="n">configure</span><span class="p">()</span>
</pre></div>
</div>
<p>For example, a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">DictConfigurator</span></code> could call
<code class="docutils literal notranslate"><span class="pre">DictConfigurator.__init__()</span></code> in its own <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, then
set up custom prefixes which would be usable in the subsequent
<code class="xref py py-meth docutils literal notranslate"><span class="pre">configure()</span></code> call. <code class="xref py py-attr docutils literal notranslate"><span class="pre">dictConfigClass</span></code> would be bound to
this new subclass, and then <a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> could be called exactly as
in the default, uncustomized state.</p>
</div></blockquote>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.config.fileConfig">
<code class="descclassname">logging.config.</code><code class="descname">fileConfig</code><span class="sig-paren">(</span><em>fname</em>, <em>defaults=None</em>, <em>disable_existing_loggers=True</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.config.fileConfig" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads the logging configuration from a <code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code>-format file
named <em>fname</em>. The format of the file should be as described in
<a class="reference internal" href="#logging-config-fileformat"><span class="std std-ref">Configuration file format</span></a>. This function can be called several times
from an application, allowing an end user to select from various pre-canned
configurations (if the developer provides a mechanism to present the choices
and load the chosen configuration).</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>defaults</strong> – Defaults to be passed to the ConfigParser can be specified
in this argument.</li>
<li><strong>disable_existing_loggers</strong> – If specified as <code class="docutils literal notranslate"><span class="pre">False</span></code>, loggers which
exist when this call is made are left
enabled. The default is <code class="docutils literal notranslate"><span class="pre">True</span></code> because this
enables old behaviour in a
backward-compatible way. This behaviour is to
disable any existing loggers unless they or
their ancestors are explicitly named in the
logging configuration.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <code class="docutils literal notranslate"><span class="pre">disable_existing_loggers</span></code> keyword argument was added. Previously,
existing loggers were <em>always</em> disabled.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.config.listen">
<code class="descclassname">logging.config.</code><code class="descname">listen</code><span class="sig-paren">(</span><em>port=DEFAULT_LOGGING_CONFIG_PORT</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.config.listen" title="Permalink to this definition">¶</a></dt>
<dd><p>Starts up a socket server on the specified port, and listens for new
configurations. If no port is specified, the module’s default
<code class="xref py py-const docutils literal notranslate"><span class="pre">DEFAULT_LOGGING_CONFIG_PORT</span></code> is used. Logging configurations will be
sent as a file suitable for processing by <a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a>. Returns a
<a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> instance on which you can call
<a class="reference internal" href="threading.html#threading.Thread.start" title="threading.Thread.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> to start the server, and which you can
<a class="reference internal" href="threading.html#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> when appropriate. To stop the server,
call <a class="reference internal" href="#logging.config.stopListening" title="logging.config.stopListening"><code class="xref py py-func docutils literal notranslate"><span class="pre">stopListening()</span></code></a>.</p>
<p>To send a configuration to the socket, read in the configuration file and
send it to the socket as a string of bytes preceded by a four-byte length
string packed in binary using <code class="docutils literal notranslate"><span class="pre">struct.pack('&gt;L',</span> <span class="pre">n)</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Because portions of the configuration are passed through
<a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, use of this function may open its users to a security risk.
While the function only binds to a socket on <code class="docutils literal notranslate"><span class="pre">localhost</span></code>, and so does
not accept connections from remote machines, there are scenarios where
untrusted code could be run under the account of the process which calls
<a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a>. Specifically, if the process calling <a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a> runs
on a multi-user machine where users cannot trust each other, then a
malicious user could arrange to run essentially arbitrary code in a
victim user’s process, simply by connecting to the victim’s
<a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a> socket and sending a configuration which runs whatever
code the attacker wants to have executed in the victim’s process. This is
especially easy to do if the default port is used, but not hard even if a
different port is used).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.config.stopListening">
<code class="descclassname">logging.config.</code><code class="descname">stopListening</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.config.stopListening" title="Permalink to this definition">¶</a></dt>
<dd><p>Stops the listening server which was created with a call to <a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a>.
This is typically called before calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> on the return value from
<a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="configuration-dictionary-schema">
<span id="logging-config-dictschema"></span><h2>15.8.2. Configuration dictionary schema<a class="headerlink" href="#configuration-dictionary-schema" title="Permalink to this headline">¶</a></h2>
<p>Describing a logging configuration requires listing the various
objects to create and the connections between them; for example, you
may create a handler named ‘console’ and then say that the logger
named ‘startup’ will send its messages to the ‘console’ handler.
These objects aren’t limited to those provided by the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a>
module because you might write your own formatter or handler class.
The parameters to these classes may also need to include external
objects such as <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.  The syntax for describing these
objects and connections is defined in <a class="reference internal" href="#logging-config-dict-connections"><span class="std std-ref">Object connections</span></a>
below.</p>
<div class="section" id="dictionary-schema-details">
<h3>15.8.2.1. Dictionary Schema Details<a class="headerlink" href="#dictionary-schema-details" title="Permalink to this headline">¶</a></h3>
<p>The dictionary passed to <a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> must contain the following
keys:</p>
<ul class="simple">
<li><em>version</em> - to be set to an integer value representing the schema
version.  The only valid value at present is 1, but having this key
allows the schema to evolve while still preserving backwards
compatibility.</li>
</ul>
<p>All other keys are optional, but if present they will be interpreted
as described below.  In all cases below where a ‘configuring dict’ is
mentioned, it will be checked for the special <code class="docutils literal notranslate"><span class="pre">'()'</span></code> key to see if a
custom instantiation is required.  If so, the mechanism described in
<a class="reference internal" href="#logging-config-dict-userdef"><span class="std std-ref">User-defined objects</span></a> below is used to create an instance;
otherwise, the context is used to determine what to instantiate.</p>
<ul>
<li><p class="first"><em>formatters</em> - the corresponding value will be a dict in which each
key is a formatter id and each value is a dict describing how to
configure the corresponding <a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> instance.</p>
<p>The configuring dict is searched for keys <code class="docutils literal notranslate"><span class="pre">format</span></code> and <code class="docutils literal notranslate"><span class="pre">datefmt</span></code>
(with defaults of <code class="docutils literal notranslate"><span class="pre">None</span></code>) and these are used to construct a
<a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> instance.</p>
</li>
<li><p class="first"><em>filters</em> - the corresponding value will be a dict in which each key
is a filter id and each value is a dict describing how to configure
the corresponding Filter instance.</p>
<p>The configuring dict is searched for the key <code class="docutils literal notranslate"><span class="pre">name</span></code> (defaulting to the
empty string) and this is used to construct a <a class="reference internal" href="logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Filter</span></code></a>
instance.</p>
</li>
<li><p class="first"><em>handlers</em> - the corresponding value will be a dict in which each
key is a handler id and each value is a dict describing how to
configure the corresponding Handler instance.</p>
<p>The configuring dict is searched for the following keys:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">class</span></code> (mandatory).  This is the fully qualified name of the
handler class.</li>
<li><code class="docutils literal notranslate"><span class="pre">level</span></code> (optional).  The level of the handler.</li>
<li><code class="docutils literal notranslate"><span class="pre">formatter</span></code> (optional).  The id of the formatter for this
handler.</li>
<li><code class="docutils literal notranslate"><span class="pre">filters</span></code> (optional).  A list of ids of the filters for this
handler.</li>
</ul>
<p>All <em>other</em> keys are passed through as keyword arguments to the
handler’s constructor.  For example, given the snippet:</p>
<div class="highlight-yaml notranslate"><div class="highlight"><pre><span></span><span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span>
  <span class="l l-Scalar l-Scalar-Plain">console</span><span class="p p-Indicator">:</span>
    <span class="l l-Scalar l-Scalar-Plain">class</span> <span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">logging.StreamHandler</span>
    <span class="l l-Scalar l-Scalar-Plain">formatter</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">brief</span>
    <span class="l l-Scalar l-Scalar-Plain">level</span>   <span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">INFO</span>
    <span class="l l-Scalar l-Scalar-Plain">filters</span><span class="p p-Indicator">:</span> <span class="p p-Indicator">[</span><span class="nv">allow_foo</span><span class="p p-Indicator">]</span>
    <span class="l l-Scalar l-Scalar-Plain">stream</span>  <span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">ext://sys.stdout</span>
  <span class="l l-Scalar l-Scalar-Plain">file</span><span class="p p-Indicator">:</span>
    <span class="l l-Scalar l-Scalar-Plain">class</span> <span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">logging.handlers.RotatingFileHandler</span>
    <span class="l l-Scalar l-Scalar-Plain">formatter</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">precise</span>
    <span class="l l-Scalar l-Scalar-Plain">filename</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">logconfig.log</span>
    <span class="l l-Scalar l-Scalar-Plain">maxBytes</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">1024</span>
    <span class="l l-Scalar l-Scalar-Plain">backupCount</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">3</span>
</pre></div>
</div>
<p>the handler with id <code class="docutils literal notranslate"><span class="pre">console</span></code> is instantiated as a
<a class="reference internal" href="logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.StreamHandler</span></code></a>, using <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> as the underlying
stream.  The handler with id <code class="docutils literal notranslate"><span class="pre">file</span></code> is instantiated as a
<a class="reference internal" href="logging.handlers.html#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.handlers.RotatingFileHandler</span></code></a> with the keyword arguments
<code class="docutils literal notranslate"><span class="pre">filename='logconfig.log',</span> <span class="pre">maxBytes=1024,</span> <span class="pre">backupCount=3</span></code>.</p>
</li>
<li><p class="first"><em>loggers</em> - the corresponding value will be a dict in which each key
is a logger name and each value is a dict describing how to
configure the corresponding Logger instance.</p>
<p>The configuring dict is searched for the following keys:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">level</span></code> (optional).  The level of the logger.</li>
<li><code class="docutils literal notranslate"><span class="pre">propagate</span></code> (optional).  The propagation setting of the logger.</li>
<li><code class="docutils literal notranslate"><span class="pre">filters</span></code> (optional).  A list of ids of the filters for this
logger.</li>
<li><code class="docutils literal notranslate"><span class="pre">handlers</span></code> (optional).  A list of ids of the handlers for this
logger.</li>
</ul>
<p>The specified loggers will be configured according to the level,
propagation, filters and handlers specified.</p>
</li>
<li><p class="first"><em>root</em> - this will be the configuration for the root logger.
Processing of the configuration will be as for any logger, except
that the <code class="docutils literal notranslate"><span class="pre">propagate</span></code> setting will not be applicable.</p>
</li>
<li><p class="first"><em>incremental</em> - whether the configuration is to be interpreted as
incremental to the existing configuration.  This value defaults to
<code class="docutils literal notranslate"><span class="pre">False</span></code>, which means that the specified configuration replaces the
existing configuration with the same semantics as used by the
existing <a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> API.</p>
<p>If the specified value is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the configuration is processed
as described in the section on <a class="reference internal" href="#logging-config-dict-incremental"><span class="std std-ref">Incremental Configuration</span></a>.</p>
</li>
<li><p class="first"><em>disable_existing_loggers</em> - whether any existing loggers are to be
disabled. This setting mirrors the parameter of the same name in
<a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a>. If absent, this parameter defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>.
This value is ignored if <em>incremental</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</li>
</ul>
</div>
<div class="section" id="incremental-configuration">
<span id="logging-config-dict-incremental"></span><h3>15.8.2.2. Incremental Configuration<a class="headerlink" href="#incremental-configuration" title="Permalink to this headline">¶</a></h3>
<p>It is difficult to provide complete flexibility for incremental
configuration.  For example, because objects such as filters
and formatters are anonymous, once a configuration is set up, it is
not possible to refer to such anonymous objects when augmenting a
configuration.</p>
<p>Furthermore, there is not a compelling case for arbitrarily altering
the object graph of loggers, handlers, filters, formatters at
run-time, once a configuration is set up; the verbosity of loggers and
handlers can be controlled just by setting levels (and, in the case of
loggers, propagation flags).  Changing the object graph arbitrarily in
a safe way is problematic in a multi-threaded environment; while not
impossible, the benefits are not worth the complexity it adds to the
implementation.</p>
<p>Thus, when the <code class="docutils literal notranslate"><span class="pre">incremental</span></code> key of a configuration dict is present
and is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the system will completely ignore any <code class="docutils literal notranslate"><span class="pre">formatters</span></code> and
<code class="docutils literal notranslate"><span class="pre">filters</span></code> entries, and process only the <code class="docutils literal notranslate"><span class="pre">level</span></code>
settings in the <code class="docutils literal notranslate"><span class="pre">handlers</span></code> entries, and the <code class="docutils literal notranslate"><span class="pre">level</span></code> and
<code class="docutils literal notranslate"><span class="pre">propagate</span></code> settings in the <code class="docutils literal notranslate"><span class="pre">loggers</span></code> and <code class="docutils literal notranslate"><span class="pre">root</span></code> entries.</p>
<p>Using a value in the configuration dict lets configurations to be sent
over the wire as pickled dicts to a socket listener. Thus, the logging
verbosity of a long-running application can be altered over time with
no need to stop and restart the application.</p>
</div>
<div class="section" id="object-connections">
<span id="logging-config-dict-connections"></span><h3>15.8.2.3. Object connections<a class="headerlink" href="#object-connections" title="Permalink to this headline">¶</a></h3>
<p>The schema describes a set of logging objects - loggers,
handlers, formatters, filters - which are connected to each other in
an object graph.  Thus, the schema needs to represent connections
between the objects.  For example, say that, once configured, a
particular logger has attached to it a particular handler.  For the
purposes of this discussion, we can say that the logger represents the
source, and the handler the destination, of a connection between the
two.  Of course in the configured objects this is represented by the
logger holding a reference to the handler.  In the configuration dict,
this is done by giving each destination object an id which identifies
it unambiguously, and then using the id in the source object’s
configuration to indicate that a connection exists between the source
and the destination object with that id.</p>
<p>So, for example, consider the following YAML snippet:</p>
<div class="highlight-yaml notranslate"><div class="highlight"><pre><span></span><span class="l l-Scalar l-Scalar-Plain">formatters</span><span class="p p-Indicator">:</span>
  <span class="l l-Scalar l-Scalar-Plain">brief</span><span class="p p-Indicator">:</span>
    <span class="c1"># configuration for formatter with id &#39;brief&#39; goes here</span>
  <span class="l l-Scalar l-Scalar-Plain">precise</span><span class="p p-Indicator">:</span>
    <span class="c1"># configuration for formatter with id &#39;precise&#39; goes here</span>
<span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span>
  <span class="l l-Scalar l-Scalar-Plain">h1</span><span class="p p-Indicator">:</span> <span class="c1">#This is an id</span>
   <span class="c1"># configuration of handler with id &#39;h1&#39; goes here</span>
   <span class="l l-Scalar l-Scalar-Plain">formatter</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">brief</span>
  <span class="l l-Scalar l-Scalar-Plain">h2</span><span class="p p-Indicator">:</span> <span class="c1">#This is another id</span>
   <span class="c1"># configuration of handler with id &#39;h2&#39; goes here</span>
   <span class="l l-Scalar l-Scalar-Plain">formatter</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">precise</span>
<span class="l l-Scalar l-Scalar-Plain">loggers</span><span class="p p-Indicator">:</span>
  <span class="l l-Scalar l-Scalar-Plain">foo.bar.baz</span><span class="p p-Indicator">:</span>
    <span class="c1"># other configuration for logger &#39;foo.bar.baz&#39;</span>
    <span class="l l-Scalar l-Scalar-Plain">handlers</span><span class="p p-Indicator">:</span> <span class="p p-Indicator">[</span><span class="nv">h1</span><span class="p p-Indicator">,</span> <span class="nv">h2</span><span class="p p-Indicator">]</span>
</pre></div>
</div>
<p>(Note: YAML used here because it’s a little more readable than the
equivalent Python source form for the dictionary.)</p>
<p>The ids for loggers are the logger names which would be used
programmatically to obtain a reference to those loggers, e.g.
<code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code>.  The ids for Formatters and Filters can be any string
value (such as <code class="docutils literal notranslate"><span class="pre">brief</span></code>, <code class="docutils literal notranslate"><span class="pre">precise</span></code> above) and they are transient,
in that they are only meaningful for processing the configuration
dictionary and used to determine connections between objects, and are
not persisted anywhere when the configuration call is complete.</p>
<p>The above snippet indicates that logger named <code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code> should
have two handlers attached to it, which are described by the handler
ids <code class="docutils literal notranslate"><span class="pre">h1</span></code> and <code class="docutils literal notranslate"><span class="pre">h2</span></code>. The formatter for <code class="docutils literal notranslate"><span class="pre">h1</span></code> is that described by id
<code class="docutils literal notranslate"><span class="pre">brief</span></code>, and the formatter for <code class="docutils literal notranslate"><span class="pre">h2</span></code> is that described by id
<code class="docutils literal notranslate"><span class="pre">precise</span></code>.</p>
</div>
<div class="section" id="user-defined-objects">
<span id="logging-config-dict-userdef"></span><h3>15.8.2.4. User-defined objects<a class="headerlink" href="#user-defined-objects" title="Permalink to this headline">¶</a></h3>
<p>The schema supports user-defined objects for handlers, filters and
formatters.  (Loggers do not need to have different types for
different instances, so there is no support in this configuration
schema for user-defined logger classes.)</p>
<p>Objects to be configured are described by dictionaries
which detail their configuration.  In some places, the logging system
will be able to infer from the context how an object is to be
instantiated, but when a user-defined object is to be instantiated,
the system will not know how to do this.  In order to provide complete
flexibility for user-defined object instantiation, the user needs
to provide a ‘factory’ - a callable which is called with a
configuration dictionary and which returns the instantiated object.
This is signalled by an absolute import path to the factory being
made available under the special key <code class="docutils literal notranslate"><span class="pre">'()'</span></code>.  Here’s a concrete
example:</p>
<div class="highlight-yaml notranslate"><div class="highlight"><pre><span></span><span class="l l-Scalar l-Scalar-Plain">formatters</span><span class="p p-Indicator">:</span>
  <span class="l l-Scalar l-Scalar-Plain">brief</span><span class="p p-Indicator">:</span>
    <span class="l l-Scalar l-Scalar-Plain">format</span><span class="p p-Indicator">:</span> <span class="s">&#39;%(message)s&#39;</span>
  <span class="l l-Scalar l-Scalar-Plain">default</span><span class="p p-Indicator">:</span>
    <span class="l l-Scalar l-Scalar-Plain">format</span><span class="p p-Indicator">:</span> <span class="s">&#39;%(asctime)s</span><span class="nv"> </span><span class="s">%(levelname)-8s</span><span class="nv"> </span><span class="s">%(name)-15s</span><span class="nv"> </span><span class="s">%(message)s&#39;</span>
    <span class="l l-Scalar l-Scalar-Plain">datefmt</span><span class="p p-Indicator">:</span> <span class="s">&#39;%Y-%m-%d</span><span class="nv"> </span><span class="s">%H:%M:%S&#39;</span>
  <span class="l l-Scalar l-Scalar-Plain">custom</span><span class="p p-Indicator">:</span>
      <span class="l l-Scalar l-Scalar-Plain">()</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">my.package.customFormatterFactory</span>
      <span class="l l-Scalar l-Scalar-Plain">bar</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">baz</span>
      <span class="l l-Scalar l-Scalar-Plain">spam</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">99.9</span>
      <span class="l l-Scalar l-Scalar-Plain">answer</span><span class="p p-Indicator">:</span> <span class="l l-Scalar l-Scalar-Plain">42</span>
</pre></div>
</div>
<p>The above YAML snippet defines three formatters.  The first, with id
<code class="docutils literal notranslate"><span class="pre">brief</span></code>, is a standard <a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Formatter</span></code></a> instance with the
specified format string.  The second, with id <code class="docutils literal notranslate"><span class="pre">default</span></code>, has a
longer format and also defines the time format explicitly, and will
result in a <a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Formatter</span></code></a> initialized with those two format
strings.  Shown in Python source form, the <code class="docutils literal notranslate"><span class="pre">brief</span></code> and <code class="docutils literal notranslate"><span class="pre">default</span></code>
formatters have configuration sub-dictionaries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  <span class="s1">&#39;format&#39;</span> <span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(message)s</span><span class="s1">&#39;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>and:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  <span class="s1">&#39;format&#39;</span> <span class="p">:</span> <span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(name)-15s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">,</span>
  <span class="s1">&#39;datefmt&#39;</span> <span class="p">:</span> <span class="s1">&#39;%Y-%m-</span><span class="si">%d</span><span class="s1"> %H:%M:%S&#39;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>respectively, and as these dictionaries do not contain the special key
<code class="docutils literal notranslate"><span class="pre">'()'</span></code>, the instantiation is inferred from the context: as a result,
standard <a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Formatter</span></code></a> instances are created.  The
configuration sub-dictionary for the third formatter, with id
<code class="docutils literal notranslate"><span class="pre">custom</span></code>, is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span>
  <span class="s1">&#39;()&#39;</span> <span class="p">:</span> <span class="s1">&#39;my.package.customFormatterFactory&#39;</span><span class="p">,</span>
  <span class="s1">&#39;bar&#39;</span> <span class="p">:</span> <span class="s1">&#39;baz&#39;</span><span class="p">,</span>
  <span class="s1">&#39;spam&#39;</span> <span class="p">:</span> <span class="mf">99.9</span><span class="p">,</span>
  <span class="s1">&#39;answer&#39;</span> <span class="p">:</span> <span class="mi">42</span>
<span class="p">}</span>
</pre></div>
</div>
<p>and this contains the special key <code class="docutils literal notranslate"><span class="pre">'()'</span></code>, which means that
user-defined instantiation is wanted.  In this case, the specified
factory callable will be used. If it is an actual callable it will be
used directly - otherwise, if you specify a string (as in the example)
the actual callable will be located using normal import mechanisms.
The callable will be called with the <strong>remaining</strong> items in the
configuration sub-dictionary as keyword arguments.  In the above
example, the formatter with id <code class="docutils literal notranslate"><span class="pre">custom</span></code> will be assumed to be
returned by the call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">my</span><span class="o">.</span><span class="n">package</span><span class="o">.</span><span class="n">customFormatterFactory</span><span class="p">(</span><span class="n">bar</span><span class="o">=</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="n">spam</span><span class="o">=</span><span class="mf">99.9</span><span class="p">,</span> <span class="n">answer</span><span class="o">=</span><span class="mi">42</span><span class="p">)</span>
</pre></div>
</div>
<p>The key <code class="docutils literal notranslate"><span class="pre">'()'</span></code> has been used as the special key because it is not a
valid keyword parameter name, and so will not clash with the names of
the keyword arguments used in the call.  The <code class="docutils literal notranslate"><span class="pre">'()'</span></code> also serves as a
mnemonic that the corresponding value is a callable.</p>
</div>
<div class="section" id="access-to-external-objects">
<span id="logging-config-dict-externalobj"></span><h3>15.8.2.5. Access to external objects<a class="headerlink" href="#access-to-external-objects" title="Permalink to this headline">¶</a></h3>
<p>There are times where a configuration needs to refer to objects
external to the configuration, for example <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.  If the
configuration dict is constructed using Python code, this is
straightforward, but a problem arises when the configuration is
provided via a text file (e.g. JSON, YAML).  In a text file, there is
no standard way to distinguish <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> from the literal string
<code class="docutils literal notranslate"><span class="pre">'sys.stderr'</span></code>.  To facilitate this distinction, the configuration
system looks for certain special prefixes in string values and
treat them specially.  For example, if the literal string
<code class="docutils literal notranslate"><span class="pre">'ext://sys.stderr'</span></code> is provided as a value in the configuration,
then the <code class="docutils literal notranslate"><span class="pre">ext://</span></code> will be stripped off and the remainder of the
value processed using normal import mechanisms.</p>
<p>The handling of such prefixes is done in a way analogous to protocol
handling: there is a generic mechanism to look for prefixes which
match the regular expression <code class="docutils literal notranslate"><span class="pre">^(?P&lt;prefix&gt;[a-z]+)://(?P&lt;suffix&gt;.*)$</span></code>
whereby, if the <code class="docutils literal notranslate"><span class="pre">prefix</span></code> is recognised, the <code class="docutils literal notranslate"><span class="pre">suffix</span></code> is processed
in a prefix-dependent manner and the result of the processing replaces
the string value.  If the prefix is not recognised, then the string
value will be left as-is.</p>
</div>
<div class="section" id="access-to-internal-objects">
<span id="logging-config-dict-internalobj"></span><h3>15.8.2.6. Access to internal objects<a class="headerlink" href="#access-to-internal-objects" title="Permalink to this headline">¶</a></h3>
<p>As well as external objects, there is sometimes also a need to refer
to objects in the configuration.  This will be done implicitly by the
configuration system for things that it knows about.  For example, the
string value <code class="docutils literal notranslate"><span class="pre">'DEBUG'</span></code> for a <code class="docutils literal notranslate"><span class="pre">level</span></code> in a logger or handler will
automatically be converted to the value <code class="docutils literal notranslate"><span class="pre">logging.DEBUG</span></code>, and the
<code class="docutils literal notranslate"><span class="pre">handlers</span></code>, <code class="docutils literal notranslate"><span class="pre">filters</span></code> and <code class="docutils literal notranslate"><span class="pre">formatter</span></code> entries will take an
object id and resolve to the appropriate destination object.</p>
<p>However, a more generic mechanism is needed for user-defined
objects which are not known to the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module.  For
example, consider <a class="reference internal" href="logging.handlers.html#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.handlers.MemoryHandler</span></code></a>, which takes
a <code class="docutils literal notranslate"><span class="pre">target</span></code> argument which is another handler to delegate to. Since
the system already knows about this class, then in the configuration,
the given <code class="docutils literal notranslate"><span class="pre">target</span></code> just needs to be the object id of the relevant
target handler, and the system will resolve to the handler from the
id.  If, however, a user defines a <code class="docutils literal notranslate"><span class="pre">my.package.MyHandler</span></code> which has
an <code class="docutils literal notranslate"><span class="pre">alternate</span></code> handler, the configuration system would not know that
the <code class="docutils literal notranslate"><span class="pre">alternate</span></code> referred to a handler.  To cater for this, a generic
resolution system allows the user to specify:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">handlers</span><span class="p">:</span>
  <span class="n">file</span><span class="p">:</span>
    <span class="c1"># configuration of file handler goes here</span>

  <span class="n">custom</span><span class="p">:</span>
    <span class="p">():</span> <span class="n">my</span><span class="o">.</span><span class="n">package</span><span class="o">.</span><span class="n">MyHandler</span>
    <span class="n">alternate</span><span class="p">:</span> <span class="n">cfg</span><span class="p">:</span><span class="o">//</span><span class="n">handlers</span><span class="o">.</span><span class="n">file</span>
</pre></div>
</div>
<p>The literal string <code class="docutils literal notranslate"><span class="pre">'cfg://handlers.file'</span></code> will be resolved in an
analogous way to strings with the <code class="docutils literal notranslate"><span class="pre">ext://</span></code> prefix, but looking
in the configuration itself rather than the import namespace.  The
mechanism allows access by dot or by index, in a similar way to
that provided by <code class="docutils literal notranslate"><span class="pre">str.format</span></code>.  Thus, given the following snippet:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">handlers</span><span class="p">:</span>
  <span class="n">email</span><span class="p">:</span>
    <span class="n">class</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">handlers</span><span class="o">.</span><span class="n">SMTPHandler</span>
    <span class="n">mailhost</span><span class="p">:</span> <span class="n">localhost</span>
    <span class="n">fromaddr</span><span class="p">:</span> <span class="n">my_app</span><span class="nd">@domain</span><span class="o">.</span><span class="n">tld</span>
    <span class="n">toaddrs</span><span class="p">:</span>
      <span class="o">-</span> <span class="n">support_team</span><span class="nd">@domain</span><span class="o">.</span><span class="n">tld</span>
      <span class="o">-</span> <span class="n">dev_team</span><span class="nd">@domain</span><span class="o">.</span><span class="n">tld</span>
    <span class="n">subject</span><span class="p">:</span> <span class="n">Houston</span><span class="p">,</span> <span class="n">we</span> <span class="n">have</span> <span class="n">a</span> <span class="n">problem</span><span class="o">.</span>
</pre></div>
</div>
<p>in the configuration, the string <code class="docutils literal notranslate"><span class="pre">'cfg://handlers'</span></code> would resolve to
the dict with key <code class="docutils literal notranslate"><span class="pre">handlers</span></code>, the string <code class="docutils literal notranslate"><span class="pre">'cfg://handlers.email</span></code>
would resolve to the dict with key <code class="docutils literal notranslate"><span class="pre">email</span></code> in the <code class="docutils literal notranslate"><span class="pre">handlers</span></code> dict,
and so on.  The string <code class="docutils literal notranslate"><span class="pre">'cfg://handlers.email.toaddrs[1]</span></code> would
resolve to <code class="docutils literal notranslate"><span class="pre">'dev_team.domain.tld'</span></code> and the string
<code class="docutils literal notranslate"><span class="pre">'cfg://handlers.email.toaddrs[0]'</span></code> would resolve to the value
<code class="docutils literal notranslate"><span class="pre">'support_team&#64;domain.tld'</span></code>. The <code class="docutils literal notranslate"><span class="pre">subject</span></code> value could be accessed
using either <code class="docutils literal notranslate"><span class="pre">'cfg://handlers.email.subject'</span></code> or, equivalently,
<code class="docutils literal notranslate"><span class="pre">'cfg://handlers.email[subject]'</span></code>.  The latter form only needs to be
used if the key contains spaces or non-alphanumeric characters.  If an
index value consists only of decimal digits, access will be attempted
using the corresponding integer value, falling back to the string
value if needed.</p>
<p>Given a string <code class="docutils literal notranslate"><span class="pre">cfg://handlers.myhandler.mykey.123</span></code>, this will
resolve to <code class="docutils literal notranslate"><span class="pre">config_dict['handlers']['myhandler']['mykey']['123']</span></code>.
If the string is specified as <code class="docutils literal notranslate"><span class="pre">cfg://handlers.myhandler.mykey[123]</span></code>,
the system will attempt to retrieve the value from
<code class="docutils literal notranslate"><span class="pre">config_dict['handlers']['myhandler']['mykey'][123]</span></code>, and fall back
to <code class="docutils literal notranslate"><span class="pre">config_dict['handlers']['myhandler']['mykey']['123']</span></code> if that
fails.</p>
</div>
<div class="section" id="import-resolution-and-custom-importers">
<span id="logging-import-resolution"></span><h3>15.8.2.7. Import resolution and custom importers<a class="headerlink" href="#import-resolution-and-custom-importers" title="Permalink to this headline">¶</a></h3>
<p>Import resolution, by default, uses the builtin <a class="reference internal" href="functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function
to do its importing. You may want to replace this with your own importing
mechanism: if so, you can replace the <code class="xref py py-attr docutils literal notranslate"><span class="pre">importer</span></code> attribute of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">DictConfigurator</span></code> or its superclass, the
<code class="xref py py-class docutils literal notranslate"><span class="pre">BaseConfigurator</span></code> class. However, you need to be
careful because of the way functions are accessed from classes via
descriptors. If you are using a Python callable to do your imports, and you
want to define it at class level rather than instance level, you need to wrap
it with <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">import_module</span>
<span class="kn">from</span> <span class="nn">logging.config</span> <span class="k">import</span> <span class="n">BaseConfigurator</span>

<span class="n">BaseConfigurator</span><span class="o">.</span><span class="n">importer</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">import_module</span><span class="p">)</span>
</pre></div>
</div>
<p>You don’t need to wrap with <a class="reference internal" href="functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> if you’re setting the import
callable on a configurator <em>instance</em>.</p>
</div>
</div>
<div class="section" id="configuration-file-format">
<span id="logging-config-fileformat"></span><h2>15.8.3. Configuration file format<a class="headerlink" href="#configuration-file-format" title="Permalink to this headline">¶</a></h2>
<p>The configuration file format understood by <a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> is based on
<code class="xref py py-mod docutils literal notranslate"><span class="pre">configparser</span></code> functionality. The file must contain sections called
<code class="docutils literal notranslate"><span class="pre">[loggers]</span></code>, <code class="docutils literal notranslate"><span class="pre">[handlers]</span></code> and <code class="docutils literal notranslate"><span class="pre">[formatters]</span></code> which identify by name the
entities of each type which are defined in the file. For each such entity, there
is a separate section which identifies how that entity is configured.  Thus, for
a logger named <code class="docutils literal notranslate"><span class="pre">log01</span></code> in the <code class="docutils literal notranslate"><span class="pre">[loggers]</span></code> section, the relevant
configuration details are held in a section <code class="docutils literal notranslate"><span class="pre">[logger_log01]</span></code>. Similarly, a
handler called <code class="docutils literal notranslate"><span class="pre">hand01</span></code> in the <code class="docutils literal notranslate"><span class="pre">[handlers]</span></code> section will have its
configuration held in a section called <code class="docutils literal notranslate"><span class="pre">[handler_hand01]</span></code>, while a formatter
called <code class="docutils literal notranslate"><span class="pre">form01</span></code> in the <code class="docutils literal notranslate"><span class="pre">[formatters]</span></code> section will have its configuration
specified in a section called <code class="docutils literal notranslate"><span class="pre">[formatter_form01]</span></code>. The root logger
configuration must be specified in a section called <code class="docutils literal notranslate"><span class="pre">[logger_root]</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a> API is older than the <a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a> API and does
not provide functionality to cover certain aspects of logging. For example,
you cannot configure <a class="reference internal" href="logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> objects, which provide for
filtering of messages beyond simple integer levels, using <a class="reference internal" href="#logging.config.fileConfig" title="logging.config.fileConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code></a>.
If you need to have instances of <a class="reference internal" href="logging.html#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> in your logging
configuration, you will need to use <a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a>. Note that future
enhancements to configuration functionality will be added to
<a class="reference internal" href="#logging.config.dictConfig" title="logging.config.dictConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code></a>, so it’s worth considering transitioning to this newer
API when it’s convenient to do so.</p>
</div>
<p>Examples of these sections in the file are given below.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[loggers]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">root,log02,log03,log04,log05,log06,log07</span>

<span class="k">[handlers]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09</span>

<span class="k">[formatters]</span>
<span class="na">keys</span><span class="o">=</span><span class="s">form01,form02,form03,form04,form05,form06,form07,form08,form09</span>
</pre></div>
</div>
<p>The root logger must specify a level and a list of handlers. An example of a
root logger section is given below.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[logger_root]</span>
<span class="na">level</span><span class="o">=</span><span class="s">NOTSET</span>
<span class="na">handlers</span><span class="o">=</span><span class="s">hand01</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">level</span></code> entry can be one of <code class="docutils literal notranslate"><span class="pre">DEBUG,</span> <span class="pre">INFO,</span> <span class="pre">WARNING,</span> <span class="pre">ERROR,</span> <span class="pre">CRITICAL</span></code> or
<code class="docutils literal notranslate"><span class="pre">NOTSET</span></code>. For the root logger only, <code class="docutils literal notranslate"><span class="pre">NOTSET</span></code> means that all messages will be
logged. Level values are <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>uated in the context of the <code class="docutils literal notranslate"><span class="pre">logging</span></code>
package’s namespace.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">handlers</span></code> entry is a comma-separated list of handler names, which must
appear in the <code class="docutils literal notranslate"><span class="pre">[handlers]</span></code> section. These names must appear in the
<code class="docutils literal notranslate"><span class="pre">[handlers]</span></code> section and have corresponding sections in the configuration
file.</p>
<p>For loggers other than the root logger, some additional information is required.
This is illustrated by the following example.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[logger_parser]</span>
<span class="na">level</span><span class="o">=</span><span class="s">DEBUG</span>
<span class="na">handlers</span><span class="o">=</span><span class="s">hand01</span>
<span class="na">propagate</span><span class="o">=</span><span class="s">1</span>
<span class="na">qualname</span><span class="o">=</span><span class="s">compiler.parser</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">level</span></code> and <code class="docutils literal notranslate"><span class="pre">handlers</span></code> entries are interpreted as for the root logger,
except that if a non-root logger’s level is specified as <code class="docutils literal notranslate"><span class="pre">NOTSET</span></code>, the system
consults loggers higher up the hierarchy to determine the effective level of the
logger. The <code class="docutils literal notranslate"><span class="pre">propagate</span></code> entry is set to 1 to indicate that messages must
propagate to handlers higher up the logger hierarchy from this logger, or 0 to
indicate that messages are <strong>not</strong> propagated to handlers up the hierarchy. The
<code class="docutils literal notranslate"><span class="pre">qualname</span></code> entry is the hierarchical channel name of the logger, that is to
say the name used by the application to get the logger.</p>
<p>Sections which specify handler configuration are exemplified by the following.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[handler_hand01]</span>
<span class="na">class</span><span class="o">=</span><span class="s">StreamHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">NOTSET</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form01</span>
<span class="na">args</span><span class="o">=</span><span class="s">(sys.stdout,)</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">class</span></code> entry indicates the handler’s class (as determined by <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>
in the <code class="docutils literal notranslate"><span class="pre">logging</span></code> package’s namespace). The <code class="docutils literal notranslate"><span class="pre">level</span></code> is interpreted as for
loggers, and <code class="docutils literal notranslate"><span class="pre">NOTSET</span></code> is taken to mean ‘log everything’.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added support for resolving the handler’s class as a dotted module and
class name.</p>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">formatter</span></code> entry indicates the key name of the formatter for this
handler. If blank, a default formatter (<code class="docutils literal notranslate"><span class="pre">logging._defaultFormatter</span></code>) is used.
If a name is specified, it must appear in the <code class="docutils literal notranslate"><span class="pre">[formatters]</span></code> section and have
a corresponding section in the configuration file.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">args</span></code> entry, when <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>uated in the context of the <code class="docutils literal notranslate"><span class="pre">logging</span></code>
package’s namespace, is the list of arguments to the constructor for the handler
class. Refer to the constructors for the relevant handlers, or to the examples
below, to see how typical entries are constructed.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[handler_hand02]</span>
<span class="na">class</span><span class="o">=</span><span class="s">FileHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">DEBUG</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form02</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;python.log&#39;, &#39;w&#39;)</span>

<span class="k">[handler_hand03]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.SocketHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">INFO</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form03</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;localhost&#39;, handlers.DEFAULT_TCP_LOGGING_PORT)</span>

<span class="k">[handler_hand04]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.DatagramHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">WARN</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form04</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;localhost&#39;, handlers.DEFAULT_UDP_LOGGING_PORT)</span>

<span class="k">[handler_hand05]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.SysLogHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">ERROR</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form05</span>
<span class="na">args</span><span class="o">=</span><span class="s">((&#39;localhost&#39;, handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)</span>

<span class="k">[handler_hand06]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.NTEventLogHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">CRITICAL</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form06</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;Python Application&#39;, &#39;&#39;, &#39;Application&#39;)</span>

<span class="k">[handler_hand07]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.SMTPHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">WARN</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form07</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;localhost&#39;, &#39;from@abc&#39;, [&#39;user1@abc&#39;, &#39;user2@xyz&#39;], &#39;Logger Subject&#39;)</span>

<span class="k">[handler_hand08]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.MemoryHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">NOTSET</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form08</span>
<span class="na">target</span><span class="o">=</span>
<span class="na">args</span><span class="o">=</span><span class="s">(10, ERROR)</span>

<span class="k">[handler_hand09]</span>
<span class="na">class</span><span class="o">=</span><span class="s">handlers.HTTPHandler</span>
<span class="na">level</span><span class="o">=</span><span class="s">NOTSET</span>
<span class="na">formatter</span><span class="o">=</span><span class="s">form09</span>
<span class="na">args</span><span class="o">=</span><span class="s">(&#39;localhost:9022&#39;, &#39;/log&#39;, &#39;GET&#39;)</span>
</pre></div>
</div>
<p>Sections which specify formatter configuration are typified by the following.</p>
<div class="highlight-ini notranslate"><div class="highlight"><pre><span></span><span class="k">[formatter_form01]</span>
<span class="na">format</span><span class="o">=</span><span class="s">F1 %(asctime)s %(levelname)s %(message)s</span>
<span class="na">datefmt</span><span class="o">=</span>
<span class="na">class</span><span class="o">=</span><span class="s">logging.Formatter</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">format</span></code> entry is the overall format string, and the <code class="docutils literal notranslate"><span class="pre">datefmt</span></code> entry is
the <code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code>-compatible date/time format string.  If empty, the
package substitutes ISO8601 format date/times, which is almost equivalent to
specifying the date format string <code class="docutils literal notranslate"><span class="pre">'%Y-%m-%d</span> <span class="pre">%H:%M:%S'</span></code>.  The ISO8601 format
also specifies milliseconds, which are appended to the result of using the above
format string, with a comma separator.  An example time in ISO8601 format is
<code class="docutils literal notranslate"><span class="pre">2003-01-23</span> <span class="pre">00:29:50,411</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">class</span></code> entry is optional.  It indicates the name of the formatter’s class
(as a dotted module and class name.)  This option is useful for instantiating a
<a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> subclass.  Subclasses of
<a class="reference internal" href="logging.html#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> can present exception tracebacks in an expanded or
condensed format.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Due to the use of <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> as described above, there are
potential security risks which result from using the <a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a> to send
and receive configurations via sockets. The risks are limited to where
multiple users with no mutual trust run code on the same machine; see the
<a class="reference internal" href="#logging.config.listen" title="logging.config.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a> documentation for more information.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a></dt>
<dd>API reference for the logging module.</dd>
<dt>Module <a class="reference internal" href="logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a></dt>
<dd>Useful handlers included with the logging module.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a><ul>
<li><a class="reference internal" href="#configuration-functions">15.8.1. Configuration functions</a></li>
<li><a class="reference internal" href="#configuration-dictionary-schema">15.8.2. Configuration dictionary schema</a><ul>
<li><a class="reference internal" href="#dictionary-schema-details">15.8.2.1. Dictionary Schema Details</a></li>
<li><a class="reference internal" href="#incremental-configuration">15.8.2.2. Incremental Configuration</a></li>
<li><a class="reference internal" href="#object-connections">15.8.2.3. Object connections</a></li>
<li><a class="reference internal" href="#user-defined-objects">15.8.2.4. User-defined objects</a></li>
<li><a class="reference internal" href="#access-to-external-objects">15.8.2.5. Access to external objects</a></li>
<li><a class="reference internal" href="#access-to-internal-objects">15.8.2.6. Access to internal objects</a></li>
<li><a class="reference internal" href="#import-resolution-and-custom-importers">15.8.2.7. Import resolution and custom importers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#configuration-file-format">15.8.3. Configuration file format</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging.html"
                        title="previous chapter">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging.handlers.html"
                        title="next chapter">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/logging.config.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.handlers.html" title="15.9. logging.handlers — Logging handlers"
             >next</a> |</li>
        <li class="right" >
          <a href="logging.html" title="15.7. logging — Logging facility for Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�F�)B9B9"html/library/logging.handlers.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.9. logging.handlers — Logging handlers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.10. getpass — Portable password input" href="getpass.html" />
    <link rel="prev" title="15.8. logging.config — Logging configuration" href="logging.config.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/logging.handlers.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="getpass.html" title="15.10. getpass — Portable password input"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="logging.config.html" title="15.8. logging.config — Logging configuration"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-logging.handlers">
<span id="logging-handlers-logging-handlers"></span><h1>15.9. <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> — Logging handlers<a class="headerlink" href="#module-logging.handlers" title="Permalink to this headline">¶</a></h1>
<div class="sidebar">
<p class="first sidebar-title">Important</p>
<p>This page contains only reference information. For tutorials,
please see</p>
<ul class="last simple">
<li><a class="reference internal" href="../howto/logging.html#logging-basic-tutorial"><span class="std std-ref">Basic Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging.html#logging-advanced-tutorial"><span class="std std-ref">Advanced Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a></li>
</ul>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/logging/handlers.py">Lib/logging/handlers.py</a></p>
<hr class="docutils" />
<p>The following useful handlers are provided in the package. Note that three of
the handlers (<a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a>, <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> and
<a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a>) are actually defined in the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module itself,
but have been documented here along with the other handlers.</p>
<div class="section" id="streamhandler">
<span id="stream-handler"></span><h2>15.9.1. StreamHandler<a class="headerlink" href="#streamhandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> class, located in the core <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package,
sends logging output to streams such as <em>sys.stdout</em>, <em>sys.stderr</em> or any
file-like object (or, more precisely, any object which supports <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code> methods).</p>
<dl class="class">
<dt id="logging.StreamHandler">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">StreamHandler</code><span class="sig-paren">(</span><em>stream=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.StreamHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> class. If <em>stream</em> is
specified, the instance will use it for logging output; otherwise, <em>sys.stderr</em>
will be used.</p>
<dl class="method">
<dt id="logging.StreamHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.StreamHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>If a formatter is specified, it is used to format the record. The record
is then written to the stream with a newline terminator. If exception
information is present, it is formatted using
<a class="reference internal" href="traceback.html#traceback.print_exception" title="traceback.print_exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">traceback.print_exception()</span></code></a> and appended to the stream.</p>
</dd></dl>

<dl class="method">
<dt id="logging.StreamHandler.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.StreamHandler.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flushes the stream by calling its <a class="reference internal" href="#logging.StreamHandler.flush" title="logging.StreamHandler.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> method. Note that the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method is inherited from <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> and so
does no output, so an explicit <a class="reference internal" href="#logging.StreamHandler.flush" title="logging.StreamHandler.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> call may be needed at times.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="filehandler">
<span id="file-handler"></span><h2>15.9.2. FileHandler<a class="headerlink" href="#filehandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> class, located in the core <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package,
sends logging output to a disk file.  It inherits the output functionality from
<a class="reference internal" href="#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a>.</p>
<dl class="class">
<dt id="logging.FileHandler">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">FileHandler</code><span class="sig-paren">(</span><em>filename</em>, <em>mode='a'</em>, <em>encoding=None</em>, <em>delay=False</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.FileHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.FileHandler" title="logging.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a> class. The specified file is
opened and used as the stream for logging. If <em>mode</em> is not specified,
<code class="xref py py-const docutils literal notranslate"><span class="pre">'a'</span></code> is used.  If <em>encoding</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is used to open the file
with that encoding.  If <em>delay</em> is true, then file opening is deferred until the
first call to <a class="reference internal" href="#logging.FileHandler.emit" title="logging.FileHandler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>. By default, the file grows indefinitely.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p>
</div>
<dl class="method">
<dt id="logging.FileHandler.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.FileHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the file.</p>
</dd></dl>

<dl class="method">
<dt id="logging.FileHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.FileHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Outputs the record to the file.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="nullhandler">
<span id="null-handler"></span><h2>15.9.3. NullHandler<a class="headerlink" href="#nullhandler" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>The <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> class, located in the core <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package,
does not do any formatting or output. It is essentially a ‘no-op’ handler
for use by library developers.</p>
<dl class="class">
<dt id="logging.NullHandler">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">NullHandler</code><a class="headerlink" href="#logging.NullHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a> class.</p>
<dl class="method">
<dt id="logging.NullHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.NullHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>This method does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="logging.NullHandler.handle">
<code class="descname">handle</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.NullHandler.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>This method does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="logging.NullHandler.createLock">
<code class="descname">createLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.NullHandler.createLock" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns <code class="docutils literal notranslate"><span class="pre">None</span></code> for the lock, since there is no
underlying I/O to which access needs to be serialized.</p>
</dd></dl>

</dd></dl>

<p>See <a class="reference internal" href="../howto/logging.html#library-config"><span class="std std-ref">Configuring Logging for a Library</span></a> for more information on how to use
<a class="reference internal" href="#logging.NullHandler" title="logging.NullHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NullHandler</span></code></a>.</p>
</div>
<div class="section" id="watchedfilehandler">
<span id="watched-file-handler"></span><h2>15.9.4. WatchedFileHandler<a class="headerlink" href="#watchedfilehandler" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The <a class="reference internal" href="#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>
module, is a <code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code> which watches the file it is logging to. If
the file changes, it is closed and reopened using the file name.</p>
<p>A file change can happen because of usage of programs such as <em>newsyslog</em> and
<em>logrotate</em> which perform log file rotation. This handler, intended for use
under Unix/Linux, watches the file to see if it has changed since the last emit.
(A file is deemed to have changed if its device or inode have changed.) If the
file has changed, the old file stream is closed, and the file opened to get a
new stream.</p>
<p>This handler is not appropriate for use under Windows, because under Windows
open log files cannot be moved or renamed - logging opens the files with
exclusive locks - and so there is no need for such a handler. Furthermore,
<em>ST_INO</em> is not supported under Windows; <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a> always returns zero
for this value.</p>
<dl class="class">
<dt id="logging.handlers.WatchedFileHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">WatchedFileHandler</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>delay</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.WatchedFileHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.WatchedFileHandler" title="logging.handlers.WatchedFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code></a> class. The specified
file is opened and used as the stream for logging. If <em>mode</em> is not specified,
<code class="xref py py-const docutils literal notranslate"><span class="pre">'a'</span></code> is used.  If <em>encoding</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is used to open the file
with that encoding.  If <em>delay</em> is true, then file opening is deferred until the
first call to <a class="reference internal" href="#logging.handlers.WatchedFileHandler.emit" title="logging.handlers.WatchedFileHandler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>.  By default, the file grows indefinitely.</p>
<dl class="method">
<dt id="logging.handlers.WatchedFileHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.WatchedFileHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Outputs the record to the file, but first checks to see if the file has
changed.  If it has, the existing stream is flushed and closed and the
file opened again, before outputting the record to the file.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="rotatingfilehandler">
<span id="rotating-file-handler"></span><h2>15.9.5. RotatingFileHandler<a class="headerlink" href="#rotatingfilehandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>
module, supports rotation of disk log files.</p>
<dl class="class">
<dt id="logging.handlers.RotatingFileHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">RotatingFileHandler</code><span class="sig-paren">(</span><em>filename</em>, <em>mode='a'</em>, <em>maxBytes=0</em>, <em>backupCount=0</em>, <em>encoding=None</em>, <em>delay=0</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.RotatingFileHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.RotatingFileHandler" title="logging.handlers.RotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code></a> class. The specified
file is opened and used as the stream for logging. If <em>mode</em> is not specified,
<code class="docutils literal notranslate"><span class="pre">'a'</span></code> is used.  If <em>encoding</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is used to open the file
with that encoding.  If <em>delay</em> is true, then file opening is deferred until the
first call to <a class="reference internal" href="#logging.handlers.RotatingFileHandler.emit" title="logging.handlers.RotatingFileHandler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>.  By default, the file grows indefinitely.</p>
<p>You can use the <em>maxBytes</em> and <em>backupCount</em> values to allow the file to
<em class="dfn">rollover</em> at a predetermined size. When the size is about to be exceeded,
the file is closed and a new file is silently opened for output. Rollover occurs
whenever the current log file is nearly <em>maxBytes</em> in length; if either of
<em>maxBytes</em> or <em>backupCount</em> is zero, rollover never occurs.  If <em>backupCount</em>
is non-zero, the system will save old log files by appending the extensions
‘.1’, ‘.2’ etc., to the filename. For example, with a <em>backupCount</em> of 5 and
a base file name of <code class="file docutils literal notranslate"><span class="pre">app.log</span></code>, you would get <code class="file docutils literal notranslate"><span class="pre">app.log</span></code>,
<code class="file docutils literal notranslate"><span class="pre">app.log.1</span></code>, <code class="file docutils literal notranslate"><span class="pre">app.log.2</span></code>, up to <code class="file docutils literal notranslate"><span class="pre">app.log.5</span></code>. The file being
written to is always <code class="file docutils literal notranslate"><span class="pre">app.log</span></code>.  When this file is filled, it is closed
and renamed to <code class="file docutils literal notranslate"><span class="pre">app.log.1</span></code>, and if files <code class="file docutils literal notranslate"><span class="pre">app.log.1</span></code>,
<code class="file docutils literal notranslate"><span class="pre">app.log.2</span></code>, etc.  exist, then they are renamed to <code class="file docutils literal notranslate"><span class="pre">app.log.2</span></code>,
<code class="file docutils literal notranslate"><span class="pre">app.log.3</span></code> etc.  respectively.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>delay</em> was added.</p>
</div>
<dl class="method">
<dt id="logging.handlers.RotatingFileHandler.doRollover">
<code class="descname">doRollover</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.RotatingFileHandler.doRollover" title="Permalink to this definition">¶</a></dt>
<dd><p>Does a rollover, as described above.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.RotatingFileHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.RotatingFileHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Outputs the record to the file, catering for rollover as described
previously.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="timedrotatingfilehandler">
<span id="timed-rotating-file-handler"></span><h2>15.9.6. TimedRotatingFileHandler<a class="headerlink" href="#timedrotatingfilehandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code></a> class, located in the
<a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module, supports rotation of disk log files at certain
timed intervals.</p>
<dl class="class">
<dt id="logging.handlers.TimedRotatingFileHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">TimedRotatingFileHandler</code><span class="sig-paren">(</span><em>filename</em>, <em>when='h'</em>, <em>interval=1</em>, <em>backupCount=0</em>, <em>encoding=None</em>, <em>delay=False</em>, <em>utc=False</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler" title="logging.handlers.TimedRotatingFileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code></a> class. The
specified file is opened and used as the stream for logging. On rotating it also
sets the filename suffix. Rotating happens based on the product of <em>when</em> and
<em>interval</em>.</p>
<p>You can use the <em>when</em> to specify the type of <em>interval</em>. The list of possible
values is below.  Note that they are not case sensitive.</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Type of interval</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'S'</span></code></td>
<td>Seconds</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'M'</span></code></td>
<td>Minutes</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'H'</span></code></td>
<td>Hours</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'D'</span></code></td>
<td>Days</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'W0'-'W6'</span></code></td>
<td>Weekday (0=Monday)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'midnight'</span></code></td>
<td>Roll over at midnight</td>
</tr>
</tbody>
</table>
<p>When using weekday-based rotation, specify ‘W0’ for Monday, ‘W1’ for
Tuesday, and so on up to ‘W6’ for Sunday. In this case, the value passed for
<em>interval</em> isn’t used.</p>
<p>The system will save old log files by appending extensions to the filename.
The extensions are date-and-time based, using the strftime format
<code class="docutils literal notranslate"><span class="pre">%Y-%m-%d_%H-%M-%S</span></code> or a leading portion thereof, depending on the
rollover interval.</p>
<p>When computing the next rollover time for the first time (when the handler
is created), the last modification time of an existing log file, or else
the current time, is used to compute when the next rotation will occur.</p>
<p>If the <em>utc</em> argument is true, times in UTC will be used; otherwise
local time is used.</p>
<p>If <em>backupCount</em> is nonzero, at most <em>backupCount</em> files
will be kept, and if more would be created when rollover occurs, the oldest
one is deleted. The deletion logic uses the interval to determine which
files to delete, so changing the interval may leave old files lying around.</p>
<p>If <em>delay</em> is true, then file opening is deferred until the first call to
<a class="reference internal" href="#logging.handlers.TimedRotatingFileHandler.emit" title="logging.handlers.TimedRotatingFileHandler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>delay</em> and <em>utc</em> were added.</p>
</div>
<dl class="method">
<dt id="logging.handlers.TimedRotatingFileHandler.doRollover">
<code class="descname">doRollover</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler.doRollover" title="Permalink to this definition">¶</a></dt>
<dd><p>Does a rollover, as described above.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.TimedRotatingFileHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.TimedRotatingFileHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Outputs the record to the file, catering for rollover as described above.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="sockethandler">
<span id="socket-handler"></span><h2>15.9.7. SocketHandler<a class="headerlink" href="#sockethandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module,
sends logging output to a network socket. The base class uses a TCP socket.</p>
<dl class="class">
<dt id="logging.handlers.SocketHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">SocketHandler</code><span class="sig-paren">(</span><em>host</em>, <em>port</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> class intended to
communicate with a remote machine whose address is given by <em>host</em> and <em>port</em>.</p>
<dl class="method">
<dt id="logging.handlers.SocketHandler.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the socket.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Pickles the record’s attribute dictionary and writes it to the socket in
binary format. If there is an error with the socket, silently drops the
packet. If the connection was previously lost, re-establishes the
connection. To unpickle the record at the receiving end into a
<a class="reference internal" href="logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>, use the <a class="reference internal" href="logging.html#logging.makeLogRecord" title="logging.makeLogRecord"><code class="xref py py-func docutils literal notranslate"><span class="pre">makeLogRecord()</span></code></a>
function.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.handleError">
<code class="descname">handleError</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.handleError" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles an error which has occurred during <a class="reference internal" href="#logging.handlers.SocketHandler.emit" title="logging.handlers.SocketHandler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a>. The most likely
cause is a lost connection. Closes the socket so that we can retry on the
next event.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.makeSocket">
<code class="descname">makeSocket</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.makeSocket" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a factory method which allows subclasses to define the precise
type of socket they want. The default implementation creates a TCP socket
(<a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.makePickle">
<code class="descname">makePickle</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.makePickle" title="Permalink to this definition">¶</a></dt>
<dd><p>Pickles the record’s attribute dictionary in binary format with a length
prefix, and returns it ready for transmission across the socket.</p>
<p>Note that pickles aren’t completely secure. If you are concerned about
security, you may want to override this method to implement a more secure
mechanism. For example, you can sign pickles using HMAC and then verify
them on the receiving end, or alternatively you can disable unpickling of
global objects on the receiving end.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.send">
<code class="descname">send</code><span class="sig-paren">(</span><em>packet</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a pickled string <em>packet</em> to the socket. This function allows for
partial sends which can happen when the network is busy.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SocketHandler.createSocket">
<code class="descname">createSocket</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SocketHandler.createSocket" title="Permalink to this definition">¶</a></dt>
<dd><p>Tries to create a socket; on failure, uses an exponential back-off
algorithm.  On initial failure, the handler will drop the message it was
trying to send.  When subsequent messages are handled by the same
instance, it will not try connecting until some time has passed.  The
default parameters are such that the initial delay is one second, and if
after that delay the connection still can’t be made, the handler will
double the delay each time up to a maximum of 30 seconds.</p>
<p>This behaviour is controlled by the following handler attributes:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">retryStart</span></code> (initial delay, defaulting to 1.0 seconds).</li>
<li><code class="docutils literal notranslate"><span class="pre">retryFactor</span></code> (multiplier, defaulting to 2.0).</li>
<li><code class="docutils literal notranslate"><span class="pre">retryMax</span></code> (maximum delay, defaulting to 30.0 seconds).</li>
</ul>
<p>This means that if the remote listener starts up <em>after</em> the handler has
been used, you could lose messages (since the handler won’t even attempt
a connection until the delay has elapsed, but just silently drop messages
during the delay period).</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="datagramhandler">
<span id="datagram-handler"></span><h2>15.9.8. DatagramHandler<a class="headerlink" href="#datagramhandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DatagramHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>
module, inherits from <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> to support sending logging messages
over UDP sockets.</p>
<dl class="class">
<dt id="logging.handlers.DatagramHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">DatagramHandler</code><span class="sig-paren">(</span><em>host</em>, <em>port</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.DatagramHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.DatagramHandler" title="logging.handlers.DatagramHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DatagramHandler</span></code></a> class intended to
communicate with a remote machine whose address is given by <em>host</em> and <em>port</em>.</p>
<dl class="method">
<dt id="logging.handlers.DatagramHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.DatagramHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Pickles the record’s attribute dictionary and writes it to the socket in
binary format. If there is an error with the socket, silently drops the
packet. To unpickle the record at the receiving end into a
<a class="reference internal" href="logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>, use the <a class="reference internal" href="logging.html#logging.makeLogRecord" title="logging.makeLogRecord"><code class="xref py py-func docutils literal notranslate"><span class="pre">makeLogRecord()</span></code></a>
function.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.DatagramHandler.makeSocket">
<code class="descname">makeSocket</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.DatagramHandler.makeSocket" title="Permalink to this definition">¶</a></dt>
<dd><p>The factory method of <a class="reference internal" href="#logging.handlers.SocketHandler" title="logging.handlers.SocketHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketHandler</span></code></a> is here overridden to create
a UDP socket (<a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_DGRAM</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.DatagramHandler.send">
<code class="descname">send</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.DatagramHandler.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a pickled string to a socket.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="sysloghandler">
<span id="syslog-handler"></span><h2>15.9.9. SysLogHandler<a class="headerlink" href="#sysloghandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module,
supports sending logging messages to a remote or local Unix syslog.</p>
<dl class="class">
<dt id="logging.handlers.SysLogHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">SysLogHandler</code><span class="sig-paren">(</span><em>address=('localhost'</em>, <em>SYSLOG_UDP_PORT)</em>, <em>facility=LOG_USER</em>, <em>socktype=socket.SOCK_DGRAM</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SysLogHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> class intended to
communicate with a remote Unix machine whose address is given by <em>address</em> in
the form of a <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> tuple.  If <em>address</em> is not specified,
<code class="docutils literal notranslate"><span class="pre">('localhost',</span> <span class="pre">514)</span></code> is used.  The address is used to open a socket.  An
alternative to providing a <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> tuple is providing an address as a
string, for example ‘/dev/log’. In this case, a Unix domain socket is used to
send the message to the syslog. If <em>facility</em> is not specified,
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_USER</span></code> is used. The type of socket opened depends on the
<em>socktype</em> argument, which defaults to <a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_DGRAM</span></code></a> and thus
opens a UDP socket. To open a TCP socket (for use with the newer syslog
daemons such as rsyslog), specify a value of <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code></a>.</p>
<p>Note that if your server is not listening on UDP port 514,
<a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> may appear not to work. In that case, check what
address you should be using for a domain socket - it’s system dependent.
For example, on Linux it’s usually ‘/dev/log’ but on OS/X it’s
‘/var/run/syslog’. You’ll need to check your platform and use the
appropriate address (you may need to do this check at runtime if your
application needs to run on several platforms). On Windows, you pretty
much have to use the UDP option.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>socktype</em> was added.</p>
</div>
<dl class="method">
<dt id="logging.handlers.SysLogHandler.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SysLogHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the socket to the remote host.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SysLogHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SysLogHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>The record is formatted, and then sent to the syslog server. If exception
information is present, it is <em>not</em> sent to the server.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SysLogHandler.encodePriority">
<code class="descname">encodePriority</code><span class="sig-paren">(</span><em>facility</em>, <em>priority</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SysLogHandler.encodePriority" title="Permalink to this definition">¶</a></dt>
<dd><p>Encodes the facility and priority into an integer. You can pass in strings
or integers - if strings are passed, internal mapping dictionaries are
used to convert them to integers.</p>
<p>The symbolic <code class="docutils literal notranslate"><span class="pre">LOG_</span></code> values are defined in <a class="reference internal" href="#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> and
mirror the values defined in the <code class="docutils literal notranslate"><span class="pre">sys/syslog.h</span></code> header file.</p>
<p><strong>Priorities</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="63%" />
<col width="37%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name (string)</th>
<th class="head">Symbolic value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">alert</span></code></td>
<td>LOG_ALERT</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">crit</span></code> or <code class="docutils literal notranslate"><span class="pre">critical</span></code></td>
<td>LOG_CRIT</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">debug</span></code></td>
<td>LOG_DEBUG</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">emerg</span></code> or <code class="docutils literal notranslate"><span class="pre">panic</span></code></td>
<td>LOG_EMERG</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">err</span></code> or <code class="docutils literal notranslate"><span class="pre">error</span></code></td>
<td>LOG_ERR</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">info</span></code></td>
<td>LOG_INFO</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">notice</span></code></td>
<td>LOG_NOTICE</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">warn</span></code> or <code class="docutils literal notranslate"><span class="pre">warning</span></code></td>
<td>LOG_WARNING</td>
</tr>
</tbody>
</table>
<p><strong>Facilities</strong></p>
<table border="1" class="docutils">
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name (string)</th>
<th class="head">Symbolic value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">auth</span></code></td>
<td>LOG_AUTH</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">authpriv</span></code></td>
<td>LOG_AUTHPRIV</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">cron</span></code></td>
<td>LOG_CRON</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">daemon</span></code></td>
<td>LOG_DAEMON</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">ftp</span></code></td>
<td>LOG_FTP</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">kern</span></code></td>
<td>LOG_KERN</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">lpr</span></code></td>
<td>LOG_LPR</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">mail</span></code></td>
<td>LOG_MAIL</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">news</span></code></td>
<td>LOG_NEWS</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">syslog</span></code></td>
<td>LOG_SYSLOG</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">user</span></code></td>
<td>LOG_USER</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">uucp</span></code></td>
<td>LOG_UUCP</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">local0</span></code></td>
<td>LOG_LOCAL0</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">local1</span></code></td>
<td>LOG_LOCAL1</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">local2</span></code></td>
<td>LOG_LOCAL2</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">local3</span></code></td>
<td>LOG_LOCAL3</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">local4</span></code></td>
<td>LOG_LOCAL4</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">local5</span></code></td>
<td>LOG_LOCAL5</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">local6</span></code></td>
<td>LOG_LOCAL6</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">local7</span></code></td>
<td>LOG_LOCAL7</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SysLogHandler.mapPriority">
<code class="descname">mapPriority</code><span class="sig-paren">(</span><em>levelname</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SysLogHandler.mapPriority" title="Permalink to this definition">¶</a></dt>
<dd><p>Maps a logging level name to a syslog priority name.
You may need to override this if you are using custom levels, or
if the default algorithm is not suitable for your needs. The
default algorithm maps <code class="docutils literal notranslate"><span class="pre">DEBUG</span></code>, <code class="docutils literal notranslate"><span class="pre">INFO</span></code>, <code class="docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="docutils literal notranslate"><span class="pre">ERROR</span></code> and
<code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code> to the equivalent syslog names, and all other level
names to ‘warning’.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="nteventloghandler">
<span id="nt-eventlog-handler"></span><h2>15.9.10. NTEventLogHandler<a class="headerlink" href="#nteventloghandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NTEventLogHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>
module, supports sending logging messages to a local Windows NT, Windows 2000 or
Windows XP event log. Before you can use it, you need Mark Hammond’s Win32
extensions for Python installed.</p>
<dl class="class">
<dt id="logging.handlers.NTEventLogHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">NTEventLogHandler</code><span class="sig-paren">(</span><em>appname</em>, <em>dllname=None</em>, <em>logtype='Application'</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.NTEventLogHandler" title="logging.handlers.NTEventLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">NTEventLogHandler</span></code></a> class. The <em>appname</em> is
used to define the application name as it appears in the event log. An
appropriate registry entry is created using this name. The <em>dllname</em> should give
the fully qualified pathname of a .dll or .exe which contains message
definitions to hold in the log (if not specified, <code class="docutils literal notranslate"><span class="pre">'win32service.pyd'</span></code> is used
- this is installed with the Win32 extensions and contains some basic
placeholder message definitions. Note that use of these placeholders will make
your event logs big, as the entire message source is held in the log. If you
want slimmer logs, you have to pass in the name of your own .dll or .exe which
contains the message definitions you want to use in the event log). The
<em>logtype</em> is one of <code class="docutils literal notranslate"><span class="pre">'Application'</span></code>, <code class="docutils literal notranslate"><span class="pre">'System'</span></code> or <code class="docutils literal notranslate"><span class="pre">'Security'</span></code>, and
defaults to <code class="docutils literal notranslate"><span class="pre">'Application'</span></code>.</p>
<dl class="method">
<dt id="logging.handlers.NTEventLogHandler.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>At this point, you can remove the application name from the registry as a
source of event log entries. However, if you do this, you will not be able
to see the events as you intended in the Event Log Viewer - it needs to be
able to access the registry to get the .dll name. The current version does
not do this.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.NTEventLogHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Determines the message ID, event category and event type, and then logs
the message in the NT event log.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.NTEventLogHandler.getEventCategory">
<code class="descname">getEventCategory</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getEventCategory" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the event category for the record. Override this if you want to
specify your own categories. This version returns 0.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.NTEventLogHandler.getEventType">
<code class="descname">getEventType</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getEventType" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the event type for the record. Override this if you want to
specify your own types. This version does a mapping using the handler’s
typemap attribute, which is set up in <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to a dictionary
which contains mappings for <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>. If you are using
your own levels, you will either need to override this method or place a
suitable dictionary in the handler’s <em>typemap</em> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.NTEventLogHandler.getMessageID">
<code class="descname">getMessageID</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.NTEventLogHandler.getMessageID" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the message ID for the record. If you are using your own messages,
you could do this by having the <em>msg</em> passed to the logger being an ID
rather than a format string. Then, in here, you could use a dictionary
lookup to get the message ID. This version returns 1, which is the base
message ID in <code class="file docutils literal notranslate"><span class="pre">win32service.pyd</span></code>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="smtphandler">
<span id="smtp-handler"></span><h2>15.9.11. SMTPHandler<a class="headerlink" href="#smtphandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module,
supports sending logging messages to an email address via SMTP.</p>
<dl class="class">
<dt id="logging.handlers.SMTPHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">SMTPHandler</code><span class="sig-paren">(</span><em>mailhost</em>, <em>fromaddr</em>, <em>toaddrs</em>, <em>subject</em>, <em>credentials=None</em>, <em>secure=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SMTPHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.SMTPHandler" title="logging.handlers.SMTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPHandler</span></code></a> class. The instance is
initialized with the from and to addresses and subject line of the email.
The <em>toaddrs</em> should be a list of strings. To specify a non-standard SMTP
port, use the (host, port) tuple format for the <em>mailhost</em> argument. If you
use a string, the standard SMTP port is used. If your SMTP server requires
authentication, you can specify a (username, password) tuple for the
<em>credentials</em> argument.</p>
<p>To specify the use of a secure protocol (TLS), pass in a tuple to the
<em>secure</em> argument. This will only be used when authentication credentials are
supplied. The tuple should be either an empty tuple, or a single-value tuple
with the name of a keyfile, or a 2-value tuple with the names of the keyfile
and certificate file. (This tuple is passed to the
<a class="reference internal" href="smtplib.html#smtplib.SMTP.starttls" title="smtplib.SMTP.starttls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">smtplib.SMTP.starttls()</span></code></a> method.)</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>credentials</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>secure</em> was added.</p>
</div>
<dl class="method">
<dt id="logging.handlers.SMTPHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SMTPHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Formats the record and sends it to the specified addressees.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.SMTPHandler.getSubject">
<code class="descname">getSubject</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.SMTPHandler.getSubject" title="Permalink to this definition">¶</a></dt>
<dd><p>If you want to specify a subject line which is record-dependent, override
this method.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="memoryhandler">
<span id="memory-handler"></span><h2>15.9.12. MemoryHandler<a class="headerlink" href="#memoryhandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module,
supports buffering of logging records in memory, periodically flushing them to a
<em class="dfn">target</em> handler. Flushing occurs whenever the buffer is full, or when an
event of a certain severity or greater is seen.</p>
<p><a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a> is a subclass of the more general
<a class="reference internal" href="#logging.handlers.BufferingHandler" title="logging.handlers.BufferingHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferingHandler</span></code></a>, which is an abstract class. This buffers logging
records in memory. Whenever each record is added to the buffer, a check is made
by calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">shouldFlush()</span></code> to see if the buffer should be flushed.  If it
should, then <code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code> is expected to do the flushing.</p>
<dl class="class">
<dt id="logging.handlers.BufferingHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">BufferingHandler</code><span class="sig-paren">(</span><em>capacity</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.BufferingHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Initializes the handler with a buffer of the specified capacity.</p>
<dl class="method">
<dt id="logging.handlers.BufferingHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.BufferingHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Appends the record to the buffer. If <a class="reference internal" href="#logging.handlers.BufferingHandler.shouldFlush" title="logging.handlers.BufferingHandler.shouldFlush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shouldFlush()</span></code></a> returns true,
calls <a class="reference internal" href="#logging.handlers.BufferingHandler.flush" title="logging.handlers.BufferingHandler.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> to process the buffer.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.BufferingHandler.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.BufferingHandler.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>You can override this to implement custom flushing behavior. This version
just zaps the buffer to empty.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.BufferingHandler.shouldFlush">
<code class="descname">shouldFlush</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.BufferingHandler.shouldFlush" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the buffer is up to capacity. This method can be
overridden to implement custom flushing strategies.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="logging.handlers.MemoryHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">MemoryHandler</code><span class="sig-paren">(</span><em>capacity</em>, <em>flushLevel=ERROR</em>, <em>target=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.MemoryHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a> class. The instance is
initialized with a buffer size of <em>capacity</em>. If <em>flushLevel</em> is not specified,
<code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> is used. If no <em>target</em> is specified, the target will need to be
set using <a class="reference internal" href="#logging.handlers.MemoryHandler.setTarget" title="logging.handlers.MemoryHandler.setTarget"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setTarget()</span></code></a> before this handler does anything useful.</p>
<dl class="method">
<dt id="logging.handlers.MemoryHandler.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.MemoryHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls <a class="reference internal" href="#logging.handlers.MemoryHandler.flush" title="logging.handlers.MemoryHandler.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a>, sets the target to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and clears the
buffer.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.MemoryHandler.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.MemoryHandler.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>For a <a class="reference internal" href="#logging.handlers.MemoryHandler" title="logging.handlers.MemoryHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MemoryHandler</span></code></a>, flushing means just sending the buffered
records to the target, if there is one. The buffer is also cleared when
this happens. Override if you want different behavior.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.MemoryHandler.setTarget">
<code class="descname">setTarget</code><span class="sig-paren">(</span><em>target</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.MemoryHandler.setTarget" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the target handler for this handler.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.MemoryHandler.shouldFlush">
<code class="descname">shouldFlush</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.MemoryHandler.shouldFlush" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks for buffer full or a record at the <em>flushLevel</em> or higher.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="httphandler">
<span id="http-handler"></span><h2>15.9.13. HTTPHandler<a class="headerlink" href="#httphandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a> class, located in the <a class="reference internal" href="#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module,
supports sending logging messages to a Web server, using either <code class="docutils literal notranslate"><span class="pre">GET</span></code> or
<code class="docutils literal notranslate"><span class="pre">POST</span></code> semantics.</p>
<dl class="class">
<dt id="logging.handlers.HTTPHandler">
<em class="property">class </em><code class="descclassname">logging.handlers.</code><code class="descname">HTTPHandler</code><span class="sig-paren">(</span><em>host</em>, <em>url</em>, <em>method='GET'</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.HTTPHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a> class. The <code class="docutils literal notranslate"><span class="pre">host</span></code> can be
of the form <code class="docutils literal notranslate"><span class="pre">host:port</span></code>, should you need to use a specific port number.</p>
<dl class="method">
<dt id="logging.handlers.HTTPHandler.mapLogRecord">
<code class="descname">mapLogRecord</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.HTTPHandler.mapLogRecord" title="Permalink to this definition">¶</a></dt>
<dd><p>Provides a dictionary, based on <code class="docutils literal notranslate"><span class="pre">record</span></code>, which is to be URL-encoded
and sent to the web server. The default implementation just returns
<code class="docutils literal notranslate"><span class="pre">record.__dict__</span></code>. This method can be overridden if e.g. only a
subset of <a class="reference internal" href="logging.html#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> is to be sent to the web server, or
if more specific customization of what’s sent to the server is required.</p>
</dd></dl>

<dl class="method">
<dt id="logging.handlers.HTTPHandler.emit">
<code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.handlers.HTTPHandler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends the record to the Web server as a URL-encoded dictionary. The
<a class="reference internal" href="#logging.handlers.HTTPHandler.mapLogRecord" title="logging.handlers.HTTPHandler.mapLogRecord"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mapLogRecord()</span></code></a> method is used to convert the record to the
dictionary to be sent.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since preparing a record for sending it to a Web server is not
the same as a generic formatting operation, using <code class="xref py py-meth docutils literal notranslate"><span class="pre">setFormatter()</span></code>
to specify a <code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code> for a <a class="reference internal" href="#logging.handlers.HTTPHandler" title="logging.handlers.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a> has no effect.
Instead of calling <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a>, this handler calls <a class="reference internal" href="#logging.handlers.HTTPHandler.mapLogRecord" title="logging.handlers.HTTPHandler.mapLogRecord"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mapLogRecord()</span></code></a>
and then <a class="reference internal" href="urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a> to encode the dictionary in a form
suitable for sending to a Web server.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a></dt>
<dd>API reference for the logging module.</dd>
<dt>Module <a class="reference internal" href="logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a></dt>
<dd>Configuration API for the logging module.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a><ul>
<li><a class="reference internal" href="#streamhandler">15.9.1. StreamHandler</a></li>
<li><a class="reference internal" href="#filehandler">15.9.2. FileHandler</a></li>
<li><a class="reference internal" href="#nullhandler">15.9.3. NullHandler</a></li>
<li><a class="reference internal" href="#watchedfilehandler">15.9.4. WatchedFileHandler</a></li>
<li><a class="reference internal" href="#rotatingfilehandler">15.9.5. RotatingFileHandler</a></li>
<li><a class="reference internal" href="#timedrotatingfilehandler">15.9.6. TimedRotatingFileHandler</a></li>
<li><a class="reference internal" href="#sockethandler">15.9.7. SocketHandler</a></li>
<li><a class="reference internal" href="#datagramhandler">15.9.8. DatagramHandler</a></li>
<li><a class="reference internal" href="#sysloghandler">15.9.9. SysLogHandler</a></li>
<li><a class="reference internal" href="#nteventloghandler">15.9.10. NTEventLogHandler</a></li>
<li><a class="reference internal" href="#smtphandler">15.9.11. SMTPHandler</a></li>
<li><a class="reference internal" href="#memoryhandler">15.9.12. MemoryHandler</a></li>
<li><a class="reference internal" href="#httphandler">15.9.13. HTTPHandler</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="logging.config.html"
                        title="previous chapter">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="getpass.html"
                        title="next chapter">15.10. <code class="docutils literal notranslate"><span class="pre">getpass</span></code> — Portable password input</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/logging.handlers.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="getpass.html" title="15.10. getpass — Portable password input"
             >next</a> |</li>
        <li class="right" >
          <a href="logging.config.html" title="15.8. logging.config — Logging configuration"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\}�>����html/library/logging.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.7. logging — Logging facility for Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.8. logging.config — Logging configuration" href="logging.config.html" />
    <link rel="prev" title="15.6. getopt — C-style parser for command line options" href="getopt.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/logging.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.config.html" title="15.8. logging.config — Logging configuration"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="15.6. getopt — C-style parser for command line options"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-logging">
<span id="logging-logging-facility-for-python"></span><h1>15.7. <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> — Logging facility for Python<a class="headerlink" href="#module-logging" title="Permalink to this headline">¶</a></h1>
<div class="sidebar" id="index-0">
<p class="first sidebar-title">Important</p>
<p>This page contains the API reference information. For tutorial
information and discussion of more advanced topics, see</p>
<ul class="last simple">
<li><a class="reference internal" href="../howto/logging.html#logging-basic-tutorial"><span class="std std-ref">Basic Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging.html#logging-advanced-tutorial"><span class="std std-ref">Advanced Tutorial</span></a></li>
<li><a class="reference internal" href="../howto/logging-cookbook.html#logging-cookbook"><span class="std std-ref">Logging Cookbook</span></a></li>
</ul>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/logging/__init__.py">Lib/logging/__init__.py</a></p>
<hr class="docutils" />
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module defines functions and classes which implement a flexible event
logging system for applications and libraries.</p>
<p>The key benefit of having the logging API provided by a standard library module
is that all Python modules can participate in logging, so your application log
can include your own messages integrated with messages from third-party
modules.</p>
<p>The module provides a lot of functionality and flexibility.  If you are
unfamiliar with logging, the best way to get to grips with it is to see the
tutorials (see the links on the right).</p>
<p>The basic classes defined by the module, together with their functions, are
listed below.</p>
<ul class="simple">
<li>Loggers expose the interface that application code directly uses.</li>
<li>Handlers send the log records (created by loggers) to the appropriate
destination.</li>
<li>Filters provide a finer grained facility for determining which log records
to output.</li>
<li>Formatters specify the layout of log records in the final output.</li>
</ul>
<div class="section" id="logger-objects">
<span id="logger"></span><h2>15.7.1. Logger Objects<a class="headerlink" href="#logger-objects" title="Permalink to this headline">¶</a></h2>
<p>Loggers have the following attributes and methods.  Note that Loggers are never
instantiated directly, but always through the module-level function
<code class="docutils literal notranslate"><span class="pre">logging.getLogger(name)</span></code>.  Multiple calls to <a class="reference internal" href="#logging.getLogger" title="logging.getLogger"><code class="xref py py-func docutils literal notranslate"><span class="pre">getLogger()</span></code></a> with the same
name will always return a reference to the same Logger object.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">name</span></code> is potentially a period-separated hierarchical value, like
<code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code> (though it could also be just plain <code class="docutils literal notranslate"><span class="pre">foo</span></code>, for example).
Loggers that are further down in the hierarchical list are children of loggers
higher up in the list.  For example, given a logger with a name of <code class="docutils literal notranslate"><span class="pre">foo</span></code>,
loggers with names of <code class="docutils literal notranslate"><span class="pre">foo.bar</span></code>, <code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code>, and <code class="docutils literal notranslate"><span class="pre">foo.bam</span></code> are all
descendants of <code class="docutils literal notranslate"><span class="pre">foo</span></code>.  The logger name hierarchy is analogous to the Python
package hierarchy, and identical to it if you organise your loggers on a
per-module basis using the recommended construction
<code class="docutils literal notranslate"><span class="pre">logging.getLogger(__name__)</span></code>.  That’s because in a module, <code class="docutils literal notranslate"><span class="pre">__name__</span></code>
is the module’s name in the Python package namespace.</p>
<dl class="class">
<dt id="logging.Logger">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">Logger</code><a class="headerlink" href="#logging.Logger" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="attribute">
<dt id="logging.Logger.propagate">
<code class="descclassname">Logger.</code><code class="descname">propagate</code><a class="headerlink" href="#logging.Logger.propagate" title="Permalink to this definition">¶</a></dt>
<dd><p>If this evaluates to true, events logged to this logger will be passed to the
handlers of higher level (ancestor) loggers, in addition to any handlers
attached to this logger. Messages are passed directly to the ancestor
loggers’ handlers - neither the level nor filters of the ancestor loggers in
question are considered.</p>
<p>If this evaluates to false, logging messages are not passed to the handlers
of ancestor loggers.</p>
<p>The constructor sets this attribute to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you attach a handler to a logger <em>and</em> one or more of its
ancestors, it may emit the same record multiple times. In general, you
should not need to attach a handler to more than one logger - if you just
attach it to the appropriate logger which is highest in the logger
hierarchy, then it will see all events logged by all descendant loggers,
provided that their propagate setting is left set to <code class="docutils literal notranslate"><span class="pre">True</span></code>. A common
scenario is to attach handlers only to the root logger, and to let
propagation take care of the rest.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.setLevel">
<code class="descclassname">Logger.</code><code class="descname">setLevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.setLevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the threshold for this logger to <em>level</em>. Logging messages which are less
severe than <em>level</em> will be ignored. When a logger is created, the level is set to
<code class="xref py py-const docutils literal notranslate"><span class="pre">NOTSET</span></code> (which causes all messages to be processed when the logger is
the root logger, or delegation to the parent when the logger is a non-root
logger). Note that the root logger is created with level <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>.</p>
<p>The term ‘delegation to the parent’ means that if a logger has a level of
NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
a level other than NOTSET is found, or the root is reached.</p>
<p>If an ancestor is found with a level other than NOTSET, then that ancestor’s
level is treated as the effective level of the logger where the ancestor search
began, and is used to determine how a logging event is handled.</p>
<p>If the root is reached, and it has a level of NOTSET, then all messages will be
processed. Otherwise, the root’s level will be used as the effective level.</p>
<p>See <a class="reference internal" href="#levels"><span class="std std-ref">Logging Levels</span></a> for a list of levels.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.isEnabledFor">
<code class="descclassname">Logger.</code><code class="descname">isEnabledFor</code><span class="sig-paren">(</span><em>lvl</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.isEnabledFor" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates if a message of severity <em>lvl</em> would be processed by this logger.
This method checks first the module-level level set by
<code class="docutils literal notranslate"><span class="pre">logging.disable(lvl)</span></code> and then the logger’s effective level as determined
by <a class="reference internal" href="#logging.Logger.getEffectiveLevel" title="logging.Logger.getEffectiveLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getEffectiveLevel()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.getEffectiveLevel">
<code class="descclassname">Logger.</code><code class="descname">getEffectiveLevel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.getEffectiveLevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates the effective level for this logger. If a value other than
<code class="xref py py-const docutils literal notranslate"><span class="pre">NOTSET</span></code> has been set using <a class="reference internal" href="#logging.Logger.setLevel" title="logging.Logger.setLevel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setLevel()</span></code></a>, it is returned. Otherwise,
the hierarchy is traversed towards the root until a value other than
<code class="xref py py-const docutils literal notranslate"><span class="pre">NOTSET</span></code> is found, and that value is returned. The value returned is
an integer, typically one of <code class="xref py py-const docutils literal notranslate"><span class="pre">logging.DEBUG</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">logging.INFO</span></code>
etc.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.getChild">
<code class="descclassname">Logger.</code><code class="descname">getChild</code><span class="sig-paren">(</span><em>suffix</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.getChild" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a logger which is a descendant to this logger, as determined by the suffix.
Thus, <code class="docutils literal notranslate"><span class="pre">logging.getLogger('abc').getChild('def.ghi')</span></code> would return the same
logger as would be returned by <code class="docutils literal notranslate"><span class="pre">logging.getLogger('abc.def.ghi')</span></code>. This is a
convenience method, useful when the parent logger is named using e.g. <code class="docutils literal notranslate"><span class="pre">__name__</span></code>
rather than a literal string.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.debug">
<code class="descclassname">Logger.</code><code class="descname">debug</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code> on this logger. The <em>msg</em> is the
message format string, and the <em>args</em> are the arguments which are merged into
<em>msg</em> using the string formatting operator. (Note that this means that you can
use keywords in the format string, together with a single dictionary argument.)</p>
<p>There are two keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em>
which, if it does not evaluate as false, causes exception information to be
added to the logging message. If an exception tuple (in the format returned by
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>) is provided, it is used; otherwise, <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
is called to get the exception information.</p>
<p>The second keyword argument is <em>extra</em> which can be used to pass a
dictionary which is used to populate the __dict__ of the LogRecord created for
the logging event with user-defined attributes. These custom attributes can then
be used as you like. For example, they could be incorporated into logged
messages. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">FORMAT</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">%(asctime)-15s</span><span class="s1"> </span><span class="si">%(clientip)s</span><span class="s1"> </span><span class="si">%(user)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="n">FORMAT</span><span class="p">)</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;clientip&#39;</span><span class="p">:</span> <span class="s1">&#39;192.168.0.1&#39;</span><span class="p">,</span> <span class="s1">&#39;user&#39;</span><span class="p">:</span> <span class="s1">&#39;fbloggs&#39;</span><span class="p">}</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;tcpserver&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Protocol problem: </span><span class="si">%s</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;connection reset&#39;</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">d</span><span class="p">)</span>
</pre></div>
</div>
<p>would print something like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2006</span><span class="o">-</span><span class="mi">02</span><span class="o">-</span><span class="mi">08</span> <span class="mi">22</span><span class="p">:</span><span class="mi">20</span><span class="p">:</span><span class="mi">02</span><span class="p">,</span><span class="mi">165</span> <span class="mf">192.168</span><span class="o">.</span><span class="mf">0.1</span> <span class="n">fbloggs</span>  <span class="n">Protocol</span> <span class="n">problem</span><span class="p">:</span> <span class="n">connection</span> <span class="n">reset</span>
</pre></div>
</div>
<p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used
by the logging system. (See the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> documentation for more
information on which keys are used by the logging system.)</p>
<p>If you choose to use these attributes in logged messages, you need to exercise
some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> has been
set up with a format string which expects ‘clientip’ and ‘user’ in the attribute
dictionary of the LogRecord. If these are missing, the message will not be
logged because a string formatting exception will occur. So in this case, you
always need to pass the <em>extra</em> dictionary with these keys.</p>
<p>While this might be annoying, this feature is intended for use in specialized
circumstances, such as multi-threaded servers where the same code executes in
many contexts, and interesting conditions which arise are dependent on this
context (such as remote client IP address and authenticated user name, in the
above example). In such circumstances, it is likely that specialized
<a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>s would be used with particular <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>s.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.info">
<code class="descclassname">Logger.</code><code class="descname">info</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.info" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code> on this logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.warning">
<code class="descclassname">Logger.</code><code class="descname">warning</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.warning" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code> on this logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.error">
<code class="descclassname">Logger.</code><code class="descname">error</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> on this logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.critical">
<code class="descclassname">Logger.</code><code class="descname">critical</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.critical" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code> on this logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.log">
<code class="descclassname">Logger.</code><code class="descname">log</code><span class="sig-paren">(</span><em>lvl</em>, <em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.log" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with integer level <em>lvl</em> on this logger. The other arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.exception">
<code class="descclassname">Logger.</code><code class="descname">exception</code><span class="sig-paren">(</span><em>msg</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> on this logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>, except that any passed <em>exc_info</em> is not
inspected. Exception info is always added to the logging message. This method
should only be called from an exception handler.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.addFilter">
<code class="descclassname">Logger.</code><code class="descname">addFilter</code><span class="sig-paren">(</span><em>filter</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.addFilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the specified filter <em>filter</em> to this logger.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.removeFilter">
<code class="descclassname">Logger.</code><code class="descname">removeFilter</code><span class="sig-paren">(</span><em>filter</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.removeFilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the specified filter <em>filter</em> from this logger.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.filter">
<code class="descclassname">Logger.</code><code class="descname">filter</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Applies this logger’s filters to the record and returns a true value if the
record is to be processed. The filters are consulted in turn, until one of
them returns a false value. If none of them return a false value, the record
will be processed (passed to handlers). If one returns a false value, no
further processing of the record occurs.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.addHandler">
<code class="descclassname">Logger.</code><code class="descname">addHandler</code><span class="sig-paren">(</span><em>hdlr</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.addHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the specified handler <em>hdlr</em> to this logger.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.removeHandler">
<code class="descclassname">Logger.</code><code class="descname">removeHandler</code><span class="sig-paren">(</span><em>hdlr</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.removeHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the specified handler <em>hdlr</em> from this logger.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.findCaller">
<code class="descclassname">Logger.</code><code class="descname">findCaller</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.findCaller" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds the caller’s source filename and line number. Returns the filename, line
number and function name as a 3-element tuple.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The function name was added. In earlier versions, the filename and line
number were returned as a 2-element tuple.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.handle">
<code class="descclassname">Logger.</code><code class="descname">handle</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles a record by passing it to all handlers associated with this logger and
its ancestors (until a false value of <em>propagate</em> is found). This method is used
for unpickled records received from a socket, as well as those created locally.
Logger-level filtering is applied using <a class="reference internal" href="#logging.Logger.filter" title="logging.Logger.filter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">filter()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Logger.makeRecord">
<code class="descclassname">Logger.</code><code class="descname">makeRecord</code><span class="sig-paren">(</span><em>name</em>, <em>lvl</em>, <em>fn</em>, <em>lno</em>, <em>msg</em>, <em>args</em>, <em>exc_info</em>, <em>func=None</em>, <em>extra=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Logger.makeRecord" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a factory method which can be overridden in subclasses to create
specialized <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instances.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><em>func</em> and <em>extra</em> were added.</p>
</div>
</dd></dl>

</div>
<div class="section" id="logging-levels">
<span id="levels"></span><h2>15.7.2. Logging Levels<a class="headerlink" href="#logging-levels" title="Permalink to this headline">¶</a></h2>
<p>The numeric values of logging levels are given in the following table. These are
primarily of interest if you want to define your own levels, and need them to
have specific values relative to the predefined levels. If you define a level
with the same numeric value, it overwrites the predefined value; the predefined
name is lost.</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">Numeric value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">CRITICAL</span></code></td>
<td>50</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">ERROR</span></code></td>
<td>40</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">WARNING</span></code></td>
<td>30</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INFO</span></code></td>
<td>20</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">DEBUG</span></code></td>
<td>10</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">NOTSET</span></code></td>
<td>0</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="handler-objects">
<span id="handler"></span><h2>15.7.3. Handler Objects<a class="headerlink" href="#handler-objects" title="Permalink to this headline">¶</a></h2>
<p>Handlers have the following attributes and methods. Note that <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>
is never instantiated directly; this class acts as a base for more useful
subclasses. However, the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method in subclasses needs to call
<a class="reference internal" href="#logging.Handler.__init__" title="logging.Handler.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Handler.__init__()</span></code></a>.</p>
<dl class="method">
<dt id="logging.Handler.__init__">
<code class="descclassname">Handler.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>level=NOTSET</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p>Initializes the <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> instance by setting its level, setting the list
of filters to the empty list and creating a lock (using <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">createLock()</span></code></a>) for
serializing access to an I/O mechanism.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.createLock">
<code class="descclassname">Handler.</code><code class="descname">createLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.createLock" title="Permalink to this definition">¶</a></dt>
<dd><p>Initializes a thread lock which can be used to serialize access to underlying
I/O functionality which may not be threadsafe.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.acquire">
<code class="descclassname">Handler.</code><code class="descname">acquire</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquires the thread lock created with <a class="reference internal" href="#logging.Handler.createLock" title="logging.Handler.createLock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">createLock()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.release">
<code class="descclassname">Handler.</code><code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases the thread lock acquired with <a class="reference internal" href="#logging.Handler.acquire" title="logging.Handler.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.setLevel">
<code class="descclassname">Handler.</code><code class="descname">setLevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.setLevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the threshold for this handler to <em>level</em>. Logging messages which are less
severe than <em>level</em> will be ignored. When a handler is created, the level is set
to <code class="xref py py-const docutils literal notranslate"><span class="pre">NOTSET</span></code> (which causes all messages to be processed).</p>
<p>See <a class="reference internal" href="#levels"><span class="std std-ref">Logging Levels</span></a> for a list of levels.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.setFormatter">
<code class="descclassname">Handler.</code><code class="descname">setFormatter</code><span class="sig-paren">(</span><em>fmt</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.setFormatter" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> for this handler to <em>fmt</em>.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.addFilter">
<code class="descclassname">Handler.</code><code class="descname">addFilter</code><span class="sig-paren">(</span><em>filter</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.addFilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the specified filter <em>filter</em> to this handler.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.removeFilter">
<code class="descclassname">Handler.</code><code class="descname">removeFilter</code><span class="sig-paren">(</span><em>filter</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.removeFilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the specified filter <em>filter</em> from this handler.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.filter">
<code class="descclassname">Handler.</code><code class="descname">filter</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Applies this handler’s filters to the record and returns a true value if the
record is to be processed. The filters are consulted in turn, until one of
them returns a false value. If none of them return a false value, the record
will be emitted. If one returns a false value, the handler will not emit the
record.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.flush">
<code class="descclassname">Handler.</code><code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Ensure all logging output has been flushed. This version does nothing and is
intended to be implemented by subclasses.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.close">
<code class="descclassname">Handler.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Tidy up any resources used by the handler. This version does no output but
removes the handler from an internal list of handlers which is closed when
<a class="reference internal" href="#logging.shutdown" title="logging.shutdown"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutdown()</span></code></a> is called. Subclasses should ensure that this gets called
from overridden <a class="reference internal" href="#logging.Handler.close" title="logging.Handler.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> methods.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.handle">
<code class="descclassname">Handler.</code><code class="descname">handle</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>Conditionally emits the specified logging record, depending on filters which may
have been added to the handler. Wraps the actual emission of the record with
acquisition/release of the I/O thread lock.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.handleError">
<code class="descclassname">Handler.</code><code class="descname">handleError</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.handleError" title="Permalink to this definition">¶</a></dt>
<dd><p>This method should be called from handlers when an exception is encountered
during an <a class="reference internal" href="#logging.Handler.emit" title="logging.Handler.emit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code></a> call. If the module-level attribute
<code class="docutils literal notranslate"><span class="pre">raiseExceptions</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, exceptions get silently ignored. This is
what is mostly wanted for a logging system - most users will not care about
errors in the logging system, they are more interested in application
errors. You could, however, replace this with a custom handler if you wish.
The specified record is the one which was being processed when the exception
occurred. (The default value of <code class="docutils literal notranslate"><span class="pre">raiseExceptions</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, as that is
more useful during development).</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.format">
<code class="descclassname">Handler.</code><code class="descname">format</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.format" title="Permalink to this definition">¶</a></dt>
<dd><p>Do formatting for a record - if a formatter is set, use it. Otherwise, use the
default formatter for the module.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Handler.emit">
<code class="descclassname">Handler.</code><code class="descname">emit</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Handler.emit" title="Permalink to this definition">¶</a></dt>
<dd><p>Do whatever it takes to actually log the specified logging record. This version
is intended to be implemented by subclasses and so raises a
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.</p>
</dd></dl>

<p>For a list of handlers included as standard, see <a class="reference internal" href="logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a>.</p>
</div>
<div class="section" id="formatter-objects">
<span id="id1"></span><h2>15.7.4. Formatter Objects<a class="headerlink" href="#formatter-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> objects have the following attributes and methods. They are
responsible for converting a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> to (usually) a string which can
be interpreted by either a human or an external system. The base
<a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> allows a formatting string to be specified. If none is
supplied, the default value of <code class="docutils literal notranslate"><span class="pre">'%(message)s'</span></code> is used, which just includes
the message in the logging call. To have additional items of information in the
formatted output (such as a timestamp), keep reading.</p>
<p>A Formatter can be initialized with a format string which makes use of knowledge
of the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> attributes - such as the default value mentioned above
making use of the fact that the user’s message and arguments are pre-formatted
into a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a>’s <em>message</em> attribute.  This format string contains
standard Python %-style mapping keys. See section <a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a>
for more information on string formatting.</p>
<p>The useful mapping keys in a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> are given in the section on
<a class="reference internal" href="#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>.</p>
<dl class="class">
<dt id="logging.Formatter">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">Formatter</code><span class="sig-paren">(</span><em>fmt=None</em>, <em>datefmt=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Formatter" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> class.  The instance is
initialized with a format string for the message as a whole, as well as a
format string for the date/time portion of a message.  If no <em>fmt</em> is
specified, <code class="docutils literal notranslate"><span class="pre">'%(message)s'</span></code> is used.  If no <em>datefmt</em> is specified, the
ISO8601 date format is used.</p>
<dl class="method">
<dt id="logging.Formatter.format">
<code class="descname">format</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Formatter.format" title="Permalink to this definition">¶</a></dt>
<dd><p>The record’s attribute dictionary is used as the operand to a string
formatting operation. Returns the resulting string. Before formatting the
dictionary, a couple of preparatory steps are carried out. The <em>message</em>
attribute of the record is computed using <em>msg</em> % <em>args</em>. If the
formatting string contains <code class="docutils literal notranslate"><span class="pre">'(asctime)'</span></code>, <a class="reference internal" href="#logging.Formatter.formatTime" title="logging.Formatter.formatTime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formatTime()</span></code></a> is called
to format the event time. If there is exception information, it is
formatted using <a class="reference internal" href="#logging.Formatter.formatException" title="logging.Formatter.formatException"><code class="xref py py-meth docutils literal notranslate"><span class="pre">formatException()</span></code></a> and appended to the message. Note
that the formatted exception information is cached in attribute
<em>exc_text</em>. This is useful because the exception information can be
pickled and sent across the wire, but you should be careful if you have
more than one <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> subclass which customizes the formatting
of exception information. In this case, you will have to clear the cached
value after a formatter has done its formatting, so that the next
formatter to handle the event doesn’t use the cached value but
recalculates it afresh.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Formatter.formatTime">
<code class="descname">formatTime</code><span class="sig-paren">(</span><em>record</em>, <em>datefmt=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Formatter.formatTime" title="Permalink to this definition">¶</a></dt>
<dd><p>This method should be called from <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> by a formatter which
wants to make use of a formatted time. This method can be overridden in
formatters to provide for any specific requirement, but the basic behavior
is as follows: if <em>datefmt</em> (a string) is specified, it is used with
<a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a> to format the creation time of the
record. Otherwise, the ISO8601 format is used.  The resulting string is
returned.</p>
<p>This function uses a user-configurable function to convert the creation
time to a tuple. By default, <a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> is used; to change
this for a particular formatter instance, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code> attribute
to a function with the same signature as <a class="reference internal" href="time.html#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.localtime()</span></code></a> or
<a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a>. To change it for all formatters, for example if you
want all logging times to be shown in GMT, set the <code class="docutils literal notranslate"><span class="pre">converter</span></code>
attribute in the <code class="docutils literal notranslate"><span class="pre">Formatter</span></code> class.</p>
</dd></dl>

<dl class="method">
<dt id="logging.Formatter.formatException">
<code class="descname">formatException</code><span class="sig-paren">(</span><em>exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Formatter.formatException" title="Permalink to this definition">¶</a></dt>
<dd><p>Formats the specified exception information (a standard exception tuple as
returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>) as a string. This default implementation
just uses <a class="reference internal" href="traceback.html#traceback.print_exception" title="traceback.print_exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">traceback.print_exception()</span></code></a>. The resulting string is
returned.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="filter-objects">
<span id="filter"></span><h2>15.7.5. Filter Objects<a class="headerlink" href="#filter-objects" title="Permalink to this headline">¶</a></h2>
<p><code class="docutils literal notranslate"><span class="pre">Filters</span></code> can be used by <code class="docutils literal notranslate"><span class="pre">Handlers</span></code> and <code class="docutils literal notranslate"><span class="pre">Loggers</span></code> for more sophisticated
filtering than is provided by levels. The base filter class only allows events
which are below a certain point in the logger hierarchy. For example, a filter
initialized with ‘A.B’ will allow events logged by loggers ‘A.B’, ‘A.B.C’,
‘A.B.C.D’, ‘A.B.D’ etc. but not ‘A.BB’, ‘B.A.B’ etc. If initialized with the
empty string, all events are passed.</p>
<dl class="class">
<dt id="logging.Filter">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">Filter</code><span class="sig-paren">(</span><em>name=''</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an instance of the <a class="reference internal" href="#logging.Filter" title="logging.Filter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Filter</span></code></a> class. If <em>name</em> is specified, it
names a logger which, together with its children, will have its events allowed
through the filter. If <em>name</em> is the empty string, allows every event.</p>
<dl class="method">
<dt id="logging.Filter.filter">
<code class="descname">filter</code><span class="sig-paren">(</span><em>record</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.Filter.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Is the specified record to be logged? Returns zero for no, nonzero for
yes. If deemed appropriate, the record may be modified in-place by this
method.</p>
</dd></dl>

</dd></dl>

<p>Note that filters attached to handlers are consulted before an event is
emitted by the handler, whereas filters attached to loggers are consulted
whenever an event is logged (using <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="#logging.info" title="logging.info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code></a>,
etc.), before sending an event to handlers. This means that events which have
been generated by descendant loggers will not be filtered by a logger’s filter
setting, unless the filter has also been applied to those descendant loggers.</p>
<p>You don’t actually need to subclass <code class="docutils literal notranslate"><span class="pre">Filter</span></code>: you can pass any instance
which has a <code class="docutils literal notranslate"><span class="pre">filter</span></code> method with the same semantics.</p>
<p>Although filters are used primarily to filter records based on more
sophisticated criteria than levels, they get to see every record which is
processed by the handler or logger they’re attached to: this can be useful if
you want to do things like counting how many records were processed by a
particular logger or handler, or adding, changing or removing attributes in
the LogRecord being processed. Obviously changing the LogRecord needs to be
done with some care, but it does allow the injection of contextual information
into logs (see <a class="reference internal" href="../howto/logging-cookbook.html#filters-contextual"><span class="std std-ref">Using Filters to impart contextual information</span></a>).</p>
</div>
<div class="section" id="logrecord-objects">
<span id="log-record"></span><h2>15.7.6. LogRecord Objects<a class="headerlink" href="#logrecord-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instances are created automatically by the <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>
every time something is logged, and can be created manually via
<a class="reference internal" href="#logging.makeLogRecord" title="logging.makeLogRecord"><code class="xref py py-func docutils literal notranslate"><span class="pre">makeLogRecord()</span></code></a> (for example, from a pickled event received over the
wire).</p>
<dl class="class">
<dt id="logging.LogRecord">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">LogRecord</code><span class="sig-paren">(</span><em>name</em>, <em>level</em>, <em>pathname</em>, <em>lineno</em>, <em>msg</em>, <em>args</em>, <em>exc_info</em>, <em>func=None</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.LogRecord" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains all the information pertinent to the event being logged.</p>
<p>The primary information is passed in <code class="xref py py-attr docutils literal notranslate"><span class="pre">msg</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code>, which
are combined using <code class="docutils literal notranslate"><span class="pre">msg</span> <span class="pre">%</span> <span class="pre">args</span></code> to create the <code class="xref py py-attr docutils literal notranslate"><span class="pre">message</span></code> field of the
record.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>name</strong> – The name of the logger used to log the event represented by
this LogRecord. Note that this name will always have this
value, even though it may be emitted by a handler attached to
a different (ancestor) logger.</li>
<li><strong>level</strong> – The numeric level of the logging event (one of DEBUG, INFO etc.)
Note that this is converted to <em>two</em> attributes of the LogRecord:
<code class="docutils literal notranslate"><span class="pre">levelno</span></code> for the numeric value and <code class="docutils literal notranslate"><span class="pre">levelname</span></code> for the
corresponding level name.</li>
<li><strong>pathname</strong> – The full pathname of the source file where the logging call
was made.</li>
<li><strong>lineno</strong> – The line number in the source file where the logging call was
made.</li>
<li><strong>msg</strong> – The event description message, possibly a format string with
placeholders for variable data.</li>
<li><strong>args</strong> – Variable data to merge into the <em>msg</em> argument to obtain the
event description.</li>
<li><strong>exc_info</strong> – An exception tuple with the current exception information,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no exception information is available.</li>
<li><strong>func</strong> – The name of the function or method from which the logging call
was invoked.</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><em>func</em> was added.</p>
</div>
<dl class="method">
<dt id="logging.LogRecord.getMessage">
<code class="descname">getMessage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.LogRecord.getMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the message for this <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance after merging any
user-supplied arguments with the message. If the user-supplied message
argument to the logging call is not a string, <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> is called on it to
convert it to a string. This allows use of user-defined classes as
messages, whose <code class="docutils literal notranslate"><span class="pre">__str__</span></code> method can return the actual format string to
be used.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="logrecord-attributes">
<span id="id2"></span><h2>15.7.7. LogRecord attributes<a class="headerlink" href="#logrecord-attributes" title="Permalink to this headline">¶</a></h2>
<p>The LogRecord has a number of attributes, most of which are derived from the
parameters to the constructor. (Note that the names do not always correspond
exactly between the LogRecord constructor parameters and the LogRecord
attributes.) These attributes can be used to merge data from the record into
the format string. The following table lists (in alphabetical order) the
attribute names, their meanings and the corresponding placeholder in a %-style
format string.</p>
<table border="1" class="docutils">
<colgroup>
<col width="18%" />
<col width="28%" />
<col width="53%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute name</th>
<th class="head">Format</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>args</td>
<td>You shouldn’t need to
format this yourself.</td>
<td>The tuple of arguments merged into <code class="docutils literal notranslate"><span class="pre">msg</span></code> to
produce <code class="docutils literal notranslate"><span class="pre">message</span></code>, or a dict whose values
are used for the merge (when there is only one
argument, and it is a dictionary).</td>
</tr>
<tr class="row-odd"><td>asctime</td>
<td><code class="docutils literal notranslate"><span class="pre">%(asctime)s</span></code></td>
<td>Human-readable time when the
<a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> was created.  By default
this is of the form ‘2003-07-08 16:49:45,896’
(the numbers after the comma are millisecond
portion of the time).</td>
</tr>
<tr class="row-even"><td>created</td>
<td><code class="docutils literal notranslate"><span class="pre">%(created)f</span></code></td>
<td>Time when the <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> was created
(as returned by <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>).</td>
</tr>
<tr class="row-odd"><td>exc_info</td>
<td>You shouldn’t need to
format this yourself.</td>
<td>Exception tuple (à la <code class="docutils literal notranslate"><span class="pre">sys.exc_info</span></code>) or,
if no exception has occurred, <code class="docutils literal notranslate"><span class="pre">None</span></code>.</td>
</tr>
<tr class="row-even"><td>filename</td>
<td><code class="docutils literal notranslate"><span class="pre">%(filename)s</span></code></td>
<td>Filename portion of <code class="docutils literal notranslate"><span class="pre">pathname</span></code>.</td>
</tr>
<tr class="row-odd"><td>funcName</td>
<td><code class="docutils literal notranslate"><span class="pre">%(funcName)s</span></code></td>
<td>Name of function containing the logging call.</td>
</tr>
<tr class="row-even"><td>levelname</td>
<td><code class="docutils literal notranslate"><span class="pre">%(levelname)s</span></code></td>
<td>Text logging level for the message
(<code class="docutils literal notranslate"><span class="pre">'DEBUG'</span></code>, <code class="docutils literal notranslate"><span class="pre">'INFO'</span></code>, <code class="docutils literal notranslate"><span class="pre">'WARNING'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'ERROR'</span></code>, <code class="docutils literal notranslate"><span class="pre">'CRITICAL'</span></code>).</td>
</tr>
<tr class="row-odd"><td>levelno</td>
<td><code class="docutils literal notranslate"><span class="pre">%(levelno)s</span></code></td>
<td>Numeric logging level for the message
(<code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>).</td>
</tr>
<tr class="row-even"><td>lineno</td>
<td><code class="docutils literal notranslate"><span class="pre">%(lineno)d</span></code></td>
<td>Source line number where the logging call was
issued (if available).</td>
</tr>
<tr class="row-odd"><td>module</td>
<td><code class="docutils literal notranslate"><span class="pre">%(module)s</span></code></td>
<td>Module (name portion of <code class="docutils literal notranslate"><span class="pre">filename</span></code>).</td>
</tr>
<tr class="row-even"><td>msecs</td>
<td><code class="docutils literal notranslate"><span class="pre">%(msecs)d</span></code></td>
<td>Millisecond portion of the time when the
<a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> was created.</td>
</tr>
<tr class="row-odd"><td>message</td>
<td><code class="docutils literal notranslate"><span class="pre">%(message)s</span></code></td>
<td>The logged message, computed as <code class="docutils literal notranslate"><span class="pre">msg</span> <span class="pre">%</span>
<span class="pre">args</span></code>. This is set when
<a class="reference internal" href="#logging.Formatter.format" title="logging.Formatter.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Formatter.format()</span></code></a> is invoked.</td>
</tr>
<tr class="row-even"><td>msg</td>
<td>You shouldn’t need to
format this yourself.</td>
<td>The format string passed in the original
logging call. Merged with <code class="docutils literal notranslate"><span class="pre">args</span></code> to
produce <code class="docutils literal notranslate"><span class="pre">message</span></code>, or an arbitrary object
(see <a class="reference internal" href="../howto/logging.html#arbitrary-object-messages"><span class="std std-ref">Using arbitrary objects as messages</span></a>).</td>
</tr>
<tr class="row-odd"><td>name</td>
<td><code class="docutils literal notranslate"><span class="pre">%(name)s</span></code></td>
<td>Name of the logger used to log the call.</td>
</tr>
<tr class="row-even"><td>pathname</td>
<td><code class="docutils literal notranslate"><span class="pre">%(pathname)s</span></code></td>
<td>Full pathname of the source file where the
logging call was issued (if available).</td>
</tr>
<tr class="row-odd"><td>process</td>
<td><code class="docutils literal notranslate"><span class="pre">%(process)d</span></code></td>
<td>Process ID (if available).</td>
</tr>
<tr class="row-even"><td>processName</td>
<td><code class="docutils literal notranslate"><span class="pre">%(processName)s</span></code></td>
<td>Process name (if available).</td>
</tr>
<tr class="row-odd"><td>relativeCreated</td>
<td><code class="docutils literal notranslate"><span class="pre">%(relativeCreated)d</span></code></td>
<td>Time in milliseconds when the LogRecord was
created, relative to the time the logging
module was loaded.</td>
</tr>
<tr class="row-even"><td>thread</td>
<td><code class="docutils literal notranslate"><span class="pre">%(thread)d</span></code></td>
<td>Thread ID (if available).</td>
</tr>
<tr class="row-odd"><td>threadName</td>
<td><code class="docutils literal notranslate"><span class="pre">%(threadName)s</span></code></td>
<td>Thread name (if available).</td>
</tr>
</tbody>
</table>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><em>funcName</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>processName</em> was added.</p>
</div>
</div>
<div class="section" id="loggeradapter-objects">
<span id="logger-adapter"></span><h2>15.7.8. LoggerAdapter Objects<a class="headerlink" href="#loggeradapter-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> instances are used to conveniently pass contextual
information into logging calls. For a usage example, see the section on
<a class="reference internal" href="../howto/logging-cookbook.html#context-info"><span class="std std-ref">adding contextual information to your logging output</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<dl class="class">
<dt id="logging.LoggerAdapter">
<em class="property">class </em><code class="descclassname">logging.</code><code class="descname">LoggerAdapter</code><span class="sig-paren">(</span><em>logger</em>, <em>extra</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.LoggerAdapter" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an instance of <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> initialized with an
underlying <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instance and a dict-like object.</p>
<dl class="method">
<dt id="logging.LoggerAdapter.process">
<code class="descname">process</code><span class="sig-paren">(</span><em>msg</em>, <em>kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.LoggerAdapter.process" title="Permalink to this definition">¶</a></dt>
<dd><p>Modifies the message and/or keyword arguments passed to a logging call in
order to insert contextual information. This implementation takes the object
passed as <em>extra</em> to the constructor and adds it to <em>kwargs</em> using key
‘extra’. The return value is a (<em>msg</em>, <em>kwargs</em>) tuple which has the
(possibly modified) versions of the arguments passed in.</p>
</dd></dl>

</dd></dl>

<p>In addition to the above, <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> supports the following
methods of <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>: <a class="reference internal" href="#logging.Logger.debug" title="logging.Logger.debug"><code class="xref py py-meth docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="#logging.Logger.info" title="logging.Logger.info"><code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code></a>,
<a class="reference internal" href="#logging.Logger.warning" title="logging.Logger.warning"><code class="xref py py-meth docutils literal notranslate"><span class="pre">warning()</span></code></a>, <a class="reference internal" href="#logging.Logger.error" title="logging.Logger.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code></a>, <a class="reference internal" href="#logging.Logger.exception" title="logging.Logger.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exception()</span></code></a>,
<a class="reference internal" href="#logging.Logger.critical" title="logging.Logger.critical"><code class="xref py py-meth docutils literal notranslate"><span class="pre">critical()</span></code></a>, <a class="reference internal" href="#logging.Logger.log" title="logging.Logger.log"><code class="xref py py-meth docutils literal notranslate"><span class="pre">log()</span></code></a> and <a class="reference internal" href="#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code></a>.
These methods have the same signatures as their counterparts in <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a>,
so you can use the two types of instances interchangeably for these calls.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The <a class="reference internal" href="#logging.Logger.isEnabledFor" title="logging.Logger.isEnabledFor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code></a> method was added to <a class="reference internal" href="#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a>.
This method delegates to the underlying logger.</p>
</div>
</div>
<div class="section" id="thread-safety">
<h2>15.7.9. Thread Safety<a class="headerlink" href="#thread-safety" title="Permalink to this headline">¶</a></h2>
<p>The logging module is intended to be thread-safe without any special work
needing to be done by its clients. It achieves this though using threading
locks; there is one lock to serialize access to the module’s shared data, and
each handler also creates a lock to serialize access to its underlying I/O.</p>
<p>If you are implementing asynchronous signal handlers using the <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>
module, you may not be able to use logging from within such handlers. This is
because lock implementations in the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module are not always
re-entrant, and so cannot be invoked from such signal handlers.</p>
</div>
<div class="section" id="module-level-functions">
<h2>15.7.10. Module-Level Functions<a class="headerlink" href="#module-level-functions" title="Permalink to this headline">¶</a></h2>
<p>In addition to the classes described above, there are a number of module- level
functions.</p>
<dl class="function">
<dt id="logging.getLogger">
<code class="descclassname">logging.</code><code class="descname">getLogger</code><span class="sig-paren">(</span><span class="optional">[</span><em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.getLogger" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a logger with the specified name or, if no name is specified, return a
logger which is the root logger of the hierarchy. If specified, the name is
typically a dot-separated hierarchical name like <em>“a”</em>, <em>“a.b”</em> or <em>“a.b.c.d”</em>.
Choice of these names is entirely up to the developer who is using logging.</p>
<p>All calls to this function with a given name return the same logger instance.
This means that logger instances never need to be passed between different parts
of an application.</p>
</dd></dl>

<dl class="function">
<dt id="logging.getLoggerClass">
<code class="descclassname">logging.</code><code class="descname">getLoggerClass</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.getLoggerClass" title="Permalink to this definition">¶</a></dt>
<dd><p>Return either the standard <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> class, or the last class passed to
<a class="reference internal" href="#logging.setLoggerClass" title="logging.setLoggerClass"><code class="xref py py-func docutils literal notranslate"><span class="pre">setLoggerClass()</span></code></a>. This function may be called from within a new class
definition, to ensure that installing a customized <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> class will
not undo customizations already applied by other code. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyLogger</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">getLoggerClass</span><span class="p">()):</span>
    <span class="c1"># ... override behaviour here</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.debug">
<code class="descclassname">logging.</code><code class="descname">debug</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code> on the root logger. The <em>msg</em> is the
message format string, and the <em>args</em> are the arguments which are merged into
<em>msg</em> using the string formatting operator. (Note that this means that you can
use keywords in the format string, together with a single dictionary argument.)</p>
<p>There are two keyword arguments in <em>kwargs</em> which are inspected: <em>exc_info</em>
which, if it does not evaluate as false, causes exception information to be
added to the logging message. If an exception tuple (in the format returned by
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>) is provided, it is used; otherwise, <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
is called to get the exception information.</p>
<p>The other optional keyword argument is <em>extra</em> which can be used to pass a
dictionary which is used to populate the __dict__ of the LogRecord created for
the logging event with user-defined attributes. These custom attributes can then
be used as you like. For example, they could be incorporated into logged
messages. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">FORMAT</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">%(asctime)-15s</span><span class="s2"> </span><span class="si">%(clientip)s</span><span class="s2"> </span><span class="si">%(user)-8s</span><span class="s2"> </span><span class="si">%(message)s</span><span class="s2">&quot;</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="nb">format</span><span class="o">=</span><span class="n">FORMAT</span><span class="p">)</span>
<span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;clientip&#39;</span><span class="p">:</span> <span class="s1">&#39;192.168.0.1&#39;</span><span class="p">,</span> <span class="s1">&#39;user&#39;</span><span class="p">:</span> <span class="s1">&#39;fbloggs&#39;</span><span class="p">}</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s2">&quot;Protocol problem: </span><span class="si">%s</span><span class="s2">&quot;</span><span class="p">,</span> <span class="s2">&quot;connection reset&quot;</span><span class="p">,</span> <span class="n">extra</span><span class="o">=</span><span class="n">d</span><span class="p">)</span>
</pre></div>
</div>
<p>would print something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">2006</span><span class="o">-</span><span class="mi">02</span><span class="o">-</span><span class="mi">08</span> <span class="mi">22</span><span class="p">:</span><span class="mi">20</span><span class="p">:</span><span class="mi">02</span><span class="p">,</span><span class="mi">165</span> <span class="mf">192.168</span><span class="o">.</span><span class="mf">0.1</span> <span class="n">fbloggs</span>  <span class="n">Protocol</span> <span class="n">problem</span><span class="p">:</span> <span class="n">connection</span> <span class="n">reset</span>
</pre></div>
</div>
<p>The keys in the dictionary passed in <em>extra</em> should not clash with the keys used
by the logging system. (See the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> documentation for more
information on which keys are used by the logging system.)</p>
<p>If you choose to use these attributes in logged messages, you need to exercise
some care. In the above example, for instance, the <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> has been
set up with a format string which expects ‘clientip’ and ‘user’ in the attribute
dictionary of the LogRecord. If these are missing, the message will not be
logged because a string formatting exception will occur. So in this case, you
always need to pass the <em>extra</em> dictionary with these keys.</p>
<p>While this might be annoying, this feature is intended for use in specialized
circumstances, such as multi-threaded servers where the same code executes in
many contexts, and interesting conditions which arise are dependent on this
context (such as remote client IP address and authenticated user name, in the
above example). In such circumstances, it is likely that specialized
<a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>s would be used with particular <code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code>s.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><em>extra</em> was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.info">
<code class="descclassname">logging.</code><code class="descname">info</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.info" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code> on the root logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="logging.warning">
<code class="descclassname">logging.</code><code class="descname">warning</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.warning" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code> on the root logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="logging.error">
<code class="descclassname">logging.</code><code class="descname">error</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> on the root logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="logging.critical">
<code class="descclassname">logging.</code><code class="descname">critical</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.critical" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code> on the root logger. The arguments
are interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="logging.exception">
<code class="descclassname">logging.</code><code class="descname">exception</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code> on the root logger. The arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>, except that any passed <em>exc_info</em> is not
inspected. Exception info is always added to the logging message. This
function should only be called from an exception handler.</p>
</dd></dl>

<dl class="function">
<dt id="logging.log">
<code class="descclassname">logging.</code><code class="descname">log</code><span class="sig-paren">(</span><em>level</em>, <em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.log" title="Permalink to this definition">¶</a></dt>
<dd><p>Logs a message with level <em>level</em> on the root logger. The other arguments are
interpreted as for <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The above module-level convenience functions, which delegate to the
root logger, call <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> to ensure that at least one handler
is available. Because of this, they should <em>not</em> be used in threads,
in versions of Python earlier than 2.7.1 and 3.2, unless at least one
handler has been added to the root logger <em>before</em> the threads are
started. In earlier versions of Python, due to a thread safety shortcoming
in <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a>, this can (under rare circumstances) lead to
handlers being added multiple times to the root logger, which can in turn
lead to multiple messages for the same event.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.disable">
<code class="descclassname">logging.</code><code class="descname">disable</code><span class="sig-paren">(</span><em>lvl</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.disable" title="Permalink to this definition">¶</a></dt>
<dd><p>Provides an overriding level <em>lvl</em> for all loggers which takes precedence over
the logger’s own level. When the need arises to temporarily throttle logging
output down across the whole application, this function can be useful. Its
effect is to disable all logging calls of severity <em>lvl</em> and below, so that
if you call it with a value of INFO, then all INFO and DEBUG events would be
discarded, whereas those of severity WARNING and above would be processed
according to the logger’s effective level. If
<code class="docutils literal notranslate"><span class="pre">logging.disable(logging.NOTSET)</span></code> is called, it effectively removes this
overriding level, so that logging output again depends on the effective
levels of individual loggers.</p>
</dd></dl>

<dl class="function">
<dt id="logging.addLevelName">
<code class="descclassname">logging.</code><code class="descname">addLevelName</code><span class="sig-paren">(</span><em>lvl</em>, <em>levelName</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.addLevelName" title="Permalink to this definition">¶</a></dt>
<dd><p>Associates level <em>lvl</em> with text <em>levelName</em> in an internal dictionary, which is
used to map numeric levels to a textual representation, for example when a
<a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> formats a message. This function can also be used to define
your own levels. The only constraints are that all levels used must be
registered using this function, levels should be positive integers and they
should increase in increasing order of severity.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you are thinking of defining your own levels, please see the
section on <a class="reference internal" href="../howto/logging.html#custom-levels"><span class="std std-ref">Custom Levels</span></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.getLevelName">
<code class="descclassname">logging.</code><code class="descname">getLevelName</code><span class="sig-paren">(</span><em>lvl</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.getLevelName" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the textual representation of logging level <em>lvl</em>. If the level is one
of the predefined levels <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code> then you get the corresponding string. If you
have associated levels with names using <a class="reference internal" href="#logging.addLevelName" title="logging.addLevelName"><code class="xref py py-func docutils literal notranslate"><span class="pre">addLevelName()</span></code></a> then the name you
have associated with <em>lvl</em> is returned. If a numeric value corresponding to one
of the defined levels is passed in, the corresponding string representation is
returned. Otherwise, the string “Level %s” % lvl is returned.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Integer levels should be used when e.g. setting levels on instances
of <a class="reference internal" href="#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> and handlers. This function is used to convert between
an integer level and the level name displayed in the formatted log output
by means of the <code class="docutils literal notranslate"><span class="pre">%(levelname)s</span></code> format specifier (see
<a class="reference internal" href="#logrecord-attributes"><span class="std std-ref">LogRecord attributes</span></a>).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="logging.makeLogRecord">
<code class="descclassname">logging.</code><code class="descname">makeLogRecord</code><span class="sig-paren">(</span><em>attrdict</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.makeLogRecord" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates and returns a new <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance whose attributes are
defined by <em>attrdict</em>. This function is useful for taking a pickled
<a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> attribute dictionary, sent over a socket, and reconstituting
it as a <a class="reference internal" href="#logging.LogRecord" title="logging.LogRecord"><code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code></a> instance at the receiving end.</p>
</dd></dl>

<dl class="function">
<dt id="logging.basicConfig">
<code class="descclassname">logging.</code><code class="descname">basicConfig</code><span class="sig-paren">(</span><span class="optional">[</span><em>**kwargs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.basicConfig" title="Permalink to this definition">¶</a></dt>
<dd><p>Does basic configuration for the logging system by creating a
<a class="reference internal" href="logging.handlers.html#logging.StreamHandler" title="logging.StreamHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamHandler</span></code></a> with a default <a class="reference internal" href="#logging.Formatter" title="logging.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> and adding it to the
root logger. The functions <a class="reference internal" href="#logging.debug" title="logging.debug"><code class="xref py py-func docutils literal notranslate"><span class="pre">debug()</span></code></a>, <a class="reference internal" href="#logging.info" title="logging.info"><code class="xref py py-func docutils literal notranslate"><span class="pre">info()</span></code></a>, <a class="reference internal" href="#logging.warning" title="logging.warning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code></a>,
<a class="reference internal" href="#logging.error" title="logging.error"><code class="xref py py-func docutils literal notranslate"><span class="pre">error()</span></code></a> and <a class="reference internal" href="#logging.critical" title="logging.critical"><code class="xref py py-func docutils literal notranslate"><span class="pre">critical()</span></code></a> will call <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> automatically
if no handlers are defined for the root logger.</p>
<p>This function does nothing if the root logger already has handlers
configured for it.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, <a class="reference internal" href="#logging.basicConfig" title="logging.basicConfig"><code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code></a> did not take any keyword arguments.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function should be called from the main thread before other
threads are started. In versions of Python prior to 2.7.1 and 3.2, if
this function is called from multiple threads, it is possible (in rare
circumstances) that a handler will be added to the root logger more than
once, leading to unexpected results such as messages being duplicated in
the log.</p>
</div>
<p>The following keyword arguments are supported.</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><em>filename</em></td>
<td>Specifies that a FileHandler be created,
using the specified filename, rather than a
StreamHandler.</td>
</tr>
<tr class="row-odd"><td><em>filemode</em></td>
<td>If <em>filename</em> is specified, open the file
in this mode. Defaults to <code class="docutils literal notranslate"><span class="pre">'a'</span></code>.</td>
</tr>
<tr class="row-even"><td><em>format</em></td>
<td>Use the specified format string for the
handler.</td>
</tr>
<tr class="row-odd"><td><em>datefmt</em></td>
<td>Use the specified date/time format, as
accepted by <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>.</td>
</tr>
<tr class="row-even"><td><em>level</em></td>
<td>Set the root logger level to the specified
<a class="reference internal" href="#levels"><span class="std std-ref">level</span></a>.</td>
</tr>
<tr class="row-odd"><td><em>stream</em></td>
<td>Use the specified stream to initialize the
StreamHandler. Note that this argument is
incompatible with <em>filename</em> - if both are
present, <em>stream</em> is ignored.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="function">
<dt id="logging.shutdown">
<code class="descclassname">logging.</code><code class="descname">shutdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#logging.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Informs the logging system to perform an orderly shutdown by flushing and
closing all handlers. This should be called at application exit and no
further use of the logging system should be made after this call.</p>
</dd></dl>

<dl class="function">
<dt id="logging.setLoggerClass">
<code class="descclassname">logging.</code><code class="descname">setLoggerClass</code><span class="sig-paren">(</span><em>klass</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.setLoggerClass" title="Permalink to this definition">¶</a></dt>
<dd><p>Tells the logging system to use the class <em>klass</em> when instantiating a logger.
The class should define <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> such that only a name argument is
required, and the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> should call <code class="xref py py-meth docutils literal notranslate"><span class="pre">Logger.__init__()</span></code>. This
function is typically called before any loggers are instantiated by applications
which need to use custom logger behavior.</p>
</dd></dl>

</div>
<div class="section" id="integration-with-the-warnings-module">
<h2>15.7.11. Integration with the warnings module<a class="headerlink" href="#integration-with-the-warnings-module" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#logging.captureWarnings" title="logging.captureWarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">captureWarnings()</span></code></a> function can be used to integrate <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a>
with the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module.</p>
<dl class="function">
<dt id="logging.captureWarnings">
<code class="descclassname">logging.</code><code class="descname">captureWarnings</code><span class="sig-paren">(</span><em>capture</em><span class="sig-paren">)</span><a class="headerlink" href="#logging.captureWarnings" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used to turn the capture of warnings by logging on and
off.</p>
<p>If <em>capture</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, warnings issued by the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module will
be redirected to the logging system. Specifically, a warning will be
formatted using <a class="reference internal" href="warnings.html#warnings.formatwarning" title="warnings.formatwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.formatwarning()</span></code></a> and the resulting string
logged to a logger named <code class="docutils literal notranslate"><span class="pre">'py.warnings'</span></code> with a severity of <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>.</p>
<p>If <em>capture</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the redirection of warnings to the logging system
will stop, and warnings will be redirected to their original destinations
(i.e. those in effect before <code class="docutils literal notranslate"><span class="pre">captureWarnings(True)</span></code> was called).</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="logging.config.html#module-logging.config" title="logging.config: Configuration of the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.config</span></code></a></dt>
<dd>Configuration API for the logging module.</dd>
<dt>Module <a class="reference internal" href="logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a></dt>
<dd>Useful handlers included with the logging module.</dd>
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> - A Logging System</dt>
<dd>The proposal which described this feature for inclusion in the Python standard
library.</dd>
<dt><a class="reference external" href="https://www.red-dove.com/python_logging.html">Original Python logging package</a></dt>
<dd>This is the original source for the <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package.  The version of the
package available from this site is suitable for use with Python 1.5.2, 2.1.x
and 2.2.x, which do not include the <a class="reference internal" href="#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package in the standard
library.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a><ul>
<li><a class="reference internal" href="#logger-objects">15.7.1. Logger Objects</a></li>
<li><a class="reference internal" href="#logging-levels">15.7.2. Logging Levels</a></li>
<li><a class="reference internal" href="#handler-objects">15.7.3. Handler Objects</a></li>
<li><a class="reference internal" href="#formatter-objects">15.7.4. Formatter Objects</a></li>
<li><a class="reference internal" href="#filter-objects">15.7.5. Filter Objects</a></li>
<li><a class="reference internal" href="#logrecord-objects">15.7.6. LogRecord Objects</a></li>
<li><a class="reference internal" href="#logrecord-attributes">15.7.7. LogRecord attributes</a></li>
<li><a class="reference internal" href="#loggeradapter-objects">15.7.8. LoggerAdapter Objects</a></li>
<li><a class="reference internal" href="#thread-safety">15.7.9. Thread Safety</a></li>
<li><a class="reference internal" href="#module-level-functions">15.7.10. Module-Level Functions</a></li>
<li><a class="reference internal" href="#integration-with-the-warnings-module">15.7.11. Integration with the warnings module</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="getopt.html"
                        title="previous chapter">15.6. <code class="docutils literal notranslate"><span class="pre">getopt</span></code> — C-style parser for command line options</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="logging.config.html"
                        title="next chapter">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/logging.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.config.html" title="15.8. logging.config — Logging configuration"
             >next</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="15.6. getopt — C-style parser for command line options"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\y‹GP[P[html/library/mac.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37. Mac OS X specific services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.1. ic — Access to the Mac OS X Internet Config" href="ic.html" />
    <link rel="prev" title="36.16. commands — Utilities for running commands" href="commands.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mac.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ic.html" title="37.1. ic — Access to the Mac OS X Internet Config"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="commands.html" title="36.16. commands — Utilities for running commands"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="mac-os-x-specific-services">
<span id="mac-specific-services"></span><h1>37. Mac OS X specific services<a class="headerlink" href="#mac-os-x-specific-services" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes modules that are only available on the Mac OS X platform.</p>
<p>See the chapters <a class="reference internal" href="macosa.html#mac-scripting"><span class="std std-ref">MacPython OSA Modules</span></a> and <a class="reference internal" href="undoc.html#undoc-mac-modules"><span class="std std-ref">Undocumented Mac OS modules</span></a> for more
modules, and the HOWTO <a class="reference internal" href="../using/mac.html#using-on-mac"><span class="std std-ref">Using Python on a Macintosh</span></a> for a general introduction to
Mac-specific Python programming.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Most of the OS X APIs that these modules use are deprecated or removed
in recent versions of OS X.  Many are not available when Python is
executing in 64-bit mode.  These modules have been removed in
Python 3.  You should avoid using them in Python 2.</p>
</div>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="ic.html">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ic.html#ic-objects">37.1.1. IC Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="macos.html">37.2. <code class="docutils literal notranslate"><span class="pre">MacOS</span></code> — Access to Mac OS interpreter features</a></li>
<li class="toctree-l1"><a class="reference internal" href="macostools.html">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></li>
<li class="toctree-l1"><a class="reference internal" href="macostools.html#module-findertools">37.4. <code class="docutils literal notranslate"><span class="pre">findertools</span></code> — The <strong class="program">finder</strong>’s Apple Events interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="easydialogs.html">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="easydialogs.html#progressbar-objects">37.5.1. ProgressBar Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="framework.html">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a><ul>
<li class="toctree-l2"><a class="reference internal" href="framework.html#application-objects">37.6.1. Application Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="framework.html#window-objects">37.6.2. Window Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="framework.html#controlswindow-object">37.6.3. ControlsWindow Object</a></li>
<li class="toctree-l2"><a class="reference internal" href="framework.html#scrolledwindow-object">37.6.4. ScrolledWindow Object</a></li>
<li class="toctree-l2"><a class="reference internal" href="framework.html#dialogwindow-objects">37.6.5. DialogWindow Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="autogil.html">37.7. <code class="docutils literal notranslate"><span class="pre">autoGIL</span></code> — Global Interpreter Lock handling in event loops</a></li>
<li class="toctree-l1"><a class="reference internal" href="carbon.html">37.8. Mac OS Toolbox Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.AE">37.8.1. <code class="docutils literal notranslate"><span class="pre">Carbon.AE</span></code> — Apple Events</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.AH">37.8.2. <code class="docutils literal notranslate"><span class="pre">Carbon.AH</span></code> — Apple Help</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.App">37.8.3. <code class="docutils literal notranslate"><span class="pre">Carbon.App</span></code> — Appearance Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Appearance">37.8.4. <code class="docutils literal notranslate"><span class="pre">Carbon.Appearance</span></code> — Appearance Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CF">37.8.5. <code class="docutils literal notranslate"><span class="pre">Carbon.CF</span></code> — Core Foundation</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CG">37.8.6. <code class="docutils literal notranslate"><span class="pre">Carbon.CG</span></code> — Core Graphics</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CarbonEvt">37.8.7. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvt</span></code> — Carbon Event Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CarbonEvents">37.8.8. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvents</span></code> — Carbon Event Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Cm">37.8.9. <code class="docutils literal notranslate"><span class="pre">Carbon.Cm</span></code> — Component Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Components">37.8.10. <code class="docutils literal notranslate"><span class="pre">Carbon.Components</span></code> — Component Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.ControlAccessor">37.8.11. <code class="docutils literal notranslate"><span class="pre">Carbon.ControlAccessor</span></code> — Control Manager accssors</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Controls">37.8.12. <code class="docutils literal notranslate"><span class="pre">Carbon.Controls</span></code> — Control Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CoreFounation">37.8.13. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreFounation</span></code> — CoreFounation constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.CoreGraphics">37.8.14. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreGraphics</span></code> — CoreGraphics constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Ctl">37.8.15. <code class="docutils literal notranslate"><span class="pre">Carbon.Ctl</span></code> — Control Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Dialogs">37.8.16. <code class="docutils literal notranslate"><span class="pre">Carbon.Dialogs</span></code> — Dialog Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Dlg">37.8.17. <code class="docutils literal notranslate"><span class="pre">Carbon.Dlg</span></code> — Dialog Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Drag">37.8.18. <code class="docutils literal notranslate"><span class="pre">Carbon.Drag</span></code> — Drag and Drop Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Dragconst">37.8.19. <code class="docutils literal notranslate"><span class="pre">Carbon.Dragconst</span></code> — Drag and Drop Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Events">37.8.20. <code class="docutils literal notranslate"><span class="pre">Carbon.Events</span></code> — Event Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Evt">37.8.21. <code class="docutils literal notranslate"><span class="pre">Carbon.Evt</span></code> — Event Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.File">37.8.22. <code class="docutils literal notranslate"><span class="pre">Carbon.File</span></code> — File Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Files">37.8.23. <code class="docutils literal notranslate"><span class="pre">Carbon.Files</span></code> — File Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Fm">37.8.24. <code class="docutils literal notranslate"><span class="pre">Carbon.Fm</span></code> — Font Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Folder">37.8.25. <code class="docutils literal notranslate"><span class="pre">Carbon.Folder</span></code> — Folder Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Folders">37.8.26. <code class="docutils literal notranslate"><span class="pre">Carbon.Folders</span></code> — Folder Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Fonts">37.8.27. <code class="docutils literal notranslate"><span class="pre">Carbon.Fonts</span></code> — Font Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Help">37.8.28. <code class="docutils literal notranslate"><span class="pre">Carbon.Help</span></code> — Help Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.IBCarbon">37.8.29. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbon</span></code> — Carbon InterfaceBuilder</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.IBCarbonRuntime">37.8.30. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbonRuntime</span></code> — Carbon InterfaceBuilder constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Icns">37.8.31. <code class="docutils literal notranslate"><span class="pre">Carbon.Icn</span></code> — Carbon Icon Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Icons">37.8.32. <code class="docutils literal notranslate"><span class="pre">Carbon.Icons</span></code> — Carbon Icon Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Launch">37.8.33. <code class="docutils literal notranslate"><span class="pre">Carbon.Launch</span></code> — Carbon Launch Services</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.LaunchServices">37.8.34. <code class="docutils literal notranslate"><span class="pre">Carbon.LaunchServices</span></code> — Carbon Launch Services constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.List">37.8.35. <code class="docutils literal notranslate"><span class="pre">Carbon.List</span></code> — List Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Lists">37.8.36. <code class="docutils literal notranslate"><span class="pre">Carbon.Lists</span></code> — List Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.MacHelp">37.8.37. <code class="docutils literal notranslate"><span class="pre">Carbon.MacHelp</span></code> — Help Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.MediaDescr">37.8.38. <code class="docutils literal notranslate"><span class="pre">Carbon.MediaDescr</span></code> — Parsers and generators for Quicktime Media descriptors</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Menu">37.8.39. <code class="docutils literal notranslate"><span class="pre">Carbon.Menu</span></code> — Menu Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Menus">37.8.40. <code class="docutils literal notranslate"><span class="pre">Carbon.Menus</span></code> — Menu Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Mlte">37.8.41. <code class="docutils literal notranslate"><span class="pre">Carbon.Mlte</span></code> — MultiLingual Text Editor</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.OSA">37.8.42. <code class="docutils literal notranslate"><span class="pre">Carbon.OSA</span></code> — Carbon OSA Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.OSAconst">37.8.43. <code class="docutils literal notranslate"><span class="pre">Carbon.OSAconst</span></code> — Carbon OSA Interface constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.QDOffscreen">37.8.44. <code class="docutils literal notranslate"><span class="pre">Carbon.QDOffscreen</span></code> — QuickDraw Offscreen constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Qd">37.8.45. <code class="docutils literal notranslate"><span class="pre">Carbon.Qd</span></code> — QuickDraw</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Qdoffs">37.8.46. <code class="docutils literal notranslate"><span class="pre">Carbon.Qdoffs</span></code> — QuickDraw Offscreen</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Qt">37.8.47. <code class="docutils literal notranslate"><span class="pre">Carbon.Qt</span></code> — QuickTime</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.QuickDraw">37.8.48. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickDraw</span></code> — QuickDraw constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.QuickTime">37.8.49. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickTime</span></code> — QuickTime constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Res">37.8.50. <code class="docutils literal notranslate"><span class="pre">Carbon.Res</span></code> — Resource Manager and Handles</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Resources">37.8.51. <code class="docutils literal notranslate"><span class="pre">Carbon.Resources</span></code> — Resource Manager and Handles constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Scrap">37.8.52. <code class="docutils literal notranslate"><span class="pre">Carbon.Scrap</span></code> — Scrap Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Snd">37.8.53. <code class="docutils literal notranslate"><span class="pre">Carbon.Snd</span></code> — Sound Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Sound">37.8.54. <code class="docutils literal notranslate"><span class="pre">Carbon.Sound</span></code> — Sound Manager constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.TE">37.8.55. <code class="docutils literal notranslate"><span class="pre">Carbon.TE</span></code> — TextEdit</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.TextEdit">37.8.56. <code class="docutils literal notranslate"><span class="pre">Carbon.TextEdit</span></code> — TextEdit constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Win">37.8.57. <code class="docutils literal notranslate"><span class="pre">Carbon.Win</span></code> — Window Manager</a></li>
<li class="toctree-l2"><a class="reference internal" href="carbon.html#module-Carbon.Windows">37.8.58. <code class="docutils literal notranslate"><span class="pre">Carbon.Windows</span></code> — Window Manager constants</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="colorpicker.html">37.9. <code class="docutils literal notranslate"><span class="pre">ColorPicker</span></code> — Color selection dialog</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="commands.html"
                        title="previous chapter">36.16. <code class="docutils literal notranslate"><span class="pre">commands</span></code> — Utilities for running commands</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ic.html"
                        title="next chapter">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mac.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ic.html" title="37.1. ic — Access to the Mac OS X Internet Config"
             >next</a> |</li>
        <li class="right" >
          <a href="commands.html" title="36.16. commands — Utilities for running commands"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���??html/library/macos.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.2. MacOS — Access to Mac OS interpreter features &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.3. macostools — Convenience routines for file manipulation" href="macostools.html" />
    <link rel="prev" title="37.1. ic — Access to the Mac OS X Internet Config" href="ic.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/macos.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macostools.html" title="37.3. macostools — Convenience routines for file manipulation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ic.html" title="37.1. ic — Access to the Mac OS X Internet Config"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-MacOS">
<span id="macos-access-to-mac-os-interpreter-features"></span><h1>37.2. <a class="reference internal" href="#module-MacOS" title="MacOS: Access to Mac OS-specific interpreter features. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MacOS</span></code></a> — Access to Mac OS interpreter features<a class="headerlink" href="#module-MacOS" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to MacOS specific functionality in the Python
interpreter, such as how the interpreter eventloop functions and the like. Use
with care.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.x.</p>
</div>
<p>Note the capitalization of the module name; this is a historical artifact.</p>
<dl class="data">
<dt id="MacOS.runtimemodel">
<code class="descclassname">MacOS.</code><code class="descname">runtimemodel</code><a class="headerlink" href="#MacOS.runtimemodel" title="Permalink to this definition">¶</a></dt>
<dd><p>Always <code class="docutils literal notranslate"><span class="pre">'macho'</span></code>, from Python 2.4 on. In earlier versions of Python the value
could also be <code class="docutils literal notranslate"><span class="pre">'ppc'</span></code> for the classic Mac OS 8 runtime model or <code class="docutils literal notranslate"><span class="pre">'carbon'</span></code>
for the Mac OS 9 runtime model.</p>
</dd></dl>

<dl class="data">
<dt id="MacOS.linkmodel">
<code class="descclassname">MacOS.</code><code class="descname">linkmodel</code><a class="headerlink" href="#MacOS.linkmodel" title="Permalink to this definition">¶</a></dt>
<dd><p>The way the interpreter has been linked. As extension modules may be
incompatible between linking models, packages could use this information to give
more decent error messages. The value is one of <code class="docutils literal notranslate"><span class="pre">'static'</span></code> for a statically
linked Python, <code class="docutils literal notranslate"><span class="pre">'framework'</span></code> for Python in a Mac OS X framework, <code class="docutils literal notranslate"><span class="pre">'shared'</span></code>
for Python in a standard Unix shared library. Older Pythons could also have the
value <code class="docutils literal notranslate"><span class="pre">'cfm'</span></code> for Mac OS 9-compatible Python.</p>
</dd></dl>

<dl class="exception">
<dt id="MacOS.Error">
<em class="property">exception </em><code class="descclassname">MacOS.</code><code class="descname">Error</code><a class="headerlink" href="#MacOS.Error" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">This exception is raised on MacOS generated errors, either from functions in
this module or from other mac-specific modules like the toolbox interfaces. The
arguments are the integer error code (the <code class="xref c c-data docutils literal notranslate"><span class="pre">OSErr</span></code> value) and a textual
description of the error code. Symbolic names for all known error codes are
defined in the standard module <a class="reference internal" href="undoc.html#module-macerrors" title="macerrors: Constant definitions for many Mac OS error codes. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="MacOS.GetErrorString">
<code class="descclassname">MacOS.</code><code class="descname">GetErrorString</code><span class="sig-paren">(</span><em>errno</em><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.GetErrorString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the textual description of MacOS error code <em>errno</em>.</p>
</dd></dl>

<dl class="function">
<dt id="MacOS.DebugStr">
<code class="descclassname">MacOS.</code><code class="descname">DebugStr</code><span class="sig-paren">(</span><em>message</em><span class="optional">[</span>, <em>object</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.DebugStr" title="Permalink to this definition">¶</a></dt>
<dd><p>On Mac OS X the string is simply printed to stderr (on older Mac OS systems more
elaborate functionality was available), but it provides a convenient location to
attach a breakpoint in a low-level debugger like <strong class="program">gdb</strong>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Not available in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="MacOS.SysBeep">
<code class="descclassname">MacOS.</code><code class="descname">SysBeep</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.SysBeep" title="Permalink to this definition">¶</a></dt>
<dd><p>Ring the bell.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Not available in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="MacOS.GetTicks">
<code class="descclassname">MacOS.</code><code class="descname">GetTicks</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.GetTicks" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the number of clock ticks (1/60th of a second) since system boot.</p>
</dd></dl>

<dl class="function">
<dt id="MacOS.GetCreatorAndType">
<code class="descclassname">MacOS.</code><code class="descname">GetCreatorAndType</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.GetCreatorAndType" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file creator and file type as two four-character strings. The <em>file</em>
parameter can be a pathname or an <code class="docutils literal notranslate"><span class="pre">FSSpec</span></code> or  <code class="docutils literal notranslate"><span class="pre">FSRef</span></code> object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is not possible to use an <code class="docutils literal notranslate"><span class="pre">FSSpec</span></code> in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="MacOS.SetCreatorAndType">
<code class="descclassname">MacOS.</code><code class="descname">SetCreatorAndType</code><span class="sig-paren">(</span><em>file</em>, <em>creator</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.SetCreatorAndType" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file creator and file type. The <em>file</em> parameter can be a pathname or an
<code class="docutils literal notranslate"><span class="pre">FSSpec</span></code> or  <code class="docutils literal notranslate"><span class="pre">FSRef</span></code> object. <em>creator</em> and <em>type</em> must be four character
strings.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It is not possible to use an <code class="docutils literal notranslate"><span class="pre">FSSpec</span></code> in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="MacOS.openrf">
<code class="descclassname">MacOS.</code><code class="descname">openrf</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.openrf" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the resource fork of a file. Arguments are the same as for the built-in
function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>. The object returned has file-like semantics, but it is
not a Python file object, so there may be subtle differences.</p>
</dd></dl>

<dl class="function">
<dt id="MacOS.WMAvailable">
<code class="descclassname">MacOS.</code><code class="descname">WMAvailable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.WMAvailable" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks whether the current process has access to the window manager. The method
will return <code class="docutils literal notranslate"><span class="pre">False</span></code> if the window manager is not available, for instance when
running on Mac OS X Server or when logged in via ssh, or when the current
interpreter is not running from a fullblown application bundle. A script runs
from an application bundle either when it has been started with
<strong class="program">pythonw</strong> instead of <strong class="program">python</strong> or when running  as an applet.</p>
</dd></dl>

<dl class="function">
<dt id="MacOS.splash">
<code class="descclassname">MacOS.</code><code class="descname">splash</code><span class="sig-paren">(</span><span class="optional">[</span><em>resourceid</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MacOS.splash" title="Permalink to this definition">¶</a></dt>
<dd><p>Opens a splash screen by resource id. Use resourceid <code class="docutils literal notranslate"><span class="pre">0</span></code> to close
the splash screen.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Not available in 64-bit mode.</p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="ic.html"
                        title="previous chapter">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="macostools.html"
                        title="next chapter">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/macos.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="macostools.html" title="37.3. macostools — Convenience routines for file manipulation"
             >next</a> |</li>
        <li class="right" >
          <a href="ic.html" title="37.1. ic — Access to the Mac OS X Internet Config"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���*77html/library/macosa.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38. MacPython OSA Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="38.1. gensuitemodule — Generate OSA stub packages" href="gensuitemodule.html" />
    <link rel="prev" title="37.9. ColorPicker — Color selection dialog" href="colorpicker.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/macosa.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gensuitemodule.html" title="38.1. gensuitemodule — Generate OSA stub packages"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="colorpicker.html" title="37.9. ColorPicker — Color selection dialog"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="macpython-osa-modules">
<span id="mac-scripting"></span><h1>38. MacPython OSA Modules<a class="headerlink" href="#macpython-osa-modules" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes the current implementation of the Open Scripting
Architecture (OSA, also commonly referred to as AppleScript) for Python,
allowing you to control scriptable applications from your Python program,
and with a fairly pythonic interface. Development on this set of modules has
stopped.</p>
<p>For a description of the various components of AppleScript and OSA, and to get
an understanding of the architecture and terminology, you should read Apple’s
documentation. The “Applescript Language Guide” explains the conceptual model
and the terminology, and documents the standard suite. The “Open Scripting
Architecture” document explains how to use OSA from an application programmers
point of view. In the Apple Help Viewer these books are located in the Developer
Documentation, Core Technologies section.</p>
<p>As an example of scripting an application, the following piece of AppleScript
will get the name of the frontmost <strong class="program">Finder</strong> window and print it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tell</span> <span class="n">application</span> <span class="s2">&quot;Finder&quot;</span>
    <span class="n">get</span> <span class="n">name</span> <span class="n">of</span> <span class="n">window</span> <span class="mi">1</span>
<span class="n">end</span> <span class="n">tell</span>
</pre></div>
</div>
<p>In Python, the following code fragment will do the same:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Finder</span>

<span class="n">f</span> <span class="o">=</span> <span class="n">Finder</span><span class="o">.</span><span class="n">Finder</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">window</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>As distributed the Python library includes packages that implement the standard
suites, plus packages that interface to a small number of common applications.</p>
<p>To send AppleEvents to an application you must first create the Python package
interfacing to the terminology of the application (what <strong class="program">Script Editor</strong>
calls the “Dictionary”). This can be done from within the <strong class="program">PythonIDE</strong>
or by running the <code class="file docutils literal notranslate"><span class="pre">gensuitemodule.py</span></code> module as a standalone program from
the command line.</p>
<p>The generated output is a package with a number of modules, one for every suite
used in the program plus an <code class="xref py py-mod docutils literal notranslate"><span class="pre">__init__</span></code> module to glue it all together. The
Python inheritance graph follows the AppleScript inheritance graph, so if a
program’s dictionary specifies that it includes support for the Standard Suite,
but extends one or two verbs with extra arguments then the output suite will
contain a module <code class="xref py py-mod docutils literal notranslate"><span class="pre">Standard_Suite</span></code> that imports and re-exports everything
from <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites.Standard_Suite</span></code> but overrides the methods that have extra
functionality. The output of <a class="reference internal" href="gensuitemodule.html#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a> is pretty readable, and
contains the documentation that was in the original AppleScript dictionary in
Python docstrings, so reading it is a good source of documentation.</p>
<p>The output package implements a main class with the same name as the package
which contains all the AppleScript verbs as methods, with the direct object as
the first argument and all optional parameters as keyword arguments. AppleScript
classes are also implemented as Python classes, as are comparisons and all the
other thingies.</p>
<p>The main Python class implementing the verbs also allows access to the
properties and elements declared in the AppleScript class “application”. In the
current release that is as far as the object orientation goes, so in the example
above we need to use <code class="docutils literal notranslate"><span class="pre">f.get(f.window(1).name)</span></code> instead of the more Pythonic
<code class="docutils literal notranslate"><span class="pre">f.window(1).name.get()</span></code>.</p>
<p>If an AppleScript identifier is not a Python identifier the name is mangled
according to a small number of rules:</p>
<ul class="simple">
<li>spaces are replaced with underscores</li>
<li>other non-alphanumeric characters are replaced with <code class="docutils literal notranslate"><span class="pre">_xx_</span></code> where <code class="docutils literal notranslate"><span class="pre">xx</span></code> is
the hexadecimal character value</li>
<li>any Python reserved word gets an underscore appended</li>
</ul>
<p>Python also has support for creating scriptable applications in Python, but The
following modules are relevant to MacPython AppleScript support:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="gensuitemodule.html">38.1. <code class="docutils literal notranslate"><span class="pre">gensuitemodule</span></code> — Generate OSA stub packages</a></li>
<li class="toctree-l1"><a class="reference internal" href="aetools.html">38.2. <code class="docutils literal notranslate"><span class="pre">aetools</span></code> — OSA client support</a></li>
<li class="toctree-l1"><a class="reference internal" href="aepack.html">38.3. <code class="docutils literal notranslate"><span class="pre">aepack</span></code> — Conversion between Python variables and AppleEvent data containers</a></li>
<li class="toctree-l1"><a class="reference internal" href="aetypes.html">38.4. <code class="docutils literal notranslate"><span class="pre">aetypes</span></code> — AppleEvent objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="miniaeframe.html">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a><ul>
<li class="toctree-l2"><a class="reference internal" href="miniaeframe.html#aeserver-objects">38.5.1. AEServer Objects</a></li>
</ul>
</li>
</ul>
</div>
<p>In addition, support modules have been pre-generated for <code class="xref py py-mod docutils literal notranslate"><span class="pre">Finder</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Terminal</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Explorer</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">Netscape</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">CodeWarrior</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">SystemEvents</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code>.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="colorpicker.html"
                        title="previous chapter">37.9. <code class="docutils literal notranslate"><span class="pre">ColorPicker</span></code> — Color selection dialog</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gensuitemodule.html"
                        title="next chapter">38.1. <code class="docutils literal notranslate"><span class="pre">gensuitemodule</span></code> — Generate OSA stub packages</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/macosa.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gensuitemodule.html" title="38.1. gensuitemodule — Generate OSA stub packages"
             >next</a> |</li>
        <li class="right" >
          <a href="colorpicker.html" title="37.9. ColorPicker — Color selection dialog"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�/BBhtml/library/macostools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>37.3. macostools — Convenience routines for file manipulation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="37.5. EasyDialogs — Basic Macintosh dialogs" href="easydialogs.html" />
    <link rel="prev" title="37.2. MacOS — Access to Mac OS interpreter features" href="macos.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/macostools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="easydialogs.html" title="37.5. EasyDialogs — Basic Macintosh dialogs"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="macos.html" title="37.2. MacOS — Access to Mac OS interpreter features"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" accesskey="U">37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-macostools">
<span id="macostools-convenience-routines-for-file-manipulation"></span><h1>37.3. <a class="reference internal" href="#module-macostools" title="macostools: Convenience routines for file manipulation. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macostools</span></code></a> — Convenience routines for file manipulation<a class="headerlink" href="#module-macostools" title="Permalink to this headline">¶</a></h1>
<p>This module contains some convenience routines for file-manipulation on the
Macintosh. All file parameters can be specified as pathnames, <code class="xref py py-class docutils literal notranslate"><span class="pre">FSRef</span></code> or
<code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code> objects.  This module expects a filesystem which supports forked
files, so it should not be used on UFS partitions.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-macostools" title="macostools: Convenience routines for file manipulation. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macostools</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="macostools.copy">
<code class="descclassname">macostools.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="optional">[</span>, <em>createpath</em><span class="optional">[</span>, <em>copytimes</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#macostools.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy file <em>src</em> to <em>dst</em>.  If <em>createpath</em> is non-zero the folders leading to
<em>dst</em> are created if necessary. The method copies data and resource fork and
some finder information (creator, type, flags) and optionally the creation,
modification and backup times (default is to copy them). Custom icons, comments
and icon position are not copied.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function does not work in 64-bit code because it uses APIs that
are not available in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="macostools.copytree">
<code class="descclassname">macostools.</code><code class="descname">copytree</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#macostools.copytree" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively copy a file tree from <em>src</em> to <em>dst</em>, creating folders as needed.
<em>src</em> and <em>dst</em> should be specified as pathnames.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function does not work in 64-bit code because it uses APIs that
are not available in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="macostools.mkalias">
<code class="descclassname">macostools.</code><code class="descname">mkalias</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#macostools.mkalias" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a finder alias <em>dst</em> pointing to <em>src</em>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function does not work in 64-bit code because it uses APIs that
are not available in 64-bit mode.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="macostools.touched">
<code class="descclassname">macostools.</code><code class="descname">touched</code><span class="sig-paren">(</span><em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#macostools.touched" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder that some bits of finder-information such as creator or type for
file <em>dst</em> has changed. The file can be specified by pathname or fsspec. This
call should tell the finder to redraw the files icon.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The function is a no-op on OS X.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="macostools.BUFSIZ">
<code class="descclassname">macostools.</code><code class="descname">BUFSIZ</code><a class="headerlink" href="#macostools.BUFSIZ" title="Permalink to this definition">¶</a></dt>
<dd><p>The buffer size for <code class="docutils literal notranslate"><span class="pre">copy</span></code>, default 1 megabyte.</p>
</dd></dl>

<p>Note that the process of creating finder aliases is not specified in the Apple
documentation. Hence, aliases created with <a class="reference internal" href="#macostools.mkalias" title="macostools.mkalias"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkalias()</span></code></a> could conceivably
have incompatible behaviour in some cases.</p>
</div>
<div class="section" id="module-findertools">
<span id="findertools-the-finder-s-apple-events-interface"></span><h1>37.4. <a class="reference internal" href="#module-findertools" title="findertools: Wrappers around the finder's Apple Events interface. (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">findertools</span></code></a> — The <strong class="program">finder</strong>’s Apple Events interface<a class="headerlink" href="#module-findertools" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module contains routines that give Python programs access to some
functionality provided by the finder. They are implemented as wrappers around
the AppleEvent interface to the finder.</p>
<p>All file and folder parameters can be specified either as full pathnames, or as
<code class="xref py py-class docutils literal notranslate"><span class="pre">FSRef</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">FSSpec</span></code> objects.</p>
<p>The <a class="reference internal" href="#module-findertools" title="findertools: Wrappers around the finder's Apple Events interface. (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">findertools</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="findertools.launch">
<code class="descclassname">findertools.</code><code class="descname">launch</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#findertools.launch" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to launch <em>file</em>. What launching means depends on the file:
applications are started, folders are opened and documents are opened in the
correct application.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.Print">
<code class="descclassname">findertools.</code><code class="descname">Print</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#findertools.Print" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to print a file. The behaviour is identical to selecting the
file and using the print command in the finder’s file menu.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.copy">
<code class="descclassname">findertools.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>file</em>, <em>destdir</em><span class="sig-paren">)</span><a class="headerlink" href="#findertools.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to copy a file or folder <em>file</em> to folder <em>destdir</em>. The
function returns an <code class="xref py py-class docutils literal notranslate"><span class="pre">Alias</span></code> object pointing to the new file.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.move">
<code class="descclassname">findertools.</code><code class="descname">move</code><span class="sig-paren">(</span><em>file</em>, <em>destdir</em><span class="sig-paren">)</span><a class="headerlink" href="#findertools.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to move a file or folder <em>file</em> to folder <em>destdir</em>. The
function returns an <code class="xref py py-class docutils literal notranslate"><span class="pre">Alias</span></code> object pointing to the new file.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.sleep">
<code class="descclassname">findertools.</code><code class="descname">sleep</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#findertools.sleep" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to put the Macintosh to sleep, if your machine supports it.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.restart">
<code class="descclassname">findertools.</code><code class="descname">restart</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#findertools.restart" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to perform an orderly restart of the machine.</p>
</dd></dl>

<dl class="function">
<dt id="findertools.shutdown">
<code class="descclassname">findertools.</code><code class="descname">shutdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#findertools.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the finder to perform an orderly shutdown of the machine.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></li>
<li><a class="reference internal" href="#module-findertools">37.4. <code class="docutils literal notranslate"><span class="pre">findertools</span></code> — The <strong class="program">finder</strong>’s Apple Events interface</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="macos.html"
                        title="previous chapter">37.2. <code class="docutils literal notranslate"><span class="pre">MacOS</span></code> — Access to Mac OS interpreter features</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="easydialogs.html"
                        title="next chapter">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/macostools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="easydialogs.html" title="37.5. EasyDialogs — Basic Macintosh dialogs"
             >next</a> |</li>
        <li class="right" >
          <a href="macos.html" title="37.2. MacOS — Access to Mac OS interpreter features"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mac.html" >37. Mac OS X specific services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\{FQ�� � html/library/macpath.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.12. macpath — Mac OS 9 path manipulation functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11. Data Persistence" href="persistence.html" />
    <link rel="prev" title="10.11. dircache — Cached directory listings" href="dircache.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/macpath.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="persistence.html" title="11. Data Persistence"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dircache.html" title="10.11. dircache — Cached directory listings"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-macpath">
<span id="macpath-mac-os-9-path-manipulation-functions"></span><h1>10.12. <a class="reference internal" href="#module-macpath" title="macpath: Mac OS 9 path manipulation functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">macpath</span></code></a> — Mac OS 9 path manipulation functions<a class="headerlink" href="#module-macpath" title="Permalink to this headline">¶</a></h1>
<p>This module is the Mac OS 9 (and earlier) implementation of the <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>
module. It can be used to manipulate old-style Macintosh pathnames on Mac OS X
(or any other platform).</p>
<p>The following functions are available in this module: <code class="xref py py-func docutils literal notranslate"><span class="pre">normcase()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">normpath()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">isabs()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">join()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">isdir()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">isfile()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">exists()</span></code>. For other functions available in
<a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> dummy counterparts are available.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="dircache.html"
                        title="previous chapter">10.11. <code class="docutils literal notranslate"><span class="pre">dircache</span></code> — Cached directory listings</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="persistence.html"
                        title="next chapter">11. Data Persistence</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/macpath.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="persistence.html" title="11. Data Persistence"
             >next</a> |</li>
        <li class="right" >
          <a href="dircache.html" title="10.11. dircache — Cached directory listings"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�W�pq�q�html/library/mailbox.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.4. mailbox — Manipulate mailboxes in various formats &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.5. mhlib — Access to MH mailboxes" href="mhlib.html" />
    <link rel="prev" title="18.3. mailcap — Mailcap file handling" href="mailcap.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mailbox.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mhlib.html" title="18.5. mhlib — Access to MH mailboxes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mailcap.html" title="18.3. mailcap — Mailcap file handling"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mailbox">
<span id="mailbox-manipulate-mailboxes-in-various-formats"></span><h1>18.4. <a class="reference internal" href="#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> — Manipulate mailboxes in various formats<a class="headerlink" href="#module-mailbox" title="Permalink to this headline">¶</a></h1>
<p>This module defines two classes, <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> and <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>, for
accessing and manipulating on-disk mailboxes and the messages they contain.
<a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> offers a dictionary-like mapping from keys to messages.
<a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> extends the <a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a> module’s
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class with format-specific state and behavior.
Supported mailbox formats are
Maildir, mbox, MH, Babyl, and MMDF.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a></dt>
<dd>Represent and manipulate messages.</dd>
</dl>
</div>
<div class="section" id="mailbox-objects">
<span id="id1"></span><h2>18.4.1. <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> objects<a class="headerlink" href="#mailbox-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="mailbox.Mailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">Mailbox</code><a class="headerlink" href="#mailbox.Mailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>A mailbox, which may be inspected and modified.</p>
<p>The <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> class defines an interface and is not intended to be
instantiated.  Instead, format-specific subclasses should inherit from
<a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> and your code should instantiate a particular subclass.</p>
<p>The <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> interface is dictionary-like, with small keys
corresponding to messages. Keys are issued by the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance
with which they will be used and are only meaningful to that <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a>
instance. A key continues to identify a message even if the corresponding
message is modified, such as by replacing it with another message.</p>
<p>Messages may be added to a <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance using the set-like
method <a class="reference internal" href="#mailbox.Mailbox.add" title="mailbox.Mailbox.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> and removed using a <code class="docutils literal notranslate"><span class="pre">del</span></code> statement or the set-like
methods <a class="reference internal" href="#mailbox.Mailbox.remove" title="mailbox.Mailbox.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code></a> and <a class="reference internal" href="#mailbox.Mailbox.discard" title="mailbox.Mailbox.discard"><code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code></a>.</p>
<p><a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> interface semantics differ from dictionary semantics in some
noteworthy ways. Each time a message is requested, a new representation
(typically a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance) is generated based upon the current
state of the mailbox. Similarly, when a message is added to a
<a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance, the provided message representation’s contents are
copied. In neither case is a reference to the message representation kept by
the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance.</p>
<p>The default <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> iterator iterates over message representations,
not keys as the default dictionary iterator does. Moreover, modification of a
mailbox during iteration is safe and well-defined. Messages added to the
mailbox after an iterator is created will not be seen by the
iterator. Messages removed from the mailbox before the iterator yields them
will be silently skipped, though using a key from an iterator may result in a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception if the corresponding message is subsequently
removed.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Be very cautious when modifying mailboxes that might be simultaneously
changed by some other process.  The safest mailbox format to use for such
tasks is Maildir; try to avoid using single-file formats such as mbox for
concurrent writing.  If you’re modifying a mailbox, you <em>must</em> lock it by
calling the <a class="reference internal" href="#mailbox.Mailbox.lock" title="mailbox.Mailbox.lock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code></a> and <a class="reference internal" href="#mailbox.Mailbox.unlock" title="mailbox.Mailbox.unlock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unlock()</span></code></a> methods <em>before</em> reading any
messages in the file or making any changes by adding or deleting a
message.  Failing to lock the mailbox runs the risk of losing messages or
corrupting the entire mailbox.</p>
</div>
<p><a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="mailbox.Mailbox.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>message</em> to the mailbox and return the key that has been assigned to
it.</p>
<p>Parameter <em>message</em> may be a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance, an
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">email.message.Message</span></code></a> instance, a string, or a file-like object
(which should be open in text mode). If <em>message</em> is an instance of the
appropriate format-specific <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass (e.g., if it’s an
<a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance and this is an <a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a> instance), its
format-specific information is used. Otherwise, reasonable defaults for
format-specific information are used.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.remove" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.__delitem__">
<code class="descname">__delitem__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__delitem__" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.discard">
<code class="descname">discard</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.discard" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the message corresponding to <em>key</em> from the mailbox.</p>
<p>If no such message exists, a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception is raised if the
method was called as <a class="reference internal" href="#mailbox.Mailbox.remove" title="mailbox.Mailbox.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code></a> or <a class="reference internal" href="#mailbox.Mailbox.__delitem__" title="mailbox.Mailbox.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> but no
exception is raised if the method was called as <a class="reference internal" href="#mailbox.Mailbox.discard" title="mailbox.Mailbox.discard"><code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code></a>. The
behavior of <a class="reference internal" href="#mailbox.Mailbox.discard" title="mailbox.Mailbox.discard"><code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code></a> may be preferred if the underlying mailbox
format supports concurrent modification by other processes.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.__setitem__">
<code class="descname">__setitem__</code><span class="sig-paren">(</span><em>key</em>, <em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace the message corresponding to <em>key</em> with <em>message</em>. Raise a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception if no message already corresponds to <em>key</em>.</p>
<p>As with <a class="reference internal" href="#mailbox.Mailbox.add" title="mailbox.Mailbox.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a>, parameter <em>message</em> may be a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>
instance, an <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">email.message.Message</span></code></a> instance, a string, or a
file-like object (which should be open in text mode). If <em>message</em> is an
instance of the appropriate format-specific <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass
(e.g., if it’s an <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance and this is an
<a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a> instance), its format-specific information is
used. Otherwise, the format-specific information of the message that
currently corresponds to <em>key</em> is left unchanged.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.iterkeys">
<code class="descname">iterkeys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.iterkeys" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.keys">
<code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over all keys if called as <a class="reference internal" href="#mailbox.Mailbox.iterkeys" title="mailbox.Mailbox.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code></a> or return a
list of keys if called as <a class="reference internal" href="#mailbox.Mailbox.keys" title="mailbox.Mailbox.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.itervalues">
<code class="descname">itervalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.itervalues" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.__iter__">
<code class="descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__iter__" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.values">
<code class="descname">values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.values" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over representations of all messages if called as
<a class="reference internal" href="#mailbox.Mailbox.itervalues" title="mailbox.Mailbox.itervalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code></a> or <a class="reference internal" href="#mailbox.Mailbox.__iter__" title="mailbox.Mailbox.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> or return a list of such
representations if called as <a class="reference internal" href="#mailbox.Mailbox.values" title="mailbox.Mailbox.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>. The messages are represented
as instances of the appropriate format-specific <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass
unless a custom message factory was specified when the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a>
instance was initialized.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The behavior of <a class="reference internal" href="#mailbox.Mailbox.__iter__" title="mailbox.Mailbox.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> is unlike that of dictionaries, which
iterate over keys.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.iteritems">
<code class="descname">iteritems</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.iteritems" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.items">
<code class="descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over (<em>key</em>, <em>message</em>) pairs, where <em>key</em> is a key and
<em>message</em> is a message representation, if called as <a class="reference internal" href="#mailbox.Mailbox.iteritems" title="mailbox.Mailbox.iteritems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code></a> or
return a list of such pairs if called as <a class="reference internal" href="#mailbox.Mailbox.items" title="mailbox.Mailbox.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a>. The messages are
represented as instances of the appropriate format-specific
<a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass unless a custom message factory was specified
when the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance was initialized.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.get">
<code class="descname">get</code><span class="sig-paren">(</span><em>key</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.get" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.__getitem__">
<code class="descname">__getitem__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of the message corresponding to <em>key</em>. If no such
message exists, <em>default</em> is returned if the method was called as
<a class="reference internal" href="#mailbox.Mailbox.get" title="mailbox.Mailbox.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> and a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception is raised if the method was
called as <a class="reference internal" href="#mailbox.Mailbox.__getitem__" title="mailbox.Mailbox.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. The message is represented as an instance
of the appropriate format-specific <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass unless a
custom message factory was specified when the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance
was initialized.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.get_message">
<code class="descname">get_message</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.get_message" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of the message corresponding to <em>key</em> as an
instance of the appropriate format-specific <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass, or
raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception if no such message exists.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.get_string">
<code class="descname">get_string</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.get_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representation of the message corresponding to <em>key</em>, or
raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception if no such message exists.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a file-like representation of the message corresponding to <em>key</em>,
or raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception if no such message exists. The
file-like object behaves as if open in binary mode. This file should be
closed once it is no longer needed.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike other representations of messages, file-like representations are
not necessarily independent of the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance that
created them or of the underlying mailbox. More specific documentation
is provided by each subclass.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.has_key">
<code class="descname">has_key</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.has_key" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Mailbox.__contains__">
<code class="descname">__contains__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>key</em> corresponds to a message, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.__len__">
<code class="descname">__len__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a count of messages in the mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all messages from the mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of the message corresponding to <em>key</em> and delete
the message. If no such message exists, return <em>default</em> if it was
supplied or else raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception. The message is
represented as an instance of the appropriate format-specific
<a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass unless a custom message factory was specified
when the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance was initialized.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.popitem">
<code class="descname">popitem</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an arbitrary (<em>key</em>, <em>message</em>) pair, where <em>key</em> is a key and
<em>message</em> is a message representation, and delete the corresponding
message. If the mailbox is empty, raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception. The
message is represented as an instance of the appropriate format-specific
<a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> subclass unless a custom message factory was specified
when the <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance was initialized.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.update">
<code class="descname">update</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Parameter <em>arg</em> should be a <em>key</em>-to-<em>message</em> mapping or an iterable of
(<em>key</em>, <em>message</em>) pairs. Updates the mailbox so that, for each given
<em>key</em> and <em>message</em>, the message corresponding to <em>key</em> is set to
<em>message</em> as if by using <a class="reference internal" href="#mailbox.Mailbox.__setitem__" title="mailbox.Mailbox.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>. As with <a class="reference internal" href="#mailbox.Mailbox.__setitem__" title="mailbox.Mailbox.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
each <em>key</em> must already correspond to a message in the mailbox or else a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception will be raised, so in general it is incorrect
for <em>arg</em> to be a <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike with dictionaries, keyword arguments are not supported.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Write any pending changes to the filesystem. For some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a>
subclasses, changes are always written immediately and <a class="reference internal" href="#mailbox.Mailbox.flush" title="mailbox.Mailbox.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> does
nothing, but you should still make a habit of calling this method.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire an exclusive advisory lock on the mailbox so that other processes
know not to modify it. An <a class="reference internal" href="#mailbox.ExternalClashError" title="mailbox.ExternalClashError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExternalClashError</span></code></a> is raised if the lock
is not available. The particular locking mechanisms used depend upon the
mailbox format.  You should <em>always</em> lock the mailbox before making any
modifications to its contents.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the lock on the mailbox, if any.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Mailbox.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Mailbox.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush the mailbox, unlock it if necessary, and close any open files. For
some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> subclasses, this method does nothing.</p>
</dd></dl>

</dd></dl>

<div class="section" id="maildir">
<span id="mailbox-maildir"></span><h3>18.4.1.1. <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a><a class="headerlink" href="#maildir" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.Maildir">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">Maildir</code><span class="sig-paren">(</span><em>dirname</em>, <em>factory=rfc822.Message</em>, <em>create=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> for mailboxes in Maildir format. Parameter
<em>factory</em> is a callable object that accepts a file-like message representation
(which behaves as if opened in binary mode) and returns a custom representation.
If <em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> is used as the default message
representation. If <em>create</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the mailbox is created if it does not
exist.</p>
<p>It is for historical reasons that <em>factory</em> defaults to <a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a>
and that <em>dirname</em> is named as such rather than <em>path</em>. For a <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a>
instance that behaves like instances of other <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> subclasses, set
<em>factory</em> to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Maildir is a directory-based mailbox format invented for the qmail mail
transfer agent and now widely supported by other programs. Messages in a
Maildir mailbox are stored in separate files within a common directory
structure. This design allows Maildir mailboxes to be accessed and modified
by multiple unrelated programs without data corruption, so file locking is
unnecessary.</p>
<p>Maildir mailboxes contain three subdirectories, namely: <code class="file docutils literal notranslate"><span class="pre">tmp</span></code>,
<code class="file docutils literal notranslate"><span class="pre">new</span></code>, and <code class="file docutils literal notranslate"><span class="pre">cur</span></code>. Messages are created momentarily in the
<code class="file docutils literal notranslate"><span class="pre">tmp</span></code> subdirectory and then moved to the <code class="file docutils literal notranslate"><span class="pre">new</span></code> subdirectory to
finalize delivery. A mail user agent may subsequently move the message to the
<code class="file docutils literal notranslate"><span class="pre">cur</span></code> subdirectory and store information about the state of the message
in a special “info” section appended to its file name.</p>
<p>Folders of the style introduced by the Courier mail transfer agent are also
supported. Any subdirectory of the main mailbox is considered a folder if
<code class="docutils literal notranslate"><span class="pre">'.'</span></code> is the first character in its name. Folder names are represented by
<a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> without the leading <code class="docutils literal notranslate"><span class="pre">'.'</span></code>. Each folder is itself a Maildir
mailbox but should not contain other folders. Instead, a logical nesting is
indicated using <code class="docutils literal notranslate"><span class="pre">'.'</span></code> to delimit levels, e.g., “Archived.2005.07”.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The Maildir specification requires the use of a colon (<code class="docutils literal notranslate"><span class="pre">':'</span></code>) in certain
message file names. However, some operating systems do not permit this
character in file names, If you wish to use a Maildir-like format on such
an operating system, you should specify another character to use
instead. The exclamation point (<code class="docutils literal notranslate"><span class="pre">'!'</span></code>) is a popular choice. For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>
<span class="n">mailbox</span><span class="o">.</span><span class="n">Maildir</span><span class="o">.</span><span class="n">colon</span> <span class="o">=</span> <span class="s1">&#39;!&#39;</span>
</pre></div>
</div>
<p class="last">The <code class="xref py py-attr docutils literal notranslate"><span class="pre">colon</span></code> attribute may also be set on a per-instance basis.</p>
</div>
<p><a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> instances have all of the methods of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> in
addition to the following:</p>
<dl class="method">
<dt id="mailbox.Maildir.list_folders">
<code class="descname">list_folders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.list_folders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the names of all folders.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.get_folder">
<code class="descname">get_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.get_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> instance representing the folder whose name is
<em>folder</em>. A <a class="reference internal" href="#mailbox.NoSuchMailboxError" title="mailbox.NoSuchMailboxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSuchMailboxError</span></code></a> exception is raised if the folder
does not exist.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.add_folder">
<code class="descname">add_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.add_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a folder whose name is <em>folder</em> and return a <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a>
instance representing it.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.remove_folder">
<code class="descname">remove_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.remove_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the folder whose name is <em>folder</em>. If the folder contains any
messages, a <a class="reference internal" href="#mailbox.NotEmptyError" title="mailbox.NotEmptyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotEmptyError</span></code></a> exception will be raised and the folder
will not be deleted.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.clean">
<code class="descname">clean</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.clean" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete temporary files from the mailbox that have not been accessed in the
last 36 hours. The Maildir specification says that mail-reading programs
should do this occasionally.</p>
</dd></dl>

<p>Some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> methods implemented by <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> deserve special
remarks:</p>
<dl class="method">
<dt id="mailbox.Maildir.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.add" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Maildir.__setitem__">
<code class="descname">__setitem__</code><span class="sig-paren">(</span><em>key</em>, <em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.__setitem__" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Maildir.update">
<code class="descname">update</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.update" title="Permalink to this definition">¶</a></dt>
<dd><div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">These methods generate unique file names based upon the current process
ID. When using multiple threads, undetected name clashes may occur and
cause corruption of the mailbox unless threads are coordinated to avoid
using these methods to manipulate the same mailbox simultaneously.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>All changes to Maildir mailboxes are immediately applied, so this method
does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.lock" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Maildir.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Maildir mailboxes do not support (or require) locking, so these methods do
nothing.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.close" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> instances do not keep any open files and the underlying
mailboxes do not support locking, so this method does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Maildir.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Maildir.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Depending upon the host platform, it may not be possible to modify or
remove the underlying message while the returned file remains open.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.qmail.org/man/man5/maildir.html">maildir man page from qmail</a></dt>
<dd>The original specification of the format.</dd>
<dt><a class="reference external" href="https://cr.yp.to/proto/maildir.html">Using maildir format</a></dt>
<dd>Notes on Maildir by its inventor. Includes an updated name-creation scheme and
details on “info” semantics.</dd>
<dt><a class="reference external" href="http://www.courier-mta.org/maildir.html">maildir man page from Courier</a></dt>
<dd>Another specification of the format. Describes a common extension for supporting
folders.</dd>
</dl>
</div>
</div>
<div class="section" id="mbox">
<span id="mailbox-mbox"></span><h3>18.4.1.2. <a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a><a class="headerlink" href="#mbox" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.mbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">mbox</code><span class="sig-paren">(</span><em>path</em>, <em>factory=None</em>, <em>create=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mbox" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> for mailboxes in mbox format. Parameter <em>factory</em>
is a callable object that accepts a file-like message representation (which
behaves as if opened in binary mode) and returns a custom representation. If
<em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> is used as the default message
representation. If <em>create</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the mailbox is created if it does not
exist.</p>
<p>The mbox format is the classic format for storing mail on Unix systems. All
messages in an mbox mailbox are stored in a single file with the beginning of
each message indicated by a line whose first five characters are “From “.</p>
<p>Several variations of the mbox format exist to address perceived shortcomings in
the original. In the interest of compatibility, <a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a> implements the
original format, which is sometimes referred to as <em class="dfn">mboxo</em>. This means that
the <em class="mailheader">Content-Length</em> header, if present, is ignored and that any
occurrences of “From ” at the beginning of a line in a message body are
transformed to “&gt;From ” when storing the message, although occurrences of “&gt;From
” are not transformed to “From ” when reading the message.</p>
<p>Some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> methods implemented by <a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a> deserve special
remarks:</p>
<dl class="method">
<dt id="mailbox.mbox.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mbox.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Using the file after calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> on the
<a class="reference internal" href="#mailbox.mbox" title="mailbox.mbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code></a> instance may yield unpredictable results or raise an
exception.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mbox.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mbox.lock" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.mbox.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mbox.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Three locking mechanisms are used—dot locking and, if available, the
<code class="xref c c-func docutils literal notranslate"><span class="pre">flock()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">lockf()</span></code> system calls.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.qmail.org/man/man5/mbox.html">mbox man page from qmail</a></dt>
<dd>A specification of the format and its variations.</dd>
<dt><a class="reference external" href="http://www.tin.org/bin/man.cgi?section=5&amp;topic=mbox">mbox man page from tin</a></dt>
<dd>Another specification of the format, with details on locking.</dd>
<dt><a class="reference external" href="https://www.jwz.org/doc/content-length.html">Configuring Netscape Mail on Unix: Why The Content-Length Format is Bad</a></dt>
<dd>An argument for using the original mbox format rather than a variation.</dd>
<dt><a class="reference external" href="https://www.loc.gov/preservation/digital/formats/fdd/fdd000383.shtml">“mbox” is a family of several mutually incompatible mailbox formats</a></dt>
<dd>A history of mbox variations.</dd>
</dl>
</div>
</div>
<div class="section" id="mh">
<span id="mailbox-mh"></span><h3>18.4.1.3. <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a><a class="headerlink" href="#mh" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.MH">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MH</code><span class="sig-paren">(</span><em>path</em>, <em>factory=None</em>, <em>create=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> for mailboxes in MH format. Parameter <em>factory</em>
is a callable object that accepts a file-like message representation (which
behaves as if opened in binary mode) and returns a custom representation. If
<em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> is used as the default message
representation. If <em>create</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the mailbox is created if it does not
exist.</p>
<p>MH is a directory-based mailbox format invented for the MH Message Handling
System, a mail user agent. Each message in an MH mailbox resides in its own
file. An MH mailbox may contain other MH mailboxes (called <em class="dfn">folders</em>) in
addition to messages. Folders may be nested indefinitely. MH mailboxes also
support <em class="dfn">sequences</em>, which are named lists used to logically group
messages without moving them to sub-folders. Sequences are defined in a file
called <code class="file docutils literal notranslate"><span class="pre">.mh_sequences</span></code> in each folder.</p>
<p>The <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> class manipulates MH mailboxes, but it does not attempt to
emulate all of <strong class="program">mh</strong>’s behaviors. In particular, it does not modify
and is not affected by the <code class="file docutils literal notranslate"><span class="pre">context</span></code> or <code class="file docutils literal notranslate"><span class="pre">.mh_profile</span></code> files that
are used by <strong class="program">mh</strong> to store its state and configuration.</p>
<p><a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> instances have all of the methods of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> in addition
to the following:</p>
<dl class="method">
<dt id="mailbox.MH.list_folders">
<code class="descname">list_folders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.list_folders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the names of all folders.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.get_folder">
<code class="descname">get_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.get_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> instance representing the folder whose name is
<em>folder</em>. A <a class="reference internal" href="#mailbox.NoSuchMailboxError" title="mailbox.NoSuchMailboxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoSuchMailboxError</span></code></a> exception is raised if the folder
does not exist.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.add_folder">
<code class="descname">add_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.add_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a folder whose name is <em>folder</em> and return an <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> instance
representing it.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.remove_folder">
<code class="descname">remove_folder</code><span class="sig-paren">(</span><em>folder</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.remove_folder" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the folder whose name is <em>folder</em>. If the folder contains any
messages, a <a class="reference internal" href="#mailbox.NotEmptyError" title="mailbox.NotEmptyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotEmptyError</span></code></a> exception will be raised and the folder
will not be deleted.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.get_sequences">
<code class="descname">get_sequences</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.get_sequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary of sequence names mapped to key lists. If there are no
sequences, the empty dictionary is returned.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.set_sequences">
<code class="descname">set_sequences</code><span class="sig-paren">(</span><em>sequences</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.set_sequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Re-define the sequences that exist in the mailbox based upon <em>sequences</em>,
a dictionary of names mapped to key lists, like returned by
<a class="reference internal" href="#mailbox.MH.get_sequences" title="mailbox.MH.get_sequences"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_sequences()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.pack">
<code class="descname">pack</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.pack" title="Permalink to this definition">¶</a></dt>
<dd><p>Rename messages in the mailbox as necessary to eliminate gaps in
numbering.  Entries in the sequences list are updated correspondingly.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Already-issued keys are invalidated by this operation and should not be
subsequently used.</p>
</div>
</dd></dl>

<p>Some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> methods implemented by <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> deserve special
remarks:</p>
<dl class="method">
<dt id="mailbox.MH.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.remove" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.MH.__delitem__">
<code class="descname">__delitem__</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.__delitem__" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.MH.discard">
<code class="descname">discard</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.discard" title="Permalink to this definition">¶</a></dt>
<dd><p>These methods immediately delete the message. The MH convention of marking
a message for deletion by prepending a comma to its name is not used.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.lock" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.MH.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Three locking mechanisms are used—dot locking and, if available, the
<code class="xref c c-func docutils literal notranslate"><span class="pre">flock()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">lockf()</span></code> system calls. For MH mailboxes, locking
the mailbox means locking the <code class="file docutils literal notranslate"><span class="pre">.mh_sequences</span></code> file and, only for the
duration of any operations that affect them, locking individual message
files.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Depending upon the host platform, it may not be possible to remove the
underlying message while the returned file remains open.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>All changes to MH mailboxes are immediately applied, so this method does
nothing.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MH.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MH.close" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> instances do not keep any open files, so this method is
equivalent to <a class="reference internal" href="#mailbox.MH.unlock" title="mailbox.MH.unlock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unlock()</span></code></a>.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.nongnu.org/nmh/">nmh - Message Handling System</a></dt>
<dd>Home page of <strong class="program">nmh</strong>, an updated version of the original <strong class="program">mh</strong>.</dd>
<dt><a class="reference external" href="http://rand-mh.sourceforge.net/book/">MH &amp; nmh: Email for Users &amp; Programmers</a></dt>
<dd>A GPL-licensed book on <strong class="program">mh</strong> and <strong class="program">nmh</strong>, with some information
on the mailbox format.</dd>
</dl>
</div>
</div>
<div class="section" id="babyl">
<span id="mailbox-babyl"></span><h3>18.4.1.4. <a class="reference internal" href="#mailbox.Babyl" title="mailbox.Babyl"><code class="xref py py-class docutils literal notranslate"><span class="pre">Babyl</span></code></a><a class="headerlink" href="#babyl" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.Babyl">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">Babyl</code><span class="sig-paren">(</span><em>path</em>, <em>factory=None</em>, <em>create=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Babyl" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> for mailboxes in Babyl format. Parameter
<em>factory</em> is a callable object that accepts a file-like message representation
(which behaves as if opened in binary mode) and returns a custom representation.
If <em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> is used as the default message
representation. If <em>create</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the mailbox is created if it does not
exist.</p>
<p>Babyl is a single-file mailbox format used by the Rmail mail user agent
included with Emacs. The beginning of a message is indicated by a line
containing the two characters Control-Underscore (<code class="docutils literal notranslate"><span class="pre">'\037'</span></code>) and Control-L
(<code class="docutils literal notranslate"><span class="pre">'\014'</span></code>). The end of a message is indicated by the start of the next
message or, in the case of the last message, a line containing a
Control-Underscore (<code class="docutils literal notranslate"><span class="pre">'\037'</span></code>) character.</p>
<p>Messages in a Babyl mailbox have two sets of headers, original headers and
so-called visible headers. Visible headers are typically a subset of the
original headers that have been reformatted or abridged to be more
attractive. Each message in a Babyl mailbox also has an accompanying list of
<em class="dfn">labels</em>, or short strings that record extra information about the
message, and a list of all user-defined labels found in the mailbox is kept
in the Babyl options section.</p>
<p><a class="reference internal" href="#mailbox.Babyl" title="mailbox.Babyl"><code class="xref py py-class docutils literal notranslate"><span class="pre">Babyl</span></code></a> instances have all of the methods of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> in
addition to the following:</p>
<dl class="method">
<dt id="mailbox.Babyl.get_labels">
<code class="descname">get_labels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Babyl.get_labels" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the names of all user-defined labels used in the mailbox.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The actual messages are inspected to determine which labels exist in
the mailbox rather than consulting the list of labels in the Babyl
options section, but the Babyl section is updated whenever the mailbox
is modified.</p>
</div>
</dd></dl>

<p>Some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> methods implemented by <a class="reference internal" href="#mailbox.Babyl" title="mailbox.Babyl"><code class="xref py py-class docutils literal notranslate"><span class="pre">Babyl</span></code></a> deserve special
remarks:</p>
<dl class="method">
<dt id="mailbox.Babyl.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Babyl.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>In Babyl mailboxes, the headers of a message are not stored contiguously
with the body of the message. To generate a file-like representation, the
headers and body are copied together into a <a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> instance
(from the <a class="reference internal" href="stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module), which has an API identical to that of a
file. As a result, the file-like object is truly independent of the
underlying mailbox but does not save memory compared to a string
representation.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.Babyl.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Babyl.lock" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.Babyl.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Babyl.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Three locking mechanisms are used—dot locking and, if available, the
<code class="xref c c-func docutils literal notranslate"><span class="pre">flock()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">lockf()</span></code> system calls.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://quimby.gnus.org/notes/BABYL">Format of Version 5 Babyl Files</a></dt>
<dd>A specification of the Babyl format.</dd>
<dt><a class="reference external" href="https://www.gnu.org/software/emacs/manual/html_node/emacs/Rmail.html">Reading Mail with Rmail</a></dt>
<dd>The Rmail manual, with some information on Babyl semantics.</dd>
</dl>
</div>
</div>
<div class="section" id="mmdf">
<span id="mailbox-mmdf"></span><h3>18.4.1.5. <a class="reference internal" href="#mailbox.MMDF" title="mailbox.MMDF"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDF</span></code></a><a class="headerlink" href="#mmdf" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.MMDF">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MMDF</code><span class="sig-paren">(</span><em>path</em>, <em>factory=None</em>, <em>create=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDF" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> for mailboxes in MMDF format. Parameter <em>factory</em>
is a callable object that accepts a file-like message representation (which
behaves as if opened in binary mode) and returns a custom representation. If
<em>factory</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> is used as the default message
representation. If <em>create</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the mailbox is created if it does not
exist.</p>
<p>MMDF is a single-file mailbox format invented for the Multichannel Memorandum
Distribution Facility, a mail transfer agent. Each message is in the same
form as an mbox message but is bracketed before and after by lines containing
four Control-A (<code class="docutils literal notranslate"><span class="pre">'\001'</span></code>) characters. As with the mbox format, the
beginning of each message is indicated by a line whose first five characters
are “From “, but additional occurrences of “From ” are not transformed to
“&gt;From ” when storing messages because the extra message separator lines
prevent mistaking such occurrences for the starts of subsequent messages.</p>
<p>Some <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> methods implemented by <a class="reference internal" href="#mailbox.MMDF" title="mailbox.MMDF"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDF</span></code></a> deserve special
remarks:</p>
<dl class="method">
<dt id="mailbox.MMDF.get_file">
<code class="descname">get_file</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDF.get_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Using the file after calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> on the
<a class="reference internal" href="#mailbox.MMDF" title="mailbox.MMDF"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDF</span></code></a> instance may yield unpredictable results or raise an
exception.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDF.lock">
<code class="descname">lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDF.lock" title="Permalink to this definition">¶</a></dt>
<dt id="mailbox.MMDF.unlock">
<code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDF.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Three locking mechanisms are used—dot locking and, if available, the
<code class="xref c c-func docutils literal notranslate"><span class="pre">flock()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">lockf()</span></code> system calls.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.tin.org/bin/man.cgi?section=5&amp;topic=mmdf">mmdf man page from tin</a></dt>
<dd>A specification of MMDF format from the documentation of tin, a newsreader.</dd>
<dt><a class="reference external" href="https://en.wikipedia.org/wiki/MMDF">MMDF</a></dt>
<dd>A Wikipedia article describing the Multichannel Memorandum Distribution
Facility.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="message-objects">
<span id="mailbox-message-objects"></span><h2>18.4.2. <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects<a class="headerlink" href="#message-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="mailbox.Message">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">Message</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.Message" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of the <a class="reference internal" href="email.message.html#module-email.message" title="email.message: The base class representing email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email.message</span></code></a> module’s
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>. Subclasses of <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mailbox.Message</span></code></a> add
mailbox-format-specific state and behavior.</p>
<p>If <em>message</em> is omitted, the new instance is created in a default, empty state.
If <em>message</em> is an <a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">email.message.Message</span></code></a> instance, its contents are
copied; furthermore, any format-specific information is converted insofar as
possible if <em>message</em> is a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance. If <em>message</em> is a string
or a file, it should contain an <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-compliant message, which is read
and parsed.</p>
<p>The format-specific state and behaviors offered by subclasses vary, but in
general it is only the properties that are not specific to a particular
mailbox that are supported (although presumably the properties are specific
to a particular mailbox format). For example, file offsets for single-file
mailbox formats and file names for directory-based mailbox formats are not
retained, because they are only applicable to the original mailbox. But state
such as whether a message has been read by the user or marked as important is
retained, because it applies to the message itself.</p>
<p>There is no requirement that <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances be used to represent
messages retrieved using <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instances. In some situations, the
time and memory required to generate <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> representations might
not be acceptable. For such situations, <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instances also
offer string and file-like representations, and a custom message factory may
be specified when a <a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> instance is initialized.</p>
</dd></dl>

<div class="section" id="maildirmessage">
<span id="mailbox-maildirmessage"></span><h3>18.4.2.1. <a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a><a class="headerlink" href="#maildirmessage" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.MaildirMessage">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MaildirMessage</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>A message with Maildir-specific behaviors. Parameter <em>message</em> has the same
meaning as with the <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructor.</p>
<p>Typically, a mail user agent application moves all of the messages in the
<code class="file docutils literal notranslate"><span class="pre">new</span></code> subdirectory to the <code class="file docutils literal notranslate"><span class="pre">cur</span></code> subdirectory after the first time
the user opens and closes the mailbox, recording that the messages are old
whether or not they’ve actually been read. Each message in <code class="file docutils literal notranslate"><span class="pre">cur</span></code> has an
“info” section added to its file name to store information about its state.
(Some mail readers may also add an “info” section to messages in
<code class="file docutils literal notranslate"><span class="pre">new</span></code>.)  The “info” section may take one of two forms: it may contain
“2,” followed by a list of standardized flags (e.g., “2,FR”) or it may
contain “1,” followed by so-called experimental information. Standard flags
for Maildir messages are as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="19%" />
<col width="68%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>D</td>
<td>Draft</td>
<td>Under composition</td>
</tr>
<tr class="row-odd"><td>F</td>
<td>Flagged</td>
<td>Marked as important</td>
</tr>
<tr class="row-even"><td>P</td>
<td>Passed</td>
<td>Forwarded, resent, or bounced</td>
</tr>
<tr class="row-odd"><td>R</td>
<td>Replied</td>
<td>Replied to</td>
</tr>
<tr class="row-even"><td>S</td>
<td>Seen</td>
<td>Read</td>
</tr>
<tr class="row-odd"><td>T</td>
<td>Trashed</td>
<td>Marked for subsequent deletion</td>
</tr>
</tbody>
</table>
<p><a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instances offer the following methods:</p>
<dl class="method">
<dt id="mailbox.MaildirMessage.get_subdir">
<code class="descname">get_subdir</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.get_subdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return either “new” (if the message should be stored in the <code class="file docutils literal notranslate"><span class="pre">new</span></code>
subdirectory) or “cur” (if the message should be stored in the <code class="file docutils literal notranslate"><span class="pre">cur</span></code>
subdirectory).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">A message is typically moved from <code class="file docutils literal notranslate"><span class="pre">new</span></code> to <code class="file docutils literal notranslate"><span class="pre">cur</span></code> after its
mailbox has been accessed, whether or not the message is has been
read. A message <code class="docutils literal notranslate"><span class="pre">msg</span></code> has been read if <code class="docutils literal notranslate"><span class="pre">&quot;S&quot;</span> <span class="pre">in</span> <span class="pre">msg.get_flags()</span></code> is
<code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.set_subdir">
<code class="descname">set_subdir</code><span class="sig-paren">(</span><em>subdir</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.set_subdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the subdirectory the message should be stored in. Parameter <em>subdir</em>
must be either “new” or “cur”.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.get_flags">
<code class="descname">get_flags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.get_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string specifying the flags that are currently set. If the
message complies with the standard Maildir format, the result is the
concatenation in alphabetical order of zero or one occurrence of each of
<code class="docutils literal notranslate"><span class="pre">'D'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, <code class="docutils literal notranslate"><span class="pre">'P'</span></code>, <code class="docutils literal notranslate"><span class="pre">'R'</span></code>, <code class="docutils literal notranslate"><span class="pre">'S'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'T'</span></code>. The empty string
is returned if no flags are set or if “info” contains experimental
semantics.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.set_flags">
<code class="descname">set_flags</code><span class="sig-paren">(</span><em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.set_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags specified by <em>flags</em> and unset all others.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.add_flag">
<code class="descname">add_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.add_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flag(s) specified by <em>flag</em> without changing other flags. To add
more than one flag at a time, <em>flag</em> may be a string of more than one
character. The current “info” is overwritten whether or not it contains
experimental information rather than flags.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.remove_flag">
<code class="descname">remove_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.remove_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Unset the flag(s) specified by <em>flag</em> without changing other flags. To
remove more than one flag at a time, <em>flag</em> maybe a string of more than
one character.  If “info” contains experimental information rather than
flags, the current “info” is not modified.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.get_date">
<code class="descname">get_date</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.get_date" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the delivery date of the message as a floating-point number
representing seconds since the epoch.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.set_date">
<code class="descname">set_date</code><span class="sig-paren">(</span><em>date</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.set_date" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the delivery date of the message to <em>date</em>, a floating-point number
representing seconds since the epoch.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.get_info">
<code class="descname">get_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.get_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing the “info” for a message. This is useful for
accessing and modifying “info” that is experimental (i.e., not a list of
flags).</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MaildirMessage.set_info">
<code class="descname">set_info</code><span class="sig-paren">(</span><em>info</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MaildirMessage.set_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Set “info” to <em>info</em>, which should be a string.</p>
</dd></dl>

</dd></dl>

<p>When a <a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance, the <em class="mailheader">Status</em>
and <em class="mailheader">X-Status</em> headers are omitted and the following conversions
take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a>
state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“cur” subdirectory</td>
<td>O flag</td>
</tr>
<tr class="row-odd"><td>F flag</td>
<td>F flag</td>
</tr>
<tr class="row-even"><td>R flag</td>
<td>A flag</td>
</tr>
<tr class="row-odd"><td>S flag</td>
<td>R flag</td>
</tr>
<tr class="row-even"><td>T flag</td>
<td>D flag</td>
</tr>
</tbody>
</table>
<p>When a <a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“cur” subdirectory</td>
<td>“unseen” sequence</td>
</tr>
<tr class="row-odd"><td>“cur” subdirectory and S flag</td>
<td>no “unseen” sequence</td>
</tr>
<tr class="row-even"><td>F flag</td>
<td>“flagged” sequence</td>
</tr>
<tr class="row-odd"><td>R flag</td>
<td>“replied” sequence</td>
</tr>
</tbody>
</table>
<p>When a <a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“cur” subdirectory</td>
<td>“unseen” label</td>
</tr>
<tr class="row-odd"><td>“cur” subdirectory and S flag</td>
<td>no “unseen” label</td>
</tr>
<tr class="row-even"><td>P flag</td>
<td>“forwarded” or “resent” label</td>
</tr>
<tr class="row-odd"><td>R flag</td>
<td>“answered” label</td>
</tr>
<tr class="row-even"><td>T flag</td>
<td>“deleted” label</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="mboxmessage">
<span id="mailbox-mboxmessage"></span><h3>18.4.2.2. <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a><a class="headerlink" href="#mboxmessage" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.mboxMessage">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">mboxMessage</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>A message with mbox-specific behaviors. Parameter <em>message</em> has the same meaning
as with the <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructor.</p>
<p>Messages in an mbox mailbox are stored together in a single file. The
sender’s envelope address and the time of delivery are typically stored in a
line beginning with “From ” that is used to indicate the start of a message,
though there is considerable variation in the exact format of this data among
mbox implementations. Flags that indicate the state of the message, such as
whether it has been read or marked as important, are typically stored in
<em class="mailheader">Status</em> and <em class="mailheader">X-Status</em> headers.</p>
<p>Conventional flags for mbox messages are as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="21%" />
<col width="67%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R</td>
<td>Read</td>
<td>Read</td>
</tr>
<tr class="row-odd"><td>O</td>
<td>Old</td>
<td>Previously detected by MUA</td>
</tr>
<tr class="row-even"><td>D</td>
<td>Deleted</td>
<td>Marked for subsequent deletion</td>
</tr>
<tr class="row-odd"><td>F</td>
<td>Flagged</td>
<td>Marked as important</td>
</tr>
<tr class="row-even"><td>A</td>
<td>Answered</td>
<td>Replied to</td>
</tr>
</tbody>
</table>
<p>The “R” and “O” flags are stored in the <em class="mailheader">Status</em> header, and the
“D”, “F”, and “A” flags are stored in the <em class="mailheader">X-Status</em> header. The
flags and headers typically appear in the order mentioned.</p>
<p><a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instances offer the following methods:</p>
<dl class="method">
<dt id="mailbox.mboxMessage.get_from">
<code class="descname">get_from</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.get_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the “From ” line that marks the start of the
message in an mbox mailbox. The leading “From ” and the trailing newline
are excluded.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mboxMessage.set_from">
<code class="descname">set_from</code><span class="sig-paren">(</span><em>from_</em>, <em>time_=None</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.set_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the “From ” line to <em>from_</em>, which should be specified without a
leading “From ” or trailing newline. For convenience, <em>time_</em> may be
specified and will be formatted appropriately and appended to <em>from_</em>. If
<em>time_</em> is specified, it should be a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> instance, a
tuple suitable for passing to <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>, or <code class="docutils literal notranslate"><span class="pre">True</span></code> (to use
<a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mboxMessage.get_flags">
<code class="descname">get_flags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.get_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string specifying the flags that are currently set. If the
message complies with the conventional format, the result is the
concatenation in the following order of zero or one occurrence of each of
<code class="docutils literal notranslate"><span class="pre">'R'</span></code>, <code class="docutils literal notranslate"><span class="pre">'O'</span></code>, <code class="docutils literal notranslate"><span class="pre">'D'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'A'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mboxMessage.set_flags">
<code class="descname">set_flags</code><span class="sig-paren">(</span><em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.set_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags specified by <em>flags</em> and unset all others. Parameter <em>flags</em>
should be the concatenation in any order of zero or more occurrences of
each of <code class="docutils literal notranslate"><span class="pre">'R'</span></code>, <code class="docutils literal notranslate"><span class="pre">'O'</span></code>, <code class="docutils literal notranslate"><span class="pre">'D'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'A'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mboxMessage.add_flag">
<code class="descname">add_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.add_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flag(s) specified by <em>flag</em> without changing other flags. To add
more than one flag at a time, <em>flag</em> may be a string of more than one
character.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.mboxMessage.remove_flag">
<code class="descname">remove_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.mboxMessage.remove_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Unset the flag(s) specified by <em>flag</em> without changing other flags. To
remove more than one flag at a time, <em>flag</em> maybe a string of more than
one character.</p>
</dd></dl>

</dd></dl>

<p>When an <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance, a “From ” line is generated based upon the
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance’s delivery date, and the following conversions
take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag</td>
<td>S flag</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“cur” subdirectory</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>T flag</td>
</tr>
<tr class="row-odd"><td>F flag</td>
<td>F flag</td>
</tr>
<tr class="row-even"><td>A flag</td>
<td>R flag</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag and O flag</td>
<td>no “unseen” sequence</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“unseen” sequence</td>
</tr>
<tr class="row-even"><td>F flag</td>
<td>“flagged” sequence</td>
</tr>
<tr class="row-odd"><td>A flag</td>
<td>“replied” sequence</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag and O flag</td>
<td>no “unseen” label</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“unseen” label</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>“deleted” label</td>
</tr>
<tr class="row-odd"><td>A flag</td>
<td>“answered” label</td>
</tr>
</tbody>
</table>
<p>When a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance is created based upon an <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a>
instance, the “From ” line is copied and all flags directly correspond:</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="62%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag</td>
<td>R flag</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>O flag</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>D flag</td>
</tr>
<tr class="row-odd"><td>F flag</td>
<td>F flag</td>
</tr>
<tr class="row-even"><td>A flag</td>
<td>A flag</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="mhmessage">
<span id="mailbox-mhmessage"></span><h3>18.4.2.3. <a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a><a class="headerlink" href="#mhmessage" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.MHMessage">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MHMessage</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>A message with MH-specific behaviors. Parameter <em>message</em> has the same meaning
as with the <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructor.</p>
<p>MH messages do not support marks or flags in the traditional sense, but they
do support sequences, which are logical groupings of arbitrary messages. Some
mail reading programs (although not the standard <strong class="program">mh</strong> and
<strong class="program">nmh</strong>) use sequences in much the same way flags are used with other
formats, as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="19%" />
<col width="81%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Sequence</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>unseen</td>
<td>Not read, but previously detected by MUA</td>
</tr>
<tr class="row-odd"><td>replied</td>
<td>Replied to</td>
</tr>
<tr class="row-even"><td>flagged</td>
<td>Marked as important</td>
</tr>
</tbody>
</table>
<p><a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instances offer the following methods:</p>
<dl class="method">
<dt id="mailbox.MHMessage.get_sequences">
<code class="descname">get_sequences</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMessage.get_sequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the names of sequences that include this message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MHMessage.set_sequences">
<code class="descname">set_sequences</code><span class="sig-paren">(</span><em>sequences</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMessage.set_sequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of sequences that include this message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MHMessage.add_sequence">
<code class="descname">add_sequence</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMessage.add_sequence" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>sequence</em> to the list of sequences that include this message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MHMessage.remove_sequence">
<code class="descname">remove_sequence</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMessage.remove_sequence" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove <em>sequence</em> from the list of sequences that include this message.</p>
</dd></dl>

</dd></dl>

<p>When an <a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” sequence</td>
<td>no S flag</td>
</tr>
<tr class="row-odd"><td>“replied” sequence</td>
<td>R flag</td>
</tr>
<tr class="row-even"><td>“flagged” sequence</td>
<td>F flag</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance, the <em class="mailheader">Status</em>
and <em class="mailheader">X-Status</em> headers are omitted and the following conversions
take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a>
state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” sequence</td>
<td>no R flag</td>
</tr>
<tr class="row-odd"><td>“replied” sequence</td>
<td>A flag</td>
</tr>
<tr class="row-even"><td>“flagged” sequence</td>
<td>F flag</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” sequence</td>
<td>“unseen” label</td>
</tr>
<tr class="row-odd"><td>“replied” sequence</td>
<td>“answered” label</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="babylmessage">
<span id="mailbox-babylmessage"></span><h3>18.4.2.4. <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a><a class="headerlink" href="#babylmessage" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.BabylMessage">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">BabylMessage</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>A message with Babyl-specific behaviors. Parameter <em>message</em> has the same
meaning as with the <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructor.</p>
<p>Certain message labels, called <em class="dfn">attributes</em>, are defined by convention
to have special meanings. The attributes are as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="79%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Label</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>unseen</td>
<td>Not read, but previously detected by MUA</td>
</tr>
<tr class="row-odd"><td>deleted</td>
<td>Marked for subsequent deletion</td>
</tr>
<tr class="row-even"><td>filed</td>
<td>Copied to another file or mailbox</td>
</tr>
<tr class="row-odd"><td>answered</td>
<td>Replied to</td>
</tr>
<tr class="row-even"><td>forwarded</td>
<td>Forwarded</td>
</tr>
<tr class="row-odd"><td>edited</td>
<td>Modified by the user</td>
</tr>
<tr class="row-even"><td>resent</td>
<td>Resent</td>
</tr>
</tbody>
</table>
<p>By default, Rmail displays only visible headers. The <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a>
class, though, uses the original headers because they are more
complete. Visible headers may be accessed explicitly if desired.</p>
<p><a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instances offer the following methods:</p>
<dl class="method">
<dt id="mailbox.BabylMessage.get_labels">
<code class="descname">get_labels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.get_labels" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of labels on the message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.set_labels">
<code class="descname">set_labels</code><span class="sig-paren">(</span><em>labels</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.set_labels" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of labels on the message to <em>labels</em>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.add_label">
<code class="descname">add_label</code><span class="sig-paren">(</span><em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.add_label" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>label</em> to the list of labels on the message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.remove_label">
<code class="descname">remove_label</code><span class="sig-paren">(</span><em>label</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.remove_label" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove <em>label</em> from the list of labels on the message.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.get_visible">
<code class="descname">get_visible</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.get_visible" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance whose headers are the message’s
visible headers and whose body is empty.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.set_visible">
<code class="descname">set_visible</code><span class="sig-paren">(</span><em>visible</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.set_visible" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the message’s visible headers to be the same as the headers in
<em>message</em>.  Parameter <em>visible</em> should be a <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance, an
<a class="reference internal" href="email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">email.message.Message</span></code></a> instance, a string, or a file-like object
(which should be open in text mode).</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.BabylMessage.update_visible">
<code class="descname">update_visible</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMessage.update_visible" title="Permalink to this definition">¶</a></dt>
<dd><p>When a <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance’s original headers are modified, the
visible headers are not automatically modified to correspond. This method
updates the visible headers as follows: each visible header with a
corresponding original header is set to the value of the original header,
each visible header without a corresponding original header is removed,
and any of <em class="mailheader">Date</em>, <em class="mailheader">From</em>, <em class="mailheader">Reply-To</em>,
<em class="mailheader">To</em>, <em class="mailheader">CC</em>, and <em class="mailheader">Subject</em> that are
present in the original headers but not the visible headers are added to
the visible headers.</p>
</dd></dl>

</dd></dl>

<p>When a <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="62%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” label</td>
<td>no S flag</td>
</tr>
<tr class="row-odd"><td>“deleted” label</td>
<td>T flag</td>
</tr>
<tr class="row-even"><td>“answered” label</td>
<td>R flag</td>
</tr>
<tr class="row-odd"><td>“forwarded” label</td>
<td>P flag</td>
</tr>
</tbody>
</table>
<p>When a <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance, the <em class="mailheader">Status</em>
and <em class="mailheader">X-Status</em> headers are omitted and the following conversions
take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="28%" />
<col width="72%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> or <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a>
state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” label</td>
<td>no R flag</td>
</tr>
<tr class="row-odd"><td>“deleted” label</td>
<td>D flag</td>
</tr>
<tr class="row-even"><td>“answered” label</td>
<td>A flag</td>
</tr>
</tbody>
</table>
<p>When a <a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“unseen” label</td>
<td>“unseen” sequence</td>
</tr>
<tr class="row-odd"><td>“answered” label</td>
<td>“replied” sequence</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="mmdfmessage">
<span id="mailbox-mmdfmessage"></span><h3>18.4.2.5. <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a><a class="headerlink" href="#mmdfmessage" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="mailbox.MMDFMessage">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MMDFMessage</code><span class="sig-paren">(</span><span class="optional">[</span><em>message</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>A message with MMDF-specific behaviors. Parameter <em>message</em> has the same meaning
as with the <a class="reference internal" href="#mailbox.Message" title="mailbox.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> constructor.</p>
<p>As with message in an mbox mailbox, MMDF messages are stored with the
sender’s address and the delivery date in an initial line beginning with
“From “.  Likewise, flags that indicate the state of the message are
typically stored in <em class="mailheader">Status</em> and <em class="mailheader">X-Status</em> headers.</p>
<p>Conventional flags for MMDF messages are identical to those of mbox message
and are as follows:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="21%" />
<col width="67%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R</td>
<td>Read</td>
<td>Read</td>
</tr>
<tr class="row-odd"><td>O</td>
<td>Old</td>
<td>Previously detected by MUA</td>
</tr>
<tr class="row-even"><td>D</td>
<td>Deleted</td>
<td>Marked for subsequent deletion</td>
</tr>
<tr class="row-odd"><td>F</td>
<td>Flagged</td>
<td>Marked as important</td>
</tr>
<tr class="row-even"><td>A</td>
<td>Answered</td>
<td>Replied to</td>
</tr>
</tbody>
</table>
<p>The “R” and “O” flags are stored in the <em class="mailheader">Status</em> header, and the
“D”, “F”, and “A” flags are stored in the <em class="mailheader">X-Status</em> header. The
flags and headers typically appear in the order mentioned.</p>
<p><a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instances offer the following methods, which are
identical to those offered by <a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a>:</p>
<dl class="method">
<dt id="mailbox.MMDFMessage.get_from">
<code class="descname">get_from</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.get_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the “From ” line that marks the start of the
message in an mbox mailbox. The leading “From ” and the trailing newline
are excluded.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDFMessage.set_from">
<code class="descname">set_from</code><span class="sig-paren">(</span><em>from_</em>, <em>time_=None</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.set_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the “From ” line to <em>from_</em>, which should be specified without a
leading “From ” or trailing newline. For convenience, <em>time_</em> may be
specified and will be formatted appropriately and appended to <em>from_</em>. If
<em>time_</em> is specified, it should be a <a class="reference internal" href="time.html#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time.struct_time</span></code></a> instance, a
tuple suitable for passing to <a class="reference internal" href="time.html#time.strftime" title="time.strftime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>, or <code class="docutils literal notranslate"><span class="pre">True</span></code> (to use
<a class="reference internal" href="time.html#time.gmtime" title="time.gmtime"><code class="xref py py-meth docutils literal notranslate"><span class="pre">time.gmtime()</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDFMessage.get_flags">
<code class="descname">get_flags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.get_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string specifying the flags that are currently set. If the
message complies with the conventional format, the result is the
concatenation in the following order of zero or one occurrence of each of
<code class="docutils literal notranslate"><span class="pre">'R'</span></code>, <code class="docutils literal notranslate"><span class="pre">'O'</span></code>, <code class="docutils literal notranslate"><span class="pre">'D'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'A'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDFMessage.set_flags">
<code class="descname">set_flags</code><span class="sig-paren">(</span><em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.set_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags specified by <em>flags</em> and unset all others. Parameter <em>flags</em>
should be the concatenation in any order of zero or more occurrences of
each of <code class="docutils literal notranslate"><span class="pre">'R'</span></code>, <code class="docutils literal notranslate"><span class="pre">'O'</span></code>, <code class="docutils literal notranslate"><span class="pre">'D'</span></code>, <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'A'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDFMessage.add_flag">
<code class="descname">add_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.add_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flag(s) specified by <em>flag</em> without changing other flags. To add
more than one flag at a time, <em>flag</em> may be a string of more than one
character.</p>
</dd></dl>

<dl class="method">
<dt id="mailbox.MMDFMessage.remove_flag">
<code class="descname">remove_flag</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MMDFMessage.remove_flag" title="Permalink to this definition">¶</a></dt>
<dd><p>Unset the flag(s) specified by <em>flag</em> without changing other flags. To
remove more than one flag at a time, <em>flag</em> maybe a string of more than
one character.</p>
</dd></dl>

</dd></dl>

<p>When an <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance, a “From ” line is generated based upon the
<a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> instance’s delivery date, and the following conversions
take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MaildirMessage" title="mailbox.MaildirMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag</td>
<td>S flag</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“cur” subdirectory</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>T flag</td>
</tr>
<tr class="row-odd"><td>F flag</td>
<td>F flag</td>
</tr>
<tr class="row-even"><td>A flag</td>
<td>R flag</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.MHMessage" title="mailbox.MHMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MHMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag and O flag</td>
<td>no “unseen” sequence</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“unseen” sequence</td>
</tr>
<tr class="row-even"><td>F flag</td>
<td>“flagged” sequence</td>
</tr>
<tr class="row-odd"><td>A flag</td>
<td>“replied” sequence</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance is created based upon a
<a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> instance, the following conversions take place:</p>
<table border="1" class="docutils">
<colgroup>
<col width="40%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.BabylMessage" title="mailbox.BabylMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag and O flag</td>
<td>no “unseen” label</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>“unseen” label</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>“deleted” label</td>
</tr>
<tr class="row-odd"><td>A flag</td>
<td>“answered” label</td>
</tr>
</tbody>
</table>
<p>When an <a class="reference internal" href="#mailbox.MMDFMessage" title="mailbox.MMDFMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a> instance is created based upon an
<a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> instance, the “From ” line is copied and all flags directly
correspond:</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="62%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Resulting state</th>
<th class="head"><a class="reference internal" href="#mailbox.mboxMessage" title="mailbox.mboxMessage"><code class="xref py py-class docutils literal notranslate"><span class="pre">mboxMessage</span></code></a> state</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>R flag</td>
<td>R flag</td>
</tr>
<tr class="row-odd"><td>O flag</td>
<td>O flag</td>
</tr>
<tr class="row-even"><td>D flag</td>
<td>D flag</td>
</tr>
<tr class="row-odd"><td>F flag</td>
<td>F flag</td>
</tr>
<tr class="row-even"><td>A flag</td>
<td>A flag</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="exceptions">
<h2>18.4.3. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>The following exception classes are defined in the <a class="reference internal" href="#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module:</p>
<dl class="exception">
<dt id="mailbox.Error">
<em class="property">exception </em><code class="descclassname">mailbox.</code><code class="descname">Error</code><a class="headerlink" href="#mailbox.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>The based class for all other module-specific exceptions.</p>
</dd></dl>

<dl class="exception">
<dt id="mailbox.NoSuchMailboxError">
<em class="property">exception </em><code class="descclassname">mailbox.</code><code class="descname">NoSuchMailboxError</code><a class="headerlink" href="#mailbox.NoSuchMailboxError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a mailbox is expected but is not found, such as when instantiating a
<a class="reference internal" href="#mailbox.Mailbox" title="mailbox.Mailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mailbox</span></code></a> subclass with a path that does not exist (and with the <em>create</em>
parameter set to <code class="docutils literal notranslate"><span class="pre">False</span></code>), or when opening a folder that does not exist.</p>
</dd></dl>

<dl class="exception">
<dt id="mailbox.NotEmptyError">
<em class="property">exception </em><code class="descclassname">mailbox.</code><code class="descname">NotEmptyError</code><a class="headerlink" href="#mailbox.NotEmptyError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a mailbox is not empty but is expected to be, such as when deleting
a folder that contains messages.</p>
</dd></dl>

<dl class="exception">
<dt id="mailbox.ExternalClashError">
<em class="property">exception </em><code class="descclassname">mailbox.</code><code class="descname">ExternalClashError</code><a class="headerlink" href="#mailbox.ExternalClashError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when some mailbox-related condition beyond the control of the program
causes it to be unable to proceed, such as when failing to acquire a lock that
another program already holds a lock, or when a uniquely-generated file name
already exists.</p>
</dd></dl>

<dl class="exception">
<dt id="mailbox.FormatError">
<em class="property">exception </em><code class="descclassname">mailbox.</code><code class="descname">FormatError</code><a class="headerlink" href="#mailbox.FormatError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the data in a file cannot be parsed, such as when an <a class="reference internal" href="#mailbox.MH" title="mailbox.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a>
instance attempts to read a corrupted <code class="file docutils literal notranslate"><span class="pre">.mh_sequences</span></code> file.</p>
</dd></dl>

</div>
<div class="section" id="deprecated-classes-and-methods">
<span id="mailbox-deprecated"></span><h2>18.4.4. Deprecated classes and methods<a class="headerlink" href="#deprecated-classes-and-methods" title="Permalink to this headline">¶</a></h2>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
<p>Older versions of the <a class="reference internal" href="#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module do not support modification of
mailboxes, such as adding or removing message, and do not provide classes to
represent format-specific message properties. For backward compatibility, the
older mailbox classes are still available, but the newer classes should be used
in preference to them.  The old classes have been removed in Python 3.</p>
<p>Older mailbox objects support only iteration and provide a single public method:</p>
<dl class="method">
<dt id="mailbox.oldmailbox.next">
<code class="descclassname">oldmailbox.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.oldmailbox.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next message in the mailbox, created with the optional <em>factory</em>
argument passed into the mailbox object’s constructor. By default this is an
<a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a> object (see the <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module).  Depending on the
mailbox implementation the <em>fp</em> attribute of this object may be a true file
object or a class instance simulating a file object, taking care of things like
message boundaries if multiple mail messages are contained in a single file,
etc.  If no more messages are available, this method returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<p>Most of the older mailbox classes have names that differ from the current
mailbox class names, except for <a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a>. For this reason, the new
<a class="reference internal" href="#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> class defines a <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method and its constructor differs
slightly from those of the other new mailbox classes.</p>
<p>The older mailbox classes whose names are not the same as their newer
counterparts are as follows:</p>
<dl class="class">
<dt id="mailbox.UnixMailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">UnixMailbox</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.UnixMailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Access to a classic Unix-style mailbox, where all messages are contained in a
single file and separated by <code class="docutils literal notranslate"><span class="pre">From</span></code> (a.k.a. <code class="docutils literal notranslate"><span class="pre">From_</span></code>) lines.  The file object
<em>fp</em> points to the mailbox file.  The optional <em>factory</em> parameter is a callable
that should create new message objects.  <em>factory</em> is called with one argument,
<em>fp</em> by the <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method of the mailbox object.  The default is the
<a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a> class (see the <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module – and the note
below).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For reasons of this module’s internal implementation, you will probably want to
open the <em>fp</em> object in binary mode.  This is especially important on Windows.</p>
</div>
<p>For maximum portability, messages in a Unix-style mailbox are separated by any
line that begins exactly with the string <code class="docutils literal notranslate"><span class="pre">'From</span> <span class="pre">'</span></code> (note the trailing space)
if preceded by exactly two newlines. Because of the wide-range of variations in
practice, nothing else on the <code class="docutils literal notranslate"><span class="pre">From_</span></code> line should be considered.  However, the
current implementation doesn’t check for the leading two newlines.  This is
usually fine for most applications.</p>
<p>The <a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a> class implements a more strict version of <code class="docutils literal notranslate"><span class="pre">From_</span></code>
line checking, using a regular expression that usually correctly matched
<code class="docutils literal notranslate"><span class="pre">From_</span></code> delimiters.  It considers delimiter line to be separated by <code class="docutils literal notranslate"><span class="pre">From</span>
<span class="pre">name</span> <span class="pre">time</span></code> lines.  For maximum portability, use the
<a class="reference internal" href="#mailbox.PortableUnixMailbox" title="mailbox.PortableUnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">PortableUnixMailbox</span></code></a> class instead.  This class is identical to
<a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a> except that individual messages are separated by only
<code class="docutils literal notranslate"><span class="pre">From</span></code> lines.</p>
</dd></dl>

<dl class="class">
<dt id="mailbox.PortableUnixMailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">PortableUnixMailbox</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.PortableUnixMailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>A less-strict version of <a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a>, which considers only the <code class="docutils literal notranslate"><span class="pre">From</span></code>
at the beginning of the line separating messages.  The “<em>name</em> <em>time</em>” portion
of the From line is ignored, to protect against some variations that are
observed in practice.  This works since lines in the message which begin with
<code class="docutils literal notranslate"><span class="pre">'From</span> <span class="pre">'</span></code> are quoted by mail handling software at delivery-time.</p>
</dd></dl>

<dl class="class">
<dt id="mailbox.MmdfMailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MmdfMailbox</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MmdfMailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Access an MMDF-style mailbox, where all messages are contained in a single file
and separated by lines consisting of 4 control-A characters.  The file object
<em>fp</em> points to the mailbox file. Optional <em>factory</em> is as with the
<a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a> class.</p>
</dd></dl>

<dl class="class">
<dt id="mailbox.MHMailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">MHMailbox</code><span class="sig-paren">(</span><em>dirname</em><span class="optional">[</span>, <em>factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.MHMailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Access an MH mailbox, a directory with each message in a separate file with a
numeric name. The name of the mailbox directory is passed in <em>dirname</em>.
<em>factory</em> is as with the <a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a> class.</p>
</dd></dl>

<dl class="class">
<dt id="mailbox.BabylMailbox">
<em class="property">class </em><code class="descclassname">mailbox.</code><code class="descname">BabylMailbox</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>factory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailbox.BabylMailbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Access a Babyl mailbox, which is similar to an MMDF mailbox.  In Babyl format,
each message has two sets of headers, the <em>original</em> headers and the <em>visible</em>
headers.  The original headers appear before a line containing only <code class="docutils literal notranslate"><span class="pre">'***</span> <span class="pre">EOOH</span>
<span class="pre">***'</span></code> (End-Of-Original-Headers) and the visible headers appear after the
<code class="docutils literal notranslate"><span class="pre">EOOH</span></code> line.  Babyl-compliant mail readers will show you only the visible
headers, and <a class="reference internal" href="#mailbox.BabylMailbox" title="mailbox.BabylMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">BabylMailbox</span></code></a> objects will return messages containing only
the visible headers.  You’ll have to do your own parsing of the mailbox file to
get at the original headers.  Mail messages start with the EOOH line and end
with a line containing only <code class="docutils literal notranslate"><span class="pre">'\037\014'</span></code>.  <em>factory</em> is as with the
<a class="reference internal" href="#mailbox.UnixMailbox" title="mailbox.UnixMailbox"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixMailbox</span></code></a> class.</p>
</dd></dl>

<p>If you wish to use the older mailbox classes with the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> module rather
than the deprecated <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module, you can do so as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">email</span>
<span class="kn">import</span> <span class="nn">email.Errors</span>
<span class="kn">import</span> <span class="nn">mailbox</span>

<span class="k">def</span> <span class="nf">msgfactory</span><span class="p">(</span><span class="n">fp</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_file</span><span class="p">(</span><span class="n">fp</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">email</span><span class="o">.</span><span class="n">Errors</span><span class="o">.</span><span class="n">MessageParseError</span><span class="p">:</span>
        <span class="c1"># Don&#39;t return None since that will</span>
        <span class="c1"># stop the mailbox iterator</span>
        <span class="k">return</span> <span class="s1">&#39;&#39;</span>

<span class="n">mbox</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">UnixMailbox</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="n">msgfactory</span><span class="p">)</span>
</pre></div>
</div>
<p>Alternatively, if you know your mailbox contains only well-formed MIME messages,
you can simplify this to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">email</span>
<span class="kn">import</span> <span class="nn">mailbox</span>

<span class="n">mbox</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">UnixMailbox</span><span class="p">(</span><span class="n">fp</span><span class="p">,</span> <span class="n">email</span><span class="o">.</span><span class="n">message_from_file</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="examples">
<span id="mailbox-examples"></span><h2>18.4.5. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>A simple example of printing the subjects of all messages in a mailbox that seem
interesting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>
<span class="k">for</span> <span class="n">message</span> <span class="ow">in</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">mbox</span><span class="p">(</span><span class="s1">&#39;~/mbox&#39;</span><span class="p">):</span>
    <span class="n">subject</span> <span class="o">=</span> <span class="n">message</span><span class="p">[</span><span class="s1">&#39;subject&#39;</span><span class="p">]</span>       <span class="c1"># Could possibly be None.</span>
    <span class="k">if</span> <span class="n">subject</span> <span class="ow">and</span> <span class="s1">&#39;python&#39;</span> <span class="ow">in</span> <span class="n">subject</span><span class="o">.</span><span class="n">lower</span><span class="p">():</span>
        <span class="nb">print</span> <span class="n">subject</span>
</pre></div>
</div>
<p>To copy all mail from a Babyl mailbox to an MH mailbox, converting all of the
format-specific information that can be converted:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>
<span class="n">destination</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">MH</span><span class="p">(</span><span class="s1">&#39;~/Mail&#39;</span><span class="p">)</span>
<span class="n">destination</span><span class="o">.</span><span class="n">lock</span><span class="p">()</span>
<span class="k">for</span> <span class="n">message</span> <span class="ow">in</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">Babyl</span><span class="p">(</span><span class="s1">&#39;~/RMAIL&#39;</span><span class="p">):</span>
    <span class="n">destination</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">mailbox</span><span class="o">.</span><span class="n">MHMessage</span><span class="p">(</span><span class="n">message</span><span class="p">))</span>
<span class="n">destination</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
<span class="n">destination</span><span class="o">.</span><span class="n">unlock</span><span class="p">()</span>
</pre></div>
</div>
<p>This example sorts mail from several mailing lists into different mailboxes,
being careful to avoid mail corruption due to concurrent modification by other
programs, mail loss due to interruption of the program, or premature termination
due to malformed messages in the mailbox:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>
<span class="kn">import</span> <span class="nn">email.errors</span>

<span class="n">list_names</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;python-list&#39;</span><span class="p">,</span> <span class="s1">&#39;python-dev&#39;</span><span class="p">,</span> <span class="s1">&#39;python-bugs&#39;</span><span class="p">)</span>

<span class="n">boxes</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">name</span><span class="p">,</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">mbox</span><span class="p">(</span><span class="s1">&#39;~/email/</span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">name</span><span class="p">))</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">list_names</span><span class="p">)</span>
<span class="n">inbox</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">Maildir</span><span class="p">(</span><span class="s1">&#39;~/Maildir&#39;</span><span class="p">,</span> <span class="n">factory</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>

<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">inbox</span><span class="o">.</span><span class="n">iterkeys</span><span class="p">():</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">message</span> <span class="o">=</span> <span class="n">inbox</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
    <span class="k">except</span> <span class="n">email</span><span class="o">.</span><span class="n">errors</span><span class="o">.</span><span class="n">MessageParseError</span><span class="p">:</span>
        <span class="k">continue</span>                <span class="c1"># The message is malformed. Just leave it.</span>

    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">list_names</span><span class="p">:</span>
        <span class="n">list_id</span> <span class="o">=</span> <span class="n">message</span><span class="p">[</span><span class="s1">&#39;list-id&#39;</span><span class="p">]</span>
        <span class="k">if</span> <span class="n">list_id</span> <span class="ow">and</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">list_id</span><span class="p">:</span>
            <span class="c1"># Get mailbox to use</span>
            <span class="n">box</span> <span class="o">=</span> <span class="n">boxes</span><span class="p">[</span><span class="n">name</span><span class="p">]</span>

            <span class="c1"># Write copy to disk before removing original.</span>
            <span class="c1"># If there&#39;s a crash, you might duplicate a message, but</span>
            <span class="c1"># that&#39;s better than losing a message completely.</span>
            <span class="n">box</span><span class="o">.</span><span class="n">lock</span><span class="p">()</span>
            <span class="n">box</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
            <span class="n">box</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
            <span class="n">box</span><span class="o">.</span><span class="n">unlock</span><span class="p">()</span>

            <span class="c1"># Remove original message</span>
            <span class="n">inbox</span><span class="o">.</span><span class="n">lock</span><span class="p">()</span>
            <span class="n">inbox</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
            <span class="n">inbox</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
            <span class="n">inbox</span><span class="o">.</span><span class="n">unlock</span><span class="p">()</span>
            <span class="k">break</span>               <span class="c1"># Found destination, so stop looking.</span>

<span class="k">for</span> <span class="n">box</span> <span class="ow">in</span> <span class="n">boxes</span><span class="o">.</span><span class="n">itervalues</span><span class="p">():</span>
    <span class="n">box</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a><ul>
<li><a class="reference internal" href="#mailbox-objects">18.4.1. <code class="docutils literal notranslate"><span class="pre">Mailbox</span></code> objects</a><ul>
<li><a class="reference internal" href="#maildir">18.4.1.1. <code class="docutils literal notranslate"><span class="pre">Maildir</span></code></a></li>
<li><a class="reference internal" href="#mbox">18.4.1.2. <code class="docutils literal notranslate"><span class="pre">mbox</span></code></a></li>
<li><a class="reference internal" href="#mh">18.4.1.3. <code class="docutils literal notranslate"><span class="pre">MH</span></code></a></li>
<li><a class="reference internal" href="#babyl">18.4.1.4. <code class="docutils literal notranslate"><span class="pre">Babyl</span></code></a></li>
<li><a class="reference internal" href="#mmdf">18.4.1.5. <code class="docutils literal notranslate"><span class="pre">MMDF</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#message-objects">18.4.2. <code class="docutils literal notranslate"><span class="pre">Message</span></code> objects</a><ul>
<li><a class="reference internal" href="#maildirmessage">18.4.2.1. <code class="docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a></li>
<li><a class="reference internal" href="#mboxmessage">18.4.2.2. <code class="docutils literal notranslate"><span class="pre">mboxMessage</span></code></a></li>
<li><a class="reference internal" href="#mhmessage">18.4.2.3. <code class="docutils literal notranslate"><span class="pre">MHMessage</span></code></a></li>
<li><a class="reference internal" href="#babylmessage">18.4.2.4. <code class="docutils literal notranslate"><span class="pre">BabylMessage</span></code></a></li>
<li><a class="reference internal" href="#mmdfmessage">18.4.2.5. <code class="docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">18.4.3. Exceptions</a></li>
<li><a class="reference internal" href="#deprecated-classes-and-methods">18.4.4. Deprecated classes and methods</a></li>
<li><a class="reference internal" href="#examples">18.4.5. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mailcap.html"
                        title="previous chapter">18.3. <code class="docutils literal notranslate"><span class="pre">mailcap</span></code> — Mailcap file handling</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mhlib.html"
                        title="next chapter">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mailbox.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mhlib.html" title="18.5. mhlib — Access to MH mailboxes"
             >next</a> |</li>
        <li class="right" >
          <a href="mailcap.html" title="18.3. mailcap — Mailcap file handling"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\K��4747html/library/mailcap.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.3. mailcap — Mailcap file handling &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.4. mailbox — Manipulate mailboxes in various formats" href="mailbox.html" />
    <link rel="prev" title="18.2. json — JSON encoder and decoder" href="json.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mailcap.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mailbox.html" title="18.4. mailbox — Manipulate mailboxes in various formats"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="json.html" title="18.2. json — JSON encoder and decoder"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mailcap">
<span id="mailcap-mailcap-file-handling"></span><h1>18.3. <a class="reference internal" href="#module-mailcap" title="mailcap: Mailcap file handling."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailcap</span></code></a> — Mailcap file handling<a class="headerlink" href="#module-mailcap" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/mailcap.py">Lib/mailcap.py</a></p>
<hr class="docutils" />
<p>Mailcap files are used to configure how MIME-aware applications such as mail
readers and Web browsers react to files with different MIME types. (The name
“mailcap” is derived from the phrase “mail capability”.)  For example, a mailcap
file might contain a line like <code class="docutils literal notranslate"><span class="pre">video/mpeg;</span> <span class="pre">xmpeg</span> <span class="pre">%s</span></code>.  Then, if the user
encounters an email message or Web document with the MIME type
<em class="mimetype">video/mpeg</em>, <code class="docutils literal notranslate"><span class="pre">%s</span></code> will be replaced by a filename (usually one
belonging to a temporary file) and the <strong class="program">xmpeg</strong> program can be
automatically started to view the file.</p>
<p>The mailcap format is documented in <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1524.html"><strong>RFC 1524</strong></a>, “A User Agent Configuration
Mechanism For Multimedia Mail Format Information,” but is not an Internet
standard.  However, mailcap files are supported on most Unix systems.</p>
<dl class="function">
<dt id="mailcap.findmatch">
<code class="descclassname">mailcap.</code><code class="descname">findmatch</code><span class="sig-paren">(</span><em>caps</em>, <em>MIMEtype</em><span class="optional">[</span>, <em>key</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>plist</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mailcap.findmatch" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a 2-tuple; the first element is a string containing the command line to
be executed (which can be passed to <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>), and the second element
is the mailcap entry for a given MIME type.  If no matching MIME type can be
found, <code class="docutils literal notranslate"><span class="pre">(None,</span> <span class="pre">None)</span></code> is returned.</p>
<p><em>key</em> is the name of the field desired, which represents the type of activity to
be performed; the default value is ‘view’, since in the  most common case you
simply want to view the body of the MIME-typed data.  Other possible values
might be ‘compose’ and ‘edit’, if you wanted to create a new body of the given
MIME type or alter the existing body data.  See <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1524.html"><strong>RFC 1524</strong></a> for a complete list
of these fields.</p>
<p><em>filename</em> is the filename to be substituted for <code class="docutils literal notranslate"><span class="pre">%s</span></code> in the command line; the
default value is <code class="docutils literal notranslate"><span class="pre">'/dev/null'</span></code> which is almost certainly not what you want, so
usually you’ll override it by specifying a filename.</p>
<p><em>plist</em> can be a list containing named parameters; the default value is simply
an empty list.  Each entry in the list must be a string containing the parameter
name, an equals sign (<code class="docutils literal notranslate"><span class="pre">'='</span></code>), and the parameter’s value.  Mailcap entries can
contain  named parameters like <code class="docutils literal notranslate"><span class="pre">%{foo}</span></code>, which will be replaced by the value
of the parameter named ‘foo’.  For example, if the command line <code class="docutils literal notranslate"><span class="pre">showpartial</span>
<span class="pre">%{id}</span> <span class="pre">%{number}</span> <span class="pre">%{total}</span></code> was in a mailcap file, and <em>plist</em> was set to
<code class="docutils literal notranslate"><span class="pre">['id=1',</span> <span class="pre">'number=2',</span> <span class="pre">'total=3']</span></code>, the resulting command line would be
<code class="docutils literal notranslate"><span class="pre">'showpartial</span> <span class="pre">1</span> <span class="pre">2</span> <span class="pre">3'</span></code>.</p>
<p>In a mailcap file, the “test” field can optionally be specified to test some
external condition (such as the machine architecture, or the window system in
use) to determine whether or not the mailcap line applies.  <a class="reference internal" href="#mailcap.findmatch" title="mailcap.findmatch"><code class="xref py py-func docutils literal notranslate"><span class="pre">findmatch()</span></code></a>
will automatically check such conditions and skip the entry if the check fails.</p>
</dd></dl>

<dl class="function">
<dt id="mailcap.getcaps">
<code class="descclassname">mailcap.</code><code class="descname">getcaps</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mailcap.getcaps" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a dictionary mapping MIME types to a list of mailcap file entries. This
dictionary must be passed to the <a class="reference internal" href="#mailcap.findmatch" title="mailcap.findmatch"><code class="xref py py-func docutils literal notranslate"><span class="pre">findmatch()</span></code></a> function.  An entry is stored
as a list of dictionaries, but it shouldn’t be necessary to know the details of
this representation.</p>
<p>The information is derived from all of the mailcap files found on the system.
Settings in the user’s mailcap file <code class="file docutils literal notranslate"><span class="pre">$HOME/.mailcap</span></code> will override
settings in the system mailcap files <code class="file docutils literal notranslate"><span class="pre">/etc/mailcap</span></code>,
<code class="file docutils literal notranslate"><span class="pre">/usr/etc/mailcap</span></code>, and <code class="file docutils literal notranslate"><span class="pre">/usr/local/etc/mailcap</span></code>.</p>
</dd></dl>

<p>An example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mailcap</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">mailcap</span><span class="o">.</span><span class="n">getcaps</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mailcap</span><span class="o">.</span><span class="n">findmatch</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="s1">&#39;video/mpeg&#39;</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s1">&#39;tmp1223&#39;</span><span class="p">)</span>
<span class="go">(&#39;xmpeg tmp1223&#39;, {&#39;view&#39;: &#39;xmpeg %s&#39;})</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="json.html"
                        title="previous chapter">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mailbox.html"
                        title="next chapter">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mailcap.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mailbox.html" title="18.4. mailbox — Manipulate mailboxes in various formats"
             >next</a> |</li>
        <li class="right" >
          <a href="json.html" title="18.2. json — JSON encoder and decoder"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\_�9�M�Mhtml/library/markup.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19. Structured Markup Processing Tools &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.1. HTMLParser — Simple HTML and XHTML parser" href="htmlparser.html" />
    <link rel="prev" title="18.16. uu — Encode and decode uuencode files" href="uu.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/markup.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="htmlparser.html" title="19.1. HTMLParser — Simple HTML and XHTML parser"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="uu.html" title="18.16. uu — Encode and decode uuencode files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="structured-markup-processing-tools">
<span id="markup"></span><h1>19. Structured Markup Processing Tools<a class="headerlink" href="#structured-markup-processing-tools" title="Permalink to this headline">¶</a></h1>
<p>Python supports a variety of modules to work with various forms of structured
data markup.  This includes modules to work with the Standard Generalized Markup
Language (SGML) and the Hypertext Markup Language (HTML), and several interfaces
for working with the Extensible Markup Language (XML).</p>
<p>It is important to note that modules in the <a class="reference internal" href="xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package require that
there be at least one SAX-compliant XML parser available. Starting with Python
2.3, the Expat parser is included with Python, so the <a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a>
module will always be available. You may still want to be aware of the <a class="reference external" href="http://pyxml.sourceforge.net/">PyXML
add-on package</a>; that package provides an
extended set of XML libraries for Python.</p>
<p>The documentation for the <a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> and <a class="reference internal" href="xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> packages are the
definition of the Python bindings for the DOM and SAX interfaces.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="htmlparser.html">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a><ul>
<li class="toctree-l2"><a class="reference internal" href="htmlparser.html#example-html-parser-application">19.1.1. Example HTML Parser Application</a></li>
<li class="toctree-l2"><a class="reference internal" href="htmlparser.html#htmlparser-methods">19.1.2. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> Methods</a></li>
<li class="toctree-l2"><a class="reference internal" href="htmlparser.html#examples">19.1.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sgmllib.html">19.2. <code class="docutils literal notranslate"><span class="pre">sgmllib</span></code> — Simple SGML parser</a></li>
<li class="toctree-l1"><a class="reference internal" href="htmllib.html">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a><ul>
<li class="toctree-l2"><a class="reference internal" href="htmllib.html#htmlparser-objects">19.3.1. HTMLParser Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="htmllib.html#module-htmlentitydefs">19.4. <code class="docutils literal notranslate"><span class="pre">htmlentitydefs</span></code> — Definitions of HTML general entities</a></li>
<li class="toctree-l1"><a class="reference internal" href="xml.html">19.5. XML Processing Modules</a></li>
<li class="toctree-l1"><a class="reference internal" href="xml.html#xml-vulnerabilities">19.6. XML vulnerabilities</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.html#defused-packages">19.6.1. defused packages</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.etree.elementtree.html">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.etree.elementtree.html#tutorial">19.7.1. Tutorial</a><ul>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#xml-tree-and-elements">19.7.1.1. XML tree and elements</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#parsing-xml">19.7.1.2. Parsing XML</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#finding-interesting-elements">19.7.1.3. Finding interesting elements</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#modifying-an-xml-file">19.7.1.4. Modifying an XML File</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#building-xml-documents">19.7.1.5. Building XML documents</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#parsing-xml-with-namespaces">19.7.1.6. Parsing XML with Namespaces</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#additional-resources">19.7.1.7. Additional resources</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="xml.etree.elementtree.html#xpath-support">19.7.2. XPath support</a><ul>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#example">19.7.2.1. Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#supported-xpath-syntax">19.7.2.2. Supported XPath syntax</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="xml.etree.elementtree.html#reference">19.7.3. Reference</a><ul>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#functions">19.7.3.1. Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#element-objects">19.7.3.2. Element Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#elementtree-objects">19.7.3.3. ElementTree Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#qname-objects">19.7.3.4. QName Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#treebuilder-objects">19.7.3.5. TreeBuilder Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.etree.elementtree.html#xmlparser-objects">19.7.3.6. XMLParser Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.dom.html">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.html#module-contents">19.8.1. Module Contents</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.html#objects-in-the-dom">19.8.2. Objects in the DOM</a><ul>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#domimplementation-objects">19.8.2.1. DOMImplementation Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#node-objects">19.8.2.2. Node Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#nodelist-objects">19.8.2.3. NodeList Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#documenttype-objects">19.8.2.4. DocumentType Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#document-objects">19.8.2.5. Document Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#element-objects">19.8.2.6. Element Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#attr-objects">19.8.2.7. Attr Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#namednodemap-objects">19.8.2.8. NamedNodeMap Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#comment-objects">19.8.2.9. Comment Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#text-and-cdatasection-objects">19.8.2.10. Text and CDATASection Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#processinginstruction-objects">19.8.2.11. ProcessingInstruction Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#exceptions">19.8.2.12. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.html#conformance">19.8.3. Conformance</a><ul>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#type-mapping">19.8.3.1. Type Mapping</a></li>
<li class="toctree-l3"><a class="reference internal" href="xml.dom.html#accessor-methods">19.8.3.2. Accessor Methods</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.dom.minidom.html">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.minidom.html#dom-objects">19.9.1. DOM Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.minidom.html#dom-example">19.9.2. DOM Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.minidom.html#minidom-and-the-dom-standard">19.9.3. minidom and the DOM standard</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.dom.pulldom.html">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.dom.pulldom.html#domeventstream-objects">19.10.1. DOMEventStream Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.sax.html">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.html#saxexception-objects">19.11.1. SAXException Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.sax.handler.html">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.handler.html#contenthandler-objects">19.12.1. ContentHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.handler.html#dtdhandler-objects">19.12.2. DTDHandler Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.handler.html#entityresolver-objects">19.12.3. EntityResolver Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.handler.html#errorhandler-objects">19.12.4. ErrorHandler Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="xml.sax.utils.html">19.13. <code class="docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code> — SAX Utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="xml.sax.reader.html">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#xmlreader-objects">19.14.1. XMLReader Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#incrementalparser-objects">19.14.2. IncrementalParser Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#locator-objects">19.14.3. Locator Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#inputsource-objects">19.14.4. InputSource Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#the-attributes-interface">19.14.5. The <code class="docutils literal notranslate"><span class="pre">Attributes</span></code> Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="xml.sax.reader.html#the-attributesns-interface">19.14.6. The <code class="docutils literal notranslate"><span class="pre">AttributesNS</span></code> Interface</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="pyexpat.html">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html#xmlparser-objects">19.15.1. XMLParser Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html#expaterror-exceptions">19.15.2. ExpatError Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html#example">19.15.3. Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html#content-model-descriptions">19.15.4. Content Model Descriptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="pyexpat.html#expat-error-constants">19.15.5. Expat error constants</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="uu.html"
                        title="previous chapter">18.16. <code class="docutils literal notranslate"><span class="pre">uu</span></code> — Encode and decode uuencode files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="htmlparser.html"
                        title="next chapter">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/markup.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="htmlparser.html" title="19.1. HTMLParser — Simple HTML and XHTML parser"
             >next</a> |</li>
        <li class="right" >
          <a href="uu.html" title="18.16. uu — Encode and decode uuencode files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\GU3�LLhtml/library/marshal.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.5. marshal — Internal Python object serialization &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.6. anydbm — Generic access to DBM-style databases" href="anydbm.html" />
    <link rel="prev" title="11.4. shelve — Python object persistence" href="shelve.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/marshal.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="anydbm.html" title="11.6. anydbm — Generic access to DBM-style databases"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="shelve.html" title="11.4. shelve — Python object persistence"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-marshal">
<span id="marshal-internal-python-object-serialization"></span><h1>11.5. <a class="reference internal" href="#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> — Internal Python object serialization<a class="headerlink" href="#module-marshal" title="Permalink to this headline">¶</a></h1>
<p>This module contains functions that can read and write Python values in a binary
format.  The format is specific to Python, but independent of machine
architecture issues (e.g., you can write a Python value to a file on a PC,
transport the file to a Sun, and read it back there).  Details of the format are
undocumented on purpose; it may change between Python versions (although it
rarely does). <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<p id="index-0">This is not a general “persistence” module.  For general persistence and
transfer of Python objects through RPC calls, see the modules <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and
<a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>.  The <a class="reference internal" href="#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module exists mainly to support reading and
writing the “pseudo-compiled” code for Python modules of <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files.
Therefore, the Python maintainers reserve the right to modify the marshal format
in backward incompatible ways should the need arise.  If you’re serializing and
de-serializing Python objects, use the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module instead – the
performance is comparable, version independence is guaranteed, and pickle
supports a substantially wider range of objects than marshal.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module is not intended to be secure against erroneous or
maliciously constructed data.  Never unmarshal data received from an
untrusted or unauthenticated source.</p>
</div>
<p id="index-1">Not all Python object types are supported; in general, only objects whose value
is independent from a particular invocation of Python can be written and read by
this module.  The following types are supported: booleans, integers, long
integers, floating point numbers, complex numbers, strings, Unicode objects,
tuples, lists, sets, frozensets, dictionaries, and code objects, where it should
be understood that tuples, lists, sets, frozensets and dictionaries are only
supported as long as the values contained therein are themselves supported; and
recursive lists, sets and dictionaries should not be written (they will cause
infinite loops).  The singletons <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, <a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-const docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> and
<a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> can also be marshalled and unmarshalled.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">On machines where C’s <code class="docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code> type has more than 32 bits (such as the
DEC Alpha), it is possible to create plain Python integers that are longer
than 32 bits. If such an integer is marshaled and read back in on a machine
where C’s <code class="docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code> type has only 32 bits, a Python long integer object
is returned instead.  While of a different type, the numeric value is the
same.  (This behavior is new in Python 2.2.  In earlier versions, all but the
least-significant 32 bits of the value were lost, and a warning message was
printed.)</p>
</div>
<p>There are functions that read/write files as well as functions operating on
strings.</p>
<p>The module defines these functions:</p>
<dl class="function">
<dt id="marshal.dump">
<code class="descclassname">marshal.</code><code class="descname">dump</code><span class="sig-paren">(</span><em>value</em>, <em>file</em><span class="optional">[</span>, <em>version</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#marshal.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the value on the open file.  The value must be a supported type.  The
file must be an open file object such as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> or returned by
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> or <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>.  It may not be a wrapper such as
TemporaryFile on Windows. It must be opened in binary mode (<code class="docutils literal notranslate"><span class="pre">'wb'</span></code>
or <code class="docutils literal notranslate"><span class="pre">'w+b'</span></code>).</p>
<p>If the value has (or contains an object that has) an unsupported type, a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception is raised — but garbage data will also be written
to the file.  The object will not be properly read back by <a class="reference internal" href="#marshal.load" title="marshal.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>The <em>version</em> argument indicates the data format that <code class="docutils literal notranslate"><span class="pre">dump</span></code> should use
(see below).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="marshal.load">
<code class="descclassname">marshal.</code><code class="descname">load</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#marshal.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Read one value from the open file and return it.  If no valid value is read
(e.g. because the data has a different Python version’s incompatible marshal
format), raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  The
file must be an open file object opened in binary mode (<code class="docutils literal notranslate"><span class="pre">'rb'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'r+b'</span></code>).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If an object containing an unsupported type was marshalled with <a class="reference internal" href="#marshal.dump" title="marshal.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>,
<a class="reference internal" href="#marshal.load" title="marshal.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code></a> will substitute <code class="docutils literal notranslate"><span class="pre">None</span></code> for the unmarshallable type.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="marshal.dumps">
<code class="descclassname">marshal.</code><code class="descname">dumps</code><span class="sig-paren">(</span><em>value</em><span class="optional">[</span>, <em>version</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#marshal.dumps" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string that would be written to a file by <code class="docutils literal notranslate"><span class="pre">dump(value,</span> <span class="pre">file)</span></code>.  The
value must be a supported type.  Raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception if value
has (or contains an object that has) an unsupported type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>The <em>version</em> argument indicates the data format that <code class="docutils literal notranslate"><span class="pre">dumps</span></code> should use
(see below).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="marshal.loads">
<code class="descclassname">marshal.</code><code class="descname">loads</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#marshal.loads" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the string to a value.  If no valid value is found, raise
<a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  Extra characters in the
string are ignored.</p>
</dd></dl>

<p>In addition, the following constants are defined:</p>
<dl class="data">
<dt id="marshal.version">
<code class="descclassname">marshal.</code><code class="descname">version</code><a class="headerlink" href="#marshal.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates the format that the module uses. Version 0 is the historical format,
version 1 (added in Python 2.4) shares interned strings and version 2 (added in
Python 2.5) uses a binary format for floating point numbers. The current version
is 2.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The name of this module stems from a bit of terminology used by the designers of
Modula-3 (amongst others), who use the term “marshalling” for shipping of data
around in a self-contained form. Strictly speaking, “to marshal” means to
convert some data from internal to external form (in an RPC buffer for instance)
and “unmarshalling” for the reverse process.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="shelve.html"
                        title="previous chapter">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="anydbm.html"
                        title="next chapter">11.6. <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> — Generic access to DBM-style databases</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/marshal.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="anydbm.html" title="11.6. anydbm — Generic access to DBM-style databases"
             >next</a> |</li>
        <li class="right" >
          <a href="shelve.html" title="11.4. shelve — Python object persistence"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\c(eM��html/library/math.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.2. math — Mathematical functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.3. cmath — Mathematical functions for complex numbers" href="cmath.html" />
    <link rel="prev" title="9.1. numbers — Numeric abstract base classes" href="numbers.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/math.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmath.html" title="9.3. cmath — Mathematical functions for complex numbers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="numbers.html" title="9.1. numbers — Numeric abstract base classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-math">
<span id="math-mathematical-functions"></span><h1>9.2. <a class="reference internal" href="#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> — Mathematical functions<a class="headerlink" href="#module-math" title="Permalink to this headline">¶</a></h1>
<p>This module is always available.  It provides access to the mathematical
functions defined by the C standard.</p>
<p>These functions cannot be used with complex numbers; use the functions of the
same name from the <a class="reference internal" href="cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module if you require support for complex
numbers.  The distinction between functions which support complex numbers and
those which don’t is made since most users do not want to learn quite as much
mathematics as required to understand complex numbers.  Receiving an exception
instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it
was generated in the first place.</p>
<p>The following functions are provided by this module.  Except when explicitly
noted otherwise, all return values are floats.</p>
<div class="section" id="number-theoretic-and-representation-functions">
<h2>9.2.1. Number-theoretic and representation functions<a class="headerlink" href="#number-theoretic-and-representation-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.ceil">
<code class="descclassname">math.</code><code class="descname">ceil</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.ceil" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the ceiling of <em>x</em> as a float, the smallest integer value greater than or
equal to <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="math.copysign">
<code class="descclassname">math.</code><code class="descname">copysign</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#math.copysign" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>x</em> with the sign of <em>y</em>.  On a platform that supports
signed zeros, <code class="docutils literal notranslate"><span class="pre">copysign(1.0,</span> <span class="pre">-0.0)</span></code> returns <em>-1.0</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.fabs">
<code class="descclassname">math.</code><code class="descname">fabs</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.fabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the absolute value of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="math.factorial">
<code class="descclassname">math.</code><code class="descname">factorial</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.factorial" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>x</em> factorial.  Raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>x</em> is not integral or
is negative.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.floor">
<code class="descclassname">math.</code><code class="descname">floor</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.floor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the floor of <em>x</em> as a float, the largest integer value less than or equal
to <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="math.fmod">
<code class="descclassname">math.</code><code class="descname">fmod</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#math.fmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">fmod(x,</span> <span class="pre">y)</span></code>, as defined by the platform C library. Note that the
Python expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code> may not return the same result.  The intent of the C
standard is that <code class="docutils literal notranslate"><span class="pre">fmod(x,</span> <span class="pre">y)</span></code> be exactly (mathematically; to infinite
precision) equal to <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">n*y</span></code> for some integer <em>n</em> such that the result has
the same sign as <em>x</em> and magnitude less than <code class="docutils literal notranslate"><span class="pre">abs(y)</span></code>.  Python’s <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code>
returns a result with the sign of <em>y</em> instead, and may not be exactly computable
for float arguments. For example, <code class="docutils literal notranslate"><span class="pre">fmod(-1e-100,</span> <span class="pre">1e100)</span></code> is <code class="docutils literal notranslate"><span class="pre">-1e-100</span></code>, but
the result of Python’s <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">%</span> <span class="pre">1e100</span></code> is <code class="docutils literal notranslate"><span class="pre">1e100-1e-100</span></code>, which cannot be
represented exactly as a float, and rounds to the surprising <code class="docutils literal notranslate"><span class="pre">1e100</span></code>.  For
this reason, function <a class="reference internal" href="#math.fmod" title="math.fmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">fmod()</span></code></a> is generally preferred when working with
floats, while Python’s <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code> is preferred when working with integers.</p>
</dd></dl>

<dl class="function">
<dt id="math.frexp">
<code class="descclassname">math.</code><code class="descname">frexp</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.frexp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mantissa and exponent of <em>x</em> as the pair <code class="docutils literal notranslate"><span class="pre">(m,</span> <span class="pre">e)</span></code>.  <em>m</em> is a float
and <em>e</em> is an integer such that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">m</span> <span class="pre">*</span> <span class="pre">2**e</span></code> exactly. If <em>x</em> is zero,
returns <code class="docutils literal notranslate"><span class="pre">(0.0,</span> <span class="pre">0)</span></code>, otherwise <code class="docutils literal notranslate"><span class="pre">0.5</span> <span class="pre">&lt;=</span> <span class="pre">abs(m)</span> <span class="pre">&lt;</span> <span class="pre">1</span></code>.  This is used to “pick
apart” the internal representation of a float in a portable way.</p>
</dd></dl>

<dl class="function">
<dt id="math.fsum">
<code class="descclassname">math.</code><code class="descname">fsum</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#math.fsum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an accurate floating point sum of values in the iterable.  Avoids
loss of precision by tracking multiple intermediate partial sums:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">])</span>
<span class="go">0.9999999999999999</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fsum</span><span class="p">([</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">])</span>
<span class="go">1.0</span>
</pre></div>
</div>
<p>The algorithm’s accuracy depends on IEEE-754 arithmetic guarantees and the
typical case where the rounding mode is half-even.  On some non-Windows
builds, the underlying C library uses extended precision addition and may
occasionally double-round an intermediate sum causing it to be off in its
least significant bit.</p>
<p>For further discussion and two alternative approaches, see the <a class="reference external" href="https://code.activestate.com/recipes/393090/">ASPN cookbook
recipes for accurate floating point summation</a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.isinf">
<code class="descclassname">math.</code><code class="descname">isinf</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.isinf" title="Permalink to this definition">¶</a></dt>
<dd><p>Check if the float <em>x</em> is positive or negative infinity.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.isnan">
<code class="descclassname">math.</code><code class="descname">isnan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.isnan" title="Permalink to this definition">¶</a></dt>
<dd><p>Check if the float <em>x</em> is a NaN (not a number).  For more information
on NaNs, see the IEEE 754 standards.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.ldexp">
<code class="descclassname">math.</code><code class="descname">ldexp</code><span class="sig-paren">(</span><em>x</em>, <em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#math.ldexp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">(2**i)</span></code>.  This is essentially the inverse of function
<a class="reference internal" href="#math.frexp" title="math.frexp"><code class="xref py py-func docutils literal notranslate"><span class="pre">frexp()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="math.modf">
<code class="descclassname">math.</code><code class="descname">modf</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.modf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the fractional and integer parts of <em>x</em>.  Both results carry the sign
of <em>x</em> and are floats.</p>
</dd></dl>

<dl class="function">
<dt id="math.trunc">
<code class="descclassname">math.</code><code class="descname">trunc</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.trunc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code></a> value <em>x</em> truncated to an
<a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a> (usually a long integer).  Uses the
<code class="docutils literal notranslate"><span class="pre">__trunc__</span></code> method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>Note that <a class="reference internal" href="#math.frexp" title="math.frexp"><code class="xref py py-func docutils literal notranslate"><span class="pre">frexp()</span></code></a> and <a class="reference internal" href="#math.modf" title="math.modf"><code class="xref py py-func docutils literal notranslate"><span class="pre">modf()</span></code></a> have a different call/return pattern
than their C equivalents: they take a single argument and return a pair of
values, rather than returning their second return value through an ‘output
parameter’ (there is no such thing in Python).</p>
<p>For the <a class="reference internal" href="#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">ceil()</span></code></a>, <a class="reference internal" href="#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code></a>, and <a class="reference internal" href="#math.modf" title="math.modf"><code class="xref py py-func docutils literal notranslate"><span class="pre">modf()</span></code></a> functions, note that <em>all</em>
floating-point numbers of sufficiently large magnitude are exact integers.
Python floats typically carry no more than 53 bits of precision (the same as the
platform C double type), in which case any float <em>x</em> with <code class="docutils literal notranslate"><span class="pre">abs(x)</span> <span class="pre">&gt;=</span> <span class="pre">2**52</span></code>
necessarily has no fractional bits.</p>
</div>
<div class="section" id="power-and-logarithmic-functions">
<h2>9.2.2. Power and logarithmic functions<a class="headerlink" href="#power-and-logarithmic-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.exp">
<code class="descclassname">math.</code><code class="descname">exp</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.exp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">e**x</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="math.expm1">
<code class="descclassname">math.</code><code class="descname">expm1</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.expm1" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">e**x</span> <span class="pre">-</span> <span class="pre">1</span></code>.  For small floats <em>x</em>, the subtraction in
<code class="docutils literal notranslate"><span class="pre">exp(x)</span> <span class="pre">-</span> <span class="pre">1</span></code> can result in a significant loss of precision; the
<a class="reference internal" href="#math.expm1" title="math.expm1"><code class="xref py py-func docutils literal notranslate"><span class="pre">expm1()</span></code></a> function provides a way to compute this quantity to
full precision:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">exp</span><span class="p">,</span> <span class="n">expm1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">exp</span><span class="p">(</span><span class="mf">1e-5</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span>  <span class="c1"># gives result accurate to 11 places</span>
<span class="go">1.0000050000069649e-05</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">expm1</span><span class="p">(</span><span class="mf">1e-5</span><span class="p">)</span>    <span class="c1"># result accurate to full precision</span>
<span class="go">1.0000050000166668e-05</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.log">
<code class="descclassname">math.</code><code class="descname">log</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>base</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#math.log" title="Permalink to this definition">¶</a></dt>
<dd><p>With one argument, return the natural logarithm of <em>x</em> (to base <em>e</em>).</p>
<p>With two arguments, return the logarithm of <em>x</em> to the given <em>base</em>,
calculated as <code class="docutils literal notranslate"><span class="pre">log(x)/log(base)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span><em>base</em> argument added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.log1p">
<code class="descclassname">math.</code><code class="descname">log1p</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.log1p" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the natural logarithm of <em>1+x</em> (base <em>e</em>). The
result is calculated in a way which is accurate for <em>x</em> near zero.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.log10">
<code class="descclassname">math.</code><code class="descname">log10</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.log10" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the base-10 logarithm of <em>x</em>.  This is usually more accurate
than <code class="docutils literal notranslate"><span class="pre">log(x,</span> <span class="pre">10)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="math.pow">
<code class="descclassname">math.</code><code class="descname">pow</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#math.pow" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">x</span></code> raised to the power <code class="docutils literal notranslate"><span class="pre">y</span></code>.  Exceptional cases follow
Annex ‘F’ of the C99 standard as far as possible.  In particular,
<code class="docutils literal notranslate"><span class="pre">pow(1.0,</span> <span class="pre">x)</span></code> and <code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">0.0)</span></code> always return <code class="docutils literal notranslate"><span class="pre">1.0</span></code>, even
when <code class="docutils literal notranslate"><span class="pre">x</span></code> is a zero or a NaN.  If both <code class="docutils literal notranslate"><span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span></code> are finite,
<code class="docutils literal notranslate"><span class="pre">x</span></code> is negative, and <code class="docutils literal notranslate"><span class="pre">y</span></code> is not an integer then <code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y)</span></code>
is undefined, and raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p>Unlike the built-in <code class="docutils literal notranslate"><span class="pre">**</span></code> operator, <a class="reference internal" href="#math.pow" title="math.pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.pow()</span></code></a> converts both
its arguments to type <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.  Use <code class="docutils literal notranslate"><span class="pre">**</span></code> or the built-in
<a class="reference internal" href="functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function for computing exact integer powers.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The outcome of <code class="docutils literal notranslate"><span class="pre">1**nan</span></code> and <code class="docutils literal notranslate"><span class="pre">nan**0</span></code> was undefined.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.sqrt">
<code class="descclassname">math.</code><code class="descname">sqrt</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.sqrt" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the square root of <em>x</em>.</p>
</dd></dl>

</div>
<div class="section" id="trigonometric-functions">
<h2>9.2.3. Trigonometric functions<a class="headerlink" href="#trigonometric-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.acos">
<code class="descclassname">math.</code><code class="descname">acos</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.acos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc cosine of <em>x</em>, in radians.</p>
</dd></dl>

<dl class="function">
<dt id="math.asin">
<code class="descclassname">math.</code><code class="descname">asin</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.asin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc sine of <em>x</em>, in radians.</p>
</dd></dl>

<dl class="function">
<dt id="math.atan">
<code class="descclassname">math.</code><code class="descname">atan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.atan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the arc tangent of <em>x</em>, in radians.</p>
</dd></dl>

<dl class="function">
<dt id="math.atan2">
<code class="descclassname">math.</code><code class="descname">atan2</code><span class="sig-paren">(</span><em>y</em>, <em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.atan2" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">atan(y</span> <span class="pre">/</span> <span class="pre">x)</span></code>, in radians. The result is between <code class="docutils literal notranslate"><span class="pre">-pi</span></code> and <code class="docutils literal notranslate"><span class="pre">pi</span></code>.
The vector in the plane from the origin to point <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code> makes this angle
with the positive X axis. The point of <a class="reference internal" href="#math.atan2" title="math.atan2"><code class="xref py py-func docutils literal notranslate"><span class="pre">atan2()</span></code></a> is that the signs of both
inputs are known to it, so it can compute the correct quadrant for the angle.
For example, <code class="docutils literal notranslate"><span class="pre">atan(1)</span></code> and <code class="docutils literal notranslate"><span class="pre">atan2(1,</span> <span class="pre">1)</span></code> are both <code class="docutils literal notranslate"><span class="pre">pi/4</span></code>, but <code class="docutils literal notranslate"><span class="pre">atan2(-1,</span>
<span class="pre">-1)</span></code> is <code class="docutils literal notranslate"><span class="pre">-3*pi/4</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="math.cos">
<code class="descclassname">math.</code><code class="descname">cos</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.cos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the cosine of <em>x</em> radians.</p>
</dd></dl>

<dl class="function">
<dt id="math.hypot">
<code class="descclassname">math.</code><code class="descname">hypot</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#math.hypot" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Euclidean norm, <code class="docutils literal notranslate"><span class="pre">sqrt(x*x</span> <span class="pre">+</span> <span class="pre">y*y)</span></code>. This is the length of the vector
from the origin to point <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="math.sin">
<code class="descclassname">math.</code><code class="descname">sin</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.sin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the sine of <em>x</em> radians.</p>
</dd></dl>

<dl class="function">
<dt id="math.tan">
<code class="descclassname">math.</code><code class="descname">tan</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.tan" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the tangent of <em>x</em> radians.</p>
</dd></dl>

</div>
<div class="section" id="angular-conversion">
<h2>9.2.4. Angular conversion<a class="headerlink" href="#angular-conversion" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.degrees">
<code class="descclassname">math.</code><code class="descname">degrees</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.degrees" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert angle <em>x</em> from radians to degrees.</p>
</dd></dl>

<dl class="function">
<dt id="math.radians">
<code class="descclassname">math.</code><code class="descname">radians</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.radians" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert angle <em>x</em> from degrees to radians.</p>
</dd></dl>

</div>
<div class="section" id="hyperbolic-functions">
<h2>9.2.5. Hyperbolic functions<a class="headerlink" href="#hyperbolic-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.acosh">
<code class="descclassname">math.</code><code class="descname">acosh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.acosh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic cosine of <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.asinh">
<code class="descclassname">math.</code><code class="descname">asinh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.asinh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic sine of <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.atanh">
<code class="descclassname">math.</code><code class="descname">atanh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.atanh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the inverse hyperbolic tangent of <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.cosh">
<code class="descclassname">math.</code><code class="descname">cosh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.cosh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic cosine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="math.sinh">
<code class="descclassname">math.</code><code class="descname">sinh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.sinh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic sine of <em>x</em>.</p>
</dd></dl>

<dl class="function">
<dt id="math.tanh">
<code class="descclassname">math.</code><code class="descname">tanh</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.tanh" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the hyperbolic tangent of <em>x</em>.</p>
</dd></dl>

</div>
<div class="section" id="special-functions">
<h2>9.2.6. Special functions<a class="headerlink" href="#special-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="math.erf">
<code class="descclassname">math.</code><code class="descname">erf</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.erf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the error function at <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.erfc">
<code class="descclassname">math.</code><code class="descname">erfc</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.erfc" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the complementary error function at <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.gamma">
<code class="descclassname">math.</code><code class="descname">gamma</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.gamma" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Gamma function at <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="math.lgamma">
<code class="descclassname">math.</code><code class="descname">lgamma</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#math.lgamma" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the natural logarithm of the absolute value of the Gamma
function at <em>x</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="constants">
<h2>9.2.7. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h2>
<dl class="data">
<dt id="math.pi">
<code class="descclassname">math.</code><code class="descname">pi</code><a class="headerlink" href="#math.pi" title="Permalink to this definition">¶</a></dt>
<dd><p>The mathematical constant π = 3.141592…, to available precision.</p>
</dd></dl>

<dl class="data">
<dt id="math.e">
<code class="descclassname">math.</code><code class="descname">e</code><a class="headerlink" href="#math.e" title="Permalink to this definition">¶</a></dt>
<dd><p>The mathematical constant e = 2.718281…, to available precision.</p>
</dd></dl>

<div class="impl-detail compound">
<p class="compound-first"><strong>CPython implementation detail:</strong> The <a class="reference internal" href="#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module consists mostly of thin wrappers around the platform C
math library functions.  Behavior in exceptional cases follows Annex F of
the C99 standard where appropriate.  The current implementation will raise
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> for invalid operations like <code class="docutils literal notranslate"><span class="pre">sqrt(-1.0)</span></code> or <code class="docutils literal notranslate"><span class="pre">log(0.0)</span></code>
(where C99 Annex F recommends signaling invalid operation or divide-by-zero),
and <a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> for results that overflow (for example,
<code class="docutils literal notranslate"><span class="pre">exp(1000.0)</span></code>).  A NaN will not be returned from any of the functions
above unless one or more of the input arguments was a NaN; in that case,
most functions will return a NaN, but (again following C99 Annex F) there
are some exceptions to this rule, for example <code class="docutils literal notranslate"><span class="pre">pow(float('nan'),</span> <span class="pre">0.0)</span></code> or
<code class="docutils literal notranslate"><span class="pre">hypot(float('nan'),</span> <span class="pre">float('inf'))</span></code>.</p>
<p class="compound-middle">Note that Python makes no effort to distinguish signaling NaNs from
quiet NaNs, and behavior for signaling NaNs remains unspecified.
Typical behavior is to treat all NaNs as though they were quiet.</p>
<div class="compound-last versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Behavior in special cases now aims to follow C99 Annex F.  In earlier
versions of Python the behavior in special cases was loosely specified.</p>
</div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a></dt>
<dd>Complex number versions of many of these functions.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a><ul>
<li><a class="reference internal" href="#number-theoretic-and-representation-functions">9.2.1. Number-theoretic and representation functions</a></li>
<li><a class="reference internal" href="#power-and-logarithmic-functions">9.2.2. Power and logarithmic functions</a></li>
<li><a class="reference internal" href="#trigonometric-functions">9.2.3. Trigonometric functions</a></li>
<li><a class="reference internal" href="#angular-conversion">9.2.4. Angular conversion</a></li>
<li><a class="reference internal" href="#hyperbolic-functions">9.2.5. Hyperbolic functions</a></li>
<li><a class="reference internal" href="#special-functions">9.2.6. Special functions</a></li>
<li><a class="reference internal" href="#constants">9.2.7. Constants</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="numbers.html"
                        title="previous chapter">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cmath.html"
                        title="next chapter">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/math.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmath.html" title="9.3. cmath — Mathematical functions for complex numbers"
             >next</a> |</li>
        <li class="right" >
          <a href="numbers.html" title="9.1. numbers — Numeric abstract base classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\x/;;html/library/md5.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14.3. md5 — MD5 message digest algorithm &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14.4. sha — SHA-1 message digest algorithm" href="sha.html" />
    <link rel="prev" title="14.2. hmac — Keyed-Hashing for Message Authentication" href="hmac.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/md5.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sha.html" title="14.4. sha — SHA-1 message digest algorithm"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="14.2. hmac — Keyed-Hashing for Message Authentication"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" accesskey="U">14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-md5">
<span id="md5-md5-message-digest-algorithm"></span><h1>14.3. <a class="reference internal" href="#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> — MD5 message digest algorithm<a class="headerlink" href="#module-md5" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.5: </span>Use the <a class="reference internal" href="hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module instead.</p>
</div>
<p id="index-0">This module implements the interface to RSA’s MD5 message digest  algorithm (see
also Internet <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1321.html"><strong>RFC 1321</strong></a>).  Its use is quite straightforward: use <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a>
to create an md5 object. You can now feed this object with arbitrary strings
using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method, and at any point you can ask it for the
<em class="dfn">digest</em> (a strong kind of 128-bit checksum, a.k.a. “fingerprint”) of the
concatenation of the strings fed to it so far using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code> method.</p>
<p>For example, to obtain the digest of the string <code class="docutils literal notranslate"><span class="pre">'Nobody</span> <span class="pre">inspects</span> <span class="pre">the</span> <span class="pre">spammish</span>
<span class="pre">repetition'</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">md5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">md5</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">&quot;Nobody inspects&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s2">&quot; the spammish repetition&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">digest</span><span class="p">()</span>
<span class="go">&#39;\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9&#39;</span>
</pre></div>
</div>
<p>More condensed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">md5</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s2">&quot;Nobody inspects the spammish repetition&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">digest</span><span class="p">()</span>
<span class="go">&#39;\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9&#39;</span>
</pre></div>
</div>
<p>The following values are provided as constants in the module and as attributes
of the md5 objects returned by <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a>:</p>
<dl class="data">
<dt id="md5.digest_size">
<code class="descclassname">md5.</code><code class="descname">digest_size</code><a class="headerlink" href="#md5.digest_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the resulting digest in bytes.  This is always <code class="docutils literal notranslate"><span class="pre">16</span></code>.</p>
</dd></dl>

<p>The md5 module provides the following functions:</p>
<dl class="function">
<dt id="md5.new">
<code class="descclassname">md5.</code><code class="descname">new</code><span class="sig-paren">(</span><span class="optional">[</span><em>arg</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#md5.new" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new md5 object.  If <em>arg</em> is present, the method call <code class="docutils literal notranslate"><span class="pre">update(arg)</span></code>
is made.</p>
</dd></dl>

<dl class="function">
<dt id="md5.md5">
<code class="descclassname">md5.</code><code class="descname">md5</code><span class="sig-paren">(</span><span class="optional">[</span><em>arg</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#md5.md5" title="Permalink to this definition">¶</a></dt>
<dd><p>For backward compatibility reasons, this is an alternative name for the
<a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a> function.</p>
</dd></dl>

<p>An md5 object has the following methods:</p>
<dl class="method">
<dt id="md5.md5.update">
<code class="descclassname">md5.</code><code class="descname">update</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#md5.md5.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the md5 object with the string <em>arg</em>.  Repeated calls are equivalent to a
single call with the concatenation of all the arguments: <code class="docutils literal notranslate"><span class="pre">m.update(a);</span>
<span class="pre">m.update(b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.update(a+b)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="md5.md5.digest">
<code class="descclassname">md5.</code><code class="descname">digest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#md5.md5.digest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the digest of the strings passed to the <a class="reference internal" href="#md5.md5.update" title="md5.md5.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> method so far.
This is a 16-byte string which may contain non-ASCII characters, including null
bytes.</p>
</dd></dl>

<dl class="method">
<dt id="md5.md5.hexdigest">
<code class="descclassname">md5.</code><code class="descname">hexdigest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#md5.md5.hexdigest" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#md5.md5.digest" title="md5.md5.digest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code></a> except the digest is returned as a string of length 32,
containing only hexadecimal digits.  This may  be used to exchange the value
safely in email or other non-binary environments.</p>
</dd></dl>

<dl class="method">
<dt id="md5.md5.copy">
<code class="descclassname">md5.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#md5.md5.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy (“clone”) of the md5 object.  This can be used to efficiently
compute the digests of strings that share a common initial substring.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="sha.html#module-sha" title="sha: NIST's secure hash algorithm, SHA. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code></a></dt>
<dd>Similar module implementing the Secure Hash Algorithm (SHA).  The SHA algorithm
is considered a more secure hash.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="hmac.html"
                        title="previous chapter">14.2. <code class="docutils literal notranslate"><span class="pre">hmac</span></code> — Keyed-Hashing for Message Authentication</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sha.html"
                        title="next chapter">14.4. <code class="docutils literal notranslate"><span class="pre">sha</span></code> — SHA-1 message digest algorithm</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/md5.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sha.html" title="14.4. sha — SHA-1 message digest algorithm"
             >next</a> |</li>
        <li class="right" >
          <a href="hmac.html" title="14.2. hmac — Keyed-Hashing for Message Authentication"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" >14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Q�;^;^html/library/mhlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.5. mhlib — Access to MH mailboxes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.6. mimetools — Tools for parsing MIME messages" href="mimetools.html" />
    <link rel="prev" title="18.4. mailbox — Manipulate mailboxes in various formats" href="mailbox.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mhlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimetools.html" title="18.6. mimetools — Tools for parsing MIME messages"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mailbox.html" title="18.4. mailbox — Manipulate mailboxes in various formats"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mhlib">
<span id="mhlib-access-to-mh-mailboxes"></span><h1>18.5. <a class="reference internal" href="#module-mhlib" title="mhlib: Manipulate MH mailboxes from Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code></a> — Access to MH mailboxes<a class="headerlink" href="#module-mhlib" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-mhlib" title="mhlib: Manipulate MH mailboxes from Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code></a> module has been removed in Python 3. Use the
<a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> instead.</p>
</div>
<p>The <a class="reference internal" href="#module-mhlib" title="mhlib: Manipulate MH mailboxes from Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code></a> module provides a Python interface to MH folders and their
contents.</p>
<p>The module contains three basic classes, <a class="reference internal" href="#mhlib.MH" title="mhlib.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a>, which represents a
particular collection of folders, <a class="reference internal" href="#mhlib.Folder" title="mhlib.Folder"><code class="xref py py-class docutils literal notranslate"><span class="pre">Folder</span></code></a>, which represents a single
folder, and <a class="reference internal" href="#mhlib.Message" title="mhlib.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>, which represents a single message.</p>
<dl class="class">
<dt id="mhlib.MH">
<em class="property">class </em><code class="descclassname">mhlib.</code><code class="descname">MH</code><span class="sig-paren">(</span><span class="optional">[</span><em>path</em><span class="optional">[</span>, <em>profile</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#mhlib.MH" title="mhlib.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> represents a collection of MH folders.</p>
</dd></dl>

<dl class="class">
<dt id="mhlib.Folder">
<em class="property">class </em><code class="descclassname">mhlib.</code><code class="descname">Folder</code><span class="sig-paren">(</span><em>mh</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#mhlib.Folder" title="mhlib.Folder"><code class="xref py py-class docutils literal notranslate"><span class="pre">Folder</span></code></a> class represents a single folder and its messages.</p>
</dd></dl>

<dl class="class">
<dt id="mhlib.Message">
<em class="property">class </em><code class="descclassname">mhlib.</code><code class="descname">Message</code><span class="sig-paren">(</span><em>folder</em>, <em>number</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Message" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#mhlib.Message" title="mhlib.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects represent individual messages in a folder.  The Message
class is derived from <a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a>.</p>
</dd></dl>

<div class="section" id="mh-objects">
<span id="id1"></span><h2>18.5.1. MH Objects<a class="headerlink" href="#mh-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#mhlib.MH" title="mhlib.MH"><code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="mhlib.MH.error">
<code class="descclassname">MH.</code><code class="descname">error</code><span class="sig-paren">(</span><em>format</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Print an error message – can be overridden.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.getprofile">
<code class="descclassname">MH.</code><code class="descname">getprofile</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.getprofile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a profile entry (<code class="docutils literal notranslate"><span class="pre">None</span></code> if not set).</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.getpath">
<code class="descclassname">MH.</code><code class="descname">getpath</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.getpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mailbox pathname.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.getcontext">
<code class="descclassname">MH.</code><code class="descname">getcontext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.getcontext" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current folder name.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.setcontext">
<code class="descclassname">MH.</code><code class="descname">setcontext</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.setcontext" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current folder name.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.listfolders">
<code class="descclassname">MH.</code><code class="descname">listfolders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.listfolders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of top-level folders.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.listallfolders">
<code class="descclassname">MH.</code><code class="descname">listallfolders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.listallfolders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all folders.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.listsubfolders">
<code class="descclassname">MH.</code><code class="descname">listsubfolders</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.listsubfolders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of direct subfolders of the given folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.listallsubfolders">
<code class="descclassname">MH.</code><code class="descname">listallsubfolders</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.listallsubfolders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all subfolders of the given folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.makefolder">
<code class="descclassname">MH.</code><code class="descname">makefolder</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.makefolder" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.deletefolder">
<code class="descclassname">MH.</code><code class="descname">deletefolder</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.deletefolder" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete a folder – must have no subfolders.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.MH.openfolder">
<code class="descclassname">MH.</code><code class="descname">openfolder</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.MH.openfolder" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new open folder object.</p>
</dd></dl>

</div>
<div class="section" id="folder-objects">
<span id="mh-folder-objects"></span><h2>18.5.2. Folder Objects<a class="headerlink" href="#folder-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#mhlib.Folder" title="mhlib.Folder"><code class="xref py py-class docutils literal notranslate"><span class="pre">Folder</span></code></a> instances represent open folders and have the following methods:</p>
<dl class="method">
<dt id="mhlib.Folder.error">
<code class="descclassname">Folder.</code><code class="descname">error</code><span class="sig-paren">(</span><em>format</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Print an error message – can be overridden.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getfullname">
<code class="descclassname">Folder.</code><code class="descname">getfullname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getfullname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the folder’s full pathname.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getsequencesfilename">
<code class="descclassname">Folder.</code><code class="descname">getsequencesfilename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getsequencesfilename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the full pathname of the folder’s sequences file.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getmessagefilename">
<code class="descclassname">Folder.</code><code class="descname">getmessagefilename</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getmessagefilename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the full pathname of message <em>n</em> of the folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.listmessages">
<code class="descclassname">Folder.</code><code class="descname">listmessages</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.listmessages" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of messages in the folder (as numbers).</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getcurrent">
<code class="descclassname">Folder.</code><code class="descname">getcurrent</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getcurrent" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current message number.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.setcurrent">
<code class="descclassname">Folder.</code><code class="descname">setcurrent</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.setcurrent" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current message number to <em>n</em>.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.parsesequence">
<code class="descclassname">Folder.</code><code class="descname">parsesequence</code><span class="sig-paren">(</span><em>seq</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.parsesequence" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse msgs syntax into list of messages.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getlast">
<code class="descclassname">Folder.</code><code class="descname">getlast</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getlast" title="Permalink to this definition">¶</a></dt>
<dd><p>Get last message, or <code class="docutils literal notranslate"><span class="pre">0</span></code> if no messages are in the folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.setlast">
<code class="descclassname">Folder.</code><code class="descname">setlast</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.setlast" title="Permalink to this definition">¶</a></dt>
<dd><p>Set last message (internal use only).</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.getsequences">
<code class="descclassname">Folder.</code><code class="descname">getsequences</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.getsequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Return dictionary of sequences in folder.  The sequence names are used  as keys,
and the values are the lists of message numbers in the sequences.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.putsequences">
<code class="descclassname">Folder.</code><code class="descname">putsequences</code><span class="sig-paren">(</span><em>dict</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.putsequences" title="Permalink to this definition">¶</a></dt>
<dd><p>Return dictionary of sequences in folder name: list.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.removemessages">
<code class="descclassname">Folder.</code><code class="descname">removemessages</code><span class="sig-paren">(</span><em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.removemessages" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove messages in list from folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.refilemessages">
<code class="descclassname">Folder.</code><code class="descname">refilemessages</code><span class="sig-paren">(</span><em>list</em>, <em>tofolder</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.refilemessages" title="Permalink to this definition">¶</a></dt>
<dd><p>Move messages in list to other folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.movemessage">
<code class="descclassname">Folder.</code><code class="descname">movemessage</code><span class="sig-paren">(</span><em>n</em>, <em>tofolder</em>, <em>ton</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.movemessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Move one message to a given destination in another folder.</p>
</dd></dl>

<dl class="method">
<dt id="mhlib.Folder.copymessage">
<code class="descclassname">Folder.</code><code class="descname">copymessage</code><span class="sig-paren">(</span><em>n</em>, <em>tofolder</em>, <em>ton</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Folder.copymessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy one message to a given destination in another folder.</p>
</dd></dl>

</div>
<div class="section" id="message-objects">
<span id="mh-message-objects"></span><h2>18.5.3. Message Objects<a class="headerlink" href="#message-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#mhlib.Message" title="mhlib.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class adds one method to those of
<a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a>:</p>
<dl class="method">
<dt id="mhlib.Message.openmessage">
<code class="descclassname">Message.</code><code class="descname">openmessage</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#mhlib.Message.openmessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new open message object (costs a file descriptor).</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a><ul>
<li><a class="reference internal" href="#mh-objects">18.5.1. MH Objects</a></li>
<li><a class="reference internal" href="#folder-objects">18.5.2. Folder Objects</a></li>
<li><a class="reference internal" href="#message-objects">18.5.3. Message Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mailbox.html"
                        title="previous chapter">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mimetools.html"
                        title="next chapter">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mhlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimetools.html" title="18.6. mimetools — Tools for parsing MIME messages"
             >next</a> |</li>
        <li class="right" >
          <a href="mailbox.html" title="18.4. mailbox — Manipulate mailboxes in various formats"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�te2�R�Rhtml/library/mimetools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.6. mimetools — Tools for parsing MIME messages &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.7. mimetypes — Map filenames to MIME types" href="mimetypes.html" />
    <link rel="prev" title="18.5. mhlib — Access to MH mailboxes" href="mhlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mimetools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimetypes.html" title="18.7. mimetypes — Map filenames to MIME types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mhlib.html" title="18.5. mhlib — Access to MH mailboxes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mimetools">
<span id="mimetools-tools-for-parsing-mime-messages"></span><h1>18.6. <a class="reference internal" href="#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a> — Tools for parsing MIME messages<a class="headerlink" href="#module-mimetools" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package should be used in preference to the <a class="reference internal" href="#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a>
module.  This module is present only to maintain backward compatibility, and
it has been removed in 3.x.</p>
</div>
<p id="index-0">This module defines a subclass of the <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module’s <a class="reference internal" href="#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>
class and a number of utility functions that are useful for the manipulation for
MIME multipart or encoded message.</p>
<p>It defines the following items:</p>
<dl class="class">
<dt id="mimetools.Message">
<em class="property">class </em><code class="descclassname">mimetools.</code><code class="descname">Message</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>seekable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the <a class="reference internal" href="#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class.  This is a subclass of the
<a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a> class, with some additional methods (see below).  The
<em>seekable</em> argument has the same meaning as for <a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="mimetools.choose_boundary">
<code class="descclassname">mimetools.</code><code class="descname">choose_boundary</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.choose_boundary" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a unique string that has a high likelihood of being usable as a part
boundary.  The string has the form <code class="docutils literal notranslate"><span class="pre">'hostipaddr.uid.pid.timestamp.random'</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="mimetools.decode">
<code class="descclassname">mimetools.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em>, <em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Read data encoded using the allowed MIME <em>encoding</em> from open file object
<em>input</em> and write the decoded data to open file object <em>output</em>.  Valid values
for <em>encoding</em> include <code class="docutils literal notranslate"><span class="pre">'base64'</span></code>, <code class="docutils literal notranslate"><span class="pre">'quoted-printable'</span></code>, <code class="docutils literal notranslate"><span class="pre">'uuencode'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'x-uuencode'</span></code>, <code class="docutils literal notranslate"><span class="pre">'uue'</span></code>, <code class="docutils literal notranslate"><span class="pre">'x-uue'</span></code>, <code class="docutils literal notranslate"><span class="pre">'7bit'</span></code>, and  <code class="docutils literal notranslate"><span class="pre">'8bit'</span></code>.  Decoding
messages encoded in <code class="docutils literal notranslate"><span class="pre">'7bit'</span></code> or <code class="docutils literal notranslate"><span class="pre">'8bit'</span></code> has no effect.  The input is simply
copied to the output.</p>
</dd></dl>

<dl class="function">
<dt id="mimetools.encode">
<code class="descclassname">mimetools.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em>, <em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Read data from open file object <em>input</em> and write it encoded using the allowed
MIME <em>encoding</em> to open file object <em>output</em>. Valid values for <em>encoding</em> are
the same as for <a class="reference internal" href="#mimetools.decode" title="mimetools.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="mimetools.copyliteral">
<code class="descclassname">mimetools.</code><code class="descname">copyliteral</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.copyliteral" title="Permalink to this definition">¶</a></dt>
<dd><p>Read lines from open file <em>input</em> until EOF and write them to open file
<em>output</em>.</p>
</dd></dl>

<dl class="function">
<dt id="mimetools.copybinary">
<code class="descclassname">mimetools.</code><code class="descname">copybinary</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.copybinary" title="Permalink to this definition">¶</a></dt>
<dd><p>Read blocks until EOF from open file <em>input</em> and write them to open file
<em>output</em>.  The block size is currently fixed at 8192.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a></dt>
<dd>Comprehensive email handling package; supersedes the <a class="reference internal" href="#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a> module.</dd>
<dt>Module <a class="reference internal" href="rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a></dt>
<dd>Provides the base class for <a class="reference internal" href="#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a>.</dd>
<dt>Module <a class="reference internal" href="multifile.html#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a></dt>
<dd>Support for reading files which contain distinct parts, such as MIME data.</dd>
<dt><a class="reference external" href="http://faqs.cs.uu.nl/na-dir/mail/mime-faq/.html">http://faqs.cs.uu.nl/na-dir/mail/mime-faq/.html</a></dt>
<dd>The MIME Frequently Asked Questions document.  For an overview of MIME, see the
answer to question 1.1 in Part 1 of this document.</dd>
</dl>
</div>
<div class="section" id="additional-methods-of-message-objects">
<span id="mimetools-message-objects"></span><h2>18.6.1. Additional Methods of Message Objects<a class="headerlink" href="#additional-methods-of-message-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class defines the following methods in addition to the
<a class="reference internal" href="rfc822.html#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a> methods:</p>
<dl class="method">
<dt id="mimetools.Message.getplist">
<code class="descclassname">Message.</code><code class="descname">getplist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.getplist" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the parameter list of the <em class="mailheader">Content-Type</em> header. This is a
list of strings.  For parameters of the form <code class="docutils literal notranslate"><span class="pre">key=value</span></code>, <em>key</em> is converted
to lower case but <em>value</em> is not.  For example, if the message contains the
header <code class="docutils literal notranslate"><span class="pre">Content-type:</span> <span class="pre">text/html;</span> <span class="pre">spam=1;</span> <span class="pre">Spam=2;</span> <span class="pre">Spam</span></code> then <a class="reference internal" href="#mimetools.Message.getplist" title="mimetools.Message.getplist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getplist()</span></code></a>
will return the Python list <code class="docutils literal notranslate"><span class="pre">['spam=1',</span> <span class="pre">'spam=2',</span> <span class="pre">'Spam']</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mimetools.Message.getparam">
<code class="descclassname">Message.</code><code class="descname">getparam</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.getparam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>value</em> of the first parameter (as returned by <a class="reference internal" href="#mimetools.Message.getplist" title="mimetools.Message.getplist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getplist()</span></code></a>) of
the form <code class="docutils literal notranslate"><span class="pre">name=value</span></code> for the given <em>name</em>.  If <em>value</em> is surrounded by
quotes of the form ‘<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>…<code class="docutils literal notranslate"><span class="pre">&gt;</span></code>’ or ‘<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>…<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>’, these are removed.</p>
</dd></dl>

<dl class="method">
<dt id="mimetools.Message.getencoding">
<code class="descclassname">Message.</code><code class="descname">getencoding</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.getencoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the encoding specified in the <em class="mailheader">Content-Transfer-Encoding</em>
message header.  If no such header exists, return <code class="docutils literal notranslate"><span class="pre">'7bit'</span></code>.  The encoding is
converted to lower case.</p>
</dd></dl>

<dl class="method">
<dt id="mimetools.Message.gettype">
<code class="descclassname">Message.</code><code class="descname">gettype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.gettype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the message type (of the form <code class="docutils literal notranslate"><span class="pre">type/subtype</span></code>) as specified in the
<em class="mailheader">Content-Type</em> header.  If no such header exists, return
<code class="docutils literal notranslate"><span class="pre">'text/plain'</span></code>.  The type is converted to lower case.</p>
</dd></dl>

<dl class="method">
<dt id="mimetools.Message.getmaintype">
<code class="descclassname">Message.</code><code class="descname">getmaintype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.getmaintype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the main type as specified in the <em class="mailheader">Content-Type</em> header.  If
no such header exists, return <code class="docutils literal notranslate"><span class="pre">'text'</span></code>.  The main type is converted to lower
case.</p>
</dd></dl>

<dl class="method">
<dt id="mimetools.Message.getsubtype">
<code class="descclassname">Message.</code><code class="descname">getsubtype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mimetools.Message.getsubtype" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the subtype as specified in the <em class="mailheader">Content-Type</em> header.  If no
such header exists, return <code class="docutils literal notranslate"><span class="pre">'plain'</span></code>.  The subtype is converted to lower case.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a><ul>
<li><a class="reference internal" href="#additional-methods-of-message-objects">18.6.1. Additional Methods of Message Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mhlib.html"
                        title="previous chapter">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mimetypes.html"
                        title="next chapter">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mimetools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimetypes.html" title="18.7. mimetypes — Map filenames to MIME types"
             >next</a> |</li>
        <li class="right" >
          <a href="mhlib.html" title="18.5. mhlib — Access to MH mailboxes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\K�x+�w�whtml/library/mimetypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.7. mimetypes — Map filenames to MIME types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.8. MimeWriter — Generic MIME file writer" href="mimewriter.html" />
    <link rel="prev" title="18.6. mimetools — Tools for parsing MIME messages" href="mimetools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mimetypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimewriter.html" title="18.8. MimeWriter — Generic MIME file writer"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mimetools.html" title="18.6. mimetools — Tools for parsing MIME messages"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mimetypes">
<span id="mimetypes-map-filenames-to-mime-types"></span><h1>18.7. <a class="reference internal" href="#module-mimetypes" title="mimetypes: Mapping of filename extensions to MIME types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetypes</span></code></a> — Map filenames to MIME types<a class="headerlink" href="#module-mimetypes" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/mimetypes.py">Lib/mimetypes.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-mimetypes" title="mimetypes: Mapping of filename extensions to MIME types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetypes</span></code></a> module converts between a filename or URL and the MIME type
associated with the filename extension.  Conversions are provided from filename
to MIME type and from MIME type to filename extension; encodings are not
supported for the latter conversion.</p>
<p>The module provides one class and a number of convenience functions. The
functions are the normal interface to this module, but some applications may be
interested in the class as well.</p>
<p>The functions described below provide the primary interface for this module.  If
the module has not been initialized, they will call <a class="reference internal" href="#mimetypes.init" title="mimetypes.init"><code class="xref py py-func docutils literal notranslate"><span class="pre">init()</span></code></a> if they rely on
the information <a class="reference internal" href="#mimetypes.init" title="mimetypes.init"><code class="xref py py-func docutils literal notranslate"><span class="pre">init()</span></code></a> sets up.</p>
<dl class="function">
<dt id="mimetypes.guess_type">
<code class="descclassname">mimetypes.</code><code class="descname">guess_type</code><span class="sig-paren">(</span><em>url</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.guess_type" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Guess the type of a file based on its filename or URL, given by <em>url</em>.  The
return value is a tuple <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">encoding)</span></code> where <em>type</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> if the
type can’t be guessed (missing or unknown suffix) or a string of the form
<code class="docutils literal notranslate"><span class="pre">'type/subtype'</span></code>, usable for a MIME <em class="mailheader">content-type</em> header.</p>
<p><em>encoding</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> for no encoding or the name of the program used to encode
(e.g. <strong class="program">compress</strong> or <strong class="program">gzip</strong>). The encoding is suitable for use
as a <em class="mailheader">Content-Encoding</em> header, <strong>not</strong> as a
<em class="mailheader">Content-Transfer-Encoding</em> header. The mappings are table driven.
Encoding suffixes are case sensitive; type suffixes are first tried case
sensitively, then case insensitively.</p>
<p>The optional <em>strict</em> argument is a flag specifying whether the list of known MIME types
is limited to only the official types <a class="reference external" href="https://www.iana.org/assignments/media-types/media-types.xhtml">registered with IANA</a>.
When <em>strict</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), only the IANA types are supported; when
<em>strict</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, some additional non-standard but commonly used MIME types
are also recognized.</p>
</dd></dl>

<dl class="function">
<dt id="mimetypes.guess_all_extensions">
<code class="descclassname">mimetypes.</code><code class="descname">guess_all_extensions</code><span class="sig-paren">(</span><em>type</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.guess_all_extensions" title="Permalink to this definition">¶</a></dt>
<dd><p>Guess the extensions for a file based on its MIME type, given by <em>type</em>. The
return value is a list of strings giving all possible filename extensions,
including the leading dot (<code class="docutils literal notranslate"><span class="pre">'.'</span></code>).  The extensions are not guaranteed to have
been associated with any particular data stream, but would be mapped to the MIME
type <em>type</em> by <a class="reference internal" href="#mimetypes.guess_type" title="mimetypes.guess_type"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_type()</span></code></a>.</p>
<p>The optional <em>strict</em> argument has the same meaning as with the <a class="reference internal" href="#mimetypes.guess_type" title="mimetypes.guess_type"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_type()</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="mimetypes.guess_extension">
<code class="descclassname">mimetypes.</code><code class="descname">guess_extension</code><span class="sig-paren">(</span><em>type</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.guess_extension" title="Permalink to this definition">¶</a></dt>
<dd><p>Guess the extension for a file based on its MIME type, given by <em>type</em>. The
return value is a string giving a filename extension, including the leading dot
(<code class="docutils literal notranslate"><span class="pre">'.'</span></code>).  The extension is not guaranteed to have been associated with any
particular data stream, but would be mapped to the MIME type <em>type</em> by
<a class="reference internal" href="#mimetypes.guess_type" title="mimetypes.guess_type"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_type()</span></code></a>.  If no extension can be guessed for <em>type</em>, <code class="docutils literal notranslate"><span class="pre">None</span></code> is
returned.</p>
<p>The optional <em>strict</em> argument has the same meaning as with the <a class="reference internal" href="#mimetypes.guess_type" title="mimetypes.guess_type"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_type()</span></code></a> function.</p>
</dd></dl>

<p>Some additional functions and data items are available for controlling the
behavior of the module.</p>
<dl class="function">
<dt id="mimetypes.init">
<code class="descclassname">mimetypes.</code><code class="descname">init</code><span class="sig-paren">(</span><em>files=None</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.init" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize the internal data structures.  If given, <em>files</em> must be a sequence
of file names which should be used to augment the default type map.  If omitted,
the file names to use are taken from <a class="reference internal" href="#mimetypes.knownfiles" title="mimetypes.knownfiles"><code class="xref py py-const docutils literal notranslate"><span class="pre">knownfiles</span></code></a>; on Windows, the
current registry settings are loaded.  Each file named in <em>files</em> or
<a class="reference internal" href="#mimetypes.knownfiles" title="mimetypes.knownfiles"><code class="xref py py-const docutils literal notranslate"><span class="pre">knownfiles</span></code></a> takes precedence over those named before it.  Calling
<a class="reference internal" href="#mimetypes.init" title="mimetypes.init"><code class="xref py py-func docutils literal notranslate"><span class="pre">init()</span></code></a> repeatedly is allowed.</p>
<p>Specifying an empty list for <em>files</em> will prevent the system defaults from
being applied: only the well-known values will be present from a built-in list.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Previously, Windows registry settings were ignored.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="mimetypes.read_mime_types">
<code class="descclassname">mimetypes.</code><code class="descname">read_mime_types</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.read_mime_types" title="Permalink to this definition">¶</a></dt>
<dd><p>Load the type map given in the file <em>filename</em>, if it exists.  The type map is
returned as a dictionary mapping filename extensions, including the leading dot
(<code class="docutils literal notranslate"><span class="pre">'.'</span></code>), to strings of the form <code class="docutils literal notranslate"><span class="pre">'type/subtype'</span></code>.  If the file <em>filename</em>
does not exist or cannot be read, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="mimetypes.add_type">
<code class="descclassname">mimetypes.</code><code class="descname">add_type</code><span class="sig-paren">(</span><em>type</em>, <em>ext</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.add_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a mapping from the MIME type <em>type</em> to the extension <em>ext</em>. When the
extension is already known, the new type will replace the old one. When the type
is already known the extension will be added to the list of known extensions.</p>
<p>When <em>strict</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), the mapping will be added to the
official MIME types, otherwise to the non-standard ones.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.inited">
<code class="descclassname">mimetypes.</code><code class="descname">inited</code><a class="headerlink" href="#mimetypes.inited" title="Permalink to this definition">¶</a></dt>
<dd><p>Flag indicating whether or not the global data structures have been initialized.
This is set to <code class="docutils literal notranslate"><span class="pre">True</span></code> by <a class="reference internal" href="#mimetypes.init" title="mimetypes.init"><code class="xref py py-func docutils literal notranslate"><span class="pre">init()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.knownfiles">
<code class="descclassname">mimetypes.</code><code class="descname">knownfiles</code><a class="headerlink" href="#mimetypes.knownfiles" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">List of type map file names commonly installed.  These files are typically named
<code class="file docutils literal notranslate"><span class="pre">mime.types</span></code> and are installed in different locations by different
packages.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.suffix_map">
<code class="descclassname">mimetypes.</code><code class="descname">suffix_map</code><a class="headerlink" href="#mimetypes.suffix_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping suffixes to suffixes.  This is used to allow recognition of
encoded files for which the encoding and the type are indicated by the same
extension.  For example, the <code class="file docutils literal notranslate"><span class="pre">.tgz</span></code> extension is mapped to <code class="file docutils literal notranslate"><span class="pre">.tar.gz</span></code>
to allow the encoding and type to be recognized separately.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.encodings_map">
<code class="descclassname">mimetypes.</code><code class="descname">encodings_map</code><a class="headerlink" href="#mimetypes.encodings_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping filename extensions to encoding types.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.types_map">
<code class="descclassname">mimetypes.</code><code class="descname">types_map</code><a class="headerlink" href="#mimetypes.types_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping filename extensions to MIME types.</p>
</dd></dl>

<dl class="data">
<dt id="mimetypes.common_types">
<code class="descclassname">mimetypes.</code><code class="descname">common_types</code><a class="headerlink" href="#mimetypes.common_types" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping filename extensions to non-standard, but commonly found MIME
types.</p>
</dd></dl>

<p>An example usage of the module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mimetypes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mimetypes</span><span class="o">.</span><span class="n">init</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mimetypes</span><span class="o">.</span><span class="n">knownfiles</span>
<span class="go">[&#39;/etc/mime.types&#39;, &#39;/etc/httpd/mime.types&#39;, ... ]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mimetypes</span><span class="o">.</span><span class="n">suffix_map</span><span class="p">[</span><span class="s1">&#39;.tgz&#39;</span><span class="p">]</span>
<span class="go">&#39;.tar.gz&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mimetypes</span><span class="o">.</span><span class="n">encodings_map</span><span class="p">[</span><span class="s1">&#39;.gz&#39;</span><span class="p">]</span>
<span class="go">&#39;gzip&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mimetypes</span><span class="o">.</span><span class="n">types_map</span><span class="p">[</span><span class="s1">&#39;.tgz&#39;</span><span class="p">]</span>
<span class="go">&#39;application/x-tar-gz&#39;</span>
</pre></div>
</div>
<div class="section" id="mimetypes-objects">
<span id="id1"></span><h2>18.7.1. MimeTypes Objects<a class="headerlink" href="#mimetypes-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#mimetypes.MimeTypes" title="mimetypes.MimeTypes"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeTypes</span></code></a> class may be useful for applications which may want more
than one MIME-type database; it provides an interface similar to the one of the
<a class="reference internal" href="#module-mimetypes" title="mimetypes: Mapping of filename extensions to MIME types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetypes</span></code></a> module.</p>
<dl class="class">
<dt id="mimetypes.MimeTypes">
<em class="property">class </em><code class="descclassname">mimetypes.</code><code class="descname">MimeTypes</code><span class="sig-paren">(</span><em>filenames=()</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes" title="Permalink to this definition">¶</a></dt>
<dd><p>This class represents a MIME-types database.  By default, it provides access to
the same database as the rest of this module. The initial database is a copy of
that provided by the module, and may be extended by loading additional
<code class="file docutils literal notranslate"><span class="pre">mime.types</span></code>-style files into the database using the <a class="reference internal" href="#mimetypes.MimeTypes.read" title="mimetypes.MimeTypes.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> or
<a class="reference internal" href="#mimetypes.MimeTypes.readfp" title="mimetypes.MimeTypes.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a> methods.  The mapping dictionaries may also be cleared before
loading additional data if the default data is not desired.</p>
<p>The optional <em>filenames</em> parameter can be used to cause additional files to be
loaded “on top” of the default database.</p>
<dl class="attribute">
<dt id="mimetypes.MimeTypes.suffix_map">
<code class="descname">suffix_map</code><a class="headerlink" href="#mimetypes.MimeTypes.suffix_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping suffixes to suffixes.  This is used to allow recognition of
encoded files for which the encoding and the type are indicated by the same
extension.  For example, the <code class="file docutils literal notranslate"><span class="pre">.tgz</span></code> extension is mapped to <code class="file docutils literal notranslate"><span class="pre">.tar.gz</span></code>
to allow the encoding and type to be recognized separately.  This is initially a
copy of the global <a class="reference internal" href="#mimetypes.suffix_map" title="mimetypes.suffix_map"><code class="xref py py-data docutils literal notranslate"><span class="pre">suffix_map</span></code></a> defined in the module.</p>
</dd></dl>

<dl class="attribute">
<dt id="mimetypes.MimeTypes.encodings_map">
<code class="descname">encodings_map</code><a class="headerlink" href="#mimetypes.MimeTypes.encodings_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping filename extensions to encoding types.  This is initially a
copy of the global <a class="reference internal" href="#mimetypes.encodings_map" title="mimetypes.encodings_map"><code class="xref py py-data docutils literal notranslate"><span class="pre">encodings_map</span></code></a> defined in the module.</p>
</dd></dl>

<dl class="attribute">
<dt id="mimetypes.MimeTypes.types_map">
<code class="descname">types_map</code><a class="headerlink" href="#mimetypes.MimeTypes.types_map" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple containing two dictionaries, mapping filename extensions to MIME types:
the first dictionary is for the non-standards types and the second one is for
the standard types. They are initialized by <a class="reference internal" href="#mimetypes.common_types" title="mimetypes.common_types"><code class="xref py py-data docutils literal notranslate"><span class="pre">common_types</span></code></a> and
<a class="reference internal" href="#mimetypes.types_map" title="mimetypes.types_map"><code class="xref py py-data docutils literal notranslate"><span class="pre">types_map</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="mimetypes.MimeTypes.types_map_inv">
<code class="descname">types_map_inv</code><a class="headerlink" href="#mimetypes.MimeTypes.types_map_inv" title="Permalink to this definition">¶</a></dt>
<dd><p>Tuple containing two dictionaries, mapping MIME types to a list of filename
extensions: the first dictionary is for the non-standards types and the
second one is for the standard types. They are initialized by
<a class="reference internal" href="#mimetypes.common_types" title="mimetypes.common_types"><code class="xref py py-data docutils literal notranslate"><span class="pre">common_types</span></code></a> and <a class="reference internal" href="#mimetypes.types_map" title="mimetypes.types_map"><code class="xref py py-data docutils literal notranslate"><span class="pre">types_map</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.guess_extension">
<code class="descname">guess_extension</code><span class="sig-paren">(</span><em>type</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.guess_extension" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#mimetypes.guess_extension" title="mimetypes.guess_extension"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_extension()</span></code></a> function, using the tables stored as part
of the object.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.guess_type">
<code class="descname">guess_type</code><span class="sig-paren">(</span><em>url</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.guess_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#mimetypes.guess_type" title="mimetypes.guess_type"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_type()</span></code></a> function, using the tables stored as part of
the object.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.guess_all_extensions">
<code class="descname">guess_all_extensions</code><span class="sig-paren">(</span><em>type</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.guess_all_extensions" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#mimetypes.guess_all_extensions" title="mimetypes.guess_all_extensions"><code class="xref py py-func docutils literal notranslate"><span class="pre">guess_all_extensions()</span></code></a> function, using the tables stored
as part of the object.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.read">
<code class="descname">read</code><span class="sig-paren">(</span><em>filename</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Load MIME information from a file named <em>filename</em>.  This uses <a class="reference internal" href="#mimetypes.MimeTypes.readfp" title="mimetypes.MimeTypes.readfp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readfp()</span></code></a> to
parse the file.</p>
<p>If <em>strict</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, information will be added to list of standard types,
else to the list of non-standard types.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.readfp">
<code class="descname">readfp</code><span class="sig-paren">(</span><em>fp</em>, <em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.readfp" title="Permalink to this definition">¶</a></dt>
<dd><p>Load MIME type information from an open file <em>fp</em>.  The file must have the format of
the standard <code class="file docutils literal notranslate"><span class="pre">mime.types</span></code> files.</p>
<p>If <em>strict</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, information will be added to the list of standard
types, else to the list of non-standard types.</p>
</dd></dl>

<dl class="method">
<dt id="mimetypes.MimeTypes.read_windows_registry">
<code class="descname">read_windows_registry</code><span class="sig-paren">(</span><em>strict=True</em><span class="sig-paren">)</span><a class="headerlink" href="#mimetypes.MimeTypes.read_windows_registry" title="Permalink to this definition">¶</a></dt>
<dd><p>Load MIME type information from the Windows registry.  Availability: Windows.</p>
<p>If <em>strict</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, information will be added to the list of standard
types, else to the list of non-standard types.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a><ul>
<li><a class="reference internal" href="#mimetypes-objects">18.7.1. MimeTypes Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mimetools.html"
                        title="previous chapter">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mimewriter.html"
                        title="next chapter">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mimetypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimewriter.html" title="18.8. MimeWriter — Generic MIME file writer"
             >next</a> |</li>
        <li class="right" >
          <a href="mimetools.html" title="18.6. mimetools — Tools for parsing MIME messages"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\]~�y�>�>html/library/mimewriter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.8. MimeWriter — Generic MIME file writer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.9. mimify — MIME processing of mail messages" href="mimify.html" />
    <link rel="prev" title="18.7. mimetypes — Map filenames to MIME types" href="mimetypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mimewriter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimify.html" title="18.9. mimify — MIME processing of mail messages"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mimetypes.html" title="18.7. mimetypes — Map filenames to MIME types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-MimeWriter">
<span id="mimewriter-generic-mime-file-writer"></span><h1>18.8. <a class="reference internal" href="#module-MimeWriter" title="MimeWriter: Write MIME format files. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> — Generic MIME file writer<a class="headerlink" href="#module-MimeWriter" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package should be used in preference to the <a class="reference internal" href="#module-MimeWriter" title="MimeWriter: Write MIME format files. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MimeWriter</span></code></a>
module.  This module is present only to maintain backward compatibility.</p>
</div>
<p>This module defines the class <a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a>.  The <a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a>
class implements a basic formatter for creating MIME multi-part files.  It
doesn’t seek around the output file nor does it use large amounts of buffer
space. You must write the parts out in the order that they should occur in the
final file. <a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> does buffer the headers you add, allowing you
to rearrange their order.</p>
<dl class="class">
<dt id="MimeWriter.MimeWriter">
<em class="property">class </em><code class="descclassname">MimeWriter.</code><code class="descname">MimeWriter</code><span class="sig-paren">(</span><em>fp</em><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the <a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> class.  The only argument
passed, <em>fp</em>, is a file object to be used for writing. Note that a
<a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object could also be used.</p>
</dd></dl>

<div class="section" id="mimewriter-objects">
<span id="id1"></span><h2>18.8.1. MimeWriter Objects<a class="headerlink" href="#mimewriter-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="MimeWriter.MimeWriter.addheader">
<code class="descclassname">MimeWriter.</code><code class="descname">addheader</code><span class="sig-paren">(</span><em>key</em>, <em>value</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.addheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a header line to the MIME message. The <em>key</em> is the name of the header,
where the <em>value</em> obviously provides the value of the header. The optional
argument <em>prefix</em> determines where the header  is inserted; <code class="docutils literal notranslate"><span class="pre">0</span></code> means append
at the end, <code class="docutils literal notranslate"><span class="pre">1</span></code> is insert at the start. The default is to append.</p>
</dd></dl>

<dl class="method">
<dt id="MimeWriter.MimeWriter.flushheaders">
<code class="descclassname">MimeWriter.</code><code class="descname">flushheaders</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.flushheaders" title="Permalink to this definition">¶</a></dt>
<dd><p>Causes all headers accumulated so far to be written out (and forgotten). This is
useful if you don’t need a body part at all, e.g. for a subpart of type
<em class="mimetype">message/rfc822</em> that’s (mis)used to store some header-like
information.</p>
</dd></dl>

<dl class="method">
<dt id="MimeWriter.MimeWriter.startbody">
<code class="descclassname">MimeWriter.</code><code class="descname">startbody</code><span class="sig-paren">(</span><em>ctype</em><span class="optional">[</span>, <em>plist</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.startbody" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a file-like object which can be used to write to the body of the
message.  The content-type is set to the provided <em>ctype</em>, and the optional
parameter <em>plist</em> provides additional parameters for the content-type
declaration. <em>prefix</em> functions as in <a class="reference internal" href="#MimeWriter.MimeWriter.addheader" title="MimeWriter.MimeWriter.addheader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addheader()</span></code></a> except that the default
is to insert at the start.</p>
</dd></dl>

<dl class="method">
<dt id="MimeWriter.MimeWriter.startmultipartbody">
<code class="descclassname">MimeWriter.</code><code class="descname">startmultipartbody</code><span class="sig-paren">(</span><em>subtype</em><span class="optional">[</span>, <em>boundary</em><span class="optional">[</span>, <em>plist</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.startmultipartbody" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a file-like object which can be used to write to the body of the
message.  Additionally, this method initializes the multi-part code, where
<em>subtype</em> provides the multipart subtype, <em>boundary</em> may provide a user-defined
boundary specification, and <em>plist</em> provides optional parameters for the
subtype. <em>prefix</em> functions as in <a class="reference internal" href="#MimeWriter.MimeWriter.startbody" title="MimeWriter.MimeWriter.startbody"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startbody()</span></code></a>.  Subparts should be created
using <a class="reference internal" href="#MimeWriter.MimeWriter.nextpart" title="MimeWriter.MimeWriter.nextpart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">nextpart()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="MimeWriter.MimeWriter.nextpart">
<code class="descclassname">MimeWriter.</code><code class="descname">nextpart</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.nextpart" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new instance of <a class="reference internal" href="#MimeWriter.MimeWriter" title="MimeWriter.MimeWriter"><code class="xref py py-class docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> which represents an individual
part in a multipart message.  This may be used to write the  part as well as
used for creating recursively complex multipart messages. The message must first
be initialized with <a class="reference internal" href="#MimeWriter.MimeWriter.startmultipartbody" title="MimeWriter.MimeWriter.startmultipartbody"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startmultipartbody()</span></code></a> before using <a class="reference internal" href="#MimeWriter.MimeWriter.nextpart" title="MimeWriter.MimeWriter.nextpart"><code class="xref py py-meth docutils literal notranslate"><span class="pre">nextpart()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="MimeWriter.MimeWriter.lastpart">
<code class="descclassname">MimeWriter.</code><code class="descname">lastpart</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#MimeWriter.MimeWriter.lastpart" title="Permalink to this definition">¶</a></dt>
<dd><p>This is used to designate the last part of a multipart message, and should
<em>always</em> be used when writing multipart messages.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a><ul>
<li><a class="reference internal" href="#mimewriter-objects">18.8.1. MimeWriter Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mimetypes.html"
                        title="previous chapter">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mimify.html"
                        title="next chapter">18.9. <code class="docutils literal notranslate"><span class="pre">mimify</span></code> — MIME processing of mail messages</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mimewriter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mimify.html" title="18.9. mimify — MIME processing of mail messages"
             >next</a> |</li>
        <li class="right" >
          <a href="mimetypes.html" title="18.7. mimetypes — Map filenames to MIME types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����;�;html/library/mimify.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.9. mimify — MIME processing of mail messages &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.10. multifile — Support for files containing distinct parts" href="multifile.html" />
    <link rel="prev" title="18.8. MimeWriter — Generic MIME file writer" href="mimewriter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mimify.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multifile.html" title="18.10. multifile — Support for files containing distinct parts"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mimewriter.html" title="18.8. MimeWriter — Generic MIME file writer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mimify">
<span id="mimify-mime-processing-of-mail-messages"></span><h1>18.9. <a class="reference internal" href="#module-mimify" title="mimify: Mimification and unmimification of mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code></a> — MIME processing of mail messages<a class="headerlink" href="#module-mimify" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package should be used in preference to the <a class="reference internal" href="#module-mimify" title="mimify: Mimification and unmimification of mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code></a>
module.  This module is present only to maintain backward compatibility.</p>
</div>
<p>The <a class="reference internal" href="#module-mimify" title="mimify: Mimification and unmimification of mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code></a> module defines two functions to convert mail messages to and
from MIME format.  The mail message can be either a simple message or a
so-called multipart message.  Each part is treated separately. Mimifying (a part
of) a message entails encoding the message as quoted-printable if it contains
any characters that cannot be represented using 7-bit ASCII.  Unmimifying (a
part of) a message entails undoing the quoted-printable encoding.  Mimify and
unmimify are especially useful when a message has to be edited before being
sent.  Typical use would be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">unmimify</span> <span class="n">message</span>
<span class="n">edit</span> <span class="n">message</span>
<span class="n">mimify</span> <span class="n">message</span>
<span class="n">send</span> <span class="n">message</span>
</pre></div>
</div>
<p>The modules defines the following user-callable functions and user-settable
variables:</p>
<dl class="function">
<dt id="mimify.mimify">
<code class="descclassname">mimify.</code><code class="descname">mimify</code><span class="sig-paren">(</span><em>infile</em>, <em>outfile</em><span class="sig-paren">)</span><a class="headerlink" href="#mimify.mimify" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the message in <em>infile</em> to <em>outfile</em>, converting parts to quoted-printable
and adding MIME mail headers when necessary. <em>infile</em> and <em>outfile</em> can be file
objects (actually, any object that has a <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method (for <em>infile</em>)
or a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method (for <em>outfile</em>)) or strings naming the files. If
<em>infile</em> and <em>outfile</em> are both strings, they may have the same value.</p>
</dd></dl>

<dl class="function">
<dt id="mimify.unmimify">
<code class="descclassname">mimify.</code><code class="descname">unmimify</code><span class="sig-paren">(</span><em>infile</em>, <em>outfile</em><span class="optional">[</span>, <em>decode_base64</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mimify.unmimify" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the message in <em>infile</em> to <em>outfile</em>, decoding all quoted-printable parts.
<em>infile</em> and <em>outfile</em> can be file objects (actually, any object that has a
<a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method (for <em>infile</em>) or a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method (for
<em>outfile</em>)) or strings naming the files.  If <em>infile</em> and <em>outfile</em> are both
strings, they may have the same value. If the <em>decode_base64</em> argument is
provided and tests true, any parts that are coded in the base64 encoding are
decoded as well.</p>
</dd></dl>

<dl class="function">
<dt id="mimify.mime_decode_header">
<code class="descclassname">mimify.</code><code class="descname">mime_decode_header</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#mimify.mime_decode_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a decoded version of the encoded header line in <em>line</em>. This only
supports the ISO 8859-1 charset (Latin-1).</p>
</dd></dl>

<dl class="function">
<dt id="mimify.mime_encode_header">
<code class="descclassname">mimify.</code><code class="descname">mime_encode_header</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#mimify.mime_encode_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a MIME-encoded version of the header line in <em>line</em>.</p>
</dd></dl>

<dl class="data">
<dt id="mimify.MAXLEN">
<code class="descclassname">mimify.</code><code class="descname">MAXLEN</code><a class="headerlink" href="#mimify.MAXLEN" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, a part will be encoded as quoted-printable when it contains any
non-ASCII characters (characters with the 8th bit set), or if there are any
lines longer than <a class="reference internal" href="#mimify.MAXLEN" title="mimify.MAXLEN"><code class="xref py py-const docutils literal notranslate"><span class="pre">MAXLEN</span></code></a> characters (default value 200).</p>
</dd></dl>

<dl class="data">
<dt id="mimify.CHARSET">
<code class="descclassname">mimify.</code><code class="descname">CHARSET</code><a class="headerlink" href="#mimify.CHARSET" title="Permalink to this definition">¶</a></dt>
<dd><p>When not specified in the mail headers, a character set must be filled in.  The
string used is stored in <a class="reference internal" href="#mimify.CHARSET" title="mimify.CHARSET"><code class="xref py py-const docutils literal notranslate"><span class="pre">CHARSET</span></code></a>, and the default value is ISO-8859-1
(also known as Latin1 (latin-one)).</p>
</dd></dl>

<p>This module can also be used from the command line.  Usage is as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mimify</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">e</span> <span class="p">[</span><span class="o">-</span><span class="n">l</span> <span class="n">length</span><span class="p">]</span> <span class="p">[</span><span class="n">infile</span> <span class="p">[</span><span class="n">outfile</span><span class="p">]]</span>
<span class="n">mimify</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">d</span> <span class="p">[</span><span class="o">-</span><span class="n">b</span><span class="p">]</span> <span class="p">[</span><span class="n">infile</span> <span class="p">[</span><span class="n">outfile</span><span class="p">]]</span>
</pre></div>
</div>
<p>to encode (mimify) and decode (unmimify) respectively.  <em>infile</em> defaults to
standard input, <em>outfile</em> defaults to standard output. The same file can be
specified for input and output.</p>
<p>If the <strong>-l</strong> option is given when encoding, if there are any lines longer than
the specified <em>length</em>, the containing part will be encoded.</p>
<p>If the <strong>-b</strong> option is given when decoding, any base64 parts will be decoded as
well.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="quopri.html#module-quopri" title="quopri: Encode and decode files using the MIME quoted-printable encoding."><code class="xref py py-mod docutils literal notranslate"><span class="pre">quopri</span></code></a></dt>
<dd>Encode and decode MIME quoted-printable files.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="mimewriter.html"
                        title="previous chapter">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="multifile.html"
                        title="next chapter">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mimify.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="multifile.html" title="18.10. multifile — Support for files containing distinct parts"
             >next</a> |</li>
        <li class="right" >
          <a href="mimewriter.html" title="18.8. MimeWriter — Generic MIME file writer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�,�|5353html/library/miniaeframe.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>38.5. MiniAEFrame — Open Scripting Architecture server support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39. SGI IRIX Specific Services" href="sgi.html" />
    <link rel="prev" title="38.4. aetypes — AppleEvent objects" href="aetypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/miniaeframe.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sgi.html" title="39. SGI IRIX Specific Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="aetypes.html" title="38.4. aetypes — AppleEvent objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" accesskey="U">38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-MiniAEFrame">
<span id="miniaeframe-open-scripting-architecture-server-support"></span><h1>38.5. <a class="reference internal" href="#module-MiniAEFrame" title="MiniAEFrame: Support to act as an Open Scripting Architecture (OSA) server (&quot;Apple Events&quot;). (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code></a> — Open Scripting Architecture server support<a class="headerlink" href="#module-MiniAEFrame" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The module <a class="reference internal" href="#module-MiniAEFrame" title="MiniAEFrame: Support to act as an Open Scripting Architecture (OSA) server (&quot;Apple Events&quot;). (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code></a> provides a framework for an application that can
function as an Open Scripting Architecture  (OSA) server, i.e. receive and
process AppleEvents. It can be used in conjunction with <a class="reference internal" href="framework.html#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a> or
standalone. As an example, it is used in <strong class="program">PythonCGISlave</strong>.</p>
<p>The <a class="reference internal" href="#module-MiniAEFrame" title="MiniAEFrame: Support to act as an Open Scripting Architecture (OSA) server (&quot;Apple Events&quot;). (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code></a> module defines the following classes:</p>
<dl class="class">
<dt id="MiniAEFrame.AEServer">
<em class="property">class </em><code class="descclassname">MiniAEFrame.</code><code class="descname">AEServer</code><a class="headerlink" href="#MiniAEFrame.AEServer" title="Permalink to this definition">¶</a></dt>
<dd><p>A class that handles AppleEvent dispatch. Your application should subclass this
class together with either <a class="reference internal" href="#MiniAEFrame.MiniApplication" title="MiniAEFrame.MiniApplication"><code class="xref py py-class docutils literal notranslate"><span class="pre">MiniApplication</span></code></a> or
<a class="reference internal" href="framework.html#FrameWork.Application" title="FrameWork.Application"><code class="xref py py-class docutils literal notranslate"><span class="pre">FrameWork.Application</span></code></a>. Your <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method should call the
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method for both classes.</p>
</dd></dl>

<dl class="class">
<dt id="MiniAEFrame.MiniApplication">
<em class="property">class </em><code class="descclassname">MiniAEFrame.</code><code class="descname">MiniApplication</code><a class="headerlink" href="#MiniAEFrame.MiniApplication" title="Permalink to this definition">¶</a></dt>
<dd><p>A class that is more or less compatible with <a class="reference internal" href="framework.html#FrameWork.Application" title="FrameWork.Application"><code class="xref py py-class docutils literal notranslate"><span class="pre">FrameWork.Application</span></code></a> but
with less functionality. Its event loop supports the apple menu, command-dot and
AppleEvents; other events are passed on to the Python interpreter and/or Sioux.
Useful if your application wants to use <a class="reference internal" href="#MiniAEFrame.AEServer" title="MiniAEFrame.AEServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">AEServer</span></code></a> but does not provide
its own windows, etc.</p>
</dd></dl>

<div class="section" id="aeserver-objects">
<span id="id1"></span><h2>38.5.1. AEServer Objects<a class="headerlink" href="#aeserver-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="MiniAEFrame.AEServer.installaehandler">
<code class="descclassname">AEServer.</code><code class="descname">installaehandler</code><span class="sig-paren">(</span><em>classe</em>, <em>type</em>, <em>callback</em><span class="sig-paren">)</span><a class="headerlink" href="#MiniAEFrame.AEServer.installaehandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Installs an AppleEvent handler. <em>classe</em> and <em>type</em> are the four-character OSA
Class and Type designators, <code class="docutils literal notranslate"><span class="pre">'****'</span></code> wildcards are allowed. When a matching
AppleEvent is received the parameters are decoded and your callback is invoked.</p>
</dd></dl>

<dl class="method">
<dt id="MiniAEFrame.AEServer.callback">
<code class="descclassname">AEServer.</code><code class="descname">callback</code><span class="sig-paren">(</span><em>_object</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#MiniAEFrame.AEServer.callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Your callback is called with the OSA Direct Object as first positional
parameter. The other parameters are passed as keyword arguments, with the
4-character designator as name. Three extra keyword parameters are passed:
<code class="docutils literal notranslate"><span class="pre">_class</span></code> and <code class="docutils literal notranslate"><span class="pre">_type</span></code> are the Class and Type designators and <code class="docutils literal notranslate"><span class="pre">_attributes</span></code>
is a dictionary with the AppleEvent attributes.</p>
<p>The return value of your method is packed with <a class="reference internal" href="aetools.html#aetools.packevent" title="aetools.packevent"><code class="xref py py-func docutils literal notranslate"><span class="pre">aetools.packevent()</span></code></a> and
sent as reply.</p>
</dd></dl>

<p>Note that there are some serious problems with the current design. AppleEvents
which have non-identifier 4-character designators for arguments are not
implementable, and it is not possible to return an error to the originator. This
will be addressed in a future release.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a><ul>
<li><a class="reference internal" href="#aeserver-objects">38.5.1. AEServer Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="aetypes.html"
                        title="previous chapter">38.4. <code class="docutils literal notranslate"><span class="pre">aetypes</span></code> — AppleEvent objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sgi.html"
                        title="next chapter">39. SGI IRIX Specific Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/miniaeframe.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sgi.html" title="39. SGI IRIX Specific Services"
             >next</a> |</li>
        <li class="right" >
          <a href="aetypes.html" title="38.4. aetypes — AppleEvent objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="macosa.html" >38. MacPython OSA Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�A/�DDhtml/library/misc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>34. Miscellaneous Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="34.1. formatter — Generic output formatting" href="formatter.html" />
    <link rel="prev" title="33. Python compiler package" href="compiler.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/misc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="formatter.html" title="34.1. formatter — Generic output formatting"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="compiler.html" title="33. Python compiler package"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="miscellaneous-services">
<span id="misc"></span><h1>34. Miscellaneous Services<a class="headerlink" href="#miscellaneous-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide miscellaneous services that are
available in all Python versions.  Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="formatter.html">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a><ul>
<li class="toctree-l2"><a class="reference internal" href="formatter.html#the-formatter-interface">34.1.1. The Formatter Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="formatter.html#formatter-implementations">34.1.2. Formatter Implementations</a></li>
<li class="toctree-l2"><a class="reference internal" href="formatter.html#the-writer-interface">34.1.3. The Writer Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="formatter.html#writer-implementations">34.1.4. Writer Implementations</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="compiler.html"
                        title="previous chapter">33. Python compiler package</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="formatter.html"
                        title="next chapter">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/misc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="formatter.html" title="34.1. formatter — Generic output formatting"
             >next</a> |</li>
        <li class="right" >
          <a href="compiler.html" title="33. Python compiler package"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Lz�>b%b%html/library/mm.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21. Multimedia Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.1. audioop — Manipulate raw audio data" href="audioop.html" />
    <link rel="prev" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server" href="docxmlrpcserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mm.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="audioop.html" title="21.1. audioop — Manipulate raw audio data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="docxmlrpcserver.html" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="multimedia-services">
<span id="mmedia"></span><h1>21. Multimedia Services<a class="headerlink" href="#multimedia-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter implement various algorithms or interfaces
that are mainly useful for multimedia applications.  They are available at the
discretion of the installation.  Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="audioop.html">21.1. <code class="docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></li>
<li class="toctree-l1"><a class="reference internal" href="imageop.html">21.2. <code class="docutils literal notranslate"><span class="pre">imageop</span></code> — Manipulate raw image data</a></li>
<li class="toctree-l1"><a class="reference internal" href="aifc.html">21.3. <code class="docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></li>
<li class="toctree-l1"><a class="reference internal" href="sunau.html">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sunau.html#au-read-objects">21.4.1. AU_read Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="sunau.html#au-write-objects">21.4.2. AU_write Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="wave.html">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="wave.html#wave-read-objects">21.5.1. Wave_read Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="wave.html#wave-write-objects">21.5.2. Wave_write Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="chunk.html">21.6. <code class="docutils literal notranslate"><span class="pre">chunk</span></code> — Read IFF chunked data</a></li>
<li class="toctree-l1"><a class="reference internal" href="colorsys.html">21.7. <code class="docutils literal notranslate"><span class="pre">colorsys</span></code> — Conversions between color systems</a></li>
<li class="toctree-l1"><a class="reference internal" href="imghdr.html">21.8. <code class="docutils literal notranslate"><span class="pre">imghdr</span></code> — Determine the type of an image</a></li>
<li class="toctree-l1"><a class="reference internal" href="sndhdr.html">21.9. <code class="docutils literal notranslate"><span class="pre">sndhdr</span></code> — Determine type of sound file</a></li>
<li class="toctree-l1"><a class="reference internal" href="ossaudiodev.html">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ossaudiodev.html#audio-device-objects">21.10.1. Audio Device Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="ossaudiodev.html#mixer-device-objects">21.10.2. Mixer Device Objects</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="docxmlrpcserver.html"
                        title="previous chapter">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="audioop.html"
                        title="next chapter">21.1. <code class="docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mm.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="audioop.html" title="21.1. audioop — Manipulate raw audio data"
             >next</a> |</li>
        <li class="right" >
          <a href="docxmlrpcserver.html" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\!�^�pxpxhtml/library/mmap.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.7. mmap — Memory-mapped file support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.8. readline — GNU readline interface" href="readline.html" />
    <link rel="prev" title="16.6. multiprocessing — Process-based “threading” interface" href="multiprocessing.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mmap.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="readline.html" title="16.8. readline — GNU readline interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="16.6. multiprocessing — Process-based “threading” interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mmap">
<span id="mmap-memory-mapped-file-support"></span><h1>16.7. <a class="reference internal" href="#module-mmap" title="mmap: Interface to memory-mapped files for Unix and Windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mmap</span></code></a> — Memory-mapped file support<a class="headerlink" href="#module-mmap" title="Permalink to this headline">¶</a></h1>
<p>Memory-mapped file objects behave like both strings and like file objects.
Unlike normal string objects, however, these are mutable.  You can use mmap
objects in most places where strings are expected; for example, you can use
the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module to search through a memory-mapped file.  Since they’re
mutable, you can change a single character by doing <code class="docutils literal notranslate"><span class="pre">obj[index]</span> <span class="pre">=</span> <span class="pre">'a'</span></code>, or
change a substring by assigning to a slice: <code class="docutils literal notranslate"><span class="pre">obj[i1:i2]</span> <span class="pre">=</span> <span class="pre">'...'</span></code>.  You can
also read and write data starting at the current file position, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code> through the file to different positions.</p>
<p>A memory-mapped file is created by the <a class="reference internal" href="#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a> constructor, which is
different on Unix and on Windows.  In either case you must provide a file
descriptor for a file opened for update. If you wish to map an existing Python
file object, use its <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> method to obtain the correct value for the
<em>fileno</em> parameter.  Otherwise, you can open the file using the
<a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> function, which returns a file descriptor directly (the file
still needs to be closed when done).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you want to create a memory-mapping for a writable, buffered file, you
should <a class="reference internal" href="io.html#io.IOBase.flush" title="io.IOBase.flush"><code class="xref py py-func docutils literal notranslate"><span class="pre">flush()</span></code></a> the file first.  This is necessary to ensure
that local modifications to the buffers are actually available to the
mapping.</p>
</div>
<p>For both the Unix and Windows versions of the constructor, <em>access</em> may be
specified as an optional keyword parameter. <em>access</em> accepts one of three
values: <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_WRITE</span></code>, or <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_COPY</span></code>
to specify read-only, write-through or copy-on-write memory respectively.
<em>access</em> can be used on both Unix and Windows.  If <em>access</em> is not specified,
Windows mmap returns a write-through mapping.  The initial memory values for
all three access types are taken from the specified file.  Assignment to an
<code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code> memory map raises a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.
Assignment to an <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_WRITE</span></code> memory map affects both memory and the
underlying file.  Assignment to an <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_COPY</span></code> memory map affects
memory but does not update the underlying file.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>To map anonymous memory, -1 should be passed as the fileno along with the
length.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>mmap.mmap has formerly been a factory function creating mmap objects. Now
mmap.mmap is the class itself.</p>
</div>
<dl class="class">
<dt id="mmap.mmap">
<em class="property">class </em><code class="descclassname">mmap.</code><code class="descname">mmap</code><span class="sig-paren">(</span><em>fileno</em>, <em>length</em><span class="optional">[</span>, <em>tagname</em><span class="optional">[</span>, <em>access</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap" title="Permalink to this definition">¶</a></dt>
<dd><p><strong>(Windows version)</strong> Maps <em>length</em> bytes from the file specified by the
file handle <em>fileno</em>, and creates a mmap object.  If <em>length</em> is larger
than the current size of the file, the file is extended to contain <em>length</em>
bytes.  If <em>length</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the maximum length of the map is the current
size of the file, except that if the file is empty Windows raises an
exception (you cannot create an empty mapping on Windows).</p>
<p><em>tagname</em>, if specified and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, is a string giving a tag name for
the mapping.  Windows allows you to have many different mappings against
the same file.  If you specify the name of an existing tag, that tag is
opened, otherwise a new tag of this name is created.  If this parameter is
omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the mapping is created without a name.  Avoiding the
use of the tag parameter will assist in keeping your code portable between
Unix and Windows.</p>
<p><em>offset</em> may be specified as a non-negative integer offset. mmap references
will be relative to the offset from the beginning of the file. <em>offset</em>
defaults to 0.  <em>offset</em> must be a multiple of the <code class="xref py py-const docutils literal notranslate"><span class="pre">ALLOCATIONGRANULARITY</span></code>.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">mmap.</code><code class="descname">mmap</code><span class="sig-paren">(</span><em>fileno</em>, <em>length</em><span class="optional">[</span>, <em>flags</em><span class="optional">[</span>, <em>prot</em><span class="optional">[</span>, <em>access</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p><strong>(Unix version)</strong> Maps <em>length</em> bytes from the file specified by the file
descriptor <em>fileno</em>, and returns a mmap object.  If <em>length</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the
maximum length of the map will be the current size of the file when
<a class="reference internal" href="#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a> is called.</p>
<p><em>flags</em> specifies the nature of the mapping. <code class="xref py py-const docutils literal notranslate"><span class="pre">MAP_PRIVATE</span></code> creates a
private copy-on-write mapping, so changes to the contents of the mmap
object will be private to this process, and <code class="xref py py-const docutils literal notranslate"><span class="pre">MAP_SHARED</span></code> creates a
mapping that’s shared with all other processes mapping the same areas of
the file.  The default value is <code class="xref py py-const docutils literal notranslate"><span class="pre">MAP_SHARED</span></code>.</p>
<p><em>prot</em>, if specified, gives the desired memory protection; the two most
useful values are <code class="xref py py-const docutils literal notranslate"><span class="pre">PROT_READ</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">PROT_WRITE</span></code>, to specify
that the pages may be read or written.  <em>prot</em> defaults to
<code class="xref py py-const docutils literal notranslate"><span class="pre">PROT_READ</span> <span class="pre">|</span> <span class="pre">PROT_WRITE</span></code>.</p>
<p><em>access</em> may be specified in lieu of <em>flags</em> and <em>prot</em> as an optional
keyword parameter.  It is an error to specify both <em>flags</em>, <em>prot</em> and
<em>access</em>.  See the description of <em>access</em> above for information on how to
use this parameter.</p>
<p><em>offset</em> may be specified as a non-negative integer offset. mmap references
will be relative to the offset from the beginning of the file. <em>offset</em>
defaults to 0. <em>offset</em> must be a multiple of <code class="xref py py-const docutils literal notranslate"><span class="pre">ALLOCATIONGRANULARITY</span></code>
which is equal to <code class="xref py py-const docutils literal notranslate"><span class="pre">PAGESIZE</span></code> on Unix systems.</p>
<p>To ensure validity of the created memory mapping the file specified
by the descriptor <em>fileno</em> is internally automatically synchronized
with physical backing store on Mac OS X and OpenVMS.</p>
<p>This example shows a simple way of using <a class="reference internal" href="#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mmap</span>

<span class="c1"># write a simple example file</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;hello.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;wb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Hello Python!</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;hello.txt&quot;</span><span class="p">,</span> <span class="s2">&quot;r+b&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="c1"># memory-map the file, size 0 means whole file</span>
    <span class="n">mm</span> <span class="o">=</span> <span class="n">mmap</span><span class="o">.</span><span class="n">mmap</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">fileno</span><span class="p">(),</span> <span class="mi">0</span><span class="p">)</span>
    <span class="c1"># read content via standard file methods</span>
    <span class="nb">print</span> <span class="n">mm</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>  <span class="c1"># prints &quot;Hello Python!&quot;</span>
    <span class="c1"># read content via slice notation</span>
    <span class="nb">print</span> <span class="n">mm</span><span class="p">[:</span><span class="mi">5</span><span class="p">]</span>  <span class="c1"># prints &quot;Hello&quot;</span>
    <span class="c1"># update content using slice notation;</span>
    <span class="c1"># note that new content must have same size</span>
    <span class="n">mm</span><span class="p">[</span><span class="mi">6</span><span class="p">:]</span> <span class="o">=</span> <span class="s2">&quot; world!</span><span class="se">\n</span><span class="s2">&quot;</span>
    <span class="c1"># ... and read again using standard file methods</span>
    <span class="n">mm</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="nb">print</span> <span class="n">mm</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>  <span class="c1"># prints &quot;Hello  world!&quot;</span>
    <span class="c1"># close the map</span>
    <span class="n">mm</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The next example demonstrates how to create an anonymous map and exchange
data between the parent and child processes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mmap</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="n">mm</span> <span class="o">=</span> <span class="n">mmap</span><span class="o">.</span><span class="n">mmap</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">13</span><span class="p">)</span>
<span class="n">mm</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Hello world!&quot;</span><span class="p">)</span>

<span class="n">pid</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">fork</span><span class="p">()</span>

<span class="k">if</span> <span class="n">pid</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>  <span class="c1"># In a child process</span>
    <span class="n">mm</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="nb">print</span> <span class="n">mm</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>

    <span class="n">mm</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Memory-mapped file objects support the following methods:</p>
<dl class="method">
<dt id="mmap.mmap.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the mmap. Subsequent calls to other methods of the object will
result in a ValueError exception being raised. This will not close
the open file.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.find">
<code class="descname">find</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the lowest index in the object where the substring <em>string</em> is
found, such that <em>string</em> is contained in the range [<em>start</em>, <em>end</em>].
Optional arguments <em>start</em> and <em>end</em> are interpreted as in slice notation.
Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.flush">
<code class="descname">flush</code><span class="sig-paren">(</span><span class="optional">[</span><em>offset</em>, <em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flushes changes made to the in-memory copy of a file back to disk. Without
use of this call there is no guarantee that changes are written back before
the object is destroyed.  If <em>offset</em> and <em>size</em> are specified, only
changes to the given range of bytes will be flushed to disk; otherwise, the
whole extent of the mapping is flushed.  <em>offset</em> must be a multiple of the
<code class="xref py py-const docutils literal notranslate"><span class="pre">PAGESIZE</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">ALLOCATIONGRANULARITY</span></code>.</p>
<p><strong>(Windows version)</strong> A nonzero value returned indicates success; zero
indicates failure.</p>
<p><strong>(Unix version)</strong> A zero value is returned to indicate success. An
exception is raised when the call failed.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.move">
<code class="descname">move</code><span class="sig-paren">(</span><em>dest</em>, <em>src</em>, <em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the <em>count</em> bytes starting at offset <em>src</em> to the destination index
<em>dest</em>.  If the mmap was created with <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code>, then calls to
move will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.read">
<code class="descname">read</code><span class="sig-paren">(</span><em>num</em><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing up to <em>num</em> bytes starting from the current
file position; the file position is updated to point after the bytes that
were returned.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.read_byte">
<code class="descname">read_byte</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.read_byte" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string of length 1 containing the character at the current file
position, and advances the file position by 1.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.readline">
<code class="descname">readline</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a single line, starting at the current file position and up to the
next newline.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.resize">
<code class="descname">resize</code><span class="sig-paren">(</span><em>newsize</em><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.resize" title="Permalink to this definition">¶</a></dt>
<dd><p>Resizes the map and the underlying file, if any. If the mmap was created
with <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_COPY</span></code>, resizing the map will
raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.rfind">
<code class="descname">rfind</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.rfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the highest index in the object where the substring <em>string</em> is
found, such that <em>string</em> is contained in the range [<em>start</em>, <em>end</em>].
Optional arguments <em>start</em> and <em>end</em> are interpreted as in slice notation.
Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.seek">
<code class="descname">seek</code><span class="sig-paren">(</span><em>pos</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file’s current position.  <em>whence</em> argument is optional and
defaults to <code class="docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> (absolute file positioning); other
values are <code class="docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code> or <code class="docutils literal notranslate"><span class="pre">1</span></code> (seek relative to the current
position) and <code class="docutils literal notranslate"><span class="pre">os.SEEK_END</span></code> or <code class="docutils literal notranslate"><span class="pre">2</span></code> (seek relative to the file’s end).</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.size">
<code class="descname">size</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the length of the file, which can be larger than the size of the
memory-mapped area.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.tell">
<code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current position of the file pointer.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the bytes in <em>string</em> into memory at the current position of the
file pointer; the file position is updated to point after the bytes that
were written. If the mmap was created with <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code>, then
writing to it will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</dd></dl>

<dl class="method">
<dt id="mmap.mmap.write_byte">
<code class="descname">write_byte</code><span class="sig-paren">(</span><em>byte</em><span class="sig-paren">)</span><a class="headerlink" href="#mmap.mmap.write_byte" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the single-character string <em>byte</em> into memory at the current
position of the file pointer; the file position is advanced by <code class="docutils literal notranslate"><span class="pre">1</span></code>. If
the mmap was created with <code class="xref py py-const docutils literal notranslate"><span class="pre">ACCESS_READ</span></code>, then writing to it will
raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</dd></dl>

</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="multiprocessing.html"
                        title="previous chapter">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="readline.html"
                        title="next chapter">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mmap.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="readline.html" title="16.8. readline — GNU readline interface"
             >next</a> |</li>
        <li class="right" >
          <a href="multiprocessing.html" title="16.6. multiprocessing — Process-based “threading” interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1<�M�F�Fhtml/library/modulefinder.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.6. modulefinder — Find modules used by a script &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.7. runpy — Locating and executing Python modules" href="runpy.html" />
    <link rel="prev" title="31.5. pkgutil — Package extension utility" href="pkgutil.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/modulefinder.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="runpy.html" title="31.7. runpy — Locating and executing Python modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pkgutil.html" title="31.5. pkgutil — Package extension utility"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-modulefinder">
<span id="modulefinder-find-modules-used-by-a-script"></span><h1>31.6. <a class="reference internal" href="#module-modulefinder" title="modulefinder: Find modules used by a script."><code class="xref py py-mod docutils literal notranslate"><span class="pre">modulefinder</span></code></a> — Find modules used by a script<a class="headerlink" href="#module-modulefinder" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/modulefinder.py">Lib/modulefinder.py</a></p>
<hr class="docutils" />
<p>This module provides a <a class="reference internal" href="#modulefinder.ModuleFinder" title="modulefinder.ModuleFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModuleFinder</span></code></a> class that can be used to determine
the set of modules imported by a script. <code class="docutils literal notranslate"><span class="pre">modulefinder.py</span></code> can also be run as
a script, giving the filename of a Python script as its argument, after which a
report of the imported modules will be printed.</p>
<dl class="function">
<dt id="modulefinder.AddPackagePath">
<code class="descclassname">modulefinder.</code><code class="descname">AddPackagePath</code><span class="sig-paren">(</span><em>pkg_name</em>, <em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#modulefinder.AddPackagePath" title="Permalink to this definition">¶</a></dt>
<dd><p>Record that the package named <em>pkg_name</em> can be found in the specified <em>path</em>.</p>
</dd></dl>

<dl class="function">
<dt id="modulefinder.ReplacePackage">
<code class="descclassname">modulefinder.</code><code class="descname">ReplacePackage</code><span class="sig-paren">(</span><em>oldname</em>, <em>newname</em><span class="sig-paren">)</span><a class="headerlink" href="#modulefinder.ReplacePackage" title="Permalink to this definition">¶</a></dt>
<dd><p>Allows specifying that the module named <em>oldname</em> is in fact the package named
<em>newname</em>.  The most common usage would be  to handle how the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_xmlplus</span></code>
package replaces the <a class="reference internal" href="xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package.</p>
</dd></dl>

<dl class="class">
<dt id="modulefinder.ModuleFinder">
<em class="property">class </em><code class="descclassname">modulefinder.</code><code class="descname">ModuleFinder</code><span class="sig-paren">(</span><span class="optional">[</span><em>path=None</em>, <em>debug=0</em>, <em>excludes=[]</em>, <em>replace_paths=[]</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#modulefinder.ModuleFinder" title="Permalink to this definition">¶</a></dt>
<dd><p>This class provides <a class="reference internal" href="#modulefinder.ModuleFinder.run_script" title="modulefinder.ModuleFinder.run_script"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_script()</span></code></a> and <a class="reference internal" href="#modulefinder.ModuleFinder.report" title="modulefinder.ModuleFinder.report"><code class="xref py py-meth docutils literal notranslate"><span class="pre">report()</span></code></a> methods to determine
the set of modules imported by a script. <em>path</em> can be a list of directories to
search for modules; if not specified, <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is used.  <em>debug</em> sets the
debugging level; higher values make the class print  debugging messages about
what it’s doing. <em>excludes</em> is a list of module names to exclude from the
analysis. <em>replace_paths</em> is a list of <code class="docutils literal notranslate"><span class="pre">(oldpath,</span> <span class="pre">newpath)</span></code> tuples that will
be replaced in module paths.</p>
<dl class="method">
<dt id="modulefinder.ModuleFinder.report">
<code class="descname">report</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#modulefinder.ModuleFinder.report" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a report to standard output that lists the modules imported by the
script and their paths, as well as modules that are missing or seem to be
missing.</p>
</dd></dl>

<dl class="method">
<dt id="modulefinder.ModuleFinder.run_script">
<code class="descname">run_script</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#modulefinder.ModuleFinder.run_script" title="Permalink to this definition">¶</a></dt>
<dd><p>Analyze the contents of the <em>pathname</em> file, which must contain Python
code.</p>
</dd></dl>

<dl class="attribute">
<dt id="modulefinder.ModuleFinder.modules">
<code class="descname">modules</code><a class="headerlink" href="#modulefinder.ModuleFinder.modules" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping module names to modules. See
<a class="reference internal" href="#modulefinder-example"><span class="std std-ref">Example usage of ModuleFinder</span></a>.</p>
</dd></dl>

</dd></dl>

<div class="section" id="example-usage-of-modulefinder">
<span id="modulefinder-example"></span><h2>31.6.1. Example usage of <a class="reference internal" href="#modulefinder.ModuleFinder" title="modulefinder.ModuleFinder"><code class="xref py py-class docutils literal notranslate"><span class="pre">ModuleFinder</span></code></a><a class="headerlink" href="#example-usage-of-modulefinder" title="Permalink to this headline">¶</a></h2>
<p>The script that is going to get analyzed later on (bacon.py):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">re</span><span class="o">,</span> <span class="nn">itertools</span>

<span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">baconhameggs</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="k">pass</span>

<span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">guido.python.ham</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The script that will output the report of bacon.py:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">modulefinder</span> <span class="k">import</span> <span class="n">ModuleFinder</span>

<span class="n">finder</span> <span class="o">=</span> <span class="n">ModuleFinder</span><span class="p">()</span>
<span class="n">finder</span><span class="o">.</span><span class="n">run_script</span><span class="p">(</span><span class="s1">&#39;bacon.py&#39;</span><span class="p">)</span>

<span class="nb">print</span> <span class="s1">&#39;Loaded modules:&#39;</span>
<span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">mod</span> <span class="ow">in</span> <span class="n">finder</span><span class="o">.</span><span class="n">modules</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">: &#39;</span> <span class="o">%</span> <span class="n">name</span><span class="p">,</span>
    <span class="nb">print</span> <span class="s1">&#39;,&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">mod</span><span class="o">.</span><span class="n">globalnames</span><span class="o">.</span><span class="n">keys</span><span class="p">()[:</span><span class="mi">3</span><span class="p">])</span>

<span class="nb">print</span> <span class="s1">&#39;-&#39;</span><span class="o">*</span><span class="mi">50</span>
<span class="nb">print</span> <span class="s1">&#39;Modules not imported:&#39;</span>
<span class="nb">print</span> <span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">finder</span><span class="o">.</span><span class="n">badmodules</span><span class="o">.</span><span class="n">iterkeys</span><span class="p">())</span>
</pre></div>
</div>
<p>Sample output (may vary depending on the architecture):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Loaded</span> <span class="n">modules</span><span class="p">:</span>
<span class="n">_types</span><span class="p">:</span>
<span class="n">copy_reg</span><span class="p">:</span>  <span class="n">_inverted_registry</span><span class="p">,</span><span class="n">_slotnames</span><span class="p">,</span><span class="n">__all__</span>
<span class="n">sre_compile</span><span class="p">:</span>  <span class="n">isstring</span><span class="p">,</span><span class="n">_sre</span><span class="p">,</span><span class="n">_optimize_unicode</span>
<span class="n">_sre</span><span class="p">:</span>
<span class="n">sre_constants</span><span class="p">:</span>  <span class="n">REPEAT_ONE</span><span class="p">,</span><span class="n">makedict</span><span class="p">,</span><span class="n">AT_END_LINE</span>
<span class="n">sys</span><span class="p">:</span>
<span class="n">re</span><span class="p">:</span>  <span class="vm">__module__</span><span class="p">,</span><span class="n">finditer</span><span class="p">,</span><span class="n">_expand</span>
<span class="n">itertools</span><span class="p">:</span>
<span class="n">__main__</span><span class="p">:</span>  <span class="n">re</span><span class="p">,</span><span class="n">itertools</span><span class="p">,</span><span class="n">baconhameggs</span>
<span class="n">sre_parse</span><span class="p">:</span>  <span class="n">__getslice__</span><span class="p">,</span><span class="n">_PATTERNENDERS</span><span class="p">,</span><span class="n">SRE_FLAG_UNICODE</span>
<span class="n">array</span><span class="p">:</span>
<span class="n">types</span><span class="p">:</span>  <span class="vm">__module__</span><span class="p">,</span><span class="n">IntType</span><span class="p">,</span><span class="n">TypeType</span>
<span class="o">---------------------------------------------------</span>
<span class="n">Modules</span> <span class="ow">not</span> <span class="n">imported</span><span class="p">:</span>
<span class="n">guido</span><span class="o">.</span><span class="n">python</span><span class="o">.</span><span class="n">ham</span>
<span class="n">baconhameggs</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a><ul>
<li><a class="reference internal" href="#example-usage-of-modulefinder">31.6.1. Example usage of <code class="docutils literal notranslate"><span class="pre">ModuleFinder</span></code></a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pkgutil.html"
                        title="previous chapter">31.5. <code class="docutils literal notranslate"><span class="pre">pkgutil</span></code> — Package extension utility</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="runpy.html"
                        title="next chapter">31.7. <code class="docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/modulefinder.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="runpy.html" title="31.7. runpy — Locating and executing Python modules"
             >next</a> |</li>
        <li class="right" >
          <a href="pkgutil.html" title="31.5. pkgutil — Package extension utility"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�h�Z9#9#html/library/modules.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31. Importing Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.1. imp — Access the import internals" href="imp.html" />
    <link rel="prev" title="30.2. Bastion — Restricting access to objects" href="bastion.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/modules.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imp.html" title="31.1. imp — Access the import internals"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bastion.html" title="30.2. Bastion — Restricting access to objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="importing-modules">
<span id="modules"></span><h1>31. Importing Modules<a class="headerlink" href="#importing-modules" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide new ways to import other Python
modules and hooks for customizing the import process.</p>
<p>The full list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="imp.html">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a><ul>
<li class="toctree-l2"><a class="reference internal" href="imp.html#examples">31.1.1. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="importlib.html">31.2. <code class="docutils literal notranslate"><span class="pre">importlib</span></code> — Convenience wrappers for <code class="docutils literal notranslate"><span class="pre">__import__()</span></code></a></li>
<li class="toctree-l1"><a class="reference internal" href="imputil.html">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a><ul>
<li class="toctree-l2"><a class="reference internal" href="imputil.html#examples">31.3.1. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="zipimport.html">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a><ul>
<li class="toctree-l2"><a class="reference internal" href="zipimport.html#zipimporter-objects">31.4.1. zipimporter Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="zipimport.html#examples">31.4.2. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="pkgutil.html">31.5. <code class="docutils literal notranslate"><span class="pre">pkgutil</span></code> — Package extension utility</a></li>
<li class="toctree-l1"><a class="reference internal" href="modulefinder.html">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a><ul>
<li class="toctree-l2"><a class="reference internal" href="modulefinder.html#example-usage-of-modulefinder">31.6.1. Example usage of <code class="docutils literal notranslate"><span class="pre">ModuleFinder</span></code></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="runpy.html">31.7. <code class="docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="bastion.html"
                        title="previous chapter">30.2. <code class="docutils literal notranslate"><span class="pre">Bastion</span></code> — Restricting access to objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imp.html"
                        title="next chapter">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/modules.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imp.html" title="31.1. imp — Access the import internals"
             >next</a> |</li>
        <li class="right" >
          <a href="bastion.html" title="30.2. Bastion — Restricting access to objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��������html/library/msilib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>35.1. msilib — Read and write Microsoft Installer files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="35.2. msvcrt — Useful routines from the MS VC++ runtime" href="msvcrt.html" />
    <link rel="prev" title="35. MS Windows Specific Services" href="windows.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/msilib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="msvcrt.html" title="35.2. msvcrt — Useful routines from the MS VC++ runtime"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="35. MS Windows Specific Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" accesskey="U">35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-msilib">
<span id="msilib-read-and-write-microsoft-installer-files"></span><h1>35.1. <a class="reference internal" href="#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> — Read and write Microsoft Installer files<a class="headerlink" href="#module-msilib" title="Permalink to this headline">¶</a></h1>
<div class="versionadded" id="index-0">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The <a class="reference internal" href="#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> supports the creation of Microsoft Installer (<code class="docutils literal notranslate"><span class="pre">.msi</span></code>) files.
Because these files often contain an embedded “cabinet” file (<code class="docutils literal notranslate"><span class="pre">.cab</span></code>), it also
exposes an API to create CAB files. Support for reading <code class="docutils literal notranslate"><span class="pre">.cab</span></code> files is
currently not implemented; read support for the <code class="docutils literal notranslate"><span class="pre">.msi</span></code> database is possible.</p>
<p>This package aims to provide complete access to all tables in an <code class="docutils literal notranslate"><span class="pre">.msi</span></code> file,
therefore, it is a fairly low-level API. Two primary applications of this
package are the <a class="reference internal" href="distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> command <code class="docutils literal notranslate"><span class="pre">bdist_msi</span></code>, and the creation of
Python installer package itself (although that currently uses a different
version of <code class="docutils literal notranslate"><span class="pre">msilib</span></code>).</p>
<p>The package contents can be roughly split into four parts: low-level CAB
routines, low-level MSI routines, higher-level MSI routines, and standard table
structures.</p>
<dl class="function">
<dt id="msilib.FCICreate">
<code class="descclassname">msilib.</code><code class="descname">FCICreate</code><span class="sig-paren">(</span><em>cabname</em>, <em>files</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.FCICreate" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new CAB file named <em>cabname</em>. <em>files</em> must be a list of tuples, each
containing the name of the file on disk, and the name of the file inside the CAB
file.</p>
<p>The files are added to the CAB file in the order they appear in the list. All
files are added into a single CAB file, using the MSZIP compression algorithm.</p>
<p>Callbacks to Python for the various steps of MSI creation are currently not
exposed.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.UuidCreate">
<code class="descclassname">msilib.</code><code class="descname">UuidCreate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.UuidCreate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string representation of a new unique identifier. This wraps the
Windows API functions <code class="xref c c-func docutils literal notranslate"><span class="pre">UuidCreate()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">UuidToString()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.OpenDatabase">
<code class="descclassname">msilib.</code><code class="descname">OpenDatabase</code><span class="sig-paren">(</span><em>path</em>, <em>persist</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.OpenDatabase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new database object by calling MsiOpenDatabase.   <em>path</em> is the file
name of the MSI file; <em>persist</em> can be one of the constants
<code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_CREATEDIRECT</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_CREATE</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_DIRECT</span></code>,
<code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_READONLY</span></code>, or <code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_TRANSACT</span></code>, and may include the flag
<code class="docutils literal notranslate"><span class="pre">MSIDBOPEN_PATCHFILE</span></code>. See the Microsoft documentation for the meaning of
these flags; depending on the flags, an existing database is opened, or a new
one created.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.CreateRecord">
<code class="descclassname">msilib.</code><code class="descname">CreateRecord</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.CreateRecord" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new record object by calling <code class="xref c c-func docutils literal notranslate"><span class="pre">MSICreateRecord()</span></code>. <em>count</em> is the
number of fields of the record.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.init_database">
<code class="descclassname">msilib.</code><code class="descname">init_database</code><span class="sig-paren">(</span><em>name</em>, <em>schema</em>, <em>ProductName</em>, <em>ProductCode</em>, <em>ProductVersion</em>, <em>Manufacturer</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.init_database" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a new database <em>name</em>, initialize it with <em>schema</em>, and set
the properties <em>ProductName</em>, <em>ProductCode</em>, <em>ProductVersion</em>, and
<em>Manufacturer</em>.</p>
<p><em>schema</em> must be a module object containing <code class="docutils literal notranslate"><span class="pre">tables</span></code> and
<code class="docutils literal notranslate"><span class="pre">_Validation_records</span></code> attributes; typically, <a class="reference internal" href="#msilib.schema" title="msilib.schema"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib.schema</span></code></a> should be
used.</p>
<p>The database will contain just the schema and the validation records when this
function returns.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.add_data">
<code class="descclassname">msilib.</code><code class="descname">add_data</code><span class="sig-paren">(</span><em>database</em>, <em>table</em>, <em>records</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.add_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Add all <em>records</em> to the table named <em>table</em> in <em>database</em>.</p>
<p>The <em>table</em> argument must be one of the predefined tables in the MSI schema,
e.g. <code class="docutils literal notranslate"><span class="pre">'Feature'</span></code>, <code class="docutils literal notranslate"><span class="pre">'File'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Component'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Dialog'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Control'</span></code>,
etc.</p>
<p><em>records</em> should be a list of tuples, each one containing all fields of a
record according to the schema of the table.  For optional fields,
<code class="docutils literal notranslate"><span class="pre">None</span></code> can be passed.</p>
<p>Field values can be int or long numbers, strings, or instances of the Binary
class.</p>
</dd></dl>

<dl class="class">
<dt id="msilib.Binary">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">Binary</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Binary" title="Permalink to this definition">¶</a></dt>
<dd><p>Represents entries in the Binary table; inserting such an object using
<a class="reference internal" href="#msilib.add_data" title="msilib.add_data"><code class="xref py py-func docutils literal notranslate"><span class="pre">add_data()</span></code></a> reads the file named <em>filename</em> into the table.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.add_tables">
<code class="descclassname">msilib.</code><code class="descname">add_tables</code><span class="sig-paren">(</span><em>database</em>, <em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.add_tables" title="Permalink to this definition">¶</a></dt>
<dd><p>Add all table content from <em>module</em> to <em>database</em>. <em>module</em> must contain an
attribute <em>tables</em> listing all tables for which content should be added, and one
attribute per table that has the actual content.</p>
<p>This is typically used to install the sequence tables.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.add_stream">
<code class="descclassname">msilib.</code><code class="descname">add_stream</code><span class="sig-paren">(</span><em>database</em>, <em>name</em>, <em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.add_stream" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the file <em>path</em> into the <code class="docutils literal notranslate"><span class="pre">_Stream</span></code> table of <em>database</em>, with the stream
name <em>name</em>.</p>
</dd></dl>

<dl class="function">
<dt id="msilib.gen_uuid">
<code class="descclassname">msilib.</code><code class="descname">gen_uuid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.gen_uuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new UUID, in the format that MSI typically requires (i.e. in curly
braces, and with all hexdigits in upper-case).</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/devnotes/winprog/fcicreate.asp">FCICreateFile</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidcreate.asp">UuidCreate</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/rpc/rpc/uuidtostring.asp">UuidToString</a></p>
</div>
<div class="section" id="database-objects">
<span id="id1"></span><h2>35.1.1. Database Objects<a class="headerlink" href="#database-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="msilib.Database.OpenView">
<code class="descclassname">Database.</code><code class="descname">OpenView</code><span class="sig-paren">(</span><em>sql</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Database.OpenView" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a view object, by calling <code class="xref c c-func docutils literal notranslate"><span class="pre">MSIDatabaseOpenView()</span></code>. <em>sql</em> is the SQL
statement to execute.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Database.Commit">
<code class="descclassname">Database.</code><code class="descname">Commit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Database.Commit" title="Permalink to this definition">¶</a></dt>
<dd><p>Commit the changes pending in the current transaction, by calling
<code class="xref c c-func docutils literal notranslate"><span class="pre">MSIDatabaseCommit()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Database.GetSummaryInformation">
<code class="descclassname">Database.</code><code class="descname">GetSummaryInformation</code><span class="sig-paren">(</span><em>count</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Database.GetSummaryInformation" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new summary information object, by calling
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiGetSummaryInformation()</span></code>.  <em>count</em> is the maximum number of updated
values.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabaseopenview.asp">MSIDatabaseOpenView</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msidatabasecommit.asp">MSIDatabaseCommit</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msigetsummaryinformation.asp">MSIGetSummaryInformation</a></p>
</div>
</div>
<div class="section" id="view-objects">
<span id="id2"></span><h2>35.1.2. View Objects<a class="headerlink" href="#view-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="msilib.View.Execute">
<code class="descclassname">View.</code><code class="descname">Execute</code><span class="sig-paren">(</span><em>params</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.View.Execute" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the SQL query of the view, through <code class="xref c c-func docutils literal notranslate"><span class="pre">MSIViewExecute()</span></code>. If
<em>params</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is a record describing actual values of the
parameter tokens in the query.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.View.GetColumnInfo">
<code class="descclassname">View.</code><code class="descname">GetColumnInfo</code><span class="sig-paren">(</span><em>kind</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.View.GetColumnInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a record describing the columns of the view, through calling
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiViewGetColumnInfo()</span></code>. <em>kind</em> can be either <code class="docutils literal notranslate"><span class="pre">MSICOLINFO_NAMES</span></code> or
<code class="docutils literal notranslate"><span class="pre">MSICOLINFO_TYPES</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.View.Fetch">
<code class="descclassname">View.</code><code class="descname">Fetch</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.View.Fetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a result record of the query, through calling <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiViewFetch()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.View.Modify">
<code class="descclassname">View.</code><code class="descname">Modify</code><span class="sig-paren">(</span><em>kind</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.View.Modify" title="Permalink to this definition">¶</a></dt>
<dd><p>Modify the view, by calling <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiViewModify()</span></code>. <em>kind</em> can be one of
<code class="docutils literal notranslate"><span class="pre">MSIMODIFY_SEEK</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_REFRESH</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_INSERT</span></code>,
<code class="docutils literal notranslate"><span class="pre">MSIMODIFY_UPDATE</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_ASSIGN</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_REPLACE</span></code>,
<code class="docutils literal notranslate"><span class="pre">MSIMODIFY_MERGE</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_DELETE</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_INSERT_TEMPORARY</span></code>,
<code class="docutils literal notranslate"><span class="pre">MSIMODIFY_VALIDATE</span></code>, <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_VALIDATE_NEW</span></code>,
<code class="docutils literal notranslate"><span class="pre">MSIMODIFY_VALIDATE_FIELD</span></code>, or <code class="docutils literal notranslate"><span class="pre">MSIMODIFY_VALIDATE_DELETE</span></code>.</p>
<p><em>data</em> must be a record describing the new data.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.View.Close">
<code class="descclassname">View.</code><code class="descname">Close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.View.Close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the view, through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiViewClose()</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewexecute.asp">MsiViewExecute</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewgetcolumninfo.asp">MSIViewGetColumnInfo</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewfetch.asp">MsiViewFetch</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewmodify.asp">MsiViewModify</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msiviewclose.asp">MsiViewClose</a></p>
</div>
</div>
<div class="section" id="summary-information-objects">
<span id="summary-objects"></span><h2>35.1.3. Summary Information Objects<a class="headerlink" href="#summary-information-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="msilib.SummaryInformation.GetProperty">
<code class="descclassname">SummaryInformation.</code><code class="descname">GetProperty</code><span class="sig-paren">(</span><em>field</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.SummaryInformation.GetProperty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a property of the summary, through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiSummaryInfoGetProperty()</span></code>.
<em>field</em> is the name of the property, and can be one of the constants
<code class="docutils literal notranslate"><span class="pre">PID_CODEPAGE</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_TITLE</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_SUBJECT</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_AUTHOR</span></code>,
<code class="docutils literal notranslate"><span class="pre">PID_KEYWORDS</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_COMMENTS</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_TEMPLATE</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_LASTAUTHOR</span></code>,
<code class="docutils literal notranslate"><span class="pre">PID_REVNUMBER</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_LASTPRINTED</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_CREATE_DTM</span></code>,
<code class="docutils literal notranslate"><span class="pre">PID_LASTSAVE_DTM</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_PAGECOUNT</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_WORDCOUNT</span></code>, <code class="docutils literal notranslate"><span class="pre">PID_CHARCOUNT</span></code>,
<code class="docutils literal notranslate"><span class="pre">PID_APPNAME</span></code>, or <code class="docutils literal notranslate"><span class="pre">PID_SECURITY</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.SummaryInformation.GetPropertyCount">
<code class="descclassname">SummaryInformation.</code><code class="descname">GetPropertyCount</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.SummaryInformation.GetPropertyCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of summary properties, through
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiSummaryInfoGetPropertyCount()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.SummaryInformation.SetProperty">
<code class="descclassname">SummaryInformation.</code><code class="descname">SetProperty</code><span class="sig-paren">(</span><em>field</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.SummaryInformation.SetProperty" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a property through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiSummaryInfoSetProperty()</span></code>. <em>field</em> can have the
same values as in <a class="reference internal" href="#msilib.SummaryInformation.GetProperty" title="msilib.SummaryInformation.GetProperty"><code class="xref py py-meth docutils literal notranslate"><span class="pre">GetProperty()</span></code></a>, <em>value</em> is the new value of the property.
Possible value types are integer and string.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.SummaryInformation.Persist">
<code class="descclassname">SummaryInformation.</code><code class="descname">Persist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.SummaryInformation.Persist" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the modified properties to the summary information stream, using
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiSummaryInfoPersist()</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetproperty.asp">MsiSummaryInfoGetProperty</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfogetpropertycount.asp">MsiSummaryInfoGetPropertyCount</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfosetproperty.asp">MsiSummaryInfoSetProperty</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msisummaryinfopersist.asp">MsiSummaryInfoPersist</a></p>
</div>
</div>
<div class="section" id="record-objects">
<span id="id3"></span><h2>35.1.4. Record Objects<a class="headerlink" href="#record-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="msilib.Record.GetFieldCount">
<code class="descclassname">Record.</code><code class="descname">GetFieldCount</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.GetFieldCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of fields of the record, through
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiRecordGetFieldCount()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.GetInteger">
<code class="descclassname">Record.</code><code class="descname">GetInteger</code><span class="sig-paren">(</span><em>field</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.GetInteger" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of <em>field</em> as an integer where possible.  <em>field</em> must
be an integer.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.GetString">
<code class="descclassname">Record.</code><code class="descname">GetString</code><span class="sig-paren">(</span><em>field</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.GetString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of <em>field</em> as a string where possible.  <em>field</em> must
be an integer.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.SetString">
<code class="descclassname">Record.</code><code class="descname">SetString</code><span class="sig-paren">(</span><em>field</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.SetString" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>field</em> to <em>value</em> through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiRecordSetString()</span></code>. <em>field</em> must be an
integer; <em>value</em> a string.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.SetStream">
<code class="descclassname">Record.</code><code class="descname">SetStream</code><span class="sig-paren">(</span><em>field</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.SetStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>field</em> to the contents of the file named <em>value</em>, through
<code class="xref c c-func docutils literal notranslate"><span class="pre">MsiRecordSetStream()</span></code>. <em>field</em> must be an integer; <em>value</em> a string.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.SetInteger">
<code class="descclassname">Record.</code><code class="descname">SetInteger</code><span class="sig-paren">(</span><em>field</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.SetInteger" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>field</em> to <em>value</em> through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiRecordSetInteger()</span></code>. Both <em>field</em> and
<em>value</em> must be an integer.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Record.ClearData">
<code class="descclassname">Record.</code><code class="descname">ClearData</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Record.ClearData" title="Permalink to this definition">¶</a></dt>
<dd><p>Set all fields of the record to 0, through <code class="xref c c-func docutils literal notranslate"><span class="pre">MsiRecordClearData()</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordgetfieldcount.asp">MsiRecordGetFieldCount</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstring.asp">MsiRecordSetString</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetstream.asp">MsiRecordSetStream</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordsetinteger.asp">MsiRecordSetInteger</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/msirecordclear.asp">MsiRecordClear</a></p>
</div>
</div>
<div class="section" id="errors">
<span id="msi-errors"></span><h2>35.1.5. Errors<a class="headerlink" href="#errors" title="Permalink to this headline">¶</a></h2>
<p>All wrappers around MSI functions raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">MSIError</span></code>; the string inside the
exception will contain more detail.</p>
</div>
<div class="section" id="cab-objects">
<span id="cab"></span><h2>35.1.6. CAB Objects<a class="headerlink" href="#cab-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="msilib.CAB">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">CAB</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.CAB" title="Permalink to this definition">¶</a></dt>
<dd><p>The class <a class="reference internal" href="#msilib.CAB" title="msilib.CAB"><code class="xref py py-class docutils literal notranslate"><span class="pre">CAB</span></code></a> represents a CAB file. During MSI construction, files
will be added simultaneously to the <code class="docutils literal notranslate"><span class="pre">Files</span></code> table, and to a CAB file. Then,
when all files have been added, the CAB file can be written, then added to the
MSI file.</p>
<p><em>name</em> is the name of the CAB file in the MSI file.</p>
<dl class="method">
<dt id="msilib.CAB.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>full</em>, <em>file</em>, <em>logical</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.CAB.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the file with the pathname <em>full</em> to the CAB file, under the name
<em>logical</em>.  If there is already a file named <em>logical</em>, a new file name is
created.</p>
<p>Return the index of the file in the CAB file, and the new name of the file
inside the CAB file.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.CAB.commit">
<code class="descname">commit</code><span class="sig-paren">(</span><em>database</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.CAB.commit" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a CAB file, add it as a stream to the MSI file, put it into the
<code class="docutils literal notranslate"><span class="pre">Media</span></code> table, and remove the generated file from the disk.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="directory-objects">
<span id="msi-directory"></span><h2>35.1.7. Directory Objects<a class="headerlink" href="#directory-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="msilib.Directory">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">Directory</code><span class="sig-paren">(</span><em>database</em>, <em>cab</em>, <em>basedir</em>, <em>physical</em>, <em>logical</em>, <em>default</em><span class="optional">[</span>, <em>componentflags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Directory" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new directory in the Directory table. There is a current component at
each point in time for the directory, which is either explicitly created through
<a class="reference internal" href="#msilib.Directory.start_component" title="msilib.Directory.start_component"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start_component()</span></code></a>, or implicitly when files are added for the first time.
Files are added into the current component, and into the cab file.  To create a
directory, a base directory object needs to be specified (can be <code class="docutils literal notranslate"><span class="pre">None</span></code>), the
path to the physical directory, and a logical directory name.  <em>default</em>
specifies the DefaultDir slot in the directory table. <em>componentflags</em> specifies
the default flags that new components get.</p>
<dl class="method">
<dt id="msilib.Directory.start_component">
<code class="descname">start_component</code><span class="sig-paren">(</span><span class="optional">[</span><em>component</em><span class="optional">[</span>, <em>feature</em><span class="optional">[</span>, <em>flags</em><span class="optional">[</span>, <em>keyfile</em><span class="optional">[</span>, <em>uuid</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Directory.start_component" title="Permalink to this definition">¶</a></dt>
<dd><p>Add an entry to the Component table, and make this component the current
component for this directory. If no component name is given, the directory
name is used. If no <em>feature</em> is given, the current feature is used. If no
<em>flags</em> are given, the directory’s default flags are used. If no <em>keyfile</em>
is given, the KeyPath is left null in the Component table.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Directory.add_file">
<code class="descname">add_file</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>src</em><span class="optional">[</span>, <em>version</em><span class="optional">[</span>, <em>language</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Directory.add_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a file to the current component of the directory, starting a new one
if there is no current component. By default, the file name in the source
and the file table will be identical. If the <em>src</em> file is specified, it
is interpreted relative to the current directory. Optionally, a <em>version</em>
and a <em>language</em> can be specified for the entry in the File table.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Directory.glob">
<code class="descname">glob</code><span class="sig-paren">(</span><em>pattern</em><span class="optional">[</span>, <em>exclude</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Directory.glob" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a list of files to the current component as specified in the glob
pattern.  Individual files can be excluded in the <em>exclude</em> list.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Directory.remove_pyc">
<code class="descname">remove_pyc</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Directory.remove_pyc" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove <code class="docutils literal notranslate"><span class="pre">.pyc</span></code>/<code class="docutils literal notranslate"><span class="pre">.pyo</span></code> files on uninstall.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/directory_table.asp">Directory Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/file_table.asp">File Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/component_table.asp">Component Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/featurecomponents_table.asp">FeatureComponents Table</a></p>
</div>
</div>
<div class="section" id="features">
<span id="id4"></span><h2>35.1.8. Features<a class="headerlink" href="#features" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="msilib.Feature">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">Feature</code><span class="sig-paren">(</span><em>database</em>, <em>id</em>, <em>title</em>, <em>desc</em>, <em>display</em><span class="optional">[</span>, <em>level=1</em><span class="optional">[</span>, <em>parent</em><span class="optional">[</span>, <em>directory</em><span class="optional">[</span>, <em>attributes=0</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Feature" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a new record to the <code class="docutils literal notranslate"><span class="pre">Feature</span></code> table, using the values <em>id</em>, <em>parent.id</em>,
<em>title</em>, <em>desc</em>, <em>display</em>, <em>level</em>, <em>directory</em>, and <em>attributes</em>. The
resulting feature object can be passed to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_component()</span></code> method of
<a class="reference internal" href="#msilib.Directory" title="msilib.Directory"><code class="xref py py-class docutils literal notranslate"><span class="pre">Directory</span></code></a>.</p>
<dl class="method">
<dt id="msilib.Feature.set_current">
<code class="descname">set_current</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Feature.set_current" title="Permalink to this definition">¶</a></dt>
<dd><p>Make this feature the current feature of <a class="reference internal" href="#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a>. New components are
automatically added to the default feature, unless a feature is explicitly
specified.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/feature_table.asp">Feature Table</a></p>
</div>
</div>
<div class="section" id="gui-classes">
<span id="msi-gui"></span><h2>35.1.9. GUI classes<a class="headerlink" href="#gui-classes" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> provides several classes that wrap the GUI tables in an MSI
database. However, no standard user interface is provided; use
<a class="reference internal" href="../distutils/apiref.html#module-distutils.command.bdist_msi" title="distutils.command.bdist_msi: Build a binary distribution as a Windows MSI file"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdist_msi</span></code></a> to create MSI files with a user-interface
for installing Python packages.</p>
<dl class="class">
<dt id="msilib.Control">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">Control</code><span class="sig-paren">(</span><em>dlg</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Control" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class of the dialog controls. <em>dlg</em> is the dialog object the control
belongs to, and <em>name</em> is the control’s name.</p>
<dl class="method">
<dt id="msilib.Control.event">
<code class="descname">event</code><span class="sig-paren">(</span><em>event</em>, <em>argument</em><span class="optional">[</span>, <em>condition=1</em><span class="optional">[</span>, <em>ordering</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Control.event" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an entry into the <code class="docutils literal notranslate"><span class="pre">ControlEvent</span></code> table for this control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Control.mapping">
<code class="descname">mapping</code><span class="sig-paren">(</span><em>event</em>, <em>attribute</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Control.mapping" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an entry into the <code class="docutils literal notranslate"><span class="pre">EventMapping</span></code> table for this control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Control.condition">
<code class="descname">condition</code><span class="sig-paren">(</span><em>action</em>, <em>condition</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Control.condition" title="Permalink to this definition">¶</a></dt>
<dd><p>Make an entry into the <code class="docutils literal notranslate"><span class="pre">ControlCondition</span></code> table for this control.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="msilib.RadioButtonGroup">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">RadioButtonGroup</code><span class="sig-paren">(</span><em>dlg</em>, <em>name</em>, <em>property</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.RadioButtonGroup" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a radio button control named <em>name</em>. <em>property</em> is the installer property
that gets set when a radio button is selected.</p>
<dl class="method">
<dt id="msilib.RadioButtonGroup.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>text</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#msilib.RadioButtonGroup.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a radio button named <em>name</em> to the group, at the coordinates <em>x</em>, <em>y</em>,
<em>width</em>, <em>height</em>, and with the label <em>text</em>. If <em>value</em> is omitted, it
defaults to <em>name</em>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="msilib.Dialog">
<em class="property">class </em><code class="descclassname">msilib.</code><code class="descname">Dialog</code><span class="sig-paren">(</span><em>db</em>, <em>name</em>, <em>x</em>, <em>y</em>, <em>w</em>, <em>h</em>, <em>attr</em>, <em>title</em>, <em>first</em>, <em>default</em>, <em>cancel</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#msilib.Dialog" title="msilib.Dialog"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dialog</span></code></a> object. An entry in the <code class="docutils literal notranslate"><span class="pre">Dialog</span></code> table is made,
with the specified coordinates, dialog attributes, title, name of the first,
default, and cancel controls.</p>
<dl class="method">
<dt id="msilib.Dialog.control">
<code class="descname">control</code><span class="sig-paren">(</span><em>name</em>, <em>type</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>attributes</em>, <em>property</em>, <em>text</em>, <em>control_next</em>, <em>help</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.control" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#msilib.Control" title="msilib.Control"><code class="xref py py-class docutils literal notranslate"><span class="pre">Control</span></code></a> object. An entry in the <code class="docutils literal notranslate"><span class="pre">Control</span></code> table is
made with the specified parameters.</p>
<p>This is a generic method; for specific types, specialized methods are
provided.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.text">
<code class="descname">text</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>attributes</em>, <em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.text" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">Text</span></code> control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.bitmap">
<code class="descname">bitmap</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.bitmap" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">Bitmap</span></code> control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.line">
<code class="descname">line</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.line" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">Line</span></code> control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.pushbutton">
<code class="descname">pushbutton</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>attributes</em>, <em>text</em>, <em>next_control</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.pushbutton" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">PushButton</span></code> control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.radiogroup">
<code class="descname">radiogroup</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>attributes</em>, <em>property</em>, <em>text</em>, <em>next_control</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.radiogroup" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">RadioButtonGroup</span></code> control.</p>
</dd></dl>

<dl class="method">
<dt id="msilib.Dialog.checkbox">
<code class="descname">checkbox</code><span class="sig-paren">(</span><em>name</em>, <em>x</em>, <em>y</em>, <em>width</em>, <em>height</em>, <em>attributes</em>, <em>property</em>, <em>text</em>, <em>next_control</em><span class="sig-paren">)</span><a class="headerlink" href="#msilib.Dialog.checkbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Add and return a <code class="docutils literal notranslate"><span class="pre">CheckBox</span></code> control.</p>
</dd></dl>

</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/dialog_table.asp">Dialog Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/control_table.asp">Control Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controls.asp">Control Types</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlcondition_table.asp">ControlCondition Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/controlevent_table.asp">ControlEvent Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/eventmapping_table.asp">EventMapping Table</a>
<a class="reference external" href="https://msdn.microsoft.com/library?url=/library/en-us/msi/setup/radiobutton_table.asp">RadioButton Table</a></p>
</div>
</div>
<div class="section" id="precomputed-tables">
<span id="msi-tables"></span><h2>35.1.10. Precomputed tables<a class="headerlink" href="#precomputed-tables" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> provides a few subpackages that contain only schema and table
definitions. Currently, these definitions are based on MSI version 2.0.</p>
<dl class="data">
<dt id="msilib.schema">
<code class="descclassname">msilib.</code><code class="descname">schema</code><a class="headerlink" href="#msilib.schema" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the standard MSI schema for MSI 2.0, with the <em>tables</em> variable
providing a list of table definitions, and <em>_Validation_records</em> providing the
data for MSI validation.</p>
</dd></dl>

<dl class="data">
<dt id="msilib.sequence">
<code class="descclassname">msilib.</code><code class="descname">sequence</code><a class="headerlink" href="#msilib.sequence" title="Permalink to this definition">¶</a></dt>
<dd><p>This module contains table contents for the standard sequence tables:
<em>AdminExecuteSequence</em>, <em>AdminUISequence</em>, <em>AdvtExecuteSequence</em>,
<em>InstallExecuteSequence</em>, and <em>InstallUISequence</em>.</p>
</dd></dl>

<dl class="data">
<dt id="msilib.text">
<code class="descclassname">msilib.</code><code class="descname">text</code><a class="headerlink" href="#msilib.text" title="Permalink to this definition">¶</a></dt>
<dd><p>This module contains definitions for the UIText and ActionText tables, for the
standard installer actions.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a><ul>
<li><a class="reference internal" href="#database-objects">35.1.1. Database Objects</a></li>
<li><a class="reference internal" href="#view-objects">35.1.2. View Objects</a></li>
<li><a class="reference internal" href="#summary-information-objects">35.1.3. Summary Information Objects</a></li>
<li><a class="reference internal" href="#record-objects">35.1.4. Record Objects</a></li>
<li><a class="reference internal" href="#errors">35.1.5. Errors</a></li>
<li><a class="reference internal" href="#cab-objects">35.1.6. CAB Objects</a></li>
<li><a class="reference internal" href="#directory-objects">35.1.7. Directory Objects</a></li>
<li><a class="reference internal" href="#features">35.1.8. Features</a></li>
<li><a class="reference internal" href="#gui-classes">35.1.9. GUI classes</a></li>
<li><a class="reference internal" href="#precomputed-tables">35.1.10. Precomputed tables</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="windows.html"
                        title="previous chapter">35. MS Windows Specific Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="msvcrt.html"
                        title="next chapter">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/msilib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="msvcrt.html" title="35.2. msvcrt — Useful routines from the MS VC++ runtime"
             >next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="35. MS Windows Specific Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" >35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����R�Rhtml/library/msvcrt.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>35.2. msvcrt — Useful routines from the MS VC++ runtime &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="35.3. _winreg — Windows registry access" href="_winreg.html" />
    <link rel="prev" title="35.1. msilib — Read and write Microsoft Installer files" href="msilib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/msvcrt.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="_winreg.html" title="35.3. _winreg — Windows registry access"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="msilib.html" title="35.1. msilib — Read and write Microsoft Installer files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" accesskey="U">35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-msvcrt">
<span id="msvcrt-useful-routines-from-the-ms-vc-runtime"></span><h1>35.2. <a class="reference internal" href="#module-msvcrt" title="msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msvcrt</span></code></a> — Useful routines from the MS VC++ runtime<a class="headerlink" href="#module-msvcrt" title="Permalink to this headline">¶</a></h1>
<p>These functions provide access to some useful capabilities on Windows platforms.
Some higher-level modules use these functions to build the  Windows
implementations of their services.  For example, the <a class="reference internal" href="getpass.html#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> module uses
this in the implementation of the <a class="reference internal" href="getpass.html#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-func docutils literal notranslate"><span class="pre">getpass()</span></code></a> function.</p>
<p>Further documentation on these functions can be found in the Platform API
documentation.</p>
<p>The module implements both the normal and wide char variants of the console I/O
api. The normal API deals only with ASCII characters and is of limited use
for internationalized applications. The wide char API should be used where
ever possible.</p>
<div class="section" id="file-operations">
<span id="msvcrt-files"></span><h2>35.2.1. File Operations<a class="headerlink" href="#file-operations" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="msvcrt.locking">
<code class="descclassname">msvcrt.</code><code class="descname">locking</code><span class="sig-paren">(</span><em>fd</em>, <em>mode</em>, <em>nbytes</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.locking" title="Permalink to this definition">¶</a></dt>
<dd><p>Lock part of a file based on file descriptor <em>fd</em> from the C runtime.  Raises
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> on failure.  The locked region of the file extends from the
current file position for <em>nbytes</em> bytes, and may continue beyond the end of the
file.  <em>mode</em> must be one of the <code class="xref py py-const docutils literal notranslate"><span class="pre">LK_*</span></code> constants listed below. Multiple
regions in a file may be locked at the same time, but may not overlap.  Adjacent
regions are not merged; they must be unlocked individually.</p>
</dd></dl>

<dl class="data">
<dt id="msvcrt.LK_LOCK">
<code class="descclassname">msvcrt.</code><code class="descname">LK_LOCK</code><a class="headerlink" href="#msvcrt.LK_LOCK" title="Permalink to this definition">¶</a></dt>
<dt id="msvcrt.LK_RLCK">
<code class="descclassname">msvcrt.</code><code class="descname">LK_RLCK</code><a class="headerlink" href="#msvcrt.LK_RLCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Locks the specified bytes. If the bytes cannot be locked, the program
immediately tries again after 1 second.  If, after 10 attempts, the bytes cannot
be locked, <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.</p>
</dd></dl>

<dl class="data">
<dt id="msvcrt.LK_NBLCK">
<code class="descclassname">msvcrt.</code><code class="descname">LK_NBLCK</code><a class="headerlink" href="#msvcrt.LK_NBLCK" title="Permalink to this definition">¶</a></dt>
<dt id="msvcrt.LK_NBRLCK">
<code class="descclassname">msvcrt.</code><code class="descname">LK_NBRLCK</code><a class="headerlink" href="#msvcrt.LK_NBRLCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Locks the specified bytes. If the bytes cannot be locked, <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is
raised.</p>
</dd></dl>

<dl class="data">
<dt id="msvcrt.LK_UNLCK">
<code class="descclassname">msvcrt.</code><code class="descname">LK_UNLCK</code><a class="headerlink" href="#msvcrt.LK_UNLCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Unlocks the specified bytes, which must have been previously locked.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.setmode">
<code class="descclassname">msvcrt.</code><code class="descname">setmode</code><span class="sig-paren">(</span><em>fd</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.setmode" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the line-end translation mode for the file descriptor <em>fd</em>. To set it to
text mode, <em>flags</em> should be <a class="reference internal" href="os.html#os.O_TEXT" title="os.O_TEXT"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_TEXT</span></code></a>; for binary, it should be
<a class="reference internal" href="os.html#os.O_BINARY" title="os.O_BINARY"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_BINARY</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.open_osfhandle">
<code class="descclassname">msvcrt.</code><code class="descname">open_osfhandle</code><span class="sig-paren">(</span><em>handle</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.open_osfhandle" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a C runtime file descriptor from the file handle <em>handle</em>.  The <em>flags</em>
parameter should be a bitwise OR of <a class="reference internal" href="os.html#os.O_APPEND" title="os.O_APPEND"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_APPEND</span></code></a>, <a class="reference internal" href="os.html#os.O_RDONLY" title="os.O_RDONLY"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_RDONLY</span></code></a>,
and <a class="reference internal" href="os.html#os.O_TEXT" title="os.O_TEXT"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_TEXT</span></code></a>.  The returned file descriptor may be used as a parameter
to <a class="reference internal" href="os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a> to create a file object.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.get_osfhandle">
<code class="descclassname">msvcrt.</code><code class="descname">get_osfhandle</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.get_osfhandle" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file handle for the file descriptor <em>fd</em>.  Raises <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if
<em>fd</em> is not recognized.</p>
</dd></dl>

</div>
<div class="section" id="console-i-o">
<span id="msvcrt-console"></span><h2>35.2.2. Console I/O<a class="headerlink" href="#console-i-o" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="msvcrt.kbhit">
<code class="descclassname">msvcrt.</code><code class="descname">kbhit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.kbhit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if a keypress is waiting to be read.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.getch">
<code class="descclassname">msvcrt.</code><code class="descname">getch</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.getch" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a keypress and return the resulting character.  Nothing is echoed to the
console.  This call will block if a keypress is not already available, but will
not wait for <kbd class="kbd docutils literal notranslate">Enter</kbd> to be pressed. If the pressed key was a special
function key, this will return <code class="docutils literal notranslate"><span class="pre">'\000'</span></code> or <code class="docutils literal notranslate"><span class="pre">'\xe0'</span></code>; the next call will
return the keycode.  The <kbd class="kbd docutils literal notranslate">Control-C</kbd> keypress cannot be read with this
function.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.getwch">
<code class="descclassname">msvcrt.</code><code class="descname">getwch</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.getwch" title="Permalink to this definition">¶</a></dt>
<dd><p>Wide char variant of <a class="reference internal" href="#msvcrt.getch" title="msvcrt.getch"><code class="xref py py-func docutils literal notranslate"><span class="pre">getch()</span></code></a>, returning a Unicode value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="msvcrt.getche">
<code class="descclassname">msvcrt.</code><code class="descname">getche</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.getche" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#msvcrt.getch" title="msvcrt.getch"><code class="xref py py-func docutils literal notranslate"><span class="pre">getch()</span></code></a>, but the keypress will be echoed if it  represents a
printable character.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.getwche">
<code class="descclassname">msvcrt.</code><code class="descname">getwche</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.getwche" title="Permalink to this definition">¶</a></dt>
<dd><p>Wide char variant of <a class="reference internal" href="#msvcrt.getche" title="msvcrt.getche"><code class="xref py py-func docutils literal notranslate"><span class="pre">getche()</span></code></a>, returning a Unicode value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="msvcrt.putch">
<code class="descclassname">msvcrt.</code><code class="descname">putch</code><span class="sig-paren">(</span><em>char</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.putch" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the character <em>char</em> to the console without buffering.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.putwch">
<code class="descclassname">msvcrt.</code><code class="descname">putwch</code><span class="sig-paren">(</span><em>unicode_char</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.putwch" title="Permalink to this definition">¶</a></dt>
<dd><p>Wide char variant of <a class="reference internal" href="#msvcrt.putch" title="msvcrt.putch"><code class="xref py py-func docutils literal notranslate"><span class="pre">putch()</span></code></a>, accepting a Unicode value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="msvcrt.ungetch">
<code class="descclassname">msvcrt.</code><code class="descname">ungetch</code><span class="sig-paren">(</span><em>char</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.ungetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Cause the character <em>char</em> to be “pushed back” into the console buffer; it will
be the next character read by <a class="reference internal" href="#msvcrt.getch" title="msvcrt.getch"><code class="xref py py-func docutils literal notranslate"><span class="pre">getch()</span></code></a> or <a class="reference internal" href="#msvcrt.getche" title="msvcrt.getche"><code class="xref py py-func docutils literal notranslate"><span class="pre">getche()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="msvcrt.ungetwch">
<code class="descclassname">msvcrt.</code><code class="descname">ungetwch</code><span class="sig-paren">(</span><em>unicode_char</em><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.ungetwch" title="Permalink to this definition">¶</a></dt>
<dd><p>Wide char variant of <a class="reference internal" href="#msvcrt.ungetch" title="msvcrt.ungetch"><code class="xref py py-func docutils literal notranslate"><span class="pre">ungetch()</span></code></a>, accepting a Unicode value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="other-functions">
<span id="msvcrt-other"></span><h2>35.2.3. Other Functions<a class="headerlink" href="#other-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="msvcrt.heapmin">
<code class="descclassname">msvcrt.</code><code class="descname">heapmin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#msvcrt.heapmin" title="Permalink to this definition">¶</a></dt>
<dd><p>Force the <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> heap to clean itself up and return unused blocks to
the operating system.  On failure, this raises <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a><ul>
<li><a class="reference internal" href="#file-operations">35.2.1. File Operations</a></li>
<li><a class="reference internal" href="#console-i-o">35.2.2. Console I/O</a></li>
<li><a class="reference internal" href="#other-functions">35.2.3. Other Functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="msilib.html"
                        title="previous chapter">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="_winreg.html"
                        title="next chapter">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/msvcrt.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="_winreg.html" title="35.3. _winreg — Windows registry access"
             >next</a> |</li>
        <li class="right" >
          <a href="msilib.html" title="35.1. msilib — Read and write Microsoft Installer files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" >35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�:b�f�fhtml/library/multifile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.10. multifile — Support for files containing distinct parts &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.11. rfc822 — Parse RFC 2822 mail headers" href="rfc822.html" />
    <link rel="prev" title="18.9. mimify — MIME processing of mail messages" href="mimify.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/multifile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rfc822.html" title="18.11. rfc822 — Parse RFC 2822 mail headers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mimify.html" title="18.9. mimify — MIME processing of mail messages"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-multifile">
<span id="multifile-support-for-files-containing-distinct-parts"></span><h1>18.10. <a class="reference internal" href="#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a> — Support for files containing distinct parts<a class="headerlink" href="#module-multifile" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.5: </span>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package should be used in preference to the <a class="reference internal" href="#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a>
module. This module is present only to maintain backward compatibility.</p>
</div>
<p>The <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> object enables you to treat sections of a text file as
file-like input objects, with <code class="docutils literal notranslate"><span class="pre">''</span></code> being returned by <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> when a
given delimiter pattern is encountered.  The defaults of this class are designed
to make it useful for parsing MIME multipart messages, but by subclassing it and
overriding methods  it can be easily adapted for more general use.</p>
<dl class="class">
<dt id="multifile.MultiFile">
<em class="property">class </em><code class="descclassname">multifile.</code><code class="descname">MultiFile</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>seekable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a multi-file.  You must instantiate this class with an input object
argument for the <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> instance to get lines from, such as a file
object returned by <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>
<p><a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> only ever looks at the input object’s <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>,
<a class="reference internal" href="#multifile.MultiFile.seek" title="multifile.MultiFile.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> and <a class="reference internal" href="#multifile.MultiFile.tell" title="multifile.MultiFile.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> methods, and the latter two are only needed if you
want random access to the individual MIME parts. To use <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> on a
non-seekable stream object, set the optional <em>seekable</em> argument to false; this
will prevent using the input object’s <a class="reference internal" href="#multifile.MultiFile.seek" title="multifile.MultiFile.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> and <a class="reference internal" href="#multifile.MultiFile.tell" title="multifile.MultiFile.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> methods.</p>
</dd></dl>

<p>It will be useful to know that in <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a>’s view of the world, text
is composed of three kinds of lines: data, section-dividers, and end-markers.
MultiFile is designed to support parsing of messages that may have multiple
nested message parts, each with its own pattern for section-divider and
end-marker lines.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a></dt>
<dd>Comprehensive email handling package; supersedes the <a class="reference internal" href="#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a> module.</dd>
</dl>
</div>
<div class="section" id="multifile-objects">
<span id="id1"></span><h2>18.10.1. MultiFile Objects<a class="headerlink" href="#multifile-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="multifile.MultiFile.readline">
<code class="descclassname">MultiFile.</code><code class="descname">readline</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a line.  If the line is data (not a section-divider or end-marker or real
EOF) return it.  If the line matches the most-recently-stacked boundary, return
<code class="docutils literal notranslate"><span class="pre">''</span></code> and set <code class="docutils literal notranslate"><span class="pre">self.last</span></code> to 1 or 0 according as the match is or is not an
end-marker.  If the line matches any other stacked boundary, raise an error.  On
encountering end-of-file on the underlying stream object, the method raises
<code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code> unless all boundaries have been popped.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.readlines">
<code class="descclassname">MultiFile.</code><code class="descname">readlines</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all lines remaining in this part as a list of strings.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.read">
<code class="descclassname">MultiFile.</code><code class="descname">read</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read all lines, up to the next section.  Return them as a single (multiline)
string.  Note that this doesn’t take a size argument!</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.seek">
<code class="descclassname">MultiFile.</code><code class="descname">seek</code><span class="sig-paren">(</span><em>pos</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Seek.  Seek indices are relative to the start of the current section. The <em>pos</em>
and <em>whence</em> arguments are interpreted as for a file seek.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.tell">
<code class="descclassname">MultiFile.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file position relative to the start of the current section.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.next">
<code class="descclassname">MultiFile.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Skip lines to the next section (that is, read lines until a section-divider or
end-marker has been consumed).  Return true if there is such a section, false if
an end-marker is seen.  Re-enable the most-recently-pushed boundary.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.is_data">
<code class="descclassname">MultiFile.</code><code class="descname">is_data</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.is_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>str</em> is data and false if it might be a section boundary.  As
written, it tests for a prefix other than <code class="docutils literal notranslate"><span class="pre">'-</span></code><code class="docutils literal notranslate"><span class="pre">-'</span></code> at start of line (which
all MIME boundaries have) but it is declared so it can be overridden in derived
classes.</p>
<p>Note that this test is used intended as a fast guard for the real boundary
tests; if it always returns false it will merely slow processing, not cause it
to fail.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.push">
<code class="descclassname">MultiFile.</code><code class="descname">push</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.push" title="Permalink to this definition">¶</a></dt>
<dd><p>Push a boundary string.  When a decorated version of this boundary  is found as
an input line, it will be interpreted as a section-divider  or end-marker
(depending on the decoration, see <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2045.html"><strong>RFC 2045</strong></a>).  All subsequent reads will
return the empty string to indicate end-of-file, until a call to <a class="reference internal" href="#multifile.MultiFile.pop" title="multifile.MultiFile.pop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code></a>
removes the boundary a or <a class="reference internal" href="#multifile.MultiFile.next" title="multifile.MultiFile.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> call reenables it.</p>
<p>It is possible to push more than one boundary.  Encountering the
most-recently-pushed boundary will return EOF; encountering any other
boundary will raise an error.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.pop">
<code class="descclassname">MultiFile.</code><code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Pop a section boundary.  This boundary will no longer be interpreted as EOF.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.section_divider">
<code class="descclassname">MultiFile.</code><code class="descname">section_divider</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.section_divider" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn a boundary into a section-divider line.  By default, this method
prepends <code class="docutils literal notranslate"><span class="pre">'--'</span></code> (which MIME section boundaries have) but it is declared so
it can be overridden in derived classes.  This method need not append LF or
CR-LF, as comparison with the result ignores trailing whitespace.</p>
</dd></dl>

<dl class="method">
<dt id="multifile.MultiFile.end_marker">
<code class="descclassname">MultiFile.</code><code class="descname">end_marker</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#multifile.MultiFile.end_marker" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn a boundary string into an end-marker line.  By default, this method
prepends <code class="docutils literal notranslate"><span class="pre">'--'</span></code> and appends <code class="docutils literal notranslate"><span class="pre">'--'</span></code> (like a MIME-multipart end-of-message
marker) but it is declared so it can be overridden in derived classes.  This
method need not append LF or CR-LF, as comparison with the result ignores
trailing whitespace.</p>
</dd></dl>

<p>Finally, <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> instances have two public instance variables:</p>
<dl class="attribute">
<dt id="multifile.MultiFile.level">
<code class="descclassname">MultiFile.</code><code class="descname">level</code><a class="headerlink" href="#multifile.MultiFile.level" title="Permalink to this definition">¶</a></dt>
<dd><p>Nesting depth of the current part.</p>
</dd></dl>

<dl class="attribute">
<dt id="multifile.MultiFile.last">
<code class="descclassname">MultiFile.</code><code class="descname">last</code><a class="headerlink" href="#multifile.MultiFile.last" title="Permalink to this definition">¶</a></dt>
<dd><p>True if the last end-of-file was for an end-of-message marker.</p>
</dd></dl>

</div>
<div class="section" id="multifile-example">
<span id="id2"></span><h2>18.10.2. <a class="reference internal" href="#multifile.MultiFile" title="multifile.MultiFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiFile</span></code></a> Example<a class="headerlink" href="#multifile-example" title="Permalink to this headline">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mimetools</span>
<span class="kn">import</span> <span class="nn">multifile</span>
<span class="kn">import</span> <span class="nn">StringIO</span>

<span class="k">def</span> <span class="nf">extract_mime_part_matching</span><span class="p">(</span><span class="n">stream</span><span class="p">,</span> <span class="n">mimetype</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Return the first element in a multipart MIME message on stream</span>
<span class="sd">    matching mimetype.&quot;&quot;&quot;</span>

    <span class="n">msg</span> <span class="o">=</span> <span class="n">mimetools</span><span class="o">.</span><span class="n">Message</span><span class="p">(</span><span class="n">stream</span><span class="p">)</span>
    <span class="n">msgtype</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">gettype</span><span class="p">()</span>
    <span class="n">params</span> <span class="o">=</span> <span class="n">msg</span><span class="o">.</span><span class="n">getplist</span><span class="p">()</span>

    <span class="n">data</span> <span class="o">=</span> <span class="n">StringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">msgtype</span><span class="p">[:</span><span class="mi">10</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&quot;multipart/&quot;</span><span class="p">:</span>

        <span class="n">file</span> <span class="o">=</span> <span class="n">multifile</span><span class="o">.</span><span class="n">MultiFile</span><span class="p">(</span><span class="n">stream</span><span class="p">)</span>
        <span class="n">file</span><span class="o">.</span><span class="n">push</span><span class="p">(</span><span class="n">msg</span><span class="o">.</span><span class="n">getparam</span><span class="p">(</span><span class="s2">&quot;boundary&quot;</span><span class="p">))</span>
        <span class="k">while</span> <span class="n">file</span><span class="o">.</span><span class="n">next</span><span class="p">():</span>
            <span class="n">submsg</span> <span class="o">=</span> <span class="n">mimetools</span><span class="o">.</span><span class="n">Message</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">data</span> <span class="o">=</span> <span class="n">StringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
                <span class="n">mimetools</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="n">submsg</span><span class="o">.</span><span class="n">getencoding</span><span class="p">())</span>
            <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
                <span class="k">continue</span>
            <span class="k">if</span> <span class="n">submsg</span><span class="o">.</span><span class="n">gettype</span><span class="p">()</span> <span class="o">==</span> <span class="n">mimetype</span><span class="p">:</span>
                <span class="k">break</span>
        <span class="n">file</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">data</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a><ul>
<li><a class="reference internal" href="#multifile-objects">18.10.1. MultiFile Objects</a></li>
<li><a class="reference internal" href="#multifile-example">18.10.2. <code class="docutils literal notranslate"><span class="pre">MultiFile</span></code> Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mimify.html"
                        title="previous chapter">18.9. <code class="docutils literal notranslate"><span class="pre">mimify</span></code> — MIME processing of mail messages</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="rfc822.html"
                        title="next chapter">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/multifile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rfc822.html" title="18.11. rfc822 — Parse RFC 2822 mail headers"
             >next</a> |</li>
        <li class="right" >
          <a href="mimify.html" title="18.9. mimify — MIME processing of mail messages"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��^�GSGS!html/library/multiprocessing.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.6. multiprocessing — Process-based “threading” interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.7. mmap — Memory-mapped file support" href="mmap.html" />
    <link rel="prev" title="16.5. dummy_thread — Drop-in replacement for the thread module" href="dummy_thread.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/multiprocessing.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mmap.html" title="16.7. mmap — Memory-mapped file support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dummy_thread.html" title="16.5. dummy_thread — Drop-in replacement for the thread module"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-multiprocessing">
<span id="multiprocessing-process-based-threading-interface"></span><h1>16.6. <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> — Process-based “threading” interface<a class="headerlink" href="#module-multiprocessing" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="section" id="introduction">
<h2>16.6.1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> is a package that supports spawning processes using an
API similar to the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.  The <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> package
offers both local and remote concurrency, effectively side-stepping the
<a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">Global Interpreter Lock</span></a> by using subprocesses instead of threads.  Due
to this, the <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module allows the programmer to fully
leverage multiple processors on a given machine.  It runs on both Unix and
Windows.</p>
<p>The <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module also introduces APIs which do not have
analogs in the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.  A prime example of this is the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> object which offers a convenient means of parallelizing the
execution of a function across multiple input values, distributing the
input data across processes (data parallelism).  The following example
demonstrates the common practice of defining such functions in a module so
that child processes can successfully import that module.  This basic example
of data parallelism using <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code>,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Pool</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]))</span>
</pre></div>
</div>
<p>will print to standard output</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">9</span><span class="p">]</span>
</pre></div>
</div>
<div class="section" id="the-process-class">
<h3>16.6.1.1. The <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> class<a class="headerlink" href="#the-process-class" title="Permalink to this headline">¶</a></h3>
<p>In <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>, processes are spawned by creating a <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a>
object and then calling its <a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> method.  <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a>
follows the API of <a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Thread</span></code></a>.  A trivial example of a
multiprocess program is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;hello&#39;</span><span class="p">,</span> <span class="n">name</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;bob&#39;</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>To show the individual process IDs involved, here is an expanded example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">def</span> <span class="nf">info</span><span class="p">(</span><span class="n">title</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">title</span>
    <span class="nb">print</span> <span class="s1">&#39;module name:&#39;</span><span class="p">,</span> <span class="vm">__name__</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">os</span><span class="p">,</span> <span class="s1">&#39;getppid&#39;</span><span class="p">):</span>  <span class="c1"># only available on Unix</span>
        <span class="nb">print</span> <span class="s1">&#39;parent process:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">getppid</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s1">&#39;process id:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
    <span class="n">info</span><span class="p">(</span><span class="s1">&#39;function f&#39;</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s1">&#39;hello&#39;</span><span class="p">,</span> <span class="n">name</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">info</span><span class="p">(</span><span class="s1">&#39;main line&#39;</span><span class="p">)</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;bob&#39;</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>For an explanation of why (on Windows) the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__'</span></code> part is
necessary, see <a class="reference internal" href="#multiprocessing-programming"><span class="std std-ref">Programming guidelines</span></a>.</p>
</div>
<div class="section" id="exchanging-objects-between-processes">
<h3>16.6.1.2. Exchanging objects between processes<a class="headerlink" href="#exchanging-objects-between-processes" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> supports two types of communication channel between
processes:</p>
<p><strong>Queues</strong></p>
<blockquote>
<div><p>The <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> class is a near clone of <a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a>.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">q</span><span class="p">):</span>
    <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">([</span><span class="mi">42</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">])</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">q</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">q</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="nb">print</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>    <span class="c1"># prints &quot;[42, None, &#39;hello&#39;]&quot;</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>Queues are thread and process safe.</p>
</div></blockquote>
<p><strong>Pipes</strong></p>
<blockquote>
<div><p>The <a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe()</span></code></a> function returns a pair of connection objects connected by a
pipe which by default is duplex (two-way).  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Pipe</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">conn</span><span class="p">):</span>
    <span class="n">conn</span><span class="o">.</span><span class="n">send</span><span class="p">([</span><span class="mi">42</span><span class="p">,</span> <span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">])</span>
    <span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">parent_conn</span><span class="p">,</span> <span class="n">child_conn</span> <span class="o">=</span> <span class="n">Pipe</span><span class="p">()</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">child_conn</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="nb">print</span> <span class="n">parent_conn</span><span class="o">.</span><span class="n">recv</span><span class="p">()</span>   <span class="c1"># prints &quot;[42, None, &#39;hello&#39;]&quot;</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
</pre></div>
</div>
<p>The two connection objects returned by <a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe()</span></code></a> represent the two ends of
the pipe.  Each connection object has <a class="reference internal" href="#Connection.send" title="Connection.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> and
<a class="reference internal" href="#Connection.recv" title="Connection.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> methods (among others).  Note that data in a pipe
may become corrupted if two processes (or threads) try to read from or write
to the <em>same</em> end of the pipe at the same time.  Of course there is no risk
of corruption from processes using different ends of the pipe at the same
time.</p>
</div></blockquote>
</div>
<div class="section" id="synchronization-between-processes">
<h3>16.6.1.3. Synchronization between processes<a class="headerlink" href="#synchronization-between-processes" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> contains equivalents of all the synchronization
primitives from <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>.  For instance one can use a lock to ensure
that only one process prints to standard output at a time:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Lock</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">l</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
    <span class="n">l</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s1">&#39;hello world&#39;</span><span class="p">,</span> <span class="n">i</span>
    <span class="n">l</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">lock</span> <span class="o">=</span> <span class="n">Lock</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">lock</span><span class="p">,</span> <span class="n">num</span><span class="p">))</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
<p>Without using the lock output from the different processes is liable to get all
mixed up.</p>
</div>
<div class="section" id="sharing-state-between-processes">
<h3>16.6.1.4. Sharing state between processes<a class="headerlink" href="#sharing-state-between-processes" title="Permalink to this headline">¶</a></h3>
<p>As mentioned above, when doing concurrent programming it is usually best to
avoid using shared state as far as possible.  This is particularly true when
using multiple processes.</p>
<p>However, if you really do need to use some shared data then
<a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> provides a couple of ways of doing so.</p>
<p><strong>Shared memory</strong></p>
<blockquote>
<div><p>Data can be stored in a shared memory map using <a class="reference internal" href="#multiprocessing.Value" title="multiprocessing.Value"><code class="xref py py-class docutils literal notranslate"><span class="pre">Value</span></code></a> or
<a class="reference internal" href="#multiprocessing.Array" title="multiprocessing.Array"><code class="xref py py-class docutils literal notranslate"><span class="pre">Array</span></code></a>.  For example, the following code</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Value</span><span class="p">,</span> <span class="n">Array</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">a</span><span class="p">):</span>
    <span class="n">n</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="mf">3.1415927</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)):</span>
        <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="o">-</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">num</span> <span class="o">=</span> <span class="n">Value</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">)</span>
    <span class="n">arr</span> <span class="o">=</span> <span class="n">Array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="n">arr</span><span class="p">))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="nb">print</span> <span class="n">num</span><span class="o">.</span><span class="n">value</span>
    <span class="nb">print</span> <span class="n">arr</span><span class="p">[:]</span>
</pre></div>
</div>
<p>will print</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">3.1415927</span>
<span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">,</span> <span class="o">-</span><span class="mi">6</span><span class="p">,</span> <span class="o">-</span><span class="mi">7</span><span class="p">,</span> <span class="o">-</span><span class="mi">8</span><span class="p">,</span> <span class="o">-</span><span class="mi">9</span><span class="p">]</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">'d'</span></code> and <code class="docutils literal notranslate"><span class="pre">'i'</span></code> arguments used when creating <code class="docutils literal notranslate"><span class="pre">num</span></code> and <code class="docutils literal notranslate"><span class="pre">arr</span></code> are
typecodes of the kind used by the <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module: <code class="docutils literal notranslate"><span class="pre">'d'</span></code> indicates a
double precision float and <code class="docutils literal notranslate"><span class="pre">'i'</span></code> indicates a signed integer.  These shared
objects will be process and thread-safe.</p>
<p>For more flexibility in using shared memory one can use the
<a class="reference internal" href="#module-multiprocessing.sharedctypes" title="multiprocessing.sharedctypes: Allocate ctypes objects from shared memory."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code></a> module which supports the creation of
arbitrary ctypes objects allocated from shared memory.</p>
</div></blockquote>
<p><strong>Server process</strong></p>
<blockquote>
<div><p>A manager object returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">Manager()</span></code> controls a server process which
holds Python objects and allows other processes to manipulate them using
proxies.</p>
<p>A manager returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">Manager()</span></code> will support types <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <a class="reference internal" href="#multiprocessing.managers.Namespace" title="multiprocessing.managers.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a>, <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>, <a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>,
<a class="reference internal" href="#multiprocessing.Semaphore" title="multiprocessing.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a>, <a class="reference internal" href="#multiprocessing.BoundedSemaphore" title="multiprocessing.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a>, <a class="reference internal" href="#multiprocessing.Condition" title="multiprocessing.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">Condition</span></code></a>,
<a class="reference internal" href="#multiprocessing.Event" title="multiprocessing.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a>, <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, <a class="reference internal" href="#multiprocessing.Value" title="multiprocessing.Value"><code class="xref py py-class docutils literal notranslate"><span class="pre">Value</span></code></a> and <a class="reference internal" href="#multiprocessing.Array" title="multiprocessing.Array"><code class="xref py py-class docutils literal notranslate"><span class="pre">Array</span></code></a>.  For
example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Manager</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">l</span><span class="p">):</span>
    <span class="n">d</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;1&#39;</span>
    <span class="n">d</span><span class="p">[</span><span class="s1">&#39;2&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span>
    <span class="n">d</span><span class="p">[</span><span class="mf">0.25</span><span class="p">]</span> <span class="o">=</span> <span class="kc">None</span>
    <span class="n">l</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">manager</span> <span class="o">=</span> <span class="n">Manager</span><span class="p">()</span>

    <span class="n">d</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">dict</span><span class="p">()</span>
    <span class="n">l</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">l</span><span class="p">))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="nb">print</span> <span class="n">d</span>
    <span class="nb">print</span> <span class="n">l</span>
</pre></div>
</div>
<p>will print</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span><span class="mf">0.25</span><span class="p">:</span> <span class="kc">None</span><span class="p">,</span> <span class="mi">1</span><span class="p">:</span> <span class="s1">&#39;1&#39;</span><span class="p">,</span> <span class="s1">&#39;2&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>
<span class="p">[</span><span class="mi">9</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>Server process managers are more flexible than using shared memory objects
because they can be made to support arbitrary object types.  Also, a single
manager can be shared by processes on different computers over a network.
They are, however, slower than using shared memory.</p>
</div></blockquote>
</div>
<div class="section" id="using-a-pool-of-workers">
<h3>16.6.1.5. Using a pool of workers<a class="headerlink" href="#using-a-pool-of-workers" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> class represents a pool of worker
processes.  It has methods which allows tasks to be offloaded to the worker
processes in a few different ways.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Pool</span><span class="p">,</span> <span class="ne">TimeoutError</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="n">processes</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>              <span class="c1"># start 4 worker processes</span>

    <span class="c1"># print &quot;[0, 1, 4,..., 81]&quot;</span>
    <span class="nb">print</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>

    <span class="c1"># print same numbers in arbitrary order</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap_unordered</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)):</span>
        <span class="nb">print</span> <span class="n">i</span>

    <span class="c1"># evaluate &quot;f(20)&quot; asynchronously</span>
    <span class="n">res</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="mi">20</span><span class="p">,))</span>      <span class="c1"># runs in *only* one process</span>
    <span class="nb">print</span> <span class="n">res</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>              <span class="c1"># prints &quot;400&quot;</span>

    <span class="c1"># evaluate &quot;os.getpid()&quot; asynchronously</span>
    <span class="n">res</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">,</span> <span class="p">())</span> <span class="c1"># runs in *only* one process</span>
    <span class="nb">print</span> <span class="n">res</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>              <span class="c1"># prints the PID of that process</span>

    <span class="c1"># launching multiple evaluations asynchronously *may* use more processes</span>
    <span class="n">multiple_results</span> <span class="o">=</span> <span class="p">[</span><span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">,</span> <span class="p">())</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)]</span>
    <span class="nb">print</span> <span class="p">[</span><span class="n">res</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="k">for</span> <span class="n">res</span> <span class="ow">in</span> <span class="n">multiple_results</span><span class="p">]</span>

    <span class="c1"># make a single worker sleep for 10 secs</span>
    <span class="n">res</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="p">(</span><span class="mi">10</span><span class="p">,))</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">res</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">TimeoutError</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;We lacked patience and got a multiprocessing.TimeoutError&quot;</span>
</pre></div>
</div>
<p>Note that the methods of a pool should only ever be used by the
process which created it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Functionality within this package requires that the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> module be
importable by the children. This is covered in <a class="reference internal" href="#multiprocessing-programming"><span class="std std-ref">Programming guidelines</span></a>
however it is worth pointing out here. This means that some examples, such
as the <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> examples will not work in the interactive interpreter.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Pool</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="go">Process PoolWorker-1:</span>
<span class="go">Process PoolWorker-2:</span>
<span class="go">Process PoolWorker-3:</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;module&#39; object has no attribute &#39;f&#39;</span>
<span class="go">AttributeError: &#39;module&#39; object has no attribute &#39;f&#39;</span>
<span class="go">AttributeError: &#39;module&#39; object has no attribute &#39;f&#39;</span>
</pre></div>
</div>
<p class="last">(If you try this it will actually output three full tracebacks
interleaved in a semi-random fashion, and then you may have to
stop the master process somehow.)</p>
</div>
</div>
</div>
<div class="section" id="reference">
<h2>16.6.2. Reference<a class="headerlink" href="#reference" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> package mostly replicates the API of the
<a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.</p>
<div class="section" id="process-and-exceptions">
<h3>16.6.2.1. <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> and exceptions<a class="headerlink" href="#process-and-exceptions" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="multiprocessing.Process">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Process</code><span class="sig-paren">(</span><em>group=None</em>, <em>target=None</em>, <em>name=None</em>, <em>args=()</em>, <em>kwargs={}</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process" title="Permalink to this definition">¶</a></dt>
<dd><p>Process objects represent activity that is run in a separate process. The
<a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> class has equivalents of all the methods of
<a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Thread</span></code></a>.</p>
<p>The constructor should always be called with keyword arguments. <em>group</em>
should always be <code class="docutils literal notranslate"><span class="pre">None</span></code>; it exists solely for compatibility with
<a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Thread</span></code></a>.  <em>target</em> is the callable object to be invoked by
the <a class="reference internal" href="#multiprocessing.Process.run" title="multiprocessing.Process.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method.  It defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning nothing is
called. <em>name</em> is the process name.  By default, a unique name is constructed
of the form ‘Process-N<sub>1</sub>:N<sub>2</sub>:…:N<sub>k</sub>’ where N<sub>1</sub>,N<sub>2</sub>,…,N<sub>k</sub> is a sequence of integers whose length
is determined by the <em>generation</em> of the process.  <em>args</em> is the argument
tuple for the target invocation.  <em>kwargs</em> is a dictionary of keyword
arguments for the target invocation.  By default, no arguments are passed to
<em>target</em>.</p>
<p>If a subclass overrides the constructor, it must make sure it invokes the
base class constructor (<code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.__init__()</span></code>) before doing anything else
to the process.</p>
<dl class="method">
<dt id="multiprocessing.Process.run">
<code class="descname">run</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Method representing the process’s activity.</p>
<p>You may override this method in a subclass.  The standard <a class="reference internal" href="#multiprocessing.Process.run" title="multiprocessing.Process.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>
method invokes the callable object passed to the object’s constructor as
the target argument, if any, with sequential and keyword arguments taken
from the <em>args</em> and <em>kwargs</em> arguments, respectively.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Process.start">
<code class="descname">start</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Start the process’s activity.</p>
<p>This must be called at most once per process object.  It arranges for the
object’s <a class="reference internal" href="#multiprocessing.Process.run" title="multiprocessing.Process.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method to be invoked in a separate process.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Process.join">
<code class="descname">join</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Block the calling thread until the process whose <a class="reference internal" href="#multiprocessing.Process.join" title="multiprocessing.Process.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method is
called terminates or until the optional timeout occurs.</p>
<p>If <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then there is no timeout.</p>
<p>A process can be joined many times.</p>
<p>A process cannot join itself because this would cause a deadlock.  It is
an error to attempt to join a process before it has been started.</p>
</dd></dl>

<dl class="attribute">
<dt id="multiprocessing.Process.name">
<code class="descname">name</code><a class="headerlink" href="#multiprocessing.Process.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The process’s name.</p>
<p>The name is a string used for identification purposes only.  It has no
semantics.  Multiple processes may be given the same name.  The initial
name is set by the constructor.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Process.is_alive">
<code class="descname">is_alive</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process.is_alive" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the process is alive.</p>
<p>Roughly, a process object is alive from the moment the <a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>
method returns until the child process terminates.</p>
</dd></dl>

<dl class="attribute">
<dt id="multiprocessing.Process.daemon">
<code class="descname">daemon</code><a class="headerlink" href="#multiprocessing.Process.daemon" title="Permalink to this definition">¶</a></dt>
<dd><p>The process’s daemon flag, a Boolean value.  This must be set before
<a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> is called.</p>
<p>The initial value is inherited from the creating process.</p>
<p>When a process exits, it attempts to terminate all of its daemonic child
processes.</p>
<p>Note that a daemonic process is not allowed to create child processes.
Otherwise a daemonic process would leave its children orphaned if it gets
terminated when its parent process exits. Additionally, these are <strong>not</strong>
Unix daemons or services, they are normal processes that will be
terminated (and not joined) if non-daemonic processes have exited.</p>
</dd></dl>

<p>In addition to the  <a class="reference internal" href="threading.html#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Thread</span></code></a> API, <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> objects
also support the following attributes and methods:</p>
<dl class="attribute">
<dt id="multiprocessing.Process.pid">
<code class="descname">pid</code><a class="headerlink" href="#multiprocessing.Process.pid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the process ID.  Before the process is spawned, this will be
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="multiprocessing.Process.exitcode">
<code class="descname">exitcode</code><a class="headerlink" href="#multiprocessing.Process.exitcode" title="Permalink to this definition">¶</a></dt>
<dd><p>The child’s exit code.  This will be <code class="docutils literal notranslate"><span class="pre">None</span></code> if the process has not yet
terminated.  A negative value <em>-N</em> indicates that the child was terminated
by signal <em>N</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="multiprocessing.Process.authkey">
<code class="descname">authkey</code><a class="headerlink" href="#multiprocessing.Process.authkey" title="Permalink to this definition">¶</a></dt>
<dd><p>The process’s authentication key (a byte string).</p>
<p>When <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> is initialized the main process is assigned a
random string using <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a>.</p>
<p>When a <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> object is created, it will inherit the
authentication key of its parent process, although this may be changed by
setting <a class="reference internal" href="#multiprocessing.Process.authkey" title="multiprocessing.Process.authkey"><code class="xref py py-attr docutils literal notranslate"><span class="pre">authkey</span></code></a> to another byte string.</p>
<p>See <a class="reference internal" href="#multiprocessing-auth-keys"><span class="std std-ref">Authentication keys</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Process.terminate">
<code class="descname">terminate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Process.terminate" title="Permalink to this definition">¶</a></dt>
<dd><p>Terminate the process.  On Unix this is done using the <code class="docutils literal notranslate"><span class="pre">SIGTERM</span></code> signal;
on Windows <code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code> is used.  Note that exit handlers and
finally clauses, etc., will not be executed.</p>
<p>Note that descendant processes of the process will <em>not</em> be terminated –
they will simply become orphaned.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If this method is used when the associated process is using a pipe or
queue then the pipe or queue is liable to become corrupted and may
become unusable by other process.  Similarly, if the process has
acquired a lock or semaphore etc. then terminating it is liable to
cause other processes to deadlock.</p>
</div>
</dd></dl>

<p>Note that the <a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a>, <a class="reference internal" href="#multiprocessing.Process.join" title="multiprocessing.Process.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a>, <a class="reference internal" href="#multiprocessing.Process.is_alive" title="multiprocessing.Process.is_alive"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code></a>,
<a class="reference internal" href="#multiprocessing.Process.terminate" title="multiprocessing.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a> and <a class="reference internal" href="#multiprocessing.Process.exitcode" title="multiprocessing.Process.exitcode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">exitcode</span></code></a> methods should only be called by
the process that created the process object.</p>
<p>Example usage of some of the methods of <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a>:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">multiprocessing</span><span class="o">,</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">signal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="mi">1000</span><span class="p">,))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>
<span class="go">&lt;Process(Process-1, initial)&gt; False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>
<span class="go">&lt;Process(Process-1, started)&gt; True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">terminate</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">p</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>
<span class="go">&lt;Process(Process-1, stopped[SIGTERM])&gt; False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span><span class="o">.</span><span class="n">exitcode</span> <span class="o">==</span> <span class="o">-</span><span class="n">signal</span><span class="o">.</span><span class="n">SIGTERM</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

<dl class="exception">
<dt id="multiprocessing.BufferTooShort">
<em class="property">exception </em><code class="descclassname">multiprocessing.</code><code class="descname">BufferTooShort</code><a class="headerlink" href="#multiprocessing.BufferTooShort" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by <a class="reference internal" href="#Connection.recv_bytes_into" title="Connection.recv_bytes_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Connection.recv_bytes_into()</span></code></a> when the supplied
buffer object is too small for the message read.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">e</span></code> is an instance of <a class="reference internal" href="#multiprocessing.BufferTooShort" title="multiprocessing.BufferTooShort"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BufferTooShort</span></code></a> then <code class="docutils literal notranslate"><span class="pre">e.args[0]</span></code> will give
the message as a byte string.</p>
</dd></dl>

</div>
<div class="section" id="pipes-and-queues">
<h3>16.6.2.2. Pipes and Queues<a class="headerlink" href="#pipes-and-queues" title="Permalink to this headline">¶</a></h3>
<p>When using multiple processes, one generally uses message passing for
communication between processes and avoids having to use any synchronization
primitives like locks.</p>
<p>For passing messages one can use <a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe()</span></code></a> (for a connection between two
processes) or a queue (which allows multiple producers and consumers).</p>
<p>The <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, <a class="reference internal" href="#multiprocessing.multiprocessing.queues.SimpleQueue" title="multiprocessing.multiprocessing.queues.SimpleQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">multiprocessing.queues.SimpleQueue</span></code></a> and <a class="reference internal" href="#multiprocessing.JoinableQueue" title="multiprocessing.JoinableQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">JoinableQueue</span></code></a> types are multi-producer,
multi-consumer FIFO queues modelled on the <a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a> class in the
standard library.  They differ in that <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> lacks the
<a class="reference internal" href="queue.html#Queue.Queue.task_done" title="Queue.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> and <a class="reference internal" href="queue.html#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> methods introduced
into Python 2.5’s <a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a> class.</p>
<p>If you use <a class="reference internal" href="#multiprocessing.JoinableQueue" title="multiprocessing.JoinableQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">JoinableQueue</span></code></a> then you <strong>must</strong> call
<a class="reference internal" href="#multiprocessing.JoinableQueue.task_done" title="multiprocessing.JoinableQueue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">JoinableQueue.task_done()</span></code></a> for each task removed from the queue or else the
semaphore used to count the number of unfinished tasks may eventually overflow,
raising an exception.</p>
<p>Note that one can also create a shared queue by using a manager object – see
<a class="reference internal" href="#multiprocessing-managers"><span class="std std-ref">Managers</span></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> uses the usual <a class="reference internal" href="queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a> and
<a class="reference internal" href="queue.html#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Full</span></code></a> exceptions to signal a timeout.  They are not available in
the <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> namespace so you need to import them from
<a class="reference internal" href="queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>When an object is put on a queue, the object is pickled and a
background thread later flushes the pickled data to an underlying
pipe.  This has some consequences which are a little surprising,
but should not cause any practical difficulties – if they really
bother you then you can instead use a queue created with a
<a class="reference internal" href="#multiprocessing-managers"><span class="std std-ref">manager</span></a>.</p>
<ol class="last arabic simple">
<li>After putting an object on an empty queue there may be an
infinitesimal delay before the queue’s <a class="reference internal" href="#multiprocessing.Queue.empty" title="multiprocessing.Queue.empty"><code class="xref py py-meth docutils literal notranslate"><span class="pre">empty()</span></code></a>
method returns <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> and <a class="reference internal" href="#multiprocessing.Queue.get_nowait" title="multiprocessing.Queue.get_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_nowait()</span></code></a> can
return without raising <a class="reference internal" href="queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a>.</li>
<li>If multiple processes are enqueuing objects, it is possible for
the objects to be received at the other end out-of-order.
However, objects enqueued by the same process will always be in
the expected order with respect to each other.</li>
</ol>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If a process is killed using <a class="reference internal" href="#multiprocessing.Process.terminate" title="multiprocessing.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.terminate()</span></code></a> or <a class="reference internal" href="os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a>
while it is trying to use a <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, then the data in the queue is
likely to become corrupted.  This may cause any other process to get an
exception when it tries to use the queue later on.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>As mentioned above, if a child process has put items on a queue (and it has
not used <a class="reference internal" href="#multiprocessing.Queue.cancel_join_thread" title="multiprocessing.Queue.cancel_join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">JoinableQueue.cancel_join_thread</span></code></a>), then that process will
not terminate until all buffered items have been flushed to the pipe.</p>
<p>This means that if you try joining that process you may get a deadlock unless
you are sure that all items which have been put on the queue have been
consumed.  Similarly, if the child process is non-daemonic then the parent
process may hang on exit when it tries to join all its non-daemonic children.</p>
<p class="last">Note that a queue created using a manager does not have this issue.  See
<a class="reference internal" href="#multiprocessing-programming"><span class="std std-ref">Programming guidelines</span></a>.</p>
</div>
<p>For an example of the usage of queues for interprocess communication see
<a class="reference internal" href="#multiprocessing-examples"><span class="std std-ref">Examples</span></a>.</p>
<dl class="function">
<dt id="multiprocessing.Pipe">
<code class="descclassname">multiprocessing.</code><code class="descname">Pipe</code><span class="sig-paren">(</span><span class="optional">[</span><em>duplex</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Pipe" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a pair <code class="docutils literal notranslate"><span class="pre">(conn1,</span> <span class="pre">conn2)</span></code> of <a class="reference internal" href="#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> objects representing
the ends of a pipe.</p>
<p>If <em>duplex</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) then the pipe is bidirectional.  If
<em>duplex</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then the pipe is unidirectional: <code class="docutils literal notranslate"><span class="pre">conn1</span></code> can only be
used for receiving messages and <code class="docutils literal notranslate"><span class="pre">conn2</span></code> can only be used for sending
messages.</p>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.Queue">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Queue</code><span class="sig-paren">(</span><span class="optional">[</span><em>maxsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a process shared queue implemented using a pipe and a few
locks/semaphores.  When a process first puts an item on the queue a feeder
thread is started which transfers objects from a buffer into the pipe.</p>
<p>The usual <a class="reference internal" href="queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a> and <a class="reference internal" href="queue.html#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Full</span></code></a> exceptions from the
standard library’s <a class="reference internal" href="queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module are raised to signal timeouts.</p>
<p><a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> implements all the methods of <a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a> except for
<a class="reference internal" href="queue.html#Queue.Queue.task_done" title="Queue.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> and <a class="reference internal" href="queue.html#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a>.</p>
<dl class="method">
<dt id="multiprocessing.Queue.qsize">
<code class="descname">qsize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.qsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the approximate size of the queue.  Because of
multithreading/multiprocessing semantics, this number is not reliable.</p>
<p>Note that this may raise <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> on Unix platforms like
Mac OS X where <code class="docutils literal notranslate"><span class="pre">sem_getvalue()</span></code> is not implemented.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Because of
multithreading/multiprocessing semantics, this is not reliable.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.full">
<code class="descname">full</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.full" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is full, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  Because of
multithreading/multiprocessing semantics, this is not reliable.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.put">
<code class="descname">put</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>block</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.put" title="Permalink to this definition">¶</a></dt>
<dd><p>Put obj into the queue.  If the optional argument <em>block</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>
(the default) and <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), block if necessary until
a free slot is available.  If <em>timeout</em> is a positive number, it blocks at
most <em>timeout</em> seconds and raises the <a class="reference internal" href="queue.html#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Full</span></code></a> exception if no
free slot was available within that time.  Otherwise (<em>block</em> is
<code class="docutils literal notranslate"><span class="pre">False</span></code>), put an item on the queue if a free slot is immediately
available, else raise the <a class="reference internal" href="queue.html#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Full</span></code></a> exception (<em>timeout</em> is
ignored in that case).</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.put_nowait">
<code class="descname">put_nowait</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.put_nowait" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">put(obj,</span> <span class="pre">False)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.get">
<code class="descname">get</code><span class="sig-paren">(</span><span class="optional">[</span><em>block</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an item from the queue.  If optional args <em>block</em> is
<code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) and <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), block if
necessary until an item is available.  If <em>timeout</em> is a positive number,
it blocks at most <em>timeout</em> seconds and raises the <a class="reference internal" href="queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a>
exception if no item was available within that time.  Otherwise (block is
<code class="docutils literal notranslate"><span class="pre">False</span></code>), return an item if one is immediately available, else raise the
<a class="reference internal" href="queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a> exception (<em>timeout</em> is ignored in that case).</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.get_nowait">
<code class="descname">get_nowait</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.get_nowait" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">get(False)</span></code>.</p>
</dd></dl>

<p><a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> has a few additional methods not found in
<a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a>.  These methods are usually unnecessary for most
code:</p>
<dl class="method">
<dt id="multiprocessing.Queue.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicate that no more data will be put on this queue by the current
process.  The background thread will quit once it has flushed all buffered
data to the pipe.  This is called automatically when the queue is garbage
collected.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.join_thread">
<code class="descname">join_thread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.join_thread" title="Permalink to this definition">¶</a></dt>
<dd><p>Join the background thread.  This can only be used after <a class="reference internal" href="#multiprocessing.Queue.close" title="multiprocessing.Queue.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> has
been called.  It blocks until the background thread exits, ensuring that
all data in the buffer has been flushed to the pipe.</p>
<p>By default if a process is not the creator of the queue then on exit it
will attempt to join the queue’s background thread.  The process can call
<a class="reference internal" href="#multiprocessing.Queue.cancel_join_thread" title="multiprocessing.Queue.cancel_join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel_join_thread()</span></code></a> to make <a class="reference internal" href="#multiprocessing.Queue.join_thread" title="multiprocessing.Queue.join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join_thread()</span></code></a> do nothing.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Queue.cancel_join_thread">
<code class="descname">cancel_join_thread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Queue.cancel_join_thread" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevent <a class="reference internal" href="#multiprocessing.Queue.join_thread" title="multiprocessing.Queue.join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join_thread()</span></code></a> from blocking.  In particular, this prevents
the background thread from being joined automatically when the process
exits – see <a class="reference internal" href="#multiprocessing.Queue.join_thread" title="multiprocessing.Queue.join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join_thread()</span></code></a>.</p>
<p>A better name for this method might be
<code class="docutils literal notranslate"><span class="pre">allow_exit_without_flush()</span></code>.  It is likely to cause enqueued
data to lost, and you almost certainly will not need to use it.
It is really only there if you need the current process to exit
immediately without waiting to flush enqueued data to the
underlying pipe, and you don’t care about lost data.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This class’s functionality requires a functioning shared semaphore
implementation on the host operating system. Without one, the
functionality in this class will be disabled, and attempts to
instantiate a <a class="reference internal" href="queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> will result in an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>. See
<a class="reference external" href="https://bugs.python.org/issue3770">bpo-3770</a> for additional information.  The same holds true for any
of the specialized queue types listed below.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.multiprocessing.queues.SimpleQueue">
<em class="property">class </em><code class="descclassname">multiprocessing.queues.</code><code class="descname">SimpleQueue</code><a class="headerlink" href="#multiprocessing.multiprocessing.queues.SimpleQueue" title="Permalink to this definition">¶</a></dt>
<dd><p>It is a simplified <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> type, very close to a locked <a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pipe</span></code></a>.</p>
<dl class="method">
<dt id="multiprocessing.multiprocessing.queues.SimpleQueue.empty">
<code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.multiprocessing.queues.SimpleQueue.empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.multiprocessing.queues.SimpleQueue.get">
<code class="descname">get</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.multiprocessing.queues.SimpleQueue.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an item from the queue.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.multiprocessing.queues.SimpleQueue.put">
<code class="descname">put</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.multiprocessing.queues.SimpleQueue.put" title="Permalink to this definition">¶</a></dt>
<dd><p>Put <em>item</em> into the queue.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="multiprocessing.JoinableQueue">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">JoinableQueue</code><span class="sig-paren">(</span><span class="optional">[</span><em>maxsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.JoinableQueue" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#multiprocessing.JoinableQueue" title="multiprocessing.JoinableQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">JoinableQueue</span></code></a>, a <a class="reference internal" href="#multiprocessing.Queue" title="multiprocessing.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> subclass, is a queue which
additionally has <a class="reference internal" href="#multiprocessing.JoinableQueue.task_done" title="multiprocessing.JoinableQueue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> and <a class="reference internal" href="#multiprocessing.JoinableQueue.join" title="multiprocessing.JoinableQueue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> methods.</p>
<dl class="method">
<dt id="multiprocessing.JoinableQueue.task_done">
<code class="descname">task_done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.JoinableQueue.task_done" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicate that a formerly enqueued task is complete. Used by queue consumer
threads.  For each <a class="reference internal" href="#multiprocessing.Queue.get" title="multiprocessing.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> used to fetch a task, a subsequent
call to <a class="reference internal" href="#multiprocessing.JoinableQueue.task_done" title="multiprocessing.JoinableQueue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> tells the queue that the processing on the task
is complete.</p>
<p>If a <a class="reference internal" href="queue.html#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is currently blocking, it will resume when all
items have been processed (meaning that a <a class="reference internal" href="#multiprocessing.JoinableQueue.task_done" title="multiprocessing.JoinableQueue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> call was
received for every item that had been <a class="reference internal" href="#multiprocessing.Queue.put" title="multiprocessing.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a> into the queue).</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called more times than there were items
placed in the queue.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.JoinableQueue.join">
<code class="descname">join</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.JoinableQueue.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Block until all items in the queue have been gotten and processed.</p>
<p>The count of unfinished tasks goes up whenever an item is added to the
queue.  The count goes down whenever a consumer thread calls
<a class="reference internal" href="#multiprocessing.JoinableQueue.task_done" title="multiprocessing.JoinableQueue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> to indicate that the item was retrieved and all work on
it is complete.  When the count of unfinished tasks drops to zero,
<a class="reference internal" href="queue.html#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> unblocks.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="miscellaneous">
<h3>16.6.2.3. Miscellaneous<a class="headerlink" href="#miscellaneous" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="multiprocessing.active_children">
<code class="descclassname">multiprocessing.</code><code class="descname">active_children</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.active_children" title="Permalink to this definition">¶</a></dt>
<dd><p>Return list of all live children of the current process.</p>
<p>Calling this has the side effect of “joining” any processes which have
already finished.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.cpu_count">
<code class="descclassname">multiprocessing.</code><code class="descname">cpu_count</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.cpu_count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of CPUs in the system.  May raise
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.current_process">
<code class="descclassname">multiprocessing.</code><code class="descname">current_process</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.current_process" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> object corresponding to the current process.</p>
<p>An analogue of <a class="reference internal" href="threading.html#threading.current_thread" title="threading.current_thread"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.current_thread()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.freeze_support">
<code class="descclassname">multiprocessing.</code><code class="descname">freeze_support</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.freeze_support" title="Permalink to this definition">¶</a></dt>
<dd><p>Add support for when a program which uses <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> has been
frozen to produce a Windows executable.  (Has been tested with <strong>py2exe</strong>,
<strong>PyInstaller</strong> and <strong>cx_Freeze</strong>.)</p>
<p>One needs to call this function straight after the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span>
<span class="pre">'__main__'</span></code> line of the main module.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">freeze_support</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s1">&#39;hello world!&#39;</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">)</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
<p>If the <code class="docutils literal notranslate"><span class="pre">freeze_support()</span></code> line is omitted then trying to run the frozen
executable will raise <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
<p>Calling <code class="docutils literal notranslate"><span class="pre">freeze_support()</span></code> has no effect when invoked on any operating
system other than Windows.  In addition, if the module is being run
normally by the Python interpreter on Windows (the program has not been
frozen), then <code class="docutils literal notranslate"><span class="pre">freeze_support()</span></code> has no effect.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.set_executable">
<code class="descclassname">multiprocessing.</code><code class="descname">set_executable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.set_executable" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the path of the Python interpreter to use when starting a child process.
(By default <a class="reference internal" href="sys.html#sys.executable" title="sys.executable"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.executable</span></code></a> is used).  Embedders will probably need to
do some thing like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">set_executable</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">exec_prefix</span><span class="p">,</span> <span class="s1">&#39;pythonw.exe&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>before they can create child processes.  (Windows only)</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> contains no analogues of
<a class="reference internal" href="threading.html#threading.active_count" title="threading.active_count"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.active_count()</span></code></a>, <a class="reference internal" href="threading.html#threading.enumerate" title="threading.enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.enumerate()</span></code></a>,
<a class="reference internal" href="threading.html#threading.settrace" title="threading.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.settrace()</span></code></a>, <a class="reference internal" href="threading.html#threading.setprofile" title="threading.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">threading.setprofile()</span></code></a>,
<a class="reference internal" href="threading.html#threading.Timer" title="threading.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Timer</span></code></a>, or <a class="reference internal" href="threading.html#threading.local" title="threading.local"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.local</span></code></a>.</p>
</div>
</div>
<div class="section" id="connection-objects">
<h3>16.6.2.4. Connection Objects<a class="headerlink" href="#connection-objects" title="Permalink to this headline">¶</a></h3>
<p>Connection objects allow the sending and receiving of picklable objects or
strings.  They can be thought of as message oriented connected sockets.</p>
<p>Connection objects are usually created using
<a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe</span></code></a> – see also
<a class="reference internal" href="#multiprocessing-listeners-clients"><span class="std std-ref">Listeners and Clients</span></a>.</p>
<dl class="class">
<dt id="Connection">
<em class="property">class </em><code class="descname">Connection</code><a class="headerlink" href="#Connection" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="Connection.send">
<code class="descname">send</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#Connection.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an object to the other end of the connection which should be read
using <a class="reference internal" href="#Connection.recv" title="Connection.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a>.</p>
<p>The object must be picklable.  Very large pickles (approximately 32 MB+,
though it depends on the OS) may raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.recv">
<code class="descname">recv</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.recv" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an object sent from the other end of the connection using
<a class="reference internal" href="#Connection.send" title="Connection.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>.  Blocks until there is something to receive.  Raises
<a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if there is nothing left to receive
and the other end was closed.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.fileno">
<code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor or handle used by the connection.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the connection.</p>
<p>This is called automatically when the connection is garbage collected.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.poll">
<code class="descname">poll</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether there is any data available to be read.</p>
<p>If <em>timeout</em> is not specified then it will return immediately.  If
<em>timeout</em> is a number then this specifies the maximum time in seconds to
block.  If <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then an infinite timeout is used.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.send_bytes">
<code class="descname">send_bytes</code><span class="sig-paren">(</span><em>buffer</em><span class="optional">[</span>, <em>offset</em><span class="optional">[</span>, <em>size</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.send_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Send byte data from an object supporting the buffer interface as a
complete message.</p>
<p>If <em>offset</em> is given then data is read from that position in <em>buffer</em>.  If
<em>size</em> is given then that many bytes will be read from buffer.  Very large
buffers (approximately 32 MB+, though it depends on the OS) may raise a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception</p>
</dd></dl>

<dl class="method">
<dt id="Connection.recv_bytes">
<code class="descname">recv_bytes</code><span class="sig-paren">(</span><span class="optional">[</span><em>maxlength</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.recv_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a complete message of byte data sent from the other end of the
connection as a string.  Blocks until there is something to receive.
Raises <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if there is nothing left
to receive and the other end has closed.</p>
<p>If <em>maxlength</em> is specified and the message is longer than <em>maxlength</em>
then <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised and the connection will no longer be
readable.</p>
</dd></dl>

<dl class="method">
<dt id="Connection.recv_bytes_into">
<code class="descname">recv_bytes_into</code><span class="sig-paren">(</span><em>buffer</em><span class="optional">[</span>, <em>offset</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Connection.recv_bytes_into" title="Permalink to this definition">¶</a></dt>
<dd><p>Read into <em>buffer</em> a complete message of byte data sent from the other end
of the connection and return the number of bytes in the message.  Blocks
until there is something to receive.  Raises
<a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if there is nothing left to receive and the other end was
closed.</p>
<p><em>buffer</em> must be an object satisfying the writable buffer interface.  If
<em>offset</em> is given then the message will be written into the buffer from
that position.  Offset must be a non-negative integer less than the
length of <em>buffer</em> (in bytes).</p>
<p>If the buffer is too short then a <code class="xref py py-exc docutils literal notranslate"><span class="pre">BufferTooShort</span></code> exception is
raised and the complete message is available as <code class="docutils literal notranslate"><span class="pre">e.args[0]</span></code> where <code class="docutils literal notranslate"><span class="pre">e</span></code>
is the exception instance.</p>
</dd></dl>

</dd></dl>

<p>For example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pipe</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">Pipe</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">send</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;hello&#39;</span><span class="p">,</span> <span class="bp">None</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">recv</span><span class="p">()</span>
<span class="go">[1, &#39;hello&#39;, None]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">send_bytes</span><span class="p">(</span><span class="s1">&#39;thank you&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">recv_bytes</span><span class="p">()</span>
<span class="go">&#39;thank you&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">arr1</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">arr2</span> <span class="o">=</span> <span class="n">array</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">send_bytes</span><span class="p">(</span><span class="n">arr1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">count</span> <span class="o">=</span> <span class="n">b</span><span class="o">.</span><span class="n">recv_bytes_into</span><span class="p">(</span><span class="n">arr2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">assert</span> <span class="n">count</span> <span class="o">==</span> <span class="nb">len</span><span class="p">(</span><span class="n">arr1</span><span class="p">)</span> <span class="o">*</span> <span class="n">arr1</span><span class="o">.</span><span class="n">itemsize</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">arr2</span>
<span class="go">array(&#39;i&#39;, [0, 1, 2, 3, 4, 0, 0, 0, 0, 0])</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>The <a class="reference internal" href="#Connection.recv" title="Connection.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Connection.recv()</span></code></a> method automatically unpickles the data it
receives, which can be a security risk unless you can trust the process
which sent the message.</p>
<p class="last">Therefore, unless the connection object was produced using <code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe()</span></code> you
should only use the <a class="reference internal" href="#Connection.recv" title="Connection.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> and <a class="reference internal" href="#Connection.send" title="Connection.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>
methods after performing some sort of authentication.  See
<a class="reference internal" href="#multiprocessing-auth-keys"><span class="std std-ref">Authentication keys</span></a>.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">If a process is killed while it is trying to read or write to a pipe then
the data in the pipe is likely to become corrupted, because it may become
impossible to be sure where the message boundaries lie.</p>
</div>
</div>
<div class="section" id="synchronization-primitives">
<h3>16.6.2.5. Synchronization primitives<a class="headerlink" href="#synchronization-primitives" title="Permalink to this headline">¶</a></h3>
<p>Generally synchronization primitives are not as necessary in a multiprocess
program as they are in a multithreaded program.  See the documentation for
<a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.</p>
<p>Note that one can also create synchronization primitives by using a manager
object – see <a class="reference internal" href="#multiprocessing-managers"><span class="std std-ref">Managers</span></a>.</p>
<dl class="class">
<dt id="multiprocessing.BoundedSemaphore">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">BoundedSemaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.BoundedSemaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>A bounded semaphore object: a close analog of
<a class="reference internal" href="threading.html#threading.BoundedSemaphore" title="threading.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.BoundedSemaphore</span></code></a>.</p>
<p>A solitary difference from its close analog exists: its <code class="docutils literal notranslate"><span class="pre">acquire</span></code> method’s
first argument is named <em>block</em> and it supports an optional second argument
<em>timeout</em>, as is consistent with <a class="reference internal" href="#multiprocessing.Lock.acquire" title="multiprocessing.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Mac OS X, this is indistinguishable from <a class="reference internal" href="#multiprocessing.Semaphore" title="multiprocessing.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a> because
<code class="docutils literal notranslate"><span class="pre">sem_getvalue()</span></code> is not implemented on that platform.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.Condition">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Condition</code><span class="sig-paren">(</span><span class="optional">[</span><em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Condition" title="Permalink to this definition">¶</a></dt>
<dd><p>A condition variable: a clone of <a class="reference internal" href="threading.html#threading.Condition" title="threading.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Condition</span></code></a>.</p>
<p>If <em>lock</em> is specified then it should be a <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> or <a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>
object from <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.Event">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Event</code><a class="headerlink" href="#multiprocessing.Event" title="Permalink to this definition">¶</a></dt>
<dd><p>A clone of <a class="reference internal" href="threading.html#threading.Event" title="threading.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Event</span></code></a>.
This method returns the state of the internal semaphore on exit, so it
will always return <code class="docutils literal notranslate"><span class="pre">True</span></code> except if a timeout is given and the operation
times out.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Previously, the method always returned <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.Lock">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Lock</code><a class="headerlink" href="#multiprocessing.Lock" title="Permalink to this definition">¶</a></dt>
<dd><p>A non-recursive lock object: a close analog of <a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a>.
Once a process or thread has acquired a lock, subsequent attempts to
acquire it from any process or thread will block until it is released;
any process or thread may release it.  The concepts and behaviors of
<a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a> as it applies to threads are replicated here in
<a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">multiprocessing.Lock</span></code></a> as it applies to either processes or threads,
except as noted.</p>
<p>Note that <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> is actually a factory function which returns an
instance of <code class="docutils literal notranslate"><span class="pre">multiprocessing.synchronize.Lock</span></code> initialized with a
default context.</p>
<p><a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> supports the <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> protocol and thus may be
used in <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements.</p>
<dl class="method">
<dt id="multiprocessing.Lock.acquire">
<code class="descname">acquire</code><span class="sig-paren">(</span><em>block=True</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Lock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>With the <em>block</em> argument set to <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default), the method call
will block until the lock is in an unlocked state, then set it to locked
and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.  Note that the name of this first argument differs
from that in <a class="reference internal" href="threading.html#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.Lock.acquire()</span></code></a>.</p>
<p>With the <em>block</em> argument set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, the method call does not
block.  If the lock is currently in a locked state, return <code class="docutils literal notranslate"><span class="pre">False</span></code>;
otherwise set the lock to a locked state and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<p>When invoked with a positive, floating-point value for <em>timeout</em>, block
for at most the number of seconds specified by <em>timeout</em> as long as
the lock can not be acquired.  Invocations with a negative value for
<em>timeout</em> are equivalent to a <em>timeout</em> of zero.  Invocations with a
<em>timeout</em> value of <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) set the timeout period to
infinite.  The <em>timeout</em> argument has no practical implications if the
<em>block</em> argument is set to <code class="docutils literal notranslate"><span class="pre">False</span></code> and is thus ignored.  Returns
<code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock has been acquired or <code class="docutils literal notranslate"><span class="pre">False</span></code> if the timeout period
has elapsed.  Note that the <em>timeout</em> argument does not exist in this
method’s analog, <a class="reference internal" href="threading.html#threading.Lock.acquire" title="threading.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.Lock.acquire()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.Lock.release">
<code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Lock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock.  This can be called from any process or thread, not only
the process or thread which originally acquired the lock.</p>
<p>Behavior is the same as in <a class="reference internal" href="threading.html#threading.Lock.release" title="threading.Lock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.Lock.release()</span></code></a> except that
when invoked on an unlocked lock, a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="multiprocessing.RLock">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">RLock</code><a class="headerlink" href="#multiprocessing.RLock" title="Permalink to this definition">¶</a></dt>
<dd><p>A recursive lock object: a close analog of <a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a>.  A
recursive lock must be released by the process or thread that acquired it.
Once a process or thread has acquired a recursive lock, the same process
or thread may acquire it again without blocking; that process or thread
must release it once for each time it has been acquired.</p>
<p>Note that <a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> is actually a factory function which returns an
instance of <code class="docutils literal notranslate"><span class="pre">multiprocessing.synchronize.RLock</span></code> initialized with a
default context.</p>
<p><a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> supports the <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> protocol and thus may be
used in <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements.</p>
<dl class="method">
<dt id="multiprocessing.RLock.acquire">
<code class="descname">acquire</code><span class="sig-paren">(</span><em>block=True</em>, <em>timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.RLock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>When invoked with the <em>block</em> argument set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, block until the
lock is in an unlocked state (not owned by any process or thread) unless
the lock is already owned by the current process or thread.  The current
process or thread then takes ownership of the lock (if it does not
already have ownership) and the recursion level inside the lock increments
by one, resulting in a return value of <code class="docutils literal notranslate"><span class="pre">True</span></code>.  Note that there are
several differences in this first argument’s behavior compared to the
implementation of <a class="reference internal" href="threading.html#threading.RLock.acquire" title="threading.RLock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.RLock.acquire()</span></code></a>, starting with the name
of the argument itself.</p>
<p>When invoked with the <em>block</em> argument set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, do not block.
If the lock has already been acquired (and thus is owned) by another
process or thread, the current process or thread does not take ownership
and the recursion level within the lock is not changed, resulting in
a return value of <code class="docutils literal notranslate"><span class="pre">False</span></code>.  If the lock is in an unlocked state, the
current process or thread takes ownership and the recursion level is
incremented, resulting in a return value of <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<p>Use and behaviors of the <em>timeout</em> argument are the same as in
<a class="reference internal" href="#multiprocessing.Lock.acquire" title="multiprocessing.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code></a>.  Note that the <em>timeout</em> argument does
not exist in this method’s analog, <a class="reference internal" href="threading.html#threading.RLock.acquire" title="threading.RLock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.RLock.acquire()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.RLock.release">
<code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.RLock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock, decrementing the recursion level.  If after the
decrement the recursion level is zero, reset the lock to unlocked (not
owned by any process or thread) and if any other processes or threads
are blocked waiting for the lock to become unlocked, allow exactly one
of them to proceed.  If after the decrement the recursion level is still
nonzero, the lock remains locked and owned by the calling process or
thread.</p>
<p>Only call this method when the calling process or thread owns the lock.
An <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> is raised if this method is called by a process
or thread other than the owner or if the lock is in an unlocked (unowned)
state.  Note that the type of exception raised in this situation
differs from the implemented behavior in <a class="reference internal" href="threading.html#threading.RLock.release" title="threading.RLock.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">threading.RLock.release()</span></code></a>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="multiprocessing.Semaphore">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Semaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Semaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>A semaphore object: a close analog of <a class="reference internal" href="threading.html#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Semaphore</span></code></a>.</p>
<p>A solitary difference from its close analog exists: its <code class="docutils literal notranslate"><span class="pre">acquire</span></code> method’s
first argument is named <em>block</em> and it supports an optional second argument
<em>timeout</em>, as is consistent with <a class="reference internal" href="#multiprocessing.Lock.acquire" title="multiprocessing.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code></a>.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> method of <a class="reference internal" href="#multiprocessing.BoundedSemaphore" title="multiprocessing.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a>, <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>,
<a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> and <a class="reference internal" href="#multiprocessing.Semaphore" title="multiprocessing.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a> has a timeout parameter not supported
by the equivalents in <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>.  The signature is
<code class="docutils literal notranslate"><span class="pre">acquire(block=True,</span> <span class="pre">timeout=None)</span></code> with keyword parameters being
acceptable.  If <em>block</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> and <em>timeout</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> then it
specifies a timeout in seconds.  If <em>block</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then <em>timeout</em> is
ignored.</p>
<p class="last">On Mac OS X, <code class="docutils literal notranslate"><span class="pre">sem_timedwait</span></code> is unsupported, so calling <code class="docutils literal notranslate"><span class="pre">acquire()</span></code> with
a timeout will emulate that function’s behavior using a sleeping loop.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If the SIGINT signal generated by <kbd class="kbd docutils literal notranslate">Ctrl-C</kbd> arrives while the main thread is
blocked by a call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">BoundedSemaphore.acquire()</span></code>, <a class="reference internal" href="#multiprocessing.Lock.acquire" title="multiprocessing.Lock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock.acquire()</span></code></a>,
<a class="reference internal" href="#multiprocessing.RLock.acquire" title="multiprocessing.RLock.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">RLock.acquire()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Semaphore.acquire()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Condition.acquire()</span></code>
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">Condition.wait()</span></code> then the call will be immediately interrupted and
<a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> will be raised.</p>
<p class="last">This differs from the behaviour of <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> where SIGINT will be
ignored while the equivalent blocking calls are in progress.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some of this package’s functionality requires a functioning shared semaphore
implementation on the host operating system. Without one, the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.synchronize</span></code> module will be disabled, and attempts to
import it will result in an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>. See
<a class="reference external" href="https://bugs.python.org/issue3770">bpo-3770</a> for additional information.</p>
</div>
</div>
<div class="section" id="shared-ctypes-objects">
<h3>16.6.2.6. Shared <a class="reference internal" href="ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> Objects<a class="headerlink" href="#shared-ctypes-objects" title="Permalink to this headline">¶</a></h3>
<p>It is possible to create shared objects using shared memory which can be
inherited by child processes.</p>
<dl class="function">
<dt id="multiprocessing.Value">
<code class="descclassname">multiprocessing.</code><code class="descname">Value</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>*args</em><span class="optional">[</span>, <em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Value" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> object allocated from shared memory.  By default the
return value is actually a synchronized wrapper for the object.</p>
<p><em>typecode_or_type</em> determines the type of the returned object: it is either a
ctypes type or a one character typecode of the kind used by the <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a>
module.  <em>*args</em> is passed on to the constructor for the type.</p>
<p>If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) then a new recursive lock
object is created to synchronize access to the value.  If <em>lock</em> is
a <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> or <a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object then that will be used to
synchronize access to the value.  If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then
access to the returned object will not be automatically protected
by a lock, so it will not necessarily be “process-safe”.</p>
<p>Operations like <code class="docutils literal notranslate"><span class="pre">+=</span></code> which involve a read and write are not
atomic.  So if, for instance, you want to atomically increment a
shared value it is insufficient to just do</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">counter</span><span class="o">.</span><span class="n">value</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Assuming the associated lock is recursive (which it is by default)
you can instead do</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">counter</span><span class="o">.</span><span class="n">get_lock</span><span class="p">():</span>
    <span class="n">counter</span><span class="o">.</span><span class="n">value</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Note that <em>lock</em> is a keyword-only argument.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.Array">
<code class="descclassname">multiprocessing.</code><code class="descname">Array</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>size_or_initializer</em>, <em>*</em>, <em>lock=True</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.Array" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a ctypes array allocated from shared memory.  By default the return
value is actually a synchronized wrapper for the array.</p>
<p><em>typecode_or_type</em> determines the type of the elements of the returned array:
it is either a ctypes type or a one character typecode of the kind used by
the <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module.  If <em>size_or_initializer</em> is an integer, then it
determines the length of the array, and the array will be initially zeroed.
Otherwise, <em>size_or_initializer</em> is a sequence which is used to initialize
the array and whose length determines the length of the array.</p>
<p>If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) then a new lock object is created to
synchronize access to the value.  If <em>lock</em> is a <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> or
<a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object then that will be used to synchronize access to the
value.  If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then access to the returned object will not be
automatically protected by a lock, so it will not necessarily be
“process-safe”.</p>
<p>Note that <em>lock</em> is a keyword only argument.</p>
<p>Note that an array of <a class="reference internal" href="ctypes.html#ctypes.c_char" title="ctypes.c_char"><code class="xref py py-data docutils literal notranslate"><span class="pre">ctypes.c_char</span></code></a> has <em>value</em> and <em>raw</em>
attributes which allow one to use it to store and retrieve strings.</p>
</dd></dl>

<div class="section" id="module-multiprocessing.sharedctypes">
<span id="the-multiprocessing-sharedctypes-module"></span><h4>16.6.2.6.1. The <a class="reference internal" href="#module-multiprocessing.sharedctypes" title="multiprocessing.sharedctypes: Allocate ctypes objects from shared memory."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code></a> module<a class="headerlink" href="#module-multiprocessing.sharedctypes" title="Permalink to this headline">¶</a></h4>
<p>The <a class="reference internal" href="#module-multiprocessing.sharedctypes" title="multiprocessing.sharedctypes: Allocate ctypes objects from shared memory."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code></a> module provides functions for allocating
<a class="reference internal" href="ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> objects from shared memory which can be inherited by child
processes.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Although it is possible to store a pointer in shared memory remember that
this will refer to a location in the address space of a specific process.
However, the pointer is quite likely to be invalid in the context of a second
process and trying to dereference the pointer from the second process may
cause a crash.</p>
</div>
<dl class="function">
<dt id="multiprocessing.sharedctypes.RawArray">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">RawArray</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>size_or_initializer</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.RawArray" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a ctypes array allocated from shared memory.</p>
<p><em>typecode_or_type</em> determines the type of the elements of the returned array:
it is either a ctypes type or a one character typecode of the kind used by
the <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module.  If <em>size_or_initializer</em> is an integer then it
determines the length of the array, and the array will be initially zeroed.
Otherwise <em>size_or_initializer</em> is a sequence which is used to initialize the
array and whose length determines the length of the array.</p>
<p>Note that setting and getting an element is potentially non-atomic – use
<a class="reference internal" href="#multiprocessing.sharedctypes.Array" title="multiprocessing.sharedctypes.Array"><code class="xref py py-func docutils literal notranslate"><span class="pre">Array()</span></code></a> instead to make sure that access is automatically synchronized
using a lock.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.sharedctypes.RawValue">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">RawValue</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.RawValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a ctypes object allocated from shared memory.</p>
<p><em>typecode_or_type</em> determines the type of the returned object: it is either a
ctypes type or a one character typecode of the kind used by the <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a>
module.  <em>*args</em> is passed on to the constructor for the type.</p>
<p>Note that setting and getting the value is potentially non-atomic – use
<a class="reference internal" href="#multiprocessing.sharedctypes.Value" title="multiprocessing.sharedctypes.Value"><code class="xref py py-func docutils literal notranslate"><span class="pre">Value()</span></code></a> instead to make sure that access is automatically synchronized
using a lock.</p>
<p>Note that an array of <a class="reference internal" href="ctypes.html#ctypes.c_char" title="ctypes.c_char"><code class="xref py py-data docutils literal notranslate"><span class="pre">ctypes.c_char</span></code></a> has <code class="docutils literal notranslate"><span class="pre">value</span></code> and <code class="docutils literal notranslate"><span class="pre">raw</span></code>
attributes which allow one to use it to store and retrieve strings – see
documentation for <a class="reference internal" href="ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.sharedctypes.Array">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">Array</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>size_or_initializer</em>, <em>*args</em><span class="optional">[</span>, <em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.Array" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#multiprocessing.sharedctypes.RawArray" title="multiprocessing.sharedctypes.RawArray"><code class="xref py py-func docutils literal notranslate"><span class="pre">RawArray()</span></code></a> except that depending on the value of <em>lock</em> a
process-safe synchronization wrapper may be returned instead of a raw ctypes
array.</p>
<p>If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) then a new lock object is created to
synchronize access to the value.  If <em>lock</em> is a
<a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> or <a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object
then that will be used to synchronize access to the
value.  If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then access to the returned object will not be
automatically protected by a lock, so it will not necessarily be
“process-safe”.</p>
<p>Note that <em>lock</em> is a keyword-only argument.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.sharedctypes.Value">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">Value</code><span class="sig-paren">(</span><em>typecode_or_type</em>, <em>*args</em><span class="optional">[</span>, <em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.Value" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#multiprocessing.sharedctypes.RawValue" title="multiprocessing.sharedctypes.RawValue"><code class="xref py py-func docutils literal notranslate"><span class="pre">RawValue()</span></code></a> except that depending on the value of <em>lock</em> a
process-safe synchronization wrapper may be returned instead of a raw ctypes
object.</p>
<p>If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default) then a new lock object is created to
synchronize access to the value.  If <em>lock</em> is a <a class="reference internal" href="#multiprocessing.Lock" title="multiprocessing.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a> or
<a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object then that will be used to synchronize access to the
value.  If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then access to the returned object will not be
automatically protected by a lock, so it will not necessarily be
“process-safe”.</p>
<p>Note that <em>lock</em> is a keyword-only argument.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.sharedctypes.copy">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a ctypes object allocated from shared memory which is a copy of the
ctypes object <em>obj</em>.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.sharedctypes.synchronized">
<code class="descclassname">multiprocessing.sharedctypes.</code><code class="descname">synchronized</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.synchronized" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a process-safe wrapper object for a ctypes object which uses <em>lock</em> to
synchronize access.  If <em>lock</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) then a
<a class="reference internal" href="#multiprocessing.RLock" title="multiprocessing.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">multiprocessing.RLock</span></code></a> object is created automatically.</p>
<p>A synchronized wrapper will have two methods in addition to those of the
object it wraps: <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_obj()</span></code> returns the wrapped object and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_lock()</span></code> returns the lock object used for synchronization.</p>
<p>Note that accessing the ctypes object through the wrapper can be a lot slower
than accessing the raw ctypes object.</p>
</dd></dl>

<p>The table below compares the syntax for creating shared ctypes objects from
shared memory with the normal ctypes syntax.  (In the table <code class="docutils literal notranslate"><span class="pre">MyStruct</span></code> is some
subclass of <a class="reference internal" href="ctypes.html#ctypes.Structure" title="ctypes.Structure"><code class="xref py py-class docutils literal notranslate"><span class="pre">ctypes.Structure</span></code></a>.)</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="36%" />
<col width="37%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">ctypes</th>
<th class="head">sharedctypes using type</th>
<th class="head">sharedctypes using typecode</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>c_double(2.4)</td>
<td>RawValue(c_double, 2.4)</td>
<td>RawValue(‘d’, 2.4)</td>
</tr>
<tr class="row-odd"><td>MyStruct(4, 6)</td>
<td>RawValue(MyStruct, 4, 6)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td>(c_short * 7)()</td>
<td>RawArray(c_short, 7)</td>
<td>RawArray(‘h’, 7)</td>
</tr>
<tr class="row-odd"><td>(c_int * 3)(9, 2, 8)</td>
<td>RawArray(c_int, (9, 2, 8))</td>
<td>RawArray(‘i’, (9, 2, 8))</td>
</tr>
</tbody>
</table>
<p>Below is an example where a number of ctypes objects are modified by a child
process:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Lock</span>
<span class="kn">from</span> <span class="nn">multiprocessing.sharedctypes</span> <span class="k">import</span> <span class="n">Value</span><span class="p">,</span> <span class="n">Array</span>
<span class="kn">from</span> <span class="nn">ctypes</span> <span class="k">import</span> <span class="n">Structure</span><span class="p">,</span> <span class="n">c_double</span>

<span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="n">Structure</span><span class="p">):</span>
    <span class="n">_fields_</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;x&#39;</span><span class="p">,</span> <span class="n">c_double</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="n">c_double</span><span class="p">)]</span>

<span class="k">def</span> <span class="nf">modify</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">A</span><span class="p">):</span>
    <span class="n">n</span><span class="o">.</span><span class="n">value</span> <span class="o">**=</span> <span class="mi">2</span>
    <span class="n">x</span><span class="o">.</span><span class="n">value</span> <span class="o">**=</span> <span class="mi">2</span>
    <span class="n">s</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">value</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">A</span><span class="p">:</span>
        <span class="n">a</span><span class="o">.</span><span class="n">x</span> <span class="o">**=</span> <span class="mi">2</span>
        <span class="n">a</span><span class="o">.</span><span class="n">y</span> <span class="o">**=</span> <span class="mi">2</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">lock</span> <span class="o">=</span> <span class="n">Lock</span><span class="p">()</span>

    <span class="n">n</span> <span class="o">=</span> <span class="n">Value</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">Value</span><span class="p">(</span><span class="n">c_double</span><span class="p">,</span> <span class="mf">1.0</span><span class="o">/</span><span class="mf">3.0</span><span class="p">,</span> <span class="n">lock</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">Array</span><span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;hello world&#39;</span><span class="p">,</span> <span class="n">lock</span><span class="o">=</span><span class="n">lock</span><span class="p">)</span>
    <span class="n">A</span> <span class="o">=</span> <span class="n">Array</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="p">[(</span><span class="mf">1.875</span><span class="p">,</span><span class="o">-</span><span class="mf">6.25</span><span class="p">),</span> <span class="p">(</span><span class="o">-</span><span class="mf">5.75</span><span class="p">,</span><span class="mf">2.0</span><span class="p">),</span> <span class="p">(</span><span class="mf">2.375</span><span class="p">,</span><span class="mf">9.5</span><span class="p">)],</span> <span class="n">lock</span><span class="o">=</span><span class="n">lock</span><span class="p">)</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">modify</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">s</span><span class="p">,</span> <span class="n">A</span><span class="p">))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="nb">print</span> <span class="n">n</span><span class="o">.</span><span class="n">value</span>
    <span class="nb">print</span> <span class="n">x</span><span class="o">.</span><span class="n">value</span>
    <span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">value</span>
    <span class="nb">print</span> <span class="p">[(</span><span class="n">a</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">a</span><span class="o">.</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">A</span><span class="p">]</span>
</pre></div>
</div>
<p>The results printed are</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>49
0.1111111111111111
HELLO WORLD
[(3.515625, 39.0625), (33.0625, 4.0), (5.640625, 90.25)]
</pre></div>
</div>
</div>
</div>
<div class="section" id="managers">
<span id="multiprocessing-managers"></span><h3>16.6.2.7. Managers<a class="headerlink" href="#managers" title="Permalink to this headline">¶</a></h3>
<p>Managers provide a way to create data which can be shared between different
processes. A manager object controls a server process which manages <em>shared
objects</em>.  Other processes can access the shared objects by using proxies.</p>
<dl class="function">
<dt id="multiprocessing.sharedctypes.multiprocessing.Manager">
<code class="descclassname">multiprocessing.</code><code class="descname">Manager</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.sharedctypes.multiprocessing.Manager" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a started <a class="reference internal" href="#multiprocessing.managers.SyncManager" title="multiprocessing.managers.SyncManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">SyncManager</span></code></a> object which
can be used for sharing objects between processes.  The returned manager
object corresponds to a spawned child process and has methods which will
create shared objects and return corresponding proxies.</p>
</dd></dl>

<span class="target" id="module-multiprocessing.managers"></span><p>Manager processes will be shutdown as soon as they are garbage collected or
their parent process exits.  The manager classes are defined in the
<a class="reference internal" href="#module-multiprocessing.managers" title="multiprocessing.managers: Share data between process with shared objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.managers</span></code></a> module:</p>
<dl class="class">
<dt id="multiprocessing.managers.BaseManager">
<em class="property">class </em><code class="descclassname">multiprocessing.managers.</code><code class="descname">BaseManager</code><span class="sig-paren">(</span><span class="optional">[</span><em>address</em><span class="optional">[</span>, <em>authkey</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a BaseManager object.</p>
<p>Once created one should call <a class="reference internal" href="#multiprocessing.managers.BaseManager.start" title="multiprocessing.managers.BaseManager.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> or <code class="docutils literal notranslate"><span class="pre">get_server().serve_forever()</span></code> to ensure
that the manager object refers to a started manager process.</p>
<p><em>address</em> is the address on which the manager process listens for new
connections.  If <em>address</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then an arbitrary one is chosen.</p>
<p><em>authkey</em> is the authentication key which will be used to check the validity
of incoming connections to the server process.  If <em>authkey</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then
<code class="docutils literal notranslate"><span class="pre">current_process().authkey</span></code>.  Otherwise <em>authkey</em> is used and it
must be a string.</p>
<dl class="method">
<dt id="multiprocessing.managers.BaseManager.start">
<code class="descname">start</code><span class="sig-paren">(</span><span class="optional">[</span><em>initializer</em><span class="optional">[</span>, <em>initargs</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Start a subprocess to start the manager.  If <em>initializer</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>
then the subprocess will call <code class="docutils literal notranslate"><span class="pre">initializer(*initargs)</span></code> when it starts.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseManager.get_server">
<code class="descname">get_server</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager.get_server" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code> object which represents the actual server under
the control of the Manager. The <code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code> object supports the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code> method:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">manager</span> <span class="o">=</span> <span class="n">BaseManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">50000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">get_server</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code> additionally has an <a class="reference internal" href="#multiprocessing.managers.BaseManager.address" title="multiprocessing.managers.BaseManager.address"><code class="xref py py-attr docutils literal notranslate"><span class="pre">address</span></code></a> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseManager.connect">
<code class="descname">connect</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect a local manager object to a remote manager process:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">BaseManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;127.0.0.1&#39;</span><span class="p">,</span> <span class="mi">5000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseManager.shutdown">
<code class="descname">shutdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the process used by the manager.  This is only available if
<a class="reference internal" href="#multiprocessing.managers.BaseManager.start" title="multiprocessing.managers.BaseManager.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> has been used to start the server process.</p>
<p>This can be called multiple times.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseManager.register">
<code class="descname">register</code><span class="sig-paren">(</span><em>typeid</em><span class="optional">[</span>, <em>callable</em><span class="optional">[</span>, <em>proxytype</em><span class="optional">[</span>, <em>exposed</em><span class="optional">[</span>, <em>method_to_typeid</em><span class="optional">[</span>, <em>create_method</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseManager.register" title="Permalink to this definition">¶</a></dt>
<dd><p>A classmethod which can be used for registering a type or callable with
the manager class.</p>
<p><em>typeid</em> is a “type identifier” which is used to identify a particular
type of shared object.  This must be a string.</p>
<p><em>callable</em> is a callable used for creating objects for this type
identifier.  If a manager instance will be created using the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">from_address()</span></code> classmethod or if the <em>create_method</em> argument is
<code class="docutils literal notranslate"><span class="pre">False</span></code> then this can be left as <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p><em>proxytype</em> is a subclass of <a class="reference internal" href="#multiprocessing.managers.BaseProxy" title="multiprocessing.managers.BaseProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseProxy</span></code></a> which is used to create
proxies for shared objects with this <em>typeid</em>.  If <code class="docutils literal notranslate"><span class="pre">None</span></code> then a proxy
class is created automatically.</p>
<p><em>exposed</em> is used to specify a sequence of method names which proxies for
this typeid should be allowed to access using
<a class="reference internal" href="#multiprocessing.managers.BaseProxy._callmethod" title="multiprocessing.managers.BaseProxy._callmethod"><code class="xref py py-meth docutils literal notranslate"><span class="pre">BaseProxy._callmethod()</span></code></a>.  (If <em>exposed</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then
<code class="xref py py-attr docutils literal notranslate"><span class="pre">proxytype._exposed_</span></code> is used instead if it exists.)  In the case
where no exposed list is specified, all “public methods” of the shared
object will be accessible.  (Here a “public method” means any attribute
which has a <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method and whose name does not begin
with <code class="docutils literal notranslate"><span class="pre">'_'</span></code>.)</p>
<p><em>method_to_typeid</em> is a mapping used to specify the return type of those
exposed methods which should return a proxy.  It maps method names to
typeid strings.  (If <em>method_to_typeid</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then
<code class="xref py py-attr docutils literal notranslate"><span class="pre">proxytype._method_to_typeid_</span></code> is used instead if it exists.)  If a
method’s name is not a key of this mapping or if the mapping is <code class="docutils literal notranslate"><span class="pre">None</span></code>
then the object returned by the method will be copied by value.</p>
<p><em>create_method</em> determines whether a method should be created with name
<em>typeid</em> which can be used to tell the server process to create a new
shared object and return a proxy for it.  By default it is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<p><a class="reference internal" href="#multiprocessing.managers.BaseManager" title="multiprocessing.managers.BaseManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseManager</span></code></a> instances also have one read-only property:</p>
<dl class="attribute">
<dt id="multiprocessing.managers.BaseManager.address">
<code class="descname">address</code><a class="headerlink" href="#multiprocessing.managers.BaseManager.address" title="Permalink to this definition">¶</a></dt>
<dd><p>The address used by the manager.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="multiprocessing.managers.SyncManager">
<em class="property">class </em><code class="descclassname">multiprocessing.managers.</code><code class="descname">SyncManager</code><a class="headerlink" href="#multiprocessing.managers.SyncManager" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#multiprocessing.managers.BaseManager" title="multiprocessing.managers.BaseManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseManager</span></code></a> which can be used for the synchronization
of processes.  Objects of this type are returned by
<code class="xref py py-func docutils literal notranslate"><span class="pre">multiprocessing.Manager()</span></code>.</p>
<p>It also supports creation of shared lists and dictionaries.</p>
<dl class="method">
<dt id="multiprocessing.managers.SyncManager.BoundedSemaphore">
<code class="descname">BoundedSemaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.BoundedSemaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.BoundedSemaphore" title="threading.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.BoundedSemaphore</span></code></a> object and return a
proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Condition">
<code class="descname">Condition</code><span class="sig-paren">(</span><span class="optional">[</span><em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Condition" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.Condition" title="threading.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Condition</span></code></a> object and return a proxy for
it.</p>
<p>If <em>lock</em> is supplied then it should be a proxy for a
<a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a> or <a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> object.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Event">
<code class="descname">Event</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Event" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.Event" title="threading.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Event</span></code></a> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Lock">
<code class="descname">Lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Lock</span></code></a> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Namespace">
<code class="descname">Namespace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="#multiprocessing.managers.Namespace" title="multiprocessing.managers.Namespace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Namespace</span></code></a> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Queue">
<code class="descname">Queue</code><span class="sig-paren">(</span><span class="optional">[</span><em>maxsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Queue" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.RLock">
<code class="descname">RLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.RLock" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.RLock</span></code></a> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Semaphore">
<code class="descname">Semaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Semaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a shared <a class="reference internal" href="threading.html#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Semaphore</span></code></a> object and return a proxy for
it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Array">
<code class="descname">Array</code><span class="sig-paren">(</span><em>typecode</em>, <em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Array" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an array and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.Value">
<code class="descname">Value</code><span class="sig-paren">(</span><em>typecode</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.Value" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an object with a writable <code class="docutils literal notranslate"><span class="pre">value</span></code> attribute and return a proxy
for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.dict">
<code class="descname">dict</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.dict" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">dict</code><span class="sig-paren">(</span><em>mapping</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descname">dict</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span></dt>
<dd><p>Create a shared <code class="docutils literal notranslate"><span class="pre">dict</span></code> object and return a proxy for it.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.SyncManager.list">
<code class="descname">list</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.SyncManager.list" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">list</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span></dt>
<dd><p>Create a shared <code class="docutils literal notranslate"><span class="pre">list</span></code> object and return a proxy for it.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Modifications to mutable values or items in dict and list proxies will not
be propagated through the manager, because the proxy has no way of knowing
when its values or items are modified.  To modify such an item, you can
re-assign the modified object to the container proxy:</p>
<div class="last highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1"># create a list proxy and append a mutable object (a dictionary)</span>
<span class="n">lproxy</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">()</span>
<span class="n">lproxy</span><span class="o">.</span><span class="n">append</span><span class="p">({})</span>
<span class="c1"># now mutate the dictionary</span>
<span class="n">d</span> <span class="o">=</span> <span class="n">lproxy</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">2</span>
<span class="c1"># at this point, the changes to d are not yet synced, but by</span>
<span class="c1"># reassigning the dictionary, the proxy is notified of the change</span>
<span class="n">lproxy</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">d</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.managers.Namespace">
<em class="property">class </em><code class="descclassname">multiprocessing.managers.</code><code class="descname">Namespace</code><a class="headerlink" href="#multiprocessing.managers.Namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>A type that can register with <a class="reference internal" href="#multiprocessing.managers.SyncManager" title="multiprocessing.managers.SyncManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">SyncManager</span></code></a>.</p>
<p>A namespace object has no public methods, but does have writable attributes.
Its representation shows the values of its attributes.</p>
<p>However, when using a proxy for a namespace object, an attribute beginning with
<code class="docutils literal notranslate"><span class="pre">'_'</span></code> will be an attribute of the proxy and not an attribute of the referent:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">manager</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Global</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">Namespace</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Global</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Global</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="s1">&#39;hello&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Global</span><span class="o">.</span><span class="n">_z</span> <span class="o">=</span> <span class="mf">12.3</span>    <span class="c1"># this is an attribute of the proxy</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">Global</span>
<span class="go">Namespace(x=10, y=&#39;hello&#39;)</span>
</pre></div>
</div>
</dd></dl>

<div class="section" id="customized-managers">
<h4>16.6.2.7.1. Customized managers<a class="headerlink" href="#customized-managers" title="Permalink to this headline">¶</a></h4>
<p>To create one’s own manager, one creates a subclass of <a class="reference internal" href="#multiprocessing.managers.BaseManager" title="multiprocessing.managers.BaseManager"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseManager</span></code></a> and
uses the <a class="reference internal" href="#multiprocessing.managers.BaseManager.register" title="multiprocessing.managers.BaseManager.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> classmethod to register new types or
callables with the manager class.  For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>

<span class="k">class</span> <span class="nc">MathsClass</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
    <span class="k">def</span> <span class="nf">mul</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">x</span> <span class="o">*</span> <span class="n">y</span>

<span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="n">MyManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;Maths&#39;</span><span class="p">,</span> <span class="n">MathsClass</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">manager</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
    <span class="n">manager</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">maths</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">Maths</span><span class="p">()</span>
    <span class="k">print</span> <span class="n">maths</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>         <span class="c1"># prints 7</span>
    <span class="k">print</span> <span class="n">maths</span><span class="o">.</span><span class="n">mul</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span>         <span class="c1"># prints 56</span>
</pre></div>
</div>
</div>
<div class="section" id="using-a-remote-manager">
<h4>16.6.2.7.2. Using a remote manager<a class="headerlink" href="#using-a-remote-manager" title="Permalink to this headline">¶</a></h4>
<p>It is possible to run a manager server on one machine and have clients use it
from other machines (assuming that the firewalls involved allow it).</p>
<p>Running the following commands creates a server for a single shared queue which
remote clients can access:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">Queue</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">QueueManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">QueueManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;get_queue&#39;</span><span class="p">,</span> <span class="nb">callable</span><span class="o">=</span><span class="k">lambda</span><span class="p">:</span><span class="n">queue</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">QueueManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">50000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">get_server</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>One client can access the server as follows:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">QueueManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">QueueManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;get_queue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">QueueManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;foo.bar.org&#39;</span><span class="p">,</span> <span class="mi">50000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">get_queue</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Another client can also use it:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">QueueManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">QueueManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;get_queue&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">QueueManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;foo.bar.org&#39;</span><span class="p">,</span> <span class="mi">50000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">connect</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">get_queue</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
<span class="go">&#39;hello&#39;</span>
</pre></div>
</div>
<p>Local processes can also access that queue, using the code from above on the
client to access it remotely:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Worker</span><span class="p">(</span><span class="n">Process</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">q</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">q</span> <span class="o">=</span> <span class="n">q</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">Worker</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;local hello&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span> <span class="o">=</span> <span class="n">Worker</span><span class="p">(</span><span class="n">queue</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">w</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">QueueManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">QueueManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;get_queue&#39;</span><span class="p">,</span> <span class="nb">callable</span><span class="o">=</span><span class="k">lambda</span><span class="p">:</span> <span class="n">queue</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">QueueManager</span><span class="p">(</span><span class="n">address</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">50000</span><span class="p">),</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">get_server</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="proxy-objects">
<h3>16.6.2.8. Proxy Objects<a class="headerlink" href="#proxy-objects" title="Permalink to this headline">¶</a></h3>
<p>A proxy is an object which <em>refers</em> to a shared object which lives (presumably)
in a different process.  The shared object is said to be the <em>referent</em> of the
proxy.  Multiple proxy objects may have the same referent.</p>
<p>A proxy object has methods which invoke corresponding methods of its referent
(although not every method of the referent will necessarily be available through
the proxy).  A proxy can usually be used in most of the same ways that its
referent can:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Manager</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">manager</span> <span class="o">=</span> <span class="n">Manager</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">([</span><span class="n">i</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">l</span>
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">l</span><span class="p">)</span>
<span class="go">&lt;ListProxy object, typeid &#39;list&#39; at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span>
<span class="go">16</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>
<span class="go">[4, 9, 16]</span>
</pre></div>
</div>
<p>Notice that applying <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> to a proxy will return the representation of
the referent, whereas applying <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> will return the representation of
the proxy.</p>
<p>An important feature of proxy objects is that they are picklable so they can be
passed between processes.  Note, however, that if a proxy is sent to the
corresponding manager’s process then unpickling it will produce the referent
itself.  This means, for example, that one shared object can contain a second:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>         <span class="c1"># referent of a now contains referent of b</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="go">[[]] []</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="go">[[&#39;hello&#39;]] [&#39;hello&#39;]</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The proxy types in <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> do nothing to support comparisons
by value.  So, for instance, we have:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span> <span class="o">==</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="go">False</span>
</pre></div>
</div>
<p class="last">One should just use a copy of the referent instead when making comparisons.</p>
</div>
<dl class="class">
<dt id="multiprocessing.managers.BaseProxy">
<em class="property">class </em><code class="descclassname">multiprocessing.managers.</code><code class="descname">BaseProxy</code><a class="headerlink" href="#multiprocessing.managers.BaseProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Proxy objects are instances of subclasses of <a class="reference internal" href="#multiprocessing.managers.BaseProxy" title="multiprocessing.managers.BaseProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseProxy</span></code></a>.</p>
<dl class="method">
<dt id="multiprocessing.managers.BaseProxy._callmethod">
<code class="descname">_callmethod</code><span class="sig-paren">(</span><em>methodname</em><span class="optional">[</span>, <em>args</em><span class="optional">[</span>, <em>kwds</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseProxy._callmethod" title="Permalink to this definition">¶</a></dt>
<dd><p>Call and return the result of a method of the proxy’s referent.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">proxy</span></code> is a proxy whose referent is <code class="docutils literal notranslate"><span class="pre">obj</span></code> then the expression</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">proxy</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="n">methodname</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">kwds</span><span class="p">)</span>
</pre></div>
</div>
<p>will evaluate the expression</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">methodname</span><span class="p">)(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
</pre></div>
</div>
<p>in the manager’s process.</p>
<p>The returned value will be a copy of the result of the call or a proxy to
a new shared object – see documentation for the <em>method_to_typeid</em>
argument of <a class="reference internal" href="#multiprocessing.managers.BaseManager.register" title="multiprocessing.managers.BaseManager.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">BaseManager.register()</span></code></a>.</p>
<p>If an exception is raised by the call, then is re-raised by
<a class="reference internal" href="#multiprocessing.managers.BaseProxy._callmethod" title="multiprocessing.managers.BaseProxy._callmethod"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_callmethod()</span></code></a>.  If some other exception is raised in the manager’s
process then this is converted into a <code class="xref py py-exc docutils literal notranslate"><span class="pre">RemoteError</span></code> exception and is
raised by <a class="reference internal" href="#multiprocessing.managers.BaseProxy._callmethod" title="multiprocessing.managers.BaseProxy._callmethod"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_callmethod()</span></code></a>.</p>
<p>Note in particular that an exception will be raised if <em>methodname</em> has
not been <em>exposed</em>.</p>
<p>An example of the usage of <a class="reference internal" href="#multiprocessing.managers.BaseProxy._callmethod" title="multiprocessing.managers.BaseProxy._callmethod"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_callmethod()</span></code></a>:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">l</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="s1">&#39;__len__&#39;</span><span class="p">)</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="s1">&#39;__getslice__&#39;</span><span class="p">,</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">7</span><span class="p">))</span>   <span class="c1"># equiv to `l[2:7]`</span>
<span class="go">[2, 3, 4, 5, 6]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">l</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="s1">&#39;__getitem__&#39;</span><span class="p">,</span> <span class="p">(</span><span class="mi">20</span><span class="p">,))</span>     <span class="c1"># equiv to `l[20]`</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">IndexError</span>: <span class="n">list index out of range</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseProxy._getvalue">
<code class="descname">_getvalue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseProxy._getvalue" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the referent.</p>
<p>If the referent is unpicklable then this will raise an exception.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseProxy.__repr__">
<code class="descname">__repr__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseProxy.__repr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of the proxy object.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.managers.BaseProxy.__str__">
<code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.managers.BaseProxy.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the representation of the referent.</p>
</dd></dl>

</dd></dl>

<div class="section" id="cleanup">
<h4>16.6.2.8.1. Cleanup<a class="headerlink" href="#cleanup" title="Permalink to this headline">¶</a></h4>
<p>A proxy object uses a weakref callback so that when it gets garbage collected it
deregisters itself from the manager which owns its referent.</p>
<p>A shared object gets deleted from the manager process when there are no longer
any proxies referring to it.</p>
</div>
</div>
<div class="section" id="module-multiprocessing.pool">
<span id="process-pools"></span><h3>16.6.2.9. Process Pools<a class="headerlink" href="#module-multiprocessing.pool" title="Permalink to this headline">¶</a></h3>
<p>One can create a pool of processes which will carry out tasks submitted to it
with the <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> class.</p>
<dl class="class">
<dt id="multiprocessing.pool.multiprocessing.Pool">
<em class="property">class </em><code class="descclassname">multiprocessing.</code><code class="descname">Pool</code><span class="sig-paren">(</span><span class="optional">[</span><em>processes</em><span class="optional">[</span>, <em>initializer</em><span class="optional">[</span>, <em>initargs</em><span class="optional">[</span>, <em>maxtasksperchild</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool" title="Permalink to this definition">¶</a></dt>
<dd><p>A process pool object which controls a pool of worker processes to which jobs
can be submitted.  It supports asynchronous results with timeouts and
callbacks and has a parallel map implementation.</p>
<p><em>processes</em> is the number of worker processes to use.  If <em>processes</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code> then the number returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">cpu_count()</span></code> is used.  If
<em>initializer</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> then each worker process will call
<code class="docutils literal notranslate"><span class="pre">initializer(*initargs)</span></code> when it starts.</p>
<p>Note that the methods of the pool object should only be called by
the process which created the pool.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span><em>maxtasksperchild</em> is the number of tasks a worker process can complete
before it will exit and be replaced with a fresh worker process, to enable
unused resources to be freed. The default <em>maxtasksperchild</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, which
means worker processes will live as long as the pool.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Worker processes within a <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> typically live for the complete
duration of the Pool’s work queue. A frequent pattern found in other
systems (such as Apache, mod_wsgi, etc) to free resources held by
workers is to allow a worker within a pool to complete only a set
amount of work before being exiting, being cleaned up and a new
process spawned to replace the old one. The <em>maxtasksperchild</em>
argument to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> exposes this ability to the end user.</p>
</div>
<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.apply">
<code class="descname">apply</code><span class="sig-paren">(</span><em>func</em><span class="optional">[</span>, <em>args</em><span class="optional">[</span>, <em>kwds</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.apply" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent of the <a class="reference internal" href="functions.html#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a> built-in function.  It blocks until the
result is ready, so <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.apply_async" title="multiprocessing.pool.multiprocessing.Pool.apply_async"><code class="xref py py-meth docutils literal notranslate"><span class="pre">apply_async()</span></code></a> is better suited for performing
work in parallel. Additionally, <em>func</em> is only executed in one of the
workers of the pool.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.apply_async">
<code class="descname">apply_async</code><span class="sig-paren">(</span><em>func</em><span class="optional">[</span>, <em>args</em><span class="optional">[</span>, <em>kwds</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.apply_async" title="Permalink to this definition">¶</a></dt>
<dd><p>A variant of the <a class="reference internal" href="functions.html#apply" title="apply"><code class="xref py py-meth docutils literal notranslate"><span class="pre">apply()</span></code></a> method which returns a result object.</p>
<p>If <em>callback</em> is specified then it should be a callable which accepts a
single argument.  When the result becomes ready <em>callback</em> is applied to
it (unless the call failed).  <em>callback</em> should complete immediately since
otherwise the thread which handles the results will get blocked.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.map">
<code class="descname">map</code><span class="sig-paren">(</span><em>func</em>, <em>iterable</em><span class="optional">[</span>, <em>chunksize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.map" title="Permalink to this definition">¶</a></dt>
<dd><p>A parallel equivalent of the <a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> built-in function (it supports only
one <em>iterable</em> argument though).  It blocks until the result is ready.</p>
<p>This method chops the iterable into a number of chunks which it submits to
the process pool as separate tasks.  The (approximate) size of these
chunks can be specified by setting <em>chunksize</em> to a positive integer.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.map_async">
<code class="descname">map_async</code><span class="sig-paren">(</span><em>func</em>, <em>iterable</em><span class="optional">[</span>, <em>chunksize</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.map_async" title="Permalink to this definition">¶</a></dt>
<dd><p>A variant of the <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.map" title="multiprocessing.pool.multiprocessing.Pool.map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">map()</span></code></a> method which returns a result object.</p>
<p>If <em>callback</em> is specified then it should be a callable which accepts a
single argument.  When the result becomes ready <em>callback</em> is applied to
it (unless the call failed).  <em>callback</em> should complete immediately since
otherwise the thread which handles the results will get blocked.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.imap">
<code class="descname">imap</code><span class="sig-paren">(</span><em>func</em>, <em>iterable</em><span class="optional">[</span>, <em>chunksize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.imap" title="Permalink to this definition">¶</a></dt>
<dd><p>An equivalent of <a class="reference internal" href="itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a>.</p>
<p>The <em>chunksize</em> argument is the same as the one used by the <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.map" title="multiprocessing.pool.multiprocessing.Pool.map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">map()</span></code></a>
method.  For very long iterables using a large value for <em>chunksize</em> can
make the job complete <strong>much</strong> faster than using the default value of
<code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
<p>Also if <em>chunksize</em> is <code class="docutils literal notranslate"><span class="pre">1</span></code> then the <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code> method of the iterator
returned by the <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.imap" title="multiprocessing.pool.multiprocessing.Pool.imap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">imap()</span></code></a> method has an optional <em>timeout</em> parameter:
<code class="docutils literal notranslate"><span class="pre">next(timeout)</span></code> will raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">multiprocessing.TimeoutError</span></code> if the
result cannot be returned within <em>timeout</em> seconds.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.imap_unordered">
<code class="descname">imap_unordered</code><span class="sig-paren">(</span><em>func</em>, <em>iterable</em><span class="optional">[</span>, <em>chunksize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.imap_unordered" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.imap" title="multiprocessing.pool.multiprocessing.Pool.imap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">imap()</span></code></a> except that the ordering of the results from the
returned iterator should be considered arbitrary.  (Only when there is
only one worker process is the order guaranteed to be “correct”.)</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents any more tasks from being submitted to the pool.  Once all the
tasks have been completed the worker processes will exit.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.terminate">
<code class="descname">terminate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.terminate" title="Permalink to this definition">¶</a></dt>
<dd><p>Stops the worker processes immediately without completing outstanding
work.  When the pool object is garbage collected <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.terminate" title="multiprocessing.pool.multiprocessing.Pool.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a> will be
called immediately.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.multiprocessing.Pool.join">
<code class="descname">join</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.multiprocessing.Pool.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for the worker processes to exit.  One must call <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.close" title="multiprocessing.pool.multiprocessing.Pool.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> or
<a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.terminate" title="multiprocessing.pool.multiprocessing.Pool.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a> before using <a class="reference internal" href="#multiprocessing.pool.multiprocessing.Pool.join" title="multiprocessing.pool.multiprocessing.Pool.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="multiprocessing.pool.AsyncResult">
<em class="property">class </em><code class="descclassname">multiprocessing.pool.</code><code class="descname">AsyncResult</code><a class="headerlink" href="#multiprocessing.pool.AsyncResult" title="Permalink to this definition">¶</a></dt>
<dd><p>The class of the result returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">Pool.apply_async()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Pool.map_async()</span></code>.</p>
<dl class="method">
<dt id="multiprocessing.pool.AsyncResult.get">
<code class="descname">get</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.AsyncResult.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the result when it arrives.  If <em>timeout</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> and the
result does not arrive within <em>timeout</em> seconds then
<code class="xref py py-exc docutils literal notranslate"><span class="pre">multiprocessing.TimeoutError</span></code> is raised.  If the remote call raised
an exception then that exception will be reraised by <a class="reference internal" href="#multiprocessing.pool.AsyncResult.get" title="multiprocessing.pool.AsyncResult.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.AsyncResult.wait">
<code class="descname">wait</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.AsyncResult.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until the result is available or until <em>timeout</em> seconds pass.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.AsyncResult.ready">
<code class="descname">ready</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.AsyncResult.ready" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the call has completed.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.pool.AsyncResult.successful">
<code class="descname">successful</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.pool.AsyncResult.successful" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the call completed without raising an exception.  Will
raise <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> if the result is not ready.</p>
</dd></dl>

</dd></dl>

<p>The following example demonstrates the use of a pool:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Pool</span>
<span class="kn">import</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="n">processes</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>              <span class="c1"># start 4 worker processes</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="mi">10</span><span class="p">,))</span>   <span class="c1"># evaluate &quot;f(10)&quot; asynchronously in a single process</span>
    <span class="k">print</span> <span class="n">result</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>           <span class="c1"># prints &quot;100&quot; unless your computer is *very* slow</span>

    <span class="k">print</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>          <span class="c1"># prints &quot;[0, 1, 4,..., 81]&quot;</span>

    <span class="n">it</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
    <span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>                       <span class="c1"># prints &quot;0&quot;</span>
    <span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>                       <span class="c1"># prints &quot;1&quot;</span>
    <span class="k">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>              <span class="c1"># prints &quot;4&quot; unless your computer is *very* slow</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="p">(</span><span class="mi">10</span><span class="p">,))</span>
    <span class="k">print</span> <span class="n">result</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>           <span class="c1"># raises multiprocessing.TimeoutError</span>
</pre></div>
</div>
</div>
<div class="section" id="module-multiprocessing.connection">
<span id="listeners-and-clients"></span><span id="multiprocessing-listeners-clients"></span><h3>16.6.2.10. Listeners and Clients<a class="headerlink" href="#module-multiprocessing.connection" title="Permalink to this headline">¶</a></h3>
<p>Usually message passing between processes is done using queues or by using
<a class="reference internal" href="#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> objects returned by <a class="reference internal" href="#multiprocessing.Pipe" title="multiprocessing.Pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pipe()</span></code></a>.</p>
<p>However, the <a class="reference internal" href="#module-multiprocessing.connection" title="multiprocessing.connection: API for dealing with sockets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.connection</span></code></a> module allows some extra
flexibility.  It basically gives a high level message oriented API for dealing
with sockets or Windows named pipes, and also has support for <em>digest
authentication</em> using the <a class="reference internal" href="hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a> module.</p>
<dl class="function">
<dt id="multiprocessing.connection.deliver_challenge">
<code class="descclassname">multiprocessing.connection.</code><code class="descname">deliver_challenge</code><span class="sig-paren">(</span><em>connection</em>, <em>authkey</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.deliver_challenge" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a randomly generated message to the other end of the connection and wait
for a reply.</p>
<p>If the reply matches the digest of the message using <em>authkey</em> as the key
then a welcome message is sent to the other end of the connection.  Otherwise
<a class="reference internal" href="#multiprocessing.connection.AuthenticationError" title="multiprocessing.connection.AuthenticationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AuthenticationError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.connection.answer_challenge">
<code class="descclassname">multiprocessing.connection.</code><code class="descname">answer_challenge</code><span class="sig-paren">(</span><em>connection</em>, <em>authkey</em><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.answer_challenge" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive a message, calculate the digest of the message using <em>authkey</em> as the
key, and then send the digest back.</p>
<p>If a welcome message is not received, then <a class="reference internal" href="#multiprocessing.connection.AuthenticationError" title="multiprocessing.connection.AuthenticationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AuthenticationError</span></code></a> is
raised.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.connection.Client">
<code class="descclassname">multiprocessing.connection.</code><code class="descname">Client</code><span class="sig-paren">(</span><em>address</em><span class="optional">[</span>, <em>family</em><span class="optional">[</span>, <em>authenticate</em><span class="optional">[</span>, <em>authkey</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.Client" title="Permalink to this definition">¶</a></dt>
<dd><p>Attempt to set up a connection to the listener which is using address
<em>address</em>, returning a <a class="reference internal" href="#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a>.</p>
<p>The type of the connection is determined by <em>family</em> argument, but this can
generally be omitted since it can usually be inferred from the format of
<em>address</em>. (See <a class="reference internal" href="#multiprocessing-address-formats"><span class="std std-ref">Address Formats</span></a>)</p>
<p>If <em>authenticate</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> or <em>authkey</em> is a string then digest
authentication is used.  The key used for authentication will be either
<em>authkey</em> or <code class="docutils literal notranslate"><span class="pre">current_process().authkey)</span></code> if <em>authkey</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.
If authentication fails then <a class="reference internal" href="#multiprocessing.connection.AuthenticationError" title="multiprocessing.connection.AuthenticationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AuthenticationError</span></code></a> is raised.  See
<a class="reference internal" href="#multiprocessing-auth-keys"><span class="std std-ref">Authentication keys</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="multiprocessing.connection.Listener">
<em class="property">class </em><code class="descclassname">multiprocessing.connection.</code><code class="descname">Listener</code><span class="sig-paren">(</span><span class="optional">[</span><em>address</em><span class="optional">[</span>, <em>family</em><span class="optional">[</span>, <em>backlog</em><span class="optional">[</span>, <em>authenticate</em><span class="optional">[</span>, <em>authkey</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.Listener" title="Permalink to this definition">¶</a></dt>
<dd><p>A wrapper for a bound socket or Windows named pipe which is ‘listening’ for
connections.</p>
<p><em>address</em> is the address to be used by the bound socket or named pipe of the
listener object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If an address of ‘0.0.0.0’ is used, the address will not be a connectable
end point on Windows. If you require a connectable end-point,
you should use ‘127.0.0.1’.</p>
</div>
<p><em>family</em> is the type of socket (or named pipe) to use.  This can be one of
the strings <code class="docutils literal notranslate"><span class="pre">'AF_INET'</span></code> (for a TCP socket), <code class="docutils literal notranslate"><span class="pre">'AF_UNIX'</span></code> (for a Unix
domain socket) or <code class="docutils literal notranslate"><span class="pre">'AF_PIPE'</span></code> (for a Windows named pipe).  Of these only
the first is guaranteed to be available.  If <em>family</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> then the
family is inferred from the format of <em>address</em>.  If <em>address</em> is also
<code class="docutils literal notranslate"><span class="pre">None</span></code> then a default is chosen.  This default is the family which is
assumed to be the fastest available.  See
<a class="reference internal" href="#multiprocessing-address-formats"><span class="std std-ref">Address Formats</span></a>.  Note that if <em>family</em> is
<code class="docutils literal notranslate"><span class="pre">'AF_UNIX'</span></code> and address is <code class="docutils literal notranslate"><span class="pre">None</span></code> then the socket will be created in a
private temporary directory created using <a class="reference internal" href="tempfile.html#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempfile.mkstemp()</span></code></a>.</p>
<p>If the listener object uses a socket then <em>backlog</em> (1 by default) is passed
to the <a class="reference internal" href="socket.html#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a> method of the socket once it has been
bound.</p>
<p>If <em>authenticate</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> (<code class="docutils literal notranslate"><span class="pre">False</span></code> by default) or <em>authkey</em> is not
<code class="docutils literal notranslate"><span class="pre">None</span></code> then digest authentication is used.</p>
<p>If <em>authkey</em> is a string then it will be used as the authentication key;
otherwise it must be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>If <em>authkey</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> and <em>authenticate</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> then
<code class="docutils literal notranslate"><span class="pre">current_process().authkey</span></code> is used as the authentication key.  If
<em>authkey</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> and <em>authenticate</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> then no
authentication is done.  If authentication fails then
<a class="reference internal" href="#multiprocessing.connection.AuthenticationError" title="multiprocessing.connection.AuthenticationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AuthenticationError</span></code></a> is raised.  See <a class="reference internal" href="#multiprocessing-auth-keys"><span class="std std-ref">Authentication keys</span></a>.</p>
<dl class="method">
<dt id="multiprocessing.connection.Listener.accept">
<code class="descname">accept</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.Listener.accept" title="Permalink to this definition">¶</a></dt>
<dd><p>Accept a connection on the bound socket or named pipe of the listener
object and return a <a class="reference internal" href="#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> object.
If authentication is attempted and fails, then
<code class="xref py py-exc docutils literal notranslate"><span class="pre">AuthenticationError</span></code> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="multiprocessing.connection.Listener.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.connection.Listener.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the bound socket or named pipe of the listener object.  This is
called automatically when the listener is garbage collected.  However it
is advisable to call it explicitly.</p>
</dd></dl>

<p>Listener objects have the following read-only properties:</p>
<dl class="attribute">
<dt id="multiprocessing.connection.Listener.address">
<code class="descname">address</code><a class="headerlink" href="#multiprocessing.connection.Listener.address" title="Permalink to this definition">¶</a></dt>
<dd><p>The address which is being used by the Listener object.</p>
</dd></dl>

<dl class="attribute">
<dt id="multiprocessing.connection.Listener.last_accepted">
<code class="descname">last_accepted</code><a class="headerlink" href="#multiprocessing.connection.Listener.last_accepted" title="Permalink to this definition">¶</a></dt>
<dd><p>The address from which the last accepted connection came.  If this is
unavailable then it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</dd></dl>

<p>The module defines the following exceptions:</p>
<dl class="exception">
<dt id="multiprocessing.connection.ProcessError">
<em class="property">exception </em><code class="descclassname">multiprocessing.connection.</code><code class="descname">ProcessError</code><a class="headerlink" href="#multiprocessing.connection.ProcessError" title="Permalink to this definition">¶</a></dt>
<dd><p>The base class of all <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> exceptions.</p>
</dd></dl>

<dl class="exception">
<dt id="multiprocessing.connection.BufferTooShort">
<em class="property">exception </em><code class="descclassname">multiprocessing.connection.</code><code class="descname">BufferTooShort</code><a class="headerlink" href="#multiprocessing.connection.BufferTooShort" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by <a class="reference internal" href="#Connection.recv_bytes_into" title="Connection.recv_bytes_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Connection.recv_bytes_into()</span></code></a> when the supplied
buffer object is too small for the message read.</p>
</dd></dl>

<dl class="exception">
<dt id="multiprocessing.connection.AuthenticationError">
<em class="property">exception </em><code class="descclassname">multiprocessing.connection.</code><code class="descname">AuthenticationError</code><a class="headerlink" href="#multiprocessing.connection.AuthenticationError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when there is an authentication error.</p>
</dd></dl>

<dl class="exception">
<dt id="multiprocessing.connection.TimeoutError">
<em class="property">exception </em><code class="descclassname">multiprocessing.connection.</code><code class="descname">TimeoutError</code><a class="headerlink" href="#multiprocessing.connection.TimeoutError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised by methods with a timeout when the timeout expires.</p>
</dd></dl>

<p><strong>Examples</strong></p>
<p>The following server code creates a listener which uses <code class="docutils literal notranslate"><span class="pre">'secret</span> <span class="pre">password'</span></code> as
an authentication key.  It then waits for a connection and sends some data to
the client:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing.connection</span> <span class="kn">import</span> <span class="n">Listener</span>
<span class="kn">from</span> <span class="nn">array</span> <span class="kn">import</span> <span class="n">array</span>

<span class="n">address</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span> <span class="mi">6000</span><span class="p">)</span>     <span class="c1"># family is deduced to be &#39;AF_INET&#39;</span>
<span class="n">listener</span> <span class="o">=</span> <span class="n">Listener</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;secret password&#39;</span><span class="p">)</span>

<span class="n">conn</span> <span class="o">=</span> <span class="n">listener</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
<span class="k">print</span> <span class="s1">&#39;connection accepted from&#39;</span><span class="p">,</span> <span class="n">listener</span><span class="o">.</span><span class="n">last_accepted</span>

<span class="n">conn</span><span class="o">.</span><span class="n">send</span><span class="p">([</span><span class="mf">2.25</span><span class="p">,</span> <span class="bp">None</span><span class="p">,</span> <span class="s1">&#39;junk&#39;</span><span class="p">,</span> <span class="nb">float</span><span class="p">])</span>

<span class="n">conn</span><span class="o">.</span><span class="n">send_bytes</span><span class="p">(</span><span class="s1">&#39;hello&#39;</span><span class="p">)</span>

<span class="n">conn</span><span class="o">.</span><span class="n">send_bytes</span><span class="p">(</span><span class="n">array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">42</span><span class="p">,</span> <span class="mi">1729</span><span class="p">]))</span>

<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">listener</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The following code connects to the server and receives some data from the
server:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing.connection</span> <span class="kn">import</span> <span class="n">Client</span>
<span class="kn">from</span> <span class="nn">array</span> <span class="kn">import</span> <span class="n">array</span>

<span class="n">address</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span> <span class="mi">6000</span><span class="p">)</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">Client</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">authkey</span><span class="o">=</span><span class="s1">&#39;secret password&#39;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">()</span>                 <span class="c1"># =&gt; [2.25, None, &#39;junk&#39;, float]</span>

<span class="k">print</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv_bytes</span><span class="p">()</span>            <span class="c1"># =&gt; &#39;hello&#39;</span>

<span class="n">arr</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">])</span>
<span class="k">print</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv_bytes_into</span><span class="p">(</span><span class="n">arr</span><span class="p">)</span>     <span class="c1"># =&gt; 8</span>
<span class="k">print</span> <span class="n">arr</span>                         <span class="c1"># =&gt; array(&#39;i&#39;, [42, 1729, 0, 0, 0])</span>

<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="address-formats">
<span id="multiprocessing-address-formats"></span><h4>16.6.2.10.1. Address Formats<a class="headerlink" href="#address-formats" title="Permalink to this headline">¶</a></h4>
<ul class="simple">
<li>An <code class="docutils literal notranslate"><span class="pre">'AF_INET'</span></code> address is a tuple of the form <code class="docutils literal notranslate"><span class="pre">(hostname,</span> <span class="pre">port)</span></code> where
<em>hostname</em> is a string and <em>port</em> is an integer.</li>
<li>An <code class="docutils literal notranslate"><span class="pre">'AF_UNIX'</span></code> address is a string representing a filename on the
filesystem.</li>
<li><dl class="first docutils">
<dt>An <code class="docutils literal notranslate"><span class="pre">'AF_PIPE'</span></code> address is a string of the form</dt>
<dd><code class="samp docutils literal notranslate"><span class="pre">r'\\.\pipe\</span><em><span class="pre">PipeName</span></em><span class="pre">'</span></code>.  To use <a class="reference internal" href="#multiprocessing.connection.Client" title="multiprocessing.connection.Client"><code class="xref py py-func docutils literal notranslate"><span class="pre">Client()</span></code></a> to connect to a named
pipe on a remote computer called <em>ServerName</em> one should use an address of the
form <code class="samp docutils literal notranslate"><span class="pre">r'\\</span><em><span class="pre">ServerName</span></em><span class="pre">\pipe\</span><em><span class="pre">PipeName</span></em><span class="pre">'</span></code> instead.</dd>
</dl>
</li>
</ul>
<p>Note that any string beginning with two backslashes is assumed by default to be
an <code class="docutils literal notranslate"><span class="pre">'AF_PIPE'</span></code> address rather than an <code class="docutils literal notranslate"><span class="pre">'AF_UNIX'</span></code> address.</p>
</div>
</div>
<div class="section" id="authentication-keys">
<span id="multiprocessing-auth-keys"></span><h3>16.6.2.11. Authentication keys<a class="headerlink" href="#authentication-keys" title="Permalink to this headline">¶</a></h3>
<p>When one uses <a class="reference internal" href="#Connection.recv" title="Connection.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Connection.recv()</span></code></a>, the
data received is automatically
unpickled.  Unfortunately unpickling data from an untrusted source is a security
risk.  Therefore <a class="reference internal" href="#multiprocessing.connection.Listener" title="multiprocessing.connection.Listener"><code class="xref py py-class docutils literal notranslate"><span class="pre">Listener</span></code></a> and <a class="reference internal" href="#multiprocessing.connection.Client" title="multiprocessing.connection.Client"><code class="xref py py-func docutils literal notranslate"><span class="pre">Client()</span></code></a> use the <a class="reference internal" href="hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a> module
to provide digest authentication.</p>
<p>An authentication key is a string which can be thought of as a password: once a
connection is established both ends will demand proof that the other knows the
authentication key.  (Demonstrating that both ends are using the same key does
<strong>not</strong> involve sending the key over the connection.)</p>
<p>If authentication is requested but no authentication key is specified then the
return value of <code class="docutils literal notranslate"><span class="pre">current_process().authkey</span></code> is used (see
<a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a>).  This value will be automatically inherited by
any <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> object that the current process creates.
This means that (by default) all processes of a multi-process program will share
a single authentication key which can be used when setting up connections
between themselves.</p>
<p>Suitable authentication keys can also be generated by using <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a>.</p>
</div>
<div class="section" id="logging">
<h3>16.6.2.12. Logging<a class="headerlink" href="#logging" title="Permalink to this headline">¶</a></h3>
<p>Some support for logging is available.  Note, however, that the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a>
package does not use process shared locks so it is possible (depending on the
handler type) for messages from different processes to get mixed up.</p>
<dl class="function">
<dt id="multiprocessing.get_logger">
<code class="descclassname">multiprocessing.</code><code class="descname">get_logger</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.get_logger" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the logger used by <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>.  If necessary, a new one
will be created.</p>
<p>When first created the logger has level <code class="xref py py-data docutils literal notranslate"><span class="pre">logging.NOTSET</span></code> and no
default handler. Messages sent to this logger will not by default propagate
to the root logger.</p>
<p>Note that on Windows child processes will only inherit the level of the
parent process’s logger – any other customization of the logger will not be
inherited.</p>
</dd></dl>

<dl class="function">
<dt id="multiprocessing.log_to_stderr">
<code class="descclassname">multiprocessing.</code><code class="descname">log_to_stderr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#multiprocessing.log_to_stderr" title="Permalink to this definition">¶</a></dt>
<dd><p>This function performs a call to <a class="reference internal" href="#multiprocessing.get_logger" title="multiprocessing.get_logger"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_logger()</span></code></a> but in addition to
returning the logger created by get_logger, it adds a handler which sends
output to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a> using format
<code class="docutils literal notranslate"><span class="pre">'[%(levelname)s/%(processName)s]</span> <span class="pre">%(message)s'</span></code>.</p>
</dd></dl>

<p>Below is an example session with logging turned on:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">multiprocessing</span><span class="o">,</span> <span class="nn">logging</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">log_to_stderr</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">logging</span><span class="o">.</span><span class="n">INFO</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;doomed&#39;</span><span class="p">)</span>
<span class="go">[WARNING/MainProcess] doomed</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
<span class="go">[INFO/SyncManager-...] child process calling self.run()</span>
<span class="go">[INFO/SyncManager-...] created temp directory /.../pymp-...</span>
<span class="go">[INFO/SyncManager-...] manager serving at &#39;/.../listener-...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">m</span>
<span class="go">[INFO/MainProcess] sending shutdown message to manager</span>
<span class="go">[INFO/SyncManager-...] manager exiting with exitcode 0</span>
</pre></div>
</div>
<p>In addition to having these two logging functions, the multiprocessing also
exposes two additional logging level attributes. These are  <code class="xref py py-const docutils literal notranslate"><span class="pre">SUBWARNING</span></code>
and <code class="xref py py-const docutils literal notranslate"><span class="pre">SUBDEBUG</span></code>. The table below illustrates where theses fit in the
normal level hierarchy.</p>
<table border="1" class="docutils">
<colgroup>
<col width="50%" />
<col width="50%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Level</th>
<th class="head">Numeric value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">SUBWARNING</span></code></td>
<td>25</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">SUBDEBUG</span></code></td>
<td>5</td>
</tr>
</tbody>
</table>
<p>For a full table of logging levels, see the <a class="reference internal" href="logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module.</p>
<p>These additional logging levels are used primarily for certain debug messages
within the multiprocessing module. Below is the same example as above, except
with <code class="xref py py-const docutils literal notranslate"><span class="pre">SUBDEBUG</span></code> enabled:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">multiprocessing</span><span class="o">,</span> <span class="nn">logging</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">log_to_stderr</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span><span class="o">.</span><span class="n">setLevel</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">SUBDEBUG</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">logger</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;doomed&#39;</span><span class="p">)</span>
<span class="go">[WARNING/MainProcess] doomed</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
<span class="go">[INFO/SyncManager-...] child process calling self.run()</span>
<span class="go">[INFO/SyncManager-...] created temp directory /.../pymp-...</span>
<span class="go">[INFO/SyncManager-...] manager serving at &#39;/.../pymp-djGBXN/listener-...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">m</span>
<span class="go">[SUBDEBUG/MainProcess] finalizer calling ...</span>
<span class="go">[INFO/MainProcess] sending shutdown message to manager</span>
<span class="go">[DEBUG/SyncManager-...] manager received shutdown message</span>
<span class="go">[SUBDEBUG/SyncManager-...] calling &lt;Finalize object, callback=unlink, ...</span>
<span class="go">[SUBDEBUG/SyncManager-...] finalizer calling &lt;built-in function unlink&gt; ...</span>
<span class="go">[SUBDEBUG/SyncManager-...] calling &lt;Finalize object, dead&gt;</span>
<span class="go">[SUBDEBUG/SyncManager-...] finalizer calling &lt;function rmtree at 0x5aa730&gt; ...</span>
<span class="go">[INFO/SyncManager-...] manager exiting with exitcode 0</span>
</pre></div>
</div>
</div>
<div class="section" id="module-multiprocessing.dummy">
<span id="the-multiprocessing-dummy-module"></span><h3>16.6.2.13. The <a class="reference internal" href="#module-multiprocessing.dummy" title="multiprocessing.dummy: Dumb wrapper around threading."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.dummy</span></code></a> module<a class="headerlink" href="#module-multiprocessing.dummy" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-multiprocessing.dummy" title="multiprocessing.dummy: Dumb wrapper around threading."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing.dummy</span></code></a> replicates the API of <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> but is
no more than a wrapper around the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.</p>
</div>
</div>
<div class="section" id="programming-guidelines">
<span id="multiprocessing-programming"></span><h2>16.6.3. Programming guidelines<a class="headerlink" href="#programming-guidelines" title="Permalink to this headline">¶</a></h2>
<p>There are certain guidelines and idioms which should be adhered to when using
<a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>.</p>
<div class="section" id="all-platforms">
<h3>16.6.3.1. All platforms<a class="headerlink" href="#all-platforms" title="Permalink to this headline">¶</a></h3>
<p>Avoid shared state</p>
<blockquote>
<div><p>As far as possible one should try to avoid shifting large amounts of data
between processes.</p>
<p>It is probably best to stick to using queues or pipes for communication
between processes rather than using the lower level synchronization
primitives from the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.</p>
</div></blockquote>
<p>Picklability</p>
<blockquote>
<div>Ensure that the arguments to the methods of proxies are picklable.</div></blockquote>
<p>Thread safety of proxies</p>
<blockquote>
<div><p>Do not use a proxy object from more than one thread unless you protect it
with a lock.</p>
<p>(There is never a problem with different processes using the <em>same</em> proxy.)</p>
</div></blockquote>
<p>Joining zombie processes</p>
<blockquote>
<div>On Unix when a process finishes but has not been joined it becomes a zombie.
There should never be very many because each time a new process starts (or
<a class="reference internal" href="#multiprocessing.active_children" title="multiprocessing.active_children"><code class="xref py py-func docutils literal notranslate"><span class="pre">active_children()</span></code></a> is called) all completed processes
which have not yet been joined will be joined.  Also calling a finished
process’s <a class="reference internal" href="#multiprocessing.Process.is_alive" title="multiprocessing.Process.is_alive"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.is_alive</span></code></a> will
join the process.  Even so it is probably good
practice to explicitly join all the processes that you start.</div></blockquote>
<p>Better to inherit than pickle/unpickle</p>
<blockquote>
<div>On Windows many types from <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> need to be picklable so
that child processes can use them.  However, one should generally avoid
sending shared objects to other processes using pipes or queues.  Instead
you should arrange the program so that a process which needs access to a
shared resource created elsewhere can inherit it from an ancestor process.</div></blockquote>
<p>Avoid terminating processes</p>
<blockquote>
<div><p>Using the <a class="reference internal" href="#multiprocessing.Process.terminate" title="multiprocessing.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.terminate</span></code></a>
method to stop a process is liable to
cause any shared resources (such as locks, semaphores, pipes and queues)
currently being used by the process to become broken or unavailable to other
processes.</p>
<p>Therefore it is probably best to only consider using
<a class="reference internal" href="#multiprocessing.Process.terminate" title="multiprocessing.Process.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.terminate</span></code></a> on processes
which never use any shared resources.</p>
</div></blockquote>
<p>Joining processes that use queues</p>
<blockquote>
<div><p>Bear in mind that a process that has put items in a queue will wait before
terminating until all the buffered items are fed by the “feeder” thread to
the underlying pipe.  (The child process can call the
<a class="reference internal" href="#multiprocessing.Queue.cancel_join_thread" title="multiprocessing.Queue.cancel_join_thread"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel_join_thread()</span></code></a> method of the queue to avoid this behaviour.)</p>
<p>This means that whenever you use a queue you need to make sure that all
items which have been put on the queue will eventually be removed before the
process is joined.  Otherwise you cannot be sure that processes which have
put items on the queue will terminate.  Remember also that non-daemonic
processes will be joined automatically.</p>
<p>An example which will deadlock is the following:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">q</span><span class="p">):</span>
    <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;X&#39;</span> <span class="o">*</span> <span class="mi">1000000</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">queue</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>                    <span class="c1"># this deadlocks</span>
    <span class="n">obj</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
</pre></div>
</div>
<p>A fix here would be to swap the last two lines (or simply remove the
<code class="docutils literal notranslate"><span class="pre">p.join()</span></code> line).</p>
</div></blockquote>
<p>Explicitly pass resources to child processes</p>
<blockquote>
<div><p>On Unix a child process can make use of a shared resource created in a
parent process using a global resource.  However, it is better to pass the
object as an argument to the constructor for the child process.</p>
<p>Apart from making the code (potentially) compatible with Windows this also
ensures that as long as the child process is still alive the object will not
be garbage collected in the parent process.  This might be important if some
resource is freed when the object is garbage collected in the parent
process.</p>
<p>So for instance</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Lock</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="o">...</span> <span class="n">do</span> <span class="n">something</span> <span class="n">using</span> <span class="s2">&quot;lock&quot;</span> <span class="o">...</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">lock</span> <span class="o">=</span> <span class="n">Lock</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">)</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
<p>should be rewritten as</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Lock</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
    <span class="o">...</span> <span class="n">do</span> <span class="n">something</span> <span class="n">using</span> <span class="s2">&quot;l&quot;</span> <span class="o">...</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">lock</span> <span class="o">=</span> <span class="n">Lock</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">f</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">lock</span><span class="p">,))</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
</div></blockquote>
<p>Beware of replacing <a class="reference internal" href="sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a> with a “file like object”</p>
<blockquote>
<div><p><a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> originally unconditionally called:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
</pre></div>
</div>
<p>in the <code class="xref py py-meth docutils literal notranslate"><span class="pre">multiprocessing.Process._bootstrap()</span></code> method — this resulted
in issues with processes-in-processes. This has been changed to:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">sys</span><span class="o">.</span><span class="n">stdin</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">devnull</span><span class="p">)</span>
</pre></div>
</div>
<p>Which solves the fundamental issue of processes colliding with each other
resulting in a bad file descriptor error, but introduces a potential danger
to applications which replace <a class="reference internal" href="sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.stdin()</span></code></a> with a “file-like object”
with output buffering.  This danger is that if multiple processes call
<a class="reference internal" href="io.html#io.IOBase.close" title="io.IOBase.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> on this file-like object, it could result in the same
data being flushed to the object multiple times, resulting in corruption.</p>
<p>If you write a file-like object and implement your own caching, you can
make it fork-safe by storing the pid whenever you append to the cache,
and discarding the cache when the pid changes. For example:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="nd">@property</span>
<span class="k">def</span> <span class="nf">cache</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">pid</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">getpid</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">pid</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">_pid</span><span class="p">:</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_pid</span> <span class="o">=</span> <span class="n">pid</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_cache</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_cache</span>
</pre></div>
</div>
<p>For more information, see <a class="reference external" href="https://bugs.python.org/issue5155">bpo-5155</a>, <a class="reference external" href="https://bugs.python.org/issue5313">bpo-5313</a> and <a class="reference external" href="https://bugs.python.org/issue5331">bpo-5331</a></p>
</div></blockquote>
</div>
<div class="section" id="windows">
<h3>16.6.3.2. Windows<a class="headerlink" href="#windows" title="Permalink to this headline">¶</a></h3>
<p>Since Windows lacks <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a> it has a few extra restrictions:</p>
<p>More picklability</p>
<blockquote>
<div><p>Ensure that all arguments to <code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.__init__()</span></code> are picklable.  This
means, in particular, that bound or unbound methods cannot be used directly
as the <code class="docutils literal notranslate"><span class="pre">target</span></code> argument on Windows — just define a function and use
that instead.</p>
<p>Also, if you subclass <a class="reference internal" href="#multiprocessing.Process" title="multiprocessing.Process"><code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code></a> then make sure that
instances will be picklable when the <a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.start</span></code></a> method is called.</p>
</div></blockquote>
<p>Global variables</p>
<blockquote>
<div><p>Bear in mind that if code run in a child process tries to access a global
variable, then the value it sees (if any) may not be the same as the value
in the parent process at the time that <a class="reference internal" href="#multiprocessing.Process.start" title="multiprocessing.Process.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Process.start</span></code></a> was called.</p>
<p>However, global variables which are just module level constants cause no
problems.</p>
</div></blockquote>
<p>Safe importing of main module</p>
<blockquote>
<div><p>Make sure that the main module can be safely imported by a new Python
interpreter without causing unintended side effects (such a starting a new
process).</p>
<p>For example, under Windows running the following module would fail with a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span>

<span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
    <span class="k">print</span> <span class="s1">&#39;hello&#39;</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">foo</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
<p>Instead one should protect the “entry point” of the program by using <code class="docutils literal notranslate"><span class="pre">if</span>
<span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__':</span></code> as follows:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">freeze_support</span>

<span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
    <span class="k">print</span> <span class="s1">&#39;hello&#39;</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">foo</span><span class="p">)</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
</pre></div>
</div>
<p>(The <code class="docutils literal notranslate"><span class="pre">freeze_support()</span></code> line can be omitted if the program will be run
normally instead of frozen.)</p>
<p>This allows the newly spawned Python interpreter to safely import the module
and then run the module’s <code class="docutils literal notranslate"><span class="pre">foo()</span></code> function.</p>
<p>Similar restrictions apply if a pool or manager is created in the main
module.</p>
</div></blockquote>
</div>
</div>
<div class="section" id="examples">
<span id="multiprocessing-examples"></span><h2>16.6.4. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Demonstration of how to create and use customized managers and proxies:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># This module shows how to use arbitrary callables with a subclass of</span>
<span class="c1"># `BaseManager`.</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">freeze_support</span>
<span class="kn">from</span> <span class="nn">multiprocessing.managers</span> <span class="kn">import</span> <span class="n">BaseManager</span><span class="p">,</span> <span class="n">BaseProxy</span>
<span class="kn">import</span> <span class="nn">operator</span>

<span class="c1">##</span>

<span class="k">class</span> <span class="nc">Foo</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span> <span class="s1">&#39;you called Foo.f()&#39;</span>
    <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span> <span class="s1">&#39;you called Foo.g()&#39;</span>
    <span class="k">def</span> <span class="nf">_h</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">print</span> <span class="s1">&#39;you called Foo._h()&#39;</span>

<span class="c1"># A simple generator function</span>
<span class="k">def</span> <span class="nf">baz</span><span class="p">():</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">i</span><span class="o">*</span><span class="n">i</span>

<span class="c1"># Proxy type for generator objects</span>
<span class="k">class</span> <span class="nc">GeneratorProxy</span><span class="p">(</span><span class="n">BaseProxy</span><span class="p">):</span>
    <span class="n">_exposed_</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;next&#39;</span><span class="p">,</span> <span class="s1">&#39;__next__&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>
    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="s1">&#39;next&#39;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">__next__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_callmethod</span><span class="p">(</span><span class="s1">&#39;__next__&#39;</span><span class="p">)</span>

<span class="c1"># Function to return the operator module</span>
<span class="k">def</span> <span class="nf">get_operator_module</span><span class="p">():</span>
    <span class="k">return</span> <span class="n">operator</span>

<span class="c1">##</span>

<span class="k">class</span> <span class="nc">MyManager</span><span class="p">(</span><span class="n">BaseManager</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="c1"># register the Foo class; make `f()` and `g()` accessible via proxy</span>
<span class="n">MyManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;Foo1&#39;</span><span class="p">,</span> <span class="n">Foo</span><span class="p">)</span>

<span class="c1"># register the Foo class; make `g()` and `_h()` accessible via proxy</span>
<span class="n">MyManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;Foo2&#39;</span><span class="p">,</span> <span class="n">Foo</span><span class="p">,</span> <span class="n">exposed</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;g&#39;</span><span class="p">,</span> <span class="s1">&#39;_h&#39;</span><span class="p">))</span>

<span class="c1"># register the generator function baz; use `GeneratorProxy` to make proxies</span>
<span class="n">MyManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;baz&#39;</span><span class="p">,</span> <span class="n">baz</span><span class="p">,</span> <span class="n">proxytype</span><span class="o">=</span><span class="n">GeneratorProxy</span><span class="p">)</span>

<span class="c1"># register get_operator_module(); make public functions accessible via proxy</span>
<span class="n">MyManager</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="s1">&#39;operator&#39;</span><span class="p">,</span> <span class="n">get_operator_module</span><span class="p">)</span>

<span class="c1">##</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">manager</span> <span class="o">=</span> <span class="n">MyManager</span><span class="p">()</span>
    <span class="n">manager</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;-&#39;</span> <span class="o">*</span> <span class="mi">20</span>

    <span class="n">f1</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">Foo1</span><span class="p">()</span>
    <span class="n">f1</span><span class="o">.</span><span class="n">f</span><span class="p">()</span>
    <span class="n">f1</span><span class="o">.</span><span class="n">g</span><span class="p">()</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">f1</span><span class="p">,</span> <span class="s1">&#39;_h&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">f1</span><span class="o">.</span><span class="n">_exposed_</span><span class="p">)</span> <span class="o">==</span> <span class="nb">sorted</span><span class="p">([</span><span class="s1">&#39;f&#39;</span><span class="p">,</span> <span class="s1">&#39;g&#39;</span><span class="p">])</span>

    <span class="k">print</span> <span class="s1">&#39;-&#39;</span> <span class="o">*</span> <span class="mi">20</span>

    <span class="n">f2</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">Foo2</span><span class="p">()</span>
    <span class="n">f2</span><span class="o">.</span><span class="n">g</span><span class="p">()</span>
    <span class="n">f2</span><span class="o">.</span><span class="n">_h</span><span class="p">()</span>
    <span class="k">assert</span> <span class="ow">not</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">f2</span><span class="p">,</span> <span class="s1">&#39;f&#39;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">f2</span><span class="o">.</span><span class="n">_exposed_</span><span class="p">)</span> <span class="o">==</span> <span class="nb">sorted</span><span class="p">([</span><span class="s1">&#39;g&#39;</span><span class="p">,</span> <span class="s1">&#39;_h&#39;</span><span class="p">])</span>

    <span class="k">print</span> <span class="s1">&#39;-&#39;</span> <span class="o">*</span> <span class="mi">20</span>

    <span class="n">it</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">baz</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">it</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;&lt;</span><span class="si">%d</span><span class="s1">&gt;&#39;</span> <span class="o">%</span> <span class="n">i</span><span class="p">,</span>
    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;-&#39;</span> <span class="o">*</span> <span class="mi">20</span>

    <span class="n">op</span> <span class="o">=</span> <span class="n">manager</span><span class="o">.</span><span class="n">operator</span><span class="p">()</span>
    <span class="k">print</span> <span class="s1">&#39;op.add(23, 45) =&#39;</span><span class="p">,</span> <span class="n">op</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">23</span><span class="p">,</span> <span class="mi">45</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;op.pow(2, 94) =&#39;</span><span class="p">,</span> <span class="n">op</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">94</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;op.getslice(range(10), 2, 6) =&#39;</span><span class="p">,</span> <span class="n">op</span><span class="o">.</span><span class="n">getslice</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;op.repeat(range(5), 3) =&#39;</span><span class="p">,</span> <span class="n">op</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">),</span> <span class="mi">3</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;op._exposed_ =&#39;</span><span class="p">,</span> <span class="n">op</span><span class="o">.</span><span class="n">_exposed_</span>

<span class="c1">##</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>Using <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># A test of `multiprocessing.Pool` class</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">import</span> <span class="nn">multiprocessing</span>
<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">random</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="c1">#</span>
<span class="c1"># Functions used by test code</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">calculate</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
    <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> says that </span><span class="si">%s%s</span><span class="s1"> = </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span>
        <span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span><span class="p">()</span><span class="o">.</span><span class="n">name</span><span class="p">,</span>
        <span class="n">func</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">result</span>
        <span class="p">)</span>

<span class="k">def</span> <span class="nf">calculatestar</span><span class="p">(</span><span class="n">args</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">calculate</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">mul</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="o">*</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">b</span>

<span class="k">def</span> <span class="nf">plus</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="o">*</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="mf">1.0</span> <span class="o">/</span> <span class="p">(</span><span class="n">x</span><span class="o">-</span><span class="mf">5.0</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">pow3</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">**</span><span class="mi">3</span>

<span class="k">def</span> <span class="nf">noop</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="c1">#</span>
<span class="c1"># Test code</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="k">print</span> <span class="s1">&#39;cpu_count() = </span><span class="si">%d</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">cpu_count</span><span class="p">()</span>

    <span class="c1">#</span>
    <span class="c1"># Create pool</span>
    <span class="c1">#</span>

    <span class="n">PROCESSES</span> <span class="o">=</span> <span class="mi">4</span>
    <span class="k">print</span> <span class="s1">&#39;Creating pool with </span><span class="si">%d</span><span class="s1"> processes</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">PROCESSES</span>
    <span class="n">pool</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Pool</span><span class="p">(</span><span class="n">PROCESSES</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;pool = </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">pool</span>
    <span class="k">print</span>

    <span class="c1">#</span>
    <span class="c1"># Tests</span>
    <span class="c1">#</span>

    <span class="n">TASKS</span> <span class="o">=</span> <span class="p">[(</span><span class="n">mul</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="mi">7</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span> <span class="o">+</span> \
            <span class="p">[(</span><span class="n">plus</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>

    <span class="n">results</span> <span class="o">=</span> <span class="p">[</span><span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">calculate</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span> <span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">TASKS</span><span class="p">]</span>
    <span class="n">imap_it</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">calculatestar</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">)</span>
    <span class="n">imap_unordered_it</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap_unordered</span><span class="p">(</span><span class="n">calculatestar</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">)</span>

    <span class="k">print</span> <span class="s1">&#39;Ordered results using pool.apply_async():&#39;</span>
    <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">results</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">r</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;Ordered results using pool.imap():&#39;</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">imap_it</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">x</span>
    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;Unordered results using pool.imap_unordered():&#39;</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">imap_unordered_it</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">x</span>
    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;Ordered results using pool.map() --- will block till complete:&#39;</span>
    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">calculatestar</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">):</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">x</span>
    <span class="k">print</span>

    <span class="c1">#</span>
    <span class="c1"># Simple benchmarks</span>
    <span class="c1">#</span>

    <span class="n">N</span> <span class="o">=</span> <span class="mi">100000</span>
    <span class="k">print</span> <span class="s1">&#39;def pow3(x): return x**3&#39;</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">A</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">N</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">map(pow3, xrange(</span><span class="si">%d</span><span class="s1">)):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> seconds&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">B</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">N</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">pool.map(pow3, xrange(</span><span class="si">%d</span><span class="s1">)):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> seconds&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">C</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">N</span><span class="p">),</span> <span class="n">chunksize</span><span class="o">=</span><span class="n">N</span><span class="o">//</span><span class="mi">8</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">list(pool.imap(pow3, xrange(</span><span class="si">%d</span><span class="s1">), chunksize=</span><span class="si">%d</span><span class="s1">)):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1">&#39;</span> \
          <span class="s1">&#39; seconds&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">N</span><span class="o">//</span><span class="mi">8</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="k">assert</span> <span class="n">A</span> <span class="o">==</span> <span class="n">B</span> <span class="o">==</span> <span class="n">C</span><span class="p">,</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">A</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">B</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">C</span><span class="p">))</span>
    <span class="k">print</span>

    <span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="bp">None</span><span class="p">]</span> <span class="o">*</span> <span class="mi">1000000</span>
    <span class="k">print</span> <span class="s1">&#39;def noop(x): pass&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;L = [None] * 1000000&#39;</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">A</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="n">noop</span><span class="p">,</span> <span class="n">L</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">map(noop, L):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> seconds&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">B</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">noop</span><span class="p">,</span> <span class="n">L</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">pool.map(noop, L):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> seconds&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="n">t</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
    <span class="n">C</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">noop</span><span class="p">,</span> <span class="n">L</span><span class="p">,</span> <span class="n">chunksize</span><span class="o">=</span><span class="nb">len</span><span class="p">(</span><span class="n">L</span><span class="p">)</span><span class="o">//</span><span class="mi">8</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">list(pool.imap(noop, L, chunksize=</span><span class="si">%d</span><span class="s1">)):</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> seconds&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">L</span><span class="p">)</span><span class="o">//</span><span class="mi">8</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span><span class="p">)</span>

    <span class="k">assert</span> <span class="n">A</span> <span class="o">==</span> <span class="n">B</span> <span class="o">==</span> <span class="n">C</span><span class="p">,</span> <span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">A</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">B</span><span class="p">),</span> <span class="nb">len</span><span class="p">(</span><span class="n">C</span><span class="p">))</span>
    <span class="k">print</span>

    <span class="k">del</span> <span class="n">A</span><span class="p">,</span> <span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">L</span>

    <span class="c1">#</span>
    <span class="c1"># Test error handling</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing error handling:&#39;</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="p">(</span><span class="mi">5</span><span class="p">,))</span>
    <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">Got ZeroDivisionError as expected from pool.apply()&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s1">&#39;expected ZeroDivisionError&#39;</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">print</span> <span class="n">pool</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
    <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">Got ZeroDivisionError as expected from pool.map()&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s1">&#39;expected ZeroDivisionError&#39;</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">print</span> <span class="nb">list</span><span class="p">(</span><span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)))</span>
    <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">Got ZeroDivisionError as expected from list(pool.imap())&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s1">&#39;expected ZeroDivisionError&#39;</span><span class="p">)</span>

    <span class="n">it</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">x</span> <span class="o">=</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
        <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">5</span><span class="p">:</span>
                <span class="k">pass</span>
        <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">5</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="s1">&#39;expected ZeroDivisionError&#39;</span><span class="p">)</span>

    <span class="k">assert</span> <span class="n">i</span> <span class="o">==</span> <span class="mi">9</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">Got ZeroDivisionError as expected from IMapIterator.next()&#39;</span>
    <span class="k">print</span>

    <span class="c1">#</span>
    <span class="c1"># Testing timeouts</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing ApplyResult.get() with timeout:&#39;</span><span class="p">,</span>
    <span class="n">res</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">calculate</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
    <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n\t</span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">res</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="mf">0.02</span><span class="p">))</span>
            <span class="k">break</span>
        <span class="k">except</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">TimeoutError</span><span class="p">:</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
    <span class="k">print</span>
    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;Testing IMapIterator.next() with timeout:&#39;</span><span class="p">,</span>
    <span class="n">it</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">imap</span><span class="p">(</span><span class="n">calculatestar</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">)</span>
    <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n\t</span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">(</span><span class="mf">0.02</span><span class="p">))</span>
        <span class="k">except</span> <span class="ne">StopIteration</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="k">except</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">TimeoutError</span><span class="p">:</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
    <span class="k">print</span>
    <span class="k">print</span>

    <span class="c1">#</span>
    <span class="c1"># Testing callback</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing callback:&#39;</span>

    <span class="n">A</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">B</span> <span class="o">=</span> <span class="p">[</span><span class="mi">56</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">27</span><span class="p">,</span> <span class="mi">64</span><span class="p">,</span> <span class="mi">125</span><span class="p">,</span> <span class="mi">216</span><span class="p">,</span> <span class="mi">343</span><span class="p">,</span> <span class="mi">512</span><span class="p">,</span> <span class="mi">729</span><span class="p">]</span>

    <span class="n">r</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">mul</span><span class="p">,</span> <span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">),</span> <span class="n">callback</span><span class="o">=</span><span class="n">A</span><span class="o">.</span><span class="n">append</span><span class="p">)</span>
    <span class="n">r</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

    <span class="n">r</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">map_async</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="n">callback</span><span class="o">=</span><span class="n">A</span><span class="o">.</span><span class="n">extend</span><span class="p">)</span>
    <span class="n">r</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

    <span class="k">if</span> <span class="n">A</span> <span class="o">==</span> <span class="n">B</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">callbacks succeeded</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">*** callbacks failed</span><span class="se">\n\t\t</span><span class="si">%s</span><span class="s1"> != </span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">A</span><span class="p">,</span> <span class="n">B</span><span class="p">)</span>

    <span class="c1">#</span>
    <span class="c1"># Check there are no outstanding tasks</span>
    <span class="c1">#</span>

    <span class="k">assert</span> <span class="ow">not</span> <span class="n">pool</span><span class="o">.</span><span class="n">_cache</span><span class="p">,</span> <span class="s1">&#39;cache = </span><span class="si">%r</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">pool</span><span class="o">.</span><span class="n">_cache</span>

    <span class="c1">#</span>
    <span class="c1"># Check close() methods</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing close():&#39;</span>

    <span class="k">for</span> <span class="n">worker</span> <span class="ow">in</span> <span class="n">pool</span><span class="o">.</span><span class="n">_pool</span><span class="p">:</span>
        <span class="k">assert</span> <span class="n">worker</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="p">[</span><span class="mf">0.5</span><span class="p">])</span>
    <span class="n">pool</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
    <span class="n">pool</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">assert</span> <span class="n">result</span><span class="o">.</span><span class="n">get</span><span class="p">()</span> <span class="ow">is</span> <span class="bp">None</span>

    <span class="k">for</span> <span class="n">worker</span> <span class="ow">in</span> <span class="n">pool</span><span class="o">.</span><span class="n">_pool</span><span class="p">:</span>
        <span class="k">assert</span> <span class="ow">not</span> <span class="n">worker</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">close() succeeded</span><span class="se">\n</span><span class="s1">&#39;</span>

    <span class="c1">#</span>
    <span class="c1"># Check terminate() method</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing terminate():&#39;</span>

    <span class="n">pool</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Pool</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
    <span class="n">DELTA</span> <span class="o">=</span> <span class="mf">0.1</span>
    <span class="n">ignore</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="p">[</span><span class="mi">2</span><span class="p">])</span>
    <span class="n">results</span> <span class="o">=</span> <span class="p">[</span><span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="p">[</span><span class="n">DELTA</span><span class="p">])</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">)]</span>
    <span class="n">pool</span><span class="o">.</span><span class="n">terminate</span><span class="p">()</span>
    <span class="n">pool</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">worker</span> <span class="ow">in</span> <span class="n">pool</span><span class="o">.</span><span class="n">_pool</span><span class="p">:</span>
        <span class="k">assert</span> <span class="ow">not</span> <span class="n">worker</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">terminate() succeeded</span><span class="se">\n</span><span class="s1">&#39;</span>

    <span class="c1">#</span>
    <span class="c1"># Check garbage collection</span>
    <span class="c1">#</span>

    <span class="k">print</span> <span class="s1">&#39;Testing garbage collection:&#39;</span>

    <span class="n">pool</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Pool</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
    <span class="n">DELTA</span> <span class="o">=</span> <span class="mf">0.1</span>
    <span class="n">processes</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">_pool</span>
    <span class="n">ignore</span> <span class="o">=</span> <span class="n">pool</span><span class="o">.</span><span class="n">apply</span><span class="p">(</span><span class="n">pow3</span><span class="p">,</span> <span class="p">[</span><span class="mi">2</span><span class="p">])</span>
    <span class="n">results</span> <span class="o">=</span> <span class="p">[</span><span class="n">pool</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">,</span> <span class="p">[</span><span class="n">DELTA</span><span class="p">])</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">)]</span>

    <span class="n">results</span> <span class="o">=</span> <span class="n">pool</span> <span class="o">=</span> <span class="bp">None</span>

    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">DELTA</span> <span class="o">*</span> <span class="mi">2</span><span class="p">)</span>

    <span class="k">for</span> <span class="n">worker</span> <span class="ow">in</span> <span class="n">processes</span><span class="p">:</span>
        <span class="k">assert</span> <span class="ow">not</span> <span class="n">worker</span><span class="o">.</span><span class="n">is_alive</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">garbage collection succeeded</span><span class="se">\n</span><span class="s1">&#39;</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">multiprocessing</span><span class="o">.</span><span class="n">freeze_support</span><span class="p">()</span>

    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span> <span class="ow">or</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;processes&#39;</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39; Using processes &#39;</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">79</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
    <span class="k">elif</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;threads&#39;</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39; Using threads &#39;</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">79</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
        <span class="kn">import</span> <span class="nn">multiprocessing.dummy</span> <span class="kn">as</span> <span class="nn">multiprocessing</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;Usage:</span><span class="se">\n\t</span><span class="si">%s</span><span class="s1"> [processes | threads]&#39;</span> <span class="o">%</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">raise</span> <span class="ne">SystemExit</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>Synchronization types like locks, conditions and queues:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># A test file for the `multiprocessing` package</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">import</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">random</span>
<span class="kn">from</span> <span class="nn">Queue</span> <span class="kn">import</span> <span class="n">Empty</span>

<span class="kn">import</span> <span class="nn">multiprocessing</span>               <span class="c1"># may get overwritten</span>


<span class="c1">#### TEST_VALUE</span>

<span class="k">def</span> <span class="nf">value_func</span><span class="p">(</span><span class="n">running</span><span class="p">,</span> <span class="n">mutex</span><span class="p">):</span>
    <span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">()</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span><span class="o">*</span><span class="mi">4</span><span class="p">)</span>

    <span class="n">mutex</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t\t\t</span><span class="s1">&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span><span class="p">())</span> <span class="o">+</span> <span class="s1">&#39; has finished&#39;</span>
    <span class="n">running</span><span class="o">.</span><span class="n">value</span> <span class="o">-=</span> <span class="mi">1</span>
    <span class="n">mutex</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">test_value</span><span class="p">():</span>
    <span class="n">TASKS</span> <span class="o">=</span> <span class="mi">10</span>
    <span class="n">running</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">TASKS</span><span class="p">)</span>
    <span class="n">mutex</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">TASKS</span><span class="p">):</span>
        <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">value_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">running</span><span class="p">,</span> <span class="n">mutex</span><span class="p">))</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">while</span> <span class="n">running</span><span class="o">.</span><span class="n">value</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.08</span><span class="p">)</span>
        <span class="n">mutex</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="k">print</span> <span class="n">running</span><span class="o">.</span><span class="n">value</span><span class="p">,</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
        <span class="n">mutex</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="k">print</span>
    <span class="k">print</span> <span class="s1">&#39;No more running processes&#39;</span>


<span class="c1">#### TEST_QUEUE</span>

<span class="k">def</span> <span class="nf">queue_func</span><span class="p">(</span><span class="n">queue</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">30</span><span class="p">):</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span> <span class="o">*</span> <span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">())</span>
        <span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</span><span class="p">)</span>
    <span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;STOP&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test_queue</span><span class="p">():</span>
    <span class="n">q</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Queue</span><span class="p">()</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">queue_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">q</span><span class="p">,))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="n">o</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="k">while</span> <span class="n">o</span> <span class="o">!=</span> <span class="s1">&#39;STOP&#39;</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">o</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mf">0.3</span><span class="p">)</span>
            <span class="k">print</span> <span class="n">o</span><span class="p">,</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>
        <span class="k">except</span> <span class="n">Empty</span><span class="p">:</span>
            <span class="k">print</span> <span class="s1">&#39;TIMEOUT&#39;</span>

    <span class="k">print</span>


<span class="c1">#### TEST_CONDITION</span>

<span class="k">def</span> <span class="nf">condition_func</span><span class="p">(</span><span class="n">cond</span><span class="p">):</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">cond</span><span class="p">)</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">child is notifying&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">cond</span><span class="p">)</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">test_condition</span><span class="p">():</span>
    <span class="n">cond</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Condition</span><span class="p">()</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">condition_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">cond</span><span class="p">,))</span>
    <span class="k">print</span> <span class="n">cond</span>

    <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="k">print</span> <span class="n">cond</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="k">print</span> <span class="n">cond</span>

    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;main is waiting&#39;</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="k">print</span> <span class="s1">&#39;main has woken up&#39;</span>

    <span class="k">print</span> <span class="n">cond</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
    <span class="k">print</span> <span class="n">cond</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>
    <span class="k">print</span> <span class="n">cond</span>


<span class="c1">#### TEST_SEMAPHORE</span>

<span class="k">def</span> <span class="nf">semaphore_func</span><span class="p">(</span><span class="n">sema</span><span class="p">,</span> <span class="n">mutex</span><span class="p">,</span> <span class="n">running</span><span class="p">):</span>
    <span class="n">sema</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>

    <span class="n">mutex</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="n">running</span><span class="o">.</span><span class="n">value</span> <span class="o">+=</span> <span class="mi">1</span>
    <span class="k">print</span> <span class="n">running</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="s1">&#39;tasks are running&#39;</span>
    <span class="n">mutex</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">()</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span>

    <span class="n">mutex</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="n">running</span><span class="o">.</span><span class="n">value</span> <span class="o">-=</span> <span class="mi">1</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> has finished&#39;</span> <span class="o">%</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span><span class="p">()</span>
    <span class="n">mutex</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="n">sema</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">test_semaphore</span><span class="p">():</span>
    <span class="n">sema</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Semaphore</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
    <span class="n">mutex</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">RLock</span><span class="p">()</span>
    <span class="n">running</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Value</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>

    <span class="n">processes</span> <span class="o">=</span> <span class="p">[</span>
        <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">semaphore_func</span><span class="p">,</span>
                                <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">sema</span><span class="p">,</span> <span class="n">mutex</span><span class="p">,</span> <span class="n">running</span><span class="p">))</span>
        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
        <span class="p">]</span>

    <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">processes</span><span class="p">:</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">processes</span><span class="p">:</span>
        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>


<span class="c1">#### TEST_JOIN_TIMEOUT</span>

<span class="k">def</span> <span class="nf">join_timeout_func</span><span class="p">():</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">child sleeping&#39;</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">5.5</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">child terminating&#39;</span>

<span class="k">def</span> <span class="nf">test_join_timeout</span><span class="p">():</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">join_timeout_func</span><span class="p">)</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;waiting for process to finish&#39;</span>

    <span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">timeout</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">p</span><span class="o">.</span><span class="n">is_alive</span><span class="p">():</span>
            <span class="k">break</span>
        <span class="k">print</span> <span class="s1">&#39;.&#39;</span><span class="p">,</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">flush</span><span class="p">()</span>


<span class="c1">#### TEST_EVENT</span>

<span class="k">def</span> <span class="nf">event_func</span><span class="p">(</span><span class="n">event</span><span class="p">):</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="si">%r</span><span class="s1"> is waiting&#39;</span> <span class="o">%</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span><span class="p">()</span>
    <span class="n">event</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="si">%r</span><span class="s1"> has woken up&#39;</span> <span class="o">%</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">test_event</span><span class="p">():</span>
    <span class="n">event</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Event</span><span class="p">()</span>

    <span class="n">processes</span> <span class="o">=</span> <span class="p">[</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">event_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">event</span><span class="p">,))</span>
                 <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">)]</span>

    <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">processes</span><span class="p">:</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;main is sleeping&#39;</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="k">print</span> <span class="s1">&#39;main is setting event&#39;</span>
    <span class="n">event</span><span class="o">.</span><span class="n">set</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">p</span> <span class="ow">in</span> <span class="n">processes</span><span class="p">:</span>
        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>


<span class="c1">#### TEST_SHAREDVALUES</span>

<span class="k">def</span> <span class="nf">sharedvalues_func</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="n">arrays</span><span class="p">,</span> <span class="n">shared_values</span><span class="p">,</span> <span class="n">shared_arrays</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)):</span>
        <span class="n">v</span> <span class="o">=</span> <span class="n">values</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
        <span class="n">sv</span> <span class="o">=</span> <span class="n">shared_values</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">.</span><span class="n">value</span>
        <span class="k">assert</span> <span class="n">v</span> <span class="o">==</span> <span class="n">sv</span>

    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)):</span>
        <span class="n">a</span> <span class="o">=</span> <span class="n">arrays</span><span class="p">[</span><span class="n">i</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
        <span class="n">sa</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">shared_arrays</span><span class="p">[</span><span class="n">i</span><span class="p">][:])</span>
        <span class="k">assert</span> <span class="n">a</span> <span class="o">==</span> <span class="n">sa</span>

    <span class="k">print</span> <span class="s1">&#39;Tests passed&#39;</span>

<span class="k">def</span> <span class="nf">test_sharedvalues</span><span class="p">():</span>
    <span class="n">values</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">),</span>
        <span class="p">(</span><span class="s1">&#39;h&#39;</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">),</span>
        <span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="mf">1.25</span><span class="p">)</span>
        <span class="p">]</span>
    <span class="n">arrays</span> <span class="o">=</span> <span class="p">[</span>
        <span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">)),</span>
        <span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mf">0.25</span> <span class="o">*</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">)]),</span>
        <span class="p">(</span><span class="s1">&#39;H&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1000</span><span class="p">))</span>
        <span class="p">]</span>

    <span class="n">shared_values</span> <span class="o">=</span> <span class="p">[</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Value</span><span class="p">(</span><span class="nb">id</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="nb">id</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">values</span><span class="p">]</span>
    <span class="n">shared_arrays</span> <span class="o">=</span> <span class="p">[</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Array</span><span class="p">(</span><span class="nb">id</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span> <span class="k">for</span> <span class="nb">id</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">arrays</span><span class="p">]</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span>
        <span class="n">target</span><span class="o">=</span><span class="n">sharedvalues_func</span><span class="p">,</span>
        <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="n">arrays</span><span class="p">,</span> <span class="n">shared_values</span><span class="p">,</span> <span class="n">shared_arrays</span><span class="p">)</span>
        <span class="p">)</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">assert</span> <span class="n">p</span><span class="o">.</span><span class="n">exitcode</span> <span class="o">==</span> <span class="mi">0</span>


<span class="c1">####</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">(</span><span class="n">namespace</span><span class="o">=</span><span class="n">multiprocessing</span><span class="p">):</span>
    <span class="k">global</span> <span class="n">multiprocessing</span>

    <span class="n">multiprocessing</span> <span class="o">=</span> <span class="n">namespace</span>

    <span class="k">for</span> <span class="n">func</span> <span class="ow">in</span> <span class="p">[</span> <span class="n">test_value</span><span class="p">,</span> <span class="n">test_queue</span><span class="p">,</span> <span class="n">test_condition</span><span class="p">,</span>
                  <span class="n">test_semaphore</span><span class="p">,</span> <span class="n">test_join_timeout</span><span class="p">,</span> <span class="n">test_event</span><span class="p">,</span>
                  <span class="n">test_sharedvalues</span> <span class="p">]:</span>

        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## </span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">func</span><span class="o">.</span><span class="vm">__name__</span>
        <span class="n">func</span><span class="p">()</span>

    <span class="n">ignore</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">active_children</span><span class="p">()</span>      <span class="c1"># cleanup any old processes</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">multiprocessing</span><span class="p">,</span> <span class="s1">&#39;_debug_info&#39;</span><span class="p">):</span>
        <span class="n">info</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">_debug_info</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">info</span><span class="p">:</span>
            <span class="k">print</span> <span class="n">info</span>
            <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s1">&#39;there should be no positive refcounts left&#39;</span><span class="p">)</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">multiprocessing</span><span class="o">.</span><span class="n">freeze_support</span><span class="p">()</span>

    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>

    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span> <span class="ow">or</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;processes&#39;</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39; Using processes &#39;</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">79</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
        <span class="n">namespace</span> <span class="o">=</span> <span class="n">multiprocessing</span>
    <span class="k">elif</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;manager&#39;</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39; Using processes and a manager &#39;</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">79</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
        <span class="n">namespace</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>
        <span class="n">namespace</span><span class="o">.</span><span class="n">Process</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span>
        <span class="n">namespace</span><span class="o">.</span><span class="n">current_process</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">current_process</span>
        <span class="n">namespace</span><span class="o">.</span><span class="n">active_children</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">active_children</span>
    <span class="k">elif</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;threads&#39;</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39; Using threads &#39;</span><span class="o">.</span><span class="n">center</span><span class="p">(</span><span class="mi">79</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">)</span>
        <span class="kn">import</span> <span class="nn">multiprocessing.dummy</span> <span class="kn">as</span> <span class="nn">namespace</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">print</span> <span class="s1">&#39;Usage:</span><span class="se">\n\t</span><span class="si">%s</span><span class="s1"> [processes | manager | threads]&#39;</span> <span class="o">%</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">raise</span> <span class="ne">SystemExit</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

    <span class="n">test</span><span class="p">(</span><span class="n">namespace</span><span class="p">)</span>
</pre></div>
</div>
<p>An example showing how to use queues to feed tasks to a collection of worker
processes and collect the results:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># Simple example which uses a pool of workers to carry out some tasks.</span>
<span class="c1">#</span>
<span class="c1"># Notice that the results will probably not come out of the output</span>
<span class="c1"># queue in the same in the same order as the corresponding tasks were</span>
<span class="c1"># put on the input queue.  If it is important to get the results back</span>
<span class="c1"># in the original order then consider using `Pool.map()` or</span>
<span class="c1"># `Pool.imap()` (which will save on the amount of code needed anyway).</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">import</span> <span class="nn">time</span>
<span class="kn">import</span> <span class="nn">random</span>

<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span><span class="p">,</span> <span class="n">current_process</span><span class="p">,</span> <span class="n">freeze_support</span>

<span class="c1">#</span>
<span class="c1"># Function run by worker processes</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">worker</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">func</span><span class="p">,</span> <span class="n">args</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="nb">input</span><span class="o">.</span><span class="n">get</span><span class="p">,</span> <span class="s1">&#39;STOP&#39;</span><span class="p">):</span>
        <span class="n">result</span> <span class="o">=</span> <span class="n">calculate</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span>
        <span class="n">output</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>

<span class="c1">#</span>
<span class="c1"># Function used to calculate result</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">calculate</span><span class="p">(</span><span class="n">func</span><span class="p">,</span> <span class="n">args</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">func</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
    <span class="k">return</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1"> says that </span><span class="si">%s%s</span><span class="s1"> = </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> \
        <span class="p">(</span><span class="n">current_process</span><span class="p">()</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">func</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">args</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>

<span class="c1">#</span>
<span class="c1"># Functions referenced by tasks</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">mul</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="o">*</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">a</span> <span class="o">*</span> <span class="n">b</span>

<span class="k">def</span> <span class="nf">plus</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">0.5</span><span class="o">*</span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">())</span>
    <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span>

<span class="c1">#</span>
<span class="c1">#</span>
<span class="c1">#</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">NUMBER_OF_PROCESSES</span> <span class="o">=</span> <span class="mi">4</span>
    <span class="n">TASKS1</span> <span class="o">=</span> <span class="p">[(</span><span class="n">mul</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="mi">7</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)]</span>
    <span class="n">TASKS2</span> <span class="o">=</span> <span class="p">[(</span><span class="n">plus</span><span class="p">,</span> <span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="mi">8</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>

    <span class="c1"># Create queues</span>
    <span class="n">task_queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
    <span class="n">done_queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>

    <span class="c1"># Submit tasks</span>
    <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">TASKS1</span><span class="p">:</span>
        <span class="n">task_queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>

    <span class="c1"># Start worker processes</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">NUMBER_OF_PROCESSES</span><span class="p">):</span>
        <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">worker</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">task_queue</span><span class="p">,</span> <span class="n">done_queue</span><span class="p">))</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="c1"># Get and print results</span>
    <span class="k">print</span> <span class="s1">&#39;Unordered results:&#39;</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">TASKS1</span><span class="p">)):</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">done_queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>

    <span class="c1"># Add more tasks using `put()`</span>
    <span class="k">for</span> <span class="n">task</span> <span class="ow">in</span> <span class="n">TASKS2</span><span class="p">:</span>
        <span class="n">task_queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">task</span><span class="p">)</span>

    <span class="c1"># Get and print some more results</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">TASKS2</span><span class="p">)):</span>
        <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\t</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">done_queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>

    <span class="c1"># Tell child processes to stop</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">NUMBER_OF_PROCESSES</span><span class="p">):</span>
        <span class="n">task_queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;STOP&#39;</span><span class="p">)</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>An example of how a pool of worker processes can each run a
<code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPServer.HttpServer</span></code> instance while sharing a single listening
socket.</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># Example where a pool of http servers share a single listening socket</span>
<span class="c1">#</span>
<span class="c1"># On Windows this module depends on the ability to pickle a socket</span>
<span class="c1"># object so that the worker processes can inherit a copy of the server</span>
<span class="c1"># object.  (We import `multiprocessing.reduction` to enable this pickling.)</span>
<span class="c1">#</span>
<span class="c1"># Not sure if we should synchronize access to `socket.accept()` method by</span>
<span class="c1"># using a process-shared lock -- does not seem to be necessary.</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="kn">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">current_process</span><span class="p">,</span> <span class="n">freeze_support</span>
<span class="kn">from</span> <span class="nn">BaseHTTPServer</span> <span class="kn">import</span> <span class="n">HTTPServer</span>
<span class="kn">from</span> <span class="nn">SimpleHTTPServer</span> <span class="kn">import</span> <span class="n">SimpleHTTPRequestHandler</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span> <span class="o">==</span> <span class="s1">&#39;win32&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">multiprocessing.reduction</span>    <span class="c1"># make sockets pickable/inheritable</span>


<span class="k">def</span> <span class="nf">note</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;[</span><span class="si">%s</span><span class="s1">]</span><span class="se">\t</span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">current_process</span><span class="p">()</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">format</span><span class="o">%</span><span class="n">args</span><span class="p">))</span>


<span class="k">class</span> <span class="nc">RequestHandler</span><span class="p">(</span><span class="n">SimpleHTTPRequestHandler</span><span class="p">):</span>
    <span class="c1"># we override log_message() to show which process is handling the request</span>
    <span class="k">def</span> <span class="nf">log_message</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
        <span class="n">note</span><span class="p">(</span><span class="n">format</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">serve_forever</span><span class="p">(</span><span class="n">server</span><span class="p">):</span>
    <span class="n">note</span><span class="p">(</span><span class="s1">&#39;starting server&#39;</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">KeyboardInterrupt</span><span class="p">:</span>
        <span class="k">pass</span>


<span class="k">def</span> <span class="nf">runpool</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">number_of_processes</span><span class="p">):</span>
    <span class="c1"># create a single server object -- children will each inherit a copy</span>
    <span class="n">server</span> <span class="o">=</span> <span class="n">HTTPServer</span><span class="p">(</span><span class="n">address</span><span class="p">,</span> <span class="n">RequestHandler</span><span class="p">)</span>

    <span class="c1"># create child processes to act as workers</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">number_of_processes</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">serve_forever</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">server</span><span class="p">,))</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

    <span class="c1"># main process also acts as a worker</span>
    <span class="n">serve_forever</span><span class="p">(</span><span class="n">server</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">DIR</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="vm">__file__</span><span class="p">),</span> <span class="s1">&#39;..&#39;</span><span class="p">)</span>
    <span class="n">ADDRESS</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">)</span>
    <span class="n">NUMBER_OF_PROCESSES</span> <span class="o">=</span> <span class="mi">4</span>

    <span class="k">print</span> <span class="s1">&#39;Serving at http://</span><span class="si">%s</span><span class="s1">:</span><span class="si">%d</span><span class="s1"> using </span><span class="si">%d</span><span class="s1"> worker processes&#39;</span> <span class="o">%</span> \
          <span class="p">(</span><span class="n">ADDRESS</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">ADDRESS</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">NUMBER_OF_PROCESSES</span><span class="p">)</span>
    <span class="k">print</span> <span class="s1">&#39;To exit press Ctrl-&#39;</span> <span class="o">+</span> <span class="p">[</span><span class="s1">&#39;C&#39;</span><span class="p">,</span> <span class="s1">&#39;Break&#39;</span><span class="p">][</span><span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="o">==</span><span class="s1">&#39;win32&#39;</span><span class="p">]</span>

    <span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="n">DIR</span><span class="p">)</span>
    <span class="n">runpool</span><span class="p">(</span><span class="n">ADDRESS</span><span class="p">,</span> <span class="n">NUMBER_OF_PROCESSES</span><span class="p">)</span>


<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
<p>Some simple benchmarks comparing <a class="reference internal" href="#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> with <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="c1">#</span>
<span class="c1"># Simple benchmarks for the multiprocessing package</span>
<span class="c1">#</span>
<span class="c1"># Copyright (c) 2006-2008, R Oudkerk</span>
<span class="c1"># All rights reserved.</span>
<span class="c1">#</span>

<span class="kn">import</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">multiprocessing</span><span class="o">,</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">Queue</span><span class="o">,</span> <span class="nn">gc</span>

<span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span> <span class="o">==</span> <span class="s1">&#39;win32&#39;</span><span class="p">:</span>
    <span class="n">_timer</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">clock</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">_timer</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span>

<span class="n">delta</span> <span class="o">=</span> <span class="mi">1</span>


<span class="c1">#### TEST_QUEUESPEED</span>

<span class="k">def</span> <span class="nf">queuespeed_func</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">iterations</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;0&#39;</span> <span class="o">*</span> <span class="mi">256</span>
    <span class="n">c</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="n">c</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
    <span class="n">c</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
        <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>

    <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s1">&#39;STOP&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test_queuespeed</span><span class="p">(</span><span class="n">Process</span><span class="p">,</span> <span class="n">q</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span>
    <span class="n">elapsed</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">while</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">iterations</span> <span class="o">*=</span> <span class="mi">2</span>

        <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">queuespeed_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">c</span><span class="p">,</span> <span class="n">iterations</span><span class="p">))</span>
        <span class="n">c</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
        <span class="n">c</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
        <span class="n">c</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

        <span class="n">result</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="n">t</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span>

        <span class="k">while</span> <span class="n">result</span> <span class="o">!=</span> <span class="s1">&#39;STOP&#39;</span><span class="p">:</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>

        <span class="n">elapsed</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span>

        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">print</span> <span class="n">iterations</span><span class="p">,</span> <span class="s1">&#39;objects passed through the queue in&#39;</span><span class="p">,</span> <span class="n">elapsed</span><span class="p">,</span> <span class="s1">&#39;seconds&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;average number/sec:&#39;</span><span class="p">,</span> <span class="n">iterations</span><span class="o">/</span><span class="n">elapsed</span>


<span class="c1">#### TEST_PIPESPEED</span>

<span class="k">def</span> <span class="nf">pipe_func</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">cond</span><span class="p">,</span> <span class="n">iterations</span><span class="p">):</span>
    <span class="n">a</span> <span class="o">=</span> <span class="s1">&#39;0&#39;</span> <span class="o">*</span> <span class="mi">256</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
    <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
        <span class="n">c</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>

    <span class="n">c</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="s1">&#39;STOP&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">test_pipespeed</span><span class="p">():</span>
    <span class="n">c</span><span class="p">,</span> <span class="n">d</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Pipe</span><span class="p">()</span>
    <span class="n">cond</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Condition</span><span class="p">()</span>
    <span class="n">elapsed</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">while</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">iterations</span> <span class="o">*=</span> <span class="mi">2</span>

        <span class="n">p</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">pipe_func</span><span class="p">,</span>
                                    <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">cond</span><span class="p">,</span> <span class="n">iterations</span><span class="p">))</span>
        <span class="n">cond</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
        <span class="n">cond</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
        <span class="n">cond</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

        <span class="n">result</span> <span class="o">=</span> <span class="bp">None</span>
        <span class="n">t</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span>

        <span class="k">while</span> <span class="n">result</span> <span class="o">!=</span> <span class="s1">&#39;STOP&#39;</span><span class="p">:</span>
            <span class="n">result</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">recv</span><span class="p">()</span>

        <span class="n">elapsed</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span> <span class="o">-</span> <span class="n">t</span>
        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">print</span> <span class="n">iterations</span><span class="p">,</span> <span class="s1">&#39;objects passed through connection in&#39;</span><span class="p">,</span><span class="n">elapsed</span><span class="p">,</span><span class="s1">&#39;seconds&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;average number/sec:&#39;</span><span class="p">,</span> <span class="n">iterations</span><span class="o">/</span><span class="n">elapsed</span>


<span class="c1">#### TEST_SEQSPEED</span>

<span class="k">def</span> <span class="nf">test_seqspeed</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
    <span class="n">elapsed</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">while</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">iterations</span> <span class="o">*=</span> <span class="mi">2</span>

        <span class="n">t</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
            <span class="n">a</span> <span class="o">=</span> <span class="n">seq</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span>

        <span class="n">elapsed</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span><span class="o">-</span><span class="n">t</span>

    <span class="k">print</span> <span class="n">iterations</span><span class="p">,</span> <span class="s1">&#39;iterations in&#39;</span><span class="p">,</span> <span class="n">elapsed</span><span class="p">,</span> <span class="s1">&#39;seconds&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;average number/sec:&#39;</span><span class="p">,</span> <span class="n">iterations</span><span class="o">/</span><span class="n">elapsed</span>


<span class="c1">#### TEST_LOCK</span>

<span class="k">def</span> <span class="nf">test_lockspeed</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
    <span class="n">elapsed</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">while</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">iterations</span> <span class="o">*=</span> <span class="mi">2</span>

        <span class="n">t</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
            <span class="n">l</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
            <span class="n">l</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

        <span class="n">elapsed</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span><span class="o">-</span><span class="n">t</span>

    <span class="k">print</span> <span class="n">iterations</span><span class="p">,</span> <span class="s1">&#39;iterations in&#39;</span><span class="p">,</span> <span class="n">elapsed</span><span class="p">,</span> <span class="s1">&#39;seconds&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;average number/sec:&#39;</span><span class="p">,</span> <span class="n">iterations</span><span class="o">/</span><span class="n">elapsed</span>


<span class="c1">#### TEST_CONDITION</span>

<span class="k">def</span> <span class="nf">conditionspeed_func</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">N</span><span class="p">):</span>
    <span class="n">c</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
    <span class="n">c</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>

    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
        <span class="n">c</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
        <span class="n">c</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>

    <span class="n">c</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">test_conditionspeed</span><span class="p">(</span><span class="n">Process</span><span class="p">,</span> <span class="n">c</span><span class="p">):</span>
    <span class="n">elapsed</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">iterations</span> <span class="o">=</span> <span class="mi">1</span>

    <span class="k">while</span> <span class="n">elapsed</span> <span class="o">&lt;</span> <span class="n">delta</span><span class="p">:</span>
        <span class="n">iterations</span> <span class="o">*=</span> <span class="mi">2</span>

        <span class="n">c</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
        <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">conditionspeed_func</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="n">iterations</span><span class="p">))</span>
        <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

        <span class="n">c</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

        <span class="n">t</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span>

        <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">xrange</span><span class="p">(</span><span class="n">iterations</span><span class="p">):</span>
            <span class="n">c</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
            <span class="n">c</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>

        <span class="n">elapsed</span> <span class="o">=</span> <span class="n">_timer</span><span class="p">()</span><span class="o">-</span><span class="n">t</span>

        <span class="n">c</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
        <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="k">print</span> <span class="n">iterations</span> <span class="o">*</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;waits in&#39;</span><span class="p">,</span> <span class="n">elapsed</span><span class="p">,</span> <span class="s1">&#39;seconds&#39;</span>
    <span class="k">print</span> <span class="s1">&#39;average number/sec:&#39;</span><span class="p">,</span> <span class="n">iterations</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">/</span> <span class="n">elapsed</span>

<span class="c1">####</span>

<span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">manager</span> <span class="o">=</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Manager</span><span class="p">()</span>

    <span class="n">gc</span><span class="o">.</span><span class="n">disable</span><span class="p">()</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing Queue.Queue</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_queuespeed</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">,</span> <span class="n">Queue</span><span class="o">.</span><span class="n">Queue</span><span class="p">(),</span>
                    <span class="n">threading</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing multiprocessing.Queue</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_queuespeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">,</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Queue</span><span class="p">(),</span>
                    <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing Queue managed by server process</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_queuespeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">,</span> <span class="n">manager</span><span class="o">.</span><span class="n">Queue</span><span class="p">(),</span>
                    <span class="n">manager</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing multiprocessing.Pipe</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_pipespeed</span><span class="p">()</span>

    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing list</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_seqspeed</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing list managed by server process</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_seqspeed</span><span class="p">(</span><span class="n">manager</span><span class="o">.</span><span class="n">list</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing Array(&quot;i&quot;, ..., lock=False)</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_seqspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="n">lock</span><span class="o">=</span><span class="bp">False</span><span class="p">))</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing Array(&quot;i&quot;, ..., lock=True)</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_seqspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Array</span><span class="p">(</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">),</span> <span class="n">lock</span><span class="o">=</span><span class="bp">True</span><span class="p">))</span>

    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing threading.Lock</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing threading.RLock</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">RLock</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing multiprocessing.Lock</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Lock</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing multiprocessing.RLock</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">RLock</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing lock managed by server process</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">manager</span><span class="o">.</span><span class="n">Lock</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing rlock managed by server process</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_lockspeed</span><span class="p">(</span><span class="n">manager</span><span class="o">.</span><span class="n">RLock</span><span class="p">())</span>

    <span class="k">print</span>

    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing threading.Condition</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_conditionspeed</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">,</span> <span class="n">threading</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing multiprocessing.Condition</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_conditionspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">,</span> <span class="n">multiprocessing</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>
    <span class="k">print</span> <span class="s1">&#39;</span><span class="se">\n\t</span><span class="s1">######## testing condition managed by a server process</span><span class="se">\n</span><span class="s1">&#39;</span>
    <span class="n">test_conditionspeed</span><span class="p">(</span><span class="n">multiprocessing</span><span class="o">.</span><span class="n">Process</span><span class="p">,</span> <span class="n">manager</span><span class="o">.</span><span class="n">Condition</span><span class="p">())</span>

    <span class="n">gc</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">multiprocessing</span><span class="o">.</span><span class="n">freeze_support</span><span class="p">()</span>
    <span class="n">test</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a><ul>
<li><a class="reference internal" href="#introduction">16.6.1. Introduction</a><ul>
<li><a class="reference internal" href="#the-process-class">16.6.1.1. The <code class="docutils literal notranslate"><span class="pre">Process</span></code> class</a></li>
<li><a class="reference internal" href="#exchanging-objects-between-processes">16.6.1.2. Exchanging objects between processes</a></li>
<li><a class="reference internal" href="#synchronization-between-processes">16.6.1.3. Synchronization between processes</a></li>
<li><a class="reference internal" href="#sharing-state-between-processes">16.6.1.4. Sharing state between processes</a></li>
<li><a class="reference internal" href="#using-a-pool-of-workers">16.6.1.5. Using a pool of workers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reference">16.6.2. Reference</a><ul>
<li><a class="reference internal" href="#process-and-exceptions">16.6.2.1. <code class="docutils literal notranslate"><span class="pre">Process</span></code> and exceptions</a></li>
<li><a class="reference internal" href="#pipes-and-queues">16.6.2.2. Pipes and Queues</a></li>
<li><a class="reference internal" href="#miscellaneous">16.6.2.3. Miscellaneous</a></li>
<li><a class="reference internal" href="#connection-objects">16.6.2.4. Connection Objects</a></li>
<li><a class="reference internal" href="#synchronization-primitives">16.6.2.5. Synchronization primitives</a></li>
<li><a class="reference internal" href="#shared-ctypes-objects">16.6.2.6. Shared <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> Objects</a><ul>
<li><a class="reference internal" href="#module-multiprocessing.sharedctypes">16.6.2.6.1. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code> module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#managers">16.6.2.7. Managers</a><ul>
<li><a class="reference internal" href="#customized-managers">16.6.2.7.1. Customized managers</a></li>
<li><a class="reference internal" href="#using-a-remote-manager">16.6.2.7.2. Using a remote manager</a></li>
</ul>
</li>
<li><a class="reference internal" href="#proxy-objects">16.6.2.8. Proxy Objects</a><ul>
<li><a class="reference internal" href="#cleanup">16.6.2.8.1. Cleanup</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-multiprocessing.pool">16.6.2.9. Process Pools</a></li>
<li><a class="reference internal" href="#module-multiprocessing.connection">16.6.2.10. Listeners and Clients</a><ul>
<li><a class="reference internal" href="#address-formats">16.6.2.10.1. Address Formats</a></li>
</ul>
</li>
<li><a class="reference internal" href="#authentication-keys">16.6.2.11. Authentication keys</a></li>
<li><a class="reference internal" href="#logging">16.6.2.12. Logging</a></li>
<li><a class="reference internal" href="#module-multiprocessing.dummy">16.6.2.13. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.dummy</span></code> module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#programming-guidelines">16.6.3. Programming guidelines</a><ul>
<li><a class="reference internal" href="#all-platforms">16.6.3.1. All platforms</a></li>
<li><a class="reference internal" href="#windows">16.6.3.2. Windows</a></li>
</ul>
</li>
<li><a class="reference internal" href="#examples">16.6.4. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="dummy_thread.html"
                        title="previous chapter">16.5. <code class="docutils literal notranslate"><span class="pre">dummy_thread</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">thread</span></code> module</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mmap.html"
                        title="next chapter">16.7. <code class="docutils literal notranslate"><span class="pre">mmap</span></code> — Memory-mapped file support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/multiprocessing.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mmap.html" title="16.7. mmap — Memory-mapped file support"
             >next</a> |</li>
        <li class="right" >
          <a href="dummy_thread.html" title="16.5. dummy_thread — Drop-in replacement for the thread module"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ȫ�<s/s/html/library/mutex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.9. mutex — Mutual exclusion support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.10. Queue — A synchronized queue class" href="queue.html" />
    <link rel="prev" title="8.8. sched — Event scheduler" href="sched.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/mutex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sched.html" title="8.8. sched — Event scheduler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-mutex">
<span id="mutex-mutual-exclusion-support"></span><h1>8.9. <a class="reference internal" href="#module-mutex" title="mutex: Lock and queue for mutual exclusion. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mutex</span></code></a> — Mutual exclusion support<a class="headerlink" href="#module-mutex" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-mutex" title="mutex: Lock and queue for mutual exclusion. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mutex</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-mutex" title="mutex: Lock and queue for mutual exclusion. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mutex</span></code></a> module defines a class that allows mutual-exclusion via
acquiring and releasing locks. It does not require (or imply)
<a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> or multi-tasking, though it could be useful for those
purposes.</p>
<p>The <a class="reference internal" href="#module-mutex" title="mutex: Lock and queue for mutual exclusion. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mutex</span></code></a> module defines the following class:</p>
<dl class="class">
<dt id="mutex.mutex">
<em class="property">class </em><code class="descclassname">mutex.</code><code class="descname">mutex</code><a class="headerlink" href="#mutex.mutex" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new (unlocked) mutex.</p>
<p>A mutex has two pieces of state — a “locked” bit and a queue. When the mutex
is not locked, the queue is empty. Otherwise, the queue contains zero or more
<code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">argument)</span></code> pairs representing functions (or methods) waiting to
acquire the lock. When the mutex is unlocked while the queue is not empty, the
first queue entry is removed and its  <code class="docutils literal notranslate"><span class="pre">function(argument)</span></code> pair called,
implying it now has the lock.</p>
<p>Of course, no multi-threading is implied – hence the funny interface for
<a class="reference internal" href="#mutex.mutex.lock" title="mutex.mutex.lock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code></a>, where a function is called once the lock is acquired.</p>
</dd></dl>

<div class="section" id="mutex-objects">
<span id="id1"></span><h2>8.9.1. Mutex Objects<a class="headerlink" href="#mutex-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#mutex.mutex" title="mutex.mutex"><code class="xref py py-class docutils literal notranslate"><span class="pre">mutex</span></code></a> objects have following methods:</p>
<dl class="method">
<dt id="mutex.mutex.test">
<code class="descclassname">mutex.</code><code class="descname">test</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mutex.mutex.test" title="Permalink to this definition">¶</a></dt>
<dd><p>Check whether the mutex is locked.</p>
</dd></dl>

<dl class="method">
<dt id="mutex.mutex.testandset">
<code class="descclassname">mutex.</code><code class="descname">testandset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mutex.mutex.testandset" title="Permalink to this definition">¶</a></dt>
<dd><p>“Atomic” test-and-set, grab the lock if it is not set, and return <code class="docutils literal notranslate"><span class="pre">True</span></code>,
otherwise, return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="mutex.mutex.lock">
<code class="descclassname">mutex.</code><code class="descname">lock</code><span class="sig-paren">(</span><em>function</em>, <em>argument</em><span class="sig-paren">)</span><a class="headerlink" href="#mutex.mutex.lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute <code class="docutils literal notranslate"><span class="pre">function(argument)</span></code>, unless the mutex is locked. In the case it is
locked, place the function and argument on the queue. See <a class="reference internal" href="#mutex.mutex.unlock" title="mutex.mutex.unlock"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unlock()</span></code></a> for
explanation of when <code class="docutils literal notranslate"><span class="pre">function(argument)</span></code> is executed in that case.</p>
</dd></dl>

<dl class="method">
<dt id="mutex.mutex.unlock">
<code class="descclassname">mutex.</code><code class="descname">unlock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#mutex.mutex.unlock" title="Permalink to this definition">¶</a></dt>
<dd><p>Unlock the mutex if queue is empty, otherwise execute the first element in the
queue.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a><ul>
<li><a class="reference internal" href="#mutex-objects">8.9.1. Mutex Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sched.html"
                        title="previous chapter">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="queue.html"
                        title="next chapter">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/mutex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             >next</a> |</li>
        <li class="right" >
          <a href="sched.html" title="8.8. sched — Event scheduler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\\�;�G�Ghtml/library/netdata.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18. Internet Data Handling &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.1. email — An email and MIME handling package" href="email.html" />
    <link rel="prev" title="17.7. asynchat — Asynchronous socket command/response handler" href="asynchat.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/netdata.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.html" title="18.1. email — An email and MIME handling package"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="asynchat.html" title="17.7. asynchat — Asynchronous socket command/response handler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="internet-data-handling">
<span id="netdata"></span><h1>18. Internet Data Handling<a class="headerlink" href="#internet-data-handling" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes modules which support handling data formats commonly used
on the Internet.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="email.html">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a><ul>
<li class="toctree-l2"><a class="reference internal" href="email.message.html">18.1.1. <code class="docutils literal notranslate"><span class="pre">email.message</span></code>: Representing an email message</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.parser.html">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a><ul>
<li class="toctree-l3"><a class="reference internal" href="email.parser.html#feedparser-api">18.1.2.1. FeedParser API</a></li>
<li class="toctree-l3"><a class="reference internal" href="email.parser.html#parser-class-api">18.1.2.2. Parser class API</a></li>
<li class="toctree-l3"><a class="reference internal" href="email.parser.html#additional-notes">18.1.2.3. Additional notes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="email.generator.html">18.1.3. <code class="docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.mime.html">18.1.4. <code class="docutils literal notranslate"><span class="pre">email.mime</span></code>: Creating email and MIME objects from scratch</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.header.html">18.1.5. <code class="docutils literal notranslate"><span class="pre">email.header</span></code>: Internationalized headers</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.charset.html">18.1.6. <code class="docutils literal notranslate"><span class="pre">email.charset</span></code>: Representing character sets</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.encoders.html">18.1.7. <code class="docutils literal notranslate"><span class="pre">email.encoders</span></code>: Encoders</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.errors.html">18.1.8. <code class="docutils literal notranslate"><span class="pre">email.errors</span></code>: Exception and Defect classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.utils.html">18.1.9. <code class="docutils literal notranslate"><span class="pre">email.utils</span></code>: Miscellaneous utilities</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.iterators.html">18.1.10. <code class="docutils literal notranslate"><span class="pre">email.iterators</span></code>: Iterators</a></li>
<li class="toctree-l2"><a class="reference internal" href="email-examples.html">18.1.11. <code class="docutils literal notranslate"><span class="pre">email</span></code>: Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.html#package-history">18.1.12. Package History</a></li>
<li class="toctree-l2"><a class="reference internal" href="email.html#differences-from-mimelib">18.1.13. Differences from <code class="docutils literal notranslate"><span class="pre">mimelib</span></code></a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="json.html">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a><ul>
<li class="toctree-l2"><a class="reference internal" href="json.html#basic-usage">18.2.1. Basic Usage</a></li>
<li class="toctree-l2"><a class="reference internal" href="json.html#encoders-and-decoders">18.2.2. Encoders and Decoders</a></li>
<li class="toctree-l2"><a class="reference internal" href="json.html#standard-compliance-and-interoperability">18.2.3. Standard Compliance and Interoperability</a><ul>
<li class="toctree-l3"><a class="reference internal" href="json.html#character-encodings">18.2.3.1. Character Encodings</a></li>
<li class="toctree-l3"><a class="reference internal" href="json.html#infinite-and-nan-number-values">18.2.3.2. Infinite and NaN Number Values</a></li>
<li class="toctree-l3"><a class="reference internal" href="json.html#repeated-names-within-an-object">18.2.3.3. Repeated Names Within an Object</a></li>
<li class="toctree-l3"><a class="reference internal" href="json.html#top-level-non-object-non-array-values">18.2.3.4. Top-level Non-Object, Non-Array Values</a></li>
<li class="toctree-l3"><a class="reference internal" href="json.html#implementation-limitations">18.2.3.5. Implementation Limitations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mailcap.html">18.3. <code class="docutils literal notranslate"><span class="pre">mailcap</span></code> — Mailcap file handling</a></li>
<li class="toctree-l1"><a class="reference internal" href="mailbox.html">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html#mailbox-objects">18.4.1. <code class="docutils literal notranslate"><span class="pre">Mailbox</span></code> objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#maildir">18.4.1.1. <code class="docutils literal notranslate"><span class="pre">Maildir</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mbox">18.4.1.2. <code class="docutils literal notranslate"><span class="pre">mbox</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mh">18.4.1.3. <code class="docutils literal notranslate"><span class="pre">MH</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#babyl">18.4.1.4. <code class="docutils literal notranslate"><span class="pre">Babyl</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mmdf">18.4.1.5. <code class="docutils literal notranslate"><span class="pre">MMDF</span></code></a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html#message-objects">18.4.2. <code class="docutils literal notranslate"><span class="pre">Message</span></code> objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#maildirmessage">18.4.2.1. <code class="docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mboxmessage">18.4.2.2. <code class="docutils literal notranslate"><span class="pre">mboxMessage</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mhmessage">18.4.2.3. <code class="docutils literal notranslate"><span class="pre">MHMessage</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#babylmessage">18.4.2.4. <code class="docutils literal notranslate"><span class="pre">BabylMessage</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="mailbox.html#mmdfmessage">18.4.2.5. <code class="docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html#exceptions">18.4.3. Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html#deprecated-classes-and-methods">18.4.4. Deprecated classes and methods</a></li>
<li class="toctree-l2"><a class="reference internal" href="mailbox.html#examples">18.4.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mhlib.html">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mhlib.html#mh-objects">18.5.1. MH Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="mhlib.html#folder-objects">18.5.2. Folder Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="mhlib.html#message-objects">18.5.3. Message Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mimetools.html">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mimetools.html#additional-methods-of-message-objects">18.6.1. Additional Methods of Message Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mimetypes.html">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mimetypes.html#mimetypes-objects">18.7.1. MimeTypes Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mimewriter.html">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mimewriter.html#mimewriter-objects">18.8.1. MimeWriter Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mimify.html">18.9. <code class="docutils literal notranslate"><span class="pre">mimify</span></code> — MIME processing of mail messages</a></li>
<li class="toctree-l1"><a class="reference internal" href="multifile.html">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a><ul>
<li class="toctree-l2"><a class="reference internal" href="multifile.html#multifile-objects">18.10.1. MultiFile Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="multifile.html#multifile-example">18.10.2. <code class="docutils literal notranslate"><span class="pre">MultiFile</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="rfc822.html">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="rfc822.html#message-objects">18.11.1. Message Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="rfc822.html#addresslist-objects">18.11.2. AddressList Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="base64.html">18.12. <code class="docutils literal notranslate"><span class="pre">base64</span></code> — RFC 3548: Base16, Base32, Base64 Data Encodings</a></li>
<li class="toctree-l1"><a class="reference internal" href="binhex.html">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="binhex.html#notes">18.13.1. Notes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="binascii.html">18.14. <code class="docutils literal notranslate"><span class="pre">binascii</span></code> — Convert between binary and ASCII</a></li>
<li class="toctree-l1"><a class="reference internal" href="quopri.html">18.15. <code class="docutils literal notranslate"><span class="pre">quopri</span></code> — Encode and decode MIME quoted-printable data</a></li>
<li class="toctree-l1"><a class="reference internal" href="uu.html">18.16. <code class="docutils literal notranslate"><span class="pre">uu</span></code> — Encode and decode uuencode files</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="asynchat.html"
                        title="previous chapter">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="email.html"
                        title="next chapter">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/netdata.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="email.html" title="18.1. email — An email and MIME handling package"
             >next</a> |</li>
        <li class="right" >
          <a href="asynchat.html" title="17.7. asynchat — Asynchronous socket command/response handler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�yM�6�6html/library/netrc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.4. netrc — netrc file processing &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.5. xdrlib — Encode and decode XDR data" href="xdrlib.html" />
    <link rel="prev" title="13.3. robotparser — Parser for robots.txt" href="robotparser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/netrc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xdrlib.html" title="13.5. xdrlib — Encode and decode XDR data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="robotparser.html" title="13.3. robotparser — Parser for robots.txt"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-netrc">
<span id="netrc-netrc-file-processing"></span><h1>13.4. <a class="reference internal" href="#module-netrc" title="netrc: Loading of .netrc files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">netrc</span></code></a> — netrc file processing<a class="headerlink" href="#module-netrc" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/netrc.py">Lib/netrc.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#netrc.netrc" title="netrc.netrc"><code class="xref py py-class docutils literal notranslate"><span class="pre">netrc</span></code></a> class parses and encapsulates the netrc file format used by
the Unix <strong class="program">ftp</strong> program and other FTP clients.</p>
<dl class="class">
<dt id="netrc.netrc">
<em class="property">class </em><code class="descclassname">netrc.</code><code class="descname">netrc</code><span class="sig-paren">(</span><span class="optional">[</span><em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#netrc.netrc" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#netrc.netrc" title="netrc.netrc"><code class="xref py py-class docutils literal notranslate"><span class="pre">netrc</span></code></a> instance or subclass instance encapsulates data from  a netrc
file.  The initialization argument, if present, specifies the file to parse.  If
no argument is given, the file <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code> in the user’s home directory will
be read.  Parse errors will raise <a class="reference internal" href="#netrc.NetrcParseError" title="netrc.NetrcParseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NetrcParseError</span></code></a> with diagnostic
information including the file name, line number, and terminating token.
If no argument is specified on a POSIX system, the presence of passwords in
the <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code> file will raise a <a class="reference internal" href="#netrc.NetrcParseError" title="netrc.NetrcParseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NetrcParseError</span></code></a> if the file
ownership or permissions are insecure (owned by a user other than the user
running the process, or accessible for read or write by any other user).
This implements security behavior equivalent to that of ftp and other
programs that use <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.6: </span>Added the POSIX permissions check.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="netrc.NetrcParseError">
<em class="property">exception </em><code class="descclassname">netrc.</code><code class="descname">NetrcParseError</code><a class="headerlink" href="#netrc.NetrcParseError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by the <a class="reference internal" href="#netrc.netrc" title="netrc.netrc"><code class="xref py py-class docutils literal notranslate"><span class="pre">netrc</span></code></a> class when syntactical errors are
encountered in source text.  Instances of this exception provide three
interesting attributes:  <code class="xref py py-attr docutils literal notranslate"><span class="pre">msg</span></code> is a textual explanation of the error,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> is the name of the source file, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">lineno</span></code> gives the
line number on which the error was found.</p>
</dd></dl>

<div class="section" id="netrc-objects">
<span id="id1"></span><h2>13.4.1. netrc Objects<a class="headerlink" href="#netrc-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#netrc.netrc" title="netrc.netrc"><code class="xref py py-class docutils literal notranslate"><span class="pre">netrc</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="netrc.netrc.authenticators">
<code class="descclassname">netrc.</code><code class="descname">authenticators</code><span class="sig-paren">(</span><em>host</em><span class="sig-paren">)</span><a class="headerlink" href="#netrc.netrc.authenticators" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a 3-tuple <code class="docutils literal notranslate"><span class="pre">(login,</span> <span class="pre">account,</span> <span class="pre">password)</span></code> of authenticators for <em>host</em>.
If the netrc file did not contain an entry for the given host, return the tuple
associated with the ‘default’ entry.  If neither matching host nor default entry
is available, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="netrc.netrc.__repr__">
<code class="descclassname">netrc.</code><code class="descname">__repr__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#netrc.netrc.__repr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Dump the class data as a string in the format of a netrc file. (This discards
comments and may reorder the entries.)</p>
</dd></dl>

<p>Instances of <a class="reference internal" href="#netrc.netrc" title="netrc.netrc"><code class="xref py py-class docutils literal notranslate"><span class="pre">netrc</span></code></a> have public instance variables:</p>
<dl class="attribute">
<dt id="netrc.netrc.hosts">
<code class="descclassname">netrc.</code><code class="descname">hosts</code><a class="headerlink" href="#netrc.netrc.hosts" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping host names to <code class="docutils literal notranslate"><span class="pre">(login,</span> <span class="pre">account,</span> <span class="pre">password)</span></code> tuples.  The
‘default’ entry, if any, is represented as a pseudo-host by that name.</p>
</dd></dl>

<dl class="attribute">
<dt id="netrc.netrc.macros">
<code class="descclassname">netrc.</code><code class="descname">macros</code><a class="headerlink" href="#netrc.netrc.macros" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping macro names to string lists.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Passwords are limited to a subset of the ASCII character set. Versions of
this module prior to 2.3 were extremely limited.  Starting with 2.3, all
ASCII punctuation is allowed in passwords.  However, note that whitespace and
non-printable characters are not allowed in passwords.  This is a limitation
of the way the .netrc file is parsed and may be removed in the future.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a><ul>
<li><a class="reference internal" href="#netrc-objects">13.4.1. netrc Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="robotparser.html"
                        title="previous chapter">13.3. <code class="docutils literal notranslate"><span class="pre">robotparser</span></code> —  Parser for robots.txt</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xdrlib.html"
                        title="next chapter">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/netrc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xdrlib.html" title="13.5. xdrlib — Encode and decode XDR data"
             >next</a> |</li>
        <li class="right" >
          <a href="robotparser.html" title="13.3. robotparser — Parser for robots.txt"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�93y3y3html/library/new.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.16. new — Creation of runtime internal objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.17. copy — Shallow and deep copy operations" href="copy.html" />
    <link rel="prev" title="8.15. types — Names for built-in types" href="types.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/new.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copy.html" title="8.17. copy — Shallow and deep copy operations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="types.html" title="8.15. types — Names for built-in types"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-new">
<span id="new-creation-of-runtime-internal-objects"></span><h1>8.16. <a class="reference internal" href="#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a> — Creation of runtime internal objects<a class="headerlink" href="#module-new" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a> module has been removed in Python 3.  Use the <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a>
module’s classes instead.</p>
</div>
<p>The <a class="reference internal" href="#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a> module allows an interface to the interpreter object creation
functions. This is for use primarily in marshal-type functions, when a new
object needs to be created “magically” and not by using the regular creation
functions. This module provides a low-level interface to the interpreter, so
care must be exercised when using this module. It is possible to supply
non-sensical arguments which crash the interpreter when the object is used.</p>
<p>The <a class="reference internal" href="#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="new.instance">
<code class="descclassname">new.</code><code class="descname">instance</code><span class="sig-paren">(</span><em>class</em><span class="optional">[</span>, <em>dict</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#new.instance" title="Permalink to this definition">¶</a></dt>
<dd><p>This function creates an instance of <em>class</em> with dictionary <em>dict</em> without
calling the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> constructor.  If <em>dict</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, a
new, empty dictionary is created for the new instance.  Note that there are no
guarantees that the object will be in a consistent state.</p>
</dd></dl>

<dl class="function">
<dt id="new.instancemethod">
<code class="descclassname">new.</code><code class="descname">instancemethod</code><span class="sig-paren">(</span><em>function</em>, <em>instance</em>, <em>class</em><span class="sig-paren">)</span><a class="headerlink" href="#new.instancemethod" title="Permalink to this definition">¶</a></dt>
<dd><p>This function will return a method object, bound to <em>instance</em>, or unbound if
<em>instance</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <em>function</em> must be callable.</p>
</dd></dl>

<dl class="function">
<dt id="new.function">
<code class="descclassname">new.</code><code class="descname">function</code><span class="sig-paren">(</span><em>code</em>, <em>globals</em><span class="optional">[</span>, <em>name</em><span class="optional">[</span>, <em>argdefs</em><span class="optional">[</span>, <em>closure</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#new.function" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a (Python) function with the given code and globals. If <em>name</em> is given,
it must be a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If it is a string, the function will have the
given name, otherwise the function name will be taken from <code class="docutils literal notranslate"><span class="pre">code.co_name</span></code>.  If
<em>argdefs</em> is given, it must be a tuple and will be used to determine the default
values of parameters.  If <em>closure</em> is given, it must be <code class="docutils literal notranslate"><span class="pre">None</span></code> or a tuple of
cell objects containing objects to bind to the names in <code class="docutils literal notranslate"><span class="pre">code.co_freevars</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="new.code">
<code class="descclassname">new.</code><code class="descname">code</code><span class="sig-paren">(</span><em>argcount</em>, <em>nlocals</em>, <em>stacksize</em>, <em>flags</em>, <em>codestring</em>, <em>constants</em>, <em>names</em>, <em>varnames</em>, <em>filename</em>, <em>name</em>, <em>firstlineno</em>, <em>lnotab</em><span class="sig-paren">)</span><a class="headerlink" href="#new.code" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is an interface to the <a class="reference internal" href="../c-api/code.html#c.PyCode_New" title="PyCode_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCode_New()</span></code></a> C function.</p>
</dd></dl>

<dl class="function">
<dt id="new.module">
<code class="descclassname">new.</code><code class="descname">module</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>doc</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#new.module" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns a new module object with name <em>name</em>. <em>name</em> must be a
string. The optional <em>doc</em> argument can have any type.</p>
</dd></dl>

<dl class="function">
<dt id="new.classobj">
<code class="descclassname">new.</code><code class="descname">classobj</code><span class="sig-paren">(</span><em>name</em>, <em>baseclasses</em>, <em>dict</em><span class="sig-paren">)</span><a class="headerlink" href="#new.classobj" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns a new class object, with name <em>name</em>, derived from
<em>baseclasses</em> (which should be a tuple of classes) and with namespace <em>dict</em>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="types.html"
                        title="previous chapter">8.15. <code class="docutils literal notranslate"><span class="pre">types</span></code> — Names for built-in types</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="copy.html"
                        title="next chapter">8.17. <code class="docutils literal notranslate"><span class="pre">copy</span></code> — Shallow and deep copy operations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/new.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copy.html" title="8.17. copy — Shallow and deep copy operations"
             >next</a> |</li>
        <li class="right" >
          <a href="types.html" title="8.15. types — Names for built-in types"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�7���,�,html/library/nis.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.14. nis — Interface to Sun’s NIS (Yellow Pages) &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.15. syslog — Unix syslog library routines" href="syslog.html" />
    <link rel="prev" title="36.13. resource — Resource usage information" href="resource.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/nis.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="syslog.html" title="36.15. syslog — Unix syslog library routines"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="resource.html" title="36.13. resource — Resource usage information"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-nis">
<span id="nis-interface-to-sun-s-nis-yellow-pages"></span><h1>36.14. <a class="reference internal" href="#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> — Interface to Sun’s NIS (Yellow Pages)<a class="headerlink" href="#module-nis" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> module gives a thin wrapper around the NIS library, useful for
central administration of several hosts.</p>
<p>Because NIS exists only on Unix systems, this module is only available for Unix.</p>
<p>The <a class="reference internal" href="#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="nis.match">
<code class="descclassname">nis.</code><code class="descname">match</code><span class="sig-paren">(</span><em>key</em>, <em>mapname</em><span class="optional">[</span>, <em>domain=default_domain</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nis.match" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the match for <em>key</em> in map <em>mapname</em>, or raise an error
(<a class="reference internal" href="#nis.error" title="nis.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">nis.error</span></code></a>) if there is none. Both should be strings, <em>key</em> is 8-bit
clean. Return value is an arbitrary array of bytes (may contain <code class="docutils literal notranslate"><span class="pre">NULL</span></code> and
other joys).</p>
<p>Note that <em>mapname</em> is first checked if it is an alias to another name.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>domain</em> argument allows overriding the NIS domain used for the lookup. If
unspecified, lookup is in the default NIS domain.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="nis.cat">
<code class="descclassname">nis.</code><code class="descname">cat</code><span class="sig-paren">(</span><em>mapname</em><span class="optional">[</span>, <em>domain=default_domain</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nis.cat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary mapping <em>key</em> to <em>value</em> such that <code class="docutils literal notranslate"><span class="pre">match(key,</span>
<span class="pre">mapname)==value</span></code>. Note that both keys and values of the dictionary are
arbitrary arrays of bytes.</p>
<p>Note that <em>mapname</em> is first checked if it is an alias to another name.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>domain</em> argument allows overriding the NIS domain used for the lookup. If
unspecified, lookup is in the default NIS domain.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="nis.maps">
<code class="descclassname">nis.</code><code class="descname">maps</code><span class="sig-paren">(</span><span class="optional">[</span><em>domain=default_domain</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nis.maps" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all valid maps.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>domain</em> argument allows overriding the NIS domain used for the lookup. If
unspecified, lookup is in the default NIS domain.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="nis.get_default_domain">
<code class="descclassname">nis.</code><code class="descname">get_default_domain</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nis.get_default_domain" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the system default NIS domain.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> module defines the following exception:</p>
<dl class="exception">
<dt id="nis.error">
<em class="property">exception </em><code class="descclassname">nis.</code><code class="descname">error</code><a class="headerlink" href="#nis.error" title="Permalink to this definition">¶</a></dt>
<dd><p>An error raised when a NIS function returns an error code.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="resource.html"
                        title="previous chapter">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="syslog.html"
                        title="next chapter">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/nis.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="syslog.html" title="36.15. syslog — Unix syslog library routines"
             >next</a> |</li>
        <li class="right" >
          <a href="resource.html" title="36.13. resource — Resource usage information"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\w��}y�y�html/library/nntplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.11. nntplib — NNTP protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.12. smtplib — SMTP protocol client" href="smtplib.html" />
    <link rel="prev" title="20.10. imaplib — IMAP4 protocol client" href="imaplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/nntplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="smtplib.html" title="20.12. smtplib — SMTP protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imaplib.html" title="20.10. imaplib — IMAP4 protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-nntplib">
<span id="nntplib-nntp-protocol-client"></span><h1>20.11. <a class="reference internal" href="#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a> — NNTP protocol client<a class="headerlink" href="#module-nntplib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/nntplib.py">Lib/nntplib.py</a></p>
<hr class="docutils" />
<p>This module defines the class <a class="reference internal" href="#nntplib.NNTP" title="nntplib.NNTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">NNTP</span></code></a> which implements the client side of
the NNTP protocol.  It can be used to implement a news reader or poster, or
automated news processors.  For more information on NNTP (Network News Transfer
Protocol), see Internet <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc977.html"><strong>RFC 977</strong></a>.</p>
<p>Here are two small examples of how it can be used.  To list some statistics
about a newsgroup and print the subjects of the last 10 articles:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">NNTP</span><span class="p">(</span><span class="s1">&#39;news.gmane.org&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resp</span><span class="p">,</span> <span class="n">count</span><span class="p">,</span> <span class="n">first</span><span class="p">,</span> <span class="n">last</span><span class="p">,</span> <span class="n">name</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;gmane.comp.python.committers&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;Group&#39;</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="s1">&#39;has&#39;</span><span class="p">,</span> <span class="n">count</span><span class="p">,</span> <span class="s1">&#39;articles, range&#39;</span><span class="p">,</span> <span class="n">first</span><span class="p">,</span> <span class="s1">&#39;to&#39;</span><span class="p">,</span> <span class="n">last</span>
<span class="go">Group gmane.comp.python.committers has 1071 articles, range 1 to 1071</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">resp</span><span class="p">,</span> <span class="n">subs</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">xhdr</span><span class="p">(</span><span class="s1">&#39;subject&#39;</span><span class="p">,</span> <span class="n">first</span> <span class="o">+</span> <span class="s1">&#39;-&#39;</span> <span class="o">+</span> <span class="n">last</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="nb">id</span><span class="p">,</span> <span class="n">sub</span> <span class="ow">in</span> <span class="n">subs</span><span class="p">[</span><span class="o">-</span><span class="mi">10</span><span class="p">:]:</span> <span class="nb">print</span> <span class="nb">id</span><span class="p">,</span> <span class="n">sub</span>
<span class="gp">...</span>
<span class="go">1062 Re: Mercurial Status?</span>
<span class="go">1063 Re: [python-committers]  (Windows) buildbots on 3.x</span>
<span class="go">1064 Re: Mercurial Status?</span>
<span class="go">1065 Re: Mercurial Status?</span>
<span class="go">1066 Python 2.6.6 status</span>
<span class="go">1067 Commit Privileges for Ask Solem</span>
<span class="go">1068 Re: Commit Privileges for Ask Solem</span>
<span class="go">1069 Re: Commit Privileges for Ask Solem</span>
<span class="go">1070 Re: Commit Privileges for Ask Solem</span>
<span class="go">1071 2.6.6 rc 2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
<span class="go">&#39;205 Bye!&#39;</span>
</pre></div>
</div>
<p>To post an article from a file (this assumes that the article has valid
headers, and that you have right to post on the particular newsgroup):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">NNTP</span><span class="p">(</span><span class="s1">&#39;news.gmane.org&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;articlefile&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">post</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="go">&#39;240 Article posted successfully.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
<span class="go">&#39;205 Bye!&#39;</span>
</pre></div>
</div>
<p>The module itself defines the following items:</p>
<dl class="class">
<dt id="nntplib.NNTP">
<em class="property">class </em><code class="descclassname">nntplib.</code><code class="descname">NNTP</code><span class="sig-paren">(</span><em>host[, port [, user[, password [, readermode] [, usenetrc]]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new instance of the <a class="reference internal" href="#nntplib.NNTP" title="nntplib.NNTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">NNTP</span></code></a> class, representing a connection
to the NNTP server running on host <em>host</em>, listening at port <em>port</em>.  The
default <em>port</em> is 119.  If the optional <em>user</em> and <em>password</em> are provided,
or if suitable credentials are present in <code class="file docutils literal notranslate"><span class="pre">/.netrc</span></code> and the optional
flag <em>usenetrc</em> is true (the default), the <code class="docutils literal notranslate"><span class="pre">AUTHINFO</span> <span class="pre">USER</span></code> and <code class="docutils literal notranslate"><span class="pre">AUTHINFO</span>
<span class="pre">PASS</span></code> commands are used to identify and authenticate the user to the server.
If the optional flag <em>readermode</em> is true, then a <code class="docutils literal notranslate"><span class="pre">mode</span> <span class="pre">reader</span></code> command is
sent before authentication is performed.  Reader mode is sometimes necessary
if you are connecting to an NNTP server on the local machine and intend to
call reader-specific commands, such as <code class="docutils literal notranslate"><span class="pre">group</span></code>.  If you get unexpected
<a class="reference internal" href="#nntplib.NNTPPermanentError" title="nntplib.NNTPPermanentError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NNTPPermanentError</span></code></a>s, you might need to set <em>readermode</em>.
<em>readermode</em> defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>. <em>usenetrc</em> defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>usenetrc</em> argument added.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPError</code><a class="headerlink" href="#nntplib.NNTPError" title="Permalink to this definition">¶</a></dt>
<dd><p>Derived from the standard exception <a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>, this is the base class for
all exceptions raised by the <a class="reference internal" href="#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a> module.</p>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPReplyError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPReplyError</code><a class="headerlink" href="#nntplib.NNTPReplyError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an unexpected reply is received from the server.  For
backwards compatibility, the exception <code class="docutils literal notranslate"><span class="pre">error_reply</span></code> is equivalent to this
class.</p>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPTemporaryError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPTemporaryError</code><a class="headerlink" href="#nntplib.NNTPTemporaryError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error code in the range 400–499 is received.  For
backwards compatibility, the exception <code class="docutils literal notranslate"><span class="pre">error_temp</span></code> is equivalent to this
class.</p>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPPermanentError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPPermanentError</code><a class="headerlink" href="#nntplib.NNTPPermanentError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error code in the range 500–599 is received.  For
backwards compatibility, the exception <code class="docutils literal notranslate"><span class="pre">error_perm</span></code> is equivalent to this
class.</p>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPProtocolError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPProtocolError</code><a class="headerlink" href="#nntplib.NNTPProtocolError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a reply is received from the server that does not begin
with a digit in the range 1–5.  For backwards compatibility, the exception
<code class="docutils literal notranslate"><span class="pre">error_proto</span></code> is equivalent to this class.</p>
</dd></dl>

<dl class="exception">
<dt id="nntplib.NNTPDataError">
<em class="property">exception </em><code class="descclassname">nntplib.</code><code class="descname">NNTPDataError</code><a class="headerlink" href="#nntplib.NNTPDataError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when there is some error in the response data.  For backwards
compatibility, the exception <code class="docutils literal notranslate"><span class="pre">error_data</span></code> is equivalent to this class.</p>
</dd></dl>

<div class="section" id="nntp-objects">
<span id="id1"></span><h2>20.11.1. NNTP Objects<a class="headerlink" href="#nntp-objects" title="Permalink to this headline">¶</a></h2>
<p>NNTP instances have the following methods.  The <em>response</em> that is returned as
the first item in the return tuple of almost all methods is the server’s
response: a string beginning with a three-digit code. If the server’s response
indicates an error, the method raises one of the above exceptions.</p>
<dl class="method">
<dt id="nntplib.NNTP.getwelcome">
<code class="descclassname">NNTP.</code><code class="descname">getwelcome</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.getwelcome" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the welcome message sent by the server in reply to the initial
connection.  (This message sometimes contains disclaimers or help information
that may be relevant to the user.)</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.set_debuglevel">
<code class="descclassname">NNTP.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the instance’s debugging level.  This controls the amount of debugging
output printed.  The default, <code class="docutils literal notranslate"><span class="pre">0</span></code>, produces no debugging output.  A value of
<code class="docutils literal notranslate"><span class="pre">1</span></code> produces a moderate amount of debugging output, generally a single line
per request or response.  A value of <code class="docutils literal notranslate"><span class="pre">2</span></code> or higher produces the maximum amount
of debugging output, logging each line sent and received on the connection
(including message text).</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.newgroups">
<code class="descclassname">NNTP.</code><code class="descname">newgroups</code><span class="sig-paren">(</span><em>date</em>, <em>time</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.newgroups" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">NEWGROUPS</span></code> command.  The <em>date</em> argument should be a string of the
form <code class="docutils literal notranslate"><span class="pre">'yymmdd'</span></code> indicating the date, and <em>time</em> should be a string of the form
<code class="docutils literal notranslate"><span class="pre">'hhmmss'</span></code> indicating the time.  Return a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">groups)</span></code> where
<em>groups</em> is a list of group names that are new since the given date and time. If
the <em>file</em> parameter is supplied, then the output of the  <code class="docutils literal notranslate"><span class="pre">NEWGROUPS</span></code> command
is stored in a file.  If <em>file</em> is a string,  then the method will open a file
object with that name, write to it  then close it.  If <em>file</em> is a file object,
then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the lines of the command
output. If <em>file</em> is supplied, then the returned <em>list</em> is an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.newnews">
<code class="descclassname">NNTP.</code><code class="descname">newnews</code><span class="sig-paren">(</span><em>group</em>, <em>date</em>, <em>time</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.newnews" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">NEWNEWS</span></code> command.  Here, <em>group</em> is a group name or <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, and
<em>date</em> and <em>time</em> have the same meaning as for <a class="reference internal" href="#nntplib.NNTP.newgroups" title="nntplib.NNTP.newgroups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">newgroups()</span></code></a>.  Return a pair
<code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">articles)</span></code> where <em>articles</em> is a list of message ids. If the
<em>file</em> parameter is supplied, then the output of the  <code class="docutils literal notranslate"><span class="pre">NEWNEWS</span></code> command is
stored in a file.  If <em>file</em> is a string,  then the method will open a file
object with that name, write to it  then close it.  If <em>file</em> is a file object,
then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the lines of the command
output. If <em>file</em> is supplied, then the returned <em>list</em> is an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.list">
<code class="descclassname">NNTP.</code><code class="descname">list</code><span class="sig-paren">(</span><span class="optional">[</span><em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.list" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">LIST</span></code> command.  Return a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">list)</span></code> where <em>list</em> is a
list of tuples.  Each tuple has the form <code class="docutils literal notranslate"><span class="pre">(group,</span> <span class="pre">last,</span> <span class="pre">first,</span> <span class="pre">flag)</span></code>, where
<em>group</em> is a group name, <em>last</em> and <em>first</em> are the last and first article
numbers (as strings), and <em>flag</em> is <code class="docutils literal notranslate"><span class="pre">'y'</span></code> if posting is allowed, <code class="docutils literal notranslate"><span class="pre">'n'</span></code> if
not, and <code class="docutils literal notranslate"><span class="pre">'m'</span></code> if the newsgroup is moderated.  (Note the ordering: <em>last</em>,
<em>first</em>.) If the <em>file</em> parameter is supplied, then the output of the  <code class="docutils literal notranslate"><span class="pre">LIST</span></code>
command is stored in a file.  If <em>file</em> is a string,  then the method will open
a file object with that name, write to it  then close it.  If <em>file</em> is a file
object, then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the lines of the
command output. If <em>file</em> is supplied, then the returned <em>list</em> is an empty
list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.descriptions">
<code class="descclassname">NNTP.</code><code class="descname">descriptions</code><span class="sig-paren">(</span><em>grouppattern</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.descriptions" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">LIST</span> <span class="pre">NEWSGROUPS</span></code> command, where <em>grouppattern</em> is a wildmat string as
specified in RFC2980 (it’s essentially the same as DOS or UNIX shell wildcard
strings).  Return a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">list)</span></code>, where <em>list</em> is a list of tuples
containing <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">title)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.description">
<code class="descclassname">NNTP.</code><code class="descname">description</code><span class="sig-paren">(</span><em>group</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.description" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a description for a single group <em>group</em>.  If more than one group matches
(if ‘group’ is a real wildmat string), return the first match.   If no group
matches, return an empty string.</p>
<p>This elides the response code from the server.  If the response code is needed,
use <a class="reference internal" href="#nntplib.NNTP.descriptions" title="nntplib.NNTP.descriptions"><code class="xref py py-meth docutils literal notranslate"><span class="pre">descriptions()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.group">
<code class="descclassname">NNTP.</code><code class="descname">group</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.group" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">GROUP</span></code> command, where <em>name</em> is the group name. Return a tuple
<code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">count,</span> <span class="pre">first,</span> <span class="pre">last,</span> <span class="pre">name)</span></code> where <em>count</em> is the (estimated) number
of articles in the group, <em>first</em> is the first article number in the group,
<em>last</em> is the last article number in the group, and <em>name</em> is the group name.
The numbers are returned as strings.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.help">
<code class="descclassname">NNTP.</code><code class="descname">help</code><span class="sig-paren">(</span><span class="optional">[</span><em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.help" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">HELP</span></code> command.  Return a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">list)</span></code> where <em>list</em> is a
list of help strings. If the <em>file</em> parameter is supplied, then the output of
the  <code class="docutils literal notranslate"><span class="pre">HELP</span></code> command is stored in a file.  If <em>file</em> is a string,  then the
method will open a file object with that name, write to it  then close it.  If
<em>file</em> is a file object, then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store
the lines of the command output. If <em>file</em> is supplied, then the returned <em>list</em>
is an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.stat">
<code class="descclassname">NNTP.</code><code class="descname">stat</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.stat" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">STAT</span></code> command, where <em>id</em> is the message id (enclosed in <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>) or an article number (as a string). Return a triple <code class="docutils literal notranslate"><span class="pre">(response,</span>
<span class="pre">number,</span> <span class="pre">id)</span></code> where <em>number</em> is the article number (as a string) and <em>id</em> is the
message id  (enclosed in <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.next">
<code class="descclassname">NNTP.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">NEXT</span></code> command.  Return as for <a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.last">
<code class="descclassname">NNTP.</code><code class="descname">last</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.last" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">LAST</span></code> command.  Return as for <a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.head">
<code class="descclassname">NNTP.</code><code class="descname">head</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.head" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">HEAD</span></code> command, where <em>id</em> has the same meaning as for <a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>.
Return a tuple <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">number,</span> <span class="pre">id,</span> <span class="pre">list)</span></code> where the first three are the
same as for <a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>, and <em>list</em> is a list of the article’s headers (an
uninterpreted list of lines, without trailing newlines).</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.body">
<code class="descclassname">NNTP.</code><code class="descname">body</code><span class="sig-paren">(</span><em>id</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.body" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">BODY</span></code> command, where <em>id</em> has the same meaning as for <a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>.
If the <em>file</em> parameter is supplied, then the body is stored in a file.  If
<em>file</em> is a string, then the method will open a file object with that name,
write to it then close it. If <em>file</em> is a file object, then it will start
calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the lines of the body. Return as for
<a class="reference internal" href="#nntplib.NNTP.head" title="nntplib.NNTP.head"><code class="xref py py-meth docutils literal notranslate"><span class="pre">head()</span></code></a>.  If <em>file</em> is supplied, then the returned <em>list</em> is an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.article">
<code class="descclassname">NNTP.</code><code class="descname">article</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.article" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an <code class="docutils literal notranslate"><span class="pre">ARTICLE</span></code> command, where <em>id</em> has the same meaning as for
<a class="reference internal" href="#nntplib.NNTP.stat" title="nntplib.NNTP.stat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stat()</span></code></a>.  Return as for <a class="reference internal" href="#nntplib.NNTP.head" title="nntplib.NNTP.head"><code class="xref py py-meth docutils literal notranslate"><span class="pre">head()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.slave">
<code class="descclassname">NNTP.</code><code class="descname">slave</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.slave" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">SLAVE</span></code> command.  Return the server’s <em>response</em>.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.xhdr">
<code class="descclassname">NNTP.</code><code class="descname">xhdr</code><span class="sig-paren">(</span><em>header</em>, <em>string</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.xhdr" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an <code class="docutils literal notranslate"><span class="pre">XHDR</span></code> command.  This command is not defined in the RFC but is a
common extension.  The <em>header</em> argument is a header keyword, e.g.
<code class="docutils literal notranslate"><span class="pre">'subject'</span></code>.  The <em>string</em> argument should have the form <code class="docutils literal notranslate"><span class="pre">'first-last'</span></code>
where <em>first</em> and <em>last</em> are the first and last article numbers to search.
Return a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">list)</span></code>, where <em>list</em> is a list of pairs <code class="docutils literal notranslate"><span class="pre">(id,</span>
<span class="pre">text)</span></code>, where <em>id</em> is an article number (as a string) and <em>text</em> is the text of
the requested header for that article. If the <em>file</em> parameter is supplied, then
the output of the  <code class="docutils literal notranslate"><span class="pre">XHDR</span></code> command is stored in a file.  If <em>file</em> is a string,
then the method will open a file object with that name, write to it  then close
it.  If <em>file</em> is a file object, then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it
to store the lines of the command output. If <em>file</em> is supplied, then the
returned <em>list</em> is an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.post">
<code class="descclassname">NNTP.</code><code class="descname">post</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.post" title="Permalink to this definition">¶</a></dt>
<dd><p>Post an article using the <code class="docutils literal notranslate"><span class="pre">POST</span></code> command.  The <em>file</em> argument is an open file
object which is read until EOF using its <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method.  It should be
a well-formed news article, including the required headers.  The <a class="reference internal" href="#nntplib.NNTP.post" title="nntplib.NNTP.post"><code class="xref py py-meth docutils literal notranslate"><span class="pre">post()</span></code></a>
method automatically escapes lines beginning with <code class="docutils literal notranslate"><span class="pre">.</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.ihave">
<code class="descclassname">NNTP.</code><code class="descname">ihave</code><span class="sig-paren">(</span><em>id</em>, <em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.ihave" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an <code class="docutils literal notranslate"><span class="pre">IHAVE</span></code> command. <em>id</em> is a message id (enclosed in  <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>). If the response is not an error, treat <em>file</em> exactly as for the
<a class="reference internal" href="#nntplib.NNTP.post" title="nntplib.NNTP.post"><code class="xref py py-meth docutils literal notranslate"><span class="pre">post()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.date">
<code class="descclassname">NNTP.</code><code class="descname">date</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.date" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a triple <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">date,</span> <span class="pre">time)</span></code>, containing the current date and time
in a form suitable for the <a class="reference internal" href="#nntplib.NNTP.newnews" title="nntplib.NNTP.newnews"><code class="xref py py-meth docutils literal notranslate"><span class="pre">newnews()</span></code></a> and <a class="reference internal" href="#nntplib.NNTP.newgroups" title="nntplib.NNTP.newgroups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">newgroups()</span></code></a> methods. This
is an optional NNTP extension, and may not be supported by all servers.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.xgtitle">
<code class="descclassname">NNTP.</code><code class="descname">xgtitle</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.xgtitle" title="Permalink to this definition">¶</a></dt>
<dd><p>Process an <code class="docutils literal notranslate"><span class="pre">XGTITLE</span></code> command, returning a pair <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">list)</span></code>, where
<em>list</em> is a list of tuples containing <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">title)</span></code>. If the <em>file</em> parameter
is supplied, then the output of the  <code class="docutils literal notranslate"><span class="pre">XGTITLE</span></code> command is stored in a file.
If <em>file</em> is a string,  then the method will open a file object with that name,
write to it  then close it.  If <em>file</em> is a file object, then it will start
calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the lines of the command output. If <em>file</em>
is supplied, then the returned <em>list</em> is an empty list. This is an optional NNTP
extension, and may not be supported by all servers.</p>
<p>RFC2980 says “It is suggested that this extension be deprecated”.  Use
<a class="reference internal" href="#nntplib.NNTP.descriptions" title="nntplib.NNTP.descriptions"><code class="xref py py-meth docutils literal notranslate"><span class="pre">descriptions()</span></code></a> or <a class="reference internal" href="#nntplib.NNTP.description" title="nntplib.NNTP.description"><code class="xref py py-meth docutils literal notranslate"><span class="pre">description()</span></code></a> instead.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.xover">
<code class="descclassname">NNTP.</code><code class="descname">xover</code><span class="sig-paren">(</span><em>start</em>, <em>end</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.xover" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pair <code class="docutils literal notranslate"><span class="pre">(resp,</span> <span class="pre">list)</span></code>.  <em>list</em> is a list of tuples, one for each
article in the range delimited by the <em>start</em> and <em>end</em> article numbers.  Each
tuple is of the form <code class="docutils literal notranslate"><span class="pre">(article</span> <span class="pre">number,</span> <span class="pre">subject,</span> <span class="pre">poster,</span> <span class="pre">date,</span> <span class="pre">id,</span> <span class="pre">references,</span>
<span class="pre">size,</span> <span class="pre">lines)</span></code>. If the <em>file</em> parameter is supplied, then the output of the
<code class="docutils literal notranslate"><span class="pre">XOVER</span></code> command is stored in a file.  If <em>file</em> is a string,  then the method
will open a file object with that name, write to it  then close it.  If <em>file</em>
is a file object, then it will start calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> on it to store the
lines of the command output. If <em>file</em> is supplied, then the returned <em>list</em> is
an empty list. This is an optional NNTP extension, and may not be supported by
all servers.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.xpath">
<code class="descclassname">NNTP.</code><code class="descname">xpath</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.xpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pair <code class="docutils literal notranslate"><span class="pre">(resp,</span> <span class="pre">path)</span></code>, where <em>path</em> is the directory path to the
article with message ID <em>id</em>.  This is an optional NNTP extension, and may not
be supported by all servers.</p>
</dd></dl>

<dl class="method">
<dt id="nntplib.NNTP.quit">
<code class="descclassname">NNTP.</code><code class="descname">quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#nntplib.NNTP.quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a <code class="docutils literal notranslate"><span class="pre">QUIT</span></code> command and close the connection.  Once this method has been
called, no other methods of the NNTP object should be called.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a><ul>
<li><a class="reference internal" href="#nntp-objects">20.11.1. NNTP Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="imaplib.html"
                        title="previous chapter">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="smtplib.html"
                        title="next chapter">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/nntplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="smtplib.html" title="20.12. smtplib — SMTP protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="imaplib.html" title="20.10. imaplib — IMAP4 protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�h�?����html/library/numbers.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.1. numbers — Numeric abstract base classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.2. math — Mathematical functions" href="math.html" />
    <link rel="prev" title="9. Numeric and Mathematical Modules" href="numeric.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/numbers.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="math.html" title="9.2. math — Mathematical functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="numeric.html" title="9. Numeric and Mathematical Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-numbers">
<span id="numbers-numeric-abstract-base-classes"></span><h1>9.1. <a class="reference internal" href="#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> — Numeric abstract base classes<a class="headerlink" href="#module-numbers" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The <a class="reference internal" href="#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module (<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3141"><strong>PEP 3141</strong></a>) defines a hierarchy of numeric
<a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base classes</span></a> which progressively define
more operations.  None of the types defined in this module can be instantiated.</p>
<dl class="class">
<dt id="numbers.Number">
<em class="property">class </em><code class="descclassname">numbers.</code><code class="descname">Number</code><a class="headerlink" href="#numbers.Number" title="Permalink to this definition">¶</a></dt>
<dd><p>The root of the numeric hierarchy. If you just want to check if an argument
<em>x</em> is a number, without caring what kind, use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">Number)</span></code>.</p>
</dd></dl>

<div class="section" id="the-numeric-tower">
<h2>9.1.1. The numeric tower<a class="headerlink" href="#the-numeric-tower" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="numbers.Complex">
<em class="property">class </em><code class="descclassname">numbers.</code><code class="descname">Complex</code><a class="headerlink" href="#numbers.Complex" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclasses of this type describe complex numbers and include the operations
that work on the built-in <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a> type. These are: conversions to
<a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a> and <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>, <a class="reference internal" href="#numbers.Complex.real" title="numbers.Complex.real"><code class="xref py py-attr docutils literal notranslate"><span class="pre">real</span></code></a>, <a class="reference internal" href="#numbers.Complex.imag" title="numbers.Complex.imag"><code class="xref py py-attr docutils literal notranslate"><span class="pre">imag</span></code></a>, <code class="docutils literal notranslate"><span class="pre">+</span></code>,
<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <a class="reference internal" href="functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a>, <a class="reference internal" href="#numbers.Complex.conjugate" title="numbers.Complex.conjugate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">conjugate()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code>. All
except <code class="docutils literal notranslate"><span class="pre">-</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code> are abstract.</p>
<dl class="attribute">
<dt id="numbers.Complex.real">
<code class="descname">real</code><a class="headerlink" href="#numbers.Complex.real" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract. Retrieves the real component of this number.</p>
</dd></dl>

<dl class="attribute">
<dt id="numbers.Complex.imag">
<code class="descname">imag</code><a class="headerlink" href="#numbers.Complex.imag" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract. Retrieves the imaginary component of this number.</p>
</dd></dl>

<dl class="method">
<dt id="numbers.Complex.conjugate">
<code class="descname">conjugate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#numbers.Complex.conjugate" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract. Returns the complex conjugate. For example, <code class="docutils literal notranslate"><span class="pre">(1+3j).conjugate()</span>
<span class="pre">==</span> <span class="pre">(1-3j)</span></code>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="numbers.Real">
<em class="property">class </em><code class="descclassname">numbers.</code><code class="descname">Real</code><a class="headerlink" href="#numbers.Real" title="Permalink to this definition">¶</a></dt>
<dd><p>To <a class="reference internal" href="#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code></a>, <a class="reference internal" href="#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code></a> adds the operations that work on real
numbers.</p>
<p>In short, those are: a conversion to <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a>,
<a class="reference internal" href="functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a>, <a class="reference internal" href="math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a>, <a class="reference internal" href="math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a>, <a class="reference internal" href="functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">//</span></code>,
<code class="docutils literal notranslate"><span class="pre">%</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>.</p>
<p>Real also provides defaults for <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>, <a class="reference internal" href="#numbers.Complex.real" title="numbers.Complex.real"><code class="xref py py-attr docutils literal notranslate"><span class="pre">real</span></code></a>,
<a class="reference internal" href="#numbers.Complex.imag" title="numbers.Complex.imag"><code class="xref py py-attr docutils literal notranslate"><span class="pre">imag</span></code></a>, and <a class="reference internal" href="#numbers.Complex.conjugate" title="numbers.Complex.conjugate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">conjugate()</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="numbers.Rational">
<em class="property">class </em><code class="descclassname">numbers.</code><code class="descname">Rational</code><a class="headerlink" href="#numbers.Rational" title="Permalink to this definition">¶</a></dt>
<dd><p>Subtypes <a class="reference internal" href="#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code></a> and adds
<a class="reference internal" href="#numbers.Rational.numerator" title="numbers.Rational.numerator"><code class="xref py py-attr docutils literal notranslate"><span class="pre">numerator</span></code></a> and <a class="reference internal" href="#numbers.Rational.denominator" title="numbers.Rational.denominator"><code class="xref py py-attr docutils literal notranslate"><span class="pre">denominator</span></code></a> properties, which
should be in lowest terms. With these, it provides a default for
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>.</p>
<dl class="attribute">
<dt id="numbers.Rational.numerator">
<code class="descname">numerator</code><a class="headerlink" href="#numbers.Rational.numerator" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract.</p>
</dd></dl>

<dl class="attribute">
<dt id="numbers.Rational.denominator">
<code class="descname">denominator</code><a class="headerlink" href="#numbers.Rational.denominator" title="Permalink to this definition">¶</a></dt>
<dd><p>Abstract.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="numbers.Integral">
<em class="property">class </em><code class="descclassname">numbers.</code><code class="descname">Integral</code><a class="headerlink" href="#numbers.Integral" title="Permalink to this definition">¶</a></dt>
<dd><p>Subtypes <a class="reference internal" href="#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code></a> and adds a conversion to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.  Provides
defaults for <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>, <a class="reference internal" href="#numbers.Rational.numerator" title="numbers.Rational.numerator"><code class="xref py py-attr docutils literal notranslate"><span class="pre">numerator</span></code></a>, and
<a class="reference internal" href="#numbers.Rational.denominator" title="numbers.Rational.denominator"><code class="xref py py-attr docutils literal notranslate"><span class="pre">denominator</span></code></a>.  Adds abstract methods for <code class="docutils literal notranslate"><span class="pre">**</span></code> and
bit-string operations: <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>, <code class="docutils literal notranslate"><span class="pre">~</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="notes-for-type-implementors">
<h2>9.1.2. Notes for type implementors<a class="headerlink" href="#notes-for-type-implementors" title="Permalink to this headline">¶</a></h2>
<p>Implementors should be careful to make equal numbers equal and hash
them to the same values. This may be subtle if there are two different
extensions of the real numbers. For example, <a class="reference internal" href="fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a>
implements <a class="reference internal" href="functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">denominator</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
        <span class="c1"># Get integers right.</span>
        <span class="k">return</span> <span class="nb">hash</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">numerator</span><span class="p">)</span>
    <span class="c1"># Expensive check, but definitely correct.</span>
    <span class="k">if</span> <span class="bp">self</span> <span class="o">==</span> <span class="nb">float</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="c1"># Use tuple&#39;s hash to avoid a high collision rate on</span>
        <span class="c1"># simple fractions.</span>
        <span class="k">return</span> <span class="nb">hash</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">numerator</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">denominator</span><span class="p">))</span>
</pre></div>
</div>
<div class="section" id="adding-more-numeric-abcs">
<h3>9.1.2.1. Adding More Numeric ABCs<a class="headerlink" href="#adding-more-numeric-abcs" title="Permalink to this headline">¶</a></h3>
<p>There are, of course, more possible ABCs for numbers, and this would
be a poor hierarchy if it precluded the possibility of adding
those. You can add <code class="docutils literal notranslate"><span class="pre">MyFoo</span></code> between <a class="reference internal" href="#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code></a> and
<a class="reference internal" href="#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code></a> with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyFoo</span><span class="p">(</span><span class="n">Complex</span><span class="p">):</span> <span class="o">...</span>
<span class="n">MyFoo</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Real</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="implementing-the-arithmetic-operations">
<h3>9.1.2.2. Implementing the arithmetic operations<a class="headerlink" href="#implementing-the-arithmetic-operations" title="Permalink to this headline">¶</a></h3>
<p>We want to implement the arithmetic operations so that mixed-mode
operations either call an implementation whose author knew about the
types of both arguments, or convert both to the nearest built in type
and do the operation there. For subtypes of <a class="reference internal" href="#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a>, this
means that <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> should be defined as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyIntegral</span><span class="p">(</span><span class="n">Integral</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">__add__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">MyIntegral</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">do_my_adding_stuff</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">OtherTypeIKnowAbout</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">do_my_other_adding_stuff</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>

    <span class="k">def</span> <span class="nf">__radd__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">MyIntegral</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">do_my_adding_stuff</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">OtherTypeIKnowAbout</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">do_my_other_adding_stuff</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Integral</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">int</span><span class="p">(</span><span class="n">other</span><span class="p">)</span> <span class="o">+</span> <span class="nb">int</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Real</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">float</span><span class="p">(</span><span class="n">other</span><span class="p">)</span> <span class="o">+</span> <span class="nb">float</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">other</span><span class="p">,</span> <span class="n">Complex</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">complex</span><span class="p">(</span><span class="n">other</span><span class="p">)</span> <span class="o">+</span> <span class="nb">complex</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>
</pre></div>
</div>
<p>There are 5 different cases for a mixed-type operation on subclasses
of <a class="reference internal" href="#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code></a>. I’ll refer to all of the above code that doesn’t
refer to <code class="docutils literal notranslate"><span class="pre">MyIntegral</span></code> and <code class="docutils literal notranslate"><span class="pre">OtherTypeIKnowAbout</span></code> as
“boilerplate”. <code class="docutils literal notranslate"><span class="pre">a</span></code> will be an instance of <code class="docutils literal notranslate"><span class="pre">A</span></code>, which is a subtype
of <a class="reference internal" href="#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code></a> (<code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">:</span> <span class="pre">A</span> <span class="pre">&lt;:</span> <span class="pre">Complex</span></code>), and <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">:</span> <span class="pre">B</span> <span class="pre">&lt;:</span>
<span class="pre">Complex</span></code>. I’ll consider <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code>:</p>
<blockquote>
<div><ol class="arabic simple">
<li>If <code class="docutils literal notranslate"><span class="pre">A</span></code> defines an <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> which accepts <code class="docutils literal notranslate"><span class="pre">b</span></code>, all is
well.</li>
<li>If <code class="docutils literal notranslate"><span class="pre">A</span></code> falls back to the boilerplate code, and it were to
return a value from <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>, we’d miss the possibility
that <code class="docutils literal notranslate"><span class="pre">B</span></code> defines a more intelligent <a class="reference internal" href="../reference/datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a>, so the
boilerplate should return <a class="reference internal" href="constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-const docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> from
<a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>. (Or <code class="docutils literal notranslate"><span class="pre">A</span></code> may not implement <a class="reference internal" href="../reference/datamodel.html#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> at
all.)</li>
<li>Then <code class="docutils literal notranslate"><span class="pre">B</span></code>’s <a class="reference internal" href="../reference/datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> gets a chance. If it accepts
<code class="docutils literal notranslate"><span class="pre">a</span></code>, all is well.</li>
<li>If it falls back to the boilerplate, there are no more possible
methods to try, so this is where the default implementation
should live.</li>
<li>If <code class="docutils literal notranslate"><span class="pre">B</span> <span class="pre">&lt;:</span> <span class="pre">A</span></code>, Python tries <code class="docutils literal notranslate"><span class="pre">B.__radd__</span></code> before
<code class="docutils literal notranslate"><span class="pre">A.__add__</span></code>. This is ok, because it was implemented with
knowledge of <code class="docutils literal notranslate"><span class="pre">A</span></code>, so it can handle those instances before
delegating to <a class="reference internal" href="#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code></a>.</li>
</ol>
</div></blockquote>
<p>If <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">&lt;:</span> <span class="pre">Complex</span></code> and <code class="docutils literal notranslate"><span class="pre">B</span> <span class="pre">&lt;:</span> <span class="pre">Real</span></code> without sharing any other knowledge,
then the appropriate shared operation is the one involving the built
in <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>, and both <a class="reference internal" href="../reference/datamodel.html#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> s land there, so <code class="docutils literal notranslate"><span class="pre">a+b</span>
<span class="pre">==</span> <span class="pre">b+a</span></code>.</p>
<p>Because most of the operations on any given type will be very similar,
it can be useful to define a helper function which generates the
forward and reverse instances of any given operator. For example,
<a class="reference internal" href="fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a> uses:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">_operator_fallbacks</span><span class="p">(</span><span class="n">monomorphic_operator</span><span class="p">,</span> <span class="n">fallback_operator</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">forward</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="p">(</span><span class="nb">int</span><span class="p">,</span> <span class="n">long</span><span class="p">,</span> <span class="n">Fraction</span><span class="p">)):</span>
            <span class="k">return</span> <span class="n">monomorphic_operator</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="nb">float</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">fallback_operator</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="n">b</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="nb">complex</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">fallback_operator</span><span class="p">(</span><span class="nb">complex</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="n">b</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>
    <span class="n">forward</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">=</span> <span class="s1">&#39;__&#39;</span> <span class="o">+</span> <span class="n">fallback_operator</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">+</span> <span class="s1">&#39;__&#39;</span>
    <span class="n">forward</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="n">monomorphic_operator</span><span class="o">.</span><span class="vm">__doc__</span>

    <span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">Rational</span><span class="p">):</span>
            <span class="c1"># Includes ints.</span>
            <span class="k">return</span> <span class="n">monomorphic_operator</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">)</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">numbers</span><span class="o">.</span><span class="n">Real</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">fallback_operator</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">float</span><span class="p">(</span><span class="n">b</span><span class="p">))</span>
        <span class="k">elif</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">numbers</span><span class="o">.</span><span class="n">Complex</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">fallback_operator</span><span class="p">(</span><span class="nb">complex</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">complex</span><span class="p">(</span><span class="n">b</span><span class="p">))</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">NotImplemented</span>
    <span class="n">reverse</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">=</span> <span class="s1">&#39;__r&#39;</span> <span class="o">+</span> <span class="n">fallback_operator</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">+</span> <span class="s1">&#39;__&#39;</span>
    <span class="n">reverse</span><span class="o">.</span><span class="vm">__doc__</span> <span class="o">=</span> <span class="n">monomorphic_operator</span><span class="o">.</span><span class="vm">__doc__</span>

    <span class="k">return</span> <span class="n">forward</span><span class="p">,</span> <span class="n">reverse</span>

<span class="k">def</span> <span class="nf">_add</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;a + b&quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">Fraction</span><span class="p">(</span><span class="n">a</span><span class="o">.</span><span class="n">numerator</span> <span class="o">*</span> <span class="n">b</span><span class="o">.</span><span class="n">denominator</span> <span class="o">+</span>
                    <span class="n">b</span><span class="o">.</span><span class="n">numerator</span> <span class="o">*</span> <span class="n">a</span><span class="o">.</span><span class="n">denominator</span><span class="p">,</span>
                    <span class="n">a</span><span class="o">.</span><span class="n">denominator</span> <span class="o">*</span> <span class="n">b</span><span class="o">.</span><span class="n">denominator</span><span class="p">)</span>

<span class="fm">__add__</span><span class="p">,</span> <span class="fm">__radd__</span> <span class="o">=</span> <span class="n">_operator_fallbacks</span><span class="p">(</span><span class="n">_add</span><span class="p">,</span> <span class="n">operator</span><span class="o">.</span><span class="n">add</span><span class="p">)</span>

<span class="c1"># ...</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a><ul>
<li><a class="reference internal" href="#the-numeric-tower">9.1.1. The numeric tower</a></li>
<li><a class="reference internal" href="#notes-for-type-implementors">9.1.2. Notes for type implementors</a><ul>
<li><a class="reference internal" href="#adding-more-numeric-abcs">9.1.2.1. Adding More Numeric ABCs</a></li>
<li><a class="reference internal" href="#implementing-the-arithmetic-operations">9.1.2.2. Implementing the arithmetic operations</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="numeric.html"
                        title="previous chapter">9. Numeric and Mathematical Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="math.html"
                        title="next chapter">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/numbers.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="math.html" title="9.2. math — Mathematical functions"
             >next</a> |</li>
        <li class="right" >
          <a href="numeric.html" title="9. Numeric and Mathematical Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ji�B�7�7html/library/numeric.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9. Numeric and Mathematical Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.1. numbers — Numeric abstract base classes" href="numbers.html" />
    <link rel="prev" title="8.19. repr — Alternate repr() implementation" href="repr.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/numeric.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="numbers.html" title="9.1. numbers — Numeric abstract base classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="repr.html" title="8.19. repr — Alternate repr() implementation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="numeric-and-mathematical-modules">
<span id="numeric"></span><h1>9. Numeric and Mathematical Modules<a class="headerlink" href="#numeric-and-mathematical-modules" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide numeric and math-related functions
and data types. The <a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module defines an abstract hierarchy of
numeric types. The <a class="reference internal" href="math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> and <a class="reference internal" href="cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> modules contain various
mathematical functions for floating-point and complex numbers. For users more
interested in decimal accuracy than in speed, the <a class="reference internal" href="decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module supports
exact representations of decimal numbers.</p>
<p>The following modules are documented in this chapter:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="numbers.html">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="numbers.html#the-numeric-tower">9.1.1. The numeric tower</a></li>
<li class="toctree-l2"><a class="reference internal" href="numbers.html#notes-for-type-implementors">9.1.2. Notes for type implementors</a><ul>
<li class="toctree-l3"><a class="reference internal" href="numbers.html#adding-more-numeric-abcs">9.1.2.1. Adding More Numeric ABCs</a></li>
<li class="toctree-l3"><a class="reference internal" href="numbers.html#implementing-the-arithmetic-operations">9.1.2.2. Implementing the arithmetic operations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="math.html">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="math.html#number-theoretic-and-representation-functions">9.2.1. Number-theoretic and representation functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#power-and-logarithmic-functions">9.2.2. Power and logarithmic functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#trigonometric-functions">9.2.3. Trigonometric functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#angular-conversion">9.2.4. Angular conversion</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#hyperbolic-functions">9.2.5. Hyperbolic functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#special-functions">9.2.6. Special functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="math.html#constants">9.2.7. Constants</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="cmath.html">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#conversions-to-and-from-polar-coordinates">9.3.1. Conversions to and from polar coordinates</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#power-and-logarithmic-functions">9.3.2. Power and logarithmic functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#trigonometric-functions">9.3.3. Trigonometric functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#hyperbolic-functions">9.3.4. Hyperbolic functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#classification-functions">9.3.5. Classification functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="cmath.html#constants">9.3.6. Constants</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="decimal.html">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a><ul>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#quick-start-tutorial">9.4.1. Quick-start Tutorial</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#decimal-objects">9.4.2. Decimal objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="decimal.html#logical-operands">9.4.2.1. Logical operands</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#context-objects">9.4.3. Context objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#signals">9.4.4. Signals</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#floating-point-notes">9.4.5. Floating Point Notes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="decimal.html#mitigating-round-off-error-with-increased-precision">9.4.5.1. Mitigating round-off error with increased precision</a></li>
<li class="toctree-l3"><a class="reference internal" href="decimal.html#special-values">9.4.5.2. Special values</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#working-with-threads">9.4.6. Working with threads</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#recipes">9.4.7. Recipes</a></li>
<li class="toctree-l2"><a class="reference internal" href="decimal.html#decimal-faq">9.4.8. Decimal FAQ</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="fractions.html">9.5. <code class="docutils literal notranslate"><span class="pre">fractions</span></code> — Rational numbers</a></li>
<li class="toctree-l1"><a class="reference internal" href="random.html">9.6. <code class="docutils literal notranslate"><span class="pre">random</span></code> — Generate pseudo-random numbers</a></li>
<li class="toctree-l1"><a class="reference internal" href="itertools.html">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a><ul>
<li class="toctree-l2"><a class="reference internal" href="itertools.html#itertool-functions">9.7.1. Itertool functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="itertools.html#recipes">9.7.2. Recipes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="functools.html">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="functools.html#partial-objects">9.8.1. <code class="docutils literal notranslate"><span class="pre">partial</span></code> Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="operator.html">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="operator.html#mapping-operators-to-functions">9.9.1. Mapping Operators to Functions</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="repr.html"
                        title="previous chapter">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="numbers.html"
                        title="next chapter">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/numeric.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="numbers.html" title="9.1. numbers — Numeric abstract base classes"
             >next</a> |</li>
        <li class="right" >
          <a href="repr.html" title="8.19. repr — Alternate repr() implementation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��x�m�mhtml/library/operator.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.9. operator — Standard operators as functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10. File and Directory Access" href="filesys.html" />
    <link rel="prev" title="9.8. functools — Higher-order functions and operations on callable objects" href="functools.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/operator.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="filesys.html" title="10. File and Directory Access"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="functools.html" title="9.8. functools — Higher-order functions and operations on callable objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-operator">
<span id="operator-standard-operators-as-functions"></span><h1>9.9. <a class="reference internal" href="#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> — Standard operators as functions<a class="headerlink" href="#module-operator" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module exports a set of efficient functions corresponding to
the intrinsic operators of Python.  For example, <code class="docutils literal notranslate"><span class="pre">operator.add(x,</span> <span class="pre">y)</span></code> is
equivalent to the expression <code class="docutils literal notranslate"><span class="pre">x+y</span></code>.  The function names are those used for
special class methods; variants without leading and trailing <code class="docutils literal notranslate"><span class="pre">__</span></code> are also
provided for convenience.</p>
<p>The functions fall into categories that perform object comparisons, logical
operations, mathematical operations, sequence operations, and abstract type
tests.</p>
<p>The object comparison functions are useful for all objects, and are named after
the rich comparison operators they support:</p>
<dl class="function">
<dt id="operator.lt">
<code class="descclassname">operator.</code><code class="descname">lt</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.lt" title="Permalink to this definition">¶</a></dt>
<dt id="operator.le">
<code class="descclassname">operator.</code><code class="descname">le</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.le" title="Permalink to this definition">¶</a></dt>
<dt id="operator.eq">
<code class="descclassname">operator.</code><code class="descname">eq</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.eq" title="Permalink to this definition">¶</a></dt>
<dt id="operator.ne">
<code class="descclassname">operator.</code><code class="descname">ne</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ne" title="Permalink to this definition">¶</a></dt>
<dt id="operator.ge">
<code class="descclassname">operator.</code><code class="descname">ge</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ge" title="Permalink to this definition">¶</a></dt>
<dt id="operator.gt">
<code class="descclassname">operator.</code><code class="descname">gt</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.gt" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__lt__">
<code class="descclassname">operator.</code><code class="descname">__lt__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__lt__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__le__">
<code class="descclassname">operator.</code><code class="descname">__le__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__le__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__eq__">
<code class="descclassname">operator.</code><code class="descname">__eq__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__eq__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ne__">
<code class="descclassname">operator.</code><code class="descname">__ne__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ne__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ge__">
<code class="descclassname">operator.</code><code class="descname">__ge__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ge__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__gt__">
<code class="descclassname">operator.</code><code class="descname">__gt__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__gt__" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform “rich comparisons” between <em>a</em> and <em>b</em>. Specifically, <code class="docutils literal notranslate"><span class="pre">lt(a,</span> <span class="pre">b)</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span></code>, <code class="docutils literal notranslate"><span class="pre">le(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code>, <code class="docutils literal notranslate"><span class="pre">eq(a,</span>
<span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code>, <code class="docutils literal notranslate"><span class="pre">ne(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">!=</span> <span class="pre">b</span></code>,
<code class="docutils literal notranslate"><span class="pre">gt(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;</span> <span class="pre">b</span></code> and <code class="docutils literal notranslate"><span class="pre">ge(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span>
<span class="pre">&gt;=</span> <span class="pre">b</span></code>.  Note that unlike the built-in <a class="reference internal" href="functions.html#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a>, these functions can
return any value, which may or may not be interpretable as a Boolean value.
See <a class="reference internal" href="../reference/expressions.html#comparisons"><span class="std std-ref">Comparisons</span></a> for more information about rich comparisons.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<p>The logical operations are also generally applicable to all objects, and support
truth tests, identity tests, and boolean operations:</p>
<dl class="function">
<dt id="operator.not_">
<code class="descclassname">operator.</code><code class="descname">not_</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.not_" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__not__">
<code class="descclassname">operator.</code><code class="descname">__not__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__not__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the outcome of <a class="reference internal" href="../reference/expressions.html#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> <em>obj</em>.  (Note that there is no
<a class="reference internal" href="#operator.__not__" title="operator.__not__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__not__()</span></code></a> method for object instances; only the interpreter core defines
this operation.  The result is affected by the <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> methods.)</p>
</dd></dl>

<dl class="function">
<dt id="operator.truth">
<code class="descclassname">operator.</code><code class="descname">truth</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.truth" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>obj</em> is true, and <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise.  This is
equivalent to using the <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> constructor.</p>
</dd></dl>

<dl class="function">
<dt id="operator.is_">
<code class="descclassname">operator.</code><code class="descname">is_</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.is_" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">b</span></code>.  Tests object identity.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.is_not">
<code class="descclassname">operator.</code><code class="descname">is_not</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.is_not" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">b</span></code>.  Tests object identity.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>The mathematical and bitwise operations are the most numerous:</p>
<dl class="function">
<dt id="operator.abs">
<code class="descclassname">operator.</code><code class="descname">abs</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.abs" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__abs__">
<code class="descclassname">operator.</code><code class="descname">__abs__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__abs__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the absolute value of <em>obj</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.add">
<code class="descclassname">operator.</code><code class="descname">add</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.add" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__add__">
<code class="descclassname">operator.</code><code class="descname">__add__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__add__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code>, for <em>a</em> and <em>b</em> numbers.</p>
</dd></dl>

<dl class="function">
<dt id="operator.and_">
<code class="descclassname">operator.</code><code class="descname">and_</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.and_" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__and__">
<code class="descclassname">operator.</code><code class="descname">__and__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__and__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the bitwise and of <em>a</em> and <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.div">
<code class="descclassname">operator.</code><code class="descname">div</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.div" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__div__">
<code class="descclassname">operator.</code><code class="descname">__div__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__div__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></code> when <code class="docutils literal notranslate"><span class="pre">__future__.division</span></code> is not in effect.  This is
also known as “classic” division.</p>
</dd></dl>

<dl class="function">
<dt id="operator.floordiv">
<code class="descclassname">operator.</code><code class="descname">floordiv</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.floordiv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__floordiv__">
<code class="descclassname">operator.</code><code class="descname">__floordiv__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__floordiv__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">//</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.index">
<code class="descclassname">operator.</code><code class="descname">index</code><span class="sig-paren">(</span><em>a</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.index" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__index__">
<code class="descclassname">operator.</code><code class="descname">__index__</code><span class="sig-paren">(</span><em>a</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__index__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>a</em> converted to an integer.  Equivalent to <code class="docutils literal notranslate"><span class="pre">a.__index__()</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.inv">
<code class="descclassname">operator.</code><code class="descname">inv</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.inv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.invert">
<code class="descclassname">operator.</code><code class="descname">invert</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.invert" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__inv__">
<code class="descclassname">operator.</code><code class="descname">__inv__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__inv__" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__invert__">
<code class="descclassname">operator.</code><code class="descname">__invert__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__invert__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the bitwise inverse of the number <em>obj</em>.  This is equivalent to <code class="docutils literal notranslate"><span class="pre">~obj</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0: </span>The names <a class="reference internal" href="#operator.invert" title="operator.invert"><code class="xref py py-func docutils literal notranslate"><span class="pre">invert()</span></code></a> and <a class="reference internal" href="#operator.__invert__" title="operator.__invert__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__invert__()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.lshift">
<code class="descclassname">operator.</code><code class="descname">lshift</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.lshift" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__lshift__">
<code class="descclassname">operator.</code><code class="descname">__lshift__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__lshift__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>a</em> shifted left by <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.mod">
<code class="descclassname">operator.</code><code class="descname">mod</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.mod" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__mod__">
<code class="descclassname">operator.</code><code class="descname">__mod__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__mod__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">%</span> <span class="pre">b</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.mul">
<code class="descclassname">operator.</code><code class="descname">mul</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.mul" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__mul__">
<code class="descclassname">operator.</code><code class="descname">__mul__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__mul__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*</span> <span class="pre">b</span></code>, for <em>a</em> and <em>b</em> numbers.</p>
</dd></dl>

<dl class="function">
<dt id="operator.neg">
<code class="descclassname">operator.</code><code class="descname">neg</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.neg" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__neg__">
<code class="descclassname">operator.</code><code class="descname">__neg__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__neg__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>obj</em> negated (<code class="docutils literal notranslate"><span class="pre">-obj</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="operator.or_">
<code class="descclassname">operator.</code><code class="descname">or_</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.or_" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__or__">
<code class="descclassname">operator.</code><code class="descname">__or__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__or__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the bitwise or of <em>a</em> and <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.pos">
<code class="descclassname">operator.</code><code class="descname">pos</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.pos" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__pos__">
<code class="descclassname">operator.</code><code class="descname">__pos__</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__pos__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>obj</em> positive (<code class="docutils literal notranslate"><span class="pre">+obj</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="operator.pow">
<code class="descclassname">operator.</code><code class="descname">pow</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.pow" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__pow__">
<code class="descclassname">operator.</code><code class="descname">__pow__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__pow__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">**</span> <span class="pre">b</span></code>, for <em>a</em> and <em>b</em> numbers.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.rshift">
<code class="descclassname">operator.</code><code class="descname">rshift</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.rshift" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__rshift__">
<code class="descclassname">operator.</code><code class="descname">__rshift__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__rshift__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>a</em> shifted right by <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.sub">
<code class="descclassname">operator.</code><code class="descname">sub</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.sub" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__sub__">
<code class="descclassname">operator.</code><code class="descname">__sub__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__sub__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">-</span> <span class="pre">b</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.truediv">
<code class="descclassname">operator.</code><code class="descname">truediv</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.truediv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__truediv__">
<code class="descclassname">operator.</code><code class="descname">__truediv__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__truediv__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></code> when <code class="docutils literal notranslate"><span class="pre">__future__.division</span></code> is in effect.  This is also
known as “true” division.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.xor">
<code class="descclassname">operator.</code><code class="descname">xor</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.xor" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__xor__">
<code class="descclassname">operator.</code><code class="descname">__xor__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__xor__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the bitwise exclusive or of <em>a</em> and <em>b</em>.</p>
</dd></dl>

<p>Operations which work with sequences (some of them with mappings too) include:</p>
<dl class="function">
<dt id="operator.concat">
<code class="descclassname">operator.</code><code class="descname">concat</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.concat" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__concat__">
<code class="descclassname">operator.</code><code class="descname">__concat__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__concat__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code> for <em>a</em> and <em>b</em> sequences.</p>
</dd></dl>

<dl class="function">
<dt id="operator.contains">
<code class="descclassname">operator.</code><code class="descname">contains</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.contains" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__contains__">
<code class="descclassname">operator.</code><code class="descname">__contains__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the outcome of the test <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">in</span> <span class="pre">a</span></code>. Note the reversed operands.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0: </span>The name <a class="reference internal" href="#operator.__contains__" title="operator.__contains__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__contains__()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.countOf">
<code class="descclassname">operator.</code><code class="descname">countOf</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.countOf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of occurrences of <em>b</em> in <em>a</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.delitem">
<code class="descclassname">operator.</code><code class="descname">delitem</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.delitem" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__delitem__">
<code class="descclassname">operator.</code><code class="descname">__delitem__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the value of <em>a</em> at index <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.delslice">
<code class="descclassname">operator.</code><code class="descname">delslice</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.delslice" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__delslice__">
<code class="descclassname">operator.</code><code class="descname">__delslice__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__delslice__" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the slice of <em>a</em> from index <em>b</em> to index <em>c-1</em>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is removed in Python 3.x.  Use <a class="reference internal" href="#operator.delitem" title="operator.delitem"><code class="xref py py-func docutils literal notranslate"><span class="pre">delitem()</span></code></a> with a slice
index.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.getitem">
<code class="descclassname">operator.</code><code class="descname">getitem</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.getitem" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__getitem__">
<code class="descclassname">operator.</code><code class="descname">__getitem__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of <em>a</em> at index <em>b</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.getslice">
<code class="descclassname">operator.</code><code class="descname">getslice</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.getslice" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__getslice__">
<code class="descclassname">operator.</code><code class="descname">__getslice__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__getslice__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the slice of <em>a</em> from index <em>b</em> to index <em>c-1</em>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is removed in Python 3.x.  Use <a class="reference internal" href="#operator.getitem" title="operator.getitem"><code class="xref py py-func docutils literal notranslate"><span class="pre">getitem()</span></code></a> with a slice
index.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.indexOf">
<code class="descclassname">operator.</code><code class="descname">indexOf</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.indexOf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the index of the first of occurrence of <em>b</em> in <em>a</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.repeat">
<code class="descclassname">operator.</code><code class="descname">repeat</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.repeat" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__repeat__">
<code class="descclassname">operator.</code><code class="descname">__repeat__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__repeat__" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <a class="reference internal" href="#operator.__mul__" title="operator.__mul__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__mul__()</span></code></a> instead.</p>
</div>
<p>Return <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*</span> <span class="pre">b</span></code> where <em>a</em> is a sequence and <em>b</em> is an integer.</p>
</dd></dl>

<dl class="function">
<dt id="operator.sequenceIncludes">
<code class="descclassname">operator.</code><code class="descname">sequenceIncludes</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.sequenceIncludes" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use <a class="reference internal" href="#operator.contains" title="operator.contains"><code class="xref py py-func docutils literal notranslate"><span class="pre">contains()</span></code></a> instead.</p>
</div>
<p>Alias for <a class="reference internal" href="#operator.contains" title="operator.contains"><code class="xref py py-func docutils literal notranslate"><span class="pre">contains()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.setitem">
<code class="descclassname">operator.</code><code class="descname">setitem</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.setitem" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__setitem__">
<code class="descclassname">operator.</code><code class="descname">__setitem__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the value of <em>a</em> at index <em>b</em> to <em>c</em>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.setslice">
<code class="descclassname">operator.</code><code class="descname">setslice</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em>, <em>v</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.setslice" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__setslice__">
<code class="descclassname">operator.</code><code class="descname">__setslice__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em>, <em>c</em>, <em>v</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__setslice__" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the slice of <em>a</em> from index <em>b</em> to index <em>c-1</em> to the sequence <em>v</em>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is removed in Python 3.x.  Use <a class="reference internal" href="#operator.setitem" title="operator.setitem"><code class="xref py py-func docutils literal notranslate"><span class="pre">setitem()</span></code></a> with a slice
index.</p>
</div>
</dd></dl>

<p>Example use of operator functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Elementwise multiplication</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">40</span><span class="p">])</span>
<span class="go">[0, 20, 60, 120]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Dot product</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">mul</span><span class="p">,</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">40</span><span class="p">]))</span>
<span class="go">200</span>
</pre></div>
</div>
<p>Many operations have an “in-place” version.  The following functions provide a
more primitive access to in-place operators than the usual syntax does; for
example, the <a class="reference internal" href="../glossary.html#term-statement"><span class="xref std std-term">statement</span></a> <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">operator.iadd(x,</span> <span class="pre">y)</span></code>.  Another way to put it is to say that
<code class="docutils literal notranslate"><span class="pre">z</span> <span class="pre">=</span> <span class="pre">operator.iadd(x,</span> <span class="pre">y)</span></code> is equivalent to the compound statement
<code class="docutils literal notranslate"><span class="pre">z</span> <span class="pre">=</span> <span class="pre">x;</span> <span class="pre">z</span> <span class="pre">+=</span> <span class="pre">y</span></code>.</p>
<dl class="function">
<dt id="operator.iadd">
<code class="descclassname">operator.</code><code class="descname">iadd</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.iadd" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__iadd__">
<code class="descclassname">operator.</code><code class="descname">__iadd__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__iadd__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">iadd(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.iand">
<code class="descclassname">operator.</code><code class="descname">iand</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.iand" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__iand__">
<code class="descclassname">operator.</code><code class="descname">__iand__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__iand__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">iand(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&amp;=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.iconcat">
<code class="descclassname">operator.</code><code class="descname">iconcat</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.iconcat" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__iconcat__">
<code class="descclassname">operator.</code><code class="descname">__iconcat__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__iconcat__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">iconcat(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+=</span> <span class="pre">b</span></code> for <em>a</em> and <em>b</em> sequences.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.idiv">
<code class="descclassname">operator.</code><code class="descname">idiv</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.idiv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__idiv__">
<code class="descclassname">operator.</code><code class="descname">__idiv__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__idiv__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">idiv(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/=</span> <span class="pre">b</span></code> when <code class="docutils literal notranslate"><span class="pre">__future__.division</span></code> is
not in effect.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.ifloordiv">
<code class="descclassname">operator.</code><code class="descname">ifloordiv</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ifloordiv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ifloordiv__">
<code class="descclassname">operator.</code><code class="descname">__ifloordiv__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ifloordiv__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">ifloordiv(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">//=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.ilshift">
<code class="descclassname">operator.</code><code class="descname">ilshift</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ilshift" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ilshift__">
<code class="descclassname">operator.</code><code class="descname">__ilshift__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ilshift__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">ilshift(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;&lt;=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.imod">
<code class="descclassname">operator.</code><code class="descname">imod</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.imod" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__imod__">
<code class="descclassname">operator.</code><code class="descname">__imod__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__imod__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">imod(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">%=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.imul">
<code class="descclassname">operator.</code><code class="descname">imul</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.imul" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__imul__">
<code class="descclassname">operator.</code><code class="descname">__imul__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__imul__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">imul(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.ior">
<code class="descclassname">operator.</code><code class="descname">ior</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ior" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ior__">
<code class="descclassname">operator.</code><code class="descname">__ior__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ior__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">ior(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">|=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.ipow">
<code class="descclassname">operator.</code><code class="descname">ipow</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ipow" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ipow__">
<code class="descclassname">operator.</code><code class="descname">__ipow__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ipow__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">ipow(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">**=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.irepeat">
<code class="descclassname">operator.</code><code class="descname">irepeat</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.irepeat" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__irepeat__">
<code class="descclassname">operator.</code><code class="descname">__irepeat__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__irepeat__" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <a class="reference internal" href="#operator.__imul__" title="operator.__imul__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__imul__()</span></code></a> instead.</p>
</div>
<p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">irepeat(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*=</span> <span class="pre">b</span></code> where <em>a</em> is a sequence and
<em>b</em> is an integer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.irshift">
<code class="descclassname">operator.</code><code class="descname">irshift</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.irshift" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__irshift__">
<code class="descclassname">operator.</code><code class="descname">__irshift__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__irshift__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">irshift(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;&gt;=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.isub">
<code class="descclassname">operator.</code><code class="descname">isub</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.isub" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__isub__">
<code class="descclassname">operator.</code><code class="descname">__isub__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__isub__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">isub(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">-=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.itruediv">
<code class="descclassname">operator.</code><code class="descname">itruediv</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.itruediv" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__itruediv__">
<code class="descclassname">operator.</code><code class="descname">__itruediv__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__itruediv__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">itruediv(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/=</span> <span class="pre">b</span></code> when <code class="docutils literal notranslate"><span class="pre">__future__.division</span></code>
is in effect.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.ixor">
<code class="descclassname">operator.</code><code class="descname">ixor</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.ixor" title="Permalink to this definition">¶</a></dt>
<dt id="operator.__ixor__">
<code class="descclassname">operator.</code><code class="descname">__ixor__</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.__ixor__" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">ixor(a,</span> <span class="pre">b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">^=</span> <span class="pre">b</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module also defines a few predicates to test the type of
objects; however, these are not all reliable.  It is preferable to test
abstract base classes instead (see <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> and
<a class="reference internal" href="numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> for details).</p>
<dl class="function">
<dt id="operator.isCallable">
<code class="descclassname">operator.</code><code class="descname">isCallable</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.isCallable" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">collections.Callable)</span></code> instead.</p>
</div>
<p>Returns true if the object <em>obj</em> can be called like a function, otherwise it
returns false.  True is returned for functions, bound and unbound methods, class
objects, and instance objects which support the <a class="reference internal" href="../reference/datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method.</p>
</dd></dl>

<dl class="function">
<dt id="operator.isMappingType">
<code class="descclassname">operator.</code><code class="descname">isMappingType</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.isMappingType" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">collections.Mapping)</span></code> instead.</p>
</div>
<p>Returns true if the object <em>obj</em> supports the mapping interface. This is true for
dictionaries and all instance objects defining <a class="reference internal" href="#operator.__getitem__" title="operator.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="operator.isNumberType">
<code class="descclassname">operator.</code><code class="descname">isNumberType</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.isNumberType" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">numbers.Number)</span></code> instead.</p>
</div>
<p>Returns true if the object <em>obj</em> represents a number.  This is true for all
numeric types implemented in C.</p>
</dd></dl>

<dl class="function">
<dt id="operator.isSequenceType">
<code class="descclassname">operator.</code><code class="descname">isSequenceType</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.isSequenceType" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">collections.Sequence)</span></code> instead.</p>
</div>
<p>Returns true if the object <em>obj</em> supports the sequence protocol. This returns true
for all objects which define sequence methods in C, and for all instance objects
defining <a class="reference internal" href="#operator.__getitem__" title="operator.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module also defines tools for generalized attribute and item
lookups.  These are useful for making fast field extractors as arguments for
<a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>, <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>, <a class="reference internal" href="itertools.html#itertools.groupby" title="itertools.groupby"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itertools.groupby()</span></code></a>, or other functions that
expect a function argument.</p>
<dl class="function">
<dt id="operator.attrgetter">
<code class="descclassname">operator.</code><code class="descname">attrgetter</code><span class="sig-paren">(</span><em>attr</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.attrgetter" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">operator.</code><code class="descname">attrgetter</code><span class="sig-paren">(</span><em>*attrs</em><span class="sig-paren">)</span></dt>
<dd><p>Return a callable object that fetches <em>attr</em> from its operand.
If more than one attribute is requested, returns a tuple of attributes.
The attribute names can also contain dots. For example:</p>
<ul class="simple">
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">attrgetter('name')</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(b)</span></code> returns <code class="docutils literal notranslate"><span class="pre">b.name</span></code>.</li>
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">attrgetter('name',</span> <span class="pre">'date')</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(b)</span></code> returns
<code class="docutils literal notranslate"><span class="pre">(b.name,</span> <span class="pre">b.date)</span></code>.</li>
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">attrgetter('name.first',</span> <span class="pre">'name.last')</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(b)</span></code>
returns <code class="docutils literal notranslate"><span class="pre">(b.name.first,</span> <span class="pre">b.name.last)</span></code>.</li>
</ul>
<p>Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">attrgetter</span><span class="p">(</span><span class="o">*</span><span class="n">items</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">items</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">attr</span> <span class="o">=</span> <span class="n">items</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">resolve_attr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">resolve_attr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">)</span> <span class="k">for</span> <span class="n">attr</span> <span class="ow">in</span> <span class="n">items</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">g</span>

<span class="k">def</span> <span class="nf">resolve_attr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">attr</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;.&quot;</span><span class="p">):</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">obj</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added support for multiple attributes.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added support for dotted attributes.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.itemgetter">
<code class="descclassname">operator.</code><code class="descname">itemgetter</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#operator.itemgetter" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">operator.</code><code class="descname">itemgetter</code><span class="sig-paren">(</span><em>*items</em><span class="sig-paren">)</span></dt>
<dd><p>Return a callable object that fetches <em>item</em> from its operand using the
operand’s <a class="reference internal" href="#operator.__getitem__" title="operator.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.  If multiple items are specified,
returns a tuple of lookup values.  For example:</p>
<ul class="simple">
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">itemgetter(2)</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(r)</span></code> returns <code class="docutils literal notranslate"><span class="pre">r[2]</span></code>.</li>
<li>After <code class="docutils literal notranslate"><span class="pre">g</span> <span class="pre">=</span> <span class="pre">itemgetter(2,</span> <span class="pre">5,</span> <span class="pre">3)</span></code>, the call <code class="docutils literal notranslate"><span class="pre">g(r)</span></code> returns
<code class="docutils literal notranslate"><span class="pre">(r[2],</span> <span class="pre">r[5],</span> <span class="pre">r[3])</span></code>.</li>
</ul>
<p>Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">itemgetter</span><span class="p">(</span><span class="o">*</span><span class="n">items</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">items</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">items</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">obj</span><span class="p">[</span><span class="n">item</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">obj</span><span class="p">[</span><span class="n">item</span><span class="p">]</span> <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">items</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">g</span>
</pre></div>
</div>
<p>The items can be any type accepted by the operand’s <a class="reference internal" href="#operator.__getitem__" title="operator.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
method.  Dictionaries accept any hashable value.  Lists, tuples, and
strings accept an index or a slice:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">)(</span><span class="s1">&#39;ABCDEFG&#39;</span><span class="p">)</span>
<span class="go">&#39;B&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">5</span><span class="p">)(</span><span class="s1">&#39;ABCDEFG&#39;</span><span class="p">)</span>
<span class="go">(&#39;B&#39;, &#39;D&#39;, &#39;F&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">itemgetter</span><span class="p">(</span><span class="nb">slice</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="kc">None</span><span class="p">))(</span><span class="s1">&#39;ABCDEFG&#39;</span><span class="p">)</span>
<span class="go">&#39;CDEFG&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added support for multiple item extraction.</p>
</div>
<p>Example of using <a class="reference internal" href="#operator.itemgetter" title="operator.itemgetter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itemgetter()</span></code></a> to retrieve specific fields from a
tuple record:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">inventory</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;banana&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcount</span> <span class="o">=</span> <span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">getcount</span><span class="p">,</span> <span class="n">inventory</span><span class="p">)</span>
<span class="go">[3, 2, 5, 1]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">inventory</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">getcount</span><span class="p">)</span>
<span class="go">[(&#39;orange&#39;, 1), (&#39;banana&#39;, 2), (&#39;apple&#39;, 3), (&#39;pear&#39;, 5)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="operator.methodcaller">
<code class="descclassname">operator.</code><code class="descname">methodcaller</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#operator.methodcaller" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a callable object that calls the method <em>name</em> on its operand.  If
additional arguments and/or keyword arguments are given, they will be given
to the method as well.  For example:</p>
<ul class="simple">
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">methodcaller('name')</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(b)</span></code> returns <code class="docutils literal notranslate"><span class="pre">b.name()</span></code>.</li>
<li>After <code class="docutils literal notranslate"><span class="pre">f</span> <span class="pre">=</span> <span class="pre">methodcaller('name',</span> <span class="pre">'foo',</span> <span class="pre">bar=1)</span></code>, the call <code class="docutils literal notranslate"><span class="pre">f(b)</span></code>
returns <code class="docutils literal notranslate"><span class="pre">b.name('foo',</span> <span class="pre">bar=1)</span></code>.</li>
</ul>
<p>Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">methodcaller</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">caller</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
        <span class="k">return</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">name</span><span class="p">)(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">caller</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<div class="section" id="mapping-operators-to-functions">
<span id="operator-map"></span><h2>9.9.1. Mapping Operators to Functions<a class="headerlink" href="#mapping-operators-to-functions" title="Permalink to this headline">¶</a></h2>
<p>This table shows how abstract operations correspond to operator symbols in the
Python syntax and the functions in the <a class="reference internal" href="#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module.</p>
<table border="1" class="docutils">
<colgroup>
<col width="26%" />
<col width="29%" />
<col width="45%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Syntax</th>
<th class="head">Function</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Addition</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">add(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Concatenation</td>
<td><code class="docutils literal notranslate"><span class="pre">seq1</span> <span class="pre">+</span> <span class="pre">seq2</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">concat(seq1,</span> <span class="pre">seq2)</span></code></td>
</tr>
<tr class="row-even"><td>Containment Test</td>
<td><code class="docutils literal notranslate"><span class="pre">obj</span> <span class="pre">in</span> <span class="pre">seq</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">contains(seq,</span> <span class="pre">obj)</span></code></td>
</tr>
<tr class="row-odd"><td>Division</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">div(a,</span> <span class="pre">b)</span></code> (without
<code class="docutils literal notranslate"><span class="pre">__future__.division</span></code>)</td>
</tr>
<tr class="row-even"><td>Division</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">/</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">truediv(a,</span> <span class="pre">b)</span></code> (with
<code class="docutils literal notranslate"><span class="pre">__future__.division</span></code>)</td>
</tr>
<tr class="row-odd"><td>Division</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">//</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">floordiv(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Bitwise And</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&amp;</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">and_(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Bitwise Exclusive Or</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">^</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">xor(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Bitwise Inversion</td>
<td><code class="docutils literal notranslate"><span class="pre">~</span> <span class="pre">a</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">invert(a)</span></code></td>
</tr>
<tr class="row-odd"><td>Bitwise Or</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">|</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">or_(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Exponentiation</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">**</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">pow(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Identity</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">is_(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Identity</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">is_not(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Indexed Assignment</td>
<td><code class="docutils literal notranslate"><span class="pre">obj[k]</span> <span class="pre">=</span> <span class="pre">v</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">setitem(obj,</span> <span class="pre">k,</span> <span class="pre">v)</span></code></td>
</tr>
<tr class="row-even"><td>Indexed Deletion</td>
<td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">obj[k]</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">delitem(obj,</span> <span class="pre">k)</span></code></td>
</tr>
<tr class="row-odd"><td>Indexing</td>
<td><code class="docutils literal notranslate"><span class="pre">obj[k]</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">getitem(obj,</span> <span class="pre">k)</span></code></td>
</tr>
<tr class="row-even"><td>Left Shift</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;&lt;</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">lshift(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Modulo</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">%</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">mod(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Multiplication</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">mul(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Negation (Arithmetic)</td>
<td><code class="docutils literal notranslate"><span class="pre">-</span> <span class="pre">a</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">neg(a)</span></code></td>
</tr>
<tr class="row-even"><td>Negation (Logical)</td>
<td><code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">a</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">not_(a)</span></code></td>
</tr>
<tr class="row-odd"><td>Positive</td>
<td><code class="docutils literal notranslate"><span class="pre">+</span> <span class="pre">a</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">pos(a)</span></code></td>
</tr>
<tr class="row-even"><td>Right Shift</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;&gt;</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">rshift(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Sequence Repetition</td>
<td><code class="docutils literal notranslate"><span class="pre">seq</span> <span class="pre">*</span> <span class="pre">i</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">repeat(seq,</span> <span class="pre">i)</span></code></td>
</tr>
<tr class="row-even"><td>Slice Assignment</td>
<td><code class="docutils literal notranslate"><span class="pre">seq[i:j]</span> <span class="pre">=</span> <span class="pre">values</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">setitem(seq,</span> <span class="pre">slice(i,</span> <span class="pre">j),</span> <span class="pre">values)</span></code></td>
</tr>
<tr class="row-odd"><td>Slice Deletion</td>
<td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">seq[i:j]</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">delitem(seq,</span> <span class="pre">slice(i,</span> <span class="pre">j))</span></code></td>
</tr>
<tr class="row-even"><td>Slicing</td>
<td><code class="docutils literal notranslate"><span class="pre">seq[i:j]</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">getitem(seq,</span> <span class="pre">slice(i,</span> <span class="pre">j))</span></code></td>
</tr>
<tr class="row-odd"><td>String Formatting</td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">%</span> <span class="pre">obj</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">mod(s,</span> <span class="pre">obj)</span></code></td>
</tr>
<tr class="row-even"><td>Subtraction</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">-</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">sub(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Truth Test</td>
<td><code class="docutils literal notranslate"><span class="pre">obj</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">truth(obj)</span></code></td>
</tr>
<tr class="row-even"><td>Ordering</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">lt(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Ordering</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">le(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Equality</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">eq(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Difference</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">!=</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">ne(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-even"><td>Ordering</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;=</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">ge(a,</span> <span class="pre">b)</span></code></td>
</tr>
<tr class="row-odd"><td>Ordering</td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;</span> <span class="pre">b</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">gt(a,</span> <span class="pre">b)</span></code></td>
</tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a><ul>
<li><a class="reference internal" href="#mapping-operators-to-functions">9.9.1. Mapping Operators to Functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="functools.html"
                        title="previous chapter">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="filesys.html"
                        title="next chapter">10. File and Directory Access</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/operator.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="filesys.html" title="10. File and Directory Access"
             >next</a> |</li>
        <li class="right" >
          <a href="functools.html" title="9.8. functools — Higher-order functions and operations on callable objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Gi����html/library/optparse.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.5. optparse — Parser for command line options &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.6. getopt — C-style parser for command line options" href="getopt.html" />
    <link rel="prev" title="15.4. argparse — Parser for command-line options, arguments and sub-commands" href="argparse.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/optparse.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="15.6. getopt — C-style parser for command line options"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="15.4. argparse — Parser for command-line options, arguments and sub-commands"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-optparse">
<span id="optparse-parser-for-command-line-options"></span><h1>15.5. <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> — Parser for command line options<a class="headerlink" href="#module-optparse" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>The <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module is deprecated and will not be developed further;
development will continue with the <a class="reference internal" href="argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/optparse.py">Lib/optparse.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> is a more convenient, flexible, and powerful library for parsing
command-line options than the old <a class="reference internal" href="getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> uses a
more declarative style of command-line parsing: you create an instance of
<a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a>, populate it with options, and parse the command
line. <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> allows users to specify options in the conventional
GNU/POSIX syntax, and additionally generates usage and help messages for you.</p>
<p>Here’s an example of using <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> in a simple script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>
<span class="o">...</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;write report to FILE&quot;</span><span class="p">,</span> <span class="n">metavar</span><span class="o">=</span><span class="s2">&quot;FILE&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;don&#39;t print status messages to stdout&quot;</span><span class="p">)</span>

<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>With these few lines of code, users of your script can now do the “usual thing”
on the command-line, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">--</span><span class="n">file</span><span class="o">=</span><span class="n">outfile</span> <span class="o">-</span><span class="n">q</span>
</pre></div>
</div>
<p>As it parses the command line, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> sets attributes of the
<code class="docutils literal notranslate"><span class="pre">options</span></code> object returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> based on user-supplied
command-line values.  When <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> returns from parsing this command
line, <code class="docutils literal notranslate"><span class="pre">options.filename</span></code> will be <code class="docutils literal notranslate"><span class="pre">&quot;outfile&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">options.verbose</span></code> will be
<code class="docutils literal notranslate"><span class="pre">False</span></code>.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> supports both long and short options, allows short
options to be merged together, and allows options to be associated with their
arguments in a variety of ways.  Thus, the following command lines are all
equivalent to the above example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">-</span><span class="n">f</span> <span class="n">outfile</span> <span class="o">--</span><span class="n">quiet</span>
<span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">--</span><span class="n">quiet</span> <span class="o">--</span><span class="n">file</span> <span class="n">outfile</span>
<span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">-</span><span class="n">q</span> <span class="o">-</span><span class="n">foutfile</span>
<span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">-</span><span class="n">qfoutfile</span>
</pre></div>
</div>
<p>Additionally, users can run one of</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">-</span><span class="n">h</span>
<span class="o">&lt;</span><span class="n">yourscript</span><span class="o">&gt;</span> <span class="o">--</span><span class="n">help</span>
</pre></div>
</div>
<p>and <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will print out a brief summary of your script’s options:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: &lt;yourscript&gt; [options]

Options:
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  write report to FILE
  -q, --quiet           don&#39;t print status messages to stdout
</pre></div>
</div>
<p>where the value of <em>yourscript</em> is determined at runtime (normally from
<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>).</p>
<div class="section" id="background">
<span id="optparse-background"></span><h2>15.5.1. Background<a class="headerlink" href="#background" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> was explicitly designed to encourage the creation of programs
with straightforward, conventional command-line interfaces.  To that end, it
supports only the most common command-line syntax and semantics conventionally
used under Unix.  If you are unfamiliar with these conventions, read this
section to acquaint yourself with them.</p>
<div class="section" id="terminology">
<span id="optparse-terminology"></span><h3>15.5.1.1. Terminology<a class="headerlink" href="#terminology" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>argument</dt>
<dd><p class="first">a string entered on the command-line, and passed by the shell to <code class="docutils literal notranslate"><span class="pre">execl()</span></code>
or <code class="docutils literal notranslate"><span class="pre">execv()</span></code>.  In Python, arguments are elements of <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>
(<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is the name of the program being executed).  Unix shells
also use the term “word”.</p>
<p class="last">It is occasionally desirable to substitute an argument list other than
<code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>, so you should read “argument” as “an element of
<code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>, or of some other list provided as a substitute for
<code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>”.</p>
</dd>
<dt>option</dt>
<dd><p class="first">an argument used to supply extra information to guide or customize the
execution of a program.  There are many different syntaxes for options; the
traditional Unix syntax is a hyphen (“-“) followed by a single letter,
e.g. <code class="docutils literal notranslate"><span class="pre">-x</span></code> or <code class="docutils literal notranslate"><span class="pre">-F</span></code>.  Also, traditional Unix syntax allows multiple
options to be merged into a single argument, e.g. <code class="docutils literal notranslate"><span class="pre">-x</span> <span class="pre">-F</span></code> is equivalent
to <code class="docutils literal notranslate"><span class="pre">-xF</span></code>.  The GNU project introduced <code class="docutils literal notranslate"><span class="pre">--</span></code> followed by a series of
hyphen-separated words, e.g. <code class="docutils literal notranslate"><span class="pre">--file</span></code> or <code class="docutils literal notranslate"><span class="pre">--dry-run</span></code>.  These are the
only two option syntaxes provided by <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>.</p>
<p>Some other option syntaxes that the world has seen include:</p>
<ul class="simple">
<li>a hyphen followed by a few letters, e.g. <code class="docutils literal notranslate"><span class="pre">-pf</span></code> (this is <em>not</em> the same
as multiple options merged into a single argument)</li>
<li>a hyphen followed by a whole word, e.g. <code class="docutils literal notranslate"><span class="pre">-file</span></code> (this is technically
equivalent to the previous syntax, but they aren’t usually seen in the same
program)</li>
<li>a plus sign followed by a single letter, or a few letters, or a word, e.g.
<code class="docutils literal notranslate"><span class="pre">+f</span></code>, <code class="docutils literal notranslate"><span class="pre">+rgb</span></code></li>
<li>a slash followed by a letter, or a few letters, or a word, e.g. <code class="docutils literal notranslate"><span class="pre">/f</span></code>,
<code class="docutils literal notranslate"><span class="pre">/file</span></code></li>
</ul>
<p class="last">These option syntaxes are not supported by <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>, and they never
will be.  This is deliberate: the first three are non-standard on any
environment, and the last only makes sense if you’re exclusively targeting
VMS, MS-DOS, and/or Windows.</p>
</dd>
<dt>option argument</dt>
<dd><p class="first">an argument that follows an option, is closely associated with that option,
and is consumed from the argument list when that option is. With
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>, option arguments may either be in a separate argument from
their option:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>-f foo
--file foo
</pre></div>
</div>
<p>or included in the same argument:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>-ffoo
--file=foo
</pre></div>
</div>
<p class="last">Typically, a given option either takes an argument or it doesn’t. Lots of
people want an “optional option arguments” feature, meaning that some options
will take an argument if they see it, and won’t if they don’t.  This is
somewhat controversial, because it makes parsing ambiguous: if <code class="docutils literal notranslate"><span class="pre">-a</span></code> takes
an optional argument and <code class="docutils literal notranslate"><span class="pre">-b</span></code> is another option entirely, how do we
interpret <code class="docutils literal notranslate"><span class="pre">-ab</span></code>?  Because of this ambiguity, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> does not
support this feature.</p>
</dd>
<dt>positional argument</dt>
<dd>something leftover in the argument list after options have been parsed, i.e.
after options and their arguments have been parsed and removed from the
argument list.</dd>
<dt>required option</dt>
<dd>an option that must be supplied on the command-line; note that the phrase
“required option” is self-contradictory in English.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> doesn’t
prevent you from implementing required options, but doesn’t give you much
help at it either.</dd>
</dl>
<p>For example, consider this hypothetical command-line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">prog</span> <span class="o">-</span><span class="n">v</span> <span class="o">--</span><span class="n">report</span> <span class="n">report</span><span class="o">.</span><span class="n">txt</span> <span class="n">foo</span> <span class="n">bar</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">-v</span></code> and <code class="docutils literal notranslate"><span class="pre">--report</span></code> are both options.  Assuming that <code class="docutils literal notranslate"><span class="pre">--report</span></code>
takes one argument, <code class="docutils literal notranslate"><span class="pre">report.txt</span></code> is an option argument.  <code class="docutils literal notranslate"><span class="pre">foo</span></code> and
<code class="docutils literal notranslate"><span class="pre">bar</span></code> are positional arguments.</p>
</div>
<div class="section" id="what-are-options-for">
<span id="optparse-what-options-for"></span><h3>15.5.1.2. What are options for?<a class="headerlink" href="#what-are-options-for" title="Permalink to this headline">¶</a></h3>
<p>Options are used to provide extra information to tune or customize the execution
of a program.  In case it wasn’t clear, options are usually <em>optional</em>.  A
program should be able to run just fine with no options whatsoever.  (Pick a
random program from the Unix or GNU toolsets.  Can it run without any options at
all and still make sense?  The main exceptions are <code class="docutils literal notranslate"><span class="pre">find</span></code>, <code class="docutils literal notranslate"><span class="pre">tar</span></code>, and
<code class="docutils literal notranslate"><span class="pre">dd</span></code>—all of which are mutant oddballs that have been rightly criticized
for their non-standard syntax and confusing interfaces.)</p>
<p>Lots of people want their programs to have “required options”.  Think about it.
If it’s required, then it’s <em>not optional</em>!  If there is a piece of information
that your program absolutely requires in order to run successfully, that’s what
positional arguments are for.</p>
<p>As an example of good command-line interface design, consider the humble <code class="docutils literal notranslate"><span class="pre">cp</span></code>
utility, for copying files.  It doesn’t make much sense to try to copy files
without supplying a destination and at least one source. Hence, <code class="docutils literal notranslate"><span class="pre">cp</span></code> fails if
you run it with no arguments.  However, it has a flexible, useful syntax that
does not require any options at all:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">cp</span> <span class="n">SOURCE</span> <span class="n">DEST</span>
<span class="n">cp</span> <span class="n">SOURCE</span> <span class="o">...</span> <span class="n">DEST</span><span class="o">-</span><span class="n">DIR</span>
</pre></div>
</div>
<p>You can get pretty far with just that.  Most <code class="docutils literal notranslate"><span class="pre">cp</span></code> implementations provide a
bunch of options to tweak exactly how the files are copied: you can preserve
mode and modification time, avoid following symlinks, ask before clobbering
existing files, etc.  But none of this distracts from the core mission of
<code class="docutils literal notranslate"><span class="pre">cp</span></code>, which is to copy either one file to another, or several files to another
directory.</p>
</div>
<div class="section" id="what-are-positional-arguments-for">
<span id="optparse-what-positional-arguments-for"></span><h3>15.5.1.3. What are positional arguments for?<a class="headerlink" href="#what-are-positional-arguments-for" title="Permalink to this headline">¶</a></h3>
<p>Positional arguments are for those pieces of information that your program
absolutely, positively requires to run.</p>
<p>A good user interface should have as few absolute requirements as possible.  If
your program requires 17 distinct pieces of information in order to run
successfully, it doesn’t much matter <em>how</em> you get that information from the
user—most people will give up and walk away before they successfully run the
program.  This applies whether the user interface is a command-line, a
configuration file, or a GUI: if you make that many demands on your users, most
of them will simply give up.</p>
<p>In short, try to minimize the amount of information that users are absolutely
required to supply—use sensible defaults whenever possible.  Of course, you
also want to make your programs reasonably flexible.  That’s what options are
for.  Again, it doesn’t matter if they are entries in a config file, widgets in
the “Preferences” dialog of a GUI, or command-line options—the more options
you implement, the more flexible your program is, and the more complicated its
implementation becomes.  Too much flexibility has drawbacks as well, of course;
too many options can overwhelm users and make your code much harder to maintain.</p>
</div>
</div>
<div class="section" id="tutorial">
<span id="optparse-tutorial"></span><h2>15.5.2. Tutorial<a class="headerlink" href="#tutorial" title="Permalink to this headline">¶</a></h2>
<p>While <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> is quite flexible and powerful, it’s also straightforward
to use in most cases.  This section covers the code patterns that are common to
any <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>-based program.</p>
<p>First, you need to import the OptionParser class; then, early in the main
program, create an OptionParser instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>
<span class="o">...</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
</pre></div>
</div>
<p>Then you can start defining options.  The basic syntax is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="n">opt_str</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span>
                  <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>Each option has one or more option strings, such as <code class="docutils literal notranslate"><span class="pre">-f</span></code> or <code class="docutils literal notranslate"><span class="pre">--file</span></code>,
and several option attributes that tell <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> what to expect and what
to do when it encounters that option on the command line.</p>
<p>Typically, each option will have one short option string and one long option
string, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>You’re free to define as many short option strings and as many long option
strings as you like (including zero), as long as there is at least one option
string overall.</p>
<p>The option strings passed to <a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.add_option()</span></code></a> are effectively
labels for the
option defined by that call.  For brevity, we will frequently refer to
<em>encountering an option</em> on the command line; in reality, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
encounters <em>option strings</em> and looks up options from them.</p>
<p>Once all of your options are defined, instruct <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to parse your
program’s command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>(If you like, you can pass a custom argument list to <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code>, but
that’s rarely necessary: by default it uses <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>.)</p>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> returns two values:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">options</span></code>, an object containing values for all of your options—e.g. if
<code class="docutils literal notranslate"><span class="pre">--file</span></code> takes a single string argument, then <code class="docutils literal notranslate"><span class="pre">options.file</span></code> will be the
filename supplied by the user, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the user did not supply that
option</li>
<li><code class="docutils literal notranslate"><span class="pre">args</span></code>, the list of positional arguments leftover after parsing options</li>
</ul>
<p>This tutorial section only covers the four most important option attributes:
<a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a>, <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>, <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>
(destination), and <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a>. Of these, <a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a> is the
most fundamental.</p>
<div class="section" id="understanding-option-actions">
<span id="optparse-understanding-option-actions"></span><h3>15.5.2.1. Understanding option actions<a class="headerlink" href="#understanding-option-actions" title="Permalink to this headline">¶</a></h3>
<p>Actions tell <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> what to do when it encounters an option on the
command line.  There is a fixed set of actions hard-coded into <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>;
adding new actions is an advanced topic covered in section
<a class="reference internal" href="#optparse-extending-optparse"><span class="std std-ref">Extending optparse</span></a>.  Most actions tell <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to store
a value in some variable—for example, take a string from the command line and
store it in an attribute of <code class="docutils literal notranslate"><span class="pre">options</span></code>.</p>
<p>If you don’t specify an option action, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> defaults to <code class="docutils literal notranslate"><span class="pre">store</span></code>.</p>
</div>
<div class="section" id="the-store-action">
<span id="optparse-store-action"></span><h3>15.5.2.2. The store action<a class="headerlink" href="#the-store-action" title="Permalink to this headline">¶</a></h3>
<p>The most common option action is <code class="docutils literal notranslate"><span class="pre">store</span></code>, which tells <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to take
the next argument (or the remainder of the current argument), ensure that it is
of the correct type, and store it to your chosen destination.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Now let’s make up a fake command line and ask <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to parse it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;foo.txt&quot;</span><span class="p">]</span>
<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<p>When <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> sees the option string <code class="docutils literal notranslate"><span class="pre">-f</span></code>, it consumes the next
argument, <code class="docutils literal notranslate"><span class="pre">foo.txt</span></code>, and stores it in <code class="docutils literal notranslate"><span class="pre">options.filename</span></code>.  So, after this
call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code>, <code class="docutils literal notranslate"><span class="pre">options.filename</span></code> is <code class="docutils literal notranslate"><span class="pre">&quot;foo.txt&quot;</span></code>.</p>
<p>Some other option types supported by <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> are <code class="docutils literal notranslate"><span class="pre">int</span></code> and <code class="docutils literal notranslate"><span class="pre">float</span></code>.
Here’s an option that expects an integer argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;int&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;num&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that this option has no long option string, which is perfectly acceptable.
Also, there’s no explicit action, since the default is <code class="docutils literal notranslate"><span class="pre">store</span></code>.</p>
<p>Let’s parse another fake command-line.  This time, we’ll jam the option argument
right up against the option: since <code class="docutils literal notranslate"><span class="pre">-n42</span></code> (one argument) is equivalent to
<code class="docutils literal notranslate"><span class="pre">-n</span> <span class="pre">42</span></code> (two arguments), the code</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s2">&quot;-n42&quot;</span><span class="p">])</span>
<span class="nb">print</span> <span class="n">options</span><span class="o">.</span><span class="n">num</span>
</pre></div>
</div>
<p>will print <code class="docutils literal notranslate"><span class="pre">42</span></code>.</p>
<p>If you don’t specify a type, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> assumes <code class="docutils literal notranslate"><span class="pre">string</span></code>.  Combined with
the fact that the default action is <code class="docutils literal notranslate"><span class="pre">store</span></code>, that means our first example can
be a lot shorter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If you don’t supply a destination, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> figures out a sensible
default from the option strings: if the first long option string is
<code class="docutils literal notranslate"><span class="pre">--foo-bar</span></code>, then the default destination is <code class="docutils literal notranslate"><span class="pre">foo_bar</span></code>.  If there are no
long option strings, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> looks at the first short option string: the
default destination for <code class="docutils literal notranslate"><span class="pre">-f</span></code> is <code class="docutils literal notranslate"><span class="pre">f</span></code>.</p>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> also includes built-in <code class="docutils literal notranslate"><span class="pre">long</span></code> and <code class="docutils literal notranslate"><span class="pre">complex</span></code> types.  Adding
types is covered in section <a class="reference internal" href="#optparse-extending-optparse"><span class="std std-ref">Extending optparse</span></a>.</p>
</div>
<div class="section" id="handling-boolean-flag-options">
<span id="optparse-handling-boolean-options"></span><h3>15.5.2.3. Handling boolean (flag) options<a class="headerlink" href="#handling-boolean-flag-options" title="Permalink to this headline">¶</a></h3>
<p>Flag options—set a variable to true or false when a particular option is seen
—are quite common.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> supports them with two separate actions,
<code class="docutils literal notranslate"><span class="pre">store_true</span></code> and <code class="docutils literal notranslate"><span class="pre">store_false</span></code>.  For example, you might have a <code class="docutils literal notranslate"><span class="pre">verbose</span></code>
flag that is turned on with <code class="docutils literal notranslate"><span class="pre">-v</span></code> and off with <code class="docutils literal notranslate"><span class="pre">-q</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here we have two different options with the same destination, which is perfectly
OK.  (It just means you have to be a bit careful when setting default values—
see below.)</p>
<p>When <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> encounters <code class="docutils literal notranslate"><span class="pre">-v</span></code> on the command line, it sets
<code class="docutils literal notranslate"><span class="pre">options.verbose</span></code> to <code class="docutils literal notranslate"><span class="pre">True</span></code>; when it encounters <code class="docutils literal notranslate"><span class="pre">-q</span></code>,
<code class="docutils literal notranslate"><span class="pre">options.verbose</span></code> is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</div>
<div class="section" id="other-actions">
<span id="optparse-other-actions"></span><h3>15.5.2.4. Other actions<a class="headerlink" href="#other-actions" title="Permalink to this headline">¶</a></h3>
<p>Some other actions supported by <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code></dt>
<dd>store a constant value</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code></dt>
<dd>append this option’s argument to a list</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;count&quot;</span></code></dt>
<dd>increment a counter by one</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code></dt>
<dd>call a specified function</dd>
</dl>
<p>These are covered in section <a class="reference internal" href="#optparse-reference-guide"><span class="std std-ref">Reference Guide</span></a>, Reference Guide
and section <a class="reference internal" href="#optparse-option-callbacks"><span class="std std-ref">Option Callbacks</span></a>.</p>
</div>
<div class="section" id="default-values">
<span id="optparse-default-values"></span><h3>15.5.2.5. Default values<a class="headerlink" href="#default-values" title="Permalink to this headline">¶</a></h3>
<p>All of the above examples involve setting some variable (the “destination”) when
certain command-line options are seen.  What happens if those options are never
seen?  Since we didn’t supply any defaults, they are all set to <code class="docutils literal notranslate"><span class="pre">None</span></code>.  This
is usually fine, but sometimes you want more control.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> lets you
supply a default value for each destination, which is assigned before the
command line is parsed.</p>
<p>First, consider the verbose/quiet example.  If we want <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to set
<code class="docutils literal notranslate"><span class="pre">verbose</span></code> to <code class="docutils literal notranslate"><span class="pre">True</span></code> unless <code class="docutils literal notranslate"><span class="pre">-q</span></code> is seen, then we can do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Since default values apply to the <em>destination</em> rather than to any particular
option, and these two options happen to have the same destination, this is
exactly equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Consider this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Again, the default value for <code class="docutils literal notranslate"><span class="pre">verbose</span></code> will be <code class="docutils literal notranslate"><span class="pre">True</span></code>: the last default
value supplied for any particular destination is the one that counts.</p>
<p>A clearer way to specify default values is the <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code> method of
OptionParser, which you can call at any time before calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>As before, the last value specified for a given option destination is the one
that counts.  For clarity, try to use one method or the other of setting default
values, not both.</p>
</div>
<div class="section" id="generating-help">
<span id="optparse-generating-help"></span><h3>15.5.2.6. Generating help<a class="headerlink" href="#generating-help" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s ability to generate help and usage text automatically is
useful for creating user-friendly command-line interfaces.  All you have to do
is supply a <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> value for each option, and optionally a short
usage message for your whole program.  Here’s an OptionParser populated with
user-friendly (documented) options:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">usage</span> <span class="o">=</span> <span class="s2">&quot;usage: %prog [options] arg1 arg2&quot;</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="n">usage</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;make lots of noise [default]&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;be vewwy quiet (I&#39;m hunting wabbits)&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--filename&quot;</span><span class="p">,</span>
                  <span class="n">metavar</span><span class="o">=</span><span class="s2">&quot;FILE&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;write output to FILE&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-m&quot;</span><span class="p">,</span> <span class="s2">&quot;--mode&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s2">&quot;intermediate&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;interaction mode: novice, intermediate, &quot;</span>
                       <span class="s2">&quot;or expert [default: </span><span class="si">%d</span><span class="s2">efault]&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> encounters either <code class="docutils literal notranslate"><span class="pre">-h</span></code> or <code class="docutils literal notranslate"><span class="pre">--help</span></code> on the
command-line, or if you just call <code class="xref py py-meth docutils literal notranslate"><span class="pre">parser.print_help()</span></code>, it prints the
following to standard output:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: &lt;yourscript&gt; [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I&#39;m hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]
</pre></div>
</div>
<p>(If the help output is triggered by a help option, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> exits after
printing the help text.)</p>
<p>There’s a lot going on here to help <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> generate the best possible
help message:</p>
<ul>
<li><p class="first">the script defines its own usage message:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">usage</span> <span class="o">=</span> <span class="s2">&quot;usage: %prog [options] arg1 arg2&quot;</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> expands <code class="docutils literal notranslate"><span class="pre">%prog</span></code> in the usage string to the name of the
current program, i.e. <code class="docutils literal notranslate"><span class="pre">os.path.basename(sys.argv[0])</span></code>.  The expanded string
is then printed before the detailed option help.</p>
<p>If you don’t supply a usage string, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> uses a bland but sensible
default: <code class="docutils literal notranslate"><span class="pre">&quot;Usage:</span> <span class="pre">%prog</span> <span class="pre">[options]&quot;</span></code>, which is fine if your script doesn’t
take any positional arguments.</p>
</li>
<li><p class="first">every option defines a help string, and doesn’t worry about line-wrapping—
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> takes care of wrapping lines and making the help output look
good.</p>
</li>
<li><p class="first">options that take a value indicate this fact in their automatically-generated
help message, e.g. for the “mode” option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-</span><span class="n">m</span> <span class="n">MODE</span><span class="p">,</span> <span class="o">--</span><span class="n">mode</span><span class="o">=</span><span class="n">MODE</span>
</pre></div>
</div>
<p>Here, “MODE” is called the meta-variable: it stands for the argument that the
user is expected to supply to <code class="docutils literal notranslate"><span class="pre">-m</span></code>/<code class="docutils literal notranslate"><span class="pre">--mode</span></code>.  By default,
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> converts the destination variable name to uppercase and uses
that for the meta-variable.  Sometimes, that’s not what you want—for
example, the <code class="docutils literal notranslate"><span class="pre">--filename</span></code> option explicitly sets <code class="docutils literal notranslate"><span class="pre">metavar=&quot;FILE&quot;</span></code>,
resulting in this automatically-generated option description:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-</span><span class="n">f</span> <span class="n">FILE</span><span class="p">,</span> <span class="o">--</span><span class="n">filename</span><span class="o">=</span><span class="n">FILE</span>
</pre></div>
</div>
<p>This is important for more than just saving space, though: the manually
written help text uses the meta-variable <code class="docutils literal notranslate"><span class="pre">FILE</span></code> to clue the user in that
there’s a connection between the semi-formal syntax <code class="docutils literal notranslate"><span class="pre">-f</span> <span class="pre">FILE</span></code> and the informal
semantic description “write output to FILE”. This is a simple but effective
way to make your help text a lot clearer and more useful for end users.</p>
</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>Options that have a default value can include <code class="docutils literal notranslate"><span class="pre">%default</span></code> in the help
string—<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will replace it with <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the option’s
default value.  If an option has no default value (or the default value is
<code class="docutils literal notranslate"><span class="pre">None</span></code>), <code class="docutils literal notranslate"><span class="pre">%default</span></code> expands to <code class="docutils literal notranslate"><span class="pre">none</span></code>.</p>
</div>
<div class="section" id="grouping-options">
<h4>15.5.2.6.1. Grouping Options<a class="headerlink" href="#grouping-options" title="Permalink to this headline">¶</a></h4>
<p>When dealing with many options, it is convenient to group these options for
better help output.  An <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> can contain several option groups,
each of which can contain several options.</p>
<p>An option group is obtained using the class <a class="reference internal" href="#optparse.OptionGroup" title="optparse.OptionGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionGroup</span></code></a>:</p>
<dl class="class">
<dt id="optparse.OptionGroup">
<em class="property">class </em><code class="descclassname">optparse.</code><code class="descname">OptionGroup</code><span class="sig-paren">(</span><em>parser</em>, <em>title</em>, <em>description=None</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionGroup" title="Permalink to this definition">¶</a></dt>
<dd><p>where</p>
<ul class="simple">
<li>parser is the <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> instance the group will be insterted in
to</li>
<li>title is the group title</li>
<li>description, optional, is a long description of the group</li>
</ul>
</dd></dl>

<p><a class="reference internal" href="#optparse.OptionGroup" title="optparse.OptionGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionGroup</span></code></a> inherits from <code class="xref py py-class docutils literal notranslate"><span class="pre">OptionContainer</span></code> (like
<a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a>) and so the <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code> method can be used to add
an option to the group.</p>
<p>Once all the options are declared, using the <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> method
<code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option_group()</span></code> the group is added to the previously defined parser.</p>
<p>Continuing with the parser defined in the previous section, adding an
<a class="reference internal" href="#optparse.OptionGroup" title="optparse.OptionGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionGroup</span></code></a> to a parser is easy:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">group</span> <span class="o">=</span> <span class="n">OptionGroup</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="s2">&quot;Dangerous Options&quot;</span><span class="p">,</span>
                    <span class="s2">&quot;Caution: use these options at your own risk.  &quot;</span>
                    <span class="s2">&quot;It is believed that some of them bite.&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-g&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Group option.&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option_group</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>
</pre></div>
</div>
<p>This would result in the following help output:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: &lt;yourscript&gt; [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I&#39;m hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
                        expert [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.
</pre></div>
</div>
<p>A bit more complete example might involve using more than one group: still
extending the previous example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">group</span> <span class="o">=</span> <span class="n">OptionGroup</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="s2">&quot;Dangerous Options&quot;</span><span class="p">,</span>
                    <span class="s2">&quot;Caution: use these options at your own risk.  &quot;</span>
                    <span class="s2">&quot;It is believed that some of them bite.&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-g&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Group option.&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option_group</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>

<span class="n">group</span> <span class="o">=</span> <span class="n">OptionGroup</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="s2">&quot;Debug Options&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-d&quot;</span><span class="p">,</span> <span class="s2">&quot;--debug&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span>
                 <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Print debug information&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-s&quot;</span><span class="p">,</span> <span class="s2">&quot;--sql&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span>
                 <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Print all SQL statements executed&quot;</span><span class="p">)</span>
<span class="n">group</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-e&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Print every action done&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option_group</span><span class="p">(</span><span class="n">group</span><span class="p">)</span>
</pre></div>
</div>
<p>that results in the following output:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: &lt;yourscript&gt; [options] arg1 arg2

Options:
  -h, --help            show this help message and exit
  -v, --verbose         make lots of noise [default]
  -q, --quiet           be vewwy quiet (I&#39;m hunting wabbits)
  -f FILE, --filename=FILE
                        write output to FILE
  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
                        [default: intermediate]

  Dangerous Options:
    Caution: use these options at your own risk.  It is believed that some
    of them bite.

    -g                  Group option.

  Debug Options:
    -d, --debug         Print debug information
    -s, --sql           Print all SQL statements executed
    -e                  Print every action done
</pre></div>
</div>
<p>Another interesting method, in particular when working programmatically with
option groups is:</p>
<dl class="method">
<dt id="optparse.OptionParser.get_option_group">
<code class="descclassname">OptionParser.</code><code class="descname">get_option_group</code><span class="sig-paren">(</span><em>opt_str</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.get_option_group" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="#optparse.OptionGroup" title="optparse.OptionGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionGroup</span></code></a> to which the short or long option
string <em>opt_str</em> (e.g. <code class="docutils literal notranslate"><span class="pre">'-o'</span></code> or <code class="docutils literal notranslate"><span class="pre">'--option'</span></code>) belongs. If
there’s no such <a class="reference internal" href="#optparse.OptionGroup" title="optparse.OptionGroup"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionGroup</span></code></a>, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</div>
</div>
<div class="section" id="printing-a-version-string">
<span id="optparse-printing-version-string"></span><h3>15.5.2.7. Printing a version string<a class="headerlink" href="#printing-a-version-string" title="Permalink to this headline">¶</a></h3>
<p>Similar to the brief usage string, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> can also print a version
string for your program.  You have to supply the string as the <code class="docutils literal notranslate"><span class="pre">version</span></code>
argument to OptionParser:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="o">=</span><span class="s2">&quot;%prog [-f] [-q]&quot;</span><span class="p">,</span> <span class="n">version</span><span class="o">=</span><span class="s2">&quot;%prog 1.0&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">%prog</span></code> is expanded just like it is in <code class="docutils literal notranslate"><span class="pre">usage</span></code>.  Apart from that,
<code class="docutils literal notranslate"><span class="pre">version</span></code> can contain anything you like.  When you supply it, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
automatically adds a <code class="docutils literal notranslate"><span class="pre">--version</span></code> option to your parser. If it encounters
this option on the command line, it expands your <code class="docutils literal notranslate"><span class="pre">version</span></code> string (by
replacing <code class="docutils literal notranslate"><span class="pre">%prog</span></code>), prints it to stdout, and exits.</p>
<p>For example, if your script is called <code class="docutils literal notranslate"><span class="pre">/usr/bin/foo</span></code>:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> /usr/bin/foo --version
<span class="go">foo 1.0</span>
</pre></div>
</div>
<p>The following two methods can be used to print and get the <code class="docutils literal notranslate"><span class="pre">version</span></code> string:</p>
<dl class="method">
<dt id="optparse.OptionParser.print_version">
<code class="descclassname">OptionParser.</code><code class="descname">print_version</code><span class="sig-paren">(</span><em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.print_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the version message for the current program (<code class="docutils literal notranslate"><span class="pre">self.version</span></code>) to
<em>file</em> (default stdout).  As with <a class="reference internal" href="#optparse.OptionParser.print_usage" title="optparse.OptionParser.print_usage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_usage()</span></code></a>, any occurrence
of <code class="docutils literal notranslate"><span class="pre">%prog</span></code> in <code class="docutils literal notranslate"><span class="pre">self.version</span></code> is replaced with the name of the current
program.  Does nothing if <code class="docutils literal notranslate"><span class="pre">self.version</span></code> is empty or undefined.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.get_version">
<code class="descclassname">OptionParser.</code><code class="descname">get_version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.get_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#optparse.OptionParser.print_version" title="optparse.OptionParser.print_version"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_version()</span></code></a> but returns the version string instead of
printing it.</p>
</dd></dl>

</div>
<div class="section" id="how-optparse-handles-errors">
<span id="optparse-how-optparse-handles-errors"></span><h3>15.5.2.8. How <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> handles errors<a class="headerlink" href="#how-optparse-handles-errors" title="Permalink to this headline">¶</a></h3>
<p>There are two broad classes of errors that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> has to worry about:
programmer errors and user errors.  Programmer errors are usually erroneous
calls to <a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-func docutils literal notranslate"><span class="pre">OptionParser.add_option()</span></code></a>, e.g. invalid option strings, unknown
option attributes, missing option attributes, etc.  These are dealt with in the
usual way: raise an exception (either <code class="xref py py-exc docutils literal notranslate"><span class="pre">optparse.OptionError</span></code> or
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>) and let the program crash.</p>
<p>Handling user errors is much more important, since they are guaranteed to happen
no matter how stable your code is.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> can automatically detect
some user errors, such as bad option arguments (passing <code class="docutils literal notranslate"><span class="pre">-n</span> <span class="pre">4x</span></code> where
<code class="docutils literal notranslate"><span class="pre">-n</span></code> takes an integer argument), missing arguments (<code class="docutils literal notranslate"><span class="pre">-n</span></code> at the end
of the command line, where <code class="docutils literal notranslate"><span class="pre">-n</span></code> takes an argument of any type).  Also,
you can call <code class="xref py py-func docutils literal notranslate"><span class="pre">OptionParser.error()</span></code> to signal an application-defined error
condition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="o">...</span>
<span class="k">if</span> <span class="n">options</span><span class="o">.</span><span class="n">a</span> <span class="ow">and</span> <span class="n">options</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&quot;options -a and -b are mutually exclusive&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In either case, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> handles the error the same way: it prints the
program’s usage message and an error message to standard error and exits with
error status 2.</p>
<p>Consider the first example above, where the user passes <code class="docutils literal notranslate"><span class="pre">4x</span></code> to an option
that takes an integer:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> /usr/bin/foo -n 4x
<span class="go">Usage: foo [options]</span>

<span class="go">foo: error: option -n: invalid integer value: &#39;4x&#39;</span>
</pre></div>
</div>
<p>Or, where the user fails to pass a value at all:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> /usr/bin/foo -n
<span class="go">Usage: foo [options]</span>

<span class="go">foo: error: -n option requires an argument</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>-generated error messages take care always to mention the
option involved in the error; be sure to do the same when calling
<code class="xref py py-func docutils literal notranslate"><span class="pre">OptionParser.error()</span></code> from your application code.</p>
<p>If <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s default error-handling behaviour does not suit your needs,
you’ll need to subclass OptionParser and override its <code class="xref py py-meth docutils literal notranslate"><span class="pre">exit()</span></code>
and/or <code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code> methods.</p>
</div>
<div class="section" id="putting-it-all-together">
<span id="optparse-putting-it-all-together"></span><h3>15.5.2.9. Putting it all together<a class="headerlink" href="#putting-it-all-together" title="Permalink to this headline">¶</a></h3>
<p>Here’s what <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>-based scripts usually look like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>
<span class="o">...</span>
<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="n">usage</span> <span class="o">=</span> <span class="s2">&quot;usage: %prog [options] arg&quot;</span>
    <span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">usage</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">,</span>
                      <span class="n">help</span><span class="o">=</span><span class="s2">&quot;read data from FILENAME&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span>
                      <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span>
                      <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
    <span class="o">...</span>
    <span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">1</span><span class="p">:</span>
        <span class="n">parser</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s2">&quot;incorrect number of arguments&quot;</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">options</span><span class="o">.</span><span class="n">verbose</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;reading </span><span class="si">%s</span><span class="s2">...&quot;</span> <span class="o">%</span> <span class="n">options</span><span class="o">.</span><span class="n">filename</span>
    <span class="o">...</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="reference-guide">
<span id="optparse-reference-guide"></span><h2>15.5.3. Reference Guide<a class="headerlink" href="#reference-guide" title="Permalink to this headline">¶</a></h2>
<div class="section" id="creating-the-parser">
<span id="optparse-creating-parser"></span><h3>15.5.3.1. Creating the parser<a class="headerlink" href="#creating-the-parser" title="Permalink to this headline">¶</a></h3>
<p>The first step in using <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> is to create an OptionParser instance.</p>
<dl class="class">
<dt id="optparse.OptionParser">
<em class="property">class </em><code class="descclassname">optparse.</code><code class="descname">OptionParser</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser" title="Permalink to this definition">¶</a></dt>
<dd><p>The OptionParser constructor has no required arguments, but a number of
optional keyword arguments.  You should always pass them as keyword
arguments, i.e. do not rely on the order in which the arguments are declared.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">usage</span></code> (default: <code class="docutils literal notranslate"><span class="pre">&quot;%prog</span> <span class="pre">[options]&quot;</span></code>)</dt>
<dd>The usage summary to print when your program is run incorrectly or with a
help option.  When <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> prints the usage string, it expands
<code class="docutils literal notranslate"><span class="pre">%prog</span></code> to <code class="docutils literal notranslate"><span class="pre">os.path.basename(sys.argv[0])</span></code> (or to <code class="docutils literal notranslate"><span class="pre">prog</span></code> if you
passed that keyword argument).  To suppress a usage message, pass the
special value <code class="xref py py-data docutils literal notranslate"><span class="pre">optparse.SUPPRESS_USAGE</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">option_list</span></code> (default: <code class="docutils literal notranslate"><span class="pre">[]</span></code>)</dt>
<dd>A list of Option objects to populate the parser with.  The options in
<code class="docutils literal notranslate"><span class="pre">option_list</span></code> are added after any options in <code class="docutils literal notranslate"><span class="pre">standard_option_list</span></code> (a
class attribute that may be set by OptionParser subclasses), but before
any version or help options. Deprecated; use <a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code></a> after
creating the parser instead.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">option_class</span></code> (default: optparse.Option)</dt>
<dd>Class to use when adding options to the parser in <a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code></a>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">version</span></code> (default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</dt>
<dd>A version string to print when the user supplies a version option. If you
supply a true value for <code class="docutils literal notranslate"><span class="pre">version</span></code>, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> automatically adds a
version option with the single option string <code class="docutils literal notranslate"><span class="pre">--version</span></code>.  The
substring <code class="docutils literal notranslate"><span class="pre">%prog</span></code> is expanded the same as for <code class="docutils literal notranslate"><span class="pre">usage</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">conflict_handler</span></code> (default: <code class="docutils literal notranslate"><span class="pre">&quot;error&quot;</span></code>)</dt>
<dd>Specifies what to do when options with conflicting option strings are
added to the parser; see section
<a class="reference internal" href="#optparse-conflicts-between-options"><span class="std std-ref">Conflicts between options</span></a>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">description</span></code> (default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</dt>
<dd>A paragraph of text giving a brief overview of your program.
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> reformats this paragraph to fit the current terminal width
and prints it when the user requests help (after <code class="docutils literal notranslate"><span class="pre">usage</span></code>, but before the
list of options).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">formatter</span></code> (default: a new <code class="xref py py-class docutils literal notranslate"><span class="pre">IndentedHelpFormatter</span></code>)</dt>
<dd>An instance of optparse.HelpFormatter that will be used for printing help
text.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> provides two concrete classes for this purpose:
IndentedHelpFormatter and TitledHelpFormatter.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">add_help_option</span></code> (default: <code class="docutils literal notranslate"><span class="pre">True</span></code>)</dt>
<dd>If true, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will add a help option (with option strings <code class="docutils literal notranslate"><span class="pre">-h</span></code>
and <code class="docutils literal notranslate"><span class="pre">--help</span></code>) to the parser.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">prog</span></code></dt>
<dd>The string to use when expanding <code class="docutils literal notranslate"><span class="pre">%prog</span></code> in <code class="docutils literal notranslate"><span class="pre">usage</span></code> and <code class="docutils literal notranslate"><span class="pre">version</span></code>
instead of <code class="docutils literal notranslate"><span class="pre">os.path.basename(sys.argv[0])</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">epilog</span></code> (default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</dt>
<dd>A paragraph of help text to print after the option help.</dd>
</dl>
</dd></dl>

</div>
<div class="section" id="populating-the-parser">
<span id="optparse-populating-parser"></span><h3>15.5.3.2. Populating the parser<a class="headerlink" href="#populating-the-parser" title="Permalink to this headline">¶</a></h3>
<p>There are several ways to populate the parser with options.  The preferred way
is by using <a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.add_option()</span></code></a>, as shown in section
<a class="reference internal" href="#optparse-tutorial"><span class="std std-ref">Tutorial</span></a>.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code> can be called in one of two ways:</p>
<ul class="simple">
<li>pass it an Option instance (as returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">make_option()</span></code>)</li>
<li>pass it any combination of positional and keyword arguments that are
acceptable to <code class="xref py py-func docutils literal notranslate"><span class="pre">make_option()</span></code> (i.e., to the Option constructor), and it
will create the Option instance for you</li>
</ul>
<p>The other alternative is to pass a list of pre-constructed Option instances to
the OptionParser constructor, as in:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">option_list</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">make_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--filename&quot;</span><span class="p">,</span>
                <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">),</span>
    <span class="n">make_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span>
                <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">),</span>
    <span class="p">]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_list</span><span class="o">=</span><span class="n">option_list</span><span class="p">)</span>
</pre></div>
</div>
<p>(<code class="xref py py-func docutils literal notranslate"><span class="pre">make_option()</span></code> is a factory function for creating Option instances;
currently it is an alias for the Option constructor.  A future version of
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> may split Option into several classes, and <code class="xref py py-func docutils literal notranslate"><span class="pre">make_option()</span></code>
will pick the right class to instantiate.  Do not instantiate Option directly.)</p>
</div>
<div class="section" id="defining-options">
<span id="optparse-defining-options"></span><h3>15.5.3.3. Defining options<a class="headerlink" href="#defining-options" title="Permalink to this headline">¶</a></h3>
<p>Each Option instance represents a set of synonymous command-line option strings,
e.g. <code class="docutils literal notranslate"><span class="pre">-f</span></code> and <code class="docutils literal notranslate"><span class="pre">--file</span></code>.  You can specify any number of short or
long option strings, but you must specify at least one overall option string.</p>
<p>The canonical way to create an <code class="xref py py-class docutils literal notranslate"><span class="pre">Option</span></code> instance is with the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code> method of <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a>.</p>
<dl class="method">
<dt id="optparse.OptionParser.add_option">
<code class="descclassname">OptionParser.</code><code class="descname">add_option</code><span class="sig-paren">(</span><em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.add_option" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">OptionParser.</code><code class="descname">add_option</code><span class="sig-paren">(</span><em>*opt_str</em>, <em>attr=value</em>, <em>...</em><span class="sig-paren">)</span></dt>
<dd><p>To define an option with only a short option string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>And to define an option with only a long option string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--foo&quot;</span><span class="p">,</span> <span class="n">attr</span><span class="o">=</span><span class="n">value</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>The keyword arguments define attributes of the new Option object.  The most
important option attribute is <a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a>, and it largely
determines which other attributes are relevant or required.  If you pass
irrelevant option attributes, or fail to pass required ones, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
raises an <code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionError</span></code> exception explaining your mistake.</p>
<p>An option’s <em>action</em> determines what <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> does when it encounters
this option on the command-line.  The standard option actions hard-coded into
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code></dt>
<dd>store this option’s argument (default)</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code></dt>
<dd>store a constant value</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;store_true&quot;</span></code></dt>
<dd>store a true value</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;store_false&quot;</span></code></dt>
<dd>store a false value</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code></dt>
<dd>append this option’s argument to a list</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;append_const&quot;</span></code></dt>
<dd>append a constant value to a list</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;count&quot;</span></code></dt>
<dd>increment a counter by one</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code></dt>
<dd>call a specified function</dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;help&quot;</span></code></dt>
<dd>print a usage message including all options and the documentation for them</dd>
</dl>
<p>(If you don’t supply an action, the default is <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code>.  For this action,
you may also supply <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> and <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> option
attributes; see <a class="reference internal" href="#optparse-standard-option-actions"><span class="std std-ref">Standard option actions</span></a>.)</p>
</dd></dl>

<p>As you can see, most actions involve storing or updating a value somewhere.
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> always creates a special object for this, conventionally called
<code class="docutils literal notranslate"><span class="pre">options</span></code> (it happens to be an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">optparse.Values</span></code>).  Option
arguments (and various other values) are stored as attributes of this object,
according to the <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> (destination) option attribute.</p>
<p>For example, when you call</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
</pre></div>
</div>
<p>one of the first things <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> does is create the <code class="docutils literal notranslate"><span class="pre">options</span></code> object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span> <span class="o">=</span> <span class="n">Values</span><span class="p">()</span>
</pre></div>
</div>
<p>If one of the options in this parser is defined with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">,</span> <span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;string&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and the command-line being parsed includes any of the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-</span><span class="n">ffoo</span>
<span class="o">-</span><span class="n">f</span> <span class="n">foo</span>
<span class="o">--</span><span class="n">file</span><span class="o">=</span><span class="n">foo</span>
<span class="o">--</span><span class="n">file</span> <span class="n">foo</span>
</pre></div>
</div>
<p>then <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>, on seeing this option, will do the equivalent of</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">filename</span> <span class="o">=</span> <span class="s2">&quot;foo&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> and <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> option attributes are almost
as important as <a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a>, but <a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a> is the only
one that makes sense for <em>all</em> options.</p>
</div>
<div class="section" id="option-attributes">
<span id="optparse-option-attributes"></span><h3>15.5.3.4. Option attributes<a class="headerlink" href="#option-attributes" title="Permalink to this headline">¶</a></h3>
<p>The following option attributes may be passed as keyword arguments to
<a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.add_option()</span></code></a>.  If you pass an option attribute that is not
relevant to a particular option, or fail to pass a required option attribute,
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionError</span></code>.</p>
<dl class="attribute">
<dt id="optparse.Option.action">
<code class="descclassname">Option.</code><code class="descname">action</code><a class="headerlink" href="#optparse.Option.action" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code>)</p>
<p>Determines <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s behaviour when this option is seen on the
command line; the available options are documented <a class="reference internal" href="#optparse-standard-option-actions"><span class="std std-ref">here</span></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.type">
<code class="descclassname">Option.</code><code class="descname">type</code><a class="headerlink" href="#optparse.Option.type" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code>)</p>
<p>The argument type expected by this option (e.g., <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;int&quot;</span></code>);
the available option types are documented <a class="reference internal" href="#optparse-standard-option-types"><span class="std std-ref">here</span></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.dest">
<code class="descclassname">Option.</code><code class="descname">dest</code><a class="headerlink" href="#optparse.Option.dest" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: derived from option strings)</p>
<p>If the option’s action implies writing or modifying a value somewhere, this
tells <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> where to write it: <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> names an
attribute of the <code class="docutils literal notranslate"><span class="pre">options</span></code> object that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> builds as it parses
the command line.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.default">
<code class="descclassname">Option.</code><code class="descname">default</code><a class="headerlink" href="#optparse.Option.default" title="Permalink to this definition">¶</a></dt>
<dd><p>The value to use for this option’s destination if the option is not seen on
the command line.  See also <a class="reference internal" href="#optparse.OptionParser.set_defaults" title="optparse.OptionParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.set_defaults()</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.nargs">
<code class="descclassname">Option.</code><code class="descname">nargs</code><a class="headerlink" href="#optparse.Option.nargs" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: 1)</p>
<p>How many arguments of type <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> should be consumed when this
option is seen.  If &gt; 1, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will store a tuple of values to
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.const">
<code class="descclassname">Option.</code><code class="descname">const</code><a class="headerlink" href="#optparse.Option.const" title="Permalink to this definition">¶</a></dt>
<dd><p>For actions that store a constant value, the constant value to store.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.choices">
<code class="descclassname">Option.</code><code class="descname">choices</code><a class="headerlink" href="#optparse.Option.choices" title="Permalink to this definition">¶</a></dt>
<dd><p>For options of type <code class="docutils literal notranslate"><span class="pre">&quot;choice&quot;</span></code>, the list of strings the user may choose
from.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.callback">
<code class="descclassname">Option.</code><code class="descname">callback</code><a class="headerlink" href="#optparse.Option.callback" title="Permalink to this definition">¶</a></dt>
<dd><p>For options with action <code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code>, the callable to call when this option
is seen.  See section <a class="reference internal" href="#optparse-option-callbacks"><span class="std std-ref">Option Callbacks</span></a> for detail on the
arguments passed to the callable.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.callback_args">
<code class="descclassname">Option.</code><code class="descname">callback_args</code><a class="headerlink" href="#optparse.Option.callback_args" title="Permalink to this definition">¶</a></dt>
<dt id="optparse.Option.callback_kwargs">
<code class="descclassname">Option.</code><code class="descname">callback_kwargs</code><a class="headerlink" href="#optparse.Option.callback_kwargs" title="Permalink to this definition">¶</a></dt>
<dd><p>Additional positional and keyword arguments to pass to <code class="docutils literal notranslate"><span class="pre">callback</span></code> after the
four standard callback arguments.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.help">
<code class="descclassname">Option.</code><code class="descname">help</code><a class="headerlink" href="#optparse.Option.help" title="Permalink to this definition">¶</a></dt>
<dd><p>Help text to print for this option when listing all available options after
the user supplies a <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> option (such as <code class="docutils literal notranslate"><span class="pre">--help</span></code>).  If
no help text is supplied, the option will be listed without help text.  To
hide this option, use the special value <code class="xref py py-data docutils literal notranslate"><span class="pre">optparse.SUPPRESS_HELP</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.metavar">
<code class="descclassname">Option.</code><code class="descname">metavar</code><a class="headerlink" href="#optparse.Option.metavar" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: derived from option strings)</p>
<p>Stand-in for the option argument(s) to use when printing help text.  See
section <a class="reference internal" href="#optparse-tutorial"><span class="std std-ref">Tutorial</span></a> for an example.</p>
</dd></dl>

</div>
<div class="section" id="standard-option-actions">
<span id="optparse-standard-option-actions"></span><h3>15.5.3.5. Standard option actions<a class="headerlink" href="#standard-option-actions" title="Permalink to this headline">¶</a></h3>
<p>The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to
guide <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s behaviour; a few have required attributes, which you
must specify for any option using that action.</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code> [relevant: <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>, <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>,
<a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>, <a class="reference internal" href="#optparse.Option.choices" title="optparse.Option.choices"><code class="xref py py-attr docutils literal notranslate"><span class="pre">choices</span></code></a>]</p>
<p>The option must be followed by an argument, which is converted to a value
according to <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> and stored in <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.  If
<a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a> &gt; 1, multiple arguments will be consumed from the
command line; all will be converted according to <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> and
stored to <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> as a tuple.  See the
<a class="reference internal" href="#optparse-standard-option-types"><span class="std std-ref">Standard option types</span></a> section.</p>
<p>If <a class="reference internal" href="#optparse.Option.choices" title="optparse.Option.choices"><code class="xref py py-attr docutils literal notranslate"><span class="pre">choices</span></code></a> is supplied (a list or tuple of strings), the type
defaults to <code class="docutils literal notranslate"><span class="pre">&quot;choice&quot;</span></code>.</p>
<p>If <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> is not supplied, it defaults to <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code>.</p>
<p>If <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> is not supplied, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> derives a destination
from the first long option string (e.g., <code class="docutils literal notranslate"><span class="pre">--foo-bar</span></code> implies
<code class="docutils literal notranslate"><span class="pre">foo_bar</span></code>). If there are no long option strings, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> derives a
destination from the first short option string (e.g., <code class="docutils literal notranslate"><span class="pre">-f</span></code> implies <code class="docutils literal notranslate"><span class="pre">f</span></code>).</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-f&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-p&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;float&quot;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;point&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>As it parses the command line</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-</span><span class="n">f</span> <span class="n">foo</span><span class="o">.</span><span class="n">txt</span> <span class="o">-</span><span class="n">p</span> <span class="mi">1</span> <span class="o">-</span><span class="mf">3.5</span> <span class="mi">4</span> <span class="o">-</span><span class="n">fbar</span><span class="o">.</span><span class="n">txt</span>
</pre></div>
</div>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will set</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="s2">&quot;foo.txt&quot;</span>
<span class="n">options</span><span class="o">.</span><span class="n">point</span> <span class="o">=</span> <span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.5</span><span class="p">,</span> <span class="mf">4.0</span><span class="p">)</span>
<span class="n">options</span><span class="o">.</span><span class="n">f</span> <span class="o">=</span> <span class="s2">&quot;bar.txt&quot;</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code> [required: <a class="reference internal" href="#optparse.Option.const" title="optparse.Option.const"><code class="xref py py-attr docutils literal notranslate"><span class="pre">const</span></code></a>; relevant:
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>]</p>
<p>The value <a class="reference internal" href="#optparse.Option.const" title="optparse.Option.const"><code class="xref py py-attr docutils literal notranslate"><span class="pre">const</span></code></a> is stored in <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-q&quot;</span><span class="p">,</span> <span class="s2">&quot;--quiet&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="s2">&quot;--verbose&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--noisy&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">--noisy</span></code> is seen, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will set</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">verbose</span> <span class="o">=</span> <span class="mi">2</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;store_true&quot;</span></code> [relevant: <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>]</p>
<p>A special case of <code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code> that stores a true value to
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;store_false&quot;</span></code> [relevant: <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>]</p>
<p>Like <code class="docutils literal notranslate"><span class="pre">&quot;store_true&quot;</span></code>, but stores a false value.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--clobber&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;clobber&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--no-clobber&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_false&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;clobber&quot;</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code> [relevant: <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>, <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>,
<a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>, <a class="reference internal" href="#optparse.Option.choices" title="optparse.Option.choices"><code class="xref py py-attr docutils literal notranslate"><span class="pre">choices</span></code></a>]</p>
<p>The option must be followed by an argument, which is appended to the list in
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.  If no default value for <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> is
supplied, an empty list is automatically created when <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> first
encounters this option on the command-line.  If <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a> &gt; 1,
multiple arguments are consumed, and a tuple of length <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>
is appended to <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.</p>
<p>The defaults for <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> and <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> are the same as
for the <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code> action.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-t&quot;</span><span class="p">,</span> <span class="s2">&quot;--tracks&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;append&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;int&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>If <code class="docutils literal notranslate"><span class="pre">-t3</span></code> is seen on the command-line, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> does the equivalent
of:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">tracks</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">options</span><span class="o">.</span><span class="n">tracks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="s2">&quot;3&quot;</span><span class="p">))</span>
</pre></div>
</div>
<p>If, a little later on, <code class="docutils literal notranslate"><span class="pre">--tracks=4</span></code> is seen, it does:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">tracks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="s2">&quot;4&quot;</span><span class="p">))</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">append</span></code> action calls the <code class="docutils literal notranslate"><span class="pre">append</span></code> method on the current value of the
option.  This means that any default value specified must have an <code class="docutils literal notranslate"><span class="pre">append</span></code>
method.  It also means that if the default value is non-empty, the default
elements will be present in the parsed value for the option, with any values
from the command line appended after those default values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--files&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;append&quot;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;~/.mypkg/defaults&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">([</span><span class="s1">&#39;--files&#39;</span><span class="p">,</span> <span class="s1">&#39;overrides.mypkg&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opts</span><span class="o">.</span><span class="n">files</span>
<span class="go">[&#39;~/.mypkg/defaults&#39;, &#39;overrides.mypkg&#39;]</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;append_const&quot;</span></code> [required: <a class="reference internal" href="#optparse.Option.const" title="optparse.Option.const"><code class="xref py py-attr docutils literal notranslate"><span class="pre">const</span></code></a>; relevant:
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>]</p>
<p>Like <code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code>, but the value <a class="reference internal" href="#optparse.Option.const" title="optparse.Option.const"><code class="xref py py-attr docutils literal notranslate"><span class="pre">const</span></code></a> is appended to
<a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>; as with <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code>, <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> defaults to
<code class="docutils literal notranslate"><span class="pre">None</span></code>, and an empty list is automatically created the first time the option
is encountered.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;count&quot;</span></code> [relevant: <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>]</p>
<p>Increment the integer stored at <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>.  If no default value is
supplied, <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a> is set to zero before being incremented the
first time.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;count&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbosity&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The first time <code class="docutils literal notranslate"><span class="pre">-v</span></code> is seen on the command line, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> does the
equivalent of:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>Every subsequent occurrence of <code class="docutils literal notranslate"><span class="pre">-v</span></code> results in</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="o">.</span><span class="n">verbosity</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code> [required: <a class="reference internal" href="#optparse.Option.callback" title="optparse.Option.callback"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback</span></code></a>; relevant:
<a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>, <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>, <a class="reference internal" href="#optparse.Option.callback_args" title="optparse.Option.callback_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_args</span></code></a>,
<a class="reference internal" href="#optparse.Option.callback_kwargs" title="optparse.Option.callback_kwargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_kwargs</span></code></a>]</p>
<p>Call the function specified by <a class="reference internal" href="#optparse.Option.callback" title="optparse.Option.callback"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback</span></code></a>, which is called as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">func</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>See section <a class="reference internal" href="#optparse-option-callbacks"><span class="std std-ref">Option Callbacks</span></a> for more detail.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;help&quot;</span></code></p>
<p>Prints a complete help message for all the options in the current option
parser.  The help message is constructed from the <code class="docutils literal notranslate"><span class="pre">usage</span></code> string passed to
OptionParser’s constructor and the <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> string passed to every
option.</p>
<p>If no <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> string is supplied for an option, it will still be
listed in the help message.  To omit an option entirely, use the special value
<code class="xref py py-data docutils literal notranslate"><span class="pre">optparse.SUPPRESS_HELP</span></code>.</p>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> automatically adds a <a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> option to all
OptionParsers, so you do not normally need to create one.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span><span class="p">,</span> <span class="n">SUPPRESS_HELP</span>

<span class="c1"># usually, a help option is added automatically, but that can</span>
<span class="c1"># be suppressed using the add_help_option argument</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">add_help_option</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>

<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-h&quot;</span><span class="p">,</span> <span class="s2">&quot;--help&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;help&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-v&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;verbose&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Be moderately verbose&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--file&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;filename&quot;</span><span class="p">,</span>
                  <span class="n">help</span><span class="o">=</span><span class="s2">&quot;Input file to read data from&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--secret&quot;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">SUPPRESS_HELP</span><span class="p">)</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> sees either <code class="docutils literal notranslate"><span class="pre">-h</span></code> or <code class="docutils literal notranslate"><span class="pre">--help</span></code> on the command line,
it will print something like the following help message to stdout (assuming
<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is <code class="docutils literal notranslate"><span class="pre">&quot;foo.py&quot;</span></code>):</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: foo.py [options]

Options:
  -h, --help        Show this help message and exit
  -v                Be moderately verbose
  --file=FILENAME   Input file to read data from
</pre></div>
</div>
<p>After printing the help message, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> terminates your process with
<code class="docutils literal notranslate"><span class="pre">sys.exit(0)</span></code>.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;version&quot;</span></code></p>
<p>Prints the version number supplied to the OptionParser to stdout and exits.
The version number is actually formatted and printed by the
<code class="docutils literal notranslate"><span class="pre">print_version()</span></code> method of OptionParser.  Generally only relevant if the
<code class="docutils literal notranslate"><span class="pre">version</span></code> argument is supplied to the OptionParser constructor.  As with
<a class="reference internal" href="#optparse.Option.help" title="optparse.Option.help"><code class="xref py py-attr docutils literal notranslate"><span class="pre">help</span></code></a> options, you will rarely create <code class="docutils literal notranslate"><span class="pre">version</span></code> options,
since <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> automatically adds them when needed.</p>
</li>
</ul>
</div>
<div class="section" id="standard-option-types">
<span id="optparse-standard-option-types"></span><h3>15.5.3.6. Standard option types<a class="headerlink" href="#standard-option-types" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> has six built-in option types: <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;int&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;long&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;choice&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;float&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;complex&quot;</span></code>.  If you need to add new
option types, see section <a class="reference internal" href="#optparse-extending-optparse"><span class="std std-ref">Extending optparse</span></a>.</p>
<p>Arguments to string options are not checked or converted in any way: the text on
the command line is stored in the destination (or passed to the callback) as-is.</p>
<p>Integer arguments (type <code class="docutils literal notranslate"><span class="pre">&quot;int&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;long&quot;</span></code>) are parsed as follows:</p>
<ul class="simple">
<li>if the number starts with <code class="docutils literal notranslate"><span class="pre">0x</span></code>, it is parsed as a hexadecimal number</li>
<li>if the number starts with <code class="docutils literal notranslate"><span class="pre">0</span></code>, it is parsed as an octal number</li>
<li>if the number starts with <code class="docutils literal notranslate"><span class="pre">0b</span></code>, it is parsed as a binary number</li>
<li>otherwise, the number is parsed as a decimal number</li>
</ul>
<p>The conversion is done by calling either <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> or <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> with the
appropriate base (2, 8, 10, or 16).  If this fails, so will <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>,
although with a more useful error message.</p>
<p><code class="docutils literal notranslate"><span class="pre">&quot;float&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;complex&quot;</span></code> option arguments are converted directly with
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> and <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>, with similar error-handling.</p>
<p><code class="docutils literal notranslate"><span class="pre">&quot;choice&quot;</span></code> options are a subtype of <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code> options.  The
<a class="reference internal" href="#optparse.Option.choices" title="optparse.Option.choices"><code class="xref py py-attr docutils literal notranslate"><span class="pre">choices</span></code></a> option attribute (a sequence of strings) defines the
set of allowed option arguments.  <code class="xref py py-func docutils literal notranslate"><span class="pre">optparse.check_choice()</span></code> compares
user-supplied option arguments against this master list and raises
<code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionValueError</span></code> if an invalid string is given.</p>
</div>
<div class="section" id="parsing-arguments">
<span id="optparse-parsing-arguments"></span><h3>15.5.3.7. Parsing arguments<a class="headerlink" href="#parsing-arguments" title="Permalink to this headline">¶</a></h3>
<p>The whole point of creating and populating an OptionParser is to call its
<code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">options</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">args</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">values</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>where the input parameters are</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">args</span></code></dt>
<dd>the list of arguments to process (default: <code class="docutils literal notranslate"><span class="pre">sys.argv[1:]</span></code>)</dd>
<dt><code class="docutils literal notranslate"><span class="pre">values</span></code></dt>
<dd>an <code class="xref py py-class docutils literal notranslate"><span class="pre">optparse.Values</span></code> object to store option arguments in (default: a
new instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Values</span></code>) – if you give an existing object, the
option defaults will not be initialized on it</dd>
</dl>
<p>and the return values are</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">options</span></code></dt>
<dd>the same object that was passed in as <code class="docutils literal notranslate"><span class="pre">values</span></code>, or the optparse.Values
instance created by <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a></dd>
<dt><code class="docutils literal notranslate"><span class="pre">args</span></code></dt>
<dd>the leftover positional arguments after all options have been processed</dd>
</dl>
<p>The most common usage is to supply neither keyword argument.  If you supply
<code class="docutils literal notranslate"><span class="pre">values</span></code>, it will be modified with repeated <a class="reference internal" href="functions.html#setattr" title="setattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">setattr()</span></code></a> calls (roughly one
for every option argument stored to an option destination) and returned by
<code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code>.</p>
<p>If <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> encounters any errors in the argument list, it calls the
OptionParser’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code> method with an appropriate end-user error message.
This ultimately terminates your process with an exit status of 2 (the
traditional Unix exit status for command-line errors).</p>
</div>
<div class="section" id="querying-and-manipulating-your-option-parser">
<span id="optparse-querying-manipulating-option-parser"></span><h3>15.5.3.8. Querying and manipulating your option parser<a class="headerlink" href="#querying-and-manipulating-your-option-parser" title="Permalink to this headline">¶</a></h3>
<p>The default behavior of the option parser can be customized slightly, and you
can also poke around your option parser and see what’s there.  OptionParser
provides several methods to help you out:</p>
<dl class="method">
<dt id="optparse.OptionParser.disable_interspersed_args">
<code class="descclassname">OptionParser.</code><code class="descname">disable_interspersed_args</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.disable_interspersed_args" title="Permalink to this definition">¶</a></dt>
<dd><p>Set parsing to stop on the first non-option.  For example, if <code class="docutils literal notranslate"><span class="pre">-a</span></code> and
<code class="docutils literal notranslate"><span class="pre">-b</span></code> are both simple options that take no arguments, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
normally accepts this syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">prog</span> <span class="o">-</span><span class="n">a</span> <span class="n">arg1</span> <span class="o">-</span><span class="n">b</span> <span class="n">arg2</span>
</pre></div>
</div>
<p>and treats it as equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">prog</span> <span class="o">-</span><span class="n">a</span> <span class="o">-</span><span class="n">b</span> <span class="n">arg1</span> <span class="n">arg2</span>
</pre></div>
</div>
<p>To disable this feature, call <a class="reference internal" href="#optparse.OptionParser.disable_interspersed_args" title="optparse.OptionParser.disable_interspersed_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">disable_interspersed_args()</span></code></a>.  This
restores traditional Unix syntax, where option parsing stops with the first
non-option argument.</p>
<p>Use this if you have a command processor which runs another command which has
options of its own and you want to make sure these options don’t get
confused.  For example, each command might have a different set of options.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.enable_interspersed_args">
<code class="descclassname">OptionParser.</code><code class="descname">enable_interspersed_args</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.enable_interspersed_args" title="Permalink to this definition">¶</a></dt>
<dd><p>Set parsing to not stop on the first non-option, allowing interspersing
switches with command arguments.  This is the default behavior.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.get_option">
<code class="descclassname">OptionParser.</code><code class="descname">get_option</code><span class="sig-paren">(</span><em>opt_str</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.get_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the Option instance with the option string <em>opt_str</em>, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
no options have that option string.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.has_option">
<code class="descclassname">OptionParser.</code><code class="descname">has_option</code><span class="sig-paren">(</span><em>opt_str</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.has_option" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the OptionParser has an option with option string <em>opt_str</em>
(e.g., <code class="docutils literal notranslate"><span class="pre">-q</span></code> or <code class="docutils literal notranslate"><span class="pre">--verbose</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.remove_option">
<code class="descclassname">OptionParser.</code><code class="descname">remove_option</code><span class="sig-paren">(</span><em>opt_str</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.remove_option" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> has an option corresponding to <em>opt_str</em>, that
option is removed.  If that option provided any other option strings, all of
those option strings become invalid. If <em>opt_str</em> does not occur in any
option belonging to this <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a>, raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="conflicts-between-options">
<span id="optparse-conflicts-between-options"></span><h3>15.5.3.9. Conflicts between options<a class="headerlink" href="#conflicts-between-options" title="Permalink to this headline">¶</a></h3>
<p>If you’re not careful, it’s easy to define options with conflicting option
strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="s2">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="s2">&quot;--noisy&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>(This is particularly true if you’ve defined your own OptionParser subclass with
some standard options.)</p>
<p>Every time you add an option, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> checks for conflicts with existing
options.  If it finds any, it invokes the current conflict-handling mechanism.
You can set the conflict-handling mechanism either in the constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="o">...</span><span class="p">,</span> <span class="n">conflict_handler</span><span class="o">=</span><span class="n">handler</span><span class="p">)</span>
</pre></div>
</div>
<p>or with a separate call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">set_conflict_handler</span><span class="p">(</span><span class="n">handler</span><span class="p">)</span>
</pre></div>
</div>
<p>The available conflict handlers are:</p>
<blockquote>
<div><dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">&quot;error&quot;</span></code> (default)</dt>
<dd>assume option conflicts are a programming error and raise
<code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionConflictError</span></code></dd>
<dt><code class="docutils literal notranslate"><span class="pre">&quot;resolve&quot;</span></code></dt>
<dd>resolve option conflicts intelligently (see below)</dd>
</dl>
</div></blockquote>
<p>As an example, let’s define an <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a> that resolves conflicts
intelligently and add conflicting options to it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">conflict_handler</span><span class="o">=</span><span class="s2">&quot;resolve&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="s2">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;do no harm&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-n&quot;</span><span class="p">,</span> <span class="s2">&quot;--noisy&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;be noisy&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>At this point, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> detects that a previously-added option is already
using the <code class="docutils literal notranslate"><span class="pre">-n</span></code> option string.  Since <code class="docutils literal notranslate"><span class="pre">conflict_handler</span></code> is <code class="docutils literal notranslate"><span class="pre">&quot;resolve&quot;</span></code>,
it resolves the situation by removing <code class="docutils literal notranslate"><span class="pre">-n</span></code> from the earlier option’s list of
option strings.  Now <code class="docutils literal notranslate"><span class="pre">--dry-run</span></code> is the only way for the user to activate
that option.  If the user asks for help, the help message will reflect that:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Options</span><span class="p">:</span>
  <span class="o">--</span><span class="n">dry</span><span class="o">-</span><span class="n">run</span>     <span class="n">do</span> <span class="n">no</span> <span class="n">harm</span>
  <span class="o">...</span>
  <span class="o">-</span><span class="n">n</span><span class="p">,</span> <span class="o">--</span><span class="n">noisy</span>   <span class="n">be</span> <span class="n">noisy</span>
</pre></div>
</div>
<p>It’s possible to whittle away the option strings for a previously-added option
until there are none left, and the user has no way of invoking that option from
the command-line.  In that case, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> removes that option completely,
so it doesn’t show up in help text or anywhere else. Carrying on with our
existing OptionParser:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--dry-run&quot;</span><span class="p">,</span> <span class="o">...</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s2">&quot;new dry-run option&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>At this point, the original <code class="docutils literal notranslate"><span class="pre">-n</span></code>/<code class="docutils literal notranslate"><span class="pre">--dry-run</span></code> option is no longer
accessible, so <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> removes it, leaving this help text:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Options</span><span class="p">:</span>
  <span class="o">...</span>
  <span class="o">-</span><span class="n">n</span><span class="p">,</span> <span class="o">--</span><span class="n">noisy</span>   <span class="n">be</span> <span class="n">noisy</span>
  <span class="o">--</span><span class="n">dry</span><span class="o">-</span><span class="n">run</span>     <span class="n">new</span> <span class="n">dry</span><span class="o">-</span><span class="n">run</span> <span class="n">option</span>
</pre></div>
</div>
</div>
<div class="section" id="cleanup">
<span id="optparse-cleanup"></span><h3>15.5.3.10. Cleanup<a class="headerlink" href="#cleanup" title="Permalink to this headline">¶</a></h3>
<p>OptionParser instances have several cyclic references.  This should not be a
problem for Python’s garbage collector, but you may wish to break the cyclic
references explicitly by calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">destroy()</span></code> on your
OptionParser once you are done with it.  This is particularly useful in
long-running applications where large object graphs are reachable from your
OptionParser.</p>
</div>
<div class="section" id="other-methods">
<span id="optparse-other-methods"></span><h3>15.5.3.11. Other methods<a class="headerlink" href="#other-methods" title="Permalink to this headline">¶</a></h3>
<p>OptionParser supports several other public methods:</p>
<dl class="method">
<dt id="optparse.OptionParser.set_usage">
<code class="descclassname">OptionParser.</code><code class="descname">set_usage</code><span class="sig-paren">(</span><em>usage</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.set_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the usage string according to the rules described above for the <code class="docutils literal notranslate"><span class="pre">usage</span></code>
constructor keyword argument.  Passing <code class="docutils literal notranslate"><span class="pre">None</span></code> sets the default usage
string; use <code class="xref py py-data docutils literal notranslate"><span class="pre">optparse.SUPPRESS_USAGE</span></code> to suppress a usage message.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.print_usage">
<code class="descclassname">OptionParser.</code><code class="descname">print_usage</code><span class="sig-paren">(</span><em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.print_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the usage message for the current program (<code class="docutils literal notranslate"><span class="pre">self.usage</span></code>) to <em>file</em>
(default stdout).  Any occurrence of the string <code class="docutils literal notranslate"><span class="pre">%prog</span></code> in <code class="docutils literal notranslate"><span class="pre">self.usage</span></code>
is replaced with the name of the current program.  Does nothing if
<code class="docutils literal notranslate"><span class="pre">self.usage</span></code> is empty or not defined.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.get_usage">
<code class="descclassname">OptionParser.</code><code class="descname">get_usage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.get_usage" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#optparse.OptionParser.print_usage" title="optparse.OptionParser.print_usage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_usage()</span></code></a> but returns the usage string instead of
printing it.</p>
</dd></dl>

<dl class="method">
<dt id="optparse.OptionParser.set_defaults">
<code class="descclassname">OptionParser.</code><code class="descname">set_defaults</code><span class="sig-paren">(</span><em>dest=value</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#optparse.OptionParser.set_defaults" title="Permalink to this definition">¶</a></dt>
<dd><p>Set default values for several option destinations at once.  Using
<a class="reference internal" href="#optparse.OptionParser.set_defaults" title="optparse.OptionParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a> is the preferred way to set default values for options,
since multiple options can share the same destination.  For example, if
several “mode” options all set the same destination, any one of them can set
the default, and the last one wins:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--advanced&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s2">&quot;advanced&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s2">&quot;novice&quot;</span><span class="p">)</span>    <span class="c1"># overridden below</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--novice&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s2">&quot;novice&quot;</span><span class="p">,</span>
                  <span class="n">default</span><span class="o">=</span><span class="s2">&quot;advanced&quot;</span><span class="p">)</span>  <span class="c1"># overrides above setting</span>
</pre></div>
</div>
<p>To avoid this confusion, use <a class="reference internal" href="#optparse.OptionParser.set_defaults" title="optparse.OptionParser.set_defaults"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_defaults()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">set_defaults</span><span class="p">(</span><span class="n">mode</span><span class="o">=</span><span class="s2">&quot;advanced&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--advanced&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s2">&quot;advanced&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--novice&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_const&quot;</span><span class="p">,</span>
                  <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;mode&quot;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s2">&quot;novice&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="option-callbacks">
<span id="optparse-option-callbacks"></span><h2>15.5.4. Option Callbacks<a class="headerlink" href="#option-callbacks" title="Permalink to this headline">¶</a></h2>
<p>When <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s built-in actions and types aren’t quite enough for your
needs, you have two choices: extend <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> or define a callback option.
Extending <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> is more general, but overkill for a lot of simple
cases.  Quite often a simple callback is all you need.</p>
<p>There are two steps to defining a callback option:</p>
<ul class="simple">
<li>define the option itself using the <code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code> action</li>
<li>write the callback; this is a function (or method) that takes at least four
arguments, as described below</li>
</ul>
<div class="section" id="defining-a-callback-option">
<span id="optparse-defining-callback-option"></span><h3>15.5.4.1. Defining a callback option<a class="headerlink" href="#defining-a-callback-option" title="Permalink to this headline">¶</a></h3>
<p>As always, the easiest way to define a callback option is by using the
<a class="reference internal" href="#optparse.OptionParser.add_option" title="optparse.OptionParser.add_option"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.add_option()</span></code></a> method.  Apart from <a class="reference internal" href="#optparse.Option.action" title="optparse.Option.action"><code class="xref py py-attr docutils literal notranslate"><span class="pre">action</span></code></a>, the
only option attribute you must specify is <code class="docutils literal notranslate"><span class="pre">callback</span></code>, the function to call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">my_callback</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">callback</span></code> is a function (or other callable object), so you must have already
defined <code class="docutils literal notranslate"><span class="pre">my_callback()</span></code> when you create this callback option. In this simple
case, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> doesn’t even know if <code class="docutils literal notranslate"><span class="pre">-c</span></code> takes any arguments,
which usually means that the option takes no arguments—the mere presence of
<code class="docutils literal notranslate"><span class="pre">-c</span></code> on the command-line is all it needs to know.  In some
circumstances, though, you might want your callback to consume an arbitrary
number of command-line arguments.  This is where writing callbacks gets tricky;
it’s covered later in this section.</p>
<p><a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> always passes four particular arguments to your callback, and it
will only pass additional arguments if you specify them via
<a class="reference internal" href="#optparse.Option.callback_args" title="optparse.Option.callback_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_args</span></code></a> and <a class="reference internal" href="#optparse.Option.callback_kwargs" title="optparse.Option.callback_kwargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_kwargs</span></code></a>.  Thus, the
minimal callback function signature is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_callback</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
</pre></div>
</div>
<p>The four arguments to a callback are described below.</p>
<p>There are several other option attributes that you can supply when you define a
callback option:</p>
<dl class="docutils">
<dt><a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a></dt>
<dd>has its usual meaning: as with the <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code> actions, it
instructs <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> to consume one argument and convert it to
<a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>.  Rather than storing the converted value(s) anywhere,
though, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> passes it to your callback function.</dd>
<dt><a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a></dt>
<dd>also has its usual meaning: if it is supplied and &gt; 1, <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will
consume <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a> arguments, each of which must be convertible to
<a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>.  It then passes a tuple of converted values to your
callback.</dd>
<dt><a class="reference internal" href="#optparse.Option.callback_args" title="optparse.Option.callback_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_args</span></code></a></dt>
<dd>a tuple of extra positional arguments to pass to the callback</dd>
<dt><a class="reference internal" href="#optparse.Option.callback_kwargs" title="optparse.Option.callback_kwargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_kwargs</span></code></a></dt>
<dd>a dictionary of extra keyword arguments to pass to the callback</dd>
</dl>
</div>
<div class="section" id="how-callbacks-are-called">
<span id="optparse-how-callbacks-called"></span><h3>15.5.4.2. How callbacks are called<a class="headerlink" href="#how-callbacks-are-called" title="Permalink to this headline">¶</a></h3>
<p>All callbacks are called as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">func</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>
</div>
<p>where</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">option</span></code></dt>
<dd>is the Option instance that’s calling the callback</dd>
<dt><code class="docutils literal notranslate"><span class="pre">opt_str</span></code></dt>
<dd>is the option string seen on the command-line that’s triggering the callback.
(If an abbreviated long option was used, <code class="docutils literal notranslate"><span class="pre">opt_str</span></code> will be the full,
canonical option string—e.g. if the user puts <code class="docutils literal notranslate"><span class="pre">--foo</span></code> on the
command-line as an abbreviation for <code class="docutils literal notranslate"><span class="pre">--foobar</span></code>, then <code class="docutils literal notranslate"><span class="pre">opt_str</span></code> will be
<code class="docutils literal notranslate"><span class="pre">&quot;--foobar&quot;</span></code>.)</dd>
<dt><code class="docutils literal notranslate"><span class="pre">value</span></code></dt>
<dd>is the argument to this option seen on the command-line.  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> will
only expect an argument if <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> is set; the type of <code class="docutils literal notranslate"><span class="pre">value</span></code> will be
the type implied by the option’s type.  If <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> for this option is
<code class="docutils literal notranslate"><span class="pre">None</span></code> (no argument expected), then <code class="docutils literal notranslate"><span class="pre">value</span></code> will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>
&gt; 1, <code class="docutils literal notranslate"><span class="pre">value</span></code> will be a tuple of values of the appropriate type.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">parser</span></code></dt>
<dd><p class="first">is the OptionParser instance driving the whole thing, mainly useful because
you can access some other interesting data through its instance attributes:</p>
<dl class="last docutils">
<dt><code class="docutils literal notranslate"><span class="pre">parser.largs</span></code></dt>
<dd>the current list of leftover arguments, ie. arguments that have been
consumed but are neither options nor option arguments. Feel free to modify
<code class="docutils literal notranslate"><span class="pre">parser.largs</span></code>, e.g. by adding more arguments to it.  (This list will
become <code class="docutils literal notranslate"><span class="pre">args</span></code>, the second return value of <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code>.)</dd>
<dt><code class="docutils literal notranslate"><span class="pre">parser.rargs</span></code></dt>
<dd>the current list of remaining arguments, ie. with <code class="docutils literal notranslate"><span class="pre">opt_str</span></code> and
<code class="docutils literal notranslate"><span class="pre">value</span></code> (if applicable) removed, and only the arguments following them
still there.  Feel free to modify <code class="docutils literal notranslate"><span class="pre">parser.rargs</span></code>, e.g. by consuming more
arguments.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">parser.values</span></code></dt>
<dd>the object where option values are by default stored (an instance of
optparse.OptionValues).  This lets callbacks use the same mechanism as the
rest of <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> for storing option values; you don’t need to mess
around with globals or closures.  You can also access or modify the
value(s) of any options already encountered on the command-line.</dd>
</dl>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">args</span></code></dt>
<dd>is a tuple of arbitrary positional arguments supplied via the
<a class="reference internal" href="#optparse.Option.callback_args" title="optparse.Option.callback_args"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_args</span></code></a> option attribute.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">kwargs</span></code></dt>
<dd>is a dictionary of arbitrary keyword arguments supplied via
<a class="reference internal" href="#optparse.Option.callback_kwargs" title="optparse.Option.callback_kwargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">callback_kwargs</span></code></a>.</dd>
</dl>
</div>
<div class="section" id="raising-errors-in-a-callback">
<span id="optparse-raising-errors-in-callback"></span><h3>15.5.4.3. Raising errors in a callback<a class="headerlink" href="#raising-errors-in-a-callback" title="Permalink to this headline">¶</a></h3>
<p>The callback function should raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionValueError</span></code> if there are any
problems with the option or its argument(s).  <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> catches this and
terminates the program, printing the error message you supply to stderr.  Your
message should be clear, concise, accurate, and mention the option at fault.
Otherwise, the user will have a hard time figuring out what they did wrong.</p>
</div>
<div class="section" id="callback-example-1-trivial-callback">
<span id="optparse-callback-example-1"></span><h3>15.5.4.4. Callback example 1: trivial callback<a class="headerlink" href="#callback-example-1-trivial-callback" title="Permalink to this headline">¶</a></h3>
<p>Here’s an example of a callback option that takes no arguments, and simply
records that the option was seen:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">record_foo_seen</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">saw_foo</span> <span class="o">=</span> <span class="kc">True</span>

<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--foo&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">record_foo_seen</span><span class="p">)</span>
</pre></div>
</div>
<p>Of course, you could do that with the <code class="docutils literal notranslate"><span class="pre">&quot;store_true&quot;</span></code> action.</p>
</div>
<div class="section" id="callback-example-2-check-option-order">
<span id="optparse-callback-example-2"></span><h3>15.5.4.5. Callback example 2: check option order<a class="headerlink" href="#callback-example-2-check-option-order" title="Permalink to this headline">¶</a></h3>
<p>Here’s a slightly more interesting example: record the fact that <code class="docutils literal notranslate"><span class="pre">-a</span></code> is
seen, but blow up if it comes after <code class="docutils literal notranslate"><span class="pre">-b</span></code> in the command-line.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">check_order</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s2">&quot;can&#39;t use -a after -b&quot;</span><span class="p">)</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">1</span>
<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-a&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-b&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;b&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-example-3-check-option-order-generalized">
<span id="optparse-callback-example-3"></span><h3>15.5.4.6. Callback example 3: check option order (generalized)<a class="headerlink" href="#callback-example-3-check-option-order-generalized" title="Permalink to this headline">¶</a></h3>
<p>If you want to re-use this callback for several similar options (set a flag, but
blow up if <code class="docutils literal notranslate"><span class="pre">-b</span></code> has already been seen), it needs a bit of work: the error
message and the flag that it sets must be generalized.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">check_order</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="o">.</span><span class="n">b</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s2">&quot;can&#39;t use </span><span class="si">%s</span><span class="s2"> after -b&quot;</span> <span class="o">%</span> <span class="n">opt_str</span><span class="p">)</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-a&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-b&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store_true&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;b&quot;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_order</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;c&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="callback-example-4-check-arbitrary-condition">
<span id="optparse-callback-example-4"></span><h3>15.5.4.7. Callback example 4: check arbitrary condition<a class="headerlink" href="#callback-example-4-check-arbitrary-condition" title="Permalink to this headline">¶</a></h3>
<p>Of course, you could put any condition in there—you’re not limited to checking
the values of already-defined options.  For example, if you have options that
should not be called when the moon is full, all you have to do is this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">check_moon</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">is_moon_full</span><span class="p">():</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> option invalid when moon is full&quot;</span>
                               <span class="o">%</span> <span class="n">opt_str</span><span class="p">)</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--foo&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">check_moon</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;foo&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>(The definition of <code class="docutils literal notranslate"><span class="pre">is_moon_full()</span></code> is left as an exercise for the reader.)</p>
</div>
<div class="section" id="callback-example-5-fixed-arguments">
<span id="optparse-callback-example-5"></span><h3>15.5.4.8. Callback example 5: fixed arguments<a class="headerlink" href="#callback-example-5-fixed-arguments" title="Permalink to this headline">¶</a></h3>
<p>Things get slightly more interesting when you define callback options that take
a fixed number of arguments.  Specifying that a callback option takes arguments
is similar to defining a <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code> option: if you define
<a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a>, then the option takes one argument that must be
convertible to that type; if you further define <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a>, then the
option takes <a class="reference internal" href="#optparse.Option.nargs" title="optparse.Option.nargs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nargs</span></code></a> arguments.</p>
<p>Here’s an example that just emulates the standard <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code> action:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">store_value</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;--foo&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">store_value</span><span class="p">,</span>
                  <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;int&quot;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;foo&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> takes care of consuming 3 arguments and converting
them to integers for you; all you have to do is store them.  (Or whatever;
obviously you don’t need a callback for this example.)</p>
</div>
<div class="section" id="callback-example-6-variable-arguments">
<span id="optparse-callback-example-6"></span><h3>15.5.4.9. Callback example 6: variable arguments<a class="headerlink" href="#callback-example-6-variable-arguments" title="Permalink to this headline">¶</a></h3>
<p>Things get hairy when you want an option to take a variable number of arguments.
For this case, you must write a callback, as <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> doesn’t provide any
built-in capabilities for it.  And you have to deal with certain intricacies of
conventional Unix command-line parsing that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> normally handles for
you.  In particular, callbacks should implement the conventional rules for bare
<code class="docutils literal notranslate"><span class="pre">--</span></code> and <code class="docutils literal notranslate"><span class="pre">-</span></code> arguments:</p>
<ul class="simple">
<li>either <code class="docutils literal notranslate"><span class="pre">--</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code> can be option arguments</li>
<li>bare <code class="docutils literal notranslate"><span class="pre">--</span></code> (if not the argument to some option): halt command-line
processing and discard the <code class="docutils literal notranslate"><span class="pre">--</span></code></li>
<li>bare <code class="docutils literal notranslate"><span class="pre">-</span></code> (if not the argument to some option): halt command-line
processing but keep the <code class="docutils literal notranslate"><span class="pre">-</span></code> (append it to <code class="docutils literal notranslate"><span class="pre">parser.largs</span></code>)</li>
</ul>
<p>If you want an option that takes a variable number of arguments, there are
several subtle, tricky issues to worry about.  The exact implementation you
choose will be based on which trade-offs you’re willing to make for your
application (which is why <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> doesn’t support this sort of thing
directly).</p>
<p>Nevertheless, here’s a stab at a callback for an option with variable
arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">vararg_callback</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt_str</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
    <span class="k">assert</span> <span class="n">value</span> <span class="ow">is</span> <span class="kc">None</span>
    <span class="n">value</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">def</span> <span class="nf">floatable</span><span class="p">(</span><span class="nb">str</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="nb">float</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>
            <span class="k">return</span> <span class="kc">True</span>
        <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
            <span class="k">return</span> <span class="kc">False</span>

    <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">parser</span><span class="o">.</span><span class="n">rargs</span><span class="p">:</span>
        <span class="c1"># stop on --foo like options</span>
        <span class="k">if</span> <span class="n">arg</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&quot;--&quot;</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">2</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="c1"># stop on -a, but not on -3 or -3.0</span>
        <span class="k">if</span> <span class="n">arg</span><span class="p">[:</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&quot;-&quot;</span> <span class="ow">and</span> <span class="nb">len</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">1</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">floatable</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span>
            <span class="k">break</span>
        <span class="n">value</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>

    <span class="k">del</span> <span class="n">parser</span><span class="o">.</span><span class="n">rargs</span><span class="p">[:</span><span class="nb">len</span><span class="p">(</span><span class="n">value</span><span class="p">)]</span>
    <span class="nb">setattr</span><span class="p">(</span><span class="n">parser</span><span class="o">.</span><span class="n">values</span><span class="p">,</span> <span class="n">option</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>

<span class="o">...</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="s2">&quot;--callback&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;vararg_attr&quot;</span><span class="p">,</span>
                  <span class="n">action</span><span class="o">=</span><span class="s2">&quot;callback&quot;</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="n">vararg_callback</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="extending-optparse">
<span id="optparse-extending-optparse"></span><h2>15.5.5. Extending <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a><a class="headerlink" href="#extending-optparse" title="Permalink to this headline">¶</a></h2>
<p>Since the two major controlling factors in how <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> interprets
command-line options are the action and type of each option, the most likely
direction of extension is to add new actions and new types.</p>
<div class="section" id="adding-new-types">
<span id="optparse-adding-new-types"></span><h3>15.5.5.1. Adding new types<a class="headerlink" href="#adding-new-types" title="Permalink to this headline">¶</a></h3>
<p>To add new types, you need to define your own subclass of <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s
<code class="xref py py-class docutils literal notranslate"><span class="pre">Option</span></code> class.  This class has a couple of attributes that define
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s types: <a class="reference internal" href="#optparse.Option.TYPES" title="optparse.Option.TYPES"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPES</span></code></a> and <a class="reference internal" href="#optparse.Option.TYPE_CHECKER" title="optparse.Option.TYPE_CHECKER"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPE_CHECKER</span></code></a>.</p>
<dl class="attribute">
<dt id="optparse.Option.TYPES">
<code class="descclassname">Option.</code><code class="descname">TYPES</code><a class="headerlink" href="#optparse.Option.TYPES" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of type names; in your subclass, simply define a new tuple
<a class="reference internal" href="#optparse.Option.TYPES" title="optparse.Option.TYPES"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPES</span></code></a> that builds on the standard one.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.TYPE_CHECKER">
<code class="descclassname">Option.</code><code class="descname">TYPE_CHECKER</code><a class="headerlink" href="#optparse.Option.TYPE_CHECKER" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping type names to type-checking functions.  A type-checking
function has the following signature:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">check_mytype</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>where <code class="docutils literal notranslate"><span class="pre">option</span></code> is an <code class="xref py py-class docutils literal notranslate"><span class="pre">Option</span></code> instance, <code class="docutils literal notranslate"><span class="pre">opt</span></code> is an option string
(e.g., <code class="docutils literal notranslate"><span class="pre">-f</span></code>), and <code class="docutils literal notranslate"><span class="pre">value</span></code> is the string from the command line that must
be checked and converted to your desired type.  <code class="docutils literal notranslate"><span class="pre">check_mytype()</span></code> should
return an object of the hypothetical type <code class="docutils literal notranslate"><span class="pre">mytype</span></code>.  The value returned by
a type-checking function will wind up in the OptionValues instance returned
by <code class="xref py py-meth docutils literal notranslate"><span class="pre">OptionParser.parse_args()</span></code>, or be passed to a callback as the
<code class="docutils literal notranslate"><span class="pre">value</span></code> parameter.</p>
<p>Your type-checking function should raise <code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionValueError</span></code> if it
encounters any problems.  <code class="xref py py-exc docutils literal notranslate"><span class="pre">OptionValueError</span></code> takes a single string
argument, which is passed as-is to <a class="reference internal" href="#optparse.OptionParser" title="optparse.OptionParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code></a>’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code>
method, which in turn prepends the program name and the string <code class="docutils literal notranslate"><span class="pre">&quot;error:&quot;</span></code>
and prints everything to stderr before terminating the process.</p>
</dd></dl>

<p>Here’s a silly example that demonstrates adding a <code class="docutils literal notranslate"><span class="pre">&quot;complex&quot;</span></code> option type to
parse Python-style complex numbers on the command line.  (This is even sillier
than it used to be, because <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> 1.3 added built-in support for
complex numbers, but never mind.)</p>
<p>First, the necessary imports:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">copy</span> <span class="k">import</span> <span class="n">copy</span>
<span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">Option</span><span class="p">,</span> <span class="n">OptionValueError</span>
</pre></div>
</div>
<p>You need to define your type-checker first, since it’s referred to later (in the
<a class="reference internal" href="#optparse.Option.TYPE_CHECKER" title="optparse.Option.TYPE_CHECKER"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPE_CHECKER</span></code></a> class attribute of your Option subclass):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">check_complex</span><span class="p">(</span><span class="n">option</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">complex</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">OptionValueError</span><span class="p">(</span>
            <span class="s2">&quot;option </span><span class="si">%s</span><span class="s2">: invalid complex value: </span><span class="si">%r</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">))</span>
</pre></div>
</div>
<p>Finally, the Option subclass:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyOption</span> <span class="p">(</span><span class="n">Option</span><span class="p">):</span>
    <span class="n">TYPES</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">TYPES</span> <span class="o">+</span> <span class="p">(</span><span class="s2">&quot;complex&quot;</span><span class="p">,)</span>
    <span class="n">TYPE_CHECKER</span> <span class="o">=</span> <span class="n">copy</span><span class="p">(</span><span class="n">Option</span><span class="o">.</span><span class="n">TYPE_CHECKER</span><span class="p">)</span>
    <span class="n">TYPE_CHECKER</span><span class="p">[</span><span class="s2">&quot;complex&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">check_complex</span>
</pre></div>
</div>
<p>(If we didn’t make a <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-func docutils literal notranslate"><span class="pre">copy()</span></code></a> of <a class="reference internal" href="#optparse.Option.TYPE_CHECKER" title="optparse.Option.TYPE_CHECKER"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Option.TYPE_CHECKER</span></code></a>, we would end
up modifying the <a class="reference internal" href="#optparse.Option.TYPE_CHECKER" title="optparse.Option.TYPE_CHECKER"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPE_CHECKER</span></code></a> attribute of <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s
Option class.  This being Python, nothing stops you from doing that except good
manners and common sense.)</p>
<p>That’s it!  Now you can write a script that uses the new option type just like
any other <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>-based script, except you have to instruct your
OptionParser to use MyOption instead of Option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_class</span><span class="o">=</span><span class="n">MyOption</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;complex&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Alternately, you can build your own option list and pass it to OptionParser; if
you don’t use <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_option()</span></code> in the above way, you don’t need to tell
OptionParser which option class to use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">option_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">MyOption</span><span class="p">(</span><span class="s2">&quot;-c&quot;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s2">&quot;store&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s2">&quot;complex&quot;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s2">&quot;c&quot;</span><span class="p">)]</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">(</span><span class="n">option_list</span><span class="o">=</span><span class="n">option_list</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="adding-new-actions">
<span id="optparse-adding-new-actions"></span><h3>15.5.5.2. Adding new actions<a class="headerlink" href="#adding-new-actions" title="Permalink to this headline">¶</a></h3>
<p>Adding new actions is a bit trickier, because you have to understand that
<a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> has a couple of classifications for actions:</p>
<dl class="docutils">
<dt>“store” actions</dt>
<dd>actions that result in <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> storing a value to an attribute of the
current OptionValues instance; these options require a <a class="reference internal" href="#optparse.Option.dest" title="optparse.Option.dest"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dest</span></code></a>
attribute to be supplied to the Option constructor.</dd>
<dt>“typed” actions</dt>
<dd>actions that take a value from the command line and expect it to be of a
certain type; or rather, a string that can be converted to a certain type.
These options require a <a class="reference internal" href="#optparse.Option.type" title="optparse.Option.type"><code class="xref py py-attr docutils literal notranslate"><span class="pre">type</span></code></a> attribute to the Option
constructor.</dd>
</dl>
<p>These are overlapping sets: some default “store” actions are <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;store_const&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;count&quot;</span></code>, while the default “typed”
actions are <code class="docutils literal notranslate"><span class="pre">&quot;store&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;callback&quot;</span></code>.</p>
<p>When you add an action, you need to categorize it by listing it in at least one
of the following class attributes of Option (all are lists of strings):</p>
<dl class="attribute">
<dt id="optparse.Option.ACTIONS">
<code class="descclassname">Option.</code><code class="descname">ACTIONS</code><a class="headerlink" href="#optparse.Option.ACTIONS" title="Permalink to this definition">¶</a></dt>
<dd><p>All actions must be listed in ACTIONS.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.STORE_ACTIONS">
<code class="descclassname">Option.</code><code class="descname">STORE_ACTIONS</code><a class="headerlink" href="#optparse.Option.STORE_ACTIONS" title="Permalink to this definition">¶</a></dt>
<dd><p>“store” actions are additionally listed here.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.TYPED_ACTIONS">
<code class="descclassname">Option.</code><code class="descname">TYPED_ACTIONS</code><a class="headerlink" href="#optparse.Option.TYPED_ACTIONS" title="Permalink to this definition">¶</a></dt>
<dd><p>“typed” actions are additionally listed here.</p>
</dd></dl>

<dl class="attribute">
<dt id="optparse.Option.ALWAYS_TYPED_ACTIONS">
<code class="descclassname">Option.</code><code class="descname">ALWAYS_TYPED_ACTIONS</code><a class="headerlink" href="#optparse.Option.ALWAYS_TYPED_ACTIONS" title="Permalink to this definition">¶</a></dt>
<dd><p>Actions that always take a type (i.e. whose options always take a value) are
additionally listed here.  The only effect of this is that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
assigns the default type, <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code>, to options with no explicit type
whose action is listed in <a class="reference internal" href="#optparse.Option.ALWAYS_TYPED_ACTIONS" title="optparse.Option.ALWAYS_TYPED_ACTIONS"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ALWAYS_TYPED_ACTIONS</span></code></a>.</p>
</dd></dl>

<p>In order to actually implement your new action, you must override Option’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">take_action()</span></code> method and add a case that recognizes your action.</p>
<p>For example, let’s add an <code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> action.  This is similar to the standard
<code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code> action, but instead of taking a single value from the command-line
and appending it to an existing list, <code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> will take multiple values in
a single comma-delimited string, and extend an existing list with them.  That
is, if <code class="docutils literal notranslate"><span class="pre">--names</span></code> is an <code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> option of type <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code>, the command
line</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">--</span><span class="n">names</span><span class="o">=</span><span class="n">foo</span><span class="p">,</span><span class="n">bar</span> <span class="o">--</span><span class="n">names</span> <span class="n">blah</span> <span class="o">--</span><span class="n">names</span> <span class="n">ding</span><span class="p">,</span><span class="n">dong</span>
</pre></div>
</div>
<p>would result in a list</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">,</span> <span class="s2">&quot;blah&quot;</span><span class="p">,</span> <span class="s2">&quot;ding&quot;</span><span class="p">,</span> <span class="s2">&quot;dong&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>Again we define a subclass of Option:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyOption</span><span class="p">(</span><span class="n">Option</span><span class="p">):</span>

    <span class="n">ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s2">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">STORE_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">STORE_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s2">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">TYPED_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">TYPED_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s2">&quot;extend&quot;</span><span class="p">,)</span>
    <span class="n">ALWAYS_TYPED_ACTIONS</span> <span class="o">=</span> <span class="n">Option</span><span class="o">.</span><span class="n">ALWAYS_TYPED_ACTIONS</span> <span class="o">+</span> <span class="p">(</span><span class="s2">&quot;extend&quot;</span><span class="p">,)</span>

    <span class="k">def</span> <span class="nf">take_action</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">parser</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">action</span> <span class="o">==</span> <span class="s2">&quot;extend&quot;</span><span class="p">:</span>
            <span class="n">lvalue</span> <span class="o">=</span> <span class="n">value</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;,&quot;</span><span class="p">)</span>
            <span class="n">values</span><span class="o">.</span><span class="n">ensure_value</span><span class="p">(</span><span class="n">dest</span><span class="p">,</span> <span class="p">[])</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">lvalue</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">Option</span><span class="o">.</span><span class="n">take_action</span><span class="p">(</span>
                <span class="bp">self</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span> <span class="n">dest</span><span class="p">,</span> <span class="n">opt</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">values</span><span class="p">,</span> <span class="n">parser</span><span class="p">)</span>
</pre></div>
</div>
<p>Features of note:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> both expects a value on the command-line and stores that value
somewhere, so it goes in both <a class="reference internal" href="#optparse.Option.STORE_ACTIONS" title="optparse.Option.STORE_ACTIONS"><code class="xref py py-attr docutils literal notranslate"><span class="pre">STORE_ACTIONS</span></code></a> and
<a class="reference internal" href="#optparse.Option.TYPED_ACTIONS" title="optparse.Option.TYPED_ACTIONS"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TYPED_ACTIONS</span></code></a>.</p>
</li>
<li><p class="first">to ensure that <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> assigns the default type of <code class="docutils literal notranslate"><span class="pre">&quot;string&quot;</span></code> to
<code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> actions, we put the <code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code> action in
<a class="reference internal" href="#optparse.Option.ALWAYS_TYPED_ACTIONS" title="optparse.Option.ALWAYS_TYPED_ACTIONS"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ALWAYS_TYPED_ACTIONS</span></code></a> as well.</p>
</li>
<li><p class="first"><code class="xref py py-meth docutils literal notranslate"><span class="pre">MyOption.take_action()</span></code> implements just this one new action, and passes
control back to <code class="xref py py-meth docutils literal notranslate"><span class="pre">Option.take_action()</span></code> for the standard <a class="reference internal" href="#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>
actions.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">values</span></code> is an instance of the optparse_parser.Values class, which provides
the very useful <code class="xref py py-meth docutils literal notranslate"><span class="pre">ensure_value()</span></code> method. <code class="xref py py-meth docutils literal notranslate"><span class="pre">ensure_value()</span></code> is
essentially <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> with a safety valve; it is called as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">values</span><span class="o">.</span><span class="n">ensure_value</span><span class="p">(</span><span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
</pre></div>
</div>
<p>If the <code class="docutils literal notranslate"><span class="pre">attr</span></code> attribute of <code class="docutils literal notranslate"><span class="pre">values</span></code> doesn’t exist or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then
ensure_value() first sets it to <code class="docutils literal notranslate"><span class="pre">value</span></code>, and then returns ‘value. This is
very handy for actions like <code class="docutils literal notranslate"><span class="pre">&quot;extend&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;append&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;count&quot;</span></code>, all
of which accumulate data in a variable and expect that variable to be of a
certain type (a list for the first two, an integer for the latter).  Using
<code class="xref py py-meth docutils literal notranslate"><span class="pre">ensure_value()</span></code> means that scripts using your action don’t have to worry
about setting a default value for the option destinations in question; they
can just leave the default as <code class="docutils literal notranslate"><span class="pre">None</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">ensure_value()</span></code> will take care of
getting it right when it’s needed.</p>
</li>
</ul>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a><ul>
<li><a class="reference internal" href="#background">15.5.1. Background</a><ul>
<li><a class="reference internal" href="#terminology">15.5.1.1. Terminology</a></li>
<li><a class="reference internal" href="#what-are-options-for">15.5.1.2. What are options for?</a></li>
<li><a class="reference internal" href="#what-are-positional-arguments-for">15.5.1.3. What are positional arguments for?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#tutorial">15.5.2. Tutorial</a><ul>
<li><a class="reference internal" href="#understanding-option-actions">15.5.2.1. Understanding option actions</a></li>
<li><a class="reference internal" href="#the-store-action">15.5.2.2. The store action</a></li>
<li><a class="reference internal" href="#handling-boolean-flag-options">15.5.2.3. Handling boolean (flag) options</a></li>
<li><a class="reference internal" href="#other-actions">15.5.2.4. Other actions</a></li>
<li><a class="reference internal" href="#default-values">15.5.2.5. Default values</a></li>
<li><a class="reference internal" href="#generating-help">15.5.2.6. Generating help</a><ul>
<li><a class="reference internal" href="#grouping-options">15.5.2.6.1. Grouping Options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#printing-a-version-string">15.5.2.7. Printing a version string</a></li>
<li><a class="reference internal" href="#how-optparse-handles-errors">15.5.2.8. How <code class="docutils literal notranslate"><span class="pre">optparse</span></code> handles errors</a></li>
<li><a class="reference internal" href="#putting-it-all-together">15.5.2.9. Putting it all together</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reference-guide">15.5.3. Reference Guide</a><ul>
<li><a class="reference internal" href="#creating-the-parser">15.5.3.1. Creating the parser</a></li>
<li><a class="reference internal" href="#populating-the-parser">15.5.3.2. Populating the parser</a></li>
<li><a class="reference internal" href="#defining-options">15.5.3.3. Defining options</a></li>
<li><a class="reference internal" href="#option-attributes">15.5.3.4. Option attributes</a></li>
<li><a class="reference internal" href="#standard-option-actions">15.5.3.5. Standard option actions</a></li>
<li><a class="reference internal" href="#standard-option-types">15.5.3.6. Standard option types</a></li>
<li><a class="reference internal" href="#parsing-arguments">15.5.3.7. Parsing arguments</a></li>
<li><a class="reference internal" href="#querying-and-manipulating-your-option-parser">15.5.3.8. Querying and manipulating your option parser</a></li>
<li><a class="reference internal" href="#conflicts-between-options">15.5.3.9. Conflicts between options</a></li>
<li><a class="reference internal" href="#cleanup">15.5.3.10. Cleanup</a></li>
<li><a class="reference internal" href="#other-methods">15.5.3.11. Other methods</a></li>
</ul>
</li>
<li><a class="reference internal" href="#option-callbacks">15.5.4. Option Callbacks</a><ul>
<li><a class="reference internal" href="#defining-a-callback-option">15.5.4.1. Defining a callback option</a></li>
<li><a class="reference internal" href="#how-callbacks-are-called">15.5.4.2. How callbacks are called</a></li>
<li><a class="reference internal" href="#raising-errors-in-a-callback">15.5.4.3. Raising errors in a callback</a></li>
<li><a class="reference internal" href="#callback-example-1-trivial-callback">15.5.4.4. Callback example 1: trivial callback</a></li>
<li><a class="reference internal" href="#callback-example-2-check-option-order">15.5.4.5. Callback example 2: check option order</a></li>
<li><a class="reference internal" href="#callback-example-3-check-option-order-generalized">15.5.4.6. Callback example 3: check option order (generalized)</a></li>
<li><a class="reference internal" href="#callback-example-4-check-arbitrary-condition">15.5.4.7. Callback example 4: check arbitrary condition</a></li>
<li><a class="reference internal" href="#callback-example-5-fixed-arguments">15.5.4.8. Callback example 5: fixed arguments</a></li>
<li><a class="reference internal" href="#callback-example-6-variable-arguments">15.5.4.9. Callback example 6: variable arguments</a></li>
</ul>
</li>
<li><a class="reference internal" href="#extending-optparse">15.5.5. Extending <code class="docutils literal notranslate"><span class="pre">optparse</span></code></a><ul>
<li><a class="reference internal" href="#adding-new-types">15.5.5.1. Adding new types</a></li>
<li><a class="reference internal" href="#adding-new-actions">15.5.5.2. Adding new actions</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="argparse.html"
                        title="previous chapter">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="getopt.html"
                        title="next chapter">15.6. <code class="docutils literal notranslate"><span class="pre">getopt</span></code> — C-style parser for command line options</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/optparse.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="getopt.html" title="15.6. getopt — C-style parser for command line options"
             >next</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="15.4. argparse — Parser for command-line options, arguments and sub-commands"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\O�C�C�html/library/os.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.1. os — Miscellaneous operating system interfaces &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.2. io — Core tools for working with streams" href="io.html" />
    <link rel="prev" title="15. Generic Operating System Services" href="allos.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/os.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="io.html" title="15.2. io — Core tools for working with streams"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="allos.html" title="15. Generic Operating System Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-os">
<span id="os-miscellaneous-operating-system-interfaces"></span><h1>15.1. <a class="reference internal" href="#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> — Miscellaneous operating system interfaces<a class="headerlink" href="#module-os" title="Permalink to this headline">¶</a></h1>
<p>This module provides a portable way of using operating system dependent
functionality.  If you just want to read or write a file see <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, if
you want to manipulate paths, see the <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, and if you want to
read all the lines in all the files on the command line see the <a class="reference internal" href="fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a>
module.  For creating temporary files and directories see the <a class="reference internal" href="tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a>
module, and for high-level file and directory handling see the <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a>
module.</p>
<p>Notes on the availability of these functions:</p>
<ul class="simple">
<li>The design of all built-in operating system dependent modules of Python is
such that as long as the same functionality is available, it uses the same
interface; for example, the function <code class="docutils literal notranslate"><span class="pre">os.stat(path)</span></code> returns stat
information about <em>path</em> in the same format (which happens to have originated
with the POSIX interface).</li>
<li>Extensions peculiar to a particular operating system are also available
through the <a class="reference internal" href="#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module, but using them is of course a threat to
portability.</li>
<li>An “Availability: Unix” note means that this function is commonly found on
Unix systems.  It does not make any claims about its existence on a specific
operating system.</li>
<li>If not separately noted, all functions that claim “Availability: Unix” are
supported on Mac OS X, which builds on a Unix core.</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">All functions in this module raise <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> in the case of invalid or
inaccessible file names and paths, or other arguments that have the correct
type, but are not accepted by the operating system.</p>
</div>
<dl class="exception">
<dt id="os.error">
<em class="property">exception </em><code class="descclassname">os.</code><code class="descname">error</code><a class="headerlink" href="#os.error" title="Permalink to this definition">¶</a></dt>
<dd><p>An alias for the built-in <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> exception.</p>
</dd></dl>

<dl class="data">
<dt id="os.name">
<code class="descclassname">os.</code><code class="descname">name</code><a class="headerlink" href="#os.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the operating system dependent module imported.  The following
names have currently been registered: <code class="docutils literal notranslate"><span class="pre">'posix'</span></code>, <code class="docutils literal notranslate"><span class="pre">'nt'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'os2'</span></code>, <code class="docutils literal notranslate"><span class="pre">'ce'</span></code>, <code class="docutils literal notranslate"><span class="pre">'java'</span></code>, <code class="docutils literal notranslate"><span class="pre">'riscos'</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="sys.html#sys.platform" title="sys.platform"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.platform</span></code></a> has a finer granularity.  <a class="reference internal" href="#os.uname" title="os.uname"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.uname()</span></code></a> gives
system-dependent version information.</p>
<p class="last">The <a class="reference internal" href="platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> module provides detailed checks for the
system’s identity.</p>
</div>
</dd></dl>

<div class="section" id="process-parameters">
<span id="os-procinfo"></span><h2>15.1.1. Process Parameters<a class="headerlink" href="#process-parameters" title="Permalink to this headline">¶</a></h2>
<p>These functions and data items provide information and operate on the current
process and user.</p>
<dl class="data">
<dt id="os.environ">
<code class="descclassname">os.</code><code class="descname">environ</code><a class="headerlink" href="#os.environ" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a> object representing the string environment. For example,
<code class="docutils literal notranslate"><span class="pre">environ['HOME']</span></code> is the pathname of your home directory (on some platforms),
and is equivalent to <code class="docutils literal notranslate"><span class="pre">getenv(&quot;HOME&quot;)</span></code> in C.</p>
<p>This mapping is captured the first time the <a class="reference internal" href="#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module is imported,
typically during Python startup as part of processing <code class="file docutils literal notranslate"><span class="pre">site.py</span></code>.  Changes
to the environment made after this time are not reflected in <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>,
except for changes made by modifying <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> directly.</p>
<p>If the platform supports the <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> function, this mapping may be used
to modify the environment as well as query the environment.  <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> will
be called automatically when the mapping is modified.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Calling <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> directly does not change <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>, so it’s better
to modify <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On some platforms, including FreeBSD and Mac OS X, setting <code class="docutils literal notranslate"><span class="pre">environ</span></code> may
cause memory leaks.  Refer to the system documentation for
<code class="xref c c-func docutils literal notranslate"><span class="pre">putenv()</span></code>.</p>
</div>
<p>If <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> is not provided, a modified copy of this mapping  may be
passed to the appropriate process-creation functions to cause  child processes
to use a modified environment.</p>
<p>If the platform supports the <a class="reference internal" href="#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">unsetenv()</span></code></a> function, you can delete items in
this mapping to unset environment variables. <a class="reference internal" href="#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">unsetenv()</span></code></a> will be called
automatically when an item is deleted from <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>, and when
one of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> methods is called.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Also unset environment variables when calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">os.environ.clear()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">os.environ.pop()</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">os.</code><code class="descname">chdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">os.</code><code class="descname">fchdir</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">os.</code><code class="descname">getcwd</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>These functions are described in <a class="reference internal" href="#os-file-dir"><span class="std std-ref">Files and Directories</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.ctermid">
<code class="descclassname">os.</code><code class="descname">ctermid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.ctermid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the filename corresponding to the controlling terminal of the process.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getegid">
<code class="descclassname">os.</code><code class="descname">getegid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getegid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the effective group id of the current process.  This corresponds to the
“set id” bit on the file being executed in the current process.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.geteuid">
<code class="descclassname">os.</code><code class="descname">geteuid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.geteuid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Return the current process’s effective user id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getgid">
<code class="descclassname">os.</code><code class="descname">getgid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getgid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Return the real group id of the current process.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getgroups">
<code class="descclassname">os.</code><code class="descname">getgroups</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getgroups" title="Permalink to this definition">¶</a></dt>
<dd><p>Return list of supplemental group ids associated with the current process.</p>
<p>Availability: Unix.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Mac OS X, <a class="reference internal" href="#os.getgroups" title="os.getgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgroups()</span></code></a> behavior differs somewhat from
other Unix platforms. If the Python interpreter was built with a
deployment target of <code class="xref py py-const docutils literal notranslate"><span class="pre">10.5</span></code> or earlier, <a class="reference internal" href="#os.getgroups" title="os.getgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgroups()</span></code></a> returns
the list of effective group ids associated with the current user process;
this list is limited to a system-defined number of entries, typically 16,
and may be modified by calls to <a class="reference internal" href="#os.setgroups" title="os.setgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">setgroups()</span></code></a> if suitably privileged.
If built with a deployment target greater than <code class="xref py py-const docutils literal notranslate"><span class="pre">10.5</span></code>,
<a class="reference internal" href="#os.getgroups" title="os.getgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgroups()</span></code></a> returns the current group access list for the user
associated with the effective user id of the process; the group access
list may change over the lifetime of the process, it is not affected by
calls to <a class="reference internal" href="#os.setgroups" title="os.setgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">setgroups()</span></code></a>, and its length is not limited to 16.  The
deployment target value, <code class="xref py py-const docutils literal notranslate"><span class="pre">MACOSX_DEPLOYMENT_TARGET</span></code>, can be
obtained with <a class="reference internal" href="sysconfig.html#sysconfig.get_config_var" title="sysconfig.get_config_var"><code class="xref py py-func docutils literal notranslate"><span class="pre">sysconfig.get_config_var()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.initgroups">
<code class="descclassname">os.</code><code class="descname">initgroups</code><span class="sig-paren">(</span><em>username</em>, <em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.initgroups" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the system initgroups() to initialize the group access list with all of
the groups of which the specified username is a member, plus the specified
group id.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.getlogin">
<code class="descclassname">os.</code><code class="descname">getlogin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getlogin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the user logged in on the controlling terminal of the
process.  For most purposes, it is more useful to use the environment
variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LOGNAME</span></code> to find out who the user is, or
<code class="docutils literal notranslate"><span class="pre">pwd.getpwuid(os.getuid())[0]</span></code> to get the login name of the process’s real
user id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getpgid">
<code class="descclassname">os.</code><code class="descname">getpgid</code><span class="sig-paren">(</span><em>pid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.getpgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the process group id of the process with process id <em>pid</em>. If <em>pid</em> is 0,
the process group id of the current process is returned.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.getpgrp">
<code class="descclassname">os.</code><code class="descname">getpgrp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getpgrp" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Return the id of the current process group.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getpid">
<code class="descclassname">os.</code><code class="descname">getpid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getpid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Return the current process id.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.getppid">
<code class="descclassname">os.</code><code class="descname">getppid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getppid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">Return the parent’s process id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getresuid">
<code class="descclassname">os.</code><code class="descname">getresuid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getresuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple (ruid, euid, suid) denoting the current process’s
real, effective, and saved user ids.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.getresgid">
<code class="descclassname">os.</code><code class="descname">getresgid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getresgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple (rgid, egid, sgid) denoting the current process’s
real, effective, and saved group ids.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.getuid">
<code class="descclassname">os.</code><code class="descname">getuid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getuid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">Return the current process’s real user id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getenv">
<code class="descclassname">os.</code><code class="descname">getenv</code><span class="sig-paren">(</span><em>varname</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getenv" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the environment variable <em>varname</em> if it exists, or <em>value</em>
if it doesn’t.  <em>value</em> defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Availability: most flavors of Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.putenv">
<code class="descclassname">os.</code><code class="descname">putenv</code><span class="sig-paren">(</span><em>varname</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#os.putenv" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-7">Set the environment variable named <em>varname</em> to the string <em>value</em>.  Such
changes to the environment affect subprocesses started with <a class="reference internal" href="#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>,
<a class="reference internal" href="#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or <a class="reference internal" href="#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a> and <a class="reference internal" href="#os.execv" title="os.execv"><code class="xref py py-func docutils literal notranslate"><span class="pre">execv()</span></code></a>.</p>
<p>Availability: most flavors of Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On some platforms, including FreeBSD and Mac OS X, setting <code class="docutils literal notranslate"><span class="pre">environ</span></code> may
cause memory leaks. Refer to the system documentation for putenv.</p>
</div>
<p>When <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> is supported, assignments to items in <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> are
automatically translated into corresponding calls to <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a>; however,
calls to <a class="reference internal" href="#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> don’t update <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>, so it is actually
preferable to assign to items of <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="os.setegid">
<code class="descclassname">os.</code><code class="descname">setegid</code><span class="sig-paren">(</span><em>egid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setegid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s effective group id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.seteuid">
<code class="descclassname">os.</code><code class="descname">seteuid</code><span class="sig-paren">(</span><em>euid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.seteuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s effective user id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setgid">
<code class="descclassname">os.</code><code class="descname">setgid</code><span class="sig-paren">(</span><em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’ group id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setgroups">
<code class="descclassname">os.</code><code class="descname">setgroups</code><span class="sig-paren">(</span><em>groups</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setgroups" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the list of supplemental group ids associated with the current process to
<em>groups</em>. <em>groups</em> must be a sequence, and each element must be an integer
identifying a group. This operation is typically available only to the superuser.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Mac OS X, the length of <em>groups</em> may not exceed the
system-defined maximum number of effective group ids, typically 16.
See the documentation for <a class="reference internal" href="#os.getgroups" title="os.getgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">getgroups()</span></code></a> for cases where it may not
return the same group list set by calling setgroups().</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.setpgrp">
<code class="descclassname">os.</code><code class="descname">setpgrp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.setpgrp" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the system call <code class="xref c c-func docutils literal notranslate"><span class="pre">setpgrp()</span></code> or <code class="docutils literal notranslate"><span class="pre">setpgrp(0,</span> <span class="pre">0)</span></code> depending on
which version is implemented (if any).  See the Unix manual for the semantics.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setpgid">
<code class="descclassname">os.</code><code class="descname">setpgid</code><span class="sig-paren">(</span><em>pid</em>, <em>pgrp</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setpgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the system call <code class="xref c c-func docutils literal notranslate"><span class="pre">setpgid()</span></code> to set the process group id of the
process with id <em>pid</em> to the process group with id <em>pgrp</em>.  See the Unix manual
for the semantics.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setregid">
<code class="descclassname">os.</code><code class="descname">setregid</code><span class="sig-paren">(</span><em>rgid</em>, <em>egid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setregid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s real and effective group ids.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setresgid">
<code class="descclassname">os.</code><code class="descname">setresgid</code><span class="sig-paren">(</span><em>rgid</em>, <em>egid</em>, <em>sgid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setresgid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s real, effective, and saved group ids.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.setresuid">
<code class="descclassname">os.</code><code class="descname">setresuid</code><span class="sig-paren">(</span><em>ruid</em>, <em>euid</em>, <em>suid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setresuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s real, effective, and saved user ids.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.setreuid">
<code class="descclassname">os.</code><code class="descname">setreuid</code><span class="sig-paren">(</span><em>ruid</em>, <em>euid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setreuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current process’s real and effective user ids.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getsid">
<code class="descclassname">os.</code><code class="descname">getsid</code><span class="sig-paren">(</span><em>pid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.getsid" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the system call <code class="xref c c-func docutils literal notranslate"><span class="pre">getsid()</span></code>.  See the Unix manual for the semantics.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.setsid">
<code class="descclassname">os.</code><code class="descname">setsid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.setsid" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the system call <code class="xref c c-func docutils literal notranslate"><span class="pre">setsid()</span></code>.  See the Unix manual for the semantics.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.setuid">
<code class="descclassname">os.</code><code class="descname">setuid</code><span class="sig-paren">(</span><em>uid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.setuid" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-8">Set the current process’s user id.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.strerror">
<code class="descclassname">os.</code><code class="descname">strerror</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#os.strerror" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the error message corresponding to the error code in <em>code</em>.
On platforms where <code class="xref c c-func docutils literal notranslate"><span class="pre">strerror()</span></code> returns <code class="docutils literal notranslate"><span class="pre">NULL</span></code> when given an unknown
error number, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.umask">
<code class="descclassname">os.</code><code class="descname">umask</code><span class="sig-paren">(</span><em>mask</em><span class="sig-paren">)</span><a class="headerlink" href="#os.umask" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current numeric umask and return the previous umask.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.uname">
<code class="descclassname">os.</code><code class="descname">uname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.uname" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-9">Return a 5-tuple containing information identifying the current operating
system.  The tuple contains 5 strings: <code class="docutils literal notranslate"><span class="pre">(sysname,</span> <span class="pre">nodename,</span> <span class="pre">release,</span> <span class="pre">version,</span>
<span class="pre">machine)</span></code>.  Some systems truncate the nodename to 8 characters or to the
leading component; a better way to get the hostname is
<a class="reference internal" href="socket.html#socket.gethostname" title="socket.gethostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.gethostname()</span></code></a>  or even
<code class="docutils literal notranslate"><span class="pre">socket.gethostbyaddr(socket.gethostname())</span></code>.</p>
<p>Availability: recent flavors of Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.unsetenv">
<code class="descclassname">os.</code><code class="descname">unsetenv</code><span class="sig-paren">(</span><em>varname</em><span class="sig-paren">)</span><a class="headerlink" href="#os.unsetenv" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-10">Unset (delete) the environment variable named <em>varname</em>. Such changes to the
environment affect subprocesses started with <a class="reference internal" href="#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>, <a class="reference internal" href="#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or
<a class="reference internal" href="#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a> and <a class="reference internal" href="#os.execv" title="os.execv"><code class="xref py py-func docutils literal notranslate"><span class="pre">execv()</span></code></a>.</p>
<p>When <a class="reference internal" href="#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">unsetenv()</span></code></a> is supported, deletion of items in <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> is
automatically translated into a corresponding call to <a class="reference internal" href="#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">unsetenv()</span></code></a>; however,
calls to <a class="reference internal" href="#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">unsetenv()</span></code></a> don’t update <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>, so it is actually
preferable to delete items of <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>.</p>
<p>Availability: most flavors of Unix, Windows.</p>
</dd></dl>

</div>
<div class="section" id="file-object-creation">
<span id="os-newstreams"></span><h2>15.1.2. File Object Creation<a class="headerlink" href="#file-object-creation" title="Permalink to this headline">¶</a></h2>
<p>These functions create new file objects. (See also <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.)</p>
<dl class="function">
<dt id="os.fdopen">
<code class="descclassname">os.</code><code class="descname">fdopen</code><span class="sig-paren">(</span><em>fd</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.fdopen" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-11">Return an open file object connected to the file descriptor <em>fd</em>.  The <em>mode</em>
and <em>bufsize</em> arguments have the same meaning as the corresponding arguments
to the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.  If <a class="reference internal" href="#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">fdopen()</span></code></a> raises an
exception, it leaves <em>fd</em> untouched (unclosed).</p>
<p>Availability: Unix, Windows.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>When specified, the <em>mode</em> argument must now start with one of the letters
<code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, otherwise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>On Unix, when the <em>mode</em> argument starts with <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, the <em>O_APPEND</em> flag is
set on the file descriptor (which the <code class="xref c c-func docutils literal notranslate"><span class="pre">fdopen()</span></code> implementation already
does on most platforms).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.popen">
<code class="descclassname">os.</code><code class="descname">popen</code><span class="sig-paren">(</span><em>command</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.popen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a pipe to or from <em>command</em>.  The return value is an open file object
connected to the pipe, which can be read or written depending on whether <em>mode</em>
is <code class="docutils literal notranslate"><span class="pre">'r'</span></code> (default) or <code class="docutils literal notranslate"><span class="pre">'w'</span></code>. The <em>bufsize</em> argument has the same meaning as
the corresponding argument to the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.  The exit
status of the command (encoded in the format specified for <a class="reference internal" href="#os.wait" title="os.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a>) is
available as the return value of the <a class="reference internal" href="stdtypes.html#file.close" title="file.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method of the file object,
except that when the exit status is zero (termination without errors), <code class="docutils literal notranslate"><span class="pre">None</span></code>
is returned.</p>
<p>Availability: Unix, Windows.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is obsolete.  Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.  Check
especially the <a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.0: </span>This function worked unreliably under Windows in earlier versions of Python.
This was due to the use of the <code class="xref c c-func docutils literal notranslate"><span class="pre">_popen()</span></code> function from the libraries
provided with Windows.  Newer versions of Python do not use the broken
implementation from the Windows libraries.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.tmpfile">
<code class="descclassname">os.</code><code class="descname">tmpfile</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.tmpfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new file object opened in update mode (<code class="docutils literal notranslate"><span class="pre">w+b</span></code>).  The file has no
directory entries associated with it and will be automatically deleted once
there are no file descriptors for the file.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<p>There are a number of different <code class="xref py py-func docutils literal notranslate"><span class="pre">popen*()</span></code> functions that provide slightly
different ways to create subprocesses.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>All of the <code class="xref py py-func docutils literal notranslate"><span class="pre">popen*()</span></code> functions are obsolete. Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>
module.</p>
</div>
<p>For each of the <code class="xref py py-func docutils literal notranslate"><span class="pre">popen*()</span></code> variants, if <em>bufsize</em> is specified, it
specifies the buffer size for the I/O pipes. <em>mode</em>, if provided, should be the
string <code class="docutils literal notranslate"><span class="pre">'b'</span></code> or <code class="docutils literal notranslate"><span class="pre">'t'</span></code>; on Windows this is needed to determine whether the
file objects should be opened in binary or text mode.  The default value for
<em>mode</em> is <code class="docutils literal notranslate"><span class="pre">'t'</span></code>.</p>
<p>Also, for each of these variants, on Unix, <em>cmd</em> may be a sequence, in which
case arguments will be passed directly to the program without shell intervention
(as with <a class="reference internal" href="#os.spawnv" title="os.spawnv"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.spawnv()</span></code></a>). If <em>cmd</em> is a string it will be passed to the shell
(as with <a class="reference internal" href="#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>).</p>
<p>These methods do not make it possible to retrieve the exit status from the child
processes.  The only way to control the input and output streams and also
retrieve the return codes is to use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module; these are only
available on Unix.</p>
<p>For a discussion of possible deadlock conditions related to the use of these
functions, see <a class="reference internal" href="popen2.html#popen2-flow-control"><span class="std std-ref">Flow Control Issues</span></a>.</p>
<dl class="function">
<dt id="os.popen2">
<code class="descclassname">os.</code><code class="descname">popen2</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.popen2" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute <em>cmd</em> as a sub-process and return the file objects <code class="docutils literal notranslate"><span class="pre">(child_stdin,</span>
<span class="pre">child_stdout)</span></code>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is obsolete.  Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.  Check
especially the <a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.</p>
</div>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.popen3">
<code class="descclassname">os.</code><code class="descname">popen3</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.popen3" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute <em>cmd</em> as a sub-process and return the file objects <code class="docutils literal notranslate"><span class="pre">(child_stdin,</span>
<span class="pre">child_stdout,</span> <span class="pre">child_stderr)</span></code>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is obsolete.  Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.  Check
especially the <a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.</p>
</div>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.popen4">
<code class="descclassname">os.</code><code class="descname">popen4</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.popen4" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute <em>cmd</em> as a sub-process and return the file objects <code class="docutils literal notranslate"><span class="pre">(child_stdin,</span>
<span class="pre">child_stdout_and_stderr)</span></code>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This function is obsolete.  Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.  Check
especially the <a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.</p>
</div>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<p>(Note that <code class="docutils literal notranslate"><span class="pre">child_stdin,</span> <span class="pre">child_stdout,</span> <span class="pre">and</span> <span class="pre">child_stderr</span></code> are named from the
point of view of the child process, so <em>child_stdin</em> is the child’s standard
input.)</p>
<p>This functionality is also available in the <a class="reference internal" href="popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module using functions
of the same names, but the return values of those functions have a different
order.</p>
</div>
<div class="section" id="file-descriptor-operations">
<span id="os-fd-ops"></span><h2>15.1.3. File Descriptor Operations<a class="headerlink" href="#file-descriptor-operations" title="Permalink to this headline">¶</a></h2>
<p>These functions operate on I/O streams referenced using file descriptors.</p>
<p>File descriptors are small integers corresponding to a file that has been opened
by the current process.  For example, standard input is usually file descriptor
0, standard output is 1, and standard error is 2.  Further files opened by a
process will then be assigned 3, 4, 5, and so forth.  The name “file descriptor”
is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
by file descriptors.</p>
<p>The <a class="reference internal" href="stdtypes.html#file.fileno" title="file.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method can be used to obtain the file descriptor
associated with a file object when required.  Note that using the file
descriptor directly will bypass the file object methods, ignoring aspects such
as internal buffering of data.</p>
<dl class="function">
<dt id="os.close">
<code class="descclassname">os.</code><code class="descname">close</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close file descriptor <em>fd</em>.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is intended for low-level I/O and must be applied to a file
descriptor as returned by <a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> or <a class="reference internal" href="#os.pipe" title="os.pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">pipe()</span></code></a>.  To close a “file
object” returned by the built-in function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> or by <a class="reference internal" href="#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or
<a class="reference internal" href="#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">fdopen()</span></code></a>, use its <a class="reference internal" href="io.html#io.IOBase.close" title="io.IOBase.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.closerange">
<code class="descclassname">os.</code><code class="descname">closerange</code><span class="sig-paren">(</span><em>fd_low</em>, <em>fd_high</em><span class="sig-paren">)</span><a class="headerlink" href="#os.closerange" title="Permalink to this definition">¶</a></dt>
<dd><p>Close all file descriptors from <em>fd_low</em> (inclusive) to <em>fd_high</em> (exclusive),
ignoring errors. Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">fd</span> <span class="ow">in</span> <span class="n">xrange</span><span class="p">(</span><span class="n">fd_low</span><span class="p">,</span> <span class="n">fd_high</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">fd</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.dup">
<code class="descclassname">os.</code><code class="descname">dup</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.dup" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a duplicate of file descriptor <em>fd</em>.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.dup2">
<code class="descclassname">os.</code><code class="descname">dup2</code><span class="sig-paren">(</span><em>fd</em>, <em>fd2</em><span class="sig-paren">)</span><a class="headerlink" href="#os.dup2" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicate file descriptor <em>fd</em> to <em>fd2</em>, closing the latter first if necessary.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.fchmod">
<code class="descclassname">os.</code><code class="descname">fchmod</code><span class="sig-paren">(</span><em>fd</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fchmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the mode of the file given by <em>fd</em> to the numeric <em>mode</em>.  See the docs
for <a class="reference internal" href="#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">chmod()</span></code></a> for possible values of <em>mode</em>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.fchown">
<code class="descclassname">os.</code><code class="descname">fchown</code><span class="sig-paren">(</span><em>fd</em>, <em>uid</em>, <em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fchown" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the owner and group id of the file given by <em>fd</em> to the numeric <em>uid</em>
and <em>gid</em>.  To leave one of the ids unchanged, set it to -1.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.fdatasync">
<code class="descclassname">os.</code><code class="descname">fdatasync</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fdatasync" title="Permalink to this definition">¶</a></dt>
<dd><p>Force write of file with filedescriptor <em>fd</em> to disk. Does not force update of
metadata.</p>
<p>Availability: Unix.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is not available on MacOS.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.fpathconf">
<code class="descclassname">os.</code><code class="descname">fpathconf</code><span class="sig-paren">(</span><em>fd</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fpathconf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return system configuration information relevant to an open file. <em>name</em>
specifies the configuration value to retrieve; it may be a string which is the
name of a defined system value; these names are specified in a number of
standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
additional names as well.  The names known to the host operating system are
given in the <code class="docutils literal notranslate"><span class="pre">pathconf_names</span></code> dictionary.  For configuration variables not
included in that mapping, passing an integer for <em>name</em> is also accepted.</p>
<p>If <em>name</em> is a string and is not known, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  If a
specific value for <em>name</em> is not supported by the host system, even if it is
included in <code class="docutils literal notranslate"><span class="pre">pathconf_names</span></code>, an <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised with
<a class="reference internal" href="errno.html#errno.EINVAL" title="errno.EINVAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">errno.EINVAL</span></code></a> for the error number.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.fstat">
<code class="descclassname">os.</code><code class="descname">fstat</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fstat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return status for file descriptor <em>fd</em>, like <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a>.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.fstatvfs">
<code class="descclassname">os.</code><code class="descname">fstatvfs</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fstatvfs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return information about the filesystem containing the file associated with file
descriptor <em>fd</em>, like <a class="reference internal" href="statvfs.html#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">statvfs()</span></code></a>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.fsync">
<code class="descclassname">os.</code><code class="descname">fsync</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fsync" title="Permalink to this definition">¶</a></dt>
<dd><p>Force write of file with filedescriptor <em>fd</em> to disk.  On Unix, this calls the
native <code class="xref c c-func docutils literal notranslate"><span class="pre">fsync()</span></code> function; on Windows, the MS <code class="xref c c-func docutils literal notranslate"><span class="pre">_commit()</span></code> function.</p>
<p>If you’re starting with a Python file object <em>f</em>, first do <code class="docutils literal notranslate"><span class="pre">f.flush()</span></code>, and
then do <code class="docutils literal notranslate"><span class="pre">os.fsync(f.fileno())</span></code>, to ensure that all internal buffers associated
with <em>f</em> are written to disk.</p>
<p>Availability: Unix, and Windows starting in 2.2.3.</p>
</dd></dl>

<dl class="function">
<dt id="os.ftruncate">
<code class="descclassname">os.</code><code class="descname">ftruncate</code><span class="sig-paren">(</span><em>fd</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#os.ftruncate" title="Permalink to this definition">¶</a></dt>
<dd><p>Truncate the file corresponding to file descriptor <em>fd</em>, so that it is at most
<em>length</em> bytes in size.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.isatty">
<code class="descclassname">os.</code><code class="descname">isatty</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.isatty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the file descriptor <em>fd</em> is open and connected to a
tty(-like) device, else <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="os.lseek">
<code class="descclassname">os.</code><code class="descname">lseek</code><span class="sig-paren">(</span><em>fd</em>, <em>pos</em>, <em>how</em><span class="sig-paren">)</span><a class="headerlink" href="#os.lseek" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current position of file descriptor <em>fd</em> to position <em>pos</em>, modified
by <em>how</em>: <a class="reference internal" href="#os.SEEK_SET" title="os.SEEK_SET"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_SET</span></code></a> or <code class="docutils literal notranslate"><span class="pre">0</span></code> to set the position relative to the
beginning of the file; <a class="reference internal" href="#os.SEEK_CUR" title="os.SEEK_CUR"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_CUR</span></code></a> or <code class="docutils literal notranslate"><span class="pre">1</span></code> to set it relative to the
current position; <a class="reference internal" href="#os.SEEK_END" title="os.SEEK_END"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_END</span></code></a> or <code class="docutils literal notranslate"><span class="pre">2</span></code> to set it relative to the end of
the file. Return the new cursor position in bytes, starting from the beginning.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="data">
<dt id="os.SEEK_SET">
<code class="descclassname">os.</code><code class="descname">SEEK_SET</code><a class="headerlink" href="#os.SEEK_SET" title="Permalink to this definition">¶</a></dt>
<dt id="os.SEEK_CUR">
<code class="descclassname">os.</code><code class="descname">SEEK_CUR</code><a class="headerlink" href="#os.SEEK_CUR" title="Permalink to this definition">¶</a></dt>
<dt id="os.SEEK_END">
<code class="descclassname">os.</code><code class="descname">SEEK_END</code><a class="headerlink" href="#os.SEEK_END" title="Permalink to this definition">¶</a></dt>
<dd><p>Parameters to the <a class="reference internal" href="#os.lseek" title="os.lseek"><code class="xref py py-func docutils literal notranslate"><span class="pre">lseek()</span></code></a> function. Their values are 0, 1, and 2,
respectively.</p>
<p>Availability: Windows, Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.open">
<code class="descclassname">os.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em>, <em>flags</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the file <em>file</em> and set various flags according to <em>flags</em> and possibly its
mode according to <em>mode</em>. The default <em>mode</em> is <code class="docutils literal notranslate"><span class="pre">0777</span></code> (octal), and the
current umask value is first masked out.  Return the file descriptor for the
newly opened file.</p>
<p>For a description of the flag and mode values, see the C run-time documentation;
flag constants (like <a class="reference internal" href="#os.O_RDONLY" title="os.O_RDONLY"><code class="xref py py-const docutils literal notranslate"><span class="pre">O_RDONLY</span></code></a> and <a class="reference internal" href="#os.O_WRONLY" title="os.O_WRONLY"><code class="xref py py-const docutils literal notranslate"><span class="pre">O_WRONLY</span></code></a>) are defined in
this module too (see <a class="reference internal" href="#open-constants"><span class="std std-ref">open() flag constants</span></a>).  In particular, on Windows adding
<a class="reference internal" href="#os.O_BINARY" title="os.O_BINARY"><code class="xref py py-const docutils literal notranslate"><span class="pre">O_BINARY</span></code></a> is needed to open files in binary mode.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is intended for low-level I/O.  For normal usage, use the
built-in function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, which returns a “file object” with
<a class="reference internal" href="stdtypes.html#file.read" title="file.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> and <a class="reference internal" href="stdtypes.html#file.write" title="file.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> methods (and many more).  To
wrap a file descriptor in a “file object”, use <a class="reference internal" href="#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">fdopen()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.openpty">
<code class="descclassname">os.</code><code class="descname">openpty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.openpty" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-12">Open a new pseudo-terminal pair. Return a pair of file descriptors <code class="docutils literal notranslate"><span class="pre">(master,</span>
<span class="pre">slave)</span></code> for the pty and the tty, respectively. For a (slightly) more portable
approach, use the <a class="reference internal" href="pty.html#module-pty" title="pty: Pseudo-Terminal Handling for Linux. (Linux)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pty</span></code></a> module.</p>
<p>Availability: some flavors of Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.pipe">
<code class="descclassname">os.</code><code class="descname">pipe</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.pipe" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a pipe.  Return a pair of file descriptors <code class="docutils literal notranslate"><span class="pre">(r,</span> <span class="pre">w)</span></code> usable for reading
and writing, respectively.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.read">
<code class="descclassname">os.</code><code class="descname">read</code><span class="sig-paren">(</span><em>fd</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#os.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at most <em>n</em> bytes from file descriptor <em>fd</em>. Return a string containing the
bytes read.  If the end of the file referred to by <em>fd</em> has been reached, an
empty string is returned.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is intended for low-level I/O and must be applied to a file
descriptor as returned by <a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> or <a class="reference internal" href="#os.pipe" title="os.pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">pipe()</span></code></a>.  To read a “file object”
returned by the built-in function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> or by <a class="reference internal" href="#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or
<a class="reference internal" href="#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">fdopen()</span></code></a>, or <a class="reference internal" href="sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a>, use its <a class="reference internal" href="stdtypes.html#file.read" title="file.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> or
<a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> methods.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.tcgetpgrp">
<code class="descclassname">os.</code><code class="descname">tcgetpgrp</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.tcgetpgrp" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the process group associated with the terminal given by <em>fd</em> (an open
file descriptor as returned by <a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>).</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.tcsetpgrp">
<code class="descclassname">os.</code><code class="descname">tcsetpgrp</code><span class="sig-paren">(</span><em>fd</em>, <em>pg</em><span class="sig-paren">)</span><a class="headerlink" href="#os.tcsetpgrp" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the process group associated with the terminal given by <em>fd</em> (an open file
descriptor as returned by <a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>) to <em>pg</em>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.ttyname">
<code class="descclassname">os.</code><code class="descname">ttyname</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.ttyname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string which specifies the terminal device associated with
file descriptor <em>fd</em>.  If <em>fd</em> is not associated with a terminal device, an
exception is raised.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.write">
<code class="descclassname">os.</code><code class="descname">write</code><span class="sig-paren">(</span><em>fd</em>, <em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#os.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the string <em>str</em> to file descriptor <em>fd</em>. Return the number of bytes
actually written.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is intended for low-level I/O and must be applied to a file
descriptor as returned by <a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> or <a class="reference internal" href="#os.pipe" title="os.pipe"><code class="xref py py-func docutils literal notranslate"><span class="pre">pipe()</span></code></a>.  To write a “file
object” returned by the built-in function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> or by <a class="reference internal" href="#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or
<a class="reference internal" href="#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">fdopen()</span></code></a>, or <a class="reference internal" href="sys.html#sys.stdout" title="sys.stdout"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdout</span></code></a> or <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>, use its
<a class="reference internal" href="stdtypes.html#file.write" title="file.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method.</p>
</div>
</dd></dl>

<div class="section" id="open-flag-constants">
<span id="open-constants"></span><h3>15.1.3.1. <code class="docutils literal notranslate"><span class="pre">open()</span></code> flag constants<a class="headerlink" href="#open-flag-constants" title="Permalink to this headline">¶</a></h3>
<p>The following constants are options for the <em>flags</em> parameter to the
<a class="reference internal" href="#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.  They can be combined using the bitwise OR operator
<code class="docutils literal notranslate"><span class="pre">|</span></code>.  Some of them are not available on all platforms.  For descriptions of
their availability and use, consult the <em class="manpage">open(2)</em> manual page on Unix
or <a class="reference external" href="http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx">the MSDN</a> on Windows.</p>
<dl class="data">
<dt id="os.O_RDONLY">
<code class="descclassname">os.</code><code class="descname">O_RDONLY</code><a class="headerlink" href="#os.O_RDONLY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_WRONLY">
<code class="descclassname">os.</code><code class="descname">O_WRONLY</code><a class="headerlink" href="#os.O_WRONLY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_RDWR">
<code class="descclassname">os.</code><code class="descname">O_RDWR</code><a class="headerlink" href="#os.O_RDWR" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_APPEND">
<code class="descclassname">os.</code><code class="descname">O_APPEND</code><a class="headerlink" href="#os.O_APPEND" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_CREAT">
<code class="descclassname">os.</code><code class="descname">O_CREAT</code><a class="headerlink" href="#os.O_CREAT" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_EXCL">
<code class="descclassname">os.</code><code class="descname">O_EXCL</code><a class="headerlink" href="#os.O_EXCL" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_TRUNC">
<code class="descclassname">os.</code><code class="descname">O_TRUNC</code><a class="headerlink" href="#os.O_TRUNC" title="Permalink to this definition">¶</a></dt>
<dd><p>The above constants are available on Unix and Windows.</p>
</dd></dl>

<dl class="data">
<dt id="os.O_DSYNC">
<code class="descclassname">os.</code><code class="descname">O_DSYNC</code><a class="headerlink" href="#os.O_DSYNC" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_RSYNC">
<code class="descclassname">os.</code><code class="descname">O_RSYNC</code><a class="headerlink" href="#os.O_RSYNC" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_SYNC">
<code class="descclassname">os.</code><code class="descname">O_SYNC</code><a class="headerlink" href="#os.O_SYNC" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NDELAY">
<code class="descclassname">os.</code><code class="descname">O_NDELAY</code><a class="headerlink" href="#os.O_NDELAY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NONBLOCK">
<code class="descclassname">os.</code><code class="descname">O_NONBLOCK</code><a class="headerlink" href="#os.O_NONBLOCK" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NOCTTY">
<code class="descclassname">os.</code><code class="descname">O_NOCTTY</code><a class="headerlink" href="#os.O_NOCTTY" title="Permalink to this definition">¶</a></dt>
<dd><p>The above constants are only available on Unix.</p>
</dd></dl>

<dl class="data">
<dt id="os.O_BINARY">
<code class="descclassname">os.</code><code class="descname">O_BINARY</code><a class="headerlink" href="#os.O_BINARY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NOINHERIT">
<code class="descclassname">os.</code><code class="descname">O_NOINHERIT</code><a class="headerlink" href="#os.O_NOINHERIT" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_SHORT_LIVED">
<code class="descclassname">os.</code><code class="descname">O_SHORT_LIVED</code><a class="headerlink" href="#os.O_SHORT_LIVED" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_TEMPORARY">
<code class="descclassname">os.</code><code class="descname">O_TEMPORARY</code><a class="headerlink" href="#os.O_TEMPORARY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_RANDOM">
<code class="descclassname">os.</code><code class="descname">O_RANDOM</code><a class="headerlink" href="#os.O_RANDOM" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_SEQUENTIAL">
<code class="descclassname">os.</code><code class="descname">O_SEQUENTIAL</code><a class="headerlink" href="#os.O_SEQUENTIAL" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_TEXT">
<code class="descclassname">os.</code><code class="descname">O_TEXT</code><a class="headerlink" href="#os.O_TEXT" title="Permalink to this definition">¶</a></dt>
<dd><p>The above constants are only available on Windows.</p>
</dd></dl>

<dl class="data">
<dt id="os.O_ASYNC">
<code class="descclassname">os.</code><code class="descname">O_ASYNC</code><a class="headerlink" href="#os.O_ASYNC" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_DIRECT">
<code class="descclassname">os.</code><code class="descname">O_DIRECT</code><a class="headerlink" href="#os.O_DIRECT" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_DIRECTORY">
<code class="descclassname">os.</code><code class="descname">O_DIRECTORY</code><a class="headerlink" href="#os.O_DIRECTORY" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NOFOLLOW">
<code class="descclassname">os.</code><code class="descname">O_NOFOLLOW</code><a class="headerlink" href="#os.O_NOFOLLOW" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_NOATIME">
<code class="descclassname">os.</code><code class="descname">O_NOATIME</code><a class="headerlink" href="#os.O_NOATIME" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_SHLOCK">
<code class="descclassname">os.</code><code class="descname">O_SHLOCK</code><a class="headerlink" href="#os.O_SHLOCK" title="Permalink to this definition">¶</a></dt>
<dt id="os.O_EXLOCK">
<code class="descclassname">os.</code><code class="descname">O_EXLOCK</code><a class="headerlink" href="#os.O_EXLOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>The above constants are extensions and not present if they are not
defined by the C library.</p>
</dd></dl>

</div>
</div>
<div class="section" id="files-and-directories">
<span id="os-file-dir"></span><h2>15.1.4. Files and Directories<a class="headerlink" href="#files-and-directories" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="os.access">
<code class="descclassname">os.</code><code class="descname">access</code><span class="sig-paren">(</span><em>path</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#os.access" title="Permalink to this definition">¶</a></dt>
<dd><p>Use the real uid/gid to test for access to <em>path</em>.  Note that most operations
will use the effective uid/gid, therefore this routine can be used in a
suid/sgid environment to test if the invoking user has the specified access to
<em>path</em>.  <em>mode</em> should be <a class="reference internal" href="#os.F_OK" title="os.F_OK"><code class="xref py py-const docutils literal notranslate"><span class="pre">F_OK</span></code></a> to test the existence of <em>path</em>, or it
can be the inclusive OR of one or more of <a class="reference internal" href="#os.R_OK" title="os.R_OK"><code class="xref py py-const docutils literal notranslate"><span class="pre">R_OK</span></code></a>, <a class="reference internal" href="#os.W_OK" title="os.W_OK"><code class="xref py py-const docutils literal notranslate"><span class="pre">W_OK</span></code></a>, and
<a class="reference internal" href="#os.X_OK" title="os.X_OK"><code class="xref py py-const docutils literal notranslate"><span class="pre">X_OK</span></code></a> to test permissions.  Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if access is allowed,
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> if not. See the Unix man page <em class="manpage">access(2)</em> for more
information.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Using <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> to check if a user is authorized to e.g. open a file
before actually doing so using <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> creates a security hole,
because the user might exploit the short time interval between checking
and opening the file to manipulate it. It’s preferable to use <a class="reference internal" href="../glossary.html#term-eafp"><span class="xref std std-term">EAFP</span></a>
techniques. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="s2">&quot;myfile&quot;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">R_OK</span><span class="p">):</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="k">return</span> <span class="s2">&quot;some default data&quot;</span>
</pre></div>
</div>
<p>is better written as:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">fp</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile&quot;</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="k">if</span> <span class="n">e</span><span class="o">.</span><span class="n">errno</span> <span class="o">==</span> <span class="n">errno</span><span class="o">.</span><span class="n">EACCES</span><span class="p">:</span>
        <span class="k">return</span> <span class="s2">&quot;some default data&quot;</span>
    <span class="c1"># Not a permission error.</span>
    <span class="k">raise</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">fp</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">I/O operations may fail even when <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> indicates that they would
succeed, particularly for operations on network filesystems which may have
permissions semantics beyond the usual POSIX permission-bit model.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.F_OK">
<code class="descclassname">os.</code><code class="descname">F_OK</code><a class="headerlink" href="#os.F_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Value to pass as the <em>mode</em> parameter of <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> to test the existence of
<em>path</em>.</p>
</dd></dl>

<dl class="data">
<dt id="os.R_OK">
<code class="descclassname">os.</code><code class="descname">R_OK</code><a class="headerlink" href="#os.R_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Value to include in the <em>mode</em> parameter of <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> to test the
readability of <em>path</em>.</p>
</dd></dl>

<dl class="data">
<dt id="os.W_OK">
<code class="descclassname">os.</code><code class="descname">W_OK</code><a class="headerlink" href="#os.W_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Value to include in the <em>mode</em> parameter of <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> to test the
writability of <em>path</em>.</p>
</dd></dl>

<dl class="data">
<dt id="os.X_OK">
<code class="descclassname">os.</code><code class="descname">X_OK</code><a class="headerlink" href="#os.X_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Value to include in the <em>mode</em> parameter of <a class="reference internal" href="#os.access" title="os.access"><code class="xref py py-func docutils literal notranslate"><span class="pre">access()</span></code></a> to determine if
<em>path</em> can be executed.</p>
</dd></dl>

<dl class="function">
<dt id="os.chdir">
<code class="descclassname">os.</code><code class="descname">chdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.chdir" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-13">Change the current working directory to <em>path</em>.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.fchdir">
<code class="descclassname">os.</code><code class="descname">fchdir</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#os.fchdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the current working directory to the directory represented by the file
descriptor <em>fd</em>.  The descriptor must refer to an opened directory, not an open
file.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.getcwd">
<code class="descclassname">os.</code><code class="descname">getcwd</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getcwd" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the current working directory.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.getcwdu">
<code class="descclassname">os.</code><code class="descname">getcwdu</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getcwdu" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a Unicode object representing the current working directory.</p>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.chflags">
<code class="descclassname">os.</code><code class="descname">chflags</code><span class="sig-paren">(</span><em>path</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#os.chflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags of <em>path</em> to the numeric <em>flags</em>. <em>flags</em> may take a combination
(bitwise OR) of the following values (as defined in the <a class="reference internal" href="stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module):</p>
<ul class="simple">
<li><a class="reference internal" href="stat.html#stat.UF_NODUMP" title="stat.UF_NODUMP"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_NODUMP</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_IMMUTABLE" title="stat.UF_IMMUTABLE"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_IMMUTABLE</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_APPEND" title="stat.UF_APPEND"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_APPEND</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_OPAQUE" title="stat.UF_OPAQUE"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_OPAQUE</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_NOUNLINK" title="stat.UF_NOUNLINK"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_NOUNLINK</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_COMPRESSED" title="stat.UF_COMPRESSED"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_COMPRESSED</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.UF_HIDDEN" title="stat.UF_HIDDEN"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.UF_HIDDEN</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.SF_ARCHIVED" title="stat.SF_ARCHIVED"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.SF_ARCHIVED</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.SF_IMMUTABLE" title="stat.SF_IMMUTABLE"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.SF_IMMUTABLE</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.SF_APPEND" title="stat.SF_APPEND"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.SF_APPEND</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.SF_NOUNLINK" title="stat.SF_NOUNLINK"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.SF_NOUNLINK</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.SF_SNAPSHOT" title="stat.SF_SNAPSHOT"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.SF_SNAPSHOT</span></code></a></li>
</ul>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.chroot">
<code class="descclassname">os.</code><code class="descname">chroot</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.chroot" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the root directory of the current process to <em>path</em>. Availability:
Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.chmod">
<code class="descclassname">os.</code><code class="descname">chmod</code><span class="sig-paren">(</span><em>path</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#os.chmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the mode of <em>path</em> to the numeric <em>mode</em>. <em>mode</em> may take one of the
following values (as defined in the <a class="reference internal" href="stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module) or bitwise ORed
combinations of them:</p>
<ul class="simple">
<li><a class="reference internal" href="stat.html#stat.S_ISUID" title="stat.S_ISUID"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_ISUID</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_ISGID" title="stat.S_ISGID"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_ISGID</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_ENFMT" title="stat.S_ENFMT"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_ENFMT</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_ISVTX" title="stat.S_ISVTX"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_ISVTX</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IREAD" title="stat.S_IREAD"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IREAD</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IWRITE" title="stat.S_IWRITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IWRITE</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IEXEC" title="stat.S_IEXEC"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IEXEC</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IRWXU" title="stat.S_IRWXU"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IRWXU</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IRUSR" title="stat.S_IRUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IRUSR</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IWUSR" title="stat.S_IWUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IWUSR</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IXUSR" title="stat.S_IXUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IXUSR</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IRWXG" title="stat.S_IRWXG"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IRWXG</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IRGRP" title="stat.S_IRGRP"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IRGRP</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IWGRP" title="stat.S_IWGRP"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IWGRP</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IXGRP" title="stat.S_IXGRP"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IXGRP</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IRWXO" title="stat.S_IRWXO"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IRWXO</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IROTH" title="stat.S_IROTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IROTH</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IWOTH" title="stat.S_IWOTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IWOTH</span></code></a></li>
<li><a class="reference internal" href="stat.html#stat.S_IXOTH" title="stat.S_IXOTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">stat.S_IXOTH</span></code></a></li>
</ul>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Although Windows supports <a class="reference internal" href="#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">chmod()</span></code></a>, you can only  set the file’s read-only
flag with it (via the <code class="docutils literal notranslate"><span class="pre">stat.S_IWRITE</span></code>  and <code class="docutils literal notranslate"><span class="pre">stat.S_IREAD</span></code>
constants or a corresponding integer value).  All other bits are
ignored.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.chown">
<code class="descclassname">os.</code><code class="descname">chown</code><span class="sig-paren">(</span><em>path</em>, <em>uid</em>, <em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.chown" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the owner and group id of <em>path</em> to the numeric <em>uid</em> and <em>gid</em>. To leave
one of the ids unchanged, set it to -1.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.lchflags">
<code class="descclassname">os.</code><code class="descname">lchflags</code><span class="sig-paren">(</span><em>path</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#os.lchflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags of <em>path</em> to the numeric <em>flags</em>, like <a class="reference internal" href="#os.chflags" title="os.chflags"><code class="xref py py-func docutils literal notranslate"><span class="pre">chflags()</span></code></a>, but do not
follow symbolic links.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.lchmod">
<code class="descclassname">os.</code><code class="descname">lchmod</code><span class="sig-paren">(</span><em>path</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#os.lchmod" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the mode of <em>path</em> to the numeric <em>mode</em>. If path is a symlink, this
affects the symlink rather than the target. See the docs for <a class="reference internal" href="#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">chmod()</span></code></a>
for possible values of <em>mode</em>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.lchown">
<code class="descclassname">os.</code><code class="descname">lchown</code><span class="sig-paren">(</span><em>path</em>, <em>uid</em>, <em>gid</em><span class="sig-paren">)</span><a class="headerlink" href="#os.lchown" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the owner and group id of <em>path</em> to the numeric <em>uid</em> and <em>gid</em>. This
function will not follow symbolic links.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.link">
<code class="descclassname">os.</code><code class="descname">link</code><span class="sig-paren">(</span><em>source</em>, <em>link_name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.link" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a hard link pointing to <em>source</em> named <em>link_name</em>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.listdir">
<code class="descclassname">os.</code><code class="descname">listdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.listdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list containing the names of the entries in the directory given by
<em>path</em>.  The list is in arbitrary order.  It does not include the special
entries <code class="docutils literal notranslate"><span class="pre">'.'</span></code> and <code class="docutils literal notranslate"><span class="pre">'..'</span></code> even if they are present in the
directory.</p>
<p>Availability: Unix, Windows.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>On Windows NT/2k/XP and Unix, if <em>path</em> is a Unicode object, the result will be
a list of Unicode objects. Undecodable filenames will still be returned as
string objects.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.lstat">
<code class="descclassname">os.</code><code class="descname">lstat</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.lstat" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the equivalent of an <code class="xref c c-func docutils literal notranslate"><span class="pre">lstat()</span></code> system call on the given path.
Similar to <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a>, but does not follow symbolic links.  On
platforms that do not support symbolic links, this is an alias for
<a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.mkfifo">
<code class="descclassname">os.</code><code class="descname">mkfifo</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.mkfifo" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a FIFO (a named pipe) named <em>path</em> with numeric mode <em>mode</em>.  The default
<em>mode</em> is <code class="docutils literal notranslate"><span class="pre">0666</span></code> (octal).  The current umask value is first masked out from
the mode.</p>
<p>Availability: Unix.</p>
<p>FIFOs are pipes that can be accessed like regular files.  FIFOs exist until they
are deleted (for example with <a class="reference internal" href="#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unlink()</span></code></a>). Generally, FIFOs are used as
rendezvous between “client” and “server” type processes: the server opens the
FIFO for reading, and the client opens it for writing.  Note that <a class="reference internal" href="#os.mkfifo" title="os.mkfifo"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkfifo()</span></code></a>
doesn’t open the FIFO — it just creates the rendezvous point.</p>
</dd></dl>

<dl class="function">
<dt id="os.mknod">
<code class="descclassname">os.</code><code class="descname">mknod</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode=0600</em><span class="optional">[</span>, <em>device=0</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.mknod" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a filesystem node (file, device special file or named pipe) named
<em>filename</em>. <em>mode</em> specifies both the permissions to use and the type of node to
be created, being combined (bitwise OR) with one of <code class="docutils literal notranslate"><span class="pre">stat.S_IFREG</span></code>,
<code class="docutils literal notranslate"><span class="pre">stat.S_IFCHR</span></code>, <code class="docutils literal notranslate"><span class="pre">stat.S_IFBLK</span></code>,
and <code class="docutils literal notranslate"><span class="pre">stat.S_IFIFO</span></code> (those constants are available in <a class="reference internal" href="stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a>).
For <code class="docutils literal notranslate"><span class="pre">stat.S_IFCHR</span></code> and
<code class="docutils literal notranslate"><span class="pre">stat.S_IFBLK</span></code>, <em>device</em> defines the newly created device special file (probably using
<a class="reference internal" href="#os.makedev" title="os.makedev"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.makedev()</span></code></a>), otherwise it is ignored.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.major">
<code class="descclassname">os.</code><code class="descname">major</code><span class="sig-paren">(</span><em>device</em><span class="sig-paren">)</span><a class="headerlink" href="#os.major" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract the device major number from a raw device number (usually the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_dev</span></code> or <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_rdev</span></code> field from <code class="xref c c-type docutils literal notranslate"><span class="pre">stat</span></code>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.minor">
<code class="descclassname">os.</code><code class="descname">minor</code><span class="sig-paren">(</span><em>device</em><span class="sig-paren">)</span><a class="headerlink" href="#os.minor" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract the device minor number from a raw device number (usually the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_dev</span></code> or <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_rdev</span></code> field from <code class="xref c c-type docutils literal notranslate"><span class="pre">stat</span></code>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.makedev">
<code class="descclassname">os.</code><code class="descname">makedev</code><span class="sig-paren">(</span><em>major</em>, <em>minor</em><span class="sig-paren">)</span><a class="headerlink" href="#os.makedev" title="Permalink to this definition">¶</a></dt>
<dd><p>Compose a raw device number from the major and minor device numbers.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.mkdir">
<code class="descclassname">os.</code><code class="descname">mkdir</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.mkdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a directory named <em>path</em> with numeric mode <em>mode</em>. The default <em>mode</em> is
<code class="docutils literal notranslate"><span class="pre">0777</span></code> (octal).  If the directory already exists,
<a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised.</p>
<p id="mkdir-modebits">On some systems, <em>mode</em> is ignored.  Where it is used, the current umask
value is first masked out.  If bits other than the last 9 (i.e. the last 3
digits of the octal representation of the <em>mode</em>) are set, their meaning is
platform-dependent.  On some platforms, they are ignored and you should call
<a class="reference internal" href="#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">chmod()</span></code></a> explicitly to set them.</p>
<p>It is also possible to create temporary directories; see the
<a class="reference internal" href="tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a> module’s <a class="reference internal" href="tempfile.html#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempfile.mkdtemp()</span></code></a> function.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.makedirs">
<code class="descclassname">os.</code><code class="descname">makedirs</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.makedirs" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-14">Recursive directory creation function.  Like <a class="reference internal" href="#os.mkdir" title="os.mkdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdir()</span></code></a>, but makes all
intermediate-level directories needed to contain the leaf directory.  Raises an
<a class="reference internal" href="#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception if the leaf directory already exists or cannot be
created.  The default <em>mode</em> is <code class="docutils literal notranslate"><span class="pre">0777</span></code> (octal).</p>
<p>The <em>mode</em> parameter is passed to <a class="reference internal" href="#os.mkdir" title="os.mkdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdir()</span></code></a>; see <a class="reference internal" href="#mkdir-modebits"><span class="std std-ref">the mkdir()
description</span></a> for how it is interpreted.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#os.makedirs" title="os.makedirs"><code class="xref py py-func docutils literal notranslate"><span class="pre">makedirs()</span></code></a> will become confused if the path elements to create include
<a class="reference internal" href="#os.pardir" title="os.pardir"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.pardir</span></code></a>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>This function now handles UNC paths correctly.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.pathconf">
<code class="descclassname">os.</code><code class="descname">pathconf</code><span class="sig-paren">(</span><em>path</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.pathconf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return system configuration information relevant to a named file. <em>name</em>
specifies the configuration value to retrieve; it may be a string which is the
name of a defined system value; these names are specified in a number of
standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
additional names as well.  The names known to the host operating system are
given in the <code class="docutils literal notranslate"><span class="pre">pathconf_names</span></code> dictionary.  For configuration variables not
included in that mapping, passing an integer for <em>name</em> is also accepted.</p>
<p>If <em>name</em> is a string and is not known, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  If a
specific value for <em>name</em> is not supported by the host system, even if it is
included in <code class="docutils literal notranslate"><span class="pre">pathconf_names</span></code>, an <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised with
<a class="reference internal" href="errno.html#errno.EINVAL" title="errno.EINVAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">errno.EINVAL</span></code></a> for the error number.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="data">
<dt id="os.pathconf_names">
<code class="descclassname">os.</code><code class="descname">pathconf_names</code><a class="headerlink" href="#os.pathconf_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping names accepted by <a class="reference internal" href="#os.pathconf" title="os.pathconf"><code class="xref py py-func docutils literal notranslate"><span class="pre">pathconf()</span></code></a> and <a class="reference internal" href="#os.fpathconf" title="os.fpathconf"><code class="xref py py-func docutils literal notranslate"><span class="pre">fpathconf()</span></code></a> to
the integer values defined for those names by the host operating system.  This
can be used to determine the set of names known to the system. Availability:
Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.readlink">
<code class="descclassname">os.</code><code class="descname">readlink</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.readlink" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representing the path to which the symbolic link points.  The
result may be either an absolute or relative pathname; if it is relative, it may
be converted to an absolute pathname using <code class="docutils literal notranslate"><span class="pre">os.path.join(os.path.dirname(path),</span>
<span class="pre">result)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>If the <em>path</em> is a Unicode object the result will also be a Unicode object.</p>
</div>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.remove">
<code class="descclassname">os.</code><code class="descname">remove</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove (delete) the file <em>path</em>.  If <em>path</em> is a directory, <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is
raised; see <a class="reference internal" href="#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">rmdir()</span></code></a> below to remove a directory.  This is identical to
the <a class="reference internal" href="#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">unlink()</span></code></a> function documented below.  On Windows, attempting to
remove a file that is in use causes an exception to be raised; on Unix, the
directory entry is removed but the storage allocated to the file is not made
available until the original file is no longer in use.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.removedirs">
<code class="descclassname">os.</code><code class="descname">removedirs</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.removedirs" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-15">Remove directories recursively.  Works like <a class="reference internal" href="#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">rmdir()</span></code></a> except that, if the
leaf directory is successfully removed, <a class="reference internal" href="#os.removedirs" title="os.removedirs"><code class="xref py py-func docutils literal notranslate"><span class="pre">removedirs()</span></code></a>  tries to
successively remove every parent directory mentioned in  <em>path</em> until an error
is raised (which is ignored, because it generally means that a parent directory
is not empty). For example, <code class="docutils literal notranslate"><span class="pre">os.removedirs('foo/bar/baz')</span></code> will first remove
the directory <code class="docutils literal notranslate"><span class="pre">'foo/bar/baz'</span></code>, and then remove <code class="docutils literal notranslate"><span class="pre">'foo/bar'</span></code> and <code class="docutils literal notranslate"><span class="pre">'foo'</span></code> if
they are empty. Raises <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> if the leaf directory could not be
successfully removed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.rename">
<code class="descclassname">os.</code><code class="descname">rename</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#os.rename" title="Permalink to this definition">¶</a></dt>
<dd><p>Rename the file or directory <em>src</em> to <em>dst</em>.  If <em>dst</em> is a directory,
<a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> will be raised.  On Unix, if <em>dst</em> exists and is a file, it will
be replaced silently if the user has permission.  The operation may fail on some
Unix flavors if <em>src</em> and <em>dst</em> are on different filesystems.  If successful,
the renaming will be an atomic operation (this is a POSIX requirement).  On
Windows, if <em>dst</em> already exists, <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> will be raised even if it is a
file; there may be no way to implement an atomic rename when <em>dst</em> names an
existing file.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.renames">
<code class="descclassname">os.</code><code class="descname">renames</code><span class="sig-paren">(</span><em>old</em>, <em>new</em><span class="sig-paren">)</span><a class="headerlink" href="#os.renames" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursive directory or file renaming function. Works like <a class="reference internal" href="#os.rename" title="os.rename"><code class="xref py py-func docutils literal notranslate"><span class="pre">rename()</span></code></a>, except
creation of any intermediate directories needed to make the new pathname good is
attempted first. After the rename, directories corresponding to rightmost path
segments of the old name will be pruned away using <a class="reference internal" href="#os.removedirs" title="os.removedirs"><code class="xref py py-func docutils literal notranslate"><span class="pre">removedirs()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function can fail with the new directory structure made if you lack
permissions needed to remove the leaf directory or file.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.rmdir">
<code class="descclassname">os.</code><code class="descname">rmdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.rmdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove (delete) the directory <em>path</em>.  Only works when the directory is
empty, otherwise, <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised.  In order to remove whole
directory trees, <a class="reference internal" href="shutil.html#shutil.rmtree" title="shutil.rmtree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.rmtree()</span></code></a> can be used.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.stat">
<code class="descclassname">os.</code><code class="descname">stat</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.stat" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the equivalent of a <code class="xref c c-func docutils literal notranslate"><span class="pre">stat()</span></code> system call on the given path.
(This function follows symlinks; to stat a symlink use <a class="reference internal" href="#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">lstat()</span></code></a>.)</p>
<p>The return value is an object whose attributes correspond to the members
of the <code class="xref c c-type docutils literal notranslate"><span class="pre">stat</span></code> structure, namely:</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mode</span></code> - protection bits,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ino</span></code> - inode number,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_dev</span></code> - device,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_nlink</span></code> - number of hard links,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_uid</span></code> - user id of owner,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gid</span></code> - group id of owner,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_size</span></code> - size of file, in bytes,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_atime</span></code> - time of most recent access,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mtime</span></code> - time of most recent content modification,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ctime</span></code> - platform dependent; time of most recent metadata change on
Unix, or the time of creation on Windows)</li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>If <a class="reference internal" href="#os.stat_float_times" title="os.stat_float_times"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat_float_times()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the time values are floats, measuring
seconds. Fractions of a second may be reported if the system supports that.
See <a class="reference internal" href="#os.stat_float_times" title="os.stat_float_times"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat_float_times()</span></code></a> for further discussion.</p>
</div>
<p>On some Unix systems (such as Linux), the following attributes may also be
available:</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_blocks</span></code> - number of 512-byte blocks allocated for file</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_blksize</span></code> - filesystem blocksize for efficient file system I/O</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_rdev</span></code> - type of device if an inode device</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_flags</span></code> - user defined flags for file</li>
</ul>
<p>On other Unix systems (such as FreeBSD), the following attributes may be
available (but may be only filled out if root tries to use them):</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gen</span></code> - file generation number</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_birthtime</span></code> - time of file creation</li>
</ul>
<p>On RISCOS systems, the following attributes are also available:</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ftype</span></code> (file type)</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_attrs</span></code> (attributes)</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">st_obtype</span></code> (object type).</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The exact meaning and resolution of the <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_atime</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mtime</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ctime</span></code> attributes depend on the operating
system and the file system. For example, on Windows systems using the FAT
or FAT32 file systems, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mtime</span></code> has 2-second resolution, and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_atime</span></code> has only 1-day resolution.  See your operating system
documentation for details.</p>
</div>
<p>For backward compatibility, the return value of <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a> is also accessible
as a tuple of at least 10 integers giving the most important (and portable)
members of the <code class="xref c c-type docutils literal notranslate"><span class="pre">stat</span></code> structure, in the order <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mode</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ino</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_dev</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_nlink</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_uid</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gid</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_size</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_atime</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_mtime</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_ctime</span></code>. More items may be added at the end by some implementations.</p>
<p id="index-16">The standard module <a class="reference internal" href="stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> defines functions and constants that are useful
for extracting information from a <code class="xref c c-type docutils literal notranslate"><span class="pre">stat</span></code> structure. (On Windows, some
items are filled with dummy values.)</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statinfo</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s1">&#39;somefile.txt&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statinfo</span>
<span class="go">(33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">statinfo</span><span class="o">.</span><span class="n">st_size</span>
<span class="go">926</span>
</pre></div>
</div>
<p>Availability: Unix, Windows.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Added access to values as attributes of the returned object.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gen</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_birthtime</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.stat_float_times">
<code class="descclassname">os.</code><code class="descname">stat_float_times</code><span class="sig-paren">(</span><span class="optional">[</span><em>newvalue</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.stat_float_times" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <code class="xref py py-class docutils literal notranslate"><span class="pre">stat_result</span></code> represents time stamps as float objects.
If <em>newvalue</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, future calls to <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a> return floats, if it is
<code class="docutils literal notranslate"><span class="pre">False</span></code>, future calls return ints. If <em>newvalue</em> is omitted, return the
current setting.</p>
<p>For compatibility with older Python versions, accessing <code class="xref py py-class docutils literal notranslate"><span class="pre">stat_result</span></code> as
a tuple always returns integers.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Python now returns float values by default. Applications which do not work
correctly with floating point time stamps can use this function to restore the
old behaviour.</p>
</div>
<p>The resolution of the timestamps (that is the smallest possible fraction)
depends on the system. Some systems only support second resolution; on these
systems, the fraction will always be zero.</p>
<p>It is recommended that this setting is only changed at program startup time in
the <em>__main__</em> module; libraries should never change this setting. If an
application uses a library that works incorrectly if floating point time stamps
are processed, this application should turn the feature off until the library
has been corrected.</p>
</dd></dl>

<dl class="function">
<dt id="os.statvfs">
<code class="descclassname">os.</code><code class="descname">statvfs</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.statvfs" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform a <code class="xref c c-func docutils literal notranslate"><span class="pre">statvfs()</span></code> system call on the given path.  The return value is
an object whose attributes describe the filesystem on the given path, and
correspond to the members of the <code class="xref c c-type docutils literal notranslate"><span class="pre">statvfs</span></code> structure, namely:
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_bsize</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_frsize</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_blocks</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_bfree</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_bavail</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_files</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_ffree</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_favail</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_flag</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_namemax</span></code>.</p>
<p id="index-17">For backward compatibility, the return value is also accessible as a tuple whose
values correspond to the attributes, in the order given above. The standard
module <a class="reference internal" href="statvfs.html#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code></a> defines constants that are useful for extracting
information from a <code class="xref c c-type docutils literal notranslate"><span class="pre">statvfs</span></code> structure when accessing it as a sequence;
this remains useful when writing code that needs to work with versions of Python
that don’t support accessing the fields as attributes.</p>
<p>Availability: Unix.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Added access to values as attributes of the returned object.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.symlink">
<code class="descclassname">os.</code><code class="descname">symlink</code><span class="sig-paren">(</span><em>source</em>, <em>link_name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.symlink" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a symbolic link pointing to <em>source</em> named <em>link_name</em>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.tempnam">
<code class="descclassname">os.</code><code class="descname">tempnam</code><span class="sig-paren">(</span><span class="optional">[</span><em>dir</em><span class="optional">[</span>, <em>prefix</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.tempnam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a unique path name that is reasonable for creating a temporary file.
This will be an absolute path that names a potential directory entry in the
directory <em>dir</em> or a common location for temporary files if <em>dir</em> is omitted or
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  If given and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>prefix</em> is used to provide a short prefix
to the filename.  Applications are responsible for properly creating and
managing files created using paths returned by <a class="reference internal" href="#os.tempnam" title="os.tempnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempnam()</span></code></a>; no automatic
cleanup is provided. On Unix, the environment variable <span class="target" id="index-18"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMPDIR</span></code>
overrides <em>dir</em>, while on Windows <span class="target" id="index-19"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMP</span></code> is used.  The specific
behavior of this function depends on the C library implementation; some aspects
are underspecified in system documentation.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Use of <a class="reference internal" href="#os.tempnam" title="os.tempnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempnam()</span></code></a> is vulnerable to symlink attacks; consider using
<a class="reference internal" href="#os.tmpfile" title="os.tmpfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpfile()</span></code></a> (section <a class="reference internal" href="#os-newstreams"><span class="std std-ref">File Object Creation</span></a>) instead.</p>
</div>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.tmpnam">
<code class="descclassname">os.</code><code class="descname">tmpnam</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.tmpnam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a unique path name that is reasonable for creating a temporary file.
This will be an absolute path that names a potential directory entry in a common
location for temporary files.  Applications are responsible for properly
creating and managing files created using paths returned by <a class="reference internal" href="#os.tmpnam" title="os.tmpnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpnam()</span></code></a>; no
automatic cleanup is provided.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Use of <a class="reference internal" href="#os.tmpnam" title="os.tmpnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpnam()</span></code></a> is vulnerable to symlink attacks; consider using
<a class="reference internal" href="#os.tmpfile" title="os.tmpfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpfile()</span></code></a> (section <a class="reference internal" href="#os-newstreams"><span class="std std-ref">File Object Creation</span></a>) instead.</p>
</div>
<p>Availability: Unix, Windows.  This function probably shouldn’t be used on
Windows, though: Microsoft’s implementation of <a class="reference internal" href="#os.tmpnam" title="os.tmpnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpnam()</span></code></a> always creates a
name in the root directory of the current drive, and that’s generally a poor
location for a temp file (depending on privileges, you may not even be able to
open a file using this name).</p>
</dd></dl>

<dl class="data">
<dt id="os.TMP_MAX">
<code class="descclassname">os.</code><code class="descname">TMP_MAX</code><a class="headerlink" href="#os.TMP_MAX" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum number of unique names that <a class="reference internal" href="#os.tmpnam" title="os.tmpnam"><code class="xref py py-func docutils literal notranslate"><span class="pre">tmpnam()</span></code></a> will generate before
reusing names.</p>
</dd></dl>

<dl class="function">
<dt id="os.unlink">
<code class="descclassname">os.</code><code class="descname">unlink</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.unlink" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove (delete) the file <em>path</em>.  This is the same function as
<a class="reference internal" href="#os.remove" title="os.remove"><code class="xref py py-func docutils literal notranslate"><span class="pre">remove()</span></code></a>; the <a class="reference internal" href="#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">unlink()</span></code></a> name is its traditional Unix
name.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.utime">
<code class="descclassname">os.</code><code class="descname">utime</code><span class="sig-paren">(</span><em>path</em>, <em>times</em><span class="sig-paren">)</span><a class="headerlink" href="#os.utime" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the access and modified times of the file specified by <em>path</em>. If <em>times</em>
is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then the file’s access and modified times are set to the current
time. (The effect is similar to running the Unix program <strong class="program">touch</strong> on
the path.)  Otherwise, <em>times</em> must be a 2-tuple of numbers, of the form
<code class="docutils literal notranslate"><span class="pre">(atime,</span> <span class="pre">mtime)</span></code> which is used to set the access and modified times,
respectively. Whether a directory can be given for <em>path</em> depends on whether
the operating system implements directories as files (for example, Windows
does not).  Note that the exact times you set here may not be returned by a
subsequent <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a> call, depending on the resolution with which your
operating system records access and modification times; see <a class="reference internal" href="#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.0: </span>Added support for <code class="docutils literal notranslate"><span class="pre">None</span></code> for <em>times</em>.</p>
</div>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.walk">
<code class="descclassname">os.</code><code class="descname">walk</code><span class="sig-paren">(</span><em>top</em>, <em>topdown=True</em>, <em>onerror=None</em>, <em>followlinks=False</em><span class="sig-paren">)</span><a class="headerlink" href="#os.walk" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-20">Generate the file names in a directory tree by walking the tree
either top-down or bottom-up. For each directory in the tree rooted at directory
<em>top</em> (including <em>top</em> itself), it yields a 3-tuple <code class="docutils literal notranslate"><span class="pre">(dirpath,</span> <span class="pre">dirnames,</span>
<span class="pre">filenames)</span></code>.</p>
<p><em>dirpath</em> is a string, the path to the directory.  <em>dirnames</em> is a list of the
names of the subdirectories in <em>dirpath</em> (excluding <code class="docutils literal notranslate"><span class="pre">'.'</span></code> and <code class="docutils literal notranslate"><span class="pre">'..'</span></code>).
<em>filenames</em> is a list of the names of the non-directory files in <em>dirpath</em>.
Note that the names in the lists contain no path components.  To get a full path
(which begins with <em>top</em>) to a file or directory in <em>dirpath</em>, do
<code class="docutils literal notranslate"><span class="pre">os.path.join(dirpath,</span> <span class="pre">name)</span></code>.</p>
<p>If optional argument <em>topdown</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code> or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top-down).  If <em>topdown</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, the triple
for a directory is generated after the triples for all of its subdirectories
(directories are generated bottom-up). No matter the value of <em>topdown</em>, the
list of subdirectories is retrieved before the tuples for the directory and
its subdirectories are generated.</p>
<p>When <em>topdown</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the caller can modify the <em>dirnames</em> list in-place
(perhaps using <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> or slice assignment), and <a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> will only
recurse into the subdirectories whose names remain in <em>dirnames</em>; this can be
used to prune the search, impose a specific order of visiting, or even to inform
<a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> about directories the caller creates or renames before it resumes
<a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> again.  Modifying <em>dirnames</em> when <em>topdown</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code> has
no effect on the behavior of the walk, because in bottom-up mode the directories
in <em>dirnames</em> are generated before <em>dirpath</em> itself is generated.</p>
<p>By default, errors from the <a class="reference internal" href="#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">listdir()</span></code></a> call are ignored.  If optional
argument <em>onerror</em> is specified, it should be a function; it will be called with
one argument, an <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> instance.  It can report the error to continue
with the walk, or raise the exception to abort the walk.  Note that the filename
is available as the <code class="docutils literal notranslate"><span class="pre">filename</span></code> attribute of the exception object.</p>
<p>By default, <a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> will not walk down into symbolic links that resolve to
directories. Set <em>followlinks</em> to <code class="docutils literal notranslate"><span class="pre">True</span></code> to visit directories pointed to by
symlinks, on systems that support them.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The <em>followlinks</em> parameter.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Be aware that setting <em>followlinks</em> to <code class="docutils literal notranslate"><span class="pre">True</span></code> can lead to infinite recursion if a
link points to a parent directory of itself. <a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> does not keep track of
the directories it visited already.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you pass a relative pathname, don’t change the current working directory
between resumptions of <a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a>.  <a class="reference internal" href="#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> never changes the current
directory, and assumes that its caller doesn’t either.</p>
</div>
<p>This example displays the number of bytes taken by non-directory files in each
directory under the starting directory, except that it doesn’t look under any
CVS subdirectory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">from</span> <span class="nn">os.path</span> <span class="k">import</span> <span class="n">join</span><span class="p">,</span> <span class="n">getsize</span>
<span class="k">for</span> <span class="n">root</span><span class="p">,</span> <span class="n">dirs</span><span class="p">,</span> <span class="n">files</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="s1">&#39;python/Lib/email&#39;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">root</span><span class="p">,</span> <span class="s2">&quot;consumes&quot;</span><span class="p">,</span>
    <span class="nb">print</span> <span class="nb">sum</span><span class="p">(</span><span class="n">getsize</span><span class="p">(</span><span class="n">join</span><span class="p">(</span><span class="n">root</span><span class="p">,</span> <span class="n">name</span><span class="p">))</span> <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">files</span><span class="p">),</span>
    <span class="nb">print</span> <span class="s2">&quot;bytes in&quot;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">files</span><span class="p">),</span> <span class="s2">&quot;non-directory files&quot;</span>
    <span class="k">if</span> <span class="s1">&#39;CVS&#39;</span> <span class="ow">in</span> <span class="n">dirs</span><span class="p">:</span>
        <span class="n">dirs</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;CVS&#39;</span><span class="p">)</span>  <span class="c1"># don&#39;t visit CVS directories</span>
</pre></div>
</div>
<p>In the next example, walking the tree bottom-up is essential: <a class="reference internal" href="#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">rmdir()</span></code></a>
doesn’t allow deleting a directory before the directory is empty:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Delete everything reachable from the directory named in &quot;top&quot;,</span>
<span class="c1"># assuming there are no symbolic links.</span>
<span class="c1"># CAUTION:  This is dangerous!  For example, if top == &#39;/&#39;, it</span>
<span class="c1"># could delete all your disk files.</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="k">for</span> <span class="n">root</span><span class="p">,</span> <span class="n">dirs</span><span class="p">,</span> <span class="n">files</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="n">top</span><span class="p">,</span> <span class="n">topdown</span><span class="o">=</span><span class="kc">False</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">files</span><span class="p">:</span>
        <span class="n">os</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">root</span><span class="p">,</span> <span class="n">name</span><span class="p">))</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">dirs</span><span class="p">:</span>
        <span class="n">os</span><span class="o">.</span><span class="n">rmdir</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">root</span><span class="p">,</span> <span class="n">name</span><span class="p">))</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="process-management">
<span id="os-process"></span><h2>15.1.5. Process Management<a class="headerlink" href="#process-management" title="Permalink to this headline">¶</a></h2>
<p>These functions may be used to create and manage processes.</p>
<p>The various <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec*</span></code></a> functions take a list of arguments for the new
program loaded into the process.  In each case, the first of these arguments is
passed to the new program as its own name rather than as an argument a user may
have typed on a command line.  For the C programmer, this is the <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code>
passed to a program’s <code class="xref c c-func docutils literal notranslate"><span class="pre">main()</span></code>.  For example, <code class="docutils literal notranslate"><span class="pre">os.execv('/bin/echo',</span>
<span class="pre">['foo',</span> <span class="pre">'bar'])</span></code> will only print <code class="docutils literal notranslate"><span class="pre">bar</span></code> on standard output; <code class="docutils literal notranslate"><span class="pre">foo</span></code> will seem
to be ignored.</p>
<dl class="function">
<dt id="os.abort">
<code class="descclassname">os.</code><code class="descname">abort</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.abort" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGABRT</span></code> signal to the current process.  On Unix, the default
behavior is to produce a core dump; on Windows, the process immediately returns
an exit code of <code class="docutils literal notranslate"><span class="pre">3</span></code>.  Be aware that calling this function will not call the
Python signal handler registered for <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGABRT</span></code> with
<a class="reference internal" href="signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a>.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.execl">
<code class="descclassname">os.</code><code class="descname">execl</code><span class="sig-paren">(</span><em>path</em>, <em>arg0</em>, <em>arg1</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execl" title="Permalink to this definition">¶</a></dt>
<dt id="os.execle">
<code class="descclassname">os.</code><code class="descname">execle</code><span class="sig-paren">(</span><em>path</em>, <em>arg0</em>, <em>arg1</em>, <em>...</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execle" title="Permalink to this definition">¶</a></dt>
<dt id="os.execlp">
<code class="descclassname">os.</code><code class="descname">execlp</code><span class="sig-paren">(</span><em>file</em>, <em>arg0</em>, <em>arg1</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execlp" title="Permalink to this definition">¶</a></dt>
<dt id="os.execlpe">
<code class="descclassname">os.</code><code class="descname">execlpe</code><span class="sig-paren">(</span><em>file</em>, <em>arg0</em>, <em>arg1</em>, <em>...</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execlpe" title="Permalink to this definition">¶</a></dt>
<dt id="os.execv">
<code class="descclassname">os.</code><code class="descname">execv</code><span class="sig-paren">(</span><em>path</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execv" title="Permalink to this definition">¶</a></dt>
<dt id="os.execve">
<code class="descclassname">os.</code><code class="descname">execve</code><span class="sig-paren">(</span><em>path</em>, <em>args</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execve" title="Permalink to this definition">¶</a></dt>
<dt id="os.execvp">
<code class="descclassname">os.</code><code class="descname">execvp</code><span class="sig-paren">(</span><em>file</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execvp" title="Permalink to this definition">¶</a></dt>
<dt id="os.execvpe">
<code class="descclassname">os.</code><code class="descname">execvpe</code><span class="sig-paren">(</span><em>file</em>, <em>args</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.execvpe" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions all execute a new program, replacing the current process; they
do not return.  On Unix, the new executable is loaded into the current process,
and will have the same process id as the caller.  Errors will be reported as
<a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> exceptions.</p>
<p>The current process is replaced immediately. Open file objects and
descriptors are not flushed, so if there may be data buffered
on these open files, you should flush them using
<code class="xref py py-func docutils literal notranslate"><span class="pre">sys.stdout.flush()</span></code> or <a class="reference internal" href="#os.fsync" title="os.fsync"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fsync()</span></code></a> before calling an
<a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec*</span></code></a> function.</p>
<p>The “l” and “v” variants of the <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec*</span></code></a> functions differ in how
command-line arguments are passed.  The “l” variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the <code class="xref py py-func docutils literal notranslate"><span class="pre">execl*()</span></code>
functions.  The “v” variants are good when the number of parameters is
variable, with the arguments being passed in a list or tuple as the <em>args</em>
parameter.  In either case, the arguments to the child process should start with
the name of the command being run, but this is not enforced.</p>
<p>The variants which include a “p” near the end (<a class="reference internal" href="#os.execlp" title="os.execlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">execlp()</span></code></a>,
<a class="reference internal" href="#os.execlpe" title="os.execlpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">execlpe()</span></code></a>, <a class="reference internal" href="#os.execvp" title="os.execvp"><code class="xref py py-func docutils literal notranslate"><span class="pre">execvp()</span></code></a>, and <a class="reference internal" href="#os.execvpe" title="os.execvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">execvpe()</span></code></a>) will use the
<span class="target" id="index-21"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> environment variable to locate the program <em>file</em>.  When the
environment is being replaced (using one of the <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec*e</span></code></a> variants,
discussed in the next paragraph), the new environment is used as the source of
the <span class="target" id="index-22"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable. The other variants, <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">execl()</span></code></a>, <a class="reference internal" href="#os.execle" title="os.execle"><code class="xref py py-func docutils literal notranslate"><span class="pre">execle()</span></code></a>,
<a class="reference internal" href="#os.execv" title="os.execv"><code class="xref py py-func docutils literal notranslate"><span class="pre">execv()</span></code></a>, and <a class="reference internal" href="#os.execve" title="os.execve"><code class="xref py py-func docutils literal notranslate"><span class="pre">execve()</span></code></a>, will not use the <span class="target" id="index-23"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable to
locate the executable; <em>path</em> must contain an appropriate absolute or relative
path.</p>
<p>For <a class="reference internal" href="#os.execle" title="os.execle"><code class="xref py py-func docutils literal notranslate"><span class="pre">execle()</span></code></a>, <a class="reference internal" href="#os.execlpe" title="os.execlpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">execlpe()</span></code></a>, <a class="reference internal" href="#os.execve" title="os.execve"><code class="xref py py-func docutils literal notranslate"><span class="pre">execve()</span></code></a>, and <a class="reference internal" href="#os.execvpe" title="os.execvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">execvpe()</span></code></a> (note
that these all end in “e”), the <em>env</em> parameter must be a mapping which is
used to define the environment variables for the new process (these are used
instead of the current process’ environment); the functions <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">execl()</span></code></a>,
<a class="reference internal" href="#os.execlp" title="os.execlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">execlp()</span></code></a>, <a class="reference internal" href="#os.execv" title="os.execv"><code class="xref py py-func docutils literal notranslate"><span class="pre">execv()</span></code></a>, and <a class="reference internal" href="#os.execvp" title="os.execvp"><code class="xref py py-func docutils literal notranslate"><span class="pre">execvp()</span></code></a> all cause the new process to
inherit the environment of the current process.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os._exit">
<code class="descclassname">os.</code><code class="descname">_exit</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#os._exit" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the process with status <em>n</em>, without calling cleanup handlers, flushing
stdio buffers, etc.</p>
<p>Availability: Unix, Windows.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The standard way to exit is <code class="docutils literal notranslate"><span class="pre">sys.exit(n)</span></code>.  <a class="reference internal" href="#os._exit" title="os._exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">_exit()</span></code></a> should
normally only be used in the child process after a <a class="reference internal" href="#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a>.</p>
</div>
</dd></dl>

<p>The following exit codes are defined and can be used with <a class="reference internal" href="#os._exit" title="os._exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">_exit()</span></code></a>,
although they are not required.  These are typically used for system programs
written in Python, such as a mail server’s external command delivery program.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some of these may not be available on all Unix platforms, since there is some
variation.  These constants are defined where they are defined by the underlying
platform.</p>
</div>
<dl class="data">
<dt id="os.EX_OK">
<code class="descclassname">os.</code><code class="descname">EX_OK</code><a class="headerlink" href="#os.EX_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means no error occurred.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_USAGE">
<code class="descclassname">os.</code><code class="descname">EX_USAGE</code><a class="headerlink" href="#os.EX_USAGE" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means the command was used incorrectly, such as when the wrong
number of arguments are given.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_DATAERR">
<code class="descclassname">os.</code><code class="descname">EX_DATAERR</code><a class="headerlink" href="#os.EX_DATAERR" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means the input data was incorrect.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_NOINPUT">
<code class="descclassname">os.</code><code class="descname">EX_NOINPUT</code><a class="headerlink" href="#os.EX_NOINPUT" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means an input file did not exist or was not readable.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_NOUSER">
<code class="descclassname">os.</code><code class="descname">EX_NOUSER</code><a class="headerlink" href="#os.EX_NOUSER" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means a specified user did not exist.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_NOHOST">
<code class="descclassname">os.</code><code class="descname">EX_NOHOST</code><a class="headerlink" href="#os.EX_NOHOST" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means a specified host did not exist.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_UNAVAILABLE">
<code class="descclassname">os.</code><code class="descname">EX_UNAVAILABLE</code><a class="headerlink" href="#os.EX_UNAVAILABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means that a required service is unavailable.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_SOFTWARE">
<code class="descclassname">os.</code><code class="descname">EX_SOFTWARE</code><a class="headerlink" href="#os.EX_SOFTWARE" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means an internal software error was detected.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_OSERR">
<code class="descclassname">os.</code><code class="descname">EX_OSERR</code><a class="headerlink" href="#os.EX_OSERR" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means an operating system error was detected, such as the
inability to fork or create a pipe.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_OSFILE">
<code class="descclassname">os.</code><code class="descname">EX_OSFILE</code><a class="headerlink" href="#os.EX_OSFILE" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means some system file did not exist, could not be opened, or had
some other kind of error.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_CANTCREAT">
<code class="descclassname">os.</code><code class="descname">EX_CANTCREAT</code><a class="headerlink" href="#os.EX_CANTCREAT" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means a user specified output file could not be created.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_IOERR">
<code class="descclassname">os.</code><code class="descname">EX_IOERR</code><a class="headerlink" href="#os.EX_IOERR" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means that an error occurred while doing I/O on some file.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_TEMPFAIL">
<code class="descclassname">os.</code><code class="descname">EX_TEMPFAIL</code><a class="headerlink" href="#os.EX_TEMPFAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means a temporary failure occurred.  This indicates something
that may not really be an error, such as a network connection that couldn’t be
made during a retryable operation.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_PROTOCOL">
<code class="descclassname">os.</code><code class="descname">EX_PROTOCOL</code><a class="headerlink" href="#os.EX_PROTOCOL" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means that a protocol exchange was illegal, invalid, or not
understood.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_NOPERM">
<code class="descclassname">os.</code><code class="descname">EX_NOPERM</code><a class="headerlink" href="#os.EX_NOPERM" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means that there were insufficient permissions to perform the
operation (but not intended for file system problems).</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_CONFIG">
<code class="descclassname">os.</code><code class="descname">EX_CONFIG</code><a class="headerlink" href="#os.EX_CONFIG" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means that some kind of configuration error occurred.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.EX_NOTFOUND">
<code class="descclassname">os.</code><code class="descname">EX_NOTFOUND</code><a class="headerlink" href="#os.EX_NOTFOUND" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit code that means something like “an entry was not found”.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.fork">
<code class="descclassname">os.</code><code class="descname">fork</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.fork" title="Permalink to this definition">¶</a></dt>
<dd><p>Fork a child process.  Return <code class="docutils literal notranslate"><span class="pre">0</span></code> in the child and the child’s process id in the
parent.  If an error occurs <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised.</p>
<p>Note that some platforms including FreeBSD &lt;= 6.3, Cygwin and OS/2 EMX have
known issues when using fork() from a thread.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">See <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> for applications that use the SSL module with fork().</p>
</div>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.forkpty">
<code class="descclassname">os.</code><code class="descname">forkpty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.forkpty" title="Permalink to this definition">¶</a></dt>
<dd><p>Fork a child process, using a new pseudo-terminal as the child’s controlling
terminal. Return a pair of <code class="docutils literal notranslate"><span class="pre">(pid,</span> <span class="pre">fd)</span></code>, where <em>pid</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code> in the child, the
new child’s process id in the parent, and <em>fd</em> is the file descriptor of the
master end of the pseudo-terminal.  For a more portable approach, use the
<a class="reference internal" href="pty.html#module-pty" title="pty: Pseudo-Terminal Handling for Linux. (Linux)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pty</span></code></a> module.  If an error occurs <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised.</p>
<p>Availability: some flavors of Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.kill">
<code class="descclassname">os.</code><code class="descname">kill</code><span class="sig-paren">(</span><em>pid</em>, <em>sig</em><span class="sig-paren">)</span><a class="headerlink" href="#os.kill" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-24">Send signal <em>sig</em> to the process <em>pid</em>.  Constants for the specific signals
available on the host platform are defined in the <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module.</p>
<p>Windows: The <a class="reference internal" href="signal.html#signal.CTRL_C_EVENT" title="signal.CTRL_C_EVENT"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.CTRL_C_EVENT</span></code></a> and
<a class="reference internal" href="signal.html#signal.CTRL_BREAK_EVENT" title="signal.CTRL_BREAK_EVENT"><code class="xref py py-data docutils literal notranslate"><span class="pre">signal.CTRL_BREAK_EVENT</span></code></a> signals are special signals which can
only be sent to console processes which share a common console window,
e.g., some subprocesses. Any other value for <em>sig</em> will cause the process
to be unconditionally killed by the TerminateProcess API, and the exit code
will be set to <em>sig</em>. The Windows version of <a class="reference internal" href="#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">kill()</span></code></a> additionally takes
process handles to be killed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>Windows support</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.killpg">
<code class="descclassname">os.</code><code class="descname">killpg</code><span class="sig-paren">(</span><em>pgid</em>, <em>sig</em><span class="sig-paren">)</span><a class="headerlink" href="#os.killpg" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-25">Send the signal <em>sig</em> to the process group <em>pgid</em>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.nice">
<code class="descclassname">os.</code><code class="descname">nice</code><span class="sig-paren">(</span><em>increment</em><span class="sig-paren">)</span><a class="headerlink" href="#os.nice" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>increment</em> to the process’s “niceness”.  Return the new niceness.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.plock">
<code class="descclassname">os.</code><code class="descname">plock</code><span class="sig-paren">(</span><em>op</em><span class="sig-paren">)</span><a class="headerlink" href="#os.plock" title="Permalink to this definition">¶</a></dt>
<dd><p>Lock program segments into memory.  The value of <em>op</em> (defined in
<code class="docutils literal notranslate"><span class="pre">&lt;sys/lock.h&gt;</span></code>) determines which segments are locked.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">os.</code><code class="descname">popen</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">os.</code><code class="descname">popen2</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">os.</code><code class="descname">popen3</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span></dt>
<dt>
<code class="descclassname">os.</code><code class="descname">popen4</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span></dt>
<dd><p>Run child processes, returning opened pipes for communications.  These functions
are described in section <a class="reference internal" href="#os-newstreams"><span class="std std-ref">File Object Creation</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.spawnl">
<code class="descclassname">os.</code><code class="descname">spawnl</code><span class="sig-paren">(</span><em>mode</em>, <em>path</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnl" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnle">
<code class="descclassname">os.</code><code class="descname">spawnle</code><span class="sig-paren">(</span><em>mode</em>, <em>path</em>, <em>...</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnle" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnlp">
<code class="descclassname">os.</code><code class="descname">spawnlp</code><span class="sig-paren">(</span><em>mode</em>, <em>file</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnlp" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnlpe">
<code class="descclassname">os.</code><code class="descname">spawnlpe</code><span class="sig-paren">(</span><em>mode</em>, <em>file</em>, <em>...</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnlpe" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnv">
<code class="descclassname">os.</code><code class="descname">spawnv</code><span class="sig-paren">(</span><em>mode</em>, <em>path</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnv" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnve">
<code class="descclassname">os.</code><code class="descname">spawnve</code><span class="sig-paren">(</span><em>mode</em>, <em>path</em>, <em>args</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnve" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnvp">
<code class="descclassname">os.</code><code class="descname">spawnvp</code><span class="sig-paren">(</span><em>mode</em>, <em>file</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnvp" title="Permalink to this definition">¶</a></dt>
<dt id="os.spawnvpe">
<code class="descclassname">os.</code><code class="descname">spawnvpe</code><span class="sig-paren">(</span><em>mode</em>, <em>file</em>, <em>args</em>, <em>env</em><span class="sig-paren">)</span><a class="headerlink" href="#os.spawnvpe" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the program <em>path</em> in a new process.</p>
<p>(Note that the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module provides more powerful facilities for
spawning new processes and retrieving their results; using that module is
preferable to using these functions.  Check especially the
<a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.)</p>
<p>If <em>mode</em> is <a class="reference internal" href="#os.P_NOWAIT" title="os.P_NOWAIT"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_NOWAIT</span></code></a>, this function returns the process id of the new
process; if <em>mode</em> is <a class="reference internal" href="#os.P_WAIT" title="os.P_WAIT"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_WAIT</span></code></a>, returns the process’s exit code if it
exits normally, or <code class="docutils literal notranslate"><span class="pre">-signal</span></code>, where <em>signal</em> is the signal that killed the
process.  On Windows, the process id will actually be the process handle, so can
be used with the <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a> function.</p>
<p>The “l” and “v” variants of the <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*</span></code></a> functions differ in how
command-line arguments are passed.  The “l” variants are perhaps the easiest
to work with if the number of parameters is fixed when the code is written; the
individual parameters simply become additional parameters to the
<code class="xref py py-func docutils literal notranslate"><span class="pre">spawnl*()</span></code> functions.  The “v” variants are good when the number of
parameters is variable, with the arguments being passed in a list or tuple as
the <em>args</em> parameter.  In either case, the arguments to the child process must
start with the name of the command being run.</p>
<p>The variants which include a second “p” near the end (<a class="reference internal" href="#os.spawnlp" title="os.spawnlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlp()</span></code></a>,
<a class="reference internal" href="#os.spawnlpe" title="os.spawnlpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlpe()</span></code></a>, <a class="reference internal" href="#os.spawnvp" title="os.spawnvp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvp()</span></code></a>, and <a class="reference internal" href="#os.spawnvpe" title="os.spawnvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvpe()</span></code></a>) will use the
<span class="target" id="index-26"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> environment variable to locate the program <em>file</em>.  When the
environment is being replaced (using one of the <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*e</span></code></a> variants,
discussed in the next paragraph), the new environment is used as the source of
the <span class="target" id="index-27"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable.  The other variants, <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnl()</span></code></a>,
<a class="reference internal" href="#os.spawnle" title="os.spawnle"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnle()</span></code></a>, <a class="reference internal" href="#os.spawnv" title="os.spawnv"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnv()</span></code></a>, and <a class="reference internal" href="#os.spawnve" title="os.spawnve"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnve()</span></code></a>, will not use the
<span class="target" id="index-28"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> variable to locate the executable; <em>path</em> must contain an
appropriate absolute or relative path.</p>
<p>For <a class="reference internal" href="#os.spawnle" title="os.spawnle"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnle()</span></code></a>, <a class="reference internal" href="#os.spawnlpe" title="os.spawnlpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlpe()</span></code></a>, <a class="reference internal" href="#os.spawnve" title="os.spawnve"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnve()</span></code></a>, and <a class="reference internal" href="#os.spawnvpe" title="os.spawnvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvpe()</span></code></a>
(note that these all end in “e”), the <em>env</em> parameter must be a mapping
which is used to define the environment variables for the new process (they are
used instead of the current process’ environment); the functions
<a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnl()</span></code></a>, <a class="reference internal" href="#os.spawnlp" title="os.spawnlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlp()</span></code></a>, <a class="reference internal" href="#os.spawnv" title="os.spawnv"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnv()</span></code></a>, and <a class="reference internal" href="#os.spawnvp" title="os.spawnvp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvp()</span></code></a> all cause
the new process to inherit the environment of the current process.  Note that
keys and values in the <em>env</em> dictionary must be strings; invalid keys or
values will cause the function to fail, with a return value of <code class="docutils literal notranslate"><span class="pre">127</span></code>.</p>
<p>As an example, the following calls to <a class="reference internal" href="#os.spawnlp" title="os.spawnlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlp()</span></code></a> and <a class="reference internal" href="#os.spawnvpe" title="os.spawnvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvpe()</span></code></a> are
equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="n">os</span><span class="o">.</span><span class="n">spawnlp</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_WAIT</span><span class="p">,</span> <span class="s1">&#39;cp&#39;</span><span class="p">,</span> <span class="s1">&#39;cp&#39;</span><span class="p">,</span> <span class="s1">&#39;index.html&#39;</span><span class="p">,</span> <span class="s1">&#39;/dev/null&#39;</span><span class="p">)</span>

<span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;cp&#39;</span><span class="p">,</span> <span class="s1">&#39;index.html&#39;</span><span class="p">,</span> <span class="s1">&#39;/dev/null&#39;</span><span class="p">]</span>
<span class="n">os</span><span class="o">.</span><span class="n">spawnvpe</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_WAIT</span><span class="p">,</span> <span class="s1">&#39;cp&#39;</span><span class="p">,</span> <span class="n">L</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">)</span>
</pre></div>
</div>
<p>Availability: Unix, Windows.  <a class="reference internal" href="#os.spawnlp" title="os.spawnlp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlp()</span></code></a>, <a class="reference internal" href="#os.spawnlpe" title="os.spawnlpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnlpe()</span></code></a>, <a class="reference internal" href="#os.spawnvp" title="os.spawnvp"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvp()</span></code></a>
and <a class="reference internal" href="#os.spawnvpe" title="os.spawnvpe"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnvpe()</span></code></a> are not available on Windows.  <a class="reference internal" href="#os.spawnle" title="os.spawnle"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnle()</span></code></a> and
<a class="reference internal" href="#os.spawnve" title="os.spawnve"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawnve()</span></code></a> are not thread-safe on Windows; we advise you to use the
<a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module instead.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.P_NOWAIT">
<code class="descclassname">os.</code><code class="descname">P_NOWAIT</code><a class="headerlink" href="#os.P_NOWAIT" title="Permalink to this definition">¶</a></dt>
<dt id="os.P_NOWAITO">
<code class="descclassname">os.</code><code class="descname">P_NOWAITO</code><a class="headerlink" href="#os.P_NOWAITO" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible values for the <em>mode</em> parameter to the <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*</span></code></a> family of
functions.  If either of these values is given, the <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*()</span></code> functions
will return as soon as the new process has been created, with the process id as
the return value.</p>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.P_WAIT">
<code class="descclassname">os.</code><code class="descname">P_WAIT</code><a class="headerlink" href="#os.P_WAIT" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for the <em>mode</em> parameter to the <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*</span></code></a> family of
functions.  If this is given as <em>mode</em>, the <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*()</span></code> functions will not
return until the new process has run to completion and will return the exit code
of the process the run is successful, or <code class="docutils literal notranslate"><span class="pre">-signal</span></code> if a signal kills the
process.</p>
<p>Availability: Unix, Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.P_DETACH">
<code class="descclassname">os.</code><code class="descname">P_DETACH</code><a class="headerlink" href="#os.P_DETACH" title="Permalink to this definition">¶</a></dt>
<dt id="os.P_OVERLAY">
<code class="descclassname">os.</code><code class="descname">P_OVERLAY</code><a class="headerlink" href="#os.P_OVERLAY" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible values for the <em>mode</em> parameter to the <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*</span></code></a> family of
functions.  These are less portable than those listed above. <a class="reference internal" href="#os.P_DETACH" title="os.P_DETACH"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_DETACH</span></code></a>
is similar to <a class="reference internal" href="#os.P_NOWAIT" title="os.P_NOWAIT"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_NOWAIT</span></code></a>, but the new process is detached from the
console of the calling process. If <a class="reference internal" href="#os.P_OVERLAY" title="os.P_OVERLAY"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_OVERLAY</span></code></a> is used, the current
process will be replaced; the <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*()</span></code> function will not return.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.startfile">
<code class="descclassname">os.</code><code class="descname">startfile</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>operation</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.startfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Start a file with its associated application.</p>
<p>When <em>operation</em> is not specified or <code class="docutils literal notranslate"><span class="pre">'open'</span></code>, this acts like double-clicking
the file in Windows Explorer, or giving the file name as an argument to the
<strong class="program">start</strong> command from the interactive command shell: the file is opened
with whatever application (if any) its extension is associated.</p>
<p>When another <em>operation</em> is given, it must be a “command verb” that specifies
what should be done with the file. Common verbs documented by Microsoft are
<code class="docutils literal notranslate"><span class="pre">'print'</span></code> and  <code class="docutils literal notranslate"><span class="pre">'edit'</span></code> (to be used on files) as well as <code class="docutils literal notranslate"><span class="pre">'explore'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'find'</span></code> (to be used on directories).</p>
<p><a class="reference internal" href="#os.startfile" title="os.startfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">startfile()</span></code></a> returns as soon as the associated application is launched.
There is no option to wait for the application to close, and no way to retrieve
the application’s exit status.  The <em>path</em> parameter is relative to the current
directory.  If you want to use an absolute path, make sure the first character
is not a slash (<code class="docutils literal notranslate"><span class="pre">'/'</span></code>); the underlying Win32 <code class="xref c c-func docutils literal notranslate"><span class="pre">ShellExecute()</span></code> function
doesn’t work if it is.  Use the <a class="reference internal" href="os.path.html#os.path.normpath" title="os.path.normpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.normpath()</span></code></a> function to ensure that
the path is properly encoded for Win32.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>The <em>operation</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.system">
<code class="descclassname">os.</code><code class="descname">system</code><span class="sig-paren">(</span><em>command</em><span class="sig-paren">)</span><a class="headerlink" href="#os.system" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the command (a string) in a subshell.  This is implemented by calling
the Standard C function <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code>, and has the same limitations.
Changes to <a class="reference internal" href="sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a>, etc. are not reflected in the environment of the
executed command.</p>
<p>On Unix, the return value is the exit status of the process encoded in the
format specified for <a class="reference internal" href="#os.wait" title="os.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a>.  Note that POSIX does not specify the meaning
of the return value of the C <code class="xref c c-func docutils literal notranslate"><span class="pre">system()</span></code> function, so the return value of
the Python function is system-dependent.</p>
<p>On Windows, the return value is that returned by the system shell after running
<em>command</em>, given by the Windows environment variable <span class="target" id="index-29"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">COMSPEC</span></code>: on
<strong class="program">command.com</strong> systems (Windows 95, 98 and ME) this is always <code class="docutils literal notranslate"><span class="pre">0</span></code>; on
<strong class="program">cmd.exe</strong> systems (Windows NT, 2000 and XP) this is the exit status of
the command run; on systems using a non-native shell, consult your shell
documentation.</p>
<p>The <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module provides more powerful facilities for spawning new
processes and retrieving their results; using that module is preferable to using
this function.  See the
<a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section in the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> documentation
for some helpful recipes.</p>
<p>Availability: Unix, Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.times">
<code class="descclassname">os.</code><code class="descname">times</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.times" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a 5-tuple of floating point numbers indicating accumulated (processor
or other) times, in seconds.  The items are: user time, system time,
children’s user time, children’s system time, and elapsed real time since a
fixed point in the past, in that order.  See the Unix manual page
<em class="manpage">times(2)</em> or the corresponding Windows Platform API documentation.
On Windows, only the first two items are filled, the others are zero.</p>
<p>Availability: Unix, Windows</p>
</dd></dl>

<dl class="function">
<dt id="os.wait">
<code class="descclassname">os.</code><code class="descname">wait</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for completion of a child process, and return a tuple containing its pid
and exit status indication: a 16-bit number, whose low byte is the signal number
that killed the process, and whose high byte is the exit status (if the signal
number is zero); the high bit of the low byte is set if a core file was
produced.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.waitpid">
<code class="descclassname">os.</code><code class="descname">waitpid</code><span class="sig-paren">(</span><em>pid</em>, <em>options</em><span class="sig-paren">)</span><a class="headerlink" href="#os.waitpid" title="Permalink to this definition">¶</a></dt>
<dd><p>The details of this function differ on Unix and Windows.</p>
<p>On Unix: Wait for completion of a child process given by process id <em>pid</em>, and
return a tuple containing its process id and exit status indication (encoded as
for <a class="reference internal" href="#os.wait" title="os.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a>).  The semantics of the call are affected by the value of the
integer <em>options</em>, which should be <code class="docutils literal notranslate"><span class="pre">0</span></code> for normal operation.</p>
<p>If <em>pid</em> is greater than <code class="docutils literal notranslate"><span class="pre">0</span></code>, <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a> requests status information for
that specific process.  If <em>pid</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, the request is for the status of any
child in the process group of the current process.  If <em>pid</em> is <code class="docutils literal notranslate"><span class="pre">-1</span></code>, the
request pertains to any child of the current process.  If <em>pid</em> is less than
<code class="docutils literal notranslate"><span class="pre">-1</span></code>, status is requested for any process in the process group <code class="docutils literal notranslate"><span class="pre">-pid</span></code> (the
absolute value of <em>pid</em>).</p>
<p>An <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised with the value of errno when the syscall
returns -1.</p>
<p>On Windows: Wait for completion of a process given by process handle <em>pid</em>, and
return a tuple containing <em>pid</em>, and its exit status shifted left by 8 bits
(shifting makes cross-platform use of the function easier). A <em>pid</em> less than or
equal to <code class="docutils literal notranslate"><span class="pre">0</span></code> has no special meaning on Windows, and raises an exception. The
value of integer <em>options</em> has no effect. <em>pid</em> can refer to any process whose
id is known, not necessarily a child process. The <a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*</span></code></a>
functions called with <a class="reference internal" href="#os.P_NOWAIT" title="os.P_NOWAIT"><code class="xref py py-const docutils literal notranslate"><span class="pre">P_NOWAIT</span></code></a> return suitable process handles.</p>
</dd></dl>

<dl class="function">
<dt id="os.wait3">
<code class="descclassname">os.</code><code class="descname">wait3</code><span class="sig-paren">(</span><em>options</em><span class="sig-paren">)</span><a class="headerlink" href="#os.wait3" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a>, except no process id argument is given and a
3-element tuple containing the child’s process id, exit status indication, and
resource usage information is returned.  Refer to <a class="reference internal" href="resource.html#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">resource</span></code></a>.<a class="reference internal" href="resource.html#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrusage()</span></code></a> for details on resource usage information.  The
option argument is the same as that provided to <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a> and
<a class="reference internal" href="#os.wait4" title="os.wait4"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code></a>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.wait4">
<code class="descclassname">os.</code><code class="descname">wait4</code><span class="sig-paren">(</span><em>pid</em>, <em>options</em><span class="sig-paren">)</span><a class="headerlink" href="#os.wait4" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a>, except a 3-element tuple, containing the child’s
process id, exit status indication, and resource usage information is returned.
Refer to <a class="reference internal" href="resource.html#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">resource</span></code></a>.<a class="reference internal" href="resource.html#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrusage()</span></code></a> for details on
resource usage information.  The arguments to <a class="reference internal" href="#os.wait4" title="os.wait4"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code></a> are the same as
those provided to <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.WNOHANG">
<code class="descclassname">os.</code><code class="descname">WNOHANG</code><a class="headerlink" href="#os.WNOHANG" title="Permalink to this definition">¶</a></dt>
<dd><p>The option for <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a> to return immediately if no child process status
is available immediately. The function returns <code class="docutils literal notranslate"><span class="pre">(0,</span> <span class="pre">0)</span></code> in this case.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="data">
<dt id="os.WCONTINUED">
<code class="descclassname">os.</code><code class="descname">WCONTINUED</code><a class="headerlink" href="#os.WCONTINUED" title="Permalink to this definition">¶</a></dt>
<dd><p>This option causes child processes to be reported if they have been continued
from a job control stop since their status was last reported.</p>
<p>Availability: Some Unix systems.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.WUNTRACED">
<code class="descclassname">os.</code><code class="descname">WUNTRACED</code><a class="headerlink" href="#os.WUNTRACED" title="Permalink to this definition">¶</a></dt>
<dd><p>This option causes child processes to be reported if they have been stopped but
their current state has not been reported since they were stopped.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>The following functions take a process status code as returned by
<a class="reference internal" href="#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">system()</span></code></a>, <a class="reference internal" href="#os.wait" title="os.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a>, or <a class="reference internal" href="#os.waitpid" title="os.waitpid"><code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code></a> as a parameter.  They may be
used to determine the disposition of a process.</p>
<dl class="function">
<dt id="os.WCOREDUMP">
<code class="descclassname">os.</code><code class="descname">WCOREDUMP</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WCOREDUMP" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if a core dump was generated for the process, otherwise
return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.WIFCONTINUED">
<code class="descclassname">os.</code><code class="descname">WIFCONTINUED</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WIFCONTINUED" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the process has been continued from a job control stop,
otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.WIFSTOPPED">
<code class="descclassname">os.</code><code class="descname">WIFSTOPPED</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WIFSTOPPED" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the process has been stopped, otherwise return
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.WIFSIGNALED">
<code class="descclassname">os.</code><code class="descname">WIFSIGNALED</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WIFSIGNALED" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the process exited due to a signal, otherwise return
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.WIFEXITED">
<code class="descclassname">os.</code><code class="descname">WIFEXITED</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WIFEXITED" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the process exited using the <em class="manpage">exit(2)</em> system call,
otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.WEXITSTATUS">
<code class="descclassname">os.</code><code class="descname">WEXITSTATUS</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WEXITSTATUS" title="Permalink to this definition">¶</a></dt>
<dd><p>If <code class="docutils literal notranslate"><span class="pre">WIFEXITED(status)</span></code> is true, return the integer parameter to the
<em class="manpage">exit(2)</em> system call.  Otherwise, the return value is meaningless.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.WSTOPSIG">
<code class="descclassname">os.</code><code class="descname">WSTOPSIG</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WSTOPSIG" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the signal which caused the process to stop.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.WTERMSIG">
<code class="descclassname">os.</code><code class="descname">WTERMSIG</code><span class="sig-paren">(</span><em>status</em><span class="sig-paren">)</span><a class="headerlink" href="#os.WTERMSIG" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the signal which caused the process to exit.</p>
<p>Availability: Unix.</p>
</dd></dl>

</div>
<div class="section" id="miscellaneous-system-information">
<span id="os-path"></span><h2>15.1.6. Miscellaneous System Information<a class="headerlink" href="#miscellaneous-system-information" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="os.confstr">
<code class="descclassname">os.</code><code class="descname">confstr</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.confstr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return string-valued system configuration values. <em>name</em> specifies the
configuration value to retrieve; it may be a string which is the name of a
defined system value; these names are specified in a number of standards (POSIX,
Unix 95, Unix 98, and others).  Some platforms define additional names as well.
The names known to the host operating system are given as the keys of the
<code class="docutils literal notranslate"><span class="pre">confstr_names</span></code> dictionary.  For configuration variables not included in that
mapping, passing an integer for <em>name</em> is also accepted.</p>
<p>If the configuration value specified by <em>name</em> isn’t defined, <code class="docutils literal notranslate"><span class="pre">None</span></code> is
returned.</p>
<p>If <em>name</em> is a string and is not known, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  If a
specific value for <em>name</em> is not supported by the host system, even if it is
included in <code class="docutils literal notranslate"><span class="pre">confstr_names</span></code>, an <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> is raised with
<a class="reference internal" href="errno.html#errno.EINVAL" title="errno.EINVAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">errno.EINVAL</span></code></a> for the error number.</p>
<p>Availability: Unix</p>
</dd></dl>

<dl class="data">
<dt id="os.confstr_names">
<code class="descclassname">os.</code><code class="descname">confstr_names</code><a class="headerlink" href="#os.confstr_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping names accepted by <a class="reference internal" href="#os.confstr" title="os.confstr"><code class="xref py py-func docutils literal notranslate"><span class="pre">confstr()</span></code></a> to the integer values
defined for those names by the host operating system. This can be used to
determine the set of names known to the system.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.getloadavg">
<code class="descclassname">os.</code><code class="descname">getloadavg</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#os.getloadavg" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of processes in the system run queue averaged over the last
1, 5, and 15 minutes or raises <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> if the load average was
unobtainable.</p>
<p>Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.sysconf">
<code class="descclassname">os.</code><code class="descname">sysconf</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#os.sysconf" title="Permalink to this definition">¶</a></dt>
<dd><p>Return integer-valued system configuration values. If the configuration value
specified by <em>name</em> isn’t defined, <code class="docutils literal notranslate"><span class="pre">-1</span></code> is returned.  The comments regarding
the <em>name</em> parameter for <a class="reference internal" href="#os.confstr" title="os.confstr"><code class="xref py py-func docutils literal notranslate"><span class="pre">confstr()</span></code></a> apply here as well; the dictionary that
provides information on the known names is given by <code class="docutils literal notranslate"><span class="pre">sysconf_names</span></code>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="data">
<dt id="os.sysconf_names">
<code class="descclassname">os.</code><code class="descname">sysconf_names</code><a class="headerlink" href="#os.sysconf_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping names accepted by <a class="reference internal" href="#os.sysconf" title="os.sysconf"><code class="xref py py-func docutils literal notranslate"><span class="pre">sysconf()</span></code></a> to the integer values
defined for those names by the host operating system. This can be used to
determine the set of names known to the system.</p>
<p>Availability: Unix.</p>
</dd></dl>

<p>The following data values are used to support path manipulation operations.  These
are defined for all platforms.</p>
<p>Higher-level operations on pathnames are defined in the <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module.</p>
<dl class="data">
<dt id="os.curdir">
<code class="descclassname">os.</code><code class="descname">curdir</code><a class="headerlink" href="#os.curdir" title="Permalink to this definition">¶</a></dt>
<dd><p>The constant string used by the operating system to refer to the current
directory. This is <code class="docutils literal notranslate"><span class="pre">'.'</span></code> for Windows and POSIX. Also available via
<a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.pardir">
<code class="descclassname">os.</code><code class="descname">pardir</code><a class="headerlink" href="#os.pardir" title="Permalink to this definition">¶</a></dt>
<dd><p>The constant string used by the operating system to refer to the parent
directory. This is <code class="docutils literal notranslate"><span class="pre">'..'</span></code> for Windows and POSIX. Also available via
<a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.sep">
<code class="descclassname">os.</code><code class="descname">sep</code><a class="headerlink" href="#os.sep" title="Permalink to this definition">¶</a></dt>
<dd><p>The character used by the operating system to separate pathname components.
This is <code class="docutils literal notranslate"><span class="pre">'/'</span></code> for POSIX and <code class="docutils literal notranslate"><span class="pre">'\\'</span></code> for Windows.  Note that knowing this
is not sufficient to be able to parse or concatenate pathnames — use
<a class="reference internal" href="os.path.html#os.path.split" title="os.path.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.split()</span></code></a> and <a class="reference internal" href="os.path.html#os.path.join" title="os.path.join"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.join()</span></code></a> — but it is occasionally
useful. Also available via <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.altsep">
<code class="descclassname">os.</code><code class="descname">altsep</code><a class="headerlink" href="#os.altsep" title="Permalink to this definition">¶</a></dt>
<dd><p>An alternative character used by the operating system to separate pathname
components, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if only one separator character exists.  This is set to
<code class="docutils literal notranslate"><span class="pre">'/'</span></code> on Windows systems where <code class="docutils literal notranslate"><span class="pre">sep</span></code> is a backslash. Also available via
<a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.extsep">
<code class="descclassname">os.</code><code class="descname">extsep</code><a class="headerlink" href="#os.extsep" title="Permalink to this definition">¶</a></dt>
<dd><p>The character which separates the base filename from the extension; for example,
the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> in <code class="file docutils literal notranslate"><span class="pre">os.py</span></code>. Also available via <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.pathsep">
<code class="descclassname">os.</code><code class="descname">pathsep</code><a class="headerlink" href="#os.pathsep" title="Permalink to this definition">¶</a></dt>
<dd><p>The character conventionally used by the operating system to separate search
path components (as in <span class="target" id="index-30"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>), such as <code class="docutils literal notranslate"><span class="pre">':'</span></code> for POSIX or <code class="docutils literal notranslate"><span class="pre">';'</span></code> for
Windows. Also available via <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.defpath">
<code class="descclassname">os.</code><code class="descname">defpath</code><a class="headerlink" href="#os.defpath" title="Permalink to this definition">¶</a></dt>
<dd><p>The default search path used by <a class="reference internal" href="#os.execl" title="os.execl"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec*p*</span></code></a> and
<a class="reference internal" href="#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">spawn*p*</span></code></a> if the environment doesn’t have a <code class="docutils literal notranslate"><span class="pre">'PATH'</span></code>
key. Also available via <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="os.linesep">
<code class="descclassname">os.</code><code class="descname">linesep</code><a class="headerlink" href="#os.linesep" title="Permalink to this definition">¶</a></dt>
<dd><p>The string used to separate (or, rather, terminate) lines on the current
platform.  This may be a single character, such as <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> for POSIX, or
multiple characters, for example, <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code> for Windows. Do not use
<em>os.linesep</em> as a line terminator when writing files opened in text mode (the
default); use a single <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> instead, on all platforms.</p>
</dd></dl>

<dl class="data">
<dt id="os.devnull">
<code class="descclassname">os.</code><code class="descname">devnull</code><a class="headerlink" href="#os.devnull" title="Permalink to this definition">¶</a></dt>
<dd><p>The file path of the null device. For example: <code class="docutils literal notranslate"><span class="pre">'/dev/null'</span></code> for
POSIX, <code class="docutils literal notranslate"><span class="pre">'nul'</span></code> for Windows.  Also available via <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="miscellaneous-functions">
<span id="os-miscfunc"></span><h2>15.1.7. Miscellaneous Functions<a class="headerlink" href="#miscellaneous-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="os.urandom">
<code class="descclassname">os.</code><code class="descname">urandom</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#os.urandom" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string of <em>n</em> random bytes suitable for cryptographic use.</p>
<p>This function returns random bytes from an OS-specific randomness source.  The
returned data should be unpredictable enough for cryptographic applications,
though its exact quality depends on the OS implementation.  On a UNIX-like
system this will query <code class="docutils literal notranslate"><span class="pre">/dev/urandom</span></code>, and on Windows it will use
<code class="docutils literal notranslate"><span class="pre">CryptGenRandom()</span></code>.  If a randomness source is not found,
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> will be raised.</p>
<p>For an easy-to-use interface to the random number generator
provided by your platform, please see <a class="reference internal" href="random.html#random.SystemRandom" title="random.SystemRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">random.SystemRandom</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a><ul>
<li><a class="reference internal" href="#process-parameters">15.1.1. Process Parameters</a></li>
<li><a class="reference internal" href="#file-object-creation">15.1.2. File Object Creation</a></li>
<li><a class="reference internal" href="#file-descriptor-operations">15.1.3. File Descriptor Operations</a><ul>
<li><a class="reference internal" href="#open-flag-constants">15.1.3.1. <code class="docutils literal notranslate"><span class="pre">open()</span></code> flag constants</a></li>
</ul>
</li>
<li><a class="reference internal" href="#files-and-directories">15.1.4. Files and Directories</a></li>
<li><a class="reference internal" href="#process-management">15.1.5. Process Management</a></li>
<li><a class="reference internal" href="#miscellaneous-system-information">15.1.6. Miscellaneous System Information</a></li>
<li><a class="reference internal" href="#miscellaneous-functions">15.1.7. Miscellaneous Functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="allos.html"
                        title="previous chapter">15. Generic Operating System Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="io.html"
                        title="next chapter">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/os.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="io.html" title="15.2. io — Core tools for working with streams"
             >next</a> |</li>
        <li class="right" >
          <a href="allos.html" title="15. Generic Operating System Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��>����html/library/os.path.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.1. os.path — Common pathname manipulations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.2. fileinput — Iterate over lines from multiple input streams" href="fileinput.html" />
    <link rel="prev" title="10. File and Directory Access" href="filesys.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/os.path.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fileinput.html" title="10.2. fileinput — Iterate over lines from multiple input streams"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="filesys.html" title="10. File and Directory Access"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-os.path">
<span id="os-path-common-pathname-manipulations"></span><h1>10.1. <a class="reference internal" href="#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> — Common pathname manipulations<a class="headerlink" href="#module-os.path" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module implements some useful functions on pathnames. To read or
write files see <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, and for accessing the filesystem see the
<a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Windows, many of these functions do not properly support UNC pathnames.
<a class="reference internal" href="#os.path.splitunc" title="os.path.splitunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">splitunc()</span></code></a> and <a class="reference internal" href="#os.path.ismount" title="os.path.ismount"><code class="xref py py-func docutils literal notranslate"><span class="pre">ismount()</span></code></a> do handle them correctly.</p>
</div>
<p>Unlike a unix shell, Python does not do any <em>automatic</em> path expansions.
Functions such as <a class="reference internal" href="#os.path.expanduser" title="os.path.expanduser"><code class="xref py py-func docutils literal notranslate"><span class="pre">expanduser()</span></code></a> and <a class="reference internal" href="#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">expandvars()</span></code></a> can be invoked
explicitly when an application desires shell-like path expansion.  (See also
the <a class="reference internal" href="glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> module.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Since different operating systems have different path name conventions, there
are several versions of this module in the standard library.  The
<a class="reference internal" href="#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module is always the path module suitable for the operating
system Python is running on, and therefore usable for local paths.  However,
you can also import and use the individual modules if you want to manipulate
a path that is <em>always</em> in one of the different formats.  They all have the
same interface:</p>
<ul class="last simple">
<li><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixpath</span></code> for UNIX-style paths</li>
<li><code class="xref py py-mod docutils literal notranslate"><span class="pre">ntpath</span></code> for Windows paths</li>
<li><a class="reference internal" href="macpath.html#module-macpath" title="macpath: Mac OS 9 path manipulation functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">macpath</span></code></a> for old-style MacOS paths</li>
<li><code class="xref py py-mod docutils literal notranslate"><span class="pre">os2emxpath</span></code> for OS/2 EMX paths</li>
</ul>
</div>
<dl class="function">
<dt id="os.path.abspath">
<code class="descclassname">os.path.</code><code class="descname">abspath</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.abspath" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a normalized absolutized version of the pathname <em>path</em>. On most
platforms, this is equivalent to calling the function <a class="reference internal" href="#os.path.normpath" title="os.path.normpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">normpath()</span></code></a> as
follows: <code class="docutils literal notranslate"><span class="pre">normpath(join(os.getcwd(),</span> <span class="pre">path))</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.basename">
<code class="descclassname">os.path.</code><code class="descname">basename</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.basename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the base name of pathname <em>path</em>.  This is the second element of the
pair returned by passing <em>path</em> to the function <a class="reference internal" href="#os.path.split" title="os.path.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>.  Note that
the result of this function is different
from the Unix <strong class="program">basename</strong> program; where <strong class="program">basename</strong> for
<code class="docutils literal notranslate"><span class="pre">'/foo/bar/'</span></code> returns <code class="docutils literal notranslate"><span class="pre">'bar'</span></code>, the <a class="reference internal" href="#os.path.basename" title="os.path.basename"><code class="xref py py-func docutils literal notranslate"><span class="pre">basename()</span></code></a> function returns an
empty string (<code class="docutils literal notranslate"><span class="pre">''</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="os.path.commonprefix">
<code class="descclassname">os.path.</code><code class="descname">commonprefix</code><span class="sig-paren">(</span><em>list</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.commonprefix" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the longest path prefix (taken character-by-character) that is a prefix
of all paths in  <em>list</em>.  If <em>list</em> is empty, return the empty string (<code class="docutils literal notranslate"><span class="pre">''</span></code>).
Note that this may return invalid paths because it works a character at a time.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.dirname">
<code class="descclassname">os.path.</code><code class="descname">dirname</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.dirname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the directory name of pathname <em>path</em>.  This is the first element of
the pair returned by passing <em>path</em> to the function <a class="reference internal" href="#os.path.split" title="os.path.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.exists">
<code class="descclassname">os.path.</code><code class="descname">exists</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.exists" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> refers to an existing path.  Returns <code class="docutils literal notranslate"><span class="pre">False</span></code> for
broken symbolic links. On some platforms, this function may return <code class="docutils literal notranslate"><span class="pre">False</span></code> if
permission is not granted to execute <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> on the requested file, even
if the <em>path</em> physically exists.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.lexists">
<code class="descclassname">os.path.</code><code class="descname">lexists</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.lexists" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> refers to an existing path. Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> for
broken symbolic links.   Equivalent to <a class="reference internal" href="#os.path.exists" title="os.path.exists"><code class="xref py py-func docutils literal notranslate"><span class="pre">exists()</span></code></a> on platforms lacking
<a class="reference internal" href="os.html#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lstat()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.expanduser">
<code class="descclassname">os.path.</code><code class="descname">expanduser</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.expanduser" title="Permalink to this definition">¶</a></dt>
<dd><p>On Unix and Windows, return the argument with an initial component of <code class="docutils literal notranslate"><span class="pre">~</span></code> or
<code class="docutils literal notranslate"><span class="pre">~user</span></code> replaced by that <em>user</em>’s home directory.</p>
<p id="index-1">On Unix, an initial <code class="docutils literal notranslate"><span class="pre">~</span></code> is replaced by the environment variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code>
if it is set; otherwise the current user’s home directory is looked up in the
password directory through the built-in module <a class="reference internal" href="pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a>. An initial <code class="docutils literal notranslate"><span class="pre">~user</span></code>
is looked up directly in the password directory.</p>
<p>On Windows, <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code> and <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">USERPROFILE</span></code> will be used if set,
otherwise a combination of <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOMEPATH</span></code> and <span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOMEDRIVE</span></code> will be
used.  An initial <code class="docutils literal notranslate"><span class="pre">~user</span></code> is handled by stripping the last directory component
from the created user path derived above.</p>
<p>If the expansion fails or if the path does not begin with a tilde, the path is
returned unchanged.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.expandvars">
<code class="descclassname">os.path.</code><code class="descname">expandvars</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.expandvars" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the argument with environment variables expanded.  Substrings of the form
<code class="docutils literal notranslate"><span class="pre">$name</span></code> or <code class="docutils literal notranslate"><span class="pre">${name}</span></code> are replaced by the value of environment variable
<em>name</em>.  Malformed variable names and references to non-existing variables are
left unchanged.</p>
<p>On Windows, <code class="docutils literal notranslate"><span class="pre">%name%</span></code> expansions are supported in addition to <code class="docutils literal notranslate"><span class="pre">$name</span></code> and
<code class="docutils literal notranslate"><span class="pre">${name}</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.getatime">
<code class="descclassname">os.path.</code><code class="descname">getatime</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.getatime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the time of last access of <em>path</em>.  The return value is a number giving
the number of seconds since the epoch (see the  <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module).  Raise
<a class="reference internal" href="os.html#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">os.error</span></code></a> if the file does not exist or is inaccessible.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>If <a class="reference internal" href="os.html#os.stat_float_times" title="os.stat_float_times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat_float_times()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the result is a floating point
number.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.getmtime">
<code class="descclassname">os.path.</code><code class="descname">getmtime</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.getmtime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the time of last modification of <em>path</em>.  The return value is a number
giving the number of seconds since the epoch (see the  <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module).
Raise <a class="reference internal" href="os.html#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">os.error</span></code></a> if the file does not exist or is inaccessible.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>If <a class="reference internal" href="os.html#os.stat_float_times" title="os.stat_float_times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat_float_times()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>, the result is a floating point
number.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.getctime">
<code class="descclassname">os.path.</code><code class="descname">getctime</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.getctime" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the system’s ctime which, on some systems (like Unix) is the time of the
last metadata change, and, on others (like Windows), is the creation time for <em>path</em>.
The return value is a number giving the number of seconds since the epoch (see
the  <a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module).  Raise <a class="reference internal" href="os.html#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">os.error</span></code></a> if the file does not exist or
is inaccessible.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.getsize">
<code class="descclassname">os.path.</code><code class="descname">getsize</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.getsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size, in bytes, of <em>path</em>.  Raise <a class="reference internal" href="os.html#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">os.error</span></code></a> if the file does
not exist or is inaccessible.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.isabs">
<code class="descclassname">os.path.</code><code class="descname">isabs</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.isabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> is an absolute pathname.  On Unix, that means it
begins with a slash, on Windows that it begins with a (back)slash after chopping
off a potential drive letter.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.isfile">
<code class="descclassname">os.path.</code><code class="descname">isfile</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.isfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> is an existing regular file.  This follows symbolic
links, so both <a class="reference internal" href="#os.path.islink" title="os.path.islink"><code class="xref py py-func docutils literal notranslate"><span class="pre">islink()</span></code></a> and <a class="reference internal" href="#os.path.isfile" title="os.path.isfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">isfile()</span></code></a> can be true for the same path.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.isdir">
<code class="descclassname">os.path.</code><code class="descname">isdir</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.isdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> is an existing directory.  This follows symbolic
links, so both <a class="reference internal" href="#os.path.islink" title="os.path.islink"><code class="xref py py-func docutils literal notranslate"><span class="pre">islink()</span></code></a> and <a class="reference internal" href="#os.path.isdir" title="os.path.isdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">isdir()</span></code></a> can be true for the same path.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.islink">
<code class="descclassname">os.path.</code><code class="descname">islink</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.islink" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>path</em> refers to a directory entry that is a symbolic link.
Always <code class="docutils literal notranslate"><span class="pre">False</span></code> if symbolic links are not supported by the Python runtime.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.ismount">
<code class="descclassname">os.path.</code><code class="descname">ismount</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.ismount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if pathname <em>path</em> is a <em class="dfn">mount point</em>: a point in a file
system where a different file system has been mounted.  The function checks
whether <em>path</em>’s parent, <code class="file docutils literal notranslate"><span class="pre">path/..</span></code>, is on a different device than <em>path</em>,
or whether <code class="file docutils literal notranslate"><span class="pre">path/..</span></code> and <em>path</em> point to the same i-node on the same
device — this should detect mount points for all Unix and POSIX variants.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.join">
<code class="descclassname">os.path.</code><code class="descname">join</code><span class="sig-paren">(</span><em>path</em>, <em>*paths</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Join one or more path components intelligently.  The return value is the
concatenation of <em>path</em> and any members of <em>*paths</em> with exactly one
directory separator (<code class="docutils literal notranslate"><span class="pre">os.sep</span></code>) following each non-empty part except the
last, meaning that the result will only end in a separator if the last
part is empty.  If a component is an absolute path, all previous
components are thrown away and joining continues from the absolute path
component.</p>
<p>On Windows, the drive letter is not reset when an absolute path component
(e.g., <code class="docutils literal notranslate"><span class="pre">r'\foo'</span></code>) is encountered.  If a component contains a drive
letter, all previous components are thrown away and the drive letter is
reset.  Note that since there is a current directory for each drive,
<code class="docutils literal notranslate"><span class="pre">os.path.join(&quot;c:&quot;,</span> <span class="pre">&quot;foo&quot;)</span></code> represents a path relative to the current
directory on drive <code class="file docutils literal notranslate"><span class="pre">C:</span></code> (<code class="file docutils literal notranslate"><span class="pre">c:foo</span></code>), not <code class="file docutils literal notranslate"><span class="pre">c:\foo</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.normcase">
<code class="descclassname">os.path.</code><code class="descname">normcase</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.normcase" title="Permalink to this definition">¶</a></dt>
<dd><p>Normalize the case of a pathname.  On Unix and Mac OS X, this returns the
path unchanged; on case-insensitive filesystems, it converts the path to
lowercase.  On Windows, it also converts forward slashes to backward slashes.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.normpath">
<code class="descclassname">os.path.</code><code class="descname">normpath</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.normpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Normalize a pathname by collapsing redundant separators and up-level
references so that <code class="docutils literal notranslate"><span class="pre">A//B</span></code>, <code class="docutils literal notranslate"><span class="pre">A/B/</span></code>, <code class="docutils literal notranslate"><span class="pre">A/./B</span></code> and <code class="docutils literal notranslate"><span class="pre">A/foo/../B</span></code> all
become <code class="docutils literal notranslate"><span class="pre">A/B</span></code>.  This string manipulation may change the meaning of a path
that contains symbolic links.  On Windows, it converts forward slashes to
backward slashes. To normalize case, use <a class="reference internal" href="#os.path.normcase" title="os.path.normcase"><code class="xref py py-func docutils literal notranslate"><span class="pre">normcase()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.realpath">
<code class="descclassname">os.path.</code><code class="descname">realpath</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.realpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the canonical path of the specified filename, eliminating any symbolic
links encountered in the path (if they are supported by the operating system).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.relpath">
<code class="descclassname">os.path.</code><code class="descname">relpath</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>start</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#os.path.relpath" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a relative filepath to <em>path</em> either from the current directory or
from an optional <em>start</em> directory.  This is a path computation:  the
filesystem is not accessed to confirm the existence or nature of <em>path</em> or
<em>start</em>.</p>
<p><em>start</em> defaults to <a class="reference internal" href="os.html#os.curdir" title="os.curdir"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.curdir</span></code></a>.</p>
<p>Availability:  Windows, Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.samefile">
<code class="descclassname">os.path.</code><code class="descname">samefile</code><span class="sig-paren">(</span><em>path1</em>, <em>path2</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.samefile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if both pathname arguments refer to the same file or directory
(as indicated by device number and i-node number). Raise an exception if an
<a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> call on either pathname fails.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.sameopenfile">
<code class="descclassname">os.path.</code><code class="descname">sameopenfile</code><span class="sig-paren">(</span><em>fp1</em>, <em>fp2</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.sameopenfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the file descriptors <em>fp1</em> and <em>fp2</em> refer to the same file.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.samestat">
<code class="descclassname">os.path.</code><code class="descname">samestat</code><span class="sig-paren">(</span><em>stat1</em>, <em>stat2</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.samestat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the stat tuples <em>stat1</em> and <em>stat2</em> refer to the same file.
These structures may have been returned by <a class="reference internal" href="os.html#os.fstat" title="os.fstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fstat()</span></code></a>,
<a class="reference internal" href="os.html#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lstat()</span></code></a>, or <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>.  This function implements the
underlying comparison used by <a class="reference internal" href="#os.path.samefile" title="os.path.samefile"><code class="xref py py-func docutils literal notranslate"><span class="pre">samefile()</span></code></a> and <a class="reference internal" href="#os.path.sameopenfile" title="os.path.sameopenfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sameopenfile()</span></code></a>.</p>
<p>Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.split">
<code class="descclassname">os.path.</code><code class="descname">split</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the pathname <em>path</em> into a pair, <code class="docutils literal notranslate"><span class="pre">(head,</span> <span class="pre">tail)</span></code> where <em>tail</em> is the
last pathname component and <em>head</em> is everything leading up to that.  The
<em>tail</em> part will never contain a slash; if <em>path</em> ends in a slash, <em>tail</em>
will be empty.  If there is no slash in <em>path</em>, <em>head</em> will be empty.  If
<em>path</em> is empty, both <em>head</em> and <em>tail</em> are empty.  Trailing slashes are
stripped from <em>head</em> unless it is the root (one or more slashes only).  In
all cases, <code class="docutils literal notranslate"><span class="pre">join(head,</span> <span class="pre">tail)</span></code> returns a path to the same location as <em>path</em>
(but the strings may differ).  Also see the functions <a class="reference internal" href="#os.path.dirname" title="os.path.dirname"><code class="xref py py-func docutils literal notranslate"><span class="pre">dirname()</span></code></a> and
<a class="reference internal" href="#os.path.basename" title="os.path.basename"><code class="xref py py-func docutils literal notranslate"><span class="pre">basename()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.splitdrive">
<code class="descclassname">os.path.</code><code class="descname">splitdrive</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.splitdrive" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the pathname <em>path</em> into a pair <code class="docutils literal notranslate"><span class="pre">(drive,</span> <span class="pre">tail)</span></code> where <em>drive</em> is either
a drive specification or the empty string.  On systems which do not use drive
specifications, <em>drive</em> will always be the empty string.  In all cases, <code class="docutils literal notranslate"><span class="pre">drive</span>
<span class="pre">+</span> <span class="pre">tail</span></code> will be the same as <em>path</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.splitext">
<code class="descclassname">os.path.</code><code class="descname">splitext</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.splitext" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the pathname <em>path</em> into a pair <code class="docutils literal notranslate"><span class="pre">(root,</span> <span class="pre">ext)</span></code>  such that <code class="docutils literal notranslate"><span class="pre">root</span> <span class="pre">+</span> <span class="pre">ext</span> <span class="pre">==</span>
<span class="pre">path</span></code>, and <em>ext</em> is empty or begins with a period and contains at most one
period. Leading periods on the basename are  ignored; <code class="docutils literal notranslate"><span class="pre">splitext('.cshrc')</span></code>
returns  <code class="docutils literal notranslate"><span class="pre">('.cshrc',</span> <span class="pre">'')</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Earlier versions could produce an empty root when the only period was the
first character.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="os.path.splitunc">
<code class="descclassname">os.path.</code><code class="descname">splitunc</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.splitunc" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the pathname <em>path</em> into a pair <code class="docutils literal notranslate"><span class="pre">(unc,</span> <span class="pre">rest)</span></code> so that <em>unc</em> is the UNC
mount point (such as <code class="docutils literal notranslate"><span class="pre">r'\\host\mount'</span></code>), if present, and <em>rest</em> the rest of
the path (such as  <code class="docutils literal notranslate"><span class="pre">r'\path\file.ext'</span></code>).  For paths containing drive letters,
<em>unc</em> will always be the empty string.</p>
<p>Availability:  Windows.</p>
</dd></dl>

<dl class="function">
<dt id="os.path.walk">
<code class="descclassname">os.path.</code><code class="descname">walk</code><span class="sig-paren">(</span><em>path</em>, <em>visit</em>, <em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#os.path.walk" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls the function <em>visit</em> with arguments <code class="docutils literal notranslate"><span class="pre">(arg,</span> <span class="pre">dirname,</span> <span class="pre">names)</span></code> for each
directory in the directory tree rooted at <em>path</em> (including <em>path</em> itself, if it
is a directory).  The argument <em>dirname</em> specifies the visited directory, the
argument <em>names</em> lists the files in the directory (gotten from
<code class="docutils literal notranslate"><span class="pre">os.listdir(dirname)</span></code>). The <em>visit</em> function may modify <em>names</em> to influence
the set of directories visited below <em>dirname</em>, e.g. to avoid visiting certain
parts of the tree.  (The object referred to by <em>names</em> must be modified in
place, using <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> or slice assignment.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Symbolic links to directories are not treated as subdirectories, and that
<a class="reference internal" href="#os.path.walk" title="os.path.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> therefore will not visit them. To visit linked directories you must
identify them with <code class="docutils literal notranslate"><span class="pre">os.path.islink(file)</span></code> and <code class="docutils literal notranslate"><span class="pre">os.path.isdir(file)</span></code>, and
invoke <a class="reference internal" href="#os.path.walk" title="os.path.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">walk()</span></code></a> as necessary.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is deprecated and has been removed in Python 3 in favor of
<a class="reference internal" href="os.html#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.walk()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="os.path.supports_unicode_filenames">
<code class="descclassname">os.path.</code><code class="descname">supports_unicode_filenames</code><a class="headerlink" href="#os.path.supports_unicode_filenames" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">True</span></code> if arbitrary Unicode strings can be used as file names (within limitations
imposed by the file system).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="filesys.html"
                        title="previous chapter">10. File and Directory Access</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fileinput.html"
                        title="next chapter">10.2. <code class="docutils literal notranslate"><span class="pre">fileinput</span></code> — Iterate over lines from multiple input streams</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/os.path.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fileinput.html" title="10.2. fileinput — Iterate over lines from multiple input streams"
             >next</a> |</li>
        <li class="right" >
          <a href="filesys.html" title="10. File and Directory Access"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6���html/library/ossaudiodev.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.10. ossaudiodev — Access to OSS-compatible audio devices &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="22. Internationalization" href="i18n.html" />
    <link rel="prev" title="21.9. sndhdr — Determine type of sound file" href="sndhdr.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ossaudiodev.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="i18n.html" title="22. Internationalization"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sndhdr.html" title="21.9. sndhdr — Determine type of sound file"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ossaudiodev">
<span id="ossaudiodev-access-to-oss-compatible-audio-devices"></span><h1>21.10. <a class="reference internal" href="#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> — Access to OSS-compatible audio devices<a class="headerlink" href="#module-ossaudiodev" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module allows you to access the OSS (Open Sound System) audio interface.
OSS is available for a wide range of open-source and commercial Unices, and is
the standard audio interface for Linux and recent versions of FreeBSD.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference external" href="http://www.opensound.com/pguide/oss.pdf">Open Sound System Programmer’s Guide</a></dt>
<dd>the official documentation for the OSS C API</dd>
</dl>
<p class="last">The module defines a large number of constants supplied by the OSS device
driver; see <code class="docutils literal notranslate"><span class="pre">&lt;sys/soundcard.h&gt;</span></code> on either Linux or FreeBSD for a listing.</p>
</div>
<p><a class="reference internal" href="#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> defines the following variables and functions:</p>
<dl class="exception">
<dt id="ossaudiodev.OSSAudioError">
<em class="property">exception </em><code class="descclassname">ossaudiodev.</code><code class="descname">OSSAudioError</code><a class="headerlink" href="#ossaudiodev.OSSAudioError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised on certain errors.  The argument is a string describing
what went wrong.</p>
<p>(If <a class="reference internal" href="#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> receives an error from a system call such as
<code class="xref c c-func docutils literal notranslate"><span class="pre">open()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">write()</span></code>, or <code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code>, it raises <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.
Errors detected directly by <a class="reference internal" href="#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> result in <a class="reference internal" href="#ossaudiodev.OSSAudioError" title="ossaudiodev.OSSAudioError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSSAudioError</span></code></a>.)</p>
<p>(For backwards compatibility, the exception class is also available as
<code class="docutils literal notranslate"><span class="pre">ossaudiodev.error</span></code>.)</p>
</dd></dl>

<dl class="function">
<dt id="ossaudiodev.open">
<code class="descclassname">ossaudiodev.</code><code class="descname">open</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.open" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">ossaudiodev.</code><code class="descname">open</code><span class="sig-paren">(</span><em>device</em>, <em>mode</em><span class="sig-paren">)</span></dt>
<dd><p>Open an audio device and return an OSS audio device object.  This object
supports many file-like methods, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> (although there are subtle differences between conventional Unix
read/write semantics and those of OSS audio devices).  It also supports a number
of audio-specific methods; see below for the complete list of methods.</p>
<p><em>device</em> is the audio device filename to use.  If it is not specified, this
module first looks in the environment variable <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">AUDIODEV</span></code> for a device
to use.  If not found, it falls back to <code class="file docutils literal notranslate"><span class="pre">/dev/dsp</span></code>.</p>
<p><em>mode</em> is one of <code class="docutils literal notranslate"><span class="pre">'r'</span></code> for read-only (record) access, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> for
write-only (playback) access and <code class="docutils literal notranslate"><span class="pre">'rw'</span></code> for both. Since many sound cards
only allow one process to have the recorder or player open at a time, it is a
good idea to open the device only for the activity needed.  Further, some
sound cards are half-duplex: they can be opened for reading or writing, but
not both at once.</p>
<p>Note the unusual calling syntax: the <em>first</em> argument is optional, and the
second is required.  This is a historical artifact for compatibility with the
older <code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code> module which <a class="reference internal" href="#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> supersedes.</p>
</dd></dl>

<dl class="function">
<dt id="ossaudiodev.openmixer">
<code class="descclassname">ossaudiodev.</code><code class="descname">openmixer</code><span class="sig-paren">(</span><span class="optional">[</span><em>device</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.openmixer" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a mixer device and return an OSS mixer device object.   <em>device</em> is the
mixer device filename to use.  If it is not specified, this module first looks
in the environment variable <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">MIXERDEV</span></code> for a device to use.  If not
found, it falls back to <code class="file docutils literal notranslate"><span class="pre">/dev/mixer</span></code>.</p>
</dd></dl>

<div class="section" id="audio-device-objects">
<span id="ossaudio-device-objects"></span><h2>21.10.1. Audio Device Objects<a class="headerlink" href="#audio-device-objects" title="Permalink to this headline">¶</a></h2>
<p>Before you can write to or read from an audio device, you must call three
methods in the correct order:</p>
<ol class="arabic simple">
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">setfmt()</span></code> to set the output format</li>
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">channels()</span></code> to set the number of channels</li>
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code> to set the sample rate</li>
</ol>
<p>Alternately, you can use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">setparameters()</span></code> method to set all three audio
parameters at once.  This is more convenient, but may not be as flexible in all
cases.</p>
<p>The audio device objects returned by <a class="reference internal" href="#ossaudiodev.open" title="ossaudiodev.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> define the following methods
and (read-only) attributes:</p>
<dl class="method">
<dt id="ossaudiodev.oss_audio_device.close">
<code class="descclassname">oss_audio_device.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Explicitly close the audio device.  When you are done writing to or reading from
an audio device, you should explicitly close it.  A closed device cannot be used
again.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.fileno">
<code class="descclassname">oss_audio_device.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor associated with the device.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.read">
<code class="descclassname">oss_audio_device.</code><code class="descname">read</code><span class="sig-paren">(</span><em>size</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read <em>size</em> bytes from the audio input and return them as a Python string.
Unlike most Unix device drivers, OSS audio devices in blocking mode (the
default) will block <a class="reference internal" href="#ossaudiodev.oss_audio_device.read" title="ossaudiodev.oss_audio_device.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">read()</span></code></a> until the entire requested amount of data is
available.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.write">
<code class="descclassname">oss_audio_device.</code><code class="descname">write</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the Python string <em>data</em> to the audio device and return the number of
bytes written.  If the audio device is in blocking mode (the default), the
entire string is always written (again, this is different from usual Unix device
semantics).  If the device is in non-blocking mode, some data may not be written
—see <a class="reference internal" href="#ossaudiodev.oss_audio_device.writeall" title="ossaudiodev.oss_audio_device.writeall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writeall()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.writeall">
<code class="descclassname">oss_audio_device.</code><code class="descname">writeall</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.writeall" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the entire Python string <em>data</em> to the audio device: waits until the audio
device is able to accept data, writes as much data as it will accept, and
repeats until <em>data</em> has been completely written. If the device is in blocking
mode (the default), this has the same effect as <a class="reference internal" href="#ossaudiodev.oss_audio_device.write" title="ossaudiodev.oss_audio_device.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a>; <a class="reference internal" href="#ossaudiodev.oss_audio_device.writeall" title="ossaudiodev.oss_audio_device.writeall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writeall()</span></code></a>
is only useful in non-blocking mode.  Has no return value, since the amount of
data written is always equal to the amount of data supplied.</p>
</dd></dl>

<p>The following methods each map to exactly one <code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> system call.  The
correspondence is obvious: for example, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setfmt()</span></code> corresponds to the
<code class="docutils literal notranslate"><span class="pre">SNDCTL_DSP_SETFMT</span></code> ioctl, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">sync()</span></code> to <code class="docutils literal notranslate"><span class="pre">SNDCTL_DSP_SYNC</span></code> (this can
be useful when consulting the OSS documentation).  If the underlying
<code class="xref c c-func docutils literal notranslate"><span class="pre">ioctl()</span></code> fails, they all raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
<dl class="method">
<dt id="ossaudiodev.oss_audio_device.nonblock">
<code class="descclassname">oss_audio_device.</code><code class="descname">nonblock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.nonblock" title="Permalink to this definition">¶</a></dt>
<dd><p>Put the device into non-blocking mode.  Once in non-blocking mode, there is no
way to return it to blocking mode.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.getfmts">
<code class="descclassname">oss_audio_device.</code><code class="descname">getfmts</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.getfmts" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a bitmask of the audio output formats supported by the soundcard.  Some
of the formats supported by OSS are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="36%" />
<col width="64%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_MU_LAW</span></code></td>
<td>a logarithmic encoding (used by Sun <code class="docutils literal notranslate"><span class="pre">.au</span></code>
files and <code class="file docutils literal notranslate"><span class="pre">/dev/audio</span></code>)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_A_LAW</span></code></td>
<td>a logarithmic encoding</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_IMA_ADPCM</span></code></td>
<td>a 4:1 compressed format defined by the
Interactive Multimedia Association</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_U8</span></code></td>
<td>Unsigned, 8-bit audio</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_S16_LE</span></code></td>
<td>Signed, 16-bit audio, little-endian byte
order (as used by Intel processors)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_S16_BE</span></code></td>
<td>Signed, 16-bit audio, big-endian byte order
(as used by 68k, PowerPC, Sparc)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_S8</span></code></td>
<td>Signed, 8 bit audio</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_U16_LE</span></code></td>
<td>Unsigned, 16-bit little-endian audio</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_U16_BE</span></code></td>
<td>Unsigned, 16-bit big-endian audio</td>
</tr>
</tbody>
</table>
<p>Consult the OSS documentation for a full list of audio formats, and note that
most devices support only a subset of these formats.  Some older devices only
support <code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_U8</span></code>; the most common format used today is
<code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_S16_LE</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.setfmt">
<code class="descclassname">oss_audio_device.</code><code class="descname">setfmt</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.setfmt" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to set the current audio format to <em>format</em>—see <a class="reference internal" href="#ossaudiodev.oss_audio_device.getfmts" title="ossaudiodev.oss_audio_device.getfmts"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getfmts()</span></code></a> for a
list.  Returns the audio format that the device was set to, which may not be the
requested format.  May also be used to return the current audio format—do this
by passing an “audio format” of <code class="xref py py-const docutils literal notranslate"><span class="pre">AFMT_QUERY</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.channels">
<code class="descclassname">oss_audio_device.</code><code class="descname">channels</code><span class="sig-paren">(</span><em>nchannels</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.channels" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the number of output channels to <em>nchannels</em>.  A value of 1 indicates
monophonic sound, 2 stereophonic.  Some devices may have more than 2 channels,
and some high-end devices may not support mono. Returns the number of channels
the device was set to.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.speed">
<code class="descclassname">oss_audio_device.</code><code class="descname">speed</code><span class="sig-paren">(</span><em>samplerate</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.speed" title="Permalink to this definition">¶</a></dt>
<dd><p>Try to set the audio sampling rate to <em>samplerate</em> samples per second.  Returns
the rate actually set.  Most sound devices don’t support arbitrary sampling
rates.  Common rates are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Rate</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>8000</td>
<td>default rate for <code class="file docutils literal notranslate"><span class="pre">/dev/audio</span></code></td>
</tr>
<tr class="row-odd"><td>11025</td>
<td>speech recording</td>
</tr>
<tr class="row-even"><td>22050</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td>44100</td>
<td>CD quality audio (at 16 bits/sample and 2
channels)</td>
</tr>
<tr class="row-even"><td>96000</td>
<td>DVD quality audio (at 24 bits/sample)</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.sync">
<code class="descclassname">oss_audio_device.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until the sound device has played every byte in its buffer.  (This happens
implicitly when the device is closed.)  The OSS documentation recommends closing
and re-opening the device rather than using <a class="reference internal" href="#ossaudiodev.oss_audio_device.sync" title="ossaudiodev.oss_audio_device.sync"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sync()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.reset">
<code class="descclassname">oss_audio_device.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Immediately stop playing or recording and return the device to a state where it
can accept commands.  The OSS documentation recommends closing and re-opening
the device after calling <a class="reference internal" href="#ossaudiodev.oss_audio_device.reset" title="ossaudiodev.oss_audio_device.reset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reset()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.post">
<code class="descclassname">oss_audio_device.</code><code class="descname">post</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.post" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the driver that there is likely to be a pause in the output, making it
possible for the device to handle the pause more intelligently.  You might use
this after playing a spot sound effect, before waiting for user input, or before
doing disk I/O.</p>
</dd></dl>

<p>The following convenience methods combine several ioctls, or one ioctl and some
simple calculations.</p>
<dl class="method">
<dt id="ossaudiodev.oss_audio_device.setparameters">
<code class="descclassname">oss_audio_device.</code><code class="descname">setparameters</code><span class="sig-paren">(</span><em>format</em>, <em>nchannels</em>, <em>samplerate</em><span class="optional">[</span>, <em>strict=False</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.setparameters" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the key audio sampling parameters—sample format, number of channels, and
sampling rate—in one method call.  <em>format</em>,  <em>nchannels</em>, and <em>samplerate</em>
should be as specified in the <a class="reference internal" href="#ossaudiodev.oss_audio_device.setfmt" title="ossaudiodev.oss_audio_device.setfmt"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setfmt()</span></code></a>, <a class="reference internal" href="#ossaudiodev.oss_audio_device.channels" title="ossaudiodev.oss_audio_device.channels"><code class="xref py py-meth docutils literal notranslate"><span class="pre">channels()</span></code></a>, and
<a class="reference internal" href="#ossaudiodev.oss_audio_device.speed" title="ossaudiodev.oss_audio_device.speed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code></a>  methods.  If <em>strict</em> is true, <a class="reference internal" href="#ossaudiodev.oss_audio_device.setparameters" title="ossaudiodev.oss_audio_device.setparameters"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setparameters()</span></code></a> checks to
see if each parameter was actually set to the requested value, and raises
<a class="reference internal" href="#ossaudiodev.OSSAudioError" title="ossaudiodev.OSSAudioError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSSAudioError</span></code></a> if not.  Returns a tuple (<em>format</em>, <em>nchannels</em>,
<em>samplerate</em>) indicating the parameter values that were actually set by the
device driver (i.e., the same as the return values of <a class="reference internal" href="#ossaudiodev.oss_audio_device.setfmt" title="ossaudiodev.oss_audio_device.setfmt"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setfmt()</span></code></a>,
<a class="reference internal" href="#ossaudiodev.oss_audio_device.channels" title="ossaudiodev.oss_audio_device.channels"><code class="xref py py-meth docutils literal notranslate"><span class="pre">channels()</span></code></a>, and <a class="reference internal" href="#ossaudiodev.oss_audio_device.speed" title="ossaudiodev.oss_audio_device.speed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code></a>).</p>
<p>For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="n">channels</span><span class="p">,</span> <span class="n">rate</span><span class="p">)</span> <span class="o">=</span> <span class="n">dsp</span><span class="o">.</span><span class="n">setparameters</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="n">channels</span><span class="p">,</span> <span class="n">rate</span><span class="p">)</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fmt</span> <span class="o">=</span> <span class="n">dsp</span><span class="o">.</span><span class="n">setfmt</span><span class="p">(</span><span class="n">fmt</span><span class="p">)</span>
<span class="n">channels</span> <span class="o">=</span> <span class="n">dsp</span><span class="o">.</span><span class="n">channels</span><span class="p">(</span><span class="n">channels</span><span class="p">)</span>
<span class="n">rate</span> <span class="o">=</span> <span class="n">dsp</span><span class="o">.</span><span class="n">rate</span><span class="p">(</span><span class="n">rate</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.bufsize">
<code class="descclassname">oss_audio_device.</code><code class="descname">bufsize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.bufsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the size of the hardware buffer, in samples.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.obufcount">
<code class="descclassname">oss_audio_device.</code><code class="descname">obufcount</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.obufcount" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of samples that are in the hardware buffer yet to be played.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_audio_device.obuffree">
<code class="descclassname">oss_audio_device.</code><code class="descname">obuffree</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_audio_device.obuffree" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of samples that could be queued into the hardware buffer to
be played without blocking.</p>
</dd></dl>

<p>Audio device objects also support several read-only attributes:</p>
<dl class="attribute">
<dt id="ossaudiodev.oss_audio_device.closed">
<code class="descclassname">oss_audio_device.</code><code class="descname">closed</code><a class="headerlink" href="#ossaudiodev.oss_audio_device.closed" title="Permalink to this definition">¶</a></dt>
<dd><p>Boolean indicating whether the device has been closed.</p>
</dd></dl>

<dl class="attribute">
<dt id="ossaudiodev.oss_audio_device.name">
<code class="descclassname">oss_audio_device.</code><code class="descname">name</code><a class="headerlink" href="#ossaudiodev.oss_audio_device.name" title="Permalink to this definition">¶</a></dt>
<dd><p>String containing the name of the device file.</p>
</dd></dl>

<dl class="attribute">
<dt id="ossaudiodev.oss_audio_device.mode">
<code class="descclassname">oss_audio_device.</code><code class="descname">mode</code><a class="headerlink" href="#ossaudiodev.oss_audio_device.mode" title="Permalink to this definition">¶</a></dt>
<dd><p>The I/O mode for the file, either <code class="docutils literal notranslate"><span class="pre">&quot;r&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;rw&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;w&quot;</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="mixer-device-objects">
<span id="id1"></span><h2>21.10.2. Mixer Device Objects<a class="headerlink" href="#mixer-device-objects" title="Permalink to this headline">¶</a></h2>
<p>The mixer object provides two file-like methods:</p>
<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.close">
<code class="descclassname">oss_mixer_device.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.close" title="Permalink to this definition">¶</a></dt>
<dd><p>This method closes the open mixer device file.  Any further attempts to use the
mixer after this file is closed will raise an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.fileno">
<code class="descclassname">oss_mixer_device.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the file handle number of the open mixer device file.</p>
</dd></dl>

<p>The remaining methods are specific to audio mixing:</p>
<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.controls">
<code class="descclassname">oss_mixer_device.</code><code class="descname">controls</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.controls" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a bitmask specifying the available mixer controls (“Control”
being a specific mixable “channel”, such as <code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_PCM</span></code> or
<code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_SYNTH</span></code>).  This bitmask indicates a subset of all available
mixer controls—the <code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_*</span></code> constants defined at module level.
To determine if, for example, the current mixer object supports a PCM mixer, use
the following Python code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mixer</span><span class="o">=</span><span class="n">ossaudiodev</span><span class="o">.</span><span class="n">openmixer</span><span class="p">()</span>
<span class="k">if</span> <span class="n">mixer</span><span class="o">.</span><span class="n">controls</span><span class="p">()</span> <span class="o">&amp;</span> <span class="p">(</span><span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="n">ossaudiodev</span><span class="o">.</span><span class="n">SOUND_MIXER_PCM</span><span class="p">):</span>
    <span class="c1"># PCM is supported</span>
    <span class="o">...</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>For most purposes, the <code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_VOLUME</span></code> (master volume) and
<code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_PCM</span></code> controls should suffice—but code that uses the mixer
should be flexible when it comes to choosing mixer controls.  On the Gravis
Ultrasound, for example, <code class="xref py py-const docutils literal notranslate"><span class="pre">SOUND_MIXER_VOLUME</span></code> does not exist.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.stereocontrols">
<code class="descclassname">oss_mixer_device.</code><code class="descname">stereocontrols</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.stereocontrols" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a bitmask indicating stereo mixer controls.  If a bit is set, the
corresponding control is stereo; if it is unset, the control is either
monophonic or not supported by the mixer (use in combination with
<a class="reference internal" href="#ossaudiodev.oss_mixer_device.controls" title="ossaudiodev.oss_mixer_device.controls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">controls()</span></code></a> to determine which).</p>
<p>See the code example for the <a class="reference internal" href="#ossaudiodev.oss_mixer_device.controls" title="ossaudiodev.oss_mixer_device.controls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">controls()</span></code></a> function for an example of getting
data from a bitmask.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.reccontrols">
<code class="descclassname">oss_mixer_device.</code><code class="descname">reccontrols</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.reccontrols" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a bitmask specifying the mixer controls that may be used to record.  See
the code example for <a class="reference internal" href="#ossaudiodev.oss_mixer_device.controls" title="ossaudiodev.oss_mixer_device.controls"><code class="xref py py-meth docutils literal notranslate"><span class="pre">controls()</span></code></a> for an example of reading from a bitmask.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.get">
<code class="descclassname">oss_mixer_device.</code><code class="descname">get</code><span class="sig-paren">(</span><em>control</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the volume of a given mixer control.  The returned volume is a 2-tuple
<code class="docutils literal notranslate"><span class="pre">(left_volume,right_volume)</span></code>.  Volumes are specified as numbers from 0
(silent) to 100 (full volume).  If the control is monophonic, a 2-tuple is still
returned, but both volumes are the same.</p>
<p>Raises <a class="reference internal" href="#ossaudiodev.OSSAudioError" title="ossaudiodev.OSSAudioError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSSAudioError</span></code></a> if an invalid control was is specified, or
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if an unsupported control is specified.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.set">
<code class="descclassname">oss_mixer_device.</code><code class="descname">set</code><span class="sig-paren">(</span><em>control</em>, <em>(left</em>, <em>right)</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the volume for a given mixer control to <code class="docutils literal notranslate"><span class="pre">(left,right)</span></code>. <code class="docutils literal notranslate"><span class="pre">left</span></code> and
<code class="docutils literal notranslate"><span class="pre">right</span></code> must be ints and between 0 (silent) and 100 (full volume).  On
success, the new volume is returned as a 2-tuple. Note that this may not be
exactly the same as the volume specified, because of the limited resolution of
some soundcard’s mixers.</p>
<p>Raises <a class="reference internal" href="#ossaudiodev.OSSAudioError" title="ossaudiodev.OSSAudioError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSSAudioError</span></code></a> if an invalid mixer control was specified, or if the
specified volumes were out-of-range.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.get_recsrc">
<code class="descclassname">oss_mixer_device.</code><code class="descname">get_recsrc</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.get_recsrc" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a bitmask indicating which control(s) are currently being
used as a recording source.</p>
</dd></dl>

<dl class="method">
<dt id="ossaudiodev.oss_mixer_device.set_recsrc">
<code class="descclassname">oss_mixer_device.</code><code class="descname">set_recsrc</code><span class="sig-paren">(</span><em>bitmask</em><span class="sig-paren">)</span><a class="headerlink" href="#ossaudiodev.oss_mixer_device.set_recsrc" title="Permalink to this definition">¶</a></dt>
<dd><p>Call this function to specify a recording source.  Returns a bitmask indicating
the new recording source (or sources) if successful; raises <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if an
invalid source was specified.  To set the current recording source to the
microphone input:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mixer</span><span class="o">.</span><span class="n">setrecsrc</span> <span class="p">(</span><span class="mi">1</span> <span class="o">&lt;&lt;</span> <span class="n">ossaudiodev</span><span class="o">.</span><span class="n">SOUND_MIXER_MIC</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a><ul>
<li><a class="reference internal" href="#audio-device-objects">21.10.1. Audio Device Objects</a></li>
<li><a class="reference internal" href="#mixer-device-objects">21.10.2. Mixer Device Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sndhdr.html"
                        title="previous chapter">21.9. <code class="docutils literal notranslate"><span class="pre">sndhdr</span></code> — Determine type of sound file</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="i18n.html"
                        title="next chapter">22. Internationalization</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ossaudiodev.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="i18n.html" title="22. Internationalization"
             >next</a> |</li>
        <li class="right" >
          <a href="sndhdr.html" title="21.9. sndhdr — Determine type of sound file"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�ҭ�$�$html/library/othergui.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.7. Other Graphical User Interface Packages &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25. Development Tools" href="development.html" />
    <link rel="prev" title="24.6. IDLE" href="idle.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/othergui.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="development.html" title="25. Development Tools"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="idle.html" title="24.6. IDLE"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="other-graphical-user-interface-packages">
<span id="other-gui-packages"></span><h1>24.7. Other Graphical User Interface Packages<a class="headerlink" href="#other-graphical-user-interface-packages" title="Permalink to this headline">¶</a></h1>
<p>Major cross-platform (Windows, Mac OS X, Unix-like) GUI toolkits are
available for Python:</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.pygtk.org/">PyGTK</a></dt>
<dd>is a set of bindings for the <a class="reference external" href="http://www.gtk.org/">GTK</a> widget set. It
provides an object oriented interface that is slightly higher level than
the C one. It comes with many more widgets than Tkinter provides, and has
good Python-specific reference documentation. There are also bindings to
<a class="reference external" href="https://www.gnome.org/">GNOME</a>.  An online <a class="reference external" href="http://www.pygtk.org/pygtk2tutorial/index.html">tutorial</a> is available.</dd>
<dt><a class="reference external" href="https://riverbankcomputing.com/software/pyqt/intro">PyQt</a></dt>
<dd>PyQt is a <strong class="program">sip</strong>-wrapped binding to the Qt toolkit.  Qt is an
extensive C++ GUI application development framework that is
available for Unix, Windows and Mac OS X. <strong class="program">sip</strong> is a tool
for generating bindings for C++ libraries as Python classes, and
is specifically designed for Python. The <em>PyQt3</em> bindings have a
book, <a class="reference external" href="https://www.commandprompt.com/community/pyqt/">GUI Programming with Python: QT Edition</a> by Boudewijn
Rempt. The <em>PyQt4</em> bindings also have a book, <a class="reference external" href="https://www.qtrac.eu/pyqtbook.html">Rapid GUI Programming
with Python and Qt</a>, by Mark
Summerfield.</dd>
<dt><a class="reference external" href="http://www.wxpython.org">wxPython</a></dt>
<dd>wxPython is a cross-platform GUI toolkit for Python that is built around
the popular <a class="reference external" href="https://www.wxwidgets.org/">wxWidgets</a> (formerly wxWindows)
C++ toolkit.  It provides a native look and feel for applications on
Windows, Mac OS X, and Unix systems by using each platform’s native
widgets where ever possible, (GTK+ on Unix-like systems).  In addition to
an extensive set of widgets, wxPython provides classes for online
documentation and context sensitive help, printing, HTML viewing,
low-level device context drawing, drag and drop, system clipboard access,
an XML-based resource format and more, including an ever growing library
of user-contributed modules.  wxPython has a book, <a class="reference external" href="https://www.manning.com/books/wxpython-in-action">wxPython in Action</a>, by Noel Rappin and
Robin Dunn.</dd>
</dl>
</div>
<p>PyGTK, PyQt, and wxPython, all have a modern look and feel and more
widgets than Tkinter. In addition, there are many other GUI toolkits for
Python, both cross-platform, and platform-specific. See the <a class="reference external" href="https://wiki.python.org/moin/GuiProgramming">GUI Programming</a> page in the Python Wiki for a
much more complete list, and also for links to documents where the
different GUI toolkits are compared.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="idle.html"
                        title="previous chapter">24.6. IDLE</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="development.html"
                        title="next chapter">25. Development Tools</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/othergui.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="development.html" title="25. Development Tools"
             >next</a> |</li>
        <li class="right" >
          <a href="idle.html" title="24.6. IDLE"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���>�>�html/library/parser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.1. parser — Access Python parse trees &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.2. ast — Abstract Syntax Trees" href="ast.html" />
    <link rel="prev" title="32. Python Language Services" href="language.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/parser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ast.html" title="32.2. ast — Abstract Syntax Trees"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="language.html" title="32. Python Language Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-parser">
<span id="parser-access-python-parse-trees"></span><h1>32.1. <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> — Access Python parse trees<a class="headerlink" href="#module-parser" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module provides an interface to Python’s internal parser and
byte-code compiler.  The primary purpose for this interface is to allow Python
code to edit the parse tree of a Python expression and create executable code
from this.  This is better than trying to parse and modify an arbitrary Python
code fragment as a string because parsing is performed in a manner identical to
the code forming the application.  It is also faster.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>From Python 2.5 onward, it’s much more convenient to cut in at the Abstract
Syntax Tree (AST) generation and compilation stage, using the <a class="reference internal" href="ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a>
module.</p>
<p class="last">The <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module exports the names documented here also with “st”
replaced by “ast”; this is a legacy from the time when there was no other
AST and has nothing to do with the AST found in Python 2.5.  This is also the
reason for the functions’ keyword arguments being called <em>ast</em>, not <em>st</em>.
The “ast” functions have been removed in Python 3.</p>
</div>
<p>There are a few things to note about this module which are important to making
use of the data structures created.  This is not a tutorial on editing the parse
trees for Python code, but some examples of using the <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module are
presented.</p>
<p>Most importantly, a good understanding of the Python grammar processed by the
internal parser is required.  For full information on the language syntax, refer
to <a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a>.  The parser
itself is created from a grammar specification defined in the file
<code class="file docutils literal notranslate"><span class="pre">Grammar/Grammar</span></code> in the standard Python distribution.  The parse trees
stored in the ST objects created by this module are the actual output from the
internal parser when created by the <a class="reference internal" href="#parser.expr" title="parser.expr"><code class="xref py py-func docutils literal notranslate"><span class="pre">expr()</span></code></a> or <a class="reference internal" href="#parser.suite" title="parser.suite"><code class="xref py py-func docutils literal notranslate"><span class="pre">suite()</span></code></a> functions,
described below.  The ST objects created by <a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a> faithfully
simulate those structures.  Be aware that the values of the sequences which are
considered “correct” will vary from one version of Python to another as the
formal grammar for the language is revised.  However, transporting code from one
Python version to another as source text will always allow correct parse trees
to be created in the target version, with the only restriction being that
migrating to an older version of the interpreter will not support more recent
language constructs.  The parse trees are not typically compatible from one
version to another, whereas source code has always been forward-compatible.</p>
<p>Each element of the sequences returned by <a class="reference internal" href="#parser.st2list" title="parser.st2list"><code class="xref py py-func docutils literal notranslate"><span class="pre">st2list()</span></code></a> or <a class="reference internal" href="#parser.st2tuple" title="parser.st2tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">st2tuple()</span></code></a>
has a simple form.  Sequences representing non-terminal elements in the grammar
always have a length greater than one.  The first element is an integer which
identifies a production in the grammar.  These integers are given symbolic names
in the C header file <code class="file docutils literal notranslate"><span class="pre">Include/graminit.h</span></code> and the Python module
<a class="reference internal" href="symbol.html#module-symbol" title="symbol: Constants representing internal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symbol</span></code></a>.  Each additional element of the sequence represents a component
of the production as recognized in the input string: these are always sequences
which have the same form as the parent.  An important aspect of this structure
which should be noted is that keywords used to identify the parent node type,
such as the keyword <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> in an <code class="xref py py-const docutils literal notranslate"><span class="pre">if_stmt</span></code>, are included in the
node tree without any special treatment.  For example, the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> keyword
is represented by the tuple <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">'if')</span></code>, where <code class="docutils literal notranslate"><span class="pre">1</span></code> is the numeric value
associated with all <code class="xref py py-const docutils literal notranslate"><span class="pre">NAME</span></code> tokens, including variable and function names
defined by the user.  In an alternate form returned when line number information
is requested, the same token might be represented as <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">'if',</span> <span class="pre">12)</span></code>, where
the <code class="docutils literal notranslate"><span class="pre">12</span></code> represents the line number at which the terminal symbol was found.</p>
<p>Terminal elements are represented in much the same way, but without any child
elements and the addition of the source text which was identified.  The example
of the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> keyword above is representative.  The various types of
terminal symbols are defined in the C header file <code class="file docutils literal notranslate"><span class="pre">Include/token.h</span></code> and
the Python module <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">token</span></code></a>.</p>
<p>The ST objects are not required to support the functionality of this module,
but are provided for three purposes: to allow an application to amortize the
cost of processing complex parse trees, to provide a parse tree representation
which conserves memory space when compared to the Python list or tuple
representation, and to ease the creation of additional modules in C which
manipulate parse trees.  A simple “wrapper” class may be created in Python to
hide the use of ST objects.</p>
<p>The <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module defines functions for a few distinct purposes.  The
most important purposes are to create ST objects and to convert ST objects to
other representations such as parse trees and compiled code objects, but there
are also functions which serve to query the type of parse tree represented by an
ST object.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="symbol.html#module-symbol" title="symbol: Constants representing internal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symbol</span></code></a></dt>
<dd>Useful constants representing internal nodes of the parse tree.</dd>
<dt>Module <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">token</span></code></a></dt>
<dd>Useful constants representing leaf nodes of the parse tree and functions for
testing node values.</dd>
</dl>
</div>
<div class="section" id="creating-st-objects">
<span id="creating-sts"></span><h2>32.1.1. Creating ST Objects<a class="headerlink" href="#creating-st-objects" title="Permalink to this headline">¶</a></h2>
<p>ST objects may be created from source code or from a parse tree. When creating
an ST object from source, different functions are used to create the <code class="docutils literal notranslate"><span class="pre">'eval'</span></code>
and <code class="docutils literal notranslate"><span class="pre">'exec'</span></code> forms.</p>
<dl class="function">
<dt id="parser.expr">
<code class="descclassname">parser.</code><code class="descname">expr</code><span class="sig-paren">(</span><em>source</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.expr" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#parser.expr" title="parser.expr"><code class="xref py py-func docutils literal notranslate"><span class="pre">expr()</span></code></a> function parses the parameter <em>source</em> as if it were an input
to <code class="docutils literal notranslate"><span class="pre">compile(source,</span> <span class="pre">'file.py',</span> <span class="pre">'eval')</span></code>.  If the parse succeeds, an ST object
is created to hold the internal parse tree representation, otherwise an
appropriate exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="parser.suite">
<code class="descclassname">parser.</code><code class="descname">suite</code><span class="sig-paren">(</span><em>source</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.suite" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#parser.suite" title="parser.suite"><code class="xref py py-func docutils literal notranslate"><span class="pre">suite()</span></code></a> function parses the parameter <em>source</em> as if it were an input
to <code class="docutils literal notranslate"><span class="pre">compile(source,</span> <span class="pre">'file.py',</span> <span class="pre">'exec')</span></code>.  If the parse succeeds, an ST object
is created to hold the internal parse tree representation, otherwise an
appropriate exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="parser.sequence2st">
<code class="descclassname">parser.</code><code class="descname">sequence2st</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.sequence2st" title="Permalink to this definition">¶</a></dt>
<dd><p>This function accepts a parse tree represented as a sequence and builds an
internal representation if possible.  If it can validate that the tree conforms
to the Python grammar and all nodes are valid node types in the host version of
Python, an ST object is created from the internal representation and returned
to the called.  If there is a problem creating the internal representation, or
if the tree cannot be validated, a <a class="reference internal" href="#parser.ParserError" title="parser.ParserError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ParserError</span></code></a> exception is raised.  An
ST object created this way should not be assumed to compile correctly; normal
exceptions raised by compilation may still be initiated when the ST object is
passed to <a class="reference internal" href="#parser.compilest" title="parser.compilest"><code class="xref py py-func docutils literal notranslate"><span class="pre">compilest()</span></code></a>.  This may indicate problems not related to syntax
(such as a <a class="reference internal" href="exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> exception), but may also be due to constructs such
as the result of parsing <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">f(0)</span></code>, which escapes the Python parser but is
checked by the bytecode compiler.</p>
<p>Sequences representing terminal tokens may be represented as either two-element
lists of the form <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">'name')</span></code> or as three-element lists of the form <code class="docutils literal notranslate"><span class="pre">(1,</span>
<span class="pre">'name',</span> <span class="pre">56)</span></code>.  If the third element is present, it is assumed to be a valid
line number.  The line number may be specified for any subset of the terminal
symbols in the input tree.</p>
</dd></dl>

<dl class="function">
<dt id="parser.tuple2st">
<code class="descclassname">parser.</code><code class="descname">tuple2st</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.tuple2st" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the same function as <a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a>.  This entry point is
maintained for backward compatibility.</p>
</dd></dl>

</div>
<div class="section" id="converting-st-objects">
<span id="converting-sts"></span><h2>32.1.2. Converting ST Objects<a class="headerlink" href="#converting-st-objects" title="Permalink to this headline">¶</a></h2>
<p>ST objects, regardless of the input used to create them, may be converted to
parse trees represented as list- or tuple- trees, or may be compiled into
executable code objects.  Parse trees may be extracted with or without line
numbering information.</p>
<dl class="function">
<dt id="parser.st2list">
<code class="descclassname">parser.</code><code class="descname">st2list</code><span class="sig-paren">(</span><em>ast</em><span class="optional">[</span>, <em>line_info</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.st2list" title="Permalink to this definition">¶</a></dt>
<dd><p>This function accepts an ST object from the caller in <em>ast</em> and returns a
Python list representing the equivalent parse tree.  The resulting list
representation can be used for inspection or the creation of a new parse tree in
list form.  This function does not fail so long as memory is available to build
the list representation.  If the parse tree will only be used for inspection,
<a class="reference internal" href="#parser.st2tuple" title="parser.st2tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">st2tuple()</span></code></a> should be used instead to reduce memory consumption and
fragmentation.  When the list representation is required, this function is
significantly faster than retrieving a tuple representation and converting that
to nested lists.</p>
<p>If <em>line_info</em> is true, line number information will be included for all
terminal tokens as a third element of the list representing the token.  Note
that the line number provided specifies the line on which the token <em>ends</em>.
This information is omitted if the flag is false or omitted.</p>
</dd></dl>

<dl class="function">
<dt id="parser.st2tuple">
<code class="descclassname">parser.</code><code class="descname">st2tuple</code><span class="sig-paren">(</span><em>ast</em><span class="optional">[</span>, <em>line_info</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.st2tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>This function accepts an ST object from the caller in <em>ast</em> and returns a
Python tuple representing the equivalent parse tree.  Other than returning a
tuple instead of a list, this function is identical to <a class="reference internal" href="#parser.st2list" title="parser.st2list"><code class="xref py py-func docutils literal notranslate"><span class="pre">st2list()</span></code></a>.</p>
<p>If <em>line_info</em> is true, line number information will be included for all
terminal tokens as a third element of the list representing the token.  This
information is omitted if the flag is false or omitted.</p>
</dd></dl>

<dl class="function">
<dt id="parser.compilest">
<code class="descclassname">parser.</code><code class="descname">compilest</code><span class="sig-paren">(</span><em>ast</em>, <em>filename='&lt;syntax-tree&gt;'</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.compilest" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">The Python byte compiler can be invoked on an ST object to produce code objects
which can be used as part of an <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement or a call to the
built-in <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> function. This function provides the interface to the
compiler, passing the internal parse tree from <em>ast</em> to the parser, using the
source file name specified by the <em>filename</em> parameter. The default value
supplied for <em>filename</em> indicates that the source was an ST object.</p>
<p>Compiling an ST object may result in exceptions related to compilation; an
example would be a <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> caused by the parse tree for <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">f(0)</span></code>:
this statement is considered legal within the formal grammar for Python but is
not a legal language construct.  The <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> raised for this
condition is actually generated by the Python byte-compiler normally, which is
why it can be raised at this point by the <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module.  Most causes of
compilation failure can be diagnosed programmatically by inspection of the parse
tree.</p>
</dd></dl>

</div>
<div class="section" id="queries-on-st-objects">
<span id="querying-sts"></span><h2>32.1.3. Queries on ST Objects<a class="headerlink" href="#queries-on-st-objects" title="Permalink to this headline">¶</a></h2>
<p>Two functions are provided which allow an application to determine if an ST was
created as an expression or a suite.  Neither of these functions can be used to
determine if an ST was created from source code via <a class="reference internal" href="#parser.expr" title="parser.expr"><code class="xref py py-func docutils literal notranslate"><span class="pre">expr()</span></code></a> or
<a class="reference internal" href="#parser.suite" title="parser.suite"><code class="xref py py-func docutils literal notranslate"><span class="pre">suite()</span></code></a> or from a parse tree via <a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a>.</p>
<dl class="function">
<dt id="parser.isexpr">
<code class="descclassname">parser.</code><code class="descname">isexpr</code><span class="sig-paren">(</span><em>ast</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.isexpr" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">When <em>ast</em> represents an <code class="docutils literal notranslate"><span class="pre">'eval'</span></code> form, this function returns true, otherwise
it returns false.  This is useful, since code objects normally cannot be queried
for this information using existing built-in functions.  Note that the code
objects created by <a class="reference internal" href="#parser.compilest" title="parser.compilest"><code class="xref py py-func docutils literal notranslate"><span class="pre">compilest()</span></code></a> cannot be queried like this either, and
are identical to those created by the built-in <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="parser.issuite">
<code class="descclassname">parser.</code><code class="descname">issuite</code><span class="sig-paren">(</span><em>ast</em><span class="sig-paren">)</span><a class="headerlink" href="#parser.issuite" title="Permalink to this definition">¶</a></dt>
<dd><p>This function mirrors <a class="reference internal" href="#parser.isexpr" title="parser.isexpr"><code class="xref py py-func docutils literal notranslate"><span class="pre">isexpr()</span></code></a> in that it reports whether an ST object
represents an <code class="docutils literal notranslate"><span class="pre">'exec'</span></code> form, commonly known as a “suite.”  It is not safe to
assume that this function is equivalent to <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">isexpr(ast)</span></code>, as additional
syntactic fragments may be supported in the future.</p>
</dd></dl>

</div>
<div class="section" id="exceptions-and-error-handling">
<span id="st-errors"></span><h2>32.1.4. Exceptions and Error Handling<a class="headerlink" href="#exceptions-and-error-handling" title="Permalink to this headline">¶</a></h2>
<p>The parser module defines a single exception, but may also pass other built-in
exceptions from other portions of the Python runtime environment.  See each
function for information about the exceptions it can raise.</p>
<dl class="exception">
<dt id="parser.ParserError">
<em class="property">exception </em><code class="descclassname">parser.</code><code class="descname">ParserError</code><a class="headerlink" href="#parser.ParserError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a failure occurs within the parser module.  This is
generally produced for validation failures rather than the built-in
<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> raised during normal parsing. The exception argument is
either a string describing the reason of the failure or a tuple containing a
sequence causing the failure from a parse tree passed to <a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a>
and an explanatory string.  Calls to <a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a> need to be able to
handle either type of exception, while calls to other functions in the module
will only need to be aware of the simple string values.</p>
</dd></dl>

<p>Note that the functions <a class="reference internal" href="#parser.compilest" title="parser.compilest"><code class="xref py py-func docutils literal notranslate"><span class="pre">compilest()</span></code></a>, <a class="reference internal" href="#parser.expr" title="parser.expr"><code class="xref py py-func docutils literal notranslate"><span class="pre">expr()</span></code></a>, and <a class="reference internal" href="#parser.suite" title="parser.suite"><code class="xref py py-func docutils literal notranslate"><span class="pre">suite()</span></code></a> may
raise exceptions which are normally raised by the parsing and compilation
process.  These include the built in exceptions <a class="reference internal" href="exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a>,
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>, and <a class="reference internal" href="exceptions.html#exceptions.SystemError" title="exceptions.SystemError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemError</span></code></a>.  In these
cases, these exceptions carry all the meaning normally associated with them.
Refer to the descriptions of each function for detailed information.</p>
</div>
<div class="section" id="st-objects">
<span id="id1"></span><h2>32.1.5. ST Objects<a class="headerlink" href="#st-objects" title="Permalink to this headline">¶</a></h2>
<p>Ordered and equality comparisons are supported between ST objects. Pickling of
ST objects (using the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module) is also supported.</p>
<dl class="data">
<dt id="parser.STType">
<code class="descclassname">parser.</code><code class="descname">STType</code><a class="headerlink" href="#parser.STType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of the objects returned by <a class="reference internal" href="#parser.expr" title="parser.expr"><code class="xref py py-func docutils literal notranslate"><span class="pre">expr()</span></code></a>, <a class="reference internal" href="#parser.suite" title="parser.suite"><code class="xref py py-func docutils literal notranslate"><span class="pre">suite()</span></code></a> and
<a class="reference internal" href="#parser.sequence2st" title="parser.sequence2st"><code class="xref py py-func docutils literal notranslate"><span class="pre">sequence2st()</span></code></a>.</p>
</dd></dl>

<p>ST objects have the following methods:</p>
<dl class="method">
<dt id="parser.ST.compile">
<code class="descclassname">ST.</code><code class="descname">compile</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.ST.compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <code class="docutils literal notranslate"><span class="pre">compilest(st,</span> <span class="pre">filename)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="parser.ST.isexpr">
<code class="descclassname">ST.</code><code class="descname">isexpr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.ST.isexpr" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <code class="docutils literal notranslate"><span class="pre">isexpr(st)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="parser.ST.issuite">
<code class="descclassname">ST.</code><code class="descname">issuite</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.ST.issuite" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <code class="docutils literal notranslate"><span class="pre">issuite(st)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="parser.ST.tolist">
<code class="descclassname">ST.</code><code class="descname">tolist</code><span class="sig-paren">(</span><span class="optional">[</span><em>line_info</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.ST.tolist" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <code class="docutils literal notranslate"><span class="pre">st2list(st,</span> <span class="pre">line_info)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="parser.ST.totuple">
<code class="descclassname">ST.</code><code class="descname">totuple</code><span class="sig-paren">(</span><span class="optional">[</span><em>line_info</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#parser.ST.totuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <code class="docutils literal notranslate"><span class="pre">st2tuple(st,</span> <span class="pre">line_info)</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="example-emulation-of-compile">
<h2>32.1.6. Example: Emulation of <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a><a class="headerlink" href="#example-emulation-of-compile" title="Permalink to this headline">¶</a></h2>
<p>While many useful operations may take place between parsing and bytecode
generation, the simplest operation is to do nothing.  For this purpose, using
the <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module to produce an intermediate data structure is equivalent
to the code</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">code</span> <span class="o">=</span> <span class="nb">compile</span><span class="p">(</span><span class="s1">&#39;a + 5&#39;</span><span class="p">,</span> <span class="s1">&#39;file.py&#39;</span><span class="p">,</span> <span class="s1">&#39;eval&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">eval</span><span class="p">(</span><span class="n">code</span><span class="p">)</span>
<span class="go">10</span>
</pre></div>
</div>
<p>The equivalent operation using the <a class="reference internal" href="#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module is somewhat longer, and
allows the intermediate internal parse tree to be retained as an ST object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">parser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">st</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">expr</span><span class="p">(</span><span class="s1">&#39;a + 5&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">code</span> <span class="o">=</span> <span class="n">st</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s1">&#39;file.py&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">eval</span><span class="p">(</span><span class="n">code</span><span class="p">)</span>
<span class="go">10</span>
</pre></div>
</div>
<p>An application which needs both ST and code objects can package this code into
readily available functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">parser</span>

<span class="k">def</span> <span class="nf">load_suite</span><span class="p">(</span><span class="n">source_string</span><span class="p">):</span>
    <span class="n">st</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">suite</span><span class="p">(</span><span class="n">source_string</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">st</span><span class="p">,</span> <span class="n">st</span><span class="o">.</span><span class="n">compile</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">load_expression</span><span class="p">(</span><span class="n">source_string</span><span class="p">):</span>
    <span class="n">st</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">expr</span><span class="p">(</span><span class="n">source_string</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">st</span><span class="p">,</span> <span class="n">st</span><span class="o">.</span><span class="n">compile</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a><ul>
<li><a class="reference internal" href="#creating-st-objects">32.1.1. Creating ST Objects</a></li>
<li><a class="reference internal" href="#converting-st-objects">32.1.2. Converting ST Objects</a></li>
<li><a class="reference internal" href="#queries-on-st-objects">32.1.3. Queries on ST Objects</a></li>
<li><a class="reference internal" href="#exceptions-and-error-handling">32.1.4. Exceptions and Error Handling</a></li>
<li><a class="reference internal" href="#st-objects">32.1.5. ST Objects</a></li>
<li><a class="reference internal" href="#example-emulation-of-compile">32.1.6. Example: Emulation of <code class="docutils literal notranslate"><span class="pre">compile()</span></code></a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="language.html"
                        title="previous chapter">32. Python Language Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ast.html"
                        title="next chapter">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/parser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ast.html" title="32.2. ast — Abstract Syntax Trees"
             >next</a> |</li>
        <li class="right" >
          <a href="language.html" title="32. Python Language Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���3˖˖html/library/pdb.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.2. pdb — The Python Debugger &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.4. The Python Profilers" href="profile.html" />
    <link rel="prev" title="26.1. bdb — Debugger framework" href="bdb.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pdb.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="profile.html" title="26.4. The Python Profilers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bdb.html" title="26.1. bdb — Debugger framework"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pdb">
<span id="pdb-the-python-debugger"></span><span id="debugger"></span><h1>26.2. <a class="reference internal" href="#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> — The Python Debugger<a class="headerlink" href="#module-pdb" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pdb.py">Lib/pdb.py</a></p>
<hr class="docutils" />
<p id="index-0">The module <a class="reference internal" href="#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> defines an interactive source code debugger for Python
programs.  It supports setting (conditional) breakpoints and single stepping at
the source line level, inspection of stack frames, source code listing, and
evaluation of arbitrary Python code in the context of any stack frame.  It also
supports post-mortem debugging and can be called under program control.</p>
<p id="index-1">The debugger is extensible — it is actually defined as the class <a class="reference internal" href="#pdb.Pdb" title="pdb.Pdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pdb</span></code></a>.
This is currently undocumented but easily understood by reading the source.  The
extension interface uses the modules <a class="reference internal" href="bdb.html#module-bdb" title="bdb: Debugger framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdb</span></code></a> and <a class="reference internal" href="cmd.html#module-cmd" title="cmd: Build line-oriented command interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmd</span></code></a>.</p>
<p>The debugger’s prompt is <code class="docutils literal notranslate"><span class="pre">(Pdb)</span></code>. Typical usage to run a program under control
of the debugger is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pdb</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mymodule</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pdb</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;mymodule.test()&#39;</span><span class="p">)</span>
<span class="go">&gt; &lt;string&gt;(0)?()</span>
<span class="go">(Pdb) continue</span>
<span class="go">&gt; &lt;string&gt;(1)?()</span>
<span class="go">(Pdb) continue</span>
<span class="go">NameError: &#39;spam&#39;</span>
<span class="go">&gt; &lt;string&gt;(1)?()</span>
<span class="go">(Pdb)</span>
</pre></div>
</div>
<p><code class="file docutils literal notranslate"><span class="pre">pdb.py</span></code> can also be invoked as a script to debug other scripts.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">pdb</span> <span class="n">myscript</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>When invoked as a script, pdb will automatically enter post-mortem debugging if
the program being debugged exits abnormally. After post-mortem debugging (or
after normal exit of the program), pdb will restart the program. Automatic
restarting preserves pdb’s state (such as breakpoints) and in most cases is more
useful than quitting the debugger upon program’s exit.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>Restarting post-mortem behavior added.</p>
</div>
<p>The typical usage to break into the debugger from a running program is to
insert</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pdb</span><span class="p">;</span> <span class="n">pdb</span><span class="o">.</span><span class="n">set_trace</span><span class="p">()</span>
</pre></div>
</div>
<p>at the location you want to break into the debugger.  You can then step through
the code following this statement, and continue running without the debugger using
the <code class="docutils literal notranslate"><span class="pre">c</span></code> command.</p>
<p>The typical usage to inspect a crashed program is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pdb</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mymodule</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mymodule</span><span class="o">.</span><span class="n">test</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;./mymodule.py&quot;</span>, line <span class="m">4</span>, in <span class="n">test</span>
    <span class="n">test2</span><span class="p">()</span>
  File <span class="nb">&quot;./mymodule.py&quot;</span>, line <span class="m">3</span>, in <span class="n">test2</span>
    <span class="nb">print</span> <span class="n">spam</span>
<span class="gr">NameError</span>: <span class="n">spam</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pdb</span><span class="o">.</span><span class="n">pm</span><span class="p">()</span>
<span class="go">&gt; ./mymodule.py(3)test2()</span>
<span class="go">-&gt; print spam</span>
<span class="go">(Pdb)</span>
</pre></div>
</div>
<p>The module defines the following functions; each enters the debugger in a
slightly different way:</p>
<dl class="function">
<dt id="pdb.run">
<code class="descclassname">pdb.</code><code class="descname">run</code><span class="sig-paren">(</span><em>statement</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the <em>statement</em> (given as a string) under debugger control.  The
debugger prompt appears before any code is executed; you can set breakpoints and
type <code class="docutils literal notranslate"><span class="pre">continue</span></code>, or you can step through the statement using <code class="docutils literal notranslate"><span class="pre">step</span></code> or
<code class="docutils literal notranslate"><span class="pre">next</span></code> (all these commands are explained below).  The optional <em>globals</em> and
<em>locals</em> arguments specify the environment in which the code is executed; by
default the dictionary of the module <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> is used.  (See the
explanation of the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement or the <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> built-in
function.)</p>
</dd></dl>

<dl class="function">
<dt id="pdb.runeval">
<code class="descclassname">pdb.</code><code class="descname">runeval</code><span class="sig-paren">(</span><em>expression</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.runeval" title="Permalink to this definition">¶</a></dt>
<dd><p>Evaluate the <em>expression</em> (given as a string) under debugger control.  When
<a class="reference internal" href="#pdb.runeval" title="pdb.runeval"><code class="xref py py-func docutils literal notranslate"><span class="pre">runeval()</span></code></a> returns, it returns the value of the expression.  Otherwise this
function is similar to <a class="reference internal" href="#pdb.run" title="pdb.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="pdb.runcall">
<code class="descclassname">pdb.</code><code class="descname">runcall</code><span class="sig-paren">(</span><em>function</em><span class="optional">[</span>, <em>argument</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.runcall" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the <em>function</em> (a function or method object, not a string) with the given
arguments.  When <a class="reference internal" href="#pdb.runcall" title="pdb.runcall"><code class="xref py py-func docutils literal notranslate"><span class="pre">runcall()</span></code></a> returns, it returns whatever the function call
returned.  The debugger prompt appears as soon as the function is entered.</p>
</dd></dl>

<dl class="function">
<dt id="pdb.set_trace">
<code class="descclassname">pdb.</code><code class="descname">set_trace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.set_trace" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the debugger at the calling stack frame.  This is useful to hard-code a
breakpoint at a given point in a program, even if the code is not otherwise
being debugged (e.g. when an assertion fails).</p>
</dd></dl>

<dl class="function">
<dt id="pdb.post_mortem">
<code class="descclassname">pdb.</code><code class="descname">post_mortem</code><span class="sig-paren">(</span><span class="optional">[</span><em>traceback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.post_mortem" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter post-mortem debugging of the given <em>traceback</em> object.  If no
<em>traceback</em> is given, it uses the one of the exception that is currently
being handled (an exception must be being handled if the default is to be
used).</p>
</dd></dl>

<dl class="function">
<dt id="pdb.pm">
<code class="descclassname">pdb.</code><code class="descname">pm</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.pm" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter post-mortem debugging of the traceback found in
<a class="reference internal" href="sys.html#sys.last_traceback" title="sys.last_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_traceback</span></code></a>.</p>
</dd></dl>

<p>The <code class="docutils literal notranslate"><span class="pre">run*</span></code> functions and <a class="reference internal" href="#pdb.set_trace" title="pdb.set_trace"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_trace()</span></code></a> are aliases for instantiating the
<a class="reference internal" href="#pdb.Pdb" title="pdb.Pdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pdb</span></code></a> class and calling the method of the same name.  If you want to
access further features, you have to do this yourself:</p>
<dl class="class">
<dt id="pdb.Pdb">
<em class="property">class </em><code class="descclassname">pdb.</code><code class="descname">Pdb</code><span class="sig-paren">(</span><em>completekey='tab'</em>, <em>stdin=None</em>, <em>stdout=None</em>, <em>skip=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pdb.Pdb" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#pdb.Pdb" title="pdb.Pdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pdb</span></code></a> is the debugger class.</p>
<p>The <em>completekey</em>, <em>stdin</em> and <em>stdout</em> arguments are passed to the
underlying <a class="reference internal" href="cmd.html#cmd.Cmd" title="cmd.Cmd"><code class="xref py py-class docutils literal notranslate"><span class="pre">cmd.Cmd</span></code></a> class; see the description there.</p>
<p>The <em>skip</em> argument, if given, must be an iterable of glob-style module name
patterns.  The debugger will not step into frames that originate in a module
that matches one of these patterns. <a class="footnote-reference" href="#id3" id="id1">[1]</a></p>
<p>Example call to enable tracing with <em>skip</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pdb</span><span class="p">;</span> <span class="n">pdb</span><span class="o">.</span><span class="n">Pdb</span><span class="p">(</span><span class="n">skip</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;django.*&#39;</span><span class="p">])</span><span class="o">.</span><span class="n">set_trace</span><span class="p">()</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The <em>skip</em> argument.</p>
</div>
<dl class="method">
<dt id="pdb.Pdb.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>statement</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.Pdb.run" title="Permalink to this definition">¶</a></dt>
<dt id="pdb.Pdb.runeval">
<code class="descname">runeval</code><span class="sig-paren">(</span><em>expression</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.Pdb.runeval" title="Permalink to this definition">¶</a></dt>
<dt id="pdb.Pdb.runcall">
<code class="descname">runcall</code><span class="sig-paren">(</span><em>function</em><span class="optional">[</span>, <em>argument</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.Pdb.runcall" title="Permalink to this definition">¶</a></dt>
<dt id="pdb.Pdb.set_trace">
<code class="descname">set_trace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pdb.Pdb.set_trace" title="Permalink to this definition">¶</a></dt>
<dd><p>See the documentation for the functions explained above.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="debugger-commands">
<span id="id2"></span><h1>26.3. Debugger Commands<a class="headerlink" href="#debugger-commands" title="Permalink to this headline">¶</a></h1>
<p>The debugger recognizes the following commands.  Most commands can be
abbreviated to one or two letters; e.g. <code class="docutils literal notranslate"><span class="pre">h(elp)</span></code> means that either <code class="docutils literal notranslate"><span class="pre">h</span></code> or
<code class="docutils literal notranslate"><span class="pre">help</span></code> can be used to enter the help command (but not <code class="docutils literal notranslate"><span class="pre">he</span></code> or <code class="docutils literal notranslate"><span class="pre">hel</span></code>, nor
<code class="docutils literal notranslate"><span class="pre">H</span></code> or <code class="docutils literal notranslate"><span class="pre">Help</span></code> or <code class="docutils literal notranslate"><span class="pre">HELP</span></code>).  Arguments to commands must be separated by
whitespace (spaces or tabs).  Optional arguments are enclosed in square brackets
(<code class="docutils literal notranslate"><span class="pre">[]</span></code>) in the command syntax; the square brackets must not be typed.
Alternatives in the command syntax are separated by a vertical bar (<code class="docutils literal notranslate"><span class="pre">|</span></code>).</p>
<p>Entering a blank line repeats the last command entered.  Exception: if the last
command was a <code class="docutils literal notranslate"><span class="pre">list</span></code> command, the next 11 lines are listed.</p>
<p>Commands that the debugger doesn’t recognize are assumed to be Python statements
and are executed in the context of the program being debugged.  Python
statements can also be prefixed with an exclamation point (<code class="docutils literal notranslate"><span class="pre">!</span></code>).  This is a
powerful way to inspect the program being debugged; it is even possible to
change a variable or call a function.  When an exception occurs in such a
statement, the exception name is printed but the debugger’s state is not
changed.</p>
<p>Multiple commands may be entered on a single line, separated by <code class="docutils literal notranslate"><span class="pre">;;</span></code>.  (A
single <code class="docutils literal notranslate"><span class="pre">;</span></code> is not used as it is the separator for multiple commands in a line
that is passed to the Python parser.) No intelligence is applied to separating
the commands; the input is split at the first <code class="docutils literal notranslate"><span class="pre">;;</span></code> pair, even if it is in the
middle of a quoted string.</p>
<p>The debugger supports aliases.  Aliases can have parameters which allows one a
certain level of adaptability to the context under examination.</p>
<p id="index-2">If a file <code class="file docutils literal notranslate"><span class="pre">.pdbrc</span></code>  exists in the user’s home directory or in the current
directory, it is read in and executed as if it had been typed at the debugger
prompt. This is particularly useful for aliases.  If both files exist, the one
in the home directory is read first and aliases defined there can be overridden
by the local file.</p>
<dl class="docutils">
<dt>h(elp) [<em>command</em>]</dt>
<dd>Without argument, print the list of available commands.  With a <em>command</em> as
argument, print help about that command.  <code class="docutils literal notranslate"><span class="pre">help</span> <span class="pre">pdb</span></code> displays the full
documentation file; if the environment variable <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PAGER</span></code> is defined, the
file is piped through that command instead.  Since the <em>command</em> argument must
be an identifier, <code class="docutils literal notranslate"><span class="pre">help</span> <span class="pre">exec</span></code> must be entered to get help on the <code class="docutils literal notranslate"><span class="pre">!</span></code>
command.</dd>
<dt>w(here)</dt>
<dd>Print a stack trace, with the most recent frame at the bottom.  An arrow
indicates the current frame, which determines the context of most commands.</dd>
<dt>d(own)</dt>
<dd>Move the current frame one level down in the stack trace (to a newer frame).</dd>
<dt>u(p)</dt>
<dd>Move the current frame one level up in the stack trace (to an older frame).</dd>
<dt>b(reak) [[<em>filename</em>:]<em>lineno</em> | <em>function</em>[, <em>condition</em>]]</dt>
<dd><p class="first">With a <em>lineno</em> argument, set a break there in the current file.  With a
<em>function</em> argument, set a break at the first executable statement within that
function. The line number may be prefixed with a filename and a colon, to
specify a breakpoint in another file (probably one that hasn’t been loaded yet).
The file is searched on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>. Note that each breakpoint is assigned a
number to which all the other breakpoint commands refer.</p>
<p>If a second argument is present, it is an expression which must evaluate to true
before the breakpoint is honored.</p>
<p class="last">Without argument, list all breaks, including for each breakpoint, the number of
times that breakpoint has been hit, the current ignore count, and the associated
condition if any.</p>
</dd>
<dt>tbreak [[<em>filename</em>:]<em>lineno</em> | <em>function</em>[, <em>condition</em>]]</dt>
<dd>Temporary breakpoint, which is removed automatically when it is first hit.  The
arguments are the same as break.</dd>
<dt>cl(ear) [<em>filename:lineno</em> | <em>bpnumber</em> [<em>bpnumber …</em>]]</dt>
<dd>With a <em>filename:lineno</em> argument, clear all the breakpoints at this line.
With a space separated list of breakpoint numbers, clear those breakpoints.
Without argument, clear all breaks (but first ask confirmation).</dd>
<dt>disable [<em>bpnumber</em> [<em>bpnumber …</em>]]</dt>
<dd>Disables the breakpoints given as a space separated list of breakpoint numbers.
Disabling a breakpoint means it cannot cause the program to stop execution, but
unlike clearing a breakpoint, it remains in the list of breakpoints and can be
(re-)enabled.</dd>
<dt>enable [<em>bpnumber</em> [<em>bpnumber …</em>]]</dt>
<dd>Enables the breakpoints specified.</dd>
<dt>ignore <em>bpnumber</em> [<em>count</em>]</dt>
<dd>Sets the ignore count for the given breakpoint number.  If count is omitted, the
ignore count is set to 0.  A breakpoint becomes active when the ignore count is
zero.  When non-zero, the count is decremented each time the breakpoint is
reached and the breakpoint is not disabled and any associated condition
evaluates to true.</dd>
<dt>condition <em>bpnumber</em> [<em>condition</em>]</dt>
<dd>Condition is an expression which must evaluate to true before the breakpoint is
honored.  If condition is absent, any existing condition is removed; i.e., the
breakpoint is made unconditional.</dd>
<dt>commands [<em>bpnumber</em>]</dt>
<dd><p class="first">Specify a list of commands for breakpoint number <em>bpnumber</em>.  The commands
themselves appear on the following lines.  Type a line containing just ‘end’ to
terminate the commands. An example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">Pdb</span><span class="p">)</span> <span class="n">commands</span> <span class="mi">1</span>
<span class="p">(</span><span class="n">com</span><span class="p">)</span> <span class="nb">print</span> <span class="n">some_variable</span>
<span class="p">(</span><span class="n">com</span><span class="p">)</span> <span class="n">end</span>
<span class="p">(</span><span class="n">Pdb</span><span class="p">)</span>
</pre></div>
</div>
<p>To remove all commands from a breakpoint, type commands and follow it
immediately with  end; that is, give no commands.</p>
<p>With no <em>bpnumber</em> argument, commands refers to the last breakpoint set.</p>
<p>You can use breakpoint commands to start your program up again. Simply use the
continue command, or step, or any other command that resumes execution.</p>
<p>Specifying any command resuming execution (currently continue, step, next,
return, jump, quit and their abbreviations) terminates the command list (as if
that command was immediately followed by end). This is because any time you
resume execution (even with a simple next or step), you may encounter another
breakpoint—which could have its own command list, leading to ambiguities about
which list to execute.</p>
<p>If you use the ‘silent’ command in the command list, the usual message about
stopping at a breakpoint is not printed.  This may be desirable for breakpoints
that are to print a specific message and then continue.  If none of the other
commands print anything, you see no sign that the breakpoint was reached.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd>
<dt>s(tep)</dt>
<dd>Execute the current line, stop at the first possible occasion (either in a
function that is called or on the next line in the current function).</dd>
<dt>n(ext)</dt>
<dd>Continue execution until the next line in the current function is reached or it
returns.  (The difference between <code class="docutils literal notranslate"><span class="pre">next</span></code> and <code class="docutils literal notranslate"><span class="pre">step</span></code> is that <code class="docutils literal notranslate"><span class="pre">step</span></code> stops
inside a called function, while <code class="docutils literal notranslate"><span class="pre">next</span></code> executes called functions at (nearly)
full speed, only stopping at the next line in the current function.)</dd>
<dt>unt(il)</dt>
<dd><p class="first">Continue execution until the line with the line number greater than the
current one is reached or when returning from current frame.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd>
<dt>r(eturn)</dt>
<dd>Continue execution until the current function returns.</dd>
<dt>c(ont(inue))</dt>
<dd>Continue execution, only stop when a breakpoint is encountered.</dd>
<dt>j(ump) <em>lineno</em></dt>
<dd><p class="first">Set the next line that will be executed.  Only available in the bottom-most
frame.  This lets you jump back and execute code again, or jump forward to skip
code that you don’t want to run.</p>
<p class="last">It should be noted that not all jumps are allowed — for instance it is not
possible to jump into the middle of a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop or out of a
<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p>
</dd>
<dt>l(ist) [<em>first</em>[, <em>last</em>]]</dt>
<dd>List source code for the current file.  Without arguments, list 11 lines around
the current line or continue the previous listing.  With one argument, list 11
lines around at that line.  With two arguments, list the given range; if the
second argument is less than the first, it is interpreted as a count.</dd>
<dt>a(rgs)</dt>
<dd>Print the argument list of the current function.</dd>
<dt>p <em>expression</em></dt>
<dd><p class="first">Evaluate the <em>expression</em> in the current context and print its value.</p>
<div class="last admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">print</span></code> can also be used, but is not a debugger command — this executes the
Python <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.</p>
</div>
</dd>
<dt>pp <em>expression</em></dt>
<dd>Like the <code class="docutils literal notranslate"><span class="pre">p</span></code> command, except the value of the expression is pretty-printed
using the <a class="reference internal" href="pprint.html#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module.</dd>
<dt>alias [<em>name</em> [command]]</dt>
<dd><p class="first">Creates an alias called <em>name</em> that executes <em>command</em>.  The command must <em>not</em>
be enclosed in quotes.  Replaceable parameters can be indicated by <code class="docutils literal notranslate"><span class="pre">%1</span></code>,
<code class="docutils literal notranslate"><span class="pre">%2</span></code>, and so on, while <code class="docutils literal notranslate"><span class="pre">%*</span></code> is replaced by all the parameters.  If no
command is given, the current alias for <em>name</em> is shown. If no arguments are
given, all aliases are listed.</p>
<p>Aliases may be nested and can contain anything that can be legally typed at the
pdb prompt.  Note that internal pdb commands <em>can</em> be overridden by aliases.
Such a command is then hidden until the alias is removed.  Aliasing is
recursively applied to the first word of the command line; all other words in
the line are left alone.</p>
<p>As an example, here are two useful aliases (especially when placed in the
<code class="file docutils literal notranslate"><span class="pre">.pdbrc</span></code> file):</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1">#Print instance variables (usage &quot;pi classInst&quot;)</span>
<span class="n">alias</span> <span class="n">pi</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="o">%</span><span class="mf">1.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">keys</span><span class="p">():</span> <span class="nb">print</span> <span class="s2">&quot;%1.&quot;</span><span class="p">,</span><span class="n">k</span><span class="p">,</span><span class="s2">&quot;=&quot;</span><span class="p">,</span><span class="o">%</span><span class="mf">1.</span><span class="vm">__dict__</span><span class="p">[</span><span class="n">k</span><span class="p">]</span>
<span class="c1">#Print instance variables in self</span>
<span class="n">alias</span> <span class="n">ps</span> <span class="n">pi</span> <span class="bp">self</span>
</pre></div>
</div>
</dd>
<dt>unalias <em>name</em></dt>
<dd>Deletes the specified alias.</dd>
<dt>[!]<em>statement</em></dt>
<dd><p class="first">Execute the (one-line) <em>statement</em> in the context of the current stack frame.
The exclamation point can be omitted unless the first word of the statement
resembles a debugger command. To set a global variable, you can prefix the
assignment command with a <code class="docutils literal notranslate"><span class="pre">global</span></code> command on the same line, e.g.:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">Pdb</span><span class="p">)</span> <span class="k">global</span> <span class="n">list_options</span><span class="p">;</span> <span class="n">list_options</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;-l&#39;</span><span class="p">]</span>
<span class="p">(</span><span class="n">Pdb</span><span class="p">)</span>
</pre></div>
</div>
</dd>
<dt>run [<em>args</em> …]</dt>
<dd><p class="first">Restart the debugged Python program. If an argument is supplied, it is split
with “shlex” and the result is used as the new sys.argv. History, breakpoints,
actions and debugger options are preserved. “restart” is an alias for “run”.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd>
<dt>q(uit)</dt>
<dd>Quit from the debugger. The program being executed is aborted.</dd>
</dl>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Whether a frame is considered to originate in a certain module
is determined by the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> in the frame globals.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></li>
<li><a class="reference internal" href="#debugger-commands">26.3. Debugger Commands</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="bdb.html"
                        title="previous chapter">26.1. <code class="docutils literal notranslate"><span class="pre">bdb</span></code> — Debugger framework</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="profile.html"
                        title="next chapter">26.4. The Python Profilers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pdb.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="profile.html" title="26.4. The Python Profilers"
             >next</a> |</li>
        <li class="right" >
          <a href="bdb.html" title="26.1. bdb — Debugger framework"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��o�<=<=html/library/persistence.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11. Data Persistence &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.1. pickle — Python object serialization" href="pickle.html" />
    <link rel="prev" title="10.12. macpath — Mac OS 9 path manipulation functions" href="macpath.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/persistence.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pickle.html" title="11.1. pickle — Python object serialization"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="macpath.html" title="10.12. macpath — Mac OS 9 path manipulation functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-persistence">
<span id="persistence"></span><h1>11. Data Persistence<a class="headerlink" href="#data-persistence" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter support storing Python data in a
persistent form on disk.  The <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> modules can turn
many Python data types into a stream of bytes and then recreate the objects from
the bytes.  The various DBM-related modules support a family of hash-based file
formats that store a mapping of strings to other strings.  The <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a>
module also provides such disk-based string-to-string mappings based on hashing,
and also supports B-Tree and record-based formats.</p>
<p>The list of modules described in this chapter is:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="pickle.html">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#relationship-to-other-python-modules">11.1.1. Relationship to other Python modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#data-stream-format">11.1.2. Data stream format</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#usage">11.1.3. Usage</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#what-can-be-pickled-and-unpickled">11.1.4. What can be pickled and unpickled?</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#the-pickle-protocol">11.1.5. The pickle protocol</a><ul>
<li class="toctree-l3"><a class="reference internal" href="pickle.html#pickling-and-unpickling-normal-class-instances">11.1.5.1. Pickling and unpickling normal class instances</a></li>
<li class="toctree-l3"><a class="reference internal" href="pickle.html#pickling-and-unpickling-extension-types">11.1.5.2. Pickling and unpickling extension types</a></li>
<li class="toctree-l3"><a class="reference internal" href="pickle.html#pickling-and-unpickling-external-objects">11.1.5.3. Pickling and unpickling external objects</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#subclassing-unpicklers">11.1.6. Subclassing Unpicklers</a></li>
<li class="toctree-l2"><a class="reference internal" href="pickle.html#example">11.1.7. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="pickle.html#module-cPickle">11.2. <code class="docutils literal notranslate"><span class="pre">cPickle</span></code> — A faster <code class="docutils literal notranslate"><span class="pre">pickle</span></code></a></li>
<li class="toctree-l1"><a class="reference internal" href="copy_reg.html">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="copy_reg.html#example">11.3.1. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="shelve.html">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a><ul>
<li class="toctree-l2"><a class="reference internal" href="shelve.html#restrictions">11.4.1. Restrictions</a></li>
<li class="toctree-l2"><a class="reference internal" href="shelve.html#example">11.4.2. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="marshal.html">11.5. <code class="docutils literal notranslate"><span class="pre">marshal</span></code> — Internal Python object serialization</a></li>
<li class="toctree-l1"><a class="reference internal" href="anydbm.html">11.6. <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> — Generic access to DBM-style databases</a></li>
<li class="toctree-l1"><a class="reference internal" href="whichdb.html">11.7. <code class="docutils literal notranslate"><span class="pre">whichdb</span></code> — Guess which DBM module created a database</a></li>
<li class="toctree-l1"><a class="reference internal" href="dbm.html">11.8. <code class="docutils literal notranslate"><span class="pre">dbm</span></code> — Simple “database” interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="gdbm.html">11.9. <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> — GNU’s reinterpretation of dbm</a></li>
<li class="toctree-l1"><a class="reference internal" href="dbhash.html">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a><ul>
<li class="toctree-l2"><a class="reference internal" href="dbhash.html#database-objects">11.10.1. Database Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="bsddb.html">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a><ul>
<li class="toctree-l2"><a class="reference internal" href="bsddb.html#hash-btree-and-record-objects">11.11.1. Hash, BTree and Record Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="dumbdbm.html">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a><ul>
<li class="toctree-l2"><a class="reference internal" href="dumbdbm.html#dumbdbm-objects">11.12.1. Dumbdbm Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sqlite3.html">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#module-functions-and-constants">11.13.1. Module functions and constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#connection-objects">11.13.2. Connection Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#cursor-objects">11.13.3. Cursor Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#row-objects">11.13.4. Row Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#sqlite-and-python-types">11.13.5. SQLite and Python types</a><ul>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#introduction">11.13.5.1. Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases">11.13.5.2. Using adapters to store additional Python types in SQLite databases</a><ul>
<li class="toctree-l4"><a class="reference internal" href="sqlite3.html#letting-your-object-adapt-itself">11.13.5.2.1. Letting your object adapt itself</a></li>
<li class="toctree-l4"><a class="reference internal" href="sqlite3.html#registering-an-adapter-callable">11.13.5.2.2. Registering an adapter callable</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#converting-sqlite-values-to-custom-python-types">11.13.5.3. Converting SQLite values to custom Python types</a></li>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#default-adapters-and-converters">11.13.5.4. Default adapters and converters</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#controlling-transactions">11.13.6. Controlling Transactions</a></li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#using-sqlite3-efficiently">11.13.7. Using <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> efficiently</a><ul>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#using-shortcut-methods">11.13.7.1. Using shortcut methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#accessing-columns-by-name-instead-of-by-index">11.13.7.2. Accessing columns by name instead of by index</a></li>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#using-the-connection-as-a-context-manager">11.13.7.3. Using the connection as a context manager</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="sqlite3.html#common-issues">11.13.8. Common issues</a><ul>
<li class="toctree-l3"><a class="reference internal" href="sqlite3.html#multithreading">11.13.8.1. Multithreading</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="macpath.html"
                        title="previous chapter">10.12. <code class="docutils literal notranslate"><span class="pre">macpath</span></code> — Mac OS 9 path manipulation functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pickle.html"
                        title="next chapter">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/persistence.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pickle.html" title="11.1. pickle — Python object serialization"
             >next</a> |</li>
        <li class="right" >
          <a href="macpath.html" title="10.12. macpath — Mac OS 9 path manipulation functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�$z0t�t�html/library/pickle.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.1. pickle — Python object serialization &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.3. copy_reg — Register pickle support functions" href="copy_reg.html" />
    <link rel="prev" title="11. Data Persistence" href="persistence.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pickle.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copy_reg.html" title="11.3. copy_reg — Register pickle support functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="persistence.html" title="11. Data Persistence"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="pickle-python-object-serialization">
<h1>11.1. <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> — Python object serialization<a class="headerlink" href="#pickle-python-object-serialization" title="Permalink to this headline">¶</a></h1>
<span class="target" id="module-pickle"><span id="index-0"></span></span><p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module implements a fundamental, but powerful algorithm for
serializing and de-serializing a Python object structure.  “Pickling” is the
process whereby a Python object hierarchy is converted into a byte stream, and
“unpickling” is the inverse operation, whereby a byte stream is converted back
into an object hierarchy.  Pickling (and unpickling) is alternatively known as
“serialization”, “marshalling,” <a class="footnote-reference" href="#id11" id="id1">[1]</a> or “flattening”, however, to avoid
confusion, the terms used here are “pickling” and “unpickling”.</p>
<p>This documentation describes both the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module and the
<a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module is not secure against erroneous or maliciously
constructed data.  Never unpickle data received from an untrusted or
unauthenticated source.</p>
</div>
<div class="section" id="relationship-to-other-python-modules">
<h2>11.1.1. Relationship to other Python modules<a class="headerlink" href="#relationship-to-other-python-modules" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module has an optimized cousin called the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>
module.  As its name implies, <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> is written in C, so it can be up to
1000 times faster than <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>.  However it does not support subclassing
of the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-func docutils literal notranslate"><span class="pre">Pickler()</span></code></a> and <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-func docutils literal notranslate"><span class="pre">Unpickler()</span></code></a> classes, because in <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>
these are functions, not classes.  Most applications have no need for this
functionality, and can benefit from the improved performance of <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>.
Other than that, the interfaces of the two modules are nearly identical; the
common interface is described in this manual and differences are pointed out
where necessary.  In the following discussions, we use the term “pickle” to
collectively describe the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> modules.</p>
<p>The data streams the two modules produce are guaranteed to be interchangeable.</p>
<p>Python has a more primitive serialization module called <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a>, but in
general <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> should always be the preferred way to serialize Python
objects.  <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> exists primarily to support Python’s <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code>
files.</p>
<p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module differs from <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> in several significant ways:</p>
<ul>
<li><p class="first">The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module keeps track of the objects it has already serialized,
so that later references to the same object won’t be serialized again.
<a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> doesn’t do this.</p>
<p>This has implications both for recursive objects and object sharing.  Recursive
objects are objects that contain references to themselves.  These are not
handled by marshal, and in fact, attempting to marshal recursive objects will
crash your Python interpreter.  Object sharing happens when there are multiple
references to the same object in different places in the object hierarchy being
serialized.  <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> stores such objects only once, and ensures that all
other references point to the master copy.  Shared objects remain shared, which
can be very important for mutable objects.</p>
</li>
<li><p class="first"><a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> cannot be used to serialize user-defined classes and their
instances.  <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> can save and restore class instances transparently,
however the class definition must be importable and live in the same module as
when the object was stored.</p>
</li>
<li><p class="first">The <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> serialization format is not guaranteed to be portable
across Python versions.  Because its primary job in life is to support
<code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files, the Python implementers reserve the right to change the
serialization format in non-backwards compatible ways should the need arise.
The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> serialization format is guaranteed to be backwards compatible
across Python releases.</p>
</li>
</ul>
<p>Note that serialization is a more primitive notion than persistence; although
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> reads and writes file objects, it does not handle the issue of
naming persistent objects, nor the (even more complicated) issue of concurrent
access to persistent objects.  The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module can transform a complex
object into a byte stream and it can transform the byte stream into an object
with the same internal structure.  Perhaps the most obvious thing to do with
these byte streams is to write them onto a file, but it is also conceivable to
send them across a network or store them in a database.  The module
<a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> provides a simple interface to pickle and unpickle objects on
DBM-style database files.</p>
</div>
<div class="section" id="data-stream-format">
<h2>11.1.2. Data stream format<a class="headerlink" href="#data-stream-format" title="Permalink to this headline">¶</a></h2>
<p id="index-1">The data format used by <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> is Python-specific.  This has the
advantage that there are no restrictions imposed by external standards such as
XDR (which can’t represent pointer sharing); however it means that non-Python
programs may not be able to reconstruct pickled Python objects.</p>
<p>By default, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> data format uses a printable ASCII representation.
This is slightly more voluminous than a binary representation.  The big
advantage of using printable ASCII (and of some other characteristics of
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>’s representation) is that for debugging or recovery purposes it is
possible for a human to read the pickled file with a standard text editor.</p>
<p>There are currently 3 different protocols which can be used for pickling.</p>
<ul class="simple">
<li>Protocol version 0 is the original ASCII protocol and is backwards compatible
with earlier versions of Python.</li>
<li>Protocol version 1 is the old binary format which is also compatible with
earlier versions of Python.</li>
<li>Protocol version 2 was introduced in Python 2.3.  It provides much more
efficient pickling of <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es.</li>
</ul>
<p>Refer to <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> for more information.</p>
<p>If a <em>protocol</em> is not specified, protocol 0 is used. If <em>protocol</em> is specified
as a negative value or <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>, the highest protocol version
available will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Introduced the <em>protocol</em> parameter.</p>
</div>
<p>A binary format, which is slightly more efficient, can be chosen by specifying a
<em>protocol</em> version &gt;= 1.</p>
</div>
<div class="section" id="usage">
<h2>11.1.3. Usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h2>
<p>To serialize an object hierarchy, you first create a pickler, then you call the
pickler’s <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dump()</span></code></a> method.  To de-serialize a data stream, you first create
an unpickler, then you call the unpickler’s <a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> method.  The
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module provides the following constant:</p>
<dl class="data">
<dt id="pickle.HIGHEST_PROTOCOL">
<code class="descclassname">pickle.</code><code class="descname">HIGHEST_PROTOCOL</code><a class="headerlink" href="#pickle.HIGHEST_PROTOCOL" title="Permalink to this definition">¶</a></dt>
<dd><p>The highest protocol version available.  This value can be passed as a
<em>protocol</em> value.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Be sure to always open pickle files created with protocols &gt;= 1 in binary mode.
For the old ASCII-based pickle protocol 0 you can use either text mode or binary
mode as long as you stay consistent.</p>
<p class="last">A pickle file written with protocol 0 in binary mode will contain lone linefeeds
as line terminators and therefore will look “funny” when viewed in Notepad or
other editors which do not support this format.</p>
</div>
<p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module provides the following functions to make the pickling
process more convenient:</p>
<dl class="function">
<dt id="pickle.dump">
<code class="descclassname">pickle.</code><code class="descname">dump</code><span class="sig-paren">(</span><em>obj</em>, <em>file</em><span class="optional">[</span>, <em>protocol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a pickled representation of <em>obj</em> to the open file object <em>file</em>.  This is
equivalent to <code class="docutils literal notranslate"><span class="pre">Pickler(file,</span> <span class="pre">protocol).dump(obj)</span></code>.</p>
<p>If the <em>protocol</em> parameter is omitted, protocol 0 is used. If <em>protocol</em> is
specified as a negative value or <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>, the highest protocol
version will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Introduced the <em>protocol</em> parameter.</p>
</div>
<p><em>file</em> must have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method that accepts a single string argument.
It can thus be a file object opened for writing, a <a class="reference internal" href="stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> object, or
any other custom object that meets this interface.</p>
</dd></dl>

<dl class="function">
<dt id="pickle.load">
<code class="descclassname">pickle.</code><code class="descname">load</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a string from the open file object <em>file</em> and interpret it as a pickle data
stream, reconstructing and returning the original object hierarchy.  This is
equivalent to <code class="docutils literal notranslate"><span class="pre">Unpickler(file).load()</span></code>.</p>
<p><em>file</em> must have two methods, a <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method that takes an integer
argument, and a <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method that requires no arguments.  Both
methods should return a string.  Thus <em>file</em> can be a file object opened for
reading, a <a class="reference internal" href="stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> object, or any other custom object that meets this
interface.</p>
<p>This function automatically determines whether the data stream was written in
binary mode or not.</p>
</dd></dl>

<dl class="function">
<dt id="pickle.dumps">
<code class="descclassname">pickle.</code><code class="descname">dumps</code><span class="sig-paren">(</span><em>obj</em><span class="optional">[</span>, <em>protocol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.dumps" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the pickled representation of the object as a string, instead of writing
it to a file.</p>
<p>If the <em>protocol</em> parameter is omitted, protocol 0 is used. If <em>protocol</em> is
specified as a negative value or <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>, the highest protocol
version will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The <em>protocol</em> parameter was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="pickle.loads">
<code class="descclassname">pickle.</code><code class="descname">loads</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.loads" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a pickled object hierarchy from a string.  Characters in the string past
the pickled object’s representation are ignored.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module also defines three exceptions:</p>
<dl class="exception">
<dt id="pickle.PickleError">
<em class="property">exception </em><code class="descclassname">pickle.</code><code class="descname">PickleError</code><a class="headerlink" href="#pickle.PickleError" title="Permalink to this definition">¶</a></dt>
<dd><p>A common base class for the other exceptions defined below.  This inherits from
<a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="pickle.PicklingError">
<em class="property">exception </em><code class="descclassname">pickle.</code><code class="descname">PicklingError</code><a class="headerlink" href="#pickle.PicklingError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when an unpicklable object is passed to the
<a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dump()</span></code></a> method.</p>
</dd></dl>

<dl class="exception">
<dt id="pickle.UnpicklingError">
<em class="property">exception </em><code class="descclassname">pickle.</code><code class="descname">UnpicklingError</code><a class="headerlink" href="#pickle.UnpicklingError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when there is a problem unpickling an object. Note that
other exceptions may also be raised during unpickling, including (but not
necessarily limited to) <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>, <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a>,
<a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>, and <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module also exports two callables <a class="footnote-reference" href="#id12" id="id2">[2]</a>, <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> and
<a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a>:</p>
<dl class="class">
<dt id="pickle.Pickler">
<em class="property">class </em><code class="descclassname">pickle.</code><code class="descname">Pickler</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>protocol</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler" title="Permalink to this definition">¶</a></dt>
<dd><p>This takes a file-like object to which it will write a pickle data stream.</p>
<p>If the <em>protocol</em> parameter is omitted, protocol 0 is used. If <em>protocol</em> is
specified as a negative value or <a class="reference internal" href="#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">HIGHEST_PROTOCOL</span></code></a>, the highest
protocol version will be used.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Introduced the <em>protocol</em> parameter.</p>
</div>
<p><em>file</em> must have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method that accepts a single string argument.
It can thus be an open file object, a <a class="reference internal" href="stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> object, or any other
custom object that meets this interface.</p>
<p><a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> objects define one (or two) public methods:</p>
<dl class="method">
<dt id="pickle.Pickler.dump">
<code class="descname">dump</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a pickled representation of <em>obj</em> to the open file object given in the
constructor.  Either the binary or ASCII format will be used, depending on the
value of the <em>protocol</em> argument passed to the constructor.</p>
</dd></dl>

<dl class="method">
<dt id="pickle.Pickler.clear_memo">
<code class="descname">clear_memo</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Pickler.clear_memo" title="Permalink to this definition">¶</a></dt>
<dd><p>Clears the pickler’s “memo”.  The memo is the data structure that remembers
which objects the pickler has already seen, so that shared or recursive objects
pickled by reference and not by value.  This method is useful when re-using
picklers.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Prior to Python 2.3, <a class="reference internal" href="#pickle.Pickler.clear_memo" title="pickle.Pickler.clear_memo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_memo()</span></code></a> was only available on the picklers
created by <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>.  In the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module, picklers have an
instance variable called <code class="xref py py-attr docutils literal notranslate"><span class="pre">memo</span></code> which is a Python dictionary.  So to clear
the memo for a <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module pickler, you could do the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mypickler</span><span class="o">.</span><span class="n">memo</span><span class="o">.</span><span class="n">clear</span><span class="p">()</span>
</pre></div>
</div>
<p class="last">Code that does not need to support older versions of Python should simply use
<a class="reference internal" href="#pickle.Pickler.clear_memo" title="pickle.Pickler.clear_memo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear_memo()</span></code></a>.</p>
</div>
</dd></dl>

</dd></dl>

<p>It is possible to make multiple calls to the <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dump()</span></code></a> method of the same
<a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a> instance.  These must then be matched to the same number of
calls to the <a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> method of the corresponding <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a>
instance.  If the same object is pickled by multiple <a class="reference internal" href="#pickle.dump" title="pickle.dump"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dump()</span></code></a> calls, the
<a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> will all yield references to the same object. <a class="footnote-reference" href="#id13" id="id3">[3]</a></p>
<p><a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> objects are defined as:</p>
<dl class="class">
<dt id="pickle.Unpickler">
<em class="property">class </em><code class="descclassname">pickle.</code><code class="descname">Unpickler</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler" title="Permalink to this definition">¶</a></dt>
<dd><p>This takes a file-like object from which it will read a pickle data stream.
This class automatically determines whether the data stream was written in
binary mode or not, so it does not need a flag as in the <a class="reference internal" href="#pickle.Pickler" title="pickle.Pickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code></a>
factory.</p>
<p><em>file</em> must have two methods, a <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method that takes an integer
argument, and a <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method that requires no arguments.  Both
methods should return a string.  Thus <em>file</em> can be a file object opened for
reading, a <a class="reference internal" href="stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> object, or any other custom object that meets this
interface.</p>
<p><a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> objects have one (or two) public methods:</p>
<dl class="method">
<dt id="pickle.Unpickler.load">
<code class="descname">load</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler.load" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a pickled object representation from the open file object given in
the constructor, and return the reconstituted object hierarchy specified
therein.</p>
<p>This method automatically determines whether the data stream was written
in binary mode or not.</p>
</dd></dl>

<dl class="method">
<dt id="pickle.Unpickler.noload">
<code class="descname">noload</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pickle.Unpickler.noload" title="Permalink to this definition">¶</a></dt>
<dd><p>This is just like <a class="reference internal" href="#pickle.load" title="pickle.load"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load()</span></code></a> except that it doesn’t actually create any
objects.  This is useful primarily for finding what’s called “persistent
ids” that may be referenced in a pickle data stream.  See section
<a class="reference internal" href="#pickle-protocol"><span class="std std-ref">The pickle protocol</span></a> below for more details.</p>
<p><strong>Note:</strong> the <a class="reference internal" href="#pickle.Unpickler.noload" title="pickle.Unpickler.noload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">noload()</span></code></a> method is currently only available on
<a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a> objects created with the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module.
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module <a class="reference internal" href="#pickle.Unpickler" title="pickle.Unpickler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code></a>s do not have the <a class="reference internal" href="#pickle.Unpickler.noload" title="pickle.Unpickler.noload"><code class="xref py py-meth docutils literal notranslate"><span class="pre">noload()</span></code></a>
method.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="what-can-be-pickled-and-unpickled">
<h2>11.1.4. What can be pickled and unpickled?<a class="headerlink" href="#what-can-be-pickled-and-unpickled" title="Permalink to this headline">¶</a></h2>
<p>The following types can be pickled:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">True</span></code>, and <code class="docutils literal notranslate"><span class="pre">False</span></code></li>
<li>integers, long integers, floating point numbers, complex numbers</li>
<li>normal and Unicode strings</li>
<li>tuples, lists, sets, and dictionaries containing only picklable objects</li>
<li>functions defined at the top level of a module</li>
<li>built-in functions defined at the top level of a module</li>
<li>classes that are defined at the top level of a module</li>
<li>instances of such classes whose <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> or the result of
calling <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> is picklable  (see section <a class="reference internal" href="#pickle-protocol"><span class="std std-ref">The pickle protocol</span></a>
for details).</li>
</ul>
<p>Attempts to pickle unpicklable objects will raise the <a class="reference internal" href="#pickle.PicklingError" title="pickle.PicklingError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PicklingError</span></code></a>
exception; when this happens, an unspecified number of bytes may have already
been written to the underlying file. Trying to pickle a highly recursive data
structure may exceed the maximum recursion depth, a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> will be
raised in this case. You can carefully raise this limit with
<a class="reference internal" href="sys.html#sys.setrecursionlimit" title="sys.setrecursionlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setrecursionlimit()</span></code></a>.</p>
<p>Note that functions (built-in and user-defined) are pickled by “fully qualified”
name reference, not by value.  This means that only the function name is
pickled, along with the name of the module the function is defined in.  Neither
the function’s code, nor any of its function attributes are pickled.  Thus the
defining module must be importable in the unpickling environment, and the module
must contain the named object, otherwise an exception will be raised. <a class="footnote-reference" href="#id14" id="id4">[4]</a></p>
<p>Similarly, classes are pickled by named reference, so the same restrictions in
the unpickling environment apply.  Note that none of the class’s code or data is
pickled, so in the following example the class attribute <code class="docutils literal notranslate"><span class="pre">attr</span></code> is not
restored in the unpickling environment:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Foo</span><span class="p">:</span>
    <span class="n">attr</span> <span class="o">=</span> <span class="s1">&#39;a class attr&#39;</span>

<span class="n">picklestring</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">Foo</span><span class="p">)</span>
</pre></div>
</div>
<p>These restrictions are why picklable functions and classes must be defined in
the top level of a module.</p>
<p>Similarly, when class instances are pickled, their class’s code and data are not
pickled along with them.  Only the instance data are pickled.  This is done on
purpose, so you can fix bugs in a class or add methods to the class and still
load objects that were created with an earlier version of the class.  If you
plan to have long-lived objects that will see many versions of a class, it may
be worthwhile to put a version number in the objects so that suitable
conversions can be made by the class’s <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method.</p>
</div>
<div class="section" id="the-pickle-protocol">
<span id="pickle-protocol"></span><h2>11.1.5. The pickle protocol<a class="headerlink" href="#the-pickle-protocol" title="Permalink to this headline">¶</a></h2>
<p>This section describes the “pickling protocol” that defines the interface
between the pickler/unpickler and the objects that are being serialized.  This
protocol provides a standard way for you to define, customize, and control how
your objects are serialized and de-serialized.  The description in this section
doesn’t cover specific customizations that you can employ to make the unpickling
environment slightly safer from untrusted pickle data streams; see section
<a class="reference internal" href="#pickle-sub"><span class="std std-ref">Subclassing Unpicklers</span></a> for more details.</p>
<div class="section" id="pickling-and-unpickling-normal-class-instances">
<span id="pickle-inst"></span><h3>11.1.5.1. Pickling and unpickling normal class instances<a class="headerlink" href="#pickling-and-unpickling-normal-class-instances" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__getinitargs__">
<code class="descclassname">object.</code><code class="descname">__getinitargs__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getinitargs__" title="Permalink to this definition">¶</a></dt>
<dd><p>When a pickled class instance is unpickled, its <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method is
normally <em>not</em> invoked.  If it is desirable that the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method
be called on unpickling, an old-style class can define a method
<a class="reference internal" href="#object.__getinitargs__" title="object.__getinitargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getinitargs__()</span></code></a>, which should return a <em>tuple</em> of positional
arguments to be passed to the class constructor (<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> for
example).  Keyword arguments are not supported.  The <a class="reference internal" href="#object.__getinitargs__" title="object.__getinitargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getinitargs__()</span></code></a>
method is called at pickle time; the tuple it returns is incorporated in the
pickle for the instance.</p>
</dd></dl>

<dl class="method">
<dt id="object.__getnewargs__">
<code class="descclassname">object.</code><code class="descname">__getnewargs__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getnewargs__" title="Permalink to this definition">¶</a></dt>
<dd><p>New-style types can provide a <a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a> method that is used for
protocol 2.  Implementing this method is needed if the type establishes some
internal invariants when the instance is created, or if the memory allocation
is affected by the values passed to the <a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method for the type
(as it is for tuples and strings).  Instances of a <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>
<code class="docutils literal notranslate"><span class="pre">C</span></code> are created using</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">obj</span> <span class="o">=</span> <span class="n">C</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="n">C</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">)</span>
</pre></div>
</div>
<p>where <em>args</em> is the result of calling <a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a> on the original
object; if there is no <a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a>, an empty tuple is assumed.</p>
</dd></dl>

<dl class="method">
<dt id="object.__getstate__">
<code class="descclassname">object.</code><code class="descname">__getstate__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__getstate__" title="Permalink to this definition">¶</a></dt>
<dd><p>Classes can further influence how their instances are pickled; if the class
defines the method <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a>, it is called and the return state is
pickled as the contents for the instance, instead of the contents of the
instance’s dictionary.  If there is no <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> method, the
instance’s <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is pickled.</p>
</dd></dl>

<dl class="method">
<dt id="object.__setstate__">
<code class="descclassname">object.</code><code class="descname">__setstate__</code><span class="sig-paren">(</span><em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setstate__" title="Permalink to this definition">¶</a></dt>
<dd><p>Upon unpickling, if the class also defines the method <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>,
it is called with the unpickled state. <a class="footnote-reference" href="#id15" id="id5">[5]</a> If there is no
<a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method, the pickled state must be a dictionary and its
items are assigned to the new instance’s dictionary.  If a class defines both
<a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> and <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>, the state object needn’t be a
dictionary and these methods can do what they want. <a class="footnote-reference" href="#id16" id="id6">[6]</a></p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es, if <a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> returns a false
value, the <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method will not be called.</p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">At unpickling time, some methods like <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>, or <a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> may be called upon the
instance.  In case those methods rely on some internal invariant being
true, the type should implement either <a class="reference internal" href="#object.__getinitargs__" title="object.__getinitargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getinitargs__()</span></code></a> or
<a class="reference internal" href="#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a> to establish such an invariant; otherwise, neither
<a class="reference internal" href="../reference/datamodel.html#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> nor <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> will be called.</p>
</div>
</div>
<div class="section" id="pickling-and-unpickling-extension-types">
<h3>11.1.5.2. Pickling and unpickling extension types<a class="headerlink" href="#pickling-and-unpickling-extension-types" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__reduce__">
<code class="descclassname">object.</code><code class="descname">__reduce__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__reduce__" title="Permalink to this definition">¶</a></dt>
<dd><p>When the <code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code> encounters an object of a type it knows nothing
about — such as an extension type — it looks in two places for a hint of
how to pickle it.  One alternative is for the object to implement a
<a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method.  If provided, at pickling time <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>
will be called with no arguments, and it must return either a string or a
tuple.</p>
<p>If a string is returned, it names a global variable whose contents are
pickled as normal.  The string returned by <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> should be the
object’s local name relative to its module; the pickle module searches the
module namespace to determine the object’s module.</p>
<p>When a tuple is returned, it must be between two and five elements long.
Optional elements can either be omitted, or <code class="docutils literal notranslate"><span class="pre">None</span></code> can be provided as their
value.  The contents of this tuple are pickled as normal and used to
reconstruct the object at unpickling time.  The semantics of each element
are:</p>
<ul>
<li><p class="first">A callable object that will be called to create the initial version of the
object.  The next element of the tuple will provide arguments for this
callable, and later elements provide additional state information that will
subsequently be used to fully reconstruct the pickled data.</p>
<p>In the unpickling environment this object must be either a class, a
callable registered as a “safe constructor” (see below), or it must have an
attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__safe_for_unpickling__</span></code> with a true value. Otherwise, an
<code class="xref py py-exc docutils literal notranslate"><span class="pre">UnpicklingError</span></code> will be raised in the unpickling environment.  Note
that as usual, the callable itself is pickled by name.</p>
</li>
<li><p class="first">A tuple of arguments for the callable object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Formerly, this argument could also be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
</li>
<li><p class="first">Optionally, the object’s state, which will be passed to the object’s
<a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method as described in section <a class="reference internal" href="#pickle-inst"><span class="std std-ref">Pickling and unpickling normal class instances</span></a>.  If
the object has no <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> method, then, as above, the value
must be a dictionary and it will be added to the object’s
<a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
</li>
<li><p class="first">Optionally, an iterator (and not a sequence) yielding successive list
items.  These list items will be pickled, and appended to the object using
either <code class="docutils literal notranslate"><span class="pre">obj.append(item)</span></code> or <code class="docutils literal notranslate"><span class="pre">obj.extend(list_of_items)</span></code>.  This is
primarily used for list subclasses, but may be used by other classes as
long as they have <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code> methods with the
appropriate signature.  (Whether <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code> is used
depends on which pickle protocol version is used as well as the number of
items to append, so both must be supported.)</p>
</li>
<li><p class="first">Optionally, an iterator (not a sequence) yielding successive dictionary
items, which should be tuples of the form <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code>.  These items
will be pickled and stored to the object using <code class="docutils literal notranslate"><span class="pre">obj[key]</span> <span class="pre">=</span> <span class="pre">value</span></code>. This
is primarily used for dictionary subclasses, but may be used by other
classes as long as they implement <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>.</p>
</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="object.__reduce_ex__">
<code class="descclassname">object.</code><code class="descname">__reduce_ex__</code><span class="sig-paren">(</span><em>protocol</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reduce_ex__" title="Permalink to this definition">¶</a></dt>
<dd><p>It is sometimes useful to know the protocol version when implementing
<a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>.  This can be done by implementing a method named
<a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a> instead of <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>. <a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a>,
when it exists, is called in preference over <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> (you may
still provide <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> for backwards compatibility).  The
<a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a> method will be called with a single integer argument,
the protocol version.</p>
<p>The <a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class implements both <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> and
<a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a>; however, if a subclass overrides <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>
but not <a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a>, the <a class="reference internal" href="#object.__reduce_ex__" title="object.__reduce_ex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce_ex__()</span></code></a> implementation
detects this and calls <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a>.</p>
</dd></dl>

<p>An alternative to implementing a <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method on the object to be
pickled, is to register the callable with the <a class="reference internal" href="copy_reg.html#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a> module.  This
module provides a way for programs to register “reduction functions” and
constructors for user-defined types.   Reduction functions have the same
semantics and interface as the <a class="reference internal" href="#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method described above, except
that they are called with a single argument, the object to be pickled.</p>
<p>The registered constructor is deemed a “safe constructor” for purposes of
unpickling as described above.</p>
</div>
<div class="section" id="pickling-and-unpickling-external-objects">
<h3>11.1.5.3. Pickling and unpickling external objects<a class="headerlink" href="#pickling-and-unpickling-external-objects" title="Permalink to this headline">¶</a></h3>
<p id="index-3">For the benefit of object persistence, the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module supports the
notion of a reference to an object outside the pickled data stream.  Such
objects are referenced by a “persistent id”, which is just an arbitrary string
of printable ASCII characters. The resolution of such names is not defined by
the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module; it will delegate this resolution to user defined
functions on the pickler and unpickler. <a class="footnote-reference" href="#id17" id="id7">[7]</a></p>
<p>To define external persistent id resolution, you need to set the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">persistent_id</span></code> attribute of the pickler object and the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">persistent_load</span></code> attribute of the unpickler object.</p>
<p>To pickle objects that have an external persistent id, the pickler must have a
custom <code class="xref py py-func docutils literal notranslate"><span class="pre">persistent_id()</span></code> method that takes an object as an
argument and returns either <code class="docutils literal notranslate"><span class="pre">None</span></code> or the persistent id for that object.
When <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned, the pickler simply pickles the object as normal.
When a persistent id string is returned, the pickler will pickle that string,
along with a marker so that the unpickler will recognize the string as a
persistent id.</p>
<p>To unpickle external objects, the unpickler must have a custom
<code class="xref py py-func docutils literal notranslate"><span class="pre">persistent_load()</span></code> function that takes a persistent id string
and returns the referenced object.</p>
<p>Here’s a silly example that <em>might</em> shed more light:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="kn">from</span> <span class="nn">cStringIO</span> <span class="k">import</span> <span class="n">StringIO</span>

<span class="n">src</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">Pickler</span><span class="p">(</span><span class="n">src</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">persistent_id</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;the value </span><span class="si">%d</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">obj</span><span class="o">.</span><span class="n">x</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="kc">None</span>

<span class="n">p</span><span class="o">.</span><span class="n">persistent_id</span> <span class="o">=</span> <span class="n">persistent_id</span>

<span class="k">class</span> <span class="nc">Integer</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">x</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;My name is integer </span><span class="si">%d</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span>

<span class="n">i</span> <span class="o">=</span> <span class="n">Integer</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">i</span>
<span class="n">p</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>

<span class="n">datastream</span> <span class="o">=</span> <span class="n">src</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
<span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">datastream</span><span class="p">)</span>
<span class="n">dst</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">(</span><span class="n">datastream</span><span class="p">)</span>

<span class="n">up</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">Unpickler</span><span class="p">(</span><span class="n">dst</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">FancyInteger</span><span class="p">(</span><span class="n">Integer</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;I am the integer </span><span class="si">%d</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="bp">self</span><span class="o">.</span><span class="n">x</span>

<span class="k">def</span> <span class="nf">persistent_load</span><span class="p">(</span><span class="n">persid</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">persid</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;the value &#39;</span><span class="p">):</span>
        <span class="n">value</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">persid</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">2</span><span class="p">])</span>
        <span class="k">return</span> <span class="n">FancyInteger</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">pickle</span><span class="o">.</span><span class="n">UnpicklingError</span><span class="p">,</span> <span class="s1">&#39;Invalid persistent id&#39;</span>

<span class="n">up</span><span class="o">.</span><span class="n">persistent_load</span> <span class="o">=</span> <span class="n">persistent_load</span>

<span class="n">j</span> <span class="o">=</span> <span class="n">up</span><span class="o">.</span><span class="n">load</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">j</span>
</pre></div>
</div>
<p>In the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module, the unpickler’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">persistent_load</span></code>
attribute can also be set to a Python list, in which case, when the unpickler
reaches a persistent id, the persistent id string will simply be appended to
this list.  This functionality exists so that a pickle data stream can be
“sniffed” for object references without actually instantiating all the objects
in a pickle.
<a class="footnote-reference" href="#id18" id="id8">[8]</a>  Setting <code class="xref py py-attr docutils literal notranslate"><span class="pre">persistent_load</span></code> to a list is usually used in
conjunction with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">noload()</span></code> method on the Unpickler.</p>
</div>
</div>
<div class="section" id="subclassing-unpicklers">
<span id="pickle-sub"></span><h2>11.1.6. Subclassing Unpicklers<a class="headerlink" href="#subclassing-unpicklers" title="Permalink to this headline">¶</a></h2>
<p id="index-4">By default, unpickling will import any class that it finds in the pickle data.
You can control exactly what gets unpickled and what gets called by customizing
your unpickler.  Unfortunately, exactly how you do this is different depending
on whether you’re using <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> or <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>. <a class="footnote-reference" href="#id19" id="id9">[9]</a></p>
<p>In the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module, you need to derive a subclass from
<code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code>, overriding the <code class="xref py py-meth docutils literal notranslate"><span class="pre">load_global()</span></code> method.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">load_global()</span></code> should read two lines from the pickle data stream where the
first line will the name of the module containing the class and the second line
will be the name of the instance’s class.  It then looks up the class, possibly
importing the module and digging out the attribute, then it appends what it
finds to the unpickler’s stack.  Later on, this class will be assigned to the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code> attribute of an empty class, as a way of magically creating an
instance without calling its class’s <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>. Your job (should you
choose to accept it), would be to have <code class="xref py py-meth docutils literal notranslate"><span class="pre">load_global()</span></code> push onto the
unpickler’s stack, a known safe version of any class you deem safe to unpickle.
It is up to you to produce such a class.  Or you could raise an error if you
want to disallow all unpickling of instances.  If this sounds like a hack,
you’re right.  Refer to the source code to make this work.</p>
<p>Things are a little cleaner with <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>, but not by much. To control
what gets unpickled, you can set the unpickler’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">find_global</span></code>
attribute to a function or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If it is <code class="docutils literal notranslate"><span class="pre">None</span></code> then any attempts to
unpickle instances will raise an <code class="xref py py-exc docutils literal notranslate"><span class="pre">UnpicklingError</span></code>.  If it is a function,
then it should accept a module name and a class name, and return the
corresponding class object.  It is responsible for looking up the class and
performing any necessary imports, and it may raise an error to prevent
instances of the class from being unpickled.</p>
<p>The moral of the story is that you should be really careful about the source of
the strings your application unpickles.</p>
</div>
<div class="section" id="example">
<span id="pickle-example"></span><h2>11.1.7. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>For the simplest code, use the <code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">load()</span></code> functions.  Note
that a self-referencing list is pickled and restored correctly.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pickle</span>

<span class="n">data1</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;a&#39;</span><span class="p">:</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="o">+</span><span class="mi">6</span><span class="n">j</span><span class="p">],</span>
         <span class="s1">&#39;b&#39;</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="sa">u</span><span class="s1">&#39;Unicode string&#39;</span><span class="p">),</span>
         <span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="kc">None</span><span class="p">}</span>

<span class="n">selfref_list</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="n">selfref_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">selfref_list</span><span class="p">)</span>

<span class="n">output</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.pkl&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span>

<span class="c1"># Pickle dictionary using protocol 0.</span>
<span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">data1</span><span class="p">,</span> <span class="n">output</span><span class="p">)</span>

<span class="c1"># Pickle the list using the highest protocol available.</span>
<span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">selfref_list</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>

<span class="n">output</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The following example reads the resulting pickled data.  When reading a
pickle-containing file, you should open the file in binary mode because you
can’t be sure if the ASCII or binary format was used.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pprint</span><span class="o">,</span> <span class="nn">pickle</span>

<span class="n">pkl_file</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;data.pkl&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>

<span class="n">data1</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">pkl_file</span><span class="p">)</span>
<span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">data1</span><span class="p">)</span>

<span class="n">data2</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">pkl_file</span><span class="p">)</span>
<span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">data2</span><span class="p">)</span>

<span class="n">pkl_file</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Here’s a larger example that shows how to modify pickling behavior for a class.
The <code class="xref py py-class docutils literal notranslate"><span class="pre">TextReader</span></code> class opens a text file, and returns the line number and
line contents each time its <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> method is called. If a
<code class="xref py py-class docutils literal notranslate"><span class="pre">TextReader</span></code> instance is pickled, all attributes <em>except</em> the file object
member are saved. When the instance is unpickled, the file is reopened, and
reading resumes from the last location. The <a class="reference internal" href="#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a> and
<a class="reference internal" href="#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a> methods are used to implement this behavior.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/local/bin/python</span>

<span class="k">class</span> <span class="nc">TextReader</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Print and number lines in a text file.&quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">file</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">file</span> <span class="o">=</span> <span class="n">file</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fh</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">lineno</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">def</span> <span class="nf">readline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">lineno</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">lineno</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="n">line</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">fh</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
            <span class="k">return</span> <span class="kc">None</span>
        <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">endswith</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">):</span>
            <span class="n">line</span> <span class="o">=</span> <span class="n">line</span><span class="p">[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
        <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%d</span><span class="s2">: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lineno</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__getstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">odict</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span> <span class="c1"># copy the dict since we change it</span>
        <span class="k">del</span> <span class="n">odict</span><span class="p">[</span><span class="s1">&#39;fh&#39;</span><span class="p">]</span>              <span class="c1"># remove filehandle entry</span>
        <span class="k">return</span> <span class="n">odict</span>

    <span class="k">def</span> <span class="nf">__setstate__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
        <span class="n">fh</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="nb">dict</span><span class="p">[</span><span class="s1">&#39;file&#39;</span><span class="p">])</span>      <span class="c1"># reopen file</span>
        <span class="n">count</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">[</span><span class="s1">&#39;lineno&#39;</span><span class="p">]</span>       <span class="c1"># read from file...</span>
        <span class="k">while</span> <span class="n">count</span><span class="p">:</span>                 <span class="c1"># until line count is restored</span>
            <span class="n">fh</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
            <span class="n">count</span> <span class="o">=</span> <span class="n">count</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="bp">self</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="nb">dict</span><span class="p">)</span>   <span class="c1"># update attributes</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fh</span> <span class="o">=</span> <span class="n">fh</span>                 <span class="c1"># save the file object</span>
</pre></div>
</div>
<p>A sample usage might be something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">TextReader</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span> <span class="o">=</span> <span class="n">TextReader</span><span class="o">.</span><span class="n">TextReader</span><span class="p">(</span><span class="s2">&quot;TextReader.py&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;1: #!/usr/local/bin/python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;2: &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;3: class TextReader:&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pickle</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;save.p&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>If you want to see that <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> works across Python processes, start
another Python session, before continuing.  What follows can happen from either
the same process or a new process.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pickle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reader</span> <span class="o">=</span> <span class="n">pickle</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;save.p&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reader</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;4:     &quot;&quot;&quot;Print and number lines in a text file.&quot;&quot;&quot;&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="copy_reg.html#module-copy_reg" title="copy_reg: Register pickle support functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy_reg</span></code></a></dt>
<dd>Pickle interface constructor registration for extension types.</dd>
<dt>Module <a class="reference internal" href="shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a></dt>
<dd>Indexed databases of objects; uses <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>.</dd>
<dt>Module <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a></dt>
<dd>Shallow and deep object copying.</dd>
<dt>Module <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a></dt>
<dd>High-performance serialization of built-in types.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="module-cPickle">
<span id="cpickle-a-faster-pickle"></span><h1>11.2. <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> — A faster <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a><a class="headerlink" href="#module-cPickle" title="Permalink to this headline">¶</a></h1>
<p id="index-5">The <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module supports serialization and de-serialization of Python
objects, providing an interface and functionality nearly identical to the
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module.  There are several differences, the most important being
performance and subclassability.</p>
<p>First, <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> can be up to 1000 times faster than <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> because
the former is implemented in C.  Second, in the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module the
callables <code class="xref py py-func docutils literal notranslate"><span class="pre">Pickler()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">Unpickler()</span></code> are functions, not classes.
This means that you cannot use them to derive custom pickling and unpickling
subclasses.  Most applications have no need for this functionality and should
benefit from the greatly improved performance of the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module.</p>
<p>The pickle data stream produced by <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> are
identical, so it is possible to use <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>
interchangeably with existing pickles. <a class="footnote-reference" href="#id20" id="id10">[10]</a></p>
<p>There are additional minor differences in API between <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> and
<a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>, however for most applications, they are interchangeable.  More
documentation is provided in the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module documentation, which
includes a list of the documented differences.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id11" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Don’t confuse this with the <a class="reference internal" href="marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id12" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>In the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module these callables are classes, which you could
subclass to customize the behavior.  However, in the <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module these
callables are factory functions and so cannot be subclassed.  One common reason
to subclass is to control what objects can actually be unpickled.  See section
<a class="reference internal" href="#pickle-sub"><span class="std std-ref">Subclassing Unpicklers</span></a> for more details.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id13" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td><em>Warning</em>: this is intended for pickling multiple objects without intervening
modifications to the objects or their parts.  If you modify an object and then
pickle it again using the same <code class="xref py py-class docutils literal notranslate"><span class="pre">Pickler</span></code> instance, the object is not
pickled again — a reference to it is pickled and the <code class="xref py py-class docutils literal notranslate"><span class="pre">Unpickler</span></code> will
return the old value, not the modified one. There are two problems here: (1)
detecting changes, and (2) marshalling a minimal set of changes.  Garbage
Collection may also become a problem here.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id14" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[4]</a></td><td>The exception raised will likely be an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> or an
<a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> but it could be something else.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id15" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id5">[5]</a></td><td>These methods can also be used to implement copying class instances.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id16" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id6">[6]</a></td><td>This protocol is also used by the shallow and deep copying operations defined in
the <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> module.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id17" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id7">[7]</a></td><td>The actual mechanism for associating these user defined functions is slightly
different for <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>.  The description given here
works the same for both implementations.  Users of the <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module
could also use subclassing to effect the same results, overriding the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_id()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">persistent_load()</span></code> methods in the derived
classes.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id18" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id8">[8]</a></td><td>We’ll leave you with the image of Guido and Jim sitting around sniffing pickles
in their living rooms.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id19" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id9">[9]</a></td><td>A word of caution: the mechanisms described here use internal attributes and
methods, which are subject to change in future versions of Python.  We intend to
someday provide a common interface for controlling this behavior, which will
work in either <a class="reference internal" href="#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> or <a class="reference internal" href="#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id20" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id10">[10]</a></td><td>Since the pickle data format is actually a tiny stack-oriented programming
language, and some freedom is taken in the encodings of certain objects, it is
possible that the two modules produce different data streams for the same input
objects.  However it is guaranteed that they will always be able to read each
other’s data streams.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a><ul>
<li><a class="reference internal" href="#relationship-to-other-python-modules">11.1.1. Relationship to other Python modules</a></li>
<li><a class="reference internal" href="#data-stream-format">11.1.2. Data stream format</a></li>
<li><a class="reference internal" href="#usage">11.1.3. Usage</a></li>
<li><a class="reference internal" href="#what-can-be-pickled-and-unpickled">11.1.4. What can be pickled and unpickled?</a></li>
<li><a class="reference internal" href="#the-pickle-protocol">11.1.5. The pickle protocol</a><ul>
<li><a class="reference internal" href="#pickling-and-unpickling-normal-class-instances">11.1.5.1. Pickling and unpickling normal class instances</a></li>
<li><a class="reference internal" href="#pickling-and-unpickling-extension-types">11.1.5.2. Pickling and unpickling extension types</a></li>
<li><a class="reference internal" href="#pickling-and-unpickling-external-objects">11.1.5.3. Pickling and unpickling external objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#subclassing-unpicklers">11.1.6. Subclassing Unpicklers</a></li>
<li><a class="reference internal" href="#example">11.1.7. Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-cPickle">11.2. <code class="docutils literal notranslate"><span class="pre">cPickle</span></code> — A faster <code class="docutils literal notranslate"><span class="pre">pickle</span></code></a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="persistence.html"
                        title="previous chapter">11. Data Persistence</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="copy_reg.html"
                        title="next chapter">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pickle.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copy_reg.html" title="11.3. copy_reg — Register pickle support functions"
             >next</a> |</li>
        <li class="right" >
          <a href="persistence.html" title="11. Data Persistence"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�1���,�,html/library/pickletools.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.13. pickletools — Tools for pickle developers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="33. Python compiler package" href="compiler.html" />
    <link rel="prev" title="32.12. dis — Disassembler for Python bytecode" href="dis.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pickletools.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compiler.html" title="33. Python compiler package"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dis.html" title="32.12. dis — Disassembler for Python bytecode"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pickletools">
<span id="pickletools-tools-for-pickle-developers"></span><h1>32.13. <a class="reference internal" href="#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> — Tools for pickle developers<a class="headerlink" href="#module-pickletools" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pickletools.py">Lib/pickletools.py</a></p>
<hr class="docutils" />
<p>This module contains various constants relating to the intimate details of the
<a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module, some lengthy comments about the implementation, and a few
useful functions for analyzing pickled data.  The contents of this module are
useful for Python core developers who are working on the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and
<a class="reference internal" href="pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> implementations; ordinary users of the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module
probably won’t find the <a class="reference internal" href="#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> module relevant.</p>
<dl class="function">
<dt id="pickletools.dis">
<code class="descclassname">pickletools.</code><code class="descname">dis</code><span class="sig-paren">(</span><em>pickle</em>, <em>out=None</em>, <em>memo=None</em>, <em>indentlevel=4</em><span class="sig-paren">)</span><a class="headerlink" href="#pickletools.dis" title="Permalink to this definition">¶</a></dt>
<dd><p>Outputs a symbolic disassembly of the pickle to the file-like object <em>out</em>,
defaulting to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.  <em>pickle</em> can be a string or a file-like object.
<em>memo</em> can be a Python dictionary that will be used as the pickle’s memo; it can
be used to perform disassemblies across multiple pickles created by the same
pickler. Successive levels, indicated by <code class="docutils literal notranslate"><span class="pre">MARK</span></code> opcodes in the stream, are
indented by <em>indentlevel</em> spaces.</p>
</dd></dl>

<dl class="function">
<dt id="pickletools.genops">
<code class="descclassname">pickletools.</code><code class="descname">genops</code><span class="sig-paren">(</span><em>pickle</em><span class="sig-paren">)</span><a class="headerlink" href="#pickletools.genops" title="Permalink to this definition">¶</a></dt>
<dd><p>Provides an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> over all of the opcodes in a pickle, returning a
sequence of <code class="docutils literal notranslate"><span class="pre">(opcode,</span> <span class="pre">arg,</span> <span class="pre">pos)</span></code> triples.  <em>opcode</em> is an instance of an
<code class="xref py py-class docutils literal notranslate"><span class="pre">OpcodeInfo</span></code> class; <em>arg</em> is the decoded value, as a Python object, of
the opcode’s argument; <em>pos</em> is the position at which this opcode is located.
<em>pickle</em> can be a string or a file-like object.</p>
</dd></dl>

<dl class="function">
<dt id="pickletools.optimize">
<code class="descclassname">pickletools.</code><code class="descname">optimize</code><span class="sig-paren">(</span><em>picklestring</em><span class="sig-paren">)</span><a class="headerlink" href="#pickletools.optimize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a new equivalent pickle string after eliminating unused <code class="docutils literal notranslate"><span class="pre">PUT</span></code>
opcodes. The optimized pickle is shorter, takes less transmission time,
requires less storage space, and unpickles more efficiently.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="dis.html"
                        title="previous chapter">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="compiler.html"
                        title="next chapter">33. Python compiler package</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pickletools.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compiler.html" title="33. Python compiler package"
             >next</a> |</li>
        <li class="right" >
          <a href="dis.html" title="32.12. dis — Disassembler for Python bytecode"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Z%P�L�Lhtml/library/pipes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.11. pipes — Interface to shell pipelines &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.12. posixfile — File-like objects with locking support" href="posixfile.html" />
    <link rel="prev" title="36.10. fcntl — The fcntl and ioctl system calls" href="fcntl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pipes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="posixfile.html" title="36.12. posixfile — File-like objects with locking support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fcntl.html" title="36.10. fcntl — The fcntl and ioctl system calls"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pipes">
<span id="pipes-interface-to-shell-pipelines"></span><h1>36.11. <a class="reference internal" href="#module-pipes" title="pipes: A Python interface to Unix shell pipelines. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pipes</span></code></a> — Interface to shell pipelines<a class="headerlink" href="#module-pipes" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pipes.py">Lib/pipes.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-pipes" title="pipes: A Python interface to Unix shell pipelines. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pipes</span></code></a> module defines a class to abstract the concept of a <em>pipeline</em>
— a sequence of converters from one file to  another.</p>
<p>Because the module uses <strong class="program">/bin/sh</strong> command lines, a POSIX or compatible
shell for <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a> and <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> is required.</p>
<dl class="class">
<dt id="pipes.Template">
<em class="property">class </em><code class="descclassname">pipes.</code><code class="descname">Template</code><a class="headerlink" href="#pipes.Template" title="Permalink to this definition">¶</a></dt>
<dd><p>An abstraction of a pipeline.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pipes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">pipes</span><span class="o">.</span><span class="n">Template</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;tr a-z A-Z&#39;</span><span class="p">,</span> <span class="s1">&#39;--&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;pipefile&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;hello world&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">open</span><span class="p">(</span><span class="s1">&#39;pipefile&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;HELLO WORLD&#39;</span>
</pre></div>
</div>
<dl class="function">
<dt id="pipes.quote">
<code class="descclassname">pipes.</code><code class="descname">quote</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.quote" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Prior to Python 2.7, this function was not publicly documented.  It is
finally exposed publicly in Python 3.3 as the
<code class="xref py py-func docutils literal notranslate"><span class="pre">quote</span></code> function in the <a class="reference internal" href="shlex.html#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a> module.</p>
</div>
<p>Return a shell-escaped version of the string <em>s</em>.  The returned value is a
string that can safely be used as one token in a shell command line, for
cases where you cannot use a list.</p>
<p>This idiom would be unsafe:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">filename</span> <span class="o">=</span> <span class="s1">&#39;somefile; rm -rf ~&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">command</span> <span class="o">=</span> <span class="s1">&#39;ls -l </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">command</span>  <span class="c1"># executed by a shell: boom!</span>
<span class="go">ls -l somefile; rm -rf ~</span>
</pre></div>
</div>
<p><a class="reference internal" href="#pipes.quote" title="pipes.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">quote()</span></code></a> lets you plug the security hole:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">command</span> <span class="o">=</span> <span class="s1">&#39;ls -l </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">quote</span><span class="p">(</span><span class="n">filename</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">command</span>
<span class="go">ls -l &#39;somefile; rm -rf ~&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">remote_command</span> <span class="o">=</span> <span class="s1">&#39;ssh home </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">quote</span><span class="p">(</span><span class="n">command</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">remote_command</span>
<span class="go">ssh home &#39;ls -l &#39;&quot;&#39;&quot;&#39;somefile; rm -rf ~&#39;&quot;&#39;&quot;&#39;&#39;</span>
</pre></div>
</div>
<p>The quoting is compatible with UNIX shells and with <a class="reference internal" href="shlex.html#shlex.split" title="shlex.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">shlex.split()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">remote_command</span> <span class="o">=</span> <span class="n">shlex</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">remote_command</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">remote_command</span>
<span class="go">[&#39;ssh&#39;, &#39;home&#39;, &quot;ls -l &#39;somefile; rm -rf ~&#39;&quot;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">command</span> <span class="o">=</span> <span class="n">shlex</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">remote_command</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">command</span>
<span class="go">[&#39;ls&#39;, &#39;-l&#39;, &#39;somefile; rm -rf ~&#39;]</span>
</pre></div>
</div>
</dd></dl>

<div class="section" id="template-objects">
<span id="id1"></span><h2>36.11.1. Template Objects<a class="headerlink" href="#template-objects" title="Permalink to this headline">¶</a></h2>
<p>Template objects following methods:</p>
<dl class="method">
<dt id="pipes.Template.reset">
<code class="descclassname">Template.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Restore a pipeline template to its initial state.</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.clone">
<code class="descclassname">Template.</code><code class="descname">clone</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.clone" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new, equivalent, pipeline template.</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.debug">
<code class="descclassname">Template.</code><code class="descname">debug</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>flag</em> is true, turn debugging on. Otherwise, turn debugging off. When
debugging is on, commands to be executed are printed, and the shell is given
<code class="docutils literal notranslate"><span class="pre">set</span> <span class="pre">-x</span></code> command to be more verbose.</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.append">
<code class="descclassname">Template.</code><code class="descname">append</code><span class="sig-paren">(</span><em>cmd</em>, <em>kind</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Append a new action at the end. The <em>cmd</em> variable must be a valid bourne shell
command. The <em>kind</em> variable consists of two letters.</p>
<p>The first letter can be either of <code class="docutils literal notranslate"><span class="pre">'-'</span></code> (which means the command reads its
standard input), <code class="docutils literal notranslate"><span class="pre">'f'</span></code> (which means the commands reads a given file on the
command line) or <code class="docutils literal notranslate"><span class="pre">'.'</span></code> (which means the commands reads no input, and hence
must be first.)</p>
<p>Similarly, the second letter can be either of <code class="docutils literal notranslate"><span class="pre">'-'</span></code> (which means  the command
writes to standard output), <code class="docutils literal notranslate"><span class="pre">'f'</span></code> (which means the  command writes a file on
the command line) or <code class="docutils literal notranslate"><span class="pre">'.'</span></code> (which means the command does not write anything,
and hence must be last.)</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.prepend">
<code class="descclassname">Template.</code><code class="descname">prepend</code><span class="sig-paren">(</span><em>cmd</em>, <em>kind</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.prepend" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a new action at the beginning. See <a class="reference internal" href="#pipes.Template.append" title="pipes.Template.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code></a> for explanations of the
arguments.</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.open">
<code class="descclassname">Template.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a file-like object, open to <em>file</em>, but read from or written to by the
pipeline.  Note that only one of <code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> may be given.</p>
</dd></dl>

<dl class="method">
<dt id="pipes.Template.copy">
<code class="descclassname">Template.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>infile</em>, <em>outfile</em><span class="sig-paren">)</span><a class="headerlink" href="#pipes.Template.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy <em>infile</em> to <em>outfile</em> through the pipe.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a><ul>
<li><a class="reference internal" href="#template-objects">36.11.1. Template Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="fcntl.html"
                        title="previous chapter">36.10. <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="posixfile.html"
                        title="next chapter">36.12. <code class="docutils literal notranslate"><span class="pre">posixfile</span></code> — File-like objects with locking support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pipes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="posixfile.html" title="36.12. posixfile — File-like objects with locking support"
             >next</a> |</li>
        <li class="right" >
          <a href="fcntl.html" title="36.10. fcntl — The fcntl and ioctl system calls"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����j�jhtml/library/pkgutil.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.5. pkgutil — Package extension utility &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.6. modulefinder — Find modules used by a script" href="modulefinder.html" />
    <link rel="prev" title="31.4. zipimport — Import modules from Zip archives" href="zipimport.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pkgutil.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.6. modulefinder — Find modules used by a script"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="zipimport.html" title="31.4. zipimport — Import modules from Zip archives"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pkgutil">
<span id="pkgutil-package-extension-utility"></span><h1>31.5. <a class="reference internal" href="#module-pkgutil" title="pkgutil: Utilities for the import system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pkgutil</span></code></a> — Package extension utility<a class="headerlink" href="#module-pkgutil" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pkgutil.py">Lib/pkgutil.py</a></p>
<hr class="docutils" />
<p>This module provides utilities for the import system, in particular package
support.</p>
<dl class="function">
<dt id="pkgutil.extend_path">
<code class="descclassname">pkgutil.</code><code class="descname">extend_path</code><span class="sig-paren">(</span><em>path</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.extend_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Extend the search path for the modules which comprise a package.  Intended
use is to place the following code in a package’s <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">pkgutil</span> <span class="k">import</span> <span class="n">extend_path</span>
<span class="n">__path__</span> <span class="o">=</span> <span class="n">extend_path</span><span class="p">(</span><span class="n">__path__</span><span class="p">,</span> <span class="vm">__name__</span><span class="p">)</span>
</pre></div>
</div>
<p>This will add to the package’s <code class="docutils literal notranslate"><span class="pre">__path__</span></code> all subdirectories of directories
on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> named after the package.  This is useful if one wants to
distribute different parts of a single logical package as multiple
directories.</p>
<p>It also looks for <code class="file docutils literal notranslate"><span class="pre">*.pkg</span></code> files beginning where <code class="docutils literal notranslate"><span class="pre">*</span></code> matches the
<em>name</em> argument.  This feature is similar to <code class="file docutils literal notranslate"><span class="pre">*.pth</span></code> files (see the
<a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module for more information), except that it doesn’t special-case
lines starting with <code class="docutils literal notranslate"><span class="pre">import</span></code>.  A <code class="file docutils literal notranslate"><span class="pre">*.pkg</span></code> file is trusted at face
value: apart from checking for duplicates, all entries found in a
<code class="file docutils literal notranslate"><span class="pre">*.pkg</span></code> file are added to the path, regardless of whether they exist
on the filesystem.  (This is a feature.)</p>
<p>If the input path is not a list (as is the case for frozen packages) it is
returned unchanged.  The input path is not modified; an extended copy is
returned.  Items are only appended to the copy at the end.</p>
<p>It is assumed that <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is a sequence.  Items of <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>
that are not (Unicode or 8-bit) strings referring to existing directories are
ignored.  Unicode items on <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> that cause errors when used as
filenames may cause this function to raise an exception (in line with
<a class="reference internal" href="os.path.html#os.path.isdir" title="os.path.isdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.isdir()</span></code></a> behavior).</p>
</dd></dl>

<dl class="class">
<dt id="pkgutil.ImpImporter">
<em class="property">class </em><code class="descclassname">pkgutil.</code><code class="descname">ImpImporter</code><span class="sig-paren">(</span><em>dirname=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.ImpImporter" title="Permalink to this definition">¶</a></dt>
<dd><p><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> Importer that wraps Python’s “classic” import algorithm.</p>
<p>If <em>dirname</em> is a string, a <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> importer is created that searches that
directory.  If <em>dirname</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, a <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> importer is created that
searches the current <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, plus any modules that are frozen or
built-in.</p>
<p>Note that <a class="reference internal" href="#pkgutil.ImpImporter" title="pkgutil.ImpImporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImpImporter</span></code></a> does not currently support being used by
placement on <a class="reference internal" href="sys.html#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="pkgutil.ImpLoader">
<em class="property">class </em><code class="descclassname">pkgutil.</code><code class="descname">ImpLoader</code><span class="sig-paren">(</span><em>fullname</em>, <em>file</em>, <em>filename</em>, <em>etc</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.ImpLoader" title="Permalink to this definition">¶</a></dt>
<dd><p><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> Loader that wraps Python’s “classic” import algorithm.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.find_loader">
<code class="descclassname">pkgutil.</code><code class="descname">find_loader</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.find_loader" title="Permalink to this definition">¶</a></dt>
<dd><p>Find a <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> “loader” object for <em>fullname</em>.</p>
<p>If <em>fullname</em> contains dots, path must be the containing package’s
<code class="docutils literal notranslate"><span class="pre">__path__</span></code>.  Returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if the module cannot be found or imported.
This function uses <a class="reference internal" href="#pkgutil.iter_importers" title="pkgutil.iter_importers"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter_importers()</span></code></a>, and is thus subject to the same
limitations regarding platform-specific special import locations such as the
Windows registry.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.get_importer">
<code class="descclassname">pkgutil.</code><code class="descname">get_importer</code><span class="sig-paren">(</span><em>path_item</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.get_importer" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a <span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> importer for the given <em>path_item</em>.</p>
<p>The returned importer is cached in <a class="reference internal" href="sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a> if it was
newly created by a path hook.</p>
<p>If there is no importer, a wrapper around the basic import machinery is
returned.  This wrapper is never inserted into the importer cache (<code class="docutils literal notranslate"><span class="pre">None</span></code>
is inserted instead).</p>
<p>The cache (or part of it) can be cleared manually if a rescan of
<a class="reference internal" href="sys.html#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a> is necessary.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.get_loader">
<code class="descclassname">pkgutil.</code><code class="descname">get_loader</code><span class="sig-paren">(</span><em>module_or_name</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.get_loader" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> “loader” object for <em>module_or_name</em>.</p>
<p>If the module or package is accessible via the normal import mechanism, a
wrapper around the relevant part of that machinery is returned.  Returns
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the module cannot be found or imported.  If the named module is
not already imported, its containing package (if any) is imported, in order
to establish the package <code class="docutils literal notranslate"><span class="pre">__path__</span></code>.</p>
<p>This function uses <a class="reference internal" href="#pkgutil.iter_importers" title="pkgutil.iter_importers"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter_importers()</span></code></a>, and is thus subject to the same
limitations regarding platform-specific special import locations such as the
Windows registry.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.iter_importers">
<code class="descclassname">pkgutil.</code><code class="descname">iter_importers</code><span class="sig-paren">(</span><em>fullname=''</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.iter_importers" title="Permalink to this definition">¶</a></dt>
<dd><p>Yield <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> importers for the given module name.</p>
<p>If fullname contains a ‘.’, the importers will be for the package containing
fullname, otherwise they will be importers for <a class="reference internal" href="sys.html#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a>,
<a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, and Python’s “classic” import machinery, in that order.  If
the named module is in a package, that package is imported as a side effect
of invoking this function.</p>
<p>Non-<span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> mechanisms (e.g. the Windows registry) used by the standard
import machinery to find files in alternative locations are partially
supported, but are searched <em>after</em> <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.  Normally, these
locations are searched <em>before</em> <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, preventing <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>
entries from shadowing them.</p>
<p>For this to cause a visible difference in behaviour, there must be a module
or package name that is accessible via both <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> and one of the
non-<span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> file system mechanisms.  In this case, the emulation will find
the former version, while the builtin import mechanism will find the latter.</p>
<p>Items of the following types can be affected by this discrepancy:
<code class="docutils literal notranslate"><span class="pre">imp.C_EXTENSION</span></code>, <code class="docutils literal notranslate"><span class="pre">imp.PY_SOURCE</span></code>, <code class="docutils literal notranslate"><span class="pre">imp.PY_COMPILED</span></code>,
<code class="docutils literal notranslate"><span class="pre">imp.PKG_DIRECTORY</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.iter_modules">
<code class="descclassname">pkgutil.</code><code class="descname">iter_modules</code><span class="sig-paren">(</span><em>path=None</em>, <em>prefix=''</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.iter_modules" title="Permalink to this definition">¶</a></dt>
<dd><p>Yields <code class="docutils literal notranslate"><span class="pre">(module_loader,</span> <span class="pre">name,</span> <span class="pre">ispkg)</span></code> for all submodules on <em>path</em>, or, if
path is <code class="docutils literal notranslate"><span class="pre">None</span></code>, all top-level modules on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.</p>
<p><em>path</em> should be either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a list of paths to look for modules in.</p>
<p><em>prefix</em> is a string to output on the front of every module name on output.</p>
</dd></dl>

<dl class="function">
<dt id="pkgutil.walk_packages">
<code class="descclassname">pkgutil.</code><code class="descname">walk_packages</code><span class="sig-paren">(</span><em>path=None</em>, <em>prefix=''</em>, <em>onerror=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.walk_packages" title="Permalink to this definition">¶</a></dt>
<dd><p>Yields <code class="docutils literal notranslate"><span class="pre">(module_loader,</span> <span class="pre">name,</span> <span class="pre">ispkg)</span></code> for all modules recursively on
<em>path</em>, or, if path is <code class="docutils literal notranslate"><span class="pre">None</span></code>, all accessible modules.</p>
<p><em>path</em> should be either <code class="docutils literal notranslate"><span class="pre">None</span></code> or a list of paths to look for modules in.</p>
<p><em>prefix</em> is a string to output on the front of every module name on output.</p>
<p>Note that this function must import all <em>packages</em> (<em>not</em> all modules!) on
the given <em>path</em>, in order to access the <code class="docutils literal notranslate"><span class="pre">__path__</span></code> attribute to find
submodules.</p>
<p><em>onerror</em> is a function which gets called with one argument (the name of the
package which was being imported) if any exception occurs while trying to
import a package.  If no <em>onerror</em> function is supplied, <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>s
are caught and ignored, while all other exceptions are propagated,
terminating the search.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># list all modules python can access</span>
<span class="n">walk_packages</span><span class="p">()</span>

<span class="c1"># list all submodules of ctypes</span>
<span class="n">walk_packages</span><span class="p">(</span><span class="n">ctypes</span><span class="o">.</span><span class="n">__path__</span><span class="p">,</span> <span class="n">ctypes</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">+</span> <span class="s1">&#39;.&#39;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="pkgutil.get_data">
<code class="descclassname">pkgutil.</code><code class="descname">get_data</code><span class="sig-paren">(</span><em>package</em>, <em>resource</em><span class="sig-paren">)</span><a class="headerlink" href="#pkgutil.get_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a resource from a package.</p>
<p>This is a wrapper for the <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> loader <a class="reference internal" href="#pkgutil.get_data" title="pkgutil.get_data"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_data()</span></code></a> API.  The
<em>package</em> argument should be the name of a package, in standard module format
(<code class="docutils literal notranslate"><span class="pre">foo.bar</span></code>).  The <em>resource</em> argument should be in the form of a relative
filename, using <code class="docutils literal notranslate"><span class="pre">/</span></code> as the path separator.  The parent directory name
<code class="docutils literal notranslate"><span class="pre">..</span></code> is not allowed, and nor is a rooted name (starting with a <code class="docutils literal notranslate"><span class="pre">/</span></code>).</p>
<p>The function returns a binary string that is the contents of the specified
resource.</p>
<p>For packages located in the filesystem, which have already been imported,
this is the rough equivalent of:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">d</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="n">package</span><span class="p">]</span><span class="o">.</span><span class="vm">__file__</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">resource</span><span class="p">),</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>If the package cannot be located or loaded, or it uses a <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> loader
which does not support <a class="reference internal" href="#pkgutil.get_data" title="pkgutil.get_data"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_data()</span></code></a>, then <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="zipimport.html"
                        title="previous chapter">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="modulefinder.html"
                        title="next chapter">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pkgutil.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.6. modulefinder — Find modules used by a script"
             >next</a> |</li>
        <li class="right" >
          <a href="zipimport.html" title="31.4. zipimport — Import modules from Zip archives"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6]�o{o{html/library/platform.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.15. platform — Access to underlying platform’s identifying data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.16. errno — Standard errno system symbols" href="errno.html" />
    <link rel="prev" title="15.14. curses.panel — A panel stack extension for curses" href="curses.panel.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/platform.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="curses.panel.html" title="15.14. curses.panel — A panel stack extension for curses"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-platform">
<span id="platform-access-to-underlying-platform-s-identifying-data"></span><h1>15.15. <a class="reference internal" href="#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> —  Access to underlying platform’s identifying data<a class="headerlink" href="#module-platform" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/platform.py">Lib/platform.py</a></p>
<hr class="docutils" />
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Specific platforms listed alphabetically, with Linux included in the Unix
section.</p>
</div>
<div class="section" id="cross-platform">
<h2>15.15.1. Cross Platform<a class="headerlink" href="#cross-platform" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="platform.architecture">
<code class="descclassname">platform.</code><code class="descname">architecture</code><span class="sig-paren">(</span><em>executable=sys.executable</em>, <em>bits=''</em>, <em>linkage=''</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.architecture" title="Permalink to this definition">¶</a></dt>
<dd><p>Queries the given executable (defaults to the Python interpreter binary) for
various architecture information.</p>
<p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(bits,</span> <span class="pre">linkage)</span></code> which contain information about the bit
architecture and the linkage format used for the executable. Both values are
returned as strings.</p>
<p>Values that cannot be determined are returned as given by the parameter presets.
If bits is given as <code class="docutils literal notranslate"><span class="pre">''</span></code>, the <code class="docutils literal notranslate"><span class="pre">sizeof(pointer)</span></code> (or
<code class="docutils literal notranslate"><span class="pre">sizeof(long)</span></code> on Python version &lt; 1.5.2) is used as indicator for the
supported pointer size.</p>
<p>The function relies on the system’s <code class="file docutils literal notranslate"><span class="pre">file</span></code> command to do the actual work.
This is available on most if not all Unix  platforms and some non-Unix platforms
and then only if the executable points to the Python interpreter.  Reasonable
defaults are used when the above needs are not met.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>On Mac OS X (and perhaps other platforms), executable files may be
universal files containing multiple architectures.</p>
<p>To get at the “64-bitness” of the current interpreter, it is more
reliable to query the <a class="reference internal" href="sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a> attribute:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">is_64bits</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">maxsize</span> <span class="o">&gt;</span> <span class="mi">2</span><span class="o">**</span><span class="mi">32</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.machine">
<code class="descclassname">platform.</code><code class="descname">machine</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.machine" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the machine type, e.g. <code class="docutils literal notranslate"><span class="pre">'i386'</span></code>. An empty string is returned if the
value cannot be determined.</p>
</dd></dl>

<dl class="function">
<dt id="platform.node">
<code class="descclassname">platform.</code><code class="descname">node</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.node" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the computer’s network name (may not be fully qualified!). An empty
string is returned if the value cannot be determined.</p>
</dd></dl>

<dl class="function">
<dt id="platform.platform">
<code class="descclassname">platform.</code><code class="descname">platform</code><span class="sig-paren">(</span><em>aliased=0</em>, <em>terse=0</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.platform" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a single string identifying the underlying platform with as much useful
information as possible.</p>
<p>The output is intended to be <em>human readable</em> rather than machine parseable. It
may look different on different platforms and this is intended.</p>
<p>If <em>aliased</em> is true, the function will use aliases for various platforms that
report system names which differ from their common names, for example SunOS will
be reported as Solaris.  The <a class="reference internal" href="#platform.system_alias" title="platform.system_alias"><code class="xref py py-func docutils literal notranslate"><span class="pre">system_alias()</span></code></a> function is used to implement
this.</p>
<p>Setting <em>terse</em> to true causes the function to return only the absolute minimum
information needed to identify the platform.</p>
</dd></dl>

<dl class="function">
<dt id="platform.processor">
<code class="descclassname">platform.</code><code class="descname">processor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.processor" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the (real) processor name, e.g. <code class="docutils literal notranslate"><span class="pre">'amdk6'</span></code>.</p>
<p>An empty string is returned if the value cannot be determined. Note that many
platforms do not provide this information or simply return the same value as for
<a class="reference internal" href="#platform.machine" title="platform.machine"><code class="xref py py-func docutils literal notranslate"><span class="pre">machine()</span></code></a>.  NetBSD does this.</p>
</dd></dl>

<dl class="function">
<dt id="platform.python_build">
<code class="descclassname">platform.</code><code class="descname">python_build</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_build" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(buildno,</span> <span class="pre">builddate)</span></code> stating the Python build number and
date as strings.</p>
</dd></dl>

<dl class="function">
<dt id="platform.python_compiler">
<code class="descclassname">platform.</code><code class="descname">python_compiler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_compiler" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string identifying the compiler used for compiling Python.</p>
</dd></dl>

<dl class="function">
<dt id="platform.python_branch">
<code class="descclassname">platform.</code><code class="descname">python_branch</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_branch" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string identifying the Python implementation SCM branch.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.python_implementation">
<code class="descclassname">platform.</code><code class="descname">python_implementation</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_implementation" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string identifying the Python implementation. Possible return values
are: ‘CPython’, ‘IronPython’, ‘Jython’, ‘PyPy’.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.python_revision">
<code class="descclassname">platform.</code><code class="descname">python_revision</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_revision" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string identifying the Python implementation SCM revision.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.python_version">
<code class="descclassname">platform.</code><code class="descname">python_version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the Python version as string <code class="docutils literal notranslate"><span class="pre">'major.minor.patchlevel'</span></code>.</p>
<p>Note that unlike the Python <code class="docutils literal notranslate"><span class="pre">sys.version</span></code>, the returned value will always
include the patchlevel (it defaults to 0).</p>
</dd></dl>

<dl class="function">
<dt id="platform.python_version_tuple">
<code class="descclassname">platform.</code><code class="descname">python_version_tuple</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.python_version_tuple" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the Python version as tuple <code class="docutils literal notranslate"><span class="pre">(major,</span> <span class="pre">minor,</span> <span class="pre">patchlevel)</span></code> of strings.</p>
<p>Note that unlike the Python <code class="docutils literal notranslate"><span class="pre">sys.version</span></code>, the returned value will always
include the patchlevel (it defaults to <code class="docutils literal notranslate"><span class="pre">'0'</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="platform.release">
<code class="descclassname">platform.</code><code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the system’s release, e.g. <code class="docutils literal notranslate"><span class="pre">'2.2.0'</span></code> or <code class="docutils literal notranslate"><span class="pre">'NT'</span></code> An empty string is
returned if the value cannot be determined.</p>
</dd></dl>

<dl class="function">
<dt id="platform.system">
<code class="descclassname">platform.</code><code class="descname">system</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.system" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the system/OS name, e.g. <code class="docutils literal notranslate"><span class="pre">'Linux'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Windows'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'Java'</span></code>. An
empty string is returned if the value cannot be determined.</p>
</dd></dl>

<dl class="function">
<dt id="platform.system_alias">
<code class="descclassname">platform.</code><code class="descname">system_alias</code><span class="sig-paren">(</span><em>system</em>, <em>release</em>, <em>version</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.system_alias" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">(system,</span> <span class="pre">release,</span> <span class="pre">version)</span></code> aliased to common marketing names used
for some systems.  It also does some reordering of the information in some cases
where it would otherwise cause confusion.</p>
</dd></dl>

<dl class="function">
<dt id="platform.version">
<code class="descclassname">platform.</code><code class="descname">version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the system’s release version, e.g. <code class="docutils literal notranslate"><span class="pre">'#3</span> <span class="pre">on</span> <span class="pre">degas'</span></code>. An empty string is
returned if the value cannot be determined.</p>
</dd></dl>

<dl class="function">
<dt id="platform.uname">
<code class="descclassname">platform.</code><code class="descname">uname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#platform.uname" title="Permalink to this definition">¶</a></dt>
<dd><p>Fairly portable uname interface. Returns a tuple of strings <code class="docutils literal notranslate"><span class="pre">(system,</span> <span class="pre">node,</span>
<span class="pre">release,</span> <span class="pre">version,</span> <span class="pre">machine,</span> <span class="pre">processor)</span></code> identifying the underlying platform.</p>
<p>Note that unlike the <a class="reference internal" href="os.html#os.uname" title="os.uname"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.uname()</span></code></a> function this also returns possible
processor information as additional tuple entry.</p>
<p>Entries which cannot be determined are set to <code class="docutils literal notranslate"><span class="pre">''</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="java-platform">
<h2>15.15.2. Java Platform<a class="headerlink" href="#java-platform" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="platform.java_ver">
<code class="descclassname">platform.</code><code class="descname">java_ver</code><span class="sig-paren">(</span><em>release=''</em>, <em>vendor=''</em>, <em>vminfo=(''</em>, <em>''</em>, <em>'')</em>, <em>osinfo=(''</em>, <em>''</em>, <em>'')</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.java_ver" title="Permalink to this definition">¶</a></dt>
<dd><p>Version interface for Jython.</p>
<p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(release,</span> <span class="pre">vendor,</span> <span class="pre">vminfo,</span> <span class="pre">osinfo)</span></code> with <em>vminfo</em> being a
tuple <code class="docutils literal notranslate"><span class="pre">(vm_name,</span> <span class="pre">vm_release,</span> <span class="pre">vm_vendor)</span></code> and <em>osinfo</em> being a tuple
<code class="docutils literal notranslate"><span class="pre">(os_name,</span> <span class="pre">os_version,</span> <span class="pre">os_arch)</span></code>. Values which cannot be determined are set to
the defaults given as parameters (which all default to <code class="docutils literal notranslate"><span class="pre">''</span></code>).</p>
</dd></dl>

</div>
<div class="section" id="windows-platform">
<h2>15.15.3. Windows Platform<a class="headerlink" href="#windows-platform" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="platform.win32_ver">
<code class="descclassname">platform.</code><code class="descname">win32_ver</code><span class="sig-paren">(</span><em>release=''</em>, <em>version=''</em>, <em>csd=''</em>, <em>ptype=''</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.win32_ver" title="Permalink to this definition">¶</a></dt>
<dd><p>Get additional version information from the Windows Registry and return a tuple
<code class="docutils literal notranslate"><span class="pre">(release,</span> <span class="pre">version,</span> <span class="pre">csd,</span> <span class="pre">ptype)</span></code> referring to OS release, version number,
CSD level (service pack) and OS type (multi/single processor).</p>
<p>As a hint: <em>ptype</em> is <code class="docutils literal notranslate"><span class="pre">'Uniprocessor</span> <span class="pre">Free'</span></code> on single processor NT machines
and <code class="docutils literal notranslate"><span class="pre">'Multiprocessor</span> <span class="pre">Free'</span></code> on multi processor machines. The <em>‘Free’</em> refers
to the OS version being free of debugging code. It could also state <em>‘Checked’</em>
which means the OS version uses debugging code, i.e. code that checks arguments,
ranges, etc.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function works best with Mark Hammond’s
<code class="xref py py-mod docutils literal notranslate"><span class="pre">win32all</span></code> package installed, but also on Python 2.3 and
later (support for this was added in Python 2.6). It obviously
only runs on Win32 compatible platforms.</p>
</div>
</dd></dl>

<div class="section" id="win95-98-specific">
<h3>15.15.3.1. Win95/98 specific<a class="headerlink" href="#win95-98-specific" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="platform.popen">
<code class="descclassname">platform.</code><code class="descname">popen</code><span class="sig-paren">(</span><em>cmd</em>, <em>mode='r'</em>, <em>bufsize=None</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.popen" title="Permalink to this definition">¶</a></dt>
<dd><p>Portable <a class="reference internal" href="#platform.popen" title="platform.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> interface.  Find a working popen implementation
preferring <code class="xref py py-func docutils literal notranslate"><span class="pre">win32pipe.popen()</span></code>.  On Windows NT, <code class="xref py py-func docutils literal notranslate"><span class="pre">win32pipe.popen()</span></code>
should work; on Windows 9x it hangs due to bugs in the MS C library.</p>
</dd></dl>

</div>
</div>
<div class="section" id="mac-os-platform">
<h2>15.15.4. Mac OS Platform<a class="headerlink" href="#mac-os-platform" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="platform.mac_ver">
<code class="descclassname">platform.</code><code class="descname">mac_ver</code><span class="sig-paren">(</span><em>release=''</em>, <em>versioninfo=(''</em>, <em>''</em>, <em>'')</em>, <em>machine=''</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.mac_ver" title="Permalink to this definition">¶</a></dt>
<dd><p>Get Mac OS version information and return it as tuple <code class="docutils literal notranslate"><span class="pre">(release,</span> <span class="pre">versioninfo,</span>
<span class="pre">machine)</span></code> with <em>versioninfo</em> being a tuple <code class="docutils literal notranslate"><span class="pre">(version,</span> <span class="pre">dev_stage,</span>
<span class="pre">non_release_version)</span></code>.</p>
<p>Entries which cannot be determined are set to <code class="docutils literal notranslate"><span class="pre">''</span></code>.  All tuple entries are
strings.</p>
</dd></dl>

</div>
<div class="section" id="unix-platforms">
<h2>15.15.5. Unix Platforms<a class="headerlink" href="#unix-platforms" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="platform.dist">
<code class="descclassname">platform.</code><code class="descname">dist</code><span class="sig-paren">(</span><em>distname=''</em>, <em>version=''</em>, <em>id=''</em>, <em>supported_dists=('SuSE'</em>, <em>'debian'</em>, <em>'redhat'</em>, <em>'mandrake'</em>, <em>...)</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.dist" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an old version of the functionality now provided by
<a class="reference internal" href="#platform.linux_distribution" title="platform.linux_distribution"><code class="xref py py-func docutils literal notranslate"><span class="pre">linux_distribution()</span></code></a>. For new code, please use the
<a class="reference internal" href="#platform.linux_distribution" title="platform.linux_distribution"><code class="xref py py-func docutils literal notranslate"><span class="pre">linux_distribution()</span></code></a>.</p>
<p>The only difference between the two is that <code class="docutils literal notranslate"><span class="pre">dist()</span></code> always
returns the short name of the distribution taken from the
<code class="docutils literal notranslate"><span class="pre">supported_dists</span></code> parameter.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.linux_distribution">
<code class="descclassname">platform.</code><code class="descname">linux_distribution</code><span class="sig-paren">(</span><em>distname=''</em>, <em>version=''</em>, <em>id=''</em>, <em>supported_dists=('SuSE'</em>, <em>'debian'</em>, <em>'redhat'</em>, <em>'mandrake'</em>, <em>...)</em>, <em>full_distribution_name=1</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.linux_distribution" title="Permalink to this definition">¶</a></dt>
<dd><p>Tries to determine the name of the Linux OS distribution name.</p>
<p><code class="docutils literal notranslate"><span class="pre">supported_dists</span></code> may be given to define the set of Linux distributions to
look for. It defaults to a list of currently supported Linux distributions
identified by their release file name.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">full_distribution_name</span></code> is true (default), the full distribution read
from the OS is returned. Otherwise the short name taken from
<code class="docutils literal notranslate"><span class="pre">supported_dists</span></code> is used.</p>
<p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(distname,version,id)</span></code> which defaults to the args given as
parameters.  <code class="docutils literal notranslate"><span class="pre">id</span></code> is the item in parentheses after the version number.  It
is usually the version codename.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is deprecated since Python 3.5 and removed in Python 3.8.
See alternative like the <a class="reference external" href="https://pypi.org/project/distro">distro</a> package.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="platform.libc_ver">
<code class="descclassname">platform.</code><code class="descname">libc_ver</code><span class="sig-paren">(</span><em>executable=sys.executable</em>, <em>lib=''</em>, <em>version=''</em>, <em>chunksize=2048</em><span class="sig-paren">)</span><a class="headerlink" href="#platform.libc_ver" title="Permalink to this definition">¶</a></dt>
<dd><p>Tries to determine the libc version against which the file executable (defaults
to the Python interpreter) is linked.  Returns a tuple of strings <code class="docutils literal notranslate"><span class="pre">(lib,</span>
<span class="pre">version)</span></code> which default to the given parameters in case the lookup fails.</p>
<p>Note that this function has intimate knowledge of how different libc versions
add symbols to the executable is probably only usable for executables compiled
using <strong class="program">gcc</strong>.</p>
<p>The file is read and scanned in chunks of <em>chunksize</em> bytes.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a><ul>
<li><a class="reference internal" href="#cross-platform">15.15.1. Cross Platform</a></li>
<li><a class="reference internal" href="#java-platform">15.15.2. Java Platform</a></li>
<li><a class="reference internal" href="#windows-platform">15.15.3. Windows Platform</a><ul>
<li><a class="reference internal" href="#win95-98-specific">15.15.3.1. Win95/98 specific</a></li>
</ul>
</li>
<li><a class="reference internal" href="#mac-os-platform">15.15.4. Mac OS Platform</a></li>
<li><a class="reference internal" href="#unix-platforms">15.15.5. Unix Platforms</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="curses.panel.html"
                        title="previous chapter">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="errno.html"
                        title="next chapter">15.16. <code class="docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/platform.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errno.html" title="15.16. errno — Standard errno system symbols"
             >next</a> |</li>
        <li class="right" >
          <a href="curses.panel.html" title="15.14. curses.panel — A panel stack extension for curses"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\;3�"�G�Ghtml/library/plistlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.6. plistlib — Generate and parse Mac OS X .plist files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14. Cryptographic Services" href="crypto.html" />
    <link rel="prev" title="13.5. xdrlib — Encode and decode XDR data" href="xdrlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/plistlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="crypto.html" title="14. Cryptographic Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xdrlib.html" title="13.5. xdrlib — Encode and decode XDR data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-plistlib">
<span id="plistlib-generate-and-parse-mac-os-x-plist-files"></span><h1>13.6. <a class="reference internal" href="#module-plistlib" title="plistlib: Generate and parse Mac OS X plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files<a class="headerlink" href="#module-plistlib" title="Permalink to this headline">¶</a></h1>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>This module was previously only available in the Mac-specific library, it is
now available for all platforms.</p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/plistlib.py">Lib/plistlib.py</a></p>
<hr class="docutils" />
<p>This module provides an interface for reading and writing the “property list”
XML files used mainly by Mac OS X.</p>
<p>The property list (<code class="docutils literal notranslate"><span class="pre">.plist</span></code>) file format is a simple XML pickle supporting
basic object types, like dictionaries, lists, numbers and strings.  Usually the
top level object is a dictionary.</p>
<p>Values can be strings, integers, floats, booleans, tuples, lists, dictionaries
(but only with string keys), <a class="reference internal" href="#plistlib.Data" title="plistlib.Data"><code class="xref py py-class docutils literal notranslate"><span class="pre">Data</span></code></a> or <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a>
objects.  String values (including dictionary keys) may be unicode strings –
they will be written out as UTF-8.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">&lt;data&gt;</span></code> plist type is supported through the <a class="reference internal" href="#plistlib.Data" title="plistlib.Data"><code class="xref py py-class docutils literal notranslate"><span class="pre">Data</span></code></a> class.  This is
a thin wrapper around a Python string.  Use <a class="reference internal" href="#plistlib.Data" title="plistlib.Data"><code class="xref py py-class docutils literal notranslate"><span class="pre">Data</span></code></a> if your strings
contain control characters.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man5/plist.5.html">PList manual page</a></dt>
<dd>Apple’s documentation of the file format.</dd>
</dl>
</div>
<p>This module defines the following functions:</p>
<dl class="function">
<dt id="plistlib.readPlist">
<code class="descclassname">plistlib.</code><code class="descname">readPlist</code><span class="sig-paren">(</span><em>pathOrFile</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.readPlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a plist file. <em>pathOrFile</em> may either be a file name or a (readable)
file object.  Return the unpacked root object (which usually is a
dictionary).</p>
<p>The XML data is parsed using the Expat parser from <a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a>
– see its documentation for possible exceptions on ill-formed XML.
Unknown elements will simply be ignored by the plist parser.</p>
</dd></dl>

<dl class="function">
<dt id="plistlib.writePlist">
<code class="descclassname">plistlib.</code><code class="descname">writePlist</code><span class="sig-paren">(</span><em>rootObject</em>, <em>pathOrFile</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.writePlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Write <em>rootObject</em> to a plist file. <em>pathOrFile</em> may either be a file name
or a (writable) file object.</p>
<p>A <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised if the object is of an unsupported type or
a container that contains objects of unsupported types.</p>
</dd></dl>

<dl class="function">
<dt id="plistlib.readPlistFromString">
<code class="descclassname">plistlib.</code><code class="descname">readPlistFromString</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.readPlistFromString" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a plist from a string.  Return the root object.</p>
</dd></dl>

<dl class="function">
<dt id="plistlib.writePlistToString">
<code class="descclassname">plistlib.</code><code class="descname">writePlistToString</code><span class="sig-paren">(</span><em>rootObject</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.writePlistToString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <em>rootObject</em> as a plist-formatted string.</p>
</dd></dl>

<dl class="function">
<dt id="plistlib.readPlistFromResource">
<code class="descclassname">plistlib.</code><code class="descname">readPlistFromResource</code><span class="sig-paren">(</span><em>path</em>, <em>restype='plst'</em>, <em>resid=0</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.readPlistFromResource" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a plist from the resource with type <em>restype</em> from the resource fork of
<em>path</em>.  Availability: Mac OS X.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3.x, this function has been removed.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="plistlib.writePlistToResource">
<code class="descclassname">plistlib.</code><code class="descname">writePlistToResource</code><span class="sig-paren">(</span><em>rootObject</em>, <em>path</em>, <em>restype='plst'</em>, <em>resid=0</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.writePlistToResource" title="Permalink to this definition">¶</a></dt>
<dd><p>Write <em>rootObject</em> as a resource with type <em>restype</em> to the resource fork of
<em>path</em>.  Availability: Mac OS X.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3.x, this function has been removed.</p>
</div>
</dd></dl>

<p>The following class is available:</p>
<dl class="class">
<dt id="plistlib.Data">
<em class="property">class </em><code class="descclassname">plistlib.</code><code class="descname">Data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#plistlib.Data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a “data” wrapper object around the string <em>data</em>.  This is used in
functions converting from/to plists to represent the <code class="docutils literal notranslate"><span class="pre">&lt;data&gt;</span></code> type
available in plists.</p>
<p>It has one attribute, <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code>, that can be used to retrieve the Python
string stored in it.</p>
</dd></dl>

<div class="section" id="examples">
<h2>13.6.1. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Generating a plist:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pl</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span>
    <span class="n">aString</span><span class="o">=</span><span class="s2">&quot;Doodah&quot;</span><span class="p">,</span>
    <span class="n">aList</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;A&quot;</span><span class="p">,</span> <span class="s2">&quot;B&quot;</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mf">32.1</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]],</span>
    <span class="n">aFloat</span> <span class="o">=</span> <span class="mf">0.1</span><span class="p">,</span>
    <span class="n">anInt</span> <span class="o">=</span> <span class="mi">728</span><span class="p">,</span>
    <span class="n">aDict</span><span class="o">=</span><span class="nb">dict</span><span class="p">(</span>
        <span class="n">anotherString</span><span class="o">=</span><span class="s2">&quot;&lt;hello &amp; hi there!&gt;&quot;</span><span class="p">,</span>
        <span class="n">aUnicodeValue</span><span class="o">=</span><span class="sa">u</span><span class="s1">&#39;M</span><span class="se">\xe4</span><span class="s1">ssig, Ma</span><span class="se">\xdf</span><span class="s1">&#39;</span><span class="p">,</span>
        <span class="n">aTrueValue</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span>
        <span class="n">aFalseValue</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="n">someData</span> <span class="o">=</span> <span class="n">Data</span><span class="p">(</span><span class="s2">&quot;&lt;binary gunk&gt;&quot;</span><span class="p">),</span>
    <span class="n">someMoreData</span> <span class="o">=</span> <span class="n">Data</span><span class="p">(</span><span class="s2">&quot;&lt;lots of binary gunk&gt;&quot;</span> <span class="o">*</span> <span class="mi">10</span><span class="p">),</span>
    <span class="n">aDate</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">fromtimestamp</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">mktime</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">gmtime</span><span class="p">())),</span>
<span class="p">)</span>
<span class="c1"># unicode keys are possible, but a little awkward to use:</span>
<span class="n">pl</span><span class="p">[</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\xc5</span><span class="s1">benraa&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;That was a unicode key.&quot;</span>
<span class="n">writePlist</span><span class="p">(</span><span class="n">pl</span><span class="p">,</span> <span class="n">fileName</span><span class="p">)</span>
</pre></div>
</div>
<p>Parsing a plist:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pl</span> <span class="o">=</span> <span class="n">readPlist</span><span class="p">(</span><span class="n">pathOrFile</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">pl</span><span class="p">[</span><span class="s2">&quot;aKey&quot;</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a><ul>
<li><a class="reference internal" href="#examples">13.6.1. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xdrlib.html"
                        title="previous chapter">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="crypto.html"
                        title="next chapter">14. Cryptographic Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/plistlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="crypto.html" title="14. Cryptographic Services"
             >next</a> |</li>
        <li class="right" >
          <a href="xdrlib.html" title="13.5. xdrlib — Encode and decode XDR data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\B_7k�k�khtml/library/popen2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.5. popen2 — Subprocesses with accessible I/O streams &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.6. asyncore — Asynchronous socket handler" href="asyncore.html" />
    <link rel="prev" title="17.4. signal — Set handlers for asynchronous events" href="signal.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/popen2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="17.6. asyncore — Asynchronous socket handler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="signal.html" title="17.4. signal — Set handlers for asynchronous events"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-popen2">
<span id="popen2-subprocesses-with-accessible-i-o-streams"></span><h1>17.5. <a class="reference internal" href="#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> — Subprocesses with accessible I/O streams<a class="headerlink" href="#module-popen2" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>This module is obsolete.  Use the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.  Check
especially the <a class="reference internal" href="subprocess.html#subprocess-replacements"><span class="std std-ref">Replacing Older Functions with the subprocess Module</span></a> section.</p>
</div>
<p>This module allows you to spawn processes and connect to their
input/output/error pipes and obtain their return codes under Unix and Windows.</p>
<p>The <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module provides more powerful facilities for spawning new
processes and retrieving their results.  Using the <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module is
preferable to using the <a class="reference internal" href="#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module.</p>
<p>The primary interface offered by this module is a trio of factory functions.
For each of these, if <em>bufsize</em> is specified,  it specifies the buffer size for
the I/O pipes.  <em>mode</em>, if provided, should be the string <code class="docutils literal notranslate"><span class="pre">'b'</span></code> or <code class="docutils literal notranslate"><span class="pre">'t'</span></code>; on
Windows this is needed to determine whether the file objects should be opened in
binary or text mode.  The default value for <em>mode</em> is <code class="docutils literal notranslate"><span class="pre">'t'</span></code>.</p>
<p>On Unix, <em>cmd</em> may be a sequence, in which case arguments will be passed
directly to the program without shell intervention (as with <a class="reference internal" href="os.html#os.spawnv" title="os.spawnv"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.spawnv()</span></code></a>).
If <em>cmd</em> is a string it will be passed to the shell (as with <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>).</p>
<p>The only way to retrieve the return codes for the child processes is by using
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">poll()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> methods on the <a class="reference internal" href="#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen3</span></code></a> and
<a class="reference internal" href="#popen2.Popen4" title="popen2.Popen4"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen4</span></code></a> classes; these are only available on Unix.  This information is
not available when using the <a class="reference internal" href="#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen2()</span></code></a>, <a class="reference internal" href="#popen2.popen3" title="popen2.popen3"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen3()</span></code></a>, and <a class="reference internal" href="#popen2.popen4" title="popen2.popen4"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen4()</span></code></a>
functions, or the equivalent functions in the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module. (Note that the
tuples returned by the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module’s functions are in a different order
from the ones returned by the <a class="reference internal" href="#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module.)</p>
<dl class="function">
<dt id="popen2.popen2">
<code class="descclassname">popen2.</code><code class="descname">popen2</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.popen2" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes <em>cmd</em> as a sub-process.  Returns the file objects <code class="docutils literal notranslate"><span class="pre">(child_stdout,</span>
<span class="pre">child_stdin)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="popen2.popen3">
<code class="descclassname">popen2.</code><code class="descname">popen3</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.popen3" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes <em>cmd</em> as a sub-process.  Returns the file objects <code class="docutils literal notranslate"><span class="pre">(child_stdout,</span>
<span class="pre">child_stdin,</span> <span class="pre">child_stderr)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="popen2.popen4">
<code class="descclassname">popen2.</code><code class="descname">popen4</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.popen4" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes <em>cmd</em> as a sub-process.  Returns the file objects
<code class="docutils literal notranslate"><span class="pre">(child_stdout_and_stderr,</span> <span class="pre">child_stdin)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<p>On Unix, a class defining the objects returned by the factory functions is also
available.  These are not used for the Windows implementation, and are not
available on that platform.</p>
<dl class="class">
<dt id="popen2.Popen3">
<em class="property">class </em><code class="descclassname">popen2.</code><code class="descname">Popen3</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>capturestderr</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.Popen3" title="Permalink to this definition">¶</a></dt>
<dd><p>This class represents a child process.  Normally, <a class="reference internal" href="#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen3</span></code></a> instances are
created using the <a class="reference internal" href="#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen2()</span></code></a> and <a class="reference internal" href="#popen2.popen3" title="popen2.popen3"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen3()</span></code></a> factory functions described
above.</p>
<p>If not using one of the helper functions to create <a class="reference internal" href="#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen3</span></code></a> objects, the
parameter <em>cmd</em> is the shell command to execute in a sub-process.  The
<em>capturestderr</em> flag, if true, specifies that the object should capture standard
error output of the child process. The default is false.  If the <em>bufsize</em>
parameter is specified, it specifies the size of the I/O buffers to/from the
child process.</p>
</dd></dl>

<dl class="class">
<dt id="popen2.Popen4">
<em class="property">class </em><code class="descclassname">popen2.</code><code class="descname">Popen4</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.Popen4" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen3</span></code></a>, but always captures standard error into the same
file object as standard output.  These are typically created using
<a class="reference internal" href="#popen2.popen4" title="popen2.popen4"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen4()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<div class="section" id="popen3-and-popen4-objects">
<span id="popen3-objects"></span><h2>17.5.1. Popen3 and Popen4 Objects<a class="headerlink" href="#popen3-and-popen4-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of the <a class="reference internal" href="#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen3</span></code></a> and <a class="reference internal" href="#popen2.Popen4" title="popen2.Popen4"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen4</span></code></a> classes have the following
methods:</p>
<dl class="method">
<dt id="popen2.Popen3.poll">
<code class="descclassname">Popen3.</code><code class="descname">poll</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.Popen3.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">-1</span></code> if child process hasn’t completed yet, or its status code
(see <a class="reference internal" href="#popen2.Popen3.wait" title="popen2.Popen3.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>) otherwise.</p>
</dd></dl>

<dl class="method">
<dt id="popen2.Popen3.wait">
<code class="descclassname">Popen3.</code><code class="descname">wait</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#popen2.Popen3.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Waits for and returns the status code of the child process.  The status code
encodes both the return code of the process and information about whether it
exited using the <code class="xref c c-func docutils literal notranslate"><span class="pre">exit()</span></code> system call or died due to a signal.  Functions
to help interpret the status code are defined in the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module; see
section <a class="reference internal" href="os.html#os-process"><span class="std std-ref">Process Management</span></a> for the <code class="xref py py-func docutils literal notranslate"><span class="pre">W*()</span></code> family of functions.</p>
</dd></dl>

<p>The following attributes are also available:</p>
<dl class="attribute">
<dt id="popen2.Popen3.fromchild">
<code class="descclassname">Popen3.</code><code class="descname">fromchild</code><a class="headerlink" href="#popen2.Popen3.fromchild" title="Permalink to this definition">¶</a></dt>
<dd><p>A file object that provides output from the child process.  For <a class="reference internal" href="#popen2.Popen4" title="popen2.Popen4"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen4</span></code></a>
instances, this will provide both the standard output and standard error
streams.</p>
</dd></dl>

<dl class="attribute">
<dt id="popen2.Popen3.tochild">
<code class="descclassname">Popen3.</code><code class="descname">tochild</code><a class="headerlink" href="#popen2.Popen3.tochild" title="Permalink to this definition">¶</a></dt>
<dd><p>A file object that provides input to the child process.</p>
</dd></dl>

<dl class="attribute">
<dt id="popen2.Popen3.childerr">
<code class="descclassname">Popen3.</code><code class="descname">childerr</code><a class="headerlink" href="#popen2.Popen3.childerr" title="Permalink to this definition">¶</a></dt>
<dd><p>A file object that provides error output from the child process, if
<em>capturestderr</em> was true for the constructor, otherwise <code class="docutils literal notranslate"><span class="pre">None</span></code>.  This will
always be <code class="docutils literal notranslate"><span class="pre">None</span></code> for <a class="reference internal" href="#popen2.Popen4" title="popen2.Popen4"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen4</span></code></a> instances.</p>
</dd></dl>

<dl class="attribute">
<dt id="popen2.Popen3.pid">
<code class="descclassname">Popen3.</code><code class="descname">pid</code><a class="headerlink" href="#popen2.Popen3.pid" title="Permalink to this definition">¶</a></dt>
<dd><p>The process ID of the child process.</p>
</dd></dl>

</div>
<div class="section" id="flow-control-issues">
<span id="popen2-flow-control"></span><h2>17.5.2. Flow Control Issues<a class="headerlink" href="#flow-control-issues" title="Permalink to this headline">¶</a></h2>
<p>Any time you are working with any form of inter-process communication, control
flow needs to be carefully thought out.  This remains the case with the file
objects provided by this module (or the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module equivalents).</p>
<p>When reading output from a child process that writes a lot of data to standard
error while the parent is reading from the child’s standard output, a deadlock
can occur.  A similar situation can occur with other combinations of reads and
writes.  The essential factors are that more than <code class="xref py py-const docutils literal notranslate"><span class="pre">_PC_PIPE_BUF</span></code> bytes
are being written by one process in a blocking fashion, while the other process
is reading from the first process, also in a blocking fashion.</p>
<p>There are several ways to deal with this situation.</p>
<p>The simplest application change, in many cases, will be to follow this model in
the parent process:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">popen2</span>

<span class="n">r</span><span class="p">,</span> <span class="n">w</span><span class="p">,</span> <span class="n">e</span> <span class="o">=</span> <span class="n">popen2</span><span class="o">.</span><span class="n">popen3</span><span class="p">(</span><span class="s1">&#39;python slave.py&#39;</span><span class="p">)</span>
<span class="n">e</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>
<span class="n">r</span><span class="o">.</span><span class="n">readlines</span><span class="p">()</span>
<span class="n">r</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">e</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">w</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>with code like this in the child:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="c1"># note that each of these print statements</span>
<span class="c1"># writes a single long string</span>

<span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">,</span> <span class="mi">400</span> <span class="o">*</span> <span class="s1">&#39;this is a test</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="n">os</span><span class="o">.</span><span class="n">close</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">fileno</span><span class="p">())</span>
<span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="mi">400</span> <span class="o">*</span> <span class="s1">&#39;this is another test</span><span class="se">\n</span><span class="s1">&#39;</span>
</pre></div>
</div>
<p>In particular, note that <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> must be closed after writing all data,
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code> won’t return.  Also note that <a class="reference internal" href="os.html#os.close" title="os.close"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.close()</span></code></a> must be
used, as <code class="docutils literal notranslate"><span class="pre">sys.stderr.close()</span></code> won’t close <code class="docutils literal notranslate"><span class="pre">stderr</span></code> (otherwise assigning to
<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> will silently close it, so no further errors can be printed).</p>
<p>Applications which need to support a more general approach should integrate I/O
over pipes with their <a class="reference internal" href="select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> loops, or use separate threads to read each
of the individual files provided by whichever <code class="xref py py-func docutils literal notranslate"><span class="pre">popen*()</span></code> function or
<code class="xref py py-class docutils literal notranslate"><span class="pre">Popen*</span></code> class was used.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a></dt>
<dd>Module for spawning and managing subprocesses.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a><ul>
<li><a class="reference internal" href="#popen3-and-popen4-objects">17.5.1. Popen3 and Popen4 Objects</a></li>
<li><a class="reference internal" href="#flow-control-issues">17.5.2. Flow Control Issues</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="signal.html"
                        title="previous chapter">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="asyncore.html"
                        title="next chapter">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/popen2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncore.html" title="17.6. asyncore — Asynchronous socket handler"
             >next</a> |</li>
        <li class="right" >
          <a href="signal.html" title="17.4. signal — Set handlers for asynchronous events"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�ar�__html/library/poplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.9. poplib — POP3 protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.10. imaplib — IMAP4 protocol client" href="imaplib.html" />
    <link rel="prev" title="20.8. ftplib — FTP protocol client" href="ftplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/poplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imaplib.html" title="20.10. imaplib — IMAP4 protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ftplib.html" title="20.8. ftplib — FTP protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-poplib">
<span id="poplib-pop3-protocol-client"></span><h1>20.9. <a class="reference internal" href="#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> — POP3 protocol client<a class="headerlink" href="#module-poplib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/poplib.py">Lib/poplib.py</a></p>
<hr class="docutils" />
<p>This module defines a class, <a class="reference internal" href="#poplib.POP3" title="poplib.POP3"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3</span></code></a>, which encapsulates a connection to a
POP3 server and implements the protocol as defined in <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1725.html"><strong>RFC 1725</strong></a>.  The
<a class="reference internal" href="#poplib.POP3" title="poplib.POP3"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3</span></code></a> class supports both the minimal and optional command sets.
Additionally, this module provides a class <a class="reference internal" href="#poplib.POP3_SSL" title="poplib.POP3_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3_SSL</span></code></a>, which provides
support for connecting to POP3 servers that use SSL as an underlying protocol
layer.</p>
<p>Note that POP3, though widely supported, is obsolescent.  The implementation
quality of POP3 servers varies widely, and too many are quite poor. If your
mailserver supports IMAP, you would be better off using the
<a class="reference internal" href="imaplib.html#imaplib.IMAP4" title="imaplib.IMAP4"><code class="xref py py-class docutils literal notranslate"><span class="pre">imaplib.IMAP4</span></code></a> class, as IMAP servers tend to be better implemented.</p>
<p>The <a class="reference internal" href="#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> module provides two classes:</p>
<dl class="class">
<dt id="poplib.POP3">
<em class="property">class </em><code class="descclassname">poplib.</code><code class="descname">POP3</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements the actual POP3 protocol.  The connection is created when
the instance is initialized. If <em>port</em> is omitted, the standard POP3 port (110)
is used. The optional <em>timeout</em> parameter specifies a timeout in seconds for the
connection attempt (if not specified, the global default timeout setting will
be used).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="poplib.POP3_SSL">
<em class="property">class </em><code class="descclassname">poplib.</code><code class="descname">POP3_SSL</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>keyfile</em><span class="optional">[</span>, <em>certfile</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3_SSL" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a subclass of <a class="reference internal" href="#poplib.POP3" title="poplib.POP3"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3</span></code></a> that connects to the server over an SSL
encrypted socket.  If <em>port</em> is not specified, 995, the standard POP3-over-SSL
port is used.  <em>keyfile</em> and <em>certfile</em> are also optional - they can contain a
PEM formatted private key and certificate chain file for the SSL connection.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>One exception is defined as an attribute of the <a class="reference internal" href="#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> module:</p>
<dl class="exception">
<dt id="poplib.error_proto">
<em class="property">exception </em><code class="descclassname">poplib.</code><code class="descname">error_proto</code><a class="headerlink" href="#poplib.error_proto" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on any errors from this module (errors from <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a>
module are not caught). The reason for the exception is passed to the
constructor as a string.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a></dt>
<dd>The standard Python IMAP module.</dd>
<dt><a class="reference external" href="http://www.catb.org/~esr/fetchmail/fetchmail-FAQ.html">Frequently Asked Questions About Fetchmail</a></dt>
<dd>The FAQ for the <strong class="program">fetchmail</strong> POP/IMAP client collects information on
POP3 server variations and RFC noncompliance that may be useful if you need to
write an application based on the POP protocol.</dd>
</dl>
</div>
<div class="section" id="pop3-objects">
<span id="id1"></span><h2>20.9.1. POP3 Objects<a class="headerlink" href="#pop3-objects" title="Permalink to this headline">¶</a></h2>
<p>All POP3 commands are represented by methods of the same name, in lower-case;
most return the response text sent by the server.</p>
<p>An <a class="reference internal" href="#poplib.POP3" title="poplib.POP3"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="poplib.POP3.set_debuglevel">
<code class="descclassname">POP3.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the instance’s debugging level.  This controls the amount of debugging
output printed.  The default, <code class="docutils literal notranslate"><span class="pre">0</span></code>, produces no debugging output.  A value of
<code class="docutils literal notranslate"><span class="pre">1</span></code> produces a moderate amount of debugging output, generally a single line
per request.  A value of <code class="docutils literal notranslate"><span class="pre">2</span></code> or higher produces the maximum amount of
debugging output, logging each line sent and received on the control connection.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.getwelcome">
<code class="descclassname">POP3.</code><code class="descname">getwelcome</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.getwelcome" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the greeting string sent by the POP3 server.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.user">
<code class="descclassname">POP3.</code><code class="descname">user</code><span class="sig-paren">(</span><em>username</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.user" title="Permalink to this definition">¶</a></dt>
<dd><p>Send user command, response should indicate that a password is required.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.pass_">
<code class="descclassname">POP3.</code><code class="descname">pass_</code><span class="sig-paren">(</span><em>password</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.pass_" title="Permalink to this definition">¶</a></dt>
<dd><p>Send password, response includes message count and mailbox size. Note: the
mailbox on the server is locked until <code class="xref py py-meth docutils literal notranslate"><span class="pre">quit()</span></code> is called.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.apop">
<code class="descclassname">POP3.</code><code class="descname">apop</code><span class="sig-paren">(</span><em>user</em>, <em>secret</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.apop" title="Permalink to this definition">¶</a></dt>
<dd><p>Use the more secure APOP authentication to log into the POP3 server.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.rpop">
<code class="descclassname">POP3.</code><code class="descname">rpop</code><span class="sig-paren">(</span><em>user</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.rpop" title="Permalink to this definition">¶</a></dt>
<dd><p>Use RPOP authentication (similar to UNIX r-commands) to log into POP3 server.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.stat">
<code class="descclassname">POP3.</code><code class="descname">stat</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.stat" title="Permalink to this definition">¶</a></dt>
<dd><p>Get mailbox status.  The result is a tuple of 2 integers: <code class="docutils literal notranslate"><span class="pre">(message</span> <span class="pre">count,</span>
<span class="pre">mailbox</span> <span class="pre">size)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.list">
<code class="descclassname">POP3.</code><code class="descname">list</code><span class="sig-paren">(</span><span class="optional">[</span><em>which</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.list" title="Permalink to this definition">¶</a></dt>
<dd><p>Request message list, result is in the form <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">['mesg_num</span> <span class="pre">octets',</span>
<span class="pre">...],</span> <span class="pre">octets)</span></code>. If <em>which</em> is set, it is the message to list.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.retr">
<code class="descclassname">POP3.</code><code class="descname">retr</code><span class="sig-paren">(</span><em>which</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.retr" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve whole message number <em>which</em>, and set its seen flag. Result is in form
<code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">['line',</span> <span class="pre">...],</span> <span class="pre">octets)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.dele">
<code class="descclassname">POP3.</code><code class="descname">dele</code><span class="sig-paren">(</span><em>which</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.dele" title="Permalink to this definition">¶</a></dt>
<dd><p>Flag message number <em>which</em> for deletion.  On most servers deletions are not
actually performed until QUIT (the major exception is Eudora QPOP, which
deliberately violates the RFCs by doing pending deletes on any disconnect).</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.rset">
<code class="descclassname">POP3.</code><code class="descname">rset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.rset" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove any deletion marks for the mailbox.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.noop">
<code class="descclassname">POP3.</code><code class="descname">noop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.noop" title="Permalink to this definition">¶</a></dt>
<dd><p>Do nothing.  Might be used as a keep-alive.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.quit">
<code class="descclassname">POP3.</code><code class="descname">quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Signoff:  commit changes, unlock mailbox, drop connection.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.top">
<code class="descclassname">POP3.</code><code class="descname">top</code><span class="sig-paren">(</span><em>which</em>, <em>howmuch</em><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.top" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieves the message header plus <em>howmuch</em> lines of the message after the
header of message number <em>which</em>. Result is in form <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">['line',</span> <span class="pre">...],</span>
<span class="pre">octets)</span></code>.</p>
<p>The POP3 TOP command this method uses, unlike the RETR command, doesn’t set the
message’s seen flag; unfortunately, TOP is poorly specified in the RFCs and is
frequently broken in off-brand servers. Test this method by hand against the
POP3 servers you will use before trusting it.</p>
</dd></dl>

<dl class="method">
<dt id="poplib.POP3.uidl">
<code class="descclassname">POP3.</code><code class="descname">uidl</code><span class="sig-paren">(</span><span class="optional">[</span><em>which</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#poplib.POP3.uidl" title="Permalink to this definition">¶</a></dt>
<dd><p>Return message digest (unique id) list. If <em>which</em> is specified, result contains
the unique id for that message in the form <code class="docutils literal notranslate"><span class="pre">'response</span> <span class="pre">mesgnum</span> <span class="pre">uid</span></code>, otherwise
result is list <code class="docutils literal notranslate"><span class="pre">(response,</span> <span class="pre">['mesgnum</span> <span class="pre">uid',</span> <span class="pre">...],</span> <span class="pre">octets)</span></code>.</p>
</dd></dl>

<p>Instances of <a class="reference internal" href="#poplib.POP3_SSL" title="poplib.POP3_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">POP3_SSL</span></code></a> have no additional methods. The interface of this
subclass is identical to its parent.</p>
</div>
<div class="section" id="pop3-example">
<span id="id2"></span><h2>20.9.2. POP3 Example<a class="headerlink" href="#pop3-example" title="Permalink to this headline">¶</a></h2>
<p>Here is a minimal example (without error checking) that opens a mailbox and
retrieves and prints all messages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">getpass</span><span class="o">,</span> <span class="nn">poplib</span>

<span class="n">M</span> <span class="o">=</span> <span class="n">poplib</span><span class="o">.</span><span class="n">POP3</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="n">M</span><span class="o">.</span><span class="n">user</span><span class="p">(</span><span class="n">getpass</span><span class="o">.</span><span class="n">getuser</span><span class="p">())</span>
<span class="n">M</span><span class="o">.</span><span class="n">pass_</span><span class="p">(</span><span class="n">getpass</span><span class="o">.</span><span class="n">getpass</span><span class="p">())</span>
<span class="n">numMessages</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">M</span><span class="o">.</span><span class="n">list</span><span class="p">()[</span><span class="mi">1</span><span class="p">])</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">numMessages</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">j</span> <span class="ow">in</span> <span class="n">M</span><span class="o">.</span><span class="n">retr</span><span class="p">(</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">)[</span><span class="mi">1</span><span class="p">]:</span>
        <span class="nb">print</span> <span class="n">j</span>
</pre></div>
</div>
<p>At the end of the module, there is a test section that contains a more extensive
example of usage.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a><ul>
<li><a class="reference internal" href="#pop3-objects">20.9.1. POP3 Objects</a></li>
<li><a class="reference internal" href="#pop3-example">20.9.2. POP3 Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="ftplib.html"
                        title="previous chapter">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="imaplib.html"
                        title="next chapter">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/poplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="imaplib.html" title="20.10. imaplib — IMAP4 protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="ftplib.html" title="20.8. ftplib — FTP protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���@�@html/library/posix.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.1. posix — The most common POSIX system calls &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.2. pwd — The password database" href="pwd.html" />
    <link rel="prev" title="36. Unix Specific Services" href="unix.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/posix.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pwd.html" title="36.2. pwd — The password database"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unix.html" title="36. Unix Specific Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-posix">
<span id="posix-the-most-common-posix-system-calls"></span><h1>36.1. <a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> — The most common POSIX system calls<a class="headerlink" href="#module-posix" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to operating system functionality that is
standardized by the C Standard and the POSIX standard (a thinly disguised Unix
interface).</p>
<p id="index-0"><strong>Do not import this module directly.</strong>  Instead, import the module <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>,
which provides a <em>portable</em> version of this interface.  On Unix, the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>
module provides a superset of the <a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> interface.  On non-Unix operating
systems the <a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> module is not available, but a subset is always
available through the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> interface.  Once <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> is imported, there is
<em>no</em> performance penalty in using it instead of <a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a>.  In addition,
<a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> provides some additional functionality, such as automatically calling
<a class="reference internal" href="os.html#os.putenv" title="os.putenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">putenv()</span></code></a> when an entry in <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> is changed.</p>
<p>Errors are reported as exceptions; the usual exceptions are given for type
errors, while errors reported by the system calls raise <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>.</p>
<div class="section" id="large-file-support">
<span id="posix-large-files"></span><h2>36.1.1. Large File Support<a class="headerlink" href="#large-file-support" title="Permalink to this headline">¶</a></h2>
<p id="index-1">Several operating systems (including AIX, HP-UX, Irix and Solaris) provide
support for files that are larger than 2 GB from a C programming model where
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> and <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> are 32-bit values. This is typically accomplished
by defining the relevant size and offset types as 64-bit values. Such files are
sometimes referred to as <em class="dfn">large files</em>.</p>
<p>Large file support is enabled in Python when the size of an <code class="xref c c-type docutils literal notranslate"><span class="pre">off_t</span></code> is
larger than a <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> and the <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> type is available and is
at least as large as an <code class="xref c c-type docutils literal notranslate"><span class="pre">off_t</span></code>. Python longs are then used to represent
file sizes, offsets and other values that can exceed the range of a Python int.
It may be necessary to configure and compile Python with certain compiler flags
to enable this mode. For example, it is enabled by default with recent versions
of Irix, but with Solaris 2.6 and 2.7 you need to do something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CFLAGS</span><span class="o">=</span><span class="s2">&quot;`getconf LFS_CFLAGS`&quot;</span> <span class="n">OPT</span><span class="o">=</span><span class="s2">&quot;-g -O2 $CFLAGS&quot;</span> \
        <span class="o">./</span><span class="n">configure</span>
</pre></div>
</div>
<p>On large-file-capable Linux systems, this might work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">CFLAGS</span><span class="o">=</span><span class="s1">&#39;-D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64&#39;</span> <span class="n">OPT</span><span class="o">=</span><span class="s2">&quot;-g -O2 $CFLAGS&quot;</span> \
        <span class="o">./</span><span class="n">configure</span>
</pre></div>
</div>
</div>
<div class="section" id="notable-module-contents">
<span id="posix-contents"></span><h2>36.1.2. Notable Module Contents<a class="headerlink" href="#notable-module-contents" title="Permalink to this headline">¶</a></h2>
<p>In addition to many functions described in the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module documentation,
<a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> defines the following data item:</p>
<dl class="data">
<dt id="posix.environ">
<code class="descclassname">posix.</code><code class="descname">environ</code><a class="headerlink" href="#posix.environ" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary representing the string environment at the time the interpreter
was started.  For example, <code class="docutils literal notranslate"><span class="pre">environ['HOME']</span></code> is the pathname of your home
directory, equivalent to <code class="docutils literal notranslate"><span class="pre">getenv(&quot;HOME&quot;)</span></code> in C.</p>
<p>Modifying this dictionary does not affect the string environment passed on by
<a class="reference internal" href="os.html#os.execv" title="os.execv"><code class="xref py py-func docutils literal notranslate"><span class="pre">execv()</span></code></a>, <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a> or <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">system()</span></code></a>; if you need to
change the environment, pass <code class="docutils literal notranslate"><span class="pre">environ</span></code> to <a class="reference internal" href="os.html#os.execve" title="os.execve"><code class="xref py py-func docutils literal notranslate"><span class="pre">execve()</span></code></a> or add
variable assignments and export statements to the command string for
<a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">system()</span></code></a> or <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">popen()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module provides an alternate implementation of <code class="docutils literal notranslate"><span class="pre">environ</span></code> which
updates the environment on modification.  Note also that updating <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>
will render this dictionary obsolete.  Use of the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module version of
this is recommended over direct access to the <a class="reference internal" href="#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> module.</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a><ul>
<li><a class="reference internal" href="#large-file-support">36.1.1. Large File Support</a></li>
<li><a class="reference internal" href="#notable-module-contents">36.1.2. Notable Module Contents</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="unix.html"
                        title="previous chapter">36. Unix Specific Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pwd.html"
                        title="next chapter">36.2. <code class="docutils literal notranslate"><span class="pre">pwd</span></code> — The password database</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/posix.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pwd.html" title="36.2. pwd — The password database"
             >next</a> |</li>
        <li class="right" >
          <a href="unix.html" title="36. Unix Specific Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�� 2�S�Shtml/library/posixfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.12. posixfile — File-like objects with locking support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.13. resource — Resource usage information" href="resource.html" />
    <link rel="prev" title="36.11. pipes — Interface to shell pipelines" href="pipes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/posixfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="resource.html" title="36.13. resource — Resource usage information"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pipes.html" title="36.11. pipes — Interface to shell pipelines"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-posixfile">
<span id="posixfile-file-like-objects-with-locking-support"></span><h1>36.12. <a class="reference internal" href="#module-posixfile" title="posixfile: A file-like object with support for locking. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code></a> — File-like objects with locking support<a class="headerlink" href="#module-posixfile" title="Permalink to this headline">¶</a></h1>
<div class="deprecated" id="index-0">
<p><span class="versionmodified">Deprecated since version 1.5: </span>The locking operation that this module provides is done better and more portably
by the <a class="reference internal" href="fcntl.html#fcntl.lockf" title="fcntl.lockf"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.lockf()</span></code></a> call.</p>
</div>
<p id="index-1">This module implements some additional functionality over the built-in file
objects.  In particular, it implements file locking, control over the file
flags, and an easy interface to duplicate the file object. The module defines a
new file object, the posixfile object.  It has all the standard file object
methods and adds the methods described below.  This module only works for
certain flavors of Unix, since it uses <a class="reference internal" href="fcntl.html#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.fcntl()</span></code></a> for file locking.</p>
<p>To instantiate a posixfile object, use the <a class="reference internal" href="#posixfile.open" title="posixfile.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">posixfile.open()</span></code></a> function.  The
resulting object looks and feels roughly the same as a standard file object.</p>
<p>The <a class="reference internal" href="#module-posixfile" title="posixfile: A file-like object with support for locking. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code></a> module defines the following constants:</p>
<dl class="data">
<dt id="posixfile.SEEK_SET">
<code class="descclassname">posixfile.</code><code class="descname">SEEK_SET</code><a class="headerlink" href="#posixfile.SEEK_SET" title="Permalink to this definition">¶</a></dt>
<dd><p>Offset is calculated from the start of the file.</p>
</dd></dl>

<dl class="data">
<dt id="posixfile.SEEK_CUR">
<code class="descclassname">posixfile.</code><code class="descname">SEEK_CUR</code><a class="headerlink" href="#posixfile.SEEK_CUR" title="Permalink to this definition">¶</a></dt>
<dd><p>Offset is calculated from the current position in the file.</p>
</dd></dl>

<dl class="data">
<dt id="posixfile.SEEK_END">
<code class="descclassname">posixfile.</code><code class="descname">SEEK_END</code><a class="headerlink" href="#posixfile.SEEK_END" title="Permalink to this definition">¶</a></dt>
<dd><p>Offset is calculated from the end of the file.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-posixfile" title="posixfile: A file-like object with support for locking. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="posixfile.open">
<code class="descclassname">posixfile.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new posixfile object with the given filename and mode.  The <em>filename</em>,
<em>mode</em> and <em>bufsize</em> arguments are interpreted the same way as by the built-in
<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="posixfile.fileopen">
<code class="descclassname">posixfile.</code><code class="descname">fileopen</code><span class="sig-paren">(</span><em>fileobject</em><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.fileopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new posixfile object with the given standard file object. The resulting
object has the same filename and mode as the original file object.</p>
</dd></dl>

<p>The posixfile object defines the following additional methods:</p>
<dl class="method">
<dt id="posixfile.posixfile.lock">
<code class="descclassname">posixfile.</code><code class="descname">lock</code><span class="sig-paren">(</span><em>fmt</em><span class="optional">[</span>, <em>len</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.posixfile.lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Lock the specified section of the file that the file object is referring to.
The format is explained below in a table.  The <em>len</em> argument specifies the
length of the section that should be locked. The default is <code class="docutils literal notranslate"><span class="pre">0</span></code>. <em>start</em>
specifies the starting offset of the section, where the default is <code class="docutils literal notranslate"><span class="pre">0</span></code>.  The
<em>whence</em> argument specifies where the offset is relative to. It accepts one of
the constants <a class="reference internal" href="#posixfile.SEEK_SET" title="posixfile.SEEK_SET"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_SET</span></code></a>, <a class="reference internal" href="#posixfile.SEEK_CUR" title="posixfile.SEEK_CUR"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_CUR</span></code></a> or <a class="reference internal" href="#posixfile.SEEK_END" title="posixfile.SEEK_END"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_END</span></code></a>.  The
default is <a class="reference internal" href="#posixfile.SEEK_SET" title="posixfile.SEEK_SET"><code class="xref py py-const docutils literal notranslate"><span class="pre">SEEK_SET</span></code></a>.  For more information about the arguments refer to
the <em class="manpage">fcntl(2)</em> manual page on your system.</p>
</dd></dl>

<dl class="method">
<dt id="posixfile.posixfile.flags">
<code class="descclassname">posixfile.</code><code class="descname">flags</code><span class="sig-paren">(</span><span class="optional">[</span><em>flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.posixfile.flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the specified flags for the file that the file object is referring to.  The
new flags are ORed with the old flags, unless specified otherwise.  The format
is explained below in a table.  Without the <em>flags</em> argument a string indicating
the current flags is returned (this is the same as the <code class="docutils literal notranslate"><span class="pre">?</span></code> modifier).  For
more information about the flags refer to the <em class="manpage">fcntl(2)</em> manual page on
your system.</p>
</dd></dl>

<dl class="method">
<dt id="posixfile.posixfile.dup">
<code class="descclassname">posixfile.</code><code class="descname">dup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.posixfile.dup" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicate the file object and the underlying file pointer and file descriptor.
The resulting object behaves as if it were newly opened.</p>
</dd></dl>

<dl class="method">
<dt id="posixfile.posixfile.dup2">
<code class="descclassname">posixfile.</code><code class="descname">dup2</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.posixfile.dup2" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicate the file object and the underlying file pointer and file descriptor.
The new object will have the given file descriptor. Otherwise the resulting
object behaves as if it were newly opened.</p>
</dd></dl>

<dl class="method">
<dt id="posixfile.posixfile.file">
<code class="descclassname">posixfile.</code><code class="descname">file</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#posixfile.posixfile.file" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the standard file object that the posixfile object is based on.  This is
sometimes necessary for functions that insist on a standard file object.</p>
</dd></dl>

<p>All methods raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> when the request fails.</p>
<p>Format characters for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code> method have the following meaning:</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">u</span></code></td>
<td>unlock the specified region</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">r</span></code></td>
<td>request a read lock for the specified section</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">w</span></code></td>
<td>request a write lock for the specified
section</td>
</tr>
</tbody>
</table>
<p>In addition the following modifiers can be added to the format:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="65%" />
<col width="14%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Modifier</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">|</span></code></td>
<td>wait until the lock has been
granted</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">?</span></code></td>
<td>return the first lock
conflicting with the requested
lock, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is
no conflict.</td>
<td>(1)</td>
</tr>
</tbody>
</table>
<p>Note:</p>
<ol class="arabic simple">
<li>The lock returned is in the format <code class="docutils literal notranslate"><span class="pre">(mode,</span> <span class="pre">len,</span> <span class="pre">start,</span> <span class="pre">whence,</span> <span class="pre">pid)</span></code> where
<em>mode</em> is a character representing the type of lock (‘r’ or ‘w’).  This modifier
prevents a request from being granted; it is for query purposes only.</li>
</ol>
<p>Format characters for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">flags()</span></code> method have the following meanings:</p>
<table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">a</span></code></td>
<td>append only flag</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">c</span></code></td>
<td>close on exec flag</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">n</span></code></td>
<td>no delay flag (also called non-blocking flag)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s</span></code></td>
<td>synchronization flag</td>
</tr>
</tbody>
</table>
<p>In addition the following modifiers can be added to the format:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="66%" />
<col width="14%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Modifier</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">!</span></code></td>
<td>turn the specified flags ‘off’,
instead of the default ‘on’</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">=</span></code></td>
<td>replace the flags, instead of
the default ‘OR’ operation</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">?</span></code></td>
<td>return a string in which the
characters represent the flags
that are set.</td>
<td>(2)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>The <code class="docutils literal notranslate"><span class="pre">!</span></code> and <code class="docutils literal notranslate"><span class="pre">=</span></code> modifiers are mutually exclusive.</li>
<li>This string represents the flags after they may have been altered by the same
call.</li>
</ol>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">posixfile</span>

<span class="n">file</span> <span class="o">=</span> <span class="n">posixfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;testfile&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">file</span><span class="o">.</span><span class="n">lock</span><span class="p">(</span><span class="s1">&#39;w|&#39;</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">file</span><span class="o">.</span><span class="n">lock</span><span class="p">(</span><span class="s1">&#39;u&#39;</span><span class="p">)</span>
<span class="n">file</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="pipes.html"
                        title="previous chapter">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="resource.html"
                        title="next chapter">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/posixfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="resource.html" title="36.13. resource — Resource usage information"
             >next</a> |</li>
        <li class="right" >
          <a href="pipes.html" title="36.11. pipes — Interface to shell pipelines"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�2c�}�}html/library/pprint.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.18. pprint — Data pretty printer &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.19. repr — Alternate repr() implementation" href="repr.html" />
    <link rel="prev" title="8.17. copy — Shallow and deep copy operations" href="copy.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pprint.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="repr.html" title="8.19. repr — Alternate repr() implementation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="copy.html" title="8.17. copy — Shallow and deep copy operations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pprint">
<span id="pprint-data-pretty-printer"></span><h1>8.18. <a class="reference internal" href="#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> — Data pretty printer<a class="headerlink" href="#module-pprint" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pprint.py">Lib/pprint.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module provides a capability to “pretty-print” arbitrary
Python data structures in a form which can be used as input to the interpreter.
If the formatted structures include objects which are not fundamental Python
types, the representation may not be loadable.  This may be the case if objects
such as files, sockets, classes, or instances are included, as well as many
other built-in objects which are not representable as Python constants.</p>
<p>The formatted representation keeps objects on a single line if it can, and
breaks them onto multiple lines if they don’t fit within the allowed width.
Construct <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> objects explicitly if you need to adjust the
width constraint.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Dictionaries are sorted by key before the display is computed; before 2.5, a
dictionary was sorted only if its display required more than one line, although
that wasn’t documented.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added support for <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>.</p>
</div>
<p>The <a class="reference internal" href="#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module defines one class:</p>
<dl class="class">
<dt id="pprint.PrettyPrinter">
<em class="property">class </em><code class="descclassname">pprint.</code><code class="descname">PrettyPrinter</code><span class="sig-paren">(</span><em>indent=1</em>, <em>width=80</em>, <em>depth=None</em>, <em>stream=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> instance.  This constructor understands
several keyword parameters.  An output stream may be set using the <em>stream</em>
keyword; the only method used on the stream object is the file protocol’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method.  If not specified, the <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> adopts
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.  Three additional parameters may be used to control the
formatted representation.  The keywords are <em>indent</em>, <em>depth</em>, and <em>width</em>.  The
amount of indentation added for each recursive level is specified by <em>indent</em>;
the default is one.  Other values can cause output to look a little odd, but can
make nesting easier to spot.  The number of levels which may be printed is
controlled by <em>depth</em>; if the data structure being printed is too deep, the next
contained level is replaced by <code class="docutils literal notranslate"><span class="pre">...</span></code>.  By default, there is no constraint on
the depth of the objects being formatted.  The desired output width is
constrained using the <em>width</em> parameter; the default is 80 characters.  If a
structure cannot be formatted within the constrained width, a best effort will
be made.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stuff</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;lumberjack&#39;</span><span class="p">,</span> <span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="s1">&#39;ni&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stuff</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">stuff</span><span class="p">[:])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pp</span> <span class="o">=</span> <span class="n">pprint</span><span class="o">.</span><span class="n">PrettyPrinter</span><span class="p">(</span><span class="n">indent</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pp</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="go">[   [&#39;spam&#39;, &#39;eggs&#39;, &#39;lumberjack&#39;, &#39;knights&#39;, &#39;ni&#39;],</span>
<span class="go">    &#39;spam&#39;,</span>
<span class="go">    &#39;eggs&#39;,</span>
<span class="go">    &#39;lumberjack&#39;,</span>
<span class="go">    &#39;knights&#39;,</span>
<span class="go">    &#39;ni&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tup</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;lumberjack&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;ni&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;dead&#39;</span><span class="p">,</span>
<span class="gp">... </span><span class="p">(</span><span class="s1">&#39;parrot&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;fresh fruit&#39;</span><span class="p">,))))))))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pp</span> <span class="o">=</span> <span class="n">pprint</span><span class="o">.</span><span class="n">PrettyPrinter</span><span class="p">(</span><span class="n">depth</span><span class="o">=</span><span class="mi">6</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pp</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">tup</span><span class="p">)</span>
<span class="go">(&#39;spam&#39;, (&#39;eggs&#39;, (&#39;lumberjack&#39;, (&#39;knights&#39;, (&#39;ni&#39;, (&#39;dead&#39;, (...)))))))</span>
</pre></div>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> class supports several derivative functions:</p>
<dl class="function">
<dt id="pprint.pformat">
<code class="descclassname">pprint.</code><code class="descname">pformat</code><span class="sig-paren">(</span><em>object</em>, <em>indent=1</em>, <em>width=80</em>, <em>depth=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.pformat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the formatted representation of <em>object</em> as a string.  <em>indent</em>, <em>width</em>
and <em>depth</em> will be passed to the <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> constructor as
formatting parameters.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The parameters <em>indent</em>, <em>width</em> and <em>depth</em> were added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="pprint.pprint">
<code class="descclassname">pprint.</code><code class="descname">pprint</code><span class="sig-paren">(</span><em>object</em>, <em>stream=None</em>, <em>indent=1</em>, <em>width=80</em>, <em>depth=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.pprint" title="Permalink to this definition">¶</a></dt>
<dd><p>Prints the formatted representation of <em>object</em> on <em>stream</em>, followed by a
newline.  If <em>stream</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> is used.  This may be used in
the interactive interpreter instead of a <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement for
inspecting values.    <em>indent</em>, <em>width</em> and <em>depth</em> will be passed to the
<a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> constructor as formatting parameters.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stuff</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;lumberjack&#39;</span><span class="p">,</span> <span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="s1">&#39;ni&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stuff</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">stuff</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="go">[&lt;Recursion on list with id=...&gt;,</span>
<span class="go"> &#39;spam&#39;,</span>
<span class="go"> &#39;eggs&#39;,</span>
<span class="go"> &#39;lumberjack&#39;,</span>
<span class="go"> &#39;knights&#39;,</span>
<span class="go"> &#39;ni&#39;]</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The parameters <em>indent</em>, <em>width</em> and <em>depth</em> were added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="pprint.isreadable">
<code class="descclassname">pprint.</code><code class="descname">isreadable</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.isreadable" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Determine if the formatted representation of <em>object</em> is “readable,” or can be
used to reconstruct the value using <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.  This always returns <code class="docutils literal notranslate"><span class="pre">False</span></code>
for recursive objects.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">isreadable</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="pprint.isrecursive">
<code class="descclassname">pprint.</code><code class="descname">isrecursive</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.isrecursive" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if <em>object</em> requires a recursive representation.</p>
</dd></dl>

<p>One more support function is also defined:</p>
<dl class="function">
<dt id="pprint.saferepr">
<code class="descclassname">pprint.</code><code class="descname">saferepr</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.saferepr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string representation of <em>object</em>, protected against recursive data
structures.  If the representation of <em>object</em> exposes a recursive entry, the
recursive reference will be represented as <code class="docutils literal notranslate"><span class="pre">&lt;Recursion</span> <span class="pre">on</span> <span class="pre">typename</span> <span class="pre">with</span>
<span class="pre">id=number&gt;</span></code>.  The representation is not otherwise formatted.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">saferepr</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="go">&quot;[&lt;Recursion on list with id=...&gt;, &#39;spam&#39;, &#39;eggs&#39;, &#39;lumberjack&#39;, &#39;knights&#39;, &#39;ni&#39;]&quot;</span>
</pre></div>
</div>
</dd></dl>

<div class="section" id="prettyprinter-objects">
<span id="id1"></span><h2>8.18.1. PrettyPrinter Objects<a class="headerlink" href="#prettyprinter-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="pprint.PrettyPrinter.pformat">
<code class="descclassname">PrettyPrinter.</code><code class="descname">pformat</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter.pformat" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the formatted representation of <em>object</em>.  This takes into account the
options passed to the <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> constructor.</p>
</dd></dl>

<dl class="method">
<dt id="pprint.PrettyPrinter.pprint">
<code class="descclassname">PrettyPrinter.</code><code class="descname">pprint</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter.pprint" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the formatted representation of <em>object</em> on the configured stream,
followed by a newline.</p>
</dd></dl>

<p>The following methods provide the implementations for the corresponding
functions of the same names.  Using these methods on an instance is slightly
more efficient since new <a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> objects don’t need to be
created.</p>
<dl class="method">
<dt id="pprint.PrettyPrinter.isreadable">
<code class="descclassname">PrettyPrinter.</code><code class="descname">isreadable</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter.isreadable" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Determine if the formatted representation of the object is “readable,” or can be
used to reconstruct the value using <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.  Note that this returns
<code class="docutils literal notranslate"><span class="pre">False</span></code> for recursive objects.  If the <em>depth</em> parameter of the
<a class="reference internal" href="#pprint.PrettyPrinter" title="pprint.PrettyPrinter"><code class="xref py py-class docutils literal notranslate"><span class="pre">PrettyPrinter</span></code></a> is set and the object is deeper than allowed, this
returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="pprint.PrettyPrinter.isrecursive">
<code class="descclassname">PrettyPrinter.</code><code class="descname">isrecursive</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter.isrecursive" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine if the object requires a recursive representation.</p>
</dd></dl>

<p>This method is provided as a hook to allow subclasses to modify the way objects
are converted to strings.  The default implementation uses the internals of the
<a class="reference internal" href="#pprint.saferepr" title="pprint.saferepr"><code class="xref py py-func docutils literal notranslate"><span class="pre">saferepr()</span></code></a> implementation.</p>
<dl class="method">
<dt id="pprint.PrettyPrinter.format">
<code class="descclassname">PrettyPrinter.</code><code class="descname">format</code><span class="sig-paren">(</span><em>object</em>, <em>context</em>, <em>maxlevels</em>, <em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#pprint.PrettyPrinter.format" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns three values: the formatted version of <em>object</em> as a string, a flag
indicating whether the result is readable, and a flag indicating whether
recursion was detected.  The first argument is the object to be presented.  The
second is a dictionary which contains the <a class="reference internal" href="functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> of objects that are part of
the current presentation context (direct and indirect containers for <em>object</em>
that are affecting the presentation) as the keys; if an object needs to be
presented which is already represented in <em>context</em>, the third return value
should be <code class="docutils literal notranslate"><span class="pre">True</span></code>.  Recursive calls to the <a class="reference internal" href="#pprint.PrettyPrinter.format" title="pprint.PrettyPrinter.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> method should add
additional entries for containers to this dictionary.  The third argument,
<em>maxlevels</em>, gives the requested limit to recursion; this will be <code class="docutils literal notranslate"><span class="pre">0</span></code> if there
is no requested limit.  This argument should be passed unmodified to recursive
calls. The fourth argument, <em>level</em>, gives the current level; recursive calls
should be passed a value less than that of the current call.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="pprint-example">
<span id="id2"></span><h2>8.18.2. pprint Example<a class="headerlink" href="#pprint-example" title="Permalink to this headline">¶</a></h2>
<p>This example demonstrates several uses of the <a class="reference internal" href="#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-func docutils literal notranslate"><span class="pre">pprint()</span></code></a> function and its
parameters.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tup</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;lumberjack&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;ni&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;dead&#39;</span><span class="p">,</span>
<span class="gp">... </span><span class="p">(</span><span class="s1">&#39;parrot&#39;</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;fresh fruit&#39;</span><span class="p">,))))))))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stuff</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span> <span class="o">*</span> <span class="mi">10</span><span class="p">,</span> <span class="n">tup</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span> <span class="o">*</span> <span class="mi">30</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span> <span class="o">*</span> <span class="mi">30</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;c&#39;</span> <span class="o">*</span> <span class="mi">20</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span> <span class="o">*</span> <span class="mi">20</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">stuff</span><span class="p">)</span>
<span class="go">[&#39;aaaaaaaaaa&#39;,</span>
<span class="go"> (&#39;spam&#39;,</span>
<span class="go">  (&#39;eggs&#39;,</span>
<span class="go">   (&#39;lumberjack&#39;,</span>
<span class="go">    (&#39;knights&#39;, (&#39;ni&#39;, (&#39;dead&#39;, (&#39;parrot&#39;, (&#39;fresh fruit&#39;,)))))))),</span>
<span class="go"> [&#39;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&#39;, &#39;bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb&#39;],</span>
<span class="go"> [&#39;cccccccccccccccccccc&#39;, &#39;dddddddddddddddddddd&#39;]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">stuff</span><span class="p">,</span> <span class="n">depth</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="go">[&#39;aaaaaaaaaa&#39;,</span>
<span class="go"> (&#39;spam&#39;, (&#39;eggs&#39;, (...))),</span>
<span class="go"> [&#39;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&#39;, &#39;bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb&#39;],</span>
<span class="go"> [&#39;cccccccccccccccccccc&#39;, &#39;dddddddddddddddddddd&#39;]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">stuff</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">60</span><span class="p">)</span>
<span class="go">[&#39;aaaaaaaaaa&#39;,</span>
<span class="go"> (&#39;spam&#39;,</span>
<span class="go">  (&#39;eggs&#39;,</span>
<span class="go">   (&#39;lumberjack&#39;,</span>
<span class="go">    (&#39;knights&#39;,</span>
<span class="go">     (&#39;ni&#39;, (&#39;dead&#39;, (&#39;parrot&#39;, (&#39;fresh fruit&#39;,)))))))),</span>
<span class="go"> [&#39;aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&#39;,</span>
<span class="go">  &#39;bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb&#39;],</span>
<span class="go"> [&#39;cccccccccccccccccccc&#39;, &#39;dddddddddddddddddddd&#39;]]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a><ul>
<li><a class="reference internal" href="#prettyprinter-objects">8.18.1. PrettyPrinter Objects</a></li>
<li><a class="reference internal" href="#pprint-example">8.18.2. pprint Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="copy.html"
                        title="previous chapter">8.17. <code class="docutils literal notranslate"><span class="pre">copy</span></code> — Shallow and deep copy operations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="repr.html"
                        title="next chapter">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pprint.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="repr.html" title="8.19. repr — Alternate repr() implementation"
             >next</a> |</li>
        <li class="right" >
          <a href="copy.html" title="8.17. copy — Shallow and deep copy operations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\x�|TThtml/library/profile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.4. The Python Profilers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.5. hotshot — High performance logging profiler" href="hotshot.html" />
    <link rel="prev" title="26.2. pdb — The Python Debugger" href="pdb.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/profile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hotshot.html" title="26.5. hotshot — High performance logging profiler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pdb.html" title="26.2. pdb — The Python Debugger"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-python-profilers">
<span id="profile"></span><h1>26.4. The Python Profilers<a class="headerlink" href="#the-python-profilers" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/profile.py">Lib/profile.py</a> and <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pstats.py">Lib/pstats.py</a></p>
<hr class="docutils" />
<div class="section" id="introduction-to-the-profilers">
<span id="profiler-introduction"></span><h2>26.4.1. Introduction to the profilers<a class="headerlink" href="#introduction-to-the-profilers" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> and <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> provide <em class="dfn">deterministic profiling</em> of
Python programs. A <em class="dfn">profile</em> is a set of statistics that describes how
often and for how long various parts of the program executed. These statistics
can be formatted into reports via the <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module.</p>
<p>The Python standard library provides three different implementations of the same
profiling interface:</p>
<ol class="arabic">
<li><p class="first"><a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> is recommended for most users; it’s a C extension with
reasonable overhead that makes it suitable for profiling long-running
programs.  Based on <code class="xref py py-mod docutils literal notranslate"><span class="pre">lsprof</span></code>, contributed by Brett Rosen and Ted
Czotter.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</li>
<li><p class="first"><a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>, a pure Python module whose interface is imitated by
<a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>, but which adds significant overhead to profiled programs.
If you’re trying to extend the profiler in some way, the task might be easier
with this module.  Originally designed and written by Jim Roskind.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Now also reports the time spent in calls to built-in functions
and methods.</p>
</div>
</li>
<li><p class="first"><a class="reference internal" href="hotshot.html#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> was an experimental C module that focused on minimizing
the overhead of profiling, at the expense of longer data
post-processing times.  It is no longer maintained and may be
dropped in a future version of Python.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The results should be more meaningful than in the past: the timing core
contained a critical bug.</p>
</div>
</li>
</ol>
<p>The <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> modules export the same interface, so
they are mostly interchangeable; <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> has a much lower overhead but
is newer and might not be available on all systems.
<a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> is really a compatibility layer on top of the internal
<code class="xref py py-mod docutils literal notranslate"><span class="pre">_lsprof</span></code> module.  The <a class="reference internal" href="hotshot.html#module-hotshot" title="hotshot: High performance logging profiler, mostly written in C."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hotshot</span></code></a> module is reserved for specialized
usage.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The profiler modules are designed to provide an execution profile for a given
program, not for benchmarking purposes (for that, there is <a class="reference internal" href="timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> for
reasonably accurate results).  This particularly applies to benchmarking
Python code against C code: the profilers introduce overhead for Python code,
but not for C-level functions, and so the C code would seem faster than any
Python one.</p>
</div>
</div>
<div class="section" id="instant-user-s-manual">
<span id="profile-instant"></span><h2>26.4.2. Instant User’s Manual<a class="headerlink" href="#instant-user-s-manual" title="Permalink to this headline">¶</a></h2>
<p>This section is provided for users that “don’t want to read the manual.” It
provides a very brief overview, and allows a user to rapidly perform profiling
on an existing application.</p>
<p>To profile a function that takes a single argument, you can do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="n">cProfile</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;re.compile(&quot;foo|bar&quot;)&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>(Use <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> instead of <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> if the latter is not available on
your system.)</p>
<p>The above action would run <a class="reference internal" href="re.html#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> and print profile results like
the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>      <span class="mi">197</span> <span class="n">function</span> <span class="n">calls</span> <span class="p">(</span><span class="mi">192</span> <span class="n">primitive</span> <span class="n">calls</span><span class="p">)</span> <span class="ow">in</span> <span class="mf">0.002</span> <span class="n">seconds</span>

<span class="n">Ordered</span> <span class="n">by</span><span class="p">:</span> <span class="n">standard</span> <span class="n">name</span>

<span class="n">ncalls</span>  <span class="n">tottime</span>  <span class="n">percall</span>  <span class="n">cumtime</span>  <span class="n">percall</span> <span class="n">filename</span><span class="p">:</span><span class="n">lineno</span><span class="p">(</span><span class="n">function</span><span class="p">)</span>
     <span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.001</span>    <span class="mf">0.001</span> <span class="o">&lt;</span><span class="n">string</span><span class="o">&gt;</span><span class="p">:</span><span class="mi">1</span><span class="p">(</span><span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span><span class="p">)</span>
     <span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.001</span>    <span class="mf">0.001</span> <span class="n">re</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">212</span><span class="p">(</span><span class="nb">compile</span><span class="p">)</span>
     <span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.001</span>    <span class="mf">0.001</span> <span class="n">re</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">268</span><span class="p">(</span><span class="n">_compile</span><span class="p">)</span>
     <span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span> <span class="n">sre_compile</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">172</span><span class="p">(</span><span class="n">_compile_charset</span><span class="p">)</span>
     <span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span> <span class="n">sre_compile</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">201</span><span class="p">(</span><span class="n">_optimize_charset</span><span class="p">)</span>
     <span class="mi">4</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span> <span class="n">sre_compile</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">25</span><span class="p">(</span><span class="n">_identityfunction</span><span class="p">)</span>
   <span class="mi">3</span><span class="o">/</span><span class="mi">1</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span>    <span class="mf">0.000</span> <span class="n">sre_compile</span><span class="o">.</span><span class="n">py</span><span class="p">:</span><span class="mi">33</span><span class="p">(</span><span class="n">_compile</span><span class="p">)</span>
</pre></div>
</div>
<p>The first line indicates that 197 calls were monitored.  Of those calls, 192
were <em class="dfn">primitive</em>, meaning that the call was not induced via recursion. The
next line: <code class="docutils literal notranslate"><span class="pre">Ordered</span> <span class="pre">by:</span> <span class="pre">standard</span> <span class="pre">name</span></code>, indicates that the text string in the
far right column was used to sort the output. The column headings include:</p>
<dl class="docutils">
<dt>ncalls</dt>
<dd>for the number of calls,</dd>
<dt>tottime</dt>
<dd>for the total time spent in the given function (and excluding time made in
calls to sub-functions)</dd>
<dt>percall</dt>
<dd>is the quotient of <code class="docutils literal notranslate"><span class="pre">tottime</span></code> divided by <code class="docutils literal notranslate"><span class="pre">ncalls</span></code></dd>
<dt>cumtime</dt>
<dd>is the cumulative time spent in this and all subfunctions (from invocation
till exit). This figure is accurate <em>even</em> for recursive functions.</dd>
<dt>percall</dt>
<dd>is the quotient of <code class="docutils literal notranslate"><span class="pre">cumtime</span></code> divided by primitive calls</dd>
<dt>filename:lineno(function)</dt>
<dd>provides the respective data of each function</dd>
</dl>
<p>When there are two numbers in the first column (for example <code class="docutils literal notranslate"><span class="pre">3/1</span></code>), it means
that the function recursed.  The second value is the number of primitive calls
and the former is the total number of calls.  Note that when the function does
not recurse, these two values are the same, and only the single figure is
printed.</p>
<p>Instead of printing the output at the end of the profile run, you can save the
results to a file by specifying a filename to the <code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span>
<span class="kn">import</span> <span class="nn">re</span>
<span class="n">cProfile</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;re.compile(&quot;foo|bar&quot;)&#39;</span><span class="p">,</span> <span class="s1">&#39;restats&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">pstats.Stats</span></code></a> class reads profile results from a file and formats
them in various ways.</p>
<p>The file <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> can also be invoked as a script to profile another
script.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">cProfile</span> <span class="p">[</span><span class="o">-</span><span class="n">o</span> <span class="n">output_file</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">s</span> <span class="n">sort_order</span><span class="p">]</span> <span class="n">myscript</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">-o</span></code> writes the profile results to a file instead of to stdout</p>
<p><code class="docutils literal notranslate"><span class="pre">-s</span></code> specifies one of the <a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-func docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> sort values to sort
the output by. This only applies when <code class="docutils literal notranslate"><span class="pre">-o</span></code> is not supplied.</p>
<p>The <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module’s <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class has a variety of methods
for manipulating and printing the data saved into a profile results file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pstats</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="s1">&#39;restats&#39;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">strip_dirs</span><span class="p">()</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a> method removed the extraneous path from all
the module names. The <a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> method sorted all the
entries according to the standard module/line/name string that is printed. The
<a class="reference internal" href="#pstats.Stats.print_stats" title="pstats.Stats.print_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_stats()</span></code></a> method printed out all the statistics.  You
might try the following sort calls:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="n">p</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
</pre></div>
</div>
<p>The first call will actually sort the list by function name, and the second call
will print out the statistics.  The following are some interesting calls to
experiment with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;cumulative&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
<p>This sorts the profile by cumulative time in a function, and then only prints
the ten most significant lines.  If you want to understand what algorithms are
taking time, the above line is what you would use.</p>
<p>If you were looking to see what functions were looping a lot, and taking a lot
of time, you would do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</pre></div>
</div>
<p>to sort according to time spent within each function, and then print the
statistics for the top ten functions.</p>
<p>You might also try:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;file&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="s1">&#39;__init__&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This will sort all the statistics by file name, and then print out statistics
for only the class init methods (since they are spelled with <code class="docutils literal notranslate"><span class="pre">__init__</span></code> in
them).  As one final example, you could try:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="s1">&#39;time&#39;</span><span class="p">,</span> <span class="s1">&#39;cum&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">print_stats</span><span class="p">(</span><span class="o">.</span><span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;init&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This line sorts statistics with a primary key of time, and a secondary key of
cumulative time, and then prints out some of the statistics. To be specific, the
list is first culled down to 50% (re: <code class="docutils literal notranslate"><span class="pre">.5</span></code>) of its original size, then only
lines containing <code class="docutils literal notranslate"><span class="pre">init</span></code> are maintained, and that sub-sub-list is printed.</p>
<p>If you wondered what functions called the above functions, you could now (<code class="docutils literal notranslate"><span class="pre">p</span></code>
is still sorted according to the last criteria) do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">print_callers</span><span class="p">(</span><span class="o">.</span><span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;init&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>and you would get a list of callers for each of the listed functions.</p>
<p>If you want more functionality, you’re going to have to read the manual, or
guess what the following functions do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span><span class="o">.</span><span class="n">print_callees</span><span class="p">()</span>
<span class="n">p</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;restats&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Invoked as a script, the <a class="reference internal" href="#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module is a statistics browser for
reading and examining profile dumps.  It has a simple line-oriented interface
(implemented using <a class="reference internal" href="cmd.html#module-cmd" title="cmd: Build line-oriented command interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmd</span></code></a>) and interactive help.</p>
</div>
<div class="section" id="module-cProfile">
<span id="profile-and-cprofile-module-reference"></span><h2>26.4.3. <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> Module Reference<a class="headerlink" href="#module-cProfile" title="Permalink to this headline">¶</a></h2>
<span class="target" id="module-profile"></span><p>Both the <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> modules provide the following
functions:</p>
<dl class="function">
<dt id="profile.run">
<code class="descclassname">profile.</code><code class="descname">run</code><span class="sig-paren">(</span><em>command</em>, <em>filename=None</em>, <em>sort=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.run" title="Permalink to this definition">¶</a></dt>
<dd><p>This function takes a single argument that can be passed to the <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code>
function, and an optional file name.  In all cases this routine executes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">exec</span><span class="p">(</span><span class="n">command</span><span class="p">,</span> <span class="n">__main__</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">,</span> <span class="n">__main__</span><span class="o">.</span><span class="vm">__dict__</span><span class="p">)</span>
</pre></div>
</div>
<p>and gathers profiling statistics from the execution. If no file name is
present, then this function automatically creates a <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a>
instance and prints a simple profiling report. If the sort value is specified
it is passed to this <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> instance to control how the
results are sorted.</p>
</dd></dl>

<dl class="function">
<dt id="profile.runctx">
<code class="descclassname">profile.</code><code class="descname">runctx</code><span class="sig-paren">(</span><em>command</em>, <em>globals</em>, <em>locals</em>, <em>filename=None</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.runctx" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is similar to <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a>, with added arguments to supply the
globals and locals dictionaries for the <em>command</em> string. This routine
executes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">exec</span><span class="p">(</span><span class="n">command</span><span class="p">,</span> <span class="nb">globals</span><span class="p">,</span> <span class="nb">locals</span><span class="p">)</span>
</pre></div>
</div>
<p>and gathers profiling statistics as in the <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">run()</span></code></a> function above.</p>
</dd></dl>

<dl class="class">
<dt id="profile.Profile">
<em class="property">class </em><code class="descclassname">profile.</code><code class="descname">Profile</code><span class="sig-paren">(</span><em>timer=None</em>, <em>timeunit=0.0</em>, <em>subcalls=True</em>, <em>builtins=True</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is normally only used if more precise control over profiling is
needed than what the <code class="xref py py-func docutils literal notranslate"><span class="pre">cProfile.run()</span></code> function provides.</p>
<p>A custom timer can be supplied for measuring how long code takes to run via
the <em>timer</em> argument. This must be a function that returns a single number
representing the current time. If the number is an integer, the <em>timeunit</em>
specifies a multiplier that specifies the duration of each unit of time. For
example, if the timer returns times measured in thousands of seconds, the
time unit would be <code class="docutils literal notranslate"><span class="pre">.001</span></code>.</p>
<p>Directly using the <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code></a> class allows formatting profile results
without writing the profile data to a file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cProfile</span><span class="o">,</span> <span class="nn">pstats</span><span class="o">,</span> <span class="nn">StringIO</span>
<span class="n">pr</span> <span class="o">=</span> <span class="n">cProfile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
<span class="n">pr</span><span class="o">.</span><span class="n">enable</span><span class="p">()</span>
<span class="c1"># ... do something ...</span>
<span class="n">pr</span><span class="o">.</span><span class="n">disable</span><span class="p">()</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">StringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
<span class="n">sortby</span> <span class="o">=</span> <span class="s1">&#39;cumulative&#39;</span>
<span class="n">ps</span> <span class="o">=</span> <span class="n">pstats</span><span class="o">.</span><span class="n">Stats</span><span class="p">(</span><span class="n">pr</span><span class="p">,</span> <span class="n">stream</span><span class="o">=</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">sort_stats</span><span class="p">(</span><span class="n">sortby</span><span class="p">)</span>
<span class="n">ps</span><span class="o">.</span><span class="n">print_stats</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>
</div>
<dl class="method">
<dt id="profile.Profile.enable">
<code class="descname">enable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.enable" title="Permalink to this definition">¶</a></dt>
<dd><p>Start collecting profiling data.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.disable">
<code class="descname">disable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.disable" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop collecting profiling data.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.create_stats">
<code class="descname">create_stats</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.create_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop collecting profiling data and record the results internally
as the current profile.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.print_stats">
<code class="descname">print_stats</code><span class="sig-paren">(</span><em>sort=-1</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.print_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object based on the current
profile and print the results to stdout.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.dump_stats">
<code class="descname">dump_stats</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.dump_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the results of the current profile to <em>filename</em>.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Profile the cmd via <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.runctx">
<code class="descname">runctx</code><span class="sig-paren">(</span><em>cmd</em>, <em>globals</em>, <em>locals</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.runctx" title="Permalink to this definition">¶</a></dt>
<dd><p>Profile the cmd via <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code> with the specified global and
local environment.</p>
</dd></dl>

<dl class="method">
<dt id="profile.Profile.runcall">
<code class="descname">runcall</code><span class="sig-paren">(</span><em>func</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#profile.Profile.runcall" title="Permalink to this definition">¶</a></dt>
<dd><p>Profile <code class="docutils literal notranslate"><span class="pre">func(*args,</span> <span class="pre">**kwargs)</span></code></p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="the-stats-class">
<span id="profile-stats"></span><h2>26.4.4. The <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> Class<a class="headerlink" href="#the-stats-class" title="Permalink to this headline">¶</a></h2>
<p>Analysis of the profiler data is done using the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class.</p>
<span class="target" id="module-pstats"></span><dl class="class">
<dt id="pstats.Stats">
<em class="property">class </em><code class="descclassname">pstats.</code><code class="descname">Stats</code><span class="sig-paren">(</span><em>*filenames or profile</em>, <em>stream=sys.stdout</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats" title="Permalink to this definition">¶</a></dt>
<dd><p>This class constructor creates an instance of a “statistics object” from a
<em>filename</em> (or list of filenames) or from a <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> instance. Output
will be printed to the stream specified by <em>stream</em>.</p>
<p>The file selected by the above constructor must have been created by the
corresponding version of <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> or <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>.  To be specific,
there is <em>no</em> file compatibility guaranteed with future versions of this
profiler, and there is no compatibility with files produced by other
profilers, or the same profiler run on a different operating system.  If
several files are provided, all the statistics for identical functions will
be coalesced, so that an overall view of several processes can be considered
in a single report.  If additional files need to be combined with data in an
existing <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object, the <a class="reference internal" href="#pstats.Stats.add" title="pstats.Stats.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> method
can be used.</p>
<p>Instead of reading the profile data from a file, a <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code>
or <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> object can be used as the profile data source.</p>
<p><a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> objects have the following methods:</p>
<dl class="method">
<dt id="pstats.Stats.strip_dirs">
<code class="descname">strip_dirs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.strip_dirs" title="Permalink to this definition">¶</a></dt>
<dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class removes all leading path
information from file names.  It is very useful in reducing the size of
the printout to fit within (close to) 80 columns.  This method modifies
the object, and the stripped information is lost.  After performing a
strip operation, the object is considered to have its entries in a
“random” order, as it was just after object initialization and loading.
If <a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a> causes two function names to be
indistinguishable (they are on the same line of the same filename, and
have the same function name), then the statistics for these two entries
are accumulated into a single entry.</p>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>*filenames</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.add" title="Permalink to this definition">¶</a></dt>
<dd><p>This method of the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class accumulates additional profiling
information into the current profiling object.  Its arguments should refer
to filenames created by the corresponding version of <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">profile.run()</span></code></a>
or <code class="xref py py-func docutils literal notranslate"><span class="pre">cProfile.run()</span></code>. Statistics for identically named (re: file, line,
name) functions are automatically accumulated into single function
statistics.</p>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.dump_stats">
<code class="descname">dump_stats</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.dump_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Save the data loaded into the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object to a file named
<em>filename</em>.  The file is created if it does not exist, and is overwritten
if it already exists.  This is equivalent to the method of the same name
on the <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> and <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code> classes.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<dl class="method">
<dt id="pstats.Stats.sort_stats">
<code class="descname">sort_stats</code><span class="sig-paren">(</span><em>*keys</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.sort_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>This method modifies the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> object by sorting it according to
the supplied criteria.  The argument is typically a string identifying the
basis of a sort (example: <code class="docutils literal notranslate"><span class="pre">'time'</span></code> or <code class="docutils literal notranslate"><span class="pre">'name'</span></code>).</p>
<p>When more than one key is provided, then additional keys are used as
secondary criteria when there is equality in all keys selected before
them.  For example, <code class="docutils literal notranslate"><span class="pre">sort_stats('name',</span> <span class="pre">'file')</span></code> will sort all the
entries according to their function name, and resolve all ties (identical
function names) by sorting by file name.</p>
<p>Abbreviations can be used for any key names, as long as the abbreviation
is unambiguous.  The following are the keys currently defined:</p>
<table border="1" class="docutils">
<colgroup>
<col width="45%" />
<col width="55%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Valid Arg</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'calls'</span></code></td>
<td>call count</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'cumulative'</span></code></td>
<td>cumulative time</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'cumtime'</span></code></td>
<td>cumulative time</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'file'</span></code></td>
<td>file name</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'filename'</span></code></td>
<td>file name</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'module'</span></code></td>
<td>file name</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'ncalls'</span></code></td>
<td>call count</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'pcalls'</span></code></td>
<td>primitive call count</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'line'</span></code></td>
<td>line number</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'name'</span></code></td>
<td>function name</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'nfl'</span></code></td>
<td>name/file/line</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'stdname'</span></code></td>
<td>standard name</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'time'</span></code></td>
<td>internal time</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'tottime'</span></code></td>
<td>internal time</td>
</tr>
</tbody>
</table>
<p>Note that all sorts on statistics are in descending order (placing most
time consuming items first), where as name, file, and line number searches
are in ascending order (alphabetical). The subtle distinction between
<code class="docutils literal notranslate"><span class="pre">'nfl'</span></code> and <code class="docutils literal notranslate"><span class="pre">'stdname'</span></code> is that the standard name is a sort of the
name as printed, which means that the embedded line numbers get compared
in an odd way.  For example, lines 3, 20, and 40 would (if the file names
were the same) appear in the string order 20, 3 and 40.  In contrast,
<code class="docutils literal notranslate"><span class="pre">'nfl'</span></code> does a numeric compare of the line numbers.  In fact,
<code class="docutils literal notranslate"><span class="pre">sort_stats('nfl')</span></code> is the same as <code class="docutils literal notranslate"><span class="pre">sort_stats('name',</span> <span class="pre">'file',</span>
<span class="pre">'line')</span></code>.</p>
<p>For backward-compatibility reasons, the numeric arguments <code class="docutils literal notranslate"><span class="pre">-1</span></code>, <code class="docutils literal notranslate"><span class="pre">0</span></code>,
<code class="docutils literal notranslate"><span class="pre">1</span></code>, and <code class="docutils literal notranslate"><span class="pre">2</span></code> are permitted.  They are interpreted as <code class="docutils literal notranslate"><span class="pre">'stdname'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'calls'</span></code>, <code class="docutils literal notranslate"><span class="pre">'time'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'cumulative'</span></code> respectively.  If this old
style format (numeric) is used, only one sort key (the numeric key) will
be used, and additional arguments will be silently ignored.</p>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.reverse_order">
<code class="descname">reverse_order</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.reverse_order" title="Permalink to this definition">¶</a></dt>
<dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class reverses the ordering of the
basic list within the object.  Note that by default ascending vs
descending order is properly selected based on the sort key of choice.</p>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.print_stats">
<code class="descname">print_stats</code><span class="sig-paren">(</span><em>*restrictions</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints out a report as described
in the <a class="reference internal" href="#profile.run" title="profile.run"><code class="xref py py-func docutils literal notranslate"><span class="pre">profile.run()</span></code></a> definition.</p>
<p>The order of the printing is based on the last
<a class="reference internal" href="#pstats.Stats.sort_stats" title="pstats.Stats.sort_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sort_stats()</span></code></a> operation done on the object (subject to
caveats in <a class="reference internal" href="#pstats.Stats.add" title="pstats.Stats.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> and
<a class="reference internal" href="#pstats.Stats.strip_dirs" title="pstats.Stats.strip_dirs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">strip_dirs()</span></code></a>).</p>
<p>The arguments provided (if any) can be used to limit the list down to the
significant entries.  Initially, the list is taken to be the complete set
of profiled functions.  Each restriction is either an integer (to select a
count of lines), or a decimal fraction between 0.0 and 1.0 inclusive (to
select a percentage of lines), or a regular expression (to pattern match
the standard name that is printed.  If several restrictions are provided,
then they are applied sequentially.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">print_stats</span><span class="p">(</span><span class="o">.</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;foo:&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>would first limit the printing to first 10% of list, and then only print
functions that were part of filename <code class="file docutils literal notranslate"><span class="pre">.*foo:</span></code>.  In contrast, the
command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">print_stats</span><span class="p">(</span><span class="s1">&#39;foo:&#39;</span><span class="p">,</span> <span class="o">.</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>would limit the list to all functions having file names <code class="file docutils literal notranslate"><span class="pre">.*foo:</span></code>,
and then proceed to only print the first 10% of them.</p>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.print_callers">
<code class="descname">print_callers</code><span class="sig-paren">(</span><em>*restrictions</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_callers" title="Permalink to this definition">¶</a></dt>
<dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints a list of all functions
that called each function in the profiled database.  The ordering is
identical to that provided by <a class="reference internal" href="#pstats.Stats.print_stats" title="pstats.Stats.print_stats"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_stats()</span></code></a>, and the
definition of the restricting argument is also identical.  Each caller is
reported on its own line.  The format differs slightly depending on the
profiler that produced the stats:</p>
<ul class="simple">
<li>With <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>, a number is shown in parentheses after each caller
to show how many times this specific call was made.  For convenience, a
second non-parenthesized number repeats the cumulative time spent in the
function at the right.</li>
<li>With <a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>, each caller is preceded by three numbers: the
number of times this specific call was made, and the total and
cumulative times spent in the current function while it was invoked by
this specific caller.</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="pstats.Stats.print_callees">
<code class="descname">print_callees</code><span class="sig-paren">(</span><em>*restrictions</em><span class="sig-paren">)</span><a class="headerlink" href="#pstats.Stats.print_callees" title="Permalink to this definition">¶</a></dt>
<dd><p>This method for the <a class="reference internal" href="#pstats.Stats" title="pstats.Stats"><code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code></a> class prints a list of all function
that were called by the indicated function.  Aside from this reversal of
direction of calls (re: called vs was called by), the arguments and
ordering are identical to the <a class="reference internal" href="#pstats.Stats.print_callers" title="pstats.Stats.print_callers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">print_callers()</span></code></a> method.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="what-is-deterministic-profiling">
<span id="deterministic-profiling"></span><h2>26.4.5. What Is Deterministic Profiling?<a class="headerlink" href="#what-is-deterministic-profiling" title="Permalink to this headline">¶</a></h2>
<p><em class="dfn">Deterministic profiling</em> is meant to reflect the fact that all <em>function
call</em>, <em>function return</em>, and <em>exception</em> events are monitored, and precise
timings are made for the intervals between these events (during which time the
user’s code is executing).  In contrast, <em class="dfn">statistical profiling</em> (which is
not done by this module) randomly samples the effective instruction pointer, and
deduces where time is being spent.  The latter technique traditionally involves
less overhead (as the code does not need to be instrumented), but provides only
relative indications of where time is being spent.</p>
<p>In Python, since there is an interpreter active during execution, the presence
of instrumented code is not required to do deterministic profiling.  Python
automatically provides a <em class="dfn">hook</em> (optional callback) for each event.  In
addition, the interpreted nature of Python tends to add so much overhead to
execution, that deterministic profiling tends to only add small processing
overhead in typical applications.  The result is that deterministic profiling is
not that expensive, yet provides extensive run time statistics about the
execution of a Python program.</p>
<p>Call count statistics can be used to identify bugs in code (surprising counts),
and to identify possible inline-expansion points (high call counts).  Internal
time statistics can be used to identify “hot loops” that should be carefully
optimized.  Cumulative time statistics should be used to identify high level
errors in the selection of algorithms.  Note that the unusual handling of
cumulative times in this profiler allows statistics for recursive
implementations of algorithms to be directly compared to iterative
implementations.</p>
</div>
<div class="section" id="limitations">
<span id="profile-limitations"></span><h2>26.4.6. Limitations<a class="headerlink" href="#limitations" title="Permalink to this headline">¶</a></h2>
<p>One limitation has to do with accuracy of timing information. There is a
fundamental problem with deterministic profilers involving accuracy.  The most
obvious restriction is that the underlying “clock” is only ticking at a rate
(typically) of about .001 seconds.  Hence no measurements will be more accurate
than the underlying clock.  If enough measurements are taken, then the “error”
will tend to average out. Unfortunately, removing this first error induces a
second source of error.</p>
<p>The second problem is that it “takes a while” from when an event is dispatched
until the profiler’s call to get the time actually <em>gets</em> the state of the
clock.  Similarly, there is a certain lag when exiting the profiler event
handler from the time that the clock’s value was obtained (and then squirreled
away), until the user’s code is once again executing.  As a result, functions
that are called many times, or call many functions, will typically accumulate
this error. The error that accumulates in this fashion is typically less than
the accuracy of the clock (less than one clock tick), but it <em>can</em> accumulate
and become very significant.</p>
<p>The problem is more important with <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> than with the lower-overhead
<a class="reference internal" href="#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a>.  For this reason, <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> provides a means of
calibrating itself for a given platform so that this error can be
probabilistically (on the average) removed. After the profiler is calibrated, it
will be more accurate (in a least square sense), but it will sometimes produce
negative numbers (when call counts are exceptionally low, and the gods of
probability work against you :-). )  Do <em>not</em> be alarmed by negative numbers in
the profile.  They should <em>only</em> appear if you have calibrated your profiler,
and the results are actually better than without calibration.</p>
</div>
<div class="section" id="calibration">
<span id="profile-calibration"></span><h2>26.4.7. Calibration<a class="headerlink" href="#calibration" title="Permalink to this headline">¶</a></h2>
<p>The profiler of the <a class="reference internal" href="#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module subtracts a constant from each event
handling time to compensate for the overhead of calling the time function, and
socking away the results.  By default, the constant is 0. The following
procedure can be used to obtain a better constant for a given platform (see
<a class="reference internal" href="#profile-limitations"><span class="std std-ref">Limitations</span></a>).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">profile</span>
<span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">pr</span><span class="o">.</span><span class="n">calibrate</span><span class="p">(</span><span class="mi">10000</span><span class="p">)</span>
</pre></div>
</div>
<p>The method executes the number of Python calls given by the argument, directly
and again under the profiler, measuring the time for both. It then computes the
hidden overhead per profiler event, and returns that as a float.  For example,
on a 1.8Ghz Intel Core i5 running Mac OS X, and using Python’s time.clock() as
the timer, the magical number is about 4.04e-6.</p>
<p>The object of this exercise is to get a fairly consistent result. If your
computer is <em>very</em> fast, or your timer function has poor resolution, you might
have to pass 100000, or even 1000000, to get consistent results.</p>
<p>When you have a consistent answer, there are three ways you can use it: <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">profile</span>

<span class="c1"># 1. Apply computed bias to all Profile instances created hereafter.</span>
<span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="o">.</span><span class="n">bias</span> <span class="o">=</span> <span class="n">your_computed_bias</span>

<span class="c1"># 2. Apply computed bias to a specific Profile instance.</span>
<span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">()</span>
<span class="n">pr</span><span class="o">.</span><span class="n">bias</span> <span class="o">=</span> <span class="n">your_computed_bias</span>

<span class="c1"># 3. Specify computed bias in instance constructor.</span>
<span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">bias</span><span class="o">=</span><span class="n">your_computed_bias</span><span class="p">)</span>
</pre></div>
</div>
<p>If you have a choice, you are better off choosing a smaller constant, and then
your results will “less often” show up as negative in profile statistics.</p>
</div>
<div class="section" id="using-a-custom-timer">
<span id="profile-timers"></span><h2>26.4.8. Using a custom timer<a class="headerlink" href="#using-a-custom-timer" title="Permalink to this headline">¶</a></h2>
<p>If you want to change how current time is determined (for example, to force use
of wall-clock time or elapsed process time), pass the timing function you want
to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> class constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pr</span> <span class="o">=</span> <span class="n">profile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">your_time_func</span><span class="p">)</span>
</pre></div>
</div>
<p>The resulting profiler will then call <code class="docutils literal notranslate"><span class="pre">your_time_func</span></code>. Depending on whether
you are using <a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a> or <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code>,
<code class="docutils literal notranslate"><span class="pre">your_time_func</span></code>’s return value will be interpreted differently:</p>
<dl class="docutils">
<dt><a class="reference internal" href="#profile.Profile" title="profile.Profile"><code class="xref py py-class docutils literal notranslate"><span class="pre">profile.Profile</span></code></a></dt>
<dd><p class="first"><code class="docutils literal notranslate"><span class="pre">your_time_func</span></code> should return a single number, or a list of numbers whose
sum is the current time (like what <a class="reference internal" href="os.html#os.times" title="os.times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.times()</span></code></a> returns).  If the
function returns a single time number, or the list of returned numbers has
length 2, then you will get an especially fast version of the dispatch
routine.</p>
<p class="last">Be warned that you should calibrate the profiler class for the timer function
that you choose (see <a class="reference internal" href="#profile-calibration"><span class="std std-ref">Calibration</span></a>).  For most machines, a timer
that returns a lone integer value will provide the best results in terms of
low overhead during profiling.  (<a class="reference internal" href="os.html#os.times" title="os.times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.times()</span></code></a> is <em>pretty</em> bad, as it
returns a tuple of floating point values).  If you want to substitute a
better timer in the cleanest fashion, derive a class and hardwire a
replacement dispatch method that best handles your timer call, along with the
appropriate calibration constant.</p>
</dd>
<dt><code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code></dt>
<dd><p class="first"><code class="docutils literal notranslate"><span class="pre">your_time_func</span></code> should return a single number.  If it returns integers,
you can also invoke the class constructor with a second argument specifying
the real duration of one unit of time.  For example, if
<code class="docutils literal notranslate"><span class="pre">your_integer_time_func</span></code> returns times measured in thousands of seconds,
you would construct the <code class="xref py py-class docutils literal notranslate"><span class="pre">Profile</span></code> instance as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pr</span> <span class="o">=</span> <span class="n">cProfile</span><span class="o">.</span><span class="n">Profile</span><span class="p">(</span><span class="n">your_integer_time_func</span><span class="p">,</span> <span class="mf">0.001</span><span class="p">)</span>
</pre></div>
</div>
<p class="last">As the <code class="xref py py-class docutils literal notranslate"><span class="pre">cProfile.Profile</span></code> class cannot be calibrated, custom timer
functions should be used with care and should be as fast as possible.  For
the best results with a custom timer, it might be necessary to hard-code it
in the C source of the internal <code class="xref py py-mod docutils literal notranslate"><span class="pre">_lsprof</span></code> module.</p>
</dd>
</dl>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Prior to Python 2.2, it was necessary to edit the profiler source code to
embed the bias as a literal number.  You still can, but that method is no longer
described, because no longer needed.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">26.4. The Python Profilers</a><ul>
<li><a class="reference internal" href="#introduction-to-the-profilers">26.4.1. Introduction to the profilers</a></li>
<li><a class="reference internal" href="#instant-user-s-manual">26.4.2. Instant User’s Manual</a></li>
<li><a class="reference internal" href="#module-cProfile">26.4.3. <code class="docutils literal notranslate"><span class="pre">profile</span></code> and <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> Module Reference</a></li>
<li><a class="reference internal" href="#the-stats-class">26.4.4. The <code class="docutils literal notranslate"><span class="pre">Stats</span></code> Class</a></li>
<li><a class="reference internal" href="#what-is-deterministic-profiling">26.4.5. What Is Deterministic Profiling?</a></li>
<li><a class="reference internal" href="#limitations">26.4.6. Limitations</a></li>
<li><a class="reference internal" href="#calibration">26.4.7. Calibration</a></li>
<li><a class="reference internal" href="#using-a-custom-timer">26.4.8. Using a custom timer</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pdb.html"
                        title="previous chapter">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="hotshot.html"
                        title="next chapter">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/profile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="hotshot.html" title="26.5. hotshot — High performance logging profiler"
             >next</a> |</li>
        <li class="right" >
          <a href="pdb.html" title="26.2. pdb — The Python Debugger"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\`jw�'�'html/library/pty.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.9. pty — Pseudo-terminal utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.10. fcntl — The fcntl and ioctl system calls" href="fcntl.html" />
    <link rel="prev" title="36.8. tty — Terminal control functions" href="tty.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pty.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fcntl.html" title="36.10. fcntl — The fcntl and ioctl system calls"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tty.html" title="36.8. tty — Terminal control functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pty">
<span id="pty-pseudo-terminal-utilities"></span><h1>36.9. <a class="reference internal" href="#module-pty" title="pty: Pseudo-Terminal Handling for Linux. (Linux)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pty</span></code></a> — Pseudo-terminal utilities<a class="headerlink" href="#module-pty" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-pty" title="pty: Pseudo-Terminal Handling for Linux. (Linux)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pty</span></code></a> module defines operations for handling the pseudo-terminal
concept: starting another process and being able to write to and read from its
controlling terminal programmatically.</p>
<p>Because pseudo-terminal handling is highly platform dependent, there is code to
do it only for Linux. (The Linux code is supposed to work on other platforms,
but hasn’t been tested yet.)</p>
<p>The <a class="reference internal" href="#module-pty" title="pty: Pseudo-Terminal Handling for Linux. (Linux)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pty</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="pty.fork">
<code class="descclassname">pty.</code><code class="descname">fork</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pty.fork" title="Permalink to this definition">¶</a></dt>
<dd><p>Fork. Connect the child’s controlling terminal to a pseudo-terminal. Return
value is <code class="docutils literal notranslate"><span class="pre">(pid,</span> <span class="pre">fd)</span></code>. Note that the child  gets <em>pid</em> 0, and the <em>fd</em> is
<em>invalid</em>. The parent’s return value is the <em>pid</em> of the child, and <em>fd</em> is a
file descriptor connected to the child’s controlling terminal (and also to the
child’s standard input and output).</p>
</dd></dl>

<dl class="function">
<dt id="pty.openpty">
<code class="descclassname">pty.</code><code class="descname">openpty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pty.openpty" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a new pseudo-terminal pair, using <a class="reference internal" href="os.html#os.openpty" title="os.openpty"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.openpty()</span></code></a> if possible, or
emulation code for generic Unix systems. Return a pair of file descriptors
<code class="docutils literal notranslate"><span class="pre">(master,</span> <span class="pre">slave)</span></code>, for the master and the slave end, respectively.</p>
</dd></dl>

<dl class="function">
<dt id="pty.spawn">
<code class="descclassname">pty.</code><code class="descname">spawn</code><span class="sig-paren">(</span><em>argv</em><span class="optional">[</span>, <em>master_read</em><span class="optional">[</span>, <em>stdin_read</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#pty.spawn" title="Permalink to this definition">¶</a></dt>
<dd><p>Spawn a process, and connect its controlling terminal with the current
process’s standard io. This is often used to baffle programs which insist on
reading from the controlling terminal.</p>
<p>The functions <em>master_read</em> and <em>stdin_read</em> should be functions which read from
a file descriptor. The defaults try to read 1024 bytes each time they are
called.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tty.html"
                        title="previous chapter">36.8. <code class="docutils literal notranslate"><span class="pre">tty</span></code> — Terminal control functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fcntl.html"
                        title="next chapter">36.10. <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pty.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fcntl.html" title="36.10. fcntl — The fcntl and ioctl system calls"
             >next</a> |</li>
        <li class="right" >
          <a href="tty.html" title="36.8. tty — Terminal control functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�
gxd0d0html/library/pwd.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.2. pwd — The password database &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.3. spwd — The shadow password database" href="spwd.html" />
    <link rel="prev" title="36.1. posix — The most common POSIX system calls" href="posix.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pwd.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="spwd.html" title="36.3. spwd — The shadow password database"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="posix.html" title="36.1. posix — The most common POSIX system calls"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pwd">
<span id="pwd-the-password-database"></span><h1>36.2. <a class="reference internal" href="#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a> — The password database<a class="headerlink" href="#module-pwd" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to the Unix user account and password database.  It
is available on all Unix versions.</p>
<p>Password database entries are reported as a tuple-like object, whose attributes
correspond to the members of the <code class="docutils literal notranslate"><span class="pre">passwd</span></code> structure (Attribute field below,
see <code class="docutils literal notranslate"><span class="pre">&lt;pwd.h&gt;</span></code>):</p>
<table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="29%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Attribute</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_name</span></code></td>
<td>Login name</td>
</tr>
<tr class="row-odd"><td>1</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_passwd</span></code></td>
<td>Optional encrypted password</td>
</tr>
<tr class="row-even"><td>2</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_uid</span></code></td>
<td>Numerical user ID</td>
</tr>
<tr class="row-odd"><td>3</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_gid</span></code></td>
<td>Numerical group ID</td>
</tr>
<tr class="row-even"><td>4</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_gecos</span></code></td>
<td>User name or comment field</td>
</tr>
<tr class="row-odd"><td>5</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_dir</span></code></td>
<td>User home directory</td>
</tr>
<tr class="row-even"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">pw_shell</span></code></td>
<td>User command interpreter</td>
</tr>
</tbody>
</table>
<p>The uid and gid items are integers, all others are strings. <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is
raised if the entry asked for cannot be found.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last" id="index-0">In traditional Unix the field <code class="docutils literal notranslate"><span class="pre">pw_passwd</span></code> usually contains a password
encrypted with a DES derived algorithm (see module <a class="reference internal" href="crypt.html#module-crypt" title="crypt: The crypt() function used to check Unix passwords. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">crypt</span></code></a>).  However most
modern unices  use a so-called <em>shadow password</em> system.  On those unices the
<em>pw_passwd</em> field only contains an asterisk (<code class="docutils literal notranslate"><span class="pre">'*'</span></code>) or the  letter <code class="docutils literal notranslate"><span class="pre">'x'</span></code>
where the encrypted password is stored in a file <code class="file docutils literal notranslate"><span class="pre">/etc/shadow</span></code> which is
not world readable.  Whether the <em>pw_passwd</em> field contains anything useful is
system-dependent.  If available, the <a class="reference internal" href="spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a> module should be used where
access to the encrypted password is required.</p>
</div>
<p>It defines the following items:</p>
<dl class="function">
<dt id="pwd.getpwuid">
<code class="descclassname">pwd.</code><code class="descname">getpwuid</code><span class="sig-paren">(</span><em>uid</em><span class="sig-paren">)</span><a class="headerlink" href="#pwd.getpwuid" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the password database entry for the given numeric user ID.</p>
</dd></dl>

<dl class="function">
<dt id="pwd.getpwnam">
<code class="descclassname">pwd.</code><code class="descname">getpwnam</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#pwd.getpwnam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the password database entry for the given user name.</p>
</dd></dl>

<dl class="function">
<dt id="pwd.getpwall">
<code class="descclassname">pwd.</code><code class="descname">getpwall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#pwd.getpwall" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all available password database entries, in arbitrary order.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="grp.html#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">grp</span></code></a></dt>
<dd>An interface to the group database, similar to this.</dd>
<dt>Module <a class="reference internal" href="spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a></dt>
<dd>An interface to the shadow password database, similar to this.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="posix.html"
                        title="previous chapter">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="spwd.html"
                        title="next chapter">36.3. <code class="docutils literal notranslate"><span class="pre">spwd</span></code> — The shadow password database</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pwd.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="spwd.html" title="36.3. spwd — The shadow password database"
             >next</a> |</li>
        <li class="right" >
          <a href="posix.html" title="36.1. posix — The most common POSIX system calls"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�
�ݜ.�.html/library/py_compile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.10. py_compile — Compile Python source files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.11. compileall — Byte-compile Python libraries" href="compileall.html" />
    <link rel="prev" title="32.9. pyclbr — Python class browser support" href="pyclbr.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/py_compile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compileall.html" title="32.11. compileall — Byte-compile Python libraries"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pyclbr.html" title="32.9. pyclbr — Python class browser support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-py_compile">
<span id="py-compile-compile-python-source-files"></span><h1>32.10. <a class="reference internal" href="#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> — Compile Python source files<a class="headerlink" href="#module-py_compile" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/py_compile.py">Lib/py_compile.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-py_compile" title="py_compile: Generate byte-code files from Python source files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">py_compile</span></code></a> module provides a function to generate a byte-code file
from a source file, and another function used when the module source file is
invoked as a script.</p>
<p>Though not often needed, this function can be useful when installing modules for
shared use, especially if some of the users may not have permission to write the
byte-code cache files in the directory containing the source code.</p>
<dl class="exception">
<dt id="py_compile.PyCompileError">
<em class="property">exception </em><code class="descclassname">py_compile.</code><code class="descname">PyCompileError</code><a class="headerlink" href="#py_compile.PyCompileError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when an error occurs while attempting to compile the file.</p>
</dd></dl>

<dl class="function">
<dt id="py_compile.compile">
<code class="descclassname">py_compile.</code><code class="descname">compile</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>cfile</em><span class="optional">[</span>, <em>dfile</em><span class="optional">[</span>, <em>doraise</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#py_compile.compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile a source file to byte-code and write out the byte-code cache  file.  The
source code is loaded from the file named <em>file</em>.  The  byte-code is written to
<em>cfile</em>, which defaults to <em>file</em> <code class="docutils literal notranslate"><span class="pre">+</span></code> <code class="docutils literal notranslate"><span class="pre">'c'</span></code> (<code class="docutils literal notranslate"><span class="pre">'o'</span></code> if optimization is
enabled in the current interpreter).  If <em>dfile</em> is specified, it is used as the
name of the source file in error messages instead of <em>file</em>.  If <em>doraise</em> is
true, a <a class="reference internal" href="#py_compile.PyCompileError" title="py_compile.PyCompileError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PyCompileError</span></code></a> is raised when an error is encountered while
compiling <em>file</em>. If <em>doraise</em> is false (the default), an error string is
written to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>, but no exception is raised.</p>
</dd></dl>

<dl class="function">
<dt id="py_compile.main">
<code class="descclassname">py_compile.</code><code class="descname">main</code><span class="sig-paren">(</span><span class="optional">[</span><em>args</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#py_compile.main" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile several source files.  The files named in <em>args</em> (or on the command
line, if <em>args</em> is not specified) are compiled and the resulting bytecode is
cached in the normal manner.  This function does not search a directory
structure to locate source files; it only compiles files named explicitly.
If <code class="docutils literal notranslate"><span class="pre">'-'</span></code> is the only parameter in args, the list of files is taken from
standard input.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added support for <code class="docutils literal notranslate"><span class="pre">'-'</span></code>.</p>
</div>
</dd></dl>

<p>When this module is run as a script, the <a class="reference internal" href="#py_compile.main" title="py_compile.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">main()</span></code></a> is used to compile all the
files named on the command line.  The exit status is nonzero if one of the files
could not be compiled.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the nonzero exit status when module is run as a script.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a></dt>
<dd>Utilities to compile all Python source files in a directory tree.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="pyclbr.html"
                        title="previous chapter">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="compileall.html"
                        title="next chapter">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/py_compile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compileall.html" title="32.11. compileall — Byte-compile Python libraries"
             >next</a> |</li>
        <li class="right" >
          <a href="pyclbr.html" title="32.9. pyclbr — Python class browser support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���'�=�=html/library/pyclbr.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.9. pyclbr — Python class browser support &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.10. py_compile — Compile Python source files" href="py_compile.html" />
    <link rel="prev" title="32.8. tabnanny — Detection of ambiguous indentation" href="tabnanny.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pyclbr.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="py_compile.html" title="32.10. py_compile — Compile Python source files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="32.8. tabnanny — Detection of ambiguous indentation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pyclbr">
<span id="pyclbr-python-class-browser-support"></span><h1>32.9. <a class="reference internal" href="#module-pyclbr" title="pyclbr: Supports information extraction for a Python class browser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pyclbr</span></code></a> — Python class browser support<a class="headerlink" href="#module-pyclbr" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pyclbr.py">Lib/pyclbr.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-pyclbr" title="pyclbr: Supports information extraction for a Python class browser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pyclbr</span></code></a> module can be used to determine some limited information
about the classes, methods and top-level functions defined in a module.  The
information provided is sufficient to implement a traditional three-pane
class browser.  The information is extracted from the source code rather
than by importing the module, so this module is safe to use with untrusted
code.  This restriction makes it impossible to use this module with modules
not implemented in Python, including all standard and optional extension
modules.</p>
<dl class="function">
<dt id="pyclbr.readmodule">
<code class="descclassname">pyclbr.</code><code class="descname">readmodule</code><span class="sig-paren">(</span><em>module</em>, <em>path=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pyclbr.readmodule" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a module and return a dictionary mapping class names to class
descriptor objects.  The parameter <em>module</em> should be the name of a
module as a string; it may be the name of a module within a package.  The
<em>path</em> parameter should be a sequence, and is used to augment the value
of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, which is used to locate module source code.</p>
</dd></dl>

<dl class="function">
<dt id="pyclbr.readmodule_ex">
<code class="descclassname">pyclbr.</code><code class="descname">readmodule_ex</code><span class="sig-paren">(</span><em>module</em>, <em>path=None</em><span class="sig-paren">)</span><a class="headerlink" href="#pyclbr.readmodule_ex" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#pyclbr.readmodule" title="pyclbr.readmodule"><code class="xref py py-func docutils literal notranslate"><span class="pre">readmodule()</span></code></a>, but the returned dictionary, in addition to
mapping class names to class descriptor objects, also maps top-level
function names to function descriptor objects.  Moreover, if the module
being read is a package, the key <code class="docutils literal notranslate"><span class="pre">'__path__'</span></code> in the returned
dictionary has as its value a list which contains the package search
path.</p>
</dd></dl>

<div class="section" id="class-objects">
<span id="pyclbr-class-objects"></span><h2>32.9.1. Class Objects<a class="headerlink" href="#class-objects" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code> objects used as values in the dictionary returned by
<a class="reference internal" href="#pyclbr.readmodule" title="pyclbr.readmodule"><code class="xref py py-func docutils literal notranslate"><span class="pre">readmodule()</span></code></a> and <a class="reference internal" href="#pyclbr.readmodule_ex" title="pyclbr.readmodule_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">readmodule_ex()</span></code></a> provide the following data
attributes:</p>
<dl class="attribute">
<dt id="pyclbr.Class.module">
<code class="descclassname">Class.</code><code class="descname">module</code><a class="headerlink" href="#pyclbr.Class.module" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the module defining the class described by the class descriptor.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Class.name">
<code class="descclassname">Class.</code><code class="descname">name</code><a class="headerlink" href="#pyclbr.Class.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the class.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Class.super">
<code class="descclassname">Class.</code><code class="descname">super</code><a class="headerlink" href="#pyclbr.Class.super" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of <code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code> objects which describe the immediate base
classes of the class being described.  Classes which are named as
superclasses but which are not discoverable by <a class="reference internal" href="#pyclbr.readmodule" title="pyclbr.readmodule"><code class="xref py py-func docutils literal notranslate"><span class="pre">readmodule()</span></code></a> are
listed as a string with the class name instead of as <code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code>
objects.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Class.methods">
<code class="descclassname">Class.</code><code class="descname">methods</code><a class="headerlink" href="#pyclbr.Class.methods" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping method names to line numbers.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Class.file">
<code class="descclassname">Class.</code><code class="descname">file</code><a class="headerlink" href="#pyclbr.Class.file" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the file containing the <code class="docutils literal notranslate"><span class="pre">class</span></code> statement defining the class.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Class.lineno">
<code class="descclassname">Class.</code><code class="descname">lineno</code><a class="headerlink" href="#pyclbr.Class.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>The line number of the <code class="docutils literal notranslate"><span class="pre">class</span></code> statement within the file named by
<a class="reference internal" href="#pyclbr.Class.file" title="pyclbr.Class.file"><code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="function-objects">
<span id="pyclbr-function-objects"></span><h2>32.9.2. Function Objects<a class="headerlink" href="#function-objects" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Function</span></code> objects used as values in the dictionary returned by
<a class="reference internal" href="#pyclbr.readmodule_ex" title="pyclbr.readmodule_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">readmodule_ex()</span></code></a> provide the following attributes:</p>
<dl class="attribute">
<dt id="pyclbr.Function.module">
<code class="descclassname">Function.</code><code class="descname">module</code><a class="headerlink" href="#pyclbr.Function.module" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the module defining the function described by the function
descriptor.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Function.name">
<code class="descclassname">Function.</code><code class="descname">name</code><a class="headerlink" href="#pyclbr.Function.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the function.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Function.file">
<code class="descclassname">Function.</code><code class="descname">file</code><a class="headerlink" href="#pyclbr.Function.file" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the file containing the <code class="docutils literal notranslate"><span class="pre">def</span></code> statement defining the function.</p>
</dd></dl>

<dl class="attribute">
<dt id="pyclbr.Function.lineno">
<code class="descclassname">Function.</code><code class="descname">lineno</code><a class="headerlink" href="#pyclbr.Function.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>The line number of the <code class="docutils literal notranslate"><span class="pre">def</span></code> statement within the file named by
<a class="reference internal" href="#pyclbr.Function.file" title="pyclbr.Function.file"><code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code></a>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a><ul>
<li><a class="reference internal" href="#class-objects">32.9.1. Class Objects</a></li>
<li><a class="reference internal" href="#function-objects">32.9.2. Function Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="tabnanny.html"
                        title="previous chapter">32.8. <code class="docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="py_compile.html"
                        title="next chapter">32.10. <code class="docutils literal notranslate"><span class="pre">py_compile</span></code> — Compile Python source files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pyclbr.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="py_compile.html" title="32.10. py_compile — Compile Python source files"
             >next</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="32.8. tabnanny — Detection of ambiguous indentation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Ka�R5R5html/library/pydoc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25.1. pydoc — Documentation generator and online help system &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25.2. doctest — Test interactive Python examples" href="doctest.html" />
    <link rel="prev" title="25. Development Tools" href="development.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pydoc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="doctest.html" title="25.2. doctest — Test interactive Python examples"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="development.html" title="25. Development Tools"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">25. Development Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-pydoc">
<span id="pydoc-documentation-generator-and-online-help-system"></span><h1>25.1. <a class="reference internal" href="#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> — Documentation generator and online help system<a class="headerlink" href="#module-pydoc" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/pydoc.py">Lib/pydoc.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module automatically generates documentation from Python
modules.  The documentation can be presented as pages of text on the console,
served to a Web browser, or saved to HTML files.</p>
<p>For modules, classes, functions and methods, the displayed documentation is
derived from the docstring (i.e. the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> attribute) of the object,
and recursively of its documentable members.  If there is no docstring,
<a class="reference internal" href="#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> tries to obtain a description from the block of comment lines just
above the definition of the class, function or method in the source file, or at
the top of the module (see <a class="reference internal" href="inspect.html#inspect.getcomments" title="inspect.getcomments"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.getcomments()</span></code></a>).</p>
<p>The built-in function <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> invokes the online help system in the
interactive interpreter, which uses <a class="reference internal" href="#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> to generate its documentation
as text on the console.  The same text documentation can also be viewed from
outside the Python interpreter by running <strong class="program">pydoc</strong> as a script at the
operating system’s command prompt. For example, running</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pydoc</span> <span class="n">sys</span>
</pre></div>
</div>
<p>at a shell prompt will display documentation on the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, in a
style similar to the manual pages shown by the Unix <strong class="program">man</strong> command.  The
argument to <strong class="program">pydoc</strong> can be the name of a function, module, or package,
or a dotted reference to a class, method, or function within a module or module
in a package.  If the argument to <strong class="program">pydoc</strong> looks like a path (that is,
it contains the path separator for your operating system, such as a slash in
Unix), and refers to an existing Python source file, then documentation is
produced for that file.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In order to find objects and their documentation, <a class="reference internal" href="#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> imports the
module(s) to be documented.  Therefore, any code on module level will be
executed on that occasion.  Use an <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__':</span></code> guard to
only execute code when a file is invoked as a script and not just imported.</p>
</div>
<p>When printing output to the console, <strong class="program">pydoc</strong> attempts to paginate the
output for easier reading.  If the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PAGER</span></code> environment variable is set,
<strong class="program">pydoc</strong> will use its value as a pagination program.</p>
<p>Specifying a <code class="docutils literal notranslate"><span class="pre">-w</span></code> flag before the argument will cause HTML documentation
to be written out to a file in the current directory, instead of displaying text
on the console.</p>
<p>Specifying a <code class="docutils literal notranslate"><span class="pre">-k</span></code> flag before the argument will search the synopsis
lines of all available modules for the keyword given as the argument, again in a
manner similar to the Unix <strong class="program">man</strong> command.  The synopsis line of a
module is the first line of its documentation string.</p>
<p>You can also use <strong class="program">pydoc</strong> to start an HTTP server on the local machine
that will serve documentation to visiting Web browsers. <strong class="program">pydoc -p 1234</strong>
will start a HTTP server on port 1234, allowing you to browse
the documentation at <code class="docutils literal notranslate"><span class="pre">http://localhost:1234/</span></code> in your preferred Web browser.
<strong class="program">pydoc -g</strong> will start the server and additionally bring up a
small <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>-based graphical interface to help you search for
documentation pages.</p>
<p>When <strong class="program">pydoc</strong> generates documentation, it uses the current environment
and path to locate modules.  Thus, invoking <strong class="program">pydoc spam</strong>
documents precisely the version of the module you would get if you started the
Python interpreter and typed <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">spam</span></code>.</p>
<p>Module docs for core modules are assumed to reside in
<a class="reference external" href="https://docs.python.org/library/">https://docs.python.org/library/</a>.  This can be overridden by setting the
<span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDOCS</span></code> environment variable to a different URL or to a local
directory containing the Library Reference Manual pages.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="development.html"
                        title="previous chapter">25. Development Tools</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="doctest.html"
                        title="next chapter">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pydoc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="doctest.html" title="25.2. doctest — Test interactive Python examples"
             >next</a> |</li>
        <li class="right" >
          <a href="development.html" title="25. Development Tools"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" >25. Development Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6�qK�;�;html/library/pyexpat.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.15. xml.parsers.expat — Fast XML parsing using Expat &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20. Internet Protocols and Support" href="internet.html" />
    <link rel="prev" title="19.14. xml.sax.xmlreader — Interface for XML parsers" href="xml.sax.reader.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/pyexpat.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="internet.html" title="20. Internet Protocols and Support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.sax.reader.html" title="19.14. xml.sax.xmlreader — Interface for XML parsers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.parsers.expat">
<span id="xml-parsers-expat-fast-xml-parsing-using-expat"></span><h1>19.15. <a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> — Fast XML parsing using Expat<a class="headerlink" href="#module-xml.parsers.expat" title="Permalink to this headline">¶</a></h1>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module is not secure against maliciously
constructed data.  If you need to parse untrusted or unauthenticated data see
<a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p id="index-0">The <a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module is a Python interface to the Expat
non-validating XML parser. The module provides a single extension type,
<code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code>, that represents the current state of an XML parser.  After
an <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object has been created, various attributes of the object
can be set to handler functions.  When an XML document is then fed to the
parser, the handler functions are called for the character data and markup in
the XML document.</p>
<p id="index-1">This module uses the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module to provide access to the Expat
parser.  Direct use of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module is deprecated.</p>
<p>This module provides one exception and one type object:</p>
<dl class="exception">
<dt id="xml.parsers.expat.ExpatError">
<em class="property">exception </em><code class="descclassname">xml.parsers.expat.</code><code class="descname">ExpatError</code><a class="headerlink" href="#xml.parsers.expat.ExpatError" title="Permalink to this definition">¶</a></dt>
<dd><p>The exception raised when Expat reports an error.  See section
<a class="reference internal" href="#expaterror-objects"><span class="std std-ref">ExpatError Exceptions</span></a> for more information on interpreting Expat errors.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.parsers.expat.error">
<em class="property">exception </em><code class="descclassname">xml.parsers.expat.</code><code class="descname">error</code><a class="headerlink" href="#xml.parsers.expat.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Alias for <a class="reference internal" href="#xml.parsers.expat.ExpatError" title="xml.parsers.expat.ExpatError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExpatError</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="xml.parsers.expat.XMLParserType">
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XMLParserType</code><a class="headerlink" href="#xml.parsers.expat.XMLParserType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of the return values from the <a class="reference internal" href="#xml.parsers.expat.ParserCreate" title="xml.parsers.expat.ParserCreate"><code class="xref py py-func docutils literal notranslate"><span class="pre">ParserCreate()</span></code></a> function.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module contains two functions:</p>
<dl class="function">
<dt id="xml.parsers.expat.ErrorString">
<code class="descclassname">xml.parsers.expat.</code><code class="descname">ErrorString</code><span class="sig-paren">(</span><em>errno</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.ErrorString" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an explanatory string for a given error number <em>errno</em>.</p>
</dd></dl>

<dl class="function">
<dt id="xml.parsers.expat.ParserCreate">
<code class="descclassname">xml.parsers.expat.</code><code class="descname">ParserCreate</code><span class="sig-paren">(</span><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>namespace_separator</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.ParserCreate" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates and returns a new <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object.   <em>encoding</em>, if specified,
must be a string naming the encoding  used by the XML data.  Expat doesn’t
support as many encodings as Python does, and its repertoire of encodings can’t
be extended; it supports UTF-8, UTF-16, ISO-8859-1 (Latin1), and ASCII.  If
<em>encoding</em> <a class="footnote-reference" href="#id3" id="id1">[1]</a> is given it will override the implicit or explicit encoding of the
document.</p>
<p>Expat can optionally do XML namespace processing for you, enabled by providing a
value for <em>namespace_separator</em>.  The value must be a one-character string; a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised if the string has an illegal length (<code class="docutils literal notranslate"><span class="pre">None</span></code>
is considered the same as omission).  When namespace processing is enabled,
element type names and attribute names that belong to a namespace will be
expanded.  The element name passed to the element handlers
<code class="xref py py-attr docutils literal notranslate"><span class="pre">StartElementHandler</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">EndElementHandler</span></code> will be the
concatenation of the namespace URI, the namespace separator character, and the
local part of the name.  If the namespace separator is a zero byte (<code class="docutils literal notranslate"><span class="pre">chr(0)</span></code>)
then the namespace URI and the local part will be concatenated without any
separator.</p>
<p>For example, if <em>namespace_separator</em> is set to a space character (<code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code>) and
the following document is parsed:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;root</span> <span class="na">xmlns    =</span> <span class="s">&quot;http://default-namespace.org/&quot;</span>
      <span class="na">xmlns:py =</span> <span class="s">&quot;http://www.python.org/ns/&quot;</span><span class="nt">&gt;</span>
  <span class="nt">&lt;py:elem1</span> <span class="nt">/&gt;</span>
  <span class="nt">&lt;elem2</span> <span class="na">xmlns=</span><span class="s">&quot;&quot;</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/root&gt;</span>
</pre></div>
</div>
<p><code class="xref py py-attr docutils literal notranslate"><span class="pre">StartElementHandler</span></code> will receive the following strings for each
element:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">default</span><span class="o">-</span><span class="n">namespace</span><span class="o">.</span><span class="n">org</span><span class="o">/</span> <span class="n">root</span>
<span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">www</span><span class="o">.</span><span class="n">python</span><span class="o">.</span><span class="n">org</span><span class="o">/</span><span class="n">ns</span><span class="o">/</span> <span class="n">elem1</span>
<span class="n">elem2</span>
</pre></div>
</div>
<p>Due to limitations in the <code class="docutils literal notranslate"><span class="pre">Expat</span></code> library used by <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code>,
the <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> instance returned can only be used to parse a single
XML document.  Call <code class="docutils literal notranslate"><span class="pre">ParserCreate</span></code> for each document to provide unique
parser instances.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.libexpat.org/">The Expat XML Parser</a></dt>
<dd>Home page of the Expat project.</dd>
</dl>
</div>
<div class="section" id="xmlparser-objects">
<span id="id2"></span><h2>19.15.1. XMLParser Objects<a class="headerlink" href="#xmlparser-objects" title="Permalink to this headline">¶</a></h2>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> objects have the following methods:</p>
<dl class="method">
<dt id="xml.parsers.expat.xmlparser.Parse">
<code class="descclassname">xmlparser.</code><code class="descname">Parse</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>isfinal</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.Parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses the contents of the string <em>data</em>, calling the appropriate handler
functions to process the parsed data.  <em>isfinal</em> must be true on the final call
to this method; it allows the parsing of a single file in fragments,
not the submission of multiple files.
<em>data</em> can be the empty string at any time.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.ParseFile">
<code class="descclassname">xmlparser.</code><code class="descname">ParseFile</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.ParseFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse XML data reading from the object <em>file</em>.  <em>file</em> only needs to provide
the <code class="docutils literal notranslate"><span class="pre">read(nbytes)</span></code> method, returning the empty string when there’s no more
data.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.SetBase">
<code class="descclassname">xmlparser.</code><code class="descname">SetBase</code><span class="sig-paren">(</span><em>base</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.SetBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the base to be used for resolving relative URIs in system identifiers in
declarations.  Resolving relative identifiers is left to the application: this
value will be passed through as the <em>base</em> argument to the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.ExternalEntityRefHandler" title="xml.parsers.expat.xmlparser.ExternalEntityRefHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">ExternalEntityRefHandler()</span></code></a>, <a class="reference internal" href="#xml.parsers.expat.xmlparser.NotationDeclHandler" title="xml.parsers.expat.xmlparser.NotationDeclHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">NotationDeclHandler()</span></code></a>, and
<a class="reference internal" href="#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler" title="xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">UnparsedEntityDeclHandler()</span></code></a> functions.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.GetBase">
<code class="descclassname">xmlparser.</code><code class="descname">GetBase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.GetBase" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a string containing the base set by a previous call to <a class="reference internal" href="#xml.parsers.expat.xmlparser.SetBase" title="xml.parsers.expat.xmlparser.SetBase"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SetBase()</span></code></a>,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if  <a class="reference internal" href="#xml.parsers.expat.xmlparser.SetBase" title="xml.parsers.expat.xmlparser.SetBase"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SetBase()</span></code></a> hasn’t been called.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.GetInputContext">
<code class="descclassname">xmlparser.</code><code class="descname">GetInputContext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.GetInputContext" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the input data that generated the current event as a string. The data is
in the encoding of the entity which contains the text. When called while an
event handler is not active, the return value is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.ExternalEntityParserCreate">
<code class="descclassname">xmlparser.</code><code class="descname">ExternalEntityParserCreate</code><span class="sig-paren">(</span><em>context</em><span class="optional">[</span>, <em>encoding</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.ExternalEntityParserCreate" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a “child” parser which can be used to parse an external parsed entity
referred to by content parsed by the parent parser.  The <em>context</em> parameter
should be the string passed to the <a class="reference internal" href="#xml.parsers.expat.xmlparser.ExternalEntityRefHandler" title="xml.parsers.expat.xmlparser.ExternalEntityRefHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ExternalEntityRefHandler()</span></code></a> handler
function, described below. The child parser is created with the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.ordered_attributes" title="xml.parsers.expat.xmlparser.ordered_attributes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ordered_attributes</span></code></a>, <a class="reference internal" href="#xml.parsers.expat.xmlparser.returns_unicode" title="xml.parsers.expat.xmlparser.returns_unicode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returns_unicode</span></code></a> and
<a class="reference internal" href="#xml.parsers.expat.xmlparser.specified_attributes" title="xml.parsers.expat.xmlparser.specified_attributes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">specified_attributes</span></code></a> set to the values of this parser.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.SetParamEntityParsing">
<code class="descclassname">xmlparser.</code><code class="descname">SetParamEntityParsing</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.SetParamEntityParsing" title="Permalink to this definition">¶</a></dt>
<dd><p>Control parsing of parameter entities (including the external DTD subset).
Possible <em>flag</em> values are <code class="xref py py-const docutils literal notranslate"><span class="pre">XML_PARAM_ENTITY_PARSING_NEVER</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE</span></code> and
<code class="xref py py-const docutils literal notranslate"><span class="pre">XML_PARAM_ENTITY_PARSING_ALWAYS</span></code>.  Return true if setting the flag
was successful.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.UseForeignDTD">
<code class="descclassname">xmlparser.</code><code class="descname">UseForeignDTD</code><span class="sig-paren">(</span><span class="optional">[</span><em>flag</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.UseForeignDTD" title="Permalink to this definition">¶</a></dt>
<dd><p>Calling this with a true value for <em>flag</em> (the default) will cause Expat to call
the <a class="reference internal" href="#xml.parsers.expat.xmlparser.ExternalEntityRefHandler" title="xml.parsers.expat.xmlparser.ExternalEntityRefHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ExternalEntityRefHandler</span></code></a> with <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> for all arguments to
allow an alternate DTD to be loaded.  If the document does not contain a
document type declaration, the <a class="reference internal" href="#xml.parsers.expat.xmlparser.ExternalEntityRefHandler" title="xml.parsers.expat.xmlparser.ExternalEntityRefHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ExternalEntityRefHandler</span></code></a> will still be
called, but the <a class="reference internal" href="#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler" title="xml.parsers.expat.xmlparser.StartDoctypeDeclHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">StartDoctypeDeclHandler</span></code></a> and
<a class="reference internal" href="#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler" title="xml.parsers.expat.xmlparser.EndDoctypeDeclHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EndDoctypeDeclHandler</span></code></a> will not be called.</p>
<p>Passing a false value for <em>flag</em> will cancel a previous call that passed a true
value, but otherwise has no effect.</p>
<p>This method can only be called before the <a class="reference internal" href="#xml.parsers.expat.xmlparser.Parse" title="xml.parsers.expat.xmlparser.Parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Parse()</span></code></a> or <a class="reference internal" href="#xml.parsers.expat.xmlparser.ParseFile" title="xml.parsers.expat.xmlparser.ParseFile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ParseFile()</span></code></a>
methods are called; calling it after either of those have been called causes
<a class="reference internal" href="#xml.parsers.expat.ExpatError" title="xml.parsers.expat.ExpatError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExpatError</span></code></a> to be raised with the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a> attribute set to
<code class="xref py py-const docutils literal notranslate"><span class="pre">errors.XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> objects have the following attributes:</p>
<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.buffer_size">
<code class="descclassname">xmlparser.</code><code class="descname">buffer_size</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.buffer_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the buffer used when <a class="reference internal" href="#xml.parsers.expat.xmlparser.buffer_text" title="xml.parsers.expat.xmlparser.buffer_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_text</span></code></a> is true.
A new buffer size can be set by assigning a new integer value
to this attribute.
When the size is changed, the buffer will be flushed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The buffer size can now be changed.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.buffer_text">
<code class="descclassname">xmlparser.</code><code class="descname">buffer_text</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.buffer_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Setting this to true causes the <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object to buffer textual
content returned by Expat to avoid multiple calls to the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.CharacterDataHandler" title="xml.parsers.expat.xmlparser.CharacterDataHandler"><code class="xref py py-meth docutils literal notranslate"><span class="pre">CharacterDataHandler()</span></code></a> callback whenever possible.  This can improve
performance substantially since Expat normally breaks character data into chunks
at every line ending.  This attribute is false by default, and may be changed at
any time.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.buffer_used">
<code class="descclassname">xmlparser.</code><code class="descname">buffer_used</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.buffer_used" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#xml.parsers.expat.xmlparser.buffer_text" title="xml.parsers.expat.xmlparser.buffer_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_text</span></code></a> is enabled, the number of bytes stored in the buffer.
These bytes represent UTF-8 encoded text.  This attribute has no meaningful
interpretation when <a class="reference internal" href="#xml.parsers.expat.xmlparser.buffer_text" title="xml.parsers.expat.xmlparser.buffer_text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_text</span></code></a> is false.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.ordered_attributes">
<code class="descclassname">xmlparser.</code><code class="descname">ordered_attributes</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.ordered_attributes" title="Permalink to this definition">¶</a></dt>
<dd><p>Setting this attribute to a non-zero integer causes the attributes to be
reported as a list rather than a dictionary.  The attributes are presented in
the order found in the document text.  For each attribute, two list entries are
presented: the attribute name and the attribute value.  (Older versions of this
module also used this format.)  By default, this attribute is false; it may be
changed at any time.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.returns_unicode">
<code class="descclassname">xmlparser.</code><code class="descname">returns_unicode</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.returns_unicode" title="Permalink to this definition">¶</a></dt>
<dd><p>If this attribute is set to a non-zero integer, the handler functions will be
passed Unicode strings.  If <a class="reference internal" href="#xml.parsers.expat.xmlparser.returns_unicode" title="xml.parsers.expat.xmlparser.returns_unicode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returns_unicode</span></code></a> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, 8-bit
strings containing UTF-8 encoded data will be passed to the handlers.  This is
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> by default when Python is built with Unicode support.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 1.6: </span>Can be changed at any time to affect the result type.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.specified_attributes">
<code class="descclassname">xmlparser.</code><code class="descname">specified_attributes</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.specified_attributes" title="Permalink to this definition">¶</a></dt>
<dd><p>If set to a non-zero integer, the parser will report only those attributes which
were specified in the document instance and not those which were derived from
attribute declarations.  Applications which set this need to be especially
careful to use what additional information is available from the declarations as
needed to comply with the standards for the behavior of XML processors.  By
default, this attribute is false; it may be changed at any time.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<p>The following attributes contain values relating to the most recent error
encountered by an <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object, and will only have correct values
once a call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">Parse()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">ParseFile()</span></code> has raised an
<a class="reference internal" href="#xml.parsers.expat.ExpatError" title="xml.parsers.expat.ExpatError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">xml.parsers.expat.ExpatError</span></code></a> exception.</p>
<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.ErrorByteIndex">
<code class="descclassname">xmlparser.</code><code class="descname">ErrorByteIndex</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.ErrorByteIndex" title="Permalink to this definition">¶</a></dt>
<dd><p>Byte index at which an error occurred.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.ErrorCode">
<code class="descclassname">xmlparser.</code><code class="descname">ErrorCode</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.ErrorCode" title="Permalink to this definition">¶</a></dt>
<dd><p>Numeric code specifying the problem.  This value can be passed to the
<a class="reference internal" href="#xml.parsers.expat.ErrorString" title="xml.parsers.expat.ErrorString"><code class="xref py py-func docutils literal notranslate"><span class="pre">ErrorString()</span></code></a> function, or compared to one of the constants defined in the
<code class="docutils literal notranslate"><span class="pre">errors</span></code> object.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.ErrorColumnNumber">
<code class="descclassname">xmlparser.</code><code class="descname">ErrorColumnNumber</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.ErrorColumnNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Column number at which an error occurred.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.ErrorLineNumber">
<code class="descclassname">xmlparser.</code><code class="descname">ErrorLineNumber</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.ErrorLineNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Line number at which an error occurred.</p>
</dd></dl>

<p>The following attributes contain values relating to the current parse location
in an <code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object.  During a callback reporting a parse event they
indicate the location of the first of the sequence of characters that generated
the event.  When called outside of a callback, the position indicated will be
just past the last parse event (regardless of whether there was an associated
callback).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.CurrentByteIndex">
<code class="descclassname">xmlparser.</code><code class="descname">CurrentByteIndex</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.CurrentByteIndex" title="Permalink to this definition">¶</a></dt>
<dd><p>Current byte index in the parser input.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.CurrentColumnNumber">
<code class="descclassname">xmlparser.</code><code class="descname">CurrentColumnNumber</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.CurrentColumnNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Current column number in the parser input.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.xmlparser.CurrentLineNumber">
<code class="descclassname">xmlparser.</code><code class="descname">CurrentLineNumber</code><a class="headerlink" href="#xml.parsers.expat.xmlparser.CurrentLineNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Current line number in the parser input.</p>
</dd></dl>

<p>Here is the list of handlers that can be set.  To set a handler on an
<code class="xref py py-class docutils literal notranslate"><span class="pre">xmlparser</span></code> object <em>o</em>, use <code class="docutils literal notranslate"><span class="pre">o.handlername</span> <span class="pre">=</span> <span class="pre">func</span></code>.  <em>handlername</em> must
be taken from the following list, and <em>func</em> must be a callable object accepting
the correct number of arguments.  The arguments are all strings, unless
otherwise stated.</p>
<dl class="method">
<dt id="xml.parsers.expat.xmlparser.XmlDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">XmlDeclHandler</code><span class="sig-paren">(</span><em>version</em>, <em>encoding</em>, <em>standalone</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.XmlDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the XML declaration is parsed.  The XML declaration is the
(optional) declaration of the applicable version of the XML recommendation, the
encoding of the document text, and an optional “standalone” declaration.
<em>version</em> and <em>encoding</em> will be strings of the type dictated by the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.returns_unicode" title="xml.parsers.expat.xmlparser.returns_unicode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returns_unicode</span></code></a> attribute, and <em>standalone</em> will be <code class="docutils literal notranslate"><span class="pre">1</span></code> if the
document is declared standalone, <code class="docutils literal notranslate"><span class="pre">0</span></code> if it is declared not to be standalone,
or <code class="docutils literal notranslate"><span class="pre">-1</span></code> if the standalone clause was omitted. This is only available with
Expat version 1.95.0 or newer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.StartDoctypeDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">StartDoctypeDeclHandler</code><span class="sig-paren">(</span><em>doctypeName</em>, <em>systemId</em>, <em>publicId</em>, <em>has_internal_subset</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.StartDoctypeDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when Expat begins parsing the document type declaration (<code class="docutils literal notranslate"><span class="pre">&lt;!DOCTYPE</span>
<span class="pre">...</span></code>).  The <em>doctypeName</em> is provided exactly as presented.  The <em>systemId</em> and
<em>publicId</em> parameters give the system and public identifiers if specified, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if omitted.  <em>has_internal_subset</em> will be true if the document
contains and internal document declaration subset. This requires Expat version
1.2 or newer.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.EndDoctypeDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">EndDoctypeDeclHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when Expat is done parsing the document type declaration. This requires
Expat version 1.2 or newer.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.ElementDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">ElementDeclHandler</code><span class="sig-paren">(</span><em>name</em>, <em>model</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.ElementDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called once for each element type declaration.  <em>name</em> is the name of the
element type, and <em>model</em> is a representation of the content model.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.AttlistDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">AttlistDeclHandler</code><span class="sig-paren">(</span><em>elname</em>, <em>attname</em>, <em>type</em>, <em>default</em>, <em>required</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.AttlistDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for each declared attribute for an element type.  If an attribute list
declaration declares three attributes, this handler is called three times, once
for each attribute.  <em>elname</em> is the name of the element to which the
declaration applies and <em>attname</em> is the name of the attribute declared.  The
attribute type is a string passed as <em>type</em>; the possible values are
<code class="docutils literal notranslate"><span class="pre">'CDATA'</span></code>, <code class="docutils literal notranslate"><span class="pre">'ID'</span></code>, <code class="docutils literal notranslate"><span class="pre">'IDREF'</span></code>, … <em>default</em> gives the default value for
the attribute used when the attribute is not specified by the document instance,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is no default value (<code class="docutils literal notranslate"><span class="pre">#IMPLIED</span></code> values).  If the
attribute is required to be given in the document instance, <em>required</em> will be
true. This requires Expat version 1.95.0 or newer.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.StartElementHandler">
<code class="descclassname">xmlparser.</code><code class="descname">StartElementHandler</code><span class="sig-paren">(</span><em>name</em>, <em>attributes</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.StartElementHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for the start of every element.  <em>name</em> is a string containing the
element name, and <em>attributes</em> is a dictionary mapping attribute names to their
values.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.EndElementHandler">
<code class="descclassname">xmlparser.</code><code class="descname">EndElementHandler</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.EndElementHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for the end of every element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.ProcessingInstructionHandler">
<code class="descclassname">xmlparser.</code><code class="descname">ProcessingInstructionHandler</code><span class="sig-paren">(</span><em>target</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.ProcessingInstructionHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for every processing instruction.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.CharacterDataHandler">
<code class="descclassname">xmlparser.</code><code class="descname">CharacterDataHandler</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.CharacterDataHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for character data.  This will be called for normal character data, CDATA
marked content, and ignorable whitespace.  Applications which must distinguish
these cases can use the <a class="reference internal" href="#xml.parsers.expat.xmlparser.StartCdataSectionHandler" title="xml.parsers.expat.xmlparser.StartCdataSectionHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">StartCdataSectionHandler</span></code></a>,
<a class="reference internal" href="#xml.parsers.expat.xmlparser.EndCdataSectionHandler" title="xml.parsers.expat.xmlparser.EndCdataSectionHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EndCdataSectionHandler</span></code></a>, and <a class="reference internal" href="#xml.parsers.expat.xmlparser.ElementDeclHandler" title="xml.parsers.expat.xmlparser.ElementDeclHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ElementDeclHandler</span></code></a> callbacks to
collect the required information.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">UnparsedEntityDeclHandler</code><span class="sig-paren">(</span><em>entityName</em>, <em>base</em>, <em>systemId</em>, <em>publicId</em>, <em>notationName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.UnparsedEntityDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for unparsed (NDATA) entity declarations.  This is only present for
version 1.2 of the Expat library; for more recent versions, use
<a class="reference internal" href="#xml.parsers.expat.xmlparser.EntityDeclHandler" title="xml.parsers.expat.xmlparser.EntityDeclHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EntityDeclHandler</span></code></a> instead.  (The underlying function in the Expat
library has been declared obsolete.)</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.EntityDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">EntityDeclHandler</code><span class="sig-paren">(</span><em>entityName</em>, <em>is_parameter_entity</em>, <em>value</em>, <em>base</em>, <em>systemId</em>, <em>publicId</em>, <em>notationName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.EntityDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for all entity declarations.  For parameter and internal entities,
<em>value</em> will be a string giving the declared contents of the entity; this will
be <code class="docutils literal notranslate"><span class="pre">None</span></code> for external entities.  The <em>notationName</em> parameter will be
<code class="docutils literal notranslate"><span class="pre">None</span></code> for parsed entities, and the name of the notation for unparsed
entities. <em>is_parameter_entity</em> will be true if the entity is a parameter entity
or false for general entities (most applications only need to be concerned with
general entities). This is only available starting with version 1.95.0 of the
Expat library.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.NotationDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">NotationDeclHandler</code><span class="sig-paren">(</span><em>notationName</em>, <em>base</em>, <em>systemId</em>, <em>publicId</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.NotationDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for notation declarations.  <em>notationName</em>, <em>base</em>, and <em>systemId</em>, and
<em>publicId</em> are strings if given.  If the public identifier is omitted,
<em>publicId</em> will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.StartNamespaceDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">StartNamespaceDeclHandler</code><span class="sig-paren">(</span><em>prefix</em>, <em>uri</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an element contains a namespace declaration.  Namespace declarations
are processed before the <a class="reference internal" href="#xml.parsers.expat.xmlparser.StartElementHandler" title="xml.parsers.expat.xmlparser.StartElementHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">StartElementHandler</span></code></a> is called for the element
on which declarations are placed.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.EndNamespaceDeclHandler">
<code class="descclassname">xmlparser.</code><code class="descname">EndNamespaceDeclHandler</code><span class="sig-paren">(</span><em>prefix</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.EndNamespaceDeclHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the closing tag is reached for an element  that contained a
namespace declaration.  This is called once for each namespace declaration on
the element in the reverse of the order for which the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.StartNamespaceDeclHandler" title="xml.parsers.expat.xmlparser.StartNamespaceDeclHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">StartNamespaceDeclHandler</span></code></a> was called to indicate the start of each
namespace declaration’s scope.  Calls to this handler are made after the
corresponding <a class="reference internal" href="#xml.parsers.expat.xmlparser.EndElementHandler" title="xml.parsers.expat.xmlparser.EndElementHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EndElementHandler</span></code></a> for the end of the element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.CommentHandler">
<code class="descclassname">xmlparser.</code><code class="descname">CommentHandler</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.CommentHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for comments.  <em>data</em> is the text of the comment, excluding the leading
<code class="docutils literal notranslate"><span class="pre">'&lt;!-</span></code><code class="docutils literal notranslate"><span class="pre">-'</span></code> and trailing <code class="docutils literal notranslate"><span class="pre">'-</span></code><code class="docutils literal notranslate"><span class="pre">-&gt;'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.StartCdataSectionHandler">
<code class="descclassname">xmlparser.</code><code class="descname">StartCdataSectionHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.StartCdataSectionHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called at the start of a CDATA section.  This and <a class="reference internal" href="#xml.parsers.expat.xmlparser.EndCdataSectionHandler" title="xml.parsers.expat.xmlparser.EndCdataSectionHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">EndCdataSectionHandler</span></code></a>
are needed to be able to identify the syntactical start and end for CDATA
sections.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.EndCdataSectionHandler">
<code class="descclassname">xmlparser.</code><code class="descname">EndCdataSectionHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.EndCdataSectionHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called at the end of a CDATA section.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.DefaultHandler">
<code class="descclassname">xmlparser.</code><code class="descname">DefaultHandler</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.DefaultHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for any characters in the XML document for which no applicable handler
has been specified.  This means characters that are part of a construct which
could be reported, but for which no handler has been supplied.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.DefaultHandlerExpand">
<code class="descclassname">xmlparser.</code><code class="descname">DefaultHandlerExpand</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.DefaultHandlerExpand" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the same as the <a class="reference internal" href="#xml.parsers.expat.xmlparser.DefaultHandler" title="xml.parsers.expat.xmlparser.DefaultHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">DefaultHandler()</span></code></a>,  but doesn’t inhibit expansion
of internal entities. The entity reference will not be passed to the default
handler.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.NotStandaloneHandler">
<code class="descclassname">xmlparser.</code><code class="descname">NotStandaloneHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.NotStandaloneHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called if the XML document hasn’t been declared as being a standalone document.
This happens when there is an external subset or a reference to a parameter
entity, but the XML declaration does not set standalone to <code class="docutils literal notranslate"><span class="pre">yes</span></code> in an XML
declaration.  If this handler returns <code class="docutils literal notranslate"><span class="pre">0</span></code>, then the parser will raise an
<code class="xref py py-const docutils literal notranslate"><span class="pre">XML_ERROR_NOT_STANDALONE</span></code> error.  If this handler is not set, no
exception is raised by the parser for this condition.</p>
</dd></dl>

<dl class="method">
<dt id="xml.parsers.expat.xmlparser.ExternalEntityRefHandler">
<code class="descclassname">xmlparser.</code><code class="descname">ExternalEntityRefHandler</code><span class="sig-paren">(</span><em>context</em>, <em>base</em>, <em>systemId</em>, <em>publicId</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.parsers.expat.xmlparser.ExternalEntityRefHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Called for references to external entities.  <em>base</em> is the current base, as set
by a previous call to <a class="reference internal" href="#xml.parsers.expat.xmlparser.SetBase" title="xml.parsers.expat.xmlparser.SetBase"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SetBase()</span></code></a>.  The public and system identifiers,
<em>systemId</em> and <em>publicId</em>, are strings if given; if the public identifier is not
given, <em>publicId</em> will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The <em>context</em> value is opaque and should
only be used as described below.</p>
<p>For external entities to be parsed, this handler must be implemented. It is
responsible for creating the sub-parser using
<code class="docutils literal notranslate"><span class="pre">ExternalEntityParserCreate(context)</span></code>, initializing it with the appropriate
callbacks, and parsing the entity.  This handler should return an integer; if it
returns <code class="docutils literal notranslate"><span class="pre">0</span></code>, the parser will raise an
<code class="xref py py-const docutils literal notranslate"><span class="pre">XML_ERROR_EXTERNAL_ENTITY_HANDLING</span></code> error, otherwise parsing will
continue.</p>
<p>If this handler is not provided, external entities are reported by the
<a class="reference internal" href="#xml.parsers.expat.xmlparser.DefaultHandler" title="xml.parsers.expat.xmlparser.DefaultHandler"><code class="xref py py-attr docutils literal notranslate"><span class="pre">DefaultHandler</span></code></a> callback, if provided.</p>
</dd></dl>

</div>
<div class="section" id="expaterror-exceptions">
<span id="expaterror-objects"></span><h2>19.15.2. ExpatError Exceptions<a class="headerlink" href="#expaterror-exceptions" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#xml.parsers.expat.ExpatError" title="xml.parsers.expat.ExpatError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExpatError</span></code></a> exceptions have a number of interesting attributes:</p>
<dl class="attribute">
<dt id="xml.parsers.expat.ExpatError.code">
<code class="descclassname">ExpatError.</code><code class="descname">code</code><a class="headerlink" href="#xml.parsers.expat.ExpatError.code" title="Permalink to this definition">¶</a></dt>
<dd><p>Expat’s internal error number for the specific error.  This will match one of
the constants defined in the <code class="docutils literal notranslate"><span class="pre">errors</span></code> object from this module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.ExpatError.lineno">
<code class="descclassname">ExpatError.</code><code class="descname">lineno</code><a class="headerlink" href="#xml.parsers.expat.ExpatError.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Line number on which the error was detected.  The first line is numbered <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="xml.parsers.expat.ExpatError.offset">
<code class="descclassname">ExpatError.</code><code class="descname">offset</code><a class="headerlink" href="#xml.parsers.expat.ExpatError.offset" title="Permalink to this definition">¶</a></dt>
<dd><p>Character offset into the line where the error occurred.  The first column is
numbered <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="example">
<span id="expat-example"></span><h2>19.15.3. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The following program defines three handlers that just print out their
arguments.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.parsers.expat</span>

<span class="c1"># 3 handler functions</span>
<span class="k">def</span> <span class="nf">start_element</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;Start element:&#39;</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">attrs</span>
<span class="k">def</span> <span class="nf">end_element</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;End element:&#39;</span><span class="p">,</span> <span class="n">name</span>
<span class="k">def</span> <span class="nf">char_data</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;Character data:&#39;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">xml</span><span class="o">.</span><span class="n">parsers</span><span class="o">.</span><span class="n">expat</span><span class="o">.</span><span class="n">ParserCreate</span><span class="p">()</span>

<span class="n">p</span><span class="o">.</span><span class="n">StartElementHandler</span> <span class="o">=</span> <span class="n">start_element</span>
<span class="n">p</span><span class="o">.</span><span class="n">EndElementHandler</span> <span class="o">=</span> <span class="n">end_element</span>
<span class="n">p</span><span class="o">.</span><span class="n">CharacterDataHandler</span> <span class="o">=</span> <span class="n">char_data</span>

<span class="n">p</span><span class="o">.</span><span class="n">Parse</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="s2">&lt;parent id=&quot;top&quot;&gt;&lt;child1 name=&quot;paul&quot;&gt;Text goes here&lt;/child1&gt;</span>
<span class="s2">&lt;child2 name=&quot;fred&quot;&gt;More text&lt;/child2&gt;</span>
<span class="s2">&lt;/parent&gt;&quot;&quot;&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>The output from this program is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Start</span> <span class="n">element</span><span class="p">:</span> <span class="n">parent</span> <span class="p">{</span><span class="s1">&#39;id&#39;</span><span class="p">:</span> <span class="s1">&#39;top&#39;</span><span class="p">}</span>
<span class="n">Start</span> <span class="n">element</span><span class="p">:</span> <span class="n">child1</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;paul&#39;</span><span class="p">}</span>
<span class="n">Character</span> <span class="n">data</span><span class="p">:</span> <span class="s1">&#39;Text goes here&#39;</span>
<span class="n">End</span> <span class="n">element</span><span class="p">:</span> <span class="n">child1</span>
<span class="n">Character</span> <span class="n">data</span><span class="p">:</span> <span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="n">Start</span> <span class="n">element</span><span class="p">:</span> <span class="n">child2</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s1">&#39;fred&#39;</span><span class="p">}</span>
<span class="n">Character</span> <span class="n">data</span><span class="p">:</span> <span class="s1">&#39;More text&#39;</span>
<span class="n">End</span> <span class="n">element</span><span class="p">:</span> <span class="n">child2</span>
<span class="n">Character</span> <span class="n">data</span><span class="p">:</span> <span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="n">End</span> <span class="n">element</span><span class="p">:</span> <span class="n">parent</span>
</pre></div>
</div>
</div>
<div class="section" id="content-model-descriptions">
<span id="expat-content-models"></span><h2>19.15.4. Content Model Descriptions<a class="headerlink" href="#content-model-descriptions" title="Permalink to this headline">¶</a></h2>
<p>Content models are described using nested tuples.  Each tuple contains four
values: the type, the quantifier, the name, and a tuple of children.  Children
are simply additional content model descriptions.</p>
<p>The values of the first two fields are constants defined in the <code class="docutils literal notranslate"><span class="pre">model</span></code> object
of the <a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module.  These constants can be collected in two
groups: the model type group and the quantifier group.</p>
<p>The constants in the model type group are:</p>
<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_ANY</code></dt>
<dd><p>The element named by the model name was declared to have a content model of
<code class="docutils literal notranslate"><span class="pre">ANY</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_CHOICE</code></dt>
<dd><p>The named element allows a choice from a number of options; this is used for
content models such as <code class="docutils literal notranslate"><span class="pre">(A</span> <span class="pre">|</span> <span class="pre">B</span> <span class="pre">|</span> <span class="pre">C)</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_EMPTY</code></dt>
<dd><p>Elements which are declared to be <code class="docutils literal notranslate"><span class="pre">EMPTY</span></code> have this model type.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_MIXED</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_NAME</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CTYPE_SEQ</code></dt>
<dd><p>Models which represent a series of models which follow one after the other are
indicated with this model type.  This is used for models such as <code class="docutils literal notranslate"><span class="pre">(A,</span> <span class="pre">B,</span> <span class="pre">C)</span></code>.</p>
</dd></dl>

<p>The constants in the quantifier group are:</p>
<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CQUANT_NONE</code></dt>
<dd><p>No modifier is given, so it can appear exactly once, as for <code class="docutils literal notranslate"><span class="pre">A</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CQUANT_OPT</code></dt>
<dd><p>The model is optional: it can appear once or not at all, as for <code class="docutils literal notranslate"><span class="pre">A?</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CQUANT_PLUS</code></dt>
<dd><p>The model must occur one or more times (like <code class="docutils literal notranslate"><span class="pre">A+</span></code>).</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_CQUANT_REP</code></dt>
<dd><p>The model must occur zero or more times, as for <code class="docutils literal notranslate"><span class="pre">A*</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="expat-error-constants">
<span id="expat-errors"></span><h2>19.15.5. Expat error constants<a class="headerlink" href="#expat-error-constants" title="Permalink to this headline">¶</a></h2>
<p>The following constants are provided in the <code class="docutils literal notranslate"><span class="pre">errors</span></code> object of the
<a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module.  These constants are useful in interpreting
some of the attributes of the <a class="reference internal" href="#xml.parsers.expat.ExpatError" title="xml.parsers.expat.ExpatError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExpatError</span></code></a> exception objects raised when an
error has occurred.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">errors</span></code> object has the following attributes:</p>
<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_ASYNC_ENTITY</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF</code></dt>
<dd><p>An entity reference in an attribute value referred to an external entity instead
of an internal entity.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_BAD_CHAR_REF</code></dt>
<dd><p>A character reference referred to a character which is illegal in XML (for
example, character <code class="docutils literal notranslate"><span class="pre">0</span></code>, or ‘<code class="docutils literal notranslate"><span class="pre">&amp;#0;</span></code>’).</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_BINARY_ENTITY_REF</code></dt>
<dd><p>An entity reference referred to an entity which was declared with a notation, so
cannot be parsed.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_DUPLICATE_ATTRIBUTE</code></dt>
<dd><p>An attribute was used more than once in a start tag.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_INCORRECT_ENCODING</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_INVALID_TOKEN</code></dt>
<dd><p>Raised when an input byte could not properly be assigned to a character; for
example, a NUL byte (value <code class="docutils literal notranslate"><span class="pre">0</span></code>) in a UTF-8 input stream.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_JUNK_AFTER_DOC_ELEMENT</code></dt>
<dd><p>Something other than whitespace occurred after the document element.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_MISPLACED_XML_PI</code></dt>
<dd><p>An XML declaration was found somewhere other than the start of the input data.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_NO_ELEMENTS</code></dt>
<dd><p>The document contains no elements (XML requires all documents to contain exactly
one top-level element)..</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_NO_MEMORY</code></dt>
<dd><p>Expat was not able to allocate memory internally.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_PARAM_ENTITY_REF</code></dt>
<dd><p>A parameter entity reference was found where it was not allowed.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_PARTIAL_CHAR</code></dt>
<dd><p>An incomplete character was found in the input.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_RECURSIVE_ENTITY_REF</code></dt>
<dd><p>An entity reference contained another reference to the same entity; possibly via
a different name, and possibly indirectly.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_SYNTAX</code></dt>
<dd><p>Some unspecified syntax error was encountered.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_TAG_MISMATCH</code></dt>
<dd><p>An end tag did not match the innermost open start tag.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNCLOSED_TOKEN</code></dt>
<dd><p>Some token (such as a start tag) was not closed before the end of the stream or
the next token was encountered.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNDEFINED_ENTITY</code></dt>
<dd><p>A reference was made to an entity which was not defined.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNKNOWN_ENCODING</code></dt>
<dd><p>The document encoding is not supported by Expat.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNCLOSED_CDATA_SECTION</code></dt>
<dd><p>A CDATA marked section was not closed.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_EXTERNAL_ENTITY_HANDLING</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_NOT_STANDALONE</code></dt>
<dd><p>The parser determined that the document was not “standalone” though it declared
itself to be in the XML declaration, and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">NotStandaloneHandler</span></code> was
set and returned <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNEXPECTED_STATE</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_ENTITY_DECLARED_IN_PE</code></dt>
<dd></dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_FEATURE_REQUIRES_XML_DTD</code></dt>
<dd><p>An operation was requested that requires DTD support to be compiled in, but
Expat was configured without DTD support.  This should never be reported by a
standard build of the <a class="reference internal" href="#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING</code></dt>
<dd><p>A behavioral change was requested after parsing started that can only be changed
before parsing has started.  This is (currently) only raised by
<code class="xref py py-meth docutils literal notranslate"><span class="pre">UseForeignDTD()</span></code>.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNBOUND_PREFIX</code></dt>
<dd><p>An undeclared prefix was found when namespace processing was enabled.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_UNDECLARING_PREFIX</code></dt>
<dd><p>The document attempted to remove the namespace declaration associated with a
prefix.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_INCOMPLETE_PE</code></dt>
<dd><p>A parameter entity contained incomplete markup.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_XML_DECL</code></dt>
<dd><p>The document contained no document element at all.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_TEXT_DECL</code></dt>
<dd><p>There was an error parsing a text declaration in an external entity.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_PUBLICID</code></dt>
<dd><p>Characters were found in the public id that are not allowed.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_SUSPENDED</code></dt>
<dd><p>The requested operation was made on a suspended parser, but isn’t allowed.  This
includes attempts to provide additional input or to stop the parser.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_NOT_SUSPENDED</code></dt>
<dd><p>An attempt to resume the parser was made when the parser had not been suspended.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_ABORTED</code></dt>
<dd><p>This should not be reported to Python applications.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_FINISHED</code></dt>
<dd><p>The requested operation was made on a parser which was finished parsing input,
but isn’t allowed.  This includes attempts to provide additional input or to
stop the parser.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descclassname">xml.parsers.expat.</code><code class="descname">XML_ERROR_SUSPEND_PE</code></dt>
<dd></dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The encoding string included in XML output should conform to the
appropriate standards. For example, “UTF-8” is valid, but “UTF8” is
not. See <a class="reference external" href="https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl">https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl</a>
and <a class="reference external" href="https://www.iana.org/assignments/character-sets/character-sets.xhtml">https://www.iana.org/assignments/character-sets/character-sets.xhtml</a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a><ul>
<li><a class="reference internal" href="#xmlparser-objects">19.15.1. XMLParser Objects</a></li>
<li><a class="reference internal" href="#expaterror-exceptions">19.15.2. ExpatError Exceptions</a></li>
<li><a class="reference internal" href="#example">19.15.3. Example</a></li>
<li><a class="reference internal" href="#content-model-descriptions">19.15.4. Content Model Descriptions</a></li>
<li><a class="reference internal" href="#expat-error-constants">19.15.5. Expat error constants</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.sax.reader.html"
                        title="previous chapter">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="internet.html"
                        title="next chapter">20. Internet Protocols and Support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/pyexpat.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="internet.html" title="20. Internet Protocols and Support"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.sax.reader.html" title="19.14. xml.sax.xmlreader — Interface for XML parsers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\8Nb�6262html/library/python.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28. Python Runtime Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.1. sys — System-specific parameters and functions" href="sys.html" />
    <link rel="prev" title="27.2. ensurepip — Bootstrapping the pip installer" href="ensurepip.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/python.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sys.html" title="28.1. sys — System-specific parameters and functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ensurepip.html" title="27.2. ensurepip — Bootstrapping the pip installer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-runtime-services">
<span id="python"></span><h1>28. Python Runtime Services<a class="headerlink" href="#python-runtime-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide a wide range of services related
to the Python interpreter and its interaction with its environment.  Here’s an
overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="sys.html">28.1. <code class="docutils literal notranslate"><span class="pre">sys</span></code> — System-specific parameters and functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="sysconfig.html">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sysconfig.html#configuration-variables">28.2.1. Configuration variables</a></li>
<li class="toctree-l2"><a class="reference internal" href="sysconfig.html#installation-paths">28.2.2. Installation paths</a></li>
<li class="toctree-l2"><a class="reference internal" href="sysconfig.html#other-functions">28.2.3. Other functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="__builtin__.html">28.3. <code class="docutils literal notranslate"><span class="pre">__builtin__</span></code> — Built-in objects</a></li>
<li class="toctree-l1"><a class="reference internal" href="future_builtins.html">28.4. <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> — Python 3 builtins</a></li>
<li class="toctree-l1"><a class="reference internal" href="__main__.html">28.5. <code class="docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level script environment</a></li>
<li class="toctree-l1"><a class="reference internal" href="warnings.html">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a><ul>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#warning-categories">28.6.1. Warning Categories</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#the-warnings-filter">28.6.2. The Warnings Filter</a><ul>
<li class="toctree-l3"><a class="reference internal" href="warnings.html#default-warning-filters">28.6.2.1. Default Warning Filters</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#temporarily-suppressing-warnings">28.6.3. Temporarily Suppressing Warnings</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#testing-warnings">28.6.4. Testing Warnings</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#updating-code-for-new-versions-of-python">28.6.5. Updating Code For New Versions of Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#available-functions">28.6.6. Available Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="warnings.html#available-context-managers">28.6.7. Available Context Managers</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="contextlib.html">28.7. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></li>
<li class="toctree-l1"><a class="reference internal" href="abc.html">28.8. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li>
<li class="toctree-l1"><a class="reference internal" href="atexit.html">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a><ul>
<li class="toctree-l2"><a class="reference internal" href="atexit.html#atexit-example">28.9.1. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="traceback.html">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a><ul>
<li class="toctree-l2"><a class="reference internal" href="traceback.html#traceback-examples">28.10.1. Traceback Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="__future__.html">28.11. <code class="docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></li>
<li class="toctree-l1"><a class="reference internal" href="gc.html">28.12. <code class="docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="inspect.html">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="inspect.html#types-and-members">28.13.1. Types and members</a></li>
<li class="toctree-l2"><a class="reference internal" href="inspect.html#retrieving-source-code">28.13.2. Retrieving source code</a></li>
<li class="toctree-l2"><a class="reference internal" href="inspect.html#classes-and-functions">28.13.3. Classes and functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="inspect.html#the-interpreter-stack">28.13.4. The interpreter stack</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="site.html">28.14. <code class="docutils literal notranslate"><span class="pre">site</span></code> — Site-specific configuration hook</a></li>
<li class="toctree-l1"><a class="reference internal" href="user.html">28.15. <code class="docutils literal notranslate"><span class="pre">user</span></code> — User-specific configuration hook</a></li>
<li class="toctree-l1"><a class="reference internal" href="fpectl.html">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a><ul>
<li class="toctree-l2"><a class="reference internal" href="fpectl.html#example">28.16.1. Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="fpectl.html#limitations-and-other-considerations">28.16.2. Limitations and other considerations</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="ensurepip.html"
                        title="previous chapter">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sys.html"
                        title="next chapter">28.1. <code class="docutils literal notranslate"><span class="pre">sys</span></code> — System-specific parameters and functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/python.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sys.html" title="28.1. sys — System-specific parameters and functions"
             >next</a> |</li>
        <li class="right" >
          <a href="ensurepip.html" title="27.2. ensurepip — Bootstrapping the pip installer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\W����h�hhtml/library/queue.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.10. Queue — A synchronized queue class &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.11. weakref — Weak references" href="weakref.html" />
    <link rel="prev" title="8.9. mutex — Mutual exclusion support" href="mutex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/queue.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="8.11. weakref — Weak references"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mutex.html" title="8.9. mutex — Mutual exclusion support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-Queue">
<span id="queue-a-synchronized-queue-class"></span><h1>8.10. <a class="reference internal" href="#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> — A synchronized queue class<a class="headerlink" href="#module-Queue" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/Queue.py">Lib/Queue.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module implements multi-producer, multi-consumer queues.
It is especially useful in threaded programming when information must be
exchanged safely between multiple threads.  The <a class="reference internal" href="#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> class in this
module implements all the required locking semantics.  It depends on the
availability of thread support in Python; see the <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>
module.</p>
<p>The module implements three types of queue, which differ only in the order in
which the entries are retrieved.  In a FIFO queue, the first tasks added are
the first retrieved. In a LIFO queue, the most recently added entry is
the first retrieved (operating like a stack).  With a priority queue,
the entries are kept sorted (using the <a class="reference internal" href="heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module) and the
lowest valued entry is retrieved first.</p>
<p>The <a class="reference internal" href="#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module defines the following classes and exceptions:</p>
<dl class="class">
<dt id="Queue.Queue">
<em class="property">class </em><code class="descclassname">Queue.</code><code class="descname">Queue</code><span class="sig-paren">(</span><em>maxsize=0</em><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for a FIFO queue.  <em>maxsize</em> is an integer that sets the upperbound
limit on the number of items that can be placed in the queue.  Insertion will
block once this size has been reached, until queue items are consumed.  If
<em>maxsize</em> is less than or equal to zero, the queue size is infinite.</p>
</dd></dl>

<dl class="class">
<dt id="Queue.LifoQueue">
<em class="property">class </em><code class="descclassname">Queue.</code><code class="descname">LifoQueue</code><span class="sig-paren">(</span><em>maxsize=0</em><span class="sig-paren">)</span><a class="headerlink" href="#Queue.LifoQueue" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for a LIFO queue.  <em>maxsize</em> is an integer that sets the upperbound
limit on the number of items that can be placed in the queue.  Insertion will
block once this size has been reached, until queue items are consumed.  If
<em>maxsize</em> is less than or equal to zero, the queue size is infinite.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="Queue.PriorityQueue">
<em class="property">class </em><code class="descclassname">Queue.</code><code class="descname">PriorityQueue</code><span class="sig-paren">(</span><em>maxsize=0</em><span class="sig-paren">)</span><a class="headerlink" href="#Queue.PriorityQueue" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructor for a priority queue.  <em>maxsize</em> is an integer that sets the upperbound
limit on the number of items that can be placed in the queue.  Insertion will
block once this size has been reached, until queue items are consumed.  If
<em>maxsize</em> is less than or equal to zero, the queue size is infinite.</p>
<p>The lowest valued entries are retrieved first (the lowest valued entry is the
one returned by <code class="docutils literal notranslate"><span class="pre">sorted(list(entries))[0]</span></code>).  A typical pattern for entries
is a tuple in the form: <code class="docutils literal notranslate"><span class="pre">(priority_number,</span> <span class="pre">data)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="Queue.Empty">
<em class="property">exception </em><code class="descclassname">Queue.</code><code class="descname">Empty</code><a class="headerlink" href="#Queue.Empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when non-blocking <a class="reference internal" href="#Queue.Queue.get" title="Queue.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> (or
<a class="reference internal" href="#Queue.Queue.get_nowait" title="Queue.Queue.get_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_nowait()</span></code></a>) is called
on a <a class="reference internal" href="#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> object which is empty.</p>
</dd></dl>

<dl class="exception">
<dt id="Queue.Full">
<em class="property">exception </em><code class="descclassname">Queue.</code><code class="descname">Full</code><a class="headerlink" href="#Queue.Full" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when non-blocking <a class="reference internal" href="#Queue.Queue.put" title="Queue.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a> (or
<a class="reference internal" href="#Queue.Queue.put_nowait" title="Queue.Queue.put_nowait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put_nowait()</span></code></a>) is called
on a <a class="reference internal" href="#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> object which is full.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a> is an alternative implementation of unbounded
queues with fast atomic <code class="xref py py-func docutils literal notranslate"><span class="pre">append()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">popleft()</span></code> operations that
do not require locking.</p>
</div>
<div class="section" id="queue-objects">
<span id="queueobjects"></span><h2>8.10.1. Queue Objects<a class="headerlink" href="#queue-objects" title="Permalink to this headline">¶</a></h2>
<p>Queue objects (<a class="reference internal" href="#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, <a class="reference internal" href="#Queue.LifoQueue" title="Queue.LifoQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">LifoQueue</span></code></a>, or <a class="reference internal" href="#Queue.PriorityQueue" title="Queue.PriorityQueue"><code class="xref py py-class docutils literal notranslate"><span class="pre">PriorityQueue</span></code></a>)
provide the public methods described below.</p>
<dl class="method">
<dt id="Queue.Queue.qsize">
<code class="descclassname">Queue.</code><code class="descname">qsize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.qsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the approximate size of the queue.  Note, qsize() &gt; 0 doesn’t
guarantee that a subsequent get() will not block, nor will qsize() &lt; maxsize
guarantee that put() will not block.</p>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.empty">
<code class="descclassname">Queue.</code><code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is empty, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  If empty()
returns <code class="docutils literal notranslate"><span class="pre">True</span></code> it doesn’t guarantee that a subsequent call to put()
will not block.  Similarly, if empty() returns <code class="docutils literal notranslate"><span class="pre">False</span></code> it doesn’t
guarantee that a subsequent call to get() will not block.</p>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.full">
<code class="descclassname">Queue.</code><code class="descname">full</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.full" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the queue is full, <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  If full()
returns <code class="docutils literal notranslate"><span class="pre">True</span></code> it doesn’t guarantee that a subsequent call to get()
will not block.  Similarly, if full() returns <code class="docutils literal notranslate"><span class="pre">False</span></code> it doesn’t
guarantee that a subsequent call to put() will not block.</p>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.put">
<code class="descclassname">Queue.</code><code class="descname">put</code><span class="sig-paren">(</span><em>item</em><span class="optional">[</span>, <em>block</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.put" title="Permalink to this definition">¶</a></dt>
<dd><p>Put <em>item</em> into the queue. If optional args <em>block</em> is true and <em>timeout</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), block if necessary until a free slot is available. If
<em>timeout</em> is a positive number, it blocks at most <em>timeout</em> seconds and raises
the <a class="reference internal" href="#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Full</span></code></a> exception if no free slot was available within that time.
Otherwise (<em>block</em> is false), put an item on the queue if a free slot is
immediately available, else raise the <a class="reference internal" href="#Queue.Full" title="Queue.Full"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Full</span></code></a> exception (<em>timeout</em> is
ignored in that case).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3: </span>The <em>timeout</em> parameter.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.put_nowait">
<code class="descclassname">Queue.</code><code class="descname">put_nowait</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.put_nowait" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">put(item,</span> <span class="pre">False)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.get">
<code class="descclassname">Queue.</code><code class="descname">get</code><span class="sig-paren">(</span><span class="optional">[</span><em>block</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an item from the queue. If optional args <em>block</em> is true and
<em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default), block if necessary until an item is available.
If <em>timeout</em> is a positive number, it blocks at most <em>timeout</em> seconds and
raises the <a class="reference internal" href="#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Empty</span></code></a> exception if no item was available within that time.
Otherwise (<em>block</em> is false), return an item if one is immediately available,
else raise the <a class="reference internal" href="#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Empty</span></code></a> exception (<em>timeout</em> is ignored in that case).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3: </span>The <em>timeout</em> parameter.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.get_nowait">
<code class="descclassname">Queue.</code><code class="descname">get_nowait</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.get_nowait" title="Permalink to this definition">¶</a></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">get(False)</span></code>.</p>
</dd></dl>

<p>Two methods are offered to support tracking whether enqueued tasks have been
fully processed by daemon consumer threads.</p>
<dl class="method">
<dt id="Queue.Queue.task_done">
<code class="descclassname">Queue.</code><code class="descname">task_done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.task_done" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicate that a formerly enqueued task is complete.  Used by queue consumer
threads.  For each <a class="reference internal" href="#Queue.Queue.get" title="Queue.Queue.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code></a> used to fetch a task, a subsequent call to
<a class="reference internal" href="#Queue.Queue.task_done" title="Queue.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> tells the queue that the processing on the task is complete.</p>
<p>If a <a class="reference internal" href="#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> is currently blocking, it will resume when all items have been
processed (meaning that a <a class="reference internal" href="#Queue.Queue.task_done" title="Queue.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> call was received for every item
that had been <a class="reference internal" href="#Queue.Queue.put" title="Queue.Queue.put"><code class="xref py py-meth docutils literal notranslate"><span class="pre">put()</span></code></a> into the queue).</p>
<p>Raises a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if called more times than there were items placed in
the queue.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="Queue.Queue.join">
<code class="descclassname">Queue.</code><code class="descname">join</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#Queue.Queue.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Blocks until all items in the queue have been gotten and processed.</p>
<p>The count of unfinished tasks goes up whenever an item is added to the queue.
The count goes down whenever a consumer thread calls <a class="reference internal" href="#Queue.Queue.task_done" title="Queue.Queue.task_done"><code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code></a> to
indicate that the item was retrieved and all work on it is complete. When the
count of unfinished tasks drops to zero, <a class="reference internal" href="#Queue.Queue.join" title="Queue.Queue.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> unblocks.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>Example of how to wait for enqueued tasks to be completed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">worker</span><span class="p">():</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">item</span> <span class="o">=</span> <span class="n">q</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
        <span class="n">do_work</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
        <span class="n">q</span><span class="o">.</span><span class="n">task_done</span><span class="p">()</span>

<span class="n">q</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">num_worker_threads</span><span class="p">):</span>
     <span class="n">t</span> <span class="o">=</span> <span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">worker</span><span class="p">)</span>
     <span class="n">t</span><span class="o">.</span><span class="n">daemon</span> <span class="o">=</span> <span class="kc">True</span>
     <span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>

<span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">source</span><span class="p">():</span>
    <span class="n">q</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>

<span class="n">q</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>       <span class="c1"># block until all tasks are done</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a><ul>
<li><a class="reference internal" href="#queue-objects">8.10.1. Queue Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mutex.html"
                        title="previous chapter">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="weakref.html"
                        title="next chapter">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/queue.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="8.11. weakref — Weak references"
             >next</a> |</li>
        <li class="right" >
          <a href="mutex.html" title="8.9. mutex — Mutual exclusion support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\&q,�1�1html/library/quopri.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.15. quopri — Encode and decode MIME quoted-printable data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.16. uu — Encode and decode uuencode files" href="uu.html" />
    <link rel="prev" title="18.14. binascii — Convert between binary and ASCII" href="binascii.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/quopri.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="uu.html" title="18.16. uu — Encode and decode uuencode files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="binascii.html" title="18.14. binascii — Convert between binary and ASCII"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-quopri">
<span id="quopri-encode-and-decode-mime-quoted-printable-data"></span><h1>18.15. <a class="reference internal" href="#module-quopri" title="quopri: Encode and decode files using the MIME quoted-printable encoding."><code class="xref py py-mod docutils literal notranslate"><span class="pre">quopri</span></code></a> — Encode and decode MIME quoted-printable data<a class="headerlink" href="#module-quopri" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/quopri.py">Lib/quopri.py</a></p>
<hr class="docutils" />
<p>This module performs quoted-printable transport encoding and decoding, as
defined in <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1521.html"><strong>RFC 1521</strong></a>: “MIME (Multipurpose Internet Mail Extensions) Part One:
Mechanisms for Specifying and Describing the Format of Internet Message Bodies”.
The quoted-printable encoding is designed for data where there are relatively
few nonprintable characters; the base64 encoding scheme available via the
<a class="reference internal" href="base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a> module is more compact if there are many such characters, as when
sending a graphics file.</p>
<dl class="function">
<dt id="quopri.decode">
<code class="descclassname">quopri.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em><span class="optional">[</span>, <em>header</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#quopri.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decode the contents of the <em>input</em> file and write the resulting decoded binary
data to the <em>output</em> file. <em>input</em> and <em>output</em> must either be file objects or
objects that mimic the file object interface. <em>input</em> will be read until
<code class="docutils literal notranslate"><span class="pre">input.readline()</span></code> returns an empty string. If the optional argument <em>header</em>
is present and true, underscore will be decoded as space. This is used to decode
“Q”-encoded headers as described in <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1522.html"><strong>RFC 1522</strong></a>: “MIME (Multipurpose Internet
Mail Extensions) Part Two: Message Header Extensions for Non-ASCII Text”.</p>
</dd></dl>

<dl class="function">
<dt id="quopri.encode">
<code class="descclassname">quopri.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>input</em>, <em>output</em>, <em>quotetabs</em><span class="sig-paren">)</span><a class="headerlink" href="#quopri.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Encode the contents of the <em>input</em> file and write the resulting quoted-printable
data to the <em>output</em> file. <em>input</em> and <em>output</em> must either be file objects or
objects that mimic the file object interface. <em>input</em> will be read until
<code class="docutils literal notranslate"><span class="pre">input.readline()</span></code> returns an empty string. <em>quotetabs</em> is a flag which
controls whether to encode embedded spaces and tabs; when true it encodes such
embedded whitespace, and when false it leaves them unencoded.  Note that spaces
and tabs appearing at the end of lines are always encoded, as per <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1521.html"><strong>RFC 1521</strong></a>.</p>
</dd></dl>

<dl class="function">
<dt id="quopri.decodestring">
<code class="descclassname">quopri.</code><code class="descname">decodestring</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>header</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#quopri.decodestring" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#quopri.decode" title="quopri.decode"><code class="xref py py-func docutils literal notranslate"><span class="pre">decode()</span></code></a>, except that it accepts a source string and returns the
corresponding decoded string.</p>
</dd></dl>

<dl class="function">
<dt id="quopri.encodestring">
<code class="descclassname">quopri.</code><code class="descname">encodestring</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>quotetabs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#quopri.encodestring" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#quopri.encode" title="quopri.encode"><code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code></a>, except that it accepts a source string and returns the
corresponding encoded string.  <em>quotetabs</em> is optional (defaulting to 0), and is
passed straight through to <a class="reference internal" href="#quopri.encode" title="quopri.encode"><code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="mimify.html#module-mimify" title="mimify: Mimification and unmimification of mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code></a></dt>
<dd>General utilities for processing of MIME messages.</dd>
<dt>Module <a class="reference internal" href="base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a></dt>
<dd>Encode and decode MIME base64 data</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="binascii.html"
                        title="previous chapter">18.14. <code class="docutils literal notranslate"><span class="pre">binascii</span></code> — Convert between binary and ASCII</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="uu.html"
                        title="next chapter">18.16. <code class="docutils literal notranslate"><span class="pre">uu</span></code> — Encode and decode uuencode files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/quopri.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="uu.html" title="18.16. uu — Encode and decode uuencode files"
             >next</a> |</li>
        <li class="right" >
          <a href="binascii.html" title="18.14. binascii — Convert between binary and ASCII"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�N�r��html/library/random.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9.6. random — Generate pseudo-random numbers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9.7. itertools — Functions creating iterators for efficient looping" href="itertools.html" />
    <link rel="prev" title="9.5. fractions — Rational numbers" href="fractions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/random.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="itertools.html" title="9.7. itertools — Functions creating iterators for efficient looping"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fractions.html" title="9.5. fractions — Rational numbers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" accesskey="U">9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-random">
<span id="random-generate-pseudo-random-numbers"></span><h1>9.6. <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> — Generate pseudo-random numbers<a class="headerlink" href="#module-random" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/random.py">Lib/random.py</a></p>
<hr class="docutils" />
<p>This module implements pseudo-random number generators for various
distributions.</p>
<p>For integers, uniform selection from a range. For sequences, uniform selection
of a random element, a function to generate a random permutation of a list
in-place, and a function for random sampling without replacement.</p>
<p>On the real line, there are functions to compute uniform, normal (Gaussian),
lognormal, negative exponential, gamma, and beta distributions. For generating
distributions of angles, the von Mises distribution is available.</p>
<p>Almost all module functions depend on the basic function <a class="reference internal" href="#random.random" title="random.random"><code class="xref py py-func docutils literal notranslate"><span class="pre">random()</span></code></a>, which
generates a random float uniformly in the semi-open range [0.0, 1.0).  Python
uses the Mersenne Twister as the core generator.  It produces 53-bit precision
floats and has a period of 2**19937-1.  The underlying implementation in C is
both fast and threadsafe.  The Mersenne Twister is one of the most extensively
tested random number generators in existence.  However, being completely
deterministic, it is not suitable for all purposes, and is completely unsuitable
for cryptographic purposes.</p>
<p>The functions supplied by this module are actually bound methods of a hidden
instance of the <code class="xref py py-class docutils literal notranslate"><span class="pre">random.Random</span></code> class.  You can instantiate your own
instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> to get generators that don’t share state.  This is
especially useful for multi-threaded programs, creating a different instance of
<code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> for each thread, and using the <a class="reference internal" href="#random.jumpahead" title="random.jumpahead"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jumpahead()</span></code></a> method to make
it likely that the generated sequences seen by each thread don’t overlap.</p>
<p>Class <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> can also be subclassed if you want to use a different
basic generator of your own devising: in that case, override the <code class="xref py py-meth docutils literal notranslate"><span class="pre">random()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">seed()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getstate()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setstate()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">jumpahead()</span></code> methods.  Optionally, a new generator can supply a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getrandbits()</span></code> method — this
allows <a class="reference internal" href="#random.randrange" title="random.randrange"><code class="xref py py-meth docutils literal notranslate"><span class="pre">randrange()</span></code></a> to produce selections over an arbitrarily large range.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span>the <a class="reference internal" href="#random.getrandbits" title="random.getrandbits"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getrandbits()</span></code></a> method.</p>
</div>
<p>As an example of subclassing, the <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module provides the
<a class="reference internal" href="#random.WichmannHill" title="random.WichmannHill"><code class="xref py py-class docutils literal notranslate"><span class="pre">WichmannHill</span></code></a> class that implements an alternative generator in pure
Python.  The class provides a backward compatible way to reproduce results from
earlier versions of Python, which used the Wichmann-Hill algorithm as the core
generator.  Note that this Wichmann-Hill generator can no longer be recommended:
its period is too short by contemporary standards, and the sequence generated is
known to fail some stringent randomness tests.  See the references below for a
recent variant that repairs these flaws.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>MersenneTwister replaced Wichmann-Hill as the default generator.</p>
</div>
<p>The <a class="reference internal" href="#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module also provides the <a class="reference internal" href="#random.SystemRandom" title="random.SystemRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">SystemRandom</span></code></a> class which
uses the system function <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a> to generate random numbers
from sources provided by the operating system.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The pseudo-random generators of this module should not be used for
security purposes.  Use <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a> or <a class="reference internal" href="#random.SystemRandom" title="random.SystemRandom"><code class="xref py py-class docutils literal notranslate"><span class="pre">SystemRandom</span></code></a> if
you require a cryptographically secure pseudo-random number generator.</p>
</div>
<p>Bookkeeping functions:</p>
<dl class="function">
<dt id="random.seed">
<code class="descclassname">random.</code><code class="descname">seed</code><span class="sig-paren">(</span><em>a=None</em><span class="sig-paren">)</span><a class="headerlink" href="#random.seed" title="Permalink to this definition">¶</a></dt>
<dd><p>Initialize internal state of the random number generator.</p>
<p><code class="docutils literal notranslate"><span class="pre">None</span></code> or no argument seeds from current time or from an operating
system specific randomness source if available (see the <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a>
function for details on availability).</p>
<p>If <em>a</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> or an <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or a <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>, then
<code class="docutils literal notranslate"><span class="pre">hash(a)</span></code> is used instead.  Note that the hash values for some types
are nondeterministic when <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHASHSEED</span></code></a> is enabled.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>formerly, operating system resources were not used.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.getstate">
<code class="descclassname">random.</code><code class="descname">getstate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#random.getstate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an object capturing the current internal state of the generator.  This
object can be passed to <a class="reference internal" href="#random.setstate" title="random.setstate"><code class="xref py py-func docutils literal notranslate"><span class="pre">setstate()</span></code></a> to restore the state.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>State values produced in Python 2.6 cannot be loaded into earlier versions.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.setstate">
<code class="descclassname">random.</code><code class="descname">setstate</code><span class="sig-paren">(</span><em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#random.setstate" title="Permalink to this definition">¶</a></dt>
<dd><p><em>state</em> should have been obtained from a previous call to <a class="reference internal" href="#random.getstate" title="random.getstate"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstate()</span></code></a>, and
<a class="reference internal" href="#random.setstate" title="random.setstate"><code class="xref py py-func docutils literal notranslate"><span class="pre">setstate()</span></code></a> restores the internal state of the generator to what it was at
the time <a class="reference internal" href="#random.getstate" title="random.getstate"><code class="xref py py-func docutils literal notranslate"><span class="pre">getstate()</span></code></a> was called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.jumpahead">
<code class="descclassname">random.</code><code class="descname">jumpahead</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#random.jumpahead" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the internal state to one different from and likely far away from the
current state.  <em>n</em> is a non-negative integer which is used to scramble the
current state vector.  This is most useful in multi-threaded programs, in
conjunction with multiple instances of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> class:
<a class="reference internal" href="#random.setstate" title="random.setstate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setstate()</span></code></a> or <a class="reference internal" href="#random.seed" title="random.seed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seed()</span></code></a> can be used to force all instances into the
same internal state, and then <a class="reference internal" href="#random.jumpahead" title="random.jumpahead"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jumpahead()</span></code></a> can be used to force the
instances’ states far apart.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Instead of jumping to a specific state, <em>n</em> steps ahead, <code class="docutils literal notranslate"><span class="pre">jumpahead(n)</span></code>
jumps to another state likely to be separated by many steps.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.getrandbits">
<code class="descclassname">random.</code><code class="descname">getrandbits</code><span class="sig-paren">(</span><em>k</em><span class="sig-paren">)</span><a class="headerlink" href="#random.getrandbits" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a python <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a> int with <em>k</em> random bits. This method is supplied
with the MersenneTwister generator and some other generators may also provide it
as an optional part of the API. When available, <a class="reference internal" href="#random.getrandbits" title="random.getrandbits"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getrandbits()</span></code></a> enables
<a class="reference internal" href="#random.randrange" title="random.randrange"><code class="xref py py-meth docutils literal notranslate"><span class="pre">randrange()</span></code></a> to handle arbitrarily large ranges.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Functions for integers:</p>
<dl class="function">
<dt id="random.randrange">
<code class="descclassname">random.</code><code class="descname">randrange</code><span class="sig-paren">(</span><em>stop</em><span class="sig-paren">)</span><a class="headerlink" href="#random.randrange" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">random.</code><code class="descname">randrange</code><span class="sig-paren">(</span><em>start</em>, <em>stop</em><span class="optional">[</span>, <em>step</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Return a randomly selected element from <code class="docutils literal notranslate"><span class="pre">range(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code>.  This is
equivalent to <code class="docutils literal notranslate"><span class="pre">choice(range(start,</span> <span class="pre">stop,</span> <span class="pre">step))</span></code>, but doesn’t actually build a
range object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.randint">
<code class="descclassname">random.</code><code class="descname">randint</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#random.randint" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a random integer <em>N</em> such that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">N</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code>.</p>
</dd></dl>

<p>Functions for sequences:</p>
<dl class="function">
<dt id="random.choice">
<code class="descclassname">random.</code><code class="descname">choice</code><span class="sig-paren">(</span><em>seq</em><span class="sig-paren">)</span><a class="headerlink" href="#random.choice" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a random element from the non-empty sequence <em>seq</em>. If <em>seq</em> is empty,
raises <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="random.shuffle">
<code class="descclassname">random.</code><code class="descname">shuffle</code><span class="sig-paren">(</span><em>x</em><span class="optional">[</span>, <em>random</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#random.shuffle" title="Permalink to this definition">¶</a></dt>
<dd><p>Shuffle the sequence <em>x</em> in place. The optional argument <em>random</em> is a
0-argument function returning a random float in [0.0, 1.0); by default, this is
the function <a class="reference internal" href="#random.random" title="random.random"><code class="xref py py-func docutils literal notranslate"><span class="pre">random()</span></code></a>.</p>
<p>Note that for even rather small <code class="docutils literal notranslate"><span class="pre">len(x)</span></code>, the total number of permutations of
<em>x</em> is larger than the period of most random number generators; this implies
that most permutations of a long sequence can never be generated.</p>
</dd></dl>

<dl class="function">
<dt id="random.sample">
<code class="descclassname">random.</code><code class="descname">sample</code><span class="sig-paren">(</span><em>population</em>, <em>k</em><span class="sig-paren">)</span><a class="headerlink" href="#random.sample" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <em>k</em> length list of unique elements chosen from the population sequence.
Used for random sampling without replacement.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>Returns a new list containing elements from the population while leaving the
original population unchanged.  The resulting list is in selection order so that
all sub-slices will also be valid random samples.  This allows raffle winners
(the sample) to be partitioned into grand prize and second place winners (the
subslices).</p>
<p>Members of the population need not be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> or unique.  If the population
contains repeats, then each occurrence is a possible selection in the sample.</p>
<p>To choose a sample from a range of integers, use an <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> object as an
argument.  This is especially fast and space efficient for sampling from a large
population:  <code class="docutils literal notranslate"><span class="pre">sample(xrange(10000000),</span> <span class="pre">60)</span></code>.</p>
</dd></dl>

<p>The following functions generate specific real-valued distributions. Function
parameters are named after the corresponding variables in the distribution’s
equation, as used in common mathematical practice; most of these equations can
be found in any statistics text.</p>
<dl class="function">
<dt id="random.random">
<code class="descclassname">random.</code><code class="descname">random</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#random.random" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next random floating point number in the range [0.0, 1.0).</p>
</dd></dl>

<dl class="function">
<dt id="random.uniform">
<code class="descclassname">random.</code><code class="descname">uniform</code><span class="sig-paren">(</span><em>a</em>, <em>b</em><span class="sig-paren">)</span><a class="headerlink" href="#random.uniform" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a random floating point number <em>N</em> such that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">N</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code> for
<code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">&lt;=</span> <span class="pre">N</span> <span class="pre">&lt;=</span> <span class="pre">a</span></code> for <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">&lt;</span> <span class="pre">a</span></code>.</p>
<p>The end-point value <code class="docutils literal notranslate"><span class="pre">b</span></code> may or may not be included in the range
depending on floating-point rounding in the equation <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">(b-a)</span> <span class="pre">*</span> <span class="pre">random()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="random.triangular">
<code class="descclassname">random.</code><code class="descname">triangular</code><span class="sig-paren">(</span><em>low</em>, <em>high</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#random.triangular" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a random floating point number <em>N</em> such that <code class="docutils literal notranslate"><span class="pre">low</span> <span class="pre">&lt;=</span> <span class="pre">N</span> <span class="pre">&lt;=</span> <span class="pre">high</span></code> and
with the specified <em>mode</em> between those bounds.  The <em>low</em> and <em>high</em> bounds
default to zero and one.  The <em>mode</em> argument defaults to the midpoint
between the bounds, giving a symmetric distribution.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="random.betavariate">
<code class="descclassname">random.</code><code class="descname">betavariate</code><span class="sig-paren">(</span><em>alpha</em>, <em>beta</em><span class="sig-paren">)</span><a class="headerlink" href="#random.betavariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Beta distribution.  Conditions on the parameters are <code class="docutils literal notranslate"><span class="pre">alpha</span> <span class="pre">&gt;</span> <span class="pre">0</span></code> and
<code class="docutils literal notranslate"><span class="pre">beta</span> <span class="pre">&gt;</span> <span class="pre">0</span></code>. Returned values range between 0 and 1.</p>
</dd></dl>

<dl class="function">
<dt id="random.expovariate">
<code class="descclassname">random.</code><code class="descname">expovariate</code><span class="sig-paren">(</span><em>lambd</em><span class="sig-paren">)</span><a class="headerlink" href="#random.expovariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Exponential distribution.  <em>lambd</em> is 1.0 divided by the desired
mean.  It should be nonzero.  (The parameter would be called
“lambda”, but that is a reserved word in Python.)  Returned values
range from 0 to positive infinity if <em>lambd</em> is positive, and from
negative infinity to 0 if <em>lambd</em> is negative.</p>
</dd></dl>

<dl class="function">
<dt id="random.gammavariate">
<code class="descclassname">random.</code><code class="descname">gammavariate</code><span class="sig-paren">(</span><em>alpha</em>, <em>beta</em><span class="sig-paren">)</span><a class="headerlink" href="#random.gammavariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Gamma distribution.  (<em>Not</em> the gamma function!)  Conditions on the
parameters are <code class="docutils literal notranslate"><span class="pre">alpha</span> <span class="pre">&gt;</span> <span class="pre">0</span></code> and <code class="docutils literal notranslate"><span class="pre">beta</span> <span class="pre">&gt;</span> <span class="pre">0</span></code>.</p>
<p>The probability distribution function is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>          <span class="n">x</span> <span class="o">**</span> <span class="p">(</span><span class="n">alpha</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span> <span class="o">*</span> <span class="n">math</span><span class="o">.</span><span class="n">exp</span><span class="p">(</span><span class="o">-</span><span class="n">x</span> <span class="o">/</span> <span class="n">beta</span><span class="p">)</span>
<span class="n">pdf</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">=</span>  <span class="o">--------------------------------------</span>
            <span class="n">math</span><span class="o">.</span><span class="n">gamma</span><span class="p">(</span><span class="n">alpha</span><span class="p">)</span> <span class="o">*</span> <span class="n">beta</span> <span class="o">**</span> <span class="n">alpha</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="random.gauss">
<code class="descclassname">random.</code><code class="descname">gauss</code><span class="sig-paren">(</span><em>mu</em>, <em>sigma</em><span class="sig-paren">)</span><a class="headerlink" href="#random.gauss" title="Permalink to this definition">¶</a></dt>
<dd><p>Gaussian distribution.  <em>mu</em> is the mean, and <em>sigma</em> is the standard
deviation.  This is slightly faster than the <a class="reference internal" href="#random.normalvariate" title="random.normalvariate"><code class="xref py py-func docutils literal notranslate"><span class="pre">normalvariate()</span></code></a> function
defined below.</p>
</dd></dl>

<dl class="function">
<dt id="random.lognormvariate">
<code class="descclassname">random.</code><code class="descname">lognormvariate</code><span class="sig-paren">(</span><em>mu</em>, <em>sigma</em><span class="sig-paren">)</span><a class="headerlink" href="#random.lognormvariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Log normal distribution.  If you take the natural logarithm of this
distribution, you’ll get a normal distribution with mean <em>mu</em> and standard
deviation <em>sigma</em>.  <em>mu</em> can have any value, and <em>sigma</em> must be greater than
zero.</p>
</dd></dl>

<dl class="function">
<dt id="random.normalvariate">
<code class="descclassname">random.</code><code class="descname">normalvariate</code><span class="sig-paren">(</span><em>mu</em>, <em>sigma</em><span class="sig-paren">)</span><a class="headerlink" href="#random.normalvariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Normal distribution.  <em>mu</em> is the mean, and <em>sigma</em> is the standard deviation.</p>
</dd></dl>

<dl class="function">
<dt id="random.vonmisesvariate">
<code class="descclassname">random.</code><code class="descname">vonmisesvariate</code><span class="sig-paren">(</span><em>mu</em>, <em>kappa</em><span class="sig-paren">)</span><a class="headerlink" href="#random.vonmisesvariate" title="Permalink to this definition">¶</a></dt>
<dd><p><em>mu</em> is the mean angle, expressed in radians between 0 and 2*<em>pi</em>, and <em>kappa</em>
is the concentration parameter, which must be greater than or equal to zero.  If
<em>kappa</em> is equal to zero, this distribution reduces to a uniform random angle
over the range 0 to 2*<em>pi</em>.</p>
</dd></dl>

<dl class="function">
<dt id="random.paretovariate">
<code class="descclassname">random.</code><code class="descname">paretovariate</code><span class="sig-paren">(</span><em>alpha</em><span class="sig-paren">)</span><a class="headerlink" href="#random.paretovariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Pareto distribution.  <em>alpha</em> is the shape parameter.</p>
</dd></dl>

<dl class="function">
<dt id="random.weibullvariate">
<code class="descclassname">random.</code><code class="descname">weibullvariate</code><span class="sig-paren">(</span><em>alpha</em>, <em>beta</em><span class="sig-paren">)</span><a class="headerlink" href="#random.weibullvariate" title="Permalink to this definition">¶</a></dt>
<dd><p>Weibull distribution.  <em>alpha</em> is the scale parameter and <em>beta</em> is the shape
parameter.</p>
</dd></dl>

<p>Alternative Generators:</p>
<dl class="class">
<dt id="random.WichmannHill">
<em class="property">class </em><code class="descclassname">random.</code><code class="descname">WichmannHill</code><span class="sig-paren">(</span><span class="optional">[</span><em>seed</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#random.WichmannHill" title="Permalink to this definition">¶</a></dt>
<dd><p>Class that implements the Wichmann-Hill algorithm as the core generator. Has all
of the same methods as <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> plus the <a class="reference internal" href="#random.whseed" title="random.whseed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">whseed()</span></code></a> method described
below.  Because this class is implemented in pure Python, it is not threadsafe
and may require locks between calls.  The period of the generator is
6,953,607,871,644 which is small enough to require care that two independent
random sequences do not overlap.</p>
</dd></dl>

<dl class="function">
<dt id="random.whseed">
<code class="descclassname">random.</code><code class="descname">whseed</code><span class="sig-paren">(</span><span class="optional">[</span><em>x</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#random.whseed" title="Permalink to this definition">¶</a></dt>
<dd><p>This is obsolete, supplied for bit-level compatibility with versions of Python
prior to 2.1. See <a class="reference internal" href="#random.seed" title="random.seed"><code class="xref py py-func docutils literal notranslate"><span class="pre">seed()</span></code></a> for details.  <a class="reference internal" href="#random.whseed" title="random.whseed"><code class="xref py py-func docutils literal notranslate"><span class="pre">whseed()</span></code></a> does not guarantee
that distinct integer arguments yield distinct internal states, and can yield no
more than about 2**24 distinct internal states in all.</p>
</dd></dl>

<dl class="class">
<dt id="random.SystemRandom">
<em class="property">class </em><code class="descclassname">random.</code><code class="descname">SystemRandom</code><span class="sig-paren">(</span><span class="optional">[</span><em>seed</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#random.SystemRandom" title="Permalink to this definition">¶</a></dt>
<dd><p>Class that uses the <a class="reference internal" href="os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a> function for generating random numbers
from sources provided by the operating system. Not available on all systems.
Does not rely on software state and sequences are not reproducible. Accordingly,
the <a class="reference internal" href="#random.seed" title="random.seed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seed()</span></code></a> and <a class="reference internal" href="#random.jumpahead" title="random.jumpahead"><code class="xref py py-meth docutils literal notranslate"><span class="pre">jumpahead()</span></code></a> methods have no effect and are ignored.
The <a class="reference internal" href="#random.getstate" title="random.getstate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getstate()</span></code></a> and <a class="reference internal" href="#random.setstate" title="random.setstate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setstate()</span></code></a> methods raise
<a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> if called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Examples of basic usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span>        <span class="c1"># Random float x, 0.0 &lt;= x &lt; 1.0</span>
<span class="go">0.37444887175646646</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">uniform</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>  <span class="c1"># Random float x, 1.0 &lt;= x &lt; 10.0</span>
<span class="go">1.1800146073117523</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">randint</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>  <span class="c1"># Integer from 1 to 10, endpoints included</span>
<span class="go">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">101</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>  <span class="c1"># Even integer from 0 to 100</span>
<span class="go">26</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">(</span><span class="s1">&#39;abcdefghij&#39;</span><span class="p">)</span>  <span class="c1"># Choose a random element</span>
<span class="go">&#39;c&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">items</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="n">items</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">items</span>
<span class="go">[7, 3, 2, 5, 6, 4, 1]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">],</span>  <span class="mi">3</span><span class="p">)</span>  <span class="c1"># Choose 3 elements</span>
<span class="go">[4, 1, 5]</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally
equidistributed uniform pseudorandom number generator”, ACM Transactions on
Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.</p>
<p>Wichmann, B. A. &amp; Hill, I. D., “Algorithm AS 183: An efficient and portable
pseudo-random number generator”, Applied Statistics 31 (1982) 188-190.</p>
<p class="last"><a class="reference external" href="http://code.activestate.com/recipes/576707/">Complementary-Multiply-with-Carry recipe</a> for a compatible alternative
random number generator with a long period and comparatively simple update
operations.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fractions.html"
                        title="previous chapter">9.5. <code class="docutils literal notranslate"><span class="pre">fractions</span></code> — Rational numbers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="itertools.html"
                        title="next chapter">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/random.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="itertools.html" title="9.7. itertools — Functions creating iterators for efficient looping"
             >next</a> |</li>
        <li class="right" >
          <a href="fractions.html" title="9.5. fractions — Rational numbers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="numeric.html" >9. Numeric and Mathematical Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\
4ΰQaQahtml/library/re.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.2. re — Regular expression operations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.3. struct — Interpret strings as packed binary data" href="struct.html" />
    <link rel="prev" title="7.1. string — Common string operations" href="string.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/re.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="struct.html" title="7.3. struct — Interpret strings as packed binary data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="string.html" title="7.1. string — Common string operations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-re">
<span id="re-regular-expression-operations"></span><h1>7.2. <a class="reference internal" href="#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> — Regular expression operations<a class="headerlink" href="#module-re" title="Permalink to this headline">¶</a></h1>
<p>This module provides regular expression matching operations similar to
those found in Perl. Both patterns and strings to be searched can be
Unicode strings as well as 8-bit strings.</p>
<p>Regular expressions use the backslash character (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) to indicate
special forms or to allow special characters to be used without invoking
their special meaning.  This collides with Python’s usage of the same
character for the same purpose in string literals; for example, to match
a literal backslash, one might have to write <code class="docutils literal notranslate"><span class="pre">'\\\\'</span></code> as the pattern
string, because the regular expression must be <code class="docutils literal notranslate"><span class="pre">\\</span></code>, and each
backslash must be expressed as <code class="docutils literal notranslate"><span class="pre">\\</span></code> inside a regular Python string
literal.</p>
<p>The solution is to use Python’s raw string notation for regular expression
patterns; backslashes are not handled in any special way in a string literal
prefixed with <code class="docutils literal notranslate"><span class="pre">'r'</span></code>.  So <code class="docutils literal notranslate"><span class="pre">r&quot;\n&quot;</span></code> is a two-character string containing
<code class="docutils literal notranslate"><span class="pre">'\'</span></code> and <code class="docutils literal notranslate"><span class="pre">'n'</span></code>, while <code class="docutils literal notranslate"><span class="pre">&quot;\n&quot;</span></code> is a one-character string containing a
newline.  Usually patterns will be expressed in Python code using this raw
string notation.</p>
<p>It is important to note that most regular expression operations are available as
module-level functions and <a class="reference internal" href="#re.RegexObject" title="re.RegexObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegexObject</span></code></a> methods.  The functions are
shortcuts that don’t require you to compile a regex object first, but miss some
fine-tuning parameters.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The third-party <a class="reference external" href="https://pypi.org/project/regex/">regex</a> module,
which has an API compatible with the standard library <a class="reference internal" href="#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module,
but offers additional functionality and a more thorough Unicode support.</p>
</div>
<div class="section" id="regular-expression-syntax">
<span id="re-syntax"></span><h2>7.2.1. Regular Expression Syntax<a class="headerlink" href="#regular-expression-syntax" title="Permalink to this headline">¶</a></h2>
<p>A regular expression (or RE) specifies a set of strings that matches it; the
functions in this module let you check if a particular string matches a given
regular expression (or if a given regular expression matches a particular
string, which comes down to the same thing).</p>
<p>Regular expressions can be concatenated to form new regular expressions; if <em>A</em>
and <em>B</em> are both regular expressions, then <em>AB</em> is also a regular expression.
In general, if a string <em>p</em> matches <em>A</em> and another string <em>q</em> matches <em>B</em>, the
string <em>pq</em> will match AB.  This holds unless <em>A</em> or <em>B</em> contain low precedence
operations; boundary conditions between <em>A</em> and <em>B</em>; or have numbered group
references.  Thus, complex expressions can easily be constructed from simpler
primitive expressions like the ones described here.  For details of the theory
and implementation of regular expressions, consult the Friedl book referenced
above, or almost any textbook about compiler construction.</p>
<p>A brief explanation of the format of regular expressions follows.  For further
information and a gentler presentation, consult the <a class="reference internal" href="../howto/regex.html#regex-howto"><span class="std std-ref">Regular Expression HOWTO</span></a>.</p>
<p>Regular expressions can contain both special and ordinary characters. Most
ordinary characters, like <code class="docutils literal notranslate"><span class="pre">'A'</span></code>, <code class="docutils literal notranslate"><span class="pre">'a'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'0'</span></code>, are the simplest regular
expressions; they simply match themselves.  You can concatenate ordinary
characters, so <code class="docutils literal notranslate"><span class="pre">last</span></code> matches the string <code class="docutils literal notranslate"><span class="pre">'last'</span></code>.  (In the rest of this
section, we’ll write RE’s in <code class="docutils literal notranslate"><span class="pre">this</span> <span class="pre">special</span> <span class="pre">style</span></code>, usually without quotes, and
strings to be matched <code class="docutils literal notranslate"><span class="pre">'in</span> <span class="pre">single</span> <span class="pre">quotes'</span></code>.)</p>
<p>Some characters, like <code class="docutils literal notranslate"><span class="pre">'|'</span></code> or <code class="docutils literal notranslate"><span class="pre">'('</span></code>, are special. Special
characters either stand for classes of ordinary characters, or affect
how the regular expressions around them are interpreted. Regular
expression pattern strings may not contain null bytes, but can specify
the null byte using the <code class="docutils literal notranslate"><span class="pre">\number</span></code> notation, e.g., <code class="docutils literal notranslate"><span class="pre">'\x00'</span></code>.</p>
<p>Repetition qualifiers (<code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, <code class="docutils literal notranslate"><span class="pre">{m,n}</span></code>, etc) cannot be
directly nested. This avoids ambiguity with the non-greedy modifier suffix
<code class="docutils literal notranslate"><span class="pre">?</span></code>, and with other modifiers in other implementations. To apply a second
repetition to an inner repetition, parentheses may be used. For example,
the expression <code class="docutils literal notranslate"><span class="pre">(?:a{6})*</span></code> matches any multiple of six <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters.</p>
<p>The special characters are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">'.'</span></code></dt>
<dd>(Dot.)  In the default mode, this matches any character except a newline.  If
the <a class="reference internal" href="#re.DOTALL" title="re.DOTALL"><code class="xref py py-const docutils literal notranslate"><span class="pre">DOTALL</span></code></a> flag has been specified, this matches any character
including a newline.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'^'</span></code></dt>
<dd>(Caret.)  Matches the start of the string, and in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode also
matches immediately after each newline.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'$'</span></code></dt>
<dd>Matches the end of the string or just before the newline at the end of the
string, and in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode also matches before a newline.  <code class="docutils literal notranslate"><span class="pre">foo</span></code>
matches both ‘foo’ and ‘foobar’, while the regular expression <code class="docutils literal notranslate"><span class="pre">foo$</span></code> matches
only ‘foo’.  More interestingly, searching for <code class="docutils literal notranslate"><span class="pre">foo.$</span></code> in <code class="docutils literal notranslate"><span class="pre">'foo1\nfoo2\n'</span></code>
matches ‘foo2’ normally, but ‘foo1’ in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode; searching for
a single <code class="docutils literal notranslate"><span class="pre">$</span></code> in <code class="docutils literal notranslate"><span class="pre">'foo\n'</span></code> will find two (empty) matches: one just before
the newline, and one at the end of the string.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'*'</span></code></dt>
<dd>Causes the resulting RE to match 0 or more repetitions of the preceding RE, as
many repetitions as are possible.  <code class="docutils literal notranslate"><span class="pre">ab*</span></code> will match ‘a’, ‘ab’, or ‘a’ followed
by any number of ‘b’s.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'+'</span></code></dt>
<dd>Causes the resulting RE to match 1 or more repetitions of the preceding RE.
<code class="docutils literal notranslate"><span class="pre">ab+</span></code> will match ‘a’ followed by any non-zero number of ‘b’s; it will not
match just ‘a’.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'?'</span></code></dt>
<dd>Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
<code class="docutils literal notranslate"><span class="pre">ab?</span></code> will match either ‘a’ or ‘ab’.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">+?</span></code>, <code class="docutils literal notranslate"><span class="pre">??</span></code></dt>
<dd>The <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, <code class="docutils literal notranslate"><span class="pre">'+'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'?'</span></code> qualifiers are all <em class="dfn">greedy</em>; they match
as much text as possible.  Sometimes this behaviour isn’t desired; if the RE
<code class="docutils literal notranslate"><span class="pre">&lt;.*&gt;</span></code> is matched against <code class="docutils literal notranslate"><span class="pre">&lt;a&gt;</span> <span class="pre">b</span> <span class="pre">&lt;c&gt;</span></code>, it will match the entire
string, and not just <code class="docutils literal notranslate"><span class="pre">&lt;a&gt;</span></code>.  Adding <code class="docutils literal notranslate"><span class="pre">?</span></code> after the qualifier makes it
perform the match in <em class="dfn">non-greedy</em> or <em class="dfn">minimal</em> fashion; as <em>few</em>
characters as possible will be matched.  Using the RE <code class="docutils literal notranslate"><span class="pre">&lt;.*?&gt;</span></code> will match
only <code class="docutils literal notranslate"><span class="pre">&lt;a&gt;</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">{m}</span></code></dt>
<dd>Specifies that exactly <em>m</em> copies of the previous RE should be matched; fewer
matches cause the entire RE not to match.  For example, <code class="docutils literal notranslate"><span class="pre">a{6}</span></code> will match
exactly six <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters, but not five.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">{m,n}</span></code></dt>
<dd>Causes the resulting RE to match from <em>m</em> to <em>n</em> repetitions of the preceding
RE, attempting to match as many repetitions as possible.  For example,
<code class="docutils literal notranslate"><span class="pre">a{3,5}</span></code> will match from 3 to 5 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters.  Omitting <em>m</em> specifies a
lower bound of zero,  and omitting <em>n</em> specifies an infinite upper bound.  As an
example, <code class="docutils literal notranslate"><span class="pre">a{4,}b</span></code> will match <code class="docutils literal notranslate"><span class="pre">aaaab</span></code> or a thousand <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters
followed by a <code class="docutils literal notranslate"><span class="pre">b</span></code>, but not <code class="docutils literal notranslate"><span class="pre">aaab</span></code>. The comma may not be omitted or the
modifier would be confused with the previously described form.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">{m,n}?</span></code></dt>
<dd>Causes the resulting RE to match from <em>m</em> to <em>n</em> repetitions of the preceding
RE, attempting to match as <em>few</em> repetitions as possible.  This is the
non-greedy version of the previous qualifier.  For example, on the
6-character string <code class="docutils literal notranslate"><span class="pre">'aaaaaa'</span></code>, <code class="docutils literal notranslate"><span class="pre">a{3,5}</span></code> will match 5 <code class="docutils literal notranslate"><span class="pre">'a'</span></code> characters,
while <code class="docutils literal notranslate"><span class="pre">a{3,5}?</span></code> will only match 3 characters.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'\'</span></code></dt>
<dd><p class="first">Either escapes special characters (permitting you to match characters like
<code class="docutils literal notranslate"><span class="pre">'*'</span></code>, <code class="docutils literal notranslate"><span class="pre">'?'</span></code>, and so forth), or signals a special sequence; special
sequences are discussed below.</p>
<p class="last">If you’re not using a raw string to express the pattern, remember that Python
also uses the backslash as an escape sequence in string literals; if the escape
sequence isn’t recognized by Python’s parser, the backslash and subsequent
character are included in the resulting string.  However, if Python would
recognize the resulting sequence, the backslash should be repeated twice.  This
is complicated and hard to understand, so it’s highly recommended that you use
raw strings for all but the simplest expressions.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">[]</span></code></dt>
<dd><p class="first">Used to indicate a set of characters.  In a set:</p>
<ul class="last simple">
<li>Characters can be listed individually, e.g. <code class="docutils literal notranslate"><span class="pre">[amk]</span></code> will match <code class="docutils literal notranslate"><span class="pre">'a'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'m'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'k'</span></code>.</li>
<li>Ranges of characters can be indicated by giving two characters and separating
them by a <code class="docutils literal notranslate"><span class="pre">'-'</span></code>, for example <code class="docutils literal notranslate"><span class="pre">[a-z]</span></code> will match any lowercase ASCII letter,
<code class="docutils literal notranslate"><span class="pre">[0-5][0-9]</span></code> will match all the two-digits numbers from <code class="docutils literal notranslate"><span class="pre">00</span></code> to <code class="docutils literal notranslate"><span class="pre">59</span></code>, and
<code class="docutils literal notranslate"><span class="pre">[0-9A-Fa-f]</span></code> will match any hexadecimal digit.  If <code class="docutils literal notranslate"><span class="pre">-</span></code> is escaped (e.g.
<code class="docutils literal notranslate"><span class="pre">[a\-z]</span></code>) or if it’s placed as the first or last character (e.g. <code class="docutils literal notranslate"><span class="pre">[a-]</span></code>),
it will match a literal <code class="docutils literal notranslate"><span class="pre">'-'</span></code>.</li>
<li>Special characters lose their special meaning inside sets.  For example,
<code class="docutils literal notranslate"><span class="pre">[(+*)]</span></code> will match any of the literal characters <code class="docutils literal notranslate"><span class="pre">'('</span></code>, <code class="docutils literal notranslate"><span class="pre">'+'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'*'</span></code>, or <code class="docutils literal notranslate"><span class="pre">')'</span></code>.</li>
<li>Character classes such as <code class="docutils literal notranslate"><span class="pre">\w</span></code> or <code class="docutils literal notranslate"><span class="pre">\S</span></code> (defined below) are also accepted
inside a set, although the characters they match depends on whether
<a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> or  <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> mode is in force.</li>
<li>Characters that are not within a range can be matched by <em class="dfn">complementing</em>
the set.  If the first character of the set is <code class="docutils literal notranslate"><span class="pre">'^'</span></code>, all the characters
that are <em>not</em> in the set will be matched.  For example, <code class="docutils literal notranslate"><span class="pre">[^5]</span></code> will match
any character except <code class="docutils literal notranslate"><span class="pre">'5'</span></code>, and <code class="docutils literal notranslate"><span class="pre">[^^]</span></code> will match any character except
<code class="docutils literal notranslate"><span class="pre">'^'</span></code>.  <code class="docutils literal notranslate"><span class="pre">^</span></code> has no special meaning if it’s not the first character in
the set.</li>
<li>To match a literal <code class="docutils literal notranslate"><span class="pre">']'</span></code> inside a set, precede it with a backslash, or
place it at the beginning of the set.  For example, both <code class="docutils literal notranslate"><span class="pre">[()[\]{}]</span></code> and
<code class="docutils literal notranslate"><span class="pre">[]()[{}]</span></code> will both match a parenthesis.</li>
</ul>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'|'</span></code></dt>
<dd><code class="docutils literal notranslate"><span class="pre">A|B</span></code>, where A and B can be arbitrary REs, creates a regular expression that
will match either A or B.  An arbitrary number of REs can be separated by the
<code class="docutils literal notranslate"><span class="pre">'|'</span></code> in this way.  This can be used inside groups (see below) as well.  As
the target string is scanned, REs separated by <code class="docutils literal notranslate"><span class="pre">'|'</span></code> are tried from left to
right. When one pattern completely matches, that branch is accepted. This means
that once <code class="docutils literal notranslate"><span class="pre">A</span></code> matches, <code class="docutils literal notranslate"><span class="pre">B</span></code> will not be tested further, even if it would
produce a longer overall match.  In other words, the <code class="docutils literal notranslate"><span class="pre">'|'</span></code> operator is never
greedy.  To match a literal <code class="docutils literal notranslate"><span class="pre">'|'</span></code>, use <code class="docutils literal notranslate"><span class="pre">\|</span></code>, or enclose it inside a
character class, as in <code class="docutils literal notranslate"><span class="pre">[|]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(...)</span></code></dt>
<dd>Matches whatever regular expression is inside the parentheses, and indicates the
start and end of a group; the contents of a group can be retrieved after a match
has been performed, and can be matched later in the string with the <code class="docutils literal notranslate"><span class="pre">\number</span></code>
special sequence, described below.  To match the literals <code class="docutils literal notranslate"><span class="pre">'('</span></code> or <code class="docutils literal notranslate"><span class="pre">')'</span></code>,
use <code class="docutils literal notranslate"><span class="pre">\(</span></code> or <code class="docutils literal notranslate"><span class="pre">\)</span></code>, or enclose them inside a character class: <code class="docutils literal notranslate"><span class="pre">[(]</span> <span class="pre">[)]</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?...)</span></code></dt>
<dd>This is an extension notation (a <code class="docutils literal notranslate"><span class="pre">'?'</span></code> following a <code class="docutils literal notranslate"><span class="pre">'('</span></code> is not meaningful
otherwise).  The first character after the <code class="docutils literal notranslate"><span class="pre">'?'</span></code> determines what the meaning
and further syntax of the construct is. Extensions usually do not create a new
group; <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> is the only exception to this rule. Following are the
currently supported extensions.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?iLmsux)</span></code></dt>
<dd><p class="first">(One or more letters from the set <code class="docutils literal notranslate"><span class="pre">'i'</span></code>, <code class="docutils literal notranslate"><span class="pre">'L'</span></code>, <code class="docutils literal notranslate"><span class="pre">'m'</span></code>, <code class="docutils literal notranslate"><span class="pre">'s'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'u'</span></code>, <code class="docutils literal notranslate"><span class="pre">'x'</span></code>.)  The group matches the empty string; the letters
set the corresponding flags: <a class="reference internal" href="#re.I" title="re.I"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.I</span></code></a> (ignore case),
<a class="reference internal" href="#re.L" title="re.L"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.L</span></code></a> (locale dependent), <a class="reference internal" href="#re.M" title="re.M"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.M</span></code></a> (multi-line),
<a class="reference internal" href="#re.S" title="re.S"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.S</span></code></a> (dot matches all), <a class="reference internal" href="#re.U" title="re.U"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.U</span></code></a> (Unicode dependent),
and <a class="reference internal" href="#re.X" title="re.X"><code class="xref py py-const docutils literal notranslate"><span class="pre">re.X</span></code></a> (verbose), for the entire regular expression. (The
flags are described in <a class="reference internal" href="#contents-of-module-re"><span class="std std-ref">Module Contents</span></a>.) This
is useful if you wish to include the flags as part of the regular
expression, instead of passing a <em>flag</em> argument to the
<a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> function.</p>
<p class="last">Note that the <code class="docutils literal notranslate"><span class="pre">(?x)</span></code> flag changes how the expression is parsed. It should be
used first in the expression string, or after one or more whitespace characters.
If there are non-whitespace characters before the flag, the results are
undefined.</p>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?:...)</span></code></dt>
<dd>A non-capturing version of regular parentheses.  Matches whatever regular
expression is inside the parentheses, but the substring matched by the group
<em>cannot</em> be retrieved after performing a match or referenced later in the
pattern.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code></dt>
<dd><p class="first">Similar to regular parentheses, but the substring matched by the group is
accessible via the symbolic group name <em>name</em>.  Group names must be valid
Python identifiers, and each group name must be defined only once within a
regular expression.  A symbolic group is also a numbered group, just as if
the group were not named.</p>
<p>Named groups can be referenced in three contexts.  If the pattern is
<code class="docutils literal notranslate"><span class="pre">(?P&lt;quote&gt;['&quot;]).*?(?P=quote)</span></code> (i.e. matching a string quoted with either
single or double quotes):</p>
<table border="1" class="last docutils">
<colgroup>
<col width="53%" />
<col width="47%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Context of reference to group “quote”</th>
<th class="head">Ways to reference it</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>in the same pattern itself</td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">(?P=quote)</span></code> (as shown)</li>
<li><code class="docutils literal notranslate"><span class="pre">\1</span></code></li>
</ul>
</td>
</tr>
<tr class="row-odd"><td>when processing match object <code class="docutils literal notranslate"><span class="pre">m</span></code></td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">m.group('quote')</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">m.end('quote')</span></code> (etc.)</li>
</ul>
</td>
</tr>
<tr class="row-even"><td>in a string passed to the <code class="docutils literal notranslate"><span class="pre">repl</span></code>
argument of <code class="docutils literal notranslate"><span class="pre">re.sub()</span></code></td>
<td><ul class="first last simple">
<li><code class="docutils literal notranslate"><span class="pre">\g&lt;quote&gt;</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">\g&lt;1&gt;</span></code></li>
<li><code class="docutils literal notranslate"><span class="pre">\1</span></code></li>
</ul>
</td>
</tr>
</tbody>
</table>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?P=name)</span></code></dt>
<dd>A backreference to a named group; it matches whatever text was matched by the
earlier group named <em>name</em>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?#...)</span></code></dt>
<dd>A comment; the contents of the parentheses are simply ignored.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?=...)</span></code></dt>
<dd>Matches if <code class="docutils literal notranslate"><span class="pre">...</span></code> matches next, but doesn’t consume any of the string.  This is
called a lookahead assertion.  For example, <code class="docutils literal notranslate"><span class="pre">Isaac</span> <span class="pre">(?=Asimov)</span></code> will match
<code class="docutils literal notranslate"><span class="pre">'Isaac</span> <span class="pre">'</span></code> only if it’s followed by <code class="docutils literal notranslate"><span class="pre">'Asimov'</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?!...)</span></code></dt>
<dd>Matches if <code class="docutils literal notranslate"><span class="pre">...</span></code> doesn’t match next.  This is a negative lookahead assertion.
For example, <code class="docutils literal notranslate"><span class="pre">Isaac</span> <span class="pre">(?!Asimov)</span></code> will match <code class="docutils literal notranslate"><span class="pre">'Isaac</span> <span class="pre">'</span></code> only if it’s <em>not</em>
followed by <code class="docutils literal notranslate"><span class="pre">'Asimov'</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?&lt;=...)</span></code></dt>
<dd><p class="first">Matches if the current position in the string is preceded by a match for <code class="docutils literal notranslate"><span class="pre">...</span></code>
that ends at the current position.  This is called a <em class="dfn">positive lookbehind
assertion</em>. <code class="docutils literal notranslate"><span class="pre">(?&lt;=abc)def</span></code> will find a match in <code class="docutils literal notranslate"><span class="pre">abcdef</span></code>, since the
lookbehind will back up 3 characters and check if the contained pattern matches.
The contained pattern must only match strings of some fixed length, meaning that
<code class="docutils literal notranslate"><span class="pre">abc</span></code> or <code class="docutils literal notranslate"><span class="pre">a|b</span></code> are allowed, but <code class="docutils literal notranslate"><span class="pre">a*</span></code> and <code class="docutils literal notranslate"><span class="pre">a{3,4}</span></code> are not.  Group
references are not supported even if they match strings of some fixed length.
Note that
patterns which start with positive lookbehind assertions will not match at the
beginning of the string being searched; you will most likely want to use the
<a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> function rather than the <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;(?&lt;=abc)def&#39;</span><span class="p">,</span> <span class="s1">&#39;abcdef&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;def&#39;</span>
</pre></div>
</div>
<p>This example looks for a word following a hyphen:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;(?&lt;=-)\w+&#39;</span><span class="p">,</span> <span class="s1">&#39;spam-egg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">&#39;egg&#39;</span>
</pre></div>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?&lt;!...)</span></code></dt>
<dd>Matches if the current position in the string is not preceded by a match for
<code class="docutils literal notranslate"><span class="pre">...</span></code>.  This is called a <em class="dfn">negative lookbehind assertion</em>.  Similar to
positive lookbehind assertions, the contained pattern must only match strings of
some fixed length and shouldn’t contain group references.
Patterns which start with negative lookbehind assertions may
match at the beginning of the string being searched.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">(?(id/name)yes-pattern|no-pattern)</span></code></dt>
<dd><p class="first">Will try to match with <code class="docutils literal notranslate"><span class="pre">yes-pattern</span></code> if the group with given <em>id</em> or <em>name</em>
exists, and with <code class="docutils literal notranslate"><span class="pre">no-pattern</span></code> if it doesn’t. <code class="docutils literal notranslate"><span class="pre">no-pattern</span></code> is optional and
can be omitted. For example,  <code class="docutils literal notranslate"><span class="pre">(&lt;)?(\w+&#64;\w+(?:\.\w+)+)(?(1)&gt;)</span></code> is a poor email
matching pattern, which will match with <code class="docutils literal notranslate"><span class="pre">'&lt;user&#64;host.com&gt;'</span></code> as well as
<code class="docutils literal notranslate"><span class="pre">'user&#64;host.com'</span></code>, but not with <code class="docutils literal notranslate"><span class="pre">'&lt;user&#64;host.com'</span></code>.</p>
<div class="last versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd>
</dl>
<p>The special sequences consist of <code class="docutils literal notranslate"><span class="pre">'\'</span></code> and a character from the list below.
If the ordinary character is not on the list, then the resulting RE will match
the second character.  For example, <code class="docutils literal notranslate"><span class="pre">\$</span></code> matches the character <code class="docutils literal notranslate"><span class="pre">'$'</span></code>.</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">\number</span></code></dt>
<dd>Matches the contents of the group of the same number.  Groups are numbered
starting from 1.  For example, <code class="docutils literal notranslate"><span class="pre">(.+)</span> <span class="pre">\1</span></code> matches <code class="docutils literal notranslate"><span class="pre">'the</span> <span class="pre">the'</span></code> or <code class="docutils literal notranslate"><span class="pre">'55</span> <span class="pre">55'</span></code>,
but not <code class="docutils literal notranslate"><span class="pre">'thethe'</span></code> (note the space after the group).  This special sequence
can only be used to match one of the first 99 groups.  If the first digit of
<em>number</em> is 0, or <em>number</em> is 3 octal digits long, it will not be interpreted as
a group match, but as the character with octal value <em>number</em>. Inside the
<code class="docutils literal notranslate"><span class="pre">'['</span></code> and <code class="docutils literal notranslate"><span class="pre">']'</span></code> of a character class, all numeric escapes are treated as
characters.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\A</span></code></dt>
<dd>Matches only at the start of the string.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\b</span></code></dt>
<dd>Matches the empty string, but only at the beginning or end of a word.  A word is
defined as a sequence of alphanumeric or underscore characters, so the end of a
word is indicated by whitespace or a non-alphanumeric, non-underscore character.
Note that formally, <code class="docutils literal notranslate"><span class="pre">\b</span></code> is defined as the boundary between a <code class="docutils literal notranslate"><span class="pre">\w</span></code> and
a <code class="docutils literal notranslate"><span class="pre">\W</span></code> character (or vice versa), or between <code class="docutils literal notranslate"><span class="pre">\w</span></code> and the beginning/end
of the string, so the precise set of characters deemed to be alphanumeric
depends on the values of the <code class="docutils literal notranslate"><span class="pre">UNICODE</span></code> and <code class="docutils literal notranslate"><span class="pre">LOCALE</span></code> flags.
For example, <code class="docutils literal notranslate"><span class="pre">r'\bfoo\b'</span></code> matches <code class="docutils literal notranslate"><span class="pre">'foo'</span></code>, <code class="docutils literal notranslate"><span class="pre">'foo.'</span></code>, <code class="docutils literal notranslate"><span class="pre">'(foo)'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'bar</span> <span class="pre">foo</span> <span class="pre">baz'</span></code> but not <code class="docutils literal notranslate"><span class="pre">'foobar'</span></code> or <code class="docutils literal notranslate"><span class="pre">'foo3'</span></code>.
Inside a character range, <code class="docutils literal notranslate"><span class="pre">\b</span></code> represents the backspace character, for
compatibility with Python’s string literals.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\B</span></code></dt>
<dd>Matches the empty string, but only when it is <em>not</em> at the beginning or end of a
word.  This means that <code class="docutils literal notranslate"><span class="pre">r'py\B'</span></code> matches <code class="docutils literal notranslate"><span class="pre">'python'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py3'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py2'</span></code>,
but not <code class="docutils literal notranslate"><span class="pre">'py'</span></code>, <code class="docutils literal notranslate"><span class="pre">'py.'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'py!'</span></code>.
<code class="docutils literal notranslate"><span class="pre">\B</span></code> is just the opposite of <code class="docutils literal notranslate"><span class="pre">\b</span></code>, so is also subject to the settings
of <code class="docutils literal notranslate"><span class="pre">LOCALE</span></code> and <code class="docutils literal notranslate"><span class="pre">UNICODE</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\d</span></code></dt>
<dd>When the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flag is not specified, matches any decimal digit; this
is equivalent to the set <code class="docutils literal notranslate"><span class="pre">[0-9]</span></code>.  With <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a>, it will match
whatever is classified as a decimal digit in the Unicode character properties
database.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\D</span></code></dt>
<dd>When the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flag is not specified, matches any non-digit
character; this is equivalent to the set  <code class="docutils literal notranslate"><span class="pre">[^0-9]</span></code>.  With <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a>, it
will match  anything other than character marked as digits in the Unicode
character  properties database.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\s</span></code></dt>
<dd>When the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flag is not specified, it matches any whitespace
character, this is equivalent to the set <code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">\t\n\r\f\v]</span></code>. The
<a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> flag has no extra effect on matching of the space.
If <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> is set, this will match the characters <code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">\t\n\r\f\v]</span></code>
plus whatever is classified as space in the Unicode character properties
database.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\S</span></code></dt>
<dd>When the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flag is not specified, matches any non-whitespace
character; this is equivalent to the set <code class="docutils literal notranslate"><span class="pre">[^</span> <span class="pre">\t\n\r\f\v]</span></code> The
<a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> flag has no extra effect on non-whitespace match.  If
<a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> is set, then any character not marked as space in the
Unicode character properties database is matched.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\w</span></code></dt>
<dd>When the <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> and <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flags are not specified, matches
any alphanumeric character and the underscore; this is equivalent to the set
<code class="docutils literal notranslate"><span class="pre">[a-zA-Z0-9_]</span></code>.  With <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a>, it will match the set <code class="docutils literal notranslate"><span class="pre">[0-9_]</span></code> plus
whatever characters are defined as alphanumeric for the current locale.  If
<a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> is set, this will match the characters <code class="docutils literal notranslate"><span class="pre">[0-9_]</span></code> plus whatever
is classified as alphanumeric in the Unicode character properties database.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\W</span></code></dt>
<dd>When the <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> and <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flags are not specified, matches
any non-alphanumeric character; this is equivalent to the set <code class="docutils literal notranslate"><span class="pre">[^a-zA-Z0-9_]</span></code>.
With <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a>, it will match any character not in the set <code class="docutils literal notranslate"><span class="pre">[0-9_]</span></code>, and
not defined as alphanumeric for the current locale. If <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> is set,
this will match anything other than <code class="docutils literal notranslate"><span class="pre">[0-9_]</span></code> plus characters classified as
not alphanumeric in the Unicode character properties database.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">\Z</span></code></dt>
<dd>Matches only at the end of the string.</dd>
</dl>
<p>If both <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> and <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flags are included for a
particular sequence, then <a class="reference internal" href="#re.LOCALE" title="re.LOCALE"><code class="xref py py-const docutils literal notranslate"><span class="pre">LOCALE</span></code></a> flag takes effect first followed by
the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a>.</p>
<p>Most of the standard escapes supported by Python string literals are also
accepted by the regular expression parser:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>\<span class="n">a</span>      \<span class="n">b</span>      \<span class="n">f</span>      \<span class="n">n</span>
\<span class="n">r</span>      \<span class="n">t</span>      \<span class="n">v</span>      \<span class="n">x</span>
\\
</pre></div>
</div>
<p>(Note that <code class="docutils literal notranslate"><span class="pre">\b</span></code> is used to represent word boundaries, and means “backspace”
only inside character classes.)</p>
<p>Octal escapes are included in a limited form: If the first digit is a 0, or if
there are three octal digits, it is considered an octal escape. Otherwise, it is
a group reference.  As for string literals, octal escapes are always at most
three digits in length.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Mastering Regular Expressions</dt>
<dd>Book on regular expressions by Jeffrey Friedl, published by O’Reilly.  The
second edition of the book no longer covers Python at all, but the first
edition covered writing good regular expression patterns in great detail.</dd>
</dl>
</div>
</div>
<div class="section" id="module-contents">
<span id="contents-of-module-re"></span><h2>7.2.2. Module Contents<a class="headerlink" href="#module-contents" title="Permalink to this headline">¶</a></h2>
<p>The module defines several functions, constants, and an exception. Some of the
functions are simplified versions of the full featured methods for compiled
regular expressions.  Most non-trivial applications always use the compiled
form.</p>
<dl class="function">
<dt id="re.compile">
<code class="descclassname">re.</code><code class="descname">compile</code><span class="sig-paren">(</span><em>pattern</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.compile" title="Permalink to this definition">¶</a></dt>
<dd><p>Compile a regular expression pattern into a regular expression object, which
can be used for matching using its <a class="reference internal" href="#re.RegexObject.match" title="re.RegexObject.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> and
<a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> methods, described below.</p>
<p>The expression’s behaviour can be modified by specifying a <em>flags</em> value.
Values can be any of the following variables, combined using bitwise OR (the
<code class="docutils literal notranslate"><span class="pre">|</span></code> operator).</p>
<p>The sequence</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">prog</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="n">pattern</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">prog</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">string</span><span class="p">)</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>
</pre></div>
</div>
<p>but using <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> and saving the resulting regular expression
object for reuse is more efficient when the expression will be used several
times in a single program.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The compiled versions of the most recent patterns passed to
<a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a>, <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a> or <a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.compile()</span></code></a> are cached, so
programs that use only a few regular expressions at a time needn’t worry
about compiling regular expressions.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="re.DEBUG">
<code class="descclassname">re.</code><code class="descname">DEBUG</code><a class="headerlink" href="#re.DEBUG" title="Permalink to this definition">¶</a></dt>
<dd><p>Display debug information about compiled expression.</p>
</dd></dl>

<dl class="data">
<dt id="re.I">
<code class="descclassname">re.</code><code class="descname">I</code><a class="headerlink" href="#re.I" title="Permalink to this definition">¶</a></dt>
<dt id="re.IGNORECASE">
<code class="descclassname">re.</code><code class="descname">IGNORECASE</code><a class="headerlink" href="#re.IGNORECASE" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform case-insensitive matching; expressions like <code class="docutils literal notranslate"><span class="pre">[A-Z]</span></code> will match
lowercase letters, too.  This is not affected by the current locale.  To
get this effect on non-ASCII Unicode characters such as <code class="docutils literal notranslate"><span class="pre">ü</span></code> and <code class="docutils literal notranslate"><span class="pre">Ü</span></code>,
add the <a class="reference internal" href="#re.UNICODE" title="re.UNICODE"><code class="xref py py-const docutils literal notranslate"><span class="pre">UNICODE</span></code></a> flag.</p>
</dd></dl>

<dl class="data">
<dt id="re.L">
<code class="descclassname">re.</code><code class="descname">L</code><a class="headerlink" href="#re.L" title="Permalink to this definition">¶</a></dt>
<dt id="re.LOCALE">
<code class="descclassname">re.</code><code class="descname">LOCALE</code><a class="headerlink" href="#re.LOCALE" title="Permalink to this definition">¶</a></dt>
<dd><p>Make <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\S</span></code> dependent on the
current locale.</p>
</dd></dl>

<dl class="data">
<dt id="re.M">
<code class="descclassname">re.</code><code class="descname">M</code><a class="headerlink" href="#re.M" title="Permalink to this definition">¶</a></dt>
<dt id="re.MULTILINE">
<code class="descclassname">re.</code><code class="descname">MULTILINE</code><a class="headerlink" href="#re.MULTILINE" title="Permalink to this definition">¶</a></dt>
<dd><p>When specified, the pattern character <code class="docutils literal notranslate"><span class="pre">'^'</span></code> matches at the beginning of the
string and at the beginning of each line (immediately following each newline);
and the pattern character <code class="docutils literal notranslate"><span class="pre">'$'</span></code> matches at the end of the string and at the
end of each line (immediately preceding each newline).  By default, <code class="docutils literal notranslate"><span class="pre">'^'</span></code>
matches only at the beginning of the string, and <code class="docutils literal notranslate"><span class="pre">'$'</span></code> only at the end of the
string and immediately before the newline (if any) at the end of the string.</p>
</dd></dl>

<dl class="data">
<dt id="re.S">
<code class="descclassname">re.</code><code class="descname">S</code><a class="headerlink" href="#re.S" title="Permalink to this definition">¶</a></dt>
<dt id="re.DOTALL">
<code class="descclassname">re.</code><code class="descname">DOTALL</code><a class="headerlink" href="#re.DOTALL" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the <code class="docutils literal notranslate"><span class="pre">'.'</span></code> special character match any character at all, including a
newline; without this flag, <code class="docutils literal notranslate"><span class="pre">'.'</span></code> will match anything <em>except</em> a newline.</p>
</dd></dl>

<dl class="data">
<dt id="re.U">
<code class="descclassname">re.</code><code class="descname">U</code><a class="headerlink" href="#re.U" title="Permalink to this definition">¶</a></dt>
<dt id="re.UNICODE">
<code class="descclassname">re.</code><code class="descname">UNICODE</code><a class="headerlink" href="#re.UNICODE" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the <code class="docutils literal notranslate"><span class="pre">\w</span></code>, <code class="docutils literal notranslate"><span class="pre">\W</span></code>, <code class="docutils literal notranslate"><span class="pre">\b</span></code>, <code class="docutils literal notranslate"><span class="pre">\B</span></code>, <code class="docutils literal notranslate"><span class="pre">\d</span></code>, <code class="docutils literal notranslate"><span class="pre">\D</span></code>, <code class="docutils literal notranslate"><span class="pre">\s</span></code> and <code class="docutils literal notranslate"><span class="pre">\S</span></code>
sequences dependent on the Unicode character properties database. Also
enables non-ASCII matching for <a class="reference internal" href="#re.IGNORECASE" title="re.IGNORECASE"><code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORECASE</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="re.X">
<code class="descclassname">re.</code><code class="descname">X</code><a class="headerlink" href="#re.X" title="Permalink to this definition">¶</a></dt>
<dt id="re.VERBOSE">
<code class="descclassname">re.</code><code class="descname">VERBOSE</code><a class="headerlink" href="#re.VERBOSE" title="Permalink to this definition">¶</a></dt>
<dd><p>This flag allows you to write regular expressions that look nicer and are
more readable by allowing you to visually separate logical sections of the
pattern and add comments. Whitespace within the pattern is ignored, except
when in a character class, or when preceded by an unescaped backslash,
or within tokens like <code class="docutils literal notranslate"><span class="pre">*?</span></code>, <code class="docutils literal notranslate"><span class="pre">(?:</span></code> or <code class="docutils literal notranslate"><span class="pre">(?P&lt;...&gt;</span></code>.
When a line contains a <code class="docutils literal notranslate"><span class="pre">#</span></code> that is not in a character class and is not
preceded by an unescaped backslash, all characters from the leftmost such
<code class="docutils literal notranslate"><span class="pre">#</span></code> through the end of the line are ignored.</p>
<p>This means that the two following regular expression objects that match a
decimal number are functionally equal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;&quot;&quot;\d +  # the integral part</span>
<span class="s2">                   \.    # the decimal point</span>
<span class="s2">                   \d *  # some fractional digits&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">X</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\d+\.\d*&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="re.search">
<code class="descclassname">re.</code><code class="descname">search</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.search" title="Permalink to this definition">¶</a></dt>
<dd><p>Scan through <em>string</em> looking for the first location where the regular expression
<em>pattern</em> produces a match, and return a corresponding <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a>
instance. Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no position in the string matches the pattern; note
that this is different from finding a zero-length match at some point in the
string.</p>
</dd></dl>

<dl class="function">
<dt id="re.match">
<code class="descclassname">re.</code><code class="descname">match</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.match" title="Permalink to this definition">¶</a></dt>
<dd><p>If zero or more characters at the beginning of <em>string</em> match the regular
expression <em>pattern</em>, return a corresponding <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> instance.
Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if the string does not match the pattern; note that this is
different from a zero-length match.</p>
<p>Note that even in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode, <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a> will only match
at the beginning of the string and not at the beginning of each line.</p>
<p>If you want to locate a match anywhere in <em>string</em>, use <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a>
instead (see also <a class="reference internal" href="#search-vs-match"><span class="std std-ref">search() vs. match()</span></a>).</p>
</dd></dl>

<dl class="function">
<dt id="re.split">
<code class="descclassname">re.</code><code class="descname">split</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>maxsplit=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Split <em>string</em> by the occurrences of <em>pattern</em>.  If capturing parentheses are
used in <em>pattern</em>, then the text of all groups in the pattern are also returned
as part of the resulting list. If <em>maxsplit</em> is nonzero, at most <em>maxsplit</em>
splits occur, and the remainder of the string is returned as the final element
of the list.  (Incompatibility note: in the original Python 1.5 release,
<em>maxsplit</em> was ignored.  This has been fixed in later releases.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;\W+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words&#39;, &#39;words&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;.&#39;, &#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;\W+&#39;</span><span class="p">,</span> <span class="s1">&#39;Words, words, words.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;Words&#39;, &#39;words, words.&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;[a-f]+&#39;</span><span class="p">,</span> <span class="s1">&#39;0a3B9&#39;</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">[&#39;0&#39;, &#39;3&#39;, &#39;9&#39;]</span>
</pre></div>
</div>
<p>If there are capturing groups in the separator and it matches at the start of
the string, the result will start with an empty string.  The same holds for
the end of the string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;(\W+)&#39;</span><span class="p">,</span> <span class="s1">&#39;...words, words...&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;, &#39;...&#39;, &#39;words&#39;, &#39;, &#39;, &#39;words&#39;, &#39;...&#39;, &#39;&#39;]</span>
</pre></div>
</div>
<p>That way, separator components are always found at the same relative
indices within the result list (e.g., if there’s one capturing group
in the separator, the 0th, the 2nd and so forth).</p>
<p>Note that <em>split</em> will never split a string on an empty pattern match.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;x*&#39;</span><span class="p">,</span> <span class="s1">&#39;foo&#39;</span><span class="p">)</span>
<span class="go">[&#39;foo&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;(?m)^$&quot;</span><span class="p">,</span> <span class="s2">&quot;foo</span><span class="se">\n\n</span><span class="s2">bar</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">[&#39;foo\n\nbar\n&#39;]</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the optional flags argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.findall">
<code class="descclassname">re.</code><code class="descname">findall</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.findall" title="Permalink to this definition">¶</a></dt>
<dd><p>Return all non-overlapping matches of <em>pattern</em> in <em>string</em>, as a list of
strings.  The <em>string</em> is scanned left-to-right, and matches are returned in
the order found.  If one or more groups are present in the pattern, return a
list of groups; this will be a list of tuples if the pattern has more than
one group.  Empty matches are included in the result.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Due to the limitation of the current implementation the character
following an empty match is not included in a next match, so
<code class="docutils literal notranslate"><span class="pre">findall(r'^|\w+',</span> <span class="pre">'two</span> <span class="pre">words')</span></code> returns <code class="docutils literal notranslate"><span class="pre">['',</span> <span class="pre">'wo',</span> <span class="pre">'words']</span></code>
(note missed “t”).  This is changed in Python 3.7.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Added the optional flags argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.finditer">
<code class="descclassname">re.</code><code class="descname">finditer</code><span class="sig-paren">(</span><em>pattern</em>, <em>string</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.finditer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> yielding <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> instances over all
non-overlapping matches for the RE <em>pattern</em> in <em>string</em>.  The <em>string</em> is
scanned left-to-right, and matches are returned in the order found.  Empty
matches are included in the result.  See also the note about <a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Added the optional flags argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.sub">
<code class="descclassname">re.</code><code class="descname">sub</code><span class="sig-paren">(</span><em>pattern</em>, <em>repl</em>, <em>string</em>, <em>count=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.sub" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string obtained by replacing the leftmost non-overlapping occurrences
of <em>pattern</em> in <em>string</em> by the replacement <em>repl</em>.  If the pattern isn’t found,
<em>string</em> is returned unchanged.  <em>repl</em> can be a string or a function; if it is
a string, any backslash escapes in it are processed.  That is, <code class="docutils literal notranslate"><span class="pre">\n</span></code> is
converted to a single newline character, <code class="docutils literal notranslate"><span class="pre">\r</span></code> is converted to a carriage return, and
so forth.  Unknown escapes such as <code class="docutils literal notranslate"><span class="pre">\j</span></code> are left alone.  Backreferences, such
as <code class="docutils literal notranslate"><span class="pre">\6</span></code>, are replaced with the substring matched by group 6 in the pattern.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):&#39;</span><span class="p">,</span>
<span class="gp">... </span>       <span class="sa">r</span><span class="s1">&#39;static PyObject*\npy_\1(void)\n{&#39;</span><span class="p">,</span>
<span class="gp">... </span>       <span class="s1">&#39;def myfunc():&#39;</span><span class="p">)</span>
<span class="go">&#39;static PyObject*\npy_myfunc(void)\n{&#39;</span>
</pre></div>
</div>
<p>If <em>repl</em> is a function, it is called for every non-overlapping occurrence of
<em>pattern</em>.  The function takes a single match object argument, and returns the
replacement string.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">dashrepl</span><span class="p">(</span><span class="n">matchobj</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">matchobj</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">==</span> <span class="s1">&#39;-&#39;</span><span class="p">:</span> <span class="k">return</span> <span class="s1">&#39; &#39;</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span> <span class="k">return</span> <span class="s1">&#39;-&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s1">&#39;-{1,2}&#39;</span><span class="p">,</span> <span class="n">dashrepl</span><span class="p">,</span> <span class="s1">&#39;pro----gram-files&#39;</span><span class="p">)</span>
<span class="go">&#39;pro--gram files&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\sAND\s&#39;</span><span class="p">,</span> <span class="s1">&#39; &amp; &#39;</span><span class="p">,</span> <span class="s1">&#39;Baked Beans And Spam&#39;</span><span class="p">,</span> <span class="n">flags</span><span class="o">=</span><span class="n">re</span><span class="o">.</span><span class="n">IGNORECASE</span><span class="p">)</span>
<span class="go">&#39;Baked Beans &amp; Spam&#39;</span>
</pre></div>
</div>
<p>The pattern may be a string or an RE object.</p>
<p>The optional argument <em>count</em> is the maximum number of pattern occurrences to be
replaced; <em>count</em> must be a non-negative integer.  If omitted or zero, all
occurrences will be replaced. Empty matches for the pattern are replaced only
when not adjacent to a previous match, so <code class="docutils literal notranslate"><span class="pre">sub('x*',</span> <span class="pre">'-',</span> <span class="pre">'abc')</span></code> returns
<code class="docutils literal notranslate"><span class="pre">'-a-b-c-'</span></code>.</p>
<p>In string-type <em>repl</em> arguments, in addition to the character escapes and
backreferences described above,
<code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code> will use the substring matched by the group named <code class="docutils literal notranslate"><span class="pre">name</span></code>, as
defined by the <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> syntax. <code class="docutils literal notranslate"><span class="pre">\g&lt;number&gt;</span></code> uses the corresponding
group number; <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;</span></code> is therefore equivalent to <code class="docutils literal notranslate"><span class="pre">\2</span></code>, but isn’t ambiguous
in a replacement such as <code class="docutils literal notranslate"><span class="pre">\g&lt;2&gt;0</span></code>.  <code class="docutils literal notranslate"><span class="pre">\20</span></code> would be interpreted as a
reference to group 20, not a reference to group 2 followed by the literal
character <code class="docutils literal notranslate"><span class="pre">'0'</span></code>.  The backreference <code class="docutils literal notranslate"><span class="pre">\g&lt;0&gt;</span></code> substitutes in the entire
substring matched by the RE.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the optional flags argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.subn">
<code class="descclassname">re.</code><code class="descname">subn</code><span class="sig-paren">(</span><em>pattern</em>, <em>repl</em>, <em>string</em>, <em>count=0</em>, <em>flags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.subn" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the same operation as <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a>, but return a tuple <code class="docutils literal notranslate"><span class="pre">(new_string,</span>
<span class="pre">number_of_subs_made)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the optional flags argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="re.escape">
<code class="descclassname">re.</code><code class="descname">escape</code><span class="sig-paren">(</span><em>pattern</em><span class="sig-paren">)</span><a class="headerlink" href="#re.escape" title="Permalink to this definition">¶</a></dt>
<dd><p>Escape all the characters in <em>pattern</em> except ASCII letters and numbers.
This is useful if you want to match an arbitrary literal string that may
have regular expression metacharacters in it.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="s1">&#39;python.exe&#39;</span><span class="p">)</span>
<span class="go">python\.exe</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">legal_chars</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">ascii_lowercase</span> <span class="o">+</span> <span class="n">string</span><span class="o">.</span><span class="n">digits</span> <span class="o">+</span> <span class="s2">&quot;!#$%&amp;&#39;*+-.^_`|~:&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;[</span><span class="si">%s</span><span class="s1">]+&#39;</span> <span class="o">%</span> <span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">(</span><span class="n">legal_chars</span><span class="p">)</span>
<span class="go">[abcdefghijklmnopqrstuvwxyz0123456789\!\#\$\%\&amp;\&#39;\*\+\-\.\^\_\`\|\~\:]+</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">operators</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;+&#39;</span><span class="p">,</span> <span class="s1">&#39;-&#39;</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="s1">&#39;/&#39;</span><span class="p">,</span> <span class="s1">&#39;**&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;|&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">re</span><span class="o">.</span><span class="n">escape</span><span class="p">,</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">operators</span><span class="p">,</span> <span class="n">reverse</span><span class="o">=</span><span class="kc">True</span><span class="p">)))</span>
<span class="go">\/|\-|\+|\*\*|\*</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="re.purge">
<code class="descclassname">re.</code><code class="descname">purge</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#re.purge" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the regular expression cache.</p>
</dd></dl>

<dl class="exception">
<dt id="re.error">
<em class="property">exception </em><code class="descclassname">re.</code><code class="descname">error</code><a class="headerlink" href="#re.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a string passed to one of the functions here is not a
valid regular expression (for example, it might contain unmatched parentheses)
or when some other error occurs during compilation or matching.  It is never an
error if a string contains no match for a pattern.</p>
</dd></dl>

</div>
<div class="section" id="regular-expression-objects">
<span id="re-objects"></span><h2>7.2.3. Regular Expression Objects<a class="headerlink" href="#regular-expression-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="re.RegexObject">
<em class="property">class </em><code class="descclassname">re.</code><code class="descname">RegexObject</code><a class="headerlink" href="#re.RegexObject" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#re.RegexObject" title="re.RegexObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegexObject</span></code></a> class supports the following methods and attributes:</p>
<dl class="method">
<dt id="re.RegexObject.search">
<code class="descname">search</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.search" title="Permalink to this definition">¶</a></dt>
<dd><p>Scan through <em>string</em> looking for a location where this regular expression
produces a match, and return a corresponding <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> instance.
Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if no position in the string matches the pattern; note that this
is different from finding a zero-length match at some point in the string.</p>
<p>The optional second parameter <em>pos</em> gives an index in the string where the
search is to start; it defaults to <code class="docutils literal notranslate"><span class="pre">0</span></code>.  This is not completely equivalent to
slicing the string; the <code class="docutils literal notranslate"><span class="pre">'^'</span></code> pattern character matches at the real beginning
of the string and at positions just after a newline, but not necessarily at the
index where the search is to start.</p>
<p>The optional parameter <em>endpos</em> limits how far the string will be searched; it
will be as if the string is <em>endpos</em> characters long, so only the characters
from <em>pos</em> to <code class="docutils literal notranslate"><span class="pre">endpos</span> <span class="pre">-</span> <span class="pre">1</span></code> will be searched for a match.  If <em>endpos</em> is less
than <em>pos</em>, no match will be found, otherwise, if <em>rx</em> is a compiled regular
expression object, <code class="docutils literal notranslate"><span class="pre">rx.search(string,</span> <span class="pre">0,</span> <span class="pre">50)</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">rx.search(string[:50],</span> <span class="pre">0)</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;d&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">)</span>     <span class="c1"># Match at index 0</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>  <span class="c1"># No match; search doesn&#39;t include the &quot;d&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.match">
<code class="descname">match</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.match" title="Permalink to this definition">¶</a></dt>
<dd><p>If zero or more characters at the <em>beginning</em> of <em>string</em> match this regular
expression, return a corresponding <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> instance.  Return
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the string does not match the pattern; note that this is different
from a zero-length match.</p>
<p>The optional <em>pos</em> and <em>endpos</em> parameters have the same meaning as for the
<a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;o&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">)</span>      <span class="c1"># No match as &quot;o&quot; is not at the start of &quot;dog&quot;.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pattern</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;dog&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>   <span class="c1"># Match as &quot;o&quot; is the 2nd character of &quot;dog&quot;.</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
<p>If you want to locate a match anywhere in <em>string</em>, use
<a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> instead (see also <a class="reference internal" href="#search-vs-match"><span class="std std-ref">search() vs. match()</span></a>).</p>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.split">
<code class="descname">split</code><span class="sig-paren">(</span><em>string</em>, <em>maxsplit=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> function, using the compiled pattern.</p>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.findall">
<code class="descname">findall</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.findall" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a> function, using the compiled pattern, but
also accepts optional <em>pos</em> and <em>endpos</em> parameters that limit the search
region like for <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.finditer">
<code class="descname">finditer</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>pos</em><span class="optional">[</span>, <em>endpos</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.finditer" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to the <a class="reference internal" href="#re.finditer" title="re.finditer"><code class="xref py py-func docutils literal notranslate"><span class="pre">finditer()</span></code></a> function, using the compiled pattern, but
also accepts optional <em>pos</em> and <em>endpos</em> parameters that limit the search
region like for <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.sub">
<code class="descname">sub</code><span class="sig-paren">(</span><em>repl</em>, <em>string</em>, <em>count=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.sub" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> function, using the compiled pattern.</p>
</dd></dl>

<dl class="method">
<dt id="re.RegexObject.subn">
<code class="descname">subn</code><span class="sig-paren">(</span><em>repl</em>, <em>string</em>, <em>count=0</em><span class="sig-paren">)</span><a class="headerlink" href="#re.RegexObject.subn" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#re.subn" title="re.subn"><code class="xref py py-func docutils literal notranslate"><span class="pre">subn()</span></code></a> function, using the compiled pattern.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.RegexObject.flags">
<code class="descname">flags</code><a class="headerlink" href="#re.RegexObject.flags" title="Permalink to this definition">¶</a></dt>
<dd><p>The regex matching flags.  This is a combination of the flags given to
<a class="reference internal" href="#re.compile" title="re.compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> and any <code class="docutils literal notranslate"><span class="pre">(?...)</span></code> inline flags in the pattern.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.RegexObject.groups">
<code class="descname">groups</code><a class="headerlink" href="#re.RegexObject.groups" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of capturing groups in the pattern.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.RegexObject.groupindex">
<code class="descname">groupindex</code><a class="headerlink" href="#re.RegexObject.groupindex" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping any symbolic group names defined by <code class="docutils literal notranslate"><span class="pre">(?P&lt;id&gt;)</span></code> to group
numbers.  The dictionary is empty if no symbolic groups were used in the
pattern.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.RegexObject.pattern">
<code class="descname">pattern</code><a class="headerlink" href="#re.RegexObject.pattern" title="Permalink to this definition">¶</a></dt>
<dd><p>The pattern string from which the RE object was compiled.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="match-objects">
<span id="id1"></span><h2>7.2.4. Match Objects<a class="headerlink" href="#match-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="re.MatchObject">
<em class="property">class </em><code class="descclassname">re.</code><code class="descname">MatchObject</code><a class="headerlink" href="#re.MatchObject" title="Permalink to this definition">¶</a></dt>
<dd><p>Match objects always have a boolean value of <code class="docutils literal notranslate"><span class="pre">True</span></code>.
Since <code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code> return <code class="docutils literal notranslate"><span class="pre">None</span></code>
when there is no match, you can test whether there was a match with a simple
<code class="docutils literal notranslate"><span class="pre">if</span></code> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">match</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">string</span><span class="p">)</span>
<span class="k">if</span> <span class="n">match</span><span class="p">:</span>
    <span class="n">process</span><span class="p">(</span><span class="n">match</span><span class="p">)</span>
</pre></div>
</div>
<p>Match objects support the following methods and attributes:</p>
<dl class="method">
<dt id="re.MatchObject.expand">
<code class="descname">expand</code><span class="sig-paren">(</span><em>template</em><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.expand" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string obtained by doing backslash substitution on the template
string <em>template</em>, as done by the <a class="reference internal" href="#re.RegexObject.sub" title="re.RegexObject.sub"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sub()</span></code></a> method.  Escapes
such as <code class="docutils literal notranslate"><span class="pre">\n</span></code> are converted to the appropriate characters, and numeric
backreferences (<code class="docutils literal notranslate"><span class="pre">\1</span></code>, <code class="docutils literal notranslate"><span class="pre">\2</span></code>) and named backreferences (<code class="docutils literal notranslate"><span class="pre">\g&lt;1&gt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">\g&lt;name&gt;</span></code>) are replaced by the contents of the corresponding group.</p>
</dd></dl>

<dl class="method">
<dt id="re.MatchObject.group">
<code class="descname">group</code><span class="sig-paren">(</span><span class="optional">[</span><em>group1</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.group" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns one or more subgroups of the match.  If there is a single argument, the
result is a single string; if there are multiple arguments, the result is a
tuple with one item per argument. Without arguments, <em>group1</em> defaults to zero
(the whole match is returned). If a <em>groupN</em> argument is zero, the corresponding
return value is the entire matching string; if it is in the inclusive range
[1..99], it is the string matching the corresponding parenthesized group.  If a
group number is negative or larger than the number of groups defined in the
pattern, an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception is raised. If a group is contained in a
part of the pattern that did not match, the corresponding result is <code class="docutils literal notranslate"><span class="pre">None</span></code>.
If a group is contained in a part of the pattern that matched multiple times,
the last match is returned.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w+) (\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Isaac Newton, physicist&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>       <span class="c1"># The entire match</span>
<span class="go">&#39;Isaac Newton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>       <span class="c1"># The first parenthesized subgroup.</span>
<span class="go">&#39;Isaac&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>       <span class="c1"># The second parenthesized subgroup.</span>
<span class="go">&#39;Newton&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>    <span class="c1"># Multiple arguments give us a tuple.</span>
<span class="go">(&#39;Isaac&#39;, &#39;Newton&#39;)</span>
</pre></div>
</div>
<p>If the regular expression uses the <code class="docutils literal notranslate"><span class="pre">(?P&lt;name&gt;...)</span></code> syntax, the <em>groupN</em>
arguments may also be strings identifying groups by their group name.  If a
string argument is not used as a group name in the pattern, an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a>
exception is raised.</p>
<p>A moderately complicated example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(?P&lt;first_name&gt;\w+) (?P&lt;last_name&gt;\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Malcolm Reynolds&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;first_name&#39;</span><span class="p">)</span>
<span class="go">&#39;Malcolm&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="s1">&#39;last_name&#39;</span><span class="p">)</span>
<span class="go">&#39;Reynolds&#39;</span>
</pre></div>
</div>
<p>Named groups can also be referred to by their index:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;Malcolm&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;Reynolds&#39;</span>
</pre></div>
</div>
<p>If a group matches multiple times, only the last match is accessible:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(..)+&quot;</span><span class="p">,</span> <span class="s2">&quot;a1b2c3&quot;</span><span class="p">)</span>  <span class="c1"># Matches 3 times.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>                        <span class="c1"># Returns only the last match.</span>
<span class="go">&#39;c3&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.MatchObject.groups">
<code class="descname">groups</code><span class="sig-paren">(</span><span class="optional">[</span><em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.groups" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing all the subgroups of the match, from 1 up to however
many groups are in the pattern.  The <em>default</em> argument is used for groups that
did not participate in the match; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.  (Incompatibility
note: in the original Python 1.5 release, if the tuple was one element long, a
string would be returned instead.  In later versions (from 1.5.1 on), a
singleton tuple is returned in such cases.)</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\d+)\.(\d+)&quot;</span><span class="p">,</span> <span class="s2">&quot;24.1632&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
<span class="go">(&#39;24&#39;, &#39;1632&#39;)</span>
</pre></div>
</div>
<p>If we make the decimal place and everything after it optional, not all groups
might participate in the match.  These groups will default to <code class="docutils literal notranslate"><span class="pre">None</span></code> unless
the <em>default</em> argument is given:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\d+)\.?(\d+)?&quot;</span><span class="p">,</span> <span class="s2">&quot;24&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>      <span class="c1"># Second group defaults to None.</span>
<span class="go">(&#39;24&#39;, None)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">(</span><span class="s1">&#39;0&#39;</span><span class="p">)</span>   <span class="c1"># Now, the second group defaults to &#39;0&#39;.</span>
<span class="go">(&#39;24&#39;, &#39;0&#39;)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.MatchObject.groupdict">
<code class="descname">groupdict</code><span class="sig-paren">(</span><span class="optional">[</span><em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.groupdict" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary containing all the <em>named</em> subgroups of the match, keyed by
the subgroup name.  The <em>default</em> argument is used for groups that did not
participate in the match; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(?P&lt;first_name&gt;\w+) (?P&lt;last_name&gt;\w+)&quot;</span><span class="p">,</span> <span class="s2">&quot;Malcolm Reynolds&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">groupdict</span><span class="p">()</span>
<span class="go">{&#39;first_name&#39;: &#39;Malcolm&#39;, &#39;last_name&#39;: &#39;Reynolds&#39;}</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.MatchObject.start">
<code class="descname">start</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.start" title="Permalink to this definition">¶</a></dt>
<dt id="re.MatchObject.end">
<code class="descname">end</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.end" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the indices of the start and end of the substring matched by <em>group</em>;
<em>group</em> defaults to zero (meaning the whole matched substring). Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if
<em>group</em> exists but did not contribute to the match.  For a match object <em>m</em>, and
a group <em>g</em> that did contribute to the match, the substring matched by group <em>g</em>
(equivalent to <code class="docutils literal notranslate"><span class="pre">m.group(g)</span></code>) is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">m</span><span class="o">.</span><span class="n">string</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(</span><span class="n">g</span><span class="p">):</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(</span><span class="n">g</span><span class="p">)]</span>
</pre></div>
</div>
<p>Note that <code class="docutils literal notranslate"><span class="pre">m.start(group)</span></code> will equal <code class="docutils literal notranslate"><span class="pre">m.end(group)</span></code> if <em>group</em> matched a
null string.  For example, after <code class="docutils literal notranslate"><span class="pre">m</span> <span class="pre">=</span> <span class="pre">re.search('b(c?)',</span> <span class="pre">'cba')</span></code>,
<code class="docutils literal notranslate"><span class="pre">m.start(0)</span></code> is 1, <code class="docutils literal notranslate"><span class="pre">m.end(0)</span></code> is 2, <code class="docutils literal notranslate"><span class="pre">m.start(1)</span></code> and <code class="docutils literal notranslate"><span class="pre">m.end(1)</span></code> are both
2, and <code class="docutils literal notranslate"><span class="pre">m.start(2)</span></code> raises an <a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception.</p>
<p>An example that will remove <em>remove_this</em> from email addresses:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">email</span> <span class="o">=</span> <span class="s2">&quot;tony@tiremove_thisger.net&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;remove_this&quot;</span><span class="p">,</span> <span class="n">email</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">email</span><span class="p">[:</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">()]</span> <span class="o">+</span> <span class="n">email</span><span class="p">[</span><span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">():]</span>
<span class="go">&#39;tony@tiger.net&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="re.MatchObject.span">
<code class="descname">span</code><span class="sig-paren">(</span><span class="optional">[</span><em>group</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#re.MatchObject.span" title="Permalink to this definition">¶</a></dt>
<dd><p>For <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> <em>m</em>, return the 2-tuple <code class="docutils literal notranslate"><span class="pre">(m.start(group),</span>
<span class="pre">m.end(group))</span></code>. Note that if <em>group</em> did not contribute to the match, this is
<code class="docutils literal notranslate"><span class="pre">(-1,</span> <span class="pre">-1)</span></code>.  <em>group</em> defaults to zero, the entire match.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.pos">
<code class="descname">pos</code><a class="headerlink" href="#re.MatchObject.pos" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of <em>pos</em> which was passed to the <a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> or
<a class="reference internal" href="#re.RegexObject.match" title="re.RegexObject.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> method of the <a class="reference internal" href="#re.RegexObject" title="re.RegexObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegexObject</span></code></a>.  This is the
index into the string at which the RE engine started looking for a match.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.endpos">
<code class="descname">endpos</code><a class="headerlink" href="#re.MatchObject.endpos" title="Permalink to this definition">¶</a></dt>
<dd><p>The value of <em>endpos</em> which was passed to the <a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> or
<a class="reference internal" href="#re.RegexObject.match" title="re.RegexObject.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> method of the <a class="reference internal" href="#re.RegexObject" title="re.RegexObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">RegexObject</span></code></a>.  This is the
index into the string beyond which the RE engine will not go.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.lastindex">
<code class="descname">lastindex</code><a class="headerlink" href="#re.MatchObject.lastindex" title="Permalink to this definition">¶</a></dt>
<dd><p>The integer index of the last matched capturing group, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no group
was matched at all. For example, the expressions <code class="docutils literal notranslate"><span class="pre">(a)b</span></code>, <code class="docutils literal notranslate"><span class="pre">((a)(b))</span></code>, and
<code class="docutils literal notranslate"><span class="pre">((ab))</span></code> will have <code class="docutils literal notranslate"><span class="pre">lastindex</span> <span class="pre">==</span> <span class="pre">1</span></code> if applied to the string <code class="docutils literal notranslate"><span class="pre">'ab'</span></code>, while
the expression <code class="docutils literal notranslate"><span class="pre">(a)(b)</span></code> will have <code class="docutils literal notranslate"><span class="pre">lastindex</span> <span class="pre">==</span> <span class="pre">2</span></code>, if applied to the same
string.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.lastgroup">
<code class="descname">lastgroup</code><a class="headerlink" href="#re.MatchObject.lastgroup" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the last matched capturing group, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the group didn’t
have a name, or if no group was matched at all.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.re">
<code class="descname">re</code><a class="headerlink" href="#re.MatchObject.re" title="Permalink to this definition">¶</a></dt>
<dd><p>The regular expression object whose <a class="reference internal" href="#re.RegexObject.match" title="re.RegexObject.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> or
<a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a> method produced this <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a>
instance.</p>
</dd></dl>

<dl class="attribute">
<dt id="re.MatchObject.string">
<code class="descname">string</code><a class="headerlink" href="#re.MatchObject.string" title="Permalink to this definition">¶</a></dt>
<dd><p>The string passed to <a class="reference internal" href="#re.RegexObject.match" title="re.RegexObject.match"><code class="xref py py-meth docutils literal notranslate"><span class="pre">match()</span></code></a> or
<a class="reference internal" href="#re.RegexObject.search" title="re.RegexObject.search"><code class="xref py py-meth docutils literal notranslate"><span class="pre">search()</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="examples">
<h2>7.2.5. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<div class="section" id="checking-for-a-pair">
<h3>7.2.5.1. Checking For a Pair<a class="headerlink" href="#checking-for-a-pair" title="Permalink to this headline">¶</a></h3>
<p>In this example, we’ll use the following helper function to display match
objects a little more gracefully:</p>
<div class="highlight-python notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">displaymatch</span><span class="p">(</span><span class="n">match</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">match</span> <span class="ow">is</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">return</span> <span class="bp">None</span>
    <span class="k">return</span> <span class="s1">&#39;&lt;Match: </span><span class="si">%r</span><span class="s1">, groups=</span><span class="si">%r</span><span class="s1">&gt;&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">match</span><span class="o">.</span><span class="n">group</span><span class="p">(),</span> <span class="n">match</span><span class="o">.</span><span class="n">groups</span><span class="p">())</span>
</pre></div>
</div>
<p>Suppose you are writing a poker program where a player’s hand is represented as
a 5-character string with each character representing a card, “a” for ace, “k”
for king, “q” for queen, “j” for jack, “t” for 10, and “2” through “9”
representing the card with that value.</p>
<p>To see if a given string is a valid hand, one could do the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">valid</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;^[a2-9tjqk]</span><span class="si">{5}</span><span class="s2">$&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt5q&quot;</span><span class="p">))</span>  <span class="c1"># Valid.</span>
<span class="go">&quot;&lt;Match: &#39;akt5q&#39;, groups=()&gt;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt5e&quot;</span><span class="p">))</span>  <span class="c1"># Invalid.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;akt&quot;</span><span class="p">))</span>    <span class="c1"># Invalid.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">valid</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;727ak&quot;</span><span class="p">))</span>  <span class="c1"># Valid.</span>
<span class="go">&quot;&lt;Match: &#39;727ak&#39;, groups=()&gt;&quot;</span>
</pre></div>
</div>
<p>That last hand, <code class="docutils literal notranslate"><span class="pre">&quot;727ak&quot;</span></code>, contained a pair, or two of the same valued cards.
To match this with a regular expression, one could use backreferences as such:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;.*(.).*\1&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;717ak&quot;</span><span class="p">))</span>     <span class="c1"># Pair of 7s.</span>
<span class="go">&quot;&lt;Match: &#39;717&#39;, groups=(&#39;7&#39;,)&gt;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;718ak&quot;</span><span class="p">))</span>     <span class="c1"># No pairs.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">displaymatch</span><span class="p">(</span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;354aa&quot;</span><span class="p">))</span>     <span class="c1"># Pair of aces.</span>
<span class="go">&quot;&lt;Match: &#39;354aa&#39;, groups=(&#39;a&#39;,)&gt;&quot;</span>
</pre></div>
</div>
<p>To find out what card the pair consists of, one could use the
<a class="reference internal" href="#re.MatchObject.group" title="re.MatchObject.group"><code class="xref py py-meth docutils literal notranslate"><span class="pre">group()</span></code></a> method of <a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> in the following
manner:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;717ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;7&#39;</span>

<span class="go"># Error because re.match() returns None, which doesn&#39;t have a group() method:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;718ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;pyshell#23&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
    <span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;.*(.).*\1&quot;</span><span class="p">,</span> <span class="s2">&quot;718ak&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;NoneType&#39; object has no attribute &#39;group&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">pair</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;354aa&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;a&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="simulating-scanf">
<h3>7.2.5.2. Simulating scanf()<a class="headerlink" href="#simulating-scanf" title="Permalink to this headline">¶</a></h3>
<p id="index-0">Python does not currently have an equivalent to <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code>.  Regular
expressions are generally more powerful, though also more verbose, than
<code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> format strings.  The table below offers some more-or-less
equivalent mappings between <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> format tokens and regular
expressions.</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"><code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> Token</th>
<th class="head">Regular Expression</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%c</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">.</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%5c</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">.{5}</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%d</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?\d+</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%e</span></code>, <code class="docutils literal notranslate"><span class="pre">%E</span></code>, <code class="docutils literal notranslate"><span class="pre">%f</span></code>, <code class="docutils literal notranslate"><span class="pre">%g</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%i</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(0[xX][\dA-Fa-f]+|0[0-7]*|\d+)</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%o</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?[0-7]+</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%s</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">\S+</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%u</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">\d+</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%x</span></code>, <code class="docutils literal notranslate"><span class="pre">%X</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">[-+]?(0[xX])?[\dA-Fa-f]+</span></code></td>
</tr>
</tbody>
</table>
<p>To extract the filename and numbers from a string like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">sbin</span><span class="o">/</span><span class="n">sendmail</span> <span class="o">-</span> <span class="mi">0</span> <span class="n">errors</span><span class="p">,</span> <span class="mi">4</span> <span class="n">warnings</span>
</pre></div>
</div>
<p>you would use a <code class="xref c c-func docutils literal notranslate"><span class="pre">scanf()</span></code> format like</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="n">s</span> <span class="o">-</span> <span class="o">%</span><span class="n">d</span> <span class="n">errors</span><span class="p">,</span> <span class="o">%</span><span class="n">d</span> <span class="n">warnings</span>
</pre></div>
</div>
<p>The equivalent regular expression would be</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span>\<span class="n">S</span><span class="o">+</span><span class="p">)</span> <span class="o">-</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">errors</span><span class="p">,</span> <span class="p">(</span>\<span class="n">d</span><span class="o">+</span><span class="p">)</span> <span class="n">warnings</span>
</pre></div>
</div>
</div>
<div class="section" id="search-vs-match">
<span id="id2"></span><h3>7.2.5.3. search() vs. match()<a class="headerlink" href="#search-vs-match" title="Permalink to this headline">¶</a></h3>
<p>Python offers two different primitive operations based on regular expressions:
<a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.match()</span></code></a> checks for a match only at the beginning of the string, while
<a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a> checks for a match anywhere in the string (this is what Perl
does by default).</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>    <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>   <span class="c1"># Match</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
<p>Regular expressions beginning with <code class="docutils literal notranslate"><span class="pre">'^'</span></code> can be used with <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> to
restrict the match at the beginning of the string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>    <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;^c&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>  <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s2">&quot;^a&quot;</span><span class="p">,</span> <span class="s2">&quot;abcdef&quot;</span><span class="p">)</span>  <span class="c1"># Match</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
<p>Note however that in <a class="reference internal" href="#re.MULTILINE" title="re.MULTILINE"><code class="xref py py-const docutils literal notranslate"><span class="pre">MULTILINE</span></code></a> mode <a class="reference internal" href="#re.match" title="re.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">match()</span></code></a> only matches at the
beginning of the string, whereas using <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> with a regular expression
beginning with <code class="docutils literal notranslate"><span class="pre">'^'</span></code> will match at the beginning of each line.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s1">&#39;X&#39;</span><span class="p">,</span> <span class="s1">&#39;A</span><span class="se">\n</span><span class="s1">B</span><span class="se">\n</span><span class="s1">X&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c1"># No match</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s1">&#39;^X&#39;</span><span class="p">,</span> <span class="s1">&#39;A</span><span class="se">\n</span><span class="s1">B</span><span class="se">\n</span><span class="s1">X&#39;</span><span class="p">,</span> <span class="n">re</span><span class="o">.</span><span class="n">MULTILINE</span><span class="p">)</span>  <span class="c1"># Match</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="making-a-phonebook">
<h3>7.2.5.4. Making a Phonebook<a class="headerlink" href="#making-a-phonebook" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> splits a string into a list delimited by the passed pattern.  The
method is invaluable for converting textual data into data structures that can be
easily read and modified by Python as demonstrated in the following example that
creates a phonebook.</p>
<p>First, here is the input.  Normally it may come from a file, here we are using
triple-quoted string syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Ross McFluff: 834.345.1254 155 Elm Street</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">Ronald Heathmore: 892.345.3428 436 Finley Avenue</span>
<span class="gp">... </span><span class="s2">Frank Burger: 925.541.7625 662 South Dogwood Way</span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">...</span><span class="s2"></span>
<span class="gp">... </span><span class="s2">Heather Albrecht: 548.326.4584 919 Park Place&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>The entries are separated by one or more newlines. Now we convert the string
into a list with each nonempty line having its own entry:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">entries</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">+&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">entries</span>
<span class="go">[&#39;Ross McFluff: 834.345.1254 155 Elm Street&#39;,</span>
<span class="go">&#39;Ronald Heathmore: 892.345.3428 436 Finley Avenue&#39;,</span>
<span class="go">&#39;Frank Burger: 925.541.7625 662 South Dogwood Way&#39;,</span>
<span class="go">&#39;Heather Albrecht: 548.326.4584 919 Park Place&#39;]</span>
</pre></div>
</div>
<p>Finally, split each entry into a list with first name, last name, telephone
number, and address.  We use the <code class="docutils literal notranslate"><span class="pre">maxsplit</span></code> parameter of <a class="reference internal" href="#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>
because the address has spaces, our splitting pattern, in it:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;:? &quot;</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[[&#39;Ross&#39;, &#39;McFluff&#39;, &#39;834.345.1254&#39;, &#39;155 Elm Street&#39;],</span>
<span class="go">[&#39;Ronald&#39;, &#39;Heathmore&#39;, &#39;892.345.3428&#39;, &#39;436 Finley Avenue&#39;],</span>
<span class="go">[&#39;Frank&#39;, &#39;Burger&#39;, &#39;925.541.7625&#39;, &#39;662 South Dogwood Way&#39;],</span>
<span class="go">[&#39;Heather&#39;, &#39;Albrecht&#39;, &#39;548.326.4584&#39;, &#39;919 Park Place&#39;]]</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">:?</span></code> pattern matches the colon after the last name, so that it does not
occur in the result list.  With a <code class="docutils literal notranslate"><span class="pre">maxsplit</span></code> of <code class="docutils literal notranslate"><span class="pre">4</span></code>, we could separate the
house number from the street name:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">re</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;:? &quot;</span><span class="p">,</span> <span class="n">entry</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span> <span class="k">for</span> <span class="n">entry</span> <span class="ow">in</span> <span class="n">entries</span><span class="p">]</span>
<span class="go">[[&#39;Ross&#39;, &#39;McFluff&#39;, &#39;834.345.1254&#39;, &#39;155&#39;, &#39;Elm Street&#39;],</span>
<span class="go">[&#39;Ronald&#39;, &#39;Heathmore&#39;, &#39;892.345.3428&#39;, &#39;436&#39;, &#39;Finley Avenue&#39;],</span>
<span class="go">[&#39;Frank&#39;, &#39;Burger&#39;, &#39;925.541.7625&#39;, &#39;662&#39;, &#39;South Dogwood Way&#39;],</span>
<span class="go">[&#39;Heather&#39;, &#39;Albrecht&#39;, &#39;548.326.4584&#39;, &#39;919&#39;, &#39;Park Place&#39;]]</span>
</pre></div>
</div>
</div>
<div class="section" id="text-munging">
<h3>7.2.5.5. Text Munging<a class="headerlink" href="#text-munging" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> replaces every occurrence of a pattern with a string or the
result of a function.  This example demonstrates using <a class="reference internal" href="#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a> with
a function to “munge” text, or randomize the order of all the characters
in each word of a sentence except for the first and last characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">repl</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">inner_word</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">2</span><span class="p">))</span>
<span class="gp">... </span>    <span class="n">random</span><span class="o">.</span><span class="n">shuffle</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">inner_word</span><span class="p">)</span> <span class="o">+</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;Professor Abdolmalek, please report your absences promptly.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w)(\w+)(\w)&quot;</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">&#39;Poefsrosr Aealmlobdk, pslaee reorpt your abnseces plmrptoy.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;(\w)(\w+)(\w)&quot;</span><span class="p">,</span> <span class="n">repl</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">&#39;Pofsroser Aodlambelk, plasee reoprt yuor asnebces potlmrpy.&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="finding-all-adverbs">
<h3>7.2.5.6. Finding all Adverbs<a class="headerlink" href="#finding-all-adverbs" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a> matches <em>all</em> occurrences of a pattern, not just the first
one as <a class="reference internal" href="#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">search()</span></code></a> does.  For example, if a writer wanted to
find all of the adverbs in some text, they might use <a class="reference internal" href="#re.findall" title="re.findall"><code class="xref py py-func docutils literal notranslate"><span class="pre">findall()</span></code></a> in
the following manner:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;He was carefully disguised but captured quickly by police.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\w+ly&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="go">[&#39;carefully&#39;, &#39;quickly&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="finding-all-adverbs-and-their-positions">
<h3>7.2.5.7. Finding all Adverbs and their Positions<a class="headerlink" href="#finding-all-adverbs-and-their-positions" title="Permalink to this headline">¶</a></h3>
<p>If one wants more information about all matches of a pattern than the matched
text, <a class="reference internal" href="#re.finditer" title="re.finditer"><code class="xref py py-func docutils literal notranslate"><span class="pre">finditer()</span></code></a> is useful as it provides instances of
<a class="reference internal" href="#re.MatchObject" title="re.MatchObject"><code class="xref py py-class docutils literal notranslate"><span class="pre">MatchObject</span></code></a> instead of strings.  Continuing with the previous example,
if a writer wanted to find all of the adverbs <em>and their positions</em>
in some text, they would use <a class="reference internal" href="#re.finditer" title="re.finditer"><code class="xref py py-func docutils literal notranslate"><span class="pre">finditer()</span></code></a> in the following manner:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;He was carefully disguised but captured quickly by police.&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">re</span><span class="o">.</span><span class="n">finditer</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\w+ly&quot;</span><span class="p">,</span> <span class="n">text</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%02d</span><span class="s1">-</span><span class="si">%02d</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">m</span><span class="o">.</span><span class="n">start</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">end</span><span class="p">(),</span> <span class="n">m</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">))</span>
<span class="go">07-16: carefully</span>
<span class="go">40-47: quickly</span>
</pre></div>
</div>
</div>
<div class="section" id="raw-string-notation">
<h3>7.2.5.8. Raw String Notation<a class="headerlink" href="#raw-string-notation" title="Permalink to this headline">¶</a></h3>
<p>Raw string notation (<code class="docutils literal notranslate"><span class="pre">r&quot;text&quot;</span></code>) keeps regular expressions sane.  Without it,
every backslash (<code class="docutils literal notranslate"><span class="pre">'\'</span></code>) in a regular expression would have to be prefixed with
another one to escape it.  For example, the two following lines of code are
functionally identical:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;\W(.)\1\W&quot;</span><span class="p">,</span> <span class="s2">&quot; ff &quot;</span><span class="p">)</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">W(.)</span><span class="se">\\</span><span class="s2">1</span><span class="se">\\</span><span class="s2">W&quot;</span><span class="p">,</span> <span class="s2">&quot; ff &quot;</span><span class="p">)</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
<p>When one wants to match a literal backslash, it must be escaped in the regular
expression.  With raw string notation, this means <code class="docutils literal notranslate"><span class="pre">r&quot;\\&quot;</span></code>.  Without raw string
notation, one must use <code class="docutils literal notranslate"><span class="pre">&quot;\\\\&quot;</span></code>, making the following lines of code
functionally identical:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">,</span> <span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">match</span><span class="p">(</span><span class="s2">&quot;</span><span class="se">\\\\</span><span class="s2">&quot;</span><span class="p">,</span> <span class="sa">r</span><span class="s2">&quot;</span><span class="se">\\</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">&lt;_sre.SRE_Match object at ...&gt;</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a><ul>
<li><a class="reference internal" href="#regular-expression-syntax">7.2.1. Regular Expression Syntax</a></li>
<li><a class="reference internal" href="#module-contents">7.2.2. Module Contents</a></li>
<li><a class="reference internal" href="#regular-expression-objects">7.2.3. Regular Expression Objects</a></li>
<li><a class="reference internal" href="#match-objects">7.2.4. Match Objects</a></li>
<li><a class="reference internal" href="#examples">7.2.5. Examples</a><ul>
<li><a class="reference internal" href="#checking-for-a-pair">7.2.5.1. Checking For a Pair</a></li>
<li><a class="reference internal" href="#simulating-scanf">7.2.5.2. Simulating scanf()</a></li>
<li><a class="reference internal" href="#search-vs-match">7.2.5.3. search() vs. match()</a></li>
<li><a class="reference internal" href="#making-a-phonebook">7.2.5.4. Making a Phonebook</a></li>
<li><a class="reference internal" href="#text-munging">7.2.5.5. Text Munging</a></li>
<li><a class="reference internal" href="#finding-all-adverbs">7.2.5.6. Finding all Adverbs</a></li>
<li><a class="reference internal" href="#finding-all-adverbs-and-their-positions">7.2.5.7. Finding all Adverbs and their Positions</a></li>
<li><a class="reference internal" href="#raw-string-notation">7.2.5.8. Raw String Notation</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="string.html"
                        title="previous chapter">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="struct.html"
                        title="next chapter">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/re.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="struct.html" title="7.3. struct — Interpret strings as packed binary data"
             >next</a> |</li>
        <li class="right" >
          <a href="string.html" title="7.1. string — Common string operations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\e�_��html/library/readline.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.8. readline — GNU readline interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.9. rlcompleter — Completion function for GNU readline" href="rlcompleter.html" />
    <link rel="prev" title="16.7. mmap — Memory-mapped file support" href="mmap.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/readline.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rlcompleter.html" title="16.9. rlcompleter — Completion function for GNU readline"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="mmap.html" title="16.7. mmap — Memory-mapped file support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-readline">
<span id="readline-gnu-readline-interface"></span><h1>16.8. <a class="reference internal" href="#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> — GNU readline interface<a class="headerlink" href="#module-readline" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module defines a number of functions to facilitate
completion and reading/writing of history files from the Python interpreter.
This module can be used directly, or via the <a class="reference internal" href="rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module, which
supports completion of Python identifiers at the interactive prompt.  Settings
made using  this module affect the behaviour of both the interpreter’s
interactive prompt  and the prompts offered by the <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> and
<a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> built-in functions.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The underlying Readline library API may be implemented by
the <code class="docutils literal notranslate"><span class="pre">libedit</span></code> library instead of GNU readline.
On MacOS X the <a class="reference internal" href="#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module detects which library is being used
at run time.</p>
<p class="last">The configuration file for <code class="docutils literal notranslate"><span class="pre">libedit</span></code> is different from that
of GNU readline. If you programmatically load configuration strings
you can check for the text “libedit” in <code class="xref py py-const docutils literal notranslate"><span class="pre">readline.__doc__</span></code>
to differentiate between GNU readline and libedit.</p>
</div>
<p>Readline keybindings may be configured via an initialization file, typically
<code class="docutils literal notranslate"><span class="pre">.inputrc</span></code> in your home directory.  See <a class="reference external" href="https://cnswww.cns.cwru.edu/php/chet/readline/rluserman.html#SEC9">Readline Init File</a>
in the GNU Readline manual for information about the format and
allowable constructs of that file, and the capabilities of the
Readline library in general.</p>
<div class="section" id="init-file">
<h2>16.8.1. Init file<a class="headerlink" href="#init-file" title="Permalink to this headline">¶</a></h2>
<p>The following functions relate to the init file and user configuration:</p>
<dl class="function">
<dt id="readline.parse_and_bind">
<code class="descclassname">readline.</code><code class="descname">parse_and_bind</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.parse_and_bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the init line provided in the <em>string</em> argument. This calls
<code class="xref c c-func docutils literal notranslate"><span class="pre">rl_parse_and_bind()</span></code> in the underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.read_init_file">
<code class="descclassname">readline.</code><code class="descname">read_init_file</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.read_init_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute a readline initialization file. The default filename is the last filename
used. This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">rl_read_init_file()</span></code> in the underlying library.</p>
</dd></dl>

</div>
<div class="section" id="line-buffer">
<h2>16.8.2. Line buffer<a class="headerlink" href="#line-buffer" title="Permalink to this headline">¶</a></h2>
<p>The following functions operate on the line buffer:</p>
<dl class="function">
<dt id="readline.get_line_buffer">
<code class="descclassname">readline.</code><code class="descname">get_line_buffer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_line_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current contents of the line buffer (<code class="xref c c-data docutils literal notranslate"><span class="pre">rl_line_buffer</span></code>
in the underlying library).</p>
</dd></dl>

<dl class="function">
<dt id="readline.insert_text">
<code class="descclassname">readline.</code><code class="descname">insert_text</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.insert_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert text into the line buffer at the cursor position.  This calls
<code class="xref c c-func docutils literal notranslate"><span class="pre">rl_insert_text()</span></code> in the underlying library, but ignores
the return value.</p>
</dd></dl>

<dl class="function">
<dt id="readline.redisplay">
<code class="descclassname">readline.</code><code class="descname">redisplay</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.redisplay" title="Permalink to this definition">¶</a></dt>
<dd><p>Change what’s displayed on the screen to reflect the current contents of the
line buffer.  This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">rl_redisplay()</span></code> in the underlying library.</p>
</dd></dl>

</div>
<div class="section" id="history-file">
<h2>16.8.3. History file<a class="headerlink" href="#history-file" title="Permalink to this headline">¶</a></h2>
<p>The following functions operate on a history file:</p>
<dl class="function">
<dt id="readline.read_history_file">
<code class="descclassname">readline.</code><code class="descname">read_history_file</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.read_history_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a readline history file, and append it to the history list.
The default filename is <code class="file docutils literal notranslate"><span class="pre">~/.history</span></code>.  This calls
<code class="xref c c-func docutils literal notranslate"><span class="pre">read_history()</span></code> in the underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.write_history_file">
<code class="descclassname">readline.</code><code class="descname">write_history_file</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.write_history_file" title="Permalink to this definition">¶</a></dt>
<dd><p>Save the history list to a readline history file, overwriting any
existing file.  The default filename is <code class="file docutils literal notranslate"><span class="pre">~/.history</span></code>.  This calls
<code class="xref c c-func docutils literal notranslate"><span class="pre">write_history()</span></code> in the underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.get_history_length">
<code class="descclassname">readline.</code><code class="descname">get_history_length</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_history_length" title="Permalink to this definition">¶</a></dt>
<dt id="readline.set_history_length">
<code class="descclassname">readline.</code><code class="descname">set_history_length</code><span class="sig-paren">(</span><em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_history_length" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or return the desired number of lines to save in the history file.
The <a class="reference internal" href="#readline.write_history_file" title="readline.write_history_file"><code class="xref py py-func docutils literal notranslate"><span class="pre">write_history_file()</span></code></a> function uses this value to truncate
the history file, by calling <code class="xref c c-func docutils literal notranslate"><span class="pre">history_truncate_file()</span></code> in
the underlying library.  Negative values imply
unlimited history file size.</p>
</dd></dl>

</div>
<div class="section" id="history-list">
<h2>16.8.4. History list<a class="headerlink" href="#history-list" title="Permalink to this headline">¶</a></h2>
<p>The following functions operate on a global history list:</p>
<dl class="function">
<dt id="readline.clear_history">
<code class="descclassname">readline.</code><code class="descname">clear_history</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.clear_history" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the current history.  This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">clear_history()</span></code> in the
underlying library.  The Python function only exists if Python was
compiled for a version of the library that supports it.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.get_current_history_length">
<code class="descclassname">readline.</code><code class="descname">get_current_history_length</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_current_history_length" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of items currently in the history.  (This is different from
<a class="reference internal" href="#readline.get_history_length" title="readline.get_history_length"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_history_length()</span></code></a>, which returns the maximum number of lines that will
be written to a history file.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.get_history_item">
<code class="descclassname">readline.</code><code class="descname">get_history_item</code><span class="sig-paren">(</span><em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_history_item" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current contents of history item at <em>index</em>.  The item index
is one-based.  This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">history_get()</span></code> in the underlying library.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.remove_history_item">
<code class="descclassname">readline.</code><code class="descname">remove_history_item</code><span class="sig-paren">(</span><em>pos</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.remove_history_item" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove history item specified by its position from the history.
The position is zero-based.  This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">remove_history()</span></code> in
the underlying library.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.replace_history_item">
<code class="descclassname">readline.</code><code class="descname">replace_history_item</code><span class="sig-paren">(</span><em>pos</em>, <em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.replace_history_item" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace history item specified by its position with <em>line</em>.
The position is zero-based.  This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">replace_history_entry()</span></code>
in the underlying library.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.add_history">
<code class="descclassname">readline.</code><code class="descname">add_history</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.add_history" title="Permalink to this definition">¶</a></dt>
<dd><p>Append <em>line</em> to the history buffer, as if it was the last line typed.
This calls <code class="xref c c-func docutils literal notranslate"><span class="pre">add_history()</span></code> in the underlying library.</p>
</dd></dl>

</div>
<div class="section" id="startup-hooks">
<h2>16.8.5. Startup hooks<a class="headerlink" href="#startup-hooks" title="Permalink to this headline">¶</a></h2>
<blockquote>
<div><div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</div></blockquote>
<dl class="function">
<dt id="readline.set_startup_hook">
<code class="descclassname">readline.</code><code class="descname">set_startup_hook</code><span class="sig-paren">(</span><span class="optional">[</span><em>function</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_startup_hook" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or remove the function invoked by the <code class="xref c c-data docutils literal notranslate"><span class="pre">rl_startup_hook</span></code>
callback of the underlying library.  If <em>function</em> is specified, it will
be used as the new hook function; if omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, any function
already installed is removed.  The hook is called with no
arguments just before readline prints the first prompt.</p>
</dd></dl>

<dl class="function">
<dt id="readline.set_pre_input_hook">
<code class="descclassname">readline.</code><code class="descname">set_pre_input_hook</code><span class="sig-paren">(</span><span class="optional">[</span><em>function</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_pre_input_hook" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or remove the function invoked by the <code class="xref c c-data docutils literal notranslate"><span class="pre">rl_pre_input_hook</span></code>
callback of the underlying library.  If <em>function</em> is specified, it will
be used as the new hook function; if omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, any
function already installed is removed.  The hook is called
with no arguments after the first prompt has been printed and just before
readline starts reading input characters.  This function only exists
if Python was compiled for a version of the library that supports it.</p>
</dd></dl>

</div>
<div class="section" id="completion">
<h2>16.8.6. Completion<a class="headerlink" href="#completion" title="Permalink to this headline">¶</a></h2>
<p>The following functions relate to implementing a custom word completion
function.  This is typically operated by the Tab key, and can suggest and
automatically complete a word being typed.  By default, Readline is set up
to be used by <a class="reference internal" href="rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> to complete Python identifiers for
the interactive interpreter.  If the <a class="reference internal" href="#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module is to be used
with a custom completer, a different set of word delimiters should be set.</p>
<dl class="function">
<dt id="readline.set_completer">
<code class="descclassname">readline.</code><code class="descname">set_completer</code><span class="sig-paren">(</span><span class="optional">[</span><em>function</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_completer" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or remove the completer function.  If <em>function</em> is specified, it will be
used as the new completer function; if omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, any completer
function already installed is removed.  The completer function is called as
<code class="docutils literal notranslate"><span class="pre">function(text,</span> <span class="pre">state)</span></code>, for <em>state</em> in <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">1</span></code>, <code class="docutils literal notranslate"><span class="pre">2</span></code>, …, until it
returns a non-string value.  It should return the next possible completion
starting with <em>text</em>.</p>
<p>The installed completer function is invoked by the <em>entry_func</em> callback
passed to <code class="xref c c-func docutils literal notranslate"><span class="pre">rl_completion_matches()</span></code> in the underlying library.
The <em>text</em> string comes from the first parameter to the
<code class="xref c c-data docutils literal notranslate"><span class="pre">rl_attempted_completion_function</span></code> callback of the
underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.get_completer">
<code class="descclassname">readline.</code><code class="descname">get_completer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_completer" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the completer function, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no completer function has been set.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.get_completion_type">
<code class="descclassname">readline.</code><code class="descname">get_completion_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_completion_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the type of completion being attempted.  This returns the
<code class="xref c c-data docutils literal notranslate"><span class="pre">rl_completion_type</span></code> variable in the underlying library as
an integer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="readline.get_begidx">
<code class="descclassname">readline.</code><code class="descname">get_begidx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_begidx" title="Permalink to this definition">¶</a></dt>
<dt id="readline.get_endidx">
<code class="descclassname">readline.</code><code class="descname">get_endidx</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_endidx" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the beginning or ending index of the completion scope.
These indexes are the <em>start</em> and <em>end</em> arguments passed to the
<code class="xref c c-data docutils literal notranslate"><span class="pre">rl_attempted_completion_function</span></code> callback of the
underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.set_completer_delims">
<code class="descclassname">readline.</code><code class="descname">set_completer_delims</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_completer_delims" title="Permalink to this definition">¶</a></dt>
<dt id="readline.get_completer_delims">
<code class="descclassname">readline.</code><code class="descname">get_completer_delims</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.get_completer_delims" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or get the word delimiters for completion.  These determine the
start of the word to be considered for completion (the completion scope).
These functions access the <code class="xref c c-data docutils literal notranslate"><span class="pre">rl_completer_word_break_characters</span></code>
variable in the underlying library.</p>
</dd></dl>

<dl class="function">
<dt id="readline.set_completion_display_matches_hook">
<code class="descclassname">readline.</code><code class="descname">set_completion_display_matches_hook</code><span class="sig-paren">(</span><span class="optional">[</span><em>function</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#readline.set_completion_display_matches_hook" title="Permalink to this definition">¶</a></dt>
<dd><p>Set or remove the completion display function.  If <em>function</em> is
specified, it will be used as the new completion display function;
if omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, any completion display function already
installed is removed.  This sets or clears the
<code class="xref c c-data docutils literal notranslate"><span class="pre">rl_completion_display_matches_hook</span></code> callback in the
underlying library.  The completion display function is called as
<code class="docutils literal notranslate"><span class="pre">function(substitution,</span> <span class="pre">[matches],</span> <span class="pre">longest_match_length)</span></code> once
each time matches need to be displayed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="example">
<span id="readline-example"></span><h2>16.8.7. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>The following example demonstrates how to use the <a class="reference internal" href="#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module’s
history reading and writing functions to automatically load and save a history
file named <code class="file docutils literal notranslate"><span class="pre">.pyhist</span></code> from the user’s home directory.  The code below would
normally be executed automatically during interactive sessions from the user’s
<span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> file.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">readline</span>
<span class="n">histfile</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s2">&quot;~&quot;</span><span class="p">),</span> <span class="s2">&quot;.pyhist&quot;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">read_history_file</span><span class="p">(</span><span class="n">histfile</span><span class="p">)</span>
    <span class="c1"># default history len is -1 (infinite), which may grow unruly</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">set_history_length</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
    <span class="k">pass</span>
<span class="kn">import</span> <span class="nn">atexit</span>
<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">readline</span><span class="o">.</span><span class="n">write_history_file</span><span class="p">,</span> <span class="n">histfile</span><span class="p">)</span>
<span class="k">del</span> <span class="n">os</span><span class="p">,</span> <span class="n">histfile</span>
</pre></div>
</div>
<p>The following example extends the <a class="reference internal" href="code.html#code.InteractiveConsole" title="code.InteractiveConsole"><code class="xref py py-class docutils literal notranslate"><span class="pre">code.InteractiveConsole</span></code></a> class to
support history save/restore.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">code</span>
<span class="kn">import</span> <span class="nn">readline</span>
<span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">os</span>

<span class="k">class</span> <span class="nc">HistoryConsole</span><span class="p">(</span><span class="n">code</span><span class="o">.</span><span class="n">InteractiveConsole</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">locals</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s2">&quot;&lt;console&gt;&quot;</span><span class="p">,</span>
                 <span class="n">histfile</span><span class="o">=</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s2">&quot;~/.console-history&quot;</span><span class="p">)):</span>
        <span class="n">code</span><span class="o">.</span><span class="n">InteractiveConsole</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">locals</span><span class="p">,</span> <span class="n">filename</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">init_history</span><span class="p">(</span><span class="n">histfile</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">init_history</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">histfile</span><span class="p">):</span>
        <span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s2">&quot;tab: complete&quot;</span><span class="p">)</span>
        <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">readline</span><span class="p">,</span> <span class="s2">&quot;read_history_file&quot;</span><span class="p">):</span>
            <span class="k">try</span><span class="p">:</span>
                <span class="n">readline</span><span class="o">.</span><span class="n">read_history_file</span><span class="p">(</span><span class="n">histfile</span><span class="p">)</span>
            <span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
                <span class="k">pass</span>
            <span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">save_history</span><span class="p">,</span> <span class="n">histfile</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">save_history</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">histfile</span><span class="p">):</span>
        <span class="n">readline</span><span class="o">.</span><span class="n">set_history_length</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
        <span class="n">readline</span><span class="o">.</span><span class="n">write_history_file</span><span class="p">(</span><span class="n">histfile</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a><ul>
<li><a class="reference internal" href="#init-file">16.8.1. Init file</a></li>
<li><a class="reference internal" href="#line-buffer">16.8.2. Line buffer</a></li>
<li><a class="reference internal" href="#history-file">16.8.3. History file</a></li>
<li><a class="reference internal" href="#history-list">16.8.4. History list</a></li>
<li><a class="reference internal" href="#startup-hooks">16.8.5. Startup hooks</a></li>
<li><a class="reference internal" href="#completion">16.8.6. Completion</a></li>
<li><a class="reference internal" href="#example">16.8.7. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="mmap.html"
                        title="previous chapter">16.7. <code class="docutils literal notranslate"><span class="pre">mmap</span></code> — Memory-mapped file support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="rlcompleter.html"
                        title="next chapter">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/readline.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rlcompleter.html" title="16.9. rlcompleter — Completion function for GNU readline"
             >next</a> |</li>
        <li class="right" >
          <a href="mmap.html" title="16.7. mmap — Memory-mapped file support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�8�sUUhtml/library/repr.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.19. repr — Alternate repr() implementation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9. Numeric and Mathematical Modules" href="numeric.html" />
    <link rel="prev" title="8.18. pprint — Data pretty printer" href="pprint.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/repr.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="numeric.html" title="9. Numeric and Mathematical Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pprint.html" title="8.18. pprint — Data pretty printer"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="repr-alternate-repr-implementation">
<h1>8.19. <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-mod docutils literal notranslate"><span class="pre">repr</span></code></a> — Alternate <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> implementation<a class="headerlink" href="#repr-alternate-repr-implementation" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-mod docutils literal notranslate"><span class="pre">repr</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">reprlib</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/repr.py">Lib/repr.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-mod docutils literal notranslate"><span class="pre">repr</span></code></a> module provides a means for producing object representations
with limits on the size of the resulting strings. This is used in the Python
debugger and may be useful in other contexts as well.</p>
<p>This module provides a class, an instance, and a function:</p>
<dl class="class">
<dt id="repr.Repr">
<em class="property">class </em><code class="descclassname">repr.</code><code class="descname">Repr</code><a class="headerlink" href="#repr.Repr" title="Permalink to this definition">¶</a></dt>
<dd><p>Class which provides formatting services useful in implementing functions
similar to the built-in <a class="reference internal" href="functions.html#func-repr"><span class="std std-ref">repr()</span></a>; size limits for different
object types are added to avoid the generation of representations which are
excessively long.</p>
</dd></dl>

<dl class="data">
<dt id="repr.aRepr">
<code class="descclassname">repr.</code><code class="descname">aRepr</code><a class="headerlink" href="#repr.aRepr" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an instance of <a class="reference internal" href="#repr.Repr" title="repr.Repr"><code class="xref py py-class docutils literal notranslate"><span class="pre">Repr</span></code></a> which is used to provide the <a class="reference internal" href="#repr.repr" title="repr.repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>
function described below.  Changing the attributes of this object will affect
the size limits used by <a class="reference internal" href="#repr.repr" title="repr.repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> and the Python debugger.</p>
</dd></dl>

<dl class="function">
<dt id="repr.repr">
<code class="descclassname">repr.</code><code class="descname">repr</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#repr.repr" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the <a class="reference internal" href="#repr.Repr.repr" title="repr.Repr.repr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repr()</span></code></a> method of <code class="docutils literal notranslate"><span class="pre">aRepr</span></code>.  It returns a string
similar to that returned by the built-in function of the same name, but with
limits on most sizes.</p>
</dd></dl>

<div class="section" id="repr-objects">
<span id="id1"></span><h2>8.19.1. Repr Objects<a class="headerlink" href="#repr-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#repr.Repr" title="repr.Repr"><code class="xref py py-class docutils literal notranslate"><span class="pre">Repr</span></code></a> instances provide several attributes which can be used to provide
size limits for the representations of different object types,  and methods
which format specific object types.</p>
<dl class="attribute">
<dt id="repr.Repr.maxlevel">
<code class="descclassname">Repr.</code><code class="descname">maxlevel</code><a class="headerlink" href="#repr.Repr.maxlevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Depth limit on the creation of recursive representations.  The default is <code class="docutils literal notranslate"><span class="pre">6</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="repr.Repr.maxdict">
<code class="descclassname">Repr.</code><code class="descname">maxdict</code><a class="headerlink" href="#repr.Repr.maxdict" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxlist">
<code class="descclassname">Repr.</code><code class="descname">maxlist</code><a class="headerlink" href="#repr.Repr.maxlist" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxtuple">
<code class="descclassname">Repr.</code><code class="descname">maxtuple</code><a class="headerlink" href="#repr.Repr.maxtuple" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxset">
<code class="descclassname">Repr.</code><code class="descname">maxset</code><a class="headerlink" href="#repr.Repr.maxset" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxfrozenset">
<code class="descclassname">Repr.</code><code class="descname">maxfrozenset</code><a class="headerlink" href="#repr.Repr.maxfrozenset" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxdeque">
<code class="descclassname">Repr.</code><code class="descname">maxdeque</code><a class="headerlink" href="#repr.Repr.maxdeque" title="Permalink to this definition">¶</a></dt>
<dt id="repr.Repr.maxarray">
<code class="descclassname">Repr.</code><code class="descname">maxarray</code><a class="headerlink" href="#repr.Repr.maxarray" title="Permalink to this definition">¶</a></dt>
<dd><p>Limits on the number of entries represented for the named object type.  The
default is <code class="docutils literal notranslate"><span class="pre">4</span></code> for <a class="reference internal" href="#repr.Repr.maxdict" title="repr.Repr.maxdict"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxdict</span></code></a>, <code class="docutils literal notranslate"><span class="pre">5</span></code> for <a class="reference internal" href="#repr.Repr.maxarray" title="repr.Repr.maxarray"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxarray</span></code></a>, and  <code class="docutils literal notranslate"><span class="pre">6</span></code> for
the others.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4: </span><a class="reference internal" href="#repr.Repr.maxset" title="repr.Repr.maxset"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxset</span></code></a>, <a class="reference internal" href="#repr.Repr.maxfrozenset" title="repr.Repr.maxfrozenset"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxfrozenset</span></code></a>, and <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-attr docutils literal notranslate"><span class="pre">set</span></code></a>.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="repr.Repr.maxlong">
<code class="descclassname">Repr.</code><code class="descname">maxlong</code><a class="headerlink" href="#repr.Repr.maxlong" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum number of characters in the representation for a long integer.  Digits
are dropped from the middle.  The default is <code class="docutils literal notranslate"><span class="pre">40</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="repr.Repr.maxstring">
<code class="descclassname">Repr.</code><code class="descname">maxstring</code><a class="headerlink" href="#repr.Repr.maxstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Limit on the number of characters in the representation of the string.  Note
that the “normal” representation of the string is used as the character source:
if escape sequences are needed in the representation, these may be mangled when
the representation is shortened.  The default is <code class="docutils literal notranslate"><span class="pre">30</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="repr.Repr.maxother">
<code class="descclassname">Repr.</code><code class="descname">maxother</code><a class="headerlink" href="#repr.Repr.maxother" title="Permalink to this definition">¶</a></dt>
<dd><p>This limit is used to control the size of object types for which no specific
formatting method is available on the <a class="reference internal" href="#repr.Repr" title="repr.Repr"><code class="xref py py-class docutils literal notranslate"><span class="pre">Repr</span></code></a> object. It is applied in a
similar manner as <a class="reference internal" href="#repr.Repr.maxstring" title="repr.Repr.maxstring"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxstring</span></code></a>.  The default is <code class="docutils literal notranslate"><span class="pre">20</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="repr.Repr.repr">
<code class="descclassname">Repr.</code><code class="descname">repr</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#repr.Repr.repr" title="Permalink to this definition">¶</a></dt>
<dd><p>The equivalent to the built-in <a class="reference internal" href="functions.html#func-repr"><span class="std std-ref">repr()</span></a> that uses the
formatting imposed by the instance.</p>
</dd></dl>

<dl class="method">
<dt id="repr.Repr.repr1">
<code class="descclassname">Repr.</code><code class="descname">repr1</code><span class="sig-paren">(</span><em>obj</em>, <em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#repr.Repr.repr1" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursive implementation used by <a class="reference internal" href="#repr.Repr.repr" title="repr.Repr.repr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repr()</span></code></a>.  This uses the type of <em>obj</em> to
determine which formatting method to call, passing it <em>obj</em> and <em>level</em>.  The
type-specific methods should call <a class="reference internal" href="#repr.Repr.repr1" title="repr.Repr.repr1"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repr1()</span></code></a> to perform recursive formatting,
with <code class="docutils literal notranslate"><span class="pre">level</span> <span class="pre">-</span> <span class="pre">1</span></code> for the value of <em>level</em> in the recursive  call.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">Repr.</code><code class="descname">repr_TYPE</code><span class="sig-paren">(</span><em>obj</em>, <em>level</em><span class="sig-paren">)</span></dt>
<dd><p>Formatting methods for specific types are implemented as methods with a name
based on the type name.  In the method name, <strong>TYPE</strong> is replaced by
<code class="docutils literal notranslate"><span class="pre">string.join(string.split(type(obj).__name__,</span> <span class="pre">'_'))</span></code>. Dispatch to these
methods is handled by <a class="reference internal" href="#repr.Repr.repr1" title="repr.Repr.repr1"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repr1()</span></code></a>. Type-specific methods which need to
recursively format a value should call <code class="docutils literal notranslate"><span class="pre">self.repr1(subobj,</span> <span class="pre">level</span> <span class="pre">-</span> <span class="pre">1)</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="subclassing-repr-objects">
<span id="subclassing-reprs"></span><h2>8.19.2. Subclassing Repr Objects<a class="headerlink" href="#subclassing-repr-objects" title="Permalink to this headline">¶</a></h2>
<p>The use of dynamic dispatching by <a class="reference internal" href="#repr.Repr.repr1" title="repr.Repr.repr1"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Repr.repr1()</span></code></a> allows subclasses of
<a class="reference internal" href="#repr.Repr" title="repr.Repr"><code class="xref py py-class docutils literal notranslate"><span class="pre">Repr</span></code></a> to add support for additional built-in object types or to modify
the handling of types already supported. This example shows how special support
for file objects could be added:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">repr</span> <span class="k">as</span> <span class="nn">reprlib</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="k">class</span> <span class="nc">MyRepr</span><span class="p">(</span><span class="n">reprlib</span><span class="o">.</span><span class="n">Repr</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">repr_file</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">,</span> <span class="n">level</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">obj</span><span class="o">.</span><span class="n">name</span> <span class="ow">in</span> <span class="p">[</span><span class="s1">&#39;&lt;stdin&gt;&#39;</span><span class="p">,</span> <span class="s1">&#39;&lt;stdout&gt;&#39;</span><span class="p">,</span> <span class="s1">&#39;&lt;stderr&gt;&#39;</span><span class="p">]:</span>
            <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">name</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>

<span class="n">aRepr</span> <span class="o">=</span> <span class="n">MyRepr</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">aRepr</span><span class="o">.</span><span class="n">repr</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="p">)</span>          <span class="c1"># prints &#39;&lt;stdin&gt;&#39;</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a><ul>
<li><a class="reference internal" href="#repr-objects">8.19.1. Repr Objects</a></li>
<li><a class="reference internal" href="#subclassing-repr-objects">8.19.2. Subclassing Repr Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="pprint.html"
                        title="previous chapter">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="numeric.html"
                        title="next chapter">9. Numeric and Mathematical Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/repr.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="numeric.html" title="9. Numeric and Mathematical Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="pprint.html" title="8.18. pprint — Data pretty printer"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�`1~n~nhtml/library/resource.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.13. resource — Resource usage information &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)" href="nis.html" />
    <link rel="prev" title="36.12. posixfile — File-like objects with locking support" href="posixfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/resource.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="nis.html" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="posixfile.html" title="36.12. posixfile — File-like objects with locking support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-resource">
<span id="resource-resource-usage-information"></span><h1>36.13. <a class="reference internal" href="#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">resource</span></code></a> — Resource usage information<a class="headerlink" href="#module-resource" title="Permalink to this headline">¶</a></h1>
<p>This module provides basic mechanisms for measuring and controlling system
resources utilized by a program.</p>
<p>Symbolic constants are used to specify particular system resources and to
request usage information about either the current process or its children.</p>
<p>A single exception is defined for errors:</p>
<dl class="exception">
<dt id="resource.error">
<em class="property">exception </em><code class="descclassname">resource.</code><code class="descname">error</code><a class="headerlink" href="#resource.error" title="Permalink to this definition">¶</a></dt>
<dd><p>The functions described below may raise this error if the underlying system call
failures unexpectedly.</p>
</dd></dl>

<div class="section" id="resource-limits">
<h2>36.13.1. Resource Limits<a class="headerlink" href="#resource-limits" title="Permalink to this headline">¶</a></h2>
<p>Resources usage can be limited using the <a class="reference internal" href="#resource.setrlimit" title="resource.setrlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">setrlimit()</span></code></a> function described
below. Each resource is controlled by a pair of limits: a soft limit and a hard
limit. The soft limit is the current limit, and may be lowered or raised by a
process over time. The soft limit can never exceed the hard limit. The hard
limit can be lowered to any value greater than the soft limit, but not raised.
(Only processes with the effective UID of the super-user can raise a hard
limit.)</p>
<p>The specific resources that can be limited are system dependent. They are
described in the <em class="manpage">getrlimit(2)</em> man page.  The resources listed below
are supported when the underlying operating system supports them; resources
which cannot be checked or controlled by the operating system are not defined in
this module for those platforms.</p>
<dl class="data">
<dt id="resource.RLIM_INFINITY">
<code class="descclassname">resource.</code><code class="descname">RLIM_INFINITY</code><a class="headerlink" href="#resource.RLIM_INFINITY" title="Permalink to this definition">¶</a></dt>
<dd><p>Constant used to represent the limit for an unlimited resource.</p>
</dd></dl>

<dl class="function">
<dt id="resource.getrlimit">
<code class="descclassname">resource.</code><code class="descname">getrlimit</code><span class="sig-paren">(</span><em>resource</em><span class="sig-paren">)</span><a class="headerlink" href="#resource.getrlimit" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(soft,</span> <span class="pre">hard)</span></code> with the current soft and hard limits of
<em>resource</em>. Raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if an invalid resource is specified, or
<a class="reference internal" href="#resource.error" title="resource.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> if the underlying system call fails unexpectedly.</p>
</dd></dl>

<dl class="function">
<dt id="resource.setrlimit">
<code class="descclassname">resource.</code><code class="descname">setrlimit</code><span class="sig-paren">(</span><em>resource</em>, <em>limits</em><span class="sig-paren">)</span><a class="headerlink" href="#resource.setrlimit" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets new limits of consumption of <em>resource</em>. The <em>limits</em> argument must be a
tuple <code class="docutils literal notranslate"><span class="pre">(soft,</span> <span class="pre">hard)</span></code> of two integers describing the new limits. A value of
<a class="reference internal" href="#resource.RLIM_INFINITY" title="resource.RLIM_INFINITY"><code class="xref py py-data docutils literal notranslate"><span class="pre">RLIM_INFINITY</span></code></a> can be used to request a limit that is
unlimited.</p>
<p>Raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if an invalid resource is specified, if the new soft
limit exceeds the hard limit, or if a process tries to raise its hard limit.
Specifying a limit of <a class="reference internal" href="#resource.RLIM_INFINITY" title="resource.RLIM_INFINITY"><code class="xref py py-data docutils literal notranslate"><span class="pre">RLIM_INFINITY</span></code></a> when the hard or
system limit for that resource is not unlimited will result in a
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.  A process with the effective UID of super-user can
request any valid limit value, including unlimited, but <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
will still be raised if the requested limit exceeds the system imposed
limit.</p>
<p><code class="docutils literal notranslate"><span class="pre">setrlimit</span></code> may also raise <a class="reference internal" href="#resource.error" title="resource.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> if the underlying system call
fails.</p>
</dd></dl>

<p>These symbols define resources whose consumption can be controlled using the
<a class="reference internal" href="#resource.setrlimit" title="resource.setrlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">setrlimit()</span></code></a> and <a class="reference internal" href="#resource.getrlimit" title="resource.getrlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrlimit()</span></code></a> functions described below. The values of
these symbols are exactly the constants used by C programs.</p>
<p>The Unix man page for <em class="manpage">getrlimit(2)</em> lists the available resources.
Note that not all systems use the same symbol or same value to denote the same
resource.  This module does not attempt to mask platform differences — symbols
not defined for a platform will not be available from this module on that
platform.</p>
<dl class="data">
<dt id="resource.RLIMIT_CORE">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_CORE</code><a class="headerlink" href="#resource.RLIMIT_CORE" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum size (in bytes) of a core file that the current process can create.
This may result in the creation of a partial core file if a larger core would be
required to contain the entire process image.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_CPU">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_CPU</code><a class="headerlink" href="#resource.RLIMIT_CPU" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum amount of processor time (in seconds) that a process can use. If
this limit is exceeded, a <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGXCPU</span></code> signal is sent to the process. (See
the <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module documentation for information about how to catch this
signal and do something useful, e.g. flush open files to disk.)</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_FSIZE">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_FSIZE</code><a class="headerlink" href="#resource.RLIMIT_FSIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum size of a file which the process may create.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_DATA">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_DATA</code><a class="headerlink" href="#resource.RLIMIT_DATA" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum size (in bytes) of the process’s heap.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_STACK">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_STACK</code><a class="headerlink" href="#resource.RLIMIT_STACK" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum size (in bytes) of the call stack for the current process.  This only
affects the stack of the main thread in a multi-threaded process.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_RSS">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_RSS</code><a class="headerlink" href="#resource.RLIMIT_RSS" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum resident set size that should be made available to the process.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_NPROC">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_NPROC</code><a class="headerlink" href="#resource.RLIMIT_NPROC" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum number of processes the current process may create.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_NOFILE">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_NOFILE</code><a class="headerlink" href="#resource.RLIMIT_NOFILE" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum number of open file descriptors for the current process.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_OFILE">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_OFILE</code><a class="headerlink" href="#resource.RLIMIT_OFILE" title="Permalink to this definition">¶</a></dt>
<dd><p>The BSD name for <a class="reference internal" href="#resource.RLIMIT_NOFILE" title="resource.RLIMIT_NOFILE"><code class="xref py py-const docutils literal notranslate"><span class="pre">RLIMIT_NOFILE</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_MEMLOCK">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_MEMLOCK</code><a class="headerlink" href="#resource.RLIMIT_MEMLOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum address space which may be locked in memory.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_VMEM">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_VMEM</code><a class="headerlink" href="#resource.RLIMIT_VMEM" title="Permalink to this definition">¶</a></dt>
<dd><p>The largest area of mapped memory which the process may occupy.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RLIMIT_AS">
<code class="descclassname">resource.</code><code class="descname">RLIMIT_AS</code><a class="headerlink" href="#resource.RLIMIT_AS" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum area (in bytes) of address space which may be taken by the process.</p>
</dd></dl>

</div>
<div class="section" id="resource-usage">
<h2>36.13.2. Resource Usage<a class="headerlink" href="#resource-usage" title="Permalink to this headline">¶</a></h2>
<p>These functions are used to retrieve resource usage information:</p>
<dl class="function">
<dt id="resource.getrusage">
<code class="descclassname">resource.</code><code class="descname">getrusage</code><span class="sig-paren">(</span><em>who</em><span class="sig-paren">)</span><a class="headerlink" href="#resource.getrusage" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns an object that describes the resources consumed by either
the current process or its children, as specified by the <em>who</em> parameter.  The
<em>who</em> parameter should be specified using one of the <code class="xref py py-const docutils literal notranslate"><span class="pre">RUSAGE_*</span></code>
constants described below.</p>
<p>The fields of the return value each describe how a particular system resource
has been used, e.g. amount of time spent running is user mode or number of times
the process was swapped out of main memory. Some values are dependent on the
clock tick internal, e.g. the amount of memory the process is using.</p>
<p>For backward compatibility, the return value is also accessible as a tuple of 16
elements.</p>
<p>The fields <code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_utime</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_stime</span></code> of the return value are
floating point values representing the amount of time spent executing in user
mode and the amount of time spent executing in system mode, respectively. The
remaining values are integers. Consult the <em class="manpage">getrusage(2)</em> man page for
detailed information about these values. A brief summary is presented here:</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="35%" />
<col width="52%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Field</th>
<th class="head">Resource</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_utime</span></code></td>
<td>time in user mode (float)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_stime</span></code></td>
<td>time in system mode (float)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">2</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_maxrss</span></code></td>
<td>maximum resident set size</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">3</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_ixrss</span></code></td>
<td>shared memory size</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">4</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_idrss</span></code></td>
<td>unshared memory size</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">5</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_isrss</span></code></td>
<td>unshared stack size</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">6</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_minflt</span></code></td>
<td>page faults not requiring I/O</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">7</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_majflt</span></code></td>
<td>page faults requiring I/O</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">8</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_nswap</span></code></td>
<td>number of swap outs</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">9</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_inblock</span></code></td>
<td>block input operations</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">10</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_oublock</span></code></td>
<td>block output operations</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">11</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_msgsnd</span></code></td>
<td>messages sent</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">12</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_msgrcv</span></code></td>
<td>messages received</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">13</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_nsignals</span></code></td>
<td>signals received</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">14</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_nvcsw</span></code></td>
<td>voluntary context switches</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">15</span></code></td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">ru_nivcsw</span></code></td>
<td>involuntary context switches</td>
</tr>
</tbody>
</table>
<p>This function will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if an invalid <em>who</em> parameter is
specified. It may also raise <a class="reference internal" href="#resource.error" title="resource.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception in unusual circumstances.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Added access to values as attributes of the returned object.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="resource.getpagesize">
<code class="descclassname">resource.</code><code class="descname">getpagesize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#resource.getpagesize" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the number of bytes in a system page. (This need not be the same as the
hardware page size.)</p>
</dd></dl>

<p>The following <code class="xref py py-const docutils literal notranslate"><span class="pre">RUSAGE_*</span></code> symbols are passed to the <a class="reference internal" href="#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrusage()</span></code></a>
function to specify which processes information should be provided for.</p>
<dl class="data">
<dt id="resource.RUSAGE_SELF">
<code class="descclassname">resource.</code><code class="descname">RUSAGE_SELF</code><a class="headerlink" href="#resource.RUSAGE_SELF" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#resource.RUSAGE_SELF" title="resource.RUSAGE_SELF"><code class="xref py py-const docutils literal notranslate"><span class="pre">RUSAGE_SELF</span></code></a> should be used to request information pertaining only to
the process itself.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RUSAGE_CHILDREN">
<code class="descclassname">resource.</code><code class="descname">RUSAGE_CHILDREN</code><a class="headerlink" href="#resource.RUSAGE_CHILDREN" title="Permalink to this definition">¶</a></dt>
<dd><p>Pass to <a class="reference internal" href="#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrusage()</span></code></a> to request resource information for child processes of
the calling process.</p>
</dd></dl>

<dl class="data">
<dt id="resource.RUSAGE_BOTH">
<code class="descclassname">resource.</code><code class="descname">RUSAGE_BOTH</code><a class="headerlink" href="#resource.RUSAGE_BOTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Pass to <a class="reference internal" href="#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrusage()</span></code></a> to request resources consumed by both the current
process and child processes.  May not be available on all systems.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a><ul>
<li><a class="reference internal" href="#resource-limits">36.13.1. Resource Limits</a></li>
<li><a class="reference internal" href="#resource-usage">36.13.2. Resource Usage</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="posixfile.html"
                        title="previous chapter">36.12. <code class="docutils literal notranslate"><span class="pre">posixfile</span></code> — File-like objects with locking support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="nis.html"
                        title="next chapter">36.14. <code class="docutils literal notranslate"><span class="pre">nis</span></code> — Interface to Sun’s NIS (Yellow Pages)</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/resource.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="nis.html" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)"
             >next</a> |</li>
        <li class="right" >
          <a href="posixfile.html" title="36.12. posixfile — File-like objects with locking support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��uN0N0html/library/restricted.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>30. Restricted Execution &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="30.1. rexec — Restricted execution framework" href="rexec.html" />
    <link rel="prev" title="29.2. codeop — Compile Python code" href="codeop.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/restricted.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rexec.html" title="30.1. rexec — Restricted execution framework"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="codeop.html" title="29.2. codeop — Compile Python code"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="restricted-execution">
<span id="restricted"></span><h1>30. Restricted Execution<a class="headerlink" href="#restricted-execution" title="Permalink to this headline">¶</a></h1>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">In Python 2.3 these modules have been disabled due to various known and not
readily fixable security holes.  The modules are still documented here to help
in reading old code that uses the <a class="reference internal" href="rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> and <a class="reference internal" href="bastion.html#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Bastion</span></code></a> modules.</p>
</div>
<p><em>Restricted execution</em> is the basic framework in Python that allows for the
segregation of trusted and untrusted code.  The framework is based on the notion
that trusted Python code (a <em>supervisor</em>) can create a “padded cell’ (or
environment) with limited permissions, and run the untrusted code within this
cell.  The untrusted code cannot break out of its cell, and can only interact
with sensitive system resources through interfaces defined and managed by the
trusted code.  The term “restricted execution” is favored over “safe-Python”
since true safety is hard to define, and is determined by the way the restricted
environment is created.  Note that the restricted environments can be nested,
with inner cells creating subcells of lesser, but never greater, privilege.</p>
<p>An interesting aspect of Python’s restricted execution model is that the
interfaces presented to untrusted code usually have the same names as those
presented to trusted code.  Therefore no special interfaces need to be learned
to write code designed to run in a restricted environment.  And because the
exact nature of the padded cell is determined by the supervisor, different
restrictions can be imposed, depending on the application.  For example, it
might be deemed “safe” for untrusted code to read any file within a specified
directory, but never to write a file.  In this case, the supervisor may redefine
the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function so that it raises an exception whenever the
<em>mode</em> parameter is <code class="docutils literal notranslate"><span class="pre">'w'</span></code>.  It might also perform a <code class="xref c c-func docutils literal notranslate"><span class="pre">chroot()</span></code>-like
operation on the <em>filename</em> parameter, such that root is always relative to some
safe “sandbox” area of the filesystem.  In this case, the untrusted code would
still see a built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function in its environment, with the same
calling interface.  The semantics would be identical too, with <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>s
being raised when the supervisor determined that an unallowable parameter is
being used.</p>
<p>The Python run-time determines whether a particular code block is executing in
restricted execution mode based on the identity of the <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> object
in its global variables: if this is (the dictionary of) the standard
<a class="reference internal" href="__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module, the code is deemed to be unrestricted, else it is
deemed to be restricted.</p>
<p>Python code executing in restricted mode faces a number of limitations that are
designed to prevent it from escaping from the padded cell. For instance, the
function object attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">func_globals</span></code> and the class and instance object
attribute <a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> are unavailable.</p>
<p>Two modules provide the framework for setting up restricted execution
environments:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="rexec.html">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a><ul>
<li class="toctree-l2"><a class="reference internal" href="rexec.html#rexec-objects">30.1.1. RExec Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="rexec.html#defining-restricted-environments">30.1.2. Defining restricted environments</a></li>
<li class="toctree-l2"><a class="reference internal" href="rexec.html#an-example">30.1.3. An example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="bastion.html">30.2. <code class="docutils literal notranslate"><span class="pre">Bastion</span></code> — Restricting access to objects</a></li>
</ul>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://grail.sourceforge.net/">Grail Home Page</a></dt>
<dd>Grail, an Internet browser written in Python, uses these modules to support
Python applets.  More information on the use of Python’s restricted execution
mode in Grail is available on the Web site.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="codeop.html"
                        title="previous chapter">29.2. <code class="docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="rexec.html"
                        title="next chapter">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/restricted.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="rexec.html" title="30.1. rexec — Restricted execution framework"
             >next</a> |</li>
        <li class="right" >
          <a href="codeop.html" title="29.2. codeop — Compile Python code"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\{<lQv�v�html/library/rexec.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>30.1. rexec — Restricted execution framework &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="30.2. Bastion — Restricting access to objects" href="bastion.html" />
    <link rel="prev" title="30. Restricted Execution" href="restricted.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/rexec.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bastion.html" title="30.2. Bastion — Restricting access to objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="restricted.html" title="30. Restricted Execution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="restricted.html" accesskey="U">30. Restricted Execution</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-rexec">
<span id="rexec-restricted-execution-framework"></span><h1>30.1. <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> — Restricted execution framework<a class="headerlink" href="#module-rexec" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> module has been removed in Python 3.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Disabled module.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The documentation has been left in place to help in reading old code that uses
the module.</p>
</div>
<p>This module contains the <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class, which supports <code class="xref py py-meth docutils literal notranslate"><span class="pre">r_eval()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">r_execfile()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">r_exec()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">r_import()</span></code> methods, which are
restricted versions of the standard Python functions <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-meth docutils literal notranslate"><span class="pre">eval()</span></code></a>,
<a class="reference internal" href="functions.html#execfile" title="execfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execfile()</span></code></a> and the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> and <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements. Code
executed in this restricted environment will only have access to modules and
functions that are deemed safe; you can subclass <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> to add or remove
capabilities as desired.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">While the <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> module is designed to perform as described below, it does
have a few known vulnerabilities which could be exploited by carefully written
code.  Thus it should not be relied upon in situations requiring “production
ready” security.  In such situations, execution via sub-processes or very
careful “cleansing” of both code and data to be processed may be necessary.
Alternatively, help in patching known <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> vulnerabilities would be
welcomed.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class can prevent code from performing unsafe operations like
reading or writing disk files, or using TCP/IP sockets.  However, it does not
protect against code using extremely large amounts of memory or processor time.</p>
</div>
<dl class="class">
<dt id="rexec.RExec">
<em class="property">class </em><code class="descclassname">rexec.</code><code class="descname">RExec</code><span class="sig-paren">(</span><span class="optional">[</span><em>hooks</em><span class="optional">[</span>, <em>verbose</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an instance of the <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class.</p>
<p><em>hooks</em> is an instance of the <code class="xref py py-class docutils literal notranslate"><span class="pre">RHooks</span></code> class or a subclass of it. If it
is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the default <code class="xref py py-class docutils literal notranslate"><span class="pre">RHooks</span></code> class is instantiated.
Whenever the <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> module searches for a module (even a built-in one) or
reads a module’s code, it doesn’t actually go out to the file system itself.
Rather, it calls methods of an <code class="xref py py-class docutils literal notranslate"><span class="pre">RHooks</span></code> instance that was passed to or
created by its constructor.  (Actually, the <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> object doesn’t make
these calls — they are made by a module loader object that’s part of the
<a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> object.  This allows another level of flexibility, which can be
useful when changing the mechanics of <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> within the restricted
environment.)</p>
<p>By providing an alternate <code class="xref py py-class docutils literal notranslate"><span class="pre">RHooks</span></code> object, we can control the file system
accesses made to import a module, without changing the actual algorithm that
controls the order in which those accesses are made.  For instance, we could
substitute an <code class="xref py py-class docutils literal notranslate"><span class="pre">RHooks</span></code> object that passes all filesystem requests to a
file server elsewhere, via some RPC mechanism such as ILU.  Grail’s applet
loader uses this to support importing applets from a URL for a directory.</p>
<p>If <em>verbose</em> is true, additional debugging output may be sent to standard
output.</p>
</dd></dl>

<p>It is important to be aware that code running in a restricted environment can
still call the <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> function.  To disallow restricted code from
exiting the interpreter, always protect calls that cause restricted code to run
with a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement that catches the
<a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> exception.  Removing the <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> function from the
restricted environment is not sufficient — the restricted code could still use
<code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">SystemExit</span></code>.  Removing <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> is not a reasonable option;
some library code makes use of this and would break were it not available.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://grail.sourceforge.net/">Grail Home Page</a></dt>
<dd>Grail is a Web browser written entirely in Python.  It uses the <a class="reference internal" href="#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a>
module as a foundation for supporting Python applets, and can be used as an
example usage of this module.</dd>
</dl>
</div>
<div class="section" id="rexec-objects">
<span id="id1"></span><h2>30.1.1. RExec Objects<a class="headerlink" href="#rexec-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> instances support the following methods:</p>
<dl class="method">
<dt id="rexec.RExec.r_eval">
<code class="descclassname">RExec.</code><code class="descname">r_eval</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_eval" title="Permalink to this definition">¶</a></dt>
<dd><p><em>code</em> must either be a string containing a Python expression, or a compiled
code object, which will be evaluated in the restricted environment’s
<a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.  The value of the expression or code object will be
returned.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.r_exec">
<code class="descclassname">RExec.</code><code class="descname">r_exec</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_exec" title="Permalink to this definition">¶</a></dt>
<dd><p><em>code</em> must either be a string containing one or more lines of Python code, or a
compiled code object, which will be executed in the restricted environment’s
<a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.r_execfile">
<code class="descclassname">RExec.</code><code class="descname">r_execfile</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_execfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the Python code contained in the file <em>filename</em> in the restricted
environment’s <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.</p>
</dd></dl>

<p>Methods whose names begin with <code class="docutils literal notranslate"><span class="pre">s_</span></code> are similar to the functions beginning
with <code class="docutils literal notranslate"><span class="pre">r_</span></code>, but the code will be granted access to restricted versions of the
standard I/O streams <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>, and <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.</p>
<dl class="method">
<dt id="rexec.RExec.s_eval">
<code class="descclassname">RExec.</code><code class="descname">s_eval</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_eval" title="Permalink to this definition">¶</a></dt>
<dd><p><em>code</em> must be a string containing a Python expression, which will be evaluated
in the restricted environment.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.s_exec">
<code class="descclassname">RExec.</code><code class="descname">s_exec</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_exec" title="Permalink to this definition">¶</a></dt>
<dd><p><em>code</em> must be a string containing one or more lines of Python code, which will
be executed in the restricted environment.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.s_execfile">
<code class="descclassname">RExec.</code><code class="descname">s_execfile</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_execfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the Python code contained in the file <em>filename</em> in the restricted
environment.</p>
</dd></dl>

<p><a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> objects must also support various methods which will be
implicitly called by code executing in the restricted environment. Overriding
these methods in a subclass is used to change the policies enforced by a
restricted environment.</p>
<dl class="method">
<dt id="rexec.RExec.r_import">
<code class="descclassname">RExec.</code><code class="descname">r_import</code><span class="sig-paren">(</span><em>modulename</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">[</span>, <em>fromlist</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_import" title="Permalink to this definition">¶</a></dt>
<dd><p>Import the module <em>modulename</em>, raising an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> exception if the
module is considered unsafe.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.r_open">
<code class="descclassname">RExec.</code><code class="descname">r_open</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called when <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> is called in the restricted environment.  The
arguments are identical to those of <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, and a file object (or a class
instance compatible with file objects) should be returned.  <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a>’s
default behaviour is allow opening any file for reading, but forbidding any
attempt to write a file.  See the example below for an implementation of a less
restrictive <a class="reference internal" href="#rexec.RExec.r_open" title="rexec.RExec.r_open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">r_open()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.r_reload">
<code class="descclassname">RExec.</code><code class="descname">r_reload</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_reload" title="Permalink to this definition">¶</a></dt>
<dd><p>Reload the module object <em>module</em>, re-parsing and re-initializing it.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.r_unload">
<code class="descclassname">RExec.</code><code class="descname">r_unload</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.r_unload" title="Permalink to this definition">¶</a></dt>
<dd><p>Unload the module object <em>module</em> (remove it from the restricted environment’s
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> dictionary).</p>
</dd></dl>

<p>And their equivalents with access to restricted standard I/O streams:</p>
<dl class="method">
<dt id="rexec.RExec.s_import">
<code class="descclassname">RExec.</code><code class="descname">s_import</code><span class="sig-paren">(</span><em>modulename</em><span class="optional">[</span>, <em>globals</em><span class="optional">[</span>, <em>locals</em><span class="optional">[</span>, <em>fromlist</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_import" title="Permalink to this definition">¶</a></dt>
<dd><p>Import the module <em>modulename</em>, raising an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> exception if the
module is considered unsafe.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.s_reload">
<code class="descclassname">RExec.</code><code class="descname">s_reload</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_reload" title="Permalink to this definition">¶</a></dt>
<dd><p>Reload the module object <em>module</em>, re-parsing and re-initializing it.</p>
</dd></dl>

<dl class="method">
<dt id="rexec.RExec.s_unload">
<code class="descclassname">RExec.</code><code class="descname">s_unload</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#rexec.RExec.s_unload" title="Permalink to this definition">¶</a></dt>
<dd><p>Unload the module object <em>module</em>.</p>
</dd></dl>

</div>
<div class="section" id="defining-restricted-environments">
<span id="rexec-extension"></span><h2>30.1.2. Defining restricted environments<a class="headerlink" href="#defining-restricted-environments" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class has the following class attributes, which are used by
the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method.  Changing them on an existing instance won’t have
any effect; instead, create a subclass of <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> and assign them new
values in the class definition. Instances of the new class will then use those
new values.  All these attributes are tuples of strings.</p>
<dl class="attribute">
<dt id="rexec.RExec.nok_builtin_names">
<code class="descclassname">RExec.</code><code class="descname">nok_builtin_names</code><a class="headerlink" href="#rexec.RExec.nok_builtin_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the names of built-in functions which will <em>not</em> be available to
programs running in the restricted environment.  The value for <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is
<code class="docutils literal notranslate"><span class="pre">('open',</span> <span class="pre">'reload',</span> <span class="pre">'__import__')</span></code>. (This gives the exceptions, because by far
the majority of built-in functions are harmless.  A subclass that wants to
override this variable should probably start with the value from the base class
and concatenate additional forbidden functions — when new dangerous built-in
functions are added to Python, they will also be added to this module.)</p>
</dd></dl>

<dl class="attribute">
<dt id="rexec.RExec.ok_builtin_modules">
<code class="descclassname">RExec.</code><code class="descname">ok_builtin_modules</code><a class="headerlink" href="#rexec.RExec.ok_builtin_modules" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the names of built-in modules which can be safely imported. The value
for <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is <code class="docutils literal notranslate"><span class="pre">('audioop',</span> <span class="pre">'array',</span> <span class="pre">'binascii',</span> <span class="pre">'cmath',</span> <span class="pre">'errno',</span>
<span class="pre">'imageop',</span> <span class="pre">'marshal',</span> <span class="pre">'math',</span> <span class="pre">'md5',</span> <span class="pre">'operator',</span> <span class="pre">'parser',</span> <span class="pre">'regex',</span> <span class="pre">'select',</span>
<span class="pre">'sha',</span> <span class="pre">'_sre',</span> <span class="pre">'strop',</span> <span class="pre">'struct',</span> <span class="pre">'time')</span></code>.  A similar remark about overriding
this variable applies — use the value from the base class as a starting point.</p>
</dd></dl>

<dl class="attribute">
<dt id="rexec.RExec.ok_path">
<code class="descclassname">RExec.</code><code class="descname">ok_path</code><a class="headerlink" href="#rexec.RExec.ok_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the directories which will be searched when an <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> is
performed in the restricted environment.   The value for <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is the
same as <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> (at the time the module is loaded) for unrestricted code.</p>
</dd></dl>

<dl class="attribute">
<dt id="rexec.RExec.ok_posix_names">
<code class="descclassname">RExec.</code><code class="descname">ok_posix_names</code><a class="headerlink" href="#rexec.RExec.ok_posix_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the names of the functions in the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module which will be
available to programs running in the restricted environment.  The value for
<a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is <code class="docutils literal notranslate"><span class="pre">('error',</span> <span class="pre">'fstat',</span> <span class="pre">'listdir',</span> <span class="pre">'lstat',</span> <span class="pre">'readlink',</span> <span class="pre">'stat',</span>
<span class="pre">'times',</span> <span class="pre">'uname',</span> <span class="pre">'getpid',</span> <span class="pre">'getppid',</span> <span class="pre">'getcwd',</span> <span class="pre">'getuid',</span> <span class="pre">'getgid',</span> <span class="pre">'geteuid',</span>
<span class="pre">'getegid')</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="rexec.RExec.ok_sys_names">
<code class="descclassname">RExec.</code><code class="descname">ok_sys_names</code><a class="headerlink" href="#rexec.RExec.ok_sys_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the names of the functions and variables in the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module which
will be available to programs running in the restricted environment.  The value
for <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is <code class="docutils literal notranslate"><span class="pre">('ps1',</span> <span class="pre">'ps2',</span> <span class="pre">'copyright',</span> <span class="pre">'version',</span> <span class="pre">'platform',</span>
<span class="pre">'exit',</span> <span class="pre">'maxint')</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="rexec.RExec.ok_file_types">
<code class="descclassname">RExec.</code><code class="descname">ok_file_types</code><a class="headerlink" href="#rexec.RExec.ok_file_types" title="Permalink to this definition">¶</a></dt>
<dd><p>Contains the file types from which modules are allowed to be loaded. Each file
type is an integer constant defined in the <a class="reference internal" href="imp.html#module-imp" title="imp: Access the implementation of the import statement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imp</span></code></a> module. The meaningful
values are <code class="xref py py-const docutils literal notranslate"><span class="pre">PY_SOURCE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">PY_COMPILED</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">C_EXTENSION</span></code>.
The value for <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> is <code class="docutils literal notranslate"><span class="pre">(C_EXTENSION,</span> <span class="pre">PY_SOURCE)</span></code>.  Adding
<code class="xref py py-const docutils literal notranslate"><span class="pre">PY_COMPILED</span></code> in subclasses is not recommended; an attacker could exit
the restricted execution mode by putting a forged byte-compiled file
(<code class="file docutils literal notranslate"><span class="pre">.pyc</span></code>) anywhere in your file system, for example by writing it to
<code class="file docutils literal notranslate"><span class="pre">/tmp</span></code> or uploading it to the <code class="file docutils literal notranslate"><span class="pre">/incoming</span></code> directory of your public
FTP server.</p>
</dd></dl>

</div>
<div class="section" id="an-example">
<h2>30.1.3. An example<a class="headerlink" href="#an-example" title="Permalink to this headline">¶</a></h2>
<p>Let us say that we want a slightly more relaxed policy than the standard
<a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class.  For example, if we’re willing to allow files in
<code class="file docutils literal notranslate"><span class="pre">/tmp</span></code> to be written, we can subclass the <a class="reference internal" href="#rexec.RExec" title="rexec.RExec"><code class="xref py py-class docutils literal notranslate"><span class="pre">RExec</span></code></a> class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TmpWriterRExec</span><span class="p">(</span><span class="n">rexec</span><span class="o">.</span><span class="n">RExec</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">r_open</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">file</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">&#39;r&#39;</span><span class="p">,</span> <span class="n">buf</span><span class="o">=-</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">mode</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;r&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">):</span>
            <span class="k">pass</span>
        <span class="k">elif</span> <span class="n">mode</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;ab&#39;</span><span class="p">):</span>
            <span class="c1"># check filename: must begin with /tmp/</span>
            <span class="k">if</span> <span class="n">file</span><span class="p">[:</span><span class="mi">5</span><span class="p">]</span><span class="o">!=</span><span class="s1">&#39;/tmp/&#39;</span><span class="p">:</span>
                <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s2">&quot;can&#39;t write outside /tmp&quot;</span><span class="p">)</span>
            <span class="k">elif</span> <span class="p">(</span><span class="n">string</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="s1">&#39;/../&#39;</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">0</span> <span class="ow">or</span>
                 <span class="n">file</span><span class="p">[:</span><span class="mi">3</span><span class="p">]</span> <span class="o">==</span> <span class="s1">&#39;../&#39;</span> <span class="ow">or</span> <span class="n">file</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">:]</span> <span class="o">==</span> <span class="s1">&#39;/..&#39;</span><span class="p">):</span>
                <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s2">&quot;&#39;..&#39; in filename forbidden&quot;</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s2">&quot;Illegal open() mode&quot;</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">open</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">buf</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice that the above code will occasionally forbid a perfectly valid filename;
for example, code in the restricted environment won’t be able to open a file
called <code class="file docutils literal notranslate"><span class="pre">/tmp/foo/../bar</span></code>.  To fix this, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">r_open()</span></code> method would
have to simplify the filename to <code class="file docutils literal notranslate"><span class="pre">/tmp/bar</span></code>, which would require splitting
apart the filename and performing various operations on it.  In cases where
security is at stake, it may be preferable to write simple code which is
sometimes overly restrictive, instead of more general code that is also more
complex and may harbor a subtle security hole.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a><ul>
<li><a class="reference internal" href="#rexec-objects">30.1.1. RExec Objects</a></li>
<li><a class="reference internal" href="#defining-restricted-environments">30.1.2. Defining restricted environments</a></li>
<li><a class="reference internal" href="#an-example">30.1.3. An example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="restricted.html"
                        title="previous chapter">30. Restricted Execution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bastion.html"
                        title="next chapter">30.2. <code class="docutils literal notranslate"><span class="pre">Bastion</span></code> — Restricting access to objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/rexec.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bastion.html" title="30.2. Bastion — Restricting access to objects"
             >next</a> |</li>
        <li class="right" >
          <a href="restricted.html" title="30. Restricted Execution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="restricted.html" >30. Restricted Execution</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\bg;�H�H�html/library/rfc822.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.11. rfc822 — Parse RFC 2822 mail headers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings" href="base64.html" />
    <link rel="prev" title="18.10. multifile — Support for files containing distinct parts" href="multifile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/rfc822.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="base64.html" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="multifile.html" title="18.10. multifile — Support for files containing distinct parts"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-rfc822">
<span id="rfc822-parse-rfc-2822-mail-headers"></span><h1>18.11. <a class="reference internal" href="#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> — Parse RFC 2822 mail headers<a class="headerlink" href="#module-rfc822" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package should be used in preference to the <a class="reference internal" href="#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a>
module.  This module is present only to maintain backward compatibility, and
has been removed in Python 3.</p>
</div>
<p>This module defines a class, <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a>, which represents an “email
message” as defined by the Internet standard <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>. <a class="footnote-reference" href="#id4" id="id1">[1]</a>  Such messages
consist of a collection of message headers, and a message body.  This module
also defines a helper class <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> for parsing <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>
addresses.  Please refer to the RFC for information on the specific syntax of
<span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> messages.</p>
<p id="index-3">The <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module provides classes  to read mailboxes produced by
various end-user mail programs.</p>
<dl class="class">
<dt id="rfc822.Message">
<em class="property">class </em><code class="descclassname">rfc822.</code><code class="descname">Message</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>seekable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance is instantiated with an input object as parameter.
Message relies only on the input object having a <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method; in
particular, ordinary file objects qualify.  Instantiation reads headers from the
input object up to a delimiter line (normally a blank line) and stores them in
the instance.  The message body, following the headers, is not consumed.</p>
<p>This class can work with any input object that supports a <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>
method.  If the input object has seek and tell capability, the
<a class="reference internal" href="#rfc822.Message.rewindbody" title="rfc822.Message.rewindbody"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rewindbody()</span></code></a> method will work; also, illegal lines will be pushed back
onto the input stream.  If the input object lacks seek but has an <code class="xref py py-meth docutils literal notranslate"><span class="pre">unread()</span></code>
method that can push back a line of input, <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> will use that to
push back illegal lines.  Thus this class can be used to parse messages coming
from a buffered stream.</p>
<p>The optional <em>seekable</em> argument is provided as a workaround for certain stdio
libraries in which <code class="xref c c-func docutils literal notranslate"><span class="pre">tell()</span></code> discards buffered data before discovering that
the <code class="xref c c-func docutils literal notranslate"><span class="pre">lseek()</span></code> system call doesn’t work.  For maximum portability, you
should set the seekable argument to zero to prevent that initial <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code>
when passing in an unseekable object such as a file object created from a socket
object.</p>
<p>Input lines as read from the file may either be terminated by CR-LF or by a
single linefeed; a terminating CR-LF is replaced by a single linefeed before the
line is stored.</p>
<p>All header matching is done independent of upper or lower case; e.g.
<code class="docutils literal notranslate"><span class="pre">m['From']</span></code>, <code class="docutils literal notranslate"><span class="pre">m['from']</span></code> and <code class="docutils literal notranslate"><span class="pre">m['FROM']</span></code> all yield the same result.</p>
</dd></dl>

<dl class="class">
<dt id="rfc822.AddressList">
<em class="property">class </em><code class="descclassname">rfc822.</code><code class="descname">AddressList</code><span class="sig-paren">(</span><em>field</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList" title="Permalink to this definition">¶</a></dt>
<dd><p>You may instantiate the <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> helper class using a single string
parameter, a comma-separated list of <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> addresses to be parsed.  (The
parameter <code class="docutils literal notranslate"><span class="pre">None</span></code> yields an empty list.)</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.quote">
<code class="descclassname">rfc822.</code><code class="descname">quote</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.quote" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new string with backslashes in <em>str</em> replaced by two backslashes and
double quotes replaced by backslash-double quote.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.unquote">
<code class="descclassname">rfc822.</code><code class="descname">unquote</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.unquote" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new string which is an <em>unquoted</em> version of <em>str</em>. If <em>str</em> ends and
begins with double quotes, they are stripped off.  Likewise if <em>str</em> ends and
begins with angle brackets, they are stripped off.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.parseaddr">
<code class="descclassname">rfc822.</code><code class="descname">parseaddr</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.parseaddr" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse <em>address</em>, which should be the value of some address-containing field such
as <em class="mailheader">To</em> or <em class="mailheader">Cc</em>, into its constituent “realname” and
“email address” parts. Returns a tuple of that information, unless the parse
fails, in which case a 2-tuple <code class="docutils literal notranslate"><span class="pre">(None,</span> <span class="pre">None)</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.dump_address_pair">
<code class="descclassname">rfc822.</code><code class="descname">dump_address_pair</code><span class="sig-paren">(</span><em>pair</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.dump_address_pair" title="Permalink to this definition">¶</a></dt>
<dd><p>The inverse of <a class="reference internal" href="#rfc822.parseaddr" title="rfc822.parseaddr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parseaddr()</span></code></a>, this takes a 2-tuple of the form <code class="docutils literal notranslate"><span class="pre">(realname,</span>
<span class="pre">email_address)</span></code> and returns the string value suitable for a <em class="mailheader">To</em> or
<em class="mailheader">Cc</em> header.  If the first element of <em>pair</em> is false, then the
second element is returned unmodified.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.parsedate">
<code class="descclassname">rfc822.</code><code class="descname">parsedate</code><span class="sig-paren">(</span><em>date</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.parsedate" title="Permalink to this definition">¶</a></dt>
<dd><p>Attempts to parse a date according to the rules in <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>. however, some
mailers don’t follow that format as specified, so <a class="reference internal" href="#rfc822.parsedate" title="rfc822.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a> tries to
guess correctly in such cases.  <em>date</em> is a string containing an <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>
date, such as  <code class="docutils literal notranslate"><span class="pre">'Mon,</span> <span class="pre">20</span> <span class="pre">Nov</span> <span class="pre">1995</span> <span class="pre">19:12:08</span> <span class="pre">-0500'</span></code>.  If it succeeds in parsing
the date, <a class="reference internal" href="#rfc822.parsedate" title="rfc822.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a> returns a 9-tuple that can be passed directly to
<a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>; otherwise <code class="docutils literal notranslate"><span class="pre">None</span></code> will be returned.  Note that indexes 6,
7, and 8 of the result tuple are not usable.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.parsedate_tz">
<code class="descclassname">rfc822.</code><code class="descname">parsedate_tz</code><span class="sig-paren">(</span><em>date</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.parsedate_tz" title="Permalink to this definition">¶</a></dt>
<dd><p>Performs the same function as <a class="reference internal" href="#rfc822.parsedate" title="rfc822.parsedate"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate()</span></code></a>, but returns either <code class="docutils literal notranslate"><span class="pre">None</span></code> or
a 10-tuple; the first 9 elements make up a tuple that can be passed directly to
<a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>, and the tenth is the offset of the date’s timezone from UTC
(which is the official term for Greenwich Mean Time).  (Note that the sign of
the timezone offset is the opposite of the sign of the <code class="docutils literal notranslate"><span class="pre">time.timezone</span></code>
variable for the same timezone; the latter variable follows the POSIX standard
while this module follows <span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>.)  If the input string has no timezone,
the last element of the tuple returned is <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Note that indexes 6, 7, and
8 of the result tuple are not usable.</p>
</dd></dl>

<dl class="function">
<dt id="rfc822.mktime_tz">
<code class="descclassname">rfc822.</code><code class="descname">mktime_tz</code><span class="sig-paren">(</span><em>tuple</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.mktime_tz" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn a 10-tuple as returned by <a class="reference internal" href="#rfc822.parsedate_tz" title="rfc822.parsedate_tz"><code class="xref py py-func docutils literal notranslate"><span class="pre">parsedate_tz()</span></code></a> into a UTC timestamp.  If
the timezone item in the tuple is <code class="docutils literal notranslate"><span class="pre">None</span></code>, assume local time.  Minor
deficiency: this first interprets the first 8 elements as a local time and then
compensates for the timezone difference; this may yield a slight error around
daylight savings time switch dates.  Not enough to worry about for common use.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a></dt>
<dd>Comprehensive email handling package; supersedes the <a class="reference internal" href="#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module.</dd>
<dt>Module <a class="reference internal" href="mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a></dt>
<dd>Classes to read various mailbox formats produced  by end-user mail programs.</dd>
<dt>Module <a class="reference internal" href="mimetools.html#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a></dt>
<dd>Subclass of <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">rfc822.Message</span></code></a> that handles MIME encoded messages.</dd>
</dl>
</div>
<div class="section" id="message-objects">
<span id="id2"></span><h2>18.11.1. Message Objects<a class="headerlink" href="#message-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="rfc822.Message.rewindbody">
<code class="descclassname">Message.</code><code class="descname">rewindbody</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.rewindbody" title="Permalink to this definition">¶</a></dt>
<dd><p>Seek to the start of the message body.  This only works if the file object is
seekable.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.isheader">
<code class="descclassname">Message.</code><code class="descname">isheader</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.isheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a line’s canonicalized fieldname (the dictionary key that will be used
to index it) if the line is a legal <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> header; otherwise returns
<code class="docutils literal notranslate"><span class="pre">None</span></code> (implying that parsing should stop here and the line be pushed back on
the input stream).  It is sometimes useful to override this method in a
subclass.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.islast">
<code class="descclassname">Message.</code><code class="descname">islast</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.islast" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the given line is a delimiter on which Message should stop.  The
delimiter line is consumed, and the file object’s read location positioned
immediately after it.  By default this method just checks that the line is
blank, but you can override it in a subclass.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.iscomment">
<code class="descclassname">Message.</code><code class="descname">iscomment</code><span class="sig-paren">(</span><em>line</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.iscomment" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the given line should be ignored entirely, just skipped. By
default this is a stub that always returns <code class="docutils literal notranslate"><span class="pre">False</span></code>, but you can override it in
a subclass.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getallmatchingheaders">
<code class="descclassname">Message.</code><code class="descname">getallmatchingheaders</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getallmatchingheaders" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of lines consisting of all headers matching <em>name</em>, if any.  Each
physical line, whether it is a continuation line or not, is a separate list
item.  Return the empty list if no header matches <em>name</em>.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getfirstmatchingheader">
<code class="descclassname">Message.</code><code class="descname">getfirstmatchingheader</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getfirstmatchingheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of lines comprising the first header matching <em>name</em>, and its
continuation line(s), if any.  Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is no header matching
<em>name</em>.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getrawheader">
<code class="descclassname">Message.</code><code class="descname">getrawheader</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getrawheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a single string consisting of the text after the colon in the first
header matching <em>name</em>.  This includes leading whitespace, the trailing
linefeed, and internal linefeeds and whitespace if there any continuation
line(s) were present.  Return <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is no header matching <em>name</em>.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getheader">
<code class="descclassname">Message.</code><code class="descname">getheader</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getheader" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a single string consisting of the last header matching <em>name</em>,
but strip leading and trailing whitespace.
Internal whitespace is not stripped.  The optional <em>default</em> argument can be
used to specify a different default to be returned when there is no header
matching <em>name</em>; it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.
This is the preferred way to get parsed headers.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.get">
<code class="descclassname">Message.</code><code class="descname">get</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.get" title="Permalink to this definition">¶</a></dt>
<dd><p>An alias for <a class="reference internal" href="#rfc822.Message.getheader" title="rfc822.Message.getheader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getheader()</span></code></a>, to make the interface more compatible  with
regular dictionaries.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getaddr">
<code class="descclassname">Message.</code><code class="descname">getaddr</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getaddr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pair <code class="docutils literal notranslate"><span class="pre">(full</span> <span class="pre">name,</span> <span class="pre">email</span> <span class="pre">address)</span></code> parsed from the string returned by
<code class="docutils literal notranslate"><span class="pre">getheader(name)</span></code>.  If no header matching <em>name</em> exists, return <code class="docutils literal notranslate"><span class="pre">(None,</span>
<span class="pre">None)</span></code>; otherwise both the full name and the address are (possibly empty)
strings.</p>
<p>Example: If <em>m</em>’s first <em class="mailheader">From</em> header contains the string
<code class="docutils literal notranslate"><span class="pre">'jack&#64;cwi.nl</span> <span class="pre">(Jack</span> <span class="pre">Jansen)'</span></code>, then <code class="docutils literal notranslate"><span class="pre">m.getaddr('From')</span></code> will yield the pair
<code class="docutils literal notranslate"><span class="pre">('Jack</span> <span class="pre">Jansen',</span> <span class="pre">'jack&#64;cwi.nl')</span></code>. If the header contained <code class="docutils literal notranslate"><span class="pre">'Jack</span> <span class="pre">Jansen</span>
<span class="pre">&lt;jack&#64;cwi.nl&gt;'</span></code> instead, it would yield the exact same result.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getaddrlist">
<code class="descclassname">Message.</code><code class="descname">getaddrlist</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getaddrlist" title="Permalink to this definition">¶</a></dt>
<dd><p>This is similar to <code class="docutils literal notranslate"><span class="pre">getaddr(list)</span></code>, but parses a header containing a list of
email addresses (e.g. a <em class="mailheader">To</em> header) and returns a list of <code class="docutils literal notranslate"><span class="pre">(full</span>
<span class="pre">name,</span> <span class="pre">email</span> <span class="pre">address)</span></code> pairs (even if there was only one address in the header).
If there is no header matching <em>name</em>, return an empty list.</p>
<p>If multiple headers exist that match the named header (e.g. if there are several
<em class="mailheader">Cc</em> headers), all are parsed for addresses. Any continuation lines
the named headers contain are also parsed.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getdate">
<code class="descclassname">Message.</code><code class="descname">getdate</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getdate" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a header using <a class="reference internal" href="#rfc822.Message.getheader" title="rfc822.Message.getheader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getheader()</span></code></a> and parse it into a 9-tuple compatible
with <a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>; note that fields 6, 7, and 8  are not usable.  If
there is no header matching <em>name</em>, or it is unparsable, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Date parsing appears to be a black art, and not all mailers adhere to the
standard.  While it has been tested and found correct on a large collection of
email from many sources, it is still possible that this function may
occasionally yield an incorrect result.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.Message.getdate_tz">
<code class="descclassname">Message.</code><code class="descname">getdate_tz</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.Message.getdate_tz" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a header using <a class="reference internal" href="#rfc822.Message.getheader" title="rfc822.Message.getheader"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getheader()</span></code></a> and parse it into a 10-tuple; the
first 9 elements will make a tuple compatible with <a class="reference internal" href="time.html#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.mktime()</span></code></a>, and the
10th is a number giving the offset of the date’s timezone from UTC.  Note that
fields 6, 7, and 8  are not usable.  Similarly to <a class="reference internal" href="#rfc822.Message.getdate" title="rfc822.Message.getdate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getdate()</span></code></a>, if there is
no header matching <em>name</em>, or it is unparsable, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<p><a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances also support a limited mapping interface. In
particular: <code class="docutils literal notranslate"><span class="pre">m[name]</span></code> is like <code class="docutils literal notranslate"><span class="pre">m.getheader(name)</span></code> but raises <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>
if there is no matching header; and <code class="docutils literal notranslate"><span class="pre">len(m)</span></code>, <code class="docutils literal notranslate"><span class="pre">m.get(name[,</span> <span class="pre">default])</span></code>,
<code class="docutils literal notranslate"><span class="pre">name</span> <span class="pre">in</span> <span class="pre">m</span></code>, <code class="docutils literal notranslate"><span class="pre">m.keys()</span></code>, <code class="docutils literal notranslate"><span class="pre">m.values()</span></code> <code class="docutils literal notranslate"><span class="pre">m.items()</span></code>, and
<code class="docutils literal notranslate"><span class="pre">m.setdefault(name[,</span> <span class="pre">default])</span></code> act as expected, with the one difference
that <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code> uses an empty string as the default value.
<a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances also support the mapping writable interface <code class="docutils literal notranslate"><span class="pre">m[name]</span>
<span class="pre">=</span> <span class="pre">value</span></code> and <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">m[name]</span></code>.  <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> objects do not support the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code>, <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code>, or <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> methods of the
mapping interface.  (Support for <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code> was only
added in Python 2.2.)</p>
<p>Finally, <a class="reference internal" href="#rfc822.Message" title="rfc822.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> instances have some public instance variables:</p>
<dl class="attribute">
<dt id="rfc822.Message.headers">
<code class="descclassname">Message.</code><code class="descname">headers</code><a class="headerlink" href="#rfc822.Message.headers" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing the entire set of header lines, in the order in which they
were read (except that setitem calls may disturb this order). Each line contains
a trailing newline.  The blank line terminating the headers is not contained in
the list.</p>
</dd></dl>

<dl class="attribute">
<dt id="rfc822.Message.fp">
<code class="descclassname">Message.</code><code class="descname">fp</code><a class="headerlink" href="#rfc822.Message.fp" title="Permalink to this definition">¶</a></dt>
<dd><p>The file or file-like object passed at instantiation time.  This can be used to
read the message content.</p>
</dd></dl>

<dl class="attribute">
<dt id="rfc822.Message.unixfrom">
<code class="descclassname">Message.</code><code class="descname">unixfrom</code><a class="headerlink" href="#rfc822.Message.unixfrom" title="Permalink to this definition">¶</a></dt>
<dd><p>The Unix <code class="docutils literal notranslate"><span class="pre">From</span></code> line, if the message had one, or an empty string.  This is
needed to regenerate the message in some contexts, such as an <code class="docutils literal notranslate"><span class="pre">mbox</span></code>-style
mailbox file.</p>
</dd></dl>

</div>
<div class="section" id="addresslist-objects">
<span id="id3"></span><h2>18.11.2. AddressList Objects<a class="headerlink" href="#addresslist-objects" title="Permalink to this headline">¶</a></h2>
<p>An <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="rfc822.AddressList.__len__">
<code class="descclassname">AddressList.</code><code class="descname">__len__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of addresses in the address list.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.AddressList.__str__">
<code class="descclassname">AddressList.</code><code class="descname">__str__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a canonicalized string representation of the address list. Addresses are
rendered in “name” &lt;<a class="reference external" href="mailto:host&#37;&#52;&#48;domain">host<span>&#64;</span>domain</a>&gt; form, comma-separated.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.AddressList.__add__">
<code class="descclassname">AddressList.</code><code class="descname">__add__</code><span class="sig-paren">(</span><em>alist</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__add__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> instance that contains all addresses in both
<a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> operands, with duplicates removed (set union).</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.AddressList.__iadd__">
<code class="descclassname">AddressList.</code><code class="descname">__iadd__</code><span class="sig-paren">(</span><em>alist</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__iadd__" title="Permalink to this definition">¶</a></dt>
<dd><p>In-place version of <a class="reference internal" href="#rfc822.AddressList.__add__" title="rfc822.AddressList.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>; turns this <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> instance
into the union of itself and the right-hand instance, <em>alist</em>.</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.AddressList.__sub__">
<code class="descclassname">AddressList.</code><code class="descname">__sub__</code><span class="sig-paren">(</span><em>alist</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__sub__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> instance that contains every address in the
left-hand <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> operand that is not present in the right-hand
address operand (set difference).</p>
</dd></dl>

<dl class="method">
<dt id="rfc822.AddressList.__isub__">
<code class="descclassname">AddressList.</code><code class="descname">__isub__</code><span class="sig-paren">(</span><em>alist</em><span class="sig-paren">)</span><a class="headerlink" href="#rfc822.AddressList.__isub__" title="Permalink to this definition">¶</a></dt>
<dd><p>In-place version of <a class="reference internal" href="#rfc822.AddressList.__sub__" title="rfc822.AddressList.__sub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__sub__()</span></code></a>, removing addresses in this list which are
also in <em>alist</em>.</p>
</dd></dl>

<p>Finally, <a class="reference internal" href="#rfc822.AddressList" title="rfc822.AddressList"><code class="xref py py-class docutils literal notranslate"><span class="pre">AddressList</span></code></a> instances have one public instance variable:</p>
<dl class="attribute">
<dt id="rfc822.AddressList.addresslist">
<code class="descclassname">AddressList.</code><code class="descname">addresslist</code><a class="headerlink" href="#rfc822.AddressList.addresslist" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of tuple string pairs, one per address.  In each member, the first is the
canonicalized name part, the second is the actual route-address (<code class="docutils literal notranslate"><span class="pre">'&#64;'</span></code>-separated username-host.domain pair).</p>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This module originally conformed to <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>, hence the name.  Since then,
<span class="target" id="index-10"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> has been released as an update to <span class="target" id="index-11"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>.  This module should be
considered <span class="target" id="index-12"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>-conformant, especially in cases where the syntax or
semantics have changed since <span class="target" id="index-13"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a><ul>
<li><a class="reference internal" href="#message-objects">18.11.1. Message Objects</a></li>
<li><a class="reference internal" href="#addresslist-objects">18.11.2. AddressList Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="multifile.html"
                        title="previous chapter">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="base64.html"
                        title="next chapter">18.12. <code class="docutils literal notranslate"><span class="pre">base64</span></code> — RFC 3548: Base16, Base32, Base64 Data Encodings</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/rfc822.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="base64.html" title="18.12. base64 — RFC 3548: Base16, Base32, Base64 Data Encodings"
             >next</a> |</li>
        <li class="right" >
          <a href="multifile.html" title="18.10. multifile — Support for files containing distinct parts"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���|8|8html/library/rlcompleter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.9. rlcompleter — Completion function for GNU readline &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17. Interprocess Communication and Networking" href="ipc.html" />
    <link rel="prev" title="16.8. readline — GNU readline interface" href="readline.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/rlcompleter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ipc.html" title="17. Interprocess Communication and Networking"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="readline.html" title="16.8. readline — GNU readline interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-rlcompleter">
<span id="rlcompleter-completion-function-for-gnu-readline"></span><h1>16.9. <a class="reference internal" href="#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> — Completion function for GNU readline<a class="headerlink" href="#module-rlcompleter" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/rlcompleter.py">Lib/rlcompleter.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module defines a completion function suitable for the
<a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module by completing valid Python identifiers and keywords.</p>
<p>When this module is imported on a Unix platform with the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module
available, an instance of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Completer</span></code> class is automatically created
and its <code class="xref py py-meth docutils literal notranslate"><span class="pre">complete()</span></code> method is set as the <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> completer.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">rlcompleter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">readline</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s2">&quot;tab: complete&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">readline</span><span class="o">.</span> <span class="o">&lt;</span><span class="n">TAB</span> <span class="n">PRESSED</span><span class="o">&gt;</span>
<span class="go">readline.__doc__          readline.get_line_buffer(  readline.read_init_file(</span>
<span class="go">readline.__file__         readline.insert_text(      readline.set_completer(</span>
<span class="go">readline.__name__         readline.parse_and_bind(</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">readline</span><span class="o">.</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module is designed for use with Python’s interactive
mode.  A user can add the following lines to his or her initialization file
(identified by the <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> environment variable) to get
automatic <kbd class="kbd docutils literal notranslate">Tab</kbd> completion:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">readline</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Module readline not available.&quot;</span>
<span class="k">else</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">rlcompleter</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s2">&quot;tab: complete&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>On platforms without <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a>, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Completer</span></code> class defined by
this module can still be used for custom purposes.</p>
<div class="section" id="completer-objects">
<span id="id1"></span><h2>16.9.1. Completer Objects<a class="headerlink" href="#completer-objects" title="Permalink to this headline">¶</a></h2>
<p>Completer objects have the following method:</p>
<dl class="method">
<dt id="rlcompleter.Completer.complete">
<code class="descclassname">Completer.</code><code class="descname">complete</code><span class="sig-paren">(</span><em>text</em>, <em>state</em><span class="sig-paren">)</span><a class="headerlink" href="#rlcompleter.Completer.complete" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>state</em>th completion for <em>text</em>.</p>
<p>If called for <em>text</em> that doesn’t include a period character (<code class="docutils literal notranslate"><span class="pre">'.'</span></code>), it will
complete from names currently defined in <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, <a class="reference internal" href="__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> and
keywords (as defined by the <a class="reference internal" href="keyword.html#module-keyword" title="keyword: Test whether a string is a keyword in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">keyword</span></code></a> module).</p>
<p>If called for a dotted name, it will try to evaluate anything without obvious
side-effects (functions will not be evaluated, but it can generate calls to
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>) up to the last part, and find matches for the rest via the
<a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> function.  Any exception raised during the evaluation of the
expression is caught, silenced and <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is returned.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a><ul>
<li><a class="reference internal" href="#completer-objects">16.9.1. Completer Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="readline.html"
                        title="previous chapter">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ipc.html"
                        title="next chapter">17. Interprocess Communication and Networking</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/rlcompleter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ipc.html" title="17. Interprocess Communication and Networking"
             >next</a> |</li>
        <li class="right" >
          <a href="readline.html" title="16.8. readline — GNU readline interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\&$[4[4html/library/robotparser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.3. robotparser — Parser for robots.txt &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.4. netrc — netrc file processing" href="netrc.html" />
    <link rel="prev" title="13.2. ConfigParser — Configuration file parser" href="configparser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/robotparser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="13.4. netrc — netrc file processing"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="configparser.html" title="13.2. ConfigParser — Configuration file parser"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-robotparser">
<span id="robotparser-parser-for-robots-txt"></span><h1>13.3. <a class="reference internal" href="#module-robotparser" title="robotparser: Loads a robots.txt file and answers questions about fetchability of other URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">robotparser</span></code></a> —  Parser for robots.txt<a class="headerlink" href="#module-robotparser" title="Permalink to this headline">¶</a></h1>
<div class="admonition note" id="index-0">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-robotparser" title="robotparser: Loads a robots.txt file and answers questions about fetchability of other URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">robotparser</span></code></a> module has been renamed <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.robotparser</span></code> in
Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<p>This module provides a single class, <a class="reference internal" href="#robotparser.RobotFileParser" title="robotparser.RobotFileParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">RobotFileParser</span></code></a>, which answers
questions about whether or not a particular user agent can fetch a URL on the
Web site that published the <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> file.  For more details on the
structure of <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> files, see <a class="reference external" href="http://www.robotstxt.org/orig.html">http://www.robotstxt.org/orig.html</a>.</p>
<dl class="class">
<dt id="robotparser.RobotFileParser">
<em class="property">class </em><code class="descclassname">robotparser.</code><code class="descname">RobotFileParser</code><span class="sig-paren">(</span><em>url=''</em><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser" title="Permalink to this definition">¶</a></dt>
<dd><p>This class provides methods to read, parse and answer questions about the
<code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> file at <em>url</em>.</p>
<dl class="method">
<dt id="robotparser.RobotFileParser.set_url">
<code class="descname">set_url</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.set_url" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the URL referring to a <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> file.</p>
</dd></dl>

<dl class="method">
<dt id="robotparser.RobotFileParser.read">
<code class="descname">read</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads the <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> URL and feeds it to the parser.</p>
</dd></dl>

<dl class="method">
<dt id="robotparser.RobotFileParser.parse">
<code class="descname">parse</code><span class="sig-paren">(</span><em>lines</em><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses the lines argument.</p>
</dd></dl>

<dl class="method">
<dt id="robotparser.RobotFileParser.can_fetch">
<code class="descname">can_fetch</code><span class="sig-paren">(</span><em>useragent</em>, <em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.can_fetch" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the <em>useragent</em> is allowed to fetch the <em>url</em>
according to the rules contained in the parsed <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code>
file.</p>
</dd></dl>

<dl class="method">
<dt id="robotparser.RobotFileParser.mtime">
<code class="descname">mtime</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.mtime" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the time the <code class="docutils literal notranslate"><span class="pre">robots.txt</span></code> file was last fetched.  This is
useful for long-running web spiders that need to check for new
<code class="docutils literal notranslate"><span class="pre">robots.txt</span></code> files periodically.</p>
</dd></dl>

<dl class="method">
<dt id="robotparser.RobotFileParser.modified">
<code class="descname">modified</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#robotparser.RobotFileParser.modified" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the time the <code class="docutils literal notranslate"><span class="pre">robots.txt</span></code> file was last fetched to the current
time.</p>
</dd></dl>

</dd></dl>

<p>The following example demonstrates basic use of the RobotFileParser class.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">robotparser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rp</span> <span class="o">=</span> <span class="n">robotparser</span><span class="o">.</span><span class="n">RobotFileParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rp</span><span class="o">.</span><span class="n">set_url</span><span class="p">(</span><span class="s2">&quot;http://www.musi-cal.com/robots.txt&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rp</span><span class="o">.</span><span class="n">can_fetch</span><span class="p">(</span><span class="s2">&quot;*&quot;</span><span class="p">,</span> <span class="s2">&quot;http://www.musi-cal.com/cgi-bin/search?city=San+Francisco&quot;</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">rp</span><span class="o">.</span><span class="n">can_fetch</span><span class="p">(</span><span class="s2">&quot;*&quot;</span><span class="p">,</span> <span class="s2">&quot;http://www.musi-cal.com/&quot;</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="configparser.html"
                        title="previous chapter">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="netrc.html"
                        title="next chapter">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/robotparser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="13.4. netrc — netrc file processing"
             >next</a> |</li>
        <li class="right" >
          <a href="configparser.html" title="13.2. ConfigParser — Configuration file parser"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\8v�U�Uhtml/library/runpy.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.7. runpy — Locating and executing Python modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32. Python Language Services" href="language.html" />
    <link rel="prev" title="31.6. modulefinder — Find modules used by a script" href="modulefinder.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/runpy.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="language.html" title="32. Python Language Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.6. modulefinder — Find modules used by a script"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-runpy">
<span id="runpy-locating-and-executing-python-modules"></span><h1>31.7. <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> — Locating and executing Python modules<a class="headerlink" href="#module-runpy" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/runpy.py">Lib/runpy.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module is used to locate and run Python modules without
importing them first. Its main use is to implement the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> command
line switch that allows scripts to be located using the Python module
namespace rather than the filesystem.</p>
<p>The <a class="reference internal" href="#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module provides two functions:</p>
<dl class="function">
<dt id="runpy.run_module">
<code class="descclassname">runpy.</code><code class="descname">run_module</code><span class="sig-paren">(</span><em>mod_name</em>, <em>init_globals=None</em>, <em>run_name=None</em>, <em>alter_sys=False</em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_module" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Execute the code of the specified module and return the resulting module
globals dictionary. The module’s code is first located using the standard
import mechanism (refer to <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for details) and then executed in a
fresh module namespace.</p>
<p>If the supplied module name refers to a package rather than a normal
module, then that package is imported and the <code class="docutils literal notranslate"><span class="pre">__main__</span></code> submodule within
that package is then executed and the resulting module globals dictionary
returned.</p>
<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by <a class="reference internal" href="#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_module()</span></code></a>.</p>
<p>The special global variables <code class="docutils literal notranslate"><span class="pre">__name__</span></code>, <code class="docutils literal notranslate"><span class="pre">__file__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code>
and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> are set in the globals dictionary before the module
code is executed (Note that this is a minimal set of variables - other
variables may be set implicitly as an interpreter implementation detail).</p>
<p><code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, to <code class="docutils literal notranslate"><span class="pre">mod_name</span> <span class="pre">+</span> <span class="pre">'.__main__'</span></code> if the named module is a
package and to the <em>mod_name</em> argument otherwise.</p>
<p><code class="docutils literal notranslate"><span class="pre">__file__</span></code> is set to the name provided by the module loader. If the
loader does not make filename information available, this variable is set
to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">__loader__</span></code> is set to the <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> module loader used to retrieve the
code for the module (This loader may be a wrapper around the standard
import mechanism).</p>
<p><code class="docutils literal notranslate"><span class="pre">__package__</span></code> is set to <em>mod_name</em> if the named module is a package and
to <code class="docutils literal notranslate"><span class="pre">mod_name.rpartition('.')[0]</span></code> otherwise.</p>
<p>If the argument <em>alter_sys</em> is supplied and evaluates to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>,
then <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is updated with the value of <code class="docutils literal notranslate"><span class="pre">__file__</span></code> and
<code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code> is updated with a temporary module object for the
module being executed. Both <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code>
are restored to their original values before the function returns.</p>
<p>Note that this manipulation of <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> is not thread-safe. Other threads
may see the partially initialised module, as well as the altered list of
arguments. It is recommended that the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module be left alone when
invoking this function from threaded code.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> option offering equivalent functionality from the
command line.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added ability to execute packages by looking for a <code class="docutils literal notranslate"><span class="pre">__main__</span></code>
submodule</p>
</div>
</dd></dl>

<dl class="function">
<dt id="runpy.run_path">
<code class="descclassname">runpy.</code><code class="descname">run_path</code><span class="sig-paren">(</span><em>file_path</em>, <em>init_globals=None</em>, <em>run_name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#runpy.run_path" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Execute the code at the named filesystem location and return the resulting
module globals dictionary. As with a script name supplied to the CPython
command line, the supplied path may refer to a Python source file, a
compiled bytecode file or a valid sys.path entry containing a <code class="docutils literal notranslate"><span class="pre">__main__</span></code>
module (e.g. a zipfile containing a top-level <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file).</p>
<p>For a simple script, the specified code is simply executed in a fresh
module namespace. For a valid sys.path entry (typically a zipfile or
directory), the entry is first added to the beginning of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>. The
function then looks for and executes a <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module using the
updated path. Note that there is no special protection against invoking
an existing <a class="reference internal" href="__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> entry located elsewhere on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> if
there is no such module at the specified location.</p>
<p>The optional dictionary argument <em>init_globals</em> may be used to pre-populate
the module’s globals dictionary before the code is executed. The supplied
dictionary will not be modified. If any of the special global variables
below are defined in the supplied dictionary, those definitions are
overridden by <a class="reference internal" href="#runpy.run_path" title="runpy.run_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_path()</span></code></a>.</p>
<p>The special global variables <code class="docutils literal notranslate"><span class="pre">__name__</span></code>, <code class="docutils literal notranslate"><span class="pre">__file__</span></code>, <code class="docutils literal notranslate"><span class="pre">__loader__</span></code>
and <code class="docutils literal notranslate"><span class="pre">__package__</span></code> are set in the globals dictionary before the module
code is executed (Note that this is a minimal set of variables - other
variables may be set implicitly as an interpreter implementation detail).</p>
<p><code class="docutils literal notranslate"><span class="pre">__name__</span></code> is set to <em>run_name</em> if this optional argument is not
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and to <code class="docutils literal notranslate"><span class="pre">'&lt;run_path&gt;'</span></code> otherwise.</p>
<p><code class="docutils literal notranslate"><span class="pre">__file__</span></code> is set to the name provided by the module loader. If the
loader does not make filename information available, this variable is set
to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>. For a simple script, this will be set to <code class="docutils literal notranslate"><span class="pre">file_path</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">__loader__</span></code> is set to the <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> module loader used to retrieve the
code for the module (This loader may be a wrapper around the standard
import mechanism). For a simple script, this will be set to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">__package__</span></code> is set to <code class="docutils literal notranslate"><span class="pre">__name__.rpartition('.')[0]</span></code>.</p>
<p>A number of alterations are also made to the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module. Firstly,
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> may be altered as described above. <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is updated
with the value of <code class="docutils literal notranslate"><span class="pre">file_path</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.modules[__name__]</span></code> is updated
with a temporary module object for the module being executed. All
modifications to items in <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> are reverted before the function
returns.</p>
<p>Note that, unlike <a class="reference internal" href="#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_module()</span></code></a>, the alterations made to <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>
are not optional in this function as these adjustments are essential to
allowing the execution of sys.path entries. As the thread-safety
limitations still apply, use of this function in threaded code should be
either serialised with the import lock or delegated to a separate process.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="../using/cmdline.html#using-on-interface-options"><span class="std std-ref">Interface options</span></a> for equivalent functionality on the
command line (<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">path/to/script</span></code>).</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0338"><strong>PEP 338</strong></a> – Executing modules as scripts</dt>
<dd>PEP written and implemented by Nick Coghlan.</dd>
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0366"><strong>PEP 366</strong></a> – Main module explicit relative imports</dt>
<dd>PEP written and implemented by Nick Coghlan.</dd>
</dl>
<p class="last"><a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a> - CPython command line details</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="modulefinder.html"
                        title="previous chapter">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="language.html"
                        title="next chapter">32. Python Language Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/runpy.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="language.html" title="32. Python Language Services"
             >next</a> |</li>
        <li class="right" >
          <a href="modulefinder.html" title="31.6. modulefinder — Find modules used by a script"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\=[�+�M�Mhtml/library/sched.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.8. sched — Event scheduler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.9. mutex — Mutual exclusion support" href="mutex.html" />
    <link rel="prev" title="8.7. sets — Unordered collections of unique elements" href="sets.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sched.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mutex.html" title="8.9. mutex — Mutual exclusion support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sets.html" title="8.7. sets — Unordered collections of unique elements"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sched">
<span id="sched-event-scheduler"></span><h1>8.8. <a class="reference internal" href="#module-sched" title="sched: General purpose event scheduler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sched</span></code></a> — Event scheduler<a class="headerlink" href="#module-sched" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/sched.py">Lib/sched.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-sched" title="sched: General purpose event scheduler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sched</span></code></a> module defines a class which implements a general purpose event
scheduler:</p>
<dl class="class">
<dt id="sched.scheduler">
<em class="property">class </em><code class="descclassname">sched.</code><code class="descname">scheduler</code><span class="sig-paren">(</span><em>timefunc</em>, <em>delayfunc</em><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#sched.scheduler" title="sched.scheduler"><code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code></a> class defines a generic interface to scheduling events.
It needs two functions to actually deal with the “outside world” — <em>timefunc</em>
should be callable without arguments, and return  a number (the “time”, in any
units whatsoever).  The <em>delayfunc</em> function should be callable with one
argument, compatible with the output of <em>timefunc</em>, and should delay that many
time units. <em>delayfunc</em> will also be called with the argument <code class="docutils literal notranslate"><span class="pre">0</span></code> after each
event is run to allow other threads an opportunity to run in multi-threaded
applications.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sched</span><span class="o">,</span> <span class="nn">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">sched</span><span class="o">.</span><span class="n">scheduler</span><span class="p">(</span><span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">print_time</span><span class="p">():</span> <span class="nb">print</span> <span class="s2">&quot;From print_time&quot;</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">print_some_times</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">s</span><span class="o">.</span><span class="n">enter</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">print_time</span><span class="p">,</span> <span class="p">())</span>
<span class="gp">... </span>    <span class="n">s</span><span class="o">.</span><span class="n">enter</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">print_time</span><span class="p">,</span> <span class="p">())</span>
<span class="gp">... </span>    <span class="n">s</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">print_some_times</span><span class="p">()</span>
<span class="go">930343690.257</span>
<span class="go">From print_time 930343695.274</span>
<span class="go">From print_time 930343700.273</span>
<span class="go">930343700.276</span>
</pre></div>
</div>
<p>In multi-threaded environments, the <a class="reference internal" href="#sched.scheduler" title="sched.scheduler"><code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code></a> class has limitations
with respect to thread-safety, inability to insert a new task before
the one currently pending in a running scheduler, and holding up the main
thread until the event queue is empty.  Instead, the preferred approach
is to use the <a class="reference internal" href="threading.html#threading.Timer" title="threading.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Timer</span></code></a> class instead.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">threading</span> <span class="k">import</span> <span class="n">Timer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">print_time</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;From print_time&quot;</span><span class="p">,</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">print_some_times</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">Timer</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="n">print_time</span><span class="p">,</span> <span class="p">())</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">Timer</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">print_time</span><span class="p">,</span> <span class="p">())</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">11</span><span class="p">)</span>  <span class="c1"># sleep while time-delay events execute</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">time</span><span class="o">.</span><span class="n">time</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">print_some_times</span><span class="p">()</span>
<span class="go">930343690.257</span>
<span class="go">From print_time 930343695.274</span>
<span class="go">From print_time 930343700.273</span>
<span class="go">930343701.301</span>
</pre></div>
</div>
<div class="section" id="scheduler-objects">
<span id="id1"></span><h2>8.8.1. Scheduler Objects<a class="headerlink" href="#scheduler-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#sched.scheduler" title="sched.scheduler"><code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code></a> instances have the following methods and attributes:</p>
<dl class="method">
<dt id="sched.scheduler.enterabs">
<code class="descclassname">scheduler.</code><code class="descname">enterabs</code><span class="sig-paren">(</span><em>time</em>, <em>priority</em>, <em>action</em>, <em>argument</em><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler.enterabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule a new event. The <em>time</em> argument should be a numeric type compatible
with the return value of the <em>timefunc</em> function passed  to the constructor.
Events scheduled for the same <em>time</em> will be executed in the order of their
<em>priority</em>. A lower number represents a higher priority.</p>
<p>Executing the event means executing <code class="docutils literal notranslate"><span class="pre">action(*argument)</span></code>.  <em>argument</em> must be a
sequence holding the parameters for <em>action</em>.</p>
<p>Return value is an event which may be used for later cancellation of the event
(see <a class="reference internal" href="#sched.scheduler.cancel" title="sched.scheduler.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="sched.scheduler.enter">
<code class="descclassname">scheduler.</code><code class="descname">enter</code><span class="sig-paren">(</span><em>delay</em>, <em>priority</em>, <em>action</em>, <em>argument</em><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler.enter" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule an event for <em>delay</em> more time units. Other than the relative time, the
other arguments, the effect and the return value are the same as those for
<a class="reference internal" href="#sched.scheduler.enterabs" title="sched.scheduler.enterabs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">enterabs()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="sched.scheduler.cancel">
<code class="descclassname">scheduler.</code><code class="descname">cancel</code><span class="sig-paren">(</span><em>event</em><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the event from the queue. If <em>event</em> is not an event currently in the
queue, this method will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="sched.scheduler.empty">
<code class="descclassname">scheduler.</code><code class="descname">empty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler.empty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the event queue is empty.</p>
</dd></dl>

<dl class="method">
<dt id="sched.scheduler.run">
<code class="descclassname">scheduler.</code><code class="descname">run</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sched.scheduler.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Run all scheduled events. This function will wait  (using the <code class="xref py py-func docutils literal notranslate"><span class="pre">delayfunc()</span></code>
function passed to the constructor) for the next event, then execute it and so
on until there are no more scheduled events.</p>
<p>Either <em>action</em> or <em>delayfunc</em> can raise an exception.  In either case, the
scheduler will maintain a consistent state and propagate the exception.  If an
exception is raised by <em>action</em>, the event will not be attempted in future calls
to <a class="reference internal" href="#sched.scheduler.run" title="sched.scheduler.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>.</p>
<p>If a sequence of events takes longer to run than the time available before the
next event, the scheduler will simply fall behind.  No events will be dropped;
the calling code is responsible for canceling  events which are no longer
pertinent.</p>
</dd></dl>

<dl class="attribute">
<dt id="sched.scheduler.queue">
<code class="descclassname">scheduler.</code><code class="descname">queue</code><a class="headerlink" href="#sched.scheduler.queue" title="Permalink to this definition">¶</a></dt>
<dd><p>Read-only attribute returning a list of upcoming events in the order they
will be run.  Each event is shown as a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> with the
following fields:  time, priority, action, argument.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a><ul>
<li><a class="reference internal" href="#scheduler-objects">8.8.1. Scheduler Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sets.html"
                        title="previous chapter">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mutex.html"
                        title="next chapter">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sched.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mutex.html" title="8.9. mutex — Mutual exclusion support"
             >next</a> |</li>
        <li class="right" >
          <a href="sets.html" title="8.7. sets — Unordered collections of unique elements"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ƭ��&&html/library/scrolledtext.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.4. ScrolledText — Scrolled Text Widget &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.5. turtle — Turtle graphics for Tk" href="turtle.html" />
    <link rel="prev" title="24.3. Tix — Extension widgets for Tk" href="tix.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/scrolledtext.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="turtle.html" title="24.5. turtle — Turtle graphics for Tk"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tix.html" title="24.3. Tix — Extension widgets for Tk"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ScrolledText">
<span id="scrolledtext-scrolled-text-widget"></span><h1>24.4. <a class="reference internal" href="#module-ScrolledText" title="ScrolledText: Text widget with a vertical scroll bar. (Tk)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ScrolledText</span></code></a> — Scrolled Text Widget<a class="headerlink" href="#module-ScrolledText" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-ScrolledText" title="ScrolledText: Text widget with a vertical scroll bar. (Tk)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ScrolledText</span></code></a> module provides a class of the same name which
implements a basic text widget which has a vertical scroll bar configured to do
the “right thing.”  Using the <code class="xref py py-class docutils literal notranslate"><span class="pre">ScrolledText</span></code> class is a lot easier than
setting up a text widget and scroll bar directly.  The constructor is the same
as that of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Text</span></code> class.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#module-ScrolledText" title="ScrolledText: Text widget with a vertical scroll bar. (Tk)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ScrolledText</span></code></a> has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter.scrolledtext</span></code> in Python
3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<p>The text widget and scrollbar are packed together in a <code class="xref py py-class docutils literal notranslate"><span class="pre">Frame</span></code>, and the
methods of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Grid</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Pack</span></code> geometry managers are acquired
from the <code class="xref py py-class docutils literal notranslate"><span class="pre">Frame</span></code> object.  This allows the <code class="xref py py-class docutils literal notranslate"><span class="pre">ScrolledText</span></code> widget to
be used directly to achieve most normal geometry management behavior.</p>
<p>Should more specific control be necessary, the following attributes are
available:</p>
<dl class="attribute">
<dt id="ScrolledText.ScrolledText.frame">
<code class="descclassname">ScrolledText.</code><code class="descname">frame</code><a class="headerlink" href="#ScrolledText.ScrolledText.frame" title="Permalink to this definition">¶</a></dt>
<dd><p>The frame which surrounds the text and scroll bar widgets.</p>
</dd></dl>

<dl class="attribute">
<dt id="ScrolledText.ScrolledText.vbar">
<code class="descclassname">ScrolledText.</code><code class="descname">vbar</code><a class="headerlink" href="#ScrolledText.ScrolledText.vbar" title="Permalink to this definition">¶</a></dt>
<dd><p>The scroll bar widget.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tix.html"
                        title="previous chapter">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="turtle.html"
                        title="next chapter">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/scrolledtext.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="turtle.html" title="24.5. turtle — Turtle graphics for Tk"
             >next</a> |</li>
        <li class="right" >
          <a href="tix.html" title="24.3. Tix — Extension widgets for Tk"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����:�:�html/library/select.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.1. select — Waiting for I/O completion &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.2. threading — Higher-level threading interface" href="threading.html" />
    <link rel="prev" title="16. Optional Operating System Services" href="someos.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/select.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="threading.html" title="16.2. threading — Higher-level threading interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-select">
<span id="select-waiting-for-i-o-completion"></span><h1>16.1. <a class="reference internal" href="#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> — Waiting for I/O completion<a class="headerlink" href="#module-select" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to the <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code> functions
available in most operating systems, <code class="xref c c-func docutils literal notranslate"><span class="pre">epoll()</span></code> available on Linux 2.5+ and
<code class="xref c c-func docutils literal notranslate"><span class="pre">kqueue()</span></code> available on most BSD.
Note that on Windows, it only works for sockets; on other operating systems,
it also works for other file types (in particular, on Unix, it works on pipes).
It cannot be used on regular files to determine whether a file has grown since
it was last read.</p>
<p>The module defines the following:</p>
<dl class="exception">
<dt id="select.error">
<em class="property">exception </em><code class="descclassname">select.</code><code class="descname">error</code><a class="headerlink" href="#select.error" title="Permalink to this definition">¶</a></dt>
<dd><p>The exception raised when an error occurs.  The accompanying value is a pair
containing the numeric error code from <code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> and the corresponding
string, as would be printed by the C function <code class="xref c c-func docutils literal notranslate"><span class="pre">perror()</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="select.epoll">
<code class="descclassname">select.</code><code class="descname">epoll</code><span class="sig-paren">(</span><span class="optional">[</span><em>sizehint=-1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll" title="Permalink to this definition">¶</a></dt>
<dd><p>(Only supported on Linux 2.5.44 and newer.)  Returns an edge polling object,
which can be used as Edge or Level Triggered interface for I/O events; see
section <a class="reference internal" href="#epoll-objects"><span class="std std-ref">Edge and Level Trigger Polling (epoll) Objects</span></a> below for the methods supported by epolling
objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="select.poll">
<code class="descclassname">select.</code><code class="descname">poll</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>(Not supported by all operating systems.)  Returns a polling object, which
supports registering and unregistering file descriptors, and then polling them
for I/O events; see section <a class="reference internal" href="#poll-objects"><span class="std std-ref">Polling Objects</span></a> below for the methods supported
by polling objects.</p>
</dd></dl>

<dl class="function">
<dt id="select.kqueue">
<code class="descclassname">select.</code><code class="descname">kqueue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.kqueue" title="Permalink to this definition">¶</a></dt>
<dd><p>(Only supported on BSD.)  Returns a kernel queue object; see section
<a class="reference internal" href="#kqueue-objects"><span class="std std-ref">Kqueue Objects</span></a> below for the methods supported by kqueue objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="select.kevent">
<code class="descclassname">select.</code><code class="descname">kevent</code><span class="sig-paren">(</span><em>ident</em>, <em>filter=KQ_FILTER_READ</em>, <em>flags=KQ_EV_ADD</em>, <em>fflags=0</em>, <em>data=0</em>, <em>udata=0</em><span class="sig-paren">)</span><a class="headerlink" href="#select.kevent" title="Permalink to this definition">¶</a></dt>
<dd><p>(Only supported on BSD.)  Returns a kernel event object; see section
<a class="reference internal" href="#kevent-objects"><span class="std std-ref">Kevent Objects</span></a> below for the methods supported by kevent objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="select.select">
<code class="descclassname">select.</code><code class="descname">select</code><span class="sig-paren">(</span><em>rlist</em>, <em>wlist</em>, <em>xlist</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.select" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a straightforward interface to the Unix <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> system call.
The first three arguments are sequences of ‘waitable objects’: either
integers representing file descriptors or objects with a parameterless method
named <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> returning such an integer:</p>
<ul class="simple">
<li><em>rlist</em>: wait until ready for reading</li>
<li><em>wlist</em>: wait until ready for writing</li>
<li><em>xlist</em>: wait for an “exceptional condition” (see the manual page for what
your system considers such a condition)</li>
</ul>
<p>Empty sequences are allowed, but acceptance of three empty sequences is
platform-dependent. (It is known to work on Unix but not on Windows.)  The
optional <em>timeout</em> argument specifies a time-out as a floating point number
in seconds.  When the <em>timeout</em> argument is omitted the function blocks until
at least one file descriptor is ready.  A time-out value of zero specifies a
poll and never blocks.</p>
<p>The return value is a triple of lists of objects that are ready: subsets of the
first three arguments.  When the time-out is reached without a file descriptor
becoming ready, three empty lists are returned.</p>
<p id="index-0">Among the acceptable object types in the sequences are Python file objects (e.g.
<code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, or objects returned by <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> or <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>), socket
objects returned by <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.socket()</span></code></a>.  You may also define a <em class="dfn">wrapper</em>
class yourself, as long as it has an appropriate <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a>
method (that really returns a file descriptor, not just a random integer).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last" id="index-1">File objects on Windows are not acceptable, but sockets are.  On Windows,
the underlying <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> function is provided by the WinSock
library, and does not handle file descriptors that don’t originate from
WinSock.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="select.select.PIPE_BUF">
<code class="descclassname">select.</code><code class="descname">PIPE_BUF</code><a class="headerlink" href="#select.select.PIPE_BUF" title="Permalink to this definition">¶</a></dt>
<dd><p>Files reported as ready for writing by <a class="reference internal" href="#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a>, <a class="reference internal" href="#select.poll" title="select.poll"><code class="xref py py-func docutils literal notranslate"><span class="pre">poll()</span></code></a> or
similar interfaces in this module are guaranteed to not block on a write
of up to <a class="reference internal" href="#select.select.PIPE_BUF" title="select.select.PIPE_BUF"><code class="xref py py-const docutils literal notranslate"><span class="pre">PIPE_BUF</span></code></a> bytes.
This value is guaranteed by POSIX to be at least 512.  Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<div class="section" id="edge-and-level-trigger-polling-epoll-objects">
<span id="epoll-objects"></span><h2>16.1.1. Edge and Level Trigger Polling (epoll) Objects<a class="headerlink" href="#edge-and-level-trigger-polling-epoll-objects" title="Permalink to this headline">¶</a></h2>
<blockquote>
<div><p><a class="reference external" href="http://linux.die.net/man/4/epoll">http://linux.die.net/man/4/epoll</a></p>
<p><em>eventmask</em></p>
<table border="1" class="docutils">
<colgroup>
<col width="33%" />
<col width="67%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLIN</span></code></td>
<td>Available for read</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLOUT</span></code></td>
<td>Available for write</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLPRI</span></code></td>
<td>Urgent data for read</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLERR</span></code></td>
<td>Error condition happened on the assoc. fd</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLHUP</span></code></td>
<td>Hang up happened on the assoc. fd</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLET</span></code></td>
<td>Set Edge Trigger behavior, the default is
Level Trigger behavior</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLONESHOT</span></code></td>
<td>Set one-shot behavior. After one event is
pulled out, the fd is internally disabled</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLRDNORM</span></code></td>
<td>Equivalent to <code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLIN</span></code></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLRDBAND</span></code></td>
<td>Priority data band can be read.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLWRNORM</span></code></td>
<td>Equivalent to <code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLOUT</span></code></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLWRBAND</span></code></td>
<td>Priority data may be written.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">EPOLLMSG</span></code></td>
<td>Ignored.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<dl class="method">
<dt id="select.epoll.close">
<code class="descclassname">epoll.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the control file descriptor of the epoll object.</p>
</dd></dl>

<dl class="method">
<dt id="select.epoll.fileno">
<code class="descclassname">epoll.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor number of the control fd.</p>
</dd></dl>

<dl class="method">
<dt id="select.epoll.fromfd">
<code class="descclassname">epoll.</code><code class="descname">fromfd</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.fromfd" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an epoll object from a given file descriptor.</p>
</dd></dl>

<dl class="method">
<dt id="select.epoll.register">
<code class="descclassname">epoll.</code><code class="descname">register</code><span class="sig-paren">(</span><em>fd</em><span class="optional">[</span>, <em>eventmask</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a fd descriptor with the epoll object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Registering a file descriptor that’s already registered raises an
IOError – contrary to <a class="reference internal" href="#poll-objects"><span class="std std-ref">Polling Objects</span></a>’s register.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="select.epoll.modify">
<code class="descclassname">epoll.</code><code class="descname">modify</code><span class="sig-paren">(</span><em>fd</em>, <em>eventmask</em><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.modify" title="Permalink to this definition">¶</a></dt>
<dd><p>Modify a register file descriptor.</p>
</dd></dl>

<dl class="method">
<dt id="select.epoll.unregister">
<code class="descclassname">epoll.</code><code class="descname">unregister</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.unregister" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove a registered file descriptor from the epoll object.</p>
</dd></dl>

<dl class="method">
<dt id="select.epoll.poll">
<code class="descclassname">epoll.</code><code class="descname">poll</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout=-1</em><span class="optional">[</span>, <em>maxevents=-1</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.epoll.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for events. timeout in seconds (float)</p>
</dd></dl>

</div>
<div class="section" id="polling-objects">
<span id="poll-objects"></span><h2>16.1.2. Polling Objects<a class="headerlink" href="#polling-objects" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code> system call, supported on most Unix systems, provides better
scalability for network servers that service many, many clients at the same
time. <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code> scales better because the system call only requires listing
the file descriptors of interest, while <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> builds a bitmap, turns
on bits for the fds of interest, and then afterward the whole bitmap has to be
linearly scanned again. <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> is O(highest file descriptor), while
<code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code> is O(number of file descriptors).</p>
<dl class="method">
<dt id="select.poll.register">
<code class="descclassname">poll.</code><code class="descname">register</code><span class="sig-paren">(</span><em>fd</em><span class="optional">[</span>, <em>eventmask</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.poll.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a file descriptor with the polling object.  Future calls to the
<a class="reference internal" href="#select.poll" title="select.poll"><code class="xref py py-meth docutils literal notranslate"><span class="pre">poll()</span></code></a> method will then check whether the file descriptor has any
pending I/O events.  <em>fd</em> can be either an integer, or an object with a
<a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method that returns an integer.  File objects
implement <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code>, so they can also be used as the argument.</p>
<p><em>eventmask</em> is an optional bitmask describing the type of events you want to
check for, and can be a combination of the constants <code class="xref py py-const docutils literal notranslate"><span class="pre">POLLIN</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">POLLPRI</span></code>, and <code class="xref py py-const docutils literal notranslate"><span class="pre">POLLOUT</span></code>, described in the table below.  If not
specified, the default value used will check for all 3 types of events.</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLIN</span></code></td>
<td>There is data to read</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLPRI</span></code></td>
<td>There is urgent data to read</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLOUT</span></code></td>
<td>Ready for output: writing will not block</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLERR</span></code></td>
<td>Error condition of some sort</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLHUP</span></code></td>
<td>Hung up</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">POLLNVAL</span></code></td>
<td>Invalid request: descriptor not open</td>
</tr>
</tbody>
</table>
<p>Registering a file descriptor that’s already registered is not an error, and has
the same effect as registering the descriptor exactly once.</p>
</dd></dl>

<dl class="method">
<dt id="select.poll.modify">
<code class="descclassname">poll.</code><code class="descname">modify</code><span class="sig-paren">(</span><em>fd</em>, <em>eventmask</em><span class="sig-paren">)</span><a class="headerlink" href="#select.poll.modify" title="Permalink to this definition">¶</a></dt>
<dd><p>Modifies an already registered fd. This has the same effect as
<code class="docutils literal notranslate"><span class="pre">register(fd,</span> <span class="pre">eventmask)</span></code>.  Attempting to modify a file descriptor
that was never registered causes an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception with errno
<code class="xref py py-const docutils literal notranslate"><span class="pre">ENOENT</span></code> to be raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="select.poll.unregister">
<code class="descclassname">poll.</code><code class="descname">unregister</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#select.poll.unregister" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove a file descriptor being tracked by a polling object.  Just like the
<a class="reference internal" href="#select.poll.register" title="select.poll.register"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code></a> method, <em>fd</em> can be an integer or an object with a
<a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method that returns an integer.</p>
<p>Attempting to remove a file descriptor that was never registered causes a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception to be raised.</p>
</dd></dl>

<dl class="method">
<dt id="select.poll.poll">
<code class="descclassname">poll.</code><code class="descname">poll</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#select.poll.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>Polls the set of registered file descriptors, and returns a possibly-empty list
containing <code class="docutils literal notranslate"><span class="pre">(fd,</span> <span class="pre">event)</span></code> 2-tuples for the descriptors that have events or
errors to report. <em>fd</em> is the file descriptor, and <em>event</em> is a bitmask with
bits set for the reported events for that descriptor — <code class="xref py py-const docutils literal notranslate"><span class="pre">POLLIN</span></code> for
waiting input, <code class="xref py py-const docutils literal notranslate"><span class="pre">POLLOUT</span></code> to indicate that the descriptor can be written
to, and so forth. An empty list indicates that the call timed out and no file
descriptors had any events to report. If <em>timeout</em> is given, it specifies the
length of time in milliseconds which the system will wait for events before
returning. If <em>timeout</em> is omitted, negative, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the call will
block until there is an event for this poll object.</p>
</dd></dl>

</div>
<div class="section" id="kqueue-objects">
<span id="id1"></span><h2>16.1.3. Kqueue Objects<a class="headerlink" href="#kqueue-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="select.kqueue.close">
<code class="descclassname">kqueue.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.kqueue.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the control file descriptor of the kqueue object.</p>
</dd></dl>

<dl class="method">
<dt id="select.kqueue.fileno">
<code class="descclassname">kqueue.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#select.kqueue.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor number of the control fd.</p>
</dd></dl>

<dl class="method">
<dt id="select.kqueue.fromfd">
<code class="descclassname">kqueue.</code><code class="descname">fromfd</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#select.kqueue.fromfd" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a kqueue object from a given file descriptor.</p>
</dd></dl>

<dl class="method">
<dt id="select.kqueue.control">
<code class="descclassname">kqueue.</code><code class="descname">control</code><span class="sig-paren">(</span><em>changelist</em>, <em>max_events</em><span class="optional">[</span>, <em>timeout=None</em><span class="optional">]</span><span class="sig-paren">)</span> &#x2192; eventlist<a class="headerlink" href="#select.kqueue.control" title="Permalink to this definition">¶</a></dt>
<dd><p>Low level interface to kevent</p>
<ul class="simple">
<li>changelist must be an iterable of kevent object or <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li>max_events must be 0 or a positive integer</li>
<li>timeout in seconds (floats possible)</li>
</ul>
</dd></dl>

</div>
<div class="section" id="kevent-objects">
<span id="id2"></span><h2>16.1.4. Kevent Objects<a class="headerlink" href="#kevent-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="https://www.freebsd.org/cgi/man.cgi?query=kqueue&amp;sektion=2">https://www.freebsd.org/cgi/man.cgi?query=kqueue&amp;sektion=2</a></p>
<dl class="attribute">
<dt id="select.kevent.ident">
<code class="descclassname">kevent.</code><code class="descname">ident</code><a class="headerlink" href="#select.kevent.ident" title="Permalink to this definition">¶</a></dt>
<dd><p>Value used to identify the event. The interpretation depends on the filter
but it’s usually the file descriptor. In the constructor ident can either
be an int or an object with a fileno() function. kevent stores the integer
internally.</p>
</dd></dl>

<dl class="attribute">
<dt id="select.kevent.filter">
<code class="descclassname">kevent.</code><code class="descname">filter</code><a class="headerlink" href="#select.kevent.filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the kernel filter.</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_READ</span></code></td>
<td>Takes a descriptor and returns whenever
there is data available to read</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_WRITE</span></code></td>
<td>Takes a descriptor and returns whenever
there is data available to write</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_AIO</span></code></td>
<td>AIO requests</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_VNODE</span></code></td>
<td>Returns when one or more of the requested
events watched in <em>fflag</em> occurs</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_PROC</span></code></td>
<td>Watch for events on a process id</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_NETDEV</span></code></td>
<td>Watch for events on a network device
[not available on Mac OS X]</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_SIGNAL</span></code></td>
<td>Returns whenever the watched signal is
delivered to the process</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_TIMER</span></code></td>
<td>Establishes an arbitrary timer</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="attribute">
<dt id="select.kevent.flags">
<code class="descclassname">kevent.</code><code class="descname">flags</code><a class="headerlink" href="#select.kevent.flags" title="Permalink to this definition">¶</a></dt>
<dd><p>Filter action.</p>
<table border="1" class="docutils">
<colgroup>
<col width="38%" />
<col width="63%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_ADD</span></code></td>
<td>Adds or modifies an event</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_DELETE</span></code></td>
<td>Removes an event from the queue</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_ENABLE</span></code></td>
<td>Permitscontrol() to returns the event</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_DISABLE</span></code></td>
<td>Disablesevent</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_ONESHOT</span></code></td>
<td>Removes event after first occurrence</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_CLEAR</span></code></td>
<td>Reset the state after an event is retrieved</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_SYSFLAGS</span></code></td>
<td>internal event</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_FLAG1</span></code></td>
<td>internal event</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_EOF</span></code></td>
<td>Filter specific EOF condition</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_EV_ERROR</span></code></td>
<td>See return values</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="attribute">
<dt id="select.kevent.fflags">
<code class="descclassname">kevent.</code><code class="descname">fflags</code><a class="headerlink" href="#select.kevent.fflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Filter specific flags.</p>
<p><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_READ</span></code> and  <code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_WRITE</span></code> filter flags:</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_LOWAT</span></code></td>
<td>low water mark of a socket buffer</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_VNODE</span></code> filter flags:</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_DELETE</span></code></td>
<td><em>unlink()</em> was called</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_WRITE</span></code></td>
<td>a write occurred</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_EXTEND</span></code></td>
<td>the file was extended</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_ATTRIB</span></code></td>
<td>an attribute was changed</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_LINK</span></code></td>
<td>the link count has changed</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_RENAME</span></code></td>
<td>the file was renamed</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_REVOKE</span></code></td>
<td>access to the file was revoked</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_PROC</span></code> filter flags:</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_EXIT</span></code></td>
<td>the process has exited</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_FORK</span></code></td>
<td>the process has called <em>fork()</em></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_EXEC</span></code></td>
<td>the process has executed a new process</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_PCTRLMASK</span></code></td>
<td>internal filter flag</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_PDATAMASK</span></code></td>
<td>internal filter flag</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_TRACK</span></code></td>
<td>follow a process across <em>fork()</em></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_CHILD</span></code></td>
<td>returned on the child process for
<em>NOTE_TRACK</em></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_TRACKERR</span></code></td>
<td>unable to attach to a child</td>
</tr>
</tbody>
</table>
<p><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_FILTER_NETDEV</span></code> filter flags (not available on Mac OS X):</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_LINKUP</span></code></td>
<td>link is up</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_LINKDOWN</span></code></td>
<td>link is down</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">KQ_NOTE_LINKINV</span></code></td>
<td>link state is invalid</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="attribute">
<dt id="select.kevent.data">
<code class="descclassname">kevent.</code><code class="descname">data</code><a class="headerlink" href="#select.kevent.data" title="Permalink to this definition">¶</a></dt>
<dd><p>Filter specific data.</p>
</dd></dl>

<dl class="attribute">
<dt id="select.kevent.udata">
<code class="descclassname">kevent.</code><code class="descname">udata</code><a class="headerlink" href="#select.kevent.udata" title="Permalink to this definition">¶</a></dt>
<dd><p>User defined value.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a><ul>
<li><a class="reference internal" href="#edge-and-level-trigger-polling-epoll-objects">16.1.1. Edge and Level Trigger Polling (epoll) Objects</a></li>
<li><a class="reference internal" href="#polling-objects">16.1.2. Polling Objects</a></li>
<li><a class="reference internal" href="#kqueue-objects">16.1.3. Kqueue Objects</a></li>
<li><a class="reference internal" href="#kevent-objects">16.1.4. Kevent Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="someos.html"
                        title="previous chapter">16. Optional Operating System Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="threading.html"
                        title="next chapter">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/select.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="threading.html" title="16.2. threading — Higher-level threading interface"
             >next</a> |</li>
        <li class="right" >
          <a href="someos.html" title="16. Optional Operating System Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\!XO�ללhtml/library/sets.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.7. sets — Unordered collections of unique elements &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.8. sched — Event scheduler" href="sched.html" />
    <link rel="prev" title="8.6. array — Efficient arrays of numeric values" href="array.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sets.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sched.html" title="8.8. sched — Event scheduler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="array.html" title="8.6. array — Efficient arrays of numeric values"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sets">
<span id="sets-unordered-collections-of-unique-elements"></span><h1>8.7. <a class="reference internal" href="#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> — Unordered collections of unique elements<a class="headerlink" href="#module-sets" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The built-in <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>/<a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types replace this module.</p>
</div>
<p>The <a class="reference internal" href="#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module provides classes for constructing and manipulating
unordered collections of unique elements.  Common uses include membership
testing, removing duplicates from a sequence, and computing standard math
operations on sets such as intersection, union, difference, and symmetric
difference.</p>
<p>Like other collections, sets support <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">len(set)</span></code>, and <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span>
<span class="pre">set</span></code>.  Being an unordered collection, sets do not record element position or
order of insertion.  Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.</p>
<p>Most set applications use the <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> class which provides every set method
except for <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>. For advanced applications requiring a hash method,
the <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> class adds a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method but omits methods
which alter the contents of the set. Both <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a>
derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseSet</span></code>, an abstract class useful for determining whether
something is a set: <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">BaseSet)</span></code>.</p>
<p>The set classes are implemented using dictionaries.  Accordingly, the
requirements for set elements are the same as those for dictionary keys; namely,
that the element defines both <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>. As a result,
sets cannot contain mutable elements such as lists or dictionaries. However,
they can contain immutable collections such as tuples or instances of
<a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a>.  For convenience in implementing sets of sets, inner sets
are automatically converted to immutable form, for example,
<code class="docutils literal notranslate"><span class="pre">Set([Set(['dog'])])</span></code> is transformed to <code class="docutils literal notranslate"><span class="pre">Set([ImmutableSet(['dog'])])</span></code>.</p>
<dl class="class">
<dt id="sets.Set">
<em class="property">class </em><code class="descclassname">sets.</code><code class="descname">Set</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sets.Set" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructs a new empty <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> object.  If the optional <em>iterable</em>
parameter is supplied, updates the set with elements obtained from iteration.
All of the elements in <em>iterable</em> should be immutable or be transformable to an
immutable using the protocol described in section <a class="reference internal" href="#immutable-transforms"><span class="std std-ref">Protocol for automatic conversion to immutable</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="sets.ImmutableSet">
<em class="property">class </em><code class="descclassname">sets.</code><code class="descname">ImmutableSet</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sets.ImmutableSet" title="Permalink to this definition">¶</a></dt>
<dd><p>Constructs a new empty <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> object.  If the optional <em>iterable</em>
parameter is supplied, updates the set with elements obtained from iteration.
All of the elements in <em>iterable</em> should be immutable or be transformable to an
immutable using the protocol described in section <a class="reference internal" href="#immutable-transforms"><span class="std std-ref">Protocol for automatic conversion to immutable</span></a>.</p>
<p>Because <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> objects provide a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method, they
can be used as set elements or as dictionary keys.  <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a>
objects do not have methods for adding or removing elements, so all of the
elements must be known when the constructor is called.</p>
</dd></dl>

<div class="section" id="set-objects">
<span id="id1"></span><h2>8.7.1. Set Objects<a class="headerlink" href="#set-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> both provide the following
operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="16%" />
<col width="43%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Equivalent</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">len(s)</span></code></td>
<td>&#160;</td>
<td>number of elements in set <em>s</em>
(cardinality)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code></td>
<td>&#160;</td>
<td>test <em>x</em> for membership in <em>s</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code></td>
<td>&#160;</td>
<td>test <em>x</em> for non-membership in
<em>s</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.issubset(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">&lt;=</span> <span class="pre">t</span></code></td>
<td>test whether every element in
<em>s</em> is in <em>t</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.issuperset(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">&gt;=</span> <span class="pre">t</span></code></td>
<td>test whether every element in
<em>t</em> is in <em>s</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.union(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">|</span> <span class="pre">t</span></code></td>
<td>new set with elements from both
<em>s</em> and <em>t</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.intersection(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">&amp;</span> <span class="pre">t</span></code></td>
<td>new set with elements common to
<em>s</em> and <em>t</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.difference(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">-</span> <span class="pre">t</span></code></td>
<td>new set with elements in <em>s</em>
but not in <em>t</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.symmetric_difference(t)</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">^</span> <span class="pre">t</span></code></td>
<td>new set with elements in either
<em>s</em> or <em>t</em> but not both</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.copy()</span></code></td>
<td>&#160;</td>
<td>new set with a shallow copy of
<em>s</em></td>
</tr>
</tbody>
</table>
<p>Note, the non-operator versions of <code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference()</span></code> will accept any iterable as
an argument. In contrast, their operator based counterparts require their
arguments to be sets.  This precludes error-prone constructions like
<code class="docutils literal notranslate"><span class="pre">Set('abc')</span> <span class="pre">&amp;</span> <span class="pre">'cbs'</span></code> in favor of the more readable
<code class="docutils literal notranslate"><span class="pre">Set('abc').intersection('cbs')</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3.1: </span>Formerly all arguments were required to be sets.</p>
</div>
<p>In addition, both <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> support set to set
comparisons.  Two sets are equal if and only if every element of each set is
contained in the other (each is a subset of the other). A set is less than
another set if and only if the first set is a proper subset of the second set
(is a subset, but is not equal). A set is greater than another set if and only
if the first set is a proper superset of the second set (is a superset, but is
not equal).</p>
<p>The subset and equality comparisons do not generalize to a complete ordering
function.  For example, any two disjoint sets are not equal and are not subsets
of each other, so <em>all</em> of the following return <code class="docutils literal notranslate"><span class="pre">False</span></code>:  <code class="docutils literal notranslate"><span class="pre">a&lt;b</span></code>, <code class="docutils literal notranslate"><span class="pre">a==b</span></code>,
or <code class="docutils literal notranslate"><span class="pre">a&gt;b</span></code>. Accordingly, sets do not implement the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method.</p>
<p>Since sets only define partial ordering (subset relationships), the output of
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method is undefined for lists of sets.</p>
<p>The following table lists operations available in <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> but not
found in <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">hash(s)</span></code></td>
<td>returns a hash value for <em>s</em></td>
</tr>
</tbody>
</table>
<p>The following table lists operations available in <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> but not found in
<a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a>:</p>
<table border="1" class="docutils">
<colgroup>
<col width="45%" />
<col width="15%" />
<col width="39%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Equivalent</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.update(t)</span></code></td>
<td><em>s</em> |= <em>t</em></td>
<td>return set <em>s</em> with elements
added from <em>t</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.intersection_update(t)</span></code></td>
<td><em>s</em> &amp;= <em>t</em></td>
<td>return set <em>s</em> keeping only
elements also found in <em>t</em></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.difference_update(t)</span></code></td>
<td><em>s</em> -= <em>t</em></td>
<td>return set <em>s</em> after removing
elements found in <em>t</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.symmetric_difference_update(t)</span></code></td>
<td><em>s</em> ^= <em>t</em></td>
<td>return set <em>s</em> with elements
from <em>s</em> or <em>t</em> but not both</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.add(x)</span></code></td>
<td>&#160;</td>
<td>add element <em>x</em> to set <em>s</em></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.remove(x)</span></code></td>
<td>&#160;</td>
<td>remove <em>x</em> from set <em>s</em>; raises
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if not present</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.discard(x)</span></code></td>
<td>&#160;</td>
<td>removes <em>x</em> from set <em>s</em> if
present</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.pop()</span></code></td>
<td>&#160;</td>
<td>remove and return an arbitrary
element from <em>s</em>; raises
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if empty</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.clear()</span></code></td>
<td>&#160;</td>
<td>remove all elements from set
<em>s</em></td>
</tr>
</tbody>
</table>
<p>Note, the non-operator versions of <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference_update()</span></code> will accept
any iterable as an argument.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3.1: </span>Formerly all arguments were required to be sets.</p>
</div>
<p>Also note, the module also includes a <code class="xref py py-meth docutils literal notranslate"><span class="pre">union_update()</span></code> method which is an
alias for <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>.  The method is included for backwards compatibility.
Programmers should prefer the <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method because it is supported by
the built-in <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set()</span></code></a> and <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset()</span></code></a> types.</p>
</div>
<div class="section" id="example">
<span id="set-example"></span><h2>8.7.2. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sets</span> <span class="k">import</span> <span class="n">Set</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">engineers</span> <span class="o">=</span> <span class="n">Set</span><span class="p">([</span><span class="s1">&#39;John&#39;</span><span class="p">,</span> <span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">,</span> <span class="s1">&#39;Janice&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">programmers</span> <span class="o">=</span> <span class="n">Set</span><span class="p">([</span><span class="s1">&#39;Jack&#39;</span><span class="p">,</span> <span class="s1">&#39;Sam&#39;</span><span class="p">,</span> <span class="s1">&#39;Susan&#39;</span><span class="p">,</span> <span class="s1">&#39;Janice&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">managers</span> <span class="o">=</span> <span class="n">Set</span><span class="p">([</span><span class="s1">&#39;Jane&#39;</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">,</span> <span class="s1">&#39;Susan&#39;</span><span class="p">,</span> <span class="s1">&#39;Zack&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">employees</span> <span class="o">=</span> <span class="n">engineers</span> <span class="o">|</span> <span class="n">programmers</span> <span class="o">|</span> <span class="n">managers</span>           <span class="c1"># union</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">engineering_management</span> <span class="o">=</span> <span class="n">engineers</span> <span class="o">&amp;</span> <span class="n">managers</span>            <span class="c1"># intersection</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fulltime_management</span> <span class="o">=</span> <span class="n">managers</span> <span class="o">-</span> <span class="n">engineers</span> <span class="o">-</span> <span class="n">programmers</span> <span class="c1"># difference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">engineers</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;Marvin&#39;</span><span class="p">)</span>                                  <span class="c1"># add element</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">engineers</span> 
<span class="go">Set([&#39;Jane&#39;, &#39;Marvin&#39;, &#39;Janice&#39;, &#39;John&#39;, &#39;Jack&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">employees</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">engineers</span><span class="p">)</span>     <span class="c1"># superset test</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">employees</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="n">engineers</span><span class="p">)</span>         <span class="c1"># update from another set</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">employees</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">engineers</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">group</span> <span class="ow">in</span> <span class="p">[</span><span class="n">engineers</span><span class="p">,</span> <span class="n">programmers</span><span class="p">,</span> <span class="n">managers</span><span class="p">,</span> <span class="n">employees</span><span class="p">]:</span> 
<span class="gp">... </span>    <span class="n">group</span><span class="o">.</span><span class="n">discard</span><span class="p">(</span><span class="s1">&#39;Susan&#39;</span><span class="p">)</span>          <span class="c1"># unconditionally remove element</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">group</span>
<span class="gp">...</span>
<span class="go">Set([&#39;Jane&#39;, &#39;Marvin&#39;, &#39;Janice&#39;, &#39;John&#39;, &#39;Jack&#39;])</span>
<span class="go">Set([&#39;Janice&#39;, &#39;Jack&#39;, &#39;Sam&#39;])</span>
<span class="go">Set([&#39;Jane&#39;, &#39;Zack&#39;, &#39;Jack&#39;])</span>
<span class="go">Set([&#39;Jack&#39;, &#39;Sam&#39;, &#39;Jane&#39;, &#39;Marvin&#39;, &#39;Janice&#39;, &#39;John&#39;, &#39;Zack&#39;])</span>
</pre></div>
</div>
</div>
<div class="section" id="protocol-for-automatic-conversion-to-immutable">
<span id="immutable-transforms"></span><h2>8.7.3. Protocol for automatic conversion to immutable<a class="headerlink" href="#protocol-for-automatic-conversion-to-immutable" title="Permalink to this headline">¶</a></h2>
<p>Sets can only contain immutable elements.  For convenience, mutable <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a>
objects are automatically copied to an <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> before being added
as a set element.</p>
<p>The mechanism is to always add a <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> element, or if it is not
hashable, the element is checked to see if it has an <code class="xref py py-meth docutils literal notranslate"><span class="pre">__as_immutable__()</span></code>
method which returns an immutable equivalent.</p>
<p>Since <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> objects have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__as_immutable__()</span></code> method returning an
instance of <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a>, it is possible to construct sets of sets.</p>
<p>A similar mechanism is needed by the <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code>
methods which need to hash an element to check for membership in a set.  Those
methods check an element for hashability and, if not, check for a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__as_temporarily_immutable__()</span></code> method which returns the element wrapped by
a class that provides temporary methods for <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a>,
and <a class="reference internal" href="../reference/datamodel.html#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a>.</p>
<p>The alternate mechanism spares the need to build a separate copy of the original
mutable object.</p>
<p><a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> objects implement the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__as_temporarily_immutable__()</span></code> method
which returns the <a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> object wrapped by a new class
<code class="xref py py-class docutils literal notranslate"><span class="pre">_TemporarilyImmutableSet</span></code>.</p>
<p>The two mechanisms for adding hashability are normally invisible to the user;
however, a conflict can arise in a multi-threaded environment where one thread
is updating a set while another has temporarily wrapped it in
<code class="xref py py-class docutils literal notranslate"><span class="pre">_TemporarilyImmutableSet</span></code>.  In other words, sets of mutable sets are not
thread-safe.</p>
</div>
<div class="section" id="comparison-to-the-built-in-set-types">
<span id="comparison-to-builtin-set"></span><h2>8.7.4. Comparison to the built-in <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> types<a class="headerlink" href="#comparison-to-the-built-in-set-types" title="Permalink to this headline">¶</a></h2>
<p>The built-in <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types were designed based on
lessons learned from the <a class="reference internal" href="#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module.  The key differences are:</p>
<ul class="simple">
<li><a class="reference internal" href="#sets.Set" title="sets.Set"><code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code></a> and <a class="reference internal" href="#sets.ImmutableSet" title="sets.ImmutableSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code></a> were renamed to <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and
<a class="reference internal" href="stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>.</li>
<li>There is no equivalent to <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseSet</span></code>.  Instead, use <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span>
<span class="pre">(set,</span> <span class="pre">frozenset))</span></code>.</li>
<li>The hash algorithm for the built-ins performs significantly better (fewer
collisions) for most datasets.</li>
<li>The built-in versions have more space efficient pickles.</li>
<li>The built-in versions do not have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">union_update()</span></code> method. Instead, use
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> method which is equivalent.</li>
<li>The built-in versions do not have a <code class="docutils literal notranslate"><span class="pre">_repr(sorted=True)</span></code> method.
Instead, use the built-in <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> and <a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> functions:
<code class="docutils literal notranslate"><span class="pre">repr(sorted(s))</span></code>.</li>
<li>The built-in version does not have a protocol for automatic conversion to
immutable.  Many found this feature to be confusing and no one in the community
reported having found real uses for it.</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a><ul>
<li><a class="reference internal" href="#set-objects">8.7.1. Set Objects</a></li>
<li><a class="reference internal" href="#example">8.7.2. Example</a></li>
<li><a class="reference internal" href="#protocol-for-automatic-conversion-to-immutable">8.7.3. Protocol for automatic conversion to immutable</a></li>
<li><a class="reference internal" href="#comparison-to-the-built-in-set-types">8.7.4. Comparison to the built-in <code class="docutils literal notranslate"><span class="pre">set</span></code> types</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="array.html"
                        title="previous chapter">8.6. <code class="docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sched.html"
                        title="next chapter">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sets.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sched.html" title="8.8. sched — Event scheduler"
             >next</a> |</li>
        <li class="right" >
          <a href="array.html" title="8.6. array — Efficient arrays of numeric values"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ӻ6�(�(html/library/sgi.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>39. SGI IRIX Specific Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="39.1. al — Audio functions on the SGI" href="al.html" />
    <link rel="prev" title="38.5. MiniAEFrame — Open Scripting Architecture server support" href="miniaeframe.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sgi.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="al.html" title="39.1. al — Audio functions on the SGI"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="miniaeframe.html" title="38.5. MiniAEFrame — Open Scripting Architecture server support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="sgi-irix-specific-services">
<span id="sgi"></span><h1>39. SGI IRIX Specific Services<a class="headerlink" href="#sgi-irix-specific-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide interfaces to features that are
unique to SGI’s IRIX operating system (versions 4 and 5).</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="al.html">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a><ul>
<li class="toctree-l2"><a class="reference internal" href="al.html#configuration-objects">39.1.1. Configuration Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="al.html#port-objects">39.1.2. Port Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="al.html#module-AL">39.2. <code class="docutils literal notranslate"><span class="pre">AL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">al</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="cd.html">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cd.html#player-objects">39.3.1. Player Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="cd.html#parser-objects">39.3.2. Parser Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="fl.html">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a><ul>
<li class="toctree-l2"><a class="reference internal" href="fl.html#functions-defined-in-module-fl">39.4.1. Functions Defined in Module <code class="docutils literal notranslate"><span class="pre">fl</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="fl.html#form-objects">39.4.2. Form Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="fl.html#forms-objects">39.4.3. FORMS Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="fl.html#module-FL">39.5. <code class="docutils literal notranslate"><span class="pre">FL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">fl</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="fl.html#module-flp">39.6. <code class="docutils literal notranslate"><span class="pre">flp</span></code> — Functions for loading stored FORMS designs</a></li>
<li class="toctree-l1"><a class="reference internal" href="fm.html">39.7. <code class="docutils literal notranslate"><span class="pre">fm</span></code> — <em>Font Manager</em> interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="gl.html">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></li>
<li class="toctree-l1"><a class="reference internal" href="gl.html#module-DEVICE">39.9. <code class="docutils literal notranslate"><span class="pre">DEVICE</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="gl.html#module-GL">39.10. <code class="docutils literal notranslate"><span class="pre">GL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="imgfile.html">39.11. <code class="docutils literal notranslate"><span class="pre">imgfile</span></code> — Support for SGI imglib files</a></li>
<li class="toctree-l1"><a class="reference internal" href="jpeg.html">39.12. <code class="docutils literal notranslate"><span class="pre">jpeg</span></code> — Read and write JPEG files</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="miniaeframe.html"
                        title="previous chapter">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="al.html"
                        title="next chapter">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sgi.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="al.html" title="39.1. al — Audio functions on the SGI"
             >next</a> |</li>
        <li class="right" >
          <a href="miniaeframe.html" title="38.5. MiniAEFrame — Open Scripting Architecture server support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\{��Ġ���html/library/sgmllib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.2. sgmllib — Simple SGML parser &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.3. htmllib — A parser for HTML documents" href="htmllib.html" />
    <link rel="prev" title="19.1. HTMLParser — Simple HTML and XHTML parser" href="htmlparser.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sgmllib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="htmllib.html" title="19.3. htmllib — A parser for HTML documents"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="htmlparser.html" title="19.1. HTMLParser — Simple HTML and XHTML parser"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sgmllib">
<span id="sgmllib-simple-sgml-parser"></span><h1>19.2. <a class="reference internal" href="#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a> — Simple SGML parser<a class="headerlink" href="#module-sgmllib" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">This module defines a class <a class="reference internal" href="#sgmllib.SGMLParser" title="sgmllib.SGMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SGMLParser</span></code></a> which serves as the basis for
parsing text files formatted in SGML (Standard Generalized Mark-up Language).
In fact, it does not provide a full SGML parser — it only parses SGML insofar
as it is used by HTML, and the module only exists as a base for the
<a class="reference internal" href="htmllib.html#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> module.  Another HTML parser which supports XHTML and offers a
somewhat different interface is available in the <a class="reference internal" href="htmlparser.html#module-HTMLParser" title="HTMLParser: A simple parser that can handle HTML and XHTML."><code class="xref py py-mod docutils literal notranslate"><span class="pre">HTMLParser</span></code></a> module.</p>
<dl class="class">
<dt id="sgmllib.SGMLParser">
<em class="property">class </em><code class="descclassname">sgmllib.</code><code class="descname">SGMLParser</code><a class="headerlink" href="#sgmllib.SGMLParser" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#sgmllib.SGMLParser" title="sgmllib.SGMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SGMLParser</span></code></a> class is instantiated without arguments. The parser is
hardcoded to recognize the following constructs:</p>
<ul class="simple">
<li>Opening and closing tags of the form <code class="docutils literal notranslate"><span class="pre">&lt;tag</span> <span class="pre">attr=&quot;value&quot;</span> <span class="pre">...&gt;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&lt;/tag&gt;</span></code>, respectively.</li>
<li>Numeric character references of the form <code class="docutils literal notranslate"><span class="pre">&amp;#name;</span></code>.</li>
<li>Entity references of the form <code class="docutils literal notranslate"><span class="pre">&amp;name;</span></code>.</li>
<li>SGML comments of the form <code class="docutils literal notranslate"><span class="pre">&lt;!--text--&gt;</span></code>.  Note that spaces, tabs, and
newlines are allowed between the trailing <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> and the immediately preceding
<code class="docutils literal notranslate"><span class="pre">--</span></code>.</li>
</ul>
</dd></dl>

<p>A single exception is defined as well:</p>
<dl class="exception">
<dt id="sgmllib.SGMLParseError">
<em class="property">exception </em><code class="descclassname">sgmllib.</code><code class="descname">SGMLParseError</code><a class="headerlink" href="#sgmllib.SGMLParseError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by the <a class="reference internal" href="#sgmllib.SGMLParser" title="sgmllib.SGMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SGMLParser</span></code></a> class when it encounters an error
while parsing.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<p><a class="reference internal" href="#sgmllib.SGMLParser" title="sgmllib.SGMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">SGMLParser</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="sgmllib.SGMLParser.reset">
<code class="descclassname">SGMLParser.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the instance.  Loses all unprocessed data.  This is called implicitly at
instantiation time.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.setnomoretags">
<code class="descclassname">SGMLParser.</code><code class="descname">setnomoretags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.setnomoretags" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop processing tags.  Treat all following input as literal input (CDATA).
(This is only provided so the HTML tag <code class="docutils literal notranslate"><span class="pre">&lt;PLAINTEXT&gt;</span></code> can be implemented.)</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.setliteral">
<code class="descclassname">SGMLParser.</code><code class="descname">setliteral</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.setliteral" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter literal mode (CDATA mode).</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.feed">
<code class="descclassname">SGMLParser.</code><code class="descname">feed</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.feed" title="Permalink to this definition">¶</a></dt>
<dd><p>Feed some text to the parser.  It is processed insofar as it consists of
complete elements; incomplete data is buffered until more data is fed or
<a class="reference internal" href="#sgmllib.SGMLParser.close" title="sgmllib.SGMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> is called.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.close">
<code class="descclassname">SGMLParser.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Force processing of all buffered data as if it were followed by an end-of-file
mark.  This method may be redefined by a derived class to define additional
processing at the end of the input, but the redefined version should always call
<a class="reference internal" href="#sgmllib.SGMLParser.close" title="sgmllib.SGMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.get_starttag_text">
<code class="descclassname">SGMLParser.</code><code class="descname">get_starttag_text</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.get_starttag_text" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the text of the most recently opened start tag.  This should not normally
be needed for structured processing, but may be useful in dealing with HTML “as
deployed” or for re-generating input with minimal changes (whitespace between
attributes can be preserved, etc.).</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_starttag">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_starttag</code><span class="sig-paren">(</span><em>tag</em>, <em>method</em>, <em>attributes</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_starttag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle start tags for which either a <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code>
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code> method has been defined.  The <em>tag</em> argument is the name of
the tag converted to lower case, and the <em>method</em> argument is the bound method
which should be used to support semantic interpretation of the start tag. The
<em>attributes</em> argument is a list of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> pairs containing the
attributes found inside the tag’s <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> brackets.</p>
<p>The <em>name</em> has been translated to lower case. Double quotes and backslashes in
the <em>value</em> have been interpreted, as well as known character references and
known entity references terminated by a semicolon (normally, entity references
can be terminated by any non-alphanumerical character, but this would break the
very common case of <code class="docutils literal notranslate"><span class="pre">&lt;A</span> <span class="pre">HREF=&quot;url?spam=1&amp;eggs=2&quot;&gt;</span></code> when <code class="docutils literal notranslate"><span class="pre">eggs</span></code> is a valid
entity name).</p>
<p>For instance, for the tag <code class="docutils literal notranslate"><span class="pre">&lt;A</span> <span class="pre">HREF=&quot;http://www.cwi.nl/&quot;&gt;</span></code>, this method would
be called as <code class="docutils literal notranslate"><span class="pre">unknown_starttag('a',</span> <span class="pre">[('href',</span> <span class="pre">'http://www.cwi.nl/')])</span></code>.  The
base implementation simply calls <em>method</em> with <em>attributes</em> as the only
argument.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>Handling of entity and character references within attribute values.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_endtag">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_endtag</code><span class="sig-paren">(</span><em>tag</em>, <em>method</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_endtag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to handle endtags for which an <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code> method has
been defined.  The <em>tag</em> argument is the name of the tag converted to lower
case, and the <em>method</em> argument is the bound method which should be used to
support semantic interpretation of the end tag.  If no <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code> method is
defined for the closing element, this handler is not called.  The base
implementation simply calls <em>method</em>.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_data">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_data" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process arbitrary data.  It is intended to be
overridden by a derived class; the base class implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_charref">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_charref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_charref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process a character reference of the form <code class="docutils literal notranslate"><span class="pre">&amp;#ref;</span></code>.
The base implementation uses <a class="reference internal" href="#sgmllib.SGMLParser.convert_charref" title="sgmllib.SGMLParser.convert_charref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_charref()</span></code></a> to convert the reference to
a string.  If that method returns a string, it is passed to <a class="reference internal" href="#sgmllib.SGMLParser.handle_data" title="sgmllib.SGMLParser.handle_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_data()</span></code></a>,
otherwise <code class="docutils literal notranslate"><span class="pre">unknown_charref(ref)</span></code> is called to handle the error.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Use <a class="reference internal" href="#sgmllib.SGMLParser.convert_charref" title="sgmllib.SGMLParser.convert_charref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_charref()</span></code></a> instead of hard-coding the conversion.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.convert_charref">
<code class="descclassname">SGMLParser.</code><code class="descname">convert_charref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.convert_charref" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a character reference to a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <em>ref</em> is the reference
passed in as a string.  In the base implementation, <em>ref</em> must be a decimal
number in the range 0–255.  It converts the code point found using the
<a class="reference internal" href="#sgmllib.SGMLParser.convert_codepoint" title="sgmllib.SGMLParser.convert_codepoint"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_codepoint()</span></code></a> method. If <em>ref</em> is invalid or out of range, this
method returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.  This method is called by the default
<a class="reference internal" href="#sgmllib.SGMLParser.handle_charref" title="sgmllib.SGMLParser.handle_charref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_charref()</span></code></a> implementation and by the attribute value parser.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.convert_codepoint">
<code class="descclassname">SGMLParser.</code><code class="descname">convert_codepoint</code><span class="sig-paren">(</span><em>codepoint</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.convert_codepoint" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a code point to a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> value.  Encodings can be handled here if
appropriate, though the rest of <a class="reference internal" href="#module-sgmllib" title="sgmllib: Only as much of an SGML parser as needed to parse HTML. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmllib</span></code></a> is oblivious on this matter.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_entityref">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_entityref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_entityref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process a general entity reference of the form
<code class="docutils literal notranslate"><span class="pre">&amp;ref;</span></code> where <em>ref</em> is a general entity reference.  It converts <em>ref</em> by
passing it to <a class="reference internal" href="#sgmllib.SGMLParser.convert_entityref" title="sgmllib.SGMLParser.convert_entityref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_entityref()</span></code></a>.  If a translation is returned, it calls
the method <a class="reference internal" href="#sgmllib.SGMLParser.handle_data" title="sgmllib.SGMLParser.handle_data"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_data()</span></code></a> with the translation; otherwise, it calls the
method <code class="docutils literal notranslate"><span class="pre">unknown_entityref(ref)</span></code>. The default <code class="xref py py-attr docutils literal notranslate"><span class="pre">entitydefs</span></code> defines
translations for <code class="docutils literal notranslate"><span class="pre">&amp;amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;apos;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;lt;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&amp;quot;</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Use <a class="reference internal" href="#sgmllib.SGMLParser.convert_entityref" title="sgmllib.SGMLParser.convert_entityref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">convert_entityref()</span></code></a> instead of hard-coding the conversion.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.convert_entityref">
<code class="descclassname">SGMLParser.</code><code class="descname">convert_entityref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.convert_entityref" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a named entity reference to a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> value, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The
resulting value will not be parsed.  <em>ref</em> will be only the name of the entity.
The default implementation looks for <em>ref</em> in the instance (or class) variable
<code class="xref py py-attr docutils literal notranslate"><span class="pre">entitydefs</span></code> which should be a mapping from entity names to corresponding
translations.  If no translation is available for <em>ref</em>, this method returns
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  This method is called by the default <a class="reference internal" href="#sgmllib.SGMLParser.handle_entityref" title="sgmllib.SGMLParser.handle_entityref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_entityref()</span></code></a>
implementation and by the attribute value parser.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_comment">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_comment</code><span class="sig-paren">(</span><em>comment</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_comment" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when a comment is encountered.  The <em>comment</em> argument is
a string containing the text between the <code class="docutils literal notranslate"><span class="pre">&lt;!--</span></code> and <code class="docutils literal notranslate"><span class="pre">--&gt;</span></code> delimiters, but
not the delimiters themselves.  For example, the comment <code class="docutils literal notranslate"><span class="pre">&lt;!--text--&gt;</span></code> will
cause this method to be called with the argument <code class="docutils literal notranslate"><span class="pre">'text'</span></code>.  The default method
does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.handle_decl">
<code class="descclassname">SGMLParser.</code><code class="descname">handle_decl</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.handle_decl" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called when an SGML declaration is read by the parser.  In practice, the
<code class="docutils literal notranslate"><span class="pre">DOCTYPE</span></code> declaration is the only thing observed in HTML, but the parser does
not discriminate among different (or broken) declarations.  Internal subsets in
a <code class="docutils literal notranslate"><span class="pre">DOCTYPE</span></code> declaration are not supported.  The <em>data</em> parameter will be the
entire contents of the declaration inside the <code class="docutils literal notranslate"><span class="pre">&lt;!</span></code>…<code class="docutils literal notranslate"><span class="pre">&gt;</span></code> markup.  The
default implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.report_unbalanced">
<code class="descclassname">SGMLParser.</code><code class="descname">report_unbalanced</code><span class="sig-paren">(</span><em>tag</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.report_unbalanced" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when an end tag is found which does not correspond to any
open element.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.unknown_starttag">
<code class="descclassname">SGMLParser.</code><code class="descname">unknown_starttag</code><span class="sig-paren">(</span><em>tag</em>, <em>attributes</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.unknown_starttag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process an unknown start tag.  It is intended to be
overridden by a derived class; the base class implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.unknown_endtag">
<code class="descclassname">SGMLParser.</code><code class="descname">unknown_endtag</code><span class="sig-paren">(</span><em>tag</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.unknown_endtag" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process an unknown end tag.  It is intended to be
overridden by a derived class; the base class implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.unknown_charref">
<code class="descclassname">SGMLParser.</code><code class="descname">unknown_charref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.unknown_charref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process unresolvable numeric character references.
Refer to <a class="reference internal" href="#sgmllib.SGMLParser.handle_charref" title="sgmllib.SGMLParser.handle_charref"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_charref()</span></code></a> to determine what is handled by default.  It is
intended to be overridden by a derived class; the base class implementation does
nothing.</p>
</dd></dl>

<dl class="method">
<dt id="sgmllib.SGMLParser.unknown_entityref">
<code class="descclassname">SGMLParser.</code><code class="descname">unknown_entityref</code><span class="sig-paren">(</span><em>ref</em><span class="sig-paren">)</span><a class="headerlink" href="#sgmllib.SGMLParser.unknown_entityref" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called to process an unknown entity reference.  It is intended to
be overridden by a derived class; the base class implementation does nothing.</p>
</dd></dl>

<p>Apart from overriding or extending the methods listed above, derived classes may
also define methods of the following form to define processing of specific tags.
Tag names in the input stream are case independent; the <em>tag</em> occurring in
method names must be in lower case:</p>
<dl class="method">
<dt>
<code class="descclassname">SGMLParser.</code><code class="descname">start_tag</code><span class="sig-paren">(</span><em>attributes</em><span class="sig-paren">)</span></dt>
<dd><p>This method is called to process an opening tag <em>tag</em>.  It has preference over
<code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code>.  The <em>attributes</em> argument has the same meaning as described for
<a class="reference internal" href="#sgmllib.SGMLParser.handle_starttag" title="sgmllib.SGMLParser.handle_starttag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_starttag()</span></code></a> above.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">SGMLParser.</code><code class="descname">do_tag</code><span class="sig-paren">(</span><em>attributes</em><span class="sig-paren">)</span></dt>
<dd><p>This method is called to process an opening tag <em>tag</em>  for which no
<code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> method is defined.   The <em>attributes</em> argument has the same
meaning as described for <a class="reference internal" href="#sgmllib.SGMLParser.handle_starttag" title="sgmllib.SGMLParser.handle_starttag"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_starttag()</span></code></a> above.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">SGMLParser.</code><code class="descname">end_tag</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>This method is called to process a closing tag <em>tag</em>.</p>
</dd></dl>

<p>Note that the parser maintains a stack of open elements for which no end tag has
been found yet.  Only tags processed by <code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> are pushed on this
stack.  Definition of an <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code> method is optional for these tags.  For
tags processed by <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code> or by <code class="xref py py-meth docutils literal notranslate"><span class="pre">unknown_tag()</span></code>, no <code class="xref py py-meth docutils literal notranslate"><span class="pre">end_tag()</span></code>
method must be defined; if defined, it will not be used.  If both
<code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">do_tag()</span></code> methods exist for a tag, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">start_tag()</span></code> method takes precedence.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="htmlparser.html"
                        title="previous chapter">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="htmllib.html"
                        title="next chapter">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sgmllib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="htmllib.html" title="19.3. htmllib — A parser for HTML documents"
             >next</a> |</li>
        <li class="right" >
          <a href="htmlparser.html" title="19.1. HTMLParser — Simple HTML and XHTML parser"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\B0�33html/library/sha.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14.4. sha — SHA-1 message digest algorithm &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15. Generic Operating System Services" href="allos.html" />
    <link rel="prev" title="14.3. md5 — MD5 message digest algorithm" href="md5.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sha.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="allos.html" title="15. Generic Operating System Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="md5.html" title="14.3. md5 — MD5 message digest algorithm"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" accesskey="U">14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sha">
<span id="sha-sha-1-message-digest-algorithm"></span><h1>14.4. <a class="reference internal" href="#module-sha" title="sha: NIST's secure hash algorithm, SHA. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code></a> — SHA-1 message digest algorithm<a class="headerlink" href="#module-sha" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.5: </span>Use the <a class="reference internal" href="hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module instead.</p>
</div>
<p id="index-0">This module implements the interface to NIST’s secure hash  algorithm, known as
SHA-1.  SHA-1 is an improved version of the original SHA hash algorithm.  It is
used in the same way as the <a class="reference internal" href="md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> module: use <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a> to create an sha
object, then feed this object with arbitrary strings using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>
method, and at any point you can ask it for the <em class="dfn">digest</em> of the
concatenation of the strings fed to it so far.  SHA-1 digests are 160 bits
instead of MD5’s 128 bits.</p>
<dl class="function">
<dt id="sha.new">
<code class="descclassname">sha.</code><code class="descname">new</code><span class="sig-paren">(</span><span class="optional">[</span><em>string</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sha.new" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new sha object.  If <em>string</em> is present, the method call
<code class="docutils literal notranslate"><span class="pre">update(string)</span></code> is made.</p>
</dd></dl>

<p>The following values are provided as constants in the module and as attributes
of the sha objects returned by <a class="reference internal" href="new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">new()</span></code></a>:</p>
<dl class="data">
<dt id="sha.blocksize">
<code class="descclassname">sha.</code><code class="descname">blocksize</code><a class="headerlink" href="#sha.blocksize" title="Permalink to this definition">¶</a></dt>
<dd><p>Size of the blocks fed into the hash function; this is always <code class="docutils literal notranslate"><span class="pre">1</span></code>.  This size
is used to allow an arbitrary string to be hashed.</p>
</dd></dl>

<dl class="data">
<dt id="sha.digest_size">
<code class="descclassname">sha.</code><code class="descname">digest_size</code><a class="headerlink" href="#sha.digest_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the resulting digest in bytes.  This is always <code class="docutils literal notranslate"><span class="pre">20</span></code>.</p>
</dd></dl>

<p>An sha object has the same methods as md5 objects:</p>
<dl class="method">
<dt id="sha.sha.update">
<code class="descclassname">sha.</code><code class="descname">update</code><span class="sig-paren">(</span><em>arg</em><span class="sig-paren">)</span><a class="headerlink" href="#sha.sha.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the sha object with the string <em>arg</em>.  Repeated calls are equivalent to a
single call with the concatenation of all the arguments: <code class="docutils literal notranslate"><span class="pre">m.update(a);</span>
<span class="pre">m.update(b)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.update(a+b)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="sha.sha.digest">
<code class="descclassname">sha.</code><code class="descname">digest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sha.sha.digest" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the digest of the strings passed to the <a class="reference internal" href="#sha.sha.update" title="sha.sha.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a> method so far.
This is a 20-byte string which may contain non-ASCII characters, including null
bytes.</p>
</dd></dl>

<dl class="method">
<dt id="sha.sha.hexdigest">
<code class="descclassname">sha.</code><code class="descname">hexdigest</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sha.sha.hexdigest" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#sha.sha.digest" title="sha.sha.digest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code></a> except the digest is returned as a string of length 40,
containing only hexadecimal digits.  This may  be used to exchange the value
safely in email or other non-binary environments.</p>
</dd></dl>

<dl class="method">
<dt id="sha.sha.copy">
<code class="descclassname">sha.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sha.sha.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy (“clone”) of the sha object.  This can be used to efficiently
compute the digests of strings that share a common initial substring.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf">Secure Hash Standard</a></dt>
<dd>The Secure Hash Algorithm is defined by NIST document FIPS PUB 180-2: <a class="reference external" href="http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf">Secure
Hash Standard</a>,
published in August 2002.</dd>
<dt><a class="reference external" href="http://csrc.nist.gov/CryptoToolkit/tkhash.html">Cryptographic Toolkit (Secure Hashing)</a></dt>
<dd>Links from NIST to various information on secure hashing.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="md5.html"
                        title="previous chapter">14.3. <code class="docutils literal notranslate"><span class="pre">md5</span></code> — MD5 message digest algorithm</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="allos.html"
                        title="next chapter">15. Generic Operating System Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sha.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="allos.html" title="15. Generic Operating System Services"
             >next</a> |</li>
        <li class="right" >
          <a href="md5.html" title="14.3. md5 — MD5 message digest algorithm"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="crypto.html" >14. Cryptographic Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���uuhtml/library/shelve.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.4. shelve — Python object persistence &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.5. marshal — Internal Python object serialization" href="marshal.html" />
    <link rel="prev" title="11.3. copy_reg — Register pickle support functions" href="copy_reg.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/shelve.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="11.5. marshal — Internal Python object serialization"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="copy_reg.html" title="11.3. copy_reg — Register pickle support functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-shelve">
<span id="shelve-python-object-persistence"></span><h1>11.4. <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> — Python object persistence<a class="headerlink" href="#module-shelve" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/shelve.py">Lib/shelve.py</a></p>
<hr class="docutils" />
<p>A “shelf” is a persistent, dictionary-like object.  The difference with “dbm”
databases is that the values (not the keys!) in a shelf can be essentially
arbitrary Python objects — anything that the <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> module can handle.
This includes most class instances, recursive data types, and objects containing
lots of shared  sub-objects.  The keys are ordinary strings.</p>
<dl class="function">
<dt id="shelve.open">
<code class="descclassname">shelve.</code><code class="descname">open</code><span class="sig-paren">(</span><em>filename</em>, <em>flag='c'</em>, <em>protocol=None</em>, <em>writeback=False</em><span class="sig-paren">)</span><a class="headerlink" href="#shelve.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a persistent dictionary.  The filename specified is the base filename for
the underlying database.  As a side-effect, an extension may be added to the
filename and more than one file may be created.  By default, the underlying
database file is opened for reading and writing.  The optional <em>flag</em> parameter
has the same interpretation as the <em>flag</em> parameter of <a class="reference internal" href="anydbm.html#anydbm.open" title="anydbm.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">anydbm.open()</span></code></a>.</p>
<p>By default, version 0 pickles are used to serialize values.  The version of the
pickle protocol can be specified with the <em>protocol</em> parameter.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The <em>protocol</em> parameter was added.</p>
</div>
<p>Because of Python semantics, a shelf cannot know when a mutable
persistent-dictionary entry is modified.  By default modified objects are
written <em>only</em> when assigned to the shelf (see <a class="reference internal" href="#shelve-example"><span class="std std-ref">Example</span></a>).  If the
optional <em>writeback</em> parameter is set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, all entries accessed are also
cached in memory, and written back on <a class="reference internal" href="#shelve.Shelf.sync" title="shelve.Shelf.sync"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sync()</span></code></a> and
<a class="reference internal" href="#shelve.Shelf.close" title="shelve.Shelf.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>; this can make it handier to mutate mutable entries in
the persistent dictionary, but, if many entries are accessed, it can consume
vast amounts of memory for the cache, and it can make the close operation
very slow since all accessed entries are written back (there is no way to
determine which accessed entries are mutable, nor which ones were actually
mutated).</p>
<p>Like file objects, shelve objects should be closed explicitly to ensure
that the persistent data is flushed to disk.</p>
</dd></dl>

<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Because the <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> module is backed by <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>, it is insecure
to load a shelf from an untrusted source.  Like with pickle, loading a shelf
can execute arbitrary code.</p>
</div>
<p>Shelf objects support most of the methods supported by dictionaries.  This
eases the transition from dictionary based scripts to those requiring
persistent storage.</p>
<p>Note, the Python 3 transition methods (<a class="reference internal" href="stdtypes.html#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewkeys()</span></code></a>,
<a class="reference internal" href="stdtypes.html#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewvalues()</span></code></a>, and <a class="reference internal" href="stdtypes.html#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewitems()</span></code></a>) are not supported.</p>
<p>Two additional methods are supported:</p>
<dl class="method">
<dt id="shelve.Shelf.sync">
<code class="descclassname">Shelf.</code><code class="descname">sync</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shelve.Shelf.sync" title="Permalink to this definition">¶</a></dt>
<dd><p>Write back all entries in the cache if the shelf was opened with <em>writeback</em>
set to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.  Also empty the cache and synchronize the persistent
dictionary on disk, if feasible.  This is called automatically when the shelf
is closed with <a class="reference internal" href="#shelve.Shelf.close" title="shelve.Shelf.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="shelve.Shelf.close">
<code class="descclassname">Shelf.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shelve.Shelf.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Synchronize and close the persistent <em>dict</em> object.  Operations on a closed
shelf will fail with a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://code.activestate.com/recipes/576642/">Persistent dictionary recipe</a>
with widely supported storage formats and having the speed of native
dictionaries.</p>
</div>
<div class="section" id="restrictions">
<h2>11.4.1. Restrictions<a class="headerlink" href="#restrictions" title="Permalink to this headline">¶</a></h2>
<blockquote>
<div></div></blockquote>
<ul class="simple" id="index-1">
<li>The choice of which database package will be used (such as <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>,
<a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a> or <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a>) depends on which interface is available.  Therefore
it is not safe to open the database directly using <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>.  The database is
also (unfortunately) subject to the limitations of <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>, if it is used —
this means that (the pickled representation of) the objects stored in the
database should be fairly small, and in rare cases key collisions may cause the
database to refuse updates.</li>
<li>The <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a> module does not support <em>concurrent</em> read/write access to
shelved objects.  (Multiple simultaneous read accesses are safe.)  When a
program has a shelf open for writing, no other program should have it open for
reading or writing.  Unix file locking can be used to solve this, but this
differs across Unix versions and requires knowledge about the database
implementation used.</li>
</ul>
<dl class="class">
<dt id="shelve.Shelf">
<em class="property">class </em><code class="descclassname">shelve.</code><code class="descname">Shelf</code><span class="sig-paren">(</span><em>dict</em>, <em>protocol=None</em>, <em>writeback=False</em><span class="sig-paren">)</span><a class="headerlink" href="#shelve.Shelf" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="userdict.html#UserDict.DictMixin" title="UserDict.DictMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict.DictMixin</span></code></a> which stores pickled values in the
<em>dict</em> object.</p>
<p>By default, version 0 pickles are used to serialize values.  The version of the
pickle protocol can be specified with the <em>protocol</em> parameter. See the
<a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> documentation for a discussion of the pickle protocols.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>The <em>protocol</em> parameter was added.</p>
</div>
<p>If the <em>writeback</em> parameter is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the object will hold a cache of all
entries accessed and write them back to the <em>dict</em> at sync and close times.
This allows natural operations on mutable entries, but can consume much more
memory and make sync and close take a long time.</p>
</dd></dl>

<dl class="class">
<dt id="shelve.BsdDbShelf">
<em class="property">class </em><code class="descclassname">shelve.</code><code class="descname">BsdDbShelf</code><span class="sig-paren">(</span><em>dict</em>, <em>protocol=None</em>, <em>writeback=False</em><span class="sig-paren">)</span><a class="headerlink" href="#shelve.BsdDbShelf" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shelf</span></code></a> which exposes <code class="xref py py-meth docutils literal notranslate"><span class="pre">first()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">previous()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">last()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_location()</span></code> which are available in
the <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module but not in other database modules.  The <em>dict</em> object
passed to the constructor must support those methods.  This is generally
accomplished by calling one of <a class="reference internal" href="bsddb.html#bsddb.hashopen" title="bsddb.hashopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">bsddb.hashopen()</span></code></a>, <a class="reference internal" href="bsddb.html#bsddb.btopen" title="bsddb.btopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">bsddb.btopen()</span></code></a> or
<a class="reference internal" href="bsddb.html#bsddb.rnopen" title="bsddb.rnopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">bsddb.rnopen()</span></code></a>.  The optional <em>protocol</em> and <em>writeback</em> parameters have
the same interpretation as for the <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shelf</span></code></a> class.</p>
</dd></dl>

<dl class="class">
<dt id="shelve.DbfilenameShelf">
<em class="property">class </em><code class="descclassname">shelve.</code><code class="descname">DbfilenameShelf</code><span class="sig-paren">(</span><em>filename</em>, <em>flag='c'</em>, <em>protocol=None</em>, <em>writeback=False</em><span class="sig-paren">)</span><a class="headerlink" href="#shelve.DbfilenameShelf" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shelf</span></code></a> which accepts a <em>filename</em> instead of a dict-like
object.  The underlying file will be opened using <a class="reference internal" href="anydbm.html#anydbm.open" title="anydbm.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">anydbm.open()</span></code></a>.  By
default, the file will be created and opened for both read and write.  The
optional <em>flag</em> parameter has the same interpretation as for the <a class="reference internal" href="#shelve.open" title="shelve.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
function.  The optional <em>protocol</em> and <em>writeback</em> parameters have the same
interpretation as for the <a class="reference internal" href="#shelve.Shelf" title="shelve.Shelf"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shelf</span></code></a> class.</p>
</dd></dl>

</div>
<div class="section" id="example">
<span id="shelve-example"></span><h2>11.4.2. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>To summarize the interface (<code class="docutils literal notranslate"><span class="pre">key</span></code> is a string, <code class="docutils literal notranslate"><span class="pre">data</span></code> is an arbitrary
object):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">shelve</span>

<span class="n">d</span> <span class="o">=</span> <span class="n">shelve</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="c1"># open -- file may get suffix added by low-level</span>
                          <span class="c1"># library</span>

<span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="n">data</span>   <span class="c1"># store data at key (overwrites old data if</span>
                <span class="c1"># using an existing key)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>   <span class="c1"># retrieve a COPY of data at key (raise KeyError if no</span>
                <span class="c1"># such key)</span>
<span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>      <span class="c1"># delete data stored at key (raises KeyError</span>
                <span class="c1"># if no such key)</span>
<span class="n">flag</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>   <span class="c1"># true if the key exists</span>
<span class="n">klist</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="c1"># a list of all existing keys (slow!)</span>

<span class="c1"># as d was opened WITHOUT writeback=True, beware:</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;xx&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>  <span class="c1"># this works as expected, but...</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;xx&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>   <span class="c1"># *this doesn&#39;t!* -- d[&#39;xx&#39;] is STILL range(4)!</span>

<span class="c1"># having opened d without writeback=True, you need to code carefully:</span>
<span class="n">temp</span> <span class="o">=</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;xx&#39;</span><span class="p">]</span>      <span class="c1"># extracts the copy</span>
<span class="n">temp</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>      <span class="c1"># mutates the copy</span>
<span class="n">d</span><span class="p">[</span><span class="s1">&#39;xx&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">temp</span>      <span class="c1"># stores the copy right back, to persist it</span>

<span class="c1"># or, d=shelve.open(filename,writeback=True) would let you just code</span>
<span class="c1"># d[&#39;xx&#39;].append(5) and have it work as expected, BUT it would also</span>
<span class="c1"># consume more memory and make the d.close() operation slower.</span>

<span class="n">d</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>       <span class="c1"># close it</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="anydbm.html#module-anydbm" title="anydbm: Generic interface to DBM-style database modules."><code class="xref py py-mod docutils literal notranslate"><span class="pre">anydbm</span></code></a></dt>
<dd>Generic interface to <code class="docutils literal notranslate"><span class="pre">dbm</span></code>-style databases.</dd>
<dt>Module <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a></dt>
<dd>BSD <code class="docutils literal notranslate"><span class="pre">db</span></code> database interface.</dd>
<dt>Module <a class="reference internal" href="dbhash.html#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a></dt>
<dd>Thin layer around the <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> which provides an <a class="reference internal" href="dbhash.html#dbhash.open" title="dbhash.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
function like the other database modules.</dd>
<dt>Module <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a></dt>
<dd>Standard Unix database interface.</dd>
<dt>Module <a class="reference internal" href="dumbdbm.html#module-dumbdbm" title="dumbdbm: Portable implementation of the simple DBM interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dumbdbm</span></code></a></dt>
<dd>Portable implementation of the <code class="docutils literal notranslate"><span class="pre">dbm</span></code> interface.</dd>
<dt>Module <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a></dt>
<dd>GNU database interface, based on the <code class="docutils literal notranslate"><span class="pre">dbm</span></code> interface.</dd>
<dt>Module <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a></dt>
<dd>Object serialization used by <a class="reference internal" href="#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>.</dd>
<dt>Module <a class="reference internal" href="pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a></dt>
<dd>High-performance version of <a class="reference internal" href="pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>.</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a><ul>
<li><a class="reference internal" href="#restrictions">11.4.1. Restrictions</a></li>
<li><a class="reference internal" href="#example">11.4.2. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="copy_reg.html"
                        title="previous chapter">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="marshal.html"
                        title="next chapter">11.5. <code class="docutils literal notranslate"><span class="pre">marshal</span></code> — Internal Python object serialization</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/shelve.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="marshal.html" title="11.5. marshal — Internal Python object serialization"
             >next</a> |</li>
        <li class="right" >
          <a href="copy_reg.html" title="11.3. copy_reg — Register pickle support functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�9�ووhtml/library/shlex.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>23.2. shlex — Simple lexical analysis &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24. Graphical User Interfaces with Tk" href="tk.html" />
    <link rel="prev" title="23.1. cmd — Support for line-oriented command interpreters" href="cmd.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/shlex.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tk.html" title="24. Graphical User Interfaces with Tk"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cmd.html" title="23.1. cmd — Support for line-oriented command interpreters"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="frameworks.html" accesskey="U">23. Program Frameworks</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-shlex">
<span id="shlex-simple-lexical-analysis"></span><h1>23.2. <a class="reference internal" href="#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a> — Simple lexical analysis<a class="headerlink" href="#module-shlex" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/shlex.py">Lib/shlex.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> class makes it easy to write lexical analyzers for
simple syntaxes resembling that of the Unix shell.  This will often be useful
for writing minilanguages, (for example, in run control files for Python
applications) or for parsing quoted strings.</p>
<p>Prior to Python 2.7.3, this module did not support Unicode input.</p>
<p>The <a class="reference internal" href="#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="shlex.split">
<code class="descclassname">shlex.</code><code class="descname">split</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>comments</em><span class="optional">[</span>, <em>posix</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the string <em>s</em> using shell-like syntax. If <em>comments</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>
(the default), the parsing of comments in the given string will be disabled
(setting the <a class="reference internal" href="#shlex.shlex.commenters" title="shlex.shlex.commenters"><code class="xref py py-attr docutils literal notranslate"><span class="pre">commenters</span></code></a> attribute of the
<a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> instance to the empty string).  This function operates
in POSIX mode by default, but uses non-POSIX mode if the <em>posix</em> argument is
false.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the <em>posix</em> parameter.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Since the <a class="reference internal" href="#shlex.split" title="shlex.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a> function instantiates a <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a>
instance, passing <code class="docutils literal notranslate"><span class="pre">None</span></code> for <em>s</em> will read the string to split from
standard input.</p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a> module defines the following class:</p>
<dl class="class">
<dt id="shlex.shlex">
<em class="property">class </em><code class="descclassname">shlex.</code><code class="descname">shlex</code><span class="sig-paren">(</span><span class="optional">[</span><em>instream</em><span class="optional">[</span>, <em>infile</em><span class="optional">[</span>, <em>posix</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> instance or subclass instance is a lexical analyzer
object.  The initialization argument, if present, specifies where to read
characters from. It must be a file-/stream-like object with
<a class="reference internal" href="io.html#io.TextIOBase.read" title="io.TextIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> and <a class="reference internal" href="io.html#io.TextIOBase.readline" title="io.TextIOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> methods, or
a string (strings are accepted since Python 2.3).  If no argument is given,
input will be taken from <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>.  The second optional argument is a
filename string, which sets the initial value of the <a class="reference internal" href="#shlex.shlex.infile" title="shlex.shlex.infile"><code class="xref py py-attr docutils literal notranslate"><span class="pre">infile</span></code></a>
attribute.  If the <em>instream</em> argument is omitted or equal to <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>,
this second argument defaults to “stdin”.  The <em>posix</em> argument was
introduced in Python 2.3, and defines the operational mode.  When <em>posix</em> is
not true (default), the <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> instance will operate in
compatibility mode.  When operating in POSIX mode, <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a>
will try to be as close as possible to the POSIX shell parsing rules.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a></dt>
<dd>Parser for configuration files similar to the Windows <code class="file docutils literal notranslate"><span class="pre">.ini</span></code> files.</dd>
</dl>
</div>
<div class="section" id="shlex-objects">
<span id="id1"></span><h2>23.2.1. shlex Objects<a class="headerlink" href="#shlex-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="shlex.shlex.get_token">
<code class="descclassname">shlex.</code><code class="descname">get_token</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.get_token" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a token.  If tokens have been stacked using <a class="reference internal" href="#shlex.shlex.push_token" title="shlex.shlex.push_token"><code class="xref py py-meth docutils literal notranslate"><span class="pre">push_token()</span></code></a>, pop a
token off the stack.  Otherwise, read one from the input stream.  If reading
encounters an immediate end-of-file, <a class="reference internal" href="#shlex.shlex.eof" title="shlex.shlex.eof"><code class="xref py py-attr docutils literal notranslate"><span class="pre">eof</span></code></a> is returned (the empty
string (<code class="docutils literal notranslate"><span class="pre">''</span></code>) in non-POSIX mode, and <code class="docutils literal notranslate"><span class="pre">None</span></code> in POSIX mode).</p>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.push_token">
<code class="descclassname">shlex.</code><code class="descname">push_token</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.push_token" title="Permalink to this definition">¶</a></dt>
<dd><p>Push the argument onto the token stack.</p>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.read_token">
<code class="descclassname">shlex.</code><code class="descname">read_token</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.read_token" title="Permalink to this definition">¶</a></dt>
<dd><p>Read a raw token.  Ignore the pushback stack, and do not interpret source
requests.  (This is not ordinarily a useful entry point, and is documented here
only for the sake of completeness.)</p>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.sourcehook">
<code class="descclassname">shlex.</code><code class="descname">sourcehook</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.sourcehook" title="Permalink to this definition">¶</a></dt>
<dd><p>When <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> detects a source request (see <a class="reference internal" href="#shlex.shlex.source" title="shlex.shlex.source"><code class="xref py py-attr docutils literal notranslate"><span class="pre">source</span></code></a>
below) this method is given the following token as argument, and expected
to return a tuple consisting of a filename and an open file-like object.</p>
<p>Normally, this method first strips any quotes off the argument.  If the result
is an absolute pathname, or there was no previous source request in effect, or
the previous source was a stream (such as <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>), the result is left
alone.  Otherwise, if the result is a relative pathname, the directory part of
the name of the file immediately before it on the source inclusion stack is
prepended (this behavior is like the way the C preprocessor handles <code class="docutils literal notranslate"><span class="pre">#include</span>
<span class="pre">&quot;file.h&quot;</span></code>).</p>
<p>The result of the manipulations is treated as a filename, and returned as the
first component of the tuple, with <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> called on it to yield the second
component. (Note: this is the reverse of the order of arguments in instance
initialization!)</p>
<p>This hook is exposed so that you can use it to implement directory search paths,
addition of file extensions, and other namespace hacks. There is no
corresponding ‘close’ hook, but a shlex instance will call the
<a class="reference internal" href="io.html#io.IOBase.close" title="io.IOBase.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method of the sourced input stream when it returns
EOF.</p>
<p>For more explicit control of source stacking, use the <a class="reference internal" href="#shlex.shlex.push_source" title="shlex.shlex.push_source"><code class="xref py py-meth docutils literal notranslate"><span class="pre">push_source()</span></code></a> and
<a class="reference internal" href="#shlex.shlex.pop_source" title="shlex.shlex.pop_source"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pop_source()</span></code></a> methods.</p>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.push_source">
<code class="descclassname">shlex.</code><code class="descname">push_source</code><span class="sig-paren">(</span><em>stream</em><span class="optional">[</span>, <em>filename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.push_source" title="Permalink to this definition">¶</a></dt>
<dd><p>Push an input source stream onto the input stack.  If the filename argument is
specified it will later be available for use in error messages.  This is the
same method used internally by the <a class="reference internal" href="#shlex.shlex.sourcehook" title="shlex.shlex.sourcehook"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sourcehook()</span></code></a> method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.pop_source">
<code class="descclassname">shlex.</code><code class="descname">pop_source</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.pop_source" title="Permalink to this definition">¶</a></dt>
<dd><p>Pop the last-pushed input source from the input stack. This is the same method
used internally when the lexer reaches EOF on a stacked input stream.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="shlex.shlex.error_leader">
<code class="descclassname">shlex.</code><code class="descname">error_leader</code><span class="sig-paren">(</span><span class="optional">[</span><em>file</em><span class="optional">[</span>, <em>line</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shlex.shlex.error_leader" title="Permalink to this definition">¶</a></dt>
<dd><p>This method generates an error message leader in the format of a Unix C compiler
error label; the format is <code class="docutils literal notranslate"><span class="pre">'&quot;%s&quot;,</span> <span class="pre">line</span> <span class="pre">%d:</span> <span class="pre">'</span></code>, where the <code class="docutils literal notranslate"><span class="pre">%s</span></code> is replaced
with the name of the current source file and the <code class="docutils literal notranslate"><span class="pre">%d</span></code> with the current input
line number (the optional arguments can be used to override these).</p>
<p>This convenience is provided to encourage <a class="reference internal" href="#module-shlex" title="shlex: Simple lexical analysis for Unix shell-like languages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shlex</span></code></a> users to generate error
messages in the standard, parseable format understood by Emacs and other Unix
tools.</p>
</dd></dl>

<p>Instances of <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> subclasses have some public instance
variables which either control lexical analysis or can be used for debugging:</p>
<dl class="attribute">
<dt id="shlex.shlex.commenters">
<code class="descclassname">shlex.</code><code class="descname">commenters</code><a class="headerlink" href="#shlex.shlex.commenters" title="Permalink to this definition">¶</a></dt>
<dd><p>The string of characters that are recognized as comment beginners. All
characters from the comment beginner to end of line are ignored. Includes just
<code class="docutils literal notranslate"><span class="pre">'#'</span></code> by default.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.wordchars">
<code class="descclassname">shlex.</code><code class="descname">wordchars</code><a class="headerlink" href="#shlex.shlex.wordchars" title="Permalink to this definition">¶</a></dt>
<dd><p>The string of characters that will accumulate into multi-character tokens.  By
default, includes all ASCII alphanumerics and underscore.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.whitespace">
<code class="descclassname">shlex.</code><code class="descname">whitespace</code><a class="headerlink" href="#shlex.shlex.whitespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Characters that will be considered whitespace and skipped.  Whitespace bounds
tokens.  By default, includes space, tab, linefeed and carriage-return.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.escape">
<code class="descclassname">shlex.</code><code class="descname">escape</code><a class="headerlink" href="#shlex.shlex.escape" title="Permalink to this definition">¶</a></dt>
<dd><p>Characters that will be considered as escape. This will be only used in POSIX
mode, and includes just <code class="docutils literal notranslate"><span class="pre">'\'</span></code> by default.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.quotes">
<code class="descclassname">shlex.</code><code class="descname">quotes</code><a class="headerlink" href="#shlex.shlex.quotes" title="Permalink to this definition">¶</a></dt>
<dd><p>Characters that will be considered string quotes.  The token accumulates until
the same quote is encountered again (thus, different quote types protect each
other as in the shell.)  By default, includes ASCII single and double quotes.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.escapedquotes">
<code class="descclassname">shlex.</code><code class="descname">escapedquotes</code><a class="headerlink" href="#shlex.shlex.escapedquotes" title="Permalink to this definition">¶</a></dt>
<dd><p>Characters in <a class="reference internal" href="#shlex.shlex.quotes" title="shlex.shlex.quotes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">quotes</span></code></a> that will interpret escape characters defined in
<a class="reference internal" href="#shlex.shlex.escape" title="shlex.shlex.escape"><code class="xref py py-attr docutils literal notranslate"><span class="pre">escape</span></code></a>.  This is only used in POSIX mode, and includes just <code class="docutils literal notranslate"><span class="pre">'&quot;'</span></code> by
default.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.whitespace_split">
<code class="descclassname">shlex.</code><code class="descname">whitespace_split</code><a class="headerlink" href="#shlex.shlex.whitespace_split" title="Permalink to this definition">¶</a></dt>
<dd><p>If <code class="docutils literal notranslate"><span class="pre">True</span></code>, tokens will only be split in whitespaces. This is useful, for
example, for parsing command lines with <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a>, getting
tokens in a similar way to shell arguments.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.infile">
<code class="descclassname">shlex.</code><code class="descname">infile</code><a class="headerlink" href="#shlex.shlex.infile" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the current input file, as initially set at class instantiation time
or stacked by later source requests.  It may be useful to examine this when
constructing error messages.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.instream">
<code class="descclassname">shlex.</code><code class="descname">instream</code><a class="headerlink" href="#shlex.shlex.instream" title="Permalink to this definition">¶</a></dt>
<dd><p>The input stream from which this <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> instance is reading
characters.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.source">
<code class="descclassname">shlex.</code><code class="descname">source</code><a class="headerlink" href="#shlex.shlex.source" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code> by default.  If you assign a string to it, that
string will be recognized as a lexical-level inclusion request similar to the
<code class="docutils literal notranslate"><span class="pre">source</span></code> keyword in various shells.  That is, the immediately following token
will be opened as a filename and input will
be taken from that stream until EOF, at which
point the <a class="reference internal" href="io.html#io.IOBase.close" title="io.IOBase.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method of that stream will be called and
the input source will again become the original input stream.  Source
requests may be stacked any number of levels deep.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.debug">
<code class="descclassname">shlex.</code><code class="descname">debug</code><a class="headerlink" href="#shlex.shlex.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>If this attribute is numeric and <code class="docutils literal notranslate"><span class="pre">1</span></code> or more, a <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a>
instance will print verbose progress output on its behavior.  If you need
to use this, you can read the module source code to learn the details.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.lineno">
<code class="descclassname">shlex.</code><code class="descname">lineno</code><a class="headerlink" href="#shlex.shlex.lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Source line number (count of newlines seen so far plus one).</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.token">
<code class="descclassname">shlex.</code><code class="descname">token</code><a class="headerlink" href="#shlex.shlex.token" title="Permalink to this definition">¶</a></dt>
<dd><p>The token buffer.  It may be useful to examine this when catching exceptions.</p>
</dd></dl>

<dl class="attribute">
<dt id="shlex.shlex.eof">
<code class="descclassname">shlex.</code><code class="descname">eof</code><a class="headerlink" href="#shlex.shlex.eof" title="Permalink to this definition">¶</a></dt>
<dd><p>Token used to determine end of file. This will be set to the empty string
(<code class="docutils literal notranslate"><span class="pre">''</span></code>), in non-POSIX mode, and to <code class="docutils literal notranslate"><span class="pre">None</span></code> in POSIX mode.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="parsing-rules">
<span id="shlex-parsing-rules"></span><h2>23.2.2. Parsing Rules<a class="headerlink" href="#parsing-rules" title="Permalink to this headline">¶</a></h2>
<p>When operating in non-POSIX mode, <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> will try to obey to the
following rules.</p>
<ul class="simple">
<li>Quote characters are not recognized within words (<code class="docutils literal notranslate"><span class="pre">Do&quot;Not&quot;Separate</span></code> is
parsed as the single word <code class="docutils literal notranslate"><span class="pre">Do&quot;Not&quot;Separate</span></code>);</li>
<li>Escape characters are not recognized;</li>
<li>Enclosing characters in quotes preserve the literal value of all characters
within the quotes;</li>
<li>Closing quotes separate words (<code class="docutils literal notranslate"><span class="pre">&quot;Do&quot;Separate</span></code> is parsed as <code class="docutils literal notranslate"><span class="pre">&quot;Do&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">Separate</span></code>);</li>
<li>If <a class="reference internal" href="#shlex.shlex.whitespace_split" title="shlex.shlex.whitespace_split"><code class="xref py py-attr docutils literal notranslate"><span class="pre">whitespace_split</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, any character not
declared to be a word character, whitespace, or a quote will be returned as
a single-character token. If it is <code class="docutils literal notranslate"><span class="pre">True</span></code>, <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> will only
split words in whitespaces;</li>
<li>EOF is signaled with an empty string (<code class="docutils literal notranslate"><span class="pre">''</span></code>);</li>
<li>It’s not possible to parse empty strings, even if quoted.</li>
</ul>
<p>When operating in POSIX mode, <a class="reference internal" href="#shlex.shlex" title="shlex.shlex"><code class="xref py py-class docutils literal notranslate"><span class="pre">shlex</span></code></a> will try to obey to the
following parsing rules.</p>
<ul class="simple">
<li>Quotes are stripped out, and do not separate words (<code class="docutils literal notranslate"><span class="pre">&quot;Do&quot;Not&quot;Separate&quot;</span></code> is
parsed as the single word <code class="docutils literal notranslate"><span class="pre">DoNotSeparate</span></code>);</li>
<li>Non-quoted escape characters (e.g. <code class="docutils literal notranslate"><span class="pre">'\'</span></code>) preserve the literal value of the
next character that follows;</li>
<li>Enclosing characters in quotes which are not part of
<a class="reference internal" href="#shlex.shlex.escapedquotes" title="shlex.shlex.escapedquotes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">escapedquotes</span></code></a> (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;'&quot;</span></code>) preserve the literal value
of all characters within the quotes;</li>
<li>Enclosing characters in quotes which are part of
<a class="reference internal" href="#shlex.shlex.escapedquotes" title="shlex.shlex.escapedquotes"><code class="xref py py-attr docutils literal notranslate"><span class="pre">escapedquotes</span></code></a> (e.g. <code class="docutils literal notranslate"><span class="pre">'&quot;'</span></code>) preserves the literal value
of all characters within the quotes, with the exception of the characters
mentioned in <a class="reference internal" href="#shlex.shlex.escape" title="shlex.shlex.escape"><code class="xref py py-attr docutils literal notranslate"><span class="pre">escape</span></code></a>.  The escape characters retain its
special meaning only when followed by the quote in use, or the escape
character itself. Otherwise the escape character will be considered a
normal character.</li>
<li>EOF is signaled with a <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> value;</li>
<li>Quoted empty strings (<code class="docutils literal notranslate"><span class="pre">''</span></code>) are allowed;</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a><ul>
<li><a class="reference internal" href="#shlex-objects">23.2.1. shlex Objects</a></li>
<li><a class="reference internal" href="#parsing-rules">23.2.2. Parsing Rules</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cmd.html"
                        title="previous chapter">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tk.html"
                        title="next chapter">24. Graphical User Interfaces with Tk</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/shlex.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tk.html" title="24. Graphical User Interfaces with Tk"
             >next</a> |</li>
        <li class="right" >
          <a href="cmd.html" title="23.1. cmd — Support for line-oriented command interpreters"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="frameworks.html" >23. Program Frameworks</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�ĭ�����html/library/shutil.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.10. shutil — High-level file operations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.11. dircache — Cached directory listings" href="dircache.html" />
    <link rel="prev" title="10.9. linecache — Random access to text lines" href="linecache.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/shutil.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dircache.html" title="10.11. dircache — Cached directory listings"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="linecache.html" title="10.9. linecache — Random access to text lines"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-shutil">
<span id="shutil-high-level-file-operations"></span><h1>10.10. <a class="reference internal" href="#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> — High-level file operations<a class="headerlink" href="#module-shutil" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/shutil.py">Lib/shutil.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module offers a number of high-level operations on files and
collections of files.  In particular, functions are provided  which support file
copying and removal. For operations on individual files, see also the
<a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Even the higher-level file copying functions (<a class="reference internal" href="#shutil.copy" title="shutil.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy()</span></code></a>,
<a class="reference internal" href="#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy2()</span></code></a>) can’t copy all file metadata.</p>
<p class="last">On POSIX platforms, this means that file owner and group are lost as well
as ACLs.  On Mac OS, the resource fork and other metadata are not used.
This means that resources will be lost and file type and creator codes will
not be correct. On Windows, file owners, ACLs and alternate data streams
are not copied.</p>
</div>
<div class="section" id="directory-and-files-operations">
<span id="file-operations"></span><h2>10.10.1. Directory and files operations<a class="headerlink" href="#directory-and-files-operations" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="shutil.copyfileobj">
<code class="descclassname">shutil.</code><code class="descname">copyfileobj</code><span class="sig-paren">(</span><em>fsrc</em>, <em>fdst</em><span class="optional">[</span>, <em>length</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copyfileobj" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the contents of the file-like object <em>fsrc</em> to the file-like object <em>fdst</em>.
The integer <em>length</em>, if given, is the buffer size. In particular, a negative
<em>length</em> value means to copy the data without looping over the source data in
chunks; by default the data is read in chunks to avoid uncontrolled memory
consumption. Note that if the current file position of the <em>fsrc</em> object is not
0, only the contents from the current file position to the end of the file will
be copied.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.copyfile">
<code class="descclassname">shutil.</code><code class="descname">copyfile</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copyfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the contents (no metadata) of the file named <em>src</em> to a file named
<em>dst</em>.  <em>dst</em> must be the complete target file name; look at
<a class="reference internal" href="#shutil.copy" title="shutil.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy()</span></code></a> for a copy that accepts a target directory path.  If
<em>src</em> and <em>dst</em> are the same files, <a class="reference internal" href="#shutil.Error" title="shutil.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised.
The destination location must be writable; otherwise,  an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception
will be raised. If <em>dst</em> already exists, it will be replaced.   Special files
such as character or block devices and pipes cannot be copied with this
function.  <em>src</em> and <em>dst</em> are path names given as strings.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.copymode">
<code class="descclassname">shutil.</code><code class="descname">copymode</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copymode" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the permission bits from <em>src</em> to <em>dst</em>.  The file contents, owner, and
group are unaffected.  <em>src</em> and <em>dst</em> are path names given as strings.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.copystat">
<code class="descclassname">shutil.</code><code class="descname">copystat</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copystat" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the permission bits, last access time, last modification time, and flags
from <em>src</em> to <em>dst</em>.  The file contents, owner, and group are unaffected.  <em>src</em>
and <em>dst</em> are path names given as strings.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.copy">
<code class="descclassname">shutil.</code><code class="descname">copy</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy the file <em>src</em> to the file or directory <em>dst</em>.  If <em>dst</em> is a directory, a
file with the same basename as <em>src</em>  is created (or overwritten) in the
directory specified.  Permission bits are copied.  <em>src</em> and <em>dst</em> are path
names given as strings.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.copy2">
<code class="descclassname">shutil.</code><code class="descname">copy2</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copy2" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to <a class="reference internal" href="#shutil.copy" title="shutil.copy"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy()</span></code></a> except that <a class="reference internal" href="#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy2()</span></code></a>
also attempts to preserve file metadata.</p>
<p><a class="reference internal" href="#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy2()</span></code></a> uses <a class="reference internal" href="#shutil.copystat" title="shutil.copystat"><code class="xref py py-func docutils literal notranslate"><span class="pre">copystat()</span></code></a> to copy the file metadata.
Please see <a class="reference internal" href="#shutil.copystat" title="shutil.copystat"><code class="xref py py-func docutils literal notranslate"><span class="pre">copystat()</span></code></a> for more information.</p>
</dd></dl>

<dl class="function">
<dt id="shutil.ignore_patterns">
<code class="descclassname">shutil.</code><code class="descname">ignore_patterns</code><span class="sig-paren">(</span><em>*patterns</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.ignore_patterns" title="Permalink to this definition">¶</a></dt>
<dd><p>This factory function creates a function that can be used as a callable for
<a class="reference internal" href="#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>’s <em>ignore</em> argument, ignoring files and directories that
match one of the glob-style <em>patterns</em> provided.  See the example below.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.copytree">
<code class="descclassname">shutil.</code><code class="descname">copytree</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em>, <em>symlinks=False</em>, <em>ignore=None</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.copytree" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively copy an entire directory tree rooted at <em>src</em>.  The destination
directory, named by <em>dst</em>, must not already exist; it will be created as
well as missing parent directories.  Permissions and times of directories
are copied with <a class="reference internal" href="#shutil.copystat" title="shutil.copystat"><code class="xref py py-func docutils literal notranslate"><span class="pre">copystat()</span></code></a>, individual files are copied using
<a class="reference internal" href="#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy2()</span></code></a>.</p>
<p>If <em>symlinks</em> is true, symbolic links in the source tree are represented as
symbolic links in the new tree, but the metadata of the original links is NOT
copied; if false or omitted, the contents and metadata of the linked files
are copied to the new tree.</p>
<p>If <em>ignore</em> is given, it must be a callable that will receive as its
arguments the directory being visited by <a class="reference internal" href="#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>, and a list of its
contents, as returned by <a class="reference internal" href="os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>.  Since <a class="reference internal" href="#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a> is
called recursively, the <em>ignore</em> callable will be called once for each
directory that is copied.  The callable must return a sequence of directory
and file names relative to the current directory (i.e. a subset of the items
in its second argument); these names will then be ignored in the copy
process.  <a class="reference internal" href="#shutil.ignore_patterns" title="shutil.ignore_patterns"><code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code></a> can be used to create such a callable that
ignores names based on glob-style patterns.</p>
<p>If exception(s) occur, an <a class="reference internal" href="#shutil.Error" title="shutil.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised with a list of reasons.</p>
<p>The source code for this should be considered an example rather than the
ultimate tool.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span><a class="reference internal" href="#shutil.Error" title="shutil.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> is raised if any exceptions occur during copying, rather than
printing a message.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Create intermediate directories needed to create <em>dst</em>, rather than raising an
error. Copy permissions and times of directories using <a class="reference internal" href="#shutil.copystat" title="shutil.copystat"><code class="xref py py-func docutils literal notranslate"><span class="pre">copystat()</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the <em>ignore</em> argument to be able to influence what is being copied.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.rmtree">
<code class="descclassname">shutil.</code><code class="descname">rmtree</code><span class="sig-paren">(</span><em>path</em><span class="optional">[</span>, <em>ignore_errors</em><span class="optional">[</span>, <em>onerror</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shutil.rmtree" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Delete an entire directory tree; <em>path</em> must point to a directory (but not a
symbolic link to a directory).  If <em>ignore_errors</em> is true, errors resulting
from failed removals will be ignored; if false or omitted, such errors are
handled by calling a handler specified by <em>onerror</em> or, if that is omitted,
they raise an exception.</p>
<p>If <em>onerror</em> is provided, it must be a callable that accepts three
parameters: <em>function</em>, <em>path</em>, and <em>excinfo</em>. The first parameter,
<em>function</em>, is the function which raised the exception; it will be
<a class="reference internal" href="os.path.html#os.path.islink" title="os.path.islink"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.islink()</span></code></a>, <a class="reference internal" href="os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>, <a class="reference internal" href="os.html#os.remove" title="os.remove"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.remove()</span></code></a> or
<a class="reference internal" href="os.html#os.rmdir" title="os.rmdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.rmdir()</span></code></a>.  The second parameter, <em>path</em>, will be the path name passed
to <em>function</em>.  The third parameter, <em>excinfo</em>, will be the exception
information return by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.  Exceptions raised by <em>onerror</em>
will not be caught.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Explicitly check for <em>path</em> being a symbolic link and raise <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>
in that case.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.move">
<code class="descclassname">shutil.</code><code class="descname">move</code><span class="sig-paren">(</span><em>src</em>, <em>dst</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Recursively move a file or directory (<em>src</em>) to another location (<em>dst</em>).</p>
<p>If the destination is an existing directory, then <em>src</em> is moved inside that
directory. If the destination already exists but is not a directory, it may
be overwritten depending on <a class="reference internal" href="os.html#os.rename" title="os.rename"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.rename()</span></code></a> semantics.</p>
<p>If the destination is on the current filesystem, then <a class="reference internal" href="os.html#os.rename" title="os.rename"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.rename()</span></code></a> is
used.  Otherwise, <em>src</em> is copied (using <a class="reference internal" href="#shutil.copy2" title="shutil.copy2"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copy2()</span></code></a>) to <em>dst</em> and
then removed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="shutil.Error">
<em class="property">exception </em><code class="descclassname">shutil.</code><code class="descname">Error</code><a class="headerlink" href="#shutil.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception collects exceptions that are raised during a multi-file
operation. For <a class="reference internal" href="#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>, the exception argument is a list of 3-tuples
(<em>srcname</em>, <em>dstname</em>, <em>exception</em>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<div class="section" id="copytree-example">
<span id="id1"></span><h3>10.10.1.1. copytree example<a class="headerlink" href="#copytree-example" title="Permalink to this headline">¶</a></h3>
<p>This example is the implementation of the <a class="reference internal" href="#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a> function, described
above, with the docstring omitted.  It demonstrates many of the other functions
provided by this module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">copytree</span><span class="p">(</span><span class="n">src</span><span class="p">,</span> <span class="n">dst</span><span class="p">,</span> <span class="n">symlinks</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">ignore</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="n">names</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">src</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">ignore</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">ignored_names</span> <span class="o">=</span> <span class="n">ignore</span><span class="p">(</span><span class="n">src</span><span class="p">,</span> <span class="n">names</span><span class="p">)</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">ignored_names</span> <span class="o">=</span> <span class="nb">set</span><span class="p">()</span>

    <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">dst</span><span class="p">)</span>
    <span class="n">errors</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">names</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">ignored_names</span><span class="p">:</span>
            <span class="k">continue</span>
        <span class="n">srcname</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">src</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
        <span class="n">dstname</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">dst</span><span class="p">,</span> <span class="n">name</span><span class="p">)</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="k">if</span> <span class="n">symlinks</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">islink</span><span class="p">(</span><span class="n">srcname</span><span class="p">):</span>
                <span class="n">linkto</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">readlink</span><span class="p">(</span><span class="n">srcname</span><span class="p">)</span>
                <span class="n">os</span><span class="o">.</span><span class="n">symlink</span><span class="p">(</span><span class="n">linkto</span><span class="p">,</span> <span class="n">dstname</span><span class="p">)</span>
            <span class="k">elif</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isdir</span><span class="p">(</span><span class="n">srcname</span><span class="p">):</span>
                <span class="n">copytree</span><span class="p">(</span><span class="n">srcname</span><span class="p">,</span> <span class="n">dstname</span><span class="p">,</span> <span class="n">symlinks</span><span class="p">,</span> <span class="n">ignore</span><span class="p">)</span>
            <span class="k">else</span><span class="p">:</span>
                <span class="n">copy2</span><span class="p">(</span><span class="n">srcname</span><span class="p">,</span> <span class="n">dstname</span><span class="p">)</span>
            <span class="c1"># XXX What about devices, sockets etc.?</span>
        <span class="k">except</span> <span class="p">(</span><span class="ne">IOError</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">error</span><span class="p">)</span> <span class="k">as</span> <span class="n">why</span><span class="p">:</span>
            <span class="n">errors</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">srcname</span><span class="p">,</span> <span class="n">dstname</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">why</span><span class="p">)))</span>
        <span class="c1"># catch the Error from the recursive copytree so that we can</span>
        <span class="c1"># continue with other files</span>
        <span class="k">except</span> <span class="n">Error</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
            <span class="n">errors</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">err</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">copystat</span><span class="p">(</span><span class="n">src</span><span class="p">,</span> <span class="n">dst</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">WindowsError</span><span class="p">:</span>
        <span class="c1"># can&#39;t copy file access times on Windows</span>
        <span class="k">pass</span>
    <span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">why</span><span class="p">:</span>
        <span class="n">errors</span><span class="o">.</span><span class="n">extend</span><span class="p">((</span><span class="n">src</span><span class="p">,</span> <span class="n">dst</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">why</span><span class="p">)))</span>
    <span class="k">if</span> <span class="n">errors</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">Error</span><span class="p">(</span><span class="n">errors</span><span class="p">)</span>
</pre></div>
</div>
<p>Another example that uses the <a class="reference internal" href="#shutil.ignore_patterns" title="shutil.ignore_patterns"><code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code></a> helper:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">shutil</span> <span class="k">import</span> <span class="n">copytree</span><span class="p">,</span> <span class="n">ignore_patterns</span>

<span class="n">copytree</span><span class="p">(</span><span class="n">source</span><span class="p">,</span> <span class="n">destination</span><span class="p">,</span> <span class="n">ignore</span><span class="o">=</span><span class="n">ignore_patterns</span><span class="p">(</span><span class="s1">&#39;*.pyc&#39;</span><span class="p">,</span> <span class="s1">&#39;tmp*&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>This will copy everything except <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files and files or directories whose
name starts with <code class="docutils literal notranslate"><span class="pre">tmp</span></code>.</p>
<p>Another example that uses the <em>ignore</em> argument to add a logging call:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">shutil</span> <span class="k">import</span> <span class="n">copytree</span>
<span class="kn">import</span> <span class="nn">logging</span>

<span class="k">def</span> <span class="nf">_logpath</span><span class="p">(</span><span class="n">path</span><span class="p">,</span> <span class="n">names</span><span class="p">):</span>
    <span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Working in </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">path</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">[]</span>   <span class="c1"># nothing will be ignored</span>

<span class="n">copytree</span><span class="p">(</span><span class="n">source</span><span class="p">,</span> <span class="n">destination</span><span class="p">,</span> <span class="n">ignore</span><span class="o">=</span><span class="n">_logpath</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="archiving-operations">
<span id="id2"></span><h2>10.10.2. Archiving operations<a class="headerlink" href="#archiving-operations" title="Permalink to this headline">¶</a></h2>
<p>High-level utilities to create and read compressed and archived files are also
provided.  They rely on the <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> and <a class="reference internal" href="tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> modules.</p>
<dl class="function">
<dt id="shutil.make_archive">
<code class="descclassname">shutil.</code><code class="descname">make_archive</code><span class="sig-paren">(</span><em>base_name</em>, <em>format</em><span class="optional">[</span>, <em>root_dir</em><span class="optional">[</span>, <em>base_dir</em><span class="optional">[</span>, <em>verbose</em><span class="optional">[</span>, <em>dry_run</em><span class="optional">[</span>, <em>owner</em><span class="optional">[</span>, <em>group</em><span class="optional">[</span>, <em>logger</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shutil.make_archive" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an archive file (eg. zip or tar) and returns its name.</p>
<p><em>base_name</em> is the name of the file to create, including the path, minus
any format-specific extension. <em>format</em> is the archive format: one of
“zip” (if the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module or external <code class="docutils literal notranslate"><span class="pre">zip</span></code> executable is
available), “tar”, “gztar” (if the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module is available), or
“bztar” (if the <a class="reference internal" href="bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> module is available).</p>
<p><em>root_dir</em> is a directory that will be the root directory of the
archive; ie. we typically chdir into <em>root_dir</em> before creating the
archive.</p>
<p><em>base_dir</em> is the directory where we start archiving from;
ie. <em>base_dir</em> will be the common prefix of all files and
directories in the archive.</p>
<p><em>root_dir</em> and <em>base_dir</em> both default to the current directory.</p>
<p><em>owner</em> and <em>group</em> are used when creating a tar archive. By default,
uses the current owner and group.</p>
<p><em>logger</em> must be an object compatible with <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a>, usually an instance of
<a class="reference internal" href="logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">logging.Logger</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.get_archive_formats">
<code class="descclassname">shutil.</code><code class="descname">get_archive_formats</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#shutil.get_archive_formats" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of supported formats for archiving.
Each element of the returned sequence is a tuple <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">description)</span></code>.</p>
<p>By default <a class="reference internal" href="#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> provides these formats:</p>
<ul class="simple">
<li><em>zip</em>: ZIP file (if the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module or external <code class="docutils literal notranslate"><span class="pre">zip</span></code>
executable is available).</li>
<li><em>tar</em>: uncompressed tar file.</li>
<li><em>gztar</em>: gzip’ed tar-file (if the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module is available).</li>
<li><em>bztar</em>: bzip2’ed tar-file (if the <a class="reference internal" href="bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> module is available).</li>
</ul>
<p>You can register new formats or provide your own archiver for any existing
formats, by using <a class="reference internal" href="#shutil.register_archive_format" title="shutil.register_archive_format"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_archive_format()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.register_archive_format">
<code class="descclassname">shutil.</code><code class="descname">register_archive_format</code><span class="sig-paren">(</span><em>name</em>, <em>function</em><span class="optional">[</span>, <em>extra_args</em><span class="optional">[</span>, <em>description</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#shutil.register_archive_format" title="Permalink to this definition">¶</a></dt>
<dd><p>Register an archiver for the format <em>name</em>. <em>function</em> is a callable that
will be used to invoke the archiver.</p>
<p>If given, <em>extra_args</em> is a sequence of <code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> that will be
used as extra keywords arguments when the archiver callable is used.</p>
<p><em>description</em> is used by <a class="reference internal" href="#shutil.get_archive_formats" title="shutil.get_archive_formats"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_archive_formats()</span></code></a> which returns the
list of archivers. Defaults to an empty list.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="shutil.unregister_archive_format">
<code class="descclassname">shutil.</code><code class="descname">unregister_archive_format</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#shutil.unregister_archive_format" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the archive format <em>name</em> from the list of supported formats.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<div class="section" id="archiving-example">
<span id="id3"></span><h3>10.10.2.1. Archiving example<a class="headerlink" href="#archiving-example" title="Permalink to this headline">¶</a></h3>
<p>In this example, we create a gzip’ed tar-file archive containing all files
found in the <code class="file docutils literal notranslate"><span class="pre">.ssh</span></code> directory of the user:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">shutil</span> <span class="k">import</span> <span class="n">make_archive</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">archive_name</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;~&#39;</span><span class="p">,</span> <span class="s1">&#39;myarchive&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">root_dir</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="s1">&#39;~&#39;</span><span class="p">,</span> <span class="s1">&#39;.ssh&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">make_archive</span><span class="p">(</span><span class="n">archive_name</span><span class="p">,</span> <span class="s1">&#39;gztar&#39;</span><span class="p">,</span> <span class="n">root_dir</span><span class="p">)</span>
<span class="go">&#39;/Users/tarek/myarchive.tar.gz&#39;</span>
</pre></div>
</div>
<p>The resulting archive contains:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> tar -tzvf /Users/tarek/myarchive.tar.gz
<span class="go">drwx------ tarek/staff       0 2010-02-01 16:23:40 ./</span>
<span class="go">-rw-r--r-- tarek/staff     609 2008-06-09 13:26:54 ./authorized_keys</span>
<span class="go">-rwxr-xr-x tarek/staff      65 2008-06-09 13:26:54 ./config</span>
<span class="go">-rwx------ tarek/staff     668 2008-06-09 13:26:54 ./id_dsa</span>
<span class="go">-rwxr-xr-x tarek/staff     609 2008-06-09 13:26:54 ./id_dsa.pub</span>
<span class="go">-rw------- tarek/staff    1675 2008-06-09 13:26:54 ./id_rsa</span>
<span class="go">-rw-r--r-- tarek/staff     397 2008-06-09 13:26:54 ./id_rsa.pub</span>
<span class="go">-rw-r--r-- tarek/staff   37192 2010-02-06 18:23:10 ./known_hosts</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a><ul>
<li><a class="reference internal" href="#directory-and-files-operations">10.10.1. Directory and files operations</a><ul>
<li><a class="reference internal" href="#copytree-example">10.10.1.1. copytree example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#archiving-operations">10.10.2. Archiving operations</a><ul>
<li><a class="reference internal" href="#archiving-example">10.10.2.1. Archiving example</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="linecache.html"
                        title="previous chapter">10.9. <code class="docutils literal notranslate"><span class="pre">linecache</span></code> — Random access to text lines</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dircache.html"
                        title="next chapter">10.11. <code class="docutils literal notranslate"><span class="pre">dircache</span></code> — Cached directory listings</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/shutil.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dircache.html" title="10.11. dircache — Cached directory listings"
             >next</a> |</li>
        <li class="right" >
          <a href="linecache.html" title="10.9. linecache — Random access to text lines"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\םr���html/library/signal.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.4. signal — Set handlers for asynchronous events &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.5. popen2 — Subprocesses with accessible I/O streams" href="popen2.html" />
    <link rel="prev" title="17.3. ssl — TLS/SSL wrapper for socket objects" href="ssl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/signal.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="popen2.html" title="17.5. popen2 — Subprocesses with accessible I/O streams"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="17.3. ssl — TLS/SSL wrapper for socket objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-signal">
<span id="signal-set-handlers-for-asynchronous-events"></span><h1>17.4. <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> — Set handlers for asynchronous events<a class="headerlink" href="#module-signal" title="Permalink to this headline">¶</a></h1>
<p>This module provides mechanisms to use signal handlers in Python. Some general
rules for working with signals and their handlers:</p>
<ul class="simple">
<li>A handler for a particular signal, once set, remains installed until it is
explicitly reset (Python emulates the BSD style interface regardless of the
underlying implementation), with the exception of the handler for
<code class="xref py py-const docutils literal notranslate"><span class="pre">SIGCHLD</span></code>, which follows the underlying implementation.</li>
<li>There is no way to “block” signals temporarily from critical sections (since
this is not supported by all Unix flavors).</li>
<li>Although Python signal handlers are called asynchronously as far as the Python
user is concerned, they can only occur between the “atomic” instructions of the
Python interpreter.  This means that signals arriving during long calculations
implemented purely in C (such as regular expression matches on large bodies of
text) may be delayed for an arbitrary amount of time.</li>
<li>When a signal arrives during an I/O operation, it is possible that the I/O
operation raises an exception after the signal handler returns. This is
dependent on the underlying Unix system’s semantics regarding interrupted system
calls.</li>
<li>Because the C signal handler always returns, it makes little sense to catch
synchronous errors like <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code> or <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGSEGV</span></code>.</li>
<li>Python installs a small number of signal handlers by default: <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGPIPE</span></code>
is ignored (so write errors on pipes and sockets can be reported as ordinary
Python exceptions) and <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGINT</span></code> is translated into a
<a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.  All of these can be overridden.</li>
<li>Some care must be taken if both signals and threads are used in the same
program.  The fundamental thing to remember in using signals and threads
simultaneously is: always perform <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-func docutils literal notranslate"><span class="pre">signal()</span></code></a> operations in the main thread
of execution.  Any thread can perform an <a class="reference internal" href="#signal.alarm" title="signal.alarm"><code class="xref py py-func docutils literal notranslate"><span class="pre">alarm()</span></code></a>, <a class="reference internal" href="#signal.getsignal" title="signal.getsignal"><code class="xref py py-func docutils literal notranslate"><span class="pre">getsignal()</span></code></a>,
<a class="reference internal" href="#signal.pause" title="signal.pause"><code class="xref py py-func docutils literal notranslate"><span class="pre">pause()</span></code></a>, <a class="reference internal" href="#signal.setitimer" title="signal.setitimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code></a> or <a class="reference internal" href="#signal.getitimer" title="signal.getitimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">getitimer()</span></code></a>; only the main thread
can set a new signal handler, and the main thread will be the only one to
receive signals (this is enforced by the Python <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module, even
if the underlying thread implementation supports sending signals to
individual threads).  This means that signals can’t be used as a means of
inter-thread communication.  Use locks instead.</li>
</ul>
<p>The variables defined in the <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module are:</p>
<dl class="data">
<dt id="signal.SIG_DFL">
<code class="descclassname">signal.</code><code class="descname">SIG_DFL</code><a class="headerlink" href="#signal.SIG_DFL" title="Permalink to this definition">¶</a></dt>
<dd><p>This is one of two standard signal handling options; it will simply perform
the default function for the signal.  For example, on most systems the
default action for <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGQUIT</span></code> is to dump core and exit, while the
default action for <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGCHLD</span></code> is to simply ignore it.</p>
</dd></dl>

<dl class="data">
<dt id="signal.SIG_IGN">
<code class="descclassname">signal.</code><code class="descname">SIG_IGN</code><a class="headerlink" href="#signal.SIG_IGN" title="Permalink to this definition">¶</a></dt>
<dd><p>This is another standard signal handler, which will simply ignore the given
signal.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">SIG*</code></dt>
<dd><p>All the signal numbers are defined symbolically.  For example, the hangup signal
is defined as <code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGHUP</span></code>; the variable names are identical to the
names used in C programs, as found in <code class="docutils literal notranslate"><span class="pre">&lt;signal.h&gt;</span></code>. The Unix man page for
‘<code class="xref c c-func docutils literal notranslate"><span class="pre">signal()</span></code>’ lists the existing signals (on some systems this is
<em class="manpage">signal(2)</em>, on others the list is in <em class="manpage">signal(7)</em>). Note that
not all systems define the same set of signal names; only those names defined by
the system are defined by this module.</p>
</dd></dl>

<dl class="data">
<dt id="signal.CTRL_C_EVENT">
<code class="descclassname">signal.</code><code class="descname">CTRL_C_EVENT</code><a class="headerlink" href="#signal.CTRL_C_EVENT" title="Permalink to this definition">¶</a></dt>
<dd><p>The signal corresponding to the <kbd class="kbd docutils literal notranslate">Ctrl+C</kbd> keystroke event. This signal can
only be used with <a class="reference internal" href="os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a>.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="signal.CTRL_BREAK_EVENT">
<code class="descclassname">signal.</code><code class="descname">CTRL_BREAK_EVENT</code><a class="headerlink" href="#signal.CTRL_BREAK_EVENT" title="Permalink to this definition">¶</a></dt>
<dd><p>The signal corresponding to the <kbd class="kbd docutils literal notranslate">Ctrl+Break</kbd> keystroke event. This signal can
only be used with <a class="reference internal" href="os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a>.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="signal.NSIG">
<code class="descclassname">signal.</code><code class="descname">NSIG</code><a class="headerlink" href="#signal.NSIG" title="Permalink to this definition">¶</a></dt>
<dd><p>One more than the number of the highest signal number.</p>
</dd></dl>

<dl class="data">
<dt id="signal.ITIMER_REAL">
<code class="descclassname">signal.</code><code class="descname">ITIMER_REAL</code><a class="headerlink" href="#signal.ITIMER_REAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrements interval timer in real time, and delivers <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGALRM</span></code> upon expiration.</p>
</dd></dl>

<dl class="data">
<dt id="signal.ITIMER_VIRTUAL">
<code class="descclassname">signal.</code><code class="descname">ITIMER_VIRTUAL</code><a class="headerlink" href="#signal.ITIMER_VIRTUAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrements interval timer only when the process is executing, and delivers
SIGVTALRM upon expiration.</p>
</dd></dl>

<dl class="data">
<dt id="signal.ITIMER_PROF">
<code class="descclassname">signal.</code><code class="descname">ITIMER_PROF</code><a class="headerlink" href="#signal.ITIMER_PROF" title="Permalink to this definition">¶</a></dt>
<dd><p>Decrements interval timer both when the process executes and when the
system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL,
this timer is usually used to profile the time spent by the application
in user and kernel space. SIGPROF is delivered upon expiration.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module defines one exception:</p>
<dl class="exception">
<dt id="signal.ItimerError">
<em class="property">exception </em><code class="descclassname">signal.</code><code class="descname">ItimerError</code><a class="headerlink" href="#signal.ItimerError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised to signal an error from the underlying <a class="reference internal" href="#signal.setitimer" title="signal.setitimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code></a> or
<a class="reference internal" href="#signal.getitimer" title="signal.getitimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">getitimer()</span></code></a> implementation. Expect this error if an invalid
interval timer or a negative time is passed to <a class="reference internal" href="#signal.setitimer" title="signal.setitimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code></a>.
This error is a subtype of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="signal.alarm">
<code class="descclassname">signal.</code><code class="descname">alarm</code><span class="sig-paren">(</span><em>time</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.alarm" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>time</em> is non-zero, this function requests that a <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGALRM</span></code> signal be
sent to the process in <em>time</em> seconds. Any previously scheduled alarm is
canceled (only one alarm can be scheduled at any time).  The returned value is
then the number of seconds before any previously set alarm was to have been
delivered. If <em>time</em> is zero, no alarm is scheduled, and any scheduled alarm is
canceled.  If the return value is zero, no alarm is currently scheduled.  (See
the Unix man page <em class="manpage">alarm(2)</em>.) Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="signal.getsignal">
<code class="descclassname">signal.</code><code class="descname">getsignal</code><span class="sig-paren">(</span><em>signalnum</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.getsignal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current signal handler for the signal <em>signalnum</em>. The returned value
may be a callable Python object, or one of the special values
<a class="reference internal" href="#signal.SIG_IGN" title="signal.SIG_IGN"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_IGN</span></code></a>, <a class="reference internal" href="#signal.SIG_DFL" title="signal.SIG_DFL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_DFL</span></code></a> or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.  Here,
<a class="reference internal" href="#signal.SIG_IGN" title="signal.SIG_IGN"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_IGN</span></code></a> means that the signal was previously ignored,
<a class="reference internal" href="#signal.SIG_DFL" title="signal.SIG_DFL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_DFL</span></code></a> means that the default way of handling the signal was
previously in use, and <code class="docutils literal notranslate"><span class="pre">None</span></code> means that the previous signal handler was not
installed from Python.</p>
</dd></dl>

<dl class="function">
<dt id="signal.pause">
<code class="descclassname">signal.</code><code class="descname">pause</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#signal.pause" title="Permalink to this definition">¶</a></dt>
<dd><p>Cause the process to sleep until a signal is received; the appropriate handler
will then be called.  Returns nothing.  Not on Windows. (See the Unix man page
<em class="manpage">signal(2)</em>.)</p>
</dd></dl>

<dl class="function">
<dt id="signal.setitimer">
<code class="descclassname">signal.</code><code class="descname">setitimer</code><span class="sig-paren">(</span><em>which</em>, <em>seconds</em><span class="optional">[</span>, <em>interval</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#signal.setitimer" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets given interval timer (one of <a class="reference internal" href="#signal.ITIMER_REAL" title="signal.ITIMER_REAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_REAL</span></code></a>,
<a class="reference internal" href="#signal.ITIMER_VIRTUAL" title="signal.ITIMER_VIRTUAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_VIRTUAL</span></code></a> or <a class="reference internal" href="#signal.ITIMER_PROF" title="signal.ITIMER_PROF"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_PROF</span></code></a>) specified
by <em>which</em> to fire after <em>seconds</em> (float is accepted, different from
<a class="reference internal" href="#signal.alarm" title="signal.alarm"><code class="xref py py-func docutils literal notranslate"><span class="pre">alarm()</span></code></a>) and after that every <em>interval</em> seconds. The interval
timer specified by <em>which</em> can be cleared by setting seconds to zero.</p>
<p>When an interval timer fires, a signal is sent to the process.
The signal sent is dependent on the timer being used;
<a class="reference internal" href="#signal.ITIMER_REAL" title="signal.ITIMER_REAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_REAL</span></code></a> will deliver <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGALRM</span></code>,
<a class="reference internal" href="#signal.ITIMER_VIRTUAL" title="signal.ITIMER_VIRTUAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_VIRTUAL</span></code></a> sends <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGVTALRM</span></code>,
and <a class="reference internal" href="#signal.ITIMER_PROF" title="signal.ITIMER_PROF"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.ITIMER_PROF</span></code></a> will deliver <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGPROF</span></code>.</p>
<p>The old values are returned as a tuple: (delay, interval).</p>
<p>Attempting to pass an invalid interval timer will cause an
<a class="reference internal" href="#signal.ItimerError" title="signal.ItimerError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ItimerError</span></code></a>.  Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="signal.getitimer">
<code class="descclassname">signal.</code><code class="descname">getitimer</code><span class="sig-paren">(</span><em>which</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.getitimer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns current value of a given interval timer specified by <em>which</em>.
Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="signal.set_wakeup_fd">
<code class="descclassname">signal.</code><code class="descname">set_wakeup_fd</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.set_wakeup_fd" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the wakeup fd to <em>fd</em>.  When a signal is received, a <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> byte is
written to the fd.  This can be used by a library to wakeup a poll or select
call, allowing the signal to be fully processed.</p>
<p>The old wakeup fd is returned (or -1 if file descriptor wakeup was not
enabled).  If <em>fd</em> is -1, file descriptor wakeup is disabled.
If not -1, <em>fd</em> must be non-blocking.  It is up to the library to remove
any bytes from <em>fd</em> before calling poll or select again.</p>
<p>When threads are enabled, this function can only be called from the main thread;
attempting to call it from other threads will cause a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
exception to be raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="signal.siginterrupt">
<code class="descclassname">signal.</code><code class="descname">siginterrupt</code><span class="sig-paren">(</span><em>signalnum</em>, <em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.siginterrupt" title="Permalink to this definition">¶</a></dt>
<dd><p>Change system call restart behaviour: if <em>flag</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, system
calls will be restarted when interrupted by signal <em>signalnum</em>, otherwise
system calls will be interrupted.  Returns nothing.  Availability: Unix (see
the man page <em class="manpage">siginterrupt(3)</em> for further information).</p>
<p>Note that installing a signal handler with <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-func docutils literal notranslate"><span class="pre">signal()</span></code></a> will reset the
restart behaviour to interruptible by implicitly calling
<code class="xref c c-func docutils literal notranslate"><span class="pre">siginterrupt()</span></code> with a true <em>flag</em> value for the given signal.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="signal.signal">
<code class="descclassname">signal.</code><code class="descname">signal</code><span class="sig-paren">(</span><em>signalnum</em>, <em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#signal.signal" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the handler for signal <em>signalnum</em> to the function <em>handler</em>.  <em>handler</em> can
be a callable Python object taking two arguments (see below), or one of the
special values <a class="reference internal" href="#signal.SIG_IGN" title="signal.SIG_IGN"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_IGN</span></code></a> or <a class="reference internal" href="#signal.SIG_DFL" title="signal.SIG_DFL"><code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIG_DFL</span></code></a>.  The previous
signal handler will be returned (see the description of <a class="reference internal" href="#signal.getsignal" title="signal.getsignal"><code class="xref py py-func docutils literal notranslate"><span class="pre">getsignal()</span></code></a>
above).  (See the Unix man page <em class="manpage">signal(2)</em>.)</p>
<p>When threads are enabled, this function can only be called from the main thread;
attempting to call it from other threads will cause a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
exception to be raised.</p>
<p>The <em>handler</em> is called with two arguments: the signal number and the current
stack frame (<code class="docutils literal notranslate"><span class="pre">None</span></code> or a frame object; for a description of frame objects,
see the <a class="reference internal" href="../reference/datamodel.html#frame-objects"><span class="std std-ref">description in the type hierarchy</span></a> or see the
attribute descriptions in the <a class="reference internal" href="inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module).</p>
<p>On Windows, <a class="reference internal" href="#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-func docutils literal notranslate"><span class="pre">signal()</span></code></a> can only be called with <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGABRT</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">SIGFPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGILL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGINT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGSEGV</span></code>, or
<code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code>. A <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised in any other case.</p>
</dd></dl>

<div class="section" id="example">
<span id="signal-example"></span><h2>17.4.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>Here is a minimal example program. It uses the <a class="reference internal" href="#signal.alarm" title="signal.alarm"><code class="xref py py-func docutils literal notranslate"><span class="pre">alarm()</span></code></a> function to limit
the time spent waiting to open a file; this is useful if the file is for a
serial device that may not be turned on, which would normally cause the
<a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> to hang indefinitely.  The solution is to set a 5-second alarm
before opening the file; if the operation takes too long, the alarm signal will
be sent, and the handler raises an exception.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">signal</span><span class="o">,</span> <span class="nn">os</span>

<span class="k">def</span> <span class="nf">handler</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;Signal handler called with signal&#39;</span><span class="p">,</span> <span class="n">signum</span>
    <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s2">&quot;Couldn&#39;t open device!&quot;</span><span class="p">)</span>

<span class="c1"># Set the signal handler and a 5-second alarm</span>
<span class="n">signal</span><span class="o">.</span><span class="n">signal</span><span class="p">(</span><span class="n">signal</span><span class="o">.</span><span class="n">SIGALRM</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span>
<span class="n">signal</span><span class="o">.</span><span class="n">alarm</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>

<span class="c1"># This open() may hang indefinitely</span>
<span class="n">fd</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;/dev/ttyS0&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">O_RDWR</span><span class="p">)</span>

<span class="n">signal</span><span class="o">.</span><span class="n">alarm</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>          <span class="c1"># Disable the alarm</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a><ul>
<li><a class="reference internal" href="#example">17.4.1. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="ssl.html"
                        title="previous chapter">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="popen2.html"
                        title="next chapter">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/signal.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="popen2.html" title="17.5. popen2 — Subprocesses with accessible I/O streams"
             >next</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="17.3. ssl — TLS/SSL wrapper for socket objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���OO"html/library/simplehttpserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.19. SimpleHTTPServer — Simple HTTP request handler &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler" href="cgihttpserver.html" />
    <link rel="prev" title="20.18. BaseHTTPServer — Basic HTTP server" href="basehttpserver.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/simplehttpserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgihttpserver.html" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="basehttpserver.html" title="20.18. BaseHTTPServer — Basic HTTP server"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-SimpleHTTPServer">
<span id="simplehttpserver-simple-http-request-handler"></span><h1>20.19. <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> — Simple HTTP request handler<a class="headerlink" href="#module-SimpleHTTPServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module has been merged into <code class="xref py py-mod docutils literal notranslate"><span class="pre">http.server</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">mod:<cite>SimpleHTTServer</cite> is not recommended for production. It only implements
basic security checks.</p>
</div>
<p>The <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module defines a single class,
<a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPRequestHandler</span></code></a>, which is interface-compatible with
<a class="reference internal" href="basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler</span></code></a>.</p>
<p>The <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module defines the following class:</p>
<dl class="class">
<dt id="SimpleHTTPServer.SimpleHTTPRequestHandler">
<em class="property">class </em><code class="descclassname">SimpleHTTPServer.</code><code class="descname">SimpleHTTPRequestHandler</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em>, <em>server</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleHTTPServer.SimpleHTTPRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This class serves files from the current directory and below, directly
mapping the directory structure to HTTP requests.</p>
<p>A lot of the work, such as parsing the request, is done by the base class
<a class="reference internal" href="basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler</span></code></a>.  This class implements the
<a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET" title="SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET"><code class="xref py py-func docutils literal notranslate"><span class="pre">do_GET()</span></code></a> and <a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD" title="SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD"><code class="xref py py-func docutils literal notranslate"><span class="pre">do_HEAD()</span></code></a> functions.</p>
<p>The following are defined as class-level attributes of
<a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPRequestHandler</span></code></a>:</p>
<dl class="attribute">
<dt id="SimpleHTTPServer.SimpleHTTPRequestHandler.server_version">
<code class="descname">server_version</code><a class="headerlink" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.server_version" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<p>This will be <code class="docutils literal notranslate"><span class="pre">&quot;SimpleHTTP/&quot;</span> <span class="pre">+</span> <span class="pre">__version__</span></code>, where <code class="docutils literal notranslate"><span class="pre">__version__</span></code> is
defined at the module level.</p>
<dl class="attribute">
<dt id="SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map">
<code class="descname">extensions_map</code><a class="headerlink" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary mapping suffixes into MIME types. The default is
signified by an empty string, and is considered to be
<code class="docutils literal notranslate"><span class="pre">application/octet-stream</span></code>. The mapping is used case-insensitively,
and so should contain only lower-cased keys.</p>
</dd></dl>

<p>The <a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPRequestHandler</span></code></a> class defines the following methods:</p>
<dl class="method">
<dt id="SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD">
<code class="descname">do_HEAD</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD" title="Permalink to this definition">¶</a></dt>
<dd><p>This method serves the <code class="docutils literal notranslate"><span class="pre">'HEAD'</span></code> request type: it sends the headers it
would send for the equivalent <code class="docutils literal notranslate"><span class="pre">GET</span></code> request. See the <a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET" title="SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET"><code class="xref py py-meth docutils literal notranslate"><span class="pre">do_GET()</span></code></a>
method for a more complete explanation of the possible headers.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET">
<code class="descname">do_GET</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET" title="Permalink to this definition">¶</a></dt>
<dd><p>The request is mapped to a local file by interpreting the request as a
path relative to the current working directory.</p>
<p>If the request was mapped to a directory, the directory is checked for a
file named <code class="docutils literal notranslate"><span class="pre">index.html</span></code> or <code class="docutils literal notranslate"><span class="pre">index.htm</span></code> (in that order). If found, the
file’s contents are returned; otherwise a directory listing is generated
by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list_directory()</span></code> method. This method uses
<a class="reference internal" href="os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> to scan the directory, and returns a <code class="docutils literal notranslate"><span class="pre">404</span></code> error
response if the <code class="xref py py-func docutils literal notranslate"><span class="pre">listdir()</span></code> fails.</p>
<p>If the request was mapped to a file, it is opened and the contents are
returned.  Any <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception in opening the requested file is
mapped to a <code class="docutils literal notranslate"><span class="pre">404</span></code>, <code class="docutils literal notranslate"><span class="pre">'File</span> <span class="pre">not</span> <span class="pre">found'</span></code> error. Otherwise, the content
type is guessed by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">guess_type()</span></code> method, which in turn
uses the <em>extensions_map</em> variable.</p>
<p>A <code class="docutils literal notranslate"><span class="pre">'Content-type:'</span></code> header with the guessed content type is output,
followed by a <code class="docutils literal notranslate"><span class="pre">'Content-Length:'</span></code> header with the file’s size and a
<code class="docutils literal notranslate"><span class="pre">'Last-Modified:'</span></code> header with the file’s modification time.</p>
<p>Then follows a blank line signifying the end of the headers, and then the
contents of the file are output. If the file’s MIME type starts with
<code class="docutils literal notranslate"><span class="pre">text/</span></code> the file is opened in text mode; otherwise binary mode is used.</p>
<p>The <a class="reference internal" href="test.html#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-func docutils literal notranslate"><span class="pre">test()</span></code></a> function in the <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module is an
example which creates a server using the <a class="reference internal" href="#SimpleHTTPServer.SimpleHTTPRequestHandler" title="SimpleHTTPServer.SimpleHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHTTPRequestHandler</span></code></a>
as the Handler.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>The <code class="docutils literal notranslate"><span class="pre">'Last-Modified'</span></code> header.</p>
</div>
</dd></dl>

</dd></dl>

<p>The <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module can be used in the following manner in order
to set up a very basic web server serving files relative to the current
directory.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">SimpleHTTPServer</span>
<span class="kn">import</span> <span class="nn">SocketServer</span>

<span class="n">PORT</span> <span class="o">=</span> <span class="mi">8000</span>

<span class="n">Handler</span> <span class="o">=</span> <span class="n">SimpleHTTPServer</span><span class="o">.</span><span class="n">SimpleHTTPRequestHandler</span>

<span class="n">httpd</span> <span class="o">=</span> <span class="n">SocketServer</span><span class="o">.</span><span class="n">TCPServer</span><span class="p">((</span><span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="n">PORT</span><span class="p">),</span> <span class="n">Handler</span><span class="p">)</span>

<span class="nb">print</span> <span class="s2">&quot;serving at port&quot;</span><span class="p">,</span> <span class="n">PORT</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-SimpleHTTPServer" title="SimpleHTTPServer: This module provides a basic request handler for HTTP servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code></a> module can also be invoked directly using the
<a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch of the interpreter with a <code class="docutils literal notranslate"><span class="pre">port</span> <span class="pre">number</span></code> argument.
Similar to the previous example, this serves the files relative to the
current directory.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">SimpleHTTPServer</span> <span class="mi">8000</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="basehttpserver.html#module-BaseHTTPServer" title="BaseHTTPServer: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code></a></dt>
<dd>Base class implementation for Web server and request handler.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="basehttpserver.html"
                        title="previous chapter">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cgihttpserver.html"
                        title="next chapter">20.20. <code class="docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code> — CGI-capable HTTP request handler</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/simplehttpserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgihttpserver.html" title="20.20. CGIHTTPServer — CGI-capable HTTP request handler"
             >next</a> |</li>
        <li class="right" >
          <a href="basehttpserver.html" title="20.18. BaseHTTPServer — Basic HTTP server"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\]��$����$html/library/simplexmlrpcserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.24. SimpleXMLRPCServer — Basic XML-RPC server &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server" href="docxmlrpcserver.html" />
    <link rel="prev" title="20.23. xmlrpclib — XML-RPC client access" href="xmlrpclib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/simplexmlrpcserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="docxmlrpcserver.html" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xmlrpclib.html" title="20.23. xmlrpclib — XML-RPC client access"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-SimpleXMLRPCServer">
<span id="simplexmlrpcserver-basic-xml-rpc-server"></span><h1>20.24. <a class="reference internal" href="#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> — Basic XML-RPC server<a class="headerlink" href="#module-SimpleXMLRPCServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> module has been merged into
<code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.server</span></code> in Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically
adapt imports when converting your sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/SimpleXMLRPCServer.py">Lib/SimpleXMLRPCServer.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> module provides a basic server framework for
XML-RPC servers written in Python.  Servers can either be free standing, using
<a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a>, or embedded in a CGI environment, using
<a class="reference internal" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler" title="SimpleXMLRPCServer.CGIXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIXMLRPCRequestHandler</span></code></a>.</p>
<dl class="class">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCServer">
<em class="property">class </em><code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">SimpleXMLRPCServer</code><span class="sig-paren">(</span><em>addr[, requestHandler[, logRequests[, allow_none[, encoding[, bind_and_activate]]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCServer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new server instance.  This class provides methods for registration of
functions that can be called by the XML-RPC protocol.  The <em>requestHandler</em>
parameter should be a factory for request handler instances; it defaults to
<a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler" title="SimpleXMLRPCServer.SimpleXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCRequestHandler</span></code></a>.  The <em>addr</em> and <em>requestHandler</em> parameters
are passed to the <a class="reference internal" href="socketserver.html#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code></a> constructor.  If <em>logRequests</em>
is true (the default), requests will be logged; setting this parameter to false
will turn off logging.   The <em>allow_none</em> and <em>encoding</em> parameters are passed
on to  <a class="reference internal" href="xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> and control the XML-RPC responses that will be returned
from the server. The <em>bind_and_activate</em> parameter controls whether
<code class="xref py py-meth docutils literal notranslate"><span class="pre">server_bind()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">server_activate()</span></code> are called immediately by the
constructor; it defaults to true. Setting it to false allows code to manipulate
the <em>allow_reuse_address</em> class variable before the address is bound.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>allow_none</em> and <em>encoding</em> parameters were added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <em>bind_and_activate</em> parameter was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler">
<em class="property">class </em><code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">CGIXMLRPCRequestHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>allow_none</em><span class="optional">[</span>, <em>encoding</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new instance to handle XML-RPC requests in a CGI environment.  The
<em>allow_none</em> and <em>encoding</em> parameters are passed on to  <a class="reference internal" href="xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> and
control the XML-RPC responses that will be returned  from the server.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>allow_none</em> and <em>encoding</em> parameters were added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCRequestHandler">
<em class="property">class </em><code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">SimpleXMLRPCRequestHandler</code><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new request handler instance.  This request handler supports <code class="docutils literal notranslate"><span class="pre">POST</span></code>
requests and modifies logging so that the <em>logRequests</em> parameter to the
<a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> constructor parameter is honored.</p>
</dd></dl>

<div class="section" id="simplexmlrpcserver-objects">
<span id="simple-xmlrpc-servers"></span><h2>20.24.1. SimpleXMLRPCServer Objects<a class="headerlink" href="#simplexmlrpcserver-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> class is based on
<a class="reference internal" href="socketserver.html#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code></a> and provides a means of creating simple, stand
alone XML-RPC servers.</p>
<dl class="method">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCServer.register_function">
<code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">register_function</code><span class="sig-paren">(</span><em>function</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCServer.register_function" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a function that can respond to XML-RPC requests.  If <em>name</em> is given,
it will be the method name associated with <em>function</em>, otherwise
<code class="docutils literal notranslate"><span class="pre">function.__name__</span></code> will be used.  <em>name</em> can be either a normal or Unicode
string, and may contain characters not legal in Python identifiers, including
the period character.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCServer.register_instance">
<code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">register_instance</code><span class="sig-paren">(</span><em>instance</em><span class="optional">[</span>, <em>allow_dotted_names</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCServer.register_instance" title="Permalink to this definition">¶</a></dt>
<dd><p>Register an object which is used to expose method names which have not been
registered using <a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCServer.register_function" title="SimpleXMLRPCServer.SimpleXMLRPCServer.register_function"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register_function()</span></code></a>.  If <em>instance</em> contains a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> method, it is called with the requested method name and the
parameters from the request.  Its API is <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">_dispatch(self,</span> <span class="pre">method,</span> <span class="pre">params)</span></code>
(note that <em>params</em> does not represent a variable argument list).  If it calls
an underlying function to perform its task, that function is called as
<code class="docutils literal notranslate"><span class="pre">func(*params)</span></code>, expanding the parameter list. The return value from
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> is returned to the client as the result.  If <em>instance</em> does
not have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> method, it is searched for an attribute matching
the name of the requested method.</p>
<p>If the optional <em>allow_dotted_names</em> argument is true and the instance does not
have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> method, then if the requested method name contains
periods, each component of the method name is searched for individually, with
the effect that a simple hierarchical search is performed.  The value found from
this search is then called with the parameters from the request, and the return
value is passed back to the client.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Enabling the <em>allow_dotted_names</em> option allows intruders to access your
module’s global variables and may allow intruders to execute arbitrary code on
your machine.  Only use this option on a secure, closed network.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3.5,: </span>2.4.1
<em>allow_dotted_names</em> was added to plug a security hole; prior versions are
insecure.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCServer.register_introspection_functions">
<code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">register_introspection_functions</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCServer.register_introspection_functions" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers the XML-RPC introspection functions <code class="docutils literal notranslate"><span class="pre">system.listMethods</span></code>,
<code class="docutils literal notranslate"><span class="pre">system.methodHelp</span></code> and <code class="docutils literal notranslate"><span class="pre">system.methodSignature</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCServer.register_multicall_functions">
<code class="descclassname">SimpleXMLRPCServer.</code><code class="descname">register_multicall_functions</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCServer.register_multicall_functions" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers the XML-RPC multicall function system.multicall.</p>
</dd></dl>

<dl class="attribute">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.rpc_paths">
<code class="descclassname">SimpleXMLRPCRequestHandler.</code><code class="descname">rpc_paths</code><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.rpc_paths" title="Permalink to this definition">¶</a></dt>
<dd><p>An attribute value that must be a tuple listing valid path portions of the URL
for receiving XML-RPC requests.  Requests posted to other paths will result in a
404 “no such page” HTTP error.  If this tuple is empty, all paths will be
considered valid. The default value is <code class="docutils literal notranslate"><span class="pre">('/',</span> <span class="pre">'/RPC2')</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.encode_threshold">
<code class="descclassname">SimpleXMLRPCRequestHandler.</code><code class="descname">encode_threshold</code><a class="headerlink" href="#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.encode_threshold" title="Permalink to this definition">¶</a></dt>
<dd><p>If this attribute is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, responses larger than this value
will be encoded using the <em>gzip</em> transfer encoding, if permitted by
the client.  The default is <code class="docutils literal notranslate"><span class="pre">1400</span></code> which corresponds roughly
to a single TCP packet.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<div class="section" id="simplexmlrpcserver-example">
<span id="id1"></span><h3>20.24.1.1. SimpleXMLRPCServer Example<a class="headerlink" href="#simplexmlrpcserver-example" title="Permalink to this headline">¶</a></h3>
<p>Server code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>
<span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCRequestHandler</span>

<span class="c1"># Restrict to a particular path.</span>
<span class="k">class</span> <span class="nc">RequestHandler</span><span class="p">(</span><span class="n">SimpleXMLRPCRequestHandler</span><span class="p">):</span>
    <span class="n">rpc_paths</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;/RPC2&#39;</span><span class="p">,)</span>

<span class="c1"># Create server</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">),</span>
                            <span class="n">requestHandler</span><span class="o">=</span><span class="n">RequestHandler</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_introspection_functions</span><span class="p">()</span>

<span class="c1"># Register pow() function; this will use the value of</span>
<span class="c1"># pow.__name__ as the name, which is just &#39;pow&#39;.</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>

<span class="c1"># Register a function under a different name</span>
<span class="k">def</span> <span class="nf">adder_function</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">adder_function</span><span class="p">,</span> <span class="s1">&#39;add&#39;</span><span class="p">)</span>

<span class="c1"># Register an instance; all the methods of the instance are</span>
<span class="c1"># published as XML-RPC methods (in this case, just &#39;div&#39;).</span>
<span class="k">class</span> <span class="nc">MyFuncs</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">div</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">x</span> <span class="o">//</span> <span class="n">y</span>

<span class="n">server</span><span class="o">.</span><span class="n">register_instance</span><span class="p">(</span><span class="n">MyFuncs</span><span class="p">())</span>

<span class="c1"># Run the server&#39;s main loop</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The following client code will call the methods made available by the preceding
server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s1">&#39;http://localhost:8000&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>  <span class="c1"># Returns 2**3 = 8</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>  <span class="c1"># Returns 5</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">div</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>  <span class="c1"># Returns 5//2 = 2</span>

<span class="c1"># Print list of available methods</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">system</span><span class="o">.</span><span class="n">listMethods</span><span class="p">()</span>
</pre></div>
</div>
<p>The following <a class="reference internal" href="#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> example is included in the module
<cite>Lib/SimpleXMLRPCServer.py</cite>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span> <span class="s1">&#39;add&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_multicall_functions</span><span class="p">()</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>This demo server can be run from the command line as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">SimpleXMLRPCServer</span>
</pre></div>
</div>
<p>Example client code which talks to the above server is included with
<cite>Lib/xmlrpclib.py</cite>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">server</span> <span class="o">=</span> <span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">server</span>
<span class="n">multi</span> <span class="o">=</span> <span class="n">MultiCall</span><span class="p">(</span><span class="n">server</span><span class="p">)</span>
<span class="n">multi</span><span class="o">.</span><span class="n">pow</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
<span class="n">multi</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">multi</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">24</span><span class="p">,</span> <span class="mi">11</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">response</span> <span class="ow">in</span> <span class="n">multi</span><span class="p">():</span>
        <span class="nb">print</span> <span class="n">response</span>
<span class="k">except</span> <span class="n">Error</span><span class="p">,</span> <span class="n">v</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;ERROR&quot;</span><span class="p">,</span> <span class="n">v</span>
</pre></div>
</div>
<p>And the client can be invoked directly using the following command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">xmlrpclib</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="cgixmlrpcrequesthandler">
<h2>20.24.2. CGIXMLRPCRequestHandler<a class="headerlink" href="#cgixmlrpcrequesthandler" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler" title="SimpleXMLRPCServer.CGIXMLRPCRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIXMLRPCRequestHandler</span></code></a> class can be used to  handle XML-RPC
requests sent to Python CGI scripts.</p>
<dl class="method">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function">
<code class="descclassname">CGIXMLRPCRequestHandler.</code><code class="descname">register_function</code><span class="sig-paren">(</span><em>function</em><span class="optional">[</span>, <em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a function that can respond to XML-RPC requests. If  <em>name</em> is given,
it will be the method name associated with  function, otherwise
<em>function.__name__</em> will be used. <em>name</em> can be either a normal or Unicode
string, and may contain  characters not legal in Python identifiers, including
the period character.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_instance">
<code class="descclassname">CGIXMLRPCRequestHandler.</code><code class="descname">register_instance</code><span class="sig-paren">(</span><em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_instance" title="Permalink to this definition">¶</a></dt>
<dd><p>Register an object which is used to expose method names  which have not been
registered using <a class="reference internal" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function" title="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register_function()</span></code></a>. If  instance contains a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> method, it is called with the  requested method name and the
parameters from the  request; the return value is returned to the client as the
result. If instance does not have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">_dispatch()</span></code> method, it is searched
for an attribute matching the name of the requested method; if  the requested
method name contains periods, each  component of the method name is searched for
individually,  with the effect that a simple hierarchical search is performed.
The value found from this search is then called with the  parameters from the
request, and the return value is passed  back to the client.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_introspection_functions">
<code class="descclassname">CGIXMLRPCRequestHandler.</code><code class="descname">register_introspection_functions</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_introspection_functions" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the XML-RPC introspection functions  <code class="docutils literal notranslate"><span class="pre">system.listMethods</span></code>,
<code class="docutils literal notranslate"><span class="pre">system.methodHelp</span></code> and  <code class="docutils literal notranslate"><span class="pre">system.methodSignature</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_multicall_functions">
<code class="descclassname">CGIXMLRPCRequestHandler.</code><code class="descname">register_multicall_functions</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_multicall_functions" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the XML-RPC multicall function <code class="docutils literal notranslate"><span class="pre">system.multicall</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="SimpleXMLRPCServer.CGIXMLRPCRequestHandler.handle_request">
<code class="descclassname">CGIXMLRPCRequestHandler.</code><code class="descname">handle_request</code><span class="sig-paren">(</span><span class="optional">[</span><em>request_text = None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.handle_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle an XML-RPC request. If <em>request_text</em> is given, it should be the POST
data provided by the HTTP server,  otherwise the contents of stdin will be used.</p>
</dd></dl>

<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyFuncs</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">div</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">//</span> <span class="n">y</span>


<span class="n">handler</span> <span class="o">=</span> <span class="n">CGIXMLRPCRequestHandler</span><span class="p">()</span>
<span class="n">handler</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="nb">pow</span><span class="p">)</span>
<span class="n">handler</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">,</span> <span class="s1">&#39;add&#39;</span><span class="p">)</span>
<span class="n">handler</span><span class="o">.</span><span class="n">register_introspection_functions</span><span class="p">()</span>
<span class="n">handler</span><span class="o">.</span><span class="n">register_instance</span><span class="p">(</span><span class="n">MyFuncs</span><span class="p">())</span>
<span class="n">handler</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a><ul>
<li><a class="reference internal" href="#simplexmlrpcserver-objects">20.24.1. SimpleXMLRPCServer Objects</a><ul>
<li><a class="reference internal" href="#simplexmlrpcserver-example">20.24.1.1. SimpleXMLRPCServer Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#cgixmlrpcrequesthandler">20.24.2. CGIXMLRPCRequestHandler</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xmlrpclib.html"
                        title="previous chapter">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="docxmlrpcserver.html"
                        title="next chapter">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/simplexmlrpcserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="docxmlrpcserver.html" title="20.25. DocXMLRPCServer — Self-documenting XML-RPC server"
             >next</a> |</li>
        <li class="right" >
          <a href="xmlrpclib.html" title="20.23. xmlrpclib — XML-RPC client access"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\TL`�iihtml/library/site.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.14. site — Site-specific configuration hook &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.15. user — User-specific configuration hook" href="user.html" />
    <link rel="prev" title="28.13. inspect — Inspect live objects" href="inspect.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/site.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="user.html" title="28.15. user — User-specific configuration hook"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="inspect.html" title="28.13. inspect — Inspect live objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-site">
<span id="site-site-specific-configuration-hook"></span><h1>28.14. <a class="reference internal" href="#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> — Site-specific configuration hook<a class="headerlink" href="#module-site" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/site.py">Lib/site.py</a></p>
<hr class="docutils" />
<p><strong>This module is automatically imported during initialization.</strong> The automatic
import can be suppressed using the interpreter’s <a class="reference internal" href="../using/cmdline.html#id2"><code class="xref std std-option docutils literal notranslate"><span class="pre">-S</span></code></a> option.</p>
<p id="index-0">Importing this module will append site-specific paths to the module search path
and add a few builtins.</p>
<p id="index-1">It starts by constructing up to four directories from a head and a tail part.
For the head part, it uses <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.exec_prefix</span></code>; empty heads
are skipped.  For the tail part, it uses the empty string and then
<code class="file docutils literal notranslate"><span class="pre">lib/site-packages</span></code> (on Windows) or
<code class="file docutils literal notranslate"><span class="pre">lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code> and then <code class="file docutils literal notranslate"><span class="pre">lib/site-python</span></code> (on
Unix and Macintosh).  For each of the distinct head-tail combinations, it sees
if it refers to an existing directory, and if so, adds it to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and
also inspects the newly added path for configuration files.</p>
<p>A path configuration file is a file whose name has the form <code class="file docutils literal notranslate"><em><span class="pre">name</span></em><span class="pre">.pth</span></code>
and exists in one of the four directories mentioned above; its contents are
additional items (one per line) to be added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  Non-existing items
are never added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, and no check is made that the item refers to a
directory rather than a file.  No item is added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> more than
once.  Blank lines and lines beginning with <code class="docutils literal notranslate"><span class="pre">#</span></code> are skipped.  Lines starting
with <code class="docutils literal notranslate"><span class="pre">import</span></code> (followed by space or tab) are executed.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>A space or tab is now required after the import keyword.</p>
</div>
<p id="index-2">For example, suppose <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.exec_prefix</span></code> are set to
<code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code>.  The Python X.Y library is then installed in
<code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em></code>.  Suppose this has
a subdirectory <code class="file docutils literal notranslate"><span class="pre">/usr/local/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code> with three
subsubdirectories, <code class="file docutils literal notranslate"><span class="pre">foo</span></code>, <code class="file docutils literal notranslate"><span class="pre">bar</span></code> and <code class="file docutils literal notranslate"><span class="pre">spam</span></code>, and two path
configuration files, <code class="file docutils literal notranslate"><span class="pre">foo.pth</span></code> and <code class="file docutils literal notranslate"><span class="pre">bar.pth</span></code>.  Assume
<code class="file docutils literal notranslate"><span class="pre">foo.pth</span></code> contains the following:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># foo package configuration

foo
bar
bletch
</pre></div>
</div>
<p>and <code class="file docutils literal notranslate"><span class="pre">bar.pth</span></code> contains:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span># bar package configuration

bar
</pre></div>
</div>
<p>Then the following version-specific directories are added to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, in this order:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>/usr/local/lib/pythonX.Y/site-packages/bar
/usr/local/lib/pythonX.Y/site-packages/foo
</pre></div>
</div>
<p>Note that <code class="file docutils literal notranslate"><span class="pre">bletch</span></code> is omitted because it doesn’t exist; the <code class="file docutils literal notranslate"><span class="pre">bar</span></code>
directory precedes the <code class="file docutils literal notranslate"><span class="pre">foo</span></code> directory because <code class="file docutils literal notranslate"><span class="pre">bar.pth</span></code> comes
alphabetically before <code class="file docutils literal notranslate"><span class="pre">foo.pth</span></code>; and <code class="file docutils literal notranslate"><span class="pre">spam</span></code> is omitted because it is
not mentioned in either path configuration file.</p>
<p id="index-3">After these path manipulations, an attempt is made to import a module named
<code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code>, which can perform arbitrary site-specific customizations.
It is typically created by a system administrator in the site-packages
directory.  If this import fails with an <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> exception, it is
silently ignored.  If Python is started without output streams available, as
with <code class="file docutils literal notranslate"><span class="pre">pythonw.exe</span></code> on Windows (which is used by default to start IDLE),
attempted output from <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> is ignored. Any exception other
than <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> causes a silent and perhaps mysterious failure of the
process.</p>
<p id="index-4">After this, an attempt is made to import a module named <code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code>,
which can perform arbitrary user-specific customizations, if
<a class="reference internal" href="#site.ENABLE_USER_SITE" title="site.ENABLE_USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ENABLE_USER_SITE</span></code></a> is true.  This file is intended to be created in the
user site-packages directory (see below), which is part of <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> unless
disabled by <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a>.  An <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> will be silently ignored.</p>
<p>Note that for some non-Unix systems, <code class="docutils literal notranslate"><span class="pre">sys.prefix</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.exec_prefix</span></code> are
empty, and the path manipulations are skipped; however the import of
<code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code> is still attempted.</p>
<dl class="data">
<dt id="site.PREFIXES">
<code class="descclassname">site.</code><code class="descname">PREFIXES</code><a class="headerlink" href="#site.PREFIXES" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of prefixes for site-packages directories.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="site.ENABLE_USER_SITE">
<code class="descclassname">site.</code><code class="descname">ENABLE_USER_SITE</code><a class="headerlink" href="#site.ENABLE_USER_SITE" title="Permalink to this definition">¶</a></dt>
<dd><p>Flag showing the status of the user site-packages directory.  <code class="docutils literal notranslate"><span class="pre">True</span></code> means
that it is enabled and was added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  <code class="docutils literal notranslate"><span class="pre">False</span></code> means that it
was disabled by user request (with <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> or
<span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNOUSERSITE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNOUSERSITE</span></code></a>).  <code class="docutils literal notranslate"><span class="pre">None</span></code> means it was disabled for security
reasons (mismatch between user or group id and effective id) or by an
administrator.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="site.USER_SITE">
<code class="descclassname">site.</code><code class="descname">USER_SITE</code><a class="headerlink" href="#site.USER_SITE" title="Permalink to this definition">¶</a></dt>
<dd><p>Path to the user site-packages for the running Python.  Can be <code class="docutils literal notranslate"><span class="pre">None</span></code> if
<a class="reference internal" href="#site.getusersitepackages" title="site.getusersitepackages"><code class="xref py py-func docutils literal notranslate"><span class="pre">getusersitepackages()</span></code></a> hasn’t been called yet.  Default value is
<code class="file docutils literal notranslate"><span class="pre">~/.local/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/site-packages</span></code> for UNIX and non-framework Mac
OS X builds, <code class="file docutils literal notranslate"><span class="pre">~/Library/Python/</span><em><span class="pre">X.Y</span></em><span class="pre">/lib/python/site-packages</span></code> for Mac
framework builds, and <code class="file docutils literal notranslate"><em><span class="pre">%APPDATA%</span></em><span class="pre">\Python\Python</span><em><span class="pre">XY</span></em><span class="pre">\site-packages</span></code>
on Windows.  This directory is a site directory, which means that
<code class="file docutils literal notranslate"><span class="pre">.pth</span></code> files in it will be processed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="site.USER_BASE">
<code class="descclassname">site.</code><code class="descname">USER_BASE</code><a class="headerlink" href="#site.USER_BASE" title="Permalink to this definition">¶</a></dt>
<dd><p>Path to the base directory for the user site-packages.  Can be <code class="docutils literal notranslate"><span class="pre">None</span></code> if
<a class="reference internal" href="#site.getuserbase" title="site.getuserbase"><code class="xref py py-func docutils literal notranslate"><span class="pre">getuserbase()</span></code></a> hasn’t been called yet.  Default value is
<code class="file docutils literal notranslate"><span class="pre">~/.local</span></code> for UNIX and Mac OS X non-framework builds,
<code class="file docutils literal notranslate"><span class="pre">~/Library/Python/</span><em><span class="pre">X.Y</span></em></code> for Mac framework builds, and
<code class="file docutils literal notranslate"><em><span class="pre">%APPDATA%</span></em><span class="pre">\Python</span></code> for Windows.  This value is used by Distutils to
compute the installation directories for scripts, data files, Python modules,
etc. for the <a class="reference internal" href="../install/index.html#inst-alt-install-user"><span class="std std-ref">user installation scheme</span></a>.  See
also <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONUSERBASE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUSERBASE</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="site.addsitedir">
<code class="descclassname">site.</code><code class="descname">addsitedir</code><span class="sig-paren">(</span><em>sitedir</em>, <em>known_paths=None</em><span class="sig-paren">)</span><a class="headerlink" href="#site.addsitedir" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a directory to sys.path and process its <code class="file docutils literal notranslate"><span class="pre">.pth</span></code> files.  Typically
used in <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code> (see above).</p>
</dd></dl>

<dl class="function">
<dt id="site.getsitepackages">
<code class="descclassname">site.</code><code class="descname">getsitepackages</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#site.getsitepackages" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list containing all global site-packages directories (and possibly
site-python).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="site.getuserbase">
<code class="descclassname">site.</code><code class="descname">getuserbase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#site.getuserbase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the path of the user base directory, <a class="reference internal" href="#site.USER_BASE" title="site.USER_BASE"><code class="xref py py-data docutils literal notranslate"><span class="pre">USER_BASE</span></code></a>.  If it is not
initialized yet, this function will also set it, respecting
<span class="target" id="index-7"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONUSERBASE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUSERBASE</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="site.getusersitepackages">
<code class="descclassname">site.</code><code class="descname">getusersitepackages</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#site.getusersitepackages" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the path of the user-specific site-packages directory,
<a class="reference internal" href="#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">USER_SITE</span></code></a>.  If it is not initialized yet, this function will also set
it, respecting <span class="target" id="index-8"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNOUSERSITE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNOUSERSITE</span></code></a> and <a class="reference internal" href="#site.USER_BASE" title="site.USER_BASE"><code class="xref py py-data docutils literal notranslate"><span class="pre">USER_BASE</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module also provides a way to get the user directories from the
command line:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python -m site --user-site
/home/user/.local/lib/python2.7/site-packages
</pre></div>
</div>
<p>If it is called without arguments, it will print the contents of
<a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> on the standard output, followed by the value of
<a class="reference internal" href="#site.USER_BASE" title="site.USER_BASE"><code class="xref py py-data docutils literal notranslate"><span class="pre">USER_BASE</span></code></a> and whether the directory exists, then the same thing for
<a class="reference internal" href="#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">USER_SITE</span></code></a>, and finally the value of <a class="reference internal" href="#site.ENABLE_USER_SITE" title="site.ENABLE_USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ENABLE_USER_SITE</span></code></a>.</p>
<dl class="cmdoption">
<dt id="cmdoption-site-user-base">
<code class="descname">--user-base</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-site-user-base" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the path to the user base directory.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-site-user-site">
<code class="descname">--user-site</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-site-user-site" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the path to the user site-packages directory.</p>
</dd></dl>

<p>If both options are given, user base and user site will be printed (always in
this order), separated by <a class="reference internal" href="os.html#os.pathsep" title="os.pathsep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.pathsep</span></code></a>.</p>
<p>If any option is given, the script will exit with one of these values: <code class="docutils literal notranslate"><span class="pre">0</span></code> if
the user site-packages directory is enabled, <code class="docutils literal notranslate"><span class="pre">1</span></code> if it was disabled by the
user, <code class="docutils literal notranslate"><span class="pre">2</span></code> if it is disabled for security reasons or by an administrator, and a
value greater than 2 if there is an error.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> – Per user site-packages directory</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="inspect.html"
                        title="previous chapter">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="user.html"
                        title="next chapter">28.15. <code class="docutils literal notranslate"><span class="pre">user</span></code> — User-specific configuration hook</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/site.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="user.html" title="28.15. user — User-specific configuration hook"
             >next</a> |</li>
        <li class="right" >
          <a href="inspect.html" title="28.13. inspect — Inspect live objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�u[\55html/library/smtpd.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.13. smtpd — SMTP Server &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.14. telnetlib — Telnet client" href="telnetlib.html" />
    <link rel="prev" title="20.12. smtplib — SMTP protocol client" href="smtplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/smtpd.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="telnetlib.html" title="20.14. telnetlib — Telnet client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="smtplib.html" title="20.12. smtplib — SMTP protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-smtpd">
<span id="smtpd-smtp-server"></span><h1>20.13. <a class="reference internal" href="#module-smtpd" title="smtpd: A SMTP server implementation in Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtpd</span></code></a> — SMTP Server<a class="headerlink" href="#module-smtpd" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/smtpd.py">Lib/smtpd.py</a></p>
<hr class="docutils" />
<p>This module offers several classes to implement SMTP servers.  One is a generic
do-nothing implementation, which can be overridden, while the other two offer
specific mail-sending strategies.</p>
<div class="section" id="smtpserver-objects">
<h2>20.13.1. SMTPServer Objects<a class="headerlink" href="#smtpserver-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="smtpd.SMTPServer">
<em class="property">class </em><code class="descclassname">smtpd.</code><code class="descname">SMTPServer</code><span class="sig-paren">(</span><em>localaddr</em>, <em>remoteaddr</em><span class="sig-paren">)</span><a class="headerlink" href="#smtpd.SMTPServer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new <a class="reference internal" href="#smtpd.SMTPServer" title="smtpd.SMTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPServer</span></code></a> object, which binds to local address
<em>localaddr</em>.  It will treat <em>remoteaddr</em> as an upstream SMTP relayer.  Both
<em>localaddr</em> and <em>remoteaddr</em> should be a <a class="reference internal" href="socket.html#host-port"><span class="std std-ref">(host, port)</span></a>
tuple.  The object inherits from <a class="reference internal" href="asyncore.html#asyncore.dispatcher" title="asyncore.dispatcher"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncore.dispatcher</span></code></a>, and so will
insert itself into <a class="reference internal" href="asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a>’s event loop on instantiation.</p>
<dl class="method">
<dt id="smtpd.SMTPServer.process_message">
<code class="descname">process_message</code><span class="sig-paren">(</span><em>peer</em>, <em>mailfrom</em>, <em>rcpttos</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#smtpd.SMTPServer.process_message" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> exception. Override this in subclasses to
do something useful with this message. Whatever was passed in the
constructor as <em>remoteaddr</em> will be available as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">_remoteaddr</span></code>
attribute. <em>peer</em> is the remote host’s address, <em>mailfrom</em> is the envelope
originator, <em>rcpttos</em> are the envelope recipients and <em>data</em> is a string
containing the contents of the e-mail (which should be in <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>
format).</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="debuggingserver-objects">
<h2>20.13.2. DebuggingServer Objects<a class="headerlink" href="#debuggingserver-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="smtpd.DebuggingServer">
<em class="property">class </em><code class="descclassname">smtpd.</code><code class="descname">DebuggingServer</code><span class="sig-paren">(</span><em>localaddr</em>, <em>remoteaddr</em><span class="sig-paren">)</span><a class="headerlink" href="#smtpd.DebuggingServer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new debugging server.  Arguments are as per <a class="reference internal" href="#smtpd.SMTPServer" title="smtpd.SMTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPServer</span></code></a>.
Messages will be discarded, and printed on stdout.</p>
</dd></dl>

</div>
<div class="section" id="pureproxy-objects">
<h2>20.13.3. PureProxy Objects<a class="headerlink" href="#pureproxy-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="smtpd.PureProxy">
<em class="property">class </em><code class="descclassname">smtpd.</code><code class="descname">PureProxy</code><span class="sig-paren">(</span><em>localaddr</em>, <em>remoteaddr</em><span class="sig-paren">)</span><a class="headerlink" href="#smtpd.PureProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new pure proxy server. Arguments are as per <a class="reference internal" href="#smtpd.SMTPServer" title="smtpd.SMTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPServer</span></code></a>.
Everything will be relayed to <em>remoteaddr</em>.  Note that running this has a good
chance to make you into an open relay, so please be careful.</p>
</dd></dl>

</div>
<div class="section" id="mailmanproxy-objects">
<h2>20.13.4. MailmanProxy Objects<a class="headerlink" href="#mailmanproxy-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="smtpd.MailmanProxy">
<em class="property">class </em><code class="descclassname">smtpd.</code><code class="descname">MailmanProxy</code><span class="sig-paren">(</span><em>localaddr</em>, <em>remoteaddr</em><span class="sig-paren">)</span><a class="headerlink" href="#smtpd.MailmanProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new pure proxy server. Arguments are as per <a class="reference internal" href="#smtpd.SMTPServer" title="smtpd.SMTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTPServer</span></code></a>.
Everything will be relayed to <em>remoteaddr</em>, unless local mailman configurations
knows about an address, in which case it will be handled via mailman.  Note that
running this has a good chance to make you into an open relay, so please be
careful.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a><ul>
<li><a class="reference internal" href="#smtpserver-objects">20.13.1. SMTPServer Objects</a></li>
<li><a class="reference internal" href="#debuggingserver-objects">20.13.2. DebuggingServer Objects</a></li>
<li><a class="reference internal" href="#pureproxy-objects">20.13.3. PureProxy Objects</a></li>
<li><a class="reference internal" href="#mailmanproxy-objects">20.13.4. MailmanProxy Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="smtplib.html"
                        title="previous chapter">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="telnetlib.html"
                        title="next chapter">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/smtpd.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="telnetlib.html" title="20.14. telnetlib — Telnet client"
             >next</a> |</li>
        <li class="right" >
          <a href="smtplib.html" title="20.12. smtplib — SMTP protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\M6��ηηhtml/library/smtplib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.12. smtplib — SMTP protocol client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.13. smtpd — SMTP Server" href="smtpd.html" />
    <link rel="prev" title="20.11. nntplib — NNTP protocol client" href="nntplib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/smtplib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="smtpd.html" title="20.13. smtpd — SMTP Server"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="nntplib.html" title="20.11. nntplib — NNTP protocol client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-smtplib">
<span id="smtplib-smtp-protocol-client"></span><h1>20.12. <a class="reference internal" href="#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> — SMTP protocol client<a class="headerlink" href="#module-smtplib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/smtplib.py">Lib/smtplib.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module defines an SMTP client session object that can be used
to send mail to any Internet machine with an SMTP or ESMTP listener daemon.  For
details of SMTP and ESMTP operation, consult <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc821.html"><strong>RFC 821</strong></a> (Simple Mail Transfer
Protocol) and <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1869.html"><strong>RFC 1869</strong></a> (SMTP Service Extensions).</p>
<dl class="class">
<dt id="smtplib.SMTP">
<em class="property">class </em><code class="descclassname">smtplib.</code><code class="descname">SMTP</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>local_hostname</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP" title="Permalink to this definition">¶</a></dt>
<dd><p>An <a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a> instance encapsulates an SMTP connection.  It has methods
that support a full repertoire of SMTP and ESMTP operations. If the optional
host and port parameters are given, the SMTP <a class="reference internal" href="#smtplib.SMTP.connect" title="smtplib.SMTP.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> method is
called with those parameters during initialization.  If specified,
<em>local_hostname</em> is used as the FQDN of the local host in the HELO/EHLO
command.  Otherwise, the local hostname is found using
<a class="reference internal" href="socket.html#socket.getfqdn" title="socket.getfqdn"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket.getfqdn()</span></code></a>.  If the <a class="reference internal" href="#smtplib.SMTP.connect" title="smtplib.SMTP.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> call returns anything other
than a success code, an <a class="reference internal" href="#smtplib.SMTPConnectError" title="smtplib.SMTPConnectError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPConnectError</span></code></a> is raised. The optional
<em>timeout</em> parameter specifies a timeout in seconds for blocking operations
like the connection attempt (if not specified, the global default timeout
setting will be used).  If the timeout expires, <a class="reference internal" href="socket.html#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.timeout</span></code></a>
is raised.</p>
<p>For normal use, you should only require the initialization/connect,
<a class="reference internal" href="#smtplib.SMTP.sendmail" title="smtplib.SMTP.sendmail"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmail()</span></code></a>, and <a class="reference internal" href="#smtplib.SMTP.quit" title="smtplib.SMTP.quit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SMTP.quit()</span></code></a> methods.
An example is included below.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="smtplib.SMTP_SSL">
<em class="property">class </em><code class="descclassname">smtplib.</code><code class="descname">SMTP_SSL</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>local_hostname</em><span class="optional">[</span>, <em>keyfile</em><span class="optional">[</span>, <em>certfile</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP_SSL" title="Permalink to this definition">¶</a></dt>
<dd><p>An <a class="reference internal" href="#smtplib.SMTP_SSL" title="smtplib.SMTP_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP_SSL</span></code></a> instance behaves exactly the same as instances of
<a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a>. <a class="reference internal" href="#smtplib.SMTP_SSL" title="smtplib.SMTP_SSL"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP_SSL</span></code></a> should be used for situations where SSL is
required from the beginning of the connection and using <code class="xref py py-meth docutils literal notranslate"><span class="pre">starttls()</span></code> is
not appropriate. If <em>host</em> is not specified, the local host is used. If
<em>port</em> is omitted, the standard SMTP-over-SSL port (465) is used.
<em>local_hostname</em> has the same meaning as it does for the <a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a>
class.  <em>keyfile</em> and <em>certfile</em> are also optional, and can contain a PEM
formatted private key and certificate chain file for the SSL connection. The
optional <em>timeout</em> parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
timeout setting will be used).  If the timeout expires, <a class="reference internal" href="socket.html#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.timeout</span></code></a>
is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="smtplib.LMTP">
<em class="property">class </em><code class="descclassname">smtplib.</code><code class="descname">LMTP</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>local_hostname</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.LMTP" title="Permalink to this definition">¶</a></dt>
<dd><p>The LMTP protocol, which is very similar to ESMTP, is heavily based on the
standard SMTP client. It’s common to use Unix sockets for LMTP, so our
<code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code> method must support that as well as a regular host:port
server.  <em>local_hostname</em> has the same meaning as it does for the
<a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a> class.  To specify a Unix socket, you must use an absolute
path for <em>host</em>, starting with a ‘/’.</p>
<p>Authentication is supported, using the regular SMTP mechanism. When using a
Unix socket, LMTP generally don’t support or require any authentication, but
your mileage might vary.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>A nice selection of exceptions is defined as well:</p>
<dl class="exception">
<dt id="smtplib.SMTPException">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPException</code><a class="headerlink" href="#smtplib.SMTPException" title="Permalink to this definition">¶</a></dt>
<dd><p>The base exception class for all the other exceptions provided by this
module.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPServerDisconnected">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPServerDisconnected</code><a class="headerlink" href="#smtplib.SMTPServerDisconnected" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when the server unexpectedly disconnects, or when an
attempt is made to use the <a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a> instance before connecting it to a
server.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPResponseException">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPResponseException</code><a class="headerlink" href="#smtplib.SMTPResponseException" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for all exceptions that include an SMTP error code. These exceptions
are generated in some instances when the SMTP server returns an error code.  The
error code is stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">smtp_code</span></code> attribute of the error, and the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">smtp_error</span></code> attribute is set to the error message.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPSenderRefused">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPSenderRefused</code><a class="headerlink" href="#smtplib.SMTPSenderRefused" title="Permalink to this definition">¶</a></dt>
<dd><p>Sender address refused.  In addition to the attributes set by on all
<a class="reference internal" href="#smtplib.SMTPResponseException" title="smtplib.SMTPResponseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPResponseException</span></code></a> exceptions, this sets ‘sender’ to the string that
the SMTP server refused.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPRecipientsRefused">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPRecipientsRefused</code><a class="headerlink" href="#smtplib.SMTPRecipientsRefused" title="Permalink to this definition">¶</a></dt>
<dd><p>All recipient addresses refused.  The errors for each recipient are accessible
through the attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">recipients</span></code>, which is a dictionary of exactly the
same sort as <a class="reference internal" href="#smtplib.SMTP.sendmail" title="smtplib.SMTP.sendmail"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SMTP.sendmail()</span></code></a> returns.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPDataError">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPDataError</code><a class="headerlink" href="#smtplib.SMTPDataError" title="Permalink to this definition">¶</a></dt>
<dd><p>The SMTP server refused to accept the message data.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPConnectError">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPConnectError</code><a class="headerlink" href="#smtplib.SMTPConnectError" title="Permalink to this definition">¶</a></dt>
<dd><p>Error occurred during establishment of a connection  with the server.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPHeloError">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPHeloError</code><a class="headerlink" href="#smtplib.SMTPHeloError" title="Permalink to this definition">¶</a></dt>
<dd><p>The server refused our <code class="docutils literal notranslate"><span class="pre">HELO</span></code> message.</p>
</dd></dl>

<dl class="exception">
<dt id="smtplib.SMTPAuthenticationError">
<em class="property">exception </em><code class="descclassname">smtplib.</code><code class="descname">SMTPAuthenticationError</code><a class="headerlink" href="#smtplib.SMTPAuthenticationError" title="Permalink to this definition">¶</a></dt>
<dd><p>SMTP authentication went wrong.  Most probably the server didn’t accept the
username/password combination provided.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc821.html"><strong>RFC 821</strong></a> - Simple Mail Transfer Protocol</dt>
<dd>Protocol definition for SMTP.  This document covers the model, operating
procedure, and protocol details for SMTP.</dd>
<dt><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1869.html"><strong>RFC 1869</strong></a> - SMTP Service Extensions</dt>
<dd>Definition of the ESMTP extensions for SMTP.  This describes a framework for
extending SMTP with new commands, supporting dynamic discovery of the commands
provided by the server, and defines a few additional commands.</dd>
</dl>
</div>
<div class="section" id="smtp-objects">
<span id="id1"></span><h2>20.12.1. SMTP Objects<a class="headerlink" href="#smtp-objects" title="Permalink to this headline">¶</a></h2>
<p>An <a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a> instance has the following methods:</p>
<dl class="method">
<dt id="smtplib.SMTP.set_debuglevel">
<code class="descclassname">SMTP.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>level</em><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the debug output level.  A true value for <em>level</em> results in debug messages
for connection and for all messages sent to and received from the server.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.docmd">
<code class="descclassname">SMTP.</code><code class="descname">docmd</code><span class="sig-paren">(</span><em>cmd</em><span class="optional">[</span>, <em>argstring</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.docmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a command <em>cmd</em> to the server.  The optional argument <em>argstring</em> is simply
concatenated to the command, separated by a space.</p>
<p>This returns a 2-tuple composed of a numeric response code and the actual
response line (multiline responses are joined into one long line.)</p>
<p>In normal operation it should not be necessary to call this method explicitly.
It is used to implement other methods and may be useful for testing private
extensions.</p>
<p>If the connection to the server is lost while waiting for the reply,
<a class="reference internal" href="#smtplib.SMTPServerDisconnected" title="smtplib.SMTPServerDisconnected"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPServerDisconnected</span></code></a> will be raised.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.connect">
<code class="descclassname">SMTP.</code><code class="descname">connect</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to a host on a given port.  The defaults are to connect to the local
host at the standard SMTP port (25). If the hostname ends with a colon (<code class="docutils literal notranslate"><span class="pre">':'</span></code>)
followed by a number, that suffix will be stripped off and the number
interpreted as the port number to use. This method is automatically invoked by
the constructor if a host is specified during instantiation.  Returns a
2-tuple of the response code and message sent by the server in its
connection response.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.helo">
<code class="descclassname">SMTP.</code><code class="descname">helo</code><span class="sig-paren">(</span><span class="optional">[</span><em>hostname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.helo" title="Permalink to this definition">¶</a></dt>
<dd><p>Identify yourself to the SMTP server using <code class="docutils literal notranslate"><span class="pre">HELO</span></code>.  The hostname argument
defaults to the fully qualified domain name of the local host.
The message returned by the server is stored as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">helo_resp</span></code> attribute
of the object.</p>
<p>In normal operation it should not be necessary to call this method explicitly.
It will be implicitly called by the <a class="reference internal" href="#smtplib.SMTP.sendmail" title="smtplib.SMTP.sendmail"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmail()</span></code></a> when necessary.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.ehlo">
<code class="descclassname">SMTP.</code><code class="descname">ehlo</code><span class="sig-paren">(</span><span class="optional">[</span><em>hostname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.ehlo" title="Permalink to this definition">¶</a></dt>
<dd><p>Identify yourself to an ESMTP server using <code class="docutils literal notranslate"><span class="pre">EHLO</span></code>.  The hostname argument
defaults to the fully qualified domain name of the local host.  Examine the
response for ESMTP option and store them for use by <a class="reference internal" href="#smtplib.SMTP.has_extn" title="smtplib.SMTP.has_extn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_extn()</span></code></a>.
Also sets several informational attributes: the message returned by
the server is stored as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">ehlo_resp</span></code> attribute, <code class="xref py py-attr docutils literal notranslate"><span class="pre">does_esmtp</span></code>
is set to true or false depending on whether the server supports ESMTP, and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">esmtp_features</span></code> will be a dictionary containing the names of the
SMTP service extensions this server supports, and their
parameters (if any).</p>
<p>Unless you wish to use <a class="reference internal" href="#smtplib.SMTP.has_extn" title="smtplib.SMTP.has_extn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_extn()</span></code></a> before sending mail, it should not be
necessary to call this method explicitly.  It will be implicitly called by
<a class="reference internal" href="#smtplib.SMTP.sendmail" title="smtplib.SMTP.sendmail"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmail()</span></code></a> when necessary.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.ehlo_or_helo_if_needed">
<code class="descclassname">SMTP.</code><code class="descname">ehlo_or_helo_if_needed</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.ehlo_or_helo_if_needed" title="Permalink to this definition">¶</a></dt>
<dd><p>This method call <a class="reference internal" href="#smtplib.SMTP.ehlo" title="smtplib.SMTP.ehlo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ehlo()</span></code></a> and or <a class="reference internal" href="#smtplib.SMTP.helo" title="smtplib.SMTP.helo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">helo()</span></code></a> if there has been no
previous <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> or <code class="docutils literal notranslate"><span class="pre">HELO</span></code> command this session.  It tries ESMTP <code class="docutils literal notranslate"><span class="pre">EHLO</span></code>
first.</p>
<dl class="docutils">
<dt><a class="reference internal" href="#smtplib.SMTPHeloError" title="smtplib.SMTPHeloError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPHeloError</span></code></a></dt>
<dd>The server didn’t reply properly to the <code class="docutils literal notranslate"><span class="pre">HELO</span></code> greeting.</dd>
</dl>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.has_extn">
<code class="descclassname">SMTP.</code><code class="descname">has_extn</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.has_extn" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>name</em> is in the set of SMTP service extensions returned
by the server, <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> otherwise. Case is ignored.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.verify">
<code class="descclassname">SMTP.</code><code class="descname">verify</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.verify" title="Permalink to this definition">¶</a></dt>
<dd><p>Check the validity of an address on this server using SMTP <code class="docutils literal notranslate"><span class="pre">VRFY</span></code>. Returns a
tuple consisting of code 250 and a full <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> address (including human
name) if the user address is valid. Otherwise returns an SMTP error code of 400
or greater and an error string.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Many sites disable SMTP <code class="docutils literal notranslate"><span class="pre">VRFY</span></code> in order to foil spammers.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.login">
<code class="descclassname">SMTP.</code><code class="descname">login</code><span class="sig-paren">(</span><em>user</em>, <em>password</em><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.login" title="Permalink to this definition">¶</a></dt>
<dd><p>Log in on an SMTP server that requires authentication. The arguments are the
username and the password to authenticate with. If there has been no previous
<code class="docutils literal notranslate"><span class="pre">EHLO</span></code> or <code class="docutils literal notranslate"><span class="pre">HELO</span></code> command this session, this method tries ESMTP <code class="docutils literal notranslate"><span class="pre">EHLO</span></code>
first. This method will return normally if the authentication was successful, or
may raise the following exceptions:</p>
<dl class="docutils">
<dt><a class="reference internal" href="#smtplib.SMTPHeloError" title="smtplib.SMTPHeloError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPHeloError</span></code></a></dt>
<dd>The server didn’t reply properly to the <code class="docutils literal notranslate"><span class="pre">HELO</span></code> greeting.</dd>
<dt><a class="reference internal" href="#smtplib.SMTPAuthenticationError" title="smtplib.SMTPAuthenticationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPAuthenticationError</span></code></a></dt>
<dd>The server didn’t accept the username/password combination.</dd>
<dt><a class="reference internal" href="#smtplib.SMTPException" title="smtplib.SMTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPException</span></code></a></dt>
<dd>No suitable authentication method was found.</dd>
</dl>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.starttls">
<code class="descclassname">SMTP.</code><code class="descname">starttls</code><span class="sig-paren">(</span><span class="optional">[</span><em>keyfile</em><span class="optional">[</span>, <em>certfile</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.starttls" title="Permalink to this definition">¶</a></dt>
<dd><p>Put the SMTP connection in TLS (Transport Layer Security) mode.  All SMTP
commands that follow will be encrypted.  You should then call <a class="reference internal" href="#smtplib.SMTP.ehlo" title="smtplib.SMTP.ehlo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ehlo()</span></code></a>
again.</p>
<p>If <em>keyfile</em> and <em>certfile</em> are provided, these are passed to the <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a>
module’s <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl()</span></code></a> function.</p>
<p>If there has been no previous <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> or <code class="docutils literal notranslate"><span class="pre">HELO</span></code> command this session,
this method tries ESMTP <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> first.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6.</span></p>
</div>
<dl class="docutils">
<dt><a class="reference internal" href="#smtplib.SMTPHeloError" title="smtplib.SMTPHeloError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPHeloError</span></code></a></dt>
<dd>The server didn’t reply properly to the <code class="docutils literal notranslate"><span class="pre">HELO</span></code> greeting.</dd>
<dt><a class="reference internal" href="#smtplib.SMTPException" title="smtplib.SMTPException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPException</span></code></a></dt>
<dd>The server does not support the STARTTLS extension.</dd>
</dl>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6.</span></p>
</div>
<dl class="docutils">
<dt><a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a></dt>
<dd>SSL/TLS support is not available to your Python interpreter.</dd>
</dl>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.sendmail">
<code class="descclassname">SMTP.</code><code class="descname">sendmail</code><span class="sig-paren">(</span><em>from_addr</em>, <em>to_addrs</em>, <em>msg</em><span class="optional">[</span>, <em>mail_options</em>, <em>rcpt_options</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.sendmail" title="Permalink to this definition">¶</a></dt>
<dd><p>Send mail.  The required arguments are an <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> from-address string, a list
of <span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> to-address strings (a bare string will be treated as a list with 1
address), and a message string.  The caller may pass a list of ESMTP options
(such as <code class="docutils literal notranslate"><span class="pre">8bitmime</span></code>) to be used in <code class="docutils literal notranslate"><span class="pre">MAIL</span> <span class="pre">FROM</span></code> commands as <em>mail_options</em>.
ESMTP options (such as <code class="docutils literal notranslate"><span class="pre">DSN</span></code> commands) that should be used with all <code class="docutils literal notranslate"><span class="pre">RCPT</span></code>
commands can be passed as <em>rcpt_options</em>.  (If you need to use different ESMTP
options to different recipients you have to use the low-level methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">mail()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">rcpt()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">data()</span></code> to send the message.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <em>from_addr</em> and <em>to_addrs</em> parameters are used to construct the message
envelope used by the transport agents. The <a class="reference internal" href="#smtplib.SMTP" title="smtplib.SMTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code></a> does not modify the
message headers in any way.</p>
</div>
<p>If there has been no previous <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> or <code class="docutils literal notranslate"><span class="pre">HELO</span></code> command this session, this
method tries ESMTP <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> first. If the server does ESMTP, message size and
each of the specified options will be passed to it (if the option is in the
feature set the server advertises).  If <code class="docutils literal notranslate"><span class="pre">EHLO</span></code> fails, <code class="docutils literal notranslate"><span class="pre">HELO</span></code> will be tried
and ESMTP options suppressed.</p>
<p>This method will return normally if the mail is accepted for at least one
recipient. Otherwise it will raise an exception.  That is, if this method does
not raise an exception, then someone should get your mail. If this method does
not raise an exception, it returns a dictionary, with one entry for each
recipient that was refused.  Each entry contains a tuple of the SMTP error code
and the accompanying error message sent by the server.</p>
<p>This method may raise the following exceptions:</p>
<dl class="docutils">
<dt><a class="reference internal" href="#smtplib.SMTPRecipientsRefused" title="smtplib.SMTPRecipientsRefused"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPRecipientsRefused</span></code></a></dt>
<dd>All recipients were refused.  Nobody got the mail.  The <code class="xref py py-attr docutils literal notranslate"><span class="pre">recipients</span></code>
attribute of the exception object is a dictionary with information about the
refused recipients (like the one returned when at least one recipient was
accepted).</dd>
<dt><a class="reference internal" href="#smtplib.SMTPHeloError" title="smtplib.SMTPHeloError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPHeloError</span></code></a></dt>
<dd>The server didn’t reply properly to the <code class="docutils literal notranslate"><span class="pre">HELO</span></code> greeting.</dd>
<dt><a class="reference internal" href="#smtplib.SMTPSenderRefused" title="smtplib.SMTPSenderRefused"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPSenderRefused</span></code></a></dt>
<dd>The server didn’t accept the <em>from_addr</em>.</dd>
<dt><a class="reference internal" href="#smtplib.SMTPDataError" title="smtplib.SMTPDataError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SMTPDataError</span></code></a></dt>
<dd>The server replied with an unexpected error code (other than a refusal of a
recipient).</dd>
</dl>
<p>Unless otherwise noted, the connection will be open even after an exception is
raised.</p>
</dd></dl>

<dl class="method">
<dt id="smtplib.SMTP.quit">
<code class="descclassname">SMTP.</code><code class="descname">quit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#smtplib.SMTP.quit" title="Permalink to this definition">¶</a></dt>
<dd><p>Terminate the SMTP session and close the connection.  Return the result of
the SMTP <code class="docutils literal notranslate"><span class="pre">QUIT</span></code> command.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Return a value.</p>
</div>
</dd></dl>

<p>Low-level methods corresponding to the standard SMTP/ESMTP commands <code class="docutils literal notranslate"><span class="pre">HELP</span></code>,
<code class="docutils literal notranslate"><span class="pre">RSET</span></code>, <code class="docutils literal notranslate"><span class="pre">NOOP</span></code>, <code class="docutils literal notranslate"><span class="pre">MAIL</span></code>, <code class="docutils literal notranslate"><span class="pre">RCPT</span></code>, and <code class="docutils literal notranslate"><span class="pre">DATA</span></code> are also supported.
Normally these do not need to be called directly, so they are not documented
here.  For details, consult the module code.</p>
</div>
<div class="section" id="smtp-example">
<span id="id2"></span><h2>20.12.2. SMTP Example<a class="headerlink" href="#smtp-example" title="Permalink to this headline">¶</a></h2>
<p>This example prompts the user for addresses needed in the message envelope (‘To’
and ‘From’ addresses), and the message to be delivered.  Note that the headers
to be included with the message must be included in the message as entered; this
example doesn’t do any processing of the <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> headers.  In particular, the
‘To’ and ‘From’ addresses must be included in the message headers explicitly.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">smtplib</span>

<span class="k">def</span> <span class="nf">prompt</span><span class="p">(</span><span class="n">prompt</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">raw_input</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>

<span class="n">fromaddr</span> <span class="o">=</span> <span class="n">prompt</span><span class="p">(</span><span class="s2">&quot;From: &quot;</span><span class="p">)</span>
<span class="n">toaddrs</span>  <span class="o">=</span> <span class="n">prompt</span><span class="p">(</span><span class="s2">&quot;To: &quot;</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="nb">print</span> <span class="s2">&quot;Enter message, end with ^D (Unix) or ^Z (Windows):&quot;</span>

<span class="c1"># Add the From: and To: headers at the start!</span>
<span class="n">msg</span> <span class="o">=</span> <span class="p">(</span><span class="s2">&quot;From: </span><span class="si">%s</span><span class="se">\r\n</span><span class="s2">To: </span><span class="si">%s</span><span class="se">\r\n\r\n</span><span class="s2">&quot;</span>
       <span class="o">%</span> <span class="p">(</span><span class="n">fromaddr</span><span class="p">,</span> <span class="s2">&quot;, &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">toaddrs</span><span class="p">)))</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">line</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">EOFError</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">line</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="n">msg</span> <span class="o">=</span> <span class="n">msg</span> <span class="o">+</span> <span class="n">line</span>

<span class="nb">print</span> <span class="s2">&quot;Message length is &quot;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">msg</span><span class="p">))</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">set_debuglevel</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="n">fromaddr</span><span class="p">,</span> <span class="n">toaddrs</span><span class="p">,</span> <span class="n">msg</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In general, you will want to use the <a class="reference internal" href="email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package’s features to
construct an email message, which you can then convert to a string and send
via <code class="xref py py-meth docutils literal notranslate"><span class="pre">sendmail()</span></code>; see <a class="reference internal" href="email-examples.html#email-examples"><span class="std std-ref">email: Examples</span></a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a><ul>
<li><a class="reference internal" href="#smtp-objects">20.12.1. SMTP Objects</a></li>
<li><a class="reference internal" href="#smtp-example">20.12.2. SMTP Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="nntplib.html"
                        title="previous chapter">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="smtpd.html"
                        title="next chapter">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/smtplib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="smtpd.html" title="20.13. smtpd — SMTP Server"
             >next</a> |</li>
        <li class="right" >
          <a href="nntplib.html" title="20.11. nntplib — NNTP protocol client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��*��*�*html/library/sndhdr.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.9. sndhdr — Determine type of sound file &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.10. ossaudiodev — Access to OSS-compatible audio devices" href="ossaudiodev.html" />
    <link rel="prev" title="21.8. imghdr — Determine the type of an image" href="imghdr.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sndhdr.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ossaudiodev.html" title="21.10. ossaudiodev — Access to OSS-compatible audio devices"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imghdr.html" title="21.8. imghdr — Determine the type of an image"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sndhdr">
<span id="sndhdr-determine-type-of-sound-file"></span><h1>21.9. <a class="reference internal" href="#module-sndhdr" title="sndhdr: Determine type of a sound file."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sndhdr</span></code></a> — Determine type of sound file<a class="headerlink" href="#module-sndhdr" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/sndhdr.py">Lib/sndhdr.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-sndhdr" title="sndhdr: Determine type of a sound file."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sndhdr</span></code></a> provides utility functions which attempt to determine the type
of sound data which is in a file.  When these functions are able to determine
what type of sound data is stored in a file, they return a tuple <code class="docutils literal notranslate"><span class="pre">(type,</span>
<span class="pre">sampling_rate,</span> <span class="pre">channels,</span> <span class="pre">frames,</span> <span class="pre">bits_per_sample)</span></code>.  The value for <em>type</em>
indicates the data type and will be one of the strings <code class="docutils literal notranslate"><span class="pre">'aifc'</span></code>, <code class="docutils literal notranslate"><span class="pre">'aiff'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'au'</span></code>, <code class="docutils literal notranslate"><span class="pre">'hcom'</span></code>, <code class="docutils literal notranslate"><span class="pre">'sndr'</span></code>, <code class="docutils literal notranslate"><span class="pre">'sndt'</span></code>, <code class="docutils literal notranslate"><span class="pre">'voc'</span></code>, <code class="docutils literal notranslate"><span class="pre">'wav'</span></code>, <code class="docutils literal notranslate"><span class="pre">'8svx'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'sb'</span></code>, <code class="docutils literal notranslate"><span class="pre">'ub'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'ul'</span></code>.  The <em>sampling_rate</em> will be either the actual
value or <code class="docutils literal notranslate"><span class="pre">0</span></code> if unknown or difficult to decode.  Similarly, <em>channels</em> will be
either the number of channels or <code class="docutils literal notranslate"><span class="pre">0</span></code> if it cannot be determined or if the
value is difficult to decode.  The value for <em>frames</em> will be either the number
of frames or <code class="docutils literal notranslate"><span class="pre">-1</span></code>.  The last item in the tuple, <em>bits_per_sample</em>, will either
be the sample size in bits or <code class="docutils literal notranslate"><span class="pre">'A'</span></code> for A-LAW or <code class="docutils literal notranslate"><span class="pre">'U'</span></code> for u-LAW.</p>
<dl class="function">
<dt id="sndhdr.what">
<code class="descclassname">sndhdr.</code><code class="descname">what</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#sndhdr.what" title="Permalink to this definition">¶</a></dt>
<dd><p>Determines the type of sound data stored in the file <em>filename</em> using
<a class="reference internal" href="#sndhdr.whathdr" title="sndhdr.whathdr"><code class="xref py py-func docutils literal notranslate"><span class="pre">whathdr()</span></code></a>.  If it succeeds, returns a tuple as described above, otherwise
<code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
</dd></dl>

<dl class="function">
<dt id="sndhdr.whathdr">
<code class="descclassname">sndhdr.</code><code class="descname">whathdr</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#sndhdr.whathdr" title="Permalink to this definition">¶</a></dt>
<dd><p>Determines the type of sound data stored in a file based on the file  header.
The name of the file is given by <em>filename</em>.  This function returns a tuple as
described above on success, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="imghdr.html"
                        title="previous chapter">21.8. <code class="docutils literal notranslate"><span class="pre">imghdr</span></code> — Determine the type of an image</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ossaudiodev.html"
                        title="next chapter">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sndhdr.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ossaudiodev.html" title="21.10. ossaudiodev — Access to OSS-compatible audio devices"
             >next</a> |</li>
        <li class="right" >
          <a href="imghdr.html" title="21.8. imghdr — Determine the type of an image"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��ƾ���html/library/socket.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.2. socket — Low-level networking interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.3. ssl — TLS/SSL wrapper for socket objects" href="ssl.html" />
    <link rel="prev" title="17.1. subprocess — Subprocess management" href="subprocess.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/socket.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="17.3. ssl — TLS/SSL wrapper for socket objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="subprocess.html" title="17.1. subprocess — Subprocess management"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-socket">
<span id="socket-low-level-networking-interface"></span><h1>17.2. <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> — Low-level networking interface<a class="headerlink" href="#module-socket" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to the BSD <em>socket</em> interface. It is available on
all modern Unix systems, Windows, Mac OS X, BeOS, OS/2, and probably additional
platforms.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some behavior may be platform dependent, since calls are made to the operating
system socket APIs.</p>
</div>
<p>For an introduction to socket programming (in C), see the following papers: An
Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and
An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J.  Leffler et
al, both in the UNIX Programmer’s Manual, Supplementary Documents 1 (sections
PS1:7 and PS1:8).  The platform-specific reference material for the various
socket-related system calls are also a valuable source of information on the
details of socket semantics.  For Unix, refer to the manual pages; for Windows,
see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
want to refer to <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3493.html"><strong>RFC 3493</strong></a> titled Basic Socket Interface Extensions for IPv6.</p>
<p id="index-1">The Python interface is a straightforward transliteration of the Unix system
call and library interface for sockets to Python’s object-oriented style: the
<a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> function returns a <em class="dfn">socket object</em> whose methods implement
the various socket system calls.  Parameter types are somewhat higher-level than
in the C interface: as with <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> operations on Python
files, buffer allocation on receive operations is automatic, and buffer length
is implicit on send operations.</p>
<p id="host-port">Socket addresses are represented as follows: A single string is used for the
<a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> address family. A pair <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> is used for the
<a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> address family, where <em>host</em> is a string representing either a
hostname in Internet domain notation like <code class="docutils literal notranslate"><span class="pre">'daring.cwi.nl'</span></code> or an IPv4 address
like <code class="docutils literal notranslate"><span class="pre">'100.50.200.5'</span></code>, and <em>port</em> is an integer. For
<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> address family, a four-tuple <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port,</span> <span class="pre">flowinfo,</span>
<span class="pre">scopeid)</span></code> is used, where <em>flowinfo</em> and <em>scopeid</em> represents <code class="docutils literal notranslate"><span class="pre">sin6_flowinfo</span></code>
and <code class="docutils literal notranslate"><span class="pre">sin6_scope_id</span></code> member in <code class="xref py py-const docutils literal notranslate"><span class="pre">struct</span> <span class="pre">sockaddr_in6</span></code> in C. For
<a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module methods, <em>flowinfo</em> and <em>scopeid</em> can be omitted just for
backward compatibility. Note, however, omission of <em>scopeid</em> can cause problems
in manipulating scoped IPv6 addresses. Other address families are currently not
supported. The address format required by a particular socket object is
automatically selected based on the address family specified when the socket
object was created.</p>
<p>For IPv4 addresses, two special forms are accepted instead of a host address:
the empty string represents <code class="xref py py-const docutils literal notranslate"><span class="pre">INADDR_ANY</span></code>, and the string
<code class="docutils literal notranslate"><span class="pre">'&lt;broadcast&gt;'</span></code> represents <code class="xref py py-const docutils literal notranslate"><span class="pre">INADDR_BROADCAST</span></code>. The behavior is not
available for IPv6 for backward compatibility, therefore, you may want to avoid
these if you intend to support IPv6 with your Python programs.</p>
<p>If you use a hostname in the <em>host</em> portion of IPv4/v6 socket address, the
program may show a nondeterministic behavior, as Python uses the first address
returned from the DNS resolution.  The socket address will be resolved
differently into an actual IPv4/v6 address, depending on the results from DNS
resolution and/or the host configuration.  For deterministic behavior use a
numeric address in <em>host</em> portion.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>AF_NETLINK sockets are represented as  pairs <code class="docutils literal notranslate"><span class="pre">pid,</span> <span class="pre">groups</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Linux-only support for TIPC is also available using the <code class="xref py py-const docutils literal notranslate"><span class="pre">AF_TIPC</span></code>
address family. TIPC is an open, non-IP based networked protocol designed
for use in clustered computer environments.  Addresses are represented by a
tuple, and the fields depend on the address type. The general tuple form is
<code class="docutils literal notranslate"><span class="pre">(addr_type,</span> <span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">v3</span> <span class="pre">[,</span> <span class="pre">scope])</span></code>, where:</p>
<ul>
<li><p class="first"><em>addr_type</em> is one of <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAMESEQ</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAME</span></code>,
or <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_ID</span></code>.</p>
</li>
<li><p class="first"><em>scope</em> is one of <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ZONE_SCOPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_CLUSTER_SCOPE</span></code>,
and <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_NODE_SCOPE</span></code>.</p>
</li>
<li><p class="first">If <em>addr_type</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAME</span></code>, then <em>v1</em> is the server type, <em>v2</em> is
the port identifier, and <em>v3</em> should be 0.</p>
<p>If <em>addr_type</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_NAMESEQ</span></code>, then <em>v1</em> is the server type, <em>v2</em>
is the lower port number, and <em>v3</em> is the upper port number.</p>
<p>If <em>addr_type</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">TIPC_ADDR_ID</span></code>, then <em>v1</em> is the node, <em>v2</em> is the
reference, and <em>v3</em> should be set to 0.</p>
</li>
</ul>
</div>
<p>All errors raise exceptions.  The normal exceptions for invalid argument types
and out-of-memory conditions can be raised; errors related to socket or address
semantics raise the error <a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a>.</p>
<p>Non-blocking mode is supported through <a class="reference internal" href="#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a>.  A
generalization of this based on timeouts is supported through
<a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>.</p>
<p>The module <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> exports the following constants and functions:</p>
<dl class="exception">
<dt id="socket.error">
<em class="property">exception </em><code class="descclassname">socket.</code><code class="descname">error</code><a class="headerlink" href="#socket.error" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">This exception is raised for socket-related errors. The accompanying value is
either a string telling what went wrong or a pair <code class="docutils literal notranslate"><span class="pre">(errno,</span> <span class="pre">string)</span></code>
representing an error returned by a system call, similar to the value
accompanying <a class="reference internal" href="os.html#os.error" title="os.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">os.error</span></code></a>. See the module <a class="reference internal" href="errno.html#module-errno" title="errno: Standard errno system symbols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">errno</span></code></a>, which contains names
for the error codes defined by the underlying operating system.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> is now a child class of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="socket.herror">
<em class="property">exception </em><code class="descclassname">socket.</code><code class="descname">herror</code><a class="headerlink" href="#socket.herror" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised for address-related errors, i.e. for functions that use
<em>h_errno</em> in the C API, including <a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a> and
<a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a>.</p>
<p>The accompanying value is a pair <code class="docutils literal notranslate"><span class="pre">(h_errno,</span> <span class="pre">string)</span></code> representing an error
returned by a library call. <em>string</em> represents the description of <em>h_errno</em>, as
returned by the <code class="xref c c-func docutils literal notranslate"><span class="pre">hstrerror()</span></code> C function.</p>
</dd></dl>

<dl class="exception">
<dt id="socket.gaierror">
<em class="property">exception </em><code class="descclassname">socket.</code><code class="descname">gaierror</code><a class="headerlink" href="#socket.gaierror" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised for address-related errors, for <a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> and
<a class="reference internal" href="#socket.getnameinfo" title="socket.getnameinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getnameinfo()</span></code></a>. The accompanying value is a pair <code class="docutils literal notranslate"><span class="pre">(error,</span> <span class="pre">string)</span></code>
representing an error returned by a library call. <em>string</em> represents the
description of <em>error</em>, as returned by the <code class="xref c c-func docutils literal notranslate"><span class="pre">gai_strerror()</span></code> C function. The
<em>error</em> value will match one of the <code class="xref py py-const docutils literal notranslate"><span class="pre">EAI_*</span></code> constants defined in this
module.</p>
</dd></dl>

<dl class="exception">
<dt id="socket.timeout">
<em class="property">exception </em><code class="descclassname">socket.</code><code class="descname">timeout</code><a class="headerlink" href="#socket.timeout" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a timeout occurs on a socket which has had
timeouts enabled via a prior call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code>.  The accompanying value
is a string whose value is currently always “timed out”.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.AF_UNIX">
<code class="descclassname">socket.</code><code class="descname">AF_UNIX</code><a class="headerlink" href="#socket.AF_UNIX" title="Permalink to this definition">¶</a></dt>
<dt id="socket.AF_INET">
<code class="descclassname">socket.</code><code class="descname">AF_INET</code><a class="headerlink" href="#socket.AF_INET" title="Permalink to this definition">¶</a></dt>
<dt id="socket.AF_INET6">
<code class="descclassname">socket.</code><code class="descname">AF_INET6</code><a class="headerlink" href="#socket.AF_INET6" title="Permalink to this definition">¶</a></dt>
<dd><p>These constants represent the address (and protocol) families, used for the
first argument to <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>.  If the <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a> constant is not
defined then this protocol is unsupported.</p>
</dd></dl>

<dl class="data">
<dt id="socket.SOCK_STREAM">
<code class="descclassname">socket.</code><code class="descname">SOCK_STREAM</code><a class="headerlink" href="#socket.SOCK_STREAM" title="Permalink to this definition">¶</a></dt>
<dt id="socket.SOCK_DGRAM">
<code class="descclassname">socket.</code><code class="descname">SOCK_DGRAM</code><a class="headerlink" href="#socket.SOCK_DGRAM" title="Permalink to this definition">¶</a></dt>
<dt id="socket.SOCK_RAW">
<code class="descclassname">socket.</code><code class="descname">SOCK_RAW</code><a class="headerlink" href="#socket.SOCK_RAW" title="Permalink to this definition">¶</a></dt>
<dt id="socket.SOCK_RDM">
<code class="descclassname">socket.</code><code class="descname">SOCK_RDM</code><a class="headerlink" href="#socket.SOCK_RDM" title="Permalink to this definition">¶</a></dt>
<dt id="socket.SOCK_SEQPACKET">
<code class="descclassname">socket.</code><code class="descname">SOCK_SEQPACKET</code><a class="headerlink" href="#socket.SOCK_SEQPACKET" title="Permalink to this definition">¶</a></dt>
<dd><p>These constants represent the socket types, used for the second argument to
<a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>. (Only <a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> and <a class="reference internal" href="#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a> appear to be
generally useful.)</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">SO_*</code></dt>
<dt id="socket.SOMAXCONN">
<code class="descclassname">socket.</code><code class="descname">SOMAXCONN</code><a class="headerlink" href="#socket.SOMAXCONN" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">MSG_*</code></dt>
<dt>
<code class="descname">SOL_*</code></dt>
<dt>
<code class="descname">IPPROTO_*</code></dt>
<dt>
<code class="descname">IPPORT_*</code></dt>
<dt>
<code class="descname">INADDR_*</code></dt>
<dt>
<code class="descname">IP_*</code></dt>
<dt>
<code class="descname">IPV6_*</code></dt>
<dt>
<code class="descname">EAI_*</code></dt>
<dt>
<code class="descname">AI_*</code></dt>
<dt>
<code class="descname">NI_*</code></dt>
<dt>
<code class="descname">TCP_*</code></dt>
<dd><p>Many constants of these forms, documented in the Unix documentation on sockets
and/or the IP protocol, are also defined in the socket module. They are
generally used in arguments to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">setsockopt()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">getsockopt()</span></code>
methods of socket objects.  In most cases, only those symbols that are defined
in the Unix header files are defined; for a few symbols, default values are
provided.</p>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">SIO_*</code></dt>
<dt>
<code class="descname">RCVALL_*</code></dt>
<dd><p>Constants for Windows’ WSAIoctl(). The constants are used as arguments to the
<a class="reference internal" href="#socket.socket.ioctl" title="socket.socket.ioctl"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code></a> method of socket objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt>
<code class="descname">TIPC_*</code></dt>
<dd><p>TIPC related constants, matching the ones exported by the C socket API. See
the TIPC documentation for more information.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.has_ipv6">
<code class="descclassname">socket.</code><code class="descname">has_ipv6</code><a class="headerlink" href="#socket.has_ipv6" title="Permalink to this definition">¶</a></dt>
<dd><p>This constant contains a boolean value which indicates if IPv6 is supported on
this platform.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.create_connection">
<code class="descclassname">socket.</code><code class="descname">create_connection</code><span class="sig-paren">(</span><em>address</em><span class="optional">[</span>, <em>timeout</em><span class="optional">[</span>, <em>source_address</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.create_connection" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to a TCP service listening on the Internet <em>address</em> (a 2-tuple
<code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code>), and return the socket object.  This is a higher-level
function than <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a>: if <em>host</em> is a non-numeric hostname,
it will try to resolve it for both <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET</span></code></a> and <a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-data docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>,
and then try to connect to all possible addresses in turn until a
connection succeeds.  This makes it easy to write clients that are
compatible to both IPv4 and IPv6.</p>
<p>Passing the optional <em>timeout</em> parameter will set the timeout on the
socket instance before attempting to connect.  If no <em>timeout</em> is
supplied, the global default timeout setting returned by
<a class="reference internal" href="#socket.getdefaulttimeout" title="socket.getdefaulttimeout"><code class="xref py py-func docutils literal notranslate"><span class="pre">getdefaulttimeout()</span></code></a> is used.</p>
<p>If supplied, <em>source_address</em> must be a 2-tuple <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> for the
socket to bind to as its source address before connecting.  If host or port
are ‘’ or 0 respectively the OS default behavior will be used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><em>source_address</em> was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getaddrinfo">
<code class="descclassname">socket.</code><code class="descname">getaddrinfo</code><span class="sig-paren">(</span><em>host</em>, <em>port</em><span class="optional">[</span>, <em>family</em><span class="optional">[</span>, <em>socktype</em><span class="optional">[</span>, <em>proto</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getaddrinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate the <em>host</em>/<em>port</em> argument into a sequence of 5-tuples that contain
all the necessary arguments for creating a socket connected to that service.
<em>host</em> is a domain name, a string representation of an IPv4/v6 address
or <code class="docutils literal notranslate"><span class="pre">None</span></code>. <em>port</em> is a string service name such as <code class="docutils literal notranslate"><span class="pre">'http'</span></code>, a numeric
port number or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  By passing <code class="docutils literal notranslate"><span class="pre">None</span></code> as the value of <em>host</em>
and <em>port</em>, you can pass <code class="docutils literal notranslate"><span class="pre">NULL</span></code> to the underlying C API.</p>
<p>The <em>family</em>, <em>socktype</em> and <em>proto</em> arguments can be optionally specified
in order to narrow the list of addresses returned.  By default, their value
is <code class="docutils literal notranslate"><span class="pre">0</span></code>, meaning that the full range of results is selected.
The <em>flags</em> argument can be one or several of the <code class="docutils literal notranslate"><span class="pre">AI_*</span></code> constants,
and will influence how results are computed and returned.  Its default value
is <code class="docutils literal notranslate"><span class="pre">0</span></code>.  For example, <code class="xref py py-const docutils literal notranslate"><span class="pre">AI_NUMERICHOST</span></code> will disable domain name
resolution and will raise an error if <em>host</em> is a domain name.</p>
<p>The function returns a list of 5-tuples with the following structure:</p>
<p><code class="docutils literal notranslate"><span class="pre">(family,</span> <span class="pre">socktype,</span> <span class="pre">proto,</span> <span class="pre">canonname,</span> <span class="pre">sockaddr)</span></code></p>
<p>In these tuples, <em>family</em>, <em>socktype</em>, <em>proto</em> are all integers and are
meant to be passed to the <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> function.  <em>canonname</em> will be
a string representing the canonical name of the <em>host</em> if
<code class="xref py py-const docutils literal notranslate"><span class="pre">AI_CANONNAME</span></code> is part of the <em>flags</em> argument; else <em>canonname</em>
will be empty.  <em>sockaddr</em> is a tuple describing a socket address, whose
format depends on the returned <em>family</em> (a <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">port)</span></code> 2-tuple for
<a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>, a <code class="docutils literal notranslate"><span class="pre">(address,</span> <span class="pre">port,</span> <span class="pre">flow</span> <span class="pre">info,</span> <span class="pre">scope</span> <span class="pre">id)</span></code> 4-tuple for
<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>), and is meant to be passed to the <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code></a>
method.</p>
<p>The following example fetches address information for a hypothetical TCP
connection to <code class="docutils literal notranslate"><span class="pre">example.org</span></code> on port 80 (results may differ on your
system if IPv6 isn’t enabled):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="s2">&quot;example.org&quot;</span><span class="p">,</span> <span class="mi">80</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_TCP</span><span class="p">)</span>
<span class="go">[(10, 1, 6, &#39;&#39;, (&#39;2606:2800:220:1:248:1893:25c8:1946&#39;, 80, 0, 0)),</span>
<span class="go"> (2, 1, 6, &#39;&#39;, (&#39;93.184.216.34&#39;, 80))]</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getfqdn">
<code class="descclassname">socket.</code><code class="descname">getfqdn</code><span class="sig-paren">(</span><span class="optional">[</span><em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getfqdn" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a fully qualified domain name for <em>name</em>. If <em>name</em> is omitted or empty,
it is interpreted as the local host.  To find the fully qualified name, the
hostname returned by <a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a> is checked, followed by aliases for the
host, if available.  The first name which includes a period is selected.  In
case no fully qualified domain name is available, the hostname as returned by
<a class="reference internal" href="#socket.gethostname" title="socket.gethostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostname()</span></code></a> is returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyname">
<code class="descclassname">socket.</code><code class="descname">gethostbyname</code><span class="sig-paren">(</span><em>hostname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyname" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate a host name to IPv4 address format.  The IPv4 address is returned as a
string, such as  <code class="docutils literal notranslate"><span class="pre">'100.50.200.5'</span></code>.  If the host name is an IPv4 address itself
it is returned unchanged.  See <a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a> for a more complete
interface. <a class="reference internal" href="#socket.gethostbyname" title="socket.gethostbyname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname()</span></code></a> does not support IPv6 name resolution, and
<a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> should be used instead for IPv4/v6 dual stack support.</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyname_ex">
<code class="descclassname">socket.</code><code class="descname">gethostbyname_ex</code><span class="sig-paren">(</span><em>hostname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyname_ex" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate a host name to IPv4 address format, extended interface. Return a
triple <code class="docutils literal notranslate"><span class="pre">(hostname,</span> <span class="pre">aliaslist,</span> <span class="pre">ipaddrlist)</span></code> where <em>hostname</em> is the primary
host name responding to the given <em>ip_address</em>, <em>aliaslist</em> is a (possibly
empty) list of alternative host names for the same address, and <em>ipaddrlist</em> is
a list of IPv4 addresses for the same interface on the same host (often but not
always a single address). <a class="reference internal" href="#socket.gethostbyname_ex" title="socket.gethostbyname_ex"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyname_ex()</span></code></a> does not support IPv6 name
resolution, and <a class="reference internal" href="#socket.getaddrinfo" title="socket.getaddrinfo"><code class="xref py py-func docutils literal notranslate"><span class="pre">getaddrinfo()</span></code></a> should be used instead for IPv4/v6 dual
stack support.</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostname">
<code class="descclassname">socket.</code><code class="descname">gethostname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing the hostname of the machine where  the Python
interpreter is currently executing.</p>
<p>If you want to know the current machine’s IP address, you may want to use
<code class="docutils literal notranslate"><span class="pre">gethostbyname(gethostname())</span></code>. This operation assumes that there is a
valid address-to-host mapping for the host, and the assumption does not
always hold.</p>
<p>Note: <a class="reference internal" href="#socket.gethostname" title="socket.gethostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostname()</span></code></a> doesn’t always return the fully qualified domain
name; use <code class="docutils literal notranslate"><span class="pre">getfqdn()</span></code> (see above).</p>
</dd></dl>

<dl class="function">
<dt id="socket.gethostbyaddr">
<code class="descclassname">socket.</code><code class="descname">gethostbyaddr</code><span class="sig-paren">(</span><em>ip_address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.gethostbyaddr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a triple <code class="docutils literal notranslate"><span class="pre">(hostname,</span> <span class="pre">aliaslist,</span> <span class="pre">ipaddrlist)</span></code> where <em>hostname</em> is the
primary host name responding to the given <em>ip_address</em>, <em>aliaslist</em> is a
(possibly empty) list of alternative host names for the same address, and
<em>ipaddrlist</em> is a list of IPv4/v6 addresses for the same interface on the same
host (most likely containing only a single address). To find the fully qualified
domain name, use the function <a class="reference internal" href="#socket.getfqdn" title="socket.getfqdn"><code class="xref py py-func docutils literal notranslate"><span class="pre">getfqdn()</span></code></a>. <a class="reference internal" href="#socket.gethostbyaddr" title="socket.gethostbyaddr"><code class="xref py py-func docutils literal notranslate"><span class="pre">gethostbyaddr()</span></code></a> supports
both IPv4 and IPv6.</p>
</dd></dl>

<dl class="function">
<dt id="socket.getnameinfo">
<code class="descclassname">socket.</code><code class="descname">getnameinfo</code><span class="sig-paren">(</span><em>sockaddr</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.getnameinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate a socket address <em>sockaddr</em> into a 2-tuple <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code>. Depending
on the settings of <em>flags</em>, the result can contain a fully-qualified domain name
or numeric address representation in <em>host</em>.  Similarly, <em>port</em> can contain a
string port name or a numeric port number.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getprotobyname">
<code class="descclassname">socket.</code><code class="descname">getprotobyname</code><span class="sig-paren">(</span><em>protocolname</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.getprotobyname" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate an Internet protocol name (for example, <code class="docutils literal notranslate"><span class="pre">'icmp'</span></code>) to a constant
suitable for passing as the (optional) third argument to the <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>
function.  This is usually only needed for sockets opened in “raw” mode
(<a class="reference internal" href="#socket.SOCK_RAW" title="socket.SOCK_RAW"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_RAW</span></code></a>); for the normal socket modes, the correct protocol is chosen
automatically if the protocol is omitted or zero.</p>
</dd></dl>

<dl class="function">
<dt id="socket.getservbyname">
<code class="descclassname">socket.</code><code class="descname">getservbyname</code><span class="sig-paren">(</span><em>servicename</em><span class="optional">[</span>, <em>protocolname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getservbyname" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate an Internet service name and protocol name to a port number for that
service.  The optional protocol name, if given, should be <code class="docutils literal notranslate"><span class="pre">'tcp'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'udp'</span></code>, otherwise any protocol will match.</p>
</dd></dl>

<dl class="function">
<dt id="socket.getservbyport">
<code class="descclassname">socket.</code><code class="descname">getservbyport</code><span class="sig-paren">(</span><em>port</em><span class="optional">[</span>, <em>protocolname</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getservbyport" title="Permalink to this definition">¶</a></dt>
<dd><p>Translate an Internet port number and protocol name to a service name for that
service.  The optional protocol name, if given, should be <code class="docutils literal notranslate"><span class="pre">'tcp'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'udp'</span></code>, otherwise any protocol will match.</p>
</dd></dl>

<dl class="function">
<dt id="socket.socket">
<code class="descclassname">socket.</code><code class="descname">socket</code><span class="sig-paren">(</span><span class="optional">[</span><em>family</em><span class="optional">[</span>, <em>type</em><span class="optional">[</span>, <em>proto</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new socket using the given address family, socket type and protocol
number.  The address family should be <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> (the default),
<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a> or <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>.  The socket type should be
<a class="reference internal" href="#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> (the default), <a class="reference internal" href="#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">SOCK_DGRAM</span></code></a> or perhaps one of the
other <code class="docutils literal notranslate"><span class="pre">SOCK_</span></code> constants.  The protocol number is usually zero and may be
omitted in that case.</p>
</dd></dl>

<dl class="function">
<dt id="socket.socketpair">
<code class="descclassname">socket.</code><code class="descname">socketpair</code><span class="sig-paren">(</span><span class="optional">[</span><em>family</em><span class="optional">[</span>, <em>type</em><span class="optional">[</span>, <em>proto</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socketpair" title="Permalink to this definition">¶</a></dt>
<dd><p>Build a pair of connected socket objects using the given address family, socket
type, and protocol number.  Address family, socket type, and protocol number are
as for the <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> function above. The default family is <a class="reference internal" href="#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_UNIX</span></code></a>
if defined on the platform; otherwise, the default is <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>.
Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.fromfd">
<code class="descclassname">socket.</code><code class="descname">fromfd</code><span class="sig-paren">(</span><em>fd</em>, <em>family</em>, <em>type</em><span class="optional">[</span>, <em>proto</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.fromfd" title="Permalink to this definition">¶</a></dt>
<dd><p>Duplicate the file descriptor <em>fd</em> (an integer as returned by a file object’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> method) and build a socket object from the result.  Address
family, socket type and protocol number are as for the <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a> function
above. The file descriptor should refer to a socket, but this is not checked —
subsequent operations on the object may fail if the file descriptor is invalid.
This function is rarely needed, but can be used to get or set socket options on
a socket passed to a program as standard input or output (such as a server
started by the Unix inet daemon).  The socket is assumed to be in blocking mode.
Availability: Unix.</p>
</dd></dl>

<dl class="function">
<dt id="socket.ntohl">
<code class="descclassname">socket.</code><code class="descname">ntohl</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.ntohl" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert 32-bit positive integers from network to host byte order.  On machines
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 4-byte swap operation.</p>
</dd></dl>

<dl class="function">
<dt id="socket.ntohs">
<code class="descclassname">socket.</code><code class="descname">ntohs</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.ntohs" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert 16-bit positive integers from network to host byte order.  On machines
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 2-byte swap operation.</p>
</dd></dl>

<dl class="function">
<dt id="socket.htonl">
<code class="descclassname">socket.</code><code class="descname">htonl</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.htonl" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert 32-bit positive integers from host to network byte order.  On machines
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 4-byte swap operation.</p>
</dd></dl>

<dl class="function">
<dt id="socket.htons">
<code class="descclassname">socket.</code><code class="descname">htons</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.htons" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert 16-bit positive integers from host to network byte order.  On machines
where the host byte order is the same as network byte order, this is a no-op;
otherwise, it performs a 2-byte swap operation.</p>
</dd></dl>

<dl class="function">
<dt id="socket.inet_aton">
<code class="descclassname">socket.</code><code class="descname">inet_aton</code><span class="sig-paren">(</span><em>ip_string</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_aton" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an IPv4 address from dotted-quad string format (for example,
‘123.45.67.89’) to 32-bit packed binary format, as a string four characters in
length.  This is useful when conversing with a program that uses the standard C
library and needs objects of type <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code>, which is the C type
for the 32-bit packed binary this function returns.</p>
<p><a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a> also accepts strings with less than three dots; see the
Unix manual page <em class="manpage">inet(3)</em> for details.</p>
<p>If the IPv4 address string passed to this function is invalid,
<a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> will be raised. Note that exactly what is valid depends on
the underlying C implementation of <code class="xref c c-func docutils literal notranslate"><span class="pre">inet_aton()</span></code>.</p>
<p><a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a> does not support IPv6, and <a class="reference internal" href="#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_pton()</span></code></a> should be used
instead for IPv4/v6 dual stack support.</p>
</dd></dl>

<dl class="function">
<dt id="socket.inet_ntoa">
<code class="descclassname">socket.</code><code class="descname">inet_ntoa</code><span class="sig-paren">(</span><em>packed_ip</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_ntoa" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a 32-bit packed IPv4 address (a string four characters in length) to its
standard dotted-quad string representation (for example, ‘123.45.67.89’).  This
is useful when conversing with a program that uses the standard C library and
needs objects of type <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code>, which is the C type for the
32-bit packed binary data this function takes as an argument.</p>
<p>If the string passed to this function is not exactly 4 bytes in length,
<a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> will be raised. <a class="reference internal" href="#socket.inet_ntoa" title="socket.inet_ntoa"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntoa()</span></code></a> does not support IPv6, and
<a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a> should be used instead for IPv4/v6 dual stack support.</p>
</dd></dl>

<dl class="function">
<dt id="socket.inet_pton">
<code class="descclassname">socket.</code><code class="descname">inet_pton</code><span class="sig-paren">(</span><em>address_family</em>, <em>ip_string</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_pton" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an IP address from its family-specific string format to a packed, binary
format. <a class="reference internal" href="#socket.inet_pton" title="socket.inet_pton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_pton()</span></code></a> is useful when a library or network protocol calls for
an object of type <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> (similar to <a class="reference internal" href="#socket.inet_aton" title="socket.inet_aton"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_aton()</span></code></a>) or
<code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in6_addr</span></code>.</p>
<p>Supported values for <em>address_family</em> are currently <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> and
<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>. If the IP address string <em>ip_string</em> is invalid,
<a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> will be raised. Note that exactly what is valid depends on
both the value of <em>address_family</em> and the underlying implementation of
<code class="xref c c-func docutils literal notranslate"><span class="pre">inet_pton()</span></code>.</p>
<p>Availability: Unix (maybe not all platforms).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.inet_ntop">
<code class="descclassname">socket.</code><code class="descname">inet_ntop</code><span class="sig-paren">(</span><em>address_family</em>, <em>packed_ip</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.inet_ntop" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a packed IP address (a string of some number of characters) to its
standard, family-specific string representation (for example, <code class="docutils literal notranslate"><span class="pre">'7.10.0.5'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'5aef:2b::8'</span></code>) <a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a> is useful when a library or network protocol
returns an object of type <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in_addr</span></code> (similar to <a class="reference internal" href="#socket.inet_ntoa" title="socket.inet_ntoa"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntoa()</span></code></a>)
or <code class="xref c c-type docutils literal notranslate"><span class="pre">struct</span> <span class="pre">in6_addr</span></code>.</p>
<p>Supported values for <em>address_family</em> are currently <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a> and
<a class="reference internal" href="#socket.AF_INET6" title="socket.AF_INET6"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET6</span></code></a>. If the string <em>packed_ip</em> is not the correct length for the
specified address family, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised.  A
<a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> is raised for errors from the call to <a class="reference internal" href="#socket.inet_ntop" title="socket.inet_ntop"><code class="xref py py-func docutils literal notranslate"><span class="pre">inet_ntop()</span></code></a>.</p>
<p>Availability: Unix (maybe not all platforms).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.getdefaulttimeout">
<code class="descclassname">socket.</code><code class="descname">getdefaulttimeout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.getdefaulttimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the default timeout in seconds (float) for new socket objects. A value
of <code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that new socket objects have no timeout. When the socket
module is first imported, the default is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="socket.setdefaulttimeout">
<code class="descclassname">socket.</code><code class="descname">setdefaulttimeout</code><span class="sig-paren">(</span><em>timeout</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.setdefaulttimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the default timeout in seconds (float) for new socket objects. A value of
<code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that new socket objects have no timeout. When the socket
module is first imported, the default is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="socket.SocketType">
<code class="descclassname">socket.</code><code class="descname">SocketType</code><a class="headerlink" href="#socket.SocketType" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a Python type object that represents the socket object type. It is the
same as <code class="docutils literal notranslate"><span class="pre">type(socket(...))</span></code>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="socketserver.html#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a></dt>
<dd>Classes that simplify writing network servers.</dd>
<dt>Module <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a></dt>
<dd>A TLS/SSL wrapper for socket objects.</dd>
</dl>
</div>
<div class="section" id="socket-objects">
<span id="id1"></span><h2>17.2.1. Socket Objects<a class="headerlink" href="#socket-objects" title="Permalink to this headline">¶</a></h2>
<p>Socket objects have the following methods.  Except for <code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code> these
correspond to Unix system calls applicable to sockets.</p>
<dl class="method">
<dt id="socket.socket.accept">
<code class="descclassname">socket.</code><code class="descname">accept</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.accept" title="Permalink to this definition">¶</a></dt>
<dd><p>Accept a connection. The socket must be bound to an address and listening for
connections. The return value is a pair <code class="docutils literal notranslate"><span class="pre">(conn,</span> <span class="pre">address)</span></code> where <em>conn</em> is a
<em>new</em> socket object usable to send and receive data on the connection, and
<em>address</em> is the address bound to the socket on the other end of the connection.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.bind">
<code class="descclassname">socket.</code><code class="descname">bind</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind the socket to <em>address</em>.  The socket must not already be bound. (The format
of <em>address</em> depends on the address family — see above.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method has historically accepted a pair of parameters for <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>
addresses instead of only a tuple.  This was never intentional and is no longer
available in Python 2.0 and later.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.close">
<code class="descclassname">socket.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the socket.  All future operations on the socket object will fail. The
remote end will receive no more data (after queued data is flushed). Sockets are
automatically closed when they are garbage-collected.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#socket.socket.close" title="socket.socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> releases the resource associated with a connection but
does not necessarily close the connection immediately.  If you want
to close the connection in a timely fashion, call <a class="reference internal" href="#socket.socket.shutdown" title="socket.socket.shutdown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shutdown()</span></code></a>
before <a class="reference internal" href="#socket.socket.close" title="socket.socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.connect">
<code class="descclassname">socket.</code><code class="descname">connect</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to a remote socket at <em>address</em>. (The format of <em>address</em> depends on the
address family — see above.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method has historically accepted a pair of parameters for <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>
addresses instead of only a tuple.  This was never intentional and is no longer
available in Python 2.0 and later.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.connect_ex">
<code class="descclassname">socket.</code><code class="descname">connect_ex</code><span class="sig-paren">(</span><em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.connect_ex" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <code class="docutils literal notranslate"><span class="pre">connect(address)</span></code>, but return an error indicator instead of raising an
exception for errors returned by the C-level <code class="xref c c-func docutils literal notranslate"><span class="pre">connect()</span></code> call (other
problems, such as “host not found,” can still raise exceptions).  The error
indicator is <code class="docutils literal notranslate"><span class="pre">0</span></code> if the operation succeeded, otherwise the value of the
<code class="xref c c-data docutils literal notranslate"><span class="pre">errno</span></code> variable.  This is useful to support, for example, asynchronous
connects.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method has historically accepted a pair of parameters for <a class="reference internal" href="#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">AF_INET</span></code></a>
addresses instead of only a tuple. This was never intentional and is no longer
available in Python 2.0 and later.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.fileno">
<code class="descclassname">socket.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the socket’s file descriptor (a small integer).  This is useful with
<a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select.select()</span></code></a>.</p>
<p>Under Windows the small integer returned by this method cannot be used where a
file descriptor can be used (such as <a class="reference internal" href="os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a>).  Unix does not have
this limitation.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getpeername">
<code class="descclassname">socket.</code><code class="descname">getpeername</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getpeername" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the remote address to which the socket is connected.  This is useful to
find out the port number of a remote IPv4/v6 socket, for instance. (The format
of the address returned depends on the address family — see above.)  On some
systems this function is not supported.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getsockname">
<code class="descclassname">socket.</code><code class="descname">getsockname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getsockname" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the socket’s own address.  This is useful to find out the port number of
an IPv4/v6 socket, for instance. (The format of the address returned depends on
the address family — see above.)</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.getsockopt">
<code class="descclassname">socket.</code><code class="descname">getsockopt</code><span class="sig-paren">(</span><em>level</em>, <em>optname</em><span class="optional">[</span>, <em>buflen</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.getsockopt" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the given socket option (see the Unix man page
<em class="manpage">getsockopt(2)</em>).  The needed symbolic constants (<code class="xref py py-const docutils literal notranslate"><span class="pre">SO_*</span></code> etc.)
are defined in this module.  If <em>buflen</em> is absent, an integer option is assumed
and its integer value is returned by the function.  If <em>buflen</em> is present, it
specifies the maximum length of the buffer used to receive the option in, and
this buffer is returned as a string.  It is up to the caller to decode the
contents of the buffer (see the optional built-in module <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> for a way
to decode C structures encoded as strings).</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.ioctl">
<code class="descclassname">socket.</code><code class="descname">ioctl</code><span class="sig-paren">(</span><em>control</em>, <em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.ioctl" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Platform:</th><td class="field-body">Windows</td>
</tr>
</tbody>
</table>
<p>The <a class="reference internal" href="#socket.socket.ioctl" title="socket.socket.ioctl"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code></a> method is a limited interface to the WSAIoctl system
interface.  Please refer to the <a class="reference external" href="https://msdn.microsoft.com/en-us/library/ms741621%28VS.85%29.aspx">Win32 documentation</a> for more
information.</p>
<p>On other platforms, the generic <a class="reference internal" href="fcntl.html#fcntl.fcntl" title="fcntl.fcntl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.fcntl()</span></code></a> and <a class="reference internal" href="fcntl.html#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.ioctl()</span></code></a>
functions may be used; they accept a socket object as their first argument.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.listen">
<code class="descclassname">socket.</code><code class="descname">listen</code><span class="sig-paren">(</span><em>backlog</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.listen" title="Permalink to this definition">¶</a></dt>
<dd><p>Listen for connections made to the socket.  The <em>backlog</em> argument specifies the
maximum number of queued connections and should be at least 0; the maximum value
is system-dependent (usually 5), the minimum value is forced to 0.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.makefile">
<code class="descclassname">socket.</code><code class="descname">makefile</code><span class="sig-paren">(</span><span class="optional">[</span><em>mode</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.makefile" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Return a <em class="dfn">file object</em> associated with the socket.  (File objects are
described in <a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>.) The file object does not close the
socket explicitly when its <a class="reference internal" href="#socket.socket.close" title="socket.socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method is called, but only removes
its reference to the socket object, so that the socket will be closed if it
is not referenced from anywhere else.</p>
<p>The socket must be in blocking mode (it can not have a timeout). The optional
<em>mode</em> and <em>bufsize</em> arguments are interpreted the same way as by the built-in
<a class="reference internal" href="functions.html#file" title="file"><code class="xref py py-func docutils literal notranslate"><span class="pre">file()</span></code></a> function.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Windows, the file-like object created by <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> cannot be
used where a file object with a file descriptor is expected, such as the
stream arguments of <a class="reference internal" href="subprocess.html#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subprocess.Popen()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recv">
<code class="descclassname">socket.</code><code class="descname">recv</code><span class="sig-paren">(</span><em>bufsize</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recv" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive data from the socket.  The return value is a string representing the
data received.  The maximum amount of data to be received at once is specified
by <em>bufsize</em>.  See the Unix manual page <em class="manpage">recv(2)</em> for the meaning of
the optional argument <em>flags</em>; it defaults to zero.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For best match with hardware and network realities, the value of  <em>bufsize</em>
should be a relatively small power of 2, for example, 4096.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvfrom">
<code class="descclassname">socket.</code><code class="descname">recvfrom</code><span class="sig-paren">(</span><em>bufsize</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvfrom" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive data from the socket.  The return value is a pair <code class="docutils literal notranslate"><span class="pre">(string,</span> <span class="pre">address)</span></code>
where <em>string</em> is a string representing the data received and <em>address</em> is the
address of the socket sending the data.  See the Unix manual page
<em class="manpage">recv(2)</em> for the meaning of the optional argument <em>flags</em>; it defaults
to zero. (The format of <em>address</em> depends on the address family — see above.)</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recvfrom_into">
<code class="descclassname">socket.</code><code class="descname">recvfrom_into</code><span class="sig-paren">(</span><em>buffer</em><span class="optional">[</span>, <em>nbytes</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recvfrom_into" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive data from the socket, writing it into <em>buffer</em> instead of  creating a
new string.  The return value is a pair <code class="docutils literal notranslate"><span class="pre">(nbytes,</span> <span class="pre">address)</span></code> where <em>nbytes</em> is
the number of bytes received and <em>address</em> is the address of the socket sending
the data.  See the Unix manual page <em class="manpage">recv(2)</em> for the meaning of the
optional argument <em>flags</em>; it defaults to zero.  (The format of <em>address</em>
depends on the address family — see above.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.recv_into">
<code class="descclassname">socket.</code><code class="descname">recv_into</code><span class="sig-paren">(</span><em>buffer</em><span class="optional">[</span>, <em>nbytes</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.recv_into" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive up to <em>nbytes</em> bytes from the socket, storing the data into a buffer
rather than creating a new string.  If <em>nbytes</em> is not specified (or 0),
receive up to the size available in the given buffer.  Returns the number of
bytes received.  See the Unix manual page <em class="manpage">recv(2)</em> for the meaning
of the optional argument <em>flags</em>; it defaults to zero.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.send">
<code class="descclassname">socket.</code><code class="descname">send</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Send data to the socket.  The socket must be connected to a remote socket.  The
optional <em>flags</em> argument has the same meaning as for <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> above.
Returns the number of bytes sent. Applications are responsible for checking that
all data has been sent; if only some of the data was transmitted, the
application needs to attempt delivery of the remaining data. For further
information on this concept, consult the <a class="reference internal" href="../howto/sockets.html#socket-howto"><span class="std std-ref">Socket Programming HOWTO</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendall">
<code class="descclassname">socket.</code><code class="descname">sendall</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>flags</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendall" title="Permalink to this definition">¶</a></dt>
<dd><p>Send data to the socket.  The socket must be connected to a remote socket.  The
optional <em>flags</em> argument has the same meaning as for <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> above.
Unlike <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>, this method continues to send data from <em>string</em> until
either all data has been sent or an error occurs.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned on
success.  On error, an exception is raised, and there is no way to determine how
much data, if any, was successfully sent.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.sendto">
<code class="descclassname">socket.</code><code class="descname">sendto</code><span class="sig-paren">(</span><em>string</em>, <em>address</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.sendto" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">socket.</code><code class="descname">sendto</code><span class="sig-paren">(</span><em>string</em>, <em>flags</em>, <em>address</em><span class="sig-paren">)</span></dt>
<dd><p>Send data to the socket.  The socket should not be connected to a remote socket,
since the destination socket is specified by <em>address</em>.  The optional <em>flags</em>
argument has the same meaning as for <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> above.  Return the number of
bytes sent. (The format of <em>address</em> depends on the address family — see
above.)</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.setblocking">
<code class="descclassname">socket.</code><code class="descname">setblocking</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.setblocking" title="Permalink to this definition">¶</a></dt>
<dd><p>Set blocking or non-blocking mode of the socket: if <em>flag</em> is 0, the socket is
set to non-blocking, else to blocking mode.  Initially all sockets are in
blocking mode.  In non-blocking mode, if a <a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> call doesn’t find any
data, or if a <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> call can’t immediately dispose of the data, an
<a class="reference internal" href="#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception is raised; in blocking mode, the calls block until they
can proceed. <code class="docutils literal notranslate"><span class="pre">s.setblocking(0)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s.settimeout(0.0)</span></code>;
<code class="docutils literal notranslate"><span class="pre">s.setblocking(1)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s.settimeout(None)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.settimeout">
<code class="descclassname">socket.</code><code class="descname">settimeout</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.settimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Set a timeout on blocking socket operations.  The <em>value</em> argument can be a
nonnegative float expressing seconds, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. If a float is given,
subsequent socket operations will raise a <a class="reference internal" href="#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">timeout</span></code></a> exception if the
timeout period <em>value</em> has elapsed before the operation has completed.  Setting
a timeout of <code class="docutils literal notranslate"><span class="pre">None</span></code> disables timeouts on socket operations.
<code class="docutils literal notranslate"><span class="pre">s.settimeout(0.0)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s.setblocking(0)</span></code>;
<code class="docutils literal notranslate"><span class="pre">s.settimeout(None)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s.setblocking(1)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="socket.socket.gettimeout">
<code class="descclassname">socket.</code><code class="descname">gettimeout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.gettimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the timeout in seconds (float) associated with socket operations, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if no timeout is set.  This reflects the last call to
<a class="reference internal" href="#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a> or <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>Some notes on socket blocking and timeouts: A socket object can be in one of
three modes: blocking, non-blocking, or timeout.  Sockets are always created in
blocking mode.  In blocking mode, operations block until complete or
the system returns an error (such as connection timed out).  In
non-blocking mode, operations fail (with an error that is unfortunately
system-dependent) if they cannot be completed immediately.  In timeout mode,
operations fail if they cannot be completed within the timeout specified for the
socket or if the system returns an error.  The <a class="reference internal" href="#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a>
method is simply a shorthand for certain <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a> calls.</p>
<p>Timeout mode internally sets the socket in non-blocking mode.  The blocking and
timeout modes are shared between file descriptors and socket objects that refer
to the same network endpoint.  A consequence of this is that file objects
returned by the <a class="reference internal" href="#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> method must only be used when the
socket is in blocking mode; in timeout or non-blocking mode file operations
that cannot be completed immediately will fail.</p>
<p>Note that the <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> operation is subject to the timeout
setting, and in general it is recommended to call <a class="reference internal" href="#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>
before calling <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a> or pass a timeout parameter to
<a class="reference internal" href="#socket.create_connection" title="socket.create_connection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">create_connection()</span></code></a>.  The system network stack may return a connection
timeout error of its own regardless of any Python socket timeout setting.</p>
<dl class="method">
<dt id="socket.socket.setsockopt">
<code class="descclassname">socket.</code><code class="descname">setsockopt</code><span class="sig-paren">(</span><em>level</em>, <em>optname</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.setsockopt" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">Set the value of the given socket option (see the Unix manual page
<em class="manpage">setsockopt(2)</em>).  The needed symbolic constants are defined in the
<a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module (<code class="xref py py-const docutils literal notranslate"><span class="pre">SO_*</span></code> etc.).  The value can be an integer or a
string representing a buffer.  In the latter case it is up to the caller to
ensure that the string contains the proper bits (see the optional built-in
module <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> for a way to encode C structures as strings).</p>
</dd></dl>

<dl class="method">
<dt id="socket.socket.shutdown">
<code class="descclassname">socket.</code><code class="descname">shutdown</code><span class="sig-paren">(</span><em>how</em><span class="sig-paren">)</span><a class="headerlink" href="#socket.socket.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Shut down one or both halves of the connection.  If <em>how</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_RD</span></code>,
further receives are disallowed.  If <em>how</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_WR</span></code>, further sends
are disallowed.  If <em>how</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">SHUT_RDWR</span></code>, further sends and receives are
disallowed.  Depending on the platform, shutting down one half of the connection
can also close the opposite half (e.g. on Mac OS X, <code class="docutils literal notranslate"><span class="pre">shutdown(SHUT_WR)</span></code> does
not allow further reads on the other end of the connection).</p>
</dd></dl>

<p>Note that there are no methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>; use
<a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> and <a class="reference internal" href="#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> without <em>flags</em> argument instead.</p>
<p>Socket objects also have these (read-only) attributes that correspond to the
values given to the <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket</span></code></a> constructor.</p>
<dl class="attribute">
<dt id="socket.socket.family">
<code class="descclassname">socket.</code><code class="descname">family</code><a class="headerlink" href="#socket.socket.family" title="Permalink to this definition">¶</a></dt>
<dd><p>The socket family.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="socket.socket.type">
<code class="descclassname">socket.</code><code class="descname">type</code><a class="headerlink" href="#socket.socket.type" title="Permalink to this definition">¶</a></dt>
<dd><p>The socket type.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="socket.socket.proto">
<code class="descclassname">socket.</code><code class="descname">proto</code><a class="headerlink" href="#socket.socket.proto" title="Permalink to this definition">¶</a></dt>
<dd><p>The socket protocol.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="example">
<span id="socket-example"></span><h2>17.2.2. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>Here are four minimal example programs using the TCP/IP protocol: a server that
echoes all data that it receives back (servicing only one client), and a client
using it.  Note that a server must perform the sequence <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>,
<a class="reference internal" href="#socket.socket.bind" title="socket.socket.bind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bind()</span></code></a>, <a class="reference internal" href="#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a>, <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> (possibly
repeating the <a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a> to service more than one client), while a
client only needs the sequence <a class="reference internal" href="#socket.socket" title="socket.socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">socket()</span></code></a>, <a class="reference internal" href="#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a>.  Also
note that the server does not <a class="reference internal" href="#socket.socket.sendall" title="socket.socket.sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendall()</span></code></a>/<a class="reference internal" href="#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> on
the socket it is listening on but on the new socket returned by
<a class="reference internal" href="#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a>.</p>
<p>The first two examples support IPv4 only.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo server program</span>
<span class="kn">import</span> <span class="nn">socket</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>                 <span class="c1"># Symbolic name meaning all available interfaces</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># Arbitrary non-privileged port</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
<span class="n">s</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">conn</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;Connected by&#39;</span><span class="p">,</span> <span class="n">addr</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">data</span><span class="p">:</span> <span class="k">break</span>
    <span class="n">conn</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo client program</span>
<span class="kn">import</span> <span class="nn">socket</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;daring.cwi.nl&#39;</span>    <span class="c1"># The remote host</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># The same port as used by the server</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="s1">&#39;Hello, world&#39;</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;Received&#39;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<p>The next two examples are identical to the above two, but support both IPv4 and
IPv6. The server side will listen to the first address family available (it
should listen to both instead). On most of IPv6-ready systems, IPv6 will take
precedence and the server may not accept IPv4 traffic. The client side will try
to connect to the all addresses returned as a result of the name resolution, and
sends traffic to the first one connected successfully.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo server program</span>
<span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="kc">None</span>               <span class="c1"># Symbolic name meaning all available interfaces</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># Arbitrary non-privileged port</span>
<span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">res</span> <span class="ow">in</span> <span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AF_UNSPEC</span><span class="p">,</span>
                              <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AI_PASSIVE</span><span class="p">):</span>
    <span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">,</span> <span class="n">canonname</span><span class="p">,</span> <span class="n">sa</span> <span class="o">=</span> <span class="n">res</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">socket</span><span class="o">.</span><span class="n">error</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">(</span><span class="n">sa</span><span class="p">)</span>
        <span class="n">s</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">socket</span><span class="o">.</span><span class="n">error</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">break</span>
<span class="k">if</span> <span class="n">s</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;could not open socket&#39;</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">conn</span><span class="p">,</span> <span class="n">addr</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;Connected by&#39;</span><span class="p">,</span> <span class="n">addr</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">data</span><span class="p">:</span> <span class="k">break</span>
    <span class="n">conn</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Echo client program</span>
<span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s1">&#39;daring.cwi.nl&#39;</span>    <span class="c1"># The remote host</span>
<span class="n">PORT</span> <span class="o">=</span> <span class="mi">50007</span>              <span class="c1"># The same port as used by the server</span>
<span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
<span class="k">for</span> <span class="n">res</span> <span class="ow">in</span> <span class="n">socket</span><span class="o">.</span><span class="n">getaddrinfo</span><span class="p">(</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">AF_UNSPEC</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">):</span>
    <span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">,</span> <span class="n">canonname</span><span class="p">,</span> <span class="n">sa</span> <span class="o">=</span> <span class="n">res</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">af</span><span class="p">,</span> <span class="n">socktype</span><span class="p">,</span> <span class="n">proto</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">socket</span><span class="o">.</span><span class="n">error</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="n">sa</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">socket</span><span class="o">.</span><span class="n">error</span> <span class="k">as</span> <span class="n">msg</span><span class="p">:</span>
        <span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="n">s</span> <span class="o">=</span> <span class="kc">None</span>
        <span class="k">continue</span>
    <span class="k">break</span>
<span class="k">if</span> <span class="n">s</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;could not open socket&#39;</span>
    <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="s1">&#39;Hello, world&#39;</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;Received&#39;</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<p>The last example shows how to write a very simple network sniffer with raw
sockets on Windows. The example requires administrator privileges to modify
the interface:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>

<span class="c1"># the public network interface</span>
<span class="n">HOST</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">gethostbyname</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">gethostname</span><span class="p">())</span>

<span class="c1"># create a raw socket and bind it to the public interface</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_RAW</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_IP</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>

<span class="c1"># Include IP headers</span>
<span class="n">s</span><span class="o">.</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">IPPROTO_IP</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">IP_HDRINCL</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>

<span class="c1"># receive all packages</span>
<span class="n">s</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SIO_RCVALL</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">RCVALL_ON</span><span class="p">)</span>

<span class="c1"># receive a package</span>
<span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">recvfrom</span><span class="p">(</span><span class="mi">65565</span><span class="p">)</span>

<span class="c1"># disabled promiscuous mode</span>
<span class="n">s</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SIO_RCVALL</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">RCVALL_OFF</span><span class="p">)</span>
</pre></div>
</div>
<p>Running an example several times with too small delay between executions, could
lead to this error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">socket</span><span class="o">.</span><span class="n">error</span><span class="p">:</span> <span class="p">[</span><span class="n">Errno</span> <span class="mi">98</span><span class="p">]</span> <span class="n">Address</span> <span class="n">already</span> <span class="ow">in</span> <span class="n">use</span>
</pre></div>
</div>
<p>This is because the previous execution has left the socket in a <code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code>
state, and can’t be immediately reused.</p>
<p>There is a <a class="reference internal" href="#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> flag to set, in order to prevent this,
<code class="xref py py-data docutils literal notranslate"><span class="pre">socket.SO_REUSEADDR</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">setsockopt</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SOL_SOCKET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SO_REUSEADDR</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">s</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
</pre></div>
</div>
<p>the <code class="xref py py-data docutils literal notranslate"><span class="pre">SO_REUSEADDR</span></code> flag tells the kernel to reuse a local socket in
<code class="docutils literal notranslate"><span class="pre">TIME_WAIT</span></code> state, without waiting for its natural timeout to expire.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a><ul>
<li><a class="reference internal" href="#socket-objects">17.2.1. Socket Objects</a></li>
<li><a class="reference internal" href="#example">17.2.2. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="subprocess.html"
                        title="previous chapter">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ssl.html"
                        title="next chapter">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/socket.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ssl.html" title="17.3. ssl — TLS/SSL wrapper for socket objects"
             >next</a> |</li>
        <li class="right" >
          <a href="subprocess.html" title="17.1. subprocess — Subprocess management"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\!���*�*html/library/socketserver.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.17. SocketServer — A framework for network servers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.18. BaseHTTPServer — Basic HTTP server" href="basehttpserver.html" />
    <link rel="prev" title="20.16. urlparse — Parse URLs into components" href="urlparse.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/socketserver.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="basehttpserver.html" title="20.18. BaseHTTPServer — Basic HTTP server"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="urlparse.html" title="20.16. urlparse — Parse URLs into components"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-SocketServer">
<span id="socketserver-a-framework-for-network-servers"></span><h1>20.17. <a class="reference internal" href="#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> — A framework for network servers<a class="headerlink" href="#module-SocketServer" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">socketserver</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/SocketServer.py">Lib/SocketServer.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> module simplifies the task of writing network servers.</p>
<p>There are four basic concrete server classes:</p>
<dl class="class">
<dt id="SocketServer.TCPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">TCPServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em>, <em>bind_and_activate=True</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.TCPServer" title="Permalink to this definition">¶</a></dt>
<dd><p>This uses the Internet TCP protocol, which provides for
continuous streams of data between the client and server.
If <em>bind_and_activate</em> is true, the constructor automatically attempts to
invoke <a class="reference internal" href="#SocketServer.BaseServer.server_bind" title="SocketServer.BaseServer.server_bind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">server_bind()</span></code></a> and
<a class="reference internal" href="#SocketServer.BaseServer.server_activate" title="SocketServer.BaseServer.server_activate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">server_activate()</span></code></a>.  The other parameters are passed to
the <a class="reference internal" href="#SocketServer.BaseServer" title="SocketServer.BaseServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseServer</span></code></a> base class.</p>
</dd></dl>

<dl class="class">
<dt id="SocketServer.UDPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">UDPServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em>, <em>bind_and_activate=True</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.UDPServer" title="Permalink to this definition">¶</a></dt>
<dd><p>This uses datagrams, which are discrete packets of information that may
arrive out of order or be lost while in transit.  The parameters are
the same as for <a class="reference internal" href="#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">TCPServer</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="SocketServer.UnixStreamServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">UnixStreamServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em>, <em>bind_and_activate=True</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.UnixStreamServer" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.UnixDatagramServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">UnixDatagramServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em>, <em>bind_and_activate=True</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.UnixDatagramServer" title="Permalink to this definition">¶</a></dt>
<dd><p>These more infrequently used classes are similar to the TCP and
UDP classes, but use Unix domain sockets; they’re not available on
non-Unix platforms.  The parameters are the same as for
<a class="reference internal" href="#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">TCPServer</span></code></a>.</p>
</dd></dl>

<p>These four classes process requests <em class="dfn">synchronously</em>; each request must be
completed before the next request can be started.  This isn’t suitable if each
request takes a long time to complete, because it requires a lot of computation,
or because it returns a lot of data which the client is slow to process.  The
solution is to create a separate process or thread to handle each request; the
<a class="reference internal" href="#SocketServer.ForkingMixIn" title="SocketServer.ForkingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForkingMixIn</span></code></a> and <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> mix-in classes can be used to
support asynchronous behaviour.</p>
<p>Creating a server requires several steps.  First, you must create a request
handler class by subclassing the <a class="reference internal" href="#SocketServer.BaseRequestHandler" title="SocketServer.BaseRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRequestHandler</span></code></a> class and
overriding its <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method;
this method will process incoming
requests.  Second, you must instantiate one of the server classes, passing it
the server’s address and the request handler class.  Then call the
<a class="reference internal" href="#SocketServer.BaseServer.handle_request" title="SocketServer.BaseServer.handle_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code></a> or
<a class="reference internal" href="#SocketServer.BaseServer.serve_forever" title="SocketServer.BaseServer.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code></a> method of the server object to
process one or many requests.  Finally, call <a class="reference internal" href="#SocketServer.BaseServer.server_close" title="SocketServer.BaseServer.server_close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">server_close()</span></code></a>
to close the socket.</p>
<p>When inheriting from <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> for threaded connection behavior,
you should explicitly declare how you want your threads to behave on an abrupt
shutdown. The <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> class defines an attribute
<em>daemon_threads</em>, which indicates whether or not the server should wait for
thread termination. You should set the flag explicitly if you would like threads
to behave autonomously; the default is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, meaning that Python will
not exit until all threads created by <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> have exited.</p>
<p>Server classes have the same external methods and attributes, no matter what
network protocol they use.</p>
<div class="section" id="server-creation-notes">
<h2>20.17.1. Server Creation Notes<a class="headerlink" href="#server-creation-notes" title="Permalink to this headline">¶</a></h2>
<p>There are five classes in an inheritance diagram, four of which represent
synchronous servers of four types:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">+------------+</span>
<span class="o">|</span> <span class="n">BaseServer</span> <span class="o">|</span>
<span class="o">+------------+</span>
      <span class="o">|</span>
      <span class="n">v</span>
<span class="o">+-----------+</span>        <span class="o">+------------------+</span>
<span class="o">|</span> <span class="n">TCPServer</span> <span class="o">|-------&gt;|</span> <span class="n">UnixStreamServer</span> <span class="o">|</span>
<span class="o">+-----------+</span>        <span class="o">+------------------+</span>
      <span class="o">|</span>
      <span class="n">v</span>
<span class="o">+-----------+</span>        <span class="o">+--------------------+</span>
<span class="o">|</span> <span class="n">UDPServer</span> <span class="o">|-------&gt;|</span> <span class="n">UnixDatagramServer</span> <span class="o">|</span>
<span class="o">+-----------+</span>        <span class="o">+--------------------+</span>
</pre></div>
</div>
<p>Note that <a class="reference internal" href="#SocketServer.UnixDatagramServer" title="SocketServer.UnixDatagramServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixDatagramServer</span></code></a> derives from <a class="reference internal" href="#SocketServer.UDPServer" title="SocketServer.UDPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">UDPServer</span></code></a>, not from
<a class="reference internal" href="#SocketServer.UnixStreamServer" title="SocketServer.UnixStreamServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnixStreamServer</span></code></a> — the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both Unix
server classes.</p>
<dl class="class">
<dt id="SocketServer.ForkingMixIn">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ForkingMixIn</code><a class="headerlink" href="#SocketServer.ForkingMixIn" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.ThreadingMixIn">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ThreadingMixIn</code><a class="headerlink" href="#SocketServer.ThreadingMixIn" title="Permalink to this definition">¶</a></dt>
<dd><p>Forking and threading versions of each type of server can be created
using these mix-in classes.  For instance, <a class="reference internal" href="#SocketServer.ThreadingUDPServer" title="SocketServer.ThreadingUDPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingUDPServer</span></code></a>
is created as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ThreadingUDPServer</span><span class="p">(</span><span class="n">ThreadingMixIn</span><span class="p">,</span> <span class="n">UDPServer</span><span class="p">):</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>The mix-in class comes first, since it overrides a method defined in
<a class="reference internal" href="#SocketServer.UDPServer" title="SocketServer.UDPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">UDPServer</span></code></a>.  Setting the various attributes also changes the
behavior of the underlying server mechanism.</p>
<p><a class="reference internal" href="#SocketServer.ForkingMixIn" title="SocketServer.ForkingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForkingMixIn</span></code></a> and the Forking classes mentioned below are
only available on POSIX platforms that support <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="SocketServer.ForkingTCPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ForkingTCPServer</code><a class="headerlink" href="#SocketServer.ForkingTCPServer" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.ForkingUDPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ForkingUDPServer</code><a class="headerlink" href="#SocketServer.ForkingUDPServer" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.ThreadingTCPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ThreadingTCPServer</code><a class="headerlink" href="#SocketServer.ThreadingTCPServer" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.ThreadingUDPServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">ThreadingUDPServer</code><a class="headerlink" href="#SocketServer.ThreadingUDPServer" title="Permalink to this definition">¶</a></dt>
<dd><p>These classes are pre-defined using the mix-in classes.</p>
</dd></dl>

<p>To implement a service, you must derive a class from <a class="reference internal" href="#SocketServer.BaseRequestHandler" title="SocketServer.BaseRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRequestHandler</span></code></a>
and redefine its <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method.
You can then run various versions of
the service by combining one of the server classes with your request handler
class.  The request handler class must be different for datagram or stream
services.  This can be hidden by using the handler subclasses
<a class="reference internal" href="#SocketServer.StreamRequestHandler" title="SocketServer.StreamRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamRequestHandler</span></code></a> or <a class="reference internal" href="#SocketServer.DatagramRequestHandler" title="SocketServer.DatagramRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DatagramRequestHandler</span></code></a>.</p>
<p>Of course, you still have to use your head!  For instance, it makes no sense to
use a forking server if the service contains state in memory that can be
modified by different requests, since the modifications in the child process
would never reach the initial state kept in the parent process and passed to
each child.  In this case, you can use a threading server, but you will probably
have to use locks to protect the integrity of the shared data.</p>
<p>On the other hand, if you are building an HTTP server where all data is stored
externally (for instance, in the file system), a synchronous class will
essentially render the service “deaf” while one request is being handled –
which may be for a very long time if a client is slow to receive all the data it
has requested.  Here a threading or forking server is appropriate.</p>
<p>In some cases, it may be appropriate to process part of a request synchronously,
but to finish processing in a forked child depending on the request data.  This
can be implemented by using a synchronous server and doing an explicit fork in
the request handler class <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method.</p>
<p>Another approach to handling multiple simultaneous requests in an environment
that supports neither threads nor <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a> (or where these are too
expensive or inappropriate for the service) is to maintain an explicit table of
partially finished requests and to use <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> to decide which
request to work on next (or whether to handle a new incoming request).  This is
particularly important for stream services where each client can potentially be
connected for a long time (if threads or subprocesses cannot be used). See
<a class="reference internal" href="asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> for another way to manage this.</p>
</div>
<div class="section" id="server-objects">
<h2>20.17.2. Server Objects<a class="headerlink" href="#server-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="SocketServer.BaseServer">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">BaseServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the superclass of all Server objects in the module.  It defines the
interface, given below, but does not implement most of the methods, which is
done in subclasses.  The two parameters are stored in the respective
<a class="reference internal" href="#SocketServer.BaseServer.server_address" title="SocketServer.BaseServer.server_address"><code class="xref py py-attr docutils literal notranslate"><span class="pre">server_address</span></code></a> and <a class="reference internal" href="#SocketServer.BaseServer.RequestHandlerClass" title="SocketServer.BaseServer.RequestHandlerClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">RequestHandlerClass</span></code></a> attributes.</p>
<dl class="method">
<dt id="SocketServer.BaseServer.fileno">
<code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an integer file descriptor for the socket on which the server is
listening.  This function is most commonly passed to <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select.select()</span></code></a>, to
allow monitoring multiple servers in the same process.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.handle_request">
<code class="descname">handle_request</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.handle_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Process a single request.  This function calls the following methods in
order: <a class="reference internal" href="#SocketServer.BaseServer.get_request" title="SocketServer.BaseServer.get_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_request()</span></code></a>, <a class="reference internal" href="#SocketServer.BaseServer.verify_request" title="SocketServer.BaseServer.verify_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">verify_request()</span></code></a>, and
<a class="reference internal" href="#SocketServer.BaseServer.process_request" title="SocketServer.BaseServer.process_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">process_request()</span></code></a>.  If the user-provided
<a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method of the
handler class raises an exception, the server’s <a class="reference internal" href="#SocketServer.BaseServer.handle_error" title="SocketServer.BaseServer.handle_error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_error()</span></code></a> method
will be called.  If no request is received within <a class="reference internal" href="#SocketServer.BaseServer.timeout" title="SocketServer.BaseServer.timeout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code></a>
seconds, <a class="reference internal" href="#SocketServer.BaseServer.handle_timeout" title="SocketServer.BaseServer.handle_timeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code></a> will be called and <a class="reference internal" href="#SocketServer.BaseServer.handle_request" title="SocketServer.BaseServer.handle_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code></a>
will return.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.serve_forever">
<code class="descname">serve_forever</code><span class="sig-paren">(</span><em>poll_interval=0.5</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.serve_forever" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle requests until an explicit <a class="reference internal" href="#SocketServer.BaseServer.shutdown" title="SocketServer.BaseServer.shutdown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shutdown()</span></code></a> request.  Poll for
shutdown every <em>poll_interval</em> seconds.
Ignores the <a class="reference internal" href="#SocketServer.BaseServer.timeout" title="SocketServer.BaseServer.timeout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code></a> attribute.
If you need to do periodic tasks, do them in another thread.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.shutdown">
<code class="descname">shutdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.shutdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Tell the <a class="reference internal" href="#SocketServer.BaseServer.serve_forever" title="SocketServer.BaseServer.serve_forever"><code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code></a> loop to stop and wait until it does.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.server_close">
<code class="descname">server_close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.server_close" title="Permalink to this definition">¶</a></dt>
<dd><p>Clean up the server. May be overridden.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.address_family">
<code class="descname">address_family</code><a class="headerlink" href="#SocketServer.BaseServer.address_family" title="Permalink to this definition">¶</a></dt>
<dd><p>The family of protocols to which the server’s socket belongs.
Common examples are <a class="reference internal" href="socket.html#socket.AF_INET" title="socket.AF_INET"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.AF_INET</span></code></a> and <a class="reference internal" href="socket.html#socket.AF_UNIX" title="socket.AF_UNIX"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.AF_UNIX</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.RequestHandlerClass">
<code class="descname">RequestHandlerClass</code><a class="headerlink" href="#SocketServer.BaseServer.RequestHandlerClass" title="Permalink to this definition">¶</a></dt>
<dd><p>The user-provided request handler class; an instance of this class is created
for each request.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.server_address">
<code class="descname">server_address</code><a class="headerlink" href="#SocketServer.BaseServer.server_address" title="Permalink to this definition">¶</a></dt>
<dd><p>The address on which the server is listening.  The format of addresses varies
depending on the protocol family;
see the documentation for the <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module
for details.  For Internet protocols, this is a tuple containing a string giving
the address, and an integer port number: <code class="docutils literal notranslate"><span class="pre">('127.0.0.1',</span> <span class="pre">80)</span></code>, for example.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.socket">
<code class="descname">socket</code><a class="headerlink" href="#SocketServer.BaseServer.socket" title="Permalink to this definition">¶</a></dt>
<dd><p>The socket object on which the server will listen for incoming requests.</p>
</dd></dl>

<p>The server classes support the following class variables:</p>
<dl class="attribute">
<dt id="SocketServer.BaseServer.allow_reuse_address">
<code class="descname">allow_reuse_address</code><a class="headerlink" href="#SocketServer.BaseServer.allow_reuse_address" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the server will allow the reuse of an address. This defaults to
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, and can be set in subclasses to change the policy.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.request_queue_size">
<code class="descname">request_queue_size</code><a class="headerlink" href="#SocketServer.BaseServer.request_queue_size" title="Permalink to this definition">¶</a></dt>
<dd><p>The size of the request queue.  If it takes a long time to process a single
request, any requests that arrive while the server is busy are placed into a
queue, up to <a class="reference internal" href="#SocketServer.BaseServer.request_queue_size" title="SocketServer.BaseServer.request_queue_size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">request_queue_size</span></code></a> requests.  Once the queue is full,
further requests from clients will get a “Connection denied” error.  The default
value is usually 5, but this can be overridden by subclasses.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.socket_type">
<code class="descname">socket_type</code><a class="headerlink" href="#SocketServer.BaseServer.socket_type" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of socket used by the server; <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code></a> and
<a class="reference internal" href="socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_DGRAM</span></code></a> are two common values.</p>
</dd></dl>

<dl class="attribute">
<dt id="SocketServer.BaseServer.timeout">
<code class="descname">timeout</code><a class="headerlink" href="#SocketServer.BaseServer.timeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Timeout duration, measured in seconds, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if no timeout is
desired.  If <a class="reference internal" href="#SocketServer.BaseServer.handle_request" title="SocketServer.BaseServer.handle_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code></a> receives no incoming requests within the
timeout period, the <a class="reference internal" href="#SocketServer.BaseServer.handle_timeout" title="SocketServer.BaseServer.handle_timeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code></a> method is called.</p>
</dd></dl>

<p>There are various server methods that can be overridden by subclasses of base
server classes like <a class="reference internal" href="#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">TCPServer</span></code></a>; these methods aren’t useful to external
users of the server object.</p>
<dl class="method">
<dt id="SocketServer.BaseServer.finish_request">
<code class="descname">finish_request</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.finish_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Actually processes the request by instantiating <a class="reference internal" href="#SocketServer.BaseServer.RequestHandlerClass" title="SocketServer.BaseServer.RequestHandlerClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">RequestHandlerClass</span></code></a> and
calling its <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.get_request">
<code class="descname">get_request</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.get_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Must accept a request from the socket, and return a 2-tuple containing the <em>new</em>
socket object to be used to communicate with the client, and the client’s
address.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.handle_error">
<code class="descname">handle_error</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.handle_error" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is called if the <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a>
method of a <a class="reference internal" href="#SocketServer.BaseServer.RequestHandlerClass" title="SocketServer.BaseServer.RequestHandlerClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">RequestHandlerClass</span></code></a> instance raises
an exception.  The default action is to print the traceback to
standard output and continue handling further requests.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.handle_timeout">
<code class="descname">handle_timeout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.handle_timeout" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is called when the <a class="reference internal" href="#SocketServer.BaseServer.timeout" title="SocketServer.BaseServer.timeout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code></a> attribute has been set to a
value other than <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> and the timeout period has passed with no
requests being received.  The default action for forking servers is
to collect the status of any child processes that have exited, while
in threading servers this method does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.process_request">
<code class="descname">process_request</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.process_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Calls <a class="reference internal" href="#SocketServer.BaseServer.finish_request" title="SocketServer.BaseServer.finish_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finish_request()</span></code></a> to create an instance of the
<a class="reference internal" href="#SocketServer.BaseServer.RequestHandlerClass" title="SocketServer.BaseServer.RequestHandlerClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">RequestHandlerClass</span></code></a>.  If desired, this function can create a new process
or thread to handle the request; the <a class="reference internal" href="#SocketServer.ForkingMixIn" title="SocketServer.ForkingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForkingMixIn</span></code></a> and
<a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> classes do this.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.server_activate">
<code class="descname">server_activate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.server_activate" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the server’s constructor to activate the server.  The default behavior
for a TCP server just invokes <a class="reference internal" href="socket.html#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a>
on the server’s socket. May be overridden.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.server_bind">
<code class="descname">server_bind</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.server_bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the server’s constructor to bind the socket to the desired address.
May be overridden.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseServer.verify_request">
<code class="descname">verify_request</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseServer.verify_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Must return a Boolean value; if the value is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, the request will be
processed, and if it’s <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, the request will be denied. This function
can be overridden to implement access controls for a server. The default
implementation always returns <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="request-handler-objects">
<h2>20.17.3. Request Handler Objects<a class="headerlink" href="#request-handler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="SocketServer.BaseRequestHandler">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">BaseRequestHandler</code><a class="headerlink" href="#SocketServer.BaseRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the superclass of all request handler objects.  It defines
the interface, given below.  A concrete request handler subclass must
define a new <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method, and can override any of
the other methods.  A new instance of the subclass is created for each
request.</p>
<dl class="method">
<dt id="SocketServer.BaseRequestHandler.setup">
<code class="descname">setup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseRequestHandler.setup" title="Permalink to this definition">¶</a></dt>
<dd><p>Called before the <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method to perform any initialization actions
required.  The default implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseRequestHandler.handle">
<code class="descname">handle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseRequestHandler.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>This function must do all the work required to service a request.  The
default implementation does nothing.  Several instance attributes are
available to it; the request is available as <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.request</span></code>; the client
address as <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.client_address</span></code>; and the server instance as
<code class="xref py py-attr docutils literal notranslate"><span class="pre">self.server</span></code>, in case it needs access to per-server information.</p>
<p>The type of <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.request</span></code> is different for datagram or stream
services.  For stream services, <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.request</span></code> is a socket object; for
datagram services, <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.request</span></code> is a pair of string and socket.</p>
</dd></dl>

<dl class="method">
<dt id="SocketServer.BaseRequestHandler.finish">
<code class="descname">finish</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#SocketServer.BaseRequestHandler.finish" title="Permalink to this definition">¶</a></dt>
<dd><p>Called after the <a class="reference internal" href="#SocketServer.BaseRequestHandler.handle" title="SocketServer.BaseRequestHandler.handle"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle()</span></code></a> method to perform any clean-up actions
required.  The default implementation does nothing.  If <a class="reference internal" href="#SocketServer.BaseRequestHandler.setup" title="SocketServer.BaseRequestHandler.setup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setup()</span></code></a>
raises an exception, this function will not be called.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="SocketServer.StreamRequestHandler">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">StreamRequestHandler</code><a class="headerlink" href="#SocketServer.StreamRequestHandler" title="Permalink to this definition">¶</a></dt>
<dt id="SocketServer.DatagramRequestHandler">
<em class="property">class </em><code class="descclassname">SocketServer.</code><code class="descname">DatagramRequestHandler</code><a class="headerlink" href="#SocketServer.DatagramRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>These <a class="reference internal" href="#SocketServer.BaseRequestHandler" title="SocketServer.BaseRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRequestHandler</span></code></a> subclasses override the
<a class="reference internal" href="#SocketServer.BaseRequestHandler.setup" title="SocketServer.BaseRequestHandler.setup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setup()</span></code></a> and <a class="reference internal" href="#SocketServer.BaseRequestHandler.finish" title="SocketServer.BaseRequestHandler.finish"><code class="xref py py-meth docutils literal notranslate"><span class="pre">finish()</span></code></a>
methods, and provide <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.rfile</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.wfile</span></code> attributes.
The <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.rfile</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.wfile</span></code> attributes can be
read or written, respectively, to get the request data or return data
to the client.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<h2>20.17.4. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<div class="section" id="socketserver-tcpserver-example">
<h3>20.17.4.1. <a class="reference internal" href="#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code></a> Example<a class="headerlink" href="#socketserver-tcpserver-example" title="Permalink to this headline">¶</a></h3>
<p>This is the server side:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">SocketServer</span>

<span class="k">class</span> <span class="nc">MyTCPHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">BaseRequestHandler</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    The request handler class for our server.</span>

<span class="sd">    It is instantiated once per connection to the server, and must</span>
<span class="sd">    override the handle() method to implement communication to the</span>
<span class="sd">    client.</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># self.request is the TCP socket connected to the client</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
        <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> wrote:&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">client_address</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
        <span class="nb">print</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span>
        <span class="c1"># just send back the same data, but upper-cased</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">9999</span>

    <span class="c1"># Create the server, binding to localhost on port 9999</span>
    <span class="n">server</span> <span class="o">=</span> <span class="n">SocketServer</span><span class="o">.</span><span class="n">TCPServer</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">),</span> <span class="n">MyTCPHandler</span><span class="p">)</span>

    <span class="c1"># Activate the server; this will keep running until you</span>
    <span class="c1"># interrupt the program with Ctrl-C</span>
    <span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>An alternative request handler class that makes use of streams (file-like
objects that simplify communication by providing the standard file interface):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyTCPHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">StreamRequestHandler</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># self.rfile is a file-like object created by the handler;</span>
        <span class="c1"># we can now use e.g. readline() instead of raw recv() calls</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">rfile</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
        <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> wrote:&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">client_address</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
        <span class="nb">print</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span>
        <span class="c1"># Likewise, self.wfile is a file-like object used to write back</span>
        <span class="c1"># to the client</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">wfile</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">upper</span><span class="p">())</span>
</pre></div>
</div>
<p>The difference is that the <code class="docutils literal notranslate"><span class="pre">readline()</span></code> call in the second handler will call
<code class="docutils literal notranslate"><span class="pre">recv()</span></code> multiple times until it encounters a newline character, while the
single <code class="docutils literal notranslate"><span class="pre">recv()</span></code> call in the first handler will just return what has been sent
from the client in one <code class="docutils literal notranslate"><span class="pre">sendall()</span></code> call.</p>
<p>This is the client side:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">9999</span>
<span class="n">data</span> <span class="o">=</span> <span class="s2">&quot; &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>

<span class="c1"># Create a socket (SOCK_STREAM means a TCP socket)</span>
<span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>

<span class="k">try</span><span class="p">:</span>
    <span class="c1"># Connect to server and send data</span>
    <span class="n">sock</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
    <span class="n">sock</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="n">data</span> <span class="o">+</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>

    <span class="c1"># Receive data from the server and shut down</span>
    <span class="n">received</span> <span class="o">=</span> <span class="n">sock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">sock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="nb">print</span> <span class="s2">&quot;Sent:     </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Received: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">received</span><span class="p">)</span>
</pre></div>
</div>
<p>The output of the example should look something like this:</p>
<p>Server:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python TCPServer.py
<span class="go">127.0.0.1 wrote:</span>
<span class="go">hello world with TCP</span>
<span class="go">127.0.0.1 wrote:</span>
<span class="go">python is nice</span>
</pre></div>
</div>
<p>Client:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python TCPClient.py hello world with TCP
<span class="go">Sent:     hello world with TCP</span>
<span class="go">Received: HELLO WORLD WITH TCP</span>
<span class="gp">$</span> python TCPClient.py python is nice
<span class="go">Sent:     python is nice</span>
<span class="go">Received: PYTHON IS NICE</span>
</pre></div>
</div>
</div>
<div class="section" id="socketserver-udpserver-example">
<h3>20.17.4.2. <a class="reference internal" href="#SocketServer.UDPServer" title="SocketServer.UDPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SocketServer.UDPServer</span></code></a> Example<a class="headerlink" href="#socketserver-udpserver-example" title="Permalink to this headline">¶</a></h3>
<p>This is the server side:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">SocketServer</span>

<span class="k">class</span> <span class="nc">MyUDPHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">BaseRequestHandler</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;</span>
<span class="sd">    This class works similar to the TCP handler class, except that</span>
<span class="sd">    self.request consists of a pair of data and client socket, and since</span>
<span class="sd">    there is no connection the client address must be given explicitly</span>
<span class="sd">    when sending data back via sendto().</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
        <span class="n">socket</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
        <span class="nb">print</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2"> wrote:&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">client_address</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
        <span class="nb">print</span> <span class="n">data</span>
        <span class="n">socket</span><span class="o">.</span><span class="n">sendto</span><span class="p">(</span><span class="n">data</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="bp">self</span><span class="o">.</span><span class="n">client_address</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">9999</span>
    <span class="n">server</span> <span class="o">=</span> <span class="n">SocketServer</span><span class="o">.</span><span class="n">UDPServer</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">),</span> <span class="n">MyUDPHandler</span><span class="p">)</span>
    <span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>This is the client side:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">sys</span>

<span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">9999</span>
<span class="n">data</span> <span class="o">=</span> <span class="s2">&quot; &quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>

<span class="c1"># SOCK_DGRAM is the socket type to use for UDP sockets</span>
<span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_DGRAM</span><span class="p">)</span>

<span class="c1"># As you can see, there is no connect() call; UDP has no connections.</span>
<span class="c1"># Instead, data is directly sent to the recipient via sendto().</span>
<span class="n">sock</span><span class="o">.</span><span class="n">sendto</span><span class="p">(</span><span class="n">data</span> <span class="o">+</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">))</span>
<span class="n">received</span> <span class="o">=</span> <span class="n">sock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>

<span class="nb">print</span> <span class="s2">&quot;Sent:     </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Received: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">received</span><span class="p">)</span>
</pre></div>
</div>
<p>The output of the example should look exactly like for the TCP server example.</p>
</div>
<div class="section" id="asynchronous-mixins">
<h3>20.17.4.3. Asynchronous Mixins<a class="headerlink" href="#asynchronous-mixins" title="Permalink to this headline">¶</a></h3>
<p>To build asynchronous handlers, use the <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> and
<a class="reference internal" href="#SocketServer.ForkingMixIn" title="SocketServer.ForkingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForkingMixIn</span></code></a> classes.</p>
<p>An example for the <a class="reference internal" href="#SocketServer.ThreadingMixIn" title="SocketServer.ThreadingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadingMixIn</span></code></a> class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span>
<span class="kn">import</span> <span class="nn">threading</span>
<span class="kn">import</span> <span class="nn">SocketServer</span>

<span class="k">class</span> <span class="nc">ThreadedTCPRequestHandler</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">BaseRequestHandler</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">handle</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">data</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
        <span class="n">cur_thread</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">current_thread</span><span class="p">()</span>
        <span class="n">response</span> <span class="o">=</span> <span class="s2">&quot;</span><span class="si">{}</span><span class="s2">: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">cur_thread</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">request</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">ThreadedTCPServer</span><span class="p">(</span><span class="n">SocketServer</span><span class="o">.</span><span class="n">ThreadingMixIn</span><span class="p">,</span> <span class="n">SocketServer</span><span class="o">.</span><span class="n">TCPServer</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">def</span> <span class="nf">client</span><span class="p">(</span><span class="n">ip</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="n">message</span><span class="p">):</span>
    <span class="n">sock</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
    <span class="n">sock</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="n">ip</span><span class="p">,</span> <span class="n">port</span><span class="p">))</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">sock</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="n">message</span><span class="p">)</span>
        <span class="n">response</span> <span class="o">=</span> <span class="n">sock</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span>
        <span class="nb">print</span> <span class="s2">&quot;Received: </span><span class="si">{}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">response</span><span class="p">)</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">sock</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="c1"># Port 0 means to select an arbitrary unused port</span>
    <span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">0</span>

    <span class="n">server</span> <span class="o">=</span> <span class="n">ThreadedTCPServer</span><span class="p">((</span><span class="n">HOST</span><span class="p">,</span> <span class="n">PORT</span><span class="p">),</span> <span class="n">ThreadedTCPRequestHandler</span><span class="p">)</span>
    <span class="n">ip</span><span class="p">,</span> <span class="n">port</span> <span class="o">=</span> <span class="n">server</span><span class="o">.</span><span class="n">server_address</span>

    <span class="c1"># Start a thread with the server -- that thread will then start one</span>
    <span class="c1"># more thread for each request</span>
    <span class="n">server_thread</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">)</span>
    <span class="c1"># Exit the server thread when the main thread terminates</span>
    <span class="n">server_thread</span><span class="o">.</span><span class="n">daemon</span> <span class="o">=</span> <span class="kc">True</span>
    <span class="n">server_thread</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s2">&quot;Server loop running in thread:&quot;</span><span class="p">,</span> <span class="n">server_thread</span><span class="o">.</span><span class="n">name</span>

    <span class="n">client</span><span class="p">(</span><span class="n">ip</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="s2">&quot;Hello World 1&quot;</span><span class="p">)</span>
    <span class="n">client</span><span class="p">(</span><span class="n">ip</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="s2">&quot;Hello World 2&quot;</span><span class="p">)</span>
    <span class="n">client</span><span class="p">(</span><span class="n">ip</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="s2">&quot;Hello World 3&quot;</span><span class="p">)</span>

    <span class="n">server</span><span class="o">.</span><span class="n">shutdown</span><span class="p">()</span>
    <span class="n">server</span><span class="o">.</span><span class="n">server_close</span><span class="p">()</span>
</pre></div>
</div>
<p>The output of the example should look something like this:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python ThreadedTCPServer.py
<span class="go">Server loop running in thread: Thread-1</span>
<span class="go">Received: Thread-2: Hello World 1</span>
<span class="go">Received: Thread-3: Hello World 2</span>
<span class="go">Received: Thread-4: Hello World 3</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#SocketServer.ForkingMixIn" title="SocketServer.ForkingMixIn"><code class="xref py py-class docutils literal notranslate"><span class="pre">ForkingMixIn</span></code></a> class is used in the same way, except that the server
will spawn a new process for each request.
Available only on POSIX platforms that support <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a>.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a><ul>
<li><a class="reference internal" href="#server-creation-notes">20.17.1. Server Creation Notes</a></li>
<li><a class="reference internal" href="#server-objects">20.17.2. Server Objects</a></li>
<li><a class="reference internal" href="#request-handler-objects">20.17.3. Request Handler Objects</a></li>
<li><a class="reference internal" href="#examples">20.17.4. Examples</a><ul>
<li><a class="reference internal" href="#socketserver-tcpserver-example">20.17.4.1. <code class="docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code> Example</a></li>
<li><a class="reference internal" href="#socketserver-udpserver-example">20.17.4.2. <code class="docutils literal notranslate"><span class="pre">SocketServer.UDPServer</span></code> Example</a></li>
<li><a class="reference internal" href="#asynchronous-mixins">20.17.4.3. Asynchronous Mixins</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="urlparse.html"
                        title="previous chapter">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="basehttpserver.html"
                        title="next chapter">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/socketserver.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="basehttpserver.html" title="20.18. BaseHTTPServer — Basic HTTP server"
             >next</a> |</li>
        <li class="right" >
          <a href="urlparse.html" title="20.16. urlparse — Parse URLs into components"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��=uX@X@html/library/someos.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16. Optional Operating System Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.1. select — Waiting for I/O completion" href="select.html" />
    <link rel="prev" title="15.17. ctypes — A foreign function library for Python" href="ctypes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/someos.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="select.html" title="16.1. select — Waiting for I/O completion"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ctypes.html" title="15.17. ctypes — A foreign function library for Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="optional-operating-system-services">
<span id="someos"></span><h1>16. Optional Operating System Services<a class="headerlink" href="#optional-operating-system-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide interfaces to operating system
features that are available on selected operating systems only. The interfaces
are generally modeled after the Unix or C interfaces but they are available on
some other systems as well (e.g. Windows or NT).  Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="select.html">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a><ul>
<li class="toctree-l2"><a class="reference internal" href="select.html#edge-and-level-trigger-polling-epoll-objects">16.1.1. Edge and Level Trigger Polling (epoll) Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="select.html#polling-objects">16.1.2. Polling Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="select.html#kqueue-objects">16.1.3. Kqueue Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="select.html#kevent-objects">16.1.4. Kevent Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="threading.html">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a><ul>
<li class="toctree-l2"><a class="reference internal" href="threading.html#thread-objects">16.2.1. Thread Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#lock-objects">16.2.2. Lock Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#rlock-objects">16.2.3. RLock Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#condition-objects">16.2.4. Condition Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#semaphore-objects">16.2.5. Semaphore Objects</a><ul>
<li class="toctree-l3"><a class="reference internal" href="threading.html#semaphore-example">16.2.5.1. <code class="docutils literal notranslate"><span class="pre">Semaphore</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#event-objects">16.2.6. Event Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#timer-objects">16.2.7. Timer Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#using-locks-conditions-and-semaphores-in-the-with-statement">16.2.8. Using locks, conditions, and semaphores in the <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="threading.html#importing-in-threaded-code">16.2.9. Importing in threaded code</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="thread.html">16.3. <code class="docutils literal notranslate"><span class="pre">thread</span></code> — Multiple threads of control</a></li>
<li class="toctree-l1"><a class="reference internal" href="dummy_threading.html">16.4. <code class="docutils literal notranslate"><span class="pre">dummy_threading</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">threading</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="dummy_thread.html">16.5. <code class="docutils literal notranslate"><span class="pre">dummy_thread</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">thread</span></code> module</a></li>
<li class="toctree-l1"><a class="reference internal" href="multiprocessing.html">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a><ul>
<li class="toctree-l2"><a class="reference internal" href="multiprocessing.html#introduction">16.6.1. Introduction</a><ul>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#the-process-class">16.6.1.1. The <code class="docutils literal notranslate"><span class="pre">Process</span></code> class</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#exchanging-objects-between-processes">16.6.1.2. Exchanging objects between processes</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#synchronization-between-processes">16.6.1.3. Synchronization between processes</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#sharing-state-between-processes">16.6.1.4. Sharing state between processes</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#using-a-pool-of-workers">16.6.1.5. Using a pool of workers</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="multiprocessing.html#reference">16.6.2. Reference</a><ul>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#process-and-exceptions">16.6.2.1. <code class="docutils literal notranslate"><span class="pre">Process</span></code> and exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#pipes-and-queues">16.6.2.2. Pipes and Queues</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#miscellaneous">16.6.2.3. Miscellaneous</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#connection-objects">16.6.2.4. Connection Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#synchronization-primitives">16.6.2.5. Synchronization primitives</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#shared-ctypes-objects">16.6.2.6. Shared <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="multiprocessing.html#module-multiprocessing.sharedctypes">16.6.2.6.1. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#managers">16.6.2.7. Managers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="multiprocessing.html#customized-managers">16.6.2.7.1. Customized managers</a></li>
<li class="toctree-l4"><a class="reference internal" href="multiprocessing.html#using-a-remote-manager">16.6.2.7.2. Using a remote manager</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#proxy-objects">16.6.2.8. Proxy Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="multiprocessing.html#cleanup">16.6.2.8.1. Cleanup</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#module-multiprocessing.pool">16.6.2.9. Process Pools</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#module-multiprocessing.connection">16.6.2.10. Listeners and Clients</a><ul>
<li class="toctree-l4"><a class="reference internal" href="multiprocessing.html#address-formats">16.6.2.10.1. Address Formats</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#authentication-keys">16.6.2.11. Authentication keys</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#logging">16.6.2.12. Logging</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#module-multiprocessing.dummy">16.6.2.13. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.dummy</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="multiprocessing.html#programming-guidelines">16.6.3. Programming guidelines</a><ul>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#all-platforms">16.6.3.1. All platforms</a></li>
<li class="toctree-l3"><a class="reference internal" href="multiprocessing.html#windows">16.6.3.2. Windows</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="multiprocessing.html#examples">16.6.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mmap.html">16.7. <code class="docutils literal notranslate"><span class="pre">mmap</span></code> — Memory-mapped file support</a></li>
<li class="toctree-l1"><a class="reference internal" href="readline.html">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a><ul>
<li class="toctree-l2"><a class="reference internal" href="readline.html#init-file">16.8.1. Init file</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#line-buffer">16.8.2. Line buffer</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#history-file">16.8.3. History file</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#history-list">16.8.4. History list</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#startup-hooks">16.8.5. Startup hooks</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#completion">16.8.6. Completion</a></li>
<li class="toctree-l2"><a class="reference internal" href="readline.html#example">16.8.7. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="rlcompleter.html">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a><ul>
<li class="toctree-l2"><a class="reference internal" href="rlcompleter.html#completer-objects">16.9.1. Completer Objects</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="ctypes.html"
                        title="previous chapter">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="select.html"
                        title="next chapter">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/someos.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="select.html" title="16.1. select — Waiting for I/O completion"
             >next</a> |</li>
        <li class="right" >
          <a href="ctypes.html" title="15.17. ctypes — A foreign function library for Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�”�+�+html/library/spwd.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.3. spwd — The shadow password database &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.4. grp — The group database" href="grp.html" />
    <link rel="prev" title="36.2. pwd — The password database" href="pwd.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/spwd.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="grp.html" title="36.4. grp — The group database"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="pwd.html" title="36.2. pwd — The password database"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-spwd">
<span id="spwd-the-shadow-password-database"></span><h1>36.3. <a class="reference internal" href="#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a> — The shadow password database<a class="headerlink" href="#module-spwd" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>This module provides access to the Unix shadow password database. It is
available on various Unix versions.</p>
<p>You must have enough privileges to access the shadow password database (this
usually means you have to be root).</p>
<p>Shadow password database entries are reported as a tuple-like object, whose
attributes correspond to the members of the <code class="docutils literal notranslate"><span class="pre">spwd</span></code> structure (Attribute field
below, see <code class="docutils literal notranslate"><span class="pre">&lt;shadow.h&gt;</span></code>):</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="27%" />
<col width="60%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Attribute</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_nam</span></code></td>
<td>Login name</td>
</tr>
<tr class="row-odd"><td>1</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_pwd</span></code></td>
<td>Encrypted password</td>
</tr>
<tr class="row-even"><td>2</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_lstchg</span></code></td>
<td>Date of last change</td>
</tr>
<tr class="row-odd"><td>3</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_min</span></code></td>
<td>Minimal number of days between
changes</td>
</tr>
<tr class="row-even"><td>4</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_max</span></code></td>
<td>Maximum number of days between
changes</td>
</tr>
<tr class="row-odd"><td>5</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_warn</span></code></td>
<td>Number of days before password
expires to warn user about it</td>
</tr>
<tr class="row-even"><td>6</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_inact</span></code></td>
<td>Number of days after password
expires until account is
blocked</td>
</tr>
<tr class="row-odd"><td>7</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_expire</span></code></td>
<td>Number of days since 1970-01-01
until account is disabled</td>
</tr>
<tr class="row-even"><td>8</td>
<td><code class="docutils literal notranslate"><span class="pre">sp_flag</span></code></td>
<td>Reserved</td>
</tr>
</tbody>
</table>
<p>The sp_nam and sp_pwd items are strings, all others are integers.
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised if the entry asked for cannot be found.</p>
<p>It defines the following items:</p>
<dl class="function">
<dt id="spwd.getspnam">
<code class="descclassname">spwd.</code><code class="descname">getspnam</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#spwd.getspnam" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the shadow password database entry for the given user name.</p>
</dd></dl>

<dl class="function">
<dt id="spwd.getspall">
<code class="descclassname">spwd.</code><code class="descname">getspall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#spwd.getspall" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all available shadow password database entries, in arbitrary
order.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="grp.html#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">grp</span></code></a></dt>
<dd>An interface to the group database, similar to this.</dd>
<dt>Module <a class="reference internal" href="pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a></dt>
<dd>An interface to the normal password database, similar to this.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="pwd.html"
                        title="previous chapter">36.2. <code class="docutils literal notranslate"><span class="pre">pwd</span></code> — The password database</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="grp.html"
                        title="next chapter">36.4. <code class="docutils literal notranslate"><span class="pre">grp</span></code> — The group database</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/spwd.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="grp.html" title="36.4. grp — The group database"
             >next</a> |</li>
        <li class="right" >
          <a href="pwd.html" title="36.2. pwd — The password database"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�	>9�I�Ihtml/library/sqlite3.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.13. sqlite3 — DB-API 2.0 interface for SQLite databases &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12. Data Compression and Archiving" href="archiving.html" />
    <link rel="prev" title="11.12. dumbdbm — Portable DBM implementation" href="dumbdbm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sqlite3.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="archiving.html" title="12. Data Compression and Archiving"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dumbdbm.html" title="11.12. dumbdbm — Portable DBM implementation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sqlite3">
<span id="sqlite3-db-api-2-0-interface-for-sqlite-databases"></span><h1>11.13. <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> — DB-API 2.0 interface for SQLite databases<a class="headerlink" href="#module-sqlite3" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>SQLite is a C library that provides a lightweight disk-based database that
doesn’t require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage.  It’s also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.</p>
<p>The sqlite3 module was written by Gerhard Häring.  It provides a SQL interface
compliant with the DB-API 2.0 specification described by <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>.</p>
<p>To use the module, you must first create a <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> object that
represents the database.  Here the data will be stored in the
<code class="file docutils literal notranslate"><span class="pre">example.db</span></code> file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;example.db&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also supply the special name <code class="docutils literal notranslate"><span class="pre">:memory:</span></code> to create a database in RAM.</p>
<p>Once you have a <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a>, you can create a <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a>  object
and call its <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code></a> method to perform SQL commands:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="c1"># Create table</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;CREATE TABLE stocks</span>
<span class="s1">             (date text, trans text, symbol text, qty real, price real)&#39;&#39;&#39;</span><span class="p">)</span>

<span class="c1"># Insert a row of data</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;INSERT INTO stocks VALUES (&#39;2006-01-05&#39;,&#39;BUY&#39;,&#39;RHAT&#39;,100,35.14)&quot;</span><span class="p">)</span>

<span class="c1"># Save (commit) the changes</span>
<span class="n">conn</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="c1"># We can also close the connection if we are done with it.</span>
<span class="c1"># Just be sure any changes have been committed or they will be lost.</span>
<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The data you’ve saved is persistent and is available in subsequent sessions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;example.db&#39;</span><span class="p">)</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
</pre></div>
</div>
<p>Usually your SQL operations will need to use values from Python variables.  You
shouldn’t assemble your query using Python’s string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack
(see <a class="reference external" href="https://xkcd.com/327/">https://xkcd.com/327/</a> for humorous example of what can go wrong).</p>
<p>Instead, use the DB-API’s parameter substitution.  Put <code class="docutils literal notranslate"><span class="pre">?</span></code> as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor’s <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code></a> method.  (Other database
modules may use a different placeholder, such as <code class="docutils literal notranslate"><span class="pre">%s</span></code> or <code class="docutils literal notranslate"><span class="pre">:1</span></code>.) For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Never do this -- insecure!</span>
<span class="n">symbol</span> <span class="o">=</span> <span class="s1">&#39;RHAT&#39;</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;SELECT * FROM stocks WHERE symbol = &#39;</span><span class="si">%s</span><span class="s2">&#39;&quot;</span> <span class="o">%</span> <span class="n">symbol</span><span class="p">)</span>

<span class="c1"># Do this instead</span>
<span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;RHAT&#39;</span><span class="p">,)</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;SELECT * FROM stocks WHERE symbol=?&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">c</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>

<span class="c1"># Larger example that inserts many records at a time</span>
<span class="n">purchases</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;2006-03-28&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">45.00</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;2006-04-05&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;MSFT&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">72.00</span><span class="p">),</span>
             <span class="p">(</span><span class="s1">&#39;2006-04-06&#39;</span><span class="p">,</span> <span class="s1">&#39;SELL&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mf">53.00</span><span class="p">),</span>
            <span class="p">]</span>
<span class="n">c</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s1">&#39;INSERT INTO stocks VALUES (?,?,?,?,?)&#39;</span><span class="p">,</span> <span class="n">purchases</span><span class="p">)</span>
</pre></div>
</div>
<p>To retrieve data after executing a SELECT statement, you can either treat the
cursor as an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>, call the cursor’s <a class="reference internal" href="#sqlite3.Cursor.fetchone" title="sqlite3.Cursor.fetchone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchone()</span></code></a> method to
retrieve a single matching row, or call <a class="reference internal" href="#sqlite3.Cursor.fetchall" title="sqlite3.Cursor.fetchall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchall()</span></code></a> to get a list of the
matching rows.</p>
<p>This example uses the iterator form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;SELECT * FROM stocks ORDER BY price&#39;</span><span class="p">):</span>
<span class="go">        print row</span>

<span class="go">(u&#39;2006-01-05&#39;, u&#39;BUY&#39;, u&#39;RHAT&#39;, 100, 35.14)</span>
<span class="go">(u&#39;2006-03-28&#39;, u&#39;BUY&#39;, u&#39;IBM&#39;, 1000, 45.0)</span>
<span class="go">(u&#39;2006-04-06&#39;, u&#39;SELL&#39;, u&#39;IBM&#39;, 500, 53.0)</span>
<span class="go">(u&#39;2006-04-05&#39;, u&#39;BUY&#39;, u&#39;MSFT&#39;, 1000, 72.0)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://github.com/ghaering/pysqlite">https://github.com/ghaering/pysqlite</a></dt>
<dd>The pysqlite web page – sqlite3 is developed externally under the name
“pysqlite”.</dd>
<dt><a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a></dt>
<dd>The SQLite web page; the documentation describes the syntax and the
available data types for the supported SQL dialect.</dd>
<dt><a class="reference external" href="http://www.w3schools.com/sql/">http://www.w3schools.com/sql/</a></dt>
<dd>Tutorial, reference and examples for learning SQL syntax.</dd>
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> - Database API Specification 2.0</dt>
<dd>PEP written by Marc-André Lemburg.</dd>
</dl>
</div>
<div class="section" id="module-functions-and-constants">
<span id="sqlite3-module-contents"></span><h2>11.13.1. Module functions and constants<a class="headerlink" href="#module-functions-and-constants" title="Permalink to this headline">¶</a></h2>
<dl class="data">
<dt id="sqlite3.version">
<code class="descclassname">sqlite3.</code><code class="descname">version</code><a class="headerlink" href="#sqlite3.version" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number of this module, as a string. This is not the version of
the SQLite library.</p>
</dd></dl>

<dl class="data">
<dt id="sqlite3.version_info">
<code class="descclassname">sqlite3.</code><code class="descname">version_info</code><a class="headerlink" href="#sqlite3.version_info" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number of this module, as a tuple of integers. This is not the
version of the SQLite library.</p>
</dd></dl>

<dl class="data">
<dt id="sqlite3.sqlite_version">
<code class="descclassname">sqlite3.</code><code class="descname">sqlite_version</code><a class="headerlink" href="#sqlite3.sqlite_version" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number of the run-time SQLite library, as a string.</p>
</dd></dl>

<dl class="data">
<dt id="sqlite3.sqlite_version_info">
<code class="descclassname">sqlite3.</code><code class="descname">sqlite_version_info</code><a class="headerlink" href="#sqlite3.sqlite_version_info" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number of the run-time SQLite library, as a tuple of integers.</p>
</dd></dl>

<dl class="data">
<dt id="sqlite3.PARSE_DECLTYPES">
<code class="descclassname">sqlite3.</code><code class="descname">PARSE_DECLTYPES</code><a class="headerlink" href="#sqlite3.PARSE_DECLTYPES" title="Permalink to this definition">¶</a></dt>
<dd><p>This constant is meant to be used with the <em>detect_types</em> parameter of the
<a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code class="xref py py-func docutils literal notranslate"><span class="pre">connect()</span></code></a> function.</p>
<p>Setting it makes the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module parse the declared type for each
column it returns.  It will parse out the first word of the declared type,
i. e.  for “integer primary key”, it will parse out “integer”, or for
“number(10)” it will parse out “number”. Then for that column, it will look
into the converters dictionary and use the converter function registered for
that type there.</p>
</dd></dl>

<dl class="data">
<dt id="sqlite3.PARSE_COLNAMES">
<code class="descclassname">sqlite3.</code><code class="descname">PARSE_COLNAMES</code><a class="headerlink" href="#sqlite3.PARSE_COLNAMES" title="Permalink to this definition">¶</a></dt>
<dd><p>This constant is meant to be used with the <em>detect_types</em> parameter of the
<a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code class="xref py py-func docutils literal notranslate"><span class="pre">connect()</span></code></a> function.</p>
<p>Setting this makes the SQLite interface parse the column name for each column it
returns.  It will look for a string formed [mytype] in there, and then decide
that ‘mytype’ is the type of the column. It will try to find an entry of
‘mytype’ in the converters dictionary and then use the converter function found
there to return the value. The column name found in <a class="reference internal" href="#sqlite3.Cursor.description" title="sqlite3.Cursor.description"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Cursor.description</span></code></a>
is only the first word of the column name, i.  e. if you use something like
<code class="docutils literal notranslate"><span class="pre">'as</span> <span class="pre">&quot;x</span> <span class="pre">[datetime]&quot;'</span></code> in your SQL, then we will parse out everything until the
first blank for the column name: the column name would simply be “x”.</p>
</dd></dl>

<dl class="function">
<dt id="sqlite3.connect">
<code class="descclassname">sqlite3.</code><code class="descname">connect</code><span class="sig-paren">(</span><em>database</em><span class="optional">[</span>, <em>timeout</em>, <em>detect_types</em>, <em>isolation_level</em>, <em>check_same_thread</em>, <em>factory</em>, <em>cached_statements</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.connect" title="Permalink to this definition">¶</a></dt>
<dd><p>Opens a connection to the SQLite database file <em>database</em>. You can use
<code class="docutils literal notranslate"><span class="pre">&quot;:memory:&quot;</span></code> to open a database connection to a database that resides in RAM
instead of on disk.</p>
<p>When a database is accessed by multiple connections, and one of the processes
modifies the database, the SQLite database is locked until that transaction is
committed. The <em>timeout</em> parameter specifies how long the connection should wait
for the lock to go away until raising an exception. The default for the timeout
parameter is 5.0 (five seconds).</p>
<p>For the <em>isolation_level</em> parameter, please see the
<a class="reference internal" href="#sqlite3.Connection.isolation_level" title="sqlite3.Connection.isolation_level"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Connection.isolation_level</span></code></a> property of <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> objects.</p>
<p>SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. If
you want to use other types you must add support for them yourself. The
<em>detect_types</em> parameter and the using custom <strong>converters</strong> registered with the
module-level <a class="reference internal" href="#sqlite3.register_converter" title="sqlite3.register_converter"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_converter()</span></code></a> function allow you to easily do that.</p>
<p><em>detect_types</em> defaults to 0 (i. e. off, no type detection), you can set it to
any combination of <a class="reference internal" href="#sqlite3.PARSE_DECLTYPES" title="sqlite3.PARSE_DECLTYPES"><code class="xref py py-const docutils literal notranslate"><span class="pre">PARSE_DECLTYPES</span></code></a> and <a class="reference internal" href="#sqlite3.PARSE_COLNAMES" title="sqlite3.PARSE_COLNAMES"><code class="xref py py-const docutils literal notranslate"><span class="pre">PARSE_COLNAMES</span></code></a> to turn
type detection on.</p>
<p>By default, the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module uses its <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> class for the
connect call.  You can, however, subclass the <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> class and make
<a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code class="xref py py-func docutils literal notranslate"><span class="pre">connect()</span></code></a> use your class instead by providing your class for the <em>factory</em>
parameter.</p>
<p>Consult the section <a class="reference internal" href="#sqlite3-types"><span class="std std-ref">SQLite and Python types</span></a> of this manual for details.</p>
<p>The <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module internally uses a statement cache to avoid SQL parsing
overhead. If you want to explicitly set the number of statements that are cached
for the connection, you can set the <em>cached_statements</em> parameter. The currently
implemented default is to cache 100 statements.</p>
</dd></dl>

<dl class="function">
<dt id="sqlite3.register_converter">
<code class="descclassname">sqlite3.</code><code class="descname">register_converter</code><span class="sig-paren">(</span><em>typename</em>, <em>callable</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.register_converter" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers a callable to convert a bytestring from the database into a custom
Python type. The callable will be invoked for all database values that are of
the type <em>typename</em>. Confer the parameter <em>detect_types</em> of the <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code class="xref py py-func docutils literal notranslate"><span class="pre">connect()</span></code></a>
function for how the type detection works. Note that <em>typename</em> and the name of
the type in your query are matched in case-insensitive manner.</p>
</dd></dl>

<dl class="function">
<dt id="sqlite3.register_adapter">
<code class="descclassname">sqlite3.</code><code class="descname">register_adapter</code><span class="sig-paren">(</span><em>type</em>, <em>callable</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.register_adapter" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers a callable to convert the custom Python type <em>type</em> into one of
SQLite’s supported types. The callable <em>callable</em> accepts as single parameter
the Python value, and must return a value of the following types: int, long,
float, str (UTF-8 encoded), unicode or buffer.</p>
</dd></dl>

<dl class="function">
<dt id="sqlite3.complete_statement">
<code class="descclassname">sqlite3.</code><code class="descname">complete_statement</code><span class="sig-paren">(</span><em>sql</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.complete_statement" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the string <em>sql</em> contains one or more complete SQL
statements terminated by semicolons. It does not verify that the SQL is
syntactically correct, only that there are no unclosed string literals and the
statement is terminated by a semicolon.</p>
<p>This can be used to build a shell for SQLite, as in the following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># A minimal SQLite shell for experiments</span>

<span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">isolation_level</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">buffer</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>

<span class="nb">print</span> <span class="s2">&quot;Enter your SQL commands to execute in sqlite3.&quot;</span>
<span class="nb">print</span> <span class="s2">&quot;Enter a blank line to exit.&quot;</span>

<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">line</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">line</span> <span class="o">==</span> <span class="s2">&quot;&quot;</span><span class="p">:</span>
        <span class="k">break</span>
    <span class="n">buffer</span> <span class="o">+=</span> <span class="n">line</span>
    <span class="k">if</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">complete_statement</span><span class="p">(</span><span class="n">buffer</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">buffer</span> <span class="o">=</span> <span class="n">buffer</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
            <span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="n">buffer</span><span class="p">)</span>

            <span class="k">if</span> <span class="n">buffer</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s2">&quot;SELECT&quot;</span><span class="p">):</span>
                <span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
        <span class="k">except</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">Error</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
            <span class="nb">print</span> <span class="s2">&quot;An error occurred:&quot;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
        <span class="n">buffer</span> <span class="o">=</span> <span class="s2">&quot;&quot;</span>

<span class="n">con</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="sqlite3.enable_callback_tracebacks">
<code class="descclassname">sqlite3.</code><code class="descname">enable_callback_tracebacks</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.enable_callback_tracebacks" title="Permalink to this definition">¶</a></dt>
<dd><p>By default you will not get any tracebacks in user-defined functions,
aggregates, converters, authorizer callbacks etc. If you want to debug them,
you can call this function with <em>flag</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code>. Afterwards, you will
get tracebacks from callbacks on <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>. Use <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> to
disable the feature again.</p>
</dd></dl>

</div>
<div class="section" id="connection-objects">
<span id="sqlite3-connection-objects"></span><h2>11.13.2. Connection Objects<a class="headerlink" href="#connection-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="sqlite3.Connection">
<em class="property">class </em><code class="descclassname">sqlite3.</code><code class="descname">Connection</code><a class="headerlink" href="#sqlite3.Connection" title="Permalink to this definition">¶</a></dt>
<dd><p>A SQLite database connection has the following attributes and methods:</p>
<dl class="attribute">
<dt id="sqlite3.Connection.isolation_level">
<code class="descname">isolation_level</code><a class="headerlink" href="#sqlite3.Connection.isolation_level" title="Permalink to this definition">¶</a></dt>
<dd><p>Get or set the current isolation level. <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> for autocommit mode or
one of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See section
<a class="reference internal" href="#sqlite3-controlling-transactions"><span class="std std-ref">Controlling Transactions</span></a> for a more detailed explanation.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.cursor">
<code class="descname">cursor</code><span class="sig-paren">(</span><em>factory=Cursor</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.cursor" title="Permalink to this definition">¶</a></dt>
<dd><p>The cursor method accepts a single optional parameter <em>factory</em>. If
supplied, this must be a callable returning an instance of <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a>
or its subclasses.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.commit">
<code class="descname">commit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.commit" title="Permalink to this definition">¶</a></dt>
<dd><p>This method commits the current transaction. If you don’t call this method,
anything you did since the last call to <code class="docutils literal notranslate"><span class="pre">commit()</span></code> is not visible from
other database connections. If you wonder why you don’t see the data you’ve
written to the database, please check you didn’t forget to call this method.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.rollback">
<code class="descname">rollback</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.rollback" title="Permalink to this definition">¶</a></dt>
<dd><p>This method rolls back any changes to the database since the last call to
<a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">commit()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.close" title="Permalink to this definition">¶</a></dt>
<dd><p>This closes the database connection. Note that this does not automatically
call <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">commit()</span></code></a>. If you just close your database connection without
calling <a class="reference internal" href="#sqlite3.Connection.commit" title="sqlite3.Connection.commit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">commit()</span></code></a> first, your changes will be lost!</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.execute">
<code class="descname">execute</code><span class="sig-paren">(</span><em>sql</em><span class="optional">[</span>, <em>parameters</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.execute" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a nonstandard shortcut that creates an intermediate cursor object by
calling the cursor method, then calls the cursor’s <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execute</span></code></a> method with the parameters given.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.executemany">
<code class="descname">executemany</code><span class="sig-paren">(</span><em>sql</em><span class="optional">[</span>, <em>parameters</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.executemany" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a nonstandard shortcut that creates an intermediate cursor object by
calling the cursor method, then calls the cursor’s <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code class="xref py py-meth docutils literal notranslate"><span class="pre">executemany</span></code></a> method with the parameters given.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.executescript">
<code class="descname">executescript</code><span class="sig-paren">(</span><em>sql_script</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.executescript" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a nonstandard shortcut that creates an intermediate cursor object by
calling the cursor method, then calls the cursor’s <a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code class="xref py py-meth docutils literal notranslate"><span class="pre">executescript</span></code></a> method with the parameters given.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.create_function">
<code class="descname">create_function</code><span class="sig-paren">(</span><em>name</em>, <em>num_params</em>, <em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.create_function" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a user-defined function that you can later use from within SQL
statements under the function name <em>name</em>. <em>num_params</em> is the number of
parameters the function accepts, and <em>func</em> is a Python callable that is called
as the SQL function.</p>
<p>The function can return any of the types supported by SQLite: unicode, str, int,
long, float, buffer and <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="kn">import</span> <span class="nn">md5</span>

<span class="k">def</span> <span class="nf">md5sum</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">md5</span><span class="o">.</span><span class="n">md5</span><span class="p">(</span><span class="n">t</span><span class="p">)</span><span class="o">.</span><span class="n">hexdigest</span><span class="p">()</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">create_function</span><span class="p">(</span><span class="s2">&quot;md5&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">md5sum</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select md5(?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;foo&quot;</span><span class="p">,))</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.create_aggregate">
<code class="descname">create_aggregate</code><span class="sig-paren">(</span><em>name</em>, <em>num_params</em>, <em>aggregate_class</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.create_aggregate" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a user-defined aggregate function.</p>
<p>The aggregate class must implement a <code class="docutils literal notranslate"><span class="pre">step</span></code> method, which accepts the number
of parameters <em>num_params</em>, and a <code class="docutils literal notranslate"><span class="pre">finalize</span></code> method which will return the
final result of the aggregate.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">finalize</span></code> method can return any of the types supported by SQLite:
unicode, str, int, long, float, buffer and <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">class</span> <span class="nc">MySum</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>

    <span class="k">def</span> <span class="nf">step</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">+=</span> <span class="n">value</span>

    <span class="k">def</span> <span class="nf">finalize</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">count</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">create_aggregate</span><span class="p">(</span><span class="s2">&quot;mysum&quot;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="n">MySum</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table test(i)&quot;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into test(i) values (1)&quot;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into test(i) values (2)&quot;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select mysum(i) from test&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.create_collation">
<code class="descname">create_collation</code><span class="sig-paren">(</span><em>name</em>, <em>callable</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.create_collation" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a collation with the specified <em>name</em> and <em>callable</em>. The callable will
be passed two string arguments. It should return -1 if the first is ordered
lower than the second, 0 if they are ordered equal and 1 if the first is ordered
higher than the second.  Note that this controls sorting (ORDER BY in SQL) so
your comparisons don’t affect other SQL operations.</p>
<p>Note that the callable will get its parameters as Python bytestrings, which will
normally be encoded in UTF-8.</p>
<p>The following example shows a custom collation that sorts “the wrong way”:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">def</span> <span class="nf">collate_reverse</span><span class="p">(</span><span class="n">string1</span><span class="p">,</span> <span class="n">string2</span><span class="p">):</span>
    <span class="k">return</span> <span class="o">-</span><span class="nb">cmp</span><span class="p">(</span><span class="n">string1</span><span class="p">,</span> <span class="n">string2</span><span class="p">)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">create_collation</span><span class="p">(</span><span class="s2">&quot;reverse&quot;</span><span class="p">,</span> <span class="n">collate_reverse</span><span class="p">)</span>

<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table test(x)&quot;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s2">&quot;insert into test(x) values (?)&quot;</span><span class="p">,</span> <span class="p">[(</span><span class="s2">&quot;a&quot;</span><span class="p">,),</span> <span class="p">(</span><span class="s2">&quot;b&quot;</span><span class="p">,)])</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select x from test order by x collate reverse&quot;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cur</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">row</span>
<span class="n">con</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>To remove a collation, call <code class="docutils literal notranslate"><span class="pre">create_collation</span></code> with <code class="docutils literal notranslate"><span class="pre">None</span></code> as callable:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">con</span><span class="o">.</span><span class="n">create_collation</span><span class="p">(</span><span class="s2">&quot;reverse&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.interrupt">
<code class="descname">interrupt</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.interrupt" title="Permalink to this definition">¶</a></dt>
<dd><p>You can call this method from a different thread to abort any queries that might
be executing on the connection. The query will then abort and the caller will
get an exception.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.set_authorizer">
<code class="descname">set_authorizer</code><span class="sig-paren">(</span><em>authorizer_callback</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.set_authorizer" title="Permalink to this definition">¶</a></dt>
<dd><p>This routine registers a callback. The callback is invoked for each attempt to
access a column of a table in the database. The callback should return
<code class="xref py py-const docutils literal notranslate"><span class="pre">SQLITE_OK</span></code> if access is allowed, <code class="xref py py-const docutils literal notranslate"><span class="pre">SQLITE_DENY</span></code> if the entire SQL
statement should be aborted with an error and <code class="xref py py-const docutils literal notranslate"><span class="pre">SQLITE_IGNORE</span></code> if the
column should be treated as a NULL value. These constants are available in the
<a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module.</p>
<p>The first argument to the callback signifies what kind of operation is to be
authorized. The second and third argument will be arguments or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>
depending on the first argument. The 4th argument is the name of the database
(“main”, “temp”, etc.) if applicable. The 5th argument is the name of the
inner-most trigger or view that is responsible for the access attempt or
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if this access attempt is directly from input SQL code.</p>
<p>Please consult the SQLite documentation about the possible values for the first
argument and the meaning of the second and third argument depending on the first
one. All necessary constants are available in the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.set_progress_handler">
<code class="descname">set_progress_handler</code><span class="sig-paren">(</span><em>handler</em>, <em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.set_progress_handler" title="Permalink to this definition">¶</a></dt>
<dd><p>This routine registers a callback. The callback is invoked for every <em>n</em>
instructions of the SQLite virtual machine. This is useful if you want to
get called from SQLite during long-running operations, for example to update
a GUI.</p>
<p>If you want to clear any previously installed progress handler, call the
method with <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> for <em>handler</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.enable_load_extension">
<code class="descname">enable_load_extension</code><span class="sig-paren">(</span><em>enabled</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.enable_load_extension" title="Permalink to this definition">¶</a></dt>
<dd><p>This routine allows/disallows the SQLite engine to load SQLite extensions
from shared libraries.  SQLite extensions can define new functions,
aggregates or whole new virtual table implementations.  One well-known
extension is the fulltext-search extension distributed with SQLite.</p>
<p>Loadable extensions are disabled by default. See <a class="footnote-reference" href="#f1" id="id1">[1]</a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>

<span class="c1"># enable extension loading</span>
<span class="n">con</span><span class="o">.</span><span class="n">enable_load_extension</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>

<span class="c1"># Load the fulltext search extension</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select load_extension(&#39;./fts3.so&#39;)&quot;</span><span class="p">)</span>

<span class="c1"># alternatively you can load the extension using an API call:</span>
<span class="c1"># con.load_extension(&quot;./fts3.so&quot;)</span>

<span class="c1"># disable extension loading again</span>
<span class="n">con</span><span class="o">.</span><span class="n">enable_load_extension</span><span class="p">(</span><span class="kc">False</span><span class="p">)</span>

<span class="c1"># example from SQLite wiki</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create virtual table recipe using fts3(name, ingredients)&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">executescript</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2">    insert into recipe (name, ingredients) values (&#39;broccoli stew&#39;, &#39;broccoli peppers cheese tomatoes&#39;);</span>
<span class="s2">    insert into recipe (name, ingredients) values (&#39;pumpkin stew&#39;, &#39;pumpkin onions garlic celery&#39;);</span>
<span class="s2">    insert into recipe (name, ingredients) values (&#39;broccoli pie&#39;, &#39;broccoli cheese onions flour&#39;);</span>
<span class="s2">    insert into recipe (name, ingredients) values (&#39;pumpkin pie&#39;, &#39;pumpkin sugar flour butter&#39;);</span>
<span class="s2">    &quot;&quot;&quot;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select rowid, name, ingredients from recipe where name match &#39;pie&#39;&quot;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">row</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Connection.load_extension">
<code class="descname">load_extension</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Connection.load_extension" title="Permalink to this definition">¶</a></dt>
<dd><p>This routine loads a SQLite extension from a shared library.  You have to
enable extension loading with <a class="reference internal" href="#sqlite3.Connection.enable_load_extension" title="sqlite3.Connection.enable_load_extension"><code class="xref py py-meth docutils literal notranslate"><span class="pre">enable_load_extension()</span></code></a> before you can
use this routine.</p>
<p>Loadable extensions are disabled by default. See <a class="footnote-reference" href="#f1" id="id2">[1]</a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Connection.row_factory">
<code class="descname">row_factory</code><a class="headerlink" href="#sqlite3.Connection.row_factory" title="Permalink to this definition">¶</a></dt>
<dd><p>You can change this attribute to a callable that accepts the cursor and the
original row as a tuple and will return the real result row.  This way, you can
implement more advanced ways of returning results, such  as returning an object
that can also access columns by name.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">def</span> <span class="nf">dict_factory</span><span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">row</span><span class="p">):</span>
    <span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">for</span> <span class="n">idx</span><span class="p">,</span> <span class="n">col</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">cursor</span><span class="o">.</span><span class="n">description</span><span class="p">):</span>
        <span class="n">d</span><span class="p">[</span><span class="n">col</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span> <span class="o">=</span> <span class="n">row</span><span class="p">[</span><span class="n">idx</span><span class="p">]</span>
    <span class="k">return</span> <span class="n">d</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">row_factory</span> <span class="o">=</span> <span class="n">dict_factory</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select 1 as a&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="s2">&quot;a&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>If returning a tuple doesn’t suffice and you want name-based access to
columns, you should consider setting <a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">row_factory</span></code></a> to the
highly-optimized <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">sqlite3.Row</span></code></a> type. <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">Row</span></code></a> provides both
index-based and case-insensitive name-based access to columns with almost no
memory overhead. It will probably be better than your own custom
dictionary-based approach or even a db_row based solution.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Connection.text_factory">
<code class="descname">text_factory</code><a class="headerlink" href="#sqlite3.Connection.text_factory" title="Permalink to this definition">¶</a></dt>
<dd><p>Using this attribute you can control what objects are returned for the <code class="docutils literal notranslate"><span class="pre">TEXT</span></code>
data type. By default, this attribute is set to <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> and the
<a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module will return Unicode objects for <code class="docutils literal notranslate"><span class="pre">TEXT</span></code>. If you want to
return bytestrings instead, you can set it to <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
<p>For efficiency reasons, there’s also a way to return Unicode objects only for
non-ASCII data, and bytestrings otherwise. To activate it, set this attribute to
<code class="xref py py-const docutils literal notranslate"><span class="pre">sqlite3.OptimizedUnicode</span></code>.</p>
<p>You can also set it to any other callable that accepts a single bytestring
parameter and returns the resulting object.</p>
<p>See the following example code for illustration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">AUSTRIA</span> <span class="o">=</span> <span class="sa">u</span><span class="s2">&quot;</span><span class="se">\xd6</span><span class="s2">sterreich&quot;</span>

<span class="c1"># by default, rows are returned as Unicode</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">AUSTRIA</span><span class="p">,))</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">AUSTRIA</span>

<span class="c1"># but we can make sqlite3 always return bytestrings ...</span>
<span class="n">con</span><span class="o">.</span><span class="n">text_factory</span> <span class="o">=</span> <span class="nb">str</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">AUSTRIA</span><span class="p">,))</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="k">assert</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="ow">is</span> <span class="nb">str</span>
<span class="c1"># the bytestrings will be encoded in UTF-8, unless you stored garbage in the</span>
<span class="c1"># database ...</span>
<span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">AUSTRIA</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;utf-8&quot;</span><span class="p">)</span>

<span class="c1"># we can also implement a custom text_factory ...</span>
<span class="c1"># here we implement one that will ignore Unicode characters that cannot be</span>
<span class="c1"># decoded from UTF-8</span>
<span class="n">con</span><span class="o">.</span><span class="n">text_factory</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">unicode</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="s2">&quot;utf-8&quot;</span><span class="p">,</span> <span class="s2">&quot;ignore&quot;</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;this is latin1 and would normally create errors&quot;</span> <span class="o">+</span>
                         <span class="sa">u</span><span class="s2">&quot;</span><span class="se">\xe4\xf6\xfc</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;latin1&quot;</span><span class="p">),))</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="k">assert</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="ow">is</span> <span class="n">unicode</span>

<span class="c1"># sqlite3 offers a built-in optimized text_factory that will return bytestring</span>
<span class="c1"># objects, if the data is in ASCII only, and otherwise return unicode objects</span>
<span class="n">con</span><span class="o">.</span><span class="n">text_factory</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">OptimizedUnicode</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">AUSTRIA</span><span class="p">,))</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="k">assert</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="ow">is</span> <span class="n">unicode</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;Germany&quot;</span><span class="p">,))</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="k">assert</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="ow">is</span> <span class="nb">str</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Connection.total_changes">
<code class="descname">total_changes</code><a class="headerlink" href="#sqlite3.Connection.total_changes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the total number of database rows that have been modified, inserted, or
deleted since the database connection was opened.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Connection.iterdump">
<code class="descname">iterdump</code><a class="headerlink" href="#sqlite3.Connection.iterdump" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns an iterator to dump the database in an SQL text format.  Useful when
saving an in-memory database for later restoration.  This function provides
the same capabilities as the <kbd class="kbd docutils literal notranslate">.dump</kbd> command in the <strong class="program">sqlite3</strong>
shell.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Convert file existing_db.db to SQL dump file dump.sql</span>
<span class="kn">import</span> <span class="nn">sqlite3</span><span class="o">,</span> <span class="nn">os</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;existing_db.db&#39;</span><span class="p">)</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;dump.sql&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">con</span><span class="o">.</span><span class="n">iterdump</span><span class="p">():</span>
        <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%s</span><span class="se">\n</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="cursor-objects">
<span id="sqlite3-cursor-objects"></span><h2>11.13.3. Cursor Objects<a class="headerlink" href="#cursor-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="sqlite3.Cursor">
<em class="property">class </em><code class="descclassname">sqlite3.</code><code class="descname">Cursor</code><a class="headerlink" href="#sqlite3.Cursor" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a> instance has the following attributes and methods.</p>
<dl class="method">
<dt id="sqlite3.Cursor.execute">
<code class="descname">execute</code><span class="sig-paren">(</span><em>sql</em><span class="optional">[</span>, <em>parameters</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.execute" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes an SQL statement. The SQL statement may be parameterized (i. e.
placeholders instead of SQL literals). The <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module supports two
kinds of placeholders: question marks (qmark style) and named placeholders
(named style).</p>
<p>Here’s an example of both styles:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table people (name_last, age)&quot;</span><span class="p">)</span>

<span class="n">who</span> <span class="o">=</span> <span class="s2">&quot;Yeltsin&quot;</span>
<span class="n">age</span> <span class="o">=</span> <span class="mi">72</span>

<span class="c1"># This is the qmark style:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into people values (?, ?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">who</span><span class="p">,</span> <span class="n">age</span><span class="p">))</span>

<span class="c1"># And this is the named style:</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select * from people where name_last=:who and age=:age&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;who&quot;</span><span class="p">:</span> <span class="n">who</span><span class="p">,</span> <span class="s2">&quot;age&quot;</span><span class="p">:</span> <span class="n">age</span><span class="p">})</span>

<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
</pre></div>
</div>
<p><a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code></a> will only execute a single SQL statement. If you try to execute
more than one statement with it, it will raise a Warning. Use
<a class="reference internal" href="#sqlite3.Cursor.executescript" title="sqlite3.Cursor.executescript"><code class="xref py py-meth docutils literal notranslate"><span class="pre">executescript()</span></code></a> if you want to execute multiple SQL statements with one
call.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Cursor.executemany">
<code class="descname">executemany</code><span class="sig-paren">(</span><em>sql</em>, <em>seq_of_parameters</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.executemany" title="Permalink to this definition">¶</a></dt>
<dd><p>Executes an SQL command against all parameter sequences or mappings found in
the sequence <em>sql</em>.  The <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module also allows using an
<a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> yielding parameters instead of a sequence.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">class</span> <span class="nc">IterChars</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">=</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">&gt;</span> <span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">):</span>
            <span class="k">raise</span> <span class="ne">StopIteration</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">return</span> <span class="p">(</span><span class="nb">chr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">count</span> <span class="o">-</span> <span class="mi">1</span><span class="p">),)</span> <span class="c1"># this is a 1-tuple</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table characters(c)&quot;</span><span class="p">)</span>

<span class="n">theIter</span> <span class="o">=</span> <span class="n">IterChars</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s2">&quot;insert into characters(c) values (?)&quot;</span><span class="p">,</span> <span class="n">theIter</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select c from characters&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>
</div>
<p>Here’s a shorter example using a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="kn">import</span> <span class="nn">string</span>

<span class="k">def</span> <span class="nf">char_generator</span><span class="p">():</span>
    <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">string</span><span class="o">.</span><span class="n">lowercase</span><span class="p">:</span>
        <span class="k">yield</span> <span class="p">(</span><span class="n">c</span><span class="p">,)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table characters(c)&quot;</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s2">&quot;insert into characters(c) values (?)&quot;</span><span class="p">,</span> <span class="n">char_generator</span><span class="p">())</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select c from characters&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchall</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Cursor.executescript">
<code class="descname">executescript</code><span class="sig-paren">(</span><em>sql_script</em><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.executescript" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a nonstandard convenience method for executing multiple SQL statements
at once. It issues a <code class="docutils literal notranslate"><span class="pre">COMMIT</span></code> statement first, then executes the SQL script it
gets as a parameter.</p>
<p><em>sql_script</em> can be a bytestring or a Unicode string.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">executescript</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2">    create table person(</span>
<span class="s2">        firstname,</span>
<span class="s2">        lastname,</span>
<span class="s2">        age</span>
<span class="s2">    );</span>

<span class="s2">    create table book(</span>
<span class="s2">        title,</span>
<span class="s2">        author,</span>
<span class="s2">        published</span>
<span class="s2">    );</span>

<span class="s2">    insert into book(title, author, published)</span>
<span class="s2">    values (</span>
<span class="s2">        &#39;Dirk Gently&#39;&#39;s Holistic Detective Agency&#39;,</span>
<span class="s2">        &#39;Douglas Adams&#39;,</span>
<span class="s2">        1987</span>
<span class="s2">    );</span>
<span class="s2">    &quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Cursor.fetchone">
<code class="descname">fetchone</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.fetchone" title="Permalink to this definition">¶</a></dt>
<dd><p>Fetches the next row of a query result set, returning a single sequence,
or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> when no more data is available.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Cursor.fetchmany">
<code class="descname">fetchmany</code><span class="sig-paren">(</span><span class="optional">[</span><em>size=cursor.arraysize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.fetchmany" title="Permalink to this definition">¶</a></dt>
<dd><p>Fetches the next set of rows of a query result, returning a list.  An empty
list is returned when no more rows are available.</p>
<p>The number of rows to fetch per call is specified by the <em>size</em> parameter.
If it is not given, the cursor’s arraysize determines the number of rows
to be fetched. The method should try to fetch as many rows as indicated by
the size parameter. If this is not possible due to the specified number of
rows not being available, fewer rows may be returned.</p>
<p>Note there are performance considerations involved with the <em>size</em> parameter.
For optimal performance, it is usually best to use the arraysize attribute.
If the <em>size</em> parameter is used, then it is best for it to retain the same
value from one <a class="reference internal" href="#sqlite3.Cursor.fetchmany" title="sqlite3.Cursor.fetchmany"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchmany()</span></code></a> call to the next.</p>
</dd></dl>

<dl class="method">
<dt id="sqlite3.Cursor.fetchall">
<code class="descname">fetchall</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Cursor.fetchall" title="Permalink to this definition">¶</a></dt>
<dd><p>Fetches all (remaining) rows of a query result, returning a list.  Note that
the cursor’s arraysize attribute can affect the performance of this operation.
An empty list is returned when no rows are available.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Cursor.rowcount">
<code class="descname">rowcount</code><a class="headerlink" href="#sqlite3.Cursor.rowcount" title="Permalink to this definition">¶</a></dt>
<dd><p>Although the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a> class of the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module implements this
attribute, the database engine’s own support for the determination of “rows
affected”/”rows selected” is quirky.</p>
<p>For <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code class="xref py py-meth docutils literal notranslate"><span class="pre">executemany()</span></code></a> statements, the number of modifications are summed up
into <a class="reference internal" href="#sqlite3.Cursor.rowcount" title="sqlite3.Cursor.rowcount"><code class="xref py py-attr docutils literal notranslate"><span class="pre">rowcount</span></code></a>.</p>
<p>As required by the Python DB API Spec, the <a class="reference internal" href="#sqlite3.Cursor.rowcount" title="sqlite3.Cursor.rowcount"><code class="xref py py-attr docutils literal notranslate"><span class="pre">rowcount</span></code></a> attribute “is -1 in
case no <code class="docutils literal notranslate"><span class="pre">executeXX()</span></code> has been performed on the cursor or the rowcount of the
last operation is not determinable by the interface”. This includes <code class="docutils literal notranslate"><span class="pre">SELECT</span></code>
statements because we cannot determine the number of rows a query produced
until all rows were fetched.</p>
<p>With SQLite versions before 3.6.5, <a class="reference internal" href="#sqlite3.Cursor.rowcount" title="sqlite3.Cursor.rowcount"><code class="xref py py-attr docutils literal notranslate"><span class="pre">rowcount</span></code></a> is set to 0 if
you make a <code class="docutils literal notranslate"><span class="pre">DELETE</span> <span class="pre">FROM</span> <span class="pre">table</span></code> without any condition.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Cursor.lastrowid">
<code class="descname">lastrowid</code><a class="headerlink" href="#sqlite3.Cursor.lastrowid" title="Permalink to this definition">¶</a></dt>
<dd><p>This read-only attribute provides the rowid of the last modified row. It is
only set if you issued an <code class="docutils literal notranslate"><span class="pre">INSERT</span></code> statement using the <a class="reference internal" href="#sqlite3.Cursor.execute" title="sqlite3.Cursor.execute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code></a>
method. For operations other than <code class="docutils literal notranslate"><span class="pre">INSERT</span></code> or when <a class="reference internal" href="#sqlite3.Cursor.executemany" title="sqlite3.Cursor.executemany"><code class="xref py py-meth docutils literal notranslate"><span class="pre">executemany()</span></code></a> is
called, <a class="reference internal" href="#sqlite3.Cursor.lastrowid" title="sqlite3.Cursor.lastrowid"><code class="xref py py-attr docutils literal notranslate"><span class="pre">lastrowid</span></code></a> is set to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Cursor.description">
<code class="descname">description</code><a class="headerlink" href="#sqlite3.Cursor.description" title="Permalink to this definition">¶</a></dt>
<dd><p>This read-only attribute provides the column names of the last query. To
remain compatible with the Python DB API, it returns a 7-tuple for each
column where the last six items of each tuple are <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>It is set for <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> statements without any matching rows as well.</p>
</dd></dl>

<dl class="attribute">
<dt id="sqlite3.Cursor.connection">
<code class="descname">connection</code><a class="headerlink" href="#sqlite3.Cursor.connection" title="Permalink to this definition">¶</a></dt>
<dd><p>This read-only attribute provides the SQLite database <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a>
used by the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a> object.  A <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a> object created by
calling <a class="reference internal" href="#sqlite3.Connection.cursor" title="sqlite3.Connection.cursor"><code class="xref py py-meth docutils literal notranslate"><span class="pre">con.cursor()</span></code></a> will have a
<a class="reference internal" href="#sqlite3.Cursor.connection" title="sqlite3.Cursor.connection"><code class="xref py py-attr docutils literal notranslate"><span class="pre">connection</span></code></a> attribute that refers to <em>con</em>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cur</span><span class="o">.</span><span class="n">connection</span> <span class="o">==</span> <span class="n">con</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="row-objects">
<span id="sqlite3-row-objects"></span><h2>11.13.4. Row Objects<a class="headerlink" href="#row-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="sqlite3.Row">
<em class="property">class </em><code class="descclassname">sqlite3.</code><code class="descname">Row</code><a class="headerlink" href="#sqlite3.Row" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">Row</span></code></a> instance serves as a highly optimized
<a class="reference internal" href="#sqlite3.Connection.row_factory" title="sqlite3.Connection.row_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">row_factory</span></code></a> for <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> objects.
It tries to mimic a tuple in most of its features.</p>
<p>It supports mapping access by column name and index, iteration,
representation, equality testing and <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>.</p>
<p>If two <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">Row</span></code></a> objects have exactly the same columns and their
members are equal, they compare equal.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added iteration and equality (hashability).</p>
</div>
<dl class="method">
<dt id="sqlite3.Row.keys">
<code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sqlite3.Row.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a list of column names. Immediately after a query,
it is the first member of each tuple in <a class="reference internal" href="#sqlite3.Cursor.description" title="sqlite3.Cursor.description"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Cursor.description</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</dd></dl>

<p>Let’s assume we initialize a table as in the example given above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;create table stocks</span>
<span class="s1">(date text, trans text, symbol text,</span>
<span class="s1"> qty real, price real)&#39;&#39;&#39;</span><span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;insert into stocks</span>
<span class="s2">          values (&#39;2006-01-05&#39;,&#39;BUY&#39;,&#39;RHAT&#39;,100,35.14)&quot;&quot;&quot;</span><span class="p">)</span>
<span class="n">conn</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Now we plug <a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">Row</span></code></a> in:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">row_factory</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">Row</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select * from stocks&#39;</span><span class="p">)</span>
<span class="go">&lt;sqlite3.Cursor object at 0x7f4e7dd8fa80&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">r</span><span class="p">)</span>
<span class="go">&lt;type &#39;sqlite3.Row&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span>
<span class="go">(u&#39;2006-01-05&#39;, u&#39;BUY&#39;, u&#39;RHAT&#39;, 100.0, 35.14)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">r</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>
<span class="go">u&#39;RHAT&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="go">[&#39;date&#39;, &#39;trans&#39;, &#39;symbol&#39;, &#39;qty&#39;, &#39;price&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span><span class="p">[</span><span class="s1">&#39;qty&#39;</span><span class="p">]</span>
<span class="go">100.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">member</span> <span class="ow">in</span> <span class="n">r</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">member</span>
<span class="gp">...</span>
<span class="go">2006-01-05</span>
<span class="go">BUY</span>
<span class="go">RHAT</span>
<span class="go">100.0</span>
<span class="go">35.14</span>
</pre></div>
</div>
</div>
<div class="section" id="sqlite-and-python-types">
<span id="sqlite3-types"></span><h2>11.13.5. SQLite and Python types<a class="headerlink" href="#sqlite-and-python-types" title="Permalink to this headline">¶</a></h2>
<div class="section" id="introduction">
<h3>11.13.5.1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h3>
<p>SQLite natively supports the following types: <code class="docutils literal notranslate"><span class="pre">NULL</span></code>, <code class="docutils literal notranslate"><span class="pre">INTEGER</span></code>,
<code class="docutils literal notranslate"><span class="pre">REAL</span></code>, <code class="docutils literal notranslate"><span class="pre">TEXT</span></code>, <code class="docutils literal notranslate"><span class="pre">BLOB</span></code>.</p>
<p>The following Python types can thus be sent to SQLite without any problem:</p>
<table border="1" class="docutils">
<colgroup>
<col width="69%" />
<col width="31%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Python type</th>
<th class="head">SQLite type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">NULL</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">INTEGER</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">INTEGER</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">REAL</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> (UTF8-encoded)</td>
<td><code class="docutils literal notranslate"><span class="pre">TEXT</span></code></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">TEXT</span></code></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">buffer</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">BLOB</span></code></td>
</tr>
</tbody>
</table>
<p>This is how SQLite types are converted to Python types by default:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">SQLite type</th>
<th class="head">Python type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">NULL</span></code></td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">INTEGER</span></code></td>
<td><a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>,
depending on size</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">REAL</span></code></td>
<td><a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">TEXT</span></code></td>
<td>depends on <a class="reference internal" href="#sqlite3.Connection.text_factory" title="sqlite3.Connection.text_factory"><code class="xref py py-attr docutils literal notranslate"><span class="pre">text_factory</span></code></a>,
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> by default</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">BLOB</span></code></td>
<td><a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">buffer</span></code></a></td>
</tr>
</tbody>
</table>
<p>The type system of the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module is extensible in two ways: you can
store additional Python types in a SQLite database via object adaptation, and
you can let the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module convert SQLite types to different Python
types via converters.</p>
</div>
<div class="section" id="using-adapters-to-store-additional-python-types-in-sqlite-databases">
<h3>11.13.5.2. Using adapters to store additional Python types in SQLite databases<a class="headerlink" href="#using-adapters-to-store-additional-python-types-in-sqlite-databases" title="Permalink to this headline">¶</a></h3>
<p>As described before, SQLite supports only a limited set of types natively. To
use other Python types with SQLite, you must <strong>adapt</strong> them to one of the
sqlite3 module’s supported types for SQLite: one of NoneType, int, long, float,
str, unicode, buffer.</p>
<p>There are two ways to enable the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module to adapt a custom Python
type to one of the supported ones.</p>
<div class="section" id="letting-your-object-adapt-itself">
<h4>11.13.5.2.1. Letting your object adapt itself<a class="headerlink" href="#letting-your-object-adapt-itself" title="Permalink to this headline">¶</a></h4>
<p>This is a good approach if you write the class yourself. Let’s suppose you have
a class like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>
</pre></div>
</div>
<p>Now you want to store the point in a single SQLite column.  First you’ll have to
choose one of the supported types first to be used for representing the point.
Let’s just use str and separate the coordinates using a semicolon. Then you need
to give your class a method <code class="docutils literal notranslate"><span class="pre">__conform__(self,</span> <span class="pre">protocol)</span></code> which must return
the converted value. The parameter <em>protocol</em> will be <code class="xref py py-class docutils literal notranslate"><span class="pre">PrepareProtocol</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>

    <span class="k">def</span> <span class="nf">__conform__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">protocol</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">protocol</span> <span class="ow">is</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">PrepareProtocol</span><span class="p">:</span>
            <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%f</span><span class="s2">;</span><span class="si">%f</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mf">4.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.2</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">p</span><span class="p">,))</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="registering-an-adapter-callable">
<h4>11.13.5.2.2. Registering an adapter callable<a class="headerlink" href="#registering-an-adapter-callable" title="Permalink to this headline">¶</a></h4>
<p>The other possibility is to create a function that converts the type to the
string representation and register the function with <a class="reference internal" href="#sqlite3.register_adapter" title="sqlite3.register_adapter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register_adapter()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The type/class to adapt must be a <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>, i. e. it must have
<a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> as one of its bases.</p>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>

<span class="k">def</span> <span class="nf">adapt_point</span><span class="p">(</span><span class="n">point</span><span class="p">):</span>
    <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%f</span><span class="s2">;</span><span class="si">%f</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>

<span class="n">sqlite3</span><span class="o">.</span><span class="n">register_adapter</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">adapt_point</span><span class="p">)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mf">4.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.2</span><span class="p">)</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">p</span><span class="p">,))</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module has two default adapters for Python’s built-in
<a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> types.  Now let’s suppose
we want to store <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> objects not in ISO representation,
but as a Unix timestamp.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="kn">import</span> <span class="nn">datetime</span><span class="o">,</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">adapt_datetime</span><span class="p">(</span><span class="n">ts</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">time</span><span class="o">.</span><span class="n">mktime</span><span class="p">(</span><span class="n">ts</span><span class="o">.</span><span class="n">timetuple</span><span class="p">())</span>

<span class="n">sqlite3</span><span class="o">.</span><span class="n">register_adapter</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">,</span> <span class="n">adapt_datetime</span><span class="p">)</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select ?&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">now</span><span class="p">,))</span>
<span class="nb">print</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="converting-sqlite-values-to-custom-python-types">
<h3>11.13.5.3. Converting SQLite values to custom Python types<a class="headerlink" href="#converting-sqlite-values-to-custom-python-types" title="Permalink to this headline">¶</a></h3>
<p>Writing an adapter lets you send custom Python types to SQLite. But to make it
really useful we need to make the Python to SQLite to Python roundtrip work.</p>
<p>Enter converters.</p>
<p>Let’s go back to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Point</span></code> class. We stored the x and y coordinates
separated via semicolons as strings in SQLite.</p>
<p>First, we’ll define a converter function that accepts the string as a parameter
and constructs a <code class="xref py py-class docutils literal notranslate"><span class="pre">Point</span></code> object from it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Converter functions <strong>always</strong> get called with a string, no matter under which
data type you sent the value to SQLite.</p>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">convert_point</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">float</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;;&quot;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
</pre></div>
</div>
<p>Now you need to make the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module know that what you select from
the database is actually a point. There are two ways of doing this:</p>
<ul class="simple">
<li>Implicitly via the declared type</li>
<li>Explicitly via the column name</li>
</ul>
<p>Both ways are described in section <a class="reference internal" href="#sqlite3-module-contents"><span class="std std-ref">Module functions and constants</span></a>, in the entries
for the constants <a class="reference internal" href="#sqlite3.PARSE_DECLTYPES" title="sqlite3.PARSE_DECLTYPES"><code class="xref py py-const docutils literal notranslate"><span class="pre">PARSE_DECLTYPES</span></code></a> and <a class="reference internal" href="#sqlite3.PARSE_COLNAMES" title="sqlite3.PARSE_COLNAMES"><code class="xref py py-const docutils literal notranslate"><span class="pre">PARSE_COLNAMES</span></code></a>.</p>
<p>The following example illustrates both approaches.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>

    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s2">&quot;(</span><span class="si">%f</span><span class="s2">;</span><span class="si">%f</span><span class="s2">)&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">adapt_point</span><span class="p">(</span><span class="n">point</span><span class="p">):</span>
    <span class="k">return</span> <span class="s2">&quot;</span><span class="si">%f</span><span class="s2">;</span><span class="si">%f</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="n">point</span><span class="o">.</span><span class="n">y</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">convert_point</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="nb">map</span><span class="p">(</span><span class="nb">float</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">&quot;;&quot;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">Point</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>

<span class="c1"># Register the adapter</span>
<span class="n">sqlite3</span><span class="o">.</span><span class="n">register_adapter</span><span class="p">(</span><span class="n">Point</span><span class="p">,</span> <span class="n">adapt_point</span><span class="p">)</span>

<span class="c1"># Register the converter</span>
<span class="n">sqlite3</span><span class="o">.</span><span class="n">register_converter</span><span class="p">(</span><span class="s2">&quot;point&quot;</span><span class="p">,</span> <span class="n">convert_point</span><span class="p">)</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">Point</span><span class="p">(</span><span class="mf">4.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.2</span><span class="p">)</span>

<span class="c1">#########################</span>
<span class="c1"># 1) Using declared types</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">,</span> <span class="n">detect_types</span><span class="o">=</span><span class="n">sqlite3</span><span class="o">.</span><span class="n">PARSE_DECLTYPES</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table test(p point)&quot;</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into test(p) values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">p</span><span class="p">,))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select p from test&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;with declared types:&quot;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">cur</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">con</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="c1">#######################</span>
<span class="c1"># 1) Using column names</span>
<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">,</span> <span class="n">detect_types</span><span class="o">=</span><span class="n">sqlite3</span><span class="o">.</span><span class="n">PARSE_COLNAMES</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table test(p)&quot;</span><span class="p">)</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into test(p) values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">p</span><span class="p">,))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select p as &quot;p [point]&quot; from test&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;with column names:&quot;</span><span class="p">,</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">cur</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">con</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="default-adapters-and-converters">
<h3>11.13.5.4. Default adapters and converters<a class="headerlink" href="#default-adapters-and-converters" title="Permalink to this headline">¶</a></h3>
<p>There are default adapters for the date and datetime types in the datetime
module. They will be sent as ISO dates/ISO timestamps to SQLite.</p>
<p>The default converters are registered under the name “date” for
<a class="reference internal" href="datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and under the name “timestamp” for
<a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a>.</p>
<p>This way, you can use date/timestamps from Python without any additional
fiddling in most cases. The format of the adapters is also compatible with the
experimental SQLite date/time functions.</p>
<p>The following example demonstrates this.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">,</span> <span class="n">detect_types</span><span class="o">=</span><span class="n">sqlite3</span><span class="o">.</span><span class="n">PARSE_DECLTYPES</span><span class="o">|</span><span class="n">sqlite3</span><span class="o">.</span><span class="n">PARSE_COLNAMES</span><span class="p">)</span>
<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table test(d date, ts timestamp)&quot;</span><span class="p">)</span>

<span class="n">today</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into test(d, ts) values (?, ?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">today</span><span class="p">,</span> <span class="n">now</span><span class="p">))</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select d, ts from test&quot;</span><span class="p">)</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">today</span><span class="p">,</span> <span class="s2">&quot;=&gt;&quot;</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="nb">print</span> <span class="n">now</span><span class="p">,</span> <span class="s2">&quot;=&gt;&quot;</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>

<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select current_date as &quot;d [date]&quot;, current_timestamp as &quot;ts [timestamp]&quot;&#39;</span><span class="p">)</span>
<span class="n">row</span> <span class="o">=</span> <span class="n">cur</span><span class="o">.</span><span class="n">fetchone</span><span class="p">()</span>
<span class="nb">print</span> <span class="s2">&quot;current_date&quot;</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="nb">print</span> <span class="s2">&quot;current_timestamp&quot;</span><span class="p">,</span> <span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="nb">type</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>If a timestamp stored in SQLite has a fractional part longer than 6
numbers, its value will be truncated to microsecond precision by the
timestamp converter.</p>
</div>
</div>
<div class="section" id="controlling-transactions">
<span id="sqlite3-controlling-transactions"></span><h2>11.13.6. Controlling Transactions<a class="headerlink" href="#controlling-transactions" title="Permalink to this headline">¶</a></h2>
<p>By default, the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module opens transactions implicitly before a
Data Modification Language (DML)  statement (i.e.
<code class="docutils literal notranslate"><span class="pre">INSERT</span></code>/<code class="docutils literal notranslate"><span class="pre">UPDATE</span></code>/<code class="docutils literal notranslate"><span class="pre">DELETE</span></code>/<code class="docutils literal notranslate"><span class="pre">REPLACE</span></code>), and commits transactions
implicitly before a non-DML, non-query statement (i. e.
anything other than <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> or the aforementioned).</p>
<p>So if you are within a transaction and issue a command like <code class="docutils literal notranslate"><span class="pre">CREATE</span> <span class="pre">TABLE</span>
<span class="pre">...</span></code>, <code class="docutils literal notranslate"><span class="pre">VACUUM</span></code>, <code class="docutils literal notranslate"><span class="pre">PRAGMA</span></code>, the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module will commit implicitly
before executing that command. There are two reasons for doing that. The first
is that some of these commands don’t work within transactions. The other reason
is that sqlite3 needs to keep track of the transaction state (if a transaction
is active or not).</p>
<p>You can control which kind of <code class="docutils literal notranslate"><span class="pre">BEGIN</span></code> statements sqlite3 implicitly executes
(or none at all) via the <em>isolation_level</em> parameter to the <a class="reference internal" href="#sqlite3.connect" title="sqlite3.connect"><code class="xref py py-func docutils literal notranslate"><span class="pre">connect()</span></code></a>
call, or via the <code class="xref py py-attr docutils literal notranslate"><span class="pre">isolation_level</span></code> property of connections.</p>
<p>If you want <strong>autocommit mode</strong>, then set <code class="xref py py-attr docutils literal notranslate"><span class="pre">isolation_level</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Otherwise leave it at its default, which will result in a plain “BEGIN”
statement, or set it to one of SQLite’s supported isolation levels: “DEFERRED”,
“IMMEDIATE” or “EXCLUSIVE”.</p>
</div>
<div class="section" id="using-sqlite3-efficiently">
<h2>11.13.7. Using <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> efficiently<a class="headerlink" href="#using-sqlite3-efficiently" title="Permalink to this headline">¶</a></h2>
<div class="section" id="using-shortcut-methods">
<h3>11.13.7.1. Using shortcut methods<a class="headerlink" href="#using-shortcut-methods" title="Permalink to this headline">¶</a></h3>
<p>Using the nonstandard <code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">executemany()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">executescript()</span></code> methods of the <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> object, your code can
be written more concisely because you don’t have to create the (often
superfluous) <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a> objects explicitly. Instead, the <a class="reference internal" href="#sqlite3.Cursor" title="sqlite3.Cursor"><code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code></a>
objects are created implicitly and these shortcut methods return the cursor
objects. This way, you can execute a <code class="docutils literal notranslate"><span class="pre">SELECT</span></code> statement and iterate over it
directly using only a single call on the <a class="reference internal" href="multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">persons</span> <span class="o">=</span> <span class="p">[</span>
    <span class="p">(</span><span class="s2">&quot;Hugo&quot;</span><span class="p">,</span> <span class="s2">&quot;Boss&quot;</span><span class="p">),</span>
    <span class="p">(</span><span class="s2">&quot;Calvin&quot;</span><span class="p">,</span> <span class="s2">&quot;Klein&quot;</span><span class="p">)</span>
    <span class="p">]</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>

<span class="c1"># Create the table</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table person(firstname, lastname)&quot;</span><span class="p">)</span>

<span class="c1"># Fill the table</span>
<span class="n">con</span><span class="o">.</span><span class="n">executemany</span><span class="p">(</span><span class="s2">&quot;insert into person(firstname, lastname) values (?, ?)&quot;</span><span class="p">,</span> <span class="n">persons</span><span class="p">)</span>

<span class="c1"># Print the table contents</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select firstname, lastname from person&quot;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">row</span>

<span class="nb">print</span> <span class="s2">&quot;I just deleted&quot;</span><span class="p">,</span> <span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;delete from person&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">rowcount</span><span class="p">,</span> <span class="s2">&quot;rows&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="accessing-columns-by-name-instead-of-by-index">
<h3>11.13.7.2. Accessing columns by name instead of by index<a class="headerlink" href="#accessing-columns-by-name-instead-of-by-index" title="Permalink to this headline">¶</a></h3>
<p>One useful feature of the <a class="reference internal" href="#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module is the built-in
<a class="reference internal" href="#sqlite3.Row" title="sqlite3.Row"><code class="xref py py-class docutils literal notranslate"><span class="pre">sqlite3.Row</span></code></a> class designed to be used as a row factory.</p>
<p>Rows wrapped with this class can be accessed both by index (like tuples) and
case-insensitively by name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">row_factory</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">Row</span>

<span class="n">cur</span> <span class="o">=</span> <span class="n">con</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="n">cur</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;select &#39;John&#39; as name, 42 as age&quot;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">cur</span><span class="p">:</span>
    <span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">row</span><span class="p">[</span><span class="s2">&quot;name&quot;</span><span class="p">]</span>
    <span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="s2">&quot;name&quot;</span><span class="p">]</span> <span class="o">==</span> <span class="n">row</span><span class="p">[</span><span class="s2">&quot;nAmE&quot;</span><span class="p">]</span>
    <span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="n">row</span><span class="p">[</span><span class="s2">&quot;age&quot;</span><span class="p">]</span>
    <span class="k">assert</span> <span class="n">row</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="n">row</span><span class="p">[</span><span class="s2">&quot;AgE&quot;</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="using-the-connection-as-a-context-manager">
<h3>11.13.7.3. Using the connection as a context manager<a class="headerlink" href="#using-the-connection-as-a-context-manager" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>Connection objects can be used as context managers
that automatically commit or rollback transactions.  In the event of an
exception, the transaction is rolled back; otherwise, the transaction is
committed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sqlite3</span>

<span class="n">con</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s2">&quot;:memory:&quot;</span><span class="p">)</span>
<span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;create table person (id integer primary key, firstname varchar unique)&quot;</span><span class="p">)</span>

<span class="c1"># Successful, con.commit() is called automatically afterwards</span>
<span class="k">with</span> <span class="n">con</span><span class="p">:</span>
    <span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into person(firstname) values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;Joe&quot;</span><span class="p">,))</span>

<span class="c1"># con.rollback() is called after the with block finishes with an exception, the</span>
<span class="c1"># exception is still raised and must be caught</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">con</span><span class="p">:</span>
        <span class="n">con</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;insert into person(firstname) values (?)&quot;</span><span class="p">,</span> <span class="p">(</span><span class="s2">&quot;Joe&quot;</span><span class="p">,))</span>
<span class="k">except</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">IntegrityError</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;couldn&#39;t add Joe twice&quot;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="common-issues">
<h2>11.13.8. Common issues<a class="headerlink" href="#common-issues" title="Permalink to this headline">¶</a></h2>
<div class="section" id="multithreading">
<h3>11.13.8.1. Multithreading<a class="headerlink" href="#multithreading" title="Permalink to this headline">¶</a></h3>
<p>Older SQLite versions had issues with sharing connections between threads.
That’s why the Python module disallows sharing connections and cursors between
threads. If you still try to do so, you will get an exception at runtime.</p>
<p>The only exception is calling the <a class="reference internal" href="#sqlite3.Connection.interrupt" title="sqlite3.Connection.interrupt"><code class="xref py py-meth docutils literal notranslate"><span class="pre">interrupt()</span></code></a> method, which
only makes sense to call from a different thread.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="f1" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[1]</td><td><em>(<a class="fn-backref" href="#id1">1</a>, <a class="fn-backref" href="#id2">2</a>)</em> The sqlite3 module is not built with loadable extension support by
default, because some platforms (notably Mac OS X) have SQLite libraries
which are compiled without this feature. To get loadable extension support,
you must modify setup.py and remove the line that sets
SQLITE_OMIT_LOAD_EXTENSION.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a><ul>
<li><a class="reference internal" href="#module-functions-and-constants">11.13.1. Module functions and constants</a></li>
<li><a class="reference internal" href="#connection-objects">11.13.2. Connection Objects</a></li>
<li><a class="reference internal" href="#cursor-objects">11.13.3. Cursor Objects</a></li>
<li><a class="reference internal" href="#row-objects">11.13.4. Row Objects</a></li>
<li><a class="reference internal" href="#sqlite-and-python-types">11.13.5. SQLite and Python types</a><ul>
<li><a class="reference internal" href="#introduction">11.13.5.1. Introduction</a></li>
<li><a class="reference internal" href="#using-adapters-to-store-additional-python-types-in-sqlite-databases">11.13.5.2. Using adapters to store additional Python types in SQLite databases</a><ul>
<li><a class="reference internal" href="#letting-your-object-adapt-itself">11.13.5.2.1. Letting your object adapt itself</a></li>
<li><a class="reference internal" href="#registering-an-adapter-callable">11.13.5.2.2. Registering an adapter callable</a></li>
</ul>
</li>
<li><a class="reference internal" href="#converting-sqlite-values-to-custom-python-types">11.13.5.3. Converting SQLite values to custom Python types</a></li>
<li><a class="reference internal" href="#default-adapters-and-converters">11.13.5.4. Default adapters and converters</a></li>
</ul>
</li>
<li><a class="reference internal" href="#controlling-transactions">11.13.6. Controlling Transactions</a></li>
<li><a class="reference internal" href="#using-sqlite3-efficiently">11.13.7. Using <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> efficiently</a><ul>
<li><a class="reference internal" href="#using-shortcut-methods">11.13.7.1. Using shortcut methods</a></li>
<li><a class="reference internal" href="#accessing-columns-by-name-instead-of-by-index">11.13.7.2. Accessing columns by name instead of by index</a></li>
<li><a class="reference internal" href="#using-the-connection-as-a-context-manager">11.13.7.3. Using the connection as a context manager</a></li>
</ul>
</li>
<li><a class="reference internal" href="#common-issues">11.13.8. Common issues</a><ul>
<li><a class="reference internal" href="#multithreading">11.13.8.1. Multithreading</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="dumbdbm.html"
                        title="previous chapter">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="archiving.html"
                        title="next chapter">12. Data Compression and Archiving</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sqlite3.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="archiving.html" title="12. Data Compression and Archiving"
             >next</a> |</li>
        <li class="right" >
          <a href="dumbdbm.html" title="11.12. dumbdbm — Portable DBM implementation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�~��html/library/ssl.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.3. ssl — TLS/SSL wrapper for socket objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.4. signal — Set handlers for asynchronous events" href="signal.html" />
    <link rel="prev" title="17.2. socket — Low-level networking interface" href="socket.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ssl.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="signal.html" title="17.4. signal — Set handlers for asynchronous events"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="socket.html" title="17.2. socket — Low-level networking interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ssl">
<span id="ssl-tls-ssl-wrapper-for-socket-objects"></span><h1>17.3. <a class="reference internal" href="#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> — TLS/SSL wrapper for socket objects<a class="headerlink" href="#module-ssl" title="Permalink to this headline">¶</a></h1>
<span class="target" id="index-0"></span><div class="versionadded" id="index-1">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/ssl.py">Lib/ssl.py</a></p>
<hr class="docutils" />
<p>This module provides access to Transport Layer Security (often known as “Secure
Sockets Layer”) encryption and peer authentication facilities for network
sockets, both client-side and server-side.  This module uses the OpenSSL
library. It is available on all modern Unix systems, Windows, Mac OS X, and
probably additional platforms, as long as OpenSSL is installed on that platform.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.13: </span>Updated to support linking with OpenSSL 1.1.0</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some behavior may be platform dependent, since calls are made to the
operating system socket APIs.  The installed version of OpenSSL may also
cause variations in behavior. For example, TLSv1.1 and TLSv1.2 come with
openssl version 1.0.1.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Don’t use this module without reading the <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a>.  Doing so
may lead to a false sense of security, as the default settings of the
ssl module are not necessarily appropriate for your application.</p>
</div>
<p>This section documents the objects and functions in the <code class="docutils literal notranslate"><span class="pre">ssl</span></code> module; for more
general information about TLS, SSL, and certificates, the reader is referred to
the documents in the “See Also” section at the bottom.</p>
<p>This module provides a class, <code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLSocket</span></code>, which is derived from the
<a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a> type, and provides a socket-like wrapper that also
encrypts and decrypts the data going over the socket with SSL.  It supports
additional methods such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeercert()</span></code>, which retrieves the
certificate of the other side of the connection, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">cipher()</span></code>,which
retrieves the cipher being used for the secure connection.</p>
<p>For more sophisticated applications, the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> class
helps manage settings and certificates, which can then be inherited
by SSL sockets created through the <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.wrap_socket()</span></code></a> method.</p>
<div class="section" id="functions-constants-and-exceptions">
<h2>17.3.1. Functions, Constants, and Exceptions<a class="headerlink" href="#functions-constants-and-exceptions" title="Permalink to this headline">¶</a></h2>
<dl class="exception">
<dt id="ssl.SSLError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLError</code><a class="headerlink" href="#ssl.SSLError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised to signal an error from the underlying SSL implementation (currently
provided by the OpenSSL library).  This signifies some problem in the
higher-level encryption and authentication layer that’s superimposed on the
underlying network connection.  This error is a subtype of
<a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a>, which in turn is a subtype of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.  The
error code and message of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> instances are provided by the
OpenSSL library.</p>
<dl class="attribute">
<dt id="ssl.SSLError.library">
<code class="descname">library</code><a class="headerlink" href="#ssl.SSLError.library" title="Permalink to this definition">¶</a></dt>
<dd><p>A string mnemonic designating the OpenSSL submodule in which the error
occurred, such as <code class="docutils literal notranslate"><span class="pre">SSL</span></code>, <code class="docutils literal notranslate"><span class="pre">PEM</span></code> or <code class="docutils literal notranslate"><span class="pre">X509</span></code>.  The range of possible
values depends on the OpenSSL version.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLError.reason">
<code class="descname">reason</code><a class="headerlink" href="#ssl.SSLError.reason" title="Permalink to this definition">¶</a></dt>
<dd><p>A string mnemonic designating the reason this error occurred, for
example <code class="docutils literal notranslate"><span class="pre">CERTIFICATE_VERIFY_FAILED</span></code>.  The range of possible
values depends on the OpenSSL version.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="ssl.SSLZeroReturnError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLZeroReturnError</code><a class="headerlink" href="#ssl.SSLZeroReturnError" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> raised when trying to read or write and
the SSL connection has been closed cleanly.  Note that this doesn’t
mean that the underlying transport (read TCP) has been closed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ssl.SSLWantReadError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLWantReadError</code><a class="headerlink" href="#ssl.SSLWantReadError" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> raised by a <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking SSL socket</span></a> when trying to read or write data, but more data needs
to be received on the underlying TCP transport before the request can be
fulfilled.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ssl.SSLWantWriteError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLWantWriteError</code><a class="headerlink" href="#ssl.SSLWantWriteError" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> raised by a <a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">non-blocking SSL socket</span></a> when trying to read or write data, but more data needs
to be sent on the underlying TCP transport before the request can be
fulfilled.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ssl.SSLSyscallError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLSyscallError</code><a class="headerlink" href="#ssl.SSLSyscallError" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> raised when a system error was encountered
while trying to fulfill an operation on a SSL socket.  Unfortunately,
there is no easy way to inspect the original errno number.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ssl.SSLEOFError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">SSLEOFError</code><a class="headerlink" href="#ssl.SSLEOFError" title="Permalink to this definition">¶</a></dt>
<dd><p>A subclass of <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a> raised when the SSL connection has been
terminated abruptly.  Generally, you shouldn’t try to reuse the underlying
transport when this error is encountered.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="ssl.CertificateError">
<em class="property">exception </em><code class="descclassname">ssl.</code><code class="descname">CertificateError</code><a class="headerlink" href="#ssl.CertificateError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised to signal an error with a certificate (such as mismatching
hostname).  Certificate errors detected by OpenSSL, though, raise
an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a>.</p>
</dd></dl>

<div class="section" id="socket-creation">
<h3>17.3.1.1. Socket creation<a class="headerlink" href="#socket-creation" title="Permalink to this headline">¶</a></h3>
<p>The following function allows for standalone socket creation.  Starting from
Python 2.7.9, it can be more flexible to use <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.wrap_socket()</span></code></a>
instead.</p>
<dl class="function">
<dt id="ssl.wrap_socket">
<code class="descclassname">ssl.</code><code class="descname">wrap_socket</code><span class="sig-paren">(</span><em>sock</em>, <em>keyfile=None</em>, <em>certfile=None</em>, <em>server_side=False</em>, <em>cert_reqs=CERT_NONE</em>, <em>ssl_version={see docs}</em>, <em>ca_certs=None</em>, <em>do_handshake_on_connect=True</em>, <em>suppress_ragged_eofs=True</em>, <em>ciphers=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.wrap_socket" title="Permalink to this definition">¶</a></dt>
<dd><p>Takes an instance <code class="docutils literal notranslate"><span class="pre">sock</span></code> of <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a>, and returns an instance
of <code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLSocket</span></code>, a subtype of <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a>, which wraps
the underlying socket in an SSL context.  <code class="docutils literal notranslate"><span class="pre">sock</span></code> must be a
<a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> socket; other socket types are unsupported.</p>
<p>For client-side sockets, the context construction is lazy; if the
underlying socket isn’t connected yet, the context construction will be
performed after <code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code> is called on the socket.  For
server-side sockets, if the socket has no remote peer, it is assumed
to be a listening socket, and the server-side SSL wrapping is
automatically performed on client connections accepted via the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code> method.  <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a> may raise <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">keyfile</span></code> and <code class="docutils literal notranslate"><span class="pre">certfile</span></code> parameters specify optional files which
contain a certificate to be used to identify the local side of the
connection.  See the discussion of <a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more
information on how the certificate is stored in the <code class="docutils literal notranslate"><span class="pre">certfile</span></code>.</p>
<p>The parameter <code class="docutils literal notranslate"><span class="pre">server_side</span></code> is a boolean which identifies whether
server-side or client-side behavior is desired from this socket.</p>
<p>The parameter <code class="docutils literal notranslate"><span class="pre">cert_reqs</span></code> specifies whether a certificate is required from
the other side of the connection, and whether it will be validated if
provided.  It must be one of the three values <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a>
(certificates ignored), <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_OPTIONAL</span></code></a> (not required, but validated
if provided), or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a> (required and validated).  If the
value of this parameter is not <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a>, then the <code class="docutils literal notranslate"><span class="pre">ca_certs</span></code>
parameter must point to a file of CA certificates.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">ca_certs</span></code> file contains a set of concatenated “certification
authority” certificates, which are used to validate certificates passed from
the other end of the connection.  See the discussion of
<a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more information about how to arrange the
certificates in this file.</p>
<p>The parameter <code class="docutils literal notranslate"><span class="pre">ssl_version</span></code> specifies which version of the SSL protocol to
use.  Typically, the server chooses a particular protocol version, and the
client must adapt to the server’s choice.  Most of the versions are not
interoperable with the other versions.  If not specified, the default is
<a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>; it provides the most compatibility with other
versions.</p>
<p>Here’s a table showing which versions in a client (down the side) can connect
to which versions in a server (along the top):</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="11%" />
<col width="11%" />
<col width="12%" />
<col width="11%" />
<col width="13%" />
<col width="13%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><em>client</em> / <strong>server</strong></td>
<td><strong>SSLv2</strong></td>
<td><strong>SSLv3</strong></td>
<td><strong>SSLv23</strong></td>
<td><strong>TLSv1</strong></td>
<td><strong>TLSv1.1</strong></td>
<td><strong>TLSv1.2</strong></td>
</tr>
<tr class="row-even"><td><em>SSLv2</em></td>
<td>yes</td>
<td>no</td>
<td>yes</td>
<td>no</td>
<td>no</td>
<td>no</td>
</tr>
<tr class="row-odd"><td><em>SSLv3</em></td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>no</td>
<td>no</td>
<td>no</td>
</tr>
<tr class="row-even"><td><em>SSLv23</em> <a class="footnote-reference" href="#id2" id="id1">[1]</a></td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
<tr class="row-odd"><td><em>TLSv1</em></td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>no</td>
<td>no</td>
</tr>
<tr class="row-even"><td><em>TLSv1.1</em></td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>no</td>
<td>yes</td>
<td>no</td>
</tr>
<tr class="row-odd"><td><em>TLSv1.2</em></td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>no</td>
<td>no</td>
<td>yes</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>TLS 1.3 protocol will be available with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a> in
OpenSSL &gt;= 1.1.1. There is no dedicated PROTOCOL constant for just
TLS 1.3.</td></tr>
</tbody>
</table>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Which connections succeed will vary depending on the version of
OpenSSL.  For example, before OpenSSL 1.0.0, an SSLv23 client
would always attempt SSLv2 connections.</p>
</div>
<p>The <em>ciphers</em> parameter sets the available ciphers for this SSL object.
It should be a string in the <a class="reference external" href="https://www.openssl.org/docs/manmaster/man1/ciphers.html">OpenSSL cipher list format</a>.</p>
<p>The parameter <code class="docutils literal notranslate"><span class="pre">do_handshake_on_connect</span></code> specifies whether to do the SSL
handshake automatically after doing a <code class="xref py py-meth docutils literal notranslate"><span class="pre">socket.connect()</span></code>, or whether the
application program will call it explicitly, by invoking the
<a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.do_handshake()</span></code></a> method.  Calling
<a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.do_handshake()</span></code></a> explicitly gives the program control over the
blocking behavior of the socket I/O involved in the handshake.</p>
<p>The parameter <code class="docutils literal notranslate"><span class="pre">suppress_ragged_eofs</span></code> specifies how the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.read()</span></code> method should signal unexpected EOF from the other end
of the connection.  If specified as <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> (the default), it returns a
normal EOF (an empty bytes object) in response to unexpected EOF errors
raised from the underlying socket; if <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, it will raise the
exceptions back to the caller.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>New optional argument <em>ciphers</em>.</p>
</div>
</dd></dl>

</div>
<div class="section" id="context-creation">
<h3>17.3.1.2. Context creation<a class="headerlink" href="#context-creation" title="Permalink to this headline">¶</a></h3>
<p>A convenience function helps create <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> objects for common
purposes.</p>
<dl class="function">
<dt id="ssl.create_default_context">
<code class="descclassname">ssl.</code><code class="descname">create_default_context</code><span class="sig-paren">(</span><em>purpose=Purpose.SERVER_AUTH</em>, <em>cafile=None</em>, <em>capath=None</em>, <em>cadata=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.create_default_context" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> object with default settings for
the given <em>purpose</em>.  The settings are chosen by the <a class="reference internal" href="#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module,
and usually represent a higher security level than when calling the
<a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> constructor directly.</p>
<p><em>cafile</em>, <em>capath</em>, <em>cadata</em> represent optional CA certificates to
trust for certificate verification, as in
<a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_verify_locations()</span></code></a>.  If all three are
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, this function can choose to trust the system’s default
CA certificates instead.</p>
<p>The settings are: <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>, <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv2</span></code></a>, and
<a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code></a> with high encryption cipher suites without RC4 and
without unauthenticated cipher suites. Passing <a class="reference internal" href="#ssl.Purpose.SERVER_AUTH" title="ssl.Purpose.SERVER_AUTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">SERVER_AUTH</span></code></a>
as <em>purpose</em> sets <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-data docutils literal notranslate"><span class="pre">verify_mode</span></code></a> to <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>
and either loads CA certificates (when at least one of <em>cafile</em>, <em>capath</em> or
<em>cadata</em> is given) or uses <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_default_certs()</span></code></a> to load
default CA certificates.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The protocol, options, cipher and other settings may change to more
restrictive values anytime without prior deprecation.  The values
represent a fair balance between compatibility and security.</p>
<p class="last">If your application needs specific settings, you should create a
<a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> and apply the settings yourself.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>If you find that when certain older clients or servers attempt to connect
with a <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> created by this function that they get an error
stating “Protocol or cipher suite mismatch”, it may be that they only
support SSL3.0 which this function excludes using the
<a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code></a>. SSL3.0 is widely considered to be <a class="reference external" href="https://en.wikipedia.org/wiki/POODLE">completely broken</a>. If you still wish to continue to
use this function but still allow SSL 3.0 connections you can re-enable
them using:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ctx</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span><span class="n">Purpose</span><span class="o">.</span><span class="n">CLIENT_AUTH</span><span class="p">)</span>
<span class="n">ctx</span><span class="o">.</span><span class="n">options</span> <span class="o">&amp;=</span> <span class="o">~</span><span class="n">ssl</span><span class="o">.</span><span class="n">OP_NO_SSLv3</span>
</pre></div>
</div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.10: </span>RC4 was dropped from the default cipher string.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.13: </span>ChaCha20/Poly1305 was added to the default cipher string.</p>
<p>3DES was dropped from the default cipher string.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl._https_verify_certificates">
<code class="descclassname">ssl.</code><code class="descname">_https_verify_certificates</code><span class="sig-paren">(</span><em>enable=True</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl._https_verify_certificates" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies whether or not server certificates are verified when creating
client HTTPS connections without specifying a particular SSL context.</p>
<p>Starting with Python 2.7.9, <a class="reference internal" href="httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> and modules which use it, such as
<a class="reference internal" href="urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> and <a class="reference internal" href="xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a>, default to verifying remote server
certificates received when establishing client HTTPS connections. This
default verification checks that the certificate is signed by a Certificate
Authority in the system trust store and that the Common Name (or Subject
Alternate Name) on the presented certificate matches the requested host.</p>
<p>Setting <em>enable</em> to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> ensures this default behaviour is in
effect.</p>
<p>Setting <em>enable</em> to <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> reverts the default HTTPS certificate
handling to that of Python 2.7.8 and earlier, allowing connections to
servers using self-signed certificates, servers using certificates signed
by a Certicate Authority not present in the system trust store, and servers
where the hostname does not match the presented server certificate.</p>
<p>The leading underscore on this function denotes that it intentionally does
not exist in any implementation of Python 3 and may not be present in all
Python 2.7 implementations. The portable approach to bypassing certificate
checks or the system trust store when necessary is for tools to enable that
on a case-by-case basis by explicitly passing in a suitably configured SSL
context, rather than reverting the default behaviour of the standard library
client modules.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.12.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<ul class="last simple">
<li><a class="reference external" href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9365">CVE-2014-9365</a>
– HTTPS man-in-the-middle attack against Python clients using default settings</li>
<li><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0476"><strong>PEP 476</strong></a> – Enabling certificate verification by default for HTTPS</li>
<li><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0493"><strong>PEP 493</strong></a> – HTTPS verification migration tools for Python 2.7</li>
</ul>
</div>
</dd></dl>

</div>
<div class="section" id="random-generation">
<h3>17.3.1.3. Random generation<a class="headerlink" href="#random-generation" title="Permalink to this headline">¶</a></h3>
<blockquote>
<div><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has deprecated <code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.RAND_pseudo_bytes()</span></code>, use
<code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.RAND_bytes()</span></code> instead.</p>
</div>
</div></blockquote>
<dl class="function">
<dt id="ssl.RAND_status">
<code class="descclassname">ssl.</code><code class="descname">RAND_status</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.RAND_status" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the SSL pseudo-random number generator has been seeded
with ‘enough’ randomness, and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.  You can use
<a class="reference internal" href="#ssl.RAND_egd" title="ssl.RAND_egd"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.RAND_egd()</span></code></a> and <a class="reference internal" href="#ssl.RAND_add" title="ssl.RAND_add"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.RAND_add()</span></code></a> to increase the randomness of
the pseudo-random number generator.</p>
</dd></dl>

<dl class="function">
<dt id="ssl.RAND_egd">
<code class="descclassname">ssl.</code><code class="descname">RAND_egd</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.RAND_egd" title="Permalink to this definition">¶</a></dt>
<dd><p>If you are running an entropy-gathering daemon (EGD) somewhere, and <em>path</em>
is the pathname of a socket connection open to it, this will read 256 bytes
of randomness from the socket, and add it to the SSL pseudo-random number
generator to increase the security of generated secret keys.  This is
typically only necessary on systems without better sources of randomness.</p>
<p>See <a class="reference external" href="http://egd.sourceforge.net/">http://egd.sourceforge.net/</a> or <a class="reference external" href="http://prngd.sourceforge.net/">http://prngd.sourceforge.net/</a> for sources
of entropy-gathering daemons.</p>
<p>Availability: not available with LibreSSL and OpenSSL &gt; 1.1.0</p>
</dd></dl>

<dl class="function">
<dt id="ssl.RAND_add">
<code class="descclassname">ssl.</code><code class="descname">RAND_add</code><span class="sig-paren">(</span><em>bytes</em>, <em>entropy</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.RAND_add" title="Permalink to this definition">¶</a></dt>
<dd><p>Mix the given <em>bytes</em> into the SSL pseudo-random number generator.  The
parameter <em>entropy</em> (a float) is a lower bound on the entropy contained in
string (so you can always use <code class="xref py py-const docutils literal notranslate"><span class="pre">0.0</span></code>).  See <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1750.html"><strong>RFC 1750</strong></a> for more
information on sources of entropy.</p>
</dd></dl>

</div>
<div class="section" id="certificate-handling">
<h3>17.3.1.4. Certificate handling<a class="headerlink" href="#certificate-handling" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="ssl.match_hostname">
<code class="descclassname">ssl.</code><code class="descname">match_hostname</code><span class="sig-paren">(</span><em>cert</em>, <em>hostname</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.match_hostname" title="Permalink to this definition">¶</a></dt>
<dd><p>Verify that <em>cert</em> (in decoded format as returned by
<a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.getpeercert()</span></code></a>) matches the given <em>hostname</em>.  The rules
applied are those for checking the identity of HTTPS servers as outlined
in <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2818.html"><strong>RFC 2818</strong></a> and <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc6125.html"><strong>RFC 6125</strong></a>, except that IP addresses are not currently
supported. In addition to HTTPS, this function should be suitable for
checking the identity of servers in various SSL-based protocols such as
FTPS, IMAPS, POPS and others.</p>
<p><a class="reference internal" href="#ssl.CertificateError" title="ssl.CertificateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CertificateError</span></code></a> is raised on failure. On success, the function
returns nothing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cert</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;subject&#39;</span><span class="p">:</span> <span class="p">(((</span><span class="s1">&#39;commonName&#39;</span><span class="p">,</span> <span class="s1">&#39;example.com&#39;</span><span class="p">),),)}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">match_hostname</span><span class="p">(</span><span class="n">cert</span><span class="p">,</span> <span class="s2">&quot;example.com&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">match_hostname</span><span class="p">(</span><span class="n">cert</span><span class="p">,</span> <span class="s2">&quot;example.org&quot;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;/home/py3k/Lib/ssl.py&quot;</span>, line <span class="m">130</span>, in <span class="n">match_hostname</span>
<span class="gr">ssl.CertificateError</span>: <span class="n">hostname &#39;example.org&#39; doesn&#39;t match &#39;example.com&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl.cert_time_to_seconds">
<code class="descclassname">ssl.</code><code class="descname">cert_time_to_seconds</code><span class="sig-paren">(</span><em>cert_time</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.cert_time_to_seconds" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the time in seconds since the Epoch, given the <code class="docutils literal notranslate"><span class="pre">cert_time</span></code>
string representing the “notBefore” or “notAfter” date from a
certificate in <code class="docutils literal notranslate"><span class="pre">&quot;%b</span> <span class="pre">%d</span> <span class="pre">%H:%M:%S</span> <span class="pre">%Y</span> <span class="pre">%Z&quot;</span></code> strptime format (C
locale).</p>
<p>Here’s an example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">ssl</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timestamp</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">cert_time_to_seconds</span><span class="p">(</span><span class="s2">&quot;Jan  5 09:34:43 2018 GMT&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timestamp</span>
<span class="go">1515144883</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">utcfromtimestamp</span><span class="p">(</span><span class="n">timestamp</span><span class="p">))</span>
<span class="go">2018-01-05 09:34:43</span>
</pre></div>
</div>
<p>“notBefore” or “notAfter” dates must use GMT (<span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc5280.html"><strong>RFC 5280</strong></a>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>Interpret the input time as a time in UTC as specified by ‘GMT’
timezone in the input string. Local timezone was used
previously. Return an integer (no fractions of a second in the
input format)</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl.get_server_certificate">
<code class="descclassname">ssl.</code><code class="descname">get_server_certificate</code><span class="sig-paren">(</span><em>addr</em>, <em>ssl_version=PROTOCOL_SSLv23</em>, <em>ca_certs=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.get_server_certificate" title="Permalink to this definition">¶</a></dt>
<dd><p>Given the address <code class="docutils literal notranslate"><span class="pre">addr</span></code> of an SSL-protected server, as a (<em>hostname</em>,
<em>port-number</em>) pair, fetches the server’s certificate, and returns it as a
PEM-encoded string.  If <code class="docutils literal notranslate"><span class="pre">ssl_version</span></code> is specified, uses that version of
the SSL protocol to attempt to connect to the server.  If <code class="docutils literal notranslate"><span class="pre">ca_certs</span></code> is
specified, it should be a file containing a list of root certificates, the
same format as used for the same parameter in <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.  The call
will attempt to validate the server certificate against that set of root
certificates, and will fail if the validation attempt fails.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>This function is now IPv6-compatible, and the default <em>ssl_version</em> is
changed from <a class="reference internal" href="#ssl.PROTOCOL_SSLv3" title="ssl.PROTOCOL_SSLv3"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv3</span></code></a> to <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a> for
maximum compatibility with modern servers.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl.DER_cert_to_PEM_cert">
<code class="descclassname">ssl.</code><code class="descname">DER_cert_to_PEM_cert</code><span class="sig-paren">(</span><em>DER_cert_bytes</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.DER_cert_to_PEM_cert" title="Permalink to this definition">¶</a></dt>
<dd><p>Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded
string version of the same certificate.</p>
</dd></dl>

<dl class="function">
<dt id="ssl.PEM_cert_to_DER_cert">
<code class="descclassname">ssl.</code><code class="descname">PEM_cert_to_DER_cert</code><span class="sig-paren">(</span><em>PEM_cert_string</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.PEM_cert_to_DER_cert" title="Permalink to this definition">¶</a></dt>
<dd><p>Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of
bytes for that same certificate.</p>
</dd></dl>

<dl class="function">
<dt id="ssl.get_default_verify_paths">
<code class="descclassname">ssl.</code><code class="descname">get_default_verify_paths</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.get_default_verify_paths" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a named tuple with paths to OpenSSL’s default cafile and capath.
The paths are the same as used by
<a class="reference internal" href="#ssl.SSLContext.set_default_verify_paths" title="ssl.SSLContext.set_default_verify_paths"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_default_verify_paths()</span></code></a>. The return value is a
<a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named tuple</span></a> <code class="docutils literal notranslate"><span class="pre">DefaultVerifyPaths</span></code>:</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">cafile</span></code> - resolved path to cafile or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the file doesn’t exist,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">capath</span></code> - resolved path to capath or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the directory doesn’t exist,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_cafile_env</span></code> - OpenSSL’s environment key that points to a cafile,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_cafile</span></code> - hard coded path to a cafile,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_capath_env</span></code> - OpenSSL’s environment key that points to a capath,</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_capath</span></code> - hard coded path to a capath directory</li>
</ul>
<p>Availability: LibreSSL ignores the environment vars
<code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_cafile_env</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">openssl_capath_env</span></code></p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl.enum_certificates">
<code class="descclassname">ssl.</code><code class="descname">enum_certificates</code><span class="sig-paren">(</span><em>store_name</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.enum_certificates" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve certificates from Windows’ system cert store. <em>store_name</em> may be
one of <code class="docutils literal notranslate"><span class="pre">CA</span></code>, <code class="docutils literal notranslate"><span class="pre">ROOT</span></code> or <code class="docutils literal notranslate"><span class="pre">MY</span></code>. Windows may provide additional cert
stores, too.</p>
<p>The function returns a list of (cert_bytes, encoding_type, trust) tuples.
The encoding_type specifies the encoding of cert_bytes. It is either
<code class="xref py py-const docutils literal notranslate"><span class="pre">x509_asn</span></code> for X.509 ASN.1 data or <code class="xref py py-const docutils literal notranslate"><span class="pre">pkcs_7_asn</span></code> for
PKCS#7 ASN.1 data. Trust specifies the purpose of the certificate as a set
of OIDS or exactly <code class="docutils literal notranslate"><span class="pre">True</span></code> if the certificate is trustworthy for all
purposes.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">enum_certificates</span><span class="p">(</span><span class="s2">&quot;CA&quot;</span><span class="p">)</span>
<span class="go">[(b&#39;data...&#39;, &#39;x509_asn&#39;, {&#39;1.3.6.1.5.5.7.3.1&#39;, &#39;1.3.6.1.5.5.7.3.2&#39;}),</span>
<span class="go"> (b&#39;data...&#39;, &#39;x509_asn&#39;, True)]</span>
</pre></div>
</div>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="ssl.enum_crls">
<code class="descclassname">ssl.</code><code class="descname">enum_crls</code><span class="sig-paren">(</span><em>store_name</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.enum_crls" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve CRLs from Windows’ system cert store. <em>store_name</em> may be
one of <code class="docutils literal notranslate"><span class="pre">CA</span></code>, <code class="docutils literal notranslate"><span class="pre">ROOT</span></code> or <code class="docutils literal notranslate"><span class="pre">MY</span></code>. Windows may provide additional cert
stores, too.</p>
<p>The function returns a list of (cert_bytes, encoding_type, trust) tuples.
The encoding_type specifies the encoding of cert_bytes. It is either
<code class="xref py py-const docutils literal notranslate"><span class="pre">x509_asn</span></code> for X.509 ASN.1 data or <code class="xref py py-const docutils literal notranslate"><span class="pre">pkcs_7_asn</span></code> for
PKCS#7 ASN.1 data.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="constants">
<h3>17.3.1.5. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h3>
<dl class="data">
<dt id="ssl.CERT_NONE">
<code class="descclassname">ssl.</code><code class="descname">CERT_NONE</code><a class="headerlink" href="#ssl.CERT_NONE" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_mode</span></code></a>, or the <code class="docutils literal notranslate"><span class="pre">cert_reqs</span></code>
parameter to <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.  In this mode (the default), no
certificates will be required from the other side of the socket connection.
If a certificate is received from the other end, no attempt to validate it
is made.</p>
<p>See the discussion of <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a> below.</p>
</dd></dl>

<dl class="data">
<dt id="ssl.CERT_OPTIONAL">
<code class="descclassname">ssl.</code><code class="descname">CERT_OPTIONAL</code><a class="headerlink" href="#ssl.CERT_OPTIONAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_mode</span></code></a>, or the <code class="docutils literal notranslate"><span class="pre">cert_reqs</span></code>
parameter to <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.  In this mode no certificates will be
required from the other side of the socket connection; but if they
are provided, validation will be attempted and an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLError</span></code></a>
will be raised on failure.</p>
<p>Use of this setting requires a valid set of CA certificates to
be passed, either to <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_verify_locations()</span></code></a> or as a
value of the <code class="docutils literal notranslate"><span class="pre">ca_certs</span></code> parameter to <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="ssl.CERT_REQUIRED">
<code class="descclassname">ssl.</code><code class="descname">CERT_REQUIRED</code><a class="headerlink" href="#ssl.CERT_REQUIRED" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_mode</span></code></a>, or the <code class="docutils literal notranslate"><span class="pre">cert_reqs</span></code>
parameter to <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.  In this mode, certificates are
required from the other side of the socket connection; an <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLError</span></code></a>
will be raised if no certificate is provided, or if its validation fails.</p>
<p>Use of this setting requires a valid set of CA certificates to
be passed, either to <a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_verify_locations()</span></code></a> or as a
value of the <code class="docutils literal notranslate"><span class="pre">ca_certs</span></code> parameter to <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="ssl.VERIFY_DEFAULT">
<code class="descclassname">ssl.</code><code class="descname">VERIFY_DEFAULT</code><a class="headerlink" href="#ssl.VERIFY_DEFAULT" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a>. In this mode, certificate
revocation lists (CRLs) are not checked. By default OpenSSL does neither
require nor verify CRLs.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.VERIFY_CRL_CHECK_LEAF">
<code class="descclassname">ssl.</code><code class="descname">VERIFY_CRL_CHECK_LEAF</code><a class="headerlink" href="#ssl.VERIFY_CRL_CHECK_LEAF" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a>. In this mode, only the
peer cert is check but non of the intermediate CA certificates. The mode
requires a valid CRL that is signed by the peer cert’s issuer (its direct
ancestor CA). If no proper has been loaded
<a class="reference internal" href="#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.load_verify_locations</span></code></a>, validation will fail.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.VERIFY_CRL_CHECK_CHAIN">
<code class="descclassname">ssl.</code><code class="descname">VERIFY_CRL_CHECK_CHAIN</code><a class="headerlink" href="#ssl.VERIFY_CRL_CHECK_CHAIN" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a>. In this mode, CRLs of
all certificates in the peer cert chain are checked.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.VERIFY_X509_STRICT">
<code class="descclassname">ssl.</code><code class="descname">VERIFY_X509_STRICT</code><a class="headerlink" href="#ssl.VERIFY_X509_STRICT" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a> to disable workarounds
for broken X.509 certificates.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.VERIFY_X509_TRUSTED_FIRST">
<code class="descclassname">ssl.</code><code class="descname">VERIFY_X509_TRUSTED_FIRST</code><a class="headerlink" href="#ssl.VERIFY_X509_TRUSTED_FIRST" title="Permalink to this definition">¶</a></dt>
<dd><p>Possible value for <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a>. It instructs OpenSSL to
prefer trusted certificates when building the trust chain to validate a
certificate. This flag is enabled by default.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.10.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_TLS">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_TLS</code><a class="headerlink" href="#ssl.PROTOCOL_TLS" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects the highest protocol version that both the client and server support.
Despite the name, this option can select “TLS” protocols as well as “SSL”.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.13.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_SSLv23">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_SSLv23</code><a class="headerlink" href="#ssl.PROTOCOL_SSLv23" title="Permalink to this definition">¶</a></dt>
<dd><p>Alias for <code class="docutils literal notranslate"><span class="pre">PROTOCOL_TLS</span></code>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>Use <code class="docutils literal notranslate"><span class="pre">PROTOCOL_TLS</span></code> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_SSLv2">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_SSLv2</code><a class="headerlink" href="#ssl.PROTOCOL_SSLv2" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects SSL version 2 as the channel encryption protocol.</p>
<p>This protocol is not available if OpenSSL is compiled with the
<code class="docutils literal notranslate"><span class="pre">OPENSSL_NO_SSL2</span></code> flag.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">SSL version 2 is insecure.  Its use is highly discouraged.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has removed support for SSLv2.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_SSLv3">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_SSLv3</code><a class="headerlink" href="#ssl.PROTOCOL_SSLv3" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects SSL version 3 as the channel encryption protocol.</p>
<p>This protocol is not be available if OpenSSL is compiled with the
<code class="docutils literal notranslate"><span class="pre">OPENSSL_NO_SSLv3</span></code> flag.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">SSL version 3 is insecure.  Its use is highly discouraged.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has deprecated all version specific protocols. Use the default
protocol with flags like <code class="docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_TLSv1">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_TLSv1</code><a class="headerlink" href="#ssl.PROTOCOL_TLSv1" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects TLS version 1.0 as the channel encryption protocol.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has deprecated all version specific protocols. Use the default
protocol with flags like <code class="docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_TLSv1_1">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_TLSv1_1</code><a class="headerlink" href="#ssl.PROTOCOL_TLSv1_1" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects TLS version 1.1 as the channel encryption protocol.
Available only with openssl version 1.0.1+.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has deprecated all version specific protocols. Use the default
protocol with flags like <code class="docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.PROTOCOL_TLSv1_2">
<code class="descclassname">ssl.</code><code class="descname">PROTOCOL_TLSv1_2</code><a class="headerlink" href="#ssl.PROTOCOL_TLSv1_2" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects TLS version 1.2 as the channel encryption protocol. This is the
most modern version, and probably the best choice for maximum protection,
if both sides can speak it.  Available only with openssl version 1.0.1+.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7.13: </span>OpenSSL has deprecated all version specific protocols. Use the default
protocol with flags like <code class="docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_ALL">
<code class="descclassname">ssl.</code><code class="descname">OP_ALL</code><a class="headerlink" href="#ssl.OP_ALL" title="Permalink to this definition">¶</a></dt>
<dd><p>Enables workarounds for various bugs present in other SSL implementations.
This option is set by default.  It does not necessarily set the same
flags as OpenSSL’s <code class="docutils literal notranslate"><span class="pre">SSL_OP_ALL</span></code> constant.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_SSLv2">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_SSLv2</code><a class="headerlink" href="#ssl.OP_NO_SSLv2" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents an SSLv2 connection.  This option is only applicable in
conjunction with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>.  It prevents the peers from
choosing SSLv2 as the protocol version.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_SSLv3">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_SSLv3</code><a class="headerlink" href="#ssl.OP_NO_SSLv3" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents an SSLv3 connection.  This option is only applicable in
conjunction with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>.  It prevents the peers from
choosing SSLv3 as the protocol version.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_TLSv1">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_TLSv1</code><a class="headerlink" href="#ssl.OP_NO_TLSv1" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents a TLSv1 connection.  This option is only applicable in
conjunction with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>.  It prevents the peers from
choosing TLSv1 as the protocol version.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_TLSv1_1">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_TLSv1_1</code><a class="headerlink" href="#ssl.OP_NO_TLSv1_1" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents a TLSv1.1 connection. This option is only applicable in conjunction
with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>. It prevents the peers from choosing TLSv1.1 as
the protocol version. Available only with openssl version 1.0.1+.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_TLSv1_2">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_TLSv1_2</code><a class="headerlink" href="#ssl.OP_NO_TLSv1_2" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents a TLSv1.2 connection. This option is only applicable in conjunction
with <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a>. It prevents the peers from choosing TLSv1.2 as
the protocol version. Available only with openssl version 1.0.1+.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_TLSv1_3">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_TLSv1_3</code><a class="headerlink" href="#ssl.OP_NO_TLSv1_3" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents a TLSv1.3 connection. This option is only applicable in conjunction
with <a class="reference internal" href="#ssl.PROTOCOL_TLS" title="ssl.PROTOCOL_TLS"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_TLS</span></code></a>. It prevents the peers from choosing TLSv1.3 as
the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later.
When Python has been compiled against an older version of OpenSSL, the
flag defaults to <em>0</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.15.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_CIPHER_SERVER_PREFERENCE">
<code class="descclassname">ssl.</code><code class="descname">OP_CIPHER_SERVER_PREFERENCE</code><a class="headerlink" href="#ssl.OP_CIPHER_SERVER_PREFERENCE" title="Permalink to this definition">¶</a></dt>
<dd><p>Use the server’s cipher ordering preference, rather than the client’s.
This option has no effect on client sockets and SSLv2 server sockets.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_SINGLE_DH_USE">
<code class="descclassname">ssl.</code><code class="descname">OP_SINGLE_DH_USE</code><a class="headerlink" href="#ssl.OP_SINGLE_DH_USE" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents re-use of the same DH key for distinct SSL sessions.  This
improves forward secrecy but requires more computational resources.
This option only applies to server sockets.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_SINGLE_ECDH_USE">
<code class="descclassname">ssl.</code><code class="descname">OP_SINGLE_ECDH_USE</code><a class="headerlink" href="#ssl.OP_SINGLE_ECDH_USE" title="Permalink to this definition">¶</a></dt>
<dd><p>Prevents re-use of the same ECDH key for distinct SSL sessions.  This
improves forward secrecy but requires more computational resources.
This option only applies to server sockets.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_ENABLE_MIDDLEBOX_COMPAT">
<code class="descclassname">ssl.</code><code class="descname">OP_ENABLE_MIDDLEBOX_COMPAT</code><a class="headerlink" href="#ssl.OP_ENABLE_MIDDLEBOX_COMPAT" title="Permalink to this definition">¶</a></dt>
<dd><p>Send dummy Change Cipher Spec (CCS) messages in TLS 1.3 handshake to make
a TLS 1.3 connection look more like a TLS 1.2 connection.</p>
<p>This option is only available with OpenSSL 1.1.1 and later.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.16.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OP_NO_COMPRESSION">
<code class="descclassname">ssl.</code><code class="descname">OP_NO_COMPRESSION</code><a class="headerlink" href="#ssl.OP_NO_COMPRESSION" title="Permalink to this definition">¶</a></dt>
<dd><p>Disable compression on the SSL channel.  This is useful if the application
protocol supports its own compression scheme.</p>
<p>This option is only available with OpenSSL 1.0.0 and later.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.HAS_ALPN">
<code class="descclassname">ssl.</code><code class="descname">HAS_ALPN</code><a class="headerlink" href="#ssl.HAS_ALPN" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the OpenSSL library has built-in support for the <em>Application-Layer
Protocol Negotiation</em> TLS extension as described in <span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7301.html"><strong>RFC 7301</strong></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.10.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.HAS_ECDH">
<code class="descclassname">ssl.</code><code class="descname">HAS_ECDH</code><a class="headerlink" href="#ssl.HAS_ECDH" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the OpenSSL library has built-in support for Elliptic Curve-based
Diffie-Hellman key exchange.  This should be true unless the feature was
explicitly disabled by the distributor.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.HAS_SNI">
<code class="descclassname">ssl.</code><code class="descname">HAS_SNI</code><a class="headerlink" href="#ssl.HAS_SNI" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the OpenSSL library has built-in support for the <em>Server Name
Indication</em> extension (as defined in <span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4366.html"><strong>RFC 4366</strong></a>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.HAS_NPN">
<code class="descclassname">ssl.</code><code class="descname">HAS_NPN</code><a class="headerlink" href="#ssl.HAS_NPN" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the OpenSSL library has built-in support for <em>Next Protocol
Negotiation</em> as described in the <a class="reference external" href="https://tools.ietf.org/html/draft-agl-tls-nextprotoneg">NPN draft specification</a>. When true,
you can use the <a class="reference internal" href="#ssl.SSLContext.set_npn_protocols" title="ssl.SSLContext.set_npn_protocols"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_npn_protocols()</span></code></a> method to advertise
which protocols you want to support.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.HAS_TLSv1_3">
<code class="descclassname">ssl.</code><code class="descname">HAS_TLSv1_3</code><a class="headerlink" href="#ssl.HAS_TLSv1_3" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether the OpenSSL library has built-in support for the TLS 1.3 protocol.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.15.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.CHANNEL_BINDING_TYPES">
<code class="descclassname">ssl.</code><code class="descname">CHANNEL_BINDING_TYPES</code><a class="headerlink" href="#ssl.CHANNEL_BINDING_TYPES" title="Permalink to this definition">¶</a></dt>
<dd><p>List of supported TLS channel binding types.  Strings in this list
can be used as arguments to <a class="reference internal" href="#ssl.SSLSocket.get_channel_binding" title="ssl.SSLSocket.get_channel_binding"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.get_channel_binding()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OPENSSL_VERSION">
<code class="descclassname">ssl.</code><code class="descname">OPENSSL_VERSION</code><a class="headerlink" href="#ssl.OPENSSL_VERSION" title="Permalink to this definition">¶</a></dt>
<dd><p>The version string of the OpenSSL library loaded by the interpreter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">OPENSSL_VERSION</span>
<span class="go">&#39;OpenSSL 0.9.8k 25 Mar 2009&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OPENSSL_VERSION_INFO">
<code class="descclassname">ssl.</code><code class="descname">OPENSSL_VERSION_INFO</code><a class="headerlink" href="#ssl.OPENSSL_VERSION_INFO" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of five integers representing version information about the
OpenSSL library:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">OPENSSL_VERSION_INFO</span>
<span class="go">(0, 9, 8, 11, 15)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.OPENSSL_VERSION_NUMBER">
<code class="descclassname">ssl.</code><code class="descname">OPENSSL_VERSION_NUMBER</code><a class="headerlink" href="#ssl.OPENSSL_VERSION_NUMBER" title="Permalink to this definition">¶</a></dt>
<dd><p>The raw version number of the OpenSSL library, as a single integer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ssl</span><span class="o">.</span><span class="n">OPENSSL_VERSION_NUMBER</span>
<span class="go">9470143L</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hex</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">OPENSSL_VERSION_NUMBER</span><span class="p">)</span>
<span class="go">&#39;0x9080bfL&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE">
<code class="descclassname">ssl.</code><code class="descname">ALERT_DESCRIPTION_HANDSHAKE_FAILURE</code><a class="headerlink" href="#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE" title="Permalink to this definition">¶</a></dt>
<dt id="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR">
<code class="descclassname">ssl.</code><code class="descname">ALERT_DESCRIPTION_INTERNAL_ERROR</code><a class="headerlink" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">ALERT_DESCRIPTION_*</code></dt>
<dd><p>Alert Descriptions from <span class="target" id="index-10"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc5246.html"><strong>RFC 5246</strong></a> and others. The <a class="reference external" href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6">IANA TLS Alert Registry</a>
contains this list and references to the RFCs where their meaning is defined.</p>
<p>Used as the return value of the callback function in
<a class="reference internal" href="#ssl.SSLContext.set_servername_callback" title="ssl.SSLContext.set_servername_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_servername_callback()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.Purpose.SERVER_AUTH">
<code class="descclassname">Purpose.</code><code class="descname">SERVER_AUTH</code><a class="headerlink" href="#ssl.Purpose.SERVER_AUTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Option for <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_default_context()</span></code></a> and
<a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_default_certs()</span></code></a>.  This value indicates that the
context may be used to authenticate Web servers (therefore, it will
be used to create client-side sockets).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="ssl.Purpose.CLIENT_AUTH">
<code class="descclassname">Purpose.</code><code class="descname">CLIENT_AUTH</code><a class="headerlink" href="#ssl.Purpose.CLIENT_AUTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Option for <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_default_context()</span></code></a> and
<a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_default_certs()</span></code></a>.  This value indicates that the
context may be used to authenticate Web clients (therefore, it will
be used to create server-side sockets).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="ssl-sockets">
<h2>17.3.2. SSL Sockets<a class="headerlink" href="#ssl-sockets" title="Permalink to this headline">¶</a></h2>
<p>SSL sockets provide the following methods of <a class="reference internal" href="socket.html#socket-objects"><span class="std std-ref">Socket Objects</span></a>:</p>
<ul class="simple">
<li><a class="reference internal" href="socket.html#socket.socket.accept" title="socket.socket.accept"><code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.bind" title="socket.socket.bind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bind()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.close" title="socket.socket.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.connect" title="socket.socket.connect"><code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.fileno" title="socket.socket.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.getpeername" title="socket.socket.getpeername"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeername()</span></code></a>, <a class="reference internal" href="socket.html#socket.socket.getsockname" title="socket.socket.getsockname"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getsockname()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.getsockopt" title="socket.socket.getsockopt"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getsockopt()</span></code></a>, <a class="reference internal" href="socket.html#socket.socket.setsockopt" title="socket.socket.setsockopt"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setsockopt()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.gettimeout" title="socket.socket.gettimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettimeout()</span></code></a>, <a class="reference internal" href="socket.html#socket.socket.settimeout" title="socket.socket.settimeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">settimeout()</span></code></a>,
<a class="reference internal" href="socket.html#socket.socket.setblocking" title="socket.socket.setblocking"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setblocking()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.listen" title="socket.socket.listen"><code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a></li>
<li><a class="reference internal" href="socket.html#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a>, <a class="reference internal" href="socket.html#socket.socket.recv_into" title="socket.socket.recv_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv_into()</span></code></a>
(but passing a non-zero <code class="docutils literal notranslate"><span class="pre">flags</span></code> argument is not allowed)</li>
<li><a class="reference internal" href="socket.html#socket.socket.send" title="socket.socket.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a>, <a class="reference internal" href="socket.html#socket.socket.sendall" title="socket.socket.sendall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sendall()</span></code></a> (with
the same limitation)</li>
<li><a class="reference internal" href="socket.html#socket.socket.shutdown" title="socket.socket.shutdown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shutdown()</span></code></a></li>
</ul>
<p>However, since the SSL (and TLS) protocol has its own framing atop
of TCP, the SSL sockets abstraction can, in certain respects, diverge from
the specification of normal, OS-level sockets.  See especially the
<a class="reference internal" href="#ssl-nonblocking"><span class="std std-ref">notes on non-blocking sockets</span></a>.</p>
<p>SSL sockets also have the following additional methods and attributes:</p>
<dl class="method">
<dt id="ssl.SSLSocket.do_handshake">
<code class="descclassname">SSLSocket.</code><code class="descname">do_handshake</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.do_handshake" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform the SSL setup handshake.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>The handshake method also performs <a class="reference internal" href="#ssl.match_hostname" title="ssl.match_hostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">match_hostname()</span></code></a> when the
<a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code class="xref py py-attr docutils literal notranslate"><span class="pre">check_hostname</span></code></a> attribute of the socket’s
<a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code class="xref py py-attr docutils literal notranslate"><span class="pre">context</span></code></a> is true.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.getpeercert">
<code class="descclassname">SSLSocket.</code><code class="descname">getpeercert</code><span class="sig-paren">(</span><em>binary_form=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.getpeercert" title="Permalink to this definition">¶</a></dt>
<dd><p>If there is no certificate for the peer on the other end of the connection,
return <code class="docutils literal notranslate"><span class="pre">None</span></code>.  If the SSL handshake hasn’t been done yet, raise
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">binary_form</span></code> parameter is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, and a certificate was
received from the peer, this method returns a <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> instance.  If the
certificate was not validated, the dict is empty.  If the certificate was
validated, it returns a dict with several keys, amongst them <code class="docutils literal notranslate"><span class="pre">subject</span></code>
(the principal for which the certificate was issued) and <code class="docutils literal notranslate"><span class="pre">issuer</span></code>
(the principal issuing the certificate).  If a certificate contains an
instance of the <em>Subject Alternative Name</em> extension (see <span class="target" id="index-11"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3280.html"><strong>RFC 3280</strong></a>),
there will also be a <code class="docutils literal notranslate"><span class="pre">subjectAltName</span></code> key in the dictionary.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">subject</span></code> and <code class="docutils literal notranslate"><span class="pre">issuer</span></code> fields are tuples containing the sequence
of relative distinguished names (RDNs) given in the certificate’s data
structure for the respective fields, and each RDN is a sequence of
name-value pairs.  Here is a real-world example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span><span class="s1">&#39;issuer&#39;</span><span class="p">:</span> <span class="p">(((</span><span class="s1">&#39;countryName&#39;</span><span class="p">,</span> <span class="s1">&#39;IL&#39;</span><span class="p">),),</span>
            <span class="p">((</span><span class="s1">&#39;organizationName&#39;</span><span class="p">,</span> <span class="s1">&#39;StartCom Ltd.&#39;</span><span class="p">),),</span>
            <span class="p">((</span><span class="s1">&#39;organizationalUnitName&#39;</span><span class="p">,</span>
              <span class="s1">&#39;Secure Digital Certificate Signing&#39;</span><span class="p">),),</span>
            <span class="p">((</span><span class="s1">&#39;commonName&#39;</span><span class="p">,</span>
              <span class="s1">&#39;StartCom Class 2 Primary Intermediate Server CA&#39;</span><span class="p">),)),</span>
 <span class="s1">&#39;notAfter&#39;</span><span class="p">:</span> <span class="s1">&#39;Nov 22 08:15:19 2013 GMT&#39;</span><span class="p">,</span>
 <span class="s1">&#39;notBefore&#39;</span><span class="p">:</span> <span class="s1">&#39;Nov 21 03:09:52 2011 GMT&#39;</span><span class="p">,</span>
 <span class="s1">&#39;serialNumber&#39;</span><span class="p">:</span> <span class="s1">&#39;95F0&#39;</span><span class="p">,</span>
 <span class="s1">&#39;subject&#39;</span><span class="p">:</span> <span class="p">(((</span><span class="s1">&#39;description&#39;</span><span class="p">,</span> <span class="s1">&#39;571208-SLe257oHY9fVQ07Z&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;countryName&#39;</span><span class="p">,</span> <span class="s1">&#39;US&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;stateOrProvinceName&#39;</span><span class="p">,</span> <span class="s1">&#39;California&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;localityName&#39;</span><span class="p">,</span> <span class="s1">&#39;San Francisco&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;organizationName&#39;</span><span class="p">,</span> <span class="s1">&#39;Electronic Frontier Foundation, Inc.&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;commonName&#39;</span><span class="p">,</span> <span class="s1">&#39;*.eff.org&#39;</span><span class="p">),),</span>
             <span class="p">((</span><span class="s1">&#39;emailAddress&#39;</span><span class="p">,</span> <span class="s1">&#39;hostmaster@eff.org&#39;</span><span class="p">),)),</span>
 <span class="s1">&#39;subjectAltName&#39;</span><span class="p">:</span> <span class="p">((</span><span class="s1">&#39;DNS&#39;</span><span class="p">,</span> <span class="s1">&#39;*.eff.org&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;DNS&#39;</span><span class="p">,</span> <span class="s1">&#39;eff.org&#39;</span><span class="p">)),</span>
 <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To validate a certificate for a particular service, you can use the
<a class="reference internal" href="#ssl.match_hostname" title="ssl.match_hostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">match_hostname()</span></code></a> function.</p>
</div>
<p>If the <code class="docutils literal notranslate"><span class="pre">binary_form</span></code> parameter is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, and a certificate was
provided, this method returns the DER-encoded form of the entire certificate
as a sequence of bytes, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the peer did not provide a
certificate.  Whether the peer provides a certificate depends on the SSL
socket’s role:</p>
<ul class="simple">
<li>for a client SSL socket, the server will always provide a certificate,
regardless of whether validation was required;</li>
<li>for a server SSL socket, the client will only provide a certificate
when requested by the server; therefore <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeercert()</span></code></a> will return
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if you used <a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a> (rather than
<a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_OPTIONAL</span></code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>).</li>
</ul>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>The returned dictionary includes additional items such as <code class="docutils literal notranslate"><span class="pre">issuer</span></code> and
<code class="docutils literal notranslate"><span class="pre">notBefore</span></code>. Additionall <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised when the handshake
isn’t done. The returned dictionary includes additional X509v3 extension
items such as <code class="docutils literal notranslate"><span class="pre">crlDistributionPoints</span></code>, <code class="docutils literal notranslate"><span class="pre">caIssuers</span></code> and <code class="docutils literal notranslate"><span class="pre">OCSP</span></code> URIs.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.cipher">
<code class="descclassname">SSLSocket.</code><code class="descname">cipher</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.cipher" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a three-value tuple containing the name of the cipher being used, the
version of the SSL protocol that defines its use, and the number of secret
bits being used.  If no connection has been established, returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.compression">
<code class="descclassname">SSLSocket.</code><code class="descname">compression</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.compression" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the compression algorithm being used as a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code>
if the connection isn’t compressed.</p>
<p>If the higher-level protocol supports its own compression mechanism,
you can use <a class="reference internal" href="#ssl.OP_NO_COMPRESSION" title="ssl.OP_NO_COMPRESSION"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_COMPRESSION</span></code></a> to disable SSL-level compression.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.get_channel_binding">
<code class="descclassname">SSLSocket.</code><code class="descname">get_channel_binding</code><span class="sig-paren">(</span><em>cb_type=&quot;tls-unique&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.get_channel_binding" title="Permalink to this definition">¶</a></dt>
<dd><p>Get channel binding data for current connection, as a bytes object.  Returns
<code class="docutils literal notranslate"><span class="pre">None</span></code> if not connected or the handshake has not been completed.</p>
<p>The <em>cb_type</em> parameter allow selection of the desired channel binding
type. Valid channel binding types are listed in the
<a class="reference internal" href="#ssl.CHANNEL_BINDING_TYPES" title="ssl.CHANNEL_BINDING_TYPES"><code class="xref py py-data docutils literal notranslate"><span class="pre">CHANNEL_BINDING_TYPES</span></code></a> list.  Currently only the ‘tls-unique’ channel
binding, defined by <span class="target" id="index-12"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc5929.html"><strong>RFC 5929</strong></a>, is supported.  <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be
raised if an unsupported channel binding type is requested.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.selected_alpn_protocol">
<code class="descclassname">SSLSocket.</code><code class="descname">selected_alpn_protocol</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.selected_alpn_protocol" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the protocol that was selected during the TLS handshake.  If
<a class="reference internal" href="#ssl.SSLContext.set_alpn_protocols" title="ssl.SSLContext.set_alpn_protocols"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_alpn_protocols()</span></code></a> was not called, if the other party does
not support ALPN, if this socket does not support any of the client’s
proposed protocols, or if the handshake has not happened yet, <code class="docutils literal notranslate"><span class="pre">None</span></code> is
returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.10.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.selected_npn_protocol">
<code class="descclassname">SSLSocket.</code><code class="descname">selected_npn_protocol</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.selected_npn_protocol" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the higher-level protocol that was selected during the TLS/SSL
handshake. If <a class="reference internal" href="#ssl.SSLContext.set_npn_protocols" title="ssl.SSLContext.set_npn_protocols"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_npn_protocols()</span></code></a> was not called, or
if the other party does not support NPN, or if the handshake has not yet
happened, this will return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.unwrap">
<code class="descclassname">SSLSocket.</code><code class="descname">unwrap</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.unwrap" title="Permalink to this definition">¶</a></dt>
<dd><p>Performs the SSL shutdown handshake, which removes the TLS layer from the
underlying socket, and returns the underlying socket object.  This can be
used to go from encrypted operation over a connection to unencrypted.  The
returned socket should always be used for further communication with the
other side of the connection, rather than the original socket.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLSocket.version">
<code class="descclassname">SSLSocket.</code><code class="descname">version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLSocket.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the actual SSL protocol version negotiated by the connection
as a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> is no secure connection is established.
As of this writing, possible return values include <code class="docutils literal notranslate"><span class="pre">&quot;SSLv2&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;SSLv3&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;TLSv1&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;TLSv1.1&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;TLSv1.2&quot;</span></code>.
Recent OpenSSL versions may define more return values.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLSocket.context">
<code class="descclassname">SSLSocket.</code><code class="descname">context</code><a class="headerlink" href="#ssl.SSLSocket.context" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> object this SSL socket is tied to.  If the SSL
socket was created using the top-level <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a> function
(rather than <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.wrap_socket()</span></code></a>), this is a custom context
object created for this SSL socket.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="ssl-contexts">
<h2>17.3.3. SSL Contexts<a class="headerlink" href="#ssl-contexts" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.9.</span></p>
</div>
<p>An SSL context holds various data longer-lived than single SSL connections,
such as SSL configuration options, certificate(s) and private key(s).
It also manages a cache of SSL sessions for server-side sockets, in order
to speed up repeated connections from the same clients.</p>
<dl class="class">
<dt id="ssl.SSLContext">
<em class="property">class </em><code class="descclassname">ssl.</code><code class="descname">SSLContext</code><span class="sig-paren">(</span><em>protocol</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new SSL context.  You must pass <em>protocol</em> which must be one
of the <code class="docutils literal notranslate"><span class="pre">PROTOCOL_*</span></code> constants defined in this module.
<a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a> is currently recommended for maximum
interoperability.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_default_context()</span></code></a> lets the <a class="reference internal" href="#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module choose
security settings for a given purpose.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.16: </span>The context is created with secure default values. The options
<a class="reference internal" href="#ssl.OP_NO_COMPRESSION" title="ssl.OP_NO_COMPRESSION"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_COMPRESSION</span></code></a>, <a class="reference internal" href="#ssl.OP_CIPHER_SERVER_PREFERENCE" title="ssl.OP_CIPHER_SERVER_PREFERENCE"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_CIPHER_SERVER_PREFERENCE</span></code></a>,
<a class="reference internal" href="#ssl.OP_SINGLE_DH_USE" title="ssl.OP_SINGLE_DH_USE"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_SINGLE_DH_USE</span></code></a>, <a class="reference internal" href="#ssl.OP_SINGLE_ECDH_USE" title="ssl.OP_SINGLE_ECDH_USE"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_SINGLE_ECDH_USE</span></code></a>,
<a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv2</span></code></a> (except for <a class="reference internal" href="#ssl.PROTOCOL_SSLv2" title="ssl.PROTOCOL_SSLv2"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv2</span></code></a>),
and <a class="reference internal" href="#ssl.OP_NO_SSLv3" title="ssl.OP_NO_SSLv3"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv3</span></code></a> (except for <a class="reference internal" href="#ssl.PROTOCOL_SSLv3" title="ssl.PROTOCOL_SSLv3"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv3</span></code></a>) are
set by default. The initial cipher suite list contains only <code class="docutils literal notranslate"><span class="pre">HIGH</span></code>
ciphers, no <code class="docutils literal notranslate"><span class="pre">NULL</span></code> ciphers and no <code class="docutils literal notranslate"><span class="pre">MD5</span></code> ciphers (except for
<a class="reference internal" href="#ssl.PROTOCOL_SSLv2" title="ssl.PROTOCOL_SSLv2"><code class="xref py py-data docutils literal notranslate"><span class="pre">PROTOCOL_SSLv2</span></code></a>).</p>
</div>
</dd></dl>

<p><a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> objects have the following methods and attributes:</p>
<dl class="method">
<dt id="ssl.SSLContext.cert_store_stats">
<code class="descclassname">SSLContext.</code><code class="descname">cert_store_stats</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.cert_store_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Get statistics about quantities of loaded X.509 certificates, count of
X.509 certificates flagged as CA certificates and certificate revocation
lists as dictionary.</p>
<p>Example for a context with one CA cert and one other cert:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">cert_store_stats</span><span class="p">()</span>
<span class="go">{&#39;crl&#39;: 0, &#39;x509_ca&#39;: 1, &#39;x509&#39;: 2}</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.load_cert_chain">
<code class="descclassname">SSLContext.</code><code class="descname">load_cert_chain</code><span class="sig-paren">(</span><em>certfile</em>, <em>keyfile=None</em>, <em>password=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.load_cert_chain" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a private key and the corresponding certificate.  The <em>certfile</em>
string must be the path to a single file in PEM format containing the
certificate as well as any number of CA certificates needed to establish
the certificate’s authenticity.  The <em>keyfile</em> string, if present, must
point to a file containing the private key in.  Otherwise the private
key will be taken from <em>certfile</em> as well.  See the discussion of
<a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more information on how the certificate
is stored in the <em>certfile</em>.</p>
<p>The <em>password</em> argument may be a function to call to get the password for
decrypting the private key.  It will only be called if the private key is
encrypted and a password is necessary.  It will be called with no arguments,
and it should return a string, bytes, or bytearray.  If the return value is
a string it will be encoded as UTF-8 before using it to decrypt the key.
Alternatively a string, bytes, or bytearray value may be supplied directly
as the <em>password</em> argument.  It will be ignored if the private key is not
encrypted and no password is needed.</p>
<p>If the <em>password</em> argument is not specified and a password is required,
OpenSSL’s built-in password prompting mechanism will be used to
interactively prompt the user for a password.</p>
<p>An <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLError</span></code></a> is raised if the private key doesn’t
match with the certificate.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.load_default_certs">
<code class="descclassname">SSLContext.</code><code class="descname">load_default_certs</code><span class="sig-paren">(</span><em>purpose=Purpose.SERVER_AUTH</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.load_default_certs" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a set of default “certification authority” (CA) certificates from
default locations. On Windows it loads CA certs from the <code class="docutils literal notranslate"><span class="pre">CA</span></code> and
<code class="docutils literal notranslate"><span class="pre">ROOT</span></code> system stores. On other systems it calls
<a class="reference internal" href="#ssl.SSLContext.set_default_verify_paths" title="ssl.SSLContext.set_default_verify_paths"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_default_verify_paths()</span></code></a>. In the future the method may
load CA certificates from other locations, too.</p>
<p>The <em>purpose</em> flag specifies what kind of CA certificates are loaded. The
default settings <a class="reference internal" href="#ssl.Purpose.SERVER_AUTH" title="ssl.Purpose.SERVER_AUTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">Purpose.SERVER_AUTH</span></code></a> loads certificates, that are
flagged and trusted for TLS web server authentication (client side
sockets). <a class="reference internal" href="#ssl.Purpose.CLIENT_AUTH" title="ssl.Purpose.CLIENT_AUTH"><code class="xref py py-data docutils literal notranslate"><span class="pre">Purpose.CLIENT_AUTH</span></code></a> loads CA certificates for client
certificate verification on the server side.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.load_verify_locations">
<code class="descclassname">SSLContext.</code><code class="descname">load_verify_locations</code><span class="sig-paren">(</span><em>cafile=None</em>, <em>capath=None</em>, <em>cadata=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.load_verify_locations" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a set of “certification authority” (CA) certificates used to validate
other peers’ certificates when <a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-data docutils literal notranslate"><span class="pre">verify_mode</span></code></a> is other than
<a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a>.  At least one of <em>cafile</em> or <em>capath</em> must be specified.</p>
<p>This method can also load certification revocation lists (CRLs) in PEM or
DER format. In order to make use of CRLs, <a class="reference internal" href="#ssl.SSLContext.verify_flags" title="ssl.SSLContext.verify_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.verify_flags</span></code></a>
must be configured properly.</p>
<p>The <em>cafile</em> string, if present, is the path to a file of concatenated
CA certificates in PEM format. See the discussion of
<a class="reference internal" href="#ssl-certificates"><span class="std std-ref">Certificates</span></a> for more information about how to arrange the
certificates in this file.</p>
<p>The <em>capath</em> string, if present, is
the path to a directory containing several CA certificates in PEM format,
following an <a class="reference external" href="https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_load_verify_locations.html">OpenSSL specific layout</a>.</p>
<p>The <em>cadata</em> object, if present, is either an ASCII string of one or more
PEM-encoded certificates or a bytes-like object of DER-encoded
certificates. Like with <em>capath</em> extra lines around PEM-encoded
certificates are ignored but at least one certificate must be present.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.get_ca_certs">
<code class="descclassname">SSLContext.</code><code class="descname">get_ca_certs</code><span class="sig-paren">(</span><em>binary_form=False</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.get_ca_certs" title="Permalink to this definition">¶</a></dt>
<dd><p>Get a list of loaded “certification authority” (CA) certificates. If the
<code class="docutils literal notranslate"><span class="pre">binary_form</span></code> parameter is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> each list
entry is a dict like the output of <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.getpeercert()</span></code></a>. Otherwise
the method returns a list of DER-encoded certificates. The returned list
does not contain certificates from <em>capath</em> unless a certificate was
requested and loaded by a SSL connection.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Certificates in a capath directory aren’t loaded unless they have
been used at least once.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_default_verify_paths">
<code class="descclassname">SSLContext.</code><code class="descname">set_default_verify_paths</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_default_verify_paths" title="Permalink to this definition">¶</a></dt>
<dd><p>Load a set of default “certification authority” (CA) certificates from
a filesystem path defined when building the OpenSSL library.  Unfortunately,
there’s no easy way to know whether this method succeeds: no error is
returned if no certificates are to be found.  When the OpenSSL library is
provided as part of the operating system, though, it is likely to be
configured properly.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_ciphers">
<code class="descclassname">SSLContext.</code><code class="descname">set_ciphers</code><span class="sig-paren">(</span><em>ciphers</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_ciphers" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the available ciphers for sockets created with this context.
It should be a string in the <a class="reference external" href="https://www.openssl.org/docs/manmaster/man1/ciphers.html">OpenSSL cipher list format</a>.
If no cipher can be selected (because compile-time options or other
configuration forbids use of all the specified ciphers), an
<a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLError</span></code></a> will be raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>when connected, the <a class="reference internal" href="#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.cipher()</span></code></a> method of SSL sockets will
give the currently selected cipher.</p>
<p class="last">OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites
cannot be disabled with <a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_ciphers()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_alpn_protocols">
<code class="descclassname">SSLContext.</code><code class="descname">set_alpn_protocols</code><span class="sig-paren">(</span><em>protocols</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_alpn_protocols" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify which protocols the socket should advertise during the SSL/TLS
handshake. It should be a list of ASCII strings, like <code class="docutils literal notranslate"><span class="pre">['http/1.1',</span>
<span class="pre">'spdy/2']</span></code>, ordered by preference. The selection of a protocol will happen
during the handshake, and will play out according to <span class="target" id="index-13"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc7301.html"><strong>RFC 7301</strong></a>. After a
successful handshake, the <a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.selected_alpn_protocol()</span></code></a> method will
return the agreed-upon protocol.</p>
<p>This method will raise <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> if <a class="reference internal" href="#ssl.HAS_ALPN" title="ssl.HAS_ALPN"><code class="xref py py-data docutils literal notranslate"><span class="pre">HAS_ALPN</span></code></a> is
False.</p>
<p>OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise <a class="reference internal" href="#ssl.SSLError" title="ssl.SSLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SSLError</span></code></a>
when both sides support ALPN but cannot agree on a protocol. 1.1.0f+
behaves like 1.0.2, <a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.selected_alpn_protocol()</span></code></a> returns None.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.10.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_npn_protocols">
<code class="descclassname">SSLContext.</code><code class="descname">set_npn_protocols</code><span class="sig-paren">(</span><em>protocols</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_npn_protocols" title="Permalink to this definition">¶</a></dt>
<dd><p>Specify which protocols the socket should advertise during the SSL/TLS
handshake. It should be a list of strings, like <code class="docutils literal notranslate"><span class="pre">['http/1.1',</span> <span class="pre">'spdy/2']</span></code>,
ordered by preference. The selection of a protocol will happen during the
handshake, and will play out according to the <a class="reference external" href="https://tools.ietf.org/html/draft-agl-tls-nextprotoneg">NPN draft specification</a>. After a
successful handshake, the <a class="reference internal" href="#ssl.SSLSocket.selected_npn_protocol" title="ssl.SSLSocket.selected_npn_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.selected_npn_protocol()</span></code></a> method will
return the agreed-upon protocol.</p>
<p>This method will raise <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> if <a class="reference internal" href="#ssl.HAS_NPN" title="ssl.HAS_NPN"><code class="xref py py-data docutils literal notranslate"><span class="pre">HAS_NPN</span></code></a> is
False.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_servername_callback">
<code class="descclassname">SSLContext.</code><code class="descname">set_servername_callback</code><span class="sig-paren">(</span><em>server_name_callback</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_servername_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a callback function that will be called after the TLS Client Hello
handshake message has been received by the SSL/TLS server when the TLS client
specifies a server name indication. The server name indication mechanism
is specified in <span class="target" id="index-14"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc6066.html"><strong>RFC 6066</strong></a> section 3 - Server Name Indication.</p>
<p>Only one callback can be set per <code class="docutils literal notranslate"><span class="pre">SSLContext</span></code>.  If <em>server_name_callback</em>
is <code class="docutils literal notranslate"><span class="pre">None</span></code> then the callback is disabled. Calling this function a
subsequent time will disable the previously registered callback.</p>
<p>The callback function, <em>server_name_callback</em>, will be called with three
arguments; the first being the <code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLSocket</span></code>, the second is a string
that represents the server name that the client is intending to communicate
(or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the TLS Client Hello does not contain a server name)
and the third argument is the original <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a>. The server name
argument is the IDNA decoded server name.</p>
<p>A typical use of this callback is to change the <code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLSocket</span></code>’s
<a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLSocket.context</span></code></a> attribute to a new object of type
<a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> representing a certificate chain that matches the server
name.</p>
<p>Due to the early negotiation phase of the TLS connection, only limited
methods and attributes are usable like
<a class="reference internal" href="#ssl.SSLSocket.selected_alpn_protocol" title="ssl.SSLSocket.selected_alpn_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.selected_alpn_protocol()</span></code></a> and <a class="reference internal" href="#ssl.SSLSocket.context" title="ssl.SSLSocket.context"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLSocket.context</span></code></a>.
<a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.getpeercert()</span></code></a>, <a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.getpeercert()</span></code></a>,
<a class="reference internal" href="#ssl.SSLSocket.cipher" title="ssl.SSLSocket.cipher"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.cipher()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.compress()</span></code> methods require that
the TLS connection has progressed beyond the TLS Client Hello and therefore
will not contain return meaningful values nor can they be called safely.</p>
<p>The <em>server_name_callback</em> function must return <code class="docutils literal notranslate"><span class="pre">None</span></code> to allow the
TLS negotiation to continue.  If a TLS failure is required, a constant
<a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ALERT_DESCRIPTION_*</span></code></a> can be
returned.  Other return values will result in a TLS fatal error with
<a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ALERT_DESCRIPTION_INTERNAL_ERROR</span></code></a>.</p>
<p>If there is an IDNA decoding error on the server name, the TLS connection
will terminate with an <a class="reference internal" href="#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR" title="ssl.ALERT_DESCRIPTION_INTERNAL_ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ALERT_DESCRIPTION_INTERNAL_ERROR</span></code></a> fatal TLS
alert message to the client.</p>
<p>If an exception is raised from the <em>server_name_callback</em> function the TLS
connection will terminate with a fatal TLS alert message
<a class="reference internal" href="#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE" title="ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE"><code class="xref py py-const docutils literal notranslate"><span class="pre">ALERT_DESCRIPTION_HANDSHAKE_FAILURE</span></code></a>.</p>
<p>This method will raise <a class="reference internal" href="exceptions.html#exceptions.NotImplementedError" title="exceptions.NotImplementedError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotImplementedError</span></code></a> if the OpenSSL library
had OPENSSL_NO_TLSEXT defined when it was built.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.load_dh_params">
<code class="descclassname">SSLContext.</code><code class="descname">load_dh_params</code><span class="sig-paren">(</span><em>dhfile</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.load_dh_params" title="Permalink to this definition">¶</a></dt>
<dd><p>Load the key generation parameters for Diffie-Helman (DH) key exchange.
Using DH key exchange improves forward secrecy at the expense of
computational resources (both on the server and on the client).
The <em>dhfile</em> parameter should be the path to a file containing DH
parameters in PEM format.</p>
<p>This setting doesn’t apply to client sockets.  You can also use the
<a class="reference internal" href="#ssl.OP_SINGLE_DH_USE" title="ssl.OP_SINGLE_DH_USE"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_SINGLE_DH_USE</span></code></a> option to further improve security.</p>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.set_ecdh_curve">
<code class="descclassname">SSLContext.</code><code class="descname">set_ecdh_curve</code><span class="sig-paren">(</span><em>curve_name</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.set_ecdh_curve" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the curve name for Elliptic Curve-based Diffie-Hellman (ECDH) key
exchange.  ECDH is significantly faster than regular DH while arguably
as secure.  The <em>curve_name</em> parameter should be a string describing
a well-known elliptic curve, for example <code class="docutils literal notranslate"><span class="pre">prime256v1</span></code> for a widely
supported curve.</p>
<p>This setting doesn’t apply to client sockets.  You can also use the
<a class="reference internal" href="#ssl.OP_SINGLE_ECDH_USE" title="ssl.OP_SINGLE_ECDH_USE"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_SINGLE_ECDH_USE</span></code></a> option to further improve security.</p>
<p>This method is not available if <a class="reference internal" href="#ssl.HAS_ECDH" title="ssl.HAS_ECDH"><code class="xref py py-data docutils literal notranslate"><span class="pre">HAS_ECDH</span></code></a> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://vincent.bernat.im/en/blog/2011-ssl-perfect-forward-secrecy.html">SSL/TLS &amp; Perfect Forward Secrecy</a></dt>
<dd>Vincent Bernat.</dd>
</dl>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.wrap_socket">
<code class="descclassname">SSLContext.</code><code class="descname">wrap_socket</code><span class="sig-paren">(</span><em>sock</em>, <em>server_side=False</em>, <em>do_handshake_on_connect=True</em>, <em>suppress_ragged_eofs=True</em>, <em>server_hostname=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.wrap_socket" title="Permalink to this definition">¶</a></dt>
<dd><p>Wrap an existing Python socket <em>sock</em> and return an <code class="xref py py-class docutils literal notranslate"><span class="pre">SSLSocket</span></code>
object.  <em>sock</em> must be a <a class="reference internal" href="socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-data docutils literal notranslate"><span class="pre">SOCK_STREAM</span></code></a> socket; other socket
types are unsupported.</p>
<p>The returned SSL socket is tied to the context, its settings and
certificates.  The parameters <em>server_side</em>, <em>do_handshake_on_connect</em>
and <em>suppress_ragged_eofs</em> have the same meaning as in the top-level
<a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a> function.</p>
<p>On client connections, the optional parameter <em>server_hostname</em> specifies
the hostname of the service which we are connecting to.  This allows a
single server to host multiple SSL-based services with distinct certificates,
quite similarly to HTTP virtual hosts. Specifying <em>server_hostname</em> will
raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if <em>server_side</em> is true.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>Always allow a server_hostname to be passed, even if OpenSSL does not
have SNI.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="ssl.SSLContext.session_stats">
<code class="descclassname">SSLContext.</code><code class="descname">session_stats</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ssl.SSLContext.session_stats" title="Permalink to this definition">¶</a></dt>
<dd><p>Get statistics about the SSL sessions created or managed by this context.
A dictionary is returned which maps the names of each <a class="reference external" href="https://www.openssl.org/docs/man1.1.0/ssl/SSL_CTX_sess_number.html">piece of information</a> to their
numeric values.  For example, here is the total number of hits and misses
in the session cache since the context was created:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">session_stats</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stats</span><span class="p">[</span><span class="s1">&#39;hits&#39;</span><span class="p">],</span> <span class="n">stats</span><span class="p">[</span><span class="s1">&#39;misses&#39;</span><span class="p">]</span>
<span class="go">(0, 0)</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLContext.check_hostname">
<code class="descclassname">SSLContext.</code><code class="descname">check_hostname</code><a class="headerlink" href="#ssl.SSLContext.check_hostname" title="Permalink to this definition">¶</a></dt>
<dd><p>Wether to match the peer cert’s hostname with <a class="reference internal" href="#ssl.match_hostname" title="ssl.match_hostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">match_hostname()</span></code></a> in
<a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.do_handshake()</span></code></a>. The context’s
<a class="reference internal" href="#ssl.SSLContext.verify_mode" title="ssl.SSLContext.verify_mode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">verify_mode</span></code></a> must be set to <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_OPTIONAL</span></code></a> or
<a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>, and you must pass <em>server_hostname</em> to
<a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a> in order to match the hostname.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">ssl</span>

<span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">SSLContext</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">PROTOCOL_TLS</span><span class="p">)</span>
<span class="n">context</span><span class="o">.</span><span class="n">verify_mode</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">CERT_REQUIRED</span>
<span class="n">context</span><span class="o">.</span><span class="n">check_hostname</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">context</span><span class="o">.</span><span class="n">load_default_certs</span><span class="p">()</span>

<span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">,</span> <span class="n">socket</span><span class="o">.</span><span class="n">SOCK_STREAM</span><span class="p">)</span>
<span class="n">ssl_sock</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">wrap_socket</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">server_hostname</span><span class="o">=</span><span class="s1">&#39;www.verisign.com&#39;</span><span class="p">)</span>
<span class="n">ssl_sock</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="s1">&#39;www.verisign.com&#39;</span><span class="p">,</span> <span class="mi">443</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This features requires OpenSSL 0.9.8f or newer.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLContext.options">
<code class="descclassname">SSLContext.</code><code class="descname">options</code><a class="headerlink" href="#ssl.SSLContext.options" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer representing the set of SSL options enabled on this context.
The default value is <a class="reference internal" href="#ssl.OP_ALL" title="ssl.OP_ALL"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_ALL</span></code></a>, but you can specify other options
such as <a class="reference internal" href="#ssl.OP_NO_SSLv2" title="ssl.OP_NO_SSLv2"><code class="xref py py-data docutils literal notranslate"><span class="pre">OP_NO_SSLv2</span></code></a> by ORing them together.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">With versions of OpenSSL older than 0.9.8m, it is only possible
to set options, not to clear them.  Attempting to clear an option
(by resetting the corresponding bits) will raise a <code class="docutils literal notranslate"><span class="pre">ValueError</span></code>.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLContext.protocol">
<code class="descclassname">SSLContext.</code><code class="descname">protocol</code><a class="headerlink" href="#ssl.SSLContext.protocol" title="Permalink to this definition">¶</a></dt>
<dd><p>The protocol version chosen when constructing the context.  This attribute
is read-only.</p>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLContext.verify_flags">
<code class="descclassname">SSLContext.</code><code class="descname">verify_flags</code><a class="headerlink" href="#ssl.SSLContext.verify_flags" title="Permalink to this definition">¶</a></dt>
<dd><p>The flags for certificate verification operations. You can set flags like
<a class="reference internal" href="#ssl.VERIFY_CRL_CHECK_LEAF" title="ssl.VERIFY_CRL_CHECK_LEAF"><code class="xref py py-data docutils literal notranslate"><span class="pre">VERIFY_CRL_CHECK_LEAF</span></code></a> by ORing them together. By default OpenSSL
does neither require nor verify certificate revocation lists (CRLs).
Available only with openssl version 0.9.8+.</p>
</dd></dl>

<dl class="attribute">
<dt id="ssl.SSLContext.verify_mode">
<code class="descclassname">SSLContext.</code><code class="descname">verify_mode</code><a class="headerlink" href="#ssl.SSLContext.verify_mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Whether to try to verify other peers’ certificates and how to behave
if verification fails.  This attribute must be one of
<a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a>, <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_OPTIONAL</span></code></a> or <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-data docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>.</p>
</dd></dl>

<span class="target" id="index-15"></span></div>
<div class="section" id="certificates">
<span id="ssl-certificates"></span><span id="index-16"></span><h2>17.3.4. Certificates<a class="headerlink" href="#certificates" title="Permalink to this headline">¶</a></h2>
<p>Certificates in general are part of a public-key / private-key system.  In this
system, each <em>principal</em>, (which may be a machine, or a person, or an
organization) is assigned a unique two-part encryption key.  One part of the key
is public, and is called the <em>public key</em>; the other part is kept secret, and is
called the <em>private key</em>.  The two parts are related, in that if you encrypt a
message with one of the parts, you can decrypt it with the other part, and
<strong>only</strong> with the other part.</p>
<p>A certificate contains information about two principals.  It contains the name
of a <em>subject</em>, and the subject’s public key.  It also contains a statement by a
second principal, the <em>issuer</em>, that the subject is who they claim to be, and
that this is indeed the subject’s public key.  The issuer’s statement is signed
with the issuer’s private key, which only the issuer knows.  However, anyone can
verify the issuer’s statement by finding the issuer’s public key, decrypting the
statement with it, and comparing it to the other information in the certificate.
The certificate also contains information about the time period over which it is
valid.  This is expressed as two fields, called “notBefore” and “notAfter”.</p>
<p>In the Python use of certificates, a client or server can use a certificate to
prove who they are.  The other side of a network connection can also be required
to produce a certificate, and that certificate can be validated to the
satisfaction of the client or server that requires such validation.  The
connection attempt can be set to raise an exception if the validation fails.
Validation is done automatically, by the underlying OpenSSL framework; the
application need not concern itself with its mechanics.  But the application
does usually need to provide sets of certificates to allow this process to take
place.</p>
<p>Python uses files to contain certificates.  They should be formatted as “PEM”
(see <span class="target" id="index-17"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1422.html"><strong>RFC 1422</strong></a>), which is a base-64 encoded form wrapped with a header line
and a footer line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-----</span><span class="n">BEGIN</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">certificate</span> <span class="ow">in</span> <span class="n">base64</span> <span class="n">PEM</span> <span class="n">encoding</span><span class="p">)</span> <span class="o">...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
</pre></div>
</div>
<div class="section" id="certificate-chains">
<h3>17.3.4.1. Certificate chains<a class="headerlink" href="#certificate-chains" title="Permalink to this headline">¶</a></h3>
<p>The Python files which contain certificates can contain a sequence of
certificates, sometimes called a <em>certificate chain</em>.  This chain should start
with the specific certificate for the principal who “is” the client or server,
and then the certificate for the issuer of that certificate, and then the
certificate for the issuer of <em>that</em> certificate, and so on up the chain till
you get to a certificate which is <em>self-signed</em>, that is, a certificate which
has the same subject and issuer, sometimes called a <em>root certificate</em>.  The
certificates should just be concatenated together in the certificate file.  For
example, suppose we had a three certificate chain, from our server certificate
to the certificate of the certification authority that signed our server
certificate, to the root certificate of the agency which issued the
certification authority’s certificate:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-----</span><span class="n">BEGIN</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">certificate</span> <span class="k">for</span> <span class="n">your</span> <span class="n">server</span><span class="p">)</span><span class="o">...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">-----</span><span class="n">BEGIN</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">the</span> <span class="n">certificate</span> <span class="k">for</span> <span class="n">the</span> <span class="n">CA</span><span class="p">)</span><span class="o">...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">-----</span><span class="n">BEGIN</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">the</span> <span class="n">root</span> <span class="n">certificate</span> <span class="k">for</span> <span class="n">the</span> <span class="n">CA</span><span class="s1">&#39;s issuer)...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
</pre></div>
</div>
</div>
<div class="section" id="ca-certificates">
<h3>17.3.4.2. CA certificates<a class="headerlink" href="#ca-certificates" title="Permalink to this headline">¶</a></h3>
<p>If you are going to require validation of the other side of the connection’s
certificate, you need to provide a “CA certs” file, filled with the certificate
chains for each issuer you are willing to trust.  Again, this file just contains
these chains concatenated together.  For validation, Python will use the first
chain it finds in the file which matches.  The platform’s certificates file can
be used by calling <a class="reference internal" href="#ssl.SSLContext.load_default_certs" title="ssl.SSLContext.load_default_certs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_default_certs()</span></code></a>, this is done
automatically with <a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_default_context()</span></code></a>.</p>
</div>
<div class="section" id="combined-key-and-certificate">
<h3>17.3.4.3. Combined key and certificate<a class="headerlink" href="#combined-key-and-certificate" title="Permalink to this headline">¶</a></h3>
<p>Often the private key is stored in the same file as the certificate; in this
case, only the <code class="docutils literal notranslate"><span class="pre">certfile</span></code> parameter to <a class="reference internal" href="#ssl.SSLContext.load_cert_chain" title="ssl.SSLContext.load_cert_chain"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_cert_chain()</span></code></a>
and <a class="reference internal" href="#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap_socket()</span></code></a> needs to be passed.  If the private key is stored
with the certificate, it should come before the first certificate in
the certificate chain:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-----</span><span class="n">BEGIN</span> <span class="n">RSA</span> <span class="n">PRIVATE</span> <span class="n">KEY</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">private</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">base64</span> <span class="n">encoding</span><span class="p">)</span> <span class="o">...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">RSA</span> <span class="n">PRIVATE</span> <span class="n">KEY</span><span class="o">-----</span>
<span class="o">-----</span><span class="n">BEGIN</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
<span class="o">...</span> <span class="p">(</span><span class="n">certificate</span> <span class="ow">in</span> <span class="n">base64</span> <span class="n">PEM</span> <span class="n">encoding</span><span class="p">)</span> <span class="o">...</span>
<span class="o">-----</span><span class="n">END</span> <span class="n">CERTIFICATE</span><span class="o">-----</span>
</pre></div>
</div>
</div>
<div class="section" id="self-signed-certificates">
<h3>17.3.4.4. Self-signed certificates<a class="headerlink" href="#self-signed-certificates" title="Permalink to this headline">¶</a></h3>
<p>If you are going to create a server that provides SSL-encrypted connection
services, you will need to acquire a certificate for that service.  There are
many ways of acquiring appropriate certificates, such as buying one from a
certification authority.  Another common practice is to generate a self-signed
certificate.  The simplest way to do this is with the OpenSSL package, using
something like the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">%</span> <span class="n">openssl</span> <span class="n">req</span> <span class="o">-</span><span class="n">new</span> <span class="o">-</span><span class="n">x509</span> <span class="o">-</span><span class="n">days</span> <span class="mi">365</span> <span class="o">-</span><span class="n">nodes</span> <span class="o">-</span><span class="n">out</span> <span class="n">cert</span><span class="o">.</span><span class="n">pem</span> <span class="o">-</span><span class="n">keyout</span> <span class="n">cert</span><span class="o">.</span><span class="n">pem</span>
<span class="n">Generating</span> <span class="n">a</span> <span class="mi">1024</span> <span class="n">bit</span> <span class="n">RSA</span> <span class="n">private</span> <span class="n">key</span>
<span class="o">.......++++++</span>
<span class="o">.............................++++++</span>
<span class="n">writing</span> <span class="n">new</span> <span class="n">private</span> <span class="n">key</span> <span class="n">to</span> <span class="s1">&#39;cert.pem&#39;</span>
<span class="o">-----</span>
<span class="n">You</span> <span class="n">are</span> <span class="n">about</span> <span class="n">to</span> <span class="n">be</span> <span class="n">asked</span> <span class="n">to</span> <span class="n">enter</span> <span class="n">information</span> <span class="n">that</span> <span class="n">will</span> <span class="n">be</span> <span class="n">incorporated</span>
<span class="n">into</span> <span class="n">your</span> <span class="n">certificate</span> <span class="n">request</span><span class="o">.</span>
<span class="n">What</span> <span class="n">you</span> <span class="n">are</span> <span class="n">about</span> <span class="n">to</span> <span class="n">enter</span> <span class="ow">is</span> <span class="n">what</span> <span class="ow">is</span> <span class="n">called</span> <span class="n">a</span> <span class="n">Distinguished</span> <span class="n">Name</span> <span class="ow">or</span> <span class="n">a</span> <span class="n">DN</span><span class="o">.</span>
<span class="n">There</span> <span class="n">are</span> <span class="n">quite</span> <span class="n">a</span> <span class="n">few</span> <span class="n">fields</span> <span class="n">but</span> <span class="n">you</span> <span class="n">can</span> <span class="n">leave</span> <span class="n">some</span> <span class="n">blank</span>
<span class="n">For</span> <span class="n">some</span> <span class="n">fields</span> <span class="n">there</span> <span class="n">will</span> <span class="n">be</span> <span class="n">a</span> <span class="n">default</span> <span class="n">value</span><span class="p">,</span>
<span class="n">If</span> <span class="n">you</span> <span class="n">enter</span> <span class="s1">&#39;.&#39;</span><span class="p">,</span> <span class="n">the</span> <span class="n">field</span> <span class="n">will</span> <span class="n">be</span> <span class="n">left</span> <span class="n">blank</span><span class="o">.</span>
<span class="o">-----</span>
<span class="n">Country</span> <span class="n">Name</span> <span class="p">(</span><span class="mi">2</span> <span class="n">letter</span> <span class="n">code</span><span class="p">)</span> <span class="p">[</span><span class="n">AU</span><span class="p">]:</span><span class="n">US</span>
<span class="n">State</span> <span class="ow">or</span> <span class="n">Province</span> <span class="n">Name</span> <span class="p">(</span><span class="n">full</span> <span class="n">name</span><span class="p">)</span> <span class="p">[</span><span class="n">Some</span><span class="o">-</span><span class="n">State</span><span class="p">]:</span><span class="n">MyState</span>
<span class="n">Locality</span> <span class="n">Name</span> <span class="p">(</span><span class="n">eg</span><span class="p">,</span> <span class="n">city</span><span class="p">)</span> <span class="p">[]:</span><span class="n">Some</span> <span class="n">City</span>
<span class="n">Organization</span> <span class="n">Name</span> <span class="p">(</span><span class="n">eg</span><span class="p">,</span> <span class="n">company</span><span class="p">)</span> <span class="p">[</span><span class="n">Internet</span> <span class="n">Widgits</span> <span class="n">Pty</span> <span class="n">Ltd</span><span class="p">]:</span><span class="n">My</span> <span class="n">Organization</span><span class="p">,</span> <span class="n">Inc</span><span class="o">.</span>
<span class="n">Organizational</span> <span class="n">Unit</span> <span class="n">Name</span> <span class="p">(</span><span class="n">eg</span><span class="p">,</span> <span class="n">section</span><span class="p">)</span> <span class="p">[]:</span><span class="n">My</span> <span class="n">Group</span>
<span class="n">Common</span> <span class="n">Name</span> <span class="p">(</span><span class="n">eg</span><span class="p">,</span> <span class="n">YOUR</span> <span class="n">name</span><span class="p">)</span> <span class="p">[]:</span><span class="n">myserver</span><span class="o">.</span><span class="n">mygroup</span><span class="o">.</span><span class="n">myorganization</span><span class="o">.</span><span class="n">com</span>
<span class="n">Email</span> <span class="n">Address</span> <span class="p">[]:</span><span class="n">ops</span><span class="nd">@myserver</span><span class="o">.</span><span class="n">mygroup</span><span class="o">.</span><span class="n">myorganization</span><span class="o">.</span><span class="n">com</span>
<span class="o">%</span>
</pre></div>
</div>
<p>The disadvantage of a self-signed certificate is that it is its own root
certificate, and no one else will have it in their cache of known (and trusted)
root certificates.</p>
</div>
</div>
<div class="section" id="examples">
<h2>17.3.5. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<div class="section" id="testing-for-ssl-support">
<h3>17.3.5.1. Testing for SSL support<a class="headerlink" href="#testing-for-ssl-support" title="Permalink to this headline">¶</a></h3>
<p>To test for the presence of SSL support in a Python installation, user code
should use the following idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">ssl</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="k">pass</span>
<span class="k">else</span><span class="p">:</span>
    <span class="o">...</span>  <span class="c1"># do something that requires SSL support</span>
</pre></div>
</div>
</div>
<div class="section" id="client-side-operation">
<h3>17.3.5.2. Client-side operation<a class="headerlink" href="#client-side-operation" title="Permalink to this headline">¶</a></h3>
<p>This example creates a SSL context with the recommended security settings
for client sockets, including automatic certificate verification:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">()</span>
</pre></div>
</div>
<p>If you prefer to tune security settings yourself, you might create
a context from scratch (but beware that you might not get the settings
right):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">SSLContext</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">PROTOCOL_TLS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">verify_mode</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">CERT_REQUIRED</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">check_hostname</span> <span class="o">=</span> <span class="kc">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">context</span><span class="o">.</span><span class="n">load_verify_locations</span><span class="p">(</span><span class="s2">&quot;/etc/ssl/certs/ca-bundle.crt&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>(this snippet assumes your operating system places a bundle of all CA
certificates in <code class="docutils literal notranslate"><span class="pre">/etc/ssl/certs/ca-bundle.crt</span></code>; if not, you’ll get an
error and have to adjust the location)</p>
<p>When you use the context to connect to a server, <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>
validates the server certificate: it ensures that the server certificate
was signed with one of the CA certificates, and checks the signature for
correctness:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">wrap_socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">AF_INET</span><span class="p">),</span>
<span class="gp">... </span>                           <span class="n">server_hostname</span><span class="o">=</span><span class="s2">&quot;www.python.org&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">connect</span><span class="p">((</span><span class="s2">&quot;www.python.org&quot;</span><span class="p">,</span> <span class="mi">443</span><span class="p">))</span>
</pre></div>
</div>
<p>You may then fetch the certificate:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cert</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">getpeercert</span><span class="p">()</span>
</pre></div>
</div>
<p>Visual inspection shows that the certificate does identify the desired service
(that is, the HTTPS host <code class="docutils literal notranslate"><span class="pre">www.python.org</span></code>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">cert</span><span class="p">)</span>
<span class="go">{&#39;OCSP&#39;: (&#39;http://ocsp.digicert.com&#39;,),</span>
<span class="go"> &#39;caIssuers&#39;: (&#39;http://cacerts.digicert.com/DigiCertSHA2ExtendedValidationServerCA.crt&#39;,),</span>
<span class="go"> &#39;crlDistributionPoints&#39;: (&#39;http://crl3.digicert.com/sha2-ev-server-g1.crl&#39;,</span>
<span class="go">                           &#39;http://crl4.digicert.com/sha2-ev-server-g1.crl&#39;),</span>
<span class="go"> &#39;issuer&#39;: (((&#39;countryName&#39;, &#39;US&#39;),),</span>
<span class="go">            ((&#39;organizationName&#39;, &#39;DigiCert Inc&#39;),),</span>
<span class="go">            ((&#39;organizationalUnitName&#39;, &#39;www.digicert.com&#39;),),</span>
<span class="go">            ((&#39;commonName&#39;, &#39;DigiCert SHA2 Extended Validation Server CA&#39;),)),</span>
<span class="go"> &#39;notAfter&#39;: &#39;Sep  9 12:00:00 2016 GMT&#39;,</span>
<span class="go"> &#39;notBefore&#39;: &#39;Sep  5 00:00:00 2014 GMT&#39;,</span>
<span class="go"> &#39;serialNumber&#39;: &#39;01BB6F00122B177F36CAB49CEA8B6B26&#39;,</span>
<span class="go"> &#39;subject&#39;: (((&#39;businessCategory&#39;, &#39;Private Organization&#39;),),</span>
<span class="go">             ((&#39;1.3.6.1.4.1.311.60.2.1.3&#39;, &#39;US&#39;),),</span>
<span class="go">             ((&#39;1.3.6.1.4.1.311.60.2.1.2&#39;, &#39;Delaware&#39;),),</span>
<span class="go">             ((&#39;serialNumber&#39;, &#39;3359300&#39;),),</span>
<span class="go">             ((&#39;streetAddress&#39;, &#39;16 Allen Rd&#39;),),</span>
<span class="go">             ((&#39;postalCode&#39;, &#39;03894-4801&#39;),),</span>
<span class="go">             ((&#39;countryName&#39;, &#39;US&#39;),),</span>
<span class="go">             ((&#39;stateOrProvinceName&#39;, &#39;NH&#39;),),</span>
<span class="go">             ((&#39;localityName&#39;, &#39;Wolfeboro,&#39;),),</span>
<span class="go">             ((&#39;organizationName&#39;, &#39;Python Software Foundation&#39;),),</span>
<span class="go">             ((&#39;commonName&#39;, &#39;www.python.org&#39;),)),</span>
<span class="go"> &#39;subjectAltName&#39;: ((&#39;DNS&#39;, &#39;www.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;pypi.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;docs.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;testpypi.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;bugs.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;wiki.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;hg.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;mail.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;packaging.python.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;pythonhosted.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;www.pythonhosted.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;test.pythonhosted.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;us.pycon.org&#39;),</span>
<span class="go">                    (&#39;DNS&#39;, &#39;id.python.org&#39;)),</span>
<span class="go"> &#39;version&#39;: 3}</span>
</pre></div>
</div>
<p>Now the SSL channel is established and the certificate verified, you can
proceed to talk with the server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">conn</span><span class="o">.</span><span class="n">sendall</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;HEAD / HTTP/1.0</span><span class="se">\r\n</span><span class="s2">Host: linuxfr.org</span><span class="se">\r\n\r\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">conn</span><span class="o">.</span><span class="n">recv</span><span class="p">(</span><span class="mi">1024</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="sa">b</span><span class="s2">&quot;</span><span class="se">\r\n</span><span class="s2">&quot;</span><span class="p">))</span>
<span class="go">[b&#39;HTTP/1.1 200 OK&#39;,</span>
<span class="go"> b&#39;Date: Sat, 18 Oct 2014 18:27:20 GMT&#39;,</span>
<span class="go"> b&#39;Server: nginx&#39;,</span>
<span class="go"> b&#39;Content-Type: text/html; charset=utf-8&#39;,</span>
<span class="go"> b&#39;X-Frame-Options: SAMEORIGIN&#39;,</span>
<span class="go"> b&#39;Content-Length: 45679&#39;,</span>
<span class="go"> b&#39;Accept-Ranges: bytes&#39;,</span>
<span class="go"> b&#39;Via: 1.1 varnish&#39;,</span>
<span class="go"> b&#39;Age: 2188&#39;,</span>
<span class="go"> b&#39;X-Served-By: cache-lcy1134-LCY&#39;,</span>
<span class="go"> b&#39;X-Cache: HIT&#39;,</span>
<span class="go"> b&#39;X-Cache-Hits: 11&#39;,</span>
<span class="go"> b&#39;Vary: Cookie&#39;,</span>
<span class="go"> b&#39;Strict-Transport-Security: max-age=63072000; includeSubDomains&#39;,</span>
<span class="go"> b&#39;Connection: close&#39;,</span>
<span class="go"> b&#39;&#39;,</span>
<span class="go"> b&#39;&#39;]</span>
</pre></div>
</div>
<p>See the discussion of <a class="reference internal" href="#ssl-security"><span class="std std-ref">Security considerations</span></a> below.</p>
</div>
<div class="section" id="server-side-operation">
<h3>17.3.5.3. Server-side operation<a class="headerlink" href="#server-side-operation" title="Permalink to this headline">¶</a></h3>
<p>For server operation, typically you’ll need to have a server certificate, and
private key, each in a file.  You’ll first create a context holding the key
and the certificate, so that clients can check your authenticity.  Then
you’ll open a socket, bind it to a port, call <code class="xref py py-meth docutils literal notranslate"><span class="pre">listen()</span></code> on it, and start
waiting for clients to connect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">socket</span><span class="o">,</span> <span class="nn">ssl</span>

<span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">Purpose</span><span class="o">.</span><span class="n">CLIENT_AUTH</span><span class="p">)</span>
<span class="n">context</span><span class="o">.</span><span class="n">load_cert_chain</span><span class="p">(</span><span class="n">certfile</span><span class="o">=</span><span class="s2">&quot;mycertfile&quot;</span><span class="p">,</span> <span class="n">keyfile</span><span class="o">=</span><span class="s2">&quot;mykeyfile&quot;</span><span class="p">)</span>

<span class="n">bindsocket</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">()</span>
<span class="n">bindsocket</span><span class="o">.</span><span class="n">bind</span><span class="p">((</span><span class="s1">&#39;myaddr.mydomain.com&#39;</span><span class="p">,</span> <span class="mi">10023</span><span class="p">))</span>
<span class="n">bindsocket</span><span class="o">.</span><span class="n">listen</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
</pre></div>
</div>
<p>When a client connects, you’ll call <code class="xref py py-meth docutils literal notranslate"><span class="pre">accept()</span></code> on the socket to get the
new socket from the other end, and use the context’s <a class="reference internal" href="#ssl.SSLContext.wrap_socket" title="ssl.SSLContext.wrap_socket"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.wrap_socket()</span></code></a>
method to create a server-side SSL socket for the connection:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="n">newsocket</span><span class="p">,</span> <span class="n">fromaddr</span> <span class="o">=</span> <span class="n">bindsocket</span><span class="o">.</span><span class="n">accept</span><span class="p">()</span>
    <span class="n">connstream</span> <span class="o">=</span> <span class="n">context</span><span class="o">.</span><span class="n">wrap_socket</span><span class="p">(</span><span class="n">newsocket</span><span class="p">,</span> <span class="n">server_side</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">deal_with_client</span><span class="p">(</span><span class="n">connstream</span><span class="p">)</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">connstream</span><span class="o">.</span><span class="n">shutdown</span><span class="p">(</span><span class="n">socket</span><span class="o">.</span><span class="n">SHUT_RDWR</span><span class="p">)</span>
        <span class="n">connstream</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Then you’ll read data from the <code class="docutils literal notranslate"><span class="pre">connstream</span></code> and do something with it till you
are finished with the client (or the client is finished with you):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">deal_with_client</span><span class="p">(</span><span class="n">connstream</span><span class="p">):</span>
    <span class="n">data</span> <span class="o">=</span> <span class="n">connstream</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
    <span class="c1"># null data means the client is finished with us</span>
    <span class="k">while</span> <span class="n">data</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="n">do_something</span><span class="p">(</span><span class="n">connstream</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
            <span class="c1"># we&#39;ll assume do_something returns False</span>
            <span class="c1"># when we&#39;re finished with client</span>
            <span class="k">break</span>
        <span class="n">data</span> <span class="o">=</span> <span class="n">connstream</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
    <span class="c1"># finished with client</span>
</pre></div>
</div>
<p>And go back to listening for new client connections (of course, a real server
would probably handle each client connection in a separate thread, or put
the sockets in non-blocking mode and use an event loop).</p>
</div>
</div>
<div class="section" id="notes-on-non-blocking-sockets">
<span id="ssl-nonblocking"></span><h2>17.3.6. Notes on non-blocking sockets<a class="headerlink" href="#notes-on-non-blocking-sockets" title="Permalink to this headline">¶</a></h2>
<p>When working with non-blocking sockets, there are several things you need
to be aware of:</p>
<ul>
<li><p class="first">Calling <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> tells you that the OS-level socket can be
read from (or written to), but it does not imply that there is sufficient
data at the upper SSL layer.  For example, only part of an SSL frame might
have arrived.  Therefore, you must be ready to handle <code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.recv()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.send()</span></code> failures, and retry after another call to
<a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a>.</p>
</li>
<li><p class="first">Conversely, since the SSL layer has its own framing, a SSL socket may
still have data available for reading without <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a>
being aware of it.  Therefore, you should first call
<code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.recv()</span></code> to drain any potentially available data, and then
only block on a <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> call if still necessary.</p>
<p>(of course, similar provisions apply when using other primitives such as
<a class="reference internal" href="select.html#select.poll" title="select.poll"><code class="xref py py-func docutils literal notranslate"><span class="pre">poll()</span></code></a>, or those in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">selectors</span></code> module)</p>
</li>
<li><p class="first">The SSL handshake itself will be non-blocking: the
<a class="reference internal" href="#ssl.SSLSocket.do_handshake" title="ssl.SSLSocket.do_handshake"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.do_handshake()</span></code></a> method has to be retried until it returns
successfully.  Here is a synopsis using <a class="reference internal" href="select.html#select.select" title="select.select"><code class="xref py py-func docutils literal notranslate"><span class="pre">select()</span></code></a> to wait for
the socket’s readiness:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">sock</span><span class="o">.</span><span class="n">do_handshake</span><span class="p">()</span>
        <span class="k">break</span>
    <span class="k">except</span> <span class="n">ssl</span><span class="o">.</span><span class="n">SSLWantReadError</span><span class="p">:</span>
        <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([</span><span class="n">sock</span><span class="p">],</span> <span class="p">[],</span> <span class="p">[])</span>
    <span class="k">except</span> <span class="n">ssl</span><span class="o">.</span><span class="n">SSLWantWriteError</span><span class="p">:</span>
        <span class="n">select</span><span class="o">.</span><span class="n">select</span><span class="p">([],</span> <span class="p">[</span><span class="n">sock</span><span class="p">],</span> <span class="p">[])</span>
</pre></div>
</div>
</li>
</ul>
</div>
<div class="section" id="security-considerations">
<span id="ssl-security"></span><h2>17.3.7. Security considerations<a class="headerlink" href="#security-considerations" title="Permalink to this headline">¶</a></h2>
<div class="section" id="best-defaults">
<h3>17.3.7.1. Best defaults<a class="headerlink" href="#best-defaults" title="Permalink to this headline">¶</a></h3>
<p>For <strong>client use</strong>, if you don’t have any special requirements for your
security policy, it is highly recommended that you use the
<a class="reference internal" href="#ssl.create_default_context" title="ssl.create_default_context"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_default_context()</span></code></a> function to create your SSL context.
It will load the system’s trusted CA certificates, enable certificate
validation and hostname checking, and try to choose reasonably secure
protocol and cipher settings.</p>
<p>If a client certificate is needed for the connection, it can be added with
<a class="reference internal" href="#ssl.SSLContext.load_cert_chain" title="ssl.SSLContext.load_cert_chain"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.load_cert_chain()</span></code></a>.</p>
<p>By contrast, if you create the SSL context by calling the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a>
constructor yourself, it will not have certificate validation nor hostname
checking enabled by default.  If you do so, please read the paragraphs below
to achieve a good security level.</p>
</div>
<div class="section" id="manual-settings">
<h3>17.3.7.2. Manual settings<a class="headerlink" href="#manual-settings" title="Permalink to this headline">¶</a></h3>
<div class="section" id="verifying-certificates">
<h4>17.3.7.2.1. Verifying certificates<a class="headerlink" href="#verifying-certificates" title="Permalink to this headline">¶</a></h4>
<p>When calling the <a class="reference internal" href="#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> constructor directly,
<a class="reference internal" href="#ssl.CERT_NONE" title="ssl.CERT_NONE"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_NONE</span></code></a> is the default.  Since it does not authenticate the other
peer, it can be insecure, especially in client mode where most of time you
would like to ensure the authenticity of the server you’re talking to.
Therefore, when in client mode, it is highly recommended to use
<a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a>.  However, it is in itself not sufficient; you also
have to check that the server certificate, which can be obtained by calling
<a class="reference internal" href="#ssl.SSLSocket.getpeercert" title="ssl.SSLSocket.getpeercert"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.getpeercert()</span></code></a>, matches the desired service.  For many
protocols and applications, the service can be identified by the hostname;
in this case, the <a class="reference internal" href="#ssl.match_hostname" title="ssl.match_hostname"><code class="xref py py-func docutils literal notranslate"><span class="pre">match_hostname()</span></code></a> function can be used.  This common
check is automatically performed when <a class="reference internal" href="#ssl.SSLContext.check_hostname" title="ssl.SSLContext.check_hostname"><code class="xref py py-attr docutils literal notranslate"><span class="pre">SSLContext.check_hostname</span></code></a> is
enabled.</p>
<p>In server mode, if you want to authenticate your clients using the SSL layer
(rather than using a higher-level authentication mechanism), you’ll also have
to specify <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a> and similarly check the client certificate.</p>
<blockquote>
<div><div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In client mode, <a class="reference internal" href="#ssl.CERT_OPTIONAL" title="ssl.CERT_OPTIONAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_OPTIONAL</span></code></a> and <a class="reference internal" href="#ssl.CERT_REQUIRED" title="ssl.CERT_REQUIRED"><code class="xref py py-const docutils literal notranslate"><span class="pre">CERT_REQUIRED</span></code></a> are
equivalent unless anonymous ciphers are enabled (they are disabled
by default).</p>
</div>
</div></blockquote>
</div>
<div class="section" id="protocol-versions">
<h4>17.3.7.2.2. Protocol versions<a class="headerlink" href="#protocol-versions" title="Permalink to this headline">¶</a></h4>
<p>SSL versions 2 and 3 are considered insecure and are therefore dangerous to
use.  If you want maximum compatibility between clients and servers, it is
recommended to use <a class="reference internal" href="#ssl.PROTOCOL_SSLv23" title="ssl.PROTOCOL_SSLv23"><code class="xref py py-const docutils literal notranslate"><span class="pre">PROTOCOL_SSLv23</span></code></a> as the protocol version and then
disable SSLv2 and SSLv3 explicitly using the <a class="reference internal" href="#ssl.SSLContext.options" title="ssl.SSLContext.options"><code class="xref py py-data docutils literal notranslate"><span class="pre">SSLContext.options</span></code></a>
attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">SSLContext</span><span class="p">(</span><span class="n">ssl</span><span class="o">.</span><span class="n">PROTOCOL_SSLv23</span><span class="p">)</span>
<span class="n">context</span><span class="o">.</span><span class="n">options</span> <span class="o">|=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">OP_NO_SSLv2</span>
<span class="n">context</span><span class="o">.</span><span class="n">options</span> <span class="o">|=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">OP_NO_SSLv3</span>
</pre></div>
</div>
<p>The SSL context created above will only allow TLSv1 and later (if
supported by your system) connections.</p>
</div>
<div class="section" id="cipher-selection">
<h4>17.3.7.2.3. Cipher selection<a class="headerlink" href="#cipher-selection" title="Permalink to this headline">¶</a></h4>
<p>If you have advanced security requirements, fine-tuning of the ciphers
enabled when negotiating a SSL session is possible through the
<a class="reference internal" href="#ssl.SSLContext.set_ciphers" title="ssl.SSLContext.set_ciphers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_ciphers()</span></code></a> method.  Starting from Python 2.7.9, the
ssl module disables certain weak ciphers by default, but you may want
to further restrict the cipher choice. Be sure to read OpenSSL’s documentation
about the <a class="reference external" href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT">cipher list format</a>.
If you want to check which ciphers are enabled by a given cipher list, use the
<code class="docutils literal notranslate"><span class="pre">openssl</span> <span class="pre">ciphers</span></code> command on your system.</p>
</div>
</div>
<div class="section" id="multi-processing">
<h3>17.3.7.3. Multi-processing<a class="headerlink" href="#multi-processing" title="Permalink to this headline">¶</a></h3>
<p>If using this module as part of a multi-processed application (using,
for example the <a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code> modules),
be aware that OpenSSL’s internal random number generator does not properly
handle forked processes.  Applications must change the PRNG state of the
parent process if they use any SSL feature with <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a>.  Any
successful call of <a class="reference internal" href="#ssl.RAND_add" title="ssl.RAND_add"><code class="xref py py-func docutils literal notranslate"><span class="pre">RAND_add()</span></code></a>, <code class="xref py py-func docutils literal notranslate"><span class="pre">RAND_bytes()</span></code> or
<code class="xref py py-func docutils literal notranslate"><span class="pre">RAND_pseudo_bytes()</span></code> is sufficient.</p>
</div>
</div>
<div class="section" id="libressl-support">
<h2>17.3.8. LibreSSL support<a class="headerlink" href="#libressl-support" title="Permalink to this headline">¶</a></h2>
<p>LibreSSL is a fork of OpenSSL 1.0.1. The ssl module has limited support for
LibreSSL. Some features are not available when the ssl module is compiled
with LibreSSL.</p>
<ul class="simple">
<li>LibreSSL &gt;= 2.6.1 no longer supports NPN. The methods
<a class="reference internal" href="#ssl.SSLContext.set_npn_protocols" title="ssl.SSLContext.set_npn_protocols"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_npn_protocols()</span></code></a> and
<a class="reference internal" href="#ssl.SSLSocket.selected_npn_protocol" title="ssl.SSLSocket.selected_npn_protocol"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLSocket.selected_npn_protocol()</span></code></a> are not available.</li>
<li><a class="reference internal" href="#ssl.SSLContext.set_default_verify_paths" title="ssl.SSLContext.set_default_verify_paths"><code class="xref py py-meth docutils literal notranslate"><span class="pre">SSLContext.set_default_verify_paths()</span></code></a> ignores the env vars
<span class="target" id="index-18"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">SSL_CERT_FILE</span></code> and <span class="target" id="index-19"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">SSL_CERT_PATH</span></code> although
<a class="reference internal" href="#ssl.get_default_verify_paths" title="ssl.get_default_verify_paths"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_default_verify_paths()</span></code></a> still reports them.</li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Class <a class="reference internal" href="socket.html#socket.socket" title="socket.socket"><code class="xref py py-class docutils literal notranslate"><span class="pre">socket.socket</span></code></a></dt>
<dd>Documentation of underlying <a class="reference internal" href="socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> class</dd>
<dt><a class="reference external" href="https://httpd.apache.org/docs/trunk/en/ssl/ssl_intro.html">SSL/TLS Strong Encryption: An Introduction</a></dt>
<dd>Intro from the Apache webserver documentation</dd>
<dt><a class="reference external" href="https://www.ietf.org/rfc/rfc1422">RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management</a></dt>
<dd>Steve Kent</dd>
<dt><a class="reference external" href="https://www.ietf.org/rfc/rfc1750">RFC 1750: Randomness Recommendations for Security</a></dt>
<dd>D. Eastlake et. al.</dd>
<dt><a class="reference external" href="https://www.ietf.org/rfc/rfc3280">RFC 3280: Internet X.509 Public Key Infrastructure Certificate and CRL Profile</a></dt>
<dd>Housley et. al.</dd>
<dt><a class="reference external" href="https://www.ietf.org/rfc/rfc4366">RFC 4366: Transport Layer Security (TLS) Extensions</a></dt>
<dd>Blake-Wilson et. al.</dd>
<dt><a class="reference external" href="https://tools.ietf.org/html/rfc5246">RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2</a></dt>
<dd>T. Dierks et. al.</dd>
<dt><a class="reference external" href="https://tools.ietf.org/html/rfc6066">RFC 6066: Transport Layer Security (TLS) Extensions</a></dt>
<dd>D. Eastlake</dd>
<dt><a class="reference external" href="https://www.iana.org/assignments/tls-parameters/tls-parameters.xml">IANA TLS: Transport Layer Security (TLS) Parameters</a></dt>
<dd>IANA</dd>
<dt><a class="reference external" href="https://tools.ietf.org/html/rfc7525">RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS)</a></dt>
<dd>IETF</dd>
<dt><a class="reference external" href="https://wiki.mozilla.org/Security/Server_Side_TLS">Mozilla’s Server Side TLS recommendations</a></dt>
<dd>Mozilla</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a><ul>
<li><a class="reference internal" href="#functions-constants-and-exceptions">17.3.1. Functions, Constants, and Exceptions</a><ul>
<li><a class="reference internal" href="#socket-creation">17.3.1.1. Socket creation</a></li>
<li><a class="reference internal" href="#context-creation">17.3.1.2. Context creation</a></li>
<li><a class="reference internal" href="#random-generation">17.3.1.3. Random generation</a></li>
<li><a class="reference internal" href="#certificate-handling">17.3.1.4. Certificate handling</a></li>
<li><a class="reference internal" href="#constants">17.3.1.5. Constants</a></li>
</ul>
</li>
<li><a class="reference internal" href="#ssl-sockets">17.3.2. SSL Sockets</a></li>
<li><a class="reference internal" href="#ssl-contexts">17.3.3. SSL Contexts</a></li>
<li><a class="reference internal" href="#certificates">17.3.4. Certificates</a><ul>
<li><a class="reference internal" href="#certificate-chains">17.3.4.1. Certificate chains</a></li>
<li><a class="reference internal" href="#ca-certificates">17.3.4.2. CA certificates</a></li>
<li><a class="reference internal" href="#combined-key-and-certificate">17.3.4.3. Combined key and certificate</a></li>
<li><a class="reference internal" href="#self-signed-certificates">17.3.4.4. Self-signed certificates</a></li>
</ul>
</li>
<li><a class="reference internal" href="#examples">17.3.5. Examples</a><ul>
<li><a class="reference internal" href="#testing-for-ssl-support">17.3.5.1. Testing for SSL support</a></li>
<li><a class="reference internal" href="#client-side-operation">17.3.5.2. Client-side operation</a></li>
<li><a class="reference internal" href="#server-side-operation">17.3.5.3. Server-side operation</a></li>
</ul>
</li>
<li><a class="reference internal" href="#notes-on-non-blocking-sockets">17.3.6. Notes on non-blocking sockets</a></li>
<li><a class="reference internal" href="#security-considerations">17.3.7. Security considerations</a><ul>
<li><a class="reference internal" href="#best-defaults">17.3.7.1. Best defaults</a></li>
<li><a class="reference internal" href="#manual-settings">17.3.7.2. Manual settings</a><ul>
<li><a class="reference internal" href="#verifying-certificates">17.3.7.2.1. Verifying certificates</a></li>
<li><a class="reference internal" href="#protocol-versions">17.3.7.2.2. Protocol versions</a></li>
<li><a class="reference internal" href="#cipher-selection">17.3.7.2.3. Cipher selection</a></li>
</ul>
</li>
<li><a class="reference internal" href="#multi-processing">17.3.7.3. Multi-processing</a></li>
</ul>
</li>
<li><a class="reference internal" href="#libressl-support">17.3.8. LibreSSL support</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="socket.html"
                        title="previous chapter">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="signal.html"
                        title="next chapter">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ssl.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="signal.html" title="17.4. signal — Set handlers for asynchronous events"
             >next</a> |</li>
        <li class="right" >
          <a href="socket.html" title="17.2. socket — Low-level networking interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��j%�%�html/library/stat.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.3. stat — Interpreting stat() results &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.4. statvfs — Constants used with os.statvfs()" href="statvfs.html" />
    <link rel="prev" title="10.2. fileinput — Iterate over lines from multiple input streams" href="fileinput.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/stat.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="statvfs.html" title="10.4. statvfs — Constants used with os.statvfs()"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="fileinput.html" title="10.2. fileinput — Iterate over lines from multiple input streams"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-stat">
<span id="stat-interpreting-stat-results"></span><h1>10.3. <a class="reference internal" href="#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> — Interpreting <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a> results<a class="headerlink" href="#module-stat" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/stat.py">Lib/stat.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module defines constants and functions for interpreting the
results of <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>, <a class="reference internal" href="os.html#os.fstat" title="os.fstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fstat()</span></code></a> and <a class="reference internal" href="os.html#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lstat()</span></code></a> (if they
exist).  For complete details about the <code class="xref c c-func docutils literal notranslate"><span class="pre">stat()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">fstat()</span></code> and
<code class="xref c c-func docutils literal notranslate"><span class="pre">lstat()</span></code> calls, consult the documentation for your system.</p>
<p>The <a class="reference internal" href="#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module defines the following functions to test for specific file
types:</p>
<dl class="function">
<dt id="stat.S_ISDIR">
<code class="descclassname">stat.</code><code class="descname">S_ISDIR</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISDIR" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a directory.</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISCHR">
<code class="descclassname">stat.</code><code class="descname">S_ISCHR</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISCHR" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a character special device file.</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISBLK">
<code class="descclassname">stat.</code><code class="descname">S_ISBLK</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISBLK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a block special device file.</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISREG">
<code class="descclassname">stat.</code><code class="descname">S_ISREG</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISREG" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a regular file.</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISFIFO">
<code class="descclassname">stat.</code><code class="descname">S_ISFIFO</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISFIFO" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a FIFO (named pipe).</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISLNK">
<code class="descclassname">stat.</code><code class="descname">S_ISLNK</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISLNK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a symbolic link.</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_ISSOCK">
<code class="descclassname">stat.</code><code class="descname">S_ISSOCK</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_ISSOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Return non-zero if the mode is from a socket.</p>
</dd></dl>

<p>Two additional functions are defined for more general manipulation of the file’s
mode:</p>
<dl class="function">
<dt id="stat.S_IMODE">
<code class="descclassname">stat.</code><code class="descname">S_IMODE</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_IMODE" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the portion of the file’s mode that can be set by <a class="reference internal" href="os.html#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chmod()</span></code></a>—that is, the file’s permission bits, plus the sticky bit, set-group-id, and
set-user-id bits (on systems that support them).</p>
</dd></dl>

<dl class="function">
<dt id="stat.S_IFMT">
<code class="descclassname">stat.</code><code class="descname">S_IFMT</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#stat.S_IFMT" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the portion of the file’s mode that describes the file type (used by the
<code class="xref py py-func docutils literal notranslate"><span class="pre">S_IS*()</span></code> functions above).</p>
</dd></dl>

<p>Normally, you would use the <code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.is*()</span></code> functions for testing the type
of a file; the functions here are useful when you are doing multiple tests of
the same file and wish to avoid the overhead of the <code class="xref c c-func docutils literal notranslate"><span class="pre">stat()</span></code> system call
for each test.  These are also useful when checking for information about a file
that isn’t handled by <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a>, like the tests for block and character
devices.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">stat</span> <span class="k">import</span> <span class="o">*</span>

<span class="k">def</span> <span class="nf">walktree</span><span class="p">(</span><span class="n">top</span><span class="p">,</span> <span class="n">callback</span><span class="p">):</span>
    <span class="sd">&#39;&#39;&#39;recursively descend the directory tree rooted at top,</span>
<span class="sd">       calling the callback function for each regular file&#39;&#39;&#39;</span>

    <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">top</span><span class="p">):</span>
        <span class="n">pathname</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">top</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
        <span class="n">mode</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="n">pathname</span><span class="p">)</span><span class="o">.</span><span class="n">st_mode</span>
        <span class="k">if</span> <span class="n">S_ISDIR</span><span class="p">(</span><span class="n">mode</span><span class="p">):</span>
            <span class="c1"># It&#39;s a directory, recurse into it</span>
            <span class="n">walktree</span><span class="p">(</span><span class="n">pathname</span><span class="p">,</span> <span class="n">callback</span><span class="p">)</span>
        <span class="k">elif</span> <span class="n">S_ISREG</span><span class="p">(</span><span class="n">mode</span><span class="p">):</span>
            <span class="c1"># It&#39;s a file, call the callback function</span>
            <span class="n">callback</span><span class="p">(</span><span class="n">pathname</span><span class="p">)</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Unknown file type, print a message</span>
            <span class="nb">print</span> <span class="s1">&#39;Skipping </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">pathname</span>

<span class="k">def</span> <span class="nf">visitfile</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;visiting&#39;</span><span class="p">,</span> <span class="n">file</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">walktree</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">visitfile</span><span class="p">)</span>
</pre></div>
</div>
<p>All the variables below are simply symbolic indexes into the 10-tuple returned
by <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>, <a class="reference internal" href="os.html#os.fstat" title="os.fstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fstat()</span></code></a> or <a class="reference internal" href="os.html#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lstat()</span></code></a>.</p>
<dl class="data">
<dt id="stat.ST_MODE">
<code class="descclassname">stat.</code><code class="descname">ST_MODE</code><a class="headerlink" href="#stat.ST_MODE" title="Permalink to this definition">¶</a></dt>
<dd><p>Inode protection mode.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_INO">
<code class="descclassname">stat.</code><code class="descname">ST_INO</code><a class="headerlink" href="#stat.ST_INO" title="Permalink to this definition">¶</a></dt>
<dd><p>Inode number.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_DEV">
<code class="descclassname">stat.</code><code class="descname">ST_DEV</code><a class="headerlink" href="#stat.ST_DEV" title="Permalink to this definition">¶</a></dt>
<dd><p>Device inode resides on.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_NLINK">
<code class="descclassname">stat.</code><code class="descname">ST_NLINK</code><a class="headerlink" href="#stat.ST_NLINK" title="Permalink to this definition">¶</a></dt>
<dd><p>Number of links to the inode.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_UID">
<code class="descclassname">stat.</code><code class="descname">ST_UID</code><a class="headerlink" href="#stat.ST_UID" title="Permalink to this definition">¶</a></dt>
<dd><p>User id of the owner.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_GID">
<code class="descclassname">stat.</code><code class="descname">ST_GID</code><a class="headerlink" href="#stat.ST_GID" title="Permalink to this definition">¶</a></dt>
<dd><p>Group id of the owner.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_SIZE">
<code class="descclassname">stat.</code><code class="descname">ST_SIZE</code><a class="headerlink" href="#stat.ST_SIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Size in bytes of a plain file; amount of data waiting on some special files.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_ATIME">
<code class="descclassname">stat.</code><code class="descname">ST_ATIME</code><a class="headerlink" href="#stat.ST_ATIME" title="Permalink to this definition">¶</a></dt>
<dd><p>Time of last access.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_MTIME">
<code class="descclassname">stat.</code><code class="descname">ST_MTIME</code><a class="headerlink" href="#stat.ST_MTIME" title="Permalink to this definition">¶</a></dt>
<dd><p>Time of last modification.</p>
</dd></dl>

<dl class="data">
<dt id="stat.ST_CTIME">
<code class="descclassname">stat.</code><code class="descname">ST_CTIME</code><a class="headerlink" href="#stat.ST_CTIME" title="Permalink to this definition">¶</a></dt>
<dd><p>The “ctime” as reported by the operating system.  On some systems (like Unix) is
the time of the last metadata change, and, on others (like Windows), is the
creation time (see platform documentation for details).</p>
</dd></dl>

<p>The interpretation of “file size” changes according to the file type.  For plain
files this is the size of the file in bytes.  For FIFOs and sockets under most
flavors of Unix (including Linux in particular), the “size” is the number of
bytes waiting to be read at the time of the call to <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a>,
<a class="reference internal" href="os.html#os.fstat" title="os.fstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fstat()</span></code></a>, or <a class="reference internal" href="os.html#os.lstat" title="os.lstat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lstat()</span></code></a>; this can sometimes be useful, especially
for polling one of these special files after a non-blocking open.  The meaning
of the size field for other character and block devices varies more, depending
on the implementation of the underlying system call.</p>
<p>The variables below define the flags used in the <a class="reference internal" href="#stat.ST_MODE" title="stat.ST_MODE"><code class="xref py py-data docutils literal notranslate"><span class="pre">ST_MODE</span></code></a> field.</p>
<p>Use of the functions above is more portable than use of the first set of flags:</p>
<dl class="data">
<dt id="stat.S_IFSOCK">
<code class="descclassname">stat.</code><code class="descname">S_IFSOCK</code><a class="headerlink" href="#stat.S_IFSOCK" title="Permalink to this definition">¶</a></dt>
<dd><p>Socket.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFLNK">
<code class="descclassname">stat.</code><code class="descname">S_IFLNK</code><a class="headerlink" href="#stat.S_IFLNK" title="Permalink to this definition">¶</a></dt>
<dd><p>Symbolic link.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFREG">
<code class="descclassname">stat.</code><code class="descname">S_IFREG</code><a class="headerlink" href="#stat.S_IFREG" title="Permalink to this definition">¶</a></dt>
<dd><p>Regular file.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFBLK">
<code class="descclassname">stat.</code><code class="descname">S_IFBLK</code><a class="headerlink" href="#stat.S_IFBLK" title="Permalink to this definition">¶</a></dt>
<dd><p>Block device.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFDIR">
<code class="descclassname">stat.</code><code class="descname">S_IFDIR</code><a class="headerlink" href="#stat.S_IFDIR" title="Permalink to this definition">¶</a></dt>
<dd><p>Directory.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFCHR">
<code class="descclassname">stat.</code><code class="descname">S_IFCHR</code><a class="headerlink" href="#stat.S_IFCHR" title="Permalink to this definition">¶</a></dt>
<dd><p>Character device.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IFIFO">
<code class="descclassname">stat.</code><code class="descname">S_IFIFO</code><a class="headerlink" href="#stat.S_IFIFO" title="Permalink to this definition">¶</a></dt>
<dd><p>FIFO.</p>
</dd></dl>

<p>The following flags can also be used in the <em>mode</em> argument of <a class="reference internal" href="os.html#os.chmod" title="os.chmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chmod()</span></code></a>:</p>
<dl class="data">
<dt id="stat.S_ISUID">
<code class="descclassname">stat.</code><code class="descname">S_ISUID</code><a class="headerlink" href="#stat.S_ISUID" title="Permalink to this definition">¶</a></dt>
<dd><p>Set UID bit.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_ISGID">
<code class="descclassname">stat.</code><code class="descname">S_ISGID</code><a class="headerlink" href="#stat.S_ISGID" title="Permalink to this definition">¶</a></dt>
<dd><p>Set-group-ID bit.  This bit has several special uses.  For a directory
it indicates that BSD semantics is to be used for that directory:
files created there inherit their group ID from the directory, not
from the effective group ID of the creating process, and directories
created there will also get the <a class="reference internal" href="#stat.S_ISGID" title="stat.S_ISGID"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_ISGID</span></code></a> bit set.  For a
file that does not have the group execution bit (<a class="reference internal" href="#stat.S_IXGRP" title="stat.S_IXGRP"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_IXGRP</span></code></a>)
set, the set-group-ID bit indicates mandatory file/record locking
(see also <a class="reference internal" href="#stat.S_ENFMT" title="stat.S_ENFMT"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_ENFMT</span></code></a>).</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_ISVTX">
<code class="descclassname">stat.</code><code class="descname">S_ISVTX</code><a class="headerlink" href="#stat.S_ISVTX" title="Permalink to this definition">¶</a></dt>
<dd><p>Sticky bit.  When this bit is set on a directory it means that a file
in that directory can be renamed or deleted only by the owner of the
file, by the owner of the directory, or by a privileged process.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IRWXU">
<code class="descclassname">stat.</code><code class="descname">S_IRWXU</code><a class="headerlink" href="#stat.S_IRWXU" title="Permalink to this definition">¶</a></dt>
<dd><p>Mask for file owner permissions.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IRUSR">
<code class="descclassname">stat.</code><code class="descname">S_IRUSR</code><a class="headerlink" href="#stat.S_IRUSR" title="Permalink to this definition">¶</a></dt>
<dd><p>Owner has read permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IWUSR">
<code class="descclassname">stat.</code><code class="descname">S_IWUSR</code><a class="headerlink" href="#stat.S_IWUSR" title="Permalink to this definition">¶</a></dt>
<dd><p>Owner has write permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IXUSR">
<code class="descclassname">stat.</code><code class="descname">S_IXUSR</code><a class="headerlink" href="#stat.S_IXUSR" title="Permalink to this definition">¶</a></dt>
<dd><p>Owner has execute permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IRWXG">
<code class="descclassname">stat.</code><code class="descname">S_IRWXG</code><a class="headerlink" href="#stat.S_IRWXG" title="Permalink to this definition">¶</a></dt>
<dd><p>Mask for group permissions.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IRGRP">
<code class="descclassname">stat.</code><code class="descname">S_IRGRP</code><a class="headerlink" href="#stat.S_IRGRP" title="Permalink to this definition">¶</a></dt>
<dd><p>Group has read permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IWGRP">
<code class="descclassname">stat.</code><code class="descname">S_IWGRP</code><a class="headerlink" href="#stat.S_IWGRP" title="Permalink to this definition">¶</a></dt>
<dd><p>Group has write permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IXGRP">
<code class="descclassname">stat.</code><code class="descname">S_IXGRP</code><a class="headerlink" href="#stat.S_IXGRP" title="Permalink to this definition">¶</a></dt>
<dd><p>Group has execute permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IRWXO">
<code class="descclassname">stat.</code><code class="descname">S_IRWXO</code><a class="headerlink" href="#stat.S_IRWXO" title="Permalink to this definition">¶</a></dt>
<dd><p>Mask for permissions for others (not in group).</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IROTH">
<code class="descclassname">stat.</code><code class="descname">S_IROTH</code><a class="headerlink" href="#stat.S_IROTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Others have read permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IWOTH">
<code class="descclassname">stat.</code><code class="descname">S_IWOTH</code><a class="headerlink" href="#stat.S_IWOTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Others have write permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IXOTH">
<code class="descclassname">stat.</code><code class="descname">S_IXOTH</code><a class="headerlink" href="#stat.S_IXOTH" title="Permalink to this definition">¶</a></dt>
<dd><p>Others have execute permission.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_ENFMT">
<code class="descclassname">stat.</code><code class="descname">S_ENFMT</code><a class="headerlink" href="#stat.S_ENFMT" title="Permalink to this definition">¶</a></dt>
<dd><p>System V file locking enforcement.  This flag is shared with <a class="reference internal" href="#stat.S_ISGID" title="stat.S_ISGID"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_ISGID</span></code></a>:
file/record locking is enforced on files that do not have the group
execution bit (<a class="reference internal" href="#stat.S_IXGRP" title="stat.S_IXGRP"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_IXGRP</span></code></a>) set.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IREAD">
<code class="descclassname">stat.</code><code class="descname">S_IREAD</code><a class="headerlink" href="#stat.S_IREAD" title="Permalink to this definition">¶</a></dt>
<dd><p>Unix V7 synonym for <a class="reference internal" href="#stat.S_IRUSR" title="stat.S_IRUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_IRUSR</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IWRITE">
<code class="descclassname">stat.</code><code class="descname">S_IWRITE</code><a class="headerlink" href="#stat.S_IWRITE" title="Permalink to this definition">¶</a></dt>
<dd><p>Unix V7 synonym for <a class="reference internal" href="#stat.S_IWUSR" title="stat.S_IWUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_IWUSR</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="stat.S_IEXEC">
<code class="descclassname">stat.</code><code class="descname">S_IEXEC</code><a class="headerlink" href="#stat.S_IEXEC" title="Permalink to this definition">¶</a></dt>
<dd><p>Unix V7 synonym for <a class="reference internal" href="#stat.S_IXUSR" title="stat.S_IXUSR"><code class="xref py py-data docutils literal notranslate"><span class="pre">S_IXUSR</span></code></a>.</p>
</dd></dl>

<p>The following flags can be used in the <em>flags</em> argument of <a class="reference internal" href="os.html#os.chflags" title="os.chflags"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.chflags()</span></code></a>:</p>
<dl class="data">
<dt id="stat.UF_NODUMP">
<code class="descclassname">stat.</code><code class="descname">UF_NODUMP</code><a class="headerlink" href="#stat.UF_NODUMP" title="Permalink to this definition">¶</a></dt>
<dd><p>Do not dump the file.</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_IMMUTABLE">
<code class="descclassname">stat.</code><code class="descname">UF_IMMUTABLE</code><a class="headerlink" href="#stat.UF_IMMUTABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may not be changed.</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_APPEND">
<code class="descclassname">stat.</code><code class="descname">UF_APPEND</code><a class="headerlink" href="#stat.UF_APPEND" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may only be appended to.</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_OPAQUE">
<code class="descclassname">stat.</code><code class="descname">UF_OPAQUE</code><a class="headerlink" href="#stat.UF_OPAQUE" title="Permalink to this definition">¶</a></dt>
<dd><p>The directory is opaque when viewed through a union stack.</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_NOUNLINK">
<code class="descclassname">stat.</code><code class="descname">UF_NOUNLINK</code><a class="headerlink" href="#stat.UF_NOUNLINK" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may not be renamed or deleted.</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_COMPRESSED">
<code class="descclassname">stat.</code><code class="descname">UF_COMPRESSED</code><a class="headerlink" href="#stat.UF_COMPRESSED" title="Permalink to this definition">¶</a></dt>
<dd><p>The file is stored compressed (Mac OS X 10.6+).</p>
</dd></dl>

<dl class="data">
<dt id="stat.UF_HIDDEN">
<code class="descclassname">stat.</code><code class="descname">UF_HIDDEN</code><a class="headerlink" href="#stat.UF_HIDDEN" title="Permalink to this definition">¶</a></dt>
<dd><p>The file should not be displayed in a GUI (Mac OS X 10.5+).</p>
</dd></dl>

<dl class="data">
<dt id="stat.SF_ARCHIVED">
<code class="descclassname">stat.</code><code class="descname">SF_ARCHIVED</code><a class="headerlink" href="#stat.SF_ARCHIVED" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may be archived.</p>
</dd></dl>

<dl class="data">
<dt id="stat.SF_IMMUTABLE">
<code class="descclassname">stat.</code><code class="descname">SF_IMMUTABLE</code><a class="headerlink" href="#stat.SF_IMMUTABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may not be changed.</p>
</dd></dl>

<dl class="data">
<dt id="stat.SF_APPEND">
<code class="descclassname">stat.</code><code class="descname">SF_APPEND</code><a class="headerlink" href="#stat.SF_APPEND" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may only be appended to.</p>
</dd></dl>

<dl class="data">
<dt id="stat.SF_NOUNLINK">
<code class="descclassname">stat.</code><code class="descname">SF_NOUNLINK</code><a class="headerlink" href="#stat.SF_NOUNLINK" title="Permalink to this definition">¶</a></dt>
<dd><p>The file may not be renamed or deleted.</p>
</dd></dl>

<dl class="data">
<dt id="stat.SF_SNAPSHOT">
<code class="descclassname">stat.</code><code class="descname">SF_SNAPSHOT</code><a class="headerlink" href="#stat.SF_SNAPSHOT" title="Permalink to this definition">¶</a></dt>
<dd><p>The file is a snapshot file.</p>
</dd></dl>

<p>See the *BSD or Mac OS systems man page <em class="manpage">chflags(2)</em> for more information.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="fileinput.html"
                        title="previous chapter">10.2. <code class="docutils literal notranslate"><span class="pre">fileinput</span></code> — Iterate over lines from multiple input streams</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="statvfs.html"
                        title="next chapter">10.4. <code class="docutils literal notranslate"><span class="pre">statvfs</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/stat.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="statvfs.html" title="10.4. statvfs — Constants used with os.statvfs()"
             >next</a> |</li>
        <li class="right" >
          <a href="fileinput.html" title="10.2. fileinput — Iterate over lines from multiple input streams"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��a�>,>,html/library/statvfs.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.4. statvfs — Constants used with os.statvfs() &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.5. filecmp — File and Directory Comparisons" href="filecmp.html" />
    <link rel="prev" title="10.3. stat — Interpreting stat() results" href="stat.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/statvfs.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="filecmp.html" title="10.5. filecmp — File and Directory Comparisons"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stat.html" title="10.3. stat — Interpreting stat() results"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-statvfs">
<span id="statvfs-constants-used-with-os-statvfs"></span><h1>10.4. <a class="reference internal" href="#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code></a> — Constants used with <a class="reference internal" href="os.html#os.statvfs" title="os.statvfs"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a><a class="headerlink" href="#module-statvfs" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code></a> module has been removed in Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code></a> module defines constants so interpreting the result if
<a class="reference internal" href="os.html#os.statvfs" title="os.statvfs"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a>, which returns a tuple, can be made without remembering
“magic numbers.”  Each of the constants defined in this module is the <em>index</em> of
the entry in the tuple returned by <a class="reference internal" href="os.html#os.statvfs" title="os.statvfs"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a> that contains the
specified information.</p>
<dl class="data">
<dt id="statvfs.F_BSIZE">
<code class="descclassname">statvfs.</code><code class="descname">F_BSIZE</code><a class="headerlink" href="#statvfs.F_BSIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Preferred file system block size.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_FRSIZE">
<code class="descclassname">statvfs.</code><code class="descname">F_FRSIZE</code><a class="headerlink" href="#statvfs.F_FRSIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>Fundamental file system block size.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_BLOCKS">
<code class="descclassname">statvfs.</code><code class="descname">F_BLOCKS</code><a class="headerlink" href="#statvfs.F_BLOCKS" title="Permalink to this definition">¶</a></dt>
<dd><p>Total number of blocks in the filesystem.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_BFREE">
<code class="descclassname">statvfs.</code><code class="descname">F_BFREE</code><a class="headerlink" href="#statvfs.F_BFREE" title="Permalink to this definition">¶</a></dt>
<dd><p>Total number of free blocks.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_BAVAIL">
<code class="descclassname">statvfs.</code><code class="descname">F_BAVAIL</code><a class="headerlink" href="#statvfs.F_BAVAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>Free blocks available to non-super user.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_FILES">
<code class="descclassname">statvfs.</code><code class="descname">F_FILES</code><a class="headerlink" href="#statvfs.F_FILES" title="Permalink to this definition">¶</a></dt>
<dd><p>Total number of file nodes.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_FFREE">
<code class="descclassname">statvfs.</code><code class="descname">F_FFREE</code><a class="headerlink" href="#statvfs.F_FFREE" title="Permalink to this definition">¶</a></dt>
<dd><p>Total number of free file nodes.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_FAVAIL">
<code class="descclassname">statvfs.</code><code class="descname">F_FAVAIL</code><a class="headerlink" href="#statvfs.F_FAVAIL" title="Permalink to this definition">¶</a></dt>
<dd><p>Free nodes available to non-super user.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_FLAG">
<code class="descclassname">statvfs.</code><code class="descname">F_FLAG</code><a class="headerlink" href="#statvfs.F_FLAG" title="Permalink to this definition">¶</a></dt>
<dd><p>Flags. System dependent: see <code class="xref c c-func docutils literal notranslate"><span class="pre">statvfs()</span></code> man page.</p>
</dd></dl>

<dl class="data">
<dt id="statvfs.F_NAMEMAX">
<code class="descclassname">statvfs.</code><code class="descname">F_NAMEMAX</code><a class="headerlink" href="#statvfs.F_NAMEMAX" title="Permalink to this definition">¶</a></dt>
<dd><p>Maximum file name length.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="stat.html"
                        title="previous chapter">10.3. <code class="docutils literal notranslate"><span class="pre">stat</span></code> — Interpreting <code class="docutils literal notranslate"><span class="pre">stat()</span></code> results</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="filecmp.html"
                        title="next chapter">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/statvfs.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="filecmp.html" title="10.5. filecmp — File and Directory Comparisons"
             >next</a> |</li>
        <li class="right" >
          <a href="stat.html" title="10.3. stat — Interpreting stat() results"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��KS����html/library/stdtypes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>5. Built-in Types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="6. Built-in Exceptions" href="exceptions.html" />
    <link rel="prev" title="4. Built-in Constants" href="constants.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/stdtypes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="6. Built-in Exceptions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="constants.html" title="4. Built-in Constants"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="built-in-types">
<span id="bltin-types"></span><h1>5. Built-in Types<a class="headerlink" href="#built-in-types" title="Permalink to this headline">¶</a></h1>
<p>The following sections describe the standard types that are built into the
interpreter.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Historically (until release 2.2), Python’s built-in types have differed from
user-defined types because it was not possible to use the built-in types as the
basis for object-oriented inheritance. This limitation no longer
exists.</p>
</div>
<p id="index-0">The principal built-in types are numerics, sequences, mappings, files, classes,
instances and exceptions.</p>
<p id="index-1">Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted
to a string (with the <a class="reference internal" href="functions.html#func-repr"><span class="std std-ref">repr()</span></a> function or the slightly different
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function).  The latter function is implicitly used when an object is
written by the <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function.</p>
<div class="section" id="truth-value-testing">
<span id="truth"></span><h2>5.1. Truth Value Testing<a class="headerlink" href="#truth-value-testing" title="Permalink to this headline">¶</a></h2>
<p id="index-2">Any object can be tested for truth value, for use in an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> or
<a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> condition or as operand of the Boolean operations below. The
following values are considered false:</p>
<blockquote>
<div></div></blockquote>
<ul id="index-3">
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">None</span></code></p>
</li>
<li id="index-4"><p class="first"><code class="docutils literal notranslate"><span class="pre">False</span></code></p>
</li>
<li><p class="first">zero of any numeric type, for example, <code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">0L</span></code>, <code class="docutils literal notranslate"><span class="pre">0.0</span></code>, <code class="docutils literal notranslate"><span class="pre">0j</span></code>.</p>
</li>
<li><p class="first">any empty sequence, for example, <code class="docutils literal notranslate"><span class="pre">''</span></code>, <code class="docutils literal notranslate"><span class="pre">()</span></code>, <code class="docutils literal notranslate"><span class="pre">[]</span></code>.</p>
</li>
<li><p class="first">any empty mapping, for example, <code class="docutils literal notranslate"><span class="pre">{}</span></code>.</p>
</li>
<li><p class="first">instances of user-defined classes, if the class defines a <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a>
or <a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> method, when that method returns the integer zero or
<a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> value <code class="docutils literal notranslate"><span class="pre">False</span></code>. <a class="footnote-reference" href="#id12" id="id1">[1]</a></p>
</li>
</ul>
<p id="index-5">All other values are considered true — so objects of many types are always
true.</p>
<p id="index-6">Operations and built-in functions that have a Boolean result always return <code class="docutils literal notranslate"><span class="pre">0</span></code>
or <code class="docutils literal notranslate"><span class="pre">False</span></code> for false and <code class="docutils literal notranslate"><span class="pre">1</span></code> or <code class="docutils literal notranslate"><span class="pre">True</span></code> for true, unless otherwise stated.
(Important exception: the Boolean operations <code class="docutils literal notranslate"><span class="pre">or</span></code> and <code class="docutils literal notranslate"><span class="pre">and</span></code> always return
one of their operands.)</p>
</div>
<div class="section" id="boolean-operations-and-or-not">
<span id="boolean"></span><h2>5.2. Boolean Operations — <a class="reference internal" href="../reference/expressions.html#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a>, <a class="reference internal" href="../reference/expressions.html#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a>, <a class="reference internal" href="../reference/expressions.html#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a><a class="headerlink" href="#boolean-operations-and-or-not" title="Permalink to this headline">¶</a></h2>
<p id="index-7">These are the Boolean operations, ordered by ascending priority:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="62%" />
<col width="13%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></code></td>
<td>if <em>x</em> is false, then <em>y</em>, else
<em>x</em></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></code></td>
<td>if <em>x</em> is false, then <em>x</em>, else
<em>y</em></td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span></code></td>
<td>if <em>x</em> is false, then <code class="docutils literal notranslate"><span class="pre">True</span></code>,
else <code class="docutils literal notranslate"><span class="pre">False</span></code></td>
<td>(3)</td>
</tr>
</tbody>
</table>
<p id="index-8">Notes:</p>
<ol class="arabic simple">
<li>This is a short-circuit operator, so it only evaluates the second
argument if the first one is false.</li>
<li>This is a short-circuit operator, so it only evaluates the second
argument if the first one is true.</li>
<li><code class="docutils literal notranslate"><span class="pre">not</span></code> has a lower priority than non-Boolean operators, so <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code> is
interpreted as <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">(a</span> <span class="pre">==</span> <span class="pre">b)</span></code>, and <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">not</span> <span class="pre">b</span></code> is a syntax error.</li>
</ol>
</div>
<div class="section" id="comparisons">
<span id="stdcomparisons"></span><h2>5.3. Comparisons<a class="headerlink" href="#comparisons" title="Permalink to this headline">¶</a></h2>
<p id="index-9">Comparison operations are supported by all objects.  They all have the same
priority (which is higher than that of the Boolean operations). Comparisons can
be chained arbitrarily; for example, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span>
<span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code>, except that <em>y</em> is evaluated only once (but in both cases <em>z</em> is not
evaluated at all when <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> is found to be false).</p>
<p>This table summarizes the comparison operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="57%" />
<col width="16%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&lt;</span></code></td>
<td>strictly less than</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&lt;=</span></code></td>
<td>less than or equal</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&gt;</span></code></td>
<td>strictly greater than</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&gt;=</span></code></td>
<td>greater than or equal</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">==</span></code></td>
<td>equal</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">!=</span></code></td>
<td>not equal</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">is</span></code></td>
<td>object identity</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></td>
<td>negated object identity</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li><code class="docutils literal notranslate"><span class="pre">!=</span></code> can also be written <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code>, but this is an obsolete usage
kept for backwards compatibility only. New code should always use
<code class="docutils literal notranslate"><span class="pre">!=</span></code>.</li>
</ol>
<p id="index-10">Objects of different types, except different numeric types and different string
types, never compare equal; such objects are ordered consistently but
arbitrarily (so that sorting a heterogeneous array yields a consistent result).
Furthermore, some types (for example, file objects) support only a degenerate
notion of comparison where any two objects of that type are unequal.  Again,
such objects are ordered arbitrarily but consistently. The <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>
and <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> operators will raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception when any operand is
a complex number.</p>
<p id="index-11">Non-identical instances of a class normally compare as non-equal unless the
class defines the <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method or the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method.</p>
<p>Instances of a class cannot be ordered with respect to other instances of the
same class, or other types of object, unless the class defines either enough of
the rich comparison methods (<a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a>, and
<a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a>) or the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Objects of different types except numbers are ordered by their type names;
objects of the same types that don’t support proper comparison are ordered by
their address.</p>
</div>
<p id="index-12">Two more operations with the same syntactic priority, <code class="docutils literal notranslate"><span class="pre">in</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code>, are
supported only by sequence types (below).</p>
</div>
<div class="section" id="numeric-types-int-float-long-complex">
<span id="typesnumeric"></span><h2>5.4. Numeric Types — <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>, <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a><a class="headerlink" href="#numeric-types-int-float-long-complex" title="Permalink to this headline">¶</a></h2>
<p id="index-13">There are four distinct numeric types: <em class="dfn">plain integers</em>, <em class="dfn">long
integers</em>, <em class="dfn">floating point numbers</em>, and <em class="dfn">complex numbers</em>. In
addition, Booleans are a subtype of plain integers. Plain integers (also just
called <em class="dfn">integers</em>) are implemented using <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> in C, which gives
them at least 32 bits of precision (<code class="docutils literal notranslate"><span class="pre">sys.maxint</span></code> is always set to the maximum
plain integer value for the current platform, the minimum value is
<code class="docutils literal notranslate"><span class="pre">-sys.maxint</span> <span class="pre">-</span> <span class="pre">1</span></code>).  Long integers have unlimited precision.  Floating point
numbers are usually implemented using <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> in C; information about
the precision and internal representation of floating point numbers for the
machine on which your program is running is available in
<a class="reference internal" href="sys.html#sys.float_info" title="sys.float_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.float_info</span></code></a>.  Complex numbers have a real and imaginary part, which
are each a floating point number.  To extract these parts from a complex number
<em>z</em>, use <code class="docutils literal notranslate"><span class="pre">z.real</span></code> and <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>. (The standard library includes additional
numeric types, <a class="reference internal" href="fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> that hold rationals, and <a class="reference internal" href="decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> that
hold floating-point numbers with user-definable precision.)</p>
<p id="index-14">Numbers are created by numeric literals or as the result of built-in functions
and operators.  Unadorned integer literals (including binary, hex, and octal
numbers) yield plain integers unless the value they denote is too large to be
represented as a plain integer, in which case they yield a long integer.
Integer literals with an <code class="docutils literal notranslate"><span class="pre">'L'</span></code> or <code class="docutils literal notranslate"><span class="pre">'l'</span></code> suffix yield long integers (<code class="docutils literal notranslate"><span class="pre">'L'</span></code>
is preferred because <code class="docutils literal notranslate"><span class="pre">1l</span></code> looks too much like eleven!).  Numeric literals
containing a decimal point or an exponent sign yield floating point numbers.
Appending <code class="docutils literal notranslate"><span class="pre">'j'</span></code> or <code class="docutils literal notranslate"><span class="pre">'J'</span></code> to a numeric literal yields an imaginary number
(a complex number with a zero real part) which you can add to an integer or
float to get a complex number with real and imaginary parts.</p>
<p id="index-15">Python fully supports mixed arithmetic: when a binary arithmetic operator has
operands of different numeric types, the operand with the “narrower” type is
widened to that of the other, where plain integer is narrower than long integer
is narrower than floating point is narrower than complex. Comparisons between
numbers of mixed type use the same rule. <a class="footnote-reference" href="#id13" id="id2">[2]</a> The constructors <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>,
<a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a>, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>, and <a class="reference internal" href="functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> can be used to produce numbers
of a specific type.</p>
<p>All built-in numeric types support the following operations. See
<a class="reference internal" href="../reference/expressions.html#power"><span class="std std-ref">The power operator</span></a> and later sections for the operators’ priorities.</p>
<table border="1" class="docutils">
<colgroup>
<col width="33%" />
<col width="54%" />
<col width="13%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code></td>
<td>sum of <em>x</em> and <em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code></td>
<td>difference of <em>x</em> and <em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></code></td>
<td>product of <em>x</em> and <em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></code></td>
<td>quotient of <em>x</em> and <em>y</em></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">//</span> <span class="pre">y</span></code></td>
<td>(floored) quotient of <em>x</em> and
<em>y</em></td>
<td>(4)(5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code></td>
<td>remainder of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">/</span> <span class="pre">y</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">-x</span></code></td>
<td><em>x</em> negated</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">+x</span></code></td>
<td><em>x</em> unchanged</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">abs(x)</span></code></td>
<td>absolute value or magnitude of
<em>x</em></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">int(x)</span></code></td>
<td><em>x</em> converted to integer</td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">long(x)</span></code></td>
<td><em>x</em> converted to long integer</td>
<td>(2)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">float(x)</span></code></td>
<td><em>x</em> converted to floating point</td>
<td>(6)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">complex(re,im)</span></code></td>
<td>a complex number with real part
<em>re</em>, imaginary part <em>im</em>.
<em>im</em> defaults to zero.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">c.conjugate()</span></code></td>
<td>conjugate of the complex number
<em>c</em>. (Identity on real numbers)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span></code></td>
<td>the pair <code class="docutils literal notranslate"><span class="pre">(x</span> <span class="pre">//</span> <span class="pre">y,</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y)</span></code></td>
<td>(3)(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y)</span></code></td>
<td><em>x</em> to the power <em>y</em></td>
<td>(3)(7)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">**</span> <span class="pre">y</span></code></td>
<td><em>x</em> to the power <em>y</em></td>
<td>(7)</td>
</tr>
</tbody>
</table>
<p id="index-16">Notes:</p>
<ol class="arabic">
<li><p id="index-17">For (plain or long) integer division, the result is an integer. The result is
always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and
(-1)/(-2) is 0.  Note that the result is a long integer if either operand is a
long integer, regardless of the numeric value.</p>
</li>
<li><p id="index-18">Conversion from floats using <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> or <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> truncates toward
zero like the related function, <a class="reference internal" href="math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a>.  Use the function
<a class="reference internal" href="math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a> to round downward and <a class="reference internal" href="math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a> to round
upward.</p>
</li>
<li><p class="first">See <a class="reference internal" href="functions.html#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a> for a full description.</p>
</li>
<li><div class="first deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The floor division operator, the modulo operator, and the <a class="reference internal" href="functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>
function are no longer defined for complex numbers.  Instead, convert to
a floating point number using the <a class="reference internal" href="functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function if appropriate.</p>
</div>
</li>
<li><p class="first">Also referred to as integer division.  The resultant value is a whole integer,
though the result’s type is not necessarily int.</p>
</li>
<li><p class="first">float also accepts the strings “nan” and “inf” with an optional prefix “+”
or “-” for Not a Number (NaN) and positive or negative infinity.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</li>
<li><p class="first">Python defines <code class="docutils literal notranslate"><span class="pre">pow(0,</span> <span class="pre">0)</span></code> and <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">**</span> <span class="pre">0</span></code> to be <code class="docutils literal notranslate"><span class="pre">1</span></code>, as is common for
programming languages.</p>
</li>
</ol>
<p>All <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> types (<a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>, and
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>) also include the following operations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="31%" />
<col width="69%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc(x)</span></code></a></td>
<td><em>x</em> truncated to <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round(x[,</span>
<span class="pre">n])</span></code></a></td>
<td><em>x</em> rounded to <em>n</em> digits,
rounding ties away from zero. If <em>n</em>
is omitted, it defaults to 0.</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor(x)</span></code></a></td>
<td>the greatest integer as a float &lt;= <em>x</em></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil(x)</span></code></a></td>
<td>the least integer as a float &gt;= <em>x</em></td>
</tr>
</tbody>
</table>
<div class="section" id="bitwise-operations-on-integer-types">
<span id="bitstring-ops"></span><h3>5.4.1. Bitwise Operations on Integer Types<a class="headerlink" href="#bitwise-operations-on-integer-types" title="Permalink to this headline">¶</a></h3>
<p id="index-19">Bitwise operations only make sense for integers.  Negative numbers are treated
as their 2’s complement value (this assumes a sufficiently large number of bits
that no overflow occurs during the operation).</p>
<p>The priorities of the binary bitwise operations are all lower than the numeric
operations and higher than the comparisons; the unary operation <code class="docutils literal notranslate"><span class="pre">~</span></code> has the
same priority as the other unary numeric operations (<code class="docutils literal notranslate"><span class="pre">+</span></code> and <code class="docutils literal notranslate"><span class="pre">-</span></code>).</p>
<p>This table lists the bitwise operations sorted in ascending priority:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="59%" />
<col width="19%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">|</span> <span class="pre">y</span></code></td>
<td>bitwise <em class="dfn">or</em> of <em>x</em> and
<em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">^</span> <span class="pre">y</span></code></td>
<td>bitwise <em class="dfn">exclusive or</em> of
<em>x</em> and <em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&amp;</span> <span class="pre">y</span></code></td>
<td>bitwise <em class="dfn">and</em> of <em>x</em> and
<em>y</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;&lt;</span> <span class="pre">n</span></code></td>
<td><em>x</em> shifted left by <em>n</em> bits</td>
<td>(1)(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;&gt;</span> <span class="pre">n</span></code></td>
<td><em>x</em> shifted right by <em>n</em> bits</td>
<td>(1)(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">~x</span></code></td>
<td>the bits of <em>x</em> inverted</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>Negative shift counts are illegal and cause a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> to be raised.</li>
<li>A left shift by <em>n</em> bits is equivalent to multiplication by <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.  A
long integer is returned if the result exceeds the range of plain integers.</li>
<li>A right shift by <em>n</em> bits is equivalent to division by <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.</li>
</ol>
</div>
<div class="section" id="additional-methods-on-integer-types">
<h3>5.4.2. Additional Methods on Integer Types<a class="headerlink" href="#additional-methods-on-integer-types" title="Permalink to this headline">¶</a></h3>
<p>The integer types implement the <a class="reference internal" href="numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base
class</span></a>. In addition, they provide one more method:</p>
<dl class="method">
<dt id="int.bit_length">
<code class="descclassname">int.</code><code class="descname">bit_length</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#int.bit_length" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<dl class="method">
<dt id="long.bit_length">
<code class="descclassname">long.</code><code class="descname">bit_length</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#long.bit_length" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of bits necessary to represent an integer in binary,
excluding the sign and leading zeros:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="o">-</span><span class="mi">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">&#39;-0b100101&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">6</span>
</pre></div>
</div>
<p>More precisely, if <code class="docutils literal notranslate"><span class="pre">x</span></code> is nonzero, then <code class="docutils literal notranslate"><span class="pre">x.bit_length()</span></code> is the
unique positive integer <code class="docutils literal notranslate"><span class="pre">k</span></code> such that <code class="docutils literal notranslate"><span class="pre">2**(k-1)</span> <span class="pre">&lt;=</span> <span class="pre">abs(x)</span> <span class="pre">&lt;</span> <span class="pre">2**k</span></code>.
Equivalently, when <code class="docutils literal notranslate"><span class="pre">abs(x)</span></code> is small enough to have a correctly
rounded logarithm, then <code class="docutils literal notranslate"><span class="pre">k</span> <span class="pre">=</span> <span class="pre">1</span> <span class="pre">+</span> <span class="pre">int(log(abs(x),</span> <span class="pre">2))</span></code>.
If <code class="docutils literal notranslate"><span class="pre">x</span></code> is zero, then <code class="docutils literal notranslate"><span class="pre">x.bit_length()</span></code> returns <code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
<p>Equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">bit_length</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="n">s</span> <span class="o">=</span> <span class="nb">bin</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>       <span class="c1"># binary representation:  bin(-37) --&gt; &#39;-0b100101&#39;</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;-0b&#39;</span><span class="p">)</span> <span class="c1"># remove leading zeros and minus sign</span>
    <span class="k">return</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>       <span class="c1"># len(&#39;100101&#39;) --&gt; 6</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="additional-methods-on-float">
<h3>5.4.3. Additional Methods on Float<a class="headerlink" href="#additional-methods-on-float" title="Permalink to this headline">¶</a></h3>
<p>The float type implements the <a class="reference internal" href="numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base
class</span></a>. float also has the following additional methods.</p>
<dl class="method">
<dt id="float.as_integer_ratio">
<code class="descclassname">float.</code><code class="descname">as_integer_ratio</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.as_integer_ratio" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pair of integers whose ratio is exactly equal to the
original float and with a positive denominator.  Raises
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> on infinities and a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> on
NaNs.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="float.is_integer">
<code class="descclassname">float.</code><code class="descname">is_integer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.is_integer" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the float instance is finite with integral
value, and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="o">-</span><span class="mf">2.0</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.2</span><span class="p">)</span><span class="o">.</span><span class="n">is_integer</span><span class="p">()</span>
<span class="go">False</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>Two methods support conversion to
and from hexadecimal strings.  Since Python’s floats are stored
internally as binary numbers, converting a float to or from a
<em>decimal</em> string usually involves a small rounding error.  In
contrast, hexadecimal strings allow exact representation and
specification of floating-point numbers.  This can be useful when
debugging, and in numerical work.</p>
<dl class="method">
<dt id="float.hex">
<code class="descclassname">float.</code><code class="descname">hex</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#float.hex" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a representation of a floating-point number as a hexadecimal
string.  For finite floating-point numbers, this representation
will always include a leading <code class="docutils literal notranslate"><span class="pre">0x</span></code> and a trailing <code class="docutils literal notranslate"><span class="pre">p</span></code> and
exponent.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="float.fromhex">
<code class="descclassname">float.</code><code class="descname">fromhex</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#float.fromhex" title="Permalink to this definition">¶</a></dt>
<dd><p>Class method to return the float represented by a hexadecimal
string <em>s</em>.  The string <em>s</em> may have leading and trailing
whitespace.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>Note that <a class="reference internal" href="#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> is an instance method, while
<a class="reference internal" href="#float.fromhex" title="float.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.fromhex()</span></code></a> is a class method.</p>
<p>A hexadecimal string takes the form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="n">sign</span><span class="p">]</span> <span class="p">[</span><span class="s1">&#39;0x&#39;</span><span class="p">]</span> <span class="n">integer</span> <span class="p">[</span><span class="s1">&#39;.&#39;</span> <span class="n">fraction</span><span class="p">]</span> <span class="p">[</span><span class="s1">&#39;p&#39;</span> <span class="n">exponent</span><span class="p">]</span>
</pre></div>
</div>
<p>where the optional <code class="docutils literal notranslate"><span class="pre">sign</span></code> may by either <code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">integer</span></code>
and <code class="docutils literal notranslate"><span class="pre">fraction</span></code> are strings of hexadecimal digits, and <code class="docutils literal notranslate"><span class="pre">exponent</span></code>
is a decimal integer with an optional leading sign.  Case is not
significant, and there must be at least one hexadecimal digit in
either the integer or the fraction.  This syntax is similar to the
syntax specified in section 6.4.4.2 of the C99 standard, and also to
the syntax used in Java 1.5 onwards.  In particular, the output of
<a class="reference internal" href="#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> is usable as a hexadecimal floating-point literal in
C or Java code, and hexadecimal strings produced by C’s <code class="docutils literal notranslate"><span class="pre">%a</span></code> format
character or Java’s <code class="docutils literal notranslate"><span class="pre">Double.toHexString</span></code> are accepted by
<a class="reference internal" href="#float.fromhex" title="float.fromhex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.fromhex()</span></code></a>.</p>
<p>Note that the exponent is written in decimal rather than hexadecimal,
and that it gives the power of 2 by which to multiply the coefficient.
For example, the hexadecimal string <code class="docutils literal notranslate"><span class="pre">0x3.a7p10</span></code> represents the
floating-point number <code class="docutils literal notranslate"><span class="pre">(3</span> <span class="pre">+</span> <span class="pre">10./16</span> <span class="pre">+</span> <span class="pre">7./16**2)</span> <span class="pre">*</span> <span class="pre">2.0**10</span></code>, or
<code class="docutils literal notranslate"><span class="pre">3740.0</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x3.a7p10&#39;</span><span class="p">)</span>
<span class="go">3740.0</span>
</pre></div>
</div>
<p>Applying the reverse conversion to <code class="docutils literal notranslate"><span class="pre">3740.0</span></code> gives a different
hexadecimal string representing the same number:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">hex</span><span class="p">(</span><span class="mf">3740.0</span><span class="p">)</span>
<span class="go">&#39;0x1.d380000000000p+11&#39;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="iterator-types">
<span id="typeiter"></span><h2>5.5. Iterator Types<a class="headerlink" href="#iterator-types" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p id="index-20">Python supports a concept of iteration over containers.  This is implemented
using two distinct methods; these are used to allow user-defined classes to
support iteration.  Sequences, described below in more detail, always support
the iteration methods.</p>
<p>One method needs to be defined for container objects to provide iteration
support:</p>
<dl class="method">
<dt id="container.__iter__">
<code class="descclassname">container.</code><code class="descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#container.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator object.  The object is required to support the iterator
protocol described below.  If a container supports different types of
iteration, additional methods can be provided to specifically request
iterators for those iteration types.  (An example of an object supporting
multiple forms of iteration would be a tree structure which supports both
breadth-first and depth-first traversal.)  This method corresponds to the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> slot of the type structure for Python objects in the Python/C
API.</p>
</dd></dl>

<p>The iterator objects themselves are required to support the following two
methods, which together form the <em class="dfn">iterator protocol</em>:</p>
<dl class="method">
<dt id="iterator.__iter__">
<code class="descclassname">iterator.</code><code class="descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#iterator.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the iterator object itself.  This is required to allow both containers
and iterators to be used with the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> and <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> statements.
This method corresponds to the <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> slot of the type structure for
Python objects in the Python/C API.</p>
</dd></dl>

<dl class="method">
<dt id="iterator.next">
<code class="descclassname">iterator.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#iterator.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next item from the container.  If there are no further items, raise
the <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception.  This method corresponds to the
<a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iternext</span></code></a> slot of the type structure for Python objects in the
Python/C API.</p>
</dd></dl>

<p>Python defines several iterator objects to support iteration over general and
specific sequence types, dictionaries, and other more specialized forms.  The
specific types are not important beyond their implementation of the iterator
protocol.</p>
<p>The intention of the protocol is that once an iterator’s <a class="reference internal" href="#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method
raises <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, it will continue to do so on subsequent calls.
Implementations that do not obey this property are deemed broken.  (This
constraint was added in Python 2.3; in Python 2.2, various iterators are broken
according to this rule.)</p>
<div class="section" id="generator-types">
<span id="id3"></span><h3>5.5.1. Generator Types<a class="headerlink" href="#generator-types" title="Permalink to this headline">¶</a></h3>
<p>Python’s <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>s provide a convenient way to implement the iterator
protocol.  If a container object’s <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method is implemented as a
generator, it will automatically return an iterator object (technically, a
generator object) supplying the <a class="reference internal" href="#iterator.__iter__" title="iterator.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and
<a class="reference internal" href="#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods.  More information about generators can be found
in <a class="reference internal" href="../reference/expressions.html#yieldexpr"><span class="std std-ref">the documentation for the yield expression</span></a>.</p>
</div>
</div>
<div class="section" id="sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange">
<span id="typesseq"></span><h2>5.6. Sequence Types — <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, <a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">buffer</span></code></a>, <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a><a class="headerlink" href="#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" title="Permalink to this headline">¶</a></h2>
<p>There are seven sequence types: strings, Unicode strings, lists, tuples,
bytearrays, buffers, and xrange objects.</p>
<p>For other containers see the built in <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> and <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> classes,
and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
<p id="index-21">String literals are written in single or double quotes: <code class="docutils literal notranslate"><span class="pre">'xyzzy'</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;frobozz&quot;</span></code>.  See <a class="reference internal" href="../reference/lexical_analysis.html#strings"><span class="std std-ref">String literals</span></a> for more about string literals.
Unicode strings are much like strings, but are specified in the syntax
using a preceding <code class="docutils literal notranslate"><span class="pre">'u'</span></code> character: <code class="docutils literal notranslate"><span class="pre">u'abc'</span></code>, <code class="docutils literal notranslate"><span class="pre">u&quot;def&quot;</span></code>. In addition
to the functionality described here, there are also string-specific
methods described in the <a class="reference internal" href="#string-methods"><span class="std std-ref">String Methods</span></a> section. Lists are
constructed with square brackets, separating items with commas: <code class="docutils literal notranslate"><span class="pre">[a,</span> <span class="pre">b,</span> <span class="pre">c]</span></code>.
Tuples are constructed by the comma operator (not within square
brackets), with or without enclosing parentheses, but an empty tuple
must have the enclosing parentheses, such as <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b,</span> <span class="pre">c</span></code> or <code class="docutils literal notranslate"><span class="pre">()</span></code>.  A
single item tuple must have a trailing comma, such as <code class="docutils literal notranslate"><span class="pre">(d,)</span></code>.</p>
<p>Bytearray objects are created with the built-in function <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a>.</p>
<p>Buffer objects are not directly supported by Python syntax, but can be created
by calling the built-in function <a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">buffer()</span></code></a>.  They don’t support
concatenation or repetition.</p>
<p>Objects of type xrange are similar to buffers in that there is no specific syntax to
create them, but they are created using the <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> function.  They don’t
support slicing, concatenation or repetition, and using <code class="docutils literal notranslate"><span class="pre">in</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code>,
<a class="reference internal" href="functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> or <a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> on them is inefficient.</p>
<p>Most sequence types support the following operations.  The <code class="docutils literal notranslate"><span class="pre">in</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code>
operations have the same priorities as the comparison operations.  The <code class="docutils literal notranslate"><span class="pre">+</span></code> and
<code class="docutils literal notranslate"><span class="pre">*</span></code> operations have the same priority as the corresponding numeric operations.
<a class="footnote-reference" href="#id14" id="id4">[3]</a> Additional methods are provided for <a class="reference internal" href="#typesseq-mutable"><span class="std std-ref">Mutable Sequence Types</span></a>.</p>
<p>This table lists the sequence operations sorted in ascending priority.
In the table, <em>s</em> and <em>t</em> are sequences of the same type; <em>n</em>, <em>i</em> and <em>j</em> are integers:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="53%" />
<col width="17%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">True</span></code> if an item of <em>s</em> is
equal to <em>x</em>, else <code class="docutils literal notranslate"><span class="pre">False</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">False</span></code> if an item of <em>s</em> is
equal to <em>x</em>, else <code class="docutils literal notranslate"><span class="pre">True</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></code></td>
<td>the concatenation of <em>s</em> and
<em>t</em></td>
<td>(6)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n,</span> <span class="pre">n</span> <span class="pre">*</span> <span class="pre">s</span></code></td>
<td>equivalent to adding <em>s</em> to
itself <em>n</em> times</td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s[i]</span></code></td>
<td><em>i</em>th item of <em>s</em>, origin 0</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s[i:j]</span></code></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em></td>
<td>(3)(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em>
with step <em>k</em></td>
<td>(3)(5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">len(s)</span></code></td>
<td>length of <em>s</em></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">min(s)</span></code></td>
<td>smallest item of <em>s</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">max(s)</span></code></td>
<td>largest item of <em>s</em></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.index(x)</span></code></td>
<td>index of the first occurrence
of <em>x</em> in <em>s</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.count(x)</span></code></td>
<td>total number of occurrences of
<em>x</em> in <em>s</em></td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Sequence types also support comparisons. In particular, tuples and lists
are compared lexicographically by comparing corresponding
elements. This means that to compare equal, every element must compare
equal and the two sequences must be of the same type and have the same
length. (For full details see <a class="reference internal" href="../reference/expressions.html#comparisons"><span class="std std-ref">Comparisons</span></a> in the language
reference.)</p>
<p id="index-22">Notes:</p>
<ol class="arabic">
<li><p class="first">When <em>s</em> is a string or Unicode string object the <code class="docutils literal notranslate"><span class="pre">in</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code>
operations act like a substring test.  In Python versions before 2.3, <em>x</em> had to
be a string of length 1. In Python 2.3 and beyond, <em>x</em> may be a string of any
length.</p>
</li>
<li><p class="first">Values of <em>n</em> less than <code class="docutils literal notranslate"><span class="pre">0</span></code> are treated as <code class="docutils literal notranslate"><span class="pre">0</span></code> (which yields an empty
sequence of the same type as <em>s</em>).  Note that items in the sequence <em>s</em>
are not copied; they are referenced multiple times.  This often haunts
new Python programmers; consider:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]]</span> <span class="o">*</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[], [], []]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [3], [3]]</span>
</pre></div>
</div>
<p>What has happened is that <code class="docutils literal notranslate"><span class="pre">[[]]</span></code> is a one-element list containing an empty
list, so all three elements of <code class="docutils literal notranslate"><span class="pre">[[]]</span> <span class="pre">*</span> <span class="pre">3</span></code> are references to this single empty
list.  Modifying any of the elements of <code class="docutils literal notranslate"><span class="pre">lists</span></code> modifies this single list.
You can create a list of different lists this way:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span> <span class="o">=</span> <span class="p">[[]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">lists</span>
<span class="go">[[3], [5], [7]]</span>
</pre></div>
</div>
<p>Further explanation is available in the FAQ entry
<a class="reference internal" href="../faq/programming.html#faq-multidimensional-list"><span class="std std-ref">How do I create a multidimensional list?</span></a>.</p>
</li>
<li><p class="first">If <em>i</em> or <em>j</em> is negative, the index is relative to the end of sequence <em>s</em>:
<code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">i</span></code> or <code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">+</span> <span class="pre">j</span></code> is substituted.  But note that <code class="docutils literal notranslate"><span class="pre">-0</span></code> is still
<code class="docutils literal notranslate"><span class="pre">0</span></code>.</p>
</li>
<li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> is defined as the sequence of items with index
<em>k</em> such that <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span> <span class="pre">j</span></code>.  If <em>i</em> or <em>j</em> is greater than <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>, use
<code class="docutils literal notranslate"><span class="pre">len(s)</span></code>.  If <em>i</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, use <code class="docutils literal notranslate"><span class="pre">0</span></code>.  If <em>j</em> is omitted or
<code class="docutils literal notranslate"><span class="pre">None</span></code>, use <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>.  If <em>i</em> is greater than or equal to <em>j</em>, the slice is
empty.</p>
</li>
<li><p class="first">The slice of <em>s</em> from <em>i</em> to <em>j</em> with step <em>k</em> is defined as the sequence of
items with index  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code> such that <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">n</span> <span class="pre">&lt;</span> <span class="pre">(j-i)/k</span></code>.  In other words,
the indices are <code class="docutils literal notranslate"><span class="pre">i</span></code>, <code class="docutils literal notranslate"><span class="pre">i+k</span></code>, <code class="docutils literal notranslate"><span class="pre">i+2*k</span></code>, <code class="docutils literal notranslate"><span class="pre">i+3*k</span></code> and so on, stopping when
<em>j</em> is reached (but never including <em>j</em>).  When <em>k</em> is positive,
<em>i</em> and <em>j</em> are reduced to <code class="docutils literal notranslate"><span class="pre">len(s)</span></code> if they are greater.
When <em>k</em> is negative, <em>i</em> and <em>j</em> are reduced to <code class="docutils literal notranslate"><span class="pre">len(s)</span> <span class="pre">-</span> <span class="pre">1</span></code> if
they are greater.  If <em>i</em> or <em>j</em> are omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, they become
“end” values (which end depends on the sign of <em>k</em>).  Note, <em>k</em> cannot be zero.
If <em>k</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is treated like <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</li>
<li><div class="impl-detail first compound">
<p><strong>CPython implementation detail:</strong> If <em>s</em> and <em>t</em> are both strings, some Python implementations such as
CPython can usually perform an in-place optimization for assignments of
the form <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">=</span> <span class="pre">s</span> <span class="pre">+</span> <span class="pre">t</span></code> or <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+=</span> <span class="pre">t</span></code>.  When applicable, this optimization
makes quadratic run-time much less likely.  This optimization is both
version and implementation dependent.  For performance sensitive code, it
is preferable to use the <a class="reference internal" href="#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.join()</span></code></a> method which assures consistent
linear concatenation performance across versions and implementations.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, string concatenation never occurred in-place.</p>
</div>
</li>
</ol>
<div class="section" id="string-methods">
<span id="id5"></span><h3>5.6.1. String Methods<a class="headerlink" href="#string-methods" title="Permalink to this headline">¶</a></h3>
<p id="index-23">Below are listed the string methods which both 8-bit strings and
Unicode objects support.  Some of them are also available on <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>
objects.</p>
<p>In addition, Python’s strings support the sequence type methods
described in the <a class="reference internal" href="#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a> section. To output formatted strings
use template strings or the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator described in the
<a class="reference internal" href="#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section. Also, see the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module for
string functions based on regular expressions.</p>
<dl class="method">
<dt id="str.capitalize">
<code class="descclassname">str.</code><code class="descname">capitalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.capitalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with its first character capitalized and the
rest lowercased.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.center">
<code class="descclassname">str.</code><code class="descname">center</code><span class="sig-paren">(</span><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.center" title="Permalink to this definition">¶</a></dt>
<dd><p>Return centered in a string of length <em>width</em>. Padding is done using the
specified <em>fillchar</em> (default is a space).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.count">
<code class="descclassname">str.</code><code class="descname">count</code><span class="sig-paren">(</span><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of non-overlapping occurrences of substring <em>sub</em> in the
range [<em>start</em>, <em>end</em>].  Optional arguments <em>start</em> and <em>end</em> are
interpreted as in slice notation.</p>
</dd></dl>

<dl class="method">
<dt id="str.decode">
<code class="descclassname">str.</code><code class="descname">decode</code><span class="sig-paren">(</span><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Decodes the string using the codec registered for <em>encoding</em>. <em>encoding</em>
defaults to the default string encoding.  <em>errors</em> may be given to set a
different error handling scheme.  The default is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>, meaning that
encoding errors raise <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.  Other possible values are
<code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> and any other name registered via
<a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a>, see section <a class="reference internal" href="codecs.html#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Support for other error handling schemes added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for keyword arguments added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.encode">
<code class="descclassname">str.</code><code class="descname">encode</code><span class="sig-paren">(</span><span class="optional">[</span><em>encoding</em><span class="optional">[</span>, <em>errors</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an encoded version of the string.  Default encoding is the current
default string encoding.  <em>errors</em> may be given to set a different error
handling scheme.  The default for <em>errors</em> is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>, meaning that
encoding errors raise a <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.  Other possible values are
<code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, <code class="docutils literal notranslate"><span class="pre">'replace'</span></code>, <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code>, <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> and
any other name registered via <a class="reference internal" href="codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a>, see section
<a class="reference internal" href="codecs.html#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a>. For a list of possible encodings, see section
<a class="reference internal" href="codecs.html#standard-encodings"><span class="std std-ref">Standard Encodings</span></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Support for <code class="docutils literal notranslate"><span class="pre">'xmlcharrefreplace'</span></code> and <code class="docutils literal notranslate"><span class="pre">'backslashreplace'</span></code> and other error
handling schemes added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for keyword arguments added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.endswith">
<code class="descclassname">str.</code><code class="descname">endswith</code><span class="sig-paren">(</span><em>suffix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.endswith" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the string ends with the specified <em>suffix</em>, otherwise return
<code class="docutils literal notranslate"><span class="pre">False</span></code>.  <em>suffix</em> can also be a tuple of suffixes to look for.  With optional
<em>start</em>, test beginning at that position.  With optional <em>end</em>, stop comparing
at that position.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Accept tuples as <em>suffix</em>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.expandtabs">
<code class="descclassname">str.</code><code class="descname">expandtabs</code><span class="sig-paren">(</span><span class="optional">[</span><em>tabsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.expandtabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string where all tab characters are replaced by one or
more spaces, depending on the current column and the given tab size.  Tab
positions occur every <em>tabsize</em> characters (default is 8, giving tab
positions at columns 0, 8, 16 and so on).  To expand the string, the current
column is set to zero and the string is examined character by character.  If
the character is a tab (<code class="docutils literal notranslate"><span class="pre">\t</span></code>), one or more space characters are inserted
in the result until the current column is equal to the next tab position.
(The tab character itself is not copied.)  If the character is a newline
(<code class="docutils literal notranslate"><span class="pre">\n</span></code>) or return (<code class="docutils literal notranslate"><span class="pre">\r</span></code>), it is copied and the current column is reset to
zero.  Any other character is copied unchanged and the current column is
incremented by one regardless of how the character is represented when
printed.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">()</span>
<span class="go">&#39;01      012     0123    01234&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;01</span><span class="se">\t</span><span class="s1">012</span><span class="se">\t</span><span class="s1">0123</span><span class="se">\t</span><span class="s1">01234&#39;</span><span class="o">.</span><span class="n">expandtabs</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">&#39;01  012 0123    01234&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.find">
<code class="descclassname">str.</code><code class="descname">find</code><span class="sig-paren">(</span><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the lowest index in the string where substring <em>sub</em> is found within
the slice <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code>.  Optional arguments <em>start</em> and <em>end</em> are
interpreted as in slice notation.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> if <em>sub</em> is not found.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The <a class="reference internal" href="#str.find" title="str.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> method should be used only if you need to know the
position of <em>sub</em>.  To check if <em>sub</em> is a substring or not, use the
<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Py&#39;</span> <span class="ow">in</span> <span class="s1">&#39;Python&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="method">
<dt id="str.format">
<code class="descclassname">str.</code><code class="descname">format</code><span class="sig-paren">(</span><em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#str.format" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform a string formatting operation.  The string on which this method is
called can contain literal text or replacement fields delimited by braces
<code class="docutils literal notranslate"><span class="pre">{}</span></code>.  Each replacement field contains either the numeric index of a
positional argument, or the name of a keyword argument.  Returns a copy of
the string where each replacement field is replaced with the string value of
the corresponding argument.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;The sum of 1 + 2 is </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">1</span><span class="o">+</span><span class="mi">2</span><span class="p">)</span>
<span class="go">&#39;The sum of 1 + 2 is 3&#39;</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a> for a description of the various formatting options
that can be specified in format strings.</p>
<p>This method of string formatting is the new standard in Python 3, and
should be preferred to the <code class="docutils literal notranslate"><span class="pre">%</span></code> formatting described in
<a class="reference internal" href="#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> in new code.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.index">
<code class="descclassname">str.</code><code class="descname">index</code><span class="sig-paren">(</span><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#str.find" title="str.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a>, but raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> when the substring is not found.</p>
</dd></dl>

<dl class="method">
<dt id="str.isalnum">
<code class="descclassname">str.</code><code class="descname">isalnum</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isalnum" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are alphanumeric and there is at
least one character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.isalpha">
<code class="descclassname">str.</code><code class="descname">isalpha</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isalpha" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are alphabetic and there is at least
one character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.isdigit">
<code class="descclassname">str.</code><code class="descname">isdigit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isdigit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all characters in the string are digits and there is at least one
character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.islower">
<code class="descclassname">str.</code><code class="descname">islower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.islower" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all cased characters <a class="footnote-reference" href="#id15" id="id6">[4]</a> in the string are lowercase and there is at
least one cased character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.isspace">
<code class="descclassname">str.</code><code class="descname">isspace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isspace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if there are only whitespace characters in the string and there is
at least one character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.istitle">
<code class="descclassname">str.</code><code class="descname">istitle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.istitle" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased characters
and lowercase characters only cased ones.  Return false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.isupper">
<code class="descclassname">str.</code><code class="descname">isupper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.isupper" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if all cased characters <a class="footnote-reference" href="#id15" id="id7">[4]</a> in the string are uppercase and there is at
least one cased character, false otherwise.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.join">
<code class="descclassname">str.</code><code class="descname">join</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#str.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string which is the concatenation of the strings in <em>iterable</em>.
If there is any Unicode object in <em>iterable</em>, return a Unicode instead.
A <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised if there are any non-string or non Unicode
object values in <em>iterable</em>.  The separator between elements is the string
providing this method.</p>
</dd></dl>

<dl class="method">
<dt id="str.ljust">
<code class="descclassname">str.</code><code class="descname">ljust</code><span class="sig-paren">(</span><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.ljust" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string left justified in a string of length <em>width</em>. Padding is done
using the specified <em>fillchar</em> (default is a space).  The original string is
returned if <em>width</em> is less than or equal to <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.lower">
<code class="descclassname">str.</code><code class="descname">lower</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.lower" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id15" id="id8">[4]</a> converted to
lowercase.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.lstrip">
<code class="descclassname">str.</code><code class="descname">lstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.lstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with leading characters removed.  The <em>chars</em>
argument is a string specifying the set of characters to be removed.  If omitted
or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <em>chars</em> argument defaults to removing whitespace.  The <em>chars</em>
argument is not a prefix; rather, all combinations of its values are stripped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">()</span>
<span class="go">&#39;spacious   &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">lstrip</span><span class="p">(</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example.com&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.partition">
<code class="descclassname">str.</code><code class="descname">partition</code><span class="sig-paren">(</span><em>sep</em><span class="sig-paren">)</span><a class="headerlink" href="#str.partition" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the string at the first occurrence of <em>sep</em>, and return a 3-tuple
containing the part before the separator, the separator itself, and the part
after the separator.  If the separator is not found, return a 3-tuple containing
the string itself, followed by two empty strings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.replace">
<code class="descclassname">str.</code><code class="descname">replace</code><span class="sig-paren">(</span><em>old</em>, <em>new</em><span class="optional">[</span>, <em>count</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all occurrences of substring <em>old</em> replaced by
<em>new</em>.  If the optional argument <em>count</em> is given, only the first <em>count</em>
occurrences are replaced.</p>
</dd></dl>

<dl class="method">
<dt id="str.rfind">
<code class="descclassname">str.</code><code class="descname">rfind</code><span class="sig-paren">(</span><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the highest index in the string where substring <em>sub</em> is found, such
that <em>sub</em> is contained within <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code>.  Optional arguments <em>start</em>
and <em>end</em> are interpreted as in slice notation.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.</p>
</dd></dl>

<dl class="method">
<dt id="str.rindex">
<code class="descclassname">str.</code><code class="descname">rindex</code><span class="sig-paren">(</span><em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rindex" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#str.rfind" title="str.rfind"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code></a> but raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> when the substring <em>sub</em> is not
found.</p>
</dd></dl>

<dl class="method">
<dt id="str.rjust">
<code class="descclassname">str.</code><code class="descname">rjust</code><span class="sig-paren">(</span><em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rjust" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the string right justified in a string of length <em>width</em>. Padding is done
using the specified <em>fillchar</em> (default is a space). The original string is
returned if <em>width</em> is less than or equal to <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Support for the <em>fillchar</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.rpartition">
<code class="descclassname">str.</code><code class="descname">rpartition</code><span class="sig-paren">(</span><em>sep</em><span class="sig-paren">)</span><a class="headerlink" href="#str.rpartition" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the string at the last occurrence of <em>sep</em>, and return a 3-tuple
containing the part before the separator, the separator itself, and the part
after the separator.  If the separator is not found, return a 3-tuple containing
two empty strings, followed by the string itself.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.rsplit">
<code class="descclassname">str.</code><code class="descname">rsplit</code><span class="sig-paren">(</span><span class="optional">[</span><em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rsplit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter string.
If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done, the <em>rightmost</em>
ones.  If <em>sep</em> is not specified or <code class="docutils literal notranslate"><span class="pre">None</span></code>, any whitespace string is a
separator.  Except for splitting from the right, <a class="reference internal" href="#str.rsplit" title="str.rsplit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rsplit()</span></code></a> behaves like
<a class="reference internal" href="#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> which is described in detail below.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.rstrip">
<code class="descclassname">str.</code><code class="descname">rstrip</code><span class="sig-paren">(</span><span class="optional">[</span><em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.rstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with trailing characters removed.  The <em>chars</em>
argument is a string specifying the set of characters to be removed.  If omitted
or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <em>chars</em> argument defaults to removing whitespace.  The <em>chars</em>
argument is not a suffix; rather, all combinations of its values are stripped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
<span class="go">&#39;   spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;mississippi&#39;</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s1">&#39;ipz&#39;</span><span class="p">)</span>
<span class="go">&#39;mississ&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.split">
<code class="descclassname">str.</code><code class="descname">split</code><span class="sig-paren">(</span><span class="optional">[</span><em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words in the string, using <em>sep</em> as the delimiter
string.  If <em>maxsplit</em> is given, at most <em>maxsplit</em> splits are done (thus,
the list will have at most <code class="docutils literal notranslate"><span class="pre">maxsplit+1</span></code> elements).  If <em>maxsplit</em> is not
specified or <code class="docutils literal notranslate"><span class="pre">-1</span></code>, then there is no limit on the number of splits
(all possible splits are made).</p>
<p>If <em>sep</em> is given, consecutive delimiters are not grouped together and are
deemed to delimit empty strings (for example, <code class="docutils literal notranslate"><span class="pre">'1,,2'.split(',')</span></code> returns
<code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'',</span> <span class="pre">'2']</span></code>).  The <em>sep</em> argument may consist of multiple characters
(for example, <code class="docutils literal notranslate"><span class="pre">'1&lt;&gt;2&lt;&gt;3'.split('&lt;&gt;')</span></code> returns <code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></code>).
Splitting an empty string with a specified separator returns <code class="docutils literal notranslate"><span class="pre">['']</span></code>.</p>
<p>If <em>sep</em> is not specified or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, a different splitting algorithm is
applied: runs of consecutive whitespace are regarded as a single separator,
and the result will contain no empty strings at the start or end if the
string has leading or trailing whitespace.  Consequently, splitting an empty
string or a string consisting of just whitespace with a <code class="docutils literal notranslate"><span class="pre">None</span></code> separator
returns <code class="docutils literal notranslate"><span class="pre">[]</span></code>.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">1</span>&#160; <span class="pre">2</span>&#160;&#160; <span class="pre">3</span>&#160; <span class="pre">'.split()</span></code> returns <code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'2',</span> <span class="pre">'3']</span></code>, and
<code class="docutils literal notranslate"><span class="pre">'</span>&#160; <span class="pre">1</span>&#160; <span class="pre">2</span>&#160;&#160; <span class="pre">3</span>&#160; <span class="pre">'.split(None,</span> <span class="pre">1)</span></code> returns <code class="docutils literal notranslate"><span class="pre">['1',</span> <span class="pre">'2</span>&#160;&#160; <span class="pre">3</span>&#160; <span class="pre">']</span></code>.</p>
</dd></dl>

<span class="target" id="index-24"></span><dl class="method">
<dt id="str.splitlines">
<code class="descclassname">str.</code><code class="descname">splitlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>keepends</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.splitlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the lines in the string, breaking at line boundaries.
This method uses the <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> approach to splitting lines.
Line breaks are not included in the resulting list unless <em>keepends</em> is
given and true.</p>
<p>Python recognizes <code class="docutils literal notranslate"><span class="pre">&quot;\r&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;\n&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;\r\n&quot;</span></code> as line boundaries for
8-bit strings.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[&#39;ab c&#39;, &#39;&#39;, &#39;de fg&#39;, &#39;kl&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab c</span><span class="se">\n\n</span><span class="s1">de fg</span><span class="se">\r</span><span class="s1">kl</span><span class="se">\r\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="go">[&#39;ab c\n&#39;, &#39;\n&#39;, &#39;de fg\r&#39;, &#39;kl\r\n&#39;]</span>
</pre></div>
</div>
<p>Unlike <a class="reference internal" href="#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code></a> when a delimiter string <em>sep</em> is given, this
method returns an empty list for the empty string, and a terminal line
break does not result in an extra line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;One line</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
<span class="go">[&#39;One line&#39;]</span>
</pre></div>
</div>
<p>For comparison, <code class="docutils literal notranslate"><span class="pre">split('\n')</span></code> gives:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">[&#39;&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Two lines</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">[&#39;Two lines&#39;, &#39;&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="unicode.splitlines">
<code class="descclassname">unicode.</code><code class="descname">splitlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>keepends</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unicode.splitlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the lines in the string, like <a class="reference internal" href="#str.splitlines" title="str.splitlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.splitlines()</span></code></a>.
However, the Unicode method splits on the following line boundaries,
which are a superset of the <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> recognized for
8-bit strings.</p>
<table border="1" class="docutils">
<colgroup>
<col width="44%" />
<col width="56%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Representation</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\n</span></code></td>
<td>Line Feed</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\r</span></code></td>
<td>Carriage Return</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\r\n</span></code></td>
<td>Carriage Return + Line Feed</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\v</span></code> or <code class="docutils literal notranslate"><span class="pre">\x0b</span></code></td>
<td>Line Tabulation</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\f</span></code> or <code class="docutils literal notranslate"><span class="pre">\x0c</span></code></td>
<td>Form Feed</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\x1c</span></code></td>
<td>File Separator</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\x1d</span></code></td>
<td>Group Separator</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\x1e</span></code></td>
<td>Record Separator</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\x85</span></code></td>
<td>Next Line (C1 Control Code)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\u2028</span></code></td>
<td>Line Separator</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\u2029</span></code></td>
<td>Paragraph Separator</td>
</tr>
</tbody>
</table>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><code class="docutils literal notranslate"><span class="pre">\v</span></code> and <code class="docutils literal notranslate"><span class="pre">\f</span></code> added to list of line boundaries.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.startswith">
<code class="descclassname">str.</code><code class="descname">startswith</code><span class="sig-paren">(</span><em>prefix</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.startswith" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if string starts with the <em>prefix</em>, otherwise return <code class="docutils literal notranslate"><span class="pre">False</span></code>.
<em>prefix</em> can also be a tuple of prefixes to look for.  With optional <em>start</em>,
test string beginning at that position.  With optional <em>end</em>, stop comparing
string at that position.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Accept tuples as <em>prefix</em>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.strip">
<code class="descclassname">str.</code><code class="descname">strip</code><span class="sig-paren">(</span><span class="optional">[</span><em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.strip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with the leading and trailing characters removed.
The <em>chars</em> argument is a string specifying the set of characters to be removed.
If omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the <em>chars</em> argument defaults to removing whitespace.
The <em>chars</em> argument is not a prefix or suffix; rather, all combinations of its
values are stripped:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   spacious   &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">&#39;spacious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.example.com&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;cmowz.&#39;</span><span class="p">)</span>
<span class="go">&#39;example&#39;</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.2: </span>Support for the <em>chars</em> argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="str.swapcase">
<code class="descclassname">str.</code><code class="descname">swapcase</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.swapcase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with uppercase characters converted to lowercase and
vice versa.</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.title">
<code class="descclassname">str.</code><code class="descname">title</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.title" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a titlecased version of the string where words start with an uppercase
character and the remaining characters are lowercase.</p>
<p>The algorithm uses a simple language-independent definition of a word as
groups of consecutive letters.  The definition works in many contexts but
it means that apostrophes in contractions and possessives form word
boundaries, which may not be the desired result:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;they&#39;re bill&#39;s friends from the UK&quot;</span><span class="o">.</span><span class="n">title</span><span class="p">()</span>
<span class="go">&quot;They&#39;Re Bill&#39;S Friends From The Uk&quot;</span>
</pre></div>
</div>
<p>A workaround for apostrophes can be constructed using regular expressions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">titlecase</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s2">&quot;[A-Za-z]+(&#39;[A-Za-z]+)?&quot;</span><span class="p">,</span>
<span class="gp">... </span>                  <span class="k">lambda</span> <span class="n">mo</span><span class="p">:</span> <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span> <span class="o">+</span>
<span class="gp">... </span>                             <span class="n">mo</span><span class="o">.</span><span class="n">group</span><span class="p">(</span><span class="mi">0</span><span class="p">)[</span><span class="mi">1</span><span class="p">:]</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span>
<span class="gp">... </span>                  <span class="n">s</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">titlecase</span><span class="p">(</span><span class="s2">&quot;they&#39;re bill&#39;s friends.&quot;</span><span class="p">)</span>
<span class="go">&quot;They&#39;re Bill&#39;s Friends.&quot;</span>
</pre></div>
</div>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.translate">
<code class="descclassname">str.</code><code class="descname">translate</code><span class="sig-paren">(</span><em>table</em><span class="optional">[</span>, <em>deletechars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#str.translate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string where all characters occurring in the optional
argument <em>deletechars</em> are removed, and the remaining characters have been
mapped through the given translation table, which must be a string of length
256.</p>
<p>You can use the <a class="reference internal" href="string.html#string.maketrans" title="string.maketrans"><code class="xref py py-func docutils literal notranslate"><span class="pre">maketrans()</span></code></a> helper function in the <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a>
module to create a translation table. For string objects, set the <em>table</em>
argument to <code class="docutils literal notranslate"><span class="pre">None</span></code> for translations that only delete characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;read this short text&#39;</span><span class="o">.</span><span class="n">translate</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s1">&#39;aeiou&#39;</span><span class="p">)</span>
<span class="go">&#39;rd ths shrt txt&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Support for a <code class="docutils literal notranslate"><span class="pre">None</span></code> <em>table</em> argument.</p>
</div>
<p>For Unicode objects, the <a class="reference internal" href="#str.translate" title="str.translate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code></a> method does not accept the optional
<em>deletechars</em> argument.  Instead, it returns a copy of the <em>s</em> where all
characters have been mapped through the given translation table which must be a
mapping of Unicode ordinals to Unicode ordinals, Unicode strings or <code class="docutils literal notranslate"><span class="pre">None</span></code>.
Unmapped characters are left untouched. Characters mapped to <code class="docutils literal notranslate"><span class="pre">None</span></code> are
deleted.  Note, a more flexible approach is to create a custom character mapping
codec using the <a class="reference internal" href="codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module (see <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings.cp1251</span></code> for an
example).</p>
</dd></dl>

<dl class="method">
<dt id="str.upper">
<code class="descclassname">str.</code><code class="descname">upper</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#str.upper" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with all the cased characters <a class="footnote-reference" href="#id15" id="id9">[4]</a> converted to
uppercase.  Note that <code class="docutils literal notranslate"><span class="pre">s.upper().isupper()</span></code> might be <code class="docutils literal notranslate"><span class="pre">False</span></code> if <code class="docutils literal notranslate"><span class="pre">s</span></code>
contains uncased characters or if the Unicode category of the resulting
character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).</p>
<p>For 8-bit strings, this method is locale-dependent.</p>
</dd></dl>

<dl class="method">
<dt id="str.zfill">
<code class="descclassname">str.</code><code class="descname">zfill</code><span class="sig-paren">(</span><em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#str.zfill" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the numeric string left filled with zeros in a string of length
<em>width</em>.  A sign prefix is handled correctly.  The original string is
returned if <em>width</em> is less than or equal to <code class="docutils literal notranslate"><span class="pre">len(s)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.2.</span></p>
</div>
</dd></dl>

<p>The following methods are present only on unicode objects:</p>
<dl class="method">
<dt id="unicode.isnumeric">
<code class="descclassname">unicode.</code><code class="descname">isnumeric</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unicode.isnumeric" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there are only numeric characters in S, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise. Numeric characters include digit characters, and all characters
that have the Unicode numeric value property, e.g. U+2155,
VULGAR FRACTION ONE FIFTH.</p>
</dd></dl>

<dl class="method">
<dt id="unicode.isdecimal">
<code class="descclassname">unicode.</code><code class="descname">isdecimal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unicode.isdecimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if there are only decimal characters in S, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise. Decimal characters include digit characters, and all characters
that can be used to form decimal-radix numbers, e.g. U+0660,
ARABIC-INDIC DIGIT ZERO.</p>
</dd></dl>

</div>
<div class="section" id="string-formatting-operations">
<span id="string-formatting"></span><h3>5.6.2. String Formatting Operations<a class="headerlink" href="#string-formatting-operations" title="Permalink to this headline">¶</a></h3>
<p id="index-25">String and Unicode objects have one unique built-in operation: the <code class="docutils literal notranslate"><span class="pre">%</span></code>
operator (modulo).  This is also known as the string <em>formatting</em> or
<em>interpolation</em> operator.  Given <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></code> (where <em>format</em> is a string
or Unicode object), <code class="docutils literal notranslate"><span class="pre">%</span></code> conversion specifications in <em>format</em> are replaced
with zero or more elements of <em>values</em>.  The effect is similar to the using
<code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code> in the C language.  If <em>format</em> is a Unicode object, or if any
of the objects being converted using the <code class="docutils literal notranslate"><span class="pre">%s</span></code> conversion are Unicode objects,
the result will also be a Unicode object.</p>
<p>If <em>format</em> requires a single argument, <em>values</em> may be a single non-tuple
object. <a class="footnote-reference" href="#id16" id="id10">[5]</a>  Otherwise, <em>values</em> must be a tuple with exactly the number of
items specified by the format string, or a single mapping object (for example, a
dictionary).</p>
<p>A conversion specifier contains two or more characters and has the following
components, which must occur in this order:</p>
<ol class="arabic simple">
<li>The <code class="docutils literal notranslate"><span class="pre">'%'</span></code> character, which marks the start of the specifier.</li>
<li>Mapping key (optional), consisting of a parenthesised sequence of characters
(for example, <code class="docutils literal notranslate"><span class="pre">(somename)</span></code>).</li>
<li>Conversion flags (optional), which affect the result of some conversion
types.</li>
<li>Minimum field width (optional).  If specified as an <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (asterisk), the
actual width is read from the next element of the tuple in <em>values</em>, and the
object to convert comes after the minimum field width and optional precision.</li>
<li>Precision (optional), given as a <code class="docutils literal notranslate"><span class="pre">'.'</span></code> (dot) followed by the precision.  If
specified as <code class="docutils literal notranslate"><span class="pre">'*'</span></code> (an asterisk), the actual width is read from the next
element of the tuple in <em>values</em>, and the value to convert comes after the
precision.</li>
<li>Length modifier (optional).</li>
<li>Conversion type.</li>
</ol>
<p>When the right argument is a dictionary (or other mapping type), then the
formats in the string <em>must</em> include a parenthesised mapping key into that
dictionary inserted immediately after the <code class="docutils literal notranslate"><span class="pre">'%'</span></code> character. The mapping key
selects the value to be formatted from the mapping.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%(language)s</span><span class="s1"> has </span><span class="si">%(number)03d</span><span class="s1"> quote types.&#39;</span> <span class="o">%</span> \
<span class="gp">... </span>      <span class="p">{</span><span class="s2">&quot;language&quot;</span><span class="p">:</span> <span class="s2">&quot;Python&quot;</span><span class="p">,</span> <span class="s2">&quot;number&quot;</span><span class="p">:</span> <span class="mi">2</span><span class="p">}</span>
<span class="go">Python has 002 quote types.</span>
</pre></div>
</div>
<p>In this case no <code class="docutils literal notranslate"><span class="pre">*</span></code> specifiers may occur in a format (since they require a
sequential parameter list).</p>
<p>The conversion flag characters are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="88%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Flag</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'#'</span></code></td>
<td>The value conversion will use the “alternate form” (where defined
below).</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'0'</span></code></td>
<td>The conversion will be zero padded for numeric values.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'-'</span></code></td>
<td>The converted value is left adjusted (overrides the <code class="docutils literal notranslate"><span class="pre">'0'</span></code>
conversion if both are given).</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code></td>
<td>(a space) A blank should be left before a positive number (or empty
string) produced by a signed conversion.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'+'</span></code></td>
<td>A sign character (<code class="docutils literal notranslate"><span class="pre">'+'</span></code> or <code class="docutils literal notranslate"><span class="pre">'-'</span></code>) will precede the conversion
(overrides a “space” flag).</td>
</tr>
</tbody>
</table>
<p>A length modifier (<code class="docutils literal notranslate"><span class="pre">h</span></code>, <code class="docutils literal notranslate"><span class="pre">l</span></code>, or <code class="docutils literal notranslate"><span class="pre">L</span></code>) may be present, but is ignored as it
is not necessary for Python – so e.g. <code class="docutils literal notranslate"><span class="pre">%ld</span></code> is identical to <code class="docutils literal notranslate"><span class="pre">%d</span></code>.</p>
<p>The conversion types are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="74%" />
<col width="10%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Conversion</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'d'</span></code></td>
<td>Signed integer decimal.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'i'</span></code></td>
<td>Signed integer decimal.</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'o'</span></code></td>
<td>Signed octal value.</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'u'</span></code></td>
<td>Obsolete type – it is identical to <code class="docutils literal notranslate"><span class="pre">'d'</span></code>.</td>
<td>(7)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'x'</span></code></td>
<td>Signed hexadecimal (lowercase).</td>
<td>(2)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'X'</span></code></td>
<td>Signed hexadecimal (uppercase).</td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'e'</span></code></td>
<td>Floating point exponential format (lowercase).</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'E'</span></code></td>
<td>Floating point exponential format (uppercase).</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'f'</span></code></td>
<td>Floating point decimal format.</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'F'</span></code></td>
<td>Floating point decimal format.</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'g'</span></code></td>
<td>Floating point format. Uses lowercase exponential
format if exponent is less than -4 or not less than
precision, decimal format otherwise.</td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'G'</span></code></td>
<td>Floating point format. Uses uppercase exponential
format if exponent is less than -4 or not less than
precision, decimal format otherwise.</td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Single character (accepts integer or single
character string).</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'r'</span></code></td>
<td>String (converts any Python object using
<a class="reference internal" href="functions.html#func-repr"><span class="std std-ref">repr()</span></a>).</td>
<td>(5)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'s'</span></code></td>
<td>String (converts any Python object using
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>).</td>
<td>(6)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'%'</span></code></td>
<td>No argument is converted, results in a <code class="docutils literal notranslate"><span class="pre">'%'</span></code>
character in the result.</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">The alternate form causes a leading zero (<code class="docutils literal notranslate"><span class="pre">'0'</span></code>) to be inserted between
left-hand padding and the formatting of the number if the leading character
of the result is not already a zero.</p>
</li>
<li><p class="first">The alternate form causes a leading <code class="docutils literal notranslate"><span class="pre">'0x'</span></code> or <code class="docutils literal notranslate"><span class="pre">'0X'</span></code> (depending on whether
the <code class="docutils literal notranslate"><span class="pre">'x'</span></code> or <code class="docutils literal notranslate"><span class="pre">'X'</span></code> format was used) to be inserted before the first digit.</p>
</li>
<li><p class="first">The alternate form causes the result to always contain a decimal point, even if
no digits follow it.</p>
<p>The precision determines the number of digits after the decimal point and
defaults to 6.</p>
</li>
<li><p class="first">The alternate form causes the result to always contain a decimal point, and
trailing zeroes are not removed as they would otherwise be.</p>
<p>The precision determines the number of significant digits before and after the
decimal point and defaults to 6.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">%r</span></code> conversion was added in Python 2.0.</p>
<p>The precision determines the maximal number of characters used.</p>
</li>
<li><p class="first">If the object or format provided is a <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> string, the resulting
string will also be <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.</p>
<p>The precision determines the maximal number of characters used.</p>
</li>
<li><p class="first">See <span class="target" id="index-26"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>.</p>
</li>
</ol>
<p>Since Python strings have an explicit length, <code class="docutils literal notranslate"><span class="pre">%s</span></code> conversions do not assume
that <code class="docutils literal notranslate"><span class="pre">'\0'</span></code> is the end of the string.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><code class="docutils literal notranslate"><span class="pre">%f</span></code> conversions for numbers whose absolute value is over 1e50 are no
longer replaced by <code class="docutils literal notranslate"><span class="pre">%g</span></code> conversions.</p>
</div>
<p id="index-27">Additional string operations are defined in standard modules <a class="reference internal" href="string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> and
<a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>.</p>
</div>
<div class="section" id="xrange-type">
<span id="typesseq-xrange"></span><h3>5.6.3. XRange Type<a class="headerlink" href="#xrange-type" title="Permalink to this headline">¶</a></h3>
<p id="index-28">The <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a> type is an immutable sequence which is commonly used for
looping.  The advantage of the <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a> type is that an <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a>
object will always take the same amount of memory, no matter the size of the
range it represents.  There are no consistent performance advantages.</p>
<p>XRange objects have very little behavior: they only support indexing, iteration,
and the <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> function.</p>
</div>
<div class="section" id="mutable-sequence-types">
<span id="typesseq-mutable"></span><h3>5.6.4. Mutable Sequence Types<a class="headerlink" href="#mutable-sequence-types" title="Permalink to this headline">¶</a></h3>
<p id="index-29">List and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> objects support additional operations that allow
in-place modification of the object. Other mutable sequence types (when added
to the language) should also support these operations. Strings and tuples
are immutable sequence types: such objects cannot be modified once created.
The following operations are defined on mutable sequence types (where <em>x</em> is
an arbitrary object):</p>
<table border="1" class="docutils" id="index-30">
<colgroup>
<col width="36%" />
<col width="39%" />
<col width="25%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s[i]</span> <span class="pre">=</span> <span class="pre">x</span></code></td>
<td>item <em>i</em> of <em>s</em> is replaced by
<em>x</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">t</span></code></td>
<td>slice of <em>s</em> from <em>i</em> to <em>j</em>
is replaced by the contents of
the iterable <em>t</em></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[i:j]</span></code></td>
<td>same as <code class="docutils literal notranslate"><span class="pre">s[i:j]</span> <span class="pre">=</span> <span class="pre">[]</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span> <span class="pre">=</span> <span class="pre">t</span></code></td>
<td>the elements of <code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code>
are replaced by those of <em>t</em></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[i:j:k]</span></code></td>
<td>removes the elements of
<code class="docutils literal notranslate"><span class="pre">s[i:j:k]</span></code> from the list</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.append(x)</span></code></td>
<td>same as <code class="docutils literal notranslate"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span>
<span class="pre">[x]</span></code></td>
<td>(2)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.extend(t)</span></code> or
<code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+=</span> <span class="pre">t</span></code></td>
<td>for the most part the same as
<code class="docutils literal notranslate"><span class="pre">s[len(s):len(s)]</span> <span class="pre">=</span> <span class="pre">t</span></code></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*=</span> <span class="pre">n</span></code></td>
<td>updates <em>s</em> with its contents
repeated <em>n</em> times</td>
<td>(11)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.count(x)</span></code></td>
<td>return number of <em>i</em>’s for
which <code class="docutils literal notranslate"><span class="pre">s[i]</span> <span class="pre">==</span> <span class="pre">x</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.index(x[,</span> <span class="pre">i[,</span> <span class="pre">j]])</span></code></td>
<td>return smallest <em>k</em> such that
<code class="docutils literal notranslate"><span class="pre">s[k]</span> <span class="pre">==</span> <span class="pre">x</span></code> and <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span>
<span class="pre">j</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.insert(i,</span> <span class="pre">x)</span></code></td>
<td>same as <code class="docutils literal notranslate"><span class="pre">s[i:i]</span> <span class="pre">=</span> <span class="pre">[x]</span></code></td>
<td>(5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.pop([i])</span></code></td>
<td>same as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">s[i];</span> <span class="pre">del</span> <span class="pre">s[i];</span>
<span class="pre">return</span> <span class="pre">x</span></code></td>
<td>(6)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.remove(x)</span></code></td>
<td>same as <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">s[s.index(x)]</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s.reverse()</span></code></td>
<td>reverses the items of <em>s</em> in
place</td>
<td>(7)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">s.sort([cmp[,</span> <span class="pre">key[,</span>
<span class="pre">reverse]]])</span></code></td>
<td>sort the items of <em>s</em> in place</td>
<td>(7)(8)(9)(10)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first"><em>t</em> must have the same length as the slice it is  replacing.</p>
</li>
<li><p class="first">The C implementation of Python has historically accepted multiple parameters and
implicitly joined them into a tuple; this no longer works in Python 2.0.  Use of
this misfeature has been deprecated since Python 1.4.</p>
</li>
<li><p class="first"><em>t</em> can be any iterable object.</p>
</li>
<li><p class="first">Raises <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> when <em>x</em> is not found in <em>s</em>. When a negative index is
passed as the second or third parameter to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> method, the list
length is added, as for slice indices.  If it is still negative, it is truncated
to zero, as for slice indices.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> didn’t have arguments for specifying start and stop
positions.</p>
</div>
</li>
<li><p class="first">When a negative index is passed as the first parameter to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">insert()</span></code>
method, the list length is added, as for slice indices.  If it is still
negative, it is truncated to zero, as for slice indices.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, all negative indices were truncated to zero.</p>
</div>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> method’s optional argument <em>i</em> defaults to <code class="docutils literal notranslate"><span class="pre">-1</span></code>, so that
by default the last item is removed and returned.</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code> methods modify the list in place for
economy of space when sorting or reversing a large list.  To remind you that
they operate by side effect, they don’t return the sorted or reversed list.</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method takes optional arguments for controlling the
comparisons.</p>
<p><em>cmp</em> specifies a custom comparison function of two arguments (list items) which
should return a negative, zero or positive number depending on whether the first
argument is considered smaller than, equal to, or larger than the second
argument: <code class="docutils literal notranslate"><span class="pre">cmp=lambda</span> <span class="pre">x,y:</span> <span class="pre">cmp(x.lower(),</span> <span class="pre">y.lower())</span></code>.  The default value
is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p><em>key</em> specifies a function of one argument that is used to extract a comparison
key from each list element: <code class="docutils literal notranslate"><span class="pre">key=str.lower</span></code>.  The default value is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p><em>reverse</em> is a boolean value.  If set to <code class="docutils literal notranslate"><span class="pre">True</span></code>, then the list elements are
sorted as if each comparison were reversed.</p>
<p>In general, the <em>key</em> and <em>reverse</em> conversion processes are much faster than
specifying an equivalent <em>cmp</em> function.  This is because <em>cmp</em> is called
multiple times for each list element while <em>key</em> and <em>reverse</em> touch each
element only once.  Use <a class="reference internal" href="functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.cmp_to_key()</span></code></a> to convert an
old-style <em>cmp</em> function to a <em>key</em> function.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Support for <code class="docutils literal notranslate"><span class="pre">None</span></code> as an equivalent to omitting <em>cmp</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Support for <em>key</em> and <em>reverse</em> was added.</p>
</div>
</li>
<li><p class="first">Starting with Python 2.3, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method is guaranteed to be stable.  A
sort is stable if it guarantees not to change the relative order of elements
that compare equal — this is helpful for sorting in multiple passes (for
example, sort by department, then by salary grade).</p>
</li>
<li><div class="impl-detail first compound">
<p><strong>CPython implementation detail:</strong> While a list is being sorted, the effect of attempting to mutate, or even
inspect, the list is undefined.  The C implementation of Python 2.3 and
newer makes the list appear empty for the duration, and raises
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if it can detect that the list has been mutated during a
sort.</p>
</div>
</li>
<li><p class="first">The value <em>n</em> is an integer, or an object implementing
<a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a>.  Zero and negative values of <em>n</em> clear
the sequence.  Items in the sequence are not copied; they are referenced
multiple times, as explained for <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">*</span> <span class="pre">n</span></code> under <a class="reference internal" href="#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>.</p>
</li>
</ol>
</div>
</div>
<div class="section" id="set-types-set-frozenset">
<span id="types-set"></span><h2>5.7. Set Types — <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a><a class="headerlink" href="#set-types-set-frozenset" title="Permalink to this headline">¶</a></h2>
<p id="index-31">A <em class="dfn">set</em> object is an unordered collection of distinct <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects.
Common uses include membership testing, removing duplicates from a sequence, and
computing mathematical operations such as intersection, union, difference, and
symmetric difference.
(For other containers see the built in <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>,
and <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> classes, and the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>Like other collections, sets support <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">len(set)</span></code>, and <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span>
<span class="pre">set</span></code>.  Being an unordered collection, sets do not record element position or
order of insertion.  Accordingly, sets do not support indexing, slicing, or
other sequence-like behavior.</p>
<p>There are currently two built-in set types, <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>.
The <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> type is mutable — the contents can be changed using methods
like <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code>.  Since it is mutable, it has no
hash value and cannot be used as either a dictionary key or as an element of
another set.  The <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> type is immutable and <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> —
its contents cannot be altered after it is created; it can therefore be used as
a dictionary key or as an element of another set.</p>
<p>As of Python 2.7, non-empty sets (not frozensets) can be created by placing a
comma-separated list of elements within braces, for example: <code class="docutils literal notranslate"><span class="pre">{'jack',</span>
<span class="pre">'sjoerd'}</span></code>, in addition to the <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> constructor.</p>
<p>The constructors for both classes work the same:</p>
<dl class="class">
<dt id="set">
<em class="property">class </em><code class="descname">set</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#set" title="Permalink to this definition">¶</a></dt>
<dt id="frozenset">
<em class="property">class </em><code class="descname">frozenset</code><span class="sig-paren">(</span><span class="optional">[</span><em>iterable</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new set or frozenset object whose elements are taken from
<em>iterable</em>.  The elements of a set must be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>.  To
represent sets of sets, the inner sets must be <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>
objects.  If <em>iterable</em> is not specified, a new empty set is
returned.</p>
<p>Instances of <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> provide the following
operations:</p>
<dl class="describe">
<dt>
<code class="descname">len(s)</code></dt>
<dd><p>Return the number of elements in set <em>s</em> (cardinality of <em>s</em>).</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">x in s</code></dt>
<dd><p>Test <em>x</em> for membership in <em>s</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">x not in s</code></dt>
<dd><p>Test <em>x</em> for non-membership in <em>s</em>.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.isdisjoint">
<code class="descname">isdisjoint</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.isdisjoint" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the set has no elements in common with <em>other</em>.  Sets are
disjoint if and only if their intersection is the empty set.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.issubset">
<code class="descname">issubset</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.issubset" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set &lt;= other</code></dt>
<dd><p>Test whether every element in the set is in <em>other</em>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">set &lt; other</code></dt>
<dd><p>Test whether the set is a proper subset of <em>other</em>, that is,
<code class="docutils literal notranslate"><span class="pre">set</span> <span class="pre">&lt;=</span> <span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.issuperset">
<code class="descname">issuperset</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.issuperset" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set &gt;= other</code></dt>
<dd><p>Test whether every element in <em>other</em> is in the set.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">set &gt; other</code></dt>
<dd><p>Test whether the set is a proper superset of <em>other</em>, that is, <code class="docutils literal notranslate"><span class="pre">set</span> <span class="pre">&gt;=</span>
<span class="pre">other</span> <span class="pre">and</span> <span class="pre">set</span> <span class="pre">!=</span> <span class="pre">other</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.union">
<code class="descname">union</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.union" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set | other | ...</code></dt>
<dd><p>Return a new set with elements from the set and all others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.intersection">
<code class="descname">intersection</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.intersection" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set &amp; other &amp; ...</code></dt>
<dd><p>Return a new set with elements common to the set and all others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.difference">
<code class="descname">difference</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.difference" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set - other - ...</code></dt>
<dd><p>Return a new set with elements in the set that are not in the others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.symmetric_difference">
<code class="descname">symmetric_difference</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.symmetric_difference" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set ^ other</code></dt>
<dd><p>Return a new set with elements in either the set or <em>other</em> but not both.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.copy">
<code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new set with a shallow copy of <em>s</em>.</p>
</dd></dl>

<p>Note, the non-operator versions of <a class="reference internal" href="#frozenset.union" title="frozenset.union"><code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code></a>, <a class="reference internal" href="#frozenset.intersection" title="frozenset.intersection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code></a>,
<a class="reference internal" href="#frozenset.difference" title="frozenset.difference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code></a>, and <a class="reference internal" href="#frozenset.symmetric_difference" title="frozenset.symmetric_difference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference()</span></code></a>, <a class="reference internal" href="#frozenset.issubset" title="frozenset.issubset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">issubset()</span></code></a>, and
<a class="reference internal" href="#frozenset.issuperset" title="frozenset.issuperset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">issuperset()</span></code></a> methods will accept any iterable as an argument.  In
contrast, their operator based counterparts require their arguments to be
sets.  This precludes error-prone constructions like <code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">&amp;</span> <span class="pre">'cbs'</span></code>
in favor of the more readable <code class="docutils literal notranslate"><span class="pre">set('abc').intersection('cbs')</span></code>.</p>
<p>Both <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> support set to set comparisons. Two
sets are equal if and only if every element of each set is contained in the
other (each is a subset of the other). A set is less than another set if and
only if the first set is a proper subset of the second set (is a subset, but
is not equal). A set is greater than another set if and only if the first set
is a proper superset of the second set (is a superset, but is not equal).</p>
<p>Instances of <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> are compared to instances of <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>
based on their members.  For example, <code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">==</span> <span class="pre">frozenset('abc')</span></code>
returns <code class="docutils literal notranslate"><span class="pre">True</span></code> and so does <code class="docutils literal notranslate"><span class="pre">set('abc')</span> <span class="pre">in</span> <span class="pre">set([frozenset('abc')])</span></code>.</p>
<p>The subset and equality comparisons do not generalize to a total ordering
function.  For example, any two non-empty disjoint sets are not equal and are not
subsets of each other, so <em>all</em> of the following return <code class="docutils literal notranslate"><span class="pre">False</span></code>: <code class="docutils literal notranslate"><span class="pre">a&lt;b</span></code>,
<code class="docutils literal notranslate"><span class="pre">a==b</span></code>, or <code class="docutils literal notranslate"><span class="pre">a&gt;b</span></code>. Accordingly, sets do not implement the <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>
method.</p>
<p>Since sets only define partial ordering (subset relationships), the output of
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method is undefined for lists of sets.</p>
<p>Set elements, like dictionary keys, must be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>.</p>
<p>Binary operations that mix <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> instances with <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>
return the type of the first operand.  For example: <code class="docutils literal notranslate"><span class="pre">frozenset('ab')</span> <span class="pre">|</span>
<span class="pre">set('bc')</span></code> returns an instance of <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>.</p>
<p>The following table lists operations available for <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> that do not
apply to immutable instances of <a class="reference internal" href="#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>:</p>
<dl class="method">
<dt id="frozenset.update">
<code class="descname">update</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.update" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set |= other | ...</code></dt>
<dd><p>Update the set, adding elements from all others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.intersection_update">
<code class="descname">intersection_update</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.intersection_update" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set &amp;= other &amp; ...</code></dt>
<dd><p>Update the set, keeping only elements found in it and all others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.difference_update">
<code class="descname">difference_update</code><span class="sig-paren">(</span><em>*others</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.difference_update" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set -= other | ...</code></dt>
<dd><p>Update the set, removing elements found in others.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Accepts multiple input iterables.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="frozenset.symmetric_difference_update">
<code class="descname">symmetric_difference_update</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.symmetric_difference_update" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">set ^= other</code></dt>
<dd><p>Update the set, keeping only elements found in either set, but not in both.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add element <em>elem</em> to the set.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove element <em>elem</em> from the set.  Raises <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if <em>elem</em> is
not contained in the set.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.discard">
<code class="descname">discard</code><span class="sig-paren">(</span><em>elem</em><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.discard" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove element <em>elem</em> from the set if it is present.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an arbitrary element from the set.  Raises
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if the set is empty.</p>
</dd></dl>

<dl class="method">
<dt id="frozenset.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frozenset.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all elements from the set.</p>
</dd></dl>

<p>Note, the non-operator versions of the <a class="reference internal" href="#frozenset.update" title="frozenset.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code></a>,
<a class="reference internal" href="#frozenset.intersection_update" title="frozenset.intersection_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code></a>, <a class="reference internal" href="#frozenset.difference_update" title="frozenset.difference_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code></a>, and
<a class="reference internal" href="#frozenset.symmetric_difference_update" title="frozenset.symmetric_difference_update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference_update()</span></code></a> methods will accept any iterable as an
argument.</p>
<p>Note, the <em>elem</em> argument to the <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="#frozenset.remove" title="frozenset.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code></a>, and
<a class="reference internal" href="#frozenset.discard" title="frozenset.discard"><code class="xref py py-meth docutils literal notranslate"><span class="pre">discard()</span></code></a> methods may be a set.  To support searching for an equivalent
frozenset, a temporary one is created from <em>elem</em>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="sets.html#comparison-to-builtin-set"><span class="std std-ref">Comparison to the built-in set types</span></a></dt>
<dd>Differences between the <a class="reference internal" href="sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module and the built-in set types.</dd>
</dl>
</div>
</div>
<div class="section" id="mapping-types-dict">
<span id="typesmapping"></span><h2>5.8. Mapping Types — <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a><a class="headerlink" href="#mapping-types-dict" title="Permalink to this headline">¶</a></h2>
<p id="index-32">A <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a> object maps <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> values to arbitrary objects.
Mappings are mutable objects.  There is currently only one standard mapping
type, the <em class="dfn">dictionary</em>.  (For other containers see the built in
<code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>, <a class="reference internal" href="#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, and <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> classes, and the
<a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.)</p>
<p>A dictionary’s keys are <em>almost</em> arbitrary values.  Values that are not
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, that is, values containing lists, dictionaries or other
mutable types (that are compared by value rather than by object identity) may
not be used as keys.  Numeric types used for keys obey the normal rules for
numeric comparison: if two numbers compare equal (such as <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>)
then they can be used interchangeably to index the same dictionary entry.  (Note
however, that since computers store floating-point numbers as approximations it
is usually unwise to use them as dictionary keys.)</p>
<p>Dictionaries can be created by placing a comma-separated list of <code class="docutils literal notranslate"><span class="pre">key:</span> <span class="pre">value</span></code>
pairs within braces, for example: <code class="docutils literal notranslate"><span class="pre">{'jack':</span> <span class="pre">4098,</span> <span class="pre">'sjoerd':</span> <span class="pre">4127}</span></code> or <code class="docutils literal notranslate"><span class="pre">{4098:</span>
<span class="pre">'jack',</span> <span class="pre">4127:</span> <span class="pre">'sjoerd'}</span></code>, or by the <a class="reference internal" href="#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor.</p>
<dl class="class">
<dt id="dict">
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>**kwarg</em><span class="sig-paren">)</span><a class="headerlink" href="#dict" title="Permalink to this definition">¶</a></dt>
<dt>
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>mapping</em>, <em>**kwarg</em><span class="sig-paren">)</span></dt>
<dt>
<em class="property">class </em><code class="descname">dict</code><span class="sig-paren">(</span><em>iterable</em>, <em>**kwarg</em><span class="sig-paren">)</span></dt>
<dd><p>Return a new dictionary initialized from an optional positional argument
and a possibly empty set of keyword arguments.</p>
<p>If no positional argument is given, an empty dictionary is created.
If a positional argument is given and it is a mapping object, a dictionary
is created with the same key-value pairs as the mapping object.  Otherwise,
the positional argument must be an <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> object.  Each item in
the iterable must itself be an iterable with exactly two objects.  The
first object of each item becomes a key in the new dictionary, and the
second object the corresponding value.  If a key occurs more than once, the
last value for that key becomes the corresponding value in the new
dictionary.</p>
<p>If keyword arguments are given, the keyword arguments and their values are
added to the dictionary created from the positional argument.  If a key
being added is already present, the value from the keyword argument
replaces the value from the positional argument.</p>
<p>To illustrate, the following examples all return a dictionary equal to
<code class="docutils literal notranslate"><span class="pre">{&quot;one&quot;:</span> <span class="pre">1,</span> <span class="pre">&quot;two&quot;:</span> <span class="pre">2,</span> <span class="pre">&quot;three&quot;:</span> <span class="pre">3}</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">one</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">two</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">three</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;one&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="nb">zip</span><span class="p">([</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">([(</span><span class="s1">&#39;two&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;one&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;three&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">e</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">({</span><span class="s1">&#39;three&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span> <span class="o">==</span> <span class="n">c</span> <span class="o">==</span> <span class="n">d</span> <span class="o">==</span> <span class="n">e</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Providing keyword arguments as in the first example only works for keys that
are valid Python identifiers.  Otherwise, any valid keys can be used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Support for building a dictionary from keyword arguments added.</p>
</div>
<p>These are the operations that dictionaries support (and therefore, custom
mapping types should support too):</p>
<dl class="describe">
<dt>
<code class="descname">len(d)</code></dt>
<dd><p>Return the number of items in the dictionary <em>d</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">d[key]</code></dt>
<dd><p>Return the item of <em>d</em> with key <em>key</em>.  Raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if <em>key</em>
is not in the map.</p>
<p id="index-33">If a subclass of dict defines a method <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> and <em>key</em>
is not present, the <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> operation calls that method with the key <em>key</em>
as argument.  The <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> operation then returns or raises whatever is
returned or raised by the <code class="docutils literal notranslate"><span class="pre">__missing__(key)</span></code> call.
No other operations or methods invoke <a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a>. If
<a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> is not defined, <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.
<a class="reference internal" href="../reference/datamodel.html#object.__missing__" title="object.__missing__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__missing__()</span></code></a> must be a method; it cannot be an instance variable:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Counter</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__missing__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;red&#39;</span><span class="p">]</span>
<span class="go">1</span>
</pre></div>
</div>
<p>The example above shows part of the implementation of
<a class="reference internal" href="collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.Counter</span></code></a>.  A different <code class="docutils literal notranslate"><span class="pre">__missing__</span></code> method is used
by <a class="reference internal" href="collections.html#collections.defaultdict" title="collections.defaultdict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.defaultdict</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>Recognition of __missing__ methods of dict subclasses.</p>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">d[key] = value</code></dt>
<dd><p>Set <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> to <em>value</em>.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">del d[key]</code></dt>
<dd><p>Remove <code class="docutils literal notranslate"><span class="pre">d[key]</span></code> from <em>d</em>.  Raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> if <em>key</em> is not in the
map.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">key in d</code></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>d</em> has a key <em>key</em>, else <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">key not in d</code></dt>
<dd><p>Equivalent to <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">iter(d)</code></dt>
<dd><p>Return an iterator over the keys of the dictionary.  This is a shortcut
for <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all items from the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="dict.copy">
<code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a shallow copy of the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="dict.fromkeys">
<code class="descname">fromkeys</code><span class="sig-paren">(</span><em>seq</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.fromkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new dictionary with keys from <em>seq</em> and values set to <em>value</em>.</p>
<p><a class="reference internal" href="#dict.fromkeys" title="dict.fromkeys"><code class="xref py py-func docutils literal notranslate"><span class="pre">fromkeys()</span></code></a> is a class method that returns a new dictionary. <em>value</em>
defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.get">
<code class="descname">get</code><span class="sig-paren">(</span><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value for <em>key</em> if <em>key</em> is in the dictionary, else <em>default</em>.
If <em>default</em> is not given, it defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, so that this method
never raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.has_key">
<code class="descname">has_key</code><span class="sig-paren">(</span><em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#dict.has_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Test for the presence of <em>key</em> in the dictionary.  <a class="reference internal" href="#dict.has_key" title="dict.has_key"><code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code></a> is
deprecated in favor of <code class="docutils literal notranslate"><span class="pre">key</span> <span class="pre">in</span> <span class="pre">d</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.items">
<code class="descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the dictionary’s list of <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Keys and values are listed in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary’s
history of insertions and deletions.</p>
</div>
<p>If <a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a>, <a class="reference internal" href="#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>, <a class="reference internal" href="#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>, <a class="reference internal" href="#dict.iteritems" title="dict.iteritems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code></a>,
<a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code></a>, and <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code></a> are called with no intervening
modifications to the dictionary, the lists will directly correspond.  This
allows the creation of <code class="docutils literal notranslate"><span class="pre">(value,</span> <span class="pre">key)</span></code> pairs using <a class="reference internal" href="functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span>
<span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></code>.  The same relationship holds for the
<a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code></a> and <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code></a> methods: <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span>
<span class="pre">zip(d.itervalues(),</span> <span class="pre">d.iterkeys())</span></code> provides the same value for
<code class="docutils literal notranslate"><span class="pre">pairs</span></code>. Another way to create the same list is <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span>
<span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.iteritems()]</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.iteritems">
<code class="descname">iteritems</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.iteritems" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over the dictionary’s <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs.  See the
note for <a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
<p>Using <a class="reference internal" href="#dict.iteritems" title="dict.iteritems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code></a> while adding or deleting entries in the dictionary
may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> or fail to iterate over all entries.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.iterkeys">
<code class="descname">iterkeys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.iterkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over the dictionary’s keys.  See the note for
<a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
<p>Using <a class="reference internal" href="#dict.iterkeys" title="dict.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code></a> while adding or deleting entries in the dictionary
may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> or fail to iterate over all entries.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.itervalues">
<code class="descname">itervalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.itervalues" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator over the dictionary’s values.  See the note for
<a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
<p>Using <a class="reference internal" href="#dict.itervalues" title="dict.itervalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code></a> while adding or deleting entries in the
dictionary may raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> or fail to iterate over all
entries.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.keys">
<code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the dictionary’s list of keys.  See the note for
<a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.pop">
<code class="descname">pop</code><span class="sig-paren">(</span><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.pop" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>key</em> is in the dictionary, remove it and return its value, else return
<em>default</em>.  If <em>default</em> is not given and <em>key</em> is not in the dictionary,
a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.popitem">
<code class="descname">popitem</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.popitem" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return an arbitrary <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pair from the dictionary.</p>
<p><a class="reference internal" href="#dict.popitem" title="dict.popitem"><code class="xref py py-func docutils literal notranslate"><span class="pre">popitem()</span></code></a> is useful to destructively iterate over a dictionary, as
often used in set algorithms.  If the dictionary is empty, calling
<a class="reference internal" href="#dict.popitem" title="dict.popitem"><code class="xref py py-func docutils literal notranslate"><span class="pre">popitem()</span></code></a> raises a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.setdefault">
<code class="descname">setdefault</code><span class="sig-paren">(</span><em>key</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.setdefault" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>key</em> is in the dictionary, return its value.  If not, insert <em>key</em>
with a value of <em>default</em> and return <em>default</em>.  <em>default</em> defaults to
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.update">
<code class="descname">update</code><span class="sig-paren">(</span><span class="optional">[</span><em>other</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Update the dictionary with the key/value pairs from <em>other</em>, overwriting
existing keys.  Return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p><a class="reference internal" href="#dict.update" title="dict.update"><code class="xref py py-func docutils literal notranslate"><span class="pre">update()</span></code></a> accepts either another dictionary object or an iterable of
key/value pairs (as tuples or other iterables of length two).  If keyword
arguments are specified, the dictionary is then updated with those
key/value pairs: <code class="docutils literal notranslate"><span class="pre">d.update(red=1,</span> <span class="pre">blue=2)</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Allowed the argument to be an iterable of key/value pairs and allowed
keyword arguments.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.values">
<code class="descname">values</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.values" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the dictionary’s list of values.  See the note for
<a class="reference internal" href="#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="dict.viewitems">
<code class="descname">viewitems</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.viewitems" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary’s items (<code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pairs).  See
below for documentation of view objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.viewkeys">
<code class="descname">viewkeys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.viewkeys" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary’s keys.  See below for documentation of
view objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="dict.viewvalues">
<code class="descname">viewvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#dict.viewvalues" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new view of the dictionary’s values.  See below for documentation of
view objects.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>Dictionaries compare equal if and only if they have the same <code class="docutils literal notranslate"><span class="pre">(key,</span>
<span class="pre">value)</span></code> pairs.</p>
</dd></dl>

<div class="section" id="dictionary-view-objects">
<span id="dict-views"></span><h3>5.8.1. Dictionary view objects<a class="headerlink" href="#dictionary-view-objects" title="Permalink to this headline">¶</a></h3>
<p>The objects returned by <a class="reference internal" href="#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewkeys()</span></code></a>, <a class="reference internal" href="#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewvalues()</span></code></a> and
<a class="reference internal" href="#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewitems()</span></code></a> are <em>view objects</em>.  They provide a dynamic view on the
dictionary’s entries, which means that when the dictionary changes, the view
reflects these changes.</p>
<p>Dictionary views can be iterated over to yield their respective data, and
support membership tests:</p>
<dl class="describe">
<dt>
<code class="descname">len(dictview)</code></dt>
<dd><p>Return the number of entries in the dictionary.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">iter(dictview)</code></dt>
<dd><p>Return an iterator over the keys, values or items (represented as tuples of
<code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code>) in the dictionary.</p>
<p>Keys and values are iterated over in an arbitrary order which is non-random,
varies across Python implementations, and depends on the dictionary’s history
of insertions and deletions. If keys, values and items views are iterated
over with no intervening modifications to the dictionary, the order of items
will directly correspond.  This allows the creation of <code class="docutils literal notranslate"><span class="pre">(value,</span> <span class="pre">key)</span></code> pairs
using <a class="reference internal" href="functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">zip(d.values(),</span> <span class="pre">d.keys())</span></code>.  Another way to
create the same list is <code class="docutils literal notranslate"><span class="pre">pairs</span> <span class="pre">=</span> <span class="pre">[(v,</span> <span class="pre">k)</span> <span class="pre">for</span> <span class="pre">(k,</span> <span class="pre">v)</span> <span class="pre">in</span> <span class="pre">d.items()]</span></code>.</p>
<p>Iterating views while adding or deleting entries in the dictionary may raise
a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> or fail to iterate over all entries.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">x in dictview</code></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is in the underlying dictionary’s keys, values or
items (in the latter case, <em>x</em> should be a <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> tuple).</p>
</dd></dl>

<p>Keys views are set-like since their entries are unique and hashable.  If all
values are hashable, so that (key, value) pairs are unique and hashable, then
the items view is also set-like.  (Values views are not treated as set-like
since the entries are generally not unique.)  Then these set operations are
available (“other” refers either to another view or a set):</p>
<dl class="describe">
<dt>
<code class="descname">dictview &amp; other</code></dt>
<dd><p>Return the intersection of the dictview and the other object as a new set.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">dictview | other</code></dt>
<dd><p>Return the union of the dictview and the other object as a new set.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">dictview - other</code></dt>
<dd><p>Return the difference between the dictview and the other object (all elements
in <em>dictview</em> that aren’t in <em>other</em>) as a new set.</p>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">dictview ^ other</code></dt>
<dd><p>Return the symmetric difference (all elements either in <em>dictview</em> or
<em>other</em>, but not in both) of the dictview and the other object as a new set.</p>
</dd></dl>

<p>An example of dictionary view usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">dishes</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;eggs&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;sausage&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;spam&#39;</span><span class="p">:</span> <span class="mi">500</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">dishes</span><span class="o">.</span><span class="n">viewvalues</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># iteration</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">values</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">n</span> <span class="o">+=</span> <span class="n">val</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">504</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># keys and values are iterated over in the same order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;eggs&#39;, &#39;bacon&#39;, &#39;sausage&#39;, &#39;spam&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
<span class="go">[2, 1, 1, 500]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># view objects are dynamic and reflect dict changes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s1">&#39;eggs&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">dishes</span><span class="p">[</span><span class="s1">&#39;sausage&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">keys</span><span class="p">)</span>
<span class="go">[&#39;spam&#39;, &#39;bacon&#39;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># set operations</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">keys</span> <span class="o">&amp;</span> <span class="p">{</span><span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">,</span> <span class="s1">&#39;salad&#39;</span><span class="p">}</span>
<span class="go">{&#39;bacon&#39;}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="file-objects">
<span id="bltin-file-objects"></span><h2>5.9. File Objects<a class="headerlink" href="#file-objects" title="Permalink to this headline">¶</a></h2>
<p id="index-34">File objects are implemented using C’s <code class="docutils literal notranslate"><span class="pre">stdio</span></code> package and can be
created with the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function.  File
objects are also returned by some other built-in functions and methods,
such as <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a> and <a class="reference internal" href="os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a> and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code>
method of socket objects. Temporary files can be created using the
<a class="reference internal" href="tempfile.html#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a> module, and high-level file operations such as copying,
moving, and deleting files and directories can be achieved with the
<a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module.</p>
<p>When a file operation fails for an I/O-related reason, the exception
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> is raised.  This includes situations where the operation is not
defined for some reason, like <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code> on a tty device or writing a file
opened for reading.</p>
<p>Files have the following methods:</p>
<dl class="method">
<dt id="file.close">
<code class="descclassname">file.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the file.  A closed file cannot be read or written any more. Any operation
which requires that the file be open will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> after the
file has been closed.  Calling <a class="reference internal" href="#file.close" title="file.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> more than once is allowed.</p>
<p>As of Python 2.5, you can avoid having to call this method explicitly if you use
the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  For example, the following code will
automatically close <em>f</em> when the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> block is exited:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">with_statement</span> <span class="c1"># This isn&#39;t required in Python 2.6</span>

<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;hello.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span><span class="p">,</span>
</pre></div>
</div>
<p>In older versions of Python, you would have needed to do this to get the same
effect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;hello.txt&quot;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span><span class="p">,</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Not all “file-like” types in Python support use as a context manager for the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  If your code is intended to work with any file-like
object, you can use the function <a class="reference internal" href="contextlib.html#contextlib.closing" title="contextlib.closing"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextlib.closing()</span></code></a> instead of using
the object directly.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.flush">
<code class="descclassname">file.</code><code class="descname">flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Flush the internal buffer, like <code class="docutils literal notranslate"><span class="pre">stdio</span></code>’s <code class="xref c c-func docutils literal notranslate"><span class="pre">fflush()</span></code>.  This may be a
no-op on some file-like objects.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#file.flush" title="file.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> does not necessarily write the file’s data to disk.  Use
<a class="reference internal" href="#file.flush" title="file.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> followed by <a class="reference internal" href="os.html#os.fsync" title="os.fsync"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fsync()</span></code></a> to ensure this behavior.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.fileno">
<code class="descclassname">file.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-35">Return the integer “file descriptor” that is used by the underlying
implementation to request I/O operations from the operating system.  This can be
useful for other, lower level interfaces that use file descriptors, such as the
<a class="reference internal" href="fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fcntl</span></code></a> module or <a class="reference internal" href="os.html#os.read" title="os.read"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.read()</span></code></a> and friends.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">File-like objects which do not have a real file descriptor should <em>not</em> provide
this method!</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.isatty">
<code class="descclassname">file.</code><code class="descname">isatty</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.isatty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the file is connected to a tty(-like) device, else <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If a file-like object is not associated with a real file, this method should
<em>not</em> be implemented.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.next">
<code class="descclassname">file.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.next" title="Permalink to this definition">¶</a></dt>
<dd><p>A file object is its own iterator, for example <code class="docutils literal notranslate"><span class="pre">iter(f)</span></code> returns <em>f</em> (unless
<em>f</em> is closed).  When a file is used as an iterator, typically in a
<a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop (for example, <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">f:</span> <span class="pre">print</span> <span class="pre">line.strip()</span></code>), the
<a class="reference internal" href="#file.next" title="file.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method is called repeatedly.  This method returns the next input
line, or raises <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> when EOF is hit when the file is open for
reading (behavior is undefined when the file is open for writing).  In order to
make a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop the most efficient way of looping over the lines of a
file (a very common operation), the <a class="reference internal" href="#file.next" title="file.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method uses a hidden read-ahead
buffer.  As a consequence of using a read-ahead buffer, combining <a class="reference internal" href="#file.next" title="file.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a>
with other file methods (like <a class="reference internal" href="#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>) does not work right.  However,
using <a class="reference internal" href="#file.seek" title="file.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> to reposition the file to an absolute position will flush the
read-ahead buffer.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.read">
<code class="descclassname">file.</code><code class="descname">read</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at most <em>size</em> bytes from the file (less if the read hits EOF before
obtaining <em>size</em> bytes).  If the <em>size</em> argument is negative or omitted, read
all data until EOF is reached.  The bytes are returned as a string object.  An
empty string is returned when EOF is encountered immediately.  (For certain
files, like ttys, it makes sense to continue reading after an EOF is hit.)  Note
that this method may call the underlying C function <code class="xref c c-func docutils literal notranslate"><span class="pre">fread()</span></code> more than
once in an effort to acquire as close to <em>size</em> bytes as possible. Also note
that when in non-blocking mode, less data than was requested may be
returned, even if no <em>size</em> parameter was given.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This function is simply a wrapper for the underlying
<code class="xref c c-func docutils literal notranslate"><span class="pre">fread()</span></code> C function, and will behave the same in corner cases,
such as whether the EOF value is cached.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.readline">
<code class="descclassname">file.</code><code class="descname">readline</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file.readline" title="Permalink to this definition">¶</a></dt>
<dd><p>Read one entire line from the file.  A trailing newline character is kept in
the string (but may be absent when a file ends with an incomplete line). <a class="footnote-reference" href="#id17" id="id11">[6]</a>
If the <em>size</em> argument is present and non-negative, it is a maximum byte
count (including the trailing newline) and an incomplete line may be
returned. When <em>size</em> is not 0, an empty string is returned <em>only</em> when EOF
is encountered immediately.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike <code class="docutils literal notranslate"><span class="pre">stdio</span></code>’s <code class="xref c c-func docutils literal notranslate"><span class="pre">fgets()</span></code>, the returned string contains null characters
(<code class="docutils literal notranslate"><span class="pre">'\0'</span></code>) if they occurred in the input.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.readlines">
<code class="descclassname">file.</code><code class="descname">readlines</code><span class="sig-paren">(</span><span class="optional">[</span><em>sizehint</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file.readlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Read until EOF using <a class="reference internal" href="#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> and return a list containing the lines
thus read.  If the optional <em>sizehint</em> argument is present, instead of
reading up to EOF, whole lines totalling approximately <em>sizehint</em> bytes
(possibly after rounding up to an internal buffer size) are read.  Objects
implementing a file-like interface may choose to ignore <em>sizehint</em> if it
cannot be implemented, or cannot be implemented efficiently.</p>
</dd></dl>

<dl class="method">
<dt id="file.xreadlines">
<code class="descclassname">file.</code><code class="descname">xreadlines</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.xreadlines" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns the same thing as <code class="docutils literal notranslate"><span class="pre">iter(f)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>Use <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></code> instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.seek">
<code class="descclassname">file.</code><code class="descname">seek</code><span class="sig-paren">(</span><em>offset</em><span class="optional">[</span>, <em>whence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file.seek" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file’s current position, like <code class="docutils literal notranslate"><span class="pre">stdio</span></code>’s <code class="xref c c-func docutils literal notranslate"><span class="pre">fseek()</span></code>. The <em>whence</em>
argument is optional and defaults to  <code class="docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code> or <code class="docutils literal notranslate"><span class="pre">0</span></code> (absolute file
positioning); other values are <code class="docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code> or <code class="docutils literal notranslate"><span class="pre">1</span></code> (seek relative to the
current position) and <code class="docutils literal notranslate"><span class="pre">os.SEEK_END</span></code> or <code class="docutils literal notranslate"><span class="pre">2</span></code>  (seek relative to the file’s
end).  There is no return value.</p>
<p>For example, <code class="docutils literal notranslate"><span class="pre">f.seek(2,</span> <span class="pre">os.SEEK_CUR)</span></code> advances the position by two and
<code class="docutils literal notranslate"><span class="pre">f.seek(-3,</span> <span class="pre">os.SEEK_END)</span></code> sets the position to the third to last.</p>
<p>Note that if the file is opened for appending
(mode <code class="docutils literal notranslate"><span class="pre">'a'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a+'</span></code>), any <a class="reference internal" href="#file.seek" title="file.seek"><code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code></a> operations will be undone at the
next write.  If the file is only opened for writing in append mode (mode
<code class="docutils literal notranslate"><span class="pre">'a'</span></code>), this method is essentially a no-op, but it remains useful for files
opened in append mode with reading enabled (mode <code class="docutils literal notranslate"><span class="pre">'a+'</span></code>).  If the file is
opened in text mode (without <code class="docutils literal notranslate"><span class="pre">'b'</span></code>), only offsets returned by <a class="reference internal" href="#file.tell" title="file.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> are
legal.  Use of other offsets causes undefined behavior.</p>
<p>Note that not all file objects are seekable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Passing float values as offset has been deprecated.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.tell">
<code class="descclassname">file.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#file.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file’s current position, like <code class="docutils literal notranslate"><span class="pre">stdio</span></code>’s <code class="xref c c-func docutils literal notranslate"><span class="pre">ftell()</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Windows, <a class="reference internal" href="#file.tell" title="file.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> can return illegal values (after an <code class="xref c c-func docutils literal notranslate"><span class="pre">fgets()</span></code>)
when reading files with Unix-style line-endings. Use binary mode (<code class="docutils literal notranslate"><span class="pre">'rb'</span></code>) to
circumvent this problem.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="file.truncate">
<code class="descclassname">file.</code><code class="descname">truncate</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#file.truncate" title="Permalink to this definition">¶</a></dt>
<dd><p>Truncate the file’s size.  If the optional <em>size</em> argument is present, the file
is truncated to (at most) that size.  The size defaults to the current position.
The current file position is not changed.  Note that if a specified size exceeds
the file’s current size, the result is platform-dependent:  possibilities
include that the file may remain unchanged, increase to the specified size as if
zero-filled, or increase to the specified size with undefined new content.
Availability:  Windows, many Unix variants.</p>
</dd></dl>

<dl class="method">
<dt id="file.write">
<code class="descclassname">file.</code><code class="descname">write</code><span class="sig-paren">(</span><em>str</em><span class="sig-paren">)</span><a class="headerlink" href="#file.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a string to the file.  There is no return value.  Due to buffering, the
string may not actually show up in the file until the <a class="reference internal" href="#file.flush" title="file.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> or
<a class="reference internal" href="#file.close" title="file.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method is called.</p>
</dd></dl>

<dl class="method">
<dt id="file.writelines">
<code class="descclassname">file.</code><code class="descname">writelines</code><span class="sig-paren">(</span><em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#file.writelines" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a sequence of strings to the file.  The sequence can be any iterable
object producing strings, typically a list of strings. There is no return value.
(The name is intended to match <a class="reference internal" href="#file.readlines" title="file.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a>; <a class="reference internal" href="#file.writelines" title="file.writelines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writelines()</span></code></a> does not
add line separators.)</p>
</dd></dl>

<p>Files support the iterator protocol.  Each iteration returns the same result as
<a class="reference internal" href="#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, and iteration ends when the <a class="reference internal" href="#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method returns
an empty string.</p>
<p>File objects also offer a number of other interesting attributes. These are not
required for file-like objects, but should be implemented if they make sense for
the particular object.</p>
<dl class="attribute">
<dt id="file.closed">
<code class="descclassname">file.</code><code class="descname">closed</code><a class="headerlink" href="#file.closed" title="Permalink to this definition">¶</a></dt>
<dd><p>bool indicating the current state of the file object.  This is a read-only
attribute; the <a class="reference internal" href="#file.close" title="file.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method changes the value. It may not be available
on all file-like objects.</p>
</dd></dl>

<dl class="attribute">
<dt id="file.encoding">
<code class="descclassname">file.</code><code class="descname">encoding</code><a class="headerlink" href="#file.encoding" title="Permalink to this definition">¶</a></dt>
<dd><p>The encoding that this file uses. When Unicode strings are written to a file,
they will be converted to byte strings using this encoding. In addition, when
the file is connected to a terminal, the attribute gives the encoding that the
terminal is likely to use (that  information might be incorrect if the user has
misconfigured the  terminal). The attribute is read-only and may not be present
on all file-like objects. It may also be <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case the file uses
the system default encoding for converting Unicode strings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="file.errors">
<code class="descclassname">file.</code><code class="descname">errors</code><a class="headerlink" href="#file.errors" title="Permalink to this definition">¶</a></dt>
<dd><p>The Unicode error handler used along with the encoding.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="file.mode">
<code class="descclassname">file.</code><code class="descname">mode</code><a class="headerlink" href="#file.mode" title="Permalink to this definition">¶</a></dt>
<dd><p>The I/O mode for the file.  If the file was created using the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
built-in function, this will be the value of the <em>mode</em> parameter.  This is a
read-only attribute and may not be present on all file-like objects.</p>
</dd></dl>

<dl class="attribute">
<dt id="file.name">
<code class="descclassname">file.</code><code class="descname">name</code><a class="headerlink" href="#file.name" title="Permalink to this definition">¶</a></dt>
<dd><p>If the file object was created using <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, the name of the file.
Otherwise, some string that indicates the source of the file object, of the
form <code class="docutils literal notranslate"><span class="pre">&lt;...&gt;</span></code>.  This is a read-only attribute and may not be present on all
file-like objects.</p>
<span class="target" id="index-36"></span></dd></dl>

<dl class="attribute">
<dt id="file.newlines">
<code class="descclassname">file.</code><code class="descname">newlines</code><a class="headerlink" href="#file.newlines" title="Permalink to this definition">¶</a></dt>
<dd><p>If Python was built with <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> enabled (the default) this
read-only attribute exists, and for files opened in universal newline read
mode it keeps track of the types of newlines encountered while reading the
file. The values it can take are <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code>
(unknown, no newlines read yet) or a tuple containing all the newline types
seen, to indicate that multiple newline conventions were encountered. For
files not opened in universal newlines read mode the value of this attribute
will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="file.softspace">
<code class="descclassname">file.</code><code class="descname">softspace</code><a class="headerlink" href="#file.softspace" title="Permalink to this definition">¶</a></dt>
<dd><p>Boolean that indicates whether a space character needs to be printed before
another value when using the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement. Classes that are trying
to simulate a file object should also have a writable <a class="reference internal" href="#file.softspace" title="file.softspace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">softspace</span></code></a>
attribute, which should be initialized to zero.  This will be automatic for most
classes implemented in Python (care may be needed for objects that override
attribute access); types implemented in C will have to provide a writable
<a class="reference internal" href="#file.softspace" title="file.softspace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">softspace</span></code></a> attribute.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This attribute is not used to control the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement, but to
allow the implementation of <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> to keep track of its internal
state.</p>
</div>
</dd></dl>

</div>
<div class="section" id="memoryview-type">
<span id="typememoryview"></span><h2>5.10. memoryview type<a class="headerlink" href="#memoryview-type" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> objects allow Python code to access the internal data
of an object that supports the buffer protocol without copying.  Memory
is generally interpreted as simple bytes.</p>
<dl class="class">
<dt id="memoryview">
<em class="property">class </em><code class="descname">memoryview</code><span class="sig-paren">(</span><em>obj</em><span class="sig-paren">)</span><a class="headerlink" href="#memoryview" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> that references <em>obj</em>.  <em>obj</em> must support the
buffer protocol.  Built-in objects that support the buffer protocol include
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> (but not <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>).</p>
<p>A <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> has the notion of an <em>element</em>, which is the
atomic memory unit handled by the originating object <em>obj</em>.  For many
simple types such as <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>, an element
is a single byte, but other third-party types may expose larger elements.</p>
<p><code class="docutils literal notranslate"><span class="pre">len(view)</span></code> returns the total number of elements in the memoryview,
<em>view</em>.  The <a class="reference internal" href="#memoryview.itemsize" title="memoryview.itemsize"><code class="xref py py-class docutils literal notranslate"><span class="pre">itemsize</span></code></a> attribute will give you the
number of bytes in a single element.</p>
<p>A <a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> supports slicing to expose its data.  Taking a single
index will return a single element as a <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> object.  Full
slicing will result in a subview:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;b&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;g&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="go">&lt;memory at 0x77ab28&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span>
<span class="go">&#39;bce&#39;</span>
</pre></div>
</div>
<p>If the object the memoryview is over supports changing its data, the
memoryview supports slice assignment:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="s1">&#39;abcefg&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="o">.</span><span class="n">readonly</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;z&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;zbcefg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;123&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">bytearray(b&#39;z123fg&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;spam&#39;</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">cannot modify size of memoryview object</span>
</pre></div>
</div>
<p>Notice how the size of the memoryview object cannot be changed.</p>
<p><a class="reference internal" href="#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> has two methods:</p>
<dl class="method">
<dt id="memoryview.tobytes">
<code class="descname">tobytes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.tobytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data in the buffer as a bytestring (an object of class
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span>
<span class="go">&#39;abc&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="memoryview.tolist">
<code class="descname">tolist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#memoryview.tolist" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data in the buffer as a list of integers.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">memoryview</span><span class="p">(</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[97, 98, 99]</span>
</pre></div>
</div>
</dd></dl>

<p>There are also several readonly attributes available:</p>
<dl class="attribute">
<dt id="memoryview.format">
<code class="descname">format</code><a class="headerlink" href="#memoryview.format" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the format (in <a class="reference internal" href="struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module style) for each
element in the view.  This defaults to <code class="docutils literal notranslate"><span class="pre">'B'</span></code>, a simple bytestring.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.itemsize">
<code class="descname">itemsize</code><a class="headerlink" href="#memoryview.itemsize" title="Permalink to this definition">¶</a></dt>
<dd><p>The size in bytes of each element of the memoryview.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.shape">
<code class="descname">shape</code><a class="headerlink" href="#memoryview.shape" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ndim</span></code></a> giving the shape of the
memory as an N-dimensional array.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.ndim">
<code class="descname">ndim</code><a class="headerlink" href="#memoryview.ndim" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer indicating how many dimensions of a multi-dimensional array the
memory represents.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.strides">
<code class="descname">strides</code><a class="headerlink" href="#memoryview.strides" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of integers the length of <a class="reference internal" href="#memoryview.ndim" title="memoryview.ndim"><code class="xref py py-attr docutils literal notranslate"><span class="pre">ndim</span></code></a> giving the size in bytes to
access each element for each dimension of the array.</p>
</dd></dl>

<dl class="attribute">
<dt id="memoryview.readonly">
<code class="descname">readonly</code><a class="headerlink" href="#memoryview.readonly" title="Permalink to this definition">¶</a></dt>
<dd><p>A bool indicating whether the memory is read only.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="context-manager-types">
<span id="typecontextmanager"></span><h2>5.11. Context Manager Types<a class="headerlink" href="#context-manager-types" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p id="index-37">Python’s <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement supports the concept of a runtime context
defined by a context manager.  This is implemented using two separate methods
that allow user-defined classes to define a runtime context that is entered
before the statement body is executed and exited when the statement ends.</p>
<p>The <em class="dfn">context management protocol</em> consists of a pair of methods that need
to be provided for a context manager object to define a runtime context:</p>
<dl class="method">
<dt id="contextmanager.__enter__">
<code class="descclassname">contextmanager.</code><code class="descname">__enter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#contextmanager.__enter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the runtime context and return either this object or another object
related to the runtime context. The value returned by this method is bound to
the identifier in the <a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause of <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements using
this context manager.</p>
<p>An example of a context manager that returns itself is a file object. File
objects return themselves from __enter__() to allow <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> to be used as
the context expression in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>An example of a context manager that returns a related object is the one
returned by <a class="reference internal" href="decimal.html#decimal.localcontext" title="decimal.localcontext"><code class="xref py py-func docutils literal notranslate"><span class="pre">decimal.localcontext()</span></code></a>. These managers set the active
decimal context to a copy of the original decimal context and then return the
copy. This allows changes to be made to the current decimal context in the body
of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement without affecting code outside the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
</dd></dl>

<dl class="method">
<dt id="contextmanager.__exit__">
<code class="descclassname">contextmanager.</code><code class="descname">__exit__</code><span class="sig-paren">(</span><em>exc_type</em>, <em>exc_val</em>, <em>exc_tb</em><span class="sig-paren">)</span><a class="headerlink" href="#contextmanager.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the runtime context and return a Boolean flag indicating if any exception
that occurred should be suppressed. If an exception occurred while executing the
body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the arguments contain the exception type,
value and traceback information. Otherwise, all three arguments are <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Returning a true value from this method will cause the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
to suppress the exception and continue execution with the statement immediately
following the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement. Otherwise the exception continues
propagating after this method has finished executing. Exceptions that occur
during execution of this method will replace any exception that occurred in the
body of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>The exception passed in should never be reraised explicitly - instead, this
method should return a false value to indicate that the method completed
successfully and does not want to suppress the raised exception. This allows
context management code (such as <code class="docutils literal notranslate"><span class="pre">contextlib.nested</span></code>) to easily detect whether
or not an <a class="reference internal" href="#contextmanager.__exit__" title="contextmanager.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method has actually failed.</p>
</dd></dl>

<p>Python defines several context managers to support easy thread synchronisation,
prompt closure of files or other objects, and simpler manipulation of the active
decimal arithmetic context. The specific types are not treated specially beyond
their implementation of the context management protocol. See the
<a class="reference internal" href="contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module for some examples.</p>
<p>Python’s <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>s and the <code class="docutils literal notranslate"><span class="pre">contextlib.contextmanager</span></code> <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a>
provide a convenient way to implement these protocols.  If a generator function is
decorated with the <code class="docutils literal notranslate"><span class="pre">contextlib.contextmanager</span></code> decorator, it will return a
context manager implementing the necessary <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods, rather than the iterator produced by an undecorated
generator function.</p>
<p>Note that there is no specific slot for any of these methods in the type
structure for Python objects in the Python/C API. Extension types wanting to
define these methods must provide them as a normal Python accessible method.
Compared to the overhead of setting up the runtime context, the overhead of a
single class dictionary lookup is negligible.</p>
</div>
<div class="section" id="other-built-in-types">
<span id="typesother"></span><h2>5.12. Other Built-in Types<a class="headerlink" href="#other-built-in-types" title="Permalink to this headline">¶</a></h2>
<p>The interpreter supports several other kinds of objects. Most of these support
only one or two operations.</p>
<div class="section" id="modules">
<span id="typesmodules"></span><h3>5.12.1. Modules<a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h3>
<p>The only special operation on a module is attribute access: <code class="docutils literal notranslate"><span class="pre">m.name</span></code>, where
<em>m</em> is a module and <em>name</em> accesses a name defined in <em>m</em>’s symbol table.
Module attributes can be assigned to.  (Note that the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>
statement is not, strictly speaking, an operation on a module object; <code class="docutils literal notranslate"><span class="pre">import</span>
<span class="pre">foo</span></code> does not require a module object named <em>foo</em> to exist, rather it requires
an (external) <em>definition</em> for a module named <em>foo</em> somewhere.)</p>
<p>A special attribute of every module is <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. This is the
dictionary containing the module’s symbol table. Modifying this dictionary will
actually change the module’s symbol table, but direct assignment to the
<a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute is not possible (you can write
<code class="docutils literal notranslate"><span class="pre">m.__dict__['a']</span> <span class="pre">=</span> <span class="pre">1</span></code>, which defines <code class="docutils literal notranslate"><span class="pre">m.a</span></code> to be <code class="docutils literal notranslate"><span class="pre">1</span></code>, but you can’t write
<code class="docutils literal notranslate"><span class="pre">m.__dict__</span> <span class="pre">=</span> <span class="pre">{}</span></code>).  Modifying <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> directly is
not recommended.</p>
<p>Modules built into the interpreter are written like this: <code class="docutils literal notranslate"><span class="pre">&lt;module</span> <span class="pre">'sys'</span>
<span class="pre">(built-in)&gt;</span></code>.  If loaded from a file, they are written as <code class="docutils literal notranslate"><span class="pre">&lt;module</span> <span class="pre">'os'</span> <span class="pre">from</span>
<span class="pre">'/usr/local/lib/pythonX.Y/os.pyc'&gt;</span></code>.</p>
</div>
<div class="section" id="classes-and-class-instances">
<span id="typesobjects"></span><h3>5.12.2. Classes and Class Instances<a class="headerlink" href="#classes-and-class-instances" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="../reference/datamodel.html#objects"><span class="std std-ref">Objects, values and types</span></a> and <a class="reference internal" href="../reference/compound_stmts.html#class"><span class="std std-ref">Class definitions</span></a> for these.</p>
</div>
<div class="section" id="functions">
<span id="typesfunctions"></span><h3>5.12.3. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h3>
<p>Function objects are created by function definitions.  The only operation on a
function object is to call it: <code class="docutils literal notranslate"><span class="pre">func(argument-list)</span></code>.</p>
<p>There are really two flavors of function objects: built-in functions and
user-defined functions.  Both support the same operation (to call the function),
but the implementation is different, hence the different object types.</p>
<p>See <a class="reference internal" href="../reference/compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for more information.</p>
</div>
<div class="section" id="methods">
<span id="typesmethods"></span><h3>5.12.4. Methods<a class="headerlink" href="#methods" title="Permalink to this headline">¶</a></h3>
<p id="index-38">Methods are functions that are called using the attribute notation. There are
two flavors: built-in methods (such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> on lists) and class
instance methods.  Built-in methods are described with the types that support
them.</p>
<p>The implementation adds two special read-only attributes to class instance
methods: <code class="docutils literal notranslate"><span class="pre">m.im_self</span></code> is the object on which the method operates, and
<code class="docutils literal notranslate"><span class="pre">m.im_func</span></code> is the function implementing the method.  Calling <code class="docutils literal notranslate"><span class="pre">m(arg-1,</span>
<span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></code> is completely equivalent to calling <code class="docutils literal notranslate"><span class="pre">m.im_func(m.im_self,</span>
<span class="pre">arg-1,</span> <span class="pre">arg-2,</span> <span class="pre">...,</span> <span class="pre">arg-n)</span></code>.</p>
<p>Class instance methods are either <em>bound</em> or <em>unbound</em>, referring to whether the
method was accessed through an instance or a class, respectively.  When a method
is unbound, its <code class="docutils literal notranslate"><span class="pre">im_self</span></code> attribute will be <code class="docutils literal notranslate"><span class="pre">None</span></code> and if called, an
explicit <code class="docutils literal notranslate"><span class="pre">self</span></code> object must be passed as the first argument.  In this case,
<code class="docutils literal notranslate"><span class="pre">self</span></code> must be an instance of the unbound method’s class (or a subclass of
that class), otherwise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
<p>Like function objects, methods objects support getting arbitrary attributes.
However, since method attributes are actually stored on the underlying function
object (<code class="docutils literal notranslate"><span class="pre">meth.im_func</span></code>), setting method attributes on either bound or unbound
methods is disallowed.  Attempting to set an attribute on a method results in
an <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> being raised.  In order to set a method attribute, you
need to explicitly set it on the underlying function object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s1">&#39;my name is method&#39;</span>  <span class="c1"># can&#39;t set on the method</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;instancemethod&#39; object has no attribute &#39;whoami&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">im_func</span><span class="o">.</span><span class="n">whoami</span> <span class="o">=</span> <span class="s1">&#39;my name is method&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">method</span><span class="o">.</span><span class="n">whoami</span>
<span class="go">&#39;my name is method&#39;</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a> for more information.</p>
</div>
<div class="section" id="code-objects">
<span id="bltin-code-objects"></span><span id="index-39"></span><h3>5.12.5. Code Objects<a class="headerlink" href="#code-objects" title="Permalink to this headline">¶</a></h3>
<p id="index-40">Code objects are used by the implementation to represent “pseudo-compiled”
executable Python code such as a function body. They differ from function
objects because they don’t contain a reference to their global execution
environment.  Code objects are returned by the built-in <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> function
and can be extracted from function objects through their <code class="xref py py-attr docutils literal notranslate"><span class="pre">func_code</span></code>
attribute. See also the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a> module.</p>
<p id="index-41">A code object can be executed or evaluated by passing it (instead of a source
string) to the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement or the built-in <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> function.</p>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a> for more information.</p>
</div>
<div class="section" id="type-objects">
<span id="bltin-type-objects"></span><h3>5.12.6. Type Objects<a class="headerlink" href="#type-objects" title="Permalink to this headline">¶</a></h3>
<p id="index-42">Type objects represent the various object types.  An object’s type is accessed
by the built-in function <a class="reference internal" href="functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>.  There are no special operations on
types.  The standard module <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> defines names for all standard built-in
types.</p>
<p>Types are written like this: <code class="docutils literal notranslate"><span class="pre">&lt;type</span> <span class="pre">'int'&gt;</span></code>.</p>
</div>
<div class="section" id="the-null-object">
<span id="bltin-null-object"></span><h3>5.12.7. The Null Object<a class="headerlink" href="#the-null-object" title="Permalink to this headline">¶</a></h3>
<p>This object is returned by functions that don’t explicitly return a value.  It
supports no special operations.  There is exactly one null object, named
<code class="docutils literal notranslate"><span class="pre">None</span></code> (a built-in name).</p>
<p>It is written as <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
<div class="section" id="the-ellipsis-object">
<span id="bltin-ellipsis-object"></span><h3>5.12.8. The Ellipsis Object<a class="headerlink" href="#the-ellipsis-object" title="Permalink to this headline">¶</a></h3>
<p>This object is used by extended slice notation (see <a class="reference internal" href="../reference/expressions.html#slicings"><span class="std std-ref">Slicings</span></a>).  It
supports no special operations.  There is exactly one ellipsis object, named
<a class="reference internal" href="constants.html#Ellipsis" title="Ellipsis"><code class="xref py py-const docutils literal notranslate"><span class="pre">Ellipsis</span></code></a> (a built-in name).</p>
<p>It is written as <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>.  When in a subscript, it can also be written as
<code class="docutils literal notranslate"><span class="pre">...</span></code>, for example <code class="docutils literal notranslate"><span class="pre">seq[...]</span></code>.</p>
</div>
<div class="section" id="the-notimplemented-object">
<h3>5.12.9. The NotImplemented Object<a class="headerlink" href="#the-notimplemented-object" title="Permalink to this headline">¶</a></h3>
<p>This object is returned from comparisons and binary operations when they are
asked to operate on types they don’t support. See <a class="reference internal" href="../reference/expressions.html#comparisons"><span class="std std-ref">Comparisons</span></a> for more
information.</p>
<p>It is written as <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>.</p>
</div>
<div class="section" id="boolean-values">
<h3>5.12.10. Boolean Values<a class="headerlink" href="#boolean-values" title="Permalink to this headline">¶</a></h3>
<p>Boolean values are the two constant objects <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>.  They are
used to represent truth values (although other values can also be considered
false or true).  In numeric contexts (for example when used as the argument to
an arithmetic operator), they behave like the integers 0 and 1, respectively.
The built-in function <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> can be used to convert any value to a
Boolean, if the value can be interpreted as a truth value (see section
<a class="reference internal" href="#truth"><span class="std std-ref">Truth Value Testing</span></a> above).</p>
<p id="index-43">They are written as <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>, respectively.</p>
</div>
<div class="section" id="internal-objects">
<span id="typesinternal"></span><h3>5.12.11. Internal Objects<a class="headerlink" href="#internal-objects" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a> for this information.  It describes stack frame objects,
traceback objects, and slice objects.</p>
</div>
</div>
<div class="section" id="special-attributes">
<span id="specialattrs"></span><h2>5.13. Special Attributes<a class="headerlink" href="#special-attributes" title="Permalink to this headline">¶</a></h2>
<p>The implementation adds a few special read-only attributes to several object
types, where they are relevant.  Some of these are not reported by the
<a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> built-in function.</p>
<dl class="attribute">
<dt id="object.__dict__">
<code class="descclassname">object.</code><code class="descname">__dict__</code><a class="headerlink" href="#object.__dict__" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary or other mapping object used to store an object’s (writable)
attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="object.__methods__">
<code class="descclassname">object.</code><code class="descname">__methods__</code><a class="headerlink" href="#object.__methods__" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.2: </span>Use the built-in function <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> to get a list of an object’s attributes.
This attribute is no longer available.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="object.__members__">
<code class="descclassname">object.</code><code class="descname">__members__</code><a class="headerlink" href="#object.__members__" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.2: </span>Use the built-in function <a class="reference internal" href="functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> to get a list of an object’s attributes.
This attribute is no longer available.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="instance.__class__">
<code class="descclassname">instance.</code><code class="descname">__class__</code><a class="headerlink" href="#instance.__class__" title="Permalink to this definition">¶</a></dt>
<dd><p>The class to which a class instance belongs.</p>
</dd></dl>

<dl class="attribute">
<dt id="class.__bases__">
<code class="descclassname">class.</code><code class="descname">__bases__</code><a class="headerlink" href="#class.__bases__" title="Permalink to this definition">¶</a></dt>
<dd><p>The tuple of base classes of a class object.</p>
</dd></dl>

<dl class="attribute">
<dt id="definition.__name__">
<code class="descclassname">definition.</code><code class="descname">__name__</code><a class="headerlink" href="#definition.__name__" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the class, type, function, method, descriptor, or
generator instance.</p>
</dd></dl>

<p>The following attributes are only supported by <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es.</p>
<dl class="attribute">
<dt id="class.__mro__">
<code class="descclassname">class.</code><code class="descname">__mro__</code><a class="headerlink" href="#class.__mro__" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute is a tuple of classes that are considered when looking for
base classes during method resolution.</p>
</dd></dl>

<dl class="method">
<dt id="class.mro">
<code class="descclassname">class.</code><code class="descname">mro</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#class.mro" title="Permalink to this definition">¶</a></dt>
<dd><p>This method can be overridden by a metaclass to customize the method
resolution order for its instances.  It is called at class instantiation, and
its result is stored in <a class="reference internal" href="#class.__mro__" title="class.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasses__">
<code class="descclassname">class.</code><code class="descname">__subclasses__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasses__" title="Permalink to this definition">¶</a></dt>
<dd><p>Each new-style class keeps a list of weak references to its immediate
subclasses.  This method returns a list of all those references still alive.
Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="n">__subclasses__</span><span class="p">()</span>
<span class="go">[&lt;type &#39;bool&#39;&gt;]</span>
</pre></div>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id12" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Additional information on these special methods may be found in the Python
Reference Manual (<a class="reference internal" href="../reference/datamodel.html#customization"><span class="std std-ref">Basic customization</span></a>).</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id13" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>As a consequence, the list <code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2]</span></code> is considered equal to <code class="docutils literal notranslate"><span class="pre">[1.0,</span> <span class="pre">2.0]</span></code>, and
similarly for tuples.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id14" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id4">[3]</a></td><td>They must have since the parser can’t tell the type of the operands.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id15" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[4]</td><td><em>(<a class="fn-backref" href="#id6">1</a>, <a class="fn-backref" href="#id7">2</a>, <a class="fn-backref" href="#id8">3</a>, <a class="fn-backref" href="#id9">4</a>)</em> Cased characters are those with general category property being one of
“Lu” (Letter, uppercase), “Ll” (Letter, lowercase), or “Lt” (Letter, titlecase).</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id16" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id10">[5]</a></td><td>To format only a tuple you should therefore provide a singleton tuple whose only
element is the tuple to be formatted.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id17" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id11">[6]</a></td><td>The advantage of leaving the newline on is that returning an empty string is
then an unambiguous EOF indication.  It is also possible (in cases where it
might matter, for example, if you want to make an exact copy of a file while
scanning its lines) to tell whether the last line of a file ended in a newline
or not (yes this happens!).</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">5. Built-in Types</a><ul>
<li><a class="reference internal" href="#truth-value-testing">5.1. Truth Value Testing</a></li>
<li><a class="reference internal" href="#boolean-operations-and-or-not">5.2. Boolean Operations — <code class="docutils literal notranslate"><span class="pre">and</span></code>, <code class="docutils literal notranslate"><span class="pre">or</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span></code></a></li>
<li><a class="reference internal" href="#comparisons">5.3. Comparisons</a></li>
<li><a class="reference internal" href="#numeric-types-int-float-long-complex">5.4. Numeric Types — <code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">float</span></code>, <code class="docutils literal notranslate"><span class="pre">long</span></code>, <code class="docutils literal notranslate"><span class="pre">complex</span></code></a><ul>
<li><a class="reference internal" href="#bitwise-operations-on-integer-types">5.4.1. Bitwise Operations on Integer Types</a></li>
<li><a class="reference internal" href="#additional-methods-on-integer-types">5.4.2. Additional Methods on Integer Types</a></li>
<li><a class="reference internal" href="#additional-methods-on-float">5.4.3. Additional Methods on Float</a></li>
</ul>
</li>
<li><a class="reference internal" href="#iterator-types">5.5. Iterator Types</a><ul>
<li><a class="reference internal" href="#generator-types">5.5.1. Generator Types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange">5.6. Sequence Types — <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">unicode</span></code>, <code class="docutils literal notranslate"><span class="pre">list</span></code>, <code class="docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="docutils literal notranslate"><span class="pre">bytearray</span></code>, <code class="docutils literal notranslate"><span class="pre">buffer</span></code>, <code class="docutils literal notranslate"><span class="pre">xrange</span></code></a><ul>
<li><a class="reference internal" href="#string-methods">5.6.1. String Methods</a></li>
<li><a class="reference internal" href="#string-formatting-operations">5.6.2. String Formatting Operations</a></li>
<li><a class="reference internal" href="#xrange-type">5.6.3. XRange Type</a></li>
<li><a class="reference internal" href="#mutable-sequence-types">5.6.4. Mutable Sequence Types</a></li>
</ul>
</li>
<li><a class="reference internal" href="#set-types-set-frozenset">5.7. Set Types — <code class="docutils literal notranslate"><span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">frozenset</span></code></a></li>
<li><a class="reference internal" href="#mapping-types-dict">5.8. Mapping Types — <code class="docutils literal notranslate"><span class="pre">dict</span></code></a><ul>
<li><a class="reference internal" href="#dictionary-view-objects">5.8.1. Dictionary view objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#file-objects">5.9. File Objects</a></li>
<li><a class="reference internal" href="#memoryview-type">5.10. memoryview type</a></li>
<li><a class="reference internal" href="#context-manager-types">5.11. Context Manager Types</a></li>
<li><a class="reference internal" href="#other-built-in-types">5.12. Other Built-in Types</a><ul>
<li><a class="reference internal" href="#modules">5.12.1. Modules</a></li>
<li><a class="reference internal" href="#classes-and-class-instances">5.12.2. Classes and Class Instances</a></li>
<li><a class="reference internal" href="#functions">5.12.3. Functions</a></li>
<li><a class="reference internal" href="#methods">5.12.4. Methods</a></li>
<li><a class="reference internal" href="#code-objects">5.12.5. Code Objects</a></li>
<li><a class="reference internal" href="#type-objects">5.12.6. Type Objects</a></li>
<li><a class="reference internal" href="#the-null-object">5.12.7. The Null Object</a></li>
<li><a class="reference internal" href="#the-ellipsis-object">5.12.8. The Ellipsis Object</a></li>
<li><a class="reference internal" href="#the-notimplemented-object">5.12.9. The NotImplemented Object</a></li>
<li><a class="reference internal" href="#boolean-values">5.12.10. Boolean Values</a></li>
<li><a class="reference internal" href="#internal-objects">5.12.11. Internal Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#special-attributes">5.13. Special Attributes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="constants.html"
                        title="previous chapter">4. Built-in Constants</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="exceptions.html"
                        title="next chapter">6. Built-in Exceptions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/stdtypes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="6. Built-in Exceptions"
             >next</a> |</li>
        <li class="right" >
          <a href="constants.html" title="4. Built-in Constants"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��Y����html/library/string.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.1. string — Common string operations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.2. re — Regular expression operations" href="re.html" />
    <link rel="prev" title="7. String Services" href="strings.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/string.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="re.html" title="7.2. re — Regular expression operations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="strings.html" title="7. String Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-string">
<span id="string-common-string-operations"></span><h1>7.1. <a class="reference internal" href="#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> — Common string operations<a class="headerlink" href="#module-string" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/string.py">Lib/string.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module contains a number of useful constants and
classes, as well as some deprecated legacy functions that are also
available as methods on strings. In addition, Python’s built-in string
classes support the sequence type methods described in the
<a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a> section, and also the string-specific methods described
in the <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a> section. To output formatted strings use
template strings or the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator described in the
<a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section. Also, see the <a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module for
string functions based on regular expressions.</p>
<div class="section" id="string-constants">
<h2>7.1.1. String constants<a class="headerlink" href="#string-constants" title="Permalink to this headline">¶</a></h2>
<p>The constants defined in this module are:</p>
<dl class="data">
<dt id="string.ascii_letters">
<code class="descclassname">string.</code><code class="descname">ascii_letters</code><a class="headerlink" href="#string.ascii_letters" title="Permalink to this definition">¶</a></dt>
<dd><p>The concatenation of the <a class="reference internal" href="#string.ascii_lowercase" title="string.ascii_lowercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_lowercase</span></code></a> and <a class="reference internal" href="#string.ascii_uppercase" title="string.ascii_uppercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_uppercase</span></code></a>
constants described below.  This value is not locale-dependent.</p>
</dd></dl>

<dl class="data">
<dt id="string.ascii_lowercase">
<code class="descclassname">string.</code><code class="descname">ascii_lowercase</code><a class="headerlink" href="#string.ascii_lowercase" title="Permalink to this definition">¶</a></dt>
<dd><p>The lowercase letters <code class="docutils literal notranslate"><span class="pre">'abcdefghijklmnopqrstuvwxyz'</span></code>.  This value is not
locale-dependent and will not change.</p>
</dd></dl>

<dl class="data">
<dt id="string.ascii_uppercase">
<code class="descclassname">string.</code><code class="descname">ascii_uppercase</code><a class="headerlink" href="#string.ascii_uppercase" title="Permalink to this definition">¶</a></dt>
<dd><p>The uppercase letters <code class="docutils literal notranslate"><span class="pre">'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code>.  This value is not
locale-dependent and will not change.</p>
</dd></dl>

<dl class="data">
<dt id="string.digits">
<code class="descclassname">string.</code><code class="descname">digits</code><a class="headerlink" href="#string.digits" title="Permalink to this definition">¶</a></dt>
<dd><p>The string <code class="docutils literal notranslate"><span class="pre">'0123456789'</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="string.hexdigits">
<code class="descclassname">string.</code><code class="descname">hexdigits</code><a class="headerlink" href="#string.hexdigits" title="Permalink to this definition">¶</a></dt>
<dd><p>The string <code class="docutils literal notranslate"><span class="pre">'0123456789abcdefABCDEF'</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="string.letters">
<code class="descclassname">string.</code><code class="descname">letters</code><a class="headerlink" href="#string.letters" title="Permalink to this definition">¶</a></dt>
<dd><p>The concatenation of the strings <a class="reference internal" href="#string.lowercase" title="string.lowercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">lowercase</span></code></a> and <a class="reference internal" href="#string.uppercase" title="string.uppercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">uppercase</span></code></a>
described below.  The specific value is locale-dependent, and will be updated
when <a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.setlocale()</span></code></a> is called.</p>
</dd></dl>

<dl class="data">
<dt id="string.lowercase">
<code class="descclassname">string.</code><code class="descname">lowercase</code><a class="headerlink" href="#string.lowercase" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing all the characters that are considered lowercase letters.
On most systems this is the string <code class="docutils literal notranslate"><span class="pre">'abcdefghijklmnopqrstuvwxyz'</span></code>.  The
specific value is locale-dependent, and will be updated when
<a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.setlocale()</span></code></a> is called.</p>
</dd></dl>

<dl class="data">
<dt id="string.octdigits">
<code class="descclassname">string.</code><code class="descname">octdigits</code><a class="headerlink" href="#string.octdigits" title="Permalink to this definition">¶</a></dt>
<dd><p>The string <code class="docutils literal notranslate"><span class="pre">'01234567'</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="string.punctuation">
<code class="descclassname">string.</code><code class="descname">punctuation</code><a class="headerlink" href="#string.punctuation" title="Permalink to this definition">¶</a></dt>
<dd><p>String of ASCII characters which are considered punctuation characters in the
<code class="docutils literal notranslate"><span class="pre">C</span></code> locale.</p>
</dd></dl>

<dl class="data">
<dt id="string.printable">
<code class="descclassname">string.</code><code class="descname">printable</code><a class="headerlink" href="#string.printable" title="Permalink to this definition">¶</a></dt>
<dd><p>String of characters which are considered printable.  This is a combination of
<a class="reference internal" href="#string.digits" title="string.digits"><code class="xref py py-const docutils literal notranslate"><span class="pre">digits</span></code></a>, <a class="reference internal" href="#string.letters" title="string.letters"><code class="xref py py-const docutils literal notranslate"><span class="pre">letters</span></code></a>, <a class="reference internal" href="#string.punctuation" title="string.punctuation"><code class="xref py py-const docutils literal notranslate"><span class="pre">punctuation</span></code></a>, and
<a class="reference internal" href="#string.whitespace" title="string.whitespace"><code class="xref py py-const docutils literal notranslate"><span class="pre">whitespace</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="string.uppercase">
<code class="descclassname">string.</code><code class="descname">uppercase</code><a class="headerlink" href="#string.uppercase" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing all the characters that are considered uppercase letters.
On most systems this is the string <code class="docutils literal notranslate"><span class="pre">'ABCDEFGHIJKLMNOPQRSTUVWXYZ'</span></code>.  The
specific value is locale-dependent, and will be updated when
<a class="reference internal" href="locale.html#locale.setlocale" title="locale.setlocale"><code class="xref py py-func docutils literal notranslate"><span class="pre">locale.setlocale()</span></code></a> is called.</p>
</dd></dl>

<dl class="data">
<dt id="string.whitespace">
<code class="descclassname">string.</code><code class="descname">whitespace</code><a class="headerlink" href="#string.whitespace" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing all characters that are considered whitespace. On most
systems this includes the characters space, tab, linefeed, return, formfeed, and
vertical tab.</p>
</dd></dl>

</div>
<div class="section" id="custom-string-formatting">
<span id="new-string-formatting"></span><h2>7.1.2. Custom String Formatting<a class="headerlink" href="#custom-string-formatting" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The built-in str and unicode classes provide the ability
to do complex variable substitutions and value formatting via the
<a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method described in <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a>.  The <a class="reference internal" href="#string.Formatter" title="string.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>
class in the <a class="reference internal" href="#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module allows you to create and customize your own
string formatting behaviors using the same implementation as the built-in
<a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> method.</p>
<dl class="class">
<dt id="string.Formatter">
<em class="property">class </em><code class="descclassname">string.</code><code class="descname">Formatter</code><a class="headerlink" href="#string.Formatter" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#string.Formatter" title="string.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> class has the following public methods:</p>
<dl class="method">
<dt id="string.Formatter.format">
<code class="descname">format</code><span class="sig-paren">(</span><em>format_string</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.format" title="Permalink to this definition">¶</a></dt>
<dd><p>The primary API method.  It takes a format string and
an arbitrary set of positional and keyword arguments.
It is just a wrapper that calls <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">vformat()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.vformat">
<code class="descname">vformat</code><span class="sig-paren">(</span><em>format_string</em>, <em>args</em>, <em>kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.vformat" title="Permalink to this definition">¶</a></dt>
<dd><p>This function does the actual work of formatting.  It is exposed as a
separate function for cases where you want to pass in a predefined
dictionary of arguments, rather than unpacking and repacking the
dictionary as individual arguments using the <code class="docutils literal notranslate"><span class="pre">*args</span></code> and <code class="docutils literal notranslate"><span class="pre">**kwargs</span></code>
syntax.  <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">vformat()</span></code></a> does the work of breaking up the format string
into character data and replacement fields.  It calls the various
methods described below.</p>
</dd></dl>

<p>In addition, the <a class="reference internal" href="#string.Formatter" title="string.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> defines a number of methods that are
intended to be replaced by subclasses:</p>
<dl class="method">
<dt id="string.Formatter.parse">
<code class="descname">parse</code><span class="sig-paren">(</span><em>format_string</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Loop over the format_string and return an iterable of tuples
(<em>literal_text</em>, <em>field_name</em>, <em>format_spec</em>, <em>conversion</em>).  This is used
by <a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">vformat()</span></code></a> to break the string into either literal text, or
replacement fields.</p>
<p>The values in the tuple conceptually represent a span of literal text
followed by a single replacement field.  If there is no literal text
(which can happen if two replacement fields occur consecutively), then
<em>literal_text</em> will be a zero-length string.  If there is no replacement
field, then the values of <em>field_name</em>, <em>format_spec</em> and <em>conversion</em>
will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.get_field">
<code class="descname">get_field</code><span class="sig-paren">(</span><em>field_name</em>, <em>args</em>, <em>kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.get_field" title="Permalink to this definition">¶</a></dt>
<dd><p>Given <em>field_name</em> as returned by <a class="reference internal" href="#string.Formatter.parse" title="string.Formatter.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> (see above), convert it to
an object to be formatted.  Returns a tuple (obj, used_key).  The default
version takes strings of the form defined in <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a>, such as
“0[name]” or “label.title”.  <em>args</em> and <em>kwargs</em> are as passed in to
<a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">vformat()</span></code></a>.  The return value <em>used_key</em> has the same meaning as the
<em>key</em> parameter to <a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_value()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.get_value">
<code class="descname">get_value</code><span class="sig-paren">(</span><em>key</em>, <em>args</em>, <em>kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.get_value" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve a given field value.  The <em>key</em> argument will be either an
integer or a string.  If it is an integer, it represents the index of the
positional argument in <em>args</em>; if it is a string, then it represents a
named argument in <em>kwargs</em>.</p>
<p>The <em>args</em> parameter is set to the list of positional arguments to
<a class="reference internal" href="#string.Formatter.vformat" title="string.Formatter.vformat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">vformat()</span></code></a>, and the <em>kwargs</em> parameter is set to the dictionary of
keyword arguments.</p>
<p>For compound field names, these functions are only called for the first
component of the field name; Subsequent components are handled through
normal attribute and indexing operations.</p>
<p>So for example, the field expression ‘0.name’ would cause
<a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_value()</span></code></a> to be called with a <em>key</em> argument of 0.  The <code class="docutils literal notranslate"><span class="pre">name</span></code>
attribute will be looked up after <a class="reference internal" href="#string.Formatter.get_value" title="string.Formatter.get_value"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_value()</span></code></a> returns by calling the
built-in <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> function.</p>
<p>If the index or keyword refers to an item that does not exist, then an
<a class="reference internal" href="exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> should be raised.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.check_unused_args">
<code class="descname">check_unused_args</code><span class="sig-paren">(</span><em>used_args</em>, <em>args</em>, <em>kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.check_unused_args" title="Permalink to this definition">¶</a></dt>
<dd><p>Implement checking for unused arguments if desired.  The arguments to this
function is the set of all argument keys that were actually referred to in
the format string (integers for positional arguments, and strings for
named arguments), and a reference to the <em>args</em> and <em>kwargs</em> that was
passed to vformat.  The set of unused args can be calculated from these
parameters.  <a class="reference internal" href="#string.Formatter.check_unused_args" title="string.Formatter.check_unused_args"><code class="xref py py-meth docutils literal notranslate"><span class="pre">check_unused_args()</span></code></a> is assumed to raise an exception if
the check fails.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.format_field">
<code class="descname">format_field</code><span class="sig-paren">(</span><em>value</em>, <em>format_spec</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.format_field" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#string.Formatter.format_field" title="string.Formatter.format_field"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format_field()</span></code></a> simply calls the global <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> built-in.  The
method is provided so that subclasses can override it.</p>
</dd></dl>

<dl class="method">
<dt id="string.Formatter.convert_field">
<code class="descname">convert_field</code><span class="sig-paren">(</span><em>value</em>, <em>conversion</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Formatter.convert_field" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the value (returned by <a class="reference internal" href="#string.Formatter.get_field" title="string.Formatter.get_field"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_field()</span></code></a>) given a conversion type
(as in the tuple returned by the <a class="reference internal" href="#string.Formatter.parse" title="string.Formatter.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> method).  The default
version understands ‘s’ (str), ‘r’ (repr) and ‘a’ (ascii) conversion
types.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="format-string-syntax">
<span id="formatstrings"></span><h2>7.1.3. Format String Syntax<a class="headerlink" href="#format-string-syntax" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method and the <a class="reference internal" href="#string.Formatter" title="string.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a> class share the same
syntax for format strings (although in the case of <a class="reference internal" href="#string.Formatter" title="string.Formatter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code></a>,
subclasses can define their own format string syntax).</p>
<p>Format strings contain “replacement fields” surrounded by curly braces <code class="docutils literal notranslate"><span class="pre">{}</span></code>.
Anything that is not contained in braces is considered literal text, which is
copied unchanged to the output.  If you need to include a brace character in the
literal text, it can be escaped by doubling: <code class="docutils literal notranslate"><span class="pre">{{</span></code> and <code class="docutils literal notranslate"><span class="pre">}}</span></code>.</p>
<p>The grammar for a replacement field is as follows:</p>
<blockquote>
<div><pre>
<strong id="grammar-token-replacement_field">replacement_field</strong> ::=  &quot;{&quot; [<a class="reference internal" href="#grammar-token-field_name"><code class="xref docutils literal notranslate"><span class="pre">field_name</span></code></a>] [&quot;!&quot; <a class="reference internal" href="#grammar-token-conversion"><code class="xref docutils literal notranslate"><span class="pre">conversion</span></code></a>] [&quot;:&quot; <a class="reference internal" href="#grammar-token-format_spec"><code class="xref docutils literal notranslate"><span class="pre">format_spec</span></code></a>] &quot;}&quot;
<strong id="grammar-token-field_name">field_name       </strong> ::=  arg_name (&quot;.&quot; <a class="reference internal" href="#grammar-token-attribute_name"><code class="xref docutils literal notranslate"><span class="pre">attribute_name</span></code></a> | &quot;[&quot; <a class="reference internal" href="#grammar-token-element_index"><code class="xref docutils literal notranslate"><span class="pre">element_index</span></code></a> &quot;]&quot;)*
<strong id="grammar-token-arg_name">arg_name         </strong> ::=  [<a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a>]
<strong id="grammar-token-attribute_name">attribute_name   </strong> ::=  <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
<strong id="grammar-token-element_index">element_index    </strong> ::=  <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> | <a class="reference internal" href="#grammar-token-index_string"><code class="xref docutils literal notranslate"><span class="pre">index_string</span></code></a>
<strong id="grammar-token-index_string">index_string     </strong> ::=  &lt;any source character except &quot;]&quot;&gt; +
<strong id="grammar-token-conversion">conversion       </strong> ::=  &quot;r&quot; | &quot;s&quot;
<strong id="grammar-token-format_spec">format_spec      </strong> ::=  &lt;described in the next section&gt;
</pre>
</div></blockquote>
<p>In less formal terms, the replacement field can start with a <em>field_name</em> that specifies
the object whose value is to be formatted and inserted
into the output instead of the replacement field.
The <em>field_name</em> is optionally followed by a  <em>conversion</em> field, which is
preceded by an exclamation point <code class="docutils literal notranslate"><span class="pre">'!'</span></code>, and a <em>format_spec</em>, which is preceded
by a colon <code class="docutils literal notranslate"><span class="pre">':'</span></code>.  These specify a non-default format for the replacement value.</p>
<p>See also the <a class="reference internal" href="#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a> section.</p>
<p>The <em>field_name</em> itself begins with an <em>arg_name</em> that is either a number or a
keyword.  If it’s a number, it refers to a positional argument, and if it’s a keyword,
it refers to a named keyword argument.  If the numerical arg_names in a format string
are 0, 1, 2, … in sequence, they can all be omitted (not just some)
and the numbers 0, 1, 2, … will be automatically inserted in that order.
Because <em>arg_name</em> is not quote-delimited, it is not possible to specify arbitrary
dictionary keys (e.g., the strings <code class="docutils literal notranslate"><span class="pre">'10'</span></code> or <code class="docutils literal notranslate"><span class="pre">':-]'</span></code>) within a format string.
The <em>arg_name</em> can be followed by any number of index or
attribute expressions. An expression of the form <code class="docutils literal notranslate"><span class="pre">'.name'</span></code> selects the named
attribute using <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a>, while an expression of the form <code class="docutils literal notranslate"><span class="pre">'[index]'</span></code>
does an index lookup using <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The positional argument specifiers can be omitted for <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">unicode.format()</span></code>, so <code class="docutils literal notranslate"><span class="pre">'{}</span> <span class="pre">{}'</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">'{0}</span> <span class="pre">{1}'</span></code>,
<code class="docutils literal notranslate"><span class="pre">u'{}</span> <span class="pre">{}'</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">u'{0}</span> <span class="pre">{1}'</span></code>.</p>
</div>
<p>Some simple format string examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;First, thou shalt count to </span><span class="si">{0}</span><span class="s2">&quot;</span>  <span class="c1"># References first positional argument</span>
<span class="s2">&quot;Bring me a </span><span class="si">{}</span><span class="s2">&quot;</span>                   <span class="c1"># Implicitly references the first positional argument</span>
<span class="s2">&quot;From </span><span class="si">{}</span><span class="s2"> to </span><span class="si">{}</span><span class="s2">&quot;</span>                   <span class="c1"># Same as &quot;From {0} to {1}&quot;</span>
<span class="s2">&quot;My quest is </span><span class="si">{name}</span><span class="s2">&quot;</span>              <span class="c1"># References keyword argument &#39;name&#39;</span>
<span class="s2">&quot;Weight in tons </span><span class="si">{0.weight}</span><span class="s2">&quot;</span>       <span class="c1"># &#39;weight&#39; attribute of first positional arg</span>
<span class="s2">&quot;Units destroyed: </span><span class="si">{players[0]}</span><span class="s2">&quot;</span>   <span class="c1"># First element of keyword argument &#39;players&#39;.</span>
</pre></div>
</div>
<p>The <em>conversion</em> field causes a type coercion before formatting.  Normally, the
job of formatting a value is done by the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method of the value
itself.  However, in some cases it is desirable to force a type to be formatted
as a string, overriding its own definition of formatting.  By converting the
value to a string before calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code>, the normal formatting logic
is bypassed.</p>
<p>Two conversion flags are currently supported: <code class="docutils literal notranslate"><span class="pre">'!s'</span></code> which calls <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>
on the value, and <code class="docutils literal notranslate"><span class="pre">'!r'</span></code> which calls <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.</p>
<p>Some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;Harold&#39;s a clever </span><span class="si">{0!s}</span><span class="s2">&quot;</span>        <span class="c1"># Calls str() on the argument first</span>
<span class="s2">&quot;Bring out the holy </span><span class="si">{name!r}</span><span class="s2">&quot;</span>    <span class="c1"># Calls repr() on the argument first</span>
</pre></div>
</div>
<p>The <em>format_spec</em> field contains a specification of how the value should be
presented, including such details as field width, alignment, padding, decimal
precision and so on.  Each value type can define its own “formatting
mini-language” or interpretation of the <em>format_spec</em>.</p>
<p>Most built-in types support a common formatting mini-language, which is
described in the next section.</p>
<p>A <em>format_spec</em> field can also include nested replacement fields within it.
These nested replacement fields may contain a field name, conversion flag
and format specification, but deeper nesting is
not allowed.  The replacement fields within the
format_spec are substituted before the <em>format_spec</em> string is interpreted.
This allows the formatting of a value to be dynamically specified.</p>
<p>See the <a class="reference internal" href="#formatexamples"><span class="std std-ref">Format examples</span></a> section for some examples.</p>
<div class="section" id="format-specification-mini-language">
<span id="formatspec"></span><h3>7.1.3.1. Format Specification Mini-Language<a class="headerlink" href="#format-specification-mini-language" title="Permalink to this headline">¶</a></h3>
<p>“Format specifications” are used within replacement fields contained within a
format string to define how individual values are presented (see
<a class="reference internal" href="#formatstrings"><span class="std std-ref">Format String Syntax</span></a>).  They can also be passed directly to the built-in
<a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> function.  Each formattable type may define how the format
specification is to be interpreted.</p>
<p>Most built-in types implement the following options for format specifications,
although some of the formatting options are only supported by the numeric types.</p>
<p>A general convention is that an empty format string (<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code>) produces
the same result as if you had called <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> on the value. A
non-empty format string typically modifies the result.</p>
<p>The general form of a <em>standard format specifier</em> is:</p>
<pre>
<strong id="id1">format_spec</strong> ::=  [[<a class="reference internal" href="#grammar-token-fill"><code class="xref docutils literal notranslate"><span class="pre">fill</span></code></a>]<a class="reference internal" href="#grammar-token-align"><code class="xref docutils literal notranslate"><span class="pre">align</span></code></a>][<a class="reference internal" href="#grammar-token-sign"><code class="xref docutils literal notranslate"><span class="pre">sign</span></code></a>][#][0][<a class="reference internal" href="#grammar-token-width"><code class="xref docutils literal notranslate"><span class="pre">width</span></code></a>][,][.<a class="reference internal" href="#grammar-token-precision"><code class="xref docutils literal notranslate"><span class="pre">precision</span></code></a>][<a class="reference internal" href="#grammar-token-type"><code class="xref docutils literal notranslate"><span class="pre">type</span></code></a>]
<strong id="grammar-token-fill">fill       </strong> ::=  &lt;any character&gt;
<strong id="grammar-token-align">align      </strong> ::=  &quot;&lt;&quot; | &quot;&gt;&quot; | &quot;=&quot; | &quot;^&quot;
<strong id="grammar-token-sign">sign       </strong> ::=  &quot;+&quot; | &quot;-&quot; | &quot; &quot;
<strong id="grammar-token-width">width      </strong> ::=  <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a>
<strong id="grammar-token-precision">precision  </strong> ::=  <a class="reference internal" href="../reference/lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a>
<strong id="grammar-token-type">type       </strong> ::=  &quot;b&quot; | &quot;c&quot; | &quot;d&quot; | &quot;e&quot; | &quot;E&quot; | &quot;f&quot; | &quot;F&quot; | &quot;g&quot; | &quot;G&quot; | &quot;n&quot; | &quot;o&quot; | &quot;s&quot; | &quot;x&quot; | &quot;X&quot; | &quot;%&quot;
</pre>
<p>If a valid <em>align</em> value is specified, it can be preceded by a <em>fill</em>
character that can be any character and defaults to a space if omitted.
It is not possible to use a literal curly brace (“<code class="docutils literal notranslate"><span class="pre">{</span></code>” or “<code class="docutils literal notranslate"><span class="pre">}</span></code>”) as
the <em>fill</em> character when using the <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>
method.  However, it is possible to insert a curly brace
with a nested replacement field.  This limitation doesn’t
affect the <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> function.</p>
<p>The meaning of the various alignment options is as follows:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Option</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code></td>
<td>Forces the field to be left-aligned within the available
space (this is the default for most objects).</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code></td>
<td>Forces the field to be right-aligned within the
available space (this is the default for numbers).</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'='</span></code></td>
<td>Forces the padding to be placed after the sign (if any)
but before the digits.  This is used for printing fields
in the form ‘+000000120’. This alignment option is only
valid for numeric types.  It becomes the default when ‘0’
immediately precedes the field width.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'^'</span></code></td>
<td>Forces the field to be centered within the available
space.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>Note that unless a minimum field width is defined, the field width will always
be the same size as the data to fill it, so that the alignment option has no
meaning in this case.</p>
<p>The <em>sign</em> option is only valid for number types, and can be one of the
following:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Option</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'+'</span></code></td>
<td>indicates that a sign should be used for both
positive as well as negative numbers.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'-'</span></code></td>
<td>indicates that a sign should be used only for negative
numbers (this is the default behavior).</td>
</tr>
<tr class="row-even"><td>space</td>
<td>indicates that a leading space should be used on
positive numbers, and a minus sign on negative numbers.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>The <code class="docutils literal notranslate"><span class="pre">'#'</span></code> option is only valid for integers, and only for binary, octal, or
hexadecimal output.  If present, it specifies that the output will be prefixed
by <code class="docutils literal notranslate"><span class="pre">'0b'</span></code>, <code class="docutils literal notranslate"><span class="pre">'0o'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'0x'</span></code>, respectively.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">','</span></code> option signals the use of a comma for a thousands separator.
For a locale aware separator, use the <code class="docutils literal notranslate"><span class="pre">'n'</span></code> integer presentation type
instead.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the <code class="docutils literal notranslate"><span class="pre">','</span></code> option (see also <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0378"><strong>PEP 378</strong></a>).</p>
</div>
<p><em>width</em> is a decimal integer defining the minimum field width.  If not
specified, then the field width will be determined by the content.</p>
<p>When no explicit alignment is given, preceding the <em>width</em> field by a zero
(<code class="docutils literal notranslate"><span class="pre">'0'</span></code>) character enables
sign-aware zero-padding for numeric types.  This is equivalent to a <em>fill</em>
character of <code class="docutils literal notranslate"><span class="pre">'0'</span></code> with an <em>alignment</em> type of <code class="docutils literal notranslate"><span class="pre">'='</span></code>.</p>
<p>The <em>precision</em> is a decimal number indicating how many digits should be
displayed after the decimal point for a floating point value formatted with
<code class="docutils literal notranslate"><span class="pre">'f'</span></code> and <code class="docutils literal notranslate"><span class="pre">'F'</span></code>, or before and after the decimal point for a floating point
value formatted with <code class="docutils literal notranslate"><span class="pre">'g'</span></code> or <code class="docutils literal notranslate"><span class="pre">'G'</span></code>.  For non-number types the field
indicates the maximum field size - in other words, how many characters will be
used from the field content. The <em>precision</em> is not allowed for integer values.</p>
<p>Finally, the <em>type</em> determines how the data should be presented.</p>
<p>The available string presentation types are:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'s'</span></code></td>
<td>String format. This is the default type for strings and
may be omitted.</td>
</tr>
<tr class="row-odd"><td>None</td>
<td>The same as <code class="docutils literal notranslate"><span class="pre">'s'</span></code>.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>The available integer presentation types are:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'b'</span></code></td>
<td>Binary format. Outputs the number in base 2.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'c'</span></code></td>
<td>Character. Converts the integer to the corresponding
unicode character before printing.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'d'</span></code></td>
<td>Decimal Integer. Outputs the number in base 10.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'o'</span></code></td>
<td>Octal format. Outputs the number in base 8.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'x'</span></code></td>
<td>Hex format. Outputs the number in base 16, using lower-
case letters for the digits above 9.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'X'</span></code></td>
<td>Hex format. Outputs the number in base 16, using upper-
case letters for the digits above 9.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Number. This is the same as <code class="docutils literal notranslate"><span class="pre">'d'</span></code>, except that it uses
the current locale setting to insert the appropriate
number separator characters.</td>
</tr>
<tr class="row-odd"><td>None</td>
<td>The same as <code class="docutils literal notranslate"><span class="pre">'d'</span></code>.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>In addition to the above presentation types, integers can be formatted
with the floating point presentation types listed below (except
<code class="docutils literal notranslate"><span class="pre">'n'</span></code> and <code class="docutils literal notranslate"><span class="pre">None</span></code>). When doing so, <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> is used to convert the
integer to a floating point number before formatting.</p>
<p>The available presentation types for floating point and decimal values are:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="87%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'e'</span></code></td>
<td>Exponent notation. Prints the number in scientific
notation using the letter ‘e’ to indicate the exponent.
The default precision is <code class="docutils literal notranslate"><span class="pre">6</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'E'</span></code></td>
<td>Exponent notation. Same as <code class="docutils literal notranslate"><span class="pre">'e'</span></code> except it uses an
upper case ‘E’ as the separator character.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'f'</span></code></td>
<td>Fixed-point notation. Displays the number as a
fixed-point number.  The default precision is <code class="docutils literal notranslate"><span class="pre">6</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'F'</span></code></td>
<td>Fixed point notation. Same as <code class="docutils literal notranslate"><span class="pre">'f'</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'g'</span></code></td>
<td><p class="first">General format.  For a given precision <code class="docutils literal notranslate"><span class="pre">p</span> <span class="pre">&gt;=</span> <span class="pre">1</span></code>,
this rounds the number to <code class="docutils literal notranslate"><span class="pre">p</span></code> significant digits and
then formats the result in either fixed-point format
or in scientific notation, depending on its magnitude.</p>
<p>The precise rules are as follows: suppose that the
result formatted with presentation type <code class="docutils literal notranslate"><span class="pre">'e'</span></code> and
precision <code class="docutils literal notranslate"><span class="pre">p-1</span></code> would have exponent <code class="docutils literal notranslate"><span class="pre">exp</span></code>.  Then
if <code class="docutils literal notranslate"><span class="pre">-4</span> <span class="pre">&lt;=</span> <span class="pre">exp</span> <span class="pre">&lt;</span> <span class="pre">p</span></code>, the number is formatted
with presentation type <code class="docutils literal notranslate"><span class="pre">'f'</span></code> and precision
<code class="docutils literal notranslate"><span class="pre">p-1-exp</span></code>.  Otherwise, the number is formatted
with presentation type <code class="docutils literal notranslate"><span class="pre">'e'</span></code> and precision <code class="docutils literal notranslate"><span class="pre">p-1</span></code>.
In both cases insignificant trailing zeros are removed
from the significand, and the decimal point is also
removed if there are no remaining digits following it.</p>
<p>Positive and negative infinity, positive and negative
zero, and nans, are formatted as <code class="docutils literal notranslate"><span class="pre">inf</span></code>, <code class="docutils literal notranslate"><span class="pre">-inf</span></code>,
<code class="docutils literal notranslate"><span class="pre">0</span></code>, <code class="docutils literal notranslate"><span class="pre">-0</span></code> and <code class="docutils literal notranslate"><span class="pre">nan</span></code> respectively, regardless of
the precision.</p>
<p class="last">A precision of <code class="docutils literal notranslate"><span class="pre">0</span></code> is treated as equivalent to a
precision of <code class="docutils literal notranslate"><span class="pre">1</span></code>.  The default precision is <code class="docutils literal notranslate"><span class="pre">6</span></code>.</p>
</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'G'</span></code></td>
<td>General format. Same as <code class="docutils literal notranslate"><span class="pre">'g'</span></code> except switches to
<code class="docutils literal notranslate"><span class="pre">'E'</span></code> if the number gets too large. The
representations of infinity and NaN are uppercased, too.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'n'</span></code></td>
<td>Number. This is the same as <code class="docutils literal notranslate"><span class="pre">'g'</span></code>, except that it uses
the current locale setting to insert the appropriate
number separator characters.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'%'</span></code></td>
<td>Percentage. Multiplies the number by 100 and displays
in fixed (<code class="docutils literal notranslate"><span class="pre">'f'</span></code>) format, followed by a percent sign.</td>
</tr>
<tr class="row-even"><td>None</td>
<td>The same as <code class="docutils literal notranslate"><span class="pre">'g'</span></code>.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="format-examples">
<span id="formatexamples"></span><h3>7.1.3.2. Format examples<a class="headerlink" href="#format-examples" title="Permalink to this headline">¶</a></h3>
<p>This section contains examples of the <a class="reference internal" href="stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> syntax and
comparison with the old <code class="docutils literal notranslate"><span class="pre">%</span></code>-formatting.</p>
<p>In most of the cases the syntax is similar to the old <code class="docutils literal notranslate"><span class="pre">%</span></code>-formatting, with the
addition of the <code class="docutils literal notranslate"><span class="pre">{}</span></code> and with <code class="docutils literal notranslate"><span class="pre">:</span></code> used instead of <code class="docutils literal notranslate"><span class="pre">%</span></code>.
For example, <code class="docutils literal notranslate"><span class="pre">'%03.2f'</span></code> can be translated to <code class="docutils literal notranslate"><span class="pre">'{:03.2f}'</span></code>.</p>
<p>The new format syntax also supports new and different options, shown in the
following examples.</p>
<p>Accessing arguments by position:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, </span><span class="si">{2}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="go">&#39;a, b, c&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{}</span><span class="s1">, </span><span class="si">{}</span><span class="s1">, </span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>  <span class="c1"># 2.7+ only</span>
<span class="go">&#39;a, b, c&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{2}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, </span><span class="si">{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="go">&#39;c, b, a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{2}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, </span><span class="si">{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="s1">&#39;abc&#39;</span><span class="p">)</span>      <span class="c1"># unpacking argument sequence</span>
<span class="go">&#39;c, b, a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0}{1}{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;abra&#39;</span><span class="p">,</span> <span class="s1">&#39;cad&#39;</span><span class="p">)</span>   <span class="c1"># arguments&#39; indices can be repeated</span>
<span class="go">&#39;abracadabra&#39;</span>
</pre></div>
</div>
<p>Accessing arguments by name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Coordinates: </span><span class="si">{latitude}</span><span class="s1">, </span><span class="si">{longitude}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">latitude</span><span class="o">=</span><span class="s1">&#39;37.24N&#39;</span><span class="p">,</span> <span class="n">longitude</span><span class="o">=</span><span class="s1">&#39;-115.81W&#39;</span><span class="p">)</span>
<span class="go">&#39;Coordinates: 37.24N, -115.81W&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">coord</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;latitude&#39;</span><span class="p">:</span> <span class="s1">&#39;37.24N&#39;</span><span class="p">,</span> <span class="s1">&#39;longitude&#39;</span><span class="p">:</span> <span class="s1">&#39;-115.81W&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Coordinates: </span><span class="si">{latitude}</span><span class="s1">, </span><span class="si">{longitude}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">coord</span><span class="p">)</span>
<span class="go">&#39;Coordinates: 37.24N, -115.81W&#39;</span>
</pre></div>
</div>
<p>Accessing arguments’ attributes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="mi">3</span><span class="o">-</span><span class="mi">5</span><span class="n">j</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;The complex number </span><span class="si">{0}</span><span class="s1"> is formed from the real part </span><span class="si">{0.real}</span><span class="s1"> &#39;</span>
<span class="gp">... </span> <span class="s1">&#39;and the imaginary part </span><span class="si">{0.imag}</span><span class="s1">.&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="go">&#39;The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Point</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">x</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">y</span> <span class="o">=</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;Point(</span><span class="si">{self.x}</span><span class="s1">, </span><span class="si">{self.y}</span><span class="s1">)&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">=</span><span class="bp">self</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">Point</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">&#39;Point(4, 2)&#39;</span>
</pre></div>
</div>
<p>Accessing arguments’ items:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">coord</span> <span class="o">=</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;X: </span><span class="si">{0[0]}</span><span class="s1">;  Y: </span><span class="si">{0[1]}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">coord</span><span class="p">)</span>
<span class="go">&#39;X: 3;  Y: 5&#39;</span>
</pre></div>
</div>
<p>Replacing <code class="docutils literal notranslate"><span class="pre">%s</span></code> and <code class="docutils literal notranslate"><span class="pre">%r</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;repr() shows quotes: </span><span class="si">{!r}</span><span class="s2">; str() doesn&#39;t: </span><span class="si">{!s}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;test1&#39;</span><span class="p">,</span> <span class="s1">&#39;test2&#39;</span><span class="p">)</span>
<span class="go">&quot;repr() shows quotes: &#39;test1&#39;; str() doesn&#39;t: test2&quot;</span>
</pre></div>
</div>
<p>Aligning the text and specifying a width:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:&lt;30}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;left aligned&#39;</span><span class="p">)</span>
<span class="go">&#39;left aligned                  &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:&gt;30}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;right aligned&#39;</span><span class="p">)</span>
<span class="go">&#39;                 right aligned&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:^30}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;centered&#39;</span><span class="p">)</span>
<span class="go">&#39;           centered           &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:*^30}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;centered&#39;</span><span class="p">)</span>  <span class="c1"># use &#39;*&#39; as a fill char</span>
<span class="go">&#39;***********centered***********&#39;</span>
</pre></div>
</div>
<p>Replacing <code class="docutils literal notranslate"><span class="pre">%+f</span></code>, <code class="docutils literal notranslate"><span class="pre">%-f</span></code>, and <code class="docutils literal notranslate"><span class="pre">%</span> <span class="pre">f</span></code> and specifying a sign:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:+f}</span><span class="s1">; </span><span class="si">{:+f}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.14</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.14</span><span class="p">)</span>  <span class="c1"># show it always</span>
<span class="go">&#39;+3.140000; -3.140000&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{: f}</span><span class="s1">; </span><span class="si">{: f}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.14</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.14</span><span class="p">)</span>  <span class="c1"># show a space for positive numbers</span>
<span class="go">&#39; 3.140000; -3.140000&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:-f}</span><span class="s1">; </span><span class="si">{:-f}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.14</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.14</span><span class="p">)</span>  <span class="c1"># show only the minus -- same as &#39;{:f}; {:f}&#39;</span>
<span class="go">&#39;3.140000; -3.140000&#39;</span>
</pre></div>
</div>
<p>Replacing <code class="docutils literal notranslate"><span class="pre">%x</span></code> and <code class="docutils literal notranslate"><span class="pre">%o</span></code> and converting the value to different bases:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># format also supports binary numbers</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;int: </span><span class="si">{0:d}</span><span class="s2">;  hex: </span><span class="si">{0:x}</span><span class="s2">;  oct: </span><span class="si">{0:o}</span><span class="s2">;  bin: </span><span class="si">{0:b}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;int: 42;  hex: 2a;  oct: 52;  bin: 101010&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># with 0x, 0o, or 0b as prefix:</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;int: </span><span class="si">{0:d}</span><span class="s2">;  hex: </span><span class="si">{0:#x}</span><span class="s2">;  oct: </span><span class="si">{0:#o}</span><span class="s2">;  bin: </span><span class="si">{0:#b}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010&#39;</span>
</pre></div>
</div>
<p>Using the comma as a thousands separator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:,}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">1234567890</span><span class="p">)</span>
<span class="go">&#39;1,234,567,890&#39;</span>
</pre></div>
</div>
<p>Expressing a percentage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">points</span> <span class="o">=</span> <span class="mf">19.5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">total</span> <span class="o">=</span> <span class="mi">22</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Correct answers: </span><span class="si">{:.2%}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">points</span><span class="o">/</span><span class="n">total</span><span class="p">)</span>
<span class="go">&#39;Correct answers: 88.64%&#39;</span>
</pre></div>
</div>
<p>Using type-specific formatting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2010</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">15</span><span class="p">,</span> <span class="mi">58</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;{:%Y-%m-</span><span class="si">%d</span><span class="s1"> %H:%M:%S}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">&#39;2010-07-04 12:15:58&#39;</span>
</pre></div>
</div>
<p>Nesting arguments and more complex examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">align</span><span class="p">,</span> <span class="n">text</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="s1">&#39;&lt;^&gt;&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;left&#39;</span><span class="p">,</span> <span class="s1">&#39;center&#39;</span><span class="p">,</span> <span class="s1">&#39;right&#39;</span><span class="p">]):</span>
<span class="gp">... </span>    <span class="s1">&#39;{0:</span><span class="si">{fill}{align}</span><span class="s1">16}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">fill</span><span class="o">=</span><span class="n">align</span><span class="p">,</span> <span class="n">align</span><span class="o">=</span><span class="n">align</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">&#39;left&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&#39;</span>
<span class="go">&#39;^^^^^center^^^^^&#39;</span>
<span class="go">&#39;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;right&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">octets</span> <span class="o">=</span> <span class="p">[</span><span class="mi">192</span><span class="p">,</span> <span class="mi">168</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:02X}{:02X}{:02X}{:02X}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">*</span><span class="n">octets</span><span class="p">)</span>
<span class="go">&#39;C0A80001&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="mi">16</span><span class="p">)</span>
<span class="go">3232235521</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span><span class="mi">12</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">base</span> <span class="ow">in</span> <span class="s1">&#39;dXob&#39;</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s1">&#39;{0:</span><span class="si">{width}{base}</span><span class="s1">}&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">num</span><span class="p">,</span> <span class="n">base</span><span class="o">=</span><span class="n">base</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="n">width</span><span class="p">),</span>
<span class="gp">... </span>    <span class="nb">print</span>
<span class="gp">...</span>
<span class="go">    5     5     5   101</span>
<span class="go">    6     6     6   110</span>
<span class="go">    7     7     7   111</span>
<span class="go">    8     8    10  1000</span>
<span class="go">    9     9    11  1001</span>
<span class="go">   10     A    12  1010</span>
<span class="go">   11     B    13  1011</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="template-strings">
<h2>7.1.4. Template strings<a class="headerlink" href="#template-strings" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>Templates provide simpler string substitutions as described in <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0292"><strong>PEP 292</strong></a>.
Instead of the normal <code class="docutils literal notranslate"><span class="pre">%</span></code>-based substitutions, Templates support <code class="docutils literal notranslate"><span class="pre">$</span></code>-based substitutions, using the following rules:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">$$</span></code> is an escape; it is replaced with a single <code class="docutils literal notranslate"><span class="pre">$</span></code>.</li>
<li><code class="docutils literal notranslate"><span class="pre">$identifier</span></code> names a substitution placeholder matching a mapping key of
<code class="docutils literal notranslate"><span class="pre">&quot;identifier&quot;</span></code>.  By default, <code class="docutils literal notranslate"><span class="pre">&quot;identifier&quot;</span></code> must spell a Python
identifier.  The first non-identifier character after the <code class="docutils literal notranslate"><span class="pre">$</span></code> character
terminates this placeholder specification.</li>
<li><code class="docutils literal notranslate"><span class="pre">${identifier}</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">$identifier</span></code>.  It is required when valid
identifier characters follow the placeholder but are not part of the
placeholder, such as <code class="docutils literal notranslate"><span class="pre">&quot;${noun}ification&quot;</span></code>.</li>
</ul>
<p>Any other appearance of <code class="docutils literal notranslate"><span class="pre">$</span></code> in the string will result in a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>
being raised.</p>
<p>The <a class="reference internal" href="#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module provides a <a class="reference internal" href="#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class that implements
these rules.  The methods of <a class="reference internal" href="#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> are:</p>
<dl class="class">
<dt id="string.Template">
<em class="property">class </em><code class="descclassname">string.</code><code class="descname">Template</code><span class="sig-paren">(</span><em>template</em><span class="sig-paren">)</span><a class="headerlink" href="#string.Template" title="Permalink to this definition">¶</a></dt>
<dd><p>The constructor takes a single argument which is the template string.</p>
<dl class="method">
<dt id="string.Template.substitute">
<code class="descname">substitute</code><span class="sig-paren">(</span><em>mapping</em><span class="optional">[</span>, <em>**kws</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.Template.substitute" title="Permalink to this definition">¶</a></dt>
<dd><p>Performs the template substitution, returning a new string.  <em>mapping</em> is
any dictionary-like object with keys that match the placeholders in the
template.  Alternatively, you can provide keyword arguments, where the
keywords are the placeholders.  When both <em>mapping</em> and <em>kws</em> are given
and there are duplicates, the placeholders from <em>kws</em> take precedence.</p>
</dd></dl>

<dl class="method">
<dt id="string.Template.safe_substitute">
<code class="descname">safe_substitute</code><span class="sig-paren">(</span><em>mapping</em><span class="optional">[</span>, <em>**kws</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.Template.safe_substitute" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a>, except that if placeholders are missing from
<em>mapping</em> and <em>kws</em>, instead of raising a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> exception, the
original placeholder will appear in the resulting string intact.  Also,
unlike with <a class="reference internal" href="#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a>, any other appearances of the <code class="docutils literal notranslate"><span class="pre">$</span></code> will
simply return <code class="docutils literal notranslate"><span class="pre">$</span></code> instead of raising <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
<p>While other exceptions may still occur, this method is called “safe”
because it always tries to return a usable string instead of
raising an exception.  In another sense, <a class="reference internal" href="#string.Template.safe_substitute" title="string.Template.safe_substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code></a> may be
anything other than safe, since it will silently ignore malformed
templates containing dangling delimiters, unmatched braces, or
placeholders that are not valid Python identifiers.</p>
</dd></dl>

<p><a class="reference internal" href="#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> instances also provide one public data attribute:</p>
<dl class="attribute">
<dt id="string.Template.template">
<code class="descname">template</code><a class="headerlink" href="#string.Template.template" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the object passed to the constructor’s <em>template</em> argument.  In
general, you shouldn’t change it, but read-only access is not enforced.</p>
</dd></dl>

</dd></dl>

<p>Here is an example of how to use a Template:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">string</span> <span class="k">import</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$who likes $what&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">who</span><span class="o">=</span><span class="s1">&#39;tim&#39;</span><span class="p">,</span> <span class="n">what</span><span class="o">=</span><span class="s1">&#39;kung pao&#39;</span><span class="p">)</span>
<span class="go">&#39;tim likes kung pao&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">who</span><span class="o">=</span><span class="s1">&#39;tim&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Template</span><span class="p">(</span><span class="s1">&#39;Give $who $100&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">Invalid placeholder in string: line 1, col 11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$who likes $what&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">KeyError</span>: <span class="n">&#39;what&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$who likes $what&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">&#39;tim likes $what&#39;</span>
</pre></div>
</div>
<p>Advanced usage: you can derive subclasses of <a class="reference internal" href="#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> to customize the
placeholder syntax, delimiter character, or the entire regular expression used
to parse template strings.  To do this, you can override these class attributes:</p>
<ul class="simple">
<li><em>delimiter</em> – This is the literal string describing a placeholder introducing
delimiter.  The default value is <code class="docutils literal notranslate"><span class="pre">$</span></code>.  Note that this should <em>not</em> be a
regular expression, as the implementation will call <a class="reference internal" href="re.html#re.escape" title="re.escape"><code class="xref py py-meth docutils literal notranslate"><span class="pre">re.escape()</span></code></a> on this
string as needed.</li>
<li><em>idpattern</em> – This is the regular expression describing the pattern for
non-braced placeholders (the braces will be added automatically as
appropriate).  The default value is the regular expression
<code class="docutils literal notranslate"><span class="pre">[_a-z][_a-z0-9]*</span></code>.</li>
</ul>
<p>Alternatively, you can provide the entire regular expression pattern by
overriding the class attribute <em>pattern</em>.  If you do this, the value must be a
regular expression object with four named capturing groups.  The capturing
groups correspond to the rules given above, along with the invalid placeholder
rule:</p>
<ul class="simple">
<li><em>escaped</em> – This group matches the escape sequence, e.g. <code class="docutils literal notranslate"><span class="pre">$$</span></code>, in the
default pattern.</li>
<li><em>named</em> – This group matches the unbraced placeholder name; it should not
include the delimiter in capturing group.</li>
<li><em>braced</em> – This group matches the brace enclosed placeholder name; it should
not include either the delimiter or braces in the capturing group.</li>
<li><em>invalid</em> – This group matches any other delimiter pattern (usually a single
delimiter), and it should appear last in the regular expression.</li>
</ul>
</div>
<div class="section" id="string-functions">
<h2>7.1.5. String functions<a class="headerlink" href="#string-functions" title="Permalink to this headline">¶</a></h2>
<p>The following functions are available to operate on string and Unicode objects.
They are not available as string methods.</p>
<dl class="function">
<dt id="string.capwords">
<code class="descclassname">string.</code><code class="descname">capwords</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>sep</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.capwords" title="Permalink to this definition">¶</a></dt>
<dd><p>Split the argument into words using <a class="reference internal" href="stdtypes.html#str.split" title="str.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.split()</span></code></a>, capitalize each word
using <a class="reference internal" href="stdtypes.html#str.capitalize" title="str.capitalize"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.capitalize()</span></code></a>, and join the capitalized words using
<a class="reference internal" href="stdtypes.html#str.join" title="str.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.join()</span></code></a>.  If the optional second argument <em>sep</em> is absent
or <code class="docutils literal notranslate"><span class="pre">None</span></code>, runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise <em>sep</em> is used to
split and join the words.</p>
</dd></dl>

<dl class="function">
<dt id="string.maketrans">
<code class="descclassname">string.</code><code class="descname">maketrans</code><span class="sig-paren">(</span><em>from</em>, <em>to</em><span class="sig-paren">)</span><a class="headerlink" href="#string.maketrans" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a translation table suitable for passing to <a class="reference internal" href="#string.translate" title="string.translate"><code class="xref py py-func docutils literal notranslate"><span class="pre">translate()</span></code></a>, that will
map each character in <em>from</em> into the character at the same position in <em>to</em>;
<em>from</em> and <em>to</em> must have the same length.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Don’t use strings derived from <a class="reference internal" href="#string.lowercase" title="string.lowercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">lowercase</span></code></a> and <a class="reference internal" href="#string.uppercase" title="string.uppercase"><code class="xref py py-const docutils literal notranslate"><span class="pre">uppercase</span></code></a> as
arguments; in some locales, these don’t have the same length.  For case
conversions, always use <a class="reference internal" href="stdtypes.html#str.lower" title="str.lower"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.lower()</span></code></a> and <a class="reference internal" href="stdtypes.html#str.upper" title="str.upper"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.upper()</span></code></a>.</p>
</div>
</dd></dl>

</div>
<div class="section" id="deprecated-string-functions">
<h2>7.1.6. Deprecated string functions<a class="headerlink" href="#deprecated-string-functions" title="Permalink to this headline">¶</a></h2>
<p>The following list of functions are also defined as methods of string and
Unicode objects; see section <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a> for more information on
those.  You should consider these functions as deprecated, although they will
not be removed until Python 3.  The functions defined in this module are:</p>
<dl class="function">
<dt id="string.atof">
<code class="descclassname">string.</code><code class="descname">atof</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#string.atof" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use the <a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> built-in function.</p>
</div>
<p id="index-5">Convert a string to a floating point number.  The string must have the standard
syntax for a floating point literal in Python, optionally preceded by a sign
(<code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code>).  Note that this behaves identical to the built-in function
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> when passed a string.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last" id="index-6">When passing in a string, values for NaN and Infinity may be returned, depending
on the underlying C library.  The specific set of strings accepted which cause
these values to be returned depends entirely on the C library and is known to
vary.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="string.atoi">
<code class="descclassname">string.</code><code class="descname">atoi</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>base</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.atoi" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use the <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> built-in function.</p>
</div>
<p id="index-7">Convert string <em>s</em> to an integer in the given <em>base</em>.  The string must consist
of one or more digits, optionally preceded by a sign (<code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code>).  The
<em>base</em> defaults to 10.  If it is 0, a default base is chosen depending on the
leading characters of the string (after stripping the sign): <code class="docutils literal notranslate"><span class="pre">0x</span></code> or <code class="docutils literal notranslate"><span class="pre">0X</span></code>
means 16, <code class="docutils literal notranslate"><span class="pre">0</span></code> means 8, anything else means 10.  If <em>base</em> is 16, a leading
<code class="docutils literal notranslate"><span class="pre">0x</span></code> or <code class="docutils literal notranslate"><span class="pre">0X</span></code> is always accepted, though not required.  This behaves
identically to the built-in function <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> when passed a string.  (Also
note: for a more flexible interpretation of numeric literals, use the built-in
function <a class="reference internal" href="functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.)</p>
</dd></dl>

<dl class="function">
<dt id="string.atol">
<code class="descclassname">string.</code><code class="descname">atol</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>base</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.atol" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use the <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> built-in function.</p>
</div>
<p id="index-8">Convert string <em>s</em> to a long integer in the given <em>base</em>. The string must
consist of one or more digits, optionally preceded by a sign (<code class="docutils literal notranslate"><span class="pre">+</span></code> or <code class="docutils literal notranslate"><span class="pre">-</span></code>).
The <em>base</em> argument has the same meaning as for <a class="reference internal" href="#string.atoi" title="string.atoi"><code class="xref py py-func docutils literal notranslate"><span class="pre">atoi()</span></code></a>.  A trailing <code class="docutils literal notranslate"><span class="pre">l</span></code>
or <code class="docutils literal notranslate"><span class="pre">L</span></code> is not allowed, except if the base is 0.  Note that when invoked
without <em>base</em> or with <em>base</em> set to 10, this behaves identical to the built-in
function <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> when passed a string.</p>
</dd></dl>

<dl class="function">
<dt id="string.capitalize">
<code class="descclassname">string.</code><code class="descname">capitalize</code><span class="sig-paren">(</span><em>word</em><span class="sig-paren">)</span><a class="headerlink" href="#string.capitalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of <em>word</em> with only its first character capitalized.</p>
</dd></dl>

<dl class="function">
<dt id="string.expandtabs">
<code class="descclassname">string.</code><code class="descname">expandtabs</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>tabsize</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.expandtabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Expand tabs in a string replacing them by one or more spaces, depending on the
current column and the given tab size.  The column number is reset to zero after
each newline occurring in the string. This doesn’t understand other non-printing
characters or escape sequences.  The tab size defaults to 8.</p>
</dd></dl>

<dl class="function">
<dt id="string.find">
<code class="descclassname">string.</code><code class="descname">find</code><span class="sig-paren">(</span><em>s</em>, <em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the lowest index in <em>s</em> where the substring <em>sub</em> is found such that
<em>sub</em> is wholly contained in <code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code>.  Return <code class="docutils literal notranslate"><span class="pre">-1</span></code> on failure.
Defaults for <em>start</em> and <em>end</em> and interpretation of negative values is the same
as for slices.</p>
</dd></dl>

<dl class="function">
<dt id="string.rfind">
<code class="descclassname">string.</code><code class="descname">rfind</code><span class="sig-paren">(</span><em>s</em>, <em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.rfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#string.find" title="string.find"><code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code></a> but find the highest index.</p>
</dd></dl>

<dl class="function">
<dt id="string.index">
<code class="descclassname">string.</code><code class="descname">index</code><span class="sig-paren">(</span><em>s</em>, <em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#string.find" title="string.find"><code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code></a> but raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> when the substring is not found.</p>
</dd></dl>

<dl class="function">
<dt id="string.rindex">
<code class="descclassname">string.</code><code class="descname">rindex</code><span class="sig-paren">(</span><em>s</em>, <em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.rindex" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#string.rfind" title="string.rfind"><code class="xref py py-func docutils literal notranslate"><span class="pre">rfind()</span></code></a> but raise <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> when the substring is not found.</p>
</dd></dl>

<dl class="function">
<dt id="string.count">
<code class="descclassname">string.</code><code class="descname">count</code><span class="sig-paren">(</span><em>s</em>, <em>sub</em><span class="optional">[</span>, <em>start</em><span class="optional">[</span>, <em>end</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.count" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of (non-overlapping) occurrences of substring <em>sub</em> in string
<code class="docutils literal notranslate"><span class="pre">s[start:end]</span></code>. Defaults for <em>start</em> and <em>end</em> and interpretation of negative
values are the same as for slices.</p>
</dd></dl>

<dl class="function">
<dt id="string.lower">
<code class="descclassname">string.</code><code class="descname">lower</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#string.lower" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of <em>s</em>, but with upper case letters converted to lower case.</p>
</dd></dl>

<dl class="function">
<dt id="string.split">
<code class="descclassname">string.</code><code class="descname">split</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.split" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words of the string <em>s</em>.  If the optional second argument
<em>sep</em> is absent or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the words are separated by arbitrary strings of
whitespace characters (space, tab, newline, return, formfeed).  If the second
argument <em>sep</em> is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it specifies a string to be used as
the  word separator.  The returned list will then have one more item than the
number of non-overlapping occurrences of the separator in the string.
If <em>maxsplit</em> is given, at most <em>maxsplit</em> number of splits occur, and the
remainder of the string is returned as the final element of the list (thus,
the list will have at most <code class="docutils literal notranslate"><span class="pre">maxsplit+1</span></code> elements).  If <em>maxsplit</em> is not
specified or <code class="docutils literal notranslate"><span class="pre">-1</span></code>, then there is no limit on the number of splits (all
possible splits are made).</p>
<p>The behavior of split on an empty string depends on the value of <em>sep</em>. If <em>sep</em>
is not specified, or specified as <code class="docutils literal notranslate"><span class="pre">None</span></code>, the result will be an empty list.
If <em>sep</em> is specified as any string, the result will be a list containing one
element which is an empty string.</p>
</dd></dl>

<dl class="function">
<dt id="string.rsplit">
<code class="descclassname">string.</code><code class="descname">rsplit</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.rsplit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the words of the string <em>s</em>, scanning <em>s</em> from the end.  To all
intents and purposes, the resulting list of words is the same as returned by
<a class="reference internal" href="#string.split" title="string.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>, except when the optional third argument <em>maxsplit</em> is explicitly
specified and nonzero.  If <em>maxsplit</em> is given, at most <em>maxsplit</em> number of
splits – the <em>rightmost</em> ones – occur, and the remainder of the string is
returned as the first element of the list (thus, the list will have at most
<code class="docutils literal notranslate"><span class="pre">maxsplit+1</span></code> elements).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="string.splitfields">
<code class="descclassname">string.</code><code class="descname">splitfields</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>sep</em><span class="optional">[</span>, <em>maxsplit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.splitfields" title="Permalink to this definition">¶</a></dt>
<dd><p>This function behaves identically to <a class="reference internal" href="#string.split" title="string.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>.  (In the past, <a class="reference internal" href="#string.split" title="string.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>
was only used with one argument, while <a class="reference internal" href="#string.splitfields" title="string.splitfields"><code class="xref py py-func docutils literal notranslate"><span class="pre">splitfields()</span></code></a> was only used with
two arguments.)</p>
</dd></dl>

<dl class="function">
<dt id="string.join">
<code class="descclassname">string.</code><code class="descname">join</code><span class="sig-paren">(</span><em>words</em><span class="optional">[</span>, <em>sep</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Concatenate a list or tuple of words with intervening occurrences of  <em>sep</em>.
The default value for <em>sep</em> is a single space character.  It is always true that
<code class="docutils literal notranslate"><span class="pre">string.join(string.split(s,</span> <span class="pre">sep),</span> <span class="pre">sep)</span></code> equals <em>s</em>.</p>
</dd></dl>

<dl class="function">
<dt id="string.joinfields">
<code class="descclassname">string.</code><code class="descname">joinfields</code><span class="sig-paren">(</span><em>words</em><span class="optional">[</span>, <em>sep</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.joinfields" title="Permalink to this definition">¶</a></dt>
<dd><p>This function behaves identically to <a class="reference internal" href="#string.join" title="string.join"><code class="xref py py-func docutils literal notranslate"><span class="pre">join()</span></code></a>.  (In the past,  <a class="reference internal" href="#string.join" title="string.join"><code class="xref py py-func docutils literal notranslate"><span class="pre">join()</span></code></a>
was only used with one argument, while <a class="reference internal" href="#string.joinfields" title="string.joinfields"><code class="xref py py-func docutils literal notranslate"><span class="pre">joinfields()</span></code></a> was only used with two
arguments.) Note that there is no <a class="reference internal" href="#string.joinfields" title="string.joinfields"><code class="xref py py-meth docutils literal notranslate"><span class="pre">joinfields()</span></code></a> method on string objects;
use the <a class="reference internal" href="#string.join" title="string.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method instead.</p>
</dd></dl>

<dl class="function">
<dt id="string.lstrip">
<code class="descclassname">string.</code><code class="descname">lstrip</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.lstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with leading characters removed.  If <em>chars</em> is
omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, whitespace characters are removed.  If given and not
<code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>chars</em> must be a string; the characters in the string will be
stripped from the beginning of the string this method is called on.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.3: </span>The <em>chars</em> parameter was added.  The <em>chars</em> parameter cannot be passed in
earlier 2.2 versions.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="string.rstrip">
<code class="descclassname">string.</code><code class="descname">rstrip</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.rstrip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with trailing characters removed.  If <em>chars</em> is
omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, whitespace characters are removed.  If given and not
<code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>chars</em> must be a string; the characters in the string will be
stripped from the end of the string this method is called on.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.3: </span>The <em>chars</em> parameter was added.  The <em>chars</em> parameter cannot be passed in
earlier 2.2 versions.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="string.strip">
<code class="descclassname">string.</code><code class="descname">strip</code><span class="sig-paren">(</span><em>s</em><span class="optional">[</span>, <em>chars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.strip" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of the string with leading and trailing characters removed.  If
<em>chars</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, whitespace characters are removed.  If given and
not <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>chars</em> must be a string; the characters in the string will be
stripped from the both ends of the string this method is called on.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2.3: </span>The <em>chars</em> parameter was added.  The <em>chars</em> parameter cannot be passed in
earlier 2.2 versions.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="string.swapcase">
<code class="descclassname">string.</code><code class="descname">swapcase</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#string.swapcase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of <em>s</em>, but with lower case letters converted to upper case and
vice versa.</p>
</dd></dl>

<dl class="function">
<dt id="string.translate">
<code class="descclassname">string.</code><code class="descname">translate</code><span class="sig-paren">(</span><em>s</em>, <em>table</em><span class="optional">[</span>, <em>deletechars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.translate" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all characters from <em>s</em> that are in <em>deletechars</em> (if  present), and then
translate the characters using <em>table</em>, which  must be a 256-character string
giving the translation for each character value, indexed by its ordinal.  If
<em>table</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, then only the character deletion step is performed.</p>
</dd></dl>

<dl class="function">
<dt id="string.upper">
<code class="descclassname">string.</code><code class="descname">upper</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#string.upper" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of <em>s</em>, but with lower case letters converted to upper case.</p>
</dd></dl>

<dl class="function">
<dt id="string.ljust">
<code class="descclassname">string.</code><code class="descname">ljust</code><span class="sig-paren">(</span><em>s</em>, <em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.ljust" title="Permalink to this definition">¶</a></dt>
<dt id="string.rjust">
<code class="descclassname">string.</code><code class="descname">rjust</code><span class="sig-paren">(</span><em>s</em>, <em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.rjust" title="Permalink to this definition">¶</a></dt>
<dt id="string.center">
<code class="descclassname">string.</code><code class="descname">center</code><span class="sig-paren">(</span><em>s</em>, <em>width</em><span class="optional">[</span>, <em>fillchar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.center" title="Permalink to this definition">¶</a></dt>
<dd><p>These functions respectively left-justify, right-justify and center a string in
a field of given width.  They return a string that is at least <em>width</em>
characters wide, created by padding the string <em>s</em> with the character <em>fillchar</em>
(default is a space) until the given width on the right, left or both sides.
The string is never truncated.</p>
</dd></dl>

<dl class="function">
<dt id="string.zfill">
<code class="descclassname">string.</code><code class="descname">zfill</code><span class="sig-paren">(</span><em>s</em>, <em>width</em><span class="sig-paren">)</span><a class="headerlink" href="#string.zfill" title="Permalink to this definition">¶</a></dt>
<dd><p>Pad a numeric string <em>s</em> on the left with zero digits until the
given <em>width</em> is reached.  Strings starting with a sign are handled
correctly.</p>
</dd></dl>

<dl class="function">
<dt id="string.replace">
<code class="descclassname">string.</code><code class="descname">replace</code><span class="sig-paren">(</span><em>s</em>, <em>old</em>, <em>new</em><span class="optional">[</span>, <em>maxreplace</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#string.replace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a copy of string <em>s</em> with all occurrences of substring <em>old</em> replaced
by <em>new</em>.  If the optional argument <em>maxreplace</em> is given, the first
<em>maxreplace</em> occurrences are replaced.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a><ul>
<li><a class="reference internal" href="#string-constants">7.1.1. String constants</a></li>
<li><a class="reference internal" href="#custom-string-formatting">7.1.2. Custom String Formatting</a></li>
<li><a class="reference internal" href="#format-string-syntax">7.1.3. Format String Syntax</a><ul>
<li><a class="reference internal" href="#format-specification-mini-language">7.1.3.1. Format Specification Mini-Language</a></li>
<li><a class="reference internal" href="#format-examples">7.1.3.2. Format examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#template-strings">7.1.4. Template strings</a></li>
<li><a class="reference internal" href="#string-functions">7.1.5. String functions</a></li>
<li><a class="reference internal" href="#deprecated-string-functions">7.1.6. Deprecated string functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="strings.html"
                        title="previous chapter">7. String Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="re.html"
                        title="next chapter">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/string.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="re.html" title="7.2. re — Regular expression operations"
             >next</a> |</li>
        <li class="right" >
          <a href="strings.html" title="7. String Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��	q]N]Nhtml/library/stringio.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.5. StringIO — Read and write strings as files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.7. textwrap — Text wrapping and filling" href="textwrap.html" />
    <link rel="prev" title="7.4. difflib — Helpers for computing deltas" href="difflib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/stringio.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="textwrap.html" title="7.7. textwrap — Text wrapping and filling"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="7.4. difflib — Helpers for computing deltas"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-StringIO">
<span id="stringio-read-and-write-strings-as-files"></span><h1>7.5. <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> — Read and write strings as files<a class="headerlink" href="#module-StringIO" title="Permalink to this headline">¶</a></h1>
<p>This module implements a file-like class, <a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a>, that reads and
writes a string buffer (also known as <em>memory files</em>).  See the description of
file objects for operations (section <a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>). (For
standard strings, see <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.)</p>
<dl class="class">
<dt id="StringIO.StringIO">
<em class="property">class </em><code class="descclassname">StringIO.</code><code class="descname">StringIO</code><span class="sig-paren">(</span><span class="optional">[</span><em>buffer</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#StringIO.StringIO" title="Permalink to this definition">¶</a></dt>
<dd><p>When a <a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object is created, it can be initialized to an existing
string by passing the string to the constructor. If no string is given, the
<a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> will start empty. In both cases, the initial file position
starts at zero.</p>
<p>The <a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object can accept either Unicode or 8-bit strings, but
mixing the two may take some care.  If both are used, 8-bit strings that cannot
be interpreted as 7-bit ASCII (that use the 8th bit) will cause a
<a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> to be raised when <a class="reference internal" href="#StringIO.StringIO.getvalue" title="StringIO.StringIO.getvalue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getvalue()</span></code></a> is called.</p>
</dd></dl>

<p>The following methods of <a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> objects require special mention:</p>
<dl class="method">
<dt id="StringIO.StringIO.getvalue">
<code class="descclassname">StringIO.</code><code class="descname">getvalue</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#StringIO.StringIO.getvalue" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieve the entire contents of the “file” at any time before the
<a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object’s <a class="reference internal" href="#StringIO.StringIO.close" title="StringIO.StringIO.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method is called.  See the note above
for information about mixing Unicode and 8-bit strings; such mixing can cause
this method to raise <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="StringIO.StringIO.close">
<code class="descclassname">StringIO.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#StringIO.StringIO.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Free the memory buffer.  Attempting to do further operations with a closed
<a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object will raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</dd></dl>

<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">StringIO</span>

<span class="n">output</span> <span class="o">=</span> <span class="n">StringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
<span class="n">output</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;First line.</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">output</span><span class="p">,</span> <span class="s1">&#39;Second line.&#39;</span>

<span class="c1"># Retrieve file contents -- this will be</span>
<span class="c1"># &#39;First line.\nSecond line.\n&#39;</span>
<span class="n">contents</span> <span class="o">=</span> <span class="n">output</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>

<span class="c1"># Close object and discard memory buffer --</span>
<span class="c1"># .getvalue() will now raise an exception.</span>
<span class="n">output</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="module-cStringIO">
<span id="cstringio-faster-version-of-stringio"></span><h1>7.6. <a class="reference internal" href="#module-cStringIO" title="cStringIO: Faster version of StringIO, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cStringIO</span></code></a> — Faster version of <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a><a class="headerlink" href="#module-cStringIO" title="Permalink to this headline">¶</a></h1>
<p>The module <a class="reference internal" href="#module-cStringIO" title="cStringIO: Faster version of StringIO, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cStringIO</span></code></a> provides an interface similar to that of the
<a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module.  Heavy use of <a class="reference internal" href="#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO.StringIO</span></code></a> objects can be
made more efficient by using the function <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-func docutils literal notranslate"><span class="pre">StringIO()</span></code></a> from this module
instead.</p>
<dl class="function">
<dt id="cStringIO.StringIO">
<code class="descclassname">cStringIO.</code><code class="descname">StringIO</code><span class="sig-paren">(</span><span class="optional">[</span><em>s</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#cStringIO.StringIO" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a StringIO-like stream for reading or writing.</p>
<p>Since this is a factory function which returns objects of built-in types,
there’s no way to build your own version using subclassing.  It’s not
possible to set attributes on it.  Use the original <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module in
those cases.</p>
<p>Unlike the <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module, this module is not able to accept Unicode
strings that cannot be encoded as plain ASCII strings.</p>
<p>Another difference from the <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module is that calling
<a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-func docutils literal notranslate"><span class="pre">StringIO()</span></code></a> with a string parameter creates a read-only object. Unlike an
object created without a string parameter, it does not have write methods.
These objects are not generally visible.  They turn up in tracebacks as
<code class="xref py py-class docutils literal notranslate"><span class="pre">StringI</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">StringO</span></code>.</p>
</dd></dl>

<p>The following data objects are provided as well:</p>
<dl class="data">
<dt id="cStringIO.InputType">
<code class="descclassname">cStringIO.</code><code class="descname">InputType</code><a class="headerlink" href="#cStringIO.InputType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object of the objects created by calling <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-func docutils literal notranslate"><span class="pre">StringIO()</span></code></a> with a string
parameter.</p>
</dd></dl>

<dl class="data">
<dt id="cStringIO.OutputType">
<code class="descclassname">cStringIO.</code><code class="descname">OutputType</code><a class="headerlink" href="#cStringIO.OutputType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object of the objects returned by calling <a class="reference internal" href="#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-func docutils literal notranslate"><span class="pre">StringIO()</span></code></a> with no
parameters.</p>
</dd></dl>

<p>There is a C API to the module as well; refer to the module source for  more
information.</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">cStringIO</span>

<span class="n">output</span> <span class="o">=</span> <span class="n">cStringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">()</span>
<span class="n">output</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;First line.</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">output</span><span class="p">,</span> <span class="s1">&#39;Second line.&#39;</span>

<span class="c1"># Retrieve file contents -- this will be</span>
<span class="c1"># &#39;First line.\nSecond line.\n&#39;</span>
<span class="n">contents</span> <span class="o">=</span> <span class="n">output</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>

<span class="c1"># Close object and discard memory buffer --</span>
<span class="c1"># .getvalue() will now raise an exception.</span>
<span class="n">output</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></li>
<li><a class="reference internal" href="#module-cStringIO">7.6. <code class="docutils literal notranslate"><span class="pre">cStringIO</span></code> — Faster version of <code class="docutils literal notranslate"><span class="pre">StringIO</span></code></a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="difflib.html"
                        title="previous chapter">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="textwrap.html"
                        title="next chapter">7.7. <code class="docutils literal notranslate"><span class="pre">textwrap</span></code> — Text wrapping and filling</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/stringio.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="textwrap.html" title="7.7. textwrap — Text wrapping and filling"
             >next</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="7.4. difflib — Helpers for computing deltas"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\уAHAEAEhtml/library/stringprep.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.10. stringprep — Internet String Preparation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.11. fpformat — Floating point conversions" href="fpformat.html" />
    <link rel="prev" title="7.9. unicodedata — Unicode Database" href="unicodedata.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/stringprep.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fpformat.html" title="7.11. fpformat — Floating point conversions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unicodedata.html" title="7.9. unicodedata — Unicode Database"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-stringprep">
<span id="stringprep-internet-string-preparation"></span><h1>7.10. <a class="reference internal" href="#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a> — Internet String Preparation<a class="headerlink" href="#module-stringprep" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>When identifying things (such as host names) in the internet, it is often
necessary to compare such identifications for “equality”. Exactly how this
comparison is executed may depend on the application domain, e.g. whether it
should be case-insensitive or not. It may be also necessary to restrict the
possible identifications, to allow only identifications consisting of
“printable” characters.</p>
<p><span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3454.html"><strong>RFC 3454</strong></a> defines a procedure for “preparing” Unicode strings in internet
protocols. Before passing strings onto the wire, they are processed with the
preparation procedure, after which they have a certain normalized form. The RFC
defines a set of tables, which can be combined into profiles. Each profile must
define which tables it uses, and what other optional parts of the <code class="docutils literal notranslate"><span class="pre">stringprep</span></code>
procedure are part of the profile. One example of a <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> profile is
<code class="docutils literal notranslate"><span class="pre">nameprep</span></code>, which is used for internationalized domain names.</p>
<p>The module <a class="reference internal" href="#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a> only exposes the tables from RFC 3454. As these
tables would be very large to represent them as dictionaries or lists, the
module uses the Unicode character database internally. The module source code
itself was generated using the <code class="docutils literal notranslate"><span class="pre">mkstringprep.py</span></code> utility.</p>
<p>As a result, these tables are exposed as functions, not as data structures.
There are two kinds of tables in the RFC: sets and mappings. For a set,
<a class="reference internal" href="#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a> provides the “characteristic function”, i.e. a function that
returns true if the parameter is part of the set. For mappings, it provides the
mapping function: given the key, it returns the associated value. Below is a
list of all functions available in the module.</p>
<dl class="function">
<dt id="stringprep.in_table_a1">
<code class="descclassname">stringprep.</code><code class="descname">in_table_a1</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_a1" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableA.1 (Unassigned code points in Unicode 3.2).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_b1">
<code class="descclassname">stringprep.</code><code class="descname">in_table_b1</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_b1" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableB.1 (Commonly mapped to nothing).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.map_table_b2">
<code class="descclassname">stringprep.</code><code class="descname">map_table_b2</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.map_table_b2" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mapped value for <em>code</em> according to tableB.2 (Mapping for
case-folding used with NFKC).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.map_table_b3">
<code class="descclassname">stringprep.</code><code class="descname">map_table_b3</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.map_table_b3" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the mapped value for <em>code</em> according to tableB.3 (Mapping for
case-folding used with no normalization).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c11">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c11</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c11" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.1.1  (ASCII space characters).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c12">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c12</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c12" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.1.2  (Non-ASCII space characters).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c11_c12">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c11_c12</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c11_c12" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.1  (Space characters, union of C.1.1 and
C.1.2).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c21">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c21</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c21" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.2.1  (ASCII control characters).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c22">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c22</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c22" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.2.2  (Non-ASCII control characters).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c21_c22">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c21_c22</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c21_c22" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.2  (Control characters, union of C.2.1 and
C.2.2).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c3">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c3</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c3" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.3  (Private use).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c4">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c4</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c4" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.4  (Non-character code points).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c5">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c5</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c5" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.5  (Surrogate codes).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c6">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c6</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c6" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.6  (Inappropriate for plain text).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c7">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c7</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c7" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.7  (Inappropriate for canonical
representation).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c8">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c8</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c8" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.8  (Change display properties or are
deprecated).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_c9">
<code class="descclassname">stringprep.</code><code class="descname">in_table_c9</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_c9" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableC.9  (Tagging characters).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_d1">
<code class="descclassname">stringprep.</code><code class="descname">in_table_d1</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_d1" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableD.1  (Characters with bidirectional property
“R” or “AL”).</p>
</dd></dl>

<dl class="function">
<dt id="stringprep.in_table_d2">
<code class="descclassname">stringprep.</code><code class="descname">in_table_d2</code><span class="sig-paren">(</span><em>code</em><span class="sig-paren">)</span><a class="headerlink" href="#stringprep.in_table_d2" title="Permalink to this definition">¶</a></dt>
<dd><p>Determine whether <em>code</em> is in tableD.2  (Characters with bidirectional property
“L”).</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="unicodedata.html"
                        title="previous chapter">7.9. <code class="docutils literal notranslate"><span class="pre">unicodedata</span></code> — Unicode Database</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fpformat.html"
                        title="next chapter">7.11. <code class="docutils literal notranslate"><span class="pre">fpformat</span></code> — Floating point conversions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/stringprep.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fpformat.html" title="7.11. fpformat — Floating point conversions"
             >next</a> |</li>
        <li class="right" >
          <a href="unicodedata.html" title="7.9. unicodedata — Unicode Database"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\D��!>!>html/library/strings.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7. String Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.1. string — Common string operations" href="string.html" />
    <link rel="prev" title="6. Built-in Exceptions" href="exceptions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/strings.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="string.html" title="7.1. string — Common string operations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="6. Built-in Exceptions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="string-services">
<span id="stringservices"></span><h1>7. String Services<a class="headerlink" href="#string-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide a wide range of string
manipulation operations.</p>
<p>In addition, Python’s built-in string classes support the sequence type
methods described in the <a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a> section, and also the
string-specific methods described in the <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a> section.
To output formatted strings use template strings or the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator
described in the <a class="reference internal" href="stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section. Also, see the
<a class="reference internal" href="re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module for string functions based on regular expressions.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="string.html">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a><ul>
<li class="toctree-l2"><a class="reference internal" href="string.html#string-constants">7.1.1. String constants</a></li>
<li class="toctree-l2"><a class="reference internal" href="string.html#custom-string-formatting">7.1.2. Custom String Formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="string.html#format-string-syntax">7.1.3. Format String Syntax</a><ul>
<li class="toctree-l3"><a class="reference internal" href="string.html#format-specification-mini-language">7.1.3.1. Format Specification Mini-Language</a></li>
<li class="toctree-l3"><a class="reference internal" href="string.html#format-examples">7.1.3.2. Format examples</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="string.html#template-strings">7.1.4. Template strings</a></li>
<li class="toctree-l2"><a class="reference internal" href="string.html#string-functions">7.1.5. String functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="string.html#deprecated-string-functions">7.1.6. Deprecated string functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="re.html">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a><ul>
<li class="toctree-l2"><a class="reference internal" href="re.html#regular-expression-syntax">7.2.1. Regular Expression Syntax</a></li>
<li class="toctree-l2"><a class="reference internal" href="re.html#module-contents">7.2.2. Module Contents</a></li>
<li class="toctree-l2"><a class="reference internal" href="re.html#regular-expression-objects">7.2.3. Regular Expression Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="re.html#match-objects">7.2.4. Match Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="re.html#examples">7.2.5. Examples</a><ul>
<li class="toctree-l3"><a class="reference internal" href="re.html#checking-for-a-pair">7.2.5.1. Checking For a Pair</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#simulating-scanf">7.2.5.2. Simulating scanf()</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#search-vs-match">7.2.5.3. search() vs. match()</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#making-a-phonebook">7.2.5.4. Making a Phonebook</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#text-munging">7.2.5.5. Text Munging</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#finding-all-adverbs">7.2.5.6. Finding all Adverbs</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#finding-all-adverbs-and-their-positions">7.2.5.7. Finding all Adverbs and their Positions</a></li>
<li class="toctree-l3"><a class="reference internal" href="re.html#raw-string-notation">7.2.5.8. Raw String Notation</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="struct.html">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a><ul>
<li class="toctree-l2"><a class="reference internal" href="struct.html#functions-and-exceptions">7.3.1. Functions and Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="struct.html#format-strings">7.3.2. Format Strings</a><ul>
<li class="toctree-l3"><a class="reference internal" href="struct.html#byte-order-size-and-alignment">7.3.2.1. Byte Order, Size, and Alignment</a></li>
<li class="toctree-l3"><a class="reference internal" href="struct.html#format-characters">7.3.2.2. Format Characters</a></li>
<li class="toctree-l3"><a class="reference internal" href="struct.html#examples">7.3.2.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="struct.html#classes">7.3.3. Classes</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="difflib.html">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a><ul>
<li class="toctree-l2"><a class="reference internal" href="difflib.html#sequencematcher-objects">7.4.1. SequenceMatcher Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="difflib.html#sequencematcher-examples">7.4.2. SequenceMatcher Examples</a></li>
<li class="toctree-l2"><a class="reference internal" href="difflib.html#differ-objects">7.4.3. Differ Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="difflib.html#differ-example">7.4.4. Differ Example</a></li>
<li class="toctree-l2"><a class="reference internal" href="difflib.html#a-command-line-interface-to-difflib">7.4.5. A command-line interface to difflib</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stringio.html">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></li>
<li class="toctree-l1"><a class="reference internal" href="stringio.html#module-cStringIO">7.6. <code class="docutils literal notranslate"><span class="pre">cStringIO</span></code> — Faster version of <code class="docutils literal notranslate"><span class="pre">StringIO</span></code></a></li>
<li class="toctree-l1"><a class="reference internal" href="textwrap.html">7.7. <code class="docutils literal notranslate"><span class="pre">textwrap</span></code> — Text wrapping and filling</a></li>
<li class="toctree-l1"><a class="reference internal" href="codecs.html">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#codec-base-classes">7.8.1. Codec Base Classes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#codec-objects">7.8.1.1. Codec Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#incrementalencoder-objects">7.8.1.2. IncrementalEncoder Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#incrementaldecoder-objects">7.8.1.3. IncrementalDecoder Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#streamwriter-objects">7.8.1.4. StreamWriter Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#streamreader-objects">7.8.1.5. StreamReader Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#streamreaderwriter-objects">7.8.1.6. StreamReaderWriter Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="codecs.html#streamrecoder-objects">7.8.1.7. StreamRecoder Objects</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#encodings-and-unicode">7.8.2. Encodings and Unicode</a></li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#standard-encodings">7.8.3. Standard Encodings</a></li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#python-specific-encodings">7.8.4. Python Specific Encodings</a></li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#module-encodings.idna">7.8.5. <code class="docutils literal notranslate"><span class="pre">encodings.idna</span></code> — Internationalized Domain Names in Applications</a></li>
<li class="toctree-l2"><a class="reference internal" href="codecs.html#module-encodings.utf_8_sig">7.8.6. <code class="docutils literal notranslate"><span class="pre">encodings.utf_8_sig</span></code> — UTF-8 codec with BOM signature</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="unicodedata.html">7.9. <code class="docutils literal notranslate"><span class="pre">unicodedata</span></code> — Unicode Database</a></li>
<li class="toctree-l1"><a class="reference internal" href="stringprep.html">7.10. <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> — Internet String Preparation</a></li>
<li class="toctree-l1"><a class="reference internal" href="fpformat.html">7.11. <code class="docutils literal notranslate"><span class="pre">fpformat</span></code> — Floating point conversions</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="exceptions.html"
                        title="previous chapter">6. Built-in Exceptions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="string.html"
                        title="next chapter">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/strings.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="string.html" title="7.1. string — Common string operations"
             >next</a> |</li>
        <li class="right" >
          <a href="exceptions.html" title="6. Built-in Exceptions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\'��`�`�html/library/struct.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.3. struct — Interpret strings as packed binary data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.4. difflib — Helpers for computing deltas" href="difflib.html" />
    <link rel="prev" title="7.2. re — Regular expression operations" href="re.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/struct.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="7.4. difflib — Helpers for computing deltas"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="re.html" title="7.2. re — Regular expression operations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-struct">
<span id="struct-interpret-strings-as-packed-binary-data"></span><h1>7.3. <a class="reference internal" href="#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> — Interpret strings as packed binary data<a class="headerlink" href="#module-struct" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module performs conversions between Python values and C structs represented
as Python strings.  This can be used in handling binary data stored in files or
from network connections, among other sources.  It uses
<a class="reference internal" href="#struct-format-strings"><span class="std std-ref">Format Strings</span></a> as compact descriptions of the layout of the C
structs and the intended conversion to/from Python values.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">By default, the result of packing a given C struct includes pad bytes in
order to maintain proper alignment for the C types involved; similarly,
alignment is taken into account when unpacking.  This behavior is chosen so
that the bytes of a packed struct correspond exactly to the layout in memory
of the corresponding C struct.  To handle platform-independent data formats
or omit implicit pad bytes, use <code class="docutils literal notranslate"><span class="pre">standard</span></code> size and alignment instead of
<code class="docutils literal notranslate"><span class="pre">native</span></code> size and alignment: see <a class="reference internal" href="#struct-alignment"><span class="std std-ref">Byte Order, Size, and Alignment</span></a> for details.</p>
</div>
<div class="section" id="functions-and-exceptions">
<h2>7.3.1. Functions and Exceptions<a class="headerlink" href="#functions-and-exceptions" title="Permalink to this headline">¶</a></h2>
<p>The module defines the following exception and functions:</p>
<dl class="exception">
<dt id="struct.error">
<em class="property">exception </em><code class="descclassname">struct.</code><code class="descname">error</code><a class="headerlink" href="#struct.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on various occasions; argument is a string describing what
is wrong.</p>
</dd></dl>

<dl class="function">
<dt id="struct.pack">
<code class="descclassname">struct.</code><code class="descname">pack</code><span class="sig-paren">(</span><em>fmt</em>, <em>v1</em>, <em>v2</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.pack" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string containing the values <code class="docutils literal notranslate"><span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">...</span></code> packed according to the
given format.  The arguments must match the values required by the format
exactly.</p>
</dd></dl>

<dl class="function">
<dt id="struct.pack_into">
<code class="descclassname">struct.</code><code class="descname">pack_into</code><span class="sig-paren">(</span><em>fmt</em>, <em>buffer</em>, <em>offset</em>, <em>v1</em>, <em>v2</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.pack_into" title="Permalink to this definition">¶</a></dt>
<dd><p>Pack the values <code class="docutils literal notranslate"><span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">...</span></code> according to the given format, write the
packed bytes into the writable <em>buffer</em> starting at <em>offset</em>. Note that the
offset is a required argument.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="struct.unpack">
<code class="descclassname">struct.</code><code class="descname">unpack</code><span class="sig-paren">(</span><em>fmt</em>, <em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.unpack" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpack the string (presumably packed by <code class="docutils literal notranslate"><span class="pre">pack(fmt,</span> <span class="pre">...)</span></code>) according to the
given format.  The result is a tuple even if it contains exactly one item.
The string must contain exactly the amount of data required by the format
(<code class="docutils literal notranslate"><span class="pre">len(string)</span></code> must equal <code class="docutils literal notranslate"><span class="pre">calcsize(fmt)</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="struct.unpack_from">
<code class="descclassname">struct.</code><code class="descname">unpack_from</code><span class="sig-paren">(</span><em>fmt</em>, <em>buffer</em><span class="optional">[</span>, <em>offset=0</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#struct.unpack_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpack the <em>buffer</em> according to the given format. The result is a tuple even
if it contains exactly one item. The <em>buffer</em> must contain at least the
amount of data required by the format (<code class="docutils literal notranslate"><span class="pre">len(buffer[offset:])</span></code> must be at
least <code class="docutils literal notranslate"><span class="pre">calcsize(fmt)</span></code>).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="struct.calcsize">
<code class="descclassname">struct.</code><code class="descname">calcsize</code><span class="sig-paren">(</span><em>fmt</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.calcsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of the struct (and hence of the string) corresponding to the
given format.</p>
</dd></dl>

</div>
<div class="section" id="format-strings">
<span id="struct-format-strings"></span><h2>7.3.2. Format Strings<a class="headerlink" href="#format-strings" title="Permalink to this headline">¶</a></h2>
<p>Format strings are the mechanism used to specify the expected layout when
packing and unpacking data.  They are built up from <a class="reference internal" href="#format-characters"><span class="std std-ref">Format Characters</span></a>,
which specify the type of data being packed/unpacked.  In addition, there are
special characters for controlling the <a class="reference internal" href="#struct-alignment"><span class="std std-ref">Byte Order, Size, and Alignment</span></a>.</p>
<div class="section" id="byte-order-size-and-alignment">
<span id="struct-alignment"></span><h3>7.3.2.1. Byte Order, Size, and Alignment<a class="headerlink" href="#byte-order-size-and-alignment" title="Permalink to this headline">¶</a></h3>
<p>By default, C types are represented in the machine’s native format and byte
order, and properly aligned by skipping pad bytes if necessary (according to the
rules used by the C compiler).</p>
<p>Alternatively, the first character of the format string can be used to indicate
the byte order, size and alignment of the packed data, according to the
following table:</p>
<table border="1" class="docutils">
<colgroup>
<col width="20%" />
<col width="43%" />
<col width="18%" />
<col width="20%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Character</th>
<th class="head">Byte order</th>
<th class="head">Size</th>
<th class="head">Alignment</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&#64;</span></code></td>
<td>native</td>
<td>native</td>
<td>native</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">=</span></code></td>
<td>native</td>
<td>standard</td>
<td>none</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&lt;</span></code></td>
<td>little-endian</td>
<td>standard</td>
<td>none</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&gt;</span></code></td>
<td>big-endian</td>
<td>standard</td>
<td>none</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">!</span></code></td>
<td>network (= big-endian)</td>
<td>standard</td>
<td>none</td>
</tr>
</tbody>
</table>
<p>If the first character is not one of these, <code class="docutils literal notranslate"><span class="pre">'&#64;'</span></code> is assumed.</p>
<p>Native byte order is big-endian or little-endian, depending on the host
system. For example, Intel x86 and AMD64 (x86-64) are little-endian;
Motorola 68000 and PowerPC G5 are big-endian; ARM and Intel Itanium feature
switchable endianness (bi-endian). Use <code class="docutils literal notranslate"><span class="pre">sys.byteorder</span></code> to check the
endianness of your system.</p>
<p>Native size and alignment are determined using the C compiler’s
<code class="docutils literal notranslate"><span class="pre">sizeof</span></code> expression.  This is always combined with native byte order.</p>
<p>Standard size depends only on the format character;  see the table in
the <a class="reference internal" href="#format-characters"><span class="std std-ref">Format Characters</span></a> section.</p>
<p>Note the difference between <code class="docutils literal notranslate"><span class="pre">'&#64;'</span></code> and <code class="docutils literal notranslate"><span class="pre">'='</span></code>: both use native byte order, but
the size and alignment of the latter is standardized.</p>
<p>The form <code class="docutils literal notranslate"><span class="pre">'!'</span></code> is available for those poor souls who claim they can’t remember
whether network byte order is big-endian or little-endian.</p>
<p>There is no way to indicate non-native byte order (force byte-swapping); use the
appropriate choice of <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> or <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>.</p>
<p>Notes:</p>
<ol class="arabic simple">
<li>Padding is only automatically added between successive structure members.
No padding is added at the beginning or the end of the encoded struct.</li>
<li>No padding is added when using non-native size and alignment, e.g.
with ‘&lt;’, ‘&gt;’, ‘=’, and ‘!’.</li>
<li>To align the end of a structure to the alignment requirement of a
particular type, end the format with the code for that type with a repeat
count of zero.  See <a class="reference internal" href="#struct-examples"><span class="std std-ref">Examples</span></a>.</li>
</ol>
</div>
<div class="section" id="format-characters">
<span id="id1"></span><h3>7.3.2.2. Format Characters<a class="headerlink" href="#format-characters" title="Permalink to this headline">¶</a></h3>
<p>Format characters have the following meaning; the conversion between C and
Python values should be obvious given their types.  The ‘Standard size’ column
refers to the size of the packed value in bytes when using standard size; that
is, when the format string starts with one of <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'!'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'='</span></code>.  When using native size, the size of the packed value is
platform-dependent.</p>
<table border="1" class="docutils">
<colgroup>
<col width="10%" />
<col width="32%" />
<col width="24%" />
<col width="20%" />
<col width="15%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Format</th>
<th class="head">C Type</th>
<th class="head">Python type</th>
<th class="head">Standard size</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x</span></code></td>
<td>pad byte</td>
<td>no value</td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">c</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code></td>
<td>string of length 1</td>
<td>1</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">b</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">signed</span> <span class="pre">char</span></code></td>
<td>integer</td>
<td>1</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">B</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code></td>
<td>integer</td>
<td>1</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">?</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code></td>
<td>bool</td>
<td>1</td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">h</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">short</span></code></td>
<td>integer</td>
<td>2</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">H</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">short</span></code></td>
<td>integer</td>
<td>2</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">i</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code></td>
<td>integer</td>
<td>4</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">I</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code></td>
<td>integer</td>
<td>4</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">l</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code></td>
<td>integer</td>
<td>4</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">L</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span></code></td>
<td>integer</td>
<td>4</td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">q</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code></td>
<td>integer</td>
<td>8</td>
<td>(2), (3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">Q</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span>
<span class="pre">long</span></code></td>
<td>integer</td>
<td>8</td>
<td>(2), (3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">f</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">float</span></code></td>
<td>float</td>
<td>4</td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">d</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code></td>
<td>float</td>
<td>8</td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">s</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char[]</span></code></td>
<td>string</td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">p</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">char[]</span></code></td>
<td>string</td>
<td>&#160;</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">P</span></code></td>
<td><code class="xref c c-type docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code></td>
<td>integer</td>
<td>&#160;</td>
<td>(5), (3)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic">
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">'?'</span></code> conversion code corresponds to the <code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code> type defined by
C99. If this type is not available, it is simulated using a <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span></code>. In
standard mode, it is always represented by one byte.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">'q'</span></code> and <code class="docutils literal notranslate"><span class="pre">'Q'</span></code> conversion codes are available in native mode only if
the platform C compiler supports C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>, or, on Windows,
<code class="xref c c-type docutils literal notranslate"><span class="pre">__int64</span></code>.  They are always available in standard modes.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</li>
<li><p class="first">When attempting to pack a non-integer using any of the integer conversion
codes, if the non-integer has a <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method then that method is
called to convert the argument to an integer before packing.  If no
<a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method exists, or the call to <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> raises
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, then the <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> method is tried.  However, the use
of <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> is deprecated, and will raise <a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Use of the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method for non-integers is new in 2.7.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Prior to version 2.7, not all integer conversion codes would use the
<a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> method to convert, and <a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> was
raised only for float arguments.</p>
</div>
</li>
<li><p class="first">For the <code class="docutils literal notranslate"><span class="pre">'f'</span></code> and <code class="docutils literal notranslate"><span class="pre">'d'</span></code> conversion codes, the packed representation uses
the IEEE 754 binary32 (for <code class="docutils literal notranslate"><span class="pre">'f'</span></code>) or binary64 (for <code class="docutils literal notranslate"><span class="pre">'d'</span></code>) format,
regardless of the floating-point format used by the platform.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">'P'</span></code> format character is only available for the native byte ordering
(selected as the default or with the <code class="docutils literal notranslate"><span class="pre">'&#64;'</span></code> byte order character). The byte
order character <code class="docutils literal notranslate"><span class="pre">'='</span></code> chooses to use little- or big-endian ordering based
on the host system. The struct module does not interpret this as native
ordering, so the <code class="docutils literal notranslate"><span class="pre">'P'</span></code> format is not available.</p>
</li>
</ol>
<p>A format character may be preceded by an integral repeat count.  For example,
the format string <code class="docutils literal notranslate"><span class="pre">'4h'</span></code> means exactly the same as <code class="docutils literal notranslate"><span class="pre">'hhhh'</span></code>.</p>
<p>Whitespace characters between formats are ignored; a count and its format must
not contain whitespace though.</p>
<p>For the <code class="docutils literal notranslate"><span class="pre">'s'</span></code> format character, the count is interpreted as the size of the
string, not a repeat count like for the other format characters; for example,
<code class="docutils literal notranslate"><span class="pre">'10s'</span></code> means a single 10-byte string, while <code class="docutils literal notranslate"><span class="pre">'10c'</span></code> means 10 characters.
If a count is not given, it defaults to 1.  For packing, the string is
truncated or padded with null bytes as appropriate to make it fit. For
unpacking, the resulting string always has exactly the specified number of
bytes.  As a special case, <code class="docutils literal notranslate"><span class="pre">'0s'</span></code> means a single, empty string (while
<code class="docutils literal notranslate"><span class="pre">'0c'</span></code> means 0 characters).</p>
<p>The <code class="docutils literal notranslate"><span class="pre">'p'</span></code> format character encodes a “Pascal string”, meaning a short
variable-length string stored in a <em>fixed number of bytes</em>, given by the count.
The first byte stored is the length of the string, or 255, whichever is smaller.
The bytes of the string follow.  If the string passed in to <a class="reference internal" href="#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> is too
long (longer than the count minus 1), only the leading <code class="docutils literal notranslate"><span class="pre">count-1</span></code> bytes of the
string are stored.  If the string is shorter than <code class="docutils literal notranslate"><span class="pre">count-1</span></code>, it is padded with
null bytes so that exactly count bytes in all are used.  Note that for
<a class="reference internal" href="#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a>, the <code class="docutils literal notranslate"><span class="pre">'p'</span></code> format character consumes count bytes, but that the
string returned can never contain more than 255 characters.</p>
<p>For the <code class="docutils literal notranslate"><span class="pre">'P'</span></code> format character, the return value is a Python integer or long
integer, depending on the size needed to hold a pointer when it has been cast to
an integer type.  A <em>NULL</em> pointer will always be returned as the Python integer
<code class="docutils literal notranslate"><span class="pre">0</span></code>. When packing pointer-sized values, Python integer or long integer objects
may be used.  For example, the Alpha and Merced processors use 64-bit pointer
values, meaning a Python long integer will be used to hold the pointer; other
platforms use 32-bit pointers and will use a Python integer.</p>
<p>For the <code class="docutils literal notranslate"><span class="pre">'?'</span></code> format character, the return value is either <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or
<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. When packing, the truth value of the argument object is used.
Either 0 or 1 in the native or standard bool representation will be packed, and
any non-zero value will be <code class="docutils literal notranslate"><span class="pre">True</span></code> when unpacking.</p>
</div>
<div class="section" id="examples">
<span id="struct-examples"></span><h3>7.3.2.3. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h3>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">All examples assume a native byte order, size, and alignment with a
big-endian machine.</p>
</div>
<p>A basic example of packing/unpacking three integers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">struct</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;hhl&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">&#39;\x00\x01\x00\x02\x00\x00\x00\x03&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;hhl&#39;</span><span class="p">,</span> <span class="s1">&#39;</span><span class="se">\x00\x01\x00\x02\x00\x00\x00\x03</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">(1, 2, 3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">&#39;hhl&#39;</span><span class="p">)</span>
<span class="go">8</span>
</pre></div>
</div>
<p>Unpacked fields can be named by assigning them to variables or by wrapping
the result in a named tuple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">record</span> <span class="o">=</span> <span class="s1">&#39;raymond   </span><span class="se">\x32\x12\x08\x01\x08</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">name</span><span class="p">,</span> <span class="n">serialnum</span><span class="p">,</span> <span class="n">school</span><span class="p">,</span> <span class="n">gradelevel</span> <span class="o">=</span> <span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;&lt;10sHHb&#39;</span><span class="p">,</span> <span class="n">record</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">namedtuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;Student&#39;</span><span class="p">,</span> <span class="s1">&#39;name serialnum school gradelevel&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Student</span><span class="o">.</span><span class="n">_make</span><span class="p">(</span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;&lt;10sHHb&#39;</span><span class="p">,</span> <span class="n">record</span><span class="p">))</span>
<span class="go">Student(name=&#39;raymond   &#39;, serialnum=4658, school=264, gradelevel=8)</span>
</pre></div>
</div>
<p>The ordering of format characters may have an impact on size since the padding
needed to satisfy alignment requirements is different:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;ci&#39;</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="mh">0x12131415</span><span class="p">)</span>
<span class="go">&#39;*\x00\x00\x00\x12\x13\x14\x15&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;ic&#39;</span><span class="p">,</span> <span class="mh">0x12131415</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">)</span>
<span class="go">&#39;\x12\x13\x14\x15*&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">&#39;ci&#39;</span><span class="p">)</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">calcsize</span><span class="p">(</span><span class="s1">&#39;ic&#39;</span><span class="p">)</span>
<span class="go">5</span>
</pre></div>
</div>
<p>The following format <code class="docutils literal notranslate"><span class="pre">'llh0l'</span></code> specifies two pad bytes at the end, assuming
longs are aligned on 4-byte boundaries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pack</span><span class="p">(</span><span class="s1">&#39;llh0l&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">&#39;\x00\x00\x00\x01\x00\x00\x00\x02\x00\x03\x00\x00&#39;</span>
</pre></div>
</div>
<p>This only works when native size and alignment are in effect; standard size and
alignment does not enforce any alignment.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a></dt>
<dd>Packed binary storage of homogeneous data.</dd>
<dt>Module <a class="reference internal" href="xdrlib.html#module-xdrlib" title="xdrlib: Encoders and decoders for the External Data Representation (XDR)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xdrlib</span></code></a></dt>
<dd>Packing and unpacking of XDR data.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="classes">
<span id="struct-objects"></span><h2>7.3.3. Classes<a class="headerlink" href="#classes" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module also defines the following type:</p>
<dl class="class">
<dt id="struct.Struct">
<em class="property">class </em><code class="descclassname">struct.</code><code class="descname">Struct</code><span class="sig-paren">(</span><em>format</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new Struct object which writes and reads binary data according to
the format string <em>format</em>.  Creating a Struct object once and calling its
methods is more efficient than calling the <a class="reference internal" href="#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> functions with the
same format since the format string only needs to be compiled once.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>Compiled Struct objects support the following methods and attributes:</p>
<dl class="method">
<dt id="struct.Struct.pack">
<code class="descname">pack</code><span class="sig-paren">(</span><em>v1</em>, <em>v2</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.pack" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> function, using the compiled format.
(<code class="docutils literal notranslate"><span class="pre">len(result)</span></code> will equal <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.size</span></code>.)</p>
</dd></dl>

<dl class="method">
<dt id="struct.Struct.pack_into">
<code class="descname">pack_into</code><span class="sig-paren">(</span><em>buffer</em>, <em>offset</em>, <em>v1</em>, <em>v2</em>, <em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.pack_into" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#struct.pack_into" title="struct.pack_into"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack_into()</span></code></a> function, using the compiled format.</p>
</dd></dl>

<dl class="method">
<dt id="struct.Struct.unpack">
<code class="descname">unpack</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.unpack" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> function, using the compiled format.
(<code class="docutils literal notranslate"><span class="pre">len(string)</span></code> must equal <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.size</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="struct.Struct.unpack_from">
<code class="descname">unpack_from</code><span class="sig-paren">(</span><em>buffer</em>, <em>offset=0</em><span class="sig-paren">)</span><a class="headerlink" href="#struct.Struct.unpack_from" title="Permalink to this definition">¶</a></dt>
<dd><p>Identical to the <a class="reference internal" href="#struct.unpack_from" title="struct.unpack_from"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack_from()</span></code></a> function, using the compiled format.
(<code class="docutils literal notranslate"><span class="pre">len(buffer[offset:])</span></code> must be at least <code class="xref py py-attr docutils literal notranslate"><span class="pre">self.size</span></code>).</p>
</dd></dl>

<dl class="attribute">
<dt id="struct.Struct.format">
<code class="descname">format</code><a class="headerlink" href="#struct.Struct.format" title="Permalink to this definition">¶</a></dt>
<dd><p>The format string used to construct this Struct object.</p>
</dd></dl>

<dl class="attribute">
<dt id="struct.Struct.size">
<code class="descname">size</code><a class="headerlink" href="#struct.Struct.size" title="Permalink to this definition">¶</a></dt>
<dd><p>The calculated size of the struct (and hence of the string) corresponding
to <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">format</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a><ul>
<li><a class="reference internal" href="#functions-and-exceptions">7.3.1. Functions and Exceptions</a></li>
<li><a class="reference internal" href="#format-strings">7.3.2. Format Strings</a><ul>
<li><a class="reference internal" href="#byte-order-size-and-alignment">7.3.2.1. Byte Order, Size, and Alignment</a></li>
<li><a class="reference internal" href="#format-characters">7.3.2.2. Format Characters</a></li>
<li><a class="reference internal" href="#examples">7.3.2.3. Examples</a></li>
</ul>
</li>
<li><a class="reference internal" href="#classes">7.3.3. Classes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="re.html"
                        title="previous chapter">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="difflib.html"
                        title="next chapter">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/struct.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="difflib.html" title="7.4. difflib — Helpers for computing deltas"
             >next</a> |</li>
        <li class="right" >
          <a href="re.html" title="7.2. re — Regular expression operations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�X6o�o�html/library/subprocess.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>17.1. subprocess — Subprocess management &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="17.2. socket — Low-level networking interface" href="socket.html" />
    <link rel="prev" title="17. Interprocess Communication and Networking" href="ipc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/subprocess.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="socket.html" title="17.2. socket — Low-level networking interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ipc.html" title="17. Interprocess Communication and Networking"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" accesskey="U">17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-subprocess">
<span id="subprocess-subprocess-management"></span><h1>17.1. <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> — Subprocess management<a class="headerlink" href="#module-subprocess" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>The <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module allows you to spawn new processes, connect to their
input/output/error pipes, and obtain their return codes.  This module intends to
replace several older modules and functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">system</span>
<span class="n">os</span><span class="o">.</span><span class="n">spawn</span><span class="o">*</span>
<span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="o">*</span>
<span class="n">popen2</span><span class="o">.*</span>
<span class="n">commands</span><span class="o">.*</span>
</pre></div>
</div>
<p>Information about how this module can be used to replace the older
functions can be found in the <a class="reference internal" href="#subprocess-replacements">subprocess-replacements</a> section.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>POSIX users (Linux, BSD, etc.) are strongly encouraged to install
and use the much more recent <a class="reference external" href="https://pypi.org/project/subprocess32/">subprocess32</a> module instead of the
version included with python 2.7.  It is a drop in replacement with
better behavior in many situations.</p>
<p class="last"><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0324"><strong>PEP 324</strong></a> – PEP proposing the subprocess module</p>
</div>
<div class="section" id="using-the-subprocess-module">
<h2>17.1.1. Using the <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> Module<a class="headerlink" href="#using-the-subprocess-module" title="Permalink to this headline">¶</a></h2>
<p>The recommended way to launch subprocesses is to use the following
convenience functions.  For more advanced use cases when these do not
meet your needs, use the underlying <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> interface.</p>
<dl class="function">
<dt id="subprocess.call">
<code class="descclassname">subprocess.</code><code class="descname">call</code><span class="sig-paren">(</span><em>args</em>, <em>*</em>, <em>stdin=None</em>, <em>stdout=None</em>, <em>stderr=None</em>, <em>shell=False</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.call" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the command described by <em>args</em>.  Wait for command to complete, then
return the <code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code> attribute.</p>
<p>The arguments shown above are merely the most common ones, described below
in <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> (hence the slightly odd notation in
the abbreviated signature). The full function signature is the same as
that of the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor - this functions passes all
supplied arguments directly through to that interface.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">([</span><span class="s2">&quot;ls&quot;</span><span class="p">,</span> <span class="s2">&quot;-l&quot;</span><span class="p">])</span>
<span class="go">0</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s2">&quot;exit 1&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">1</span>
</pre></div>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Using <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> can be a security hazard.  See the warning
under <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> for details.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Do not use <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> or <code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> with this function
as that can deadlock based on the child process output volume.
Use <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code> method when you
need pipes.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="subprocess.check_call">
<code class="descclassname">subprocess.</code><code class="descname">check_call</code><span class="sig-paren">(</span><em>args</em>, <em>*</em>, <em>stdin=None</em>, <em>stdout=None</em>, <em>stderr=None</em>, <em>shell=False</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.check_call" title="Permalink to this definition">¶</a></dt>
<dd><p>Run command with arguments.  Wait for command to complete. If the return
code was zero then return, otherwise raise <a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a>. The
<a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a> object will have the return code in the
<a class="reference internal" href="#subprocess.CalledProcessError.returncode" title="subprocess.CalledProcessError.returncode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code></a> attribute.</p>
<p>The arguments shown above are merely the most common ones, described below
in <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> (hence the slightly odd notation in
the abbreviated signature). The full function signature is the same as
that of the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor - this functions passes all
supplied arguments directly through to that interface.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_call</span><span class="p">([</span><span class="s2">&quot;ls&quot;</span><span class="p">,</span> <span class="s2">&quot;-l&quot;</span><span class="p">])</span>
<span class="go">0</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_call</span><span class="p">(</span><span class="s2">&quot;exit 1&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
   <span class="c">...</span>
<span class="gr">subprocess.CalledProcessError</span>: <span class="n">Command &#39;exit 1&#39; returned non-zero exit status 1</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Using <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> can be a security hazard.  See the warning
under <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> for details.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Do not use <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> or <code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> with this function
as that can deadlock based on the child process output volume.
Use <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code> method when you
need pipes.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="subprocess.check_output">
<code class="descclassname">subprocess.</code><code class="descname">check_output</code><span class="sig-paren">(</span><em>args</em>, <em>*</em>, <em>stdin=None</em>, <em>stderr=None</em>, <em>shell=False</em>, <em>universal_newlines=False</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.check_output" title="Permalink to this definition">¶</a></dt>
<dd><p>Run command with arguments and return its output as a byte string.</p>
<p>If the return code was non-zero it raises a <a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a>. The
<a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a> object will have the return code in the
<a class="reference internal" href="#subprocess.CalledProcessError.returncode" title="subprocess.CalledProcessError.returncode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code></a> attribute and any output in the
<a class="reference internal" href="#subprocess.CalledProcessError.output" title="subprocess.CalledProcessError.output"><code class="xref py py-attr docutils literal notranslate"><span class="pre">output</span></code></a> attribute.</p>
<p>The arguments shown above are merely the most common ones, described below
in <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> (hence the slightly odd notation in
the abbreviated signature). The full function signature is largely the
same as that of the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor, except that <em>stdout</em> is
not permitted as it is used internally. All other supplied arguments are
passed directly through to the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">([</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="s2">&quot;Hello World!&quot;</span><span class="p">])</span>
<span class="go">&#39;Hello World!\n&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">(</span><span class="s2">&quot;exit 1&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
   <span class="c">...</span>
<span class="gr">subprocess.CalledProcessError</span>: <span class="n">Command &#39;exit 1&#39; returned non-zero exit status 1</span>
</pre></div>
</div>
<p>To also capture standard error in the result, use
<code class="docutils literal notranslate"><span class="pre">stderr=subprocess.STDOUT</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">(</span>
<span class="gp">... </span>    <span class="s2">&quot;ls non_existent_file; exit 0&quot;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">stderr</span><span class="o">=</span><span class="n">subprocess</span><span class="o">.</span><span class="n">STDOUT</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;ls: non_existent_file: No such file or directory\n&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Using <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> can be a security hazard.  See the warning
under <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a> for details.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Do not use <code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> with this function as that can deadlock
based on the child process error volume.  Use <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> with
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code> method when you need a stderr pipe.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="subprocess.PIPE">
<code class="descclassname">subprocess.</code><code class="descname">PIPE</code><a class="headerlink" href="#subprocess.PIPE" title="Permalink to this definition">¶</a></dt>
<dd><p>Special value that can be used as the <em>stdin</em>, <em>stdout</em> or <em>stderr</em> argument
to <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> and indicates that a pipe to the standard stream should be
opened.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.STDOUT">
<code class="descclassname">subprocess.</code><code class="descname">STDOUT</code><a class="headerlink" href="#subprocess.STDOUT" title="Permalink to this definition">¶</a></dt>
<dd><p>Special value that can be used as the <em>stderr</em> argument to <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> and
indicates that standard error should go into the same handle as standard
output.</p>
</dd></dl>

<dl class="exception">
<dt id="subprocess.CalledProcessError">
<em class="property">exception </em><code class="descclassname">subprocess.</code><code class="descname">CalledProcessError</code><a class="headerlink" href="#subprocess.CalledProcessError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a process run by <a class="reference internal" href="#subprocess.check_call" title="subprocess.check_call"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_call()</span></code></a> or
<a class="reference internal" href="#subprocess.check_output" title="subprocess.check_output"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_output()</span></code></a> returns a non-zero exit status.</p>
<dl class="attribute">
<dt id="subprocess.CalledProcessError.returncode">
<code class="descname">returncode</code><a class="headerlink" href="#subprocess.CalledProcessError.returncode" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit status of the child process.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.CalledProcessError.cmd">
<code class="descname">cmd</code><a class="headerlink" href="#subprocess.CalledProcessError.cmd" title="Permalink to this definition">¶</a></dt>
<dd><p>Command that was used to spawn the child process.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.CalledProcessError.output">
<code class="descname">output</code><a class="headerlink" href="#subprocess.CalledProcessError.output" title="Permalink to this definition">¶</a></dt>
<dd><p>Output of the child process if this exception is raised by
<a class="reference internal" href="#subprocess.check_output" title="subprocess.check_output"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_output()</span></code></a>.  Otherwise, <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</dd></dl>

<div class="section" id="frequently-used-arguments">
<span id="id1"></span><h3>17.1.1.1. Frequently Used Arguments<a class="headerlink" href="#frequently-used-arguments" title="Permalink to this headline">¶</a></h3>
<p>To support a wide variety of use cases, the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor (and
the convenience functions) accept a large number of optional arguments. For
most typical use cases, many of these arguments can be safely left at their
default values. The arguments that are most commonly needed are:</p>
<blockquote>
<div><p><em>args</em> is required for all calls and should be a string, or a sequence of
program arguments. Providing a sequence of arguments is generally
preferred, as it allows the module to take care of any required escaping
and quoting of arguments (e.g. to permit spaces in file names). If passing
a single string, either <em>shell</em> must be <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> (see below) or else
the string must simply name the program to be executed without specifying
any arguments.</p>
<p><em>stdin</em>, <em>stdout</em> and <em>stderr</em> specify the executed program’s standard input,
standard output and standard error file handles, respectively.  Valid values
are <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a>, an existing file descriptor (a positive integer), an
existing file object, and <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a> indicates that a new pipe
to the child should be created.  With the default settings of <code class="docutils literal notranslate"><span class="pre">None</span></code>, no
redirection will occur; the child’s file handles will be inherited from the
parent.  Additionally, <em>stderr</em> can be <a class="reference internal" href="#subprocess.STDOUT" title="subprocess.STDOUT"><code class="xref py py-data docutils literal notranslate"><span class="pre">STDOUT</span></code></a>, which indicates that
the stderr data from the child process should be captured into the same file
handle as for stdout.</p>
<p id="index-1">When <em>stdout</em> or <em>stderr</em> are pipes and <em>universal_newlines</em> is
<code class="docutils literal notranslate"><span class="pre">True</span></code> then all line endings will be converted to <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> as described
for the <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> <code class="docutils literal notranslate"><span class="pre">'U'</span></code> mode argument to <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>
<p>If <em>shell</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the specified command will be executed through
the shell.  This can be useful if you are using Python primarily for the
enhanced control flow it offers over most system shells and still want
convenient access to other shell features such as shell pipes, filename
wildcards, environment variable expansion, and expansion of <code class="docutils literal notranslate"><span class="pre">~</span></code> to a
user’s home directory.  However, note that Python itself offers
implementations of many shell-like features (in particular, <a class="reference internal" href="glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a>,
<a class="reference internal" href="fnmatch.html#module-fnmatch" title="fnmatch: Unix shell style filename pattern matching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fnmatch</span></code></a>, <a class="reference internal" href="os.html#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.walk()</span></code></a>, <a class="reference internal" href="os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a>,
<a class="reference internal" href="os.path.html#os.path.expanduser" title="os.path.expanduser"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expanduser()</span></code></a>, and <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a>).</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Executing shell commands that incorporate unsanitized input from an
untrusted source makes a program vulnerable to <a class="reference external" href="http://en.wikipedia.org/wiki/Shell_injection#Shell_injection">shell injection</a>,
a serious security flaw which can result in arbitrary command execution.
For this reason, the use of <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> is <strong>strongly discouraged</strong>
in cases where the command string is constructed from external input:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">subprocess</span> <span class="k">import</span> <span class="n">call</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filename</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s2">&quot;What file would you like to display?</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="go">What file would you like to display?</span>
<span class="go">non_existent; rm -rf / #</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">call</span><span class="p">(</span><span class="s2">&quot;cat &quot;</span> <span class="o">+</span> <span class="n">filename</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="c1"># Uh-oh. This will end badly...</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">shell=False</span></code> disables all shell based features, but does not suffer
from this vulnerability; see the Note in the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor
documentation for helpful hints in getting <code class="docutils literal notranslate"><span class="pre">shell=False</span></code> to work.</p>
<p class="last">When using <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>, <a class="reference internal" href="pipes.html#pipes.quote" title="pipes.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">pipes.quote()</span></code></a> can be used to properly
escape whitespace and shell metacharacters in strings that are going to
be used to construct shell commands.</p>
</div>
</div></blockquote>
<p>These options, along with all of the other options, are described in more
detail in the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> constructor documentation.</p>
</div>
<div class="section" id="popen-constructor">
<h3>17.1.1.2. Popen Constructor<a class="headerlink" href="#popen-constructor" title="Permalink to this headline">¶</a></h3>
<p>The underlying process creation and management in this module is handled by
the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> class. It offers a lot of flexibility so that developers
are able to handle the less common cases not covered by the convenience
functions.</p>
<dl class="class">
<dt id="subprocess.Popen">
<em class="property">class </em><code class="descclassname">subprocess.</code><code class="descname">Popen</code><span class="sig-paren">(</span><em>args</em>, <em>bufsize=0</em>, <em>executable=None</em>, <em>stdin=None</em>, <em>stdout=None</em>, <em>stderr=None</em>, <em>preexec_fn=None</em>, <em>close_fds=False</em>, <em>shell=False</em>, <em>cwd=None</em>, <em>env=None</em>, <em>universal_newlines=False</em>, <em>startupinfo=None</em>, <em>creationflags=0</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute a child program in a new process.  On Unix, the class uses
<a class="reference internal" href="os.html#os.execvp" title="os.execvp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">os.execvp()</span></code></a>-like behavior to execute the child program.  On Windows,
the class uses the Windows <code class="docutils literal notranslate"><span class="pre">CreateProcess()</span></code> function.  The arguments to
<a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> are as follows.</p>
<p><em>args</em> should be a sequence of program arguments or else a single string.
By default, the program to execute is the first item in <em>args</em> if <em>args</em> is
a sequence.  If <em>args</em> is a string, the interpretation is
platform-dependent and described below.  See the <em>shell</em> and <em>executable</em>
arguments for additional differences from the default behavior.  Unless
otherwise stated, it is recommended to pass <em>args</em> as a sequence.</p>
<p>On Unix, if <em>args</em> is a string, the string is interpreted as the name or
path of the program to execute.  However, this can only be done if not
passing arguments to the program.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p><a class="reference internal" href="shlex.html#shlex.split" title="shlex.split"><code class="xref py py-meth docutils literal notranslate"><span class="pre">shlex.split()</span></code></a> can be useful when determining the correct
tokenization for <em>args</em>, especially in complex cases:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">shlex</span><span class="o">,</span> <span class="nn">subprocess</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">command_line</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">()</span>
<span class="go">/bin/vikings -input eggs.txt -output &quot;spam spam.txt&quot; -cmd &quot;echo &#39;$MONEY&#39;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">shlex</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="n">command_line</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">args</span>
<span class="go">[&#39;/bin/vikings&#39;, &#39;-input&#39;, &#39;eggs.txt&#39;, &#39;-output&#39;, &#39;spam spam.txt&#39;, &#39;-cmd&#39;, &quot;echo &#39;$MONEY&#39;&quot;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">Popen</span><span class="p">(</span><span class="n">args</span><span class="p">)</span> <span class="c1"># Success!</span>
</pre></div>
</div>
<p class="last">Note in particular that options (such as <em>-input</em>) and arguments (such
as <em>eggs.txt</em>) that are separated by whitespace in the shell go in separate
list elements, while arguments that need quoting or backslash escaping when
used in the shell (such as filenames containing spaces or the <em>echo</em> command
shown above) are single list elements.</p>
</div>
<p>On Windows, if <em>args</em> is a sequence, it will be converted to a string in a
manner described in <a class="reference internal" href="#converting-argument-sequence"><span class="std std-ref">Converting an argument sequence to a string on Windows</span></a>.  This is because
the underlying <code class="docutils literal notranslate"><span class="pre">CreateProcess()</span></code> operates on strings.</p>
<p>The <em>shell</em> argument (which defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>) specifies whether to use
the shell as the program to execute.  If <em>shell</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, it is
recommended to pass <em>args</em> as a string rather than as a sequence.</p>
<p>On Unix with <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>, the shell defaults to <code class="file docutils literal notranslate"><span class="pre">/bin/sh</span></code>.  If
<em>args</em> is a string, the string specifies the command
to execute through the shell.  This means that the string must be
formatted exactly as it would be when typed at the shell prompt.  This
includes, for example, quoting or backslash escaping filenames with spaces in
them.  If <em>args</em> is a sequence, the first item specifies the command string, and
any additional items will be treated as additional arguments to the shell
itself.  That is to say, <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> does the equivalent of:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Popen</span><span class="p">([</span><span class="s1">&#39;/bin/sh&#39;</span><span class="p">,</span> <span class="s1">&#39;-c&#39;</span><span class="p">,</span> <span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="o">...</span><span class="p">])</span>
</pre></div>
</div>
<p>On Windows with <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>, the <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">COMSPEC</span></code> environment variable
specifies the default shell.  The only time you need to specify
<code class="docutils literal notranslate"><span class="pre">shell=True</span></code> on Windows is when the command you wish to execute is built
into the shell (e.g. <strong class="command">dir</strong> or <strong class="command">copy</strong>).  You do not need
<code class="docutils literal notranslate"><span class="pre">shell=True</span></code> to run a batch file or console-based executable.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Passing <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> can be a security hazard if combined with
untrusted input.  See the warning under <a class="reference internal" href="#frequently-used-arguments"><span class="std std-ref">Frequently Used Arguments</span></a>
for details.</p>
</div>
<p><em>bufsize</em>, if given, has the same meaning as the corresponding argument to the
built-in open() function: <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> means unbuffered, <code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code> means line
buffered, any other positive value means use a buffer of (approximately) that
size.  A negative <em>bufsize</em> means to use the system default, which usually means
fully buffered.  The default value for <em>bufsize</em> is <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code> (unbuffered).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If you experience performance issues, it is recommended that you try to
enable buffering by setting <em>bufsize</em> to either -1 or a large enough
positive value (such as 4096).</p>
</div>
<p>The <em>executable</em> argument specifies a replacement program to execute.   It
is very seldom needed.  When <code class="docutils literal notranslate"><span class="pre">shell=False</span></code>, <em>executable</em> replaces the
program to execute specified by <em>args</em>.  However, the original <em>args</em> is
still passed to the program.  Most programs treat the program specified
by <em>args</em> as the command name, which can then be different from the program
actually executed.  On Unix, the <em>args</em> name
becomes the display name for the executable in utilities such as
<strong class="program">ps</strong>.  If <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>, on Unix the <em>executable</em> argument
specifies a replacement shell for the default <code class="file docutils literal notranslate"><span class="pre">/bin/sh</span></code>.</p>
<p><em>stdin</em>, <em>stdout</em> and <em>stderr</em> specify the executed program’s standard input,
standard output and standard error file handles, respectively.  Valid values
are <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a>, an existing file descriptor (a positive integer), an
existing file object, and <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a> indicates that a new pipe
to the child should be created.  With the default settings of <code class="docutils literal notranslate"><span class="pre">None</span></code>, no
redirection will occur; the child’s file handles will be inherited from the
parent.  Additionally, <em>stderr</em> can be <a class="reference internal" href="#subprocess.STDOUT" title="subprocess.STDOUT"><code class="xref py py-data docutils literal notranslate"><span class="pre">STDOUT</span></code></a>, which indicates that
the stderr data from the child process should be captured into the same file
handle as for stdout.</p>
<p>If <em>preexec_fn</em> is set to a callable object, this object will be called in the
child process just before the child is executed. (Unix only)</p>
<p>If <em>close_fds</em> is true, all file descriptors except <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">1</span></code> and
<code class="xref py py-const docutils literal notranslate"><span class="pre">2</span></code> will be closed before the child process is executed. (Unix only).
Or, on Windows, if <em>close_fds</em> is true then no handles will be inherited by the
child process.  Note that on Windows, you cannot set <em>close_fds</em> to true and
also redirect the standard handles by setting <em>stdin</em>, <em>stdout</em> or <em>stderr</em>.</p>
<p>If <em>cwd</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the child’s current directory will be changed to <em>cwd</em>
before it is executed.  Note that this directory is not considered when
searching the executable, so you can’t specify the program’s path relative to
<em>cwd</em>.</p>
<p>If <em>env</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be a mapping that defines the environment
variables for the new process; these are used instead of inheriting the current
process’ environment, which is the default behavior.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If specified, <em>env</em> must provide any variables required
for the program to execute.  On Windows, in order to run a
<a class="reference external" href="https://en.wikipedia.org/wiki/Side-by-Side_Assembly">side-by-side assembly</a> the specified <em>env</em> <strong>must</strong> include a valid
<span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">SystemRoot</span></code>.</p>
</div>
<p>If <em>universal_newlines</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the file objects <em>stdout</em> and <em>stderr</em>
are opened as text files in <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode.  Lines may be
terminated by any of <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, the Unix end-of-line convention, <code class="docutils literal notranslate"><span class="pre">'\r'</span></code>,
the old Macintosh convention or <code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>, the Windows convention. All of
these external representations are seen as <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> by the Python program.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This feature is only available if Python is built with universal newline
support (the default).  Also, the newlines attribute of the file objects
<a class="reference internal" href="#subprocess.Popen.stdout" title="subprocess.Popen.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stdout</span></code></a>, <a class="reference internal" href="#subprocess.Popen.stdin" title="subprocess.Popen.stdin"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stdin</span></code></a> and <a class="reference internal" href="#subprocess.Popen.stderr" title="subprocess.Popen.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stderr</span></code></a> are not updated by the
communicate() method.</p>
</div>
<p>If given, <em>startupinfo</em> will be a <a class="reference internal" href="#subprocess.STARTUPINFO" title="subprocess.STARTUPINFO"><code class="xref py py-class docutils literal notranslate"><span class="pre">STARTUPINFO</span></code></a> object, which is
passed to the underlying <code class="docutils literal notranslate"><span class="pre">CreateProcess</span></code> function.
<em>creationflags</em>, if given, can be <a class="reference internal" href="#subprocess.CREATE_NEW_CONSOLE" title="subprocess.CREATE_NEW_CONSOLE"><code class="xref py py-data docutils literal notranslate"><span class="pre">CREATE_NEW_CONSOLE</span></code></a> or
<a class="reference internal" href="#subprocess.CREATE_NEW_PROCESS_GROUP" title="subprocess.CREATE_NEW_PROCESS_GROUP"><code class="xref py py-data docutils literal notranslate"><span class="pre">CREATE_NEW_PROCESS_GROUP</span></code></a>. (Windows only)</p>
</dd></dl>

</div>
<div class="section" id="exceptions">
<h3>17.1.1.3. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h3>
<p>Exceptions raised in the child process, before the new program has started to
execute, will be re-raised in the parent.  Additionally, the exception object
will have one extra attribute called <code class="xref py py-attr docutils literal notranslate"><span class="pre">child_traceback</span></code>, which is a string
containing traceback information from the child’s point of view.</p>
<p>The most common exception raised is <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>.  This occurs, for example,
when trying to execute a non-existent file.  Applications should prepare for
<a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> exceptions.</p>
<p>A <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised if <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> is called with invalid
arguments.</p>
<p><a class="reference internal" href="#subprocess.check_call" title="subprocess.check_call"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_call()</span></code></a> and <a class="reference internal" href="#subprocess.check_output" title="subprocess.check_output"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_output()</span></code></a> will raise
<a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a> if the called process returns a non-zero return
code.</p>
</div>
<div class="section" id="security">
<h3>17.1.1.4. Security<a class="headerlink" href="#security" title="Permalink to this headline">¶</a></h3>
<p>Unlike some other popen functions, this implementation will never call a
system shell implicitly.  This means that all characters, including shell
metacharacters, can safely be passed to child processes. Obviously, if the
shell is invoked explicitly, then it is the application’s responsibility to
ensure that all whitespace and metacharacters are quoted appropriately.</p>
</div>
</div>
<div class="section" id="popen-objects">
<h2>17.1.2. Popen Objects<a class="headerlink" href="#popen-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of the <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> class have the following methods:</p>
<dl class="method">
<dt id="subprocess.Popen.poll">
<code class="descclassname">Popen.</code><code class="descname">poll</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.poll" title="Permalink to this definition">¶</a></dt>
<dd><p>Check if child process has terminated.  Set and return
<a class="reference internal" href="#subprocess.Popen.returncode" title="subprocess.Popen.returncode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code></a> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="subprocess.Popen.wait">
<code class="descclassname">Popen.</code><code class="descname">wait</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for child process to terminate.  Set and return
<a class="reference internal" href="#subprocess.Popen.returncode" title="subprocess.Popen.returncode"><code class="xref py py-attr docutils literal notranslate"><span class="pre">returncode</span></code></a> attribute.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">This will deadlock when using <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> and/or
<code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> and the child process generates enough output to
a pipe such that it blocks waiting for the OS pipe buffer to
accept more data.  Use <a class="reference internal" href="#subprocess.Popen.communicate" title="subprocess.Popen.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> to avoid that.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="subprocess.Popen.communicate">
<code class="descclassname">Popen.</code><code class="descname">communicate</code><span class="sig-paren">(</span><em>input=None</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.communicate" title="Permalink to this definition">¶</a></dt>
<dd><p>Interact with process: Send data to stdin.  Read data from stdout and stderr,
until end-of-file is reached.  Wait for process to terminate. The optional
<em>input</em> argument should be a string to be sent to the child process, or
<code class="docutils literal notranslate"><span class="pre">None</span></code>, if no data should be sent to the child.</p>
<p><a class="reference internal" href="#subprocess.Popen.communicate" title="subprocess.Popen.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> returns a tuple <code class="docutils literal notranslate"><span class="pre">(stdoutdata,</span> <span class="pre">stderrdata)</span></code>.</p>
<p>Note that if you want to send data to the process’s stdin, you need to create
the Popen object with <code class="docutils literal notranslate"><span class="pre">stdin=PIPE</span></code>.  Similarly, to get anything other than
<code class="docutils literal notranslate"><span class="pre">None</span></code> in the result tuple, you need to give <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> and/or
<code class="docutils literal notranslate"><span class="pre">stderr=PIPE</span></code> too.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The data read is buffered in memory, so do not use this method if the data
size is large or unlimited.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="subprocess.Popen.send_signal">
<code class="descclassname">Popen.</code><code class="descname">send_signal</code><span class="sig-paren">(</span><em>signal</em><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.send_signal" title="Permalink to this definition">¶</a></dt>
<dd><p>Sends the signal <em>signal</em> to the child.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Windows, SIGTERM is an alias for <a class="reference internal" href="#subprocess.Popen.terminate" title="subprocess.Popen.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a>. CTRL_C_EVENT and
CTRL_BREAK_EVENT can be sent to processes started with a <em>creationflags</em>
parameter which includes <cite>CREATE_NEW_PROCESS_GROUP</cite>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="subprocess.Popen.terminate">
<code class="descclassname">Popen.</code><code class="descname">terminate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.terminate" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the child. On Posix OSs the method sends SIGTERM to the
child. On Windows the Win32 API function <code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code> is called
to stop the child.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="subprocess.Popen.kill">
<code class="descclassname">Popen.</code><code class="descname">kill</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#subprocess.Popen.kill" title="Permalink to this definition">¶</a></dt>
<dd><p>Kills the child. On Posix OSs the function sends SIGKILL to the child.
On Windows <a class="reference internal" href="#subprocess.Popen.kill" title="subprocess.Popen.kill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">kill()</span></code></a> is an alias for <a class="reference internal" href="#subprocess.Popen.terminate" title="subprocess.Popen.terminate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>The following attributes are also available:</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Use <a class="reference internal" href="#subprocess.Popen.communicate" title="subprocess.Popen.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a> rather than <a class="reference internal" href="#subprocess.Popen.stdin" title="subprocess.Popen.stdin"><code class="xref py py-attr docutils literal notranslate"><span class="pre">.stdin.write</span></code></a>,
<a class="reference internal" href="#subprocess.Popen.stdout" title="subprocess.Popen.stdout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">.stdout.read</span></code></a> or <a class="reference internal" href="#subprocess.Popen.stderr" title="subprocess.Popen.stderr"><code class="xref py py-attr docutils literal notranslate"><span class="pre">.stderr.read</span></code></a> to avoid
deadlocks due to any of the other OS pipe buffers filling up and blocking the
child process.</p>
</div>
<dl class="attribute">
<dt id="subprocess.Popen.stdin">
<code class="descclassname">Popen.</code><code class="descname">stdin</code><a class="headerlink" href="#subprocess.Popen.stdin" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>stdin</em> argument was <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a>, this attribute is a file object
that provides input to the child process.  Otherwise, it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.Popen.stdout">
<code class="descclassname">Popen.</code><code class="descname">stdout</code><a class="headerlink" href="#subprocess.Popen.stdout" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>stdout</em> argument was <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a>, this attribute is a file object
that provides output from the child process.  Otherwise, it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.Popen.stderr">
<code class="descclassname">Popen.</code><code class="descname">stderr</code><a class="headerlink" href="#subprocess.Popen.stderr" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>stderr</em> argument was <a class="reference internal" href="#subprocess.PIPE" title="subprocess.PIPE"><code class="xref py py-data docutils literal notranslate"><span class="pre">PIPE</span></code></a>, this attribute is a file object
that provides error output from the child process.  Otherwise, it is
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.Popen.pid">
<code class="descclassname">Popen.</code><code class="descname">pid</code><a class="headerlink" href="#subprocess.Popen.pid" title="Permalink to this definition">¶</a></dt>
<dd><p>The process ID of the child process.</p>
<p>Note that if you set the <em>shell</em> argument to <code class="docutils literal notranslate"><span class="pre">True</span></code>, this is the process ID
of the spawned shell.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.Popen.returncode">
<code class="descclassname">Popen.</code><code class="descname">returncode</code><a class="headerlink" href="#subprocess.Popen.returncode" title="Permalink to this definition">¶</a></dt>
<dd><p>The child return code, set by <a class="reference internal" href="#subprocess.Popen.poll" title="subprocess.Popen.poll"><code class="xref py py-meth docutils literal notranslate"><span class="pre">poll()</span></code></a> and <a class="reference internal" href="#subprocess.Popen.wait" title="subprocess.Popen.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> (and indirectly
by <a class="reference internal" href="#subprocess.Popen.communicate" title="subprocess.Popen.communicate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">communicate()</span></code></a>).  A <code class="docutils literal notranslate"><span class="pre">None</span></code> value indicates that the process
hasn’t terminated yet.</p>
<p>A negative value <code class="docutils literal notranslate"><span class="pre">-N</span></code> indicates that the child was terminated by signal
<code class="docutils literal notranslate"><span class="pre">N</span></code> (Unix only).</p>
</dd></dl>

</div>
<div class="section" id="windows-popen-helpers">
<h2>17.1.3. Windows Popen Helpers<a class="headerlink" href="#windows-popen-helpers" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#subprocess.STARTUPINFO" title="subprocess.STARTUPINFO"><code class="xref py py-class docutils literal notranslate"><span class="pre">STARTUPINFO</span></code></a> class and following constants are only available
on Windows.</p>
<dl class="class">
<dt id="subprocess.STARTUPINFO">
<em class="property">class </em><code class="descclassname">subprocess.</code><code class="descname">STARTUPINFO</code><a class="headerlink" href="#subprocess.STARTUPINFO" title="Permalink to this definition">¶</a></dt>
<dd><p>Partial support of the Windows
<a class="reference external" href="https://msdn.microsoft.com/en-us/library/ms686331(v=vs.85).aspx">STARTUPINFO</a>
structure is used for <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> creation.</p>
<dl class="attribute">
<dt id="subprocess.STARTUPINFO.dwFlags">
<code class="descname">dwFlags</code><a class="headerlink" href="#subprocess.STARTUPINFO.dwFlags" title="Permalink to this definition">¶</a></dt>
<dd><p>A bit field that determines whether certain <a class="reference internal" href="#subprocess.STARTUPINFO" title="subprocess.STARTUPINFO"><code class="xref py py-class docutils literal notranslate"><span class="pre">STARTUPINFO</span></code></a>
attributes are used when the process creates a window.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">si</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">STARTUPINFO</span><span class="p">()</span>
<span class="n">si</span><span class="o">.</span><span class="n">dwFlags</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">STARTF_USESTDHANDLES</span> <span class="o">|</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">STARTF_USESHOWWINDOW</span>
</pre></div>
</div>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.STARTUPINFO.hStdInput">
<code class="descname">hStdInput</code><a class="headerlink" href="#subprocess.STARTUPINFO.hStdInput" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#subprocess.STARTUPINFO.dwFlags" title="subprocess.STARTUPINFO.dwFlags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dwFlags</span></code></a> specifies <a class="reference internal" href="#subprocess.STARTF_USESTDHANDLES" title="subprocess.STARTF_USESTDHANDLES"><code class="xref py py-data docutils literal notranslate"><span class="pre">STARTF_USESTDHANDLES</span></code></a>, this attribute
is the standard input handle for the process. If
<a class="reference internal" href="#subprocess.STARTF_USESTDHANDLES" title="subprocess.STARTF_USESTDHANDLES"><code class="xref py py-data docutils literal notranslate"><span class="pre">STARTF_USESTDHANDLES</span></code></a> is not specified, the default for standard
input is the keyboard buffer.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.STARTUPINFO.hStdOutput">
<code class="descname">hStdOutput</code><a class="headerlink" href="#subprocess.STARTUPINFO.hStdOutput" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#subprocess.STARTUPINFO.dwFlags" title="subprocess.STARTUPINFO.dwFlags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dwFlags</span></code></a> specifies <a class="reference internal" href="#subprocess.STARTF_USESTDHANDLES" title="subprocess.STARTF_USESTDHANDLES"><code class="xref py py-data docutils literal notranslate"><span class="pre">STARTF_USESTDHANDLES</span></code></a>, this attribute
is the standard output handle for the process. Otherwise, this attribute
is ignored and the default for standard output is the console window’s
buffer.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.STARTUPINFO.hStdError">
<code class="descname">hStdError</code><a class="headerlink" href="#subprocess.STARTUPINFO.hStdError" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#subprocess.STARTUPINFO.dwFlags" title="subprocess.STARTUPINFO.dwFlags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dwFlags</span></code></a> specifies <a class="reference internal" href="#subprocess.STARTF_USESTDHANDLES" title="subprocess.STARTF_USESTDHANDLES"><code class="xref py py-data docutils literal notranslate"><span class="pre">STARTF_USESTDHANDLES</span></code></a>, this attribute
is the standard error handle for the process. Otherwise, this attribute is
ignored and the default for standard error is the console window’s buffer.</p>
</dd></dl>

<dl class="attribute">
<dt id="subprocess.STARTUPINFO.wShowWindow">
<code class="descname">wShowWindow</code><a class="headerlink" href="#subprocess.STARTUPINFO.wShowWindow" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#subprocess.STARTUPINFO.dwFlags" title="subprocess.STARTUPINFO.dwFlags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">dwFlags</span></code></a> specifies <a class="reference internal" href="#subprocess.STARTF_USESHOWWINDOW" title="subprocess.STARTF_USESHOWWINDOW"><code class="xref py py-data docutils literal notranslate"><span class="pre">STARTF_USESHOWWINDOW</span></code></a>, this attribute
can be any of the values that can be specified in the <code class="docutils literal notranslate"><span class="pre">nCmdShow</span></code>
parameter for the
<a class="reference external" href="https://msdn.microsoft.com/en-us/library/ms633548(v=vs.85).aspx">ShowWindow</a>
function, except for <code class="docutils literal notranslate"><span class="pre">SW_SHOWDEFAULT</span></code>. Otherwise, this attribute is
ignored.</p>
<p><a class="reference internal" href="#subprocess.SW_HIDE" title="subprocess.SW_HIDE"><code class="xref py py-data docutils literal notranslate"><span class="pre">SW_HIDE</span></code></a> is provided for this attribute. It is used when
<a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> is called with <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>.</p>
</dd></dl>

</dd></dl>

<div class="section" id="constants">
<h3>17.1.3.1. Constants<a class="headerlink" href="#constants" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module exposes the following constants.</p>
<dl class="data">
<dt id="subprocess.STD_INPUT_HANDLE">
<code class="descclassname">subprocess.</code><code class="descname">STD_INPUT_HANDLE</code><a class="headerlink" href="#subprocess.STD_INPUT_HANDLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard input device. Initially, this is the console input buffer,
<code class="docutils literal notranslate"><span class="pre">CONIN$</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.STD_OUTPUT_HANDLE">
<code class="descclassname">subprocess.</code><code class="descname">STD_OUTPUT_HANDLE</code><a class="headerlink" href="#subprocess.STD_OUTPUT_HANDLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard output device. Initially, this is the active console screen
buffer, <code class="docutils literal notranslate"><span class="pre">CONOUT$</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.STD_ERROR_HANDLE">
<code class="descclassname">subprocess.</code><code class="descname">STD_ERROR_HANDLE</code><a class="headerlink" href="#subprocess.STD_ERROR_HANDLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard error device. Initially, this is the active console screen
buffer, <code class="docutils literal notranslate"><span class="pre">CONOUT$</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.SW_HIDE">
<code class="descclassname">subprocess.</code><code class="descname">SW_HIDE</code><a class="headerlink" href="#subprocess.SW_HIDE" title="Permalink to this definition">¶</a></dt>
<dd><p>Hides the window. Another window will be activated.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.STARTF_USESTDHANDLES">
<code class="descclassname">subprocess.</code><code class="descname">STARTF_USESTDHANDLES</code><a class="headerlink" href="#subprocess.STARTF_USESTDHANDLES" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies that the <a class="reference internal" href="#subprocess.STARTUPINFO.hStdInput" title="subprocess.STARTUPINFO.hStdInput"><code class="xref py py-attr docutils literal notranslate"><span class="pre">STARTUPINFO.hStdInput</span></code></a>,
<a class="reference internal" href="#subprocess.STARTUPINFO.hStdOutput" title="subprocess.STARTUPINFO.hStdOutput"><code class="xref py py-attr docutils literal notranslate"><span class="pre">STARTUPINFO.hStdOutput</span></code></a>, and <a class="reference internal" href="#subprocess.STARTUPINFO.hStdError" title="subprocess.STARTUPINFO.hStdError"><code class="xref py py-attr docutils literal notranslate"><span class="pre">STARTUPINFO.hStdError</span></code></a> attributes
contain additional information.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.STARTF_USESHOWWINDOW">
<code class="descclassname">subprocess.</code><code class="descname">STARTF_USESHOWWINDOW</code><a class="headerlink" href="#subprocess.STARTF_USESHOWWINDOW" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies that the <a class="reference internal" href="#subprocess.STARTUPINFO.wShowWindow" title="subprocess.STARTUPINFO.wShowWindow"><code class="xref py py-attr docutils literal notranslate"><span class="pre">STARTUPINFO.wShowWindow</span></code></a> attribute contains
additional information.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.CREATE_NEW_CONSOLE">
<code class="descclassname">subprocess.</code><code class="descname">CREATE_NEW_CONSOLE</code><a class="headerlink" href="#subprocess.CREATE_NEW_CONSOLE" title="Permalink to this definition">¶</a></dt>
<dd><p>The new process has a new console, instead of inheriting its parent’s
console (the default).</p>
<p>This flag is always set when <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> is created with <code class="docutils literal notranslate"><span class="pre">shell=True</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="subprocess.CREATE_NEW_PROCESS_GROUP">
<code class="descclassname">subprocess.</code><code class="descname">CREATE_NEW_PROCESS_GROUP</code><a class="headerlink" href="#subprocess.CREATE_NEW_PROCESS_GROUP" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> <code class="docutils literal notranslate"><span class="pre">creationflags</span></code> parameter to specify that a new process
group will be created. This flag is necessary for using <a class="reference internal" href="os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a>
on the subprocess.</p>
<p>This flag is ignored if <a class="reference internal" href="#subprocess.CREATE_NEW_CONSOLE" title="subprocess.CREATE_NEW_CONSOLE"><code class="xref py py-data docutils literal notranslate"><span class="pre">CREATE_NEW_CONSOLE</span></code></a> is specified.</p>
</dd></dl>

</div>
</div>
<div class="section" id="replacing-older-functions-with-the-subprocess-module">
<span id="subprocess-replacements"></span><h2>17.1.4. Replacing Older Functions with the <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> Module<a class="headerlink" href="#replacing-older-functions-with-the-subprocess-module" title="Permalink to this headline">¶</a></h2>
<p>In this section, “a becomes b” means that b can be used as a replacement for a.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>All “a” functions in this section fail (more or less) silently if the
executed program cannot be found; the “b” replacements raise <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a>
instead.</p>
<p class="last">In addition, the replacements using <a class="reference internal" href="#subprocess.check_output" title="subprocess.check_output"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_output()</span></code></a> will fail with a
<a class="reference internal" href="#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a> if the requested operation produces a non-zero
return code. The output is still available as the
<a class="reference internal" href="#subprocess.CalledProcessError.output" title="subprocess.CalledProcessError.output"><code class="xref py py-attr docutils literal notranslate"><span class="pre">output</span></code></a> attribute of the raised exception.</p>
</div>
<p>In the following examples, we assume that the relevant functions have already
been imported from the <a class="reference internal" href="#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.</p>
<div class="section" id="replacing-bin-sh-shell-backquote">
<h3>17.1.4.1. Replacing /bin/sh shell backquote<a class="headerlink" href="#replacing-bin-sh-shell-backquote" title="Permalink to this headline">¶</a></h3>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nv">output</span><span class="o">=</span><span class="sb">`</span>mycmd myarg<span class="sb">`</span>
</pre></div>
</div>
<p>becomes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">output</span> <span class="o">=</span> <span class="n">check_output</span><span class="p">([</span><span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="section" id="replacing-shell-pipeline">
<h3>17.1.4.2. Replacing shell pipeline<a class="headerlink" href="#replacing-shell-pipeline" title="Permalink to this headline">¶</a></h3>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nv">output</span><span class="o">=</span><span class="sb">`</span>dmesg <span class="p">|</span> grep hda<span class="sb">`</span>
</pre></div>
</div>
<p>becomes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p1</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;dmesg&quot;</span><span class="p">],</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span>
<span class="n">p2</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;grep&quot;</span><span class="p">,</span> <span class="s2">&quot;hda&quot;</span><span class="p">],</span> <span class="n">stdin</span><span class="o">=</span><span class="n">p1</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span>
<span class="n">p1</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>  <span class="c1"># Allow p1 to receive a SIGPIPE if p2 exits.</span>
<span class="n">output</span> <span class="o">=</span> <span class="n">p2</span><span class="o">.</span><span class="n">communicate</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
</pre></div>
</div>
<p>The p1.stdout.close() call after starting the p2 is important in order for p1
to receive a SIGPIPE if p2 exits before p1.</p>
<p>Alternatively, for trusted input, the shell’s own pipeline support may still
be used directly:</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="nv">output</span><span class="o">=</span><span class="sb">`</span>dmesg <span class="p">|</span> grep hda<span class="sb">`</span>
</pre></div>
</div>
<p>becomes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">output</span><span class="o">=</span><span class="n">check_output</span><span class="p">(</span><span class="s2">&quot;dmesg | grep hda&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="replacing-os-system">
<h3>17.1.4.3. Replacing <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a><a class="headerlink" href="#replacing-os-system" title="Permalink to this headline">¶</a></h3>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">status</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s2">&quot;mycmd&quot;</span> <span class="o">+</span> <span class="s2">&quot; myarg&quot;</span><span class="p">)</span>
<span class="c1"># becomes</span>
<span class="n">status</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s2">&quot;mycmd&quot;</span> <span class="o">+</span> <span class="s2">&quot; myarg&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>Notes:</p>
<ul class="simple">
<li>Calling the program through the shell is usually not required.</li>
</ul>
<p>A more realistic example would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">retcode</span> <span class="o">=</span> <span class="n">call</span><span class="p">(</span><span class="s2">&quot;mycmd&quot;</span> <span class="o">+</span> <span class="s2">&quot; myarg&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">retcode</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
        <span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">,</span> <span class="s2">&quot;Child was terminated by signal&quot;</span><span class="p">,</span> <span class="o">-</span><span class="n">retcode</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">,</span> <span class="s2">&quot;Child returned&quot;</span><span class="p">,</span> <span class="n">retcode</span>
<span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="nb">print</span> <span class="o">&gt;&gt;</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">,</span> <span class="s2">&quot;Execution failed:&quot;</span><span class="p">,</span> <span class="n">e</span>
</pre></div>
</div>
</div>
<div class="section" id="replacing-the-os-spawn-family">
<h3>17.1.4.4. Replacing the <a class="reference internal" href="os.html#os.spawnl" title="os.spawnl"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.spawn</span></code></a> family<a class="headerlink" href="#replacing-the-os-spawn-family" title="Permalink to this headline">¶</a></h3>
<p>P_NOWAIT example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pid</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">spawnlp</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_NOWAIT</span><span class="p">,</span> <span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">pid</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">])</span><span class="o">.</span><span class="n">pid</span>
</pre></div>
</div>
<p>P_WAIT example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">retcode</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">spawnlp</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_WAIT</span><span class="p">,</span> <span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">retcode</span> <span class="o">=</span> <span class="n">call</span><span class="p">([</span><span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>Vector example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">spawnvp</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_NOWAIT</span><span class="p">,</span> <span class="n">path</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">Popen</span><span class="p">([</span><span class="n">path</span><span class="p">]</span> <span class="o">+</span> <span class="n">args</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>
</pre></div>
</div>
<p>Environment example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">os</span><span class="o">.</span><span class="n">spawnlpe</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">P_NOWAIT</span><span class="p">,</span> <span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">,</span> <span class="n">env</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;/bin/mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">],</span> <span class="n">env</span><span class="o">=</span><span class="p">{</span><span class="s2">&quot;PATH&quot;</span><span class="p">:</span> <span class="s2">&quot;/usr/bin&quot;</span><span class="p">})</span>
</pre></div>
</div>
</div>
<div class="section" id="replacing-os-popen-os-popen2-os-popen3">
<h3>17.1.4.5. Replacing <a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="os.html#os.popen2" title="os.popen2"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen2()</span></code></a>, <a class="reference internal" href="os.html#os.popen3" title="os.popen3"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen3()</span></code></a><a class="headerlink" href="#replacing-os-popen-os-popen2-os-popen3" title="Permalink to this headline">¶</a></h3>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pipe</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">,</span> <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">pipe</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span><span class="o">.</span><span class="n">stdout</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pipe</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">pipe</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span> <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span><span class="o">.</span><span class="n">stdin</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout</span><span class="p">)</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen2</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span>
          <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span>
 <span class="n">child_stdout</span><span class="p">,</span>
 <span class="n">child_stderr</span><span class="p">)</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen3</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span> <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span>
          <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stderr</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span>
 <span class="n">child_stdout</span><span class="p">,</span>
 <span class="n">child_stderr</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stderr</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout_and_stderr</span><span class="p">)</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen4</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">mode</span><span class="p">,</span>
                                                   <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span>
          <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stderr</span><span class="o">=</span><span class="n">STDOUT</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout_and_stderr</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
</pre></div>
</div>
<p>On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
the command to execute, in which case arguments will be passed
directly to the program without shell intervention.  This usage can be
replaced as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout</span><span class="p">)</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen2</span><span class="p">([</span><span class="s2">&quot;/bin/ls&quot;</span><span class="p">,</span> <span class="s2">&quot;-l&quot;</span><span class="p">],</span> <span class="n">mode</span><span class="p">,</span>
                                        <span class="n">bufsize</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;/bin/ls&quot;</span><span class="p">,</span> <span class="s2">&quot;-l&quot;</span><span class="p">],</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span> <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdin</span><span class="p">,</span> <span class="n">child_stdout</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
</pre></div>
</div>
<p>Return code handling translates as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pipe</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">rc</span> <span class="o">=</span> <span class="n">pipe</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">if</span> <span class="n">rc</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span> <span class="ow">and</span> <span class="n">rc</span> <span class="o">&gt;&gt;</span> <span class="mi">8</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;There were some errors&quot;</span>
<span class="o">==&gt;</span>
<span class="n">process</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;cmd&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">process</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">if</span> <span class="n">process</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;There were some errors&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="replacing-functions-from-the-popen2-module">
<h3>17.1.4.6. Replacing functions from the <a class="reference internal" href="popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module<a class="headerlink" href="#replacing-functions-from-the-popen2-module" title="Permalink to this headline">¶</a></h3>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdout</span><span class="p">,</span> <span class="n">child_stdin</span><span class="p">)</span> <span class="o">=</span> <span class="n">popen2</span><span class="o">.</span><span class="n">popen2</span><span class="p">(</span><span class="s2">&quot;somestring&quot;</span><span class="p">,</span> <span class="n">bufsize</span><span class="p">,</span> <span class="n">mode</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">(</span><span class="s2">&quot;somestring&quot;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span>
          <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdout</span><span class="p">,</span> <span class="n">child_stdin</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">)</span>
</pre></div>
</div>
<p>On Unix, popen2 also accepts a sequence as the command to execute, in
which case arguments will be passed directly to the program without
shell intervention.  This usage can be replaced as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="n">child_stdout</span><span class="p">,</span> <span class="n">child_stdin</span><span class="p">)</span> <span class="o">=</span> <span class="n">popen2</span><span class="o">.</span><span class="n">popen2</span><span class="p">([</span><span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">],</span> <span class="n">bufsize</span><span class="p">,</span>
                                            <span class="n">mode</span><span class="p">)</span>
<span class="o">==&gt;</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Popen</span><span class="p">([</span><span class="s2">&quot;mycmd&quot;</span><span class="p">,</span> <span class="s2">&quot;myarg&quot;</span><span class="p">],</span> <span class="n">bufsize</span><span class="o">=</span><span class="n">bufsize</span><span class="p">,</span>
          <span class="n">stdin</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="n">PIPE</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="p">(</span><span class="n">child_stdout</span><span class="p">,</span> <span class="n">child_stdin</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">stdout</span><span class="p">,</span> <span class="n">p</span><span class="o">.</span><span class="n">stdin</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="popen2.html#popen2.Popen3" title="popen2.Popen3"><code class="xref py py-class docutils literal notranslate"><span class="pre">popen2.Popen3</span></code></a> and <a class="reference internal" href="popen2.html#popen2.Popen4" title="popen2.Popen4"><code class="xref py py-class docutils literal notranslate"><span class="pre">popen2.Popen4</span></code></a> basically work as
<a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">subprocess.Popen</span></code></a>, except that:</p>
<ul class="simple">
<li><a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a> raises an exception if the execution fails.</li>
<li>the <em>capturestderr</em> argument is replaced with the <em>stderr</em> argument.</li>
<li><code class="docutils literal notranslate"><span class="pre">stdin=PIPE</span></code> and <code class="docutils literal notranslate"><span class="pre">stdout=PIPE</span></code> must be specified.</li>
<li>popen2 closes all file descriptors by default, but you have to specify
<code class="docutils literal notranslate"><span class="pre">close_fds=True</span></code> with <a class="reference internal" href="#subprocess.Popen" title="subprocess.Popen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code></a>.</li>
</ul>
</div>
</div>
<div class="section" id="notes">
<h2>17.1.5. Notes<a class="headerlink" href="#notes" title="Permalink to this headline">¶</a></h2>
<div class="section" id="converting-an-argument-sequence-to-a-string-on-windows">
<span id="converting-argument-sequence"></span><h3>17.1.5.1. Converting an argument sequence to a string on Windows<a class="headerlink" href="#converting-an-argument-sequence-to-a-string-on-windows" title="Permalink to this headline">¶</a></h3>
<p>On Windows, an <em>args</em> sequence is converted to a string that can be parsed
using the following rules (which correspond to the rules used by the MS C
runtime):</p>
<ol class="arabic simple">
<li>Arguments are delimited by white space, which is either a
space or a tab.</li>
<li>A string surrounded by double quotation marks is
interpreted as a single argument, regardless of white space
contained within.  A quoted string can be embedded in an
argument.</li>
<li>A double quotation mark preceded by a backslash is
interpreted as a literal double quotation mark.</li>
<li>Backslashes are interpreted literally, unless they
immediately precede a double quotation mark.</li>
<li>If backslashes immediately precede a double quotation mark,
every pair of backslashes is interpreted as a literal
backslash.  If the number of backslashes is odd, the last
backslash escapes the next double quotation mark as
described in rule 3.</li>
</ol>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a><ul>
<li><a class="reference internal" href="#using-the-subprocess-module">17.1.1. Using the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li><a class="reference internal" href="#frequently-used-arguments">17.1.1.1. Frequently Used Arguments</a></li>
<li><a class="reference internal" href="#popen-constructor">17.1.1.2. Popen Constructor</a></li>
<li><a class="reference internal" href="#exceptions">17.1.1.3. Exceptions</a></li>
<li><a class="reference internal" href="#security">17.1.1.4. Security</a></li>
</ul>
</li>
<li><a class="reference internal" href="#popen-objects">17.1.2. Popen Objects</a></li>
<li><a class="reference internal" href="#windows-popen-helpers">17.1.3. Windows Popen Helpers</a><ul>
<li><a class="reference internal" href="#constants">17.1.3.1. Constants</a></li>
</ul>
</li>
<li><a class="reference internal" href="#replacing-older-functions-with-the-subprocess-module">17.1.4. Replacing Older Functions with the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li><a class="reference internal" href="#replacing-bin-sh-shell-backquote">17.1.4.1. Replacing /bin/sh shell backquote</a></li>
<li><a class="reference internal" href="#replacing-shell-pipeline">17.1.4.2. Replacing shell pipeline</a></li>
<li><a class="reference internal" href="#replacing-os-system">17.1.4.3. Replacing <code class="docutils literal notranslate"><span class="pre">os.system()</span></code></a></li>
<li><a class="reference internal" href="#replacing-the-os-spawn-family">17.1.4.4. Replacing the <code class="docutils literal notranslate"><span class="pre">os.spawn</span></code> family</a></li>
<li><a class="reference internal" href="#replacing-os-popen-os-popen2-os-popen3">17.1.4.5. Replacing <code class="docutils literal notranslate"><span class="pre">os.popen()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen2()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen3()</span></code></a></li>
<li><a class="reference internal" href="#replacing-functions-from-the-popen2-module">17.1.4.6. Replacing functions from the <code class="docutils literal notranslate"><span class="pre">popen2</span></code> module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#notes">17.1.5. Notes</a><ul>
<li><a class="reference internal" href="#converting-an-argument-sequence-to-a-string-on-windows">17.1.5.1. Converting an argument sequence to a string on Windows</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="ipc.html"
                        title="previous chapter">17. Interprocess Communication and Networking</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="socket.html"
                        title="next chapter">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/subprocess.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="socket.html" title="17.2. socket — Low-level networking interface"
             >next</a> |</li>
        <li class="right" >
          <a href="ipc.html" title="17. Interprocess Communication and Networking"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" >17. Interprocess Communication and Networking</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\:l�UUhtml/library/sun.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>40. SunOS Specific Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="40.1. sunaudiodev — Access to Sun audio hardware" href="sunaudio.html" />
    <link rel="prev" title="39.12. jpeg — Read and write JPEG files" href="jpeg.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sun.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sunaudio.html" title="40.1. sunaudiodev — Access to Sun audio hardware"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="jpeg.html" title="39.12. jpeg — Read and write JPEG files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="sunos-specific-services">
<span id="sunos"></span><h1>40. SunOS Specific Services<a class="headerlink" href="#sunos-specific-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide interfaces to features that are
unique to SunOS 5 (also known as Solaris version 2).</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="sunaudio.html">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a><ul>
<li class="toctree-l2"><a class="reference internal" href="sunaudio.html#audio-device-objects">40.1.1. Audio Device Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="sunaudio.html#module-SUNAUDIODEV">40.2. <code class="docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="jpeg.html"
                        title="previous chapter">39.12. <code class="docutils literal notranslate"><span class="pre">jpeg</span></code> — Read and write JPEG files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sunaudio.html"
                        title="next chapter">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sun.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sunaudio.html" title="40.1. sunaudiodev — Access to Sun audio hardware"
             >next</a> |</li>
        <li class="right" >
          <a href="jpeg.html" title="39.12. jpeg — Read and write JPEG files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\g�ih;u;uhtml/library/sunau.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.4. sunau — Read and write Sun AU files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.5. wave — Read and write WAV files" href="wave.html" />
    <link rel="prev" title="21.3. aifc — Read and write AIFF and AIFC files" href="aifc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sunau.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="wave.html" title="21.5. wave — Read and write WAV files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="aifc.html" title="21.3. aifc — Read and write AIFF and AIFC files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sunau">
<span id="sunau-read-and-write-sun-au-files"></span><h1>21.4. <a class="reference internal" href="#module-sunau" title="sunau: Provide an interface to the Sun AU sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunau</span></code></a> — Read and write Sun AU files<a class="headerlink" href="#module-sunau" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/sunau.py">Lib/sunau.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-sunau" title="sunau: Provide an interface to the Sun AU sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunau</span></code></a> module provides a convenient interface to the Sun AU sound
format.  Note that this module is interface-compatible with the modules
<a class="reference internal" href="aifc.html#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a> and <a class="reference internal" href="wave.html#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a>.</p>
<p>An audio file consists of a header followed by the data.  The fields of the
header are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="76%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">Contents</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>magic word</td>
<td>The four bytes <code class="docutils literal notranslate"><span class="pre">.snd</span></code>.</td>
</tr>
<tr class="row-odd"><td>header size</td>
<td>Size of the header, including info, in bytes.</td>
</tr>
<tr class="row-even"><td>data size</td>
<td>Physical size of the data, in bytes.</td>
</tr>
<tr class="row-odd"><td>encoding</td>
<td>Indicates how the audio samples are encoded.</td>
</tr>
<tr class="row-even"><td>sample rate</td>
<td>The sampling rate.</td>
</tr>
<tr class="row-odd"><td># of channels</td>
<td>The number of channels in the samples.</td>
</tr>
<tr class="row-even"><td>info</td>
<td>ASCII string giving a description of the
audio file (padded with null bytes).</td>
</tr>
</tbody>
</table>
<p>Apart from the info field, all header fields are 4 bytes in size. They are all
32-bit unsigned integers encoded in big-endian byte order.</p>
<p>The <a class="reference internal" href="#module-sunau" title="sunau: Provide an interface to the Sun AU sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunau</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="sunau.open">
<code class="descclassname">sunau.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.open" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>file</em> is a string, open the file by that name, otherwise treat it as a
seekable file-like object. <em>mode</em> can be any of</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">'r'</span></code></dt>
<dd>Read only mode.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'w'</span></code></dt>
<dd>Write only mode.</dd>
</dl>
<p>Note that it does not allow read/write files.</p>
<p>A <em>mode</em> of <code class="docutils literal notranslate"><span class="pre">'r'</span></code> returns an <code class="xref py py-class docutils literal notranslate"><span class="pre">AU_read</span></code> object, while a <em>mode</em> of <code class="docutils literal notranslate"><span class="pre">'w'</span></code>
or <code class="docutils literal notranslate"><span class="pre">'wb'</span></code> returns an <code class="xref py py-class docutils literal notranslate"><span class="pre">AU_write</span></code> object.</p>
</dd></dl>

<dl class="function">
<dt id="sunau.openfp">
<code class="descclassname">sunau.</code><code class="descname">openfp</code><span class="sig-paren">(</span><em>file</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.openfp" title="Permalink to this definition">¶</a></dt>
<dd><p>A synonym for <a class="reference internal" href="#sunau.open" title="sunau.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, maintained for backwards compatibility.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-sunau" title="sunau: Provide an interface to the Sun AU sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunau</span></code></a> module defines the following exception:</p>
<dl class="exception">
<dt id="sunau.Error">
<em class="property">exception </em><code class="descclassname">sunau.</code><code class="descname">Error</code><a class="headerlink" href="#sunau.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>An error raised when something is impossible because of Sun AU specs or
implementation deficiency.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-sunau" title="sunau: Provide an interface to the Sun AU sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunau</span></code></a> module defines the following data items:</p>
<dl class="data">
<dt id="sunau.AUDIO_FILE_MAGIC">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_MAGIC</code><a class="headerlink" href="#sunau.AUDIO_FILE_MAGIC" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer every valid Sun AU file begins with, stored in big-endian form.  This
is the string <code class="docutils literal notranslate"><span class="pre">.snd</span></code> interpreted as an integer.</p>
</dd></dl>

<dl class="data">
<dt id="sunau.AUDIO_FILE_ENCODING_MULAW_8">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_MULAW_8</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_MULAW_8" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_LINEAR_8">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_LINEAR_8</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_LINEAR_8" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_LINEAR_16">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_LINEAR_16</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_LINEAR_16" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_LINEAR_24">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_LINEAR_24</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_LINEAR_24" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_LINEAR_32">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_LINEAR_32</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_LINEAR_32" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_ALAW_8">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_ALAW_8</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_ALAW_8" title="Permalink to this definition">¶</a></dt>
<dd><p>Values of the encoding field from the AU header which are supported by this
module.</p>
</dd></dl>

<dl class="data">
<dt id="sunau.AUDIO_FILE_ENCODING_FLOAT">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_FLOAT</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_FLOAT" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_DOUBLE">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_DOUBLE</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_DOUBLE" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_ADPCM_G721">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_ADPCM_G721</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_ADPCM_G721" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_ADPCM_G722">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_ADPCM_G722</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_ADPCM_G722" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_ADPCM_G723_3</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3" title="Permalink to this definition">¶</a></dt>
<dt id="sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5">
<code class="descclassname">sunau.</code><code class="descname">AUDIO_FILE_ENCODING_ADPCM_G723_5</code><a class="headerlink" href="#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5" title="Permalink to this definition">¶</a></dt>
<dd><p>Additional known values of the encoding field from the AU header, but which are
not supported by this module.</p>
</dd></dl>

<div class="section" id="au-read-objects">
<span id="id1"></span><h2>21.4.1. AU_read Objects<a class="headerlink" href="#au-read-objects" title="Permalink to this headline">¶</a></h2>
<p>AU_read objects, as returned by <a class="reference internal" href="#sunau.open" title="sunau.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> above, have the following methods:</p>
<dl class="method">
<dt id="sunau.AU_read.close">
<code class="descclassname">AU_read.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the stream, and make the instance unusable. (This is  called automatically
on deletion.)</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getnchannels">
<code class="descclassname">AU_read.</code><code class="descname">getnchannels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns number of audio channels (1 for mono, 2 for stereo).</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getsampwidth">
<code class="descclassname">AU_read.</code><code class="descname">getsampwidth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns sample width in bytes.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getframerate">
<code class="descclassname">AU_read.</code><code class="descname">getframerate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns sampling frequency.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getnframes">
<code class="descclassname">AU_read.</code><code class="descname">getnframes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns number of audio frames.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getcomptype">
<code class="descclassname">AU_read.</code><code class="descname">getcomptype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns compression type. Supported compression types are <code class="docutils literal notranslate"><span class="pre">'ULAW'</span></code>, <code class="docutils literal notranslate"><span class="pre">'ALAW'</span></code>
and <code class="docutils literal notranslate"><span class="pre">'NONE'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getcompname">
<code class="descclassname">AU_read.</code><code class="descname">getcompname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getcompname" title="Permalink to this definition">¶</a></dt>
<dd><p>Human-readable version of <a class="reference internal" href="#sunau.AU_read.getcomptype" title="sunau.AU_read.getcomptype"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getcomptype()</span></code></a>.  The supported types have the
respective names <code class="docutils literal notranslate"><span class="pre">'CCITT</span> <span class="pre">G.711</span> <span class="pre">u-law'</span></code>, <code class="docutils literal notranslate"><span class="pre">'CCITT</span> <span class="pre">G.711</span> <span class="pre">A-law'</span></code> and <code class="docutils literal notranslate"><span class="pre">'not</span>
<span class="pre">compressed'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getparams">
<code class="descclassname">AU_read.</code><code class="descname">getparams</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getparams" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(nchannels,</span> <span class="pre">sampwidth,</span> <span class="pre">framerate,</span> <span class="pre">nframes,</span> <span class="pre">comptype,</span>
<span class="pre">compname)</span></code>, equivalent to output of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">get*()</span></code> methods.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.readframes">
<code class="descclassname">AU_read.</code><code class="descname">readframes</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.readframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads and returns at most <em>n</em> frames of audio, as a string of bytes.  The data
will be returned in linear format.  If the original data is in u-LAW format, it
will be converted.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.rewind">
<code class="descclassname">AU_read.</code><code class="descname">rewind</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.rewind" title="Permalink to this definition">¶</a></dt>
<dd><p>Rewind the file pointer to the beginning of the audio stream.</p>
</dd></dl>

<p>The following two methods define a term “position” which is compatible between
them, and is otherwise implementation dependent.</p>
<dl class="method">
<dt id="sunau.AU_read.setpos">
<code class="descclassname">AU_read.</code><code class="descname">setpos</code><span class="sig-paren">(</span><em>pos</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.setpos" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file pointer to the specified position.  Only values returned from
<a class="reference internal" href="#sunau.AU_read.tell" title="sunau.AU_read.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code></a> should be used for <em>pos</em>.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.tell">
<code class="descclassname">AU_read.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current file pointer position.  Note that the returned value has nothing
to do with the actual position in the file.</p>
</dd></dl>

<p>The following two functions are defined for compatibility with the  <a class="reference internal" href="aifc.html#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a>,
and don’t do anything interesting.</p>
<dl class="method">
<dt id="sunau.AU_read.getmarkers">
<code class="descclassname">AU_read.</code><code class="descname">getmarkers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getmarkers" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_read.getmark">
<code class="descclassname">AU_read.</code><code class="descname">getmark</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_read.getmark" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise an error.</p>
</dd></dl>

</div>
<div class="section" id="au-write-objects">
<span id="id2"></span><h2>21.4.2. AU_write Objects<a class="headerlink" href="#au-write-objects" title="Permalink to this headline">¶</a></h2>
<p>AU_write objects, as returned by <a class="reference internal" href="#sunau.open" title="sunau.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> above, have the following methods:</p>
<dl class="method">
<dt id="sunau.AU_write.setnchannels">
<code class="descclassname">AU_write.</code><code class="descname">setnchannels</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the number of channels.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.setsampwidth">
<code class="descclassname">AU_write.</code><code class="descname">setsampwidth</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the sample width (in bytes.)</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.setframerate">
<code class="descclassname">AU_write.</code><code class="descname">setframerate</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the frame rate.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.setnframes">
<code class="descclassname">AU_write.</code><code class="descname">setnframes</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the number of frames. This can be later changed, when and if more  frames
are written.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.setcomptype">
<code class="descclassname">AU_write.</code><code class="descname">setcomptype</code><span class="sig-paren">(</span><em>type</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the compression type and description. Only <code class="docutils literal notranslate"><span class="pre">'NONE'</span></code> and <code class="docutils literal notranslate"><span class="pre">'ULAW'</span></code> are
supported on output.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.setparams">
<code class="descclassname">AU_write.</code><code class="descname">setparams</code><span class="sig-paren">(</span><em>tuple</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.setparams" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>tuple</em> should be <code class="docutils literal notranslate"><span class="pre">(nchannels,</span> <span class="pre">sampwidth,</span> <span class="pre">framerate,</span> <span class="pre">nframes,</span> <span class="pre">comptype,</span>
<span class="pre">compname)</span></code>, with values valid for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">set*()</span></code> methods.  Set all
parameters.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.tell">
<code class="descclassname">AU_write.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current position in the file, with the same disclaimer for the
<a class="reference internal" href="#sunau.AU_read.tell" title="sunau.AU_read.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AU_read.tell()</span></code></a> and <a class="reference internal" href="#sunau.AU_read.setpos" title="sunau.AU_read.setpos"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AU_read.setpos()</span></code></a> methods.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.writeframesraw">
<code class="descclassname">AU_write.</code><code class="descname">writeframesraw</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.writeframesraw" title="Permalink to this definition">¶</a></dt>
<dd><p>Write audio frames, without correcting <em>nframes</em>.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.writeframes">
<code class="descclassname">AU_write.</code><code class="descname">writeframes</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.writeframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Write audio frames and make sure <em>nframes</em> is correct.</p>
</dd></dl>

<dl class="method">
<dt id="sunau.AU_write.close">
<code class="descclassname">AU_write.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sunau.AU_write.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Make sure <em>nframes</em> is correct, and close the file.</p>
<p>This method is called upon deletion.</p>
</dd></dl>

<p>Note that it is invalid to set any parameters after calling  <code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframes()</span></code>
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframesraw()</span></code>.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a><ul>
<li><a class="reference internal" href="#au-read-objects">21.4.1. AU_read Objects</a></li>
<li><a class="reference internal" href="#au-write-objects">21.4.2. AU_write Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="aifc.html"
                        title="previous chapter">21.3. <code class="docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="wave.html"
                        title="next chapter">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sunau.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="wave.html" title="21.5. wave — Read and write WAV files"
             >next</a> |</li>
        <li class="right" >
          <a href="aifc.html" title="21.3. aifc — Read and write AIFF and AIFC files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�s�g$K$Khtml/library/sunaudio.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>40.1. sunaudiodev — Access to Sun audio hardware &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="41. Undocumented Modules" href="undoc.html" />
    <link rel="prev" title="40. SunOS Specific Services" href="sun.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sunaudio.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="undoc.html" title="41. Undocumented Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sun.html" title="40. SunOS Specific Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sun.html" accesskey="U">40. SunOS Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sunaudiodev">
<span id="sunaudiodev-access-to-sun-audio-hardware"></span><h1>40.1. <a class="reference internal" href="#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a> — Access to Sun audio hardware<a class="headerlink" href="#module-sunaudiodev" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">This module allows you to access the Sun audio interface. The Sun audio hardware
is capable of recording and playing back audio data in u-LAW format with a
sample rate of 8K per second. A full description can be found in the
<em class="manpage">audio(7I)</em> manual page.</p>
<p id="index-1">The module <a class="reference internal" href="#module-SUNAUDIODEV" title="SUNAUDIODEV: Constants for use with sunaudiodev. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code></a>  defines constants which may be used with this
module.</p>
<p>This module defines the following variables and functions:</p>
<dl class="exception">
<dt id="sunaudiodev.error">
<em class="property">exception </em><code class="descclassname">sunaudiodev.</code><code class="descname">error</code><a class="headerlink" href="#sunaudiodev.error" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised on all errors. The argument is a string describing what
went wrong.</p>
</dd></dl>

<dl class="function">
<dt id="sunaudiodev.open">
<code class="descclassname">sunaudiodev.</code><code class="descname">open</code><span class="sig-paren">(</span><em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#sunaudiodev.open" title="Permalink to this definition">¶</a></dt>
<dd><p>This function opens the audio device and returns a Sun audio device object. This
object can then be used to do I/O on. The <em>mode</em> parameter is one of <code class="docutils literal notranslate"><span class="pre">'r'</span></code> for
record-only access, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> for play-only access, <code class="docutils literal notranslate"><span class="pre">'rw'</span></code> for both and
<code class="docutils literal notranslate"><span class="pre">'control'</span></code> for access to the control device. Since only one process is
allowed to have the recorder or player open at the same time it is a good idea
to open the device only for the activity needed. See <em class="manpage">audio(7I)</em> for
details.</p>
<p>As per the manpage, this module first looks in the environment variable
<code class="docutils literal notranslate"><span class="pre">AUDIODEV</span></code> for the base audio device filename.  If not found, it falls back to
<code class="file docutils literal notranslate"><span class="pre">/dev/audio</span></code>.  The control device is calculated by appending “ctl” to the
base audio device.</p>
</dd></dl>

<div class="section" id="audio-device-objects">
<span id="id1"></span><h2>40.1.1. Audio Device Objects<a class="headerlink" href="#audio-device-objects" title="Permalink to this headline">¶</a></h2>
<p>The audio device objects are returned by <a class="reference internal" href="#sunaudiodev.open" title="sunaudiodev.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> define the following
methods (except <code class="docutils literal notranslate"><span class="pre">control</span></code> objects which only provide <code class="xref py py-meth docutils literal notranslate"><span class="pre">getinfo()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">setinfo()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">drain()</span></code>):</p>
<dl class="method">
<dt>
<code class="descname">audio device.close()</code></dt>
<dd><p>This method explicitly closes the device. It is useful in situations where
deleting the object does not immediately close it since there are other
references to it. A closed device should not be used again.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.fileno()</code></dt>
<dd><p>Returns the file descriptor associated with the device.  This can be used to set
up <code class="docutils literal notranslate"><span class="pre">SIGPOLL</span></code> notification, as described below.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.drain()</code></dt>
<dd><p>This method waits until all pending output is processed and then returns.
Calling this method is often not necessary: destroying the object will
automatically close the audio device and this will do an implicit drain.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.flush()</code></dt>
<dd><p>This method discards all pending output. It can be used avoid the slow response
to a user’s stop request (due to buffering of up to one second of sound).</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.getinfo()</code></dt>
<dd><p>This method retrieves status information like input and output volume, etc. and
returns it in the form of an audio status object. This object has no methods but
it contains a number of attributes describing the current device status. The
names and meanings of the attributes are described in <code class="docutils literal notranslate"><span class="pre">&lt;sun/audioio.h&gt;</span></code> and in
the <em class="manpage">audio(7I)</em> manual page.  Member names are slightly different from
their C counterparts: a status object is only a single structure. Members of the
<code class="xref c c-data docutils literal notranslate"><span class="pre">play</span></code> substructure have <code class="docutils literal notranslate"><span class="pre">o_</span></code> prepended to their name and members of
the <code class="xref c c-data docutils literal notranslate"><span class="pre">record</span></code> structure have <code class="docutils literal notranslate"><span class="pre">i_</span></code>. So, the C member
<code class="xref c c-data docutils literal notranslate"><span class="pre">play.sample_rate</span></code> is accessed as <code class="xref py py-attr docutils literal notranslate"><span class="pre">o_sample_rate</span></code>,
<code class="xref c c-data docutils literal notranslate"><span class="pre">record.gain</span></code> as <code class="xref py py-attr docutils literal notranslate"><span class="pre">i_gain</span></code> and <code class="xref c c-data docutils literal notranslate"><span class="pre">monitor_gain</span></code> plainly as
<code class="xref py py-attr docutils literal notranslate"><span class="pre">monitor_gain</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.ibufcount()</code></dt>
<dd><p>This method returns the number of samples that are buffered on the recording
side, i.e. the program will not block on a <code class="xref py py-func docutils literal notranslate"><span class="pre">read()</span></code> call of so many samples.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.obufcount()</code></dt>
<dd><p>This method returns the number of samples buffered on the playback side.
Unfortunately, this number cannot be used to determine a number of samples that
can be written without blocking since the kernel output queue length seems to be
variable.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.read(size)</code></dt>
<dd><p>This method reads <em>size</em> samples from the audio input and returns them as a
Python string. The function blocks until enough data is available.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.setinfo(status)</code></dt>
<dd><p>This method sets the audio device status parameters. The <em>status</em> parameter is
a device status object as returned by <code class="xref py py-func docutils literal notranslate"><span class="pre">getinfo()</span></code> and possibly modified by
the program.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descname">audio device.write(samples)</code></dt>
<dd><p>Write is passed a Python string containing audio samples to be played. If there
is enough buffer space free it will immediately return, otherwise it will block.</p>
</dd></dl>

<p>The audio device supports asynchronous notification of various events, through
the SIGPOLL signal.  Here’s an example of how you might enable this in Python:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">handle_sigpoll</span><span class="p">(</span><span class="n">signum</span><span class="p">,</span> <span class="n">frame</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s1">&#39;I got a SIGPOLL update&#39;</span>

<span class="kn">import</span> <span class="nn">fcntl</span><span class="o">,</span> <span class="nn">signal</span><span class="o">,</span> <span class="nn">STROPTS</span>

<span class="n">signal</span><span class="o">.</span><span class="n">signal</span><span class="p">(</span><span class="n">signal</span><span class="o">.</span><span class="n">SIGPOLL</span><span class="p">,</span> <span class="n">handle_sigpoll</span><span class="p">)</span>
<span class="n">fcntl</span><span class="o">.</span><span class="n">ioctl</span><span class="p">(</span><span class="n">audio_obj</span><span class="o">.</span><span class="n">fileno</span><span class="p">(),</span> <span class="n">STROPTS</span><span class="o">.</span><span class="n">I_SETSIG</span><span class="p">,</span> <span class="n">STROPTS</span><span class="o">.</span><span class="n">S_MSG</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="module-SUNAUDIODEV">
<span id="sunaudiodev-constants-used-with-sunaudiodev"></span><h1>40.2. <a class="reference internal" href="#module-SUNAUDIODEV" title="SUNAUDIODEV: Constants for use with sunaudiodev. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code></a> — Constants used with <a class="reference internal" href="#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a><a class="headerlink" href="#module-SUNAUDIODEV" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-SUNAUDIODEV" title="SUNAUDIODEV: Constants for use with sunaudiodev. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-2">This is a companion module to <a class="reference internal" href="#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a> which defines useful symbolic
constants like <code class="xref py py-const docutils literal notranslate"><span class="pre">MIN_GAIN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">MAX_GAIN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SPEAKER</span></code>, etc. The
names of the constants are the same names as used in the C include file
<code class="docutils literal notranslate"><span class="pre">&lt;sun/audioio.h&gt;</span></code>, with the leading string <code class="docutils literal notranslate"><span class="pre">AUDIO_</span></code> stripped.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a><ul>
<li><a class="reference internal" href="#audio-device-objects">40.1.1. Audio Device Objects</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-SUNAUDIODEV">40.2. <code class="docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sun.html"
                        title="previous chapter">40. SunOS Specific Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="undoc.html"
                        title="next chapter">41. Undocumented Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sunaudio.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="undoc.html" title="41. Undocumented Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="sun.html" title="40. SunOS Specific Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="sun.html" >40. SunOS Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�&����html/library/symbol.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.4. symbol — Constants used with Python parse trees &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.5. token — Constants used with Python parse trees" href="token.html" />
    <link rel="prev" title="32.3. symtable — Access to the compiler’s symbol tables" href="symtable.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/symbol.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="token.html" title="32.5. token — Constants used with Python parse trees"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="symtable.html" title="32.3. symtable — Access to the compiler’s symbol tables"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-symbol">
<span id="symbol-constants-used-with-python-parse-trees"></span><h1>32.4. <a class="reference internal" href="#module-symbol" title="symbol: Constants representing internal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symbol</span></code></a> — Constants used with Python parse trees<a class="headerlink" href="#module-symbol" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/symbol.py">Lib/symbol.py</a></p>
<hr class="docutils" />
<p>This module provides constants which represent the numeric values of internal
nodes of the parse tree.  Unlike most Python constants, these use lower-case
names.  Refer to the file <code class="file docutils literal notranslate"><span class="pre">Grammar/Grammar</span></code> in the Python distribution for
the definitions of the names in the context of the language grammar.  The
specific numeric values which the names map to may change between Python
versions.</p>
<p>This module also provides one additional data object:</p>
<dl class="data">
<dt id="symbol.sym_name">
<code class="descclassname">symbol.</code><code class="descname">sym_name</code><a class="headerlink" href="#symbol.sym_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping the numeric values of the constants defined in this module
back to name strings, allowing more human-readable representation of parse trees
to be generated.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="symtable.html"
                        title="previous chapter">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="token.html"
                        title="next chapter">32.5. <code class="docutils literal notranslate"><span class="pre">token</span></code> — Constants used with Python parse trees</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/symbol.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="token.html" title="32.5. token — Constants used with Python parse trees"
             >next</a> |</li>
        <li class="right" >
          <a href="symtable.html" title="32.3. symtable — Access to the compiler’s symbol tables"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\0i�eehtml/library/symtable.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.3. symtable — Access to the compiler’s symbol tables &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.4. symbol — Constants used with Python parse trees" href="symbol.html" />
    <link rel="prev" title="32.2. ast — Abstract Syntax Trees" href="ast.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/symtable.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="symbol.html" title="32.4. symbol — Constants used with Python parse trees"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ast.html" title="32.2. ast — Abstract Syntax Trees"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-symtable">
<span id="symtable-access-to-the-compiler-s-symbol-tables"></span><h1>32.3. <a class="reference internal" href="#module-symtable" title="symtable: Interface to the compiler's internal symbol tables."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symtable</span></code></a> — Access to the compiler’s symbol tables<a class="headerlink" href="#module-symtable" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/symtable.py">Lib/symtable.py</a></p>
<hr class="docutils" />
<p>Symbol tables are generated by the compiler from AST just before bytecode is
generated.  The symbol table is responsible for calculating the scope of every
identifier in the code.  <a class="reference internal" href="#module-symtable" title="symtable: Interface to the compiler's internal symbol tables."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symtable</span></code></a> provides an interface to examine these
tables.</p>
<div class="section" id="generating-symbol-tables">
<h2>32.3.1. Generating Symbol Tables<a class="headerlink" href="#generating-symbol-tables" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="symtable.symtable">
<code class="descclassname">symtable.</code><code class="descname">symtable</code><span class="sig-paren">(</span><em>code</em>, <em>filename</em>, <em>compile_type</em><span class="sig-paren">)</span><a class="headerlink" href="#symtable.symtable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the toplevel <a class="reference internal" href="#symtable.SymbolTable" title="symtable.SymbolTable"><code class="xref py py-class docutils literal notranslate"><span class="pre">SymbolTable</span></code></a> for the Python source <em>code</em>.
<em>filename</em> is the name of the file containing the code.  <em>compile_type</em> is
like the <em>mode</em> argument to <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="examining-symbol-tables">
<h2>32.3.2. Examining Symbol Tables<a class="headerlink" href="#examining-symbol-tables" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="symtable.SymbolTable">
<em class="property">class </em><code class="descclassname">symtable.</code><code class="descname">SymbolTable</code><a class="headerlink" href="#symtable.SymbolTable" title="Permalink to this definition">¶</a></dt>
<dd><p>A namespace table for a block.  The constructor is not public.</p>
<dl class="method">
<dt id="symtable.SymbolTable.get_type">
<code class="descname">get_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the type of the symbol table.  Possible values are <code class="docutils literal notranslate"><span class="pre">'class'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'module'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'function'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_id">
<code class="descname">get_id</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_id" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the table’s identifier.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_name">
<code class="descname">get_name</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the table’s name.  This is the name of the class if the table is
for a class, the name of the function if the table is for a function, or
<code class="docutils literal notranslate"><span class="pre">'top'</span></code> if the table is global (<a class="reference internal" href="#symtable.SymbolTable.get_type" title="symtable.SymbolTable.get_type"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_type()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">'module'</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_lineno">
<code class="descname">get_lineno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of the first line in the block this table represents.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.is_optimized">
<code class="descname">is_optimized</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.is_optimized" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the locals in this table can be optimized.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.is_nested">
<code class="descname">is_nested</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.is_nested" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the block is a nested class or function.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.has_children">
<code class="descname">has_children</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.has_children" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the block has nested namespaces within it.  These can
be obtained with <a class="reference internal" href="#symtable.SymbolTable.get_children" title="symtable.SymbolTable.get_children"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_children()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.has_exec">
<code class="descname">has_exec</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.has_exec" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the block uses <code class="docutils literal notranslate"><span class="pre">exec</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.has_import_star">
<code class="descname">has_import_star</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.has_import_star" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the block uses a starred from-import.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_identifiers">
<code class="descname">get_identifiers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_identifiers" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of names of symbols in this table.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.lookup">
<code class="descname">lookup</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.lookup" title="Permalink to this definition">¶</a></dt>
<dd><p>Lookup <em>name</em> in the table and return a <a class="reference internal" href="#symtable.Symbol" title="symtable.Symbol"><code class="xref py py-class docutils literal notranslate"><span class="pre">Symbol</span></code></a> instance.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_symbols">
<code class="descname">get_symbols</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_symbols" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of <a class="reference internal" href="#symtable.Symbol" title="symtable.Symbol"><code class="xref py py-class docutils literal notranslate"><span class="pre">Symbol</span></code></a> instances for names in the table.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.SymbolTable.get_children">
<code class="descname">get_children</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.SymbolTable.get_children" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of the nested symbol tables.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="symtable.Function">
<em class="property">class </em><code class="descclassname">symtable.</code><code class="descname">Function</code><a class="headerlink" href="#symtable.Function" title="Permalink to this definition">¶</a></dt>
<dd><p>A namespace for a function or method.  This class inherits
<a class="reference internal" href="#symtable.SymbolTable" title="symtable.SymbolTable"><code class="xref py py-class docutils literal notranslate"><span class="pre">SymbolTable</span></code></a>.</p>
<dl class="method">
<dt id="symtable.Function.get_parameters">
<code class="descname">get_parameters</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Function.get_parameters" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing names of parameters to this function.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Function.get_locals">
<code class="descname">get_locals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Function.get_locals" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing names of locals in this function.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Function.get_globals">
<code class="descname">get_globals</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Function.get_globals" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing names of globals in this function.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Function.get_frees">
<code class="descname">get_frees</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Function.get_frees" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing names of free variables in this function.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="symtable.Class">
<em class="property">class </em><code class="descclassname">symtable.</code><code class="descname">Class</code><a class="headerlink" href="#symtable.Class" title="Permalink to this definition">¶</a></dt>
<dd><p>A namespace of a class.  This class inherits <a class="reference internal" href="#symtable.SymbolTable" title="symtable.SymbolTable"><code class="xref py py-class docutils literal notranslate"><span class="pre">SymbolTable</span></code></a>.</p>
<dl class="method">
<dt id="symtable.Class.get_methods">
<code class="descname">get_methods</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Class.get_methods" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing the names of methods declared in the class.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="symtable.Symbol">
<em class="property">class </em><code class="descclassname">symtable.</code><code class="descname">Symbol</code><a class="headerlink" href="#symtable.Symbol" title="Permalink to this definition">¶</a></dt>
<dd><p>An entry in a <a class="reference internal" href="#symtable.SymbolTable" title="symtable.SymbolTable"><code class="xref py py-class docutils literal notranslate"><span class="pre">SymbolTable</span></code></a> corresponding to an identifier in the
source.  The constructor is not public.</p>
<dl class="method">
<dt id="symtable.Symbol.get_name">
<code class="descname">get_name</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.get_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the symbol’s name.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_referenced">
<code class="descname">is_referenced</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_referenced" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is used in its block.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_imported">
<code class="descname">is_imported</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_imported" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is created from an import statement.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_parameter">
<code class="descname">is_parameter</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_parameter" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is a parameter.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_global">
<code class="descname">is_global</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_global" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is global.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_declared_global">
<code class="descname">is_declared_global</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_declared_global" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is declared global with a global statement.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_local">
<code class="descname">is_local</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_local" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is local to its block.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_free">
<code class="descname">is_free</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_free" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is referenced in its block, but not assigned
to.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_assigned">
<code class="descname">is_assigned</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_assigned" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the symbol is assigned to in its block.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.is_namespace">
<code class="descname">is_namespace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.is_namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if name binding introduces new namespace.</p>
<p>If the name is used as the target of a function or class statement, this
will be true.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="n">symtable</span><span class="o">.</span><span class="n">symtable</span><span class="p">(</span><span class="s2">&quot;def some_func(): pass&quot;</span><span class="p">,</span> <span class="s2">&quot;string&quot;</span><span class="p">,</span> <span class="s2">&quot;exec&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">table</span><span class="o">.</span><span class="n">lookup</span><span class="p">(</span><span class="s2">&quot;some_func&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">is_namespace</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Note that a single name can be bound to multiple objects.  If the result
is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the name may also be bound to other objects, like an int or
list, that does not introduce a new namespace.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.get_namespaces">
<code class="descname">get_namespaces</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.get_namespaces" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of namespaces bound to this name.</p>
</dd></dl>

<dl class="method">
<dt id="symtable.Symbol.get_namespace">
<code class="descname">get_namespace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#symtable.Symbol.get_namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the namespace bound to this name.  If more than one namespace is
bound, a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a><ul>
<li><a class="reference internal" href="#generating-symbol-tables">32.3.1. Generating Symbol Tables</a></li>
<li><a class="reference internal" href="#examining-symbol-tables">32.3.2. Examining Symbol Tables</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="ast.html"
                        title="previous chapter">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="symbol.html"
                        title="next chapter">32.4. <code class="docutils literal notranslate"><span class="pre">symbol</span></code> — Constants used with Python parse trees</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/symtable.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="symbol.html" title="32.4. symbol — Constants used with Python parse trees"
             >next</a> |</li>
        <li class="right" >
          <a href="ast.html" title="32.2. ast — Abstract Syntax Trees"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�܂����html/library/sys.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.1. sys — System-specific parameters and functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.2. sysconfig — Provide access to Python’s configuration information" href="sysconfig.html" />
    <link rel="prev" title="28. Python Runtime Services" href="python.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sys.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sysconfig.html" title="28.2. sysconfig — Provide access to Python’s configuration information"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="python.html" title="28. Python Runtime Services"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sys">
<span id="sys-system-specific-parameters-and-functions"></span><h1>28.1. <a class="reference internal" href="#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> — System-specific parameters and functions<a class="headerlink" href="#module-sys" title="Permalink to this headline">¶</a></h1>
<p>This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter. It is
always available.</p>
<dl class="data">
<dt id="sys.argv">
<code class="descclassname">sys.</code><code class="descname">argv</code><a class="headerlink" href="#sys.argv" title="Permalink to this definition">¶</a></dt>
<dd><p>The list of command line arguments passed to a Python script. <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code> is the
script name (it is operating system dependent whether this is a full pathname or
not).  If the command was executed using the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> command line option to
the interpreter, <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code> is set to the string <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>.  If no script name
was passed to the Python interpreter, <code class="docutils literal notranslate"><span class="pre">argv[0]</span></code> is the empty string.</p>
<p>To loop over the standard input, or the list of files given on the
command line, see the <a class="reference internal" href="fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a> module.</p>
</dd></dl>

<dl class="data">
<dt id="sys.byteorder">
<code class="descclassname">sys.</code><code class="descname">byteorder</code><a class="headerlink" href="#sys.byteorder" title="Permalink to this definition">¶</a></dt>
<dd><p>An indicator of the native byte order.  This will have the value <code class="docutils literal notranslate"><span class="pre">'big'</span></code> on
big-endian (most-significant byte first) platforms, and <code class="docutils literal notranslate"><span class="pre">'little'</span></code> on
little-endian (least-significant byte first) platforms.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.builtin_module_names">
<code class="descclassname">sys.</code><code class="descname">builtin_module_names</code><a class="headerlink" href="#sys.builtin_module_names" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of strings giving the names of all modules that are compiled into this
Python interpreter.  (This information is not available in any other way —
<code class="docutils literal notranslate"><span class="pre">modules.keys()</span></code> only lists the imported modules.)</p>
</dd></dl>

<dl class="function">
<dt id="sys.call_tracing">
<code class="descclassname">sys.</code><code class="descname">call_tracing</code><span class="sig-paren">(</span><em>func</em>, <em>args</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.call_tracing" title="Permalink to this definition">¶</a></dt>
<dd><p>Call <code class="docutils literal notranslate"><span class="pre">func(*args)</span></code>, while tracing is enabled.  The tracing state is saved,
and restored afterwards.  This is intended to be called from a debugger from
a checkpoint, to recursively debug some other code.</p>
</dd></dl>

<dl class="data">
<dt id="sys.copyright">
<code class="descclassname">sys.</code><code class="descname">copyright</code><a class="headerlink" href="#sys.copyright" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the copyright pertaining to the Python interpreter.</p>
</dd></dl>

<dl class="function">
<dt id="sys._clear_type_cache">
<code class="descclassname">sys.</code><code class="descname">_clear_type_cache</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys._clear_type_cache" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the internal type cache. The type cache is used to speed up attribute
and method lookups. Use the function <em>only</em> to drop unnecessary references
during reference leak debugging.</p>
<p>This function should be used for internal and specialized purposes only.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys._current_frames">
<code class="descclassname">sys.</code><code class="descname">_current_frames</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys._current_frames" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary mapping each thread’s identifier to the topmost stack frame
currently active in that thread at the time the function is called. Note that
functions in the <a class="reference internal" href="traceback.html#module-traceback" title="traceback: Print or retrieve a stack traceback."><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code></a> module can build the call stack given such a
frame.</p>
<p>This is most useful for debugging deadlock:  this function does not require the
deadlocked threads’ cooperation, and such threads’ call stacks are frozen for as
long as they remain deadlocked.  The frame returned for a non-deadlocked thread
may bear no relationship to that thread’s current activity by the time calling
code examines the frame.</p>
<p>This function should be used for internal and specialized purposes only.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.dllhandle">
<code class="descclassname">sys.</code><code class="descname">dllhandle</code><a class="headerlink" href="#sys.dllhandle" title="Permalink to this definition">¶</a></dt>
<dd><p>Integer specifying the handle of the Python DLL. Availability: Windows.</p>
</dd></dl>

<dl class="function">
<dt id="sys.displayhook">
<code class="descclassname">sys.</code><code class="descname">displayhook</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.displayhook" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>value</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this function prints it to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>, and saves
it in <code class="docutils literal notranslate"><span class="pre">__builtin__._</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">sys.displayhook</span></code> is called on the result of evaluating an <a class="reference internal" href="../glossary.html#term-expression"><span class="xref std std-term">expression</span></a>
entered in an interactive Python session.  The display of these values can be
customized by assigning another one-argument function to <code class="docutils literal notranslate"><span class="pre">sys.displayhook</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.dont_write_bytecode">
<code class="descclassname">sys.</code><code class="descname">dont_write_bytecode</code><a class="headerlink" href="#sys.dont_write_bytecode" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is true, Python won’t try to write <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="docutils literal notranslate"><span class="pre">.pyo</span></code> files on the
import of source modules.  This value is initially set to <code class="docutils literal notranslate"><span class="pre">True</span></code> or
<code class="docutils literal notranslate"><span class="pre">False</span></code> depending on the <a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a> command line option and the
<span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment variable, but you can set it
yourself to control bytecode file generation.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.excepthook">
<code class="descclassname">sys.</code><code class="descname">excepthook</code><span class="sig-paren">(</span><em>type</em>, <em>value</em>, <em>traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.excepthook" title="Permalink to this definition">¶</a></dt>
<dd><p>This function prints out a given traceback and exception to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.</p>
<p>When an exception is raised and uncaught, the interpreter calls
<code class="docutils literal notranslate"><span class="pre">sys.excepthook</span></code> with three arguments, the exception class, exception
instance, and a traceback object.  In an interactive session this happens just
before control is returned to the prompt; in a Python program this happens just
before the program exits.  The handling of such top-level exceptions can be
customized by assigning another three-argument function to <code class="docutils literal notranslate"><span class="pre">sys.excepthook</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.__displayhook__">
<code class="descclassname">sys.</code><code class="descname">__displayhook__</code><a class="headerlink" href="#sys.__displayhook__" title="Permalink to this definition">¶</a></dt>
<dt id="sys.__excepthook__">
<code class="descclassname">sys.</code><code class="descname">__excepthook__</code><a class="headerlink" href="#sys.__excepthook__" title="Permalink to this definition">¶</a></dt>
<dd><p>These objects contain the original values of <code class="docutils literal notranslate"><span class="pre">displayhook</span></code> and <code class="docutils literal notranslate"><span class="pre">excepthook</span></code>
at the start of the program.  They are saved so that <code class="docutils literal notranslate"><span class="pre">displayhook</span></code> and
<code class="docutils literal notranslate"><span class="pre">excepthook</span></code> can be restored in case they happen to get replaced with broken
objects.</p>
</dd></dl>

<dl class="function">
<dt id="sys.exc_info">
<code class="descclassname">sys.</code><code class="descname">exc_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.exc_info" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns a tuple of three values that give information about the
exception that is currently being handled.  The information returned is specific
both to the current thread and to the current stack frame.  If the current stack
frame is not handling an exception, the information is taken from the calling
stack frame, or its caller, and so on until a stack frame is found that is
handling an exception.  Here, “handling an exception” is defined as “executing
or having executed an except clause.”  For any stack frame, only information
about the most recently handled exception is accessible.</p>
<p id="index-1">If no exception is being handled anywhere on the stack, a tuple containing three
<code class="docutils literal notranslate"><span class="pre">None</span></code> values is returned.  Otherwise, the values returned are <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">value,</span>
<span class="pre">traceback)</span></code>.  Their meaning is: <em>type</em> gets the exception type of the exception
being handled (a class object); <em>value</em> gets the exception parameter (its
<em class="dfn">associated value</em> or the second argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a>, which is
always a class instance if the exception type is a class object); <em>traceback</em>
gets a traceback object (see the Reference Manual) which encapsulates the call
stack at the point where the exception originally occurred.</p>
<p>If <a class="reference internal" href="#sys.exc_clear" title="sys.exc_clear"><code class="xref py py-func docutils literal notranslate"><span class="pre">exc_clear()</span></code></a> is called, this function will return three <code class="docutils literal notranslate"><span class="pre">None</span></code> values
until either another exception is raised in the current thread or the execution
stack returns to a frame where another exception is being handled.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Assigning the <em>traceback</em> return value to a local variable in a function that is
handling an exception will cause a circular reference.  This will prevent
anything referenced by a local variable in the same function or by the traceback
from being garbage collected.  Since most functions don’t need access to the
traceback, the best solution is to use something like <code class="docutils literal notranslate"><span class="pre">exctype,</span> <span class="pre">value</span> <span class="pre">=</span>
<span class="pre">sys.exc_info()[:2]</span></code> to extract only the exception type and value.  If you do
need the traceback, make sure to delete it after use (best done with a
<a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement) or to call <a class="reference internal" href="#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">exc_info()</span></code></a> in
a function that does not itself handle an exception.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Beginning with Python 2.2, such cycles are automatically reclaimed when garbage
collection is enabled and they become unreachable, but it remains more efficient
to avoid creating cycles.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.exc_clear">
<code class="descclassname">sys.</code><code class="descname">exc_clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.exc_clear" title="Permalink to this definition">¶</a></dt>
<dd><p>This function clears all information relating to the current or last exception
that occurred in the current thread.  After calling this function,
<a class="reference internal" href="#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">exc_info()</span></code></a> will return three <code class="docutils literal notranslate"><span class="pre">None</span></code> values until another exception is
raised in the current thread or the execution stack returns to a frame where
another exception is being handled.</p>
<p>This function is only needed in only a few obscure situations.  These include
logging and error handling systems that report information on the last or
current exception.  This function can also be used to try to free resources and
trigger object finalization, though no guarantee is made as to what objects will
be freed, if any.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.exc_type">
<code class="descclassname">sys.</code><code class="descname">exc_type</code><a class="headerlink" href="#sys.exc_type" title="Permalink to this definition">¶</a></dt>
<dt id="sys.exc_value">
<code class="descclassname">sys.</code><code class="descname">exc_value</code><a class="headerlink" href="#sys.exc_value" title="Permalink to this definition">¶</a></dt>
<dt id="sys.exc_traceback">
<code class="descclassname">sys.</code><code class="descname">exc_traceback</code><a class="headerlink" href="#sys.exc_traceback" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 1.5: </span>Use <a class="reference internal" href="#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">exc_info()</span></code></a> instead.</p>
</div>
<p>Since they are global variables, they are not specific to the current thread, so
their use is not safe in a multi-threaded program.  When no exception is being
handled, <code class="docutils literal notranslate"><span class="pre">exc_type</span></code> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code> and the other two are undefined.</p>
</dd></dl>

<dl class="data">
<dt id="sys.exec_prefix">
<code class="descclassname">sys.</code><code class="descname">exec_prefix</code><a class="headerlink" href="#sys.exec_prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>A string giving the site-specific directory prefix where the platform-dependent
Python files are installed; by default, this is also <code class="docutils literal notranslate"><span class="pre">'/usr/local'</span></code>.  This can
be set at build time with the <code class="docutils literal notranslate"><span class="pre">--exec-prefix</span></code> argument to the
<strong class="program">configure</strong> script.  Specifically, all configuration files (e.g. the
<code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code> header file) are installed in the directory
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/config</span></code>, and shared library modules are
installed in <code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em><span class="pre">/lib-dynload</span></code>, where <em>X.Y</em>
is the version number of Python, for example <code class="docutils literal notranslate"><span class="pre">2.7</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.executable">
<code class="descclassname">sys.</code><code class="descname">executable</code><a class="headerlink" href="#sys.executable" title="Permalink to this definition">¶</a></dt>
<dd><p>A string giving the absolute path of the executable binary for the Python
interpreter, on systems where this makes sense. If Python is unable to retrieve
the real path to its executable, <a class="reference internal" href="#sys.executable" title="sys.executable"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.executable</span></code></a> will be an empty string
or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="sys.exit">
<code class="descclassname">sys.</code><code class="descname">exit</code><span class="sig-paren">(</span><span class="optional">[</span><em>arg</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.exit" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit from Python.  This is implemented by raising the <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>
exception, so cleanup actions specified by finally clauses of <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
statements are honored, and it is possible to intercept the exit attempt at
an outer level.</p>
<p>The optional argument <em>arg</em> can be an integer giving the exit status
(defaulting to zero), or another type of object.  If it is an integer, zero
is considered “successful termination” and any nonzero value is considered
“abnormal termination” by shells and the like.  Most systems require it to be
in the range 0–127, and produce undefined results otherwise.  Some systems
have a convention for assigning specific meanings to specific exit codes, but
these are generally underdeveloped; Unix programs generally use 2 for command
line syntax errors and 1 for all other kind of errors.  If another type of
object is passed, <code class="docutils literal notranslate"><span class="pre">None</span></code> is equivalent to passing zero, and any other
object is printed to <a class="reference internal" href="#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">stderr</span></code></a> and results in an exit code of 1.  In
particular, <code class="docutils literal notranslate"><span class="pre">sys.exit(&quot;some</span> <span class="pre">error</span> <span class="pre">message&quot;)</span></code> is a quick way to exit a
program when an error occurs.</p>
<p>Since <a class="reference internal" href="constants.html#exit" title="exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">exit()</span></code></a> ultimately “only” raises an exception, it will only exit
the process when called from the main thread, and the exception is not
intercepted.</p>
</dd></dl>

<dl class="data">
<dt id="sys.exitfunc">
<code class="descclassname">sys.</code><code class="descname">exitfunc</code><a class="headerlink" href="#sys.exitfunc" title="Permalink to this definition">¶</a></dt>
<dd><p>This value is not actually defined by the module, but can be set by the user (or
by a program) to specify a clean-up action at program exit.  When set, it should
be a parameterless function.  This function will be called when the interpreter
exits.  Only one function may be installed in this way; to allow multiple
functions which will be called at termination, use the <a class="reference internal" href="atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The exit function is not called when the program is killed by a signal, when a
Python fatal internal error is detected, or when <code class="docutils literal notranslate"><span class="pre">os._exit()</span></code> is called.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.4: </span>Use <a class="reference internal" href="atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.flags">
<code class="descclassname">sys.</code><code class="descname">flags</code><a class="headerlink" href="#sys.flags" title="Permalink to this definition">¶</a></dt>
<dd><p>The struct sequence <em>flags</em> exposes the status of command line flags. The
attributes are read only.</p>
<table border="1" class="docutils">
<colgroup>
<col width="45%" />
<col width="55%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">attribute</th>
<th class="head">flag</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">debug</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-d"><code class="xref std std-option docutils literal notranslate"><span class="pre">-d</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">py3k_warning</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">division_warning</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-q"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Q</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">division_new</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-q"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Qnew</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-const docutils literal notranslate"><span class="pre">inspect</span></code></a></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">interactive</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">optimize</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-oo"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#sys.dont_write_bytecode" title="sys.dont_write_bytecode"><code class="xref py py-const docutils literal notranslate"><span class="pre">dont_write_bytecode</span></code></a></td>
<td><a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">no_user_site</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">no_site</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#id2"><code class="xref std std-option docutils literal notranslate"><span class="pre">-S</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">ignore_environment</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-e"><code class="xref std std-option docutils literal notranslate"><span class="pre">-E</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">tabcheck</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">-t</span></code></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">-tt</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">verbose</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#id3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-const docutils literal notranslate"><span class="pre">unicode</span></code></a></td>
<td><a class="reference internal" href="../using/cmdline.html#id4"><code class="xref std std-option docutils literal notranslate"><span class="pre">-U</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">bytes_warning</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-b"><code class="xref std std-option docutils literal notranslate"><span class="pre">-b</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">hash_randomization</span></code></td>
<td><a class="reference internal" href="../using/cmdline.html#cmdoption-r"><code class="xref std std-option docutils literal notranslate"><span class="pre">-R</span></code></a></td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.3: </span>The <code class="docutils literal notranslate"><span class="pre">hash_randomization</span></code> attribute.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.float_info">
<code class="descclassname">sys.</code><code class="descname">float_info</code><a class="headerlink" href="#sys.float_info" title="Permalink to this definition">¶</a></dt>
<dd><p>A structseq holding information about the float type. It contains low level
information about the precision and internal representation.  The values
correspond to the various floating-point constants defined in the standard
header file <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> for the ‘C’ programming language; see section
5.2.4.2.2 of the 1999 ISO/IEC C standard <a class="reference internal" href="#c99" id="id1">[C99]</a>, ‘Characteristics of
floating types’, for details.</p>
<table border="1" class="docutils">
<colgroup>
<col width="24%" />
<col width="18%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">attribute</th>
<th class="head">float.h macro</th>
<th class="head">explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">epsilon</span></code></td>
<td>DBL_EPSILON</td>
<td>difference between 1 and the least value greater
than 1 that is representable as a float</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">dig</span></code></td>
<td>DBL_DIG</td>
<td>maximum number of decimal digits that can be
faithfully represented in a float;  see below</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">mant_dig</span></code></td>
<td>DBL_MANT_DIG</td>
<td>float precision: the number of base-<code class="docutils literal notranslate"><span class="pre">radix</span></code>
digits in the significand of a float</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="functions.html#max" title="max"><code class="xref py py-const docutils literal notranslate"><span class="pre">max</span></code></a></td>
<td>DBL_MAX</td>
<td>maximum representable finite float</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">max_exp</span></code></td>
<td>DBL_MAX_EXP</td>
<td>maximum integer e such that <code class="docutils literal notranslate"><span class="pre">radix**(e-1)</span></code> is
a representable finite float</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">max_10_exp</span></code></td>
<td>DBL_MAX_10_EXP</td>
<td>maximum integer e such that <code class="docutils literal notranslate"><span class="pre">10**e</span></code> is in the
range of representable finite floats</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="functions.html#min" title="min"><code class="xref py py-const docutils literal notranslate"><span class="pre">min</span></code></a></td>
<td>DBL_MIN</td>
<td>minimum positive normalized float</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">min_exp</span></code></td>
<td>DBL_MIN_EXP</td>
<td>minimum integer e such that <code class="docutils literal notranslate"><span class="pre">radix**(e-1)</span></code> is
a normalized float</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">min_10_exp</span></code></td>
<td>DBL_MIN_10_EXP</td>
<td>minimum integer e such that <code class="docutils literal notranslate"><span class="pre">10**e</span></code> is a
normalized float</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">radix</span></code></td>
<td>FLT_RADIX</td>
<td>radix of exponent representation</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">rounds</span></code></td>
<td>FLT_ROUNDS</td>
<td>integer constant representing the rounding mode
used for arithmetic operations.  This reflects
the value of the system FLT_ROUNDS macro at
interpreter startup time.  See section 5.2.4.2.2
of the C99 standard for an explanation of the
possible values and their meanings.</td>
</tr>
</tbody>
</table>
<p>The attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.float_info.dig</span></code> needs further explanation.  If
<code class="docutils literal notranslate"><span class="pre">s</span></code> is any string representing a decimal number with at most
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.float_info.dig</span></code> significant digits, then converting <code class="docutils literal notranslate"><span class="pre">s</span></code> to a
float and back again will recover a string representing the same decimal
value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">float_info</span><span class="o">.</span><span class="n">dig</span>
<span class="go">15</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;3.14159265358979&#39;</span>    <span class="c1"># decimal string with 15 significant digits</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">s</span><span class="p">),</span> <span class="s1">&#39;.15g&#39;</span><span class="p">)</span>  <span class="c1"># convert to float and back -&gt; same value</span>
<span class="go">&#39;3.14159265358979&#39;</span>
</pre></div>
</div>
<p>But for strings with more than <code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.float_info.dig</span></code> significant digits,
this isn’t always true:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;9876543211234567&#39;</span>    <span class="c1"># 16 significant digits is too many!</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">s</span><span class="p">),</span> <span class="s1">&#39;.16g&#39;</span><span class="p">)</span>  <span class="c1"># conversion changes value</span>
<span class="go">&#39;9876543211234568&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.float_repr_style">
<code class="descclassname">sys.</code><code class="descname">float_repr_style</code><a class="headerlink" href="#sys.float_repr_style" title="Permalink to this definition">¶</a></dt>
<dd><p>A string indicating how the <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function behaves for
floats.  If the string has value <code class="docutils literal notranslate"><span class="pre">'short'</span></code> then for a finite
float <code class="docutils literal notranslate"><span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">repr(x)</span></code> aims to produce a short string with the
property that <code class="docutils literal notranslate"><span class="pre">float(repr(x))</span> <span class="pre">==</span> <span class="pre">x</span></code>.  This is the usual behaviour
in Python 2.7 and later.  Otherwise, <code class="docutils literal notranslate"><span class="pre">float_repr_style</span></code> has value
<code class="docutils literal notranslate"><span class="pre">'legacy'</span></code> and <code class="docutils literal notranslate"><span class="pre">repr(x)</span></code> behaves in the same way as it did in
versions of Python prior to 2.7.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getcheckinterval">
<code class="descclassname">sys.</code><code class="descname">getcheckinterval</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getcheckinterval" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the interpreter’s “check interval”; see <a class="reference internal" href="#sys.setcheckinterval" title="sys.setcheckinterval"><code class="xref py py-func docutils literal notranslate"><span class="pre">setcheckinterval()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getdefaultencoding">
<code class="descclassname">sys.</code><code class="descname">getdefaultencoding</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getdefaultencoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the current default string encoding used by the Unicode
implementation.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getdlopenflags">
<code class="descclassname">sys.</code><code class="descname">getdlopenflags</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getdlopenflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current value of the flags that are used for <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> calls.
The flag constants are defined in the <a class="reference internal" href="dl.html#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">DLFCN</span></code> modules.
Availability: Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getfilesystemencoding">
<code class="descclassname">sys.</code><code class="descname">getfilesystemencoding</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getfilesystemencoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the name of the encoding used to convert Unicode filenames into system
file names, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the system default encoding is used. The result value
depends on the operating system:</p>
<ul class="simple">
<li>On Mac OS X, the encoding is <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code>.</li>
<li>On Unix, the encoding is the user’s preference according to the result of
nl_langinfo(CODESET), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the <code class="docutils literal notranslate"><span class="pre">nl_langinfo(CODESET)</span></code>
failed.</li>
<li>On Windows NT+, file names are Unicode natively, so no conversion is
performed. <a class="reference internal" href="#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">getfilesystemencoding()</span></code></a> still returns <code class="docutils literal notranslate"><span class="pre">'mbcs'</span></code>, as
this is the encoding that applications should use when they explicitly
want to convert Unicode strings to byte strings that are equivalent when
used as file names.</li>
<li>On Windows 9x, the encoding is <code class="docutils literal notranslate"><span class="pre">'mbcs'</span></code>.</li>
</ul>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getrefcount">
<code class="descclassname">sys.</code><code class="descname">getrefcount</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.getrefcount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the reference count of the <em>object</em>.  The count returned is generally one
higher than you might expect, because it includes the (temporary) reference as
an argument to <a class="reference internal" href="#sys.getrefcount" title="sys.getrefcount"><code class="xref py py-func docutils literal notranslate"><span class="pre">getrefcount()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sys.getrecursionlimit">
<code class="descclassname">sys.</code><code class="descname">getrecursionlimit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getrecursionlimit" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current value of the recursion limit, the maximum depth of the Python
interpreter stack.  This limit prevents infinite recursion from causing an
overflow of the C stack and crashing Python.  It can be set by
<a class="reference internal" href="#sys.setrecursionlimit" title="sys.setrecursionlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">setrecursionlimit()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sys.getsizeof">
<code class="descclassname">sys.</code><code class="descname">getsizeof</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getsizeof" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the size of an object in bytes. The object can be any type of
object. All built-in objects will return correct results, but this
does not have to hold true for third-party extensions as it is implementation
specific.</p>
<p>If given, <em>default</em> will be returned if the object does not provide means to
retrieve the size.  Otherwise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised.</p>
<p><a class="reference internal" href="#sys.getsizeof" title="sys.getsizeof"><code class="xref py py-func docutils literal notranslate"><span class="pre">getsizeof()</span></code></a> calls the object’s <code class="docutils literal notranslate"><span class="pre">__sizeof__</span></code> method and adds an
additional garbage collector overhead if the object is managed by the garbage
collector.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys._getframe">
<code class="descclassname">sys.</code><code class="descname">_getframe</code><span class="sig-paren">(</span><span class="optional">[</span><em>depth</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sys._getframe" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a frame object from the call stack.  If optional integer <em>depth</em> is
given, return the frame object that many calls below the top of the stack.  If
that is deeper than the call stack, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  The default
for <em>depth</em> is zero, returning the frame at the top of the call stack.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> This function should be used for internal and specialized purposes only.
It is not guaranteed to exist in all implementations of Python.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getprofile">
<code class="descclassname">sys.</code><code class="descname">getprofile</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getprofile" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Get the profiler function as set by <a class="reference internal" href="#sys.setprofile" title="sys.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">setprofile()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.gettrace">
<code class="descclassname">sys.</code><code class="descname">gettrace</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.gettrace" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">Get the trace function as set by <a class="reference internal" href="#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">settrace()</span></code></a>.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> The <a class="reference internal" href="#sys.gettrace" title="sys.gettrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettrace()</span></code></a> function is intended only for implementing debuggers,
profilers, coverage tools and the like.  Its behavior is part of the
implementation platform, rather than part of the language definition, and
thus may not be available in all Python implementations.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.getwindowsversion">
<code class="descclassname">sys.</code><code class="descname">getwindowsversion</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sys.getwindowsversion" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a named tuple describing the Windows version
currently running.  The named elements are <em>major</em>, <em>minor</em>,
<em>build</em>, <em>platform</em>, <em>service_pack</em>, <em>service_pack_minor</em>,
<em>service_pack_major</em>, <em>suite_mask</em>, and <em>product_type</em>.
<em>service_pack</em> contains a string while all other values are
integers. The components can also be accessed by name, so
<code class="docutils literal notranslate"><span class="pre">sys.getwindowsversion()[0]</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">sys.getwindowsversion().major</span></code>. For compatibility with prior
versions, only the first 5 elements are retrievable by indexing.</p>
<p><em>platform</em> may be one of the following values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="62%" />
<col width="38%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Platform</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">0</span> <span class="pre">(VER_PLATFORM_WIN32s)</span></code></td>
<td>Win32s on Windows 3.1</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">1</span> <span class="pre">(VER_PLATFORM_WIN32_WINDOWS)</span></code></td>
<td>Windows 95/98/ME</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">2</span> <span class="pre">(VER_PLATFORM_WIN32_NT)</span></code></td>
<td>Windows NT/2000/XP/x64</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">3</span> <span class="pre">(VER_PLATFORM_WIN32_CE)</span></code></td>
<td>Windows CE</td>
</tr>
</tbody>
</table>
<p><em>product_type</em> may be one of the following values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">1</span> <span class="pre">(VER_NT_WORKSTATION)</span></code></td>
<td>The system is a workstation.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">2</span> <span class="pre">(VER_NT_DOMAIN_CONTROLLER)</span></code></td>
<td>The system is a domain
controller.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">3</span> <span class="pre">(VER_NT_SERVER)</span></code></td>
<td>The system is a server, but not
a domain controller.</td>
</tr>
</tbody>
</table>
<p>This function wraps the Win32 <code class="xref c c-func docutils literal notranslate"><span class="pre">GetVersionEx()</span></code> function; see the
Microsoft documentation on <code class="xref c c-func docutils literal notranslate"><span class="pre">OSVERSIONINFOEX()</span></code> for more information
about these fields.</p>
<p>Availability: Windows.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Changed to a named tuple and added <em>service_pack_minor</em>,
<em>service_pack_major</em>, <em>suite_mask</em>, and <em>product_type</em>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.hexversion">
<code class="descclassname">sys.</code><code class="descname">hexversion</code><a class="headerlink" href="#sys.hexversion" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number encoded as a single integer.  This is guaranteed to increase
with each version, including proper support for non-production releases.  For
example, to test that the Python interpreter is at least version 1.5.2, use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">hexversion</span> <span class="o">&gt;=</span> <span class="mh">0x010502F0</span><span class="p">:</span>
    <span class="c1"># use some advanced feature</span>
    <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># use an alternative implementation or warn the user</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This is called <code class="docutils literal notranslate"><span class="pre">hexversion</span></code> since it only really looks meaningful when viewed
as the result of passing it to the built-in <a class="reference internal" href="functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> function.  The
<code class="docutils literal notranslate"><span class="pre">version_info</span></code> value may be used for a more human-friendly encoding of the
same information.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">hexversion</span></code> is a 32-bit number with the following layout:</p>
<table border="1" class="docutils">
<colgroup>
<col width="34%" />
<col width="66%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Bits (big endian order)</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">1-8</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">PY_MAJOR_VERSION</span></code>  (the <code class="docutils literal notranslate"><span class="pre">2</span></code> in
<code class="docutils literal notranslate"><span class="pre">2.1.0a3</span></code>)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">9-16</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">PY_MINOR_VERSION</span></code>  (the <code class="docutils literal notranslate"><span class="pre">1</span></code> in
<code class="docutils literal notranslate"><span class="pre">2.1.0a3</span></code>)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">17-24</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">PY_MICRO_VERSION</span></code>  (the <code class="docutils literal notranslate"><span class="pre">0</span></code> in
<code class="docutils literal notranslate"><span class="pre">2.1.0a3</span></code>)</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">25-28</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">PY_RELEASE_LEVEL</span></code>  (<code class="docutils literal notranslate"><span class="pre">0xA</span></code> for alpha,
<code class="docutils literal notranslate"><span class="pre">0xB</span></code> for beta, <code class="docutils literal notranslate"><span class="pre">0xC</span></code> for release
candidate and <code class="docutils literal notranslate"><span class="pre">0xF</span></code> for final)</td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">29-32</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">PY_RELEASE_SERIAL</span></code>  (the <code class="docutils literal notranslate"><span class="pre">3</span></code> in
<code class="docutils literal notranslate"><span class="pre">2.1.0a3</span></code>, zero for final releases)</td>
</tr>
</tbody>
</table>
<p>Thus <code class="docutils literal notranslate"><span class="pre">2.1.0a3</span></code> is hexversion <code class="docutils literal notranslate"><span class="pre">0x020100a3</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.long_info">
<code class="descclassname">sys.</code><code class="descname">long_info</code><a class="headerlink" href="#sys.long_info" title="Permalink to this definition">¶</a></dt>
<dd><p>A struct sequence that holds information about Python’s
internal representation of integers.  The attributes are read only.</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="65%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Explanation</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">bits_per_digit</span></code></td>
<td>number of bits held in each digit.  Python
integers are stored internally in base
<code class="docutils literal notranslate"><span class="pre">2**long_info.bits_per_digit</span></code></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">sizeof_digit</span></code></td>
<td>size in bytes of the C type used to
represent a digit</td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.last_type">
<code class="descclassname">sys.</code><code class="descname">last_type</code><a class="headerlink" href="#sys.last_type" title="Permalink to this definition">¶</a></dt>
<dt id="sys.last_value">
<code class="descclassname">sys.</code><code class="descname">last_value</code><a class="headerlink" href="#sys.last_value" title="Permalink to this definition">¶</a></dt>
<dt id="sys.last_traceback">
<code class="descclassname">sys.</code><code class="descname">last_traceback</code><a class="headerlink" href="#sys.last_traceback" title="Permalink to this definition">¶</a></dt>
<dd><p>These three variables are not always defined; they are set when an exception is
not handled and the interpreter prints an error message and a stack traceback.
Their intended use is to allow an interactive user to import a debugger module
and engage in post-mortem debugging without having to re-execute the command
that caused the error.  (Typical use is <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">pdb;</span> <span class="pre">pdb.pm()</span></code> to enter the
post-mortem debugger; see chapter <a class="reference internal" href="pdb.html#debugger"><span class="std std-ref">pdb — The Python Debugger</span></a> for
more information.)</p>
<p>The meaning of the variables is the same as that of the return values from
<a class="reference internal" href="#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">exc_info()</span></code></a> above.  (Since there is only one interactive thread,
thread-safety is not a concern for these variables, unlike for <code class="docutils literal notranslate"><span class="pre">exc_type</span></code>
etc.)</p>
</dd></dl>

<dl class="data">
<dt id="sys.maxint">
<code class="descclassname">sys.</code><code class="descname">maxint</code><a class="headerlink" href="#sys.maxint" title="Permalink to this definition">¶</a></dt>
<dd><p>The largest positive integer supported by Python’s regular integer type.  This
is at least 2**31-1.  The largest negative integer is <code class="docutils literal notranslate"><span class="pre">-maxint-1</span></code> — the
asymmetry results from the use of 2’s complement binary arithmetic.</p>
</dd></dl>

<dl class="data">
<dt id="sys.maxsize">
<code class="descclassname">sys.</code><code class="descname">maxsize</code><a class="headerlink" href="#sys.maxsize" title="Permalink to this definition">¶</a></dt>
<dd><p>The largest positive integer supported by the platform’s Py_ssize_t type,
and thus the maximum size lists, strings, dicts, and many other containers
can have.</p>
</dd></dl>

<dl class="data">
<dt id="sys.maxunicode">
<code class="descclassname">sys.</code><code class="descname">maxunicode</code><a class="headerlink" href="#sys.maxunicode" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer giving the largest supported code point for a Unicode character.  The
value of this depends on the configuration option that specifies whether Unicode
characters are stored as UCS-2 or UCS-4.</p>
</dd></dl>

<dl class="data">
<dt id="sys.meta_path">
<code class="descclassname">sys.</code><code class="descname">meta_path</code><a class="headerlink" href="#sys.meta_path" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of <a class="reference internal" href="../glossary.html#term-finder"><span class="xref std std-term">finder</span></a> objects that have their <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code>
methods called to see if one of the objects can find the module to be
imported. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code> method is called at least with the
absolute name of the module being imported. If the module to be imported is
contained in package then the parent package’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code> attribute
is passed in as a second argument. The method returns <code class="docutils literal notranslate"><span class="pre">None</span></code> if
the module cannot be found, else returns a <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a>.</p>
<p><a class="reference internal" href="#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a> is searched before any implicit default finders or
<a class="reference internal" href="#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<p>See <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for the original specification.</p>
</dd></dl>

<dl class="data">
<dt id="sys.modules">
<code class="descclassname">sys.</code><code class="descname">modules</code><a class="headerlink" href="#sys.modules" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-5">This is a dictionary that maps module names to modules which have already been
loaded.  This can be manipulated to force reloading of modules and other tricks.
Note that removing a module from this dictionary is <em>not</em> the same as calling
<a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> on the corresponding module object.</p>
</dd></dl>

<dl class="data">
<dt id="sys.path">
<code class="descclassname">sys.</code><code class="descname">path</code><a class="headerlink" href="#sys.path" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-6">A list of strings that specifies the search path for modules. Initialized from
the environment variable <span class="target" id="index-7"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>, plus an installation-dependent
default.</p>
<p>As initialized upon program startup, the first item of this list, <code class="docutils literal notranslate"><span class="pre">path[0]</span></code>,
is the directory containing the script that was used to invoke the Python
interpreter.  If the script directory is not available (e.g.  if the interpreter
is invoked interactively or if the script is read from standard input),
<code class="docutils literal notranslate"><span class="pre">path[0]</span></code> is the empty string, which directs Python to search modules in the
current directory first.  Notice that the script directory is inserted <em>before</em>
the entries inserted as a result of <span class="target" id="index-8"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>.</p>
<p>A program is free to modify this list for its own purposes.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Unicode strings are no longer ignored.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">Module <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> This describes how to use .pth files to extend
<a class="reference internal" href="#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.path_hooks">
<code class="descclassname">sys.</code><code class="descname">path_hooks</code><a class="headerlink" href="#sys.path_hooks" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of callables that take a path argument to try to create a
<a class="reference internal" href="../glossary.html#term-finder"><span class="xref std std-term">finder</span></a> for the path. If a finder can be created, it is to be
returned by the callable, else raise <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.</p>
<p>Originally specified in <span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.path_importer_cache">
<code class="descclassname">sys.</code><code class="descname">path_importer_cache</code><a class="headerlink" href="#sys.path_importer_cache" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary acting as a cache for <a class="reference internal" href="../glossary.html#term-finder"><span class="xref std std-term">finder</span></a> objects. The keys are
paths that have been passed to <a class="reference internal" href="#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a> and the values are
the finders that are found. If a path is a valid file system path but no
explicit finder is found on <a class="reference internal" href="#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a> then <code class="docutils literal notranslate"><span class="pre">None</span></code> is
stored to represent the implicit default finder should be used. If the path
is not an existing path then <a class="reference internal" href="imp.html#imp.NullImporter" title="imp.NullImporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">imp.NullImporter</span></code></a> is set.</p>
<p>Originally specified in <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.platform">
<code class="descclassname">sys.</code><code class="descname">platform</code><a class="headerlink" href="#sys.platform" title="Permalink to this definition">¶</a></dt>
<dd><p>This string contains a platform identifier that can be used to append
platform-specific components to <a class="reference internal" href="#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, for instance.</p>
<p>For most Unix systems, this is the lowercased OS name as returned by <code class="docutils literal notranslate"><span class="pre">uname</span>
<span class="pre">-s</span></code> with the first part of the version as returned by <code class="docutils literal notranslate"><span class="pre">uname</span> <span class="pre">-r</span></code> appended,
e.g. <code class="docutils literal notranslate"><span class="pre">'sunos5'</span></code>, <em>at the time when Python was built</em>.  Unless you want to
test for a specific system version, it is therefore recommended to use the
following idiom:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;freebsd&#39;</span><span class="p">):</span>
    <span class="c1"># FreeBSD-specific code here...</span>
<span class="k">elif</span> <span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">&#39;linux&#39;</span><span class="p">):</span>
    <span class="c1"># Linux-specific code here...</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.3: </span>Since lots of code check for <code class="docutils literal notranslate"><span class="pre">sys.platform</span> <span class="pre">==</span> <span class="pre">'linux2'</span></code>, and there is
no essential change between Linux 2.x and 3.x, <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code> is always
set to <code class="docutils literal notranslate"><span class="pre">'linux2'</span></code>, even on Linux 3.x.  In Python 3.3 and later, the
value will always be set to <code class="docutils literal notranslate"><span class="pre">'linux'</span></code>, so it is recommended to always
use the <code class="docutils literal notranslate"><span class="pre">startswith</span></code> idiom presented above.</p>
</div>
<p>For other systems, the values are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="44%" />
<col width="56%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">System</th>
<th class="head"><a class="reference internal" href="platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-data docutils literal notranslate"><span class="pre">platform</span></code></a> value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>Linux (2.x <em>and</em> 3.x)</td>
<td><code class="docutils literal notranslate"><span class="pre">'linux2'</span></code></td>
</tr>
<tr class="row-odd"><td>Windows</td>
<td><code class="docutils literal notranslate"><span class="pre">'win32'</span></code></td>
</tr>
<tr class="row-even"><td>Windows/Cygwin</td>
<td><code class="docutils literal notranslate"><span class="pre">'cygwin'</span></code></td>
</tr>
<tr class="row-odd"><td>Mac OS X</td>
<td><code class="docutils literal notranslate"><span class="pre">'darwin'</span></code></td>
</tr>
<tr class="row-even"><td>OS/2</td>
<td><code class="docutils literal notranslate"><span class="pre">'os2'</span></code></td>
</tr>
<tr class="row-odd"><td>OS/2 EMX</td>
<td><code class="docutils literal notranslate"><span class="pre">'os2emx'</span></code></td>
</tr>
<tr class="row-even"><td>RiscOS</td>
<td><code class="docutils literal notranslate"><span class="pre">'riscos'</span></code></td>
</tr>
<tr class="row-odd"><td>AtheOS</td>
<td><code class="docutils literal notranslate"><span class="pre">'atheos'</span></code></td>
</tr>
</tbody>
</table>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="os.html#os.name" title="os.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.name</span></code></a> has a coarser granularity.  <a class="reference internal" href="os.html#os.uname" title="os.uname"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.uname()</span></code></a> gives
system-dependent version information.</p>
<p class="last">The <a class="reference internal" href="platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> module provides detailed checks for the
system’s identity.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.prefix">
<code class="descclassname">sys.</code><code class="descname">prefix</code><a class="headerlink" href="#sys.prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>A string giving the site-specific directory prefix where the platform
independent Python files are installed; by default, this is the string
<code class="docutils literal notranslate"><span class="pre">'/usr/local'</span></code>.  This can be set at build time with the <code class="docutils literal notranslate"><span class="pre">--prefix</span></code>
argument to the <strong class="program">configure</strong> script.  The main collection of Python
library modules is installed in the directory <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">X.Y</span></em></code>
while the platform independent header files (all except <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code>) are
stored in <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include/python</span><em><span class="pre">X.Y</span></em></code>, where <em>X.Y</em> is the version
number of Python, for example <code class="docutils literal notranslate"><span class="pre">2.7</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="sys.ps1">
<code class="descclassname">sys.</code><code class="descname">ps1</code><a class="headerlink" href="#sys.ps1" title="Permalink to this definition">¶</a></dt>
<dt id="sys.ps2">
<code class="descclassname">sys.</code><code class="descname">ps2</code><a class="headerlink" href="#sys.ps2" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-11">Strings specifying the primary and secondary prompt of the interpreter.  These
are only defined if the interpreter is in interactive mode.  Their initial
values in this case are <code class="docutils literal notranslate"><span class="pre">'&gt;&gt;&gt;</span> <span class="pre">'</span></code> and <code class="docutils literal notranslate"><span class="pre">'...</span> <span class="pre">'</span></code>.  If a non-string object is
assigned to either variable, its <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> is re-evaluated each time the
interpreter prepares to read a new interactive command; this can be used to
implement a dynamic prompt.</p>
</dd></dl>

<dl class="data">
<dt id="sys.py3kwarning">
<code class="descclassname">sys.</code><code class="descname">py3kwarning</code><a class="headerlink" href="#sys.py3kwarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Bool containing the status of the Python 3 warning flag. It’s <code class="docutils literal notranslate"><span class="pre">True</span></code>
when Python is started with the -3 option.  (This should be considered
read-only; setting it to a different value doesn’t have an effect on
Python 3 warnings.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.setcheckinterval">
<code class="descclassname">sys.</code><code class="descname">setcheckinterval</code><span class="sig-paren">(</span><em>interval</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.setcheckinterval" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the interpreter’s “check interval”.  This integer value determines how often
the interpreter checks for periodic things such as thread switches and signal
handlers.  The default is <code class="docutils literal notranslate"><span class="pre">100</span></code>, meaning the check is performed every 100
Python virtual instructions. Setting it to a larger value may increase
performance for programs using threads.  Setting it to a value <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> 0 checks
every virtual instruction, maximizing responsiveness as well as overhead.</p>
</dd></dl>

<dl class="function">
<dt id="sys.setdefaultencoding">
<code class="descclassname">sys.</code><code class="descname">setdefaultencoding</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.setdefaultencoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current default string encoding used by the Unicode implementation.  If
<em>name</em> does not match any available encoding, <a class="reference internal" href="exceptions.html#exceptions.LookupError" title="exceptions.LookupError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">LookupError</span></code></a> is raised.
This function is only intended to be used by the <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module
implementation and, where needed, by <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code>.  Once used by the
<a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module, it is removed from the <a class="reference internal" href="#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module’s namespace.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.setdlopenflags">
<code class="descclassname">sys.</code><code class="descname">setdlopenflags</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.setdlopenflags" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the flags used by the interpreter for <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> calls, such as when
the interpreter loads extension modules.  Among other things, this will enable a
lazy resolving of symbols when importing a module, if called as
<code class="docutils literal notranslate"><span class="pre">sys.setdlopenflags(0)</span></code>.  To share symbols across extension modules, call as
<code class="docutils literal notranslate"><span class="pre">sys.setdlopenflags(dl.RTLD_NOW</span> <span class="pre">|</span> <span class="pre">dl.RTLD_GLOBAL)</span></code>.  Symbolic names for the
flag modules can be either found in the <a class="reference internal" href="dl.html#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module, or in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">DLFCN</span></code>
module. If <code class="xref py py-mod docutils literal notranslate"><span class="pre">DLFCN</span></code> is not available, it can be generated from
<code class="file docutils literal notranslate"><span class="pre">/usr/include/dlfcn.h</span></code> using the <strong class="program">h2py</strong> script. Availability:
Unix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.setprofile">
<code class="descclassname">sys.</code><code class="descname">setprofile</code><span class="sig-paren">(</span><em>profilefunc</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.setprofile" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-12">Set the system’s profile function, which allows you to implement a Python source
code profiler in Python.  See chapter <a class="reference internal" href="profile.html#profile"><span class="std std-ref">The Python Profilers</span></a> for more information on the
Python profiler.  The system’s profile function is called similarly to the
system’s trace function (see <a class="reference internal" href="#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">settrace()</span></code></a>), but it is called with different events,
for example it isn’t called for each executed line of code (only on call and return,
but the return event is reported even when an exception has been set). The function is
thread-specific, but there is no way for the profiler to know about context switches between
threads, so it does not make sense to use this in the presence of multiple threads. Also,
its return value is not used, so it can simply return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>Profile functions should have three arguments: <em>frame</em>, <em>event</em>, and
<em>arg</em>. <em>frame</em> is the current stack frame.  <em>event</em> is a string: <code class="docutils literal notranslate"><span class="pre">'call'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'return'</span></code>, <code class="docutils literal notranslate"><span class="pre">'c_call'</span></code>, <code class="docutils literal notranslate"><span class="pre">'c_return'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'c_exception'</span></code>. <em>arg</em> depends
on the event type.</p>
<p>The events have the following meaning:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">'call'</span></code></dt>
<dd>A function is called (or some other code block entered).  The
profile function is called; <em>arg</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'return'</span></code></dt>
<dd>A function (or other code block) is about to return.  The profile
function is called; <em>arg</em> is the value that will be returned, or <code class="docutils literal notranslate"><span class="pre">None</span></code>
if the event is caused by an exception being raised.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'c_call'</span></code></dt>
<dd>A C function is about to be called.  This may be an extension function or
a built-in.  <em>arg</em> is the C function object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'c_return'</span></code></dt>
<dd>A C function has returned. <em>arg</em> is the C function object.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'c_exception'</span></code></dt>
<dd>A C function has raised an exception.  <em>arg</em> is the C function object.</dd>
</dl>
</dd></dl>

<dl class="function">
<dt id="sys.setrecursionlimit">
<code class="descclassname">sys.</code><code class="descname">setrecursionlimit</code><span class="sig-paren">(</span><em>limit</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.setrecursionlimit" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the maximum depth of the Python interpreter stack to <em>limit</em>.  This limit
prevents infinite recursion from causing an overflow of the C stack and crashing
Python.</p>
<p>The highest possible limit is platform-dependent.  A user may need to set the
limit higher when she has a program that requires deep recursion and a platform
that supports a higher limit.  This should be done with care, because a too-high
limit can lead to a crash.</p>
</dd></dl>

<dl class="function">
<dt id="sys.settrace">
<code class="descclassname">sys.</code><code class="descname">settrace</code><span class="sig-paren">(</span><em>tracefunc</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.settrace" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-13">Set the system’s trace function, which allows you to implement a Python
source code debugger in Python.  The function is thread-specific; for a
debugger to support multiple threads, it must be registered using
<a class="reference internal" href="#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">settrace()</span></code></a> for each thread being debugged.</p>
<p>Trace functions should have three arguments: <em>frame</em>, <em>event</em>, and
<em>arg</em>. <em>frame</em> is the current stack frame.  <em>event</em> is a string: <code class="docutils literal notranslate"><span class="pre">'call'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'line'</span></code>, <code class="docutils literal notranslate"><span class="pre">'return'</span></code> or <code class="docutils literal notranslate"><span class="pre">'exception'</span></code>.  <em>arg</em> depends on
the event type.</p>
<p>The trace function is invoked (with <em>event</em> set to <code class="docutils literal notranslate"><span class="pre">'call'</span></code>) whenever a new
local scope is entered; it should return a reference to a local trace
function to be used that scope, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the scope shouldn’t be traced.</p>
<p>The local trace function should return a reference to itself (or to another
function for further tracing in that scope), or <code class="docutils literal notranslate"><span class="pre">None</span></code> to turn off tracing
in that scope.</p>
<p>The events have the following meaning:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">'call'</span></code></dt>
<dd>A function is called (or some other code block entered).  The
global trace function is called; <em>arg</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>; the return value
specifies the local trace function.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'line'</span></code></dt>
<dd>The interpreter is about to execute a new line of code or re-execute the
condition of a loop.  The local trace function is called; <em>arg</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code>; the return value specifies the new local trace function.  See
<code class="file docutils literal notranslate"><span class="pre">Objects/lnotab_notes.txt</span></code> for a detailed explanation of how this
works.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'return'</span></code></dt>
<dd>A function (or other code block) is about to return.  The local trace
function is called; <em>arg</em> is the value that will be returned, or <code class="docutils literal notranslate"><span class="pre">None</span></code>
if the event is caused by an exception being raised.  The trace function’s
return value is ignored.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'exception'</span></code></dt>
<dd>An exception has occurred.  The local trace function is called; <em>arg</em> is a
tuple <code class="docutils literal notranslate"><span class="pre">(exception,</span> <span class="pre">value,</span> <span class="pre">traceback)</span></code>; the return value specifies the
new local trace function.</dd>
</dl>
<p>Note that as an exception is propagated down the chain of callers, an
<code class="docutils literal notranslate"><span class="pre">'exception'</span></code> event is generated at each level.</p>
<p>For more information on code and frame objects, refer to <a class="reference internal" href="../reference/datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> The <a class="reference internal" href="#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">settrace()</span></code></a> function is intended only for implementing debuggers,
profilers, coverage tools and the like.  Its behavior is part of the
implementation platform, rather than part of the language definition, and
thus may not be available in all Python implementations.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="sys.settscdump">
<code class="descclassname">sys.</code><code class="descname">settscdump</code><span class="sig-paren">(</span><em>on_flag</em><span class="sig-paren">)</span><a class="headerlink" href="#sys.settscdump" title="Permalink to this definition">¶</a></dt>
<dd><p>Activate dumping of VM measurements using the Pentium timestamp counter, if
<em>on_flag</em> is true. Deactivate these dumps if <em>on_flag</em> is off. The function is
available only if Python was compiled with <code class="docutils literal notranslate"><span class="pre">--with-tsc</span></code>. To understand
the output of this dump, read <code class="file docutils literal notranslate"><span class="pre">Python/ceval.c</span></code> in the Python sources.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> This function is intimately bound to CPython implementation details and
thus not likely to be implemented elsewhere.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.stdin">
<code class="descclassname">sys.</code><code class="descname">stdin</code><a class="headerlink" href="#sys.stdin" title="Permalink to this definition">¶</a></dt>
<dt id="sys.stdout">
<code class="descclassname">sys.</code><code class="descname">stdout</code><a class="headerlink" href="#sys.stdout" title="Permalink to this definition">¶</a></dt>
<dt id="sys.stderr">
<code class="descclassname">sys.</code><code class="descname">stderr</code><a class="headerlink" href="#sys.stderr" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-14">File objects corresponding to the interpreter’s standard input, output and error
streams.  <code class="docutils literal notranslate"><span class="pre">stdin</span></code> is used for all interpreter input except for scripts but
including calls to <a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> and <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a>.  <code class="docutils literal notranslate"><span class="pre">stdout</span></code> is used for
the output of <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> and <a class="reference internal" href="../glossary.html#term-expression"><span class="xref std std-term">expression</span></a> statements and for the
prompts of <a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> and <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a>. The interpreter’s own prompts
and (almost all of) its error messages go to <code class="docutils literal notranslate"><span class="pre">stderr</span></code>.  <code class="docutils literal notranslate"><span class="pre">stdout</span></code> and
<code class="docutils literal notranslate"><span class="pre">stderr</span></code> needn’t be built-in file objects: any object is acceptable as long
as it has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method that takes a string argument.  (Changing these
objects doesn’t affect the standard I/O streams of processes executed by
<a class="reference internal" href="os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a> or the <code class="xref py py-func docutils literal notranslate"><span class="pre">exec*()</span></code> family of functions in
the <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module.)</p>
</dd></dl>

<dl class="data">
<dt id="sys.__stdin__">
<code class="descclassname">sys.</code><code class="descname">__stdin__</code><a class="headerlink" href="#sys.__stdin__" title="Permalink to this definition">¶</a></dt>
<dt id="sys.__stdout__">
<code class="descclassname">sys.</code><code class="descname">__stdout__</code><a class="headerlink" href="#sys.__stdout__" title="Permalink to this definition">¶</a></dt>
<dt id="sys.__stderr__">
<code class="descclassname">sys.</code><code class="descname">__stderr__</code><a class="headerlink" href="#sys.__stderr__" title="Permalink to this definition">¶</a></dt>
<dd><p>These objects contain the original values of <code class="docutils literal notranslate"><span class="pre">stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">stderr</span></code> and
<code class="docutils literal notranslate"><span class="pre">stdout</span></code> at the start of the program.  They are used during finalization,
and could be useful to print to the actual standard stream no matter if the
<code class="docutils literal notranslate"><span class="pre">sys.std*</span></code> object has been redirected.</p>
<p>It can also be used to restore the actual files to known working file objects
in case they have been overwritten with a broken object.  However, the
preferred way to do this is to explicitly save the previous stream before
replacing it, and restore the saved object.</p>
</dd></dl>

<dl class="data">
<dt id="sys.subversion">
<code class="descclassname">sys.</code><code class="descname">subversion</code><a class="headerlink" href="#sys.subversion" title="Permalink to this definition">¶</a></dt>
<dd><p>A triple (repo, branch, version) representing the Subversion information of the
Python interpreter. <em>repo</em> is the name of the repository, <code class="docutils literal notranslate"><span class="pre">'CPython'</span></code>.
<em>branch</em> is a string of one of the forms <code class="docutils literal notranslate"><span class="pre">'trunk'</span></code>, <code class="docutils literal notranslate"><span class="pre">'branches/name'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'tags/name'</span></code>. <em>version</em> is the output of <code class="docutils literal notranslate"><span class="pre">svnversion</span></code>, if the interpreter
was built from a Subversion checkout; it contains the revision number (range)
and possibly a trailing ‘M’ if there were local modifications. If the tree was
exported (or svnversion was not available), it is the revision of
<code class="docutils literal notranslate"><span class="pre">Include/patchlevel.h</span></code> if the branch is a tag. Otherwise, it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Python is now <a class="reference external" href="https://docs.python.org/devguide/">developed</a> using
Mercurial.  In recent Python 2.7 bugfix releases, <a class="reference internal" href="#sys.subversion" title="sys.subversion"><code class="xref py py-data docutils literal notranslate"><span class="pre">subversion</span></code></a>
therefore contains placeholder information.  It is removed in Python
3.3.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.tracebacklimit">
<code class="descclassname">sys.</code><code class="descname">tracebacklimit</code><a class="headerlink" href="#sys.tracebacklimit" title="Permalink to this definition">¶</a></dt>
<dd><p>When this variable is set to an integer value, it determines the maximum number
of levels of traceback information printed when an unhandled exception occurs.
The default is <code class="docutils literal notranslate"><span class="pre">1000</span></code>.  When set to <code class="docutils literal notranslate"><span class="pre">0</span></code> or less, all traceback information
is suppressed and only the exception type and value are printed.</p>
</dd></dl>

<dl class="data">
<dt id="sys.version">
<code class="descclassname">sys.</code><code class="descname">version</code><a class="headerlink" href="#sys.version" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the version number of the Python interpreter plus additional
information on the build number and compiler used.  This string is displayed
when the interactive interpreter is started.  Do not extract version information
out of it, rather, use <a class="reference internal" href="#sys.version_info" title="sys.version_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">version_info</span></code></a> and the functions provided by the
<a class="reference internal" href="platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> module.</p>
</dd></dl>

<dl class="data">
<dt id="sys.api_version">
<code class="descclassname">sys.</code><code class="descname">api_version</code><a class="headerlink" href="#sys.api_version" title="Permalink to this definition">¶</a></dt>
<dd><p>The C API version for this interpreter.  Programmers may find this useful when
debugging version conflicts between Python and extension modules.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.version_info">
<code class="descclassname">sys.</code><code class="descname">version_info</code><a class="headerlink" href="#sys.version_info" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple containing the five components of the version number: <em>major</em>, <em>minor</em>,
<em>micro</em>, <em>releaselevel</em>, and <em>serial</em>.  All values except <em>releaselevel</em> are
integers; the release level is <code class="docutils literal notranslate"><span class="pre">'alpha'</span></code>, <code class="docutils literal notranslate"><span class="pre">'beta'</span></code>, <code class="docutils literal notranslate"><span class="pre">'candidate'</span></code>, or
<code class="docutils literal notranslate"><span class="pre">'final'</span></code>.  The <code class="docutils literal notranslate"><span class="pre">version_info</span></code> value corresponding to the Python version 2.0
is <code class="docutils literal notranslate"><span class="pre">(2,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">'final',</span> <span class="pre">0)</span></code>.  The components can also be accessed by name,
so <code class="docutils literal notranslate"><span class="pre">sys.version_info[0]</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">sys.version_info.major</span></code>
and so on.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added named component attributes</p>
</div>
</dd></dl>

<dl class="data">
<dt id="sys.warnoptions">
<code class="descclassname">sys.</code><code class="descname">warnoptions</code><a class="headerlink" href="#sys.warnoptions" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an implementation detail of the warnings framework; do not modify this
value.  Refer to the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module for more information on the warnings
framework.</p>
</dd></dl>

<dl class="data">
<dt id="sys.winver">
<code class="descclassname">sys.</code><code class="descname">winver</code><a class="headerlink" href="#sys.winver" title="Permalink to this definition">¶</a></dt>
<dd><p>The version number used to form registry keys on Windows platforms. This is
stored as string resource 1000 in the Python DLL.  The value is normally the
first three characters of <a class="reference internal" href="#sys.version" title="sys.version"><code class="xref py py-const docutils literal notranslate"><span class="pre">version</span></code></a>.  It is provided in the <a class="reference internal" href="#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>
module for informational purposes; modifying this value has no effect on the
registry keys used by Python. Availability: Windows.</p>
</dd></dl>

<p class="rubric">Citations</p>
<table class="docutils citation" frame="void" id="c99" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[C99]</a></td><td>ISO/IEC 9899:1999.  “Programming languages – C.”  A public draft of this standard is available at <a class="reference external" href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf">http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf</a>.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="python.html"
                        title="previous chapter">28. Python Runtime Services</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="sysconfig.html"
                        title="next chapter">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sys.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="sysconfig.html" title="28.2. sysconfig — Provide access to Python’s configuration information"
             >next</a> |</li>
        <li class="right" >
          <a href="python.html" title="28. Python Runtime Services"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\'���f�fhtml/library/sysconfig.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.2. sysconfig — Provide access to Python’s configuration information &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.3. __builtin__ — Built-in objects" href="__builtin__.html" />
    <link rel="prev" title="28.1. sys — System-specific parameters and functions" href="sys.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/sysconfig.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__builtin__.html" title="28.3. __builtin__ — Built-in objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sys.html" title="28.1. sys — System-specific parameters and functions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-sysconfig">
<span id="sysconfig-provide-access-to-python-s-configuration-information"></span><h1>28.2. <a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> — Provide access to Python’s configuration information<a class="headerlink" href="#module-sysconfig" title="Permalink to this headline">¶</a></h1>
<div class="versionadded" id="index-0">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/sysconfig.py">Lib/sysconfig.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> module provides access to Python’s configuration
information like the list of installation paths and the configuration variables
relevant for the current platform.</p>
<div class="section" id="configuration-variables">
<h2>28.2.1. Configuration variables<a class="headerlink" href="#configuration-variables" title="Permalink to this headline">¶</a></h2>
<p>A Python distribution contains a <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code> and a <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code>
header file that are necessary to build both the Python binary itself and
third-party C extensions compiled using <a class="reference internal" href="distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a>.</p>
<p><a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> puts all variables found in these files in a dictionary that
can be accessed using <a class="reference internal" href="#sysconfig.get_config_vars" title="sysconfig.get_config_vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_vars()</span></code></a> or <a class="reference internal" href="#sysconfig.get_config_var" title="sysconfig.get_config_var"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_var()</span></code></a>.</p>
<p>Notice that on Windows, it’s a much smaller set.</p>
<dl class="function">
<dt id="sysconfig.get_config_vars">
<code class="descclassname">sysconfig.</code><code class="descname">get_config_vars</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_config_vars" title="Permalink to this definition">¶</a></dt>
<dd><p>With no arguments, return a dictionary of all configuration variables
relevant for the current platform.</p>
<p>With arguments, return a list of values that result from looking up each
argument in the configuration variable dictionary.</p>
<p>For each argument, if the value is not found, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_config_var">
<code class="descclassname">sysconfig.</code><code class="descname">get_config_var</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_config_var" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of a single variable <em>name</em>. Equivalent to
<code class="docutils literal notranslate"><span class="pre">get_config_vars().get(name)</span></code>.</p>
<p>If <em>name</em> is not found, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<p>Example of usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sysconfig</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">&#39;Py_ENABLE_SHARED&#39;</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_var</span><span class="p">(</span><span class="s1">&#39;LIBDIR&#39;</span><span class="p">)</span>
<span class="go">&#39;/usr/local/lib&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sysconfig</span><span class="o">.</span><span class="n">get_config_vars</span><span class="p">(</span><span class="s1">&#39;AR&#39;</span><span class="p">,</span> <span class="s1">&#39;CXX&#39;</span><span class="p">)</span>
<span class="go">[&#39;ar&#39;, &#39;g++&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="installation-paths">
<h2>28.2.2. Installation paths<a class="headerlink" href="#installation-paths" title="Permalink to this headline">¶</a></h2>
<p>Python uses an installation scheme that differs depending on the platform and on
the installation options.  These schemes are stored in <a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> under
unique identifiers based on the value returned by <a class="reference internal" href="os.html#os.name" title="os.name"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.name</span></code></a>.</p>
<p>Every new component that is installed using <a class="reference internal" href="distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> or a
Distutils-based system will follow the same scheme to copy its file in the right
places.</p>
<p>Python currently supports seven schemes:</p>
<ul class="simple">
<li><em>posix_prefix</em>: scheme for Posix platforms like Linux or Mac OS X.  This is
the default scheme used when Python or a component is installed.</li>
<li><em>posix_home</em>: scheme for Posix platforms used when a <em>home</em> option is used
upon installation.  This scheme is used when a component is installed through
Distutils with a specific home prefix.</li>
<li><em>posix_user</em>: scheme for Posix platforms used when a component is installed
through Distutils and the <em>user</em> option is used.  This scheme defines paths
located under the user home directory.</li>
<li><em>nt</em>: scheme for NT platforms like Windows.</li>
<li><em>nt_user</em>: scheme for NT platforms, when the <em>user</em> option is used.</li>
<li><em>os2</em>: scheme for OS/2 platforms.</li>
<li><em>os2_home</em>: scheme for OS/2 platforms, when the <em>user</em> option is used.</li>
</ul>
<p>Each scheme is itself composed of a series of paths and each path has a unique
identifier.  Python currently uses eight paths:</p>
<ul class="simple">
<li><em>stdlib</em>: directory containing the standard Python library files that are not
platform-specific.</li>
<li><em>platstdlib</em>: directory containing the standard Python library files that are
platform-specific.</li>
<li><em>platlib</em>: directory for site-specific, platform-specific files.</li>
<li><em>purelib</em>: directory for site-specific, non-platform-specific files.</li>
<li><em>include</em>: directory for non-platform-specific header files.</li>
<li><em>platinclude</em>: directory for platform-specific header files.</li>
<li><em>scripts</em>: directory for script files.</li>
<li><em>data</em>: directory for data files.</li>
</ul>
<p><a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> provides some functions to determine these paths.</p>
<dl class="function">
<dt id="sysconfig.get_scheme_names">
<code class="descclassname">sysconfig.</code><code class="descname">get_scheme_names</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_scheme_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing all schemes currently supported in
<a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_path_names">
<code class="descclassname">sysconfig.</code><code class="descname">get_path_names</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_path_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a tuple containing all path names currently supported in
<a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_path">
<code class="descclassname">sysconfig.</code><code class="descname">get_path</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>scheme</em><span class="optional">[</span>, <em>vars</em><span class="optional">[</span>, <em>expand</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_path" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an installation path corresponding to the path <em>name</em>, from the
install scheme named <em>scheme</em>.</p>
<p><em>name</em> has to be a value from the list returned by <a class="reference internal" href="#sysconfig.get_path_names" title="sysconfig.get_path_names"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_path_names()</span></code></a>.</p>
<p><a class="reference internal" href="#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> stores installation paths corresponding to each path name,
for each platform, with variables to be expanded.  For instance the <em>stdlib</em>
path for the <em>nt</em> scheme is: <code class="docutils literal notranslate"><span class="pre">{base}/Lib</span></code>.</p>
<p><a class="reference internal" href="#sysconfig.get_path" title="sysconfig.get_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_path()</span></code></a> will use the variables returned by <a class="reference internal" href="#sysconfig.get_config_vars" title="sysconfig.get_config_vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_vars()</span></code></a>
to expand the path.  All variables have default values for each platform so
one may call this function and get the default value.</p>
<p>If <em>scheme</em> is provided, it must be a value from the list returned by
<a class="reference internal" href="#sysconfig.get_scheme_names" title="sysconfig.get_scheme_names"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_scheme_names()</span></code></a>.  Otherwise, the default scheme for the current
platform is used.</p>
<p>If <em>vars</em> is provided, it must be a dictionary of variables that will update
the dictionary return by <a class="reference internal" href="#sysconfig.get_config_vars" title="sysconfig.get_config_vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_vars()</span></code></a>.</p>
<p>If <em>expand</em> is set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, the path will not be expanded using the
variables.</p>
<p>If <em>name</em> is not found, return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_paths">
<code class="descclassname">sysconfig.</code><code class="descname">get_paths</code><span class="sig-paren">(</span><span class="optional">[</span><em>scheme</em><span class="optional">[</span>, <em>vars</em><span class="optional">[</span>, <em>expand</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_paths" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a dictionary containing all installation paths corresponding to an
installation scheme. See <a class="reference internal" href="#sysconfig.get_path" title="sysconfig.get_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_path()</span></code></a> for more information.</p>
<p>If <em>scheme</em> is not provided, will use the default scheme for the current
platform.</p>
<p>If <em>vars</em> is provided, it must be a dictionary of variables that will
update the dictionary used to expand the paths.</p>
<p>If <em>expand</em> is set to false, the paths will not be expanded.</p>
<p>If <em>scheme</em> is not an existing scheme, <a class="reference internal" href="#sysconfig.get_paths" title="sysconfig.get_paths"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_paths()</span></code></a> will raise a
<a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="other-functions">
<h2>28.2.3. Other functions<a class="headerlink" href="#other-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="sysconfig.get_python_version">
<code class="descclassname">sysconfig.</code><code class="descname">get_python_version</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_python_version" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <code class="docutils literal notranslate"><span class="pre">MAJOR.MINOR</span></code> Python version number as a string.  Similar to
<code class="docutils literal notranslate"><span class="pre">sys.version[:3]</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_platform">
<code class="descclassname">sysconfig.</code><code class="descname">get_platform</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_platform" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string that identifies the current platform.</p>
<p>This is used mainly to distinguish platform-specific build directories and
platform-specific built distributions.  Typically includes the OS name and
version and the architecture (as supplied by <a class="reference internal" href="os.html#os.uname" title="os.uname"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.uname()</span></code></a>), although the
exact information included depends on the OS; e.g. for IRIX the architecture
isn’t particularly important (IRIX only runs on SGI hardware), but for Linux
the kernel version isn’t particularly important.</p>
<p>Examples of returned values:</p>
<ul class="simple">
<li>linux-i586</li>
<li>linux-alpha (?)</li>
<li>solaris-2.6-sun4u</li>
<li>irix-5.3</li>
<li>irix64-6.2</li>
</ul>
<p>Windows will return one of:</p>
<ul class="simple">
<li>win-amd64 (64bit Windows on AMD64, aka x86_64, Intel64, and EM64T)</li>
<li>win-ia64 (64bit Windows on Itanium)</li>
<li>win32 (all others - specifically, sys.platform is returned)</li>
</ul>
<p>Mac OS X can return:</p>
<ul class="simple">
<li>macosx-10.6-ppc</li>
<li>macosx-10.4-ppc64</li>
<li>macosx-10.3-i386</li>
<li>macosx-10.4-fat</li>
</ul>
<p>For other non-POSIX platforms, currently just returns <a class="reference internal" href="sys.html#sys.platform" title="sys.platform"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.platform</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.is_python_build">
<code class="descclassname">sysconfig.</code><code class="descname">is_python_build</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.is_python_build" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the current Python installation was built from source.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.parse_config_h">
<code class="descclassname">sysconfig.</code><code class="descname">parse_config_h</code><span class="sig-paren">(</span><em>fp</em><span class="optional">[</span>, <em>vars</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.parse_config_h" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a <code class="file docutils literal notranslate"><span class="pre">config.h</span></code>-style file.</p>
<p><em>fp</em> is a file-like object pointing to the <code class="file docutils literal notranslate"><span class="pre">config.h</span></code>-like file.</p>
<p>A dictionary containing name/value pairs is returned.  If an optional
dictionary is passed in as the second argument, it is used instead of a new
dictionary, and updated with the values read in the file.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_config_h_filename">
<code class="descclassname">sysconfig.</code><code class="descname">get_config_h_filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_config_h_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the path of <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="sysconfig.get_makefile_filename">
<code class="descclassname">sysconfig.</code><code class="descname">get_makefile_filename</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#sysconfig.get_makefile_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the path of <code class="file docutils literal notranslate"><span class="pre">Makefile</span></code>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a><ul>
<li><a class="reference internal" href="#configuration-variables">28.2.1. Configuration variables</a></li>
<li><a class="reference internal" href="#installation-paths">28.2.2. Installation paths</a></li>
<li><a class="reference internal" href="#other-functions">28.2.3. Other functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sys.html"
                        title="previous chapter">28.1. <code class="docutils literal notranslate"><span class="pre">sys</span></code> — System-specific parameters and functions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="__builtin__.html"
                        title="next chapter">28.3. <code class="docutils literal notranslate"><span class="pre">__builtin__</span></code> — Built-in objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/sysconfig.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__builtin__.html" title="28.3. __builtin__ — Built-in objects"
             >next</a> |</li>
        <li class="right" >
          <a href="sys.html" title="28.1. sys — System-specific parameters and functions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\E��oMMhtml/library/syslog.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.15. syslog — Unix syslog library routines &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.16. commands — Utilities for running commands" href="commands.html" />
    <link rel="prev" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)" href="nis.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/syslog.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="commands.html" title="36.16. commands — Utilities for running commands"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="nis.html" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-syslog">
<span id="syslog-unix-syslog-library-routines"></span><h1>36.15. <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">syslog</span></code></a> — Unix syslog library routines<a class="headerlink" href="#module-syslog" title="Permalink to this headline">¶</a></h1>
<p>This module provides an interface to the Unix <code class="docutils literal notranslate"><span class="pre">syslog</span></code> library routines.
Refer to the Unix manual pages for a detailed description of the <code class="docutils literal notranslate"><span class="pre">syslog</span></code>
facility.</p>
<p>This module wraps the system <code class="docutils literal notranslate"><span class="pre">syslog</span></code> family of routines.  A pure Python
library that can speak to a syslog server is available in the
<a class="reference internal" href="logging.handlers.html#module-logging.handlers" title="logging.handlers: Handlers for the logging module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging.handlers</span></code></a> module as <code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code>.</p>
<p>The module defines the following functions:</p>
<dl class="function">
<dt id="syslog.syslog">
<code class="descclassname">syslog.</code><code class="descname">syslog</code><span class="sig-paren">(</span><em>message</em><span class="sig-paren">)</span><a class="headerlink" href="#syslog.syslog" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descclassname">syslog.</code><code class="descname">syslog</code><span class="sig-paren">(</span><em>priority</em>, <em>message</em><span class="sig-paren">)</span></dt>
<dd><p>Send the string <em>message</em> to the system logger.  A trailing newline is added
if necessary.  Each message is tagged with a priority composed of a
<em>facility</em> and a <em>level</em>.  The optional <em>priority</em> argument, which defaults
to <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_INFO</span></code>, determines the message priority.  If the facility is
not encoded in <em>priority</em> using logical-or (<code class="docutils literal notranslate"><span class="pre">LOG_INFO</span> <span class="pre">|</span> <span class="pre">LOG_USER</span></code>), the
value given in the <a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> call is used.</p>
<p>If <a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> has not been called prior to the call to <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">syslog()</span></code></a>,
<code class="docutils literal notranslate"><span class="pre">openlog()</span></code> will be called with no arguments.</p>
</dd></dl>

<dl class="function">
<dt id="syslog.openlog">
<code class="descclassname">syslog.</code><code class="descname">openlog</code><span class="sig-paren">(</span><span class="optional">[</span><em>ident</em><span class="optional">[</span>, <em>logoption</em><span class="optional">[</span>, <em>facility</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#syslog.openlog" title="Permalink to this definition">¶</a></dt>
<dd><p>Logging options of subsequent <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">syslog()</span></code></a> calls can be set by calling
<a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a>.  <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">syslog()</span></code></a> will call <a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> with no arguments
if the log is not currently open.</p>
<p>The optional <em>ident</em> keyword argument is a string which is prepended to every
message, and defaults to <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> with leading path components
stripped.  The optional <em>logoption</em> keyword argument (default is 0) is a bit
field – see below for possible values to combine.  The optional <em>facility</em>
keyword argument (default is <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_USER</span></code>) sets the default facility for
messages which do not have a facility explicitly encoded.</p>
</dd></dl>

<dl class="function">
<dt id="syslog.closelog">
<code class="descclassname">syslog.</code><code class="descname">closelog</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#syslog.closelog" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the syslog module values and call the system library <code class="docutils literal notranslate"><span class="pre">closelog()</span></code>.</p>
<p>This causes the module to behave as it does when initially imported.  For
example, <a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> will be called on the first <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">syslog()</span></code></a> call (if
<a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> hasn’t already been called), and <em>ident</em> and other
<a class="reference internal" href="#syslog.openlog" title="syslog.openlog"><code class="xref py py-func docutils literal notranslate"><span class="pre">openlog()</span></code></a> parameters are reset to defaults.</p>
</dd></dl>

<dl class="function">
<dt id="syslog.setlogmask">
<code class="descclassname">syslog.</code><code class="descname">setlogmask</code><span class="sig-paren">(</span><em>maskpri</em><span class="sig-paren">)</span><a class="headerlink" href="#syslog.setlogmask" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the priority mask to <em>maskpri</em> and return the previous mask value.  Calls
to <a class="reference internal" href="#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">syslog()</span></code></a> with a priority level not set in <em>maskpri</em> are ignored.
The default is to log all priorities.  The function <code class="docutils literal notranslate"><span class="pre">LOG_MASK(pri)</span></code>
calculates the mask for the individual priority <em>pri</em>.  The function
<code class="docutils literal notranslate"><span class="pre">LOG_UPTO(pri)</span></code> calculates the mask for all priorities up to and including
<em>pri</em>.</p>
</dd></dl>

<p>The module defines the following constants:</p>
<dl class="docutils">
<dt>Priority levels (high to low):</dt>
<dd><code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_EMERG</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_ALERT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_CRIT</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_ERR</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_NOTICE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_INFO</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_DEBUG</span></code>.</dd>
<dt>Facilities:</dt>
<dd><code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_KERN</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_USER</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_MAIL</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_DAEMON</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_AUTH</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_LPR</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_NEWS</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_UUCP</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_CRON</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_SYSLOG</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_LOCAL0</span></code> to
<code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_LOCAL7</span></code>.</dd>
<dt>Log options:</dt>
<dd><code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_PID</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_CONS</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_NDELAY</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_NOWAIT</span></code>
and <code class="xref py py-const docutils literal notranslate"><span class="pre">LOG_PERROR</span></code> if defined in <code class="docutils literal notranslate"><span class="pre">&lt;syslog.h&gt;</span></code>.</dd>
</dl>
<div class="section" id="examples">
<h2>36.15.1. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<div class="section" id="simple-example">
<h3>36.15.1.1. Simple example<a class="headerlink" href="#simple-example" title="Permalink to this headline">¶</a></h3>
<p>A simple set of examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">syslog</span>

<span class="n">syslog</span><span class="o">.</span><span class="n">syslog</span><span class="p">(</span><span class="s1">&#39;Processing started&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">error</span><span class="p">:</span>
    <span class="n">syslog</span><span class="o">.</span><span class="n">syslog</span><span class="p">(</span><span class="n">syslog</span><span class="o">.</span><span class="n">LOG_ERR</span><span class="p">,</span> <span class="s1">&#39;Processing started&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>An example of setting some log options, these would include the process ID in
logged messages, and write the messages to the destination facility used for
mail logging:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">syslog</span><span class="o">.</span><span class="n">openlog</span><span class="p">(</span><span class="n">logoption</span><span class="o">=</span><span class="n">syslog</span><span class="o">.</span><span class="n">LOG_PID</span><span class="p">,</span> <span class="n">facility</span><span class="o">=</span><span class="n">syslog</span><span class="o">.</span><span class="n">LOG_MAIL</span><span class="p">)</span>
<span class="n">syslog</span><span class="o">.</span><span class="n">syslog</span><span class="p">(</span><span class="s1">&#39;E-mail processing initiated...&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a><ul>
<li><a class="reference internal" href="#examples">36.15.1. Examples</a><ul>
<li><a class="reference internal" href="#simple-example">36.15.1.1. Simple example</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="nis.html"
                        title="previous chapter">36.14. <code class="docutils literal notranslate"><span class="pre">nis</span></code> — Interface to Sun’s NIS (Yellow Pages)</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="commands.html"
                        title="next chapter">36.16. <code class="docutils literal notranslate"><span class="pre">commands</span></code> — Utilities for running commands</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/syslog.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="commands.html" title="36.16. commands — Utilities for running commands"
             >next</a> |</li>
        <li class="right" >
          <a href="nis.html" title="36.14. nis — Interface to Sun’s NIS (Yellow Pages)"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\&9�$�,�,html/library/tabnanny.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.8. tabnanny — Detection of ambiguous indentation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.9. pyclbr — Python class browser support" href="pyclbr.html" />
    <link rel="prev" title="32.7. tokenize — Tokenizer for Python source" href="tokenize.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tabnanny.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyclbr.html" title="32.9. pyclbr — Python class browser support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tokenize.html" title="32.7. tokenize — Tokenizer for Python source"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-tabnanny">
<span id="tabnanny-detection-of-ambiguous-indentation"></span><h1>32.8. <a class="reference internal" href="#module-tabnanny" title="tabnanny: Tool for detecting white space related problems in Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tabnanny</span></code></a> — Detection of ambiguous indentation<a class="headerlink" href="#module-tabnanny" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/tabnanny.py">Lib/tabnanny.py</a></p>
<hr class="docutils" />
<p>For the time being this module is intended to be called as a script. However it
is possible to import it into an IDE and use the function <a class="reference internal" href="#tabnanny.check" title="tabnanny.check"><code class="xref py py-func docutils literal notranslate"><span class="pre">check()</span></code></a>
described below.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The API provided by this module is likely to change in future releases; such
changes may not be backward compatible.</p>
</div>
<dl class="function">
<dt id="tabnanny.check">
<code class="descclassname">tabnanny.</code><code class="descname">check</code><span class="sig-paren">(</span><em>file_or_dir</em><span class="sig-paren">)</span><a class="headerlink" href="#tabnanny.check" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>file_or_dir</em> is a directory and not a symbolic link, then recursively
descend the directory tree named by <em>file_or_dir</em>, checking all <code class="file docutils literal notranslate"><span class="pre">.py</span></code>
files along the way.  If <em>file_or_dir</em> is an ordinary Python source file, it is
checked for whitespace related problems.  The diagnostic messages are written to
standard output using the print statement.</p>
</dd></dl>

<dl class="data">
<dt id="tabnanny.verbose">
<code class="descclassname">tabnanny.</code><code class="descname">verbose</code><a class="headerlink" href="#tabnanny.verbose" title="Permalink to this definition">¶</a></dt>
<dd><p>Flag indicating whether to print verbose messages. This is incremented by the
<code class="docutils literal notranslate"><span class="pre">-v</span></code> option if called as a script.</p>
</dd></dl>

<dl class="data">
<dt id="tabnanny.filename_only">
<code class="descclassname">tabnanny.</code><code class="descname">filename_only</code><a class="headerlink" href="#tabnanny.filename_only" title="Permalink to this definition">¶</a></dt>
<dd><p>Flag indicating whether to print only the filenames of files containing
whitespace related problems.  This is set to true by the <code class="docutils literal notranslate"><span class="pre">-q</span></code> option if called
as a script.</p>
</dd></dl>

<dl class="exception">
<dt id="tabnanny.NannyNag">
<em class="property">exception </em><code class="descclassname">tabnanny.</code><code class="descname">NannyNag</code><a class="headerlink" href="#tabnanny.NannyNag" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised by <a class="reference internal" href="#tabnanny.process_tokens" title="tabnanny.process_tokens"><code class="xref py py-func docutils literal notranslate"><span class="pre">process_tokens()</span></code></a> if detecting an ambiguous indent. Captured and
handled in <a class="reference internal" href="#tabnanny.check" title="tabnanny.check"><code class="xref py py-func docutils literal notranslate"><span class="pre">check()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="tabnanny.process_tokens">
<code class="descclassname">tabnanny.</code><code class="descname">process_tokens</code><span class="sig-paren">(</span><em>tokens</em><span class="sig-paren">)</span><a class="headerlink" href="#tabnanny.process_tokens" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is used by <a class="reference internal" href="#tabnanny.check" title="tabnanny.check"><code class="xref py py-func docutils literal notranslate"><span class="pre">check()</span></code></a> to process tokens generated by the
<a class="reference internal" href="tokenize.html#module-tokenize" title="tokenize: Lexical scanner for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code></a> module.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="tokenize.html#module-tokenize" title="tokenize: Lexical scanner for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code></a></dt>
<dd>Lexical scanner for Python source code.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="tokenize.html"
                        title="previous chapter">32.7. <code class="docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pyclbr.html"
                        title="next chapter">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tabnanny.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyclbr.html" title="32.9. pyclbr — Python class browser support"
             >next</a> |</li>
        <li class="right" >
          <a href="tokenize.html" title="32.7. tokenize — Tokenizer for Python source"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\e��ۘZ�Zhtml/library/tarfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12.5. tarfile — Read and write tar archive files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13. File Formats" href="fileformats.html" />
    <link rel="prev" title="12.4. zipfile — Work with ZIP archives" href="zipfile.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tarfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fileformats.html" title="13. File Formats"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="zipfile.html" title="12.4. zipfile — Work with ZIP archives"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" accesskey="U">12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-tarfile">
<span id="tarfile-read-and-write-tar-archive-files"></span><h1>12.5. <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> — Read and write tar archive files<a class="headerlink" href="#module-tarfile" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/tarfile.py">Lib/tarfile.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module makes it possible to read and write tar
archives, including those using gzip or bz2 compression.
Use the <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module to read or write <code class="file docutils literal notranslate"><span class="pre">.zip</span></code> files, or the
higher-level functions in <a class="reference internal" href="shutil.html#archiving-operations"><span class="std std-ref">shutil</span></a>.</p>
<p>Some facts and figures:</p>
<ul>
<li><p class="first">reads and writes <a class="reference internal" href="gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> and <a class="reference internal" href="bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> compressed archives
if the respective modules are available.</p>
</li>
<li><p class="first">read/write support for the POSIX.1-1988 (ustar) format.</p>
</li>
<li><p class="first">read/write support for the GNU tar format including <em>longname</em> and <em>longlink</em>
extensions, read-only support for the <em>sparse</em> extension.</p>
</li>
<li><p class="first">read/write support for the POSIX.1-2001 (pax) format.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</li>
<li><p class="first">handles directories, regular files, hardlinks, symbolic links, fifos,
character devices and block devices and is able to acquire and restore file
information like timestamp, access permissions and owner.</p>
</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Handling of multi-stream bzip2 files is not supported.  Modules such as
<a class="reference external" href="https://github.com/nvawda/bz2file">bz2file</a> let you overcome this.</p>
</div>
<dl class="function">
<dt id="tarfile.open">
<code class="descclassname">tarfile.</code><code class="descname">open</code><span class="sig-paren">(</span><em>name=None</em>, <em>mode='r'</em>, <em>fileobj=None</em>, <em>bufsize=10240</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> object for the pathname <em>name</em>. For detailed
information on <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> objects and the keyword arguments that are
allowed, see <a class="reference internal" href="#tarfile-objects"><span class="std std-ref">TarFile Objects</span></a>.</p>
<p><em>mode</em> has to be a string of the form <code class="docutils literal notranslate"><span class="pre">'filemode[:compression]'</span></code>, it defaults
to <code class="docutils literal notranslate"><span class="pre">'r'</span></code>. Here is a full list of mode combinations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">mode</th>
<th class="head">action</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r'</span> <span class="pre">or</span> <span class="pre">'r:*'</span></code></td>
<td>Open for reading with transparent
compression (recommended).</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'r:'</span></code></td>
<td>Open for reading exclusively without
compression.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r:gz'</span></code></td>
<td>Open for reading with gzip compression.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'r:bz2'</span></code></td>
<td>Open for reading with bzip2 compression.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'a'</span> <span class="pre">or</span> <span class="pre">'a:'</span></code></td>
<td>Open for appending with no compression. The
file is created if it does not exist.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w'</span> <span class="pre">or</span> <span class="pre">'w:'</span></code></td>
<td>Open for uncompressed writing.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'w:gz'</span></code></td>
<td>Open for gzip compressed writing.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w:bz2'</span></code></td>
<td>Open for bzip2 compressed writing.</td>
</tr>
</tbody>
</table>
<p>Note that <code class="docutils literal notranslate"><span class="pre">'a:gz'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a:bz2'</span></code> is not possible. If <em>mode</em> is not suitable
to open a certain (compressed) file for reading, <a class="reference internal" href="#tarfile.ReadError" title="tarfile.ReadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ReadError</span></code></a> is raised. Use
<em>mode</em> <code class="docutils literal notranslate"><span class="pre">'r'</span></code> to avoid this.  If a compression method is not supported,
<a class="reference internal" href="#tarfile.CompressionError" title="tarfile.CompressionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CompressionError</span></code></a> is raised.</p>
<p>If <em>fileobj</em> is specified, it is used as an alternative to a file object opened
for <em>name</em>. It is supposed to be at position 0.</p>
<p>For modes <code class="docutils literal notranslate"><span class="pre">'w:gz'</span></code>, <code class="docutils literal notranslate"><span class="pre">'r:gz'</span></code>, <code class="docutils literal notranslate"><span class="pre">'w:bz2'</span></code>, <code class="docutils literal notranslate"><span class="pre">'r:bz2'</span></code>, <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">tarfile.open()</span></code></a>
accepts the keyword argument <em>compresslevel</em> (default <code class="docutils literal notranslate"><span class="pre">9</span></code>) to
specify the compression level of the file.</p>
<p>For special purposes, there is a second format for <em>mode</em>:
<code class="docutils literal notranslate"><span class="pre">'filemode|[compression]'</span></code>.  <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">tarfile.open()</span></code></a> will return a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a>
object that processes its data as a stream of blocks.  No random seeking will
be done on the file. If given, <em>fileobj</em> may be any object that has a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method (depending on the <em>mode</em>). <em>bufsize</em>
specifies the blocksize and defaults to <code class="docutils literal notranslate"><span class="pre">20</span> <span class="pre">*</span> <span class="pre">512</span></code> bytes. Use this variant
in combination with e.g. <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, a socket file object or a tape
device. However, such a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> object is limited in that it does
not allow random access, see <a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a>.  The currently
possible modes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="77%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Mode</th>
<th class="head">Action</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r|*'</span></code></td>
<td>Open a <em>stream</em> of tar blocks for reading
with transparent compression.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'r|'</span></code></td>
<td>Open a <em>stream</em> of uncompressed tar blocks
for reading.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'r|gz'</span></code></td>
<td>Open a gzip compressed <em>stream</em> for
reading.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'r|bz2'</span></code></td>
<td>Open a bzip2 compressed <em>stream</em> for
reading.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'w|'</span></code></td>
<td>Open an uncompressed <em>stream</em> for writing.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w|gz'</span></code></td>
<td>Open a gzip compressed <em>stream</em> for
writing.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'w|bz2'</span></code></td>
<td>Open a bzip2 compressed <em>stream</em> for
writing.</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="class">
<dt id="tarfile.TarFile">
<em class="property">class </em><code class="descclassname">tarfile.</code><code class="descname">TarFile</code><a class="headerlink" href="#tarfile.TarFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Class for reading and writing tar archives. Do not use this class directly,
better use <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">tarfile.open()</span></code></a> instead. See <a class="reference internal" href="#tarfile-objects"><span class="std std-ref">TarFile Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="tarfile.is_tarfile">
<code class="descclassname">tarfile.</code><code class="descname">is_tarfile</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.is_tarfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>name</em> is a tar archive file, that the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a>
module can read.</p>
</dd></dl>

<dl class="class">
<dt id="tarfile.TarFileCompat">
<em class="property">class </em><code class="descclassname">tarfile.</code><code class="descname">TarFileCompat</code><span class="sig-paren">(</span><em>filename</em>, <em>mode='r'</em>, <em>compression=TAR_PLAIN</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFileCompat" title="Permalink to this definition">¶</a></dt>
<dd><p>Class for limited access to tar archives with a <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a>-like interface.
Please consult the documentation of the <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module for more details.
<em>compression</em> must be one of the following constants:</p>
<dl class="data">
<dt id="tarfile.TarFileCompat.TAR_PLAIN">
<code class="descname">TAR_PLAIN</code><a class="headerlink" href="#tarfile.TarFileCompat.TAR_PLAIN" title="Permalink to this definition">¶</a></dt>
<dd><p>Constant for an uncompressed tar archive.</p>
</dd></dl>

<dl class="data">
<dt id="tarfile.TarFileCompat.TAR_GZIPPED">
<code class="descname">TAR_GZIPPED</code><a class="headerlink" href="#tarfile.TarFileCompat.TAR_GZIPPED" title="Permalink to this definition">¶</a></dt>
<dd><p>Constant for a <a class="reference internal" href="gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> compressed tar archive.</p>
</dd></dl>

<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#tarfile.TarFileCompat" title="tarfile.TarFileCompat"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFileCompat</span></code></a> class has been removed in Python 3.</p>
</div>
</dd></dl>

<dl class="exception">
<dt id="tarfile.TarError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">TarError</code><a class="headerlink" href="#tarfile.TarError" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for all <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> exceptions.</p>
</dd></dl>

<dl class="exception">
<dt id="tarfile.ReadError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">ReadError</code><a class="headerlink" href="#tarfile.ReadError" title="Permalink to this definition">¶</a></dt>
<dd><p>Is raised when a tar archive is opened, that either cannot be handled by the
<a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module or is somehow invalid.</p>
</dd></dl>

<dl class="exception">
<dt id="tarfile.CompressionError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">CompressionError</code><a class="headerlink" href="#tarfile.CompressionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Is raised when a compression method is not supported or when the data cannot be
decoded properly.</p>
</dd></dl>

<dl class="exception">
<dt id="tarfile.StreamError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">StreamError</code><a class="headerlink" href="#tarfile.StreamError" title="Permalink to this definition">¶</a></dt>
<dd><p>Is raised for the limitations that are typical for stream-like <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a>
objects.</p>
</dd></dl>

<dl class="exception">
<dt id="tarfile.ExtractError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">ExtractError</code><a class="headerlink" href="#tarfile.ExtractError" title="Permalink to this definition">¶</a></dt>
<dd><p>Is raised for <em>non-fatal</em> errors when using <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.extract()</span></code></a>, but only if
<code class="xref py py-attr docutils literal notranslate"><span class="pre">TarFile.errorlevel</span></code><code class="docutils literal notranslate"><span class="pre">==</span> <span class="pre">2</span></code>.</p>
</dd></dl>

<p>The following constants are available at the module level:</p>
<dl class="data">
<dt id="tarfile.ENCODING">
<code class="descclassname">tarfile.</code><code class="descname">ENCODING</code><a class="headerlink" href="#tarfile.ENCODING" title="Permalink to this definition">¶</a></dt>
<dd><p>The default character encoding: <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> on Windows, the value returned by
<a class="reference internal" href="sys.html#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getfilesystemencoding()</span></code></a> otherwise.</p>
</dd></dl>

<dl class="exception">
<dt id="tarfile.HeaderError">
<em class="property">exception </em><code class="descclassname">tarfile.</code><code class="descname">HeaderError</code><a class="headerlink" href="#tarfile.HeaderError" title="Permalink to this definition">¶</a></dt>
<dd><p>Is raised by <a class="reference internal" href="#tarfile.TarInfo.frombuf" title="tarfile.TarInfo.frombuf"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TarInfo.frombuf()</span></code></a> if the buffer it gets is invalid.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>Each of the following constants defines a tar archive format that the
<a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module is able to create. See section <a class="reference internal" href="#tar-formats"><span class="std std-ref">Supported tar formats</span></a> for
details.</p>
<dl class="data">
<dt id="tarfile.USTAR_FORMAT">
<code class="descclassname">tarfile.</code><code class="descname">USTAR_FORMAT</code><a class="headerlink" href="#tarfile.USTAR_FORMAT" title="Permalink to this definition">¶</a></dt>
<dd><p>POSIX.1-1988 (ustar) format.</p>
</dd></dl>

<dl class="data">
<dt id="tarfile.GNU_FORMAT">
<code class="descclassname">tarfile.</code><code class="descname">GNU_FORMAT</code><a class="headerlink" href="#tarfile.GNU_FORMAT" title="Permalink to this definition">¶</a></dt>
<dd><p>GNU tar format.</p>
</dd></dl>

<dl class="data">
<dt id="tarfile.PAX_FORMAT">
<code class="descclassname">tarfile.</code><code class="descname">PAX_FORMAT</code><a class="headerlink" href="#tarfile.PAX_FORMAT" title="Permalink to this definition">¶</a></dt>
<dd><p>POSIX.1-2001 (pax) format.</p>
</dd></dl>

<dl class="data">
<dt id="tarfile.DEFAULT_FORMAT">
<code class="descclassname">tarfile.</code><code class="descname">DEFAULT_FORMAT</code><a class="headerlink" href="#tarfile.DEFAULT_FORMAT" title="Permalink to this definition">¶</a></dt>
<dd><p>The default format for creating archives. This is currently <a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">GNU_FORMAT</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a></dt>
<dd>Documentation of the <a class="reference internal" href="zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> standard module.</dd>
<dt><a class="reference internal" href="shutil.html#archiving-operations"><span class="std std-ref">Archiving operations</span></a></dt>
<dd>Documentation of the higher-level archiving facilities provided by the
standard <a class="reference internal" href="shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module.</dd>
<dt><a class="reference external" href="https://www.gnu.org/software/tar/manual/html_node/Standard.html">GNU tar manual, Basic Tar Format</a></dt>
<dd>Documentation for tar archive files, including GNU tar extensions.</dd>
</dl>
</div>
<div class="section" id="tarfile-objects">
<span id="id1"></span><h2>12.5.1. TarFile Objects<a class="headerlink" href="#tarfile-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> object provides an interface to a tar archive. A tar
archive is a sequence of blocks. An archive member (a stored file) is made up of
a header block followed by data blocks. It is possible to store a file in a tar
archive several times. Each archive member is represented by a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a>
object, see <a class="reference internal" href="#tarinfo-objects"><span class="std std-ref">TarInfo Objects</span></a> for details.</p>
<p>A <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> object can be used as a context manager in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement. It will automatically be closed when the block is completed. Please
note that in the event of an exception an archive opened for writing will not
be finalized; only the internally used file object will be closed. See the
<a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a> section for a use case.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>Added support for the context management protocol.</p>
</div>
<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">tarfile.</code><code class="descname">TarFile</code><span class="sig-paren">(</span><em>name=None</em>, <em>mode='r'</em>, <em>fileobj=None</em>, <em>format=DEFAULT_FORMAT</em>, <em>tarinfo=TarInfo</em>, <em>dereference=False</em>, <em>ignore_zeros=False</em>, <em>encoding=ENCODING</em>, <em>errors=None</em>, <em>pax_headers=None</em>, <em>debug=0</em>, <em>errorlevel=0</em><span class="sig-paren">)</span></dt>
<dd><p>All following arguments are optional and can be accessed as instance attributes
as well.</p>
<p><em>name</em> is the pathname of the archive. It can be omitted if <em>fileobj</em> is given.
In this case, the file object’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute is used if it exists.</p>
<p><em>mode</em> is either <code class="docutils literal notranslate"><span class="pre">'r'</span></code> to read from an existing archive, <code class="docutils literal notranslate"><span class="pre">'a'</span></code> to append
data to an existing file or <code class="docutils literal notranslate"><span class="pre">'w'</span></code> to create a new file overwriting an existing
one.</p>
<p>If <em>fileobj</em> is given, it is used for reading or writing data. If it can be
determined, <em>mode</em> is overridden by <em>fileobj</em>’s mode. <em>fileobj</em> will be used
from position 0.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><em>fileobj</em> is not closed, when <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> is closed.</p>
</div>
<p><em>format</em> controls the archive format. It must be one of the constants
<a class="reference internal" href="#tarfile.USTAR_FORMAT" title="tarfile.USTAR_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">USTAR_FORMAT</span></code></a>, <a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">GNU_FORMAT</span></code></a> or <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAX_FORMAT</span></code></a> that are
defined at module level.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The <em>tarinfo</em> argument can be used to replace the default <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> class
with a different one.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>If <em>dereference</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, add symbolic and hard links to the archive. If it
is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, add the content of the target files to the archive. This has no
effect on systems that do not support symbolic links.</p>
<p>If <em>ignore_zeros</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>, treat an empty block as the end of the archive.
If it is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, skip empty (and invalid) blocks and try to get as many members
as possible. This is only useful for reading concatenated or damaged archives.</p>
<p><em>debug</em> can be set from <code class="docutils literal notranslate"><span class="pre">0</span></code> (no debug messages) up to <code class="docutils literal notranslate"><span class="pre">3</span></code> (all debug
messages). The messages are written to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.</p>
<p>If <em>errorlevel</em> is <code class="docutils literal notranslate"><span class="pre">0</span></code>, all errors are ignored when using <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.extract()</span></code></a>.
Nevertheless, they appear as error messages in the debug output, when debugging
is enabled.  If <code class="docutils literal notranslate"><span class="pre">1</span></code>, all <em>fatal</em> errors are raised as <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> or
<a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exceptions. If <code class="docutils literal notranslate"><span class="pre">2</span></code>, all <em>non-fatal</em> errors are raised as
<a class="reference internal" href="#tarfile.TarError" title="tarfile.TarError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TarError</span></code></a> exceptions as well.</p>
<p>The <em>encoding</em> and <em>errors</em> arguments control the way strings are converted to
unicode objects and vice versa. The default settings will work for most users.
See section <a class="reference internal" href="#tar-unicode"><span class="std std-ref">Unicode issues</span></a> for in-depth information.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The <em>pax_headers</em> argument is an optional dictionary of unicode strings which
will be added as a pax global header if <em>format</em> is <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAX_FORMAT</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="classmethod">
<dt id="tarfile.TarFile.open">
<em class="property">classmethod </em><code class="descclassname">TarFile.</code><code class="descname">open</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Alternative constructor. The <a class="reference internal" href="#tarfile.open" title="tarfile.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">tarfile.open()</span></code></a> function is actually a
shortcut to this classmethod.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.getmember">
<code class="descclassname">TarFile.</code><code class="descname">getmember</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.getmember" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object for member <em>name</em>. If <em>name</em> can not be found
in the archive, <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If a member occurs more than once in the archive, its last occurrence is assumed
to be the most up-to-date version.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.getmembers">
<code class="descclassname">TarFile.</code><code class="descname">getmembers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.getmembers" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the members of the archive as a list of <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> objects. The
list has the same order as the members in the archive.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.getnames">
<code class="descclassname">TarFile.</code><code class="descname">getnames</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.getnames" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the members as a list of their names. It has the same order as the list
returned by <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getmembers()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.list">
<code class="descclassname">TarFile.</code><code class="descname">list</code><span class="sig-paren">(</span><em>verbose=True</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.list" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a table of contents to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>. If <em>verbose</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>,
only the names of the members are printed. If it is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, output
similar to that of <strong class="program">ls -l</strong> is produced.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.next">
<code class="descclassname">TarFile.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the next member of the archive as a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object, when
<a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> is opened for reading. Return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if there is no more
available.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.extractall">
<code class="descclassname">TarFile.</code><code class="descname">extractall</code><span class="sig-paren">(</span><em>path=&quot;.&quot;</em>, <em>members=None</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.extractall" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract all members from the archive to the current working directory or
directory <em>path</em>. If optional <em>members</em> is given, it must be a subset of the
list returned by <a class="reference internal" href="#tarfile.TarFile.getmembers" title="tarfile.TarFile.getmembers"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getmembers()</span></code></a>. Directory information like owner,
modification time and permissions are set after all members have been extracted.
This is done to work around two problems: A directory’s modification time is
reset each time a file is created in it. And, if a directory’s permissions do
not allow writing, extracting files to it will fail.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Never extract archives from untrusted sources without prior inspection.
It is possible that files are created outside of <em>path</em>, e.g. members
that have absolute filenames starting with <code class="docutils literal notranslate"><span class="pre">&quot;/&quot;</span></code> or filenames with two
dots <code class="docutils literal notranslate"><span class="pre">&quot;..&quot;</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.extract">
<code class="descclassname">TarFile.</code><code class="descname">extract</code><span class="sig-paren">(</span><em>member</em>, <em>path=&quot;&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.extract" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract a member from the archive to the current working directory, using its
full name. Its file information is extracted as accurately as possible. <em>member</em>
may be a filename or a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object. You can specify a different
directory using <em>path</em>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#tarfile.TarFile.extract" title="tarfile.TarFile.extract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code></a> method does not take care of several extraction issues.
In most cases you should consider using the <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code></a> method.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">See the warning for <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.extractfile">
<code class="descclassname">TarFile.</code><code class="descname">extractfile</code><span class="sig-paren">(</span><em>member</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.extractfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract a member from the archive as a file object. <em>member</em> may be a filename
or a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object. If <em>member</em> is a regular file, a file-like object
is returned. If <em>member</em> is a link, a file-like object is constructed from the
link’s target. If <em>member</em> is none of the above, <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is returned.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The file-like object is read-only.  It provides the methods
<code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>, <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code>,
and <a class="reference internal" href="#tarfile.TarFile.close" title="tarfile.TarFile.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a>, and also supports iteration over its lines.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.add">
<code class="descclassname">TarFile.</code><code class="descname">add</code><span class="sig-paren">(</span><em>name</em>, <em>arcname=None</em>, <em>recursive=True</em>, <em>exclude=None</em>, <em>filter=None</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the file <em>name</em> to the archive. <em>name</em> may be any type of file (directory,
fifo, symbolic link, etc.). If given, <em>arcname</em> specifies an alternative name
for the file in the archive. Directories are added recursively by default. This
can be avoided by setting <em>recursive</em> to <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>. If <em>exclude</em> is given
it must be a function that takes one filename argument and returns a boolean
value. Depending on this value the respective file is either excluded
(<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>) or added (<a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>). If <em>filter</em> is specified it must
be a function that takes a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object argument and returns the
changed <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object. If it instead returns <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a>
object will be excluded from the archive. See <a class="reference internal" href="#tar-examples"><span class="std std-ref">Examples</span></a> for an
example.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the <em>exclude</em> parameter.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the <em>filter</em> parameter.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>The <em>exclude</em> parameter is deprecated, please use the <em>filter</em> parameter
instead.  For maximum portability, <em>filter</em> should be used as a keyword
argument rather than as a positional argument so that code won’t be
affected when <em>exclude</em> is ultimately removed.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.addfile">
<code class="descclassname">TarFile.</code><code class="descname">addfile</code><span class="sig-paren">(</span><em>tarinfo</em>, <em>fileobj=None</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.addfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Add the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object <em>tarinfo</em> to the archive. If <em>fileobj</em> is given,
<code class="docutils literal notranslate"><span class="pre">tarinfo.size</span></code> bytes are read from it and added to the archive.  You can
create <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> objects directly, or by using <a class="reference internal" href="#tarfile.TarFile.gettarinfo" title="tarfile.TarFile.gettarinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">gettarinfo()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">On Windows platforms, <em>fileobj</em> should always be opened with mode <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> to
avoid irritation about the file size.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.gettarinfo">
<code class="descclassname">TarFile.</code><code class="descname">gettarinfo</code><span class="sig-paren">(</span><em>name=None</em>, <em>arcname=None</em>, <em>fileobj=None</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.gettarinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object from the result of <a class="reference internal" href="os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> or
equivalent on an existing file.  The file is either named by <em>name</em>, or
specified as a file object <em>fileobj</em> with a file descriptor.  If
given, <em>arcname</em> specifies an alternative name for the file in the
archive, otherwise, the name is taken from <em>fileobj</em>’s
<a class="reference internal" href="stdtypes.html#file.name" title="file.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a> attribute, or the <em>name</em> argument.</p>
<p>You can modify some
of the <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a>’s attributes before you add it using <a class="reference internal" href="#tarfile.TarFile.addfile" title="tarfile.TarFile.addfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addfile()</span></code></a>.
If the file object is not an ordinary file object positioned at the
beginning of the file, attributes such as <a class="reference internal" href="#tarfile.TarInfo.size" title="tarfile.TarInfo.size"><code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code></a> may need
modifying.  This is the case for objects such as <a class="reference internal" href="gzip.html#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a>.
The <a class="reference internal" href="#tarfile.TarInfo.name" title="tarfile.TarInfo.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a> may also be modified, in which case <em>arcname</em>
could be a dummy string.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarFile.close">
<code class="descclassname">TarFile.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarFile.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a>. In write mode, two finishing zero blocks are
appended to the archive.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarFile.posix">
<code class="descclassname">TarFile.</code><code class="descname">posix</code><a class="headerlink" href="#tarfile.TarFile.posix" title="Permalink to this definition">¶</a></dt>
<dd><p>Setting this to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> is equivalent to setting the <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">format</span></code></a>
attribute to <a class="reference internal" href="#tarfile.USTAR_FORMAT" title="tarfile.USTAR_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">USTAR_FORMAT</span></code></a>, <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> is equivalent to
<a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">GNU_FORMAT</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><em>posix</em> defaults to <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>Use the <a class="reference internal" href="functions.html#format" title="format"><code class="xref py py-attr docutils literal notranslate"><span class="pre">format</span></code></a> attribute instead.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarFile.pax_headers">
<code class="descclassname">TarFile.</code><code class="descname">pax_headers</code><a class="headerlink" href="#tarfile.TarFile.pax_headers" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary containing key-value pairs of pax global headers.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="tarinfo-objects">
<span id="id2"></span><h2>12.5.2. TarInfo Objects<a class="headerlink" href="#tarinfo-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object represents one member in a <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a>. Aside
from storing all required attributes of a file (like file type, size, time,
permissions, owner etc.), it provides some useful methods to determine its type.
It does <em>not</em> contain the file’s data itself.</p>
<p><a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> objects are returned by <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a>’s methods
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getmember()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getmembers()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">gettarinfo()</span></code>.</p>
<dl class="class">
<dt id="tarfile.TarInfo">
<em class="property">class </em><code class="descclassname">tarfile.</code><code class="descname">TarInfo</code><span class="sig-paren">(</span><em>name=&quot;&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.frombuf">
<code class="descclassname">TarInfo.</code><code class="descname">frombuf</code><span class="sig-paren">(</span><em>buf</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.frombuf" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object from string buffer <em>buf</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Raises <a class="reference internal" href="#tarfile.HeaderError" title="tarfile.HeaderError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HeaderError</span></code></a> if the buffer is invalid..</p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.fromtarfile">
<code class="descclassname">TarInfo.</code><code class="descname">fromtarfile</code><span class="sig-paren">(</span><em>tarfile</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.fromtarfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Read the next member from the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> object <em>tarfile</em> and return it as
a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.tobuf">
<code class="descclassname">TarInfo.</code><code class="descname">tobuf</code><span class="sig-paren">(</span><em>format=DEFAULT_FORMAT</em>, <em>encoding=ENCODING</em>, <em>errors='strict'</em><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.tobuf" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a string buffer from a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object. For information on the
arguments see the constructor of the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> class.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The arguments were added.</p>
</div>
</dd></dl>

<p>A <code class="docutils literal notranslate"><span class="pre">TarInfo</span></code> object has the following public data attributes:</p>
<dl class="attribute">
<dt id="tarfile.TarInfo.name">
<code class="descclassname">TarInfo.</code><code class="descname">name</code><a class="headerlink" href="#tarfile.TarInfo.name" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the archive member.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.size">
<code class="descclassname">TarInfo.</code><code class="descname">size</code><a class="headerlink" href="#tarfile.TarInfo.size" title="Permalink to this definition">¶</a></dt>
<dd><p>Size in bytes.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.mtime">
<code class="descclassname">TarInfo.</code><code class="descname">mtime</code><a class="headerlink" href="#tarfile.TarInfo.mtime" title="Permalink to this definition">¶</a></dt>
<dd><p>Time of last modification.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.mode">
<code class="descclassname">TarInfo.</code><code class="descname">mode</code><a class="headerlink" href="#tarfile.TarInfo.mode" title="Permalink to this definition">¶</a></dt>
<dd><p>Permission bits.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.type">
<code class="descclassname">TarInfo.</code><code class="descname">type</code><a class="headerlink" href="#tarfile.TarInfo.type" title="Permalink to this definition">¶</a></dt>
<dd><p>File type.  <em>type</em> is usually one of these constants: <code class="xref py py-const docutils literal notranslate"><span class="pre">REGTYPE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">AREGTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">LNKTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">SYMTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">DIRTYPE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">FIFOTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">CONTTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">CHRTYPE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">BLKTYPE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">GNUTYPE_SPARSE</span></code>.  To determine the type of a <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object
more conveniently, use the <code class="docutils literal notranslate"><span class="pre">is*()</span></code> methods below.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.linkname">
<code class="descclassname">TarInfo.</code><code class="descname">linkname</code><a class="headerlink" href="#tarfile.TarInfo.linkname" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the target file name, which is only present in <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> objects
of type <code class="xref py py-const docutils literal notranslate"><span class="pre">LNKTYPE</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">SYMTYPE</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.uid">
<code class="descclassname">TarInfo.</code><code class="descname">uid</code><a class="headerlink" href="#tarfile.TarInfo.uid" title="Permalink to this definition">¶</a></dt>
<dd><p>User ID of the user who originally stored this member.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.gid">
<code class="descclassname">TarInfo.</code><code class="descname">gid</code><a class="headerlink" href="#tarfile.TarInfo.gid" title="Permalink to this definition">¶</a></dt>
<dd><p>Group ID of the user who originally stored this member.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.uname">
<code class="descclassname">TarInfo.</code><code class="descname">uname</code><a class="headerlink" href="#tarfile.TarInfo.uname" title="Permalink to this definition">¶</a></dt>
<dd><p>User name.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.gname">
<code class="descclassname">TarInfo.</code><code class="descname">gname</code><a class="headerlink" href="#tarfile.TarInfo.gname" title="Permalink to this definition">¶</a></dt>
<dd><p>Group name.</p>
</dd></dl>

<dl class="attribute">
<dt id="tarfile.TarInfo.pax_headers">
<code class="descclassname">TarInfo.</code><code class="descname">pax_headers</code><a class="headerlink" href="#tarfile.TarInfo.pax_headers" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary containing key-value pairs of an associated pax extended header.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>A <a class="reference internal" href="#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> object also provides some convenient query methods:</p>
<dl class="method">
<dt id="tarfile.TarInfo.isfile">
<code class="descclassname">TarInfo.</code><code class="descname">isfile</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the <code class="xref py py-class docutils literal notranslate"><span class="pre">Tarinfo</span></code> object is a regular file.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.isreg">
<code class="descclassname">TarInfo.</code><code class="descname">isreg</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isreg" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#tarfile.TarInfo.isfile" title="tarfile.TarInfo.isfile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isfile()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.isdir">
<code class="descclassname">TarInfo.</code><code class="descname">isdir</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a directory.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.issym">
<code class="descclassname">TarInfo.</code><code class="descname">issym</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.issym" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a symbolic link.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.islnk">
<code class="descclassname">TarInfo.</code><code class="descname">islnk</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.islnk" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a hard link.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.ischr">
<code class="descclassname">TarInfo.</code><code class="descname">ischr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.ischr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a character device.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.isblk">
<code class="descclassname">TarInfo.</code><code class="descname">isblk</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isblk" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a block device.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.isfifo">
<code class="descclassname">TarInfo.</code><code class="descname">isfifo</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isfifo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is a FIFO.</p>
</dd></dl>

<dl class="method">
<dt id="tarfile.TarInfo.isdev">
<code class="descclassname">TarInfo.</code><code class="descname">isdev</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tarfile.TarInfo.isdev" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if it is one of character device, block device or FIFO.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="tar-examples"></span><h2>12.5.3. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>How to extract an entire tar archive to the current working directory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tarfile</span>
<span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar.gz&quot;</span><span class="p">)</span>
<span class="n">tar</span><span class="o">.</span><span class="n">extractall</span><span class="p">()</span>
<span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>How to extract a subset of a tar archive with <a class="reference internal" href="#tarfile.TarFile.extractall" title="tarfile.TarFile.extractall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.extractall()</span></code></a> using
a generator function instead of a list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">tarfile</span>

<span class="k">def</span> <span class="nf">py_files</span><span class="p">(</span><span class="n">members</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">tarinfo</span> <span class="ow">in</span> <span class="n">members</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">splitext</span><span class="p">(</span><span class="n">tarinfo</span><span class="o">.</span><span class="n">name</span><span class="p">)[</span><span class="mi">1</span><span class="p">]</span> <span class="o">==</span> <span class="s2">&quot;.py&quot;</span><span class="p">:</span>
            <span class="k">yield</span> <span class="n">tarinfo</span>

<span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar.gz&quot;</span><span class="p">)</span>
<span class="n">tar</span><span class="o">.</span><span class="n">extractall</span><span class="p">(</span><span class="n">members</span><span class="o">=</span><span class="n">py_files</span><span class="p">(</span><span class="n">tar</span><span class="p">))</span>
<span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>How to create an uncompressed tar archive from a list of filenames:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tarfile</span>
<span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">,</span> <span class="s2">&quot;quux&quot;</span><span class="p">]:</span>
    <span class="n">tar</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The same example using the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tarfile</span>
<span class="k">with</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">tar</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;bar&quot;</span><span class="p">,</span> <span class="s2">&quot;quux&quot;</span><span class="p">]:</span>
        <span class="n">tar</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>How to read a gzip compressed tar archive and display some member information:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tarfile</span>
<span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar.gz&quot;</span><span class="p">,</span> <span class="s2">&quot;r:gz&quot;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">tarinfo</span> <span class="ow">in</span> <span class="n">tar</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="s2">&quot;is&quot;</span><span class="p">,</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">size</span><span class="p">,</span> <span class="s2">&quot;bytes in size and is&quot;</span><span class="p">,</span>
    <span class="k">if</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">isreg</span><span class="p">():</span>
        <span class="nb">print</span> <span class="s2">&quot;a regular file.&quot;</span>
    <span class="k">elif</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">isdir</span><span class="p">():</span>
        <span class="nb">print</span> <span class="s2">&quot;a directory.&quot;</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;something else.&quot;</span>
<span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>How to create an archive and reset the user information using the <em>filter</em>
parameter in <a class="reference internal" href="#tarfile.TarFile.add" title="tarfile.TarFile.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.add()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">tarfile</span>
<span class="k">def</span> <span class="nf">reset</span><span class="p">(</span><span class="n">tarinfo</span><span class="p">):</span>
    <span class="n">tarinfo</span><span class="o">.</span><span class="n">uid</span> <span class="o">=</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">gid</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="n">tarinfo</span><span class="o">.</span><span class="n">uname</span> <span class="o">=</span> <span class="n">tarinfo</span><span class="o">.</span><span class="n">gname</span> <span class="o">=</span> <span class="s2">&quot;root&quot;</span>
    <span class="k">return</span> <span class="n">tarinfo</span>
<span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;sample.tar.gz&quot;</span><span class="p">,</span> <span class="s2">&quot;w:gz&quot;</span><span class="p">)</span>
<span class="n">tar</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="nb">filter</span><span class="o">=</span><span class="n">reset</span><span class="p">)</span>
<span class="n">tar</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="supported-tar-formats">
<span id="tar-formats"></span><h2>12.5.4. Supported tar formats<a class="headerlink" href="#supported-tar-formats" title="Permalink to this headline">¶</a></h2>
<p>There are three tar formats that can be created with the <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module:</p>
<ul>
<li><p class="first">The POSIX.1-1988 ustar format (<a class="reference internal" href="#tarfile.USTAR_FORMAT" title="tarfile.USTAR_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">USTAR_FORMAT</span></code></a>). It supports filenames
up to a length of at best 256 characters and linknames up to 100 characters. The
maximum file size is 8 gigabytes. This is an old and limited but widely
supported format.</p>
</li>
<li><p class="first">The GNU tar format (<a class="reference internal" href="#tarfile.GNU_FORMAT" title="tarfile.GNU_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">GNU_FORMAT</span></code></a>). It supports long filenames and
linknames, files bigger than 8 gigabytes and sparse files. It is the de facto
standard on GNU/Linux systems. <a class="reference internal" href="#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> fully supports the GNU tar
extensions for long names, sparse file support is read-only.</p>
</li>
<li><p class="first">The POSIX.1-2001 pax format (<a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAX_FORMAT</span></code></a>). It is the most flexible
format with virtually no limits. It supports long filenames and linknames, large
files and stores pathnames in a portable way. However, not all tar
implementations today are able to handle pax archives properly.</p>
<p>The <em>pax</em> format is an extension to the existing <em>ustar</em> format. It uses extra
headers for information that cannot be stored otherwise. There are two flavours
of pax headers: Extended headers only affect the subsequent file header, global
headers are valid for the complete archive and affect all following files. All
the data in a pax header is encoded in <em>UTF-8</em> for portability reasons.</p>
</li>
</ul>
<p>There are some more variants of the tar format which can be read, but not
created:</p>
<ul class="simple">
<li>The ancient V7 format. This is the first tar format from Unix Seventh Edition,
storing only regular files and directories. Names must not be longer than 100
characters, there is no user/group name information. Some archives have
miscalculated header checksums in case of fields with non-ASCII characters.</li>
<li>The SunOS tar extended format. This format is a variant of the POSIX.1-2001
pax format, but is not compatible.</li>
</ul>
</div>
<div class="section" id="unicode-issues">
<span id="tar-unicode"></span><h2>12.5.5. Unicode issues<a class="headerlink" href="#unicode-issues" title="Permalink to this headline">¶</a></h2>
<p>The tar format was originally conceived to make backups on tape drives with the
main focus on preserving file system information. Nowadays tar archives are
commonly used for file distribution and exchanging archives over networks. One
problem of the original format (that all other formats are merely variants of)
is that there is no concept of supporting different character encodings. For
example, an ordinary tar archive created on a <em>UTF-8</em> system cannot be read
correctly on a <em>Latin-1</em> system if it contains non-ASCII characters. Names (i.e.
filenames, linknames, user/group names) containing these characters will appear
damaged.  Unfortunately, there is no way to autodetect the encoding of an
archive.</p>
<p>The pax format was designed to solve this problem. It stores non-ASCII names
using the universal character encoding <em>UTF-8</em>. When a pax archive is read,
these <em>UTF-8</em> names are converted to the encoding of the local file system.</p>
<p>The details of unicode conversion are controlled by the <em>encoding</em> and <em>errors</em>
keyword arguments of the <a class="reference internal" href="#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> class.</p>
<p>The default value for <em>encoding</em> is the local character encoding. It is deduced
from <a class="reference internal" href="sys.html#sys.getfilesystemencoding" title="sys.getfilesystemencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getfilesystemencoding()</span></code></a> and <a class="reference internal" href="sys.html#sys.getdefaultencoding" title="sys.getdefaultencoding"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getdefaultencoding()</span></code></a>. In
read mode, <em>encoding</em> is used exclusively to convert unicode names from a pax
archive to strings in the local character encoding. In write mode, the use of
<em>encoding</em> depends on the chosen archive format. In case of <a class="reference internal" href="#tarfile.PAX_FORMAT" title="tarfile.PAX_FORMAT"><code class="xref py py-const docutils literal notranslate"><span class="pre">PAX_FORMAT</span></code></a>,
input names that contain non-ASCII characters need to be decoded before being
stored as <em>UTF-8</em> strings. The other formats do not make use of <em>encoding</em>
unless unicode objects are used as input names. These are converted to 8-bit
character strings before they are added to the archive.</p>
<p>The <em>errors</em> argument defines how characters are treated that cannot be
converted to or from <em>encoding</em>. Possible values are listed in section
<a class="reference internal" href="codecs.html#codec-base-classes"><span class="std std-ref">Codec Base Classes</span></a>. In read mode, there is an additional scheme
<code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> which means that bad characters are replaced by their <em>UTF-8</em>
representation. This is the default scheme. In write mode the default value for
<em>errors</em> is <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> to ensure that name information is not altered
unnoticed.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a><ul>
<li><a class="reference internal" href="#tarfile-objects">12.5.1. TarFile Objects</a></li>
<li><a class="reference internal" href="#tarinfo-objects">12.5.2. TarInfo Objects</a></li>
<li><a class="reference internal" href="#examples">12.5.3. Examples</a></li>
<li><a class="reference internal" href="#supported-tar-formats">12.5.4. Supported tar formats</a></li>
<li><a class="reference internal" href="#unicode-issues">12.5.5. Unicode issues</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="zipfile.html"
                        title="previous chapter">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fileformats.html"
                        title="next chapter">13. File Formats</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tarfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fileformats.html" title="13. File Formats"
             >next</a> |</li>
        <li class="right" >
          <a href="zipfile.html" title="12.4. zipfile — Work with ZIP archives"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" >12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��E�l�lhtml/library/telnetlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.14. telnetlib — Telnet client &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.15. uuid — UUID objects according to RFC 4122" href="uuid.html" />
    <link rel="prev" title="20.13. smtpd — SMTP Server" href="smtpd.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/telnetlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="uuid.html" title="20.15. uuid — UUID objects according to RFC 4122"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="smtpd.html" title="20.13. smtpd — SMTP Server"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-telnetlib">
<span id="telnetlib-telnet-client"></span><h1>20.14. <a class="reference internal" href="#module-telnetlib" title="telnetlib: Telnet client class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">telnetlib</span></code></a> — Telnet client<a class="headerlink" href="#module-telnetlib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/telnetlib.py">Lib/telnetlib.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-telnetlib" title="telnetlib: Telnet client class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">telnetlib</span></code></a> module provides a <a class="reference internal" href="#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">Telnet</span></code></a> class that implements the
Telnet protocol.  See <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc854.html"><strong>RFC 854</strong></a> for details about the protocol. In addition, it
provides symbolic constants for the protocol characters (see below), and for the
telnet options. The symbolic names of the telnet options follow the definitions
in <code class="docutils literal notranslate"><span class="pre">arpa/telnet.h</span></code>, with the leading <code class="docutils literal notranslate"><span class="pre">TELOPT_</span></code> removed. For symbolic names
of options which are traditionally not included in <code class="docutils literal notranslate"><span class="pre">arpa/telnet.h</span></code>, see the
module source itself.</p>
<p>The symbolic constants for the telnet commands are: IAC, DONT, DO, WONT, WILL,
SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP
(Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase
Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).</p>
<dl class="class">
<dt id="telnetlib.Telnet">
<em class="property">class </em><code class="descclassname">telnetlib.</code><code class="descname">Telnet</code><span class="sig-paren">(</span><span class="optional">[</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">Telnet</span></code></a> represents a connection to a Telnet server. The instance is
initially not connected by default; the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> method must be used to
establish a connection.  Alternatively, the host name and optional port
number can be passed to the constructor, to, in which case the connection to
the server will be established before the constructor returns.  The optional
<em>timeout</em> parameter specifies a timeout in seconds for blocking operations
like the connection attempt (if not specified, the global default timeout
setting will be used).</p>
<p>Do not reopen an already connected instance.</p>
<p>This class has many <code class="xref py py-meth docutils literal notranslate"><span class="pre">read_*()</span></code> methods.  Note that some of them  raise
<a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> when the end of the connection is read, because they can return
an empty string for other reasons.  See the individual descriptions below.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc854.html"><strong>RFC 854</strong></a> - Telnet Protocol Specification</dt>
<dd>Definition of the Telnet protocol.</dd>
</dl>
</div>
<div class="section" id="telnet-objects">
<span id="id1"></span><h2>20.14.1. Telnet Objects<a class="headerlink" href="#telnet-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">Telnet</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="telnetlib.Telnet.read_until">
<code class="descclassname">Telnet.</code><code class="descname">read_until</code><span class="sig-paren">(</span><em>expected</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_until" title="Permalink to this definition">¶</a></dt>
<dd><p>Read until a given string, <em>expected</em>, is encountered or until <em>timeout</em> seconds
have passed.</p>
<p>When no match is found, return whatever is available instead, possibly the empty
string.  Raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if the connection is closed and no cooked data is
available.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_all">
<code class="descclassname">Telnet.</code><code class="descname">read_all</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Read all data until EOF; block until connection closed.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_some">
<code class="descclassname">Telnet.</code><code class="descname">read_some</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_some" title="Permalink to this definition">¶</a></dt>
<dd><p>Read at least one byte of cooked data unless EOF is hit. Return <code class="docutils literal notranslate"><span class="pre">''</span></code> if EOF is
hit.  Block if no data is immediately available.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_very_eager">
<code class="descclassname">Telnet.</code><code class="descname">read_very_eager</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_very_eager" title="Permalink to this definition">¶</a></dt>
<dd><p>Read everything that can be without blocking in I/O (eager).</p>
<p>Raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if connection closed and no cooked data available.  Return
<code class="docutils literal notranslate"><span class="pre">''</span></code> if no cooked data available otherwise. Do not block unless in the midst
of an IAC sequence.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_eager">
<code class="descclassname">Telnet.</code><code class="descname">read_eager</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_eager" title="Permalink to this definition">¶</a></dt>
<dd><p>Read readily available data.</p>
<p>Raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if connection closed and no cooked data available.  Return
<code class="docutils literal notranslate"><span class="pre">''</span></code> if no cooked data available otherwise. Do not block unless in the midst
of an IAC sequence.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_lazy">
<code class="descclassname">Telnet.</code><code class="descname">read_lazy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_lazy" title="Permalink to this definition">¶</a></dt>
<dd><p>Process and return data already in the queues (lazy).</p>
<p>Raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if connection closed and no data available. Return <code class="docutils literal notranslate"><span class="pre">''</span></code>
if no cooked data available otherwise.  Do not block unless in the midst of an
IAC sequence.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_very_lazy">
<code class="descclassname">Telnet.</code><code class="descname">read_very_lazy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_very_lazy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return any data available in the cooked queue (very lazy).</p>
<p>Raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a> if connection closed and no data available. Return <code class="docutils literal notranslate"><span class="pre">''</span></code>
if no cooked data available otherwise.  This method never blocks.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.read_sb_data">
<code class="descclassname">Telnet.</code><code class="descname">read_sb_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.read_sb_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data collected between a SB/SE pair (suboption begin/end). The
callback should access these data when it was invoked with a <code class="docutils literal notranslate"><span class="pre">SE</span></code> command.
This method never blocks.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.open">
<code class="descclassname">Telnet.</code><code class="descname">open</code><span class="sig-paren">(</span><em>host</em><span class="optional">[</span>, <em>port</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Connect to a host. The optional second argument is the port number, which
defaults to the standard Telnet port (23). The optional <em>timeout</em> parameter
specifies a timeout in seconds for blocking operations like the connection
attempt (if not specified, the global default timeout setting will be used).</p>
<p>Do not try to reopen an already connected instance.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.msg">
<code class="descclassname">Telnet.</code><code class="descname">msg</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>*args</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.msg" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a debug message when the debug level is <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> 0. If extra arguments are
present, they are substituted in the message using the standard string
formatting operator.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.set_debuglevel">
<code class="descclassname">Telnet.</code><code class="descname">set_debuglevel</code><span class="sig-paren">(</span><em>debuglevel</em><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.set_debuglevel" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the debug level.  The higher the value of <em>debuglevel</em>, the more debug
output you get (on <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.close">
<code class="descclassname">Telnet.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the connection.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.get_socket">
<code class="descclassname">Telnet.</code><code class="descname">get_socket</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.get_socket" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the socket object used internally.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.fileno">
<code class="descclassname">Telnet.</code><code class="descname">fileno</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.fileno" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the file descriptor of the socket object used internally.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.write">
<code class="descclassname">Telnet.</code><code class="descname">write</code><span class="sig-paren">(</span><em>buffer</em><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a string to the socket, doubling any IAC characters. This can block if the
connection is blocked.  May raise <a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> if the connection is
closed.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.interact">
<code class="descclassname">Telnet.</code><code class="descname">interact</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.interact" title="Permalink to this definition">¶</a></dt>
<dd><p>Interaction function, emulates a very dumb Telnet client.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.mt_interact">
<code class="descclassname">Telnet.</code><code class="descname">mt_interact</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.mt_interact" title="Permalink to this definition">¶</a></dt>
<dd><p>Multithreaded version of <a class="reference internal" href="#telnetlib.Telnet.interact" title="telnetlib.Telnet.interact"><code class="xref py py-meth docutils literal notranslate"><span class="pre">interact()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.expect">
<code class="descclassname">Telnet.</code><code class="descname">expect</code><span class="sig-paren">(</span><em>list</em><span class="optional">[</span>, <em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.expect" title="Permalink to this definition">¶</a></dt>
<dd><p>Read until one from a list of a regular expressions matches.</p>
<p>The first argument is a list of regular expressions, either compiled
(<code class="xref py py-class docutils literal notranslate"><span class="pre">regex</span> <span class="pre">objects</span></code>) or uncompiled (strings). The optional second
argument is a timeout, in seconds; the default is to block indefinitely.</p>
<p>Return a tuple of three items: the index in the list of the first regular
expression that matches; the match object returned; and the text read up till
and including the match.</p>
<p>If end of file is found and no text was read, raise <a class="reference internal" href="exceptions.html#exceptions.EOFError" title="exceptions.EOFError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">EOFError</span></code></a>.  Otherwise,
when nothing matches, return <code class="docutils literal notranslate"><span class="pre">(-1,</span> <span class="pre">None,</span> <span class="pre">text)</span></code> where <em>text</em> is the text
received so far (may be the empty string if a timeout happened).</p>
<p>If a regular expression ends with a greedy match (such as <code class="docutils literal notranslate"><span class="pre">.*</span></code>) or if more
than one expression can match the same input, the results are
non-deterministic, and may depend on the I/O timing.</p>
</dd></dl>

<dl class="method">
<dt id="telnetlib.Telnet.set_option_negotiation_callback">
<code class="descclassname">Telnet.</code><code class="descname">set_option_negotiation_callback</code><span class="sig-paren">(</span><em>callback</em><span class="sig-paren">)</span><a class="headerlink" href="#telnetlib.Telnet.set_option_negotiation_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Each time a telnet option is read on the input flow, this <em>callback</em> (if set) is
called with the following parameters: callback(telnet socket, command
(DO/DONT/WILL/WONT), option).  No other action is done afterwards by telnetlib.</p>
</dd></dl>

</div>
<div class="section" id="telnet-example">
<span id="id2"></span><h2>20.14.2. Telnet Example<a class="headerlink" href="#telnet-example" title="Permalink to this headline">¶</a></h2>
<p>A simple example illustrating typical use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">getpass</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">telnetlib</span>

<span class="n">HOST</span> <span class="o">=</span> <span class="s2">&quot;localhost&quot;</span>
<span class="n">user</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;Enter your remote account: &quot;</span><span class="p">)</span>
<span class="n">password</span> <span class="o">=</span> <span class="n">getpass</span><span class="o">.</span><span class="n">getpass</span><span class="p">()</span>

<span class="n">tn</span> <span class="o">=</span> <span class="n">telnetlib</span><span class="o">.</span><span class="n">Telnet</span><span class="p">(</span><span class="n">HOST</span><span class="p">)</span>

<span class="n">tn</span><span class="o">.</span><span class="n">read_until</span><span class="p">(</span><span class="s2">&quot;login: &quot;</span><span class="p">)</span>
<span class="n">tn</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">user</span> <span class="o">+</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">password</span><span class="p">:</span>
    <span class="n">tn</span><span class="o">.</span><span class="n">read_until</span><span class="p">(</span><span class="s2">&quot;Password: &quot;</span><span class="p">)</span>
    <span class="n">tn</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">password</span> <span class="o">+</span> <span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>

<span class="n">tn</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;ls</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="n">tn</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;exit</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>

<span class="nb">print</span> <span class="n">tn</span><span class="o">.</span><span class="n">read_all</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a><ul>
<li><a class="reference internal" href="#telnet-objects">20.14.1. Telnet Objects</a></li>
<li><a class="reference internal" href="#telnet-example">20.14.2. Telnet Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="smtpd.html"
                        title="previous chapter">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="uuid.html"
                        title="next chapter">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/telnetlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="uuid.html" title="20.15. uuid — UUID objects according to RFC 4122"
             >next</a> |</li>
        <li class="right" >
          <a href="smtpd.html" title="20.13. smtpd — SMTP Server"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���|�|html/library/tempfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10.6. tempfile — Generate temporary files and directories &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10.7. glob — Unix style pathname pattern expansion" href="glob.html" />
    <link rel="prev" title="10.5. filecmp — File and Directory Comparisons" href="filecmp.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tempfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="glob.html" title="10.7. glob — Unix style pathname pattern expansion"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="filecmp.html" title="10.5. filecmp — File and Directory Comparisons"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-tempfile">
<span id="tempfile-generate-temporary-files-and-directories"></span><h1>10.6. <a class="reference internal" href="#module-tempfile" title="tempfile: Generate temporary files and directories."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code></a> — Generate temporary files and directories<a class="headerlink" href="#module-tempfile" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/tempfile.py">Lib/tempfile.py</a></p>
<hr class="docutils" />
<p>This module generates temporary files and directories.  It works on all
supported platforms.</p>
<p>In version 2.3 of Python, this module was overhauled for enhanced security.  It
now provides three new functions, <a class="reference internal" href="#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">NamedTemporaryFile()</span></code></a>, <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>,
and <a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a>, which should eliminate all remaining need to use the
insecure <a class="reference internal" href="#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code></a> function.  Temporary file names created by this module
no longer contain the process ID; instead a string of six random characters is
used.</p>
<p>Also, all the user-callable functions now take additional arguments which
allow direct control over the location and name of temporary files.  It is
no longer necessary to use the global <em>tempdir</em> and <em>template</em> variables.
To maintain backward compatibility, the argument order is somewhat odd; it
is recommended to use keyword arguments for clarity.</p>
<p>The module defines the following user-callable functions:</p>
<dl class="function">
<dt id="tempfile.TemporaryFile">
<code class="descclassname">tempfile.</code><code class="descname">TemporaryFile</code><span class="sig-paren">(</span><span class="optional">[</span><em>mode='w+b'</em><span class="optional">[</span>, <em>bufsize=-1</em><span class="optional">[</span>, <em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.TemporaryFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a file-like object that can be used as a temporary storage area.
The file is created using <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>. It will be destroyed as soon
as it is closed (including an implicit close when the object is garbage
collected).  Under Unix, the directory entry for the file is removed
immediately after the file is created.  Other platforms do not support
this; your code should not rely on a temporary file created using this
function having or not having a visible name in the file system.</p>
<p>The <em>mode</em> parameter defaults to <code class="docutils literal notranslate"><span class="pre">'w+b'</span></code> so that the file created can
be read and written without being closed.  Binary mode is used so that it
behaves consistently on all platforms without regard for the data that is
stored.  <em>bufsize</em> defaults to <code class="docutils literal notranslate"><span class="pre">-1</span></code>, meaning that the operating system
default is used.</p>
<p>The <em>dir</em>, <em>prefix</em> and <em>suffix</em> parameters are passed to <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>.</p>
<p>The returned object is a true file object on POSIX platforms.  On other
platforms, it is a file-like object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code> attribute is the
underlying true file object. This file-like object can be used in a
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, just like a normal file.</p>
</dd></dl>

<dl class="function">
<dt id="tempfile.NamedTemporaryFile">
<code class="descclassname">tempfile.</code><code class="descname">NamedTemporaryFile</code><span class="sig-paren">(</span><span class="optional">[</span><em>mode='w+b'</em><span class="optional">[</span>, <em>bufsize=-1</em><span class="optional">[</span>, <em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">[</span>, <em>delete=True</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.NamedTemporaryFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This function operates exactly as <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a> does, except that
the file is guaranteed to have a visible name in the file system (on
Unix, the directory entry is not unlinked).  That name can be retrieved
from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute of the returned
file-like object.  Whether the name can be
used to open the file a second time, while the named temporary file is
still open, varies across platforms (it can be so used on Unix; it cannot
on Windows NT or later).  If <em>delete</em> is true (the default), the file is
deleted as soon as it is closed.</p>
<p>The returned object is always a file-like object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code>
attribute is the underlying true file object. This file-like object can
be used in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, just like a normal file.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>The <em>delete</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="tempfile.SpooledTemporaryFile">
<code class="descclassname">tempfile.</code><code class="descname">SpooledTemporaryFile</code><span class="sig-paren">(</span><span class="optional">[</span><em>max_size=0</em><span class="optional">[</span>, <em>mode='w+b'</em><span class="optional">[</span>, <em>bufsize=-1</em><span class="optional">[</span>, <em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.SpooledTemporaryFile" title="Permalink to this definition">¶</a></dt>
<dd><p>This function operates exactly as <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a> does, except that
data is spooled in memory until the file size exceeds <em>max_size</em>, or
until the file’s <code class="xref py py-func docutils literal notranslate"><span class="pre">fileno()</span></code> method is called, at which point the
contents are written to disk and operation proceeds as with
<a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a>.  Also, it’s <code class="docutils literal notranslate"><span class="pre">truncate</span></code> method does not
accept a <code class="docutils literal notranslate"><span class="pre">size</span></code> argument.</p>
<p>The resulting file has one additional method, <code class="xref py py-func docutils literal notranslate"><span class="pre">rollover()</span></code>, which
causes the file to roll over to an on-disk file regardless of its size.</p>
<p>The returned object is a file-like object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">_file</span></code> attribute
is either a <a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object or a true file object, depending on
whether <code class="xref py py-func docutils literal notranslate"><span class="pre">rollover()</span></code> has been called. This file-like object can be
used in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, just like a normal file.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="tempfile.mkstemp">
<code class="descclassname">tempfile.</code><code class="descname">mkstemp</code><span class="sig-paren">(</span><span class="optional">[</span><em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">[</span>, <em>text=False</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mkstemp" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a temporary file in the most secure manner possible.  There are
no race conditions in the file’s creation, assuming that the platform
properly implements the <a class="reference internal" href="os.html#os.O_EXCL" title="os.O_EXCL"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_EXCL</span></code></a> flag for <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>.  The
file is readable and writable only by the creating user ID.  If the
platform uses permission bits to indicate whether a file is executable,
the file is executable by no one.  The file descriptor is not inherited
by child processes.</p>
<p>Unlike <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a>, the user of <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> is responsible
for deleting the temporary file when done with it.</p>
<p>If <em>suffix</em> is specified, the file name will end with that suffix,
otherwise there will be no suffix.  <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> does not put a dot
between the file name and the suffix; if you need one, put it at the
beginning of <em>suffix</em>.</p>
<p>If <em>prefix</em> is specified, the file name will begin with that prefix;
otherwise, a default prefix is used.</p>
<p>If <em>dir</em> is specified, the file will be created in that directory;
otherwise, a default directory is used.  The default directory is chosen
from a platform-dependent list, but the user of the application can
control the directory location by setting the <em>TMPDIR</em>, <em>TEMP</em> or <em>TMP</em>
environment variables.  There is thus no guarantee that the generated
filename will have any nice properties, such as not requiring quoting
when passed to external commands via <code class="docutils literal notranslate"><span class="pre">os.popen()</span></code>.</p>
<p>If <em>text</em> is specified, it indicates whether to open the file in binary
mode (the default) or text mode.  On some platforms, this makes no
difference.</p>
<p><a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> returns a tuple containing an OS-level handle to an open
file (as would be returned by <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>) and the absolute pathname
of that file, in that order.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="tempfile.mkdtemp">
<code class="descclassname">tempfile.</code><code class="descname">mkdtemp</code><span class="sig-paren">(</span><span class="optional">[</span><em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mkdtemp" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a temporary directory in the most secure manner possible. There
are no race conditions in the directory’s creation.  The directory is
readable, writable, and searchable only by the creating user ID.</p>
<p>The user of <a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a> is responsible for deleting the temporary
directory and its contents when done with it.</p>
<p>The <em>prefix</em>, <em>suffix</em>, and <em>dir</em> arguments are the same as for
<a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>.</p>
<p><a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a> returns the absolute pathname of the new directory.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="tempfile.mktemp">
<code class="descclassname">tempfile.</code><code class="descname">mktemp</code><span class="sig-paren">(</span><span class="optional">[</span><em>suffix=''</em><span class="optional">[</span>, <em>prefix='tmp'</em><span class="optional">[</span>, <em>dir=None</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mktemp" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>Use <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> instead.</p>
</div>
<p>Return an absolute pathname of a file that did not exist at the time the
call is made.  The <em>prefix</em>, <em>suffix</em>, and <em>dir</em> arguments are the same
as for <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p>Use of this function may introduce a security hole in your program.  By
the time you get around to doing anything with the file name it returns,
someone else may have beaten you to the punch.  <a class="reference internal" href="#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code></a> usage can
be replaced easily with <a class="reference internal" href="#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">NamedTemporaryFile()</span></code></a>, passing it the
<code class="docutils literal notranslate"><span class="pre">delete=False</span></code> parameter:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">NamedTemporaryFile</span><span class="p">(</span><span class="n">delete</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span>
<span class="go">&lt;open file &#39;&lt;fdopen&gt;&#39;, mode &#39;w+b&#39; at 0x384698&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">name</span>
<span class="go">&#39;/var/folders/5q/5qTPn6xq2RaWqk+1Ytw3-U+++TI/-Tmp-/tmpG7V1Y0&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Hello World!</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">unlink</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
</div>
</dd></dl>

<p>The module uses a global variable that tell it how to construct a
temporary name.  They are initialized at the first call to any of the
functions above.  The caller may change them, but this is discouraged; use
the appropriate function arguments, instead.</p>
<dl class="data">
<dt id="tempfile.tempdir">
<code class="descclassname">tempfile.</code><code class="descname">tempdir</code><a class="headerlink" href="#tempfile.tempdir" title="Permalink to this definition">¶</a></dt>
<dd><p>When set to a value other than <code class="docutils literal notranslate"><span class="pre">None</span></code>, this variable defines the
default value for the <em>dir</em> argument to all the functions defined in this
module.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">tempdir</span></code> is unset or <code class="docutils literal notranslate"><span class="pre">None</span></code> at any call to any of the above
functions, Python searches a standard list of directories and sets
<em>tempdir</em> to the first one which the calling user can create files in.
The list is:</p>
<ol class="arabic simple">
<li>The directory named by the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMPDIR</span></code> environment variable.</li>
<li>The directory named by the <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TEMP</span></code> environment variable.</li>
<li>The directory named by the <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMP</span></code> environment variable.</li>
<li>A platform-specific location:<ul>
<li>On RiscOS, the directory named by the <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">Wimp$ScrapDir</span></code> environment
variable.</li>
<li>On Windows, the directories <code class="file docutils literal notranslate"><span class="pre">C:\TEMP</span></code>, <code class="file docutils literal notranslate"><span class="pre">C:\TMP</span></code>,
<code class="file docutils literal notranslate"><span class="pre">\TEMP</span></code>, and <code class="file docutils literal notranslate"><span class="pre">\TMP</span></code>, in that order.</li>
<li>On all other platforms, the directories <code class="file docutils literal notranslate"><span class="pre">/tmp</span></code>, <code class="file docutils literal notranslate"><span class="pre">/var/tmp</span></code>, and
<code class="file docutils literal notranslate"><span class="pre">/usr/tmp</span></code>, in that order.</li>
</ul>
</li>
<li>As a last resort, the current working directory.</li>
</ol>
</dd></dl>

<dl class="function">
<dt id="tempfile.gettempdir">
<code class="descclassname">tempfile.</code><code class="descname">gettempdir</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the directory currently selected to create temporary files in. If
<a class="reference internal" href="#tempfile.tempdir" title="tempfile.tempdir"><code class="xref py py-data docutils literal notranslate"><span class="pre">tempdir</span></code></a> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this simply returns its contents; otherwise,
the search described above is performed, and the result returned.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="tempfile.template">
<code class="descclassname">tempfile.</code><code class="descname">template</code><a class="headerlink" href="#tempfile.template" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Use <a class="reference internal" href="#tempfile.gettempprefix" title="tempfile.gettempprefix"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempprefix()</span></code></a> instead.</p>
</div>
<p>When set to a value other than <code class="docutils literal notranslate"><span class="pre">None</span></code>, this variable defines the prefix of the
final component of the filenames returned by <a class="reference internal" href="#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code></a>.  A string of six
random letters and digits is appended to the prefix to make the filename unique.
The default prefix is <code class="file docutils literal notranslate"><span class="pre">tmp</span></code>.</p>
<p>Older versions of this module used to require that <code class="docutils literal notranslate"><span class="pre">template</span></code> be set to
<code class="docutils literal notranslate"><span class="pre">None</span></code> after a call to <a class="reference internal" href="os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a>; this has not been necessary since
version 1.5.2.</p>
</dd></dl>

<dl class="function">
<dt id="tempfile.gettempprefix">
<code class="descclassname">tempfile.</code><code class="descname">gettempprefix</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempprefix" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the filename prefix used to create temporary files.  This does not
contain the directory component.  Using this function is preferred over reading
the <em>template</em> variable directly.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="filecmp.html"
                        title="previous chapter">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="glob.html"
                        title="next chapter">10.7. <code class="docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tempfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="glob.html" title="10.7. glob — Unix style pathname pattern expansion"
             >next</a> |</li>
        <li class="right" >
          <a href="filecmp.html" title="10.5. filecmp — File and Directory Comparisons"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="filesys.html" >10. File and Directory Access</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�,�C�Chtml/library/termios.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.7. termios — POSIX style tty control &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.8. tty — Terminal control functions" href="tty.html" />
    <link rel="prev" title="36.6. dl — Call C functions in shared objects" href="dl.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/termios.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tty.html" title="36.8. tty — Terminal control functions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="dl.html" title="36.6. dl — Call C functions in shared objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-termios">
<span id="termios-posix-style-tty-control"></span><h1>36.7. <a class="reference internal" href="#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> — POSIX style tty control<a class="headerlink" href="#module-termios" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module provides an interface to the POSIX calls for tty I/O control. For a
complete description of these calls, see <em class="manpage">termios(2)</em> Unix manual
page.  It is only available for those Unix versions that support POSIX
<em>termios</em> style tty I/O control configured during installation.</p>
<p>All functions in this module take a file descriptor <em>fd</em> as their first
argument.  This can be an integer file descriptor, such as returned by
<code class="docutils literal notranslate"><span class="pre">sys.stdin.fileno()</span></code>, or a file object, such as <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code> itself.</p>
<p>This module also defines all the constants needed to work with the functions
provided here; these have the same name as their counterparts in C.  Please
refer to your system documentation for more information on using these terminal
control interfaces.</p>
<p>The module defines the following functions:</p>
<dl class="function">
<dt id="termios.tcgetattr">
<code class="descclassname">termios.</code><code class="descname">tcgetattr</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcgetattr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list containing the tty attributes for file descriptor <em>fd</em>, as
follows: <code class="docutils literal notranslate"><span class="pre">[iflag,</span> <span class="pre">oflag,</span> <span class="pre">cflag,</span> <span class="pre">lflag,</span> <span class="pre">ispeed,</span> <span class="pre">ospeed,</span> <span class="pre">cc]</span></code> where <em>cc</em> is a
list of the tty special characters (each a string of length 1, except the
items with indices <code class="xref py py-const docutils literal notranslate"><span class="pre">VMIN</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">VTIME</span></code>, which are integers when
these fields are defined).  The interpretation of the flags and the speeds as
well as the indexing in the <em>cc</em> array must be done using the symbolic
constants defined in the <a class="reference internal" href="#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> module.</p>
</dd></dl>

<dl class="function">
<dt id="termios.tcsetattr">
<code class="descclassname">termios.</code><code class="descname">tcsetattr</code><span class="sig-paren">(</span><em>fd</em>, <em>when</em>, <em>attributes</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcsetattr" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the tty attributes for file descriptor <em>fd</em> from the <em>attributes</em>, which is
a list like the one returned by <a class="reference internal" href="#termios.tcgetattr" title="termios.tcgetattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">tcgetattr()</span></code></a>.  The <em>when</em> argument
determines when the attributes are changed: <code class="xref py py-const docutils literal notranslate"><span class="pre">TCSANOW</span></code> to change
immediately, <code class="xref py py-const docutils literal notranslate"><span class="pre">TCSADRAIN</span></code> to change after transmitting all queued output,
or <code class="xref py py-const docutils literal notranslate"><span class="pre">TCSAFLUSH</span></code> to change after transmitting all queued output and
discarding all queued input.</p>
</dd></dl>

<dl class="function">
<dt id="termios.tcsendbreak">
<code class="descclassname">termios.</code><code class="descname">tcsendbreak</code><span class="sig-paren">(</span><em>fd</em>, <em>duration</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcsendbreak" title="Permalink to this definition">¶</a></dt>
<dd><p>Send a break on file descriptor <em>fd</em>.  A zero <em>duration</em> sends a break for 0.25
–0.5 seconds; a nonzero <em>duration</em> has a system dependent meaning.</p>
</dd></dl>

<dl class="function">
<dt id="termios.tcdrain">
<code class="descclassname">termios.</code><code class="descname">tcdrain</code><span class="sig-paren">(</span><em>fd</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcdrain" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until all output written to file descriptor <em>fd</em> has been transmitted.</p>
</dd></dl>

<dl class="function">
<dt id="termios.tcflush">
<code class="descclassname">termios.</code><code class="descname">tcflush</code><span class="sig-paren">(</span><em>fd</em>, <em>queue</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcflush" title="Permalink to this definition">¶</a></dt>
<dd><p>Discard queued data on file descriptor <em>fd</em>.  The <em>queue</em> selector specifies
which queue: <code class="xref py py-const docutils literal notranslate"><span class="pre">TCIFLUSH</span></code> for the input queue, <code class="xref py py-const docutils literal notranslate"><span class="pre">TCOFLUSH</span></code> for the
output queue, or <code class="xref py py-const docutils literal notranslate"><span class="pre">TCIOFLUSH</span></code> for both queues.</p>
</dd></dl>

<dl class="function">
<dt id="termios.tcflow">
<code class="descclassname">termios.</code><code class="descname">tcflow</code><span class="sig-paren">(</span><em>fd</em>, <em>action</em><span class="sig-paren">)</span><a class="headerlink" href="#termios.tcflow" title="Permalink to this definition">¶</a></dt>
<dd><p>Suspend or resume input or output on file descriptor <em>fd</em>.  The <em>action</em>
argument can be <code class="xref py py-const docutils literal notranslate"><span class="pre">TCOOFF</span></code> to suspend output, <code class="xref py py-const docutils literal notranslate"><span class="pre">TCOON</span></code> to restart
output, <code class="xref py py-const docutils literal notranslate"><span class="pre">TCIOFF</span></code> to suspend input, or <code class="xref py py-const docutils literal notranslate"><span class="pre">TCION</span></code> to restart input.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="tty.html#module-tty" title="tty: Utility functions that perform common terminal control operations. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tty</span></code></a></dt>
<dd>Convenience functions for common terminal control operations.</dd>
</dl>
</div>
<div class="section" id="example">
<h2>36.7.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p id="termios-example">Here’s a function that prompts for a password with echoing turned off.  Note the
technique using a separate <a class="reference internal" href="#termios.tcgetattr" title="termios.tcgetattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">tcgetattr()</span></code></a> call and a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> …
<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement to ensure that the old tty attributes are restored
exactly no matter what happens:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">getpass</span><span class="p">(</span><span class="n">prompt</span><span class="o">=</span><span class="s2">&quot;Password: &quot;</span><span class="p">):</span>
    <span class="kn">import</span> <span class="nn">termios</span><span class="o">,</span> <span class="nn">sys</span>
    <span class="n">fd</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">fileno</span><span class="p">()</span>
    <span class="n">old</span> <span class="o">=</span> <span class="n">termios</span><span class="o">.</span><span class="n">tcgetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">)</span>
    <span class="n">new</span> <span class="o">=</span> <span class="n">termios</span><span class="o">.</span><span class="n">tcgetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">)</span>
    <span class="n">new</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="n">new</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">&amp;</span> <span class="o">~</span><span class="n">termios</span><span class="o">.</span><span class="n">ECHO</span>          <span class="c1"># lflags</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">termios</span><span class="o">.</span><span class="n">tcsetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TCSADRAIN</span><span class="p">,</span> <span class="n">new</span><span class="p">)</span>
        <span class="n">passwd</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">termios</span><span class="o">.</span><span class="n">tcsetattr</span><span class="p">(</span><span class="n">fd</span><span class="p">,</span> <span class="n">termios</span><span class="o">.</span><span class="n">TCSADRAIN</span><span class="p">,</span> <span class="n">old</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">passwd</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a><ul>
<li><a class="reference internal" href="#example">36.7.1. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="dl.html"
                        title="previous chapter">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tty.html"
                        title="next chapter">36.8. <code class="docutils literal notranslate"><span class="pre">tty</span></code> — Terminal control functions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/termios.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tty.html" title="36.8. tty — Terminal control functions"
             >next</a> |</li>
        <li class="right" >
          <a href="dl.html" title="36.6. dl — Call C functions in shared objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��~����html/library/test.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25.5. test — Regression tests package for Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26. Debugging and Profiling" href="debug.html" />
    <link rel="prev" title="25.4. 2to3 - Automated Python 2 to 3 code translation" href="2to3.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/test.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="debug.html" title="26. Debugging and Profiling"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2to3.html" title="25.4. 2to3 - Automated Python 2 to 3 code translation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">25. Development Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-test">
<span id="test-regression-tests-package-for-python"></span><h1>25.5. <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> — Regression tests package for Python<a class="headerlink" href="#module-test" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package is meant for internal use by Python only. It is
documented for the benefit of the core developers of Python. Any use of
this package outside of Python’s standard library is discouraged as code
mentioned here can change or be removed without notice between releases of
Python.</p>
</div>
<p>The <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package contains all regression tests for Python as well as the
modules <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code>.
<a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> is used to enhance your tests while
<code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> drives the testing suite.</p>
<p>Each module in the <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package whose name starts with <code class="docutils literal notranslate"><span class="pre">test_</span></code> is a
testing suite for a specific module or feature. All new tests should be written
using the <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> or <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module.  Some older tests are
written using a “traditional” testing style that compares output printed to
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>; this style of test is considered deprecated.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a></dt>
<dd>Writing PyUnit regression tests.</dd>
<dt>Module <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a></dt>
<dd>Tests embedded in documentation strings.</dd>
</dl>
</div>
<div class="section" id="writing-unit-tests-for-the-test-package">
<span id="writing-tests"></span><h2>25.5.1. Writing Unit Tests for the <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package<a class="headerlink" href="#writing-unit-tests-for-the-test-package" title="Permalink to this headline">¶</a></h2>
<p>It is preferred that tests that use the <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module follow a few
guidelines. One is to name the test module by starting it with <code class="docutils literal notranslate"><span class="pre">test_</span></code> and end
it with the name of the module being tested. The test methods in the test module
should start with <code class="docutils literal notranslate"><span class="pre">test_</span></code> and end with a description of what the method is
testing. This is needed so that the methods are recognized by the test driver as
test methods. Also, no documentation string for the method should be included. A
comment (such as <code class="docutils literal notranslate"><span class="pre">#</span> <span class="pre">Tests</span> <span class="pre">function</span> <span class="pre">returns</span> <span class="pre">only</span> <span class="pre">True</span> <span class="pre">or</span> <span class="pre">False</span></code>) should be used
to provide documentation for test methods. This is done because documentation
strings get printed out if they exist and thus what test is being run is not
stated.</p>
<p>A basic boilerplate is often used:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>
<span class="kn">from</span> <span class="nn">test</span> <span class="k">import</span> <span class="n">support</span>

<span class="k">class</span> <span class="nc">MyTestCase1</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="c1"># Only use setUp() and tearDown() if necessary</span>

    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span> <span class="n">code</span> <span class="n">to</span> <span class="n">execute</span> <span class="ow">in</span> <span class="n">preparation</span> <span class="k">for</span> <span class="n">tests</span> <span class="o">...</span>

    <span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span> <span class="n">code</span> <span class="n">to</span> <span class="n">execute</span> <span class="n">to</span> <span class="n">clean</span> <span class="n">up</span> <span class="n">after</span> <span class="n">tests</span> <span class="o">...</span>

    <span class="k">def</span> <span class="nf">test_feature_one</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Test feature one.</span>
        <span class="o">...</span> <span class="n">testing</span> <span class="n">code</span> <span class="o">...</span>

    <span class="k">def</span> <span class="nf">test_feature_two</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Test feature two.</span>
        <span class="o">...</span> <span class="n">testing</span> <span class="n">code</span> <span class="o">...</span>

    <span class="o">...</span> <span class="n">more</span> <span class="n">test</span> <span class="n">methods</span> <span class="o">...</span>

<span class="k">class</span> <span class="nc">MyTestCase2</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="o">...</span> <span class="n">same</span> <span class="n">structure</span> <span class="k">as</span> <span class="n">MyTestCase1</span> <span class="o">...</span>

<span class="o">...</span> <span class="n">more</span> <span class="n">test</span> <span class="n">classes</span> <span class="o">...</span>

<span class="k">def</span> <span class="nf">test_main</span><span class="p">():</span>
    <span class="n">support</span><span class="o">.</span><span class="n">run_unittest</span><span class="p">(</span><span class="n">MyTestCase1</span><span class="p">,</span>
                         <span class="n">MyTestCase2</span><span class="p">,</span>
                         <span class="o">...</span> <span class="nb">list</span> <span class="n">other</span> <span class="n">tests</span> <span class="o">...</span>
                         <span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">test_main</span><span class="p">()</span>
</pre></div>
</div>
<p>This boilerplate code allows the testing suite to be run by <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code>
as well as on its own as a script.</p>
<p>The goal for regression testing is to try to break code. This leads to a few
guidelines to be followed:</p>
<ul>
<li><p class="first">The testing suite should exercise all classes, functions, and constants. This
includes not just the external API that is to be presented to the outside
world but also “private” code.</p>
</li>
<li><p class="first">Whitebox testing (examining the code being tested when the tests are being
written) is preferred. Blackbox testing (testing only the published user
interface) is not complete enough to make sure all boundary and edge cases
are tested.</p>
</li>
<li><p class="first">Make sure all possible values are tested including invalid ones. This makes
sure that not only all valid values are acceptable but also that improper
values are handled correctly.</p>
</li>
<li><p class="first">Exhaust as many code paths as possible. Test where branching occurs and thus
tailor input to make sure as many different paths through the code are taken.</p>
</li>
<li><p class="first">Add an explicit test for any bugs discovered for the tested code. This will
make sure that the error does not crop up again if the code is changed in the
future.</p>
</li>
<li><p class="first">Make sure to clean up after your tests (such as close and remove all temporary
files).</p>
</li>
<li><p class="first">If a test is dependent on a specific condition of the operating system then
verify the condition already exists before attempting the test.</p>
</li>
<li><p class="first">Import as few modules as possible and do it as soon as possible. This
minimizes external dependencies of tests and also minimizes possible anomalous
behavior from side-effects of importing a module.</p>
</li>
<li><p class="first">Try to maximize code reuse. On occasion, tests will vary by something as small
as what type of input is used. Minimize code duplication by subclassing a
basic test class with a class that specifies the input:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">TestFuncAcceptsSequences</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="n">func</span> <span class="o">=</span> <span class="n">mySuperWhammyFunction</span>

    <span class="k">def</span> <span class="nf">test_func</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">func</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">arg</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">AcceptLists</span><span class="p">(</span><span class="n">TestFuncAcceptsSequences</span><span class="p">):</span>
    <span class="n">arg</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>

<span class="k">class</span> <span class="nc">AcceptStrings</span><span class="p">(</span><span class="n">TestFuncAcceptsSequences</span><span class="p">):</span>
    <span class="n">arg</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>

<span class="k">class</span> <span class="nc">AcceptTuples</span><span class="p">(</span><span class="n">TestFuncAcceptsSequences</span><span class="p">):</span>
    <span class="n">arg</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Test Driven Development</dt>
<dd>A book by Kent Beck on writing tests before code.</dd>
</dl>
</div>
</div>
<div class="section" id="running-tests-using-the-command-line-interface">
<span id="regrtest"></span><h2>25.5.2. Running tests using the command-line interface<a class="headerlink" href="#running-tests-using-the-command-line-interface" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> module can be run as a script to drive Python’s regression
test suite, thanks to the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> option: <strong class="program">python -m test.regrtest</strong>.
Running the script by itself automatically starts running all regression
tests in the <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package. It does this by finding all modules in the
package whose name starts with <code class="docutils literal notranslate"><span class="pre">test_</span></code>, importing them, and executing the
function <code class="xref py py-func docutils literal notranslate"><span class="pre">test_main()</span></code> if present. The names of tests to execute may also
be passed to the script. Specifying a single regression test (<strong class="program">python
-m test.regrtest test_spam</strong>) will minimize output and only print whether
the test passed or failed and thus minimize output.</p>
<p>Running <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> directly allows what resources are available for
tests to use to be set. You do this by using the <code class="docutils literal notranslate"><span class="pre">-u</span></code> command-line
option. Specifying <code class="docutils literal notranslate"><span class="pre">all</span></code> as the value for the <code class="docutils literal notranslate"><span class="pre">-u</span></code> option enables all
possible resources: <strong class="program">python -m test.regrtest -uall</strong>.
If all but one resource is desired (a more common case), a
comma-separated list of resources that are not desired may be listed after
<code class="docutils literal notranslate"><span class="pre">all</span></code>. The command <strong class="program">python -m test.regrtest -uall,-audio,-largefile</strong>
will run <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> with all resources except the <code class="docutils literal notranslate"><span class="pre">audio</span></code> and
<code class="docutils literal notranslate"><span class="pre">largefile</span></code> resources. For a list of all resources and more command-line
options, run <strong class="program">python -m test.regrtest -h</strong>.</p>
<p>Some other ways to execute the regression tests depend on what platform the
tests are being executed on. On Unix, you can run <strong class="program">make test</strong> at the
top-level directory where Python was built. On Windows, executing
<strong class="program">rt.bat</strong> from your <code class="file docutils literal notranslate"><span class="pre">PCBuild</span></code> directory will run all regression
tests.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.14: </span>The <a class="reference internal" href="#module-test" title="test: Regression tests package containing the testing suite for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test</span></code></a> package can be run as a script: <strong class="program">python -m test</strong>.
This works the same as running the <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> module.</p>
</div>
</div>
</div>
<div class="section" id="module-test.support">
<span id="test-support-utility-functions-for-tests"></span><h1>25.6. <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> — Utility functions for tests<a class="headerlink" href="#module-test.support" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.test_support</span></code> module has been renamed to <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a>
in Python 3.x and 2.7.14.  The name <code class="docutils literal notranslate"><span class="pre">test.test_support</span></code> has been retained
as an alias in 2.7.</p>
</div>
<p>The <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> module provides support for Python’s regression
tests.</p>
<p>This module defines the following exceptions:</p>
<dl class="exception">
<dt id="test.support.TestFailed">
<em class="property">exception </em><code class="descclassname">test.support.</code><code class="descname">TestFailed</code><a class="headerlink" href="#test.support.TestFailed" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception to be raised when a test fails. This is deprecated in favor of
<a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>-based tests and <a class="reference internal" href="unittest.html#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a>’s assertion
methods.</p>
</dd></dl>

<dl class="exception">
<dt id="test.support.ResourceDenied">
<em class="property">exception </em><code class="descclassname">test.support.</code><code class="descname">ResourceDenied</code><a class="headerlink" href="#test.support.ResourceDenied" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="unittest.html#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">unittest.SkipTest</span></code></a>. Raised when a resource (such as a
network connection) is not available. Raised by the <a class="reference internal" href="#test.support.requires" title="test.support.requires"><code class="xref py py-func docutils literal notranslate"><span class="pre">requires()</span></code></a>
function.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> module defines the following constants:</p>
<dl class="data">
<dt id="test.support.verbose">
<code class="descclassname">test.support.</code><code class="descname">verbose</code><a class="headerlink" href="#test.support.verbose" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> when verbose output is enabled. Should be checked when more
detailed information is desired about a running test. <em>verbose</em> is set by
<code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="test.support.have_unicode">
<code class="descclassname">test.support.</code><code class="descname">have_unicode</code><a class="headerlink" href="#test.support.have_unicode" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> when Unicode support is available.</p>
</dd></dl>

<dl class="data">
<dt id="test.support.is_jython">
<code class="descclassname">test.support.</code><code class="descname">is_jython</code><a class="headerlink" href="#test.support.is_jython" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if the running interpreter is Jython.</p>
</dd></dl>

<dl class="data">
<dt id="test.support.TESTFN">
<code class="descclassname">test.support.</code><code class="descname">TESTFN</code><a class="headerlink" href="#test.support.TESTFN" title="Permalink to this definition">¶</a></dt>
<dd><p>Set to a name that is safe to use as the name of a temporary file.  Any
temporary file that is created should be closed and unlinked (removed).</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="test.support.forget">
<code class="descclassname">test.support.</code><code class="descname">forget</code><span class="sig-paren">(</span><em>module_name</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.forget" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove the module named <em>module_name</em> from <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> and delete any
byte-compiled files of the module.</p>
</dd></dl>

<dl class="function">
<dt id="test.support.is_resource_enabled">
<code class="descclassname">test.support.</code><code class="descname">is_resource_enabled</code><span class="sig-paren">(</span><em>resource</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.is_resource_enabled" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>resource</em> is enabled and available. The list of
available resources is only set when <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code> is executing the
tests.</p>
</dd></dl>

<dl class="function">
<dt id="test.support.requires">
<code class="descclassname">test.support.</code><code class="descname">requires</code><span class="sig-paren">(</span><em>resource</em><span class="optional">[</span>, <em>msg</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#test.support.requires" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise <a class="reference internal" href="#test.support.ResourceDenied" title="test.support.ResourceDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceDenied</span></code></a> if <em>resource</em> is not available. <em>msg</em> is the
argument to <a class="reference internal" href="#test.support.ResourceDenied" title="test.support.ResourceDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceDenied</span></code></a> if it is raised. Always returns
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if called by a function whose <code class="docutils literal notranslate"><span class="pre">__name__</span></code> is <code class="docutils literal notranslate"><span class="pre">'__main__'</span></code>.
Used when tests are executed by <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.regrtest</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="test.support.findfile">
<code class="descclassname">test.support.</code><code class="descname">findfile</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.findfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the path to the file named <em>filename</em>. If no match is found
<em>filename</em> is returned. This does not equal a failure since it could be the
path to the file.</p>
</dd></dl>

<dl class="function">
<dt id="test.support.run_unittest">
<code class="descclassname">test.support.</code><code class="descname">run_unittest</code><span class="sig-paren">(</span><em>*classes</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.run_unittest" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute <a class="reference internal" href="unittest.html#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a> subclasses passed to the function. The
function scans the classes for methods starting with the prefix <code class="docutils literal notranslate"><span class="pre">test_</span></code>
and executes the tests individually.</p>
<p>It is also legal to pass strings as parameters; these should be keys in
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>. Each associated module will be scanned by
<code class="docutils literal notranslate"><span class="pre">unittest.TestLoader.loadTestsFromModule()</span></code>. This is usually seen in the
following <code class="xref py py-func docutils literal notranslate"><span class="pre">test_main()</span></code> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test_main</span><span class="p">():</span>
    <span class="n">support</span><span class="o">.</span><span class="n">run_unittest</span><span class="p">(</span><span class="vm">__name__</span><span class="p">)</span>
</pre></div>
</div>
<p>This will run all tests defined in the named module.</p>
</dd></dl>

<dl class="function">
<dt id="test.support.check_warnings">
<code class="descclassname">test.support.</code><code class="descname">check_warnings</code><span class="sig-paren">(</span><em>*filters</em>, <em>quiet=True</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.check_warnings" title="Permalink to this definition">¶</a></dt>
<dd><p>A convenience wrapper for <a class="reference internal" href="warnings.html#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.catch_warnings()</span></code></a> that makes it
easier to test that a warning was correctly raised.  It is approximately
equivalent to calling <code class="docutils literal notranslate"><span class="pre">warnings.catch_warnings(record=True)</span></code> with
<a class="reference internal" href="warnings.html#warnings.simplefilter" title="warnings.simplefilter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">warnings.simplefilter()</span></code></a> set to <code class="docutils literal notranslate"><span class="pre">always</span></code> and with the option to
automatically validate the results that are recorded.</p>
<p><code class="docutils literal notranslate"><span class="pre">check_warnings</span></code> accepts 2-tuples of the form <code class="docutils literal notranslate"><span class="pre">(&quot;message</span> <span class="pre">regexp&quot;,</span>
<span class="pre">WarningCategory)</span></code> as positional arguments. If one or more <em>filters</em> are
provided, or if the optional keyword argument <em>quiet</em> is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>,
it checks to make sure the warnings are as expected:  each specified filter
must match at least one of the warnings raised by the enclosed code or the
test fails, and if any warnings are raised that do not match any of the
specified filters the test fails.  To disable the first of these checks,
set <em>quiet</em> to <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<p>If no arguments are specified, it defaults to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">check_warnings</span><span class="p">((</span><span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="ne">Warning</span><span class="p">),</span> <span class="n">quiet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>In this case all warnings are caught and no errors are raised.</p>
<p>On entry to the context manager, a <code class="xref py py-class docutils literal notranslate"><span class="pre">WarningRecorder</span></code> instance is
returned. The underlying warnings list from
<a class="reference internal" href="warnings.html#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">catch_warnings()</span></code></a> is available via the recorder object’s
<a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-attr docutils literal notranslate"><span class="pre">warnings</span></code></a> attribute.  As a convenience, the attributes of the object
representing the most recent warning can also be accessed directly through
the recorder object (see example below).  If no warning has been raised,
then any of the attributes that would otherwise be expected on an object
representing a warning will return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>The recorder object also has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">reset()</span></code> method, which clears the
warnings list.</p>
<p>The context manager is designed to be used like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">check_warnings</span><span class="p">((</span><span class="s2">&quot;assertion is always true&quot;</span><span class="p">,</span> <span class="ne">SyntaxWarning</span><span class="p">),</span>
                    <span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="ne">UserWarning</span><span class="p">)):</span>
    <span class="n">exec</span><span class="p">(</span><span class="s1">&#39;assert(False, &quot;Hey!&quot;)&#39;</span><span class="p">)</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="ne">UserWarning</span><span class="p">(</span><span class="s2">&quot;Hide me!&quot;</span><span class="p">))</span>
</pre></div>
</div>
<p>In this case if either warning was not raised, or some other warning was
raised, <a class="reference internal" href="#test.support.check_warnings" title="test.support.check_warnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code></a> would raise an error.</p>
<p>When a test needs to look more deeply into the warnings, rather than
just checking whether or not they occurred, code like this can be used:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">check_warnings</span><span class="p">(</span><span class="n">quiet</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">as</span> <span class="n">w</span><span class="p">:</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;foo&quot;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="s2">&quot;foo&quot;</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;bar&quot;</span><span class="p">)</span>
    <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="s2">&quot;bar&quot;</span>
    <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="o">.</span><span class="n">warnings</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="s2">&quot;foo&quot;</span>
    <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="o">.</span><span class="n">warnings</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">args</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="o">==</span> <span class="s2">&quot;bar&quot;</span>
    <span class="n">w</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</span><span class="o">.</span><span class="n">warnings</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span>
</pre></div>
</div>
<p>Here all warnings will be caught, and the test code tests the captured
warnings directly.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>New optional arguments <em>filters</em> and <em>quiet</em>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="test.support.check_py3k_warnings">
<code class="descclassname">test.support.</code><code class="descname">check_py3k_warnings</code><span class="sig-paren">(</span><em>*filters</em>, <em>quiet=False</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.check_py3k_warnings" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#test.support.check_warnings" title="test.support.check_warnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code></a>, but for Python 3 compatibility warnings.
If <code class="docutils literal notranslate"><span class="pre">sys.py3kwarning</span> <span class="pre">==</span> <span class="pre">1</span></code>, it checks if the warning is effectively raised.
If <code class="docutils literal notranslate"><span class="pre">sys.py3kwarning</span> <span class="pre">==</span> <span class="pre">0</span></code>, it checks that no warning is raised.  It
accepts 2-tuples of the form <code class="docutils literal notranslate"><span class="pre">(&quot;message</span> <span class="pre">regexp&quot;,</span> <span class="pre">WarningCategory)</span></code> as
positional arguments.  When the optional keyword argument <em>quiet</em> is
<a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, it does not fail if a filter catches nothing.  Without
arguments, it defaults to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">check_py3k_warnings</span><span class="p">((</span><span class="s2">&quot;&quot;</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">),</span> <span class="n">quiet</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="test.support.captured_stdout">
<code class="descclassname">test.support.</code><code class="descname">captured_stdout</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#test.support.captured_stdout" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a context manager that runs the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement body using
a <a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO.StringIO</span></code></a> object as sys.stdout.  That object can be
retrieved using the <code class="docutils literal notranslate"><span class="pre">as</span></code> clause of the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>Example use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">captured_stdout</span><span class="p">()</span> <span class="k">as</span> <span class="n">s</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;hello&quot;</span>
<span class="k">assert</span> <span class="n">s</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span> <span class="o">==</span> <span class="s2">&quot;hello</span><span class="se">\n</span><span class="s2">&quot;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="test.support.import_module">
<code class="descclassname">test.support.</code><code class="descname">import_module</code><span class="sig-paren">(</span><em>name</em>, <em>deprecated=False</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.import_module" title="Permalink to this definition">¶</a></dt>
<dd><p>This function imports and returns the named module. Unlike a normal
import, this function raises <a class="reference internal" href="unittest.html#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">unittest.SkipTest</span></code></a> if the module
cannot be imported.</p>
<p>Module and package deprecation messages are suppressed during this import
if <em>deprecated</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="test.support.import_fresh_module">
<code class="descclassname">test.support.</code><code class="descname">import_fresh_module</code><span class="sig-paren">(</span><em>name</em>, <em>fresh=()</em>, <em>blocked=()</em>, <em>deprecated=False</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.import_fresh_module" title="Permalink to this definition">¶</a></dt>
<dd><p>This function imports and returns a fresh copy of the named Python module
by removing the named module from <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> before doing the import.
Note that unlike <a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a>, the original module is not affected by
this operation.</p>
<p><em>fresh</em> is an iterable of additional module names that are also removed
from the <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> cache before doing the import.</p>
<p><em>blocked</em> is an iterable of module names that are replaced with <code class="xref py py-const docutils literal notranslate"><span class="pre">0</span></code>
in the module cache during the import to ensure that attempts to import
them raise <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.</p>
<p>The named module and any modules named in the <em>fresh</em> and <em>blocked</em>
parameters are saved before starting the import and then reinserted into
<code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> when the fresh import is complete.</p>
<p>Module and package deprecation messages are suppressed during this import
if <em>deprecated</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<p>This function will raise <a class="reference internal" href="unittest.html#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">unittest.SkipTest</span></code></a> if the named module
cannot be imported.</p>
<p>Example use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Get copies of the warnings module for testing without</span>
<span class="c1"># affecting the version being used by the rest of the test suite</span>
<span class="c1"># One copy uses the C implementation, the other is forced to use</span>
<span class="c1"># the pure Python fallback implementation</span>
<span class="n">py_warnings</span> <span class="o">=</span> <span class="n">import_fresh_module</span><span class="p">(</span><span class="s1">&#39;warnings&#39;</span><span class="p">,</span> <span class="n">blocked</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;_warnings&#39;</span><span class="p">])</span>
<span class="n">c_warnings</span> <span class="o">=</span> <span class="n">import_fresh_module</span><span class="p">(</span><span class="s1">&#39;warnings&#39;</span><span class="p">,</span> <span class="n">fresh</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;_warnings&#39;</span><span class="p">])</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>The <a class="reference internal" href="#module-test.support" title="test.support: Support for Python regression tests."><code class="xref py py-mod docutils literal notranslate"><span class="pre">test.support</span></code></a> module defines the following classes:</p>
<dl class="class">
<dt id="test.support.TransientResource">
<em class="property">class </em><code class="descclassname">test.support.</code><code class="descname">TransientResource</code><span class="sig-paren">(</span><em>exc</em><span class="optional">[</span>, <em>**kwargs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#test.support.TransientResource" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances are a context manager that raises <a class="reference internal" href="#test.support.ResourceDenied" title="test.support.ResourceDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceDenied</span></code></a> if the
specified exception type is raised.  Any keyword arguments are treated as
attribute/value pairs to be compared against any exception raised within the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  Only if all pairs match properly against
attributes on the exception is <a class="reference internal" href="#test.support.ResourceDenied" title="test.support.ResourceDenied"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ResourceDenied</span></code></a> raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="test.support.EnvironmentVarGuard">
<em class="property">class </em><code class="descclassname">test.support.</code><code class="descname">EnvironmentVarGuard</code><a class="headerlink" href="#test.support.EnvironmentVarGuard" title="Permalink to this definition">¶</a></dt>
<dd><p>Class used to temporarily set or unset environment variables.  Instances can
be used as a context manager and have a complete dictionary interface for
querying/modifying the underlying <code class="docutils literal notranslate"><span class="pre">os.environ</span></code>. After exit from the
context manager all changes to environment variables done through this
instance will be rolled back.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added dictionary interface.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="test.support.EnvironmentVarGuard.set">
<code class="descclassname">EnvironmentVarGuard.</code><code class="descname">set</code><span class="sig-paren">(</span><em>envvar</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.EnvironmentVarGuard.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Temporarily set the environment variable <code class="docutils literal notranslate"><span class="pre">envvar</span></code> to the value of
<code class="docutils literal notranslate"><span class="pre">value</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="test.support.EnvironmentVarGuard.unset">
<code class="descclassname">EnvironmentVarGuard.</code><code class="descname">unset</code><span class="sig-paren">(</span><em>envvar</em><span class="sig-paren">)</span><a class="headerlink" href="#test.support.EnvironmentVarGuard.unset" title="Permalink to this definition">¶</a></dt>
<dd><p>Temporarily unset the environment variable <code class="docutils literal notranslate"><span class="pre">envvar</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="test.support.WarningsRecorder">
<em class="property">class </em><code class="descclassname">test.support.</code><code class="descname">WarningsRecorder</code><a class="headerlink" href="#test.support.WarningsRecorder" title="Permalink to this definition">¶</a></dt>
<dd><p>Class used to record warnings for unit tests. See documentation of
<a class="reference internal" href="#test.support.check_warnings" title="test.support.check_warnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code></a> above for more details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a><ul>
<li><a class="reference internal" href="#writing-unit-tests-for-the-test-package">25.5.1. Writing Unit Tests for the <code class="docutils literal notranslate"><span class="pre">test</span></code> package</a></li>
<li><a class="reference internal" href="#running-tests-using-the-command-line-interface">25.5.2. Running tests using the command-line interface</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-test.support">25.6. <code class="docutils literal notranslate"><span class="pre">test.support</span></code> — Utility functions for tests</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2to3.html"
                        title="previous chapter">25.4. 2to3 - Automated Python 2 to 3 code translation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="debug.html"
                        title="next chapter">26. Debugging and Profiling</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/test.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="debug.html" title="26. Debugging and Profiling"
             >next</a> |</li>
        <li class="right" >
          <a href="2to3.html" title="25.4. 2to3 - Automated Python 2 to 3 code translation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" >25. Development Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\W$i�u�uhtml/library/textwrap.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.7. textwrap — Text wrapping and filling &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.8. codecs — Codec registry and base classes" href="codecs.html" />
    <link rel="prev" title="7.5. StringIO — Read and write strings as files" href="stringio.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/textwrap.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codecs.html" title="7.8. codecs — Codec registry and base classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stringio.html" title="7.5. StringIO — Read and write strings as files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-textwrap">
<span id="textwrap-text-wrapping-and-filling"></span><h1>7.7. <a class="reference internal" href="#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> — Text wrapping and filling<a class="headerlink" href="#module-textwrap" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/textwrap.py">Lib/textwrap.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module provides two convenience functions, <a class="reference internal" href="#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a> and
<a class="reference internal" href="#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a>, as well as <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a>, the class that does all the work,
and a utility function  <a class="reference internal" href="#textwrap.dedent" title="textwrap.dedent"><code class="xref py py-func docutils literal notranslate"><span class="pre">dedent()</span></code></a>.  If you’re just wrapping or filling one
or two  text strings, the convenience functions should be good enough;
otherwise,  you should use an instance of <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> for efficiency.</p>
<dl class="function">
<dt id="textwrap.wrap">
<code class="descclassname">textwrap.</code><code class="descname">wrap</code><span class="sig-paren">(</span><em>text</em><span class="optional">[</span>, <em>width</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.wrap" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps the single paragraph in <em>text</em> (a string) so every line is at most <em>width</em>
characters long.  Returns a list of output lines, without final newlines.</p>
<p>Optional keyword arguments correspond to the instance attributes of
<a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a>, documented below.  <em>width</em> defaults to <code class="docutils literal notranslate"><span class="pre">70</span></code>.</p>
<p>See the <a class="reference internal" href="#textwrap.TextWrapper.wrap" title="textwrap.TextWrapper.wrap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TextWrapper.wrap()</span></code></a> method for additional details on how
<a class="reference internal" href="#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a> behaves.</p>
</dd></dl>

<dl class="function">
<dt id="textwrap.fill">
<code class="descclassname">textwrap.</code><code class="descname">fill</code><span class="sig-paren">(</span><em>text</em><span class="optional">[</span>, <em>width</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.fill" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps the single paragraph in <em>text</em>, and returns a single string containing the
wrapped paragraph.  <a class="reference internal" href="#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a> is shorthand for</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">wrap</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="o">...</span><span class="p">))</span>
</pre></div>
</div>
<p>In particular, <a class="reference internal" href="#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a> accepts exactly the same keyword arguments as
<a class="reference internal" href="#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a>.</p>
</dd></dl>

<p>Both <a class="reference internal" href="#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code></a> and <a class="reference internal" href="#textwrap.fill" title="textwrap.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a> work by creating a <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a>
instance and calling a single method on it.  That instance is not reused, so for
applications that wrap/fill many text strings, it will be more efficient for you
to create your own <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> object.</p>
<p>Text is preferably wrapped on whitespaces and right after the hyphens in
hyphenated words; only then will long words be broken if necessary, unless
<a class="reference internal" href="#textwrap.TextWrapper.break_long_words" title="textwrap.TextWrapper.break_long_words"><code class="xref py py-attr docutils literal notranslate"><span class="pre">TextWrapper.break_long_words</span></code></a> is set to false.</p>
<p>An additional utility function, <a class="reference internal" href="#textwrap.dedent" title="textwrap.dedent"><code class="xref py py-func docutils literal notranslate"><span class="pre">dedent()</span></code></a>, is provided to remove
indentation from strings that have unwanted whitespace to the left of the text.</p>
<dl class="function">
<dt id="textwrap.dedent">
<code class="descclassname">textwrap.</code><code class="descname">dedent</code><span class="sig-paren">(</span><em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.dedent" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove any common leading whitespace from every line in <em>text</em>.</p>
<p>This can be used to make triple-quoted strings line up with the left edge of the
display, while still presenting them in the source code in indented form.</p>
<p>Note that tabs and spaces are both treated as whitespace, but they are not
equal: the lines <code class="docutils literal notranslate"><span class="pre">&quot;</span>&#160; <span class="pre">hello&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;\thello&quot;</span></code> are considered to have no
common leading whitespace.  (This behaviour is new in Python 2.5; older versions
of this module incorrectly expanded tabs before searching for common leading
whitespace.)</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="c1"># end first line with \ to avoid the empty line!</span>
    <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;&#39;&#39;</span><span class="se">\</span>
<span class="s1">    hello</span>
<span class="s1">      world</span>
<span class="s1">    &#39;&#39;&#39;</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>          <span class="c1"># prints &#39;    hello\n      world\n    &#39;</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">dedent</span><span class="p">(</span><span class="n">s</span><span class="p">))</span>  <span class="c1"># prints &#39;hello\n  world\n&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="textwrap.TextWrapper">
<em class="property">class </em><code class="descclassname">textwrap.</code><code class="descname">TextWrapper</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.TextWrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> constructor accepts a number of optional keyword
arguments.  Each argument corresponds to one instance attribute, so for example</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">wrapper</span> <span class="o">=</span> <span class="n">TextWrapper</span><span class="p">(</span><span class="n">initial_indent</span><span class="o">=</span><span class="s2">&quot;* &quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>is the same as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">wrapper</span> <span class="o">=</span> <span class="n">TextWrapper</span><span class="p">()</span>
<span class="n">wrapper</span><span class="o">.</span><span class="n">initial_indent</span> <span class="o">=</span> <span class="s2">&quot;* &quot;</span>
</pre></div>
</div>
<p>You can re-use the same <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> object many times, and you can
change any of its options through direct assignment to instance attributes
between uses.</p>
<p>The <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> instance attributes (and keyword arguments to the
constructor) are as follows:</p>
<dl class="attribute">
<dt id="textwrap.TextWrapper.width">
<code class="descname">width</code><a class="headerlink" href="#textwrap.TextWrapper.width" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">70</span></code>) The maximum length of wrapped lines.  As long as there
are no individual words in the input text longer than <a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a>,
<a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> guarantees that no output line will be longer than
<a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a> characters.</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.expand_tabs">
<code class="descname">expand_tabs</code><a class="headerlink" href="#textwrap.TextWrapper.expand_tabs" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">True</span></code>) If true, then all tab characters in <em>text</em> will be
expanded to spaces using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">expandtabs()</span></code> method of <em>text</em>.</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.replace_whitespace">
<code class="descname">replace_whitespace</code><a class="headerlink" href="#textwrap.TextWrapper.replace_whitespace" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">True</span></code>) If true, after tab expansion but before wrapping,
the <a class="reference internal" href="#textwrap.wrap" title="textwrap.wrap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wrap()</span></code></a> method will replace each whitespace character
with a single space.  The whitespace characters replaced are
as follows: tab, newline, vertical tab, formfeed, and carriage
return (<code class="docutils literal notranslate"><span class="pre">'\t\n\v\f\r'</span></code>).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <a class="reference internal" href="#textwrap.TextWrapper.expand_tabs" title="textwrap.TextWrapper.expand_tabs"><code class="xref py py-attr docutils literal notranslate"><span class="pre">expand_tabs</span></code></a> is false and <a class="reference internal" href="#textwrap.TextWrapper.replace_whitespace" title="textwrap.TextWrapper.replace_whitespace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">replace_whitespace</span></code></a> is true,
each tab character will be replaced by a single space, which is <em>not</em>
the same as tab expansion.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <a class="reference internal" href="#textwrap.TextWrapper.replace_whitespace" title="textwrap.TextWrapper.replace_whitespace"><code class="xref py py-attr docutils literal notranslate"><span class="pre">replace_whitespace</span></code></a> is false, newlines may appear in the
middle of a line and cause strange output. For this reason, text should
be split into paragraphs (using <a class="reference internal" href="stdtypes.html#str.splitlines" title="str.splitlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.splitlines()</span></code></a> or similar)
which are wrapped separately.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.drop_whitespace">
<code class="descname">drop_whitespace</code><a class="headerlink" href="#textwrap.TextWrapper.drop_whitespace" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">True</span></code>) If true, whitespace at the beginning and ending of
every line (after wrapping but before indenting) is dropped.
Whitespace at the beginning of the paragraph, however, is not dropped
if non-whitespace follows it.  If whitespace being dropped takes up an
entire line, the whole line is dropped.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Whitespace was always dropped in earlier versions.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.initial_indent">
<code class="descname">initial_indent</code><a class="headerlink" href="#textwrap.TextWrapper.initial_indent" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">''</span></code>) String that will be prepended to the first line of
wrapped output.  Counts towards the length of the first line.  The empty
string is not indented.</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.subsequent_indent">
<code class="descname">subsequent_indent</code><a class="headerlink" href="#textwrap.TextWrapper.subsequent_indent" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">''</span></code>) String that will be prepended to all lines of wrapped
output except the first.  Counts towards the length of each line except
the first.</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.fix_sentence_endings">
<code class="descname">fix_sentence_endings</code><a class="headerlink" href="#textwrap.TextWrapper.fix_sentence_endings" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">False</span></code>) If true, <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> attempts to detect
sentence endings and ensure that sentences are always separated by exactly
two spaces.  This is generally desired for text in a monospaced font.
However, the sentence detection algorithm is imperfect: it assumes that a
sentence ending consists of a lowercase letter followed by one of <code class="docutils literal notranslate"><span class="pre">'.'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'!'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'?'</span></code>, possibly followed by one of <code class="docutils literal notranslate"><span class="pre">'&quot;'</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;'&quot;</span></code>,
followed by a space.  One problem with this is algorithm is that it is
unable to detect the difference between “Dr.” in</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="o">...</span><span class="p">]</span> <span class="n">Dr</span><span class="o">.</span> <span class="n">Frankenstein</span><span class="s1">&#39;s monster [...]</span>
</pre></div>
</div>
<p>and “Spot.” in</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="o">...</span><span class="p">]</span> <span class="n">See</span> <span class="n">Spot</span><span class="o">.</span> <span class="n">See</span> <span class="n">Spot</span> <span class="n">run</span> <span class="p">[</span><span class="o">...</span><span class="p">]</span>
</pre></div>
</div>
<p><a class="reference internal" href="#textwrap.TextWrapper.fix_sentence_endings" title="textwrap.TextWrapper.fix_sentence_endings"><code class="xref py py-attr docutils literal notranslate"><span class="pre">fix_sentence_endings</span></code></a> is false by default.</p>
<p>Since the sentence detection algorithm relies on <code class="docutils literal notranslate"><span class="pre">string.lowercase</span></code> for
the definition of “lowercase letter,” and a convention of using two spaces
after a period to separate sentences on the same line, it is specific to
English-language texts.</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.break_long_words">
<code class="descname">break_long_words</code><a class="headerlink" href="#textwrap.TextWrapper.break_long_words" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">True</span></code>) If true, then words longer than <a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a> will be
broken in order to ensure that no lines are longer than <a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a>.  If
it is false, long words will not be broken, and some lines may be longer
than <a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a>.  (Long words will be put on a line by themselves, in
order to minimize the amount by which <a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a> is exceeded.)</p>
</dd></dl>

<dl class="attribute">
<dt id="textwrap.TextWrapper.break_on_hyphens">
<code class="descname">break_on_hyphens</code><a class="headerlink" href="#textwrap.TextWrapper.break_on_hyphens" title="Permalink to this definition">¶</a></dt>
<dd><p>(default: <code class="docutils literal notranslate"><span class="pre">True</span></code>) If true, wrapping will occur preferably on whitespaces
and right after hyphens in compound words, as it is customary in English.
If false, only whitespaces will be considered as potentially good places
for line breaks, but you need to set <a class="reference internal" href="#textwrap.TextWrapper.break_long_words" title="textwrap.TextWrapper.break_long_words"><code class="xref py py-attr docutils literal notranslate"><span class="pre">break_long_words</span></code></a> to false if
you want truly insecable words.  Default behaviour in previous versions
was to always allow breaking hyphenated words.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p><a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> also provides two public methods, analogous to the
module-level convenience functions:</p>
<dl class="method">
<dt id="textwrap.TextWrapper.wrap">
<code class="descname">wrap</code><span class="sig-paren">(</span><em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.TextWrapper.wrap" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps the single paragraph in <em>text</em> (a string) so every line is at most
<a class="reference internal" href="#textwrap.TextWrapper.width" title="textwrap.TextWrapper.width"><code class="xref py py-attr docutils literal notranslate"><span class="pre">width</span></code></a> characters long.  All wrapping options are taken from
instance attributes of the <a class="reference internal" href="#textwrap.TextWrapper" title="textwrap.TextWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code></a> instance.  Returns a list
of output lines, without final newlines.  If the wrapped output has no
content, the returned list is empty.</p>
</dd></dl>

<dl class="method">
<dt id="textwrap.TextWrapper.fill">
<code class="descname">fill</code><span class="sig-paren">(</span><em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#textwrap.TextWrapper.fill" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps the single paragraph in <em>text</em>, and returns a single string
containing the wrapped paragraph.</p>
</dd></dl>

</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="stringio.html"
                        title="previous chapter">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="codecs.html"
                        title="next chapter">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/textwrap.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="codecs.html" title="7.8. codecs — Codec registry and base classes"
             >next</a> |</li>
        <li class="right" >
          <a href="stringio.html" title="7.5. StringIO — Read and write strings as files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\F٠�S�Shtml/library/thread.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.3. thread — Multiple threads of control &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.4. dummy_threading — Drop-in replacement for the threading module" href="dummy_threading.html" />
    <link rel="prev" title="16.2. threading — Higher-level threading interface" href="threading.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/thread.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dummy_threading.html" title="16.4. dummy_threading — Drop-in replacement for the threading module"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="threading.html" title="16.2. threading — Higher-level threading interface"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-thread">
<span id="thread-multiple-threads-of-control"></span><h1>16.3. <a class="reference internal" href="#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> — Multiple threads of control<a class="headerlink" href="#module-thread" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">_thread</span></code> in Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3; however, you should consider using the high-level
<a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module instead.</p>
</div>
<p id="index-0">This module provides low-level primitives for working with multiple threads
(also called <em class="dfn">light-weight processes</em> or <em class="dfn">tasks</em>) — multiple threads of
control sharing their global data space.  For synchronization, simple locks
(also called <em class="dfn">mutexes</em> or <em class="dfn">binary semaphores</em>) are provided.
The <a class="reference internal" href="threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module provides an easier to use and higher-level
threading API built on top of this module.</p>
<p id="index-1">The module is optional.  It is supported on Windows, Linux, SGI IRIX, Solaris
2.x, as well as on systems that have a POSIX thread (a.k.a. “pthread”)
implementation.  For systems lacking the <a class="reference internal" href="#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module, the
<a class="reference internal" href="dummy_thread.html#module-dummy_thread" title="dummy_thread: Drop-in replacement for the thread module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_thread</span></code></a> module is available. It duplicates this module’s interface
and can be used as a drop-in replacement.</p>
<p>It defines the following constant and functions:</p>
<dl class="exception">
<dt id="thread.error">
<em class="property">exception </em><code class="descclassname">thread.</code><code class="descname">error</code><a class="headerlink" href="#thread.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised on thread-specific errors.</p>
</dd></dl>

<dl class="data">
<dt id="thread.LockType">
<code class="descclassname">thread.</code><code class="descname">LockType</code><a class="headerlink" href="#thread.LockType" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the type of lock objects.</p>
</dd></dl>

<dl class="function">
<dt id="thread.start_new_thread">
<code class="descclassname">thread.</code><code class="descname">start_new_thread</code><span class="sig-paren">(</span><em>function</em>, <em>args</em><span class="optional">[</span>, <em>kwargs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.start_new_thread" title="Permalink to this definition">¶</a></dt>
<dd><p>Start a new thread and return its identifier.  The thread executes the function
<em>function</em> with the argument list <em>args</em> (which must be a tuple).  The optional
<em>kwargs</em> argument specifies a dictionary of keyword arguments. When the function
returns, the thread silently exits.  When the function terminates with an
unhandled exception, a stack trace is printed and then the thread exits (but
other threads continue to run).</p>
</dd></dl>

<dl class="function">
<dt id="thread.interrupt_main">
<code class="descclassname">thread.</code><code class="descname">interrupt_main</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.interrupt_main" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise a <a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception in the main thread.  A subthread can
use this function to interrupt the main thread.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="thread.exit">
<code class="descclassname">thread.</code><code class="descname">exit</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.exit" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise the <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> exception.  When not caught, this will cause the
thread to exit silently.</p>
</dd></dl>

<dl class="function">
<dt id="thread.allocate_lock">
<code class="descclassname">thread.</code><code class="descname">allocate_lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.allocate_lock" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new lock object.  Methods of locks are described below.  The lock is
initially unlocked.</p>
</dd></dl>

<dl class="function">
<dt id="thread.get_ident">
<code class="descclassname">thread.</code><code class="descname">get_ident</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.get_ident" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the ‘thread identifier’ of the current thread.  This is a nonzero
integer.  Its value has no direct meaning; it is intended as a magic cookie to
be used e.g. to index a dictionary of thread-specific data.  Thread identifiers
may be recycled when a thread exits and another thread is created.</p>
</dd></dl>

<dl class="function">
<dt id="thread.stack_size">
<code class="descclassname">thread.</code><code class="descname">stack_size</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.stack_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the thread stack size used when creating new threads.  The optional
<em>size</em> argument specifies the stack size to be used for subsequently created
threads, and must be 0 (use platform or configured default) or a positive
integer value of at least 32,768 (32kB). If <em>size</em> is not specified,
0 is used. If changing the thread stack size is
unsupported, the <a class="reference internal" href="#thread.error" title="thread.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception is raised.  If the specified stack size is
invalid, a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised and the stack size is unmodified.  32kB
is currently the minimum supported stack size value to guarantee sufficient
stack space for the interpreter itself.  Note that some platforms may have
particular restrictions on values for the stack size, such as requiring a
minimum stack size &gt; 32kB or requiring allocation in multiples of the system
memory page size - platform documentation should be referred to for more
information (4kB pages are common; using multiples of 4096 for the stack size is
the suggested approach in the absence of more specific information).
Availability: Windows, systems with POSIX threads.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>Lock objects have the following methods:</p>
<dl class="method">
<dt id="thread.lock.acquire">
<code class="descclassname">lock.</code><code class="descname">acquire</code><span class="sig-paren">(</span><span class="optional">[</span><em>waitflag</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Without the optional argument, this method acquires the lock unconditionally, if
necessary waiting until it is released by another thread (only one thread at a
time can acquire a lock — that’s their reason for existence).  If the integer
<em>waitflag</em> argument is present, the action depends on its value: if it is zero,
the lock is only acquired if it can be acquired immediately without waiting,
while if it is nonzero, the lock is acquired unconditionally as before.  The
return value is <code class="docutils literal notranslate"><span class="pre">True</span></code> if the lock is acquired successfully, <code class="docutils literal notranslate"><span class="pre">False</span></code> if not.</p>
</dd></dl>

<dl class="method">
<dt id="thread.lock.release">
<code class="descclassname">lock.</code><code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Releases the lock.  The lock must have been acquired earlier, but not
necessarily by the same thread.</p>
</dd></dl>

<dl class="method">
<dt id="thread.lock.locked">
<code class="descclassname">lock.</code><code class="descname">locked</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#thread.lock.locked" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the status of the lock: <code class="docutils literal notranslate"><span class="pre">True</span></code> if it has been acquired by some thread,
<code class="docutils literal notranslate"><span class="pre">False</span></code> if not.</p>
</dd></dl>

<p>In addition to these methods, lock objects can also be used via the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">thread</span>

<span class="n">a_lock</span> <span class="o">=</span> <span class="n">thread</span><span class="o">.</span><span class="n">allocate_lock</span><span class="p">()</span>

<span class="k">with</span> <span class="n">a_lock</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;a_lock is locked while this executes&quot;</span>
</pre></div>
</div>
<p><strong>Caveats:</strong></p>
<blockquote>
<div></div></blockquote>
<ul id="index-2">
<li><p class="first">Threads interact strangely with interrupts: the <a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a>
exception will be received by an arbitrary thread.  (When the <a class="reference internal" href="signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>
module is available, interrupts always go to the main thread.)</p>
</li>
<li><p class="first">Calling <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> or raising the <a class="reference internal" href="exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> exception is
equivalent to calling <a class="reference internal" href="#thread.exit" title="thread.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">thread.exit()</span></code></a>.</p>
</li>
<li><p class="first">It is not possible to interrupt the <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> method on a lock — the
<a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception will happen after the lock has been acquired.</p>
</li>
<li id="index-3"><p class="first">When the main thread exits, it is system defined whether the other threads
survive.  On SGI IRIX using the native thread implementation, they survive.  On
most other systems, they are killed without executing <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> …
<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses or executing object destructors.</p>
</li>
<li><p class="first">When the main thread exits, it does not do any of its usual cleanup (except
that <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses are honored), and the
standard I/O files are not flushed.</p>
</li>
</ul>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="threading.html"
                        title="previous chapter">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dummy_threading.html"
                        title="next chapter">16.4. <code class="docutils literal notranslate"><span class="pre">dummy_threading</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">threading</span></code> module</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/thread.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dummy_threading.html" title="16.4. dummy_threading — Drop-in replacement for the threading module"
             >next</a> |</li>
        <li class="right" >
          <a href="threading.html" title="16.2. threading — Higher-level threading interface"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�C�RRhtml/library/threading.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>16.2. threading — Higher-level threading interface &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="16.3. thread — Multiple threads of control" href="thread.html" />
    <link rel="prev" title="16.1. select — Waiting for I/O completion" href="select.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/threading.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="thread.html" title="16.3. thread — Multiple threads of control"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="select.html" title="16.1. select — Waiting for I/O completion"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" accesskey="U">16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-threading">
<span id="threading-higher-level-threading-interface"></span><h1>16.2. <a class="reference internal" href="#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> — Higher-level threading interface<a class="headerlink" href="#module-threading" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/threading.py">Lib/threading.py</a></p>
<hr class="docutils" />
<p>This module constructs higher-level threading interfaces on top of the  lower
level <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module.
See also the <a class="reference internal" href="mutex.html#module-mutex" title="mutex: Lock and queue for mutual exclusion. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mutex</span></code></a> and <a class="reference internal" href="queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> modules.</p>
<p>The <a class="reference internal" href="dummy_threading.html#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_threading</span></code></a> module is provided for situations where
<a class="reference internal" href="#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> cannot be used because <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> is missing.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Starting with Python 2.6, this module provides <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> compliant aliases and
properties to replace the <code class="docutils literal notranslate"><span class="pre">camelCase</span></code> names that were inspired by Java’s
threading API. This updated API is compatible with that of the
<a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module. However, no schedule has been set for the
deprecation of the <code class="docutils literal notranslate"><span class="pre">camelCase</span></code> names and they remain fully supported in
both Python 2.x and 3.x.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Starting with Python 2.5, several Thread methods raise <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>
instead of <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> if called erroneously.</p>
</div>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In CPython, due to the <a class="reference internal" href="../glossary.html#term-global-interpreter-lock"><span class="xref std std-term">Global Interpreter Lock</span></a>, only one thread
can execute Python code at once (even though certain performance-oriented
libraries might overcome this limitation).
If you want your application to make better use of the computational
resources of multi-core machines, you are advised to use
<a class="reference internal" href="multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>. However, threading is still an appropriate model
if you want to run multiple I/O-bound tasks simultaneously.</p>
</div>
<p>This module defines the following functions and objects:</p>
<dl class="function">
<dt id="threading.active_count">
<code class="descclassname">threading.</code><code class="descname">active_count</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.active_count" title="Permalink to this definition">¶</a></dt>
<dt id="threading.activeCount">
<code class="descclassname">threading.</code><code class="descname">activeCount</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.activeCount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> objects currently alive.  The returned
count is equal to the length of the list returned by <a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="docutils literal notranslate"><span class="pre">active_count()</span></code> spelling.</p>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">threading.</code><code class="descname">Condition</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>A factory function that returns a new condition variable object. A condition
variable allows one or more threads to wait until they are notified by another
thread.</p>
<p>See <a class="reference internal" href="#condition-objects"><span class="std std-ref">Condition Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="threading.current_thread">
<code class="descclassname">threading.</code><code class="descname">current_thread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.current_thread" title="Permalink to this definition">¶</a></dt>
<dt id="threading.currentThread">
<code class="descclassname">threading.</code><code class="descname">currentThread</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.currentThread" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> object, corresponding to the caller’s thread
of control.  If the caller’s thread of control was not created through the
<a class="reference internal" href="#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module, a dummy thread object with limited functionality is
returned.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="docutils literal notranslate"><span class="pre">current_thread()</span></code> spelling.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.enumerate">
<code class="descclassname">threading.</code><code class="descname">enumerate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.enumerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> objects currently alive.  The list
includes daemonic threads, dummy thread objects created by
<a class="reference internal" href="#threading.current_thread" title="threading.current_thread"><code class="xref py py-func docutils literal notranslate"><span class="pre">current_thread()</span></code></a>, and the main thread.  It excludes terminated threads
and threads that have not yet been started.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">threading.</code><code class="descname">Event</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>A factory function that returns a new event object.  An event manages a flag
that can be set to true with the <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method and reset to false
with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> method.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> method blocks until the flag
is true.</p>
<p>See <a class="reference internal" href="#event-objects"><span class="std std-ref">Event Objects</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="threading.local">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">local</code><a class="headerlink" href="#threading.local" title="Permalink to this definition">¶</a></dt>
<dd><p>A class that represents thread-local data.  Thread-local data are data whose
values are thread specific.  To manage thread-local data, just create an
instance of <a class="reference internal" href="#threading.local" title="threading.local"><code class="xref py py-class docutils literal notranslate"><span class="pre">local</span></code></a> (or a subclass) and store attributes on it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">mydata</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
<span class="n">mydata</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>The instance’s values will be different for separate threads.</p>
<p>For more details and extensive examples, see the documentation string of the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading_local</span></code> module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.Lock">
<code class="descclassname">threading.</code><code class="descname">Lock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock" title="Permalink to this definition">¶</a></dt>
<dd><p>A factory function that returns a new primitive lock object.  Once a thread has
acquired it, subsequent attempts to acquire it block, until it is released; any
thread may release it.</p>
<p>See <a class="reference internal" href="#lock-objects"><span class="std std-ref">Lock Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="threading.RLock">
<code class="descclassname">threading.</code><code class="descname">RLock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.RLock" title="Permalink to this definition">¶</a></dt>
<dd><p>A factory function that returns a new reentrant lock object. A reentrant lock
must be released by the thread that acquired it. Once a thread has acquired a
reentrant lock, the same thread may acquire it again without blocking; the
thread must release it once for each time it has acquired it.</p>
<p>See <a class="reference internal" href="#rlock-objects"><span class="std std-ref">RLock Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">threading.</code><code class="descname">Semaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>A factory function that returns a new semaphore object.  A semaphore manages a
counter representing the number of <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> calls minus the number of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> calls, plus an initial value. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> method blocks
if necessary until it can return without making the counter negative.  If not
given, <em>value</em> defaults to 1.</p>
<p>See <a class="reference internal" href="#semaphore-objects"><span class="std std-ref">Semaphore Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="threading.BoundedSemaphore">
<code class="descclassname">threading.</code><code class="descname">BoundedSemaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.BoundedSemaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>A factory function that returns a new bounded semaphore object.  A bounded
semaphore checks to make sure its current value doesn’t exceed its initial
value.  If it does, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised. In most situations semaphores
are used to guard resources with limited capacity.  If the semaphore is released
too many times it’s a sign of a bug.  If not given, <em>value</em> defaults to 1.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Thread</code></dt>
<dd><p>A class that represents a thread of control.  This class can be safely
subclassed in a limited fashion.</p>
<p>See <a class="reference internal" href="#thread-objects"><span class="std std-ref">Thread Objects</span></a>.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Timer</code></dt>
<dd><p>A thread that executes a function after a specified interval has passed.</p>
<p>See <a class="reference internal" href="#timer-objects"><span class="std std-ref">Timer Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="threading.settrace">
<code class="descclassname">threading.</code><code class="descname">settrace</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.settrace" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">Set a trace function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.
The <em>func</em> will be passed to  <a class="reference internal" href="sys.html#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.settrace()</span></code></a> for each thread, before its
<a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.setprofile">
<code class="descclassname">threading.</code><code class="descname">setprofile</code><span class="sig-paren">(</span><em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.setprofile" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">Set a profile function for all threads started from the <a class="reference internal" href="#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.
The <em>func</em> will be passed to  <a class="reference internal" href="sys.html#sys.setprofile" title="sys.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setprofile()</span></code></a> for each thread, before its
<a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method is called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="threading.stack_size">
<code class="descclassname">threading.</code><code class="descname">stack_size</code><span class="sig-paren">(</span><span class="optional">[</span><em>size</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.stack_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the thread stack size used when creating new threads.  The optional
<em>size</em> argument specifies the stack size to be used for subsequently created
threads, and must be 0 (use platform or configured default) or a positive
integer value of at least 32,768 (32 KiB). If <em>size</em> is not specified,
0 is used.  If changing the thread stack size is
unsupported, a <a class="reference internal" href="#threading.ThreadError" title="threading.ThreadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ThreadError</span></code></a> is raised.  If the specified stack size is
invalid, a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised and the stack size is unmodified.  32kB
is currently the minimum supported stack size value to guarantee sufficient
stack space for the interpreter itself.  Note that some platforms may have
particular restrictions on values for the stack size, such as requiring a
minimum stack size &gt; 32kB or requiring allocation in multiples of the system
memory page size - platform documentation should be referred to for more
information (4kB pages are common; using multiples of 4096 for the stack size is
the suggested approach in the absence of more specific information).
Availability: Windows, systems with POSIX threads.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="threading.ThreadError">
<em class="property">exception </em><code class="descclassname">threading.</code><code class="descname">ThreadError</code><a class="headerlink" href="#threading.ThreadError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised for various threading-related errors as described below.  Note that
many interfaces use <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> instead of <a class="reference internal" href="#threading.ThreadError" title="threading.ThreadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ThreadError</span></code></a>.</p>
</dd></dl>

<p>Detailed interfaces for the objects are documented below.</p>
<p>The design of this module is loosely based on Java’s threading model. However,
where Java makes locks and condition variables basic behavior of every object,
they are separate objects in Python.  Python’s <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a> class supports a
subset of the behavior of Java’s Thread class; currently, there are no
priorities, no thread groups, and threads cannot be destroyed, stopped,
suspended, resumed, or interrupted.  The static methods of Java’s Thread class,
when implemented, are mapped to module-level functions.</p>
<p>All of the methods described below are executed atomically.</p>
<div class="section" id="thread-objects">
<span id="id1"></span><h2>16.2.1. Thread Objects<a class="headerlink" href="#thread-objects" title="Permalink to this headline">¶</a></h2>
<p>This class represents an activity that is run in a separate thread of control.
There are two ways to specify the activity: by passing a callable object to the
constructor, or by overriding the <code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code> method in a subclass.  No other
methods (except for the constructor) should be overridden in a subclass.  In
other words,  <em>only</em>  override the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code> methods of
this class.</p>
<p>Once a thread object is created, its activity must be started by calling the
thread’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> method.  This invokes the <code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code> method in a
separate thread of control.</p>
<p>Once the thread’s activity is started, the thread is considered ‘alive’. It
stops being alive when its <code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code> method terminates – either normally, or
by raising an unhandled exception.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code> method tests whether the
thread is alive.</p>
<p>Other threads can call a thread’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method.  This blocks the calling
thread until the thread whose <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method is called is terminated.</p>
<p>A thread has a name.  The name can be passed to the constructor, and read or
changed through the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute.</p>
<p>A thread can be flagged as a “daemon thread”.  The significance of this flag is
that the entire Python program exits when only daemon threads are left.  The
initial value is inherited from the creating thread.  The flag can be set
through the <code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code> property.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Daemon threads are abruptly stopped at shutdown.  Their resources (such
as open files, database transactions, etc.) may not be released properly.
If you want your threads to stop gracefully, make them non-daemonic and
use a suitable signalling mechanism such as an <a class="reference internal" href="#threading.Event" title="threading.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">Event</span></code></a>.</p>
</div>
<p>There is a “main thread” object; this corresponds to the initial thread of
control in the Python program.  It is not a daemon thread.</p>
<p>There is the possibility that “dummy thread objects” are created. These are
thread objects corresponding to “alien threads”, which are threads of control
started outside the threading module, such as directly from C code.  Dummy
thread objects have limited functionality; they are always considered alive and
daemonic, and cannot be <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code>ed.  They are never deleted, since it is
impossible to detect the termination of alien threads.</p>
<dl class="class">
<dt id="threading.Thread">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Thread</code><span class="sig-paren">(</span><em>group=None</em>, <em>target=None</em>, <em>name=None</em>, <em>args=()</em>, <em>kwargs={}</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread" title="Permalink to this definition">¶</a></dt>
<dd><p>This constructor should always be called with keyword arguments.  Arguments
are:</p>
<p><em>group</em> should be <code class="docutils literal notranslate"><span class="pre">None</span></code>; reserved for future extension when a
<code class="xref py py-class docutils literal notranslate"><span class="pre">ThreadGroup</span></code> class is implemented.</p>
<p><em>target</em> is the callable object to be invoked by the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method.
Defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code>, meaning nothing is called.</p>
<p><em>name</em> is the thread name.  By default, a unique name is constructed of the
form “Thread-<em>N</em>” where <em>N</em> is a small decimal number.</p>
<p><em>args</em> is the argument tuple for the target invocation.  Defaults to <code class="docutils literal notranslate"><span class="pre">()</span></code>.</p>
<p><em>kwargs</em> is a dictionary of keyword arguments for the target invocation.
Defaults to <code class="docutils literal notranslate"><span class="pre">{}</span></code>.</p>
<p>If the subclass overrides the constructor, it must make sure to invoke the
base class constructor (<code class="docutils literal notranslate"><span class="pre">Thread.__init__()</span></code>) before doing anything else to
the thread.</p>
<dl class="method">
<dt id="threading.Thread.start">
<code class="descname">start</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Start the thread’s activity.</p>
<p>It must be called at most once per thread object.  It arranges for the
object’s <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method to be invoked in a separate thread of control.</p>
<p>This method will raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if called more than once
on the same thread object.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.run">
<code class="descname">run</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Method representing the thread’s activity.</p>
<p>You may override this method in a subclass.  The standard <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>
method invokes the callable object passed to the object’s constructor as
the <em>target</em> argument, if any, with sequential and keyword arguments taken
from the <em>args</em> and <em>kwargs</em> arguments, respectively.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.join">
<code class="descname">join</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.join" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until the thread terminates. This blocks the calling thread until the
thread whose <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> method is called terminates – either normally
or through an unhandled exception – or until the optional timeout occurs.</p>
<p>When the <em>timeout</em> argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> always returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, you must
call <a class="reference internal" href="#threading.Thread.isAlive" title="threading.Thread.isAlive"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isAlive()</span></code></a> after <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> to decide whether a timeout
happened – if the thread is still alive, the <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> call timed out.</p>
<p>When the <em>timeout</em> argument is not present or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the operation will
block until the thread terminates.</p>
<p>A thread can be <a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a>ed many times.</p>
<p><a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> raises a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> if an attempt is made to join
the current thread as that would cause a deadlock. It is also an error to
<a class="reference internal" href="#threading.Thread.join" title="threading.Thread.join"><code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code></a> a thread before it has been started and attempts to do so
raises the same exception.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.name">
<code class="descname">name</code><a class="headerlink" href="#threading.Thread.name" title="Permalink to this definition">¶</a></dt>
<dd><p>A string used for identification purposes only. It has no semantics.
Multiple threads may be given the same name.  The initial name is set by
the constructor.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.getName">
<code class="descname">getName</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.getName" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Thread.setName">
<code class="descname">setName</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.setName" title="Permalink to this definition">¶</a></dt>
<dd><p>Pre-2.6 API for <a class="reference internal" href="#threading.Thread.name" title="threading.Thread.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.ident">
<code class="descname">ident</code><a class="headerlink" href="#threading.Thread.ident" title="Permalink to this definition">¶</a></dt>
<dd><p>The ‘thread identifier’ of this thread or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the thread has not
been started.  This is a nonzero integer.  See the
<a class="reference internal" href="thread.html#thread.get_ident" title="thread.get_ident"><code class="xref py py-func docutils literal notranslate"><span class="pre">thread.get_ident()</span></code></a> function.  Thread identifiers may be recycled
when a thread exits and another thread is created.  The identifier is
available even after the thread has exited.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.is_alive">
<code class="descname">is_alive</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.is_alive" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Thread.isAlive">
<code class="descname">isAlive</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.isAlive" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the thread is alive.</p>
<p>This method returns <code class="docutils literal notranslate"><span class="pre">True</span></code> just before the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method starts
until just after the <a class="reference internal" href="#threading.Thread.run" title="threading.Thread.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method terminates.  The module function
<a class="reference internal" href="#threading.enumerate" title="threading.enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> returns a list of all alive threads.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="docutils literal notranslate"><span class="pre">is_alive()</span></code> spelling.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="threading.Thread.daemon">
<code class="descname">daemon</code><a class="headerlink" href="#threading.Thread.daemon" title="Permalink to this definition">¶</a></dt>
<dd><p>A boolean value indicating whether this thread is a daemon thread (True)
or not (False).  This must be set before <a class="reference internal" href="#threading.Thread.start" title="threading.Thread.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code></a> is called,
otherwise <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.  Its initial value is inherited
from the creating thread; the main thread is not a daemon thread and
therefore all threads created in the main thread default to <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code></a>
= <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p>The entire Python program exits when no alive non-daemon threads are left.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Thread.isDaemon">
<code class="descname">isDaemon</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.isDaemon" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Thread.setDaemon">
<code class="descname">setDaemon</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Thread.setDaemon" title="Permalink to this definition">¶</a></dt>
<dd><p>Pre-2.6 API for <a class="reference internal" href="#threading.Thread.daemon" title="threading.Thread.daemon"><code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="lock-objects">
<span id="id2"></span><h2>16.2.2. Lock Objects<a class="headerlink" href="#lock-objects" title="Permalink to this headline">¶</a></h2>
<p>A primitive lock is a synchronization primitive that is not owned by a
particular thread when locked.  In Python, it is currently the lowest level
synchronization primitive available, implemented directly by the <a class="reference internal" href="thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a>
extension module.</p>
<p>A primitive lock is in one of two states, “locked” or “unlocked”. It is created
in the unlocked state.  It has two basic methods, <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code>.  When the state is unlocked, <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> changes the state
to locked and returns immediately.  When the state is locked, <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code>
blocks until a call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> in another thread changes it to unlocked,
then the <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> call resets it to locked and returns.  The
<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> method should only be called in the locked state; it changes the
state to unlocked and returns immediately. If an attempt is made to release an
unlocked lock, a <a class="reference internal" href="#threading.ThreadError" title="threading.ThreadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ThreadError</span></code></a> will be raised.</p>
<p>When more than one thread is blocked in <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> waiting for the state to
turn to unlocked, only one thread proceeds when a <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> call resets
the state to unlocked; which one of the waiting threads proceeds is not defined,
and may vary across implementations.</p>
<p>All methods are executed atomically.</p>
<dl class="method">
<dt id="threading.Lock.acquire">
<code class="descclassname">Lock.</code><code class="descname">acquire</code><span class="sig-paren">(</span><span class="optional">[</span><em>blocking</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">True</span></code> (the default),
block until the lock is unlocked, then set it to locked and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<p>When invoked with the <em>blocking</em> argument set to <code class="docutils literal notranslate"><span class="pre">False</span></code>, do not block.
If a call with <em>blocking</em> set to <code class="docutils literal notranslate"><span class="pre">True</span></code> would block, return <code class="docutils literal notranslate"><span class="pre">False</span></code>
immediately; otherwise, set the lock to locked and return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Lock.release">
<code class="descclassname">Lock.</code><code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Lock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock.</p>
<p>When the lock is locked, reset it to unlocked, and return.  If any other threads
are blocked waiting for the lock to become unlocked, allow exactly one of them
to proceed.</p>
<p>When invoked on an unlocked lock, a <a class="reference internal" href="#threading.ThreadError" title="threading.ThreadError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ThreadError</span></code></a> is raised.</p>
<p>There is no return value.</p>
</dd></dl>

</div>
<div class="section" id="rlock-objects">
<span id="id3"></span><h2>16.2.3. RLock Objects<a class="headerlink" href="#rlock-objects" title="Permalink to this headline">¶</a></h2>
<p>A reentrant lock is a synchronization primitive that may be acquired multiple
times by the same thread.  Internally, it uses the concepts of “owning thread”
and “recursion level” in addition to the locked/unlocked state used by primitive
locks.  In the locked state, some thread owns the lock; in the unlocked state,
no thread owns it.</p>
<p>To lock the lock, a thread calls its <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> method; this returns once
the thread owns the lock.  To unlock the lock, a thread calls its
<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> method. <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> call pairs may be
nested; only the final <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> (the <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> of the outermost
pair) resets the lock to unlocked and allows another thread blocked in
<code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> to proceed.</p>
<dl class="method">
<dt id="threading.RLock.acquire">
<code class="descclassname">RLock.</code><code class="descname">acquire</code><span class="sig-paren">(</span><span class="optional">[</span><em>blocking=1</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.RLock.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a lock, blocking or non-blocking.</p>
<p>When invoked without arguments: if this thread already owns the lock, increment
the recursion level by one, and return immediately.  Otherwise, if another
thread owns the lock, block until the lock is unlocked.  Once the lock is
unlocked (not owned by any thread), then grab ownership, set the recursion level
to one, and return.  If more than one thread is blocked waiting until the lock
is unlocked, only one at a time will be able to grab ownership of the lock.
There is no return value in this case.</p>
<p>When invoked with the <em>blocking</em> argument set to true, do the same thing as when
called without arguments, and return true.</p>
<p>When invoked with the <em>blocking</em> argument set to false, do not block.  If a call
without an argument would block, return false immediately; otherwise, do the
same thing as when called without arguments, and return true.</p>
</dd></dl>

<dl class="method">
<dt id="threading.RLock.release">
<code class="descclassname">RLock.</code><code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.RLock.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a lock, decrementing the recursion level.  If after the decrement it is
zero, reset the lock to unlocked (not owned by any thread), and if any other
threads are blocked waiting for the lock to become unlocked, allow exactly one
of them to proceed.  If after the decrement the recursion level is still
nonzero, the lock remains locked and owned by the calling thread.</p>
<p>Only call this method when the calling thread owns the lock. A
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if this method is called when the lock is
unlocked.</p>
<p>There is no return value.</p>
</dd></dl>

</div>
<div class="section" id="condition-objects">
<span id="id4"></span><h2>16.2.4. Condition Objects<a class="headerlink" href="#condition-objects" title="Permalink to this headline">¶</a></h2>
<p>A condition variable is always associated with some kind of lock; this can be
passed in or one will be created by default.  (Passing one in is useful when
several condition variables must share the same lock.)</p>
<p>A condition variable has <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> methods that call
the corresponding methods of the associated lock. It also has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code>
method, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> methods.  These three must only
be called when the calling thread has acquired the lock, otherwise a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> method releases the lock, and then blocks until it is awakened
by a <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> call for the same condition variable in
another thread.  Once awakened, it re-acquires the lock and returns.  It is also
possible to specify a timeout.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> method wakes up one of the threads waiting for the condition
variable, if any are waiting.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> method wakes up all threads
waiting for the condition variable.</p>
<p>Note: the <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> methods don’t release the lock;
this means that the thread or threads awakened will not return from their
<code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> call immediately, but only when the thread that called
<code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> finally relinquishes ownership of the lock.</p>
<p>Tip: the typical programming style using condition variables uses the lock to
synchronize access to some shared state; threads that are interested in a
particular change of state call <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code> repeatedly until they see the
desired state, while threads that modify the state call <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> or
<code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code> when they change the state in such a way that it could
possibly be a desired state for one of the waiters.  For example, the following
code is a generic producer-consumer situation with unlimited buffer capacity:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Consume one item</span>
<span class="n">cv</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
<span class="k">while</span> <span class="ow">not</span> <span class="n">an_item_is_available</span><span class="p">():</span>
    <span class="n">cv</span><span class="o">.</span><span class="n">wait</span><span class="p">()</span>
<span class="n">get_an_available_item</span><span class="p">()</span>
<span class="n">cv</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>

<span class="c1"># Produce one item</span>
<span class="n">cv</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
<span class="n">make_an_item_available</span><span class="p">()</span>
<span class="n">cv</span><span class="o">.</span><span class="n">notify</span><span class="p">()</span>
<span class="n">cv</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
</pre></div>
</div>
<p>To choose between <code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code>, consider whether one
state change can be interesting for only one or several waiting threads.  E.g.
in a typical producer-consumer situation, adding one item to the buffer only
needs to wake up one consumer thread.</p>
<dl class="class">
<dt id="threading.Condition">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Condition</code><span class="sig-paren">(</span><span class="optional">[</span><em>lock</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <em>lock</em> argument is given and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be a <a class="reference internal" href="#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>
or <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object, and it is used as the underlying lock.  Otherwise,
a new <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> object is created and used as the underlying lock.</p>
<dl class="method">
<dt id="threading.Condition.acquire">
<code class="descname">acquire</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire the underlying lock. This method calls the corresponding method on
the underlying lock; the return value is whatever that method returns.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.release">
<code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release the underlying lock. This method calls the corresponding method on
the underlying lock; there is no return value.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.wait">
<code class="descname">wait</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait until notified or until a timeout occurs. If the calling thread has not
acquired the lock when this method is called, a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<p>This method releases the underlying lock, and then blocks until it is
awakened by a <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> or <a class="reference internal" href="#threading.Condition.notifyAll" title="threading.Condition.notifyAll"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notifyAll()</span></code></a> call for the same
condition variable in another thread, or until the optional timeout
occurs.  Once awakened or timed out, it re-acquires the lock and returns.</p>
<p>When the <em>timeout</em> argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).</p>
<p>When the underlying lock is an <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>, it is not released using
its <a class="reference internal" href="#threading.Condition.release" title="threading.Condition.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> method, since this may not actually unlock the lock
when it was acquired multiple times recursively.  Instead, an internal
interface of the <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a> class is used, which really unlocks it
even when it has been recursively acquired several times. Another internal
interface is then used to restore the recursion level when the lock is
reacquired.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.notify">
<code class="descname">notify</code><span class="sig-paren">(</span><em>n=1</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.notify" title="Permalink to this definition">¶</a></dt>
<dd><p>By default, wake up one thread waiting on this condition, if any.  If the
calling thread has not acquired the lock when this method is called, a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<p>This method wakes up at most <em>n</em> of the threads waiting for the condition
variable; it is a no-op if no threads are waiting.</p>
<p>The current implementation wakes up exactly <em>n</em> threads, if at least <em>n</em>
threads are waiting.  However, it’s not safe to rely on this behavior.
A future, optimized implementation may occasionally wake up more than
<em>n</em> threads.</p>
<p>Note: an awakened thread does not actually return from its <a class="reference internal" href="#threading.Condition.wait" title="threading.Condition.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a>
call until it can reacquire the lock.  Since <a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a> does not
release the lock, its caller should.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Condition.notify_all">
<code class="descname">notify_all</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.notify_all" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Condition.notifyAll">
<code class="descname">notifyAll</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Condition.notifyAll" title="Permalink to this definition">¶</a></dt>
<dd><p>Wake up all threads waiting on this condition.  This method acts like
<a class="reference internal" href="#threading.Condition.notify" title="threading.Condition.notify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">notify()</span></code></a>, but wakes up all waiting threads instead of one. If the
calling thread has not acquired the lock when this method is called, a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="docutils literal notranslate"><span class="pre">notify_all()</span></code> spelling.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="semaphore-objects">
<span id="id5"></span><h2>16.2.5. Semaphore Objects<a class="headerlink" href="#semaphore-objects" title="Permalink to this headline">¶</a></h2>
<p>This is one of the oldest synchronization primitives in the history of computer
science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he
used <code class="xref py py-meth docutils literal notranslate"><span class="pre">P()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">V()</span></code> instead of <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code>).</p>
<p>A semaphore manages an internal counter which is decremented by each
<code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> call and incremented by each <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> call.  The counter
can never go below zero; when <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> finds that it is zero, it blocks,
waiting until some other thread calls <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code>.</p>
<dl class="class">
<dt id="threading.Semaphore">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Semaphore</code><span class="sig-paren">(</span><span class="optional">[</span><em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore" title="Permalink to this definition">¶</a></dt>
<dd><p>The optional argument gives the initial <em>value</em> for the internal counter; it
defaults to <code class="docutils literal notranslate"><span class="pre">1</span></code>. If the <em>value</em> given is less than 0, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is
raised.</p>
<dl class="method">
<dt id="threading.Semaphore.acquire">
<code class="descname">acquire</code><span class="sig-paren">(</span><span class="optional">[</span><em>blocking</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore.acquire" title="Permalink to this definition">¶</a></dt>
<dd><p>Acquire a semaphore.</p>
<p>When invoked without arguments: if the internal counter is larger than
zero on entry, decrement it by one and return immediately.  If it is zero
on entry, block, waiting until some other thread has called
<a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> to make it larger than zero.  This is done with proper
interlocking so that if multiple <a class="reference internal" href="#threading.Semaphore.acquire" title="threading.Semaphore.acquire"><code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code></a> calls are blocked,
<a class="reference internal" href="#threading.Semaphore.release" title="threading.Semaphore.release"><code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code></a> will wake exactly one of them up.  The implementation may
pick one at random, so the order in which blocked threads are awakened
should not be relied on.  There is no return value in this case.</p>
<p>When invoked with <em>blocking</em> set to true, do the same thing as when called
without arguments, and return true.</p>
<p>When invoked with <em>blocking</em> set to false, do not block.  If a call
without an argument would block, return false immediately; otherwise, do
the same thing as when called without arguments, and return true.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Semaphore.release">
<code class="descname">release</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Semaphore.release" title="Permalink to this definition">¶</a></dt>
<dd><p>Release a semaphore, incrementing the internal counter by one.  When it
was zero on entry and another thread is waiting for it to become larger
than zero again, wake up that thread.</p>
</dd></dl>

</dd></dl>

<div class="section" id="semaphore-example">
<span id="semaphore-examples"></span><h3>16.2.5.1. <a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a> Example<a class="headerlink" href="#semaphore-example" title="Permalink to this headline">¶</a></h3>
<p>Semaphores are often used to guard resources with limited capacity, for example,
a database server.  In any situation where the size of the resource is fixed,
you should use a bounded semaphore.  Before spawning any worker threads, your
main thread would initialize the semaphore:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">maxconnections</span> <span class="o">=</span> <span class="mi">5</span>
<span class="o">...</span>
<span class="n">pool_sema</span> <span class="o">=</span> <span class="n">BoundedSemaphore</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="n">maxconnections</span><span class="p">)</span>
</pre></div>
</div>
<p>Once spawned, worker threads call the semaphore’s acquire and release methods
when they need to connect to the server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pool_sema</span><span class="o">.</span><span class="n">acquire</span><span class="p">()</span>
<span class="n">conn</span> <span class="o">=</span> <span class="n">connectdb</span><span class="p">()</span>
<span class="o">...</span> <span class="n">use</span> <span class="n">connection</span> <span class="o">...</span>
<span class="n">conn</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="n">pool_sema</span><span class="o">.</span><span class="n">release</span><span class="p">()</span>
</pre></div>
</div>
<p>The use of a bounded semaphore reduces the chance that a programming error which
causes the semaphore to be released more than it’s acquired will go undetected.</p>
</div>
</div>
<div class="section" id="event-objects">
<span id="id6"></span><h2>16.2.6. Event Objects<a class="headerlink" href="#event-objects" title="Permalink to this headline">¶</a></h2>
<p>This is one of the simplest mechanisms for communication between threads: one
thread signals an event and other threads wait for it.</p>
<p>An event object manages an internal flag that can be set to true with the
<a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method and reset to false with the <a class="reference internal" href="#threading.Event.clear" title="threading.Event.clear"><code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code></a>
method.  The <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method blocks until the flag is true.</p>
<dl class="class">
<dt id="threading.Event">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Event</code><a class="headerlink" href="#threading.Event" title="Permalink to this definition">¶</a></dt>
<dd><p>The internal flag is initially false.</p>
<dl class="method">
<dt id="threading.Event.is_set">
<code class="descname">is_set</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.is_set" title="Permalink to this definition">¶</a></dt>
<dt id="threading.Event.isSet">
<code class="descname">isSet</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.isSet" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if and only if the internal flag is true.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="docutils literal notranslate"><span class="pre">is_set()</span></code> spelling.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="threading.Event.set">
<code class="descname">set</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the internal flag to true. All threads waiting for it to become true
are awakened. Threads that call <a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> once the flag is true will
not block at all.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Event.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the internal flag to false. Subsequently, threads calling
<a class="reference internal" href="#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> will block until <a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> is called to set the internal
flag to true again.</p>
</dd></dl>

<dl class="method">
<dt id="threading.Event.wait">
<code class="descname">wait</code><span class="sig-paren">(</span><span class="optional">[</span><em>timeout</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Event.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Block until the internal flag is true.  If the internal flag is true on
entry, return immediately.  Otherwise, block until another thread calls
<a class="reference internal" href="#threading.Event.set" title="threading.Event.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> to set the flag to true, or until the optional timeout
occurs.</p>
<p>When the timeout argument is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof).</p>
<p>This method returns the internal flag on exit, so it will always return
<code class="docutils literal notranslate"><span class="pre">True</span></code> except if a timeout is given and the operation times out.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Previously, the method always returned <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="timer-objects">
<span id="id7"></span><h2>16.2.7. Timer Objects<a class="headerlink" href="#timer-objects" title="Permalink to this headline">¶</a></h2>
<p>This class represents an action that should be run only after a certain amount
of time has passed — a timer.  <a class="reference internal" href="#threading.Timer" title="threading.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> is a subclass of <a class="reference internal" href="#threading.Thread" title="threading.Thread"><code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code></a>
and as such also functions as an example of creating custom threads.</p>
<p>Timers are started, as with threads, by calling their <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code>
method.  The timer can be stopped (before its action has begun) by calling the
<a class="reference internal" href="#threading.Timer.cancel" title="threading.Timer.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> method.  The interval the timer will wait before
executing its action may not be exactly the same as the interval specified by
the user.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">hello</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s2">&quot;hello, world&quot;</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">Timer</span><span class="p">(</span><span class="mf">30.0</span><span class="p">,</span> <span class="n">hello</span><span class="p">)</span>
<span class="n">t</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>  <span class="c1"># after 30 seconds, &quot;hello, world&quot; will be printed</span>
</pre></div>
</div>
<dl class="class">
<dt id="threading.Timer">
<em class="property">class </em><code class="descclassname">threading.</code><code class="descname">Timer</code><span class="sig-paren">(</span><em>interval</em>, <em>function</em>, <em>args=[]</em>, <em>kwargs={}</em><span class="sig-paren">)</span><a class="headerlink" href="#threading.Timer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a timer that will run <em>function</em> with arguments <em>args</em> and  keyword
arguments <em>kwargs</em>, after <em>interval</em> seconds have passed.</p>
<dl class="method">
<dt id="threading.Timer.cancel">
<code class="descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#threading.Timer.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the timer, and cancel the execution of the timer’s action.  This will
only work if the timer is still in its waiting stage.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="using-locks-conditions-and-semaphores-in-the-with-statement">
<span id="with-locks"></span><h2>16.2.8. Using locks, conditions, and semaphores in the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement<a class="headerlink" href="#using-locks-conditions-and-semaphores-in-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>All of the objects provided by this module that have <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> methods can be used as context managers for a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">acquire()</span></code> method will be called when the block is entered,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">release()</span></code> will be called when the block is exited.</p>
<p>Currently, <a class="reference internal" href="#threading.Lock" title="threading.Lock"><code class="xref py py-class docutils literal notranslate"><span class="pre">Lock</span></code></a>, <a class="reference internal" href="#threading.RLock" title="threading.RLock"><code class="xref py py-class docutils literal notranslate"><span class="pre">RLock</span></code></a>, <a class="reference internal" href="#threading.Condition" title="threading.Condition"><code class="xref py py-class docutils literal notranslate"><span class="pre">Condition</span></code></a>,
<a class="reference internal" href="#threading.Semaphore" title="threading.Semaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">Semaphore</span></code></a>, and <a class="reference internal" href="#threading.BoundedSemaphore" title="threading.BoundedSemaphore"><code class="xref py py-class docutils literal notranslate"><span class="pre">BoundedSemaphore</span></code></a> objects may be used as
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement context managers.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span>

<span class="n">some_rlock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">RLock</span><span class="p">()</span>

<span class="k">with</span> <span class="n">some_rlock</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;some_rlock is locked while this executes&quot;</span>
</pre></div>
</div>
</div>
<div class="section" id="importing-in-threaded-code">
<span id="threaded-imports"></span><h2>16.2.9. Importing in threaded code<a class="headerlink" href="#importing-in-threaded-code" title="Permalink to this headline">¶</a></h2>
<p>While the import machinery is thread-safe, there are two key restrictions on
threaded imports due to inherent limitations in the way that thread-safety is
provided:</p>
<ul class="simple">
<li>Firstly, other than in the main module, an import should not have the
side effect of spawning a new thread and then waiting for that thread in
any way. Failing to abide by this restriction can lead to a deadlock if
the spawned thread directly or indirectly attempts to import a module.</li>
<li>Secondly, all import attempts must be completed before the interpreter
starts shutting itself down. This can be most easily achieved by only
performing imports from non-daemon threads created through the threading
module. Daemon threads and threads created directly with the thread
module will require some other form of synchronization to ensure they do
not attempt imports after system shutdown has commenced. Failure to
abide by this restriction will lead to intermittent exceptions and
crashes during interpreter shutdown (as the late imports attempt to
access machinery which is no longer in a valid state).</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a><ul>
<li><a class="reference internal" href="#thread-objects">16.2.1. Thread Objects</a></li>
<li><a class="reference internal" href="#lock-objects">16.2.2. Lock Objects</a></li>
<li><a class="reference internal" href="#rlock-objects">16.2.3. RLock Objects</a></li>
<li><a class="reference internal" href="#condition-objects">16.2.4. Condition Objects</a></li>
<li><a class="reference internal" href="#semaphore-objects">16.2.5. Semaphore Objects</a><ul>
<li><a class="reference internal" href="#semaphore-example">16.2.5.1. <code class="docutils literal notranslate"><span class="pre">Semaphore</span></code> Example</a></li>
</ul>
</li>
<li><a class="reference internal" href="#event-objects">16.2.6. Event Objects</a></li>
<li><a class="reference internal" href="#timer-objects">16.2.7. Timer Objects</a></li>
<li><a class="reference internal" href="#using-locks-conditions-and-semaphores-in-the-with-statement">16.2.8. Using locks, conditions, and semaphores in the <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#importing-in-threaded-code">16.2.9. Importing in threaded code</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="select.html"
                        title="previous chapter">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="thread.html"
                        title="next chapter">16.3. <code class="docutils literal notranslate"><span class="pre">thread</span></code> — Multiple threads of control</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/threading.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="thread.html" title="16.3. thread — Multiple threads of control"
             >next</a> |</li>
        <li class="right" >
          <a href="select.html" title="16.1. select — Waiting for I/O completion"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="someos.html" >16. Optional Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\E��6�6�html/library/time.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15.3. time — Time access and conversions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15.4. argparse — Parser for command-line options, arguments and sub-commands" href="argparse.html" />
    <link rel="prev" title="15.2. io — Core tools for working with streams" href="io.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/time.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="15.4. argparse — Parser for command-line options, arguments and sub-commands"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="io.html" title="15.2. io — Core tools for working with streams"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" accesskey="U">15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-time">
<span id="time-time-access-and-conversions"></span><h1>15.3. <a class="reference internal" href="#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> — Time access and conversions<a class="headerlink" href="#module-time" title="Permalink to this headline">¶</a></h1>
<p>This module provides various time-related functions. For related
functionality, see also the <a class="reference internal" href="datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> and <a class="reference internal" href="calendar.html#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a> modules.</p>
<p>Although this module is always available,
not all functions are available on all platforms.  Most of the functions
defined in this module call platform C library functions with the same name.  It
may sometimes be helpful to consult the platform documentation, because the
semantics of these functions varies among platforms.</p>
<p>An explanation of some terminology and conventions is in order.</p>
<ul class="simple" id="index-0">
<li>The <em class="dfn">epoch</em> is the point where the time starts.  On January 1st of that
year, at 0 hours, the “time since the epoch” is zero.  For Unix, the epoch is
1970.  To find out what the epoch is, look at <code class="docutils literal notranslate"><span class="pre">gmtime(0)</span></code>.</li>
</ul>
<ul class="simple" id="index-1">
<li>The functions in this module do not handle dates and times before the epoch or
far in the future.  The cut-off point in the future is determined by the C
library; for Unix, it is typically in 2038.</li>
</ul>
<span id="index-2"></span><ul class="simple" id="time-y2kissues">
<li><strong>Year 2000 (Y2K) issues</strong>:  Python depends on the platform’s C library, which
generally doesn’t have year 2000 issues, since all dates and times are
represented internally as seconds since the epoch.  Functions accepting a
<a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> (see below) generally require a 4-digit year.  For backward
compatibility, 2-digit years are supported if the module variable
<code class="docutils literal notranslate"><span class="pre">accept2dyear</span></code> is a non-zero integer; this variable is initialized to <code class="docutils literal notranslate"><span class="pre">1</span></code>
unless the environment variable <span class="target" id="index-3"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONY2K"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONY2K</span></code></a> is set to a non-empty
string, in which case it is initialized to <code class="docutils literal notranslate"><span class="pre">0</span></code>.  Thus, you can set
<span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONY2K"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONY2K</span></code></a> to a non-empty string in the environment to require 4-digit
years for all year input.  When 2-digit years are accepted, they are converted
according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999,
and values 0–68 are mapped to 2000–2068. Values 100–1899 are always illegal.</li>
</ul>
<ul class="simple" id="index-5">
<li>UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or
GMT).  The acronym UTC is not a mistake but a compromise between English and
French.</li>
</ul>
<ul id="index-6">
<li><p class="first">DST is Daylight Saving Time, an adjustment of the timezone by (usually) one
hour during part of the year.  DST rules are magic (determined by local law) and
can change from year to year.  The C library has a table containing the local
rules (often it is read from a system file for flexibility) and is the only
source of True Wisdom in this respect.</p>
</li>
<li><p class="first">The precision of the various real-time functions may be less than suggested by
the units in which their value or argument is expressed. E.g. on most Unix
systems, the clock “ticks” only 50 or 100 times a second.</p>
</li>
<li><p class="first">On the other hand, the precision of <a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a> and <a class="reference internal" href="#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">sleep()</span></code></a> is better
than their Unix equivalents: times are expressed as floating point numbers,
<a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a> returns the most accurate time available (using Unix
<code class="xref c c-func docutils literal notranslate"><span class="pre">gettimeofday()</span></code> where available), and <a class="reference internal" href="#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">sleep()</span></code></a> will accept a time
with a nonzero fraction (Unix <code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> is used to implement this, where
available).</p>
</li>
<li><p class="first">The time value as returned by <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a>, <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a>, and
<a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a>, and accepted by <a class="reference internal" href="#time.asctime" title="time.asctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">asctime()</span></code></a>, <a class="reference internal" href="#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktime()</span></code></a> and
<a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a>, may be considered as a sequence of 9 integers.  The return
values of <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a>, <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a>, and <a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a> also offer
attribute names for individual fields.</p>
<p>See <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> for a description of these objects.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>The time value sequence was changed from a tuple to a <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a>, with
the addition of attribute names for the fields.</p>
</div>
</li>
<li><p class="first">Use the following functions to convert between time representations:</p>
<table border="1" class="docutils">
<colgroup>
<col width="33%" />
<col width="33%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">From</th>
<th class="head">To</th>
<th class="head">Use</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>seconds since the epoch</td>
<td><a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> in
UTC</td>
<td><a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a></td>
</tr>
<tr class="row-odd"><td>seconds since the epoch</td>
<td><a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> in
local time</td>
<td><a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a></td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> in
UTC</td>
<td>seconds since the epoch</td>
<td><a class="reference internal" href="calendar.html#calendar.timegm" title="calendar.timegm"><code class="xref py py-func docutils literal notranslate"><span class="pre">calendar.timegm()</span></code></a></td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> in
local time</td>
<td>seconds since the epoch</td>
<td><a class="reference internal" href="#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktime()</span></code></a></td>
</tr>
</tbody>
</table>
</li>
</ul>
<p>The module defines the following functions and data items:</p>
<dl class="data">
<dt id="time.accept2dyear">
<code class="descclassname">time.</code><code class="descname">accept2dyear</code><a class="headerlink" href="#time.accept2dyear" title="Permalink to this definition">¶</a></dt>
<dd><p>Boolean value indicating whether two-digit year values will be accepted.  This
is true by default, but will be set to false if the environment variable
<span class="target" id="index-7"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONY2K"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONY2K</span></code></a> has been set to a non-empty string.  It may also be modified
at run time.</p>
</dd></dl>

<dl class="data">
<dt id="time.altzone">
<code class="descclassname">time.</code><code class="descname">altzone</code><a class="headerlink" href="#time.altzone" title="Permalink to this definition">¶</a></dt>
<dd><p>The offset of the local DST timezone, in seconds west of UTC, if one is defined.
This is negative if the local DST timezone is east of UTC (as in Western Europe,
including the UK).  Only use this if <code class="docutils literal notranslate"><span class="pre">daylight</span></code> is nonzero.</p>
</dd></dl>

<dl class="function">
<dt id="time.asctime">
<code class="descclassname">time.</code><code class="descname">asctime</code><span class="sig-paren">(</span><span class="optional">[</span><em>t</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.asctime" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a tuple or <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> representing a time as returned by
<a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> or <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a> to a 24-character string of the following
form: <code class="docutils literal notranslate"><span class="pre">'Sun</span> <span class="pre">Jun</span> <span class="pre">20</span> <span class="pre">23:21:05</span> <span class="pre">1993'</span></code>.  If <em>t</em> is not provided, the current time
as returned by <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a> is used. Locale information is not used by
<a class="reference internal" href="#time.asctime" title="time.asctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">asctime()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike the C function of the same name, there is no trailing newline.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>Allowed <em>t</em> to be omitted.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="time.clock">
<code class="descclassname">time.</code><code class="descname">clock</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#time.clock" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-8">On Unix, return the current processor time as a floating point number expressed
in seconds.  The precision, and in fact the very definition of the meaning of
“processor time”, depends on that of the C function of the same name, but in any
case, this is the function to use for benchmarking Python or timing algorithms.</p>
<p>On Windows, this function returns wall-clock seconds elapsed since the first
call to this function, as a floating point number, based on the Win32 function
<code class="xref c c-func docutils literal notranslate"><span class="pre">QueryPerformanceCounter()</span></code>. The resolution is typically better than one
microsecond.</p>
</dd></dl>

<dl class="function">
<dt id="time.ctime">
<code class="descclassname">time.</code><code class="descname">ctime</code><span class="sig-paren">(</span><span class="optional">[</span><em>secs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.ctime" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a time expressed in seconds since the epoch to a string representing
local time. If <em>secs</em> is not provided or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time as
returned by <a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a> is used.  <code class="docutils literal notranslate"><span class="pre">ctime(secs)</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">asctime(localtime(secs))</span></code>. Locale information is not used by <a class="reference internal" href="#time.ctime" title="time.ctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctime()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>Allowed <em>secs</em> to be omitted.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>If <em>secs</em> is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time is used.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="time.daylight">
<code class="descclassname">time.</code><code class="descname">daylight</code><a class="headerlink" href="#time.daylight" title="Permalink to this definition">¶</a></dt>
<dd><p>Nonzero if a DST timezone is defined.</p>
</dd></dl>

<dl class="function">
<dt id="time.gmtime">
<code class="descclassname">time.</code><code class="descname">gmtime</code><span class="sig-paren">(</span><span class="optional">[</span><em>secs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.gmtime" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a time expressed in seconds since the epoch to a <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> in
UTC in which the dst flag is always zero.  If <em>secs</em> is not provided or
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time as returned by <a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a> is used.  Fractions
of a second are ignored.  See above for a description of the
<a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> object. See <a class="reference internal" href="calendar.html#calendar.timegm" title="calendar.timegm"><code class="xref py py-func docutils literal notranslate"><span class="pre">calendar.timegm()</span></code></a> for the inverse of this
function.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>Allowed <em>secs</em> to be omitted.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>If <em>secs</em> is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time is used.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="time.localtime">
<code class="descclassname">time.</code><code class="descname">localtime</code><span class="sig-paren">(</span><span class="optional">[</span><em>secs</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.localtime" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> but converts to local time.  If <em>secs</em> is not provided or
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time as returned by <a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a> is used.  The dst
flag is set to <code class="docutils literal notranslate"><span class="pre">1</span></code> when DST applies to the given time.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>Allowed <em>secs</em> to be omitted.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>If <em>secs</em> is <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the current time is used.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="time.mktime">
<code class="descclassname">time.</code><code class="descname">mktime</code><span class="sig-paren">(</span><em>t</em><span class="sig-paren">)</span><a class="headerlink" href="#time.mktime" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the inverse function of <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a>.  Its argument is the
<a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> or full 9-tuple (since the dst flag is needed; use <code class="docutils literal notranslate"><span class="pre">-1</span></code>
as the dst flag if it is unknown) which expresses the time in <em>local</em> time, not
UTC.  It returns a floating point number, for compatibility with <a class="reference internal" href="#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time()</span></code></a>.
If the input value cannot be represented as a valid time, either
<a class="reference internal" href="exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> or <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> will be raised (which depends on
whether the invalid value is caught by Python or the underlying C libraries).
The earliest date for which it can generate a time is platform-dependent.</p>
</dd></dl>

<dl class="function">
<dt id="time.sleep">
<code class="descclassname">time.</code><code class="descname">sleep</code><span class="sig-paren">(</span><em>secs</em><span class="sig-paren">)</span><a class="headerlink" href="#time.sleep" title="Permalink to this definition">¶</a></dt>
<dd><p>Suspend execution of the current thread for the given number of seconds.
The argument may be a floating point number to indicate a more precise sleep
time. The actual suspension time may be less than that requested because any
caught signal will terminate the <a class="reference internal" href="#time.sleep" title="time.sleep"><code class="xref py py-func docutils literal notranslate"><span class="pre">sleep()</span></code></a> following execution of that
signal’s catching routine.  Also, the suspension time may be longer than
requested by an arbitrary amount because of the scheduling of other activity
in the system.</p>
</dd></dl>

<dl class="function">
<dt id="time.strftime">
<code class="descclassname">time.</code><code class="descname">strftime</code><span class="sig-paren">(</span><em>format</em><span class="optional">[</span>, <em>t</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.strftime" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a tuple or <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> representing a time as returned by
<a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> or <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a> to a string as specified by the <em>format</em>
argument.  If <em>t</em> is not provided, the current time as returned by
<a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a> is used.  <em>format</em> must be a string.  <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is
raised if any field in <em>t</em> is outside of the allowed range. <a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a>
returns a locale dependent byte string; the result may be converted to unicode
by doing <code class="docutils literal notranslate"><span class="pre">strftime(&lt;myformat&gt;).decode(locale.getlocale()[1])</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>Allowed <em>t</em> to be omitted.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> raised if a field in <em>t</em> is out of range.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>0 is now a legal argument for any position in the time tuple; if it is normally
illegal the value is forced to a correct one.</p>
</div>
<p>The following directives can be embedded in the <em>format</em> string. They are shown
without the optional field width and precision specification, and are replaced
by the indicated characters in the <a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a> result:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="64%" />
<col width="14%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Directive</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%a</span></code></td>
<td>Locale’s abbreviated weekday
name.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%A</span></code></td>
<td>Locale’s full weekday name.</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%b</span></code></td>
<td>Locale’s abbreviated month
name.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%B</span></code></td>
<td>Locale’s full month name.</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%c</span></code></td>
<td>Locale’s appropriate date and
time representation.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%d</span></code></td>
<td>Day of the month as a decimal
number [01,31].</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%H</span></code></td>
<td>Hour (24-hour clock) as a
decimal number [00,23].</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%I</span></code></td>
<td>Hour (12-hour clock) as a
decimal number [01,12].</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%j</span></code></td>
<td>Day of the year as a decimal
number [001,366].</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%m</span></code></td>
<td>Month as a decimal number
[01,12].</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%M</span></code></td>
<td>Minute as a decimal number
[00,59].</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%p</span></code></td>
<td>Locale’s equivalent of either
AM or PM.</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%S</span></code></td>
<td>Second as a decimal number
[00,61].</td>
<td>(2)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%U</span></code></td>
<td>Week number of the year
(Sunday as the first day of
the week) as a decimal number
[00,53].  All days in a new
year preceding the first
Sunday are considered to be in
week 0.</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%w</span></code></td>
<td>Weekday as a decimal number
[0(Sunday),6].</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%W</span></code></td>
<td>Week number of the year
(Monday as the first day of
the week) as a decimal number
[00,53].  All days in a new
year preceding the first
Monday are considered to be in
week 0.</td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%x</span></code></td>
<td>Locale’s appropriate date
representation.</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%X</span></code></td>
<td>Locale’s appropriate time
representation.</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%y</span></code></td>
<td>Year without century as a
decimal number [00,99].</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%Y</span></code></td>
<td>Year with century as a decimal
number.</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">%Z</span></code></td>
<td>Time zone name (no characters
if no time zone exists).</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%%</span></code></td>
<td>A literal <code class="docutils literal notranslate"><span class="pre">'%'</span></code> character.</td>
<td>&#160;</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>When used with the <a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a> function, the <code class="docutils literal notranslate"><span class="pre">%p</span></code> directive only affects
the output hour field if the <code class="docutils literal notranslate"><span class="pre">%I</span></code> directive is used to parse the hour.</li>
<li>The range really is <code class="docutils literal notranslate"><span class="pre">0</span></code> to <code class="docutils literal notranslate"><span class="pre">61</span></code>; this accounts for leap seconds and the
(very rare) double leap seconds.</li>
<li>When used with the <a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a> function, <code class="docutils literal notranslate"><span class="pre">%U</span></code> and <code class="docutils literal notranslate"><span class="pre">%W</span></code> are only used in
calculations when the day of the week and the year are specified.</li>
</ol>
<p>Here is an example, a format for dates compatible with that specified  in the
<span class="target" id="index-9"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a> Internet email standard.  <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">time</span> <span class="k">import</span> <span class="n">gmtime</span><span class="p">,</span> <span class="n">strftime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%a, </span><span class="si">%d</span><span class="s2"> %b %Y %H:%M:%S +0000&quot;</span><span class="p">,</span> <span class="n">gmtime</span><span class="p">())</span>
<span class="go">&#39;Thu, 28 Jun 2001 14:17:15 +0000&#39;</span>
</pre></div>
</div>
<p>Additional directives may be supported on certain platforms, but only the
ones listed here have a meaning standardized by ANSI C.  To see the full set
of format codes supported on your platform, consult the <em class="manpage">strftime(3)</em>
documentation.</p>
<p>On some platforms, an optional field width and precision specification can
immediately follow the initial <code class="docutils literal notranslate"><span class="pre">'%'</span></code> of a directive in the following order;
this is also not portable. The field width is normally 2 except for <code class="docutils literal notranslate"><span class="pre">%j</span></code> where
it is 3.</p>
</dd></dl>

<dl class="function">
<dt id="time.strptime">
<code class="descclassname">time.</code><code class="descname">strptime</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>format</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#time.strptime" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a string representing a time according to a format.  The return  value is
a <a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a> as returned by <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> or <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a>.</p>
<p>The <em>format</em> parameter uses the same directives as those used by
<a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a>; it defaults to <code class="docutils literal notranslate"><span class="pre">&quot;%a</span> <span class="pre">%b</span> <span class="pre">%d</span> <span class="pre">%H:%M:%S</span> <span class="pre">%Y&quot;</span></code> which matches the
formatting returned by <a class="reference internal" href="#time.ctime" title="time.ctime"><code class="xref py py-func docutils literal notranslate"><span class="pre">ctime()</span></code></a>. If <em>string</em> cannot be parsed according to
<em>format</em>, or if it has excess data after parsing, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.
The default values used to fill in any missing data when more accurate values
cannot be inferred are <code class="docutils literal notranslate"><span class="pre">(1900,</span> <span class="pre">1,</span> <span class="pre">1,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">0,</span> <span class="pre">1,</span> <span class="pre">-1)</span></code>.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="s2">&quot;30 Nov 00&quot;</span><span class="p">,</span> <span class="s2">&quot;</span><span class="si">%d</span><span class="s2"> %b %y&quot;</span><span class="p">)</span>   
<span class="go">time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,</span>
<span class="go">                 tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)</span>
</pre></div>
</div>
<p>Support for the <code class="docutils literal notranslate"><span class="pre">%Z</span></code> directive is based on the values contained in <code class="docutils literal notranslate"><span class="pre">tzname</span></code>
and whether <code class="docutils literal notranslate"><span class="pre">daylight</span></code> is true.  Because of this, it is platform-specific
except for recognizing UTC and GMT which are always known (and are considered to
be non-daylight savings timezones).</p>
<p>Only the directives specified in the documentation are supported.  Because
<code class="docutils literal notranslate"><span class="pre">strftime()</span></code> is implemented per platform it can sometimes offer more
directives than those listed.  But <code class="docutils literal notranslate"><span class="pre">strptime()</span></code> is independent of any platform
and thus does not necessarily support all directives available that are not
documented as supported.</p>
</dd></dl>

<dl class="class">
<dt id="time.struct_time">
<em class="property">class </em><code class="descclassname">time.</code><code class="descname">struct_time</code><a class="headerlink" href="#time.struct_time" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of the time value sequence returned by <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a>,
<a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a>, and <a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a>.  It is an object with a <a class="reference internal" href="../glossary.html#term-named-tuple"><span class="xref std std-term">named
tuple</span></a> interface: values can be accessed by index and by attribute name.  The
following values are present:</p>
<table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="32%" />
<col width="56%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Attribute</th>
<th class="head">Values</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_year</span></code></td>
<td>(for example, 1993)</td>
</tr>
<tr class="row-odd"><td>1</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_mon</span></code></td>
<td>range [1, 12]</td>
</tr>
<tr class="row-even"><td>2</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_mday</span></code></td>
<td>range [1, 31]</td>
</tr>
<tr class="row-odd"><td>3</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_hour</span></code></td>
<td>range [0, 23]</td>
</tr>
<tr class="row-even"><td>4</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_min</span></code></td>
<td>range [0, 59]</td>
</tr>
<tr class="row-odd"><td>5</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_sec</span></code></td>
<td>range [0, 61]; see <strong>(2)</strong> in
<a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a> description</td>
</tr>
<tr class="row-even"><td>6</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_wday</span></code></td>
<td>range [0, 6], Monday is 0</td>
</tr>
<tr class="row-odd"><td>7</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_yday</span></code></td>
<td>range [1, 366]</td>
</tr>
<tr class="row-even"><td>8</td>
<td><code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code></td>
<td>0, 1 or -1; see below</td>
</tr>
</tbody>
</table>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p>Note that unlike the C structure, the month value is a range of [1, 12], not
[0, 11].  A year value will be handled as described under <a class="reference internal" href="#time-y2kissues"><span class="std std-ref">Year 2000
(Y2K) issues</span></a> above.</p>
<p>In calls to <a class="reference internal" href="#time.mktime" title="time.mktime"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktime()</span></code></a>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_isdst</span></code> may be set to 1 when daylight
savings time is in effect, and 0 when it is not.  A value of -1 indicates
that this is not known, and will usually result in the correct state being
filled in.</p>
<p>When a tuple with an incorrect length is passed to a function expecting a
<a class="reference internal" href="#time.struct_time" title="time.struct_time"><code class="xref py py-class docutils literal notranslate"><span class="pre">struct_time</span></code></a>, or having elements of the wrong type, a
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="time.time">
<code class="descclassname">time.</code><code class="descname">time</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#time.time" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the time in seconds since the epoch as a floating point number.
Note that even though the time is always returned as a floating point
number, not all systems provide time with a better precision than 1 second.
While this function normally returns non-decreasing values, it can return a
lower value than a previous call if the system clock has been set back between
the two calls.</p>
</dd></dl>

<dl class="data">
<dt id="time.timezone">
<code class="descclassname">time.</code><code class="descname">timezone</code><a class="headerlink" href="#time.timezone" title="Permalink to this definition">¶</a></dt>
<dd><p>The offset of the local (non-DST) timezone, in seconds west of UTC (negative in
most of Western Europe, positive in the US, zero in the UK).</p>
</dd></dl>

<dl class="data">
<dt id="time.tzname">
<code class="descclassname">time.</code><code class="descname">tzname</code><a class="headerlink" href="#time.tzname" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of two strings: the first is the name of the local non-DST timezone, the
second is the name of the local DST timezone.  If no DST timezone is defined,
the second string should not be used.</p>
</dd></dl>

<dl class="function">
<dt id="time.tzset">
<code class="descclassname">time.</code><code class="descname">tzset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#time.tzset" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the time conversion rules used by the library routines. The environment
variable <span class="target" id="index-10"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> specifies how this is done. It will also set the variables
<code class="docutils literal notranslate"><span class="pre">tzname</span></code> (from the <span class="target" id="index-11"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> environment variable), <code class="docutils literal notranslate"><span class="pre">timezone</span></code> (non-DST
seconds West of UTC), <code class="docutils literal notranslate"><span class="pre">altzone</span></code> (DST seconds west of UTC) and <code class="docutils literal notranslate"><span class="pre">daylight</span></code>
(to 0 if this timezone does not have any daylight saving time rules, or to
nonzero if there is a time, past, present or future when daylight saving time
applies).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>Availability: Unix.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>Although in many cases, changing the <span class="target" id="index-12"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> environment variable may
affect the output of functions like <a class="reference internal" href="#time.localtime" title="time.localtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code></a> without calling
<a class="reference internal" href="#time.tzset" title="time.tzset"><code class="xref py py-func docutils literal notranslate"><span class="pre">tzset()</span></code></a>, this behavior should not be relied on.</p>
<p class="last">The <span class="target" id="index-13"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> environment variable should contain no whitespace.</p>
</div>
<p>The standard format of the <span class="target" id="index-14"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> environment variable is (whitespace
added for clarity):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">std</span> <span class="n">offset</span> <span class="p">[</span><span class="n">dst</span> <span class="p">[</span><span class="n">offset</span> <span class="p">[,</span><span class="n">start</span><span class="p">[</span><span class="o">/</span><span class="n">time</span><span class="p">],</span> <span class="n">end</span><span class="p">[</span><span class="o">/</span><span class="n">time</span><span class="p">]]]]</span>
</pre></div>
</div>
<p>Where the components are:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">std</span></code> and <code class="docutils literal notranslate"><span class="pre">dst</span></code></dt>
<dd>Three or more alphanumerics giving the timezone abbreviations. These will be
propagated into time.tzname</dd>
<dt><code class="docutils literal notranslate"><span class="pre">offset</span></code></dt>
<dd>The offset has the form: <code class="docutils literal notranslate"><span class="pre">±</span> <span class="pre">hh[:mm[:ss]]</span></code>. This indicates the value
added the local time to arrive at UTC.  If preceded by a ‘-‘, the timezone
is east of the Prime Meridian; otherwise, it is west. If no offset follows
dst, summer time is assumed to be one hour ahead of standard time.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">start[/time],</span> <span class="pre">end[/time]</span></code></dt>
<dd><p class="first">Indicates when to change to and back from DST. The format of the
start and end dates are one of the following:</p>
<dl class="docutils">
<dt><code class="samp docutils literal notranslate"><span class="pre">J</span><em><span class="pre">n</span></em></code></dt>
<dd>The Julian day <em>n</em> (1 &lt;= <em>n</em> &lt;= 365). Leap days are not counted, so in
all years February 28 is day 59 and March 1 is day 60.</dd>
<dt><code class="samp docutils literal notranslate"><em><span class="pre">n</span></em></code></dt>
<dd>The zero-based Julian day (0 &lt;= <em>n</em> &lt;= 365). Leap days are counted, and
it is possible to refer to February 29.</dd>
<dt><code class="samp docutils literal notranslate"><span class="pre">M</span><em><span class="pre">m</span></em><span class="pre">.</span><em><span class="pre">n</span></em><span class="pre">.</span><em><span class="pre">d</span></em></code></dt>
<dd>The <em>d</em>’th day (0 &lt;= <em>d</em> &lt;= 6) or week <em>n</em> of month <em>m</em> of the year (1
&lt;= <em>n</em> &lt;= 5, 1 &lt;= <em>m</em> &lt;= 12, where week 5 means “the last <em>d</em> day in
month <em>m</em>” which may occur in either the fourth or the fifth
week). Week 1 is the first week in which the <em>d</em>’th day occurs. Day
zero is Sunday.</dd>
</dl>
<p class="last"><code class="docutils literal notranslate"><span class="pre">time</span></code> has the same format as <code class="docutils literal notranslate"><span class="pre">offset</span></code> except that no leading sign
(‘-‘ or ‘+’) is allowed. The default, if time is not given, is 02:00:00.</p>
</dd>
</dl>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;TZ&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;EST+05EDT,M4.1.0,M10.5.0&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1"> </span><span class="si">%x</span><span class="s1"> %Z&#39;</span><span class="p">)</span>
<span class="go">&#39;02:07:36 05/08/03 EDT&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;TZ&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;AEST-10AEDT-11,M10.5.0,M3.5.0&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%X</span><span class="s1"> </span><span class="si">%x</span><span class="s1"> %Z&#39;</span><span class="p">)</span>
<span class="go">&#39;16:08:12 05/08/03 AEST&#39;</span>
</pre></div>
</div>
<p>On many Unix systems (including *BSD, Linux, Solaris, and Darwin), it is more
convenient to use the system’s zoneinfo (<em class="manpage">tzfile(5)</em>)  database to
specify the timezone rules. To do this, set the  <span class="target" id="index-15"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TZ</span></code> environment
variable to the path of the required timezone  datafile, relative to the root of
the systems ‘zoneinfo’ timezone database, usually located at
<code class="file docutils literal notranslate"><span class="pre">/usr/share/zoneinfo</span></code>. For example,  <code class="docutils literal notranslate"><span class="pre">'US/Eastern'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'Australia/Melbourne'</span></code>, <code class="docutils literal notranslate"><span class="pre">'Egypt'</span></code> or  <code class="docutils literal notranslate"><span class="pre">'Europe/Amsterdam'</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;TZ&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;US/Eastern&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzname</span>
<span class="go">(&#39;EST&#39;, &#39;EDT&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="s1">&#39;TZ&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;Egypt&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">time</span><span class="o">.</span><span class="n">tzname</span>
<span class="go">(&#39;EET&#39;, &#39;EEST&#39;)</span>
</pre></div>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a></dt>
<dd>More object-oriented interface to dates and times.</dd>
<dt>Module <a class="reference internal" href="locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a></dt>
<dd>Internationalization services.  The locale setting affects the interpretation
of many format specifiers in <a class="reference internal" href="#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strftime()</span></code></a> and <a class="reference internal" href="#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code></a>.</dd>
<dt>Module <a class="reference internal" href="calendar.html#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a></dt>
<dd>General calendar-related functions.   <a class="reference internal" href="calendar.html#calendar.timegm" title="calendar.timegm"><code class="xref py py-func docutils literal notranslate"><span class="pre">timegm()</span></code></a> is the
inverse of <a class="reference internal" href="#time.gmtime" title="time.gmtime"><code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code></a> from this module.</dd>
</dl>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The use of <code class="docutils literal notranslate"><span class="pre">%Z</span></code> is now deprecated, but the <code class="docutils literal notranslate"><span class="pre">%z</span></code> escape that expands to the
preferred  hour/minute offset is not supported by all ANSI C libraries. Also, a
strict reading of the original 1982 <span class="target" id="index-16"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> standard calls for a two-digit
year (%y rather than %Y), but practice moved to 4-digit years long before the
year 2000.  After that, <span class="target" id="index-17"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a> became obsolete and the 4-digit year has
been first recommended by <span class="target" id="index-18"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1123.html"><strong>RFC 1123</strong></a> and then mandated by <span class="target" id="index-19"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>.</td></tr>
</tbody>
</table>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="io.html"
                        title="previous chapter">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="argparse.html"
                        title="next chapter">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/time.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="argparse.html" title="15.4. argparse — Parser for command-line options, arguments and sub-commands"
             >next</a> |</li>
        <li class="right" >
          <a href="io.html" title="15.2. io — Core tools for working with streams"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="allos.html" >15. Generic Operating System Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\���Q�Q�html/library/timeit.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.6. timeit — Measure execution time of small code snippets &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="26.7. trace — Trace or track Python statement execution" href="trace.html" />
    <link rel="prev" title="26.5. hotshot — High performance logging profiler" href="hotshot.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/timeit.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="trace.html" title="26.7. trace — Trace or track Python statement execution"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="hotshot.html" title="26.5. hotshot — High performance logging profiler"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-timeit">
<span id="timeit-measure-execution-time-of-small-code-snippets"></span><h1>26.6. <a class="reference internal" href="#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> — Measure execution time of small code snippets<a class="headerlink" href="#module-timeit" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/timeit.py">Lib/timeit.py</a></p>
<hr class="docutils" />
<p>This module provides a simple way to time small bits of Python code. It has both
a <a class="reference internal" href="#timeit-command-line-interface"><span class="std std-ref">Command-Line Interface</span></a> as well as a <a class="reference internal" href="#python-interface"><span class="std std-ref">callable</span></a>
one.  It avoids a number of common traps for measuring execution times.
See also Tim Peters’ introduction to the “Algorithms” chapter in the <em>Python
Cookbook</em>, published by O’Reilly.</p>
<div class="section" id="basic-examples">
<h2>26.6.1. Basic Examples<a class="headerlink" href="#basic-examples" title="Permalink to this headline">¶</a></h2>
<p>The following example shows how the <a class="reference internal" href="#timeit-command-line-interface"><span class="std std-ref">Command-Line Interface</span></a>
can be used to compare three different expressions:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python -m timeit <span class="s1">&#39;&quot;-&quot;.join(str(n) for n in range(100))&#39;</span>
<span class="m">10000</span> loops, best of <span class="m">3</span>: <span class="m">40</span>.3 usec per loop
$ python -m timeit <span class="s1">&#39;&quot;-&quot;.join([str(n) for n in range(100)])&#39;</span>
<span class="m">10000</span> loops, best of <span class="m">3</span>: <span class="m">33</span>.4 usec per loop
$ python -m timeit <span class="s1">&#39;&quot;-&quot;.join(map(str, range(100)))&#39;</span>
<span class="m">10000</span> loops, best of <span class="m">3</span>: <span class="m">25</span>.2 usec per loop
</pre></div>
</div>
<p>This can be achieved from the <a class="reference internal" href="#python-interface"><span class="std std-ref">Python Interface</span></a> with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s1">&#39;&quot;-&quot;.join(str(n) for n in range(100))&#39;</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">10000</span><span class="p">)</span>
<span class="go">0.8187260627746582</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s1">&#39;&quot;-&quot;.join([str(n) for n in range(100)])&#39;</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">10000</span><span class="p">)</span>
<span class="go">0.7288308143615723</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s1">&#39;&quot;-&quot;.join(map(str, range(100)))&#39;</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">10000</span><span class="p">)</span>
<span class="go">0.5858950614929199</span>
</pre></div>
</div>
<p>Note however that <a class="reference internal" href="#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> will automatically determine the number of
repetitions only when the command-line interface is used.  In the
<a class="reference internal" href="#timeit-examples"><span class="std std-ref">Examples</span></a> section you can find more advanced examples.</p>
</div>
<div class="section" id="python-interface">
<span id="id1"></span><h2>26.6.2. Python Interface<a class="headerlink" href="#python-interface" title="Permalink to this headline">¶</a></h2>
<p>The module defines three convenience functions and a public class:</p>
<dl class="function">
<dt id="timeit.timeit">
<code class="descclassname">timeit.</code><code class="descname">timeit</code><span class="sig-paren">(</span><em>stmt='pass'</em>, <em>setup='pass'</em>, <em>timer=&lt;default timer&gt;</em>, <em>number=1000000</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.timeit" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> instance with the given statement, <em>setup</em> code and
<em>timer</em> function and run its <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a> method with <em>number</em> executions.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="timeit.repeat">
<code class="descclassname">timeit.</code><code class="descname">repeat</code><span class="sig-paren">(</span><em>stmt='pass'</em>, <em>setup='pass'</em>, <em>timer=&lt;default timer&gt;</em>, <em>repeat=3</em>, <em>number=1000000</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.repeat" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> instance with the given statement, <em>setup</em> code and
<em>timer</em> function and run its <a class="reference internal" href="#timeit.Timer.repeat" title="timeit.Timer.repeat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repeat()</span></code></a> method with the given <em>repeat</em>
count and <em>number</em> executions.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="timeit.default_timer">
<code class="descclassname">timeit.</code><code class="descname">default_timer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#timeit.default_timer" title="Permalink to this definition">¶</a></dt>
<dd><p>Define a default timer, in a platform-specific manner.  On Windows,
<a class="reference internal" href="time.html#time.clock" title="time.clock"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.clock()</span></code></a> has microsecond granularity, but <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>’s
granularity is 1/60th of a second.  On Unix, <a class="reference internal" href="time.html#time.clock" title="time.clock"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.clock()</span></code></a> has 1/100th of
a second granularity, and <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a> is much more precise.  On either
platform, <a class="reference internal" href="#timeit.default_timer" title="timeit.default_timer"><code class="xref py py-func docutils literal notranslate"><span class="pre">default_timer()</span></code></a> measures wall clock time, not the CPU
time.  This means that other processes running on the same computer may
interfere with the timing.</p>
</dd></dl>

<dl class="class">
<dt id="timeit.Timer">
<em class="property">class </em><code class="descclassname">timeit.</code><code class="descname">Timer</code><span class="sig-paren">(</span><em>stmt='pass'</em>, <em>setup='pass'</em>, <em>timer=&lt;timer function&gt;</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.Timer" title="Permalink to this definition">¶</a></dt>
<dd><p>Class for timing execution speed of small code snippets.</p>
<p>The constructor takes a statement to be timed, an additional statement used
for setup, and a timer function.  Both statements default to <code class="docutils literal notranslate"><span class="pre">'pass'</span></code>;
the timer function is platform-dependent (see the module doc string).
<em>stmt</em> and <em>setup</em> may also contain multiple statements separated by <code class="docutils literal notranslate"><span class="pre">;</span></code>
or newlines, as long as they don’t contain multi-line string literals.</p>
<p>To measure the execution time of the first statement, use the <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a>
method.  The <a class="reference internal" href="#timeit.Timer.repeat" title="timeit.Timer.repeat"><code class="xref py py-meth docutils literal notranslate"><span class="pre">repeat()</span></code></a> method is a convenience to call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a>
multiple times and return a list of results.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The <em>stmt</em> and <em>setup</em> parameters can now also take objects that are
callable without arguments.  This will embed calls to them in a timer
function that will then be executed by <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a>.  Note that the
timing overhead is a little larger in this case because of the extra
function calls.</p>
</div>
<dl class="method">
<dt id="timeit.Timer.timeit">
<code class="descname">timeit</code><span class="sig-paren">(</span><em>number=1000000</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.Timer.timeit" title="Permalink to this definition">¶</a></dt>
<dd><p>Time <em>number</em> executions of the main statement.  This executes the setup
statement once, and then returns the time it takes to execute the main
statement a number of times, measured in seconds as a float.
The argument is the number of times through the loop, defaulting to one
million.  The main statement, the setup statement and the timer function
to be used are passed to the constructor.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>By default, <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a> temporarily turns off <a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage
collection</span></a> during the timing.  The advantage of this approach is that
it makes independent timings more comparable.  This disadvantage is
that GC may be an important component of the performance of the
function being measured.  If so, GC can be re-enabled as the first
statement in the <em>setup</em> string.  For example:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;for i in xrange(10): oct(i)&#39;</span><span class="p">,</span> <span class="s1">&#39;gc.enable()&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
</pre></div>
</div>
</div>
</dd></dl>

<dl class="method">
<dt id="timeit.Timer.repeat">
<code class="descname">repeat</code><span class="sig-paren">(</span><em>repeat=3</em>, <em>number=1000000</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.Timer.repeat" title="Permalink to this definition">¶</a></dt>
<dd><p>Call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a> a few times.</p>
<p>This is a convenience function that calls the <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a> repeatedly,
returning a list of results.  The first argument specifies how many times
to call <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a>.  The second argument specifies the <em>number</em>
argument for <a class="reference internal" href="#timeit.Timer.timeit" title="timeit.Timer.timeit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">timeit()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">It’s tempting to calculate mean and standard deviation from the result
vector and report these.  However, this is not very useful.
In a typical case, the lowest value gives a lower bound for how fast
your machine can run the given code snippet; higher values in the
result vector are typically not caused by variability in Python’s
speed, but by other processes interfering with your timing accuracy.
So the <a class="reference internal" href="functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> of the result is probably the only number you
should be interested in.  After that, you should look at the entire
vector and apply common sense rather than statistics.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="timeit.Timer.print_exc">
<code class="descname">print_exc</code><span class="sig-paren">(</span><em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#timeit.Timer.print_exc" title="Permalink to this definition">¶</a></dt>
<dd><p>Helper to print a traceback from the timed code.</p>
<p>Typical use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="n">Timer</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>       <span class="c1"># outside the try/except</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">t</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>    <span class="c1"># or t.repeat(...)</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">t</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
</pre></div>
</div>
<p>The advantage over the standard traceback is that source lines in the
compiled template will be displayed. The optional <em>file</em> argument directs
where the traceback is sent; it defaults to <a class="reference internal" href="sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="command-line-interface">
<span id="timeit-command-line-interface"></span><h2>26.6.3. Command-Line Interface<a class="headerlink" href="#command-line-interface" title="Permalink to this headline">¶</a></h2>
<p>When called as a program from the command line, the following form is used:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">timeit</span> <span class="p">[</span><span class="o">-</span><span class="n">n</span> <span class="n">N</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">r</span> <span class="n">N</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">s</span> <span class="n">S</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">t</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">c</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">h</span><span class="p">]</span> <span class="p">[</span><span class="n">statement</span> <span class="o">...</span><span class="p">]</span>
</pre></div>
</div>
<p>Where the following options are understood:</p>
<dl class="cmdoption">
<dt id="cmdoption-timeit-n">
<code class="descname">-n</code><code class="descclassname"> N</code><code class="descclassname">, </code><code class="descname">--number</code><code class="descclassname">=N</code><a class="headerlink" href="#cmdoption-timeit-n" title="Permalink to this definition">¶</a></dt>
<dd><p>how many times to execute ‘statement’</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-r">
<code class="descname">-r</code><code class="descclassname"> N</code><code class="descclassname">, </code><code class="descname">--repeat</code><code class="descclassname">=N</code><a class="headerlink" href="#cmdoption-timeit-r" title="Permalink to this definition">¶</a></dt>
<dd><p>how many times to repeat the timer (default 3)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-s">
<code class="descname">-s</code><code class="descclassname"> S</code><code class="descclassname">, </code><code class="descname">--setup</code><code class="descclassname">=S</code><a class="headerlink" href="#cmdoption-timeit-s" title="Permalink to this definition">¶</a></dt>
<dd><p>statement to be executed once initially (default <code class="docutils literal notranslate"><span class="pre">pass</span></code>)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-t">
<code class="descname">-t</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--time</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-timeit-t" title="Permalink to this definition">¶</a></dt>
<dd><p>use <a class="reference internal" href="time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a> (default on all platforms but Windows)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-c">
<code class="descname">-c</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--clock</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-timeit-c" title="Permalink to this definition">¶</a></dt>
<dd><p>use <a class="reference internal" href="time.html#time.clock" title="time.clock"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.clock()</span></code></a> (default on Windows)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-v">
<code class="descname">-v</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--verbose</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-timeit-v" title="Permalink to this definition">¶</a></dt>
<dd><p>print raw timing results; repeat for more digits precision</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-timeit-h">
<code class="descname">-h</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--help</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-timeit-h" title="Permalink to this definition">¶</a></dt>
<dd><p>print a short usage message and exit</p>
</dd></dl>

<p>A multi-line statement may be given by specifying each line as a separate
statement argument; indented lines are possible by enclosing an argument in
quotes and using leading spaces.  Multiple <a class="reference internal" href="#cmdoption-timeit-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> options are treated
similarly.</p>
<p>If <a class="reference internal" href="#cmdoption-timeit-n"><code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code></a> is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.</p>
<p><a class="reference internal" href="#timeit.default_timer" title="timeit.default_timer"><code class="xref py py-func docutils literal notranslate"><span class="pre">default_timer()</span></code></a> measurations can be affected by other programs running on
the same machine, so
the best thing to do when accurate timing is necessary is to repeat
the timing a few times and use the best time.  The <a class="reference internal" href="#cmdoption-timeit-r"><code class="xref std std-option docutils literal notranslate"><span class="pre">-r</span></code></a> option is good
for this; the default of 3 repetitions is probably enough in most cases.  On
Unix, you can use <a class="reference internal" href="time.html#time.clock" title="time.clock"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.clock()</span></code></a> to measure CPU time.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There is a certain baseline overhead associated with executing a pass statement.
The code here doesn’t try to hide it, but you should be aware of it.  The
baseline overhead can be measured by invoking the program without arguments, and
it might differ between Python versions.  Also, to fairly compare older Python
versions to Python 2.3, you may want to use Python’s <code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code>
option (see <a class="reference internal" href="../using/cmdline.html#using-on-optimizations"><span class="std std-ref">Optimizations</span></a>) for
the older versions to avoid timing <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code> instructions.</p>
</div>
</div>
<div class="section" id="examples">
<span id="timeit-examples"></span><h2>26.6.4. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>It is possible to provide a setup statement that is executed only once at the beginning:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python -m timeit -s <span class="s1">&#39;text = &quot;sample string&quot;; char = &quot;g&quot;&#39;</span>  <span class="s1">&#39;char in text&#39;</span>
<span class="m">10000000</span> loops, best of <span class="m">3</span>: <span class="m">0</span>.0877 usec per loop
$ python -m timeit -s <span class="s1">&#39;text = &quot;sample string&quot;; char = &quot;g&quot;&#39;</span>  <span class="s1">&#39;text.find(char)&#39;</span>
<span class="m">1000000</span> loops, best of <span class="m">3</span>: <span class="m">0</span>.342 usec per loop
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s1">&#39;char in text&#39;</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s1">&#39;text = &quot;sample string&quot;; char = &quot;g&quot;&#39;</span><span class="p">)</span>
<span class="go">0.41440500499993504</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s1">&#39;text.find(char)&#39;</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s1">&#39;text = &quot;sample string&quot;; char = &quot;g&quot;&#39;</span><span class="p">)</span>
<span class="go">1.7246671520006203</span>
</pre></div>
</div>
<p>The same can be done using the <a class="reference internal" href="#timeit.Timer" title="timeit.Timer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code></a> class and its methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;char in text&#39;</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s1">&#39;text = &quot;sample string&quot;; char = &quot;g&quot;&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
<span class="go">0.3955516149999312</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">repeat</span><span class="p">()</span>
<span class="go">[0.40193588800002544, 0.3960157959998014, 0.39594301399984033]</span>
</pre></div>
</div>
<p>The following examples show how to time expressions that contain multiple lines.
Here we compare the cost of using <a class="reference internal" href="functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> vs. <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>/<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
to test for missing and present object attributes:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ python -m timeit <span class="s1">&#39;try:&#39;</span> <span class="s1">&#39;  str.__nonzero__&#39;</span> <span class="s1">&#39;except AttributeError:&#39;</span> <span class="s1">&#39;  pass&#39;</span>
<span class="m">100000</span> loops, best of <span class="m">3</span>: <span class="m">15</span>.7 usec per loop
$ python -m timeit <span class="s1">&#39;if hasattr(str, &quot;__nonzero__&quot;): pass&#39;</span>
<span class="m">100000</span> loops, best of <span class="m">3</span>: <span class="m">4</span>.26 usec per loop

$ python -m timeit <span class="s1">&#39;try:&#39;</span> <span class="s1">&#39;  int.__nonzero__&#39;</span> <span class="s1">&#39;except AttributeError:&#39;</span> <span class="s1">&#39;  pass&#39;</span>
<span class="m">1000000</span> loops, best of <span class="m">3</span>: <span class="m">1</span>.43 usec per loop
$ python -m timeit <span class="s1">&#39;if hasattr(int, &quot;__nonzero__&quot;): pass&#39;</span>
<span class="m">100000</span> loops, best of <span class="m">3</span>: <span class="m">2</span>.23 usec per loop
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">timeit</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># attribute is missing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="gp">... </span><span class="s2">try:</span>
<span class="gp">... </span><span class="s2">    str.__nonzero__</span>
<span class="gp">... </span><span class="s2">except AttributeError:</span>
<span class="gp">... </span><span class="s2">    pass</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">stmt</span><span class="o">=</span><span class="n">s</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="go">0.9138244460009446</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;if hasattr(str, &#39;__bool__&#39;): pass&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">stmt</span><span class="o">=</span><span class="n">s</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="go">0.5829014980008651</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># attribute is present</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="gp">... </span><span class="s2">try:</span>
<span class="gp">... </span><span class="s2">    int.__nonzero__</span>
<span class="gp">... </span><span class="s2">except AttributeError:</span>
<span class="gp">... </span><span class="s2">    pass</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">stmt</span><span class="o">=</span><span class="n">s</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="go">0.04215312199994514</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;if hasattr(int, &#39;__bool__&#39;): pass&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="n">stmt</span><span class="o">=</span><span class="n">s</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="go">0.08588060699912603</span>
</pre></div>
</div>
<p>To give the <a class="reference internal" href="#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module access to functions you define, you can pass a
<em>setup</em> parameter which contains an import statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="sd">&quot;&quot;&quot;Stupid test function&quot;&quot;&quot;</span>
    <span class="n">L</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">):</span>
        <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">timeit</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">timeit</span><span class="o">.</span><span class="n">timeit</span><span class="p">(</span><span class="s2">&quot;test()&quot;</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s2">&quot;from __main__ import test&quot;</span><span class="p">))</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a><ul>
<li><a class="reference internal" href="#basic-examples">26.6.1. Basic Examples</a></li>
<li><a class="reference internal" href="#python-interface">26.6.2. Python Interface</a></li>
<li><a class="reference internal" href="#command-line-interface">26.6.3. Command-Line Interface</a></li>
<li><a class="reference internal" href="#examples">26.6.4. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="hotshot.html"
                        title="previous chapter">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="trace.html"
                        title="next chapter">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/timeit.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="trace.html" title="26.7. trace — Trace or track Python statement execution"
             >next</a> |</li>
        <li class="right" >
          <a href="hotshot.html" title="26.5. hotshot — High performance logging profiler"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��`�����html/library/tix.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.3. Tix — Extension widgets for Tk &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.4. ScrolledText — Scrolled Text Widget" href="scrolledtext.html" />
    <link rel="prev" title="24.2. ttk — Tk themed widgets" href="ttk.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tix.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="scrolledtext.html" title="24.4. ScrolledText — Scrolled Text Widget"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="ttk.html" title="24.2. ttk — Tk themed widgets"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-Tix">
<span id="tix-extension-widgets-for-tk"></span><h1>24.3. <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> — Extension widgets for Tk<a class="headerlink" href="#module-Tix" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> (Tk Interface Extension) module provides an additional rich set
of widgets. Although the standard Tk library has many useful widgets, they are
far from complete. The <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> library provides most of the commonly needed
widgets that are missing from standard Tk: <a class="reference internal" href="#Tix.HList" title="Tix.HList"><code class="xref py py-class docutils literal notranslate"><span class="pre">HList</span></code></a>, <a class="reference internal" href="#Tix.ComboBox" title="Tix.ComboBox"><code class="xref py py-class docutils literal notranslate"><span class="pre">ComboBox</span></code></a>,
<a class="reference internal" href="#Tix.Control" title="Tix.Control"><code class="xref py py-class docutils literal notranslate"><span class="pre">Control</span></code></a> (a.k.a. SpinBox) and an assortment of scrollable widgets.
<a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> also includes many more widgets that are generally useful in a wide
range of applications: <a class="reference internal" href="#Tix.NoteBook" title="Tix.NoteBook"><code class="xref py py-class docutils literal notranslate"><span class="pre">NoteBook</span></code></a>, <a class="reference internal" href="#Tix.FileEntry" title="Tix.FileEntry"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileEntry</span></code></a>,
<a class="reference internal" href="#Tix.PanedWindow" title="Tix.PanedWindow"><code class="xref py py-class docutils literal notranslate"><span class="pre">PanedWindow</span></code></a>, etc; there are more than 40 of them.</p>
<p>With all these new widgets, you can introduce new interaction techniques into
applications, creating more useful and more intuitive user interfaces. You can
design your application by choosing the most appropriate widgets to match the
special needs of your application and users.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter.tix</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://tix.sourceforge.net/">Tix Homepage</a></dt>
<dd>The home page for <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a>.  This includes links to additional documentation
and downloads.</dd>
<dt><a class="reference external" href="http://tix.sourceforge.net/dist/current/man/">Tix Man Pages</a></dt>
<dd>On-line version of the man pages and reference material.</dd>
<dt><a class="reference external" href="http://tix.sourceforge.net/dist/current/docs/tix-book/tix.book.html">Tix Programming Guide</a></dt>
<dd>On-line version of the programmer’s reference material.</dd>
<dt><a class="reference external" href="http://tix.sourceforge.net/Tixapps/src/Tide.html">Tix Development Applications</a></dt>
<dd>Tix applications for development of Tix and Tkinter programs. Tide applications
work under Tk or Tkinter, and include <strong class="program">TixInspect</strong>, an inspector to
remotely modify and debug Tix/Tk/Tkinter applications.</dd>
</dl>
</div>
<div class="section" id="using-tix">
<h2>24.3.1. Using Tix<a class="headerlink" href="#using-tix" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="Tix.Tix">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Tix</code><span class="sig-paren">(</span><em>screenName</em><span class="optional">[</span>, <em>baseName</em><span class="optional">[</span>, <em>className</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Tix.Tix" title="Permalink to this definition">¶</a></dt>
<dd><p>Toplevel widget of Tix which represents mostly the main window of an
application. It has an associated Tcl interpreter.</p>
<p>Classes in the <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> module subclasses the classes in the <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>
module. The former imports the latter, so to use <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> with Tkinter, all
you need to do is to import one module. In general, you can just import
<a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a>, and replace the toplevel call to <a class="reference internal" href="tkinter.html#Tkinter.Tk" title="Tkinter.Tk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Tk</span></code></a> with
<code class="xref py py-class docutils literal notranslate"><span class="pre">Tix.Tk</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tix</span>
<span class="kn">from</span> <span class="nn">Tkconstants</span> <span class="k">import</span> <span class="o">*</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">Tix</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<p>To use <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a>, you must have the <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> widgets installed, usually
alongside your installation of the Tk widgets. To test your installation, try
the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tix</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">Tix</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>
<span class="n">root</span><span class="o">.</span><span class="n">tk</span><span class="o">.</span><span class="n">eval</span><span class="p">(</span><span class="s1">&#39;package require Tix&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If this fails, you have a Tk installation problem which must be resolved before
proceeding. Use the environment variable <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TIX_LIBRARY</span></code> to point to the
installed <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> library directory, and make sure you have the dynamic
object library (<code class="file docutils literal notranslate"><span class="pre">tix8183.dll</span></code> or <code class="file docutils literal notranslate"><span class="pre">libtix8183.so</span></code>) in  the same
directory that contains your Tk dynamic object library (<code class="file docutils literal notranslate"><span class="pre">tk8183.dll</span></code> or
<code class="file docutils literal notranslate"><span class="pre">libtk8183.so</span></code>). The directory with the dynamic object library should also
have a file called <code class="file docutils literal notranslate"><span class="pre">pkgIndex.tcl</span></code> (case sensitive), which contains the
line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">package</span> <span class="n">ifneeded</span> <span class="n">Tix</span> <span class="mf">8.1</span> <span class="p">[</span><span class="nb">list</span> <span class="n">load</span> <span class="s2">&quot;[file join $dir tix8183.dll]&quot;</span> <span class="n">Tix</span><span class="p">]</span>
</pre></div>
</div>
</div>
<div class="section" id="tix-widgets">
<h2>24.3.2. Tix Widgets<a class="headerlink" href="#tix-widgets" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm">Tix</a>
introduces over 40 widget classes to the <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>  repertoire.  There is a
demo of all the <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> widgets in the <code class="file docutils literal notranslate"><span class="pre">Demo/tix</span></code> directory of the
standard distribution.</p>
<div class="section" id="basic-widgets">
<h3>24.3.2.1. Basic Widgets<a class="headerlink" href="#basic-widgets" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.Balloon">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Balloon</code><a class="headerlink" href="#Tix.Balloon" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixBalloon.htm">Balloon</a> that
pops up over a widget to provide help.  When the user moves the cursor inside a
widget to which a Balloon widget has been bound, a small pop-up window with a
descriptive message will be shown on the screen.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.ButtonBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">ButtonBox</code><a class="headerlink" href="#Tix.ButtonBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixButtonBox.htm">ButtonBox</a>
widget creates a box of buttons, such as is commonly used for <code class="docutils literal notranslate"><span class="pre">Ok</span> <span class="pre">Cancel</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.ComboBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">ComboBox</code><a class="headerlink" href="#Tix.ComboBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixComboBox.htm">ComboBox</a>
widget is similar to the combo box control in MS Windows. The user can select a
choice by either typing in the entry subwidget or selecting from the listbox
subwidget.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.Control">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Control</code><a class="headerlink" href="#Tix.Control" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixControl.htm">Control</a>
widget is also known as the <code class="xref py py-class docutils literal notranslate"><span class="pre">SpinBox</span></code> widget. The user can adjust the
value by pressing the two arrow buttons or by entering the value directly into
the entry. The new value will be checked against the user-defined upper and
lower limits.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.LabelEntry">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">LabelEntry</code><a class="headerlink" href="#Tix.LabelEntry" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelEntry.htm">LabelEntry</a>
widget packages an entry widget and a label into one mega widget. It can
be used to simplify the creation of “entry-form” type of interface.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.LabelFrame">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">LabelFrame</code><a class="headerlink" href="#Tix.LabelFrame" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixLabelFrame.htm">LabelFrame</a>
widget packages a frame widget and a label into one mega widget.  To create
widgets inside a LabelFrame widget, one creates the new widgets relative to the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">frame</span></code> subwidget and manage them inside the <code class="xref py py-attr docutils literal notranslate"><span class="pre">frame</span></code> subwidget.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.Meter">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Meter</code><a class="headerlink" href="#Tix.Meter" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixMeter.htm">Meter</a> widget
can be used to show the progress of a background job which may take a long time
to execute.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.OptionMenu">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">OptionMenu</code><a class="headerlink" href="#Tix.OptionMenu" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixOptionMenu.htm">OptionMenu</a>
creates a menu button of options.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.PopupMenu">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">PopupMenu</code><a class="headerlink" href="#Tix.PopupMenu" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPopupMenu.htm">PopupMenu</a>
widget can be used as a replacement of the <code class="docutils literal notranslate"><span class="pre">tk_popup</span></code> command. The advantage
of the <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> <a class="reference internal" href="#Tix.PopupMenu" title="Tix.PopupMenu"><code class="xref py py-class docutils literal notranslate"><span class="pre">PopupMenu</span></code></a> widget is it requires less application code
to manipulate.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.Select">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Select</code><a class="headerlink" href="#Tix.Select" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixSelect.htm">Select</a> widget
is a container of button subwidgets. It can be used to provide radio-box or
check-box style of selection options for the user.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.StdButtonBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">StdButtonBox</code><a class="headerlink" href="#Tix.StdButtonBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixStdButtonBox.htm">StdButtonBox</a>
widget is a group of standard buttons for Motif-like dialog boxes.</p>
</dd></dl>

</div>
<div class="section" id="file-selectors">
<h3>24.3.2.2. File Selectors<a class="headerlink" href="#file-selectors" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.DirList">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">DirList</code><a class="headerlink" href="#Tix.DirList" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirList.htm">DirList</a>
widget displays a list view of a directory, its previous directories and its
sub-directories. The user can choose one of the directories displayed in the
list or change to another directory.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.DirTree">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">DirTree</code><a class="headerlink" href="#Tix.DirTree" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirTree.htm">DirTree</a>
widget displays a tree view of a directory, its previous directories and its
sub-directories. The user can choose one of the directories displayed in the
list or change to another directory.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.DirSelectDialog">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">DirSelectDialog</code><a class="headerlink" href="#Tix.DirSelectDialog" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixDirSelectDialog.htm">DirSelectDialog</a>
widget presents the directories in the file system in a dialog window.  The user
can use this dialog window to navigate through the file system to select the
desired directory.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.DirSelectBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">DirSelectBox</code><a class="headerlink" href="#Tix.DirSelectBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#Tix.DirSelectBox" title="Tix.DirSelectBox"><code class="xref py py-class docutils literal notranslate"><span class="pre">DirSelectBox</span></code></a> is similar to the standard Motif(TM)
directory-selection box. It is generally used for the user to choose a
directory.  DirSelectBox stores the directories mostly recently selected into
a ComboBox widget so that they can be quickly selected again.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.ExFileSelectBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">ExFileSelectBox</code><a class="headerlink" href="#Tix.ExFileSelectBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixExFileSelectBox.htm">ExFileSelectBox</a>
widget is usually embedded in a tixExFileSelectDialog widget. It provides a
convenient method for the user to select files. The style of the
<a class="reference internal" href="#Tix.ExFileSelectBox" title="Tix.ExFileSelectBox"><code class="xref py py-class docutils literal notranslate"><span class="pre">ExFileSelectBox</span></code></a> widget is very similar to the standard file dialog on
MS Windows 3.1.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.FileSelectBox">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">FileSelectBox</code><a class="headerlink" href="#Tix.FileSelectBox" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileSelectBox.htm">FileSelectBox</a>
is similar to the standard Motif(TM) file-selection box. It is generally used
for the user to choose a file. FileSelectBox stores the files mostly recently
selected into a <a class="reference internal" href="#Tix.ComboBox" title="Tix.ComboBox"><code class="xref py py-class docutils literal notranslate"><span class="pre">ComboBox</span></code></a> widget so that they can be quickly selected
again.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.FileEntry">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">FileEntry</code><a class="headerlink" href="#Tix.FileEntry" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixFileEntry.htm">FileEntry</a>
widget can be used to input a filename. The user can type in the filename
manually. Alternatively, the user can press the button widget that sits next to
the entry, which will bring up a file selection dialog.</p>
</dd></dl>

</div>
<div class="section" id="hierarchical-listbox">
<h3>24.3.2.3. Hierarchical ListBox<a class="headerlink" href="#hierarchical-listbox" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.HList">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">HList</code><a class="headerlink" href="#Tix.HList" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixHList.htm">HList</a> widget
can be used to display any data that have a hierarchical structure, for example,
file system directory trees. The list entries are indented and connected by
branch lines according to their places in the hierarchy.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.CheckList">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">CheckList</code><a class="headerlink" href="#Tix.CheckList" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixCheckList.htm">CheckList</a>
widget displays a list of items to be selected by the user. CheckList acts
similarly to the Tk checkbutton or radiobutton widgets, except it is capable of
handling many more items than checkbuttons or radiobuttons.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.Tree">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Tree</code><a class="headerlink" href="#Tix.Tree" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTree.htm">Tree</a> widget
can be used to display hierarchical data in a tree form. The user can adjust the
view of the tree by opening or closing parts of the tree.</p>
</dd></dl>

</div>
<div class="section" id="tabular-listbox">
<h3>24.3.2.4. Tabular ListBox<a class="headerlink" href="#tabular-listbox" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.TList">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">TList</code><a class="headerlink" href="#Tix.TList" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixTList.htm">TList</a> widget
can be used to display data in a tabular format. The list entries of a
<a class="reference internal" href="#Tix.TList" title="Tix.TList"><code class="xref py py-class docutils literal notranslate"><span class="pre">TList</span></code></a> widget are similar to the entries in the Tk listbox widget.  The
main differences are (1) the <a class="reference internal" href="#Tix.TList" title="Tix.TList"><code class="xref py py-class docutils literal notranslate"><span class="pre">TList</span></code></a> widget can display the list entries
in a two dimensional format and (2) you can use graphical images as well as
multiple colors and fonts for the list entries.</p>
</dd></dl>

</div>
<div class="section" id="manager-widgets">
<h3>24.3.2.5. Manager Widgets<a class="headerlink" href="#manager-widgets" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.PanedWindow">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">PanedWindow</code><a class="headerlink" href="#Tix.PanedWindow" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixPanedWindow.htm">PanedWindow</a>
widget allows the user to interactively manipulate the sizes of several panes.
The panes can be arranged either vertically or horizontally.  The user changes
the sizes of the panes by dragging the resize handle between two panes.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.ListNoteBook">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">ListNoteBook</code><a class="headerlink" href="#Tix.ListNoteBook" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixListNoteBook.htm">ListNoteBook</a>
widget is very similar to the <code class="xref py py-class docutils literal notranslate"><span class="pre">TixNoteBook</span></code> widget: it can be used to
display many windows in a limited space using a notebook metaphor. The notebook
is divided into a stack of pages (windows). At one time only one of these pages
can be shown. The user can navigate through these pages by choosing the name of
the desired page in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">hlist</span></code> subwidget.</p>
</dd></dl>

<dl class="class">
<dt id="Tix.NoteBook">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">NoteBook</code><a class="headerlink" href="#Tix.NoteBook" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixNoteBook.htm">NoteBook</a>
widget can be used to display many windows in a limited space using a notebook
metaphor. The notebook is divided into a stack of pages. At one time only one of
these pages can be shown. The user can navigate through these pages by choosing
the visual “tabs” at the top of the NoteBook widget.</p>
</dd></dl>

</div>
<div class="section" id="image-types">
<h3>24.3.2.6. Image Types<a class="headerlink" href="#image-types" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> module adds:</p>
<ul class="simple">
<li><a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/pixmap.htm">pixmap</a>
capabilities to all <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> and <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> widgets to create color images
from XPM files.</li>
<li><a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/compound.htm">Compound</a> image
types can be used to create images that consists of multiple horizontal lines;
each line is composed of a series of items (texts, bitmaps, images or spaces)
arranged from left to right. For example, a compound image can be used to
display a bitmap and a text string simultaneously in a Tk <code class="xref py py-class docutils literal notranslate"><span class="pre">Button</span></code>
widget.</li>
</ul>
</div>
<div class="section" id="miscellaneous-widgets">
<h3>24.3.2.7. Miscellaneous Widgets<a class="headerlink" href="#miscellaneous-widgets" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="Tix.InputOnly">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">InputOnly</code><a class="headerlink" href="#Tix.InputOnly" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixInputOnly.htm">InputOnly</a>
widgets are to accept inputs from the user, which can be done with the <code class="docutils literal notranslate"><span class="pre">bind</span></code>
command (Unix only).</p>
</dd></dl>

</div>
<div class="section" id="form-geometry-manager">
<h3>24.3.2.8. Form Geometry Manager<a class="headerlink" href="#form-geometry-manager" title="Permalink to this headline">¶</a></h3>
<p>In addition, <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> augments <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> by providing:</p>
<dl class="class">
<dt id="Tix.Form">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">Form</code><a class="headerlink" href="#Tix.Form" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tixForm.htm">Form</a> geometry
manager based on attachment rules for all Tk widgets.</p>
</dd></dl>

</div>
</div>
<div class="section" id="tix-commands">
<h2>24.3.3. Tix Commands<a class="headerlink" href="#tix-commands" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="Tix.tixCommand">
<em class="property">class </em><code class="descclassname">Tix.</code><code class="descname">tixCommand</code><a class="headerlink" href="#Tix.tixCommand" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference external" href="http://tix.sourceforge.net/dist/current/man/html/TixCmd/tix.htm">tix commands</a> provide
access to miscellaneous elements of <a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a>’s internal state and the
<a class="reference internal" href="#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> application context.  Most of the information manipulated by these
methods pertains to the application as a whole, or to a screen or display,
rather than to a particular window.</p>
<p>To view the current settings, the common usage is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tix</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">Tix</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">root</span><span class="o">.</span><span class="n">tix_configure</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_configure">
<code class="descclassname">tixCommand.</code><code class="descname">tix_configure</code><span class="sig-paren">(</span><em>cnf=None **kw</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_configure" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the configuration options of the Tix application context. If no
option is specified, returns a dictionary all of the available options.  If
option is specified with no value, then the method returns a list describing the
one named option (this list will be identical to the corresponding sublist of
the value returned if no option is specified).  If one or more option-value
pairs are specified, then the method modifies the given option(s) to have the
given value(s); in this case the method returns an empty string. Option may be
any of the configuration options.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_cget">
<code class="descclassname">tixCommand.</code><code class="descname">tix_cget</code><span class="sig-paren">(</span><em>option</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_cget" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current value of the configuration option given by <em>option</em>. Option
may be any of the configuration options.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_getbitmap">
<code class="descclassname">tixCommand.</code><code class="descname">tix_getbitmap</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_getbitmap" title="Permalink to this definition">¶</a></dt>
<dd><p>Locates a bitmap file of the name <code class="docutils literal notranslate"><span class="pre">name.xpm</span></code> or <code class="docutils literal notranslate"><span class="pre">name</span></code> in one of the bitmap
directories (see the <a class="reference internal" href="#Tix.tixCommand.tix_addbitmapdir" title="Tix.tixCommand.tix_addbitmapdir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_addbitmapdir()</span></code></a> method).  By using
<a class="reference internal" href="#Tix.tixCommand.tix_getbitmap" title="Tix.tixCommand.tix_getbitmap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getbitmap()</span></code></a>, you can avoid hard coding the pathnames of the bitmap
files in your application. When successful, it returns the complete pathname of
the bitmap file, prefixed with the character <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>.  The returned value can be
used to configure the <code class="docutils literal notranslate"><span class="pre">bitmap</span></code> option of the Tk and Tix widgets.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_addbitmapdir">
<code class="descclassname">tixCommand.</code><code class="descname">tix_addbitmapdir</code><span class="sig-paren">(</span><em>directory</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_addbitmapdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Tix maintains a list of directories under which the <a class="reference internal" href="#Tix.tixCommand.tix_getimage" title="Tix.tixCommand.tix_getimage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getimage()</span></code></a> and
<a class="reference internal" href="#Tix.tixCommand.tix_getbitmap" title="Tix.tixCommand.tix_getbitmap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getbitmap()</span></code></a> methods will search for image files.  The standard bitmap
directory is <code class="file docutils literal notranslate"><span class="pre">$TIX_LIBRARY/bitmaps</span></code>. The <a class="reference internal" href="#Tix.tixCommand.tix_addbitmapdir" title="Tix.tixCommand.tix_addbitmapdir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_addbitmapdir()</span></code></a> method
adds <em>directory</em> into this list. By using this method, the image files of an
applications can also be located using the <a class="reference internal" href="#Tix.tixCommand.tix_getimage" title="Tix.tixCommand.tix_getimage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getimage()</span></code></a> or
<a class="reference internal" href="#Tix.tixCommand.tix_getbitmap" title="Tix.tixCommand.tix_getbitmap"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getbitmap()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_filedialog">
<code class="descclassname">tixCommand.</code><code class="descname">tix_filedialog</code><span class="sig-paren">(</span><span class="optional">[</span><em>dlgclass</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_filedialog" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the file selection dialog that may be shared among different calls from
this application.  This method will create a file selection dialog widget when
it is called the first time. This dialog will be returned by all subsequent
calls to <a class="reference internal" href="#Tix.tixCommand.tix_filedialog" title="Tix.tixCommand.tix_filedialog"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_filedialog()</span></code></a>.  An optional dlgclass parameter can be passed
as a string to specified what type of file selection dialog widget is desired.
Possible options are <code class="docutils literal notranslate"><span class="pre">tix</span></code>, <code class="docutils literal notranslate"><span class="pre">FileSelectDialog</span></code> or <code class="docutils literal notranslate"><span class="pre">tixExFileSelectDialog</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_getimage">
<code class="descclassname">tixCommand.</code><code class="descname">tix_getimage</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_getimage" title="Permalink to this definition">¶</a></dt>
<dd><p>Locates an image file of the name <code class="file docutils literal notranslate"><span class="pre">name.xpm</span></code>, <code class="file docutils literal notranslate"><span class="pre">name.xbm</span></code> or
<code class="file docutils literal notranslate"><span class="pre">name.ppm</span></code> in one of the bitmap directories (see the
<a class="reference internal" href="#Tix.tixCommand.tix_addbitmapdir" title="Tix.tixCommand.tix_addbitmapdir"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_addbitmapdir()</span></code></a> method above). If more than one file with the same name
(but different extensions) exist, then the image type is chosen according to the
depth of the X display: xbm images are chosen on monochrome displays and color
images are chosen on color displays. By using <a class="reference internal" href="#Tix.tixCommand.tix_getimage" title="Tix.tixCommand.tix_getimage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_getimage()</span></code></a>, you can
avoid hard coding the pathnames of the image files in your application. When
successful, this method returns the name of the newly created image, which can
be used to configure the <code class="docutils literal notranslate"><span class="pre">image</span></code> option of the Tk and Tix widgets.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_option_get">
<code class="descclassname">tixCommand.</code><code class="descname">tix_option_get</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_option_get" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the options maintained by the Tix scheme mechanism.</p>
</dd></dl>

<dl class="method">
<dt id="Tix.tixCommand.tix_resetoptions">
<code class="descclassname">tixCommand.</code><code class="descname">tix_resetoptions</code><span class="sig-paren">(</span><em>newScheme</em>, <em>newFontSet</em><span class="optional">[</span>, <em>newScmPrio</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#Tix.tixCommand.tix_resetoptions" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the scheme and fontset of the Tix application to <em>newScheme</em> and
<em>newFontSet</em>, respectively.  This affects only those widgets created after this
call.  Therefore, it is best to call the resetoptions method before the creation
of any widgets in a Tix application.</p>
<p>The optional parameter <em>newScmPrio</em> can be given to reset the priority level of
the Tk options set by the Tix schemes.</p>
<p>Because of the way Tk handles the X option database, after Tix has been has
imported and inited, it is not possible to reset the color schemes and font sets
using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_config()</span></code> method. Instead, the <a class="reference internal" href="#Tix.tixCommand.tix_resetoptions" title="Tix.tixCommand.tix_resetoptions"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tix_resetoptions()</span></code></a>
method must be used.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a><ul>
<li><a class="reference internal" href="#using-tix">24.3.1. Using Tix</a></li>
<li><a class="reference internal" href="#tix-widgets">24.3.2. Tix Widgets</a><ul>
<li><a class="reference internal" href="#basic-widgets">24.3.2.1. Basic Widgets</a></li>
<li><a class="reference internal" href="#file-selectors">24.3.2.2. File Selectors</a></li>
<li><a class="reference internal" href="#hierarchical-listbox">24.3.2.3. Hierarchical ListBox</a></li>
<li><a class="reference internal" href="#tabular-listbox">24.3.2.4. Tabular ListBox</a></li>
<li><a class="reference internal" href="#manager-widgets">24.3.2.5. Manager Widgets</a></li>
<li><a class="reference internal" href="#image-types">24.3.2.6. Image Types</a></li>
<li><a class="reference internal" href="#miscellaneous-widgets">24.3.2.7. Miscellaneous Widgets</a></li>
<li><a class="reference internal" href="#form-geometry-manager">24.3.2.8. Form Geometry Manager</a></li>
</ul>
</li>
<li><a class="reference internal" href="#tix-commands">24.3.3. Tix Commands</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="ttk.html"
                        title="previous chapter">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="scrolledtext.html"
                        title="next chapter">24.4. <code class="docutils literal notranslate"><span class="pre">ScrolledText</span></code> — Scrolled Text Widget</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tix.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="scrolledtext.html" title="24.4. ScrolledText — Scrolled Text Widget"
             >next</a> |</li>
        <li class="right" >
          <a href="ttk.html" title="24.2. ttk — Tk themed widgets"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�np�g�ghtml/library/tk.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24. Graphical User Interfaces with Tk &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.1. Tkinter — Python interface to Tcl/Tk" href="tkinter.html" />
    <link rel="prev" title="23.2. shlex — Simple lexical analysis" href="shlex.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tk.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tkinter.html" title="24.1. Tkinter — Python interface to Tcl/Tk"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="shlex.html" title="23.2. shlex — Simple lexical analysis"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="graphical-user-interfaces-with-tk">
<span id="tkinter"></span><h1>24. Graphical User Interfaces with Tk<a class="headerlink" href="#graphical-user-interfaces-with-tk" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Tk/Tcl has long been an integral part of Python.  It provides a robust and
platform independent windowing toolkit, that is available to Python programmers
using the <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module, and its extensions, the <a class="reference internal" href="tix.html#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> and
the <a class="reference internal" href="ttk.html#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> modules.</p>
<p>The <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module is a thin object-oriented layer on top of Tcl/Tk. To
use <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>, you don’t need to write Tcl code, but you will need to
consult the Tk documentation, and occasionally the Tcl documentation.
<a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> is a set of wrappers that implement the Tk widgets as Python
classes.  In addition, the internal module <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> provides a threadsafe
mechanism which allows Python and Tcl to interact.</p>
<p><a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>’s chief virtues are that it is fast, and that it usually comes
bundled with Python. Although its standard documentation is weak, good
material is available, which includes: references, tutorials, a book and
others. <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> is also famous for having an outdated look and feel,
which has been vastly improved in Tk 8.5. Nevertheless, there are many other
GUI libraries that you could be interested in. For more information about
alternatives, see the <a class="reference internal" href="othergui.html#other-gui-packages"><span class="std std-ref">Other Graphical User Interface Packages</span></a> section.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="tkinter.html">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a><ul>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#tkinter-modules">24.1.1. Tkinter Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#tkinter-life-preserver">24.1.2. Tkinter Life Preserver</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#how-to-use-this-section">24.1.2.1. How To Use This Section</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#a-simple-hello-world-program">24.1.2.2. A Simple Hello World Program</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#a-very-quick-look-at-tcl-tk">24.1.3. A (Very) Quick Look at Tcl/Tk</a></li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#mapping-basic-tk-into-tkinter">24.1.4. Mapping Basic Tk into Tkinter</a></li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#how-tk-and-tkinter-are-related">24.1.5. How Tk and Tkinter are Related</a></li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#handy-reference">24.1.6. Handy Reference</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#setting-options">24.1.6.1. Setting Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#the-packer">24.1.6.2. The Packer</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#packer-options">24.1.6.3. Packer Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#coupling-widget-variables">24.1.6.4. Coupling Widget Variables</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#the-window-manager">24.1.6.5. The Window Manager</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#tk-option-data-types">24.1.6.6. Tk Option Data Types</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#bindings-and-events">24.1.6.7. Bindings and Events</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#the-index-parameter">24.1.6.8. The index Parameter</a></li>
<li class="toctree-l3"><a class="reference internal" href="tkinter.html#images">24.1.6.9. Images</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tkinter.html#file-handlers">24.1.7. File Handlers</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="ttk.html">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a><ul>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#using-ttk">24.2.1. Using Ttk</a></li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#ttk-widgets">24.2.2. Ttk Widgets</a></li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#widget">24.2.3. Widget</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#standard-options">24.2.3.1. Standard Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#scrollable-widget-options">24.2.3.2. Scrollable Widget Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#label-options">24.2.3.3. Label Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#compatibility-options">24.2.3.4. Compatibility Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#widget-states">24.2.3.5. Widget States</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#ttk-widget">24.2.3.6. ttk.Widget</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#combobox">24.2.4. Combobox</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#options">24.2.4.1. Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#virtual-events">24.2.4.2. Virtual events</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#ttk-combobox">24.2.4.3. ttk.Combobox</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#notebook">24.2.5. Notebook</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id1">24.2.5.1. Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#tab-options">24.2.5.2. Tab Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#tab-identifiers">24.2.5.3. Tab Identifiers</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id2">24.2.5.4. Virtual Events</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#ttk-notebook">24.2.5.5. ttk.Notebook</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#progressbar">24.2.6. Progressbar</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id3">24.2.6.1. Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#ttk-progressbar">24.2.6.2. ttk.Progressbar</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#separator">24.2.7. Separator</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id4">24.2.7.1. Options</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#sizegrip">24.2.8. Sizegrip</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#platform-specific-notes">24.2.8.1. Platform-specific notes</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#bugs">24.2.8.2. Bugs</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#treeview">24.2.9. Treeview</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id5">24.2.9.1. Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#item-options">24.2.9.2. Item Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#tag-options">24.2.9.3. Tag Options</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#column-identifiers">24.2.9.4. Column Identifiers</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#id6">24.2.9.5. Virtual Events</a></li>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#ttk-treeview">24.2.9.6. ttk.Treeview</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="ttk.html#ttk-styling">24.2.10. Ttk Styling</a><ul>
<li class="toctree-l3"><a class="reference internal" href="ttk.html#layouts">24.2.10.1. Layouts</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tix.html">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a><ul>
<li class="toctree-l2"><a class="reference internal" href="tix.html#using-tix">24.3.1. Using Tix</a></li>
<li class="toctree-l2"><a class="reference internal" href="tix.html#tix-widgets">24.3.2. Tix Widgets</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tix.html#basic-widgets">24.3.2.1. Basic Widgets</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#file-selectors">24.3.2.2. File Selectors</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#hierarchical-listbox">24.3.2.3. Hierarchical ListBox</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#tabular-listbox">24.3.2.4. Tabular ListBox</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#manager-widgets">24.3.2.5. Manager Widgets</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#image-types">24.3.2.6. Image Types</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#miscellaneous-widgets">24.3.2.7. Miscellaneous Widgets</a></li>
<li class="toctree-l3"><a class="reference internal" href="tix.html#form-geometry-manager">24.3.2.8. Form Geometry Manager</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tix.html#tix-commands">24.3.3. Tix Commands</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="scrolledtext.html">24.4. <code class="docutils literal notranslate"><span class="pre">ScrolledText</span></code> — Scrolled Text Widget</a></li>
<li class="toctree-l1"><a class="reference internal" href="turtle.html">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a><ul>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#introduction">24.5.1. Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#overview-over-available-turtle-and-screen-methods">24.5.2. Overview over available Turtle and Screen methods</a><ul>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#turtle-methods">24.5.2.1. Turtle methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#methods-of-turtlescreen-screen">24.5.2.2. Methods of TurtleScreen/Screen</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#methods-of-rawturtle-turtle-and-corresponding-functions">24.5.3. Methods of RawTurtle/Turtle and corresponding functions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#turtle-motion">24.5.3.1. Turtle motion</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#tell-turtle-s-state">24.5.3.2. Tell Turtle’s state</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#settings-for-measurement">24.5.3.3. Settings for measurement</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#pen-control">24.5.3.4. Pen control</a><ul>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#drawing-state">24.5.3.4.1. Drawing state</a></li>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#color-control">24.5.3.4.2. Color control</a></li>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#filling">24.5.3.4.3. Filling</a></li>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#more-drawing-control">24.5.3.4.4. More drawing control</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#turtle-state">24.5.3.5. Turtle state</a><ul>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#visibility">24.5.3.5.1. Visibility</a></li>
<li class="toctree-l4"><a class="reference internal" href="turtle.html#appearance">24.5.3.5.2. Appearance</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#using-events">24.5.3.6. Using events</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#special-turtle-methods">24.5.3.7. Special Turtle methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#excursus-about-the-use-of-compound-shapes">24.5.3.8. Excursus about the use of compound shapes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#methods-of-turtlescreen-screen-and-corresponding-functions">24.5.4. Methods of TurtleScreen/Screen and corresponding functions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#window-control">24.5.4.1. Window control</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#animation-control">24.5.4.2. Animation control</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#using-screen-events">24.5.4.3. Using screen events</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#settings-and-special-methods">24.5.4.4. Settings and special methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#methods-specific-to-screen-not-inherited-from-turtlescreen">24.5.4.5. Methods specific to Screen, not inherited from TurtleScreen</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#the-public-classes-of-the-module-turtle">24.5.5. The public classes of the module <code class="docutils literal notranslate"><span class="pre">turtle</span></code></a></li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#help-and-configuration">24.5.6. Help and configuration</a><ul>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#how-to-use-help">24.5.6.1. How to use help</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#translation-of-docstrings-into-different-languages">24.5.6.2. Translation of docstrings into different languages</a></li>
<li class="toctree-l3"><a class="reference internal" href="turtle.html#how-to-configure-screen-and-turtles">24.5.6.3. How to configure Screen and Turtles</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="turtle.html#demo-scripts">24.5.7. Demo scripts</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="idle.html">24.6. IDLE</a><ul>
<li class="toctree-l2"><a class="reference internal" href="idle.html#menus">24.6.1. Menus</a><ul>
<li class="toctree-l3"><a class="reference internal" href="idle.html#file-menu-shell-and-editor">24.6.1.1. File menu (Shell and Editor)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#edit-menu-shell-and-editor">24.6.1.2. Edit menu (Shell and Editor)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#format-menu-editor-window-only">24.6.1.3. Format menu (Editor window only)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#run-menu-editor-window-only">24.6.1.4. Run menu (Editor window only)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#shell-menu-shell-window-only">24.6.1.5. Shell menu (Shell window only)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#debug-menu-shell-window-only">24.6.1.6. Debug menu (Shell window only)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#options-menu-shell-and-editor">24.6.1.7. Options menu (Shell and Editor)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#window-menu-shell-and-editor">24.6.1.8. Window menu (Shell and Editor)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#help-menu-shell-and-editor">24.6.1.9. Help menu (Shell and Editor)</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#context-menus">24.6.1.10. Context Menus</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="idle.html#editing-and-navigation">24.6.2. Editing and navigation</a><ul>
<li class="toctree-l3"><a class="reference internal" href="idle.html#automatic-indentation">24.6.2.1. Automatic indentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#completions">24.6.2.2. Completions</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#calltips">24.6.2.3. Calltips</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#python-shell-window">24.6.2.4. Python Shell window</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#text-colors">24.6.2.5. Text colors</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="idle.html#startup-and-code-execution">24.6.3. Startup and code execution</a><ul>
<li class="toctree-l3"><a class="reference internal" href="idle.html#command-line-usage">24.6.3.1. Command line usage</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#idle-console-differences">24.6.3.2. IDLE-console differences</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#running-without-a-subprocess">24.6.3.3. Running without a subprocess</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="idle.html#help-and-preferences">24.6.4. Help and preferences</a><ul>
<li class="toctree-l3"><a class="reference internal" href="idle.html#additional-help-sources">24.6.4.1. Additional help sources</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#setting-preferences">24.6.4.2. Setting preferences</a></li>
<li class="toctree-l3"><a class="reference internal" href="idle.html#extensions">24.6.4.3. Extensions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="othergui.html">24.7. Other Graphical User Interface Packages</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="shlex.html"
                        title="previous chapter">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tkinter.html"
                        title="next chapter">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tk.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tkinter.html" title="24.1. Tkinter — Python interface to Tcl/Tk"
             >next</a> |</li>
        <li class="right" >
          <a href="shlex.html" title="23.2. shlex — Simple lexical analysis"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�^�\I\Ihtml/library/tkinter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.1. Tkinter — Python interface to Tcl/Tk &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.2. ttk — Tk themed widgets" href="ttk.html" />
    <link rel="prev" title="24. Graphical User Interfaces with Tk" href="tk.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tkinter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ttk.html" title="24.2. ttk — Tk themed widgets"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tk.html" title="24. Graphical User Interfaces with Tk"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-Tkinter">
<span id="tkinter-python-interface-to-tcl-tk"></span><h1>24.1. <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> — Python interface to Tcl/Tk<a class="headerlink" href="#module-Tkinter" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module (“Tk interface”) is the standard Python interface to
the Tk GUI toolkit.  Both Tk and <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> are available on most Unix
platforms, as well as on Windows systems.  (Tk itself is not part of Python; it
is maintained at ActiveState.)</p>
<p>Running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">Tkinter</span></code> from the command line should open a window
demonstrating a simple Tk interface, letting you know that <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> is
properly installed on your system, and also showing what version of Tcl/Tk is
installed, so you can read the Tcl/Tk documentation specific to that version.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">tkinter</span></code> in Python 3.  The
<a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting your
sources to Python 3.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>Tkinter documentation:</p>
<dl class="docutils">
<dt><a class="reference external" href="https://wiki.python.org/moin/TkInter">Python Tkinter Resources</a></dt>
<dd>The Python Tkinter Topic Guide provides a great deal of information on using Tk
from Python and links to other sources of information on Tk.</dd>
<dt><a class="reference external" href="http://www.tkdocs.com/">TKDocs</a></dt>
<dd>Extensive tutorial plus friendlier widget pages for some of the widgets.</dd>
<dt><a class="reference external" href="https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html">Tkinter reference: a GUI for Python</a></dt>
<dd>On-line reference material.</dd>
<dt><a class="reference external" href="http://effbot.org/tkinterbook/">Tkinter docs from effbot</a></dt>
<dd>Online reference for tkinter supported by effbot.org.</dd>
<dt><a class="reference external" href="http://learning-python.com/about-pp4e.html">Programming Python</a></dt>
<dd>Book by Mark Lutz, has excellent coverage of Tkinter.</dd>
<dt><a class="reference external" href="https://www.amazon.com/Modern-Tkinter-Python-Developers-ebook/dp/B0071QDNLO/">Modern Tkinter for Busy Python Developers</a></dt>
<dd>Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.</dd>
<dt><a class="reference external" href="https://www.manning.com/books/python-and-tkinter-programming">Python and Tkinter Programming</a></dt>
<dd>Book by John Grayson (ISBN 1-884777-81-3).</dd>
</dl>
<p>Tcl/Tk documentation:</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.tcl.tk/man/tcl8.6/TkCmd/contents.htm">Tk commands</a></dt>
<dd>Most commands are available as <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter.ttk</span></code> classes.
Change ‘8.6’ to match the version of your Tcl/Tk installation.</dd>
<dt><a class="reference external" href="https://www.tcl.tk/doc/">Tcl/Tk recent man pages</a></dt>
<dd>Recent Tcl/Tk manuals on www.tcl.tk.</dd>
<dt><a class="reference external" href="http://tcl.activestate.com/">ActiveState Tcl Home Page</a></dt>
<dd>The Tk/Tcl development is largely taking place at ActiveState.</dd>
<dt><a class="reference external" href="https://www.amazon.com/exec/obidos/ASIN/020163337X">Tcl and the Tk Toolkit</a></dt>
<dd>Book by John Ousterhout, the inventor of Tcl.</dd>
<dt><a class="reference external" href="http://www.beedub.com/book/">Practical Programming in Tcl and Tk</a></dt>
<dd>Brent Welch’s encyclopedic book.</dd>
</dl>
</div>
<div class="section" id="tkinter-modules">
<h2>24.1.1. Tkinter Modules<a class="headerlink" href="#tkinter-modules" title="Permalink to this headline">¶</a></h2>
<p>Most of the time, the <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module is all you really need, but a number
of additional modules are available as well.  The Tk interface is located in a
binary module named <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code>. This module contains the low-level
interface to Tk, and should never be used directly by application programmers.
It is usually a shared library (or DLL), but might in some cases be statically
linked with the Python interpreter.</p>
<p>In addition to the Tk interface module, <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> includes a number of
Python modules. The two most important modules are the <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module
itself, and a module called <code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkconstants</span></code>. The former automatically imports
the latter, so to use Tkinter, all you need to do is to import one module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tkinter</span>
</pre></div>
</div>
<p>Or, more often:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Tkinter</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<dl class="class">
<dt id="Tkinter.Tk">
<em class="property">class </em><code class="descclassname">Tkinter.</code><code class="descname">Tk</code><span class="sig-paren">(</span><em>screenName=None</em>, <em>baseName=None</em>, <em>className='Tk'</em>, <em>useTk=1</em><span class="sig-paren">)</span><a class="headerlink" href="#Tkinter.Tk" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#Tkinter.Tk" title="Tkinter.Tk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tk</span></code></a> class is instantiated without arguments. This creates a toplevel
widget of Tk which usually is the main window of an application. Each instance
has its own associated Tcl interpreter.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>The <em>useTk</em> parameter was added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="Tkinter.Tcl">
<code class="descclassname">Tkinter.</code><code class="descname">Tcl</code><span class="sig-paren">(</span><em>screenName=None</em>, <em>baseName=None</em>, <em>className='Tk'</em>, <em>useTk=0</em><span class="sig-paren">)</span><a class="headerlink" href="#Tkinter.Tcl" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#Tkinter.Tcl" title="Tkinter.Tcl"><code class="xref py py-func docutils literal notranslate"><span class="pre">Tcl()</span></code></a> function is a factory function which creates an object much like
that created by the <a class="reference internal" href="#Tkinter.Tk" title="Tkinter.Tk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tk</span></code></a> class, except that it does not initialize the Tk
subsystem.  This is most often useful when driving the Tcl interpreter in an
environment where one doesn’t want to create extraneous toplevel windows, or
where one cannot (such as Unix/Linux systems without an X server).  An object
created by the <a class="reference internal" href="#Tkinter.Tcl" title="Tkinter.Tcl"><code class="xref py py-func docutils literal notranslate"><span class="pre">Tcl()</span></code></a> object can have a Toplevel window created (and the Tk
subsystem initialized) by calling its <code class="xref py py-meth docutils literal notranslate"><span class="pre">loadtk()</span></code> method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<p>Other modules that provide Tk support include:</p>
<dl class="docutils">
<dt><a class="reference internal" href="scrolledtext.html#module-ScrolledText" title="ScrolledText: Text widget with a vertical scroll bar. (Tk)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ScrolledText</span></code></a></dt>
<dd>Text widget with a vertical scroll bar built in.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkColorChooser</span></code></dt>
<dd>Dialog to let the user choose a color.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkCommonDialog</span></code></dt>
<dd>Base class for the dialogs defined in the other modules listed here.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkFileDialog</span></code></dt>
<dd>Common dialogs to allow the user to specify a file to open or save.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkFont</span></code></dt>
<dd>Utilities to help work with fonts.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkMessageBox</span></code></dt>
<dd>Access to standard Tk dialog boxes.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">tkSimpleDialog</span></code></dt>
<dd>Basic dialogs and convenience functions.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkdnd</span></code></dt>
<dd>Drag-and-drop support for <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>. This is experimental and should become
deprecated when it is replaced  with the Tk DND.</dd>
<dt><a class="reference internal" href="turtle.html#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a></dt>
<dd>Turtle graphics in a Tk window.</dd>
</dl>
<p>These have been renamed as well in Python 3; they were all made submodules of
the new <code class="docutils literal notranslate"><span class="pre">tkinter</span></code> package.</p>
</div>
<div class="section" id="tkinter-life-preserver">
<h2>24.1.2. Tkinter Life Preserver<a class="headerlink" href="#tkinter-life-preserver" title="Permalink to this headline">¶</a></h2>
<p>This section is not designed to be an exhaustive tutorial on either Tk or
Tkinter.  Rather, it is intended as a stop gap, providing some introductory
orientation on the system.</p>
<p>Credits:</p>
<ul class="simple">
<li>Tkinter was written by Steen Lumholt and Guido van Rossum.</li>
<li>Tk was written by John Ousterhout while at Berkeley.</li>
<li>This Life Preserver was written by Matt Conway at the University of Virginia.</li>
<li>The html rendering, and some liberal editing, was produced from a FrameMaker
version by Ken Manheimer.</li>
<li>Fredrik Lundh elaborated and revised the class interface descriptions, to get
them current with Tk 4.2.</li>
<li>Mike Clarkson converted the documentation to LaTeX, and compiled the  User
Interface chapter of the reference manual.</li>
</ul>
<div class="section" id="how-to-use-this-section">
<h3>24.1.2.1. How To Use This Section<a class="headerlink" href="#how-to-use-this-section" title="Permalink to this headline">¶</a></h3>
<p>This section is designed in two parts: the first half (roughly) covers
background material, while the second half can be taken to the keyboard as a
handy reference.</p>
<p>When trying to answer questions of the form “how do I do blah”, it is often best
to find out how to do “blah” in straight Tk, and then convert this back into the
corresponding <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> call. Python programmers can often guess at the
correct Python command by looking at the Tk documentation. This means that in
order to use Tkinter, you will have to know a little bit about Tk. This document
can’t fulfill that role, so the best we can do is point you to the best
documentation that exists. Here are some hints:</p>
<ul class="simple">
<li>The authors strongly suggest getting a copy of the Tk man pages. Specifically,
the man pages in the <code class="docutils literal notranslate"><span class="pre">mann</span></code> directory are most useful. The <code class="docutils literal notranslate"><span class="pre">man3</span></code> man pages
describe the C interface to the Tk library and thus are not especially helpful
for script writers.</li>
<li>Addison-Wesley publishes a book called Tcl and the Tk Toolkit by John
Ousterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk for
the novice.  The book is not exhaustive, and for many details it defers to the
man pages.</li>
<li><code class="file docutils literal notranslate"><span class="pre">Tkinter.py</span></code> is a last resort for most, but can be a good place to go
when nothing else makes sense.</li>
</ul>
</div>
<div class="section" id="a-simple-hello-world-program">
<h3>24.1.2.2. A Simple Hello World Program<a class="headerlink" href="#a-simple-hello-world-program" title="Permalink to this headline">¶</a></h3>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Tkinter</span> <span class="k">import</span> <span class="o">*</span>

<span class="k">class</span> <span class="nc">Application</span><span class="p">(</span><span class="n">Frame</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">say_hi</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;hi there, everyone!&quot;</span>

    <span class="k">def</span> <span class="nf">createWidgets</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">QUIT</span> <span class="o">=</span> <span class="n">Button</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">QUIT</span><span class="p">[</span><span class="s2">&quot;text&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;QUIT&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">QUIT</span><span class="p">[</span><span class="s2">&quot;fg&quot;</span><span class="p">]</span>   <span class="o">=</span> <span class="s2">&quot;red&quot;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">QUIT</span><span class="p">[</span><span class="s2">&quot;command&quot;</span><span class="p">]</span> <span class="o">=</span>  <span class="bp">self</span><span class="o">.</span><span class="n">quit</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">QUIT</span><span class="o">.</span><span class="n">pack</span><span class="p">({</span><span class="s2">&quot;side&quot;</span><span class="p">:</span> <span class="s2">&quot;left&quot;</span><span class="p">})</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">hi_there</span> <span class="o">=</span> <span class="n">Button</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">hi_there</span><span class="p">[</span><span class="s2">&quot;text&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;Hello&quot;</span><span class="p">,</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">hi_there</span><span class="p">[</span><span class="s2">&quot;command&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">say_hi</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">hi_there</span><span class="o">.</span><span class="n">pack</span><span class="p">({</span><span class="s2">&quot;side&quot;</span><span class="p">:</span> <span class="s2">&quot;left&quot;</span><span class="p">})</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">Frame</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">createWidgets</span><span class="p">()</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">Tk</span><span class="p">()</span>
<span class="n">app</span> <span class="o">=</span> <span class="n">Application</span><span class="p">(</span><span class="n">master</span><span class="o">=</span><span class="n">root</span><span class="p">)</span>
<span class="n">app</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
<span class="n">root</span><span class="o">.</span><span class="n">destroy</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="a-very-quick-look-at-tcl-tk">
<h2>24.1.3. A (Very) Quick Look at Tcl/Tk<a class="headerlink" href="#a-very-quick-look-at-tcl-tk" title="Permalink to this headline">¶</a></h2>
<p>The class hierarchy looks complicated, but in actual practice, application
programmers almost always refer to the classes at the very bottom of the
hierarchy.</p>
<p>Notes:</p>
<ul class="simple">
<li>These classes are provided for the purposes of organizing certain functions
under one namespace. They aren’t meant to be instantiated independently.</li>
<li>The <a class="reference internal" href="#Tkinter.Tk" title="Tkinter.Tk"><code class="xref py py-class docutils literal notranslate"><span class="pre">Tk</span></code></a> class is meant to be instantiated only once in an application.
Application programmers need not instantiate one explicitly, the system creates
one whenever any of the other classes are instantiated.</li>
<li>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Widget</span></code> class is not meant to be instantiated, it is meant only
for subclassing to make “real” widgets (in C++, this is called an ‘abstract
class’).</li>
</ul>
<p>To make use of this reference material, there will be times when you will need
to know how to read short passages of Tk and how to identify the various parts
of a Tk command.   (See section <a class="reference internal" href="#tkinter-basic-mapping"><span class="std std-ref">Mapping Basic Tk into Tkinter</span></a> for the
<a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> equivalents of what’s below.)</p>
<p>Tk scripts are Tcl programs.  Like all Tcl programs, Tk scripts are just lists
of tokens separated by spaces.  A Tk widget is just its <em>class</em>, the <em>options</em>
that help configure it, and the <em>actions</em> that make it do useful things.</p>
<p>To make a widget in Tk, the command is always of the form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">classCommand</span> <span class="n">newPathname</span> <span class="n">options</span>
</pre></div>
</div>
<dl class="docutils">
<dt><em>classCommand</em></dt>
<dd>denotes which kind of widget to make (a button, a label, a menu…)</dd>
<dt><em>newPathname</em></dt>
<dd>is the new name for this widget.  All names in Tk must be unique.  To help
enforce this, widgets in Tk are named with <em>pathnames</em>, just like files in a
file system.  The top level widget, the <em>root</em>, is called <code class="docutils literal notranslate"><span class="pre">.</span></code> (period) and
children are delimited by more periods.  For example,
<code class="docutils literal notranslate"><span class="pre">.myApp.controlPanel.okButton</span></code> might be the name of a widget.</dd>
<dt><em>options</em></dt>
<dd>configure the widget’s appearance and in some cases, its behavior.  The options
come in the form of a list of flags and values. Flags are preceded by a ‘-‘,
like Unix shell command flags, and values are put in quotes if they are more
than one word.</dd>
</dl>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">button</span>   <span class="o">.</span><span class="n">fred</span>   <span class="o">-</span><span class="n">fg</span> <span class="n">red</span> <span class="o">-</span><span class="n">text</span> <span class="s2">&quot;hi there&quot;</span>
   <span class="o">^</span>       <span class="o">^</span>     \<span class="n">_____________________</span><span class="o">/</span>
   <span class="o">|</span>       <span class="o">|</span>                <span class="o">|</span>
 <span class="k">class</span>    <span class="nc">new</span>            <span class="n">options</span>
<span class="n">command</span>  <span class="n">widget</span>  <span class="p">(</span><span class="o">-</span><span class="n">opt</span> <span class="n">val</span> <span class="o">-</span><span class="n">opt</span> <span class="n">val</span> <span class="o">...</span><span class="p">)</span>
</pre></div>
</div>
<p>Once created, the pathname to the widget becomes a new command.  This new
<em>widget command</em> is the programmer’s handle for getting the new widget to
perform some <em>action</em>.  In C, you’d express this as someAction(fred,
someOptions), in C++, you would express this as fred.someAction(someOptions),
and in Tk, you say:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">.</span><span class="n">fred</span> <span class="n">someAction</span> <span class="n">someOptions</span>
</pre></div>
</div>
<p>Note that the object name, <code class="docutils literal notranslate"><span class="pre">.fred</span></code>, starts with a dot.</p>
<p>As you’d expect, the legal values for <em>someAction</em> will depend on the widget’s
class: <code class="docutils literal notranslate"><span class="pre">.fred</span> <span class="pre">disable</span></code> works if fred is a button (fred gets greyed out), but
does not work if fred is a label (disabling of labels is not supported in Tk).</p>
<p>The legal values of <em>someOptions</em> is action dependent.  Some actions, like
<code class="docutils literal notranslate"><span class="pre">disable</span></code>, require no arguments, others, like a text-entry box’s <code class="docutils literal notranslate"><span class="pre">delete</span></code>
command, would need arguments to specify what range of text to delete.</p>
</div>
<div class="section" id="mapping-basic-tk-into-tkinter">
<span id="tkinter-basic-mapping"></span><h2>24.1.4. Mapping Basic Tk into Tkinter<a class="headerlink" href="#mapping-basic-tk-into-tkinter" title="Permalink to this headline">¶</a></h2>
<p>Class commands in Tk correspond to class constructors in Tkinter.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">button</span> <span class="o">.</span><span class="n">fred</span>                <span class="o">=====&gt;</span>  <span class="n">fred</span> <span class="o">=</span> <span class="n">Button</span><span class="p">()</span>
</pre></div>
</div>
<p>The master of an object is implicit in the new name given to it at creation
time.  In Tkinter, masters are specified explicitly.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">button</span> <span class="o">.</span><span class="n">panel</span><span class="o">.</span><span class="n">fred</span>          <span class="o">=====&gt;</span>  <span class="n">fred</span> <span class="o">=</span> <span class="n">Button</span><span class="p">(</span><span class="n">panel</span><span class="p">)</span>
</pre></div>
</div>
<p>The configuration options in Tk are given in lists of hyphened tags followed by
values.  In Tkinter, options are specified as keyword-arguments in the instance
constructor, and keyword-args for configure calls or as instance indices, in
dictionary style, for established instances.  See section
<a class="reference internal" href="#tkinter-setting-options"><span class="std std-ref">Setting Options</span></a> on setting options.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">button</span> <span class="o">.</span><span class="n">fred</span> <span class="o">-</span><span class="n">fg</span> <span class="n">red</span>        <span class="o">=====&gt;</span>  <span class="n">fred</span> <span class="o">=</span> <span class="n">Button</span><span class="p">(</span><span class="n">panel</span><span class="p">,</span> <span class="n">fg</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span><span class="p">)</span>
<span class="o">.</span><span class="n">fred</span> <span class="n">configure</span> <span class="o">-</span><span class="n">fg</span> <span class="n">red</span>     <span class="o">=====&gt;</span>  <span class="n">fred</span><span class="p">[</span><span class="s2">&quot;fg&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">red</span>
                            <span class="n">OR</span> <span class="o">==&gt;</span>  <span class="n">fred</span><span class="o">.</span><span class="n">config</span><span class="p">(</span><span class="n">fg</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>In Tk, to perform an action on a widget, use the widget name as a command, and
follow it with an action name, possibly with arguments (options).  In Tkinter,
you call methods on the class instance to invoke actions on the widget.  The
actions (methods) that a given widget can perform are listed in the Tkinter.py
module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">.</span><span class="n">fred</span> <span class="n">invoke</span>                <span class="o">=====&gt;</span>  <span class="n">fred</span><span class="o">.</span><span class="n">invoke</span><span class="p">()</span>
</pre></div>
</div>
<p>To give a widget to the packer (geometry manager), you call pack with optional
arguments.  In Tkinter, the Pack class holds all this functionality, and the
various forms of the pack command are implemented as methods.  All widgets in
<a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> are subclassed from the Packer, and so inherit all the packing
methods. See the <a class="reference internal" href="tix.html#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> module documentation for additional information on
the Form geometry manager.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pack</span> <span class="o">.</span><span class="n">fred</span> <span class="o">-</span><span class="n">side</span> <span class="n">left</span>       <span class="o">=====&gt;</span>  <span class="n">fred</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="n">side</span> <span class="o">=</span> <span class="s2">&quot;left&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="how-tk-and-tkinter-are-related">
<h2>24.1.5. How Tk and Tkinter are Related<a class="headerlink" href="#how-tk-and-tkinter-are-related" title="Permalink to this headline">¶</a></h2>
<p>From the top down:</p>
<dl class="docutils">
<dt>Your App Here (Python)</dt>
<dd>A Python application makes a <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> call.</dd>
<dt>Tkinter (Python Module)</dt>
<dd>This call (say, for example, creating a button widget), is implemented in the
<em>Tkinter</em> module, which is written in Python.  This Python function will parse
the commands and the arguments and convert them into a form that makes them look
as if they had come from a Tk script instead of a Python script.</dd>
<dt>tkinter (C)</dt>
<dd>These commands and their arguments will be passed to a C function in the
<em>tkinter</em> - note the lowercase - extension module.</dd>
<dt>Tk Widgets (C and Tcl)</dt>
<dd>This C function is able to make calls into other C modules, including the C
functions that make up the Tk library.  Tk is implemented in C and some Tcl.
The Tcl part of the Tk widgets is used to bind certain default behaviors to
widgets, and is executed once at the point where the Python <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>
module is imported. (The user never sees this stage).</dd>
<dt>Tk (C)</dt>
<dd>The Tk part of the Tk Widgets implement the final mapping to …</dd>
<dt>Xlib (C)</dt>
<dd>the Xlib library to draw graphics on the screen.</dd>
</dl>
</div>
<div class="section" id="handy-reference">
<h2>24.1.6. Handy Reference<a class="headerlink" href="#handy-reference" title="Permalink to this headline">¶</a></h2>
<div class="section" id="setting-options">
<span id="tkinter-setting-options"></span><h3>24.1.6.1. Setting Options<a class="headerlink" href="#setting-options" title="Permalink to this headline">¶</a></h3>
<p>Options control things like the color and border width of a widget. Options can
be set in three ways:</p>
<dl class="docutils">
<dt>At object creation time, using keyword arguments</dt>
<dd><div class="first last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fred</span> <span class="o">=</span> <span class="n">Button</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fg</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="n">bg</span> <span class="o">=</span> <span class="s2">&quot;blue&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd>
<dt>After object creation, treating the option name like a dictionary index</dt>
<dd><div class="first last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fred</span><span class="p">[</span><span class="s2">&quot;fg&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span>
<span class="n">fred</span><span class="p">[</span><span class="s2">&quot;bg&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;blue&quot;</span>
</pre></div>
</div>
</dd>
<dt>Use the config() method to update multiple attrs subsequent to object creation</dt>
<dd><div class="first last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fred</span><span class="o">.</span><span class="n">config</span><span class="p">(</span><span class="n">fg</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="n">bg</span> <span class="o">=</span> <span class="s2">&quot;blue&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd>
</dl>
<p>For a complete explanation of a given option and its behavior, see the Tk man
pages for the widget in question.</p>
<p>Note that the man pages list “STANDARD OPTIONS” and “WIDGET SPECIFIC OPTIONS”
for each widget.  The former is a list of options that are common to many
widgets, the latter are the options that are idiosyncratic to that particular
widget.  The Standard Options are documented on the <em class="manpage">options(3)</em> man
page.</p>
<p>No distinction between standard and widget-specific options is made in this
document.  Some options don’t apply to some kinds of widgets. Whether a given
widget responds to a particular option depends on the class of the widget;
buttons have a <code class="docutils literal notranslate"><span class="pre">command</span></code> option, labels do not.</p>
<p>The options supported by a given widget are listed in that widget’s man page, or
can be queried at runtime by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">config()</span></code> method without
arguments, or by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code> method on that widget.  The return
value of these calls is a dictionary whose key is the name of the option as a
string (for example, <code class="docutils literal notranslate"><span class="pre">'relief'</span></code>) and whose values are 5-tuples.</p>
<p>Some options, like <code class="docutils literal notranslate"><span class="pre">bg</span></code> are synonyms for common options with long names
(<code class="docutils literal notranslate"><span class="pre">bg</span></code> is shorthand for “background”). Passing the <code class="docutils literal notranslate"><span class="pre">config()</span></code> method the name
of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed
back will contain the name of the synonym and the “real” option (such as
<code class="docutils literal notranslate"><span class="pre">('bg',</span> <span class="pre">'background')</span></code>).</p>
<table border="1" class="docutils">
<colgroup>
<col width="13%" />
<col width="61%" />
<col width="26%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Meaning</th>
<th class="head">Example</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0</td>
<td>option name</td>
<td><code class="docutils literal notranslate"><span class="pre">'relief'</span></code></td>
</tr>
<tr class="row-odd"><td>1</td>
<td>option name for database lookup</td>
<td><code class="docutils literal notranslate"><span class="pre">'relief'</span></code></td>
</tr>
<tr class="row-even"><td>2</td>
<td>option class for database
lookup</td>
<td><code class="docutils literal notranslate"><span class="pre">'Relief'</span></code></td>
</tr>
<tr class="row-odd"><td>3</td>
<td>default value</td>
<td><code class="docutils literal notranslate"><span class="pre">'raised'</span></code></td>
</tr>
<tr class="row-even"><td>4</td>
<td>current value</td>
<td><code class="docutils literal notranslate"><span class="pre">'groove'</span></code></td>
</tr>
</tbody>
</table>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">fred</span><span class="o">.</span><span class="n">config</span><span class="p">()</span>
<span class="go">{&#39;relief&#39;: (&#39;relief&#39;, &#39;relief&#39;, &#39;Relief&#39;, &#39;raised&#39;, &#39;groove&#39;)}</span>
</pre></div>
</div>
<p>Of course, the dictionary printed will include all the options available and
their values.  This is meant only as an example.</p>
</div>
<div class="section" id="the-packer">
<h3>24.1.6.2. The Packer<a class="headerlink" href="#the-packer" title="Permalink to this headline">¶</a></h3>
<p id="index-0">The packer is one of Tk’s geometry-management mechanisms.    Geometry managers
are used to specify the relative positioning of the positioning of widgets
within their container - their mutual <em>master</em>.  In contrast to the more
cumbersome <em>placer</em> (which is used less commonly, and we do not cover here), the
packer takes qualitative relationship specification - <em>above</em>, <em>to the left of</em>,
<em>filling</em>, etc - and works everything out to determine the exact placement
coordinates for you.</p>
<p>The size of any <em>master</em> widget is determined by the size of the “slave widgets”
inside.  The packer is used to control where slave widgets appear inside the
master into which they are packed.  You can pack widgets into frames, and frames
into other frames, in order to achieve the kind of layout you desire.
Additionally, the arrangement is dynamically adjusted to accommodate incremental
changes to the configuration, once it is packed.</p>
<p>Note that widgets do not appear until they have had their geometry specified
with a geometry manager.  It’s a common early mistake to leave out the geometry
specification, and then be surprised when the widget is created but nothing
appears.  A widget will appear only after it has had, for example, the packer’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">pack()</span></code> method applied to it.</p>
<p>The pack() method can be called with keyword-option/value pairs that control
where the widget is to appear within its container, and how it is to behave when
the main application window is resized.  Here are some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">fred</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>                     <span class="c1"># defaults to side = &quot;top&quot;</span>
<span class="n">fred</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="n">side</span> <span class="o">=</span> <span class="s2">&quot;left&quot;</span><span class="p">)</span>
<span class="n">fred</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="n">expand</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="packer-options">
<h3>24.1.6.3. Packer Options<a class="headerlink" href="#packer-options" title="Permalink to this headline">¶</a></h3>
<p>For more extensive information on the packer and the options that it can take,
see the man pages and page 183 of John Ousterhout’s book.</p>
<dl class="docutils">
<dt>anchor</dt>
<dd>Anchor type.  Denotes where the packer is to place each slave in its parcel.</dd>
<dt>expand</dt>
<dd>Boolean, <code class="docutils literal notranslate"><span class="pre">0</span></code> or <code class="docutils literal notranslate"><span class="pre">1</span></code>.</dd>
<dt>fill</dt>
<dd>Legal values: <code class="docutils literal notranslate"><span class="pre">'x'</span></code>, <code class="docutils literal notranslate"><span class="pre">'y'</span></code>, <code class="docutils literal notranslate"><span class="pre">'both'</span></code>, <code class="docutils literal notranslate"><span class="pre">'none'</span></code>.</dd>
<dt>ipadx and ipady</dt>
<dd>A distance - designating internal padding on each side of the slave widget.</dd>
<dt>padx and pady</dt>
<dd>A distance - designating external padding on each side of the slave widget.</dd>
<dt>side</dt>
<dd>Legal values are: <code class="docutils literal notranslate"><span class="pre">'left'</span></code>, <code class="docutils literal notranslate"><span class="pre">'right'</span></code>, <code class="docutils literal notranslate"><span class="pre">'top'</span></code>, <code class="docutils literal notranslate"><span class="pre">'bottom'</span></code>.</dd>
</dl>
</div>
<div class="section" id="coupling-widget-variables">
<h3>24.1.6.4. Coupling Widget Variables<a class="headerlink" href="#coupling-widget-variables" title="Permalink to this headline">¶</a></h3>
<p>The current-value setting of some widgets (like text entry widgets) can be
connected directly to application variables by using special options.  These
options are <code class="docutils literal notranslate"><span class="pre">variable</span></code>, <code class="docutils literal notranslate"><span class="pre">textvariable</span></code>, <code class="docutils literal notranslate"><span class="pre">onvalue</span></code>, <code class="docutils literal notranslate"><span class="pre">offvalue</span></code>, and
<code class="docutils literal notranslate"><span class="pre">value</span></code>.  This connection works both ways: if the variable changes for any
reason, the widget it’s connected to will be updated to reflect the new value.</p>
<p>Unfortunately, in the current implementation of <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> it is not
possible to hand over an arbitrary Python variable to a widget through a
<code class="docutils literal notranslate"><span class="pre">variable</span></code> or <code class="docutils literal notranslate"><span class="pre">textvariable</span></code> option.  The only kinds of variables for which
this works are variables that are subclassed from a class called Variable,
defined in the <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module.</p>
<p>There are many useful subclasses of Variable already defined:
<code class="xref py py-class docutils literal notranslate"><span class="pre">StringVar</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">IntVar</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">DoubleVar</span></code>, and
<code class="xref py py-class docutils literal notranslate"><span class="pre">BooleanVar</span></code>.  To read the current value of such a variable, call the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> method on it, and to change its value you call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code>
method.  If you follow this protocol, the widget will always track the value of
the variable, with no further intervention on your part.</p>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">App</span><span class="p">(</span><span class="n">Frame</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">Frame</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

        <span class="bp">self</span><span class="o">.</span><span class="n">entrythingy</span> <span class="o">=</span> <span class="n">Entry</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">entrythingy</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

        <span class="c1"># here is the application variable</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">contents</span> <span class="o">=</span> <span class="n">StringVar</span><span class="p">()</span>
        <span class="c1"># set it to some value</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s2">&quot;this is a variable&quot;</span><span class="p">)</span>
        <span class="c1"># tell the entry widget to watch this variable</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">entrythingy</span><span class="p">[</span><span class="s2">&quot;textvariable&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">contents</span>

        <span class="c1"># and here we get a callback when the user hits return.</span>
        <span class="c1"># we will have the program print out the value of the</span>
        <span class="c1"># application variable when the user hits return</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">entrythingy</span><span class="o">.</span><span class="n">bind</span><span class="p">(</span><span class="s1">&#39;&lt;Key-Return&gt;&#39;</span><span class="p">,</span>
                              <span class="bp">self</span><span class="o">.</span><span class="n">print_contents</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">print_contents</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">event</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s2">&quot;hi. contents of entry is now ----&gt;&quot;</span><span class="p">,</span> \
              <span class="bp">self</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="the-window-manager">
<h3>24.1.6.5. The Window Manager<a class="headerlink" href="#the-window-manager" title="Permalink to this headline">¶</a></h3>
<p id="index-1">In Tk, there is a utility command, <code class="docutils literal notranslate"><span class="pre">wm</span></code>, for interacting with the window
manager.  Options to the <code class="docutils literal notranslate"><span class="pre">wm</span></code> command allow you to control things like titles,
placement, icon bitmaps, and the like.  In <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>, these commands have
been implemented as methods on the <code class="xref py py-class docutils literal notranslate"><span class="pre">Wm</span></code> class.  Toplevel widgets are
subclassed from the <code class="xref py py-class docutils literal notranslate"><span class="pre">Wm</span></code> class, and so can call the <code class="xref py py-class docutils literal notranslate"><span class="pre">Wm</span></code> methods
directly.</p>
<p>To get at the toplevel window that contains a given widget, you can often just
refer to the widget’s master.  Of course if the widget has been packed inside of
a frame, the master won’t represent a toplevel window.  To get at the toplevel
window that contains an arbitrary widget, you can call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">_root()</span></code> method.
This method begins with an underscore to denote the fact that this function is
part of the implementation, and not an interface to Tk functionality.</p>
<p>Here are some examples of typical usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Tkinter</span> <span class="k">import</span> <span class="o">*</span>
<span class="k">class</span> <span class="nc">App</span><span class="p">(</span><span class="n">Frame</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
        <span class="n">Frame</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">master</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>


<span class="c1"># create the application</span>
<span class="n">myapp</span> <span class="o">=</span> <span class="n">App</span><span class="p">()</span>

<span class="c1">#</span>
<span class="c1"># here are method calls to the window manager class</span>
<span class="c1">#</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">master</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s2">&quot;My Do-Nothing Application&quot;</span><span class="p">)</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">master</span><span class="o">.</span><span class="n">maxsize</span><span class="p">(</span><span class="mi">1000</span><span class="p">,</span> <span class="mi">400</span><span class="p">)</span>

<span class="c1"># start the program</span>
<span class="n">myapp</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="tk-option-data-types">
<h3>24.1.6.6. Tk Option Data Types<a class="headerlink" href="#tk-option-data-types" title="Permalink to this headline">¶</a></h3>
<dl class="docutils" id="index-2">
<dt>anchor</dt>
<dd>Legal values are points of the compass: <code class="docutils literal notranslate"><span class="pre">&quot;n&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;ne&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;e&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;se&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;s&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;sw&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;w&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;nw&quot;</span></code>, and also <code class="docutils literal notranslate"><span class="pre">&quot;center&quot;</span></code>.</dd>
<dt>bitmap</dt>
<dd>There are eight built-in, named bitmaps: <code class="docutils literal notranslate"><span class="pre">'error'</span></code>, <code class="docutils literal notranslate"><span class="pre">'gray25'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'gray50'</span></code>, <code class="docutils literal notranslate"><span class="pre">'hourglass'</span></code>, <code class="docutils literal notranslate"><span class="pre">'info'</span></code>, <code class="docutils literal notranslate"><span class="pre">'questhead'</span></code>, <code class="docutils literal notranslate"><span class="pre">'question'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'warning'</span></code>.  To specify an X bitmap filename, give the full path to the file,
preceded with an <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>, as in <code class="docutils literal notranslate"><span class="pre">&quot;&#64;/usr/contrib/bitmap/gumby.bit&quot;</span></code>.</dd>
<dt>boolean</dt>
<dd>You can pass integers 0 or 1 or the strings <code class="docutils literal notranslate"><span class="pre">&quot;yes&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;no&quot;</span></code>.</dd>
<dt>callback</dt>
<dd><p class="first">This is any Python function that takes no arguments.  For example:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">print_it</span><span class="p">():</span>
        <span class="nb">print</span> <span class="s2">&quot;hi there&quot;</span>
<span class="n">fred</span><span class="p">[</span><span class="s2">&quot;command&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="n">print_it</span>
</pre></div>
</div>
</dd>
<dt>color</dt>
<dd>Colors can be given as the names of X colors in the rgb.txt file, or as strings
representing RGB values in 4 bit: <code class="docutils literal notranslate"><span class="pre">&quot;#RGB&quot;</span></code>, 8 bit: <code class="docutils literal notranslate"><span class="pre">&quot;#RRGGBB&quot;</span></code>, 12 bit”
<code class="docutils literal notranslate"><span class="pre">&quot;#RRRGGGBBB&quot;</span></code>, or 16 bit <code class="docutils literal notranslate"><span class="pre">&quot;#RRRRGGGGBBBB&quot;</span></code> ranges, where R,G,B here
represent any legal hex digit.  See page 160 of Ousterhout’s book for details.</dd>
<dt>cursor</dt>
<dd>The standard X cursor names from <code class="file docutils literal notranslate"><span class="pre">cursorfont.h</span></code> can be used, without the
<code class="docutils literal notranslate"><span class="pre">XC_</span></code> prefix.  For example to get a hand cursor (<code class="xref py py-const docutils literal notranslate"><span class="pre">XC_hand2</span></code>), use the
string <code class="docutils literal notranslate"><span class="pre">&quot;hand2&quot;</span></code>.  You can also specify a bitmap and mask file of your own.
See page 179 of Ousterhout’s book.</dd>
<dt>distance</dt>
<dd>Screen distances can be specified in either pixels or absolute distances.
Pixels are given as numbers and absolute distances as strings, with the trailing
character denoting units: <code class="docutils literal notranslate"><span class="pre">c</span></code> for centimetres, <code class="docutils literal notranslate"><span class="pre">i</span></code> for inches, <code class="docutils literal notranslate"><span class="pre">m</span></code> for
millimetres, <code class="docutils literal notranslate"><span class="pre">p</span></code> for printer’s points.  For example, 3.5 inches is expressed
as <code class="docutils literal notranslate"><span class="pre">&quot;3.5i&quot;</span></code>.</dd>
<dt>font</dt>
<dd>Tk uses a list font name format, such as <code class="docutils literal notranslate"><span class="pre">{courier</span> <span class="pre">10</span> <span class="pre">bold}</span></code>. Font sizes with
positive numbers are measured in points; sizes with negative numbers are
measured in pixels.</dd>
<dt>geometry</dt>
<dd>This is a string of the form <code class="docutils literal notranslate"><span class="pre">widthxheight</span></code>, where width and height are
measured in pixels for most widgets (in characters for widgets displaying text).
For example: <code class="docutils literal notranslate"><span class="pre">fred[&quot;geometry&quot;]</span> <span class="pre">=</span> <span class="pre">&quot;200x100&quot;</span></code>.</dd>
<dt>justify</dt>
<dd>Legal values are the strings: <code class="docutils literal notranslate"><span class="pre">&quot;left&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;center&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;right&quot;</span></code>, and
<code class="docutils literal notranslate"><span class="pre">&quot;fill&quot;</span></code>.</dd>
<dt>region</dt>
<dd>This is a string with four space-delimited elements, each of which is a legal
distance (see above).  For example: <code class="docutils literal notranslate"><span class="pre">&quot;2</span> <span class="pre">3</span> <span class="pre">4</span> <span class="pre">5&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;3i</span> <span class="pre">2i</span> <span class="pre">4.5i</span> <span class="pre">2i&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&quot;3c</span> <span class="pre">2c</span> <span class="pre">4c</span> <span class="pre">10.43c&quot;</span></code>  are all legal regions.</dd>
<dt>relief</dt>
<dd>Determines what the border style of a widget will be.  Legal values are:
<code class="docutils literal notranslate"><span class="pre">&quot;raised&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;sunken&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;flat&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;groove&quot;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&quot;ridge&quot;</span></code>.</dd>
<dt>scrollcommand</dt>
<dd>This is almost always the <code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code> method of some scrollbar widget, but can
be any widget method that takes a single argument.   Refer to the file
<code class="file docutils literal notranslate"><span class="pre">Demo/tkinter/matt/canvas-with-scrollbars.py</span></code> in the Python source
distribution for an example.</dd>
<dt>wrap:</dt>
<dd>Must be one of: <code class="docutils literal notranslate"><span class="pre">&quot;none&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;char&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;word&quot;</span></code>.</dd>
</dl>
</div>
<div class="section" id="bindings-and-events">
<h3>24.1.6.7. Bindings and Events<a class="headerlink" href="#bindings-and-events" title="Permalink to this headline">¶</a></h3>
<p id="index-3">The bind method from the widget command allows you to watch for certain events
and to have a callback function trigger when that event type occurs.  The form
of the bind method is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">bind</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">sequence</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="n">add</span><span class="o">=</span><span class="s1">&#39;&#39;</span><span class="p">):</span>
</pre></div>
</div>
<p>where:</p>
<dl class="docutils">
<dt>sequence</dt>
<dd>is a string that denotes the target kind of event.  (See the bind man page and
page 201 of John Ousterhout’s book for details).</dd>
<dt>func</dt>
<dd>is a Python function, taking one argument, to be invoked when the event occurs.
An Event instance will be passed as the argument. (Functions deployed this way
are commonly known as <em>callbacks</em>.)</dd>
<dt>add</dt>
<dd>is optional, either <code class="docutils literal notranslate"><span class="pre">''</span></code> or <code class="docutils literal notranslate"><span class="pre">'+'</span></code>.  Passing an empty string denotes that
this binding is to replace any other bindings that this event is associated
with.  Passing a <code class="docutils literal notranslate"><span class="pre">'+'</span></code> means that this function is to be added to the list
of functions bound to this event type.</dd>
</dl>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">turnRed</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">event</span><span class="p">):</span>
    <span class="n">event</span><span class="o">.</span><span class="n">widget</span><span class="p">[</span><span class="s2">&quot;activeforeground&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;red&quot;</span>

<span class="bp">self</span><span class="o">.</span><span class="n">button</span><span class="o">.</span><span class="n">bind</span><span class="p">(</span><span class="s2">&quot;&lt;Enter&gt;&quot;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">turnRed</span><span class="p">)</span>
</pre></div>
</div>
<p>Notice how the widget field of the event is being accessed in the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">turnRed()</span></code> callback.  This field contains the widget that caught the X
event.  The following table lists the other event fields you can access, and how
they are denoted in Tk, which can be useful when referring to the Tk man pages.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Tk</span>      <span class="n">Tkinter</span> <span class="n">Event</span> <span class="n">Field</span>             <span class="n">Tk</span>      <span class="n">Tkinter</span> <span class="n">Event</span> <span class="n">Field</span>
<span class="o">--</span>      <span class="o">-------------------</span>             <span class="o">--</span>      <span class="o">-------------------</span>
<span class="o">%</span><span class="n">f</span>      <span class="n">focus</span>                           <span class="o">%</span><span class="n">A</span>      <span class="n">char</span>
<span class="o">%</span><span class="n">h</span>      <span class="n">height</span>                          <span class="o">%</span><span class="n">E</span>      <span class="n">send_event</span>
<span class="o">%</span><span class="n">k</span>      <span class="n">keycode</span>                         <span class="o">%</span><span class="n">K</span>      <span class="n">keysym</span>
<span class="o">%</span><span class="n">s</span>      <span class="n">state</span>                           <span class="o">%</span><span class="n">N</span>      <span class="n">keysym_num</span>
<span class="o">%</span><span class="n">t</span>      <span class="n">time</span>                            <span class="o">%</span><span class="n">T</span>      <span class="nb">type</span>
<span class="o">%</span><span class="n">w</span>      <span class="n">width</span>                           <span class="o">%</span><span class="n">W</span>      <span class="n">widget</span>
<span class="o">%</span><span class="n">x</span>      <span class="n">x</span>                               <span class="o">%</span><span class="n">X</span>      <span class="n">x_root</span>
<span class="o">%</span><span class="n">y</span>      <span class="n">y</span>                               <span class="o">%</span><span class="n">Y</span>      <span class="n">y_root</span>
</pre></div>
</div>
</div>
<div class="section" id="the-index-parameter">
<h3>24.1.6.8. The index Parameter<a class="headerlink" href="#the-index-parameter" title="Permalink to this headline">¶</a></h3>
<p>A number of widgets require”index” parameters to be passed.  These are used to
point at a specific place in a Text widget, or to particular characters in an
Entry widget, or to particular menu items in a Menu widget.</p>
<dl class="docutils">
<dt>Entry widget indexes (index, view index, etc.)</dt>
<dd><p class="first">Entry widgets have options that refer to character positions in the text being
displayed.  You can use these <a class="reference internal" href="#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> functions to access these special
points in text widgets:</p>
<dl class="last docutils">
<dt>AtEnd()</dt>
<dd>refers to the last position in the text</dd>
<dt>AtInsert()</dt>
<dd>refers to the point where the text cursor is</dd>
<dt>AtSelFirst()</dt>
<dd>indicates the beginning point of the selected text</dd>
<dt>AtSelLast()</dt>
<dd>denotes the last point of the selected text and finally</dd>
<dt>At(x[, y])</dt>
<dd>refers to the character at pixel location <em>x</em>, <em>y</em> (with <em>y</em> not used in the
case of a text entry widget, which contains a single line of text).</dd>
</dl>
</dd>
<dt>Text widget indexes</dt>
<dd>The index notation for Text widgets is very rich and is best described in the Tk
man pages.</dd>
<dt>Menu indexes (menu.invoke(), menu.entryconfig(), etc.)</dt>
<dd><p class="first">Some options and methods for menus manipulate specific menu entries. Anytime a
menu index is needed for an option or a parameter, you may pass in:</p>
<ul class="last simple">
<li>an integer which refers to the numeric position of the entry in the widget,
counted from the top, starting with 0;</li>
<li>the string <code class="docutils literal notranslate"><span class="pre">'active'</span></code>, which refers to the menu position that is currently
under the cursor;</li>
<li>the string <code class="docutils literal notranslate"><span class="pre">&quot;last&quot;</span></code> which refers to the last menu item;</li>
<li>An integer preceded by <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>, as in <code class="docutils literal notranslate"><span class="pre">&#64;6</span></code>, where the integer is interpreted
as a y pixel coordinate in the menu’s coordinate system;</li>
<li>the string <code class="docutils literal notranslate"><span class="pre">&quot;none&quot;</span></code>, which indicates no menu entry at all, most often used
with menu.activate() to deactivate all entries, and finally,</li>
<li>a text string that is pattern matched against the label of the menu entry, as
scanned from the top of the menu to the bottom.  Note that this index type is
considered after all the others, which means that matches for menu items
labelled <code class="docutils literal notranslate"><span class="pre">last</span></code>, <code class="docutils literal notranslate"><span class="pre">active</span></code>, or <code class="docutils literal notranslate"><span class="pre">none</span></code> may be interpreted as the above
literals, instead.</li>
</ul>
</dd>
</dl>
</div>
<div class="section" id="images">
<h3>24.1.6.9. Images<a class="headerlink" href="#images" title="Permalink to this headline">¶</a></h3>
<p>Images of different formats can be created through the corresponding subclass
of <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Image</span></code>:</p>
<ul class="simple">
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">BitmapImage</span></code> for images in XBM format.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">PhotoImage</span></code> for images in PGM, PPM, GIF and PNG formats. The latter
is supported starting with Tk 8.6.</li>
</ul>
<p>Either type of image is created through either the <code class="docutils literal notranslate"><span class="pre">file</span></code> or the <code class="docutils literal notranslate"><span class="pre">data</span></code>
option (other options are available as well).</p>
<p>The image object can then be used wherever an <code class="docutils literal notranslate"><span class="pre">image</span></code> option is supported by
some widget (e.g. labels, buttons, menus). In these cases, Tk will not keep a
reference to the image. When the last Python reference to the image object is
deleted, the image data is deleted as well, and Tk will display an empty box
wherever the image was used.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference external" href="http://python-pillow.org/">Pillow</a> package adds support for
formats such as BMP, JPEG, TIFF, and WebP, among others.</p>
</div>
</div>
</div>
<div class="section" id="file-handlers">
<span id="tkinter-file-handlers"></span><h2>24.1.7. File Handlers<a class="headerlink" href="#file-handlers" title="Permalink to this headline">¶</a></h2>
<p>Tk allows you to register and unregister a callback function which will be
called from the Tk mainloop when I/O is possible on a file descriptor.
Only one handler may be registered per file descriptor. Example code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tkinter</span>
<span class="n">widget</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>
<span class="n">mask</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">READABLE</span> <span class="o">|</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">WRITABLE</span>
<span class="n">widget</span><span class="o">.</span><span class="n">tk</span><span class="o">.</span><span class="n">createfilehandler</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">mask</span><span class="p">,</span> <span class="n">callback</span><span class="p">)</span>
<span class="o">...</span>
<span class="n">widget</span><span class="o">.</span><span class="n">tk</span><span class="o">.</span><span class="n">deletefilehandler</span><span class="p">(</span><span class="n">file</span><span class="p">)</span>
</pre></div>
</div>
<p>This feature is not available on Windows.</p>
<p>Since you don’t know how many bytes are available for reading, you may not
want to use the <a class="reference internal" href="io.html#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code></a> or <a class="reference internal" href="io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code></a>
<a class="reference internal" href="io.html#io.BufferedIOBase.read" title="io.BufferedIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> or <a class="reference internal" href="io.html#io.IOBase.readline" title="io.IOBase.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> methods,
since these will insist on reading a predefined number of bytes.
For sockets, the <a class="reference internal" href="socket.html#socket.socket.recv" title="socket.socket.recv"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code></a> or
<a class="reference internal" href="socket.html#socket.socket.recvfrom" title="socket.socket.recvfrom"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvfrom()</span></code></a> methods will work fine; for other files,
use raw reads or <code class="docutils literal notranslate"><span class="pre">os.read(file.fileno(),</span> <span class="pre">maxbytecount)</span></code>.</p>
<dl class="method">
<dt id="Tkinter.Widget.tk.createfilehandler">
<code class="descclassname">Widget.tk.</code><code class="descname">createfilehandler</code><span class="sig-paren">(</span><em>file</em>, <em>mask</em>, <em>func</em><span class="sig-paren">)</span><a class="headerlink" href="#Tkinter.Widget.tk.createfilehandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers the file handler callback function <em>func</em>. The <em>file</em> argument
may either be an object with a <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code></a> method (such as
a file or socket object), or an integer file descriptor. The <em>mask</em>
argument is an ORed combination of any of the three constants below.
The callback is called as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">callback</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">mask</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="Tkinter.Widget.tk.deletefilehandler">
<code class="descclassname">Widget.tk.</code><code class="descname">deletefilehandler</code><span class="sig-paren">(</span><em>file</em><span class="sig-paren">)</span><a class="headerlink" href="#Tkinter.Widget.tk.deletefilehandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Unregisters a file handler.</p>
</dd></dl>

<dl class="data">
<dt id="Tkinter.READABLE">
<code class="descclassname">Tkinter.</code><code class="descname">READABLE</code><a class="headerlink" href="#Tkinter.READABLE" title="Permalink to this definition">¶</a></dt>
<dt id="Tkinter.WRITABLE">
<code class="descclassname">Tkinter.</code><code class="descname">WRITABLE</code><a class="headerlink" href="#Tkinter.WRITABLE" title="Permalink to this definition">¶</a></dt>
<dt id="Tkinter.EXCEPTION">
<code class="descclassname">Tkinter.</code><code class="descname">EXCEPTION</code><a class="headerlink" href="#Tkinter.EXCEPTION" title="Permalink to this definition">¶</a></dt>
<dd><p>Constants used in the <em>mask</em> arguments.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a><ul>
<li><a class="reference internal" href="#tkinter-modules">24.1.1. Tkinter Modules</a></li>
<li><a class="reference internal" href="#tkinter-life-preserver">24.1.2. Tkinter Life Preserver</a><ul>
<li><a class="reference internal" href="#how-to-use-this-section">24.1.2.1. How To Use This Section</a></li>
<li><a class="reference internal" href="#a-simple-hello-world-program">24.1.2.2. A Simple Hello World Program</a></li>
</ul>
</li>
<li><a class="reference internal" href="#a-very-quick-look-at-tcl-tk">24.1.3. A (Very) Quick Look at Tcl/Tk</a></li>
<li><a class="reference internal" href="#mapping-basic-tk-into-tkinter">24.1.4. Mapping Basic Tk into Tkinter</a></li>
<li><a class="reference internal" href="#how-tk-and-tkinter-are-related">24.1.5. How Tk and Tkinter are Related</a></li>
<li><a class="reference internal" href="#handy-reference">24.1.6. Handy Reference</a><ul>
<li><a class="reference internal" href="#setting-options">24.1.6.1. Setting Options</a></li>
<li><a class="reference internal" href="#the-packer">24.1.6.2. The Packer</a></li>
<li><a class="reference internal" href="#packer-options">24.1.6.3. Packer Options</a></li>
<li><a class="reference internal" href="#coupling-widget-variables">24.1.6.4. Coupling Widget Variables</a></li>
<li><a class="reference internal" href="#the-window-manager">24.1.6.5. The Window Manager</a></li>
<li><a class="reference internal" href="#tk-option-data-types">24.1.6.6. Tk Option Data Types</a></li>
<li><a class="reference internal" href="#bindings-and-events">24.1.6.7. Bindings and Events</a></li>
<li><a class="reference internal" href="#the-index-parameter">24.1.6.8. The index Parameter</a></li>
<li><a class="reference internal" href="#images">24.1.6.9. Images</a></li>
</ul>
</li>
<li><a class="reference internal" href="#file-handlers">24.1.7. File Handlers</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="tk.html"
                        title="previous chapter">24. Graphical User Interfaces with Tk</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="ttk.html"
                        title="next chapter">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tkinter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="ttk.html" title="24.2. ttk — Tk themed widgets"
             >next</a> |</li>
        <li class="right" >
          <a href="tk.html" title="24. Graphical User Interfaces with Tk"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��ZRRhtml/library/token.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.5. token — Constants used with Python parse trees &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.6. keyword — Testing for Python keywords" href="keyword.html" />
    <link rel="prev" title="32.4. symbol — Constants used with Python parse trees" href="symbol.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/token.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="32.6. keyword — Testing for Python keywords"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="symbol.html" title="32.4. symbol — Constants used with Python parse trees"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-token">
<span id="token-constants-used-with-python-parse-trees"></span><h1>32.5. <a class="reference internal" href="#module-token" title="token: Constants representing terminal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">token</span></code></a> — Constants used with Python parse trees<a class="headerlink" href="#module-token" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/token.py">Lib/token.py</a></p>
<hr class="docutils" />
<p>This module provides constants which represent the numeric values of leaf nodes
of the parse tree (terminal tokens).  Refer to the file <code class="file docutils literal notranslate"><span class="pre">Grammar/Grammar</span></code>
in the Python distribution for the definitions of the names in the context of
the language grammar.  The specific numeric values which the names map to may
change between Python versions.</p>
<p>The module also provides a mapping from numeric codes to names and some
functions.  The functions mirror definitions in the Python C header files.</p>
<dl class="data">
<dt id="token.tok_name">
<code class="descclassname">token.</code><code class="descname">tok_name</code><a class="headerlink" href="#token.tok_name" title="Permalink to this definition">¶</a></dt>
<dd><p>Dictionary mapping the numeric values of the constants defined in this module
back to name strings, allowing more human-readable representation of parse trees
to be generated.</p>
</dd></dl>

<dl class="function">
<dt id="token.ISTERMINAL">
<code class="descclassname">token.</code><code class="descname">ISTERMINAL</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#token.ISTERMINAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true for terminal token values.</p>
</dd></dl>

<dl class="function">
<dt id="token.ISNONTERMINAL">
<code class="descclassname">token.</code><code class="descname">ISNONTERMINAL</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#token.ISNONTERMINAL" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true for non-terminal token values.</p>
</dd></dl>

<dl class="function">
<dt id="token.ISEOF">
<code class="descclassname">token.</code><code class="descname">ISEOF</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#token.ISEOF" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>x</em> is the marker indicating the end of input.</p>
</dd></dl>

<p>The token constants are:</p>
<dl class="data">
<dt id="token.ENDMARKER">
<code class="descclassname">token.</code><code class="descname">ENDMARKER</code><a class="headerlink" href="#token.ENDMARKER" title="Permalink to this definition">¶</a></dt>
<dt id="token.NAME">
<code class="descclassname">token.</code><code class="descname">NAME</code><a class="headerlink" href="#token.NAME" title="Permalink to this definition">¶</a></dt>
<dt id="token.NUMBER">
<code class="descclassname">token.</code><code class="descname">NUMBER</code><a class="headerlink" href="#token.NUMBER" title="Permalink to this definition">¶</a></dt>
<dt id="token.STRING">
<code class="descclassname">token.</code><code class="descname">STRING</code><a class="headerlink" href="#token.STRING" title="Permalink to this definition">¶</a></dt>
<dt id="token.NEWLINE">
<code class="descclassname">token.</code><code class="descname">NEWLINE</code><a class="headerlink" href="#token.NEWLINE" title="Permalink to this definition">¶</a></dt>
<dt id="token.INDENT">
<code class="descclassname">token.</code><code class="descname">INDENT</code><a class="headerlink" href="#token.INDENT" title="Permalink to this definition">¶</a></dt>
<dt id="token.DEDENT">
<code class="descclassname">token.</code><code class="descname">DEDENT</code><a class="headerlink" href="#token.DEDENT" title="Permalink to this definition">¶</a></dt>
<dt id="token.LPAR">
<code class="descclassname">token.</code><code class="descname">LPAR</code><a class="headerlink" href="#token.LPAR" title="Permalink to this definition">¶</a></dt>
<dt id="token.RPAR">
<code class="descclassname">token.</code><code class="descname">RPAR</code><a class="headerlink" href="#token.RPAR" title="Permalink to this definition">¶</a></dt>
<dt id="token.LSQB">
<code class="descclassname">token.</code><code class="descname">LSQB</code><a class="headerlink" href="#token.LSQB" title="Permalink to this definition">¶</a></dt>
<dt id="token.RSQB">
<code class="descclassname">token.</code><code class="descname">RSQB</code><a class="headerlink" href="#token.RSQB" title="Permalink to this definition">¶</a></dt>
<dt id="token.COLON">
<code class="descclassname">token.</code><code class="descname">COLON</code><a class="headerlink" href="#token.COLON" title="Permalink to this definition">¶</a></dt>
<dt id="token.COMMA">
<code class="descclassname">token.</code><code class="descname">COMMA</code><a class="headerlink" href="#token.COMMA" title="Permalink to this definition">¶</a></dt>
<dt id="token.SEMI">
<code class="descclassname">token.</code><code class="descname">SEMI</code><a class="headerlink" href="#token.SEMI" title="Permalink to this definition">¶</a></dt>
<dt id="token.PLUS">
<code class="descclassname">token.</code><code class="descname">PLUS</code><a class="headerlink" href="#token.PLUS" title="Permalink to this definition">¶</a></dt>
<dt id="token.MINUS">
<code class="descclassname">token.</code><code class="descname">MINUS</code><a class="headerlink" href="#token.MINUS" title="Permalink to this definition">¶</a></dt>
<dt id="token.STAR">
<code class="descclassname">token.</code><code class="descname">STAR</code><a class="headerlink" href="#token.STAR" title="Permalink to this definition">¶</a></dt>
<dt id="token.SLASH">
<code class="descclassname">token.</code><code class="descname">SLASH</code><a class="headerlink" href="#token.SLASH" title="Permalink to this definition">¶</a></dt>
<dt id="token.VBAR">
<code class="descclassname">token.</code><code class="descname">VBAR</code><a class="headerlink" href="#token.VBAR" title="Permalink to this definition">¶</a></dt>
<dt id="token.AMPER">
<code class="descclassname">token.</code><code class="descname">AMPER</code><a class="headerlink" href="#token.AMPER" title="Permalink to this definition">¶</a></dt>
<dt id="token.LESS">
<code class="descclassname">token.</code><code class="descname">LESS</code><a class="headerlink" href="#token.LESS" title="Permalink to this definition">¶</a></dt>
<dt id="token.GREATER">
<code class="descclassname">token.</code><code class="descname">GREATER</code><a class="headerlink" href="#token.GREATER" title="Permalink to this definition">¶</a></dt>
<dt id="token.EQUAL">
<code class="descclassname">token.</code><code class="descname">EQUAL</code><a class="headerlink" href="#token.EQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.DOT">
<code class="descclassname">token.</code><code class="descname">DOT</code><a class="headerlink" href="#token.DOT" title="Permalink to this definition">¶</a></dt>
<dt id="token.PERCENT">
<code class="descclassname">token.</code><code class="descname">PERCENT</code><a class="headerlink" href="#token.PERCENT" title="Permalink to this definition">¶</a></dt>
<dt id="token.BACKQUOTE">
<code class="descclassname">token.</code><code class="descname">BACKQUOTE</code><a class="headerlink" href="#token.BACKQUOTE" title="Permalink to this definition">¶</a></dt>
<dt id="token.LBRACE">
<code class="descclassname">token.</code><code class="descname">LBRACE</code><a class="headerlink" href="#token.LBRACE" title="Permalink to this definition">¶</a></dt>
<dt id="token.RBRACE">
<code class="descclassname">token.</code><code class="descname">RBRACE</code><a class="headerlink" href="#token.RBRACE" title="Permalink to this definition">¶</a></dt>
<dt id="token.EQEQUAL">
<code class="descclassname">token.</code><code class="descname">EQEQUAL</code><a class="headerlink" href="#token.EQEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.NOTEQUAL">
<code class="descclassname">token.</code><code class="descname">NOTEQUAL</code><a class="headerlink" href="#token.NOTEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.LESSEQUAL">
<code class="descclassname">token.</code><code class="descname">LESSEQUAL</code><a class="headerlink" href="#token.LESSEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.GREATEREQUAL">
<code class="descclassname">token.</code><code class="descname">GREATEREQUAL</code><a class="headerlink" href="#token.GREATEREQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.TILDE">
<code class="descclassname">token.</code><code class="descname">TILDE</code><a class="headerlink" href="#token.TILDE" title="Permalink to this definition">¶</a></dt>
<dt id="token.CIRCUMFLEX">
<code class="descclassname">token.</code><code class="descname">CIRCUMFLEX</code><a class="headerlink" href="#token.CIRCUMFLEX" title="Permalink to this definition">¶</a></dt>
<dt id="token.LEFTSHIFT">
<code class="descclassname">token.</code><code class="descname">LEFTSHIFT</code><a class="headerlink" href="#token.LEFTSHIFT" title="Permalink to this definition">¶</a></dt>
<dt id="token.RIGHTSHIFT">
<code class="descclassname">token.</code><code class="descname">RIGHTSHIFT</code><a class="headerlink" href="#token.RIGHTSHIFT" title="Permalink to this definition">¶</a></dt>
<dt id="token.DOUBLESTAR">
<code class="descclassname">token.</code><code class="descname">DOUBLESTAR</code><a class="headerlink" href="#token.DOUBLESTAR" title="Permalink to this definition">¶</a></dt>
<dt id="token.PLUSEQUAL">
<code class="descclassname">token.</code><code class="descname">PLUSEQUAL</code><a class="headerlink" href="#token.PLUSEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.MINEQUAL">
<code class="descclassname">token.</code><code class="descname">MINEQUAL</code><a class="headerlink" href="#token.MINEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.STAREQUAL">
<code class="descclassname">token.</code><code class="descname">STAREQUAL</code><a class="headerlink" href="#token.STAREQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.SLASHEQUAL">
<code class="descclassname">token.</code><code class="descname">SLASHEQUAL</code><a class="headerlink" href="#token.SLASHEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.PERCENTEQUAL">
<code class="descclassname">token.</code><code class="descname">PERCENTEQUAL</code><a class="headerlink" href="#token.PERCENTEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.AMPEREQUAL">
<code class="descclassname">token.</code><code class="descname">AMPEREQUAL</code><a class="headerlink" href="#token.AMPEREQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.VBAREQUAL">
<code class="descclassname">token.</code><code class="descname">VBAREQUAL</code><a class="headerlink" href="#token.VBAREQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.CIRCUMFLEXEQUAL">
<code class="descclassname">token.</code><code class="descname">CIRCUMFLEXEQUAL</code><a class="headerlink" href="#token.CIRCUMFLEXEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.LEFTSHIFTEQUAL">
<code class="descclassname">token.</code><code class="descname">LEFTSHIFTEQUAL</code><a class="headerlink" href="#token.LEFTSHIFTEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.RIGHTSHIFTEQUAL">
<code class="descclassname">token.</code><code class="descname">RIGHTSHIFTEQUAL</code><a class="headerlink" href="#token.RIGHTSHIFTEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.DOUBLESTAREQUAL">
<code class="descclassname">token.</code><code class="descname">DOUBLESTAREQUAL</code><a class="headerlink" href="#token.DOUBLESTAREQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.DOUBLESLASH">
<code class="descclassname">token.</code><code class="descname">DOUBLESLASH</code><a class="headerlink" href="#token.DOUBLESLASH" title="Permalink to this definition">¶</a></dt>
<dt id="token.DOUBLESLASHEQUAL">
<code class="descclassname">token.</code><code class="descname">DOUBLESLASHEQUAL</code><a class="headerlink" href="#token.DOUBLESLASHEQUAL" title="Permalink to this definition">¶</a></dt>
<dt id="token.AT">
<code class="descclassname">token.</code><code class="descname">AT</code><a class="headerlink" href="#token.AT" title="Permalink to this definition">¶</a></dt>
<dt id="token.OP">
<code class="descclassname">token.</code><code class="descname">OP</code><a class="headerlink" href="#token.OP" title="Permalink to this definition">¶</a></dt>
<dt id="token.ERRORTOKEN">
<code class="descclassname">token.</code><code class="descname">ERRORTOKEN</code><a class="headerlink" href="#token.ERRORTOKEN" title="Permalink to this definition">¶</a></dt>
<dt id="token.N_TOKENS">
<code class="descclassname">token.</code><code class="descname">N_TOKENS</code><a class="headerlink" href="#token.N_TOKENS" title="Permalink to this definition">¶</a></dt>
<dt id="token.NT_OFFSET">
<code class="descclassname">token.</code><code class="descname">NT_OFFSET</code><a class="headerlink" href="#token.NT_OFFSET" title="Permalink to this definition">¶</a></dt>
<dd></dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="parser.html#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a></dt>
<dd>The second example for the <a class="reference internal" href="parser.html#module-parser" title="parser: Access parse trees for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">parser</span></code></a> module shows how to use the
<a class="reference internal" href="symbol.html#module-symbol" title="symbol: Constants representing internal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symbol</span></code></a> module.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="symbol.html"
                        title="previous chapter">32.4. <code class="docutils literal notranslate"><span class="pre">symbol</span></code> — Constants used with Python parse trees</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="keyword.html"
                        title="next chapter">32.6. <code class="docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/token.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="32.6. keyword — Testing for Python keywords"
             >next</a> |</li>
        <li class="right" >
          <a href="symbol.html" title="32.4. symbol — Constants used with Python parse trees"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�{�PPhtml/library/tokenize.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>32.7. tokenize — Tokenizer for Python source &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="32.8. tabnanny — Detection of ambiguous indentation" href="tabnanny.html" />
    <link rel="prev" title="32.6. keyword — Testing for Python keywords" href="keyword.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tokenize.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="32.8. tabnanny — Detection of ambiguous indentation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="32.6. keyword — Testing for Python keywords"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" accesskey="U">32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-tokenize">
<span id="tokenize-tokenizer-for-python-source"></span><h1>32.7. <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code></a> — Tokenizer for Python source<a class="headerlink" href="#module-tokenize" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/tokenize.py">Lib/tokenize.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code></a> module provides a lexical scanner for Python source code,
implemented in Python.  The scanner in this module returns comments as tokens as
well, making it useful for implementing “pretty-printers,” including colorizers
for on-screen displays.</p>
<p>To simplify token stream handling, all <a class="reference internal" href="../reference/lexical_analysis.html#operators"><span class="std std-ref">Operators</span></a> and <a class="reference internal" href="../reference/lexical_analysis.html#delimiters"><span class="std std-ref">Delimiters</span></a>
tokens are returned using the generic <a class="reference internal" href="token.html#token.OP" title="token.OP"><code class="xref py py-data docutils literal notranslate"><span class="pre">token.OP</span></code></a> token type.  The exact
type can be determined by checking the second field (containing the actual
token string matched) of the tuple returned from
<a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize.generate_tokens()</span></code></a> for the character sequence that identifies a
specific operator token.</p>
<p>The primary entry point is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>:</p>
<dl class="function">
<dt id="tokenize.generate_tokens">
<code class="descclassname">tokenize.</code><code class="descname">generate_tokens</code><span class="sig-paren">(</span><em>readline</em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.generate_tokens" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><code class="xref py py-func docutils literal notranslate"><span class="pre">generate_tokens()</span></code></a> generator requires one argument, <em>readline</em>,
which must be a callable object which provides the same interface as the
<a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method of built-in file objects (see section
<a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>).  Each call to the function should return one line
of input as a string. Alternately, <em>readline</em> may be a callable object that
signals completion by raising <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>.</p>
<p>The generator produces 5-tuples with these members: the token type; the token
string; a 2-tuple <code class="docutils literal notranslate"><span class="pre">(srow,</span> <span class="pre">scol)</span></code> of ints specifying the row and column
where the token begins in the source; a 2-tuple <code class="docutils literal notranslate"><span class="pre">(erow,</span> <span class="pre">ecol)</span></code> of ints
specifying the row and column where the token ends in the source; and the
line on which the token was found.  The line passed (the last tuple item) is
the <em>logical</em> line; continuation lines are included.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<p>An older entry point is retained for backward compatibility:</p>
<dl class="function">
<dt id="tokenize.tokenize">
<code class="descclassname">tokenize.</code><code class="descname">tokenize</code><span class="sig-paren">(</span><em>readline</em><span class="optional">[</span>, <em>tokeneater</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.tokenize" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a> function accepts two parameters: one representing the input
stream, and one providing an output mechanism for <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>.</p>
<p>The first parameter, <em>readline</em>, must be a callable object which provides the
same interface as the <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method of built-in file objects (see
section <a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a>).  Each call to the function should return one
line of input as a string. Alternately, <em>readline</em> may be a callable object that
signals completion by raising <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added <a class="reference internal" href="exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> support.</p>
</div>
<p>The second parameter, <em>tokeneater</em>, must also be a callable object.  It is
called once for each token, with five arguments, corresponding to the tuples
generated by <a class="reference internal" href="#tokenize.generate_tokens" title="tokenize.generate_tokens"><code class="xref py py-func docutils literal notranslate"><span class="pre">generate_tokens()</span></code></a>.</p>
</dd></dl>

<p>All constants from the <a class="reference internal" href="token.html#module-token" title="token: Constants representing terminal nodes of the parse tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">token</span></code></a> module are also exported from
<a class="reference internal" href="#module-tokenize" title="tokenize: Lexical scanner for Python source code."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tokenize</span></code></a>, as are two additional token type values that might be passed to
the <em>tokeneater</em> function by <a class="reference internal" href="#tokenize.tokenize" title="tokenize.tokenize"><code class="xref py py-func docutils literal notranslate"><span class="pre">tokenize()</span></code></a>:</p>
<dl class="data">
<dt id="tokenize.COMMENT">
<code class="descclassname">tokenize.</code><code class="descname">COMMENT</code><a class="headerlink" href="#tokenize.COMMENT" title="Permalink to this definition">¶</a></dt>
<dd><p>Token value used to indicate a comment.</p>
</dd></dl>

<dl class="data">
<dt id="tokenize.NL">
<code class="descclassname">tokenize.</code><code class="descname">NL</code><a class="headerlink" href="#tokenize.NL" title="Permalink to this definition">¶</a></dt>
<dd><p>Token value used to indicate a non-terminating newline.  The NEWLINE token
indicates the end of a logical line of Python code; NL tokens are generated when
a logical line of code is continued over multiple physical lines.</p>
</dd></dl>

<p>Another function is provided to reverse the tokenization process. This is useful
for creating tools that tokenize a script, modify the token stream, and write
back the modified script.</p>
<dl class="function">
<dt id="tokenize.untokenize">
<code class="descclassname">tokenize.</code><code class="descname">untokenize</code><span class="sig-paren">(</span><em>iterable</em><span class="sig-paren">)</span><a class="headerlink" href="#tokenize.untokenize" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts tokens back into Python source code.  The <em>iterable</em> must return
sequences with at least two elements, the token type and the token string.  Any
additional sequence elements are ignored.</p>
<p>The reconstructed script is returned as a single string.  The result is
guaranteed to tokenize back to match the input so that the conversion is
lossless and round-trips are assured.  The guarantee applies only to the token
type and token string as the spacing between tokens (column positions) may
change.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="exception">
<dt id="tokenize.TokenError">
<em class="property">exception </em><code class="descclassname">tokenize.</code><code class="descname">TokenError</code><a class="headerlink" href="#tokenize.TokenError" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when either a docstring or expression that may be split over several
lines is not completed anywhere in the file, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;&quot;&quot;Beginning of</span>
<span class="s2">docstring</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">,</span>
 <span class="mi">2</span><span class="p">,</span>
 <span class="mi">3</span>
</pre></div>
</div>
</dd></dl>

<p>Note that unclosed single-quoted strings do not cause an error to be
raised. They are tokenized as <code class="docutils literal notranslate"><span class="pre">ERRORTOKEN</span></code>, followed by the tokenization of
their contents.</p>
<p>Example of a script re-writer that transforms float literals into Decimal
objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">decistmt</span><span class="p">(</span><span class="n">s</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Substitute Decimals for floats in a string of statements.</span>

<span class="sd">    &gt;&gt;&gt; from decimal import Decimal</span>
<span class="sd">    &gt;&gt;&gt; s = &#39;print +21.3e-5*-.1234/81.7&#39;</span>
<span class="sd">    &gt;&gt;&gt; decistmt(s)</span>
<span class="sd">    &quot;print +Decimal (&#39;21.3e-5&#39;)*-Decimal (&#39;.1234&#39;)/Decimal (&#39;81.7&#39;)&quot;</span>

<span class="sd">    &gt;&gt;&gt; exec(s)</span>
<span class="sd">    -3.21716034272e-007</span>
<span class="sd">    &gt;&gt;&gt; exec(decistmt(s))</span>
<span class="sd">    -3.217160342717258261933904529E-7</span>

<span class="sd">    &quot;&quot;&quot;</span>
    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">g</span> <span class="o">=</span> <span class="n">generate_tokens</span><span class="p">(</span><span class="n">StringIO</span><span class="p">(</span><span class="n">s</span><span class="p">)</span><span class="o">.</span><span class="n">readline</span><span class="p">)</span>   <span class="c1"># tokenize the string</span>
    <span class="k">for</span> <span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span><span class="p">,</span> <span class="n">_</span>  <span class="ow">in</span> <span class="n">g</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">toknum</span> <span class="o">==</span> <span class="n">NUMBER</span> <span class="ow">and</span> <span class="s1">&#39;.&#39;</span> <span class="ow">in</span> <span class="n">tokval</span><span class="p">:</span>  <span class="c1"># replace NUMBER tokens</span>
            <span class="n">result</span><span class="o">.</span><span class="n">extend</span><span class="p">([</span>
                <span class="p">(</span><span class="n">NAME</span><span class="p">,</span> <span class="s1">&#39;Decimal&#39;</span><span class="p">),</span>
                <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s1">&#39;(&#39;</span><span class="p">),</span>
                <span class="p">(</span><span class="n">STRING</span><span class="p">,</span> <span class="nb">repr</span><span class="p">(</span><span class="n">tokval</span><span class="p">)),</span>
                <span class="p">(</span><span class="n">OP</span><span class="p">,</span> <span class="s1">&#39;)&#39;</span><span class="p">)</span>
            <span class="p">])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">toknum</span><span class="p">,</span> <span class="n">tokval</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">untokenize</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="keyword.html"
                        title="previous chapter">32.6. <code class="docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tabnanny.html"
                        title="next chapter">32.8. <code class="docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tokenize.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tabnanny.html" title="32.8. tabnanny — Detection of ambiguous indentation"
             >next</a> |</li>
        <li class="right" >
          <a href="keyword.html" title="32.6. keyword — Testing for Python keywords"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="language.html" >32. Python Language Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�v�o�ohtml/library/trace.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>26.7. trace — Trace or track Python statement execution &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="27. Software Packaging and Distribution" href="distribution.html" />
    <link rel="prev" title="26.6. timeit — Measure execution time of small code snippets" href="timeit.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/trace.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distribution.html" title="27. Software Packaging and Distribution"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="timeit.html" title="26.6. timeit — Measure execution time of small code snippets"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" accesskey="U">26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-trace">
<span id="trace-trace-or-track-python-statement-execution"></span><h1>26.7. <a class="reference internal" href="#module-trace" title="trace: Trace or track Python statement execution."><code class="xref py py-mod docutils literal notranslate"><span class="pre">trace</span></code></a> — Trace or track Python statement execution<a class="headerlink" href="#module-trace" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/trace.py">Lib/trace.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-trace" title="trace: Trace or track Python statement execution."><code class="xref py py-mod docutils literal notranslate"><span class="pre">trace</span></code></a> module allows you to trace program execution, generate
annotated statement coverage listings, print caller/callee relationships and
list functions executed during a program run.  It can be used in another program
or from the command line.</p>
<div class="section" id="command-line-usage">
<span id="trace-cli"></span><h2>26.7.1. Command-Line Usage<a class="headerlink" href="#command-line-usage" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-trace" title="trace: Trace or track Python statement execution."><code class="xref py py-mod docutils literal notranslate"><span class="pre">trace</span></code></a> module can be invoked from the command line.  It can be as
simple as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">trace</span> <span class="o">--</span><span class="n">count</span> <span class="o">-</span><span class="n">C</span> <span class="o">.</span> <span class="n">somefile</span><span class="o">.</span><span class="n">py</span> <span class="o">...</span>
</pre></div>
</div>
<p>The above will execute <code class="file docutils literal notranslate"><span class="pre">somefile.py</span></code> and generate annotated listings of
all Python modules imported during the execution into the current directory.</p>
<dl class="cmdoption">
<dt id="cmdoption-trace-help">
<code class="descname">--help</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-help" title="Permalink to this definition">¶</a></dt>
<dd><p>Display usage and exit.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-version">
<code class="descname">--version</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-version" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the version of the module and exit.</p>
</dd></dl>

<div class="section" id="main-options">
<h3>26.7.1.1. Main options<a class="headerlink" href="#main-options" title="Permalink to this headline">¶</a></h3>
<p>At least one of the following options must be specified when invoking
<a class="reference internal" href="#module-trace" title="trace: Trace or track Python statement execution."><code class="xref py py-mod docutils literal notranslate"><span class="pre">trace</span></code></a>.  The <a class="reference internal" href="#cmdoption-trace-l"><code class="xref std std-option docutils literal notranslate"><span class="pre">--listfuncs</span></code></a> option is mutually exclusive with
the <a class="reference internal" href="#cmdoption-trace-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">--trace</span></code></a> and <a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a> options. When
<a class="reference internal" href="#cmdoption-trace-l"><code class="xref std std-option docutils literal notranslate"><span class="pre">--listfuncs</span></code></a> is provided, neither <a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a> nor
<a class="reference internal" href="#cmdoption-trace-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">--trace</span></code></a> are accepted, and vice versa.</p>
<dl class="cmdoption">
<dt id="cmdoption-trace-c">
<code class="descname">-c</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--count</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-c" title="Permalink to this definition">¶</a></dt>
<dd><p>Produce a set of annotated listing files upon program completion that shows
how many times each statement was executed.  See also
<a class="reference internal" href="#cmdoption-trace-coverdir"><code class="xref std std-option docutils literal notranslate"><span class="pre">--coverdir</span></code></a>, <a class="reference internal" href="#cmdoption-trace-f"><code class="xref std std-option docutils literal notranslate"><span class="pre">--file</span></code></a> and
<a class="reference internal" href="#cmdoption-trace-no-report"><code class="xref std std-option docutils literal notranslate"><span class="pre">--no-report</span></code></a> below.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-t">
<code class="descname">-t</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--trace</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-t" title="Permalink to this definition">¶</a></dt>
<dd><p>Display lines as they are executed.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-l">
<code class="descname">-l</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--listfuncs</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-l" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the functions executed by running the program.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-r">
<code class="descname">-r</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--report</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-r" title="Permalink to this definition">¶</a></dt>
<dd><p>Produce an annotated list from an earlier program run that used the
<a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a> and <a class="reference internal" href="#cmdoption-trace-f"><code class="xref std std-option docutils literal notranslate"><span class="pre">--file</span></code></a> option.  This does not
execute any code.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-trackcalls">
<code class="descname">-T</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--trackcalls</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-trackcalls" title="Permalink to this definition">¶</a></dt>
<dd><p>Display the calling relationships exposed by running the program.</p>
</dd></dl>

</div>
<div class="section" id="modifiers">
<h3>26.7.1.2. Modifiers<a class="headerlink" href="#modifiers" title="Permalink to this headline">¶</a></h3>
<dl class="cmdoption">
<dt id="cmdoption-trace-f">
<code class="descname">-f</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--file</code><code class="descclassname">=&lt;file&gt;</code><a class="headerlink" href="#cmdoption-trace-f" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of a file to accumulate counts over several tracing runs.  Should be
used with the <a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a> option.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-coverdir">
<code class="descname">-C</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--coverdir</code><code class="descclassname">=&lt;dir&gt;</code><a class="headerlink" href="#cmdoption-trace-coverdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Directory where the report files go.  The coverage report for
<code class="docutils literal notranslate"><span class="pre">package.module</span></code> is written to file <code class="file docutils literal notranslate"><em><span class="pre">dir</span></em><span class="pre">/</span><em><span class="pre">package</span></em><span class="pre">/</span><em><span class="pre">module</span></em><span class="pre">.cover</span></code>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-m">
<code class="descname">-m</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--missing</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-m" title="Permalink to this definition">¶</a></dt>
<dd><p>When generating annotated listings, mark lines which were not executed with
<code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;&gt;&gt;&gt;</span></code>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-s">
<code class="descname">-s</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--summary</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-s" title="Permalink to this definition">¶</a></dt>
<dd><p>When using <a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a> or <a class="reference internal" href="#cmdoption-trace-r"><code class="xref std std-option docutils literal notranslate"><span class="pre">--report</span></code></a>, write a brief
summary to stdout for each file processed.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-no-report">
<code class="descname">-R</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--no-report</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-no-report" title="Permalink to this definition">¶</a></dt>
<dd><p>Do not generate annotated listings.  This is useful if you intend to make
several runs with <a class="reference internal" href="#cmdoption-trace-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">--count</span></code></a>, and then produce a single set of
annotated listings at the end.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-g">
<code class="descname">-g</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--timing</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-trace-g" title="Permalink to this definition">¶</a></dt>
<dd><p>Prefix each line with the time since the program started.  Only used while
tracing.</p>
</dd></dl>

</div>
<div class="section" id="filters">
<h3>26.7.1.3. Filters<a class="headerlink" href="#filters" title="Permalink to this headline">¶</a></h3>
<p>These options may be repeated multiple times.</p>
<dl class="cmdoption">
<dt id="cmdoption-trace-ignore-module">
<code class="descname">--ignore-module</code><code class="descclassname">=&lt;mod&gt;</code><a class="headerlink" href="#cmdoption-trace-ignore-module" title="Permalink to this definition">¶</a></dt>
<dd><p>Ignore each of the given module names and its submodules (if it is a
package).  The argument can be a list of names separated by a comma.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-trace-ignore-dir">
<code class="descname">--ignore-dir</code><code class="descclassname">=&lt;dir&gt;</code><a class="headerlink" href="#cmdoption-trace-ignore-dir" title="Permalink to this definition">¶</a></dt>
<dd><p>Ignore all modules and packages in the named directory and subdirectories.
The argument can be a list of directories separated by <a class="reference internal" href="os.html#os.pathsep" title="os.pathsep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.pathsep</span></code></a>.</p>
</dd></dl>

</div>
</div>
<div class="section" id="programmatic-interface">
<span id="trace-api"></span><h2>26.7.2. Programmatic Interface<a class="headerlink" href="#programmatic-interface" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="trace.Trace">
<em class="property">class </em><code class="descclassname">trace.</code><code class="descname">Trace</code><span class="sig-paren">(</span><span class="optional">[</span><em>count=1</em><span class="optional">[</span>, <em>trace=1</em><span class="optional">[</span>, <em>countfuncs=0</em><span class="optional">[</span>, <em>countcallers=0</em><span class="optional">[</span>, <em>ignoremods=()</em><span class="optional">[</span>, <em>ignoredirs=()</em><span class="optional">[</span>, <em>infile=None</em><span class="optional">[</span>, <em>outfile=None</em><span class="optional">[</span>, <em>timing=False</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#trace.Trace" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an object to trace execution of a single statement or expression.  All
parameters are optional.  <em>count</em> enables counting of line numbers.  <em>trace</em>
enables line execution tracing.  <em>countfuncs</em> enables listing of the
functions called during the run.  <em>countcallers</em> enables call relationship
tracking.  <em>ignoremods</em> is a list of modules or packages to ignore.
<em>ignoredirs</em> is a list of directories whose modules or packages should be
ignored.  <em>infile</em> is the name of the file from which to read stored count
information.  <em>outfile</em> is the name of the file in which to write updated
count information.  <em>timing</em> enables a timestamp relative to when tracing was
started to be displayed.</p>
<blockquote>
<div><dl class="method">
<dt id="trace.Trace.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>cmd</em><span class="sig-paren">)</span><a class="headerlink" href="#trace.Trace.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the command and gather statistics from the execution with
the current tracing parameters.  <em>cmd</em> must be a string or code object,
suitable for passing into <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="trace.Trace.runctx">
<code class="descname">runctx</code><span class="sig-paren">(</span><em>cmd</em>, <em>globals=None</em>, <em>locals=None</em><span class="sig-paren">)</span><a class="headerlink" href="#trace.Trace.runctx" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the command and gather statistics from the execution with the
current tracing parameters, in the defined global and local
environments.  If not defined, <em>globals</em> and <em>locals</em> default to empty
dictionaries.</p>
</dd></dl>

<dl class="method">
<dt id="trace.Trace.runfunc">
<code class="descname">runfunc</code><span class="sig-paren">(</span><em>func</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#trace.Trace.runfunc" title="Permalink to this definition">¶</a></dt>
<dd><p>Call <em>func</em> with the given arguments under control of the <a class="reference internal" href="#trace.Trace" title="trace.Trace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Trace</span></code></a>
object with the current tracing parameters.</p>
</dd></dl>

<dl class="method">
<dt id="trace.Trace.results">
<code class="descname">results</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#trace.Trace.results" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#trace.CoverageResults" title="trace.CoverageResults"><code class="xref py py-class docutils literal notranslate"><span class="pre">CoverageResults</span></code></a> object that contains the cumulative
results of all previous calls to <code class="docutils literal notranslate"><span class="pre">run</span></code>, <code class="docutils literal notranslate"><span class="pre">runctx</span></code> and <code class="docutils literal notranslate"><span class="pre">runfunc</span></code>
for the given <a class="reference internal" href="#trace.Trace" title="trace.Trace"><code class="xref py py-class docutils literal notranslate"><span class="pre">Trace</span></code></a> instance.  Does not reset the accumulated
trace results.</p>
</dd></dl>

</div></blockquote>
</dd></dl>

<dl class="class">
<dt id="trace.CoverageResults">
<em class="property">class </em><code class="descclassname">trace.</code><code class="descname">CoverageResults</code><a class="headerlink" href="#trace.CoverageResults" title="Permalink to this definition">¶</a></dt>
<dd><p>A container for coverage results, created by <a class="reference internal" href="#trace.Trace.results" title="trace.Trace.results"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Trace.results()</span></code></a>.  Should
not be created directly by the user.</p>
<blockquote>
<div><dl class="method">
<dt id="trace.CoverageResults.update">
<code class="descname">update</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#trace.CoverageResults.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Merge in data from another <a class="reference internal" href="#trace.CoverageResults" title="trace.CoverageResults"><code class="xref py py-class docutils literal notranslate"><span class="pre">CoverageResults</span></code></a> object.</p>
</dd></dl>

<dl class="method">
<dt id="trace.CoverageResults.write_results">
<code class="descname">write_results</code><span class="sig-paren">(</span><span class="optional">[</span><em>show_missing=True</em><span class="optional">[</span>, <em>summary=False</em><span class="optional">[</span>, <em>coverdir=None</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#trace.CoverageResults.write_results" title="Permalink to this definition">¶</a></dt>
<dd><p>Write coverage results.  Set <em>show_missing</em> to show lines that had no
hits.  Set <em>summary</em> to include in the output the coverage summary per
module.  <em>coverdir</em> specifies the directory into which the coverage
result files will be output.  If <code class="docutils literal notranslate"><span class="pre">None</span></code>, the results for each source
file are placed in its directory.</p>
</dd></dl>

</div></blockquote>
</dd></dl>

<p>A simple example demonstrating the use of the programmatic interface:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">trace</span>

<span class="c1"># create a Trace object, telling it what to ignore, and whether to</span>
<span class="c1"># do tracing or line-counting or both.</span>
<span class="n">tracer</span> <span class="o">=</span> <span class="n">trace</span><span class="o">.</span><span class="n">Trace</span><span class="p">(</span>
    <span class="n">ignoredirs</span><span class="o">=</span><span class="p">[</span><span class="n">sys</span><span class="o">.</span><span class="n">prefix</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">exec_prefix</span><span class="p">],</span>
    <span class="n">trace</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
    <span class="n">count</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>

<span class="c1"># run the new command using the given tracer</span>
<span class="n">tracer</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="s1">&#39;main()&#39;</span><span class="p">)</span>

<span class="c1"># make a report, placing output in the current directory</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">tracer</span><span class="o">.</span><span class="n">results</span><span class="p">()</span>
<span class="n">r</span><span class="o">.</span><span class="n">write_results</span><span class="p">(</span><span class="n">show_missing</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">coverdir</span><span class="o">=</span><span class="s2">&quot;.&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a><ul>
<li><a class="reference internal" href="#command-line-usage">26.7.1. Command-Line Usage</a><ul>
<li><a class="reference internal" href="#main-options">26.7.1.1. Main options</a></li>
<li><a class="reference internal" href="#modifiers">26.7.1.2. Modifiers</a></li>
<li><a class="reference internal" href="#filters">26.7.1.3. Filters</a></li>
</ul>
</li>
<li><a class="reference internal" href="#programmatic-interface">26.7.2. Programmatic Interface</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="timeit.html"
                        title="previous chapter">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="distribution.html"
                        title="next chapter">27. Software Packaging and Distribution</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/trace.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="distribution.html" title="27. Software Packaging and Distribution"
             >next</a> |</li>
        <li class="right" >
          <a href="timeit.html" title="26.6. timeit — Measure execution time of small code snippets"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="debug.html" >26. Debugging and Profiling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\lŨ;ğğhtml/library/traceback.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.10. traceback — Print or retrieve a stack traceback &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.11. __future__ — Future statement definitions" href="__future__.html" />
    <link rel="prev" title="28.9. atexit — Exit handlers" href="atexit.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/traceback.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__future__.html" title="28.11. __future__ — Future statement definitions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="atexit.html" title="28.9. atexit — Exit handlers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-traceback">
<span id="traceback-print-or-retrieve-a-stack-traceback"></span><h1>28.10. <a class="reference internal" href="#module-traceback" title="traceback: Print or retrieve a stack traceback."><code class="xref py py-mod docutils literal notranslate"><span class="pre">traceback</span></code></a> — Print or retrieve a stack traceback<a class="headerlink" href="#module-traceback" title="Permalink to this headline">¶</a></h1>
<p>This module provides a standard interface to extract, format and print stack
traces of Python programs.  It exactly mimics the behavior of the Python
interpreter when it prints a stack trace.  This is useful when you want to print
stack traces under program control, such as in a “wrapper” around the
interpreter.</p>
<p id="index-0">The module uses traceback objects — this is the object type that is stored in
the variables <a class="reference internal" href="sys.html#sys.exc_traceback" title="sys.exc_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code></a> (deprecated) and
<a class="reference internal" href="sys.html#sys.last_traceback" title="sys.last_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_traceback</span></code></a> and returned as the third item from
<a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.</p>
<p>The module defines the following functions:</p>
<dl class="function">
<dt id="traceback.print_tb">
<code class="descclassname">traceback.</code><code class="descname">print_tb</code><span class="sig-paren">(</span><em>tb</em><span class="optional">[</span>, <em>limit</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.print_tb" title="Permalink to this definition">¶</a></dt>
<dd><p>Print up to <em>limit</em> stack trace entries from the traceback object <em>tb</em>. If
<em>limit</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, all entries are printed. If <em>file</em> is omitted
or <code class="docutils literal notranslate"><span class="pre">None</span></code>, the output goes to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>; otherwise it should be an
open file or file-like object to receive the output.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.print_exception">
<code class="descclassname">traceback.</code><code class="descname">print_exception</code><span class="sig-paren">(</span><em>etype</em>, <em>value</em>, <em>tb</em><span class="optional">[</span>, <em>limit</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.print_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Print exception information and up to <em>limit</em> stack trace entries from the
traceback <em>tb</em> to <em>file</em>. This differs from <a class="reference internal" href="#traceback.print_tb" title="traceback.print_tb"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_tb()</span></code></a> in the following
ways: (1) if <em>tb</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it prints a header <code class="docutils literal notranslate"><span class="pre">Traceback</span> <span class="pre">(most</span>
<span class="pre">recent</span> <span class="pre">call</span> <span class="pre">last):</span></code>; (2) it prints the exception <em>etype</em> and <em>value</em> after
the stack trace; (3) if <em>etype</em> is <a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> and <em>value</em> has the
appropriate format, it prints the line where the syntax error occurred with a
caret indicating the approximate position of the error.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.print_exc">
<code class="descclassname">traceback.</code><code class="descname">print_exc</code><span class="sig-paren">(</span><span class="optional">[</span><em>limit</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.print_exc" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">print_exception(sys.exc_type,</span> <span class="pre">sys.exc_value,</span>
<span class="pre">sys.exc_traceback,</span> <span class="pre">limit,</span> <span class="pre">file)</span></code>.  (In fact, it uses <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> to
retrieve the same information in a thread-safe way instead of using the
deprecated variables.)</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_exc">
<code class="descclassname">traceback.</code><code class="descname">format_exc</code><span class="sig-paren">(</span><span class="optional">[</span><em>limit</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_exc" title="Permalink to this definition">¶</a></dt>
<dd><p>This is like <code class="docutils literal notranslate"><span class="pre">print_exc(limit)</span></code> but returns a string instead of printing to
a file.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="traceback.print_last">
<code class="descclassname">traceback.</code><code class="descname">print_last</code><span class="sig-paren">(</span><span class="optional">[</span><em>limit</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.print_last" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a shorthand for <code class="docutils literal notranslate"><span class="pre">print_exception(sys.last_type,</span> <span class="pre">sys.last_value,</span>
<span class="pre">sys.last_traceback,</span> <span class="pre">limit,</span> <span class="pre">file)</span></code>.  In general it will work only after
an exception has reached an interactive prompt (see <a class="reference internal" href="sys.html#sys.last_type" title="sys.last_type"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_type</span></code></a>).</p>
</dd></dl>

<dl class="function">
<dt id="traceback.print_stack">
<code class="descclassname">traceback.</code><code class="descname">print_stack</code><span class="sig-paren">(</span><span class="optional">[</span><em>f</em><span class="optional">[</span>, <em>limit</em><span class="optional">[</span>, <em>file</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.print_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>This function prints a stack trace from its invocation point. The optional
<em>f</em> argument can be used to specify an alternate stack frame to start. The
optional <em>limit</em> and <em>file</em> arguments have the same meaning as for
<a class="reference internal" href="#traceback.print_exception" title="traceback.print_exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_exception()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.extract_tb">
<code class="descclassname">traceback.</code><code class="descname">extract_tb</code><span class="sig-paren">(</span><em>tb</em><span class="optional">[</span>, <em>limit</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.extract_tb" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of up to <em>limit</em> “pre-processed” stack trace entries extracted
from the traceback object <em>tb</em>.  It is useful for alternate formatting of
stack traces.  If <em>limit</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, all entries are extracted.
A “pre-processed” stack trace entry is a 4-tuple (<em>filename</em>, <em>line number</em>,
function name*, <em>text</em>) representing the information that is usually printed
for a stack trace.  The <em>text</em> is a string with leading and trailing
whitespace stripped; if the source is not available it is <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.extract_stack">
<code class="descclassname">traceback.</code><code class="descname">extract_stack</code><span class="sig-paren">(</span><span class="optional">[</span><em>f</em><span class="optional">[</span>, <em>limit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.extract_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract the raw traceback from the current stack frame.  The return value has
the same format as for <a class="reference internal" href="#traceback.extract_tb" title="traceback.extract_tb"><code class="xref py py-func docutils literal notranslate"><span class="pre">extract_tb()</span></code></a>.  The optional <em>f</em> and <em>limit</em>
arguments have the same meaning as for <a class="reference internal" href="#traceback.print_stack" title="traceback.print_stack"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_stack()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_list">
<code class="descclassname">traceback.</code><code class="descname">format_list</code><span class="sig-paren">(</span><em>extracted_list</em><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_list" title="Permalink to this definition">¶</a></dt>
<dd><p>Given a list of tuples as returned by <a class="reference internal" href="#traceback.extract_tb" title="traceback.extract_tb"><code class="xref py py-func docutils literal notranslate"><span class="pre">extract_tb()</span></code></a> or
<a class="reference internal" href="#traceback.extract_stack" title="traceback.extract_stack"><code class="xref py py-func docutils literal notranslate"><span class="pre">extract_stack()</span></code></a>, return a list of strings ready for printing.  Each
string in the resulting list corresponds to the item with the same index in
the argument list.  Each string ends in a newline; the strings may contain
internal newlines as well, for those items whose source text line is not
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_exception_only">
<code class="descclassname">traceback.</code><code class="descname">format_exception_only</code><span class="sig-paren">(</span><em>etype</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_exception_only" title="Permalink to this definition">¶</a></dt>
<dd><p>Format the exception part of a traceback.  The arguments are the exception
type, <em>etype</em> and <em>value</em> such as given by <code class="docutils literal notranslate"><span class="pre">sys.last_type</span></code> and
<code class="docutils literal notranslate"><span class="pre">sys.last_value</span></code>.  The return value is a list of strings, each ending in a
newline.  Normally, the list contains a single string; however, for
<a class="reference internal" href="exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> exceptions, it contains several lines that (when printed)
display detailed information about where the syntax error occurred.  The
message indicating which exception occurred is the always last string in the
list.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_exception">
<code class="descclassname">traceback.</code><code class="descname">format_exception</code><span class="sig-paren">(</span><em>etype</em>, <em>value</em>, <em>tb</em><span class="optional">[</span>, <em>limit</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Format a stack trace and the exception information.  The arguments  have the
same meaning as the corresponding arguments to <a class="reference internal" href="#traceback.print_exception" title="traceback.print_exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_exception()</span></code></a>.  The
return value is a list of strings, each ending in a newline and some
containing internal newlines.  When these lines are concatenated and printed,
exactly the same text is printed as does <a class="reference internal" href="#traceback.print_exception" title="traceback.print_exception"><code class="xref py py-func docutils literal notranslate"><span class="pre">print_exception()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_tb">
<code class="descclassname">traceback.</code><code class="descname">format_tb</code><span class="sig-paren">(</span><em>tb</em><span class="optional">[</span>, <em>limit</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_tb" title="Permalink to this definition">¶</a></dt>
<dd><p>A shorthand for <code class="docutils literal notranslate"><span class="pre">format_list(extract_tb(tb,</span> <span class="pre">limit))</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.format_stack">
<code class="descclassname">traceback.</code><code class="descname">format_stack</code><span class="sig-paren">(</span><span class="optional">[</span><em>f</em><span class="optional">[</span>, <em>limit</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#traceback.format_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>A shorthand for <code class="docutils literal notranslate"><span class="pre">format_list(extract_stack(f,</span> <span class="pre">limit))</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="traceback.tb_lineno">
<code class="descclassname">traceback.</code><code class="descname">tb_lineno</code><span class="sig-paren">(</span><em>tb</em><span class="sig-paren">)</span><a class="headerlink" href="#traceback.tb_lineno" title="Permalink to this definition">¶</a></dt>
<dd><p>This function returns the current line number set in the traceback object.
This function was necessary because in versions of Python prior to 2.3 when
the <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> flag was passed to Python the <code class="docutils literal notranslate"><span class="pre">tb.tb_lineno</span></code> was not
updated correctly.  This function has no use in versions past 2.3.</p>
</dd></dl>

<div class="section" id="traceback-examples">
<span id="traceback-example"></span><h2>28.10.1. Traceback Examples<a class="headerlink" href="#traceback-examples" title="Permalink to this headline">¶</a></h2>
<p>This simple example implements a basic read-eval-print loop, similar to (but
less useful than) the standard Python interactive interpreter loop.  For a more
complete implementation of the interpreter loop, refer to the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-mod docutils literal notranslate"><span class="pre">code</span></code></a>
module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">traceback</span>

<span class="k">def</span> <span class="nf">run_user_code</span><span class="p">(</span><span class="n">envdir</span><span class="p">):</span>
    <span class="n">source</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;&gt;&gt;&gt; &quot;</span><span class="p">)</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">exec</span> <span class="n">source</span> <span class="ow">in</span> <span class="n">envdir</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;Exception in user code:&quot;</span>
        <span class="nb">print</span> <span class="s1">&#39;-&#39;</span><span class="o">*</span><span class="mi">60</span>
        <span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">(</span><span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
        <span class="nb">print</span> <span class="s1">&#39;-&#39;</span><span class="o">*</span><span class="mi">60</span>

<span class="n">envdir</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">while</span> <span class="mi">1</span><span class="p">:</span>
    <span class="n">run_user_code</span><span class="p">(</span><span class="n">envdir</span><span class="p">)</span>
</pre></div>
</div>
<p>The following example demonstrates the different ways to print and format the
exception and traceback:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">traceback</span>

<span class="k">def</span> <span class="nf">lumberjack</span><span class="p">():</span>
    <span class="n">bright_side_of_death</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">bright_side_of_death</span><span class="p">():</span>
    <span class="k">return</span> <span class="nb">tuple</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">lumberjack</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">IndexError</span><span class="p">:</span>
    <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_traceback</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s2">&quot;*** print_tb:&quot;</span>
    <span class="n">traceback</span><span class="o">.</span><span class="n">print_tb</span><span class="p">(</span><span class="n">exc_traceback</span><span class="p">,</span> <span class="n">limit</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s2">&quot;*** print_exception:&quot;</span>
    <span class="n">traceback</span><span class="o">.</span><span class="n">print_exception</span><span class="p">(</span><span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span> <span class="n">exc_traceback</span><span class="p">,</span>
                              <span class="n">limit</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s2">&quot;*** print_exc:&quot;</span>
    <span class="n">traceback</span><span class="o">.</span><span class="n">print_exc</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s2">&quot;*** format_exc, first and last line:&quot;</span>
    <span class="n">formatted_lines</span> <span class="o">=</span> <span class="n">traceback</span><span class="o">.</span><span class="n">format_exc</span><span class="p">()</span><span class="o">.</span><span class="n">splitlines</span><span class="p">()</span>
    <span class="nb">print</span> <span class="n">formatted_lines</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="nb">print</span> <span class="n">formatted_lines</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
    <span class="nb">print</span> <span class="s2">&quot;*** format_exception:&quot;</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">format_exception</span><span class="p">(</span><span class="n">exc_type</span><span class="p">,</span> <span class="n">exc_value</span><span class="p">,</span>
                                          <span class="n">exc_traceback</span><span class="p">))</span>
    <span class="nb">print</span> <span class="s2">&quot;*** extract_tb:&quot;</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">extract_tb</span><span class="p">(</span><span class="n">exc_traceback</span><span class="p">))</span>
    <span class="nb">print</span> <span class="s2">&quot;*** format_tb:&quot;</span>
    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">format_tb</span><span class="p">(</span><span class="n">exc_traceback</span><span class="p">))</span>
    <span class="nb">print</span> <span class="s2">&quot;*** tb_lineno:&quot;</span><span class="p">,</span> <span class="n">exc_traceback</span><span class="o">.</span><span class="n">tb_lineno</span>
</pre></div>
</div>
<p>The output for the example would look similar to this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">***</span> <span class="n">print_tb</span><span class="p">:</span>
  <span class="n">File</span> <span class="s2">&quot;&lt;doctest...&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">10</span><span class="p">,</span> <span class="ow">in</span> <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span>
    <span class="n">lumberjack</span><span class="p">()</span>
<span class="o">***</span> <span class="n">print_exception</span><span class="p">:</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
  <span class="n">File</span> <span class="s2">&quot;&lt;doctest...&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">10</span><span class="p">,</span> <span class="ow">in</span> <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span>
    <span class="n">lumberjack</span><span class="p">()</span>
  <span class="n">File</span> <span class="s2">&quot;&lt;doctest...&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">4</span><span class="p">,</span> <span class="ow">in</span> <span class="n">lumberjack</span>
    <span class="n">bright_side_of_death</span><span class="p">()</span>
<span class="ne">IndexError</span><span class="p">:</span> <span class="nb">tuple</span> <span class="n">index</span> <span class="n">out</span> <span class="n">of</span> <span class="nb">range</span>
<span class="o">***</span> <span class="n">print_exc</span><span class="p">:</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
  <span class="n">File</span> <span class="s2">&quot;&lt;doctest...&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">10</span><span class="p">,</span> <span class="ow">in</span> <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span>
    <span class="n">lumberjack</span><span class="p">()</span>
  <span class="n">File</span> <span class="s2">&quot;&lt;doctest...&gt;&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">4</span><span class="p">,</span> <span class="ow">in</span> <span class="n">lumberjack</span>
    <span class="n">bright_side_of_death</span><span class="p">()</span>
<span class="ne">IndexError</span><span class="p">:</span> <span class="nb">tuple</span> <span class="n">index</span> <span class="n">out</span> <span class="n">of</span> <span class="nb">range</span>
<span class="o">***</span> <span class="n">format_exc</span><span class="p">,</span> <span class="n">first</span> <span class="ow">and</span> <span class="n">last</span> <span class="n">line</span><span class="p">:</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
<span class="ne">IndexError</span><span class="p">:</span> <span class="nb">tuple</span> <span class="n">index</span> <span class="n">out</span> <span class="n">of</span> <span class="nb">range</span>
<span class="o">***</span> <span class="n">format_exception</span><span class="p">:</span>
<span class="p">[</span><span class="s1">&#39;Traceback (most recent call last):</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 10, in &lt;module&gt;</span><span class="se">\n</span><span class="s1">    lumberjack()</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 4, in lumberjack</span><span class="se">\n</span><span class="s1">    bright_side_of_death()</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 7, in bright_side_of_death</span><span class="se">\n</span><span class="s1">    return tuple()[0]</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;IndexError: tuple index out of range</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="o">***</span> <span class="n">extract_tb</span><span class="p">:</span>
<span class="p">[(</span><span class="s1">&#39;&lt;doctest...&gt;&#39;</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="s1">&#39;&lt;module&gt;&#39;</span><span class="p">,</span> <span class="s1">&#39;lumberjack()&#39;</span><span class="p">),</span>
 <span class="p">(</span><span class="s1">&#39;&lt;doctest...&gt;&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;lumberjack&#39;</span><span class="p">,</span> <span class="s1">&#39;bright_side_of_death()&#39;</span><span class="p">),</span>
 <span class="p">(</span><span class="s1">&#39;&lt;doctest...&gt;&#39;</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;bright_side_of_death&#39;</span><span class="p">,</span> <span class="s1">&#39;return tuple()[0]&#39;</span><span class="p">)]</span>
<span class="o">***</span> <span class="n">format_tb</span><span class="p">:</span>
<span class="p">[</span><span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 10, in &lt;module&gt;</span><span class="se">\n</span><span class="s1">    lumberjack()</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 4, in lumberjack</span><span class="se">\n</span><span class="s1">    bright_side_of_death()</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span>
 <span class="s1">&#39;  File &quot;&lt;doctest...&gt;&quot;, line 7, in bright_side_of_death</span><span class="se">\n</span><span class="s1">    return tuple()[0]</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">]</span>
<span class="o">***</span> <span class="n">tb_lineno</span><span class="p">:</span> <span class="mi">10</span>
</pre></div>
</div>
<p>The following example shows the different ways to print and format the stack:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">traceback</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">another_function</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">lumberstack</span><span class="p">()</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">lumberstack</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">traceback</span><span class="o">.</span><span class="n">print_stack</span><span class="p">()</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">extract_stack</span><span class="p">())</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">format_stack</span><span class="p">())</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">another_function</span><span class="p">()</span>
<span class="go">  File &quot;&lt;doctest&gt;&quot;, line 10, in &lt;module&gt;</span>
<span class="go">    another_function()</span>
<span class="go">  File &quot;&lt;doctest&gt;&quot;, line 3, in another_function</span>
<span class="go">    lumberstack()</span>
<span class="go">  File &quot;&lt;doctest&gt;&quot;, line 6, in lumberstack</span>
<span class="go">    traceback.print_stack()</span>
<span class="go">[(&#39;&lt;doctest&gt;&#39;, 10, &#39;&lt;module&gt;&#39;, &#39;another_function()&#39;),</span>
<span class="go"> (&#39;&lt;doctest&gt;&#39;, 3, &#39;another_function&#39;, &#39;lumberstack()&#39;),</span>
<span class="go"> (&#39;&lt;doctest&gt;&#39;, 7, &#39;lumberstack&#39;, &#39;print repr(traceback.extract_stack())&#39;)]</span>
<span class="go">[&#39;  File &quot;&lt;doctest&gt;&quot;, line 10, in &lt;module&gt;\n    another_function()\n&#39;,</span>
<span class="go"> &#39;  File &quot;&lt;doctest&gt;&quot;, line 3, in another_function\n    lumberstack()\n&#39;,</span>
<span class="go"> &#39;  File &quot;&lt;doctest&gt;&quot;, line 8, in lumberstack\n    print repr(traceback.format_stack())\n&#39;]</span>
</pre></div>
</div>
<p>This last example demonstrates the final few formatting functions:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">traceback</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">traceback</span><span class="o">.</span><span class="n">format_list</span><span class="p">([(</span><span class="s1">&#39;spam.py&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;&lt;module&gt;&#39;</span><span class="p">,</span> <span class="s1">&#39;spam.eggs()&#39;</span><span class="p">),</span>
<span class="gp">... </span>                       <span class="p">(</span><span class="s1">&#39;eggs.py&#39;</span><span class="p">,</span> <span class="mi">42</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">,</span> <span class="s1">&#39;return &quot;bacon&quot;&#39;</span><span class="p">)])</span>
<span class="go">[&#39;  File &quot;spam.py&quot;, line 3, in &lt;module&gt;\n    spam.eggs()\n&#39;,</span>
<span class="go"> &#39;  File &quot;eggs.py&quot;, line 42, in eggs\n    return &quot;bacon&quot;\n&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">an_error</span> <span class="o">=</span> <span class="ne">IndexError</span><span class="p">(</span><span class="s1">&#39;tuple index out of range&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">traceback</span><span class="o">.</span><span class="n">format_exception_only</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">an_error</span><span class="p">),</span> <span class="n">an_error</span><span class="p">)</span>
<span class="go">[&#39;IndexError: tuple index out of range\n&#39;]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a><ul>
<li><a class="reference internal" href="#traceback-examples">28.10.1. Traceback Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="atexit.html"
                        title="previous chapter">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="__future__.html"
                        title="next chapter">28.11. <code class="docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/traceback.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="__future__.html" title="28.11. __future__ — Future statement definitions"
             >next</a> |</li>
        <li class="right" >
          <a href="atexit.html" title="28.9. atexit — Exit handlers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����html/library/ttk.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.2. ttk — Tk themed widgets &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.3. Tix — Extension widgets for Tk" href="tix.html" />
    <link rel="prev" title="24.1. Tkinter — Python interface to Tcl/Tk" href="tkinter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/ttk.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tix.html" title="24.3. Tix — Extension widgets for Tk"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="tkinter.html" title="24.1. Tkinter — Python interface to Tcl/Tk"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-ttk">
<span id="ttk-tk-themed-widgets"></span><h1>24.2. <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> — Tk themed widgets<a class="headerlink" href="#module-ttk" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> module provides access to the Tk themed widget set, which has
been introduced in Tk 8.5. If Python is not compiled against Tk 8.5 code may
still use this module as long as Tile is installed. However, some features
provided by the new Tk, like anti-aliased font rendering under X11, window
transparency (on X11 you will need a composition window manager) will be
missing.</p>
<p>The basic idea of <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> is to separate, to the extent possible, the code
implementing a widget’s behavior from the code implementing its appearance.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.tcl.tk/cgi-bin/tct/tip/48">Tk Widget Styling Support</a></dt>
<dd>The document which brought up theming support for Tk</dd>
</dl>
</div>
<div class="section" id="using-ttk">
<h2>24.2.1. Using Ttk<a class="headerlink" href="#using-ttk" title="Permalink to this headline">¶</a></h2>
<p>To start using Ttk, import its module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ttk</span>
</pre></div>
</div>
<p>But code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Tkinter</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<p>may optionally want to use this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">Tkinter</span> <span class="k">import</span> <span class="o">*</span>
<span class="kn">from</span> <span class="nn">ttk</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<p>And then several <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> widgets (<code class="xref py py-class docutils literal notranslate"><span class="pre">Button</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Checkbutton</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Entry</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Frame</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Label</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">LabelFrame</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Menubutton</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">PanedWindow</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Radiobutton</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Scale</span></code>
and <code class="xref py py-class docutils literal notranslate"><span class="pre">Scrollbar</span></code>) will automatically substitute for the Tk widgets.</p>
<p>This has the direct benefit of using the new widgets, giving better look &amp; feel
across platforms, but be aware that they are not totally compatible. The main
difference is that widget options such as “fg”, “bg” and others related to
widget styling are no longer present in Ttk widgets. Use <a class="reference internal" href="#ttk.Style" title="ttk.Style"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Style</span></code></a> to
achieve the same (or better) styling.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://tktable.sourceforge.net/tile/doc/converting.txt">Converting existing applications to use the Tile widgets</a></dt>
<dd>A text which talks in Tcl terms about differences typically found when
converting applications to use the new widgets.</dd>
</dl>
</div>
</div>
<div class="section" id="ttk-widgets">
<h2>24.2.2. Ttk Widgets<a class="headerlink" href="#ttk-widgets" title="Permalink to this headline">¶</a></h2>
<p>Ttk comes with 17 widgets, 11 of which already exist in Tkinter:
<code class="xref py py-class docutils literal notranslate"><span class="pre">Button</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Checkbutton</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Entry</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Frame</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Label</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">LabelFrame</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Menubutton</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">PanedWindow</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Radiobutton</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Scale</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">Scrollbar</span></code>. The 6 new widget classes are: <a class="reference internal" href="#ttk.Combobox" title="ttk.Combobox"><code class="xref py py-class docutils literal notranslate"><span class="pre">Combobox</span></code></a>,
<a class="reference internal" href="#ttk.Notebook" title="ttk.Notebook"><code class="xref py py-class docutils literal notranslate"><span class="pre">Notebook</span></code></a>, <a class="reference internal" href="#ttk.Progressbar" title="ttk.Progressbar"><code class="xref py py-class docutils literal notranslate"><span class="pre">Progressbar</span></code></a>, <code class="xref py py-class docutils literal notranslate"><span class="pre">Separator</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Sizegrip</span></code> and <a class="reference internal" href="#ttk.Treeview" title="ttk.Treeview"><code class="xref py py-class docutils literal notranslate"><span class="pre">Treeview</span></code></a>.  All of these classes are
subclasses of <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">Widget</span></code></a>.</p>
<p>As said previously, you will notice changes in look-and-feel as well in the
styling code. To demonstrate the latter, a very simple example is shown below.</p>
<p>Tk code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">l1</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Label</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">,</span> <span class="n">fg</span><span class="o">=</span><span class="s2">&quot;black&quot;</span><span class="p">,</span> <span class="n">bg</span><span class="o">=</span><span class="s2">&quot;white&quot;</span><span class="p">)</span>
<span class="n">l2</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Label</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">,</span> <span class="n">fg</span><span class="o">=</span><span class="s2">&quot;black&quot;</span><span class="p">,</span> <span class="n">bg</span><span class="o">=</span><span class="s2">&quot;white&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Corresponding Ttk code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">style</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span>
<span class="n">style</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="s2">&quot;BW.TLabel&quot;</span><span class="p">,</span> <span class="n">foreground</span><span class="o">=</span><span class="s2">&quot;black&quot;</span><span class="p">,</span> <span class="n">background</span><span class="o">=</span><span class="s2">&quot;white&quot;</span><span class="p">)</span>

<span class="n">l1</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Label</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">,</span> <span class="n">style</span><span class="o">=</span><span class="s2">&quot;BW.TLabel&quot;</span><span class="p">)</span>
<span class="n">l2</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Label</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">,</span> <span class="n">style</span><span class="o">=</span><span class="s2">&quot;BW.TLabel&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>For more information about <a class="reference internal" href="#ttkstyling">TtkStyling</a> read the <a class="reference internal" href="#ttk.Style" title="ttk.Style"><code class="xref py py-class docutils literal notranslate"><span class="pre">Style</span></code></a> class
documentation.</p>
</div>
<div class="section" id="widget">
<h2>24.2.3. Widget<a class="headerlink" href="#widget" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Widget</span></code></a> defines standard options and methods supported by Tk
themed widgets and is not supposed to be directly instantiated.</p>
<div class="section" id="standard-options">
<h3>24.2.3.1. Standard Options<a class="headerlink" href="#standard-options" title="Permalink to this headline">¶</a></h3>
<p>All the <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> widgets accept the following options:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Option</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>class</td>
<td>Specifies the window class. The class is used when querying
the option database for the window’s other options, to
determine the default bindtags for the window, and to select
the widget’s default layout and style. This is a read-only
option which may only be specified when the window is
created.</td>
</tr>
<tr class="row-odd"><td>cursor</td>
<td>Specifies the mouse cursor to be used for the widget. If set
to the empty string (the default), the cursor is inherited
from the parent widget.</td>
</tr>
<tr class="row-even"><td>takefocus</td>
<td>Determines whether the window accepts the focus during
keyboard traversal. 0, 1 or an empty string is returned.
If 0, the window should be skipped entirely
during keyboard traversal. If 1, the window
should receive the input focus as long as it is viewable.
An empty string means that the traversal scripts make the
decision about whether or not to focus on the window.</td>
</tr>
<tr class="row-odd"><td>style</td>
<td>May be used to specify a custom widget style.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="scrollable-widget-options">
<h3>24.2.3.2. Scrollable Widget Options<a class="headerlink" href="#scrollable-widget-options" title="Permalink to this headline">¶</a></h3>
<p>The following options are supported by widgets that are controlled by a
scrollbar.</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>xscrollcommand</td>
<td><p class="first">Used to communicate with horizontal scrollbars.</p>
<p>When the view in the widget’s window changes, the widget
will generate a Tcl command based on the scrollcommand.</p>
<p class="last">Usually this option consists of the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Scrollbar.set()</span></code> method of some scrollbar. This
will cause
the scrollbar to be updated whenever the view in the
window changes.</p>
</td>
</tr>
<tr class="row-odd"><td>yscrollcommand</td>
<td>Used to communicate with vertical scrollbars.
For more information, see above.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="label-options">
<h3>24.2.3.3. Label Options<a class="headerlink" href="#label-options" title="Permalink to this headline">¶</a></h3>
<p>The following options are supported by labels, buttons and other button-like
widgets.</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="19%" />
<col width="81%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>text</td>
<td>Specifies a text string to be displayed inside the widget.</td>
</tr>
<tr class="row-odd"><td>textvariable</td>
<td>Specifies a name whose value will be used in place of the
text option resource.</td>
</tr>
<tr class="row-even"><td>underline</td>
<td>If set, specifies the index (0-based) of a character to
underline in the text string. The underline character is
used for mnemonic activation.</td>
</tr>
<tr class="row-odd"><td>image</td>
<td>Specifies an image to display. This is a list of 1 or more
elements. The first element is the default image name. The
rest of the list is a sequence of statespec/value pairs as
defined by <a class="reference internal" href="#ttk.Style.map" title="ttk.Style.map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Style.map()</span></code></a>, specifying different images
to use when the widget is in a particular state or a
combination of states. All images in the list should have
the same size.</td>
</tr>
<tr class="row-even"><td>compound</td>
<td><p class="first">Specifies how to display the image relative to the text,
in the case both text and image options are present.
Valid values are:</p>
<ul class="last simple">
<li>text: display text only</li>
<li>image: display image only</li>
<li>top, bottom, left, right: display image above, below,
left of, or right of the text, respectively.</li>
<li>none: the default. display the image if present,
otherwise the text.</li>
</ul>
</td>
</tr>
<tr class="row-odd"><td>width</td>
<td>If greater than zero, specifies how much space, in
character widths, to allocate for the text label; if less
than zero, specifies a minimum width. If zero or
unspecified, the natural width of the text label is used.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="compatibility-options">
<h3>24.2.3.4. Compatibility Options<a class="headerlink" href="#compatibility-options" title="Permalink to this headline">¶</a></h3>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="11%" />
<col width="89%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>state</td>
<td>May be set to “normal” or “disabled” to control the “disabled”
state bit. This is a write-only option: setting it changes the
widget state, but the <a class="reference internal" href="#ttk.Widget.state" title="ttk.Widget.state"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.state()</span></code></a> method does not
affect this option.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="widget-states">
<h3>24.2.3.5. Widget States<a class="headerlink" href="#widget-states" title="Permalink to this headline">¶</a></h3>
<p>The widget state is a bitmap of independent state flags.</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="16%" />
<col width="84%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">flag</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>active</td>
<td>The mouse cursor is over the widget and pressing a mouse
button will cause some action to occur.</td>
</tr>
<tr class="row-odd"><td>disabled</td>
<td>Widget is disabled under program control.</td>
</tr>
<tr class="row-even"><td>focus</td>
<td>Widget has keyboard focus.</td>
</tr>
<tr class="row-odd"><td>pressed</td>
<td>Widget is being pressed.</td>
</tr>
<tr class="row-even"><td>selected</td>
<td>“On”, “true”, or “current” for things like Checkbuttons and
radiobuttons.</td>
</tr>
<tr class="row-odd"><td>background</td>
<td>Windows and Mac have a notion of an “active” or foreground
window. The <em>background</em> state is set for widgets in a
background window, and cleared for those in the foreground
window.</td>
</tr>
<tr class="row-even"><td>readonly</td>
<td>Widget should not allow user modification.</td>
</tr>
<tr class="row-odd"><td>alternate</td>
<td>A widget-specific alternate display format.</td>
</tr>
<tr class="row-even"><td>invalid</td>
<td>The widget’s value is invalid.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>A state specification is a sequence of state names, optionally prefixed with
an exclamation point indicating that the bit is off.</p>
</div>
<div class="section" id="ttk-widget">
<h3>24.2.3.6. ttk.Widget<a class="headerlink" href="#ttk-widget" title="Permalink to this headline">¶</a></h3>
<p>Besides the methods described below, the <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Widget</span></code></a> class supports the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Tkinter.Widget.cget()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">Tkinter.Widget.configure()</span></code> methods.</p>
<dl class="class">
<dt id="ttk.Widget">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Widget</code><a class="headerlink" href="#ttk.Widget" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="ttk.Widget.identify">
<code class="descname">identify</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Widget.identify" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name of the element at position <em>x</em> <em>y</em>, or the empty string
if the point does not lie within any element.</p>
<p><em>x</em> and <em>y</em> are pixel coordinates relative to the widget.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Widget.instate">
<code class="descname">instate</code><span class="sig-paren">(</span><em>statespec</em>, <em>callback=None</em>, <em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Widget.instate" title="Permalink to this definition">¶</a></dt>
<dd><p>Test the widget’s state. If a callback is not specified, returns <code class="docutils literal notranslate"><span class="pre">True</span></code>
if the widget state matches <em>statespec</em> and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise. If callback
is specified then it is called with <em>args</em> if widget state matches
<em>statespec</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Widget.state">
<code class="descname">state</code><span class="sig-paren">(</span><span class="optional">[</span><em>statespec=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Widget.state" title="Permalink to this definition">¶</a></dt>
<dd><p>Modify or read widget state. If <em>statespec</em> is specified, sets the
widget state accordingly and returns a new <em>statespec</em> indicating
which flags were changed. If <em>statespec</em> is not specified, returns
the currently-enabled state flags.</p>
</dd></dl>

<p><em>statespec</em> will usually be a list or a tuple.</p>
</dd></dl>

</div>
</div>
<div class="section" id="combobox">
<h2>24.2.4. Combobox<a class="headerlink" href="#combobox" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#ttk.Combobox" title="ttk.Combobox"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Combobox</span></code></a> widget combines a text field with a pop-down list of
values. This widget is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Entry</span></code>.</p>
<p>Besides the methods inherited from <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">Widget</span></code></a> (<code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.cget()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.configure()</span></code>, <a class="reference internal" href="#ttk.Widget.identify" title="ttk.Widget.identify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.identify()</span></code></a>, <a class="reference internal" href="#ttk.Widget.instate" title="ttk.Widget.instate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.instate()</span></code></a>
and <a class="reference internal" href="#ttk.Widget.state" title="ttk.Widget.state"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.state()</span></code></a>) and those inherited from <code class="xref py py-class docutils literal notranslate"><span class="pre">Entry</span></code>
(<code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.bbox()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.delete()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.icursor()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.index()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.insert()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.selection()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Entry.xview()</span></code>), this class has some other methods, described at
<a class="reference internal" href="#ttk.Combobox" title="ttk.Combobox"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Combobox</span></code></a>.</p>
<div class="section" id="options">
<h3>24.2.4.1. Options<a class="headerlink" href="#options" title="Permalink to this headline">¶</a></h3>
<p>This widget accepts the following options:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="77%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>exportselection</td>
<td>Boolean value. If set, the widget selection is linked
to the Window Manager selection (which can be returned
by invoking <code class="xref py py-meth docutils literal notranslate"><span class="pre">Misc.selection_get()</span></code>, for example).</td>
</tr>
<tr class="row-odd"><td>justify</td>
<td>Specifies how the text is aligned within the widget.
One of “left”, “center”, or “right”.</td>
</tr>
<tr class="row-even"><td>height</td>
<td>Specifies the height of the pop-down listbox, in rows.</td>
</tr>
<tr class="row-odd"><td>postcommand</td>
<td>A script (possibly registered with
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Misc.register()</span></code>) that
is called immediately before displaying the values. It
may specify which values to display.</td>
</tr>
<tr class="row-even"><td>state</td>
<td>One of “normal”, “readonly”, or “disabled”. In the
“readonly” state, the value may not be edited directly,
and the user can only select one of the values from the
dropdown list. In the “normal” state, the text field is
directly editable. In the “disabled” state, no
interaction is possible.</td>
</tr>
<tr class="row-odd"><td>textvariable</td>
<td>Specifies a name whose value is linked to the widget
value. Whenever the value associated with that name
changes, the widget value is updated, and vice versa.
See <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.StringVar</span></code>.</td>
</tr>
<tr class="row-even"><td>values</td>
<td>Specifies the list of values to display in the
drop-down listbox.</td>
</tr>
<tr class="row-odd"><td>width</td>
<td>Specifies an integer value indicating the desired width
of the entry window, in average-size characters of the
widget’s font.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="virtual-events">
<h3>24.2.4.2. Virtual events<a class="headerlink" href="#virtual-events" title="Permalink to this headline">¶</a></h3>
<p>The combobox widget generates a <strong>&lt;&lt;ComboboxSelected&gt;&gt;</strong> virtual event
when the user selects an element from the list of values.</p>
</div>
<div class="section" id="ttk-combobox">
<h3>24.2.4.3. ttk.Combobox<a class="headerlink" href="#ttk-combobox" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ttk.Combobox">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Combobox</code><a class="headerlink" href="#ttk.Combobox" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="ttk.Combobox.current">
<code class="descname">current</code><span class="sig-paren">(</span><span class="optional">[</span><em>newindex=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Combobox.current" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>newindex</em> is specified, sets the combobox value to the element
position <em>newindex</em>. Otherwise, returns the index of the current value or
-1 if the current value is not in the values list.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Combobox.get">
<code class="descname">get</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Combobox.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current value of the combobox.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Combobox.set">
<code class="descname">set</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Combobox.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the value of the combobox to <em>value</em>.</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="notebook">
<h2>24.2.5. Notebook<a class="headerlink" href="#notebook" title="Permalink to this headline">¶</a></h2>
<p>The Ttk Notebook widget manages a collection of windows and displays a single
one at a time. Each child window is associated with a tab, which the user
may select to change the currently-displayed window.</p>
<div class="section" id="id1">
<h3>24.2.5.1. Options<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h3>
<p>This widget accepts the following specific options:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="12%" />
<col width="88%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>height</td>
<td>If present and greater than zero, specifies the desired height
of the pane area (not including internal padding or tabs).
Otherwise, the maximum height of all panes is used.</td>
</tr>
<tr class="row-odd"><td>padding</td>
<td>Specifies the amount of extra space to add around the outside
of the notebook. The padding is a list of up to four length
specifications: left top right bottom. If fewer than four
elements are specified, bottom defaults to top, right defaults
to left, and top defaults to left.</td>
</tr>
<tr class="row-even"><td>width</td>
<td>If present and greater than zero, specifies the desired width
of the pane area (not including internal padding). Otherwise,
the maximum width of all panes is used.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="tab-options">
<h3>24.2.5.2. Tab Options<a class="headerlink" href="#tab-options" title="Permalink to this headline">¶</a></h3>
<p>There are also specific options for tabs:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="15%" />
<col width="85%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>state</td>
<td>Either “normal”, “disabled” or “hidden”. If “disabled”, then
the tab is not selectable. If “hidden”, then the tab is not
shown.</td>
</tr>
<tr class="row-odd"><td>sticky</td>
<td>Specifies how the child window is positioned within the pane
area. Value is a string containing zero or more of the
characters “n”, “s”, “e” or “w”. Each letter refers to a
side (north, south, east or west) that the child window will
stick to, as per the <code class="xref py py-meth docutils literal notranslate"><span class="pre">grid()</span></code> geometry manager.</td>
</tr>
<tr class="row-even"><td>padding</td>
<td>Specifies the amount of extra space to add between the
notebook and this pane. Syntax is the same as for the option
padding used by this widget.</td>
</tr>
<tr class="row-odd"><td>text</td>
<td>Specifies a text to be displayed in the tab.</td>
</tr>
<tr class="row-even"><td>image</td>
<td>Specifies an image to display in the tab. See the option
image described in <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">Widget</span></code></a>.</td>
</tr>
<tr class="row-odd"><td>compound</td>
<td>Specifies how to display the image relative to the text, in
the case both text and image options are present. See
<a class="reference internal" href="#label-options">Label Options</a> for legal values.</td>
</tr>
<tr class="row-even"><td>underline</td>
<td>Specifies the index (0-based) of a character to underline in
the text string. The underlined character is used for
mnemonic activation if <a class="reference internal" href="#ttk.Notebook.enable_traversal" title="ttk.Notebook.enable_traversal"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Notebook.enable_traversal()</span></code></a> is
called.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="tab-identifiers">
<h3>24.2.5.3. Tab Identifiers<a class="headerlink" href="#tab-identifiers" title="Permalink to this headline">¶</a></h3>
<p>The <em>tab_id</em> present in several methods of <a class="reference internal" href="#ttk.Notebook" title="ttk.Notebook"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Notebook</span></code></a> may take any
of the following forms:</p>
<ul class="simple">
<li>An integer between zero and the number of tabs.</li>
<li>The name of a child window.</li>
<li>A positional specification of the form “&#64;x,y”, which identifies the tab.</li>
<li>The literal string “current”, which identifies the currently-selected tab.</li>
<li>The literal string “end”, which returns the number of tabs (only valid for
<a class="reference internal" href="#ttk.Notebook.index" title="ttk.Notebook.index"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Notebook.index()</span></code></a>).</li>
</ul>
</div>
<div class="section" id="id2">
<h3>24.2.5.4. Virtual Events<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h3>
<p>This widget generates a <strong>&lt;&lt;NotebookTabChanged&gt;&gt;</strong> virtual event after a new
tab is selected.</p>
</div>
<div class="section" id="ttk-notebook">
<h3>24.2.5.5. ttk.Notebook<a class="headerlink" href="#ttk-notebook" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ttk.Notebook">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Notebook</code><a class="headerlink" href="#ttk.Notebook" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="ttk.Notebook.add">
<code class="descname">add</code><span class="sig-paren">(</span><em>child</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.add" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds a new tab to the notebook.</p>
<p>If window is currently managed by the notebook but hidden, it is
restored to its previous position.</p>
<p>See <a class="reference internal" href="#tab-options">Tab Options</a> for the list of available options.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.forget">
<code class="descname">forget</code><span class="sig-paren">(</span><em>tab_id</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.forget" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes the tab specified by <em>tab_id</em>, unmaps and unmanages the
associated window.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.hide">
<code class="descname">hide</code><span class="sig-paren">(</span><em>tab_id</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.hide" title="Permalink to this definition">¶</a></dt>
<dd><p>Hides the tab specified by <em>tab_id</em>.</p>
<p>The tab will not be displayed, but the associated window remains
managed by the notebook and its configuration remembered. Hidden tabs
may be restored with the <a class="reference internal" href="#ttk.Notebook.add" title="ttk.Notebook.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a> command.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.identify">
<code class="descname">identify</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.identify" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name of the tab element at position <em>x</em>, <em>y</em>, or the empty
string if none.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.index">
<code class="descname">index</code><span class="sig-paren">(</span><em>tab_id</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the numeric index of the tab specified by <em>tab_id</em>, or the total
number of tabs if <em>tab_id</em> is the string “end”.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>pos</em>, <em>child</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.insert" title="Permalink to this definition">¶</a></dt>
<dd><p>Inserts a pane at the specified position.</p>
<p><em>pos</em> is either the string “end”, an integer index, or the name of a
managed child. If <em>child</em> is already managed by the notebook, moves it to
the specified position.</p>
<p>See <a class="reference internal" href="#tab-options">Tab Options</a> for the list of available options.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.select">
<code class="descname">select</code><span class="sig-paren">(</span><span class="optional">[</span><em>tab_id</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.select" title="Permalink to this definition">¶</a></dt>
<dd><p>Selects the specified <em>tab_id</em>.</p>
<p>The associated child window will be displayed, and the
previously-selected window (if different) is unmapped. If <em>tab_id</em> is
omitted, returns the widget name of the currently selected pane.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.tab">
<code class="descname">tab</code><span class="sig-paren">(</span><em>tab_id</em>, <em>option=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.tab" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the options of the specific <em>tab_id</em>.</p>
<p>If <em>kw</em> is not given, returns a dictionary of the tab option values. If
<em>option</em> is specified, returns the value of that <em>option</em>. Otherwise,
sets the options to the corresponding values.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.tabs">
<code class="descname">tabs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.tabs" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of windows managed by the notebook.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Notebook.enable_traversal">
<code class="descname">enable_traversal</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Notebook.enable_traversal" title="Permalink to this definition">¶</a></dt>
<dd><p>Enable keyboard traversal for a toplevel window containing this notebook.</p>
<p>This will extend the bindings for the toplevel window containing the
notebook as follows:</p>
<ul class="simple">
<li><kbd class="kbd docutils literal notranslate">Control-Tab</kbd>: selects the tab following the currently selected one.</li>
<li><kbd class="kbd docutils literal notranslate">Shift-Control-Tab</kbd>: selects the tab preceding the currently selected one.</li>
<li><kbd class="kbd docutils literal notranslate">Alt-K</kbd>: where <em>K</em> is the mnemonic (underlined) character of any tab, will
select that tab.</li>
</ul>
<p>Multiple notebooks in a single toplevel may be enabled for traversal,
including nested notebooks. However, notebook traversal only works
properly if all panes have the notebook they are in as master.</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="progressbar">
<h2>24.2.6. Progressbar<a class="headerlink" href="#progressbar" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#ttk.Progressbar" title="ttk.Progressbar"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Progressbar</span></code></a> widget shows the status of a long-running
operation. It can operate in two modes: determinate mode shows the amount
completed relative to the total amount of work to be done, and indeterminate
mode provides an animated display to let the user know that something is
happening.</p>
<div class="section" id="id3">
<h3>24.2.6.1. Options<a class="headerlink" href="#id3" title="Permalink to this headline">¶</a></h3>
<p>This widget accepts the following specific options:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>orient</td>
<td>One of “horizontal” or “vertical”. Specifies the orientation
of the progress bar.</td>
</tr>
<tr class="row-odd"><td>length</td>
<td>Specifies the length of the long axis of the progress bar
(width if horizontal, height if vertical).</td>
</tr>
<tr class="row-even"><td>mode</td>
<td>One of “determinate” or “indeterminate”.</td>
</tr>
<tr class="row-odd"><td>maximum</td>
<td>A number specifying the maximum value. Defaults to 100.</td>
</tr>
<tr class="row-even"><td>value</td>
<td>The current value of the progress bar. In “determinate” mode,
this represents the amount of work completed. In
“indeterminate” mode, it is interpreted as modulo <em>maximum</em>;
that is, the progress bar completes one “cycle” when its value
increases by <em>maximum</em>.</td>
</tr>
<tr class="row-odd"><td>variable</td>
<td>A name which is linked to the option value. If specified, the
value of the progress bar is automatically set to the value of
this name whenever the latter is modified.</td>
</tr>
<tr class="row-even"><td>phase</td>
<td>Read-only option. The widget periodically increments the value
of this option whenever its value is greater than 0 and, in
determinate mode, less than maximum. This option may be used
by the current theme to provide additional animation effects.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="ttk-progressbar">
<h3>24.2.6.2. ttk.Progressbar<a class="headerlink" href="#ttk-progressbar" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ttk.Progressbar">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Progressbar</code><a class="headerlink" href="#ttk.Progressbar" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="ttk.Progressbar.start">
<code class="descname">start</code><span class="sig-paren">(</span><span class="optional">[</span><em>interval</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Progressbar.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Begin autoincrement mode: schedules a recurring timer event that calls
<a class="reference internal" href="#ttk.Progressbar.step" title="ttk.Progressbar.step"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Progressbar.step()</span></code></a> every <em>interval</em> milliseconds. If omitted,
<em>interval</em> defaults to 50 milliseconds.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Progressbar.step">
<code class="descname">step</code><span class="sig-paren">(</span><span class="optional">[</span><em>amount</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Progressbar.step" title="Permalink to this definition">¶</a></dt>
<dd><p>Increments the progress bar’s value by <em>amount</em>.</p>
<p><em>amount</em> defaults to 1.0 if omitted.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Progressbar.stop">
<code class="descname">stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Progressbar.stop" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop autoincrement mode: cancels any recurring timer event initiated by
<a class="reference internal" href="#ttk.Progressbar.start" title="ttk.Progressbar.start"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Progressbar.start()</span></code></a> for this progress bar.</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="separator">
<h2>24.2.7. Separator<a class="headerlink" href="#separator" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Separator</span></code> widget displays a horizontal or vertical separator
bar.</p>
<p>It has no other methods besides the ones inherited from <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Widget</span></code></a>.</p>
<div class="section" id="id4">
<h3>24.2.7.1. Options<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h3>
<p>This widget accepts the following specific option:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="11%" />
<col width="89%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>orient</td>
<td>One of “horizontal” or “vertical”. Specifies the orientation of
the separator.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
</div>
<div class="section" id="sizegrip">
<h2>24.2.8. Sizegrip<a class="headerlink" href="#sizegrip" title="Permalink to this headline">¶</a></h2>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Sizegrip</span></code> widget (also known as a grow box) allows the user to
resize the containing toplevel window by pressing and dragging the grip.</p>
<p>This widget has neither specific options nor specific methods, besides the
ones inherited from <a class="reference internal" href="#ttk.Widget" title="ttk.Widget"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Widget</span></code></a>.</p>
<div class="section" id="platform-specific-notes">
<h3>24.2.8.1. Platform-specific notes<a class="headerlink" href="#platform-specific-notes" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>On Mac OS X, toplevel windows automatically include a built-in size grip
by default. Adding a <code class="xref py py-class docutils literal notranslate"><span class="pre">Sizegrip</span></code> is harmless, since the built-in
grip will just mask the widget.</li>
</ul>
</div>
<div class="section" id="bugs">
<h3>24.2.8.2. Bugs<a class="headerlink" href="#bugs" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>If the containing toplevel’s position was specified relative to the right
or bottom of the screen (e.g. ….), the <code class="xref py py-class docutils literal notranslate"><span class="pre">Sizegrip</span></code> widget will
not resize the window.</li>
<li>This widget supports only “southeast” resizing.</li>
</ul>
</div>
</div>
<div class="section" id="treeview">
<h2>24.2.9. Treeview<a class="headerlink" href="#treeview" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#ttk.Treeview" title="ttk.Treeview"><code class="xref py py-class docutils literal notranslate"><span class="pre">ttk.Treeview</span></code></a> widget displays a hierarchical collection of items.
Each item has a textual label, an optional image, and an optional list of data
values. The data values are displayed in successive columns after the tree
label.</p>
<p>The order in which data values are displayed may be controlled by setting
the widget option <code class="docutils literal notranslate"><span class="pre">displaycolumns</span></code>. The tree widget can also display column
headings. Columns may be accessed by number or symbolic names listed in the
widget option columns. See <a class="reference internal" href="#column-identifiers">Column Identifiers</a>.</p>
<p>Each item is identified by a unique name. The widget will generate item IDs
if they are not supplied by the caller. There is a distinguished root item,
named <code class="docutils literal notranslate"><span class="pre">{}</span></code>. The root item itself is not displayed; its children appear at the
top level of the hierarchy.</p>
<p>Each item also has a list of tags, which can be used to associate event bindings
with individual items and control the appearance of the item.</p>
<p>The Treeview widget supports horizontal and vertical scrolling, according to
the options described in <a class="reference internal" href="#scrollable-widget-options">Scrollable Widget Options</a> and the methods
<a class="reference internal" href="#ttk.Treeview.xview" title="ttk.Treeview.xview"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Treeview.xview()</span></code></a> and <a class="reference internal" href="#ttk.Treeview.yview" title="ttk.Treeview.yview"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Treeview.yview()</span></code></a>.</p>
<div class="section" id="id5">
<h3>24.2.9.1. Options<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h3>
<p>This widget accepts the following specific options:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>columns</td>
<td>A list of column identifiers, specifying the number of
columns and their names.</td>
</tr>
<tr class="row-odd"><td>displaycolumns</td>
<td>A list of column identifiers (either symbolic or
integer indices) specifying which data columns are
displayed and the order in which they appear, or the
string “#all”.</td>
</tr>
<tr class="row-even"><td>height</td>
<td>Specifies the number of rows which should be visible.
Note: the requested width is determined from the sum
of the column widths.</td>
</tr>
<tr class="row-odd"><td>padding</td>
<td>Specifies the internal padding for the widget. The
padding is a list of up to four length specifications.</td>
</tr>
<tr class="row-even"><td>selectmode</td>
<td><p class="first">Controls how the built-in class bindings manage the
selection. One of “extended”, “browse” or “none”.
If set to “extended” (the default), multiple items may
be selected. If “browse”, only a single item will be
selected at a time. If “none”, the selection will not
be changed.</p>
<p class="last">Note that the application code and tag bindings can set
the selection however they wish, regardless of the
value  of this option.</p>
</td>
</tr>
<tr class="row-odd"><td>show</td>
<td><p class="first">A list containing zero or more of the following values,
specifying which elements of the tree to display.</p>
<ul class="simple">
<li>tree: display tree labels in column #0.</li>
<li>headings: display the heading row.</li>
</ul>
<p>The default is “tree headings”, i.e., show all
elements.</p>
<p class="last"><strong>Note</strong>: Column #0 always refers to the tree column,
even if show=”tree” is not specified.</p>
</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="item-options">
<h3>24.2.9.2. Item Options<a class="headerlink" href="#item-options" title="Permalink to this headline">¶</a></h3>
<p>The following item options may be specified for items in the insert and item
widget commands.</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="11%" />
<col width="89%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>text</td>
<td>The textual label to display for the item.</td>
</tr>
<tr class="row-odd"><td>image</td>
<td>A Tk Image, displayed to the left of the label.</td>
</tr>
<tr class="row-even"><td>values</td>
<td><p class="first">The list of values associated with the item.</p>
<p class="last">Each item should have the same number of values as the widget
option columns. If there are fewer values than columns, the
remaining values are assumed empty. If there are more values
than columns, the extra values are ignored.</p>
</td>
</tr>
<tr class="row-odd"><td>open</td>
<td>True/False value indicating whether the item’s children should
be displayed or hidden.</td>
</tr>
<tr class="row-even"><td>tags</td>
<td>A list of tags associated with this item.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="tag-options">
<h3>24.2.9.3. Tag Options<a class="headerlink" href="#tag-options" title="Permalink to this headline">¶</a></h3>
<p>The following options may be specified on tags:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="17%" />
<col width="83%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">option</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>foreground</td>
<td>Specifies the text foreground color.</td>
</tr>
<tr class="row-odd"><td>background</td>
<td>Specifies the cell or item background color.</td>
</tr>
<tr class="row-even"><td>font</td>
<td>Specifies the font to use when drawing text.</td>
</tr>
<tr class="row-odd"><td>image</td>
<td>Specifies the item image, in case the item’s image option
is empty.</td>
</tr>
</tbody>
</table>
</div></blockquote>
</div>
<div class="section" id="column-identifiers">
<h3>24.2.9.4. Column Identifiers<a class="headerlink" href="#column-identifiers" title="Permalink to this headline">¶</a></h3>
<p>Column identifiers take any of the following forms:</p>
<ul class="simple">
<li>A symbolic name from the list of columns option.</li>
<li>An integer n, specifying the nth data column.</li>
<li>A string of the form #n, where n is an integer, specifying the nth display
column.</li>
</ul>
<p>Notes:</p>
<ul class="simple">
<li>Item’s option values may be displayed in a different order than the order
in which they are stored.</li>
<li>Column #0 always refers to the tree column, even if show=”tree” is not
specified.</li>
</ul>
<p>A data column number is an index into an item’s option values list; a display
column number is the column number in the tree where the values are displayed.
Tree labels are displayed in column #0. If option displaycolumns is not set,
then data column n is displayed in column #n+1. Again, <strong>column #0 always
refers to the tree column</strong>.</p>
</div>
<div class="section" id="id6">
<h3>24.2.9.5. Virtual Events<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h3>
<p>The Treeview widget generates the following virtual events.</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">event</th>
<th class="head">description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>&lt;&lt;TreeviewSelect&gt;&gt;</td>
<td>Generated whenever the selection changes.</td>
</tr>
<tr class="row-odd"><td>&lt;&lt;TreeviewOpen&gt;&gt;</td>
<td>Generated just before settings the focus item to
open=True.</td>
</tr>
<tr class="row-even"><td>&lt;&lt;TreeviewClose&gt;&gt;</td>
<td>Generated just after setting the focus item to
open=False.</td>
</tr>
</tbody>
</table>
</div></blockquote>
<p>The <a class="reference internal" href="#ttk.Treeview.focus" title="ttk.Treeview.focus"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Treeview.focus()</span></code></a> and <a class="reference internal" href="#ttk.Treeview.selection" title="ttk.Treeview.selection"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Treeview.selection()</span></code></a> methods can be used
to determine the affected item or items.</p>
</div>
<div class="section" id="ttk-treeview">
<h3>24.2.9.6. ttk.Treeview<a class="headerlink" href="#ttk-treeview" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="ttk.Treeview">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Treeview</code><a class="headerlink" href="#ttk.Treeview" title="Permalink to this definition">¶</a></dt>
<dd><dl class="method">
<dt id="ttk.Treeview.bbox">
<code class="descname">bbox</code><span class="sig-paren">(</span><em>item</em>, <em>column=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.bbox" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the bounding box (relative to the treeview widget’s window) of
the specified <em>item</em> in the form (x, y, width, height).</p>
<p>If <em>column</em> is specified, returns the bounding box of that cell. If the
<em>item</em> is not visible (i.e., if it is a descendant of a closed item or is
scrolled offscreen), returns an empty string.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.get_children">
<code class="descname">get_children</code><span class="sig-paren">(</span><span class="optional">[</span><em>item</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.get_children" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the list of children belonging to <em>item</em>.</p>
<p>If <em>item</em> is not specified, returns root children.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.set_children">
<code class="descname">set_children</code><span class="sig-paren">(</span><em>item</em>, <em>*newchildren</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.set_children" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces <em>item</em>’s child with <em>newchildren</em>.</p>
<p>Children present in <em>item</em> that are not present in <em>newchildren</em> are
detached from the tree. No items in <em>newchildren</em> may be an ancestor of
<em>item</em>. Note that not specifying <em>newchildren</em> results in detaching
<em>item</em>’s children.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.column">
<code class="descname">column</code><span class="sig-paren">(</span><em>column</em>, <em>option=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.column" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the options for the specified <em>column</em>.</p>
<p>If <em>kw</em> is not given, returns a dict of the column option values. If
<em>option</em> is specified then the value for that <em>option</em> is returned.
Otherwise, sets the options to the corresponding values.</p>
<p>The valid options/values are:</p>
<ul class="simple">
<li><dl class="first docutils">
<dt>id</dt>
<dd>Returns the column name. This is a read-only option.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>anchor: One of the standard Tk anchor values.</dt>
<dd>Specifies how the text in this column should be aligned with respect
to the cell.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>minwidth: width</dt>
<dd>The minimum width of the column in pixels. The treeview widget will
not make the column any smaller than specified by this option when
the widget is resized or the user drags a column.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>stretch: True/False</dt>
<dd>Specifies whether the column’s width should be adjusted when
the widget is resized.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>width: width</dt>
<dd>The width of the column in pixels.</dd>
</dl>
</li>
</ul>
<p>To configure the tree column, call this with column = “#0”</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.delete">
<code class="descname">delete</code><span class="sig-paren">(</span><em>*items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.delete" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all specified <em>items</em> and all their descendants.</p>
<p>The root item may not be deleted.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.detach">
<code class="descname">detach</code><span class="sig-paren">(</span><em>*items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.detach" title="Permalink to this definition">¶</a></dt>
<dd><p>Unlinks all of the specified <em>items</em> from the tree.</p>
<p>The items and all of their descendants are still present, and may be
reinserted at another point in the tree, but will not be displayed.</p>
<p>The root item may not be detached.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.exists">
<code class="descname">exists</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.exists" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the specified <em>item</em> is present in the tree.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.focus">
<code class="descname">focus</code><span class="sig-paren">(</span><span class="optional">[</span><em>item=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.focus" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>item</em> is specified, sets the focus item to <em>item</em>. Otherwise, returns
the current focus item, or ‘’ if there is none.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.heading">
<code class="descname">heading</code><span class="sig-paren">(</span><em>column</em>, <em>option=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.heading" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the heading options for the specified <em>column</em>.</p>
<p>If <em>kw</em> is not given, returns a dict of the heading option values. If
<em>option</em> is specified then the value for that <em>option</em> is returned.
Otherwise, sets the options to the corresponding values.</p>
<p>The valid options/values are:</p>
<ul class="simple">
<li><dl class="first docutils">
<dt>text: text</dt>
<dd>The text to display in the column heading.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>image: imageName</dt>
<dd>Specifies an image to display to the right of the column heading.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>anchor: anchor</dt>
<dd>Specifies how the heading text should be aligned. One of the standard
Tk anchor values.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>command: callback</dt>
<dd>A callback to be invoked when the heading label is pressed.</dd>
</dl>
</li>
</ul>
<p>To configure the tree column heading, call this with column = “#0”.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.identify">
<code class="descname">identify</code><span class="sig-paren">(</span><em>component</em>, <em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.identify" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a description of the specified <em>component</em> under the point given
by <em>x</em> and <em>y</em>, or the empty string if no such <em>component</em> is present at
that position.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.identify_row">
<code class="descname">identify_row</code><span class="sig-paren">(</span><em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.identify_row" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the item ID of the item at position <em>y</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.identify_column">
<code class="descname">identify_column</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.identify_column" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the data column identifier of the cell at position <em>x</em>.</p>
<p>The tree column has ID #0.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.identify_region">
<code class="descname">identify_region</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.identify_region" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns one of:</p>
<table border="1" class="docutils">
<colgroup>
<col width="22%" />
<col width="78%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">region</th>
<th class="head">meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>heading</td>
<td>Tree heading area.</td>
</tr>
<tr class="row-odd"><td>separator</td>
<td>Space between two columns headings.</td>
</tr>
<tr class="row-even"><td>tree</td>
<td>The tree area.</td>
</tr>
<tr class="row-odd"><td>cell</td>
<td>A data cell.</td>
</tr>
</tbody>
</table>
<p>Availability: Tk 8.6.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.identify_element">
<code class="descname">identify_element</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.identify_element" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the element at position <em>x</em>, <em>y</em>.</p>
<p>Availability: Tk 8.6.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.index">
<code class="descname">index</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.index" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the integer index of <em>item</em> within its parent’s list of children.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>parent</em>, <em>index</em>, <em>iid=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.insert" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new item and returns the item identifier of the newly created
item.</p>
<p><em>parent</em> is the item ID of the parent item, or the empty string to create
a new top-level item. <em>index</em> is an integer, or the value “end”,
specifying where in the list of parent’s children to insert the new item.
If <em>index</em> is less than or equal to zero, the new node is inserted at
the beginning; if <em>index</em> is greater than or equal to the current number
of children, it is inserted at the end. If <em>iid</em> is specified, it is used
as the item identifier; <em>iid</em> must not already exist in the tree.
Otherwise, a new unique identifier is generated.</p>
<p>See <a class="reference internal" href="#item-options">Item Options</a> for the list of available points.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.item">
<code class="descname">item</code><span class="sig-paren">(</span><em>item</em><span class="optional">[</span>, <em>option</em><span class="optional">[</span>, <em>**kw</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.item" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the options for the specified <em>item</em>.</p>
<p>If no options are given, a dict with options/values for the item is
returned.
If <em>option</em> is specified then the value for that option is returned.
Otherwise, sets the options to the corresponding values as given by <em>kw</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.move">
<code class="descname">move</code><span class="sig-paren">(</span><em>item</em>, <em>parent</em>, <em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.move" title="Permalink to this definition">¶</a></dt>
<dd><p>Moves <em>item</em> to position <em>index</em> in <em>parent</em>’s list of children.</p>
<p>It is illegal to move an item under one of its descendants. If <em>index</em> is
less than or equal to zero, <em>item</em> is moved to the beginning; if greater
than or equal to the number of children, it is moved to the end. If <em>item</em>
was detached it is reattached.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.next">
<code class="descname">next</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the identifier of <em>item</em>’s next sibling, or ‘’ if <em>item</em> is the
last child of its parent.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.parent">
<code class="descname">parent</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.parent" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the ID of the parent of <em>item</em>, or ‘’ if <em>item</em> is at the top
level of the hierarchy.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.prev">
<code class="descname">prev</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.prev" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the identifier of <em>item</em>’s previous sibling, or ‘’ if <em>item</em> is
the first child of its parent.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.reattach">
<code class="descname">reattach</code><span class="sig-paren">(</span><em>item</em>, <em>parent</em>, <em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.reattach" title="Permalink to this definition">¶</a></dt>
<dd><p>An alias for <a class="reference internal" href="#ttk.Treeview.move" title="ttk.Treeview.move"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Treeview.move()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.see">
<code class="descname">see</code><span class="sig-paren">(</span><em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.see" title="Permalink to this definition">¶</a></dt>
<dd><p>Ensure that <em>item</em> is visible.</p>
<p>Sets all of <em>item</em>’s ancestors open option to <code class="docutils literal notranslate"><span class="pre">True</span></code>, and scrolls the
widget if necessary so that <em>item</em> is within the visible portion of
the tree.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.selection">
<code class="descname">selection</code><span class="sig-paren">(</span><span class="optional">[</span><em>selop=None</em><span class="optional">[</span>, <em>items=None</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.selection" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>selop</em> is not specified, returns selected items. Otherwise, it will
act according to the following selection methods.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.selection_set">
<code class="descname">selection_set</code><span class="sig-paren">(</span><em>items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.selection_set" title="Permalink to this definition">¶</a></dt>
<dd><p><em>items</em> becomes the new selection.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.selection_add">
<code class="descname">selection_add</code><span class="sig-paren">(</span><em>items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.selection_add" title="Permalink to this definition">¶</a></dt>
<dd><p>Add <em>items</em> to the selection.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.selection_remove">
<code class="descname">selection_remove</code><span class="sig-paren">(</span><em>items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.selection_remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove <em>items</em> from the selection.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.selection_toggle">
<code class="descname">selection_toggle</code><span class="sig-paren">(</span><em>items</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.selection_toggle" title="Permalink to this definition">¶</a></dt>
<dd><p>Toggle the selection state of each item in <em>items</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.set">
<code class="descname">set</code><span class="sig-paren">(</span><em>item</em>, <em>column=None</em>, <em>value=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.set" title="Permalink to this definition">¶</a></dt>
<dd><p>With one argument, returns a dictionary of column/value pairs for the
specified <em>item</em>. With two arguments, returns the current value of the
specified <em>column</em>. With three arguments, sets the value of given
<em>column</em> in given <em>item</em> to the specified <em>value</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.tag_bind">
<code class="descname">tag_bind</code><span class="sig-paren">(</span><em>tagname</em>, <em>sequence=None</em>, <em>callback=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.tag_bind" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind a callback for the given event <em>sequence</em> to the tag <em>tagname</em>.
When an event is delivered to an item, the callbacks for each of the
item’s tags option are called.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.tag_configure">
<code class="descname">tag_configure</code><span class="sig-paren">(</span><em>tagname</em>, <em>option=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.tag_configure" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify the options for the specified <em>tagname</em>.</p>
<p>If <em>kw</em> is not given, returns a dict of the option settings for
<em>tagname</em>. If <em>option</em> is specified, returns the value for that <em>option</em>
for the specified <em>tagname</em>. Otherwise, sets the options to the
corresponding values for the given <em>tagname</em>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.tag_has">
<code class="descname">tag_has</code><span class="sig-paren">(</span><em>tagname</em><span class="optional">[</span>, <em>item</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.tag_has" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>item</em> is specified, returns 1 or 0 depending on whether the specified
<em>item</em> has the given <em>tagname</em>. Otherwise, returns a list of all items
that have the specified tag.</p>
<p>Availability: Tk 8.6</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.xview">
<code class="descname">xview</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.xview" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify horizontal position of the treeview.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Treeview.yview">
<code class="descname">yview</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Treeview.yview" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or modify vertical position of the treeview.</p>
</dd></dl>

</dd></dl>

</div>
</div>
<div class="section" id="ttk-styling">
<span id="ttkstyling"></span><h2>24.2.10. Ttk Styling<a class="headerlink" href="#ttk-styling" title="Permalink to this headline">¶</a></h2>
<p>Each widget in <a class="reference internal" href="#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> is assigned a style, which specifies the set of
elements making up the widget and how they are arranged, along with dynamic and
default settings for element options. By default the style name is the same as
the widget’s class name, but it may be overridden by the widget’s style
option. If the class name of a widget is unknown, use the method
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Misc.winfo_class()</span></code> (somewidget.winfo_class()).</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://tktable.sourceforge.net/tile/tile-tcl2004.pdf">Tcl‘2004 conference presentation</a></dt>
<dd>This document explains how the theme engine works</dd>
</dl>
</div>
<dl class="class">
<dt id="ttk.Style">
<em class="property">class </em><code class="descclassname">ttk.</code><code class="descname">Style</code><a class="headerlink" href="#ttk.Style" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is used to manipulate the style database.</p>
<dl class="method">
<dt id="ttk.Style.configure">
<code class="descname">configure</code><span class="sig-paren">(</span><em>style</em>, <em>query_opt=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.configure" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or set the default value of the specified option(s) in <em>style</em>.</p>
<p>Each key in <em>kw</em> is an option and each value is a string identifying
the value for that option.</p>
<p>For example, to change every default button to be a flat button with some
padding and a different background color do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ttk</span>
<span class="kn">import</span> <span class="nn">Tkinter</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>

<span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span><span class="o">.</span><span class="n">configure</span><span class="p">(</span><span class="s2">&quot;TButton&quot;</span><span class="p">,</span> <span class="n">padding</span><span class="o">=</span><span class="mi">6</span><span class="p">,</span> <span class="n">relief</span><span class="o">=</span><span class="s2">&quot;flat&quot;</span><span class="p">,</span>
   <span class="n">background</span><span class="o">=</span><span class="s2">&quot;#ccc&quot;</span><span class="p">)</span>

<span class="n">btn</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Button</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Sample&quot;</span><span class="p">)</span>
<span class="n">btn</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

<span class="n">root</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.map">
<code class="descname">map</code><span class="sig-paren">(</span><em>style</em>, <em>query_opt=None</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.map" title="Permalink to this definition">¶</a></dt>
<dd><p>Query or sets dynamic values of the specified option(s) in <em>style</em>.</p>
<p>Each key in <em>kw</em> is an option and each value should be a list or a
tuple (usually) containing statespecs grouped in tuples, lists, or
something else of your preference. A statespec is a compound of one
or more states and then a value.</p>
<p>An example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tkinter</span>
<span class="kn">import</span> <span class="nn">ttk</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>

<span class="n">style</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span>
<span class="n">style</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="s2">&quot;C.TButton&quot;</span><span class="p">,</span>
    <span class="n">foreground</span><span class="o">=</span><span class="p">[(</span><span class="s1">&#39;pressed&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;active&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">)],</span>
    <span class="n">background</span><span class="o">=</span><span class="p">[(</span><span class="s1">&#39;pressed&#39;</span><span class="p">,</span> <span class="s1">&#39;!disabled&#39;</span><span class="p">,</span> <span class="s1">&#39;black&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;active&#39;</span><span class="p">,</span> <span class="s1">&#39;white&#39;</span><span class="p">)]</span>
    <span class="p">)</span>

<span class="n">colored_btn</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Button</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s2">&quot;Test&quot;</span><span class="p">,</span> <span class="n">style</span><span class="o">=</span><span class="s2">&quot;C.TButton&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

<span class="n">root</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
<p>Note that the order of the (states, value) sequences for an
option matters.  In the previous example, if you change the
order to <code class="docutils literal notranslate"><span class="pre">[('active',</span> <span class="pre">'blue'),</span> <span class="pre">('pressed',</span> <span class="pre">'red')]</span></code> in the
foreground option, for example, you would get a blue foreground
when the widget is in the active or pressed states.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.lookup">
<code class="descname">lookup</code><span class="sig-paren">(</span><em>style</em>, <em>option</em>, <em>state=None</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.lookup" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the value specified for <em>option</em> in <em>style</em>.</p>
<p>If <em>state</em> is specified, it is expected to be a sequence of one or more
states. If the <em>default</em> argument is set, it is used as a fallback value
in case no specification for option is found.</p>
<p>To check what font a Button uses by default, do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ttk</span>

<span class="nb">print</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span><span class="o">.</span><span class="n">lookup</span><span class="p">(</span><span class="s2">&quot;TButton&quot;</span><span class="p">,</span> <span class="s2">&quot;font&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.layout">
<code class="descname">layout</code><span class="sig-paren">(</span><em>style</em>, <em>layoutspec=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.layout" title="Permalink to this definition">¶</a></dt>
<dd><p>Define the widget layout for given <em>style</em>. If <em>layoutspec</em> is omitted,
return the layout specification for given style.</p>
<p><em>layoutspec</em>, if specified, is expected to be a list or some other
sequence type (excluding strings), where each item should be a tuple and
the first item is the layout name and the second item should have the
format described in <a class="reference internal" href="#layouts">Layouts</a>.</p>
<p>To understand the format, see the following example (it is not
intended to do anything useful):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ttk</span>
<span class="kn">import</span> <span class="nn">Tkinter</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>

<span class="n">style</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span>
<span class="n">style</span><span class="o">.</span><span class="n">layout</span><span class="p">(</span><span class="s2">&quot;TMenubutton&quot;</span><span class="p">,</span> <span class="p">[</span>
   <span class="p">(</span><span class="s2">&quot;Menubutton.background&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">),</span>
   <span class="p">(</span><span class="s2">&quot;Menubutton.button&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;children&quot;</span><span class="p">:</span>
       <span class="p">[(</span><span class="s2">&quot;Menubutton.focus&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;children&quot;</span><span class="p">:</span>
           <span class="p">[(</span><span class="s2">&quot;Menubutton.padding&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;children&quot;</span><span class="p">:</span>
               <span class="p">[(</span><span class="s2">&quot;Menubutton.label&quot;</span><span class="p">,</span> <span class="p">{</span><span class="s2">&quot;side&quot;</span><span class="p">:</span> <span class="s2">&quot;left&quot;</span><span class="p">,</span> <span class="s2">&quot;expand&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">})]</span>
           <span class="p">})]</span>
       <span class="p">})]</span>
   <span class="p">}),</span>
<span class="p">])</span>

<span class="n">mbtn</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Menubutton</span><span class="p">(</span><span class="n">text</span><span class="o">=</span><span class="s1">&#39;Text&#39;</span><span class="p">)</span>
<span class="n">mbtn</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>
<span class="n">root</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.element_create">
<code class="descname">element_create</code><span class="sig-paren">(</span><em>elementname</em>, <em>etype</em>, <em>*args</em>, <em>**kw</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.element_create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new element in the current theme, of the given <em>etype</em> which is
expected to be either “image”, “from” or “vsapi”. The latter is only
available in Tk 8.6a for Windows XP and Vista and is not described here.</p>
<p>If “image” is used, <em>args</em> should contain the default image name followed
by statespec/value pairs (this is the imagespec), and <em>kw</em> may have the
following options:</p>
<blockquote>
<div><ul class="simple">
<li><dl class="first docutils">
<dt>border=padding</dt>
<dd>padding is a list of up to four integers, specifying the left, top,
right, and bottom borders, respectively.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>height=height</dt>
<dd>Specifies a minimum height for the element. If less than zero, the
base image’s height is used as a default.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>padding=padding</dt>
<dd>Specifies the element’s interior padding. Defaults to border’s value
if not specified.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>sticky=spec</dt>
<dd>Specifies how the image is placed within the final parcel. spec
contains zero or more characters “n”, “s”, “w”, or “e”.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>width=width</dt>
<dd>Specifies a minimum width for the element. If less than zero, the
base image’s width is used as a default.</dd>
</dl>
</li>
</ul>
</div></blockquote>
<p>If “from” is used as the value of <em>etype</em>,
<a class="reference internal" href="#ttk.Style.element_create" title="ttk.Style.element_create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">element_create()</span></code></a> will clone an existing
element. <em>args</em> is expected to contain a themename, from which
the element will be cloned, and optionally an element to clone from.
If this element to clone from is not specified, an empty element will
be used. <em>kw</em> is discarded.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.element_names">
<code class="descname">element_names</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.element_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the list of elements defined in the current theme.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.element_options">
<code class="descname">element_options</code><span class="sig-paren">(</span><em>elementname</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.element_options" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the list of <em>elementname</em>’s options.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.theme_create">
<code class="descname">theme_create</code><span class="sig-paren">(</span><em>themename</em>, <em>parent=None</em>, <em>settings=None</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.theme_create" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new theme.</p>
<p>It is an error if <em>themename</em> already exists. If <em>parent</em> is specified,
the new theme will inherit styles, elements and layouts from the parent
theme. If <em>settings</em> are present they are expected to have the same
syntax used for <a class="reference internal" href="#ttk.Style.theme_settings" title="ttk.Style.theme_settings"><code class="xref py py-meth docutils literal notranslate"><span class="pre">theme_settings()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.theme_settings">
<code class="descname">theme_settings</code><span class="sig-paren">(</span><em>themename</em>, <em>settings</em><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.theme_settings" title="Permalink to this definition">¶</a></dt>
<dd><p>Temporarily sets the current theme to <em>themename</em>, apply specified
<em>settings</em> and then restore the previous theme.</p>
<p>Each key in <em>settings</em> is a style and each value may contain the keys
‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected
to have the same format as specified by the methods
<a class="reference internal" href="#ttk.Style.configure" title="ttk.Style.configure"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Style.configure()</span></code></a>, <a class="reference internal" href="#ttk.Style.map" title="ttk.Style.map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Style.map()</span></code></a>, <a class="reference internal" href="#ttk.Style.layout" title="ttk.Style.layout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Style.layout()</span></code></a> and
<a class="reference internal" href="#ttk.Style.element_create" title="ttk.Style.element_create"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Style.element_create()</span></code></a> respectively.</p>
<p>As an example, let’s change the Combobox for the default theme a bit:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ttk</span>
<span class="kn">import</span> <span class="nn">Tkinter</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">Tkinter</span><span class="o">.</span><span class="n">Tk</span><span class="p">()</span>

<span class="n">style</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Style</span><span class="p">()</span>
<span class="n">style</span><span class="o">.</span><span class="n">theme_settings</span><span class="p">(</span><span class="s2">&quot;default&quot;</span><span class="p">,</span> <span class="p">{</span>
   <span class="s2">&quot;TCombobox&quot;</span><span class="p">:</span> <span class="p">{</span>
       <span class="s2">&quot;configure&quot;</span><span class="p">:</span> <span class="p">{</span><span class="s2">&quot;padding&quot;</span><span class="p">:</span> <span class="mi">5</span><span class="p">},</span>
       <span class="s2">&quot;map&quot;</span><span class="p">:</span> <span class="p">{</span>
           <span class="s2">&quot;background&quot;</span><span class="p">:</span> <span class="p">[(</span><span class="s2">&quot;active&quot;</span><span class="p">,</span> <span class="s2">&quot;green2&quot;</span><span class="p">),</span>
                          <span class="p">(</span><span class="s2">&quot;!disabled&quot;</span><span class="p">,</span> <span class="s2">&quot;green4&quot;</span><span class="p">)],</span>
           <span class="s2">&quot;fieldbackground&quot;</span><span class="p">:</span> <span class="p">[(</span><span class="s2">&quot;!disabled&quot;</span><span class="p">,</span> <span class="s2">&quot;green3&quot;</span><span class="p">)],</span>
           <span class="s2">&quot;foreground&quot;</span><span class="p">:</span> <span class="p">[(</span><span class="s2">&quot;focus&quot;</span><span class="p">,</span> <span class="s2">&quot;OliveDrab1&quot;</span><span class="p">),</span>
                          <span class="p">(</span><span class="s2">&quot;!disabled&quot;</span><span class="p">,</span> <span class="s2">&quot;OliveDrab2&quot;</span><span class="p">)]</span>
       <span class="p">}</span>
   <span class="p">}</span>
<span class="p">})</span>

<span class="n">combo</span> <span class="o">=</span> <span class="n">ttk</span><span class="o">.</span><span class="n">Combobox</span><span class="p">()</span><span class="o">.</span><span class="n">pack</span><span class="p">()</span>

<span class="n">root</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.theme_names">
<code class="descname">theme_names</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.theme_names" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a list of all known themes.</p>
</dd></dl>

<dl class="method">
<dt id="ttk.Style.theme_use">
<code class="descname">theme_use</code><span class="sig-paren">(</span><span class="optional">[</span><em>themename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#ttk.Style.theme_use" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>themename</em> is not given, returns the theme in use.  Otherwise, sets
the current theme to <em>themename</em>, refreshes all widgets and emits a
&lt;&lt;ThemeChanged&gt;&gt; event.</p>
</dd></dl>

</dd></dl>

<div class="section" id="layouts">
<h3>24.2.10.1. Layouts<a class="headerlink" href="#layouts" title="Permalink to this headline">¶</a></h3>
<p>A layout can be just <code class="docutils literal notranslate"><span class="pre">None</span></code>, if it takes no options, or a dict of
options specifying how to arrange the element. The layout mechanism
uses a simplified version of the pack geometry manager: given an
initial cavity, each element is allocated a parcel. Valid
options/values are:</p>
<blockquote>
<div><ul class="simple">
<li><dl class="first docutils">
<dt>side: whichside</dt>
<dd>Specifies which side of the cavity to place the element; one of
top, right, bottom or left. If omitted, the element occupies the
entire cavity.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>sticky: nswe</dt>
<dd>Specifies where the element is placed inside its allocated parcel.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>unit: 0 or 1</dt>
<dd>If set to 1, causes the element and all of its descendants to be treated as
a single element for the purposes of <a class="reference internal" href="#ttk.Widget.identify" title="ttk.Widget.identify"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Widget.identify()</span></code></a> et al. It’s
used for things like scrollbar thumbs with grips.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>children: [sublayout… ]</dt>
<dd>Specifies a list of elements to place inside the element. Each
element is a tuple (or other sequence type) where the first item is
the layout name, and the other is a <a class="reference internal" href="#layouts">Layout</a>.</dd>
</dl>
</li>
</ul>
</div></blockquote>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a><ul>
<li><a class="reference internal" href="#using-ttk">24.2.1. Using Ttk</a></li>
<li><a class="reference internal" href="#ttk-widgets">24.2.2. Ttk Widgets</a></li>
<li><a class="reference internal" href="#widget">24.2.3. Widget</a><ul>
<li><a class="reference internal" href="#standard-options">24.2.3.1. Standard Options</a></li>
<li><a class="reference internal" href="#scrollable-widget-options">24.2.3.2. Scrollable Widget Options</a></li>
<li><a class="reference internal" href="#label-options">24.2.3.3. Label Options</a></li>
<li><a class="reference internal" href="#compatibility-options">24.2.3.4. Compatibility Options</a></li>
<li><a class="reference internal" href="#widget-states">24.2.3.5. Widget States</a></li>
<li><a class="reference internal" href="#ttk-widget">24.2.3.6. ttk.Widget</a></li>
</ul>
</li>
<li><a class="reference internal" href="#combobox">24.2.4. Combobox</a><ul>
<li><a class="reference internal" href="#options">24.2.4.1. Options</a></li>
<li><a class="reference internal" href="#virtual-events">24.2.4.2. Virtual events</a></li>
<li><a class="reference internal" href="#ttk-combobox">24.2.4.3. ttk.Combobox</a></li>
</ul>
</li>
<li><a class="reference internal" href="#notebook">24.2.5. Notebook</a><ul>
<li><a class="reference internal" href="#id1">24.2.5.1. Options</a></li>
<li><a class="reference internal" href="#tab-options">24.2.5.2. Tab Options</a></li>
<li><a class="reference internal" href="#tab-identifiers">24.2.5.3. Tab Identifiers</a></li>
<li><a class="reference internal" href="#id2">24.2.5.4. Virtual Events</a></li>
<li><a class="reference internal" href="#ttk-notebook">24.2.5.5. ttk.Notebook</a></li>
</ul>
</li>
<li><a class="reference internal" href="#progressbar">24.2.6. Progressbar</a><ul>
<li><a class="reference internal" href="#id3">24.2.6.1. Options</a></li>
<li><a class="reference internal" href="#ttk-progressbar">24.2.6.2. ttk.Progressbar</a></li>
</ul>
</li>
<li><a class="reference internal" href="#separator">24.2.7. Separator</a><ul>
<li><a class="reference internal" href="#id4">24.2.7.1. Options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#sizegrip">24.2.8. Sizegrip</a><ul>
<li><a class="reference internal" href="#platform-specific-notes">24.2.8.1. Platform-specific notes</a></li>
<li><a class="reference internal" href="#bugs">24.2.8.2. Bugs</a></li>
</ul>
</li>
<li><a class="reference internal" href="#treeview">24.2.9. Treeview</a><ul>
<li><a class="reference internal" href="#id5">24.2.9.1. Options</a></li>
<li><a class="reference internal" href="#item-options">24.2.9.2. Item Options</a></li>
<li><a class="reference internal" href="#tag-options">24.2.9.3. Tag Options</a></li>
<li><a class="reference internal" href="#column-identifiers">24.2.9.4. Column Identifiers</a></li>
<li><a class="reference internal" href="#id6">24.2.9.5. Virtual Events</a></li>
<li><a class="reference internal" href="#ttk-treeview">24.2.9.6. ttk.Treeview</a></li>
</ul>
</li>
<li><a class="reference internal" href="#ttk-styling">24.2.10. Ttk Styling</a><ul>
<li><a class="reference internal" href="#layouts">24.2.10.1. Layouts</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="tkinter.html"
                        title="previous chapter">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tix.html"
                        title="next chapter">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/ttk.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tix.html" title="24.3. Tix — Extension widgets for Tk"
             >next</a> |</li>
        <li class="right" >
          <a href="tkinter.html" title="24.1. Tkinter — Python interface to Tcl/Tk"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\j�&&&html/library/tty.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36.8. tty — Terminal control functions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.9. pty — Pseudo-terminal utilities" href="pty.html" />
    <link rel="prev" title="36.7. termios — POSIX style tty control" href="termios.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/tty.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pty.html" title="36.9. pty — Pseudo-terminal utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="termios.html" title="36.7. termios — POSIX style tty control"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" accesskey="U">36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-tty">
<span id="tty-terminal-control-functions"></span><h1>36.8. <a class="reference internal" href="#module-tty" title="tty: Utility functions that perform common terminal control operations. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tty</span></code></a> — Terminal control functions<a class="headerlink" href="#module-tty" title="Permalink to this headline">¶</a></h1>
<p>The <a class="reference internal" href="#module-tty" title="tty: Utility functions that perform common terminal control operations. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tty</span></code></a> module defines functions for putting the tty into cbreak and raw
modes.</p>
<p>Because it requires the <a class="reference internal" href="termios.html#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a> module, it will work only on Unix.</p>
<p>The <a class="reference internal" href="#module-tty" title="tty: Utility functions that perform common terminal control operations. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tty</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="tty.setraw">
<code class="descclassname">tty.</code><code class="descname">setraw</code><span class="sig-paren">(</span><em>fd</em><span class="optional">[</span>, <em>when</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tty.setraw" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the mode of the file descriptor <em>fd</em> to raw. If <em>when</em> is omitted, it
defaults to <code class="xref py py-const docutils literal notranslate"><span class="pre">termios.TCSAFLUSH</span></code>, and is passed to
<a class="reference internal" href="termios.html#termios.tcsetattr" title="termios.tcsetattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">termios.tcsetattr()</span></code></a>.</p>
</dd></dl>

<dl class="function">
<dt id="tty.setcbreak">
<code class="descclassname">tty.</code><code class="descname">setcbreak</code><span class="sig-paren">(</span><em>fd</em><span class="optional">[</span>, <em>when</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#tty.setcbreak" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the mode of file descriptor <em>fd</em> to cbreak. If <em>when</em> is omitted, it
defaults to <code class="xref py py-const docutils literal notranslate"><span class="pre">termios.TCSAFLUSH</span></code>, and is passed to
<a class="reference internal" href="termios.html#termios.tcsetattr" title="termios.tcsetattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">termios.tcsetattr()</span></code></a>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="termios.html#module-termios" title="termios: POSIX style tty control. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">termios</span></code></a></dt>
<dd>Low-level terminal control interface.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="termios.html"
                        title="previous chapter">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pty.html"
                        title="next chapter">36.9. <code class="docutils literal notranslate"><span class="pre">pty</span></code> — Pseudo-terminal utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/tty.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pty.html" title="36.9. pty — Pseudo-terminal utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="termios.html" title="36.7. termios — POSIX style tty control"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="unix.html" >36. Unix Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\#r�S�S�html/library/turtle.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>24.5. turtle — Turtle graphics for Tk &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="24.6. IDLE" href="idle.html" />
    <link rel="prev" title="24.4. ScrolledText — Scrolled Text Widget" href="scrolledtext.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/turtle.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="idle.html" title="24.6. IDLE"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="scrolledtext.html" title="24.4. ScrolledText — Scrolled Text Widget"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" accesskey="U">24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-turtle">
<span id="turtle-turtle-graphics-for-tk"></span><h1>24.5. <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> — Turtle graphics for Tk<a class="headerlink" href="#module-turtle" title="Permalink to this headline">¶</a></h1>
<div class="section" id="introduction">
<h2>24.5.1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>Turtle graphics is a popular way for introducing programming to kids.  It was
part of the original Logo programming language developed by Wally Feurzig and
Seymour Papert in 1966.</p>
<p>Imagine a robotic turtle starting at (0, 0) in the x-y plane.  After an <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">turtle</span></code>, give it the
command <code class="docutils literal notranslate"><span class="pre">turtle.forward(15)</span></code>, and it moves (on-screen!) 15 pixels in the
direction it is facing, drawing a line as it moves.  Give it the command
<code class="docutils literal notranslate"><span class="pre">turtle.right(25)</span></code>, and it rotates in-place 25 degrees clockwise.</p>
<p>By combining together these and similar commands, intricate shapes and pictures
can easily be drawn.</p>
<p>The <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> module is an extended reimplementation of the same-named
module from the Python standard distribution up to version Python 2.5.</p>
<p>It tries to keep the merits of the old turtle module and to be (nearly) 100%
compatible with it.  This means in the first place to enable the learning
programmer to use all the commands, classes and methods interactively when using
the module from within IDLE run with the <code class="docutils literal notranslate"><span class="pre">-n</span></code> switch.</p>
<p>The turtle module provides turtle graphics primitives, in both object-oriented
and procedure-oriented ways.  Because it uses <a class="reference internal" href="tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> for the underlying
graphics, it needs a version of Python installed with Tk support.</p>
<p>The object-oriented interface uses essentially two+two classes:</p>
<ol class="arabic">
<li><p class="first">The <a class="reference internal" href="#turtle.TurtleScreen" title="turtle.TurtleScreen"><code class="xref py py-class docutils literal notranslate"><span class="pre">TurtleScreen</span></code></a> class defines graphics windows as a playground for
the drawing turtles.  Its constructor needs a <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Canvas</span></code> or a
<a class="reference internal" href="#turtle.ScrolledCanvas" title="turtle.ScrolledCanvas"><code class="xref py py-class docutils literal notranslate"><span class="pre">ScrolledCanvas</span></code></a> as argument.  It should be used when <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> is
used as part of some application.</p>
<p>The function <a class="reference internal" href="#turtle.Screen" title="turtle.Screen"><code class="xref py py-func docutils literal notranslate"><span class="pre">Screen()</span></code></a> returns a singleton object of a
<a class="reference internal" href="#turtle.TurtleScreen" title="turtle.TurtleScreen"><code class="xref py py-class docutils literal notranslate"><span class="pre">TurtleScreen</span></code></a> subclass. This function should be used when
<a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> is used as a standalone tool for doing graphics.
As a singleton object, inheriting from its class is not possible.</p>
<p>All methods of TurtleScreen/Screen also exist as functions, i.e. as part of
the procedure-oriented interface.</p>
</li>
<li><p class="first"><a class="reference internal" href="#turtle.RawTurtle" title="turtle.RawTurtle"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawTurtle</span></code></a> (alias: <a class="reference internal" href="#turtle.RawPen" title="turtle.RawPen"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawPen</span></code></a>) defines Turtle objects which draw
on a <a class="reference internal" href="#turtle.TurtleScreen" title="turtle.TurtleScreen"><code class="xref py py-class docutils literal notranslate"><span class="pre">TurtleScreen</span></code></a>.  Its constructor needs a Canvas, ScrolledCanvas
or TurtleScreen as argument, so the RawTurtle objects know where to draw.</p>
<p>Derived from RawTurtle is the subclass <a class="reference internal" href="#turtle.Turtle" title="turtle.Turtle"><code class="xref py py-class docutils literal notranslate"><span class="pre">Turtle</span></code></a> (alias: <code class="xref py py-class docutils literal notranslate"><span class="pre">Pen</span></code>),
which draws on “the” <a class="reference internal" href="#turtle.Screen" title="turtle.Screen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Screen</span></code></a> - instance which is automatically
created, if not already present.</p>
<p>All methods of RawTurtle/Turtle also exist as functions, i.e. part of the
procedure-oriented interface.</p>
</li>
</ol>
<p>The procedural interface provides functions which are derived from the methods
of the classes <a class="reference internal" href="#turtle.Screen" title="turtle.Screen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Screen</span></code></a> and <a class="reference internal" href="#turtle.Turtle" title="turtle.Turtle"><code class="xref py py-class docutils literal notranslate"><span class="pre">Turtle</span></code></a>.  They have the same names as
the corresponding methods.  A screen object is automatically created whenever a
function derived from a Screen method is called.  An (unnamed) turtle object is
automatically created whenever any of the functions derived from a Turtle method
is called.</p>
<p>To use multiple turtles an a screen one has to use the object-oriented interface.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In the following documentation the argument list for functions is given.
Methods, of course, have the additional first argument <em>self</em> which is
omitted here.</p>
</div>
</div>
<div class="section" id="overview-over-available-turtle-and-screen-methods">
<h2>24.5.2. Overview over available Turtle and Screen methods<a class="headerlink" href="#overview-over-available-turtle-and-screen-methods" title="Permalink to this headline">¶</a></h2>
<div class="section" id="turtle-methods">
<h3>24.5.2.1. Turtle methods<a class="headerlink" href="#turtle-methods" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Turtle motion</dt>
<dd><dl class="first last docutils">
<dt>Move and draw</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.forward" title="turtle.forward"><code class="xref py py-func docutils literal notranslate"><span class="pre">forward()</span></code></a> | <a class="reference internal" href="#turtle.fd" title="turtle.fd"><code class="xref py py-func docutils literal notranslate"><span class="pre">fd()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.backward" title="turtle.backward"><code class="xref py py-func docutils literal notranslate"><span class="pre">backward()</span></code></a> | <a class="reference internal" href="#turtle.bk" title="turtle.bk"><code class="xref py py-func docutils literal notranslate"><span class="pre">bk()</span></code></a> | <a class="reference internal" href="#turtle.back" title="turtle.back"><code class="xref py py-func docutils literal notranslate"><span class="pre">back()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.right" title="turtle.right"><code class="xref py py-func docutils literal notranslate"><span class="pre">right()</span></code></a> | <a class="reference internal" href="#turtle.rt" title="turtle.rt"><code class="xref py py-func docutils literal notranslate"><span class="pre">rt()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.left" title="turtle.left"><code class="xref py py-func docutils literal notranslate"><span class="pre">left()</span></code></a> | <a class="reference internal" href="#turtle.lt" title="turtle.lt"><code class="xref py py-func docutils literal notranslate"><span class="pre">lt()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.goto" title="turtle.goto"><code class="xref py py-func docutils literal notranslate"><span class="pre">goto()</span></code></a> | <a class="reference internal" href="#turtle.setpos" title="turtle.setpos"><code class="xref py py-func docutils literal notranslate"><span class="pre">setpos()</span></code></a> | <a class="reference internal" href="#turtle.setposition" title="turtle.setposition"><code class="xref py py-func docutils literal notranslate"><span class="pre">setposition()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.setx" title="turtle.setx"><code class="xref py py-func docutils literal notranslate"><span class="pre">setx()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.sety" title="turtle.sety"><code class="xref py py-func docutils literal notranslate"><span class="pre">sety()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.setheading" title="turtle.setheading"><code class="xref py py-func docutils literal notranslate"><span class="pre">setheading()</span></code></a> | <a class="reference internal" href="#turtle.seth" title="turtle.seth"><code class="xref py py-func docutils literal notranslate"><span class="pre">seth()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.home" title="turtle.home"><code class="xref py py-func docutils literal notranslate"><span class="pre">home()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.circle" title="turtle.circle"><code class="xref py py-func docutils literal notranslate"><span class="pre">circle()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.dot" title="turtle.dot"><code class="xref py py-func docutils literal notranslate"><span class="pre">dot()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.stamp" title="turtle.stamp"><code class="xref py py-func docutils literal notranslate"><span class="pre">stamp()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.clearstamp" title="turtle.clearstamp"><code class="xref py py-func docutils literal notranslate"><span class="pre">clearstamp()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.clearstamps" title="turtle.clearstamps"><code class="xref py py-func docutils literal notranslate"><span class="pre">clearstamps()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.undo" title="turtle.undo"><code class="xref py py-func docutils literal notranslate"><span class="pre">undo()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.speed" title="turtle.speed"><code class="xref py py-func docutils literal notranslate"><span class="pre">speed()</span></code></a></div>
</div>
</dd>
<dt>Tell Turtle’s state</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.position" title="turtle.position"><code class="xref py py-func docutils literal notranslate"><span class="pre">position()</span></code></a> | <a class="reference internal" href="#turtle.pos" title="turtle.pos"><code class="xref py py-func docutils literal notranslate"><span class="pre">pos()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.towards" title="turtle.towards"><code class="xref py py-func docutils literal notranslate"><span class="pre">towards()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.xcor" title="turtle.xcor"><code class="xref py py-func docutils literal notranslate"><span class="pre">xcor()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.ycor" title="turtle.ycor"><code class="xref py py-func docutils literal notranslate"><span class="pre">ycor()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.heading" title="turtle.heading"><code class="xref py py-func docutils literal notranslate"><span class="pre">heading()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.distance" title="turtle.distance"><code class="xref py py-func docutils literal notranslate"><span class="pre">distance()</span></code></a></div>
</div>
</dd>
<dt>Setting and measurement</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.degrees" title="turtle.degrees"><code class="xref py py-func docutils literal notranslate"><span class="pre">degrees()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.radians" title="turtle.radians"><code class="xref py py-func docutils literal notranslate"><span class="pre">radians()</span></code></a></div>
</div>
</dd>
</dl>
</dd>
<dt>Pen control</dt>
<dd><dl class="first last docutils">
<dt>Drawing state</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.pendown" title="turtle.pendown"><code class="xref py py-func docutils literal notranslate"><span class="pre">pendown()</span></code></a> | <a class="reference internal" href="#turtle.pd" title="turtle.pd"><code class="xref py py-func docutils literal notranslate"><span class="pre">pd()</span></code></a> | <a class="reference internal" href="#turtle.down" title="turtle.down"><code class="xref py py-func docutils literal notranslate"><span class="pre">down()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.penup" title="turtle.penup"><code class="xref py py-func docutils literal notranslate"><span class="pre">penup()</span></code></a> | <a class="reference internal" href="#turtle.pu" title="turtle.pu"><code class="xref py py-func docutils literal notranslate"><span class="pre">pu()</span></code></a> | <a class="reference internal" href="#turtle.up" title="turtle.up"><code class="xref py py-func docutils literal notranslate"><span class="pre">up()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.pensize" title="turtle.pensize"><code class="xref py py-func docutils literal notranslate"><span class="pre">pensize()</span></code></a> | <a class="reference internal" href="#turtle.width" title="turtle.width"><code class="xref py py-func docutils literal notranslate"><span class="pre">width()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.pen" title="turtle.pen"><code class="xref py py-func docutils literal notranslate"><span class="pre">pen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.isdown" title="turtle.isdown"><code class="xref py py-func docutils literal notranslate"><span class="pre">isdown()</span></code></a></div>
</div>
</dd>
<dt>Color control</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.color" title="turtle.color"><code class="xref py py-func docutils literal notranslate"><span class="pre">color()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.pencolor" title="turtle.pencolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">pencolor()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.fillcolor" title="turtle.fillcolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">fillcolor()</span></code></a></div>
</div>
</dd>
<dt>Filling</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.fill" title="turtle.fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.begin_fill" title="turtle.begin_fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">begin_fill()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.end_fill" title="turtle.end_fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">end_fill()</span></code></a></div>
</div>
</dd>
<dt>More drawing control</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.reset" title="turtle.reset"><code class="xref py py-func docutils literal notranslate"><span class="pre">reset()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.clear" title="turtle.clear"><code class="xref py py-func docutils literal notranslate"><span class="pre">clear()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.write" title="turtle.write"><code class="xref py py-func docutils literal notranslate"><span class="pre">write()</span></code></a></div>
</div>
</dd>
</dl>
</dd>
<dt>Turtle state</dt>
<dd><dl class="first last docutils">
<dt>Visibility</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.showturtle" title="turtle.showturtle"><code class="xref py py-func docutils literal notranslate"><span class="pre">showturtle()</span></code></a> | <a class="reference internal" href="#turtle.st" title="turtle.st"><code class="xref py py-func docutils literal notranslate"><span class="pre">st()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.hideturtle" title="turtle.hideturtle"><code class="xref py py-func docutils literal notranslate"><span class="pre">hideturtle()</span></code></a> | <a class="reference internal" href="#turtle.ht" title="turtle.ht"><code class="xref py py-func docutils literal notranslate"><span class="pre">ht()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.isvisible" title="turtle.isvisible"><code class="xref py py-func docutils literal notranslate"><span class="pre">isvisible()</span></code></a></div>
</div>
</dd>
<dt>Appearance</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.shape" title="turtle.shape"><code class="xref py py-func docutils literal notranslate"><span class="pre">shape()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.resizemode" title="turtle.resizemode"><code class="xref py py-func docutils literal notranslate"><span class="pre">resizemode()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.shapesize" title="turtle.shapesize"><code class="xref py py-func docutils literal notranslate"><span class="pre">shapesize()</span></code></a> | <a class="reference internal" href="#turtle.turtlesize" title="turtle.turtlesize"><code class="xref py py-func docutils literal notranslate"><span class="pre">turtlesize()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.settiltangle" title="turtle.settiltangle"><code class="xref py py-func docutils literal notranslate"><span class="pre">settiltangle()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.tiltangle" title="turtle.tiltangle"><code class="xref py py-func docutils literal notranslate"><span class="pre">tiltangle()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.tilt" title="turtle.tilt"><code class="xref py py-func docutils literal notranslate"><span class="pre">tilt()</span></code></a></div>
</div>
</dd>
</dl>
</dd>
<dt>Using events</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.onclick" title="turtle.onclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">onclick()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.onrelease" title="turtle.onrelease"><code class="xref py py-func docutils literal notranslate"><span class="pre">onrelease()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.ondrag" title="turtle.ondrag"><code class="xref py py-func docutils literal notranslate"><span class="pre">ondrag()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.mainloop" title="turtle.mainloop"><code class="xref py py-func docutils literal notranslate"><span class="pre">mainloop()</span></code></a> | <a class="reference internal" href="#turtle.done" title="turtle.done"><code class="xref py py-func docutils literal notranslate"><span class="pre">done()</span></code></a></div>
</div>
</dd>
<dt>Special Turtle methods</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.begin_poly" title="turtle.begin_poly"><code class="xref py py-func docutils literal notranslate"><span class="pre">begin_poly()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.end_poly" title="turtle.end_poly"><code class="xref py py-func docutils literal notranslate"><span class="pre">end_poly()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.get_poly" title="turtle.get_poly"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_poly()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.clone" title="turtle.clone"><code class="xref py py-func docutils literal notranslate"><span class="pre">clone()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.getturtle" title="turtle.getturtle"><code class="xref py py-func docutils literal notranslate"><span class="pre">getturtle()</span></code></a> | <a class="reference internal" href="#turtle.getpen" title="turtle.getpen"><code class="xref py py-func docutils literal notranslate"><span class="pre">getpen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.getscreen" title="turtle.getscreen"><code class="xref py py-func docutils literal notranslate"><span class="pre">getscreen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.setundobuffer" title="turtle.setundobuffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">setundobuffer()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.undobufferentries" title="turtle.undobufferentries"><code class="xref py py-func docutils literal notranslate"><span class="pre">undobufferentries()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.tracer" title="turtle.tracer"><code class="xref py py-func docutils literal notranslate"><span class="pre">tracer()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.window_width" title="turtle.window_width"><code class="xref py py-func docutils literal notranslate"><span class="pre">window_width()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.window_height" title="turtle.window_height"><code class="xref py py-func docutils literal notranslate"><span class="pre">window_height()</span></code></a></div>
</div>
</dd>
</dl>
</div>
<div class="section" id="methods-of-turtlescreen-screen">
<h3>24.5.2.2. Methods of TurtleScreen/Screen<a class="headerlink" href="#methods-of-turtlescreen-screen" title="Permalink to this headline">¶</a></h3>
<dl class="docutils">
<dt>Window control</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.bgcolor" title="turtle.bgcolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">bgcolor()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.bgpic" title="turtle.bgpic"><code class="xref py py-func docutils literal notranslate"><span class="pre">bgpic()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.clear" title="turtle.clear"><code class="xref py py-func docutils literal notranslate"><span class="pre">clear()</span></code></a> | <a class="reference internal" href="#turtle.clearscreen" title="turtle.clearscreen"><code class="xref py py-func docutils literal notranslate"><span class="pre">clearscreen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.reset" title="turtle.reset"><code class="xref py py-func docutils literal notranslate"><span class="pre">reset()</span></code></a> | <a class="reference internal" href="#turtle.resetscreen" title="turtle.resetscreen"><code class="xref py py-func docutils literal notranslate"><span class="pre">resetscreen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.screensize" title="turtle.screensize"><code class="xref py py-func docutils literal notranslate"><span class="pre">screensize()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.setworldcoordinates" title="turtle.setworldcoordinates"><code class="xref py py-func docutils literal notranslate"><span class="pre">setworldcoordinates()</span></code></a></div>
</div>
</dd>
<dt>Animation control</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.delay" title="turtle.delay"><code class="xref py py-func docutils literal notranslate"><span class="pre">delay()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.tracer" title="turtle.tracer"><code class="xref py py-func docutils literal notranslate"><span class="pre">tracer()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.update" title="turtle.update"><code class="xref py py-func docutils literal notranslate"><span class="pre">update()</span></code></a></div>
</div>
</dd>
<dt>Using screen events</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.listen" title="turtle.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.onkey" title="turtle.onkey"><code class="xref py py-func docutils literal notranslate"><span class="pre">onkey()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.onclick" title="turtle.onclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">onclick()</span></code></a> | <a class="reference internal" href="#turtle.onscreenclick" title="turtle.onscreenclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">onscreenclick()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.ontimer" title="turtle.ontimer"><code class="xref py py-func docutils literal notranslate"><span class="pre">ontimer()</span></code></a></div>
</div>
</dd>
<dt>Settings and special methods</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.mode" title="turtle.mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">mode()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.colormode" title="turtle.colormode"><code class="xref py py-func docutils literal notranslate"><span class="pre">colormode()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.getcanvas" title="turtle.getcanvas"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcanvas()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.getshapes" title="turtle.getshapes"><code class="xref py py-func docutils literal notranslate"><span class="pre">getshapes()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.register_shape" title="turtle.register_shape"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_shape()</span></code></a> | <a class="reference internal" href="#turtle.addshape" title="turtle.addshape"><code class="xref py py-func docutils literal notranslate"><span class="pre">addshape()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.turtles" title="turtle.turtles"><code class="xref py py-func docutils literal notranslate"><span class="pre">turtles()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.window_height" title="turtle.window_height"><code class="xref py py-func docutils literal notranslate"><span class="pre">window_height()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.window_width" title="turtle.window_width"><code class="xref py py-func docutils literal notranslate"><span class="pre">window_width()</span></code></a></div>
</div>
</dd>
<dt>Methods specific to Screen</dt>
<dd><div class="first last line-block">
<div class="line"><a class="reference internal" href="#turtle.bye" title="turtle.bye"><code class="xref py py-func docutils literal notranslate"><span class="pre">bye()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.exitonclick" title="turtle.exitonclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">exitonclick()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.setup" title="turtle.setup"><code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code></a></div>
<div class="line"><a class="reference internal" href="#turtle.title" title="turtle.title"><code class="xref py py-func docutils literal notranslate"><span class="pre">title()</span></code></a></div>
</div>
</dd>
</dl>
</div>
</div>
<div class="section" id="methods-of-rawturtle-turtle-and-corresponding-functions">
<h2>24.5.3. Methods of RawTurtle/Turtle and corresponding functions<a class="headerlink" href="#methods-of-rawturtle-turtle-and-corresponding-functions" title="Permalink to this headline">¶</a></h2>
<p>Most of the examples in this section refer to a Turtle instance called
<code class="docutils literal notranslate"><span class="pre">turtle</span></code>.</p>
<div class="section" id="turtle-motion">
<h3>24.5.3.1. Turtle motion<a class="headerlink" href="#turtle-motion" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.forward">
<code class="descclassname">turtle.</code><code class="descname">forward</code><span class="sig-paren">(</span><em>distance</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.forward" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.fd">
<code class="descclassname">turtle.</code><code class="descname">fd</code><span class="sig-paren">(</span><em>distance</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.fd" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>distance</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Move the turtle forward by the specified <em>distance</em>, in the direction the
turtle is headed.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="mi">25</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(25.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="o">-</span><span class="mi">75</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(-50.00,0.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.back">
<code class="descclassname">turtle.</code><code class="descname">back</code><span class="sig-paren">(</span><em>distance</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.back" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.bk">
<code class="descclassname">turtle.</code><code class="descname">bk</code><span class="sig-paren">(</span><em>distance</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.bk" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.backward">
<code class="descclassname">turtle.</code><code class="descname">backward</code><span class="sig-paren">(</span><em>distance</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.backward" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>distance</strong> – a number</td>
</tr>
</tbody>
</table>
<p>Move the turtle backward by <em>distance</em>, opposite to the direction the
turtle is headed.  Do not change the turtle’s heading.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">backward</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(-30.00,0.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.right">
<code class="descclassname">turtle.</code><code class="descname">right</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.right" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.rt">
<code class="descclassname">turtle.</code><code class="descname">rt</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.rt" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>angle</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Turn turtle right by <em>angle</em> units.  (Units are by default degrees, but
can be set via the <a class="reference internal" href="#turtle.degrees" title="turtle.degrees"><code class="xref py py-func docutils literal notranslate"><span class="pre">degrees()</span></code></a> and <a class="reference internal" href="#turtle.radians" title="turtle.radians"><code class="xref py py-func docutils literal notranslate"><span class="pre">radians()</span></code></a> functions.)  Angle
orientation depends on the turtle mode, see <a class="reference internal" href="#turtle.mode" title="turtle.mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">mode()</span></code></a>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">22.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">right</span><span class="p">(</span><span class="mi">45</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">337.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.left">
<code class="descclassname">turtle.</code><code class="descname">left</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.left" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.lt">
<code class="descclassname">turtle.</code><code class="descname">lt</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.lt" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>angle</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Turn turtle left by <em>angle</em> units.  (Units are by default degrees, but
can be set via the <a class="reference internal" href="#turtle.degrees" title="turtle.degrees"><code class="xref py py-func docutils literal notranslate"><span class="pre">degrees()</span></code></a> and <a class="reference internal" href="#turtle.radians" title="turtle.radians"><code class="xref py py-func docutils literal notranslate"><span class="pre">radians()</span></code></a> functions.)  Angle
orientation depends on the turtle mode, see <a class="reference internal" href="#turtle.mode" title="turtle.mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">mode()</span></code></a>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">22.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">45</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">67.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.goto">
<code class="descclassname">turtle.</code><code class="descname">goto</code><span class="sig-paren">(</span><em>x</em>, <em>y=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.goto" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.setpos">
<code class="descclassname">turtle.</code><code class="descname">setpos</code><span class="sig-paren">(</span><em>x</em>, <em>y=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setpos" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.setposition">
<code class="descclassname">turtle.</code><code class="descname">setposition</code><span class="sig-paren">(</span><em>x</em>, <em>y=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setposition" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>x</strong> – a number or a pair/vector of numbers</li>
<li><strong>y</strong> – a number or <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>If <em>y</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>x</em> must be a pair of coordinates or a <a class="reference internal" href="#turtle.Vec2D" title="turtle.Vec2D"><code class="xref py py-class docutils literal notranslate"><span class="pre">Vec2D</span></code></a>
(e.g. as returned by <a class="reference internal" href="#turtle.pos" title="turtle.pos"><code class="xref py py-func docutils literal notranslate"><span class="pre">pos()</span></code></a>).</p>
<p>Move turtle to an absolute position.  If the pen is down, draw line.  Do
not change the turtle’s orientation.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">tp</span> <span class="o">=</span> <span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tp</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setpos</span><span class="p">(</span><span class="mi">60</span><span class="p">,</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(60.00,30.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setpos</span><span class="p">((</span><span class="mi">20</span><span class="p">,</span><span class="mi">80</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(20.00,80.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setpos</span><span class="p">(</span><span class="n">tp</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.setx">
<code class="descclassname">turtle.</code><code class="descname">setx</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setx" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>x</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Set the turtle’s first coordinate to <em>x</em>, leave second coordinate
unchanged.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,240.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setx</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(10.00,240.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.sety">
<code class="descclassname">turtle.</code><code class="descname">sety</code><span class="sig-paren">(</span><em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.sety" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>y</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Set the turtle’s second coordinate to <em>y</em>, leave first coordinate unchanged.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,40.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">sety</span><span class="p">(</span><span class="o">-</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,-10.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.setheading">
<code class="descclassname">turtle.</code><code class="descname">setheading</code><span class="sig-paren">(</span><em>to_angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setheading" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.seth">
<code class="descclassname">turtle.</code><code class="descname">seth</code><span class="sig-paren">(</span><em>to_angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.seth" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>to_angle</strong> – a number (integer or float)</td>
</tr>
</tbody>
</table>
<p>Set the orientation of the turtle to <em>to_angle</em>.  Here are some common
directions in degrees:</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">standard mode</th>
<th class="head">logo mode</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>0 - east</td>
<td>0 - north</td>
</tr>
<tr class="row-odd"><td>90 - north</td>
<td>90 - east</td>
</tr>
<tr class="row-even"><td>180 - west</td>
<td>180 - south</td>
</tr>
<tr class="row-odd"><td>270 - south</td>
<td>270 - west</td>
</tr>
</tbody>
</table>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setheading</span><span class="p">(</span><span class="mi">90</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">90.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.home">
<code class="descclassname">turtle.</code><code class="descname">home</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.home" title="Permalink to this definition">¶</a></dt>
<dd><p>Move turtle to the origin – coordinates (0,0) – and set its heading to
its start-orientation (which depends on the mode, see <a class="reference internal" href="#turtle.mode" title="turtle.mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">mode()</span></code></a>).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">90.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,-10.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">0.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.circle">
<code class="descclassname">turtle.</code><code class="descname">circle</code><span class="sig-paren">(</span><em>radius</em>, <em>extent=None</em>, <em>steps=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.circle" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>radius</strong> – a number</li>
<li><strong>extent</strong> – a number (or <code class="docutils literal notranslate"><span class="pre">None</span></code>)</li>
<li><strong>steps</strong> – an integer (or <code class="docutils literal notranslate"><span class="pre">None</span></code>)</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Draw a circle with given <em>radius</em>.  The center is <em>radius</em> units left of
the turtle; <em>extent</em> – an angle – determines which part of the circle
is drawn.  If <em>extent</em> is not given, draw the entire circle.  If <em>extent</em>
is not a full circle, one endpoint of the arc is the current pen
position.  Draw the arc in counterclockwise direction if <em>radius</em> is
positive, otherwise in clockwise direction.  Finally the direction of the
turtle is changed by the amount of <em>extent</em>.</p>
<p>As the circle is approximated by an inscribed regular polygon, <em>steps</em>
determines the number of steps to use.  If not given, it will be
calculated automatically.  May be used to draw regular polygons.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">0.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">circle</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(-0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">0.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">circle</span><span class="p">(</span><span class="mi">120</span><span class="p">,</span> <span class="mi">180</span><span class="p">)</span>  <span class="c1"># draw a semicircle</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,240.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">180.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.dot">
<code class="descclassname">turtle.</code><code class="descname">dot</code><span class="sig-paren">(</span><em>size=None</em>, <em>*color</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.dot" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>size</strong> – an integer &gt;= 1 (if given)</li>
<li><strong>color</strong> – a colorstring or a numeric color tuple</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Draw a circular dot with diameter <em>size</em>, using <em>color</em>.  If <em>size</em> is
not given, the maximum of pensize+4 and 2*pensize is used.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">dot</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">);</span> <span class="n">turtle</span><span class="o">.</span><span class="n">dot</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="s2">&quot;blue&quot;</span><span class="p">);</span> <span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(100.00,-0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">0.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.stamp">
<code class="descclassname">turtle.</code><code class="descname">stamp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.stamp" title="Permalink to this definition">¶</a></dt>
<dd><p>Stamp a copy of the turtle shape onto the canvas at the current turtle
position.  Return a stamp_id for that stamp, which can be used to delete
it by calling <code class="docutils literal notranslate"><span class="pre">clearstamp(stamp_id)</span></code>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;blue&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">stamp</span><span class="p">()</span>
<span class="go">11</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.clearstamp">
<code class="descclassname">turtle.</code><code class="descname">clearstamp</code><span class="sig-paren">(</span><em>stampid</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.clearstamp" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>stampid</strong> – an integer, must be return value of previous
<a class="reference internal" href="#turtle.stamp" title="turtle.stamp"><code class="xref py py-func docutils literal notranslate"><span class="pre">stamp()</span></code></a> call</td>
</tr>
</tbody>
</table>
<p>Delete stamp with given <em>stampid</em>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(150.00,-0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;blue&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">astamp</span> <span class="o">=</span> <span class="n">turtle</span><span class="o">.</span><span class="n">stamp</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(200.00,-0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">clearstamp</span><span class="p">(</span><span class="n">astamp</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(200.00,-0.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.clearstamps">
<code class="descclassname">turtle.</code><code class="descname">clearstamps</code><span class="sig-paren">(</span><em>n=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.clearstamps" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>n</strong> – an integer (or <code class="docutils literal notranslate"><span class="pre">None</span></code>)</td>
</tr>
</tbody>
</table>
<p>Delete all or first/last <em>n</em> of turtle’s stamps.  If <em>n</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, delete
all stamps, if <em>n</em> &gt; 0 delete first <em>n</em> stamps, else if <em>n</em> &lt; 0 delete
last <em>n</em> stamps.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">turtle</span><span class="o">.</span><span class="n">stamp</span><span class="p">();</span> <span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span>
<span class="go">13</span>
<span class="go">14</span>
<span class="go">15</span>
<span class="go">16</span>
<span class="go">17</span>
<span class="go">18</span>
<span class="go">19</span>
<span class="go">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">clearstamps</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">clearstamps</span><span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">clearstamps</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.undo">
<code class="descclassname">turtle.</code><code class="descname">undo</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.undo" title="Permalink to this definition">¶</a></dt>
<dd><p>Undo (repeatedly) the last turtle action(s).  Number of available
undo actions is determined by the size of the undobuffer.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">);</span> <span class="n">turtle</span><span class="o">.</span><span class="n">lt</span><span class="p">(</span><span class="mi">80</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">turtle</span><span class="o">.</span><span class="n">undo</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.speed">
<code class="descclassname">turtle.</code><code class="descname">speed</code><span class="sig-paren">(</span><em>speed=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.speed" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>speed</strong> – an integer in the range 0..10 or a speedstring (see below)</td>
</tr>
</tbody>
</table>
<p>Set the turtle’s speed to an integer value in the range 0..10.  If no
argument is given, return current speed.</p>
<p>If input is a number greater than 10 or smaller than 0.5, speed is set
to 0.  Speedstrings are mapped to speedvalues as follows:</p>
<ul class="simple">
<li>“fastest”:  0</li>
<li>“fast”:  10</li>
<li>“normal”:  6</li>
<li>“slow”:  3</li>
<li>“slowest”:  1</li>
</ul>
<p>Speeds from 1 to 10 enforce increasingly faster animation of line drawing
and turtle turning.</p>
<p>Attention: <em>speed</em> = 0 means that <em>no</em> animation takes
place. forward/back makes turtle jump and likewise left/right make the
turtle turn instantly.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">speed</span><span class="p">()</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">speed</span><span class="p">(</span><span class="s1">&#39;normal&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">speed</span><span class="p">()</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">speed</span><span class="p">(</span><span class="mi">9</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">speed</span><span class="p">()</span>
<span class="go">9</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="tell-turtle-s-state">
<h3>24.5.3.2. Tell Turtle’s state<a class="headerlink" href="#tell-turtle-s-state" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.position">
<code class="descclassname">turtle.</code><code class="descname">position</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.position" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.pos">
<code class="descclassname">turtle.</code><code class="descname">pos</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pos" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the turtle’s current location (x,y) (as a <a class="reference internal" href="#turtle.Vec2D" title="turtle.Vec2D"><code class="xref py py-class docutils literal notranslate"><span class="pre">Vec2D</span></code></a> vector).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(440.00,-0.00)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.towards">
<code class="descclassname">turtle.</code><code class="descname">towards</code><span class="sig-paren">(</span><em>x</em>, <em>y=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.towards" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>x</strong> – a number or a pair/vector of numbers or a turtle instance</li>
<li><strong>y</strong> – a number if <em>x</em> is a number, else <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Return the angle between the line from turtle position to position specified
by (x,y), the vector or the other turtle.  This depends on the turtle’s start
orientation which depends on the mode - “standard”/”world” or “logo”).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">goto</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">towards</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">)</span>
<span class="go">225.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.xcor">
<code class="descclassname">turtle.</code><code class="descname">xcor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.xcor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the turtle’s x coordinate.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(64.28,76.60)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">turtle</span><span class="o">.</span><span class="n">xcor</span><span class="p">()</span>
<span class="go">64.2787609687</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.ycor">
<code class="descclassname">turtle.</code><code class="descname">ycor</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.ycor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the turtle’s y coordinate.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">turtle</span><span class="o">.</span><span class="n">pos</span><span class="p">()</span>
<span class="go">(50.00,86.60)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">print</span> <span class="n">turtle</span><span class="o">.</span><span class="n">ycor</span><span class="p">()</span>
<span class="go">86.6025403784</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.heading">
<code class="descclassname">turtle.</code><code class="descname">heading</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.heading" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the turtle’s current heading (value depends on the turtle mode, see
<a class="reference internal" href="#turtle.mode" title="turtle.mode"><code class="xref py py-func docutils literal notranslate"><span class="pre">mode()</span></code></a>).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">67</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">67.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.distance">
<code class="descclassname">turtle.</code><code class="descname">distance</code><span class="sig-paren">(</span><em>x</em>, <em>y=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.distance" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>x</strong> – a number or a pair/vector of numbers or a turtle instance</li>
<li><strong>y</strong> – a number if <em>x</em> is a number, else <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Return the distance from the turtle to (x,y), the given vector, or the given
other turtle, in turtle step units.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">distance</span><span class="p">(</span><span class="mi">30</span><span class="p">,</span><span class="mi">40</span><span class="p">)</span>
<span class="go">50.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">distance</span><span class="p">((</span><span class="mi">30</span><span class="p">,</span><span class="mi">40</span><span class="p">))</span>
<span class="go">50.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">joe</span> <span class="o">=</span> <span class="n">Turtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">joe</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="mi">77</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">distance</span><span class="p">(</span><span class="n">joe</span><span class="p">)</span>
<span class="go">77.0</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="settings-for-measurement">
<h3>24.5.3.3. Settings for measurement<a class="headerlink" href="#settings-for-measurement" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.degrees">
<code class="descclassname">turtle.</code><code class="descname">degrees</code><span class="sig-paren">(</span><em>fullcircle=360.0</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.degrees" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>fullcircle</strong> – a number</td>
</tr>
</tbody>
</table>
<p>Set angle measurement units, i.e. set number of “degrees” for a full circle.
Default value is 360 degrees.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">90</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">90.0</span>

<span class="go">Change angle measurement unit to grad (also known as gon,</span>
<span class="go">grade, or gradian and equals 1/100-th of the right angle.)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">degrees</span><span class="p">(</span><span class="mf">400.0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">100.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">degrees</span><span class="p">(</span><span class="mi">360</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">90.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.radians">
<code class="descclassname">turtle.</code><code class="descname">radians</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.radians" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the angle measurement units to radians.  Equivalent to
<code class="docutils literal notranslate"><span class="pre">degrees(2*math.pi)</span></code>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">90</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">90.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">radians</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">1.5707963267948966</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="pen-control">
<h3>24.5.3.4. Pen control<a class="headerlink" href="#pen-control" title="Permalink to this headline">¶</a></h3>
<div class="section" id="drawing-state">
<h4>24.5.3.4.1. Drawing state<a class="headerlink" href="#drawing-state" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.pendown">
<code class="descclassname">turtle.</code><code class="descname">pendown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pendown" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.pd">
<code class="descclassname">turtle.</code><code class="descname">pd</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pd" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.down">
<code class="descclassname">turtle.</code><code class="descname">down</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.down" title="Permalink to this definition">¶</a></dt>
<dd><p>Pull the pen down – drawing when moving.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.penup">
<code class="descclassname">turtle.</code><code class="descname">penup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.penup" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.pu">
<code class="descclassname">turtle.</code><code class="descname">pu</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pu" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.up">
<code class="descclassname">turtle.</code><code class="descname">up</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.up" title="Permalink to this definition">¶</a></dt>
<dd><p>Pull the pen up – no drawing when moving.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.pensize">
<code class="descclassname">turtle.</code><code class="descname">pensize</code><span class="sig-paren">(</span><em>width=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pensize" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.width">
<code class="descclassname">turtle.</code><code class="descname">width</code><span class="sig-paren">(</span><em>width=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.width" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>width</strong> – a positive number</td>
</tr>
</tbody>
</table>
<p>Set the line thickness to <em>width</em> or return it.  If resizemode is set to
“auto” and turtleshape is a polygon, that polygon is drawn with the same line
thickness.  If no argument is given, the current pensize is returned.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pensize</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pensize</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>   <span class="c1"># from here on lines of width 10 are drawn</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.pen">
<code class="descclassname">turtle.</code><code class="descname">pen</code><span class="sig-paren">(</span><em>pen=None</em>, <em>**pendict</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pen" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>pen</strong> – a dictionary with some or all of the below listed keys</li>
<li><strong>pendict</strong> – one or more keyword-arguments with the below listed keys as keywords</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Return or set the pen’s attributes in a “pen-dictionary” with the following
key/value pairs:</p>
<ul class="simple">
<li>“shown”: True/False</li>
<li>“pendown”: True/False</li>
<li>“pencolor”: color-string or color-tuple</li>
<li>“fillcolor”: color-string or color-tuple</li>
<li>“pensize”: positive number</li>
<li>“speed”: number in range 0..10</li>
<li>“resizemode”: “auto” or “user” or “noresize”</li>
<li>“stretchfactor”: (positive number, positive number)</li>
<li>“outline”: positive number</li>
<li>“tilt”: number</li>
</ul>
<p>This dictionary can be used as argument for a subsequent call to <a class="reference internal" href="#turtle.pen" title="turtle.pen"><code class="xref py py-func docutils literal notranslate"><span class="pre">pen()</span></code></a>
to restore the former pen-state.  Moreover one or more of these attributes
can be provided as keyword-arguments.  This can be used to set several pen
attributes in one statement.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">(</span><span class="n">fillcolor</span><span class="o">=</span><span class="s2">&quot;black&quot;</span><span class="p">,</span> <span class="n">pencolor</span><span class="o">=</span><span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="n">pensize</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">()</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;fillcolor&#39;, &#39;black&#39;), (&#39;outline&#39;, 1), (&#39;pencolor&#39;, &#39;red&#39;),</span>
<span class="go"> (&#39;pendown&#39;, True), (&#39;pensize&#39;, 10), (&#39;resizemode&#39;, &#39;noresize&#39;),</span>
<span class="go"> (&#39;shown&#39;, True), (&#39;speed&#39;, 9), (&#39;stretchfactor&#39;, (1, 1)), (&#39;tilt&#39;, 0)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">penstate</span><span class="o">=</span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;yellow&quot;</span><span class="p">,</span> <span class="s2">&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">penup</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">()</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;fillcolor&#39;, &#39;&#39;), (&#39;outline&#39;, 1), (&#39;pencolor&#39;, &#39;yellow&#39;),</span>
<span class="go"> (&#39;pendown&#39;, False), (&#39;pensize&#39;, 10), (&#39;resizemode&#39;, &#39;noresize&#39;),</span>
<span class="go"> (&#39;shown&#39;, True), (&#39;speed&#39;, 9), (&#39;stretchfactor&#39;, (1, 1)), (&#39;tilt&#39;, 0)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">(</span><span class="n">penstate</span><span class="p">,</span> <span class="n">fillcolor</span><span class="o">=</span><span class="s2">&quot;green&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">pen</span><span class="p">()</span><span class="o">.</span><span class="n">items</span><span class="p">())</span>
<span class="go">[(&#39;fillcolor&#39;, &#39;green&#39;), (&#39;outline&#39;, 1), (&#39;pencolor&#39;, &#39;red&#39;),</span>
<span class="go"> (&#39;pendown&#39;, True), (&#39;pensize&#39;, 10), (&#39;resizemode&#39;, &#39;noresize&#39;),</span>
<span class="go"> (&#39;shown&#39;, True), (&#39;speed&#39;, 9), (&#39;stretchfactor&#39;, (1, 1)), (&#39;tilt&#39;, 0)]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.isdown">
<code class="descclassname">turtle.</code><code class="descname">isdown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.isdown" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if pen is down, <code class="docutils literal notranslate"><span class="pre">False</span></code> if it’s up.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">penup</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">isdown</span><span class="p">()</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pendown</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">isdown</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="color-control">
<h4>24.5.3.4.2. Color control<a class="headerlink" href="#color-control" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.pencolor">
<code class="descclassname">turtle.</code><code class="descname">pencolor</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.pencolor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return or set the pencolor.</p>
<p>Four input formats are allowed:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">pencolor()</span></code></dt>
<dd>Return the current pencolor as color specification string or
as a tuple (see example).  May be used as input to another
color/pencolor/fillcolor call.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">pencolor(colorstring)</span></code></dt>
<dd>Set pencolor to <em>colorstring</em>, which is a Tk color specification string,
such as <code class="docutils literal notranslate"><span class="pre">&quot;red&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;yellow&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;#33cc8c&quot;</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">pencolor((r,</span> <span class="pre">g,</span> <span class="pre">b))</span></code></dt>
<dd>Set pencolor to the RGB color represented by the tuple of <em>r</em>, <em>g</em>, and
<em>b</em>.  Each of <em>r</em>, <em>g</em>, and <em>b</em> must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see <a class="reference internal" href="#turtle.colormode" title="turtle.colormode"><code class="xref py py-func docutils literal notranslate"><span class="pre">colormode()</span></code></a>).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">pencolor(r,</span> <span class="pre">g,</span> <span class="pre">b)</span></code></dt>
<dd><blockquote class="first">
<div>Set pencolor to the RGB color represented by <em>r</em>, <em>g</em>, and <em>b</em>.  Each of
<em>r</em>, <em>g</em>, and <em>b</em> must be in the range 0..colormode.</div></blockquote>
<p class="last">If turtleshape is a polygon, the outline of that polygon is drawn with the
newly set pencolor.</p>
</dd>
</dl>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">colormode</span><span class="p">()</span>
<span class="go">1.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="go">&#39;red&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">(</span><span class="s2">&quot;brown&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="go">&#39;brown&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tup</span> <span class="o">=</span> <span class="p">(</span><span class="mf">0.2</span><span class="p">,</span> <span class="mf">0.8</span><span class="p">,</span> <span class="mf">0.55</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">(</span><span class="n">tup</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="go">(0.2, 0.8, 0.5490196078431373)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">colormode</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="go">(51, 204, 140)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">(</span><span class="s1">&#39;#32c18f&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="go">(50, 193, 143)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.fillcolor">
<code class="descclassname">turtle.</code><code class="descname">fillcolor</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.fillcolor" title="Permalink to this definition">¶</a></dt>
<dd><p>Return or set the fillcolor.</p>
<p>Four input formats are allowed:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">fillcolor()</span></code></dt>
<dd>Return the current fillcolor as color specification string, possibly
in tuple format (see example).  May be used as input to another
color/pencolor/fillcolor call.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">fillcolor(colorstring)</span></code></dt>
<dd>Set fillcolor to <em>colorstring</em>, which is a Tk color specification string,
such as <code class="docutils literal notranslate"><span class="pre">&quot;red&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;yellow&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;#33cc8c&quot;</span></code>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">fillcolor((r,</span> <span class="pre">g,</span> <span class="pre">b))</span></code></dt>
<dd>Set fillcolor to the RGB color represented by the tuple of <em>r</em>, <em>g</em>, and
<em>b</em>.  Each of <em>r</em>, <em>g</em>, and <em>b</em> must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see <a class="reference internal" href="#turtle.colormode" title="turtle.colormode"><code class="xref py py-func docutils literal notranslate"><span class="pre">colormode()</span></code></a>).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">fillcolor(r,</span> <span class="pre">g,</span> <span class="pre">b)</span></code></dt>
<dd><blockquote class="first">
<div>Set fillcolor to the RGB color represented by <em>r</em>, <em>g</em>, and <em>b</em>.  Each of
<em>r</em>, <em>g</em>, and <em>b</em> must be in the range 0..colormode.</div></blockquote>
<p class="last">If turtleshape is a polygon, the interior of that polygon is drawn
with the newly set fillcolor.</p>
</dd>
</dl>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">(</span><span class="s2">&quot;violet&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">()</span>
<span class="go">&#39;violet&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">col</span> <span class="o">=</span> <span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">col</span>
<span class="go">(50, 193, 143)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">(</span><span class="n">col</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">()</span>
<span class="go">(50, 193, 143)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">(</span><span class="s1">&#39;#ffffff&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">()</span>
<span class="go">(255, 255, 255)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.color">
<code class="descclassname">turtle.</code><code class="descname">color</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.color" title="Permalink to this definition">¶</a></dt>
<dd><p>Return or set pencolor and fillcolor.</p>
<p>Several input formats are allowed.  They use 0 to 3 arguments as
follows:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">color()</span></code></dt>
<dd>Return the current pencolor and the current fillcolor as a pair of color
specification strings or tuples as returned by <a class="reference internal" href="#turtle.pencolor" title="turtle.pencolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">pencolor()</span></code></a> and
<a class="reference internal" href="#turtle.fillcolor" title="turtle.fillcolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">fillcolor()</span></code></a>.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">color(colorstring)</span></code>, <code class="docutils literal notranslate"><span class="pre">color((r,g,b))</span></code>, <code class="docutils literal notranslate"><span class="pre">color(r,g,b)</span></code></dt>
<dd>Inputs as in <a class="reference internal" href="#turtle.pencolor" title="turtle.pencolor"><code class="xref py py-func docutils literal notranslate"><span class="pre">pencolor()</span></code></a>, set both, fillcolor and pencolor, to the
given value.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">color(colorstring1,</span> <span class="pre">colorstring2)</span></code>, <code class="docutils literal notranslate"><span class="pre">color((r1,g1,b1),</span> <span class="pre">(r2,g2,b2))</span></code></dt>
<dd><blockquote class="first">
<div>Equivalent to <code class="docutils literal notranslate"><span class="pre">pencolor(colorstring1)</span></code> and <code class="docutils literal notranslate"><span class="pre">fillcolor(colorstring2)</span></code>
and analogously if the other input format is used.</div></blockquote>
<p class="last">If turtleshape is a polygon, outline and interior of that polygon is drawn
with the newly set colors.</p>
</dd>
</dl>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="s2">&quot;green&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">()</span>
<span class="go">(&#39;red&#39;, &#39;green&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;#285078&quot;</span><span class="p">,</span> <span class="s2">&quot;#a0c8f0&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">color</span><span class="p">()</span>
<span class="go">((40, 80, 120), (160, 200, 240))</span>
</pre></div>
</div>
</dd></dl>

<p>See also: Screen method <a class="reference internal" href="#turtle.colormode" title="turtle.colormode"><code class="xref py py-func docutils literal notranslate"><span class="pre">colormode()</span></code></a>.</p>
</div>
<div class="section" id="filling">
<h4>24.5.3.4.3. Filling<a class="headerlink" href="#filling" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.fill">
<code class="descclassname">turtle.</code><code class="descname">fill</code><span class="sig-paren">(</span><em>flag</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.fill" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>flag</strong> – True/False (or 1/0 respectively)</td>
</tr>
</tbody>
</table>
<p>Call <code class="docutils literal notranslate"><span class="pre">fill(True)</span></code> before drawing the shape you want to fill, and
<code class="docutils literal notranslate"><span class="pre">fill(False)</span></code> when done.  When used without argument: return fillstate
(<code class="docutils literal notranslate"><span class="pre">True</span></code> if filling, <code class="docutils literal notranslate"><span class="pre">False</span></code> else).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
<span class="gp">... </span>   <span class="n">turtle</span><span class="o">.</span><span class="n">forward</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="gp">... </span>   <span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">120</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="bp">False</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.begin_fill">
<code class="descclassname">turtle.</code><code class="descname">begin_fill</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.begin_fill" title="Permalink to this definition">¶</a></dt>
<dd><p>Call just before drawing a shape to be filled.  Equivalent to <code class="docutils literal notranslate"><span class="pre">fill(True)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.end_fill">
<code class="descclassname">turtle.</code><code class="descname">end_fill</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.end_fill" title="Permalink to this definition">¶</a></dt>
<dd><p>Fill the shape drawn after the last call to <a class="reference internal" href="#turtle.begin_fill" title="turtle.begin_fill"><code class="xref py py-func docutils literal notranslate"><span class="pre">begin_fill()</span></code></a>.  Equivalent
to <code class="docutils literal notranslate"><span class="pre">fill(False)</span></code>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;black&quot;</span><span class="p">,</span> <span class="s2">&quot;red&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">begin_fill</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">circle</span><span class="p">(</span><span class="mi">80</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">end_fill</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="more-drawing-control">
<h4>24.5.3.4.4. More drawing control<a class="headerlink" href="#more-drawing-control" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.reset">
<code class="descclassname">turtle.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the turtle’s drawings from the screen, re-center the turtle and set
variables to the default values.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">goto</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="o">-</span><span class="mi">22</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,-22.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">100.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">position</span><span class="p">()</span>
<span class="go">(0.00,0.00)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">heading</span><span class="p">()</span>
<span class="go">0.0</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.clear">
<code class="descclassname">turtle.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete the turtle’s drawings from the screen.  Do not move turtle.  State and
position of the turtle as well as drawings of other turtles are not affected.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.write">
<code class="descclassname">turtle.</code><code class="descname">write</code><span class="sig-paren">(</span><em>arg</em>, <em>move=False</em>, <em>align=&quot;left&quot;</em>, <em>font=(&quot;Arial&quot;</em>, <em>8</em>, <em>&quot;normal&quot;)</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.write" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>arg</strong> – object to be written to the TurtleScreen</li>
<li><strong>move</strong> – True/False</li>
<li><strong>align</strong> – one of the strings “left”, “center” or right”</li>
<li><strong>font</strong> – a triple (fontname, fontsize, fonttype)</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Write text - the string representation of <em>arg</em> - at the current turtle
position according to <em>align</em> (“left”, “center” or right”) and with the given
font.  If <em>move</em> is true, the pen is moved to the bottom-right corner of the
text.  By default, <em>move</em> is <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;Home = &quot;</span><span class="p">,</span> <span class="kc">True</span><span class="p">,</span> <span class="n">align</span><span class="o">=</span><span class="s2">&quot;center&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">write</span><span class="p">((</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">),</span> <span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="turtle-state">
<h3>24.5.3.5. Turtle state<a class="headerlink" href="#turtle-state" title="Permalink to this headline">¶</a></h3>
<div class="section" id="visibility">
<h4>24.5.3.5.1. Visibility<a class="headerlink" href="#visibility" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.hideturtle">
<code class="descclassname">turtle.</code><code class="descname">hideturtle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.hideturtle" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.ht">
<code class="descclassname">turtle.</code><code class="descname">ht</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.ht" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the turtle invisible.  It’s a good idea to do this while you’re in the
middle of doing some complex drawing, because hiding the turtle speeds up the
drawing observably.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">hideturtle</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.showturtle">
<code class="descclassname">turtle.</code><code class="descname">showturtle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.showturtle" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.st">
<code class="descclassname">turtle.</code><code class="descname">st</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.st" title="Permalink to this definition">¶</a></dt>
<dd><p>Make the turtle visible.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">showturtle</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.isvisible">
<code class="descclassname">turtle.</code><code class="descname">isvisible</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.isvisible" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the Turtle is shown, <code class="docutils literal notranslate"><span class="pre">False</span></code> if it’s hidden.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">hideturtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">isvisible</span><span class="p">()</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">showturtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">isvisible</span><span class="p">()</span>
<span class="go">True</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="appearance">
<h4>24.5.3.5.2. Appearance<a class="headerlink" href="#appearance" title="Permalink to this headline">¶</a></h4>
<dl class="function">
<dt id="turtle.shape">
<code class="descclassname">turtle.</code><code class="descname">shape</code><span class="sig-paren">(</span><em>name=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.shape" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>name</strong> – a string which is a valid shapename</td>
</tr>
</tbody>
</table>
<p>Set turtle shape to shape with given <em>name</em> or, if name is not given, return
name of current shape.  Shape with <em>name</em> must exist in the TurtleScreen’s
shape dictionary.  Initially there are the following polygon shapes: “arrow”,
“turtle”, “circle”, “square”, “triangle”, “classic”.  To learn about how to
deal with shapes see Screen method <a class="reference internal" href="#turtle.register_shape" title="turtle.register_shape"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_shape()</span></code></a>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">()</span>
<span class="go">&#39;classic&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="s2">&quot;turtle&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">()</span>
<span class="go">&#39;turtle&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.resizemode">
<code class="descclassname">turtle.</code><code class="descname">resizemode</code><span class="sig-paren">(</span><em>rmode=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.resizemode" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>rmode</strong> – one of the strings “auto”, “user”, “noresize”</td>
</tr>
</tbody>
</table>
<p>Set resizemode to one of the values: “auto”, “user”, “noresize”.  If <em>rmode</em>
is not given, return current resizemode.  Different resizemodes have the
following effects:</p>
<ul class="simple">
<li>“auto”: adapts the appearance of the turtle corresponding to the value of pensize.</li>
<li>“user”: adapts the appearance of the turtle according to the values of
stretchfactor and outlinewidth (outline), which are set by
<a class="reference internal" href="#turtle.shapesize" title="turtle.shapesize"><code class="xref py py-func docutils literal notranslate"><span class="pre">shapesize()</span></code></a>.</li>
<li>“noresize”: no adaption of the turtle’s appearance takes place.</li>
</ul>
<p>resizemode(“user”) is called by <a class="reference internal" href="#turtle.shapesize" title="turtle.shapesize"><code class="xref py py-func docutils literal notranslate"><span class="pre">shapesize()</span></code></a> when used with arguments.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">resizemode</span><span class="p">()</span>
<span class="go">&#39;noresize&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">resizemode</span><span class="p">(</span><span class="s2">&quot;auto&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">resizemode</span><span class="p">()</span>
<span class="go">&#39;auto&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.shapesize">
<code class="descclassname">turtle.</code><code class="descname">shapesize</code><span class="sig-paren">(</span><em>stretch_wid=None</em>, <em>stretch_len=None</em>, <em>outline=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.shapesize" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.turtlesize">
<code class="descclassname">turtle.</code><code class="descname">turtlesize</code><span class="sig-paren">(</span><em>stretch_wid=None</em>, <em>stretch_len=None</em>, <em>outline=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.turtlesize" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>stretch_wid</strong> – positive number</li>
<li><strong>stretch_len</strong> – positive number</li>
<li><strong>outline</strong> – positive number</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Return or set the pen’s attributes x/y-stretchfactors and/or outline.  Set
resizemode to “user”.  If and only if resizemode is set to “user”, the turtle
will be displayed stretched according to its stretchfactors: <em>stretch_wid</em> is
stretchfactor perpendicular to its orientation, <em>stretch_len</em> is
stretchfactor in direction of its orientation, <em>outline</em> determines the width
of the shapes’s outline.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">()</span>
<span class="go">(1, 1, 1)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">resizemode</span><span class="p">(</span><span class="s2">&quot;user&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">12</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">()</span>
<span class="go">(5, 5, 12)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">(</span><span class="n">outline</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">()</span>
<span class="go">(5, 5, 8)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.tilt">
<code class="descclassname">turtle.</code><code class="descname">tilt</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.tilt" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>angle</strong> – a number</td>
</tr>
</tbody>
</table>
<p>Rotate the turtleshape by <em>angle</em> from its current tilt-angle, but do <em>not</em>
change the turtle’s heading (direction of movement).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="s2">&quot;circle&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">tilt</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">tilt</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.settiltangle">
<code class="descclassname">turtle.</code><code class="descname">settiltangle</code><span class="sig-paren">(</span><em>angle</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.settiltangle" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>angle</strong> – a number</td>
</tr>
</tbody>
</table>
<p>Rotate the turtleshape to point in the direction specified by <em>angle</em>,
regardless of its current tilt-angle.  <em>Do not</em> change the turtle’s heading
(direction of movement).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="s2">&quot;circle&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">settiltangle</span><span class="p">(</span><span class="mi">45</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">settiltangle</span><span class="p">(</span><span class="o">-</span><span class="mi">45</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.tiltangle">
<code class="descclassname">turtle.</code><code class="descname">tiltangle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.tiltangle" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current tilt-angle, i.e. the angle between the orientation of the
turtleshape and the heading of the turtle (its direction of movement).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shape</span><span class="p">(</span><span class="s2">&quot;circle&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">shapesize</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">tilt</span><span class="p">(</span><span class="mi">45</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">tiltangle</span><span class="p">()</span>
<span class="go">45.0</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="using-events">
<h3>24.5.3.6. Using events<a class="headerlink" href="#using-events" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.onclick">
<code class="descclassname">turtle.</code><code class="descname">onclick</code><span class="sig-paren">(</span><em>fun</em>, <em>btn=1</em>, <em>add=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.onclick" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with two arguments which will be called with the
coordinates of the clicked point on the canvas</li>
<li><strong>btn</strong> – number of the mouse-button, defaults to 1 (left mouse button)</li>
<li><strong>add</strong> – <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code> – if <code class="docutils literal notranslate"><span class="pre">True</span></code>, a new binding will be
added, otherwise it will replace a former binding</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Bind <em>fun</em> to mouse-click events on this turtle.  If <em>fun</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
existing bindings are removed.  Example for the anonymous turtle, i.e. the
procedural way:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">turn</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">left</span><span class="p">(</span><span class="mi">180</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">onclick</span><span class="p">(</span><span class="n">turn</span><span class="p">)</span>  <span class="c1"># Now clicking into the turtle will turn it.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">onclick</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>  <span class="c1"># event-binding will be removed</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.onrelease">
<code class="descclassname">turtle.</code><code class="descname">onrelease</code><span class="sig-paren">(</span><em>fun</em>, <em>btn=1</em>, <em>add=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.onrelease" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with two arguments which will be called with the
coordinates of the clicked point on the canvas</li>
<li><strong>btn</strong> – number of the mouse-button, defaults to 1 (left mouse button)</li>
<li><strong>add</strong> – <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code> – if <code class="docutils literal notranslate"><span class="pre">True</span></code>, a new binding will be
added, otherwise it will replace a former binding</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Bind <em>fun</em> to mouse-button-release events on this turtle.  If <em>fun</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, existing bindings are removed.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyTurtle</span><span class="p">(</span><span class="n">Turtle</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">glow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">(</span><span class="s2">&quot;red&quot;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">unglow</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">fillcolor</span><span class="p">(</span><span class="s2">&quot;&quot;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span> <span class="o">=</span> <span class="n">MyTurtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">onclick</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">glow</span><span class="p">)</span>     <span class="c1"># clicking on turtle turns fillcolor red,</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">onrelease</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">unglow</span><span class="p">)</span> <span class="c1"># releasing turns it to transparent.</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.ondrag">
<code class="descclassname">turtle.</code><code class="descname">ondrag</code><span class="sig-paren">(</span><em>fun</em>, <em>btn=1</em>, <em>add=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.ondrag" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with two arguments which will be called with the
coordinates of the clicked point on the canvas</li>
<li><strong>btn</strong> – number of the mouse-button, defaults to 1 (left mouse button)</li>
<li><strong>add</strong> – <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code> – if <code class="docutils literal notranslate"><span class="pre">True</span></code>, a new binding will be
added, otherwise it will replace a former binding</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Bind <em>fun</em> to mouse-move events on this turtle.  If <em>fun</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
existing bindings are removed.</p>
<p>Remark: Every sequence of mouse-move-events on a turtle is preceded by a
mouse-click event on that turtle.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">ondrag</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">goto</span><span class="p">)</span>
</pre></div>
</div>
<p>Subsequently, clicking and dragging the Turtle will move it across
the screen thereby producing handdrawings (if pen is down).</p>
</dd></dl>

<dl class="function">
<dt id="turtle.mainloop">
<code class="descclassname">turtle.</code><code class="descname">mainloop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.mainloop" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.done">
<code class="descclassname">turtle.</code><code class="descname">done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.done" title="Permalink to this definition">¶</a></dt>
<dd><p>Starts event loop - calling Tkinter’s mainloop function. Must be the last
statement in a turtle graphics program.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">mainloop</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="special-turtle-methods">
<h3>24.5.3.7. Special Turtle methods<a class="headerlink" href="#special-turtle-methods" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.begin_poly">
<code class="descclassname">turtle.</code><code class="descname">begin_poly</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.begin_poly" title="Permalink to this definition">¶</a></dt>
<dd><p>Start recording the vertices of a polygon.  Current turtle position is first
vertex of polygon.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.end_poly">
<code class="descclassname">turtle.</code><code class="descname">end_poly</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.end_poly" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop recording the vertices of a polygon.  Current turtle position is last
vertex of polygon.  This will be connected with the first vertex.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.get_poly">
<code class="descclassname">turtle.</code><code class="descname">get_poly</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.get_poly" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the last recorded polygon.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">home</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">begin_poly</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">20</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">30</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">left</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">end_poly</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">turtle</span><span class="o">.</span><span class="n">get_poly</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">register_shape</span><span class="p">(</span><span class="s2">&quot;myFavouriteShape&quot;</span><span class="p">,</span> <span class="n">p</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.clone">
<code class="descclassname">turtle.</code><code class="descname">clone</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.clone" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a clone of the turtle with same position, heading and
turtle properties.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mick</span> <span class="o">=</span> <span class="n">Turtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">joe</span> <span class="o">=</span> <span class="n">mick</span><span class="o">.</span><span class="n">clone</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.getturtle">
<code class="descclassname">turtle.</code><code class="descname">getturtle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.getturtle" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.getpen">
<code class="descclassname">turtle.</code><code class="descname">getpen</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.getpen" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Turtle object itself.  Only reasonable use: as a function to
return the “anonymous turtle”:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pet</span> <span class="o">=</span> <span class="n">getturtle</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pet</span><span class="o">.</span><span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pet</span>
<span class="go">&lt;turtle.Turtle object at 0x...&gt;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.getscreen">
<code class="descclassname">turtle.</code><code class="descname">getscreen</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.getscreen" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <a class="reference internal" href="#turtle.TurtleScreen" title="turtle.TurtleScreen"><code class="xref py py-class docutils literal notranslate"><span class="pre">TurtleScreen</span></code></a> object the turtle is drawing on.
TurtleScreen methods can then be called for that object.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span> <span class="o">=</span> <span class="n">turtle</span><span class="o">.</span><span class="n">getscreen</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span>
<span class="go">&lt;turtle._Screen object at 0x...&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ts</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">(</span><span class="s2">&quot;pink&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.setundobuffer">
<code class="descclassname">turtle.</code><code class="descname">setundobuffer</code><span class="sig-paren">(</span><em>size</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setundobuffer" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>size</strong> – an integer or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
</tbody>
</table>
<p>Set or disable undobuffer.  If <em>size</em> is an integer an empty undobuffer of
given size is installed.  <em>size</em> gives the maximum number of turtle actions
that can be undone by the <a class="reference internal" href="#turtle.undo" title="turtle.undo"><code class="xref py py-func docutils literal notranslate"><span class="pre">undo()</span></code></a> method/function.  If <em>size</em> is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, the undobuffer is disabled.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">setundobuffer</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.undobufferentries">
<code class="descclassname">turtle.</code><code class="descname">undobufferentries</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.undobufferentries" title="Permalink to this definition">¶</a></dt>
<dd><p>Return number of entries in the undobuffer.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">undobufferentries</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">undo</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.tracer">
<code class="descclassname">turtle.</code><code class="descname">tracer</code><span class="sig-paren">(</span><em>flag=None</em>, <em>delay=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.tracer" title="Permalink to this definition">¶</a></dt>
<dd><p>A replica of the corresponding TurtleScreen method.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.window_width">
<code class="descclassname">turtle.</code><code class="descname">window_width</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.window_width" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.window_height">
<code class="descclassname">turtle.</code><code class="descname">window_height</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.window_height" title="Permalink to this definition">¶</a></dt>
<dd><p>Both are replicas of the corresponding TurtleScreen methods.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="excursus-about-the-use-of-compound-shapes">
<span id="compoundshapes"></span><h3>24.5.3.8. Excursus about the use of compound shapes<a class="headerlink" href="#excursus-about-the-use-of-compound-shapes" title="Permalink to this headline">¶</a></h3>
<p>To use compound turtle shapes, which consist of several polygons of different
color, you must use the helper class <a class="reference internal" href="#turtle.Shape" title="turtle.Shape"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shape</span></code></a> explicitly as described
below:</p>
<ol class="arabic">
<li><p class="first">Create an empty Shape object of type “compound”.</p>
</li>
<li><p class="first">Add as many components to this object as desired, using the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">addcomponent()</span></code> method.</p>
<p>For example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Shape</span><span class="p">(</span><span class="s2">&quot;compound&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly1</span> <span class="o">=</span> <span class="p">((</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">),(</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">),(</span><span class="mi">0</span><span class="p">,</span><span class="mi">10</span><span class="p">),(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">addcomponent</span><span class="p">(</span><span class="n">poly1</span><span class="p">,</span> <span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="s2">&quot;blue&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly2</span> <span class="o">=</span> <span class="p">((</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">),(</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">),(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">addcomponent</span><span class="p">(</span><span class="n">poly2</span><span class="p">,</span> <span class="s2">&quot;blue&quot;</span><span class="p">,</span> <span class="s2">&quot;red&quot;</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">Now add the Shape to the Screen’s shapelist and use it:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">register_shape</span><span class="p">(</span><span class="s2">&quot;myshape&quot;</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shape</span><span class="p">(</span><span class="s2">&quot;myshape&quot;</span><span class="p">)</span>
</pre></div>
</div>
</li>
</ol>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#turtle.Shape" title="turtle.Shape"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shape</span></code></a> class is used internally by the <a class="reference internal" href="#turtle.register_shape" title="turtle.register_shape"><code class="xref py py-func docutils literal notranslate"><span class="pre">register_shape()</span></code></a>
method in different ways.  The application programmer has to deal with the
Shape class <em>only</em> when using compound shapes like shown above!</p>
</div>
</div>
</div>
<div class="section" id="methods-of-turtlescreen-screen-and-corresponding-functions">
<h2>24.5.4. Methods of TurtleScreen/Screen and corresponding functions<a class="headerlink" href="#methods-of-turtlescreen-screen-and-corresponding-functions" title="Permalink to this headline">¶</a></h2>
<p>Most of the examples in this section refer to a TurtleScreen instance called
<code class="docutils literal notranslate"><span class="pre">screen</span></code>.</p>
<div class="section" id="window-control">
<h3>24.5.4.1. Window control<a class="headerlink" href="#window-control" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.bgcolor">
<code class="descclassname">turtle.</code><code class="descname">bgcolor</code><span class="sig-paren">(</span><em>*args</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.bgcolor" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>args</strong> – a color string or three numbers in the range 0..colormode or a
3-tuple of such numbers</td>
</tr>
</tbody>
</table>
<p>Set or return background color of the TurtleScreen.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">(</span><span class="s2">&quot;orange&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">()</span>
<span class="go">&#39;orange&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">(</span><span class="s2">&quot;#800080&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">()</span>
<span class="go">(128, 0, 128)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.bgpic">
<code class="descclassname">turtle.</code><code class="descname">bgpic</code><span class="sig-paren">(</span><em>picname=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.bgpic" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>picname</strong> – a string, name of a gif-file or <code class="docutils literal notranslate"><span class="pre">&quot;nopic&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">None</span></code></td>
</tr>
</tbody>
</table>
<p>Set background image or return name of current backgroundimage.  If <em>picname</em>
is a filename, set the corresponding image as background.  If <em>picname</em> is
<code class="docutils literal notranslate"><span class="pre">&quot;nopic&quot;</span></code>, delete background image, if present.  If <em>picname</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
return the filename of the current backgroundimage.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgpic</span><span class="p">()</span>
<span class="go">&#39;nopic&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgpic</span><span class="p">(</span><span class="s2">&quot;landscape.gif&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">bgpic</span><span class="p">()</span>
<span class="go">&quot;landscape.gif&quot;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dt id="turtle.clearscreen">
<code class="descclassname">turtle.</code><code class="descname">clearscreen</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.clearscreen" title="Permalink to this definition">¶</a></dt>
<dd><p>Delete all drawings and all turtles from the TurtleScreen.  Reset the now
empty TurtleScreen to its initial state: white background, no background
image, no event bindings and tracing on.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This TurtleScreen method is available as a global function only under the
name <code class="docutils literal notranslate"><span class="pre">clearscreen</span></code>.  The global function <code class="docutils literal notranslate"><span class="pre">clear</span></code> is another one
derived from the Turtle method <code class="docutils literal notranslate"><span class="pre">clear</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dt id="turtle.resetscreen">
<code class="descclassname">turtle.</code><code class="descname">resetscreen</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.resetscreen" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset all Turtles on the Screen to their initial state.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This TurtleScreen method is available as a global function only under the
name <code class="docutils literal notranslate"><span class="pre">resetscreen</span></code>.  The global function <code class="docutils literal notranslate"><span class="pre">reset</span></code> is another one
derived from the Turtle method <code class="docutils literal notranslate"><span class="pre">reset</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.screensize">
<code class="descclassname">turtle.</code><code class="descname">screensize</code><span class="sig-paren">(</span><em>canvwidth=None</em>, <em>canvheight=None</em>, <em>bg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.screensize" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>canvwidth</strong> – positive integer, new width of canvas in pixels</li>
<li><strong>canvheight</strong> – positive integer, new height of canvas in pixels</li>
<li><strong>bg</strong> – colorstring or color-tuple, new background color</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>If no arguments are given, return current (canvaswidth, canvasheight).  Else
resize the canvas the turtles are drawing on.  Do not alter the drawing
window.  To observe hidden parts of the canvas, use the scrollbars. With this
method, one can make visible those parts of a drawing which were outside the
canvas before.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">screensize</span><span class="p">()</span>
<span class="go">(400, 300)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">screensize</span><span class="p">(</span><span class="mi">2000</span><span class="p">,</span><span class="mi">1500</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">screensize</span><span class="p">()</span>
<span class="go">(2000, 1500)</span>
</pre></div>
</div>
<p>e.g. to search for an erroneously escaped turtle ;-)</p>
</dd></dl>

<dl class="function">
<dt id="turtle.setworldcoordinates">
<code class="descclassname">turtle.</code><code class="descname">setworldcoordinates</code><span class="sig-paren">(</span><em>llx</em>, <em>lly</em>, <em>urx</em>, <em>ury</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setworldcoordinates" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>llx</strong> – a number, x-coordinate of lower left corner of canvas</li>
<li><strong>lly</strong> – a number, y-coordinate of lower left corner of canvas</li>
<li><strong>urx</strong> – a number, x-coordinate of upper right corner of canvas</li>
<li><strong>ury</strong> – a number, y-coordinate of upper right corner of canvas</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Set up user-defined coordinate system and switch to mode “world” if
necessary.  This performs a <code class="docutils literal notranslate"><span class="pre">screen.reset()</span></code>.  If mode “world” is already
active, all drawings are redrawn according to the new coordinates.</p>
<p><strong>ATTENTION</strong>: in user-defined coordinate systems angles may appear
distorted.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">reset</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">setworldcoordinates</span><span class="p">(</span><span class="o">-</span><span class="mi">50</span><span class="p">,</span><span class="o">-</span><span class="mf">7.5</span><span class="p">,</span><span class="mi">50</span><span class="p">,</span><span class="mf">7.5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">72</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">left</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">left</span><span class="p">(</span><span class="mi">45</span><span class="p">);</span> <span class="n">fd</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>   <span class="c1"># a regular octagon</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="animation-control">
<h3>24.5.4.2. Animation control<a class="headerlink" href="#animation-control" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.delay">
<code class="descclassname">turtle.</code><code class="descname">delay</code><span class="sig-paren">(</span><em>delay=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.delay" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>delay</strong> – positive integer</td>
</tr>
</tbody>
</table>
<p>Set or return the drawing <em>delay</em> in milliseconds.  (This is approximately
the time interval between two consecutive canvas updates.)  The longer the
drawing delay, the slower the animation.</p>
<p>Optional argument:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">delay</span><span class="p">()</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">delay</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">delay</span><span class="p">()</span>
<span class="go">5</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">tracer</code><span class="sig-paren">(</span><em>n=None</em>, <em>delay=None</em><span class="sig-paren">)</span></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>n</strong> – nonnegative integer</li>
<li><strong>delay</strong> – nonnegative integer</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Turn turtle animation on/off and set delay for update drawings.  If <em>n</em> is
given, only each n-th regular screen update is really performed.  (Can be
used to accelerate the drawing of complex graphics.)  Second argument sets
delay value (see <a class="reference internal" href="#turtle.delay" title="turtle.delay"><code class="xref py py-func docutils literal notranslate"><span class="pre">delay()</span></code></a>).</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">tracer</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="mi">25</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dist</span> <span class="o">=</span> <span class="mi">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">200</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">fd</span><span class="p">(</span><span class="n">dist</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">rt</span><span class="p">(</span><span class="mi">90</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">dist</span> <span class="o">+=</span> <span class="mi">2</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.update">
<code class="descclassname">turtle.</code><code class="descname">update</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.update" title="Permalink to this definition">¶</a></dt>
<dd><p>Perform a TurtleScreen update. To be used when tracer is turned off.</p>
</dd></dl>

<p>See also the RawTurtle/Turtle method <a class="reference internal" href="#turtle.speed" title="turtle.speed"><code class="xref py py-func docutils literal notranslate"><span class="pre">speed()</span></code></a>.</p>
</div>
<div class="section" id="using-screen-events">
<h3>24.5.4.3. Using screen events<a class="headerlink" href="#using-screen-events" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.listen">
<code class="descclassname">turtle.</code><code class="descname">listen</code><span class="sig-paren">(</span><em>xdummy=None</em>, <em>ydummy=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.listen" title="Permalink to this definition">¶</a></dt>
<dd><p>Set focus on TurtleScreen (in order to collect key-events).  Dummy arguments
are provided in order to be able to pass <a class="reference internal" href="#turtle.listen" title="turtle.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a> to the onclick method.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.onkey">
<code class="descclassname">turtle.</code><code class="descname">onkey</code><span class="sig-paren">(</span><em>fun</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.onkey" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with no arguments or <code class="docutils literal notranslate"><span class="pre">None</span></code></li>
<li><strong>key</strong> – a string: key (e.g. “a”) or key-symbol (e.g. “space”)</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Bind <em>fun</em> to key-release event of key.  If <em>fun</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, event bindings
are removed. Remark: in order to be able to register key-events, TurtleScreen
must have the focus. (See method <a class="reference internal" href="#turtle.listen" title="turtle.listen"><code class="xref py py-func docutils literal notranslate"><span class="pre">listen()</span></code></a>.)</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">lt</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">onkey</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="s2">&quot;Up&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">listen</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">onclick</code><span class="sig-paren">(</span><em>fun</em>, <em>btn=1</em>, <em>add=None</em><span class="sig-paren">)</span></dt>
<dt id="turtle.onscreenclick">
<code class="descclassname">turtle.</code><code class="descname">onscreenclick</code><span class="sig-paren">(</span><em>fun</em>, <em>btn=1</em>, <em>add=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.onscreenclick" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with two arguments which will be called with the
coordinates of the clicked point on the canvas</li>
<li><strong>btn</strong> – number of the mouse-button, defaults to 1 (left mouse button)</li>
<li><strong>add</strong> – <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code> – if <code class="docutils literal notranslate"><span class="pre">True</span></code>, a new binding will be
added, otherwise it will replace a former binding</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Bind <em>fun</em> to mouse-click events on this screen.  If <em>fun</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>,
existing bindings are removed.</p>
<p>Example for a TurtleScreen instance named <code class="docutils literal notranslate"><span class="pre">screen</span></code> and a Turtle instance
named turtle:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">onclick</span><span class="p">(</span><span class="n">turtle</span><span class="o">.</span><span class="n">goto</span><span class="p">)</span> <span class="c1"># Subsequently clicking into the TurtleScreen will</span>
<span class="gp">&gt;&gt;&gt; </span>                            <span class="c1"># make the turtle move to the clicked point.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">onclick</span><span class="p">(</span><span class="bp">None</span><span class="p">)</span>        <span class="c1"># remove event binding again</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This TurtleScreen method is available as a global function only under the
name <code class="docutils literal notranslate"><span class="pre">onscreenclick</span></code>.  The global function <code class="docutils literal notranslate"><span class="pre">onclick</span></code> is another one
derived from the Turtle method <code class="docutils literal notranslate"><span class="pre">onclick</span></code>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.ontimer">
<code class="descclassname">turtle.</code><code class="descname">ontimer</code><span class="sig-paren">(</span><em>fun</em>, <em>t=0</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.ontimer" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>fun</strong> – a function with no arguments</li>
<li><strong>t</strong> – a number &gt;= 0</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Install a timer that calls <em>fun</em> after <em>t</em> milliseconds.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">running</span> <span class="o">=</span> <span class="bp">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">running</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">fd</span><span class="p">(</span><span class="mi">50</span><span class="p">)</span>
<span class="gp">... </span>        <span class="n">lt</span><span class="p">(</span><span class="mi">60</span><span class="p">)</span>
<span class="gp">... </span>        <span class="n">screen</span><span class="o">.</span><span class="n">ontimer</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="mi">250</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>   <span class="c1">### makes the turtle march around</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">running</span> <span class="o">=</span> <span class="bp">False</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="settings-and-special-methods">
<h3>24.5.4.4. Settings and special methods<a class="headerlink" href="#settings-and-special-methods" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.mode">
<code class="descclassname">turtle.</code><code class="descname">mode</code><span class="sig-paren">(</span><em>mode=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.mode" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>mode</strong> – one of the strings “standard”, “logo” or “world”</td>
</tr>
</tbody>
</table>
<p>Set turtle mode (“standard”, “logo” or “world”) and perform reset.  If mode
is not given, current mode is returned.</p>
<p>Mode “standard” is compatible with old <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a>.  Mode “logo” is
compatible with most Logo turtle graphics.  Mode “world” uses user-defined
“world coordinates”. <strong>Attention</strong>: in this mode angles appear distorted if
<code class="docutils literal notranslate"><span class="pre">x/y</span></code> unit-ratio doesn’t equal 1.</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="45%" />
<col width="34%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Mode</th>
<th class="head">Initial turtle heading</th>
<th class="head">positive angles</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“standard”</td>
<td>to the right (east)</td>
<td>counterclockwise</td>
</tr>
<tr class="row-odd"><td>“logo”</td>
<td>upward    (north)</td>
<td>clockwise</td>
</tr>
</tbody>
</table>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">mode</span><span class="p">(</span><span class="s2">&quot;logo&quot;</span><span class="p">)</span>   <span class="c1"># resets turtle heading to north</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mode</span><span class="p">()</span>
<span class="go">&#39;logo&#39;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.colormode">
<code class="descclassname">turtle.</code><code class="descname">colormode</code><span class="sig-paren">(</span><em>cmode=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.colormode" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>cmode</strong> – one of the values 1.0 or 255</td>
</tr>
</tbody>
</table>
<p>Return the colormode or set it to 1.0 or 255.  Subsequently <em>r</em>, <em>g</em>, <em>b</em>
values of color triples have to be in the range 0..<em>cmode</em>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">colormode</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">(</span><span class="mi">240</span><span class="p">,</span> <span class="mi">160</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
     <span class="o">...</span>
<span class="gr">TurtleGraphicsError</span>: <span class="n">bad color sequence: (240, 160, 80)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">colormode</span><span class="p">()</span>
<span class="go">1.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">colormode</span><span class="p">(</span><span class="mi">255</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">colormode</span><span class="p">()</span>
<span class="go">255</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">turtle</span><span class="o">.</span><span class="n">pencolor</span><span class="p">(</span><span class="mi">240</span><span class="p">,</span><span class="mi">160</span><span class="p">,</span><span class="mi">80</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.getcanvas">
<code class="descclassname">turtle.</code><code class="descname">getcanvas</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.getcanvas" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the Canvas of this TurtleScreen.  Useful for insiders who know what to
do with a Tkinter Canvas.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cv</span> <span class="o">=</span> <span class="n">screen</span><span class="o">.</span><span class="n">getcanvas</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cv</span>
<span class="go">&lt;turtle.ScrolledCanvas instance at 0x...&gt;</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.getshapes">
<code class="descclassname">turtle.</code><code class="descname">getshapes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.getshapes" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of names of all currently available turtle shapes.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">getshapes</span><span class="p">()</span>
<span class="go">[&#39;arrow&#39;, &#39;blank&#39;, &#39;circle&#39;, ..., &#39;turtle&#39;]</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.register_shape">
<code class="descclassname">turtle.</code><code class="descname">register_shape</code><span class="sig-paren">(</span><em>name</em>, <em>shape=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.register_shape" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.addshape">
<code class="descclassname">turtle.</code><code class="descname">addshape</code><span class="sig-paren">(</span><em>name</em>, <em>shape=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.addshape" title="Permalink to this definition">¶</a></dt>
<dd><p>There are three different ways to call this function:</p>
<ol class="arabic">
<li><p class="first"><em>name</em> is the name of a gif-file and <em>shape</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>: Install the
corresponding image shape.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">register_shape</span><span class="p">(</span><span class="s2">&quot;turtle.gif&quot;</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Image shapes <em>do not</em> rotate when turning the turtle, so they do not
display the heading of the turtle!</p>
</div>
</li>
<li><p class="first"><em>name</em> is an arbitrary string and <em>shape</em> is a tuple of pairs of
coordinates: Install the corresponding polygon shape.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">register_shape</span><span class="p">(</span><span class="s2">&quot;triangle&quot;</span><span class="p">,</span> <span class="p">((</span><span class="mi">5</span><span class="p">,</span><span class="o">-</span><span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">5</span><span class="p">),</span> <span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">,</span><span class="o">-</span><span class="mi">3</span><span class="p">)))</span>
</pre></div>
</div>
</li>
<li><p class="first"><em>name</em> is an arbitrary string and shape is a (compound) <a class="reference internal" href="#turtle.Shape" title="turtle.Shape"><code class="xref py py-class docutils literal notranslate"><span class="pre">Shape</span></code></a>
object: Install the corresponding compound shape.</p>
</li>
</ol>
<p>Add a turtle shape to TurtleScreen’s shapelist.  Only thusly registered
shapes can be used by issuing the command <code class="docutils literal notranslate"><span class="pre">shape(shapename)</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.turtles">
<code class="descclassname">turtle.</code><code class="descname">turtles</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.turtles" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the list of turtles on the screen.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">turtle</span> <span class="ow">in</span> <span class="n">screen</span><span class="o">.</span><span class="n">turtles</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">turtle</span><span class="o">.</span><span class="n">color</span><span class="p">(</span><span class="s2">&quot;red&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">window_height</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the height of the turtle window.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">window_height</span><span class="p">()</span>
<span class="go">480</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt>
<code class="descclassname">turtle.</code><code class="descname">window_width</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Return the width of the turtle window.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">window_width</span><span class="p">()</span>
<span class="go">640</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="methods-specific-to-screen-not-inherited-from-turtlescreen">
<span id="screenspecific"></span><h3>24.5.4.5. Methods specific to Screen, not inherited from TurtleScreen<a class="headerlink" href="#methods-specific-to-screen-not-inherited-from-turtlescreen" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="turtle.bye">
<code class="descclassname">turtle.</code><code class="descname">bye</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.bye" title="Permalink to this definition">¶</a></dt>
<dd><p>Shut the turtlegraphics window.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.exitonclick">
<code class="descclassname">turtle.</code><code class="descname">exitonclick</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#turtle.exitonclick" title="Permalink to this definition">¶</a></dt>
<dd><p>Bind bye() method to mouse clicks on the Screen.</p>
<p>If the value “using_IDLE” in the configuration dictionary is <code class="docutils literal notranslate"><span class="pre">False</span></code>
(default value), also enter mainloop.  Remark: If IDLE with the <code class="docutils literal notranslate"><span class="pre">-n</span></code> switch
(no subprocess) is used, this value should be set to <code class="docutils literal notranslate"><span class="pre">True</span></code> in
<code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code>.  In this case IDLE’s own mainloop is active also for the
client script.</p>
</dd></dl>

<dl class="function">
<dt id="turtle.setup">
<code class="descclassname">turtle.</code><code class="descname">setup</code><span class="sig-paren">(</span><em>width=_CFG[&quot;width&quot;], height=_CFG[&quot;height&quot;], startx=_CFG[&quot;leftright&quot;], starty=_CFG[&quot;topbottom&quot;]</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.setup" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the size and position of the main window.  Default values of arguments
are stored in the configuration dictionary and can be changed via a
<code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file.</p>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>width</strong> – if an integer, a size in pixels, if a float, a fraction of the
screen; default is 50% of screen</li>
<li><strong>height</strong> – if an integer, the height in pixels, if a float, a fraction of
the screen; default is 75% of screen</li>
<li><strong>startx</strong> – if positive, starting position in pixels from the left
edge of the screen, if negative from the right edge, if <code class="docutils literal notranslate"><span class="pre">None</span></code>,
center window horizontally</li>
<li><strong>starty</strong> – if positive, starting position in pixels from the top
edge of the screen, if negative from the bottom edge, if <code class="docutils literal notranslate"><span class="pre">None</span></code>,
center window vertically</li>
</ul>
</td>
</tr>
</tbody>
</table>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">setup</span> <span class="p">(</span><span class="n">width</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">height</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">startx</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">starty</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span>             <span class="c1"># sets window to 200x200 pixels, in upper left of screen</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">setup</span><span class="p">(</span><span class="n">width</span><span class="o">=.</span><span class="mi">75</span><span class="p">,</span> <span class="n">height</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span> <span class="n">startx</span><span class="o">=</span><span class="bp">None</span><span class="p">,</span> <span class="n">starty</span><span class="o">=</span><span class="bp">None</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span>             <span class="c1"># sets window to 75% of screen by 50% of screen and centers</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="turtle.title">
<code class="descclassname">turtle.</code><code class="descname">title</code><span class="sig-paren">(</span><em>titlestring</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.title" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>titlestring</strong> – a string that is shown in the titlebar of the turtle
graphics window</td>
</tr>
</tbody>
</table>
<p>Set title of turtle window to <em>titlestring</em>.</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">screen</span><span class="o">.</span><span class="n">title</span><span class="p">(</span><span class="s2">&quot;Welcome to the turtle zoo!&quot;</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>
<div class="section" id="the-public-classes-of-the-module-turtle">
<h2>24.5.5. The public classes of the module <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a><a class="headerlink" href="#the-public-classes-of-the-module-turtle" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="turtle.RawTurtle">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">RawTurtle</code><span class="sig-paren">(</span><em>canvas</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.RawTurtle" title="Permalink to this definition">¶</a></dt>
<dt id="turtle.RawPen">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">RawPen</code><span class="sig-paren">(</span><em>canvas</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.RawPen" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>canvas</strong> – a <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Canvas</span></code>, a <a class="reference internal" href="#turtle.ScrolledCanvas" title="turtle.ScrolledCanvas"><code class="xref py py-class docutils literal notranslate"><span class="pre">ScrolledCanvas</span></code></a> or a
<a class="reference internal" href="#turtle.TurtleScreen" title="turtle.TurtleScreen"><code class="xref py py-class docutils literal notranslate"><span class="pre">TurtleScreen</span></code></a></td>
</tr>
</tbody>
</table>
<p>Create a turtle.  The turtle has all methods described above as “methods of
Turtle/RawTurtle”.</p>
</dd></dl>

<dl class="class">
<dt id="turtle.Turtle">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">Turtle</code><a class="headerlink" href="#turtle.Turtle" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of RawTurtle, has the same interface but draws on a default
<a class="reference internal" href="#turtle.Screen" title="turtle.Screen"><code class="xref py py-class docutils literal notranslate"><span class="pre">Screen</span></code></a> object created automatically when needed for the first time.</p>
</dd></dl>

<dl class="class">
<dt id="turtle.TurtleScreen">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">TurtleScreen</code><span class="sig-paren">(</span><em>cv</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.TurtleScreen" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>cv</strong> – a <code class="xref py py-class docutils literal notranslate"><span class="pre">Tkinter.Canvas</span></code></td>
</tr>
</tbody>
</table>
<p>Provides screen oriented methods like <code class="xref py py-func docutils literal notranslate"><span class="pre">setbg()</span></code> etc. that are described
above.</p>
</dd></dl>

<dl class="class">
<dt id="turtle.Screen">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">Screen</code><a class="headerlink" href="#turtle.Screen" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of TurtleScreen, with <a class="reference internal" href="#screenspecific"><span class="std std-ref">four methods added</span></a>.</p>
</dd></dl>

<dl class="class">
<dt id="turtle.ScrolledCanvas">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">ScrolledCanvas</code><span class="sig-paren">(</span><em>master</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.ScrolledCanvas" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>master</strong> – some Tkinter widget to contain the ScrolledCanvas, i.e.
a Tkinter-canvas with scrollbars added</td>
</tr>
</tbody>
</table>
<p>Used by class Screen, which thus automatically provides a ScrolledCanvas as
playground for the turtles.</p>
</dd></dl>

<dl class="class">
<dt id="turtle.Shape">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">Shape</code><span class="sig-paren">(</span><em>type_</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.Shape" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>type_</strong> – one of the strings “polygon”, “image”, “compound”</td>
</tr>
</tbody>
</table>
<p>Data structure modeling shapes.  The pair <code class="docutils literal notranslate"><span class="pre">(type_,</span> <span class="pre">data)</span></code> must follow this
specification:</p>
<table border="1" class="docutils">
<colgroup>
<col width="16%" />
<col width="84%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"><em>type_</em></th>
<th class="head"><em>data</em></th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>“polygon”</td>
<td>a polygon-tuple, i.e. a tuple of pairs of coordinates</td>
</tr>
<tr class="row-odd"><td>“image”</td>
<td>an image  (in this form only used internally!)</td>
</tr>
<tr class="row-even"><td>“compound”</td>
<td><code class="docutils literal notranslate"><span class="pre">None</span></code> (a compound shape has to be constructed using the
<a class="reference internal" href="#turtle.Shape.addcomponent" title="turtle.Shape.addcomponent"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addcomponent()</span></code></a> method)</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="turtle.Shape.addcomponent">
<code class="descname">addcomponent</code><span class="sig-paren">(</span><em>poly</em>, <em>fill</em>, <em>outline=None</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.Shape.addcomponent" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple">
<li><strong>poly</strong> – a polygon, i.e. a tuple of pairs of numbers</li>
<li><strong>fill</strong> – a color the <em>poly</em> will be filled with</li>
<li><strong>outline</strong> – a color for the poly’s outline (if given)</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p>Example:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">poly</span> <span class="o">=</span> <span class="p">((</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">),(</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">),(</span><span class="mi">0</span><span class="p">,</span><span class="mi">10</span><span class="p">),(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span><span class="o">-</span><span class="mi">5</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">Shape</span><span class="p">(</span><span class="s2">&quot;compound&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">addcomponent</span><span class="p">(</span><span class="n">poly</span><span class="p">,</span> <span class="s2">&quot;red&quot;</span><span class="p">,</span> <span class="s2">&quot;blue&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># ... add more components and then use register_shape()</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#compoundshapes"><span class="std std-ref">Excursus about the use of compound shapes</span></a>.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="turtle.Vec2D">
<em class="property">class </em><code class="descclassname">turtle.</code><code class="descname">Vec2D</code><span class="sig-paren">(</span><em>x</em>, <em>y</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.Vec2D" title="Permalink to this definition">¶</a></dt>
<dd><p>A two-dimensional vector class, used as a helper class for implementing
turtle graphics.  May be useful for turtle graphics programs too.  Derived
from tuple, so a vector is a tuple!</p>
<p>Provides (for <em>a</em>, <em>b</em> vectors, <em>k</em> number):</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+</span> <span class="pre">b</span></code> vector addition</li>
<li><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">-</span> <span class="pre">b</span></code> vector subtraction</li>
<li><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*</span> <span class="pre">b</span></code> inner product</li>
<li><code class="docutils literal notranslate"><span class="pre">k</span> <span class="pre">*</span> <span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">*</span> <span class="pre">k</span></code> multiplication with scalar</li>
<li><code class="docutils literal notranslate"><span class="pre">abs(a)</span></code> absolute value of a</li>
<li><code class="docutils literal notranslate"><span class="pre">a.rotate(angle)</span></code> rotation</li>
</ul>
</dd></dl>

</div>
<div class="section" id="help-and-configuration">
<h2>24.5.6. Help and configuration<a class="headerlink" href="#help-and-configuration" title="Permalink to this headline">¶</a></h2>
<div class="section" id="how-to-use-help">
<h3>24.5.6.1. How to use help<a class="headerlink" href="#how-to-use-help" title="Permalink to this headline">¶</a></h3>
<p>The public methods of the Screen and Turtle classes are documented extensively
via docstrings.  So these can be used as online-help via the Python help
facilities:</p>
<ul>
<li><p class="first">When using IDLE, tooltips show the signatures and first lines of the
docstrings of typed in function-/method calls.</p>
</li>
<li><p class="first">Calling <a class="reference internal" href="functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> on methods or functions displays the docstrings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">Screen</span><span class="o">.</span><span class="n">bgcolor</span><span class="p">)</span>
<span class="go">Help on method bgcolor in module turtle:</span>

<span class="go">bgcolor(self, *args) unbound turtle.Screen method</span>
<span class="go">    Set or return backgroundcolor of the TurtleScreen.</span>

<span class="go">    Arguments (if given): a color string or three numbers</span>
<span class="go">    in the range 0..colormode or a 3-tuple of such numbers.</span>


<span class="go">      &gt;&gt;&gt; screen.bgcolor(&quot;orange&quot;)</span>
<span class="go">      &gt;&gt;&gt; screen.bgcolor()</span>
<span class="go">      &quot;orange&quot;</span>
<span class="go">      &gt;&gt;&gt; screen.bgcolor(0.5,0,0.5)</span>
<span class="go">      &gt;&gt;&gt; screen.bgcolor()</span>
<span class="go">      &quot;#800080&quot;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">Turtle</span><span class="o">.</span><span class="n">penup</span><span class="p">)</span>
<span class="go">Help on method penup in module turtle:</span>

<span class="go">penup(self) unbound turtle.Turtle method</span>
<span class="go">    Pull the pen up -- no drawing when moving.</span>

<span class="go">    Aliases: penup | pu | up</span>

<span class="go">    No argument</span>

<span class="go">    &gt;&gt;&gt; turtle.penup()</span>
</pre></div>
</div>
</li>
<li><p class="first">The docstrings of the functions which are derived from methods have a modified
form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">bgcolor</span><span class="p">)</span>
<span class="go">Help on function bgcolor in module turtle:</span>

<span class="go">bgcolor(*args)</span>
<span class="go">    Set or return backgroundcolor of the TurtleScreen.</span>

<span class="go">    Arguments (if given): a color string or three numbers</span>
<span class="go">    in the range 0..colormode or a 3-tuple of such numbers.</span>

<span class="go">    Example::</span>

<span class="go">      &gt;&gt;&gt; bgcolor(&quot;orange&quot;)</span>
<span class="go">      &gt;&gt;&gt; bgcolor()</span>
<span class="go">      &quot;orange&quot;</span>
<span class="go">      &gt;&gt;&gt; bgcolor(0.5,0,0.5)</span>
<span class="go">      &gt;&gt;&gt; bgcolor()</span>
<span class="go">      &quot;#800080&quot;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">penup</span><span class="p">)</span>
<span class="go">Help on function penup in module turtle:</span>

<span class="go">penup()</span>
<span class="go">    Pull the pen up -- no drawing when moving.</span>

<span class="go">    Aliases: penup | pu | up</span>

<span class="go">    No argument</span>

<span class="go">    Example:</span>
<span class="go">    &gt;&gt;&gt; penup()</span>
</pre></div>
</div>
</li>
</ul>
<p>These modified docstrings are created automatically together with the function
definitions that are derived from the methods at import time.</p>
</div>
<div class="section" id="translation-of-docstrings-into-different-languages">
<h3>24.5.6.2. Translation of docstrings into different languages<a class="headerlink" href="#translation-of-docstrings-into-different-languages" title="Permalink to this headline">¶</a></h3>
<p>There is a utility to create a dictionary the keys of which are the method names
and the values of which are the docstrings of the public methods of the classes
Screen and Turtle.</p>
<dl class="function">
<dt id="turtle.write_docstringdict">
<code class="descclassname">turtle.</code><code class="descname">write_docstringdict</code><span class="sig-paren">(</span><em>filename=&quot;turtle_docstringdict&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#turtle.write_docstringdict" title="Permalink to this definition">¶</a></dt>
<dd><table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><strong>filename</strong> – a string, used as filename</td>
</tr>
</tbody>
</table>
<p>Create and write docstring-dictionary to a Python script with the given
filename.  This function has to be called explicitly (it is not used by the
turtle graphics classes).  The docstring dictionary will be written to the
Python script <code class="file docutils literal notranslate"><em><span class="pre">filename</span></em><span class="pre">.py</span></code>.  It is intended to serve as a template
for translation of the docstrings into different languages.</p>
</dd></dl>

<p>If you (or your students) want to use <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> with online help in your
native language, you have to translate the docstrings and save the resulting
file as e.g. <code class="file docutils literal notranslate"><span class="pre">turtle_docstringdict_german.py</span></code>.</p>
<p>If you have an appropriate entry in your <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file this dictionary
will be read in at import time and will replace the original English docstrings.</p>
<p>At the time of this writing there are docstring dictionaries in German and in
Italian.  (Requests please to <a class="reference external" href="mailto:glingl&#37;&#52;&#48;aon&#46;at">glingl<span>&#64;</span>aon<span>&#46;</span>at</a>.)</p>
</div>
<div class="section" id="how-to-configure-screen-and-turtles">
<h3>24.5.6.3. How to configure Screen and Turtles<a class="headerlink" href="#how-to-configure-screen-and-turtles" title="Permalink to this headline">¶</a></h3>
<p>The built-in default configuration mimics the appearance and behaviour of the
old turtle module in order to retain best possible compatibility with it.</p>
<p>If you want to use a different configuration which better reflects the features
of this module or which better fits to your needs, e.g. for use in a classroom,
you can prepare a configuration file <code class="docutils literal notranslate"><span class="pre">turtle.cfg</span></code> which will be read at import
time and modify the configuration according to its settings.</p>
<p>The built in configuration would correspond to the following turtle.cfg:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">width</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="n">height</span> <span class="o">=</span> <span class="mf">0.75</span>
<span class="n">leftright</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">topbottom</span> <span class="o">=</span> <span class="kc">None</span>
<span class="n">canvwidth</span> <span class="o">=</span> <span class="mi">400</span>
<span class="n">canvheight</span> <span class="o">=</span> <span class="mi">300</span>
<span class="n">mode</span> <span class="o">=</span> <span class="n">standard</span>
<span class="n">colormode</span> <span class="o">=</span> <span class="mf">1.0</span>
<span class="n">delay</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">undobuffersize</span> <span class="o">=</span> <span class="mi">1000</span>
<span class="n">shape</span> <span class="o">=</span> <span class="n">classic</span>
<span class="n">pencolor</span> <span class="o">=</span> <span class="n">black</span>
<span class="n">fillcolor</span> <span class="o">=</span> <span class="n">black</span>
<span class="n">resizemode</span> <span class="o">=</span> <span class="n">noresize</span>
<span class="n">visible</span> <span class="o">=</span> <span class="kc">True</span>
<span class="n">language</span> <span class="o">=</span> <span class="n">english</span>
<span class="n">exampleturtle</span> <span class="o">=</span> <span class="n">turtle</span>
<span class="n">examplescreen</span> <span class="o">=</span> <span class="n">screen</span>
<span class="n">title</span> <span class="o">=</span> <span class="n">Python</span> <span class="n">Turtle</span> <span class="n">Graphics</span>
<span class="n">using_IDLE</span> <span class="o">=</span> <span class="kc">False</span>
</pre></div>
</div>
<p>Short explanation of selected entries:</p>
<ul class="simple">
<li>The first four lines correspond to the arguments of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">Screen.setup()</span></code>
method.</li>
<li>Line 5 and 6 correspond to the arguments of the method
<code class="xref py py-meth docutils literal notranslate"><span class="pre">Screen.screensize()</span></code>.</li>
<li><em>shape</em> can be any of the built-in shapes, e.g: arrow, turtle, etc.  For more
info try <code class="docutils literal notranslate"><span class="pre">help(shape)</span></code>.</li>
<li>If you want to use no fillcolor (i.e. make the turtle transparent), you have
to write <code class="docutils literal notranslate"><span class="pre">fillcolor</span> <span class="pre">=</span> <span class="pre">&quot;&quot;</span></code> (but all nonempty strings must not have quotes in
the cfg-file).</li>
<li>If you want to reflect the turtle its state, you have to use <code class="docutils literal notranslate"><span class="pre">resizemode</span> <span class="pre">=</span>
<span class="pre">auto</span></code>.</li>
<li>If you set e.g. <code class="docutils literal notranslate"><span class="pre">language</span> <span class="pre">=</span> <span class="pre">italian</span></code> the docstringdict
<code class="file docutils literal notranslate"><span class="pre">turtle_docstringdict_italian.py</span></code> will be loaded at import time (if
present on the import path, e.g. in the same directory as <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a>.</li>
<li>The entries <em>exampleturtle</em> and <em>examplescreen</em> define the names of these
objects as they occur in the docstrings.  The transformation of
method-docstrings to function-docstrings will delete these names from the
docstrings.</li>
<li><em>using_IDLE</em>: Set this to <code class="docutils literal notranslate"><span class="pre">True</span></code> if you regularly work with IDLE and its -n
switch (“no subprocess”).  This will prevent <a class="reference internal" href="#turtle.exitonclick" title="turtle.exitonclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">exitonclick()</span></code></a> to enter the
mainloop.</li>
</ul>
<p>There can be a <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file in the directory where <a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> is
stored and an additional one in the current working directory.  The latter will
override the settings of the first one.</p>
<p>The <code class="file docutils literal notranslate"><span class="pre">Demo/turtle</span></code> directory contains a <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file.  You can
study it as an example and see its effects when running the demos (preferably
not from within the demo-viewer).</p>
</div>
</div>
<div class="section" id="demo-scripts">
<h2>24.5.7. Demo scripts<a class="headerlink" href="#demo-scripts" title="Permalink to this headline">¶</a></h2>
<p>There is a set of demo scripts in the turtledemo directory located in the
<code class="file docutils literal notranslate"><span class="pre">Demo/turtle</span></code> directory in the source distribution.</p>
<p>It contains:</p>
<ul class="simple">
<li>a set of 15 demo scripts demonstrating different features of the new module
<a class="reference internal" href="#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a></li>
<li>a demo viewer <code class="file docutils literal notranslate"><span class="pre">turtleDemo.py</span></code> which can be used to view the sourcecode
of the scripts and run them at the same time. 14 of the examples can be
accessed via the Examples menu; all of them can also be run standalone.</li>
<li>The example <code class="file docutils literal notranslate"><span class="pre">turtledemo_two_canvases.py</span></code> demonstrates the simultaneous
use of two canvases with the turtle module.  Therefore it only can be run
standalone.</li>
<li>There is a <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file in this directory, which also serves as an
example for how to write and use such files.</li>
</ul>
<p>The demoscripts are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="23%" />
<col width="43%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Name</th>
<th class="head">Description</th>
<th class="head">Features</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>bytedesign</td>
<td>complex classical
turtlegraphics pattern</td>
<td><a class="reference internal" href="#turtle.tracer" title="turtle.tracer"><code class="xref py py-func docutils literal notranslate"><span class="pre">tracer()</span></code></a>, delay,
<a class="reference internal" href="#turtle.update" title="turtle.update"><code class="xref py py-func docutils literal notranslate"><span class="pre">update()</span></code></a></td>
</tr>
<tr class="row-odd"><td>chaos</td>
<td>graphs Verhulst dynamics,
shows that computer’s
computations can generate
results sometimes against the
common sense expectations</td>
<td>world coordinates</td>
</tr>
<tr class="row-even"><td>clock</td>
<td>analog clock showing time
of your computer</td>
<td>turtles as clock’s
hands, ontimer</td>
</tr>
<tr class="row-odd"><td>colormixer</td>
<td>experiment with r, g, b</td>
<td><a class="reference internal" href="#turtle.ondrag" title="turtle.ondrag"><code class="xref py py-func docutils literal notranslate"><span class="pre">ondrag()</span></code></a></td>
</tr>
<tr class="row-even"><td>fractalcurves</td>
<td>Hilbert &amp; Koch curves</td>
<td>recursion</td>
</tr>
<tr class="row-odd"><td>lindenmayer</td>
<td>ethnomathematics
(indian kolams)</td>
<td>L-System</td>
</tr>
<tr class="row-even"><td>minimal_hanoi</td>
<td>Towers of Hanoi</td>
<td>Rectangular Turtles
as Hanoi discs
(shape, shapesize)</td>
</tr>
<tr class="row-odd"><td>paint</td>
<td>super minimalistic
drawing program</td>
<td><a class="reference internal" href="#turtle.onclick" title="turtle.onclick"><code class="xref py py-func docutils literal notranslate"><span class="pre">onclick()</span></code></a></td>
</tr>
<tr class="row-even"><td>peace</td>
<td>elementary</td>
<td>turtle: appearance
and animation</td>
</tr>
<tr class="row-odd"><td>penrose</td>
<td>aperiodic tiling with
kites and darts</td>
<td><a class="reference internal" href="#turtle.stamp" title="turtle.stamp"><code class="xref py py-func docutils literal notranslate"><span class="pre">stamp()</span></code></a></td>
</tr>
<tr class="row-even"><td>planet_and_moon</td>
<td>simulation of
gravitational system</td>
<td>compound shapes,
<a class="reference internal" href="#turtle.Vec2D" title="turtle.Vec2D"><code class="xref py py-class docutils literal notranslate"><span class="pre">Vec2D</span></code></a></td>
</tr>
<tr class="row-odd"><td>tree</td>
<td>a (graphical) breadth
first tree (using generators)</td>
<td><a class="reference internal" href="#turtle.clone" title="turtle.clone"><code class="xref py py-func docutils literal notranslate"><span class="pre">clone()</span></code></a></td>
</tr>
<tr class="row-even"><td>wikipedia</td>
<td>a pattern from the wikipedia
article on turtle graphics</td>
<td><a class="reference internal" href="#turtle.clone" title="turtle.clone"><code class="xref py py-func docutils literal notranslate"><span class="pre">clone()</span></code></a>,
<a class="reference internal" href="#turtle.undo" title="turtle.undo"><code class="xref py py-func docutils literal notranslate"><span class="pre">undo()</span></code></a></td>
</tr>
<tr class="row-odd"><td>yinyang</td>
<td>another elementary example</td>
<td><a class="reference internal" href="#turtle.circle" title="turtle.circle"><code class="xref py py-func docutils literal notranslate"><span class="pre">circle()</span></code></a></td>
</tr>
</tbody>
</table>
<p>Have fun!</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a><ul>
<li><a class="reference internal" href="#introduction">24.5.1. Introduction</a></li>
<li><a class="reference internal" href="#overview-over-available-turtle-and-screen-methods">24.5.2. Overview over available Turtle and Screen methods</a><ul>
<li><a class="reference internal" href="#turtle-methods">24.5.2.1. Turtle methods</a></li>
<li><a class="reference internal" href="#methods-of-turtlescreen-screen">24.5.2.2. Methods of TurtleScreen/Screen</a></li>
</ul>
</li>
<li><a class="reference internal" href="#methods-of-rawturtle-turtle-and-corresponding-functions">24.5.3. Methods of RawTurtle/Turtle and corresponding functions</a><ul>
<li><a class="reference internal" href="#turtle-motion">24.5.3.1. Turtle motion</a></li>
<li><a class="reference internal" href="#tell-turtle-s-state">24.5.3.2. Tell Turtle’s state</a></li>
<li><a class="reference internal" href="#settings-for-measurement">24.5.3.3. Settings for measurement</a></li>
<li><a class="reference internal" href="#pen-control">24.5.3.4. Pen control</a><ul>
<li><a class="reference internal" href="#drawing-state">24.5.3.4.1. Drawing state</a></li>
<li><a class="reference internal" href="#color-control">24.5.3.4.2. Color control</a></li>
<li><a class="reference internal" href="#filling">24.5.3.4.3. Filling</a></li>
<li><a class="reference internal" href="#more-drawing-control">24.5.3.4.4. More drawing control</a></li>
</ul>
</li>
<li><a class="reference internal" href="#turtle-state">24.5.3.5. Turtle state</a><ul>
<li><a class="reference internal" href="#visibility">24.5.3.5.1. Visibility</a></li>
<li><a class="reference internal" href="#appearance">24.5.3.5.2. Appearance</a></li>
</ul>
</li>
<li><a class="reference internal" href="#using-events">24.5.3.6. Using events</a></li>
<li><a class="reference internal" href="#special-turtle-methods">24.5.3.7. Special Turtle methods</a></li>
<li><a class="reference internal" href="#excursus-about-the-use-of-compound-shapes">24.5.3.8. Excursus about the use of compound shapes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#methods-of-turtlescreen-screen-and-corresponding-functions">24.5.4. Methods of TurtleScreen/Screen and corresponding functions</a><ul>
<li><a class="reference internal" href="#window-control">24.5.4.1. Window control</a></li>
<li><a class="reference internal" href="#animation-control">24.5.4.2. Animation control</a></li>
<li><a class="reference internal" href="#using-screen-events">24.5.4.3. Using screen events</a></li>
<li><a class="reference internal" href="#settings-and-special-methods">24.5.4.4. Settings and special methods</a></li>
<li><a class="reference internal" href="#methods-specific-to-screen-not-inherited-from-turtlescreen">24.5.4.5. Methods specific to Screen, not inherited from TurtleScreen</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-public-classes-of-the-module-turtle">24.5.5. The public classes of the module <code class="docutils literal notranslate"><span class="pre">turtle</span></code></a></li>
<li><a class="reference internal" href="#help-and-configuration">24.5.6. Help and configuration</a><ul>
<li><a class="reference internal" href="#how-to-use-help">24.5.6.1. How to use help</a></li>
<li><a class="reference internal" href="#translation-of-docstrings-into-different-languages">24.5.6.2. Translation of docstrings into different languages</a></li>
<li><a class="reference internal" href="#how-to-configure-screen-and-turtles">24.5.6.3. How to configure Screen and Turtles</a></li>
</ul>
</li>
<li><a class="reference internal" href="#demo-scripts">24.5.7. Demo scripts</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="scrolledtext.html"
                        title="previous chapter">24.4. <code class="docutils literal notranslate"><span class="pre">ScrolledText</span></code> — Scrolled Text Widget</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="idle.html"
                        title="next chapter">24.6. IDLE</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/turtle.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="idle.html" title="24.6. IDLE"
             >next</a> |</li>
        <li class="right" >
          <a href="scrolledtext.html" title="24.4. ScrolledText — Scrolled Text Widget"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="tk.html" >24. Graphical User Interfaces with Tk</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\oZ�t�thtml/library/types.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.15. types — Names for built-in types &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.16. new — Creation of runtime internal objects" href="new.html" />
    <link rel="prev" title="8.12. UserDict — Class wrapper for dictionary objects" href="userdict.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/types.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="new.html" title="8.16. new — Creation of runtime internal objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-types">
<span id="types-names-for-built-in-types"></span><h1>8.15. <a class="reference internal" href="#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> — Names for built-in types<a class="headerlink" href="#module-types" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/types.py">Lib/types.py</a></p>
<hr class="docutils" />
<p>This module defines names for some object types that are used by the standard
Python interpreter, but not for the types defined by various extension modules.
Also, it does not include some of the types that arise during processing such as
the <code class="docutils literal notranslate"><span class="pre">listiterator</span></code> type. It is safe to use <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">types</span> <span class="pre">import</span> <span class="pre">*</span></code> — the
module does not export any names besides the ones listed here. New names
exported by future versions of this module will all end in <code class="docutils literal notranslate"><span class="pre">Type</span></code>.</p>
<p>Typical use is for functions that do different things depending on their
argument types, like the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">types</span> <span class="k">import</span> <span class="o">*</span>
<span class="k">def</span> <span class="nf">delete</span><span class="p">(</span><span class="n">mylist</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">type</span><span class="p">(</span><span class="n">item</span><span class="p">)</span> <span class="ow">is</span> <span class="n">IntType</span><span class="p">:</span>
       <span class="k">del</span> <span class="n">mylist</span><span class="p">[</span><span class="n">item</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
       <span class="n">mylist</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
</pre></div>
</div>
<p>Starting in Python 2.2, built-in factory functions such as <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> are also names for the corresponding types.  This is now the
preferred way to access the type instead of using the <a class="reference internal" href="#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> module.
Accordingly, the example above should be written as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">delete</span><span class="p">(</span><span class="n">mylist</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="nb">int</span><span class="p">):</span>
       <span class="k">del</span> <span class="n">mylist</span><span class="p">[</span><span class="n">item</span><span class="p">]</span>
    <span class="k">else</span><span class="p">:</span>
       <span class="n">mylist</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
</pre></div>
</div>
<p>The module defines the following names:</p>
<dl class="data">
<dt id="types.NoneType">
<code class="descclassname">types.</code><code class="descname">NoneType</code><a class="headerlink" href="#types.NoneType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.TypeType">
<code class="descclassname">types.</code><code class="descname">TypeType</code><a class="headerlink" href="#types.TypeType" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">The type of type objects (such as returned by <a class="reference internal" href="functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>); alias of the
built-in <a class="reference internal" href="functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.BooleanType">
<code class="descclassname">types.</code><code class="descname">BooleanType</code><a class="headerlink" href="#types.BooleanType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of the <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> values <code class="docutils literal notranslate"><span class="pre">True</span></code> and <code class="docutils literal notranslate"><span class="pre">False</span></code>; alias of the
built-in <a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="types.IntType">
<code class="descclassname">types.</code><code class="descname">IntType</code><a class="headerlink" href="#types.IntType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of integers (e.g. <code class="docutils literal notranslate"><span class="pre">1</span></code>); alias of the built-in <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.LongType">
<code class="descclassname">types.</code><code class="descname">LongType</code><a class="headerlink" href="#types.LongType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of long integers (e.g. <code class="docutils literal notranslate"><span class="pre">1L</span></code>); alias of the built-in <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.FloatType">
<code class="descclassname">types.</code><code class="descname">FloatType</code><a class="headerlink" href="#types.FloatType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of floating point numbers (e.g. <code class="docutils literal notranslate"><span class="pre">1.0</span></code>); alias of the built-in
<a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.ComplexType">
<code class="descclassname">types.</code><code class="descname">ComplexType</code><a class="headerlink" href="#types.ComplexType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of complex numbers (e.g. <code class="docutils literal notranslate"><span class="pre">1.0j</span></code>).  This is not defined if Python was
built without complex number support.</p>
</dd></dl>

<dl class="data">
<dt id="types.StringType">
<code class="descclassname">types.</code><code class="descname">StringType</code><a class="headerlink" href="#types.StringType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of character strings (e.g. <code class="docutils literal notranslate"><span class="pre">'Spam'</span></code>); alias of the built-in
<a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.UnicodeType">
<code class="descclassname">types.</code><code class="descname">UnicodeType</code><a class="headerlink" href="#types.UnicodeType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of Unicode character strings (e.g. <code class="docutils literal notranslate"><span class="pre">u'Spam'</span></code>).  This is not defined
if Python was built without Unicode support.  It’s an alias of the built-in
<a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.TupleType">
<code class="descclassname">types.</code><code class="descname">TupleType</code><a class="headerlink" href="#types.TupleType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of tuples (e.g. <code class="docutils literal notranslate"><span class="pre">(1,</span> <span class="pre">2,</span> <span class="pre">3,</span> <span class="pre">'Spam')</span></code>); alias of the built-in
<a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.ListType">
<code class="descclassname">types.</code><code class="descname">ListType</code><a class="headerlink" href="#types.ListType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of lists (e.g. <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">2,</span> <span class="pre">3]</span></code>); alias of the built-in
<code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.DictType">
<code class="descclassname">types.</code><code class="descname">DictType</code><a class="headerlink" href="#types.DictType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of dictionaries (e.g. <code class="docutils literal notranslate"><span class="pre">{'Bacon':</span> <span class="pre">1,</span> <span class="pre">'Ham':</span> <span class="pre">0}</span></code>); alias of the
built-in <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.DictionaryType">
<code class="descclassname">types.</code><code class="descname">DictionaryType</code><a class="headerlink" href="#types.DictionaryType" title="Permalink to this definition">¶</a></dt>
<dd><p>An alternate name for <code class="docutils literal notranslate"><span class="pre">DictType</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.FunctionType">
<code class="descclassname">types.</code><code class="descname">FunctionType</code><a class="headerlink" href="#types.FunctionType" title="Permalink to this definition">¶</a></dt>
<dt id="types.LambdaType">
<code class="descclassname">types.</code><code class="descname">LambdaType</code><a class="headerlink" href="#types.LambdaType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of user-defined functions and functions created by <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a>
expressions.</p>
</dd></dl>

<dl class="data">
<dt id="types.GeneratorType">
<code class="descclassname">types.</code><code class="descname">GeneratorType</code><a class="headerlink" href="#types.GeneratorType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>-iterator objects, produced by calling a
generator function.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="types.CodeType">
<code class="descclassname">types.</code><code class="descname">CodeType</code><a class="headerlink" href="#types.CodeType" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-1">The type for code objects such as returned by <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.ClassType">
<code class="descclassname">types.</code><code class="descname">ClassType</code><a class="headerlink" href="#types.ClassType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of user-defined old-style classes.</p>
</dd></dl>

<dl class="data">
<dt id="types.InstanceType">
<code class="descclassname">types.</code><code class="descname">InstanceType</code><a class="headerlink" href="#types.InstanceType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of instances of user-defined old-style classes.</p>
</dd></dl>

<dl class="data">
<dt id="types.MethodType">
<code class="descclassname">types.</code><code class="descname">MethodType</code><a class="headerlink" href="#types.MethodType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of methods of user-defined class instances.</p>
</dd></dl>

<dl class="data">
<dt id="types.UnboundMethodType">
<code class="descclassname">types.</code><code class="descname">UnboundMethodType</code><a class="headerlink" href="#types.UnboundMethodType" title="Permalink to this definition">¶</a></dt>
<dd><p>An alternate name for <code class="docutils literal notranslate"><span class="pre">MethodType</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.BuiltinFunctionType">
<code class="descclassname">types.</code><code class="descname">BuiltinFunctionType</code><a class="headerlink" href="#types.BuiltinFunctionType" title="Permalink to this definition">¶</a></dt>
<dt id="types.BuiltinMethodType">
<code class="descclassname">types.</code><code class="descname">BuiltinMethodType</code><a class="headerlink" href="#types.BuiltinMethodType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of built-in functions like <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> or <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>, and
methods of built-in classes.  (Here, the term “built-in” means “written in
C”.)</p>
</dd></dl>

<dl class="data">
<dt id="types.ModuleType">
<code class="descclassname">types.</code><code class="descname">ModuleType</code><a class="headerlink" href="#types.ModuleType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of modules.</p>
</dd></dl>

<dl class="data">
<dt id="types.FileType">
<code class="descclassname">types.</code><code class="descname">FileType</code><a class="headerlink" href="#types.FileType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of open file objects such as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>; alias of the built-in
<a class="reference internal" href="functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.XRangeType">
<code class="descclassname">types.</code><code class="descname">XRangeType</code><a class="headerlink" href="#types.XRangeType" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-2">The type of range objects returned by <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a>; alias of the built-in
<a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.SliceType">
<code class="descclassname">types.</code><code class="descname">SliceType</code><a class="headerlink" href="#types.SliceType" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-3">The type of objects returned by <a class="reference internal" href="functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a>; alias of the built-in
<a class="reference internal" href="functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="types.EllipsisType">
<code class="descclassname">types.</code><code class="descname">EllipsisType</code><a class="headerlink" href="#types.EllipsisType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.TracebackType">
<code class="descclassname">types.</code><code class="descname">TracebackType</code><a class="headerlink" href="#types.TracebackType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of traceback objects such as found in <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.FrameType">
<code class="descclassname">types.</code><code class="descname">FrameType</code><a class="headerlink" href="#types.FrameType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of frame objects such as found in <code class="docutils literal notranslate"><span class="pre">tb.tb_frame</span></code> if <code class="docutils literal notranslate"><span class="pre">tb</span></code> is a
traceback object.</p>
</dd></dl>

<dl class="data">
<dt id="types.BufferType">
<code class="descclassname">types.</code><code class="descname">BufferType</code><a class="headerlink" href="#types.BufferType" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-4">The type of buffer objects created by the <a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-func docutils literal notranslate"><span class="pre">buffer()</span></code></a> function.</p>
</dd></dl>

<dl class="data">
<dt id="types.DictProxyType">
<code class="descclassname">types.</code><code class="descname">DictProxyType</code><a class="headerlink" href="#types.DictProxyType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of dict proxies, such as <code class="docutils literal notranslate"><span class="pre">TypeType.__dict__</span></code>.</p>
</dd></dl>

<dl class="data">
<dt id="types.NotImplementedType">
<code class="descclassname">types.</code><code class="descname">NotImplementedType</code><a class="headerlink" href="#types.NotImplementedType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code></p>
</dd></dl>

<dl class="data">
<dt id="types.GetSetDescriptorType">
<code class="descclassname">types.</code><code class="descname">GetSetDescriptorType</code><a class="headerlink" href="#types.GetSetDescriptorType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of objects defined in extension modules with <code class="docutils literal notranslate"><span class="pre">PyGetSetDef</span></code>, such
as <code class="docutils literal notranslate"><span class="pre">FrameType.f_locals</span></code> or <code class="docutils literal notranslate"><span class="pre">array.array.typecode</span></code>.  This type is used as
descriptor for object attributes; it has the same purpose as the
<a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a> type, but for classes defined in extension modules.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="types.MemberDescriptorType">
<code class="descclassname">types.</code><code class="descname">MemberDescriptorType</code><a class="headerlink" href="#types.MemberDescriptorType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type of objects defined in extension modules with <code class="docutils literal notranslate"><span class="pre">PyMemberDef</span></code>, such
as <code class="docutils literal notranslate"><span class="pre">datetime.timedelta.days</span></code>.  This type is used as descriptor for simple C
data members which use standard conversion functions; it has the same purpose
as the <a class="reference internal" href="functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a> type, but for classes defined in extension modules.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In other implementations of Python, this type may be identical to
<code class="docutils literal notranslate"><span class="pre">GetSetDescriptorType</span></code>.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="types.StringTypes">
<code class="descclassname">types.</code><code class="descname">StringTypes</code><a class="headerlink" href="#types.StringTypes" title="Permalink to this definition">¶</a></dt>
<dd><p>A sequence containing <code class="docutils literal notranslate"><span class="pre">StringType</span></code> and <code class="docutils literal notranslate"><span class="pre">UnicodeType</span></code> used to facilitate
easier checking for any string object.  Using this is more portable than using a
sequence of the two string types constructed elsewhere since it only contains
<code class="docutils literal notranslate"><span class="pre">UnicodeType</span></code> if it has been built in the running version of Python.  For
example: <code class="docutils literal notranslate"><span class="pre">isinstance(s,</span> <span class="pre">types.StringTypes)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="userdict.html"
                        title="previous chapter">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="new.html"
                        title="next chapter">8.16. <code class="docutils literal notranslate"><span class="pre">new</span></code> — Creation of runtime internal objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/types.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="new.html" title="8.16. new — Creation of runtime internal objects"
             >next</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6�!h`h`html/library/undoc.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>41. Undocumented Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Extending and Embedding the Python Interpreter" href="../extending/index.html" />
    <link rel="prev" title="40.1. sunaudiodev — Access to Sun audio hardware" href="sunaudio.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/undoc.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../extending/index.html" title="Extending and Embedding the Python Interpreter"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sunaudio.html" title="40.1. sunaudiodev — Access to Sun audio hardware"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="undocumented-modules">
<span id="undoc"></span><h1>41. Undocumented Modules<a class="headerlink" href="#undocumented-modules" title="Permalink to this headline">¶</a></h1>
<p>Here’s a quick listing of modules that are currently undocumented, but that
should be documented.  Feel free to contribute documentation for them!  (Send
via email to <a class="reference external" href="mailto:docs&#37;&#52;&#48;python&#46;org">docs<span>&#64;</span>python<span>&#46;</span>org</a>.)</p>
<p>The idea and original contents for this chapter were taken from a posting by
Fredrik Lundh; the specific contents of this chapter have been substantially
revised.</p>
<div class="section" id="miscellaneous-useful-utilities">
<h2>41.1. Miscellaneous useful utilities<a class="headerlink" href="#miscellaneous-useful-utilities" title="Permalink to this headline">¶</a></h2>
<p>Some of these are very old and/or not very robust; marked with “hmm.”</p>
<dl class="docutils">
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code></dt>
<dd>— Import hook support (for <a class="reference internal" href="rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a>; may become obsolete).  Removed in
Python 3.x.</dd>
</dl>
</div>
<div class="section" id="platform-specific-modules">
<h2>41.2. Platform specific modules<a class="headerlink" href="#platform-specific-modules" title="Permalink to this headline">¶</a></h2>
<p>These modules are used to implement the <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, and are not
documented beyond this mention.  There’s little need to document these.</p>
<dl class="docutils">
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">ntpath</span></code></dt>
<dd>— Implementation of <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> on Win32, Win64, WinCE, and OS/2 platforms.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixpath</span></code></dt>
<dd>— Implementation of <a class="reference internal" href="os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> on POSIX.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb185</span></code></dt>
<dd>— Backwards compatibility module for systems which still use the Berkeley DB
1.85 module.  It is normally only available on certain BSD Unix-based systems.
It should never be used directly.</dd>
</dl>
</div>
<div class="section" id="multimedia">
<h2>41.3. Multimedia<a class="headerlink" href="#multimedia" title="Permalink to this headline">¶</a></h2>
<dl class="docutils">
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">audiodev</span></code></dt>
<dd>— Platform-independent API for playing audio data.  Removed in Python 3.x.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code></dt>
<dd>— Play audio data on the Linux audio device.  Replaced in Python 2.3 by the
<a class="reference internal" href="ossaudiodev.html#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> module.  Removed in Python 3.x.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudio</span></code></dt>
<dd>— Interpret Sun audio headers (may become obsolete or a tool/demo).
Removed in Python 3.x.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">toaiff</span></code></dt>
<dd>— Convert “arbitrary” sound files to AIFF files; should probably become a tool
or demo.  Requires the external program <strong class="program">sox</strong>.  Removed in Python 3.x.</dd>
</dl>
</div>
<div class="section" id="undocumented-mac-os-modules">
<span id="undoc-mac-modules"></span><h2>41.4. Undocumented Mac OS modules<a class="headerlink" href="#undocumented-mac-os-modules" title="Permalink to this headline">¶</a></h2>
<div class="section" id="module-applesingle">
<span id="applesingle-applesingle-decoder"></span><h3>41.4.1. <a class="reference internal" href="#module-applesingle" title="applesingle: Rudimentary decoder for AppleSingle format files. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">applesingle</span></code></a> — AppleSingle decoder<a class="headerlink" href="#module-applesingle" title="Permalink to this headline">¶</a></h3>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-buildtools">
<span id="buildtools-helper-module-for-buildapplet-and-friends"></span><h3>41.4.2. <a class="reference internal" href="#module-buildtools" title="buildtools: Helper module for BuildApplet, BuildApplication and macfreeze. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">buildtools</span></code></a> — Helper module for BuildApplet and Friends<a class="headerlink" href="#module-buildtools" title="Permalink to this headline">¶</a></h3>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.4.</span></p>
</div>
</div>
<div class="section" id="module-cfmfile">
<span id="cfmfile-code-fragment-resource-module"></span><h3>41.4.3. <a class="reference internal" href="#module-cfmfile" title="cfmfile: Code Fragment Resource module. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cfmfile</span></code></a> — Code Fragment Resource module<a class="headerlink" href="#module-cfmfile" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-cfmfile" title="cfmfile: Code Fragment Resource module. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cfmfile</span></code></a> is a module that understands Code Fragments and the accompanying
“cfrg” resources. It can parse them and merge them, and is used by
BuildApplication to combine all plugin modules to a single executable.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.4.</span></p>
</div>
</div>
<div class="section" id="module-icopen">
<span id="icopen-internet-config-replacement-for-open"></span><h3>41.4.4. <a class="reference internal" href="#module-icopen" title="icopen: Internet Config replacement for open(). (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">icopen</span></code></a> — Internet Config replacement for <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a><a class="headerlink" href="#module-icopen" title="Permalink to this headline">¶</a></h3>
<p>Importing <a class="reference internal" href="#module-icopen" title="icopen: Internet Config replacement for open(). (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">icopen</span></code></a> will replace the built-in <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> with a version
that uses Internet Config to set file type and creator for new files.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-macerrors">
<span id="macerrors-mac-os-errors"></span><h3>41.4.5. <a class="reference internal" href="#module-macerrors" title="macerrors: Constant definitions for many Mac OS error codes. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code></a> — Mac OS Errors<a class="headerlink" href="#module-macerrors" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-macerrors" title="macerrors: Constant definitions for many Mac OS error codes. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code></a> contains constant definitions for many Mac OS error codes.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-macresource">
<span id="macresource-locate-script-resources"></span><h3>41.4.6. <a class="reference internal" href="#module-macresource" title="macresource: Locate script resources. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macresource</span></code></a> — Locate script resources<a class="headerlink" href="#module-macresource" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-macresource" title="macresource: Locate script resources. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macresource</span></code></a> helps scripts finding their resources, such as dialogs and
menus, without requiring special case code for when the script is run under
MacPython, as a MacPython applet or under OSX Python.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-Nav">
<span id="nav-navservices-calls"></span><h3>41.4.7. <a class="reference internal" href="#module-Nav" title="Nav: Interface to Navigation Services. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Nav</span></code></a> — NavServices calls<a class="headerlink" href="#module-Nav" title="Permalink to this headline">¶</a></h3>
<p>A low-level interface to Navigation Services.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-PixMapWrapper">
<span id="pixmapwrapper-wrapper-for-pixmap-objects"></span><h3>41.4.8. <a class="reference internal" href="#module-PixMapWrapper" title="PixMapWrapper: Wrapper for PixMap objects. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">PixMapWrapper</span></code></a> — Wrapper for PixMap objects<a class="headerlink" href="#module-PixMapWrapper" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-PixMapWrapper" title="PixMapWrapper: Wrapper for PixMap objects. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">PixMapWrapper</span></code></a> wraps a PixMap object with a Python object that allows
access to the fields by name. It also has methods to convert to and from
<code class="xref py py-mod docutils literal notranslate"><span class="pre">PIL</span></code> images.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-videoreader">
<span id="videoreader-read-quicktime-movies"></span><h3>41.4.9. <a class="reference internal" href="#module-videoreader" title="videoreader: Read QuickTime movies frame by frame for further processing. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">videoreader</span></code></a> — Read QuickTime movies<a class="headerlink" href="#module-videoreader" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#module-videoreader" title="videoreader: Read QuickTime movies frame by frame for further processing. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">videoreader</span></code></a> reads and decodes QuickTime movies and passes a stream of
images to your program. It also provides some support for audio tracks.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
<div class="section" id="module-W">
<span id="w-widgets-built-on-framework"></span><h3>41.4.10. <a class="reference internal" href="#module-W" title="W: Widgets for the Mac, built on top of FrameWork. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">W</span></code></a> — Widgets built on <a class="reference internal" href="framework.html#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a><a class="headerlink" href="#module-W" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#module-W" title="W: Widgets for the Mac, built on top of FrameWork. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">W</span></code></a> widgets are used extensively in the <strong class="program">IDE</strong>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6.</span></p>
</div>
</div>
</div>
<div class="section" id="obsolete">
<span id="obsolete-modules"></span><h2>41.5. Obsolete<a class="headerlink" href="#obsolete" title="Permalink to this headline">¶</a></h2>
<p>These modules are not normally available for import; additional work must be
done to make them available.</p>
<p>These extension modules written in C are not built by default. Under Unix, these
must be enabled by uncommenting the appropriate lines in <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code>
in the build tree and either rebuilding Python if the modules are statically
linked, or building and installing the shared object if using dynamically-loaded
extensions.</p>
<dl class="docutils">
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">timing</span></code></dt>
<dd>— Measure time intervals to high resolution (use <a class="reference internal" href="time.html#time.clock" title="time.clock"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.clock()</span></code></a>
instead).  Removed in Python 3.x.</dd>
</dl>
</div>
<div class="section" id="sgi-specific-extension-modules">
<h2>41.6. SGI-specific Extension modules<a class="headerlink" href="#sgi-specific-extension-modules" title="Permalink to this headline">¶</a></h2>
<p>The following are SGI specific, and may be out of touch with the current version
of reality.</p>
<dl class="docutils">
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">cl</span></code></dt>
<dd>— Interface to the SGI compression library.</dd>
<dt><code class="xref py py-mod docutils literal notranslate"><span class="pre">sv</span></code></dt>
<dd>— Interface to the “simple video” board on SGI Indigo (obsolete hardware).
Removed in Python 3.x.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">41. Undocumented Modules</a><ul>
<li><a class="reference internal" href="#miscellaneous-useful-utilities">41.1. Miscellaneous useful utilities</a></li>
<li><a class="reference internal" href="#platform-specific-modules">41.2. Platform specific modules</a></li>
<li><a class="reference internal" href="#multimedia">41.3. Multimedia</a></li>
<li><a class="reference internal" href="#undocumented-mac-os-modules">41.4. Undocumented Mac OS modules</a><ul>
<li><a class="reference internal" href="#module-applesingle">41.4.1. <code class="docutils literal notranslate"><span class="pre">applesingle</span></code> — AppleSingle decoder</a></li>
<li><a class="reference internal" href="#module-buildtools">41.4.2. <code class="docutils literal notranslate"><span class="pre">buildtools</span></code> — Helper module for BuildApplet and Friends</a></li>
<li><a class="reference internal" href="#module-cfmfile">41.4.3. <code class="docutils literal notranslate"><span class="pre">cfmfile</span></code> — Code Fragment Resource module</a></li>
<li><a class="reference internal" href="#module-icopen">41.4.4. <code class="docutils literal notranslate"><span class="pre">icopen</span></code> — Internet Config replacement for <code class="docutils literal notranslate"><span class="pre">open()</span></code></a></li>
<li><a class="reference internal" href="#module-macerrors">41.4.5. <code class="docutils literal notranslate"><span class="pre">macerrors</span></code> — Mac OS Errors</a></li>
<li><a class="reference internal" href="#module-macresource">41.4.6. <code class="docutils literal notranslate"><span class="pre">macresource</span></code> — Locate script resources</a></li>
<li><a class="reference internal" href="#module-Nav">41.4.7. <code class="docutils literal notranslate"><span class="pre">Nav</span></code> — NavServices calls</a></li>
<li><a class="reference internal" href="#module-PixMapWrapper">41.4.8. <code class="docutils literal notranslate"><span class="pre">PixMapWrapper</span></code> — Wrapper for PixMap objects</a></li>
<li><a class="reference internal" href="#module-videoreader">41.4.9. <code class="docutils literal notranslate"><span class="pre">videoreader</span></code> — Read QuickTime movies</a></li>
<li><a class="reference internal" href="#module-W">41.4.10. <code class="docutils literal notranslate"><span class="pre">W</span></code> — Widgets built on <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#obsolete">41.5. Obsolete</a></li>
<li><a class="reference internal" href="#sgi-specific-extension-modules">41.6. SGI-specific Extension modules</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sunaudio.html"
                        title="previous chapter">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../extending/index.html"
                        title="next chapter">Extending and Embedding the Python Interpreter</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/undoc.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../extending/index.html" title="Extending and Embedding the Python Interpreter"
             >next</a> |</li>
        <li class="right" >
          <a href="sunaudio.html" title="40.1. sunaudiodev — Access to Sun audio hardware"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ր�A�N�Nhtml/library/unicodedata.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7.9. unicodedata — Unicode Database &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7.10. stringprep — Internet String Preparation" href="stringprep.html" />
    <link rel="prev" title="7.8. codecs — Codec registry and base classes" href="codecs.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/unicodedata.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stringprep.html" title="7.10. stringprep — Internet String Preparation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="codecs.html" title="7.8. codecs — Codec registry and base classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" accesskey="U">7. String Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-unicodedata">
<span id="unicodedata-unicode-database"></span><h1>7.9. <a class="reference internal" href="#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> — Unicode Database<a class="headerlink" href="#module-unicodedata" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This module provides access to the Unicode Character Database which defines
character properties for all Unicode characters. The data in this database is
based on the <code class="file docutils literal notranslate"><span class="pre">UnicodeData.txt</span></code> file version 5.2.0 which is publicly
available from <a class="reference external" href="ftp://ftp.unicode.org/">ftp://ftp.unicode.org/</a>.</p>
<p>The module uses the same names and symbols as defined by the UnicodeData File
Format 5.2.0 (see <a class="reference external" href="http://www.unicode.org/reports/tr44/tr44-4.html">http://www.unicode.org/reports/tr44/tr44-4.html</a>).
It defines the following functions:</p>
<dl class="function">
<dt id="unicodedata.lookup">
<code class="descclassname">unicodedata.</code><code class="descname">lookup</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.lookup" title="Permalink to this definition">¶</a></dt>
<dd><p>Look up character by name.  If a character with the given name is found, return
the corresponding Unicode character.  If not found, <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.name">
<code class="descclassname">unicodedata.</code><code class="descname">name</code><span class="sig-paren">(</span><em>unichr</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.name" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the name assigned to the Unicode character <em>unichr</em> as a string. If no
name is defined, <em>default</em> is returned, or, if not given, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is
raised.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.decimal">
<code class="descclassname">unicodedata.</code><code class="descname">decimal</code><span class="sig-paren">(</span><em>unichr</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.decimal" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the decimal value assigned to the Unicode character <em>unichr</em> as integer.
If no such value is defined, <em>default</em> is returned, or, if not given,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.digit">
<code class="descclassname">unicodedata.</code><code class="descname">digit</code><span class="sig-paren">(</span><em>unichr</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.digit" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the digit value assigned to the Unicode character <em>unichr</em> as integer.
If no such value is defined, <em>default</em> is returned, or, if not given,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.numeric">
<code class="descclassname">unicodedata.</code><code class="descname">numeric</code><span class="sig-paren">(</span><em>unichr</em><span class="optional">[</span>, <em>default</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.numeric" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the numeric value assigned to the Unicode character <em>unichr</em> as float.
If no such value is defined, <em>default</em> is returned, or, if not given,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.category">
<code class="descclassname">unicodedata.</code><code class="descname">category</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.category" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the general category assigned to the Unicode character <em>unichr</em> as
string.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.bidirectional">
<code class="descclassname">unicodedata.</code><code class="descname">bidirectional</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.bidirectional" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the bidirectional class assigned to the Unicode character <em>unichr</em> as
string. If no such value is defined, an empty string is returned.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.combining">
<code class="descclassname">unicodedata.</code><code class="descname">combining</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.combining" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the canonical combining class assigned to the Unicode character <em>unichr</em>
as integer. Returns <code class="docutils literal notranslate"><span class="pre">0</span></code> if no combining class is defined.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.east_asian_width">
<code class="descclassname">unicodedata.</code><code class="descname">east_asian_width</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.east_asian_width" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the east asian width assigned to the Unicode character <em>unichr</em> as
string.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unicodedata.mirrored">
<code class="descclassname">unicodedata.</code><code class="descname">mirrored</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.mirrored" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the mirrored property assigned to the Unicode character <em>unichr</em> as
integer. Returns <code class="docutils literal notranslate"><span class="pre">1</span></code> if the character has been identified as a “mirrored”
character in bidirectional text, <code class="docutils literal notranslate"><span class="pre">0</span></code> otherwise.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.decomposition">
<code class="descclassname">unicodedata.</code><code class="descname">decomposition</code><span class="sig-paren">(</span><em>unichr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.decomposition" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the character decomposition mapping assigned to the Unicode character
<em>unichr</em> as string. An empty string is returned in case no such mapping is
defined.</p>
</dd></dl>

<dl class="function">
<dt id="unicodedata.normalize">
<code class="descclassname">unicodedata.</code><code class="descname">normalize</code><span class="sig-paren">(</span><em>form</em>, <em>unistr</em><span class="sig-paren">)</span><a class="headerlink" href="#unicodedata.normalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the normal form <em>form</em> for the Unicode string <em>unistr</em>. Valid values for
<em>form</em> are ‘NFC’, ‘NFKC’, ‘NFD’, and ‘NFKD’.</p>
<p>The Unicode standard defines various normalization forms of a Unicode string,
based on the definition of canonical equivalence and compatibility equivalence.
In Unicode, several characters can be expressed in various way. For example, the
character U+00C7 (LATIN CAPITAL LETTER C WITH CEDILLA) can also be expressed as
the sequence U+0043 (LATIN CAPITAL LETTER C) U+0327 (COMBINING CEDILLA).</p>
<p>For each character, there are two normal forms: normal form C and normal form D.
Normal form D (NFD) is also known as canonical decomposition, and translates
each character into its decomposed form. Normal form C (NFC) first applies a
canonical decomposition, then composes pre-combined characters again.</p>
<p>In addition to these two forms, there are two additional normal forms based on
compatibility equivalence. In Unicode, certain characters are supported which
normally would be unified with other characters. For example, U+2160 (ROMAN
NUMERAL ONE) is really the same thing as U+0049 (LATIN CAPITAL LETTER I).
However, it is supported in Unicode for compatibility with existing character
sets (e.g. gb2312).</p>
<p>The normal form KD (NFKD) will apply the compatibility decomposition, i.e.
replace all compatibility characters with their equivalents. The normal form KC
(NFKC) first applies the compatibility decomposition, followed by the canonical
composition.</p>
<p>Even if two unicode strings are normalized and look the same to
a human reader, if one has combining characters and the other
doesn’t, they may not compare equal.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<p>In addition, the module exposes the following constant:</p>
<dl class="data">
<dt id="unicodedata.unidata_version">
<code class="descclassname">unicodedata.</code><code class="descname">unidata_version</code><a class="headerlink" href="#unicodedata.unidata_version" title="Permalink to this definition">¶</a></dt>
<dd><p>The version of the Unicode database used in this module.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="unicodedata.ucd_3_2_0">
<code class="descclassname">unicodedata.</code><code class="descname">ucd_3_2_0</code><a class="headerlink" href="#unicodedata.ucd_3_2_0" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an object that has the same methods as the entire module, but uses the
Unicode database version 3.2 instead, for applications that require this
specific version of the Unicode database (such as IDNA).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">unicodedata</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">lookup</span><span class="p">(</span><span class="s1">&#39;LEFT CURLY BRACKET&#39;</span><span class="p">)</span>
<span class="go">u&#39;{&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">name</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
<span class="go">&#39;SOLIDUS&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">decimal</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;9&#39;</span><span class="p">)</span>
<span class="go">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">decimal</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">not a decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">category</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;A&#39;</span><span class="p">)</span>  <span class="c1"># &#39;L&#39;etter, &#39;u&#39;ppercase</span>
<span class="go">&#39;Lu&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicodedata</span><span class="o">.</span><span class="n">bidirectional</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u0660</span><span class="s1">&#39;</span><span class="p">)</span> <span class="c1"># &#39;A&#39;rabic, &#39;N&#39;umber</span>
<span class="go">&#39;AN&#39;</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="codecs.html"
                        title="previous chapter">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stringprep.html"
                        title="next chapter">7.10. <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> — Internet String Preparation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/unicodedata.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stringprep.html" title="7.10. stringprep — Internet String Preparation"
             >next</a> |</li>
        <li class="right" >
          <a href="codecs.html" title="7.8. codecs — Codec registry and base classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="strings.html" >7. String Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1^	�n�nhtml/library/unittest.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25.3. unittest — Unit testing framework &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25.4. 2to3 - Automated Python 2 to 3 code translation" href="2to3.html" />
    <link rel="prev" title="25.2. doctest — Test interactive Python examples" href="doctest.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/unittest.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2to3.html" title="25.4. 2to3 - Automated Python 2 to 3 code translation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="doctest.html" title="25.2. doctest — Test interactive Python examples"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">25. Development Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-unittest">
<span id="unittest-unit-testing-framework"></span><h1>25.3. <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> — Unit testing framework<a class="headerlink" href="#module-unittest" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p>(If you are already familiar with the basic concepts of testing, you might want
to skip to <a class="reference internal" href="#assert-methods"><span class="std std-ref">the list of assert methods</span></a>.)</p>
<p>The Python unit testing framework, sometimes referred to as “PyUnit,” is a
Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
turn, a Java version of Kent’s Smalltalk testing framework.  Each is the de
facto standard unit testing framework for its respective language.</p>
<p><a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> supports test automation, sharing of setup and shutdown code for
tests, aggregation of tests into collections, and independence of the tests from
the reporting framework.  The <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module provides classes that make
it easy to support these qualities for a set of tests.</p>
<p>To achieve this, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> supports some important concepts:</p>
<dl class="docutils">
<dt>test fixture</dt>
<dd>A <em class="dfn">test fixture</em> represents the preparation needed to perform one or more
tests, and any associate cleanup actions.  This may involve, for example,
creating temporary or proxy databases, directories, or starting a server
process.</dd>
<dt>test case</dt>
<dd>A <em class="dfn">test case</em> is the smallest unit of testing.  It checks for a specific
response to a particular set of inputs.  <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> provides a base class,
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>, which may be used to create new test cases.</dd>
<dt>test suite</dt>
<dd>A <em class="dfn">test suite</em> is a collection of test cases, test suites, or both.  It is
used to aggregate tests that should be executed together.</dd>
<dt>test runner</dt>
<dd>A <em class="dfn">test runner</em> is a component which orchestrates the execution of tests
and provides the outcome to the user.  The runner may use a graphical interface,
a textual interface, or return a special value to indicate the results of
executing the tests.</dd>
</dl>
<p>The test case and test fixture concepts are supported through the
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> and <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTestCase</span></code></a> classes; the former should be
used when creating new tests, and the latter can be used when integrating
existing test code with a <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>-driven framework. When building test
fixtures using <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>, the <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> and
<a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> methods can be overridden to provide initialization
and cleanup for the fixture.  With <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTestCase</span></code></a>, existing functions
can be passed to the constructor for these purposes.  When the test is run, the
fixture initialization is run first; if it succeeds, the cleanup method is run
after the test has been executed, regardless of the outcome of the test.  Each
instance of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> will only be used to run a single test method,
so a new fixture is created for each test.</p>
<p>Test suites are implemented by the <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> class.  This class allows
individual tests and test suites to be aggregated; when the suite is executed,
all tests added directly to the suite and in “child” test suites are run.</p>
<p>A test runner is an object that provides a single method,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code>, which accepts a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> or <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a>
object as a parameter, and returns a result object.  The class
<a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> is provided for use as the result object. <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>
provides the <a class="reference internal" href="#unittest.TextTestRunner" title="unittest.TextTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextTestRunner</span></code></a> as an example test runner which reports
test results on the standard error stream by default.  Alternate runners can be
implemented for other environments (such as graphical environments) without any
need to derive from a specific class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a></dt>
<dd>Another test-support module with a very different flavor.</dd>
<dt><a class="reference external" href="https://pypi.org/project/unittest2">unittest2: A backport of new unittest features for Python 2.4-2.6</a></dt>
<dd>Many new features were added to unittest in Python 2.7, including test
discovery. unittest2 allows you to use these features with earlier
versions of Python.</dd>
<dt><a class="reference external" href="https://web.archive.org/web/20150315073817/http://www.xprogramming.com/testfram.htm">Simple Smalltalk Testing: With Patterns</a></dt>
<dd>Kent Beck’s original paper on testing frameworks using the pattern shared
by <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>.</dd>
<dt><a class="reference external" href="https://nose.readthedocs.io/">Nose</a> and <a class="reference external" href="https://docs.pytest.org/">pytest</a></dt>
<dd>Third-party unittest frameworks with a lighter-weight syntax for writing
tests.  For example, <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">func(10)</span> <span class="pre">==</span> <span class="pre">42</span></code>.</dd>
<dt><a class="reference external" href="https://wiki.python.org/moin/PythonTestingToolsTaxonomy">The Python Testing Tools Taxonomy</a></dt>
<dd>An extensive list of Python testing tools including functional testing
frameworks and mock object libraries.</dd>
<dt><a class="reference external" href="http://lists.idyll.org/listinfo/testing-in-python">Testing in Python Mailing List</a></dt>
<dd>A special-interest-group for discussion of testing, and testing tools,
in Python.</dd>
</dl>
</div>
<div class="section" id="basic-example">
<span id="unittest-minimal-example"></span><h2>25.3.1. Basic example<a class="headerlink" href="#basic-example" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module provides a rich set of tools for constructing and
running tests.  This section demonstrates that a small subset of the tools
suffice to meet the needs of most users.</p>
<p>Here is a short script to test three string methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">TestStringMethods</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_upper</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="o">.</span><span class="n">upper</span><span class="p">(),</span> <span class="s1">&#39;FOO&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_isupper</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertTrue</span><span class="p">(</span><span class="s1">&#39;FOO&#39;</span><span class="o">.</span><span class="n">isupper</span><span class="p">())</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertFalse</span><span class="p">(</span><span class="s1">&#39;Foo&#39;</span><span class="o">.</span><span class="n">isupper</span><span class="p">())</span>

    <span class="k">def</span> <span class="nf">test_split</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;hello world&#39;</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">(),</span> <span class="p">[</span><span class="s1">&#39;hello&#39;</span><span class="p">,</span> <span class="s1">&#39;world&#39;</span><span class="p">])</span>
        <span class="c1"># check that s.split fails when the separator is not a string</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
            <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>A testcase is created by subclassing <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestCase</span></code></a>.  The three
individual tests are defined with methods whose names start with the letters
<code class="docutils literal notranslate"><span class="pre">test</span></code>.  This naming convention informs the test runner about which methods
represent tests.</p>
<p>The crux of each test is a call to <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> to check for an
expected result; <a class="reference internal" href="#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue()</span></code></a> or <a class="reference internal" href="#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertFalse()</span></code></a>
to verify a condition; or <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a> to verify that a
specific exception gets raised.  These methods are used instead of the
<a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement so the test runner can accumulate all test results
and produce a report.</p>
<p>The <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> and <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> methods allow you
to define instructions that will be executed before and after each test method.
They are covered in more detail in the section <a class="reference internal" href="#organizing-tests"><span class="std std-ref">Organizing test code</span></a>.</p>
<p>The final block shows a simple way to run the tests. <a class="reference internal" href="#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">unittest.main()</span></code></a>
provides a command-line interface to the test script.  When run from the command
line, the above script produces an output that looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="o">----------------------------------------------------------------------</span>
<span class="n">Ran</span> <span class="mi">3</span> <span class="n">tests</span> <span class="ow">in</span> <span class="mf">0.000</span><span class="n">s</span>

<span class="n">OK</span>
</pre></div>
</div>
<p>Instead of <a class="reference internal" href="#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">unittest.main()</span></code></a>, there are other ways to run the tests with a
finer level of control, less terse output, and no requirement to be run from the
command line.  For example, the last two lines may be replaced with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestLoader</span><span class="p">()</span><span class="o">.</span><span class="n">loadTestsFromTestCase</span><span class="p">(</span><span class="n">TestStringMethods</span><span class="p">)</span>
<span class="n">unittest</span><span class="o">.</span><span class="n">TextTestRunner</span><span class="p">(</span><span class="n">verbosity</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">suite</span><span class="p">)</span>
</pre></div>
</div>
<p>Running the revised script from the interpreter or another script produces the
following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">test_isupper</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">TestStringMethods</span><span class="p">)</span> <span class="o">...</span> <span class="n">ok</span>
<span class="n">test_split</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">TestStringMethods</span><span class="p">)</span> <span class="o">...</span> <span class="n">ok</span>
<span class="n">test_upper</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">TestStringMethods</span><span class="p">)</span> <span class="o">...</span> <span class="n">ok</span>

<span class="o">----------------------------------------------------------------------</span>
<span class="n">Ran</span> <span class="mi">3</span> <span class="n">tests</span> <span class="ow">in</span> <span class="mf">0.001</span><span class="n">s</span>

<span class="n">OK</span>
</pre></div>
</div>
<p>The above examples show the most commonly used <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> features which
are sufficient to meet many everyday testing needs.  The remainder of the
documentation explores the full feature set from first principles.</p>
</div>
<div class="section" id="command-line-interface">
<span id="unittest-command-line-interface"></span><h2>25.3.2. Command-Line Interface<a class="headerlink" href="#command-line-interface" title="Permalink to this headline">¶</a></h2>
<p>The unittest module can be used from the command line to run tests from
modules, classes or even individual test methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">test_module1</span> <span class="n">test_module2</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">test_module</span><span class="o">.</span><span class="n">TestClass</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">test_module</span><span class="o">.</span><span class="n">TestClass</span><span class="o">.</span><span class="n">test_method</span>
</pre></div>
</div>
<p>You can pass in a list with any combination of module names, and fully
qualified class or method names.</p>
<p>You can run tests with more detail (higher verbosity) by passing in the -v flag:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="o">-</span><span class="n">v</span> <span class="n">test_module</span>
</pre></div>
</div>
<p>For a list of all the command-line options:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="o">-</span><span class="n">h</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>In earlier versions it was only possible to run individual test methods and
not modules or classes.</p>
</div>
<div class="section" id="command-line-options">
<h3>25.3.2.1. Command-line options<a class="headerlink" href="#command-line-options" title="Permalink to this headline">¶</a></h3>
<p><strong class="program">unittest</strong> supports these command-line options:</p>
<dl class="cmdoption">
<dt id="cmdoption-unittest-b">
<code class="descname">-b</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--buffer</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-unittest-b" title="Permalink to this definition">¶</a></dt>
<dd><p>The standard output and standard error streams are buffered during the test
run. Output during a passing test is discarded. Output is echoed normally
on test fail or error and is added to the failure messages.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-unittest-c">
<code class="descname">-c</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--catch</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-unittest-c" title="Permalink to this definition">¶</a></dt>
<dd><p><kbd class="kbd docutils literal notranslate">Control-C</kbd> during the test run waits for the current test to end and then
reports all the results so far. A second <kbd class="kbd docutils literal notranslate">Control-C</kbd> raises the normal
<a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.</p>
<p>See <a class="reference internal" href="#signal-handling">Signal Handling</a> for the functions that provide this functionality.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-unittest-f">
<code class="descname">-f</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--failfast</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-unittest-f" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop the test run on the first error or failure.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>The command-line options <code class="docutils literal notranslate"><span class="pre">-b</span></code>, <code class="docutils literal notranslate"><span class="pre">-c</span></code> and <code class="docutils literal notranslate"><span class="pre">-f</span></code> were added.</p>
</div>
<p>The command line can also be used for test discovery, for running all of the
tests in a project or just a subset.</p>
</div>
</div>
<div class="section" id="test-discovery">
<span id="unittest-test-discovery"></span><h2>25.3.3. Test Discovery<a class="headerlink" href="#test-discovery" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>Unittest supports simple test discovery. In order to be compatible with test
discovery, all of the test files must be <a class="reference internal" href="../tutorial/modules.html#tut-modules"><span class="std std-ref">modules</span></a> or
<a class="reference internal" href="../tutorial/modules.html#tut-packages"><span class="std std-ref">packages</span></a> importable from the top-level directory of
the project (this means that their filenames must be valid
<a class="reference internal" href="../reference/lexical_analysis.html#identifiers"><span class="std std-ref">identifiers</span></a>).</p>
<p>Test discovery is implemented in <a class="reference internal" href="#unittest.TestLoader.discover" title="unittest.TestLoader.discover"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestLoader.discover()</span></code></a>, but can also be
used from the command line. The basic command-line usage is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">cd</span> <span class="n">project_directory</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">discover</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">discover</span></code> sub-command has the following options:</p>
<dl class="cmdoption">
<dt id="cmdoption-unittest-discover-v">
<code class="descname">-v</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--verbose</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-unittest-discover-v" title="Permalink to this definition">¶</a></dt>
<dd><p>Verbose output</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-unittest-discover-s">
<code class="descname">-s</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--start-directory</code><code class="descclassname"> directory</code><a class="headerlink" href="#cmdoption-unittest-discover-s" title="Permalink to this definition">¶</a></dt>
<dd><p>Directory to start discovery (<code class="docutils literal notranslate"><span class="pre">.</span></code> default)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-unittest-discover-p">
<code class="descname">-p</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--pattern</code><code class="descclassname"> pattern</code><a class="headerlink" href="#cmdoption-unittest-discover-p" title="Permalink to this definition">¶</a></dt>
<dd><p>Pattern to match test files (<code class="docutils literal notranslate"><span class="pre">test*.py</span></code> default)</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-unittest-discover-t">
<code class="descname">-t</code><code class="descclassname"></code><code class="descclassname">, </code><code class="descname">--top-level-directory</code><code class="descclassname"> directory</code><a class="headerlink" href="#cmdoption-unittest-discover-t" title="Permalink to this definition">¶</a></dt>
<dd><p>Top level directory of project (defaults to start directory)</p>
</dd></dl>

<p>The <a class="reference internal" href="#cmdoption-unittest-discover-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a>, <a class="reference internal" href="#cmdoption-unittest-discover-p"><code class="xref std std-option docutils literal notranslate"><span class="pre">-p</span></code></a>, and <a class="reference internal" href="#cmdoption-unittest-discover-t"><code class="xref std std-option docutils literal notranslate"><span class="pre">-t</span></code></a> options can be passed in
as positional arguments in that order. The following two command lines
are equivalent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">discover</span> <span class="o">-</span><span class="n">s</span> <span class="n">project_directory</span> <span class="o">-</span><span class="n">p</span> <span class="s2">&quot;*_test.py&quot;</span>
<span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">discover</span> <span class="n">project_directory</span> <span class="s2">&quot;*_test.py&quot;</span>
</pre></div>
</div>
<p>As well as being a path it is possible to pass a package name, for example
<code class="docutils literal notranslate"><span class="pre">myproject.subpackage.test</span></code>, as the start directory. The package name you
supply will then be imported and its location on the filesystem will be used
as the start directory.</p>
<div class="admonition caution">
<p class="first admonition-title">Caution</p>
<p>Test discovery loads tests by importing them. Once test discovery has
found all the test files from the start directory you specify it turns the
paths into package names to import. For example <code class="file docutils literal notranslate"><span class="pre">foo/bar/baz.py</span></code> will be
imported as <code class="docutils literal notranslate"><span class="pre">foo.bar.baz</span></code>.</p>
<p>If you have a package installed globally and attempt test discovery on
a different copy of the package then the import <em>could</em> happen from the
wrong place. If this happens test discovery will warn you and exit.</p>
<p class="last">If you supply the start directory as a package name rather than a
path to a directory then discover assumes that whichever location it
imports from is the location you intended, so you will not get the
warning.</p>
</div>
<p>Test modules and packages can customize test loading and discovery by through
the <a class="reference internal" href="#load-tests-protocol">load_tests protocol</a>.</p>
</div>
<div class="section" id="organizing-test-code">
<span id="organizing-tests"></span><h2>25.3.4. Organizing test code<a class="headerlink" href="#organizing-test-code" title="Permalink to this headline">¶</a></h2>
<p>The basic building blocks of unit testing are <em class="dfn">test cases</em> — single
scenarios that must be set up and checked for correctness.  In <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>,
test cases are represented by instances of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>’s <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>
class. To make your own test cases you must write subclasses of
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>, or use <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTestCase</span></code></a>.</p>
<p>An instance of a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>-derived class is an object that can
completely run a single test method, together with optional set-up and tidy-up
code.</p>
<p>The testing code of a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instance should be entirely self
contained, such that it can be run either in isolation or in arbitrary
combination with any number of other test cases.</p>
<p>The simplest <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> subclass will simply override the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> method in order to perform specific testing code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">DefaultWidgetSizeTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">runTest</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">widget</span> <span class="o">=</span> <span class="n">Widget</span><span class="p">(</span><span class="s1">&#39;The widget&#39;</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">widget</span><span class="o">.</span><span class="n">size</span><span class="p">(),</span> <span class="p">(</span><span class="mi">50</span><span class="p">,</span> <span class="mi">50</span><span class="p">),</span> <span class="s1">&#39;incorrect default size&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that in order to test something, we use one of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">assert*()</span></code>
methods provided by the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> base class.  If the test fails, an
exception will be raised, and <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> will identify the test case as a
<em class="dfn">failure</em>.  Any other exceptions will be treated as <em class="dfn">errors</em>. This
helps you identify where the problem is: <em class="dfn">failures</em> are caused by incorrect
results - a 5 where you expected a 6. <em class="dfn">Errors</em> are caused by incorrect
code - e.g., a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> caused by an incorrect function call.</p>
<p>The way to run a test case will be described later.  For now, note that to
construct an instance of such a test case, we call its constructor without
arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">testCase</span> <span class="o">=</span> <span class="n">DefaultWidgetSizeTestCase</span><span class="p">()</span>
</pre></div>
</div>
<p>Now, such test cases can be numerous, and their set-up can be repetitive.  In
the above case, constructing a <code class="xref py py-class docutils literal notranslate"><span class="pre">Widget</span></code> in each of 100 Widget test case
subclasses would mean unsightly duplication.</p>
<p>Luckily, we can factor out such set-up code by implementing a method called
<a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a>, which the testing framework will automatically call for
us when we run the test:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">SimpleWidgetTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span> <span class="o">=</span> <span class="n">Widget</span><span class="p">(</span><span class="s1">&#39;The widget&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">DefaultWidgetSizeTestCase</span><span class="p">(</span><span class="n">SimpleWidgetTestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">runTest</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">size</span><span class="p">(),</span> <span class="p">(</span><span class="mi">50</span><span class="p">,</span><span class="mi">50</span><span class="p">),</span>
                         <span class="s1">&#39;incorrect default size&#39;</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">WidgetResizeTestCase</span><span class="p">(</span><span class="n">SimpleWidgetTestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">runTest</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">resize</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span><span class="mi">150</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">size</span><span class="p">(),</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span><span class="mi">150</span><span class="p">),</span>
                         <span class="s1">&#39;wrong size after resize&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>If the <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> method raises an exception while the test is
running, the framework will consider the test to have suffered an error, and the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> method will not be executed.</p>
<p>Similarly, we can provide a <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> method that tidies up
after the <code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> method has been run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">SimpleWidgetTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span> <span class="o">=</span> <span class="n">Widget</span><span class="p">(</span><span class="s1">&#39;The widget&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">dispose</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> succeeded, the <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> method will
be run whether <code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> succeeded or not.</p>
<p>Such a working environment for the testing code is called a <em class="dfn">fixture</em>.</p>
<p>Often, many small test cases will use the same fixture.  In this case, we would
end up subclassing <code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleWidgetTestCase</span></code> into many small one-method
classes such as <code class="xref py py-class docutils literal notranslate"><span class="pre">DefaultWidgetSizeTestCase</span></code>.  This is time-consuming and
discouraging, so in the same vein as JUnit, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> provides a simpler
mechanism:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">WidgetTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">setUp</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span> <span class="o">=</span> <span class="n">Widget</span><span class="p">(</span><span class="s1">&#39;The widget&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">tearDown</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">dispose</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span> <span class="o">=</span> <span class="kc">None</span>

    <span class="k">def</span> <span class="nf">test_default_size</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">size</span><span class="p">(),</span> <span class="p">(</span><span class="mi">50</span><span class="p">,</span><span class="mi">50</span><span class="p">),</span>
                         <span class="s1">&#39;incorrect default size&#39;</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">test_resize</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">resize</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span><span class="mi">150</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">widget</span><span class="o">.</span><span class="n">size</span><span class="p">(),</span> <span class="p">(</span><span class="mi">100</span><span class="p">,</span><span class="mi">150</span><span class="p">),</span>
                         <span class="s1">&#39;wrong size after resize&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here we have not provided a <code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code> method, but have instead
provided two different test methods.  Class instances will now each run one of
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_*()</span></code> methods, with <code class="docutils literal notranslate"><span class="pre">self.widget</span></code> created and destroyed
separately for each instance.  When creating an instance we must specify the
test method it is to run.  We do this by passing the method name in the
constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">defaultSizeTestCase</span> <span class="o">=</span> <span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_default_size&#39;</span><span class="p">)</span>
<span class="n">resizeTestCase</span> <span class="o">=</span> <span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_resize&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Test case instances are grouped together according to the features they test.
<a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> provides a mechanism for this: the <em class="dfn">test suite</em>,
represented by <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>’s <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">widgetTestSuite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestSuite</span><span class="p">()</span>
<span class="n">widgetTestSuite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_default_size&#39;</span><span class="p">))</span>
<span class="n">widgetTestSuite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_resize&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>For the ease of running tests, as we will see later, it is a good idea to
provide in each test module a callable object that returns a pre-built test
suite:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">suite</span><span class="p">():</span>
    <span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestSuite</span><span class="p">()</span>
    <span class="n">suite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_default_size&#39;</span><span class="p">))</span>
    <span class="n">suite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_resize&#39;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">suite</span>
</pre></div>
</div>
<p>or even:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">suite</span><span class="p">():</span>
    <span class="n">tests</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;test_default_size&#39;</span><span class="p">,</span> <span class="s1">&#39;test_resize&#39;</span><span class="p">]</span>

    <span class="k">return</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestSuite</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">,</span> <span class="n">tests</span><span class="p">))</span>
</pre></div>
</div>
<p>Since it is a common pattern to create a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> subclass with many
similarly named test functions, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> provides a <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a>
class that can be used to automate the process of creating a test suite and
populating it with individual tests. For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestLoader</span><span class="p">()</span><span class="o">.</span><span class="n">loadTestsFromTestCase</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">)</span>
</pre></div>
</div>
<p>will create a test suite that will run <code class="docutils literal notranslate"><span class="pre">WidgetTestCase.test_default_size()</span></code> and
<code class="docutils literal notranslate"><span class="pre">WidgetTestCase.test_resize</span></code>. <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> uses the <code class="docutils literal notranslate"><span class="pre">'test'</span></code> method
name prefix to identify test methods automatically.</p>
<p>Note that the order in which the various test cases will be run is
determined by sorting the test function names with respect to the
built-in ordering for strings.</p>
<p>Often it is desirable to group suites of test cases together, so as to run tests
for the whole system at once.  This is easy, since <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> instances
can be added to a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> just as <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances can be
added to a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">suite1</span> <span class="o">=</span> <span class="n">module1</span><span class="o">.</span><span class="n">TheTestSuite</span><span class="p">()</span>
<span class="n">suite2</span> <span class="o">=</span> <span class="n">module2</span><span class="o">.</span><span class="n">TheTestSuite</span><span class="p">()</span>
<span class="n">alltests</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestSuite</span><span class="p">([</span><span class="n">suite1</span><span class="p">,</span> <span class="n">suite2</span><span class="p">])</span>
</pre></div>
</div>
<p>You can place the definitions of test cases and test suites in the same modules
as the code they are to test (such as <code class="file docutils literal notranslate"><span class="pre">widget.py</span></code>), but there are several
advantages to placing the test code in a separate module, such as
<code class="file docutils literal notranslate"><span class="pre">test_widget.py</span></code>:</p>
<ul class="simple">
<li>The test module can be run standalone from the command line.</li>
<li>The test code can more easily be separated from shipped code.</li>
<li>There is less temptation to change test code to fit the code it tests without
a good reason.</li>
<li>Test code should be modified much less frequently than the code it tests.</li>
<li>Tested code can be refactored more easily.</li>
<li>Tests for modules written in C must be in separate modules anyway, so why not
be consistent?</li>
<li>If the testing strategy changes, there is no need to change the source code.</li>
</ul>
</div>
<div class="section" id="re-using-old-test-code">
<span id="legacy-unit-tests"></span><h2>25.3.5. Re-using old test code<a class="headerlink" href="#re-using-old-test-code" title="Permalink to this headline">¶</a></h2>
<p>Some users will find that they have existing test code that they would like to
run from <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>, without converting every old test function to a
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> subclass.</p>
<p>For this reason, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> provides a <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTestCase</span></code></a> class.
This subclass of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> can be used to wrap an existing test
function.  Set-up and tear-down functions can also be provided.</p>
<p>Given the following test function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">testSomething</span><span class="p">():</span>
    <span class="n">something</span> <span class="o">=</span> <span class="n">makeSomething</span><span class="p">()</span>
    <span class="k">assert</span> <span class="n">something</span><span class="o">.</span><span class="n">name</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span>
    <span class="c1"># ...</span>
</pre></div>
</div>
<p>one can create an equivalent test case instance as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">testcase</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">FunctionTestCase</span><span class="p">(</span><span class="n">testSomething</span><span class="p">)</span>
</pre></div>
</div>
<p>If there are additional set-up and tear-down methods that should be called as
part of the test case’s operation, they can also be provided like so:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">testcase</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">FunctionTestCase</span><span class="p">(</span><span class="n">testSomething</span><span class="p">,</span>
                                     <span class="n">setUp</span><span class="o">=</span><span class="n">makeSomethingDB</span><span class="p">,</span>
                                     <span class="n">tearDown</span><span class="o">=</span><span class="n">deleteSomethingDB</span><span class="p">)</span>
</pre></div>
</div>
<p>To make migrating existing test suites easier, <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> supports tests
raising <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> to indicate test failure. However, it is
recommended that you use the explicit <code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.fail*()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.assert*()</span></code> methods instead, as future versions of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>
may treat <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> differently.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Even though <a class="reference internal" href="#unittest.FunctionTestCase" title="unittest.FunctionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTestCase</span></code></a> can be used to quickly convert an
existing test base over to a <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>-based system, this approach is
not recommended.  Taking the time to set up proper <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>
subclasses will make future test refactorings infinitely easier.</p>
</div>
<p>In some cases, the existing tests may have been written using the <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>
module.  If so, <a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> provides a <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestSuite</span></code> class that can
automatically build <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> instances from the existing
<a class="reference internal" href="doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a>-based tests.</p>
</div>
<div class="section" id="skipping-tests-and-expected-failures">
<span id="unittest-skipping"></span><h2>25.3.6. Skipping tests and expected failures<a class="headerlink" href="#skipping-tests-and-expected-failures" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>Unittest supports skipping individual test methods and even whole classes of
tests.  In addition, it supports marking a test as an “expected failure,” a test
that is broken and will fail, but shouldn’t be counted as a failure on a
<a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a>.</p>
<p>Skipping a test is simply a matter of using the <a class="reference internal" href="#unittest.skip" title="unittest.skip"><code class="xref py py-func docutils literal notranslate"><span class="pre">skip()</span></code></a> <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a>
or one of its conditional variants.</p>
<p>Basic skipping looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="nd">@unittest</span><span class="o">.</span><span class="n">skip</span><span class="p">(</span><span class="s2">&quot;demonstrating skipping&quot;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_nothing</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">fail</span><span class="p">(</span><span class="s2">&quot;shouldn&#39;t happen&quot;</span><span class="p">)</span>

    <span class="nd">@unittest</span><span class="o">.</span><span class="n">skipIf</span><span class="p">(</span><span class="n">mylib</span><span class="o">.</span><span class="n">__version__</span> <span class="o">&lt;</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span>
                     <span class="s2">&quot;not supported in this library version&quot;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_format</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Tests that work for only a certain version of the library.</span>
        <span class="k">pass</span>

    <span class="nd">@unittest</span><span class="o">.</span><span class="n">skipUnless</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">platform</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s2">&quot;win&quot;</span><span class="p">),</span> <span class="s2">&quot;requires Windows&quot;</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">test_windows_support</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># windows specific testing code</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p>This is the output of running the example above in verbose mode:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">test_format</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">MyTestCase</span><span class="p">)</span> <span class="o">...</span> <span class="n">skipped</span> <span class="s1">&#39;not supported in this library version&#39;</span>
<span class="n">test_nothing</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">MyTestCase</span><span class="p">)</span> <span class="o">...</span> <span class="n">skipped</span> <span class="s1">&#39;demonstrating skipping&#39;</span>
<span class="n">test_windows_support</span> <span class="p">(</span><span class="n">__main__</span><span class="o">.</span><span class="n">MyTestCase</span><span class="p">)</span> <span class="o">...</span> <span class="n">skipped</span> <span class="s1">&#39;requires Windows&#39;</span>

<span class="o">----------------------------------------------------------------------</span>
<span class="n">Ran</span> <span class="mi">3</span> <span class="n">tests</span> <span class="ow">in</span> <span class="mf">0.005</span><span class="n">s</span>

<span class="n">OK</span> <span class="p">(</span><span class="n">skipped</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>Classes can be skipped just like methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@unittest</span><span class="o">.</span><span class="n">skip</span><span class="p">(</span><span class="s2">&quot;showing class skipping&quot;</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">MySkippedTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">test_not_run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">pass</span>
</pre></div>
</div>
<p><a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.setUp()</span></code></a> can also skip the test.  This is useful when a resource
that needs to be set up is not available.</p>
<p>Expected failures use the <a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code class="xref py py-func docutils literal notranslate"><span class="pre">expectedFailure()</span></code></a> decorator.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ExpectedFailureTestCase</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@unittest</span><span class="o">.</span><span class="n">expectedFailure</span>
    <span class="k">def</span> <span class="nf">test_fail</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s2">&quot;broken&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>It’s easy to roll your own skipping decorators by making a decorator that calls
<a class="reference internal" href="#unittest.skip" title="unittest.skip"><code class="xref py py-func docutils literal notranslate"><span class="pre">skip()</span></code></a> on the test when it wants it to be skipped.  This decorator skips
the test unless the passed object has a certain attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">skipUnlessHasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">):</span>
        <span class="k">return</span> <span class="k">lambda</span> <span class="n">func</span><span class="p">:</span> <span class="n">func</span>
    <span class="k">return</span> <span class="n">unittest</span><span class="o">.</span><span class="n">skip</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">{!r}</span><span class="s2"> doesn&#39;t have </span><span class="si">{!r}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">attr</span><span class="p">))</span>
</pre></div>
</div>
<p>The following decorators implement test skipping and expected failures:</p>
<dl class="function">
<dt id="unittest.skip">
<code class="descclassname">unittest.</code><code class="descname">skip</code><span class="sig-paren">(</span><em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.skip" title="Permalink to this definition">¶</a></dt>
<dd><p>Unconditionally skip the decorated test.  <em>reason</em> should describe why the
test is being skipped.</p>
</dd></dl>

<dl class="function">
<dt id="unittest.skipIf">
<code class="descclassname">unittest.</code><code class="descname">skipIf</code><span class="sig-paren">(</span><em>condition</em>, <em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.skipIf" title="Permalink to this definition">¶</a></dt>
<dd><p>Skip the decorated test if <em>condition</em> is true.</p>
</dd></dl>

<dl class="function">
<dt id="unittest.skipUnless">
<code class="descclassname">unittest.</code><code class="descname">skipUnless</code><span class="sig-paren">(</span><em>condition</em>, <em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.skipUnless" title="Permalink to this definition">¶</a></dt>
<dd><p>Skip the decorated test unless <em>condition</em> is true.</p>
</dd></dl>

<dl class="function">
<dt id="unittest.expectedFailure">
<code class="descclassname">unittest.</code><code class="descname">expectedFailure</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.expectedFailure" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the test as an expected failure.  If the test fails when run, the test
is not counted as a failure.</p>
</dd></dl>

<dl class="exception">
<dt id="unittest.SkipTest">
<em class="property">exception </em><code class="descclassname">unittest.</code><code class="descname">SkipTest</code><span class="sig-paren">(</span><em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.SkipTest" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised to skip a test.</p>
<p>Usually you can use <a class="reference internal" href="#unittest.TestCase.skipTest" title="unittest.TestCase.skipTest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.skipTest()</span></code></a> or one of the skipping
decorators instead of raising this directly.</p>
</dd></dl>

<p>Skipped tests will not have <code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code> run around them.
Skipped classes will not have <code class="xref py py-meth docutils literal notranslate"><span class="pre">setUpClass()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDownClass()</span></code> run.</p>
</div>
<div class="section" id="classes-and-functions">
<span id="unittest-contents"></span><h2>25.3.7. Classes and functions<a class="headerlink" href="#classes-and-functions" title="Permalink to this headline">¶</a></h2>
<p>This section describes in depth the API of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>.</p>
<div class="section" id="test-cases">
<span id="testcase-objects"></span><h3>25.3.7.1. Test cases<a class="headerlink" href="#test-cases" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="unittest.TestCase">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TestCase</code><span class="sig-paren">(</span><em>methodName='runTest'</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase" title="Permalink to this definition">¶</a></dt>
<dd><p>Instances of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> class represent the smallest testable units
in the <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> universe.  This class is intended to be used as a base
class, with specific tests being implemented by concrete subclasses.  This class
implements the interface needed by the test runner to allow it to drive the
test, and methods that the test code can use to check for and report various
kinds of failure.</p>
<p>Each instance of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> will run a single test method: the method
named <em>methodName</em>.  If you remember, we had an earlier example that went
something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">suite</span><span class="p">():</span>
    <span class="n">suite</span> <span class="o">=</span> <span class="n">unittest</span><span class="o">.</span><span class="n">TestSuite</span><span class="p">()</span>
    <span class="n">suite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_default_size&#39;</span><span class="p">))</span>
    <span class="n">suite</span><span class="o">.</span><span class="n">addTest</span><span class="p">(</span><span class="n">WidgetTestCase</span><span class="p">(</span><span class="s1">&#39;test_resize&#39;</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">suite</span>
</pre></div>
</div>
<p>Here, we create two instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">WidgetTestCase</span></code>, each of which runs a
single test.</p>
<p><em>methodName</em> defaults to <code class="xref py py-meth docutils literal notranslate"><span class="pre">runTest()</span></code>.</p>
<p><a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances provide three groups of methods: one group used
to run the test, another used by the test implementation to check conditions
and report failures, and some inquiry methods allowing information about the
test itself to be gathered.</p>
<p>Methods in the first group (running the test) are:</p>
<dl class="method">
<dt id="unittest.TestCase.setUp">
<code class="descname">setUp</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.setUp" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called to prepare the test fixture.  This is called immediately
before calling the test method; other than <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SkipTest</span></code></a>,
any exception raised by this method will be considered an error rather than
a test failure. The default implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.tearDown">
<code class="descname">tearDown</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.tearDown" title="Permalink to this definition">¶</a></dt>
<dd><p>Method called immediately after the test method has been called and the
result recorded.  This is called even if the test method raised an
exception, so the implementation in subclasses may need to be particularly
careful about checking internal state.  Any exception, other than
<a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> or <a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SkipTest</span></code></a>, raised by this method will be
considered an additional error rather than a test failure (thus increasing
the total number of reported errors). This method will only be called if
the <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> succeeds, regardless of the outcome of the test method.
The default implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.setUpClass">
<code class="descname">setUpClass</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.setUpClass" title="Permalink to this definition">¶</a></dt>
<dd><p>A class method called before tests in an individual class are run.
<code class="docutils literal notranslate"><span class="pre">setUpClass</span></code> is called with the class as the only argument
and must be decorated as a <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@classmethod</span>
<span class="k">def</span> <span class="nf">setUpClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#class-and-module-fixtures">Class and Module Fixtures</a> for more details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.tearDownClass">
<code class="descname">tearDownClass</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.tearDownClass" title="Permalink to this definition">¶</a></dt>
<dd><p>A class method called after tests in an individual class have run.
<code class="docutils literal notranslate"><span class="pre">tearDownClass</span></code> is called with the class as the only argument
and must be decorated as a <a class="reference internal" href="functions.html#classmethod" title="classmethod"><code class="xref py py-meth docutils literal notranslate"><span class="pre">classmethod()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@classmethod</span>
<span class="k">def</span> <span class="nf">tearDownClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#class-and-module-fixtures">Class and Module Fixtures</a> for more details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>result=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the test, collecting the result into the test result object passed as
<em>result</em>.  If <em>result</em> is omitted or <code class="docutils literal notranslate"><span class="pre">None</span></code>, a temporary result
object is created (by calling the <a class="reference internal" href="#unittest.TestCase.defaultTestResult" title="unittest.TestCase.defaultTestResult"><code class="xref py py-meth docutils literal notranslate"><span class="pre">defaultTestResult()</span></code></a> method) and
used. The result object is not returned to <a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a>’s caller.</p>
<p>The same effect may be had by simply calling the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>
instance.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.skipTest">
<code class="descname">skipTest</code><span class="sig-paren">(</span><em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.skipTest" title="Permalink to this definition">¶</a></dt>
<dd><p>Calling this during a test method or <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> skips the current
test.  See <a class="reference internal" href="#unittest-skipping"><span class="std std-ref">Skipping tests and expected failures</span></a> for more information.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.debug">
<code class="descname">debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the test without collecting the result.  This allows exceptions raised
by the test to be propagated to the caller, and can be used to support
running tests under a debugger.</p>
</dd></dl>

<p id="assert-methods">The <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> class provides several assert methods to check for and
report failures.  The following table lists the most commonly used methods
(see the tables below for more assert methods):</p>
<table border="1" class="docutils">
<colgroup>
<col width="48%" />
<col width="34%" />
<col width="18%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method</th>
<th class="head">Checks that</th>
<th class="head">New in</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">==</span> <span class="pre">b</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotEqual" title="unittest.TestCase.assertNotEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">!=</span> <span class="pre">b</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue(x)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">bool(x)</span> <span class="pre">is</span> <span class="pre">True</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertFalse(x)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">bool(x)</span> <span class="pre">is</span> <span class="pre">False</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertIs" title="unittest.TestCase.assertIs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIs(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertIsNot" title="unittest.TestCase.assertIsNot"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNot(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertIsNone" title="unittest.TestCase.assertIsNone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNone(x)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">None</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertIsNotNone" title="unittest.TestCase.assertIsNotNone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNotNone(x)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">None</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertIn" title="unittest.TestCase.assertIn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIn(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">in</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotIn" title="unittest.TestCase.assertNotIn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotIn(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertIsInstance" title="unittest.TestCase.assertIsInstance"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsInstance(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">isinstance(a,</span> <span class="pre">b)</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotIsInstance" title="unittest.TestCase.assertNotIsInstance"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotIsInstance(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">isinstance(a,</span> <span class="pre">b)</span></code></td>
<td>2.7</td>
</tr>
</tbody>
</table>
<p>All the assert methods (except <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a>,
<a class="reference internal" href="#unittest.TestCase.assertRaisesRegexp" title="unittest.TestCase.assertRaisesRegexp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaisesRegexp()</span></code></a>)
accept a <em>msg</em> argument that, if specified, is used as the error message on
failure (see also <a class="reference internal" href="#unittest.TestCase.longMessage" title="unittest.TestCase.longMessage"><code class="xref py py-data docutils literal notranslate"><span class="pre">longMessage</span></code></a>).</p>
<dl class="method">
<dt id="unittest.TestCase.assertEqual">
<code class="descname">assertEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> and <em>second</em> are equal.  If the values do not compare
equal, the test will fail.</p>
<p>In addition, if <em>first</em> and <em>second</em> are the exact same type and one of
list, tuple, dict, set, frozenset or unicode or any type that a subclass
registers with <a class="reference internal" href="#unittest.TestCase.addTypeEqualityFunc" title="unittest.TestCase.addTypeEqualityFunc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addTypeEqualityFunc()</span></code></a> the type-specific equality
function will be called in order to generate a more useful default
error message (see also the <a class="reference internal" href="#type-specific-methods"><span class="std std-ref">list of type-specific methods</span></a>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the automatic calling of type-specific equality function.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertNotEqual">
<code class="descname">assertNotEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertNotEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> and <em>second</em> are not equal.  If the values do compare
equal, the test will fail.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertTrue">
<code class="descname">assertTrue</code><span class="sig-paren">(</span><em>expr</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertTrue" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertFalse">
<code class="descname">assertFalse</code><span class="sig-paren">(</span><em>expr</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertFalse" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>expr</em> is true (or false).</p>
<p>Note that this is equivalent to <code class="docutils literal notranslate"><span class="pre">bool(expr)</span> <span class="pre">is</span> <span class="pre">True</span></code> and not to <code class="docutils literal notranslate"><span class="pre">expr</span>
<span class="pre">is</span> <span class="pre">True</span></code> (use <code class="docutils literal notranslate"><span class="pre">assertIs(expr,</span> <span class="pre">True)</span></code> for the latter).  This method
should also be avoided when more specific methods are available (e.g.
<code class="docutils literal notranslate"><span class="pre">assertEqual(a,</span> <span class="pre">b)</span></code> instead of <code class="docutils literal notranslate"><span class="pre">assertTrue(a</span> <span class="pre">==</span> <span class="pre">b)</span></code>), because they
provide a better error message in case of failure.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertIs">
<code class="descname">assertIs</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIs" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertIsNot">
<code class="descname">assertIsNot</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIsNot" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> and <em>second</em> evaluate (or don’t evaluate) to the same object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertIsNone">
<code class="descname">assertIsNone</code><span class="sig-paren">(</span><em>expr</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIsNone" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertIsNotNone">
<code class="descname">assertIsNotNone</code><span class="sig-paren">(</span><em>expr</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIsNotNone" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>expr</em> is (or is not) <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertIn">
<code class="descname">assertIn</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIn" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertNotIn">
<code class="descname">assertNotIn</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertNotIn" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> is (or is not) in <em>second</em>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertIsInstance">
<code class="descname">assertIsInstance</code><span class="sig-paren">(</span><em>obj</em>, <em>cls</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertIsInstance" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertNotIsInstance">
<code class="descname">assertNotIsInstance</code><span class="sig-paren">(</span><em>obj</em>, <em>cls</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertNotIsInstance" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>obj</em> is (or is not) an instance of <em>cls</em> (which can be a
class or a tuple of classes, as supported by <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a>).
To check for the exact type, use <a class="reference internal" href="#unittest.TestCase.assertIs" title="unittest.TestCase.assertIs"><code class="xref py py-func docutils literal notranslate"><span class="pre">assertIs(type(obj),</span> <span class="pre">cls)</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>It is also possible to check that exceptions and warnings are raised using
the following methods:</p>
<table border="1" class="docutils">
<colgroup>
<col width="53%" />
<col width="36%" />
<col width="11%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method</th>
<th class="head">Checks that</th>
<th class="head">New in</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises(exc,</span> <span class="pre">fun,</span> <span class="pre">*args,</span> <span class="pre">**kwds)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">fun(*args,</span> <span class="pre">**kwds)</span></code> raises <em>exc</em></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertRaisesRegexp" title="unittest.TestCase.assertRaisesRegexp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaisesRegexp(exc,</span> <span class="pre">r,</span> <span class="pre">fun,</span> <span class="pre">*args,</span> <span class="pre">**kwds)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">fun(*args,</span> <span class="pre">**kwds)</span></code> raises <em>exc</em>
and the message matches regex <em>r</em></td>
<td>2.7</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="unittest.TestCase.assertRaises">
<code class="descname">assertRaises</code><span class="sig-paren">(</span><em>exception</em>, <em>callable</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertRaises" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">assertRaises</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span></dt>
<dd><p>Test that an exception is raised when <em>callable</em> is called with any
positional or keyword arguments that are also passed to
<a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a>.  The test passes if <em>exception</em> is raised, is an
error if another exception is raised, or fails if no exception is raised.
To catch any of a group of exceptions, a tuple containing the exception
classes may be passed as <em>exception</em>.</p>
<p>If only the <em>exception</em> argument is given, returns a context manager so
that the code under test can be written inline rather than as a function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="n">SomeException</span><span class="p">):</span>
    <span class="n">do_something</span><span class="p">()</span>
</pre></div>
</div>
<p>The context manager will store the caught exception object in its
<code class="xref py py-attr docutils literal notranslate"><span class="pre">exception</span></code> attribute.  This can be useful if the intention
is to perform additional checks on the exception raised:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="n">SomeException</span><span class="p">)</span> <span class="k">as</span> <span class="n">cm</span><span class="p">:</span>
    <span class="n">do_something</span><span class="p">()</span>

<span class="n">the_exception</span> <span class="o">=</span> <span class="n">cm</span><span class="o">.</span><span class="n">exception</span>
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">the_exception</span><span class="o">.</span><span class="n">error_code</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added the ability to use <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a> as a context manager.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertRaisesRegexp">
<code class="descname">assertRaisesRegexp</code><span class="sig-paren">(</span><em>exception</em>, <em>regexp</em>, <em>callable</em>, <em>*args</em>, <em>**kwds</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertRaisesRegexp" title="Permalink to this definition">¶</a></dt>
<dt>
<code class="descname">assertRaisesRegexp</code><span class="sig-paren">(</span><em>exception</em>, <em>regexp</em><span class="sig-paren">)</span></dt>
<dd><p>Like <a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a> but also tests that <em>regexp</em> matches
on the string representation of the raised exception.  <em>regexp</em> may be
a regular expression object or a string containing a regular expression
suitable for use by <a class="reference internal" href="re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a>.  Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="bp">self</span><span class="o">.</span><span class="n">assertRaisesRegexp</span><span class="p">(</span><span class="ne">ValueError</span><span class="p">,</span> <span class="s2">&quot;invalid literal for.*XYZ&#39;$&quot;</span><span class="p">,</span>
                        <span class="nb">int</span><span class="p">,</span> <span class="s1">&#39;XYZ&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>or:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaisesRegexp</span><span class="p">(</span><span class="ne">ValueError</span><span class="p">,</span> <span class="s1">&#39;literal&#39;</span><span class="p">):</span>
   <span class="nb">int</span><span class="p">(</span><span class="s1">&#39;XYZ&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>There are also other methods used to perform more specific checks, such as:</p>
<table border="1" class="docutils">
<colgroup>
<col width="46%" />
<col width="38%" />
<col width="16%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method</th>
<th class="head">Checks that</th>
<th class="head">New in</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">round(a-b,</span> <span class="pre">7)</span> <span class="pre">==</span> <span class="pre">0</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">round(a-b,</span> <span class="pre">7)</span> <span class="pre">!=</span> <span class="pre">0</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertGreater" title="unittest.TestCase.assertGreater"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertGreater(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertGreaterEqual" title="unittest.TestCase.assertGreaterEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertGreaterEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&gt;=</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertLess" title="unittest.TestCase.assertLess"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertLess(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertLessEqual" title="unittest.TestCase.assertLessEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertLessEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;=</span> <span class="pre">b</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertRegexpMatches" title="unittest.TestCase.assertRegexpMatches"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRegexpMatches(s,</span> <span class="pre">r)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">r.search(s)</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotRegexpMatches" title="unittest.TestCase.assertNotRegexpMatches"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotRegexpMatches(s,</span> <span class="pre">r)</span></code></a></td>
<td><code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">r.search(s)</span></code></td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertItemsEqual" title="unittest.TestCase.assertItemsEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertItemsEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>sorted(a) == sorted(b) and
works with unhashable objs</td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertDictContainsSubset" title="unittest.TestCase.assertDictContainsSubset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertDictContainsSubset(a,</span> <span class="pre">b)</span></code></a></td>
<td>all the key/value pairs
in <em>a</em> exist in <em>b</em></td>
<td>2.7</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="unittest.TestCase.assertAlmostEqual">
<code class="descname">assertAlmostEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>places=7</em>, <em>msg=None</em>, <em>delta=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertAlmostEqual" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertNotAlmostEqual">
<code class="descname">assertNotAlmostEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>places=7</em>, <em>msg=None</em>, <em>delta=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertNotAlmostEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> and <em>second</em> are approximately (or not approximately)
equal by computing the difference, rounding to the given number of
decimal <em>places</em> (default 7), and comparing to zero.  Note that these
methods round the values to the given number of <em>decimal places</em> (i.e.
like the <a class="reference internal" href="functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function) and not <em>significant digits</em>.</p>
<p>If <em>delta</em> is supplied instead of <em>places</em> then the difference
between <em>first</em> and <em>second</em> must be less or equal to (or greater than) <em>delta</em>.</p>
<p>Supplying both <em>delta</em> and <em>places</em> raises a <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><a class="reference internal" href="#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual()</span></code></a> automatically considers almost equal objects
that compare equal.  <a class="reference internal" href="#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual()</span></code></a> automatically fails
if the objects compare equal.  Added the <em>delta</em> keyword argument.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertGreater">
<code class="descname">assertGreater</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertGreater" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertGreaterEqual">
<code class="descname">assertGreaterEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertGreaterEqual" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertLess">
<code class="descname">assertLess</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertLess" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertLessEqual">
<code class="descname">assertLessEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertLessEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that <em>first</em> is respectively &gt;, &gt;=, &lt; or &lt;= than <em>second</em> depending
on the method name.  If not, the test will fail:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="bp">self</span><span class="o">.</span><span class="n">assertGreaterEqual</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="go">AssertionError: &quot;3&quot; unexpectedly not greater than or equal to &quot;4&quot;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertRegexpMatches">
<code class="descname">assertRegexpMatches</code><span class="sig-paren">(</span><em>text</em>, <em>regexp</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertRegexpMatches" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that a <em>regexp</em> search matches <em>text</em>.  In case
of failure, the error message will include the pattern and the <em>text</em> (or
the pattern and the part of <em>text</em> that unexpectedly matched).  <em>regexp</em>
may be a regular expression object or a string containing a regular
expression suitable for use by <a class="reference internal" href="re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertNotRegexpMatches">
<code class="descname">assertNotRegexpMatches</code><span class="sig-paren">(</span><em>text</em>, <em>regexp</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertNotRegexpMatches" title="Permalink to this definition">¶</a></dt>
<dd><p>Verifies that a <em>regexp</em> search does not match <em>text</em>.  Fails with an error
message including the pattern and the part of <em>text</em> that matches.  <em>regexp</em>
may be a regular expression object or a string containing a regular
expression suitable for use by <a class="reference internal" href="re.html#re.search" title="re.search"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.search()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertItemsEqual">
<code class="descname">assertItemsEqual</code><span class="sig-paren">(</span><em>actual</em>, <em>expected</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertItemsEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that sequence <em>expected</em> contains the same elements as <em>actual</em>,
regardless of their order. When they don’t, an error message listing the
differences between the sequences will be generated.</p>
<p>Duplicate elements are <em>not</em> ignored when comparing <em>actual</em> and
<em>expected</em>. It verifies if each element has the same count in both
sequences. It is the equivalent of <code class="docutils literal notranslate"><span class="pre">assertEqual(sorted(expected),</span>
<span class="pre">sorted(actual))</span></code> but it works with sequences of unhashable objects as
well.</p>
<p>In Python 3, this method is named <code class="docutils literal notranslate"><span class="pre">assertCountEqual</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertDictContainsSubset">
<code class="descname">assertDictContainsSubset</code><span class="sig-paren">(</span><em>expected</em>, <em>actual</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertDictContainsSubset" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests whether the key/value pairs in dictionary <em>actual</em> are a
superset of those in <em>expected</em>.  If not, an error message listing
the missing keys and mismatched values is generated.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 3.2.</span></p>
</div>
</dd></dl>

<p id="type-specific-methods">The <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> method dispatches the equality check for objects of
the same type to different type-specific methods.  These methods are already
implemented for most of the built-in types, but it’s also possible to
register new methods using <a class="reference internal" href="#unittest.TestCase.addTypeEqualityFunc" title="unittest.TestCase.addTypeEqualityFunc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addTypeEqualityFunc()</span></code></a>:</p>
<dl class="method">
<dt id="unittest.TestCase.addTypeEqualityFunc">
<code class="descname">addTypeEqualityFunc</code><span class="sig-paren">(</span><em>typeobj</em>, <em>function</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.addTypeEqualityFunc" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers a type-specific method called by <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> to check
if two objects of exactly the same <em>typeobj</em> (not subclasses) compare
equal.  <em>function</em> must take two positional arguments and a third msg=None
keyword argument just as <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> does.  It must raise
<a class="reference internal" href="#unittest.TestCase.failureException" title="unittest.TestCase.failureException"><code class="xref py py-data docutils literal notranslate"><span class="pre">self.failureException(msg)</span></code></a> when inequality
between the first two parameters is detected – possibly providing useful
information and explaining the inequalities in details in the error
message.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>The list of type-specific methods automatically used by
<a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> are summarized in the following table.  Note
that it’s usually not necessary to invoke these methods directly.</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="35%" />
<col width="17%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method</th>
<th class="head">Used to compare</th>
<th class="head">New in</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertMultiLineEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>strings</td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertSequenceEqual" title="unittest.TestCase.assertSequenceEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertSequenceEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>sequences</td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertListEqual" title="unittest.TestCase.assertListEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertListEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>lists</td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertTupleEqual" title="unittest.TestCase.assertTupleEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTupleEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>tuples</td>
<td>2.7</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertSetEqual" title="unittest.TestCase.assertSetEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertSetEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>sets or frozensets</td>
<td>2.7</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertDictEqual" title="unittest.TestCase.assertDictEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertDictEqual(a,</span> <span class="pre">b)</span></code></a></td>
<td>dicts</td>
<td>2.7</td>
</tr>
</tbody>
</table>
<dl class="method">
<dt id="unittest.TestCase.assertMultiLineEqual">
<code class="descname">assertMultiLineEqual</code><span class="sig-paren">(</span><em>first</em>, <em>second</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertMultiLineEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that the multiline string <em>first</em> is equal to the string <em>second</em>.
When not equal a diff of the two strings highlighting the differences
will be included in the error message. This method is used by default
when comparing Unicode strings with <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertSequenceEqual">
<code class="descname">assertSequenceEqual</code><span class="sig-paren">(</span><em>seq1</em>, <em>seq2</em>, <em>msg=None</em>, <em>seq_type=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertSequenceEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests that two sequences are equal.  If a <em>seq_type</em> is supplied, both
<em>seq1</em> and <em>seq2</em> must be instances of <em>seq_type</em> or a failure will
be raised.  If the sequences are different an error message is
constructed that shows the difference between the two.</p>
<p>This method is not called directly by <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>, but
it’s used to implement <a class="reference internal" href="#unittest.TestCase.assertListEqual" title="unittest.TestCase.assertListEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertListEqual()</span></code></a> and
<a class="reference internal" href="#unittest.TestCase.assertTupleEqual" title="unittest.TestCase.assertTupleEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTupleEqual()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertListEqual">
<code class="descname">assertListEqual</code><span class="sig-paren">(</span><em>list1</em>, <em>list2</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertListEqual" title="Permalink to this definition">¶</a></dt>
<dt id="unittest.TestCase.assertTupleEqual">
<code class="descname">assertTupleEqual</code><span class="sig-paren">(</span><em>tuple1</em>, <em>tuple2</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertTupleEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests that two lists or tuples are equal.  If not, an error message is
constructed that shows only the differences between the two.  An error
is also raised if either of the parameters are of the wrong type.
These methods are used by default when comparing lists or tuples with
<a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertSetEqual">
<code class="descname">assertSetEqual</code><span class="sig-paren">(</span><em>set1</em>, <em>set2</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertSetEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests that two sets are equal.  If not, an error message is constructed
that lists the differences between the sets.  This method is used by
default when comparing sets or frozensets with <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.</p>
<p>Fails if either of <em>set1</em> or <em>set2</em> does not have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">set.difference()</span></code>
method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.assertDictEqual">
<code class="descname">assertDictEqual</code><span class="sig-paren">(</span><em>expected</em>, <em>actual</em>, <em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.assertDictEqual" title="Permalink to this definition">¶</a></dt>
<dd><p>Test that two dictionaries are equal.  If not, an error message is
constructed that shows the differences in the dictionaries. This
method will be used by default to compare dictionaries in
calls to <a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p id="other-methods-and-attrs">Finally the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> provides the following methods and attributes:</p>
<dl class="method">
<dt id="unittest.TestCase.fail">
<code class="descname">fail</code><span class="sig-paren">(</span><em>msg=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.fail" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals a test failure unconditionally, with <em>msg</em> or <code class="docutils literal notranslate"><span class="pre">None</span></code> for
the error message.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestCase.failureException">
<code class="descname">failureException</code><a class="headerlink" href="#unittest.TestCase.failureException" title="Permalink to this definition">¶</a></dt>
<dd><p>This class attribute gives the exception raised by the test method.  If a
test framework needs to use a specialized exception, possibly to carry
additional information, it must subclass this exception in order to “play
fair” with the framework.  The initial value of this attribute is
<a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestCase.longMessage">
<code class="descname">longMessage</code><a class="headerlink" href="#unittest.TestCase.longMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>If set to <code class="docutils literal notranslate"><span class="pre">True</span></code> then any explicit failure message you pass in to the
<a class="reference internal" href="#assert-methods"><span class="std std-ref">assert methods</span></a> will be appended to the end of the
normal failure message.  The normal messages contain useful information
about the objects involved, for example the message from assertEqual
shows you the repr of the two unequal objects. Setting this attribute
to <code class="docutils literal notranslate"><span class="pre">True</span></code> allows you to have a custom error message in addition to the
normal one.</p>
<p>This attribute defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>, meaning that a custom message passed
to an assert method will silence the normal message.</p>
<p>The class setting can be overridden in individual tests by assigning an
instance attribute to <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code> before calling the assert methods.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestCase.maxDiff">
<code class="descname">maxDiff</code><a class="headerlink" href="#unittest.TestCase.maxDiff" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute controls the maximum length of diffs output by assert
methods that report diffs on failure. It defaults to 80*8 characters.
Assert methods affected by this attribute are
<a class="reference internal" href="#unittest.TestCase.assertSequenceEqual" title="unittest.TestCase.assertSequenceEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertSequenceEqual()</span></code></a> (including all the sequence comparison
methods that delegate to it), <a class="reference internal" href="#unittest.TestCase.assertDictEqual" title="unittest.TestCase.assertDictEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertDictEqual()</span></code></a> and
<a class="reference internal" href="#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertMultiLineEqual()</span></code></a>.</p>
<p>Setting <code class="docutils literal notranslate"><span class="pre">maxDiff</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> means that there is no maximum length of
diffs.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>Testing frameworks can use the following methods to collect information on
the test:</p>
<dl class="method">
<dt id="unittest.TestCase.countTestCases">
<code class="descname">countTestCases</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.countTestCases" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of tests represented by this test object.  For
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances, this will always be <code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.defaultTestResult">
<code class="descname">defaultTestResult</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.defaultTestResult" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an instance of the test result class that should be used for this
test case class (if no other result instance is provided to the
<a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method).</p>
<p>For <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances, this will always be an instance of
<a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a>; subclasses of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> should override this
as necessary.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.id">
<code class="descname">id</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.id" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string identifying the specific test case.  This is usually the
full name of the test method, including the module and class name.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.shortDescription">
<code class="descname">shortDescription</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.shortDescription" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a description of the test, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no description
has been provided.  The default implementation of this method
returns the first line of the test method’s docstring, if available,
or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.addCleanup">
<code class="descname">addCleanup</code><span class="sig-paren">(</span><em>function</em>, <em>*args</em>, <em>**kwargs</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.addCleanup" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a function to be called after <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> to cleanup resources
used during the test. Functions will be called in reverse order to the
order they are added (LIFO). They are called with any arguments and
keyword arguments passed into <a class="reference internal" href="#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addCleanup()</span></code></a> when they are
added.</p>
<p>If <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> fails, meaning that <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> is not called,
then any cleanup functions added will still be called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestCase.doCleanups">
<code class="descname">doCleanups</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestCase.doCleanups" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called unconditionally after <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a>, or
after <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> if <a class="reference internal" href="#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> raises an exception.</p>
<p>It is responsible for calling all the cleanup functions added by
<a class="reference internal" href="#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addCleanup()</span></code></a>. If you need cleanup functions to be called
<em>prior</em> to <a class="reference internal" href="#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a> then you can call <a class="reference internal" href="#unittest.TestCase.doCleanups" title="unittest.TestCase.doCleanups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">doCleanups()</span></code></a>
yourself.</p>
<p><a class="reference internal" href="#unittest.TestCase.doCleanups" title="unittest.TestCase.doCleanups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">doCleanups()</span></code></a> pops methods off the stack of cleanup
functions one at a time, so it can be called at any time.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="unittest.FunctionTestCase">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">FunctionTestCase</code><span class="sig-paren">(</span><em>testFunc</em>, <em>setUp=None</em>, <em>tearDown=None</em>, <em>description=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.FunctionTestCase" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements the portion of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> interface which
allows the test runner to drive the test, but does not provide the methods
which test code can use to check and report errors.  This is used to create
test cases using legacy test code, allowing it to be integrated into a
<a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>-based test framework.</p>
</dd></dl>

<div class="section" id="deprecated-aliases">
<h4>25.3.7.1.1. Deprecated aliases<a class="headerlink" href="#deprecated-aliases" title="Permalink to this headline">¶</a></h4>
<p>For historical reasons, some of the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> methods had one or more
aliases that are now deprecated.  The following table lists the correct names
along with their deprecated aliases:</p>
<blockquote>
<div><table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Method Name</th>
<th class="head">Deprecated alias(es)</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a></td>
<td>failUnlessEqual, assertEquals</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertNotEqual" title="unittest.TestCase.assertNotEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotEqual()</span></code></a></td>
<td>failIfEqual</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue()</span></code></a></td>
<td>failUnless, assert_</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertFalse()</span></code></a></td>
<td>failIf</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a></td>
<td>failUnlessRaises</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual()</span></code></a></td>
<td>failUnlessAlmostEqual</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual()</span></code></a></td>
<td>failIfAlmostEqual</td>
</tr>
</tbody>
</table>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>the aliases listed in the second column</p>
</div>
</div></blockquote>
</div>
</div>
<div class="section" id="grouping-tests">
<span id="testsuite-objects"></span><h3>25.3.7.2. Grouping tests<a class="headerlink" href="#grouping-tests" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="unittest.TestSuite">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TestSuite</code><span class="sig-paren">(</span><em>tests=()</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite" title="Permalink to this definition">¶</a></dt>
<dd><p>This class represents an aggregation of individual test cases and test suites.
The class presents the interface needed by the test runner to allow it to be run
as any other test case.  Running a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> instance is the same as
iterating over the suite, running each test individually.</p>
<p>If <em>tests</em> is given, it must be an iterable of individual test cases or other
test suites that will be used to build the suite initially. Additional methods
are provided to add test cases and suites to the collection later on.</p>
<p><a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> objects behave much like <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> objects, except
they do not actually implement a test.  Instead, they are used to aggregate
tests into groups of tests that should be run together. Some additional
methods are available to add tests to <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> instances:</p>
<dl class="method">
<dt id="unittest.TestSuite.addTest">
<code class="descname">addTest</code><span class="sig-paren">(</span><em>test</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.addTest" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> or <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> to the suite.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestSuite.addTests">
<code class="descname">addTests</code><span class="sig-paren">(</span><em>tests</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.addTests" title="Permalink to this definition">¶</a></dt>
<dd><p>Add all the tests from an iterable of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> and <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a>
instances to this test suite.</p>
<p>This is equivalent to iterating over <em>tests</em>, calling <a class="reference internal" href="#unittest.TestSuite.addTest" title="unittest.TestSuite.addTest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addTest()</span></code></a> for
each element.</p>
</dd></dl>

<p><a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> shares the following methods with <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>:</p>
<dl class="method">
<dt id="unittest.TestSuite.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>result</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the tests associated with this suite, collecting the result into the
test result object passed as <em>result</em>.  Note that unlike
<a class="reference internal" href="#unittest.TestCase.run" title="unittest.TestCase.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.run()</span></code></a>, <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestSuite.run()</span></code></a> requires the result object to
be passed in.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestSuite.debug">
<code class="descname">debug</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the tests associated with this suite without collecting the
result. This allows exceptions raised by the test to be propagated to the
caller and can be used to support running tests under a debugger.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestSuite.countTestCases">
<code class="descname">countTestCases</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.countTestCases" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of tests represented by this test object, including all
individual tests and sub-suites.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestSuite.__iter__">
<code class="descname">__iter__</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestSuite.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Tests grouped by a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> are always accessed by iteration.
Subclasses can lazily provide tests by overriding <a class="reference internal" href="#unittest.TestSuite.__iter__" title="unittest.TestSuite.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>. Note
that this method maybe called several times on a single suite
(for example when counting tests or comparing for equality)
so the tests returned must be the same for repeated iterations.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>In earlier versions the <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> accessed tests directly rather
than through iteration, so overriding <a class="reference internal" href="#unittest.TestSuite.__iter__" title="unittest.TestSuite.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> wasn’t sufficient
for providing tests.</p>
</div>
</dd></dl>

<p>In the typical usage of a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> object, the <a class="reference internal" href="#unittest.TestSuite.run" title="unittest.TestSuite.run"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code></a> method
is invoked by a <code class="xref py py-class docutils literal notranslate"><span class="pre">TestRunner</span></code> rather than by the end-user test harness.</p>
</dd></dl>

</div>
<div class="section" id="loading-and-running-tests">
<h3>25.3.7.3. Loading and running tests<a class="headerlink" href="#loading-and-running-tests" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="unittest.TestLoader">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TestLoader</code><a class="headerlink" href="#unittest.TestLoader" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> class is used to create test suites from classes and
modules.  Normally, there is no need to create an instance of this class; the
<a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module provides an instance that can be shared as
<a class="reference internal" href="#unittest.defaultTestLoader" title="unittest.defaultTestLoader"><code class="xref py py-data docutils literal notranslate"><span class="pre">unittest.defaultTestLoader</span></code></a>.  Using a subclass or instance, however,
allows customization of some configurable properties.</p>
<p><a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> objects have the following methods:</p>
<dl class="method">
<dt id="unittest.TestLoader.loadTestsFromTestCase">
<code class="descname">loadTestsFromTestCase</code><span class="sig-paren">(</span><em>testCaseClass</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.loadTestsFromTestCase" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a suite of all test cases contained in the <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>-derived
<code class="xref py py-class docutils literal notranslate"><span class="pre">testCaseClass</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestLoader.loadTestsFromModule">
<code class="descname">loadTestsFromModule</code><span class="sig-paren">(</span><em>module</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.loadTestsFromModule" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a suite of all test cases contained in the given module. This
method searches <em>module</em> for classes derived from <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> and
creates an instance of the class for each test method defined for the
class.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">While using a hierarchy of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>-derived classes can be
convenient in sharing fixtures and helper functions, defining test
methods on base classes that are not intended to be instantiated
directly does not play well with this method.  Doing so, however, can
be useful when the fixtures are different and defined in subclasses.</p>
</div>
<p>If a module provides a <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> function it will be called to
load the tests. This allows modules to customize test loading.
This is the <a class="reference internal" href="#load-tests-protocol">load_tests protocol</a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestLoader.loadTestsFromName">
<code class="descname">loadTestsFromName</code><span class="sig-paren">(</span><em>name</em>, <em>module=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.loadTestsFromName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a suite of all test cases given a string specifier.</p>
<p>The specifier <em>name</em> is a “dotted name” that may resolve either to a
module, a test case class, a test method within a test case class, a
<a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> instance, or a callable object which returns a
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> or <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> instance.  These checks are
applied in the order listed here; that is, a method on a possible test
case class will be picked up as “a test method within a test case class”,
rather than “a callable object”.</p>
<p>For example, if you have a module <code class="xref py py-mod docutils literal notranslate"><span class="pre">SampleTests</span></code> containing a
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>-derived class <code class="xref py py-class docutils literal notranslate"><span class="pre">SampleTestCase</span></code> with three test
methods (<code class="xref py py-meth docutils literal notranslate"><span class="pre">test_one()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_two()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_three()</span></code>), the
specifier <code class="docutils literal notranslate"><span class="pre">'SampleTests.SampleTestCase'</span></code> would cause this method to
return a suite which will run all three test methods. Using the specifier
<code class="docutils literal notranslate"><span class="pre">'SampleTests.SampleTestCase.test_two'</span></code> would cause it to return a test
suite which will run only the <code class="xref py py-meth docutils literal notranslate"><span class="pre">test_two()</span></code> test method. The specifier
can refer to modules and packages which have not been imported; they will
be imported as a side-effect.</p>
<p>The method optionally resolves <em>name</em> relative to the given <em>module</em>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestLoader.loadTestsFromNames">
<code class="descname">loadTestsFromNames</code><span class="sig-paren">(</span><em>names</em>, <em>module=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.loadTestsFromNames" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#unittest.TestLoader.loadTestsFromName" title="unittest.TestLoader.loadTestsFromName"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loadTestsFromName()</span></code></a>, but takes a sequence of names rather
than a single name.  The return value is a test suite which supports all
the tests defined for each name.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestLoader.getTestCaseNames">
<code class="descname">getTestCaseNames</code><span class="sig-paren">(</span><em>testCaseClass</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.getTestCaseNames" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a sorted sequence of method names found within <em>testCaseClass</em>;
this should be a subclass of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestLoader.discover">
<code class="descname">discover</code><span class="sig-paren">(</span><em>start_dir</em>, <em>pattern='test*.py'</em>, <em>top_level_dir=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestLoader.discover" title="Permalink to this definition">¶</a></dt>
<dd><p>Find all the test modules by recursing into subdirectories from the
specified start directory, and return a TestSuite object containing them.
Only test files that match <em>pattern</em> will be loaded. (Using shell style
pattern matching.) Only module names that are importable (i.e. are valid
Python identifiers) will be loaded.</p>
<p>All test modules must be importable from the top level of the project. If
the start directory is not the top level directory then the top level
directory must be specified separately.</p>
<p>If importing a module fails, for example due to a syntax error, then this
will be recorded as a single error and discovery will continue.</p>
<p>If a test package name (directory with <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>) matches the
pattern then the package will be checked for a <code class="docutils literal notranslate"><span class="pre">load_tests</span></code>
function. If this exists then it will be called with <em>loader</em>, <em>tests</em>,
<em>pattern</em>.</p>
<p>If load_tests exists then discovery does <em>not</em> recurse into the package,
<code class="docutils literal notranslate"><span class="pre">load_tests</span></code> is responsible for loading all tests in the package.</p>
<p>The pattern is deliberately not stored as a loader attribute so that
packages can continue discovery themselves. <em>top_level_dir</em> is stored so
<code class="docutils literal notranslate"><span class="pre">load_tests</span></code> does not need to pass this argument in to
<code class="docutils literal notranslate"><span class="pre">loader.discover()</span></code>.</p>
<p><em>start_dir</em> can be a dotted module name as well as a directory.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<p>The following attributes of a <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> can be configured either by
subclassing or assignment on an instance:</p>
<dl class="attribute">
<dt id="unittest.TestLoader.testMethodPrefix">
<code class="descname">testMethodPrefix</code><a class="headerlink" href="#unittest.TestLoader.testMethodPrefix" title="Permalink to this definition">¶</a></dt>
<dd><p>String giving the prefix of method names which will be interpreted as test
methods.  The default value is <code class="docutils literal notranslate"><span class="pre">'test'</span></code>.</p>
<p>This affects <a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getTestCaseNames()</span></code></a> and all the <code class="xref py py-meth docutils literal notranslate"><span class="pre">loadTestsFrom*()</span></code>
methods.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestLoader.sortTestMethodsUsing">
<code class="descname">sortTestMethodsUsing</code><a class="headerlink" href="#unittest.TestLoader.sortTestMethodsUsing" title="Permalink to this definition">¶</a></dt>
<dd><p>Function to be used to compare method names when sorting them in
<a class="reference internal" href="#unittest.TestLoader.getTestCaseNames" title="unittest.TestLoader.getTestCaseNames"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getTestCaseNames()</span></code></a> and all the <code class="xref py py-meth docutils literal notranslate"><span class="pre">loadTestsFrom*()</span></code> methods. The
default value is the built-in <a class="reference internal" href="functions.html#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a> function; the attribute can also
be set to <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> to disable the sort.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestLoader.suiteClass">
<code class="descname">suiteClass</code><a class="headerlink" href="#unittest.TestLoader.suiteClass" title="Permalink to this definition">¶</a></dt>
<dd><p>Callable object that constructs a test suite from a list of tests. No
methods on the resulting object are needed.  The default value is the
<a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> class.</p>
<p>This affects all the <code class="xref py py-meth docutils literal notranslate"><span class="pre">loadTestsFrom*()</span></code> methods.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="unittest.TestResult">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TestResult</code><a class="headerlink" href="#unittest.TestResult" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is used to compile information about which tests have succeeded
and which have failed.</p>
<p>A <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> object stores the results of a set of tests.  The
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> and <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> classes ensure that results are
properly recorded; test authors do not need to worry about recording the
outcome of tests.</p>
<p>Testing frameworks built on top of <a class="reference internal" href="#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> may want access to the
<a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> object generated by running a set of tests for reporting
purposes; a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> instance is returned by the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">TestRunner.run()</span></code> method for this purpose.</p>
<p><a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> instances have the following attributes that will be of
interest when inspecting the results of running a set of tests:</p>
<dl class="attribute">
<dt id="unittest.TestResult.errors">
<code class="descname">errors</code><a class="headerlink" href="#unittest.TestResult.errors" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances and strings
holding formatted tracebacks. Each tuple represents a test which raised an
unexpected exception.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Contains formatted tracebacks instead of <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> results.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.failures">
<code class="descname">failures</code><a class="headerlink" href="#unittest.TestResult.failures" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances and strings
holding formatted tracebacks. Each tuple represents a test where a failure
was explicitly signalled using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.assert*()</span></code> methods.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span>Contains formatted tracebacks instead of <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a> results.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.skipped">
<code class="descname">skipped</code><a class="headerlink" href="#unittest.TestResult.skipped" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances and strings
holding the reason for skipping the test.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.expectedFailures">
<code class="descname">expectedFailures</code><a class="headerlink" href="#unittest.TestResult.expectedFailures" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing 2-tuples of <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances and strings
holding formatted tracebacks.  Each tuple represents an expected failure
of the test case.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.unexpectedSuccesses">
<code class="descname">unexpectedSuccesses</code><a class="headerlink" href="#unittest.TestResult.unexpectedSuccesses" title="Permalink to this definition">¶</a></dt>
<dd><p>A list containing <a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> instances that were marked as expected
failures, but succeeded.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.shouldStop">
<code class="descname">shouldStop</code><a class="headerlink" href="#unittest.TestResult.shouldStop" title="Permalink to this definition">¶</a></dt>
<dd><p>Set to <code class="docutils literal notranslate"><span class="pre">True</span></code> when the execution of tests should stop by <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.testsRun">
<code class="descname">testsRun</code><a class="headerlink" href="#unittest.TestResult.testsRun" title="Permalink to this definition">¶</a></dt>
<dd><p>The total number of tests run so far.</p>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.buffer">
<code class="descname">buffer</code><a class="headerlink" href="#unittest.TestResult.buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>If set to true, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> will be buffered in between
<a class="reference internal" href="#unittest.TestResult.startTest" title="unittest.TestResult.startTest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startTest()</span></code></a> and <a class="reference internal" href="#unittest.TestResult.stopTest" title="unittest.TestResult.stopTest"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stopTest()</span></code></a> being called. Collected output will
only be echoed onto the real <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> if the test
fails or errors. Any output is also attached to the failure / error message.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="unittest.TestResult.failfast">
<code class="descname">failfast</code><a class="headerlink" href="#unittest.TestResult.failfast" title="Permalink to this definition">¶</a></dt>
<dd><p>If set to true <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> will be called on the first failure or error,
halting the test run.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.wasSuccessful">
<code class="descname">wasSuccessful</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.wasSuccessful" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if all tests run so far have passed, otherwise returns
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.stop">
<code class="descname">stop</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.stop" title="Permalink to this definition">¶</a></dt>
<dd><p>This method can be called to signal that the set of tests being run should
be aborted by setting the <a class="reference internal" href="#unittest.TestResult.shouldStop" title="unittest.TestResult.shouldStop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">shouldStop</span></code></a> attribute to <code class="docutils literal notranslate"><span class="pre">True</span></code>.
<code class="xref py py-class docutils literal notranslate"><span class="pre">TestRunner</span></code> objects should respect this flag and return without
running any additional tests.</p>
<p>For example, this feature is used by the <a class="reference internal" href="#unittest.TextTestRunner" title="unittest.TextTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextTestRunner</span></code></a> class to
stop the test framework when the user signals an interrupt from the
keyboard.  Interactive tools which provide <code class="xref py py-class docutils literal notranslate"><span class="pre">TestRunner</span></code>
implementations can use this in a similar manner.</p>
</dd></dl>

<p>The following methods of the <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> class are used to maintain
the internal data structures, and may be extended in subclasses to support
additional reporting requirements.  This is particularly useful in building
tools which support interactive reporting while tests are being run.</p>
<dl class="method">
<dt id="unittest.TestResult.startTest">
<code class="descname">startTest</code><span class="sig-paren">(</span><em>test</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.startTest" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> is about to be run.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.stopTest">
<code class="descname">stopTest</code><span class="sig-paren">(</span><em>test</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.stopTest" title="Permalink to this definition">¶</a></dt>
<dd><p>Called after the test case <em>test</em> has been executed, regardless of the
outcome.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.startTestRun">
<code class="descname">startTestRun</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.startTestRun" title="Permalink to this definition">¶</a></dt>
<dd><p>Called once before any tests are executed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.stopTestRun">
<code class="descname">stopTestRun</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.stopTestRun" title="Permalink to this definition">¶</a></dt>
<dd><p>Called once after all tests are executed.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addError">
<code class="descname">addError</code><span class="sig-paren">(</span><em>test</em>, <em>err</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addError" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> raises an unexpected exception. <em>err</em> is a
tuple of the form returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">value,</span>
<span class="pre">traceback)</span></code>.</p>
<p>The default implementation appends a tuple <code class="docutils literal notranslate"><span class="pre">(test,</span> <span class="pre">formatted_err)</span></code> to
the instance’s <a class="reference internal" href="#unittest.TestResult.errors" title="unittest.TestResult.errors"><code class="xref py py-attr docutils literal notranslate"><span class="pre">errors</span></code></a> attribute, where <em>formatted_err</em> is a
formatted traceback derived from <em>err</em>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addFailure">
<code class="descname">addFailure</code><span class="sig-paren">(</span><em>test</em>, <em>err</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addFailure" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> signals a failure. <em>err</em> is a tuple of
the form returned by <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">value,</span> <span class="pre">traceback)</span></code>.</p>
<p>The default implementation appends a tuple <code class="docutils literal notranslate"><span class="pre">(test,</span> <span class="pre">formatted_err)</span></code> to
the instance’s <a class="reference internal" href="#unittest.TestResult.failures" title="unittest.TestResult.failures"><code class="xref py py-attr docutils literal notranslate"><span class="pre">failures</span></code></a> attribute, where <em>formatted_err</em> is a
formatted traceback derived from <em>err</em>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addSuccess">
<code class="descname">addSuccess</code><span class="sig-paren">(</span><em>test</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addSuccess" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> succeeds.</p>
<p>The default implementation does nothing.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addSkip">
<code class="descname">addSkip</code><span class="sig-paren">(</span><em>test</em>, <em>reason</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addSkip" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> is skipped.  <em>reason</em> is the reason the
test gave for skipping.</p>
<p>The default implementation appends a tuple <code class="docutils literal notranslate"><span class="pre">(test,</span> <span class="pre">reason)</span></code> to the
instance’s <a class="reference internal" href="#unittest.TestResult.skipped" title="unittest.TestResult.skipped"><code class="xref py py-attr docutils literal notranslate"><span class="pre">skipped</span></code></a> attribute.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addExpectedFailure">
<code class="descname">addExpectedFailure</code><span class="sig-paren">(</span><em>test</em>, <em>err</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addExpectedFailure" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> fails, but was marked with the
<a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code class="xref py py-func docutils literal notranslate"><span class="pre">expectedFailure()</span></code></a> decorator.</p>
<p>The default implementation appends a tuple <code class="docutils literal notranslate"><span class="pre">(test,</span> <span class="pre">formatted_err)</span></code> to
the instance’s <a class="reference internal" href="#unittest.TestResult.expectedFailures" title="unittest.TestResult.expectedFailures"><code class="xref py py-attr docutils literal notranslate"><span class="pre">expectedFailures</span></code></a> attribute, where <em>formatted_err</em>
is a formatted traceback derived from <em>err</em>.</p>
</dd></dl>

<dl class="method">
<dt id="unittest.TestResult.addUnexpectedSuccess">
<code class="descname">addUnexpectedSuccess</code><span class="sig-paren">(</span><em>test</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TestResult.addUnexpectedSuccess" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the test case <em>test</em> was marked with the
<a class="reference internal" href="#unittest.expectedFailure" title="unittest.expectedFailure"><code class="xref py py-func docutils literal notranslate"><span class="pre">expectedFailure()</span></code></a> decorator, but succeeded.</p>
<p>The default implementation appends the test to the instance’s
<a class="reference internal" href="#unittest.TestResult.unexpectedSuccesses" title="unittest.TestResult.unexpectedSuccesses"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unexpectedSuccesses</span></code></a> attribute.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="unittest.TextTestResult">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TextTestResult</code><span class="sig-paren">(</span><em>stream</em>, <em>descriptions</em>, <em>verbosity</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TextTestResult" title="Permalink to this definition">¶</a></dt>
<dd><p>A concrete implementation of <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> used by the
<a class="reference internal" href="#unittest.TextTestRunner" title="unittest.TextTestRunner"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextTestRunner</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>This class was previously named <code class="docutils literal notranslate"><span class="pre">_TextTestResult</span></code>. The old name still
exists as an alias but is deprecated.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="unittest.defaultTestLoader">
<code class="descclassname">unittest.</code><code class="descname">defaultTestLoader</code><a class="headerlink" href="#unittest.defaultTestLoader" title="Permalink to this definition">¶</a></dt>
<dd><p>Instance of the <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> class intended to be shared.  If no
customization of the <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> is needed, this instance can be used
instead of repeatedly creating new instances.</p>
</dd></dl>

<dl class="class">
<dt id="unittest.TextTestRunner">
<em class="property">class </em><code class="descclassname">unittest.</code><code class="descname">TextTestRunner</code><span class="sig-paren">(</span><em>stream=sys.stderr</em>, <em>descriptions=True</em>, <em>verbosity=1</em>, <em>failfast=False</em>, <em>buffer=False</em>, <em>resultclass=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TextTestRunner" title="Permalink to this definition">¶</a></dt>
<dd><p>A basic test runner implementation which prints results on standard error. It
has a few configurable parameters, but is essentially very simple.  Graphical
applications which run test suites should provide alternate implementations.</p>
<dl class="method">
<dt id="unittest.TextTestRunner._makeResult">
<code class="descname">_makeResult</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.TextTestRunner._makeResult" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns the instance of <code class="docutils literal notranslate"><span class="pre">TestResult</span></code> used by <code class="xref py py-meth docutils literal notranslate"><span class="pre">run()</span></code>.
It is not intended to be called directly, but can be overridden in
subclasses to provide a custom <code class="docutils literal notranslate"><span class="pre">TestResult</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">_makeResult()</span></code> instantiates the class or callable passed in the
<code class="docutils literal notranslate"><span class="pre">TextTestRunner</span></code> constructor as the <code class="docutils literal notranslate"><span class="pre">resultclass</span></code> argument. It
defaults to <a class="reference internal" href="#unittest.TextTestResult" title="unittest.TextTestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextTestResult</span></code></a> if no <code class="docutils literal notranslate"><span class="pre">resultclass</span></code> is provided.
The result class is instantiated with the following arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">stream</span><span class="p">,</span> <span class="n">descriptions</span><span class="p">,</span> <span class="n">verbosity</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

<dl class="function">
<dt id="unittest.main">
<code class="descclassname">unittest.</code><code class="descname">main</code><span class="sig-paren">(</span><span class="optional">[</span><em>module</em><span class="optional">[</span>, <em>defaultTest</em><span class="optional">[</span>, <em>argv</em><span class="optional">[</span>, <em>testRunner</em><span class="optional">[</span>, <em>testLoader</em><span class="optional">[</span>, <em>exit</em><span class="optional">[</span>, <em>verbosity</em><span class="optional">[</span>, <em>failfast</em><span class="optional">[</span>, <em>catchbreak</em><span class="optional">[</span>, <em>buffer</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.main" title="Permalink to this definition">¶</a></dt>
<dd><p>A command-line program that loads a set of tests from <em>module</em> and runs them;
this is primarily for making test modules conveniently executable.
The simplest use for this function is to include the following line at the
end of a test script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<p>You can run tests with more detailed information by passing in the verbosity
argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">(</span><span class="n">verbosity</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>The <em>defaultTest</em> argument is the name of the test to run if no test names
are specified via <em>argv</em>.  If not specified or <code class="docutils literal notranslate"><span class="pre">None</span></code> and no test names are
provided via <em>argv</em>, all tests found in <em>module</em> are run.</p>
<p>The <em>argv</em> argument can be a list of options passed to the program, with the
first element being the program name.  If not specified or <code class="docutils literal notranslate"><span class="pre">None</span></code>,
the values of <a class="reference internal" href="sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> are used.</p>
<p>The <em>testRunner</em> argument can either be a test runner class or an already
created instance of it. By default <code class="docutils literal notranslate"><span class="pre">main</span></code> calls <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> with
an exit code indicating success or failure of the tests run.</p>
<p>The <em>testLoader</em> argument has to be a <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> instance,
and defaults to <a class="reference internal" href="#unittest.defaultTestLoader" title="unittest.defaultTestLoader"><code class="xref py py-data docutils literal notranslate"><span class="pre">defaultTestLoader</span></code></a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">main</span></code> supports being used from the interactive interpreter by passing in the
argument <code class="docutils literal notranslate"><span class="pre">exit=False</span></code>. This displays the result on standard output without
calling <a class="reference internal" href="sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">unittest</span> <span class="k">import</span> <span class="n">main</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">main</span><span class="p">(</span><span class="n">module</span><span class="o">=</span><span class="s1">&#39;test_module&#39;</span><span class="p">,</span> <span class="n">exit</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<p>The <em>failfast</em>, <em>catchbreak</em> and <em>buffer</em> parameters have the same
effect as the same-name <a class="reference internal" href="#command-line-options">command-line options</a>.</p>
<p>Calling <code class="docutils literal notranslate"><span class="pre">main</span></code> actually returns an instance of the <code class="docutils literal notranslate"><span class="pre">TestProgram</span></code> class.
This stores the result of the tests run as the <code class="docutils literal notranslate"><span class="pre">result</span></code> attribute.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The <em>exit</em>, <em>verbosity</em>, <em>failfast</em>, <em>catchbreak</em> and <em>buffer</em>
parameters were added.</p>
</div>
</dd></dl>

<div class="section" id="load-tests-protocol">
<h4>25.3.7.3.1. load_tests Protocol<a class="headerlink" href="#load-tests-protocol" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<p>Modules or packages can customize how tests are loaded from them during normal
test runs or test discovery by implementing a function called <code class="docutils literal notranslate"><span class="pre">load_tests</span></code>.</p>
<p>If a test module defines <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> it will be called by
<a class="reference internal" href="#unittest.TestLoader.loadTestsFromModule" title="unittest.TestLoader.loadTestsFromModule"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestLoader.loadTestsFromModule()</span></code></a> with the following arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">load_tests</span><span class="p">(</span><span class="n">loader</span><span class="p">,</span> <span class="n">standard_tests</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>It should return a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a>.</p>
<p><em>loader</em> is the instance of <a class="reference internal" href="#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a> doing the loading.
<em>standard_tests</em> are the tests that would be loaded by default from the
module. It is common for test modules to only want to add or remove tests
from the standard set of tests.
The third argument is used when loading packages as part of test discovery.</p>
<p>A typical <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> function that loads tests from a specific set of
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> classes may look like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">test_cases</span> <span class="o">=</span> <span class="p">(</span><span class="n">TestCase1</span><span class="p">,</span> <span class="n">TestCase2</span><span class="p">,</span> <span class="n">TestCase3</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">load_tests</span><span class="p">(</span><span class="n">loader</span><span class="p">,</span> <span class="n">tests</span><span class="p">,</span> <span class="n">pattern</span><span class="p">):</span>
    <span class="n">suite</span> <span class="o">=</span> <span class="n">TestSuite</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">test_class</span> <span class="ow">in</span> <span class="n">test_cases</span><span class="p">:</span>
        <span class="n">tests</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">loadTestsFromTestCase</span><span class="p">(</span><span class="n">test_class</span><span class="p">)</span>
        <span class="n">suite</span><span class="o">.</span><span class="n">addTests</span><span class="p">(</span><span class="n">tests</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">suite</span>
</pre></div>
</div>
<p>If discovery is started, either from the command line or by calling
<a class="reference internal" href="#unittest.TestLoader.discover" title="unittest.TestLoader.discover"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestLoader.discover()</span></code></a>, with a pattern that matches a package
name then the package <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> will be checked for <code class="docutils literal notranslate"><span class="pre">load_tests</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The default pattern is <code class="docutils literal notranslate"><span class="pre">'test*.py'</span></code>. This matches all Python files
that start with <code class="docutils literal notranslate"><span class="pre">'test'</span></code> but <em>won’t</em> match any test directories.</p>
<p class="last">A pattern like <code class="docutils literal notranslate"><span class="pre">'test*'</span></code> will match test packages as well as
modules.</p>
</div>
<p>If the package <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> defines <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> then it will be
called and discovery not continued into the package. <code class="docutils literal notranslate"><span class="pre">load_tests</span></code>
is called with the following arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">load_tests</span><span class="p">(</span><span class="n">loader</span><span class="p">,</span> <span class="n">standard_tests</span><span class="p">,</span> <span class="n">pattern</span><span class="p">)</span>
</pre></div>
</div>
<p>This should return a <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a> representing all the tests
from the package. (<code class="docutils literal notranslate"><span class="pre">standard_tests</span></code> will only contain tests
collected from <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>.)</p>
<p>Because the pattern is passed into <code class="docutils literal notranslate"><span class="pre">load_tests</span></code> the package is free to
continue (and potentially modify) test discovery. A ‘do nothing’
<code class="docutils literal notranslate"><span class="pre">load_tests</span></code> function for a test package would look like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">load_tests</span><span class="p">(</span><span class="n">loader</span><span class="p">,</span> <span class="n">standard_tests</span><span class="p">,</span> <span class="n">pattern</span><span class="p">):</span>
    <span class="c1"># top level directory cached on loader instance</span>
    <span class="n">this_dir</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">dirname</span><span class="p">(</span><span class="vm">__file__</span><span class="p">)</span>
    <span class="n">package_tests</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">discover</span><span class="p">(</span><span class="n">start_dir</span><span class="o">=</span><span class="n">this_dir</span><span class="p">,</span> <span class="n">pattern</span><span class="o">=</span><span class="n">pattern</span><span class="p">)</span>
    <span class="n">standard_tests</span><span class="o">.</span><span class="n">addTests</span><span class="p">(</span><span class="n">package_tests</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">standard_tests</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="class-and-module-fixtures">
<h2>25.3.8. Class and Module Fixtures<a class="headerlink" href="#class-and-module-fixtures" title="Permalink to this headline">¶</a></h2>
<p>Class and module level fixtures are implemented in <a class="reference internal" href="#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestSuite</span></code></a>. When
the test suite encounters a test from a new class then <code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDownClass()</span></code>
from the previous class (if there is one) is called, followed by
<code class="xref py py-meth docutils literal notranslate"><span class="pre">setUpClass()</span></code> from the new class.</p>
<p>Similarly if a test is from a different module from the previous test then
<code class="docutils literal notranslate"><span class="pre">tearDownModule</span></code> from the previous module is run, followed by
<code class="docutils literal notranslate"><span class="pre">setUpModule</span></code> from the new module.</p>
<p>After all the tests have run the final <code class="docutils literal notranslate"><span class="pre">tearDownClass</span></code> and
<code class="docutils literal notranslate"><span class="pre">tearDownModule</span></code> are run.</p>
<p>Note that shared fixtures do not play well with [potential] features like test
parallelization and they break test isolation. They should be used with care.</p>
<p>The default ordering of tests created by the unittest test loaders is to group
all tests from the same modules and classes together. This will lead to
<code class="docutils literal notranslate"><span class="pre">setUpClass</span></code> / <code class="docutils literal notranslate"><span class="pre">setUpModule</span></code> (etc) being called exactly once per class and
module. If you randomize the order, so that tests from different modules and
classes are adjacent to each other, then these shared fixture functions may be
called multiple times in a single test run.</p>
<p>Shared fixtures are not intended to work with suites with non-standard
ordering. A <code class="docutils literal notranslate"><span class="pre">BaseTestSuite</span></code> still exists for frameworks that don’t want to
support shared fixtures.</p>
<p>If there are any exceptions raised during one of the shared fixture functions
the test is reported as an error. Because there is no corresponding test
instance an <code class="docutils literal notranslate"><span class="pre">_ErrorHolder</span></code> object (that has the same interface as a
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>) is created to represent the error. If you are just using
the standard unittest test runner then this detail doesn’t matter, but if you
are a framework author it may be relevant.</p>
<div class="section" id="setupclass-and-teardownclass">
<h3>25.3.8.1. setUpClass and tearDownClass<a class="headerlink" href="#setupclass-and-teardownclass" title="Permalink to this headline">¶</a></h3>
<p>These must be implemented as class methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">Test</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">setUpClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">_connection</span> <span class="o">=</span> <span class="n">createExpensiveConnectionObject</span><span class="p">()</span>

    <span class="nd">@classmethod</span>
    <span class="k">def</span> <span class="nf">tearDownClass</span><span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
        <span class="bp">cls</span><span class="o">.</span><span class="n">_connection</span><span class="o">.</span><span class="n">destroy</span><span class="p">()</span>
</pre></div>
</div>
<p>If you want the <code class="docutils literal notranslate"><span class="pre">setUpClass</span></code> and <code class="docutils literal notranslate"><span class="pre">tearDownClass</span></code> on base classes called
then you must call up to them yourself. The implementations in
<a class="reference internal" href="#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> are empty.</p>
<p>If an exception is raised during a <code class="docutils literal notranslate"><span class="pre">setUpClass</span></code> then the tests in the class
are not run and the <code class="docutils literal notranslate"><span class="pre">tearDownClass</span></code> is not run. Skipped classes will not
have <code class="docutils literal notranslate"><span class="pre">setUpClass</span></code> or <code class="docutils literal notranslate"><span class="pre">tearDownClass</span></code> run. If the exception is a
<a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SkipTest</span></code></a> exception then the class will be reported as having been skipped
instead of as an error.</p>
</div>
<div class="section" id="setupmodule-and-teardownmodule">
<h3>25.3.8.2. setUpModule and tearDownModule<a class="headerlink" href="#setupmodule-and-teardownmodule" title="Permalink to this headline">¶</a></h3>
<p>These should be implemented as functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">setUpModule</span><span class="p">():</span>
    <span class="n">createConnection</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">tearDownModule</span><span class="p">():</span>
    <span class="n">closeConnection</span><span class="p">()</span>
</pre></div>
</div>
<p>If an exception is raised in a <code class="docutils literal notranslate"><span class="pre">setUpModule</span></code> then none of the tests in the
module will be run and the <code class="docutils literal notranslate"><span class="pre">tearDownModule</span></code> will not be run. If the exception is a
<a class="reference internal" href="#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SkipTest</span></code></a> exception then the module will be reported as having been skipped
instead of as an error.</p>
</div>
</div>
<div class="section" id="signal-handling">
<h2>25.3.9. Signal Handling<a class="headerlink" href="#signal-handling" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#cmdoption-unittest-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c/--catch</span></code></a> command-line option to unittest,
along with the <code class="docutils literal notranslate"><span class="pre">catchbreak</span></code> parameter to <a class="reference internal" href="#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">unittest.main()</span></code></a>, provide
more friendly handling of control-C during a test run. With catch break
behavior enabled control-C will allow the currently running test to complete,
and the test run will then end and report all the results so far. A second
control-c will raise a <a class="reference internal" href="exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> in the usual way.</p>
<p>The control-c handling signal handler attempts to remain compatible with code or
tests that install their own <code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code> handler. If the <code class="docutils literal notranslate"><span class="pre">unittest</span></code>
handler is called but <em>isn’t</em> the installed <code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code> handler,
i.e. it has been replaced by the system under test and delegated to, then it
calls the default handler. This will normally be the expected behavior by code
that replaces an installed handler and delegates to it. For individual tests
that need <code class="docutils literal notranslate"><span class="pre">unittest</span></code> control-c handling disabled the <a class="reference internal" href="#unittest.removeHandler" title="unittest.removeHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">removeHandler()</span></code></a>
decorator can be used.</p>
<p>There are a few utility functions for framework authors to enable control-c
handling functionality within test frameworks.</p>
<dl class="function">
<dt id="unittest.installHandler">
<code class="descclassname">unittest.</code><code class="descname">installHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#unittest.installHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Install the control-c handler. When a <code class="xref py py-const docutils literal notranslate"><span class="pre">signal.SIGINT</span></code> is received
(usually in response to the user pressing control-c) all registered results
have <a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> called.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unittest.registerResult">
<code class="descclassname">unittest.</code><code class="descname">registerResult</code><span class="sig-paren">(</span><em>result</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.registerResult" title="Permalink to this definition">¶</a></dt>
<dd><p>Register a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> object for control-c handling. Registering a
result stores a weak reference to it, so it doesn’t prevent the result from
being garbage collected.</p>
<p>Registering a <a class="reference internal" href="#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> object has no side-effects if control-c
handling is not enabled, so test frameworks can unconditionally register
all results they create independently of whether or not handling is enabled.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unittest.removeResult">
<code class="descclassname">unittest.</code><code class="descname">removeResult</code><span class="sig-paren">(</span><em>result</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.removeResult" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove a registered result. Once a result has been removed then
<a class="reference internal" href="#unittest.TestResult.stop" title="unittest.TestResult.stop"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stop()</span></code></a> will no longer be called on that result object in
response to a control-c.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="unittest.removeHandler">
<code class="descclassname">unittest.</code><code class="descname">removeHandler</code><span class="sig-paren">(</span><em>function=None</em><span class="sig-paren">)</span><a class="headerlink" href="#unittest.removeHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>When called without arguments this function removes the control-c handler
if it has been installed. This function can also be used as a test decorator
to temporarily remove the handler while the test is being executed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@unittest</span><span class="o">.</span><span class="n">removeHandler</span>
<span class="k">def</span> <span class="nf">test_signal_handling</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a><ul>
<li><a class="reference internal" href="#basic-example">25.3.1. Basic example</a></li>
<li><a class="reference internal" href="#command-line-interface">25.3.2. Command-Line Interface</a><ul>
<li><a class="reference internal" href="#command-line-options">25.3.2.1. Command-line options</a></li>
</ul>
</li>
<li><a class="reference internal" href="#test-discovery">25.3.3. Test Discovery</a></li>
<li><a class="reference internal" href="#organizing-test-code">25.3.4. Organizing test code</a></li>
<li><a class="reference internal" href="#re-using-old-test-code">25.3.5. Re-using old test code</a></li>
<li><a class="reference internal" href="#skipping-tests-and-expected-failures">25.3.6. Skipping tests and expected failures</a></li>
<li><a class="reference internal" href="#classes-and-functions">25.3.7. Classes and functions</a><ul>
<li><a class="reference internal" href="#test-cases">25.3.7.1. Test cases</a><ul>
<li><a class="reference internal" href="#deprecated-aliases">25.3.7.1.1. Deprecated aliases</a></li>
</ul>
</li>
<li><a class="reference internal" href="#grouping-tests">25.3.7.2. Grouping tests</a></li>
<li><a class="reference internal" href="#loading-and-running-tests">25.3.7.3. Loading and running tests</a><ul>
<li><a class="reference internal" href="#load-tests-protocol">25.3.7.3.1. load_tests Protocol</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#class-and-module-fixtures">25.3.8. Class and Module Fixtures</a><ul>
<li><a class="reference internal" href="#setupclass-and-teardownclass">25.3.8.1. setUpClass and tearDownClass</a></li>
<li><a class="reference internal" href="#setupmodule-and-teardownmodule">25.3.8.2. setUpModule and tearDownModule</a></li>
</ul>
</li>
<li><a class="reference internal" href="#signal-handling">25.3.9. Signal Handling</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="doctest.html"
                        title="previous chapter">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2to3.html"
                        title="next chapter">25.4. 2to3 - Automated Python 2 to 3 code translation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/unittest.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2to3.html" title="25.4. 2to3 - Automated Python 2 to 3 code translation"
             >next</a> |</li>
        <li class="right" >
          <a href="doctest.html" title="25.2. doctest — Test interactive Python examples"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" >25. Development Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1�F��+�+html/library/unix.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>36. Unix Specific Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36.1. posix — The most common POSIX system calls" href="posix.html" />
    <link rel="prev" title="35.4. winsound — Sound-playing interface for Windows" href="winsound.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/unix.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="posix.html" title="36.1. posix — The most common POSIX system calls"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="winsound.html" title="35.4. winsound — Sound-playing interface for Windows"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="unix-specific-services">
<span id="unix"></span><h1>36. Unix Specific Services<a class="headerlink" href="#unix-specific-services" title="Permalink to this headline">¶</a></h1>
<p>The modules described in this chapter provide interfaces to features that are
unique to the Unix operating system, or in some cases to some or many variants
of it.  Here’s an overview:</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="posix.html">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a><ul>
<li class="toctree-l2"><a class="reference internal" href="posix.html#large-file-support">36.1.1. Large File Support</a></li>
<li class="toctree-l2"><a class="reference internal" href="posix.html#notable-module-contents">36.1.2. Notable Module Contents</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="pwd.html">36.2. <code class="docutils literal notranslate"><span class="pre">pwd</span></code> — The password database</a></li>
<li class="toctree-l1"><a class="reference internal" href="spwd.html">36.3. <code class="docutils literal notranslate"><span class="pre">spwd</span></code> — The shadow password database</a></li>
<li class="toctree-l1"><a class="reference internal" href="grp.html">36.4. <code class="docutils literal notranslate"><span class="pre">grp</span></code> — The group database</a></li>
<li class="toctree-l1"><a class="reference internal" href="crypt.html">36.5. <code class="docutils literal notranslate"><span class="pre">crypt</span></code> — Function to check Unix passwords</a></li>
<li class="toctree-l1"><a class="reference internal" href="dl.html">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a><ul>
<li class="toctree-l2"><a class="reference internal" href="dl.html#dl-objects">36.6.1. Dl Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="termios.html">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a><ul>
<li class="toctree-l2"><a class="reference internal" href="termios.html#example">36.7.1. Example</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tty.html">36.8. <code class="docutils literal notranslate"><span class="pre">tty</span></code> — Terminal control functions</a></li>
<li class="toctree-l1"><a class="reference internal" href="pty.html">36.9. <code class="docutils literal notranslate"><span class="pre">pty</span></code> — Pseudo-terminal utilities</a></li>
<li class="toctree-l1"><a class="reference internal" href="fcntl.html">36.10. <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls</a></li>
<li class="toctree-l1"><a class="reference internal" href="pipes.html">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a><ul>
<li class="toctree-l2"><a class="reference internal" href="pipes.html#template-objects">36.11.1. Template Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="posixfile.html">36.12. <code class="docutils literal notranslate"><span class="pre">posixfile</span></code> — File-like objects with locking support</a></li>
<li class="toctree-l1"><a class="reference internal" href="resource.html">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a><ul>
<li class="toctree-l2"><a class="reference internal" href="resource.html#resource-limits">36.13.1. Resource Limits</a></li>
<li class="toctree-l2"><a class="reference internal" href="resource.html#resource-usage">36.13.2. Resource Usage</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="nis.html">36.14. <code class="docutils literal notranslate"><span class="pre">nis</span></code> — Interface to Sun’s NIS (Yellow Pages)</a></li>
<li class="toctree-l1"><a class="reference internal" href="syslog.html">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a><ul>
<li class="toctree-l2"><a class="reference internal" href="syslog.html#examples">36.15.1. Examples</a><ul>
<li class="toctree-l3"><a class="reference internal" href="syslog.html#simple-example">36.15.1.1. Simple example</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="commands.html">36.16. <code class="docutils literal notranslate"><span class="pre">commands</span></code> — Utilities for running commands</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="winsound.html"
                        title="previous chapter">35.4. <code class="docutils literal notranslate"><span class="pre">winsound</span></code> — Sound-playing interface for Windows</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="posix.html"
                        title="next chapter">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/unix.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="posix.html" title="36.1. posix — The most common POSIX system calls"
             >next</a> |</li>
        <li class="right" >
          <a href="winsound.html" title="35.4. winsound — Sound-playing interface for Windows"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\DB�t�
�
html/library/urllib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.5. urllib — Open arbitrary resources by URL &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.6. urllib2 — extensible library for opening URLs" href="urllib2.html" />
    <link rel="prev" title="20.4. wsgiref — WSGI Utilities and Reference Implementation" href="wsgiref.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/urllib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="20.6. urllib2 — extensible library for opening URLs"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="wsgiref.html" title="20.4. wsgiref — WSGI Utilities and Reference Implementation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-urllib">
<span id="urllib-open-arbitrary-resources-by-url"></span><h1>20.5. <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> — Open arbitrary resources by URL<a class="headerlink" href="#module-urllib" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> module has been split into parts and renamed in
Python 3 to <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.parse</span></code>,
and <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.error</span></code>. The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt
imports when converting your sources to Python 3.
Also note that the <code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.request.urlopen()</span></code> function in Python 3 is
equivalent to <a class="reference internal" href="urllib2.html#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib2.urlopen()</span></code></a> and that <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlopen()</span></code></a> has
been removed.</p>
</div>
<p id="index-0">This module provides a high-level interface for fetching data across the World
Wide Web.  In particular, the <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> function is similar to the
built-in function <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, but accepts Universal Resource Locators (URLs)
instead of filenames.  Some restrictions apply — it can only open URLs for
reading, and no seek operations are available.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference external" href="http://docs.python-requests.org/">Requests package</a>
is recommended for a higher-level HTTP client interface.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>For HTTPS URIs, <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> performs all the neccessary certificate and hostname checks by default.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">For Python versions earlier than 2.7.9, urllib does not attempt to validate the server certificates of HTTPS URIs. Use at your own risk!</p>
</div>
<div class="section" id="high-level-interface">
<h2>20.5.1. High-level interface<a class="headerlink" href="#high-level-interface" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="urllib.urlopen">
<code class="descclassname">urllib.</code><code class="descname">urlopen</code><span class="sig-paren">(</span><em>url</em><span class="optional">[</span>, <em>data</em><span class="optional">[</span>, <em>proxies</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.urlopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a network object denoted by a URL for reading.  If the URL does not
have a scheme identifier, or if it has <code class="file docutils literal notranslate"><span class="pre">file:</span></code> as its scheme
identifier, this opens a local file (without <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a>);
otherwise it opens a socket to a server somewhere on the network.  If the
connection cannot be made the <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception is raised.  If all
went well, a file-like object is returned.  This supports the following
methods: <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>, <a class="reference internal" href="readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getcode()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code>.  It also
has proper support for the <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> protocol. One caveat: the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method, if the size argument is omitted or negative, may not
read until the end of the data stream; there is no good way to determine
that the entire stream from a socket has been read in the general case.</p>
<p>Except for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">getcode()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code> methods,
these methods have the same interface as for file objects — see section
<a class="reference internal" href="stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a> in this manual.  (It is not a built-in file object,
however, so it can’t be used at those few places where a true built-in file
object is required.)</p>
<p id="index-1">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> method returns an instance of the class
<a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a> containing meta-information associated with the
URL.  When the method is HTTP, these headers are those returned by the server
at the head of the retrieved HTML page (including Content-Length and
Content-Type).  When the method is FTP, a Content-Length header will be
present if (as is now usual) the server passed back a file length in response
to the FTP retrieval request. A Content-Type header will be present if the
MIME type can be guessed.  When the method is local-file, returned headers
will include a Date representing the file’s last-modified time, a
Content-Length giving file size, and a Content-Type containing a guess at the
file’s type. See also the description of the <a class="reference internal" href="mimetools.html#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a> module.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code> method returns the real URL of the page.  In some cases, the
HTTP server redirects a client to another URL.  The <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> function
handles this transparently, but in some cases the caller needs to know which URL
the client was redirected to.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code> method can be used to get at
this redirected URL.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">getcode()</span></code> method returns the HTTP status code that was sent with the
response, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the URL is no HTTP URL.</p>
<p>If the <em>url</em> uses the <code class="file docutils literal notranslate"><span class="pre">http:</span></code> scheme identifier, the optional <em>data</em>
argument may be given to specify a <code class="docutils literal notranslate"><span class="pre">POST</span></code> request (normally the request type
is <code class="docutils literal notranslate"><span class="pre">GET</span></code>).  The <em>data</em> argument must be in standard
<em class="mimetype">application/x-www-form-urlencoded</em> format; see the <a class="reference internal" href="#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlencode()</span></code></a>
function below.</p>
<p>The <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> function works transparently with proxies which do not
require authentication.  In a Unix or Windows environment, set the
<span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">http_proxy</span></code>, or <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">ftp_proxy</span></code> environment variables to a URL that
identifies the proxy server before starting the Python interpreter.  For example
(the <code class="docutils literal notranslate"><span class="pre">'%'</span></code> is the command prompt):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">%</span> <span class="n">http_proxy</span><span class="o">=</span><span class="s2">&quot;http://www.someproxy.com:3128&quot;</span>
<span class="o">%</span> <span class="n">export</span> <span class="n">http_proxy</span>
<span class="o">%</span> <span class="n">python</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The <span class="target" id="index-4"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">no_proxy</span></code> environment variable can be used to specify hosts which
shouldn’t be reached via proxy; if set, it should be a comma-separated list
of hostname suffixes, optionally with <code class="docutils literal notranslate"><span class="pre">:port</span></code> appended, for example
<code class="docutils literal notranslate"><span class="pre">cern.ch,ncsa.uiuc.edu,some.host:8080</span></code>.</p>
<p>In a Windows environment, if no proxy environment variables are set, proxy
settings are obtained from the registry’s Internet Settings section.</p>
<p id="index-5">In a Mac OS X  environment, <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> will retrieve proxy information
from the OS X System Configuration Framework, which can be managed with
Network System Preferences panel.</p>
<p>Alternatively, the optional <em>proxies</em> argument may be used to explicitly specify
proxies.  It must be a dictionary mapping scheme names to proxy URLs, where an
empty dictionary causes no proxies to be used, and <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default value)
causes environmental proxy settings to be used as discussed above.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Use http://www.someproxy.com:3128 for HTTP proxying</span>
<span class="n">proxies</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;http&#39;</span><span class="p">:</span> <span class="s1">&#39;http://www.someproxy.com:3128&#39;</span><span class="p">}</span>
<span class="n">filehandle</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">some_url</span><span class="p">,</span> <span class="n">proxies</span><span class="o">=</span><span class="n">proxies</span><span class="p">)</span>
<span class="c1"># Don&#39;t use any proxies</span>
<span class="n">filehandle</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">some_url</span><span class="p">,</span> <span class="n">proxies</span><span class="o">=</span><span class="p">{})</span>
<span class="c1"># Use proxies from environment - both versions are equivalent</span>
<span class="n">filehandle</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">some_url</span><span class="p">,</span> <span class="n">proxies</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="n">filehandle</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">some_url</span><span class="p">)</span>
</pre></div>
</div>
<p>Proxies which require authentication for use are not currently supported;
this is considered an implementation limitation.</p>
<p>The <em>context</em> parameter may be set to a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> instance to
configure the SSL settings that are used if <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> makes a HTTPS
connection.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Added the <em>proxies</em> support.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added <code class="xref py py-meth docutils literal notranslate"><span class="pre">getcode()</span></code> to returned object and support for the
<span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">no_proxy</span></code> environment variable.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>The <em>context</em> parameter was added.  All the neccessary certificate and hostname
checks are done by default.</p>
</div>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> function has been removed in Python 3 in favor
of <a class="reference internal" href="urllib2.html#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib2.urlopen()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urllib.urlretrieve">
<code class="descclassname">urllib.</code><code class="descname">urlretrieve</code><span class="sig-paren">(</span><em>url</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>reporthook</em><span class="optional">[</span>, <em>data</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.urlretrieve" title="Permalink to this definition">¶</a></dt>
<dd><p>Copy a network object denoted by a URL to a local file, if necessary. If the URL
points to a local file, or a valid cached copy of the object exists, the object
is not copied.  Return a tuple <code class="docutils literal notranslate"><span class="pre">(filename,</span> <span class="pre">headers)</span></code> where <em>filename</em> is the
local file name under which the object can be found, and <em>headers</em> is whatever
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> method of the object returned by <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> returned (for
a remote object, possibly cached). Exceptions are the same as for
<a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.</p>
<p>The second argument, if present, specifies the file location to copy to (if
absent, the location will be a tempfile with a generated name). The third
argument, if present, is a callable that will be called once on
establishment of the network connection and once after each block read
thereafter.  The callable will be passed three arguments; a count of blocks
transferred so far, a block size in bytes, and the total size of the file.  The
third argument may be <code class="docutils literal notranslate"><span class="pre">-1</span></code> on older FTP servers which do not return a file
size in response to a retrieval request.</p>
<p>If the <em>url</em> uses the <code class="file docutils literal notranslate"><span class="pre">http:</span></code> scheme identifier, the optional <em>data</em>
argument may be given to specify a <code class="docutils literal notranslate"><span class="pre">POST</span></code> request (normally the request type
is <code class="docutils literal notranslate"><span class="pre">GET</span></code>).  The <em>data</em> argument must in standard
<em class="mimetype">application/x-www-form-urlencoded</em> format; see the <a class="reference internal" href="#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlencode()</span></code></a>
function below.</p>
<p>The <em>context</em> parameter may be set to a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> instance to
configure the SSL settings that are used if <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> makes a HTTPS
connection.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> will raise <a class="reference internal" href="#urllib.ContentTooShortError" title="urllib.ContentTooShortError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ContentTooShortError</span></code></a> when it detects that
the amount of data available  was less than the expected amount (which is the
size reported by a  <em>Content-Length</em> header). This can occur, for example, when
the  download is interrupted.</p>
<p>The <em>Content-Length</em> is treated as a lower bound: if there’s more data  to read,
<a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> reads more data, but if less data is available,  it raises
the exception.</p>
<p>You can still retrieve the downloaded data in this case, it is stored  in the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">content</span></code> attribute of the exception instance.</p>
<p>If no <em>Content-Length</em> header was supplied, <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> can not check
the size of the data it has downloaded, and just returns it.  In this case you
just have to assume that the download was successful.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>The <em>context</em> parameter was added.  All the neccessary certificate and hostname
checks are done by default.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="urllib._urlopener">
<code class="descclassname">urllib.</code><code class="descname">_urlopener</code><a class="headerlink" href="#urllib._urlopener" title="Permalink to this definition">¶</a></dt>
<dd><p>The public functions <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> and <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> create an instance
of the <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a> class and use it to perform their requested
actions.  To override this functionality, programmers can create a subclass of
<a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> or <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a>, then assign an instance of that
class to the <code class="docutils literal notranslate"><span class="pre">urllib._urlopener</span></code> variable before calling the desired function.
For example, applications may want to specify a different
<em class="mailheader">User-Agent</em> header than <a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> defines.  This can be
accomplished with the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span>

<span class="k">class</span> <span class="nc">AppURLopener</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">FancyURLopener</span><span class="p">):</span>
    <span class="n">version</span> <span class="o">=</span> <span class="s2">&quot;App/1.7&quot;</span>

<span class="n">urllib</span><span class="o">.</span><span class="n">_urlopener</span> <span class="o">=</span> <span class="n">AppURLopener</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="urllib.urlcleanup">
<code class="descclassname">urllib.</code><code class="descname">urlcleanup</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.urlcleanup" title="Permalink to this definition">¶</a></dt>
<dd><p>Clear the cache that may have been built up by previous calls to
<a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="utility-functions">
<h2>20.5.2. Utility functions<a class="headerlink" href="#utility-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="urllib.quote">
<code class="descclassname">urllib.</code><code class="descname">quote</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>safe</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.quote" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace special characters in <em>string</em> using the <code class="docutils literal notranslate"><span class="pre">%xx</span></code> escape. Letters,
digits, and the characters <code class="docutils literal notranslate"><span class="pre">'_.-'</span></code> are never quoted. By default, this
function is intended for quoting the path section of the URL. The optional
<em>safe</em> parameter specifies additional characters that should not be quoted
— its default value is <code class="docutils literal notranslate"><span class="pre">'/'</span></code>.</p>
<p>Example: <code class="docutils literal notranslate"><span class="pre">quote('/~connolly/')</span></code> yields <code class="docutils literal notranslate"><span class="pre">'/%7econnolly/'</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.quote_plus">
<code class="descclassname">urllib.</code><code class="descname">quote_plus</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>safe</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.quote_plus" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#urllib.quote" title="urllib.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">quote()</span></code></a>, but also replaces spaces by plus signs, as required for
quoting HTML form values when building up a query string to go into a URL.
Plus signs in the original string are escaped unless they are included in
<em>safe</em>.  It also does not have <em>safe</em> default to <code class="docutils literal notranslate"><span class="pre">'/'</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.unquote">
<code class="descclassname">urllib.</code><code class="descname">unquote</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.unquote" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace <code class="docutils literal notranslate"><span class="pre">%xx</span></code> escapes by their single-character equivalent.</p>
<p>Example: <code class="docutils literal notranslate"><span class="pre">unquote('/%7Econnolly/')</span></code> yields <code class="docutils literal notranslate"><span class="pre">'/~connolly/'</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.unquote_plus">
<code class="descclassname">urllib.</code><code class="descname">unquote_plus</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.unquote_plus" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#urllib.unquote" title="urllib.unquote"><code class="xref py py-func docutils literal notranslate"><span class="pre">unquote()</span></code></a>, but also replaces plus signs by spaces, as required for
unquoting HTML form values.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.urlencode">
<code class="descclassname">urllib.</code><code class="descname">urlencode</code><span class="sig-paren">(</span><em>query</em><span class="optional">[</span>, <em>doseq</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.urlencode" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert a mapping object or a sequence of two-element tuples to a
“percent-encoded” string, suitable to pass to <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> above as the
optional <em>data</em> argument.  This is useful to pass a dictionary of form
fields to a <code class="docutils literal notranslate"><span class="pre">POST</span></code> request.  The resulting string is a series of
<code class="docutils literal notranslate"><span class="pre">key=value</span></code> pairs separated by <code class="docutils literal notranslate"><span class="pre">'&amp;'</span></code> characters, where both <em>key</em> and
<em>value</em> are quoted using <a class="reference internal" href="#urllib.quote_plus" title="urllib.quote_plus"><code class="xref py py-func docutils literal notranslate"><span class="pre">quote_plus()</span></code></a> above.  When a sequence of
two-element tuples is used as the <em>query</em> argument, the first element of
each tuple is a key and the second is a value. The value element in itself
can be a sequence and in that case, if the optional parameter <em>doseq</em> is
evaluates to <code class="docutils literal notranslate"><span class="pre">True</span></code>, individual <code class="docutils literal notranslate"><span class="pre">key=value</span></code> pairs separated by <code class="docutils literal notranslate"><span class="pre">'&amp;'</span></code> are
generated for each element of the value sequence for the key.  The order of
parameters in the encoded string will match the order of parameter tuples in
the sequence. The <a class="reference internal" href="urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module provides the functions
<code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qs()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qsl()</span></code> which are used to parse query strings
into Python data structures.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.pathname2url">
<code class="descclassname">urllib.</code><code class="descname">pathname2url</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.pathname2url" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the pathname <em>path</em> from the local syntax for a path to the form used in
the path component of a URL.  This does not produce a complete URL.  The return
value will already be quoted using the <a class="reference internal" href="#urllib.quote" title="urllib.quote"><code class="xref py py-func docutils literal notranslate"><span class="pre">quote()</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.url2pathname">
<code class="descclassname">urllib.</code><code class="descname">url2pathname</code><span class="sig-paren">(</span><em>path</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.url2pathname" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert the path component <em>path</em> from a percent-encoded URL to the local syntax for a
path.  This does not accept a complete URL.  This function uses <a class="reference internal" href="#urllib.unquote" title="urllib.unquote"><code class="xref py py-func docutils literal notranslate"><span class="pre">unquote()</span></code></a>
to decode <em>path</em>.</p>
</dd></dl>

<dl class="function">
<dt id="urllib.getproxies">
<code class="descclassname">urllib.</code><code class="descname">getproxies</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.getproxies" title="Permalink to this definition">¶</a></dt>
<dd><p>This helper function returns a dictionary of scheme to proxy server URL
mappings. It scans the environment for variables named <code class="docutils literal notranslate"><span class="pre">&lt;scheme&gt;_proxy</span></code>,
in case insensitive way, for all operating systems first, and when it cannot
find it, looks for proxy information from Mac OSX System Configuration for
Mac OS X and Windows Systems Registry for Windows.
If both lowercase and uppercase environment variables exist (and disagree),
lowercase is preferred.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the environment variable <code class="docutils literal notranslate"><span class="pre">REQUEST_METHOD</span></code> is set, which usually
indicates your script is running in a CGI environment, the environment
variable <code class="docutils literal notranslate"><span class="pre">HTTP_PROXY</span></code> (uppercase <code class="docutils literal notranslate"><span class="pre">_PROXY</span></code>) will be ignored. This is
because that variable can be injected by a client using the “Proxy:” HTTP
header. If you need to use an HTTP proxy in a CGI environment, either use
<code class="docutils literal notranslate"><span class="pre">ProxyHandler</span></code> explicitly, or make sure the variable name is in
lowercase (or at least the <code class="docutils literal notranslate"><span class="pre">_proxy</span></code> suffix).</p>
</div>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">urllib also exposes certain utility functions like splittype, splithost and
others parsing URL into various components. But it is recommended to use
<a class="reference internal" href="urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> for parsing URLs rather than using these functions directly.
Python 3 does not expose these helper functions from <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.parse</span></code>
module.</p>
</div>
</div>
<div class="section" id="url-opener-objects">
<h2>20.5.3. URL Opener objects<a class="headerlink" href="#url-opener-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="urllib.URLopener">
<em class="property">class </em><code class="descclassname">urllib.</code><code class="descname">URLopener</code><span class="sig-paren">(</span><span class="optional">[</span><em>proxies</em><span class="optional">[</span>, <em>context</em><span class="optional">[</span>, <em>**x509</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.URLopener" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for opening and reading URLs.  Unless you need to support opening
objects using schemes other than <code class="file docutils literal notranslate"><span class="pre">http:</span></code>, <code class="file docutils literal notranslate"><span class="pre">ftp:</span></code>, or <code class="file docutils literal notranslate"><span class="pre">file:</span></code>,
you probably want to use <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a>.</p>
<p>By default, the <a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> class sends a <em class="mailheader">User-Agent</em> header
of <code class="docutils literal notranslate"><span class="pre">urllib/VVV</span></code>, where <em>VVV</em> is the <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> version number.
Applications can define their own <em class="mailheader">User-Agent</em> header by subclassing
<a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> or <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a> and setting the class attribute
<a class="reference internal" href="#urllib.URLopener.version" title="urllib.URLopener.version"><code class="xref py py-attr docutils literal notranslate"><span class="pre">version</span></code></a> to an appropriate string value in the subclass definition.</p>
<p>The optional <em>proxies</em> parameter should be a dictionary mapping scheme names to
proxy URLs, where an empty dictionary turns proxies off completely.  Its default
value is <code class="docutils literal notranslate"><span class="pre">None</span></code>, in which case environmental proxy settings will be used if
present, as discussed in the definition of <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>, above.</p>
<p>The <em>context</em> parameter may be a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> instance.  If given,
it defines the SSL settings the opener uses to make HTTPS connections.</p>
<p>Additional keyword parameters, collected in <em>x509</em>, may be used for
authentication of the client when using the <code class="file docutils literal notranslate"><span class="pre">https:</span></code> scheme.  The keywords
<em>key_file</em> and <em>cert_file</em> are supported to provide an  SSL key and certificate;
both are needed to support client authentication.</p>
<p><a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> objects will raise an <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception if the server
returns an error code.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>The <em>context</em> parameter was added.  All the neccessary certificate and hostname
checks are done by default.</p>
</div>
<dl class="method">
<dt id="urllib.URLopener.open">
<code class="descname">open</code><span class="sig-paren">(</span><em>fullurl</em><span class="optional">[</span>, <em>data</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.URLopener.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>fullurl</em> using the appropriate protocol.  This method sets up cache and
proxy information, then calls the appropriate open method with its input
arguments.  If the scheme is not recognized, <a class="reference internal" href="#urllib.URLopener.open_unknown" title="urllib.URLopener.open_unknown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open_unknown()</span></code></a> is called.
The <em>data</em> argument has the same meaning as the <em>data</em> argument of
<a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib.URLopener.open_unknown">
<code class="descname">open_unknown</code><span class="sig-paren">(</span><em>fullurl</em><span class="optional">[</span>, <em>data</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.URLopener.open_unknown" title="Permalink to this definition">¶</a></dt>
<dd><p>Overridable interface to open unknown URL types.</p>
</dd></dl>

<dl class="method">
<dt id="urllib.URLopener.retrieve">
<code class="descname">retrieve</code><span class="sig-paren">(</span><em>url</em><span class="optional">[</span>, <em>filename</em><span class="optional">[</span>, <em>reporthook</em><span class="optional">[</span>, <em>data</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.URLopener.retrieve" title="Permalink to this definition">¶</a></dt>
<dd><p>Retrieves the contents of <em>url</em> and places it in <em>filename</em>.  The return value
is a tuple consisting of a local filename and either a
<a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a> object containing the response headers (for remote
URLs) or <code class="docutils literal notranslate"><span class="pre">None</span></code> (for local URLs).  The caller must then open and read the
contents of <em>filename</em>.  If <em>filename</em> is not given and the URL refers to a
local file, the input filename is returned.  If the URL is non-local and
<em>filename</em> is not given, the filename is the output of <a class="reference internal" href="tempfile.html#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">tempfile.mktemp()</span></code></a>
with a suffix that matches the suffix of the last path component of the input
URL.  If <em>reporthook</em> is given, it must be a function accepting three numeric
parameters.  It will be called after each chunk of data is read from the
network.  <em>reporthook</em> is ignored for local URLs.</p>
<p>If the <em>url</em> uses the <code class="file docutils literal notranslate"><span class="pre">http:</span></code> scheme identifier, the optional <em>data</em>
argument may be given to specify a <code class="docutils literal notranslate"><span class="pre">POST</span></code> request (normally the request type
is <code class="docutils literal notranslate"><span class="pre">GET</span></code>).  The <em>data</em> argument must in standard
<em class="mimetype">application/x-www-form-urlencoded</em> format; see the <a class="reference internal" href="#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlencode()</span></code></a>
function below.</p>
</dd></dl>

<dl class="attribute">
<dt id="urllib.URLopener.version">
<code class="descname">version</code><a class="headerlink" href="#urllib.URLopener.version" title="Permalink to this definition">¶</a></dt>
<dd><p>Variable that specifies the user agent of the opener object.  To get
<a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> to tell servers that it is a particular user agent, set this in a
subclass as a class variable or in the constructor before calling the base
constructor.</p>
</dd></dl>

</dd></dl>

<dl class="class">
<dt id="urllib.FancyURLopener">
<em class="property">class </em><code class="descclassname">urllib.</code><code class="descname">FancyURLopener</code><span class="sig-paren">(</span><em>...</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.FancyURLopener" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a> subclasses <a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a> providing default handling
for the following HTTP response codes: 301, 302, 303, 307 and 401.  For the 30x
response codes listed above, the <em class="mailheader">Location</em> header is used to fetch
the actual URL.  For 401 response codes (authentication required), basic HTTP
authentication is performed.  For the 30x response codes, recursion is bounded
by the value of the <em>maxtries</em> attribute, which defaults to 10.</p>
<p>For all other response codes, the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_default()</span></code> is called
which you can override in subclasses to handle the error appropriately.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">According to the letter of <span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>, 301 and 302 responses to POST requests
must not be automatically redirected without confirmation by the user.  In
reality, browsers do allow automatic redirection of these responses, changing
the POST to a GET, and <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> reproduces this behaviour.</p>
</div>
<p>The parameters to the constructor are the same as those for <a class="reference internal" href="#urllib.URLopener" title="urllib.URLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">URLopener</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When performing basic authentication, a <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a> instance calls
its <a class="reference internal" href="#urllib.FancyURLopener.prompt_user_passwd" title="urllib.FancyURLopener.prompt_user_passwd"><code class="xref py py-meth docutils literal notranslate"><span class="pre">prompt_user_passwd()</span></code></a> method.  The default implementation asks the
users for the required information on the controlling terminal.  A subclass may
override this method to support more appropriate behavior if needed.</p>
</div>
<p>The <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a> class offers one additional method that should be
overloaded to provide the appropriate behavior:</p>
<dl class="method">
<dt id="urllib.FancyURLopener.prompt_user_passwd">
<code class="descname">prompt_user_passwd</code><span class="sig-paren">(</span><em>host</em>, <em>realm</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib.FancyURLopener.prompt_user_passwd" title="Permalink to this definition">¶</a></dt>
<dd><p>Return information needed to authenticate the user at the given host in the
specified security realm.  The return value should be a tuple, <code class="docutils literal notranslate"><span class="pre">(user,</span>
<span class="pre">password)</span></code>, which can be used for basic authentication.</p>
<p>The implementation prompts for this information on the terminal; an application
should override this method to use an appropriate interaction model in the local
environment.</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="urllib.ContentTooShortError">
<em class="property">exception </em><code class="descclassname">urllib.</code><code class="descname">ContentTooShortError</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>content</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib.ContentTooShortError" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when the <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> function detects that the
amount of the downloaded data is less than the  expected amount (given by the
<em>Content-Length</em> header). The <code class="xref py py-attr docutils literal notranslate"><span class="pre">content</span></code> attribute stores the downloaded
(and supposedly truncated) data.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

</div>
<div class="section" id="urllib-restrictions">
<h2>20.5.4. <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> Restrictions<a class="headerlink" href="#urllib-restrictions" title="Permalink to this headline">¶</a></h2>
<blockquote>
<div></div></blockquote>
<ul id="index-8">
<li><p class="first">Currently, only the following protocols are supported: HTTP, (versions 0.9 and
1.0),  FTP, and local files.</p>
</li>
<li><p class="first">The caching feature of <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> has been disabled until I find the
time to hack proper processing of Expiration time headers.</p>
</li>
<li><p class="first">There should be a function to query whether a particular URL is in the cache.</p>
</li>
<li><p class="first">For backward compatibility, if a URL appears to point to a local file but the
file can’t be opened, the URL is re-interpreted using the FTP protocol.  This
can sometimes cause confusing error messages.</p>
</li>
<li><p class="first">The <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> and <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> functions can cause arbitrarily
long delays while waiting for a network connection to be set up.  This means
that it is difficult to build an interactive Web client using these functions
without using threads.</p>
</li>
<li id="index-9"><p class="first">The data returned by <a class="reference internal" href="#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> or <a class="reference internal" href="#urllib.urlretrieve" title="urllib.urlretrieve"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlretrieve()</span></code></a> is the raw data
returned by the server.  This may be binary data (such as an image), plain text
or (for example) HTML.  The HTTP protocol provides type information in the reply
header, which can be inspected by looking at the <em class="mailheader">Content-Type</em>
header.  If the returned data is HTML, you can use the module <a class="reference internal" href="htmllib.html#module-htmllib" title="htmllib: A parser for HTML documents. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">htmllib</span></code></a> to
parse it.</p>
</li>
<li id="index-10"><p class="first">The code handling the FTP protocol cannot differentiate between a file and a
directory.  This can lead to unexpected behavior when attempting to read a URL
that points to a file that is not accessible.  If the URL ends in a <code class="docutils literal notranslate"><span class="pre">/</span></code>, it is
assumed to refer to a directory and will be handled accordingly.  But if an
attempt to read a file leads to a 550 error (meaning the URL cannot be found or
is not accessible, often for permission reasons), then the path is treated as a
directory in order to handle the case when a directory is specified by a URL but
the trailing <code class="docutils literal notranslate"><span class="pre">/</span></code> has been left off.  This can cause misleading results when
you try to fetch a file whose read permissions make it inaccessible; the FTP
code will try to read it, fail with a 550 error, and then perform a directory
listing for the unreadable file. If fine-grained control is needed, consider
using the <a class="reference internal" href="ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> module, subclassing <a class="reference internal" href="#urllib.FancyURLopener" title="urllib.FancyURLopener"><code class="xref py py-class docutils literal notranslate"><span class="pre">FancyURLopener</span></code></a>, or changing
<em>_urlopener</em> to meet your needs.</p>
</li>
<li><p class="first">This module does not support the use of proxies which require authentication.
This may be implemented in the future.</p>
</li>
<li id="index-11"><p class="first">Although the <a class="reference internal" href="#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> module contains (undocumented) routines to parse
and unparse URL strings, the recommended interface for URL manipulation is in
module <a class="reference internal" href="urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a>.</p>
</li>
</ul>
</div>
<div class="section" id="examples">
<span id="urllib-examples"></span><h2>20.5.5. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Here is an example session that uses the <code class="docutils literal notranslate"><span class="pre">GET</span></code> method to retrieve a URL
containing parameters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">params</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">&#39;spam&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">:</span> <span class="mi">0</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;http://www.musi-cal.com/cgi-bin/query?</span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">params</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>The following example uses the <code class="docutils literal notranslate"><span class="pre">POST</span></code> method instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">params</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlencode</span><span class="p">({</span><span class="s1">&#39;spam&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;bacon&#39;</span><span class="p">:</span> <span class="mi">0</span><span class="p">})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;http://www.musi-cal.com/cgi-bin/query&quot;</span><span class="p">,</span> <span class="n">params</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>The following example uses an explicitly specified HTTP proxy, overriding
environment settings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">proxies</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;http&#39;</span><span class="p">:</span> <span class="s1">&#39;http://proxy.example.com:8080/&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">FancyURLopener</span><span class="p">(</span><span class="n">proxies</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;http://www.python.org&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
<p>The following example uses no proxies at all, overriding environment settings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">opener</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">FancyURLopener</span><span class="p">({})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;http://www.python.org/&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a><ul>
<li><a class="reference internal" href="#high-level-interface">20.5.1. High-level interface</a></li>
<li><a class="reference internal" href="#utility-functions">20.5.2. Utility functions</a></li>
<li><a class="reference internal" href="#url-opener-objects">20.5.3. URL Opener objects</a></li>
<li><a class="reference internal" href="#urllib-restrictions">20.5.4. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> Restrictions</a></li>
<li><a class="reference internal" href="#examples">20.5.5. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="wsgiref.html"
                        title="previous chapter">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="urllib2.html"
                        title="next chapter">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/urllib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib2.html" title="20.6. urllib2 — extensible library for opening URLs"
             >next</a> |</li>
        <li class="right" >
          <a href="wsgiref.html" title="20.4. wsgiref — WSGI Utilities and Reference Implementation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����html/library/urllib2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.6. urllib2 — extensible library for opening URLs &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.7. httplib — HTTP protocol client" href="httplib.html" />
    <link rel="prev" title="20.5. urllib — Open arbitrary resources by URL" href="urllib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/urllib2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="httplib.html" title="20.7. httplib — HTTP protocol client"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="urllib.html" title="20.5. urllib — Open arbitrary resources by URL"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-urllib2">
<span id="urllib2-extensible-library-for-opening-urls"></span><h1>20.6. <a class="reference internal" href="#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> — extensible library for opening URLs<a class="headerlink" href="#module-urllib2" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> module has been split across several modules in
Python 3 named <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.error</span></code>.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<p>The <a class="reference internal" href="#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> module defines functions and classes which help in opening
URLs (mostly HTTP) in a complex world — basic and digest authentication,
redirections, cookies and more.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The <a class="reference external" href="http://requests.readthedocs.org/">Requests package</a>
is recommended for a higher-level HTTP client interface.</p>
</div>
<p>The <a class="reference internal" href="#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="urllib2.urlopen">
<code class="descclassname">urllib2.</code><code class="descname">urlopen</code><span class="sig-paren">(</span><em>url[, data[, timeout[, cafile[, capath[, cadefault[, context]]]]]</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.urlopen" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the URL <em>url</em>, which can be either a string or a <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object.</p>
<p><em>data</em> may be a string specifying additional data to send to the server, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if no such data is needed.  Currently HTTP requests are the only ones
that use <em>data</em>; the HTTP request will be a POST instead of a GET when the
<em>data</em> parameter is provided.  <em>data</em> should be a buffer in the standard
<em class="mimetype">application/x-www-form-urlencoded</em> format.  The
<a class="reference internal" href="urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a> function takes a mapping or sequence of 2-tuples and
returns a string in this format. urllib2 module sends HTTP/1.1 requests with
<code class="docutils literal notranslate"><span class="pre">Connection:close</span></code> header included.</p>
<p>The optional <em>timeout</em> parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
timeout setting will be used).  This actually only works for HTTP, HTTPS and
FTP connections.</p>
<p>If <em>context</em> is specified, it must be a <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> instance
describing the various SSL options. See <a class="reference internal" href="httplib.html#httplib.HTTPSConnection" title="httplib.HTTPSConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSConnection</span></code></a> for
more details.</p>
<p>The optional <em>cafile</em> and <em>capath</em> parameters specify a set of trusted CA
certificates for HTTPS requests.  <em>cafile</em> should point to a single file
containing a bundle of CA certificates, whereas <em>capath</em> should point to a
directory of hashed certificate files.  More information can be found in
<a class="reference internal" href="ssl.html#ssl.SSLContext.load_verify_locations" title="ssl.SSLContext.load_verify_locations"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ssl.SSLContext.load_verify_locations()</span></code></a>.</p>
<p>The <em>cadefault</em> parameter is ignored.</p>
<p>This function returns a file-like object with three additional methods:</p>
<ul class="simple">
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">geturl()</span></code> — return the URL of the resource retrieved, commonly used to
determine if a redirect was followed</li>
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">info()</span></code> — return the meta-information of the page, such as headers,
in the form of an <a class="reference internal" href="mimetools.html#mimetools.Message" title="mimetools.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">mimetools.Message</span></code></a> instance
(see <a class="reference external" href="https://www.cs.tut.fi/~jkorpela/http.html">Quick Reference to HTTP Headers</a>)</li>
<li><code class="xref py py-meth docutils literal notranslate"><span class="pre">getcode()</span></code> — return the HTTP status code of the response.</li>
</ul>
<p>Raises <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a> on errors.</p>
<p>Note that <code class="docutils literal notranslate"><span class="pre">None</span></code> may be returned if no handler handles the request (though the
default installed global <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> uses <a class="reference internal" href="#urllib2.UnknownHandler" title="urllib2.UnknownHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnknownHandler</span></code></a> to
ensure this never happens).</p>
<p>In addition, if proxy settings are detected (for example, when a <code class="docutils literal notranslate"><span class="pre">*_proxy</span></code>
environment variable like <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">http_proxy</span></code> is set),
<a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a> is default installed and makes sure the requests are
handled through the proxy.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span><em>cafile</em>, <em>capath</em>, <em>cadefault</em>, and <em>context</em> were added.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urllib2.install_opener">
<code class="descclassname">urllib2.</code><code class="descname">install_opener</code><span class="sig-paren">(</span><em>opener</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.install_opener" title="Permalink to this definition">¶</a></dt>
<dd><p>Install an <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> instance as the default global opener.
Installing an opener is only necessary if you want urlopen to use that opener;
otherwise, simply call <a class="reference internal" href="#urllib2.OpenerDirector.open" title="urllib2.OpenerDirector.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OpenerDirector.open()</span></code></a> instead of <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.
The code does not check for a real <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>, and any class with
the appropriate interface will work.</p>
</dd></dl>

<dl class="function">
<dt id="urllib2.build_opener">
<code class="descclassname">urllib2.</code><code class="descname">build_opener</code><span class="sig-paren">(</span><span class="optional">[</span><em>handler</em>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.build_opener" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> instance, which chains the handlers in the
order given. <em>handler</em>s can be either instances of <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, or
subclasses of <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> (in which case it must be possible to call
the constructor without any parameters).  Instances of the following classes
will be in front of the <em>handler</em>s, unless the <em>handler</em>s contain them,
instances of them or subclasses of them: <a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a> (if proxy
settings are detected),
<a class="reference internal" href="#urllib2.UnknownHandler" title="urllib2.UnknownHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">UnknownHandler</span></code></a>, <a class="reference internal" href="#urllib2.HTTPHandler" title="urllib2.HTTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPHandler</span></code></a>, <a class="reference internal" href="#urllib2.HTTPDefaultErrorHandler" title="urllib2.HTTPDefaultErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPDefaultErrorHandler</span></code></a>,
<a class="reference internal" href="#urllib2.HTTPRedirectHandler" title="urllib2.HTTPRedirectHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPRedirectHandler</span></code></a>, <a class="reference internal" href="#urllib2.FTPHandler" title="urllib2.FTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTPHandler</span></code></a>, <a class="reference internal" href="#urllib2.FileHandler" title="urllib2.FileHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code></a>,
<a class="reference internal" href="#urllib2.HTTPErrorProcessor" title="urllib2.HTTPErrorProcessor"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPErrorProcessor</span></code></a>.</p>
<p>If the Python installation has SSL support (i.e., if the <a class="reference internal" href="ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module can be imported),
<a class="reference internal" href="#urllib2.HTTPSHandler" title="urllib2.HTTPSHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSHandler</span></code></a> will also be added.</p>
<p>Beginning in Python 2.3, a <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> subclass may also change its
<code class="xref py py-attr docutils literal notranslate"><span class="pre">handler_order</span></code> attribute to modify its position in the handlers
list.</p>
</dd></dl>

<p>The following exceptions are raised as appropriate:</p>
<dl class="exception">
<dt id="urllib2.URLError">
<em class="property">exception </em><code class="descclassname">urllib2.</code><code class="descname">URLError</code><a class="headerlink" href="#urllib2.URLError" title="Permalink to this definition">¶</a></dt>
<dd><p>The handlers raise this exception (or derived exceptions) when they run into a
problem.  It is a subclass of <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.</p>
<dl class="attribute">
<dt id="urllib2.URLError.reason">
<code class="descname">reason</code><a class="headerlink" href="#urllib2.URLError.reason" title="Permalink to this definition">¶</a></dt>
<dd><p>The reason for this error.  It can be a message string or another exception
instance (<a class="reference internal" href="socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> for remote URLs, <a class="reference internal" href="exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> for local
URLs).</p>
</dd></dl>

</dd></dl>

<dl class="exception">
<dt id="urllib2.HTTPError">
<em class="property">exception </em><code class="descclassname">urllib2.</code><code class="descname">HTTPError</code><a class="headerlink" href="#urllib2.HTTPError" title="Permalink to this definition">¶</a></dt>
<dd><p>Though being an exception (a subclass of <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a>), an <a class="reference internal" href="#urllib2.HTTPError" title="urllib2.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a>
can also function as a non-exceptional file-like return value (the same thing
that <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> returns).  This is useful when handling exotic HTTP
errors, such as requests for authentication.</p>
<dl class="attribute">
<dt id="urllib2.HTTPError.code">
<code class="descname">code</code><a class="headerlink" href="#urllib2.HTTPError.code" title="Permalink to this definition">¶</a></dt>
<dd><p>An HTTP status code as defined in <a class="reference external" href="http://www.faqs.org/rfcs/rfc2616.html">RFC 2616</a>.
This numeric value corresponds to a value found in the dictionary of
codes as found in <a class="reference internal" href="basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.responses" title="BaseHTTPServer.BaseHTTPRequestHandler.responses"><code class="xref py py-attr docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler.responses</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="urllib2.HTTPError.reason">
<code class="descname">reason</code><a class="headerlink" href="#urllib2.HTTPError.reason" title="Permalink to this definition">¶</a></dt>
<dd><p>The reason for this error.  It can be a message string or another exception
instance.</p>
</dd></dl>

</dd></dl>

<p>The following classes are provided:</p>
<dl class="class">
<dt id="urllib2.Request">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">Request</code><span class="sig-paren">(</span><em>url[, data][, headers][, origin_req_host][, unverifiable]</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is an abstraction of a URL request.</p>
<p><em>url</em> should be a string containing a valid URL.</p>
<p><em>data</em> may be a string specifying additional data to send to the server, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if no such data is needed.  Currently HTTP requests are the only ones
that use <em>data</em>; the HTTP request will be a POST instead of a GET when the
<em>data</em> parameter is provided.  <em>data</em> should be a buffer in the standard
<em class="mimetype">application/x-www-form-urlencoded</em> format.  The
<a class="reference internal" href="urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a> function takes a mapping or sequence of 2-tuples and
returns a string in this format.</p>
<p><em>headers</em> should be a dictionary, and will be treated as if <a class="reference internal" href="#urllib2.Request.add_header" title="urllib2.Request.add_header"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_header()</span></code></a>
was called with each key and value as arguments.  This is often used to “spoof”
the <code class="docutils literal notranslate"><span class="pre">User-Agent</span></code> header value, which is used by a browser to identify itself –
some HTTP servers only allow requests coming from common browsers as opposed
to scripts.  For example, Mozilla Firefox may identify itself as <code class="docutils literal notranslate"><span class="pre">&quot;Mozilla/5.0</span>
<span class="pre">(X11;</span> <span class="pre">U;</span> <span class="pre">Linux</span> <span class="pre">i686)</span> <span class="pre">Gecko/20071127</span> <span class="pre">Firefox/2.0.0.11&quot;</span></code>, while <a class="reference internal" href="#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a>’s
default user agent string is <code class="docutils literal notranslate"><span class="pre">&quot;Python-urllib/2.6&quot;</span></code> (on Python 2.6).</p>
<p>The final two arguments are only of interest for correct handling of third-party
HTTP cookies:</p>
<p><em>origin_req_host</em> should be the request-host of the origin transaction, as
defined by <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2965.html"><strong>RFC 2965</strong></a>.  It defaults to <code class="docutils literal notranslate"><span class="pre">cookielib.request_host(self)</span></code>.  This
is the host name or IP address of the original request that was initiated by the
user.  For example, if the request is for an image in an HTML document, this
should be the request-host of the request for the page containing the image.</p>
<p><em>unverifiable</em> should indicate whether the request is unverifiable, as defined
by RFC 2965.  It defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>.  An unverifiable request is one whose URL
the user did not have the option to approve.  For example, if the request is for
an image in an HTML document, and the user had no option to approve the
automatic fetching of the image, this should be true.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.OpenerDirector">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">OpenerDirector</code><a class="headerlink" href="#urllib2.OpenerDirector" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> class opens URLs via <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>s chained
together. It manages the chaining of handlers, and recovery from errors.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.BaseHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">BaseHandler</code><a class="headerlink" href="#urllib2.BaseHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the base class for all registered handlers — and handles only the
simple mechanics of registration.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPDefaultErrorHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPDefaultErrorHandler</code><a class="headerlink" href="#urllib2.HTTPDefaultErrorHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>A class which defines a default handler for HTTP error responses; all responses
are turned into <a class="reference internal" href="#urllib2.HTTPError" title="urllib2.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> exceptions.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPRedirectHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPRedirectHandler</code><a class="headerlink" href="#urllib2.HTTPRedirectHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>A class to handle redirections.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPCookieProcessor">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPCookieProcessor</code><span class="sig-paren">(</span><span class="optional">[</span><em>cookiejar</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPCookieProcessor" title="Permalink to this definition">¶</a></dt>
<dd><p>A class to handle HTTP Cookies.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.ProxyHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">ProxyHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>proxies</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.ProxyHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Cause requests to go through a proxy. If <em>proxies</em> is given, it must be a
dictionary mapping protocol names to URLs of proxies. The default is to read
the list of proxies from the environment variables
<span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">&lt;protocol&gt;_proxy</span></code>.  If no proxy environment variables are set, then
in a Windows environment proxy settings are obtained from the registry’s
Internet Settings section, and in a Mac OS X environment proxy information
is retrieved from the OS X System Configuration Framework.</p>
<p>To disable autodetected proxy pass an empty dictionary.</p>
<blockquote>
<div><div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">HTTP_PROXY</span></code> will be ignored if a variable <code class="docutils literal notranslate"><span class="pre">REQUEST_METHOD</span></code> is set;
see the documentation on <a class="reference internal" href="urllib.html#urllib.getproxies" title="urllib.getproxies"><code class="xref py py-func docutils literal notranslate"><span class="pre">getproxies()</span></code></a>.</p>
</div>
</div></blockquote>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPPasswordMgr">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPPasswordMgr</code><a class="headerlink" href="#urllib2.HTTPPasswordMgr" title="Permalink to this definition">¶</a></dt>
<dd><p>Keep a database of  <code class="docutils literal notranslate"><span class="pre">(realm,</span> <span class="pre">uri)</span> <span class="pre">-&gt;</span> <span class="pre">(user,</span> <span class="pre">password)</span></code> mappings.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPPasswordMgrWithDefaultRealm">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPPasswordMgrWithDefaultRealm</code><a class="headerlink" href="#urllib2.HTTPPasswordMgrWithDefaultRealm" title="Permalink to this definition">¶</a></dt>
<dd><p>Keep a database of  <code class="docutils literal notranslate"><span class="pre">(realm,</span> <span class="pre">uri)</span> <span class="pre">-&gt;</span> <span class="pre">(user,</span> <span class="pre">password)</span></code> mappings. A realm of
<code class="docutils literal notranslate"><span class="pre">None</span></code> is considered a catch-all realm, which is searched if no other realm
fits.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.AbstractBasicAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">AbstractBasicAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.AbstractBasicAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a mixin class that helps with HTTP authentication, both to the remote
host and to a proxy. <em>password_mgr</em>, if given, should be something that is
compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPBasicAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPBasicAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPBasicAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle authentication with the remote host. <em>password_mgr</em>, if given, should be
something that is compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.ProxyBasicAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">ProxyBasicAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.ProxyBasicAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle authentication with the proxy. <em>password_mgr</em>, if given, should be
something that is compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.AbstractDigestAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">AbstractDigestAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.AbstractDigestAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a mixin class that helps with HTTP authentication, both to the remote
host and to a proxy. <em>password_mgr</em>, if given, should be something that is
compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPDigestAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPDigestAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPDigestAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle authentication with the remote host. <em>password_mgr</em>, if given, should be
something that is compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.ProxyDigestAuthHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">ProxyDigestAuthHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>password_mgr</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.ProxyDigestAuthHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle authentication with the proxy. <em>password_mgr</em>, if given, should be
something that is compatible with <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a>; refer to section
<a class="reference internal" href="#http-password-mgr"><span class="std std-ref">HTTPPasswordMgr Objects</span></a> for information on the interface that must be
supported.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPHandler</code><a class="headerlink" href="#urllib2.HTTPHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>A class to handle opening of HTTP URLs.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPSHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPSHandler</code><span class="sig-paren">(</span><span class="optional">[</span><em>debuglevel</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPSHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>A class to handle opening of HTTPS URLs. <em>context</em> has the same meaning as
for <a class="reference internal" href="httplib.html#httplib.HTTPSConnection" title="httplib.HTTPSConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">httplib.HTTPSConnection</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span><em>context</em> added.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="urllib2.FileHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">FileHandler</code><a class="headerlink" href="#urllib2.FileHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Open local files.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.FTPHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">FTPHandler</code><a class="headerlink" href="#urllib2.FTPHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Open FTP URLs.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.CacheFTPHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">CacheFTPHandler</code><a class="headerlink" href="#urllib2.CacheFTPHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Open FTP URLs, keeping a cache of open FTP connections to minimize delays.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.UnknownHandler">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">UnknownHandler</code><a class="headerlink" href="#urllib2.UnknownHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>A catch-all class to handle unknown URLs.</p>
</dd></dl>

<dl class="class">
<dt id="urllib2.HTTPErrorProcessor">
<em class="property">class </em><code class="descclassname">urllib2.</code><code class="descname">HTTPErrorProcessor</code><a class="headerlink" href="#urllib2.HTTPErrorProcessor" title="Permalink to this definition">¶</a></dt>
<dd><p>Process HTTP error responses.</p>
</dd></dl>

<div class="section" id="request-objects">
<span id="id1"></span><h2>20.6.1. Request Objects<a class="headerlink" href="#request-objects" title="Permalink to this headline">¶</a></h2>
<p>The following methods describe all of <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a>’s public interface, and
so all must be overridden in subclasses.</p>
<dl class="method">
<dt id="urllib2.Request.add_data">
<code class="descclassname">Request.</code><code class="descname">add_data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.add_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> data to <em>data</em>.  This is ignored by all handlers except
HTTP handlers — and there it should be a byte string, and will change the
request to be <code class="docutils literal notranslate"><span class="pre">POST</span></code> rather than <code class="docutils literal notranslate"><span class="pre">GET</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_method">
<code class="descclassname">Request.</code><code class="descname">get_method</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_method" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a string indicating the HTTP request method.  This is only meaningful for
HTTP requests, and currently always returns <code class="docutils literal notranslate"><span class="pre">'GET'</span></code> or <code class="docutils literal notranslate"><span class="pre">'POST'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.has_data">
<code class="descclassname">Request.</code><code class="descname">has_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.has_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the instance has a non-<code class="docutils literal notranslate"><span class="pre">None</span></code> data.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_data">
<code class="descclassname">Request.</code><code class="descname">get_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the instance’s data.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.add_header">
<code class="descclassname">Request.</code><code class="descname">add_header</code><span class="sig-paren">(</span><em>key</em>, <em>val</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.add_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Add another header to the request.  Headers are currently ignored by all
handlers except HTTP handlers, where they are added to the list of headers sent
to the server.  Note that there cannot be more than one header with the same
name, and later calls will overwrite previous calls in case the <em>key</em> collides.
Currently, this is no loss of HTTP functionality, since all headers which have
meaning when used more than once have a (header-specific) way of gaining the
same functionality using only one header.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.add_unredirected_header">
<code class="descclassname">Request.</code><code class="descname">add_unredirected_header</code><span class="sig-paren">(</span><em>key</em>, <em>header</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.add_unredirected_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a header that will not be added to a redirected request.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.has_header">
<code class="descclassname">Request.</code><code class="descname">has_header</code><span class="sig-paren">(</span><em>header</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.has_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the instance has the named header (checks both regular and
unredirected).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_full_url">
<code class="descclassname">Request.</code><code class="descname">get_full_url</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_full_url" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the URL given in the constructor.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_type">
<code class="descclassname">Request.</code><code class="descname">get_type</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the type of the URL — also known as the scheme.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_host">
<code class="descclassname">Request.</code><code class="descname">get_host</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_host" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the host to which a connection will be made.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_selector">
<code class="descclassname">Request.</code><code class="descname">get_selector</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_selector" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the selector — the part of the URL that is sent to the server.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_header">
<code class="descclassname">Request.</code><code class="descname">get_header</code><span class="sig-paren">(</span><em>header_name</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the given header. If the header is not present, return
the default value.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.header_items">
<code class="descclassname">Request.</code><code class="descname">header_items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.header_items" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of tuples (header_name, header_value) of the Request headers.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.set_proxy">
<code class="descclassname">Request.</code><code class="descname">set_proxy</code><span class="sig-paren">(</span><em>host</em>, <em>type</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.set_proxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Prepare the request by connecting to a proxy server. The <em>host</em> and <em>type</em> will
replace those of the instance, and the instance’s selector will be the original
URL given in the constructor.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.get_origin_req_host">
<code class="descclassname">Request.</code><code class="descname">get_origin_req_host</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.get_origin_req_host" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the request-host of the origin transaction, as defined by <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2965.html"><strong>RFC 2965</strong></a>.
See the documentation for the <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> constructor.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.Request.is_unverifiable">
<code class="descclassname">Request.</code><code class="descname">is_unverifiable</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.Request.is_unverifiable" title="Permalink to this definition">¶</a></dt>
<dd><p>Return whether the request is unverifiable, as defined by RFC 2965. See the
documentation for the <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> constructor.</p>
</dd></dl>

</div>
<div class="section" id="openerdirector-objects">
<span id="opener-director-objects"></span><h2>20.6.2. OpenerDirector Objects<a class="headerlink" href="#openerdirector-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="urllib2.OpenerDirector.add_handler">
<code class="descclassname">OpenerDirector.</code><code class="descname">add_handler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.OpenerDirector.add_handler" title="Permalink to this definition">¶</a></dt>
<dd><p><em>handler</em> should be an instance of <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>.  The following
methods are searched, and added to the possible chains (note that HTTP errors
are a special case).</p>
<ul class="simple">
<li><code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_open</span></code> — signal that the handler knows how to open
<em>protocol</em> URLs.</li>
<li><code class="samp docutils literal notranslate"><span class="pre">http_error_</span><em><span class="pre">type</span></em></code> — signal that the handler knows how to handle
HTTP errors with HTTP error code <em>type</em>.</li>
<li><code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_error</span></code> — signal that the handler knows how to handle
errors from (non-<code class="docutils literal notranslate"><span class="pre">http</span></code>) <em>protocol</em>.</li>
<li><code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_request</span></code> — signal that the handler knows how to
pre-process <em>protocol</em> requests.</li>
<li><code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_response</span></code> — signal that the handler knows how to
post-process <em>protocol</em> responses.</li>
</ul>
</dd></dl>

<dl class="method">
<dt id="urllib2.OpenerDirector.open">
<code class="descclassname">OpenerDirector.</code><code class="descname">open</code><span class="sig-paren">(</span><em>url[, data][, timeout]</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.OpenerDirector.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the given <em>url</em> (which can be a request object or a string), optionally
passing the given <em>data</em>. Arguments, return values and exceptions raised are
the same as those of <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> (which simply calls the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a>
method on the currently installed global <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>).  The
optional <em>timeout</em> parameter specifies a timeout in seconds for blocking
operations like the connection attempt (if not specified, the global default
timeout setting will be used). The timeout feature actually works only for
HTTP, HTTPS and FTP connections).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>timeout</em> was added.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="urllib2.OpenerDirector.error">
<code class="descclassname">OpenerDirector.</code><code class="descname">error</code><span class="sig-paren">(</span><em>proto</em><span class="optional">[</span>, <em>arg</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.OpenerDirector.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle an error of the given protocol.  This will call the registered error
handlers for the given protocol with the given arguments (which are protocol
specific).  The HTTP protocol is a special case which uses the HTTP response
code to determine the specific error handler; refer to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_*()</span></code>
methods of the handler classes.</p>
<p>Return values and exceptions raised are the same as those of <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.</p>
</dd></dl>

<p>OpenerDirector objects open URLs in three stages:</p>
<p>The order in which these methods are called within each stage is determined by
sorting the handler instances.</p>
<ol class="arabic">
<li><p class="first">Every handler with a method named like <code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_request</span></code> has that
method called to pre-process the request.</p>
</li>
<li><p class="first">Handlers with a method named like <code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_open</span></code> are called to handle
the request. This stage ends when a handler either returns a non-<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>
value (ie. a response), or raises an exception (usually <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a>).
Exceptions are allowed to propagate.</p>
<p>In fact, the above algorithm is first tried for methods named
<code class="xref py py-meth docutils literal notranslate"><span class="pre">default_open()</span></code>.  If all such methods return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the
algorithm is repeated for methods named like <code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_open</span></code>.  If all
such methods return <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, the algorithm is repeated for methods
named <code class="xref py py-meth docutils literal notranslate"><span class="pre">unknown_open()</span></code>.</p>
<p>Note that the implementation of these methods may involve calls of the parent
<a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> instance’s <a class="reference internal" href="#urllib2.OpenerDirector.open" title="urllib2.OpenerDirector.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> and
<a class="reference internal" href="#urllib2.OpenerDirector.error" title="urllib2.OpenerDirector.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">error()</span></code></a> methods.</p>
</li>
<li><p class="first">Every handler with a method named like <code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_response</span></code> has that
method called to post-process the response.</p>
</li>
</ol>
</div>
<div class="section" id="basehandler-objects">
<span id="base-handler-objects"></span><h2>20.6.3. BaseHandler Objects<a class="headerlink" href="#basehandler-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> objects provide a couple of methods that are directly
useful, and others that are meant to be used by derived classes.  These are
intended for direct use:</p>
<dl class="method">
<dt id="urllib2.BaseHandler.add_parent">
<code class="descclassname">BaseHandler.</code><code class="descname">add_parent</code><span class="sig-paren">(</span><em>director</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.add_parent" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a director as parent.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.BaseHandler.close">
<code class="descclassname">BaseHandler.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove any parents.</p>
</dd></dl>

<p>The following attributes and methods should only be used by classes derived from
<a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The convention has been adopted that subclasses defining
<code class="xref py py-meth docutils literal notranslate"><span class="pre">protocol_request()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">protocol_response()</span></code> methods are named
<code class="xref py py-class docutils literal notranslate"><span class="pre">*Processor</span></code>; all others are named <code class="xref py py-class docutils literal notranslate"><span class="pre">*Handler</span></code>.</p>
</div>
<dl class="attribute">
<dt id="urllib2.BaseHandler.parent">
<code class="descclassname">BaseHandler.</code><code class="descname">parent</code><a class="headerlink" href="#urllib2.BaseHandler.parent" title="Permalink to this definition">¶</a></dt>
<dd><p>A valid <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>, which can be used to open using a different
protocol, or handle errors.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.BaseHandler.default_open">
<code class="descclassname">BaseHandler.</code><code class="descname">default_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.default_open" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
define it if they want to catch all URLs.</p>
<p>This method, if implemented, will be called by the parent
<a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>.  It should return a file-like object as described in
the return value of the <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> of <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.
It should raise <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a>, unless a truly exceptional thing happens (for
example, <a class="reference internal" href="exceptions.html#exceptions.MemoryError" title="exceptions.MemoryError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">MemoryError</span></code></a> should not be mapped to <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a>).</p>
<p>This method will be called before any protocol-specific open method.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">BaseHandler.</code><code class="descname">protocol_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></dt>
<dd><p>(“protocol” is to be replaced by the protocol name.)</p>
<p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
define it if they want to handle URLs with the given <em>protocol</em>.</p>
<p>This method, if defined, will be called by the parent <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>.
Return values should be the same as for  <a class="reference internal" href="#urllib2.BaseHandler.default_open" title="urllib2.BaseHandler.default_open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">default_open()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.BaseHandler.unknown_open">
<code class="descclassname">BaseHandler.</code><code class="descname">unknown_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.unknown_open" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
define it if they want to catch all URLs with no specific registered handler to
open it.</p>
<p>This method, if implemented, will be called by the <a class="reference internal" href="#urllib2.BaseHandler.parent" title="urllib2.BaseHandler.parent"><code class="xref py py-attr docutils literal notranslate"><span class="pre">parent</span></code></a>
<a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>.  Return values should be the same as for
<a class="reference internal" href="#urllib2.BaseHandler.default_open" title="urllib2.BaseHandler.default_open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">default_open()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.BaseHandler.http_error_default">
<code class="descclassname">BaseHandler.</code><code class="descname">http_error_default</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.http_error_default" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
override it if they intend to provide a catch-all for otherwise unhandled HTTP
errors.  It will be called automatically by the  <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> getting
the error, and should not normally be called in other circumstances.</p>
<p><em>req</em> will be a <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object, <em>fp</em> will be a file-like object with
the HTTP error body, <em>code</em> will be the three-digit code of the error, <em>msg</em>
will be the user-visible explanation of the code and <em>hdrs</em> will be a mapping
object with the headers of the error.</p>
<p>Return values and exceptions raised should be the same as those of
<a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.BaseHandler.http_error_nnn">
<code class="descclassname">BaseHandler.</code><code class="descname">http_error_nnn</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.BaseHandler.http_error_nnn" title="Permalink to this definition">¶</a></dt>
<dd><p><em>nnn</em> should be a three-digit HTTP error code.  This method is also not defined
in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but will be called, if it exists, on an instance of a
subclass, when an HTTP error with code <em>nnn</em> occurs.</p>
<p>Subclasses should override this method to handle specific HTTP errors.</p>
<p>Arguments, return values and exceptions raised should be the same as for
<a class="reference internal" href="#urllib2.BaseHandler.http_error_default" title="urllib2.BaseHandler.http_error_default"><code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_default()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">BaseHandler.</code><code class="descname">protocol_request</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span></dt>
<dd><p>(“protocol” is to be replaced by the protocol name.)</p>
<p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
define it if they want to pre-process requests of the given <em>protocol</em>.</p>
<p>This method, if defined, will be called by the parent <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>.
<em>req</em> will be a <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object. The return value should be a
<a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">BaseHandler.</code><code class="descname">protocol_response</code><span class="sig-paren">(</span><em>req</em>, <em>response</em><span class="sig-paren">)</span></dt>
<dd><p>(“protocol” is to be replaced by the protocol name.)</p>
<p>This method is <em>not</em> defined in <a class="reference internal" href="#urllib2.BaseHandler" title="urllib2.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but subclasses should
define it if they want to post-process responses of the given <em>protocol</em>.</p>
<p>This method, if defined, will be called by the parent <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a>.
<em>req</em> will be a <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object. <em>response</em> will be an object
implementing the same interface as the return value of <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.  The
return value should implement the same interface as the return value of
<a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="httpredirecthandler-objects">
<span id="http-redirect-handler"></span><h2>20.6.4. HTTPRedirectHandler Objects<a class="headerlink" href="#httpredirecthandler-objects" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Some HTTP redirections require action from this module’s client code.  If this
is the case, <a class="reference internal" href="#urllib2.HTTPError" title="urllib2.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> is raised.  See <span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a> for details of the
precise meanings of the various redirection codes.</p>
</div>
<dl class="method">
<dt id="urllib2.HTTPRedirectHandler.redirect_request">
<code class="descclassname">HTTPRedirectHandler.</code><code class="descname">redirect_request</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em>, <em>newurl</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPRedirectHandler.redirect_request" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> or <code class="docutils literal notranslate"><span class="pre">None</span></code> in response to a redirect. This is called
by the default implementations of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_30*()</span></code> methods when a
redirection is received from the server.  If a redirection should take place,
return a new <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> to allow <code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_30*()</span></code> to perform the
redirect to <em>newurl</em>.  Otherwise, raise <a class="reference internal" href="#urllib2.HTTPError" title="urllib2.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> if no other handler
should try to handle this URL, or return <code class="docutils literal notranslate"><span class="pre">None</span></code> if you can’t but another
handler might.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The default implementation of this method does not strictly follow <span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>,
which says that 301 and 302 responses to <code class="docutils literal notranslate"><span class="pre">POST</span></code> requests must not be
automatically redirected without confirmation by the user.  In reality, browsers
do allow automatic redirection of these responses, changing the POST to a
<code class="docutils literal notranslate"><span class="pre">GET</span></code>, and the default implementation reproduces this behavior.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPRedirectHandler.http_error_301">
<code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_301</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPRedirectHandler.http_error_301" title="Permalink to this definition">¶</a></dt>
<dd><p>Redirect to the <code class="docutils literal notranslate"><span class="pre">Location:</span></code> or <code class="docutils literal notranslate"><span class="pre">URI:</span></code> URL.  This method is called by the
parent <a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> when getting an HTTP ‘moved permanently’ response.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPRedirectHandler.http_error_302">
<code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_302</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPRedirectHandler.http_error_302" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#urllib2.HTTPRedirectHandler.http_error_301" title="urllib2.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_301()</span></code></a>, but called for the ‘found’ response.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPRedirectHandler.http_error_303">
<code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_303</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPRedirectHandler.http_error_303" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#urllib2.HTTPRedirectHandler.http_error_301" title="urllib2.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_301()</span></code></a>, but called for the ‘see other’ response.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPRedirectHandler.http_error_307">
<code class="descclassname">HTTPRedirectHandler.</code><code class="descname">http_error_307</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPRedirectHandler.http_error_307" title="Permalink to this definition">¶</a></dt>
<dd><p>The same as <a class="reference internal" href="#urllib2.HTTPRedirectHandler.http_error_301" title="urllib2.HTTPRedirectHandler.http_error_301"><code class="xref py py-meth docutils literal notranslate"><span class="pre">http_error_301()</span></code></a>, but called for the ‘temporary redirect’
response.</p>
</dd></dl>

</div>
<div class="section" id="httpcookieprocessor-objects">
<span id="http-cookie-processor"></span><h2>20.6.5. HTTPCookieProcessor Objects<a class="headerlink" href="#httpcookieprocessor-objects" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p><a class="reference internal" href="#urllib2.HTTPCookieProcessor" title="urllib2.HTTPCookieProcessor"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPCookieProcessor</span></code></a> instances have one attribute:</p>
<dl class="attribute">
<dt id="urllib2.HTTPCookieProcessor.cookiejar">
<code class="descclassname">HTTPCookieProcessor.</code><code class="descname">cookiejar</code><a class="headerlink" href="#urllib2.HTTPCookieProcessor.cookiejar" title="Permalink to this definition">¶</a></dt>
<dd><p>The <a class="reference internal" href="cookielib.html#cookielib.CookieJar" title="cookielib.CookieJar"><code class="xref py py-class docutils literal notranslate"><span class="pre">cookielib.CookieJar</span></code></a> in which cookies are stored.</p>
</dd></dl>

</div>
<div class="section" id="proxyhandler-objects">
<span id="proxy-handler"></span><h2>20.6.6. ProxyHandler Objects<a class="headerlink" href="#proxyhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt>
<code class="descclassname">ProxyHandler.</code><code class="descname">protocol_open</code><span class="sig-paren">(</span><em>request</em><span class="sig-paren">)</span></dt>
<dd><p>(“protocol” is to be replaced by the protocol name.)</p>
<p>The <a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a> will have a method <code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_open</span></code> for every
<em>protocol</em> which has a proxy in the <em>proxies</em> dictionary given in the
constructor.  The method will modify requests to go through the proxy, by
calling <code class="docutils literal notranslate"><span class="pre">request.set_proxy()</span></code>, and call the next handler in the chain to
actually execute the protocol.</p>
</dd></dl>

</div>
<div class="section" id="httppasswordmgr-objects">
<span id="http-password-mgr"></span><h2>20.6.7. HTTPPasswordMgr Objects<a class="headerlink" href="#httppasswordmgr-objects" title="Permalink to this headline">¶</a></h2>
<p>These methods are available on <a class="reference internal" href="#urllib2.HTTPPasswordMgr" title="urllib2.HTTPPasswordMgr"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgr</span></code></a> and
<a class="reference internal" href="#urllib2.HTTPPasswordMgrWithDefaultRealm" title="urllib2.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a> objects.</p>
<dl class="method">
<dt id="urllib2.HTTPPasswordMgr.add_password">
<code class="descclassname">HTTPPasswordMgr.</code><code class="descname">add_password</code><span class="sig-paren">(</span><em>realm</em>, <em>uri</em>, <em>user</em>, <em>passwd</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPPasswordMgr.add_password" title="Permalink to this definition">¶</a></dt>
<dd><p><em>uri</em> can be either a single URI, or a sequence of URIs. <em>realm</em>, <em>user</em> and
<em>passwd</em> must be strings. This causes <code class="docutils literal notranslate"><span class="pre">(user,</span> <span class="pre">passwd)</span></code> to be used as
authentication tokens when authentication for <em>realm</em> and a super-URI of any of
the given URIs is given.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPPasswordMgr.find_user_password">
<code class="descclassname">HTTPPasswordMgr.</code><code class="descname">find_user_password</code><span class="sig-paren">(</span><em>realm</em>, <em>authuri</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPPasswordMgr.find_user_password" title="Permalink to this definition">¶</a></dt>
<dd><p>Get user/password for given realm and URI, if any.  This method will return
<code class="docutils literal notranslate"><span class="pre">(None,</span> <span class="pre">None)</span></code> if there is no matching user/password.</p>
<p>For <a class="reference internal" href="#urllib2.HTTPPasswordMgrWithDefaultRealm" title="urllib2.HTTPPasswordMgrWithDefaultRealm"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPPasswordMgrWithDefaultRealm</span></code></a> objects, the realm <code class="docutils literal notranslate"><span class="pre">None</span></code> will be
searched if the given <em>realm</em> has no matching user/password.</p>
</dd></dl>

</div>
<div class="section" id="abstractbasicauthhandler-objects">
<span id="abstract-basic-auth-handler"></span><h2>20.6.8. AbstractBasicAuthHandler Objects<a class="headerlink" href="#abstractbasicauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.AbstractBasicAuthHandler.http_error_auth_reqed">
<code class="descclassname">AbstractBasicAuthHandler.</code><code class="descname">http_error_auth_reqed</code><span class="sig-paren">(</span><em>authreq</em>, <em>host</em>, <em>req</em>, <em>headers</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.AbstractBasicAuthHandler.http_error_auth_reqed" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle an authentication request by getting a user/password pair, and re-trying
the request.  <em>authreq</em> should be the name of the header where the information
about the realm is included in the request, <em>host</em> specifies the URL and path to
authenticate for, <em>req</em> should be the (failed) <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object, and
<em>headers</em> should be the error headers.</p>
<p><em>host</em> is either an authority (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;python.org&quot;</span></code>) or a URL containing an
authority component (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;http://python.org/&quot;</span></code>). In either case, the
authority must not contain a userinfo component (so, <code class="docutils literal notranslate"><span class="pre">&quot;python.org&quot;</span></code> and
<code class="docutils literal notranslate"><span class="pre">&quot;python.org:80&quot;</span></code> are fine, <code class="docutils literal notranslate"><span class="pre">&quot;joe:password&#64;python.org&quot;</span></code> is not).</p>
</dd></dl>

</div>
<div class="section" id="httpbasicauthhandler-objects">
<span id="http-basic-auth-handler"></span><h2>20.6.9. HTTPBasicAuthHandler Objects<a class="headerlink" href="#httpbasicauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.HTTPBasicAuthHandler.http_error_401">
<code class="descclassname">HTTPBasicAuthHandler.</code><code class="descname">http_error_401</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPBasicAuthHandler.http_error_401" title="Permalink to this definition">¶</a></dt>
<dd><p>Retry the request with authentication information, if available.</p>
</dd></dl>

</div>
<div class="section" id="proxybasicauthhandler-objects">
<span id="proxy-basic-auth-handler"></span><h2>20.6.10. ProxyBasicAuthHandler Objects<a class="headerlink" href="#proxybasicauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.ProxyBasicAuthHandler.http_error_407">
<code class="descclassname">ProxyBasicAuthHandler.</code><code class="descname">http_error_407</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.ProxyBasicAuthHandler.http_error_407" title="Permalink to this definition">¶</a></dt>
<dd><p>Retry the request with authentication information, if available.</p>
</dd></dl>

</div>
<div class="section" id="abstractdigestauthhandler-objects">
<span id="abstract-digest-auth-handler"></span><h2>20.6.11. AbstractDigestAuthHandler Objects<a class="headerlink" href="#abstractdigestauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.AbstractDigestAuthHandler.http_error_auth_reqed">
<code class="descclassname">AbstractDigestAuthHandler.</code><code class="descname">http_error_auth_reqed</code><span class="sig-paren">(</span><em>authreq</em>, <em>host</em>, <em>req</em>, <em>headers</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.AbstractDigestAuthHandler.http_error_auth_reqed" title="Permalink to this definition">¶</a></dt>
<dd><p><em>authreq</em> should be the name of the header where the information about the realm
is included in the request, <em>host</em> should be the host to authenticate to, <em>req</em>
should be the (failed) <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> object, and <em>headers</em> should be the
error headers.</p>
</dd></dl>

</div>
<div class="section" id="httpdigestauthhandler-objects">
<span id="http-digest-auth-handler"></span><h2>20.6.12. HTTPDigestAuthHandler Objects<a class="headerlink" href="#httpdigestauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.HTTPDigestAuthHandler.http_error_401">
<code class="descclassname">HTTPDigestAuthHandler.</code><code class="descname">http_error_401</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPDigestAuthHandler.http_error_401" title="Permalink to this definition">¶</a></dt>
<dd><p>Retry the request with authentication information, if available.</p>
</dd></dl>

</div>
<div class="section" id="proxydigestauthhandler-objects">
<span id="proxy-digest-auth-handler"></span><h2>20.6.13. ProxyDigestAuthHandler Objects<a class="headerlink" href="#proxydigestauthhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.ProxyDigestAuthHandler.http_error_407">
<code class="descclassname">ProxyDigestAuthHandler.</code><code class="descname">http_error_407</code><span class="sig-paren">(</span><em>req</em>, <em>fp</em>, <em>code</em>, <em>msg</em>, <em>hdrs</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.ProxyDigestAuthHandler.http_error_407" title="Permalink to this definition">¶</a></dt>
<dd><p>Retry the request with authentication information, if available.</p>
</dd></dl>

</div>
<div class="section" id="httphandler-objects">
<span id="http-handler-objects"></span><h2>20.6.14. HTTPHandler Objects<a class="headerlink" href="#httphandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.HTTPHandler.http_open">
<code class="descclassname">HTTPHandler.</code><code class="descname">http_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPHandler.http_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an HTTP request, which can be either GET or POST, depending on
<code class="docutils literal notranslate"><span class="pre">req.has_data()</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="httpshandler-objects">
<span id="https-handler-objects"></span><h2>20.6.15. HTTPSHandler Objects<a class="headerlink" href="#httpshandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.HTTPSHandler.https_open">
<code class="descclassname">HTTPSHandler.</code><code class="descname">https_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPSHandler.https_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Send an HTTPS request, which can be either GET or POST, depending on
<code class="docutils literal notranslate"><span class="pre">req.has_data()</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="filehandler-objects">
<span id="file-handler-objects"></span><h2>20.6.16. FileHandler Objects<a class="headerlink" href="#filehandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.FileHandler.file_open">
<code class="descclassname">FileHandler.</code><code class="descname">file_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.FileHandler.file_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the file locally, if there is no host name, or the host name is
<code class="docutils literal notranslate"><span class="pre">'localhost'</span></code>. Change the protocol to <code class="docutils literal notranslate"><span class="pre">ftp</span></code> otherwise, and retry opening it
using <code class="xref py py-attr docutils literal notranslate"><span class="pre">parent</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="ftphandler-objects">
<span id="ftp-handler-objects"></span><h2>20.6.17. FTPHandler Objects<a class="headerlink" href="#ftphandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.FTPHandler.ftp_open">
<code class="descclassname">FTPHandler.</code><code class="descname">ftp_open</code><span class="sig-paren">(</span><em>req</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.FTPHandler.ftp_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Open the FTP file indicated by <em>req</em>. The login is always done with empty
username and password.</p>
</dd></dl>

</div>
<div class="section" id="cacheftphandler-objects">
<span id="cacheftp-handler-objects"></span><h2>20.6.18. CacheFTPHandler Objects<a class="headerlink" href="#cacheftphandler-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#urllib2.CacheFTPHandler" title="urllib2.CacheFTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CacheFTPHandler</span></code></a> objects are <a class="reference internal" href="#urllib2.FTPHandler" title="urllib2.FTPHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTPHandler</span></code></a> objects with the
following additional methods:</p>
<dl class="method">
<dt id="urllib2.CacheFTPHandler.setTimeout">
<code class="descclassname">CacheFTPHandler.</code><code class="descname">setTimeout</code><span class="sig-paren">(</span><em>t</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.CacheFTPHandler.setTimeout" title="Permalink to this definition">¶</a></dt>
<dd><p>Set timeout of connections to <em>t</em> seconds.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.CacheFTPHandler.setMaxConns">
<code class="descclassname">CacheFTPHandler.</code><code class="descname">setMaxConns</code><span class="sig-paren">(</span><em>m</em><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.CacheFTPHandler.setMaxConns" title="Permalink to this definition">¶</a></dt>
<dd><p>Set maximum number of cached connections to <em>m</em>.</p>
</dd></dl>

</div>
<div class="section" id="unknownhandler-objects">
<span id="unknown-handler-objects"></span><h2>20.6.19. UnknownHandler Objects<a class="headerlink" href="#unknownhandler-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="urllib2.UnknownHandler.unknown_open">
<code class="descclassname">UnknownHandler.</code><code class="descname">unknown_open</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.UnknownHandler.unknown_open" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise a <a class="reference internal" href="#urllib2.URLError" title="urllib2.URLError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">URLError</span></code></a> exception.</p>
</dd></dl>

</div>
<div class="section" id="httperrorprocessor-objects">
<span id="http-error-processor-objects"></span><h2>20.6.20. HTTPErrorProcessor Objects<a class="headerlink" href="#httperrorprocessor-objects" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<dl class="method">
<dt id="urllib2.HTTPErrorProcessor.http_response">
<code class="descclassname">HTTPErrorProcessor.</code><code class="descname">http_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPErrorProcessor.http_response" title="Permalink to this definition">¶</a></dt>
<dd><p>Process HTTP error responses.</p>
<p>For 200 error codes, the response object is returned immediately.</p>
<p>For non-200 error codes, this simply passes the job on to the
<code class="samp docutils literal notranslate"><em><span class="pre">protocol</span></em><span class="pre">_error_code</span></code> handler methods, via
<a class="reference internal" href="#urllib2.OpenerDirector.error" title="urllib2.OpenerDirector.error"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OpenerDirector.error()</span></code></a>.  Eventually,
<a class="reference internal" href="#urllib2.HTTPDefaultErrorHandler" title="urllib2.HTTPDefaultErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">urllib2.HTTPDefaultErrorHandler</span></code></a> will raise an <a class="reference internal" href="#urllib2.HTTPError" title="urllib2.HTTPError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HTTPError</span></code></a> if no
other handler handles the error.</p>
</dd></dl>

<dl class="method">
<dt id="urllib2.HTTPErrorProcessor.https_response">
<code class="descclassname">HTTPErrorProcessor.</code><code class="descname">https_response</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urllib2.HTTPErrorProcessor.https_response" title="Permalink to this definition">¶</a></dt>
<dd><p>Process HTTPS error responses.</p>
<p>The behavior is same as <a class="reference internal" href="#urllib2.HTTPErrorProcessor.http_response" title="urllib2.HTTPErrorProcessor.http_response"><code class="xref py py-meth docutils literal notranslate"><span class="pre">http_response()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="urllib2-examples"></span><h2>20.6.21. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>In addition to the examples below, more examples are given in
<a class="reference internal" href="../howto/urllib2.html#urllib-howto"><span class="std std-ref">HOWTO Fetch Internet Resources Using urllib2</span></a>.</p>
<p>This example gets the python.org main page and displays the first 100 bytes of
it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.python.org/&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="go">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt;</span>
<span class="go">&lt;?xml-stylesheet href=&quot;./css/ht2html</span>
</pre></div>
</div>
<p>Here we are sending a data-stream to the stdin of a CGI and reading the data it
returns to us. Note that this example will only work when the Python
installation supports SSL.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="n">url</span><span class="o">=</span><span class="s1">&#39;https://localhost/cgi-bin/test.cgi&#39;</span><span class="p">,</span>
<span class="gp">... </span>                      <span class="n">data</span><span class="o">=</span><span class="s1">&#39;This data is passed to stdin of the CGI&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">Got Data: &quot;This data is passed to stdin of the CGI&quot;</span>
</pre></div>
</div>
<p>The code for the sample CGI used in the above example is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;Content-type: text-plain</span><span class="se">\n\n</span><span class="s1">Got Data: &quot;</span><span class="si">%s</span><span class="s1">&quot;&#39;</span> <span class="o">%</span> <span class="n">data</span>
</pre></div>
</div>
<p>Use of Basic HTTP Authentication:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="c1"># Create an OpenerDirector with support for Basic HTTP Authentication...</span>
<span class="n">auth_handler</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">HTTPBasicAuthHandler</span><span class="p">()</span>
<span class="n">auth_handler</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="n">realm</span><span class="o">=</span><span class="s1">&#39;PDQ Application&#39;</span><span class="p">,</span>
                          <span class="n">uri</span><span class="o">=</span><span class="s1">&#39;https://mahler:8092/site-updates.py&#39;</span><span class="p">,</span>
                          <span class="n">user</span><span class="o">=</span><span class="s1">&#39;klem&#39;</span><span class="p">,</span>
                          <span class="n">passwd</span><span class="o">=</span><span class="s1">&#39;kadidd!ehopper&#39;</span><span class="p">)</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">auth_handler</span><span class="p">)</span>
<span class="c1"># ...and install it globally so it can be used with urlopen.</span>
<span class="n">urllib2</span><span class="o">.</span><span class="n">install_opener</span><span class="p">(</span><span class="n">opener</span><span class="p">)</span>
<span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/login.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#urllib2.build_opener" title="urllib2.build_opener"><code class="xref py py-func docutils literal notranslate"><span class="pre">build_opener()</span></code></a> provides many handlers by default, including a
<a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a>.  By default, <a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a> uses the environment
variables named <code class="docutils literal notranslate"><span class="pre">&lt;scheme&gt;_proxy</span></code>, where <code class="docutils literal notranslate"><span class="pre">&lt;scheme&gt;</span></code> is the URL scheme
involved.  For example, the <span class="target" id="index-6"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">http_proxy</span></code> environment variable is read to
obtain the HTTP proxy’s URL.</p>
<p>This example replaces the default <a class="reference internal" href="#urllib2.ProxyHandler" title="urllib2.ProxyHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyHandler</span></code></a> with one that uses
programmatically-supplied proxy URLs, and adds proxy authorization support with
<a class="reference internal" href="#urllib2.ProxyBasicAuthHandler" title="urllib2.ProxyBasicAuthHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProxyBasicAuthHandler</span></code></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">proxy_handler</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">ProxyHandler</span><span class="p">({</span><span class="s1">&#39;http&#39;</span><span class="p">:</span> <span class="s1">&#39;http://www.example.com:3128/&#39;</span><span class="p">})</span>
<span class="n">proxy_auth_handler</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">ProxyBasicAuthHandler</span><span class="p">()</span>
<span class="n">proxy_auth_handler</span><span class="o">.</span><span class="n">add_password</span><span class="p">(</span><span class="s1">&#39;realm&#39;</span><span class="p">,</span> <span class="s1">&#39;host&#39;</span><span class="p">,</span> <span class="s1">&#39;username&#39;</span><span class="p">,</span> <span class="s1">&#39;password&#39;</span><span class="p">)</span>

<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">(</span><span class="n">proxy_handler</span><span class="p">,</span> <span class="n">proxy_auth_handler</span><span class="p">)</span>
<span class="c1"># This time, rather than install the OpenerDirector, we use it directly:</span>
<span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/login.html&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Adding HTTP headers:</p>
<p>Use the <em>headers</em> argument to the <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> constructor, or:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="n">req</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">Request</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/&#39;</span><span class="p">)</span>
<span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;Referer&#39;</span><span class="p">,</span> <span class="s1">&#39;http://www.python.org/&#39;</span><span class="p">)</span>
<span class="c1"># Customize the default User-Agent header value:</span>
<span class="n">req</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;User-Agent&#39;</span><span class="p">,</span> <span class="s1">&#39;urllib-example/0.1 (Contact: . . .)&#39;</span><span class="p">)</span>
<span class="n">r</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="n">req</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#urllib2.OpenerDirector" title="urllib2.OpenerDirector"><code class="xref py py-class docutils literal notranslate"><span class="pre">OpenerDirector</span></code></a> automatically adds a <em class="mailheader">User-Agent</em> header to
every <a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a>.  To change this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="n">opener</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">build_opener</span><span class="p">()</span>
<span class="n">opener</span><span class="o">.</span><span class="n">addheaders</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;User-agent&#39;</span><span class="p">,</span> <span class="s1">&#39;Mozilla/5.0&#39;</span><span class="p">)]</span>
<span class="n">opener</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Also, remember that a few standard headers (<em class="mailheader">Content-Length</em>,
<em class="mailheader">Content-Type</em> and <em class="mailheader">Host</em>) are added when the
<a class="reference internal" href="#urllib2.Request" title="urllib2.Request"><code class="xref py py-class docutils literal notranslate"><span class="pre">Request</span></code></a> is passed to <a class="reference internal" href="#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlopen()</span></code></a> (or <a class="reference internal" href="#urllib2.OpenerDirector.open" title="urllib2.OpenerDirector.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">OpenerDirector.open()</span></code></a>).</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a><ul>
<li><a class="reference internal" href="#request-objects">20.6.1. Request Objects</a></li>
<li><a class="reference internal" href="#openerdirector-objects">20.6.2. OpenerDirector Objects</a></li>
<li><a class="reference internal" href="#basehandler-objects">20.6.3. BaseHandler Objects</a></li>
<li><a class="reference internal" href="#httpredirecthandler-objects">20.6.4. HTTPRedirectHandler Objects</a></li>
<li><a class="reference internal" href="#httpcookieprocessor-objects">20.6.5. HTTPCookieProcessor Objects</a></li>
<li><a class="reference internal" href="#proxyhandler-objects">20.6.6. ProxyHandler Objects</a></li>
<li><a class="reference internal" href="#httppasswordmgr-objects">20.6.7. HTTPPasswordMgr Objects</a></li>
<li><a class="reference internal" href="#abstractbasicauthhandler-objects">20.6.8. AbstractBasicAuthHandler Objects</a></li>
<li><a class="reference internal" href="#httpbasicauthhandler-objects">20.6.9. HTTPBasicAuthHandler Objects</a></li>
<li><a class="reference internal" href="#proxybasicauthhandler-objects">20.6.10. ProxyBasicAuthHandler Objects</a></li>
<li><a class="reference internal" href="#abstractdigestauthhandler-objects">20.6.11. AbstractDigestAuthHandler Objects</a></li>
<li><a class="reference internal" href="#httpdigestauthhandler-objects">20.6.12. HTTPDigestAuthHandler Objects</a></li>
<li><a class="reference internal" href="#proxydigestauthhandler-objects">20.6.13. ProxyDigestAuthHandler Objects</a></li>
<li><a class="reference internal" href="#httphandler-objects">20.6.14. HTTPHandler Objects</a></li>
<li><a class="reference internal" href="#httpshandler-objects">20.6.15. HTTPSHandler Objects</a></li>
<li><a class="reference internal" href="#filehandler-objects">20.6.16. FileHandler Objects</a></li>
<li><a class="reference internal" href="#ftphandler-objects">20.6.17. FTPHandler Objects</a></li>
<li><a class="reference internal" href="#cacheftphandler-objects">20.6.18. CacheFTPHandler Objects</a></li>
<li><a class="reference internal" href="#unknownhandler-objects">20.6.19. UnknownHandler Objects</a></li>
<li><a class="reference internal" href="#httperrorprocessor-objects">20.6.20. HTTPErrorProcessor Objects</a></li>
<li><a class="reference internal" href="#examples">20.6.21. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="urllib.html"
                        title="previous chapter">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="httplib.html"
                        title="next chapter">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/urllib2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="httplib.html" title="20.7. httplib — HTTP protocol client"
             >next</a> |</li>
        <li class="right" >
          <a href="urllib.html" title="20.5. urllib — Open arbitrary resources by URL"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\r�]ҩҩhtml/library/urlparse.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.16. urlparse — Parse URLs into components &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.17. SocketServer — A framework for network servers" href="socketserver.html" />
    <link rel="prev" title="20.15. uuid — UUID objects according to RFC 4122" href="uuid.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/urlparse.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="socketserver.html" title="20.17. SocketServer — A framework for network servers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="uuid.html" title="20.15. uuid — UUID objects according to RFC 4122"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-urlparse">
<span id="urlparse-parse-urls-into-components"></span><h1>20.16. <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> — Parse URLs into components<a class="headerlink" href="#module-urlparse" title="Permalink to this headline">¶</a></h1>
<div class="admonition note" id="index-0">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module is renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.parse</span></code> in Python 3.
The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when converting
your sources to Python 3.</p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/urlparse.py">Lib/urlparse.py</a></p>
<hr class="docutils" />
<p>This module defines a standard interface to break Uniform Resource Locator (URL)
strings up in components (addressing scheme, network location, path etc.), to
combine the components back into a URL string, and to convert a “relative URL”
to an absolute URL given a “base URL.”</p>
<p>The module has been designed to match the Internet RFC on Relative Uniform
Resource Locators. It supports the following URL schemes: <code class="docutils literal notranslate"><span class="pre">file</span></code>, <code class="docutils literal notranslate"><span class="pre">ftp</span></code>,
<code class="docutils literal notranslate"><span class="pre">gopher</span></code>, <code class="docutils literal notranslate"><span class="pre">hdl</span></code>, <code class="docutils literal notranslate"><span class="pre">http</span></code>, <code class="docutils literal notranslate"><span class="pre">https</span></code>, <code class="docutils literal notranslate"><span class="pre">imap</span></code>, <code class="docutils literal notranslate"><span class="pre">mailto</span></code>, <code class="docutils literal notranslate"><span class="pre">mms</span></code>,
<code class="docutils literal notranslate"><span class="pre">news</span></code>,  <code class="docutils literal notranslate"><span class="pre">nntp</span></code>, <code class="docutils literal notranslate"><span class="pre">prospero</span></code>, <code class="docutils literal notranslate"><span class="pre">rsync</span></code>, <code class="docutils literal notranslate"><span class="pre">rtsp</span></code>, <code class="docutils literal notranslate"><span class="pre">rtspu</span></code>,  <code class="docutils literal notranslate"><span class="pre">sftp</span></code>,
<code class="docutils literal notranslate"><span class="pre">shttp</span></code>, <code class="docutils literal notranslate"><span class="pre">sip</span></code>, <code class="docutils literal notranslate"><span class="pre">sips</span></code>, <code class="docutils literal notranslate"><span class="pre">snews</span></code>, <code class="docutils literal notranslate"><span class="pre">svn</span></code>,  <code class="docutils literal notranslate"><span class="pre">svn+ssh</span></code>, <code class="docutils literal notranslate"><span class="pre">telnet</span></code>,
<code class="docutils literal notranslate"><span class="pre">wais</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5: </span>Support for the <code class="docutils literal notranslate"><span class="pre">sftp</span></code> and <code class="docutils literal notranslate"><span class="pre">sips</span></code> schemes.</p>
</div>
<p>The <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="urlparse.urlparse">
<code class="descclassname">urlparse.</code><code class="descname">urlparse</code><span class="sig-paren">(</span><em>urlstring</em><span class="optional">[</span>, <em>scheme</em><span class="optional">[</span>, <em>allow_fragments</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urlparse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a URL into six components, returning a 6-tuple.  This corresponds to the
general structure of a URL: <code class="docutils literal notranslate"><span class="pre">scheme://netloc/path;parameters?query#fragment</span></code>.
Each tuple item is a string, possibly empty. The components are not broken up in
smaller parts (for example, the network location is a single string), and %
escapes are not expanded. The delimiters as shown above are not part of the
result, except for a leading slash in the <em>path</em> component, which is retained if
present.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">urlparse</span> <span class="k">import</span> <span class="n">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="n">urlparse</span><span class="p">(</span><span class="s1">&#39;http://www.cwi.nl:80/</span><span class="si">%7E</span><span class="s1">guido/Python.html&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span>   
<span class="go">ParseResult(scheme=&#39;http&#39;, netloc=&#39;www.cwi.nl:80&#39;, path=&#39;/%7Eguido/Python.html&#39;,</span>
<span class="go">            params=&#39;&#39;, query=&#39;&#39;, fragment=&#39;&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">scheme</span>
<span class="go">&#39;http&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">port</span>
<span class="go">80</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span><span class="o">.</span><span class="n">geturl</span><span class="p">()</span>
<span class="go">&#39;http://www.cwi.nl:80/%7Eguido/Python.html&#39;</span>
</pre></div>
</div>
<p>Following the syntax specifications in <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1808.html"><strong>RFC 1808</strong></a>, urlparse recognizes
a netloc only if it is properly introduced by ‘//’.  Otherwise the
input is presumed to be a relative URL and thus to start with
a path component.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">urlparse</span> <span class="k">import</span> <span class="n">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="p">(</span><span class="s1">&#39;//www.cwi.nl:80/</span><span class="si">%7E</span><span class="s1">guido/Python.html&#39;</span><span class="p">)</span>
<span class="go">ParseResult(scheme=&#39;&#39;, netloc=&#39;www.cwi.nl:80&#39;, path=&#39;/%7Eguido/Python.html&#39;,</span>
<span class="go">           params=&#39;&#39;, query=&#39;&#39;, fragment=&#39;&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="p">(</span><span class="s1">&#39;www.cwi.nl/</span><span class="si">%7E</span><span class="s1">guido/Python.html&#39;</span><span class="p">)</span>
<span class="go">ParseResult(scheme=&#39;&#39;, netloc=&#39;&#39;, path=&#39;www.cwi.nl/%7Eguido/Python.html&#39;,</span>
<span class="go">           params=&#39;&#39;, query=&#39;&#39;, fragment=&#39;&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="p">(</span><span class="s1">&#39;help/Python.html&#39;</span><span class="p">)</span>
<span class="go">ParseResult(scheme=&#39;&#39;, netloc=&#39;&#39;, path=&#39;help/Python.html&#39;, params=&#39;&#39;,</span>
<span class="go">           query=&#39;&#39;, fragment=&#39;&#39;)</span>
</pre></div>
</div>
<p>If the <em>scheme</em> argument is specified, it gives the default addressing
scheme, to be used only if the URL does not specify one.  The default value for
this argument is the empty string.</p>
<p>If the <em>allow_fragments</em> argument is false, fragment identifiers are not
recognized and parsed as part of the preceding component, even if the URL’s
addressing scheme normally does support them.  The default value for this
argument is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<p>The return value is actually an instance of a subclass of <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.  This
class has the following additional read-only convenience attributes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="10%" />
<col width="36%" />
<col width="30%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Index</th>
<th class="head">Value</th>
<th class="head">Value if not present</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">scheme</span></code></td>
<td>0</td>
<td>URL scheme specifier</td>
<td><em>scheme</em> parameter</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">netloc</span></code></td>
<td>1</td>
<td>Network location part</td>
<td>empty string</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">path</span></code></td>
<td>2</td>
<td>Hierarchical path</td>
<td>empty string</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">params</span></code></td>
<td>3</td>
<td>Parameters for last path
element</td>
<td>empty string</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">query</span></code></td>
<td>4</td>
<td>Query component</td>
<td>empty string</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">fragment</span></code></td>
<td>5</td>
<td>Fragment identifier</td>
<td>empty string</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">username</span></code></td>
<td>&#160;</td>
<td>User name</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">password</span></code></td>
<td>&#160;</td>
<td>Password</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">hostname</span></code></td>
<td>&#160;</td>
<td>Host name (lower case)</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">port</span></code></td>
<td>&#160;</td>
<td>Port number as integer,
if present</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
</tbody>
</table>
<p>See section <a class="reference internal" href="#urlparse-result-object"><span class="std std-ref">Results of urlparse() and urlsplit()</span></a> for more information on the result
object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added attributes to return value.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added IPv6 URL parsing capabilities.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urlparse.parse_qs">
<code class="descclassname">urlparse.</code><code class="descname">parse_qs</code><span class="sig-paren">(</span><em>qs</em><span class="optional">[</span>, <em>keep_blank_values</em><span class="optional">[</span>, <em>strict_parsing</em><span class="optional">[</span>, <em>max_num_fields</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.parse_qs" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a query string given as a string argument (data of type
<em class="mimetype">application/x-www-form-urlencoded</em>).  Data are returned as a
dictionary.  The dictionary keys are the unique query variable names and the
values are lists of values for each name.</p>
<p>The optional argument <em>keep_blank_values</em> is a flag indicating whether blank
values in percent-encoded queries should be treated as blank strings.   A true value
indicates that blanks should be retained as  blank strings.  The default false
value indicates that blank values are to be ignored and treated as if they were
not included.</p>
<p>The optional argument <em>strict_parsing</em> is a flag indicating what to do with
parsing errors.  If false (the default), errors are silently ignored.  If true,
errors raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
<p>The optional argument <em>max_num_fields</em> is the maximum number of fields to
read. If set, then throws a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if there are more than
<em>max_num_fields</em> fields read.</p>
<p>Use the <a class="reference internal" href="urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a> function to convert such dictionaries into
query strings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Copied from the <a class="reference internal" href="cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.16: </span>Added <em>max_num_fields</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urlparse.parse_qsl">
<code class="descclassname">urlparse.</code><code class="descname">parse_qsl</code><span class="sig-paren">(</span><em>qs</em><span class="optional">[</span>, <em>keep_blank_values</em><span class="optional">[</span>, <em>strict_parsing</em><span class="optional">[</span>, <em>max_num_fields</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.parse_qsl" title="Permalink to this definition">¶</a></dt>
<dd><p>Parse a query string given as a string argument (data of type
<em class="mimetype">application/x-www-form-urlencoded</em>).  Data are returned as a list of
name, value pairs.</p>
<p>The optional argument <em>keep_blank_values</em> is a flag indicating whether blank
values in percent-encoded queries should be treated as blank strings.   A true value
indicates that blanks should be retained as  blank strings.  The default false
value indicates that blank values are to be ignored and treated as if they were
not included.</p>
<p>The optional argument <em>strict_parsing</em> is a flag indicating what to do with
parsing errors.  If false (the default), errors are silently ignored.  If true,
errors raise a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
<p>The optional argument <em>max_num_fields</em> is the maximum number of fields to
read. If set, then throws a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if there are more than
<em>max_num_fields</em> fields read.</p>
<p>Use the <a class="reference internal" href="urllib.html#urllib.urlencode" title="urllib.urlencode"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlencode()</span></code></a> function to convert such lists of pairs into
query strings.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6: </span>Copied from the <a class="reference internal" href="cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.16: </span>Added <em>max_num_fields</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urlparse.urlunparse">
<code class="descclassname">urlparse.</code><code class="descname">urlunparse</code><span class="sig-paren">(</span><em>parts</em><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urlunparse" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a URL from a tuple as returned by <code class="docutils literal notranslate"><span class="pre">urlparse()</span></code>. The <em>parts</em> argument
can be any six-item iterable. This may result in a slightly different, but
equivalent URL, if the URL that was parsed originally had unnecessary delimiters
(for example, a ? with an empty query; the RFC states that these are
equivalent).</p>
</dd></dl>

<dl class="function">
<dt id="urlparse.urlsplit">
<code class="descclassname">urlparse.</code><code class="descname">urlsplit</code><span class="sig-paren">(</span><em>urlstring</em><span class="optional">[</span>, <em>scheme</em><span class="optional">[</span>, <em>allow_fragments</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urlsplit" title="Permalink to this definition">¶</a></dt>
<dd><p>This is similar to <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a>, but does not split the params from the URL.
This should generally be used instead of <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a> if the more recent URL
syntax allowing parameters to be applied to each segment of the <em>path</em> portion
of the URL (see <span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2396.html"><strong>RFC 2396</strong></a>) is wanted.  A separate function is needed to
separate the path segments and parameters.  This function returns a 5-tuple:
(addressing scheme, network location, path, query, fragment identifier).</p>
<p>The return value is actually an instance of a subclass of <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.  This
class has the following additional read-only convenience attributes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="10%" />
<col width="35%" />
<col width="31%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Index</th>
<th class="head">Value</th>
<th class="head">Value if not present</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">scheme</span></code></td>
<td>0</td>
<td>URL scheme specifier</td>
<td><em>scheme</em> parameter</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">netloc</span></code></td>
<td>1</td>
<td>Network location part</td>
<td>empty string</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">path</span></code></td>
<td>2</td>
<td>Hierarchical path</td>
<td>empty string</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">query</span></code></td>
<td>3</td>
<td>Query component</td>
<td>empty string</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">fragment</span></code></td>
<td>4</td>
<td>Fragment identifier</td>
<td>empty string</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">username</span></code></td>
<td>&#160;</td>
<td>User name</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">password</span></code></td>
<td>&#160;</td>
<td>Password</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">hostname</span></code></td>
<td>&#160;</td>
<td>Host name (lower case)</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">port</span></code></td>
<td>&#160;</td>
<td>Port number as integer,
if present</td>
<td><a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a></td>
</tr>
</tbody>
</table>
<p>See section <a class="reference internal" href="#urlparse-result-object"><span class="std std-ref">Results of urlparse() and urlsplit()</span></a> for more information on the result
object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added attributes to return value.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="urlparse.urlunsplit">
<code class="descclassname">urlparse.</code><code class="descname">urlunsplit</code><span class="sig-paren">(</span><em>parts</em><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urlunsplit" title="Permalink to this definition">¶</a></dt>
<dd><p>Combine the elements of a tuple as returned by <a class="reference internal" href="#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> into a complete
URL as a string. The <em>parts</em> argument can be any five-item iterable. This may
result in a slightly different, but equivalent URL, if the URL that was parsed
originally had unnecessary delimiters (for example, a ? with an empty query; the
RFC states that these are equivalent).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="urlparse.urljoin">
<code class="descclassname">urlparse.</code><code class="descname">urljoin</code><span class="sig-paren">(</span><em>base</em>, <em>url</em><span class="optional">[</span>, <em>allow_fragments</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urljoin" title="Permalink to this definition">¶</a></dt>
<dd><p>Construct a full (“absolute”) URL by combining a “base URL” (<em>base</em>) with
another URL (<em>url</em>).  Informally, this uses components of the base URL, in
particular the addressing scheme, the network location and (part of) the path,
to provide missing components in the relative URL.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">urlparse</span> <span class="k">import</span> <span class="n">urljoin</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urljoin</span><span class="p">(</span><span class="s1">&#39;http://www.cwi.nl/</span><span class="si">%7E</span><span class="s1">guido/Python.html&#39;</span><span class="p">,</span> <span class="s1">&#39;FAQ.html&#39;</span><span class="p">)</span>
<span class="go">&#39;http://www.cwi.nl/%7Eguido/FAQ.html&#39;</span>
</pre></div>
</div>
<p>The <em>allow_fragments</em> argument has the same meaning and default as for
<a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <em>url</em> is an absolute URL (that is, starting with <code class="docutils literal notranslate"><span class="pre">//</span></code> or <code class="docutils literal notranslate"><span class="pre">scheme://</span></code>),
the <em>url</em>’s host name and/or scheme will be present in the result.  For example:</p>
</div>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">urljoin</span><span class="p">(</span><span class="s1">&#39;http://www.cwi.nl/</span><span class="si">%7E</span><span class="s1">guido/Python.html&#39;</span><span class="p">,</span>
<span class="gp">... </span>        <span class="s1">&#39;//www.python.org/</span><span class="si">%7E</span><span class="s1">guido&#39;</span><span class="p">)</span>
<span class="go">&#39;http://www.python.org/%7Eguido&#39;</span>
</pre></div>
</div>
<p>If you do not want that behavior, preprocess the <em>url</em> with <a class="reference internal" href="#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> and
<a class="reference internal" href="#urlparse.urlunsplit" title="urlparse.urlunsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlunsplit()</span></code></a>, removing possible <em>scheme</em> and <em>netloc</em> parts.</p>
</dd></dl>

<dl class="function">
<dt id="urlparse.urldefrag">
<code class="descclassname">urlparse.</code><code class="descname">urldefrag</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.urldefrag" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>url</em> contains a fragment identifier, returns a modified version of <em>url</em>
with no fragment identifier, and the fragment identifier as a separate string.
If there is no fragment identifier in <em>url</em>, returns <em>url</em> unmodified and an
empty string.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3986.html"><strong>RFC 3986</strong></a> - Uniform Resource Identifiers</dt>
<dd>This is the current standard (STD66). Any changes to urlparse module
should conform to this. Certain deviations could be observed, which are
mostly for backward compatibility purposes and for certain de-facto
parsing requirements as commonly observed in major browsers.</dd>
<dt><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2732.html"><strong>RFC 2732</strong></a> - Format for Literal IPv6 Addresses in URL’s.</dt>
<dd>This specifies the parsing requirements of IPv6 URLs.</dd>
<dt><span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2396.html"><strong>RFC 2396</strong></a> - Uniform Resource Identifiers (URI): Generic Syntax</dt>
<dd>Document describing the generic syntactic requirements for both Uniform Resource
Names (URNs) and Uniform Resource Locators (URLs).</dd>
<dt><span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2368.html"><strong>RFC 2368</strong></a> - The mailto URL scheme.</dt>
<dd>Parsing requirements for mailto URL schemes.</dd>
<dt><span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1808.html"><strong>RFC 1808</strong></a> - Relative Uniform Resource Locators</dt>
<dd>This Request For Comments includes the rules for joining an absolute and a
relative URL, including a fair number of “Abnormal Examples” which govern the
treatment of border cases.</dd>
<dt><span class="target" id="index-8"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1738.html"><strong>RFC 1738</strong></a> - Uniform Resource Locators (URL)</dt>
<dd>This specifies the formal syntax and semantics of absolute URLs.</dd>
</dl>
</div>
<div class="section" id="results-of-urlparse-and-urlsplit">
<span id="urlparse-result-object"></span><h2>20.16.1. Results of <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a> and <a class="reference internal" href="#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a><a class="headerlink" href="#results-of-urlparse-and-urlsplit" title="Permalink to this headline">¶</a></h2>
<p>The result objects from the <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a> and <a class="reference internal" href="#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> functions are
subclasses of the <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> type.  These subclasses add the attributes
described in those functions, as well as provide an additional method:</p>
<dl class="method">
<dt id="urlparse.ParseResult.geturl">
<code class="descclassname">ParseResult.</code><code class="descname">geturl</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.ParseResult.geturl" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the re-combined version of the original URL as a string. This may differ
from the original URL in that the scheme will always be normalized to lower case
and empty components may be dropped. Specifically, empty parameters, queries,
and fragment identifiers will be removed.</p>
<p>The result of this method is a fixpoint if passed back through the original
parsing function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;HTTP://www.Python.org/doc/#&#39;</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">r1</span> <span class="o">=</span> <span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r1</span><span class="o">.</span><span class="n">geturl</span><span class="p">()</span>
<span class="go">&#39;http://www.Python.org/doc/&#39;</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">r2</span> <span class="o">=</span> <span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="n">r1</span><span class="o">.</span><span class="n">geturl</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r2</span><span class="o">.</span><span class="n">geturl</span><span class="p">()</span>
<span class="go">&#39;http://www.Python.org/doc/&#39;</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>The following classes provide the implementations of the parse results:</p>
<dl class="class">
<dt id="urlparse.ParseResult">
<em class="property">class </em><code class="descclassname">urlparse.</code><code class="descname">ParseResult</code><span class="sig-paren">(</span><em>scheme</em>, <em>netloc</em>, <em>path</em>, <em>params</em>, <em>query</em>, <em>fragment</em><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.ParseResult" title="Permalink to this definition">¶</a></dt>
<dd><p>Concrete class for <a class="reference internal" href="#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-func docutils literal notranslate"><span class="pre">urlparse()</span></code></a> results.</p>
</dd></dl>

<dl class="class">
<dt id="urlparse.SplitResult">
<em class="property">class </em><code class="descclassname">urlparse.</code><code class="descname">SplitResult</code><span class="sig-paren">(</span><em>scheme</em>, <em>netloc</em>, <em>path</em>, <em>query</em>, <em>fragment</em><span class="sig-paren">)</span><a class="headerlink" href="#urlparse.SplitResult" title="Permalink to this definition">¶</a></dt>
<dd><p>Concrete class for <a class="reference internal" href="#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> results.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a><ul>
<li><a class="reference internal" href="#results-of-urlparse-and-urlsplit">20.16.1. Results of <code class="docutils literal notranslate"><span class="pre">urlparse()</span></code> and <code class="docutils literal notranslate"><span class="pre">urlsplit()</span></code></a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="uuid.html"
                        title="previous chapter">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="socketserver.html"
                        title="next chapter">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/urlparse.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="socketserver.html" title="20.17. SocketServer — A framework for network servers"
             >next</a> |</li>
        <li class="right" >
          <a href="uuid.html" title="20.15. uuid — UUID objects according to RFC 4122"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\n�m5�1�1html/library/user.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.15. user — User-specific configuration hook &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.16. fpectl — Floating point exception control" href="fpectl.html" />
    <link rel="prev" title="28.14. site — Site-specific configuration hook" href="site.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/user.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fpectl.html" title="28.16. fpectl — Floating point exception control"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="site.html" title="28.14. site — Site-specific configuration hook"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-user">
<span id="user-user-specific-configuration-hook"></span><h1>28.15. <a class="reference internal" href="#module-user" title="user: A standard way to reference user-specific modules. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">user</span></code></a> — User-specific configuration hook<a class="headerlink" href="#module-user" title="Permalink to this headline">¶</a></h1>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#module-user" title="user: A standard way to reference user-specific modules. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">user</span></code></a> module has been removed in Python 3.</p>
</div>
<p id="index-0">As a policy, Python doesn’t run user-specified code on startup of Python
programs.  (Only interactive sessions execute the script specified in the
<span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> environment variable if it exists).</p>
<p>However, some programs or sites may find it convenient to allow users to have a
standard customization file, which gets run when a program requests it.  This
module implements such a mechanism.  A program that wishes to use the mechanism
must execute the statement</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">user</span>
</pre></div>
</div>
<p id="index-2">The <a class="reference internal" href="#module-user" title="user: A standard way to reference user-specific modules. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">user</span></code></a> module looks for a file <code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> in the user’s home
directory and if it can be opened, executes it (using <a class="reference internal" href="functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a>) in its
own (the module <a class="reference internal" href="#module-user" title="user: A standard way to reference user-specific modules. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">user</span></code></a>’s) global namespace.  Errors during this phase are
not caught; that’s up to the program that imports the <a class="reference internal" href="#module-user" title="user: A standard way to reference user-specific modules. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">user</span></code></a> module, if it
wishes.  The home directory is assumed to be named by the <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">HOME</span></code>
environment variable; if this is not set, the current directory is used.</p>
<p>The user’s <code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> could conceivably test for <code class="docutils literal notranslate"><span class="pre">sys.version</span></code> if it
wishes to do different things depending on the Python version.</p>
<p>A warning to users: be very conservative in what you place in your
<code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> file.  Since you don’t know which programs will use it,
changing the behavior of standard modules or functions is generally not a good
idea.</p>
<p>A suggestion for programmers who wish to use this mechanism: a simple way to let
users specify options for your package is to have them define variables in their
<code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> file that you test in your module.  For example, a module
<code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> that has a verbosity level can look for a variable
<code class="docutils literal notranslate"><span class="pre">user.spam_verbose</span></code>, as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">user</span>

<span class="n">verbose</span> <span class="o">=</span> <span class="nb">bool</span><span class="p">(</span><span class="nb">getattr</span><span class="p">(</span><span class="n">user</span><span class="p">,</span> <span class="s2">&quot;spam_verbose&quot;</span><span class="p">,</span> <span class="mi">0</span><span class="p">))</span>
</pre></div>
</div>
<p>(The three-argument form of <a class="reference internal" href="functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> is used in case the user has not
defined <code class="docutils literal notranslate"><span class="pre">spam_verbose</span></code> in their <code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> file.)</p>
<p>Programs with extensive customization needs are better off reading a
program-specific customization file.</p>
<p>Programs with security or privacy concerns should <em>not</em> import this module; a
user can easily break into a program by placing arbitrary code in the
<code class="file docutils literal notranslate"><span class="pre">.pythonrc.py</span></code> file.</p>
<p>Modules for general use should <em>not</em> import this module; it may interfere with
the operation of the importing program.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a></dt>
<dd>Site-wide customization mechanism.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="site.html"
                        title="previous chapter">28.14. <code class="docutils literal notranslate"><span class="pre">site</span></code> — Site-specific configuration hook</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="fpectl.html"
                        title="next chapter">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/user.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="fpectl.html" title="28.16. fpectl — Floating point exception control"
             >next</a> |</li>
        <li class="right" >
          <a href="site.html" title="28.14. site — Site-specific configuration hook"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�P��E}E}html/library/userdict.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.12. UserDict — Class wrapper for dictionary objects &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.15. types — Names for built-in types" href="types.html" />
    <link rel="prev" title="8.11. weakref — Weak references" href="weakref.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/userdict.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="types.html" title="8.15. types — Names for built-in types"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="8.11. weakref — Weak references"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-UserDict">
<span id="userdict-class-wrapper-for-dictionary-objects"></span><h1>8.12. <a class="reference internal" href="#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserDict</span></code></a> — Class wrapper for dictionary objects<a class="headerlink" href="#module-UserDict" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/UserDict.py">Lib/UserDict.py</a></p>
<hr class="docutils" />
<p>The module defines a mixin,  <a class="reference internal" href="#UserDict.DictMixin" title="UserDict.DictMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code></a>, defining all dictionary methods
for classes that already have a minimum mapping interface.  This greatly
simplifies writing classes that need to be substitutable for dictionaries (such
as the shelve module).</p>
<p>This module also defines a class, <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a>, that acts as a wrapper
around dictionary objects.  The need for this class has been largely supplanted
by the ability to subclass directly from <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> (a feature that became
available starting with Python version 2.2).  Prior to the introduction of
<a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>, the <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> class was used to create dictionary-like
sub-classes that obtained new behaviors by overriding existing methods or adding
new ones.</p>
<p>The <a class="reference internal" href="#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserDict</span></code></a> module defines the <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> class and
<a class="reference internal" href="#UserDict.DictMixin" title="UserDict.DictMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code></a>:</p>
<dl class="class">
<dt id="UserDict.UserDict">
<em class="property">class </em><code class="descclassname">UserDict.</code><code class="descname">UserDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>initialdata</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#UserDict.UserDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Class that simulates a dictionary.  The instance’s contents are kept in a
regular dictionary, which is accessible via the <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code> attribute of
<a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> instances.  If <em>initialdata</em> is provided, <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code> is
initialized with its contents; note that a reference to <em>initialdata</em> will not
be kept, allowing it be used for other purposes.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For backward compatibility, instances of <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> are not iterable.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="UserDict.IterableUserDict">
<em class="property">class </em><code class="descclassname">UserDict.</code><code class="descname">IterableUserDict</code><span class="sig-paren">(</span><span class="optional">[</span><em>initialdata</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#UserDict.IterableUserDict" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> that supports direct iteration (e.g.  <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">key</span> <span class="pre">in</span>
<span class="pre">myDict</span></code>).</p>
</dd></dl>

<p>In addition to supporting the methods and operations of mappings (see section
<a class="reference internal" href="stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a>), <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> and <a class="reference internal" href="#UserDict.IterableUserDict" title="UserDict.IterableUserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableUserDict</span></code></a> instances
provide the following attribute:</p>
<dl class="attribute">
<dt id="UserDict.IterableUserDict.data">
<code class="descclassname">IterableUserDict.</code><code class="descname">data</code><a class="headerlink" href="#UserDict.IterableUserDict.data" title="Permalink to this definition">¶</a></dt>
<dd><p>A real dictionary used to store the contents of the <a class="reference internal" href="#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> class.</p>
</dd></dl>

<dl class="class">
<dt id="UserDict.DictMixin">
<em class="property">class </em><code class="descclassname">UserDict.</code><code class="descname">DictMixin</code><a class="headerlink" href="#UserDict.DictMixin" title="Permalink to this definition">¶</a></dt>
<dd><p>Mixin defining all dictionary methods for classes that already have a minimum
dictionary interface including <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>.</p>
<p>This mixin should be used as a superclass.  Adding each of the above methods
adds progressively more functionality.  For instance, defining all but
<a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> will preclude only <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code> from the
full interface.</p>
<p>In addition to the four base methods, progressively more efficiency comes with
defining <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code>.</p>
<p>Since the mixin has no knowledge of the subclass constructor, it does not define
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> or <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>.</p>
<p>Starting with Python version 2.6, it is recommended to use
<a class="reference internal" href="collections.html#collections.MutableMapping" title="collections.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.MutableMapping</span></code></a> instead of <a class="reference internal" href="#UserDict.DictMixin" title="UserDict.DictMixin"><code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code></a>.</p>
<p>Note that DictMixin does not implement the <a class="reference internal" href="stdtypes.html#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewkeys()</span></code></a>,
<a class="reference internal" href="stdtypes.html#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewvalues()</span></code></a>, or <a class="reference internal" href="stdtypes.html#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewitems()</span></code></a> methods.</p>
</dd></dl>

</div>
<div class="section" id="module-UserList">
<span id="userlist-class-wrapper-for-list-objects"></span><h1>8.13. <a class="reference internal" href="#module-UserList" title="UserList: Class wrapper for list objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserList</span></code></a> — Class wrapper for list objects<a class="headerlink" href="#module-UserList" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>When Python 2.2 was released, many of the use cases for this class were
subsumed by the ability to subclass <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> directly.  However, a
handful of use cases remain.</p>
<p>This module provides a list-interface around an underlying data store.  By
default, that data store is a <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>; however, it can be used to wrap
a list-like interface around other objects (such as persistent storage).</p>
<p class="last">In addition, this class can be mixed-in with built-in classes using multiple
inheritance.  This can sometimes be useful.  For example, you can inherit
from <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> and <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> at the same time.  That would not be
possible with both a real <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> and a real <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
</div>
<p>This module defines a class that acts as a wrapper around list objects.  It is a
useful base class for your own list-like classes, which can inherit from them
and override existing methods or add new ones.  In this way one can add new
behaviors to lists.</p>
<p>The <a class="reference internal" href="#module-UserList" title="UserList: Class wrapper for list objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserList</span></code></a> module defines the <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> class:</p>
<dl class="class">
<dt id="UserList.UserList">
<em class="property">class </em><code class="descclassname">UserList.</code><code class="descname">UserList</code><span class="sig-paren">(</span><span class="optional">[</span><em>list</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#UserList.UserList" title="Permalink to this definition">¶</a></dt>
<dd><p>Class that simulates a list.  The instance’s contents are kept in a regular
list, which is accessible via the <a class="reference internal" href="#UserList.UserList.data" title="UserList.UserList.data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code></a> attribute of <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a>
instances.  The instance’s contents are initially set to a copy of <em>list</em>,
defaulting to the empty list <code class="docutils literal notranslate"><span class="pre">[]</span></code>.  <em>list</em> can be any iterable, e.g. a
real Python list or a <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> object.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> class has been moved to the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module in Python 3. The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt
imports when converting your sources to Python 3.</p>
</div>
</dd></dl>

<p>In addition to supporting the methods and operations of mutable sequences (see
section <a class="reference internal" href="stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>), <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> instances provide the following
attribute:</p>
<dl class="attribute">
<dt id="UserList.UserList.data">
<code class="descclassname">UserList.</code><code class="descname">data</code><a class="headerlink" href="#UserList.UserList.data" title="Permalink to this definition">¶</a></dt>
<dd><p>A real Python list object used to store the contents of the <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a>
class.</p>
</dd></dl>

<p><strong>Subclassing requirements:</strong> Subclasses of <a class="reference internal" href="#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a> are expected to
offer a constructor which can be called with either no arguments or one
argument.  List operations which return a new sequence attempt to create an
instance of the actual implementation class.  To do so, it assumes that the
constructor can be called with a single parameter, which is a sequence object
used as a data source.</p>
<p>If a derived class does not wish to comply with this requirement, all of the
special methods supported by this class will need to be overridden; please
consult the sources for information about the methods which need to be provided
in that case.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.0: </span>Python versions 1.5.2 and 1.6 also required that the constructor be callable
with no parameters, and offer a mutable <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code> attribute.  Earlier
versions of Python did not attempt to create instances of the derived class.</p>
</div>
</div>
<div class="section" id="module-UserString">
<span id="userstring-class-wrapper-for-string-objects"></span><h1>8.14. <a class="reference internal" href="#module-UserString" title="UserString: Class wrapper for string objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserString</span></code></a> — Class wrapper for string objects<a class="headerlink" href="#module-UserString" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> class from this module is available for backward
compatibility only.  If you are writing code that does not need to work with
versions of Python earlier than Python 2.2, please consider subclassing directly
from the built-in <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type instead of using <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> (there
is no built-in equivalent to <a class="reference internal" href="#UserString.MutableString" title="UserString.MutableString"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableString</span></code></a>).</p>
</div>
<p>This module defines a class that acts as a wrapper around string objects.  It is
a useful base class for your own string-like classes, which can inherit from
them and override existing methods or add new ones.  In this way one can add new
behaviors to strings.</p>
<p>It should be noted that these classes are highly inefficient compared to real
string or Unicode objects; this is especially the case for
<a class="reference internal" href="#UserString.MutableString" title="UserString.MutableString"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableString</span></code></a>.</p>
<p>The <a class="reference internal" href="#module-UserString" title="UserString: Class wrapper for string objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserString</span></code></a> module defines the following classes:</p>
<dl class="class">
<dt id="UserString.UserString">
<em class="property">class </em><code class="descclassname">UserString.</code><code class="descname">UserString</code><span class="sig-paren">(</span><span class="optional">[</span><em>sequence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#UserString.UserString" title="Permalink to this definition">¶</a></dt>
<dd><p>Class that simulates a string or a Unicode string object.  The instance’s
content is kept in a regular string or Unicode string object, which is
accessible via the <code class="xref py py-attr docutils literal notranslate"><span class="pre">data</span></code> attribute of <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> instances.  The
instance’s contents are initially set to a copy of <em>sequence</em>.  <em>sequence</em> can
be either a regular Python string or Unicode string, an instance of
<a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> (or a subclass) or an arbitrary sequence which can be
converted into a string using the built-in <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> class has been moved to the <a class="reference internal" href="collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module in Python 3. The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt
imports when converting your sources to Python 3.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="UserString.MutableString">
<em class="property">class </em><code class="descclassname">UserString.</code><code class="descname">MutableString</code><span class="sig-paren">(</span><span class="optional">[</span><em>sequence</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#UserString.MutableString" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is derived from the <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> above and redefines strings
to be <em>mutable</em>.  Mutable strings can’t be used as dictionary keys, because
dictionaries require <em>immutable</em> objects as keys.  The main intention of this
class is to serve as an educational example for inheritance and necessity to
remove (override) the <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method in order to trap attempts to use a
mutable object as dictionary key, which would be otherwise very error prone and
hard to track down.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.6: </span>The <a class="reference internal" href="#UserString.MutableString" title="UserString.MutableString"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableString</span></code></a> class has been removed in Python 3.</p>
</div>
</dd></dl>

<p>In addition to supporting the methods and operations of string and Unicode
objects (see section <a class="reference internal" href="stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a>), <a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> instances
provide the following attribute:</p>
<dl class="attribute">
<dt id="UserString.MutableString.data">
<code class="descclassname">MutableString.</code><code class="descname">data</code><a class="headerlink" href="#UserString.MutableString.data" title="Permalink to this definition">¶</a></dt>
<dd><p>A real Python string or Unicode object used to store the content of the
<a class="reference internal" href="#UserString.UserString" title="UserString.UserString"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserString</span></code></a> class.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></li>
<li><a class="reference internal" href="#module-UserList">8.13. <code class="docutils literal notranslate"><span class="pre">UserList</span></code> — Class wrapper for list objects</a></li>
<li><a class="reference internal" href="#module-UserString">8.14. <code class="docutils literal notranslate"><span class="pre">UserString</span></code> — Class wrapper for string objects</a></li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="weakref.html"
                        title="previous chapter">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="types.html"
                        title="next chapter">8.15. <code class="docutils literal notranslate"><span class="pre">types</span></code> — Names for built-in types</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/userdict.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="types.html" title="8.15. types — Names for built-in types"
             >next</a> |</li>
        <li class="right" >
          <a href="weakref.html" title="8.11. weakref — Weak references"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\%��".".html/library/uu.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>18.16. uu — Encode and decode uuencode files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19. Structured Markup Processing Tools" href="markup.html" />
    <link rel="prev" title="18.15. quopri — Encode and decode MIME quoted-printable data" href="quopri.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/uu.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="markup.html" title="19. Structured Markup Processing Tools"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="quopri.html" title="18.15. quopri — Encode and decode MIME quoted-printable data"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" accesskey="U">18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-uu">
<span id="uu-encode-and-decode-uuencode-files"></span><h1>18.16. <a class="reference internal" href="#module-uu" title="uu: Encode and decode files in uuencode format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">uu</span></code></a> — Encode and decode uuencode files<a class="headerlink" href="#module-uu" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/uu.py">Lib/uu.py</a></p>
<hr class="docutils" />
<p>This module encodes and decodes files in uuencode format, allowing arbitrary
binary data to be transferred over ASCII-only connections. Wherever a file
argument is expected, the methods accept a file-like object.  For backwards
compatibility, a string containing a pathname is also accepted, and the
corresponding file will be opened for reading and writing; the pathname <code class="docutils literal notranslate"><span class="pre">'-'</span></code>
is understood to mean the standard input or output.  However, this interface is
deprecated; it’s better for the caller to open the file itself, and be sure
that, when required, the mode is <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> or <code class="docutils literal notranslate"><span class="pre">'wb'</span></code> on Windows.</p>
<p id="index-0">This code was contributed by Lance Ellinghouse, and modified by Jack Jansen.</p>
<p>The <a class="reference internal" href="#module-uu" title="uu: Encode and decode files in uuencode format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">uu</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="uu.encode">
<code class="descclassname">uu.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>in_file</em>, <em>out_file</em><span class="optional">[</span>, <em>name</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#uu.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Uuencode file <em>in_file</em> into file <em>out_file</em>.  The uuencoded file will have the
header specifying <em>name</em> and <em>mode</em> as the defaults for the results of decoding
the file. The default defaults are taken from <em>in_file</em>, or <code class="docutils literal notranslate"><span class="pre">'-'</span></code> and <code class="docutils literal notranslate"><span class="pre">0666</span></code>
respectively.</p>
</dd></dl>

<dl class="function">
<dt id="uu.decode">
<code class="descclassname">uu.</code><code class="descname">decode</code><span class="sig-paren">(</span><em>in_file</em><span class="optional">[</span>, <em>out_file</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>quiet</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#uu.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>This call decodes uuencoded file <em>in_file</em> placing the result on file
<em>out_file</em>. If <em>out_file</em> is a pathname, <em>mode</em> is used to set the permission
bits if the file must be created. Defaults for <em>out_file</em> and <em>mode</em> are taken
from the uuencode header.  However, if the file specified in the header already
exists, a <a class="reference internal" href="#uu.Error" title="uu.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">uu.Error</span></code></a> is raised.</p>
<p><a class="reference internal" href="#uu.decode" title="uu.decode"><code class="xref py py-func docutils literal notranslate"><span class="pre">decode()</span></code></a> may print a warning to standard error if the input was produced
by an incorrect uuencoder and Python could recover from that error.  Setting
<em>quiet</em> to a true value silences this warning.</p>
</dd></dl>

<dl class="exception">
<dt id="uu.Error">
<em class="property">exception </em><code class="descclassname">uu.</code><code class="descname">Error</code><a class="headerlink" href="#uu.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>, this can be raised by <a class="reference internal" href="#uu.decode" title="uu.decode"><code class="xref py py-func docutils literal notranslate"><span class="pre">uu.decode()</span></code></a> under
various situations, such as described above, but also including a badly
formatted header, or truncated input file.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="binascii.html#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a></dt>
<dd>Support module containing ASCII-to-binary and binary-to-ASCII conversions.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="quopri.html"
                        title="previous chapter">18.15. <code class="docutils literal notranslate"><span class="pre">quopri</span></code> — Encode and decode MIME quoted-printable data</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="markup.html"
                        title="next chapter">19. Structured Markup Processing Tools</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/uu.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="markup.html" title="19. Structured Markup Processing Tools"
             >next</a> |</li>
        <li class="right" >
          <a href="quopri.html" title="18.15. quopri — Encode and decode MIME quoted-printable data"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="netdata.html" >18. Internet Data Handling</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\?zZ7�u�uhtml/library/uuid.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.15. uuid — UUID objects according to RFC 4122 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.16. urlparse — Parse URLs into components" href="urlparse.html" />
    <link rel="prev" title="20.14. telnetlib — Telnet client" href="telnetlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/uuid.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urlparse.html" title="20.16. urlparse — Parse URLs into components"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="telnetlib.html" title="20.14. telnetlib — Telnet client"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-uuid">
<span id="uuid-uuid-objects-according-to-rfc-4122"></span><h1>20.15. <a class="reference internal" href="#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> — UUID objects according to RFC 4122<a class="headerlink" href="#module-uuid" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>This module provides immutable <a class="reference internal" href="#uuid.UUID" title="uuid.UUID"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> objects (the <a class="reference internal" href="#uuid.UUID" title="uuid.UUID"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> class)
and the functions <a class="reference internal" href="#uuid.uuid1" title="uuid.uuid1"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid1()</span></code></a>, <a class="reference internal" href="#uuid.uuid3" title="uuid.uuid3"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid3()</span></code></a>, <a class="reference internal" href="#uuid.uuid4" title="uuid.uuid4"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid4()</span></code></a>, <a class="reference internal" href="#uuid.uuid5" title="uuid.uuid5"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid5()</span></code></a> for
generating version 1, 3, 4, and 5 UUIDs as specified in <span class="target" id="index-0"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a>.</p>
<p>If all you want is a unique ID, you should probably call <a class="reference internal" href="#uuid.uuid1" title="uuid.uuid1"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid1()</span></code></a> or
<a class="reference internal" href="#uuid.uuid4" title="uuid.uuid4"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid4()</span></code></a>.  Note that <a class="reference internal" href="#uuid.uuid1" title="uuid.uuid1"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid1()</span></code></a> may compromise privacy since it creates
a UUID containing the computer’s network address.  <a class="reference internal" href="#uuid.uuid4" title="uuid.uuid4"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid4()</span></code></a> creates a
random UUID.</p>
<dl class="class">
<dt id="uuid.UUID">
<em class="property">class </em><code class="descclassname">uuid.</code><code class="descname">UUID</code><span class="sig-paren">(</span><span class="optional">[</span><em>hex</em><span class="optional">[</span>, <em>bytes</em><span class="optional">[</span>, <em>bytes_le</em><span class="optional">[</span>, <em>fields</em><span class="optional">[</span>, <em>int</em><span class="optional">[</span>, <em>version</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#uuid.UUID" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a UUID from either a string of 32 hexadecimal digits, a string of 16
bytes in big-endian order as the <em>bytes</em> argument, a string of 16 bytes in
little-endian order as the <em>bytes_le</em> argument, a tuple of six integers
(32-bit <em>time_low</em>, 16-bit <em>time_mid</em>, 16-bit <em>time_hi_version</em>,
8-bit <em>clock_seq_hi_variant</em>, 8-bit <em>clock_seq_low</em>, 48-bit <em>node</em>) as the
<em>fields</em> argument, or a single 128-bit integer as the <em>int</em> argument.
When a string of hex digits is given, curly braces, hyphens,
and a URN prefix are all optional.  For example, these
expressions all yield the same UUID:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">UUID</span><span class="p">(</span><span class="s1">&#39;{12345678-1234-5678-1234-567812345678}&#39;</span><span class="p">)</span>
<span class="n">UUID</span><span class="p">(</span><span class="s1">&#39;12345678123456781234567812345678&#39;</span><span class="p">)</span>
<span class="n">UUID</span><span class="p">(</span><span class="s1">&#39;urn:uuid:12345678-1234-5678-1234-567812345678&#39;</span><span class="p">)</span>
<span class="n">UUID</span><span class="p">(</span><span class="nb">bytes</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\x12\x34\x56\x78</span><span class="s1">&#39;</span><span class="o">*</span><span class="mi">4</span><span class="p">)</span>
<span class="n">UUID</span><span class="p">(</span><span class="n">bytes_le</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\x78\x56\x34\x12\x34\x12\x78\x56</span><span class="s1">&#39;</span> <span class="o">+</span>
              <span class="s1">&#39;</span><span class="se">\x12\x34\x56\x78\x12\x34\x56\x78</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="n">UUID</span><span class="p">(</span><span class="n">fields</span><span class="o">=</span><span class="p">(</span><span class="mh">0x12345678</span><span class="p">,</span> <span class="mh">0x1234</span><span class="p">,</span> <span class="mh">0x5678</span><span class="p">,</span> <span class="mh">0x12</span><span class="p">,</span> <span class="mh">0x34</span><span class="p">,</span> <span class="mh">0x567812345678</span><span class="p">))</span>
<span class="n">UUID</span><span class="p">(</span><span class="nb">int</span><span class="o">=</span><span class="mh">0x12345678123456781234567812345678</span><span class="p">)</span>
</pre></div>
</div>
<p>Exactly one of <em>hex</em>, <em>bytes</em>, <em>bytes_le</em>, <em>fields</em>, or <em>int</em> must be given.
The <em>version</em> argument is optional; if given, the resulting UUID will have its
variant and version number set according to RFC 4122, overriding bits in the
given <em>hex</em>, <em>bytes</em>, <em>bytes_le</em>, <em>fields</em>, or <em>int</em>.</p>
</dd></dl>

<p><a class="reference internal" href="#uuid.UUID" title="uuid.UUID"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a> instances have these read-only attributes:</p>
<dl class="attribute">
<dt id="uuid.UUID.bytes">
<code class="descclassname">UUID.</code><code class="descname">bytes</code><a class="headerlink" href="#uuid.UUID.bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID as a 16-byte string (containing the six integer fields in big-endian
byte order).</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.bytes_le">
<code class="descclassname">UUID.</code><code class="descname">bytes_le</code><a class="headerlink" href="#uuid.UUID.bytes_le" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID as a 16-byte string (with <em>time_low</em>, <em>time_mid</em>, and <em>time_hi_version</em>
in little-endian byte order).</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.fields">
<code class="descclassname">UUID.</code><code class="descname">fields</code><a class="headerlink" href="#uuid.UUID.fields" title="Permalink to this definition">¶</a></dt>
<dd><p>A tuple of the six integer fields of the UUID, which are also available as six
individual attributes and two derived attributes:</p>
<table border="1" class="docutils">
<colgroup>
<col width="49%" />
<col width="51%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Field</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">time_low</span></code></td>
<td>the first 32 bits of the UUID</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">time_mid</span></code></td>
<td>the next 16 bits of the UUID</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">time_hi_version</span></code></td>
<td>the next 16 bits of the UUID</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">clock_seq_hi_variant</span></code></td>
<td>the next 8 bits of the UUID</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">clock_seq_low</span></code></td>
<td>the next 8 bits of the UUID</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">node</span></code></td>
<td>the last 48 bits of the UUID</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="time.html#module-time" title="time: Time access and conversions."><code class="xref py py-attr docutils literal notranslate"><span class="pre">time</span></code></a></td>
<td>the 60-bit timestamp</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">clock_seq</span></code></td>
<td>the 14-bit sequence number</td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.hex">
<code class="descclassname">UUID.</code><code class="descname">hex</code><a class="headerlink" href="#uuid.UUID.hex" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID as a 32-character hexadecimal string.</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.int">
<code class="descclassname">UUID.</code><code class="descname">int</code><a class="headerlink" href="#uuid.UUID.int" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID as a 128-bit integer.</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.urn">
<code class="descclassname">UUID.</code><code class="descname">urn</code><a class="headerlink" href="#uuid.UUID.urn" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID as a URN as specified in RFC 4122.</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.variant">
<code class="descclassname">UUID.</code><code class="descname">variant</code><a class="headerlink" href="#uuid.UUID.variant" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID variant, which determines the internal layout of the UUID. This will be
one of the constants <a class="reference internal" href="#uuid.RESERVED_NCS" title="uuid.RESERVED_NCS"><code class="xref py py-const docutils literal notranslate"><span class="pre">RESERVED_NCS</span></code></a>, <a class="reference internal" href="#uuid.RFC_4122" title="uuid.RFC_4122"><code class="xref py py-const docutils literal notranslate"><span class="pre">RFC_4122</span></code></a>,
<a class="reference internal" href="#uuid.RESERVED_MICROSOFT" title="uuid.RESERVED_MICROSOFT"><code class="xref py py-const docutils literal notranslate"><span class="pre">RESERVED_MICROSOFT</span></code></a>, or <a class="reference internal" href="#uuid.RESERVED_FUTURE" title="uuid.RESERVED_FUTURE"><code class="xref py py-const docutils literal notranslate"><span class="pre">RESERVED_FUTURE</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="uuid.UUID.version">
<code class="descclassname">UUID.</code><code class="descname">version</code><a class="headerlink" href="#uuid.UUID.version" title="Permalink to this definition">¶</a></dt>
<dd><p>The UUID version number (1 through 5, meaningful only when the variant is
<a class="reference internal" href="#uuid.RFC_4122" title="uuid.RFC_4122"><code class="xref py py-const docutils literal notranslate"><span class="pre">RFC_4122</span></code></a>).</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module defines the following functions:</p>
<dl class="function">
<dt id="uuid.getnode">
<code class="descclassname">uuid.</code><code class="descname">getnode</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#uuid.getnode" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the hardware address as a 48-bit positive integer.  The first time this
runs, it may launch a separate program, which could be quite slow.  If all
attempts to obtain the hardware address fail, we choose a random 48-bit number
with its eighth bit set to 1 as recommended in RFC 4122.  “Hardware address”
means the MAC address of a network interface, and on a machine with multiple
network interfaces the MAC address of any one of them may be returned.</p>
</dd></dl>

<span class="target" id="index-1"></span><dl class="function">
<dt id="uuid.uuid1">
<code class="descclassname">uuid.</code><code class="descname">uuid1</code><span class="sig-paren">(</span><span class="optional">[</span><em>node</em><span class="optional">[</span>, <em>clock_seq</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#uuid.uuid1" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a UUID from a host ID, sequence number, and the current time. If <em>node</em>
is not given, <a class="reference internal" href="#uuid.getnode" title="uuid.getnode"><code class="xref py py-func docutils literal notranslate"><span class="pre">getnode()</span></code></a> is used to obtain the hardware address. If
<em>clock_seq</em> is given, it is used as the sequence number; otherwise a random
14-bit sequence number is chosen.</p>
</dd></dl>

<span class="target" id="index-2"></span><dl class="function">
<dt id="uuid.uuid3">
<code class="descclassname">uuid.</code><code class="descname">uuid3</code><span class="sig-paren">(</span><em>namespace</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#uuid.uuid3" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a UUID based on the MD5 hash of a namespace identifier (which is a
UUID) and a name (which is a string).</p>
</dd></dl>

<span class="target" id="index-3"></span><dl class="function">
<dt id="uuid.uuid4">
<code class="descclassname">uuid.</code><code class="descname">uuid4</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#uuid.uuid4" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a random UUID.</p>
</dd></dl>

<span class="target" id="index-4"></span><dl class="function">
<dt id="uuid.uuid5">
<code class="descclassname">uuid.</code><code class="descname">uuid5</code><span class="sig-paren">(</span><em>namespace</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#uuid.uuid5" title="Permalink to this definition">¶</a></dt>
<dd><p>Generate a UUID based on the SHA-1 hash of a namespace identifier (which is a
UUID) and a name (which is a string).</p>
</dd></dl>

<p id="index-5">The <a class="reference internal" href="#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module defines the following namespace identifiers for use with
<a class="reference internal" href="#uuid.uuid3" title="uuid.uuid3"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid3()</span></code></a> or <a class="reference internal" href="#uuid.uuid5" title="uuid.uuid5"><code class="xref py py-func docutils literal notranslate"><span class="pre">uuid5()</span></code></a>.</p>
<dl class="data">
<dt id="uuid.NAMESPACE_DNS">
<code class="descclassname">uuid.</code><code class="descname">NAMESPACE_DNS</code><a class="headerlink" href="#uuid.NAMESPACE_DNS" title="Permalink to this definition">¶</a></dt>
<dd><p>When this namespace is specified, the <em>name</em> string is a fully-qualified domain
name.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.NAMESPACE_URL">
<code class="descclassname">uuid.</code><code class="descname">NAMESPACE_URL</code><a class="headerlink" href="#uuid.NAMESPACE_URL" title="Permalink to this definition">¶</a></dt>
<dd><p>When this namespace is specified, the <em>name</em> string is a URL.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.NAMESPACE_OID">
<code class="descclassname">uuid.</code><code class="descname">NAMESPACE_OID</code><a class="headerlink" href="#uuid.NAMESPACE_OID" title="Permalink to this definition">¶</a></dt>
<dd><p>When this namespace is specified, the <em>name</em> string is an ISO OID.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.NAMESPACE_X500">
<code class="descclassname">uuid.</code><code class="descname">NAMESPACE_X500</code><a class="headerlink" href="#uuid.NAMESPACE_X500" title="Permalink to this definition">¶</a></dt>
<dd><p>When this namespace is specified, the <em>name</em> string is an X.500 DN in DER or a
text output format.</p>
</dd></dl>

<p>The <a class="reference internal" href="#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module defines the following constants for the possible values
of the <code class="xref py py-attr docutils literal notranslate"><span class="pre">variant</span></code> attribute:</p>
<dl class="data">
<dt id="uuid.RESERVED_NCS">
<code class="descclassname">uuid.</code><code class="descname">RESERVED_NCS</code><a class="headerlink" href="#uuid.RESERVED_NCS" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for NCS compatibility.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.RFC_4122">
<code class="descclassname">uuid.</code><code class="descname">RFC_4122</code><a class="headerlink" href="#uuid.RFC_4122" title="Permalink to this definition">¶</a></dt>
<dd><p>Specifies the UUID layout given in <span class="target" id="index-6"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a>.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.RESERVED_MICROSOFT">
<code class="descclassname">uuid.</code><code class="descname">RESERVED_MICROSOFT</code><a class="headerlink" href="#uuid.RESERVED_MICROSOFT" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for Microsoft compatibility.</p>
</dd></dl>

<dl class="data">
<dt id="uuid.RESERVED_FUTURE">
<code class="descclassname">uuid.</code><code class="descname">RESERVED_FUTURE</code><a class="headerlink" href="#uuid.RESERVED_FUTURE" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for future definition.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a> - A Universally Unique IDentifier (UUID) URN Namespace</dt>
<dd>This specification defines a Uniform Resource Name namespace for UUIDs, the
internal format of UUIDs, and methods of generating UUIDs.</dd>
</dl>
</div>
<div class="section" id="example">
<span id="uuid-example"></span><h2>20.15.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>Here are some examples of typical usage of the <a class="reference internal" href="#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">uuid</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID based on the host ID and current time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid1</span><span class="p">()</span>
<span class="go">UUID(&#39;a8098c1a-f86e-11da-bd1a-00112444be1e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using an MD5 hash of a namespace UUID and a name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid3</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;6fa459ea-ee8a-3ca4-894e-db77e160355e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a random UUID</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">()</span>
<span class="go">UUID(&#39;16fd2706-8baf-433b-82eb-8c7fada847da&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using a SHA-1 hash of a namespace UUID and a name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid5</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;886313e1-3b8a-5372-9b90-0c9aee199e5d&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID from a string of hex digits (braces and hyphens ignored)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">uuid</span><span class="o">.</span><span class="n">UUID</span><span class="p">(</span><span class="s1">&#39;{00010203-0405-0607-0809-0a0b0c0d0e0f}&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># convert a UUID to a string of hex digits in standard form</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="go">&#39;00010203-0405-0607-0809-0a0b0c0d0e0f&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># get the raw 16 bytes of the UUID</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">bytes</span>
<span class="go">&#39;\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID from a 16-byte string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">UUID</span><span class="p">(</span><span class="nb">bytes</span><span class="o">=</span><span class="n">x</span><span class="o">.</span><span class="n">bytes</span><span class="p">)</span>
<span class="go">UUID(&#39;00010203-0405-0607-0809-0a0b0c0d0e0f&#39;)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a><ul>
<li><a class="reference internal" href="#example">20.15.1. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="telnetlib.html"
                        title="previous chapter">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="urlparse.html"
                        title="next chapter">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/uuid.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urlparse.html" title="20.16. urlparse — Parse URLs into components"
             >next</a> |</li>
        <li class="right" >
          <a href="telnetlib.html" title="20.14. telnetlib — Telnet client"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����html/library/warnings.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>28.6. warnings — Warning control &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="28.7. contextlib — Utilities for with-statement contexts" href="contextlib.html" />
    <link rel="prev" title="28.5. __main__ — Top-level script environment" href="__main__.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/warnings.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="__main__.html" title="28.5. __main__ — Top-level script environment"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" accesskey="U">28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="warnings-warning-control">
<h1>28.6. <a class="reference internal" href="#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> — Warning control<a class="headerlink" href="#warnings-warning-control" title="Permalink to this headline">¶</a></h1>
<span class="target" id="module-warnings"><span id="index-0"></span></span><div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/warnings.py">Lib/warnings.py</a></p>
<hr class="docutils" />
<p>Warning messages are typically issued in situations where it is useful to alert
the user of some condition in a program, where that condition (normally) doesn’t
warrant raising an exception and terminating the program.  For example, one
might want to issue a warning when a program uses an obsolete module.</p>
<p>Python programmers issue warnings by calling the <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a> function defined
in this module.  (C programmers use <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a>; see
<a class="reference internal" href="../c-api/exceptions.html#exceptionhandling"><span class="std std-ref">Exception Handling</span></a> for details).</p>
<p>Warning messages are normally written to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>, but their disposition
can be changed flexibly, from ignoring all warnings to turning them into
exceptions.  The disposition of warnings can vary based on the warning category
(see below), the text of the warning message, and the source location where it
is issued.  Repetitions of a particular warning for the same source location are
typically suppressed.</p>
<p>There are two stages in warning control: first, each time a warning is issued, a
determination is made whether a message should be issued or not; next, if a
message is to be issued, it is formatted and printed using a user-settable hook.</p>
<p>The determination whether to issue a warning message is controlled by the
warning filter, which is a sequence of matching rules and actions. Rules can be
added to the filter by calling <a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a> and reset to its default
state by calling <a class="reference internal" href="#warnings.resetwarnings" title="warnings.resetwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">resetwarnings()</span></code></a>.</p>
<p>The printing of warning messages is done by calling <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a>, which
may be overridden; the default implementation of this function formats the
message by calling <a class="reference internal" href="#warnings.formatwarning" title="warnings.formatwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code></a>, which is also available for use by
custom implementations.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="logging.html#logging.captureWarnings" title="logging.captureWarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">logging.captureWarnings()</span></code></a> allows you to handle all warnings with
the standard logging infrastructure.</p>
</div>
<div class="section" id="warning-categories">
<span id="id1"></span><h2>28.6.1. Warning Categories<a class="headerlink" href="#warning-categories" title="Permalink to this headline">¶</a></h2>
<p>There are a number of built-in exceptions that represent warning categories.
This categorization is useful to be able to filter out groups of warnings.  The
following warnings category classes are currently defined:</p>
<table border="1" class="docutils">
<colgroup>
<col width="42%" />
<col width="58%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Class</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a></td>
<td>This is the base class of all warning
category classes.  It is a subclass of
<a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="exceptions.html#exceptions.UserWarning" title="exceptions.UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a></td>
<td>The default category for <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a>.</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a></td>
<td>Base category for warnings about deprecated
features (ignored by default).</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a></td>
<td>Base category for warnings about dubious
syntactic features.</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="exceptions.html#exceptions.RuntimeWarning" title="exceptions.RuntimeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeWarning</span></code></a></td>
<td>Base category for warnings about dubious
runtime features.</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a></td>
<td>Base category for warnings about constructs
that will change semantically in the future.</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a></td>
<td>Base category for warnings about features
that will be deprecated in the future
(ignored by default).</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="exceptions.html#exceptions.ImportWarning" title="exceptions.ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a></td>
<td>Base category for warnings triggered during
the process of importing a module (ignored by
default).</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="exceptions.html#exceptions.UnicodeWarning" title="exceptions.UnicodeWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeWarning</span></code></a></td>
<td>Base category for warnings related to
Unicode.</td>
</tr>
</tbody>
</table>
<p>While these are technically built-in exceptions, they are documented here,
because conceptually they belong to the warnings mechanism.</p>
<p>User code can define additional warning categories by subclassing one of the
standard warning categories.  A warning category must always be a subclass of
the <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> class.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span><a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> is ignored by default.</p>
</div>
</div>
<div class="section" id="the-warnings-filter">
<span id="warning-filter"></span><h2>28.6.2. The Warnings Filter<a class="headerlink" href="#the-warnings-filter" title="Permalink to this headline">¶</a></h2>
<p>The warnings filter controls whether warnings are ignored, displayed, or turned
into errors (raising an exception).</p>
<p>Conceptually, the warnings filter maintains an ordered list of filter
specifications; any specific warning is matched against each filter
specification in the list in turn until a match is found; the match determines
the disposition of the match.  Each entry is a tuple of the form (<em>action</em>,
<em>message</em>, <em>category</em>, <em>module</em>, <em>lineno</em>), where:</p>
<ul>
<li><p class="first"><em>action</em> is one of the following strings:</p>
<table border="1" class="docutils">
<colgroup>
<col width="25%" />
<col width="75%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Value</th>
<th class="head">Disposition</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;error&quot;</span></code></td>
<td>turn matching warnings into exceptions</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&quot;ignore&quot;</span></code></td>
<td>never print matching warnings</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;always&quot;</span></code></td>
<td>always print matching warnings</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code></td>
<td>print the first occurrence of matching
warnings for each location where the warning
is issued</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&quot;module&quot;</span></code></td>
<td>print the first occurrence of matching
warnings for each module where the warning
is issued</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&quot;once&quot;</span></code></td>
<td>print only the first occurrence of matching
warnings, regardless of location</td>
</tr>
</tbody>
</table>
</li>
<li><p class="first"><em>message</em> is a string containing a regular expression that the start of
the warning message must match.  The expression is compiled to always be
case-insensitive.</p>
</li>
<li><p class="first"><em>category</em> is a class (a subclass of <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a>) of which the warning
category must be a subclass in order to match.</p>
</li>
<li><p class="first"><em>module</em> is a string containing a regular expression that the module name must
match.  The expression is compiled to be case-sensitive.</p>
</li>
<li><p class="first"><em>lineno</em> is an integer that the line number where the warning occurred must
match, or <code class="docutils literal notranslate"><span class="pre">0</span></code> to match all line numbers.</p>
</li>
</ul>
<p>Since the <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> class is derived from the built-in <a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>
class, to turn a warning into an error we simply raise <code class="docutils literal notranslate"><span class="pre">category(message)</span></code>.</p>
<p>The warnings filter is initialized by <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> options passed to the Python
interpreter command line.  The interpreter saves the arguments for all
<a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> options without interpretation in <code class="docutils literal notranslate"><span class="pre">sys.warnoptions</span></code>; the
<a class="reference internal" href="#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module parses these when it is first imported (invalid options
are ignored, after printing a message to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>).</p>
<div class="section" id="default-warning-filters">
<h3>28.6.2.1. Default Warning Filters<a class="headerlink" href="#default-warning-filters" title="Permalink to this headline">¶</a></h3>
<p>By default, Python installs several warning filters, which can be overridden by
the command-line options passed to <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> and calls to
<a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>.</p>
<ul class="simple">
<li><a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and <a class="reference internal" href="exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a>, and
<a class="reference internal" href="exceptions.html#exceptions.ImportWarning" title="exceptions.ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a> are ignored.</li>
<li><code class="xref py py-exc docutils literal notranslate"><span class="pre">BytesWarning</span></code> is ignored unless the <a class="reference internal" href="../using/cmdline.html#cmdoption-b"><code class="xref std std-option docutils literal notranslate"><span class="pre">-b</span></code></a> option is given once or
twice; in this case this warning is either printed (<code class="docutils literal notranslate"><span class="pre">-b</span></code>) or turned into an
exception (<code class="docutils literal notranslate"><span class="pre">-bb</span></code>).</li>
</ul>
</div>
</div>
<div class="section" id="temporarily-suppressing-warnings">
<span id="warning-suppress"></span><h2>28.6.3. Temporarily Suppressing Warnings<a class="headerlink" href="#temporarily-suppressing-warnings" title="Permalink to this headline">¶</a></h2>
<p>If you are using code that you know will raise a warning, such as a deprecated
function, but do not want to see the warning, then it is possible to suppress
the warning using the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context manager:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>

<span class="k">def</span> <span class="nf">fxn</span><span class="p">():</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;deprecated&quot;</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>

<span class="k">with</span> <span class="n">warnings</span><span class="o">.</span><span class="n">catch_warnings</span><span class="p">():</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;ignore&quot;</span><span class="p">)</span>
    <span class="n">fxn</span><span class="p">()</span>
</pre></div>
</div>
<p>While within the context manager all warnings will simply be ignored. This
allows you to use known-deprecated code without having to see the warning while
not suppressing the warning for other code that might not be aware of its use
of deprecated code.  Note: this can only be guaranteed in a single-threaded
application. If two or more threads use the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context
manager at the same time, the behavior is undefined.</p>
</div>
<div class="section" id="testing-warnings">
<span id="warning-testing"></span><h2>28.6.4. Testing Warnings<a class="headerlink" href="#testing-warnings" title="Permalink to this headline">¶</a></h2>
<p>To test warnings raised by code, use the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context
manager. With it you can temporarily mutate the warnings filter to facilitate
your testing. For instance, do the following to capture all raised warnings to
check:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>

<span class="k">def</span> <span class="nf">fxn</span><span class="p">():</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;deprecated&quot;</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>

<span class="k">with</span> <span class="n">warnings</span><span class="o">.</span><span class="n">catch_warnings</span><span class="p">(</span><span class="n">record</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span> <span class="k">as</span> <span class="n">w</span><span class="p">:</span>
    <span class="c1"># Cause all warnings to always be triggered.</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;always&quot;</span><span class="p">)</span>
    <span class="c1"># Trigger a warning.</span>
    <span class="n">fxn</span><span class="p">()</span>
    <span class="c1"># Verify some things</span>
    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span>
    <span class="k">assert</span> <span class="nb">issubclass</span><span class="p">(</span><span class="n">w</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">category</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">)</span>
    <span class="k">assert</span> <span class="s2">&quot;deprecated&quot;</span> <span class="ow">in</span> <span class="nb">str</span><span class="p">(</span><span class="n">w</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">message</span><span class="p">)</span>
</pre></div>
</div>
<p>One can also cause all warnings to be exceptions by using <code class="docutils literal notranslate"><span class="pre">error</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">always</span></code>. One thing to be aware of is that if a warning has already been
raised because of a <code class="docutils literal notranslate"><span class="pre">once</span></code>/<code class="docutils literal notranslate"><span class="pre">default</span></code> rule, then no matter what filters are
set the warning will not be seen again unless the warnings registry related to
the warning has been cleared.</p>
<p>Once the context manager exits, the warnings filter is restored to its state
when the context was entered. This prevents tests from changing the warnings
filter in unexpected ways between tests and leading to indeterminate test
results. The <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function in the module is also restored to
its original value.  Note: this can only be guaranteed in a single-threaded
application. If two or more threads use the <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> context
manager at the same time, the behavior is undefined.</p>
<p>When testing multiple operations that raise the same kind of warning, it
is important to test them in a manner that confirms each operation is raising
a new warning (e.g. set warnings to be raised as exceptions and check the
operations raise exceptions, check that the length of the warning list
continues to increase after each operation, or else delete the previous
entries from the warnings list before each new operation).</p>
</div>
<div class="section" id="updating-code-for-new-versions-of-python">
<h2>28.6.5. Updating Code For New Versions of Python<a class="headerlink" href="#updating-code-for-new-versions-of-python" title="Permalink to this headline">¶</a></h2>
<p>Warnings that are only of interest to the developer are ignored by default. As
such you should make sure to test your code with typically ignored warnings
made visible. You can do this from the command-line by passing <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code></a>
to the interpreter (this is shorthand for <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">default</span></code>).  This enables
default handling for all warnings, including those that are ignored by default.
To change what action is taken for encountered warnings you simply change what
argument is passed to <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a>, e.g. <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span> <span class="pre">error</span></code>. See the
<a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> flag for more details on what is possible.</p>
<p>To programmatically do the same as <code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code>, use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s1">&#39;default&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Make sure to execute this code as soon as possible. This prevents the
registering of what warnings have been raised from unexpectedly influencing how
future warnings are treated.</p>
<p>Having certain warnings ignored by default is done to prevent a user from
seeing warnings that are only of interest to the developer. As you do not
necessarily have control over what interpreter a user uses to run their code,
it is possible that a new version of Python will be released between your
release cycles.  The new interpreter release could trigger new warnings in your
code that were not there in an older interpreter, e.g.
<a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> for a module that you are using. While you as a
developer want to be notified that your code is using a deprecated module, to a
user this information is essentially noise and provides no benefit to them.</p>
</div>
<div class="section" id="available-functions">
<span id="warning-functions"></span><h2>28.6.6. Available Functions<a class="headerlink" href="#available-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="warnings.warn">
<code class="descclassname">warnings.</code><code class="descname">warn</code><span class="sig-paren">(</span><em>message</em><span class="optional">[</span>, <em>category</em><span class="optional">[</span>, <em>stacklevel</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.warn" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning, or maybe ignore it or raise an exception.  The <em>category</em>
argument, if given, must be a warning category class (see above); it defaults to
<a class="reference internal" href="exceptions.html#exceptions.UserWarning" title="exceptions.UserWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UserWarning</span></code></a>.  Alternatively <em>message</em> can be a <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> instance,
in which case <em>category</em> will be ignored and <code class="docutils literal notranslate"><span class="pre">message.__class__</span></code> will be used.
In this case the message text will be <code class="docutils literal notranslate"><span class="pre">str(message)</span></code>. This function raises an
exception if the particular warning issued is changed into an error by the
warnings filter see above.  The <em>stacklevel</em> argument can be used by wrapper
functions written in Python, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">deprecation</span><span class="p">(</span><span class="n">message</span><span class="p">):</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="ne">DeprecationWarning</span><span class="p">,</span> <span class="n">stacklevel</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
<p>This makes the warning refer to <code class="xref py py-func docutils literal notranslate"><span class="pre">deprecation()</span></code>’s caller, rather than to the
source of <code class="xref py py-func docutils literal notranslate"><span class="pre">deprecation()</span></code> itself (since the latter would defeat the purpose
of the warning message).</p>
</dd></dl>

<dl class="function">
<dt id="warnings.warn_explicit">
<code class="descclassname">warnings.</code><code class="descname">warn_explicit</code><span class="sig-paren">(</span><em>message</em>, <em>category</em>, <em>filename</em>, <em>lineno</em><span class="optional">[</span>, <em>module</em><span class="optional">[</span>, <em>registry</em><span class="optional">[</span>, <em>module_globals</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.warn_explicit" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a low-level interface to the functionality of <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a>, passing in
explicitly the message, category, filename and line number, and optionally the
module name and the registry (which should be the <code class="docutils literal notranslate"><span class="pre">__warningregistry__</span></code>
dictionary of the module).  The module name defaults to the filename with
<code class="docutils literal notranslate"><span class="pre">.py</span></code> stripped; if no registry is passed, the warning is never suppressed.
<em>message</em> must be a string and <em>category</em> a subclass of <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> or
<em>message</em> may be a <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a> instance, in which case <em>category</em> will be
ignored.</p>
<p><em>module_globals</em>, if supplied, should be the global namespace in use by the code
for which the warning is issued.  (This argument is used to support displaying
source for modules found in zipfiles or other non-filesystem import
sources).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Added the <em>module_globals</em> parameter.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="warnings.warnpy3k">
<code class="descclassname">warnings.</code><code class="descname">warnpy3k</code><span class="sig-paren">(</span><em>message</em><span class="optional">[</span>, <em>category</em><span class="optional">[</span>, <em>stacklevel</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.warnpy3k" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning related to Python 3.x deprecation. Warnings are only shown
when Python is started with the -3 option. Like <a class="reference internal" href="#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warn()</span></code></a> <em>message</em> must
be a string and <em>category</em> a subclass of <a class="reference internal" href="exceptions.html#exceptions.Warning" title="exceptions.Warning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Warning</span></code></a>. <a class="reference internal" href="#warnings.warnpy3k" title="warnings.warnpy3k"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnpy3k()</span></code></a>
is using <a class="reference internal" href="exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> as default warning class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="warnings.showwarning">
<code class="descclassname">warnings.</code><code class="descname">showwarning</code><span class="sig-paren">(</span><em>message</em>, <em>category</em>, <em>filename</em>, <em>lineno</em><span class="optional">[</span>, <em>file</em><span class="optional">[</span>, <em>line</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.showwarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Write a warning to a file.  The default implementation calls
<code class="docutils literal notranslate"><span class="pre">formatwarning(message,</span> <span class="pre">category,</span> <span class="pre">filename,</span> <span class="pre">lineno,</span> <span class="pre">line)</span></code> and writes the
resulting string to <em>file</em>, which defaults to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.  You may replace
this function with an alternative implementation by assigning to
<code class="docutils literal notranslate"><span class="pre">warnings.showwarning</span></code>.
<em>line</em> is a line of source code to be included in the warning
message; if <em>line</em> is not supplied, <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> will
try to read the line specified by <em>filename</em> and <em>lineno</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The <em>line</em> argument is required to be supported.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="warnings.formatwarning">
<code class="descclassname">warnings.</code><code class="descname">formatwarning</code><span class="sig-paren">(</span><em>message</em>, <em>category</em>, <em>filename</em>, <em>lineno</em><span class="optional">[</span>, <em>line</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.formatwarning" title="Permalink to this definition">¶</a></dt>
<dd><p>Format a warning the standard way.  This returns a string which may contain
embedded newlines and ends in a newline.  <em>line</em> is a line of source code to
be included in the warning message; if <em>line</em> is not supplied,
<a class="reference internal" href="#warnings.formatwarning" title="warnings.formatwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code></a> will try to read the line specified by <em>filename</em> and
<em>lineno</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Added the <em>line</em> argument.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="warnings.filterwarnings">
<code class="descclassname">warnings.</code><code class="descname">filterwarnings</code><span class="sig-paren">(</span><em>action</em><span class="optional">[</span>, <em>message</em><span class="optional">[</span>, <em>category</em><span class="optional">[</span>, <em>module</em><span class="optional">[</span>, <em>lineno</em><span class="optional">[</span>, <em>append</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.filterwarnings" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert an entry into the list of <a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter specifications</span></a>.  The entry is inserted at the front by default; if
<em>append</em> is true, it is inserted at the end.  This checks the types of the
arguments, compiles the <em>message</em> and <em>module</em> regular expressions, and
inserts them as a tuple in the list of warnings filters.  Entries closer to
the front of the list override entries later in the list, if both match a
particular warning.  Omitted arguments default to a value that matches
everything.</p>
</dd></dl>

<dl class="function">
<dt id="warnings.simplefilter">
<code class="descclassname">warnings.</code><code class="descname">simplefilter</code><span class="sig-paren">(</span><em>action</em><span class="optional">[</span>, <em>category</em><span class="optional">[</span>, <em>lineno</em><span class="optional">[</span>, <em>append</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.simplefilter" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a simple entry into the list of <a class="reference internal" href="#warning-filter"><span class="std std-ref">warnings filter specifications</span></a>.  The meaning of the function parameters is as for
<a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>, but regular expressions are not needed as the filter
inserted always matches any message in any module as long as the category and
line number match.</p>
</dd></dl>

<dl class="function">
<dt id="warnings.resetwarnings">
<code class="descclassname">warnings.</code><code class="descname">resetwarnings</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.resetwarnings" title="Permalink to this definition">¶</a></dt>
<dd><p>Reset the warnings filter.  This discards the effect of all previous calls to
<a class="reference internal" href="#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">filterwarnings()</span></code></a>, including that of the <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> command line options
and calls to <a class="reference internal" href="#warnings.simplefilter" title="warnings.simplefilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">simplefilter()</span></code></a>.</p>
</dd></dl>

</div>
<div class="section" id="available-context-managers">
<h2>28.6.7. Available Context Managers<a class="headerlink" href="#available-context-managers" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="warnings.catch_warnings">
<em class="property">class </em><code class="descclassname">warnings.</code><code class="descname">catch_warnings</code><span class="sig-paren">(</span><span class="optional">[</span><em>*</em>, <em>record=False</em>, <em>module=None</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#warnings.catch_warnings" title="Permalink to this definition">¶</a></dt>
<dd><p>A context manager that copies and, upon exit, restores the warnings filter
and the <a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function.
If the <em>record</em> argument is <a class="reference internal" href="constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> (the default) the context manager
returns <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-class docutils literal notranslate"><span class="pre">None</span></code></a> on entry. If <em>record</em> is <a class="reference internal" href="constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, a list is
returned that is progressively populated with objects as seen by a custom
<a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function (which also suppresses output to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>).
Each object in the list has attributes with the same names as the arguments to
<a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a>.</p>
<p>The <em>module</em> argument takes a module that will be used instead of the
module returned when you import <a class="reference internal" href="#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> whose filter will be
protected. This argument exists primarily for testing the <a class="reference internal" href="#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a>
module itself.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> manager works by replacing and
then later restoring the module’s
<a class="reference internal" href="#warnings.showwarning" title="warnings.showwarning"><code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code></a> function and internal list of filter
specifications.  This means the context manager is modifying
global state and therefore is not thread-safe.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 3, the arguments to the constructor for
<a class="reference internal" href="#warnings.catch_warnings" title="warnings.catch_warnings"><code class="xref py py-class docutils literal notranslate"><span class="pre">catch_warnings</span></code></a> are keyword-only arguments.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a><ul>
<li><a class="reference internal" href="#warning-categories">28.6.1. Warning Categories</a></li>
<li><a class="reference internal" href="#the-warnings-filter">28.6.2. The Warnings Filter</a><ul>
<li><a class="reference internal" href="#default-warning-filters">28.6.2.1. Default Warning Filters</a></li>
</ul>
</li>
<li><a class="reference internal" href="#temporarily-suppressing-warnings">28.6.3. Temporarily Suppressing Warnings</a></li>
<li><a class="reference internal" href="#testing-warnings">28.6.4. Testing Warnings</a></li>
<li><a class="reference internal" href="#updating-code-for-new-versions-of-python">28.6.5. Updating Code For New Versions of Python</a></li>
<li><a class="reference internal" href="#available-functions">28.6.6. Available Functions</a></li>
<li><a class="reference internal" href="#available-context-managers">28.6.7. Available Context Managers</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="__main__.html"
                        title="previous chapter">28.5. <code class="docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level script environment</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="contextlib.html"
                        title="next chapter">28.7. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/warnings.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="contextlib.html" title="28.7. contextlib — Utilities for with-statement contexts"
             >next</a> |</li>
        <li class="right" >
          <a href="__main__.html" title="28.5. __main__ — Top-level script environment"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="python.html" >28. Python Runtime Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\	.�>a>ahtml/library/wave.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>21.5. wave — Read and write WAV files &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="21.6. chunk — Read IFF chunked data" href="chunk.html" />
    <link rel="prev" title="21.4. sunau — Read and write Sun AU files" href="sunau.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/wave.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="chunk.html" title="21.6. chunk — Read IFF chunked data"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="sunau.html" title="21.4. sunau — Read and write Sun AU files"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" accesskey="U">21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-wave">
<span id="wave-read-and-write-wav-files"></span><h1>21.5. <a class="reference internal" href="#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a> — Read and write WAV files<a class="headerlink" href="#module-wave" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/wave.py">Lib/wave.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a> module provides a convenient interface to the WAV sound format.
It does not support compression/decompression, but it does support mono/stereo.</p>
<p>The <a class="reference internal" href="#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a> module defines the following function and exception:</p>
<dl class="function">
<dt id="wave.open">
<code class="descclassname">wave.</code><code class="descname">open</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.open" title="Permalink to this definition">¶</a></dt>
<dd><p>If <em>file</em> is a string, open the file by that name, otherwise treat it as a
seekable file-like object.  <em>mode</em> can be any of</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">'r'</span></code>, <code class="docutils literal notranslate"><span class="pre">'rb'</span></code></dt>
<dd>Read only mode.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">'w'</span></code>, <code class="docutils literal notranslate"><span class="pre">'wb'</span></code></dt>
<dd>Write only mode.</dd>
</dl>
<p>Note that it does not allow read/write WAV files.</p>
<p>A <em>mode</em> of <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'rb'</span></code> returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">Wave_read</span></code> object, while a
<em>mode</em> of <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or <code class="docutils literal notranslate"><span class="pre">'wb'</span></code> returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">Wave_write</span></code> object.  If
<em>mode</em> is omitted and a file-like object is passed as <em>file</em>, <code class="docutils literal notranslate"><span class="pre">file.mode</span></code>
is used as the default value for <em>mode</em> (the <code class="docutils literal notranslate"><span class="pre">'b'</span></code> flag is still added if
necessary).</p>
<p>If you pass in a file-like object, the wave object will not close it when its
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method is called; it is the caller’s responsibility to close
the file object.</p>
</dd></dl>

<dl class="function">
<dt id="wave.openfp">
<code class="descclassname">wave.</code><code class="descname">openfp</code><span class="sig-paren">(</span><em>file</em>, <em>mode</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.openfp" title="Permalink to this definition">¶</a></dt>
<dd><p>A synonym for <a class="reference internal" href="#wave.open" title="wave.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, maintained for backwards compatibility.</p>
</dd></dl>

<dl class="exception">
<dt id="wave.Error">
<em class="property">exception </em><code class="descclassname">wave.</code><code class="descname">Error</code><a class="headerlink" href="#wave.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>An error raised when something is impossible because it violates the WAV
specification or hits an implementation deficiency.</p>
</dd></dl>

<div class="section" id="wave-read-objects">
<span id="id1"></span><h2>21.5.1. Wave_read Objects<a class="headerlink" href="#wave-read-objects" title="Permalink to this headline">¶</a></h2>
<p>Wave_read objects, as returned by <a class="reference internal" href="#wave.open" title="wave.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, have the following methods:</p>
<dl class="method">
<dt id="wave.Wave_read.close">
<code class="descclassname">Wave_read.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the stream if it was opened by <a class="reference internal" href="#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a>, and make the instance
unusable.  This is called automatically on object collection.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getnchannels">
<code class="descclassname">Wave_read.</code><code class="descname">getnchannels</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns number of audio channels (<code class="docutils literal notranslate"><span class="pre">1</span></code> for mono, <code class="docutils literal notranslate"><span class="pre">2</span></code> for stereo).</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getsampwidth">
<code class="descclassname">Wave_read.</code><code class="descname">getsampwidth</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns sample width in bytes.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getframerate">
<code class="descclassname">Wave_read.</code><code class="descname">getframerate</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns sampling frequency.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getnframes">
<code class="descclassname">Wave_read.</code><code class="descname">getnframes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns number of audio frames.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getcomptype">
<code class="descclassname">Wave_read.</code><code class="descname">getcomptype</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns compression type (<code class="docutils literal notranslate"><span class="pre">'NONE'</span></code> is the only supported type).</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getcompname">
<code class="descclassname">Wave_read.</code><code class="descname">getcompname</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getcompname" title="Permalink to this definition">¶</a></dt>
<dd><p>Human-readable version of <a class="reference internal" href="#wave.Wave_read.getcomptype" title="wave.Wave_read.getcomptype"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getcomptype()</span></code></a>. Usually <code class="docutils literal notranslate"><span class="pre">'not</span> <span class="pre">compressed'</span></code>
parallels <code class="docutils literal notranslate"><span class="pre">'NONE'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getparams">
<code class="descclassname">Wave_read.</code><code class="descname">getparams</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getparams" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a tuple <code class="docutils literal notranslate"><span class="pre">(nchannels,</span> <span class="pre">sampwidth,</span> <span class="pre">framerate,</span> <span class="pre">nframes,</span> <span class="pre">comptype,</span>
<span class="pre">compname)</span></code>, equivalent to output of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">get*()</span></code> methods.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.readframes">
<code class="descclassname">Wave_read.</code><code class="descname">readframes</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.readframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Reads and returns at most <em>n</em> frames of audio, as a string of bytes.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.rewind">
<code class="descclassname">Wave_read.</code><code class="descname">rewind</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.rewind" title="Permalink to this definition">¶</a></dt>
<dd><p>Rewind the file pointer to the beginning of the audio stream.</p>
</dd></dl>

<p>The following two methods are defined for compatibility with the <a class="reference internal" href="aifc.html#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a>
module, and don’t do anything interesting.</p>
<dl class="method">
<dt id="wave.Wave_read.getmarkers">
<code class="descclassname">Wave_read.</code><code class="descname">getmarkers</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getmarkers" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.getmark">
<code class="descclassname">Wave_read.</code><code class="descname">getmark</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.getmark" title="Permalink to this definition">¶</a></dt>
<dd><p>Raise an error.</p>
</dd></dl>

<p>The following two methods define a term “position” which is compatible between
them, and is otherwise implementation dependent.</p>
<dl class="method">
<dt id="wave.Wave_read.setpos">
<code class="descclassname">Wave_read.</code><code class="descname">setpos</code><span class="sig-paren">(</span><em>pos</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.setpos" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the file pointer to the specified position.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_read.tell">
<code class="descclassname">Wave_read.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_read.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current file pointer position.</p>
</dd></dl>

</div>
<div class="section" id="wave-write-objects">
<span id="id2"></span><h2>21.5.2. Wave_write Objects<a class="headerlink" href="#wave-write-objects" title="Permalink to this headline">¶</a></h2>
<p>Wave_write objects, as returned by <a class="reference internal" href="#wave.open" title="wave.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, have the following methods:</p>
<dl class="method">
<dt id="wave.Wave_write.close">
<code class="descclassname">Wave_write.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Make sure <em>nframes</em> is correct, and close the file if it was opened by
<a class="reference internal" href="#module-wave" title="wave: Provide an interface to the WAV sound format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wave</span></code></a>.  This method is called upon object collection.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setnchannels">
<code class="descclassname">Wave_write.</code><code class="descname">setnchannels</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setnchannels" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the number of channels.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setsampwidth">
<code class="descclassname">Wave_write.</code><code class="descname">setsampwidth</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setsampwidth" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the sample width to <em>n</em> bytes.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setframerate">
<code class="descclassname">Wave_write.</code><code class="descname">setframerate</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setframerate" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the frame rate to <em>n</em>.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setnframes">
<code class="descclassname">Wave_write.</code><code class="descname">setnframes</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setnframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the number of frames to <em>n</em>. This will be changed later if more frames are
written.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setcomptype">
<code class="descclassname">Wave_write.</code><code class="descname">setcomptype</code><span class="sig-paren">(</span><em>type</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setcomptype" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the compression type and description. At the moment, only compression type
<code class="docutils literal notranslate"><span class="pre">NONE</span></code> is supported, meaning no compression.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.setparams">
<code class="descclassname">Wave_write.</code><code class="descname">setparams</code><span class="sig-paren">(</span><em>tuple</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.setparams" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>tuple</em> should be <code class="docutils literal notranslate"><span class="pre">(nchannels,</span> <span class="pre">sampwidth,</span> <span class="pre">framerate,</span> <span class="pre">nframes,</span> <span class="pre">comptype,</span>
<span class="pre">compname)</span></code>, with values valid for the <code class="xref py py-meth docutils literal notranslate"><span class="pre">set*()</span></code> methods.  Sets all
parameters.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.tell">
<code class="descclassname">Wave_write.</code><code class="descname">tell</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.tell" title="Permalink to this definition">¶</a></dt>
<dd><p>Return current position in the file, with the same disclaimer for the
<a class="reference internal" href="#wave.Wave_read.tell" title="wave.Wave_read.tell"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Wave_read.tell()</span></code></a> and <a class="reference internal" href="#wave.Wave_read.setpos" title="wave.Wave_read.setpos"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Wave_read.setpos()</span></code></a> methods.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.writeframesraw">
<code class="descclassname">Wave_write.</code><code class="descname">writeframesraw</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.writeframesraw" title="Permalink to this definition">¶</a></dt>
<dd><p>Write audio frames, without correcting <em>nframes</em>.</p>
</dd></dl>

<dl class="method">
<dt id="wave.Wave_write.writeframes">
<code class="descclassname">Wave_write.</code><code class="descname">writeframes</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#wave.Wave_write.writeframes" title="Permalink to this definition">¶</a></dt>
<dd><p>Write audio frames and make sure <em>nframes</em> is correct.</p>
</dd></dl>

<p>Note that it is invalid to set any parameters after calling <code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframes()</span></code>
or <code class="xref py py-meth docutils literal notranslate"><span class="pre">writeframesraw()</span></code>, and any attempt to do so will raise
<a class="reference internal" href="#wave.Error" title="wave.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">wave.Error</span></code></a>.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a><ul>
<li><a class="reference internal" href="#wave-read-objects">21.5.1. Wave_read Objects</a></li>
<li><a class="reference internal" href="#wave-write-objects">21.5.2. Wave_write Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="sunau.html"
                        title="previous chapter">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="chunk.html"
                        title="next chapter">21.6. <code class="docutils literal notranslate"><span class="pre">chunk</span></code> — Read IFF chunked data</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/wave.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="chunk.html" title="21.6. chunk — Read IFF chunked data"
             >next</a> |</li>
        <li class="right" >
          <a href="sunau.html" title="21.4. sunau — Read and write Sun AU files"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="mm.html" >21. Multimedia Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ӄ�~����html/library/weakref.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8.11. weakref — Weak references &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8.12. UserDict — Class wrapper for dictionary objects" href="userdict.html" />
    <link rel="prev" title="8.10. Queue — A synchronized queue class" href="queue.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/weakref.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" accesskey="U">8. Data Types</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-weakref">
<span id="weakref-weak-references"></span><h1>8.11. <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> — Weak references<a class="headerlink" href="#module-weakref" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/weakref.py">Lib/weakref.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module allows the Python programmer to create <em class="dfn">weak
references</em> to objects.</p>
<p>In the following, the term <em class="dfn">referent</em> means the object which is referred to
by a weak reference.</p>
<p>A weak reference to an object is not enough to keep the object alive: when the
only remaining references to a referent are weak references,
<a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> is free to destroy the referent and reuse its memory
for something else.  A primary use for weak references is to implement caches or
mappings holding large objects, where it’s desired that a large object not be
kept alive solely because it appears in a cache or mapping.</p>
<p>For example, if you have a number of large binary image objects, you may wish to
associate a name with each.  If you used a Python dictionary to map names to
images, or images to names, the image objects would remain alive just because
they appeared as values or keys in the dictionaries.  The
<a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> classes supplied by
the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module are an alternative, using weak references to construct
mappings that don’t keep objects alive solely because they appear in the mapping
objects.  If, for example, an image object is a value in a
<a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a>, then when the last remaining references to that
image object are the weak references held by weak mappings, garbage collection
can reclaim the object, and its corresponding entries in weak mappings are
simply deleted.</p>
<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> and <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> use weak references
in their implementation, setting up callback functions on the weak references
that notify the weak dictionaries when a key or value has been reclaimed by
garbage collection.  Most programs should find that using one of these weak
dictionary types is all they need – it’s not usually necessary to create your
own weak references directly.  The low-level machinery used by the weak
dictionary implementations is exposed by the <a class="reference internal" href="#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module for the
benefit of advanced uses.</p>
<p>Not all objects can be weakly referenced; those objects which can include class
instances, functions written in Python (but not in C), methods (both bound and
unbound), sets, frozensets, file objects, <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>s, type objects,
<code class="xref py py-class docutils literal notranslate"><span class="pre">DBcursor</span></code> objects from the <a class="reference internal" href="bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module, sockets, arrays, deques,
regular expression pattern objects, and code objects.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Added support for files, sockets, arrays, and patterns.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Added support for thread.lock, threading.Lock, and code objects.</p>
</div>
<p>Several built-in types such as <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> and <a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> do not directly
support weak references but can add support through subclassing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dict</span><span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="n">obj</span> <span class="o">=</span> <span class="n">Dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>   <span class="c1"># this object is weak referenceable</span>
</pre></div>
</div>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Other built-in types such as <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> and <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a> do not support
weak references even when subclassed.</p>
</div>
<p>Extension types can easily be made to support weak references; see
<a class="reference internal" href="../extending/newtypes.html#weakref-support"><span class="std std-ref">Weak Reference Support</span></a>.</p>
<dl class="class">
<dt id="weakref.ref">
<em class="property">class </em><code class="descclassname">weakref.</code><code class="descname">ref</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.ref" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a weak reference to <em>object</em>.  The original object can be retrieved by
calling the reference object if the referent is still alive; if the referent is
no longer alive, calling the reference object will cause <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> to be
returned.  If <em>callback</em> is provided and not <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, and the returned
weakref object is still alive, the callback will be called when the object is
about to be finalized; the weak reference object will be passed as the only
parameter to the callback; the referent will no longer be available.</p>
<p>It is allowable for many weak references to be constructed for the same object.
Callbacks registered for each weak reference will be called from the most
recently registered callback to the oldest registered callback.</p>
<p>Exceptions raised by the callback will be noted on the standard error output,
but cannot be propagated; they are handled in exactly the same way as exceptions
raised from an object’s <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method.</p>
<p>Weak references are <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> if the <em>object</em> is hashable.  They will maintain
their hash value even after the <em>object</em> was deleted.  If <a class="reference internal" href="functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> is called
the first time only after the <em>object</em> was deleted, the call will raise
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
<p>Weak references support tests for equality, but not ordering.  If the referents
are still alive, two references have the same equality relationship as their
referents (regardless of the <em>callback</em>).  If either referent has been deleted,
the references are equal only if the reference objects are the same object.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>This is now a subclassable type rather than a factory function; it derives from
<a class="reference internal" href="functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="weakref.proxy">
<code class="descclassname">weakref.</code><code class="descname">proxy</code><span class="sig-paren">(</span><em>object</em><span class="optional">[</span>, <em>callback</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.proxy" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a proxy to <em>object</em> which uses a weak reference.  This supports use of
the proxy in most contexts instead of requiring the explicit dereferencing used
with weak reference objects.  The returned object will have a type of either
<code class="docutils literal notranslate"><span class="pre">ProxyType</span></code> or <code class="docutils literal notranslate"><span class="pre">CallableProxyType</span></code>, depending on whether <em>object</em> is
callable.  Proxy objects are not <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> regardless of the referent; this
avoids a number of problems related to their fundamentally mutable nature, and
prevent their use as dictionary keys.  <em>callback</em> is the same as the parameter
of the same name to the <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-func docutils literal notranslate"><span class="pre">ref()</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="weakref.getweakrefcount">
<code class="descclassname">weakref.</code><code class="descname">getweakrefcount</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#weakref.getweakrefcount" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of weak references and proxies which refer to <em>object</em>.</p>
</dd></dl>

<dl class="function">
<dt id="weakref.getweakrefs">
<code class="descclassname">weakref.</code><code class="descname">getweakrefs</code><span class="sig-paren">(</span><em>object</em><span class="sig-paren">)</span><a class="headerlink" href="#weakref.getweakrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all weak reference and proxy objects which refer to <em>object</em>.</p>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakKeyDictionary">
<em class="property">class </em><code class="descclassname">weakref.</code><code class="descname">WeakKeyDictionary</code><span class="sig-paren">(</span><span class="optional">[</span><em>dict</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakKeyDictionary" title="Permalink to this definition">¶</a></dt>
<dd><p>Mapping class that references keys weakly.  Entries in the dictionary will be
discarded when there is no longer a strong reference to the key.  This can be
used to associate additional data with an object owned by other parts of an
application without adding attributes to those objects.  This can be especially
useful with objects that override attribute accesses.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Caution: Because a <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> is built on top of a Python
dictionary, it must not change size when iterating over it.  This can be
difficult to ensure for a <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> because actions
performed by the program during iteration may cause items in the
dictionary to vanish “by magic” (as a side effect of garbage collection).</p>
</div>
</dd></dl>

<p><a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> objects have the following additional methods.  These
expose the internal references directly.  The references are not guaranteed to
be “live” at the time they are used, so the result of calling the references
needs to be checked before being used.  This can be used to avoid creating
references that will cause the garbage collector to keep the keys around longer
than needed.</p>
<dl class="method">
<dt id="weakref.WeakKeyDictionary.iterkeyrefs">
<code class="descclassname">WeakKeyDictionary.</code><code class="descname">iterkeyrefs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakKeyDictionary.iterkeyrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterable of the weak references to the keys.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="weakref.WeakKeyDictionary.keyrefs">
<code class="descclassname">WeakKeyDictionary.</code><code class="descname">keyrefs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakKeyDictionary.keyrefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of weak references to the keys.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakValueDictionary">
<em class="property">class </em><code class="descclassname">weakref.</code><code class="descname">WeakValueDictionary</code><span class="sig-paren">(</span><span class="optional">[</span><em>dict</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakValueDictionary" title="Permalink to this definition">¶</a></dt>
<dd><p>Mapping class that references values weakly.  Entries in the dictionary will be
discarded when no strong reference to the value exists any more.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Caution:  Because a <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> is built on top of a Python
dictionary, it must not change size when iterating over it.  This can be
difficult to ensure for a <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> because actions performed
by the program during iteration may cause items in the dictionary to vanish “by
magic” (as a side effect of garbage collection).</p>
</div>
</dd></dl>

<p><a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> objects have the following additional methods.
These methods have the same issues as the <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeyrefs()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keyrefs()</span></code> methods of <a class="reference internal" href="#weakref.WeakKeyDictionary" title="weakref.WeakKeyDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code></a> objects.</p>
<dl class="method">
<dt id="weakref.WeakValueDictionary.itervaluerefs">
<code class="descclassname">WeakValueDictionary.</code><code class="descname">itervaluerefs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakValueDictionary.itervaluerefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterable of the weak references to the values.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="weakref.WeakValueDictionary.valuerefs">
<code class="descclassname">WeakValueDictionary.</code><code class="descname">valuerefs</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakValueDictionary.valuerefs" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of weak references to the values.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="weakref.WeakSet">
<em class="property">class </em><code class="descclassname">weakref.</code><code class="descname">WeakSet</code><span class="sig-paren">(</span><span class="optional">[</span><em>elements</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#weakref.WeakSet" title="Permalink to this definition">¶</a></dt>
<dd><p>Set class that keeps weak references to its elements.  An element will be
discarded when no strong reference to it exists any more.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="weakref.ReferenceType">
<code class="descclassname">weakref.</code><code class="descname">ReferenceType</code><a class="headerlink" href="#weakref.ReferenceType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for weak references objects.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.ProxyType">
<code class="descclassname">weakref.</code><code class="descname">ProxyType</code><a class="headerlink" href="#weakref.ProxyType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for proxies of objects which are not callable.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.CallableProxyType">
<code class="descclassname">weakref.</code><code class="descname">CallableProxyType</code><a class="headerlink" href="#weakref.CallableProxyType" title="Permalink to this definition">¶</a></dt>
<dd><p>The type object for proxies of callable objects.</p>
</dd></dl>

<dl class="data">
<dt id="weakref.ProxyTypes">
<code class="descclassname">weakref.</code><code class="descname">ProxyTypes</code><a class="headerlink" href="#weakref.ProxyTypes" title="Permalink to this definition">¶</a></dt>
<dd><p>Sequence containing all the type objects for proxies.  This can make it simpler
to test if an object is a proxy without being dependent on naming both proxy
types.</p>
</dd></dl>

<dl class="exception">
<dt id="weakref.ReferenceError">
<em class="property">exception </em><code class="descclassname">weakref.</code><code class="descname">ReferenceError</code><a class="headerlink" href="#weakref.ReferenceError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a proxy object is used but the underlying object has been
collected.  This is the same as the standard <a class="reference internal" href="#weakref.ReferenceError" title="weakref.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ReferenceError</span></code></a> exception.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0205"><strong>PEP 205</strong></a> - Weak References</dt>
<dd>The proposal and rationale for this feature, including links to earlier
implementations and information about similar features in other languages.</dd>
</dl>
</div>
<div class="section" id="weak-reference-objects">
<span id="weakref-objects"></span><h2>8.11.1. Weak Reference Objects<a class="headerlink" href="#weak-reference-objects" title="Permalink to this headline">¶</a></h2>
<p>Weak reference objects have no attributes or methods, but do allow the referent
to be obtained, if it still exists, by calling it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">weakref</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Object</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="o">=</span> <span class="n">Object</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">(</span><span class="n">o</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o2</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">o</span> <span class="ow">is</span> <span class="n">o2</span>
<span class="go">True</span>
</pre></div>
</div>
<p>If the referent no longer exists, calling the reference object returns
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">o</span><span class="p">,</span> <span class="n">o2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">r</span><span class="p">()</span>
<span class="go">None</span>
</pre></div>
</div>
<p>Testing that a weak reference object is still live should be done using the
expression <code class="docutils literal notranslate"><span class="pre">ref()</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">None</span></code>.  Normally, application code that needs to use
a reference object should follow this pattern:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># r is a weak reference object</span>
<span class="n">o</span> <span class="o">=</span> <span class="n">r</span><span class="p">()</span>
<span class="k">if</span> <span class="n">o</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="c1"># referent has been garbage collected</span>
    <span class="nb">print</span> <span class="s2">&quot;Object has been deallocated; can&#39;t frobnicate.&quot;</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Object is still live!&quot;</span>
    <span class="n">o</span><span class="o">.</span><span class="n">do_something_useful</span><span class="p">()</span>
</pre></div>
</div>
<p>Using a separate test for “liveness” creates race conditions in threaded
applications; another thread can cause a weak reference to become invalidated
before the weak reference is called; the idiom shown above is safe in threaded
applications as well as single-threaded applications.</p>
<p>Specialized versions of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-class docutils literal notranslate"><span class="pre">ref</span></code></a> objects can be created through subclassing.
This is used in the implementation of the <a class="reference internal" href="#weakref.WeakValueDictionary" title="weakref.WeakValueDictionary"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code></a> to reduce
the memory overhead for each entry in the mapping.  This may be most useful to
associate additional information with a reference, but could also be used to
insert additional processing on calls to retrieve the referent.</p>
<p>This example shows how a subclass of <a class="reference internal" href="#weakref.ref" title="weakref.ref"><code class="xref py py-class docutils literal notranslate"><span class="pre">ref</span></code></a> can be used to store
additional information about an object and affect the value that’s returned when
the referent is accessed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">weakref</span>

<span class="k">class</span> <span class="nc">ExtendedRef</span><span class="p">(</span><span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="o">**</span><span class="n">annotations</span><span class="p">):</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">ExtendedRef</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="n">callback</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">=</span> <span class="mi">0</span>
        <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">annotations</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
            <span class="nb">setattr</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="sd">&quot;&quot;&quot;Return a pair containing the referent and the number of</span>
<span class="sd">        times the reference has been called.</span>
<span class="sd">        &quot;&quot;&quot;</span>
        <span class="n">ob</span> <span class="o">=</span> <span class="nb">super</span><span class="p">(</span><span class="n">ExtendedRef</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="fm">__call__</span><span class="p">()</span>
        <span class="k">if</span> <span class="n">ob</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">ob</span> <span class="o">=</span> <span class="p">(</span><span class="n">ob</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">__counter</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">ob</span>
</pre></div>
</div>
</div>
<div class="section" id="example">
<span id="weakref-example"></span><h2>8.11.2. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h2>
<p>This simple example shows how an application can use object IDs to retrieve
objects that it has seen before.  The IDs of the objects can then be used in
other data structures without forcing the objects to remain alive, but the
objects can still be retrieved by ID if they do.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">weakref</span>

<span class="n">_id2obj_dict</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>

<span class="k">def</span> <span class="nf">remember</span><span class="p">(</span><span class="n">obj</span><span class="p">):</span>
    <span class="n">oid</span> <span class="o">=</span> <span class="nb">id</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
    <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span> <span class="o">=</span> <span class="n">obj</span>
    <span class="k">return</span> <span class="n">oid</span>

<span class="k">def</span> <span class="nf">id2obj</span><span class="p">(</span><span class="n">oid</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">_id2obj_dict</span><span class="p">[</span><span class="n">oid</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a><ul>
<li><a class="reference internal" href="#weak-reference-objects">8.11.1. Weak Reference Objects</a></li>
<li><a class="reference internal" href="#example">8.11.2. Example</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="queue.html"
                        title="previous chapter">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="userdict.html"
                        title="next chapter">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/weakref.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="userdict.html" title="8.12. UserDict — Class wrapper for dictionary objects"
             >next</a> |</li>
        <li class="right" >
          <a href="queue.html" title="8.10. Queue — A synchronized queue class"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="datatypes.html" >8. Data Types</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\%�i��g�ghtml/library/webbrowser.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.1. webbrowser — Convenient Web-browser controller &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.2. cgi — Common Gateway Interface support" href="cgi.html" />
    <link rel="prev" title="20. Internet Protocols and Support" href="internet.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/webbrowser.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgi.html" title="20.2. cgi — Common Gateway Interface support"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="internet.html" title="20. Internet Protocols and Support"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-webbrowser">
<span id="webbrowser-convenient-web-browser-controller"></span><h1>20.1. <a class="reference internal" href="#module-webbrowser" title="webbrowser: Easy-to-use controller for Web browsers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">webbrowser</span></code></a> — Convenient Web-browser controller<a class="headerlink" href="#module-webbrowser" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/webbrowser.py">Lib/webbrowser.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-webbrowser" title="webbrowser: Easy-to-use controller for Web browsers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">webbrowser</span></code></a> module provides a high-level interface to allow displaying
Web-based documents to users. Under most circumstances, simply calling the
<a class="reference internal" href="#webbrowser.open" title="webbrowser.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function from this module will do the right thing.</p>
<p>Under Unix, graphical browsers are preferred under X11, but text-mode browsers
will be used if graphical browsers are not available or an X11 display isn’t
available.  If text-mode browsers are used, the calling process will block until
the user exits the browser.</p>
<p>If the environment variable <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">BROWSER</span></code> exists, it is interpreted to
override the platform default list of browsers, as an <a class="reference internal" href="os.html#os.pathsep" title="os.pathsep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.pathsep</span></code></a>-separated
list of browsers to try in order.  When the value of a list part contains the
string <code class="docutils literal notranslate"><span class="pre">%s</span></code>, then it is  interpreted as a literal browser command line to be
used with the argument URL substituted for <code class="docutils literal notranslate"><span class="pre">%s</span></code>; if the part does not contain
<code class="docutils literal notranslate"><span class="pre">%s</span></code>, it is simply interpreted as the name of the browser to launch. <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<p>For non-Unix platforms, or when a remote browser is available on Unix, the
controlling process will not wait for the user to finish with the browser, but
allow the remote browser to maintain its own windows on the display.  If remote
browsers are not available on Unix, the controlling process will launch a new
browser and wait.</p>
<p>The script <strong class="program">webbrowser</strong> can be used as a command-line interface for the
module. It accepts a URL as the argument. It accepts the following optional
parameters: <code class="docutils literal notranslate"><span class="pre">-n</span></code> opens the URL in a new browser window, if possible;
<code class="docutils literal notranslate"><span class="pre">-t</span></code> opens the URL in a new browser page (“tab”). The options are,
naturally, mutually exclusive.  Usage example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">webbrowser</span> <span class="o">-</span><span class="n">t</span> <span class="s2">&quot;http://www.python.org&quot;</span>
</pre></div>
</div>
<p>The following exception is defined:</p>
<dl class="exception">
<dt id="webbrowser.Error">
<em class="property">exception </em><code class="descclassname">webbrowser.</code><code class="descname">Error</code><a class="headerlink" href="#webbrowser.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised when a browser control error occurs.</p>
</dd></dl>

<p>The following functions are defined:</p>
<dl class="function">
<dt id="webbrowser.open">
<code class="descclassname">webbrowser.</code><code class="descname">open</code><span class="sig-paren">(</span><em>url</em>, <em>new=0</em>, <em>autoraise=True</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Display <em>url</em> using the default browser. If <em>new</em> is 0, the <em>url</em> is opened
in the same browser window if possible.  If <em>new</em> is 1, a new browser window
is opened if possible.  If <em>new</em> is 2, a new browser page (“tab”) is opened
if possible.  If <em>autoraise</em> is <code class="docutils literal notranslate"><span class="pre">True</span></code>, the window is raised if possible
(note that under many window managers this will occur regardless of the
setting of this variable).</p>
<p>Note that on some platforms, trying to open a filename using this function,
may work and start the operating system’s associated program.  However, this
is neither supported nor portable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><em>new</em> can now be 2.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="webbrowser.open_new">
<code class="descclassname">webbrowser.</code><code class="descname">open_new</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.open_new" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>url</em> in a new window of the default browser, if possible, otherwise, open
<em>url</em> in the only browser window.</p>
</dd></dl>

<dl class="function">
<dt id="webbrowser.open_new_tab">
<code class="descclassname">webbrowser.</code><code class="descname">open_new_tab</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.open_new_tab" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>url</em> in a new page (“tab”) of the default browser, if possible, otherwise
equivalent to <a class="reference internal" href="#webbrowser.open_new" title="webbrowser.open_new"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_new()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="webbrowser.get">
<code class="descclassname">webbrowser.</code><code class="descname">get</code><span class="sig-paren">(</span><span class="optional">[</span><em>name</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a controller object for the browser type <em>name</em>.  If <em>name</em> is empty,
return a controller for a default browser appropriate to the caller’s
environment.</p>
</dd></dl>

<dl class="function">
<dt id="webbrowser.register">
<code class="descclassname">webbrowser.</code><code class="descname">register</code><span class="sig-paren">(</span><em>name</em>, <em>constructor</em><span class="optional">[</span>, <em>instance</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.register" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the browser type <em>name</em>.  Once a browser type is registered, the
<a class="reference internal" href="#webbrowser.get" title="webbrowser.get"><code class="xref py py-func docutils literal notranslate"><span class="pre">get()</span></code></a> function can return a controller for that browser type.  If
<em>instance</em> is not provided, or is <code class="docutils literal notranslate"><span class="pre">None</span></code>, <em>constructor</em> will be called without
parameters to create an instance when needed.  If <em>instance</em> is provided,
<em>constructor</em> will never be called, and may be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>This entry point is only useful if you plan to either set the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">BROWSER</span></code>
variable or call <a class="reference internal" href="#webbrowser.get" title="webbrowser.get"><code class="xref py py-func docutils literal notranslate"><span class="pre">get()</span></code></a> with a nonempty argument matching the name of a
handler you declare.</p>
</dd></dl>

<p>A number of browser types are predefined.  This table gives the type names that
may be passed to the <a class="reference internal" href="#webbrowser.get" title="webbrowser.get"><code class="xref py py-func docutils literal notranslate"><span class="pre">get()</span></code></a> function and the corresponding instantiations
for the controller classes, all defined in this module.</p>
<table border="1" class="docutils">
<colgroup>
<col width="32%" />
<col width="58%" />
<col width="10%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Type Name</th>
<th class="head">Class Name</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'mozilla'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Mozilla('mozilla')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'firefox'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Mozilla('mozilla')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'netscape'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Mozilla('netscape')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'galeon'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Galeon('galeon')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'epiphany'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Galeon('epiphany')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'skipstone'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">BackgroundBrowser('skipstone')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'kfmclient'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Konqueror()</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'konqueror'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Konqueror()</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'kfm'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Konqueror()</span></code></td>
<td>(1)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'mosaic'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">BackgroundBrowser('mosaic')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'opera'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Opera()</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'grail'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Grail()</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'links'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericBrowser('links')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'elinks'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Elinks('elinks')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'lynx'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericBrowser('lynx')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'w3m'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">GenericBrowser('w3m')</span></code></td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'windows-default'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">WindowsDefault</span></code></td>
<td>(2)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'macosx'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">MacOSX('default')</span></code></td>
<td>(3)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'safari'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">MacOSX('safari')</span></code></td>
<td>(3)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'google-chrome'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Chrome('google-chrome')</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'chrome'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Chrome('chrome')</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'chromium'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Chromium('chromium')</span></code></td>
<td>(4)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'chromium-browser'</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">Chromium('chromium-browser')</span></code></td>
<td>(4)</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ol class="arabic simple">
<li>“Konqueror” is the file manager for the KDE desktop environment for Unix, and
only makes sense to use if KDE is running.  Some way of reliably detecting KDE
would be nice; the <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">KDEDIR</span></code> variable is not sufficient.  Note also that
the name “kfm” is used even when using the <strong class="program">konqueror</strong> command with KDE
2 — the implementation selects the best strategy for running Konqueror.</li>
<li>Only on Windows platforms.</li>
<li>Only on Mac OS X platform.</li>
<li>Support for Chrome/Chromium has been added in version 2.7.5.</li>
</ol>
<p>Here are some simple examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">url</span> <span class="o">=</span> <span class="s1">&#39;http://www.python.org/&#39;</span>

<span class="c1"># Open URL in a new tab, if a browser window is already open.</span>
<span class="n">webbrowser</span><span class="o">.</span><span class="n">open_new_tab</span><span class="p">(</span><span class="n">url</span> <span class="o">+</span> <span class="s1">&#39;doc/&#39;</span><span class="p">)</span>

<span class="c1"># Open URL in new window, raising the window if possible.</span>
<span class="n">webbrowser</span><span class="o">.</span><span class="n">open_new</span><span class="p">(</span><span class="n">url</span><span class="p">)</span>
</pre></div>
</div>
<div class="section" id="browser-controller-objects">
<span id="browser-controllers"></span><h2>20.1.1. Browser Controller Objects<a class="headerlink" href="#browser-controller-objects" title="Permalink to this headline">¶</a></h2>
<p>Browser controllers provide these methods which parallel three of the
module-level convenience functions:</p>
<dl class="method">
<dt id="webbrowser.controller.open">
<code class="descclassname">controller.</code><code class="descname">open</code><span class="sig-paren">(</span><em>url</em>, <em>new=0</em>, <em>autoraise=True</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.controller.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Display <em>url</em> using the browser handled by this controller. If <em>new</em> is 1, a new
browser window is opened if possible. If <em>new</em> is 2, a new browser page (“tab”)
is opened if possible.</p>
</dd></dl>

<dl class="method">
<dt id="webbrowser.controller.open_new">
<code class="descclassname">controller.</code><code class="descname">open_new</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.controller.open_new" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>url</em> in a new window of the browser handled by this controller, if
possible, otherwise, open <em>url</em> in the only browser window.  Alias
<a class="reference internal" href="#webbrowser.open_new" title="webbrowser.open_new"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_new()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="webbrowser.controller.open_new_tab">
<code class="descclassname">controller.</code><code class="descname">open_new_tab</code><span class="sig-paren">(</span><em>url</em><span class="sig-paren">)</span><a class="headerlink" href="#webbrowser.controller.open_new_tab" title="Permalink to this definition">¶</a></dt>
<dd><p>Open <em>url</em> in a new page (“tab”) of the browser handled by this controller, if
possible, otherwise equivalent to <a class="reference internal" href="#webbrowser.open_new" title="webbrowser.open_new"><code class="xref py py-func docutils literal notranslate"><span class="pre">open_new()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Executables named here without a full path will be searched in the
directories given in the <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code> environment variable.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a><ul>
<li><a class="reference internal" href="#browser-controller-objects">20.1.1. Browser Controller Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="internet.html"
                        title="previous chapter">20. Internet Protocols and Support</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cgi.html"
                        title="next chapter">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/webbrowser.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cgi.html" title="20.2. cgi — Common Gateway Interface support"
             >next</a> |</li>
        <li class="right" >
          <a href="internet.html" title="20. Internet Protocols and Support"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\=X��%%html/library/whichdb.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11.7. whichdb — Guess which DBM module created a database &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11.8. dbm — Simple “database” interface" href="dbm.html" />
    <link rel="prev" title="11.6. anydbm — Generic access to DBM-style databases" href="anydbm.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/whichdb.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dbm.html" title="11.8. dbm — Simple “database” interface"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="anydbm.html" title="11.6. anydbm — Generic access to DBM-style databases"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" accesskey="U">11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-whichdb">
<span id="whichdb-guess-which-dbm-module-created-a-database"></span><h1>11.7. <a class="reference internal" href="#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a> — Guess which DBM module created a database<a class="headerlink" href="#module-whichdb" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-whichdb" title="whichdb: Guess which DBM-style module created a given database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">whichdb</span></code></a> module’s only function has been put into the <a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>
module in Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports
when converting your sources to Python 3.</p>
</div>
<p>The single function in this module attempts to guess which of the several simple
database modules available—<a class="reference internal" href="dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>, <a class="reference internal" href="gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a>, or <a class="reference internal" href="dbhash.html#module-dbhash" title="dbhash: DBM-style interface to the BSD database library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbhash</span></code></a>—should be used to open a given file.</p>
<dl class="function">
<dt id="whichdb.whichdb">
<code class="descclassname">whichdb.</code><code class="descname">whichdb</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#whichdb.whichdb" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns one of the following values: <code class="docutils literal notranslate"><span class="pre">None</span></code> if the file can’t be opened
because it’s unreadable or doesn’t exist; the empty string (<code class="docutils literal notranslate"><span class="pre">''</span></code>) if the
file’s format can’t be guessed; or a string containing the required module name,
such as <code class="docutils literal notranslate"><span class="pre">'dbm'</span></code> or <code class="docutils literal notranslate"><span class="pre">'gdbm'</span></code>.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="anydbm.html"
                        title="previous chapter">11.6. <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> — Generic access to DBM-style databases</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="dbm.html"
                        title="next chapter">11.8. <code class="docutils literal notranslate"><span class="pre">dbm</span></code> — Simple “database” interface</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/whichdb.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="dbm.html" title="11.8. dbm — Simple “database” interface"
             >next</a> |</li>
        <li class="right" >
          <a href="anydbm.html" title="11.6. anydbm — Generic access to DBM-style databases"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="persistence.html" >11. Data Persistence</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\t�Y&Y&html/library/windows.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>35. MS Windows Specific Services &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="35.1. msilib — Read and write Microsoft Installer files" href="msilib.html" />
    <link rel="prev" title="34.1. formatter — Generic output formatting" href="formatter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/windows.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="msilib.html" title="35.1. msilib — Read and write Microsoft Installer files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="formatter.html" title="34.1. formatter — Generic output formatting"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="ms-windows-specific-services">
<span id="mswin-specific-services"></span><h1>35. MS Windows Specific Services<a class="headerlink" href="#ms-windows-specific-services" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes modules that are only available on MS Windows platforms.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="msilib.html">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a><ul>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#database-objects">35.1.1. Database Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#view-objects">35.1.2. View Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#summary-information-objects">35.1.3. Summary Information Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#record-objects">35.1.4. Record Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#errors">35.1.5. Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#cab-objects">35.1.6. CAB Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#directory-objects">35.1.7. Directory Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#features">35.1.8. Features</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#gui-classes">35.1.9. GUI classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="msilib.html#precomputed-tables">35.1.10. Precomputed tables</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="msvcrt.html">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a><ul>
<li class="toctree-l2"><a class="reference internal" href="msvcrt.html#file-operations">35.2.1. File Operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="msvcrt.html#console-i-o">35.2.2. Console I/O</a></li>
<li class="toctree-l2"><a class="reference internal" href="msvcrt.html#other-functions">35.2.3. Other Functions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="_winreg.html">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a><ul>
<li class="toctree-l2"><a class="reference internal" href="_winreg.html#constants">35.3.1. Constants</a><ul>
<li class="toctree-l3"><a class="reference internal" href="_winreg.html#hkey-constants">35.3.1.1. HKEY_* Constants</a></li>
<li class="toctree-l3"><a class="reference internal" href="_winreg.html#access-rights">35.3.1.2. Access Rights</a><ul>
<li class="toctree-l4"><a class="reference internal" href="_winreg.html#bit-specific">35.3.1.2.1. 64-bit Specific</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="_winreg.html#value-types">35.3.1.3. Value Types</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="_winreg.html#registry-handle-objects">35.3.2. Registry Handle Objects</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="winsound.html">35.4. <code class="docutils literal notranslate"><span class="pre">winsound</span></code> — Sound-playing interface for Windows</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="formatter.html"
                        title="previous chapter">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="msilib.html"
                        title="next chapter">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/windows.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="msilib.html" title="35.1. msilib — Read and write Microsoft Installer files"
             >next</a> |</li>
        <li class="right" >
          <a href="formatter.html" title="34.1. formatter — Generic output formatting"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\X\T�O�Ohtml/library/winsound.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>35.4. winsound — Sound-playing interface for Windows &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="36. Unix Specific Services" href="unix.html" />
    <link rel="prev" title="35.3. _winreg — Windows registry access" href="_winreg.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/winsound.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unix.html" title="36. Unix Specific Services"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="_winreg.html" title="35.3. _winreg — Windows registry access"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" accesskey="U">35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-winsound">
<span id="winsound-sound-playing-interface-for-windows"></span><h1>35.4. <a class="reference internal" href="#module-winsound" title="winsound: Access to the sound-playing machinery for Windows. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">winsound</span></code></a> — Sound-playing interface for Windows<a class="headerlink" href="#module-winsound" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.5.2.</span></p>
</div>
<p>The <a class="reference internal" href="#module-winsound" title="winsound: Access to the sound-playing machinery for Windows. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">winsound</span></code></a> module provides access to the basic sound-playing machinery
provided by Windows platforms.  It includes functions and several constants.</p>
<dl class="function">
<dt id="winsound.Beep">
<code class="descclassname">winsound.</code><code class="descname">Beep</code><span class="sig-paren">(</span><em>frequency</em>, <em>duration</em><span class="sig-paren">)</span><a class="headerlink" href="#winsound.Beep" title="Permalink to this definition">¶</a></dt>
<dd><p>Beep the PC’s speaker. The <em>frequency</em> parameter specifies frequency, in hertz,
of the sound, and must be in the range 37 through 32,767. The <em>duration</em>
parameter specifies the number of milliseconds the sound should last.  If the
system is not able to beep the speaker, <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="winsound.PlaySound">
<code class="descclassname">winsound.</code><code class="descname">PlaySound</code><span class="sig-paren">(</span><em>sound</em>, <em>flags</em><span class="sig-paren">)</span><a class="headerlink" href="#winsound.PlaySound" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the underlying <code class="xref c c-func docutils literal notranslate"><span class="pre">PlaySound()</span></code> function from the Platform API.  The
<em>sound</em> parameter may be a filename, audio data as a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Its
interpretation depends on the value of <em>flags</em>, which can be a bitwise ORed
combination of the constants described below. If the <em>sound</em> parameter is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, any currently playing waveform sound is stopped. If the system
indicates an error, <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.</p>
</dd></dl>

<dl class="function">
<dt id="winsound.MessageBeep">
<code class="descclassname">winsound.</code><code class="descname">MessageBeep</code><span class="sig-paren">(</span><span class="optional">[</span><em>type=MB_OK</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#winsound.MessageBeep" title="Permalink to this definition">¶</a></dt>
<dd><p>Call the underlying <code class="xref c c-func docutils literal notranslate"><span class="pre">MessageBeep()</span></code> function from the Platform API.  This
plays a sound as specified in the registry.  The <em>type</em> argument specifies which
sound to play; possible values are <code class="docutils literal notranslate"><span class="pre">-1</span></code>, <code class="docutils literal notranslate"><span class="pre">MB_ICONASTERISK</span></code>,
<code class="docutils literal notranslate"><span class="pre">MB_ICONEXCLAMATION</span></code>, <code class="docutils literal notranslate"><span class="pre">MB_ICONHAND</span></code>, <code class="docutils literal notranslate"><span class="pre">MB_ICONQUESTION</span></code>, and <code class="docutils literal notranslate"><span class="pre">MB_OK</span></code>, all
described below.  The value <code class="docutils literal notranslate"><span class="pre">-1</span></code> produces a “simple beep”; this is the final
fallback if a sound cannot be played otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_FILENAME">
<code class="descclassname">winsound.</code><code class="descname">SND_FILENAME</code><a class="headerlink" href="#winsound.SND_FILENAME" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>sound</em> parameter is the name of a WAV file. Do not use with
<a class="reference internal" href="#winsound.SND_ALIAS" title="winsound.SND_ALIAS"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_ALIAS</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_ALIAS">
<code class="descclassname">winsound.</code><code class="descname">SND_ALIAS</code><a class="headerlink" href="#winsound.SND_ALIAS" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>sound</em> parameter is a sound association name from the registry.  If the
registry contains no such name, play the system default sound unless
<a class="reference internal" href="#winsound.SND_NODEFAULT" title="winsound.SND_NODEFAULT"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_NODEFAULT</span></code></a> is also specified. If no default sound is registered,
raise <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>. Do not use with <a class="reference internal" href="#winsound.SND_FILENAME" title="winsound.SND_FILENAME"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_FILENAME</span></code></a>.</p>
<p>All Win32 systems support at least the following; most systems support many
more:</p>
<table border="1" class="docutils">
<colgroup>
<col width="39%" />
<col width="61%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head"><a class="reference internal" href="#winsound.PlaySound" title="winsound.PlaySound"><code class="xref py py-func docutils literal notranslate"><span class="pre">PlaySound()</span></code></a> <em>name</em></th>
<th class="head">Corresponding Control Panel Sound name</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'SystemAsterisk'</span></code></td>
<td>Asterisk</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'SystemExclamation'</span></code></td>
<td>Exclamation</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'SystemExit'</span></code></td>
<td>Exit Windows</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">'SystemHand'</span></code></td>
<td>Critical Stop</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">'SystemQuestion'</span></code></td>
<td>Question</td>
</tr>
</tbody>
</table>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">winsound</span>
<span class="c1"># Play Windows exit sound.</span>
<span class="n">winsound</span><span class="o">.</span><span class="n">PlaySound</span><span class="p">(</span><span class="s2">&quot;SystemExit&quot;</span><span class="p">,</span> <span class="n">winsound</span><span class="o">.</span><span class="n">SND_ALIAS</span><span class="p">)</span>

<span class="c1"># Probably play Windows default sound, if any is registered (because</span>
<span class="c1"># &quot;*&quot; probably isn&#39;t the registered name of any sound).</span>
<span class="n">winsound</span><span class="o">.</span><span class="n">PlaySound</span><span class="p">(</span><span class="s2">&quot;*&quot;</span><span class="p">,</span> <span class="n">winsound</span><span class="o">.</span><span class="n">SND_ALIAS</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_LOOP">
<code class="descclassname">winsound.</code><code class="descname">SND_LOOP</code><a class="headerlink" href="#winsound.SND_LOOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the sound repeatedly.  The <a class="reference internal" href="#winsound.SND_ASYNC" title="winsound.SND_ASYNC"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_ASYNC</span></code></a> flag must also be used to
avoid blocking.  Cannot be used with <a class="reference internal" href="#winsound.SND_MEMORY" title="winsound.SND_MEMORY"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_MEMORY</span></code></a>.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_MEMORY">
<code class="descclassname">winsound.</code><code class="descname">SND_MEMORY</code><a class="headerlink" href="#winsound.SND_MEMORY" title="Permalink to this definition">¶</a></dt>
<dd><p>The <em>sound</em> parameter to <a class="reference internal" href="#winsound.PlaySound" title="winsound.PlaySound"><code class="xref py py-func docutils literal notranslate"><span class="pre">PlaySound()</span></code></a> is a memory image of a WAV file, as a
string.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This module does not support playing from a memory image asynchronously, so a
combination of this flag and <a class="reference internal" href="#winsound.SND_ASYNC" title="winsound.SND_ASYNC"><code class="xref py py-const docutils literal notranslate"><span class="pre">SND_ASYNC</span></code></a> will raise <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_PURGE">
<code class="descclassname">winsound.</code><code class="descname">SND_PURGE</code><a class="headerlink" href="#winsound.SND_PURGE" title="Permalink to this definition">¶</a></dt>
<dd><p>Stop playing all instances of the specified sound.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This flag is not supported on modern Windows platforms.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_ASYNC">
<code class="descclassname">winsound.</code><code class="descname">SND_ASYNC</code><a class="headerlink" href="#winsound.SND_ASYNC" title="Permalink to this definition">¶</a></dt>
<dd><p>Return immediately, allowing sounds to play asynchronously.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_NODEFAULT">
<code class="descclassname">winsound.</code><code class="descname">SND_NODEFAULT</code><a class="headerlink" href="#winsound.SND_NODEFAULT" title="Permalink to this definition">¶</a></dt>
<dd><p>If the specified sound cannot be found, do not play the system default sound.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_NOSTOP">
<code class="descclassname">winsound.</code><code class="descname">SND_NOSTOP</code><a class="headerlink" href="#winsound.SND_NOSTOP" title="Permalink to this definition">¶</a></dt>
<dd><p>Do not interrupt sounds currently playing.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.SND_NOWAIT">
<code class="descclassname">winsound.</code><code class="descname">SND_NOWAIT</code><a class="headerlink" href="#winsound.SND_NOWAIT" title="Permalink to this definition">¶</a></dt>
<dd><p>Return immediately if the sound driver is busy.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This flag is not supported on modern Windows platforms.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="winsound.MB_ICONASTERISK">
<code class="descclassname">winsound.</code><code class="descname">MB_ICONASTERISK</code><a class="headerlink" href="#winsound.MB_ICONASTERISK" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the <code class="docutils literal notranslate"><span class="pre">SystemDefault</span></code> sound.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.MB_ICONEXCLAMATION">
<code class="descclassname">winsound.</code><code class="descname">MB_ICONEXCLAMATION</code><a class="headerlink" href="#winsound.MB_ICONEXCLAMATION" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the <code class="docutils literal notranslate"><span class="pre">SystemExclamation</span></code> sound.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.MB_ICONHAND">
<code class="descclassname">winsound.</code><code class="descname">MB_ICONHAND</code><a class="headerlink" href="#winsound.MB_ICONHAND" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the <code class="docutils literal notranslate"><span class="pre">SystemHand</span></code> sound.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.MB_ICONQUESTION">
<code class="descclassname">winsound.</code><code class="descname">MB_ICONQUESTION</code><a class="headerlink" href="#winsound.MB_ICONQUESTION" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the <code class="docutils literal notranslate"><span class="pre">SystemQuestion</span></code> sound.</p>
</dd></dl>

<dl class="data">
<dt id="winsound.MB_OK">
<code class="descclassname">winsound.</code><code class="descname">MB_OK</code><a class="headerlink" href="#winsound.MB_OK" title="Permalink to this definition">¶</a></dt>
<dd><p>Play the <code class="docutils literal notranslate"><span class="pre">SystemDefault</span></code> sound.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="_winreg.html"
                        title="previous chapter">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unix.html"
                        title="next chapter">36. Unix Specific Services</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/winsound.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unix.html" title="36. Unix Specific Services"
             >next</a> |</li>
        <li class="right" >
          <a href="_winreg.html" title="35.3. _winreg — Windows registry access"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="windows.html" >35. MS Windows Specific Services</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\D��@Y@Yhtml/library/wsgiref.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.4. wsgiref — WSGI Utilities and Reference Implementation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.5. urllib — Open arbitrary resources by URL" href="urllib.html" />
    <link rel="prev" title="20.3. cgitb — Traceback manager for CGI scripts" href="cgitb.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/wsgiref.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib.html" title="20.5. urllib — Open arbitrary resources by URL"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cgitb.html" title="20.3. cgitb — Traceback manager for CGI scripts"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-wsgiref">
<span id="wsgiref-wsgi-utilities-and-reference-implementation"></span><h1>20.4. <a class="reference internal" href="#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a> — WSGI Utilities and Reference Implementation<a class="headerlink" href="#module-wsgiref" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The Web Server Gateway Interface (WSGI) is a standard interface between web
server software and web applications written in Python. Having a standard
interface makes it easy to use an application that supports WSGI with a number
of different web servers.</p>
<p>Only authors of web servers and programming frameworks need to know every detail
and corner case of the WSGI design.  You don’t need to understand every detail
of WSGI just to install a WSGI application or to write a web application using
an existing framework.</p>
<p><a class="reference internal" href="#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a> is a reference implementation of the WSGI specification that can
be used to add WSGI support to a web server or framework.  It provides utilities
for manipulating WSGI environment variables and response headers, base classes
for implementing WSGI servers, a demo HTTP server that serves WSGI applications,
and a validation tool that checks WSGI servers and applications for conformance
to the WSGI specification (<span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>).</p>
<p>See <a class="reference external" href="https://wsgi.readthedocs.org/">https://wsgi.readthedocs.org/</a> for more information about WSGI, and links to
tutorials and other resources.</p>
<div class="section" id="module-wsgiref.util">
<span id="wsgiref-util-wsgi-environment-utilities"></span><h2>20.4.1. <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.util</span></code></a> – WSGI environment utilities<a class="headerlink" href="#module-wsgiref.util" title="Permalink to this headline">¶</a></h2>
<p>This module provides a variety of utility functions for working with WSGI
environments.  A WSGI environment is a dictionary containing HTTP request
variables as described in <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.  All of the functions taking an <em>environ</em>
parameter expect a WSGI-compliant dictionary to be supplied; please see
<span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> for a detailed specification.</p>
<dl class="function">
<dt id="wsgiref.util.guess_scheme">
<code class="descclassname">wsgiref.util.</code><code class="descname">guess_scheme</code><span class="sig-paren">(</span><em>environ</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.guess_scheme" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a guess for whether <code class="docutils literal notranslate"><span class="pre">wsgi.url_scheme</span></code> should be “http” or “https”, by
checking for a <code class="docutils literal notranslate"><span class="pre">HTTPS</span></code> environment variable in the <em>environ</em> dictionary.  The
return value is a string.</p>
<p>This function is useful when creating a gateway that wraps CGI or a CGI-like
protocol such as FastCGI.  Typically, servers providing such protocols will
include a <code class="docutils literal notranslate"><span class="pre">HTTPS</span></code> variable with a value of “1” “yes”, or “on” when a request
is received via SSL.  So, this function returns “https” if such a value is
found, and “http” otherwise.</p>
</dd></dl>

<dl class="function">
<dt id="wsgiref.util.request_uri">
<code class="descclassname">wsgiref.util.</code><code class="descname">request_uri</code><span class="sig-paren">(</span><em>environ</em>, <em>include_query=1</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.request_uri" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the full request URI, optionally including the query string, using the
algorithm found in the “URL Reconstruction” section of <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.  If
<em>include_query</em> is false, the query string is not included in the resulting URI.</p>
</dd></dl>

<dl class="function">
<dt id="wsgiref.util.application_uri">
<code class="descclassname">wsgiref.util.</code><code class="descname">application_uri</code><span class="sig-paren">(</span><em>environ</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.application_uri" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#wsgiref.util.request_uri" title="wsgiref.util.request_uri"><code class="xref py py-func docutils literal notranslate"><span class="pre">request_uri()</span></code></a>, except that the <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> and
<code class="docutils literal notranslate"><span class="pre">QUERY_STRING</span></code> variables are ignored.  The result is the base URI of the
application object addressed by the request.</p>
</dd></dl>

<dl class="function">
<dt id="wsgiref.util.shift_path_info">
<code class="descclassname">wsgiref.util.</code><code class="descname">shift_path_info</code><span class="sig-paren">(</span><em>environ</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.shift_path_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Shift a single name from <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> to <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code> and return the name.
The <em>environ</em> dictionary is <em>modified</em> in-place; use a copy if you need to keep
the original <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> or <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code> intact.</p>
<p>If there are no remaining path segments in <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code> is returned.</p>
<p>Typically, this routine is used to process each portion of a request URI path,
for example to treat the path as a series of dictionary keys. This routine
modifies the passed-in environment to make it suitable for invoking another WSGI
application that is located at the target URI. For example, if there is a WSGI
application at <code class="docutils literal notranslate"><span class="pre">/foo</span></code>, and the request URI path is <code class="docutils literal notranslate"><span class="pre">/foo/bar/baz</span></code>, and the
WSGI application at <code class="docutils literal notranslate"><span class="pre">/foo</span></code> calls <a class="reference internal" href="#wsgiref.util.shift_path_info" title="wsgiref.util.shift_path_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">shift_path_info()</span></code></a>, it will receive the
string “bar”, and the environment will be updated to be suitable for passing to
a WSGI application at <code class="docutils literal notranslate"><span class="pre">/foo/bar</span></code>.  That is, <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code> will change from
<code class="docutils literal notranslate"><span class="pre">/foo</span></code> to <code class="docutils literal notranslate"><span class="pre">/foo/bar</span></code>, and <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> will change from <code class="docutils literal notranslate"><span class="pre">/bar/baz</span></code> to
<code class="docutils literal notranslate"><span class="pre">/baz</span></code>.</p>
<p>When <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> is just a “/”, this routine returns an empty string and
appends a trailing slash to <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code>, even though empty path segments are
normally ignored, and <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code> doesn’t normally end in a slash.  This is
intentional behavior, to ensure that an application can tell the difference
between URIs ending in <code class="docutils literal notranslate"><span class="pre">/x</span></code> from ones ending in <code class="docutils literal notranslate"><span class="pre">/x/</span></code> when using this
routine to do object traversal.</p>
</dd></dl>

<dl class="function">
<dt id="wsgiref.util.setup_testing_defaults">
<code class="descclassname">wsgiref.util.</code><code class="descname">setup_testing_defaults</code><span class="sig-paren">(</span><em>environ</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.setup_testing_defaults" title="Permalink to this definition">¶</a></dt>
<dd><p>Update <em>environ</em> with trivial defaults for testing purposes.</p>
<p>This routine adds various parameters required for WSGI, including <code class="docutils literal notranslate"><span class="pre">HTTP_HOST</span></code>,
<code class="docutils literal notranslate"><span class="pre">SERVER_NAME</span></code>, <code class="docutils literal notranslate"><span class="pre">SERVER_PORT</span></code>, <code class="docutils literal notranslate"><span class="pre">REQUEST_METHOD</span></code>, <code class="docutils literal notranslate"><span class="pre">SCRIPT_NAME</span></code>,
<code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code>, and all of the <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>-defined <code class="docutils literal notranslate"><span class="pre">wsgi.*</span></code> variables.  It
only supplies default values, and does not replace any existing settings for
these variables.</p>
<p>This routine is intended to make it easier for unit tests of WSGI servers and
applications to set up dummy environments.  It should NOT be used by actual WSGI
servers or applications, since the data is fake!</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref.util</span> <span class="k">import</span> <span class="n">setup_testing_defaults</span>
<span class="kn">from</span> <span class="nn">wsgiref.simple_server</span> <span class="k">import</span> <span class="n">make_server</span>

<span class="c1"># A relatively simple WSGI application. It&#39;s going to print out the</span>
<span class="c1"># environment dictionary after being updated by setup_testing_defaults</span>
<span class="k">def</span> <span class="nf">simple_app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">setup_testing_defaults</span><span class="p">(</span><span class="n">environ</span><span class="p">)</span>

    <span class="n">status</span> <span class="o">=</span> <span class="s1">&#39;200 OK&#39;</span>
    <span class="n">headers</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Content-type&#39;</span><span class="p">,</span> <span class="s1">&#39;text/plain&#39;</span><span class="p">)]</span>

    <span class="n">start_response</span><span class="p">(</span><span class="n">status</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>

    <span class="n">ret</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2">: </span><span class="si">%s</span><span class="se">\n</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span>
           <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">environ</span><span class="o">.</span><span class="n">iteritems</span><span class="p">()]</span>
    <span class="k">return</span> <span class="n">ret</span>

<span class="n">httpd</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="n">simple_app</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Serving on port 8000...&quot;</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<p>In addition to the environment functions above, the <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.util</span></code></a> module
also provides these miscellaneous utilities:</p>
<dl class="function">
<dt id="wsgiref.util.is_hop_by_hop">
<code class="descclassname">wsgiref.util.</code><code class="descname">is_hop_by_hop</code><span class="sig-paren">(</span><em>header_name</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.is_hop_by_hop" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by
<span class="target" id="index-5"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2616.html"><strong>RFC 2616</strong></a>.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.util.FileWrapper">
<em class="property">class </em><code class="descclassname">wsgiref.util.</code><code class="descname">FileWrapper</code><span class="sig-paren">(</span><em>filelike</em>, <em>blksize=8192</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.util.FileWrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>A wrapper to convert a file-like object to an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>.  The resulting objects
support both <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> iteration styles, for
compatibility with Python 2.1 and Jython. As the object is iterated over, the
optional <em>blksize</em> parameter will be repeatedly passed to the <em>filelike</em>
object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method to obtain strings to yield.  When <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>
returns an empty string, iteration is ended and is not resumable.</p>
<p>If <em>filelike</em> has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method, the returned object will also have a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method, and it will invoke the <em>filelike</em> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>
method when called.</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">StringIO</span> <span class="k">import</span> <span class="n">StringIO</span>
<span class="kn">from</span> <span class="nn">wsgiref.util</span> <span class="k">import</span> <span class="n">FileWrapper</span>

<span class="c1"># We&#39;re using a StringIO-buffer for as the file-like object</span>
<span class="n">filelike</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">(</span><span class="s2">&quot;This is an example file-like object&quot;</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span>
<span class="n">wrapper</span> <span class="o">=</span> <span class="n">FileWrapper</span><span class="p">(</span><span class="n">filelike</span><span class="p">,</span> <span class="n">blksize</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>

<span class="k">for</span> <span class="n">chunk</span> <span class="ow">in</span> <span class="n">wrapper</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">chunk</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="module-wsgiref.headers">
<span id="wsgiref-headers-wsgi-response-header-tools"></span><h2>20.4.2. <a class="reference internal" href="#module-wsgiref.headers" title="wsgiref.headers: WSGI response header tools."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.headers</span></code></a> – WSGI response header tools<a class="headerlink" href="#module-wsgiref.headers" title="Permalink to this headline">¶</a></h2>
<p>This module provides a single class, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a>, for convenient
manipulation of WSGI response headers using a mapping-like interface.</p>
<dl class="class">
<dt id="wsgiref.headers.Headers">
<em class="property">class </em><code class="descclassname">wsgiref.headers.</code><code class="descname">Headers</code><span class="sig-paren">(</span><em>headers</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.headers.Headers" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a mapping-like object wrapping <em>headers</em>, which must be a list of header
name/value tuples as described in <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.  Any changes made to the new
<a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> object will directly update the <em>headers</em> list it was created
with.</p>
<p><a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> objects support typical mapping operations including
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code>,
<a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code>.  For each of
these methods, the key is the header name (treated case-insensitively), and the
value is the first value associated with that header name.  Setting a header
deletes any existing values for that header, then adds a new value at the end of
the wrapped header list.  Headers’ existing order is generally maintained, with
new headers added to the end of the wrapped list.</p>
<p>Unlike a dictionary, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> objects do not raise an error when you try
to get or delete a key that isn’t in the wrapped header list. Getting a
nonexistent header just returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, and deleting a nonexistent header does
nothing.</p>
<p><a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> objects also support <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> methods.  The lists returned by <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> can
include the same key more than once if there is a multi-valued header.  The
<code class="docutils literal notranslate"><span class="pre">len()</span></code> of a <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> object is the same as the length of its
<code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, which is the same as the length of the wrapped header list.  In
fact, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code> method just returns a copy of the wrapped header list.</p>
<p>Calling <code class="docutils literal notranslate"><span class="pre">str()</span></code> on a <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a> object returns a formatted string
suitable for transmission as HTTP response headers.  Each header is placed on a
line with its value, separated by a colon and a space. Each line is terminated
by a carriage return and line feed, and the string is terminated with a blank
line.</p>
<p>In addition to their mapping interface and formatting features, <a class="reference internal" href="#wsgiref.headers.Headers" title="wsgiref.headers.Headers"><code class="xref py py-class docutils literal notranslate"><span class="pre">Headers</span></code></a>
objects also have the following methods for querying and adding multi-valued
headers, and for adding headers with MIME parameters:</p>
<dl class="method">
<dt id="wsgiref.headers.Headers.get_all">
<code class="descname">get_all</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.headers.Headers.get_all" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of all the values for the named header.</p>
<p>The returned list will be sorted in the order they appeared in the original
header list or were added to this instance, and may contain duplicates.  Any
fields deleted and re-inserted are always appended to the header list.  If no
fields exist with the given name, returns an empty list.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.headers.Headers.add_header">
<code class="descname">add_header</code><span class="sig-paren">(</span><em>name</em>, <em>value</em>, <em>**_params</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.headers.Headers.add_header" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a (possibly multi-valued) header, with optional MIME parameters specified
via keyword arguments.</p>
<p><em>name</em> is the header field to add.  Keyword arguments can be used to set MIME
parameters for the header field.  Each parameter must be a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.
Underscores in parameter names are converted to dashes, since dashes are illegal
in Python identifiers, but many MIME parameter names include dashes.  If the
parameter value is a string, it is added to the header value parameters in the
form <code class="docutils literal notranslate"><span class="pre">name=&quot;value&quot;</span></code>. If it is <code class="docutils literal notranslate"><span class="pre">None</span></code>, only the parameter name is added.
(This is used for MIME parameters without a value.)  Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">h</span><span class="o">.</span><span class="n">add_header</span><span class="p">(</span><span class="s1">&#39;content-disposition&#39;</span><span class="p">,</span> <span class="s1">&#39;attachment&#39;</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s1">&#39;bud.gif&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The above will add a header that looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Content</span><span class="o">-</span><span class="n">Disposition</span><span class="p">:</span> <span class="n">attachment</span><span class="p">;</span> <span class="n">filename</span><span class="o">=</span><span class="s2">&quot;bud.gif&quot;</span>
</pre></div>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="module-wsgiref.simple_server">
<span id="wsgiref-simple-server-a-simple-wsgi-http-server"></span><h2>20.4.3. <a class="reference internal" href="#module-wsgiref.simple_server" title="wsgiref.simple_server: A simple WSGI HTTP server."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code></a> – a simple WSGI HTTP server<a class="headerlink" href="#module-wsgiref.simple_server" title="Permalink to this headline">¶</a></h2>
<p>This module implements a simple HTTP server (based on <a class="reference internal" href="basehttpserver.html#module-BaseHTTPServer" title="BaseHTTPServer: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code></a>)
that serves WSGI applications.  Each server instance serves a single WSGI
application on a given host and port.  If you want to serve multiple
applications on a single host and port, you should create a WSGI application
that parses <code class="docutils literal notranslate"><span class="pre">PATH_INFO</span></code> to select which application to invoke for each
request.  (E.g., using the <code class="xref py py-func docutils literal notranslate"><span class="pre">shift_path_info()</span></code> function from
<a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.util</span></code></a>.)</p>
<dl class="function">
<dt id="wsgiref.simple_server.make_server">
<code class="descclassname">wsgiref.simple_server.</code><code class="descname">make_server</code><span class="sig-paren">(</span><em>host</em>, <em>port</em>, <em>app</em>, <em>server_class=WSGIServer</em>, <em>handler_class=WSGIRequestHandler</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.make_server" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new WSGI server listening on <em>host</em> and <em>port</em>, accepting connections
for <em>app</em>.  The return value is an instance of the supplied <em>server_class</em>, and
will process requests using the specified <em>handler_class</em>.  <em>app</em> must be a WSGI
application object, as defined by <span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref.simple_server</span> <span class="k">import</span> <span class="n">make_server</span><span class="p">,</span> <span class="n">demo_app</span>

<span class="n">httpd</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="n">demo_app</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Serving HTTP on port 8000...&quot;</span>

<span class="c1"># Respond to requests until process is killed</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>

<span class="c1"># Alternative: serve one request, then exit</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">handle_request</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="wsgiref.simple_server.demo_app">
<code class="descclassname">wsgiref.simple_server.</code><code class="descname">demo_app</code><span class="sig-paren">(</span><em>environ</em>, <em>start_response</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.demo_app" title="Permalink to this definition">¶</a></dt>
<dd><p>This function is a small but complete WSGI application that returns a text page
containing the message “Hello world!” and a list of the key/value pairs provided
in the <em>environ</em> parameter.  It’s useful for verifying that a WSGI server (such
as <a class="reference internal" href="#module-wsgiref.simple_server" title="wsgiref.simple_server: A simple WSGI HTTP server."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code></a>) is able to run a simple WSGI application
correctly.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.simple_server.WSGIServer">
<em class="property">class </em><code class="descclassname">wsgiref.simple_server.</code><code class="descname">WSGIServer</code><span class="sig-paren">(</span><em>server_address</em>, <em>RequestHandlerClass</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIServer" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> instance.  <em>server_address</em> should be a
<code class="docutils literal notranslate"><span class="pre">(host,port)</span></code> tuple, and <em>RequestHandlerClass</em> should be the subclass of
<a class="reference internal" href="basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler" title="BaseHTTPServer.BaseHTTPRequestHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPServer.BaseHTTPRequestHandler</span></code></a> that will be used to process
requests.</p>
<p>You do not normally need to call this constructor, as the <a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_server()</span></code></a>
function can handle all the details for you.</p>
<p><a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> is a subclass of <a class="reference internal" href="basehttpserver.html#BaseHTTPServer.HTTPServer" title="BaseHTTPServer.HTTPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHTTPServer.HTTPServer</span></code></a>, so all
of its methods (such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code>) are
available. <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> also provides these WSGI-specific methods:</p>
<dl class="method">
<dt id="wsgiref.simple_server.WSGIServer.set_app">
<code class="descname">set_app</code><span class="sig-paren">(</span><em>application</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIServer.set_app" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the callable <em>application</em> as the WSGI application that will receive
requests.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.simple_server.WSGIServer.get_app">
<code class="descname">get_app</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIServer.get_app" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the currently-set application callable.</p>
</dd></dl>

<p>Normally, however, you do not need to use these additional methods, as
<a class="reference internal" href="#wsgiref.simple_server.WSGIServer.set_app" title="wsgiref.simple_server.WSGIServer.set_app"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_app()</span></code></a> is normally called by <a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_server()</span></code></a>, and the
<a class="reference internal" href="#wsgiref.simple_server.WSGIServer.get_app" title="wsgiref.simple_server.WSGIServer.get_app"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_app()</span></code></a> exists mainly for the benefit of request handler instances.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.simple_server.WSGIRequestHandler">
<em class="property">class </em><code class="descclassname">wsgiref.simple_server.</code><code class="descname">WSGIRequestHandler</code><span class="sig-paren">(</span><em>request</em>, <em>client_address</em>, <em>server</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIRequestHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an HTTP handler for the given <em>request</em> (i.e. a socket), <em>client_address</em>
(a <code class="docutils literal notranslate"><span class="pre">(host,port)</span></code> tuple), and <em>server</em> (<a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> instance).</p>
<p>You do not need to create instances of this class directly; they are
automatically created as needed by <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> objects.  You can,
however, subclass this class and supply it as a <em>handler_class</em> to the
<a class="reference internal" href="#wsgiref.simple_server.make_server" title="wsgiref.simple_server.make_server"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_server()</span></code></a> function.  Some possibly relevant methods for overriding in
subclasses:</p>
<dl class="method">
<dt id="wsgiref.simple_server.WSGIRequestHandler.get_environ">
<code class="descname">get_environ</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIRequestHandler.get_environ" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a dictionary containing the WSGI environment for a request.  The default
implementation copies the contents of the <a class="reference internal" href="#wsgiref.simple_server.WSGIServer" title="wsgiref.simple_server.WSGIServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">WSGIServer</span></code></a> object’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">base_environ</span></code> dictionary attribute and then adds various headers derived
from the HTTP request.  Each call to this method should return a new dictionary
containing all of the relevant CGI environment variables as specified in
<span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.simple_server.WSGIRequestHandler.get_stderr">
<code class="descname">get_stderr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIRequestHandler.get_stderr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the object that should be used as the <code class="docutils literal notranslate"><span class="pre">wsgi.errors</span></code> stream. The default
implementation just returns <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.simple_server.WSGIRequestHandler.handle">
<code class="descname">handle</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.simple_server.WSGIRequestHandler.handle" title="Permalink to this definition">¶</a></dt>
<dd><p>Process the HTTP request.  The default implementation creates a handler instance
using a <a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code></a> class to implement the actual WSGI application
interface.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="module-wsgiref.validate">
<span id="wsgiref-validate-wsgi-conformance-checker"></span><h2>20.4.4. <a class="reference internal" href="#module-wsgiref.validate" title="wsgiref.validate: WSGI conformance checker."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.validate</span></code></a> — WSGI conformance checker<a class="headerlink" href="#module-wsgiref.validate" title="Permalink to this headline">¶</a></h2>
<p>When creating new WSGI application objects, frameworks, servers, or middleware,
it can be useful to validate the new code’s conformance using
<a class="reference internal" href="#module-wsgiref.validate" title="wsgiref.validate: WSGI conformance checker."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.validate</span></code></a>.  This module provides a function that creates WSGI
application objects that validate communications between a WSGI server or
gateway and a WSGI application object, to check both sides for protocol
conformance.</p>
<p>Note that this utility does not guarantee complete <span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> compliance; an
absence of errors from this module does not necessarily mean that errors do not
exist.  However, if this module does produce an error, then it is virtually
certain that either the server or application is not 100% compliant.</p>
<p>This module is based on the <code class="xref py py-mod docutils literal notranslate"><span class="pre">paste.lint</span></code> module from Ian Bicking’s “Python
Paste” library.</p>
<dl class="function">
<dt id="wsgiref.validate.validator">
<code class="descclassname">wsgiref.validate.</code><code class="descname">validator</code><span class="sig-paren">(</span><em>application</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.validate.validator" title="Permalink to this definition">¶</a></dt>
<dd><p>Wrap <em>application</em> and return a new WSGI application object.  The returned
application will forward all requests to the original <em>application</em>, and will
check that both the <em>application</em> and the server invoking it are conforming to
the WSGI specification and to RFC 2616.</p>
<p>Any detected nonconformance results in an <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> being raised;
note, however, that how these errors are handled is server-dependent.  For
example, <a class="reference internal" href="#module-wsgiref.simple_server" title="wsgiref.simple_server: A simple WSGI HTTP server."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code></a> and other servers based on
<a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code></a> (that don’t override the error handling methods to do
something else) will simply output a message that an error has occurred, and
dump the traceback to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> or some other error stream.</p>
<p>This wrapper may also generate output using the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module to
indicate behaviors that are questionable but which may not actually be
prohibited by <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.  Unless they are suppressed using Python command-line
options or the <a class="reference internal" href="warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> API, any such warnings will be written to
<code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> (<em>not</em> <code class="docutils literal notranslate"><span class="pre">wsgi.errors</span></code>, unless they happen to be the same
object).</p>
<p>Example usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref.validate</span> <span class="k">import</span> <span class="n">validator</span>
<span class="kn">from</span> <span class="nn">wsgiref.simple_server</span> <span class="k">import</span> <span class="n">make_server</span>

<span class="c1"># Our callable object which is intentionally not compliant to the</span>
<span class="c1"># standard, so the validator is going to break</span>
<span class="k">def</span> <span class="nf">simple_app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">status</span> <span class="o">=</span> <span class="s1">&#39;200 OK&#39;</span>  <span class="c1"># HTTP Status</span>
    <span class="n">headers</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Content-type&#39;</span><span class="p">,</span> <span class="s1">&#39;text/plain&#39;</span><span class="p">)]</span>  <span class="c1"># HTTP Headers</span>
    <span class="n">start_response</span><span class="p">(</span><span class="n">status</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>

    <span class="c1"># This is going to break because we need to return a list, and</span>
    <span class="c1"># the validator is going to inform us</span>
    <span class="k">return</span> <span class="s2">&quot;Hello World&quot;</span>

<span class="c1"># This is the application wrapped in a validator</span>
<span class="n">validator_app</span> <span class="o">=</span> <span class="n">validator</span><span class="p">(</span><span class="n">simple_app</span><span class="p">)</span>

<span class="n">httpd</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="n">validator_app</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000....&quot;</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="module-wsgiref.handlers">
<span id="wsgiref-handlers-server-gateway-base-classes"></span><h2>20.4.5. <a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code></a> – server/gateway base classes<a class="headerlink" href="#module-wsgiref.handlers" title="Permalink to this headline">¶</a></h2>
<p>This module provides base handler classes for implementing WSGI servers and
gateways.  These base classes handle most of the work of communicating with a
WSGI application, as long as they are given a CGI-like environment, along with
input, output, and error streams.</p>
<dl class="class">
<dt id="wsgiref.handlers.CGIHandler">
<em class="property">class </em><code class="descclassname">wsgiref.handlers.</code><code class="descname">CGIHandler</code><a class="headerlink" href="#wsgiref.handlers.CGIHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>CGI-based invocation via <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> and
<code class="docutils literal notranslate"><span class="pre">os.environ</span></code>.  This is useful when you have a WSGI application and want to run
it as a CGI script.  Simply invoke <code class="docutils literal notranslate"><span class="pre">CGIHandler().run(app)</span></code>, where <code class="docutils literal notranslate"><span class="pre">app</span></code> is
the WSGI application object you wish to invoke.</p>
<p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCGIHandler</span></code></a> that sets <code class="docutils literal notranslate"><span class="pre">wsgi.run_once</span></code>
to true, <code class="docutils literal notranslate"><span class="pre">wsgi.multithread</span></code> to false, and <code class="docutils literal notranslate"><span class="pre">wsgi.multiprocess</span></code> to true, and
always uses <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> and <a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> to obtain the necessary CGI streams and
environment.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.handlers.BaseCGIHandler">
<em class="property">class </em><code class="descclassname">wsgiref.handlers.</code><code class="descname">BaseCGIHandler</code><span class="sig-paren">(</span><em>stdin</em>, <em>stdout</em>, <em>stderr</em>, <em>environ</em>, <em>multithread=True</em>, <em>multiprocess=False</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseCGIHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHandler</span></code></a>, but instead of using the <a class="reference internal" href="sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> and
<a class="reference internal" href="os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> modules, the CGI environment and I/O streams are specified explicitly.
The <em>multithread</em> and <em>multiprocess</em> values are used to set the
<code class="docutils literal notranslate"><span class="pre">wsgi.multithread</span></code> and <code class="docutils literal notranslate"><span class="pre">wsgi.multiprocess</span></code> flags for any applications run by
the handler instance.</p>
<p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.SimpleHandler" title="wsgiref.handlers.SimpleHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHandler</span></code></a> intended for use with
software other than HTTP “origin servers”.  If you are writing a gateway
protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a
<code class="docutils literal notranslate"><span class="pre">Status:</span></code> header to send an HTTP status, you probably want to subclass this
instead of <a class="reference internal" href="#wsgiref.handlers.SimpleHandler" title="wsgiref.handlers.SimpleHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleHandler</span></code></a>.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.handlers.SimpleHandler">
<em class="property">class </em><code class="descclassname">wsgiref.handlers.</code><code class="descname">SimpleHandler</code><span class="sig-paren">(</span><em>stdin</em>, <em>stdout</em>, <em>stderr</em>, <em>environ</em>, <em>multithread=True</em>, <em>multiprocess=False</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.SimpleHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCGIHandler</span></code></a>, but designed for use with HTTP origin
servers.  If you are writing an HTTP server implementation, you will probably
want to subclass this instead of <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCGIHandler</span></code></a>.</p>
<p>This class is a subclass of <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>.  It overrides the
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stdin()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stderr()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">add_cgi_vars()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">_write()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">_flush()</span></code> methods to support explicitly setting the
environment and streams via the constructor.  The supplied environment and
streams are stored in the <code class="xref py py-attr docutils literal notranslate"><span class="pre">stdin</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">stdout</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">stderr</span></code>, and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">environ</span></code> attributes.</p>
</dd></dl>

<dl class="class">
<dt id="wsgiref.handlers.BaseHandler">
<em class="property">class </em><code class="descclassname">wsgiref.handlers.</code><code class="descname">BaseHandler</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an abstract base class for running WSGI applications.  Each instance
will handle a single HTTP request, although in principle you could create a
subclass that was reusable for multiple requests.</p>
<p><a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> instances have only one method intended for external use:</p>
<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.run">
<code class="descname">run</code><span class="sig-paren">(</span><em>app</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.run" title="Permalink to this definition">¶</a></dt>
<dd><p>Run the specified WSGI application, <em>app</em>.</p>
</dd></dl>

<p>All of the other <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> methods are invoked by this method in the
process of running the application, and thus exist primarily to allow
customizing the process.</p>
<p>The following methods MUST be overridden in a subclass:</p>
<dl class="method">
<dt id="wsgiref.handlers.BaseHandler._write">
<code class="descname">_write</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler._write" title="Permalink to this definition">¶</a></dt>
<dd><p>Buffer the string <em>data</em> for transmission to the client.  It’s okay if this
method actually transmits the data; <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a> just separates write
and flush operations for greater efficiency when the underlying system actually
has such a distinction.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler._flush">
<code class="descname">_flush</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler._flush" title="Permalink to this definition">¶</a></dt>
<dd><p>Force buffered data to be transmitted to the client.  It’s okay if this method
is a no-op (i.e., if <a class="reference internal" href="#wsgiref.handlers.BaseHandler._write" title="wsgiref.handlers.BaseHandler._write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_write()</span></code></a> actually sends the data).</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.get_stdin">
<code class="descname">get_stdin</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.get_stdin" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an input stream object suitable for use as the <code class="docutils literal notranslate"><span class="pre">wsgi.input</span></code> of the
request currently being processed.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.get_stderr">
<code class="descname">get_stderr</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.get_stderr" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an output stream object suitable for use as the <code class="docutils literal notranslate"><span class="pre">wsgi.errors</span></code> of the
request currently being processed.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.add_cgi_vars">
<code class="descname">add_cgi_vars</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.add_cgi_vars" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert CGI variables for the current request into the <code class="xref py py-attr docutils literal notranslate"><span class="pre">environ</span></code> attribute.</p>
</dd></dl>

<p>Here are some other methods and attributes you may wish to override. This list
is only a summary, however, and does not include every method that can be
overridden.  You should consult the docstrings and source code for additional
information before attempting to create a customized <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>
subclass.</p>
<p>Attributes and methods for customizing the WSGI environment:</p>
<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.wsgi_multithread">
<code class="descname">wsgi_multithread</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.wsgi_multithread" title="Permalink to this definition">¶</a></dt>
<dd><p>The value to be used for the <code class="docutils literal notranslate"><span class="pre">wsgi.multithread</span></code> environment variable.  It
defaults to true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but may have a different default (or
be set by the constructor) in the other subclasses.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.wsgi_multiprocess">
<code class="descname">wsgi_multiprocess</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.wsgi_multiprocess" title="Permalink to this definition">¶</a></dt>
<dd><p>The value to be used for the <code class="docutils literal notranslate"><span class="pre">wsgi.multiprocess</span></code> environment variable.  It
defaults to true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but may have a different default (or
be set by the constructor) in the other subclasses.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.wsgi_run_once">
<code class="descname">wsgi_run_once</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.wsgi_run_once" title="Permalink to this definition">¶</a></dt>
<dd><p>The value to be used for the <code class="docutils literal notranslate"><span class="pre">wsgi.run_once</span></code> environment variable.  It
defaults to false in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHandler</span></code></a> sets it to
true by default.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.os_environ">
<code class="descname">os_environ</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.os_environ" title="Permalink to this definition">¶</a></dt>
<dd><p>The default environment variables to be included in every request’s WSGI
environment.  By default, this is a copy of <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> at the time that
<a class="reference internal" href="#module-wsgiref.handlers" title="wsgiref.handlers: WSGI server/gateway base classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code></a> was imported, but subclasses can either create their own
at the class or instance level.  Note that the dictionary should be considered
read-only, since the default value is shared between multiple classes and
instances.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.server_software">
<code class="descname">server_software</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.server_software" title="Permalink to this definition">¶</a></dt>
<dd><p>If the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code class="xref py py-attr docutils literal notranslate"><span class="pre">origin_server</span></code></a> attribute is set, this attribute’s value is used to
set the default <code class="docutils literal notranslate"><span class="pre">SERVER_SOFTWARE</span></code> WSGI environment variable, and also to set a
default <code class="docutils literal notranslate"><span class="pre">Server:</span></code> header in HTTP responses.  It is ignored for handlers (such
as <a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCGIHandler</span></code></a> and <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHandler</span></code></a>) that are not HTTP origin
servers.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.get_scheme">
<code class="descname">get_scheme</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.get_scheme" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the URL scheme being used for the current request.  The default
implementation uses the <code class="xref py py-func docutils literal notranslate"><span class="pre">guess_scheme()</span></code> function from <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.util</span></code></a>
to guess whether the scheme should be “http” or “https”, based on the current
request’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">environ</span></code> variables.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.setup_environ">
<code class="descname">setup_environ</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.setup_environ" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">environ</span></code> attribute to a fully-populated WSGI environment.  The
default implementation uses all of the above methods and attributes, plus the
<a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stdin" title="wsgiref.handlers.BaseHandler.get_stdin"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stdin()</span></code></a>, <a class="reference internal" href="#wsgiref.handlers.BaseHandler.get_stderr" title="wsgiref.handlers.BaseHandler.get_stderr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_stderr()</span></code></a>, and <a class="reference internal" href="#wsgiref.handlers.BaseHandler.add_cgi_vars" title="wsgiref.handlers.BaseHandler.add_cgi_vars"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_cgi_vars()</span></code></a> methods and the
<a class="reference internal" href="#wsgiref.handlers.BaseHandler.wsgi_file_wrapper" title="wsgiref.handlers.BaseHandler.wsgi_file_wrapper"><code class="xref py py-attr docutils literal notranslate"><span class="pre">wsgi_file_wrapper</span></code></a> attribute.  It also inserts a <code class="docutils literal notranslate"><span class="pre">SERVER_SOFTWARE</span></code> key
if not present, as long as the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code class="xref py py-attr docutils literal notranslate"><span class="pre">origin_server</span></code></a> attribute is a true value
and the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.server_software" title="wsgiref.handlers.BaseHandler.server_software"><code class="xref py py-attr docutils literal notranslate"><span class="pre">server_software</span></code></a> attribute is set.</p>
</dd></dl>

<p>Methods and attributes for customizing exception handling:</p>
<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.log_exception">
<code class="descname">log_exception</code><span class="sig-paren">(</span><em>exc_info</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.log_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Log the <em>exc_info</em> tuple in the server log.  <em>exc_info</em> is a <code class="docutils literal notranslate"><span class="pre">(type,</span> <span class="pre">value,</span>
<span class="pre">traceback)</span></code> tuple.  The default implementation simply writes the traceback to
the request’s <code class="docutils literal notranslate"><span class="pre">wsgi.errors</span></code> stream and flushes it.  Subclasses can override
this method to change the format or retarget the output, mail the traceback to
an administrator, or whatever other action may be deemed suitable.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.traceback_limit">
<code class="descname">traceback_limit</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.traceback_limit" title="Permalink to this definition">¶</a></dt>
<dd><p>The maximum number of frames to include in tracebacks output by the default
<a class="reference internal" href="#wsgiref.handlers.BaseHandler.log_exception" title="wsgiref.handlers.BaseHandler.log_exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">log_exception()</span></code></a> method.  If <code class="docutils literal notranslate"><span class="pre">None</span></code>, all frames are included.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.error_output">
<code class="descname">error_output</code><span class="sig-paren">(</span><em>environ</em>, <em>start_response</em><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.error_output" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is a WSGI application to generate an error page for the user.  It is
only invoked if an error occurs before headers are sent to the client.</p>
<p>This method can access the current error information using <code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code>,
and should pass that information to <em>start_response</em> when calling it (as
described in the “Error Handling” section of <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>).</p>
<p>The default implementation just uses the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_status" title="wsgiref.handlers.BaseHandler.error_status"><code class="xref py py-attr docutils literal notranslate"><span class="pre">error_status</span></code></a>,
<a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_headers" title="wsgiref.handlers.BaseHandler.error_headers"><code class="xref py py-attr docutils literal notranslate"><span class="pre">error_headers</span></code></a>, and <a class="reference internal" href="#wsgiref.handlers.BaseHandler.error_body" title="wsgiref.handlers.BaseHandler.error_body"><code class="xref py py-attr docutils literal notranslate"><span class="pre">error_body</span></code></a> attributes to generate an output
page.  Subclasses can override this to produce more dynamic error output.</p>
<p>Note, however, that it’s not recommended from a security perspective to spit out
diagnostics to any old user; ideally, you should have to do something special to
enable diagnostic output, which is why the default implementation doesn’t
include any.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.error_status">
<code class="descname">error_status</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.error_status" title="Permalink to this definition">¶</a></dt>
<dd><p>The HTTP status used for error responses.  This should be a status string as
defined in <span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>; it defaults to a 500 code and message.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.error_headers">
<code class="descname">error_headers</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.error_headers" title="Permalink to this definition">¶</a></dt>
<dd><p>The HTTP headers used for error responses.  This should be a list of WSGI
response headers (<code class="docutils literal notranslate"><span class="pre">(name,</span> <span class="pre">value)</span></code> tuples), as described in <span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.  The
default list just sets the content type to <code class="docutils literal notranslate"><span class="pre">text/plain</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.error_body">
<code class="descname">error_body</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.error_body" title="Permalink to this definition">¶</a></dt>
<dd><p>The error response body.  This should be an HTTP response body string. It
defaults to the plain text, “A server error occurred.  Please contact the
administrator.”</p>
</dd></dl>

<p>Methods and attributes for <span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>’s “Optional Platform-Specific File
Handling” feature:</p>
<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.wsgi_file_wrapper">
<code class="descname">wsgi_file_wrapper</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.wsgi_file_wrapper" title="Permalink to this definition">¶</a></dt>
<dd><p>A <code class="docutils literal notranslate"><span class="pre">wsgi.file_wrapper</span></code> factory, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The default value of this
attribute is the <code class="xref py py-class docutils literal notranslate"><span class="pre">FileWrapper</span></code> class from <a class="reference internal" href="#module-wsgiref.util" title="wsgiref.util: WSGI environment utilities."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref.util</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="wsgiref.handlers.BaseHandler.sendfile">
<code class="descname">sendfile</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#wsgiref.handlers.BaseHandler.sendfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Override to implement platform-specific file transmission.  This method is
called only if the application’s return value is an instance of the class
specified by the <a class="reference internal" href="#wsgiref.handlers.BaseHandler.wsgi_file_wrapper" title="wsgiref.handlers.BaseHandler.wsgi_file_wrapper"><code class="xref py py-attr docutils literal notranslate"><span class="pre">wsgi_file_wrapper</span></code></a> attribute.  It should return a true
value if it was able to successfully transmit the file, so that the default
transmission code will not be executed. The default implementation of this
method just returns a false value.</p>
</dd></dl>

<p>Miscellaneous methods and attributes:</p>
<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.origin_server">
<code class="descname">origin_server</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.origin_server" title="Permalink to this definition">¶</a></dt>
<dd><p>This attribute should be set to a true value if the handler’s <a class="reference internal" href="#wsgiref.handlers.BaseHandler._write" title="wsgiref.handlers.BaseHandler._write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_write()</span></code></a> and
<a class="reference internal" href="#wsgiref.handlers.BaseHandler._flush" title="wsgiref.handlers.BaseHandler._flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_flush()</span></code></a> are being used to communicate directly to the client, rather than
via a CGI-like gateway protocol that wants the HTTP status in a special
<code class="docutils literal notranslate"><span class="pre">Status:</span></code> header.</p>
<p>This attribute’s default value is true in <a class="reference internal" href="#wsgiref.handlers.BaseHandler" title="wsgiref.handlers.BaseHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseHandler</span></code></a>, but false in
<a class="reference internal" href="#wsgiref.handlers.BaseCGIHandler" title="wsgiref.handlers.BaseCGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseCGIHandler</span></code></a> and <a class="reference internal" href="#wsgiref.handlers.CGIHandler" title="wsgiref.handlers.CGIHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">CGIHandler</span></code></a>.</p>
</dd></dl>

<dl class="attribute">
<dt id="wsgiref.handlers.BaseHandler.http_version">
<code class="descname">http_version</code><a class="headerlink" href="#wsgiref.handlers.BaseHandler.http_version" title="Permalink to this definition">¶</a></dt>
<dd><p>If <a class="reference internal" href="#wsgiref.handlers.BaseHandler.origin_server" title="wsgiref.handlers.BaseHandler.origin_server"><code class="xref py py-attr docutils literal notranslate"><span class="pre">origin_server</span></code></a> is true, this string attribute is used to set the HTTP
version of the response set to the client.  It defaults to <code class="docutils literal notranslate"><span class="pre">&quot;1.0&quot;</span></code>.</p>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="examples">
<h2>20.4.6. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>This is a working “Hello World” WSGI application:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref.simple_server</span> <span class="k">import</span> <span class="n">make_server</span>

<span class="c1"># Every WSGI application must have an application object - a callable</span>
<span class="c1"># object that accepts two arguments. For that purpose, we&#39;re going to</span>
<span class="c1"># use a function (note that you&#39;re not limited to a function, you can</span>
<span class="c1"># use a class for example). The first argument passed to the function</span>
<span class="c1"># is a dictionary containing CGI-style environment variables and the</span>
<span class="c1"># second variable is the callable object (see PEP 333).</span>
<span class="k">def</span> <span class="nf">hello_world_app</span><span class="p">(</span><span class="n">environ</span><span class="p">,</span> <span class="n">start_response</span><span class="p">):</span>
    <span class="n">status</span> <span class="o">=</span> <span class="s1">&#39;200 OK&#39;</span>  <span class="c1"># HTTP Status</span>
    <span class="n">headers</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;Content-type&#39;</span><span class="p">,</span> <span class="s1">&#39;text/plain&#39;</span><span class="p">)]</span>  <span class="c1"># HTTP Headers</span>
    <span class="n">start_response</span><span class="p">(</span><span class="n">status</span><span class="p">,</span> <span class="n">headers</span><span class="p">)</span>

    <span class="c1"># The returned object is going to be printed</span>
    <span class="k">return</span> <span class="p">[</span><span class="s2">&quot;Hello World&quot;</span><span class="p">]</span>

<span class="n">httpd</span> <span class="o">=</span> <span class="n">make_server</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="n">hello_world_app</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Serving on port 8000...&quot;</span>

<span class="c1"># Serve until process is killed</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a><ul>
<li><a class="reference internal" href="#module-wsgiref.util">20.4.1. <code class="docutils literal notranslate"><span class="pre">wsgiref.util</span></code> – WSGI environment utilities</a></li>
<li><a class="reference internal" href="#module-wsgiref.headers">20.4.2. <code class="docutils literal notranslate"><span class="pre">wsgiref.headers</span></code> – WSGI response header tools</a></li>
<li><a class="reference internal" href="#module-wsgiref.simple_server">20.4.3. <code class="docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code> – a simple WSGI HTTP server</a></li>
<li><a class="reference internal" href="#module-wsgiref.validate">20.4.4. <code class="docutils literal notranslate"><span class="pre">wsgiref.validate</span></code> — WSGI conformance checker</a></li>
<li><a class="reference internal" href="#module-wsgiref.handlers">20.4.5. <code class="docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code> – server/gateway base classes</a></li>
<li><a class="reference internal" href="#examples">20.4.6. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cgitb.html"
                        title="previous chapter">20.3. <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> — Traceback manager for CGI scripts</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="urllib.html"
                        title="next chapter">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/wsgiref.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="urllib.html" title="20.5. urllib — Open arbitrary resources by URL"
             >next</a> |</li>
        <li class="right" >
          <a href="cgitb.html" title="20.3. cgitb — Traceback manager for CGI scripts"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�
]����html/library/xdrlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13.5. xdrlib — Encode and decode XDR data &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13.6. plistlib — Generate and parse Mac OS X .plist files" href="plistlib.html" />
    <link rel="prev" title="13.4. netrc — netrc file processing" href="netrc.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xdrlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="plistlib.html" title="13.6. plistlib — Generate and parse Mac OS X .plist files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="13.4. netrc — netrc file processing"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" accesskey="U">13. File Formats</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xdrlib">
<span id="xdrlib-encode-and-decode-xdr-data"></span><h1>13.5. <a class="reference internal" href="#module-xdrlib" title="xdrlib: Encoders and decoders for the External Data Representation (XDR)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xdrlib</span></code></a> — Encode and decode XDR data<a class="headerlink" href="#module-xdrlib" title="Permalink to this headline">¶</a></h1>
<p id="index-0"><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/xdrlib.py">Lib/xdrlib.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#module-xdrlib" title="xdrlib: Encoders and decoders for the External Data Representation (XDR)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xdrlib</span></code></a> module supports the External Data Representation Standard as
described in <span class="target" id="index-1"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1014.html"><strong>RFC 1014</strong></a>, written by Sun Microsystems, Inc. June 1987.  It
supports most of the data types described in the RFC.</p>
<p>The <a class="reference internal" href="#module-xdrlib" title="xdrlib: Encoders and decoders for the External Data Representation (XDR)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xdrlib</span></code></a> module defines two classes, one for packing variables into XDR
representation, and another for unpacking from XDR representation.  There are
also two exception classes.</p>
<dl class="class">
<dt id="xdrlib.Packer">
<em class="property">class </em><code class="descclassname">xdrlib.</code><code class="descname">Packer</code><a class="headerlink" href="#xdrlib.Packer" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#xdrlib.Packer" title="xdrlib.Packer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Packer</span></code></a> is the class for packing data into XDR representation. The
<a class="reference internal" href="#xdrlib.Packer" title="xdrlib.Packer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Packer</span></code></a> class is instantiated with no arguments.</p>
</dd></dl>

<dl class="class">
<dt id="xdrlib.Unpacker">
<em class="property">class </em><code class="descclassname">xdrlib.</code><code class="descname">Unpacker</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker" title="Permalink to this definition">¶</a></dt>
<dd><p><code class="docutils literal notranslate"><span class="pre">Unpacker</span></code> is the complementary class which unpacks XDR data values from a
string buffer.  The input buffer is given as <em>data</em>.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1014.html"><strong>RFC 1014</strong></a> - XDR: External Data Representation Standard</dt>
<dd>This RFC defined the encoding of data which was XDR at the time this module was
originally written.  It has apparently been obsoleted by <span class="target" id="index-3"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1832.html"><strong>RFC 1832</strong></a>.</dd>
<dt><span class="target" id="index-4"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc1832.html"><strong>RFC 1832</strong></a> - XDR: External Data Representation Standard</dt>
<dd>Newer RFC that provides a revised definition of XDR.</dd>
</dl>
</div>
<div class="section" id="packer-objects">
<span id="xdr-packer-objects"></span><h2>13.5.1. Packer Objects<a class="headerlink" href="#packer-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#xdrlib.Packer" title="xdrlib.Packer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Packer</span></code></a> instances have the following methods:</p>
<dl class="method">
<dt id="xdrlib.Packer.get_buffer">
<code class="descclassname">Packer.</code><code class="descname">get_buffer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.get_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current pack buffer as a string.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.reset">
<code class="descclassname">Packer.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the pack buffer to the empty string.</p>
</dd></dl>

<p>In general, you can pack any of the most common XDR data types by calling the
appropriate <code class="docutils literal notranslate"><span class="pre">pack_type()</span></code> method.  Each method takes a single argument, the
value to pack.  The following simple data type packing methods are supported:
<code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_uint()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_int()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_enum()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_bool()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_uhyper()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_hyper()</span></code>.</p>
<dl class="method">
<dt id="xdrlib.Packer.pack_float">
<code class="descclassname">Packer.</code><code class="descname">pack_float</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs the single-precision floating point number <em>value</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_double">
<code class="descclassname">Packer.</code><code class="descname">pack_double</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_double" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs the double-precision floating point number <em>value</em>.</p>
</dd></dl>

<p>The following methods support packing strings, bytes, and opaque data:</p>
<dl class="method">
<dt id="xdrlib.Packer.pack_fstring">
<code class="descclassname">Packer.</code><code class="descname">pack_fstring</code><span class="sig-paren">(</span><em>n</em>, <em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_fstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a fixed length string, <em>s</em>.  <em>n</em> is the length of the string but it is
<em>not</em> packed into the data buffer.  The string is padded with null bytes if
necessary to guaranteed 4 byte alignment.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_fopaque">
<code class="descclassname">Packer.</code><code class="descname">pack_fopaque</code><span class="sig-paren">(</span><em>n</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_fopaque" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a fixed length opaque data stream, similarly to <a class="reference internal" href="#xdrlib.Packer.pack_fstring" title="xdrlib.Packer.pack_fstring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_fstring()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_string">
<code class="descclassname">Packer.</code><code class="descname">pack_string</code><span class="sig-paren">(</span><em>s</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a variable length string, <em>s</em>.  The length of the string is first packed
as an unsigned integer, then the string data is packed with
<a class="reference internal" href="#xdrlib.Packer.pack_fstring" title="xdrlib.Packer.pack_fstring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_fstring()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_opaque">
<code class="descclassname">Packer.</code><code class="descname">pack_opaque</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_opaque" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a variable length opaque data string, similarly to <a class="reference internal" href="#xdrlib.Packer.pack_string" title="xdrlib.Packer.pack_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_string()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_bytes">
<code class="descclassname">Packer.</code><code class="descname">pack_bytes</code><span class="sig-paren">(</span><em>bytes</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a variable length byte stream, similarly to <a class="reference internal" href="#xdrlib.Packer.pack_string" title="xdrlib.Packer.pack_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_string()</span></code></a>.</p>
</dd></dl>

<p>The following methods support packing arrays and lists:</p>
<dl class="method">
<dt id="xdrlib.Packer.pack_list">
<code class="descclassname">Packer.</code><code class="descname">pack_list</code><span class="sig-paren">(</span><em>list</em>, <em>pack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_list" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a <em>list</em> of homogeneous items.  This method is useful for lists with an
indeterminate size; i.e. the size is not available until the entire list has
been walked.  For each item in the list, an unsigned integer <code class="docutils literal notranslate"><span class="pre">1</span></code> is packed
first, followed by the data value from the list.  <em>pack_item</em> is the function
that is called to pack the individual item.  At the end of the list, an unsigned
integer <code class="docutils literal notranslate"><span class="pre">0</span></code> is packed.</p>
<p>For example, to pack a list of integers, the code might appear like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xdrlib</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">xdrlib</span><span class="o">.</span><span class="n">Packer</span><span class="p">()</span>
<span class="n">p</span><span class="o">.</span><span class="n">pack_list</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="n">p</span><span class="o">.</span><span class="n">pack_int</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_farray">
<code class="descclassname">Packer.</code><code class="descname">pack_farray</code><span class="sig-paren">(</span><em>n</em>, <em>array</em>, <em>pack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_farray" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a fixed length list (<em>array</em>) of homogeneous items.  <em>n</em> is the length of
the list; it is <em>not</em> packed into the buffer, but a <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception
is raised if <code class="docutils literal notranslate"><span class="pre">len(array)</span></code> is not equal to <em>n</em>.  As above, <em>pack_item</em> is the
function used to pack each element.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Packer.pack_array">
<code class="descclassname">Packer.</code><code class="descname">pack_array</code><span class="sig-paren">(</span><em>list</em>, <em>pack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Packer.pack_array" title="Permalink to this definition">¶</a></dt>
<dd><p>Packs a variable length <em>list</em> of homogeneous items.  First, the length of the
list is packed as an unsigned integer, then each element is packed as in
<a class="reference internal" href="#xdrlib.Packer.pack_farray" title="xdrlib.Packer.pack_farray"><code class="xref py py-meth docutils literal notranslate"><span class="pre">pack_farray()</span></code></a> above.</p>
</dd></dl>

</div>
<div class="section" id="unpacker-objects">
<span id="xdr-unpacker-objects"></span><h2>13.5.2. Unpacker Objects<a class="headerlink" href="#unpacker-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#xdrlib.Unpacker" title="xdrlib.Unpacker"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpacker</span></code></a> class offers the following methods:</p>
<dl class="method">
<dt id="xdrlib.Unpacker.reset">
<code class="descclassname">Unpacker.</code><code class="descname">reset</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets the string buffer with the given <em>data</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.get_position">
<code class="descclassname">Unpacker.</code><code class="descname">get_position</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.get_position" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current unpack position in the data buffer.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.set_position">
<code class="descclassname">Unpacker.</code><code class="descname">set_position</code><span class="sig-paren">(</span><em>position</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.set_position" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the data buffer unpack position to <em>position</em>.  You should be careful about
using <a class="reference internal" href="#xdrlib.Unpacker.get_position" title="xdrlib.Unpacker.get_position"><code class="xref py py-meth docutils literal notranslate"><span class="pre">get_position()</span></code></a> and <a class="reference internal" href="#xdrlib.Unpacker.set_position" title="xdrlib.Unpacker.set_position"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set_position()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.get_buffer">
<code class="descclassname">Unpacker.</code><code class="descname">get_buffer</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.get_buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the current unpack data buffer as a string.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.done">
<code class="descclassname">Unpacker.</code><code class="descname">done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.done" title="Permalink to this definition">¶</a></dt>
<dd><p>Indicates unpack completion.  Raises an <a class="reference internal" href="#xdrlib.Error" title="xdrlib.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> exception if all of the
data has not been unpacked.</p>
</dd></dl>

<p>In addition, every data type that can be packed with a <a class="reference internal" href="#xdrlib.Packer" title="xdrlib.Packer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Packer</span></code></a>, can be
unpacked with an <a class="reference internal" href="#xdrlib.Unpacker" title="xdrlib.Unpacker"><code class="xref py py-class docutils literal notranslate"><span class="pre">Unpacker</span></code></a>.  Unpacking methods are of the form
<code class="docutils literal notranslate"><span class="pre">unpack_type()</span></code>, and take no arguments.  They return the unpacked object.</p>
<dl class="method">
<dt id="xdrlib.Unpacker.unpack_float">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_float</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_float" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks a single-precision floating point number.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_double">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_double</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_double" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks a double-precision floating point number, similarly to
<a class="reference internal" href="#xdrlib.Unpacker.unpack_float" title="xdrlib.Unpacker.unpack_float"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_float()</span></code></a>.</p>
</dd></dl>

<p>In addition, the following methods unpack strings, bytes, and opaque data:</p>
<dl class="method">
<dt id="xdrlib.Unpacker.unpack_fstring">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_fstring</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_fstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a fixed length string.  <em>n</em> is the number of characters
expected.  Padding with null bytes to guaranteed 4 byte alignment is assumed.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_fopaque">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_fopaque</code><span class="sig-paren">(</span><em>n</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_fopaque" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a fixed length opaque data stream, similarly to
<a class="reference internal" href="#xdrlib.Unpacker.unpack_fstring" title="xdrlib.Unpacker.unpack_fstring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_fstring()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_string">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_string</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_string" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a variable length string.  The length of the string is first
unpacked as an unsigned integer, then the string data is unpacked with
<a class="reference internal" href="#xdrlib.Unpacker.unpack_fstring" title="xdrlib.Unpacker.unpack_fstring"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_fstring()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_opaque">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_opaque</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_opaque" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a variable length opaque data string, similarly to
<a class="reference internal" href="#xdrlib.Unpacker.unpack_string" title="xdrlib.Unpacker.unpack_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_string()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_bytes">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_bytes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_bytes" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a variable length byte stream, similarly to
<a class="reference internal" href="#xdrlib.Unpacker.unpack_string" title="xdrlib.Unpacker.unpack_string"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_string()</span></code></a>.</p>
</dd></dl>

<p>The following methods support unpacking arrays and lists:</p>
<dl class="method">
<dt id="xdrlib.Unpacker.unpack_list">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_list</code><span class="sig-paren">(</span><em>unpack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_list" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a list of homogeneous items.  The list is unpacked one
element at a time by first unpacking an unsigned integer flag.  If the flag is
<code class="docutils literal notranslate"><span class="pre">1</span></code>, then the item is unpacked and appended to the list.  A flag of <code class="docutils literal notranslate"><span class="pre">0</span></code>
indicates the end of the list.  <em>unpack_item</em> is the function that is called to
unpack the items.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_farray">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_farray</code><span class="sig-paren">(</span><em>n</em>, <em>unpack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_farray" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns (as a list) a fixed length array of homogeneous items.  <em>n</em>
is number of list elements to expect in the buffer. As above, <em>unpack_item</em> is
the function used to unpack each element.</p>
</dd></dl>

<dl class="method">
<dt id="xdrlib.Unpacker.unpack_array">
<code class="descclassname">Unpacker.</code><code class="descname">unpack_array</code><span class="sig-paren">(</span><em>unpack_item</em><span class="sig-paren">)</span><a class="headerlink" href="#xdrlib.Unpacker.unpack_array" title="Permalink to this definition">¶</a></dt>
<dd><p>Unpacks and returns a variable length <em>list</em> of homogeneous items. First, the
length of the list is unpacked as an unsigned integer, then each element is
unpacked as in <a class="reference internal" href="#xdrlib.Unpacker.unpack_farray" title="xdrlib.Unpacker.unpack_farray"><code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack_farray()</span></code></a> above.</p>
</dd></dl>

</div>
<div class="section" id="exceptions">
<span id="xdr-exceptions"></span><h2>13.5.3. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>Exceptions in this module are coded as class instances:</p>
<dl class="exception">
<dt id="xdrlib.Error">
<em class="property">exception </em><code class="descclassname">xdrlib.</code><code class="descname">Error</code><a class="headerlink" href="#xdrlib.Error" title="Permalink to this definition">¶</a></dt>
<dd><p>The base exception class.  <a class="reference internal" href="#xdrlib.Error" title="xdrlib.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a> has a single public attribute
<code class="xref py py-attr docutils literal notranslate"><span class="pre">msg</span></code> containing the description of the error.</p>
</dd></dl>

<dl class="exception">
<dt id="xdrlib.ConversionError">
<em class="property">exception </em><code class="descclassname">xdrlib.</code><code class="descname">ConversionError</code><a class="headerlink" href="#xdrlib.ConversionError" title="Permalink to this definition">¶</a></dt>
<dd><p>Class derived from <a class="reference internal" href="#xdrlib.Error" title="xdrlib.Error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code></a>.  Contains no additional instance variables.</p>
</dd></dl>

<p>Here is an example of how you would catch one of these exceptions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xdrlib</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">xdrlib</span><span class="o">.</span><span class="n">Packer</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">p</span><span class="o">.</span><span class="n">pack_double</span><span class="p">(</span><span class="mf">8.01</span><span class="p">)</span>
<span class="k">except</span> <span class="n">xdrlib</span><span class="o">.</span><span class="n">ConversionError</span> <span class="k">as</span> <span class="n">instance</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s1">&#39;packing the double failed:&#39;</span><span class="p">,</span> <span class="n">instance</span><span class="o">.</span><span class="n">msg</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a><ul>
<li><a class="reference internal" href="#packer-objects">13.5.1. Packer Objects</a></li>
<li><a class="reference internal" href="#unpacker-objects">13.5.2. Unpacker Objects</a></li>
<li><a class="reference internal" href="#exceptions">13.5.3. Exceptions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="netrc.html"
                        title="previous chapter">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="plistlib.html"
                        title="next chapter">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xdrlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="plistlib.html" title="13.6. plistlib — Generate and parse Mac OS X .plist files"
             >next</a> |</li>
        <li class="right" >
          <a href="netrc.html" title="13.4. netrc — netrc file processing"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="fileformats.html" >13. File Formats</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�g�U~U~html/library/xml.dom.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.8. xml.dom — The Document Object Model API &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.9. xml.dom.minidom — Minimal DOM implementation" href="xml.dom.minidom.html" />
    <link rel="prev" title="19.7. xml.etree.ElementTree — The ElementTree XML API" href="xml.etree.elementtree.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.dom.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.minidom.html" title="19.9. xml.dom.minidom — Minimal DOM implementation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.etree.elementtree.html" title="19.7. xml.etree.ElementTree — The ElementTree XML API"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.dom">
<span id="xml-dom-the-document-object-model-api"></span><h1>19.8. <a class="reference internal" href="#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> — The Document Object Model API<a class="headerlink" href="#module-xml.dom" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>The Document Object Model, or “DOM,” is a cross-language API from the World Wide
Web Consortium (W3C) for accessing and modifying XML documents.  A DOM
implementation presents an XML document as a tree structure, or allows client
code to build such a structure from scratch.  It then gives access to the
structure through a set of objects which provided well-known interfaces.</p>
<p>The DOM is extremely useful for random-access applications.  SAX only allows you
a view of one bit of the document at a time.  If you are looking at one SAX
element, you have no access to another.  If you are looking at a text node, you
have no access to a containing element. When you write a SAX application, you
need to keep track of your program’s position in the document somewhere in your
own code.  SAX does not do it for you.  Also, if you need to look ahead in the
XML document, you are just out of luck.</p>
<p>Some applications are simply impossible in an event driven model with no access
to a tree.  Of course you could build some sort of tree yourself in SAX events,
but the DOM allows you to avoid writing that code.  The DOM is a standard tree
representation for XML data.</p>
<p>The Document Object Model is being defined by the W3C in stages, or “levels” in
their terminology.  The Python mapping of the API is substantially based on the
DOM Level 2 recommendation.</p>
<p>DOM applications typically start by parsing some XML into a DOM.  How this is
accomplished is not covered at all by DOM Level 1, and Level 2 provides only
limited improvements: There is a <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> object class which
provides access to <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> creation methods, but no way to access an
XML reader/parser/Document builder in an implementation-independent way. There
is also no well-defined way to access these methods without an existing
<code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object.  In Python, each DOM implementation will provide a
function <a class="reference internal" href="#xml.dom.getDOMImplementation" title="xml.dom.getDOMImplementation"><code class="xref py py-func docutils literal notranslate"><span class="pre">getDOMImplementation()</span></code></a>. DOM Level 3 adds a Load/Store
specification, which defines an interface to the reader, but this is not yet
available in the Python standard library.</p>
<p>Once you have a DOM document object, you can access the parts of your XML
document through its properties and methods.  These properties are defined in
the DOM specification; this portion of the reference manual describes the
interpretation of the specification in Python.</p>
<p>The specification provided by the W3C defines the DOM API for Java, ECMAScript,
and OMG IDL.  The Python mapping defined here is based in large part on the IDL
version of the specification, but strict compliance is not required (though
implementations are free to support the strict mapping from IDL).  See section
<a class="reference internal" href="#dom-conformance"><span class="std std-ref">Conformance</span></a> for a detailed discussion of mapping requirements.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.w3.org/TR/DOM-Level-2-Core/">Document Object Model (DOM) Level 2 Specification</a></dt>
<dd>The W3C recommendation upon which the Python DOM API is based.</dd>
<dt><a class="reference external" href="https://www.w3.org/TR/REC-DOM-Level-1/">Document Object Model (DOM) Level 1 Specification</a></dt>
<dd>The W3C recommendation for the DOM supported by <a class="reference internal" href="xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>.</dd>
<dt><a class="reference external" href="http://www.omg.org/spec/PYTH/1.2/PDF">Python Language Mapping Specification</a></dt>
<dd>This specifies the mapping from OMG IDL to Python.</dd>
</dl>
</div>
<div class="section" id="module-contents">
<h2>19.8.1. Module Contents<a class="headerlink" href="#module-contents" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> contains the following functions:</p>
<dl class="function">
<dt id="xml.dom.registerDOMImplementation">
<code class="descclassname">xml.dom.</code><code class="descname">registerDOMImplementation</code><span class="sig-paren">(</span><em>name</em>, <em>factory</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.registerDOMImplementation" title="Permalink to this definition">¶</a></dt>
<dd><p>Register the <em>factory</em> function with the name <em>name</em>.  The factory function
should return an object which implements the <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code>
interface.  The factory function can return the same object every time, or a new
one for each call, as appropriate for the specific implementation (e.g. if that
implementation supports some customization).</p>
</dd></dl>

<dl class="function">
<dt id="xml.dom.getDOMImplementation">
<code class="descclassname">xml.dom.</code><code class="descname">getDOMImplementation</code><span class="sig-paren">(</span><span class="optional">[</span><em>name</em><span class="optional">[</span>, <em>features</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.getDOMImplementation" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a suitable DOM implementation. The <em>name</em> is either well-known, the
module name of a DOM implementation, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. If it is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, imports
the corresponding module and returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> object if the
import succeeds.  If no name is given, and if the environment variable
<span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHON_DOM</span></code> is set, this variable is used to find the implementation.</p>
<p>If name is not given, this examines the available implementations to find one
with the required feature set.  If no implementation can be found, raise an
<a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.  The features list must be a sequence of <code class="docutils literal notranslate"><span class="pre">(feature,</span>
<span class="pre">version)</span></code> pairs which are passed to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">hasFeature()</span></code> method on available
<code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> objects.</p>
</dd></dl>

<p>Some convenience constants are also provided:</p>
<dl class="data">
<dt id="xml.dom.EMPTY_NAMESPACE">
<code class="descclassname">xml.dom.</code><code class="descname">EMPTY_NAMESPACE</code><a class="headerlink" href="#xml.dom.EMPTY_NAMESPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>The value used to indicate that no namespace is associated with a node in the
DOM.  This is typically found as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">namespaceURI</span></code> of a node, or used as
the <em>namespaceURI</em> parameter to a namespaces-specific method.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.dom.XML_NAMESPACE">
<code class="descclassname">xml.dom.</code><code class="descname">XML_NAMESPACE</code><a class="headerlink" href="#xml.dom.XML_NAMESPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>The namespace URI associated with the reserved prefix <code class="docutils literal notranslate"><span class="pre">xml</span></code>, as defined by
<a class="reference external" href="https://www.w3.org/TR/REC-xml-names/">Namespaces in XML</a> (section 4).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.dom.XMLNS_NAMESPACE">
<code class="descclassname">xml.dom.</code><code class="descname">XMLNS_NAMESPACE</code><a class="headerlink" href="#xml.dom.XMLNS_NAMESPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>The namespace URI for namespace declarations, as defined by <a class="reference external" href="https://www.w3.org/TR/DOM-Level-2-Core/core.html">Document Object
Model (DOM) Level 2 Core Specification</a> (section 1.1.8).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.dom.XHTML_NAMESPACE">
<code class="descclassname">xml.dom.</code><code class="descname">XHTML_NAMESPACE</code><a class="headerlink" href="#xml.dom.XHTML_NAMESPACE" title="Permalink to this definition">¶</a></dt>
<dd><p>The URI of the XHTML namespace as defined by <a class="reference external" href="https://www.w3.org/TR/xhtml1/">XHTML 1.0: The Extensible
HyperText Markup Language</a> (section 3.1.1).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<p>In addition, <a class="reference internal" href="#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> contains a base <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> class and the DOM
exception classes.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> class provided by this module does not
implement any of the methods or attributes defined by the DOM specification;
concrete DOM implementations must provide those.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> class
provided as part of this module does provide the constants used for the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nodeType</span></code> attribute on concrete <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> objects; they are located
within the class rather than at the module level to conform with the DOM
specifications.</p>
</div>
<div class="section" id="objects-in-the-dom">
<span id="dom-objects"></span><h2>19.8.2. Objects in the DOM<a class="headerlink" href="#objects-in-the-dom" title="Permalink to this headline">¶</a></h2>
<p>The definitive documentation for the DOM is the DOM specification from the W3C.</p>
<p>Note that DOM attributes may also be manipulated as nodes instead of as simple
strings.  It is fairly rare that you must do this, however, so this usage is not
yet documented.</p>
<table border="1" class="docutils">
<colgroup>
<col width="32%" />
<col width="35%" />
<col width="33%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Interface</th>
<th class="head">Section</th>
<th class="head">Purpose</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code></td>
<td><a class="reference internal" href="#dom-implementation-objects"><span class="std std-ref">DOMImplementation Objects</span></a></td>
<td>Interface to the underlying
implementation.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code></td>
<td><a class="reference internal" href="#dom-node-objects"><span class="std std-ref">Node Objects</span></a></td>
<td>Base interface for most objects
in a document.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code></td>
<td><a class="reference internal" href="#dom-nodelist-objects"><span class="std std-ref">NodeList Objects</span></a></td>
<td>Interface for a sequence of
nodes.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code></td>
<td><a class="reference internal" href="#dom-documenttype-objects"><span class="std std-ref">DocumentType Objects</span></a></td>
<td>Information about the
declarations needed to process
a document.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code></td>
<td><a class="reference internal" href="#dom-document-objects"><span class="std std-ref">Document Objects</span></a></td>
<td>Object which represents an
entire document.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></td>
<td><a class="reference internal" href="#dom-element-objects"><span class="std std-ref">Element Objects</span></a></td>
<td>Element nodes in the document
hierarchy.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Attr</span></code></td>
<td><a class="reference internal" href="#dom-attr-objects"><span class="std std-ref">Attr Objects</span></a></td>
<td>Attribute value nodes on
element nodes.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Comment</span></code></td>
<td><a class="reference internal" href="#dom-comment-objects"><span class="std std-ref">Comment Objects</span></a></td>
<td>Representation of comments in
the source document.</td>
</tr>
<tr class="row-even"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">Text</span></code></td>
<td><a class="reference internal" href="#dom-text-objects"><span class="std std-ref">Text and CDATASection Objects</span></a></td>
<td>Nodes containing textual
content from the document.</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-class docutils literal notranslate"><span class="pre">ProcessingInstruction</span></code></td>
<td><a class="reference internal" href="#dom-pi-objects"><span class="std std-ref">ProcessingInstruction Objects</span></a></td>
<td>Processing instruction
representation.</td>
</tr>
</tbody>
</table>
<p>An additional section describes the exceptions defined for working with the DOM
in Python.</p>
<div class="section" id="domimplementation-objects">
<span id="dom-implementation-objects"></span><h3>19.8.2.1. DOMImplementation Objects<a class="headerlink" href="#domimplementation-objects" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> interface provides a way for applications to
determine the availability of particular features in the DOM they are using.
DOM Level 2 added the ability to create new <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> objects using the <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> as well.</p>
<dl class="method">
<dt id="xml.dom.DOMImplementation.hasFeature">
<code class="descclassname">DOMImplementation.</code><code class="descname">hasFeature</code><span class="sig-paren">(</span><em>feature</em>, <em>version</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.DOMImplementation.hasFeature" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if the feature identified by the pair of strings <em>feature</em> and
<em>version</em> is implemented.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.DOMImplementation.createDocument">
<code class="descclassname">DOMImplementation.</code><code class="descname">createDocument</code><span class="sig-paren">(</span><em>namespaceUri</em>, <em>qualifiedName</em>, <em>doctype</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.DOMImplementation.createDocument" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object (the root of the DOM), with a child
<code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> object having the given <em>namespaceUri</em> and <em>qualifiedName</em>. The
<em>doctype</em> must be a <code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> object created by
<a class="reference internal" href="#xml.dom.DOMImplementation.createDocumentType" title="xml.dom.DOMImplementation.createDocumentType"><code class="xref py py-meth docutils literal notranslate"><span class="pre">createDocumentType()</span></code></a>, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. In the Python DOM API, the first two
arguments can also be <code class="docutils literal notranslate"><span class="pre">None</span></code> in order to indicate that no <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code>
child is to be created.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.DOMImplementation.createDocumentType">
<code class="descclassname">DOMImplementation.</code><code class="descname">createDocumentType</code><span class="sig-paren">(</span><em>qualifiedName</em>, <em>publicId</em>, <em>systemId</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.DOMImplementation.createDocumentType" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a new <code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> object that encapsulates the given
<em>qualifiedName</em>, <em>publicId</em>, and <em>systemId</em> strings, representing the
information contained in an XML document type declaration.</p>
</dd></dl>

</div>
<div class="section" id="node-objects">
<span id="dom-node-objects"></span><h3>19.8.2.2. Node Objects<a class="headerlink" href="#node-objects" title="Permalink to this headline">¶</a></h3>
<p>All of the components of an XML document are subclasses of <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>.</p>
<dl class="attribute">
<dt id="xml.dom.Node.nodeType">
<code class="descclassname">Node.</code><code class="descname">nodeType</code><a class="headerlink" href="#xml.dom.Node.nodeType" title="Permalink to this definition">¶</a></dt>
<dd><p>An integer representing the node type.  Symbolic constants for the types are on
the <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> object: <code class="xref py py-const docutils literal notranslate"><span class="pre">ELEMENT_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ATTRIBUTE_NODE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">TEXT_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">CDATA_SECTION_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ENTITY_NODE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">PROCESSING_INSTRUCTION_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">COMMENT_NODE</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">DOCUMENT_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">DOCUMENT_TYPE_NODE</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">NOTATION_NODE</span></code>.
This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.parentNode">
<code class="descclassname">Node.</code><code class="descname">parentNode</code><a class="headerlink" href="#xml.dom.Node.parentNode" title="Permalink to this definition">¶</a></dt>
<dd><p>The parent of the current node, or <code class="docutils literal notranslate"><span class="pre">None</span></code> for the document node. The value is
always a <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> object or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  For <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> nodes, this
will be the parent element, except for the root element, in which case it will
be the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object. For <code class="xref py py-class docutils literal notranslate"><span class="pre">Attr</span></code> nodes, this is always
<code class="docutils literal notranslate"><span class="pre">None</span></code>. This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.attributes">
<code class="descclassname">Node.</code><code class="descname">attributes</code><a class="headerlink" href="#xml.dom.Node.attributes" title="Permalink to this definition">¶</a></dt>
<dd><p>A <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedNodeMap</span></code> of attribute objects.  Only elements have actual values
for this; others provide <code class="docutils literal notranslate"><span class="pre">None</span></code> for this attribute. This is a read-only
attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.previousSibling">
<code class="descclassname">Node.</code><code class="descname">previousSibling</code><a class="headerlink" href="#xml.dom.Node.previousSibling" title="Permalink to this definition">¶</a></dt>
<dd><p>The node that immediately precedes this one with the same parent.  For
instance the element with an end-tag that comes just before the <em>self</em>
element’s start-tag.  Of course, XML documents are made up of more than just
elements so the previous sibling could be text, a comment, or something else.
If this node is the first child of the parent, this attribute will be
<code class="docutils literal notranslate"><span class="pre">None</span></code>. This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.nextSibling">
<code class="descclassname">Node.</code><code class="descname">nextSibling</code><a class="headerlink" href="#xml.dom.Node.nextSibling" title="Permalink to this definition">¶</a></dt>
<dd><p>The node that immediately follows this one with the same parent.  See also
<a class="reference internal" href="#xml.dom.Node.previousSibling" title="xml.dom.Node.previousSibling"><code class="xref py py-attr docutils literal notranslate"><span class="pre">previousSibling</span></code></a>.  If this is the last child of the parent, this
attribute will be <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.childNodes">
<code class="descclassname">Node.</code><code class="descname">childNodes</code><a class="headerlink" href="#xml.dom.Node.childNodes" title="Permalink to this definition">¶</a></dt>
<dd><p>A list of nodes contained within this node. This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.firstChild">
<code class="descclassname">Node.</code><code class="descname">firstChild</code><a class="headerlink" href="#xml.dom.Node.firstChild" title="Permalink to this definition">¶</a></dt>
<dd><p>The first child of the node, if there are any, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is a read-only
attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.lastChild">
<code class="descclassname">Node.</code><code class="descname">lastChild</code><a class="headerlink" href="#xml.dom.Node.lastChild" title="Permalink to this definition">¶</a></dt>
<dd><p>The last child of the node, if there are any, or <code class="docutils literal notranslate"><span class="pre">None</span></code>. This is a read-only
attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.localName">
<code class="descclassname">Node.</code><code class="descname">localName</code><a class="headerlink" href="#xml.dom.Node.localName" title="Permalink to this definition">¶</a></dt>
<dd><p>The part of the <code class="xref py py-attr docutils literal notranslate"><span class="pre">tagName</span></code> following the colon if there is one, else the
entire <code class="xref py py-attr docutils literal notranslate"><span class="pre">tagName</span></code>.  The value is a string.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.prefix">
<code class="descclassname">Node.</code><code class="descname">prefix</code><a class="headerlink" href="#xml.dom.Node.prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>The part of the <code class="xref py py-attr docutils literal notranslate"><span class="pre">tagName</span></code> preceding the colon if there is one, else the
empty string.  The value is a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.namespaceURI">
<code class="descclassname">Node.</code><code class="descname">namespaceURI</code><a class="headerlink" href="#xml.dom.Node.namespaceURI" title="Permalink to this definition">¶</a></dt>
<dd><p>The namespace associated with the element name.  This will be a string or
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.nodeName">
<code class="descclassname">Node.</code><code class="descname">nodeName</code><a class="headerlink" href="#xml.dom.Node.nodeName" title="Permalink to this definition">¶</a></dt>
<dd><p>This has a different meaning for each node type; see the DOM specification for
details.  You can always get the information you would get here from another
property such as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">tagName</span></code> property for elements or the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code>
property for attributes. For all node types, the value of this attribute will be
either a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Node.nodeValue">
<code class="descclassname">Node.</code><code class="descname">nodeValue</code><a class="headerlink" href="#xml.dom.Node.nodeValue" title="Permalink to this definition">¶</a></dt>
<dd><p>This has a different meaning for each node type; see the DOM specification for
details.  The situation is similar to that with <a class="reference internal" href="#xml.dom.Node.nodeName" title="xml.dom.Node.nodeName"><code class="xref py py-attr docutils literal notranslate"><span class="pre">nodeName</span></code></a>.  The value is
a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.hasAttributes">
<code class="descclassname">Node.</code><code class="descname">hasAttributes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.hasAttributes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the node has any attributes.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.hasChildNodes">
<code class="descclassname">Node.</code><code class="descname">hasChildNodes</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.hasChildNodes" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the node has any child nodes.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.isSameNode">
<code class="descclassname">Node.</code><code class="descname">isSameNode</code><span class="sig-paren">(</span><em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.isSameNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if <em>other</em> refers to the same node as this node. This is especially
useful for DOM implementations which use any sort of proxy architecture (because
more than one object can refer to the same node).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This is based on a proposed DOM Level 3 API which is still in the “working
draft” stage, but this particular interface appears uncontroversial.  Changes
from the W3C will not necessarily affect this method in the Python DOM interface
(though any new W3C API for this would also be supported).</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.appendChild">
<code class="descclassname">Node.</code><code class="descname">appendChild</code><span class="sig-paren">(</span><em>newChild</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.appendChild" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a new child node to this node at the end of the list of
children, returning <em>newChild</em>. If the node was already in
the tree, it is removed first.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.insertBefore">
<code class="descclassname">Node.</code><code class="descname">insertBefore</code><span class="sig-paren">(</span><em>newChild</em>, <em>refChild</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.insertBefore" title="Permalink to this definition">¶</a></dt>
<dd><p>Insert a new child node before an existing child.  It must be the case that
<em>refChild</em> is a child of this node; if not, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.
<em>newChild</em> is returned. If <em>refChild</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, it inserts <em>newChild</em> at the
end of the children’s list.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.removeChild">
<code class="descclassname">Node.</code><code class="descname">removeChild</code><span class="sig-paren">(</span><em>oldChild</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.removeChild" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove a child node.  <em>oldChild</em> must be a child of this node; if not,
<a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.  <em>oldChild</em> is returned on success.  If <em>oldChild</em>
will not be used further, its <code class="xref py py-meth docutils literal notranslate"><span class="pre">unlink()</span></code> method should be called.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.replaceChild">
<code class="descclassname">Node.</code><code class="descname">replaceChild</code><span class="sig-paren">(</span><em>newChild</em>, <em>oldChild</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.replaceChild" title="Permalink to this definition">¶</a></dt>
<dd><p>Replace an existing node with a new node. It must be the case that  <em>oldChild</em>
is a child of this node; if not, <a class="reference internal" href="exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.normalize">
<code class="descclassname">Node.</code><code class="descname">normalize</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.normalize" title="Permalink to this definition">¶</a></dt>
<dd><p>Join adjacent text nodes so that all stretches of text are stored as single
<code class="xref py py-class docutils literal notranslate"><span class="pre">Text</span></code> instances.  This simplifies processing text from a DOM tree for
many applications.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Node.cloneNode">
<code class="descclassname">Node.</code><code class="descname">cloneNode</code><span class="sig-paren">(</span><em>deep</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Node.cloneNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Clone this node.  Setting <em>deep</em> means to clone all child nodes as well.  This
returns the clone.</p>
</dd></dl>

</div>
<div class="section" id="nodelist-objects">
<span id="dom-nodelist-objects"></span><h3>19.8.2.3. NodeList Objects<a class="headerlink" href="#nodelist-objects" title="Permalink to this headline">¶</a></h3>
<p>A <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> represents a sequence of nodes.  These objects are used in
two ways in the DOM Core recommendation:  an <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> object provides
one as its list of child nodes, and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">getElementsByTagName()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getElementsByTagNameNS()</span></code> methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> return objects with this
interface to represent query results.</p>
<p>The DOM Level 2 recommendation defines one method and one attribute for these
objects:</p>
<dl class="method">
<dt id="xml.dom.NodeList.item">
<code class="descclassname">NodeList.</code><code class="descname">item</code><span class="sig-paren">(</span><em>i</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.NodeList.item" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <em>i</em>’th item from the sequence, if there is one, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The
index <em>i</em> is not allowed to be less than zero or greater than or equal to the
length of the sequence.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.NodeList.length">
<code class="descclassname">NodeList.</code><code class="descname">length</code><a class="headerlink" href="#xml.dom.NodeList.length" title="Permalink to this definition">¶</a></dt>
<dd><p>The number of nodes in the sequence.</p>
</dd></dl>

<p>In addition, the Python DOM interface requires that some additional support is
provided to allow <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> objects to be used as Python sequences.  All
<code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> implementations must include support for
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>; this allows iteration over the <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> in
<a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements and proper support for the <a class="reference internal" href="functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> built-in
function.</p>
<p>If a DOM implementation supports modification of the document, the
<code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> implementation must also support the
<a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> methods.</p>
</div>
<div class="section" id="documenttype-objects">
<span id="dom-documenttype-objects"></span><h3>19.8.2.4. DocumentType Objects<a class="headerlink" href="#documenttype-objects" title="Permalink to this headline">¶</a></h3>
<p>Information about the notations and entities declared by a document (including
the external subset if the parser uses it and can provide the information) is
available from a <code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> object.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> for a
document is available from the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">doctype</span></code>
attribute; if there is no <code class="docutils literal notranslate"><span class="pre">DOCTYPE</span></code> declaration for the document, the
document’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">doctype</span></code> attribute will be set to <code class="docutils literal notranslate"><span class="pre">None</span></code> instead of an
instance of this interface.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> is a specialization of <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>, and adds the
following attributes:</p>
<dl class="attribute">
<dt id="xml.dom.DocumentType.publicId">
<code class="descclassname">DocumentType.</code><code class="descname">publicId</code><a class="headerlink" href="#xml.dom.DocumentType.publicId" title="Permalink to this definition">¶</a></dt>
<dd><p>The public identifier for the external subset of the document type definition.
This will be a string or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.DocumentType.systemId">
<code class="descclassname">DocumentType.</code><code class="descname">systemId</code><a class="headerlink" href="#xml.dom.DocumentType.systemId" title="Permalink to this definition">¶</a></dt>
<dd><p>The system identifier for the external subset of the document type definition.
This will be a URI as a string, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.DocumentType.internalSubset">
<code class="descclassname">DocumentType.</code><code class="descname">internalSubset</code><a class="headerlink" href="#xml.dom.DocumentType.internalSubset" title="Permalink to this definition">¶</a></dt>
<dd><p>A string giving the complete internal subset from the document. This does not
include the brackets which enclose the subset.  If the document has no internal
subset, this should be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.DocumentType.name">
<code class="descclassname">DocumentType.</code><code class="descname">name</code><a class="headerlink" href="#xml.dom.DocumentType.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The name of the root element as given in the <code class="docutils literal notranslate"><span class="pre">DOCTYPE</span></code> declaration, if
present.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.DocumentType.entities">
<code class="descclassname">DocumentType.</code><code class="descname">entities</code><a class="headerlink" href="#xml.dom.DocumentType.entities" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedNodeMap</span></code> giving the definitions of external entities.
For entity names defined more than once, only the first definition is provided
(others are ignored as required by the XML recommendation).  This may be
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the information is not provided by the parser, or if no entities are
defined.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.DocumentType.notations">
<code class="descclassname">DocumentType.</code><code class="descname">notations</code><a class="headerlink" href="#xml.dom.DocumentType.notations" title="Permalink to this definition">¶</a></dt>
<dd><p>This is a <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedNodeMap</span></code> giving the definitions of notations. For
notation names defined more than once, only the first definition is provided
(others are ignored as required by the XML recommendation).  This may be
<code class="docutils literal notranslate"><span class="pre">None</span></code> if the information is not provided by the parser, or if no notations
are defined.</p>
</dd></dl>

</div>
<div class="section" id="document-objects">
<span id="dom-document-objects"></span><h3>19.8.2.5. Document Objects<a class="headerlink" href="#document-objects" title="Permalink to this headline">¶</a></h3>
<p>A <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> represents an entire XML document, including its constituent
elements, attributes, processing instructions, comments etc.  Remember that it
inherits properties from <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>.</p>
<dl class="attribute">
<dt id="xml.dom.Document.documentElement">
<code class="descclassname">Document.</code><code class="descname">documentElement</code><a class="headerlink" href="#xml.dom.Document.documentElement" title="Permalink to this definition">¶</a></dt>
<dd><p>The one and only root element of the document.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createElement">
<code class="descclassname">Document.</code><code class="descname">createElement</code><span class="sig-paren">(</span><em>tagName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createElement" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a new element node.  The element is not inserted into the
document when it is created.  You need to explicitly insert it with one of the
other methods such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">insertBefore()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">appendChild()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createElementNS">
<code class="descclassname">Document.</code><code class="descname">createElementNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>tagName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createElementNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a new element with a namespace.  The <em>tagName</em> may have a
prefix.  The element is not inserted into the document when it is created.  You
need to explicitly insert it with one of the other methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">insertBefore()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">appendChild()</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createTextNode">
<code class="descclassname">Document.</code><code class="descname">createTextNode</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createTextNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a text node containing the data passed as a parameter.  As
with the other creation methods, this one does not insert the node into the
tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createComment">
<code class="descclassname">Document.</code><code class="descname">createComment</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createComment" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a comment node containing the data passed as a parameter.  As
with the other creation methods, this one does not insert the node into the
tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createProcessingInstruction">
<code class="descclassname">Document.</code><code class="descname">createProcessingInstruction</code><span class="sig-paren">(</span><em>target</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createProcessingInstruction" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a processing instruction node containing the <em>target</em> and
<em>data</em> passed as parameters.  As with the other creation methods, this one does
not insert the node into the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createAttribute">
<code class="descclassname">Document.</code><code class="descname">createAttribute</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createAttribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return an attribute node.  This method does not associate the
attribute node with any particular element.  You must use
<code class="xref py py-meth docutils literal notranslate"><span class="pre">setAttributeNode()</span></code> on the appropriate <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> object to use the
newly created attribute instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.createAttributeNS">
<code class="descclassname">Document.</code><code class="descname">createAttributeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>qualifiedName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.createAttributeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return an attribute node with a namespace.  The <em>tagName</em> may have a
prefix.  This method does not associate the attribute node with any particular
element.  You must use <code class="xref py py-meth docutils literal notranslate"><span class="pre">setAttributeNode()</span></code> on the appropriate
<code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> object to use the newly created attribute instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.getElementsByTagName">
<code class="descclassname">Document.</code><code class="descname">getElementsByTagName</code><span class="sig-paren">(</span><em>tagName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.getElementsByTagName" title="Permalink to this definition">¶</a></dt>
<dd><p>Search for all descendants (direct children, children’s children, etc.) with a
particular element type name.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Document.getElementsByTagNameNS">
<code class="descclassname">Document.</code><code class="descname">getElementsByTagNameNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Document.getElementsByTagNameNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Search for all descendants (direct children, children’s children, etc.) with a
particular namespace URI and localname.  The localname is the part of the
namespace after the prefix.</p>
</dd></dl>

</div>
<div class="section" id="element-objects">
<span id="dom-element-objects"></span><h3>19.8.2.6. Element Objects<a class="headerlink" href="#element-objects" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>, so inherits all the attributes
of that class.</p>
<dl class="attribute">
<dt id="xml.dom.Element.tagName">
<code class="descclassname">Element.</code><code class="descname">tagName</code><a class="headerlink" href="#xml.dom.Element.tagName" title="Permalink to this definition">¶</a></dt>
<dd><p>The element type name.  In a namespace-using document it may have colons in it.
The value is a string.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getElementsByTagName">
<code class="descclassname">Element.</code><code class="descname">getElementsByTagName</code><span class="sig-paren">(</span><em>tagName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getElementsByTagName" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as equivalent method in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> class.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getElementsByTagNameNS">
<code class="descclassname">Element.</code><code class="descname">getElementsByTagNameNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getElementsByTagNameNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as equivalent method in the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> class.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.hasAttribute">
<code class="descclassname">Element.</code><code class="descname">hasAttribute</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.hasAttribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the element has an attribute named by <em>name</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.hasAttributeNS">
<code class="descclassname">Element.</code><code class="descname">hasAttributeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.hasAttributeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns true if the element has an attribute named by <em>namespaceURI</em> and
<em>localName</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getAttribute">
<code class="descclassname">Element.</code><code class="descname">getAttribute</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getAttribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the attribute named by <em>name</em> as a string. If no such
attribute exists, an empty string is returned, as if the attribute had no value.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getAttributeNode">
<code class="descclassname">Element.</code><code class="descname">getAttributeNode</code><span class="sig-paren">(</span><em>attrname</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getAttributeNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <code class="xref py py-class docutils literal notranslate"><span class="pre">Attr</span></code> node for the attribute named by <em>attrname</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getAttributeNS">
<code class="descclassname">Element.</code><code class="descname">getAttributeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getAttributeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of the attribute named by <em>namespaceURI</em> and <em>localName</em> as a
string. If no such attribute exists, an empty string is returned, as if the
attribute had no value.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.getAttributeNodeNS">
<code class="descclassname">Element.</code><code class="descname">getAttributeNodeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.getAttributeNodeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an attribute value as a node, given a <em>namespaceURI</em> and <em>localName</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.removeAttribute">
<code class="descclassname">Element.</code><code class="descname">removeAttribute</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.removeAttribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove an attribute by name.  If there is no matching attribute, a
<a class="reference internal" href="#xml.dom.NotFoundErr" title="xml.dom.NotFoundErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotFoundErr</span></code></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.removeAttributeNode">
<code class="descclassname">Element.</code><code class="descname">removeAttributeNode</code><span class="sig-paren">(</span><em>oldAttr</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.removeAttributeNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove and return <em>oldAttr</em> from the attribute list, if present. If <em>oldAttr</em> is
not present, <a class="reference internal" href="#xml.dom.NotFoundErr" title="xml.dom.NotFoundErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotFoundErr</span></code></a> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.removeAttributeNS">
<code class="descclassname">Element.</code><code class="descname">removeAttributeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>localName</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.removeAttributeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove an attribute by name.  Note that it uses a localName, not a qname.  No
exception is raised if there is no matching attribute.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.setAttribute">
<code class="descclassname">Element.</code><code class="descname">setAttribute</code><span class="sig-paren">(</span><em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.setAttribute" title="Permalink to this definition">¶</a></dt>
<dd><p>Set an attribute value from a string.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.setAttributeNode">
<code class="descclassname">Element.</code><code class="descname">setAttributeNode</code><span class="sig-paren">(</span><em>newAttr</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.setAttributeNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a new attribute node to the element, replacing an existing attribute if
necessary if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute matches.  If a replacement occurs, the
old attribute node will be returned.  If <em>newAttr</em> is already in use,
<a class="reference internal" href="#xml.dom.InuseAttributeErr" title="xml.dom.InuseAttributeErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InuseAttributeErr</span></code></a> will be raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.setAttributeNodeNS">
<code class="descclassname">Element.</code><code class="descname">setAttributeNodeNS</code><span class="sig-paren">(</span><em>newAttr</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.setAttributeNodeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a new attribute node to the element, replacing an existing attribute if
necessary if the <code class="xref py py-attr docutils literal notranslate"><span class="pre">namespaceURI</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">localName</span></code> attributes match.
If a replacement occurs, the old attribute node will be returned.  If <em>newAttr</em>
is already in use, <a class="reference internal" href="#xml.dom.InuseAttributeErr" title="xml.dom.InuseAttributeErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InuseAttributeErr</span></code></a> will be raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.Element.setAttributeNS">
<code class="descclassname">Element.</code><code class="descname">setAttributeNS</code><span class="sig-paren">(</span><em>namespaceURI</em>, <em>qname</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.Element.setAttributeNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Set an attribute value from a string, given a <em>namespaceURI</em> and a <em>qname</em>.
Note that a qname is the whole attribute name.  This is different than above.</p>
</dd></dl>

</div>
<div class="section" id="attr-objects">
<span id="dom-attr-objects"></span><h3>19.8.2.7. Attr Objects<a class="headerlink" href="#attr-objects" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Attr</span></code> inherits from <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>, so inherits all its attributes.</p>
<dl class="attribute">
<dt id="xml.dom.Attr.name">
<code class="descclassname">Attr.</code><code class="descname">name</code><a class="headerlink" href="#xml.dom.Attr.name" title="Permalink to this definition">¶</a></dt>
<dd><p>The attribute name.
In a namespace-using document it may include a colon.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Attr.localName">
<code class="descclassname">Attr.</code><code class="descname">localName</code><a class="headerlink" href="#xml.dom.Attr.localName" title="Permalink to this definition">¶</a></dt>
<dd><p>The part of the name following the colon if there is one, else the
entire name.
This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Attr.prefix">
<code class="descclassname">Attr.</code><code class="descname">prefix</code><a class="headerlink" href="#xml.dom.Attr.prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>The part of the name preceding the colon if there is one, else the
empty string.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.Attr.value">
<code class="descclassname">Attr.</code><code class="descname">value</code><a class="headerlink" href="#xml.dom.Attr.value" title="Permalink to this definition">¶</a></dt>
<dd><p>The text value of the attribute.  This is a synonym for the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nodeValue</span></code> attribute.</p>
</dd></dl>

</div>
<div class="section" id="namednodemap-objects">
<span id="dom-attributelist-objects"></span><h3>19.8.2.8. NamedNodeMap Objects<a class="headerlink" href="#namednodemap-objects" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">NamedNodeMap</span></code> does <em>not</em> inherit from <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>.</p>
<dl class="attribute">
<dt id="xml.dom.NamedNodeMap.length">
<code class="descclassname">NamedNodeMap.</code><code class="descname">length</code><a class="headerlink" href="#xml.dom.NamedNodeMap.length" title="Permalink to this definition">¶</a></dt>
<dd><p>The length of the attribute list.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.NamedNodeMap.item">
<code class="descclassname">NamedNodeMap.</code><code class="descname">item</code><span class="sig-paren">(</span><em>index</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.NamedNodeMap.item" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an attribute with a particular index.  The order you get the attributes
in is arbitrary but will be consistent for the life of a DOM.  Each item is an
attribute node.  Get its value with the <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> attribute.</p>
</dd></dl>

<p>There are also experimental methods that give this class more mapping behavior.
You can use them or you can use the standardized <code class="xref py py-meth docutils literal notranslate"><span class="pre">getAttribute*()</span></code> family
of methods on the <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> objects.</p>
</div>
<div class="section" id="comment-objects">
<span id="dom-comment-objects"></span><h3>19.8.2.9. Comment Objects<a class="headerlink" href="#comment-objects" title="Permalink to this headline">¶</a></h3>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Comment</span></code> represents a comment in the XML document.  It is a subclass of
<code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code>, but cannot have child nodes.</p>
<dl class="attribute">
<dt id="xml.dom.Comment.data">
<code class="descclassname">Comment.</code><code class="descname">data</code><a class="headerlink" href="#xml.dom.Comment.data" title="Permalink to this definition">¶</a></dt>
<dd><p>The content of the comment as a string.  The attribute contains all characters
between the leading <code class="docutils literal notranslate"><span class="pre">&lt;!-</span></code><code class="docutils literal notranslate"><span class="pre">-</span></code> and trailing <code class="docutils literal notranslate"><span class="pre">-</span></code><code class="docutils literal notranslate"><span class="pre">-&gt;</span></code>, but does not
include them.</p>
</dd></dl>

</div>
<div class="section" id="text-and-cdatasection-objects">
<span id="dom-text-objects"></span><h3>19.8.2.10. Text and CDATASection Objects<a class="headerlink" href="#text-and-cdatasection-objects" title="Permalink to this headline">¶</a></h3>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Text</span></code> interface represents text in the XML document.  If the parser
and DOM implementation support the DOM’s XML extension, portions of the text
enclosed in CDATA marked sections are stored in <code class="xref py py-class docutils literal notranslate"><span class="pre">CDATASection</span></code> objects.
These two interfaces are identical, but provide different values for the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">nodeType</span></code> attribute.</p>
<p>These interfaces extend the <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> interface.  They cannot have child
nodes.</p>
<dl class="attribute">
<dt id="xml.dom.Text.data">
<code class="descclassname">Text.</code><code class="descname">data</code><a class="headerlink" href="#xml.dom.Text.data" title="Permalink to this definition">¶</a></dt>
<dd><p>The content of the text node as a string.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The use of a <code class="xref py py-class docutils literal notranslate"><span class="pre">CDATASection</span></code> node does not indicate that the node
represents a complete CDATA marked section, only that the content of the node
was part of a CDATA section.  A single CDATA section may be represented by more
than one node in the document tree.  There is no way to determine whether two
adjacent <code class="xref py py-class docutils literal notranslate"><span class="pre">CDATASection</span></code> nodes represent different CDATA marked sections.</p>
</div>
</div>
<div class="section" id="processinginstruction-objects">
<span id="dom-pi-objects"></span><h3>19.8.2.11. ProcessingInstruction Objects<a class="headerlink" href="#processinginstruction-objects" title="Permalink to this headline">¶</a></h3>
<p>Represents a processing instruction in the XML document; this inherits from the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> interface and cannot have child nodes.</p>
<dl class="attribute">
<dt id="xml.dom.ProcessingInstruction.target">
<code class="descclassname">ProcessingInstruction.</code><code class="descname">target</code><a class="headerlink" href="#xml.dom.ProcessingInstruction.target" title="Permalink to this definition">¶</a></dt>
<dd><p>The content of the processing instruction up to the first whitespace character.
This is a read-only attribute.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.dom.ProcessingInstruction.data">
<code class="descclassname">ProcessingInstruction.</code><code class="descname">data</code><a class="headerlink" href="#xml.dom.ProcessingInstruction.data" title="Permalink to this definition">¶</a></dt>
<dd><p>The content of the processing instruction following the first whitespace
character.</p>
</dd></dl>

</div>
<div class="section" id="exceptions">
<span id="dom-exceptions"></span><h3>19.8.2.12. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p>The DOM Level 2 recommendation defines a single exception, <a class="reference internal" href="#xml.dom.DOMException" title="xml.dom.DOMException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DOMException</span></code></a>,
and a number of constants that allow applications to determine what sort of
error occurred. <a class="reference internal" href="#xml.dom.DOMException" title="xml.dom.DOMException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DOMException</span></code></a> instances carry a <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a> attribute
that provides the appropriate value for the specific exception.</p>
<p>The Python DOM interface provides the constants, but also expands the set of
exceptions so that a specific exception exists for each of the exception codes
defined by the DOM.  The implementations must raise the appropriate specific
exception, each of which carries the appropriate value for the <a class="reference internal" href="code.html#module-code" title="code: Facilities to implement read-eval-print loops."><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span></code></a>
attribute.</p>
<dl class="exception">
<dt id="xml.dom.DOMException">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">DOMException</code><a class="headerlink" href="#xml.dom.DOMException" title="Permalink to this definition">¶</a></dt>
<dd><p>Base exception class used for all specific DOM exceptions.  This exception class
cannot be directly instantiated.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.DomstringSizeErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">DomstringSizeErr</code><a class="headerlink" href="#xml.dom.DomstringSizeErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a specified range of text does not fit into a string. This is not
known to be used in the Python DOM implementations, but may be received from DOM
implementations not written in Python.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.HierarchyRequestErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">HierarchyRequestErr</code><a class="headerlink" href="#xml.dom.HierarchyRequestErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an attempt is made to insert a node where the node type is not
allowed.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.IndexSizeErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">IndexSizeErr</code><a class="headerlink" href="#xml.dom.IndexSizeErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an index or size parameter to a method is negative or exceeds the
allowed values.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.InuseAttributeErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">InuseAttributeErr</code><a class="headerlink" href="#xml.dom.InuseAttributeErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an attempt is made to insert an <code class="xref py py-class docutils literal notranslate"><span class="pre">Attr</span></code> node that is already
present elsewhere in the document.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.InvalidAccessErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">InvalidAccessErr</code><a class="headerlink" href="#xml.dom.InvalidAccessErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised if a parameter or an operation is not supported on the underlying object.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.InvalidCharacterErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">InvalidCharacterErr</code><a class="headerlink" href="#xml.dom.InvalidCharacterErr" title="Permalink to this definition">¶</a></dt>
<dd><p>This exception is raised when a string parameter contains a character that is
not permitted in the context it’s being used in by the XML 1.0 recommendation.
For example, attempting to create an <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> node with a space in the
element type name will cause this error to be raised.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.InvalidModificationErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">InvalidModificationErr</code><a class="headerlink" href="#xml.dom.InvalidModificationErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an attempt is made to modify the type of a node.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.InvalidStateErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">InvalidStateErr</code><a class="headerlink" href="#xml.dom.InvalidStateErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an attempt is made to use an object that is not defined or is no
longer usable.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.NamespaceErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">NamespaceErr</code><a class="headerlink" href="#xml.dom.NamespaceErr" title="Permalink to this definition">¶</a></dt>
<dd><p>If an attempt is made to change any object in a way that is not permitted with
regard to the <a class="reference external" href="https://www.w3.org/TR/REC-xml-names/">Namespaces in XML</a>
recommendation, this exception is raised.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.NotFoundErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">NotFoundErr</code><a class="headerlink" href="#xml.dom.NotFoundErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception when a node does not exist in the referenced context.  For example,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">NamedNodeMap.removeNamedItem()</span></code> will raise this if the node passed in does
not exist in the map.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.NotSupportedErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">NotSupportedErr</code><a class="headerlink" href="#xml.dom.NotSupportedErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when the implementation does not support the requested type of object or
operation.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.NoDataAllowedErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">NoDataAllowedErr</code><a class="headerlink" href="#xml.dom.NoDataAllowedErr" title="Permalink to this definition">¶</a></dt>
<dd><p>This is raised if data is specified for a node which does not support data.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.NoModificationAllowedErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">NoModificationAllowedErr</code><a class="headerlink" href="#xml.dom.NoModificationAllowedErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised on attempts to modify an object where modifications are not allowed (such
as for read-only nodes).</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.SyntaxErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">SyntaxErr</code><a class="headerlink" href="#xml.dom.SyntaxErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when an invalid or illegal string is specified.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.dom.WrongDocumentErr">
<em class="property">exception </em><code class="descclassname">xml.dom.</code><code class="descname">WrongDocumentErr</code><a class="headerlink" href="#xml.dom.WrongDocumentErr" title="Permalink to this definition">¶</a></dt>
<dd><p>Raised when a node is inserted in a different document than it currently belongs
to, and the implementation does not support migrating the node from one document
to the other.</p>
</dd></dl>

<p>The exception codes defined in the DOM recommendation map to the exceptions
described above according to this table:</p>
<table border="1" class="docutils">
<colgroup>
<col width="54%" />
<col width="46%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Constant</th>
<th class="head">Exception</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">DOMSTRING_SIZE_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.DomstringSizeErr" title="xml.dom.DomstringSizeErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DomstringSizeErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">HIERARCHY_REQUEST_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.HierarchyRequestErr" title="xml.dom.HierarchyRequestErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">HierarchyRequestErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INDEX_SIZE_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.IndexSizeErr" title="xml.dom.IndexSizeErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexSizeErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INUSE_ATTRIBUTE_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.InuseAttributeErr" title="xml.dom.InuseAttributeErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InuseAttributeErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INVALID_ACCESS_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.InvalidAccessErr" title="xml.dom.InvalidAccessErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidAccessErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INVALID_CHARACTER_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.InvalidCharacterErr" title="xml.dom.InvalidCharacterErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidCharacterErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INVALID_MODIFICATION_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.InvalidModificationErr" title="xml.dom.InvalidModificationErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidModificationErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">INVALID_STATE_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.InvalidStateErr" title="xml.dom.InvalidStateErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NAMESPACE_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.NamespaceErr" title="xml.dom.NamespaceErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NamespaceErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_FOUND_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.NotFoundErr" title="xml.dom.NotFoundErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotFoundErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NOT_SUPPORTED_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.NotSupportedErr" title="xml.dom.NotSupportedErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NotSupportedErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NO_DATA_ALLOWED_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.NoDataAllowedErr" title="xml.dom.NoDataAllowedErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoDataAllowedErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">NO_MODIFICATION_ALLOWED_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.NoModificationAllowedErr" title="xml.dom.NoModificationAllowedErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NoModificationAllowedErr</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">SYNTAX_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.SyntaxErr" title="xml.dom.SyntaxErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxErr</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="xref py py-const docutils literal notranslate"><span class="pre">WRONG_DOCUMENT_ERR</span></code></td>
<td><a class="reference internal" href="#xml.dom.WrongDocumentErr" title="xml.dom.WrongDocumentErr"><code class="xref py py-exc docutils literal notranslate"><span class="pre">WrongDocumentErr</span></code></a></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="section" id="conformance">
<span id="dom-conformance"></span><h2>19.8.3. Conformance<a class="headerlink" href="#conformance" title="Permalink to this headline">¶</a></h2>
<p>This section describes the conformance requirements and relationships between
the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for
Python.</p>
<div class="section" id="type-mapping">
<span id="dom-type-mapping"></span><h3>19.8.3.1. Type Mapping<a class="headerlink" href="#type-mapping" title="Permalink to this headline">¶</a></h3>
<p>The primitive IDL types used in the DOM specification are mapped to Python types
according to the following table.</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">IDL Type</th>
<th class="head">Python Type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">boolean</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">IntegerType</span></code> (with a value of <code class="docutils literal notranslate"><span class="pre">0</span></code> or
<code class="docutils literal notranslate"><span class="pre">1</span></code>)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">int</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">IntegerType</span></code></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">long</span> <span class="pre">int</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">IntegerType</span></code></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">IntegerType</span></code></td>
</tr>
</tbody>
</table>
<p>Additionally, the <code class="xref py py-class docutils literal notranslate"><span class="pre">DOMString</span></code> defined in the recommendation is mapped to
a Python string or Unicode string.  Applications should be able to handle
Unicode whenever a string is returned from the DOM.</p>
<p>The IDL <code class="docutils literal notranslate"><span class="pre">null</span></code> value is mapped to <code class="docutils literal notranslate"><span class="pre">None</span></code>, which may be accepted or
provided by the implementation whenever <code class="docutils literal notranslate"><span class="pre">null</span></code> is allowed by the API.</p>
</div>
<div class="section" id="accessor-methods">
<span id="dom-accessor-methods"></span><h3>19.8.3.2. Accessor Methods<a class="headerlink" href="#accessor-methods" title="Permalink to this headline">¶</a></h3>
<p>The mapping from OMG IDL to Python defines accessor functions for IDL
<code class="docutils literal notranslate"><span class="pre">attribute</span></code> declarations in much the way the Java mapping does.
Mapping the IDL declarations</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">readonly</span> <span class="n">attribute</span> <span class="n">string</span> <span class="n">someValue</span><span class="p">;</span>
         <span class="n">attribute</span> <span class="n">string</span> <span class="n">anotherValue</span><span class="p">;</span>
</pre></div>
</div>
<p>yields three accessor functions:  a “get” method for <code class="xref py py-attr docutils literal notranslate"><span class="pre">someValue</span></code>
(<code class="xref py py-meth docutils literal notranslate"><span class="pre">_get_someValue()</span></code>), and “get” and “set” methods for <code class="xref py py-attr docutils literal notranslate"><span class="pre">anotherValue</span></code>
(<code class="xref py py-meth docutils literal notranslate"><span class="pre">_get_anotherValue()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">_set_anotherValue()</span></code>).  The mapping, in
particular, does not require that the IDL attributes are accessible as normal
Python attributes:  <code class="docutils literal notranslate"><span class="pre">object.someValue</span></code> is <em>not</em> required to work, and may
raise an <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</p>
<p>The Python DOM API, however, <em>does</em> require that normal attribute access work.
This means that the typical surrogates generated by Python IDL compilers are not
likely to work, and wrapper objects may be needed on the client if the DOM
objects are accessed via CORBA. While this does require some additional
consideration for CORBA DOM clients, the implementers with experience using DOM
over CORBA from Python do not consider this a problem.  Attributes that are
declared <code class="docutils literal notranslate"><span class="pre">readonly</span></code> may not restrict write access in all DOM
implementations.</p>
<p>In the Python DOM API, accessor functions are not required.  If provided, they
should take the form defined by the Python IDL mapping, but these methods are
considered unnecessary since the attributes are accessible directly from Python.
“Set” accessors should never be provided for <code class="docutils literal notranslate"><span class="pre">readonly</span></code> attributes.</p>
<p>The IDL definitions do not fully embody the requirements of the W3C DOM API,
such as the notion of certain objects, such as the return value of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getElementsByTagName()</span></code>, being “live”.  The Python DOM API does not require
implementations to enforce such requirements.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a><ul>
<li><a class="reference internal" href="#module-contents">19.8.1. Module Contents</a></li>
<li><a class="reference internal" href="#objects-in-the-dom">19.8.2. Objects in the DOM</a><ul>
<li><a class="reference internal" href="#domimplementation-objects">19.8.2.1. DOMImplementation Objects</a></li>
<li><a class="reference internal" href="#node-objects">19.8.2.2. Node Objects</a></li>
<li><a class="reference internal" href="#nodelist-objects">19.8.2.3. NodeList Objects</a></li>
<li><a class="reference internal" href="#documenttype-objects">19.8.2.4. DocumentType Objects</a></li>
<li><a class="reference internal" href="#document-objects">19.8.2.5. Document Objects</a></li>
<li><a class="reference internal" href="#element-objects">19.8.2.6. Element Objects</a></li>
<li><a class="reference internal" href="#attr-objects">19.8.2.7. Attr Objects</a></li>
<li><a class="reference internal" href="#namednodemap-objects">19.8.2.8. NamedNodeMap Objects</a></li>
<li><a class="reference internal" href="#comment-objects">19.8.2.9. Comment Objects</a></li>
<li><a class="reference internal" href="#text-and-cdatasection-objects">19.8.2.10. Text and CDATASection Objects</a></li>
<li><a class="reference internal" href="#processinginstruction-objects">19.8.2.11. ProcessingInstruction Objects</a></li>
<li><a class="reference internal" href="#exceptions">19.8.2.12. Exceptions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#conformance">19.8.3. Conformance</a><ul>
<li><a class="reference internal" href="#type-mapping">19.8.3.1. Type Mapping</a></li>
<li><a class="reference internal" href="#accessor-methods">19.8.3.2. Accessor Methods</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.etree.elementtree.html"
                        title="previous chapter">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.dom.minidom.html"
                        title="next chapter">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.dom.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.minidom.html" title="19.9. xml.dom.minidom — Minimal DOM implementation"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.etree.elementtree.html" title="19.7. xml.etree.ElementTree — The ElementTree XML API"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\*=ިި!html/library/xml.dom.minidom.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.9. xml.dom.minidom — Minimal DOM implementation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.10. xml.dom.pulldom — Support for building partial DOM trees" href="xml.dom.pulldom.html" />
    <link rel="prev" title="19.8. xml.dom — The Document Object Model API" href="xml.dom.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.dom.minidom.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.pulldom.html" title="19.10. xml.dom.pulldom — Support for building partial DOM trees"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="19.8. xml.dom — The Document Object Model API"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.dom.minidom">
<span id="xml-dom-minidom-minimal-dom-implementation"></span><h1>19.9. <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> — Minimal DOM implementation<a class="headerlink" href="#module-xml.dom.minidom" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/xml/dom/minidom.py">Lib/xml/dom/minidom.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> is a minimal implementation of the Document Object
Model interface, with an API similar to that in other languages.  It is intended
to be simpler than the full DOM and also significantly smaller.  Users who are
not already proficient with the DOM should consider using the
<a class="reference internal" href="xml.etree.elementtree.html#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> module for their XML processing instead.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> module is not secure against
maliciously constructed data.  If you need to parse untrusted or
unauthenticated data see <a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<p>DOM applications typically start by parsing some XML into a DOM.  With
<a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>, this is done through the parse functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.dom.minidom</span> <span class="k">import</span> <span class="n">parse</span><span class="p">,</span> <span class="n">parseString</span>

<span class="n">dom1</span> <span class="o">=</span> <span class="n">parse</span><span class="p">(</span><span class="s1">&#39;c:</span><span class="se">\\</span><span class="s1">temp</span><span class="se">\\</span><span class="s1">mydata.xml&#39;</span><span class="p">)</span>  <span class="c1"># parse an XML file by name</span>

<span class="n">datasource</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;c:</span><span class="se">\\</span><span class="s1">temp</span><span class="se">\\</span><span class="s1">mydata.xml&#39;</span><span class="p">)</span>
<span class="n">dom2</span> <span class="o">=</span> <span class="n">parse</span><span class="p">(</span><span class="n">datasource</span><span class="p">)</span>  <span class="c1"># parse an open file</span>

<span class="n">dom3</span> <span class="o">=</span> <span class="n">parseString</span><span class="p">(</span><span class="s1">&#39;&lt;myxml&gt;Some data&lt;empty/&gt; some more data&lt;/myxml&gt;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="#xml.dom.minidom.parse" title="xml.dom.minidom.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a> function can take either a filename or an open file object.</p>
<dl class="function">
<dt id="xml.dom.minidom.parse">
<code class="descclassname">xml.dom.minidom.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>filename_or_file</em><span class="optional">[</span>, <em>parser</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> from the given input. <em>filename_or_file</em> may be
either a file name, or a file-like object. <em>parser</em>, if given, must be a SAX2
parser object. This function will change the document handler of the parser and
activate namespace support; other parser configuration (like setting an entity
resolver) must have been done in advance.</p>
</dd></dl>

<p>If you have XML in a string, you can use the <a class="reference internal" href="#xml.dom.minidom.parseString" title="xml.dom.minidom.parseString"><code class="xref py py-func docutils literal notranslate"><span class="pre">parseString()</span></code></a> function
instead:</p>
<dl class="function">
<dt id="xml.dom.minidom.parseString">
<code class="descclassname">xml.dom.minidom.</code><code class="descname">parseString</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>parser</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.parseString" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> that represents the <em>string</em>. This method creates a
<a class="reference internal" href="stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> object for the string and passes that on to <a class="reference internal" href="#xml.dom.minidom.parse" title="xml.dom.minidom.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a>.</p>
</dd></dl>

<p>Both functions return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object representing the content of the
document.</p>
<p>What the <a class="reference internal" href="#xml.dom.minidom.parse" title="xml.dom.minidom.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a> and <a class="reference internal" href="#xml.dom.minidom.parseString" title="xml.dom.minidom.parseString"><code class="xref py py-func docutils literal notranslate"><span class="pre">parseString()</span></code></a> functions do is connect an XML
parser with a “DOM builder” that can accept parse events from any SAX parser and
convert them into a DOM tree.  The name of the functions are perhaps misleading,
but are easy to grasp when learning the interfaces.  The parsing of the document
will be completed before these functions return; it’s simply that these
functions do not provide a parser implementation themselves.</p>
<p>You can also create a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> by calling a method on a “DOM
Implementation” object.  You can get this object either by calling the
<code class="xref py py-func docutils literal notranslate"><span class="pre">getDOMImplementation()</span></code> function in the <a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> package or the
<a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> module. Using the implementation from the
<a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> module will always return a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> instance
from the minidom implementation, while the version from <a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> may
provide an alternate implementation (this is likely if you have the <a class="reference external" href="http://pyxml.sourceforge.net/">PyXML
package</a> installed).  Once you have a
<code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code>, you can add child nodes to it to populate the DOM:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.dom.minidom</span> <span class="k">import</span> <span class="n">getDOMImplementation</span>

<span class="n">impl</span> <span class="o">=</span> <span class="n">getDOMImplementation</span><span class="p">()</span>

<span class="n">newdoc</span> <span class="o">=</span> <span class="n">impl</span><span class="o">.</span><span class="n">createDocument</span><span class="p">(</span><span class="kc">None</span><span class="p">,</span> <span class="s2">&quot;some_tag&quot;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
<span class="n">top_element</span> <span class="o">=</span> <span class="n">newdoc</span><span class="o">.</span><span class="n">documentElement</span>
<span class="n">text</span> <span class="o">=</span> <span class="n">newdoc</span><span class="o">.</span><span class="n">createTextNode</span><span class="p">(</span><span class="s1">&#39;Some textual content.&#39;</span><span class="p">)</span>
<span class="n">top_element</span><span class="o">.</span><span class="n">appendChild</span><span class="p">(</span><span class="n">text</span><span class="p">)</span>
</pre></div>
</div>
<p>Once you have a DOM document object, you can access the parts of your XML
document through its properties and methods.  These properties are defined in
the DOM specification.  The main property of the document object is the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">documentElement</span></code> property.  It gives you the main element in the XML
document: the one that holds all others.  Here is an example program:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">dom3</span> <span class="o">=</span> <span class="n">parseString</span><span class="p">(</span><span class="s2">&quot;&lt;myxml&gt;Some data&lt;/myxml&gt;&quot;</span><span class="p">)</span>
<span class="k">assert</span> <span class="n">dom3</span><span class="o">.</span><span class="n">documentElement</span><span class="o">.</span><span class="n">tagName</span> <span class="o">==</span> <span class="s2">&quot;myxml&quot;</span>
</pre></div>
</div>
<p>When you are finished with a DOM tree, you may optionally call the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">unlink()</span></code> method to encourage early cleanup of the now-unneeded
objects.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">unlink()</span></code> is an <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>-specific
extension to the DOM API that renders the node and its descendants are
essentially useless.  Otherwise, Python’s garbage collector will
eventually take care of the objects in the tree.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.w3.org/TR/REC-DOM-Level-1/">Document Object Model (DOM) Level 1 Specification</a></dt>
<dd>The W3C recommendation for the DOM supported by <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>.</dd>
</dl>
</div>
<div class="section" id="dom-objects">
<span id="minidom-objects"></span><h2>19.9.1. DOM Objects<a class="headerlink" href="#dom-objects" title="Permalink to this headline">¶</a></h2>
<p>The definition of the DOM API for Python is given as part of the <a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a>
module documentation.  This section lists the differences between the API and
<a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>.</p>
<dl class="method">
<dt id="xml.dom.minidom.Node.unlink">
<code class="descclassname">Node.</code><code class="descname">unlink</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.Node.unlink" title="Permalink to this definition">¶</a></dt>
<dd><p>Break internal references within the DOM so that it will be garbage collected on
versions of Python without cyclic GC.  Even when cyclic GC is available, using
this can make large amounts of memory available sooner, so calling this on DOM
objects as soon as they are no longer needed is good practice.  This only needs
to be called on the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object, but may be called on child nodes
to discard children of that node.</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.minidom.Node.writexml">
<code class="descclassname">Node.</code><code class="descname">writexml</code><span class="sig-paren">(</span><em>writer</em>, <em>indent=&quot;&quot;</em>, <em>addindent=&quot;&quot;</em>, <em>newl=&quot;&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.Node.writexml" title="Permalink to this definition">¶</a></dt>
<dd><p>Write XML to the writer object.  The writer should have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method
which matches that of the file object interface.  The <em>indent</em> parameter is the
indentation of the current node.  The <em>addindent</em> parameter is the incremental
indentation to use for subnodes of the current one.  The <em>newl</em> parameter
specifies the string to use to terminate newlines.</p>
<p>For the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> node, an additional keyword argument <em>encoding</em> can
be used to specify the encoding field of the XML header.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>The optional keyword parameters <em>indent</em>, <em>addindent</em>, and <em>newl</em> were added to
support pretty output.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>For the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> node, an additional keyword argument
<em>encoding</em> can be used to specify the encoding field of the XML header.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.dom.minidom.Node.toxml">
<code class="descclassname">Node.</code><code class="descname">toxml</code><span class="sig-paren">(</span><span class="optional">[</span><em>encoding</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.Node.toxml" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the XML that the DOM represents as a string.</p>
<p>With no argument, the XML header does not specify an encoding, and the result is
Unicode string if the default encoding cannot represent all characters in the
document. Encoding this string in an encoding other than UTF-8 is likely
incorrect, since UTF-8 is the default encoding of XML.</p>
<p>With an explicit <em>encoding</em> <a class="footnote-reference" href="#id3" id="id1">[1]</a> argument, the result is a byte string in the
specified encoding. It is recommended that this argument is always specified. To
avoid <a class="reference internal" href="exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a> exceptions in case of unrepresentable text data, the
encoding argument should be specified as “utf-8”.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>the <em>encoding</em> argument was introduced; see <a class="reference internal" href="#xml.dom.minidom.Node.writexml" title="xml.dom.minidom.Node.writexml"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writexml()</span></code></a>.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.dom.minidom.Node.toprettyxml">
<code class="descclassname">Node.</code><code class="descname">toprettyxml</code><span class="sig-paren">(</span><em>indent=&quot;\t&quot;</em>, <em>newl=&quot;\n&quot;</em>, <em>encoding=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.Node.toprettyxml" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a pretty-printed version of the document. <em>indent</em> specifies the
indentation string and defaults to a tabulator; <em>newl</em> specifies the string
emitted at the end of each line and defaults to <code class="docutils literal notranslate"><span class="pre">\n</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>the encoding argument was introduced; see <a class="reference internal" href="#xml.dom.minidom.Node.writexml" title="xml.dom.minidom.Node.writexml"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writexml()</span></code></a>.</p>
</div>
</dd></dl>

<p>The following standard DOM methods have special considerations with
<a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>:</p>
<dl class="method">
<dt id="xml.dom.minidom.Node.cloneNode">
<code class="descclassname">Node.</code><code class="descname">cloneNode</code><span class="sig-paren">(</span><em>deep</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.minidom.Node.cloneNode" title="Permalink to this definition">¶</a></dt>
<dd><p>Although this method was present in the version of <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>
packaged with Python 2.0, it was seriously broken.  This has been corrected for
subsequent releases.</p>
</dd></dl>

</div>
<div class="section" id="dom-example">
<span id="id2"></span><h2>19.9.2. DOM Example<a class="headerlink" href="#dom-example" title="Permalink to this headline">¶</a></h2>
<p>This example program is a fairly realistic example of a simple program. In this
particular case, we do not take much advantage of the flexibility of the DOM.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.dom.minidom</span>

<span class="n">document</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">&lt;slideshow&gt;</span>
<span class="s2">&lt;title&gt;Demo slideshow&lt;/title&gt;</span>
<span class="s2">&lt;slide&gt;&lt;title&gt;Slide title&lt;/title&gt;</span>
<span class="s2">&lt;point&gt;This is a demo&lt;/point&gt;</span>
<span class="s2">&lt;point&gt;Of a program for processing slides&lt;/point&gt;</span>
<span class="s2">&lt;/slide&gt;</span>

<span class="s2">&lt;slide&gt;&lt;title&gt;Another demo slide&lt;/title&gt;</span>
<span class="s2">&lt;point&gt;It is important&lt;/point&gt;</span>
<span class="s2">&lt;point&gt;To have more than&lt;/point&gt;</span>
<span class="s2">&lt;point&gt;one slide&lt;/point&gt;</span>
<span class="s2">&lt;/slide&gt;</span>
<span class="s2">&lt;/slideshow&gt;</span>
<span class="s2">&quot;&quot;&quot;</span>

<span class="n">dom</span> <span class="o">=</span> <span class="n">xml</span><span class="o">.</span><span class="n">dom</span><span class="o">.</span><span class="n">minidom</span><span class="o">.</span><span class="n">parseString</span><span class="p">(</span><span class="n">document</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">getText</span><span class="p">(</span><span class="n">nodelist</span><span class="p">):</span>
    <span class="n">rc</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">node</span> <span class="ow">in</span> <span class="n">nodelist</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">node</span><span class="o">.</span><span class="n">nodeType</span> <span class="o">==</span> <span class="n">node</span><span class="o">.</span><span class="n">TEXT_NODE</span><span class="p">:</span>
            <span class="n">rc</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">node</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
    <span class="k">return</span> <span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">rc</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">handleSlideshow</span><span class="p">(</span><span class="n">slideshow</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;html&gt;&quot;</span>
    <span class="n">handleSlideshowTitle</span><span class="p">(</span><span class="n">slideshow</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span><span class="s2">&quot;title&quot;</span><span class="p">)[</span><span class="mi">0</span><span class="p">])</span>
    <span class="n">slides</span> <span class="o">=</span> <span class="n">slideshow</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span><span class="s2">&quot;slide&quot;</span><span class="p">)</span>
    <span class="n">handleToc</span><span class="p">(</span><span class="n">slides</span><span class="p">)</span>
    <span class="n">handleSlides</span><span class="p">(</span><span class="n">slides</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;/html&gt;&quot;</span>

<span class="k">def</span> <span class="nf">handleSlides</span><span class="p">(</span><span class="n">slides</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">slide</span> <span class="ow">in</span> <span class="n">slides</span><span class="p">:</span>
        <span class="n">handleSlide</span><span class="p">(</span><span class="n">slide</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">handleSlide</span><span class="p">(</span><span class="n">slide</span><span class="p">):</span>
    <span class="n">handleSlideTitle</span><span class="p">(</span><span class="n">slide</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span><span class="s2">&quot;title&quot;</span><span class="p">)[</span><span class="mi">0</span><span class="p">])</span>
    <span class="n">handlePoints</span><span class="p">(</span><span class="n">slide</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span><span class="s2">&quot;point&quot;</span><span class="p">))</span>

<span class="k">def</span> <span class="nf">handleSlideshowTitle</span><span class="p">(</span><span class="n">title</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;title&gt;</span><span class="si">%s</span><span class="s2">&lt;/title&gt;&quot;</span> <span class="o">%</span> <span class="n">getText</span><span class="p">(</span><span class="n">title</span><span class="o">.</span><span class="n">childNodes</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">handleSlideTitle</span><span class="p">(</span><span class="n">title</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;h2&gt;</span><span class="si">%s</span><span class="s2">&lt;/h2&gt;&quot;</span> <span class="o">%</span> <span class="n">getText</span><span class="p">(</span><span class="n">title</span><span class="o">.</span><span class="n">childNodes</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">handlePoints</span><span class="p">(</span><span class="n">points</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;ul&gt;&quot;</span>
    <span class="k">for</span> <span class="n">point</span> <span class="ow">in</span> <span class="n">points</span><span class="p">:</span>
        <span class="n">handlePoint</span><span class="p">(</span><span class="n">point</span><span class="p">)</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;/ul&gt;&quot;</span>

<span class="k">def</span> <span class="nf">handlePoint</span><span class="p">(</span><span class="n">point</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;&lt;li&gt;</span><span class="si">%s</span><span class="s2">&lt;/li&gt;&quot;</span> <span class="o">%</span> <span class="n">getText</span><span class="p">(</span><span class="n">point</span><span class="o">.</span><span class="n">childNodes</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">handleToc</span><span class="p">(</span><span class="n">slides</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">slide</span> <span class="ow">in</span> <span class="n">slides</span><span class="p">:</span>
        <span class="n">title</span> <span class="o">=</span> <span class="n">slide</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span><span class="s2">&quot;title&quot;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
        <span class="nb">print</span> <span class="s2">&quot;&lt;p&gt;</span><span class="si">%s</span><span class="s2">&lt;/p&gt;&quot;</span> <span class="o">%</span> <span class="n">getText</span><span class="p">(</span><span class="n">title</span><span class="o">.</span><span class="n">childNodes</span><span class="p">)</span>

<span class="n">handleSlideshow</span><span class="p">(</span><span class="n">dom</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="minidom-and-the-dom-standard">
<span id="minidom-and-dom"></span><h2>19.9.3. minidom and the DOM standard<a class="headerlink" href="#minidom-and-the-dom-standard" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> module is essentially a DOM 1.0-compatible DOM with
some DOM 2 features (primarily namespace features).</p>
<p>Usage of the DOM interface in Python is straight-forward.  The following mapping
rules apply:</p>
<ul class="simple">
<li>Interfaces are accessed through instance objects. Applications should not
instantiate the classes themselves; they should use the creator functions
available on the <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> object. Derived interfaces support all
operations (and attributes) from the base interfaces, plus any new operations.</li>
<li>Operations are used as methods. Since the DOM uses only <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>
parameters, the arguments are passed in normal order (from left to right).
There are no optional arguments. <code class="docutils literal notranslate"><span class="pre">void</span></code> operations return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
<li>IDL attributes map to instance attributes. For compatibility with the OMG IDL
language mapping for Python, an attribute <code class="docutils literal notranslate"><span class="pre">foo</span></code> can also be accessed through
accessor methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">_get_foo()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">_set_foo()</span></code>.  <code class="docutils literal notranslate"><span class="pre">readonly</span></code>
attributes must not be changed; this is not enforced at runtime.</li>
<li>The types <code class="docutils literal notranslate"><span class="pre">short</span> <span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">long</span> <span class="pre">long</span></code>, and
<code class="docutils literal notranslate"><span class="pre">boolean</span></code> all map to Python integer objects.</li>
<li>The type <code class="docutils literal notranslate"><span class="pre">DOMString</span></code> maps to Python strings. <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> supports
either byte or Unicode strings, but will normally produce Unicode strings.
Values of type <code class="docutils literal notranslate"><span class="pre">DOMString</span></code> may also be <code class="docutils literal notranslate"><span class="pre">None</span></code> where allowed to have the IDL
<code class="docutils literal notranslate"><span class="pre">null</span></code> value by the DOM specification from the W3C.</li>
<li><code class="docutils literal notranslate"><span class="pre">const</span></code> declarations map to variables in their respective scope (e.g.
<code class="docutils literal notranslate"><span class="pre">xml.dom.minidom.Node.PROCESSING_INSTRUCTION_NODE</span></code>); they must not be changed.</li>
<li><code class="docutils literal notranslate"><span class="pre">DOMException</span></code> is currently not supported in <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>.
Instead, <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> uses standard Python exceptions such as
<a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and <a class="reference internal" href="exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>.</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> objects are implemented using Python’s built-in list type.
Starting with Python 2.2, these objects provide the interface defined in the DOM
specification, but with earlier versions of Python they do not support the
official API.  They are, however, much more “Pythonic” than the interface
defined in the W3C recommendations.</li>
</ul>
<p>The following interfaces have no implementation in <a class="reference internal" href="#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>:</p>
<ul class="simple">
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">DOMTimeStamp</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentType</span></code> (added in Python 2.1)</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">DOMImplementation</span></code> (added in Python 2.1)</li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">CharacterData</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">CDATASection</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">Notation</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">Entity</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">EntityReference</span></code></li>
<li><code class="xref py py-class docutils literal notranslate"><span class="pre">DocumentFragment</span></code></li>
</ul>
<p>Most of these reflect information in the XML document that is not of general
utility to most DOM users.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The encoding string included in XML output should conform to the
appropriate standards. For example, “UTF-8” is valid, but “UTF8” is
not. See <a class="reference external" href="https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl">https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl</a>
and <a class="reference external" href="https://www.iana.org/assignments/character-sets/character-sets.xhtml">https://www.iana.org/assignments/character-sets/character-sets.xhtml</a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a><ul>
<li><a class="reference internal" href="#dom-objects">19.9.1. DOM Objects</a></li>
<li><a class="reference internal" href="#dom-example">19.9.2. DOM Example</a></li>
<li><a class="reference internal" href="#minidom-and-the-dom-standard">19.9.3. minidom and the DOM standard</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.dom.html"
                        title="previous chapter">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.dom.pulldom.html"
                        title="next chapter">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.dom.minidom.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.pulldom.html" title="19.10. xml.dom.pulldom — Support for building partial DOM trees"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="19.8. xml.dom — The Document Object Model API"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�]�66!html/library/xml.dom.pulldom.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.10. xml.dom.pulldom — Support for building partial DOM trees &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.11. xml.sax — Support for SAX2 parsers" href="xml.sax.html" />
    <link rel="prev" title="19.9. xml.dom.minidom — Minimal DOM implementation" href="xml.dom.minidom.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.dom.pulldom.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.html" title="19.11. xml.sax — Support for SAX2 parsers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.dom.minidom.html" title="19.9. xml.dom.minidom — Minimal DOM implementation"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.dom.pulldom">
<span id="xml-dom-pulldom-support-for-building-partial-dom-trees"></span><h1>19.10. <a class="reference internal" href="#module-xml.dom.pulldom" title="xml.dom.pulldom: Support for building partial DOM trees from SAX events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code></a> — Support for building partial DOM trees<a class="headerlink" href="#module-xml.dom.pulldom" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/xml/dom/pulldom.py">Lib/xml/dom/pulldom.py</a></p>
<hr class="docutils" />
<p><a class="reference internal" href="#module-xml.dom.pulldom" title="xml.dom.pulldom: Support for building partial DOM trees from SAX events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code></a> allows building only selected portions of a Document
Object Model representation of a document from SAX events.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-xml.dom.pulldom" title="xml.dom.pulldom: Support for building partial DOM trees from SAX events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code></a> module is not secure against
maliciously constructed data.  If you need to parse untrusted or
unauthenticated data see <a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<dl class="class">
<dt id="xml.dom.pulldom.PullDOM">
<em class="property">class </em><code class="descclassname">xml.dom.pulldom.</code><code class="descname">PullDOM</code><span class="sig-paren">(</span><span class="optional">[</span><em>documentFactory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.PullDOM" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">xml.sax.handler.ContentHandler</span></code></a> implementation that …</p>
</dd></dl>

<dl class="class">
<dt id="xml.dom.pulldom.DOMEventStream">
<em class="property">class </em><code class="descclassname">xml.dom.pulldom.</code><code class="descname">DOMEventStream</code><span class="sig-paren">(</span><em>stream</em>, <em>parser</em>, <em>bufsize</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.DOMEventStream" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

<dl class="class">
<dt id="xml.dom.pulldom.SAX2DOM">
<em class="property">class </em><code class="descclassname">xml.dom.pulldom.</code><code class="descname">SAX2DOM</code><span class="sig-paren">(</span><span class="optional">[</span><em>documentFactory</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.SAX2DOM" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">xml.sax.handler.ContentHandler</span></code></a> implementation that …</p>
</dd></dl>

<dl class="function">
<dt id="xml.dom.pulldom.parse">
<code class="descclassname">xml.dom.pulldom.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>stream_or_string</em><span class="optional">[</span>, <em>parser</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

<dl class="function">
<dt id="xml.dom.pulldom.parseString">
<code class="descclassname">xml.dom.pulldom.</code><code class="descname">parseString</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>parser</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.parseString" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

<dl class="data">
<dt id="xml.dom.pulldom.default_bufsize">
<code class="descclassname">xml.dom.pulldom.</code><code class="descname">default_bufsize</code><a class="headerlink" href="#xml.dom.pulldom.default_bufsize" title="Permalink to this definition">¶</a></dt>
<dd><p>Default value for the <em>bufsize</em> parameter to <a class="reference internal" href="#xml.dom.pulldom.parse" title="xml.dom.pulldom.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>The value of this variable can be changed before calling <a class="reference internal" href="#xml.dom.pulldom.parse" title="xml.dom.pulldom.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a> and the
new value will take effect.</p>
</div>
</dd></dl>

<div class="section" id="domeventstream-objects">
<span id="id1"></span><h2>19.10.1. DOMEventStream Objects<a class="headerlink" href="#domeventstream-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="xml.dom.pulldom.DOMEventStream.getEvent">
<code class="descclassname">DOMEventStream.</code><code class="descname">getEvent</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.DOMEventStream.getEvent" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.pulldom.DOMEventStream.expandNode">
<code class="descclassname">DOMEventStream.</code><code class="descname">expandNode</code><span class="sig-paren">(</span><em>node</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.DOMEventStream.expandNode" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

<dl class="method">
<dt id="xml.dom.pulldom.DOMEventStream.reset">
<code class="descclassname">DOMEventStream.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.dom.pulldom.DOMEventStream.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>…</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a><ul>
<li><a class="reference internal" href="#domeventstream-objects">19.10.1. DOMEventStream Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.dom.minidom.html"
                        title="previous chapter">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.sax.html"
                        title="next chapter">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.dom.pulldom.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.html" title="19.11. xml.sax — Support for SAX2 parsers"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.dom.minidom.html" title="19.9. xml.dom.minidom — Minimal DOM implementation"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\?8x����'html/library/xml.etree.elementtree.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.7. xml.etree.ElementTree — The ElementTree XML API &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.8. xml.dom — The Document Object Model API" href="xml.dom.html" />
    <link rel="prev" title="19.5. XML Processing Modules" href="xml.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.etree.elementtree.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="19.8. xml.dom — The Document Object Model API"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.html" title="19.5. XML Processing Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.etree.ElementTree">
<span id="xml-etree-elementtree-the-elementtree-xml-api"></span><h1>19.7. <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> — The ElementTree XML API<a class="headerlink" href="#module-xml.etree.ElementTree" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/xml/etree/ElementTree.py">Lib/xml/etree/ElementTree.py</a></p>
<hr class="docutils" />
<p>The <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> type is a flexible container object, designed to store
hierarchical data structures in memory.  The type can be described as a cross
between a list and a dictionary.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> module is not secure against
maliciously constructed data.  If you need to parse untrusted or
unauthenticated data see <a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<p>Each element has a number of properties associated with it:</p>
<ul class="simple">
<li>a tag which is a string identifying what kind of data this element represents
(the element type, in other words).</li>
<li>a number of attributes, stored in a Python dictionary.</li>
<li>a text string.</li>
<li>an optional tail string.</li>
<li>a number of child elements, stored in a Python sequence</li>
</ul>
<p>To create an element instance, use the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> constructor or the
<a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code class="xref py py-func docutils literal notranslate"><span class="pre">SubElement()</span></code></a> factory function.</p>
<p>The <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> class can be used to wrap an element structure, and
convert it from and to XML.</p>
<p>A C implementation of this API is available as <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.cElementTree</span></code>.</p>
<p>See <a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a> for tutorials and links to other
docs.  Fredrik Lundh’s page is also the location of the development version of
the xml.etree.ElementTree.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The ElementTree API is updated to 1.3.  For more information, see
<a class="reference external" href="http://effbot.org/zone/elementtree-13-intro.htm">Introducing ElementTree 1.3</a>.</p>
</div>
<div class="section" id="tutorial">
<h2>19.7.1. Tutorial<a class="headerlink" href="#tutorial" title="Permalink to this headline">¶</a></h2>
<p>This is a short tutorial for using <a class="reference internal" href="#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> (<code class="docutils literal notranslate"><span class="pre">ET</span></code> in
short).  The goal is to demonstrate some of the building blocks and basic
concepts of the module.</p>
<div class="section" id="xml-tree-and-elements">
<h3>19.7.1.1. XML tree and elements<a class="headerlink" href="#xml-tree-and-elements" title="Permalink to this headline">¶</a></h3>
<p>XML is an inherently hierarchical data format, and the most natural way to
represent it is with a tree.  <code class="docutils literal notranslate"><span class="pre">ET</span></code> has two classes for this purpose -
<a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> represents the whole XML document as a tree, and
<a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> represents a single node in this tree.  Interactions with
the whole document (reading and writing to/from files) are usually done
on the <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> level.  Interactions with a single XML element
and its sub-elements are done on the <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> level.</p>
</div>
<div class="section" id="parsing-xml">
<span id="elementtree-parsing-xml"></span><h3>19.7.1.2. Parsing XML<a class="headerlink" href="#parsing-xml" title="Permalink to this headline">¶</a></h3>
<p>We’ll be using the following XML document as the sample data for this section:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>1<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>4<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Panama&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank&gt;</span>68<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>13600<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Costa Rica&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Colombia&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
<p>We have a number of ways to import the data.  Reading the file from disk:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">as</span> <span class="nn">ET</span>
<span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s1">&#39;country_data.xml&#39;</span><span class="p">)</span>
<span class="n">root</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">getroot</span><span class="p">()</span>
</pre></div>
</div>
<p>Reading the data from a string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">root</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="n">country_data_as_string</span><span class="p">)</span>
</pre></div>
</div>
<p><a class="reference internal" href="#xml.etree.ElementTree.fromstring" title="xml.etree.ElementTree.fromstring"><code class="xref py py-func docutils literal notranslate"><span class="pre">fromstring()</span></code></a> parses XML from a string directly into an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a>,
which is the root element of the parsed tree.  Other parsing functions may
create an <a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a>.  Check the documentation to be sure.</p>
<p>As an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a>, <code class="docutils literal notranslate"><span class="pre">root</span></code> has a tag and a dictionary of attributes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="o">.</span><span class="n">tag</span>
<span class="go">&#39;data&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="o">.</span><span class="n">attrib</span>
<span class="go">{}</span>
</pre></div>
</div>
<p>It also has children nodes over which we can iterate:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">child</span> <span class="ow">in</span> <span class="n">root</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">child</span><span class="o">.</span><span class="n">tag</span><span class="p">,</span> <span class="n">child</span><span class="o">.</span><span class="n">attrib</span>
<span class="gp">...</span>
<span class="go">country {&#39;name&#39;: &#39;Liechtenstein&#39;}</span>
<span class="go">country {&#39;name&#39;: &#39;Singapore&#39;}</span>
<span class="go">country {&#39;name&#39;: &#39;Panama&#39;}</span>
</pre></div>
</div>
<p>Children are nested, and we can access specific child nodes by index:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">root</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">text</span>
<span class="go">&#39;2008&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="finding-interesting-elements">
<h3>19.7.1.3. Finding interesting elements<a class="headerlink" href="#finding-interesting-elements" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> has some useful methods that help iterate recursively over all
the sub-tree below it (its children, their children, and so on).  For example,
<a class="reference internal" href="#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.iter()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">neighbor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s1">&#39;neighbor&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">neighbor</span><span class="o">.</span><span class="n">attrib</span>
<span class="gp">...</span>
<span class="go">{&#39;name&#39;: &#39;Austria&#39;, &#39;direction&#39;: &#39;E&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Switzerland&#39;, &#39;direction&#39;: &#39;W&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Malaysia&#39;, &#39;direction&#39;: &#39;N&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Costa Rica&#39;, &#39;direction&#39;: &#39;W&#39;}</span>
<span class="go">{&#39;name&#39;: &#39;Colombia&#39;, &#39;direction&#39;: &#39;E&#39;}</span>
</pre></div>
</div>
<p><a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findall()</span></code></a> finds only elements with a tag which are direct
children of the current element.  <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.find()</span></code></a> finds the <em>first</em> child
with a particular tag, and <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Element.text</span></code></a> accesses the element’s text
content.  <a class="reference internal" href="#xml.etree.ElementTree.Element.get" title="xml.etree.ElementTree.Element.get"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.get()</span></code></a> accesses the element’s attributes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">country</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;country&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">rank</span> <span class="o">=</span> <span class="n">country</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">text</span>
<span class="gp">... </span>    <span class="n">name</span> <span class="o">=</span> <span class="n">country</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">name</span><span class="p">,</span> <span class="n">rank</span>
<span class="gp">...</span>
<span class="go">Liechtenstein 1</span>
<span class="go">Singapore 4</span>
<span class="go">Panama 68</span>
</pre></div>
</div>
<p>More sophisticated specification of which elements to look for is possible by
using <a class="reference internal" href="#elementtree-xpath"><span class="std std-ref">XPath</span></a>.</p>
</div>
<div class="section" id="modifying-an-xml-file">
<h3>19.7.1.4. Modifying an XML File<a class="headerlink" href="#modifying-an-xml-file" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> provides a simple way to build XML documents and write them to files.
The <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code></a> method serves this purpose.</p>
<p>Once created, an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> object may be manipulated by directly changing
its fields (such as <a class="reference internal" href="#xml.etree.ElementTree.Element.text" title="xml.etree.ElementTree.Element.text"><code class="xref py py-attr docutils literal notranslate"><span class="pre">Element.text</span></code></a>), adding and modifying attributes
(<a class="reference internal" href="#xml.etree.ElementTree.Element.set" title="xml.etree.ElementTree.Element.set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.set()</span></code></a> method), as well as adding new children (for example
with <a class="reference internal" href="#xml.etree.ElementTree.Element.append" title="xml.etree.ElementTree.Element.append"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.append()</span></code></a>).</p>
<p>Let’s say we want to add one to each country’s rank, and add an <code class="docutils literal notranslate"><span class="pre">updated</span></code>
attribute to the rank element:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">rank</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">new_rank</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">rank</span><span class="o">.</span><span class="n">text</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="n">rank</span><span class="o">.</span><span class="n">text</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">new_rank</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">rank</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;updated&#39;</span><span class="p">,</span> <span class="s1">&#39;yes&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Our XML now looks like this:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>2<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>5<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Panama&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>69<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>13600<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Costa Rica&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Colombia&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
<p>We can remove elements using <a class="reference internal" href="#xml.etree.ElementTree.Element.remove" title="xml.etree.ElementTree.Element.remove"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.remove()</span></code></a>.  Let’s say we want to
remove all countries with a rank higher than 50:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">country</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;country&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">rank</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">country</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;rank&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">text</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">rank</span> <span class="o">&gt;</span> <span class="mi">50</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">root</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">country</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Our XML now looks like this:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;data&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Liechtenstein&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>2<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2008<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>141100<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Austria&quot;</span> <span class="na">direction=</span><span class="s">&quot;E&quot;</span><span class="nt">/&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Switzerland&quot;</span> <span class="na">direction=</span><span class="s">&quot;W&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
    <span class="nt">&lt;country</span> <span class="na">name=</span><span class="s">&quot;Singapore&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;rank</span> <span class="na">updated=</span><span class="s">&quot;yes&quot;</span><span class="nt">&gt;</span>5<span class="nt">&lt;/rank&gt;</span>
        <span class="nt">&lt;year&gt;</span>2011<span class="nt">&lt;/year&gt;</span>
        <span class="nt">&lt;gdppc&gt;</span>59900<span class="nt">&lt;/gdppc&gt;</span>
        <span class="nt">&lt;neighbor</span> <span class="na">name=</span><span class="s">&quot;Malaysia&quot;</span> <span class="na">direction=</span><span class="s">&quot;N&quot;</span><span class="nt">/&gt;</span>
    <span class="nt">&lt;/country&gt;</span>
<span class="nt">&lt;/data&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="building-xml-documents">
<h3>19.7.1.5. Building XML documents<a class="headerlink" href="#building-xml-documents" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code class="xref py py-func docutils literal notranslate"><span class="pre">SubElement()</span></code></a> function also provides a convenient way to create new
sub-elements for a given element:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">Element</span><span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">SubElement</span><span class="p">(</span><span class="n">c</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ET</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">&lt;a&gt;&lt;b /&gt;&lt;c&gt;&lt;d /&gt;&lt;/c&gt;&lt;/a&gt;</span>
</pre></div>
</div>
</div>
<div class="section" id="parsing-xml-with-namespaces">
<h3>19.7.1.6. Parsing XML with Namespaces<a class="headerlink" href="#parsing-xml-with-namespaces" title="Permalink to this headline">¶</a></h3>
<p>If the XML input has <a class="reference external" href="https://en.wikipedia.org/wiki/XML_namespace">namespaces</a>, tags and attributes
with prefixes in the form <code class="docutils literal notranslate"><span class="pre">prefix:sometag</span></code> get expanded to
<code class="docutils literal notranslate"><span class="pre">{uri}sometag</span></code> where the <em>prefix</em> is replaced by the full <em>URI</em>.
Also, if there is a <a class="reference external" href="https://www.w3.org/TR/xml-names/#defaulting">default namespace</a>,
that full URI gets prepended to all of the non-prefixed tags.</p>
<p>Here is an XML example that incorporates two namespaces, one with the
prefix “fictional” and the other serving as the default namespace:</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="cp">&lt;?xml version=&quot;1.0&quot;?&gt;</span>
<span class="nt">&lt;actors</span> <span class="na">xmlns:fictional=</span><span class="s">&quot;http://characters.example.com&quot;</span>
        <span class="na">xmlns=</span><span class="s">&quot;http://people.example.com&quot;</span><span class="nt">&gt;</span>
    <span class="nt">&lt;actor&gt;</span>
        <span class="nt">&lt;name&gt;</span>John Cleese<span class="nt">&lt;/name&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Lancelot<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Archie Leach<span class="nt">&lt;/fictional:character&gt;</span>
    <span class="nt">&lt;/actor&gt;</span>
    <span class="nt">&lt;actor&gt;</span>
        <span class="nt">&lt;name&gt;</span>Eric Idle<span class="nt">&lt;/name&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Sir Robin<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Gunther<span class="nt">&lt;/fictional:character&gt;</span>
        <span class="nt">&lt;fictional:character&gt;</span>Commander Clement<span class="nt">&lt;/fictional:character&gt;</span>
    <span class="nt">&lt;/actor&gt;</span>
<span class="nt">&lt;/actors&gt;</span>
</pre></div>
</div>
<p>One way to search and explore this XML example is to manually add the
URI to every tag or attribute in the xpath of a
<a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code></a> or <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">findall()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">root</span> <span class="o">=</span> <span class="n">fromstring</span><span class="p">(</span><span class="n">xml_text</span><span class="p">)</span>
<span class="k">for</span> <span class="n">actor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;{http://people.example.com}actor&#39;</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">actor</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;{http://people.example.com}name&#39;</span><span class="p">)</span>
    <span class="nb">print</span> <span class="n">name</span><span class="o">.</span><span class="n">text</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">actor</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;{http://characters.example.com}character&#39;</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39; |--&gt;&#39;</span><span class="p">,</span> <span class="n">char</span><span class="o">.</span><span class="n">text</span>
</pre></div>
</div>
<p>A better way to search the namespaced XML example is to create a
dictionary with your own prefixes and use those in the search functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ns</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;real_person&#39;</span><span class="p">:</span> <span class="s1">&#39;http://people.example.com&#39;</span><span class="p">,</span>
      <span class="s1">&#39;role&#39;</span><span class="p">:</span> <span class="s1">&#39;http://characters.example.com&#39;</span><span class="p">}</span>

<span class="k">for</span> <span class="n">actor</span> <span class="ow">in</span> <span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;real_person:actor&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">actor</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;real_person:name&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">)</span>
    <span class="nb">print</span> <span class="n">name</span><span class="o">.</span><span class="n">text</span>
    <span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">actor</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s1">&#39;role:character&#39;</span><span class="p">,</span> <span class="n">ns</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39; |--&gt;&#39;</span><span class="p">,</span> <span class="n">char</span><span class="o">.</span><span class="n">text</span>
</pre></div>
</div>
<p>These two approaches both output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">John</span> <span class="n">Cleese</span>
 <span class="o">|--&gt;</span> <span class="n">Lancelot</span>
 <span class="o">|--&gt;</span> <span class="n">Archie</span> <span class="n">Leach</span>
<span class="n">Eric</span> <span class="n">Idle</span>
 <span class="o">|--&gt;</span> <span class="n">Sir</span> <span class="n">Robin</span>
 <span class="o">|--&gt;</span> <span class="n">Gunther</span>
 <span class="o">|--&gt;</span> <span class="n">Commander</span> <span class="n">Clement</span>
</pre></div>
</div>
</div>
<div class="section" id="additional-resources">
<h3>19.7.1.7. Additional resources<a class="headerlink" href="#additional-resources" title="Permalink to this headline">¶</a></h3>
<p>See <a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a> for tutorials and links to other
docs.</p>
</div>
</div>
<div class="section" id="xpath-support">
<span id="elementtree-xpath"></span><h2>19.7.2. XPath support<a class="headerlink" href="#xpath-support" title="Permalink to this headline">¶</a></h2>
<p>This module provides limited support for
<a class="reference external" href="https://www.w3.org/TR/xpath">XPath expressions</a> for locating elements in a
tree.  The goal is to support a small subset of the abbreviated syntax; a full
XPath engine is outside the scope of the module.</p>
<div class="section" id="example">
<h3>19.7.2.1. Example<a class="headerlink" href="#example" title="Permalink to this headline">¶</a></h3>
<p>Here’s an example that demonstrates some of the XPath capabilities of the
module.  We’ll be using the <code class="docutils literal notranslate"><span class="pre">countrydata</span></code> XML document from the
<a class="reference internal" href="#elementtree-parsing-xml"><span class="std std-ref">Parsing XML</span></a> section:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">as</span> <span class="nn">ET</span>

<span class="n">root</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">fromstring</span><span class="p">(</span><span class="n">countrydata</span><span class="p">)</span>

<span class="c1"># Top-level elements</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.&quot;</span><span class="p">)</span>

<span class="c1"># All &#39;neighbor&#39; grand-children of &#39;country&#39; children of the top-level</span>
<span class="c1"># elements</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;./country/neighbor&quot;</span><span class="p">)</span>

<span class="c1"># Nodes with name=&#39;Singapore&#39; that have a &#39;year&#39; child</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//year/..[@name=&#39;Singapore&#39;]&quot;</span><span class="p">)</span>

<span class="c1"># &#39;year&#39; nodes that are children of nodes with name=&#39;Singapore&#39;</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//*[@name=&#39;Singapore&#39;]/year&quot;</span><span class="p">)</span>

<span class="c1"># All &#39;neighbor&#39; nodes that are the second child of their parent</span>
<span class="n">root</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="s2">&quot;.//neighbor[2]&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="supported-xpath-syntax">
<h3>19.7.2.2. Supported XPath syntax<a class="headerlink" href="#supported-xpath-syntax" title="Permalink to this headline">¶</a></h3>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="70%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Syntax</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">tag</span></code></td>
<td>Selects all child elements with the given tag.
For example, <code class="docutils literal notranslate"><span class="pre">spam</span></code> selects all child elements
named <code class="docutils literal notranslate"><span class="pre">spam</span></code>, and <code class="docutils literal notranslate"><span class="pre">spam/egg</span></code> selects all
grandchildren named <code class="docutils literal notranslate"><span class="pre">egg</span></code> in all children named
<code class="docutils literal notranslate"><span class="pre">spam</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">*</span></code></td>
<td>Selects all child elements.  For example, <code class="docutils literal notranslate"><span class="pre">*/egg</span></code>
selects all grandchildren named <code class="docutils literal notranslate"><span class="pre">egg</span></code>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">.</span></code></td>
<td>Selects the current node.  This is mostly useful
at the beginning of the path, to indicate that it’s
a relative path.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">//</span></code></td>
<td>Selects all subelements, on all levels beneath the
current  element.  For example, <code class="docutils literal notranslate"><span class="pre">.//egg</span></code> selects
all <code class="docutils literal notranslate"><span class="pre">egg</span></code> elements in the entire tree.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">..</span></code></td>
<td>Selects the parent element.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">[&#64;attrib]</span></code></td>
<td>Selects all elements that have the given attribute.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">[&#64;attrib='value']</span></code></td>
<td>Selects all elements for which the given attribute
has the given value.  The value cannot contain
quotes.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">[tag]</span></code></td>
<td>Selects all elements that have a child named
<code class="docutils literal notranslate"><span class="pre">tag</span></code>.  Only immediate children are supported.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">[tag='text']</span></code></td>
<td>Selects all elements that have a child named
<code class="docutils literal notranslate"><span class="pre">tag</span></code> whose complete text content, including
descendants, equals the given <code class="docutils literal notranslate"><span class="pre">text</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">[position]</span></code></td>
<td>Selects all elements that are located at the given
position.  The position can be either an integer
(1 is the first position), the expression <code class="docutils literal notranslate"><span class="pre">last()</span></code>
(for the last position), or a position relative to
the last position (e.g. <code class="docutils literal notranslate"><span class="pre">last()-1</span></code>).</td>
</tr>
</tbody>
</table>
<p>Predicates (expressions within square brackets) must be preceded by a tag
name, an asterisk, or another predicate.  <code class="docutils literal notranslate"><span class="pre">position</span></code> predicates must be
preceded by a tag name.</p>
</div>
</div>
<div class="section" id="reference">
<h2>19.7.3. Reference<a class="headerlink" href="#reference" title="Permalink to this headline">¶</a></h2>
<div class="section" id="functions">
<span id="elementtree-functions"></span><h3>19.7.3.1. Functions<a class="headerlink" href="#functions" title="Permalink to this headline">¶</a></h3>
<dl class="function">
<dt id="xml.etree.ElementTree.Comment">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">Comment</code><span class="sig-paren">(</span><em>text=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Comment" title="Permalink to this definition">¶</a></dt>
<dd><p>Comment element factory.  This factory function creates a special element
that will be serialized as an XML comment by the standard serializer.  The
comment string can be either a bytestring or a Unicode string.  <em>text</em> is a
string containing the comment string.  Returns an element instance
representing a comment.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.dump">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">dump</code><span class="sig-paren">(</span><em>elem</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.dump" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes an element tree or element structure to sys.stdout.  This function
should be used for debugging only.</p>
<p>The exact output format is implementation dependent.  In this version, it’s
written as an ordinary XML file.</p>
<p><em>elem</em> is an element tree or an individual element.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.fromstring">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">fromstring</code><span class="sig-paren">(</span><em>text</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.fromstring" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML section from a string constant.  Same as <a class="reference internal" href="#xml.etree.ElementTree.XML" title="xml.etree.ElementTree.XML"><code class="xref py py-func docutils literal notranslate"><span class="pre">XML()</span></code></a>.  <em>text</em>
is a string containing XML data.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.fromstringlist">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">fromstringlist</code><span class="sig-paren">(</span><em>sequence</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.fromstringlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML document from a sequence of string fragments.  <em>sequence</em> is a
list or other sequence containing XML data fragments.  <em>parser</em> is an
optional parser instance.  If not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a>
parser is used.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.iselement">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">iselement</code><span class="sig-paren">(</span><em>element</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.iselement" title="Permalink to this definition">¶</a></dt>
<dd><p>Checks if an object appears to be a valid element object.  <em>element</em> is an
element instance.  Returns a true value if this is an element object.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.iterparse">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">iterparse</code><span class="sig-paren">(</span><em>source</em>, <em>events=None</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.iterparse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML section into an element tree incrementally, and reports what’s
going on to the user.  <em>source</em> is a filename or file object containing XML
data.  <em>events</em> is a list of events to report back.  If omitted, only “end”
events are reported.  <em>parser</em> is an optional parser instance.  If not
given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  <em>parser</em> is not
supported by <code class="docutils literal notranslate"><span class="pre">cElementTree</span></code>. Returns an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> providing
<code class="docutils literal notranslate"><span class="pre">(event,</span> <span class="pre">elem)</span></code> pairs.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p><a class="reference internal" href="#xml.etree.ElementTree.iterparse" title="xml.etree.ElementTree.iterparse"><code class="xref py py-func docutils literal notranslate"><span class="pre">iterparse()</span></code></a> only guarantees that it has seen the “&gt;”
character of a starting tag when it emits a “start” event, so the
attributes are defined, but the contents of the text and tail attributes
are undefined at that point.  The same applies to the element children;
they may or may not be present.</p>
<p class="last">If you need a fully populated element, look for “end” events instead.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.parse">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>source</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML section into an element tree.  <em>source</em> is a filename or file
object containing XML data.  <em>parser</em> is an optional parser instance.  If
not given, the standard <a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns an
<a class="reference internal" href="#xml.etree.ElementTree.ElementTree" title="xml.etree.ElementTree.ElementTree"><code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.ProcessingInstruction">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">ProcessingInstruction</code><span class="sig-paren">(</span><em>target</em>, <em>text=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ProcessingInstruction" title="Permalink to this definition">¶</a></dt>
<dd><p>PI element factory.  This factory function creates a special element that
will be serialized as an XML processing instruction.  <em>target</em> is a string
containing the PI target.  <em>text</em> is a string containing the PI contents, if
given.  Returns an element instance, representing a processing instruction.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.register_namespace">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">register_namespace</code><span class="sig-paren">(</span><em>prefix</em>, <em>uri</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.register_namespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Registers a namespace prefix.  The registry is global, and any existing
mapping for either the given prefix or the namespace URI will be removed.
<em>prefix</em> is a namespace prefix.  <em>uri</em> is a namespace uri.  Tags and
attributes in this namespace will be serialized with the given prefix, if at
all possible.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.SubElement">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">SubElement</code><span class="sig-paren">(</span><em>parent</em>, <em>tag</em>, <em>attrib={}</em>, <em>**extra</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.SubElement" title="Permalink to this definition">¶</a></dt>
<dd><p>Subelement factory.  This function creates an element instance, and appends
it to an existing element.</p>
<p>The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings.  <em>parent</em> is the parent element.  <em>tag</em> is
the subelement name.  <em>attrib</em> is an optional dictionary, containing element
attributes.  <em>extra</em> contains additional attributes, given as keyword
arguments.  Returns an element instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.tostring">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">tostring</code><span class="sig-paren">(</span><em>element</em>, <em>encoding=&quot;us-ascii&quot;</em>, <em>method=&quot;xml&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.tostring" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates a string representation of an XML element, including all
subelements.  <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.  <em>encoding</em> <a class="footnote-reference" href="#id5" id="id1">[1]</a> is
the output encoding (default is US-ASCII).  <em>method</em> is either <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).  Returns an encoded string
containing the XML data.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.tostringlist">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">tostringlist</code><span class="sig-paren">(</span><em>element</em>, <em>encoding=&quot;us-ascii&quot;</em>, <em>method=&quot;xml&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.tostringlist" title="Permalink to this definition">¶</a></dt>
<dd><p>Generates a string representation of an XML element, including all
subelements.  <em>element</em> is an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.  <em>encoding</em> <a class="footnote-reference" href="#id5" id="id2">[1]</a> is
the output encoding (default is US-ASCII).   <em>method</em> is either <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).  Returns a list of encoded
strings containing the XML data.  It does not guarantee any specific
sequence, except that <code class="docutils literal notranslate"><span class="pre">&quot;&quot;.join(tostringlist(element))</span> <span class="pre">==</span>
<span class="pre">tostring(element)</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.XML">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">XML</code><span class="sig-paren">(</span><em>text</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XML" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML section from a string constant.  This function can be used to
embed “XML literals” in Python code.  <em>text</em> is a string containing XML
data.  <em>parser</em> is an optional parser instance.  If not given, the standard
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="function">
<dt id="xml.etree.ElementTree.XMLID">
<code class="descclassname">xml.etree.ElementTree.</code><code class="descname">XMLID</code><span class="sig-paren">(</span><em>text</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLID" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses an XML section from a string constant, and also returns a dictionary
which maps from element id:s to elements.  <em>text</em> is a string containing XML
data.  <em>parser</em> is an optional parser instance.  If not given, the standard
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> parser is used.  Returns a tuple containing an
<a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance and a dictionary.</p>
</dd></dl>

</div>
<div class="section" id="element-objects">
<span id="elementtree-element-objects"></span><h3>19.7.3.2. Element Objects<a class="headerlink" href="#element-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.Element">
<em class="property">class </em><code class="descclassname">xml.etree.ElementTree.</code><code class="descname">Element</code><span class="sig-paren">(</span><em>tag</em>, <em>attrib={}</em>, <em>**extra</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element" title="Permalink to this definition">¶</a></dt>
<dd><p>Element class.  This class defines the Element interface, and provides a
reference implementation of this interface.</p>
<p>The element name, attribute names, and attribute values can be either
bytestrings or Unicode strings.  <em>tag</em> is the element name.  <em>attrib</em> is
an optional dictionary, containing element attributes.  <em>extra</em> contains
additional attributes, given as keyword arguments.</p>
<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.tag">
<code class="descname">tag</code><a class="headerlink" href="#xml.etree.ElementTree.Element.tag" title="Permalink to this definition">¶</a></dt>
<dd><p>A string identifying what kind of data this element represents (the
element type, in other words).</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.text">
<code class="descname">text</code><a class="headerlink" href="#xml.etree.ElementTree.Element.text" title="Permalink to this definition">¶</a></dt>
<dt id="xml.etree.ElementTree.Element.tail">
<code class="descname">tail</code><a class="headerlink" href="#xml.etree.ElementTree.Element.tail" title="Permalink to this definition">¶</a></dt>
<dd><p>These attributes can be used to hold additional data associated with
the element.  Their values are usually strings but may be any
application-specific object.  If the element is created from
an XML file, the <em>text</em> attribute holds either the text between
the element’s start tag and its first child or end tag, or <code class="docutils literal notranslate"><span class="pre">None</span></code>, and
the <em>tail</em> attribute holds either the text between the element’s
end tag and the next tag, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.  For the XML data</p>
<div class="highlight-xml notranslate"><div class="highlight"><pre><span></span><span class="nt">&lt;a&gt;&lt;b&gt;</span>1<span class="nt">&lt;c&gt;</span>2<span class="nt">&lt;d/&gt;</span>3<span class="nt">&lt;/c&gt;&lt;/b&gt;</span>4<span class="nt">&lt;/a&gt;</span>
</pre></div>
</div>
<p>the <em>a</em> element has <code class="docutils literal notranslate"><span class="pre">None</span></code> for both <em>text</em> and <em>tail</em> attributes,
the <em>b</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">&quot;1&quot;</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">&quot;4&quot;</span></code>,
the <em>c</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">&quot;2&quot;</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">None</span></code>,
and the <em>d</em> element has <em>text</em> <code class="docutils literal notranslate"><span class="pre">None</span></code> and <em>tail</em> <code class="docutils literal notranslate"><span class="pre">&quot;3&quot;</span></code>.</p>
<p>To collect the inner text of an element, see <a class="reference internal" href="#xml.etree.ElementTree.Element.itertext" title="xml.etree.ElementTree.Element.itertext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itertext()</span></code></a>, for
example <code class="docutils literal notranslate"><span class="pre">&quot;&quot;.join(element.itertext())</span></code>.</p>
<p>Applications may store arbitrary objects in these attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="xml.etree.ElementTree.Element.attrib">
<code class="descname">attrib</code><a class="headerlink" href="#xml.etree.ElementTree.Element.attrib" title="Permalink to this definition">¶</a></dt>
<dd><p>A dictionary containing the element’s attributes.  Note that while the
<em>attrib</em> value is always a real mutable Python dictionary, an ElementTree
implementation may choose to use another internal representation, and
create the dictionary only if someone asks for it.  To take advantage of
such implementations, use the dictionary methods below whenever possible.</p>
</dd></dl>

<p>The following dictionary-like methods work on the element attributes.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.Element.clear">
<code class="descname">clear</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.clear" title="Permalink to this definition">¶</a></dt>
<dd><p>Resets an element.  This function removes all subelements, clears all
attributes, and sets the text and tail attributes to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.get">
<code class="descname">get</code><span class="sig-paren">(</span><em>key</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.get" title="Permalink to this definition">¶</a></dt>
<dd><p>Gets the element attribute named <em>key</em>.</p>
<p>Returns the attribute value, or <em>default</em> if the attribute was not found.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.items">
<code class="descname">items</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.items" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the element attributes as a sequence of (name, value) pairs.  The
attributes are returned in an arbitrary order.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.keys">
<code class="descname">keys</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.keys" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the elements attribute names as a list.  The names are returned
in an arbitrary order.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.set">
<code class="descname">set</code><span class="sig-paren">(</span><em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.set" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the attribute <em>key</em> on the element to <em>value</em>.</p>
</dd></dl>

<p>The following methods work on the element’s children (subelements).</p>
<dl class="method">
<dt id="xml.etree.ElementTree.Element.append">
<code class="descname">append</code><span class="sig-paren">(</span><em>subelement</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.append" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds the element <em>subelement</em> to the end of this elements internal list
of subelements.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.extend">
<code class="descname">extend</code><span class="sig-paren">(</span><em>subelements</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.extend" title="Permalink to this definition">¶</a></dt>
<dd><p>Appends <em>subelements</em> from a sequence object with zero or more elements.
Raises <a class="reference internal" href="exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> if a subelement is not a valid object.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.find">
<code class="descname">find</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds the first subelement matching <em>match</em>.  <em>match</em> may be a tag name
or path.  Returns an element instance or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.findall">
<code class="descname">findall</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.findall" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds all matching subelements, by tag name or path.  Returns a list
containing all matching elements in document order.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.findtext">
<code class="descname">findtext</code><span class="sig-paren">(</span><em>match</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.findtext" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds text for the first subelement matching <em>match</em>.  <em>match</em> may be
a tag name or path.  Returns the text content of the first matching
element, or <em>default</em> if no element was found.  Note that if the matching
element has no text content an empty string is returned.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.getchildren">
<code class="descname">getchildren</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.getchildren" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use <code class="docutils literal notranslate"><span class="pre">list(elem)</span></code> or iteration.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.getiterator">
<code class="descname">getiterator</code><span class="sig-paren">(</span><em>tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.getiterator" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use method <a class="reference internal" href="#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.iter()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.insert">
<code class="descname">insert</code><span class="sig-paren">(</span><em>index</em>, <em>element</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.insert" title="Permalink to this definition">¶</a></dt>
<dd><p>Inserts a subelement at the given position in this element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.iter">
<code class="descname">iter</code><span class="sig-paren">(</span><em>tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.iter" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a tree <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> with the current element as the root.
The iterator iterates over this element and all elements below it, in
document (depth first) order.  If <em>tag</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code> or <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, only
elements whose tag equals <em>tag</em> are returned from the iterator.  If the
tree structure is modified during iteration, the result is undefined.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.iterfind">
<code class="descname">iterfind</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.iterfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds all matching subelements, by tag name or path.  Returns an iterable
yielding all matching elements in document order.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.itertext">
<code class="descname">itertext</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.itertext" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a text iterator.  The iterator loops over this element and all
subelements, in document order, and returns all inner text.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.makeelement">
<code class="descname">makeelement</code><span class="sig-paren">(</span><em>tag</em>, <em>attrib</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.makeelement" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates a new element object of the same type as this element.  Do not
call this method, use the <a class="reference internal" href="#xml.etree.ElementTree.SubElement" title="xml.etree.ElementTree.SubElement"><code class="xref py py-func docutils literal notranslate"><span class="pre">SubElement()</span></code></a> factory function instead.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.Element.remove">
<code class="descname">remove</code><span class="sig-paren">(</span><em>subelement</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.Element.remove" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes <em>subelement</em> from the element.  Unlike the find* methods this
method compares elements based on the instance identity, not on tag value
or contents.</p>
</dd></dl>

<p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> objects also support the following sequence type methods
for working with subelements: <a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a>.</p>
<p>Caution: Elements with no subelements will test as <code class="docutils literal notranslate"><span class="pre">False</span></code>.  This behavior
will change in future versions.  Use specific <code class="docutils literal notranslate"><span class="pre">len(elem)</span></code> or <code class="docutils literal notranslate"><span class="pre">elem</span> <span class="pre">is</span>
<span class="pre">None</span></code> test instead.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">element</span> <span class="o">=</span> <span class="n">root</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;foo&#39;</span><span class="p">)</span>

<span class="k">if</span> <span class="ow">not</span> <span class="n">element</span><span class="p">:</span>  <span class="c1"># careful!</span>
    <span class="nb">print</span> <span class="s2">&quot;element not found, or element has no subelements&quot;</span>

<span class="k">if</span> <span class="n">element</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;element not found&quot;</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="elementtree-objects">
<span id="elementtree-elementtree-objects"></span><h3>19.7.3.3. ElementTree Objects<a class="headerlink" href="#elementtree-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.ElementTree">
<em class="property">class </em><code class="descclassname">xml.etree.ElementTree.</code><code class="descname">ElementTree</code><span class="sig-paren">(</span><em>element=None</em>, <em>file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree" title="Permalink to this definition">¶</a></dt>
<dd><p>ElementTree wrapper class.  This class represents an entire element
hierarchy, and adds some extra support for serialization to and from
standard XML.</p>
<p><em>element</em> is the root element.  The tree is initialized with the contents
of the XML <em>file</em> if given.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree._setroot">
<code class="descname">_setroot</code><span class="sig-paren">(</span><em>element</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree._setroot" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces the root element for this tree.  This discards the current
contents of the tree, and replaces it with the given element.  Use with
care.  <em>element</em> is an element instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.find">
<code class="descname">find</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.find" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.find" title="xml.etree.ElementTree.Element.find"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.find()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.findall">
<code class="descname">findall</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.findall" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findall" title="xml.etree.ElementTree.Element.findall"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findall()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.findtext">
<code class="descname">findtext</code><span class="sig-paren">(</span><em>match</em>, <em>default=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.findtext" title="Permalink to this definition">¶</a></dt>
<dd><p>Same as <a class="reference internal" href="#xml.etree.ElementTree.Element.findtext" title="xml.etree.ElementTree.Element.findtext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.findtext()</span></code></a>, starting at the root of the tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.getiterator">
<code class="descname">getiterator</code><span class="sig-paren">(</span><em>tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.getiterator" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Use method <a class="reference internal" href="#xml.etree.ElementTree.ElementTree.iter" title="xml.etree.ElementTree.ElementTree.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.iter()</span></code></a> instead.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.getroot">
<code class="descname">getroot</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.getroot" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the root element for this tree.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.iter">
<code class="descname">iter</code><span class="sig-paren">(</span><em>tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.iter" title="Permalink to this definition">¶</a></dt>
<dd><p>Creates and returns a tree iterator for the root element.  The iterator
loops over all elements in this tree, in section order.  <em>tag</em> is the tag
to look for (default is to return all elements).</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.iterfind">
<code class="descname">iterfind</code><span class="sig-paren">(</span><em>match</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.iterfind" title="Permalink to this definition">¶</a></dt>
<dd><p>Finds all matching subelements, by tag name or path.  Same as
getroot().iterfind(match). Returns an iterable yielding all matching
elements in document order.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.parse">
<code class="descname">parse</code><span class="sig-paren">(</span><em>source</em>, <em>parser=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Loads an external XML section into this element tree.  <em>source</em> is a file
name or file object.  <em>parser</em> is an optional parser instance.  If not
given, the standard XMLParser parser is used.  Returns the section
root element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.ElementTree.write">
<code class="descname">write</code><span class="sig-paren">(</span><em>file</em>, <em>encoding=&quot;us-ascii&quot;</em>, <em>xml_declaration=None</em>, <em>default_namespace=None</em>, <em>method=&quot;xml&quot;</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.ElementTree.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Writes the element tree to a file, as XML.  <em>file</em> is a file name, or a
file object opened for writing.  <em>encoding</em> <a class="footnote-reference" href="#id5" id="id3">[1]</a> is the output encoding
(default is US-ASCII).  <em>xml_declaration</em> controls if an XML declaration
should be added to the file.  Use <code class="docutils literal notranslate"><span class="pre">False</span></code> for never, <code class="docutils literal notranslate"><span class="pre">True</span></code> for always, <code class="docutils literal notranslate"><span class="pre">None</span></code>
for only if not US-ASCII or UTF-8 (default is <code class="docutils literal notranslate"><span class="pre">None</span></code>).  <em>default_namespace</em>
sets the default XML namespace (for “xmlns”).  <em>method</em> is either
<code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;html&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;text&quot;</span></code> (default is <code class="docutils literal notranslate"><span class="pre">&quot;xml&quot;</span></code>).  Returns an
encoded string.</p>
</dd></dl>

</dd></dl>

<p>This is the XML file that is going to be manipulated:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">html</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">head</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">title</span><span class="o">&gt;</span><span class="n">Example</span> <span class="n">page</span><span class="o">&lt;/</span><span class="n">title</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="n">head</span><span class="o">&gt;</span>
    <span class="o">&lt;</span><span class="n">body</span><span class="o">&gt;</span>
        <span class="o">&lt;</span><span class="n">p</span><span class="o">&gt;</span><span class="n">Moved</span> <span class="n">to</span> <span class="o">&lt;</span><span class="n">a</span> <span class="n">href</span><span class="o">=</span><span class="s2">&quot;http://example.org/&quot;</span><span class="o">&gt;</span><span class="n">example</span><span class="o">.</span><span class="n">org</span><span class="o">&lt;/</span><span class="n">a</span><span class="o">&gt;</span>
        <span class="ow">or</span> <span class="o">&lt;</span><span class="n">a</span> <span class="n">href</span><span class="o">=</span><span class="s2">&quot;http://example.com/&quot;</span><span class="o">&gt;</span><span class="n">example</span><span class="o">.</span><span class="n">com</span><span class="o">&lt;/</span><span class="n">a</span><span class="o">&gt;.&lt;/</span><span class="n">p</span><span class="o">&gt;</span>
    <span class="o">&lt;/</span><span class="n">body</span><span class="o">&gt;</span>
<span class="o">&lt;/</span><span class="n">html</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>Example of changing the attribute “target” of every link in first paragraph:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">import</span> <span class="n">ElementTree</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span> <span class="o">=</span> <span class="n">ElementTree</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;index.xhtml&quot;</span><span class="p">)</span>
<span class="go">&lt;Element &#39;html&#39; at 0xb77e6fac&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span> <span class="o">=</span> <span class="n">tree</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s2">&quot;body/p&quot;</span><span class="p">)</span>     <span class="c1"># Finds first occurrence of tag p in body</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">p</span>
<span class="go">&lt;Element &#39;p&#39; at 0xb77ec26c&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">links</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">p</span><span class="o">.</span><span class="n">iter</span><span class="p">(</span><span class="s2">&quot;a&quot;</span><span class="p">))</span>   <span class="c1"># Returns list of all links</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">links</span>
<span class="go">[&lt;Element &#39;a&#39; at 0xb77ec2ac&gt;, &lt;Element &#39;a&#39; at 0xb77ec1cc&gt;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span>             <span class="c1"># Iterates through all found links</span>
<span class="gp">... </span>    <span class="n">i</span><span class="o">.</span><span class="n">attrib</span><span class="p">[</span><span class="s2">&quot;target&quot;</span><span class="p">]</span> <span class="o">=</span> <span class="s2">&quot;blank&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">&quot;output.xhtml&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="qname-objects">
<span id="elementtree-qname-objects"></span><h3>19.7.3.4. QName Objects<a class="headerlink" href="#qname-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.QName">
<em class="property">class </em><code class="descclassname">xml.etree.ElementTree.</code><code class="descname">QName</code><span class="sig-paren">(</span><em>text_or_uri</em>, <em>tag=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.QName" title="Permalink to this definition">¶</a></dt>
<dd><p>QName wrapper.  This can be used to wrap a QName attribute value, in order
to get proper namespace handling on output.  <em>text_or_uri</em> is a string
containing the QName value, in the form {uri}local, or, if the tag argument
is given, the URI part of a QName.  If <em>tag</em> is given, the first argument is
interpreted as a URI, and this argument is interpreted as a local name.
<a class="reference internal" href="#xml.etree.ElementTree.QName" title="xml.etree.ElementTree.QName"><code class="xref py py-class docutils literal notranslate"><span class="pre">QName</span></code></a> instances are opaque.</p>
</dd></dl>

</div>
<div class="section" id="treebuilder-objects">
<span id="elementtree-treebuilder-objects"></span><h3>19.7.3.5. TreeBuilder Objects<a class="headerlink" href="#treebuilder-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.TreeBuilder">
<em class="property">class </em><code class="descclassname">xml.etree.ElementTree.</code><code class="descname">TreeBuilder</code><span class="sig-paren">(</span><em>element_factory=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder" title="Permalink to this definition">¶</a></dt>
<dd><p>Generic element structure builder.  This builder converts a sequence of
start, data, and end method calls to a well-formed element structure.  You
can use this class to build an element structure using a custom XML parser,
or a parser for some other XML-like format.  The <em>element_factory</em> is called
to create new <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instances when given.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Flushes the builder buffers, and returns the toplevel document
element.  Returns an <a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> instance.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.data">
<code class="descname">data</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.data" title="Permalink to this definition">¶</a></dt>
<dd><p>Adds text to the current element.  <em>data</em> is a string.  This should be
either a bytestring, or a Unicode string.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.end">
<code class="descname">end</code><span class="sig-paren">(</span><em>tag</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.end" title="Permalink to this definition">¶</a></dt>
<dd><p>Closes the current element.  <em>tag</em> is the element name.  Returns the
closed element.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.start">
<code class="descname">start</code><span class="sig-paren">(</span><em>tag</em>, <em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.start" title="Permalink to this definition">¶</a></dt>
<dd><p>Opens a new element.  <em>tag</em> is the element name.  <em>attrs</em> is a dictionary
containing element attributes.  Returns the opened element.</p>
</dd></dl>

<p>In addition, a custom <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> object can provide the
following method:</p>
<dl class="method">
<dt id="xml.etree.ElementTree.TreeBuilder.doctype">
<code class="descname">doctype</code><span class="sig-paren">(</span><em>name</em>, <em>pubid</em>, <em>system</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.TreeBuilder.doctype" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles a doctype declaration.  <em>name</em> is the doctype name.  <em>pubid</em> is
the public identifier.  <em>system</em> is the system identifier.  This method
does not exist on the default <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder" title="xml.etree.ElementTree.TreeBuilder"><code class="xref py py-class docutils literal notranslate"><span class="pre">TreeBuilder</span></code></a> class.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
</dd></dl>

</dd></dl>

</div>
<div class="section" id="xmlparser-objects">
<span id="elementtree-xmlparser-objects"></span><h3>19.7.3.6. XMLParser Objects<a class="headerlink" href="#xmlparser-objects" title="Permalink to this headline">¶</a></h3>
<dl class="class">
<dt id="xml.etree.ElementTree.XMLParser">
<em class="property">class </em><code class="descclassname">xml.etree.ElementTree.</code><code class="descname">XMLParser</code><span class="sig-paren">(</span><em>html=0</em>, <em>target=None</em>, <em>encoding=None</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser" title="Permalink to this definition">¶</a></dt>
<dd><p><a class="reference internal" href="#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> structure builder for XML source data, based on the expat
parser.  <em>html</em> are predefined HTML entities.  This flag is not supported by
the current implementation.  <em>target</em> is the target object.  If omitted, the
builder uses an instance of the standard TreeBuilder class.  <em>encoding</em> <a class="footnote-reference" href="#id5" id="id4">[1]</a>
is optional.  If given, the value overrides the encoding specified in the
XML file.</p>
<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.close">
<code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Finishes feeding data to the parser.  Returns an element structure.</p>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.doctype">
<code class="descname">doctype</code><span class="sig-paren">(</span><em>name</em>, <em>pubid</em>, <em>system</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.doctype" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.7: </span>Define the <a class="reference internal" href="#xml.etree.ElementTree.TreeBuilder.doctype" title="xml.etree.ElementTree.TreeBuilder.doctype"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TreeBuilder.doctype()</span></code></a> method on a custom TreeBuilder
target.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.etree.ElementTree.XMLParser.feed">
<code class="descname">feed</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.etree.ElementTree.XMLParser.feed" title="Permalink to this definition">¶</a></dt>
<dd><p>Feeds data to the parser.  <em>data</em> is encoded data.</p>
</dd></dl>

</dd></dl>

<p><a class="reference internal" href="#xml.etree.ElementTree.XMLParser.feed" title="xml.etree.ElementTree.XMLParser.feed"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLParser.feed()</span></code></a> calls <em>target</em>’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> method
for each opening tag, its <code class="xref py py-meth docutils literal notranslate"><span class="pre">end()</span></code> method for each closing tag,
and data is processed by method <code class="xref py py-meth docutils literal notranslate"><span class="pre">data()</span></code>.  <a class="reference internal" href="#xml.etree.ElementTree.XMLParser.close" title="xml.etree.ElementTree.XMLParser.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLParser.close()</span></code></a>
calls <em>target</em>’s method <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>.
<a class="reference internal" href="#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> can be used not only for building a tree structure.
This is an example of counting the maximum depth of an XML file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">xml.etree.ElementTree</span> <span class="k">import</span> <span class="n">XMLParser</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MaxDepth</span><span class="p">:</span>                     <span class="c1"># The target object of the parser</span>
<span class="gp">... </span>    <span class="n">maxDepth</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>    <span class="n">depth</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">start</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">,</span> <span class="n">attrib</span><span class="p">):</span>   <span class="c1"># Called for each opening tag.</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">&gt;</span> <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span><span class="p">:</span>
<span class="gp">... </span>            <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">depth</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">end</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span>             <span class="c1"># Called for each closing tag.</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">depth</span> <span class="o">-=</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">data</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">pass</span>            <span class="c1"># We do not need to do anything with data.</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">close</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>    <span class="c1"># Called when all data has been parsed.</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">maxDepth</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">target</span> <span class="o">=</span> <span class="n">MaxDepth</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">XMLParser</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">target</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">exampleXml</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">&lt;a&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;b&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;/b&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;b&gt;</span>
<span class="gp">... </span><span class="s2">    &lt;c&gt;</span>
<span class="gp">... </span><span class="s2">      &lt;d&gt;</span>
<span class="gp">... </span><span class="s2">      &lt;/d&gt;</span>
<span class="gp">... </span><span class="s2">    &lt;/c&gt;</span>
<span class="gp">... </span><span class="s2">  &lt;/b&gt;</span>
<span class="gp">... </span><span class="s2">&lt;/a&gt;&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">feed</span><span class="p">(</span><span class="n">exampleXml</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="go">4</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label">[1]</td><td><em>(<a class="fn-backref" href="#id1">1</a>, <a class="fn-backref" href="#id2">2</a>, <a class="fn-backref" href="#id3">3</a>, <a class="fn-backref" href="#id4">4</a>)</em> The encoding string included in XML output should conform to the
appropriate standards.  For example, “UTF-8” is valid, but “UTF8” is
not.  See <a class="reference external" href="https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl">https://www.w3.org/TR/2006/REC-xml11-20060816/#NT-EncodingDecl</a>
and <a class="reference external" href="https://www.iana.org/assignments/character-sets/character-sets.xhtml">https://www.iana.org/assignments/character-sets/character-sets.xhtml</a>.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a><ul>
<li><a class="reference internal" href="#tutorial">19.7.1. Tutorial</a><ul>
<li><a class="reference internal" href="#xml-tree-and-elements">19.7.1.1. XML tree and elements</a></li>
<li><a class="reference internal" href="#parsing-xml">19.7.1.2. Parsing XML</a></li>
<li><a class="reference internal" href="#finding-interesting-elements">19.7.1.3. Finding interesting elements</a></li>
<li><a class="reference internal" href="#modifying-an-xml-file">19.7.1.4. Modifying an XML File</a></li>
<li><a class="reference internal" href="#building-xml-documents">19.7.1.5. Building XML documents</a></li>
<li><a class="reference internal" href="#parsing-xml-with-namespaces">19.7.1.6. Parsing XML with Namespaces</a></li>
<li><a class="reference internal" href="#additional-resources">19.7.1.7. Additional resources</a></li>
</ul>
</li>
<li><a class="reference internal" href="#xpath-support">19.7.2. XPath support</a><ul>
<li><a class="reference internal" href="#example">19.7.2.1. Example</a></li>
<li><a class="reference internal" href="#supported-xpath-syntax">19.7.2.2. Supported XPath syntax</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reference">19.7.3. Reference</a><ul>
<li><a class="reference internal" href="#functions">19.7.3.1. Functions</a></li>
<li><a class="reference internal" href="#element-objects">19.7.3.2. Element Objects</a></li>
<li><a class="reference internal" href="#elementtree-objects">19.7.3.3. ElementTree Objects</a></li>
<li><a class="reference internal" href="#qname-objects">19.7.3.4. QName Objects</a></li>
<li><a class="reference internal" href="#treebuilder-objects">19.7.3.5. TreeBuilder Objects</a></li>
<li><a class="reference internal" href="#xmlparser-objects">19.7.3.6. XMLParser Objects</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.html"
                        title="previous chapter">19.5. XML Processing Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.dom.html"
                        title="next chapter">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.etree.elementtree.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.dom.html" title="19.8. xml.dom — The Document Object Model API"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.html" title="19.5. XML Processing Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\1:WFWFhtml/library/xml.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.5. XML Processing Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.7. xml.etree.ElementTree — The ElementTree XML API" href="xml.etree.elementtree.html" />
    <link rel="prev" title="19.3. htmllib — A parser for HTML documents" href="htmllib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.etree.elementtree.html" title="19.7. xml.etree.ElementTree — The ElementTree XML API"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="htmllib.html" title="19.3. htmllib — A parser for HTML documents"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml">
<span id="xml-processing-modules"></span><span id="xml"></span><h1>19.5. XML Processing Modules<a class="headerlink" href="#module-xml" title="Permalink to this headline">¶</a></h1>
<p>Python’s interfaces for processing XML are grouped in the <code class="docutils literal notranslate"><span class="pre">xml</span></code> package.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The XML modules are not secure against erroneous or maliciously
constructed data.  If you need to parse untrusted or unauthenticated data see
<a class="reference internal" href="#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<p>It is important to note that modules in the <a class="reference internal" href="#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package require that
there be at least one SAX-compliant XML parser available. The Expat parser is
included with Python, so the <a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a> module will always be
available.</p>
<p>The documentation for the <a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> and <a class="reference internal" href="xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> packages are the
definition of the Python bindings for the DOM and SAX interfaces.</p>
<p>The XML handling submodules are:</p>
<ul class="simple">
<li><a class="reference internal" href="xml.etree.elementtree.html#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a>: the ElementTree API, a simple and lightweight
XML processor</li>
</ul>
<ul class="simple">
<li><a class="reference internal" href="xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a>: the DOM API definition</li>
<li><a class="reference internal" href="xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>: a minimal DOM implementation</li>
<li><a class="reference internal" href="xml.dom.pulldom.html#module-xml.dom.pulldom" title="xml.dom.pulldom: Support for building partial DOM trees from SAX events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code></a>: support for building partial DOM trees</li>
</ul>
<ul class="simple">
<li><a class="reference internal" href="xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a>: SAX2 base classes and convenience functions</li>
<li><a class="reference internal" href="pyexpat.html#module-xml.parsers.expat" title="xml.parsers.expat: An interface to the Expat non-validating XML parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code></a>: the Expat parser binding</li>
</ul>
</div>
<div class="section" id="xml-vulnerabilities">
<span id="id1"></span><h1>19.6. XML vulnerabilities<a class="headerlink" href="#xml-vulnerabilities" title="Permalink to this headline">¶</a></h1>
<p>The XML processing modules are not secure against maliciously constructed data.
An attacker can abuse vulnerabilities for e.g. denial of service attacks, to
access local files, to generate network connections to other machines, or
to or circumvent firewalls. The attacks on XML abuse unfamiliar features
like inline <a class="reference external" href="https://en.wikipedia.org/wiki/Document_type_definition">DTD</a> (document type definition) with entities.</p>
<p>The following table gives an overview of the known attacks and if the various
modules are vulnerable to them.</p>
<table border="1" class="docutils">
<colgroup>
<col width="26%" />
<col width="15%" />
<col width="16%" />
<col width="15%" />
<col width="15%" />
<col width="15%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">kind</th>
<th class="head">sax</th>
<th class="head">etree</th>
<th class="head">minidom</th>
<th class="head">pulldom</th>
<th class="head">xmlrpc</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>billion laughs</td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
</tr>
<tr class="row-odd"><td>quadratic blowup</td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
<td><strong>Vulnerable</strong></td>
</tr>
<tr class="row-even"><td>external entity expansion</td>
<td><strong>Vulnerable</strong></td>
<td>Safe    (1)</td>
<td>Safe    (2)</td>
<td><strong>Vulnerable</strong></td>
<td>Safe    (3)</td>
</tr>
<tr class="row-odd"><td><a class="reference external" href="https://en.wikipedia.org/wiki/Document_type_definition">DTD</a> retrieval</td>
<td><strong>Vulnerable</strong></td>
<td>Safe</td>
<td>Safe</td>
<td><strong>Vulnerable</strong></td>
<td>Safe</td>
</tr>
<tr class="row-even"><td>decompression bomb</td>
<td>Safe</td>
<td>Safe</td>
<td>Safe</td>
<td>Safe</td>
<td><strong>Vulnerable</strong></td>
</tr>
</tbody>
</table>
<ol class="arabic simple">
<li><a class="reference internal" href="xml.etree.elementtree.html#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a> doesn’t expand external entities and raises a
ParserError when an entity occurs.</li>
<li><a class="reference internal" href="xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> doesn’t expand external entities and simply returns
the unexpanded entity verbatim.</li>
<li><a class="reference internal" href="xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> doesn’t expand external entities and omits them.</li>
</ol>
<dl class="docutils">
<dt>billion laughs / exponential entity expansion</dt>
<dd>The <a class="reference external" href="https://en.wikipedia.org/wiki/Billion_laughs">Billion Laughs</a> attack – also known as exponential entity expansion –
uses multiple levels of nested entities. Each entity refers to another entity
several times, the final entity definition contains a small string. Eventually
the small string is expanded to several gigabytes. The exponential expansion
consumes lots of CPU time, too.</dd>
<dt>quadratic blowup entity expansion</dt>
<dd>A quadratic blowup attack is similar to a <a class="reference external" href="https://en.wikipedia.org/wiki/Billion_laughs">Billion Laughs</a> attack; it abuses
entity expansion, too. Instead of nested entities it repeats one large entity
with a couple of thousand chars over and over again. The attack isn’t as
efficient as the exponential case but it avoids triggering countermeasures of
parsers against heavily nested entities.</dd>
<dt>external entity expansion</dt>
<dd>Entity declarations can contain more than just text for replacement. They can
also point to external resources by public identifiers or system identifiers.
System identifiers are standard URIs or can refer to local files. The XML
parser retrieves the resource with e.g. HTTP or FTP requests and embeds the
content into the XML document.</dd>
<dt><a class="reference external" href="https://en.wikipedia.org/wiki/Document_type_definition">DTD</a> retrieval</dt>
<dd>Some XML libraries like Python’s <a class="reference internal" href="xml.dom.pulldom.html#module-xml.dom.pulldom" title="xml.dom.pulldom: Support for building partial DOM trees from SAX events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code></a> retrieve document type
definitions from remote or local locations. The feature has similar
implications as the external entity expansion issue.</dd>
<dt>decompression bomb</dt>
<dd>The issue of decompression bombs (aka <a class="reference external" href="https://en.wikipedia.org/wiki/Zip_bomb">ZIP bomb</a>) apply to all XML libraries
that can parse compressed XML stream like gzipped HTTP streams or LZMA-ed
files. For an attacker it can reduce the amount of transmitted data by three
magnitudes or more.</dd>
</dl>
<p>The documentation of <a class="reference external" href="https://pypi.org/project/defusedxml/">defusedxml</a> on PyPI has further information about
all known attack vectors with examples and references.</p>
<div class="section" id="defused-packages">
<h2>19.6.1. defused packages<a class="headerlink" href="#defused-packages" title="Permalink to this headline">¶</a></h2>
<p>These external packages are recommended for any code that parses
untrusted XML data.</p>
<p><a class="reference external" href="https://pypi.org/project/defusedxml/">defusedxml</a> is a pure Python package with modified subclasses of all stdlib
XML parsers that prevent any potentially malicious operation. The
package also ships with example exploits and extended documentation on more
XML exploits like xpath injection.</p>
<p><a class="reference external" href="https://pypi.org/project/defusedexpat/">defusedexpat</a> provides a modified libexpat and patched replacement
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> extension module with countermeasures against entity expansion
DoS attacks. Defusedexpat still allows a sane and configurable amount of entity
expansions. The modifications will be merged into future releases of Python.</p>
<p>The workarounds and modifications are not included in patch releases as they
break backward compatibility. After all inline DTD and entity expansion are
well-defined XML features.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.5. XML Processing Modules</a></li>
<li><a class="reference internal" href="#xml-vulnerabilities">19.6. XML vulnerabilities</a><ul>
<li><a class="reference internal" href="#defused-packages">19.6.1. defused packages</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="htmllib.html"
                        title="previous chapter">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.etree.elementtree.html"
                        title="next chapter">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.etree.elementtree.html" title="19.7. xml.etree.ElementTree — The ElementTree XML API"
             >next</a> |</li>
        <li class="right" >
          <a href="htmllib.html" title="19.3. htmllib — A parser for HTML documents"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6������!html/library/xml.sax.handler.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.12. xml.sax.handler — Base classes for SAX handlers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.13. xml.sax.saxutils — SAX Utilities" href="xml.sax.utils.html" />
    <link rel="prev" title="19.11. xml.sax — Support for SAX2 parsers" href="xml.sax.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.sax.handler.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.utils.html" title="19.13. xml.sax.saxutils — SAX Utilities"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.sax.html" title="19.11. xml.sax — Support for SAX2 parsers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.sax.handler">
<span id="xml-sax-handler-base-classes-for-sax-handlers"></span><h1>19.12. <a class="reference internal" href="#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a> — Base classes for SAX handlers<a class="headerlink" href="#module-xml.sax.handler" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>The SAX API defines four kinds of handlers: content handlers, DTD handlers,
error handlers, and entity resolvers. Applications normally only need to
implement those interfaces whose events they are interested in; they can
implement the interfaces in a single object or in multiple objects. Handler
implementations should inherit from the base classes provided in the module
<a class="reference internal" href="#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a>, so that all methods get default implementations.</p>
<dl class="class">
<dt id="xml.sax.handler.ContentHandler">
<em class="property">class </em><code class="descclassname">xml.sax.handler.</code><code class="descname">ContentHandler</code><a class="headerlink" href="#xml.sax.handler.ContentHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>This is the main callback interface in SAX, and the one most important to
applications. The order of events in this interface mirrors the order of the
information in the document.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.handler.DTDHandler">
<em class="property">class </em><code class="descclassname">xml.sax.handler.</code><code class="descname">DTDHandler</code><a class="headerlink" href="#xml.sax.handler.DTDHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle DTD events.</p>
<p>This interface specifies only those DTD events required for basic parsing
(unparsed entities and attributes).</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.handler.EntityResolver">
<em class="property">class </em><code class="descclassname">xml.sax.handler.</code><code class="descname">EntityResolver</code><a class="headerlink" href="#xml.sax.handler.EntityResolver" title="Permalink to this definition">¶</a></dt>
<dd><p>Basic interface for resolving entities. If you create an object implementing
this interface, then register the object with your Parser, the parser will call
the method in your object to resolve all external entities.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.handler.ErrorHandler">
<em class="property">class </em><code class="descclassname">xml.sax.handler.</code><code class="descname">ErrorHandler</code><a class="headerlink" href="#xml.sax.handler.ErrorHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Interface used by the parser to present error and warning messages to the
application.  The methods of this object control whether errors are immediately
converted to exceptions or are handled in some other way.</p>
</dd></dl>

<p>In addition to these classes, <a class="reference internal" href="#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a> provides symbolic constants
for the feature and property names.</p>
<dl class="data">
<dt id="xml.sax.handler.feature_namespaces">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_namespaces</code><a class="headerlink" href="#xml.sax.handler.feature_namespaces" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/namespaces&quot;</span></code></div>
<div class="line">true: Perform Namespace processing.</div>
<div class="line">false: Optionally do not perform Namespace processing (implies
namespace-prefixes; default).</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.feature_namespace_prefixes">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_namespace_prefixes</code><a class="headerlink" href="#xml.sax.handler.feature_namespace_prefixes" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/namespace-prefixes&quot;</span></code></div>
<div class="line">true: Report the original prefixed names and attributes used for Namespace
declarations.</div>
<div class="line">false: Do not report attributes used for Namespace declarations, and
optionally do not report original prefixed names (default).</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.feature_string_interning">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_string_interning</code><a class="headerlink" href="#xml.sax.handler.feature_string_interning" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/string-interning&quot;</span></code></div>
<div class="line">true: All element names, prefixes, attribute names, Namespace URIs, and
local names are interned using the built-in intern function.</div>
<div class="line">false: Names are not necessarily interned, although they may be (default).</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.feature_validation">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_validation</code><a class="headerlink" href="#xml.sax.handler.feature_validation" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/validation&quot;</span></code></div>
<div class="line">true: Report all validation errors (implies external-general-entities and
external-parameter-entities).</div>
<div class="line">false: Do not report validation errors.</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.feature_external_ges">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_external_ges</code><a class="headerlink" href="#xml.sax.handler.feature_external_ges" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/external-general-entities&quot;</span></code></div>
<div class="line">true: Include all external general (text) entities.</div>
<div class="line">false: Do not include external general entities.</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.feature_external_pes">
<code class="descclassname">xml.sax.handler.</code><code class="descname">feature_external_pes</code><a class="headerlink" href="#xml.sax.handler.feature_external_pes" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/features/external-parameter-entities&quot;</span></code></div>
<div class="line">true: Include all external parameter entities, including the external DTD
subset.</div>
<div class="line">false: Do not include any external parameter entities, even the external
DTD subset.</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.all_features">
<code class="descclassname">xml.sax.handler.</code><code class="descname">all_features</code><a class="headerlink" href="#xml.sax.handler.all_features" title="Permalink to this definition">¶</a></dt>
<dd><p>List of all features.</p>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.property_lexical_handler">
<code class="descclassname">xml.sax.handler.</code><code class="descname">property_lexical_handler</code><a class="headerlink" href="#xml.sax.handler.property_lexical_handler" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/properties/lexical-handler&quot;</span></code></div>
<div class="line">data type: xml.sax.sax2lib.LexicalHandler (not supported in Python 2)</div>
<div class="line">description: An optional extension handler for lexical events like
comments.</div>
<div class="line">access: read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.property_declaration_handler">
<code class="descclassname">xml.sax.handler.</code><code class="descname">property_declaration_handler</code><a class="headerlink" href="#xml.sax.handler.property_declaration_handler" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/properties/declaration-handler&quot;</span></code></div>
<div class="line">data type: xml.sax.sax2lib.DeclHandler (not supported in Python 2)</div>
<div class="line">description: An optional extension handler for DTD-related events other
than notations and unparsed entities.</div>
<div class="line">access: read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.property_dom_node">
<code class="descclassname">xml.sax.handler.</code><code class="descname">property_dom_node</code><a class="headerlink" href="#xml.sax.handler.property_dom_node" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/properties/dom-node&quot;</span></code></div>
<div class="line">data type: org.w3c.dom.Node (not supported in Python 2)</div>
<div class="line">description: When parsing, the current DOM node being visited if this is
a DOM iterator; when not parsing, the root DOM node for iteration.</div>
<div class="line">access: (parsing) read-only; (not parsing) read/write</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.property_xml_string">
<code class="descclassname">xml.sax.handler.</code><code class="descname">property_xml_string</code><a class="headerlink" href="#xml.sax.handler.property_xml_string" title="Permalink to this definition">¶</a></dt>
<dd><div class="line-block">
<div class="line">value: <code class="docutils literal notranslate"><span class="pre">&quot;http://xml.org/sax/properties/xml-string&quot;</span></code></div>
<div class="line">data type: String</div>
<div class="line">description: The literal string of characters that was the source for the
current event.</div>
<div class="line">access: read-only</div>
</div>
</dd></dl>

<dl class="data">
<dt id="xml.sax.handler.all_properties">
<code class="descclassname">xml.sax.handler.</code><code class="descname">all_properties</code><a class="headerlink" href="#xml.sax.handler.all_properties" title="Permalink to this definition">¶</a></dt>
<dd><p>List of all known property names.</p>
</dd></dl>

<div class="section" id="contenthandler-objects">
<span id="content-handler-objects"></span><h2>19.12.1. ContentHandler Objects<a class="headerlink" href="#contenthandler-objects" title="Permalink to this headline">¶</a></h2>
<p>Users are expected to subclass <a class="reference internal" href="#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a> to support their
application.  The following methods are called by the parser on the appropriate
events in the input document:</p>
<dl class="method">
<dt id="xml.sax.handler.ContentHandler.setDocumentLocator">
<code class="descclassname">ContentHandler.</code><code class="descname">setDocumentLocator</code><span class="sig-paren">(</span><em>locator</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.setDocumentLocator" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by the parser to give the application a locator for locating the origin
of document events.</p>
<p>SAX parsers are strongly encouraged (though not absolutely required) to supply a
locator: if it does so, it must supply the locator to the application by
invoking this method before invoking any of the other methods in the
DocumentHandler interface.</p>
<p>The locator allows the application to determine the end position of any
document-related event, even if the parser is not reporting an error. Typically,
the application will use this information for reporting its own errors (such as
character content that does not match an application’s business rules). The
information returned by the locator is probably not sufficient for use with a
search engine.</p>
<p>Note that the locator will return correct information only during the invocation
of the events in this interface. The application should not attempt to use it at
any other time.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.startDocument">
<code class="descclassname">ContentHandler.</code><code class="descname">startDocument</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.startDocument" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of the beginning of a document.</p>
<p>The SAX parser will invoke this method only once, before any other methods in
this interface or in DTDHandler (except for <a class="reference internal" href="#xml.sax.handler.ContentHandler.setDocumentLocator" title="xml.sax.handler.ContentHandler.setDocumentLocator"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setDocumentLocator()</span></code></a>).</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.endDocument">
<code class="descclassname">ContentHandler.</code><code class="descname">endDocument</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.endDocument" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of the end of a document.</p>
<p>The SAX parser will invoke this method only once, and it will be the last method
invoked during the parse. The parser shall not invoke this method until it has
either abandoned parsing (because of an unrecoverable error) or reached the end
of input.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.startPrefixMapping">
<code class="descclassname">ContentHandler.</code><code class="descname">startPrefixMapping</code><span class="sig-paren">(</span><em>prefix</em>, <em>uri</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.startPrefixMapping" title="Permalink to this definition">¶</a></dt>
<dd><p>Begin the scope of a prefix-URI Namespace mapping.</p>
<p>The information from this event is not necessary for normal Namespace
processing: the SAX XML reader will automatically replace prefixes for element
and attribute names when the <code class="docutils literal notranslate"><span class="pre">feature_namespaces</span></code> feature is enabled (the
default).</p>
<p>There are cases, however, when applications need to use prefixes in character
data or in attribute values, where they cannot safely be expanded automatically;
the <a class="reference internal" href="#xml.sax.handler.ContentHandler.startPrefixMapping" title="xml.sax.handler.ContentHandler.startPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startPrefixMapping()</span></code></a> and <a class="reference internal" href="#xml.sax.handler.ContentHandler.endPrefixMapping" title="xml.sax.handler.ContentHandler.endPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endPrefixMapping()</span></code></a> events supply the
information to the application to expand prefixes in those contexts itself, if
necessary.</p>
<p>Note that <a class="reference internal" href="#xml.sax.handler.ContentHandler.startPrefixMapping" title="xml.sax.handler.ContentHandler.startPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startPrefixMapping()</span></code></a> and <a class="reference internal" href="#xml.sax.handler.ContentHandler.endPrefixMapping" title="xml.sax.handler.ContentHandler.endPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endPrefixMapping()</span></code></a> events are not
guaranteed to be properly nested relative to each-other: all
<a class="reference internal" href="#xml.sax.handler.ContentHandler.startPrefixMapping" title="xml.sax.handler.ContentHandler.startPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startPrefixMapping()</span></code></a> events will occur before the corresponding
<a class="reference internal" href="#xml.sax.handler.ContentHandler.startElement" title="xml.sax.handler.ContentHandler.startElement"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startElement()</span></code></a> event, and all <a class="reference internal" href="#xml.sax.handler.ContentHandler.endPrefixMapping" title="xml.sax.handler.ContentHandler.endPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endPrefixMapping()</span></code></a> events will occur
after the corresponding <a class="reference internal" href="#xml.sax.handler.ContentHandler.endElement" title="xml.sax.handler.ContentHandler.endElement"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endElement()</span></code></a> event, but their order is not
guaranteed.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.endPrefixMapping">
<code class="descclassname">ContentHandler.</code><code class="descname">endPrefixMapping</code><span class="sig-paren">(</span><em>prefix</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.endPrefixMapping" title="Permalink to this definition">¶</a></dt>
<dd><p>End the scope of a prefix-URI mapping.</p>
<p>See <a class="reference internal" href="#xml.sax.handler.ContentHandler.startPrefixMapping" title="xml.sax.handler.ContentHandler.startPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startPrefixMapping()</span></code></a> for details. This event will always occur after
the corresponding <a class="reference internal" href="#xml.sax.handler.ContentHandler.endElement" title="xml.sax.handler.ContentHandler.endElement"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endElement()</span></code></a> event, but the order of
<a class="reference internal" href="#xml.sax.handler.ContentHandler.endPrefixMapping" title="xml.sax.handler.ContentHandler.endPrefixMapping"><code class="xref py py-meth docutils literal notranslate"><span class="pre">endPrefixMapping()</span></code></a> events is not otherwise guaranteed.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.startElement">
<code class="descclassname">ContentHandler.</code><code class="descname">startElement</code><span class="sig-paren">(</span><em>name</em>, <em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.startElement" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals the start of an element in non-namespace mode.</p>
<p>The <em>name</em> parameter contains the raw XML 1.0 name of the element type as a
string and the <em>attrs</em> parameter holds an object of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code>
interface (see <a class="reference internal" href="xml.sax.reader.html#attributes-objects"><span class="std std-ref">The Attributes Interface</span></a>) containing the attributes of
the element.  The object passed as <em>attrs</em> may be re-used by the parser; holding
on to a reference to it is not a reliable way to keep a copy of the attributes.
To keep a copy of the attributes, use the <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a> method of the <em>attrs</em>
object.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.endElement">
<code class="descclassname">ContentHandler.</code><code class="descname">endElement</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.endElement" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals the end of an element in non-namespace mode.</p>
<p>The <em>name</em> parameter contains the name of the element type, just as with the
<a class="reference internal" href="#xml.sax.handler.ContentHandler.startElement" title="xml.sax.handler.ContentHandler.startElement"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startElement()</span></code></a> event.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.startElementNS">
<code class="descclassname">ContentHandler.</code><code class="descname">startElementNS</code><span class="sig-paren">(</span><em>name</em>, <em>qname</em>, <em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.startElementNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals the start of an element in namespace mode.</p>
<p>The <em>name</em> parameter contains the name of the element type as a <code class="docutils literal notranslate"><span class="pre">(uri,</span>
<span class="pre">localname)</span></code> tuple, the <em>qname</em> parameter contains the raw XML 1.0 name used in
the source document, and the <em>attrs</em> parameter holds an instance of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesNS</span></code> interface (see
<a class="reference internal" href="xml.sax.reader.html#attributes-ns-objects"><span class="std std-ref">The AttributesNS Interface</span></a>)
containing the attributes of the element.  If no namespace is associated with
the element, the <em>uri</em> component of <em>name</em> will be <code class="docutils literal notranslate"><span class="pre">None</span></code>.  The object passed
as <em>attrs</em> may be re-used by the parser; holding on to a reference to it is not
a reliable way to keep a copy of the attributes.  To keep a copy of the
attributes, use the <a class="reference internal" href="copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a> method of the <em>attrs</em> object.</p>
<p>Parsers may set the <em>qname</em> parameter to <code class="docutils literal notranslate"><span class="pre">None</span></code>, unless the
<code class="docutils literal notranslate"><span class="pre">feature_namespace_prefixes</span></code> feature is activated.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.endElementNS">
<code class="descclassname">ContentHandler.</code><code class="descname">endElementNS</code><span class="sig-paren">(</span><em>name</em>, <em>qname</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.endElementNS" title="Permalink to this definition">¶</a></dt>
<dd><p>Signals the end of an element in namespace mode.</p>
<p>The <em>name</em> parameter contains the name of the element type, just as with the
<a class="reference internal" href="#xml.sax.handler.ContentHandler.startElementNS" title="xml.sax.handler.ContentHandler.startElementNS"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startElementNS()</span></code></a> method, likewise the <em>qname</em> parameter.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.characters">
<code class="descclassname">ContentHandler.</code><code class="descname">characters</code><span class="sig-paren">(</span><em>content</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.characters" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of character data.</p>
<p>The Parser will call this method to report each chunk of character data. SAX
parsers may return all contiguous character data in a single chunk, or they may
split it into several chunks; however, all of the characters in any single event
must come from the same external entity so that the Locator provides useful
information.</p>
<p><em>content</em> may be a Unicode string or a byte string; the <code class="docutils literal notranslate"><span class="pre">expat</span></code> reader module
produces always Unicode strings.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The earlier SAX 1 interface provided by the Python XML Special Interest Group
used a more Java-like interface for this method.  Since most parsers used from
Python did not take advantage of the older interface, the simpler signature was
chosen to replace it.  To convert old code to the new interface, use <em>content</em>
instead of slicing content with the old <em>offset</em> and <em>length</em> parameters.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.ignorableWhitespace">
<code class="descclassname">ContentHandler.</code><code class="descname">ignorableWhitespace</code><span class="sig-paren">(</span><em>whitespace</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.ignorableWhitespace" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of ignorable whitespace in element content.</p>
<p>Validating Parsers must use this method to report each chunk of ignorable
whitespace (see the W3C XML 1.0 recommendation, section 2.10): non-validating
parsers may also use this method if they are capable of parsing and using
content models.</p>
<p>SAX parsers may return all contiguous whitespace in a single chunk, or they may
split it into several chunks; however, all of the characters in any single event
must come from the same external entity, so that the Locator provides useful
information.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.processingInstruction">
<code class="descclassname">ContentHandler.</code><code class="descname">processingInstruction</code><span class="sig-paren">(</span><em>target</em>, <em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.processingInstruction" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of a processing instruction.</p>
<p>The Parser will invoke this method once for each processing instruction found:
note that processing instructions may occur before or after the main document
element.</p>
<p>A SAX parser should never report an XML declaration (XML 1.0, section 2.8) or a
text declaration (XML 1.0, section 4.3.1) using this method.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ContentHandler.skippedEntity">
<code class="descclassname">ContentHandler.</code><code class="descname">skippedEntity</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ContentHandler.skippedEntity" title="Permalink to this definition">¶</a></dt>
<dd><p>Receive notification of a skipped entity.</p>
<p>The Parser will invoke this method once for each entity skipped. Non-validating
processors may skip entities if they have not seen the declarations (because,
for example, the entity was declared in an external DTD subset). All processors
may skip external entities, depending on the values of the
<code class="docutils literal notranslate"><span class="pre">feature_external_ges</span></code> and the <code class="docutils literal notranslate"><span class="pre">feature_external_pes</span></code> properties.</p>
</dd></dl>

</div>
<div class="section" id="dtdhandler-objects">
<span id="dtd-handler-objects"></span><h2>19.12.2. DTDHandler Objects<a class="headerlink" href="#dtdhandler-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#xml.sax.handler.DTDHandler" title="xml.sax.handler.DTDHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DTDHandler</span></code></a> instances provide the following methods:</p>
<dl class="method">
<dt id="xml.sax.handler.DTDHandler.notationDecl">
<code class="descclassname">DTDHandler.</code><code class="descname">notationDecl</code><span class="sig-paren">(</span><em>name</em>, <em>publicId</em>, <em>systemId</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.DTDHandler.notationDecl" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle a notation declaration event.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.DTDHandler.unparsedEntityDecl">
<code class="descclassname">DTDHandler.</code><code class="descname">unparsedEntityDecl</code><span class="sig-paren">(</span><em>name</em>, <em>publicId</em>, <em>systemId</em>, <em>ndata</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.DTDHandler.unparsedEntityDecl" title="Permalink to this definition">¶</a></dt>
<dd><p>Handle an unparsed entity declaration event.</p>
</dd></dl>

</div>
<div class="section" id="entityresolver-objects">
<span id="entity-resolver-objects"></span><h2>19.12.3. EntityResolver Objects<a class="headerlink" href="#entityresolver-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="xml.sax.handler.EntityResolver.resolveEntity">
<code class="descclassname">EntityResolver.</code><code class="descname">resolveEntity</code><span class="sig-paren">(</span><em>publicId</em>, <em>systemId</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.EntityResolver.resolveEntity" title="Permalink to this definition">¶</a></dt>
<dd><p>Resolve the system identifier of an entity and return either the system
identifier to read from as a string, or an InputSource to read from. The default
implementation returns <em>systemId</em>.</p>
</dd></dl>

</div>
<div class="section" id="errorhandler-objects">
<span id="sax-error-handler"></span><h2>19.12.4. ErrorHandler Objects<a class="headerlink" href="#errorhandler-objects" title="Permalink to this headline">¶</a></h2>
<p>Objects with this interface are used to receive error and warning information
from the <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a>.  If you create an object that
implements this interface, then register the object with your
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a>, the parser
will call the methods in your object to report all warnings and errors. There
are three levels of errors available: warnings, (possibly) recoverable errors,
and unrecoverable errors.  All methods take a <code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXParseException</span></code> as the
only parameter.  Errors and warnings may be converted to an exception by raising
the passed-in exception object.</p>
<dl class="method">
<dt id="xml.sax.handler.ErrorHandler.error">
<code class="descclassname">ErrorHandler.</code><code class="descname">error</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ErrorHandler.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the parser encounters a recoverable error.  If this method does not
raise an exception, parsing may continue, but further document information
should not be expected by the application.  Allowing the parser to continue may
allow additional errors to be discovered in the input document.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ErrorHandler.fatalError">
<code class="descclassname">ErrorHandler.</code><code class="descname">fatalError</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ErrorHandler.fatalError" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the parser encounters an error it cannot recover from; parsing is
expected to terminate when this method returns.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.handler.ErrorHandler.warning">
<code class="descclassname">ErrorHandler.</code><code class="descname">warning</code><span class="sig-paren">(</span><em>exception</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.handler.ErrorHandler.warning" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when the parser presents minor warning information to the application.
Parsing is expected to continue when this method returns, and document
information will continue to be passed to the application. Raising an exception
in this method will cause parsing to end.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a><ul>
<li><a class="reference internal" href="#contenthandler-objects">19.12.1. ContentHandler Objects</a></li>
<li><a class="reference internal" href="#dtdhandler-objects">19.12.2. DTDHandler Objects</a></li>
<li><a class="reference internal" href="#entityresolver-objects">19.12.3. EntityResolver Objects</a></li>
<li><a class="reference internal" href="#errorhandler-objects">19.12.4. ErrorHandler Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.sax.html"
                        title="previous chapter">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.sax.utils.html"
                        title="next chapter">19.13. <code class="docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code> — SAX Utilities</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.sax.handler.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.utils.html" title="19.13. xml.sax.saxutils — SAX Utilities"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.sax.html" title="19.11. xml.sax — Support for SAX2 parsers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\%{Xe�[�[html/library/xml.sax.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.11. xml.sax — Support for SAX2 parsers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.12. xml.sax.handler — Base classes for SAX handlers" href="xml.sax.handler.html" />
    <link rel="prev" title="19.10. xml.dom.pulldom — Support for building partial DOM trees" href="xml.dom.pulldom.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.sax.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.handler.html" title="19.12. xml.sax.handler — Base classes for SAX handlers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.dom.pulldom.html" title="19.10. xml.dom.pulldom — Support for building partial DOM trees"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.sax">
<span id="xml-sax-support-for-sax2-parsers"></span><h1>19.11. <a class="reference internal" href="#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> — Support for SAX2 parsers<a class="headerlink" href="#module-xml.sax" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>The <a class="reference internal" href="#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> package provides a number of modules which implement the
Simple API for XML (SAX) interface for Python.  The package itself provides the
SAX exceptions and the convenience functions which will be most used by users of
the SAX API.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> module is not secure against maliciously
constructed data.  If you need to parse untrusted or unauthenticated data see
<a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<p>The convenience functions are:</p>
<dl class="function">
<dt id="xml.sax.make_parser">
<code class="descclassname">xml.sax.</code><code class="descname">make_parser</code><span class="sig-paren">(</span><span class="optional">[</span><em>parser_list</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.make_parser" title="Permalink to this definition">¶</a></dt>
<dd><p>Create and return a SAX <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> object.  The
first parser found will
be used.  If <em>parser_list</em> is provided, it must be a list of strings which
name modules that have a function named <code class="xref py py-func docutils literal notranslate"><span class="pre">create_parser()</span></code>.  Modules listed
in <em>parser_list</em> will be used before modules in the default list of parsers.</p>
</dd></dl>

<dl class="function">
<dt id="xml.sax.parse">
<code class="descclassname">xml.sax.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>filename_or_stream</em>, <em>handler</em><span class="optional">[</span>, <em>error_handler</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a SAX parser and use it to parse a document.  The document, passed in as
<em>filename_or_stream</em>, can be a filename or a file object.  The <em>handler</em>
parameter needs to be a SAX <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a> instance.  If
<em>error_handler</em> is given, it must be a SAX <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ErrorHandler" title="xml.sax.handler.ErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ErrorHandler</span></code></a>
instance; if
omitted,  <a class="reference internal" href="#xml.sax.SAXParseException" title="xml.sax.SAXParseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXParseException</span></code></a> will be raised on all errors.  There is no
return value; all work must be done by the <em>handler</em> passed in.</p>
</dd></dl>

<dl class="function">
<dt id="xml.sax.parseString">
<code class="descclassname">xml.sax.</code><code class="descname">parseString</code><span class="sig-paren">(</span><em>string</em>, <em>handler</em><span class="optional">[</span>, <em>error_handler</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.parseString" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#xml.sax.parse" title="xml.sax.parse"><code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code></a>, but parses from a buffer <em>string</em> received as a
parameter.</p>
</dd></dl>

<p>A typical SAX application uses three kinds of objects: readers, handlers and
input sources.  “Reader” in this context is another term for parser, i.e. some
piece of code that reads the bytes or characters from the input source, and
produces a sequence of events. The events then get distributed to the handler
objects, i.e. the reader invokes a method on the handler.  A SAX application
must therefore obtain a reader object, create or open the input sources, create
the handlers, and connect these objects all together.  As the final step of
preparation, the reader is called to parse the input. During parsing, methods on
the handler objects are called based on structural and syntactic events from the
input data.</p>
<p>For these objects, only the interfaces are relevant; they are normally not
instantiated by the application itself.  Since Python does not have an explicit
notion of interface, they are formally introduced as classes, but applications
may use implementations which do not inherit from the provided classes.  The
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>, <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.Locator" title="xml.sax.xmlreader.Locator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Locator</span></code></a>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesNS</span></code>,
and <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> interfaces are defined in the
module <a class="reference internal" href="xml.sax.reader.html#module-xml.sax.xmlreader" title="xml.sax.xmlreader: Interface which SAX-compliant XML parsers must implement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code></a>.  The handler interfaces are defined in
<a class="reference internal" href="xml.sax.handler.html#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a>.  For convenience,
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> (which is often
instantiated directly) and the handler classes are also available from
<a class="reference internal" href="#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a>.  These interfaces are described below.</p>
<p>In addition to these classes, <a class="reference internal" href="#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> provides the following exception
classes.</p>
<dl class="exception">
<dt id="xml.sax.SAXException">
<em class="property">exception </em><code class="descclassname">xml.sax.</code><code class="descname">SAXException</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>exception</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXException" title="Permalink to this definition">¶</a></dt>
<dd><p>Encapsulate an XML error or warning.  This class can contain basic error or
warning information from either the XML parser or the application: it can be
subclassed to provide additional functionality or to add localization.  Note
that although the handlers defined in the
<a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ErrorHandler" title="xml.sax.handler.ErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ErrorHandler</span></code></a> interface
receive instances of this exception, it is not required to actually raise the
exception — it is also useful as a container for information.</p>
<p>When instantiated, <em>msg</em> should be a human-readable description of the error.
The optional <em>exception</em> parameter, if given, should be <code class="docutils literal notranslate"><span class="pre">None</span></code> or an exception
that was caught by the parsing code and is being passed along as information.</p>
<p>This is the base class for the other SAX exception classes.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.sax.SAXParseException">
<em class="property">exception </em><code class="descclassname">xml.sax.</code><code class="descname">SAXParseException</code><span class="sig-paren">(</span><em>msg</em>, <em>exception</em>, <em>locator</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXParseException" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="#xml.sax.SAXException" title="xml.sax.SAXException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXException</span></code></a> raised on parse errors. Instances of this
class are passed to the methods of the SAX
<a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ErrorHandler" title="xml.sax.handler.ErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ErrorHandler</span></code></a> interface to provide information
about the parse error.  This class supports the SAX
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.Locator" title="xml.sax.xmlreader.Locator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Locator</span></code></a> interface as well as the
<a class="reference internal" href="#xml.sax.SAXException" title="xml.sax.SAXException"><code class="xref py py-class docutils literal notranslate"><span class="pre">SAXException</span></code></a> interface.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.sax.SAXNotRecognizedException">
<em class="property">exception </em><code class="descclassname">xml.sax.</code><code class="descname">SAXNotRecognizedException</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>exception</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXNotRecognizedException" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="#xml.sax.SAXException" title="xml.sax.SAXException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXException</span></code></a> raised when a SAX
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> is
confronted with an unrecognized feature or property.  SAX applications and
extensions may use this class for similar purposes.</p>
</dd></dl>

<dl class="exception">
<dt id="xml.sax.SAXNotSupportedException">
<em class="property">exception </em><code class="descclassname">xml.sax.</code><code class="descname">SAXNotSupportedException</code><span class="sig-paren">(</span><em>msg</em><span class="optional">[</span>, <em>exception</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXNotSupportedException" title="Permalink to this definition">¶</a></dt>
<dd><p>Subclass of <a class="reference internal" href="#xml.sax.SAXException" title="xml.sax.SAXException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXException</span></code></a> raised when a SAX
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> is asked to
enable a feature that is not supported, or to set a property to a value that the
implementation does not support.  SAX applications and extensions may use this
class for similar purposes.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.saxproject.org/">SAX: The Simple API for XML</a></dt>
<dd>This site is the focal point for the definition of the SAX API.  It provides a
Java implementation and online documentation.  Links to implementations and
historical information are also available.</dd>
<dt>Module <a class="reference internal" href="xml.sax.handler.html#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a></dt>
<dd>Definitions of the interfaces for application-provided objects.</dd>
<dt>Module <a class="reference internal" href="xml.sax.utils.html#module-xml.sax.saxutils" title="xml.sax.saxutils: Convenience functions and classes for use with SAX."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code></a></dt>
<dd>Convenience functions for use in SAX applications.</dd>
<dt>Module <a class="reference internal" href="xml.sax.reader.html#module-xml.sax.xmlreader" title="xml.sax.xmlreader: Interface which SAX-compliant XML parsers must implement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code></a></dt>
<dd>Definitions of the interfaces for parser-provided objects.</dd>
</dl>
</div>
<div class="section" id="saxexception-objects">
<span id="sax-exception-objects"></span><h2>19.11.1. SAXException Objects<a class="headerlink" href="#saxexception-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#xml.sax.SAXException" title="xml.sax.SAXException"><code class="xref py py-class docutils literal notranslate"><span class="pre">SAXException</span></code></a> exception class supports the following methods:</p>
<dl class="method">
<dt id="xml.sax.SAXException.getMessage">
<code class="descclassname">SAXException.</code><code class="descname">getMessage</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXException.getMessage" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a human-readable message describing the error condition.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.SAXException.getException">
<code class="descclassname">SAXException.</code><code class="descname">getException</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.SAXException.getException" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an encapsulated exception object, or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a><ul>
<li><a class="reference internal" href="#saxexception-objects">19.11.1. SAXException Objects</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.dom.pulldom.html"
                        title="previous chapter">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.sax.handler.html"
                        title="next chapter">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.sax.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.handler.html" title="19.12. xml.sax.handler — Base classes for SAX handlers"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.dom.pulldom.html" title="19.10. xml.dom.pulldom — Support for building partial DOM trees"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�
 �� html/library/xml.sax.reader.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.14. xml.sax.xmlreader — Interface for XML parsers &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.15. xml.parsers.expat — Fast XML parsing using Expat" href="pyexpat.html" />
    <link rel="prev" title="19.13. xml.sax.saxutils — SAX Utilities" href="xml.sax.utils.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.sax.reader.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyexpat.html" title="19.15. xml.parsers.expat — Fast XML parsing using Expat"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.sax.utils.html" title="19.13. xml.sax.saxutils — SAX Utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.sax.xmlreader">
<span id="xml-sax-xmlreader-interface-for-xml-parsers"></span><h1>19.14. <a class="reference internal" href="#module-xml.sax.xmlreader" title="xml.sax.xmlreader: Interface which SAX-compliant XML parsers must implement."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code></a> — Interface for XML parsers<a class="headerlink" href="#module-xml.sax.xmlreader" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>SAX parsers implement the <a class="reference internal" href="#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> interface. They are implemented in
a Python module, which must provide a function <code class="xref py py-func docutils literal notranslate"><span class="pre">create_parser()</span></code>. This
function is invoked by  <a class="reference internal" href="xml.sax.html#xml.sax.make_parser" title="xml.sax.make_parser"><code class="xref py py-func docutils literal notranslate"><span class="pre">xml.sax.make_parser()</span></code></a> with no arguments to create
a new  parser object.</p>
<dl class="class">
<dt id="xml.sax.xmlreader.XMLReader">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">XMLReader</code><a class="headerlink" href="#xml.sax.xmlreader.XMLReader" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class which can be inherited by SAX parsers.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.xmlreader.IncrementalParser">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">IncrementalParser</code><a class="headerlink" href="#xml.sax.xmlreader.IncrementalParser" title="Permalink to this definition">¶</a></dt>
<dd><p>In some cases, it is desirable not to parse an input source at once, but to feed
chunks of the document as they get available. Note that the reader will normally
not read the entire file, but read it in chunks as well; still <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code>
won’t return until the entire document is processed. So these interfaces should
be used if the blocking behaviour of <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code> is not desirable.</p>
<p>When the parser is instantiated it is ready to begin accepting data from the
feed method immediately. After parsing has been finished with a call to close
the reset method must be called to make the parser ready to accept new data,
either from feed or using the parse method.</p>
<p>Note that these methods must <em>not</em> be called during parsing, that is, after
parse has been called and before it returns.</p>
<p>By default, the class also implements the parse method of the XMLReader
interface using the feed, close and reset methods of the IncrementalParser
interface as a convenience to SAX 2.0 driver writers.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.xmlreader.Locator">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">Locator</code><a class="headerlink" href="#xml.sax.xmlreader.Locator" title="Permalink to this definition">¶</a></dt>
<dd><p>Interface for associating a SAX event with a document location. A locator object
will return valid results only during calls to DocumentHandler methods; at any
other time, the results are unpredictable. If information is not available,
methods may return <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.xmlreader.InputSource">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">InputSource</code><span class="sig-paren">(</span><span class="optional">[</span><em>systemId</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource" title="Permalink to this definition">¶</a></dt>
<dd><p>Encapsulation of the information needed by the <a class="reference internal" href="#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> to read
entities.</p>
<p>This class may include information about the public identifier, system
identifier, byte stream (possibly with character encoding information) and/or
the character stream of an entity.</p>
<p>Applications will create objects of this class for use in the
<a class="reference internal" href="#xml.sax.xmlreader.XMLReader.parse" title="xml.sax.xmlreader.XMLReader.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">XMLReader.parse()</span></code></a> method and for returning from
EntityResolver.resolveEntity.</p>
<p>An <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> belongs to the application, the <a class="reference internal" href="#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> is
not allowed to modify <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> objects passed to it from the
application, although it may make copies and modify those.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.xmlreader.AttributesImpl">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">AttributesImpl</code><span class="sig-paren">(</span><em>attrs</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesImpl" title="Permalink to this definition">¶</a></dt>
<dd><p>This is an implementation of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code> interface (see section
<a class="reference internal" href="#attributes-objects"><span class="std std-ref">The Attributes Interface</span></a>).  This is a dictionary-like object which
represents the element attributes in a <code class="xref py py-meth docutils literal notranslate"><span class="pre">startElement()</span></code> call. In addition
to the most useful dictionary operations, it supports a number of other
methods as described by the interface. Objects of this class should be
instantiated by readers; <em>attrs</em> must be a dictionary-like object containing
a mapping from attribute names to attribute values.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.xmlreader.AttributesNSImpl">
<em class="property">class </em><code class="descclassname">xml.sax.xmlreader.</code><code class="descname">AttributesNSImpl</code><span class="sig-paren">(</span><em>attrs</em>, <em>qnames</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesNSImpl" title="Permalink to this definition">¶</a></dt>
<dd><p>Namespace-aware variant of <a class="reference internal" href="#xml.sax.xmlreader.AttributesImpl" title="xml.sax.xmlreader.AttributesImpl"><code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesImpl</span></code></a>, which will be passed to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">startElementNS()</span></code>. It is derived from <a class="reference internal" href="#xml.sax.xmlreader.AttributesImpl" title="xml.sax.xmlreader.AttributesImpl"><code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesImpl</span></code></a>, but
understands attribute names as two-tuples of <em>namespaceURI</em> and
<em>localname</em>. In addition, it provides a number of methods expecting qualified
names as they appear in the original document.  This class implements the
<code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesNS</span></code> interface (see section <a class="reference internal" href="#attributes-ns-objects"><span class="std std-ref">The AttributesNS Interface</span></a>).</p>
</dd></dl>

<div class="section" id="xmlreader-objects">
<span id="id1"></span><h2>19.14.1. XMLReader Objects<a class="headerlink" href="#xmlreader-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> interface supports the following methods:</p>
<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.parse">
<code class="descclassname">XMLReader.</code><code class="descname">parse</code><span class="sig-paren">(</span><em>source</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.parse" title="Permalink to this definition">¶</a></dt>
<dd><p>Process an input source, producing SAX events. The <em>source</em> object can be a
system identifier (a string identifying the input source – typically a file
name or a URL), a file-like object, or an <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> object. When
<a class="reference internal" href="#xml.sax.xmlreader.XMLReader.parse" title="xml.sax.xmlreader.XMLReader.parse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code></a> returns, the input is completely processed, and the parser object
can be discarded or reset. As a limitation, the current implementation only
accepts byte streams; processing of character streams is for further study.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getContentHandler">
<code class="descclassname">XMLReader.</code><code class="descname">getContentHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getContentHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setContentHandler">
<code class="descclassname">XMLReader.</code><code class="descname">setContentHandler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setContentHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a>.  If no
<a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a> is set, content events will be
discarded.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getDTDHandler">
<code class="descclassname">XMLReader.</code><code class="descname">getDTDHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getDTDHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.DTDHandler" title="xml.sax.handler.DTDHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DTDHandler</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setDTDHandler">
<code class="descclassname">XMLReader.</code><code class="descname">setDTDHandler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setDTDHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.DTDHandler" title="xml.sax.handler.DTDHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DTDHandler</span></code></a>.  If no
<a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.DTDHandler" title="xml.sax.handler.DTDHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">DTDHandler</span></code></a> is set, DTD
events will be discarded.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getEntityResolver">
<code class="descclassname">XMLReader.</code><code class="descname">getEntityResolver</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getEntityResolver" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.EntityResolver" title="xml.sax.handler.EntityResolver"><code class="xref py py-class docutils literal notranslate"><span class="pre">EntityResolver</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setEntityResolver">
<code class="descclassname">XMLReader.</code><code class="descname">setEntityResolver</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setEntityResolver" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.EntityResolver" title="xml.sax.handler.EntityResolver"><code class="xref py py-class docutils literal notranslate"><span class="pre">EntityResolver</span></code></a>.  If no
<a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.EntityResolver" title="xml.sax.handler.EntityResolver"><code class="xref py py-class docutils literal notranslate"><span class="pre">EntityResolver</span></code></a> is set,
attempts to resolve an external entity will result in opening the system
identifier for the entity, and fail if it is not available.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getErrorHandler">
<code class="descclassname">XMLReader.</code><code class="descname">getErrorHandler</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getErrorHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ErrorHandler" title="xml.sax.handler.ErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ErrorHandler</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setErrorHandler">
<code class="descclassname">XMLReader.</code><code class="descname">setErrorHandler</code><span class="sig-paren">(</span><em>handler</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setErrorHandler" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the current error handler.  If no <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ErrorHandler" title="xml.sax.handler.ErrorHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ErrorHandler</span></code></a>
is set, errors will be raised as exceptions, and warnings will be printed.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setLocale">
<code class="descclassname">XMLReader.</code><code class="descname">setLocale</code><span class="sig-paren">(</span><em>locale</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setLocale" title="Permalink to this definition">¶</a></dt>
<dd><p>Allow an application to set the locale for errors and warnings.</p>
<p>SAX parsers are not required to provide localization for errors and warnings; if
they cannot support the requested locale, however, they must raise a SAX
exception.  Applications may request a locale change in the middle of a parse.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getFeature">
<code class="descclassname">XMLReader.</code><code class="descname">getFeature</code><span class="sig-paren">(</span><em>featurename</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getFeature" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current setting for feature <em>featurename</em>.  If the feature is not
recognized, <code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXNotRecognizedException</span></code> is raised. The well-known
featurenames are listed in the module <a class="reference internal" href="xml.sax.handler.html#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setFeature">
<code class="descclassname">XMLReader.</code><code class="descname">setFeature</code><span class="sig-paren">(</span><em>featurename</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setFeature" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>featurename</em> to <em>value</em>. If the feature is not recognized,
<code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXNotRecognizedException</span></code> is raised. If the feature or its setting is not
supported by the parser, <em>SAXNotSupportedException</em> is raised.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.getProperty">
<code class="descclassname">XMLReader.</code><code class="descname">getProperty</code><span class="sig-paren">(</span><em>propertyname</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.getProperty" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the current setting for property <em>propertyname</em>. If the property is not
recognized, a <code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXNotRecognizedException</span></code> is raised. The well-known
propertynames are listed in the module <a class="reference internal" href="xml.sax.handler.html#module-xml.sax.handler" title="xml.sax.handler: Base classes for SAX event handlers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.handler</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.XMLReader.setProperty">
<code class="descclassname">XMLReader.</code><code class="descname">setProperty</code><span class="sig-paren">(</span><em>propertyname</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.XMLReader.setProperty" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the <em>propertyname</em> to <em>value</em>. If the property is not recognized,
<code class="xref py py-exc docutils literal notranslate"><span class="pre">SAXNotRecognizedException</span></code> is raised. If the property or its setting is
not supported by the parser, <em>SAXNotSupportedException</em> is raised.</p>
</dd></dl>

</div>
<div class="section" id="incrementalparser-objects">
<span id="incremental-parser-objects"></span><h2>19.14.2. IncrementalParser Objects<a class="headerlink" href="#incrementalparser-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of <a class="reference internal" href="#xml.sax.xmlreader.IncrementalParser" title="xml.sax.xmlreader.IncrementalParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">IncrementalParser</span></code></a> offer the following additional methods:</p>
<dl class="method">
<dt id="xml.sax.xmlreader.IncrementalParser.feed">
<code class="descclassname">IncrementalParser.</code><code class="descname">feed</code><span class="sig-paren">(</span><em>data</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.IncrementalParser.feed" title="Permalink to this definition">¶</a></dt>
<dd><p>Process a chunk of <em>data</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.IncrementalParser.close">
<code class="descclassname">IncrementalParser.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.IncrementalParser.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Assume the end of the document. That will check well-formedness conditions that
can be checked only at the end, invoke handlers, and may clean up resources
allocated during parsing.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.IncrementalParser.reset">
<code class="descclassname">IncrementalParser.</code><code class="descname">reset</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.IncrementalParser.reset" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called after close has been called to reset the parser so that it
is ready to parse new documents. The results of calling parse or feed after
close without calling reset are undefined.</p>
</dd></dl>

</div>
<div class="section" id="locator-objects">
<span id="id2"></span><h2>19.14.3. Locator Objects<a class="headerlink" href="#locator-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of <a class="reference internal" href="#xml.sax.xmlreader.Locator" title="xml.sax.xmlreader.Locator"><code class="xref py py-class docutils literal notranslate"><span class="pre">Locator</span></code></a> provide these methods:</p>
<dl class="method">
<dt id="xml.sax.xmlreader.Locator.getColumnNumber">
<code class="descclassname">Locator.</code><code class="descname">getColumnNumber</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Locator.getColumnNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the column number where the current event begins.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Locator.getLineNumber">
<code class="descclassname">Locator.</code><code class="descname">getLineNumber</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Locator.getLineNumber" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the line number where the current event begins.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Locator.getPublicId">
<code class="descclassname">Locator.</code><code class="descname">getPublicId</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Locator.getPublicId" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the public identifier for the current event.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Locator.getSystemId">
<code class="descclassname">Locator.</code><code class="descname">getSystemId</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Locator.getSystemId" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the system identifier for the current event.</p>
</dd></dl>

</div>
<div class="section" id="inputsource-objects">
<span id="input-source-objects"></span><h2>19.14.4. InputSource Objects<a class="headerlink" href="#inputsource-objects" title="Permalink to this headline">¶</a></h2>
<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.setPublicId">
<code class="descclassname">InputSource.</code><code class="descname">setPublicId</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.setPublicId" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the public identifier of this <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.getPublicId">
<code class="descclassname">InputSource.</code><code class="descname">getPublicId</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.getPublicId" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the public identifier of this <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.setSystemId">
<code class="descclassname">InputSource.</code><code class="descname">setSystemId</code><span class="sig-paren">(</span><em>id</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.setSystemId" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the system identifier of this <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.getSystemId">
<code class="descclassname">InputSource.</code><code class="descname">getSystemId</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.getSystemId" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the system identifier of this <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.setEncoding">
<code class="descclassname">InputSource.</code><code class="descname">setEncoding</code><span class="sig-paren">(</span><em>encoding</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.setEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Sets the character encoding of this <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a>.</p>
<p>The encoding must be a string acceptable for an XML encoding declaration (see
section 4.3.3 of the XML recommendation).</p>
<p>The encoding attribute of the <a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> is ignored if the
<a class="reference internal" href="#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> also contains a character stream.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.getEncoding">
<code class="descclassname">InputSource.</code><code class="descname">getEncoding</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.getEncoding" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the character encoding of this InputSource.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.setByteStream">
<code class="descclassname">InputSource.</code><code class="descname">setByteStream</code><span class="sig-paren">(</span><em>bytefile</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.setByteStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the byte stream (a Python file-like object which does not perform
byte-to-character conversion) for this input source.</p>
<p>The SAX parser will ignore this if there is also a character stream specified,
but it will use a byte stream in preference to opening a URI connection itself.</p>
<p>If the application knows the character encoding of the byte stream, it should
set it with the setEncoding method.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.getByteStream">
<code class="descclassname">InputSource.</code><code class="descname">getByteStream</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.getByteStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the byte stream for this input source.</p>
<p>The getEncoding method will return the character encoding for this byte stream,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unknown.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.setCharacterStream">
<code class="descclassname">InputSource.</code><code class="descname">setCharacterStream</code><span class="sig-paren">(</span><em>charfile</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.setCharacterStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Set the character stream for this input source. (The stream must be a Python 1.6
Unicode-wrapped file-like that performs conversion to Unicode strings.)</p>
<p>If there is a character stream specified, the SAX parser will ignore any byte
stream and will not attempt to open a URI connection to the system identifier.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.InputSource.getCharacterStream">
<code class="descclassname">InputSource.</code><code class="descname">getCharacterStream</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.InputSource.getCharacterStream" title="Permalink to this definition">¶</a></dt>
<dd><p>Get the character stream for this input source.</p>
</dd></dl>

</div>
<div class="section" id="the-attributes-interface">
<span id="attributes-objects"></span><h2>19.14.5. The <code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code> Interface<a class="headerlink" href="#the-attributes-interface" title="Permalink to this headline">¶</a></h2>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code> objects implement a portion of the mapping protocol,
including the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>.  The following methods
are also provided:</p>
<dl class="method">
<dt id="xml.sax.xmlreader.Attributes.getLength">
<code class="descclassname">Attributes.</code><code class="descname">getLength</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Attributes.getLength" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the number of attributes.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Attributes.getNames">
<code class="descclassname">Attributes.</code><code class="descname">getNames</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Attributes.getNames" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the names of the attributes.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Attributes.getType">
<code class="descclassname">Attributes.</code><code class="descname">getType</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Attributes.getType" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the type of the attribute <em>name</em>, which is normally <code class="docutils literal notranslate"><span class="pre">'CDATA'</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.Attributes.getValue">
<code class="descclassname">Attributes.</code><code class="descname">getValue</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.Attributes.getValue" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value of attribute <em>name</em>.</p>
</dd></dl>

</div>
<div class="section" id="the-attributesns-interface">
<span id="attributes-ns-objects"></span><h2>19.14.6. The <code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesNS</span></code> Interface<a class="headerlink" href="#the-attributesns-interface" title="Permalink to this headline">¶</a></h2>
<p>This interface is a subtype of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Attributes</span></code> interface (see section
<a class="reference internal" href="#attributes-objects"><span class="std std-ref">The Attributes Interface</span></a>).  All methods supported by that interface are also
available on <code class="xref py py-class docutils literal notranslate"><span class="pre">AttributesNS</span></code> objects.</p>
<p>The following methods are also available:</p>
<dl class="method">
<dt id="xml.sax.xmlreader.AttributesNS.getValueByQName">
<code class="descclassname">AttributesNS.</code><code class="descname">getValueByQName</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesNS.getValueByQName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value for a qualified name.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.AttributesNS.getNameByQName">
<code class="descclassname">AttributesNS.</code><code class="descname">getNameByQName</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesNS.getNameByQName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the <code class="docutils literal notranslate"><span class="pre">(namespace,</span> <span class="pre">localname)</span></code> pair for a qualified <em>name</em>.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.AttributesNS.getQNameByName">
<code class="descclassname">AttributesNS.</code><code class="descname">getQNameByName</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesNS.getQNameByName" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the qualified name for a <code class="docutils literal notranslate"><span class="pre">(namespace,</span> <span class="pre">localname)</span></code> pair.</p>
</dd></dl>

<dl class="method">
<dt id="xml.sax.xmlreader.AttributesNS.getQNames">
<code class="descclassname">AttributesNS.</code><code class="descname">getQNames</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.xmlreader.AttributesNS.getQNames" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the qualified names of all attributes.</p>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a><ul>
<li><a class="reference internal" href="#xmlreader-objects">19.14.1. XMLReader Objects</a></li>
<li><a class="reference internal" href="#incrementalparser-objects">19.14.2. IncrementalParser Objects</a></li>
<li><a class="reference internal" href="#locator-objects">19.14.3. Locator Objects</a></li>
<li><a class="reference internal" href="#inputsource-objects">19.14.4. InputSource Objects</a></li>
<li><a class="reference internal" href="#the-attributes-interface">19.14.5. The <code class="docutils literal notranslate"><span class="pre">Attributes</span></code> Interface</a></li>
<li><a class="reference internal" href="#the-attributesns-interface">19.14.6. The <code class="docutils literal notranslate"><span class="pre">AttributesNS</span></code> Interface</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.sax.utils.html"
                        title="previous chapter">19.13. <code class="docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code> — SAX Utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pyexpat.html"
                        title="next chapter">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.sax.reader.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pyexpat.html" title="19.15. xml.parsers.expat — Fast XML parsing using Expat"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.sax.utils.html" title="19.13. xml.sax.saxutils — SAX Utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��P�>�>html/library/xml.sax.utils.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>19.13. xml.sax.saxutils — SAX Utilities &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="19.14. xml.sax.xmlreader — Interface for XML parsers" href="xml.sax.reader.html" />
    <link rel="prev" title="19.12. xml.sax.handler — Base classes for SAX handlers" href="xml.sax.handler.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xml.sax.utils.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.reader.html" title="19.14. xml.sax.xmlreader — Interface for XML parsers"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="xml.sax.handler.html" title="19.12. xml.sax.handler — Base classes for SAX handlers"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" accesskey="U">19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xml.sax.saxutils">
<span id="xml-sax-saxutils-sax-utilities"></span><h1>19.13. <a class="reference internal" href="#module-xml.sax.saxutils" title="xml.sax.saxutils: Convenience functions and classes for use with SAX."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code></a> — SAX Utilities<a class="headerlink" href="#module-xml.sax.saxutils" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.0.</span></p>
</div>
<p>The module <a class="reference internal" href="#module-xml.sax.saxutils" title="xml.sax.saxutils: Convenience functions and classes for use with SAX."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code></a> contains a number of classes and functions
that are commonly useful when creating SAX applications, either in direct use,
or as base classes.</p>
<dl class="function">
<dt id="xml.sax.saxutils.escape">
<code class="descclassname">xml.sax.saxutils.</code><code class="descname">escape</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>entities</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.escape" title="Permalink to this definition">¶</a></dt>
<dd><p>Escape <code class="docutils literal notranslate"><span class="pre">'&amp;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> in a string of data.</p>
<p>You can escape other strings of data by passing a dictionary as the optional
<em>entities</em> parameter.  The keys and values must all be strings; each key will be
replaced with its corresponding value.  The characters <code class="docutils literal notranslate"><span class="pre">'&amp;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&lt;'</span></code> and
<code class="docutils literal notranslate"><span class="pre">'&gt;'</span></code> are always escaped, even if <em>entities</em> is provided.</p>
</dd></dl>

<dl class="function">
<dt id="xml.sax.saxutils.unescape">
<code class="descclassname">xml.sax.saxutils.</code><code class="descname">unescape</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>entities</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.unescape" title="Permalink to this definition">¶</a></dt>
<dd><p>Unescape <code class="docutils literal notranslate"><span class="pre">'&amp;amp;'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&amp;lt;'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'&amp;gt;'</span></code> in a string of data.</p>
<p>You can unescape other strings of data by passing a dictionary as the optional
<em>entities</em> parameter.  The keys and values must all be strings; each key will be
replaced with its corresponding value.  <code class="docutils literal notranslate"><span class="pre">'&amp;amp'</span></code>, <code class="docutils literal notranslate"><span class="pre">'&amp;lt;'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'&amp;gt;'</span></code>
are always unescaped, even if <em>entities</em> is provided.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="xml.sax.saxutils.quoteattr">
<code class="descclassname">xml.sax.saxutils.</code><code class="descname">quoteattr</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>entities</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.quoteattr" title="Permalink to this definition">¶</a></dt>
<dd><p>Similar to <a class="reference internal" href="#xml.sax.saxutils.escape" title="xml.sax.saxutils.escape"><code class="xref py py-func docutils literal notranslate"><span class="pre">escape()</span></code></a>, but also prepares <em>data</em> to be used as an
attribute value.  The return value is a quoted version of <em>data</em> with any
additional required replacements. <a class="reference internal" href="#xml.sax.saxutils.quoteattr" title="xml.sax.saxutils.quoteattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">quoteattr()</span></code></a> will select a quote
character based on the content of <em>data</em>, attempting to avoid encoding any
quote characters in the string.  If both single- and double-quote characters
are already in <em>data</em>, the double-quote characters will be encoded and <em>data</em>
will be wrapped in double-quotes.  The resulting string can be used directly
as an attribute value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s2">&quot;&lt;element attr=</span><span class="si">%s</span><span class="s2">&gt;&quot;</span> <span class="o">%</span> <span class="n">quoteattr</span><span class="p">(</span><span class="s2">&quot;ab &#39; cd </span><span class="se">\&quot;</span><span class="s2"> ef&quot;</span><span class="p">)</span>
<span class="go">&lt;element attr=&quot;ab &#39; cd &amp;quot; ef&quot;&gt;</span>
</pre></div>
</div>
<p>This function is useful when generating attribute values for HTML or any SGML
using the reference concrete syntax.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="class">
<dt id="xml.sax.saxutils.XMLGenerator">
<em class="property">class </em><code class="descclassname">xml.sax.saxutils.</code><code class="descname">XMLGenerator</code><span class="sig-paren">(</span><span class="optional">[</span><em>out</em><span class="optional">[</span>, <em>encoding</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.XMLGenerator" title="Permalink to this definition">¶</a></dt>
<dd><p>This class implements the <a class="reference internal" href="xml.sax.handler.html#xml.sax.handler.ContentHandler" title="xml.sax.handler.ContentHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentHandler</span></code></a> interface
by writing SAX
events back into an XML document. In other words, using an <a class="reference internal" href="#xml.sax.saxutils.XMLGenerator" title="xml.sax.saxutils.XMLGenerator"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLGenerator</span></code></a>
as the content handler will reproduce the original document being parsed. <em>out</em>
should be a file-like object which will default to <em>sys.stdout</em>. <em>encoding</em> is
the encoding of the output stream which defaults to <code class="docutils literal notranslate"><span class="pre">'iso-8859-1'</span></code>.</p>
</dd></dl>

<dl class="class">
<dt id="xml.sax.saxutils.XMLFilterBase">
<em class="property">class </em><code class="descclassname">xml.sax.saxutils.</code><code class="descname">XMLFilterBase</code><span class="sig-paren">(</span><em>base</em><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.XMLFilterBase" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is designed to sit between an
<a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.XMLReader" title="xml.sax.xmlreader.XMLReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLReader</span></code></a> and the client
application’s event handlers.  By default, it does nothing but pass requests up
to the reader and events on to the handlers unmodified, but subclasses can
override specific methods to modify the event stream or the configuration
requests as they pass through.</p>
</dd></dl>

<dl class="function">
<dt id="xml.sax.saxutils.prepare_input_source">
<code class="descclassname">xml.sax.saxutils.</code><code class="descname">prepare_input_source</code><span class="sig-paren">(</span><em>source</em><span class="optional">[</span>, <em>base</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xml.sax.saxutils.prepare_input_source" title="Permalink to this definition">¶</a></dt>
<dd><p>This function takes an input source and an optional base URL and returns a
fully resolved <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> object ready for
reading.  The input source can be given as a string, a file-like object, or
an <a class="reference internal" href="xml.sax.reader.html#xml.sax.xmlreader.InputSource" title="xml.sax.xmlreader.InputSource"><code class="xref py py-class docutils literal notranslate"><span class="pre">InputSource</span></code></a> object; parsers will use this
function to implement the polymorphic <em>source</em> argument to their
<code class="xref py py-meth docutils literal notranslate"><span class="pre">parse()</span></code> method.</p>
</dd></dl>

</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="xml.sax.handler.html"
                        title="previous chapter">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="xml.sax.reader.html"
                        title="next chapter">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xml.sax.utils.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="xml.sax.reader.html" title="19.14. xml.sax.xmlreader — Interface for XML parsers"
             >next</a> |</li>
        <li class="right" >
          <a href="xml.sax.handler.html" title="19.12. xml.sax.handler — Base classes for SAX handlers"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="markup.html" >19. Structured Markup Processing Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��UGGhtml/library/xmlrpclib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>20.23. xmlrpclib — XML-RPC client access &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server" href="simplexmlrpcserver.html" />
    <link rel="prev" title="20.22. Cookie — HTTP state management" href="cookie.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/xmlrpclib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simplexmlrpcserver.html" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cookie.html" title="20.22. Cookie — HTTP state management"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" accesskey="U">20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-xmlrpclib">
<span id="xmlrpclib-xml-rpc-client-access"></span><h1>20.23. <a class="reference internal" href="#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> — XML-RPC client access<a class="headerlink" href="#module-xmlrpclib" title="Permalink to this headline">¶</a></h1>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module has been renamed to <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.client</span></code> in
Python 3.  The <a class="reference internal" href="../glossary.html#term-2to3"><span class="xref std std-term">2to3</span></a> tool will automatically adapt imports when
converting your sources to Python 3.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/xmlrpclib.py">Lib/xmlrpclib.py</a></p>
<hr class="docutils" />
<p>XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a
transport.  With it, a client can call methods with parameters on a remote
server (the server is named by a URI) and get back structured data.  This module
supports writing XML-RPC client code; it handles all the details of translating
between conformable Python objects and XML on the wire.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">The <a class="reference internal" href="#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module is not secure against maliciously
constructed data.  If you need to parse untrusted or unauthenticated data see
<a class="reference internal" href="xml.html#xml-vulnerabilities"><span class="std std-ref">XML vulnerabilities</span></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>For HTTPS URIs, <a class="reference internal" href="#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> now performs all the necessary certificate
and hostname checks by default.</p>
</div>
<dl class="class">
<dt id="xmlrpclib.ServerProxy">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">ServerProxy</code><span class="sig-paren">(</span><em>uri</em><span class="optional">[</span>, <em>transport</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>verbose</em><span class="optional">[</span>, <em>allow_none</em><span class="optional">[</span>, <em>use_datetime</em><span class="optional">[</span>, <em>context</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.ServerProxy" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#xmlrpclib.ServerProxy" title="xmlrpclib.ServerProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">ServerProxy</span></code></a> instance is an object that manages communication with a
remote XML-RPC server.  The required first argument is a URI (Uniform Resource
Indicator), and will normally be the URL of the server.  The optional second
argument is a transport factory instance; by default it is an internal
<code class="xref py py-class docutils literal notranslate"><span class="pre">SafeTransport</span></code> instance for https: URLs and an internal HTTP
<code class="xref py py-class docutils literal notranslate"><span class="pre">Transport</span></code> instance otherwise.  The optional third argument is an
encoding, by default UTF-8. The optional fourth argument is a debugging flag.</p>
<p>The following parameters govern the use of the returned proxy instance.
If <em>allow_none</em> is true,  the Python constant <code class="docutils literal notranslate"><span class="pre">None</span></code> will be translated into
XML; the default behaviour is for <code class="docutils literal notranslate"><span class="pre">None</span></code> to raise a <a class="reference internal" href="exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>. This is
a commonly-used extension to the XML-RPC specification, but isn’t supported by
all clients and servers; see <a class="reference external" href="https://web.archive.org/web/20130120074804/http://ontosys.com/xml-rpc/extensions.php">http://ontosys.com/xml-rpc/extensions.php</a>
for a description.
The <em>use_datetime</em> flag can be used to cause date/time values to
be presented as <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> objects; this is false by default.
<a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> objects may be passed to calls.</p>
<p>Both the HTTP and HTTPS transports support the URL syntax extension for HTTP
Basic Authentication: <code class="docutils literal notranslate"><span class="pre">http://user:pass&#64;host:port/path</span></code>.  The <code class="docutils literal notranslate"><span class="pre">user:pass</span></code>
portion will be base64-encoded as an HTTP ‘Authorization’ header, and sent to
the remote server as part of the connection process when invoking an XML-RPC
method.  You only need to use this if the remote server requires a Basic
Authentication user and password. If an HTTPS URL is provided, <em>context</em> may
be <a class="reference internal" href="ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">ssl.SSLContext</span></code></a> and configures the SSL settings of the underlying
HTTPS connection.</p>
<p>The returned instance is a proxy object with methods that can be used to invoke
corresponding RPC calls on the remote server.  If the remote server supports the
introspection API, the proxy can also be used to query the remote server for the
methods it supports (service discovery) and fetch other server-associated
metadata.</p>
<p>Types that are conformable (e.g. that can be marshalled through XML),
include the following (and except where noted, they are unmarshalled
as the same Python type):</p>
<table border="1" class="docutils">
<colgroup>
<col width="29%" />
<col width="71%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">XML-RPC type</th>
<th class="head">Python type</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">boolean</span></code></td>
<td><a class="reference internal" href="functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">int</span></code> or <code class="docutils literal notranslate"><span class="pre">i4</span></code></td>
<td><a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a> in range from
-2147483648 to 2147483647.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">double</span></code></td>
<td><a class="reference internal" href="functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">string</span></code></td>
<td><a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">array</span></code></td>
<td><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> or <a class="reference internal" href="functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing
conformable elements.  Arrays are returned as
<code class="xref py py-class docutils literal notranslate"><span class="pre">lists</span></code>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">struct</span></code></td>
<td><a class="reference internal" href="stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  Keys must be strings, values may be
any conformable type.  Objects of user-defined
classes can be passed in; only their
<a class="reference internal" href="stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute is transmitted.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">dateTime.iso8601</span></code></td>
<td><a class="reference internal" href="#xmlrpclib.DateTime" title="xmlrpclib.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTime</span></code></a> or <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a>.
Returned type depends on values of the <em>use_datetime</em>
flags.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">base64</span></code></td>
<td><a class="reference internal" href="#xmlrpclib.Binary" title="xmlrpclib.Binary"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binary</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">nil</span></code></td>
<td>The <code class="docutils literal notranslate"><span class="pre">None</span></code> constant.  Passing is allowed only if
<em>allow_none</em> is true.</td>
</tr>
</tbody>
</table>
<p>This is the full set of data types supported by XML-RPC.  Method calls may also
raise a special <a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Fault</span></code></a> instance, used to signal XML-RPC server errors, or
<a class="reference internal" href="#xmlrpclib.ProtocolError" title="xmlrpclib.ProtocolError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ProtocolError</span></code></a> used to signal an error in the HTTP/HTTPS transport layer.
Both <a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Fault</span></code></a> and <a class="reference internal" href="#xmlrpclib.ProtocolError" title="xmlrpclib.ProtocolError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ProtocolError</span></code></a> derive from a base class called
<code class="xref py py-exc docutils literal notranslate"><span class="pre">Error</span></code>.  Note that even though starting with Python 2.2 you can subclass
built-in types, the xmlrpclib module currently does not marshal instances of such
subclasses.</p>
<p>When passing strings, characters special to XML such as <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, and <code class="docutils literal notranslate"><span class="pre">&amp;</span></code>
will be automatically escaped.  However, it’s the caller’s responsibility to
ensure that the string is free of characters that aren’t allowed in XML, such as
the control characters with ASCII values between 0 and 31 (except, of course,
tab, newline and carriage return); failing to do this will result in an XML-RPC
request that isn’t well-formed XML.  If you have to pass arbitrary strings via
XML-RPC, use the <a class="reference internal" href="#xmlrpclib.Binary" title="xmlrpclib.Binary"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binary</span></code></a> wrapper class described below.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Server</span></code> is retained as an alias for <a class="reference internal" href="#xmlrpclib.ServerProxy" title="xmlrpclib.ServerProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">ServerProxy</span></code></a> for backwards
compatibility.  New code should use <a class="reference internal" href="#xmlrpclib.ServerProxy" title="xmlrpclib.ServerProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">ServerProxy</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>use_datetime</em> flag was added.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Instances of <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es can be passed in if they have an
<em>__dict__</em> attribute and don’t have a base class that is marshalled in a
special way.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.9: </span>Added the <em>context</em> argument.</p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.tldp.org/HOWTO/XML-RPC-HOWTO/index.html">XML-RPC HOWTO</a></dt>
<dd>A good description of XML-RPC operation and client software in several languages.
Contains pretty much everything an XML-RPC client developer needs to know.</dd>
<dt><a class="reference external" href="http://xmlrpc-c.sourceforge.net/introspection.html">XML-RPC Introspection</a></dt>
<dd>Describes the XML-RPC protocol extension for introspection.</dd>
<dt><a class="reference external" href="http://www.xmlrpc.com/spec">XML-RPC Specification</a></dt>
<dd>The official specification.</dd>
<dt><a class="reference external" href="http://effbot.org/zone/xmlrpc-errata.htm">Unofficial XML-RPC Errata</a></dt>
<dd>Fredrik Lundh’s “unofficial errata, intended to clarify certain
details in the XML-RPC specification, as well as hint at
‘best practices’ to use when designing your own XML-RPC
implementations.”</dd>
</dl>
</div>
<div class="section" id="serverproxy-objects">
<span id="id1"></span><h2>20.23.1. ServerProxy Objects<a class="headerlink" href="#serverproxy-objects" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#xmlrpclib.ServerProxy" title="xmlrpclib.ServerProxy"><code class="xref py py-class docutils literal notranslate"><span class="pre">ServerProxy</span></code></a> instance has a method corresponding to each remote
procedure call accepted by the XML-RPC server.  Calling the method performs an
RPC, dispatched by both name and argument signature (e.g. the same method name
can be overloaded with multiple argument signatures).  The RPC finishes by
returning a value, which may be either returned data in a conformant type or a
<a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fault</span></code></a> or <a class="reference internal" href="#xmlrpclib.ProtocolError" title="xmlrpclib.ProtocolError"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProtocolError</span></code></a> object indicating an error.</p>
<p>Servers that support the XML introspection API support some common methods
grouped under the reserved <code class="xref py py-attr docutils literal notranslate"><span class="pre">system</span></code> attribute:</p>
<dl class="method">
<dt id="xmlrpclib.ServerProxy.system.listMethods">
<code class="descclassname">ServerProxy.system.</code><code class="descname">listMethods</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.ServerProxy.system.listMethods" title="Permalink to this definition">¶</a></dt>
<dd><p>This method returns a list of strings, one for each (non-system) method
supported by the XML-RPC server.</p>
</dd></dl>

<dl class="method">
<dt id="xmlrpclib.ServerProxy.system.methodSignature">
<code class="descclassname">ServerProxy.system.</code><code class="descname">methodSignature</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.ServerProxy.system.methodSignature" title="Permalink to this definition">¶</a></dt>
<dd><p>This method takes one parameter, the name of a method implemented by the XML-RPC
server. It returns an array of possible signatures for this method. A signature
is an array of types. The first of these types is the return type of the method,
the rest are parameters.</p>
<p>Because multiple signatures (ie. overloading) is permitted, this method returns
a list of signatures rather than a singleton.</p>
<p>Signatures themselves are restricted to the top level parameters expected by a
method. For instance if a method expects one array of structs as a parameter,
and it returns a string, its signature is simply “string, array”. If it expects
three integers and returns a string, its signature is “string, int, int, int”.</p>
<p>If no signature is defined for the method, a non-array value is returned. In
Python this means that the type of the returned  value will be something other
than list.</p>
</dd></dl>

<dl class="method">
<dt id="xmlrpclib.ServerProxy.system.methodHelp">
<code class="descclassname">ServerProxy.system.</code><code class="descname">methodHelp</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.ServerProxy.system.methodHelp" title="Permalink to this definition">¶</a></dt>
<dd><p>This method takes one parameter, the name of a method implemented by the XML-RPC
server.  It returns a documentation string describing the use of that method. If
no such string is available, an empty string is returned. The documentation
string may contain HTML markup.</p>
</dd></dl>

</div>
<div class="section" id="boolean-objects">
<span id="id2"></span><h2>20.23.2. Boolean Objects<a class="headerlink" href="#boolean-objects" title="Permalink to this headline">¶</a></h2>
<p>This class may be initialized from any Python value; the instance returned
depends only on its truth value.  It supports various Python operators through
<a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a>, and <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a>
methods, all implemented in the obvious ways.</p>
<p>It also has the following method, supported mainly for internal use by the
unmarshalling code:</p>
<dl class="method">
<dt id="xmlrpclib.Boolean.encode">
<code class="descclassname">Boolean.</code><code class="descname">encode</code><span class="sig-paren">(</span><em>out</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.Boolean.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the XML-RPC encoding of this Boolean item to the out stream object.</p>
</dd></dl>

<p>A working example follows. The server code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>
<span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>

<span class="k">def</span> <span class="nf">is_even</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">n</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000...&quot;</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">is_even</span><span class="p">,</span> <span class="s2">&quot;is_even&quot;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The client code for the preceding server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000/&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;3 is even: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">proxy</span><span class="o">.</span><span class="n">is_even</span><span class="p">(</span><span class="mi">3</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;100 is even: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="nb">str</span><span class="p">(</span><span class="n">proxy</span><span class="o">.</span><span class="n">is_even</span><span class="p">(</span><span class="mi">100</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="datetime-objects">
<span id="id3"></span><h2>20.23.3. DateTime Objects<a class="headerlink" href="#datetime-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="xmlrpclib.DateTime">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">DateTime</code><a class="headerlink" href="#xmlrpclib.DateTime" title="Permalink to this definition">¶</a></dt>
<dd><p>This class may be initialized with seconds since the epoch, a time
tuple, an ISO 8601 time/date string, or a <a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a>
instance.  It has the following methods, supported mainly for internal
use by the marshalling/unmarshalling code:</p>
<dl class="method">
<dt id="xmlrpclib.DateTime.decode">
<code class="descname">decode</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.DateTime.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Accept a string as the instance’s new time value.</p>
</dd></dl>

<dl class="method">
<dt id="xmlrpclib.DateTime.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><em>out</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.DateTime.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the XML-RPC encoding of this <a class="reference internal" href="#xmlrpclib.DateTime" title="xmlrpclib.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">DateTime</span></code></a> item to the <em>out</em> stream
object.</p>
</dd></dl>

<p>It also supports certain of Python’s built-in operators through <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>
and <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> methods.</p>
</dd></dl>

<p>A working example follows. The server code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>
<span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="k">def</span> <span class="nf">today</span><span class="p">():</span>
    <span class="n">today</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">DateTime</span><span class="p">(</span><span class="n">today</span><span class="p">)</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000...&quot;</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">today</span><span class="p">,</span> <span class="s2">&quot;today&quot;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The client code for the preceding server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000/&quot;</span><span class="p">)</span>

<span class="n">today</span> <span class="o">=</span> <span class="n">proxy</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="c1"># convert the ISO8601 string to a datetime object</span>
<span class="n">converted</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="n">today</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="s2">&quot;%Y%m</span><span class="si">%d</span><span class="s2">T%H:%M:%S&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;Today: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">converted</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2">.%m.%Y, %H:%M&quot;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="binary-objects">
<span id="id4"></span><h2>20.23.4. Binary Objects<a class="headerlink" href="#binary-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="xmlrpclib.Binary">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">Binary</code><a class="headerlink" href="#xmlrpclib.Binary" title="Permalink to this definition">¶</a></dt>
<dd><p>This class may be initialized from string data (which may include NULs). The
primary access to the content of a <a class="reference internal" href="#xmlrpclib.Binary" title="xmlrpclib.Binary"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binary</span></code></a> object is provided by an
attribute:</p>
<dl class="attribute">
<dt id="xmlrpclib.Binary.data">
<code class="descname">data</code><a class="headerlink" href="#xmlrpclib.Binary.data" title="Permalink to this definition">¶</a></dt>
<dd><p>The binary data encapsulated by the <a class="reference internal" href="#xmlrpclib.Binary" title="xmlrpclib.Binary"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binary</span></code></a> instance.  The data is
provided as an 8-bit string.</p>
</dd></dl>

<p><a class="reference internal" href="#xmlrpclib.Binary" title="xmlrpclib.Binary"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binary</span></code></a> objects have the following methods, supported mainly for
internal use by the marshalling/unmarshalling code:</p>
<dl class="method">
<dt id="xmlrpclib.Binary.decode">
<code class="descname">decode</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.Binary.decode" title="Permalink to this definition">¶</a></dt>
<dd><p>Accept a base64 string and decode it as the instance’s new data.</p>
</dd></dl>

<dl class="method">
<dt id="xmlrpclib.Binary.encode">
<code class="descname">encode</code><span class="sig-paren">(</span><em>out</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.Binary.encode" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the XML-RPC base 64 encoding of this binary item to the <em>out</em> stream object.</p>
<p>The encoded data will have newlines every 76 characters as per
<a class="reference external" href="https://tools.ietf.org/html/rfc2045#section-6.8">RFC 2045 section 6.8</a>,
which was the de facto standard base64 specification when the
XML-RPC spec was written.</p>
</dd></dl>

<p>It also supports certain of Python’s built-in operators through a
<a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method.</p>
</dd></dl>

<p>Example usage of the binary objects.  We’re going to transfer an image over
XMLRPC:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>
<span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="k">def</span> <span class="nf">python_logo</span><span class="p">():</span>
     <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;python_logo.jpg&quot;</span><span class="p">,</span> <span class="s2">&quot;rb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">handle</span><span class="p">:</span>
         <span class="k">return</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">Binary</span><span class="p">(</span><span class="n">handle</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000...&quot;</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">python_logo</span><span class="p">,</span> <span class="s1">&#39;python_logo&#39;</span><span class="p">)</span>

<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The client gets the image and saves it to a file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000/&quot;</span><span class="p">)</span>
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;fetched_python_logo.jpg&quot;</span><span class="p">,</span> <span class="s2">&quot;wb&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">handle</span><span class="p">:</span>
    <span class="n">handle</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">proxy</span><span class="o">.</span><span class="n">python_logo</span><span class="p">()</span><span class="o">.</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="fault-objects">
<span id="id5"></span><h2>20.23.5. Fault Objects<a class="headerlink" href="#fault-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="xmlrpclib.Fault">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">Fault</code><a class="headerlink" href="#xmlrpclib.Fault" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fault</span></code></a> object encapsulates the content of an XML-RPC fault tag. Fault
objects have the following attributes:</p>
<dl class="attribute">
<dt id="xmlrpclib.Fault.faultCode">
<code class="descname">faultCode</code><a class="headerlink" href="#xmlrpclib.Fault.faultCode" title="Permalink to this definition">¶</a></dt>
<dd><p>A string indicating the fault type.</p>
</dd></dl>

<dl class="attribute">
<dt id="xmlrpclib.Fault.faultString">
<code class="descname">faultString</code><a class="headerlink" href="#xmlrpclib.Fault.faultString" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing a diagnostic message associated with the fault.</p>
</dd></dl>

</dd></dl>

<p>In the following example we’re going to intentionally cause a <a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Fault</span></code></a> by
returning a complex type object.  The server code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>

<span class="c1"># A marshalling error is going to occur because we&#39;re returning a</span>
<span class="c1"># complex number</span>
<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="o">+</span><span class="mi">0</span><span class="n">j</span>

<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000...&quot;</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">add</span><span class="p">,</span> <span class="s1">&#39;add&#39;</span><span class="p">)</span>

<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The client code for the preceding server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000/&quot;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">proxy</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="k">except</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">Fault</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;A fault occurred&quot;</span>
    <span class="nb">print</span> <span class="s2">&quot;Fault code: </span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">faultCode</span>
    <span class="nb">print</span> <span class="s2">&quot;Fault string: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">faultString</span>
</pre></div>
</div>
</div>
<div class="section" id="protocolerror-objects">
<span id="protocol-error-objects"></span><h2>20.23.6. ProtocolError Objects<a class="headerlink" href="#protocolerror-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="xmlrpclib.ProtocolError">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">ProtocolError</code><a class="headerlink" href="#xmlrpclib.ProtocolError" title="Permalink to this definition">¶</a></dt>
<dd><p>A <a class="reference internal" href="#xmlrpclib.ProtocolError" title="xmlrpclib.ProtocolError"><code class="xref py py-class docutils literal notranslate"><span class="pre">ProtocolError</span></code></a> object describes a protocol error in the underlying
transport layer (such as a 404 ‘not found’ error if the server named by the URI
does not exist).  It has the following attributes:</p>
<dl class="attribute">
<dt id="xmlrpclib.ProtocolError.url">
<code class="descname">url</code><a class="headerlink" href="#xmlrpclib.ProtocolError.url" title="Permalink to this definition">¶</a></dt>
<dd><p>The URI or URL that triggered the error.</p>
</dd></dl>

<dl class="attribute">
<dt id="xmlrpclib.ProtocolError.errcode">
<code class="descname">errcode</code><a class="headerlink" href="#xmlrpclib.ProtocolError.errcode" title="Permalink to this definition">¶</a></dt>
<dd><p>The error code.</p>
</dd></dl>

<dl class="attribute">
<dt id="xmlrpclib.ProtocolError.errmsg">
<code class="descname">errmsg</code><a class="headerlink" href="#xmlrpclib.ProtocolError.errmsg" title="Permalink to this definition">¶</a></dt>
<dd><p>The error message or diagnostic string.</p>
</dd></dl>

<dl class="attribute">
<dt id="xmlrpclib.ProtocolError.headers">
<code class="descname">headers</code><a class="headerlink" href="#xmlrpclib.ProtocolError.headers" title="Permalink to this definition">¶</a></dt>
<dd><p>A string containing the headers of the HTTP/HTTPS request that triggered the
error.</p>
</dd></dl>

</dd></dl>

<p>In the following example we’re going to intentionally cause a <a class="reference internal" href="#xmlrpclib.ProtocolError" title="xmlrpclib.ProtocolError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ProtocolError</span></code></a>
by providing a URI that doesn’t point to an XMLRPC server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="c1"># create a ServerProxy with a URI that doesn&#39;t respond to XMLRPC requests</span>
<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://www.google.com/&quot;</span><span class="p">)</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">proxy</span><span class="o">.</span><span class="n">some_method</span><span class="p">()</span>
<span class="k">except</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ProtocolError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;A protocol error occurred&quot;</span>
    <span class="nb">print</span> <span class="s2">&quot;URL: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">url</span>
    <span class="nb">print</span> <span class="s2">&quot;HTTP/HTTPS headers: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">headers</span>
    <span class="nb">print</span> <span class="s2">&quot;Error code: </span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">errcode</span>
    <span class="nb">print</span> <span class="s2">&quot;Error message: </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">err</span><span class="o">.</span><span class="n">errmsg</span>
</pre></div>
</div>
</div>
<div class="section" id="multicall-objects">
<h2>20.23.7. MultiCall Objects<a class="headerlink" href="#multicall-objects" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<p>The <a class="reference internal" href="#xmlrpclib.MultiCall" title="xmlrpclib.MultiCall"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiCall</span></code></a> object provides a way to encapsulate multiple calls to a
remote server into a single request <a class="footnote-reference" href="#id7" id="id6">[1]</a>.</p>
<dl class="class">
<dt id="xmlrpclib.MultiCall">
<em class="property">class </em><code class="descclassname">xmlrpclib.</code><code class="descname">MultiCall</code><span class="sig-paren">(</span><em>server</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.MultiCall" title="Permalink to this definition">¶</a></dt>
<dd><p>Create an object used to boxcar method calls. <em>server</em> is the eventual target of
the call. Calls can be made to the result object, but they will immediately
return <code class="docutils literal notranslate"><span class="pre">None</span></code>, and only store the call name and parameters in the
<a class="reference internal" href="#xmlrpclib.MultiCall" title="xmlrpclib.MultiCall"><code class="xref py py-class docutils literal notranslate"><span class="pre">MultiCall</span></code></a> object. Calling the object itself causes all stored calls to
be transmitted as a single <code class="docutils literal notranslate"><span class="pre">system.multicall</span></code> request. The result of this call
is a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>; iterating over this generator yields the individual
results.</p>
</dd></dl>

<p>A usage example of this class follows.  The server code</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span>

<span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>

<span class="k">def</span> <span class="nf">subtract</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">-</span><span class="n">y</span>

<span class="k">def</span> <span class="nf">multiply</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span>

<span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">/</span><span class="n">y</span>

<span class="c1"># A simple server with simple arithmetic functions</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">SimpleXMLRPCServer</span><span class="p">((</span><span class="s2">&quot;localhost&quot;</span><span class="p">,</span> <span class="mi">8000</span><span class="p">))</span>
<span class="nb">print</span> <span class="s2">&quot;Listening on port 8000...&quot;</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_multicall_functions</span><span class="p">()</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">add</span><span class="p">,</span> <span class="s1">&#39;add&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">subtract</span><span class="p">,</span> <span class="s1">&#39;subtract&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">multiply</span><span class="p">,</span> <span class="s1">&#39;multiply&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">register_function</span><span class="p">(</span><span class="n">divide</span><span class="p">,</span> <span class="s1">&#39;divide&#39;</span><span class="p">)</span>
<span class="n">server</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<p>The client code for the preceding server:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>

<span class="n">proxy</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://localhost:8000/&quot;</span><span class="p">)</span>
<span class="n">multicall</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">MultiCall</span><span class="p">(</span><span class="n">proxy</span><span class="p">)</span>
<span class="n">multicall</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="n">multicall</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="n">multicall</span><span class="o">.</span><span class="n">multiply</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="n">multicall</span><span class="o">.</span><span class="n">divide</span><span class="p">(</span><span class="mi">7</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">multicall</span><span class="p">()</span>

<span class="nb">print</span> <span class="s2">&quot;7+3=</span><span class="si">%d</span><span class="s2">, 7-3=</span><span class="si">%d</span><span class="s2">, 7*3=</span><span class="si">%d</span><span class="s2">, 7/3=</span><span class="si">%d</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="convenience-functions">
<h2>20.23.8. Convenience Functions<a class="headerlink" href="#convenience-functions" title="Permalink to this headline">¶</a></h2>
<dl class="function">
<dt id="xmlrpclib.boolean">
<code class="descclassname">xmlrpclib.</code><code class="descname">boolean</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.boolean" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert any Python value to one of the XML-RPC Boolean constants, <code class="docutils literal notranslate"><span class="pre">True</span></code> or
<code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="xmlrpclib.dumps">
<code class="descclassname">xmlrpclib.</code><code class="descname">dumps</code><span class="sig-paren">(</span><em>params</em><span class="optional">[</span>, <em>methodname</em><span class="optional">[</span>, <em>methodresponse</em><span class="optional">[</span>, <em>encoding</em><span class="optional">[</span>, <em>allow_none</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.dumps" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert <em>params</em> into an XML-RPC request. or into a response if <em>methodresponse</em>
is true. <em>params</em> can be either a tuple of arguments or an instance of the
<a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Fault</span></code></a> exception class.  If <em>methodresponse</em> is true, only a single value
can be returned, meaning that <em>params</em> must be of length 1. <em>encoding</em>, if
supplied, is the encoding to use in the generated XML; the default is UTF-8.
Python’s <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> value cannot be used in standard XML-RPC; to allow using
it via an extension,  provide a true value for <em>allow_none</em>.</p>
</dd></dl>

<dl class="function">
<dt id="xmlrpclib.loads">
<code class="descclassname">xmlrpclib.</code><code class="descname">loads</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>use_datetime</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#xmlrpclib.loads" title="Permalink to this definition">¶</a></dt>
<dd><p>Convert an XML-RPC request or response into Python objects, a <code class="docutils literal notranslate"><span class="pre">(params,</span>
<span class="pre">methodname)</span></code>.  <em>params</em> is a tuple of argument; <em>methodname</em> is a string, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if no method name is present in the packet. If the XML-RPC packet
represents a fault condition, this function will raise a <a class="reference internal" href="#xmlrpclib.Fault" title="xmlrpclib.Fault"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Fault</span></code></a> exception.
The <em>use_datetime</em> flag can be used to cause date/time values to be presented as
<a class="reference internal" href="datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.datetime</span></code></a> objects; this is false by default.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <em>use_datetime</em> flag was added.</p>
</div>
</dd></dl>

</div>
<div class="section" id="example-of-client-usage">
<span id="xmlrpc-client-example"></span><h2>20.23.9. Example of Client Usage<a class="headerlink" href="#example-of-client-usage" title="Permalink to this headline">¶</a></h2>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># simple test program (from the XML-RPC specification)</span>
<span class="kn">from</span> <span class="nn">xmlrpclib</span> <span class="k">import</span> <span class="n">ServerProxy</span><span class="p">,</span> <span class="n">Error</span>

<span class="c1"># server = ServerProxy(&quot;http://localhost:8000&quot;) # local server</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">ServerProxy</span><span class="p">(</span><span class="s2">&quot;http://betty.userland.com&quot;</span><span class="p">)</span>

<span class="nb">print</span> <span class="n">server</span>

<span class="k">try</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">server</span><span class="o">.</span><span class="n">examples</span><span class="o">.</span><span class="n">getStateName</span><span class="p">(</span><span class="mi">41</span><span class="p">)</span>
<span class="k">except</span> <span class="n">Error</span> <span class="k">as</span> <span class="n">v</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;ERROR&quot;</span><span class="p">,</span> <span class="n">v</span>
</pre></div>
</div>
<p>To access an XML-RPC server through a HTTP proxy, you need to define a custom
transport.  The following example shows how:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span><span class="o">,</span> <span class="nn">httplib</span>

<span class="k">class</span> <span class="nc">ProxiedTransport</span><span class="p">(</span><span class="n">xmlrpclib</span><span class="o">.</span><span class="n">Transport</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">set_proxy</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">proxy</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">proxy</span> <span class="o">=</span> <span class="n">proxy</span>

    <span class="k">def</span> <span class="nf">make_connection</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">host</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">realhost</span> <span class="o">=</span> <span class="n">host</span>
        <span class="n">h</span> <span class="o">=</span> <span class="n">httplib</span><span class="o">.</span><span class="n">HTTPConnection</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">proxy</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">h</span>

    <span class="k">def</span> <span class="nf">send_request</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">handler</span><span class="p">,</span> <span class="n">request_body</span><span class="p">):</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">putrequest</span><span class="p">(</span><span class="s2">&quot;POST&quot;</span><span class="p">,</span> <span class="s1">&#39;http://</span><span class="si">%s%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">realhost</span><span class="p">,</span> <span class="n">handler</span><span class="p">))</span>

    <span class="k">def</span> <span class="nf">send_host</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">connection</span><span class="p">,</span> <span class="n">host</span><span class="p">):</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">putheader</span><span class="p">(</span><span class="s1">&#39;Host&#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">realhost</span><span class="p">)</span>

<span class="n">p</span> <span class="o">=</span> <span class="n">ProxiedTransport</span><span class="p">()</span>
<span class="n">p</span><span class="o">.</span><span class="n">set_proxy</span><span class="p">(</span><span class="s1">&#39;proxy-server:8080&#39;</span><span class="p">)</span>
<span class="n">server</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">ServerProxy</span><span class="p">(</span><span class="s1">&#39;http://time.xmlrpc.com/RPC2&#39;</span><span class="p">,</span> <span class="n">transport</span><span class="o">=</span><span class="n">p</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">server</span><span class="o">.</span><span class="n">currentTime</span><span class="o">.</span><span class="n">getCurrentTime</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="section" id="example-of-client-and-server-usage">
<h2>20.23.10. Example of Client and Server Usage<a class="headerlink" href="#example-of-client-and-server-usage" title="Permalink to this headline">¶</a></h2>
<p>See <a class="reference internal" href="simplexmlrpcserver.html#simplexmlrpcserver-example"><span class="std std-ref">SimpleXMLRPCServer Example</span></a>.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id7" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id6">[1]</a></td><td>This approach has been first presented in <a class="reference external" href="https://web.archive.org/web/20060624230303/http://www.xmlrpc.com/discuss/msgReader$1208?mode=topic">a discussion on xmlrpc.com</a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a><ul>
<li><a class="reference internal" href="#serverproxy-objects">20.23.1. ServerProxy Objects</a></li>
<li><a class="reference internal" href="#boolean-objects">20.23.2. Boolean Objects</a></li>
<li><a class="reference internal" href="#datetime-objects">20.23.3. DateTime Objects</a></li>
<li><a class="reference internal" href="#binary-objects">20.23.4. Binary Objects</a></li>
<li><a class="reference internal" href="#fault-objects">20.23.5. Fault Objects</a></li>
<li><a class="reference internal" href="#protocolerror-objects">20.23.6. ProtocolError Objects</a></li>
<li><a class="reference internal" href="#multicall-objects">20.23.7. MultiCall Objects</a></li>
<li><a class="reference internal" href="#convenience-functions">20.23.8. Convenience Functions</a></li>
<li><a class="reference internal" href="#example-of-client-usage">20.23.9. Example of Client Usage</a></li>
<li><a class="reference internal" href="#example-of-client-and-server-usage">20.23.10. Example of Client and Server Usage</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cookie.html"
                        title="previous chapter">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="simplexmlrpcserver.html"
                        title="next chapter">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/xmlrpclib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simplexmlrpcserver.html" title="20.24. SimpleXMLRPCServer — Basic XML-RPC server"
             >next</a> |</li>
        <li class="right" >
          <a href="cookie.html" title="20.22. Cookie — HTTP state management"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="internet.html" >20. Internet Protocols and Support</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��-��html/library/zipfile.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12.4. zipfile — Work with ZIP archives &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12.5. tarfile — Read and write tar archive files" href="tarfile.html" />
    <link rel="prev" title="12.3. bz2 — Compression compatible with bzip2" href="bz2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/zipfile.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tarfile.html" title="12.5. tarfile — Read and write tar archive files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bz2.html" title="12.3. bz2 — Compression compatible with bzip2"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" accesskey="U">12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-zipfile">
<span id="zipfile-work-with-zip-archives"></span><h1>12.4. <a class="reference internal" href="#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> — Work with ZIP archives<a class="headerlink" href="#module-zipfile" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 1.6.</span></p>
</div>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Lib/zipfile.py">Lib/zipfile.py</a></p>
<hr class="docutils" />
<p>The ZIP file format is a common archive and compression standard. This module
provides tools to create, read, write, append, and list a ZIP file.  Any
advanced use of this module will require an understanding of the format, as
defined in <a class="reference external" href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">PKZIP Application Note</a>.</p>
<p>This module does not currently handle multi-disk ZIP files.
It can handle ZIP files that use the ZIP64 extensions
(that is ZIP files that are more than 4 GByte in size).  It supports
decryption of encrypted files in ZIP archives, but it currently cannot
create an encrypted file.  Decryption is extremely slow as it is
implemented in native Python rather than C.</p>
<p>The module defines the following items:</p>
<dl class="exception">
<dt id="zipfile.BadZipfile">
<em class="property">exception </em><code class="descclassname">zipfile.</code><code class="descname">BadZipfile</code><a class="headerlink" href="#zipfile.BadZipfile" title="Permalink to this definition">¶</a></dt>
<dd><p>The error raised for bad ZIP files (old name: <code class="docutils literal notranslate"><span class="pre">zipfile.error</span></code>).</p>
</dd></dl>

<dl class="exception">
<dt id="zipfile.LargeZipFile">
<em class="property">exception </em><code class="descclassname">zipfile.</code><code class="descname">LargeZipFile</code><a class="headerlink" href="#zipfile.LargeZipFile" title="Permalink to this definition">¶</a></dt>
<dd><p>The error raised when a ZIP file would require ZIP64 functionality but that has
not been enabled.</p>
</dd></dl>

<dl class="class">
<dt>
<em class="property">class </em><code class="descclassname">zipfile.</code><code class="descname">ZipFile</code></dt>
<dd><p>The class for reading and writing ZIP files.  See section
<a class="reference internal" href="#zipfile-objects"><span class="std std-ref">ZipFile Objects</span></a> for constructor details.</p>
</dd></dl>

<dl class="class">
<dt id="zipfile.PyZipFile">
<em class="property">class </em><code class="descclassname">zipfile.</code><code class="descname">PyZipFile</code><a class="headerlink" href="#zipfile.PyZipFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Class for creating ZIP archives containing Python libraries.</p>
</dd></dl>

<dl class="class">
<dt id="zipfile.ZipInfo">
<em class="property">class </em><code class="descclassname">zipfile.</code><code class="descname">ZipInfo</code><span class="sig-paren">(</span><span class="optional">[</span><em>filename</em><span class="optional">[</span>, <em>date_time</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipInfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Class used to represent information about a member of an archive. Instances
of this class are returned by the <a class="reference internal" href="#zipfile.ZipFile.getinfo" title="zipfile.ZipFile.getinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getinfo()</span></code></a> and <a class="reference internal" href="#zipfile.ZipFile.infolist" title="zipfile.ZipFile.infolist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">infolist()</span></code></a>
methods of <a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> objects.  Most users of the <a class="reference internal" href="#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module
will not need to create these, but only use those created by this
module. <em>filename</em> should be the full name of the archive member, and
<em>date_time</em> should be a tuple containing six fields which describe the time
of the last modification to the file; the fields are described in section
<a class="reference internal" href="#zipinfo-objects"><span class="std std-ref">ZipInfo Objects</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="zipfile.is_zipfile">
<code class="descclassname">zipfile.</code><code class="descname">is_zipfile</code><span class="sig-paren">(</span><em>filename</em><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.is_zipfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>filename</em> is a valid ZIP file based on its magic number,
otherwise returns <code class="docutils literal notranslate"><span class="pre">False</span></code>.  <em>filename</em> may be a file or file-like object too.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for file and file-like objects.</p>
</div>
</dd></dl>

<dl class="data">
<dt id="zipfile.ZIP_STORED">
<code class="descclassname">zipfile.</code><code class="descname">ZIP_STORED</code><a class="headerlink" href="#zipfile.ZIP_STORED" title="Permalink to this definition">¶</a></dt>
<dd><p>The numeric constant for an uncompressed archive member.</p>
</dd></dl>

<dl class="data">
<dt id="zipfile.ZIP_DEFLATED">
<code class="descclassname">zipfile.</code><code class="descname">ZIP_DEFLATED</code><a class="headerlink" href="#zipfile.ZIP_DEFLATED" title="Permalink to this definition">¶</a></dt>
<dd><p>The numeric constant for the usual ZIP compression method.  This requires the
<a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module.  No other compression methods are currently supported.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">PKZIP Application Note</a></dt>
<dd>Documentation on the ZIP file format by Phil Katz, the creator of the format and
algorithms used.</dd>
<dt><a class="reference external" href="http://www.info-zip.org/">Info-ZIP Home Page</a></dt>
<dd>Information about the Info-ZIP project’s ZIP archive programs and development
libraries.</dd>
</dl>
</div>
<div class="section" id="zipfile-objects">
<span id="id1"></span><h2>12.4.1. ZipFile Objects<a class="headerlink" href="#zipfile-objects" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="zipfile.ZipFile">
<em class="property">class </em><code class="descclassname">zipfile.</code><code class="descname">ZipFile</code><span class="sig-paren">(</span><em>file</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>compression</em><span class="optional">[</span>, <em>allowZip64</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile" title="Permalink to this definition">¶</a></dt>
<dd><p>Open a ZIP file, where <em>file</em> can be either a path to a file (a string) or a
file-like object.  The <em>mode</em> parameter should be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> to read an existing
file, <code class="docutils literal notranslate"><span class="pre">'w'</span></code> to truncate and write a new file, or <code class="docutils literal notranslate"><span class="pre">'a'</span></code> to append to an
existing file.  If <em>mode</em> is <code class="docutils literal notranslate"><span class="pre">'a'</span></code> and <em>file</em> refers to an existing ZIP
file, then additional files are added to it.  If <em>file</em> does not refer to a
ZIP file, then a new ZIP archive is appended to the file.  This is meant for
adding a ZIP archive to another file (such as <code class="file docutils literal notranslate"><span class="pre">python.exe</span></code>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>If <em>mode</em> is <code class="docutils literal notranslate"><span class="pre">a</span></code> and the file does not exist at all, it is created.</p>
</div>
<p><em>compression</em> is the ZIP compression method to use when writing the archive,
and should be <a class="reference internal" href="#zipfile.ZIP_STORED" title="zipfile.ZIP_STORED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ZIP_STORED</span></code></a> or <a class="reference internal" href="#zipfile.ZIP_DEFLATED" title="zipfile.ZIP_DEFLATED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ZIP_DEFLATED</span></code></a>; unrecognized
values will cause <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> to be raised.  If <a class="reference internal" href="#zipfile.ZIP_DEFLATED" title="zipfile.ZIP_DEFLATED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ZIP_DEFLATED</span></code></a>
is specified but the <a class="reference internal" href="zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module is not available, <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>
is also raised. The default is <a class="reference internal" href="#zipfile.ZIP_STORED" title="zipfile.ZIP_STORED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ZIP_STORED</span></code></a>.  If <em>allowZip64</em> is
<code class="docutils literal notranslate"><span class="pre">True</span></code> zipfile will create ZIP files that use the ZIP64 extensions when
the zipfile is larger than 2 GB. If it is  false (the default) <a class="reference internal" href="#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a>
will raise an exception when the ZIP file would require ZIP64 extensions.
ZIP64 extensions are disabled by default because the default <strong class="program">zip</strong>
and <strong class="program">unzip</strong> commands on Unix (the InfoZIP utilities) don’t support
these extensions.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.1: </span>If the file is created with mode <code class="docutils literal notranslate"><span class="pre">'a'</span></code> or <code class="docutils literal notranslate"><span class="pre">'w'</span></code> and then
<a class="reference internal" href="#zipfile.ZipFile.close" title="zipfile.ZipFile.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">closed</span></code></a> without adding any files to the archive, the appropriate
ZIP structures for an empty archive will be written to the file.</p>
</div>
<p>ZipFile is also a context manager and therefore supports the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  In the example, <em>myzip</em> is closed after the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement’s suite is finished—even if an exception occurs:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">ZipFile</span><span class="p">(</span><span class="s1">&#39;spam.zip&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">myzip</span><span class="p">:</span>
    <span class="n">myzip</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;eggs.txt&#39;</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7: </span>Added the ability to use <a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> as a context manager.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.close">
<code class="descclassname">ZipFile.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Close the archive file.  You must call <a class="reference internal" href="#zipfile.ZipFile.close" title="zipfile.ZipFile.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> before exiting your program
or essential records will not be written.</p>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.getinfo">
<code class="descclassname">ZipFile.</code><code class="descname">getinfo</code><span class="sig-paren">(</span><em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.getinfo" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object with information about the archive member
<em>name</em>.  Calling <a class="reference internal" href="#zipfile.ZipFile.getinfo" title="zipfile.ZipFile.getinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getinfo()</span></code></a> for a name not currently contained in the
archive will raise a <a class="reference internal" href="exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.infolist">
<code class="descclassname">ZipFile.</code><code class="descname">infolist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.infolist" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list containing a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object for each member of the
archive.  The objects are in the same order as their entries in the actual ZIP
file on disk if an existing archive was opened.</p>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.namelist">
<code class="descclassname">ZipFile.</code><code class="descname">namelist</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.namelist" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a list of archive members by name.</p>
<span class="target" id="index-0"></span></dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.open">
<code class="descclassname">ZipFile.</code><code class="descname">open</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>mode</em><span class="optional">[</span>, <em>pwd</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.open" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract a member from the archive as a file-like object (ZipExtFile). <em>name</em> is
the name of the file in the archive, or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object. The <em>mode</em>
parameter, if included, must be one of the following: <code class="docutils literal notranslate"><span class="pre">'r'</span></code> (the default),
<code class="docutils literal notranslate"><span class="pre">'U'</span></code>, or <code class="docutils literal notranslate"><span class="pre">'rU'</span></code>. Choosing <code class="docutils literal notranslate"><span class="pre">'U'</span></code> or  <code class="docutils literal notranslate"><span class="pre">'rU'</span></code> will enable
<a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newline</span></a>
support in the read-only object. <em>pwd</em> is the password used for encrypted files.
Calling  <a class="reference internal" href="#zipfile.ZipFile.open" title="zipfile.ZipFile.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> on a closed ZipFile will raise a  <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The file-like object is read-only and provides the following methods:
<a class="reference internal" href="stdtypes.html#file.read" title="file.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a>, <a class="reference internal" href="stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>,
<a class="reference internal" href="stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code>.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the ZipFile was created by passing in a file-like object as the  first
argument to the constructor, then the object returned by <a class="reference internal" href="#zipfile.ZipFile.open" title="zipfile.ZipFile.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> shares the
ZipFile’s file pointer.  Under these  circumstances, the object returned by
<a class="reference internal" href="#zipfile.ZipFile.open" title="zipfile.ZipFile.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> should not  be used after any additional operations are performed
on the  ZipFile object.  If the ZipFile was created by passing in a string (the
filename) as the first argument to the constructor, then  <a class="reference internal" href="#zipfile.ZipFile.open" title="zipfile.ZipFile.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a> will
create a new file object that will be held by the ZipExtFile, allowing it to
operate independently of the  ZipFile.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#zipfile.ZipFile.open" title="zipfile.ZipFile.open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a>, <a class="reference internal" href="#zipfile.ZipFile.read" title="zipfile.ZipFile.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> and <a class="reference internal" href="#zipfile.ZipFile.extract" title="zipfile.ZipFile.extract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code></a> methods can take a filename
or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object.  You will appreciate this when trying to read a
ZIP file that contains members with duplicate names.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.extract">
<code class="descclassname">ZipFile.</code><code class="descname">extract</code><span class="sig-paren">(</span><em>member</em><span class="optional">[</span>, <em>path</em><span class="optional">[</span>, <em>pwd</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.extract" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract a member from the archive to the current working directory; <em>member</em>
must be its full name or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object).  Its file information is
extracted as accurately as possible.  <em>path</em> specifies a different directory
to extract to.  <em>member</em> can be a filename or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object.
<em>pwd</em> is the password used for encrypted files.</p>
<p>Returns the normalized path created (a directory or new file).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If a member filename is an absolute path, a drive/UNC sharepoint and
leading (back)slashes will be stripped, e.g.: <code class="docutils literal notranslate"><span class="pre">///foo/bar</span></code> becomes
<code class="docutils literal notranslate"><span class="pre">foo/bar</span></code> on Unix, and <code class="docutils literal notranslate"><span class="pre">C:\foo\bar</span></code> becomes <code class="docutils literal notranslate"><span class="pre">foo\bar</span></code> on Windows.
And all <code class="docutils literal notranslate"><span class="pre">&quot;..&quot;</span></code> components in a member filename will be removed, e.g.:
<code class="docutils literal notranslate"><span class="pre">../../foo../../ba..r</span></code> becomes <code class="docutils literal notranslate"><span class="pre">foo../ba..r</span></code>.  On Windows illegal
characters (<code class="docutils literal notranslate"><span class="pre">:</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">?</span></code>, and <code class="docutils literal notranslate"><span class="pre">*</span></code>)
replaced by underscore (<code class="docutils literal notranslate"><span class="pre">_</span></code>).</p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.extractall">
<code class="descclassname">ZipFile.</code><code class="descname">extractall</code><span class="sig-paren">(</span><span class="optional">[</span><em>path</em><span class="optional">[</span>, <em>members</em><span class="optional">[</span>, <em>pwd</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.extractall" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract all members from the archive to the current working directory.  <em>path</em>
specifies a different directory to extract to.  <em>members</em> is optional and must
be a subset of the list returned by <a class="reference internal" href="#zipfile.ZipFile.namelist" title="zipfile.ZipFile.namelist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">namelist()</span></code></a>.  <em>pwd</em> is the password
used for encrypted files.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Never extract archives from untrusted sources without prior inspection.
It is possible that files are created outside of <em>path</em>, e.g. members
that have absolute filenames starting with <code class="docutils literal notranslate"><span class="pre">&quot;/&quot;</span></code> or filenames with two
dots <code class="docutils literal notranslate"><span class="pre">&quot;..&quot;</span></code>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.4: </span>The zipfile module attempts to prevent that.  See <a class="reference internal" href="#zipfile.ZipFile.extract" title="zipfile.ZipFile.extract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code></a> note.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.printdir">
<code class="descclassname">ZipFile.</code><code class="descname">printdir</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.printdir" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a table of contents for the archive to <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.setpassword">
<code class="descclassname">ZipFile.</code><code class="descname">setpassword</code><span class="sig-paren">(</span><em>pwd</em><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.setpassword" title="Permalink to this definition">¶</a></dt>
<dd><p>Set <em>pwd</em> as default password to extract encrypted files.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.read">
<code class="descclassname">ZipFile.</code><code class="descname">read</code><span class="sig-paren">(</span><em>name</em><span class="optional">[</span>, <em>pwd</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.read" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the bytes of the file <em>name</em> in the archive.  <em>name</em> is the name of the
file in the archive, or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object.  The archive must be open for
read or append. <em>pwd</em> is the password used for encrypted  files and, if specified,
it will override the default password set with <a class="reference internal" href="#zipfile.ZipFile.setpassword" title="zipfile.ZipFile.setpassword"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setpassword()</span></code></a>.  Calling
<a class="reference internal" href="#zipfile.ZipFile.read" title="zipfile.ZipFile.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> on a closed ZipFile  will raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><em>pwd</em> was added, and <em>name</em> can now be a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> object.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.testzip">
<code class="descclassname">ZipFile.</code><code class="descname">testzip</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.testzip" title="Permalink to this definition">¶</a></dt>
<dd><p>Read all the files in the archive and check their CRC’s and file headers.
Return the name of the first bad file, or else return <code class="docutils literal notranslate"><span class="pre">None</span></code>. Calling
<a class="reference internal" href="#zipfile.ZipFile.testzip" title="zipfile.ZipFile.testzip"><code class="xref py py-meth docutils literal notranslate"><span class="pre">testzip()</span></code></a> on a closed ZipFile will raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.write">
<code class="descclassname">ZipFile.</code><code class="descname">write</code><span class="sig-paren">(</span><em>filename</em><span class="optional">[</span>, <em>arcname</em><span class="optional">[</span>, <em>compress_type</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.write" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the file named <em>filename</em> to the archive, giving it the archive name
<em>arcname</em> (by default, this will be the same as <em>filename</em>, but without a drive
letter and with leading path separators removed).  If given, <em>compress_type</em>
overrides the value given for the <em>compression</em> parameter to the constructor for
the new entry.  The archive must be open with mode <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a'</span></code> – calling
<a class="reference internal" href="#zipfile.ZipFile.write" title="zipfile.ZipFile.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> on a ZipFile created with mode <code class="docutils literal notranslate"><span class="pre">'r'</span></code> will raise a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.  Calling  <a class="reference internal" href="#zipfile.ZipFile.write" title="zipfile.ZipFile.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> on a closed ZipFile will raise a
<a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">There is no official file name encoding for ZIP files. If you have unicode file
names, you must convert them to byte strings in your desired encoding before
passing them to <a class="reference internal" href="#zipfile.ZipFile.write" title="zipfile.ZipFile.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a>. WinZip interprets all file names as encoded in
CP437, also known as DOS Latin.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Archive names should be relative to the archive root, that is, they should not
start with a path separator.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If <code class="docutils literal notranslate"><span class="pre">arcname</span></code> (or <code class="docutils literal notranslate"><span class="pre">filename</span></code>, if <code class="docutils literal notranslate"><span class="pre">arcname</span></code> is  not given) contains a null
byte, the name of the file in the archive will be truncated at the null byte.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="zipfile.ZipFile.writestr">
<code class="descclassname">ZipFile.</code><code class="descname">writestr</code><span class="sig-paren">(</span><em>zinfo_or_arcname</em>, <em>bytes</em><span class="optional">[</span>, <em>compress_type</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.ZipFile.writestr" title="Permalink to this definition">¶</a></dt>
<dd><p>Write the string <em>bytes</em> to the archive; <em>zinfo_or_arcname</em> is either the file
name it will be given in the archive, or a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> instance.  If it’s
an instance, at least the filename, date, and time must be given.  If it’s a
name, the date and time is set to the current date and time. The archive must be
opened with mode <code class="docutils literal notranslate"><span class="pre">'w'</span></code> or <code class="docutils literal notranslate"><span class="pre">'a'</span></code> – calling  <a class="reference internal" href="#zipfile.ZipFile.writestr" title="zipfile.ZipFile.writestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writestr()</span></code></a> on a ZipFile
created with mode <code class="docutils literal notranslate"><span class="pre">'r'</span></code>  will raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.  Calling
<a class="reference internal" href="#zipfile.ZipFile.writestr" title="zipfile.ZipFile.writestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writestr()</span></code></a> on a closed ZipFile will raise a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.</p>
<p>If given, <em>compress_type</em> overrides the value given for the <em>compression</em>
parameter to the constructor for the new entry, or in the <em>zinfo_or_arcname</em>
(if that is a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> instance).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">When passing a <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> instance as the <em>zinfo_or_arcname</em> parameter,
the compression method used will be that specified in the <em>compress_type</em>
member of the given <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> instance.  By default, the
<a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> constructor sets this member to <a class="reference internal" href="#zipfile.ZIP_STORED" title="zipfile.ZIP_STORED"><code class="xref py py-const docutils literal notranslate"><span class="pre">ZIP_STORED</span></code></a>.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The <em>compress_type</em> argument.</p>
</div>
</dd></dl>

<p>The following data attributes are also available:</p>
<dl class="attribute">
<dt id="zipfile.ZipFile.debug">
<code class="descclassname">ZipFile.</code><code class="descname">debug</code><a class="headerlink" href="#zipfile.ZipFile.debug" title="Permalink to this definition">¶</a></dt>
<dd><p>The level of debug output to use.  This may be set from <code class="docutils literal notranslate"><span class="pre">0</span></code> (the default, no
output) to <code class="docutils literal notranslate"><span class="pre">3</span></code> (the most output).  Debugging information is written to
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipFile.comment">
<code class="descclassname">ZipFile.</code><code class="descname">comment</code><a class="headerlink" href="#zipfile.ZipFile.comment" title="Permalink to this definition">¶</a></dt>
<dd><p>The comment text associated with the ZIP file.  If assigning a comment to a
<a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> instance created with mode ‘a’ or ‘w’, this should be a
string no longer than 65535 bytes.  Comments longer than this will be
truncated in the written archive when <a class="reference internal" href="#zipfile.ZipFile.close" title="zipfile.ZipFile.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> is called.</p>
</dd></dl>

</div>
<div class="section" id="pyzipfile-objects">
<span id="id2"></span><h2>12.4.2. PyZipFile Objects<a class="headerlink" href="#pyzipfile-objects" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#zipfile.PyZipFile" title="zipfile.PyZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">PyZipFile</span></code></a> constructor takes the same parameters as the
<a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> constructor.  Instances have one method in addition to those of
<a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> objects.</p>
<dl class="method">
<dt id="zipfile.PyZipFile.writepy">
<code class="descclassname">PyZipFile.</code><code class="descname">writepy</code><span class="sig-paren">(</span><em>pathname</em><span class="optional">[</span>, <em>basename</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipfile.PyZipFile.writepy" title="Permalink to this definition">¶</a></dt>
<dd><p>Search for files <code class="file docutils literal notranslate"><span class="pre">*.py</span></code> and add the corresponding file to the archive.
The corresponding file is a <code class="file docutils literal notranslate"><span class="pre">*.pyo</span></code> file if available, else a
<code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code> file, compiling if necessary.  If the pathname is a file, the
filename must end with <code class="file docutils literal notranslate"><span class="pre">.py</span></code>, and just the (corresponding
<code class="file docutils literal notranslate"><span class="pre">*.py[co]</span></code>) file is added at the top level (no path information).  If the
pathname is a file that does not end with <code class="file docutils literal notranslate"><span class="pre">.py</span></code>, a <a class="reference internal" href="exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>
will be raised.  If it is a directory, and the directory is not a package
directory, then all the files <code class="file docutils literal notranslate"><span class="pre">*.py[co]</span></code> are added at the top level.  If
the directory is a package directory, then all <code class="file docutils literal notranslate"><span class="pre">*.py[co]</span></code> are added under
the package name as a file path, and if any subdirectories are package
directories, all of these are added recursively.  <em>basename</em> is intended for
internal use only.  The <a class="reference internal" href="#zipfile.PyZipFile.writepy" title="zipfile.PyZipFile.writepy"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writepy()</span></code></a> method makes archives with file names
like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">string</span><span class="o">.</span><span class="n">pyc</span>                                <span class="c1"># Top level name</span>
<span class="n">test</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">pyc</span>                         <span class="c1"># Package directory</span>
<span class="n">test</span><span class="o">/</span><span class="n">test_support</span><span class="o">.</span><span class="n">pyc</span>                          <span class="c1"># Module test.test_support</span>
<span class="n">test</span><span class="o">/</span><span class="n">bogus</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">pyc</span>                   <span class="c1"># Subpackage directory</span>
<span class="n">test</span><span class="o">/</span><span class="n">bogus</span><span class="o">/</span><span class="n">myfile</span><span class="o">.</span><span class="n">pyc</span>                     <span class="c1"># Submodule test.bogus.myfile</span>
</pre></div>
</div>
</dd></dl>

</div>
<div class="section" id="zipinfo-objects">
<span id="id3"></span><h2>12.4.3. ZipInfo Objects<a class="headerlink" href="#zipinfo-objects" title="Permalink to this headline">¶</a></h2>
<p>Instances of the <a class="reference internal" href="#zipfile.ZipInfo" title="zipfile.ZipInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code></a> class are returned by the <a class="reference internal" href="#zipfile.ZipFile.getinfo" title="zipfile.ZipFile.getinfo"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getinfo()</span></code></a> and
<a class="reference internal" href="#zipfile.ZipFile.infolist" title="zipfile.ZipFile.infolist"><code class="xref py py-meth docutils literal notranslate"><span class="pre">infolist()</span></code></a> methods of <a class="reference internal" href="#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> objects.  Each object stores
information about a single member of the ZIP archive.</p>
<p>Instances have the following attributes:</p>
<dl class="attribute">
<dt id="zipfile.ZipInfo.filename">
<code class="descclassname">ZipInfo.</code><code class="descname">filename</code><a class="headerlink" href="#zipfile.ZipInfo.filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Name of the file in the archive.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.date_time">
<code class="descclassname">ZipInfo.</code><code class="descname">date_time</code><a class="headerlink" href="#zipfile.ZipInfo.date_time" title="Permalink to this definition">¶</a></dt>
<dd><p>The time and date of the last modification to the archive member.  This is a
tuple of six values:</p>
<table border="1" class="docutils">
<colgroup>
<col width="21%" />
<col width="79%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Index</th>
<th class="head">Value</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">0</span></code></td>
<td>Year (&gt;= 1980)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">1</span></code></td>
<td>Month (one-based)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">2</span></code></td>
<td>Day of month (one-based)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">3</span></code></td>
<td>Hours (zero-based)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">4</span></code></td>
<td>Minutes (zero-based)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">5</span></code></td>
<td>Seconds (zero-based)</td>
</tr>
</tbody>
</table>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The ZIP file format does not support timestamps before 1980.</p>
</div>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.compress_type">
<code class="descclassname">ZipInfo.</code><code class="descname">compress_type</code><a class="headerlink" href="#zipfile.ZipInfo.compress_type" title="Permalink to this definition">¶</a></dt>
<dd><p>Type of compression for the archive member.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.comment">
<code class="descclassname">ZipInfo.</code><code class="descname">comment</code><a class="headerlink" href="#zipfile.ZipInfo.comment" title="Permalink to this definition">¶</a></dt>
<dd><p>Comment for the individual archive member.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.extra">
<code class="descclassname">ZipInfo.</code><code class="descname">extra</code><a class="headerlink" href="#zipfile.ZipInfo.extra" title="Permalink to this definition">¶</a></dt>
<dd><p>Expansion field data.  The <a class="reference external" href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">PKZIP Application Note</a> contains
some comments on the internal structure of the data contained in this string.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.create_system">
<code class="descclassname">ZipInfo.</code><code class="descname">create_system</code><a class="headerlink" href="#zipfile.ZipInfo.create_system" title="Permalink to this definition">¶</a></dt>
<dd><p>System which created ZIP archive.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.create_version">
<code class="descclassname">ZipInfo.</code><code class="descname">create_version</code><a class="headerlink" href="#zipfile.ZipInfo.create_version" title="Permalink to this definition">¶</a></dt>
<dd><p>PKZIP version which created ZIP archive.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.extract_version">
<code class="descclassname">ZipInfo.</code><code class="descname">extract_version</code><a class="headerlink" href="#zipfile.ZipInfo.extract_version" title="Permalink to this definition">¶</a></dt>
<dd><p>PKZIP version needed to extract archive.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.reserved">
<code class="descclassname">ZipInfo.</code><code class="descname">reserved</code><a class="headerlink" href="#zipfile.ZipInfo.reserved" title="Permalink to this definition">¶</a></dt>
<dd><p>Must be zero.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.flag_bits">
<code class="descclassname">ZipInfo.</code><code class="descname">flag_bits</code><a class="headerlink" href="#zipfile.ZipInfo.flag_bits" title="Permalink to this definition">¶</a></dt>
<dd><p>ZIP flag bits.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.volume">
<code class="descclassname">ZipInfo.</code><code class="descname">volume</code><a class="headerlink" href="#zipfile.ZipInfo.volume" title="Permalink to this definition">¶</a></dt>
<dd><p>Volume number of file header.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.internal_attr">
<code class="descclassname">ZipInfo.</code><code class="descname">internal_attr</code><a class="headerlink" href="#zipfile.ZipInfo.internal_attr" title="Permalink to this definition">¶</a></dt>
<dd><p>Internal attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.external_attr">
<code class="descclassname">ZipInfo.</code><code class="descname">external_attr</code><a class="headerlink" href="#zipfile.ZipInfo.external_attr" title="Permalink to this definition">¶</a></dt>
<dd><p>External file attributes.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.header_offset">
<code class="descclassname">ZipInfo.</code><code class="descname">header_offset</code><a class="headerlink" href="#zipfile.ZipInfo.header_offset" title="Permalink to this definition">¶</a></dt>
<dd><p>Byte offset to the file header.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.CRC">
<code class="descclassname">ZipInfo.</code><code class="descname">CRC</code><a class="headerlink" href="#zipfile.ZipInfo.CRC" title="Permalink to this definition">¶</a></dt>
<dd><p>CRC-32 of the uncompressed file.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.compress_size">
<code class="descclassname">ZipInfo.</code><code class="descname">compress_size</code><a class="headerlink" href="#zipfile.ZipInfo.compress_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Size of the compressed data.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipfile.ZipInfo.file_size">
<code class="descclassname">ZipInfo.</code><code class="descname">file_size</code><a class="headerlink" href="#zipfile.ZipInfo.file_size" title="Permalink to this definition">¶</a></dt>
<dd><p>Size of the uncompressed file.</p>
</dd></dl>

</div>
<div class="section" id="command-line-interface">
<span id="zipfile-commandline"></span><h2>12.4.4. Command-Line Interface<a class="headerlink" href="#command-line-interface" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module provides a simple command-line interface to interact
with ZIP archives.</p>
<p>If you want to create a new ZIP archive, specify its name after the <a class="reference internal" href="#cmdoption-zipfile-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a>
option and then list the filename(s) that should be included:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python -m zipfile -c monty.zip spam.txt eggs.txt
</pre></div>
</div>
<p>Passing a directory is also acceptable:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python -m zipfile -c monty.zip life-of-brian_1979/
</pre></div>
</div>
<p>If you want to extract a ZIP archive into the specified directory, use
the <a class="reference internal" href="#cmdoption-zipfile-e"><code class="xref std std-option docutils literal notranslate"><span class="pre">-e</span></code></a> option:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python -m zipfile -e monty.zip target-dir/
</pre></div>
</div>
<p>For a list of the files in a ZIP archive, use the <a class="reference internal" href="#cmdoption-zipfile-l"><code class="xref std std-option docutils literal notranslate"><span class="pre">-l</span></code></a> option:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python -m zipfile -l monty.zip
</pre></div>
</div>
<div class="section" id="command-line-options">
<h3>12.4.4.1. Command-line options<a class="headerlink" href="#command-line-options" title="Permalink to this headline">¶</a></h3>
<dl class="cmdoption">
<dt id="cmdoption-zipfile-l">
<code class="descname">-l</code><code class="descclassname"> &lt;zipfile&gt;</code><a class="headerlink" href="#cmdoption-zipfile-l" title="Permalink to this definition">¶</a></dt>
<dd><p>List files in a zipfile.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-zipfile-c">
<code class="descname">-c</code><code class="descclassname"> &lt;zipfile&gt; &lt;source1&gt; ... &lt;sourceN&gt;</code><a class="headerlink" href="#cmdoption-zipfile-c" title="Permalink to this definition">¶</a></dt>
<dd><p>Create zipfile from source files.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-zipfile-e">
<code class="descname">-e</code><code class="descclassname"> &lt;zipfile&gt; &lt;output_dir&gt;</code><a class="headerlink" href="#cmdoption-zipfile-e" title="Permalink to this definition">¶</a></dt>
<dd><p>Extract zipfile into target directory.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-zipfile-t">
<code class="descname">-t</code><code class="descclassname"> &lt;zipfile&gt;</code><a class="headerlink" href="#cmdoption-zipfile-t" title="Permalink to this definition">¶</a></dt>
<dd><p>Test whether the zipfile is valid or not.</p>
</dd></dl>

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a><ul>
<li><a class="reference internal" href="#zipfile-objects">12.4.1. ZipFile Objects</a></li>
<li><a class="reference internal" href="#pyzipfile-objects">12.4.2. PyZipFile Objects</a></li>
<li><a class="reference internal" href="#zipinfo-objects">12.4.3. ZipInfo Objects</a></li>
<li><a class="reference internal" href="#command-line-interface">12.4.4. Command-Line Interface</a><ul>
<li><a class="reference internal" href="#command-line-options">12.4.4.1. Command-line options</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="bz2.html"
                        title="previous chapter">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="tarfile.html"
                        title="next chapter">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/zipfile.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="tarfile.html" title="12.5. tarfile — Read and write tar archive files"
             >next</a> |</li>
        <li class="right" >
          <a href="bz2.html" title="12.3. bz2 — Compression compatible with bzip2"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" >12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\n5v\�X�Xhtml/library/zipimport.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>31.4. zipimport — Import modules from Zip archives &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="31.5. pkgutil — Package extension utility" href="pkgutil.html" />
    <link rel="prev" title="31.3. imputil — Import utilities" href="imputil.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/zipimport.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pkgutil.html" title="31.5. pkgutil — Package extension utility"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="imputil.html" title="31.3. imputil — Import utilities"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" accesskey="U">31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-zipimport">
<span id="zipimport-import-modules-from-zip-archives"></span><h1>31.4. <a class="reference internal" href="#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> — Import modules from Zip archives<a class="headerlink" href="#module-zipimport" title="Permalink to this headline">¶</a></h1>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
<p>This module adds the ability to import Python modules (<code class="file docutils literal notranslate"><span class="pre">*.py</span></code>,
<code class="file docutils literal notranslate"><span class="pre">*.py[co]</span></code>) and packages from ZIP-format archives. It is usually not
needed to use the <a class="reference internal" href="#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module explicitly; it is automatically used
by the built-in <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> mechanism for <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> items that are paths
to ZIP archives.</p>
<p>Typically, <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is a list of directory names as strings.  This module
also allows an item of <a class="reference internal" href="sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> to be a string naming a ZIP file archive.
The ZIP archive can contain a subdirectory structure to support package imports,
and a path within the archive can be specified to only import from a
subdirectory.  For example, the path <code class="file docutils literal notranslate"><span class="pre">example.zip/lib/</span></code> would only
import from the <code class="file docutils literal notranslate"><span class="pre">lib/</span></code> subdirectory within the archive.</p>
<p>Any files may be present in the ZIP archive, but only files <code class="file docutils literal notranslate"><span class="pre">.py</span></code> and
<code class="file docutils literal notranslate"><span class="pre">.py[co]</span></code> are available for import.  ZIP import of dynamic modules
(<code class="file docutils literal notranslate"><span class="pre">.pyd</span></code>, <code class="file docutils literal notranslate"><span class="pre">.so</span></code>) is disallowed. Note that if an archive only contains
<code class="file docutils literal notranslate"><span class="pre">.py</span></code> files, Python will not attempt to modify the archive by adding the
corresponding <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> file, meaning that if a ZIP archive
doesn’t contain <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files, importing may be rather slow.</p>
<p>Using the built-in <a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> function will fail if called on a module
loaded from a ZIP archive; it is unlikely that <a class="reference internal" href="functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a> would be needed,
since this would imply that the ZIP has been altered during runtime.</p>
<p>ZIP archives with an archive comment are currently not supported.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT">PKZIP Application Note</a></dt>
<dd>Documentation on the ZIP file format by Phil Katz, the creator of the format and
algorithms used.</dd>
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0273"><strong>PEP 273</strong></a> - Import Modules from Zip Archives</dt>
<dd>Written by James C. Ahlstrom, who also provided an implementation. Python 2.3
follows the specification in PEP 273, but uses an implementation written by Just
van Rossum that uses the import hooks described in PEP 302.</dd>
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> - New Import Hooks</dt>
<dd>The PEP to add the import hooks that help this module work.</dd>
</dl>
</div>
<p>This module defines an exception:</p>
<dl class="exception">
<dt id="zipimport.ZipImportError">
<em class="property">exception </em><code class="descclassname">zipimport.</code><code class="descname">ZipImportError</code><a class="headerlink" href="#zipimport.ZipImportError" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised by zipimporter objects. It’s a subclass of <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>,
so it can be caught as <a class="reference internal" href="exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>, too.</p>
</dd></dl>

<div class="section" id="zipimporter-objects">
<span id="id1"></span><h2>31.4.1. zipimporter Objects<a class="headerlink" href="#zipimporter-objects" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#zipimport.zipimporter" title="zipimport.zipimporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">zipimporter</span></code></a> is the class for importing ZIP files.</p>
<dl class="class">
<dt id="zipimport.zipimporter">
<em class="property">class </em><code class="descclassname">zipimport.</code><code class="descname">zipimporter</code><span class="sig-paren">(</span><em>archivepath</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a new zipimporter instance. <em>archivepath</em> must be a path to a ZIP
file, or to a specific path within a ZIP file.  For example, an <em>archivepath</em>
of <code class="file docutils literal notranslate"><span class="pre">foo/bar.zip/lib</span></code> will look for modules in the <code class="file docutils literal notranslate"><span class="pre">lib</span></code> directory
inside the ZIP file <code class="file docutils literal notranslate"><span class="pre">foo/bar.zip</span></code> (provided that it exists).</p>
<p><a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> is raised if <em>archivepath</em> doesn’t point to a valid ZIP
archive.</p>
<dl class="method">
<dt id="zipimport.zipimporter.find_module">
<code class="descname">find_module</code><span class="sig-paren">(</span><em>fullname</em><span class="optional">[</span>, <em>path</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.find_module" title="Permalink to this definition">¶</a></dt>
<dd><p>Search for a module specified by <em>fullname</em>. <em>fullname</em> must be the fully
qualified (dotted) module name. It returns the zipimporter instance itself
if the module was found, or <a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if it wasn’t. The optional
<em>path</em> argument is ignored—it’s there for compatibility with the
importer protocol.</p>
</dd></dl>

<dl class="method">
<dt id="zipimport.zipimporter.get_code">
<code class="descname">get_code</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.get_code" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the code object for the specified module. Raise
<a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> if the module couldn’t be found.</p>
</dd></dl>

<dl class="method">
<dt id="zipimport.zipimporter.get_data">
<code class="descname">get_data</code><span class="sig-paren">(</span><em>pathname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.get_data" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the data associated with <em>pathname</em>. Raise <a class="reference internal" href="exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> if the
file wasn’t found.</p>
</dd></dl>

<dl class="method">
<dt id="zipimport.zipimporter.get_filename">
<code class="descname">get_filename</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.get_filename" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the value <code class="docutils literal notranslate"><span class="pre">__file__</span></code> would be set to if the specified module
was imported. Raise <a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> if the module couldn’t be
found.</p>
</dd></dl>

<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.</span></p>
</div>
<dl class="method">
<dt id="zipimport.zipimporter.get_source">
<code class="descname">get_source</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.get_source" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the source code for the specified module. Raise
<a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> if the module couldn’t be found, return
<a class="reference internal" href="constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> if the archive does contain the module, but has no source
for it.</p>
</dd></dl>

<dl class="method">
<dt id="zipimport.zipimporter.is_package">
<code class="descname">is_package</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.is_package" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the module specified by <em>fullname</em> is a package. Raise
<a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> if the module couldn’t be found.</p>
</dd></dl>

<dl class="method">
<dt id="zipimport.zipimporter.load_module">
<code class="descname">load_module</code><span class="sig-paren">(</span><em>fullname</em><span class="sig-paren">)</span><a class="headerlink" href="#zipimport.zipimporter.load_module" title="Permalink to this definition">¶</a></dt>
<dd><p>Load the module specified by <em>fullname</em>. <em>fullname</em> must be the fully
qualified (dotted) module name. It returns the imported module, or raises
<a class="reference internal" href="#zipimport.ZipImportError" title="zipimport.ZipImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZipImportError</span></code></a> if it wasn’t found.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipimport.zipimporter.archive">
<code class="descname">archive</code><a class="headerlink" href="#zipimport.zipimporter.archive" title="Permalink to this definition">¶</a></dt>
<dd><p>The file name of the importer’s associated ZIP file, without a possible
subpath.</p>
</dd></dl>

<dl class="attribute">
<dt id="zipimport.zipimporter.prefix">
<code class="descname">prefix</code><a class="headerlink" href="#zipimport.zipimporter.prefix" title="Permalink to this definition">¶</a></dt>
<dd><p>The subpath within the ZIP file where modules are searched.  This is the
empty string for zipimporter objects which point to the root of the ZIP
file.</p>
</dd></dl>

<p>The <a class="reference internal" href="#zipimport.zipimporter.archive" title="zipimport.zipimporter.archive"><code class="xref py py-attr docutils literal notranslate"><span class="pre">archive</span></code></a> and <a class="reference internal" href="#zipimport.zipimporter.prefix" title="zipimport.zipimporter.prefix"><code class="xref py py-attr docutils literal notranslate"><span class="pre">prefix</span></code></a> attributes, when combined with a
slash, equal the original <em>archivepath</em> argument given to the
<a class="reference internal" href="#zipimport.zipimporter" title="zipimport.zipimporter"><code class="xref py py-class docutils literal notranslate"><span class="pre">zipimporter</span></code></a> constructor.</p>
</dd></dl>

</div>
<div class="section" id="examples">
<span id="zipimport-examples"></span><h2>31.4.2. Examples<a class="headerlink" href="#examples" title="Permalink to this headline">¶</a></h2>
<p>Here is an example that imports a module from a ZIP archive - note that the
<a class="reference internal" href="#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module is not explicitly used.</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> unzip -l example.zip
<span class="go">Archive:  example.zip</span>
<span class="go">  Length     Date   Time    Name</span>
<span class="go"> --------    ----   ----    ----</span>
<span class="go">     8467  11-26-02 22:30   jwzthreading.py</span>
<span class="go"> --------                   -------</span>
<span class="go">     8467                   1 file</span>
<span class="gp">$</span> ./python
<span class="go">Python 2.3 (#1, Aug 1 2003, 19:54:32)</span>
<span class="gp">&gt;</span>&gt;&gt; import sys
<span class="gp">&gt;</span>&gt;&gt; sys.path.insert<span class="o">(</span><span class="m">0</span>, <span class="s1">&#39;example.zip&#39;</span><span class="o">)</span>  <span class="c1"># Add .zip file to front of path</span>
<span class="gp">&gt;</span>&gt;&gt; import jwzthreading
<span class="gp">&gt;</span>&gt;&gt; jwzthreading.__file__
<span class="go">&#39;example.zip/jwzthreading.py&#39;</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a><ul>
<li><a class="reference internal" href="#zipimporter-objects">31.4.1. zipimporter Objects</a></li>
<li><a class="reference internal" href="#examples">31.4.2. Examples</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="imputil.html"
                        title="previous chapter">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="pkgutil.html"
                        title="next chapter">31.5. <code class="docutils literal notranslate"><span class="pre">pkgutil</span></code> — Package extension utility</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/zipimport.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="pkgutil.html" title="31.5. pkgutil — Package extension utility"
             >next</a> |</li>
        <li class="right" >
          <a href="imputil.html" title="31.3. imputil — Import utilities"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="modules.html" >31. Importing Modules</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\¸C��y�yhtml/library/zlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12.1. zlib — Compression compatible with gzip &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12.2. gzip — Support for gzip files" href="gzip.html" />
    <link rel="prev" title="12. Data Compression and Archiving" href="archiving.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/zlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gzip.html" title="12.2. gzip — Support for gzip files"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="archiving.html" title="12. Data Compression and Archiving"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" accesskey="U">12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="module-zlib">
<span id="zlib-compression-compatible-with-gzip"></span><h1>12.1. <a class="reference internal" href="#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> — Compression compatible with <strong class="program">gzip</strong><a class="headerlink" href="#module-zlib" title="Permalink to this headline">¶</a></h1>
<p>For applications that require data compression, the functions in this module
allow compression and decompression, using the zlib library. The zlib library
has its own home page at <a class="reference external" href="http://www.zlib.net">http://www.zlib.net</a>.   There are known
incompatibilities between the Python module and versions of the zlib library
earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using
1.1.4 or later.</p>
<p>zlib’s functions have many options and often need to be used in a particular
order.  This documentation doesn’t attempt to cover all of the permutations;
consult the zlib manual at <a class="reference external" href="http://www.zlib.net/manual.html">http://www.zlib.net/manual.html</a> for authoritative
information.</p>
<p>For reading and writing <code class="docutils literal notranslate"><span class="pre">.gz</span></code> files see the <a class="reference internal" href="gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module.</p>
<p>The available exception and functions in this module are:</p>
<dl class="exception">
<dt id="zlib.error">
<em class="property">exception </em><code class="descclassname">zlib.</code><code class="descname">error</code><a class="headerlink" href="#zlib.error" title="Permalink to this definition">¶</a></dt>
<dd><p>Exception raised on compression and decompression errors.</p>
</dd></dl>

<dl class="function">
<dt id="zlib.adler32">
<code class="descclassname">zlib.</code><code class="descname">adler32</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.adler32" title="Permalink to this definition">¶</a></dt>
<dd><p>Computes an Adler-32 checksum of <em>data</em>.  (An Adler-32 checksum is almost as
reliable as a CRC32 but can be computed much more quickly.)  If <em>value</em> is
present, it is used as the starting value of the checksum; otherwise, a fixed
default value is used.  This allows computing a running checksum over the
concatenation of several inputs.  The algorithm is not cryptographically
strong, and should not be used for authentication or digital signatures.  Since
the algorithm is designed for use as a checksum algorithm, it is not suitable
for use as a general hash algorithm.</p>
<p>This function always returns an integer object.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To generate the same numeric value across all Python versions and
platforms use adler32(data) &amp; 0xffffffff.  If you are only using
the checksum in packed binary format this is not necessary as the
return value is the correct 32bit binary representation
regardless of sign.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The return value is in the range [-2**31, 2**31-1]
regardless of platform.  In older versions the value is
signed on some platforms and unsigned on others.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.0: </span>The return value is unsigned and in the range [0, 2**32-1]
regardless of platform.</p>
</div>
<dl class="function">
<dt id="zlib.compress">
<code class="descclassname">zlib.</code><code class="descname">compress</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>level</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.compress" title="Permalink to this definition">¶</a></dt>
<dd><p>Compresses the data in <em>string</em>, returning a string contained compressed data.
<em>level</em> is an integer from <code class="docutils literal notranslate"><span class="pre">0</span></code> to <code class="docutils literal notranslate"><span class="pre">9</span></code> controlling the level of compression;
<code class="docutils literal notranslate"><span class="pre">1</span></code> is fastest and produces the least compression, <code class="docutils literal notranslate"><span class="pre">9</span></code> is slowest and
produces the most.  <code class="docutils literal notranslate"><span class="pre">0</span></code> is no compression.  The default value is <code class="docutils literal notranslate"><span class="pre">6</span></code>.
Raises the <a class="reference internal" href="#zlib.error" title="zlib.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception if any error occurs.</p>
</dd></dl>

<dl class="function">
<dt id="zlib.compressobj">
<code class="descclassname">zlib.</code><code class="descname">compressobj</code><span class="sig-paren">(</span><span class="optional">[</span><em>level</em><span class="optional">[</span>, <em>method</em><span class="optional">[</span>, <em>wbits</em><span class="optional">[</span>, <em>memlevel</em><span class="optional">[</span>, <em>strategy</em><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.compressobj" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a compression object, to be used for compressing data streams that won’t
fit into memory at once.  <em>level</em> is an integer from
<code class="docutils literal notranslate"><span class="pre">0</span></code> to <code class="docutils literal notranslate"><span class="pre">9</span></code> or <code class="docutils literal notranslate"><span class="pre">-1</span></code>, controlling
the level of compression; <code class="docutils literal notranslate"><span class="pre">1</span></code> is fastest and produces the least compression,
<code class="docutils literal notranslate"><span class="pre">9</span></code> is slowest and produces the most.  <code class="docutils literal notranslate"><span class="pre">0</span></code> is no compression.  The default
value is <code class="docutils literal notranslate"><span class="pre">-1</span></code> (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default
compromise between speed and compression (currently equivalent to level 6).</p>
<p><em>method</em> is the compression algorithm. Currently, the only supported value is
<code class="docutils literal notranslate"><span class="pre">DEFLATED</span></code>.</p>
<p>The <em>wbits</em> argument controls the size of the history buffer (or the
“window size”) used when compressing data, and whether a header and
trailer is included in the output.  It can take several ranges of values.
The default is 15.</p>
<ul class="simple">
<li>+9 to +15: The base-two logarithm of the window size, which
therefore ranges between 512 and 32768.  Larger values produce
better compression at the expense of greater memory usage.  The
resulting output will include a zlib-specific header and trailer.</li>
<li>−9 to −15: Uses the absolute value of <em>wbits</em> as the
window size logarithm, while producing a raw output stream with no
header or trailing checksum.</li>
<li>+25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the
window size logarithm, while including a basic <strong class="program">gzip</strong> header
and trailing checksum in the output.</li>
</ul>
<p><em>memlevel</em> controls the amount of memory used for internal compression state.
Valid values range from <code class="docutils literal notranslate"><span class="pre">1</span></code> to <code class="docutils literal notranslate"><span class="pre">9</span></code>. Higher values using more memory,
but are faster and produce smaller output. The default is 8.</p>
<p><em>strategy</em> is used to tune the compression algorithm. Possible values are
<code class="docutils literal notranslate"><span class="pre">Z_DEFAULT_STRATEGY</span></code>, <code class="docutils literal notranslate"><span class="pre">Z_FILTERED</span></code>, and <code class="docutils literal notranslate"><span class="pre">Z_HUFFMAN_ONLY</span></code>. The default
is <code class="docutils literal notranslate"><span class="pre">Z_DEFAULT_STRATEGY</span></code>.</p>
</dd></dl>

<dl class="function">
<dt id="zlib.crc32">
<code class="descclassname">zlib.</code><code class="descname">crc32</code><span class="sig-paren">(</span><em>data</em><span class="optional">[</span>, <em>value</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.crc32" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-0">Computes a CRC (Cyclic Redundancy Check)  checksum of <em>data</em>. If <em>value</em> is
present, it is used as the starting value of the checksum; otherwise, a fixed
default value is used.  This allows computing a running checksum over the
concatenation of several inputs.  The algorithm is not cryptographically
strong, and should not be used for authentication or digital signatures.  Since
the algorithm is designed for use as a checksum algorithm, it is not suitable
for use as a general hash algorithm.</p>
<p>This function always returns an integer object.</p>
</dd></dl>

<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">To generate the same numeric value across all Python versions and
platforms use crc32(data) &amp; 0xffffffff.  If you are only using
the checksum in packed binary format this is not necessary as the
return value is the correct 32bit binary representation
regardless of sign.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The return value is in the range [-2**31, 2**31-1]
regardless of platform.  In older versions the value would be
signed on some platforms and unsigned on others.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 3.0: </span>The return value is unsigned and in the range [0, 2**32-1]
regardless of platform.</p>
</div>
<dl class="function">
<dt id="zlib.decompress">
<code class="descclassname">zlib.</code><code class="descname">decompress</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>wbits</em><span class="optional">[</span>, <em>bufsize</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.decompress" title="Permalink to this definition">¶</a></dt>
<dd><p>Decompresses the data in <em>string</em>, returning a string containing the
uncompressed data.  The <em>wbits</em> parameter depends on
the format of <em>string</em>, and is discussed further below.
If <em>bufsize</em> is given, it is used as the initial size of the output
buffer.  Raises the <a class="reference internal" href="#zlib.error" title="zlib.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception if any error occurs.</p>
<p id="decompress-wbits">The <em>wbits</em> parameter controls the size of the history buffer
(or “window size”), and what header and trailer format is expected.
It is similar to the parameter for <a class="reference internal" href="#zlib.compressobj" title="zlib.compressobj"><code class="xref py py-func docutils literal notranslate"><span class="pre">compressobj()</span></code></a>, but accepts
more ranges of values:</p>
<ul class="simple">
<li>+8 to +15: The base-two logarithm of the window size.  The input
must include a zlib header and trailer.</li>
<li>0: Automatically determine the window size from the zlib header.
Only supported since zlib 1.2.3.5.</li>
<li>−8 to −15: Uses the absolute value of <em>wbits</em> as the window size
logarithm.  The input must be a raw stream with no header or trailer.</li>
<li>+24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as
the window size logarithm.  The input must include a gzip header and
trailer.</li>
<li>+40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as
the window size logarithm, and automatically accepts either
the zlib or gzip format.</li>
</ul>
<p>When decompressing a stream, the window size must not be smaller
than the size originally used to compress the stream; using a too-small
value may result in an <a class="reference internal" href="#zlib.error" title="zlib.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">error</span></code></a> exception. The default <em>wbits</em> value
is 15, which corresponds to the largest window size and requires a zlib
header and trailer to be included.</p>
<p><em>bufsize</em> is the initial size of the buffer used to hold decompressed data.  If
more space is required, the buffer size will be increased as needed, so you
don’t have to get this value exactly right; tuning it will only save a few calls
to <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code>.  The default size is 16384.</p>
</dd></dl>

<dl class="function">
<dt id="zlib.decompressobj">
<code class="descclassname">zlib.</code><code class="descname">decompressobj</code><span class="sig-paren">(</span><span class="optional">[</span><em>wbits</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.decompressobj" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a decompression object, to be used for decompressing data streams that
won’t fit into memory at once.</p>
<p>The <em>wbits</em> parameter controls the size of the history buffer (or the
“window size”), and what header and trailer format is expected.  It has
the same meaning as <a class="reference external" href="#decompress-wbits">described for decompress()</a>.</p>
</dd></dl>

<p>Compression objects support the following methods:</p>
<dl class="method">
<dt id="zlib.Compress.compress">
<code class="descclassname">Compress.</code><code class="descname">compress</code><span class="sig-paren">(</span><em>string</em><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Compress.compress" title="Permalink to this definition">¶</a></dt>
<dd><p>Compress <em>string</em>, returning a string containing compressed data for at least
part of the data in <em>string</em>.  This data should be concatenated to the output
produced by any preceding calls to the <a class="reference internal" href="#zlib.compress" title="zlib.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compress()</span></code></a> method.  Some input may
be kept in internal buffers for later processing.</p>
</dd></dl>

<dl class="method">
<dt id="zlib.Compress.flush">
<code class="descclassname">Compress.</code><code class="descname">flush</code><span class="sig-paren">(</span><span class="optional">[</span><em>mode</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Compress.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>All pending input is processed, and a string containing the remaining compressed
output is returned.  <em>mode</em> can be selected from the constants
<code class="xref py py-const docutils literal notranslate"><span class="pre">Z_SYNC_FLUSH</span></code>,  <code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FULL_FLUSH</span></code>,  or  <code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FINISH</span></code>,
defaulting to <code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FINISH</span></code>.  <code class="xref py py-const docutils literal notranslate"><span class="pre">Z_SYNC_FLUSH</span></code> and
<code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FULL_FLUSH</span></code> allow compressing further strings of data, while
<code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FINISH</span></code> finishes the compressed stream and  prevents compressing any
more data.  After calling <a class="reference internal" href="#zlib.Compress.flush" title="zlib.Compress.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a> with <em>mode</em> set to <code class="xref py py-const docutils literal notranslate"><span class="pre">Z_FINISH</span></code>,
the <a class="reference internal" href="#zlib.compress" title="zlib.compress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">compress()</span></code></a> method cannot be called again; the only realistic action is
to delete the object.</p>
</dd></dl>

<dl class="method">
<dt id="zlib.Compress.copy">
<code class="descclassname">Compress.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Compress.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a copy of the compression object.  This can be used to efficiently
compress a set of data that share a common initial prefix.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<p>Decompression objects support the following methods, and two attributes:</p>
<dl class="attribute">
<dt id="zlib.Decompress.unused_data">
<code class="descclassname">Decompress.</code><code class="descname">unused_data</code><a class="headerlink" href="#zlib.Decompress.unused_data" title="Permalink to this definition">¶</a></dt>
<dd><p>A string which contains any bytes past the end of the compressed data. That is,
this remains <code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code> until the last byte that contains compression data is
available.  If the whole string turned out to contain compressed data, this is
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code>, the empty string.</p>
<p>The only way to determine where a string of compressed data ends is by actually
decompressing it.  This means that when compressed data is contained part of a
larger file, you can only find the end of it by reading data and feeding it
followed by some non-empty string into a decompression object’s
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> method until the <a class="reference internal" href="#zlib.Decompress.unused_data" title="zlib.Decompress.unused_data"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unused_data</span></code></a> attribute is no longer
the empty string.</p>
</dd></dl>

<dl class="attribute">
<dt id="zlib.Decompress.unconsumed_tail">
<code class="descclassname">Decompress.</code><code class="descname">unconsumed_tail</code><a class="headerlink" href="#zlib.Decompress.unconsumed_tail" title="Permalink to this definition">¶</a></dt>
<dd><p>A string that contains any data that was not consumed by the last
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> call because it exceeded the limit for the uncompressed data
buffer.  This data has not yet been seen by the zlib machinery, so you must feed
it (possibly with further data concatenated to it) back to a subsequent
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> method call in order to get correct output.</p>
</dd></dl>

<dl class="method">
<dt id="zlib.Decompress.decompress">
<code class="descclassname">Decompress.</code><code class="descname">decompress</code><span class="sig-paren">(</span><em>string</em><span class="optional">[</span>, <em>max_length</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Decompress.decompress" title="Permalink to this definition">¶</a></dt>
<dd><p>Decompress <em>string</em>, returning a string containing the uncompressed data
corresponding to at least part of the data in <em>string</em>.  This data should be
concatenated to the output produced by any preceding calls to the
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> method.  Some of the input data may be preserved in internal
buffers for later processing.</p>
<p>If the optional parameter <em>max_length</em> is non-zero then the return value will be
no longer than <em>max_length</em>. This may mean that not all of the compressed input
can be processed; and unconsumed data will be stored in the attribute
<a class="reference internal" href="#zlib.Decompress.unconsumed_tail" title="zlib.Decompress.unconsumed_tail"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unconsumed_tail</span></code></a>. This string must be passed to a subsequent call to
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> if decompression is to continue.  If <em>max_length</em> is not
supplied then the whole input is decompressed, and <a class="reference internal" href="#zlib.Decompress.unconsumed_tail" title="zlib.Decompress.unconsumed_tail"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unconsumed_tail</span></code></a> is an
empty string.</p>
</dd></dl>

<dl class="method">
<dt id="zlib.Decompress.flush">
<code class="descclassname">Decompress.</code><code class="descname">flush</code><span class="sig-paren">(</span><span class="optional">[</span><em>length</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Decompress.flush" title="Permalink to this definition">¶</a></dt>
<dd><p>All pending input is processed, and a string containing the remaining
uncompressed output is returned.  After calling <a class="reference internal" href="#zlib.Decompress.flush" title="zlib.Decompress.flush"><code class="xref py py-meth docutils literal notranslate"><span class="pre">flush()</span></code></a>, the
<a class="reference internal" href="#zlib.decompress" title="zlib.decompress"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decompress()</span></code></a> method cannot be called again; the only realistic action is
to delete the object.</p>
<p>The optional parameter <em>length</em> sets the initial size of the output buffer.</p>
</dd></dl>

<dl class="method">
<dt id="zlib.Decompress.copy">
<code class="descclassname">Decompress.</code><code class="descname">copy</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#zlib.Decompress.copy" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns a copy of the decompression object.  This can be used to save the state
of the decompressor midway through the data stream in order to speed up random
seeks into the stream at a future point.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a class="reference internal" href="gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a></dt>
<dd>Reading and writing <strong class="program">gzip</strong>-format files.</dd>
<dt><a class="reference external" href="http://www.zlib.net">http://www.zlib.net</a></dt>
<dd>The zlib library home page.</dd>
<dt><a class="reference external" href="http://www.zlib.net/manual.html">http://www.zlib.net/manual.html</a></dt>
<dd>The zlib manual explains  the semantics and usage of the library’s many
functions.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="archiving.html"
                        title="previous chapter">12. Data Compression and Archiving</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="gzip.html"
                        title="next chapter">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/zlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="gzip.html" title="12.2. gzip — Support for gzip files"
             >next</a> |</li>
        <li class="right" >
          <a href="archiving.html" title="12. Data Compression and Archiving"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="archiving.html" >12. Data Compression and Archiving</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\q�Cs�s�html/library/2to3.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>25.4. 2to3 - Automated Python 2 to 3 code translation &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="25.5. test — Regression tests package for Python" href="test.html" />
    <link rel="prev" title="25.3. unittest — Unit testing framework" href="unittest.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/library/2to3.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="test.html" title="25.5. test — Regression tests package for Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unittest.html" title="25.3. unittest — Unit testing framework"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" accesskey="U">25. Development Tools</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="to3-automated-python-2-to-3-code-translation">
<span id="to3-reference"></span><h1>25.4. 2to3 - Automated Python 2 to 3 code translation<a class="headerlink" href="#to3-automated-python-2-to-3-code-translation" title="Permalink to this headline">¶</a></h1>
<p>2to3 is a Python program that reads Python 2.x source code and applies a series
of <em>fixers</em> to transform it into valid Python 3.x code.  The standard library
contains a rich set of fixers that will handle almost all code.  2to3 supporting
library <a class="reference internal" href="#module-lib2to3" title="lib2to3: the 2to3 library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lib2to3</span></code></a> is, however, a flexible and generic library, so it is
possible to write your own fixers for 2to3.  <a class="reference internal" href="#module-lib2to3" title="lib2to3: the 2to3 library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lib2to3</span></code></a> could also be
adapted to custom applications in which Python code needs to be edited
automatically.</p>
<div class="section" id="using-2to3">
<span id="to3-using"></span><h2>25.4.1. Using 2to3<a class="headerlink" href="#using-2to3" title="Permalink to this headline">¶</a></h2>
<p>2to3 will usually be installed with the Python interpreter as a script.  It is
also located in the <code class="file docutils literal notranslate"><span class="pre">Tools/scripts</span></code> directory of the Python root.</p>
<p>2to3’s basic arguments are a list of files or directories to transform.  The
directories are recursively traversed for Python sources.</p>
<p>Here is a sample Python 2.x source file, <code class="file docutils literal notranslate"><span class="pre">example.py</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">greet</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;Hello, </span><span class="si">{0}</span><span class="s2">!&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="nb">print</span> <span class="s2">&quot;What&#39;s your name?&quot;</span>
<span class="n">name</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">()</span>
<span class="n">greet</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>It can be converted to Python 3.x code via 2to3 on the command line:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 example.py
</pre></div>
</div>
<p>A diff against the original source file is printed.  2to3 can also write the
needed modifications right back to the source file.  (A backup of the original
file is made unless <code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code> is also given.)  Writing the changes back is
enabled with the <code class="xref std std-option docutils literal notranslate"><span class="pre">-w</span></code> flag:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 -w example.py
</pre></div>
</div>
<p>After transformation, <code class="file docutils literal notranslate"><span class="pre">example.py</span></code> looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">greet</span><span class="p">(</span><span class="n">name</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Hello, </span><span class="si">{0}</span><span class="s2">!&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">&quot;What&#39;s your name?&quot;</span><span class="p">)</span>
<span class="n">name</span> <span class="o">=</span> <span class="nb">input</span><span class="p">()</span>
<span class="n">greet</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
</pre></div>
</div>
<p>Comments and exact indentation are preserved throughout the translation process.</p>
<p>By default, 2to3 runs a set of <a class="reference internal" href="#to3-fixers"><span class="std std-ref">predefined fixers</span></a>.  The
<code class="xref std std-option docutils literal notranslate"><span class="pre">-l</span></code> flag lists all available fixers.  An explicit set of fixers to run
can be given with <code class="xref std std-option docutils literal notranslate"><span class="pre">-f</span></code>.  Likewise the <code class="xref std std-option docutils literal notranslate"><span class="pre">-x</span></code> explicitly disables a
fixer.  The following example runs only the <code class="docutils literal notranslate"><span class="pre">imports</span></code> and <code class="docutils literal notranslate"><span class="pre">has_key</span></code> fixers:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 -f imports -f has_key example.py
</pre></div>
</div>
<p>This command runs every fixer except the <code class="docutils literal notranslate"><span class="pre">apply</span></code> fixer:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 -x apply example.py
</pre></div>
</div>
<p>Some fixers are <em>explicit</em>, meaning they aren’t run by default and must be
listed on the command line to be run.  Here, in addition to the default fixers,
the <code class="docutils literal notranslate"><span class="pre">idioms</span></code> fixer is run:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 -f all -f idioms example.py
</pre></div>
</div>
<p>Notice how passing <code class="docutils literal notranslate"><span class="pre">all</span></code> enables all default fixers.</p>
<p>Sometimes 2to3 will find a place in your source code that needs to be changed,
but 2to3 cannot fix automatically.  In this case, 2to3 will print a warning
beneath the diff for a file.  You should address the warning in order to have
compliant 3.x code.</p>
<p>2to3 can also refactor doctests.  To enable this mode, use the <code class="xref std std-option docutils literal notranslate"><span class="pre">-d</span></code>
flag.  Note that <em>only</em> doctests will be refactored.  This also doesn’t require
the module to be valid Python.  For example, doctest like examples in a reST
document could also be refactored with this option.</p>
<p>The <code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code> option enables output of more information on the translation
process.</p>
<p>Since some print statements can be parsed as function calls or statements, 2to3
cannot always read files containing the print function.  When 2to3 detects the
presence of the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">print_function</span></code> compiler directive, it
modifies its internal grammar to interpret <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> as a function.  This
change can also be enabled manually with the <code class="xref std std-option docutils literal notranslate"><span class="pre">-p</span></code> flag.  Use
<code class="xref std std-option docutils literal notranslate"><span class="pre">-p</span></code> to run fixers on code that already has had its print statements
converted.</p>
<p>The <code class="xref std std-option docutils literal notranslate"><span class="pre">-o</span></code> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--output-dir</span></code> option allows specification of an
alternate directory for processed output files to be written to.  The
<code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code> flag is required when using this as backup files do not make sense
when not overwriting the input files.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.3: </span>The <code class="xref std std-option docutils literal notranslate"><span class="pre">-o</span></code> option was added.</p>
</div>
<p>The <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--write-unchanged-files</span></code> flag tells 2to3 to always
write output files even if no changes were required to the file.  This is most
useful with <code class="xref std std-option docutils literal notranslate"><span class="pre">-o</span></code> so that an entire Python source tree is copied with
translation from one directory to another.
This option implies the <code class="xref std std-option docutils literal notranslate"><span class="pre">-w</span></code> flag as it would not make sense otherwise.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.3: </span>The <code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code> flag was added.</p>
</div>
<p>The <code class="xref std std-option docutils literal notranslate"><span class="pre">--add-suffix</span></code> option specifies a string to append to all output
filenames.  The <code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code> flag is required when specifying this as backups
are not necessary when writing to different filenames.  Example:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 -n -W --add-suffix<span class="o">=</span><span class="m">3</span> example.py
</pre></div>
</div>
<p>Will cause a converted file named <code class="docutils literal notranslate"><span class="pre">example.py3</span></code> to be written.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.3: </span>The <code class="xref std std-option docutils literal notranslate"><span class="pre">--add-suffix</span></code> option was added.</p>
</div>
<p>To translate an entire project from one directory tree to another use:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> 2to3 --output-dir<span class="o">=</span>python3-version/mycode -W -n python2-version/mycode
</pre></div>
</div>
</div>
<div class="section" id="fixers">
<span id="to3-fixers"></span><h2>25.4.2. Fixers<a class="headerlink" href="#fixers" title="Permalink to this headline">¶</a></h2>
<p>Each step of transforming code is encapsulated in a fixer.  The command <code class="docutils literal notranslate"><span class="pre">2to3</span>
<span class="pre">-l</span></code> lists them.  As <a class="reference internal" href="#to3-using"><span class="std std-ref">documented above</span></a>, each can be turned on
and off individually.  They are described here in more detail.</p>
<dl class="2to3fixer">
<dt id="2to3fixer-apply">
<code class="descname">apply</code><a class="headerlink" href="#2to3fixer-apply" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes usage of <a class="reference internal" href="functions.html#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a>.  For example <code class="docutils literal notranslate"><span class="pre">apply(function,</span> <span class="pre">*args,</span>
<span class="pre">**kwargs)</span></code> is converted to <code class="docutils literal notranslate"><span class="pre">function(*args,</span> <span class="pre">**kwargs)</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-asserts">
<code class="descname">asserts</code><a class="headerlink" href="#2to3fixer-asserts" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces deprecated <a class="reference internal" href="unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> method names with the correct ones.</p>
<table border="1" class="docutils">
<colgroup>
<col width="43%" />
<col width="57%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">From</th>
<th class="head">To</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failUnlessEqual(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">assertEquals(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failIfEqual(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertNotEqual" title="unittest.TestCase.assertNotEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">assertNotEquals(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertNotEqual" title="unittest.TestCase.assertNotEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failUnless(a)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue(a)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">assert_(a)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue(a)</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failIf(a)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertFalse(a)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">failUnlessRaises(exc,</span> <span class="pre">cal)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises(exc,</span> <span class="pre">cal)</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failUnlessAlmostEqual(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">assertAlmostEquals(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">failIfAlmostEqual(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">assertNotAlmostEquals(a,</span> <span class="pre">b)</span></code></td>
<td><a class="reference internal" href="unittest.html#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual(a,</span> <span class="pre">b)</span></code></a></td>
</tr>
</tbody>
</table>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-basestring">
<code class="descname">basestring</code><a class="headerlink" href="#2to3fixer-basestring" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <a class="reference internal" href="functions.html#basestring" title="basestring"><code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code></a> to <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-buffer">
<code class="descname">buffer</code><a class="headerlink" href="#2to3fixer-buffer" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">buffer</span></code></a> to <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>.  This fixer is optional
because the <a class="reference internal" href="stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> API is similar but not exactly the same as
that of <a class="reference internal" href="functions.html#buffer" title="buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">buffer</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-dict">
<code class="descname">dict</code><a class="headerlink" href="#2to3fixer-dict" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes dictionary iteration methods.  <a class="reference internal" href="stdtypes.html#dict.iteritems" title="dict.iteritems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.iteritems()</span></code></a> is converted to
<a class="reference internal" href="stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>, <a class="reference internal" href="stdtypes.html#dict.iterkeys" title="dict.iterkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.iterkeys()</span></code></a> to <a class="reference internal" href="stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.keys()</span></code></a>, and
<a class="reference internal" href="stdtypes.html#dict.itervalues" title="dict.itervalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.itervalues()</span></code></a> to <a class="reference internal" href="stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.values()</span></code></a>.  Similarly,
<a class="reference internal" href="stdtypes.html#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewitems()</span></code></a>, <a class="reference internal" href="stdtypes.html#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewkeys()</span></code></a> and <a class="reference internal" href="stdtypes.html#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.viewvalues()</span></code></a> are
converted respectively to <a class="reference internal" href="stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>, <a class="reference internal" href="stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.keys()</span></code></a> and
<a class="reference internal" href="stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.values()</span></code></a>.  It also wraps existing usages of <a class="reference internal" href="stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.items()</span></code></a>,
<a class="reference internal" href="stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.keys()</span></code></a>, and <a class="reference internal" href="stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.values()</span></code></a> in a call to <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-except">
<code class="descname">except</code><a class="headerlink" href="#2to3fixer-except" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">X,</span> <span class="pre">T</span></code> to <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">X</span> <span class="pre">as</span> <span class="pre">T</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-exec">
<code class="descname">exec</code><a class="headerlink" href="#2to3fixer-exec" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement to the <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code> function.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-execfile">
<code class="descname">execfile</code><a class="headerlink" href="#2to3fixer-execfile" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes usage of <a class="reference internal" href="functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a>.  The argument to <a class="reference internal" href="functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> is
wrapped in calls to <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, <a class="reference internal" href="functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-exitfunc">
<code class="descname">exitfunc</code><a class="headerlink" href="#2to3fixer-exitfunc" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes assignment of <a class="reference internal" href="sys.html#sys.exitfunc" title="sys.exitfunc"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.exitfunc</span></code></a> to use of the <a class="reference internal" href="atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a>
module.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-filter">
<code class="descname">filter</code><a class="headerlink" href="#2to3fixer-filter" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps <a class="reference internal" href="functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> usage in a <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> call.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-funcattrs">
<code class="descname">funcattrs</code><a class="headerlink" href="#2to3fixer-funcattrs" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes function attributes that have been renamed.  For example,
<code class="docutils literal notranslate"><span class="pre">my_function.func_closure</span></code> is converted to <code class="docutils literal notranslate"><span class="pre">my_function.__closure__</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-future">
<code class="descname">future</code><a class="headerlink" href="#2to3fixer-future" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">new_feature</span></code> statements.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-getcwdu">
<code class="descname">getcwdu</code><a class="headerlink" href="#2to3fixer-getcwdu" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="os.html#os.getcwdu" title="os.getcwdu"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.getcwdu()</span></code></a> to <a class="reference internal" href="os.html#os.getcwd" title="os.getcwd"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.getcwd()</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-has_key">
<code class="descname">has_key</code><a class="headerlink" href="#2to3fixer-has_key" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes <code class="docutils literal notranslate"><span class="pre">dict.has_key(key)</span></code> to <code class="docutils literal notranslate"><span class="pre">key</span> <span class="pre">in</span> <span class="pre">dict</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-idioms">
<code class="descname">idioms</code><a class="headerlink" href="#2to3fixer-idioms" title="Permalink to this definition">¶</a></dt>
<dd><p>This optional fixer performs several transformations that make Python code
more idiomatic.  Type comparisons like <code class="docutils literal notranslate"><span class="pre">type(x)</span> <span class="pre">is</span> <span class="pre">SomeClass</span></code> and
<code class="docutils literal notranslate"><span class="pre">type(x)</span> <span class="pre">==</span> <span class="pre">SomeClass</span></code> are converted to <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">SomeClass)</span></code>.
<code class="docutils literal notranslate"><span class="pre">while</span> <span class="pre">1</span></code> becomes <code class="docutils literal notranslate"><span class="pre">while</span> <span class="pre">True</span></code>.  This fixer also tries to make use of
<a class="reference internal" href="functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> in appropriate places.  For example, this block</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">some_iterable</span><span class="p">)</span>
<span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
</pre></div>
</div>
<p>is changed to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">some_iterable</span><span class="p">)</span>
</pre></div>
</div>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-import">
<code class="descname">import</code><a class="headerlink" href="#2to3fixer-import" title="Permalink to this definition">¶</a></dt>
<dd><p>Detects sibling imports and converts them to relative imports.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-imports">
<code class="descname">imports</code><a class="headerlink" href="#2to3fixer-imports" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles module renames in the standard library.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-imports2">
<code class="descname">imports2</code><a class="headerlink" href="#2to3fixer-imports2" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles other modules renames in the standard library.  It is separate from
the <a class="reference internal" href="#2to3fixer-imports"><code class="xref std std-2to3fixer docutils literal notranslate"><span class="pre">imports</span></code></a> fixer only because of technical limitations.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-input">
<code class="descname">input</code><a class="headerlink" href="#2to3fixer-input" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <code class="docutils literal notranslate"><span class="pre">input(prompt)</span></code> to <code class="docutils literal notranslate"><span class="pre">eval(input(prompt))</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-intern">
<code class="descname">intern</code><a class="headerlink" href="#2to3fixer-intern" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <a class="reference internal" href="functions.html#intern" title="intern"><code class="xref py py-func docutils literal notranslate"><span class="pre">intern()</span></code></a> to <code class="xref py py-func docutils literal notranslate"><span class="pre">sys.intern()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-isinstance">
<code class="descname">isinstance</code><a class="headerlink" href="#2to3fixer-isinstance" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes duplicate types in the second argument of <a class="reference internal" href="functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a>.  For
example, <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">(int,</span> <span class="pre">int))</span></code> is converted to <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span>
<span class="pre">(int))</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-itertools_imports">
<code class="descname">itertools_imports</code><a class="headerlink" href="#2to3fixer-itertools_imports" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes imports of <a class="reference internal" href="itertools.html#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilter()</span></code></a>, <a class="reference internal" href="itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a>, and
<a class="reference internal" href="itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a>.  Imports of <a class="reference internal" href="itertools.html#itertools.ifilterfalse" title="itertools.ifilterfalse"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilterfalse()</span></code></a> are also
changed to <code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.filterfalse()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-itertools">
<code class="descname">itertools</code><a class="headerlink" href="#2to3fixer-itertools" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes usage of <a class="reference internal" href="itertools.html#itertools.ifilter" title="itertools.ifilter"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilter()</span></code></a>, <a class="reference internal" href="itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a>, and
<a class="reference internal" href="itertools.html#itertools.imap" title="itertools.imap"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.imap()</span></code></a> to their built-in equivalents.
<a class="reference internal" href="itertools.html#itertools.ifilterfalse" title="itertools.ifilterfalse"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.ifilterfalse()</span></code></a> is changed to <code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.filterfalse()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-long">
<code class="descname">long</code><a class="headerlink" href="#2to3fixer-long" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a> to <a class="reference internal" href="functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-map">
<code class="descname">map</code><a class="headerlink" href="#2to3fixer-map" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps <a class="reference internal" href="functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> in a <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> call.  It also changes <code class="docutils literal notranslate"><span class="pre">map(None,</span> <span class="pre">x)</span></code>
to <code class="docutils literal notranslate"><span class="pre">list(x)</span></code>.  Using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">future_builtins</span> <span class="pre">import</span> <span class="pre">map</span></code> disables this
fixer.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-metaclass">
<code class="descname">metaclass</code><a class="headerlink" href="#2to3fixer-metaclass" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the old metaclass syntax (<code class="docutils literal notranslate"><span class="pre">__metaclass__</span> <span class="pre">=</span> <span class="pre">Meta</span></code> in the class
body) to the new (<code class="docutils literal notranslate"><span class="pre">class</span> <span class="pre">X(metaclass=Meta)</span></code>).</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-methodattrs">
<code class="descname">methodattrs</code><a class="headerlink" href="#2to3fixer-methodattrs" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes old method attribute names.  For example, <code class="docutils literal notranslate"><span class="pre">meth.im_func</span></code> is converted
to <code class="docutils literal notranslate"><span class="pre">meth.__func__</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-ne">
<code class="descname">ne</code><a class="headerlink" href="#2to3fixer-ne" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the old not-equal syntax, <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code>, to <code class="docutils literal notranslate"><span class="pre">!=</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-next">
<code class="descname">next</code><a class="headerlink" href="#2to3fixer-next" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the use of iterator’s <a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods to the
<a class="reference internal" href="functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> function.  It also renames <a class="reference internal" href="stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-nonzero">
<code class="descname">nonzero</code><a class="headerlink" href="#2to3fixer-nonzero" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="../reference/datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a> to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-numliterals">
<code class="descname">numliterals</code><a class="headerlink" href="#2to3fixer-numliterals" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts octal literals into the new syntax.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-paren">
<code class="descname">paren</code><a class="headerlink" href="#2to3fixer-paren" title="Permalink to this definition">¶</a></dt>
<dd><p>Add extra parenthesis where they are required in list comprehensions.  For
example, <code class="docutils literal notranslate"><span class="pre">[x</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">1,</span> <span class="pre">2]</span></code> becomes <code class="docutils literal notranslate"><span class="pre">[x</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">(1,</span> <span class="pre">2)]</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-print">
<code class="descname">print</code><a class="headerlink" href="#2to3fixer-print" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement to the <a class="reference internal" href="functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-raise">
<code class="descname">raise</code><a class="headerlink" href="#2to3fixer-raise" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">E,</span> <span class="pre">V</span></code> to <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">E(V)</span></code>, and <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">E,</span> <span class="pre">V,</span> <span class="pre">T</span></code> to <code class="docutils literal notranslate"><span class="pre">raise</span>
<span class="pre">E(V).with_traceback(T)</span></code>.  If <code class="docutils literal notranslate"><span class="pre">E</span></code> is a tuple, the translation will be
incorrect because substituting tuples for exceptions has been removed in Python 3.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-raw_input">
<code class="descname">raw_input</code><a class="headerlink" href="#2to3fixer-raw_input" title="Permalink to this definition">¶</a></dt>
<dd><p>Converts <a class="reference internal" href="functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> to <a class="reference internal" href="functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-reduce">
<code class="descname">reduce</code><a class="headerlink" href="#2to3fixer-reduce" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles the move of <a class="reference internal" href="functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> to <a class="reference internal" href="functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-renames">
<code class="descname">renames</code><a class="headerlink" href="#2to3fixer-renames" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes <a class="reference internal" href="sys.html#sys.maxint" title="sys.maxint"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.maxint</span></code></a> to <a class="reference internal" href="sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-repr">
<code class="descname">repr</code><a class="headerlink" href="#2to3fixer-repr" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces backtick repr with the <a class="reference internal" href="functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-set_literal">
<code class="descname">set_literal</code><a class="headerlink" href="#2to3fixer-set_literal" title="Permalink to this definition">¶</a></dt>
<dd><p>Replaces use of the <a class="reference internal" href="stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> constructor with set literals.  This fixer
is optional.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-standarderror">
<code class="descname">standarderror</code><a class="headerlink" href="#2to3fixer-standarderror" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="exceptions.html#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a> to <a class="reference internal" href="exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-sys_exc">
<code class="descname">sys_exc</code><a class="headerlink" href="#2to3fixer-sys_exc" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes the deprecated <a class="reference internal" href="sys.html#sys.exc_value" title="sys.exc_value"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.exc_value</span></code></a>, <a class="reference internal" href="sys.html#sys.exc_type" title="sys.exc_type"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.exc_type</span></code></a>,
<a class="reference internal" href="sys.html#sys.exc_traceback" title="sys.exc_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code></a> to use <a class="reference internal" href="sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-throw">
<code class="descname">throw</code><a class="headerlink" href="#2to3fixer-throw" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes the API change in generator’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code> method.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-tuple_params">
<code class="descname">tuple_params</code><a class="headerlink" href="#2to3fixer-tuple_params" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes implicit tuple parameter unpacking.  This fixer inserts temporary
variables.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-types">
<code class="descname">types</code><a class="headerlink" href="#2to3fixer-types" title="Permalink to this definition">¶</a></dt>
<dd><p>Fixes code broken from the removal of some members in the <a class="reference internal" href="types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a>
module.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-unicode">
<code class="descname">unicode</code><a class="headerlink" href="#2to3fixer-unicode" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> to <a class="reference internal" href="functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-urllib">
<code class="descname">urllib</code><a class="headerlink" href="#2to3fixer-urllib" title="Permalink to this definition">¶</a></dt>
<dd><p>Handles the rename of <a class="reference internal" href="urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> and <a class="reference internal" href="urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> to the <a class="reference internal" href="urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a>
package.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-ws_comma">
<code class="descname">ws_comma</code><a class="headerlink" href="#2to3fixer-ws_comma" title="Permalink to this definition">¶</a></dt>
<dd><p>Removes excess whitespace from comma separated items.  This fixer is
optional.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-xrange">
<code class="descname">xrange</code><a class="headerlink" href="#2to3fixer-xrange" title="Permalink to this definition">¶</a></dt>
<dd><p>Renames <a class="reference internal" href="functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> to <a class="reference internal" href="functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> and wraps existing <a class="reference internal" href="functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a>
calls with <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-xreadlines">
<code class="descname">xreadlines</code><a class="headerlink" href="#2to3fixer-xreadlines" title="Permalink to this definition">¶</a></dt>
<dd><p>Changes <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">file.xreadlines()</span></code> to <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">file</span></code>.</p>
</dd></dl>

<dl class="2to3fixer">
<dt id="2to3fixer-zip">
<code class="descname">zip</code><a class="headerlink" href="#2to3fixer-zip" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps <a class="reference internal" href="functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> usage in a <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> call.  This is disabled when
<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">future_builtins</span> <span class="pre">import</span> <span class="pre">zip</span></code> appears.</p>
</dd></dl>

</div>
<div class="section" id="module-lib2to3">
<span id="lib2to3-2to3-s-library"></span><h2>25.4.3. <a class="reference internal" href="#module-lib2to3" title="lib2to3: the 2to3 library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lib2to3</span></code></a> - 2to3’s library<a class="headerlink" href="#module-lib2to3" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#module-lib2to3" title="lib2to3: the 2to3 library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">lib2to3</span></code></a> API should be considered unstable and may change
drastically in the future.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">25.4. 2to3 - Automated Python 2 to 3 code translation</a><ul>
<li><a class="reference internal" href="#using-2to3">25.4.1. Using 2to3</a></li>
<li><a class="reference internal" href="#fixers">25.4.2. Fixers</a></li>
<li><a class="reference internal" href="#module-lib2to3">25.4.3. <code class="docutils literal notranslate"><span class="pre">lib2to3</span></code> - 2to3’s library</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="unittest.html"
                        title="previous chapter">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="test.html"
                        title="next chapter">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/library/2to3.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="test.html" title="25.5. test — Regression tests package for Python"
             >next</a> |</li>
        <li class="right" >
          <a href="unittest.html" title="25.3. unittest — Unit testing framework"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="development.html" >25. Development Tools</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�O�66"html/reference/compound_stmts.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7. Compound statements &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8. Top-level components" href="toplevel_components.html" />
    <link rel="prev" title="6. Simple statements" href="simple_stmts.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/compound_stmts.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="8. Top-level components"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. Simple statements"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="compound-statements">
<span id="compound"></span><h1>7. Compound statements<a class="headerlink" href="#compound-statements" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Compound statements contain (groups of) other statements; they affect or control
the execution of those other statements in some way.  In general, compound
statements span multiple lines, although in simple incarnations a whole compound
statement may be contained in one line.</p>
<p>The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>, <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> and <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statements implement
traditional control flow constructs.  <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> specifies exception
handlers and/or cleanup code for a group of statements.  Function and class
definitions are also syntactically compound statements.</p>
<p id="index-1">Compound statements consist of one or more ‘clauses.’  A clause consists of a
header and a ‘suite.’  The clause headers of a particular compound statement are
all at the same indentation level. Each clause header begins with a uniquely
identifying keyword and ends with a colon.  A suite is a group of statements
controlled by a clause.  A suite can be one or more semicolon-separated simple
statements on the same line as the header, following the header’s colon, or it
can be one or more indented statements on subsequent lines.  Only the latter
form of suite can contain nested compound statements; the following is illegal,
mostly because it wouldn’t be clear to which <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause a following
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause would belong:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">test1</span><span class="p">:</span> <span class="k">if</span> <span class="n">test2</span><span class="p">:</span> <span class="nb">print</span> <span class="n">x</span>
</pre></div>
</div>
<p>Also note that the semicolon binds tighter than the colon in this context, so
that in the following example, either all or none of the <a class="reference internal" href="simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>
statements are executed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="n">y</span> <span class="o">&lt;</span> <span class="n">z</span><span class="p">:</span> <span class="nb">print</span> <span class="n">x</span><span class="p">;</span> <span class="nb">print</span> <span class="n">y</span><span class="p">;</span> <span class="nb">print</span> <span class="n">z</span>
</pre></div>
</div>
<p>Summarizing:</p>
<pre>
<strong id="grammar-token-compound_stmt">compound_stmt</strong> ::=  <a class="reference internal" href="#grammar-token-if_stmt"><code class="xref docutils literal notranslate"><span class="pre">if_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-while_stmt"><code class="xref docutils literal notranslate"><span class="pre">while_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-for_stmt"><code class="xref docutils literal notranslate"><span class="pre">for_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-try_stmt"><code class="xref docutils literal notranslate"><span class="pre">try_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-with_stmt"><code class="xref docutils literal notranslate"><span class="pre">with_stmt</span></code></a>
                   | <a class="reference internal" href="#grammar-token-funcdef"><code class="xref docutils literal notranslate"><span class="pre">funcdef</span></code></a>
                   | <a class="reference internal" href="#grammar-token-classdef"><code class="xref docutils literal notranslate"><span class="pre">classdef</span></code></a>
                   | <a class="reference internal" href="#grammar-token-decorated"><code class="xref docutils literal notranslate"><span class="pre">decorated</span></code></a>
<strong id="grammar-token-suite">suite        </strong> ::=  <a class="reference internal" href="#grammar-token-stmt_list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | NEWLINE INDENT <a class="reference internal" href="#grammar-token-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>+ DEDENT
<strong id="grammar-token-statement">statement    </strong> ::=  <a class="reference internal" href="#grammar-token-stmt_list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a> NEWLINE | <a class="reference internal" href="#grammar-token-compound_stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a>
<strong id="grammar-token-stmt_list">stmt_list    </strong> ::=  <a class="reference internal" href="simple_stmts.html#grammar-token-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a> (&quot;;&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-simple_stmt"><code class="xref docutils literal notranslate"><span class="pre">simple_stmt</span></code></a>)* [&quot;;&quot;]
</pre>
<p id="index-2">Note that statements always end in a <code class="docutils literal notranslate"><span class="pre">NEWLINE</span></code> possibly followed by a
<code class="docutils literal notranslate"><span class="pre">DEDENT</span></code>. Also note that optional continuation clauses always begin with a
keyword that cannot start a statement, thus there are no ambiguities (the
‘dangling <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>’ problem is solved in Python by requiring nested
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements to be indented).</p>
<p>The formatting of the grammar rules in the following sections places each clause
on a separate line for clarity.</p>
<div class="section" id="the-if-statement">
<span id="else"></span><span id="elif"></span><span id="if"></span><h2>7.1. The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement<a class="headerlink" href="#the-if-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-3">The <a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is used for conditional execution:</p>
<pre>
<strong id="grammar-token-if_stmt">if_stmt</strong> ::=  &quot;if&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
             ( &quot;elif&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a> )*
             [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>It selects exactly one of the suites by evaluating the expressions one by one
until one is found to be true (see section <a class="reference internal" href="expressions.html#booleans"><span class="std std-ref">Boolean operations</span></a> for the definition of
true and false); then that suite is executed (and no other part of the
<a class="reference internal" href="#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement is executed or evaluated).  If all expressions are
false, the suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed.</p>
</div>
<div class="section" id="the-while-statement">
<span id="while"></span><h2>7.2. The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement<a class="headerlink" href="#the-while-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-4">The <a class="reference internal" href="#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement is used for repeated execution as long as an
expression is true:</p>
<pre>
<strong id="grammar-token-while_stmt">while_stmt</strong> ::=  &quot;while&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
                [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>This repeatedly tests the expression and, if it is true, executes the first
suite; if the expression is false (which may be the first time it is tested) the
suite of the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed and the loop
terminates.</p>
<p id="index-5">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause’s suite.  A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and goes back
to testing the expression.</p>
</div>
<div class="section" id="the-for-statement">
<span id="for"></span><h2>7.3. The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement<a class="headerlink" href="#the-for-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-6">The <a class="reference internal" href="#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:</p>
<pre>
<strong id="grammar-token-for_stmt">for_stmt</strong> ::=  &quot;for&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;in&quot; <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
              [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
</pre>
<p>The expression list is evaluated once; it should yield an iterable object.  An
iterator is created for the result of the <code class="docutils literal notranslate"><span class="pre">expression_list</span></code>.  The suite is
then executed once for each item provided by the iterator, in the order of
ascending indices.  Each item in turn is assigned to the target list using the
standard rules for assignments, and then the suite is executed.  When the items
are exhausted (which is immediately when the sequence is empty), the suite in
the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause, if present, is executed, and the loop terminates.</p>
<p id="index-7">A <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement executed in the first suite terminates the loop
without executing the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause’s suite.  A <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>
statement executed in the first suite skips the rest of the suite and continues
with the next item, or with the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause if there was no next
item.</p>
<p>The suite may assign to the variable(s) in the target list; this does not affect
the next item assigned to it.</p>
<p id="index-8">The target list is not deleted when the loop is finished, but if the sequence is
empty, it will not have been assigned to at all by the loop.  Hint: the built-in
function <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> returns a sequence of integers suitable to emulate the
effect of Pascal’s <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">:=</span> <span class="pre">a</span> <span class="pre">to</span> <span class="pre">b</span> <span class="pre">do</span></code>; e.g., <code class="docutils literal notranslate"><span class="pre">range(3)</span></code> returns the list
<code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">2]</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p id="index-9">There is a subtlety when the sequence is being modified by the loop (this can
only occur for mutable sequences, e.g. lists). An internal counter is used to
keep track of which item is used next, and this is incremented on each
iteration.  When this counter has reached the length of the sequence the loop
terminates.  This means that if the suite deletes the current (or a previous)
item from the sequence, the next item will be skipped (since it gets the index
of the current item which has already been treated).  Likewise, if the suite
inserts an item in the sequence before the current item, the current item will
be treated again the next time through the loop. This can lead to nasty bugs
that can be avoided by making a temporary copy using a slice of the whole
sequence, e.g.,</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">a</span><span class="p">[:]:</span>
    <span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span> <span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-try-statement">
<span id="finally"></span><span id="except"></span><span id="try"></span><h2>7.4. The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement<a class="headerlink" href="#the-try-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-10">The <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement specifies exception handlers and/or cleanup code
for a group of statements:</p>
<pre>
<strong id="grammar-token-try_stmt">try_stmt </strong> ::=  try1_stmt | try2_stmt
<strong id="grammar-token-try1_stmt">try1_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
               (&quot;except&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [(&quot;as&quot; | &quot;,&quot;) <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>)+
               [&quot;else&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
               [&quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>]
<strong id="grammar-token-try2_stmt">try2_stmt</strong> ::=  &quot;try&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
               &quot;finally&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
</pre>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>In previous versions of Python, <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> did not work. <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> had to be
nested in <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>.</p>
</div>
<p>The <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause(s) specify one or more exception handlers. When no
exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, no exception handler is executed.
When an exception occurs in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, a search for an exception
handler is started.  This search inspects the except clauses in turn until one
is found that matches the exception.  An expression-less except clause, if
present, must be last; it matches any exception.  For an except clause with an
expression, that expression is evaluated, and the clause matches the exception
if the resulting object is “compatible” with the exception.  An object is
compatible with an exception if it is the class or a base class of the exception
object, or a tuple containing an item compatible with the exception.</p>
<p>If no except clause matches the exception, the search for an exception handler
continues in the surrounding code and on the invocation stack.  <a class="footnote-reference" href="#id4" id="id1">[1]</a></p>
<p>If the evaluation of an expression in the header of an except clause raises an
exception, the original search for a handler is canceled and a search starts for
the new exception in the surrounding code and on the call stack (it is treated
as if the entire <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement raised the exception).</p>
<p>When a matching except clause is found, the exception is assigned to the target
specified in that except clause, if present, and the except clause’s suite is
executed.  All except clauses must have an executable block.  When the end of
this block is reached, execution continues normally after the entire try
statement.  (This means that if two nested handlers exist for the same
exception, and the exception occurs in the try clause of the inner handler, the
outer handler will not handle the exception.)</p>
<p id="index-11">Before an except clause’s suite is executed, details about the exception are
assigned to three variables in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module: <code class="docutils literal notranslate"><span class="pre">sys.exc_type</span></code> receives
the object identifying the exception; <code class="docutils literal notranslate"><span class="pre">sys.exc_value</span></code> receives the exception’s
parameter; <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code> receives a traceback object (see section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) identifying the point in the program where the exception
occurred. These details are also available through the <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
function, which returns a tuple <code class="docutils literal notranslate"><span class="pre">(exc_type,</span> <span class="pre">exc_value,</span> <span class="pre">exc_traceback)</span></code>.  Use
of the corresponding variables is deprecated in favor of this function, since
their use is unsafe in a threaded program.  As of Python 1.5, the variables are
restored to their previous values (before the call) when returning from a
function that handled an exception.</p>
<p id="index-12">The optional <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause is executed if the control flow leaves the
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite, no exception was raised, and no <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>,
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a>, or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement was executed.  Exceptions in
the <a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause are not handled by the preceding <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
clauses.</p>
<p id="index-13">If <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> is present, it specifies a ‘cleanup’ handler.  The
<a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause is executed, including any <a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and
<a class="reference internal" href="#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clauses.  If an exception occurs in any of the clauses and is
not handled, the exception is temporarily saved. The <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause
is executed.  If there is a saved exception, it is re-raised at the end of the
<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause. If the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause raises another
exception or executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> or <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement, the
saved exception is discarded:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">42</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">()</span>
<span class="go">42</span>
</pre></div>
</div>
<p>The exception information is not available to the program during execution of
the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p>
<p id="index-14">When a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>, <a class="reference internal" href="simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> or <a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is
executed in the <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> suite of a <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
statement, the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is also executed ‘on the way out.’ A
<a class="reference internal" href="simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement is illegal in the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause. (The
reason is a problem with the current implementation — this restriction may be
lifted in the future).</p>
<p>The return value of a function is determined by the last <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
statement executed.  Since the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause always executes, a
<a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement executed in the <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause will
always be the last one executed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">foo</span><span class="p">():</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;try&#39;</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="s1">&#39;finally&#39;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo</span><span class="p">()</span>
<span class="go">&#39;finally&#39;</span>
</pre></div>
</div>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>,
and information on using the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement to generate exceptions
may be found in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p>
</div>
<div class="section" id="the-with-statement">
<span id="as"></span><span id="with"></span><h2>7.5. The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement<a class="headerlink" href="#the-with-statement" title="Permalink to this headline">¶</a></h2>
<div class="versionadded" id="index-15">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is used to wrap the execution of a block with
methods defined by a context manager (see section <a class="reference internal" href="datamodel.html#context-managers"><span class="std std-ref">With Statement Context Managers</span></a>). This
allows common <a class="reference internal" href="#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>…<a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> usage
patterns to be encapsulated for convenient reuse.</p>
<pre>
<strong id="grammar-token-with_stmt">with_stmt</strong> ::=  &quot;with&quot; with_item (&quot;,&quot; with_item)* &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-with_item">with_item</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;as&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>]
</pre>
<p>The execution of the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement with one “item” proceeds as follows:</p>
<ol class="arabic">
<li><p class="first">The context expression (the expression given in the <a class="reference internal" href="#grammar-token-with_item"><code class="xref std std-token docutils literal notranslate"><span class="pre">with_item</span></code></a>) is
evaluated to obtain a context manager.</p>
</li>
<li><p class="first">The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is loaded for later use.</p>
</li>
<li><p class="first">The context manager’s <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is invoked.</p>
</li>
<li><p class="first">If a target was included in the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the return value
from <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is assigned to it.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement guarantees that if the <a class="reference internal" href="datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method
returns without an error, then <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> will always be called. Thus, if
an error occurs during the assignment to the target list, it will be treated the
same as an error occurring within the suite would be. See step 6 below.</p>
</div>
</li>
<li><p class="first">The suite is executed.</p>
</li>
<li><p class="first">The context manager’s <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is invoked. If an exception
caused the suite to be exited, its type, value, and traceback are passed as
arguments to <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>. Otherwise, three <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> arguments are
supplied.</p>
<p>If the suite was exited due to an exception, and the return value from the
<a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method was false, the exception is reraised. If the return
value was true, the exception is suppressed, and execution continues with the
statement following the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p>
<p>If the suite was exited for any reason other than an exception, the return value
from <a class="reference internal" href="datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> is ignored, and execution proceeds at the normal location
for the kind of exit that was taken.</p>
</li>
</ol>
<p>With more than one item, the context managers are processed as if multiple
<a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements were nested:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
    <span class="n">suite</span>
</pre></div>
</div>
<p>is equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
        <span class="n">suite</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In Python 2.5, the <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement is only allowed when the
<code class="docutils literal notranslate"><span class="pre">with_statement</span></code> feature has been enabled.  It is always enabled in
Python 2.6.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Support for multiple context expressions.</p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
<dd>The specification, background, and examples for the Python <a class="reference internal" href="#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</dd>
</dl>
</div>
</div>
<div class="section" id="function-definitions">
<span id="def"></span><span id="function"></span><span id="index-17"></span><h2>7.6. Function definitions<a class="headerlink" href="#function-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-18">A function definition defines a user-defined function object (see section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-decorated">decorated     </strong> ::=  decorators (classdef | funcdef)
<strong id="grammar-token-decorators">decorators    </strong> ::=  <a class="reference internal" href="#grammar-token-decorator"><code class="xref docutils literal notranslate"><span class="pre">decorator</span></code></a>+
<strong id="grammar-token-decorator">decorator     </strong> ::=  &quot;&#64;&quot; <a class="reference internal" href="#grammar-token-dotted_name"><code class="xref docutils literal notranslate"><span class="pre">dotted_name</span></code></a> [&quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [&quot;,&quot;]] &quot;)&quot;] NEWLINE
<strong id="grammar-token-funcdef">funcdef       </strong> ::=  &quot;def&quot; <a class="reference internal" href="#grammar-token-funcname"><code class="xref docutils literal notranslate"><span class="pre">funcname</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>] &quot;)&quot; &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-dotted_name">dotted_name   </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;.&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
<strong id="grammar-token-parameter_list">parameter_list</strong> ::=  (<a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> &quot;,&quot;)*
                    (  &quot;*&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;,&quot; &quot;**&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>]
                    | &quot;**&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
                    | <a class="reference internal" href="#grammar-token-defparameter"><code class="xref docutils literal notranslate"><span class="pre">defparameter</span></code></a> [&quot;,&quot;] )
<strong id="grammar-token-defparameter">defparameter  </strong> ::=  <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> [&quot;=&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-sublist">sublist       </strong> ::=  <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-parameter"><code class="xref docutils literal notranslate"><span class="pre">parameter</span></code></a>)* [&quot;,&quot;]
<strong id="grammar-token-parameter">parameter     </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | &quot;(&quot; <a class="reference internal" href="#grammar-token-sublist"><code class="xref docutils literal notranslate"><span class="pre">sublist</span></code></a> &quot;)&quot;
<strong id="grammar-token-funcname">funcname      </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A function definition is an executable statement.  Its execution binds the
function name in the current local namespace to a function object (a wrapper
around the executable code for the function).  This function object contains a
reference to the current global namespace as the global namespace to be used
when the function is called.</p>
<p>The function definition does not execute the function body; this gets executed
only when the function is called. <a class="footnote-reference" href="#id5" id="id2">[2]</a></p>
<p id="index-19">A function definition may be wrapped by one or more <a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> expressions.
Decorator expressions are evaluated when the function is defined, in the scope
that contains the function definition.  The result must be a callable, which is
invoked with the function object as the only argument. The returned value is
bound to the function name instead of the function object.  Multiple decorators
are applied in nested fashion. For example, the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>
<span class="nd">@f2</span>
<span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
</pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">():</span> <span class="k">pass</span>
<span class="n">func</span> <span class="o">=</span> <span class="n">f1</span><span class="p">(</span><span class="n">arg</span><span class="p">)(</span><span class="n">f2</span><span class="p">(</span><span class="n">func</span><span class="p">))</span>
</pre></div>
</div>
<p id="index-20">When one or more top-level <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> have the form
<em>parameter</em> <code class="docutils literal notranslate"><span class="pre">=</span></code> <em>expression</em>, the function is said to have “default parameter
values.”  For a parameter with a default value, the corresponding
<a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">argument</span></a> may be omitted from a call, in which
case the parameter’s default value is substituted.  If a
parameter has a default value, all following parameters must also have a default
value — this is a syntactic restriction that is not expressed by the grammar.</p>
<p><strong>Default parameter values are evaluated when the function definition is
executed.</strong>  This means that the expression is evaluated once, when the function
is defined, and that the same “pre-computed” value is used for each call.  This
is especially important to understand when a default parameter is a mutable
object, such as a list or a dictionary: if the function modifies the object
(e.g. by appending an item to a list), the default value is in effect modified.
This is generally not what was intended.  A way around this  is to use <code class="docutils literal notranslate"><span class="pre">None</span></code>
as the default, and explicitly test for it in the body of the function, e.g.:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">whats_on_the_telly</span><span class="p">(</span><span class="n">penguin</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">penguin</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">penguin</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">penguin</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;property of the zoo&quot;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">penguin</span>
</pre></div>
</div>
<p id="index-21">Function call semantics are described in more detail in section <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>. A
function call always assigns values to all parameters mentioned in the parameter
list, either from position arguments, from keyword arguments, or from default
values.  If the form “<code class="docutils literal notranslate"><span class="pre">*identifier</span></code>” is present, it is initialized to a tuple
receiving any excess positional parameters, defaulting to the empty tuple.  If
the form “<code class="docutils literal notranslate"><span class="pre">**identifier</span></code>” is present, it is initialized to a new dictionary
receiving any excess keyword arguments, defaulting to a new empty dictionary.</p>
<p id="index-22">It is also possible to create anonymous functions (functions not bound to a
name), for immediate use in expressions.  This uses lambda expressions, described in
section <a class="reference internal" href="expressions.html#lambda"><span class="std std-ref">Lambdas</span></a>.  Note that the lambda expression is merely a shorthand for a
simplified function definition; a function defined in a “<a class="reference internal" href="#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>”
statement can be passed around or assigned to another name just like a function
defined by a lambda expression.  The “<a class="reference internal" href="#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>” form is actually more powerful
since it allows the execution of multiple statements.</p>
<p><strong>Programmer’s note:</strong> Functions are first-class objects.  A “<code class="docutils literal notranslate"><span class="pre">def</span></code>” form
executed inside a function definition defines a local function that can be
returned or passed around.  Free variables used in the nested function can
access the local variables of the function containing the def.  See section
<a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for details.</p>
</div>
<div class="section" id="class-definitions">
<span id="class"></span><h2>7.7. Class definitions<a class="headerlink" href="#class-definitions" title="Permalink to this headline">¶</a></h2>
<p id="index-23">A class definition defines a class object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>):</p>
<pre>
<strong id="grammar-token-classdef">classdef   </strong> ::=  &quot;class&quot; <a class="reference internal" href="#grammar-token-classname"><code class="xref docutils literal notranslate"><span class="pre">classname</span></code></a> [<a class="reference internal" href="#grammar-token-inheritance"><code class="xref docutils literal notranslate"><span class="pre">inheritance</span></code></a>] &quot;:&quot; <a class="reference internal" href="#grammar-token-suite"><code class="xref docutils literal notranslate"><span class="pre">suite</span></code></a>
<strong id="grammar-token-inheritance">inheritance</strong> ::=  &quot;(&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>] &quot;)&quot;
<strong id="grammar-token-classname">classname  </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>A class definition is an executable statement.  It first evaluates the
inheritance list, if present.  Each item in the inheritance list should evaluate
to a class object or class type which allows subclassing.  The class’s suite is
then executed in a new execution frame (see section <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a>), using a
newly created local namespace and the original global namespace. (Usually, the
suite contains only function definitions.)  When the class’s suite finishes
execution, its execution frame is discarded but its local namespace is
saved. <a class="footnote-reference" href="#id6" id="id3">[3]</a> A class object is then created using the inheritance list for the
base classes and the saved local namespace for the attribute dictionary.  The
class name is bound to this class object in the original local namespace.</p>
<p><strong>Programmer’s note:</strong> Variables defined in the class definition are class
variables; they are shared by all instances.  To create instance variables, they
can be set in a method with <code class="docutils literal notranslate"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code>.  Both class and instance
variables are accessible through the notation “<code class="docutils literal notranslate"><span class="pre">self.name</span></code>”, and an instance
variable hides a class variable with the same name when accessed in this way.
Class variables can be used as defaults for instance variables, but using
mutable values there can lead to unexpected results.  For <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style
class</span></a>es, descriptors can be used to create instance variables with different
implementation details.</p>
<p>Class definitions, like function definitions, may be wrapped by one or more
<a class="reference internal" href="../glossary.html#term-decorator"><span class="xref std std-term">decorator</span></a> expressions.  The evaluation rules for the decorator
expressions are the same as for functions.  The result must be a class object,
which is then bound to the class name.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The exception is propagated to the invocation stack unless
there is a <a class="reference internal" href="#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause which happens to raise another
exception. That new exception causes the old one to be lost.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>A string literal appearing as the first statement in the function body is
transformed into the function’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute and therefore the
function’s <a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[3]</a></td><td>A string literal appearing as the first statement in the class body is
transformed into the namespace’s <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> item and therefore the class’s
<a class="reference internal" href="../glossary.html#term-docstring"><span class="xref std std-term">docstring</span></a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. Compound statements</a><ul>
<li><a class="reference internal" href="#the-if-statement">7.1. The <code class="docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li><a class="reference internal" href="#the-while-statement">7.2. The <code class="docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li><a class="reference internal" href="#the-for-statement">7.3. The <code class="docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li><a class="reference internal" href="#the-try-statement">7.4. The <code class="docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li><a class="reference internal" href="#the-with-statement">7.5. The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li><a class="reference internal" href="#function-definitions">7.6. Function definitions</a></li>
<li><a class="reference internal" href="#class-definitions">7.7. Class definitions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="simple_stmts.html"
                        title="previous chapter">6. Simple statements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="toplevel_components.html"
                        title="next chapter">8. Top-level components</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/compound_stmts.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="8. Top-level components"
             >next</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. Simple statements"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ŝg�����html/reference/datamodel.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>3. Data model &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. Execution model" href="executionmodel.html" />
    <link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/datamodel.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-model">
<span id="datamodel"></span><h1>3. Data model<a class="headerlink" href="#data-model" title="Permalink to this headline">¶</a></h1>
<div class="section" id="objects-values-and-types">
<span id="objects"></span><h2>3.1. Objects, values and types<a class="headerlink" href="#objects-values-and-types" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><em class="dfn">Objects</em> are Python’s abstraction for data.  All data in a Python program
is represented by objects or by relations between objects. (In a sense, and in
conformance to Von Neumann’s model of a “stored program computer,” code is also
represented by objects.)</p>
<p id="index-1">Every object has an identity, a type and a value.  An object’s <em>identity</em> never
changes once it has been created; you may think of it as the object’s address in
memory.  The ‘<a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>’ operator compares the identity of two objects; the
<a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> function returns an integer representing its identity (currently
implemented as its address). An object’s <em class="dfn">type</em> is also unchangeable. <a class="footnote-reference" href="#id5" id="id1">[1]</a>
An object’s type determines the operations that the object supports (e.g., “does
it have a length?”) and also defines the possible values for objects of that
type.  The <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> function returns an object’s type (which is an object
itself).  The <em>value</em> of some objects can change.  Objects whose value can
change are said to be <em>mutable</em>; objects whose value is unchangeable once they
are created are called <em>immutable</em>. (The value of an immutable container object
that contains a reference to a mutable object can change when the latter’s value
is changed; however the container is still considered immutable, because the
collection of objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.) An
object’s mutability is determined by its type; for instance, numbers, strings
and tuples are immutable, while dictionaries and lists are mutable.</p>
<p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
they may be garbage-collected.  An implementation is allowed to postpone garbage
collection or omit it altogether — it is a matter of implementation quality
how garbage collection is implemented, as long as no objects are collected that
are still reachable.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
detection of cyclically linked garbage, which collects most objects as soon
as they become unreachable, but is not guaranteed to collect garbage
containing circular references.  See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a>
module for information on controlling the collection of cyclic garbage.
Other implementations act differently and CPython may change.
Do not depend on immediate finalization of objects when they become
unreachable (ex: always close files).</p>
</div>
<p>Note that the use of the implementation’s tracing or debugging facilities may
keep objects alive that would normally be collectable. Also note that catching
an exception with a ‘<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>’ statement may keep
objects alive.</p>
<p>Some objects contain references to “external” resources such as open files or
windows.  It is understood that these resources are freed when the object is
garbage-collected, but since garbage collection is not guaranteed to happen,
such objects also provide an explicit way to release the external resource,
usually a <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly
close such objects.  The ‘<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>’ statement
provides a convenient way to do this.</p>
<p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
Examples of containers are tuples, lists and dictionaries.  The references are
part of a container’s value.  In most cases, when we talk about the value of a
container, we imply the values, not the identities of the contained objects;
however, when we talk about the mutability of a container, only the identities
of the immediately contained objects are implied.  So, if an immutable container
(like a tuple) contains a reference to a mutable object, its value changes if
that mutable object is changed.</p>
<p>Types affect almost all aspects of object behavior.  Even the importance of
object identity is affected in some sense: for immutable types, operations that
compute new values may actually return a reference to any existing object with
the same type and value, while for mutable objects this is not allowed.  E.g.,
after <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code>, <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code> may or may not refer to the same object
with the value one, depending on the implementation, but after <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span>
<span class="pre">[]</span></code>, <code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code> are guaranteed to refer to two different, unique, newly
created empty lists. (Note that <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the same object to both
<code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code>.)</p>
</div>
<div class="section" id="the-standard-type-hierarchy">
<span id="types"></span><h2>3.2. The standard type hierarchy<a class="headerlink" href="#the-standard-type-hierarchy" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Below is a list of the types that are built into Python.  Extension modules
(written in C, Java, or other languages, depending on the implementation) can
define additional types.  Future versions of Python may add types to the type
hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).</p>
<p id="index-5">Some of the type descriptions below contain a paragraph listing ‘special
attributes.’  These are attributes that provide access to the implementation and
are not intended for general use.  Their definition may change in the future.</p>
<dl class="docutils">
<dt>None</dt>
<dd><p class="first last" id="index-6">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">None</span></code>. It is used to signify the
absence of a value in many situations, e.g., it is returned from functions that
don’t explicitly return anything. Its truth value is false.</p>
</dd>
<dt>NotImplemented</dt>
<dd><p class="first last" id="index-7">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>. Numeric methods
and rich comparison methods may return this value if they do not implement the
operation for the operands provided.  (The interpreter will then try the
reflected operation, or some other fallback, depending on the operator.)  Its
truth value is true.</p>
</dd>
<dt>Ellipsis</dt>
<dd><p class="first last" id="index-8">This type has a single value.  There is a single object with this value. This
object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>. It is used to
indicate the presence of the <code class="docutils literal notranslate"><span class="pre">...</span></code> syntax in a slice.  Its truth value is
true.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a></dt>
<dd><p class="first" id="index-9">These are created by numeric literals and returned as results by arithmetic
operators and arithmetic built-in functions.  Numeric objects are immutable;
once created their value never changes.  Python numbers are of course strongly
related to mathematical numbers, but subject to the limitations of numerical
representation in computers.</p>
<p>Python distinguishes between integers, floating point numbers, and complex
numbers:</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a></dt>
<dd><p class="first" id="index-10">These represent elements from the mathematical set of integers (positive and
negative).</p>
<p>There are three types of integers:</p>
<dl class="docutils">
<dt>Plain integers</dt>
<dd><p class="first last" id="index-11">These represent numbers in the range -2147483648 through 2147483647.
(The range may be larger on machines with a larger natural word size,
but not smaller.)  When the result of an operation would fall outside
this range, the result is normally returned as a long integer (in some
cases, the exception <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> is raised instead).  For the
purpose of shift and mask operations, integers are assumed to have a
binary, 2’s complement notation using 32 or more bits, and hiding no
bits from the user (i.e., all 4294967296 different bit patterns
correspond to different values).</p>
</dd>
<dt>Long integers</dt>
<dd><p class="first last" id="index-12">These represent numbers in an unlimited range, subject to available
(virtual) memory only.  For the purpose of shift and mask operations, a
binary representation is assumed, and negative numbers are represented
in a variant of 2’s complement which gives the illusion of an infinite
string of sign bits extending to the left.</p>
</dd>
<dt>Booleans</dt>
<dd><p class="first last" id="index-13">These represent the truth values False and True.  The two objects
representing the values <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code> are the only Boolean objects.
The Boolean type is a subtype of plain integers, and Boolean values
behave like the values 0 and 1, respectively, in almost all contexts,
the exception being that when converted to a string, the strings
<code class="docutils literal notranslate"><span class="pre">&quot;False&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;True&quot;</span></code> are returned, respectively.</p>
</dd>
</dl>
<p class="last" id="index-14">The rules for integer representation are intended to give the most
meaningful interpretation of shift and mask operations involving negative
integers and the least surprises when switching between the plain and long
integer domains.  Any operation, if it yields a result in the plain
integer domain, will yield the same result in the long integer domain or
when using mixed operands.  The switch between domains is transparent to
the programmer.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> (<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>)</dt>
<dd><p class="first last" id="index-15">These represent machine-level double precision floating point numbers. You are
at the mercy of the underlying machine architecture (and C or Java
implementation) for the accepted range and handling of overflow. Python does not
support single-precision floating point numbers; the savings in processor and
memory usage that are usually the reason for using these are dwarfed by the
overhead of using objects in Python, so there is no reason to complicate the
language with two kinds of floating point numbers.</p>
</dd>
<dt><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code></a></dt>
<dd><p class="first last" id="index-16">These represent complex numbers as a pair of machine-level double precision
floating point numbers.  The same caveats apply as for floating point numbers.
The real and imaginary parts of a complex number <code class="docutils literal notranslate"><span class="pre">z</span></code> can be retrieved through
the read-only attributes <code class="docutils literal notranslate"><span class="pre">z.real</span></code> and <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>.</p>
</dd>
</dl>
</dd>
<dt>Sequences</dt>
<dd><p class="first" id="index-17">These represent finite ordered sets indexed by non-negative numbers. The
built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number of items of a sequence. When
the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
…, <em>n</em>-1.  Item <em>i</em> of sequence <em>a</em> is selected by <code class="docutils literal notranslate"><span class="pre">a[i]</span></code>.</p>
<p id="index-18">Sequences also support slicing: <code class="docutils literal notranslate"><span class="pre">a[i:j]</span></code> selects all items with index <em>k</em> such
that <em>i</em> <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> <em>k</em> <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> <em>j</em>.  When used as an expression, a slice is a
sequence of the same type.  This implies that the index set is renumbered so
that it starts at 0.</p>
<p id="index-19">Some sequences also support “extended slicing” with a third “step” parameter:
<code class="docutils literal notranslate"><span class="pre">a[i:j:k]</span></code> selects all items of <em>a</em> with index <em>x</em> where <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em>
<code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>i</em> <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> <em>x</em> <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> <em>j</em>.</p>
<p>Sequences are distinguished according to their mutability:</p>
<dl class="last docutils">
<dt>Immutable sequences</dt>
<dd><p class="first" id="index-20">An object of an immutable sequence type cannot change once it is created.  (If
the object contains references to other objects, these other objects may be
mutable and may be changed; however, the collection of objects directly
referenced by an immutable object cannot change.)</p>
<p>The following types are immutable sequences:</p>
<dl class="last docutils">
<dt>Strings</dt>
<dd><p class="first" id="index-21">The items of a string are characters.  There is no separate character type; a
character is represented by a string of one item. Characters represent (at
least) 8-bit bytes.  The built-in functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> and <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> convert
between characters and nonnegative integers representing the byte values.  Bytes
with the values 0–127 usually represent the corresponding ASCII values, but the
interpretation of values is up to the program.  The string data type is also
used to represent arrays of bytes, e.g., to hold data read from a file.</p>
<p class="last" id="index-22">(On systems whose native character set is not ASCII, strings may use EBCDIC in
their internal representation, provided the functions <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> and
<a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> implement a mapping between ASCII and EBCDIC, and string comparison
preserves the ASCII order. Or perhaps someone can propose a better rule?)</p>
</dd>
<dt>Unicode</dt>
<dd><p class="first last" id="index-23">The items of a Unicode object are Unicode code units.  A Unicode code unit is
represented by a Unicode object of one item and can hold either a 16-bit or
32-bit value representing a Unicode ordinal (the maximum value for the ordinal
is given in <code class="docutils literal notranslate"><span class="pre">sys.maxunicode</span></code>, and depends on how Python is configured at
compile time).  Surrogate pairs may be present in the Unicode object, and will
be reported as two separate items.  The built-in functions <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a> and
<a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> convert between code units and nonnegative integers representing the
Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to
other encodings are possible through the Unicode method <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> and the
built-in function <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a>.</p>
</dd>
<dt>Tuples</dt>
<dd><p class="first last" id="index-24">The items of a tuple are arbitrary Python objects. Tuples of two or more items
are formed by comma-separated lists of expressions.  A tuple of one item (a
‘singleton’) can be formed by affixing a comma to an expression (an expression
by itself does not create a tuple, since parentheses must be usable for grouping
of expressions).  An empty tuple can be formed by an empty pair of parentheses.</p>
</dd>
</dl>
</dd>
<dt>Mutable sequences</dt>
<dd><p class="first" id="index-25">Mutable sequences can be changed after they are created.  The subscription and
slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a>
(delete) statements.</p>
<p>There are currently two intrinsic mutable sequence types:</p>
<dl class="docutils">
<dt>Lists</dt>
<dd><p class="first last" id="index-26">The items of a list are arbitrary Python objects.  Lists are formed by placing a
comma-separated list of expressions in square brackets. (Note that there are no
special cases needed to form lists of length 0 or 1.)</p>
</dd>
<dt>Byte Arrays</dt>
<dd><p class="first last" id="index-27">A bytearray object is a mutable array. They are created by the built-in
<a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a> constructor.  Aside from being mutable (and hence
unhashable), byte arrays otherwise provide the same interface and
functionality as immutable bytes objects.</p>
</dd>
</dl>
<p class="last" id="index-28">The extension module <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> provides an additional example of a mutable
sequence type.</p>
</dd>
</dl>
</dd>
<dt>Set types</dt>
<dd><p class="first" id="index-29">These represent unordered, finite sets of unique, immutable objects. As such,
they cannot be indexed by any subscript. However, they can be iterated over, and
the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number of items in a set. Common
uses for sets are fast membership testing, removing duplicates from a sequence,
and computing mathematical operations such as intersection, union, difference,
and symmetric difference.</p>
<p>For set elements, the same immutability rules apply as for dictionary keys. Note
that numeric types obey the normal rules for numeric comparison: if two numbers
compare equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>), only one of them can be contained in a
set.</p>
<p>There are currently two intrinsic set types:</p>
<dl class="last docutils">
<dt>Sets</dt>
<dd><p class="first last" id="index-30">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a>
constructor and can be modified afterwards by several methods, such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>.</p>
</dd>
<dt>Frozen sets</dt>
<dd><p class="first last" id="index-31">These represent an immutable set.  They are created by the built-in
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> constructor.  As a frozenset is immutable and
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, it can be used again as an element of another set, or as
a dictionary key.</p>
</dd>
</dl>
</dd>
<dt>Mappings</dt>
<dd><p class="first" id="index-32">These represent finite sets of objects indexed by arbitrary index sets. The
subscript notation <code class="docutils literal notranslate"><span class="pre">a[k]</span></code> selects the item indexed by <code class="docutils literal notranslate"><span class="pre">k</span></code> from the mapping
<code class="docutils literal notranslate"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements. The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the number
of items in a mapping.</p>
<p>There is currently a single intrinsic mapping type:</p>
<dl class="last docutils">
<dt>Dictionaries</dt>
<dd><p class="first" id="index-33">These represent finite sets of objects indexed by nearly arbitrary values.  The
only types of values not acceptable as keys are values containing lists or
dictionaries or other mutable types that are compared by value rather than by
object identity, the reason being that the efficient implementation of
dictionaries requires a key’s hash value to remain constant. Numeric types used
for keys obey the normal rules for numeric comparison: if two numbers compare
equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>) then they can be used interchangeably to index
the same dictionary entry.</p>
<p>Dictionaries are mutable; they can be created by the <code class="docutils literal notranslate"><span class="pre">{...}</span></code> notation (see
section <a class="reference internal" href="expressions.html#dict"><span class="std std-ref">Dictionary displays</span></a>).</p>
<p class="last" id="index-34">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm" title="dbm: The standard &quot;database&quot; interface, based on ndbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm</span></code></a>, <a class="reference internal" href="../library/gdbm.html#module-gdbm" title="gdbm: GNU's reinterpretation of dbm. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gdbm</span></code></a>, and <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> provide
additional examples of mapping types.</p>
</dd>
</dl>
</dd>
<dt>Callable types</dt>
<dd><p class="first" id="index-35">These are the types to which the function call operation (see section
<a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>) can be applied:</p>
<dl class="last docutils">
<dt>User-defined functions</dt>
<dd><p class="first" id="index-36">A user-defined function object is created by a function definition (see
section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>).  It should be called with an argument list
containing the same number of items as the function’s formal parameter
list.</p>
<p>Special attributes:</p>
<table border="1" class="docutils" id="index-37">
<colgroup>
<col width="35%" />
<col width="48%" />
<col width="17%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Attribute</th>
<th class="head">Meaning</th>
<th class="head">&#160;</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_doc</span></code></td>
<td>The function’s documentation
string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable.</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_name</span></code></td>
<td>The function’s name</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code></td>
<td>The name of the module the
function was defined in, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__defaults__</span></code>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_defaults</span></code></td>
<td>A tuple containing default
argument values for those
arguments that have defaults,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no arguments
have a default value.</td>
<td>Writable</td>
</tr>
<tr class="row-even"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__code__</span></code>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_code</span></code></td>
<td>The code object representing
the compiled function body.</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__globals__</span></code>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_globals</span></code></td>
<td>A reference to the dictionary
that holds the function’s
global variables — the
global namespace of the
module in which the function
was defined.</td>
<td>Read-only</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_dict</span></code></td>
<td>The namespace supporting
arbitrary function
attributes.</td>
<td>Writable</td>
</tr>
<tr class="row-odd"><td><code class="xref py py-attr docutils literal notranslate"><span class="pre">__closure__</span></code>
<code class="xref py py-attr docutils literal notranslate"><span class="pre">func_closure</span></code></td>
<td><code class="docutils literal notranslate"><span class="pre">None</span></code> or a tuple of cells
that contain bindings for the
function’s free variables.</td>
<td>Read-only</td>
</tr>
</tbody>
</table>
<p>Most of the attributes labelled “Writable” check the type of the assigned value.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><code class="docutils literal notranslate"><span class="pre">func_name</span></code> is now writable.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>The double-underscore attributes <code class="docutils literal notranslate"><span class="pre">__closure__</span></code>, <code class="docutils literal notranslate"><span class="pre">__code__</span></code>,
<code class="docutils literal notranslate"><span class="pre">__defaults__</span></code>, and <code class="docutils literal notranslate"><span class="pre">__globals__</span></code> were introduced as aliases for
the corresponding <code class="docutils literal notranslate"><span class="pre">func_*</span></code> attributes for forwards compatibility
with Python 3.</p>
</div>
<p>Function objects also support getting and setting arbitrary attributes, which
can be used, for example, to attach metadata to functions.  Regular attribute
dot-notation is used to get and set such attributes. <em>Note that the current
implementation only supports function attributes on user-defined functions.
Function attributes on built-in functions may be supported in the future.</em></p>
<p class="last">Additional information about a function’s definition can be retrieved from its
code object; see the description of internal types below.</p>
</dd>
<dt>User-defined methods</dt>
<dd><p class="first" id="index-38">A user-defined method object combines a class, a class instance (or <code class="docutils literal notranslate"><span class="pre">None</span></code>)
and any callable object (normally a user-defined function).</p>
<p>Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> is the class instance object,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> is the function object; <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code> is the class of
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> for bound methods or the class that asked for the method for
unbound methods; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the method’s documentation (same as
<code class="docutils literal notranslate"><span class="pre">im_func.__doc__</span></code>); <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the method name (same as
<code class="docutils literal notranslate"><span class="pre">im_func.__name__</span></code>); <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the name of the module the method
was defined in, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.2: </span><code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> used to refer to the class that defined the method.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>For Python 3 forward-compatibility, <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> is also available as
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> as <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code>.</p>
</div>
<p id="index-39">Methods also support accessing (but not setting) the arbitrary function
attributes on the underlying function object.</p>
<p>User-defined method objects may be created when getting an attribute of a class
(perhaps via an instance of that class), if that attribute is a user-defined
function object, an unbound user-defined method object, or a class method
object. When the attribute is a user-defined method object, a new method object
is only created if the class from which it is being retrieved is the same as, or
a derived class of, the class stored in the original method object; otherwise,
the original method object is used as it is.</p>
<p id="index-40">When a user-defined method object is created by retrieving a user-defined
function object from a class, its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> attribute is <code class="docutils literal notranslate"><span class="pre">None</span></code>
and the method object is said to be unbound. When one is created by
retrieving a user-defined function object from a class via one of its
instances, its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> attribute is the instance, and the method
object is said to be bound. In either case, the new method’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code> attribute is the class from which the retrieval takes
place, and its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> attribute is the original function object.</p>
<p id="index-41">When a user-defined method object is created by retrieving another method object
from a class or instance, the behaviour is the same as for a function object,
except that the <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> attribute of the new instance is not the
original method object but its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> attribute.</p>
<p id="index-42">When a user-defined method object is created by retrieving a class method object
from a class or instance, its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> attribute is the class itself, and
its <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> attribute is the function object underlying the class method.</p>
<p>When an unbound user-defined method object is called, the underlying function
(<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code>) is called, with the restriction that the first argument must
be an instance of the proper class (<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code>) or of a derived class
thereof.</p>
<p>When a bound user-defined method object is called, the underlying function
(<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code>) is called, inserting the class instance (<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code>) in
front of the argument list.  For instance, when <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> is a class which
contains a definition for a function <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code>, and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of
<code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, calling <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> is equivalent to calling <code class="docutils literal notranslate"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p>
<p>When a user-defined method object is derived from a class method object, the
“class instance” stored in <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> will actually be the class itself, so
that calling either <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> or <code class="docutils literal notranslate"><span class="pre">C.f(1)</span></code> is equivalent to calling <code class="docutils literal notranslate"><span class="pre">f(C,1)</span></code>
where <code class="docutils literal notranslate"><span class="pre">f</span></code> is the underlying function.</p>
<p class="last">Note that the transformation from function object to (unbound or bound) method
object happens each time the attribute is retrieved from the class or instance.
In some cases, a fruitful optimization is to assign the attribute to a local
variable and call that local variable. Also notice that this transformation only
happens for user-defined functions; other callable objects (and all non-callable
objects) are retrieved without transformation.  It is also important to note
that user-defined functions which are attributes of a class instance are not
converted to bound methods; this <em>only</em> happens when the function is an
attribute of the class.</p>
</dd>
<dt>Generator functions</dt>
<dd><p class="first last" id="index-43">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement (see section
<a class="reference internal" href="simple_stmts.html#yield"><span class="std std-ref">The yield statement</span></a>) is called a <em class="dfn">generator
function</em>.  Such a function, when called, always returns an iterator object
which can be used to execute the body of the function:  calling the iterator’s
<a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method will cause the function to execute until
it provides a value
using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement.  When the function executes a
<a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
exception is raised and the iterator will have reached the end of the set of
values to be returned.</p>
</dd>
<dt>Built-in functions</dt>
<dd><p class="first last" id="index-44">A built-in function object is a wrapper around a C function.  Examples of
built-in functions are <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> (<a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the function’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable; <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the function’s name; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is
set to <code class="docutils literal notranslate"><span class="pre">None</span></code> (but see the next item); <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the name of
the module the function was defined in or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p>
</dd>
<dt>Built-in methods</dt>
<dd><p class="first last" id="index-45">This is really a different disguise of a built-in function, this time containing
an object passed to the C function as an implicit extra argument.  An example of
a built-in method is <code class="docutils literal notranslate"><span class="pre">alist.append()</span></code>, assuming <em>alist</em> is a list object. In
this case, the special read-only attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is set to the object
denoted by <em>alist</em>.</p>
</dd>
<dt>Class Types</dt>
<dd>Class types, or “new-style classes,” are callable.  These objects normally act
as factories for new instances of themselves, but variations are possible for
class types that override <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>.  The arguments of the call are passed
to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to initialize
the new instance.</dd>
<dt>Classic Classes</dt>
<dd><p class="first last" id="index-46">Class objects are described below.  When a class object is called, a new class
instance (also described below) is created and returned.  This implies a call to
the class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method if it has one.  Any arguments are passed on
to the <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method.  If there is no <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, the
class must be called without arguments.</p>
</dd>
<dt>Class instances</dt>
<dd>Class instances are described below.  Class instances are callable only when the
class has a <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method; <code class="docutils literal notranslate"><span class="pre">x(arguments)</span></code> is a shorthand for
<code class="docutils literal notranslate"><span class="pre">x.__call__(arguments)</span></code>.</dd>
</dl>
</dd>
<dt>Modules</dt>
<dd><p class="first" id="index-47">Modules are imported by the <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement (see section
<a class="reference internal" href="simple_stmts.html#import"><span class="std std-ref">The import statement</span></a>). A module object has a
namespace implemented by a dictionary object (this is the dictionary referenced
by the func_globals attribute of functions defined in the module).  Attribute
references are translated to lookups in this dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">m.__dict__[&quot;x&quot;]</span></code>. A module object does not contain the code
object used to initialize the module (since it isn’t needed once the
initialization is done).</p>
<p>Attribute assignment updates the module’s namespace dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span> <span class="pre">=</span>
<span class="pre">1</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.__dict__[&quot;x&quot;]</span> <span class="pre">=</span> <span class="pre">1</span></code>.</p>
<p id="index-48">Special read-only attribute: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the module’s namespace as a
dictionary object.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
dictionary will be cleared when the module falls out of scope even if the
dictionary still has live references.  To avoid this, copy the dictionary
or keep the module around while using its dictionary directly.</p>
</div>
<p class="last" id="index-49">Predefined (writable) attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> is the module’s name;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the module’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
unavailable; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> is the pathname of the file from which the module
was loaded, if it was loaded from a file. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> attribute is not
present for C modules that are statically linked into the interpreter; for
extension modules loaded dynamically from a shared library, it is the pathname
of the shared library file.</p>
</dd>
<dt>Classes</dt>
<dd><p class="first">Both class types (new-style classes) and class objects (old-style/classic
classes) are typically created by class definitions (see section
<a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">Class definitions</span></a>).  A class has a namespace implemented by a dictionary object.
Class attribute references are translated to lookups in this dictionary, e.g.,
<code class="docutils literal notranslate"><span class="pre">C.x</span></code> is translated to <code class="docutils literal notranslate"><span class="pre">C.__dict__[&quot;x&quot;]</span></code> (although for new-style classes
in particular there are a number of hooks which allow for other means of
locating attributes). When the attribute name is not found there, the
attribute search continues in the base classes.  For old-style classes, the
search is depth-first, left-to-right in the order of occurrence in the base
class list. New-style classes use the more complex C3 method resolution
order which behaves correctly even in the presence of ‘diamond’
inheritance structures where there are multiple inheritance paths
leading back to a common ancestor. Additional details on the C3 MRO used by
new-style classes can be found in the documentation accompanying the
2.3 release at <a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
<p id="index-50">When a class attribute reference (for class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, say) would yield a
user-defined function object or an unbound user-defined method object whose
associated class is either <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> or one of its base classes, it is
transformed into an unbound user-defined method object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code>
attribute is <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>. When it would yield a class method object, it is
transformed into a bound user-defined method object whose
<code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> attribute is <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>.  When it would yield a
static method object, it is transformed into the object wrapped by the static
method object. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which
attributes retrieved from a class may differ from those actually contained in
its <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> (note that only new-style classes support descriptors).</p>
<p id="index-51">Class attribute assignments update the class’s dictionary, never the dictionary
of a base class.</p>
<p id="index-52">A class object can be called (see above) to yield a class instance (see below).</p>
<p class="last" id="index-53">Special attributes: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the class name; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is
the module name in which the class was defined; <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the
dictionary containing the class’s namespace; <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> is a
tuple (possibly empty or a singleton) containing the base classes, in the
order of their occurrence in the base class list; <code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the
class’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p>
</dd>
<dt>Class instances</dt>
<dd><p class="first" id="index-54">A class instance is created by calling a class object (see above). A class
instance has a namespace implemented as a dictionary which is the first place in
which attribute references are searched.  When an attribute is not found there,
and the instance’s class has an attribute by that name, the search continues
with the class attributes.  If a class attribute is found that is a user-defined
function object or an unbound user-defined method object whose associated class
is the class (call it <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>) of the instance for which the attribute
reference was initiated or one of its bases, it is transformed into a bound
user-defined method object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_class</span></code> attribute is <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> and
whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> attribute is the instance. Static method and class method
objects are also transformed, as if they had been retrieved from class
<code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>; see above under “Classes”. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for
another way in which attributes of a class retrieved via its instances may
differ from the objects actually stored in the class’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. If no
class attribute is found, and the object’s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>
method, that is called to satisfy the lookup.</p>
<p id="index-55">Attribute assignments and deletions update the instance’s dictionary, never a
class’s dictionary.  If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> or
<a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delattr__()</span></code></a> method, this is called instead of updating the instance
dictionary directly.</p>
<p id="index-56">Class instances can pretend to be numbers, sequences, or mappings if they have
methods with certain special names.  See section <a class="reference internal" href="#specialnames"><span class="std std-ref">Special method names</span></a>.</p>
<p class="last" id="index-57">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the attribute dictionary;
<a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> is the instance’s class.</p>
</dd>
<dt>Files</dt>
<dd><p class="first last" id="index-58">A file object represents an open file.  File objects are created by the
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function, and also by <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>,
<a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a>, and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code> method of socket objects (and
perhaps by other functions or methods provided by extension modules).  The
objects <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> are initialized to
file objects corresponding to the interpreter’s standard input, output and
error streams.  See <a class="reference internal" href="../library/stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a> for complete documentation of
file objects.</p>
</dd>
<dt>Internal types</dt>
<dd><p class="first" id="index-59">A few types used internally by the interpreter are exposed to the user. Their
definitions may change with future versions of the interpreter, but they are
mentioned here for completeness.</p>
<dl class="docutils" id="index-60">
<dt>Code objects</dt>
<dd><p class="first">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.
The difference between a code object and a function object is that the function
object contains an explicit reference to the function’s globals (the module in
which it was defined), while a code object contains no context; also the default
argument values are stored in the function object, not in the code object
(because they represent values calculated at run-time).  Unlike function
objects, code objects are immutable and contain no references (directly or
indirectly) to mutable objects.</p>
<p id="index-61">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_name</span></code> gives the function name;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_argcount</span></code> is the number of positional arguments (including arguments
with default values); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_nlocals</span></code> is the number of local variables used
by the function (including arguments); <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_varnames</span></code> is a tuple containing
the names of the local variables (starting with the argument names);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_cellvars</span></code> is a tuple containing the names of local variables that are
referenced by nested functions; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_freevars</span></code> is a tuple containing the
names of free variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_code</span></code> is a string representing the sequence
of bytecode instructions; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> is a tuple containing the literals
used by the bytecode; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_names</span></code> is a tuple containing the names used by
the bytecode; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_filename</span></code> is the filename from which the code was
compiled; <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_firstlineno</span></code> is the first line number of the function;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_lnotab</span></code> is a string encoding the mapping from bytecode offsets to
line numbers (for details see the source code of the interpreter);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_stacksize</span></code> is the required stack size (including local variables);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> is an integer encoding a number of flags for the interpreter.</p>
<p id="index-62">The following flag bits are defined for <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code>: bit <code class="docutils literal notranslate"><span class="pre">0x04</span></code> is set if
the function uses the <code class="docutils literal notranslate"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of
positional arguments; bit <code class="docutils literal notranslate"><span class="pre">0x08</span></code> is set if the function uses the
<code class="docutils literal notranslate"><span class="pre">**keywords</span></code> syntax to accept arbitrary keyword arguments; bit <code class="docutils literal notranslate"><span class="pre">0x20</span></code> is set
if the function is a generator.</p>
<p>Future feature declarations (<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) also use bits
in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> to indicate whether a code object was compiled with a
particular feature enabled: bit <code class="docutils literal notranslate"><span class="pre">0x2000</span></code> is set if the function was compiled
with future division enabled; bits <code class="docutils literal notranslate"><span class="pre">0x10</span></code> and <code class="docutils literal notranslate"><span class="pre">0x1000</span></code> were used in earlier
versions of Python.</p>
<p>Other bits in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code> are reserved for internal use.</p>
<p class="last" id="index-63">If a code object represents a function, the first item in <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code> is
the documentation string of the function, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p>
</dd>
</dl>
<dl class="last docutils" id="frame-objects">
<dt>Frame objects</dt>
<dd><p class="first" id="index-64">Frame objects represent execution frames.  They may occur in traceback objects
(see below).</p>
<p id="index-65">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_back</span></code> is to the previous stack frame
(towards the caller), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if this is the bottom stack frame;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_code</span></code> is the code object being executed in this frame; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_locals</span></code>
is the dictionary used to look up local variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_globals</span></code> is used for
global variables; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_builtins</span></code> is used for built-in (intrinsic) names;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_restricted</span></code> is a flag indicating whether the function is executing in
restricted execution mode; <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lasti</span></code> gives the precise instruction (this
is an index into the bytecode string of the code object).</p>
<p class="last" id="index-66">Special writable attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace</span></code>, if not <code class="docutils literal notranslate"><span class="pre">None</span></code>, is a function
called at the start of each source code line (this is used by the debugger);
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_exc_type</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_exc_value</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_exc_traceback</span></code> represent the
last exception raised in the parent frame provided another exception was ever
raised in the current frame (in all other cases they are <code class="docutils literal notranslate"><span class="pre">None</span></code>); <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code>
is the current line number of the frame — writing to this from within a trace
function jumps to the given line (only for the bottom-most frame).  A debugger
can implement a Jump command (aka Set Next Statement) by writing to f_lineno.</p>
</dd>
<dt>Traceback objects</dt>
<dd><p class="first" id="index-67">Traceback objects represent a stack trace of an exception.  A traceback object
is created when an exception occurs.  When the search for an exception handler
unwinds the execution stack, at each unwound level a traceback object is
inserted in front of the current traceback.  When an exception handler is
entered, the stack trace is made available to the program. (See section
<a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>.) It is accessible as <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code>,
and also as the third item of the tuple returned by <code class="docutils literal notranslate"><span class="pre">sys.exc_info()</span></code>.  The
latter is the preferred interface, since it works correctly when the program is
using multiple threads. When the program contains no suitable handler, the stack
trace is written (nicely formatted) to the standard error stream; if the
interpreter is interactive, it is also made available to the user as
<code class="docutils literal notranslate"><span class="pre">sys.last_traceback</span></code>.</p>
<p class="last" id="index-68">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_next</span></code> is the next level in the stack
trace (towards the frame where the exception occurred), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is
no next level; <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_frame</span></code> points to the execution frame of the current
level; <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lineno</span></code> gives the line number where the exception occurred;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_lasti</span></code> indicates the precise instruction.  The line number and last
instruction in the traceback may differ from the line number of its frame object
if the exception occurred in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with no matching except
clause or with a finally clause.</p>
</dd>
<dt>Slice objects</dt>
<dd><p class="first" id="index-69">Slice objects are used to represent slices when <em>extended slice syntax</em> is used.
This is a slice using two colons, or multiple slices or ellipses separated by
commas, e.g., <code class="docutils literal notranslate"><span class="pre">a[i:j:step]</span></code>, <code class="docutils literal notranslate"><span class="pre">a[i:j,</span> <span class="pre">k:l]</span></code>, or <code class="docutils literal notranslate"><span class="pre">a[...,</span> <span class="pre">i:j]</span></code>.  They are
also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a> function.</p>
<p id="index-70">Special read-only attributes: <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code> is the lower bound;
<code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> is the upper bound; <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> is the step
value; each is <code class="docutils literal notranslate"><span class="pre">None</span></code> if omitted.  These attributes can have any type.</p>
<p>Slice objects support one method:</p>
<dl class="last method">
<dt id="slice.indices">
<code class="descclassname">slice.</code><code class="descname">indices</code><span class="sig-paren">(</span><em>self</em>, <em>length</em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="Permalink to this definition">¶</a></dt>
<dd><p>This method takes a single integer argument <em>length</em> and computes information
about the extended slice that the slice object would describe if applied to a
sequence of <em>length</em> items.  It returns a tuple of three integers; respectively
these are the <em>start</em> and <em>stop</em> indices and the <em>step</em> or stride length of the
slice. Missing or out-of-bounds indices are handled in a manner consistent with
regular slices.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3.</span></p>
</div>
</dd></dl>

</dd>
<dt>Static method objects</dt>
<dd>Static method objects provide a way of defeating the transformation of function
objects to method objects described above. A static method object is a wrapper
around any other object, usually a user-defined method object. When a static
method object is retrieved from a class or a class instance, the object actually
returned is the wrapped object, which is not subject to any further
transformation. Static method objects are not themselves callable, although the
objects they wrap usually are. Static method objects are created by the built-in
<a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> constructor.</dd>
<dt>Class method objects</dt>
<dd>A class method object, like a static method object, is a wrapper around another
object that alters the way in which that object is retrieved from classes and
class instances. The behaviour of class method objects upon such retrieval is
described above, under “User-defined methods”. Class method objects are created
by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> constructor.</dd>
</dl>
</dd>
</dl>
</div>
<div class="section" id="new-style-and-classic-classes">
<span id="newstyle"></span><h2>3.3. New-style and classic classes<a class="headerlink" href="#new-style-and-classic-classes" title="Permalink to this headline">¶</a></h2>
<p>Classes and instances come in two flavors: old-style (or classic) and new-style.</p>
<p>Up to Python 2.1 the concept of <code class="docutils literal notranslate"><span class="pre">class</span></code> was unrelated to the concept of
<code class="docutils literal notranslate"><span class="pre">type</span></code>, and old-style classes were the only flavor available.  For an
old-style class, the statement <code class="docutils literal notranslate"><span class="pre">x.__class__</span></code> provides the class of <em>x</em>, but
<code class="docutils literal notranslate"><span class="pre">type(x)</span></code> is always <code class="docutils literal notranslate"><span class="pre">&lt;type</span> <span class="pre">'instance'&gt;</span></code>.  This reflects the fact that all
old-style instances, independent of their class, are implemented with a single
built-in type, called <code class="docutils literal notranslate"><span class="pre">instance</span></code>.</p>
<p>New-style classes were introduced in Python 2.2 to unify the concepts of
<code class="docutils literal notranslate"><span class="pre">class</span></code> and <code class="docutils literal notranslate"><span class="pre">type</span></code>.  A new-style class is simply a user-defined type,
no more, no less.  If <em>x</em> is an instance of a new-style class, then <code class="docutils literal notranslate"><span class="pre">type(x)</span></code>
is typically the same as <code class="docutils literal notranslate"><span class="pre">x.__class__</span></code> (although this is not guaranteed – a
new-style class instance is permitted to override the value returned for
<code class="docutils literal notranslate"><span class="pre">x.__class__</span></code>).</p>
<p>The major motivation for introducing new-style classes is to provide a unified
object model with a full meta-model.  It also has a number of practical
benefits, like the ability to subclass most built-in types, or the introduction
of “descriptors”, which enable computed properties.</p>
<p>For compatibility reasons, classes are still old-style by default.  New-style
classes are created by specifying another new-style class (i.e. a type) as a
parent class, or the “top-level type” <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> if no other parent is
needed.  The behaviour of new-style classes differs from that of old-style
classes in a number of important details in addition to what <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>
returns.  Some of these changes are fundamental to the new object model, like
the way special methods are invoked.  Others are “fixes” that could not be
implemented before for compatibility concerns, like the method resolution order
in case of multiple inheritance.</p>
<p>While this manual aims to provide comprehensive coverage of Python’s class
mechanics, it may still be lacking in some areas when it comes to its coverage
of new-style classes. Please see <a class="reference external" href="https://www.python.org/doc/newstyle/">https://www.python.org/doc/newstyle/</a> for
sources of additional information.</p>
<p id="index-71">Old-style classes are removed in Python 3, leaving only new-style classes.</p>
</div>
<div class="section" id="special-method-names">
<span id="specialnames"></span><h2>3.4. Special method names<a class="headerlink" href="#special-method-names" title="Permalink to this headline">¶</a></h2>
<p id="index-72">A class can implement certain operations that are invoked by special syntax
(such as arithmetic operations or subscripting and slicing) by defining methods
with special names. This is Python’s approach to <em class="dfn">operator overloading</em>,
allowing classes to define their own behavior with respect to language
operators.  For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>,
and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of this class, then <code class="docutils literal notranslate"><span class="pre">x[i]</span></code> is roughly equivalent
to <code class="docutils literal notranslate"><span class="pre">x.__getitem__(i)</span></code> for old-style classes and <code class="docutils literal notranslate"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>
for new-style classes.  Except where mentioned, attempts to execute an
operation raise an exception when no appropriate method is defined (typically
<a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>).</p>
<p>When implementing a class that emulates any built-in type, it is important that
the emulation only be implemented to the degree that it makes sense for the
object being modelled.  For example, some sequences may work well with retrieval
of individual elements, but extracting a slice may not make sense.  (One example
of this is the <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> interface in the W3C’s Document
Object Model.)</p>
<div class="section" id="basic-customization">
<span id="customization"></span><h3>3.4.1. Basic customization<a class="headerlink" href="#basic-customization" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__new__">
<code class="descclassname">object.</code><code class="descname">__new__</code><span class="sig-paren">(</span><em>cls</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-73">Called to create a new instance of class <em>cls</em>.  <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is a static
method (special-cased so you need not declare it as such) that takes the class
of which an instance was requested as its first argument.  The remaining
arguments are those passed to the object constructor expression (the call to the
class).  The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> should be the new object instance
(usually an instance of <em>cls</em>).</p>
<p>Typical implementations create a new instance of the class by invoking the
superclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method using <code class="docutils literal notranslate"><span class="pre">super(currentclass,</span>
<span class="pre">cls).__new__(cls[,</span> <span class="pre">...])</span></code> with appropriate arguments and then modifying the
newly-created instance as necessary before returning it.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> returns an instance of <em>cls</em>, then the new instance’s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will be invoked like <code class="docutils literal notranslate"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code>, where
<em>self</em> is the new instance and the remaining arguments are the same as were
passed to <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>.</p>
<p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> does not return an instance of <em>cls</em>, then the new instance’s
<a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will not be invoked.</p>
<p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is intended mainly to allow subclasses of immutable types (like
int, str, or tuple) to customize instance creation.  It is also commonly
overridden in custom metaclasses in order to customize class creation.</p>
</dd></dl>

<dl class="method">
<dt id="object.__init__">
<code class="descclassname">object.</code><code class="descname">__init__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-74">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>), but before
it is returned to the caller.  The arguments are those passed to the
class constructor expression.  If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method,
the derived class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, if any, must explicitly call it to
ensure proper initialization of the base class part of the instance; for
example: <code class="docutils literal notranslate"><span class="pre">BaseClass.__init__(self,</span> <span class="pre">[args...])</span></code>.</p>
<p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> work together in constructing
objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to customise it),
no non-<code class="docutils literal notranslate"><span class="pre">None</span></code> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>; doing so will
cause a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> to be raised at runtime.</p>
</dd></dl>

<dl class="method">
<dt id="object.__del__">
<code class="descclassname">object.</code><code class="descname">__del__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-75">Called when the instance is about to be destroyed.  This is also called a
destructor.  If a base class has a <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, the derived class’s
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, if any, must explicitly call it to ensure proper
deletion of the base class part of the instance.  Note that it is possible
(though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method to postpone destruction
of the instance by creating a new reference to it.  It may then be called at a
later time when this new reference is deleted.  It is not guaranteed that
<a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are called for objects that still exist when the
interpreter exits.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> doesn’t directly call <code class="docutils literal notranslate"><span class="pre">x.__del__()</span></code> — the former decrements
the reference count for <code class="docutils literal notranslate"><span class="pre">x</span></code> by one, and the latter is only called when
<code class="docutils literal notranslate"><span class="pre">x</span></code>’s reference count reaches zero.  Some common situations that may
prevent the reference count of an object from going to zero include:
circular references between objects (e.g., a doubly-linked list or a tree
data structure with parent and child pointers); a reference to the object
on the stack frame of a function that caught an exception (the traceback
stored in <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code> keeps the stack frame alive); or a
reference to the object on the stack frame that raised an unhandled
exception in interactive mode (the traceback stored in
<code class="docutils literal notranslate"><span class="pre">sys.last_traceback</span></code> keeps the stack frame alive).  The first situation
can only be remedied by explicitly breaking the cycles; the latter two
situations can be resolved by storing <code class="docutils literal notranslate"><span class="pre">None</span></code> in <code class="docutils literal notranslate"><span class="pre">sys.exc_traceback</span></code> or
<code class="docutils literal notranslate"><span class="pre">sys.last_traceback</span></code>.  Circular references which are garbage are
detected when the option cycle detector is enabled (it’s on by default),
but can only be cleaned up if there are no Python-level <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a>
methods involved. Refer to the documentation for the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module for
more information about how <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are handled by the
cycle detector, particularly the description of the <code class="docutils literal notranslate"><span class="pre">garbage</span></code> value.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last">Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are
invoked, exceptions that occur during their execution are ignored, and a warning
is printed to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> instead.  Also, when <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> is invoked in
response to a module being deleted (e.g., when execution of the program is
done), other globals referenced by the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method may already have
been deleted or in the process of being torn down (e.g. the import
machinery shutting down).  For this reason, <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods
should do the absolute
minimum needed to maintain external invariants.  Starting with version 1.5,
Python guarantees that globals whose name begins with a single underscore are
deleted from their module before other globals are deleted; if no other
references to such globals exist, this may help in assuring that imported
modules are still available at the time when the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method is
called.</p>
</div>
<p>See also the <a class="reference internal" href="../using/cmdline.html#cmdoption-r"><code class="xref std std-option docutils literal notranslate"><span class="pre">-R</span></code></a> command-line option.</p>
</dd></dl>

<dl class="method">
<dt id="object.__repr__">
<code class="descclassname">object.</code><code class="descname">__repr__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-76">Called by the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> built-in function and by string conversions (reverse
quotes) to compute the “official” string representation of an object.  If at all
possible, this should look like a valid Python expression that could be used to
recreate an object with the same value (given an appropriate environment).  If
this is not possible, a string of the form <code class="docutils literal notranslate"><span class="pre">&lt;...some</span> <span class="pre">useful</span> <span class="pre">description...&gt;</span></code>
should be returned.  The return value must be a string object. If a class
defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> but not <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> is also
used when an “informal” string representation of instances of that class is
required.</p>
<p id="index-77">This is typically used for debugging, so it is important that the representation
is information-rich and unambiguous.</p>
</dd></dl>

<dl class="method">
<dt id="object.__str__">
<code class="descclassname">object.</code><code class="descname">__str__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-78">Called by the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> built-in function and by the <a class="reference internal" href="simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>
statement to compute the “informal” string representation of an object.  This
differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> in that it does not have to be a valid Python
expression: a more convenient or concise representation may be used instead.
The return value must be a string object.</p>
</dd></dl>

<dl class="method">
<dt id="object.__lt__">
<code class="descclassname">object.</code><code class="descname">__lt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__le__">
<code class="descclassname">object.</code><code class="descname">__le__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__le__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__eq__">
<code class="descclassname">object.</code><code class="descname">__eq__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__eq__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ne__">
<code class="descclassname">object.</code><code class="descname">__ne__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ne__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__gt__">
<code class="descclassname">object.</code><code class="descname">__gt__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__gt__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ge__">
<code class="descclassname">object.</code><code class="descname">__ge__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ge__" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionadded">
<p><span class="versionmodified">New in version 2.1.</span></p>
</div>
<p id="index-79">These are the so-called “rich comparison” methods, and are called for comparison
operators in preference to <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> below. The correspondence between
operator symbols and method names is as follows: <code class="docutils literal notranslate"><span class="pre">x&lt;y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__lt__(y)</span></code>,
<code class="docutils literal notranslate"><span class="pre">x&lt;=y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__le__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x==y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__eq__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x!=y</span></code> and
<code class="docutils literal notranslate"><span class="pre">x&lt;&gt;y</span></code> call <code class="docutils literal notranslate"><span class="pre">x.__ne__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x&gt;y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__gt__(y)</span></code>, and <code class="docutils literal notranslate"><span class="pre">x&gt;=y</span></code> calls
<code class="docutils literal notranslate"><span class="pre">x.__ge__(y)</span></code>.</p>
<p>A rich comparison method may return the singleton <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> if it does
not implement the operation for a given pair of arguments. By convention,
<code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code> are returned for a successful comparison. However, these
methods can return any value, so if the comparison operator is used in a Boolean
context (e.g., in the condition of an <code class="docutils literal notranslate"><span class="pre">if</span></code> statement), Python will call
<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> on the value to determine if the result is true or false.</p>
<p>There are no implied relationships among the comparison operators. The truth
of <code class="docutils literal notranslate"><span class="pre">x==y</span></code> does not imply that <code class="docutils literal notranslate"><span class="pre">x!=y</span></code> is false.  Accordingly, when
defining <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a>, one should also define <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a> so that the
operators will behave as expected.  See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> for
some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support
custom comparison operations and are usable as dictionary keys.</p>
<p>There are no swapped-argument versions of these methods (to be used when the
left argument does not support the operation but the right argument does);
rather, <a class="reference internal" href="#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a> are each other’s reflection,
<a class="reference internal" href="#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a> are each other’s reflection, and
<a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a> are their own reflection.</p>
<p>Arguments to rich comparison methods are never coerced.</p>
<p>To automatically generate ordering operations from a single root operation,
see <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.total_ordering()</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__cmp__">
<code class="descclassname">object.</code><code class="descname">__cmp__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__cmp__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-80">Called by comparison operations if rich comparison (see above) is not
defined.  Should return a negative integer if <code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">&lt;</span> <span class="pre">other</span></code>, zero if
<code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">==</span> <span class="pre">other</span></code>, a positive integer if <code class="docutils literal notranslate"><span class="pre">self</span> <span class="pre">&gt;</span> <span class="pre">other</span></code>.  If no
<a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>, <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> or <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a> operation is defined, class
instances are compared by object identity (“address”).  See also the
description of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> for some important notes on creating
<a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support custom comparison operations and are
usable as dictionary keys. (Note: the restriction that exceptions are not
propagated by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> has been removed since Python 1.5.)</p>
</dd></dl>

<dl class="method">
<dt id="object.__rcmp__">
<code class="descclassname">object.</code><code class="descname">__rcmp__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rcmp__" title="Permalink to this definition">¶</a></dt>
<dd><div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.1: </span>No longer supported.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__hash__">
<code class="descclassname">object.</code><code class="descname">__hash__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hash__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-81">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> and for operations on members of
hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, and
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.  <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> should return an integer.  The only required
property is that objects which compare equal have the same hash value; it is
advised to mix together the hash values of the components of the object that
also play a part in comparison of objects by packing them into a tuple and
hashing the tuple. Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">hash</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">nick</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">color</span><span class="p">))</span>
</pre></div>
</div>
<p>If a class does not define a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method it
should not define a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> operation either; if it defines
<a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> but not <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, its instances
will not be usable in hashed collections.  If a class defines mutable objects
and implements a <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method, it should not
implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, since hashable collection implementations require
that an object’s hash value is immutable (if the object’s hash value changes,
it will be in the wrong hash bucket).</p>
<p>User-defined classes have <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> methods
by default; with them, all objects compare unequal (except with themselves)
and <code class="docutils literal notranslate"><span class="pre">x.__hash__()</span></code> returns a result derived from <code class="docutils literal notranslate"><span class="pre">id(x)</span></code>.</p>
<p>Classes which inherit a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method from a parent class but
change the meaning of <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> or <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> such that the hash
value returned is no longer appropriate (e.g. by switching to a value-based
concept of equality instead of the default identity based equality) can
explicitly flag themselves as being unhashable by setting <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code>
in the class definition. Doing so means that not only will instances of the
class raise an appropriate <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> when a program attempts to
retrieve their hash value, but they will also be correctly identified as
unhashable when checking <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.Hashable)</span></code> (unlike
classes which define their own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> to explicitly raise
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>).</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> may now also return a long integer object; the 32-bit
integer is then derived from the hash of that object.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__hash__</span></code></a> may now be set to <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> to explicitly flag
instances of a class as unhashable.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__nonzero__">
<code class="descclassname">object.</code><code class="descname">__nonzero__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__nonzero__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-82">Called to implement truth value testing and the built-in operation <code class="docutils literal notranslate"><span class="pre">bool()</span></code>;
should return <code class="docutils literal notranslate"><span class="pre">False</span></code> or <code class="docutils literal notranslate"><span class="pre">True</span></code>, or their integer equivalents <code class="docutils literal notranslate"><span class="pre">0</span></code> or
<code class="docutils literal notranslate"><span class="pre">1</span></code>.  When this method is not defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> is called, if it is
defined, and the object is considered true if its result is nonzero.
If a class defines neither <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> nor <a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a>, all its
instances are considered true.</p>
</dd></dl>

<dl class="method">
<dt id="object.__unicode__">
<code class="descclassname">object.</code><code class="descname">__unicode__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__unicode__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-83">Called to implement <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> built-in; should return a Unicode object.
When this method is not defined, string conversion is attempted, and the result
of string conversion is converted to Unicode using the system default encoding.</p>
</dd></dl>

</div>
<div class="section" id="customizing-attribute-access">
<span id="attribute-access"></span><h3>3.4.2. Customizing attribute access<a class="headerlink" href="#customizing-attribute-access" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to customize the meaning of attribute
access (use of, assignment to, or deletion of <code class="docutils literal notranslate"><span class="pre">x.name</span></code>) for class instances.</p>
<dl class="method">
<dt id="object.__getattr__">
<code class="descclassname">object.</code><code class="descname">__getattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute lookup has not found the attribute in the usual places
(i.e. it is not an instance attribute nor is it found in the class tree for
<code class="docutils literal notranslate"><span class="pre">self</span></code>).  <code class="docutils literal notranslate"><span class="pre">name</span></code> is the attribute name. This method should return the
(computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception.</p>
<p id="index-84">Note that if the attribute is found through the normal mechanism,
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> is not called.  (This is an intentional asymmetry between
<a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a>.) This is done both for efficiency
reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> would have no way to access
other attributes of the instance.  Note that at least for instance variables,
you can fake total control by not inserting any values in the instance attribute
dictionary (but instead inserting them in another object).  See the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method below for a way to actually get total control in
new-style classes.</p>
</dd></dl>

<dl class="method">
<dt id="object.__setattr__">
<code class="descclassname">object.</code><code class="descname">__setattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called when an attribute assignment is attempted.  This is called instead of the
normal mechanism (i.e. store the value in the instance dictionary).  <em>name</em> is
the attribute name, <em>value</em> is the value to be assigned to it.</p>
<p id="index-85">If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> wants to assign to an instance attribute, it should not
simply execute <code class="docutils literal notranslate"><span class="pre">self.name</span> <span class="pre">=</span> <span class="pre">value</span></code> — this would cause a recursive call to
itself.  Instead, it should insert the value in the dictionary of instance
attributes, e.g., <code class="docutils literal notranslate"><span class="pre">self.__dict__[name]</span> <span class="pre">=</span> <span class="pre">value</span></code>.  For new-style classes,
rather than accessing the instance dictionary, it should call the base class
method with the same name, for example, <code class="docutils literal notranslate"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span>
<span class="pre">value)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delattr__">
<code class="descclassname">object.</code><code class="descname">__delattr__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delattr__" title="Permalink to this definition">¶</a></dt>
<dd><p>Like <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> but for attribute deletion instead of assignment.  This
should only be implemented if <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">obj.name</span></code> is meaningful for the object.</p>
</dd></dl>

<div class="section" id="more-attribute-access-for-new-style-classes">
<span id="new-style-attribute-access"></span><h4>3.4.2.1. More attribute access for new-style classes<a class="headerlink" href="#more-attribute-access-for-new-style-classes" title="Permalink to this headline">¶</a></h4>
<p>The following methods only apply to new-style classes.</p>
<dl class="method">
<dt id="object.__getattribute__">
<code class="descclassname">object.</code><code class="descname">__getattribute__</code><span class="sig-paren">(</span><em>self</em>, <em>name</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattribute__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called unconditionally to implement attribute accesses for instances of the
class. If the class also defines <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>, the latter will not be
called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> either calls it explicitly or raises an
<a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. This method should return the (computed) attribute value
or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception. In order to avoid infinite
recursion in this method, its implementation should always call the base class
method with the same name to access any attributes it needs, for example,
<code class="docutils literal notranslate"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This method may still be bypassed when looking up special methods as the
result of implicit invocation via language syntax or built-in functions.
See <a class="reference internal" href="#new-style-special-lookup"><span class="std std-ref">Special method lookup for new-style classes</span></a>.</p>
</div>
</dd></dl>

</div>
<div class="section" id="implementing-descriptors">
<span id="descriptors"></span><h4>3.4.2.2. Implementing Descriptors<a class="headerlink" href="#implementing-descriptors" title="Permalink to this headline">¶</a></h4>
<p>The following methods only apply when an instance of the class containing the
method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the
descriptor must be in either the owner’s class dictionary or in the class
dictionary for one of its parents).  In the examples below, “the attribute”
refers to the attribute whose name is the key of the property in the owner
class’ <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
<dl class="method">
<dt id="object.__get__">
<code class="descclassname">object.</code><code class="descname">__get__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>owner</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__get__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to get the attribute of the owner class (class attribute access) or of an
instance of that class (instance attribute access). <em>owner</em> is always the owner
class, while <em>instance</em> is the instance that the attribute was accessed through,
or <code class="docutils literal notranslate"><span class="pre">None</span></code> when the attribute is accessed through the <em>owner</em>.  This method
should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>
exception.</p>
</dd></dl>

<dl class="method">
<dt id="object.__set__">
<code class="descclassname">object.</code><code class="descname">__set__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a
new value, <em>value</em>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delete__">
<code class="descclassname">object.</code><code class="descname">__delete__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delete__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p>
</dd></dl>

</div>
<div class="section" id="invoking-descriptors">
<span id="descriptor-invocation"></span><h4>3.4.2.3. Invoking Descriptors<a class="headerlink" href="#invoking-descriptors" title="Permalink to this headline">¶</a></h4>
<p>In general, a descriptor is an object attribute with “binding behavior”, one
whose attribute access has been overridden by methods in the descriptor
protocol:  <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>. If any of
those methods are defined for an object, it is said to be a descriptor.</p>
<p>The default behavior for attribute access is to get, set, or delete the
attribute from an object’s dictionary. For instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> has a lookup chain
starting with <code class="docutils literal notranslate"><span class="pre">a.__dict__['x']</span></code>, then <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x']</span></code>, and
continuing through the base classes of <code class="docutils literal notranslate"><span class="pre">type(a)</span></code> excluding metaclasses.</p>
<p>However, if the looked-up value is an object defining one of the descriptor
methods, then Python may override the default behavior and invoke the descriptor
method instead.  Where this occurs in the precedence chain depends on which
descriptor methods were defined and how they were called.  Note that descriptors
are only invoked for new style objects or classes (ones that subclass
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object()</span></code></a> or <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type()</span></code></a>).</p>
<p>The starting point for descriptor invocation is a binding, <code class="docutils literal notranslate"><span class="pre">a.x</span></code>. How the
arguments are assembled depends on <code class="docutils literal notranslate"><span class="pre">a</span></code>:</p>
<dl class="docutils">
<dt>Direct Call</dt>
<dd>The simplest and least common call is when user code directly invokes a
descriptor method:    <code class="docutils literal notranslate"><span class="pre">x.__get__(a)</span></code>.</dd>
<dt>Instance Binding</dt>
<dd>If binding to a new-style object instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> is transformed into the call:
<code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>.</dd>
<dt>Class Binding</dt>
<dd>If binding to a new-style class, <code class="docutils literal notranslate"><span class="pre">A.x</span></code> is transformed into the call:
<code class="docutils literal notranslate"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>.</dd>
<dt>Super Binding</dt>
<dd>If <code class="docutils literal notranslate"><span class="pre">a</span></code> is an instance of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-class docutils literal notranslate"><span class="pre">super</span></code></a>, then the binding <code class="docutils literal notranslate"><span class="pre">super(B,</span>
<span class="pre">obj).m()</span></code> searches <code class="docutils literal notranslate"><span class="pre">obj.__class__.__mro__</span></code> for the base class <code class="docutils literal notranslate"><span class="pre">A</span></code>
immediately preceding <code class="docutils literal notranslate"><span class="pre">B</span></code> and then invokes the descriptor with the call:
<code class="docutils literal notranslate"><span class="pre">A.__dict__['m'].__get__(obj,</span> <span class="pre">obj.__class__)</span></code>.</dd>
</dl>
<p>For instance bindings, the precedence of descriptor invocation depends on the
which descriptor methods are defined.  A descriptor can define any combination
of <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>.  If it does not
define <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, then accessing the attribute will return the descriptor
object itself unless there is a value in the object’s instance dictionary.  If
the descriptor defines <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> and/or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>, it is a data
descriptor; if it defines neither, it is a non-data descriptor.  Normally, data
descriptors define both <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> and <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, while non-data
descriptors have just the <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> method.  Data descriptors with
<a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be overridden by
instances.</p>
<p>Python methods (including <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>) are
implemented as non-data descriptors.  Accordingly, instances can redefine and
override methods.  This allows individual instances to acquire behaviors that
differ from other instances of the same class.</p>
<p>The <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> function is implemented as a data descriptor. Accordingly,
instances cannot override the behavior of a property.</p>
</div>
<div class="section" id="slots">
<span id="id2"></span><h4>3.4.2.4. __slots__<a class="headerlink" href="#slots" title="Permalink to this headline">¶</a></h4>
<p>By default, instances of both old and new-style classes have a dictionary for
attribute storage.  This wastes space for objects having very few instance
variables.  The space consumption can become acute when creating large numbers
of instances.</p>
<p>The default can be overridden by defining <em>__slots__</em> in a new-style class
definition.  The <em>__slots__</em> declaration takes a sequence of instance variables
and reserves just enough space in each instance to hold a value for each
variable.  Space is saved because <em>__dict__</em> is not created for each instance.</p>
<dl class="data">
<dt id="__slots__">
<code class="descname">__slots__</code><a class="headerlink" href="#__slots__" title="Permalink to this definition">¶</a></dt>
<dd><p>This class variable can be assigned a string, iterable, or sequence of strings
with variable names used by instances.  If defined in a new-style class,
<em>__slots__</em> reserves space for the declared variables and prevents the automatic
creation of <em>__dict__</em> and <em>__weakref__</em> for each instance.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<p>Notes on using <em>__slots__</em></p>
<ul>
<li><p class="first">When inheriting from a class without <em>__slots__</em>, the <em>__dict__</em> attribute of
that class will always be accessible, so a <em>__slots__</em> definition in the
subclass is meaningless.</p>
</li>
<li><p class="first">Without a <em>__dict__</em> variable, instances cannot be assigned new variables not
listed in the <em>__slots__</em> definition.  Attempts to assign to an unlisted
variable name raises <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. If dynamic assignment of new
variables is desired, then add <code class="docutils literal notranslate"><span class="pre">'__dict__'</span></code> to the sequence of strings in the
<em>__slots__</em> declaration.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, adding <code class="docutils literal notranslate"><span class="pre">'__dict__'</span></code> to the <em>__slots__</em> declaration would not
enable the assignment of new attributes not specifically listed in the sequence
of instance variable names.</p>
</div>
</li>
<li><p class="first">Without a <em>__weakref__</em> variable for each instance, classes defining
<em>__slots__</em> do not support weak references to its instances. If weak reference
support is needed, then add <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> to the sequence of strings in the
<em>__slots__</em> declaration.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.3: </span>Previously, adding <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> to the <em>__slots__</em> declaration would not
enable support for weak references.</p>
</div>
</li>
<li><p class="first"><em>__slots__</em> are implemented at the class level by creating descriptors
(<a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a>) for each variable name.  As a result, class attributes
cannot be used to set default values for instance variables defined by
<em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor
assignment.</p>
</li>
<li><p class="first">The action of a <em>__slots__</em> declaration is limited to the class where it is
defined.  As a result, subclasses will have a <em>__dict__</em> unless they also define
<em>__slots__</em> (which must only contain names of any <em>additional</em> slots).</p>
</li>
<li><p class="first">If a class defines a slot also defined in a base class, the instance variable
defined by the base class slot is inaccessible (except by retrieving its
descriptor directly from the base class). This renders the meaning of the
program undefined.  In the future, a check may be added to prevent this.</p>
</li>
<li><p class="first">Nonempty <em>__slots__</em> does not work for classes derived from “variable-length”
built-in types such as <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>, <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p>
</li>
<li><p class="first">Any non-string iterable may be assigned to <em>__slots__</em>. Mappings may also be
used; however, in the future, special meaning may be assigned to the values
corresponding to each key.</p>
</li>
<li><p class="first"><em>__class__</em> assignment works only if both classes have the same <em>__slots__</em>.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Previously, <em>__class__</em> assignment raised an error if either new or old class
had <em>__slots__</em>.</p>
</div>
</li>
</ul>
</div>
</div>
<div class="section" id="customizing-class-creation">
<span id="metaclasses"></span><h3>3.4.3. Customizing class creation<a class="headerlink" href="#customizing-class-creation" title="Permalink to this headline">¶</a></h3>
<p>By default, new-style classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>. A class
definition is read into a separate namespace and the value of class name is
bound to the result of <code class="docutils literal notranslate"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">dict)</span></code>.</p>
<p>When the class definition is read, if <em>__metaclass__</em> is defined then the
callable assigned to it will be called instead of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>. This allows
classes or functions to be written which monitor or alter the class creation
process:</p>
<ul class="simple">
<li>Modifying the class dictionary prior to the class being created.</li>
<li>Returning an instance of another class – essentially performing the role of a
factory function.</li>
</ul>
<p>These steps will have to be performed in the metaclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method
– <code class="xref py py-meth docutils literal notranslate"><span class="pre">type.__new__()</span></code> can then be called from this method to create a class
with different properties.  This example adds a new element to the class
dictionary before creating the class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">metacls</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__new__</span><span class="p">(</span><span class="n">mcs</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">):</span>
        <span class="nb">dict</span><span class="p">[</span><span class="s1">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;metacls was here&#39;</span>
        <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="fm">__new__</span><span class="p">(</span><span class="n">mcs</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">bases</span><span class="p">,</span> <span class="nb">dict</span><span class="p">)</span>
</pre></div>
</div>
<p>You can of course also override other class methods (or add new methods); for
example defining a custom <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method in the metaclass allows custom
behavior when the class is called, e.g. not always creating a new instance.</p>
<dl class="data">
<dt id="__metaclass__">
<code class="descname">__metaclass__</code><a class="headerlink" href="#__metaclass__" title="Permalink to this definition">¶</a></dt>
<dd><p>This variable can be any callable accepting arguments for <code class="docutils literal notranslate"><span class="pre">name</span></code>, <code class="docutils literal notranslate"><span class="pre">bases</span></code>,
and <code class="docutils literal notranslate"><span class="pre">dict</span></code>.  Upon class creation, the callable is used instead of the built-in
<a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<p>The appropriate metaclass is determined by the following precedence rules:</p>
<ul class="simple">
<li>If <code class="docutils literal notranslate"><span class="pre">dict['__metaclass__']</span></code> exists, it is used.</li>
<li>Otherwise, if there is at least one base class, its metaclass is used (this
looks for a <em>__class__</em> attribute first and if not found, uses its type).</li>
<li>Otherwise, if a global variable named __metaclass__ exists, it is used.</li>
<li>Otherwise, the old-style, classic metaclass (types.ClassType) is used.</li>
</ul>
<p>The potential uses for metaclasses are boundless. Some ideas that have been
explored including logging, interface checking, automatic delegation, automatic
property creation, proxies, frameworks, and automatic resource
locking/synchronization.</p>
</div>
<div class="section" id="customizing-instance-and-subclass-checks">
<h3>3.4.4. Customizing instance and subclass checks<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>The following methods are used to override the default behavior of the
<a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> built-in functions.</p>
<p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code></a> implements these methods in
order to allow the addition of Abstract Base Classes (ABCs) as “virtual base
classes” to any class or type (including built-in types), including other
ABCs.</p>
<dl class="method">
<dt id="class.__instancecheck__">
<code class="descclassname">class.</code><code class="descname">__instancecheck__</code><span class="sig-paren">(</span><em>self</em>, <em>instance</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__instancecheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>instance</em> should be considered a (direct or indirect)
instance of <em>class</em>. If defined, called to implement <code class="docutils literal notranslate"><span class="pre">isinstance(instance,</span>
<span class="pre">class)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="class.__subclasscheck__">
<code class="descclassname">class.</code><code class="descname">__subclasscheck__</code><span class="sig-paren">(</span><em>self</em>, <em>subclass</em><span class="sig-paren">)</span><a class="headerlink" href="#class.__subclasscheck__" title="Permalink to this definition">¶</a></dt>
<dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect)
subclass of <em>class</em>.  If defined, called to implement <code class="docutils literal notranslate"><span class="pre">issubclass(subclass,</span>
<span class="pre">class)</span></code>.</p>
</dd></dl>

<p>Note that these methods are looked up on the type (metaclass) of a class.  They
cannot be defined as class methods in the actual class.  This is consistent with
the lookup of special methods that are called on instances, only in this
case the instance is itself a class.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-86"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt>
<dd>Includes the specification for customizing <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and
<a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> behavior through <a class="reference internal" href="#class.__instancecheck__" title="class.__instancecheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a> and
<a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a>, with motivation for this functionality
in the context of adding Abstract Base Classes (see the <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a>
module) to the language.</dd>
</dl>
</div>
</div>
<div class="section" id="emulating-callable-objects">
<span id="callable-types"></span><h3>3.4.5. Emulating callable objects<a class="headerlink" href="#emulating-callable-objects" title="Permalink to this headline">¶</a></h3>
<dl class="method">
<dt id="object.__call__">
<code class="descclassname">object.</code><code class="descname">__call__</code><span class="sig-paren">(</span><em>self</em><span class="optional">[</span>, <em>args...</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__call__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-87">Called when the instance is “called” as a function; if this method is defined,
<code class="docutils literal notranslate"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> is a shorthand for <code class="docutils literal notranslate"><span class="pre">x.__call__(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="emulating-container-types">
<span id="sequence-types"></span><h3>3.4.6. Emulating container types<a class="headerlink" href="#emulating-container-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to implement container objects.  Containers
usually are sequences (such as lists or tuples) or mappings (like dictionaries),
but can represent other containers as well.  The first set of methods is used
either to emulate a sequence or to emulate a mapping; the difference is that for
a sequence, the allowable keys should be the integers <em>k</em> for which <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span>
<span class="pre">N</span></code> where <em>N</em> is the length of the sequence, or slice objects, which define a
range of items. (For backwards compatibility, the method <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a>
(see below) can also be defined to handle simple, but not extended slices.) It
is also recommended that mappings provide the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> behaving similar
to those for Python’s standard dictionary objects.  The <a class="reference internal" href="../library/userdict.html#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserDict</span></code></a> module
provides a <code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code> class to help create those methods from a base set
of <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>. Mutable sequences should provide methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">insert()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code>, like Python standard list
objects.  Finally, sequence types should implement addition (meaning
concatenation) and multiplication (meaning repetition) by defining the methods
<a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>, <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mul__()</span></code></a>,
<a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmul__()</span></code></a> and <a class="reference internal" href="#object.__imul__" title="object.__imul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__imul__()</span></code></a> described below; they should not define
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a> or other numerical operators.  It is recommended that both
mappings and sequences implement the <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method to allow
efficient use of the <code class="docutils literal notranslate"><span class="pre">in</span></code> operator; for mappings, <code class="docutils literal notranslate"><span class="pre">in</span></code> should be equivalent
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">has_key()</span></code>; for sequences, it should search through the values.  It is
further recommended that both mappings and sequences implement the
<a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method to allow efficient iteration through the container; for
mappings, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> should be the same as <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>; for
sequences, it should iterate through the values.</p>
<dl class="method">
<dt id="object.__len__">
<code class="descclassname">object.</code><code class="descname">__len__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__len__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-88">Called to implement the built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>.  Should return the length
of the object, an integer <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> 0.  Also, an object that doesn’t define a
<a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a> method and whose <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> method returns zero is
considered to be false in a Boolean context.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In CPython, the length is required to be at most <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>.
If the length is larger than <code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code> some features (such as
<a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a>) may raise <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>.  To prevent raising
<code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code> by truth value testing, an object must define a
<a class="reference internal" href="#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a> method.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__getitem__">
<code class="descclassname">object.</code><code class="descname">__getitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getitem__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-89">Called to implement evaluation of <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. For sequence types, the
accepted keys should be integers and slice objects.  Note that the special
interpretation of negative indexes (if the class wishes to emulate a sequence
type) is up to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method. If <em>key</em> is of an inappropriate
type, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> may be raised; if of a value outside the set of indexes
for the sequence (after any special interpretation of negative values),
<a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> should be raised. For mapping types, if <em>key</em> is missing (not
in the container), <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> should be raised.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last"><a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> will be raised for illegal
indexes to allow proper detection of the end of the sequence.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__setitem__">
<code class="descclassname">object.</code><code class="descname">__setitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em>, <em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement assignment to <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.  This should only be implemented for mappings if the
objects support changes to the values for keys, or if new keys can be added, or
for sequences if elements can be replaced.  The same exceptions should be raised
for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delitem__">
<code class="descclassname">object.</code><code class="descname">__delitem__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delitem__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement deletion of <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>.  Same note as for
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>.  This should only be implemented for mappings if the
objects support removal of keys, or for sequences if elements can be removed
from the sequence.  The same exceptions should be raised for improper <em>key</em>
values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.</p>
</dd></dl>

<dl class="method">
<dt id="object.__missing__">
<code class="descclassname">object.</code><code class="descname">__missing__</code><span class="sig-paren">(</span><em>self</em>, <em>key</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__missing__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> to implement <code class="docutils literal notranslate"><span class="pre">self[key]</span></code> for dict subclasses
when key is not in the dictionary.</p>
</dd></dl>

<dl class="method">
<dt id="object.__iter__">
<code class="descclassname">object.</code><code class="descname">__iter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iter__" title="Permalink to this definition">¶</a></dt>
<dd><p>This method is called when an iterator is required for a container. This method
should return a new iterator object that can iterate over all the objects in the
container.  For mappings, it should iterate over the keys of the container, and
should also be made available as the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>.</p>
<p>Iterator objects also need to implement this method; they are required to return
themselves.  For more information on iterator objects, see <a class="reference internal" href="../library/stdtypes.html#typeiter"><span class="std std-ref">Iterator Types</span></a>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__reversed__">
<code class="descclassname">object.</code><code class="descname">__reversed__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reversed__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called (if present) by the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> built-in to implement
reverse iteration.  It should return a new iterator object that iterates
over all the objects in the container in reverse order.</p>
<p>If the <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>
built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>).  Objects that support the sequence protocol should
only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> if they can provide an implementation
that is more efficient than the one provided by <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<p>The membership test operators (<a class="reference internal" href="expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="expressions.html#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>) are normally
implemented as an iteration through a sequence.  However, container objects can
supply the following special method with a more efficient implementation, which
also does not require the object be a sequence.</p>
<dl class="method">
<dt id="object.__contains__">
<code class="descclassname">object.</code><code class="descname">__contains__</code><span class="sig-paren">(</span><em>self</em>, <em>item</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__contains__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement membership test operators.  Should return true if <em>item</em>
is in <em>self</em>, false otherwise.  For mapping objects, this should consider the
keys of the mapping rather than the values or the key-item pairs.</p>
<p>For objects that don’t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, the membership test first
tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, then the old sequence iteration
protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><span class="std std-ref">this section in the language
reference</span></a>.</p>
</dd></dl>

</div>
<div class="section" id="additional-methods-for-emulation-of-sequence-types">
<span id="sequence-methods"></span><h3>3.4.7. Additional methods for emulation of sequence types<a class="headerlink" href="#additional-methods-for-emulation-of-sequence-types" title="Permalink to this headline">¶</a></h3>
<p>The following optional methods can be defined to further emulate sequence
objects.  Immutable sequences methods should at most only define
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a>; mutable sequences might define all three methods.</p>
<dl class="method">
<dt id="object.__getslice__">
<code class="descclassname">object.</code><code class="descname">__getslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getslice__" title="Permalink to this definition">¶</a></dt>
<dd><div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.0: </span>Support slice objects as parameters to the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.
(However, built-in types in CPython currently still implement
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a>.  Therefore, you have to override it in derived
classes when implementing slicing.)</p>
</div>
<p>Called to implement evaluation of <code class="docutils literal notranslate"><span class="pre">self[i:j]</span></code>. The returned object should
be of the same type as <em>self</em>.  Note that missing <em>i</em> or <em>j</em> in the slice
expression are replaced by zero or <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>, respectively.  If
negative indexes are used in the slice, the length of the sequence is added
to that index. If the instance does not implement the <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> method,
an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised. No guarantee is made that indexes
adjusted this way are not still negative.  Indexes which are greater than the
length of the sequence are not modified. If no <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a> is found,
a slice object is created instead, and passed to <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> instead.</p>
</dd></dl>

<dl class="method">
<dt id="object.__setslice__">
<code class="descclassname">object.</code><code class="descname">__setslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em>, <em>sequence</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setslice__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement assignment to <code class="docutils literal notranslate"><span class="pre">self[i:j]</span></code>. Same notes for <em>i</em> and <em>j</em> as
for <a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a>.</p>
<p>This method is deprecated. If no <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setslice__()</span></code></a> is found, or for extended
slicing of the form <code class="docutils literal notranslate"><span class="pre">self[i:j:k]</span></code>, a slice object is created, and passed to
<a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, instead of <a class="reference internal" href="#object.__setslice__" title="object.__setslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setslice__()</span></code></a> being called.</p>
</dd></dl>

<dl class="method">
<dt id="object.__delslice__">
<code class="descclassname">object.</code><code class="descname">__delslice__</code><span class="sig-paren">(</span><em>self</em>, <em>i</em>, <em>j</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delslice__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement deletion of <code class="docutils literal notranslate"><span class="pre">self[i:j]</span></code>. Same notes for <em>i</em> and <em>j</em> as for
<a class="reference internal" href="#object.__getslice__" title="object.__getslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getslice__()</span></code></a>. This method is deprecated. If no <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delslice__()</span></code></a> is
found, or for extended slicing of the form <code class="docutils literal notranslate"><span class="pre">self[i:j:k]</span></code>, a slice object is
created, and passed to <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, instead of <a class="reference internal" href="#object.__delslice__" title="object.__delslice__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delslice__()</span></code></a>
being called.</p>
</dd></dl>

<p>Notice that these methods are only invoked when a single slice with a single
colon is used, and the slice method is available.  For slice operations
involving extended slice notation, or in absence of the slice methods,
<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> or <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> is called with a
slice object as argument.</p>
<p>The following example demonstrate how to make your program or module compatible
with earlier versions of Python (assuming that methods <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>,
<a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a> and <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a> support slice objects as
arguments):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>
        <span class="o">...</span>

    <span class="k">if</span> <span class="n">sys</span><span class="o">.</span><span class="n">version_info</span> <span class="o">&lt;</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">):</span>
        <span class="c1"># They won&#39;t be defined if version is at least 2.0 final</span>

        <span class="k">def</span> <span class="nf">__getslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">):</span>
            <span class="k">return</span> <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span>
        <span class="k">def</span> <span class="nf">__setslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">,</span> <span class="n">seq</span><span class="p">):</span>
            <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span> <span class="o">=</span> <span class="n">seq</span>
        <span class="k">def</span> <span class="nf">__delslice__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">):</span>
            <span class="k">del</span> <span class="bp">self</span><span class="p">[</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span><span class="nb">max</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">j</span><span class="p">):]</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Note the calls to <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>; these are necessary because of the handling of
negative indices before the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__*slice__()</span></code> methods are called.  When
negative indexes are used, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__*item__()</span></code> methods receive them as
provided, but the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__*slice__()</span></code> methods get a “cooked” form of the index
values.  For each negative index value, the length of the sequence is added to
the index before calling the method (which may still result in a negative
index); this is the customary handling of negative indexes by the built-in
sequence types, and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__*item__()</span></code> methods are expected to do this as
well.  However, since they should already be doing that, negative indexes cannot
be passed in; they must be constrained to the bounds of the sequence before
being passed to the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__*item__()</span></code> methods. Calling <code class="docutils literal notranslate"><span class="pre">max(0,</span> <span class="pre">i)</span></code>
conveniently returns the proper value.</p>
</div>
<div class="section" id="emulating-numeric-types">
<span id="numeric-types"></span><h3>3.4.8. Emulating numeric types<a class="headerlink" href="#emulating-numeric-types" title="Permalink to this headline">¶</a></h3>
<p>The following methods can be defined to emulate numeric objects. Methods
corresponding to operations that are not supported by the particular kind of
number implemented (e.g., bitwise operations for non-integral numbers) should be
left undefined.</p>
<dl class="method">
<dt id="object.__add__">
<code class="descclassname">object.</code><code class="descname">__add__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__add__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__sub__">
<code class="descclassname">object.</code><code class="descname">__sub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__sub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mul__">
<code class="descclassname">object.</code><code class="descname">__mul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__floordiv__">
<code class="descclassname">object.</code><code class="descname">__floordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__mod__">
<code class="descclassname">object.</code><code class="descname">__mod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__divmod__">
<code class="descclassname">object.</code><code class="descname">__divmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__divmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pow__">
<code class="descclassname">object.</code><code class="descname">__pow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__pow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__lshift__">
<code class="descclassname">object.</code><code class="descname">__lshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rshift__">
<code class="descclassname">object.</code><code class="descname">__rshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__and__">
<code class="descclassname">object.</code><code class="descname">__and__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__and__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__xor__">
<code class="descclassname">object.</code><code class="descname">__xor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__xor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__or__">
<code class="descclassname">object.</code><code class="descname">__or__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__or__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-90">These methods are called to implement the binary arithmetic operations (<code class="docutils literal notranslate"><span class="pre">+</span></code>,
<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>).  For instance, to evaluate the expression
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>
method, <code class="docutils literal notranslate"><span class="pre">x.__add__(y)</span></code> is called.  The <a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__divmod__()</span></code></a> method should be the
equivalent to using <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mod__()</span></code></a>; it should not be
related to <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a> (described below).  Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pow__()</span></code></a>
should be defined to accept an optional third argument if the ternary version of
the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function is to be supported.</p>
<p>If one of those methods does not support the operation with the supplied
arguments, it should return <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__div__">
<code class="descclassname">object.</code><code class="descname">__div__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__div__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__truediv__">
<code class="descclassname">object.</code><code class="descname">__truediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__truediv__" title="Permalink to this definition">¶</a></dt>
<dd><p>The division operator (<code class="docutils literal notranslate"><span class="pre">/</span></code>) is implemented by these methods.  The
<a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a> method is used when <code class="docutils literal notranslate"><span class="pre">__future__.division</span></code> is in effect,
otherwise <a class="reference internal" href="#object.__div__" title="object.__div__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__div__()</span></code></a> is used.  If only one of these two methods is defined,
the object will not support division in the alternate context; <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
will be raised instead.</p>
</dd></dl>

<dl class="method">
<dt id="object.__radd__">
<code class="descclassname">object.</code><code class="descname">__radd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__radd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rsub__">
<code class="descclassname">object.</code><code class="descname">__rsub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rsub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmul__">
<code class="descclassname">object.</code><code class="descname">__rmul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rdiv__">
<code class="descclassname">object.</code><code class="descname">__rdiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rtruediv__">
<code class="descclassname">object.</code><code class="descname">__rtruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rtruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rfloordiv__">
<code class="descclassname">object.</code><code class="descname">__rfloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rfloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rmod__">
<code class="descclassname">object.</code><code class="descname">__rmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rdivmod__">
<code class="descclassname">object.</code><code class="descname">__rdivmod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdivmod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rpow__">
<code class="descclassname">object.</code><code class="descname">__rpow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rpow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rlshift__">
<code class="descclassname">object.</code><code class="descname">__rlshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rlshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rrshift__">
<code class="descclassname">object.</code><code class="descname">__rrshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rrshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rand__">
<code class="descclassname">object.</code><code class="descname">__rand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__rxor__">
<code class="descclassname">object.</code><code class="descname">__rxor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rxor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ror__">
<code class="descclassname">object.</code><code class="descname">__ror__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ror__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-91">These methods are called to implement the binary arithmetic operations (<code class="docutils literal notranslate"><span class="pre">+</span></code>,
<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>) with reflected (swapped) operands.  These functions are
only called if the left operand does not support the corresponding operation and
the operands are of different types. <a class="footnote-reference" href="#id6" id="id3">[2]</a> For instance, to evaluate the
expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code>, where <em>y</em> is an instance of a class that has an
<a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rsub__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">y.__rsub__(x)</span></code> is called if <code class="docutils literal notranslate"><span class="pre">x.__sub__(y)</span></code> returns
<em>NotImplemented</em>.</p>
<p id="index-92">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rpow__()</span></code></a> (the
coercion rules would become too complicated).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">If the right operand’s type is a subclass of the left operand’s type and that
subclass provides the reflected method for the operation, this method will be
called before the left operand’s non-reflected method.  This behavior allows
subclasses to override their ancestors’ operations.</p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__iadd__">
<code class="descclassname">object.</code><code class="descname">__iadd__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iadd__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__isub__">
<code class="descclassname">object.</code><code class="descname">__isub__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__isub__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imul__">
<code class="descclassname">object.</code><code class="descname">__imul__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imul__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__idiv__">
<code class="descclassname">object.</code><code class="descname">__idiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__idiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__itruediv__">
<code class="descclassname">object.</code><code class="descname">__itruediv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__itruediv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ifloordiv__">
<code class="descclassname">object.</code><code class="descname">__ifloordiv__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ifloordiv__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__imod__">
<code class="descclassname">object.</code><code class="descname">__imod__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imod__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ipow__">
<code class="descclassname">object.</code><code class="descname">__ipow__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="optional">[</span>, <em>modulo</em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__ipow__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ilshift__">
<code class="descclassname">object.</code><code class="descname">__ilshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ilshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__irshift__">
<code class="descclassname">object.</code><code class="descname">__irshift__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__irshift__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__iand__">
<code class="descclassname">object.</code><code class="descname">__iand__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iand__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ixor__">
<code class="descclassname">object.</code><code class="descname">__ixor__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ixor__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__ior__">
<code class="descclassname">object.</code><code class="descname">__ior__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ior__" title="Permalink to this definition">¶</a></dt>
<dd><p>These methods are called to implement the augmented arithmetic assignments
(<code class="docutils literal notranslate"><span class="pre">+=</span></code>, <code class="docutils literal notranslate"><span class="pre">-=</span></code>, <code class="docutils literal notranslate"><span class="pre">*=</span></code>, <code class="docutils literal notranslate"><span class="pre">/=</span></code>, <code class="docutils literal notranslate"><span class="pre">//=</span></code>, <code class="docutils literal notranslate"><span class="pre">%=</span></code>, <code class="docutils literal notranslate"><span class="pre">**=</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;=</span></code>,
<code class="docutils literal notranslate"><span class="pre">&amp;=</span></code>, <code class="docutils literal notranslate"><span class="pre">^=</span></code>, <code class="docutils literal notranslate"><span class="pre">|=</span></code>).  These methods should attempt to do the operation
in-place (modifying <em>self</em>) and return the result (which could be, but does
not have to be, <em>self</em>).  If a specific method is not defined, the augmented
assignment falls back to the normal methods.  For instance, to execute the
statement <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that has an
<a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x.__iadd__(y)</span></code> is called.  If <em>x</em> is an instance
of a class that does not define a <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x.__add__(y)</span></code>
and <code class="docutils literal notranslate"><span class="pre">y.__radd__(x)</span></code> are considered, as with the evaluation of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="object.__neg__">
<code class="descclassname">object.</code><code class="descname">__neg__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__neg__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__pos__">
<code class="descclassname">object.</code><code class="descname">__pos__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__pos__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__abs__">
<code class="descclassname">object.</code><code class="descname">__abs__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__abs__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__invert__">
<code class="descclassname">object.</code><code class="descname">__invert__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__invert__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-93">Called to implement the unary arithmetic operations (<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a>
and <code class="docutils literal notranslate"><span class="pre">~</span></code>).</p>
</dd></dl>

<dl class="method">
<dt id="object.__complex__">
<code class="descclassname">object.</code><code class="descname">__complex__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__complex__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__int__">
<code class="descclassname">object.</code><code class="descname">__int__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__int__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__long__">
<code class="descclassname">object.</code><code class="descname">__long__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__long__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__float__">
<code class="descclassname">object.</code><code class="descname">__float__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__float__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-94">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>, <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>,
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a>, and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>.  Should return a value of the appropriate type.</p>
</dd></dl>

<dl class="method">
<dt id="object.__oct__">
<code class="descclassname">object.</code><code class="descname">__oct__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__oct__" title="Permalink to this definition">¶</a></dt>
<dt id="object.__hex__">
<code class="descclassname">object.</code><code class="descname">__hex__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hex__" title="Permalink to this definition">¶</a></dt>
<dd><p id="index-95">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> and <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a>.  Should
return a string value.</p>
</dd></dl>

<dl class="method">
<dt id="object.__index__">
<code class="descclassname">object.</code><code class="descname">__index__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__index__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.index()</span></code></a>.  Also called whenever Python needs
an integer object (such as in slicing).  Must return an integer (int or long).</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
</dd></dl>

<dl class="method">
<dt id="object.__coerce__">
<code class="descclassname">object.</code><code class="descname">__coerce__</code><span class="sig-paren">(</span><em>self</em>, <em>other</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__coerce__" title="Permalink to this definition">¶</a></dt>
<dd><p>Called to implement “mixed-mode” numeric arithmetic.  Should either return a
2-tuple containing <em>self</em> and <em>other</em> converted to a common numeric type, or
<code class="docutils literal notranslate"><span class="pre">None</span></code> if conversion is impossible.  When the common type would be the type of
<code class="docutils literal notranslate"><span class="pre">other</span></code>, it is sufficient to return <code class="docutils literal notranslate"><span class="pre">None</span></code>, since the interpreter will also
ask the other object to attempt a coercion (but sometimes, if the implementation
of the other type cannot be changed, it is useful to do the conversion to the
other type here).  A return value of <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> is equivalent to
returning <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
</dd></dl>

</div>
<div class="section" id="coercion-rules">
<span id="id4"></span><h3>3.4.9. Coercion rules<a class="headerlink" href="#coercion-rules" title="Permalink to this headline">¶</a></h3>
<p>This section used to document the rules for coercion.  As the language has
evolved, the coercion rules have become hard to document precisely; documenting
what one version of one particular implementation does is undesirable.  Instead,
here are some informal guidelines regarding coercion.  In Python 3, coercion
will not be supported.</p>
<ul>
<li><p class="first">If the left operand of a % operator is a string or Unicode object, no coercion
takes place and the string formatting operation is invoked instead.</p>
</li>
<li><p class="first">It is no longer recommended to define a coercion operation. Mixed-mode
operations on types that don’t define coercion pass the original arguments to
the operation.</p>
</li>
<li><p class="first">New-style classes (those derived from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>) never invoke the
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a> method in response to a binary operator; the only time
<a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a> is invoked is when the built-in function <a class="reference internal" href="../library/functions.html#coerce" title="coerce"><code class="xref py py-func docutils literal notranslate"><span class="pre">coerce()</span></code></a> is
called.</p>
</li>
<li><p class="first">For most intents and purposes, an operator that returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code> is
treated the same as one that is not implemented at all.</p>
</li>
<li><p class="first">Below, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__op__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__rop__()</span></code> are used to signify the generic method
names corresponding to an operator; <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iop__()</span></code> is used for the
corresponding in-place operator.  For example, for the operator ‘<code class="docutils literal notranslate"><span class="pre">+</span></code>’,
<a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> and <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a> are used for the left and right variant of
the binary operator, and <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> for the in-place variant.</p>
</li>
<li><p class="first">For objects <em>x</em> and <em>y</em>, first <code class="docutils literal notranslate"><span class="pre">x.__op__(y)</span></code> is tried.  If this is not
implemented or returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, <code class="docutils literal notranslate"><span class="pre">y.__rop__(x)</span></code> is tried.  If this
is also not implemented or returns <code class="docutils literal notranslate"><span class="pre">NotImplemented</span></code>, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
exception is raised.  But see the following exception:</p>
</li>
<li><p class="first">Exception to the previous item: if the left operand is an instance of a built-in
type or a new-style class, and the right operand is an instance of a proper
subclass of that type or class and overrides the base’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__rop__()</span></code> method,
the right operand’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__rop__()</span></code> method is tried <em>before</em> the left operand’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__op__()</span></code> method.</p>
<p>This is done so that a subclass can completely override binary operators.
Otherwise, the left operand’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__op__()</span></code> method would always accept the
right operand: when an instance of a given class is expected, an instance of a
subclass of that class is always acceptable.</p>
</li>
<li><p class="first">When either operand type defines a coercion, this coercion is called before that
type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__op__()</span></code> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__rop__()</span></code> method is called, but no sooner.  If
the coercion returns an object of a different type for the operand whose
coercion is invoked, part of the process is redone using the new object.</p>
</li>
<li><p class="first">When an in-place operator (like ‘<code class="docutils literal notranslate"><span class="pre">+=</span></code>’) is used, if the left operand
implements <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iop__()</span></code>, it is invoked without any coercion.  When the
operation falls back to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__op__()</span></code> and/or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__rop__()</span></code>, the normal
coercion rules apply.</p>
</li>
<li><p class="first">In <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, if <em>x</em> is a sequence that implements sequence concatenation,
sequence concatenation is invoked.</p>
</li>
<li><p class="first">In <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">*</span> <span class="pre">y</span></code>, if one operand is a sequence that implements sequence
repetition, and the other is an integer (<a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>),
sequence repetition is invoked.</p>
</li>
<li><p class="first">Rich comparisons (implemented by methods <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and so on) never use
coercion.  Three-way comparison (implemented by <a class="reference internal" href="#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a>) does use
coercion under the same conditions as other binary operations use it.</p>
</li>
<li><p class="first">In the current implementation, the built-in numeric types <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>,
<a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-class docutils literal notranslate"><span class="pre">long</span></code></a>, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, and <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a> do not use coercion.
All these types implement a <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a> method, for use by the built-in
<a class="reference internal" href="../library/functions.html#coerce" title="coerce"><code class="xref py py-func docutils literal notranslate"><span class="pre">coerce()</span></code></a> function.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>The complex type no longer makes implicit calls to the <a class="reference internal" href="#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a>
method for mixed-type binary arithmetic operations.</p>
</div>
</li>
</ul>
</div>
<div class="section" id="with-statement-context-managers">
<span id="context-managers"></span><h3>3.4.10. With Statement Context Managers<a class="headerlink" href="#with-statement-context-managers" title="Permalink to this headline">¶</a></h3>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be
established when executing a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement. The context manager
handles the entry into, and the exit from, the desired runtime context for the
execution of the block of code.  Context managers are normally invoked using the
<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><span class="std std-ref">The with statement</span></a>), but can also be
used by directly invoking their methods.</p>
<p id="index-96">Typical uses of context managers include saving and restoring various kinds of
global state, locking and unlocking resources, closing opened files, etc.</p>
<p>For more information on context managers, see <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a>.</p>
<dl class="method">
<dt id="object.__enter__">
<code class="descclassname">object.</code><code class="descname">__enter__</code><span class="sig-paren">(</span><em>self</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__enter__" title="Permalink to this definition">¶</a></dt>
<dd><p>Enter the runtime context related to this object. The <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
will bind this method’s return value to the target(s) specified in the
<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause of the statement, if any.</p>
</dd></dl>

<dl class="method">
<dt id="object.__exit__">
<code class="descclassname">object.</code><code class="descname">__exit__</code><span class="sig-paren">(</span><em>self</em>, <em>exc_type</em>, <em>exc_value</em>, <em>traceback</em><span class="sig-paren">)</span><a class="headerlink" href="#object.__exit__" title="Permalink to this definition">¶</a></dt>
<dd><p>Exit the runtime context related to this object. The parameters describe the
exception that caused the context to be exited. If the context was exited
without an exception, all three arguments will be <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>If an exception is supplied, and the method wishes to suppress the exception
(i.e., prevent it from being propagated), it should return a true value.
Otherwise, the exception will be processed normally upon exit from this method.</p>
<p>Note that <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods should not reraise the passed-in exception;
this is the caller’s responsibility.</p>
</dd></dl>

<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-97"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
<dd>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement.</dd>
</dl>
</div>
</div>
<div class="section" id="special-method-lookup-for-old-style-classes">
<span id="old-style-special-lookup"></span><h3>3.4.11. Special method lookup for old-style classes<a class="headerlink" href="#special-method-lookup-for-old-style-classes" title="Permalink to this headline">¶</a></h3>
<p>For old-style classes, special methods are always looked up in exactly the
same way as any other method or attribute. This is the case regardless of
whether the method is being looked up explicitly as in <code class="docutils literal notranslate"><span class="pre">x.__getitem__(i)</span></code>
or implicitly as in <code class="docutils literal notranslate"><span class="pre">x[i]</span></code>.</p>
<p>This behaviour means that special methods may exhibit different behaviour
for different instances of a single old-style class if the appropriate
special attributes are set differently:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c1</span><span class="o">.</span><span class="fm">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c2</span><span class="o">.</span><span class="fm">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c1</span><span class="p">)</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c2</span><span class="p">)</span>
<span class="go">9</span>
</pre></div>
</div>
</div>
<div class="section" id="special-method-lookup-for-new-style-classes">
<span id="new-style-special-lookup"></span><h3>3.4.12. Special method lookup for new-style classes<a class="headerlink" href="#special-method-lookup-for-new-style-classes" title="Permalink to this headline">¶</a></h3>
<p>For new-style classes, implicit invocations of special methods are only guaranteed
to work correctly if defined on an object’s type, not in the object’s instance
dictionary.  That behaviour is the reason why the following code raises an
exception (unlike the equivalent example with old-style classes):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">object of type &#39;C&#39; has no len()</span>
</pre></div>
</div>
<p>The rationale behind this behaviour lies with a number of special methods such
as <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> that are implemented by all objects,
including type objects. If the implicit lookup of these methods used the
conventional lookup process, they would fail when invoked on the type object
itself:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">descriptor &#39;__hash__&#39; of &#39;int&#39; object needs an argument</span>
</pre></div>
</div>
<p>Incorrectly attempting to invoke an unbound method of a class in this way is
sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing
the instance when looking up special methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses the
<a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method even of the object’s metaclass:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span>
<span class="gp">... </span>   <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>      <span class="nb">print</span> <span class="s2">&quot;Metaclass getattribute invoked&quot;</span>
<span class="gp">... </span>      <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">Meta</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__len__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="mi">10</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;Class getattribute invoked&quot;</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span><span class="p">()</span>                 <span class="c1"># Explicit lookup via instance</span>
<span class="go">Class getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="fm">__len__</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>          <span class="c1"># Explicit lookup via type</span>
<span class="go">Metaclass getattribute invoked</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>                      <span class="c1"># Implicit lookup</span>
<span class="go">10</span>
</pre></div>
</div>
<p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> machinery in this fashion
provides significant scope for speed optimisations within the
interpreter, at the cost of some flexibility in the handling of
special methods (the special method <em>must</em> be set on the class
object itself in order to be consistently invoked by the interpreter).</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id5" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>It <em>is</em> possible in some cases to change an object’s type, under certain
controlled conditions. It generally isn’t a good idea though, since it can
lead to some very strange behaviour if it is handled incorrectly.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id6" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[2]</a></td><td>For operands of the same type, it is assumed that if the non-reflected method
(such as <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>) fails the operation is not supported, which is why the
reflected method is not called.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. Data model</a><ul>
<li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
<li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li><a class="reference internal" href="#new-style-and-classic-classes">3.3. New-style and classic classes</a></li>
<li><a class="reference internal" href="#special-method-names">3.4. Special method names</a><ul>
<li><a class="reference internal" href="#basic-customization">3.4.1. Basic customization</a></li>
<li><a class="reference internal" href="#customizing-attribute-access">3.4.2. Customizing attribute access</a><ul>
<li><a class="reference internal" href="#more-attribute-access-for-new-style-classes">3.4.2.1. More attribute access for new-style classes</a></li>
<li><a class="reference internal" href="#implementing-descriptors">3.4.2.2. Implementing Descriptors</a></li>
<li><a class="reference internal" href="#invoking-descriptors">3.4.2.3. Invoking Descriptors</a></li>
<li><a class="reference internal" href="#slots">3.4.2.4. __slots__</a></li>
</ul>
</li>
<li><a class="reference internal" href="#customizing-class-creation">3.4.3. Customizing class creation</a></li>
<li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.4.4. Customizing instance and subclass checks</a></li>
<li><a class="reference internal" href="#emulating-callable-objects">3.4.5. Emulating callable objects</a></li>
<li><a class="reference internal" href="#emulating-container-types">3.4.6. Emulating container types</a></li>
<li><a class="reference internal" href="#additional-methods-for-emulation-of-sequence-types">3.4.7. Additional methods for emulation of sequence types</a></li>
<li><a class="reference internal" href="#emulating-numeric-types">3.4.8. Emulating numeric types</a></li>
<li><a class="reference internal" href="#coercion-rules">3.4.9. Coercion rules</a></li>
<li><a class="reference internal" href="#with-statement-context-managers">3.4.10. With Statement Context Managers</a></li>
<li><a class="reference internal" href="#special-method-lookup-for-old-style-classes">3.4.11. Special method lookup for old-style classes</a></li>
<li><a class="reference internal" href="#special-method-lookup-for-new-style-classes">3.4.12. Special method lookup for new-style classes</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="lexical_analysis.html"
                        title="previous chapter">2. Lexical analysis</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="executionmodel.html"
                        title="next chapter">4. Execution model</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/datamodel.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             >next</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\,�s�kkkk"html/reference/executionmodel.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. Execution model &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="5. Expressions" href="expressions.html" />
    <link rel="prev" title="3. Data model" href="datamodel.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/executionmodel.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="expressions.html" title="5. Expressions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="datamodel.html" title="3. Data model"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="execution-model">
<span id="execmodel"></span><h1>4. Execution model<a class="headerlink" href="#execution-model" title="Permalink to this headline">¶</a></h1>
<div class="section" id="naming-and-binding">
<span id="naming"></span><span id="index-0"></span><h2>4.1. Naming and binding<a class="headerlink" href="#naming-and-binding" title="Permalink to this headline">¶</a></h2>
<span class="target" id="index-1"></span><p id="index-2"><em class="dfn">Names</em> refer to objects.  Names are introduced by name binding operations.
Each occurrence of a name in the program text refers to the <em class="dfn">binding</em> of
that name established in the innermost function block containing the use.</p>
<p id="index-3">A <em class="dfn">block</em> is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class definition.
Each command typed interactively is a block.  A script file (a file given as
standard input to the interpreter or specified on the interpreter command line
the first argument) is a code block.  A script command (a command specified on
the interpreter command line with the ‘<strong>-c</strong>’ option) is a code block.  The
file read by the built-in function <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> is a code block.  The string
argument passed to the built-in function <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> and to the <a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>
statement is a code block. The expression read and evaluated by the built-in
function <a class="reference internal" href="../library/functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> is a code block.</p>
<p id="index-4">A code block is executed in an <em class="dfn">execution frame</em>.  A frame contains some
administrative information (used for debugging) and determines where and how
execution continues after the code block’s execution has completed.</p>
<p id="index-5">A <em class="dfn">scope</em> defines the visibility of a name within a block.  If a local
variable is defined in a block, its scope includes that block.  If the
definition occurs in a function block, the scope extends to any blocks contained
within the defining one, unless a contained block introduces a different binding
for the name.  The scope of names defined in a class block is limited to the
class block; it does not extend to the code blocks of methods – this includes
generator expressions since they are implemented using a function scope.  This
means that the following will fail:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
    <span class="n">a</span> <span class="o">=</span> <span class="mi">42</span>
    <span class="n">b</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="n">a</span> <span class="o">+</span> <span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>
</pre></div>
</div>
<p id="index-6">When a name is used in a code block, it is resolved using the nearest enclosing
scope.  The set of all such scopes visible to a code block is called the block’s
<em class="dfn">environment</em>.</p>
<p id="index-7">If a name is bound in a block, it is a local variable of that block. If a name
is bound at the module level, it is a global variable.  (The variables of the
module code block are local and global.)  If a variable is used in a code block
but not defined there, it is a <em class="dfn">free variable</em>.</p>
<p id="index-8">When a name is not found at all, a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception is raised.  If the
name refers to a local variable that has not been bound, a
<a class="reference internal" href="../library/exceptions.html#exceptions.UnboundLocalError" title="exceptions.UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> exception is raised.  <a class="reference internal" href="../library/exceptions.html#exceptions.UnboundLocalError" title="exceptions.UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> is a
subclass of <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>.</p>
<p id="index-9">The following constructs bind names: formal parameters to functions,
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements, class and function definitions (these bind the
class or function name in the defining block), and targets that are identifiers
if occurring in an assignment, <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop header, in the second
position of an <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause header or after <a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> in a
<a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.  The <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement
of the form <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span> <span class="pre">*</span></code> binds all names defined in the imported
module, except those beginning with an underscore.  This form may only be used
at the module level.</p>
<p>A target occurring in a <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement is also considered bound for
this purpose (though the actual semantics are to unbind the name).  It is
illegal to unbind a name that is referenced by an enclosing scope; the compiler
will report a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
<p>Each assignment or import statement occurs within a block defined by a class or
function definition or at the module level (the top-level code block).</p>
<p>If a name binding operation occurs anywhere within a code block, all uses of the
name within the block are treated as references to the current block.  This can
lead to errors when a name is used within a block before it is bound. This rule
is subtle.  Python lacks declarations and allows name binding operations to
occur anywhere within a code block.  The local variables of a code block can be
determined by scanning the entire text of the block for name binding operations.</p>
<p>If the global statement occurs within a block, all uses of the name specified in
the statement refer to the binding of that name in the top-level namespace.
Names are resolved in the top-level namespace by searching the global namespace,
i.e. the namespace of the module containing the code block, and the builtins
namespace, the namespace of the module <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a>.  The global namespace
is searched first.  If the name is not found there, the builtins namespace is
searched.  The global statement must precede all uses of the name.</p>
<p id="index-10">The builtins namespace associated with the execution of a code block is actually
found by looking up the name <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> in its global namespace; this
should be a dictionary or a module (in the latter case the module’s dictionary
is used).  By default, when in the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module, <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> is
the built-in module <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> (note: no ‘s’); when in any other module,
<code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> is an alias for the dictionary of the <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module
itself.  <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> can be set to a user-created dictionary to create a
weak form of restricted execution.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Users should not touch <code class="docutils literal notranslate"><span class="pre">__builtins__</span></code>; it is strictly an implementation
detail.  Users wanting to override values in the builtins namespace should
<a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> the <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> (no ‘s’) module and modify its
attributes appropriately.</p>
</div>
<p id="index-11">The namespace for a module is automatically created the first time a module is
imported.  The main module for a script is always called <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>.</p>
<p>The <a class="reference internal" href="simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement has the same scope as a name binding operation
in the same block.  If the nearest enclosing scope for a free variable contains
a global statement, the free variable is treated as a global.</p>
<p>A class definition is an executable statement that may use and define names.
These references follow the normal rules for name resolution. The namespace of
the class definition becomes the attribute dictionary of the class.  Names
defined at the class scope are not visible in methods.</p>
<div class="section" id="interaction-with-dynamic-features">
<span id="dynamic-features"></span><h3>4.1.1. Interaction with dynamic features<a class="headerlink" href="#interaction-with-dynamic-features" title="Permalink to this headline">¶</a></h3>
<p>There are several cases where Python statements are illegal when used in
conjunction with nested scopes that contain free variables.</p>
<p>If a variable is referenced in an enclosing scope, it is illegal to delete the
name.  An error will be reported at compile time.</p>
<p>If the wild card form of import — <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">*</span></code> — is used in a function and
the function contains or is a nested block with free variables, the compiler
will raise a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
<p>If <a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> is used in a function and the function contains or is a
nested block with free variables, the compiler will raise a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>
unless the exec explicitly specifies the local namespace for the
<a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>.  (In other words, <code class="docutils literal notranslate"><span class="pre">exec</span> <span class="pre">obj</span></code> would be illegal, but <code class="docutils literal notranslate"><span class="pre">exec</span> <span class="pre">obj</span>
<span class="pre">in</span> <span class="pre">ns</span></code> would be legal.)</p>
<p>The <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a>, and <a class="reference internal" href="../library/functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> functions and the
<a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement do not have access to the full environment for
resolving names.  Names may be resolved in the local and global namespaces of
the caller.  Free variables are not resolved in the nearest enclosing namespace,
but in the global namespace. <a class="footnote-reference" href="#id3" id="id1">[1]</a> The <a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement and the
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> and <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> functions have optional arguments to override
the global and local namespace.  If only one namespace is specified, it is used
for both.</p>
</div>
</div>
<div class="section" id="exceptions">
<span id="id2"></span><h2>4.2. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<span class="target" id="index-12"></span><p id="index-13">Exceptions are a means of breaking out of the normal flow of control of a code
block in order to handle errors or other exceptional conditions.  An exception
is <em>raised</em> at the point where the error is detected; it may be <em>handled</em> by the
surrounding code block or by any code block that directly or indirectly invoked
the code block where the error occurred.</p>
<p>The Python interpreter raises an exception when it detects a run-time error
(such as division by zero).  A Python program can also explicitly raise an
exception with the <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement. Exception handlers are specified
with the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement.  The <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
clause of such a statement can be used to specify cleanup code which does not
handle the exception, but is executed whether an exception occurred or not in
the preceding code.</p>
<p id="index-14">Python uses the “termination” model of error handling: an exception handler can
find out what happened and continue execution at an outer level, but it cannot
repair the cause of the error and retry the failing operation (except by
re-entering the offending piece of code from the top).</p>
<p id="index-15">When an exception is not handled at all, the interpreter terminates execution of
the program, or returns to its interactive main loop.  In either case, it prints
a stack backtrace, except when the exception is  <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>.</p>
<p>Exceptions are identified by class instances.  The <a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is
selected depending on the class of the instance: it must reference the class of
the instance or a base class thereof.  The instance can be received by the
handler and can carry additional information about the exceptional condition.</p>
<p>Exceptions can also be identified by strings, in which case the
<a class="reference internal" href="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is selected by object identity.  An arbitrary value can
be raised along with the identifying string which can be passed to the handler.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Messages to exceptions are not part of the Python API.  Their contents may
change from one version of Python to the next without warning and should not be
relied on by code which will run under multiple versions of the interpreter.</p>
</div>
<p>See also the description of the <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement in section <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>
and <a class="reference internal" href="simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement in section <a class="reference internal" href="simple_stmts.html#raise"><span class="std std-ref">The raise statement</span></a>.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>This limitation occurs because the code that is executed by these operations is
not available at the time the module is compiled.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Execution model</a><ul>
<li><a class="reference internal" href="#naming-and-binding">4.1. Naming and binding</a><ul>
<li><a class="reference internal" href="#interaction-with-dynamic-features">4.1.1. Interaction with dynamic features</a></li>
</ul>
</li>
<li><a class="reference internal" href="#exceptions">4.2. Exceptions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="datamodel.html"
                        title="previous chapter">3. Data model</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="expressions.html"
                        title="next chapter">5. Expressions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/executionmodel.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="expressions.html" title="5. Expressions"
             >next</a> |</li>
        <li class="right" >
          <a href="datamodel.html" title="3. Data model"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��p�P�Phtml/reference/expressions.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>5. Expressions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="6. Simple statements" href="simple_stmts.html" />
    <link rel="prev" title="4. Execution model" href="executionmodel.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/expressions.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. Simple statements"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="expressions">
<span id="id1"></span><h1>5. Expressions<a class="headerlink" href="#expressions" title="Permalink to this headline">¶</a></h1>
<p id="index-0">This chapter explains the meaning of the elements of expressions in Python.</p>
<p id="index-1"><strong>Syntax Notes:</strong> In this and the following chapters, extended BNF notation will
be used to describe syntax, not lexical analysis.  When (one alternative of) a
syntax rule has the form</p>
<pre>
<strong id="grammar-token-name">name</strong> ::=  <code class="xref docutils literal notranslate"><span class="pre">othername</span></code>
</pre>
<p id="index-2">and no semantics are given, the semantics of this form of <code class="docutils literal notranslate"><span class="pre">name</span></code> are the same
as for <code class="docutils literal notranslate"><span class="pre">othername</span></code>.</p>
<div class="section" id="arithmetic-conversions">
<span id="conversions"></span><h2>5.1. Arithmetic conversions<a class="headerlink" href="#arithmetic-conversions" title="Permalink to this headline">¶</a></h2>
<p id="index-3">When a description of an arithmetic operator below uses the phrase “the numeric
arguments are converted to a common type,” the arguments are coerced using the
coercion rules listed at  <a class="reference internal" href="datamodel.html#coercion-rules"><span class="std std-ref">Coercion rules</span></a>.  If both arguments are standard
numeric types, the following coercions are applied:</p>
<ul class="simple">
<li>If either argument is a complex number, the other is converted to complex;</li>
<li>otherwise, if either argument is a floating point number, the other is
converted to floating point;</li>
<li>otherwise, if either argument is a long integer, the other is converted to
long integer;</li>
<li>otherwise, both must be plain integers and no conversion is necessary.</li>
</ul>
<p>Some additional rules apply for certain operators (e.g., a string left argument
to the ‘%’ operator). Extensions can define their own coercions.</p>
</div>
<div class="section" id="atoms">
<span id="id2"></span><h2>5.2. Atoms<a class="headerlink" href="#atoms" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Atoms are the most basic elements of expressions.  The simplest atoms are
identifiers or literals.  Forms enclosed in reverse quotes or in parentheses,
brackets or braces are also categorized syntactically as atoms.  The syntax for
atoms is:</p>
<pre>
<strong id="grammar-token-atom">atom     </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="#grammar-token-literal"><code class="xref docutils literal notranslate"><span class="pre">literal</span></code></a> | <a class="reference internal" href="#grammar-token-enclosure"><code class="xref docutils literal notranslate"><span class="pre">enclosure</span></code></a>
<strong id="grammar-token-enclosure">enclosure</strong> ::=  <a class="reference internal" href="#grammar-token-parenth_form"><code class="xref docutils literal notranslate"><span class="pre">parenth_form</span></code></a> | <a class="reference internal" href="#grammar-token-list_display"><code class="xref docutils literal notranslate"><span class="pre">list_display</span></code></a>
               | <a class="reference internal" href="#grammar-token-generator_expression"><code class="xref docutils literal notranslate"><span class="pre">generator_expression</span></code></a> | <a class="reference internal" href="#grammar-token-dict_display"><code class="xref docutils literal notranslate"><span class="pre">dict_display</span></code></a> | <a class="reference internal" href="#grammar-token-set_display"><code class="xref docutils literal notranslate"><span class="pre">set_display</span></code></a>
               | <a class="reference internal" href="#grammar-token-string_conversion"><code class="xref docutils literal notranslate"><span class="pre">string_conversion</span></code></a> | <a class="reference internal" href="#grammar-token-yield_atom"><code class="xref docutils literal notranslate"><span class="pre">yield_atom</span></code></a>
</pre>
<div class="section" id="atom-identifiers">
<span id="identifiers-names"></span><h3>5.2.1. Identifiers (Names)<a class="headerlink" href="#atom-identifiers" title="Permalink to this headline">¶</a></h3>
<p id="index-5">An identifier occurring as an atom is a name.  See section <a class="reference internal" href="lexical_analysis.html#identifiers"><span class="std std-ref">Identifiers and keywords</span></a>
for lexical definition and section <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">Naming and binding</span></a> for documentation of naming and
binding.</p>
<p id="index-6">When the name is bound to an object, evaluation of the atom yields that object.
When a name is not bound, an attempt to evaluate it raises a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>
exception.</p>
<p id="index-7"><strong>Private name mangling:</strong> When an identifier that textually occurs in a class
definition begins with two or more underscore characters and does not end in two
or more underscores, it is considered a <em class="dfn">private name</em> of that class.
Private names are transformed to a longer form before code is generated for
them.  The transformation inserts the class name, with leading underscores
removed and a single underscore inserted, in front of the name.  For example,
the identifier <code class="docutils literal notranslate"><span class="pre">__spam</span></code> occurring in a class named <code class="docutils literal notranslate"><span class="pre">Ham</span></code> will be transformed
to <code class="docutils literal notranslate"><span class="pre">_Ham__spam</span></code>.  This transformation is independent of the syntactical
context in which the identifier is used.  If the transformed name is extremely
long (longer than 255 characters), implementation defined truncation may happen.
If the class name consists only of underscores, no transformation is done.</p>
</div>
<div class="section" id="literals">
<span id="atom-literals"></span><h3>5.2.2. Literals<a class="headerlink" href="#literals" title="Permalink to this headline">¶</a></h3>
<p id="index-8">Python supports string literals and various numeric literals:</p>
<pre>
<strong id="grammar-token-literal">literal</strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-stringliteral"><code class="xref docutils literal notranslate"><span class="pre">stringliteral</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-longinteger"><code class="xref docutils literal notranslate"><span class="pre">longinteger</span></code></a>
             | <a class="reference internal" href="lexical_analysis.html#grammar-token-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="lexical_analysis.html#grammar-token-imagnumber"><code class="xref docutils literal notranslate"><span class="pre">imagnumber</span></code></a>
</pre>
<p>Evaluation of a literal yields an object of the given type (string, integer,
long integer, floating point number, complex number) with the given value.  The
value may be approximated in the case of floating point and imaginary (complex)
literals.  See section <a class="reference internal" href="lexical_analysis.html#literals"><span class="std std-ref">Literals</span></a> for details.</p>
<p id="index-9">All literals correspond to immutable data types, and hence the object’s identity
is less important than its value.  Multiple evaluations of literals with the
same value (either the same occurrence in the program text or a different
occurrence) may obtain the same object or a different object with the same
value.</p>
</div>
<div class="section" id="parenthesized-forms">
<span id="parenthesized"></span><h3>5.2.3. Parenthesized forms<a class="headerlink" href="#parenthesized-forms" title="Permalink to this headline">¶</a></h3>
<p id="index-10">A parenthesized form is an optional expression list enclosed in parentheses:</p>
<pre>
<strong id="grammar-token-parenth_form">parenth_form</strong> ::=  &quot;(&quot; [<a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>] &quot;)&quot;
</pre>
<p>A parenthesized expression list yields whatever that expression list yields: if
the list contains at least one comma, it yields a tuple; otherwise, it yields
the single expression that makes up the expression list.</p>
<p id="index-11">An empty pair of parentheses yields an empty tuple object.  Since tuples are
immutable, the rules for literals apply (i.e., two occurrences of the empty
tuple may or may not yield the same object).</p>
<p id="index-12">Note that tuples are not formed by the parentheses, but rather by use of the
comma operator.  The exception is the empty tuple, for which parentheses <em>are</em>
required — allowing unparenthesized “nothing” in expressions would cause
ambiguities and allow common typos to pass uncaught.</p>
</div>
<div class="section" id="list-displays">
<span id="lists"></span><h3>5.2.4. List displays<a class="headerlink" href="#list-displays" title="Permalink to this headline">¶</a></h3>
<p id="index-13">A list display is a possibly empty series of expressions enclosed in square
brackets:</p>
<pre>
<strong id="grammar-token-list_display">list_display       </strong> ::=  &quot;[&quot; [<a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-list_comprehension"><code class="xref docutils literal notranslate"><span class="pre">list_comprehension</span></code></a>] &quot;]&quot;
<strong id="grammar-token-list_comprehension">list_comprehension </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-list_for"><code class="xref docutils literal notranslate"><span class="pre">list_for</span></code></a>
<strong id="grammar-token-list_for">list_for           </strong> ::=  &quot;for&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;in&quot; <a class="reference internal" href="#grammar-token-old_expression_list"><code class="xref docutils literal notranslate"><span class="pre">old_expression_list</span></code></a> [<a class="reference internal" href="#grammar-token-list_iter"><code class="xref docutils literal notranslate"><span class="pre">list_iter</span></code></a>]
<strong id="grammar-token-old_expression_list">old_expression_list</strong> ::=  <a class="reference internal" href="#grammar-token-old_expression"><code class="xref docutils literal notranslate"><span class="pre">old_expression</span></code></a> [(&quot;,&quot; <a class="reference internal" href="#grammar-token-old_expression"><code class="xref docutils literal notranslate"><span class="pre">old_expression</span></code></a>)+ [&quot;,&quot;]]
<strong id="grammar-token-old_expression">old_expression     </strong> ::=  <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> | <a class="reference internal" href="#grammar-token-old_lambda_expr"><code class="xref docutils literal notranslate"><span class="pre">old_lambda_expr</span></code></a>
<strong id="grammar-token-list_iter">list_iter          </strong> ::=  <a class="reference internal" href="#grammar-token-list_for"><code class="xref docutils literal notranslate"><span class="pre">list_for</span></code></a> | <a class="reference internal" href="#grammar-token-list_if"><code class="xref docutils literal notranslate"><span class="pre">list_if</span></code></a>
<strong id="grammar-token-list_if">list_if            </strong> ::=  &quot;if&quot; <a class="reference internal" href="#grammar-token-old_expression"><code class="xref docutils literal notranslate"><span class="pre">old_expression</span></code></a> [<a class="reference internal" href="#grammar-token-list_iter"><code class="xref docutils literal notranslate"><span class="pre">list_iter</span></code></a>]
</pre>
<p id="index-14">A list display yields a new list object.  Its contents are specified by
providing either a list of expressions or a list comprehension.  When a
comma-separated list of expressions is supplied, its elements are evaluated from
left to right and placed into the list object in that order.  When a list
comprehension is supplied, it consists of a single expression followed by at
least one <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> clause and zero or more <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>
clauses.  In this case, the elements of the new list are those that would be
produced by considering each of the <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clauses a
block, nesting from left to right, and evaluating the expression to produce a
list element each time the innermost block is reached <a class="footnote-reference" href="#id19" id="id3">[1]</a>.</p>
</div>
<div class="section" id="displays-for-sets-and-dictionaries">
<span id="comprehensions"></span><h3>5.2.5. Displays for sets and dictionaries<a class="headerlink" href="#displays-for-sets-and-dictionaries" title="Permalink to this headline">¶</a></h3>
<p>For constructing a set or a dictionary Python provides special syntax
called “displays”, each of them in two flavors:</p>
<ul class="simple">
<li>either the container contents are listed explicitly, or</li>
<li>they are computed via a set of looping and filtering instructions, called a
<em class="dfn">comprehension</em>.</li>
</ul>
<p>Common syntax elements for comprehensions are:</p>
<pre>
<strong id="grammar-token-comprehension">comprehension</strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
<strong id="grammar-token-comp_for">comp_for     </strong> ::=  &quot;for&quot; <a class="reference internal" href="simple_stmts.html#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;in&quot; <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [<a class="reference internal" href="#grammar-token-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
<strong id="grammar-token-comp_iter">comp_iter    </strong> ::=  <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> | <a class="reference internal" href="#grammar-token-comp_if"><code class="xref docutils literal notranslate"><span class="pre">comp_if</span></code></a>
<strong id="grammar-token-comp_if">comp_if      </strong> ::=  &quot;if&quot; <code class="xref docutils literal notranslate"><span class="pre">expression_nocond</span></code> [<a class="reference internal" href="#grammar-token-comp_iter"><code class="xref docutils literal notranslate"><span class="pre">comp_iter</span></code></a>]
</pre>
<p>The comprehension consists of a single expression followed by at least one
<a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> clause and zero or more <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clauses.
In this case, the elements of the new container are those that would be produced
by considering each of the <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clauses a block,
nesting from left to right, and evaluating the expression to produce an element
each time the innermost block is reached.</p>
<p>Note that the comprehension is executed in a separate scope, so names assigned
to in the target list don’t “leak” in the enclosing scope.</p>
</div>
<div class="section" id="generator-expressions">
<span id="genexpr"></span><h3>5.2.6. Generator expressions<a class="headerlink" href="#generator-expressions" title="Permalink to this headline">¶</a></h3>
<p id="index-15">A generator expression is a compact generator notation in parentheses:</p>
<pre>
<strong id="grammar-token-generator_expression">generator_expression</strong> ::=  &quot;(&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a> &quot;)&quot;
</pre>
<p>A generator expression yields a new generator object.  Its syntax is the same as
for comprehensions, except that it is enclosed in parentheses instead of
brackets or curly braces.</p>
<p>Variables used in the generator expression are evaluated lazily when the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__next__()</span></code> method is called for generator object (in the same fashion as
normal generators).  However, the leftmost <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> clause is immediately
evaluated, so that an error produced by it can be seen before any other possible
error in the code that handles the generator expression.  Subsequent
<a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> clauses cannot be evaluated immediately since they may depend on
the previous <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop. For example: <code class="docutils literal notranslate"><span class="pre">(x*y</span> <span class="pre">for</span> <span class="pre">x</span> <span class="pre">in</span> <span class="pre">range(10)</span> <span class="pre">for</span> <span class="pre">y</span>
<span class="pre">in</span> <span class="pre">bar(x))</span></code>.</p>
<p>The parentheses can be omitted on calls with only one argument.  See section
<a class="reference internal" href="#calls"><span class="std std-ref">Calls</span></a> for the detail.</p>
</div>
<div class="section" id="dictionary-displays">
<span id="dict"></span><h3>5.2.7. Dictionary displays<a class="headerlink" href="#dictionary-displays" title="Permalink to this headline">¶</a></h3>
<p id="index-16">A dictionary display is a possibly empty series of key/datum pairs enclosed in
curly braces:</p>
<pre>
<strong id="grammar-token-dict_display">dict_display      </strong> ::=  &quot;{&quot; [<a class="reference internal" href="#grammar-token-key_datum_list"><code class="xref docutils literal notranslate"><span class="pre">key_datum_list</span></code></a> | <a class="reference internal" href="#grammar-token-dict_comprehension"><code class="xref docutils literal notranslate"><span class="pre">dict_comprehension</span></code></a>] &quot;}&quot;
<strong id="grammar-token-key_datum_list">key_datum_list    </strong> ::=  <a class="reference internal" href="#grammar-token-key_datum"><code class="xref docutils literal notranslate"><span class="pre">key_datum</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-key_datum"><code class="xref docutils literal notranslate"><span class="pre">key_datum</span></code></a>)* [&quot;,&quot;]
<strong id="grammar-token-key_datum">key_datum         </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-dict_comprehension">dict_comprehension</strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> &quot;:&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <a class="reference internal" href="#grammar-token-comp_for"><code class="xref docutils literal notranslate"><span class="pre">comp_for</span></code></a>
</pre>
<p>A dictionary display yields a new dictionary object.</p>
<p>If a comma-separated sequence of key/datum pairs is given, they are evaluated
from left to right to define the entries of the dictionary: each key object is
used as a key into the dictionary to store the corresponding datum.  This means
that you can specify the same key multiple times in the key/datum list, and the
final dictionary’s value for that key will be the last one given.</p>
<p>A dict comprehension, in contrast to list and set comprehensions, needs two
expressions separated with a colon followed by the usual “for” and “if” clauses.
When the comprehension is run, the resulting key and value elements are inserted
in the new dictionary in the order they are produced.</p>
<p id="index-17">Restrictions on the types of the key values are listed earlier in section
<a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>.  (To summarize, the key type should be <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, which excludes
all mutable objects.)  Clashes between duplicate keys are not detected; the last
datum (textually rightmost in the display) stored for a given key value
prevails.</p>
</div>
<div class="section" id="set-displays">
<span id="set"></span><h3>5.2.8. Set displays<a class="headerlink" href="#set-displays" title="Permalink to this headline">¶</a></h3>
<p id="index-18">A set display is denoted by curly braces and distinguishable from dictionary
displays by the lack of colons separating keys and values:</p>
<pre>
<strong id="grammar-token-set_display">set_display</strong> ::=  &quot;{&quot; (<a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="#grammar-token-comprehension"><code class="xref docutils literal notranslate"><span class="pre">comprehension</span></code></a>) &quot;}&quot;
</pre>
<p>A set display yields a new mutable set object, the contents being specified by
either a sequence of expressions or a comprehension.  When a comma-separated
list of expressions is supplied, its elements are evaluated from left to right
and added to the set object.  When a comprehension is supplied, the set is
constructed from the elements resulting from the comprehension.</p>
<p>An empty set cannot be constructed with <code class="docutils literal notranslate"><span class="pre">{}</span></code>; this literal constructs an empty
dictionary.</p>
</div>
<div class="section" id="string-conversions">
<span id="id4"></span><h3>5.2.9. String conversions<a class="headerlink" href="#string-conversions" title="Permalink to this headline">¶</a></h3>
<p id="index-19">A string conversion is an expression list enclosed in reverse (a.k.a. backward)
quotes:</p>
<pre>
<strong id="grammar-token-string_conversion">string_conversion</strong> ::=  &quot;`&quot; <a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;`&quot;
</pre>
<p>A string conversion evaluates the contained expression list and converts the
resulting object into a string according to rules specific to its type.</p>
<p>If the object is a string, a number, <code class="docutils literal notranslate"><span class="pre">None</span></code>, or a tuple, list or dictionary
containing only objects whose type is one of these, the resulting string is a
valid Python expression which can be passed to the built-in function
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> to yield an expression with the same value (or an approximation, if
floating point numbers are involved).</p>
<p>(In particular, converting a string adds quotes around it and converts “funny”
characters to escape sequences that are safe to print.)</p>
<p id="index-20">Recursive objects (for example, lists or dictionaries that contain a reference
to themselves, directly or indirectly) use <code class="docutils literal notranslate"><span class="pre">...</span></code> to indicate a recursive
reference, and the result cannot be passed to <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> to get an equal value
(<a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> will be raised instead).</p>
<p id="index-21">The built-in function <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> performs exactly the same conversion in its
argument as enclosing it in parentheses and reverse quotes does.  The built-in
function <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> performs a similar but more user-friendly conversion.</p>
</div>
<div class="section" id="yield-expressions">
<span id="yieldexpr"></span><h3>5.2.10. Yield expressions<a class="headerlink" href="#yield-expressions" title="Permalink to this headline">¶</a></h3>
<pre id="index-22">
<strong id="grammar-token-yield_atom">yield_atom      </strong> ::=  &quot;(&quot; <a class="reference internal" href="#grammar-token-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a> &quot;)&quot;
<strong id="grammar-token-yield_expression">yield_expression</strong> ::=  &quot;yield&quot; [<a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>]
</pre>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<p>The <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression is only used when defining a generator function,
and can only be used in the body of a function definition. Using a
<a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression in a function definition is sufficient to cause that
definition to create a generator function instead of a normal function.</p>
<p>When a generator function is called, it returns an iterator known as a
generator.  That generator then controls the execution of a generator function.
The execution starts when one of the generator’s methods is called.  At that
time, the execution proceeds to the first <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression, where it
is suspended again, returning the value of <a class="reference internal" href="#grammar-token-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> to
generator’s caller.  By suspended we mean that all local state is retained,
including the current bindings of local variables, the instruction pointer, and
the internal evaluation stack.  When the execution is resumed by calling one of
the generator’s methods, the function can proceed exactly as if the
<a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression was just another external call. The value of the
<a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression after resuming depends on the method which resumed
the execution.</p>
<p id="index-23">All of this makes generator functions quite similar to coroutines; they yield
multiple times, they have more than one entry point and their execution can be
suspended.  The only difference is that a generator function cannot control
where should the execution continue after it yields; the control is always
transferred to the generator’s caller.</p>
<div class="section" id="generator-iterator-methods">
<span id="index-24"></span><h4>5.2.10.1. Generator-iterator methods<a class="headerlink" href="#generator-iterator-methods" title="Permalink to this headline">¶</a></h4>
<p>This subsection describes the methods of a generator iterator.  They can
be used to control the execution of a generator function.</p>
<p>Note that calling any of the generator methods below when the generator
is already executing raises a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
<span class="target" id="index-25"></span><dl class="method">
<dt id="generator.next">
<code class="descclassname">generator.</code><code class="descname">next</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.next" title="Permalink to this definition">¶</a></dt>
<dd><p>Starts the execution of a generator function or resumes it at the last executed
<a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression.  When a generator function is resumed with a
<a class="reference internal" href="#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method, the current <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression
always evaluates to
<a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.  The execution then continues to the next <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
expression, where the generator is suspended again, and the value of the
<a class="reference internal" href="#grammar-token-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> is returned to <a class="reference internal" href="#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a>’s caller.
If the generator
exits without yielding another value, a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is
raised.</p>
</dd></dl>

<dl class="method">
<dt id="generator.send">
<code class="descclassname">generator.</code><code class="descname">send</code><span class="sig-paren">(</span><em>value</em><span class="sig-paren">)</span><a class="headerlink" href="#generator.send" title="Permalink to this definition">¶</a></dt>
<dd><p>Resumes the execution and “sends” a value into the generator function.  The
<code class="docutils literal notranslate"><span class="pre">value</span></code> argument becomes the result of the current <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
expression.  The <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method returns the next value yielded by the
generator, or raises <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> if the generator exits without
yielding another value. When <a class="reference internal" href="#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> is called to start the generator, it
must be called with <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> as the argument, because there is no
<a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression that could receive the value.</p>
</dd></dl>

<dl class="method">
<dt id="generator.throw">
<code class="descclassname">generator.</code><code class="descname">throw</code><span class="sig-paren">(</span><em>type</em><span class="optional">[</span>, <em>value</em><span class="optional">[</span>, <em>traceback</em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.throw" title="Permalink to this definition">¶</a></dt>
<dd><p>Raises an exception of type <code class="docutils literal notranslate"><span class="pre">type</span></code> at the point where generator was paused,
and returns the next value yielded by the generator function.  If the generator
exits without yielding another value, a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is
raised.  If the generator function does not catch the passed-in exception, or
raises a different exception, then that exception propagates to the caller.</p>
</dd></dl>

<span class="target" id="index-26"></span><dl class="method">
<dt id="generator.close">
<code class="descclassname">generator.</code><code class="descname">close</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#generator.close" title="Permalink to this definition">¶</a></dt>
<dd><p>Raises a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> at the point where the generator function was
paused.  If the generator function then raises <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> (by exiting
normally, or due to already being closed) or <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> (by not
catching the exception), close returns to its caller.  If the generator yields a
value, a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised.  If the generator raises any other
exception, it is propagated to the caller.  <a class="reference internal" href="#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> does nothing if the
generator has already exited due to an exception or normal exit.</p>
</dd></dl>

<p>Here is a simple example that demonstrates the behavior of generators and
generator functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">echo</span><span class="p">(</span><span class="n">value</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;Execution starts when &#39;next()&#39; is called for the first time.&quot;</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>                <span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">value</span><span class="p">)</span>
<span class="gp">... </span>            <span class="k">except</span> <span class="ne">Exception</span><span class="p">,</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span>                <span class="n">value</span> <span class="o">=</span> <span class="n">e</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;Don&#39;t forget to clean up when &#39;close()&#39; is called.&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span> <span class="o">=</span> <span class="n">echo</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">generator</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">Execution starts when &#39;next()&#39; is called for the first time.</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">generator</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">generator</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span><span class="o">.</span><span class="n">throw</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="s2">&quot;spam&quot;</span><span class="p">)</span>
<span class="go">TypeError(&#39;spam&#39;,)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">generator</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="go">Don&#39;t forget to clean up when &#39;close()&#39; is called.</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-27"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd>The proposal to enhance the API and syntax of generators, making them usable as
simple coroutines.</dd>
</dl>
</div>
</div>
</div>
</div>
<div class="section" id="primaries">
<span id="id5"></span><h2>5.3. Primaries<a class="headerlink" href="#primaries" title="Permalink to this headline">¶</a></h2>
<p id="index-28">Primaries represent the most tightly bound operations of the language. Their
syntax is:</p>
<pre>
<strong id="grammar-token-primary">primary</strong> ::=  <a class="reference internal" href="#grammar-token-atom"><code class="xref docutils literal notranslate"><span class="pre">atom</span></code></a> | <a class="reference internal" href="#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a> | <a class="reference internal" href="#grammar-token-call"><code class="xref docutils literal notranslate"><span class="pre">call</span></code></a>
</pre>
<div class="section" id="attribute-references">
<span id="id6"></span><h3>5.3.1. Attribute references<a class="headerlink" href="#attribute-references" title="Permalink to this headline">¶</a></h3>
<p id="index-29">An attribute reference is a primary followed by a period and a name:</p>
<pre>
<strong id="grammar-token-attributeref">attributeref</strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;.&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p id="index-30">The primary must evaluate to an object of a type that supports attribute
references, e.g., a module, list, or an instance.  This object is then asked to
produce the attribute whose name is the identifier.  If this attribute is not
available, the exception <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> is raised. Otherwise, the type
and value of the object produced is determined by the object.  Multiple
evaluations of the same attribute reference may yield different objects.</p>
</div>
<div class="section" id="subscriptions">
<span id="id7"></span><h3>5.3.2. Subscriptions<a class="headerlink" href="#subscriptions" title="Permalink to this headline">¶</a></h3>
<span class="target" id="index-31"></span><p id="index-32">A subscription selects an item of a sequence (string, tuple or list) or mapping
(dictionary) object:</p>
<pre>
<strong id="grammar-token-subscription">subscription</strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;[&quot; <a class="reference internal" href="#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> &quot;]&quot;
</pre>
<p>The primary must evaluate to an object of a sequence or mapping type.</p>
<p>If the primary is a mapping, the expression list must evaluate to an object
whose value is one of the keys of the mapping, and the subscription selects the
value in the mapping that corresponds to that key.  (The expression list is a
tuple except if it has exactly one item.)</p>
<p>If the primary is a sequence, the expression list must evaluate to a plain
integer.  If this value is negative, the length of the sequence is added to it
(so that, e.g., <code class="docutils literal notranslate"><span class="pre">x[-1]</span></code> selects the last item of <code class="docutils literal notranslate"><span class="pre">x</span></code>.)  The resulting value
must be a nonnegative integer less than the number of items in the sequence, and
the subscription selects the item whose index is that value (counting from
zero).</p>
<p id="index-33">A string’s items are characters.  A character is not a separate data type but a
string of exactly one character.</p>
</div>
<div class="section" id="slicings">
<span id="id8"></span><h3>5.3.3. Slicings<a class="headerlink" href="#slicings" title="Permalink to this headline">¶</a></h3>
<span class="target" id="index-34"></span><p id="index-35">A slicing selects a range of items in a sequence object (e.g., a string, tuple
or list).  Slicings may be used as expressions or as targets in assignment or
<a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements.  The syntax for a slicing:</p>
<pre>
<strong id="grammar-token-slicing">slicing         </strong> ::=  <a class="reference internal" href="#grammar-token-simple_slicing"><code class="xref docutils literal notranslate"><span class="pre">simple_slicing</span></code></a> | <a class="reference internal" href="#grammar-token-extended_slicing"><code class="xref docutils literal notranslate"><span class="pre">extended_slicing</span></code></a>
<strong id="grammar-token-simple_slicing">simple_slicing  </strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;[&quot; <a class="reference internal" href="#grammar-token-short_slice"><code class="xref docutils literal notranslate"><span class="pre">short_slice</span></code></a> &quot;]&quot;
<strong id="grammar-token-extended_slicing">extended_slicing</strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;[&quot; <a class="reference internal" href="#grammar-token-slice_list"><code class="xref docutils literal notranslate"><span class="pre">slice_list</span></code></a> &quot;]&quot;
<strong id="grammar-token-slice_list">slice_list      </strong> ::=  <a class="reference internal" href="#grammar-token-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-slice_item"><code class="xref docutils literal notranslate"><span class="pre">slice_item</span></code></a>)* [&quot;,&quot;]
<strong id="grammar-token-slice_item">slice_item      </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> | <a class="reference internal" href="#grammar-token-proper_slice"><code class="xref docutils literal notranslate"><span class="pre">proper_slice</span></code></a> | <a class="reference internal" href="#grammar-token-ellipsis"><code class="xref docutils literal notranslate"><span class="pre">ellipsis</span></code></a>
<strong id="grammar-token-proper_slice">proper_slice    </strong> ::=  <a class="reference internal" href="#grammar-token-short_slice"><code class="xref docutils literal notranslate"><span class="pre">short_slice</span></code></a> | <a class="reference internal" href="#grammar-token-long_slice"><code class="xref docutils literal notranslate"><span class="pre">long_slice</span></code></a>
<strong id="grammar-token-short_slice">short_slice     </strong> ::=  [<a class="reference internal" href="#grammar-token-lower_bound"><code class="xref docutils literal notranslate"><span class="pre">lower_bound</span></code></a>] &quot;:&quot; [<a class="reference internal" href="#grammar-token-upper_bound"><code class="xref docutils literal notranslate"><span class="pre">upper_bound</span></code></a>]
<strong id="grammar-token-long_slice">long_slice      </strong> ::=  <a class="reference internal" href="#grammar-token-short_slice"><code class="xref docutils literal notranslate"><span class="pre">short_slice</span></code></a> &quot;:&quot; [<a class="reference internal" href="#grammar-token-stride"><code class="xref docutils literal notranslate"><span class="pre">stride</span></code></a>]
<strong id="grammar-token-lower_bound">lower_bound     </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-upper_bound">upper_bound     </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-stride">stride          </strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-ellipsis">ellipsis        </strong> ::=  &quot;...&quot;
</pre>
<p id="index-36">There is ambiguity in the formal syntax here: anything that looks like an
expression list also looks like a slice list, so any subscription can be
interpreted as a slicing.  Rather than further complicating the syntax, this is
disambiguated by defining that in this case the interpretation as a subscription
takes priority over the interpretation as a slicing (this is the case if the
slice list contains no proper slice nor ellipses).  Similarly, when the slice
list has exactly one short slice and no trailing comma, the interpretation as a
simple slicing takes priority over that as an extended slicing.</p>
<p>The semantics for a simple slicing are as follows.  The primary must evaluate to
a sequence object.  The lower and upper bound expressions, if present, must
evaluate to plain integers; defaults are zero and the <code class="docutils literal notranslate"><span class="pre">sys.maxint</span></code>,
respectively.  If either bound is negative, the sequence’s length is added to
it.  The slicing now selects all items with index <em>k</em> such that <code class="docutils literal notranslate"><span class="pre">i</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span> <span class="pre">j</span></code>
where <em>i</em> and <em>j</em> are the specified lower and upper bounds.  This may be an
empty sequence.  It is not an error if <em>i</em> or <em>j</em> lie outside the range of valid
indexes (such items don’t exist so they aren’t selected).</p>
<p id="index-37">The semantics for an extended slicing are as follows.  The primary must evaluate
to a mapping object, and it is indexed with a key that is constructed from the
slice list, as follows.  If the slice list contains at least one comma, the key
is a tuple containing the conversion of the slice items; otherwise, the
conversion of the lone slice item is the key.  The conversion of a slice item
that is an expression is that expression.  The conversion of an ellipsis slice
item is the built-in <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code> object.  The conversion of a proper slice is a
slice object (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>) whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code> attributes are the values of the
expressions given as lower bound, upper bound and stride, respectively,
substituting <code class="docutils literal notranslate"><span class="pre">None</span></code> for missing expressions.</p>
</div>
<div class="section" id="calls">
<span id="index-38"></span><span id="id9"></span><h3>5.3.4. Calls<a class="headerlink" href="#calls" title="Permalink to this headline">¶</a></h3>
<p>A call calls a callable object (e.g., a <a class="reference internal" href="../glossary.html#term-function"><span class="xref std std-term">function</span></a>) with a possibly empty
series of <a class="reference internal" href="../glossary.html#term-argument"><span class="xref std std-term">arguments</span></a>:</p>
<pre>
<strong id="grammar-token-call">call                </strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> &quot;(&quot; [<a class="reference internal" href="#grammar-token-argument_list"><code class="xref docutils literal notranslate"><span class="pre">argument_list</span></code></a> [&quot;,&quot;]
                          | <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> <code class="xref docutils literal notranslate"><span class="pre">genexpr_for</span></code>] &quot;)&quot;
<strong id="grammar-token-argument_list">argument_list       </strong> ::=  <a class="reference internal" href="#grammar-token-positional_arguments"><code class="xref docutils literal notranslate"><span class="pre">positional_arguments</span></code></a> [&quot;,&quot; <a class="reference internal" href="#grammar-token-keyword_arguments"><code class="xref docutils literal notranslate"><span class="pre">keyword_arguments</span></code></a>]
                            [&quot;,&quot; &quot;*&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>] [&quot;,&quot; <a class="reference internal" href="#grammar-token-keyword_arguments"><code class="xref docutils literal notranslate"><span class="pre">keyword_arguments</span></code></a>]
                            [&quot;,&quot; &quot;**&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
                          | <a class="reference internal" href="#grammar-token-keyword_arguments"><code class="xref docutils literal notranslate"><span class="pre">keyword_arguments</span></code></a> [&quot;,&quot; &quot;*&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
                            [&quot;,&quot; &quot;**&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
                          | &quot;*&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="#grammar-token-keyword_arguments"><code class="xref docutils literal notranslate"><span class="pre">keyword_arguments</span></code></a>] [&quot;,&quot; &quot;**&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
                          | &quot;**&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-positional_arguments">positional_arguments</strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)*
<strong id="grammar-token-keyword_arguments">keyword_arguments   </strong> ::=  <a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-keyword_item"><code class="xref docutils literal notranslate"><span class="pre">keyword_item</span></code></a>)*
<strong id="grammar-token-keyword_item">keyword_item        </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> &quot;=&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
</pre>
<p>A trailing comma may be present after the positional and keyword arguments but
does not affect the semantics.</p>
<p id="index-39">The primary must evaluate to a callable object (user-defined functions, built-in
functions, methods of built-in objects, class objects, methods of class
instances, and certain class instances themselves are callable; extensions may
define additional callable object types).  All argument expressions are
evaluated before the call is attempted.  Please refer to section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>
for the syntax of formal <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameter</span></a> lists.</p>
<p>If keyword arguments are present, they are first converted to positional
arguments, as follows.  First, a list of unfilled slots is created for the
formal parameters.  If there are N positional arguments, they are placed in the
first N slots.  Next, for each keyword argument, the identifier is used to
determine the corresponding slot (if the identifier is the same as the first
formal parameter name, the first slot is used, and so on).  If the slot is
already filled, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised. Otherwise, the value of
the argument is placed in the slot, filling it (even if the expression is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, it fills the slot).  When all arguments have been processed, the slots
that are still unfilled are filled with the corresponding default value from the
function definition.  (Default values are calculated, once, when the function is
defined; thus, a mutable object such as a list or dictionary used as default
value will be shared by all calls that don’t specify an argument value for the
corresponding slot; this should usually be avoided.)  If there are any unfilled
slots for which no default value is specified, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is
raised.  Otherwise, the list of filled slots is used as the argument list for
the call.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> An implementation may provide built-in functions whose positional parameters
do not have names, even if they are ‘named’ for the purpose of documentation,
and which therefore cannot be supplied by keyword.  In CPython, this is the
case for functions implemented in C that use <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> to
parse their arguments.</p>
</div>
<p>If there are more positional arguments than there are formal parameter slots, a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised, unless a formal parameter using the syntax
<code class="docutils literal notranslate"><span class="pre">*identifier</span></code> is present; in this case, that formal parameter receives a tuple
containing the excess positional arguments (or an empty tuple if there were no
excess positional arguments).</p>
<p>If any keyword argument does not correspond to a formal parameter name, a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised, unless a formal parameter using the syntax
<code class="docutils literal notranslate"><span class="pre">**identifier</span></code> is present; in this case, that formal parameter receives a
dictionary containing the excess keyword arguments (using the keywords as keys
and the argument values as corresponding values), or a (new) empty dictionary if
there were no excess keyword arguments.</p>
<p id="index-40">If the syntax <code class="docutils literal notranslate"><span class="pre">*expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
evaluate to an iterable.  Elements from this iterable are treated as if they
were additional positional arguments; if there are positional arguments
<em>x1</em>, …, <em>xN</em>, and <code class="docutils literal notranslate"><span class="pre">expression</span></code> evaluates to a sequence <em>y1</em>, …, <em>yM</em>, this
is equivalent to a call with M+N positional arguments <em>x1</em>, …, <em>xN</em>, <em>y1</em>,
…, <em>yM</em>.</p>
<p>A consequence of this is that although the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax may appear
<em>after</em> some keyword arguments, it is processed <em>before</em> the keyword arguments
(and the <code class="docutils literal notranslate"><span class="pre">**expression</span></code> argument, if any – see below).  So:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">a</span><span class="p">,</span> <span class="n">b</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="go">2 1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="n">a</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">f() got multiple values for keyword argument &#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">2</span><span class="p">,))</span>
<span class="go">1 2</span>
</pre></div>
</div>
<p>It is unusual for both keyword arguments and the <code class="docutils literal notranslate"><span class="pre">*expression</span></code> syntax to be
used in the same call, so in practice this confusion does not arise.</p>
<p id="index-41">If the syntax <code class="docutils literal notranslate"><span class="pre">**expression</span></code> appears in the function call, <code class="docutils literal notranslate"><span class="pre">expression</span></code> must
evaluate to a mapping, the contents of which are treated as additional keyword
arguments.  In the case of a keyword appearing in both <code class="docutils literal notranslate"><span class="pre">expression</span></code> and as an
explicit keyword argument, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
<p>Formal parameters using the syntax <code class="docutils literal notranslate"><span class="pre">*identifier</span></code> or <code class="docutils literal notranslate"><span class="pre">**identifier</span></code> cannot be
used as positional argument slots or as keyword argument names.  Formal
parameters using the syntax <code class="docutils literal notranslate"><span class="pre">(sublist)</span></code> cannot be used as keyword argument
names; the outermost sublist corresponds to a single unnamed argument slot, and
the argument value is assigned to the sublist using the usual tuple assignment
rules after all other parameter processing is done.</p>
<p>A call always returns some value, possibly <code class="docutils literal notranslate"><span class="pre">None</span></code>, unless it raises an
exception.  How this value is computed depends on the type of the callable
object.</p>
<p>If it is—</p>
<dl class="docutils">
<dt>a user-defined function:</dt>
<dd><p class="first last" id="index-42">The code block for the function is executed, passing it the argument list.  The
first thing the code block will do is bind the formal parameters to the
arguments; this is described in section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>.  When the code block
executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, this specifies the return value of the
function call.</p>
</dd>
<dt>a built-in function or method:</dt>
<dd><p class="first last" id="index-43">The result is up to the interpreter; see <a class="reference internal" href="../library/functions.html#built-in-funcs"><span class="std std-ref">Built-in Functions</span></a> for the
descriptions of built-in functions and methods.</p>
</dd>
<dt>a class object:</dt>
<dd><p class="first last" id="index-44">A new instance of that class is returned.</p>
</dd>
<dt>a class instance method:</dt>
<dd><p class="first last" id="index-45">The corresponding user-defined function is called, with an argument list that is
one longer than the argument list of the call: the instance becomes the first
argument.</p>
</dd>
<dt>a class instance:</dt>
<dd><p class="first last" id="index-46">The class must define a <a class="reference internal" href="datamodel.html#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method; the effect is then the same as
if that method was called.</p>
</dd>
</dl>
</div>
</div>
<div class="section" id="the-power-operator">
<span id="power"></span><h2>5.4. The power operator<a class="headerlink" href="#the-power-operator" title="Permalink to this headline">¶</a></h2>
<p>The power operator binds more tightly than unary operators on its left; it binds
less tightly than unary operators on its right.  The syntax is:</p>
<pre>
<strong id="grammar-token-power">power</strong> ::=  <a class="reference internal" href="#grammar-token-primary"><code class="xref docutils literal notranslate"><span class="pre">primary</span></code></a> [&quot;**&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>]
</pre>
<p>Thus, in an unparenthesized sequence of power and unary operators, the operators
are evaluated from right to left (this does not constrain the evaluation order
for the operands): <code class="docutils literal notranslate"><span class="pre">-1**2</span></code> results in <code class="docutils literal notranslate"><span class="pre">-1</span></code>.</p>
<p>The power operator has the same semantics as the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function,
when called with two arguments: it yields its left argument raised to the power
of its right argument.  The numeric arguments are first converted to a common
type.  The result type is that of the arguments after coercion.</p>
<p>With mixed operand types, the coercion rules for binary arithmetic operators
apply. For int and long int operands, the result has the same type as the
operands (after coercion) unless the second argument is negative; in that case,
all arguments are converted to float and a float result is delivered. For
example, <code class="docutils literal notranslate"><span class="pre">10**2</span></code> returns <code class="docutils literal notranslate"><span class="pre">100</span></code>, but <code class="docutils literal notranslate"><span class="pre">10**-2</span></code> returns <code class="docutils literal notranslate"><span class="pre">0.01</span></code>. (This last
feature was added in Python 2.2. In Python 2.1 and before, if both arguments
were of integer types and the second argument was negative, an exception was
raised).</p>
<p>Raising <code class="docutils literal notranslate"><span class="pre">0.0</span></code> to a negative power results in a <a class="reference internal" href="../library/exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>.
Raising a negative number to a fractional power results in a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.</p>
</div>
<div class="section" id="unary-arithmetic-and-bitwise-operations">
<span id="unary"></span><h2>5.5. Unary arithmetic and bitwise operations<a class="headerlink" href="#unary-arithmetic-and-bitwise-operations" title="Permalink to this headline">¶</a></h2>
<p id="index-47">All unary arithmetic and bitwise operations have the same priority:</p>
<pre>
<strong id="grammar-token-u_expr">u_expr</strong> ::=  <a class="reference internal" href="#grammar-token-power"><code class="xref docutils literal notranslate"><span class="pre">power</span></code></a> | &quot;-&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | &quot;+&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | &quot;~&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
</pre>
<p id="index-48">The unary <code class="docutils literal notranslate"><span class="pre">-</span></code> (minus) operator yields the negation of its numeric argument.</p>
<p id="index-49">The unary <code class="docutils literal notranslate"><span class="pre">+</span></code> (plus) operator yields its numeric argument unchanged.</p>
<p id="index-50">The unary <code class="docutils literal notranslate"><span class="pre">~</span></code> (invert) operator yields the bitwise inversion of its plain or
long integer argument.  The bitwise inversion of <code class="docutils literal notranslate"><span class="pre">x</span></code> is defined as
<code class="docutils literal notranslate"><span class="pre">-(x+1)</span></code>.  It only applies to integral numbers.</p>
<p id="index-51">In all three cases, if the argument does not have the proper type, a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised.</p>
</div>
<div class="section" id="binary-arithmetic-operations">
<span id="binary"></span><h2>5.6. Binary arithmetic operations<a class="headerlink" href="#binary-arithmetic-operations" title="Permalink to this headline">¶</a></h2>
<p id="index-52">The binary arithmetic operations have the conventional priority levels.  Note
that some of these operations also apply to certain non-numeric types.  Apart
from the power operator, there are only two levels, one for multiplicative
operators and one for additive operators:</p>
<pre>
<strong id="grammar-token-m_expr">m_expr</strong> ::=  <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;*&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;//&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a> | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;/&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
            | <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> &quot;%&quot; <a class="reference internal" href="#grammar-token-u_expr"><code class="xref docutils literal notranslate"><span class="pre">u_expr</span></code></a>
<strong id="grammar-token-a_expr">a_expr</strong> ::=  <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> &quot;+&quot; <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a> | <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> &quot;-&quot; <a class="reference internal" href="#grammar-token-m_expr"><code class="xref docutils literal notranslate"><span class="pre">m_expr</span></code></a>
</pre>
<p id="index-53">The <code class="docutils literal notranslate"><span class="pre">*</span></code> (multiplication) operator yields the product of its arguments.  The
arguments must either both be numbers, or one argument must be an integer (plain
or long) and the other must be a sequence. In the former case, the numbers are
converted to a common type and then multiplied together.  In the latter case,
sequence repetition is performed; a negative repetition factor yields an empty
sequence.</p>
<p id="index-54">The <code class="docutils literal notranslate"><span class="pre">/</span></code> (division) and <code class="docutils literal notranslate"><span class="pre">//</span></code> (floor division) operators yield the quotient of
their arguments.  The numeric arguments are first converted to a common type.
Plain or long integer division yields an integer of the same type; the result is
that of mathematical division with the ‘floor’ function applied to the result.
Division by zero raises the <a class="reference internal" href="../library/exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a> exception.</p>
<p id="index-55">The <code class="docutils literal notranslate"><span class="pre">%</span></code> (modulo) operator yields the remainder from the division of the first
argument by the second.  The numeric arguments are first converted to a common
type.  A zero right argument raises the <a class="reference internal" href="../library/exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a> exception.  The
arguments may be floating point numbers, e.g., <code class="docutils literal notranslate"><span class="pre">3.14%0.7</span></code> equals <code class="docutils literal notranslate"><span class="pre">0.34</span></code>
(since <code class="docutils literal notranslate"><span class="pre">3.14</span></code> equals <code class="docutils literal notranslate"><span class="pre">4*0.7</span> <span class="pre">+</span> <span class="pre">0.34</span></code>.)  The modulo operator always yields a
result with the same sign as its second operand (or zero); the absolute value of
the result is strictly smaller than the absolute value of the second operand
<a class="footnote-reference" href="#id20" id="id10">[2]</a>.</p>
<p>The integer division and modulo operators are connected by the following
identity: <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">(x/y)*y</span> <span class="pre">+</span> <span class="pre">(x%y)</span></code>.  Integer division and modulo are also
connected with the built-in function <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>: <code class="docutils literal notranslate"><span class="pre">divmod(x,</span> <span class="pre">y)</span> <span class="pre">==</span> <span class="pre">(x/y,</span>
<span class="pre">x%y)</span></code>.  These identities don’t hold for floating point numbers; there similar
identities hold approximately where <code class="docutils literal notranslate"><span class="pre">x/y</span></code> is replaced by <code class="docutils literal notranslate"><span class="pre">floor(x/y)</span></code> or
<code class="docutils literal notranslate"><span class="pre">floor(x/y)</span> <span class="pre">-</span> <span class="pre">1</span></code> <a class="footnote-reference" href="#id21" id="id11">[3]</a>.</p>
<p>In addition to performing the modulo operation on numbers, the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is
also overloaded by string and unicode objects to perform string formatting (also
known as interpolation). The syntax for string formatting is described in the
Python Library Reference, section <a class="reference internal" href="../library/stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a>.</p>
<div class="deprecated">
<p><span class="versionmodified">Deprecated since version 2.3: </span>The floor division operator, the modulo operator, and the <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>
function are no longer defined for complex numbers.  Instead, convert to a
floating point number using the <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> function if appropriate.</p>
</div>
<p id="index-56">The <code class="docutils literal notranslate"><span class="pre">+</span></code> (addition) operator yields the sum of its arguments. The arguments
must either both be numbers or both sequences of the same type.  In the former
case, the numbers are converted to a common type and then added together.  In
the latter case, the sequences are concatenated.</p>
<p id="index-57">The <code class="docutils literal notranslate"><span class="pre">-</span></code> (subtraction) operator yields the difference of its arguments.  The
numeric arguments are first converted to a common type.</p>
</div>
<div class="section" id="shifting-operations">
<span id="shifting"></span><h2>5.7. Shifting operations<a class="headerlink" href="#shifting-operations" title="Permalink to this headline">¶</a></h2>
<p id="index-58">The shifting operations have lower priority than the arithmetic operations:</p>
<pre>
<strong id="grammar-token-shift_expr">shift_expr</strong> ::=  <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a> | <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> ( &quot;&lt;&lt;&quot; | &quot;&gt;&gt;&quot; ) <a class="reference internal" href="#grammar-token-a_expr"><code class="xref docutils literal notranslate"><span class="pre">a_expr</span></code></a>
</pre>
<p>These operators accept plain or long integers as arguments.  The arguments are
converted to a common type.  They shift the first argument to the left or right
by the number of bits given by the second argument.</p>
<p id="index-59">A right shift by <em>n</em> bits is defined as division by <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.  A left shift
by <em>n</em> bits is defined as multiplication with <code class="docutils literal notranslate"><span class="pre">pow(2,</span> <span class="pre">n)</span></code>.  Negative shift
counts raise a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In the current implementation, the right-hand operand is required
to be at most <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>.  If the right-hand operand is larger than
<a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-attr docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a> an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> exception is raised.</p>
</div>
</div>
<div class="section" id="binary-bitwise-operations">
<span id="bitwise"></span><h2>5.8. Binary bitwise operations<a class="headerlink" href="#binary-bitwise-operations" title="Permalink to this headline">¶</a></h2>
<p id="index-60">Each of the three bitwise operations has a different priority level:</p>
<pre>
<strong id="grammar-token-and_expr">and_expr</strong> ::=  <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a> | <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> &quot;&amp;&quot; <a class="reference internal" href="#grammar-token-shift_expr"><code class="xref docutils literal notranslate"><span class="pre">shift_expr</span></code></a>
<strong id="grammar-token-xor_expr">xor_expr</strong> ::=  <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a> | <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> &quot;^&quot; <a class="reference internal" href="#grammar-token-and_expr"><code class="xref docutils literal notranslate"><span class="pre">and_expr</span></code></a>
<strong id="grammar-token-or_expr">or_expr </strong> ::=  <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a> | <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> &quot;|&quot; <a class="reference internal" href="#grammar-token-xor_expr"><code class="xref docutils literal notranslate"><span class="pre">xor_expr</span></code></a>
</pre>
<p id="index-61">The <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> operator yields the bitwise AND of its arguments, which must be plain
or long integers.  The arguments are converted to a common type.</p>
<p id="index-62">The <code class="docutils literal notranslate"><span class="pre">^</span></code> operator yields the bitwise XOR (exclusive OR) of its arguments, which
must be plain or long integers.  The arguments are converted to a common type.</p>
<p id="index-63">The <code class="docutils literal notranslate"><span class="pre">|</span></code> operator yields the bitwise (inclusive) OR of its arguments, which
must be plain or long integers.  The arguments are converted to a common type.</p>
</div>
<div class="section" id="comparisons">
<span id="id12"></span><h2>5.9. Comparisons<a class="headerlink" href="#comparisons" title="Permalink to this headline">¶</a></h2>
<span class="target" id="index-64"></span><p id="index-65">Unlike C, all comparison operations in Python have the same priority, which is
lower than that of any arithmetic, shifting or bitwise operation.  Also unlike
C, expressions like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span> <span class="pre">&lt;</span> <span class="pre">c</span></code> have the interpretation that is conventional
in mathematics:</p>
<pre>
<strong id="grammar-token-comparison">comparison   </strong> ::=  <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> ( <a class="reference internal" href="#grammar-token-comp_operator"><code class="xref docutils literal notranslate"><span class="pre">comp_operator</span></code></a> <a class="reference internal" href="#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> )*
<strong id="grammar-token-comp_operator">comp_operator</strong> ::=  &quot;&lt;&quot; | &quot;&gt;&quot; | &quot;==&quot; | &quot;&gt;=&quot; | &quot;&lt;=&quot; | &quot;&lt;&gt;&quot; | &quot;!=&quot;
                   | &quot;is&quot; [&quot;not&quot;] | [&quot;not&quot;] &quot;in&quot;
</pre>
<p>Comparisons yield boolean values: <code class="docutils literal notranslate"><span class="pre">True</span></code> or <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p>
<p id="index-66">Comparisons can be chained arbitrarily, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code>, except that <code class="docutils literal notranslate"><span class="pre">y</span></code> is evaluated only once (but in both
cases <code class="docutils literal notranslate"><span class="pre">z</span></code> is not evaluated at all when <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> is found to be false).</p>
<p>Formally, if <em>a</em>, <em>b</em>, <em>c</em>, …, <em>y</em>, <em>z</em> are expressions and <em>op1</em>, <em>op2</em>, …,
<em>opN</em> are comparison operators, then <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code> is equivalent
to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">and</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span> <span class="pre">and</span> <span class="pre">...</span> <span class="pre">y</span> <span class="pre">opN</span> <span class="pre">z</span></code>, except that each expression is
evaluated at most once.</p>
<p>Note that <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">op1</span> <span class="pre">b</span> <span class="pre">op2</span> <span class="pre">c</span></code> doesn’t imply any kind of comparison between <em>a</em> and
<em>c</em>, so that, e.g., <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">z</span></code> is perfectly legal (though perhaps not
pretty).</p>
<p>The forms <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code> are equivalent; for consistency with C, <code class="docutils literal notranslate"><span class="pre">!=</span></code> is
preferred; where <code class="docutils literal notranslate"><span class="pre">!=</span></code> is mentioned below <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> is also accepted.  The <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code>
spelling is considered obsolescent.</p>
<div class="section" id="value-comparisons">
<h3>5.9.1. Value comparisons<a class="headerlink" href="#value-comparisons" title="Permalink to this headline">¶</a></h3>
<p>The operators <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code> compare the
values of two objects.  The objects do not need to have the same type.</p>
<p>Chapter <a class="reference internal" href="datamodel.html#objects"><span class="std std-ref">Objects, values and types</span></a> states that objects have a value (in addition to type
and identity).  The value of an object is a rather abstract notion in Python:
For example, there is no canonical access method for an object’s value.  Also,
there is no requirement that the value of an object should be constructed in a
particular way, e.g. comprised of all its data attributes. Comparison operators
implement a particular notion of what the value of an object is.  One can think
of them as defining the value of an object indirectly, by means of their
comparison implementation.</p>
<p>Types can customize their comparison behavior by implementing
a <a class="reference internal" href="datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method or
<em class="dfn">rich comparison methods</em> like <a class="reference internal" href="datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, described in
<a class="reference internal" href="datamodel.html#customization"><span class="std std-ref">Basic customization</span></a>.</p>
<p>The default behavior for equality comparison (<code class="docutils literal notranslate"><span class="pre">==</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code>) is based on
the identity of the objects.  Hence, equality comparison of instances with the
same identity results in equality, and equality comparison of instances with
different identities results in inequality.  A motivation for this default
behavior is the desire that all objects should be reflexive (i.e. <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code>
implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code>).</p>
<p>The default order comparison (<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>) gives a
consistent but arbitrary order.</p>
<p>(This unusual definition of comparison was used to simplify the definition of
operations like sorting and the <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> operators.
In the future, the comparison rules for objects of different types are likely to
change.)</p>
<p>The behavior of the default equality comparison, that instances with different
identities are always unequal, may be in contrast to what types will need that
have a sensible definition of object value and value-based equality.  Such
types will need to customize their comparison behavior, and in fact, a number
of built-in types have done that.</p>
<p>The following list describes the comparison behavior of the most important
built-in types.</p>
<ul>
<li><p class="first">Numbers of built-in numeric types (<a class="reference internal" href="../library/stdtypes.html#typesnumeric"><span class="std std-ref">Numeric Types — int, float, long, complex</span></a>) and of the standard
library types <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">fractions.Fraction</span></code></a> and <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">decimal.Decimal</span></code></a> can be
compared within and across their types, with the restriction that complex
numbers do not support order comparison.  Within the limits of the types
involved, they compare mathematically (algorithmically) correct without loss
of precision.</p>
</li>
<li><p class="first">Strings (instances of <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> or <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>)
compare lexicographically using the numeric equivalents (the
result of the built-in function <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a>) of their characters. <a class="footnote-reference" href="#id22" id="id13">[4]</a>
When comparing an 8-bit string and a Unicode string, the 8-bit string
is converted to Unicode.  If the conversion fails, the strings
are considered unequal.</p>
</li>
<li><p class="first">Instances of <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> or <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code> can be compared only
within each of their types.  Equality comparison across these types
results in unequality, and ordering comparison across these types
gives an arbitrary order.</p>
<p>These sequences compare lexicographically using comparison of corresponding
elements, whereby reflexivity of the elements is enforced.</p>
<p>In enforcing reflexivity of elements, the comparison of collections assumes
that for a collection element <code class="docutils literal notranslate"><span class="pre">x</span></code>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">x</span></code> is always true.  Based on
that assumption, element identity is compared first, and element comparison
is performed only for distinct elements.  This approach yields the same
result as a strict element comparison would, if the compared elements are
reflexive.  For non-reflexive elements, the result is different than for
strict element comparison.</p>
<p>Lexicographical comparison between built-in collections works as follows:</p>
<ul class="simple">
<li>For two collections to compare equal, they must be of the same type, have
the same length, and each pair of corresponding elements must compare
equal (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre">==</span> <span class="pre">(1,2)</span></code> is false because the type is not the
same).</li>
<li>Collections are ordered the same as their
first unequal elements (for example, <code class="docutils literal notranslate"><span class="pre">cmp([1,2,x],</span> <span class="pre">[1,2,y])</span></code> returns the
same as <code class="docutils literal notranslate"><span class="pre">cmp(x,y)</span></code>).  If a corresponding element does not exist, the
shorter collection is ordered first (for example, <code class="docutils literal notranslate"><span class="pre">[1,2]</span> <span class="pre">&lt;</span> <span class="pre">[1,2,3]</span></code> is
true).</li>
</ul>
</li>
<li><p class="first">Mappings (instances of <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>) compare equal if and only if they have
equal <cite>(key, value)</cite> pairs. Equality comparison of the keys and values
enforces reflexivity.</p>
<p>Outcomes other than equality are resolved
consistently, but are not otherwise defined. <a class="footnote-reference" href="#id23" id="id14">[5]</a></p>
</li>
<li><p class="first">Most other objects of built-in types compare unequal unless they are the same
object; the choice whether one object is considered smaller or larger than
another one is made arbitrarily but consistently within one execution of a
program.</p>
</li>
</ul>
<p>User-defined classes that customize their comparison behavior should follow
some consistency rules, if possible:</p>
<ul>
<li><p class="first">Equality comparison should be reflexive.
In other words, identical objects should compare equal:</p>
<blockquote>
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code></p>
</div></blockquote>
</li>
<li><p class="first">Comparison should be symmetric.
In other words, the following expressions should have the same result:</p>
<blockquote>
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">==</span> <span class="pre">x</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">!=</span> <span class="pre">x</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">x</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">y</span> <span class="pre">&gt;=</span> <span class="pre">x</span></code></p>
</div></blockquote>
</li>
<li><p class="first">Comparison should be transitive.
The following (non-exhaustive) examples illustrate that:</p>
<blockquote>
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&gt;</span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">z</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span> <span class="pre">and</span> <span class="pre">y</span> <span class="pre">&lt;=</span> <span class="pre">z</span></code> implies <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">z</span></code></p>
</div></blockquote>
</li>
<li><p class="first">Inverse comparison should result in the boolean negation.
In other words, the following expressions should have the same result:</p>
<blockquote>
<div><p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">!=</span> <span class="pre">y</span></code></p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&lt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">&gt;=</span> <span class="pre">y</span></code> (for total ordering)</p>
<p><code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">&gt;</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">x</span> <span class="pre">&lt;=</span> <span class="pre">y</span></code> (for total ordering)</p>
</div></blockquote>
<p>The last two expressions apply to totally ordered collections (e.g. to
sequences, but not to sets or mappings). See also the
<a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">total_ordering()</span></code></a> decorator.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> result should be consistent with equality.
Objects that are equal should either have the same hash value,
or be marked as unhashable.</p>
</li>
</ul>
<p>Python does not enforce these consistency rules.</p>
</div>
<div class="section" id="membership-test-operations">
<span id="membership-test-details"></span><span id="not-in"></span><span id="in"></span><h3>5.9.2. Membership test operations<a class="headerlink" href="#membership-test-operations" title="Permalink to this headline">¶</a></h3>
<p>The operators <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> test for membership.  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
<span class="pre">s</span></code> evaluates to <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>x</em> is a member of <em>s</em>, and <code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.
<code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">not</span> <span class="pre">in</span> <span class="pre">s</span></code> returns the negation of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">s</span></code>.  All built-in sequences and
set types support this as well as dictionary, for which <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> tests
whether the dictionary has a given key. For container types such as list, tuple,
set, frozenset, dict, or collections.deque, the expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is equivalent
to <code class="docutils literal notranslate"><span class="pre">any(x</span> <span class="pre">is</span> <span class="pre">e</span> <span class="pre">or</span> <span class="pre">x</span> <span class="pre">==</span> <span class="pre">e</span> <span class="pre">for</span> <span class="pre">e</span> <span class="pre">in</span> <span class="pre">y)</span></code>.</p>
<p>For the string and bytes types, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if <em>x</em> is a
substring of <em>y</em>.  An equivalent test is <code class="docutils literal notranslate"><span class="pre">y.find(x)</span> <span class="pre">!=</span> <span class="pre">-1</span></code>.  Empty strings are
always considered to be a substring of any other string, so <code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span> <span class="pre">in</span> <span class="pre">&quot;abc&quot;</span></code> will
return <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
<p>For user-defined classes which define the <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span>
<span class="pre">y</span></code> returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if <code class="docutils literal notranslate"><span class="pre">y.__contains__(x)</span></code> returns a true value, and
<code class="docutils literal notranslate"><span class="pre">False</span></code> otherwise.</p>
<p>For user-defined classes which do not define <a class="reference internal" href="datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> but do define
<a class="reference internal" href="datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if some value <code class="docutils literal notranslate"><span class="pre">z</span></code> with <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">z</span></code> is
produced while iterating over <code class="docutils literal notranslate"><span class="pre">y</span></code>.  If an exception is raised during the
iteration, it is as if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised that exception.</p>
<p>Lastly, the old-style iteration protocol is tried: if a class defines
<a class="reference internal" href="datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> is <code class="docutils literal notranslate"><span class="pre">True</span></code> if and only if there is a non-negative
integer index <em>i</em> such that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y[i]</span></code>, and all lower integer indices do not
raise <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> exception. (If any other exception is raised, it is as
if <a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> raised that exception).</p>
<p id="index-67">The operator <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a> is defined to have the inverse true value of
<a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>.</p>
</div>
<div class="section" id="is-not">
<span id="is"></span><span id="index-68"></span><span id="identity-comparisons"></span><h3>5.9.3. Identity comparisons<a class="headerlink" href="#is-not" title="Permalink to this headline">¶</a></h3>
<p>The operators <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> and <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a> test for object identity: <code class="docutils literal notranslate"><span class="pre">x</span>
<span class="pre">is</span> <span class="pre">y</span></code> is true if and only if <em>x</em> and <em>y</em> are the same object.  <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">y</span></code>
yields the inverse truth value. <a class="footnote-reference" href="#id24" id="id15">[6]</a></p>
</div>
</div>
<div class="section" id="boolean-operations">
<span id="not"></span><span id="or"></span><span id="and"></span><span id="booleans"></span><h2>5.10. Boolean operations<a class="headerlink" href="#boolean-operations" title="Permalink to this headline">¶</a></h2>
<pre id="index-69">
<strong id="grammar-token-or_test">or_test </strong> ::=  <a class="reference internal" href="#grammar-token-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> | <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> &quot;or&quot; <a class="reference internal" href="#grammar-token-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a>
<strong id="grammar-token-and_test">and_test</strong> ::=  <a class="reference internal" href="#grammar-token-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a> | <a class="reference internal" href="#grammar-token-and_test"><code class="xref docutils literal notranslate"><span class="pre">and_test</span></code></a> &quot;and&quot; <a class="reference internal" href="#grammar-token-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
<strong id="grammar-token-not_test">not_test</strong> ::=  <a class="reference internal" href="#grammar-token-comparison"><code class="xref docutils literal notranslate"><span class="pre">comparison</span></code></a> | &quot;not&quot; <a class="reference internal" href="#grammar-token-not_test"><code class="xref docutils literal notranslate"><span class="pre">not_test</span></code></a>
</pre>
<p>In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
<code class="docutils literal notranslate"><span class="pre">False</span></code>, <code class="docutils literal notranslate"><span class="pre">None</span></code>, numeric zero of all types, and empty strings and containers
(including strings, tuples, lists, dictionaries, sets and frozensets).  All
other values are interpreted as true.  (See the <a class="reference internal" href="datamodel.html#object.__nonzero__" title="object.__nonzero__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__nonzero__()</span></code></a>
special method for a way to change this.)</p>
<p id="index-70">The operator <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> yields <code class="docutils literal notranslate"><span class="pre">True</span></code> if its argument is false, <code class="docutils literal notranslate"><span class="pre">False</span></code>
otherwise.</p>
<p id="index-71">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">and</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is false, its value is
returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
<p id="index-72">The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">or</span> <span class="pre">y</span></code> first evaluates <em>x</em>; if <em>x</em> is true, its value is
returned; otherwise, <em>y</em> is evaluated and the resulting value is returned.</p>
<p>(Note that neither <a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a> nor <a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a> restrict the value and type
they return to <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code>, but rather return the last evaluated
argument. This is sometimes useful, e.g., if <code class="docutils literal notranslate"><span class="pre">s</span></code> is a string that should be
replaced by a default value if it is empty, the expression <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">or</span> <span class="pre">'foo'</span></code> yields
the desired value.  Because <a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> has to invent a value anyway, it does
not bother to return a value of the same type as its argument, so e.g., <code class="docutils literal notranslate"><span class="pre">not</span>
<span class="pre">'foo'</span></code> yields <code class="docutils literal notranslate"><span class="pre">False</span></code>, not <code class="docutils literal notranslate"><span class="pre">''</span></code>.)</p>
</div>
<div class="section" id="conditional-expressions">
<h2>5.11. Conditional Expressions<a class="headerlink" href="#conditional-expressions" title="Permalink to this headline">¶</a></h2>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.5.</span></p>
</div>
<pre id="index-73">
<strong id="grammar-token-conditional_expression">conditional_expression</strong> ::=  <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> [&quot;if&quot; <a class="reference internal" href="#grammar-token-or_test"><code class="xref docutils literal notranslate"><span class="pre">or_test</span></code></a> &quot;else&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
<strong id="grammar-token-expression">expression            </strong> ::=  <a class="reference internal" href="#grammar-token-conditional_expression"><code class="xref docutils literal notranslate"><span class="pre">conditional_expression</span></code></a> | <a class="reference internal" href="#grammar-token-lambda_expr"><code class="xref docutils literal notranslate"><span class="pre">lambda_expr</span></code></a>
</pre>
<p>Conditional expressions (sometimes called a “ternary operator”) have the lowest
priority of all Python operations.</p>
<p>The expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">if</span> <span class="pre">C</span> <span class="pre">else</span> <span class="pre">y</span></code> first evaluates the condition, <em>C</em> (<em>not</em> <em>x</em>);
if <em>C</em> is true, <em>x</em> is evaluated and its value is returned; otherwise, <em>y</em> is
evaluated and its value is returned.</p>
<p>See <span class="target" id="index-74"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> for more details about conditional expressions.</p>
</div>
<div class="section" id="lambda">
<span id="lambdas"></span><span id="id16"></span><h2>5.12. Lambdas<a class="headerlink" href="#lambda" title="Permalink to this headline">¶</a></h2>
<pre id="index-75">
<strong id="grammar-token-lambda_expr">lambda_expr    </strong> ::=  &quot;lambda&quot; [<a class="reference internal" href="compound_stmts.html#grammar-token-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>]: <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>
<strong id="grammar-token-old_lambda_expr">old_lambda_expr</strong> ::=  &quot;lambda&quot; [<a class="reference internal" href="compound_stmts.html#grammar-token-parameter_list"><code class="xref docutils literal notranslate"><span class="pre">parameter_list</span></code></a>]: <a class="reference internal" href="#grammar-token-old_expression"><code class="xref docutils literal notranslate"><span class="pre">old_expression</span></code></a>
</pre>
<p>Lambda expressions (sometimes called lambda forms) have the same syntactic position as
expressions.  They are a shorthand to create anonymous functions; the expression
<code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">parameters:</span> <span class="pre">expression</span></code> yields a function object.  The unnamed object
behaves like a function object defined with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>def &lt;lambda&gt;(parameters):
    return expression
</pre></div>
</div>
<p>See section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a> for the syntax of parameter lists.  Note that
functions created with lambda expressions cannot contain statements.</p>
</div>
<div class="section" id="expression-lists">
<span id="exprlists"></span><h2>5.13. Expression lists<a class="headerlink" href="#expression-lists" title="Permalink to this headline">¶</a></h2>
<pre id="index-76">
<strong id="grammar-token-expression_list">expression_list</strong> ::=  <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> ( &quot;,&quot; <a class="reference internal" href="#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> )* [&quot;,&quot;]
</pre>
<p id="index-77">An expression list containing at least one comma yields a tuple.  The length of
the tuple is the number of expressions in the list.  The expressions are
evaluated from left to right.</p>
<p id="index-78">The trailing comma is required only to create a single tuple (a.k.a. a
<em>singleton</em>); it is optional in all other cases.  A single expression without a
trailing comma doesn’t create a tuple, but rather yields the value of that
expression. (To create an empty tuple, use an empty pair of parentheses:
<code class="docutils literal notranslate"><span class="pre">()</span></code>.)</p>
</div>
<div class="section" id="evaluation-order">
<span id="evalorder"></span><h2>5.14. Evaluation order<a class="headerlink" href="#evaluation-order" title="Permalink to this headline">¶</a></h2>
<p id="index-79">Python evaluates expressions from left to right. Notice that while evaluating an
assignment, the right-hand side is evaluated before the left-hand side.</p>
<p>In the following lines, expressions will be evaluated in the arithmetic order of
their suffixes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span>
<span class="p">(</span><span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span><span class="p">)</span>
<span class="p">{</span><span class="n">expr1</span><span class="p">:</span> <span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">:</span> <span class="n">expr4</span><span class="p">}</span>
<span class="n">expr1</span> <span class="o">+</span> <span class="n">expr2</span> <span class="o">*</span> <span class="p">(</span><span class="n">expr3</span> <span class="o">-</span> <span class="n">expr4</span><span class="p">)</span>
<span class="n">expr1</span><span class="p">(</span><span class="n">expr2</span><span class="p">,</span> <span class="n">expr3</span><span class="p">,</span> <span class="o">*</span><span class="n">expr4</span><span class="p">,</span> <span class="o">**</span><span class="n">expr5</span><span class="p">)</span>
<span class="n">expr3</span><span class="p">,</span> <span class="n">expr4</span> <span class="o">=</span> <span class="n">expr1</span><span class="p">,</span> <span class="n">expr2</span>
</pre></div>
</div>
</div>
<div class="section" id="operator-precedence">
<span id="operator-summary"></span><h2>5.15. Operator precedence<a class="headerlink" href="#operator-precedence" title="Permalink to this headline">¶</a></h2>
<p id="index-80">The following table summarizes the operator precedences in Python, from lowest
precedence (least binding) to highest precedence (most binding). Operators in
the same box have the same precedence.  Unless the syntax is explicitly given,
operators are binary.  Operators in the same box group left to right (except for
comparisons, including tests, which all have the same precedence and chain from
left to right — see section <a class="reference internal" href="#comparisons"><span class="std std-ref">Comparisons</span></a> — and exponentiation, which
groups from right to left).</p>
<table border="1" class="docutils">
<colgroup>
<col width="56%" />
<col width="44%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operator</th>
<th class="head">Description</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><a class="reference internal" href="#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a></td>
<td>Lambda expression</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> – <a class="reference internal" href="compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a></td>
<td>Conditional expression</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#or"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">or</span></code></a></td>
<td>Boolean OR</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#and"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">and</span></code></a></td>
<td>Boolean AND</td>
</tr>
<tr class="row-even"><td><a class="reference internal" href="#not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span></code></a> <code class="docutils literal notranslate"><span class="pre">x</span></code></td>
<td>Boolean NOT</td>
</tr>
<tr class="row-odd"><td><a class="reference internal" href="#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>, <a class="reference internal" href="#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>,
<a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a>, <a class="reference internal" href="#is-not"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code></a>, <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">!=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code></td>
<td>Comparisons, including membership
tests and identity tests</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">|</span></code></td>
<td>Bitwise OR</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">^</span></code></td>
<td>Bitwise XOR</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&amp;</span></code></td>
<td>Bitwise AND</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code></td>
<td>Shifts</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code></td>
<td>Addition and subtraction</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">*</span></code>, <code class="docutils literal notranslate"><span class="pre">/</span></code>, <code class="docutils literal notranslate"><span class="pre">//</span></code>, <code class="docutils literal notranslate"><span class="pre">%</span></code></td>
<td>Multiplication, division, remainder
<a class="footnote-reference" href="#id25" id="id17">[7]</a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">+x</span></code>, <code class="docutils literal notranslate"><span class="pre">-x</span></code>, <code class="docutils literal notranslate"><span class="pre">~x</span></code></td>
<td>Positive, negative, bitwise NOT</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">**</span></code></td>
<td>Exponentiation <a class="footnote-reference" href="#id26" id="id18">[8]</a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">x[index]</span></code>, <code class="docutils literal notranslate"><span class="pre">x[index:index]</span></code>,
<code class="docutils literal notranslate"><span class="pre">x(arguments...)</span></code>, <code class="docutils literal notranslate"><span class="pre">x.attribute</span></code></td>
<td>Subscription, slicing,
call, attribute reference</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">(expressions...)</span></code>,
<code class="docutils literal notranslate"><span class="pre">[expressions...]</span></code>,
<code class="docutils literal notranslate"><span class="pre">{key:</span> <span class="pre">value...}</span></code>,
<code class="docutils literal notranslate"><span class="pre">`expressions...`</span></code></td>
<td>Binding or tuple display,
list display,
dictionary display,
string conversion</td>
</tr>
</tbody>
</table>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id19" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id3">[1]</a></td><td>In Python 2.3 and later releases, a list comprehension “leaks” the control
variables of each <code class="docutils literal notranslate"><span class="pre">for</span></code> it contains into the containing scope.  However, this
behavior is deprecated, and relying on it will not work in Python 3.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id20" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id10">[2]</a></td><td>While <code class="docutils literal notranslate"><span class="pre">abs(x%y)</span> <span class="pre">&lt;</span> <span class="pre">abs(y)</span></code> is true mathematically, for floats it may not be
true numerically due to roundoff.  For example, and assuming a platform on which
a Python float is an IEEE 754 double-precision number, in order that <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">%</span>
<span class="pre">1e100</span></code> have the same sign as <code class="docutils literal notranslate"><span class="pre">1e100</span></code>, the computed result is <code class="docutils literal notranslate"><span class="pre">-1e-100</span> <span class="pre">+</span>
<span class="pre">1e100</span></code>, which is numerically exactly equal to <code class="docutils literal notranslate"><span class="pre">1e100</span></code>.  The function
<a class="reference internal" href="../library/math.html#math.fmod" title="math.fmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fmod()</span></code></a> returns a result whose sign matches the sign of the
first argument instead, and so returns <code class="docutils literal notranslate"><span class="pre">-1e-100</span></code> in this case. Which approach
is more appropriate depends on the application.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id21" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id11">[3]</a></td><td>If x is very close to an exact integer multiple of y, it’s possible for
<code class="docutils literal notranslate"><span class="pre">floor(x/y)</span></code> to be one larger than <code class="docutils literal notranslate"><span class="pre">(x-x%y)/y</span></code> due to rounding.  In such
cases, Python returns the latter result, in order to preserve that
<code class="docutils literal notranslate"><span class="pre">divmod(x,y)[0]</span> <span class="pre">*</span> <span class="pre">y</span> <span class="pre">+</span> <span class="pre">x</span> <span class="pre">%</span> <span class="pre">y</span></code> be very close to <code class="docutils literal notranslate"><span class="pre">x</span></code>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id22" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id13">[4]</a></td><td><p class="first">The Unicode standard distinguishes between <em class="dfn">code points</em>
(e.g. U+0041) and <em class="dfn">abstract characters</em> (e.g. “LATIN CAPITAL LETTER A”).
While most abstract characters in Unicode are only represented using one
code point, there is a number of abstract characters that can in addition be
represented using a sequence of more than one code point.  For example, the
abstract character “LATIN CAPITAL LETTER C WITH CEDILLA” can be represented
as a single <em class="dfn">precomposed character</em> at code position U+00C7, or as a
sequence of a <em class="dfn">base character</em> at code position U+0043 (LATIN CAPITAL
LETTER C), followed by a <em class="dfn">combining character</em> at code position U+0327
(COMBINING CEDILLA).</p>
<p>The comparison operators on unicode strings compare at the level of Unicode code
points. This may be counter-intuitive to humans.  For example,
<code class="docutils literal notranslate"><span class="pre">u&quot;\u00C7&quot;</span> <span class="pre">==</span> <span class="pre">u&quot;\u0043\u0327&quot;</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code>, even though both strings
represent the same abstract character “LATIN CAPITAL LETTER C WITH CEDILLA”.</p>
<p class="last">To compare strings at the level of abstract characters (that is, in a way
intuitive to humans), use <a class="reference internal" href="../library/unicodedata.html#unicodedata.normalize" title="unicodedata.normalize"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicodedata.normalize()</span></code></a>.</p>
</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id23" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id14">[5]</a></td><td>Earlier versions of Python used lexicographic comparison of the sorted (key,
value) lists, but this was very expensive for the common case of comparing for
equality.  An even earlier version of Python compared dictionaries by identity
only, but this caused surprises because people expected to be able to test a
dictionary for emptiness by comparing it to <code class="docutils literal notranslate"><span class="pre">{}</span></code>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id24" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id15">[6]</a></td><td>Due to automatic garbage-collection, free lists, and the dynamic nature of
descriptors, you may notice seemingly unusual behaviour in certain uses of
the <a class="reference internal" href="#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator, like those involving comparisons between instance
methods, or constants.  Check their documentation for more info.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id25" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id17">[7]</a></td><td>The <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is also used for string formatting; the same
precedence applies.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id26" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id18">[8]</a></td><td>The power operator <code class="docutils literal notranslate"><span class="pre">**</span></code> binds less tightly than an arithmetic or
bitwise unary operator on its right, that is, <code class="docutils literal notranslate"><span class="pre">2**-1</span></code> is <code class="docutils literal notranslate"><span class="pre">0.5</span></code>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">5. Expressions</a><ul>
<li><a class="reference internal" href="#arithmetic-conversions">5.1. Arithmetic conversions</a></li>
<li><a class="reference internal" href="#atoms">5.2. Atoms</a><ul>
<li><a class="reference internal" href="#atom-identifiers">5.2.1. Identifiers (Names)</a></li>
<li><a class="reference internal" href="#literals">5.2.2. Literals</a></li>
<li><a class="reference internal" href="#parenthesized-forms">5.2.3. Parenthesized forms</a></li>
<li><a class="reference internal" href="#list-displays">5.2.4. List displays</a></li>
<li><a class="reference internal" href="#displays-for-sets-and-dictionaries">5.2.5. Displays for sets and dictionaries</a></li>
<li><a class="reference internal" href="#generator-expressions">5.2.6. Generator expressions</a></li>
<li><a class="reference internal" href="#dictionary-displays">5.2.7. Dictionary displays</a></li>
<li><a class="reference internal" href="#set-displays">5.2.8. Set displays</a></li>
<li><a class="reference internal" href="#string-conversions">5.2.9. String conversions</a></li>
<li><a class="reference internal" href="#yield-expressions">5.2.10. Yield expressions</a><ul>
<li><a class="reference internal" href="#generator-iterator-methods">5.2.10.1. Generator-iterator methods</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#primaries">5.3. Primaries</a><ul>
<li><a class="reference internal" href="#attribute-references">5.3.1. Attribute references</a></li>
<li><a class="reference internal" href="#subscriptions">5.3.2. Subscriptions</a></li>
<li><a class="reference internal" href="#slicings">5.3.3. Slicings</a></li>
<li><a class="reference internal" href="#calls">5.3.4. Calls</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-power-operator">5.4. The power operator</a></li>
<li><a class="reference internal" href="#unary-arithmetic-and-bitwise-operations">5.5. Unary arithmetic and bitwise operations</a></li>
<li><a class="reference internal" href="#binary-arithmetic-operations">5.6. Binary arithmetic operations</a></li>
<li><a class="reference internal" href="#shifting-operations">5.7. Shifting operations</a></li>
<li><a class="reference internal" href="#binary-bitwise-operations">5.8. Binary bitwise operations</a></li>
<li><a class="reference internal" href="#comparisons">5.9. Comparisons</a><ul>
<li><a class="reference internal" href="#value-comparisons">5.9.1. Value comparisons</a></li>
<li><a class="reference internal" href="#membership-test-operations">5.9.2. Membership test operations</a></li>
<li><a class="reference internal" href="#is-not">5.9.3. Identity comparisons</a></li>
</ul>
</li>
<li><a class="reference internal" href="#boolean-operations">5.10. Boolean operations</a></li>
<li><a class="reference internal" href="#conditional-expressions">5.11. Conditional Expressions</a></li>
<li><a class="reference internal" href="#lambda">5.12. Lambdas</a></li>
<li><a class="reference internal" href="#expression-lists">5.13. Expression lists</a></li>
<li><a class="reference internal" href="#evaluation-order">5.14. Evaluation order</a></li>
<li><a class="reference internal" href="#operator-precedence">5.15. Operator precedence</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="executionmodel.html"
                        title="previous chapter">4. Execution model</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="simple_stmts.html"
                        title="next chapter">6. Simple statements</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/expressions.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="simple_stmts.html" title="6. Simple statements"
             >next</a> |</li>
        <li class="right" >
          <a href="executionmodel.html" title="4. Execution model"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�6P.�.�html/reference/grammar.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9. Full Grammar specification &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="The Python Standard Library" href="../library/index.html" />
    <link rel="prev" title="8. Top-level components" href="toplevel_components.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/grammar.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../library/index.html" title="The Python Standard Library"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="8. Top-level components"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="full-grammar-specification">
<h1>9. Full Grammar specification<a class="headerlink" href="#full-grammar-specification" title="Permalink to this headline">¶</a></h1>
<p>This is the full Python grammar, as it is read by the parser generator and used
to parse Python source files:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Grammar for Python</span>

<span class="c1"># Note:  Changing the grammar specified in this file will most likely</span>
<span class="c1">#        require corresponding changes in the parser module</span>
<span class="c1">#        (../Modules/parsermodule.c).  If you can&#39;t make the changes to</span>
<span class="c1">#        that module yourself, please co-ordinate the required changes</span>
<span class="c1">#        with someone who can; ask around on python-dev for help.  Fred</span>
<span class="c1">#        Drake &lt;fdrake@acm.org&gt; will probably be listening there.</span>

<span class="c1"># NOTE WELL: You should also follow all the steps listed in PEP 306,</span>
<span class="c1"># &quot;How to Change Python&#39;s Grammar&quot;</span>

<span class="c1"># Start symbols for the grammar:</span>
<span class="c1">#       single_input is a single interactive statement;</span>
<span class="c1">#       file_input is a module or sequence of commands read from an input file;</span>
<span class="c1">#       eval_input is the input for the eval() and input() functions.</span>
<span class="c1"># NB: compound_stmt in single_input is followed by extra NEWLINE!</span>
<span class="n">single_input</span><span class="p">:</span> <span class="n">NEWLINE</span> <span class="o">|</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">compound_stmt</span> <span class="n">NEWLINE</span>
<span class="n">file_input</span><span class="p">:</span> <span class="p">(</span><span class="n">NEWLINE</span> <span class="o">|</span> <span class="n">stmt</span><span class="p">)</span><span class="o">*</span> <span class="n">ENDMARKER</span>
<span class="n">eval_input</span><span class="p">:</span> <span class="n">testlist</span> <span class="n">NEWLINE</span><span class="o">*</span> <span class="n">ENDMARKER</span>

<span class="n">decorator</span><span class="p">:</span> <span class="s1">&#39;@&#39;</span> <span class="n">dotted_name</span> <span class="p">[</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">arglist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="p">]</span> <span class="n">NEWLINE</span>
<span class="n">decorators</span><span class="p">:</span> <span class="n">decorator</span><span class="o">+</span>
<span class="n">decorated</span><span class="p">:</span> <span class="n">decorators</span> <span class="p">(</span><span class="n">classdef</span> <span class="o">|</span> <span class="n">funcdef</span><span class="p">)</span>
<span class="n">funcdef</span><span class="p">:</span> <span class="s1">&#39;def&#39;</span> <span class="n">NAME</span> <span class="n">parameters</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="n">parameters</span><span class="p">:</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">varargslist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span>
<span class="n">varargslist</span><span class="p">:</span> <span class="p">((</span><span class="n">fpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="s1">&#39;,&#39;</span><span class="p">)</span><span class="o">*</span>
              <span class="p">(</span><span class="s1">&#39;*&#39;</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="s1">&#39;**&#39;</span> <span class="n">NAME</span><span class="p">]</span> <span class="o">|</span> <span class="s1">&#39;**&#39;</span> <span class="n">NAME</span><span class="p">)</span> <span class="o">|</span>
              <span class="n">fpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">fpdef</span> <span class="p">[</span><span class="s1">&#39;=&#39;</span> <span class="n">test</span><span class="p">])</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">])</span>
<span class="n">fpdef</span><span class="p">:</span> <span class="n">NAME</span> <span class="o">|</span> <span class="s1">&#39;(&#39;</span> <span class="n">fplist</span> <span class="s1">&#39;)&#39;</span>
<span class="n">fplist</span><span class="p">:</span> <span class="n">fpdef</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">fpdef</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>

<span class="n">stmt</span><span class="p">:</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">compound_stmt</span>
<span class="n">simple_stmt</span><span class="p">:</span> <span class="n">small_stmt</span> <span class="p">(</span><span class="s1">&#39;;&#39;</span> <span class="n">small_stmt</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;;&#39;</span><span class="p">]</span> <span class="n">NEWLINE</span>
<span class="n">small_stmt</span><span class="p">:</span> <span class="p">(</span><span class="n">expr_stmt</span> <span class="o">|</span> <span class="n">print_stmt</span>  <span class="o">|</span> <span class="n">del_stmt</span> <span class="o">|</span> <span class="n">pass_stmt</span> <span class="o">|</span> <span class="n">flow_stmt</span> <span class="o">|</span>
             <span class="n">import_stmt</span> <span class="o">|</span> <span class="n">global_stmt</span> <span class="o">|</span> <span class="n">exec_stmt</span> <span class="o">|</span> <span class="n">assert_stmt</span><span class="p">)</span>
<span class="n">expr_stmt</span><span class="p">:</span> <span class="n">testlist</span> <span class="p">(</span><span class="n">augassign</span> <span class="p">(</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist</span><span class="p">)</span> <span class="o">|</span>
                     <span class="p">(</span><span class="s1">&#39;=&#39;</span> <span class="p">(</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist</span><span class="p">))</span><span class="o">*</span><span class="p">)</span>
<span class="n">augassign</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;+=&#39;</span> <span class="o">|</span> <span class="s1">&#39;-=&#39;</span> <span class="o">|</span> <span class="s1">&#39;*=&#39;</span> <span class="o">|</span> <span class="s1">&#39;/=&#39;</span> <span class="o">|</span> <span class="s1">&#39;%=&#39;</span> <span class="o">|</span> <span class="s1">&#39;&amp;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;|=&#39;</span> <span class="o">|</span> <span class="s1">&#39;^=&#39;</span> <span class="o">|</span>
            <span class="s1">&#39;&lt;&lt;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;&gt;&gt;=&#39;</span> <span class="o">|</span> <span class="s1">&#39;**=&#39;</span> <span class="o">|</span> <span class="s1">&#39;//=&#39;</span><span class="p">)</span>
<span class="c1"># For normal assignments, additional restrictions enforced by the interpreter</span>
<span class="n">print_stmt</span><span class="p">:</span> <span class="s1">&#39;print&#39;</span> <span class="p">(</span> <span class="p">[</span> <span class="n">test</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span> <span class="p">]</span> <span class="o">|</span>
                      <span class="s1">&#39;&gt;&gt;&#39;</span> <span class="n">test</span> <span class="p">[</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">+</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span> <span class="p">]</span> <span class="p">)</span>
<span class="n">del_stmt</span><span class="p">:</span> <span class="s1">&#39;del&#39;</span> <span class="n">exprlist</span>
<span class="n">pass_stmt</span><span class="p">:</span> <span class="s1">&#39;pass&#39;</span>
<span class="n">flow_stmt</span><span class="p">:</span> <span class="n">break_stmt</span> <span class="o">|</span> <span class="n">continue_stmt</span> <span class="o">|</span> <span class="n">return_stmt</span> <span class="o">|</span> <span class="n">raise_stmt</span> <span class="o">|</span> <span class="n">yield_stmt</span>
<span class="n">break_stmt</span><span class="p">:</span> <span class="s1">&#39;break&#39;</span>
<span class="n">continue_stmt</span><span class="p">:</span> <span class="s1">&#39;continue&#39;</span>
<span class="n">return_stmt</span><span class="p">:</span> <span class="s1">&#39;return&#39;</span> <span class="p">[</span><span class="n">testlist</span><span class="p">]</span>
<span class="n">yield_stmt</span><span class="p">:</span> <span class="n">yield_expr</span>
<span class="n">raise_stmt</span><span class="p">:</span> <span class="s1">&#39;raise&#39;</span> <span class="p">[</span><span class="n">test</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">]]]</span>
<span class="n">import_stmt</span><span class="p">:</span> <span class="n">import_name</span> <span class="o">|</span> <span class="n">import_from</span>
<span class="n">import_name</span><span class="p">:</span> <span class="s1">&#39;import&#39;</span> <span class="n">dotted_as_names</span>
<span class="n">import_from</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;from&#39;</span> <span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="o">*</span> <span class="n">dotted_name</span> <span class="o">|</span> <span class="s1">&#39;.&#39;</span><span class="o">+</span><span class="p">)</span>
              <span class="s1">&#39;import&#39;</span> <span class="p">(</span><span class="s1">&#39;*&#39;</span> <span class="o">|</span> <span class="s1">&#39;(&#39;</span> <span class="n">import_as_names</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span> <span class="n">import_as_names</span><span class="p">))</span>
<span class="n">import_as_name</span><span class="p">:</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">NAME</span><span class="p">]</span>
<span class="n">dotted_as_name</span><span class="p">:</span> <span class="n">dotted_name</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">NAME</span><span class="p">]</span>
<span class="n">import_as_names</span><span class="p">:</span> <span class="n">import_as_name</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">import_as_name</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">dotted_as_names</span><span class="p">:</span> <span class="n">dotted_as_name</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">dotted_as_name</span><span class="p">)</span><span class="o">*</span>
<span class="n">dotted_name</span><span class="p">:</span> <span class="n">NAME</span> <span class="p">(</span><span class="s1">&#39;.&#39;</span> <span class="n">NAME</span><span class="p">)</span><span class="o">*</span>
<span class="n">global_stmt</span><span class="p">:</span> <span class="s1">&#39;global&#39;</span> <span class="n">NAME</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">NAME</span><span class="p">)</span><span class="o">*</span>
<span class="n">exec_stmt</span><span class="p">:</span> <span class="s1">&#39;exec&#39;</span> <span class="n">expr</span> <span class="p">[</span><span class="s1">&#39;in&#39;</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">]]</span>
<span class="n">assert_stmt</span><span class="p">:</span> <span class="s1">&#39;assert&#39;</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">]</span>

<span class="n">compound_stmt</span><span class="p">:</span> <span class="n">if_stmt</span> <span class="o">|</span> <span class="n">while_stmt</span> <span class="o">|</span> <span class="n">for_stmt</span> <span class="o">|</span> <span class="n">try_stmt</span> <span class="o">|</span> <span class="n">with_stmt</span> <span class="o">|</span> <span class="n">funcdef</span> <span class="o">|</span> <span class="n">classdef</span> <span class="o">|</span> <span class="n">decorated</span>
<span class="n">if_stmt</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">(</span><span class="s1">&#39;elif&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">while_stmt</span><span class="p">:</span> <span class="s1">&#39;while&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">for_stmt</span><span class="p">:</span> <span class="s1">&#39;for&#39;</span> <span class="n">exprlist</span> <span class="s1">&#39;in&#39;</span> <span class="n">testlist</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span> <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
<span class="n">try_stmt</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;try&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
           <span class="p">((</span><span class="n">except_clause</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">)</span><span class="o">+</span>
            <span class="p">[</span><span class="s1">&#39;else&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span>
            <span class="p">[</span><span class="s1">&#39;finally&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">]</span> <span class="o">|</span>
           <span class="s1">&#39;finally&#39;</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span><span class="p">))</span>
<span class="n">with_stmt</span><span class="p">:</span> <span class="s1">&#39;with&#39;</span> <span class="n">with_item</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">with_item</span><span class="p">)</span><span class="o">*</span>  <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>
<span class="n">with_item</span><span class="p">:</span> <span class="n">test</span> <span class="p">[</span><span class="s1">&#39;as&#39;</span> <span class="n">expr</span><span class="p">]</span>
<span class="c1"># NB compile.c makes sure that the default except clause is last</span>
<span class="n">except_clause</span><span class="p">:</span> <span class="s1">&#39;except&#39;</span> <span class="p">[</span><span class="n">test</span> <span class="p">[(</span><span class="s1">&#39;as&#39;</span> <span class="o">|</span> <span class="s1">&#39;,&#39;</span><span class="p">)</span> <span class="n">test</span><span class="p">]]</span>
<span class="n">suite</span><span class="p">:</span> <span class="n">simple_stmt</span> <span class="o">|</span> <span class="n">NEWLINE</span> <span class="n">INDENT</span> <span class="n">stmt</span><span class="o">+</span> <span class="n">DEDENT</span>

<span class="c1"># Backward compatibility cruft to support:</span>
<span class="c1"># [ x for x in lambda: True, lambda: False if x() ]</span>
<span class="c1"># even while also allowing:</span>
<span class="c1"># lambda x: 5 if x else 2</span>
<span class="c1"># (But not a mix of the two)</span>
<span class="n">testlist_safe</span><span class="p">:</span> <span class="n">old_test</span> <span class="p">[(</span><span class="s1">&#39;,&#39;</span> <span class="n">old_test</span><span class="p">)</span><span class="o">+</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]]</span>
<span class="n">old_test</span><span class="p">:</span> <span class="n">or_test</span> <span class="o">|</span> <span class="n">old_lambdef</span>
<span class="n">old_lambdef</span><span class="p">:</span> <span class="s1">&#39;lambda&#39;</span> <span class="p">[</span><span class="n">varargslist</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">old_test</span>

<span class="n">test</span><span class="p">:</span> <span class="n">or_test</span> <span class="p">[</span><span class="s1">&#39;if&#39;</span> <span class="n">or_test</span> <span class="s1">&#39;else&#39;</span> <span class="n">test</span><span class="p">]</span> <span class="o">|</span> <span class="n">lambdef</span>
<span class="n">or_test</span><span class="p">:</span> <span class="n">and_test</span> <span class="p">(</span><span class="s1">&#39;or&#39;</span> <span class="n">and_test</span><span class="p">)</span><span class="o">*</span>
<span class="n">and_test</span><span class="p">:</span> <span class="n">not_test</span> <span class="p">(</span><span class="s1">&#39;and&#39;</span> <span class="n">not_test</span><span class="p">)</span><span class="o">*</span>
<span class="n">not_test</span><span class="p">:</span> <span class="s1">&#39;not&#39;</span> <span class="n">not_test</span> <span class="o">|</span> <span class="n">comparison</span>
<span class="n">comparison</span><span class="p">:</span> <span class="n">expr</span> <span class="p">(</span><span class="n">comp_op</span> <span class="n">expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">comp_op</span><span class="p">:</span> <span class="s1">&#39;&lt;&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;&#39;</span><span class="o">|</span><span class="s1">&#39;==&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;=&#39;</span><span class="o">|</span><span class="s1">&#39;&lt;=&#39;</span><span class="o">|</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="o">|</span><span class="s1">&#39;!=&#39;</span><span class="o">|</span><span class="s1">&#39;in&#39;</span><span class="o">|</span><span class="s1">&#39;not&#39;</span> <span class="s1">&#39;in&#39;</span><span class="o">|</span><span class="s1">&#39;is&#39;</span><span class="o">|</span><span class="s1">&#39;is&#39;</span> <span class="s1">&#39;not&#39;</span>
<span class="n">expr</span><span class="p">:</span> <span class="n">xor_expr</span> <span class="p">(</span><span class="s1">&#39;|&#39;</span> <span class="n">xor_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">xor_expr</span><span class="p">:</span> <span class="n">and_expr</span> <span class="p">(</span><span class="s1">&#39;^&#39;</span> <span class="n">and_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">and_expr</span><span class="p">:</span> <span class="n">shift_expr</span> <span class="p">(</span><span class="s1">&#39;&amp;&#39;</span> <span class="n">shift_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">shift_expr</span><span class="p">:</span> <span class="n">arith_expr</span> <span class="p">((</span><span class="s1">&#39;&lt;&lt;&#39;</span><span class="o">|</span><span class="s1">&#39;&gt;&gt;&#39;</span><span class="p">)</span> <span class="n">arith_expr</span><span class="p">)</span><span class="o">*</span>
<span class="n">arith_expr</span><span class="p">:</span> <span class="n">term</span> <span class="p">((</span><span class="s1">&#39;+&#39;</span><span class="o">|</span><span class="s1">&#39;-&#39;</span><span class="p">)</span> <span class="n">term</span><span class="p">)</span><span class="o">*</span>
<span class="n">term</span><span class="p">:</span> <span class="n">factor</span> <span class="p">((</span><span class="s1">&#39;*&#39;</span><span class="o">|</span><span class="s1">&#39;/&#39;</span><span class="o">|</span><span class="s1">&#39;%&#39;</span><span class="o">|</span><span class="s1">&#39;//&#39;</span><span class="p">)</span> <span class="n">factor</span><span class="p">)</span><span class="o">*</span>
<span class="n">factor</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;+&#39;</span><span class="o">|</span><span class="s1">&#39;-&#39;</span><span class="o">|</span><span class="s1">&#39;~&#39;</span><span class="p">)</span> <span class="n">factor</span> <span class="o">|</span> <span class="n">power</span>
<span class="n">power</span><span class="p">:</span> <span class="n">atom</span> <span class="n">trailer</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;**&#39;</span> <span class="n">factor</span><span class="p">]</span>
<span class="n">atom</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">yield_expr</span><span class="o">|</span><span class="n">testlist_comp</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span>
       <span class="s1">&#39;[&#39;</span> <span class="p">[</span><span class="n">listmaker</span><span class="p">]</span> <span class="s1">&#39;]&#39;</span> <span class="o">|</span>
       <span class="s1">&#39;{&#39;</span> <span class="p">[</span><span class="n">dictorsetmaker</span><span class="p">]</span> <span class="s1">&#39;}&#39;</span> <span class="o">|</span>
       <span class="s1">&#39;`&#39;</span> <span class="n">testlist1</span> <span class="s1">&#39;`&#39;</span> <span class="o">|</span>
       <span class="n">NAME</span> <span class="o">|</span> <span class="n">NUMBER</span> <span class="o">|</span> <span class="n">STRING</span><span class="o">+</span><span class="p">)</span>
<span class="n">listmaker</span><span class="p">:</span> <span class="n">test</span> <span class="p">(</span> <span class="n">list_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span> <span class="p">)</span>
<span class="n">testlist_comp</span><span class="p">:</span> <span class="n">test</span> <span class="p">(</span> <span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span> <span class="p">)</span>
<span class="n">lambdef</span><span class="p">:</span> <span class="s1">&#39;lambda&#39;</span> <span class="p">[</span><span class="n">varargslist</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span>
<span class="n">trailer</span><span class="p">:</span> <span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">arglist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span> <span class="o">|</span> <span class="s1">&#39;[&#39;</span> <span class="n">subscriptlist</span> <span class="s1">&#39;]&#39;</span> <span class="o">|</span> <span class="s1">&#39;.&#39;</span> <span class="n">NAME</span>
<span class="n">subscriptlist</span><span class="p">:</span> <span class="n">subscript</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">subscript</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">subscript</span><span class="p">:</span> <span class="s1">&#39;.&#39;</span> <span class="s1">&#39;.&#39;</span> <span class="s1">&#39;.&#39;</span> <span class="o">|</span> <span class="n">test</span> <span class="o">|</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span> <span class="p">[</span><span class="n">sliceop</span><span class="p">]</span>
<span class="n">sliceop</span><span class="p">:</span> <span class="s1">&#39;:&#39;</span> <span class="p">[</span><span class="n">test</span><span class="p">]</span>
<span class="n">exprlist</span><span class="p">:</span> <span class="n">expr</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">expr</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">testlist</span><span class="p">:</span> <span class="n">test</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
<span class="n">dictorsetmaker</span><span class="p">:</span> <span class="p">(</span> <span class="p">(</span><span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span> <span class="p">(</span><span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span> <span class="s1">&#39;:&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]))</span> <span class="o">|</span>
                  <span class="p">(</span><span class="n">test</span> <span class="p">(</span><span class="n">comp_for</span> <span class="o">|</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]))</span> <span class="p">)</span>

<span class="n">classdef</span><span class="p">:</span> <span class="s1">&#39;class&#39;</span> <span class="n">NAME</span> <span class="p">[</span><span class="s1">&#39;(&#39;</span> <span class="p">[</span><span class="n">testlist</span><span class="p">]</span> <span class="s1">&#39;)&#39;</span><span class="p">]</span> <span class="s1">&#39;:&#39;</span> <span class="n">suite</span>

<span class="n">arglist</span><span class="p">:</span> <span class="p">(</span><span class="n">argument</span> <span class="s1">&#39;,&#39;</span><span class="p">)</span><span class="o">*</span> <span class="p">(</span><span class="n">argument</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span><span class="p">]</span>
                         <span class="o">|</span><span class="s1">&#39;*&#39;</span> <span class="n">test</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">argument</span><span class="p">)</span><span class="o">*</span> <span class="p">[</span><span class="s1">&#39;,&#39;</span> <span class="s1">&#39;**&#39;</span> <span class="n">test</span><span class="p">]</span> 
                         <span class="o">|</span><span class="s1">&#39;**&#39;</span> <span class="n">test</span><span class="p">)</span>
<span class="c1"># The reason that keywords are test nodes instead of NAME is that using NAME</span>
<span class="c1"># results in an ambiguity. ast.c makes sure it&#39;s a NAME.</span>
<span class="n">argument</span><span class="p">:</span> <span class="n">test</span> <span class="p">[</span><span class="n">comp_for</span><span class="p">]</span> <span class="o">|</span> <span class="n">test</span> <span class="s1">&#39;=&#39;</span> <span class="n">test</span>

<span class="n">list_iter</span><span class="p">:</span> <span class="n">list_for</span> <span class="o">|</span> <span class="n">list_if</span>
<span class="n">list_for</span><span class="p">:</span> <span class="s1">&#39;for&#39;</span> <span class="n">exprlist</span> <span class="s1">&#39;in&#39;</span> <span class="n">testlist_safe</span> <span class="p">[</span><span class="n">list_iter</span><span class="p">]</span>
<span class="n">list_if</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">old_test</span> <span class="p">[</span><span class="n">list_iter</span><span class="p">]</span>

<span class="n">comp_iter</span><span class="p">:</span> <span class="n">comp_for</span> <span class="o">|</span> <span class="n">comp_if</span>
<span class="n">comp_for</span><span class="p">:</span> <span class="s1">&#39;for&#39;</span> <span class="n">exprlist</span> <span class="s1">&#39;in&#39;</span> <span class="n">or_test</span> <span class="p">[</span><span class="n">comp_iter</span><span class="p">]</span>
<span class="n">comp_if</span><span class="p">:</span> <span class="s1">&#39;if&#39;</span> <span class="n">old_test</span> <span class="p">[</span><span class="n">comp_iter</span><span class="p">]</span>

<span class="n">testlist1</span><span class="p">:</span> <span class="n">test</span> <span class="p">(</span><span class="s1">&#39;,&#39;</span> <span class="n">test</span><span class="p">)</span><span class="o">*</span>

<span class="c1"># not used in grammar, but may appear in &quot;node&quot; passed from Parser to Compiler</span>
<span class="n">encoding_decl</span><span class="p">:</span> <span class="n">NAME</span>

<span class="n">yield_expr</span><span class="p">:</span> <span class="s1">&#39;yield&#39;</span> <span class="p">[</span><span class="n">testlist</span><span class="p">]</span>
</pre></div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="toplevel_components.html"
                        title="previous chapter">8. Top-level components</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../library/index.html"
                        title="next chapter">The Python Standard Library</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/grammar.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../library/index.html" title="The Python Standard Library"
             >next</a> |</li>
        <li class="right" >
          <a href="toplevel_components.html" title="8. Top-level components"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\-*sN@N@html/reference/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>The Python Language Reference &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. Introduction" href="introduction.html" />
    <link rel="prev" title="4. Using Python on a Macintosh" href="../using/mac.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. Introduction"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../using/mac.html" title="4. Using Python on a Macintosh"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-python-language-reference">
<span id="reference-index"></span><h1>The Python Language Reference<a class="headerlink" href="#the-python-language-reference" title="Permalink to this headline">¶</a></h1>
<p>This reference manual describes the syntax and “core semantics” of the
language. It is terse, but attempts to be exact and complete. The semantics of
non-essential built-in object types and of the built-in functions and modules
are described in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>. For an informal introduction to the
language, see <a class="reference internal" href="../tutorial/index.html#tutorial-index"><span class="std std-ref">The Python Tutorial</span></a>. For C or C++ programmers, two additional
manuals exist: <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a> describes the high-level picture of how to
write a Python extension module, and the <a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a> describes the
interfaces available to C/C++ programmers in detail.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="introduction.html">1. Introduction</a><ul>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#alternate-implementations">1.1. Alternate Implementations</a></li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#notation">1.2. Notation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="lexical_analysis.html">2. Lexical analysis</a><ul>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#line-structure">2.1. Line structure</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#other-tokens">2.2. Other tokens</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#identifiers">2.3. Identifiers and keywords</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#literals">2.4. Literals</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#operators">2.5. Operators</a></li>
<li class="toctree-l2"><a class="reference internal" href="lexical_analysis.html#delimiters">2.6. Delimiters</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="datamodel.html">3. Data model</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#objects-values-and-types">3.1. Objects, values and types</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#new-style-and-classic-classes">3.3. New-style and classic classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="datamodel.html#special-method-names">3.4. Special method names</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="executionmodel.html">4. Execution model</a><ul>
<li class="toctree-l2"><a class="reference internal" href="executionmodel.html#naming-and-binding">4.1. Naming and binding</a></li>
<li class="toctree-l2"><a class="reference internal" href="executionmodel.html#exceptions">4.2. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="expressions.html">5. Expressions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#arithmetic-conversions">5.1. Arithmetic conversions</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#atoms">5.2. Atoms</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#primaries">5.3. Primaries</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#the-power-operator">5.4. The power operator</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#unary-arithmetic-and-bitwise-operations">5.5. Unary arithmetic and bitwise operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#binary-arithmetic-operations">5.6. Binary arithmetic operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#shifting-operations">5.7. Shifting operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#binary-bitwise-operations">5.8. Binary bitwise operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#comparisons">5.9. Comparisons</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#boolean-operations">5.10. Boolean operations</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#conditional-expressions">5.11. Conditional Expressions</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#lambda">5.12. Lambdas</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#expression-lists">5.13. Expression lists</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#evaluation-order">5.14. Evaluation order</a></li>
<li class="toctree-l2"><a class="reference internal" href="expressions.html#operator-precedence">5.15. Operator precedence</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="simple_stmts.html">6. Simple statements</a><ul>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#expression-statements">6.1. Expression statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#assignment-statements">6.2. Assignment statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-assert-statement">6.3. The <code class="docutils literal notranslate"><span class="pre">assert</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-pass-statement">6.4. The <code class="docutils literal notranslate"><span class="pre">pass</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-del-statement">6.5. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-print-statement">6.6. The <code class="docutils literal notranslate"><span class="pre">print</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-return-statement">6.7. The <code class="docutils literal notranslate"><span class="pre">return</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-yield-statement">6.8. The <code class="docutils literal notranslate"><span class="pre">yield</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-raise-statement">6.9. The <code class="docutils literal notranslate"><span class="pre">raise</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-break-statement">6.10. The <code class="docutils literal notranslate"><span class="pre">break</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-continue-statement">6.11. The <code class="docutils literal notranslate"><span class="pre">continue</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-import-statement">6.12. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-global-statement">6.13. The <code class="docutils literal notranslate"><span class="pre">global</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="simple_stmts.html#the-exec-statement">6.14. The <code class="docutils literal notranslate"><span class="pre">exec</span></code> statement</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="compound_stmts.html">7. Compound statements</a><ul>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-if-statement">7.1. The <code class="docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-while-statement">7.2. The <code class="docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-for-statement">7.3. The <code class="docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-try-statement">7.4. The <code class="docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#the-with-statement">7.5. The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#function-definitions">7.6. Function definitions</a></li>
<li class="toctree-l2"><a class="reference internal" href="compound_stmts.html#class-definitions">7.7. Class definitions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="toplevel_components.html">8. Top-level components</a><ul>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#complete-python-programs">8.1. Complete Python programs</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#file-input">8.2. File input</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#interactive-input">8.3. Interactive input</a></li>
<li class="toctree-l2"><a class="reference internal" href="toplevel_components.html#expression-input">8.4. Expression input</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="grammar.html">9. Full Grammar specification</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../using/mac.html"
                        title="previous chapter">4. Using Python on a Macintosh</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="next chapter">1. Introduction</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. Introduction"
             >next</a> |</li>
        <li class="right" >
          <a href="../using/mac.html" title="4. Using Python on a Macintosh"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\_ܶs?9?9 html/reference/introduction.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. Introduction &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Lexical analysis" href="lexical_analysis.html" />
    <link rel="prev" title="The Python Language Reference" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/introduction.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Language Reference"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="introduction">
<span id="id1"></span><h1>1. Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h1>
<p>This reference manual describes the Python programming language. It is not
intended as a tutorial.</p>
<p>While I am trying to be as precise as possible, I chose to use English rather
than formal specifications for everything except syntax and lexical analysis.
This should make the document more understandable to the average reader, but
will leave room for ambiguities. Consequently, if you were coming from Mars and
tried to re-implement Python from this document alone, you might have to guess
things and in fact you would probably end up implementing quite a different
language. On the other hand, if you are using Python and wonder what the precise
rules about a particular area of the language are, you should definitely be able
to find them here. If you would like to see a more formal definition of the
language, maybe you could volunteer your time — or invent a cloning machine
:-).</p>
<p>It is dangerous to add too many implementation details to a language reference
document — the implementation may change, and other implementations of the
same language may work differently.  On the other hand, there is currently only
one Python implementation in widespread use (although alternate implementations
exist), and its particular quirks are sometimes worth being mentioned,
especially where the implementation imposes additional limitations.  Therefore,
you’ll find short “implementation notes” sprinkled throughout the text.</p>
<p>Every Python implementation comes with a number of built-in and standard
modules.  These are documented in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.  A few built-in modules
are mentioned when they interact in a significant way with the language
definition.</p>
<div class="section" id="alternate-implementations">
<span id="implementations"></span><h2>1.1. Alternate Implementations<a class="headerlink" href="#alternate-implementations" title="Permalink to this headline">¶</a></h2>
<p>Though there is one Python implementation which is by far the most popular,
there are some alternate implementations which are of particular interest to
different audiences.</p>
<p>Known implementations include:</p>
<dl class="docutils">
<dt>CPython</dt>
<dd>This is the original and most-maintained implementation of Python, written in C.
New language features generally appear here first.</dd>
<dt>Jython</dt>
<dd>Python implemented in Java.  This implementation can be used as a scripting
language for Java applications, or can be used to create applications using the
Java class libraries.  It is also often used to create tests for Java libraries.
More information can be found at <a class="reference external" href="http://www.jython.org/">the Jython website</a>.</dd>
<dt>Python for .NET</dt>
<dd>This implementation actually uses the CPython implementation, but is a managed
.NET application and makes .NET libraries available.  It was created by Brian
Lloyd.  For more information, see the <a class="reference external" href="https://pythonnet.github.io/">Python for .NET home page</a>.</dd>
<dt>IronPython</dt>
<dd>An alternate Python for .NET.  Unlike Python.NET, this is a complete Python
implementation that generates IL, and compiles Python code directly to .NET
assemblies.  It was created by Jim Hugunin, the original creator of Jython.  For
more information, see <a class="reference external" href="http://ironpython.net/">the IronPython website</a>.</dd>
<dt>PyPy</dt>
<dd>An implementation of Python written completely in Python. It supports several
advanced features not found in other implementations like stackless support
and a Just in Time compiler. One of the goals of the project is to encourage
experimentation with the language itself by making it easier to modify the
interpreter (since it is written in Python).  Additional information is
available on <a class="reference external" href="http://pypy.org/">the PyPy project’s home page</a>.</dd>
</dl>
<p>Each of these implementations varies in some way from the language as documented
in this manual, or introduces specific information beyond what’s covered in the
standard Python documentation.  Please refer to the implementation-specific
documentation to determine what else you need to know about the specific
implementation you’re using.</p>
</div>
<div class="section" id="notation">
<span id="id2"></span><h2>1.2. Notation<a class="headerlink" href="#notation" title="Permalink to this headline">¶</a></h2>
<p id="index-0">The descriptions of lexical analysis and syntax use a modified BNF grammar
notation.  This uses the following style of definition:</p>
<pre>
<strong id="grammar-token-name">name     </strong> ::=  <a class="reference internal" href="#grammar-token-lc_letter"><code class="xref docutils literal notranslate"><span class="pre">lc_letter</span></code></a> (<a class="reference internal" href="#grammar-token-lc_letter"><code class="xref docutils literal notranslate"><span class="pre">lc_letter</span></code></a> | &quot;_&quot;)*
<strong id="grammar-token-lc_letter">lc_letter</strong> ::=  &quot;a&quot;...&quot;z&quot;
</pre>
<p>The first line says that a <code class="docutils literal notranslate"><span class="pre">name</span></code> is an <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code> followed by a sequence
of zero or more <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code>s and underscores.  An <code class="docutils literal notranslate"><span class="pre">lc_letter</span></code> in turn is
any of the single characters <code class="docutils literal notranslate"><span class="pre">'a'</span></code> through <code class="docutils literal notranslate"><span class="pre">'z'</span></code>.  (This rule is actually
adhered to for the names defined in lexical and grammar rules in this document.)</p>
<p>Each rule begins with a name (which is the name defined by the rule) and
<code class="docutils literal notranslate"><span class="pre">::=</span></code>.  A vertical bar (<code class="docutils literal notranslate"><span class="pre">|</span></code>) is used to separate alternatives; it is the
least binding operator in this notation.  A star (<code class="docutils literal notranslate"><span class="pre">*</span></code>) means zero or more
repetitions of the preceding item; likewise, a plus (<code class="docutils literal notranslate"><span class="pre">+</span></code>) means one or more
repetitions, and a phrase enclosed in square brackets (<code class="docutils literal notranslate"><span class="pre">[</span> <span class="pre">]</span></code>) means zero or
one occurrences (in other words, the enclosed phrase is optional).  The <code class="docutils literal notranslate"><span class="pre">*</span></code>
and <code class="docutils literal notranslate"><span class="pre">+</span></code> operators bind as tightly as possible; parentheses are used for
grouping.  Literal strings are enclosed in quotes.  White space is only
meaningful to separate tokens. Rules are normally contained on a single line;
rules with many alternatives may be formatted alternatively with each line after
the first beginning with a vertical bar.</p>
<p id="index-1">In lexical definitions (as the example above), two more conventions are used:
Two literal characters separated by three dots mean a choice of any single
character in the given (inclusive) range of ASCII characters.  A phrase between
angular brackets (<code class="docutils literal notranslate"><span class="pre">&lt;...&gt;</span></code>) gives an informal description of the symbol
defined; e.g., this could be used to describe the notion of ‘control character’
if needed.</p>
<p>Even though the notation used is almost the same, there is a big difference
between the meaning of lexical and syntactic definitions: a lexical definition
operates on the individual characters of the input source, while a syntax
definition operates on the stream of tokens generated by the lexical analysis.
All uses of BNF in the next chapter (“Lexical Analysis”) are lexical
definitions; uses in subsequent chapters are syntactic definitions.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">1. Introduction</a><ul>
<li><a class="reference internal" href="#alternate-implementations">1.1. Alternate Implementations</a></li>
<li><a class="reference internal" href="#notation">1.2. Notation</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">The Python Language Reference</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="lexical_analysis.html"
                        title="next chapter">2. Lexical analysis</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/introduction.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="lexical_analysis.html" title="2. Lexical analysis"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Language Reference"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��Y��$html/reference/lexical_analysis.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Lexical analysis &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="3. Data model" href="datamodel.html" />
    <link rel="prev" title="1. Introduction" href="introduction.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/lexical_analysis.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datamodel.html" title="3. Data model"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. Introduction"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="lexical-analysis">
<span id="lexical"></span><h1>2. Lexical analysis<a class="headerlink" href="#lexical-analysis" title="Permalink to this headline">¶</a></h1>
<p id="index-0">A Python program is read by a <em>parser</em>.  Input to the parser is a stream of
<em>tokens</em>, generated by the <em>lexical analyzer</em>.  This chapter describes how the
lexical analyzer breaks a file into tokens.</p>
<p>Python uses the 7-bit ASCII character set for program text.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.3: </span>An encoding declaration can be used to indicate that  string literals and
comments use an encoding different from ASCII.</p>
</div>
<p>For compatibility with older versions, Python only warns if it finds 8-bit
characters; those warnings should be corrected by either declaring an explicit
encoding, or using escape sequences if those bytes are binary data, instead of
characters.</p>
<p>The run-time character set depends on the I/O devices connected to the program
but is generally a superset of ASCII.</p>
<p><strong>Future compatibility note:</strong> It may be tempting to assume that the character
set for 8-bit characters is ISO Latin-1 (an ASCII superset that covers most
western languages that use the Latin alphabet), but it is possible that in the
future Unicode text editors will become common.  These generally use the UTF-8
encoding, which is also an ASCII superset, but with very different use for the
characters with ordinals 128-255.  While there is no consensus on this subject
yet, it is unwise to assume either Latin-1 or UTF-8, even though the current
implementation appears to favor Latin-1.  This applies both to the source
character set and the run-time character set.</p>
<div class="section" id="line-structure">
<span id="id1"></span><h2>2.1. Line structure<a class="headerlink" href="#line-structure" title="Permalink to this headline">¶</a></h2>
<p id="index-1">A Python program is divided into a number of <em>logical lines</em>.</p>
<div class="section" id="logical-lines">
<span id="logical"></span><h3>2.1.1. Logical lines<a class="headerlink" href="#logical-lines" title="Permalink to this headline">¶</a></h3>
<p id="index-2">The end of a logical line is represented by the token NEWLINE.  Statements
cannot cross logical line boundaries except where NEWLINE is allowed by the
syntax (e.g., between statements in compound statements). A logical line is
constructed from one or more <em>physical lines</em> by following the explicit or
implicit <em>line joining</em> rules.</p>
</div>
<div class="section" id="physical-lines">
<span id="physical"></span><h3>2.1.2. Physical lines<a class="headerlink" href="#physical-lines" title="Permalink to this headline">¶</a></h3>
<p>A physical line is a sequence of characters terminated by an end-of-line
sequence.  In source files and strings, any of the standard platform line
termination sequences can be used - the Unix form using ASCII LF (linefeed),
the Windows form using the ASCII sequence CR LF (return followed by linefeed),
or the old Macintosh form using the ASCII CR (return) character.  All of these
forms can be used equally, regardless of platform. The end of input also serves
as an implicit terminator for the final physical line.</p>
<p>When embedding Python, source code strings should be passed to Python APIs using
the standard C conventions for newline characters (the <code class="docutils literal notranslate"><span class="pre">\n</span></code> character,
representing ASCII LF, is the line terminator).</p>
</div>
<div class="section" id="comments">
<span id="id2"></span><h3>2.1.3. Comments<a class="headerlink" href="#comments" title="Permalink to this headline">¶</a></h3>
<p id="index-3">A comment starts with a hash character (<code class="docutils literal notranslate"><span class="pre">#</span></code>) that is not part of a string
literal, and ends at the end of the physical line.  A comment signifies the end
of the logical line unless the implicit line joining rules are invoked. Comments
are ignored by the syntax; they are not tokens.</p>
</div>
<div class="section" id="encoding-declarations">
<span id="encodings"></span><h3>2.1.4. Encoding declarations<a class="headerlink" href="#encoding-declarations" title="Permalink to this headline">¶</a></h3>
<p id="index-4">If a comment in the first or second line of the Python script matches the
regular expression <code class="docutils literal notranslate"><span class="pre">coding[=:]\s*([-\w.]+)</span></code>, this comment is processed as an
encoding declaration; the first group of this expression names the encoding of
the source code file. The encoding declaration must appear on a line of its
own. If it is the second line, the first line must also be a comment-only line.
The recommended forms of an encoding expression are</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: &lt;encoding-name&gt; -*-</span>
</pre></div>
</div>
<p>which is recognized also by GNU Emacs, and</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># vim:fileencoding=&lt;encoding-name&gt;</span>
</pre></div>
</div>
<p>which is recognized by Bram Moolenaar’s VIM. In addition, if the first bytes of
the file are the UTF-8 byte-order mark (<code class="docutils literal notranslate"><span class="pre">'\xef\xbb\xbf'</span></code>), the declared file
encoding is UTF-8 (this is supported, among others, by Microsoft’s
<strong class="program">notepad</strong>).</p>
<p>If an encoding is declared, the encoding name must be recognized by Python. The
encoding is used for all lexical analysis, in particular to find the end of a
string, and to interpret the contents of Unicode literals. String literals are
converted to Unicode for syntactical analysis, then converted back to their
original encoding before interpretation starts.</p>
</div>
<div class="section" id="explicit-line-joining">
<span id="explicit-joining"></span><h3>2.1.5. Explicit line joining<a class="headerlink" href="#explicit-line-joining" title="Permalink to this headline">¶</a></h3>
<p id="index-5">Two or more physical lines may be joined into logical lines using backslash
characters (<code class="docutils literal notranslate"><span class="pre">\</span></code>), as follows: when a physical line ends in a backslash that is
not part of a string literal or comment, it is joined with the following forming
a single logical line, deleting the backslash and the following end-of-line
character.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="mi">1900</span> <span class="o">&lt;</span> <span class="n">year</span> <span class="o">&lt;</span> <span class="mi">2100</span> <span class="ow">and</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">month</span> <span class="o">&lt;=</span> <span class="mi">12</span> \
   <span class="ow">and</span> <span class="mi">1</span> <span class="o">&lt;=</span> <span class="n">day</span> <span class="o">&lt;=</span> <span class="mi">31</span> <span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">hour</span> <span class="o">&lt;</span> <span class="mi">24</span> \
   <span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">minute</span> <span class="o">&lt;</span> <span class="mi">60</span> <span class="ow">and</span> <span class="mi">0</span> <span class="o">&lt;=</span> <span class="n">second</span> <span class="o">&lt;</span> <span class="mi">60</span><span class="p">:</span>   <span class="c1"># Looks like a valid date</span>
        <span class="k">return</span> <span class="mi">1</span>
</pre></div>
</div>
<p>A line ending in a backslash cannot carry a comment.  A backslash does not
continue a comment.  A backslash does not continue a token except for string
literals (i.e., tokens other than string literals cannot be split across
physical lines using a backslash).  A backslash is illegal elsewhere on a line
outside a string literal.</p>
</div>
<div class="section" id="implicit-line-joining">
<span id="implicit-joining"></span><h3>2.1.6. Implicit line joining<a class="headerlink" href="#implicit-line-joining" title="Permalink to this headline">¶</a></h3>
<p>Expressions in parentheses, square brackets or curly braces can be split over
more than one physical line without using backslashes. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">month_names</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Januari&#39;</span><span class="p">,</span> <span class="s1">&#39;Februari&#39;</span><span class="p">,</span> <span class="s1">&#39;Maart&#39;</span><span class="p">,</span>      <span class="c1"># These are the</span>
               <span class="s1">&#39;April&#39;</span><span class="p">,</span>   <span class="s1">&#39;Mei&#39;</span><span class="p">,</span>      <span class="s1">&#39;Juni&#39;</span><span class="p">,</span>       <span class="c1"># Dutch names</span>
               <span class="s1">&#39;Juli&#39;</span><span class="p">,</span>    <span class="s1">&#39;Augustus&#39;</span><span class="p">,</span> <span class="s1">&#39;September&#39;</span><span class="p">,</span>  <span class="c1"># for the months</span>
               <span class="s1">&#39;Oktober&#39;</span><span class="p">,</span> <span class="s1">&#39;November&#39;</span><span class="p">,</span> <span class="s1">&#39;December&#39;</span><span class="p">]</span>   <span class="c1"># of the year</span>
</pre></div>
</div>
<p>Implicitly continued lines can carry comments.  The indentation of the
continuation lines is not important.  Blank continuation lines are allowed.
There is no NEWLINE token between implicit continuation lines.  Implicitly
continued lines can also occur within triple-quoted strings (see below); in that
case they cannot carry comments.</p>
</div>
<div class="section" id="blank-lines">
<span id="id3"></span><h3>2.1.7. Blank lines<a class="headerlink" href="#blank-lines" title="Permalink to this headline">¶</a></h3>
<p id="index-6">A logical line that contains only spaces, tabs, formfeeds and possibly a
comment, is ignored (i.e., no NEWLINE token is generated).  During interactive
input of statements, handling of a blank line may differ depending on the
implementation of the read-eval-print loop.  In the standard implementation, an
entirely blank logical line (i.e. one containing not even whitespace or a
comment) terminates a multi-line statement.</p>
</div>
<div class="section" id="indentation">
<span id="id4"></span><h3>2.1.8. Indentation<a class="headerlink" href="#indentation" title="Permalink to this headline">¶</a></h3>
<p id="index-7">Leading whitespace (spaces and tabs) at the beginning of a logical line is used
to compute the indentation level of the line, which in turn is used to determine
the grouping of statements.</p>
<p>First, tabs are replaced (from left to right) by one to eight spaces such that
the total number of characters up to and including the replacement is a multiple
of eight (this is intended to be the same rule as used by Unix).  The total
number of spaces preceding the first non-blank character then determines the
line’s indentation.  Indentation cannot be split over multiple physical lines
using backslashes; the whitespace up to the first backslash determines the
indentation.</p>
<p><strong>Cross-platform compatibility note:</strong> because of the nature of text editors on
non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
indentation in a single source file.  It should also be noted that different
platforms may explicitly limit the maximum indentation level.</p>
<p>A formfeed character may be present at the start of the line; it will be ignored
for the indentation calculations above.  Formfeed characters occurring elsewhere
in the leading whitespace have an undefined effect (for instance, they may reset
the space count to zero).</p>
<p id="index-8">The indentation levels of consecutive lines are used to generate INDENT and
DEDENT tokens, using a stack, as follows.</p>
<p>Before the first line of the file is read, a single zero is pushed on the stack;
this will never be popped off again.  The numbers pushed on the stack will
always be strictly increasing from bottom to top.  At the beginning of each
logical line, the line’s indentation level is compared to the top of the stack.
If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
one INDENT token is generated.  If it is smaller, it <em>must</em> be one of the
numbers occurring on the stack; all numbers on the stack that are larger are
popped off, and for each number popped off a DEDENT token is generated.  At the
end of the file, a DEDENT token is generated for each number remaining on the
stack that is larger than zero.</p>
<p>Here is an example of a correctly (though confusingly) indented piece of Python
code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">perm</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>
        <span class="c1"># Compute the list of all permutations of l</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)</span> <span class="o">&lt;=</span> <span class="mi">1</span><span class="p">:</span>
                  <span class="k">return</span> <span class="p">[</span><span class="n">l</span><span class="p">]</span>
    <span class="n">r</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)):</span>
             <span class="n">s</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
             <span class="n">p</span> <span class="o">=</span> <span class="n">perm</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
             <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p</span><span class="p">:</span>
              <span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">x</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">r</span>
</pre></div>
</div>
<p>The following example shows various indentation errors:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span> <span class="k">def</span> <span class="nf">perm</span><span class="p">(</span><span class="n">l</span><span class="p">):</span>                       <span class="c1"># error: first line indented</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">l</span><span class="p">)):</span>             <span class="c1"># error: not indented</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:]</span>
        <span class="n">p</span> <span class="o">=</span> <span class="n">perm</span><span class="p">(</span><span class="n">l</span><span class="p">[:</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">:])</span>   <span class="c1"># error: unexpected indent</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">p</span><span class="p">:</span>
                <span class="n">r</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">l</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">+</span> <span class="n">x</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">r</span>                <span class="c1"># error: inconsistent dedent</span>
</pre></div>
</div>
<p>(Actually, the first three errors are detected by the parser; only the last
error is found by the lexical analyzer — the indentation of <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">r</span></code> does
not match a level popped off the stack.)</p>
</div>
<div class="section" id="whitespace-between-tokens">
<span id="whitespace"></span><h3>2.1.9. Whitespace between tokens<a class="headerlink" href="#whitespace-between-tokens" title="Permalink to this headline">¶</a></h3>
<p>Except at the beginning of a logical line or in string literals, the whitespace
characters space, tab and formfeed can be used interchangeably to separate
tokens.  Whitespace is needed between two tokens only if their concatenation
could otherwise be interpreted as a different token (e.g., ab is one token, but
a b is two tokens).</p>
</div>
</div>
<div class="section" id="other-tokens">
<span id="id5"></span><h2>2.2. Other tokens<a class="headerlink" href="#other-tokens" title="Permalink to this headline">¶</a></h2>
<p>Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
<em>identifiers</em>, <em>keywords</em>, <em>literals</em>, <em>operators</em>, and <em>delimiters</em>. Whitespace
characters (other than line terminators, discussed earlier) are not tokens, but
serve to delimit tokens. Where ambiguity exists, a token comprises the longest
possible string that forms a legal token, when read from left to right.</p>
</div>
<div class="section" id="identifiers">
<span id="identifiers-and-keywords"></span><h2>2.3. Identifiers and keywords<a class="headerlink" href="#identifiers" title="Permalink to this headline">¶</a></h2>
<p id="index-9">Identifiers (also referred to as <em>names</em>) are described by the following lexical
definitions:</p>
<pre>
<strong id="grammar-token-identifier">identifier</strong> ::=  (<a class="reference internal" href="#grammar-token-letter"><code class="xref docutils literal notranslate"><span class="pre">letter</span></code></a>|&quot;_&quot;) (<a class="reference internal" href="#grammar-token-letter"><code class="xref docutils literal notranslate"><span class="pre">letter</span></code></a> | <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a> | &quot;_&quot;)*
<strong id="grammar-token-letter">letter    </strong> ::=  <a class="reference internal" href="#grammar-token-lowercase"><code class="xref docutils literal notranslate"><span class="pre">lowercase</span></code></a> | <a class="reference internal" href="#grammar-token-uppercase"><code class="xref docutils literal notranslate"><span class="pre">uppercase</span></code></a>
<strong id="grammar-token-lowercase">lowercase </strong> ::=  &quot;a&quot;...&quot;z&quot;
<strong id="grammar-token-uppercase">uppercase </strong> ::=  &quot;A&quot;...&quot;Z&quot;
<strong id="grammar-token-digit">digit     </strong> ::=  &quot;0&quot;...&quot;9&quot;
</pre>
<p>Identifiers are unlimited in length.  Case is significant.</p>
<div class="section" id="keywords">
<span id="id6"></span><h3>2.3.1. Keywords<a class="headerlink" href="#keywords" title="Permalink to this headline">¶</a></h3>
<p id="index-10">The following identifiers are used as reserved words, or <em>keywords</em> of the
language, and cannot be used as ordinary identifiers.  They must be spelled
exactly as written here:</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue  finally   is        return
def       for       lambda    try
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span><a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> became a constant and is now recognized by the compiler as a name
for the built-in object <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.  Although it is not a keyword, you cannot
assign a different object to it.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Using <a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> and <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> as identifiers triggers a warning.  To
use them as keywords, enable the <code class="docutils literal notranslate"><span class="pre">with_statement</span></code> future feature .</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span><a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> and <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> are full keywords.</p>
</div>
</div>
<div class="section" id="reserved-classes-of-identifiers">
<span id="id-classes"></span><h3>2.3.2. Reserved classes of identifiers<a class="headerlink" href="#reserved-classes-of-identifiers" title="Permalink to this headline">¶</a></h3>
<p>Certain classes of identifiers (besides keywords) have special meanings.  These
classes are identified by the patterns of leading and trailing underscore
characters:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">_*</span></code></dt>
<dd><p class="first">Not imported by <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code>.  The special identifier <code class="docutils literal notranslate"><span class="pre">_</span></code> is used
in the interactive interpreter to store the result of the last evaluation; it is
stored in the <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module.  When not in interactive mode, <code class="docutils literal notranslate"><span class="pre">_</span></code>
has no special meaning and is not defined. See section <a class="reference internal" href="simple_stmts.html#import"><span class="std std-ref">The import statement</span></a>.</p>
<div class="last admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The name <code class="docutils literal notranslate"><span class="pre">_</span></code> is often used in conjunction with internationalization;
refer to the documentation for the <a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a> module for more
information on this convention.</p>
</div>
</dd>
<dt><code class="docutils literal notranslate"><span class="pre">__*__</span></code></dt>
<dd>System-defined names. These names are defined by the interpreter and its
implementation (including the standard library).  Current system names are
discussed in the <a class="reference internal" href="datamodel.html#specialnames"><span class="std std-ref">Special method names</span></a> section and elsewhere.  More will likely
be defined in future versions of Python.  <em>Any</em> use of <code class="docutils literal notranslate"><span class="pre">__*__</span></code> names, in
any context, that does not follow explicitly documented use, is subject to
breakage without warning.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">__*</span></code></dt>
<dd>Class-private names.  Names in this category, when used within the context of a
class definition, are re-written to use a mangled form to help avoid name
clashes between “private” attributes of base and derived classes. See section
<a class="reference internal" href="expressions.html#atom-identifiers"><span class="std std-ref">Identifiers (Names)</span></a>.</dd>
</dl>
</div>
</div>
<div class="section" id="literals">
<span id="id7"></span><h2>2.4. Literals<a class="headerlink" href="#literals" title="Permalink to this headline">¶</a></h2>
<p id="index-11">Literals are notations for constant values of some built-in types.</p>
<div class="section" id="string-literals">
<span id="strings"></span><h3>2.4.1. String literals<a class="headerlink" href="#string-literals" title="Permalink to this headline">¶</a></h3>
<p id="index-12">String literals are described by the following lexical definitions:</p>
<pre id="index-13">
<strong id="grammar-token-stringliteral">stringliteral  </strong> ::=  [<a class="reference internal" href="#grammar-token-stringprefix"><code class="xref docutils literal notranslate"><span class="pre">stringprefix</span></code></a>](<a class="reference internal" href="#grammar-token-shortstring"><code class="xref docutils literal notranslate"><span class="pre">shortstring</span></code></a> | <a class="reference internal" href="#grammar-token-longstring"><code class="xref docutils literal notranslate"><span class="pre">longstring</span></code></a>)
<strong id="grammar-token-stringprefix">stringprefix   </strong> ::=  &quot;r&quot; | &quot;u&quot; | &quot;ur&quot; | &quot;R&quot; | &quot;U&quot; | &quot;UR&quot; | &quot;Ur&quot; | &quot;uR&quot;
                     | &quot;b&quot; | &quot;B&quot; | &quot;br&quot; | &quot;Br&quot; | &quot;bR&quot; | &quot;BR&quot;
<strong id="grammar-token-shortstring">shortstring    </strong> ::=  &quot;'&quot; <a class="reference internal" href="#grammar-token-shortstringitem"><code class="xref docutils literal notranslate"><span class="pre">shortstringitem</span></code></a>* &quot;'&quot; | '&quot;' <a class="reference internal" href="#grammar-token-shortstringitem"><code class="xref docutils literal notranslate"><span class="pre">shortstringitem</span></code></a>* '&quot;'
<strong id="grammar-token-longstring">longstring     </strong> ::=  &quot;'''&quot; <a class="reference internal" href="#grammar-token-longstringitem"><code class="xref docutils literal notranslate"><span class="pre">longstringitem</span></code></a>* &quot;'''&quot;
                     | '&quot;&quot;&quot;' <a class="reference internal" href="#grammar-token-longstringitem"><code class="xref docutils literal notranslate"><span class="pre">longstringitem</span></code></a>* '&quot;&quot;&quot;'
<strong id="grammar-token-shortstringitem">shortstringitem</strong> ::=  <a class="reference internal" href="#grammar-token-shortstringchar"><code class="xref docutils literal notranslate"><span class="pre">shortstringchar</span></code></a> | <a class="reference internal" href="#grammar-token-escapeseq"><code class="xref docutils literal notranslate"><span class="pre">escapeseq</span></code></a>
<strong id="grammar-token-longstringitem">longstringitem </strong> ::=  <a class="reference internal" href="#grammar-token-longstringchar"><code class="xref docutils literal notranslate"><span class="pre">longstringchar</span></code></a> | <a class="reference internal" href="#grammar-token-escapeseq"><code class="xref docutils literal notranslate"><span class="pre">escapeseq</span></code></a>
<strong id="grammar-token-shortstringchar">shortstringchar</strong> ::=  &lt;any source character except &quot;\&quot; or newline or the quote&gt;
<strong id="grammar-token-longstringchar">longstringchar </strong> ::=  &lt;any source character except &quot;\&quot;&gt;
<strong id="grammar-token-escapeseq">escapeseq      </strong> ::=  &quot;\&quot; &lt;any ASCII character&gt;
</pre>
<p>One syntactic restriction not indicated by these productions is that whitespace
is not allowed between the <a class="reference internal" href="#grammar-token-stringprefix"><code class="xref std std-token docutils literal notranslate"><span class="pre">stringprefix</span></code></a> and the rest of the string
literal. The source character set is defined by the encoding declaration; it is
ASCII if no encoding declaration is given in the source file; see section
<a class="reference internal" href="#encodings"><span class="std std-ref">Encoding declarations</span></a>.</p>
<p id="index-14">In plain English: String literals can be enclosed in matching single quotes
(<code class="docutils literal notranslate"><span class="pre">'</span></code>) or double quotes (<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>).  They can also be enclosed in matching groups
of three single or double quotes (these are generally referred to as
<em>triple-quoted strings</em>).  The backslash (<code class="docutils literal notranslate"><span class="pre">\</span></code>) character is used to escape
characters that otherwise have a special meaning, such as newline, backslash
itself, or the quote character.  String literals may optionally be prefixed with
a letter <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'R'</span></code>; such strings are called <em class="dfn">raw strings</em> and use
different rules for interpreting backslash escape sequences.  A prefix of
<code class="docutils literal notranslate"><span class="pre">'u'</span></code> or <code class="docutils literal notranslate"><span class="pre">'U'</span></code> makes the string a Unicode string.  Unicode strings use the
Unicode character set as defined by the Unicode Consortium and ISO 10646.  Some
additional escape sequences, described below, are available in Unicode strings.
A prefix of <code class="docutils literal notranslate"><span class="pre">'b'</span></code> or <code class="docutils literal notranslate"><span class="pre">'B'</span></code> is ignored in Python 2; it indicates that the
literal should become a bytes literal in Python 3 (e.g. when code is
automatically converted with 2to3).  A <code class="docutils literal notranslate"><span class="pre">'u'</span></code> or <code class="docutils literal notranslate"><span class="pre">'b'</span></code> prefix may be followed
by an <code class="docutils literal notranslate"><span class="pre">'r'</span></code> prefix.</p>
<p>In triple-quoted strings, unescaped newlines and quotes are allowed (and are
retained), except that three unescaped quotes in a row terminate the string.  (A
“quote” is the character used to open the string, i.e. either <code class="docutils literal notranslate"><span class="pre">'</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;</span></code>.)</p>
<p id="index-15">Unless an <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'R'</span></code> prefix is present, escape sequences in strings are
interpreted according to rules similar to those used by Standard C.  The
recognized escape sequences are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="30%" />
<col width="58%" />
<col width="12%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Escape Sequence</th>
<th class="head">Meaning</th>
<th class="head">Notes</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\newline</span></code></td>
<td>Ignored</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\\</span></code></td>
<td>Backslash (<code class="docutils literal notranslate"><span class="pre">\</span></code>)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\'</span></code></td>
<td>Single quote (<code class="docutils literal notranslate"><span class="pre">'</span></code>)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\&quot;</span></code></td>
<td>Double quote (<code class="docutils literal notranslate"><span class="pre">&quot;</span></code>)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\a</span></code></td>
<td>ASCII Bell (BEL)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\b</span></code></td>
<td>ASCII Backspace (BS)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\f</span></code></td>
<td>ASCII Formfeed (FF)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\n</span></code></td>
<td>ASCII Linefeed (LF)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\N{name}</span></code></td>
<td>Character named <em>name</em> in the
Unicode database (Unicode only)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\r</span></code></td>
<td>ASCII Carriage Return (CR)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\t</span></code></td>
<td>ASCII Horizontal Tab (TAB)</td>
<td>&#160;</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\uxxxx</span></code></td>
<td>Character with 16-bit hex value
<em>xxxx</em> (Unicode only)</td>
<td>(1)</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\Uxxxxxxxx</span></code></td>
<td>Character with 32-bit hex value
<em>xxxxxxxx</em> (Unicode only)</td>
<td>(2)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\v</span></code></td>
<td>ASCII Vertical Tab (VT)</td>
<td>&#160;</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">\ooo</span></code></td>
<td>Character with octal value
<em>ooo</em></td>
<td>(3,5)</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">\xhh</span></code></td>
<td>Character with hex value <em>hh</em></td>
<td>(4,5)</td>
</tr>
</tbody>
</table>
<p id="index-16">Notes:</p>
<ol class="arabic simple">
<li>Individual code units which form parts of a surrogate pair can be encoded using
this escape sequence.</li>
<li>Any Unicode character can be encoded this way, but characters outside the Basic
Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is
compiled to use 16-bit code units (the default).</li>
<li>As in Standard C, up to three octal digits are accepted.</li>
<li>Unlike in Standard C, exactly two hex digits are required.</li>
<li>In a string literal, hexadecimal and octal escapes denote the byte with the
given value; it is not necessary that the byte encodes a character in the source
character set. In a Unicode literal, these escapes denote a Unicode character
with the given value.</li>
</ol>
<p id="index-17">Unlike Standard C, all unrecognized escape sequences are left in the string
unchanged, i.e., <em>the backslash is left in the string</em>.  (This behavior is
useful when debugging: if an escape sequence is mistyped, the resulting output
is more easily recognized as broken.)  It is also important to note that the
escape sequences marked as “(Unicode only)” in the table above fall into the
category of unrecognized escapes for non-Unicode string literals.</p>
<p>When an <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'R'</span></code> prefix is present, a character following a backslash
is included in the string without change, and <em>all backslashes are left in the
string</em>.  For example, the string literal <code class="docutils literal notranslate"><span class="pre">r&quot;\n&quot;</span></code> consists of two characters:
a backslash and a lowercase <code class="docutils literal notranslate"><span class="pre">'n'</span></code>.  String quotes can be escaped with a
backslash, but the backslash remains in the string; for example, <code class="docutils literal notranslate"><span class="pre">r&quot;\&quot;&quot;</span></code> is a
valid string literal consisting of two characters: a backslash and a double
quote; <code class="docutils literal notranslate"><span class="pre">r&quot;\&quot;</span></code> is not a valid string literal (even a raw string cannot end in
an odd number of backslashes).  Specifically, <em>a raw string cannot end in a
single backslash</em> (since the backslash would escape the following quote
character).  Note also that a single backslash followed by a newline is
interpreted as those two characters as part of the string, <em>not</em> as a line
continuation.</p>
<p>When an <code class="docutils literal notranslate"><span class="pre">'r'</span></code> or <code class="docutils literal notranslate"><span class="pre">'R'</span></code> prefix is used in conjunction with a <code class="docutils literal notranslate"><span class="pre">'u'</span></code> or
<code class="docutils literal notranslate"><span class="pre">'U'</span></code> prefix, then the <code class="docutils literal notranslate"><span class="pre">\uXXXX</span></code> and <code class="docutils literal notranslate"><span class="pre">\UXXXXXXXX</span></code> escape sequences are
processed while  <em>all other backslashes are left in the string</em>. For example,
the string literal <code class="docutils literal notranslate"><span class="pre">ur&quot;\u0062\n&quot;</span></code> consists of three Unicode characters: ‘LATIN
SMALL LETTER B’, ‘REVERSE SOLIDUS’, and ‘LATIN SMALL LETTER N’. Backslashes can
be escaped with a preceding backslash; however, both remain in the string.  As a
result, <code class="docutils literal notranslate"><span class="pre">\uXXXX</span></code> escape sequences are only recognized when there are an odd
number of backslashes.</p>
</div>
<div class="section" id="string-literal-concatenation">
<span id="string-catenation"></span><h3>2.4.2. String literal concatenation<a class="headerlink" href="#string-literal-concatenation" title="Permalink to this headline">¶</a></h3>
<p>Multiple adjacent string literals (delimited by whitespace), possibly using
different quoting conventions, are allowed, and their meaning is the same as
their concatenation.  Thus, <code class="docutils literal notranslate"><span class="pre">&quot;hello&quot;</span> <span class="pre">'world'</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">&quot;helloworld&quot;</span></code>.  This feature can be used to reduce the number of backslashes
needed, to split long strings conveniently across long lines, or even to add
comments to parts of strings, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">re</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span><span class="s2">&quot;[A-Za-z_]&quot;</span>       <span class="c1"># letter or underscore</span>
           <span class="s2">&quot;[A-Za-z0-9_]*&quot;</span>   <span class="c1"># letter, digit or underscore</span>
          <span class="p">)</span>
</pre></div>
</div>
<p>Note that this feature is defined at the syntactical level, but implemented at
compile time.  The ‘+’ operator must be used to concatenate string expressions
at run time.  Also note that literal concatenation can use different quoting
styles for each component (even mixing raw strings and triple quoted strings).</p>
</div>
<div class="section" id="numeric-literals">
<span id="numbers"></span><h3>2.4.3. Numeric literals<a class="headerlink" href="#numeric-literals" title="Permalink to this headline">¶</a></h3>
<p id="index-18">There are four types of numeric literals: plain integers, long integers,
floating point numbers, and imaginary numbers.  There are no complex literals
(complex numbers can be formed by adding a real number and an imaginary number).</p>
<p>Note that numeric literals do not include a sign; a phrase like <code class="docutils literal notranslate"><span class="pre">-1</span></code> is
actually an expression composed of the unary operator ‘<code class="docutils literal notranslate"><span class="pre">-</span></code>‘ and the literal
<code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</div>
<div class="section" id="integer-and-long-integer-literals">
<span id="integers"></span><h3>2.4.4. Integer and long integer literals<a class="headerlink" href="#integer-and-long-integer-literals" title="Permalink to this headline">¶</a></h3>
<p>Integer and long integer literals are described by the following lexical
definitions:</p>
<pre>
<strong id="grammar-token-longinteger">longinteger   </strong> ::=  <a class="reference internal" href="#grammar-token-integer"><code class="xref docutils literal notranslate"><span class="pre">integer</span></code></a> (&quot;l&quot; | &quot;L&quot;)
<strong id="grammar-token-integer">integer       </strong> ::=  <a class="reference internal" href="#grammar-token-decimalinteger"><code class="xref docutils literal notranslate"><span class="pre">decimalinteger</span></code></a> | <a class="reference internal" href="#grammar-token-octinteger"><code class="xref docutils literal notranslate"><span class="pre">octinteger</span></code></a> | <a class="reference internal" href="#grammar-token-hexinteger"><code class="xref docutils literal notranslate"><span class="pre">hexinteger</span></code></a> | <a class="reference internal" href="#grammar-token-bininteger"><code class="xref docutils literal notranslate"><span class="pre">bininteger</span></code></a>
<strong id="grammar-token-decimalinteger">decimalinteger</strong> ::=  <a class="reference internal" href="#grammar-token-nonzerodigit"><code class="xref docutils literal notranslate"><span class="pre">nonzerodigit</span></code></a> <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>* | &quot;0&quot;
<strong id="grammar-token-octinteger">octinteger    </strong> ::=  &quot;0&quot; (&quot;o&quot; | &quot;O&quot;) <a class="reference internal" href="#grammar-token-octdigit"><code class="xref docutils literal notranslate"><span class="pre">octdigit</span></code></a>+ | &quot;0&quot; <a class="reference internal" href="#grammar-token-octdigit"><code class="xref docutils literal notranslate"><span class="pre">octdigit</span></code></a>+
<strong id="grammar-token-hexinteger">hexinteger    </strong> ::=  &quot;0&quot; (&quot;x&quot; | &quot;X&quot;) <a class="reference internal" href="#grammar-token-hexdigit"><code class="xref docutils literal notranslate"><span class="pre">hexdigit</span></code></a>+
<strong id="grammar-token-bininteger">bininteger    </strong> ::=  &quot;0&quot; (&quot;b&quot; | &quot;B&quot;) <a class="reference internal" href="#grammar-token-bindigit"><code class="xref docutils literal notranslate"><span class="pre">bindigit</span></code></a>+
<strong id="grammar-token-nonzerodigit">nonzerodigit  </strong> ::=  &quot;1&quot;...&quot;9&quot;
<strong id="grammar-token-octdigit">octdigit      </strong> ::=  &quot;0&quot;...&quot;7&quot;
<strong id="grammar-token-bindigit">bindigit      </strong> ::=  &quot;0&quot; | &quot;1&quot;
<strong id="grammar-token-hexdigit">hexdigit      </strong> ::=  <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a> | &quot;a&quot;...&quot;f&quot; | &quot;A&quot;...&quot;F&quot;
</pre>
<p>Although both lower case <code class="docutils literal notranslate"><span class="pre">'l'</span></code> and upper case <code class="docutils literal notranslate"><span class="pre">'L'</span></code> are allowed as suffix
for long integers, it is strongly recommended to always use <code class="docutils literal notranslate"><span class="pre">'L'</span></code>, since the
letter <code class="docutils literal notranslate"><span class="pre">'l'</span></code> looks too much like the digit <code class="docutils literal notranslate"><span class="pre">'1'</span></code>.</p>
<p>Plain integer literals that are above the largest representable plain integer
(e.g., 2147483647 when using 32-bit arithmetic) are accepted as if they were
long integers instead. <a class="footnote-reference" href="#id11" id="id8">[1]</a>  There is no limit for long integer literals apart
from what can be stored in available memory.</p>
<p>Some examples of plain integer literals (first row) and long integer literals
(second and third rows):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">7</span>     <span class="mi">2147483647</span>                        <span class="mi">0177</span>
<span class="mi">3</span><span class="n">L</span>    <span class="mi">79228162514264337593543950336</span><span class="n">L</span>    <span class="mi">0377</span><span class="n">L</span>   <span class="mh">0x100000000</span><span class="n">L</span>
      <span class="mi">79228162514264337593543950336</span>             <span class="mh">0xdeadbeef</span>
</pre></div>
</div>
</div>
<div class="section" id="floating-point-literals">
<span id="floating"></span><h3>2.4.5. Floating point literals<a class="headerlink" href="#floating-point-literals" title="Permalink to this headline">¶</a></h3>
<p>Floating point literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-floatnumber">floatnumber  </strong> ::=  <a class="reference internal" href="#grammar-token-pointfloat"><code class="xref docutils literal notranslate"><span class="pre">pointfloat</span></code></a> | <a class="reference internal" href="#grammar-token-exponentfloat"><code class="xref docutils literal notranslate"><span class="pre">exponentfloat</span></code></a>
<strong id="grammar-token-pointfloat">pointfloat   </strong> ::=  [<a class="reference internal" href="#grammar-token-intpart"><code class="xref docutils literal notranslate"><span class="pre">intpart</span></code></a>] <a class="reference internal" href="#grammar-token-fraction"><code class="xref docutils literal notranslate"><span class="pre">fraction</span></code></a> | <a class="reference internal" href="#grammar-token-intpart"><code class="xref docutils literal notranslate"><span class="pre">intpart</span></code></a> &quot;.&quot;
<strong id="grammar-token-exponentfloat">exponentfloat</strong> ::=  (<a class="reference internal" href="#grammar-token-intpart"><code class="xref docutils literal notranslate"><span class="pre">intpart</span></code></a> | <a class="reference internal" href="#grammar-token-pointfloat"><code class="xref docutils literal notranslate"><span class="pre">pointfloat</span></code></a>) <a class="reference internal" href="#grammar-token-exponent"><code class="xref docutils literal notranslate"><span class="pre">exponent</span></code></a>
<strong id="grammar-token-intpart">intpart      </strong> ::=  <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>+
<strong id="grammar-token-fraction">fraction     </strong> ::=  &quot;.&quot; <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>+
<strong id="grammar-token-exponent">exponent     </strong> ::=  (&quot;e&quot; | &quot;E&quot;) [&quot;+&quot; | &quot;-&quot;] <a class="reference internal" href="#grammar-token-digit"><code class="xref docutils literal notranslate"><span class="pre">digit</span></code></a>+
</pre>
<p>Note that the integer and exponent parts of floating point numbers can look like
octal integers, but are interpreted using radix 10.  For example, <code class="docutils literal notranslate"><span class="pre">077e010</span></code> is
legal, and denotes the same number as <code class="docutils literal notranslate"><span class="pre">77e10</span></code>. The allowed range of floating
point literals is implementation-dependent. Some examples of floating point
literals:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">3.14</span>    <span class="mf">10.</span>    <span class="o">.</span><span class="mi">001</span>    <span class="mf">1e100</span>    <span class="mf">3.14e-10</span>    <span class="mf">0e0</span>
</pre></div>
</div>
<p>Note that numeric literals do not include a sign; a phrase like <code class="docutils literal notranslate"><span class="pre">-1</span></code> is
actually an expression composed of the unary operator <code class="docutils literal notranslate"><span class="pre">-</span></code> and the literal
<code class="docutils literal notranslate"><span class="pre">1</span></code>.</p>
</div>
<div class="section" id="imaginary-literals">
<span id="imaginary"></span><h3>2.4.6. Imaginary literals<a class="headerlink" href="#imaginary-literals" title="Permalink to this headline">¶</a></h3>
<p>Imaginary literals are described by the following lexical definitions:</p>
<pre>
<strong id="grammar-token-imagnumber">imagnumber</strong> ::=  (<a class="reference internal" href="#grammar-token-floatnumber"><code class="xref docutils literal notranslate"><span class="pre">floatnumber</span></code></a> | <a class="reference internal" href="#grammar-token-intpart"><code class="xref docutils literal notranslate"><span class="pre">intpart</span></code></a>) (&quot;j&quot; | &quot;J&quot;)
</pre>
<p>An imaginary literal yields a complex number with a real part of 0.0.  Complex
numbers are represented as a pair of floating point numbers and have the same
restrictions on their range.  To create a complex number with a nonzero real
part, add a floating point number to it, e.g., <code class="docutils literal notranslate"><span class="pre">(3+4j)</span></code>.  Some examples of
imaginary literals:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">3.14</span><span class="n">j</span>   <span class="mf">10.</span><span class="n">j</span>    <span class="mi">10</span><span class="n">j</span>     <span class="o">.</span><span class="mi">001</span><span class="n">j</span>   <span class="mf">1e100j</span>  <span class="mf">3.14e-10</span><span class="n">j</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="operators">
<span id="id9"></span><h2>2.5. Operators<a class="headerlink" href="#operators" title="Permalink to this headline">¶</a></h2>
<p id="index-19">The following tokens are operators:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>+       -       *       **      /       //      %
&lt;&lt;      &gt;&gt;      &amp;       |       ^       ~
&lt;       &gt;       &lt;=      &gt;=      ==      !=      &lt;&gt;
</pre></div>
</div>
<p>The comparison operators <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code> are alternate spellings of the same
operator.  <code class="docutils literal notranslate"><span class="pre">!=</span></code> is the preferred spelling; <code class="docutils literal notranslate"><span class="pre">&lt;&gt;</span></code> is obsolescent.</p>
</div>
<div class="section" id="delimiters">
<span id="id10"></span><h2>2.6. Delimiters<a class="headerlink" href="#delimiters" title="Permalink to this headline">¶</a></h2>
<p id="index-20">The following tokens serve as delimiters in the grammar:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>(       )       [       ]       {       }      @
,       :       .       `       =       ;
+=      -=      *=      /=      //=     %=
&amp;=      |=      ^=      &gt;&gt;=     &lt;&lt;=     **=
</pre></div>
</div>
<p>The period can also occur in floating-point and imaginary literals.  A sequence
of three periods has a special meaning as an ellipsis in slices. The second half
of the list, the augmented assignment operators, serve lexically as delimiters,
but also perform an operation.</p>
<p>The following printing ASCII characters have special meaning as part of other
tokens or are otherwise significant to the lexical analyzer:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>&#39;       &quot;       #       \
</pre></div>
</div>
<p id="index-21">The following printing ASCII characters are not used in Python.  Their
occurrence outside string literals and comments is an unconditional error:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>$       ?
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id11" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id8">[1]</a></td><td>In versions of Python prior to 2.4, octal and hexadecimal literals in the range
just above the largest representable plain integer but below the largest
unsigned 32-bit number (on a machine using 32-bit arithmetic), 4294967296, were
taken as the negative plain integer obtained by subtracting 4294967296 from
their unsigned value.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Lexical analysis</a><ul>
<li><a class="reference internal" href="#line-structure">2.1. Line structure</a><ul>
<li><a class="reference internal" href="#logical-lines">2.1.1. Logical lines</a></li>
<li><a class="reference internal" href="#physical-lines">2.1.2. Physical lines</a></li>
<li><a class="reference internal" href="#comments">2.1.3. Comments</a></li>
<li><a class="reference internal" href="#encoding-declarations">2.1.4. Encoding declarations</a></li>
<li><a class="reference internal" href="#explicit-line-joining">2.1.5. Explicit line joining</a></li>
<li><a class="reference internal" href="#implicit-line-joining">2.1.6. Implicit line joining</a></li>
<li><a class="reference internal" href="#blank-lines">2.1.7. Blank lines</a></li>
<li><a class="reference internal" href="#indentation">2.1.8. Indentation</a></li>
<li><a class="reference internal" href="#whitespace-between-tokens">2.1.9. Whitespace between tokens</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-tokens">2.2. Other tokens</a></li>
<li><a class="reference internal" href="#identifiers">2.3. Identifiers and keywords</a><ul>
<li><a class="reference internal" href="#keywords">2.3.1. Keywords</a></li>
<li><a class="reference internal" href="#reserved-classes-of-identifiers">2.3.2. Reserved classes of identifiers</a></li>
</ul>
</li>
<li><a class="reference internal" href="#literals">2.4. Literals</a><ul>
<li><a class="reference internal" href="#string-literals">2.4.1. String literals</a></li>
<li><a class="reference internal" href="#string-literal-concatenation">2.4.2. String literal concatenation</a></li>
<li><a class="reference internal" href="#numeric-literals">2.4.3. Numeric literals</a></li>
<li><a class="reference internal" href="#integer-and-long-integer-literals">2.4.4. Integer and long integer literals</a></li>
<li><a class="reference internal" href="#floating-point-literals">2.4.5. Floating point literals</a></li>
<li><a class="reference internal" href="#imaginary-literals">2.4.6. Imaginary literals</a></li>
</ul>
</li>
<li><a class="reference internal" href="#operators">2.5. Operators</a></li>
<li><a class="reference internal" href="#delimiters">2.6. Delimiters</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="previous chapter">1. Introduction</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datamodel.html"
                        title="next chapter">3. Data model</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/lexical_analysis.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datamodel.html" title="3. Data model"
             >next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="1. Introduction"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�aITψψ html/reference/simple_stmts.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>6. Simple statements &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7. Compound statements" href="compound_stmts.html" />
    <link rel="prev" title="5. Expressions" href="expressions.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/simple_stmts.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compound_stmts.html" title="7. Compound statements"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="expressions.html" title="5. Expressions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="simple-statements">
<span id="simple"></span><h1>6. Simple statements<a class="headerlink" href="#simple-statements" title="Permalink to this headline">¶</a></h1>
<p id="index-0">Simple statements are comprised within a single logical line. Several simple
statements may occur on a single line separated by semicolons.  The syntax for
simple statements is:</p>
<pre>
<strong id="grammar-token-simple_stmt">simple_stmt</strong> ::=  <a class="reference internal" href="#grammar-token-expression_stmt"><code class="xref docutils literal notranslate"><span class="pre">expression_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-assert_stmt"><code class="xref docutils literal notranslate"><span class="pre">assert_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-assignment_stmt"><code class="xref docutils literal notranslate"><span class="pre">assignment_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-augmented_assignment_stmt"><code class="xref docutils literal notranslate"><span class="pre">augmented_assignment_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-pass_stmt"><code class="xref docutils literal notranslate"><span class="pre">pass_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-del_stmt"><code class="xref docutils literal notranslate"><span class="pre">del_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-print_stmt"><code class="xref docutils literal notranslate"><span class="pre">print_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-return_stmt"><code class="xref docutils literal notranslate"><span class="pre">return_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-yield_stmt"><code class="xref docutils literal notranslate"><span class="pre">yield_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-raise_stmt"><code class="xref docutils literal notranslate"><span class="pre">raise_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-break_stmt"><code class="xref docutils literal notranslate"><span class="pre">break_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-continue_stmt"><code class="xref docutils literal notranslate"><span class="pre">continue_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-import_stmt"><code class="xref docutils literal notranslate"><span class="pre">import_stmt</span></code></a>
                 | <code class="xref docutils literal notranslate"><span class="pre">future_stmt</span></code>
                 | <a class="reference internal" href="#grammar-token-global_stmt"><code class="xref docutils literal notranslate"><span class="pre">global_stmt</span></code></a>
                 | <a class="reference internal" href="#grammar-token-exec_stmt"><code class="xref docutils literal notranslate"><span class="pre">exec_stmt</span></code></a>
</pre>
<div class="section" id="expression-statements">
<span id="exprstmts"></span><h2>6.1. Expression statements<a class="headerlink" href="#expression-statements" title="Permalink to this headline">¶</a></h2>
<p id="index-1">Expression statements are used (mostly interactively) to compute and write a
value, or (usually) to call a procedure (a function that returns no meaningful
result; in Python, procedures return the value <code class="docutils literal notranslate"><span class="pre">None</span></code>).  Other uses of
expression statements are allowed and occasionally useful.  The syntax for an
expression statement is:</p>
<pre>
<strong id="grammar-token-expression_stmt">expression_stmt</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>
</pre>
<p>An expression statement evaluates the expression list (which may be a single
expression).</p>
<p id="index-2">In interactive mode, if the value is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it is converted to a string
using the built-in <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function and the resulting string is written to
standard output (see section <a class="reference internal" href="#print"><span class="std std-ref">The print statement</span></a>) on a line by itself.  (Expression
statements yielding <code class="docutils literal notranslate"><span class="pre">None</span></code> are not written, so that procedure calls do not
cause any output.)</p>
</div>
<div class="section" id="assignment-statements">
<span id="assignment"></span><h2>6.2. Assignment statements<a class="headerlink" href="#assignment-statements" title="Permalink to this headline">¶</a></h2>
<p id="index-3">Assignment statements are used to (re)bind names to values and to modify
attributes or items of mutable objects:</p>
<pre>
<strong id="grammar-token-assignment_stmt">assignment_stmt</strong> ::=  (<a class="reference internal" href="#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;=&quot;)+ (<a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>)
<strong id="grammar-token-target_list">target_list    </strong> ::=  <a class="reference internal" href="#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a> (&quot;,&quot; <a class="reference internal" href="#grammar-token-target"><code class="xref docutils literal notranslate"><span class="pre">target</span></code></a>)* [&quot;,&quot;]
<strong id="grammar-token-target">target         </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
                     | &quot;(&quot; <a class="reference internal" href="#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a> &quot;)&quot;
                     | &quot;[&quot; [<a class="reference internal" href="#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a>] &quot;]&quot;
                     | <a class="reference internal" href="expressions.html#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a>
                     | <a class="reference internal" href="expressions.html#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a>
                     | <a class="reference internal" href="expressions.html#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a>
</pre>
<p>(See section <a class="reference internal" href="expressions.html#primaries"><span class="std std-ref">Primaries</span></a> for the syntax definitions for the last three
symbols.)</p>
<p id="index-4">An assignment statement evaluates the expression list (remember that this can be
a single expression or a comma-separated list, the latter yielding a tuple) and
assigns the single resulting object to each of the target lists, from left to
right.</p>
<p id="index-5">Assignment is defined recursively depending on the form of the target (list).
When a target is part of a mutable object (an attribute reference, subscription
or slicing), the mutable object must ultimately perform the assignment and
decide about its validity, and may raise an exception if the assignment is
unacceptable.  The rules observed by various types and the exceptions raised are
given with the definition of the object types (see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>).</p>
<p id="index-6">Assignment of an object to a target list is recursively defined as follows.</p>
<ul class="simple">
<li>If the target list is a single target: The object is assigned to that target.</li>
<li>If the target list is a comma-separated list of targets: The object must be an
iterable with the same number of items as there are targets in the target list,
and the items are assigned, from left to right, to the corresponding targets.</li>
</ul>
<p>Assignment of an object to a single target is recursively defined as follows.</p>
<ul>
<li><p class="first">If the target is an identifier (name):</p>
<blockquote>
<div></div></blockquote>
<ul class="simple" id="index-7">
<li>If the name does not occur in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement in the current
code block: the name is bound to the object in the current local namespace.</li>
<li>Otherwise: the name is bound to the object in the current global namespace.</li>
</ul>
<p id="index-8">The name is rebound if it was already bound.  This may cause the reference count
for the object previously bound to the name to reach zero, causing the object to
be deallocated and its destructor (if it has one) to be called.</p>
</li>
<li><p class="first">If the target is a target list enclosed in parentheses or in square brackets:
The object must be an iterable with the same number of items as there are
targets in the target list, and its items are assigned, from left to right,
to the corresponding targets.</p>
</li>
<li id="index-9"><p class="first">If the target is an attribute reference: The primary expression in the
reference is evaluated.  It should yield an object with assignable attributes;
if this is not the case, <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> is raised.  That object is then
asked to assign the assigned object to the given attribute; if it cannot
perform the assignment, it raises an exception (usually but not necessarily
<a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>).</p>
<p id="attr-target-note">Note: If the object is a class instance and the attribute reference occurs on
both sides of the assignment operator, the RHS expression, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> can access
either an instance attribute or (if no instance attribute exists) a class
attribute.  The LHS target <code class="docutils literal notranslate"><span class="pre">a.x</span></code> is always set as an instance attribute,
creating it if necessary.  Thus, the two occurrences of <code class="docutils literal notranslate"><span class="pre">a.x</span></code> do not
necessarily refer to the same attribute: if the RHS expression refers to a
class attribute, the LHS creates a new instance attribute as the target of the
assignment:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Cls</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="mi">3</span>             <span class="c1"># class variable</span>
<span class="n">inst</span> <span class="o">=</span> <span class="n">Cls</span><span class="p">()</span>
<span class="n">inst</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">x</span> <span class="o">+</span> <span class="mi">1</span>   <span class="c1"># writes inst.x as 4 leaving Cls.x as 3</span>
</pre></div>
</div>
<p>This description does not necessarily apply to descriptor attributes, such as
properties created with <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a>.</p>
</li>
<li id="index-10"><p class="first">If the target is a subscription: The primary expression in the reference is
evaluated.  It should yield either a mutable sequence object (such as a list) or
a mapping object (such as a dictionary). Next, the subscript expression is
evaluated.</p>
<p id="index-11">If the primary is a mutable sequence object (such as a list), the subscript must
yield a plain integer.  If it is negative, the sequence’s length is added to it.
The resulting value must be a nonnegative integer less than the sequence’s
length, and the sequence is asked to assign the assigned object to its item with
that index.  If the index is out of range, <a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is raised
(assignment to a subscripted sequence cannot add new items to a list).</p>
<p id="index-12">If the primary is a mapping object (such as a dictionary), the subscript must
have a type compatible with the mapping’s key type, and the mapping is then
asked to create a key/datum pair which maps the subscript to the assigned
object.  This can either replace an existing key/value pair with the same key
value, or insert a new key/value pair (if no key with the same value existed).</p>
</li>
<li id="index-13"><p class="first">If the target is a slicing: The primary expression in the reference is
evaluated.  It should yield a mutable sequence object (such as a list).  The
assigned object should be a sequence object of the same type.  Next, the lower
and upper bound expressions are evaluated, insofar they are present; defaults
are zero and the sequence’s length.  The bounds should evaluate to (small)
integers.  If either bound is negative, the sequence’s length is added to it.
The resulting bounds are clipped to lie between zero and the sequence’s length,
inclusive.  Finally, the sequence object is asked to replace the slice with the
items of the assigned sequence.  The length of the slice may be different from
the length of the assigned sequence, thus changing the length of the target
sequence, if the object allows it.</p>
</li>
</ul>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> In the current implementation, the syntax for targets is taken to be the same
as for expressions, and invalid syntax is rejected during the code generation
phase, causing less detailed error messages.</p>
</div>
<p>WARNING: Although the definition of assignment implies that overlaps between the
left-hand side and the right-hand side are ‘safe’ (for example <code class="docutils literal notranslate"><span class="pre">a,</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">b,</span> <span class="pre">a</span></code>
swaps two variables), overlaps <em>within</em> the collection of assigned-to variables
are not safe!  For instance, the following program prints <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">2]</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">]</span>
<span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
<span class="n">i</span><span class="p">,</span> <span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span>
<span class="nb">print</span> <span class="n">x</span>
</pre></div>
</div>
<div class="section" id="augmented-assignment-statements">
<span id="augassign"></span><h3>6.2.1. Augmented assignment statements<a class="headerlink" href="#augmented-assignment-statements" title="Permalink to this headline">¶</a></h3>
<p id="index-14">Augmented assignment is the combination, in a single statement, of a binary
operation and an assignment statement:</p>
<pre>
<strong id="grammar-token-augmented_assignment_stmt">augmented_assignment_stmt</strong> ::=  <a class="reference internal" href="#grammar-token-augtarget"><code class="xref docutils literal notranslate"><span class="pre">augtarget</span></code></a> <a class="reference internal" href="#grammar-token-augop"><code class="xref docutils literal notranslate"><span class="pre">augop</span></code></a> (<a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>)
<strong id="grammar-token-augtarget">augtarget                </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-attributeref"><code class="xref docutils literal notranslate"><span class="pre">attributeref</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-subscription"><code class="xref docutils literal notranslate"><span class="pre">subscription</span></code></a> | <a class="reference internal" href="expressions.html#grammar-token-slicing"><code class="xref docutils literal notranslate"><span class="pre">slicing</span></code></a>
<strong id="grammar-token-augop">augop                    </strong> ::=  &quot;+=&quot; | &quot;-=&quot; | &quot;*=&quot; | &quot;/=&quot; | &quot;//=&quot; | &quot;%=&quot; | &quot;**=&quot;
                               | &quot;&gt;&gt;=&quot; | &quot;&lt;&lt;=&quot; | &quot;&amp;=&quot; | &quot;^=&quot; | &quot;|=&quot;
</pre>
<p>(See section <a class="reference internal" href="expressions.html#primaries"><span class="std std-ref">Primaries</span></a> for the syntax definitions for the last three
symbols.)</p>
<p>An augmented assignment evaluates the target (which, unlike normal assignment
statements, cannot be an unpacking) and the expression list, performs the binary
operation specific to the type of assignment on the two operands, and assigns
the result to the original target.  The target is only evaluated once.</p>
<p>An augmented assignment expression like <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">1</span></code> can be rewritten as <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x</span> <span class="pre">+</span>
<span class="pre">1</span></code> to achieve a similar, but not exactly equal effect. In the augmented
version, <code class="docutils literal notranslate"><span class="pre">x</span></code> is only evaluated once. Also, when possible, the actual operation
is performed <em>in-place</em>, meaning that rather than creating a new object and
assigning that to the target, the old object is modified instead.</p>
<p>With the exception of assigning to tuples and multiple targets in a single
statement, the assignment done by augmented assignment statements is handled the
same way as normal assignments. Similarly, with the exception of the possible
<em>in-place</em> behavior, the binary operation performed by augmented assignment is
the same as the normal binary operations.</p>
<p>For targets which are attribute references, the same <a class="reference internal" href="#attr-target-note"><span class="std std-ref">caveat about class
and instance attributes</span></a> applies as for regular assignments.</p>
</div>
</div>
<div class="section" id="the-assert-statement">
<span id="assert"></span><h2>6.3. The <a class="reference internal" href="#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement<a class="headerlink" href="#the-assert-statement" title="Permalink to this headline">¶</a></h2>
<p id="index-15">Assert statements are a convenient way to insert debugging assertions into a
program:</p>
<pre>
<strong id="grammar-token-assert_stmt">assert_stmt</strong> ::=  &quot;assert&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]
</pre>
<p>The simple form, <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">expression</span></code>, is equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">__debug__</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">expression</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">AssertionError</span>
</pre></div>
</div>
<p>The extended form, <code class="docutils literal notranslate"><span class="pre">assert</span> <span class="pre">expression1,</span> <span class="pre">expression2</span></code>, is equivalent to</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">__debug__</span><span class="p">:</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">expression1</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">AssertionError</span><span class="p">(</span><span class="n">expression2</span><span class="p">)</span>
</pre></div>
</div>
<p id="index-16">These equivalences assume that <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.AssertionError" title="exceptions.AssertionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AssertionError</span></code></a> refer to
the built-in variables with those names.  In the current implementation, the
built-in variable <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> is <code class="docutils literal notranslate"><span class="pre">True</span></code> under normal circumstances,
<code class="docutils literal notranslate"><span class="pre">False</span></code> when optimization is requested (command line option -O).  The current
code generator emits no code for an assert statement when optimization is
requested at compile time.  Note that it is unnecessary to include the source
code for the expression that failed in the error message; it will be displayed
as part of the stack trace.</p>
<p>Assignments to <a class="reference internal" href="../library/constants.html#__debug__" title="__debug__"><code class="xref py py-const docutils literal notranslate"><span class="pre">__debug__</span></code></a> are illegal.  The value for the built-in variable
is determined when the interpreter starts.</p>
</div>
<div class="section" id="the-pass-statement">
<span id="pass"></span><h2>6.4. The <a class="reference internal" href="#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> statement<a class="headerlink" href="#the-pass-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-17">
<strong id="grammar-token-pass_stmt">pass_stmt</strong> ::=  &quot;pass&quot;
</pre>
<p><a class="reference internal" href="#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> is a null operation — when it is executed, nothing happens.
It is useful as a placeholder when a statement is required syntactically, but no
code needs to be executed, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span> <span class="k">pass</span>    <span class="c1"># a function that does nothing (yet)</span>

<span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="k">pass</span>       <span class="c1"># a class with no methods (yet)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-del-statement">
<span id="del"></span><h2>6.5. The <a class="reference internal" href="#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement<a class="headerlink" href="#the-del-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-18">
<strong id="grammar-token-del_stmt">del_stmt</strong> ::=  &quot;del&quot; <a class="reference internal" href="#grammar-token-target_list"><code class="xref docutils literal notranslate"><span class="pre">target_list</span></code></a>
</pre>
<p>Deletion is recursively defined very similar to the way assignment is defined.
Rather than spelling it out in full details, here are some hints.</p>
<p>Deletion of a target list recursively deletes each target, from left to right.</p>
<p id="index-19">Deletion of a name removes the binding of that name  from the local or global
namespace, depending on whether the name occurs in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement
in the same code block.  If the name is unbound, a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception
will be raised.</p>
<p id="index-20">It is illegal to delete a name from the local namespace if it occurs as a free
variable in a nested block.</p>
<p id="index-21">Deletion of attribute references, subscriptions and slicings is passed to the
primary object involved; deletion of a slicing is in general equivalent to
assignment of an empty slice of the right type (but even this is determined by
the sliced object).</p>
</div>
<div class="section" id="the-print-statement">
<span id="print"></span><h2>6.6. The <a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement<a class="headerlink" href="#the-print-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-22">
<strong id="grammar-token-print_stmt">print_stmt</strong> ::=  &quot;print&quot; ([<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> (&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)* [&quot;,&quot;]]
                | &quot;&gt;&gt;&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [(&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>)+ [&quot;,&quot;]])
</pre>
<p><a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> evaluates each expression in turn and writes the resulting
object to standard output (see below).  If an object is not a string, it is
first converted to a string using the rules for string conversions.  The
(resulting or original) string is then written.  A space is written before each
object is (converted and) written, unless the output system believes it is
positioned at the beginning of a line.  This is the case (1) when no characters
have yet been written to standard output, (2) when the last character written to
standard output is a whitespace character except <code class="docutils literal notranslate"><span class="pre">'</span> <span class="pre">'</span></code>, or (3) when the last
write operation on standard output was not a <a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.
(In some cases it may be functional to write an empty string to standard output
for this reason.)</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Objects which act like file objects but which are not the built-in file objects
often do not properly emulate this aspect of the file object’s behavior, so it
is best not to rely on this.</p>
</div>
<p id="index-23">A <code class="docutils literal notranslate"><span class="pre">'\n'</span></code> character is written at the end, unless the <a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>
statement ends with a comma.  This is the only action if the statement contains
just the keyword <a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>.</p>
<p id="index-24">Standard output is defined as the file object named <code class="docutils literal notranslate"><span class="pre">stdout</span></code> in the built-in
module <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>.  If no such object exists, or if it does not have a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method, a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> exception is raised.</p>
<p id="index-25"><a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> also has an extended form, defined by the second portion of the
syntax described above. This form is sometimes referred to as “<a class="reference internal" href="#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>
chevron.” In this form, the first expression after the <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code> must evaluate to a
“file-like” object, specifically an object that has a <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method as
described above.  With this extended form, the subsequent expressions are
printed to this file object.  If the first expression evaluates to <code class="docutils literal notranslate"><span class="pre">None</span></code>,
then <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> is used as the file for output.</p>
</div>
<div class="section" id="the-return-statement">
<span id="return"></span><h2>6.7. The <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement<a class="headerlink" href="#the-return-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-26">
<strong id="grammar-token-return_stmt">return_stmt</strong> ::=  &quot;return&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a>]
</pre>
<p><a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> may only occur syntactically nested in a function definition,
not within a nested class definition.</p>
<p>If an expression list is present, it is evaluated, else <code class="docutils literal notranslate"><span class="pre">None</span></code> is substituted.</p>
<p><a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> leaves the current function call with the expression list (or
<code class="docutils literal notranslate"><span class="pre">None</span></code>) as return value.</p>
<p id="index-27">When <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed before
really leaving the function.</p>
<p>In a generator function, the <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement is not allowed to
include an <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a>.  In that context, a bare <a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a>
indicates that the generator is done and will cause <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> to be
raised.</p>
</div>
<div class="section" id="the-yield-statement">
<span id="yield"></span><h2>6.8. The <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement<a class="headerlink" href="#the-yield-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-28">
<strong id="grammar-token-yield_stmt">yield_stmt</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-yield_expression"><code class="xref docutils literal notranslate"><span class="pre">yield_expression</span></code></a>
</pre>
<p>The <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is only used when defining a generator function,
and is only used in the body of the generator function. Using a <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
statement in a function definition is sufficient to cause that definition to
create a generator function instead of a normal function.</p>
<p>When a generator function is called, it returns an iterator known as a generator
iterator, or more commonly, a generator.  The body of the generator function is
executed by calling the generator’s <a class="reference internal" href="expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method repeatedly
until it raises an exception.</p>
<p>When a <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is executed, the state of the generator is
frozen and the value of <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref std std-token docutils literal notranslate"><span class="pre">expression_list</span></code></a> is returned to
<a class="reference internal" href="expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a>’s caller.  By “frozen” we mean that all local state is
retained, including the current bindings of local variables, the instruction
pointer, and the internal evaluation stack: enough information is saved so that
the next time <a class="reference internal" href="expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> is invoked, the function can proceed
exactly as if the <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement were just another external call.</p>
<p>As of Python version 2.5, the <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is now allowed in the
<a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> …  <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> construct.  If
the generator is not resumed before it is finalized (by reaching a zero
reference count or by being garbage collected), the generator-iterator’s
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method will be called, allowing any pending <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
clauses to execute.</p>
<p>For full details of <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> semantics, refer to the <a class="reference internal" href="expressions.html#yieldexpr"><span class="std std-ref">Yield expressions</span></a>
section.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>In Python 2.2, the <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement was only allowed when the
<code class="docutils literal notranslate"><span class="pre">generators</span></code> feature has been enabled.  This <code class="docutils literal notranslate"><span class="pre">__future__</span></code>
import statement was used to enable the feature:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">generators</span>
</pre></div>
</div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-29"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>The proposal for adding generators and the <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement to Python.</dd>
<dt><span class="target" id="index-30"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd>The proposal that, among other generator enhancements, proposed allowing
<a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> to appear inside a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block.</dd>
</dl>
</div>
</div>
<div class="section" id="the-raise-statement">
<span id="raise"></span><h2>6.9. The <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement<a class="headerlink" href="#the-raise-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-31">
<strong id="grammar-token-raise_stmt">raise_stmt</strong> ::=  &quot;raise&quot; [<a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]]]
</pre>
<p>If no expressions are present, <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> re-raises the last exception
that was active in the current scope.  If no exception is active in the current
scope, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is raised indicating that this is an error
(if running under IDLE, a <a class="reference internal" href="../library/queue.html#Queue.Empty" title="Queue.Empty"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Queue.Empty</span></code></a> exception is raised instead).</p>
<p>Otherwise, <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> evaluates the expressions to get three objects,
using <code class="docutils literal notranslate"><span class="pre">None</span></code> as the value of omitted expressions.  The first two objects are
used to determine the <em>type</em> and <em>value</em> of the exception.</p>
<p>If the first object is an instance, the type of the exception is the class of
the instance, the instance itself is the value, and the second object must be
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>If the first object is a class, it becomes the type of the exception. The second
object is used to determine the exception value: If it is an instance of the
class, the instance becomes the exception value. If the second object is a
tuple, it is used as the argument list for the class constructor; if it is
<code class="docutils literal notranslate"><span class="pre">None</span></code>, an empty argument list is used, and any other object is treated as a
single argument to the constructor.  The instance so created by calling the
constructor is used as the exception value.</p>
<p id="index-32">If a third object is present and not <code class="docutils literal notranslate"><span class="pre">None</span></code>, it must be a traceback object
(see section <a class="reference internal" href="datamodel.html#types"><span class="std std-ref">The standard type hierarchy</span></a>), and it is substituted instead of the current
location as the place where the exception occurred.  If the third object is
present and not a traceback object or <code class="docutils literal notranslate"><span class="pre">None</span></code>, a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception is
raised.  The three-expression form of <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> is useful to re-raise an
exception transparently in an except clause, but <a class="reference internal" href="#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> with no
expressions should be preferred if the exception to be re-raised was the most
recently active exception in the current scope.</p>
<p>Additional information on exceptions can be found in section <a class="reference internal" href="executionmodel.html#exceptions"><span class="std std-ref">Exceptions</span></a>,
and information about handling exceptions is in section <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>.</p>
</div>
<div class="section" id="the-break-statement">
<span id="break"></span><h2>6.10. The <a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement<a class="headerlink" href="#the-break-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-33">
<strong id="grammar-token-break_stmt">break_stmt</strong> ::=  &quot;break&quot;
</pre>
<p><a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> may only occur syntactically nested in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or
<a class="reference internal" href="compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop, but not nested in a function or class definition within
that loop.</p>
<p id="index-34">It terminates the nearest enclosing loop, skipping the optional <a class="reference internal" href="compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a>
clause if the loop has one.</p>
<p id="index-35">If a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop is terminated by <a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, the loop control
target keeps its current value.</p>
<p id="index-36">When <a class="reference internal" href="#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed before
really leaving the loop.</p>
</div>
<div class="section" id="the-continue-statement">
<span id="continue"></span><h2>6.11. The <a class="reference internal" href="#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement<a class="headerlink" href="#the-continue-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-37">
<strong id="grammar-token-continue_stmt">continue_stmt</strong> ::=  &quot;continue&quot;
</pre>
<p><a class="reference internal" href="#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> may only occur syntactically nested in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or
<a class="reference internal" href="compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop, but not nested in a function or class definition or
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause within that loop.  It continues with the next
cycle of the nearest enclosing loop.</p>
<p>When <a class="reference internal" href="#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> passes control out of a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with a
<a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause, that <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed before
really starting the next loop cycle.</p>
</div>
<div class="section" id="the-import-statement">
<span id="from"></span><span id="import"></span><h2>6.12. The <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement<a class="headerlink" href="#the-import-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-38">
<strong id="grammar-token-import_stmt">import_stmt    </strong> ::=  &quot;import&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>] ( &quot;,&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>] )*
                     | &quot;from&quot; <a class="reference internal" href="#grammar-token-relative_module"><code class="xref docutils literal notranslate"><span class="pre">relative_module</span></code></a> &quot;import&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>]
                     ( &quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>] )*
                     | &quot;from&quot; <a class="reference internal" href="#grammar-token-relative_module"><code class="xref docutils literal notranslate"><span class="pre">relative_module</span></code></a> &quot;import&quot; &quot;(&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>]
                     ( &quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> [&quot;as&quot; <a class="reference internal" href="#grammar-token-name"><code class="xref docutils literal notranslate"><span class="pre">name</span></code></a>] )* [&quot;,&quot;] &quot;)&quot;
                     | &quot;from&quot; <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> &quot;import&quot; &quot;*&quot;
<strong id="grammar-token-module">module         </strong> ::=  (<a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> &quot;.&quot;)* <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
<strong id="grammar-token-relative_module">relative_module</strong> ::=  &quot;.&quot;* <a class="reference internal" href="#grammar-token-module"><code class="xref docutils literal notranslate"><span class="pre">module</span></code></a> | &quot;.&quot;+
<strong id="grammar-token-name">name           </strong> ::=  <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>
</pre>
<p>Import statements are executed in two steps: (1) find a module, and initialize
it if necessary; (2) define a name or names in the local namespace (of the scope
where the <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement occurs). The statement comes in two
forms differing on whether it uses the <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> keyword. The first form
(without <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a>) repeats these steps for each identifier in the list.
The form with <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> performs step (1) once, and then performs step
(2) repeatedly.</p>
<p id="index-39">To understand how step (1) occurs, one must first understand how Python handles
hierarchical naming of modules. To help organize modules and provide a
hierarchy in naming, Python has a concept of packages. A package can contain
other packages and modules while modules cannot contain other modules or
packages. From a file system perspective, packages are directories and modules
are files.</p>
<p id="index-40">Once the name of the module is known (unless otherwise specified, the term
“module” will refer to both packages and modules), searching
for the module or package can begin. The first place checked is
<a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a>, the cache of all modules that have been imported
previously. If the module is found there then it is used in step (2) of import.</p>
<p id="index-41">If the module is not found in the cache, then <a class="reference internal" href="../library/sys.html#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a> is searched
(the specification for <a class="reference internal" href="../library/sys.html#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a> can be found in <span class="target" id="index-42"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>).
The object is a list of <a class="reference internal" href="../glossary.html#term-finder"><span class="xref std std-term">finder</span></a> objects which are queried in order as to
whether they know how to load the module by calling their <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code>
method with the name of the module. If the module happens to be contained
within a package (as denoted by the existence of a dot in the name), then a
second argument to <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code> is given as the value of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code> attribute from the parent package (everything up to the last
dot in the name of the module being imported). If a finder can find the module
it returns a <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a> (discussed later) or returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p id="index-43">If none of the finders on <a class="reference internal" href="../library/sys.html#sys.meta_path" title="sys.meta_path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.meta_path</span></code></a> are able to find the module
then some implicitly defined finders are queried. Implementations of Python
vary in what implicit meta path finders are defined. The one they all do
define, though, is one that handles <a class="reference internal" href="../library/sys.html#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a>,
<a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a>, and <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<p>The implicit finder searches for the requested module in the “paths” specified
in one of two places (“paths” do not have to be file system paths). If the
module being imported is supposed to be contained within a package then the
second argument passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code> on the parent
package, is used as the source of paths. If the module is not contained in a
package then <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is used as the source of paths.</p>
<p>Once the source of paths is chosen it is iterated over to find a finder that
can handle that path. The dict at <a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a> caches
finders for paths and is checked for a finder. If the path does not have a
finder cached then <a class="reference internal" href="../library/sys.html#sys.path_hooks" title="sys.path_hooks"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_hooks</span></code></a> is searched by calling each object in
the list with a single argument of the path, returning a finder or raises
<a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>. If a finder is returned then it is cached in
<a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a> and then used for that path entry. If no finder
can be found but the path exists then a value of <code class="docutils literal notranslate"><span class="pre">None</span></code> is
stored in <a class="reference internal" href="../library/sys.html#sys.path_importer_cache" title="sys.path_importer_cache"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code></a> to signify that an implicit,
file-based finder that handles modules stored as individual files should be
used for that path. If the path does not exist then a finder which always
returns <code class="docutils literal notranslate"><span class="pre">None</span></code> is placed in the cache for the path.</p>
<p id="index-44">If no finder can find the module then <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is raised. Otherwise
some finder returned a loader whose <code class="xref py py-meth docutils literal notranslate"><span class="pre">load_module()</span></code> method is called with
the name of the module to load (see <span class="target" id="index-45"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for the original definition of
loaders). A loader has several responsibilities to perform on a module it
loads. First, if the module already exists in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> (a
possibility if the loader is called outside of the import machinery) then it
is to use that module for initialization and not a new module. But if the
module does not exist in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> then it is to be added to that
dict before initialization begins. If an error occurs during loading of the
module and it was added to <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> it is to be removed from the
dict. If an error occurs but the module was already in <a class="reference internal" href="../library/sys.html#sys.modules" title="sys.modules"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.modules</span></code></a> it
is left in the dict.</p>
<p id="index-46">The loader must set several attributes on the module. <code class="xref py py-data docutils literal notranslate"><span class="pre">__name__</span></code> is to be
set to the name of the module. <code class="xref py py-data docutils literal notranslate"><span class="pre">__file__</span></code> is to be the “path” to the file
unless the module is built-in (and thus listed in
<a class="reference internal" href="../library/sys.html#sys.builtin_module_names" title="sys.builtin_module_names"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.builtin_module_names</span></code></a>) in which case the attribute is not set.
If what is being imported is a package then <code class="xref py py-data docutils literal notranslate"><span class="pre">__path__</span></code> is to be set to a
list of paths to be searched when looking for modules and packages contained
within the package being imported. <code class="xref py py-data docutils literal notranslate"><span class="pre">__package__</span></code> is optional but should
be set to the name of package that contains the module or package (the empty
string is used for module not contained in a package). <code class="xref py py-data docutils literal notranslate"><span class="pre">__loader__</span></code> is
also optional but should be set to the loader object that is loading the
module.</p>
<p id="index-47">If an error occurs during loading then the loader raises <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> if
some other exception is not already being propagated. Otherwise the loader
returns the module that was loaded and initialized.</p>
<p>When step (1) finishes without raising an exception, step (2) can begin.</p>
<p>The first form of <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement binds the module name in the local
namespace to the module object, and then goes on to import the next identifier,
if any.  If the module name is followed by <a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a>, the name following
<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> is used as the local name for the module.</p>
<p id="index-48">The <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> form does not bind the module name: it goes through the list
of identifiers, looks each one of them up in the module found in step (1), and
binds the name in the local namespace to the object thus found.  As with the
first form of <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>, an alternate local name can be supplied by
specifying “<a class="reference internal" href="compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> localname”.  If a name is not found,
<a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is raised.  If the list of identifiers is replaced by a star
(<code class="docutils literal notranslate"><span class="pre">'*'</span></code>), all public names defined in the module are bound in the local
namespace of the <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement..</p>
<p id="index-49">The <em>public names</em> defined by a module are determined by checking the module’s
namespace for a variable named <code class="docutils literal notranslate"><span class="pre">__all__</span></code>; if defined, it must be a sequence of
strings which are names defined or imported by that module.  The names given in
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> are all considered public and are required to exist.  If <code class="docutils literal notranslate"><span class="pre">__all__</span></code>
is not defined, the set of public names includes all names found in the module’s
namespace which do not begin with an underscore character (<code class="docutils literal notranslate"><span class="pre">'_'</span></code>).
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> should contain the entire public API. It is intended to avoid
accidentally exporting items that are not part of the API (such as library
modules which were imported and used within the module).</p>
<p>The <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> form with <code class="docutils literal notranslate"><span class="pre">*</span></code> may only occur in a module scope.  If the
wild card form of import — <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">*</span></code> — is used in a function and the
function contains or is a nested block with free variables, the compiler will
raise a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>.</p>
<p id="index-50">When specifying what module to import you do not have to specify the absolute
name of the module. When a module or package is contained within another
package it is possible to make a relative import within the same top package
without having to mention the package name. By using leading dots in the
specified module or package after <a class="reference internal" href="#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> you can specify how high to
traverse up the current package hierarchy without specifying exact names. One
leading dot means the current package where the module making the import
exists. Two dots means up one package level. Three dots is up two levels, etc.
So if you execute <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">.</span> <span class="pre">import</span> <span class="pre">mod</span></code> from a module in the <code class="docutils literal notranslate"><span class="pre">pkg</span></code> package
then you will end up importing <code class="docutils literal notranslate"><span class="pre">pkg.mod</span></code>. If you execute <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">..subpkg2</span>
<span class="pre">import</span> <span class="pre">mod</span></code> from within <code class="docutils literal notranslate"><span class="pre">pkg.subpkg1</span></code> you will import <code class="docutils literal notranslate"><span class="pre">pkg.subpkg2.mod</span></code>.
The specification for relative imports is contained within <span class="target" id="index-51"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a>.</p>
<p><a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> is provided to support applications that
determine which modules need to be loaded dynamically.</p>
<div class="section" id="future-statements">
<span id="future"></span><h3>6.12.1. Future statements<a class="headerlink" href="#future-statements" title="Permalink to this headline">¶</a></h3>
<p id="index-52">A <em class="dfn">future statement</em> is a directive to the compiler that a particular
module should be compiled using syntax or semantics that will be available in a
specified future release of Python.  The future statement is intended to ease
migration to future versions of Python that introduce incompatible changes to
the language.  It allows use of the new features on a per-module basis before
the release in which the feature becomes standard.</p>
<pre>
<strong id="grammar-token-future_statement">future_statement</strong> ::=  &quot;from&quot; &quot;__future__&quot; &quot;import&quot; feature [&quot;as&quot; name]
                      (&quot;,&quot; feature [&quot;as&quot; name])*
                      | &quot;from&quot; &quot;__future__&quot; &quot;import&quot; &quot;(&quot; feature [&quot;as&quot; name]
                      (&quot;,&quot; feature [&quot;as&quot; name])* [&quot;,&quot;] &quot;)&quot;
<strong id="grammar-token-feature">feature         </strong> ::=  identifier
<strong id="id1">name            </strong> ::=  identifier
</pre>
<p>A future statement must appear near the top of the module.  The only lines that
can appear before a future statement are:</p>
<ul class="simple">
<li>the module docstring (if any),</li>
<li>comments,</li>
<li>blank lines, and</li>
<li>other future statements.</li>
</ul>
<p>The features recognized by Python 2.6 are <code class="docutils literal notranslate"><span class="pre">unicode_literals</span></code>,
<code class="docutils literal notranslate"><span class="pre">print_function</span></code>, <code class="docutils literal notranslate"><span class="pre">absolute_import</span></code>, <code class="docutils literal notranslate"><span class="pre">division</span></code>, <code class="docutils literal notranslate"><span class="pre">generators</span></code>,
<code class="docutils literal notranslate"><span class="pre">nested_scopes</span></code> and <code class="docutils literal notranslate"><span class="pre">with_statement</span></code>.  <code class="docutils literal notranslate"><span class="pre">generators</span></code>, <code class="docutils literal notranslate"><span class="pre">with_statement</span></code>,
<code class="docutils literal notranslate"><span class="pre">nested_scopes</span></code> are redundant in Python version 2.6 and above because they are
always enabled.</p>
<p>A future statement is recognized and treated specially at compile time: Changes
to the semantics of core constructs are often implemented by generating
different code.  It may even be the case that a new feature introduces new
incompatible syntax (such as a new reserved word), in which case the compiler
may need to parse the module differently.  Such decisions cannot be pushed off
until runtime.</p>
<p>For any given release, the compiler knows which feature names have been defined,
and raises a compile-time error if a future statement contains a feature not
known to it.</p>
<p>The direct runtime semantics are the same as for any import statement: there is
a standard module <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a>, described later, and it will be imported in
the usual way at the time the future statement is executed.</p>
<p>The interesting runtime semantics depend on the specific feature enabled by the
future statement.</p>
<p>Note that there is nothing special about the statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">__future__</span> <span class="p">[</span><span class="k">as</span> <span class="n">name</span><span class="p">]</span>
</pre></div>
</div>
<p>That is not a future statement; it’s an ordinary import statement with no
special semantics or syntax restrictions.</p>
<p>Code compiled by an <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement or calls to the built-in functions
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> and <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> that occur in a module <code class="xref py py-mod docutils literal notranslate"><span class="pre">M</span></code> containing
a future statement will, by default, use the new  syntax or semantics associated
with the future statement.  This can, starting with Python 2.2 be controlled by
optional arguments to <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> — see the documentation of that function
for details.</p>
<p>A future statement typed at an interactive interpreter prompt will take effect
for the rest of the interpreter session.  If an interpreter is started with the
<a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> option, is passed a script name to execute, and the script includes
a future statement, it will be in effect in the interactive session started
after the script is executed.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-53"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0236"><strong>PEP 236</strong></a> - Back to the __future__</dt>
<dd>The original proposal for the __future__ mechanism.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="the-global-statement">
<span id="global"></span><h2>6.13. The <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement<a class="headerlink" href="#the-global-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-54">
<strong id="grammar-token-global_stmt">global_stmt</strong> ::=  &quot;global&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a> (&quot;,&quot; <a class="reference internal" href="lexical_analysis.html#grammar-token-identifier"><code class="xref docutils literal notranslate"><span class="pre">identifier</span></code></a>)*
</pre>
<p>The <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement is a declaration which holds for the entire
current code block.  It means that the listed identifiers are to be interpreted
as globals.  It would be impossible to assign to a global variable without
<a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a>, although free variables may refer to globals without being
declared global.</p>
<p>Names listed in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement must not be used in the same code
block textually preceding that <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement.</p>
<p>Names listed in a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement must not be defined as formal
parameters or in a <a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop control target, <a class="reference internal" href="compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>
definition, function definition, or <a class="reference internal" href="#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> The current implementation does not enforce the latter two restrictions, but
programs should not abuse this freedom, as future implementations may enforce
them or silently change the meaning of the program.</p>
</div>
<p id="index-55"><strong>Programmer’s note:</strong> <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> is a directive to the parser.  It
applies only to code parsed at the same time as the <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement.
In particular, a <a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement contained in an <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>
statement does not affect the code block <em>containing</em> the <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>
statement, and code contained in an <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement is unaffected by
<a class="reference internal" href="#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statements in the code containing the <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>
statement.  The same applies to the <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>, <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> and
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> functions.</p>
</div>
<div class="section" id="the-exec-statement">
<span id="exec"></span><h2>6.14. The <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement<a class="headerlink" href="#the-exec-statement" title="Permalink to this headline">¶</a></h2>
<pre id="index-56">
<strong id="grammar-token-exec_stmt">exec_stmt</strong> ::=  &quot;exec&quot; <a class="reference internal" href="expressions.html#grammar-token-or_expr"><code class="xref docutils literal notranslate"><span class="pre">or_expr</span></code></a> [&quot;in&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a> [&quot;,&quot; <a class="reference internal" href="expressions.html#grammar-token-expression"><code class="xref docutils literal notranslate"><span class="pre">expression</span></code></a>]]
</pre>
<p>This statement supports dynamic execution of Python code.  The first expression
should evaluate to either a Unicode string, a <em>Latin-1</em> encoded string, an open
file object, a code object, or a tuple.  If it is a string, the string is parsed
as a suite of Python statements which is then executed (unless a syntax error
occurs). <a class="footnote-reference" href="#id3" id="id2">[1]</a> If it is an open file, the file is parsed until EOF and executed.
If it is a code object, it is simply executed.  For the interpretation of a
tuple, see below.  In all cases, the code that’s executed is expected to be
valid as file input (see section <a class="reference internal" href="toplevel_components.html#file-input"><span class="std std-ref">File input</span></a>).  Be aware that the
<a class="reference internal" href="#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> and <a class="reference internal" href="#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statements may not be used outside of
function definitions even within the context of code passed to the
<a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement.</p>
<p>In all cases, if the optional parts are omitted, the code is executed in the
current scope.  If only the first expression after <code class="docutils literal notranslate"><span class="pre">in</span></code> is specified,
it should be a dictionary, which will be used for both the global and the local
variables.  If two expressions are given, they are used for the global and local
variables, respectively. If provided, <em>locals</em> can be any mapping object.
Remember that at module level, globals and locals are the same dictionary. If
two separate objects are given as <em>globals</em> and <em>locals</em>, the code will be
executed as if it were embedded in a class definition.</p>
<p>The first expression may also be a tuple of length 2 or 3.  In this case, the
optional parts must be omitted.  The form <code class="docutils literal notranslate"><span class="pre">exec(expr,</span> <span class="pre">globals)</span></code> is equivalent
to <code class="docutils literal notranslate"><span class="pre">exec</span> <span class="pre">expr</span> <span class="pre">in</span> <span class="pre">globals</span></code>, while the form <code class="docutils literal notranslate"><span class="pre">exec(expr,</span> <span class="pre">globals,</span> <span class="pre">locals)</span></code> is
equivalent to <code class="docutils literal notranslate"><span class="pre">exec</span> <span class="pre">expr</span> <span class="pre">in</span> <span class="pre">globals,</span> <span class="pre">locals</span></code>.  The tuple form of <code class="docutils literal notranslate"><span class="pre">exec</span></code>
provides compatibility with Python 3, where <code class="docutils literal notranslate"><span class="pre">exec</span></code> is a function rather than
a statement.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.4: </span>Formerly, <em>locals</em> was required to be a dictionary.</p>
</div>
<p id="index-57">As a side effect, an implementation may insert additional keys into the
dictionaries given besides those corresponding to variable names set by the
executed code.  For example, the current implementation may add a reference to
the dictionary of the built-in module <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> under the key
<code class="docutils literal notranslate"><span class="pre">__builtins__</span></code> (!).</p>
<p id="index-58"><strong>Programmer’s hints:</strong> dynamic evaluation of expressions is supported by the
built-in function <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.  The built-in functions <a class="reference internal" href="../library/functions.html#globals" title="globals"><code class="xref py py-func docutils literal notranslate"><span class="pre">globals()</span></code></a> and
<a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> return the current global and local dictionary, respectively,
which may be useful to pass around for use by <a class="reference internal" href="#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a>.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[1]</a></td><td>Note that the parser only accepts the Unix-style end of line convention.
If you are reading the code from a file, make sure to use
<a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> mode to convert Windows or Mac-style newlines.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">6. Simple statements</a><ul>
<li><a class="reference internal" href="#expression-statements">6.1. Expression statements</a></li>
<li><a class="reference internal" href="#assignment-statements">6.2. Assignment statements</a><ul>
<li><a class="reference internal" href="#augmented-assignment-statements">6.2.1. Augmented assignment statements</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-assert-statement">6.3. The <code class="docutils literal notranslate"><span class="pre">assert</span></code> statement</a></li>
<li><a class="reference internal" href="#the-pass-statement">6.4. The <code class="docutils literal notranslate"><span class="pre">pass</span></code> statement</a></li>
<li><a class="reference internal" href="#the-del-statement">6.5. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li><a class="reference internal" href="#the-print-statement">6.6. The <code class="docutils literal notranslate"><span class="pre">print</span></code> statement</a></li>
<li><a class="reference internal" href="#the-return-statement">6.7. The <code class="docutils literal notranslate"><span class="pre">return</span></code> statement</a></li>
<li><a class="reference internal" href="#the-yield-statement">6.8. The <code class="docutils literal notranslate"><span class="pre">yield</span></code> statement</a></li>
<li><a class="reference internal" href="#the-raise-statement">6.9. The <code class="docutils literal notranslate"><span class="pre">raise</span></code> statement</a></li>
<li><a class="reference internal" href="#the-break-statement">6.10. The <code class="docutils literal notranslate"><span class="pre">break</span></code> statement</a></li>
<li><a class="reference internal" href="#the-continue-statement">6.11. The <code class="docutils literal notranslate"><span class="pre">continue</span></code> statement</a></li>
<li><a class="reference internal" href="#the-import-statement">6.12. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement</a><ul>
<li><a class="reference internal" href="#future-statements">6.12.1. Future statements</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-global-statement">6.13. The <code class="docutils literal notranslate"><span class="pre">global</span></code> statement</a></li>
<li><a class="reference internal" href="#the-exec-statement">6.14. The <code class="docutils literal notranslate"><span class="pre">exec</span></code> statement</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="expressions.html"
                        title="previous chapter">5. Expressions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="compound_stmts.html"
                        title="next chapter">7. Compound statements</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/simple_stmts.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="compound_stmts.html" title="7. Compound statements"
             >next</a> |</li>
        <li class="right" >
          <a href="expressions.html" title="5. Expressions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�{^��4�4'html/reference/toplevel_components.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8. Top-level components &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9. Full Grammar specification" href="grammar.html" />
    <link rel="prev" title="7. Compound statements" href="compound_stmts.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/reference/toplevel_components.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="grammar.html" title="9. Full Grammar specification"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="compound_stmts.html" title="7. Compound statements"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="top-level-components">
<span id="top-level"></span><h1>8. Top-level components<a class="headerlink" href="#top-level-components" title="Permalink to this headline">¶</a></h1>
<p id="index-0">The Python interpreter can get its input from a number of sources: from a script
passed to it as standard input or as program argument, typed in interactively,
from a module source file, etc.  This chapter gives the syntax used in these
cases.</p>
<div class="section" id="complete-python-programs">
<span id="programs"></span><h2>8.1. Complete Python programs<a class="headerlink" href="#complete-python-programs" title="Permalink to this headline">¶</a></h2>
<span class="target" id="index-1"></span><p id="index-2">While a language specification need not prescribe how the language interpreter
is invoked, it is useful to have a notion of a complete Python program.  A
complete Python program is executed in a minimally initialized environment: all
built-in and standard modules are available, but none have been initialized,
except for <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> (various system services), <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> (built-in
functions, exceptions and <code class="docutils literal notranslate"><span class="pre">None</span></code>) and <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>.  The latter is used to
provide the local and global namespace for execution of the complete program.</p>
<p>The syntax for a complete Python program is that for file input, described in
the next section.</p>
<p id="index-3">The interpreter may also be invoked in interactive mode; in this case, it does
not read and execute a complete program but reads and executes one statement
(possibly compound) at a time.  The initial environment is identical to that of
a complete program; each statement is executed in the namespace of
<a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>.</p>
<p id="index-4">A complete program can be passed to the interpreter
in three forms: with the <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>string</em> command line option, as a file
passed as the first command line argument, or as standard input. If the file
or standard input is a tty device, the interpreter enters interactive mode;
otherwise, it executes the file as a complete program.</p>
</div>
<div class="section" id="file-input">
<span id="id1"></span><h2>8.2. File input<a class="headerlink" href="#file-input" title="Permalink to this headline">¶</a></h2>
<p>All input read from non-interactive files has the same form:</p>
<pre>
<strong id="grammar-token-file_input">file_input</strong> ::=  (NEWLINE | <a class="reference internal" href="compound_stmts.html#grammar-token-statement"><code class="xref docutils literal notranslate"><span class="pre">statement</span></code></a>)*
</pre>
<p>This syntax is used in the following situations:</p>
<ul class="simple">
<li>when parsing a complete Python program (from a file or from a string);</li>
<li>when parsing a module;</li>
<li>when parsing a string passed to the <a class="reference internal" href="simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement;</li>
</ul>
</div>
<div class="section" id="interactive-input">
<span id="interactive"></span><h2>8.3. Interactive input<a class="headerlink" href="#interactive-input" title="Permalink to this headline">¶</a></h2>
<p>Input in interactive mode is parsed using the following grammar:</p>
<pre>
<strong id="grammar-token-interactive_input">interactive_input</strong> ::=  [<a class="reference internal" href="compound_stmts.html#grammar-token-stmt_list"><code class="xref docutils literal notranslate"><span class="pre">stmt_list</span></code></a>] NEWLINE | <a class="reference internal" href="compound_stmts.html#grammar-token-compound_stmt"><code class="xref docutils literal notranslate"><span class="pre">compound_stmt</span></code></a> NEWLINE
</pre>
<p>Note that a (top-level) compound statement must be followed by a blank line in
interactive mode; this is needed to help the parser detect the end of the input.</p>
</div>
<div class="section" id="expression-input">
<span id="id2"></span><h2>8.4. Expression input<a class="headerlink" href="#expression-input" title="Permalink to this headline">¶</a></h2>
<span class="target" id="index-5"></span><p id="index-6">There are two forms of expression input.  Both ignore leading whitespace. The
string argument to <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> must have the following form:</p>
<pre>
<strong id="grammar-token-eval_input">eval_input</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> NEWLINE*
</pre>
<p id="index-7">The input line read by <a class="reference internal" href="../library/functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> must have the following form:</p>
<pre>
<strong id="grammar-token-input_input">input_input</strong> ::=  <a class="reference internal" href="expressions.html#grammar-token-expression_list"><code class="xref docutils literal notranslate"><span class="pre">expression_list</span></code></a> NEWLINE
</pre>
<p id="index-8">Note: to read ‘raw’ input line without interpretation, you can use the built-in
function <a class="reference internal" href="../library/functions.html#raw_input" title="raw_input"><code class="xref py py-func docutils literal notranslate"><span class="pre">raw_input()</span></code></a> or the <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method of file objects.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8. Top-level components</a><ul>
<li><a class="reference internal" href="#complete-python-programs">8.1. Complete Python programs</a></li>
<li><a class="reference internal" href="#file-input">8.2. File input</a></li>
<li><a class="reference internal" href="#interactive-input">8.3. Interactive input</a></li>
<li><a class="reference internal" href="#expression-input">8.4. Expression input</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="compound_stmts.html"
                        title="previous chapter">7. Compound statements</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="grammar.html"
                        title="next chapter">9. Full Grammar specification</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/reference/toplevel_components.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="grammar.html" title="9. Full Grammar specification"
             >next</a> |</li>
        <li class="right" >
          <a href="compound_stmts.html" title="7. Compound statements"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��^B^Bhtml/tutorial/appendix.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>15. Appendix &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="Python Setup and Usage" href="../using/index.html" />
    <link rel="prev" title="14. Floating Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/appendix.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../using/index.html" title="Python Setup and Usage"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="appendix">
<span id="tut-appendix"></span><h1>15. Appendix<a class="headerlink" href="#appendix" title="Permalink to this headline">¶</a></h1>
<div class="section" id="interactive-mode">
<span id="tut-interac"></span><h2>15.1. Interactive Mode<a class="headerlink" href="#interactive-mode" title="Permalink to this headline">¶</a></h2>
<div class="section" id="error-handling">
<span id="tut-error"></span><h3>15.1.1. Error Handling<a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h3>
<p>When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause in a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement
are not errors in this context.)  Some errors are unconditionally fatal and
cause an exit with a nonzero exit; this applies to internal inconsistencies and
some cases of running out of memory.  All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.</p>
<p>Typing the interrupt character (usually <kbd class="kbd docutils literal notranslate">Control-C</kbd> or <kbd class="kbd docutils literal notranslate">Delete</kbd>) to the primary or
secondary prompt cancels the input and returns to the primary prompt. <a class="footnote-reference" href="#id2" id="id1">[1]</a>
Typing an interrupt while a command is executing raises the
<a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception, which may be handled by a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
statement.</p>
</div>
<div class="section" id="executable-python-scripts">
<span id="tut-scripts"></span><h3>15.1.2. Executable Python Scripts<a class="headerlink" href="#executable-python-scripts" title="Permalink to this headline">¶</a></h3>
<p>On BSD’ish Unix systems, Python scripts can be made directly executable, like
shell scripts, by putting the line</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
</pre></div>
</div>
<p>(assuming that the interpreter is on the user’s <span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>) at the beginning
of the script and giving the file an executable mode.  The <code class="docutils literal notranslate"><span class="pre">#!</span></code> must be the
first two characters of the file.  On some platforms, this first line must end
with a Unix-style line ending (<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>), not a Windows (<code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>) line
ending.  Note that the hash, or pound, character, <code class="docutils literal notranslate"><span class="pre">'#'</span></code>, is used to start a
comment in Python.</p>
<p>The script can be given an executable mode, or permission, using the
<strong class="program">chmod</strong> command.</p>
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>$ chmod +x myscript.py
</pre></div>
</div>
<p>On Windows systems, there is no notion of an “executable mode”.  The Python
installer automatically associates <code class="docutils literal notranslate"><span class="pre">.py</span></code> files with <code class="docutils literal notranslate"><span class="pre">python.exe</span></code> so that
a double-click on a Python file will run it as a script.  The extension can
also be <code class="docutils literal notranslate"><span class="pre">.pyw</span></code>, in that case, the console window that normally appears is
suppressed.</p>
</div>
<div class="section" id="the-interactive-startup-file">
<span id="tut-startup"></span><h3>15.1.3. The Interactive Startup File<a class="headerlink" href="#the-interactive-startup-file" title="Permalink to this headline">¶</a></h3>
<p>When you use Python interactively, it is frequently handy to have some standard
commands executed every time the interpreter is started.  You can do this by
setting an environment variable named <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> to the name of a
file containing your start-up commands.  This is similar to the <code class="file docutils literal notranslate"><span class="pre">.profile</span></code>
feature of the Unix shells.</p>
<p>This file is only read in interactive sessions, not when Python reads commands
from a script, and not when <code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> is given as the explicit source of
commands (which otherwise behaves like an interactive session).  It is executed
in the same namespace where interactive commands are executed, so that objects
that it defines or imports can be used without qualification in the interactive
session. You can also change the prompts <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code> in this
file.</p>
<p>If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like <code class="docutils literal notranslate"><span class="pre">if</span>
<span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">exec(open('.pythonrc.py').read())</span></code>.
If you want to use the startup file in a script, you must do this explicitly
in the script:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">os</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;PYTHONSTARTUP&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">filename</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">fobj</span><span class="p">:</span>
        <span class="n">startup_file</span> <span class="o">=</span> <span class="n">fobj</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
    <span class="n">exec</span><span class="p">(</span><span class="n">startup_file</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-customization-modules">
<span id="tut-customize"></span><h3>15.1.4. The Customization Modules<a class="headerlink" href="#the-customization-modules" title="Permalink to this headline">¶</a></h3>
<p>Python provides two hooks to let you customize it: <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code>.  To see how it works, you need first to find the location
of your user site-packages directory.  Start Python and run this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">site</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">site</span><span class="o">.</span><span class="n">getusersitepackages</span><span class="p">()</span>
<span class="go">&#39;/home/user/.local/lib/python2.7/site-packages&#39;</span>
</pre></div>
</div>
<p>Now you can create a file named <code class="file docutils literal notranslate"><span class="pre">usercustomize.py</span></code> in that directory and
put anything you want in it.  It will affect every invocation of Python, unless
it is started with the <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option to disable the automatic import.</p>
<p><code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> works in the same way, but is typically created by an
administrator of the computer in the global site-packages directory, and is
imported before <code class="xref py py-mod docutils literal notranslate"><span class="pre">usercustomize</span></code>.  See the documentation of the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a>
module for more details.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>A problem with the GNU Readline package may prevent this.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">15. Appendix</a><ul>
<li><a class="reference internal" href="#interactive-mode">15.1. Interactive Mode</a><ul>
<li><a class="reference internal" href="#error-handling">15.1.1. Error Handling</a></li>
<li><a class="reference internal" href="#executable-python-scripts">15.1.2. Executable Python Scripts</a></li>
<li><a class="reference internal" href="#the-interactive-startup-file">15.1.3. The Interactive Startup File</a></li>
<li><a class="reference internal" href="#the-customization-modules">15.1.4. The Customization Modules</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="floatingpoint.html"
                        title="previous chapter">14. Floating Point Arithmetic:  Issues and Limitations</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../using/index.html"
                        title="next chapter">Python Setup and Usage</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/appendix.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../using/index.html" title="Python Setup and Usage"
             >next</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�~X�)�)html/tutorial/appetite.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. Whetting Your Appetite &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Using the Python Interpreter" href="interpreter.html" />
    <link rel="prev" title="The Python Tutorial" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/appetite.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="interpreter.html" title="2. Using the Python Interpreter"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Tutorial"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="whetting-your-appetite">
<span id="tut-intro"></span><h1>1. Whetting Your Appetite<a class="headerlink" href="#whetting-your-appetite" title="Permalink to this headline">¶</a></h1>
<p>If you do much work on computers, eventually you find that there’s some task
you’d like to automate.  For example, you may wish to perform a
search-and-replace over a large number of text files, or rename and rearrange a
bunch of photo files in a complicated way. Perhaps you’d like to write a small
custom database, or a specialized GUI application, or a simple game.</p>
<p>If you’re a professional software developer, you may have to work with several
C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is
too slow.  Perhaps you’re writing a test suite for such a library and find
writing the testing code a tedious task.  Or maybe you’ve written a program that
could use an extension language, and you don’t want to design and implement a
whole new language for your application.</p>
<p>Python is just the language for you.</p>
<p>You could write a Unix shell script or Windows batch files for some of these
tasks, but shell scripts are best at moving around files and changing text data,
not well-suited for GUI applications or games. You could write a C/C++/Java
program, but it can take a lot of development time to get even a first-draft
program.  Python is simpler to use, available on Windows, Mac OS X, and Unix
operating systems, and will help you get the job done more quickly.</p>
<p>Python is simple to use, but it is a real programming language, offering much
more structure and support for large programs than shell scripts or batch files
can offer.  On the other hand, Python also offers much more error checking than
C, and, being a <em>very-high-level language</em>, it has high-level data types built
in, such as flexible arrays and dictionaries.  Because of its more general data
types Python is applicable to a much larger problem domain than Awk or even
Perl, yet many things are at least as easy in Python as in those languages.</p>
<p>Python allows you to split your program into modules that can be reused in other
Python programs.  It comes with a large collection of standard modules that you
can use as the basis of your programs — or as examples to start learning to
program in Python.  Some of these modules provide things like file I/O, system
calls, sockets, and even interfaces to graphical user interface toolkits like
Tk.</p>
<p>Python is an interpreted language, which can save you considerable time during
program development because no compilation and linking is necessary.  The
interpreter can be used interactively, which makes it easy to experiment with
features of the language, to write throw-away programs, or to test functions
during bottom-up program development. It is also a handy desk calculator.</p>
<p>Python enables programs to be written compactly and readably.  Programs written
in Python are typically much shorter than equivalent C,  C++, or Java programs,
for several reasons:</p>
<ul class="simple">
<li>the high-level data types allow you to express complex operations in a single
statement;</li>
<li>statement grouping is done by indentation instead of beginning and ending
brackets;</li>
<li>no variable or argument declarations are necessary.</li>
</ul>
<p>Python is <em>extensible</em>: if you know how to program in C it is easy to add a new
built-in function or module to the interpreter, either to perform critical
operations at maximum speed, or to link Python programs to libraries that may
only be available in binary form (such as a vendor-specific graphics library).
Once you are really hooked, you can link the Python interpreter into an
application written in C and use it as an extension or command language for that
application.</p>
<p>By the way, the language is named after the BBC show “Monty Python’s Flying
Circus” and has nothing to do with reptiles.  Making references to Monty
Python skits in documentation is not only allowed, it is encouraged!</p>
<p>Now that you are all excited about Python, you’ll want to examine it in some
more detail.  Since the best way to learn a language is to use it, the tutorial
invites you to play with the Python interpreter as you read.</p>
<p>In the next chapter, the mechanics of using the interpreter are explained.  This
is rather mundane information, but essential for trying out the examples shown
later.</p>
<p>The rest of the tutorial introduces various features of the Python language and
system through examples, beginning with simple expressions, statements and data
types, through functions and modules, and finally touching upon advanced
concepts like exceptions and user-defined classes.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">The Python Tutorial</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="interpreter.html"
                        title="next chapter">2. Using the Python Interpreter</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/appetite.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="interpreter.html" title="2. Using the Python Interpreter"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="The Python Tutorial"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��Ġg�ghtml/tutorial/classes.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>9. Classes &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
    <link rel="prev" title="8. Errors and Exceptions" href="errors.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/classes.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="classes">
<span id="tut-classes"></span><h1>9. Classes<a class="headerlink" href="#classes" title="Permalink to this headline">¶</a></h1>
<p>Compared with other programming languages, Python’s class mechanism adds classes
with a minimum of new syntax and semantics.  It is a mixture of the class
mechanisms found in C++ and Modula-3.  Python classes provide all the standard
features of Object Oriented Programming: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
name.  Objects can contain arbitrary amounts and kinds of data.  As is true for
modules, classes partake of the dynamic nature of Python: they are created at
runtime, and can be modified further after creation.</p>
<p>In C++ terminology, normally class members (including the data members) are
<em>public</em> (except see below <a class="reference internal" href="#tut-private"><span class="std std-ref">Private Variables and Class-local References</span></a>), and all member functions are
<em>virtual</em>.  As in Modula-3, there are no shorthands for referencing the object’s
members from its methods: the method function is declared with an explicit first
argument representing the object, which is provided implicitly by the call.  As
in Smalltalk, classes themselves are objects.  This provides semantics for
importing and renaming.  Unlike C++ and Modula-3, built-in types can be used as
base classes for extension by the user.  Also, like in C++, most built-in
operators with special syntax (arithmetic operators, subscripting etc.) can be
redefined for class instances.</p>
<p>(Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms.  I would use Modula-3 terms, since
its object-oriented semantics are closer to those of Python than C++, but I
expect that few readers have heard of it.)</p>
<div class="section" id="a-word-about-names-and-objects">
<span id="tut-object"></span><h2>9.1. A Word About Names and Objects<a class="headerlink" href="#a-word-about-names-and-objects" title="Permalink to this headline">¶</a></h2>
<p>Objects have individuality, and multiple names (in multiple scopes) can be bound
to the same object.  This is known as aliasing in other languages.  This is
usually not appreciated on a first glance at Python, and can be safely ignored
when dealing with immutable basic types (numbers, strings, tuples).  However,
aliasing has a possibly surprising effect on the semantics of Python code
involving mutable objects such as lists, dictionaries, and most other types.
This is usually used to the benefit of the program, since aliases behave like
pointers in some respects.  For example, passing an object is cheap since only a
pointer is passed by the implementation; and if a function modifies an object
passed as an argument, the caller will see the change — this eliminates the
need for two different argument passing mechanisms as in Pascal.</p>
</div>
<div class="section" id="python-scopes-and-namespaces">
<span id="tut-scopes"></span><h2>9.2. Python Scopes and Namespaces<a class="headerlink" href="#python-scopes-and-namespaces" title="Permalink to this headline">¶</a></h2>
<p>Before introducing classes, I first have to tell you something about Python’s
scope rules.  Class definitions play some neat tricks with namespaces, and you
need to know how scopes and namespaces work to fully understand what’s going on.
Incidentally, knowledge about this subject is useful for any advanced Python
programmer.</p>
<p>Let’s begin with some definitions.</p>
<p>A <em>namespace</em> is a mapping from names to objects.  Most namespaces are currently
implemented as Python dictionaries, but that’s normally not noticeable in any
way (except for performance), and it may change in the future.  Examples of
namespaces are: the set of built-in names (containing functions such as <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a>, and
built-in exception names); the global names in a module; and the local names in
a function invocation.  In a sense the set of attributes of an object also form
a namespace.  The important thing to know about namespaces is that there is
absolutely no relation between names in different namespaces; for instance, two
different modules may both define a function <code class="docutils literal notranslate"><span class="pre">maximize</span></code> without confusion —
users of the modules must prefix it with the module name.</p>
<p>By the way, I use the word <em>attribute</em> for any name following a dot — for
example, in the expression <code class="docutils literal notranslate"><span class="pre">z.real</span></code>, <code class="docutils literal notranslate"><span class="pre">real</span></code> is an attribute of the object
<code class="docutils literal notranslate"><span class="pre">z</span></code>.  Strictly speaking, references to names in modules are attribute
references: in the expression <code class="docutils literal notranslate"><span class="pre">modname.funcname</span></code>, <code class="docutils literal notranslate"><span class="pre">modname</span></code> is a module
object and <code class="docutils literal notranslate"><span class="pre">funcname</span></code> is an attribute of it.  In this case there happens to be
a straightforward mapping between the module’s attributes and the global names
defined in the module: they share the same namespace!  <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<p>Attributes may be read-only or writable.  In the latter case, assignment to
attributes is possible.  Module attributes are writable: you can write
<code class="docutils literal notranslate"><span class="pre">modname.the_answer</span> <span class="pre">=</span> <span class="pre">42</span></code>.  Writable attributes may also be deleted with the
<a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement.  For example, <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">modname.the_answer</span></code> will remove
the attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">the_answer</span></code> from the object named by <code class="docutils literal notranslate"><span class="pre">modname</span></code>.</p>
<p>Namespaces are created at different moments and have different lifetimes.  The
namespace containing the built-in names is created when the Python interpreter
starts up, and is never deleted.  The global namespace for a module is created
when the module definition is read in; normally, module namespaces also last
until the interpreter quits.  The statements executed by the top-level
invocation of the interpreter, either read from a script file or interactively,
are considered part of a module called <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a>, so they have their own
global namespace.  (The built-in names actually also live in a module; this is
called <a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a>.)</p>
<p>The local namespace for a function is created when the function is called, and
deleted when the function returns or raises an exception that is not handled
within the function.  (Actually, forgetting would be a better way to describe
what actually happens.)  Of course, recursive invocations each have their own
local namespace.</p>
<p>A <em>scope</em> is a textual region of a Python program where a namespace is directly
accessible.  “Directly accessible” here means that an unqualified reference to a
name attempts to find the name in the namespace.</p>
<p>Although scopes are determined statically, they are used dynamically. At any
time during execution, there are at least three nested scopes whose namespaces
are directly accessible:</p>
<ul class="simple">
<li>the innermost scope, which is searched first, contains the local names</li>
<li>the scopes of any enclosing functions, which are searched starting with the
nearest enclosing scope, contains non-local, but also non-global names</li>
<li>the next-to-last scope contains the current module’s global names</li>
<li>the outermost scope (searched last) is the namespace containing built-in names</li>
</ul>
<p>If a name is declared global, then all references and assignments go directly to
the middle scope containing the module’s global names. Otherwise, all variables
found outside of the innermost scope are read-only (an attempt to write to such
a variable will simply create a <em>new</em> local variable in the innermost scope,
leaving the identically named outer variable unchanged).</p>
<p>Usually, the local scope references the local names of the (textually) current
function.  Outside functions, the local scope references the same namespace as
the global scope: the module’s namespace. Class definitions place yet another
namespace in the local scope.</p>
<p>It is important to realize that scopes are determined textually: the global
scope of a function defined in a module is that module’s namespace, no matter
from where or by what alias the function is called.  On the other hand, the
actual search for names is done dynamically, at run time — however, the
language definition is evolving towards static name resolution, at “compile”
time, so don’t rely on dynamic name resolution!  (In fact, local variables are
already determined statically.)</p>
<p>A special quirk of Python is that – if no <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement is in
effect – assignments to names always go into the innermost scope.  Assignments
do not copy data — they just bind names to objects.  The same is true for
deletions: the statement <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> removes the binding of <code class="docutils literal notranslate"><span class="pre">x</span></code> from the
namespace referenced by the local scope.  In fact, all operations that introduce
new names use the local scope: in particular, <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements and
function definitions bind the module or function name in the local scope.  (The
<a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement can be used to indicate that particular variables
live in the global scope.)</p>
</div>
<div class="section" id="a-first-look-at-classes">
<span id="tut-firstclasses"></span><h2>9.3. A First Look at Classes<a class="headerlink" href="#a-first-look-at-classes" title="Permalink to this headline">¶</a></h2>
<p>Classes introduce a little bit of new syntax, three new object types, and some
new semantics.</p>
<div class="section" id="class-definition-syntax">
<span id="tut-classdefinition"></span><h3>9.3.1. Class Definition Syntax<a class="headerlink" href="#class-definition-syntax" title="Permalink to this headline">¶</a></h3>
<p>The simplest form of class definition looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">ClassName</span><span class="p">:</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>Class definitions, like function definitions (<a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> statements) must be
executed before they have any effect.  (You could conceivably place a class
definition in a branch of an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, or inside a function.)</p>
<p>In practice, the statements inside a class definition will usually be function
definitions, but other statements are allowed, and sometimes useful — we’ll
come back to this later.  The function definitions inside a class normally have
a peculiar form of argument list, dictated by the calling conventions for
methods — again, this is explained later.</p>
<p>When a class definition is entered, a new namespace is created, and used as the
local scope — thus, all assignments to local variables go into this new
namespace.  In particular, function definitions bind the name of the new
function here.</p>
<p>When a class definition is left normally (via the end), a <em>class object</em> is
created.  This is basically a wrapper around the contents of the namespace
created by the class definition; we’ll learn more about class objects in the
next section.  The original local scope (the one in effect just before the class
definition was entered) is reinstated, and the class object is bound here to the
class name given in the class definition header (<code class="xref py py-class docutils literal notranslate"><span class="pre">ClassName</span></code> in the
example).</p>
</div>
<div class="section" id="class-objects">
<span id="tut-classobjects"></span><h3>9.3.2. Class Objects<a class="headerlink" href="#class-objects" title="Permalink to this headline">¶</a></h3>
<p>Class objects support two kinds of operations: attribute references and
instantiation.</p>
<p><em>Attribute references</em> use the standard syntax used for all attribute references
in Python: <code class="docutils literal notranslate"><span class="pre">obj.name</span></code>.  Valid attribute names are all the names that were in
the class’s namespace when the class object was created.  So, if the class
definition looked like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">MyClass</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;A simple example class&quot;&quot;&quot;</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">12345</span>

    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>
</pre></div>
</div>
<p>then <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> and <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> are valid attribute references, returning
an integer and a function object, respectively. Class attributes can also be
assigned to, so you can change the value of <code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> by assignment.
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is also a valid attribute, returning the docstring belonging to
the class: <code class="docutils literal notranslate"><span class="pre">&quot;A</span> <span class="pre">simple</span> <span class="pre">example</span> <span class="pre">class&quot;</span></code>.</p>
<p>Class <em>instantiation</em> uses function notation.  Just pretend that the class
object is a parameterless function that returns a new instance of the class.
For example (assuming the above class):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
</pre></div>
</div>
<p>creates a new <em>instance</em> of the class and assigns this object to the local
variable <code class="docutils literal notranslate"><span class="pre">x</span></code>.</p>
<p>The instantiation operation (“calling” a class object) creates an empty object.
Many classes like to create objects with instances customized to a specific
initial state. Therefore a class may define a special method named
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>
</pre></div>
</div>
<p>When a class defines an <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, class instantiation
automatically invokes <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> for the newly-created class instance.  So
in this example, a new, initialized instance can be obtained by:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">MyClass</span><span class="p">()</span>
</pre></div>
</div>
<p>Of course, the <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method may have arguments for greater
flexibility.  In that case, arguments given to the class instantiation operator
are passed on to <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Complex</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">realpart</span><span class="p">,</span> <span class="n">imagpart</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">r</span> <span class="o">=</span> <span class="n">realpart</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">i</span> <span class="o">=</span> <span class="n">imagpart</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">Complex</span><span class="p">(</span><span class="mf">3.0</span><span class="p">,</span> <span class="o">-</span><span class="mf">4.5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">r</span><span class="p">,</span> <span class="n">x</span><span class="o">.</span><span class="n">i</span>
<span class="go">(3.0, -4.5)</span>
</pre></div>
</div>
</div>
<div class="section" id="instance-objects">
<span id="tut-instanceobjects"></span><h3>9.3.3. Instance Objects<a class="headerlink" href="#instance-objects" title="Permalink to this headline">¶</a></h3>
<p>Now what can we do with instance objects?  The only operations understood by
instance objects are attribute references.  There are two kinds of valid
attribute names, data attributes and methods.</p>
<p><em>data attributes</em> correspond to “instance variables” in Smalltalk, and to “data
members” in C++.  Data attributes need not be declared; like local variables,
they spring into existence when they are first assigned to.  For example, if
<code class="docutils literal notranslate"><span class="pre">x</span></code> is the instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> created above, the following piece of
code will print the value <code class="docutils literal notranslate"><span class="pre">16</span></code>, without leaving a trace:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">while</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">:</span>
    <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span> <span class="o">*</span> <span class="mi">2</span>
<span class="nb">print</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span>
<span class="k">del</span> <span class="n">x</span><span class="o">.</span><span class="n">counter</span>
</pre></div>
</div>
<p>The other kind of instance attribute reference is a <em>method</em>. A method is a
function that “belongs to” an object.  (In Python, the term method is not unique
to class instances: other object types can have methods as well.  For example,
list objects have methods called append, insert, remove, sort, and so on.
However, in the following discussion, we’ll use the term method exclusively to
mean methods of class instance objects, unless explicitly stated otherwise.)</p>
<p id="index-0">Valid method names of an instance object depend on its class.  By definition,
all attributes of a class that are function  objects define corresponding
methods of its instances.  So in our example, <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a valid method
reference, since <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> is a function, but <code class="docutils literal notranslate"><span class="pre">x.i</span></code> is not, since
<code class="docutils literal notranslate"><span class="pre">MyClass.i</span></code> is not.  But <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is not the same thing as <code class="docutils literal notranslate"><span class="pre">MyClass.f</span></code> — it
is a <em>method object</em>, not a function object.</p>
</div>
<div class="section" id="method-objects">
<span id="tut-methodobjects"></span><h3>9.3.4. Method Objects<a class="headerlink" href="#method-objects" title="Permalink to this headline">¶</a></h3>
<p>Usually, a method is called right after it is bound:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span><span class="o">.</span><span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">MyClass</span></code> example, this will return the string <code class="docutils literal notranslate"><span class="pre">'hello</span> <span class="pre">world'</span></code>.
However, it is not necessary to call a method right away: <code class="docutils literal notranslate"><span class="pre">x.f</span></code> is a method
object, and can be stored away and called at a later time.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">xf</span> <span class="o">=</span> <span class="n">x</span><span class="o">.</span><span class="n">f</span>
<span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">xf</span><span class="p">()</span>
</pre></div>
</div>
<p>will continue to print <code class="docutils literal notranslate"><span class="pre">hello</span> <span class="pre">world</span></code> until the end of time.</p>
<p>What exactly happens when a method is called?  You may have noticed that
<code class="docutils literal notranslate"><span class="pre">x.f()</span></code> was called without an argument above, even though the function
definition for <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code> specified an argument.  What happened to the argument?
Surely Python raises an exception when a function that requires an argument is
called without any — even if the argument isn’t actually used…</p>
<p>Actually, you may have guessed the answer: the special thing about methods is
that the object is passed as the first argument of the function.  In our
example, the call <code class="docutils literal notranslate"><span class="pre">x.f()</span></code> is exactly equivalent to <code class="docutils literal notranslate"><span class="pre">MyClass.f(x)</span></code>.  In
general, calling a method with a list of <em>n</em> arguments is equivalent to calling
the corresponding function with an argument list that is created by inserting
the method’s object before the first argument.</p>
<p>If you still don’t understand how methods work, a look at the implementation can
perhaps clarify matters.  When a non-data attribute of an instance is
referenced, the instance’s class is searched.  If the name denotes a valid class
attribute that is a function object, a method object is created by packing
(pointers to) the instance object and the function object just found together in
an abstract object: this is the method object.  When the method object is called
with an argument list, a new argument list is constructed from the instance
object and the argument list, and the function object is called with this new
argument list.</p>
</div>
<div class="section" id="class-and-instance-variables">
<span id="tut-class-and-instance-variables"></span><h3>9.3.5. Class and Instance Variables<a class="headerlink" href="#class-and-instance-variables" title="Permalink to this headline">¶</a></h3>
<p>Generally speaking, instance variables are for data unique to each instance
and class variables are for attributes and methods shared by all instances
of the class:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>

    <span class="n">kind</span> <span class="o">=</span> <span class="s1">&#39;canine&#39;</span>         <span class="c1"># class variable shared by all instances</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>    <span class="c1"># instance variable unique to each instance</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">kind</span>                  <span class="c1"># shared by all dogs</span>
<span class="s1">&#39;canine&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">kind</span>                  <span class="c1"># shared by all dogs</span>
<span class="s1">&#39;canine&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">name</span>                  <span class="c1"># unique to d</span>
<span class="s1">&#39;Fido&#39;</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">name</span>                  <span class="c1"># unique to e</span>
<span class="s1">&#39;Buddy&#39;</span>
</pre></div>
</div>
<p>As discussed in <a class="reference internal" href="#tut-object"><span class="std std-ref">A Word About Names and Objects</span></a>, shared data can have possibly surprising
effects with involving <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a> objects such as lists and dictionaries.
For example, the <em>tricks</em> list in the following code should not be used as a
class variable because just a single list would be shared by all <em>Dog</em>
instances:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>

    <span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span>             <span class="c1"># mistaken use of a class variable</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>

    <span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span>                <span class="c1"># unexpectedly shared by all dogs</span>
<span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">,</span> <span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>Correct design of the class should use an instance variable instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Dog</span><span class="p">:</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="n">name</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span> <span class="o">=</span> <span class="p">[]</span>    <span class="c1"># creates a new empty list for each dog</span>

    <span class="k">def</span> <span class="nf">add_trick</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">trick</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tricks</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">trick</span><span class="p">)</span>

<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Fido&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span> <span class="o">=</span> <span class="n">Dog</span><span class="p">(</span><span class="s1">&#39;Buddy&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;roll over&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">add_trick</span><span class="p">(</span><span class="s1">&#39;play dead&#39;</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">d</span><span class="o">.</span><span class="n">tricks</span>
<span class="p">[</span><span class="s1">&#39;roll over&#39;</span><span class="p">]</span>
<span class="o">&gt;&gt;&gt;</span> <span class="n">e</span><span class="o">.</span><span class="n">tricks</span>
<span class="p">[</span><span class="s1">&#39;play dead&#39;</span><span class="p">]</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="random-remarks">
<span id="tut-remarks"></span><h2>9.4. Random Remarks<a class="headerlink" href="#random-remarks" title="Permalink to this headline">¶</a></h2>
<p>Data attributes override method attributes with the same name; to avoid
accidental name conflicts, which may cause hard-to-find bugs in large programs,
it is wise to use some kind of convention that minimizes the chance of
conflicts.  Possible conventions include capitalizing method names, prefixing
data attribute names with a small unique string (perhaps just an underscore), or
using verbs for methods and nouns for data attributes.</p>
<p>Data attributes may be referenced by methods as well as by ordinary users
(“clients”) of an object.  In other words, classes are not usable to implement
pure abstract data types.  In fact, nothing in Python makes it possible to
enforce data hiding — it is all based upon convention.  (On the other hand,
the Python implementation, written in C, can completely hide implementation
details and control access to an object if necessary; this can be used by
extensions to Python written in C.)</p>
<p>Clients should use data attributes with care — clients may mess up invariants
maintained by the methods by stamping on their data attributes.  Note that
clients may add data attributes of their own to an instance object without
affecting the validity of the methods, as long as name conflicts are avoided —
again, a naming convention can save a lot of headaches here.</p>
<p>There is no shorthand for referencing data attributes (or other methods!) from
within methods.  I find that this actually increases the readability of methods:
there is no chance of confusing local variables and instance variables when
glancing through a method.</p>
<p>Often, the first argument of a method is called <code class="docutils literal notranslate"><span class="pre">self</span></code>.  This is nothing more
than a convention: the name <code class="docutils literal notranslate"><span class="pre">self</span></code> has absolutely no special meaning to
Python.  Note, however, that by not following the convention your code may be
less readable to other Python programmers, and it is also conceivable that a
<em>class browser</em> program might be written that relies upon such a convention.</p>
<p>Any function object that is a class attribute defines a method for instances of
that class.  It is not necessary that the function definition is textually
enclosed in the class definition: assigning a function object to a local
variable in the class is also ok.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Function defined outside the class</span>
<span class="k">def</span> <span class="nf">f1</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="k">return</span> <span class="nb">min</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="n">f</span> <span class="o">=</span> <span class="n">f1</span>

    <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="s1">&#39;hello world&#39;</span>

    <span class="n">h</span> <span class="o">=</span> <span class="n">g</span>
</pre></div>
</div>
<p>Now <code class="docutils literal notranslate"><span class="pre">f</span></code>, <code class="docutils literal notranslate"><span class="pre">g</span></code> and <code class="docutils literal notranslate"><span class="pre">h</span></code> are all attributes of class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> that refer to
function objects, and consequently they are all methods of instances of
<code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> — <code class="docutils literal notranslate"><span class="pre">h</span></code> being exactly equivalent to <code class="docutils literal notranslate"><span class="pre">g</span></code>.  Note that this practice
usually only serves to confuse the reader of a program.</p>
<p>Methods may call other methods by using method attributes of the <code class="docutils literal notranslate"><span class="pre">self</span></code>
argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Bag</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">addtwice</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
<p>Methods may reference global names in the same way as ordinary functions.  The
global scope associated with a method is the module containing its
definition.  (A class is never used as a global scope.)  While one
rarely encounters a good reason for using global data in a method, there are
many legitimate uses of the global scope: for one thing, functions and modules
imported into the global scope can be used by methods, as well as functions and
classes defined in it.  Usually, the class containing the method is itself
defined in this global scope, and in the next section we’ll find some good
reasons why a method would want to reference its own class.</p>
<p>Each value is an object, and therefore has a <em>class</em> (also called its <em>type</em>).
It is stored as <code class="docutils literal notranslate"><span class="pre">object.__class__</span></code>.</p>
</div>
<div class="section" id="inheritance">
<span id="tut-inheritance"></span><h2>9.5. Inheritance<a class="headerlink" href="#inheritance" title="Permalink to this headline">¶</a></h2>
<p>Of course, a language feature would not be worthy of the name “class” without
supporting inheritance.  The syntax for a derived class definition looks like
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">BaseClassName</span><span class="p">):</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>The name <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseClassName</span></code> must be defined in a scope containing the
derived class definition.  In place of a base class name, other arbitrary
expressions are also allowed.  This can be useful, for example, when the base
class is defined in another module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">modname</span><span class="o">.</span><span class="n">BaseClassName</span><span class="p">):</span>
</pre></div>
</div>
<p>Execution of a derived class definition proceeds the same as for a base class.
When the class object is constructed, the base class is remembered.  This is
used for resolving attribute references: if a requested attribute is not found
in the class, the search proceeds to look in the base class.  This rule is
applied recursively if the base class itself is derived from some other class.</p>
<p>There’s nothing special about instantiation of derived classes:
<code class="docutils literal notranslate"><span class="pre">DerivedClassName()</span></code> creates a new instance of the class.  Method references
are resolved as follows: the corresponding class attribute is searched,
descending down the chain of base classes if necessary, and the method reference
is valid if this yields a function object.</p>
<p>Derived classes may override methods of their base classes.  Because methods
have no special privileges when calling other methods of the same object, a
method of a base class that calls another method defined in the same base class
may end up calling a method of a derived class that overrides it.  (For C++
programmers: all methods in Python are effectively <code class="docutils literal notranslate"><span class="pre">virtual</span></code>.)</p>
<p>An overriding method in a derived class may in fact want to extend rather than
simply replace the base class method of the same name. There is a simple way to
call the base class method directly: just call <code class="docutils literal notranslate"><span class="pre">BaseClassName.methodname(self,</span>
<span class="pre">arguments)</span></code>.  This is occasionally useful to clients as well.  (Note that this
only works if the base class is accessible as <code class="docutils literal notranslate"><span class="pre">BaseClassName</span></code> in the global
scope.)</p>
<p>Python has two built-in functions that work with inheritance:</p>
<ul class="simple">
<li>Use <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> to check an instance’s type: <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">int)</span></code>
will be <code class="docutils literal notranslate"><span class="pre">True</span></code> only if <code class="docutils literal notranslate"><span class="pre">obj.__class__</span></code> is <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> or some class
derived from <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.</li>
<li>Use <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> to check class inheritance: <code class="docutils literal notranslate"><span class="pre">issubclass(bool,</span> <span class="pre">int)</span></code>
is <code class="docutils literal notranslate"><span class="pre">True</span></code> since <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> is a subclass of <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>.  However,
<code class="docutils literal notranslate"><span class="pre">issubclass(unicode,</span> <span class="pre">str)</span></code> is <code class="docutils literal notranslate"><span class="pre">False</span></code> since <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> is not a
subclass of <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> (they only share a common ancestor,
<a class="reference internal" href="../library/functions.html#basestring" title="basestring"><code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code></a>).</li>
</ul>
<div class="section" id="multiple-inheritance">
<span id="tut-multiple"></span><h3>9.5.1. Multiple Inheritance<a class="headerlink" href="#multiple-inheritance" title="Permalink to this headline">¶</a></h3>
<p>Python supports a limited form of multiple inheritance as well.  A class
definition with multiple base classes looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DerivedClassName</span><span class="p">(</span><span class="n">Base1</span><span class="p">,</span> <span class="n">Base2</span><span class="p">,</span> <span class="n">Base3</span><span class="p">):</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="mi">1</span><span class="o">&gt;</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">.</span>
    <span class="o">&lt;</span><span class="n">statement</span><span class="o">-</span><span class="n">N</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>For old-style classes, the only rule is depth-first, left-to-right.  Thus, if an
attribute is not found in <code class="xref py py-class docutils literal notranslate"><span class="pre">DerivedClassName</span></code>, it is searched in
<code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>, then (recursively) in the base classes of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>, and
only if it is not found there, it is searched in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base2</span></code>, and so on.</p>
<p>(To some people breadth first — searching <code class="xref py py-class docutils literal notranslate"><span class="pre">Base2</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Base3</span></code>
before the base classes of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code> — looks more natural.  However, this
would require you to know whether a particular attribute of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code> is
actually defined in <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code> or in one of its base classes before you can
figure out the consequences of a name conflict with an attribute of
<code class="xref py py-class docutils literal notranslate"><span class="pre">Base2</span></code>.  The depth-first rule makes no differences between direct and
inherited attributes of <code class="xref py py-class docutils literal notranslate"><span class="pre">Base1</span></code>.)</p>
<p>For <a class="reference internal" href="../glossary.html#term-new-style-class"><span class="xref std std-term">new-style class</span></a>es, the method resolution order changes dynamically
to support cooperative calls to <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>.  This approach is known in some
other multiple-inheritance languages as call-next-method and is more powerful
than the super call found in single-inheritance languages.</p>
<p>With new-style classes, dynamic ordering is necessary because all  cases of
multiple inheritance exhibit one or more diamond relationships (where at
least one of the parent classes can be accessed through multiple paths from the
bottommost class).  For example, all new-style classes inherit from
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, so any case of multiple inheritance provides more than one path
to reach <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>.  To keep the base classes from being accessed more
than once, the dynamic algorithm linearizes the search order in a way that
preserves the left-to-right ordering specified in each class, that calls each
parent only once, and that is monotonic (meaning that a class can be subclassed
without affecting the precedence order of its parents).  Taken together, these
properties make it possible to design reliable and extensible classes with
multiple inheritance.  For more detail, see
<a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
</div>
</div>
<div class="section" id="private-variables-and-class-local-references">
<span id="tut-private"></span><h2>9.6. Private Variables and Class-local References<a class="headerlink" href="#private-variables-and-class-local-references" title="Permalink to this headline">¶</a></h2>
<p>“Private” instance variables that cannot be accessed except from inside an
object don’t exist in Python.  However, there is a convention that is followed
by most Python code: a name prefixed with an underscore (e.g. <code class="docutils literal notranslate"><span class="pre">_spam</span></code>) should
be treated as a non-public part of the API (whether it is a function, a method
or a data member).  It should be considered an implementation detail and subject
to change without notice.</p>
<p id="index-1">Since there is a valid use-case for class-private members (namely to avoid name
clashes of names with names defined by subclasses), there is limited support for
such a mechanism, called <em class="dfn">name mangling</em>.  Any identifier of the form
<code class="docutils literal notranslate"><span class="pre">__spam</span></code> (at least two leading underscores, at most one trailing underscore)
is textually replaced with <code class="docutils literal notranslate"><span class="pre">_classname__spam</span></code>, where <code class="docutils literal notranslate"><span class="pre">classname</span></code> is the
current class name with leading underscore(s) stripped.  This mangling is done
without regard to the syntactic position of the identifier, as long as it
occurs within the definition of a class.</p>
<p>Name mangling is helpful for letting subclasses override methods without
breaking intraclass method calls.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Mapping</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span> <span class="o">=</span> <span class="p">[]</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">__update</span><span class="p">(</span><span class="n">iterable</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">iterable</span><span class="p">):</span>
        <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">iterable</span><span class="p">:</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>

    <span class="n">__update</span> <span class="o">=</span> <span class="n">update</span>   <span class="c1"># private copy of original update() method</span>

<span class="k">class</span> <span class="nc">MappingSubclass</span><span class="p">(</span><span class="n">Mapping</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">update</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
        <span class="c1"># provides new signature for update()</span>
        <span class="c1"># but does not break __init__()</span>
        <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">keys</span><span class="p">,</span> <span class="n">values</span><span class="p">):</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">items_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
</pre></div>
</div>
<p>The above example would work even if <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code> were to introduce a
<code class="docutils literal notranslate"><span class="pre">__update</span></code> identifier since it is replaced with <code class="docutils literal notranslate"><span class="pre">_Mapping__update</span></code> in the
<code class="docutils literal notranslate"><span class="pre">Mapping</span></code> class  and <code class="docutils literal notranslate"><span class="pre">_MappingSubclass__update</span></code> in the <code class="docutils literal notranslate"><span class="pre">MappingSubclass</span></code>
class respectively.</p>
<p>Note that the mangling rules are designed mostly to avoid accidents; it still is
possible to access or modify a variable that is considered private.  This can
even be useful in special circumstances, such as in the debugger.</p>
<p>Notice that code passed to <code class="docutils literal notranslate"><span class="pre">exec</span></code>, <code class="docutils literal notranslate"><span class="pre">eval()</span></code> or <code class="docutils literal notranslate"><span class="pre">execfile()</span></code> does not
consider the classname of the invoking  class to be the current class; this is
similar to the effect of the  <code class="docutils literal notranslate"><span class="pre">global</span></code> statement, the effect of which is
likewise restricted to  code that is byte-compiled together.  The same
restriction applies to <code class="docutils literal notranslate"><span class="pre">getattr()</span></code>, <code class="docutils literal notranslate"><span class="pre">setattr()</span></code> and <code class="docutils literal notranslate"><span class="pre">delattr()</span></code>, as well
as when referencing <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> directly.</p>
</div>
<div class="section" id="odds-and-ends">
<span id="tut-odds"></span><h2>9.7. Odds and Ends<a class="headerlink" href="#odds-and-ends" title="Permalink to this headline">¶</a></h2>
<p>Sometimes it is useful to have a data type similar to the Pascal “record” or C
“struct”, bundling together a few named data items.  An empty class definition
will do nicely:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Employee</span><span class="p">:</span>
    <span class="k">pass</span>

<span class="n">john</span> <span class="o">=</span> <span class="n">Employee</span><span class="p">()</span>  <span class="c1"># Create an empty employee record</span>

<span class="c1"># Fill the fields of the record</span>
<span class="n">john</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;John Doe&#39;</span>
<span class="n">john</span><span class="o">.</span><span class="n">dept</span> <span class="o">=</span> <span class="s1">&#39;computer lab&#39;</span>
<span class="n">john</span><span class="o">.</span><span class="n">salary</span> <span class="o">=</span> <span class="mi">1000</span>
</pre></div>
</div>
<p>A piece of Python code that expects a particular abstract data type can often be
passed a class that emulates the methods of that data type instead.  For
instance, if you have a function that formats some data from a file object, you
can define a class with methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> that get the
data from a string buffer instead, and pass it as an argument.</p>
<p>Instance method objects have attributes, too: <code class="docutils literal notranslate"><span class="pre">m.im_self</span></code> is the instance
object with the method <code class="xref py py-meth docutils literal notranslate"><span class="pre">m()</span></code>, and <code class="docutils literal notranslate"><span class="pre">m.im_func</span></code> is the function object
corresponding to the method.</p>
</div>
<div class="section" id="exceptions-are-classes-too">
<span id="tut-exceptionclasses"></span><h2>9.8. Exceptions Are Classes Too<a class="headerlink" href="#exceptions-are-classes-too" title="Permalink to this headline">¶</a></h2>
<p>User-defined exceptions are identified by classes as well.  Using this mechanism
it is possible to create extensible hierarchies of exceptions.</p>
<p>There are two new valid (semantic) forms for the <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="n">Class</span><span class="p">,</span> <span class="n">instance</span>

<span class="k">raise</span> <span class="n">instance</span>
</pre></div>
</div>
<p>In the first form, <code class="docutils literal notranslate"><span class="pre">instance</span></code> must be an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">Class</span></code> or of a
class derived from it.  The second form is a shorthand for:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="n">instance</span><span class="o">.</span><span class="vm">__class__</span><span class="p">,</span> <span class="n">instance</span>
</pre></div>
</div>
<p>A class in an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause is compatible with an exception if it is
the same class or a base class thereof (but not the other way around — an
except clause listing a derived class is not compatible with a base class).  For
example, the following code will print B, C, D in that order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">B</span><span class="p">:</span>
    <span class="k">pass</span>
<span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
    <span class="k">pass</span>
<span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
    <span class="k">pass</span>

<span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="p">[</span><span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">D</span><span class="p">]:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">c</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">D</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;D&quot;</span>
    <span class="k">except</span> <span class="n">C</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;C&quot;</span>
    <span class="k">except</span> <span class="n">B</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s2">&quot;B&quot;</span>
</pre></div>
</div>
<p>Note that if the except clauses were reversed (with <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">B</span></code> first), it
would have printed B, B, B — the first matching except clause is triggered.</p>
<p>When an error message is printed for an unhandled exception, the exception’s
class name is printed, then a colon and a space, and finally the instance
converted to a string using the built-in function <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.</p>
</div>
<div class="section" id="iterators">
<span id="tut-iterators"></span><h2>9.9. Iterators<a class="headerlink" href="#iterators" title="Permalink to this headline">¶</a></h2>
<p>By now you have probably noticed that most container objects can be looped over
using a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]:</span>
    <span class="nb">print</span> <span class="n">element</span>
<span class="k">for</span> <span class="n">element</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">element</span>
<span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="p">{</span><span class="s1">&#39;one&#39;</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">}:</span>
    <span class="nb">print</span> <span class="n">key</span>
<span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="s2">&quot;123&quot;</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">char</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">line</span><span class="p">,</span>
</pre></div>
</div>
<p>This style of access is clear, concise, and convenient.  The use of iterators
pervades and unifies Python.  Behind the scenes, the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement
calls <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on the container object.  The function returns an iterator
object that defines the method <a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> which accesses elements
in the container one at a time.  When there are no more elements,
<a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> raises a <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception which tells the
<a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop to terminate.
This example shows how it all works:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span>
<span class="go">&lt;iterator object at 0x00A1DB50&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">&#39;a&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">&#39;b&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">&#39;c&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
    <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>Having seen the mechanics behind the iterator protocol, it is easy to add
iterator behavior to your classes.  Define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method which
returns an object with a <a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method.  If the class
defines <a class="reference internal" href="../library/stdtypes.html#iterator.next" title="iterator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a>, then <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> can just return <code class="docutils literal notranslate"><span class="pre">self</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reverse</span><span class="p">:</span>
    <span class="sd">&quot;&quot;&quot;Iterator for looping over a sequence backwards.&quot;&quot;&quot;</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">data</span> <span class="o">=</span> <span class="n">data</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span>

    <span class="k">def</span> <span class="nf">next</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">StopIteration</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">index</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">index</span><span class="p">]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">rev</span> <span class="o">=</span> <span class="n">Reverse</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">iter</span><span class="p">(</span><span class="n">rev</span><span class="p">)</span>
<span class="go">&lt;__main__.Reverse object at 0x00A1DB50&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">rev</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">char</span>
<span class="gp">...</span>
<span class="go">m</span>
<span class="go">a</span>
<span class="go">p</span>
<span class="go">s</span>
</pre></div>
</div>
</div>
<div class="section" id="generators">
<span id="tut-generators"></span><h2>9.10. Generators<a class="headerlink" href="#generators" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">Generator</span></a>s are a simple and powerful tool for creating iterators.  They
are written like regular functions but use the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement
whenever they want to return data.  Each time <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-func docutils literal notranslate"><span class="pre">next()</span></code></a> is called on it, the
generator resumes where it left off (it remembers all the data values and which
statement was last executed).  An example shows that generators can be trivially
easy to create:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="n">data</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">index</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">data</span><span class="p">[</span><span class="n">index</span><span class="p">]</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">char</span> <span class="ow">in</span> <span class="n">reverse</span><span class="p">(</span><span class="s1">&#39;golf&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">char</span>
<span class="gp">...</span>
<span class="go">f</span>
<span class="go">l</span>
<span class="go">o</span>
<span class="go">g</span>
</pre></div>
</div>
<p>Anything that can be done with generators can also be done with class-based
iterators as described in the previous section.  What makes generators so
compact is that the <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> and <a class="reference internal" href="../reference/expressions.html#generator.next" title="generator.next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> methods
are created automatically.</p>
<p>Another key feature is that the local variables and execution state are
automatically saved between calls.  This made the function easier to write and
much more clear than an approach using instance variables like <code class="docutils literal notranslate"><span class="pre">self.index</span></code>
and <code class="docutils literal notranslate"><span class="pre">self.data</span></code>.</p>
<p>In addition to automatic method creation and saving program state, when
generators terminate, they automatically raise <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>. In
combination, these features make it easy to create iterators with no more effort
than writing a regular function.</p>
</div>
<div class="section" id="generator-expressions">
<span id="tut-genexps"></span><h2>9.11. Generator Expressions<a class="headerlink" href="#generator-expressions" title="Permalink to this headline">¶</a></h2>
<p>Some simple generators can be coded succinctly as expressions using a syntax
similar to list comprehensions but with parentheses instead of square brackets.
These expressions are designed for situations where the generator is used right
away by an enclosing function.  Generator expressions are more compact but less
versatile than full generator definitions and tend to be more memory friendly
than equivalent list comprehensions.</p>
<p>Examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">i</span><span class="o">*</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">))</span>                 <span class="c1"># sum of squares</span>
<span class="go">285</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">xvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">10</span><span class="p">,</span> <span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">yvec</span> <span class="o">=</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">xvec</span><span class="p">,</span> <span class="n">yvec</span><span class="p">))</span>         <span class="c1"># dot product</span>
<span class="go">260</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">pi</span><span class="p">,</span> <span class="n">sin</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sine_table</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">sin</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">pi</span><span class="o">/</span><span class="mi">180</span><span class="p">))</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">91</span><span class="p">))</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">unique_words</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">word</span>  <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">page</span>  <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">line</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">valedictorian</span> <span class="o">=</span> <span class="nb">max</span><span class="p">((</span><span class="n">student</span><span class="o">.</span><span class="n">gpa</span><span class="p">,</span> <span class="n">student</span><span class="o">.</span><span class="n">name</span><span class="p">)</span> <span class="k">for</span> <span class="n">student</span> <span class="ow">in</span> <span class="n">graduates</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="s1">&#39;golf&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">data</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">data</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">))</span>
<span class="go">[&#39;f&#39;, &#39;l&#39;, &#39;o&#39;, &#39;g&#39;]</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Except for one thing.  Module objects have a secret read-only attribute called
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> which returns the dictionary used to implement the module’s
namespace; the name <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is an attribute but not a global name.
Obviously, using this violates the abstraction of namespace implementation, and
should be restricted to things like post-mortem debuggers.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">9. Classes</a><ul>
<li><a class="reference internal" href="#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
<li><a class="reference internal" href="#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a></li>
<li><a class="reference internal" href="#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
<li><a class="reference internal" href="#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
<li><a class="reference internal" href="#class-objects">9.3.2. Class Objects</a></li>
<li><a class="reference internal" href="#instance-objects">9.3.3. Instance Objects</a></li>
<li><a class="reference internal" href="#method-objects">9.3.4. Method Objects</a></li>
<li><a class="reference internal" href="#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
</ul>
</li>
<li><a class="reference internal" href="#random-remarks">9.4. Random Remarks</a></li>
<li><a class="reference internal" href="#inheritance">9.5. Inheritance</a><ul>
<li><a class="reference internal" href="#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
</ul>
</li>
<li><a class="reference internal" href="#private-variables-and-class-local-references">9.6. Private Variables and Class-local References</a></li>
<li><a class="reference internal" href="#odds-and-ends">9.7. Odds and Ends</a></li>
<li><a class="reference internal" href="#exceptions-are-classes-too">9.8. Exceptions Are Classes Too</a></li>
<li><a class="reference internal" href="#iterators">9.9. Iterators</a></li>
<li><a class="reference internal" href="#generators">9.10. Generators</a></li>
<li><a class="reference internal" href="#generator-expressions">9.11. Generator Expressions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="errors.html"
                        title="previous chapter">8. Errors and Exceptions</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stdlib.html"
                        title="next chapter">10. Brief Tour of the Standard Library</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/classes.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
             >next</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�.��$�$html/tutorial/controlflow.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. More Control Flow Tools &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="5. Data Structures" href="datastructures.html" />
    <link rel="prev" title="3. An Informal Introduction to Python" href="introduction.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/controlflow.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="more-control-flow-tools">
<span id="tut-morecontrol"></span><h1>4. More Control Flow Tools<a class="headerlink" href="#more-control-flow-tools" title="Permalink to this headline">¶</a></h1>
<p>Besides the <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> statement just introduced, Python knows the usual
control flow statements known from other languages, with some twists.</p>
<div class="section" id="if-statements">
<span id="tut-if"></span><h2>4.1. <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> Statements<a class="headerlink" href="#if-statements" title="Permalink to this headline">¶</a></h2>
<p>Perhaps the most well-known statement type is the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;Please enter an integer: &quot;</span><span class="p">))</span>
<span class="go">Please enter an integer: 42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">x</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Negative changed to zero&#39;</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Zero&#39;</span>
<span class="gp">... </span><span class="k">elif</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Single&#39;</span>
<span class="gp">... </span><span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;More&#39;</span>
<span class="gp">...</span>
<span class="go">More</span>
</pre></div>
</div>
<p>There can be zero or more <a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> parts, and the <a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> part is
optional.  The keyword ‘<a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a>’ is short for ‘else if’, and is useful
to avoid excessive indentation.  An  <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> …
<a class="reference internal" href="../reference/compound_stmts.html#elif"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">elif</span></code></a> … sequence is a substitute for the <code class="docutils literal notranslate"><span class="pre">switch</span></code> or
<code class="docutils literal notranslate"><span class="pre">case</span></code> statements found in other languages.</p>
</div>
<div class="section" id="for-statements">
<span id="tut-for"></span><h2>4.2. <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> Statements<a class="headerlink" href="#for-statements" title="Permalink to this headline">¶</a></h2>
<p id="index-0">The <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement in Python differs a bit from what you may be used
to in C or Pascal.  Rather than always iterating over an arithmetic progression
of numbers (like in Pascal), or giving the user the ability to define both the
iteration step and halting condition (as C), Python’s <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement
iterates over the items of any sequence (a list or a string), in the order that
they appear in the sequence.  For example (no pun intended):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Measure some strings:</span>
<span class="gp">... </span><span class="n">words</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;cat&#39;</span><span class="p">,</span> <span class="s1">&#39;window&#39;</span><span class="p">,</span> <span class="s1">&#39;defenestrate&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">w</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">cat 3</span>
<span class="go">window 6</span>
<span class="go">defenestrate 12</span>
</pre></div>
</div>
<p>If you need to modify the sequence you are iterating over while inside the loop
(for example to duplicate selected items), it is recommended that you first
make a copy.  Iterating over a sequence does not implicitly make a copy.  The
slice notation makes this especially convenient:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">[:]:</span>  <span class="c1"># Loop over a slice copy of the entire list.</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">w</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">6</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">words</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">w</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">words</span>
<span class="go">[&#39;defenestrate&#39;, &#39;cat&#39;, &#39;window&#39;, &#39;defenestrate&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="the-range-function">
<span id="tut-range"></span><h2>4.3. The <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> Function<a class="headerlink" href="#the-range-function" title="Permalink to this headline">¶</a></h2>
<p>If you do need to iterate over a sequence of numbers, the built-in function
<a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> comes in handy.  It generates lists containing arithmetic
progressions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="go">[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<p>The given end point is never part of the generated list; <code class="docutils literal notranslate"><span class="pre">range(10)</span></code> generates
a list of 10 values, the legal indices for items of a sequence of length 10.  It
is possible to let the range start at another number, or to specify a different
increment (even negative; sometimes this is called the ‘step’):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="go">[5, 6, 7, 8, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">[0, 3, 6, 9]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="o">-</span><span class="mi">10</span><span class="p">,</span> <span class="o">-</span><span class="mi">100</span><span class="p">,</span> <span class="o">-</span><span class="mi">30</span><span class="p">)</span>
<span class="go">[-10, -40, -70]</span>
</pre></div>
</div>
<p>To iterate over the indices of a sequence, you can combine <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> and
<a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Mary&#39;</span><span class="p">,</span> <span class="s1">&#39;had&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;little&#39;</span><span class="p">,</span> <span class="s1">&#39;lamb&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">a</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">i</span><span class="p">,</span> <span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">0 Mary</span>
<span class="go">1 had</span>
<span class="go">2 a</span>
<span class="go">3 little</span>
<span class="go">4 lamb</span>
</pre></div>
</div>
<p>In most such cases, however, it is convenient to use the <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>
function, see <a class="reference internal" href="datastructures.html#tut-loopidioms"><span class="std std-ref">Looping Techniques</span></a>.</p>
</div>
<div class="section" id="break-and-continue-statements-and-else-clauses-on-loops">
<span id="tut-break"></span><h2>4.4. <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> and <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> Statements, and <a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> Clauses on Loops<a class="headerlink" href="#break-and-continue-statements-and-else-clauses-on-loops" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement, like in C, breaks out of the innermost enclosing
<a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop.</p>
<p>Loop statements may have an <code class="docutils literal notranslate"><span class="pre">else</span></code> clause; it is executed when the loop
terminates through exhaustion of the list (with <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>) or when the
condition becomes false (with <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a>), but not when the loop is
terminated by a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a> statement.  This is exemplified by the
following loop, which searches for prime numbers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">n</span> <span class="o">%</span> <span class="n">x</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>            <span class="nb">print</span> <span class="n">n</span><span class="p">,</span> <span class="s1">&#39;equals&#39;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">n</span><span class="o">/</span><span class="n">x</span>
<span class="gp">... </span>            <span class="k">break</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>        <span class="c1"># loop fell through without finding a factor</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="n">n</span><span class="p">,</span> <span class="s1">&#39;is a prime number&#39;</span>
<span class="gp">...</span>
<span class="go">2 is a prime number</span>
<span class="go">3 is a prime number</span>
<span class="go">4 equals 2 * 2</span>
<span class="go">5 is a prime number</span>
<span class="go">6 equals 2 * 3</span>
<span class="go">7 is a prime number</span>
<span class="go">8 equals 2 * 4</span>
<span class="go">9 equals 3 * 3</span>
</pre></div>
</div>
<p>(Yes, this is the correct code.  Look closely: the <code class="docutils literal notranslate"><span class="pre">else</span></code> clause belongs to
the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop, <strong>not</strong> the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement.)</p>
<p>When used with a loop, the <code class="docutils literal notranslate"><span class="pre">else</span></code> clause has more in common with the
<code class="docutils literal notranslate"><span class="pre">else</span></code> clause of a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement than it does that of
<a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements: a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement’s <code class="docutils literal notranslate"><span class="pre">else</span></code> clause runs
when no exception occurs, and a loop’s <code class="docutils literal notranslate"><span class="pre">else</span></code> clause runs when no <code class="docutils literal notranslate"><span class="pre">break</span></code>
occurs. For more on the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement and exceptions, see
<a class="reference internal" href="errors.html#tut-handling"><span class="std std-ref">Handling Exceptions</span></a>.</p>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> statement, also borrowed from C, continues with the next
iteration of the loop:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">num</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;Found an even number&quot;</span><span class="p">,</span> <span class="n">num</span>
<span class="gp">... </span>        <span class="k">continue</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;Found a number&quot;</span><span class="p">,</span> <span class="n">num</span>
<span class="go">Found an even number 2</span>
<span class="go">Found a number 3</span>
<span class="go">Found an even number 4</span>
<span class="go">Found a number 5</span>
<span class="go">Found an even number 6</span>
<span class="go">Found a number 7</span>
<span class="go">Found an even number 8</span>
<span class="go">Found a number 9</span>
</pre></div>
</div>
</div>
<div class="section" id="pass-statements">
<span id="tut-pass"></span><h2>4.5. <a class="reference internal" href="../reference/simple_stmts.html#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> Statements<a class="headerlink" href="#pass-statements" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> statement does nothing. It can be used when a statement is
required syntactically but the program requires no action. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>  <span class="c1"># Busy-wait for keyboard interrupt (Ctrl+C)</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>This is commonly used for creating minimal classes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyEmptyClass</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>Another place <a class="reference internal" href="../reference/simple_stmts.html#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> can be used is as a place-holder for a function or
conditional body when you are working on new code, allowing you to keep thinking
at a more abstract level.  The <a class="reference internal" href="../reference/simple_stmts.html#pass"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code></a> is silently ignored:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">initlog</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>   <span class="c1"># Remember to implement this!</span>
<span class="gp">...</span>
</pre></div>
</div>
</div>
<div class="section" id="defining-functions">
<span id="tut-functions"></span><h2>4.6. Defining Functions<a class="headerlink" href="#defining-functions" title="Permalink to this headline">¶</a></h2>
<p>We can create a function that writes the Fibonacci series to an arbitrary
boundary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>    <span class="c1"># write Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Print a Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="n">a</span><span class="p">,</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Now call the function we just defined:</span>
<span class="gp">... </span><span class="n">fib</span><span class="p">(</span><span class="mi">2000</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597</span>
</pre></div>
</div>
<p id="index-1">The keyword <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> introduces a function <em>definition</em>.  It must be
followed by the function name and the parenthesized list of formal parameters.
The statements that form the body of the function start at the next line, and
must be indented.</p>
<p>The first statement of the function body can optionally be a string literal;
this string literal is the function’s documentation string, or <em class="dfn">docstring</em>.
(More about docstrings can be found in the section <a class="reference internal" href="#tut-docstrings"><span class="std std-ref">Documentation Strings</span></a>.)
There are tools which use docstrings to automatically produce online or printed
documentation, or to let the user interactively browse through code; it’s good
practice to include docstrings in code that you write, so make a habit of it.</p>
<p>The <em>execution</em> of a function introduces a new symbol table used for the local
variables of the function.  More precisely, all variable assignments in a
function store the value in the local symbol table; whereas variable references
first look in the local symbol table, then in the local symbol tables of
enclosing functions, then in the global symbol table, and finally in the table
of built-in names. Thus, global variables cannot be directly assigned a value
within a function (unless named in a <a class="reference internal" href="../reference/simple_stmts.html#global"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">global</span></code></a> statement), although they
may be referenced.</p>
<p>The actual parameters (arguments) to a function call are introduced in the local
symbol table of the called function when it is called; thus, arguments are
passed using <em>call by value</em> (where the <em>value</em> is always an object <em>reference</em>,
not the value of the object). <a class="footnote-reference" href="#id2" id="id1">[1]</a> When a function calls another function, a new
local symbol table is created for that call.</p>
<p>A function definition introduces the function name in the current symbol table.
The value of the function name has a type that is recognized by the interpreter
as a user-defined function.  This value can be assigned to another name which
can then also be used as a function.  This serves as a general renaming
mechanism:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span>
<span class="go">&lt;function fib at 10042ed0&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89</span>
</pre></div>
</div>
<p>Coming from other languages, you might object that <code class="docutils literal notranslate"><span class="pre">fib</span></code> is not a function but
a procedure since it doesn’t return a value.  In fact, even functions without a
<a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement do return a value, albeit a rather boring one.  This
value is called <code class="docutils literal notranslate"><span class="pre">None</span></code> (it’s a built-in name).  Writing the value <code class="docutils literal notranslate"><span class="pre">None</span></code> is
normally suppressed by the interpreter if it would be the only value written.
You can see it if you really want to using <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">fib</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">None</span>
</pre></div>
</div>
<p>It is simple to write a function that returns a list of the numbers of the
Fibonacci series, instead of printing it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">fib2</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>  <span class="c1"># return Fibonacci series up to n</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Return a list containing the Fibonacci series up to n.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">... </span>    <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>    <span class="c1"># see below</span>
<span class="gp">... </span>        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">result</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span> <span class="o">=</span> <span class="n">fib2</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>    <span class="c1"># call it</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f100</span>                <span class="c1"># write the result</span>
<span class="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
</pre></div>
</div>
<p>This example, as usual, demonstrates some new Python features:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement returns with a value from a function.
<a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> without an expression argument returns <code class="docutils literal notranslate"><span class="pre">None</span></code>. Falling off
the end of a function also returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
<li>The statement <code class="docutils literal notranslate"><span class="pre">result.append(a)</span></code> calls a <em>method</em> of the list object
<code class="docutils literal notranslate"><span class="pre">result</span></code>.  A method is a function that ‘belongs’ to an object and is named
<code class="docutils literal notranslate"><span class="pre">obj.methodname</span></code>, where <code class="docutils literal notranslate"><span class="pre">obj</span></code> is some object (this may be an expression),
and <code class="docutils literal notranslate"><span class="pre">methodname</span></code> is the name of a method that is defined by the object’s type.
Different types define different methods.  Methods of different types may have
the same name without causing ambiguity.  (It is possible to define your own
object types and methods, using <em>classes</em>, see <a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a>)
The method <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> shown in the example is defined for list objects; it
adds a new element at the end of the list.  In this example it is equivalent to
<code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">result</span> <span class="pre">+</span> <span class="pre">[a]</span></code>, but more efficient.</li>
</ul>
</div>
<div class="section" id="more-on-defining-functions">
<span id="tut-defining"></span><h2>4.7. More on Defining Functions<a class="headerlink" href="#more-on-defining-functions" title="Permalink to this headline">¶</a></h2>
<p>It is also possible to define functions with a variable number of arguments.
There are three forms, which can be combined.</p>
<div class="section" id="default-argument-values">
<span id="tut-defaultargs"></span><h3>4.7.1. Default Argument Values<a class="headerlink" href="#default-argument-values" title="Permalink to this headline">¶</a></h3>
<p>The most useful form is to specify a default value for one or more arguments.
This creates a function that can be called with fewer arguments than it is
defined to allow.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">ask_ok</span><span class="p">(</span><span class="n">prompt</span><span class="p">,</span> <span class="n">retries</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">complaint</span><span class="o">=</span><span class="s1">&#39;Yes or no, please!&#39;</span><span class="p">):</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="n">ok</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="n">prompt</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;y&#39;</span><span class="p">,</span> <span class="s1">&#39;ye&#39;</span><span class="p">,</span> <span class="s1">&#39;yes&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="kc">True</span>
        <span class="k">if</span> <span class="n">ok</span> <span class="ow">in</span> <span class="p">(</span><span class="s1">&#39;n&#39;</span><span class="p">,</span> <span class="s1">&#39;no&#39;</span><span class="p">,</span> <span class="s1">&#39;nop&#39;</span><span class="p">,</span> <span class="s1">&#39;nope&#39;</span><span class="p">):</span>
            <span class="k">return</span> <span class="kc">False</span>
        <span class="n">retries</span> <span class="o">=</span> <span class="n">retries</span> <span class="o">-</span> <span class="mi">1</span>
        <span class="k">if</span> <span class="n">retries</span> <span class="o">&lt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="k">raise</span> <span class="ne">IOError</span><span class="p">(</span><span class="s1">&#39;refusenik user&#39;</span><span class="p">)</span>
        <span class="nb">print</span> <span class="n">complaint</span>
</pre></div>
</div>
<p>This function can be called in several ways:</p>
<ul class="simple">
<li>giving only the mandatory argument:
<code class="docutils literal notranslate"><span class="pre">ask_ok('Do</span> <span class="pre">you</span> <span class="pre">really</span> <span class="pre">want</span> <span class="pre">to</span> <span class="pre">quit?')</span></code></li>
<li>giving one of the optional arguments:
<code class="docutils literal notranslate"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2)</span></code></li>
<li>or even giving all arguments:
<code class="docutils literal notranslate"><span class="pre">ask_ok('OK</span> <span class="pre">to</span> <span class="pre">overwrite</span> <span class="pre">the</span> <span class="pre">file?',</span> <span class="pre">2,</span> <span class="pre">'Come</span> <span class="pre">on,</span> <span class="pre">only</span> <span class="pre">yes</span> <span class="pre">or</span> <span class="pre">no!')</span></code></li>
</ul>
<p>This example also introduces the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> keyword. This tests whether or
not a sequence contains a certain value.</p>
<p>The default values are evaluated at the point of function definition in the
<em>defining</em> scope, so that</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">i</span> <span class="o">=</span> <span class="mi">5</span>

<span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg</span><span class="o">=</span><span class="n">i</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">arg</span>

<span class="n">i</span> <span class="o">=</span> <span class="mi">6</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>will print <code class="docutils literal notranslate"><span class="pre">5</span></code>.</p>
<p><strong>Important warning:</strong>  The default value is evaluated only once. This makes a
difference when the default is a mutable object such as a list, dictionary, or
instances of most classes.  For example, the following function accumulates the
arguments passed to it on subsequent calls:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="p">[]):</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>

<span class="nb">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">f</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
</pre></div>
</div>
<p>This will print</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">]</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
</pre></div>
</div>
<p>If you don’t want the default to be shared between subsequent calls, you can
write the function like this instead:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">L</span><span class="o">=</span><span class="kc">None</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">L</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">L</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>
</pre></div>
</div>
</div>
<div class="section" id="keyword-arguments">
<span id="tut-keywordargs"></span><h3>4.7.2. Keyword Arguments<a class="headerlink" href="#keyword-arguments" title="Permalink to this headline">¶</a></h3>
<p>Functions can also be called using <a class="reference internal" href="../glossary.html#term-keyword-argument"><span class="xref std std-term">keyword arguments</span></a>
of the form <code class="docutils literal notranslate"><span class="pre">kwarg=value</span></code>.  For instance, the following function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s1">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;voom&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;Norwegian Blue&#39;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span>
    <span class="nb">print</span> <span class="s2">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s2">&quot;volts through it.&quot;</span>
    <span class="nb">print</span> <span class="s2">&quot;-- Lovely plumage, the&quot;</span><span class="p">,</span> <span class="nb">type</span>
    <span class="nb">print</span> <span class="s2">&quot;-- It&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s2">&quot;!&quot;</span>
</pre></div>
</div>
<p>accepts one required argument (<code class="docutils literal notranslate"><span class="pre">voltage</span></code>) and three optional arguments
(<code class="docutils literal notranslate"><span class="pre">state</span></code>, <code class="docutils literal notranslate"><span class="pre">action</span></code>, and <code class="docutils literal notranslate"><span class="pre">type</span></code>).  This function can be called in any
of the following ways:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parrot</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>                                          <span class="c1"># 1 positional argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mi">1000</span><span class="p">)</span>                                  <span class="c1"># 1 keyword argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mi">1000000</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;VOOOOOM&#39;</span><span class="p">)</span>             <span class="c1"># 2 keyword arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">action</span><span class="o">=</span><span class="s1">&#39;VOOOOOM&#39;</span><span class="p">,</span> <span class="n">voltage</span><span class="o">=</span><span class="mi">1000000</span><span class="p">)</span>             <span class="c1"># 2 keyword arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="s1">&#39;a million&#39;</span><span class="p">,</span> <span class="s1">&#39;bereft of life&#39;</span><span class="p">,</span> <span class="s1">&#39;jump&#39;</span><span class="p">)</span>         <span class="c1"># 3 positional arguments</span>
<span class="n">parrot</span><span class="p">(</span><span class="s1">&#39;a thousand&#39;</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s1">&#39;pushing up the daisies&#39;</span><span class="p">)</span>  <span class="c1"># 1 positional, 1 keyword</span>
</pre></div>
</div>
<p>but all the following calls would be invalid:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">parrot</span><span class="p">()</span>                     <span class="c1"># required argument missing</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="o">=</span><span class="mf">5.0</span><span class="p">,</span> <span class="s1">&#39;dead&#39;</span><span class="p">)</span>  <span class="c1"># non-keyword argument after a keyword argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="mi">110</span><span class="p">,</span> <span class="n">voltage</span><span class="o">=</span><span class="mi">220</span><span class="p">)</span>     <span class="c1"># duplicate value for the same argument</span>
<span class="n">parrot</span><span class="p">(</span><span class="n">actor</span><span class="o">=</span><span class="s1">&#39;John Cleese&#39;</span><span class="p">)</span>  <span class="c1"># unknown keyword argument</span>
</pre></div>
</div>
<p>In a function call, keyword arguments must follow positional arguments.
All the keyword arguments passed must match one of the arguments
accepted by the function (e.g. <code class="docutils literal notranslate"><span class="pre">actor</span></code> is not a valid argument for the
<code class="docutils literal notranslate"><span class="pre">parrot</span></code> function), and their order is not important.  This also includes
non-optional arguments (e.g. <code class="docutils literal notranslate"><span class="pre">parrot(voltage=1000)</span></code> is valid too).
No argument may receive a value more than once.
Here’s an example that fails due to this restriction:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">function</span><span class="p">(</span><span class="n">a</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">function</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">function() got multiple values for keyword argument &#39;a&#39;</span>
</pre></div>
</div>
<p>When a final formal parameter of the form <code class="docutils literal notranslate"><span class="pre">**name</span></code> is present, it receives a
dictionary (see <a class="reference internal" href="../library/stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a>) containing all keyword arguments except for
those corresponding to a formal parameter.  This may be combined with a formal
parameter of the form <code class="docutils literal notranslate"><span class="pre">*name</span></code> (described in the next subsection) which
receives a tuple containing the positional arguments beyond the formal parameter
list.  (<code class="docutils literal notranslate"><span class="pre">*name</span></code> must occur before <code class="docutils literal notranslate"><span class="pre">**name</span></code>.) For example, if we define a
function like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">cheeseshop</span><span class="p">(</span><span class="n">kind</span><span class="p">,</span> <span class="o">*</span><span class="n">arguments</span><span class="p">,</span> <span class="o">**</span><span class="n">keywords</span><span class="p">):</span>
    <span class="nb">print</span> <span class="s2">&quot;-- Do you have any&quot;</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="s2">&quot;?&quot;</span>
    <span class="nb">print</span> <span class="s2">&quot;-- I&#39;m sorry, we&#39;re all out of&quot;</span><span class="p">,</span> <span class="n">kind</span>
    <span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">arguments</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">arg</span>
    <span class="nb">print</span> <span class="s2">&quot;-&quot;</span> <span class="o">*</span> <span class="mi">40</span>
    <span class="n">keys</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">keywords</span><span class="o">.</span><span class="n">keys</span><span class="p">())</span>
    <span class="k">for</span> <span class="n">kw</span> <span class="ow">in</span> <span class="n">keys</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">kw</span><span class="p">,</span> <span class="s2">&quot;:&quot;</span><span class="p">,</span> <span class="n">keywords</span><span class="p">[</span><span class="n">kw</span><span class="p">]</span>
</pre></div>
</div>
<p>It could be called like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">cheeseshop</span><span class="p">(</span><span class="s2">&quot;Limburger&quot;</span><span class="p">,</span> <span class="s2">&quot;It&#39;s very runny, sir.&quot;</span><span class="p">,</span>
           <span class="s2">&quot;It&#39;s really very, VERY runny, sir.&quot;</span><span class="p">,</span>
           <span class="n">shopkeeper</span><span class="o">=</span><span class="s1">&#39;Michael Palin&#39;</span><span class="p">,</span>
           <span class="n">client</span><span class="o">=</span><span class="s2">&quot;John Cleese&quot;</span><span class="p">,</span>
           <span class="n">sketch</span><span class="o">=</span><span class="s2">&quot;Cheese Shop Sketch&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>and of course it would print:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>-- Do you have any Limburger ?
-- I&#39;m sorry, we&#39;re all out of Limburger
It&#39;s very runny, sir.
It&#39;s really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
</pre></div>
</div>
<p>Note that the list of keyword argument names is created by sorting the result
of the keywords dictionary’s <code class="docutils literal notranslate"><span class="pre">keys()</span></code> method before printing its contents;
if this is not done, the order in which the arguments are printed is undefined.</p>
</div>
<div class="section" id="arbitrary-argument-lists">
<span id="tut-arbitraryargs"></span><h3>4.7.3. Arbitrary Argument Lists<a class="headerlink" href="#arbitrary-argument-lists" title="Permalink to this headline">¶</a></h3>
<p id="index-2">Finally, the least frequently used option is to specify that a function can be
called with an arbitrary number of arguments.  These arguments will be wrapped
up in a tuple (see <a class="reference internal" href="datastructures.html#tut-tuples"><span class="std std-ref">Tuples and Sequences</span></a>).  Before the variable number of arguments,
zero or more normal arguments may occur.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">write_multiple_items</span><span class="p">(</span><span class="n">file</span><span class="p">,</span> <span class="n">separator</span><span class="p">,</span> <span class="o">*</span><span class="n">args</span><span class="p">):</span>
    <span class="n">file</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">separator</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">args</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="section" id="unpacking-argument-lists">
<span id="tut-unpacking-arguments"></span><h3>4.7.4. Unpacking Argument Lists<a class="headerlink" href="#unpacking-argument-lists" title="Permalink to this headline">¶</a></h3>
<p>The reverse situation occurs when the arguments are already in a list or tuple
but need to be unpacked for a function call requiring separate positional
arguments.  For instance, the built-in <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> function expects separate
<em>start</em> and <em>stop</em> arguments.  If they are not available separately, write the
function call with the  <code class="docutils literal notranslate"><span class="pre">*</span></code>-operator to unpack the arguments out of a list
or tuple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">)</span>             <span class="c1"># normal call with separate arguments</span>
<span class="go">[3, 4, 5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>            <span class="c1"># call with arguments unpacked from a list</span>
<span class="go">[3, 4, 5]</span>
</pre></div>
</div>
<p id="index-3">In the same fashion, dictionaries can deliver keyword arguments with the <code class="docutils literal notranslate"><span class="pre">**</span></code>-operator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">parrot</span><span class="p">(</span><span class="n">voltage</span><span class="p">,</span> <span class="n">state</span><span class="o">=</span><span class="s1">&#39;a stiff&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;voom&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;-- This parrot wouldn&#39;t&quot;</span><span class="p">,</span> <span class="n">action</span><span class="p">,</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;if you put&quot;</span><span class="p">,</span> <span class="n">voltage</span><span class="p">,</span> <span class="s2">&quot;volts through it.&quot;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;E&#39;s&quot;</span><span class="p">,</span> <span class="n">state</span><span class="p">,</span> <span class="s2">&quot;!&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;voltage&quot;</span><span class="p">:</span> <span class="s2">&quot;four million&quot;</span><span class="p">,</span> <span class="s2">&quot;state&quot;</span><span class="p">:</span> <span class="s2">&quot;bleedin&#39; demised&quot;</span><span class="p">,</span> <span class="s2">&quot;action&quot;</span><span class="p">:</span> <span class="s2">&quot;VOOM&quot;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parrot</span><span class="p">(</span><span class="o">**</span><span class="n">d</span><span class="p">)</span>
<span class="go">-- This parrot wouldn&#39;t VOOM if you put four million volts through it. E&#39;s bleedin&#39; demised !</span>
</pre></div>
</div>
</div>
<div class="section" id="lambda-expressions">
<span id="tut-lambda"></span><h3>4.7.5. Lambda Expressions<a class="headerlink" href="#lambda-expressions" title="Permalink to this headline">¶</a></h3>
<p>Small anonymous functions can be created with the <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> keyword.
This function returns the sum of its two arguments: <code class="docutils literal notranslate"><span class="pre">lambda</span> <span class="pre">a,</span> <span class="pre">b:</span> <span class="pre">a+b</span></code>.
Lambda functions can be used wherever function objects are required.  They are
syntactically restricted to a single expression.  Semantically, they are just
syntactic sugar for a normal function definition.  Like nested function
definitions, lambda functions can reference variables from the containing
scope:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">make_incrementor</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">n</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="n">make_incrementor</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">43</span>
</pre></div>
</div>
<p>The above example uses a lambda expression to return a function.  Another use
is to pass a small function as an argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;one&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;three&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;four&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">pair</span><span class="p">:</span> <span class="n">pair</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pairs</span>
<span class="go">[(4, &#39;four&#39;), (1, &#39;one&#39;), (3, &#39;three&#39;), (2, &#39;two&#39;)]</span>
</pre></div>
</div>
</div>
<div class="section" id="documentation-strings">
<span id="tut-docstrings"></span><h3>4.7.6. Documentation Strings<a class="headerlink" href="#documentation-strings" title="Permalink to this headline">¶</a></h3>
<p id="index-4">There are emerging conventions about the content and formatting of documentation
strings.</p>
<p>The first line should always be a short, concise summary of the object’s
purpose.  For brevity, it should not explicitly state the object’s name or type,
since these are available by other means (except if the name happens to be a
verb describing a function’s operation).  This line should begin with a capital
letter and end with a period.</p>
<p>If there are more lines in the documentation string, the second line should be
blank, visually separating the summary from the rest of the description.  The
following lines should be one or more paragraphs describing the object’s calling
conventions, its side effects, etc.</p>
<p>The Python parser does not strip indentation from multi-line string literals in
Python, so tools that process documentation have to strip indentation if
desired.  This is done using the following convention. The first non-blank line
<em>after</em> the first line of the string determines the amount of indentation for
the entire documentation string.  (We can’t use the first line since it is
generally adjacent to the string’s opening quotes so its indentation is not
apparent in the string literal.)  Whitespace “equivalent” to this indentation is
then stripped from the start of all lines of the string.  Lines that are
indented less should not occur, but if they occur all their leading whitespace
should be stripped.  Equivalence of whitespace should be tested after expansion
of tabs (to 8 spaces, normally).</p>
<p>Here is an example of a multi-line docstring:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">my_function</span><span class="p">():</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Do nothing, but document it.</span>
<span class="gp">...</span><span class="sd"></span>
<span class="gp">... </span><span class="sd">    No, really, it doesn&#39;t do anything.</span>
<span class="gp">... </span><span class="sd">    &quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">my_function</span><span class="o">.</span><span class="vm">__doc__</span>
<span class="go">Do nothing, but document it.</span>

<span class="go">    No, really, it doesn&#39;t do anything.</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="intermezzo-coding-style">
<span id="tut-codingstyle"></span><h2>4.8. Intermezzo: Coding Style<a class="headerlink" href="#intermezzo-coding-style" title="Permalink to this headline">¶</a></h2>
<p id="index-5">Now that you are about to write longer, more complex pieces of Python, it is a
good time to talk about <em>coding style</em>.  Most languages can be written (or more
concise, <em>formatted</em>) in different styles; some are more readable than others.
Making it easy for others to read your code is always a good idea, and adopting
a nice coding style helps tremendously for that.</p>
<p>For Python, <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> has emerged as the style guide that most projects adhere to;
it promotes a very readable and eye-pleasing coding style.  Every Python
developer should read it at some point; here are the most important points
extracted for you:</p>
<ul>
<li><p class="first">Use 4-space indentation, and no tabs.</p>
<p>4 spaces are a good compromise between small indentation (allows greater
nesting depth) and large indentation (easier to read).  Tabs introduce
confusion, and are best left out.</p>
</li>
<li><p class="first">Wrap lines so that they don’t exceed 79 characters.</p>
<p>This helps users with small displays and makes it possible to have several
code files side-by-side on larger displays.</p>
</li>
<li><p class="first">Use blank lines to separate functions and classes, and larger blocks of
code inside functions.</p>
</li>
<li><p class="first">When possible, put comments on a line of their own.</p>
</li>
<li><p class="first">Use docstrings.</p>
</li>
<li><p class="first">Use spaces around operators and after commas, but not directly inside
bracketing constructs: <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">f(1,</span> <span class="pre">2)</span> <span class="pre">+</span> <span class="pre">g(3,</span> <span class="pre">4)</span></code>.</p>
</li>
<li><p class="first">Name your classes and functions consistently; the convention is to use
<code class="docutils literal notranslate"><span class="pre">CamelCase</span></code> for classes and <code class="docutils literal notranslate"><span class="pre">lower_case_with_underscores</span></code> for functions
and methods.  Always use <code class="docutils literal notranslate"><span class="pre">self</span></code> as the name for the first method argument
(see <a class="reference internal" href="classes.html#tut-firstclasses"><span class="std std-ref">A First Look at Classes</span></a> for more on classes and methods).</p>
</li>
<li><p class="first">Don’t use fancy encodings if your code is meant to be used in international
environments.  Plain ASCII works best in any case.</p>
</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Actually, <em>call by object reference</em> would be a better description,
since if a mutable object is passed, the caller will see any changes the
callee makes to it (items inserted into a list).</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. More Control Flow Tools</a><ul>
<li><a class="reference internal" href="#if-statements">4.1. <code class="docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
<li><a class="reference internal" href="#for-statements">4.2. <code class="docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
<li><a class="reference internal" href="#the-range-function">4.3. The <code class="docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
<li><a class="reference internal" href="#break-and-continue-statements-and-else-clauses-on-loops">4.4. <code class="docutils literal notranslate"><span class="pre">break</span></code> and <code class="docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
<li><a class="reference internal" href="#pass-statements">4.5. <code class="docutils literal notranslate"><span class="pre">pass</span></code> Statements</a></li>
<li><a class="reference internal" href="#defining-functions">4.6. Defining Functions</a></li>
<li><a class="reference internal" href="#more-on-defining-functions">4.7. More on Defining Functions</a><ul>
<li><a class="reference internal" href="#default-argument-values">4.7.1. Default Argument Values</a></li>
<li><a class="reference internal" href="#keyword-arguments">4.7.2. Keyword Arguments</a></li>
<li><a class="reference internal" href="#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists</a></li>
<li><a class="reference internal" href="#unpacking-argument-lists">4.7.4. Unpacking Argument Lists</a></li>
<li><a class="reference internal" href="#lambda-expressions">4.7.5. Lambda Expressions</a></li>
<li><a class="reference internal" href="#documentation-strings">4.7.6. Documentation Strings</a></li>
</ul>
</li>
<li><a class="reference internal" href="#intermezzo-coding-style">4.8. Intermezzo: Coding Style</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="previous chapter">3. An Informal Introduction to Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="datastructures.html"
                        title="next chapter">5. Data Structures</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/controlflow.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             >next</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�j1�\�\!html/tutorial/datastructures.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>5. Data Structures &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="6. Modules" href="modules.html" />
    <link rel="prev" title="4. More Control Flow Tools" href="controlflow.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/datastructures.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="controlflow.html" title="4. More Control Flow Tools"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="data-structures">
<span id="tut-structures"></span><h1>5. Data Structures<a class="headerlink" href="#data-structures" title="Permalink to this headline">¶</a></h1>
<p>This chapter describes some things you’ve learned about already in more detail,
and adds some new things as well.</p>
<div class="section" id="more-on-lists">
<span id="tut-morelists"></span><h2>5.1. More on Lists<a class="headerlink" href="#more-on-lists" title="Permalink to this headline">¶</a></h2>
<p>The list data type has some more methods.  Here are all of the methods of list
objects:</p>
<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">append</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Add an item to the end of the list; equivalent to <code class="docutils literal notranslate"><span class="pre">a[len(a):]</span> <span class="pre">=</span> <span class="pre">[x]</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">extend</code><span class="sig-paren">(</span><em>L</em><span class="sig-paren">)</span></dt>
<dd><p>Extend the list by appending all the items in the given list; equivalent to
<code class="docutils literal notranslate"><span class="pre">a[len(a):]</span> <span class="pre">=</span> <span class="pre">L</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">insert</code><span class="sig-paren">(</span><em>i</em>, <em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Insert an item at a given position.  The first argument is the index of the
element before which to insert, so <code class="docutils literal notranslate"><span class="pre">a.insert(0,</span> <span class="pre">x)</span></code> inserts at the front of
the list, and <code class="docutils literal notranslate"><span class="pre">a.insert(len(a),</span> <span class="pre">x)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">a.append(x)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">remove</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Remove the first item from the list whose value is <em>x</em>. It is an error if there
is no such item.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">pop</code><span class="sig-paren">(</span><span class="optional">[</span><em>i</em><span class="optional">]</span><span class="sig-paren">)</span></dt>
<dd><p>Remove the item at the given position in the list, and return it.  If no index
is specified, <code class="docutils literal notranslate"><span class="pre">a.pop()</span></code> removes and returns the last item in the list.  (The
square brackets around the <em>i</em> in the method signature denote that the parameter
is optional, not that you should type square brackets at that position.  You
will see this notation frequently in the Python Library Reference.)</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">index</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Return the index in the list of the first item whose value is <em>x</em>. It is an
error if there is no such item.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">count</code><span class="sig-paren">(</span><em>x</em><span class="sig-paren">)</span></dt>
<dd><p>Return the number of times <em>x</em> appears in the list.</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">sort</code><span class="sig-paren">(</span><em>cmp=None</em>, <em>key=None</em>, <em>reverse=False</em><span class="sig-paren">)</span></dt>
<dd><p>Sort the items of the list in place (the arguments can be used for sort
customization, see <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> for their explanation).</p>
</dd></dl>

<dl class="method">
<dt>
<code class="descclassname">list.</code><code class="descname">reverse</code><span class="sig-paren">(</span><span class="sig-paren">)</span></dt>
<dd><p>Reverse the elements of the list, in place.</p>
</dd></dl>

<p>An example that uses most of the list methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mf">66.25</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">1234.5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">a</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">333</span><span class="p">),</span> <span class="n">a</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mf">66.25</span><span class="p">),</span> <span class="n">a</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">)</span>
<span class="go">2 1 0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">insert</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">333</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[66.25, 333, -1, 333, 1, 1234.5, 333]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">333</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">333</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[66.25, -1, 333, 1, 1234.5, 333]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">reverse</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[333, 1234.5, 1, 333, -1, 66.25]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[-1, 1, 66.25, 333, 333, 1234.5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">1234.5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[-1, 1, 66.25, 333, 333]</span>
</pre></div>
</div>
<p>You might have noticed that methods like <code class="docutils literal notranslate"><span class="pre">insert</span></code>, <code class="docutils literal notranslate"><span class="pre">remove</span></code> or <code class="docutils literal notranslate"><span class="pre">sort</span></code> that
only modify the list have no return value printed – they return the default
<code class="docutils literal notranslate"><span class="pre">None</span></code>.  This is a design principle for all mutable data structures in
Python.</p>
<div class="section" id="using-lists-as-stacks">
<span id="tut-lists-as-stacks"></span><h3>5.1.1. Using Lists as Stacks<a class="headerlink" href="#using-lists-as-stacks" title="Permalink to this headline">¶</a></h3>
<p>The list methods make it very easy to use a list as a stack, where the last
element added is the first element retrieved (“last-in, first-out”).  To add an
item to the top of the stack, use <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>.  To retrieve an item from the
top of the stack, use <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> without an explicit index.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span> <span class="o">=</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4, 5, 6, 7]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4, 5, 6]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">stack</span>
<span class="go">[3, 4]</span>
</pre></div>
</div>
</div>
<div class="section" id="using-lists-as-queues">
<span id="tut-lists-as-queues"></span><h3>5.1.2. Using Lists as Queues<a class="headerlink" href="#using-lists-as-queues" title="Permalink to this headline">¶</a></h3>
<p>It is also possible to use a list as a queue, where the first element added is
the first element retrieved (“first-in, first-out”); however, lists are not
efficient for this purpose.  While appends and pops from the end of list are
fast, doing inserts or pops from the beginning of a list is slow (because all
of the other elements have to be shifted by one).</p>
<p>To implement a queue, use <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a> which was designed to
have fast appends and pops from both ends.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">&quot;Eric&quot;</span><span class="p">,</span> <span class="s2">&quot;John&quot;</span><span class="p">,</span> <span class="s2">&quot;Michael&quot;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;Terry&quot;</span><span class="p">)</span>           <span class="c1"># Terry arrives</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;Graham&quot;</span><span class="p">)</span>          <span class="c1"># Graham arrives</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                 <span class="c1"># The first to arrive now leaves</span>
<span class="go">&#39;Eric&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>                 <span class="c1"># The second to arrive now leaves</span>
<span class="go">&#39;John&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">queue</span>                           <span class="c1"># Remaining queue in order of arrival</span>
<span class="go">deque([&#39;Michael&#39;, &#39;Terry&#39;, &#39;Graham&#39;])</span>
</pre></div>
</div>
</div>
<div class="section" id="functional-programming-tools">
<span id="tut-functional"></span><h3>5.1.3. Functional Programming Tools<a class="headerlink" href="#functional-programming-tools" title="Permalink to this headline">¶</a></h3>
<p>There are three built-in functions that are very useful when used with lists:
<a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a>, <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>, and <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">filter(function,</span> <span class="pre">sequence)</span></code> returns a sequence consisting of those items from
the sequence for which <code class="docutils literal notranslate"><span class="pre">function(item)</span></code> is true. If <em>sequence</em> is a
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> or <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>, the result will be of the
same type; otherwise, it is always a <code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code>.  For example, to compute a
sequence of numbers divisible by 3 or 5:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">3</span> <span class="o">==</span> <span class="mi">0</span> <span class="ow">or</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">5</span> <span class="o">==</span> <span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">filter</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">25</span><span class="p">))</span>
<span class="go">[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">map(function,</span> <span class="pre">sequence)</span></code> calls <code class="docutils literal notranslate"><span class="pre">function(item)</span></code> for each of the sequence’s
items and returns a list of the return values.  For example, to compute some
cubes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">cube</span><span class="p">(</span><span class="n">x</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">cube</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">))</span>
<span class="go">[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]</span>
</pre></div>
</div>
<p>More than one sequence may be passed; the function must then have as many
arguments as there are sequences and is called with the corresponding item from
each sequence (or <code class="docutils literal notranslate"><span class="pre">None</span></code> if some sequence is shorter than another).  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">seq</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">add</span><span class="p">,</span> <span class="n">seq</span><span class="p">,</span> <span class="n">seq</span><span class="p">)</span>
<span class="go">[0, 2, 4, 6, 8, 10, 12, 14]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">reduce(function,</span> <span class="pre">sequence)</span></code> returns a single value constructed by calling the
binary function <em>function</em> on the first two items of the sequence, then on the
result and the next item, and so on.  For example, to compute the sum of the
numbers 1 through 10:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">reduce</span><span class="p">(</span><span class="n">add</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">))</span>
<span class="go">55</span>
</pre></div>
</div>
<p>If there’s only one item in the sequence, its value is returned; if the sequence
is empty, an exception is raised.</p>
<p>A third argument can be passed to indicate the starting value.  In this case the
starting value is returned for an empty sequence, and the function is first
applied to the starting value and the first sequence item, then to the result
and the next item, and so on.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">sum</span><span class="p">(</span><span class="n">seq</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">):</span> <span class="k">return</span> <span class="n">x</span><span class="o">+</span><span class="n">y</span>
<span class="gp">... </span>    <span class="k">return</span> <span class="n">reduce</span><span class="p">(</span><span class="n">add</span><span class="p">,</span> <span class="n">seq</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">))</span>
<span class="go">55</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([])</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Don’t use this example’s definition of <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a>: since summing numbers is
such a common need, a built-in function <code class="docutils literal notranslate"><span class="pre">sum(sequence)</span></code> is already provided,
and works exactly like this.</p>
</div>
<div class="section" id="list-comprehensions">
<span id="tut-listcomps"></span><h3>5.1.4. List Comprehensions<a class="headerlink" href="#list-comprehensions" title="Permalink to this headline">¶</a></h3>
<p>List comprehensions provide a concise way to create lists.
Common applications are to make new lists where each element is the result of
some operations applied to each member of another sequence or iterable, or to
create a subsequence of those elements that satisfy a certain condition.</p>
<p>For example, assume we want to create a list of squares, like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">squares</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span>
<span class="go">[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]</span>
</pre></div>
</div>
<p>We can obtain the same result with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">squares</span> <span class="o">=</span> <span class="p">[</span><span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)]</span>
</pre></div>
</div>
<p>This is also equivalent to <code class="docutils literal notranslate"><span class="pre">squares</span> <span class="pre">=</span> <span class="pre">map(lambda</span> <span class="pre">x:</span> <span class="pre">x**2,</span> <span class="pre">range(10))</span></code>,
but it’s more concise and readable.</p>
<p>A list comprehension consists of brackets containing an expression followed
by a <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> clause, then zero or more <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> or <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a>
clauses.  The result will be a new list resulting from evaluating the expression
in the context of the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> and <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clauses which follow it.
For example, this listcomp combines the elements of two lists if they are not
equal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">]</span> <span class="k">if</span> <span class="n">x</span> <span class="o">!=</span> <span class="n">y</span><span class="p">]</span>
<span class="go">[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]</span>
</pre></div>
</div>
<p>and it’s equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">combs</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]:</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">]:</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">x</span> <span class="o">!=</span> <span class="n">y</span><span class="p">:</span>
<span class="gp">... </span>            <span class="n">combs</span><span class="o">.</span><span class="n">append</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">combs</span>
<span class="go">[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]</span>
</pre></div>
</div>
<p>Note how the order of the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> and <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statements is the
same in both these snippets.</p>
<p>If the expression is a tuple (e.g. the <code class="docutils literal notranslate"><span class="pre">(x,</span> <span class="pre">y)</span></code> in the previous example),
it must be parenthesized.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">vec</span> <span class="o">=</span> <span class="p">[</span><span class="o">-</span><span class="mi">4</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create a new list with the values doubled</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span><span class="o">*</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span><span class="p">]</span>
<span class="go">[-8, -4, 0, 4, 8]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># filter the list to exclude negative numbers</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span> <span class="k">if</span> <span class="n">x</span> <span class="o">&gt;=</span> <span class="mi">0</span><span class="p">]</span>
<span class="go">[0, 2, 4]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># apply a function to all the elements</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">abs</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">vec</span><span class="p">]</span>
<span class="go">[4, 2, 0, 2, 4]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># call a method on each element</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">freshfruit</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;  banana&#39;</span><span class="p">,</span> <span class="s1">&#39;  loganberry &#39;</span><span class="p">,</span> <span class="s1">&#39;passion fruit  &#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">weapon</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">weapon</span> <span class="ow">in</span> <span class="n">freshfruit</span><span class="p">]</span>
<span class="go">[&#39;banana&#39;, &#39;loganberry&#39;, &#39;passion fruit&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># create a list of 2-tuples like (number, square)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)]</span>
<span class="go">[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># the tuple must be parenthesized, otherwise an error is raised</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)]</span>
<span class="go">  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;</span>
<span class="go">    [x, x**2 for x in range(6)]</span>
<span class="go">               ^</span>
<span class="go">SyntaxError: invalid syntax</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># flatten a list using a listcomp with two &#39;for&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vec</span> <span class="o">=</span> <span class="p">[[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">],</span> <span class="p">[</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">9</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">num</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">vec</span> <span class="k">for</span> <span class="n">num</span> <span class="ow">in</span> <span class="n">elem</span><span class="p">]</span>
<span class="go">[1, 2, 3, 4, 5, 6, 7, 8, 9]</span>
</pre></div>
</div>
<p>List comprehensions can contain complex expressions and nested functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">math</span> <span class="k">import</span> <span class="n">pi</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">pi</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">6</span><span class="p">)]</span>
<span class="go">[&#39;3.1&#39;, &#39;3.14&#39;, &#39;3.142&#39;, &#39;3.1416&#39;, &#39;3.14159&#39;]</span>
</pre></div>
</div>
<div class="section" id="nested-list-comprehensions">
<h4>5.1.4.1. Nested List Comprehensions<a class="headerlink" href="#nested-list-comprehensions" title="Permalink to this headline">¶</a></h4>
<p>The initial expression in a list comprehension can be any arbitrary expression,
including another list comprehension.</p>
<p>Consider the following example of a 3x4 matrix implemented as a list of
3 lists of length 4:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">matrix</span> <span class="o">=</span> <span class="p">[</span>
<span class="gp">... </span>    <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">],</span>
<span class="gp">... </span>    <span class="p">[</span><span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">],</span>
<span class="gp">... </span>    <span class="p">[</span><span class="mi">9</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">],</span>
<span class="gp">... </span><span class="p">]</span>
</pre></div>
</div>
<p>The following list comprehension will transpose rows and columns:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">[[</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)]</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>As we saw in the previous section, the nested listcomp is evaluated in
the context of the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> that follows it, so this example is
equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">transposed</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">])</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>which, in turn, is the same as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">):</span>
<span class="gp">... </span>    <span class="c1"># the following 3 lines implement the nested listcomp</span>
<span class="gp">... </span>    <span class="n">transposed_row</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">matrix</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">transposed_row</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">row</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="gp">... </span>    <span class="n">transposed</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">transposed_row</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transposed</span>
<span class="go">[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]</span>
</pre></div>
</div>
<p>In the real world, you should prefer built-in functions to complex flow statements.
The <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> function would do a great job for this use case:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">matrix</span><span class="p">)</span>
<span class="go">[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="controlflow.html#tut-unpacking-arguments"><span class="std std-ref">Unpacking Argument Lists</span></a> for details on the asterisk in this line.</p>
</div>
</div>
</div>
<div class="section" id="the-del-statement">
<span id="tut-del"></span><h2>5.2. The <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement<a class="headerlink" href="#the-del-statement" title="Permalink to this headline">¶</a></h2>
<p>There is a way to remove an item from a list given its index instead of its
value: the <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement.  This differs from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code> method
which returns a value.  The <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statement can also be used to remove
slices from a list or clear the entire list (which we did earlier by assignment
of an empty list to the slice).  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mf">66.25</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mi">333</span><span class="p">,</span> <span class="mf">1234.5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 66.25, 333, 333, 1234.5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">4</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 66.25, 1234.5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[:]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[]</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> can also be used to delete entire variables:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span>
</pre></div>
</div>
<p>Referencing the name <code class="docutils literal notranslate"><span class="pre">a</span></code> hereafter is an error (at least until another value
is assigned to it).  We’ll find other uses for <a class="reference internal" href="../reference/simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> later.</p>
</div>
<div class="section" id="tuples-and-sequences">
<span id="tut-tuples"></span><h2>5.3. Tuples and Sequences<a class="headerlink" href="#tuples-and-sequences" title="Permalink to this headline">¶</a></h2>
<p>We saw that lists and strings have many common properties, such as indexing and
slicing operations.  They are two examples of <em>sequence</em> data types (see
<a class="reference internal" href="../library/stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a>).  Since Python is an evolving language, other sequence data
types may be added.  There is also another standard sequence data type: the
<em>tuple</em>.</p>
<p>A tuple consists of a number of values separated by commas, for instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="mi">12345</span><span class="p">,</span> <span class="mi">54321</span><span class="p">,</span> <span class="s1">&#39;hello!&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">12345</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span>
<span class="go">(12345, 54321, &#39;hello!&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tuples may be nested:</span>
<span class="gp">... </span><span class="n">u</span> <span class="o">=</span> <span class="n">t</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">u</span>
<span class="go">((12345, 54321, &#39;hello!&#39;), (1, 2, 3, 4, 5))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Tuples are immutable:</span>
<span class="gp">... </span><span class="n">t</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">88888</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">&#39;tuple&#39; object does not support item assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># but they can contain mutable objects:</span>
<span class="gp">... </span><span class="n">v</span> <span class="o">=</span> <span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v</span>
<span class="go">([1, 2, 3], [3, 2, 1])</span>
</pre></div>
</div>
<p>As you see, on output tuples are always enclosed in parentheses, so that nested
tuples are interpreted correctly; they may be input with or without surrounding
parentheses, although often parentheses are necessary anyway (if the tuple is
part of a larger expression).  It is not possible to assign to the individual
items of a tuple, however it is possible to create tuples which contain mutable
objects, such as lists.</p>
<p>Though tuples may seem similar to lists, they are often used in different
situations and for different purposes.
Tuples are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, and usually contain a heterogeneous sequence of
elements that are accessed via unpacking (see later in this section) or indexing
(or even by attribute in the case of <a class="reference internal" href="../library/collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">namedtuples</span></code></a>).
Lists are <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>, and their elements are usually homogeneous and are
accessed by iterating over the list.</p>
<p>A special problem is the construction of tuples containing 0 or 1 items: the
syntax has some extra quirks to accommodate these.  Empty tuples are constructed
by an empty pair of parentheses; a tuple with one item is constructed by
following a value with a comma (it is not sufficient to enclose a single value
in parentheses). Ugly, but effective.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">empty</span> <span class="o">=</span> <span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">singleton</span> <span class="o">=</span> <span class="s1">&#39;hello&#39;</span><span class="p">,</span>    <span class="c1"># &lt;-- note trailing comma</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">empty</span><span class="p">)</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">singleton</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">singleton</span>
<span class="go">(&#39;hello&#39;,)</span>
</pre></div>
</div>
<p>The statement <code class="docutils literal notranslate"><span class="pre">t</span> <span class="pre">=</span> <span class="pre">12345,</span> <span class="pre">54321,</span> <span class="pre">'hello!'</span></code> is an example of <em>tuple packing</em>:
the values <code class="docutils literal notranslate"><span class="pre">12345</span></code>, <code class="docutils literal notranslate"><span class="pre">54321</span></code> and <code class="docutils literal notranslate"><span class="pre">'hello!'</span></code> are packed together in a tuple.
The reverse operation is also possible:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">z</span> <span class="o">=</span> <span class="n">t</span>
</pre></div>
</div>
<p>This is called, appropriately enough, <em>sequence unpacking</em> and works for any
sequence on the right-hand side.  Sequence unpacking requires the list of
variables on the left to have the same number of elements as the length of the
sequence.  Note that multiple assignment is really just a combination of tuple
packing and sequence unpacking.</p>
</div>
<div class="section" id="sets">
<span id="tut-sets"></span><h2>5.4. Sets<a class="headerlink" href="#sets" title="Permalink to this headline">¶</a></h2>
<p>Python also includes a data type for <em>sets</em>.  A set is an unordered collection
with no duplicate elements.  Basic uses include membership testing and
eliminating duplicate entries.  Set objects also support mathematical operations
like union, intersection, difference, and symmetric difference.</p>
<p>Curly braces or the <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a> function can be used to create sets.  Note: to
create an empty set you have to use <code class="docutils literal notranslate"><span class="pre">set()</span></code>, not <code class="docutils literal notranslate"><span class="pre">{}</span></code>; the latter creates an
empty dictionary, a data structure that we discuss in the next section.</p>
<p>Here is a brief demonstration:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">basket</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruit</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="n">basket</span><span class="p">)</span>               <span class="c1"># create a set without duplicates</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fruit</span>
<span class="go">set([&#39;orange&#39;, &#39;pear&#39;, &#39;apple&#39;, &#39;banana&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;orange&#39;</span> <span class="ow">in</span> <span class="n">fruit</span>                 <span class="c1"># fast membership testing</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;crabgrass&#39;</span> <span class="ow">in</span> <span class="n">fruit</span>
<span class="go">False</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Demonstrate set operations on unique letters from two words</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;alacazam&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>                                  <span class="c1"># unique letters in a</span>
<span class="go">set([&#39;a&#39;, &#39;r&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span>                              <span class="c1"># letters in a but not in b</span>
<span class="go">set([&#39;r&#39;, &#39;d&#39;, &#39;b&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">|</span> <span class="n">b</span>                              <span class="c1"># letters in either a or b</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;, &#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">&amp;</span> <span class="n">b</span>                              <span class="c1"># letters in both a and b</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">^</span> <span class="n">b</span>                              <span class="c1"># letters in a or b but not both</span>
<span class="go">set([&#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;])</span>
</pre></div>
</div>
<p>Similarly to <a class="reference internal" href="#tut-listcomps"><span class="std std-ref">list comprehensions</span></a>, set comprehensions
are also supported:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">{</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="s1">&#39;abracadabra&#39;</span> <span class="k">if</span> <span class="n">x</span> <span class="ow">not</span> <span class="ow">in</span> <span class="s1">&#39;abc&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">set([&#39;r&#39;, &#39;d&#39;])</span>
</pre></div>
</div>
</div>
<div class="section" id="dictionaries">
<span id="tut-dictionaries"></span><h2>5.5. Dictionaries<a class="headerlink" href="#dictionaries" title="Permalink to this headline">¶</a></h2>
<p>Another useful data type built into Python is the <em>dictionary</em> (see
<a class="reference internal" href="../library/stdtypes.html#typesmapping"><span class="std std-ref">Mapping Types — dict</span></a>). Dictionaries are sometimes found in other languages as
“associative memories” or “associative arrays”.  Unlike sequences, which are
indexed by a range of numbers, dictionaries are indexed by <em>keys</em>, which can be
any immutable type; strings and numbers can always be keys.  Tuples can be used
as keys if they contain only strings, numbers, or tuples; if a tuple contains
any mutable object either directly or indirectly, it cannot be used as a key.
You can’t use lists as keys, since lists can be modified in place using index
assignments, slice assignments, or methods like <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>.</p>
<p>It is best to think of a dictionary as an unordered set of <em>key: value</em> pairs,
with the requirement that the keys are unique (within one dictionary). A pair of
braces creates an empty dictionary: <code class="docutils literal notranslate"><span class="pre">{}</span></code>. Placing a comma-separated list of
key:value pairs within the braces adds initial key:value pairs to the
dictionary; this is also the way dictionaries are written on output.</p>
<p>The main operations on a dictionary are storing a value with some key and
extracting the value given the key.  It is also possible to delete a key:value
pair with <code class="docutils literal notranslate"><span class="pre">del</span></code>. If you store using a key that is already in use, the old
value associated with that key is forgotten.  It is an error to extract a value
using a non-existent key.</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code> method of a dictionary object returns a list of all the keys
used in the dictionary, in arbitrary order (if you want it sorted, just apply
the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function to it).  To check whether a single key is in the
dictionary, use the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> keyword.</p>
<p>Here is a small example using a dictionary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;sape&#39;</span><span class="p">:</span> <span class="mi">4139</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;guido&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4127</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span>
<span class="go">{&#39;sape&#39;: 4139, &#39;guido&#39;: 4127, &#39;jack&#39;: 4098}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;jack&#39;</span><span class="p">]</span>
<span class="go">4098</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">tel</span><span class="p">[</span><span class="s1">&#39;sape&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="p">[</span><span class="s1">&#39;irv&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4127</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span>
<span class="go">{&#39;guido&#39;: 4127, &#39;irv&#39;: 4127, &#39;jack&#39;: 4098}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">tel</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
<span class="go">[&#39;guido&#39;, &#39;irv&#39;, &#39;jack&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;guido&#39;</span> <span class="ow">in</span> <span class="n">tel</span>
<span class="go">True</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> constructor builds dictionaries directly from sequences of
key-value pairs:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">([(</span><span class="s1">&#39;sape&#39;</span><span class="p">,</span> <span class="mi">4139</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;guido&#39;</span><span class="p">,</span> <span class="mi">4127</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;jack&#39;</span><span class="p">,</span> <span class="mi">4098</span><span class="p">)])</span>
<span class="go">{&#39;sape&#39;: 4139, &#39;jack&#39;: 4098, &#39;guido&#39;: 4127}</span>
</pre></div>
</div>
<p>In addition, dict comprehensions can be used to create dictionaries from
arbitrary key and value expressions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">**</span><span class="mi">2</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">)}</span>
<span class="go">{2: 4, 4: 16, 6: 36}</span>
</pre></div>
</div>
<p>When the keys are simple strings, it is sometimes easier to specify pairs using
keyword arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="n">sape</span><span class="o">=</span><span class="mi">4139</span><span class="p">,</span> <span class="n">guido</span><span class="o">=</span><span class="mi">4127</span><span class="p">,</span> <span class="n">jack</span><span class="o">=</span><span class="mi">4098</span><span class="p">)</span>
<span class="go">{&#39;sape&#39;: 4139, &#39;jack&#39;: 4098, &#39;guido&#39;: 4127}</span>
</pre></div>
</div>
</div>
<div class="section" id="looping-techniques">
<span id="tut-loopidioms"></span><h2>5.6. Looping Techniques<a class="headerlink" href="#looping-techniques" title="Permalink to this headline">¶</a></h2>
<p>When looping through a sequence, the position index and corresponding value can
be retrieved at the same time using the <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">([</span><span class="s1">&#39;tic&#39;</span><span class="p">,</span> <span class="s1">&#39;tac&#39;</span><span class="p">,</span> <span class="s1">&#39;toe&#39;</span><span class="p">]):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">i</span><span class="p">,</span> <span class="n">v</span>
<span class="gp">...</span>
<span class="go">0 tic</span>
<span class="go">1 tac</span>
<span class="go">2 toe</span>
</pre></div>
</div>
<p>To loop over two or more sequences at the same time, the entries can be paired
with the <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">questions</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;name&#39;</span><span class="p">,</span> <span class="s1">&#39;quest&#39;</span><span class="p">,</span> <span class="s1">&#39;favorite color&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">answers</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;lancelot&#39;</span><span class="p">,</span> <span class="s1">&#39;the holy grail&#39;</span><span class="p">,</span> <span class="s1">&#39;blue&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">q</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="nb">zip</span><span class="p">(</span><span class="n">questions</span><span class="p">,</span> <span class="n">answers</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;What is your </span><span class="si">{0}</span><span class="s1">?  It is </span><span class="si">{1}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">q</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">What is your name?  It is lancelot.</span>
<span class="go">What is your quest?  It is the holy grail.</span>
<span class="go">What is your favorite color?  It is blue.</span>
</pre></div>
</div>
<p>To loop over a sequence in reverse, first specify the sequence in a forward
direction and then call the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> function.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">10</span><span class="p">,</span><span class="mi">2</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">9</span>
<span class="go">7</span>
<span class="go">5</span>
<span class="go">3</span>
<span class="go">1</span>
</pre></div>
</div>
<p>To loop over a sequence in sorted order, use the <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a> function which
returns a new sorted list while leaving the source unaltered.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">basket</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;orange&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="n">basket</span><span class="p">)):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">f</span>
<span class="gp">...</span>
<span class="go">apple</span>
<span class="go">banana</span>
<span class="go">orange</span>
<span class="go">pear</span>
</pre></div>
</div>
<p>When looping through dictionaries, the key and corresponding value can be
retrieved at the same time using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">knights</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;gallahad&#39;</span><span class="p">:</span> <span class="s1">&#39;the pure&#39;</span><span class="p">,</span> <span class="s1">&#39;robin&#39;</span><span class="p">:</span> <span class="s1">&#39;the brave&#39;</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">knights</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
<span class="gp">...</span>
<span class="go">gallahad the pure</span>
<span class="go">robin the brave</span>
</pre></div>
</div>
<p>It is sometimes tempting to change a list while you are looping over it;
however, it is often simpler and safer to create a new list instead.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">raw_data</span> <span class="o">=</span> <span class="p">[</span><span class="mf">56.2</span><span class="p">,</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">),</span> <span class="mf">51.7</span><span class="p">,</span> <span class="mf">55.3</span><span class="p">,</span> <span class="mf">52.5</span><span class="p">,</span> <span class="nb">float</span><span class="p">(</span><span class="s1">&#39;NaN&#39;</span><span class="p">),</span> <span class="mf">47.8</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filtered_data</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">value</span> <span class="ow">in</span> <span class="n">raw_data</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="ow">not</span> <span class="n">math</span><span class="o">.</span><span class="n">isnan</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">filtered_data</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">filtered_data</span>
<span class="go">[56.2, 51.7, 55.3, 52.5, 47.8]</span>
</pre></div>
</div>
</div>
<div class="section" id="more-on-conditions">
<span id="tut-conditions"></span><h2>5.7. More on Conditions<a class="headerlink" href="#more-on-conditions" title="Permalink to this headline">¶</a></h2>
<p>The conditions used in <code class="docutils literal notranslate"><span class="pre">while</span></code> and <code class="docutils literal notranslate"><span class="pre">if</span></code> statements can contain any
operators, not just comparisons.</p>
<p>The comparison operators <code class="docutils literal notranslate"><span class="pre">in</span></code> and <code class="docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code> check whether a value occurs
(does not occur) in a sequence.  The operators <code class="docutils literal notranslate"><span class="pre">is</span></code> and <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code> compare
whether two objects are really the same object; this only matters for mutable
objects like lists.  All comparison operators have the same priority, which is
lower than that of all numerical operators.</p>
<p>Comparisons can be chained.  For example, <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">&lt;</span> <span class="pre">b</span> <span class="pre">==</span> <span class="pre">c</span></code> tests whether <code class="docutils literal notranslate"><span class="pre">a</span></code> is
less than <code class="docutils literal notranslate"><span class="pre">b</span></code> and moreover <code class="docutils literal notranslate"><span class="pre">b</span></code> equals <code class="docutils literal notranslate"><span class="pre">c</span></code>.</p>
<p>Comparisons may be combined using the Boolean operators <code class="docutils literal notranslate"><span class="pre">and</span></code> and <code class="docutils literal notranslate"><span class="pre">or</span></code>, and
the outcome of a comparison (or of any other Boolean expression) may be negated
with <code class="docutils literal notranslate"><span class="pre">not</span></code>.  These have lower priorities than comparison operators; between
them, <code class="docutils literal notranslate"><span class="pre">not</span></code> has the highest priority and <code class="docutils literal notranslate"><span class="pre">or</span></code> the lowest, so that <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">and</span>
<span class="pre">not</span> <span class="pre">B</span> <span class="pre">or</span> <span class="pre">C</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">(A</span> <span class="pre">and</span> <span class="pre">(not</span> <span class="pre">B))</span> <span class="pre">or</span> <span class="pre">C</span></code>. As always, parentheses
can be used to express the desired composition.</p>
<p>The Boolean operators <code class="docutils literal notranslate"><span class="pre">and</span></code> and <code class="docutils literal notranslate"><span class="pre">or</span></code> are so-called <em>short-circuit</em>
operators: their arguments are evaluated from left to right, and evaluation
stops as soon as the outcome is determined.  For example, if <code class="docutils literal notranslate"><span class="pre">A</span></code> and <code class="docutils literal notranslate"><span class="pre">C</span></code> are
true but <code class="docutils literal notranslate"><span class="pre">B</span></code> is false, <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">and</span> <span class="pre">B</span> <span class="pre">and</span> <span class="pre">C</span></code> does not evaluate the expression
<code class="docutils literal notranslate"><span class="pre">C</span></code>.  When used as a general value and not as a Boolean, the return value of a
short-circuit operator is the last evaluated argument.</p>
<p>It is possible to assign the result of a comparison or other Boolean expression
to a variable.  For example,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">string1</span><span class="p">,</span> <span class="n">string2</span><span class="p">,</span> <span class="n">string3</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span><span class="p">,</span> <span class="s1">&#39;Trondheim&#39;</span><span class="p">,</span> <span class="s1">&#39;Hammer Dance&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">non_null</span> <span class="o">=</span> <span class="n">string1</span> <span class="ow">or</span> <span class="n">string2</span> <span class="ow">or</span> <span class="n">string3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">non_null</span>
<span class="go">&#39;Trondheim&#39;</span>
</pre></div>
</div>
<p>Note that in Python, unlike C, assignment cannot occur inside expressions. C
programmers may grumble about this, but it avoids a common class of problems
encountered in C programs: typing <code class="docutils literal notranslate"><span class="pre">=</span></code> in an expression when <code class="docutils literal notranslate"><span class="pre">==</span></code> was
intended.</p>
</div>
<div class="section" id="comparing-sequences-and-other-types">
<span id="tut-comparing"></span><h2>5.8. Comparing Sequences and Other Types<a class="headerlink" href="#comparing-sequences-and-other-types" title="Permalink to this headline">¶</a></h2>
<p>Sequence objects may be compared to other objects with the same sequence type.
The comparison uses <em>lexicographical</em> ordering: first the first two items are
compared, and if they differ this determines the outcome of the comparison; if
they are equal, the next two items are compared, and so on, until either
sequence is exhausted. If two items to be compared are themselves sequences of
the same type, the lexicographical comparison is carried out recursively.  If
all items of two sequences compare equal, the sequences are considered equal.
If one sequence is an initial sub-sequence of the other, the shorter sequence is
the smaller (lesser) one.  Lexicographical ordering for strings uses the ASCII
ordering for individual characters.  Some examples of comparisons between
sequences of the same type:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>              <span class="o">&lt;</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>              <span class="o">&lt;</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">]</span>
<span class="s1">&#39;ABC&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;C&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;Pascal&#39;</span> <span class="o">&lt;</span> <span class="s1">&#39;Python&#39;</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>           <span class="o">&lt;</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>                 <span class="o">&lt;</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>             <span class="o">==</span> <span class="p">(</span><span class="mf">1.0</span><span class="p">,</span> <span class="mf">2.0</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">)</span>
<span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;aa&#39;</span><span class="p">,</span> <span class="s1">&#39;ab&#39;</span><span class="p">))</span>   <span class="o">&lt;</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span> <span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that comparing objects of different types is legal.  The outcome is
deterministic but arbitrary: the types are ordered by their name. Thus, a list
is always smaller than a string, a string is always smaller than a tuple, etc.
<a class="footnote-reference" href="#id2" id="id1">[1]</a> Mixed numeric types are compared according to their numeric value, so 0
equals 0.0, etc.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>The rules for comparing objects of different types should not be relied upon;
they may change in a future version of the language.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">5. Data Structures</a><ul>
<li><a class="reference internal" href="#more-on-lists">5.1. More on Lists</a><ul>
<li><a class="reference internal" href="#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
<li><a class="reference internal" href="#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
<li><a class="reference internal" href="#functional-programming-tools">5.1.3. Functional Programming Tools</a></li>
<li><a class="reference internal" href="#list-comprehensions">5.1.4. List Comprehensions</a><ul>
<li><a class="reference internal" href="#nested-list-comprehensions">5.1.4.1. Nested List Comprehensions</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#the-del-statement">5.2. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li><a class="reference internal" href="#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
<li><a class="reference internal" href="#sets">5.4. Sets</a></li>
<li><a class="reference internal" href="#dictionaries">5.5. Dictionaries</a></li>
<li><a class="reference internal" href="#looping-techniques">5.6. Looping Techniques</a></li>
<li><a class="reference internal" href="#more-on-conditions">5.7. More on Conditions</a></li>
<li><a class="reference internal" href="#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="controlflow.html"
                        title="previous chapter">4. More Control Flow Tools</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="modules.html"
                        title="next chapter">6. Modules</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/datastructures.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             >next</a> |</li>
        <li class="right" >
          <a href="controlflow.html" title="4. More Control Flow Tools"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�/Ѷ���html/tutorial/errors.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>8. Errors and Exceptions &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="9. Classes" href="classes.html" />
    <link rel="prev" title="7. Input and Output" href="inputoutput.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/errors.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="errors-and-exceptions">
<span id="tut-errors"></span><h1>8. Errors and Exceptions<a class="headerlink" href="#errors-and-exceptions" title="Permalink to this headline">¶</a></h1>
<p>Until now error messages haven’t been more than mentioned, but if you have tried
out the examples you have probably seen some.  There are (at least) two
distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
<div class="section" id="syntax-errors">
<span id="tut-syntaxerrors"></span><h2>8.1. Syntax Errors<a class="headerlink" href="#syntax-errors" title="Permalink to this headline">¶</a></h2>
<p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span> <span class="s1">&#39;Hello world&#39;</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>
    <span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span> <span class="s1">&#39;Hello world&#39;</span>
                   <span class="o">^</span>
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
</pre></div>
</div>
<p>The parser repeats the offending line and displays a little ‘arrow’ pointing at
the earliest point in the line where the error was detected.  The error is
caused by (or at least detected at) the token <em>preceding</em> the arrow: in the
example, the error is detected at the keyword <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>, since a colon
(<code class="docutils literal notranslate"><span class="pre">':'</span></code>) is missing before it.  File name and line number are printed so you
know where to look in case the input came from a script.</p>
</div>
<div class="section" id="exceptions">
<span id="tut-exceptions"></span><h2>8.2. Exceptions<a class="headerlink" href="#exceptions" title="Permalink to this headline">¶</a></h2>
<p>Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
how to handle them in Python programs.  Most exceptions are not handled by
programs, however, and result in error messages as shown here:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ZeroDivisionError</span>: <span class="n">integer division or modulo by zero</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">name &#39;spam&#39; is not defined</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;2&#39;</span> <span class="o">+</span> <span class="mi">2</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">cannot concatenate &#39;str&#39; and &#39;int&#39; objects</span>
</pre></div>
</div>
<p>The last line of the error message indicates what happened. Exceptions come in
different types, and the type is printed as part of the message: the types in
the example are <a class="reference internal" href="../library/exceptions.html#exceptions.ZeroDivisionError" title="exceptions.ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
The string printed as the exception type is the name of the built-in exception
that occurred.  This is true for all built-in exceptions, but need not be true
for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).</p>
<p>The rest of the line provides detail based on the type of exception and what
caused it.</p>
<p>The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack
traceback listing source lines; however, it will not display lines read from
standard input.</p>
<p><a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a> lists the built-in exceptions and their meanings.</p>
</div>
<div class="section" id="handling-exceptions">
<span id="tut-handling"></span><h2>8.3. Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Permalink to this headline">¶</a></h2>
<p>It is possible to write programs that handle selected exceptions. Look at the
following example, which asks the user for input until a valid integer has been
entered, but allows the user to interrupt the program (using <kbd class="kbd docutils literal notranslate">Control-C</kbd> or
whatever the operating system supports); note that a user-generated interruption
is signalled by raising the <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">raw_input</span><span class="p">(</span><span class="s2">&quot;Please enter a number: &quot;</span><span class="p">))</span>
<span class="gp">... </span>        <span class="k">break</span>
<span class="gp">... </span>    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;Oops!  That was no valid number.  Try again...&quot;</span>
<span class="gp">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement works as follows.</p>
<ul class="simple">
<li>First, the <em>try clause</em> (the statement(s) between the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> and
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keywords) is executed.</li>
<li>If no exception occurs, the <em>except clause</em> is skipped and execution of the
<a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement is finished.</li>
<li>If an exception occurs during execution of the try clause, the rest of the
clause is skipped.  Then if its type matches the exception named after the
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keyword, the except clause is executed, and then execution
continues after the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement.</li>
<li>If an exception occurs which does not match the exception named in the except
clause, it is passed on to outer <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statements; if no handler is
found, it is an <em>unhandled exception</em> and execution stops with a message as
shown above.</li>
</ul>
<p>A <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement may have more than one except clause, to specify
handlers for different exceptions.  At most one handler will be executed.
Handlers only handle exceptions that occur in the corresponding try clause, not
in other handlers of the same <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement.  An except clause may
name multiple exceptions as a parenthesized tuple, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span> <span class="k">except</span> <span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">NameError</span><span class="p">):</span>
<span class="o">...</span>     <span class="k">pass</span>
</pre></div>
</div>
<p>Note that the parentheses around this tuple are required, because
<code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">ValueError,</span> <span class="pre">e:</span></code> was the syntax used for what is normally
written as <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">ValueError</span> <span class="pre">as</span> <span class="pre">e:</span></code> in modern Python (described
below). The old syntax is still supported for backwards compatibility.
This means <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">RuntimeError,</span> <span class="pre">TypeError</span></code> is not equivalent to
<code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">(RuntimeError,</span> <span class="pre">TypeError):</span></code> but to <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">RuntimeError</span> <span class="pre">as</span>
<span class="pre">TypeError:</span></code> which is not what you want.</p>
<p>The last except clause may omit the exception name(s), to serve as a wildcard.
Use this with extreme caution, since it is easy to mask a real programming error
in this way!  It can also be used to print an error message and then re-raise
the exception (allowing a caller to handle the exception as well):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.txt&#39;</span><span class="p">)</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
    <span class="n">i</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span>
<span class="k">except</span> <span class="ne">IOError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;I/O error(</span><span class="si">{0}</span><span class="s2">): </span><span class="si">{1}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">e</span><span class="o">.</span><span class="n">errno</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">strerror</span><span class="p">)</span>
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Could not convert data to an integer.&quot;</span>
<span class="k">except</span><span class="p">:</span>
    <span class="nb">print</span> <span class="s2">&quot;Unexpected error:&quot;</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">exc_info</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">raise</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement has an optional <em>else
clause</em>, which, when present, must follow all except clauses.  It is useful for
code that must be executed if the try clause does not raise an exception.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">IOError</span><span class="p">:</span>
        <span class="nb">print</span> <span class="s1">&#39;cannot open&#39;</span><span class="p">,</span> <span class="n">arg</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">arg</span><span class="p">,</span> <span class="s1">&#39;has&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()),</span> <span class="s1">&#39;lines&#39;</span>
        <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The use of the <a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause is better than adding additional code to
the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause because it avoids accidentally catching an exception
that wasn’t raised by the code being protected by the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> …
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement.</p>
<p>When an exception occurs, it may have an associated value, also known as the
exception’s <em>argument</em>. The presence and type of the argument depend on the
exception type.</p>
<p>The except clause may specify a variable after the exception name (or tuple).
The variable is bound to an exception instance with the arguments stored in
<code class="docutils literal notranslate"><span class="pre">instance.args</span></code>.  For convenience, the exception instance defines
<a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> so the arguments can be printed directly without having to
reference <code class="docutils literal notranslate"><span class="pre">.args</span></code>.</p>
<p>One may also instantiate an exception first before raising it and add any
attributes to it as desired.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">inst</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="nb">type</span><span class="p">(</span><span class="n">inst</span><span class="p">)</span>     <span class="c1"># the exception instance</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span>      <span class="c1"># arguments stored in .args</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">inst</span>           <span class="c1"># __str__ allows args to be printed directly</span>
<span class="gp">... </span>    <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;x =&#39;</span><span class="p">,</span> <span class="n">x</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;y =&#39;</span><span class="p">,</span> <span class="n">y</span>
<span class="gp">...</span>
<span class="go">&lt;type &#39;exceptions.Exception&#39;&gt;</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">(&#39;spam&#39;, &#39;eggs&#39;)</span>
<span class="go">x = spam</span>
<span class="go">y = eggs</span>
</pre></div>
</div>
<p>If an exception has an argument, it is printed as the last part (‘detail’) of
the message for unhandled exceptions.</p>
<p>Exception handlers don’t just handle exceptions if they occur immediately in the
try clause, but also if they occur inside functions that are called (even
indirectly) in the try clause. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">this_fails</span><span class="p">():</span>
<span class="gp">... </span>    <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">this_fails</span><span class="p">()</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">detail</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Handling run-time error:&#39;</span><span class="p">,</span> <span class="n">detail</span>
<span class="gp">...</span>
<span class="go">Handling run-time error: integer division or modulo by zero</span>
</pre></div>
</div>
</div>
<div class="section" id="raising-exceptions">
<span id="tut-raising"></span><h2>8.4. Raising Exceptions<a class="headerlink" href="#raising-exceptions" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows the programmer to force a specified
exception to occur. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">HiThere</span>
</pre></div>
</div>
<p>The sole argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> indicates the exception to be raised.
This must be either an exception instance or an exception class (a class that
derives from <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code>).</p>
<p>If you need to determine whether an exception was raised but don’t intend to
handle it, a simpler form of the <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows you to
re-raise the exception:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">&#39;HiThere&#39;</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;An exception flew by!&#39;</span>
<span class="gp">... </span>    <span class="k">raise</span>
<span class="gp">...</span>
<span class="go">An exception flew by!</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">HiThere</span>
</pre></div>
</div>
</div>
<div class="section" id="user-defined-exceptions">
<span id="tut-userexceptions"></span><h2>8.5. User-defined Exceptions<a class="headerlink" href="#user-defined-exceptions" title="Permalink to this headline">¶</a></h2>
<p>Programs may name their own exceptions by creating a new exception class (see
<a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a> for more about Python classes).  Exceptions should typically
be derived from the <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class, either directly or indirectly.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyError</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">repr</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="n">MyError</span><span class="p">(</span><span class="mi">2</span><span class="o">*</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">... </span><span class="k">except</span> <span class="n">MyError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;My exception occurred, value:&#39;</span><span class="p">,</span> <span class="n">e</span><span class="o">.</span><span class="n">value</span>
<span class="gp">...</span>
<span class="go">My exception occurred, value: 4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">raise</span> <span class="n">MyError</span><span class="p">(</span><span class="s1">&#39;oops!&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">__main__.MyError</span>: <span class="n">&#39;oops!&#39;</span>
</pre></div>
</div>
<p>In this example, the default <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> of <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code> has been
overridden.  The new behavior simply creates the <em>value</em> attribute.  This
replaces the default behavior of creating the <em>args</em> attribute.</p>
<p>Exception classes can be defined which do anything any other class can do, but
are usually kept simple, often only offering a number of attributes that allow
information about the error to be extracted by handlers for the exception.  When
creating a module that can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and subclass that
to create specific exception classes for different error conditions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Error</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Base class for exceptions in this module.&quot;&quot;&quot;</span>
    <span class="k">pass</span>

<span class="k">class</span> <span class="nc">InputError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Exception raised for errors in the input.</span>

<span class="sd">    Attributes:</span>
<span class="sd">        expr -- input expression in which the error occurred</span>
<span class="sd">        msg  -- explanation of the error</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">expr</span><span class="p">,</span> <span class="n">msg</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">expr</span> <span class="o">=</span> <span class="n">expr</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="n">msg</span>

<span class="k">class</span> <span class="nc">TransitionError</span><span class="p">(</span><span class="n">Error</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Raised when an operation attempts a state transition that&#39;s not</span>
<span class="sd">    allowed.</span>

<span class="sd">    Attributes:</span>
<span class="sd">        prev -- state at beginning of transition</span>
<span class="sd">        next -- attempted new state</span>
<span class="sd">        msg  -- explanation of why the specific transition is not allowed</span>
<span class="sd">    &quot;&quot;&quot;</span>

    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">prev</span><span class="p">,</span> <span class="nb">next</span><span class="p">,</span> <span class="n">msg</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">prev</span> <span class="o">=</span> <span class="n">prev</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">next</span> <span class="o">=</span> <span class="nb">next</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">msg</span> <span class="o">=</span> <span class="n">msg</span>
</pre></div>
</div>
<p>Most exceptions are defined with names that end in “Error”, similar to the
naming of the standard exceptions.</p>
<p>Many standard modules define their own exceptions to report errors that may
occur in functions they define.  More information on classes is presented in
chapter <a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a>.</p>
</div>
<div class="section" id="defining-clean-up-actions">
<span id="tut-cleanup"></span><h2>8.6. Defining Clean-up Actions<a class="headerlink" href="#defining-clean-up-actions" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement has another optional clause which is intended to
define clean-up actions that must be executed under all circumstances.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
<span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;Goodbye, world!&#39;</span>
<span class="gp">...</span>
<span class="go">Goodbye, world!</span>
<span class="nc">KeyboardInterrupt</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">&lt;module&gt;</span>
</pre></div>
</div>
<p>A <em>finally clause</em> is always executed before leaving the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
statement, whether an exception has occurred or not. When an exception has
occurred in the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause and has not been handled by an
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause (or it has occurred in an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> or
<a class="reference internal" href="../reference/compound_stmts.html#else"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code></a> clause), it is re-raised after the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause has
been executed.  The <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is also executed “on the way out”
when any other clause of the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement is left via a
<a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>, <a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement.  A more
complicated example (having <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> and <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clauses in
the same <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement works as of Python 2.5):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>        <span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
<span class="gp">... </span>    <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;division by zero!&quot;</span>
<span class="gp">... </span>    <span class="k">else</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;result is&quot;</span><span class="p">,</span> <span class="n">result</span>
<span class="gp">... </span>    <span class="k">finally</span><span class="p">:</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="s2">&quot;executing finally clause&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">result is 2</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">division by zero!</span>
<span class="go">executing finally clause</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">divide</span><span class="p">(</span><span class="s2">&quot;2&quot;</span><span class="p">,</span> <span class="s2">&quot;1&quot;</span><span class="p">)</span>
<span class="go">executing finally clause</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">3</span>, in <span class="n">divide</span>
<span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: &#39;str&#39; and &#39;str&#39;</span>
</pre></div>
</div>
<p>As you can see, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed in any event.  The
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> raised by dividing two strings is not handled by the
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause and therefore re-raised after the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a>
clause has been executed.</p>
<p>In real world applications, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is useful for
releasing external resources (such as files or network connections), regardless
of whether the use of the resource was successful.</p>
</div>
<div class="section" id="predefined-clean-up-actions">
<span id="tut-cleanup-with"></span><h2>8.7. Predefined Clean-up Actions<a class="headerlink" href="#predefined-clean-up-actions" title="Permalink to this headline">¶</a></h2>
<p>Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">line</span><span class="p">,</span>
</pre></div>
</div>
<p>The problem with this code is that it leaves the file open for an indeterminate
amount of time after the code has finished executing. This is not an issue in
simple scripts, but can be a problem for larger applications. The
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows objects like files to be used in a way that
ensures they are always cleaned up promptly and correctly.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;myfile.txt&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span><span class="p">,</span>
</pre></div>
</div>
<p>After the statement is executed, the file <em>f</em> is always closed, even if a
problem was encountered while processing the lines. Other objects which provide
predefined clean-up actions will indicate this in their documentation.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
<li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
<li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
<li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
<li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
<li><a class="reference internal" href="#user-defined-exceptions">8.5. User-defined Exceptions</a></li>
<li><a class="reference internal" href="#defining-clean-up-actions">8.6. Defining Clean-up Actions</a></li>
<li><a class="reference internal" href="#predefined-clean-up-actions">8.7. Predefined Clean-up Actions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="inputoutput.html"
                        title="previous chapter">7. Input and Output</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="classes.html"
                        title="next chapter">9. Classes</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/errors.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes"
             >next</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\H�elWlW html/tutorial/floatingpoint.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>14. Floating Point Arithmetic: Issues and Limitations &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="15. Appendix" href="appendix.html" />
    <link rel="prev" title="13. Interactive Input Editing and History Substitution" href="interactive.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/floatingpoint.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="appendix.html" title="15. Appendix"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="interactive.html" title="13. Interactive Input Editing and History Substitution"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="floating-point-arithmetic-issues-and-limitations">
<span id="tut-fp-issues"></span><h1>14. Floating Point Arithmetic:  Issues and Limitations<a class="headerlink" href="#floating-point-arithmetic-issues-and-limitations" title="Permalink to this headline">¶</a></h1>
<p>Floating-point numbers are represented in computer hardware as base 2 (binary)
fractions.  For example, the decimal fraction</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.125</span>
</pre></div>
</div>
<p>has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.001</span>
</pre></div>
</div>
<p>has value 0/2 + 0/4 + 1/8.  These two fractions have identical values, the only
real difference being that the first is written in base 10 fractional notation,
and the second in base 2.</p>
<p>Unfortunately, most decimal fractions cannot be represented exactly as binary
fractions.  A consequence is that, in general, the decimal floating-point
numbers you enter are only approximated by the binary floating-point numbers
actually stored in the machine.</p>
<p>The problem is easier to understand at first in base 10.  Consider the fraction
1/3.  You can approximate that as a base 10 fraction:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.3</span>
</pre></div>
</div>
<p>or, better,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.33</span>
</pre></div>
</div>
<p>or, better,</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.333</span>
</pre></div>
</div>
<p>and so on.  No matter how many digits you’re willing to write down, the result
will never be exactly 1/3, but will be an increasingly better approximation of
1/3.</p>
<p>In the same way, no matter how many base 2 digits you’re willing to use, the
decimal value 0.1 cannot be represented exactly as a base 2 fraction.  In base
2, 1/10 is the infinitely repeating fraction</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.0001100110011001100110011001100110011001100110011</span><span class="o">...</span>
</pre></div>
</div>
<p>Stop at any finite number of bits, and you get an approximation.</p>
<p>On a typical machine running Python, there are 53 bits of precision available
for a Python float, so the value stored internally when you enter the decimal
number <code class="docutils literal notranslate"><span class="pre">0.1</span></code> is the binary fraction</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">0.00011001100110011001100110011001100110011001100110011010</span>
</pre></div>
</div>
<p>which is close to, but not exactly equal to, 1/10.</p>
<p>It’s easy to forget that the stored value is an approximation to the original
decimal fraction, because of the way that floats are displayed at the
interpreter prompt.  Python only prints a decimal approximation to the true
decimal value of the binary approximation stored by the machine.  If Python
were to print the true decimal value of the binary approximation stored for
0.1, it would have to display</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span>
<span class="go">0.1000000000000000055511151231257827021181583404541015625</span>
</pre></div>
</div>
<p>That is more digits than most people find useful, so Python keeps the number
of digits manageable by displaying a rounded value instead</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span>
<span class="go">0.1</span>
</pre></div>
</div>
<p>It’s important to realize that this is, in a real sense, an illusion: the value
in the machine is not exactly 1/10, you’re simply rounding the <em>display</em> of the
true machine value.  This fact becomes apparent as soon as you try to do
arithmetic with these values</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.2</span>
<span class="go">0.30000000000000004</span>
</pre></div>
</div>
<p>Note that this is in the very nature of binary floating-point: this is not a
bug in Python, and it is not a bug in your code either.  You’ll see the same
kind of thing in all languages that support your hardware’s floating-point
arithmetic (although some languages may not <em>display</em> the difference by
default, or in all output modes).</p>
<p>Other surprises follow from this one.  For example, if you try to round the
value 2.675 to two decimal places, you get this</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="mf">2.675</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">2.67</span>
</pre></div>
</div>
<p>The documentation for the built-in <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function says that it rounds
to the nearest value, rounding ties away from zero.  Since the decimal fraction
2.675 is exactly halfway between 2.67 and 2.68, you might expect the result
here to be (a binary approximation to) 2.68.  It’s not, because when the
decimal string <code class="docutils literal notranslate"><span class="pre">2.675</span></code> is converted to a binary floating-point number, it’s
again replaced with a binary approximation, whose exact value is</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mf">2.67499999999999982236431605997495353221893310546875</span>
</pre></div>
</div>
<p>Since this approximation is slightly closer to 2.67 than to 2.68, it’s rounded
down.</p>
<p>If you’re in a situation where you care which way your decimal halfway-cases
are rounded, you should consider using the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module.
Incidentally, the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module also provides a nice way to “see” the
exact value that’s stored in any particular Python float</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mf">2.675</span><span class="p">)</span>
<span class="go">Decimal(&#39;2.67499999999999982236431605997495353221893310546875&#39;)</span>
</pre></div>
</div>
<p>Another consequence is that since 0.1 is not exactly 1/10, summing ten values
of 0.1 may not yield exactly 1.0, either:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span> <span class="o">=</span> <span class="mf">0.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">sum</span> <span class="o">+=</span> <span class="mf">0.1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span>
<span class="go">0.9999999999999999</span>
</pre></div>
</div>
<p>Binary floating-point arithmetic holds many surprises like this.  The problem
with “0.1” is explained in precise detail below, in the “Representation Error”
section.  See <a class="reference external" href="http://www.lahey.com/float.htm">The Perils of Floating Point</a>
for a more complete account of other common surprises.</p>
<p>As that says near the end, “there are no easy answers.”  Still, don’t be unduly
wary of floating-point!  The errors in Python float operations are inherited
from the floating-point hardware, and on most machines are on the order of no
more than 1 part in 2**53 per operation.  That’s more than adequate for most
tasks, but you do need to keep in mind that it’s not decimal arithmetic, and
that every float operation can suffer a new rounding error.</p>
<p>While pathological cases do exist, for most casual use of floating-point
arithmetic you’ll see the result you expect in the end if you simply round the
display of your final results to the number of decimal digits you expect.  For
fine control over how a float is displayed see the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method’s
format specifiers in <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
<div class="section" id="representation-error">
<span id="tut-fp-error"></span><h2>14.1. Representation Error<a class="headerlink" href="#representation-error" title="Permalink to this headline">¶</a></h2>
<p>This section explains the “0.1” example in detail, and shows how you can
perform an exact analysis of cases like this yourself.  Basic familiarity with
binary floating-point representation is assumed.</p>
<p><em class="dfn">Representation error</em> refers to the fact that some (most, actually)
decimal fractions cannot be represented exactly as binary (base 2) fractions.
This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many
others) often won’t display the exact decimal number you expect:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.2</span>
<span class="go">0.30000000000000004</span>
</pre></div>
</div>
<p>Why is that?  1/10 and 2/10 are not exactly representable as a binary
fraction. Almost all machines today (July 2010) use IEEE-754 floating point
arithmetic, and almost all platforms map Python floats to IEEE-754 “double
precision”.  754 doubles contain 53 bits of precision, so on input the computer
strives to convert 0.1 to the closest fraction it can of the form <em>J</em>/2**<em>N</em>
where <em>J</em> is an integer containing exactly 53 bits.  Rewriting</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="o">/</span> <span class="mi">10</span> <span class="o">~=</span> <span class="n">J</span> <span class="o">/</span> <span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="n">N</span><span class="p">)</span>
</pre></div>
</div>
<p>as</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">J</span> <span class="o">~=</span> <span class="mi">2</span><span class="o">**</span><span class="n">N</span> <span class="o">/</span> <span class="mi">10</span>
</pre></div>
</div>
<p>and recalling that <em>J</em> has exactly 53 bits (is <code class="docutils literal notranslate"><span class="pre">&gt;=</span> <span class="pre">2**52</span></code> but <code class="docutils literal notranslate"><span class="pre">&lt;</span> <span class="pre">2**53</span></code>),
the best value for <em>N</em> is 56:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span><span class="o">**</span><span class="mi">52</span>
<span class="go">4503599627370496</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span><span class="o">**</span><span class="mi">53</span>
<span class="go">9007199254740992</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span><span class="o">**</span><span class="mi">56</span><span class="o">/</span><span class="mi">10</span>
<span class="go">7205759403792793</span>
</pre></div>
</div>
<p>That is, 56 is the only value for <em>N</em> that leaves <em>J</em> with exactly 53 bits.
The best possible value for <em>J</em> is then that quotient rounded:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="p">,</span> <span class="n">r</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="mi">56</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">r</span>
<span class="go">6</span>
</pre></div>
</div>
<p>Since the remainder is more than half of 10, the best approximation is obtained
by rounding up:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">q</span><span class="o">+</span><span class="mi">1</span>
<span class="go">7205759403792794</span>
</pre></div>
</div>
<p>Therefore the best possible approximation to 1/10 in 754 double precision is
that over 2**56, or</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">7205759403792794</span> <span class="o">/</span> <span class="mi">72057594037927936</span>
</pre></div>
</div>
<p>Note that since we rounded up, this is actually a little bit larger than 1/10;
if we had not rounded up, the quotient would have been a little bit smaller
than 1/10.  But in no case can it be <em>exactly</em> 1/10!</p>
<p>So the computer never “sees” 1/10:  what it sees is the exact fraction given
above, the best 754 double approximation it can get:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="o">.</span><span class="mi">1</span> <span class="o">*</span> <span class="mi">2</span><span class="o">**</span><span class="mi">56</span>
<span class="go">7205759403792794.0</span>
</pre></div>
</div>
<p>If we multiply that fraction by 10**30, we can see the (truncated) value of
its 30 most significant decimal digits:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">7205759403792794</span> <span class="o">*</span> <span class="mi">10</span><span class="o">**</span><span class="mi">30</span> <span class="o">//</span> <span class="mi">2</span><span class="o">**</span><span class="mi">56</span>
<span class="go">100000000000000005551115123125L</span>
</pre></div>
</div>
<p>meaning that the exact number stored in the computer is approximately equal to
the decimal value 0.100000000000000005551115123125.  In versions prior to
Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits,
giving ‘0.10000000000000001’.  In current versions, Python displays a value
based on the shortest decimal fraction that rounds correctly back to the true
binary value, resulting simply in ‘0.1’.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">14. Floating Point Arithmetic:  Issues and Limitations</a><ul>
<li><a class="reference internal" href="#representation-error">14.1. Representation Error</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="interactive.html"
                        title="previous chapter">13. Interactive Input Editing and History Substitution</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="appendix.html"
                        title="next chapter">15. Appendix</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/floatingpoint.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="appendix.html" title="15. Appendix"
             >next</a> |</li>
        <li class="right" >
          <a href="interactive.html" title="13. Interactive Input Editing and History Substitution"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\C��d�dhtml/tutorial/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>The Python Tutorial &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. Whetting Your Appetite" href="appetite.html" />
    <link rel="prev" title="What’s New in Python 2.0" href="../whatsnew/2.0.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../whatsnew/2.0.html" title="What’s New in Python 2.0"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="the-python-tutorial">
<span id="tutorial-index"></span><h1>The Python Tutorial<a class="headerlink" href="#the-python-tutorial" title="Permalink to this headline">¶</a></h1>
<p>Python is an easy to learn, powerful programming language. It has efficient
high-level data structures and a simple but effective approach to
object-oriented programming. Python’s elegant syntax and dynamic typing,
together with its interpreted nature, make it an ideal language for scripting
and rapid application development in many areas on most platforms.</p>
<p>The Python interpreter and the extensive standard library are freely available
in source or binary form for all major platforms from the Python Web site,
<a class="reference external" href="https://www.python.org/">https://www.python.org/</a>, and may be freely distributed. The same site also
contains distributions of and pointers to many free third party Python modules,
programs and tools, and additional documentation.</p>
<p>The Python interpreter is easily extended with new functions and data types
implemented in C or C++ (or other languages callable from C). Python is also
suitable as an extension language for customizable applications.</p>
<p>This tutorial introduces the reader informally to the basic concepts and
features of the Python language and system. It helps to have a Python
interpreter handy for hands-on experience, but all examples are self-contained,
so the tutorial can be read off-line as well.</p>
<p>For a description of standard objects and modules, see <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.
<a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a> gives a more formal definition of the language.  To write
extensions in C or C++, read <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a> and
<a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a>. There are also several books covering Python in depth.</p>
<p>This tutorial does not attempt to be comprehensive and cover every single
feature, or even every commonly used feature. Instead, it introduces many of
Python’s most noteworthy features, and will give you a good idea of the
language’s flavor and style. After reading it, you will be able to read and
write Python modules and programs, and you will be ready to learn more about the
various Python library modules described in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.</p>
<p>The <a class="reference internal" href="../glossary.html#glossary"><span class="std std-ref">Glossary</span></a> is also worth going through.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="appetite.html">1. Whetting Your Appetite</a></li>
<li class="toctree-l1"><a class="reference internal" href="interpreter.html">2. Using the Python Interpreter</a><ul>
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#argument-passing">2.1.1. Argument Passing</a></li>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#source-code-encoding">2.2.1. Source Code Encoding</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="introduction.html">3. An Informal Introduction to Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#numbers">3.1.1. Numbers</a></li>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#strings">3.1.2. Strings</a></li>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#unicode-strings">3.1.3. Unicode Strings</a></li>
<li class="toctree-l3"><a class="reference internal" href="introduction.html#lists">3.1.4. Lists</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="introduction.html#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="controlflow.html">4. More Control Flow Tools</a><ul>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#if-statements">4.1. <code class="docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#for-statements">4.2. <code class="docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#the-range-function">4.3. The <code class="docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">4.4. <code class="docutils literal notranslate"><span class="pre">break</span></code> and <code class="docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#pass-statements">4.5. <code class="docutils literal notranslate"><span class="pre">pass</span></code> Statements</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#defining-functions">4.6. Defining Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#more-on-defining-functions">4.7. More on Defining Functions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#default-argument-values">4.7.1. Default Argument Values</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#keyword-arguments">4.7.2. Keyword Arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#unpacking-argument-lists">4.7.4. Unpacking Argument Lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#lambda-expressions">4.7.5. Lambda Expressions</a></li>
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#documentation-strings">4.7.6. Documentation Strings</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#intermezzo-coding-style">4.8. Intermezzo: Coding Style</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="datastructures.html">5. Data Structures</a><ul>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-lists">5.1. More on Lists</a><ul>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#functional-programming-tools">5.1.3. Functional Programming Tools</a></li>
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#list-comprehensions">5.1.4. List Comprehensions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="datastructures.html#nested-list-comprehensions">5.1.4.1. Nested List Comprehensions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#the-del-statement">5.2. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#sets">5.4. Sets</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#dictionaries">5.5. Dictionaries</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#looping-techniques">5.6. Looping Techniques</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-conditions">5.7. More on Conditions</a></li>
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="modules.html">6. Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="modules.html#more-on-modules">6.1. More on Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="modules.html#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#the-module-search-path">6.1.2. The Module Search Path</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#standard-modules">6.2. Standard Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#the-dir-function">6.3. The <code class="docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="modules.html#packages">6.4. Packages</a><ul>
<li class="toctree-l3"><a class="reference internal" href="modules.html#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#intra-package-references">6.4.2. Intra-package References</a></li>
<li class="toctree-l3"><a class="reference internal" href="modules.html#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="inputoutput.html">7. Input and Output</a><ul>
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#old-string-formatting">7.1.1. Old string formatting</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="errors.html">8. Errors and Exceptions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="errors.html#syntax-errors">8.1. Syntax Errors</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#exceptions">8.2. Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#handling-exceptions">8.3. Handling Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#raising-exceptions">8.4. Raising Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#user-defined-exceptions">8.5. User-defined Exceptions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#defining-clean-up-actions">8.6. Defining Clean-up Actions</a></li>
<li class="toctree-l2"><a class="reference internal" href="errors.html#predefined-clean-up-actions">8.7. Predefined Clean-up Actions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="classes.html">9. Classes</a><ul>
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-objects">9.3.2. Class Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#instance-objects">9.3.3. Instance Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#method-objects">9.3.4. Method Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#random-remarks">9.4. Random Remarks</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#inheritance">9.5. Inheritance</a><ul>
<li class="toctree-l3"><a class="reference internal" href="classes.html#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#private-variables-and-class-local-references">9.6. Private Variables and Class-local References</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#odds-and-ends">9.7. Odds and Ends</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#exceptions-are-classes-too">9.8. Exceptions Are Classes Too</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#iterators">9.9. Iterators</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#generators">9.10. Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="classes.html#generator-expressions">9.11. Generator Expressions</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdlib.html">10. Brief Tour of the Standard Library</a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#operating-system-interface">10.1. Operating System Interface</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#file-wildcards">10.2. File Wildcards</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#command-line-arguments">10.3. Command Line Arguments</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#string-pattern-matching">10.5. String Pattern Matching</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#mathematics">10.6. Mathematics</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#internet-access">10.7. Internet Access</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#dates-and-times">10.8. Dates and Times</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#data-compression">10.9. Data Compression</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#performance-measurement">10.10. Performance Measurement</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#quality-control">10.11. Quality Control</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#batteries-included">10.12. Batteries Included</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="stdlib2.html">11. Brief Tour of the Standard Library — Part II</a><ul>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#output-formatting">11.1. Output Formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#templating">11.2. Templating</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#multi-threading">11.4. Multi-threading</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#logging">11.5. Logging</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#weak-references">11.6. Weak References</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="whatnow.html">12. What Now?</a></li>
<li class="toctree-l1"><a class="reference internal" href="interactive.html">13. Interactive Input Editing and History Substitution</a><ul>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#line-editing">13.1. Line Editing</a></li>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#history-substitution">13.2. History Substitution</a></li>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#key-bindings">13.3. Key Bindings</a></li>
<li class="toctree-l2"><a class="reference internal" href="interactive.html#alternatives-to-the-interactive-interpreter">13.4. Alternatives to the Interactive Interpreter</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="floatingpoint.html">14. Floating Point Arithmetic:  Issues and Limitations</a><ul>
<li class="toctree-l2"><a class="reference internal" href="floatingpoint.html#representation-error">14.1. Representation Error</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="appendix.html">15. Appendix</a><ul>
<li class="toctree-l2"><a class="reference internal" href="appendix.html#interactive-mode">15.1. Interactive Mode</a><ul>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#error-handling">15.1.1. Error Handling</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#executable-python-scripts">15.1.2. Executable Python Scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-interactive-startup-file">15.1.3. The Interactive Startup File</a></li>
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-customization-modules">15.1.4. The Customization Modules</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../whatsnew/2.0.html"
                        title="previous chapter">What’s New in Python 2.0</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="appetite.html"
                        title="next chapter">1. Whetting Your Appetite</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             >next</a> |</li>
        <li class="right" >
          <a href="../whatsnew/2.0.html" title="What’s New in Python 2.0"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\I�����html/tutorial/inputoutput.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>7. Input and Output &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="8. Errors and Exceptions" href="errors.html" />
    <link rel="prev" title="6. Modules" href="modules.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/inputoutput.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="input-and-output">
<span id="tut-io"></span><h1>7. Input and Output<a class="headerlink" href="#input-and-output" title="Permalink to this headline">¶</a></h1>
<p>There are several ways to present the output of a program; data can be printed
in a human-readable form, or written to a file for future use. This chapter will
discuss some of the possibilities.</p>
<div class="section" id="fancier-output-formatting">
<span id="tut-formatting"></span><h2>7.1. Fancier Output Formatting<a class="headerlink" href="#fancier-output-formatting" title="Permalink to this headline">¶</a></h2>
<p>So far we’ve encountered two ways of writing values: <em>expression statements</em> and
the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement.  (A third way is using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method
of file objects; the standard output file can be referenced as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.
See the Library Reference for more information on this.)</p>
<p>Often you’ll want more control over the formatting of your output than simply
printing space-separated values.  There are two ways to format your output; the
first way is to do all the string handling yourself; using string slicing and
concatenation operations you can create any layout you can imagine.  The
string types have some methods that perform useful operations for padding
strings to a given column width; these will be discussed shortly.  The second
way is to use the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.</p>
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module contains a <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class which offers
yet another way to substitute values into strings.</p>
<p>One question remains, of course: how do you convert values to strings? Luckily,
Python has ways to convert any value to a string: pass it to the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>
or <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> functions.</p>
<p>The <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function is meant to return representations of values which are
fairly human-readable, while <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> is meant to generate representations
which can be read by the interpreter (or will force a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if
there is no equivalent syntax).  For objects which don’t have a particular
representation for human consumption, <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> will return the same value as
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  Many values, such as numbers or structures like lists and
dictionaries, have the same representation using either function.  Strings and
floating point numbers, in particular, have two distinct representations.</p>
<p>Some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&#39;Hello, world.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">&quot;&#39;Hello, world.&#39;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="mf">1.0</span><span class="o">/</span><span class="mf">7.0</span><span class="p">)</span>
<span class="go">&#39;0.142857142857&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="p">(</span><span class="mf">1.0</span><span class="o">/</span><span class="mf">7.0</span><span class="p">)</span>
<span class="go">&#39;0.14285714285714285&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="mf">3.25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">y</span> <span class="o">=</span> <span class="mi">200</span> <span class="o">*</span> <span class="mi">200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;The value of x is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;, and y is &#39;</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="s1">&#39;...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">s</span>
<span class="go">The value of x is 32.5, and y is 40000...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The repr() of a string adds string quotes and backslashes:</span>
<span class="gp">... </span><span class="n">hello</span> <span class="o">=</span> <span class="s1">&#39;hello, world</span><span class="se">\n</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">hellos</span> <span class="o">=</span> <span class="nb">repr</span><span class="p">(</span><span class="n">hello</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">hellos</span>
<span class="go">&#39;hello, world\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># The argument to repr() may be any Python object:</span>
<span class="gp">... </span><span class="nb">repr</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)))</span>
<span class="go">&quot;(32.5, 40000, (&#39;spam&#39;, &#39;eggs&#39;))&quot;</span>
</pre></div>
</div>
<p>Here are two ways to write a table of squares and cubes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span>
<span class="gp">... </span>    <span class="c1"># Note trailing comma on previous line</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>

<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">11</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">{0:2d}</span><span class="s1"> </span><span class="si">{1:3d}</span><span class="s1"> </span><span class="si">{2:4d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go"> 1   1    1</span>
<span class="go"> 2   4    8</span>
<span class="go"> 3   9   27</span>
<span class="go"> 4  16   64</span>
<span class="go"> 5  25  125</span>
<span class="go"> 6  36  216</span>
<span class="go"> 7  49  343</span>
<span class="go"> 8  64  512</span>
<span class="go"> 9  81  729</span>
<span class="go">10 100 1000</span>
</pre></div>
</div>
<p>(Note that in the first example, one space between each column was added by the
way <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> works: by default it adds spaces between its arguments.)</p>
<p>This example demonstrates the <a class="reference internal" href="../library/stdtypes.html#str.rjust" title="str.rjust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.rjust()</span></code></a> method of string
objects, which right-justifies a string in a field of a given width by padding
it with spaces on the left.  There are similar methods <a class="reference internal" href="../library/stdtypes.html#str.ljust" title="str.ljust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.ljust()</span></code></a> and
<a class="reference internal" href="../library/stdtypes.html#str.center" title="str.center"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.center()</span></code></a>.  These methods do not write anything, they just return a
new string.  If the input string is too long, they don’t truncate it, but
return it unchanged; this will mess up your column lay-out but that’s usually
better than the alternative, which would be lying about a value.  (If you
really want truncation you can always add a slice operation, as in
<code class="docutils literal notranslate"><span class="pre">x.ljust(n)[:n]</span></code>.)</p>
<p>There is another method, <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.zfill()</span></code></a>, which pads a numeric string on the
left with zeros.  It understands about plus and minus signs:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;12&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;00012&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;-3.14&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">&#39;-003.14&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;3.14159265359&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">&#39;3.14159265359&#39;</span>
</pre></div>
</div>
<p>Basic usage of the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;We are the </span><span class="si">{}</span><span class="s1"> who say &quot;</span><span class="si">{}</span><span class="s1">!&quot;&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;knights&#39;</span><span class="p">,</span> <span class="s1">&#39;Ni&#39;</span><span class="p">)</span>
<span class="go">We are the knights who say &quot;Ni!&quot;</span>
</pre></div>
</div>
<p>The brackets and characters within them (called format fields) are replaced with
the objects passed into the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.  A number in the
brackets refers to the position of the object passed into the
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;</span><span class="si">{0}</span><span class="s1"> and </span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span>
<span class="go">spam and eggs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;</span><span class="si">{1}</span><span class="s1"> and </span><span class="si">{0}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="s1">&#39;eggs&#39;</span><span class="p">)</span>
<span class="go">eggs and spam</span>
</pre></div>
</div>
<p>If keyword arguments are used in the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method, their values
are referred to by using the name of the argument.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;This </span><span class="si">{food}</span><span class="s1"> is </span><span class="si">{adjective}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span>      <span class="n">food</span><span class="o">=</span><span class="s1">&#39;spam&#39;</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s1">&#39;absolutely horrible&#39;</span><span class="p">)</span>
<span class="go">This spam is absolutely horrible.</span>
</pre></div>
</div>
<p>Positional and keyword arguments can be arbitrarily combined:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The story of </span><span class="si">{0}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, and </span><span class="si">{other}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Bill&#39;</span><span class="p">,</span> <span class="s1">&#39;Manfred&#39;</span><span class="p">,</span>
<span class="gp">... </span>                                                   <span class="n">other</span><span class="o">=</span><span class="s1">&#39;Georg&#39;</span><span class="p">)</span>
<span class="go">The story of Bill, Manfred, and Georg.</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">'!s'</span></code> (apply <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>) and <code class="docutils literal notranslate"><span class="pre">'!r'</span></code> (apply <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>) can be used to
convert the value before it is formatted.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The value of PI is approximately </span><span class="si">{}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of PI is approximately 3.14159265359.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The value of PI is approximately </span><span class="si">{!r}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of PI is approximately 3.141592653589793.</span>
</pre></div>
</div>
<p>An optional <code class="docutils literal notranslate"><span class="pre">':'</span></code> and format specifier can follow the field name. This allows
greater control over how the value is formatted.  The following example
rounds Pi to three places after the decimal.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The value of PI is approximately </span><span class="si">{0:.3f}</span><span class="s1">.&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
<span class="go">The value of PI is approximately 3.142.</span>
</pre></div>
</div>
<p>Passing an integer after the <code class="docutils literal notranslate"><span class="pre">':'</span></code> will cause that field to be a minimum
number of characters wide.  This is useful for making tables pretty.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">7678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">phone</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">{0:10}</span><span class="s1"> ==&gt; </span><span class="si">{1:10d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">phone</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">Jack       ==&gt;       4098</span>
<span class="go">Dcab       ==&gt;       7678</span>
<span class="go">Sjoerd     ==&gt;       4127</span>
</pre></div>
</div>
<p>If you have a really long format string that you don’t want to split up, it
would be nice if you could reference the variables to be formatted by name
instead of by position.  This can be done by simply passing the dict and using
square brackets <code class="docutils literal notranslate"><span class="pre">'[]'</span></code> to access the keys</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="p">(</span><span class="s1">&#39;Jack: </span><span class="si">{0[Jack]:d}</span><span class="s1">; Sjoerd: </span><span class="si">{0[Sjoerd]:d}</span><span class="s1">; &#39;</span>
<span class="gp">... </span>       <span class="s1">&#39;Dcab: </span><span class="si">{0[Dcab]:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">table</span><span class="p">))</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This could also be done by passing the table as keyword arguments with the ‘**’
notation.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Sjoerd&#39;</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">&#39;Jack&#39;</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">&#39;Dcab&#39;</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;Jack: </span><span class="si">{Jack:d}</span><span class="s1">; Sjoerd: </span><span class="si">{Sjoerd:d}</span><span class="s1">; Dcab: </span><span class="si">{Dcab:d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">)</span>
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
</pre></div>
</div>
<p>This is particularly useful in combination with the built-in function
<a class="reference internal" href="../library/functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>, which returns a dictionary containing all local variables.</p>
<p>For a complete overview of string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, see
<a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
<div class="section" id="old-string-formatting">
<h3>7.1.1. Old string formatting<a class="headerlink" href="#old-string-formatting" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">%</span></code> operator can also be used for string formatting. It interprets the
left argument much like a <code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code>-style format string to be applied
to the right argument, and returns the string resulting from this formatting
operation. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The value of PI is approximately </span><span class="si">%5.3f</span><span class="s1">.&#39;</span> <span class="o">%</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span>
<span class="go">The value of PI is approximately 3.142.</span>
</pre></div>
</div>
<p>More information can be found in the <a class="reference internal" href="../library/stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a> section.</p>
</div>
</div>
<div class="section" id="reading-and-writing-files">
<span id="tut-files"></span><h2>7.2. Reading and Writing Files<a class="headerlink" href="#reading-and-writing-files" title="Permalink to this headline">¶</a></h2>
<p id="index-0"><a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> returns a file object, and is most commonly used with two
arguments: <code class="docutils literal notranslate"><span class="pre">open(filename,</span> <span class="pre">mode)</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">f</span>
<span class="go">&lt;open file &#39;workfile&#39;, mode &#39;w&#39; at 80a0960&gt;</span>
</pre></div>
</div>
<p>The first argument is a string containing the filename.  The second argument is
another string containing a few characters describing the way in which the file
will be used.  <em>mode</em> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> when the file will only be read, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>
for only writing (an existing file with the same name will be erased), and
<code class="docutils literal notranslate"><span class="pre">'a'</span></code> opens the file for appending; any data written to the file is
automatically added to the end.  <code class="docutils literal notranslate"><span class="pre">'r+'</span></code> opens the file for both reading and
writing. The <em>mode</em> argument is optional; <code class="docutils literal notranslate"><span class="pre">'r'</span></code> will be assumed if it’s
omitted.</p>
<p>On Windows, <code class="docutils literal notranslate"><span class="pre">'b'</span></code> appended to the mode opens the file in binary mode, so there
are also modes like <code class="docutils literal notranslate"><span class="pre">'rb'</span></code>, <code class="docutils literal notranslate"><span class="pre">'wb'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'r+b'</span></code>.  Python on Windows makes
a distinction between text and binary files; the end-of-line characters in text
files are automatically altered slightly when data is read or written.  This
behind-the-scenes modification to file data is fine for ASCII text files, but
it’ll corrupt binary data like that in <code class="file docutils literal notranslate"><span class="pre">JPEG</span></code> or <code class="file docutils literal notranslate"><span class="pre">EXE</span></code> files.  Be
very careful to use binary mode when reading and writing such files.  On Unix,
it doesn’t hurt to append a <code class="docutils literal notranslate"><span class="pre">'b'</span></code> to the mode, so you can use it
platform-independently for all binary files.</p>
<div class="section" id="methods-of-file-objects">
<span id="tut-filemethods"></span><h3>7.2.1. Methods of File Objects<a class="headerlink" href="#methods-of-file-objects" title="Permalink to this headline">¶</a></h3>
<p>The rest of the examples in this section will assume that a file object called
<code class="docutils literal notranslate"><span class="pre">f</span></code> has already been created.</p>
<p>To read a file’s contents, call <code class="docutils literal notranslate"><span class="pre">f.read(size)</span></code>, which reads some quantity of
data and returns it as a string.  <em>size</em> is an optional numeric argument.  When
<em>size</em> is omitted or negative, the entire contents of the file will be read and
returned; it’s your problem if the file is twice as large as your machine’s
memory. Otherwise, at most <em>size</em> bytes are read and returned.  If the end of
the file has been reached, <code class="docutils literal notranslate"><span class="pre">f.read()</span></code> will return an empty string (<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code>).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;This is the entire file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> reads a single line from the file; a newline character (<code class="docutils literal notranslate"><span class="pre">\n</span></code>)
is left at the end of the string, and is only omitted on the last line of the
file if the file doesn’t end in a newline.  This makes the return value
unambiguous; if <code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> returns an empty string, the end of the file
has been reached, while a blank line is represented by <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, a string
containing only a single newline.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;This is the first line of the file.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;Second line of the file\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p>For reading lines from a file, you can loop over the file object. This is memory
efficient, fast, and leads to simple code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
<span class="go">        print line,</span>

<span class="go">This is the first line of the file.</span>
<span class="go">Second line of the file</span>
</pre></div>
</div>
<p>If you want to read all the lines of a file in a list you can also use
<code class="docutils literal notranslate"><span class="pre">list(f)</span></code> or <code class="docutils literal notranslate"><span class="pre">f.readlines()</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">f.write(string)</span></code> writes the contents of <em>string</em> to the file, returning
<code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;This is a test</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>To write something other than a string, it needs to be converted to a string
first:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;the answer&#39;</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">f.tell()</span></code> returns an integer giving the file object’s current position in the
file, measured in bytes from the beginning of the file.  To change the file
object’s position, use <code class="docutils literal notranslate"><span class="pre">f.seek(offset,</span> <span class="pre">from_what)</span></code>.  The position is computed
from adding <em>offset</em> to a reference point; the reference point is selected by
the <em>from_what</em> argument.  A <em>from_what</em> value of 0 measures from the beginning
of the file, 1 uses the current file position, and 2 uses the end of the file as
the reference point.  <em>from_what</em> can be omitted and defaults to 0, using the
beginning of the file as the reference point.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;r+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;0123456789abcdef&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>      <span class="c1"># Go to the 6th byte in the file</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;5&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>  <span class="c1"># Go to the 3rd byte before the end</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">&#39;d&#39;</span>
</pre></div>
</div>
<p>When you’re done with a file, call <code class="docutils literal notranslate"><span class="pre">f.close()</span></code> to close it and free up any
system resources taken up by the open file.  After calling <code class="docutils literal notranslate"><span class="pre">f.close()</span></code>,
attempts to use the file object will automatically fail.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">ValueError</span>: <span class="n">I/O operation on closed file</span>
</pre></div>
</div>
<p>It is good practice to use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword when dealing with file
objects.  This has the advantage that the file is properly closed after its
suite finishes, even if an exception is raised on the way.  It is also much
shorter than writing equivalent <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>-<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> blocks:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;workfile&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">read_data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
<span class="go">True</span>
</pre></div>
</div>
<p>File objects have some additional methods, such as <a class="reference internal" href="../library/stdtypes.html#file.isatty" title="file.isatty"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isatty()</span></code></a> and
<a class="reference internal" href="../library/stdtypes.html#file.truncate" title="file.truncate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code></a> which are less frequently used; consult the Library
Reference for a complete guide to file objects.</p>
</div>
<div class="section" id="saving-structured-data-with-json">
<span id="tut-json"></span><h3>7.2.2. Saving structured data with <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a><a class="headerlink" href="#saving-structured-data-with-json" title="Permalink to this headline">¶</a></h3>
<p id="index-1">Strings can easily be written to and read from a file.  Numbers take a bit more
effort, since the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method only returns strings, which will have to
be passed to a function like <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, which takes a string like <code class="docutils literal notranslate"><span class="pre">'123'</span></code>
and returns its numeric value 123.  When you want to save more complex data
types like nested lists and dictionaries, parsing and serializing by hand
becomes complicated.</p>
<p>Rather than having users constantly writing and debugging code to save
complicated data types to files, Python allows you to use the popular data
interchange format called <a class="reference external" href="http://json.org">JSON (JavaScript Object Notation)</a>.  The standard module called <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> can take Python
data hierarchies, and convert them to string representations; this process is
called <em class="dfn">serializing</em>.  Reconstructing the data from the string representation
is called <em class="dfn">deserializing</em>.  Between serializing and deserializing, the
string representing the object may have been stored in a file or data, or
sent over a network connection to some distant machine.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The JSON format is commonly used by modern applications to allow for data
exchange.  Many programmers are already familiar with it, which makes
it a good choice for interoperability.</p>
</div>
<p>If you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code>, you can view its JSON string representation with a
simple line of code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;simple&#39;</span><span class="p">,</span> <span class="s1">&#39;list&#39;</span><span class="p">])</span>
<span class="go">&#39;[1, &quot;simple&quot;, &quot;list&quot;]&#39;</span>
</pre></div>
</div>
<p>Another variant of the <a class="reference internal" href="../library/json.html#json.dumps" title="json.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function, called <a class="reference internal" href="../library/json.html#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>,
simply serializes the object to a file.  So if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>
opened for writing, we can do this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">json</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>To decode the object again, if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> which has
been opened for reading:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>This simple serialization technique can handle lists and dictionaries, but
serializing arbitrary class instances in JSON requires a bit of extra effort.
The reference for the <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module contains an explanation of this.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> - the pickle module</p>
<p class="last">Contrary to <a class="reference internal" href="#tut-json"><span class="std std-ref">JSON</span></a>, <em>pickle</em> is a protocol which allows
the serialization of arbitrarily complex Python objects.  As such, it is
specific to Python and cannot be used to communicate with applications
written in other languages.  It is also insecure by default:
deserializing pickle data coming from an untrusted source can execute
arbitrary code, if the data was crafted by a skilled attacker.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li><a class="reference internal" href="#old-string-formatting">7.1.1. Old string formatting</a></li>
</ul>
</li>
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="modules.html"
                        title="previous chapter">6. Modules</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="errors.html"
                        title="next chapter">8. Errors and Exceptions</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/inputoutput.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="errors.html" title="8. Errors and Exceptions"
             >next</a> |</li>
        <li class="right" >
          <a href="modules.html" title="6. Modules"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��3OOhtml/tutorial/interactive.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>13. Interactive Input Editing and History Substitution &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="14. Floating Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
    <link rel="prev" title="12. What Now?" href="whatnow.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/interactive.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now?"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="interactive-input-editing-and-history-substitution">
<span id="tut-interacting"></span><h1>13. Interactive Input Editing and History Substitution<a class="headerlink" href="#interactive-input-editing-and-history-substitution" title="Permalink to this headline">¶</a></h1>
<p>Some versions of the Python interpreter support editing of the current input
line and history substitution, similar to facilities found in the Korn shell and
the GNU Bash shell.  This is implemented using the <a class="reference external" href="https://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> library,
which supports Emacs-style and vi-style editing.  This library has its own
documentation which I won’t duplicate here; however, the basics are easily
explained.  The interactive editing and history described here are optionally
available in the Unix and Cygwin versions of the interpreter.</p>
<p>This chapter does <em>not</em> document the editing facilities of Mark Hammond’s
PythonWin package or the Tk-based environment, IDLE, distributed with Python.
The command line history recall which operates within DOS boxes on NT and some
other DOS and Windows flavors  is yet another beast.</p>
<div class="section" id="line-editing">
<span id="tut-lineediting"></span><h2>13.1. Line Editing<a class="headerlink" href="#line-editing" title="Permalink to this headline">¶</a></h2>
<p>If supported, input line editing is active whenever the interpreter prints a
primary or secondary prompt.  The current line can be edited using the
conventional Emacs control characters.  The most important of these are:
<kbd class="kbd docutils literal notranslate">C-A</kbd> (Control-A) moves the cursor to the beginning of the line, <kbd class="kbd docutils literal notranslate">C-E</kbd>
to the end, <kbd class="kbd docutils literal notranslate">C-B</kbd> moves it one position to the left, <kbd class="kbd docutils literal notranslate">C-F</kbd> to the
right.  Backspace erases the character to the left of the cursor, <kbd class="kbd docutils literal notranslate">C-D</kbd> the
character to its right. <kbd class="kbd docutils literal notranslate">C-K</kbd> kills (erases) the rest of the line to the
right of the cursor, <kbd class="kbd docutils literal notranslate">C-Y</kbd> yanks back the last killed string.
<kbd class="kbd docutils literal notranslate">C-underscore</kbd> undoes the last change you made; it can be repeated for
cumulative effect.</p>
</div>
<div class="section" id="history-substitution">
<span id="tut-history"></span><h2>13.2. History Substitution<a class="headerlink" href="#history-substitution" title="Permalink to this headline">¶</a></h2>
<p>History substitution works as follows.  All non-empty input lines issued are
saved in a history buffer, and when a new prompt is given you are positioned on
a new line at the bottom of this buffer. <kbd class="kbd docutils literal notranslate">C-P</kbd> moves one line up (back) in
the history buffer, <kbd class="kbd docutils literal notranslate">C-N</kbd> moves one down.  Any line in the history buffer
can be edited; an asterisk appears in front of the prompt to mark a line as
modified.  Pressing the <kbd class="kbd docutils literal notranslate">Return</kbd> key passes the current line to the
interpreter.  <kbd class="kbd docutils literal notranslate">C-R</kbd> starts an incremental reverse search; <kbd class="kbd docutils literal notranslate">C-S</kbd> starts
a forward search.</p>
</div>
<div class="section" id="key-bindings">
<span id="tut-keybindings"></span><h2>13.3. Key Bindings<a class="headerlink" href="#key-bindings" title="Permalink to this headline">¶</a></h2>
<p>The key bindings and some other parameters of the Readline library can be
customized by placing commands in an initialization file called
<code class="file docutils literal notranslate"><span class="pre">~/.inputrc</span></code>.  Key bindings have the form</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">key</span><span class="o">-</span><span class="n">name</span><span class="p">:</span> <span class="n">function</span><span class="o">-</span><span class="n">name</span>
</pre></div>
</div>
<p>or</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;string&quot;</span><span class="p">:</span> <span class="n">function</span><span class="o">-</span><span class="n">name</span>
</pre></div>
</div>
<p>and options can be set with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">set</span> <span class="n">option</span><span class="o">-</span><span class="n">name</span> <span class="n">value</span>
</pre></div>
</div>
<p>For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># I prefer vi-style editing:</span>
<span class="nb">set</span> <span class="n">editing</span><span class="o">-</span><span class="n">mode</span> <span class="n">vi</span>

<span class="c1"># Edit using a single line:</span>
<span class="nb">set</span> <span class="n">horizontal</span><span class="o">-</span><span class="n">scroll</span><span class="o">-</span><span class="n">mode</span> <span class="n">On</span>

<span class="c1"># Rebind some keys:</span>
<span class="n">Meta</span><span class="o">-</span><span class="n">h</span><span class="p">:</span> <span class="n">backward</span><span class="o">-</span><span class="n">kill</span><span class="o">-</span><span class="n">word</span>
<span class="s2">&quot;\C-u&quot;</span><span class="p">:</span> <span class="n">universal</span><span class="o">-</span><span class="n">argument</span>
<span class="s2">&quot;\C-x\C-r&quot;</span><span class="p">:</span> <span class="n">re</span><span class="o">-</span><span class="n">read</span><span class="o">-</span><span class="n">init</span><span class="o">-</span><span class="n">file</span>
</pre></div>
</div>
<p>Note that the default binding for <kbd class="kbd docutils literal notranslate">Tab</kbd> in Python is to insert a <kbd class="kbd docutils literal notranslate">Tab</kbd>
character instead of Readline’s default filename completion function.  If you
insist, you can override this by putting</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Tab</span><span class="p">:</span> <span class="n">complete</span>
</pre></div>
</div>
<p>in your <code class="file docutils literal notranslate"><span class="pre">~/.inputrc</span></code>.  (Of course, this makes it harder to type indented
continuation lines if you’re accustomed to using <kbd class="kbd docutils literal notranslate">Tab</kbd> for that purpose.)</p>
<p id="index-0">Automatic completion of variable and module names is optionally available.  To
enable it in the interpreter’s interactive mode, add the following to your
startup file: <a class="footnote-reference" href="#id2" id="id1">[1]</a></p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">rlcompleter</span><span class="o">,</span> <span class="nn">readline</span>
<span class="n">readline</span><span class="o">.</span><span class="n">parse_and_bind</span><span class="p">(</span><span class="s1">&#39;tab: complete&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This binds the <kbd class="kbd docutils literal notranslate">Tab</kbd> key to the completion function, so hitting the
<kbd class="kbd docutils literal notranslate">Tab</kbd> key twice suggests completions; it looks at Python statement names,
the current local variables, and the available module names.  For dotted
expressions such as <code class="docutils literal notranslate"><span class="pre">string.a</span></code>, it will evaluate the expression up to the
final <code class="docutils literal notranslate"><span class="pre">'.'</span></code> and then suggest completions from the attributes of the resulting
object.  Note that this may execute application-defined code if an object with a
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method is part of the expression.</p>
<p>A more capable startup file might look like this example.  Note that this
deletes the names it creates once they are no longer needed; this is done since
the startup file is executed in the same namespace as the interactive commands,
and removing the names avoids creating side effects in the interactive
environment.  You may find it convenient to keep some of the imported modules,
such as <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>, which turn out to be needed in most sessions with the
interpreter.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Add auto-completion and a stored history file of commands to your Python</span>
<span class="c1"># interactive interpreter. Requires Python 2.0+, readline. Autocomplete is</span>
<span class="c1"># bound to the Esc key by default (you can change it - see readline docs).</span>
<span class="c1">#</span>
<span class="c1"># Store the file in ~/.pystartup, and set an environment variable to point</span>
<span class="c1"># to it:  &quot;export PYTHONSTARTUP=~/.pystartup&quot; in bash.</span>

<span class="kn">import</span> <span class="nn">atexit</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="kn">import</span> <span class="nn">readline</span>
<span class="kn">import</span> <span class="nn">rlcompleter</span>

<span class="n">historyPath</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">expanduser</span><span class="p">(</span><span class="s2">&quot;~/.pyhistory&quot;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">save_history</span><span class="p">(</span><span class="n">historyPath</span><span class="o">=</span><span class="n">historyPath</span><span class="p">):</span>
    <span class="kn">import</span> <span class="nn">readline</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">write_history_file</span><span class="p">(</span><span class="n">historyPath</span><span class="p">)</span>

<span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">historyPath</span><span class="p">):</span>
    <span class="n">readline</span><span class="o">.</span><span class="n">read_history_file</span><span class="p">(</span><span class="n">historyPath</span><span class="p">)</span>

<span class="n">atexit</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">save_history</span><span class="p">)</span>
<span class="k">del</span> <span class="n">os</span><span class="p">,</span> <span class="n">atexit</span><span class="p">,</span> <span class="n">readline</span><span class="p">,</span> <span class="n">rlcompleter</span><span class="p">,</span> <span class="n">save_history</span><span class="p">,</span> <span class="n">historyPath</span>
</pre></div>
</div>
</div>
<div class="section" id="alternatives-to-the-interactive-interpreter">
<span id="tut-commentary"></span><h2>13.4. Alternatives to the Interactive Interpreter<a class="headerlink" href="#alternatives-to-the-interactive-interpreter" title="Permalink to this headline">¶</a></h2>
<p>This facility is an enormous step forward compared to earlier versions of the
interpreter; however, some wishes are left: It would be nice if the proper
indentation were suggested on continuation lines (the parser knows if an indent
token is required next).  The completion mechanism might use the interpreter’s
symbol table.  A command to check (or even suggest) matching parentheses,
quotes, etc., would also be useful.</p>
<p>One alternative enhanced interactive interpreter that has been around for quite
some time is <a class="reference external" href="http://ipython.scipy.org/">IPython</a>, which features tab completion, object exploration and
advanced history management.  It can also be thoroughly customized and embedded
into other applications.  Another similar enhanced interactive environment is
<a class="reference external" href="http://www.bpython-interpreter.org/">bpython</a>.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Python will execute the contents of a file identified by the
<span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> environment variable when you start an interactive
interpreter.  To customize Python even for non-interactive mode, see
<a class="reference internal" href="appendix.html#tut-customize"><span class="std std-ref">The Customization Modules</span></a>.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">13. Interactive Input Editing and History Substitution</a><ul>
<li><a class="reference internal" href="#line-editing">13.1. Line Editing</a></li>
<li><a class="reference internal" href="#history-substitution">13.2. History Substitution</a></li>
<li><a class="reference internal" href="#key-bindings">13.3. Key Bindings</a></li>
<li><a class="reference internal" href="#alternatives-to-the-interactive-interpreter">13.4. Alternatives to the Interactive Interpreter</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="whatnow.html"
                        title="previous chapter">12. What Now?</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="floatingpoint.html"
                        title="next chapter">14. Floating Point Arithmetic:  Issues and Limitations</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/interactive.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="floatingpoint.html" title="14. Floating Point Arithmetic: Issues and Limitations"
             >next</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now?"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��/)�H�Hhtml/tutorial/interpreter.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Using the Python Interpreter &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="3. An Informal Introduction to Python" href="introduction.html" />
    <link rel="prev" title="1. Whetting Your Appetite" href="appetite.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/interpreter.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="using-the-python-interpreter">
<span id="tut-using"></span><h1>2. Using the Python Interpreter<a class="headerlink" href="#using-the-python-interpreter" title="Permalink to this headline">¶</a></h1>
<div class="section" id="invoking-the-interpreter">
<span id="tut-invoking"></span><h2>2.1. Invoking the Interpreter<a class="headerlink" href="#invoking-the-interpreter" title="Permalink to this headline">¶</a></h2>
<p>The Python interpreter is usually installed as <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin/python</span></code> on
those machines where it is available; putting <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin</span></code> in your
Unix shell’s search path makes it possible to start it by typing the command</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span>
</pre></div>
</div>
<p>to the shell.  Since the choice of the directory where the interpreter lives is
an installation option, other places are possible; check with your local Python
guru or system administrator.  (E.g., <code class="file docutils literal notranslate"><span class="pre">/usr/local/python</span></code> is a popular
alternative location.)</p>
<p>On Windows machines, the Python installation is usually placed in
<code class="file docutils literal notranslate"><span class="pre">C:\Python27</span></code>, though you can change this when you’re running the
installer.  To add this directory to your path,  you can type the following
command into the command prompt in a DOS box:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">set</span> <span class="n">path</span><span class="o">=%</span><span class="n">path</span><span class="o">%</span><span class="p">;</span><span class="n">C</span><span class="p">:</span>\<span class="n">python27</span>
</pre></div>
</div>
<p>Typing an end-of-file character (<kbd class="kbd docutils literal notranslate">Control-D</kbd> on Unix, <kbd class="kbd docutils literal notranslate">Control-Z</kbd> on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status.  If that doesn’t work, you can exit the interpreter by typing the
following command: <code class="docutils literal notranslate"><span class="pre">quit()</span></code>.</p>
<p>The interpreter’s line-editing features usually aren’t very sophisticated.  On
Unix, whoever installed the interpreter may have enabled support for the GNU
readline library, which adds more elaborate interactive editing and history
features. Perhaps the quickest check to see whether command line editing is
supported is typing <kbd class="kbd docutils literal notranslate">Control-P</kbd> to the first Python prompt you get.  If it beeps,
you have command line editing; see Appendix <a class="reference internal" href="interactive.html#tut-interacting"><span class="std std-ref">Interactive Input Editing and History Substitution</span></a> for an
introduction to the keys.  If nothing appears to happen, or if <code class="docutils literal notranslate"><span class="pre">^P</span></code> is echoed,
command line editing isn’t available; you’ll only be able to use backspace to
remove characters from the current line.</p>
<p>The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a <em>script</em> from that file.</p>
<p>A second way of starting the interpreter is <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>,
which executes the statement(s) in <em>command</em>, analogous to the shell’s
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option.  Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
<em>command</em> in its entirety with single quotes.</p>
<p>Some Python modules are also useful as scripts.  These can be invoked using
<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>, which executes the source file for <em>module</em> as
if you had spelled out its full name on the command line.</p>
<p>When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards.  This can be done by passing <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a>
before the script.</p>
<p>All command-line options are described in <a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a>.</p>
<div class="section" id="argument-passing">
<span id="tut-argpassing"></span><h3>2.1.1. Argument Passing<a class="headerlink" href="#argument-passing" title="Permalink to this headline">¶</a></h3>
<p>When known to the interpreter, the script name and additional arguments
thereafter are turned into a list of strings and assigned to the <code class="docutils literal notranslate"><span class="pre">argv</span></code>
variable in the <code class="docutils literal notranslate"><span class="pre">sys</span></code> module.  You can access this list by executing <code class="docutils literal notranslate"><span class="pre">import</span>
<span class="pre">sys</span></code>.  The length of the list is at least one; when no script and no arguments
are given, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is an empty string.  When the script name is given as
<code class="docutils literal notranslate"><span class="pre">'-'</span></code> (meaning  standard input), <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-'</span></code>.  When
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>.  When
<a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> <em>module</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>  is set to the full name of the
located module.  Options found after  <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> or <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a>
<em>module</em> are not consumed  by the Python interpreter’s option processing but
left in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> for  the command or module to handle.</p>
</div>
<div class="section" id="interactive-mode">
<span id="tut-interactive"></span><h3>2.1.2. Interactive Mode<a class="headerlink" href="#interactive-mode" title="Permalink to this headline">¶</a></h3>
<p>When commands are read from a tty, the interpreter is said to be in <em>interactive
mode</em>.  In this mode it prompts for the next command with the <em>primary prompt</em>,
usually three greater-than signs (<code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>); for continuation lines it prompts
with the <em>secondary prompt</em>, by default three dots (<code class="docutils literal notranslate"><span class="pre">...</span></code>). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="go">python</span>
<span class="go">Python 2.7 (#1, Feb 28 2010, 00:02:06)</span>
<span class="go">Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.</span>
<span class="gp">&gt;</span>&gt;&gt;
</pre></div>
</div>
<p>Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">the_world_is_flat</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">the_world_is_flat</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s2">&quot;Be careful not to fall off!&quot;</span>
<span class="gp">...</span>
<span class="go">Be careful not to fall off!</span>
</pre></div>
</div>
<p>For more on interactive mode, see <a class="reference internal" href="appendix.html#tut-interac"><span class="std std-ref">Interactive Mode</span></a>.</p>
</div>
</div>
<div class="section" id="the-interpreter-and-its-environment">
<span id="tut-interp"></span><h2>2.2. The Interpreter and Its Environment<a class="headerlink" href="#the-interpreter-and-its-environment" title="Permalink to this headline">¶</a></h2>
<div class="section" id="source-code-encoding">
<span id="tut-source-encoding"></span><h3>2.2.1. Source Code Encoding<a class="headerlink" href="#source-code-encoding" title="Permalink to this headline">¶</a></h3>
<p>By default, Python source files are treated as encoded in ASCII.
To declare an encoding other than the default one, a special comment line
should be added as the <em>first</em> line of the file.  The syntax is as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: encoding -*-</span>
</pre></div>
</div>
<p>where <em>encoding</em> is one of the valid <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> supported by Python.</p>
<p>For example, to declare that Windows-1252 encoding is to be used, the first
line of your source code file should be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: cp1252 -*-</span>
</pre></div>
</div>
<p>One exception to the <em>first line</em> rule is when the source code starts with a
<a class="reference internal" href="appendix.html#tut-scripts"><span class="std std-ref">UNIX “shebang” line</span></a>.  In this case, the encoding
declaration should be added as the second line of the file.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: cp1252 -*-</span>
</pre></div>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Using the Python Interpreter</a><ul>
<li><a class="reference internal" href="#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li><a class="reference internal" href="#argument-passing">2.1.1. Argument Passing</a></li>
<li><a class="reference internal" href="#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li><a class="reference internal" href="#source-code-encoding">2.2.1. Source Code Encoding</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="appetite.html"
                        title="previous chapter">1. Whetting Your Appetite</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="introduction.html"
                        title="next chapter">3. An Informal Introduction to Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/interpreter.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             >next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��}]]html/tutorial/introduction.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>3. An Informal Introduction to Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. More Control Flow Tools" href="controlflow.html" />
    <link rel="prev" title="2. Using the Python Interpreter" href="interpreter.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/introduction.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="controlflow.html" title="4. More Control Flow Tools"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="interpreter.html" title="2. Using the Python Interpreter"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="an-informal-introduction-to-python">
<span id="tut-informal"></span><h1>3. An Informal Introduction to Python<a class="headerlink" href="#an-informal-introduction-to-python" title="Permalink to this headline">¶</a></h1>
<p>In the following examples, input and output are distinguished by the presence or
absence of prompts (<a class="reference internal" href="../glossary.html#term"><span class="xref std std-term">&gt;&gt;&gt;</span></a> and <a class="reference internal" href="../glossary.html#term-1"><span class="xref std std-term">…</span></a>): to repeat the example, you must type
everything after the prompt, when the prompt appears; lines that do not begin
with a prompt are output from the interpreter. Note that a secondary prompt on a
line by itself in an example means you must type a blank line; this is used to
end a multi-line command.</p>
<p>Many of the examples in this manual, even those entered at the interactive
prompt, include comments.  Comments in Python start with the hash character,
<code class="docutils literal notranslate"><span class="pre">#</span></code>, and extend to the end of the physical line.  A comment may appear at the
start of a line or following whitespace or code, but not within a string
literal.  A hash character within a string literal is just a hash character.
Since comments are to clarify code and are not interpreted by Python, they may
be omitted when typing in examples.</p>
<p>Some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># this is the first comment</span>
<span class="n">spam</span> <span class="o">=</span> <span class="mi">1</span>  <span class="c1"># and this is the second comment</span>
          <span class="c1"># ... and now a third!</span>
<span class="n">text</span> <span class="o">=</span> <span class="s2">&quot;# This is not a comment because it&#39;s inside quotes.&quot;</span>
</pre></div>
</div>
<div class="section" id="using-python-as-a-calculator">
<span id="tut-calculator"></span><h2>3.1. Using Python as a Calculator<a class="headerlink" href="#using-python-as-a-calculator" title="Permalink to this headline">¶</a></h2>
<p>Let’s try some simple Python commands.  Start the interpreter and wait for the
primary prompt, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;&gt;</span></code>.  (It shouldn’t take long.)</p>
<div class="section" id="numbers">
<span id="tut-numbers"></span><h3>3.1.1. Numbers<a class="headerlink" href="#numbers" title="Permalink to this headline">¶</a></h3>
<p>The interpreter acts as a simple calculator: you can type an expression at it
and it will write the value.  Expression syntax is straightforward: the
operators <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> work just like in most other languages
(for example, Pascal or C); parentheses (<code class="docutils literal notranslate"><span class="pre">()</span></code>) can be used for grouping.
For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span> <span class="o">+</span> <span class="mi">2</span>
<span class="go">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">50</span> <span class="o">-</span> <span class="mi">5</span><span class="o">*</span><span class="mi">6</span>
<span class="go">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mi">50</span> <span class="o">-</span> <span class="mf">5.0</span><span class="o">*</span><span class="mi">6</span><span class="p">)</span> <span class="o">/</span> <span class="mi">4</span>
<span class="go">5.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">8</span> <span class="o">/</span> <span class="mf">5.0</span>
<span class="go">1.6</span>
</pre></div>
</div>
<p>The integer numbers (e.g. <code class="docutils literal notranslate"><span class="pre">2</span></code>, <code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">20</span></code>) have type <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>,
the ones with a fractional part (e.g. <code class="docutils literal notranslate"><span class="pre">5.0</span></code>, <code class="docutils literal notranslate"><span class="pre">1.6</span></code>) have type
<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>.  We will see more about numeric types later in the tutorial.</p>
<p>The return type of a division (<code class="docutils literal notranslate"><span class="pre">/</span></code>) operation depends on its operands.  If
both operands are of type <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../glossary.html#term-floor-division"><span class="xref std std-term">floor division</span></a> is performed
and an <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> is returned.  If either operand is a <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>,
classic division is performed and a <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> is returned.  The <code class="docutils literal notranslate"><span class="pre">//</span></code>
operator is also provided for doing floor division no matter what the
operands are.  The remainder can be calculated with the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">/</span> <span class="mi">3</span>  <span class="c1"># int / int -&gt; int</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">/</span> <span class="mf">3.0</span>  <span class="c1"># int / float -&gt; float</span>
<span class="go">5.666666666666667</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">//</span> <span class="mf">3.0</span>  <span class="c1"># explicit floor division discards the fractional part</span>
<span class="go">5.0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">17</span> <span class="o">%</span> <span class="mi">3</span>  <span class="c1"># the % operator returns the remainder of the division</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">5</span> <span class="o">*</span> <span class="mi">3</span> <span class="o">+</span> <span class="mi">2</span>  <span class="c1"># result * divisor + remainder</span>
<span class="go">17</span>
</pre></div>
</div>
<p>With Python, it is possible to use the <code class="docutils literal notranslate"><span class="pre">**</span></code> operator to calculate powers <a class="footnote-reference" href="#id3" id="id1">[1]</a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">5</span> <span class="o">**</span> <span class="mi">2</span>  <span class="c1"># 5 squared</span>
<span class="go">25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span> <span class="o">**</span> <span class="mi">7</span>  <span class="c1"># 2 to the power of 7</span>
<span class="go">128</span>
</pre></div>
</div>
<p>The equal sign (<code class="docutils literal notranslate"><span class="pre">=</span></code>) is used to assign a value to a variable. Afterwards, no
result is displayed before the next interactive prompt:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">height</span> <span class="o">=</span> <span class="mi">5</span> <span class="o">*</span> <span class="mi">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">*</span> <span class="n">height</span>
<span class="go">900</span>
</pre></div>
</div>
<p>If a variable is not “defined” (assigned a value), trying to use it will
give you an error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span>  <span class="c1"># try to access an undefined variable</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">NameError</span>: <span class="n">name &#39;n&#39; is not defined</span>
</pre></div>
</div>
<p>There is full support for floating point; operators with mixed type operands
convert the integer operand to floating point:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">3</span> <span class="o">*</span> <span class="mf">3.75</span> <span class="o">/</span> <span class="mf">1.5</span>
<span class="go">7.5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">7.0</span> <span class="o">/</span> <span class="mi">2</span>
<span class="go">3.5</span>
</pre></div>
</div>
<p>In interactive mode, the last printed expression is assigned to the variable
<code class="docutils literal notranslate"><span class="pre">_</span></code>.  This means that when you are using Python as a desk calculator, it is
somewhat easier to continue calculations, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">tax</span> <span class="o">=</span> <span class="mf">12.5</span> <span class="o">/</span> <span class="mi">100</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">=</span> <span class="mf">100.50</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">*</span> <span class="n">tax</span>
<span class="go">12.5625</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">price</span> <span class="o">+</span> <span class="n">_</span>
<span class="go">113.0625</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">113.06</span>
</pre></div>
</div>
<p>This variable should be treated as read-only by the user.  Don’t explicitly
assign a value to it — you would create an independent local variable with the
same name masking the built-in variable with its magic behavior.</p>
<p>In addition to <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, Python supports other types of
numbers, such as <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> and <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a>.
Python also has built-in support for <a class="reference internal" href="../library/stdtypes.html#typesnumeric"><span class="std std-ref">complex numbers</span></a>,
and uses the <code class="docutils literal notranslate"><span class="pre">j</span></code> or <code class="docutils literal notranslate"><span class="pre">J</span></code> suffix to indicate the imaginary part
(e.g. <code class="docutils literal notranslate"><span class="pre">3+5j</span></code>).</p>
</div>
<div class="section" id="strings">
<span id="tut-strings"></span><h3>3.1.2. Strings<a class="headerlink" href="#strings" title="Permalink to this headline">¶</a></h3>
<p>Besides numbers, Python can also manipulate strings, which can be expressed
in several ways.  They can be enclosed in single quotes (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) or
double quotes (<code class="docutils literal notranslate"><span class="pre">&quot;...&quot;</span></code>) with the same result <a class="footnote-reference" href="#id4" id="id2">[2]</a>.  <code class="docutils literal notranslate"><span class="pre">\</span></code> can be used
to escape quotes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;spam eggs&#39;</span>  <span class="c1"># single quotes</span>
<span class="go">&#39;spam eggs&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;doesn</span><span class="se">\&#39;</span><span class="s1">t&#39;</span>  <span class="c1"># use \&#39; to escape the single quote...</span>
<span class="go">&quot;doesn&#39;t&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;doesn&#39;t&quot;</span>  <span class="c1"># ...or use double quotes instead</span>
<span class="go">&quot;doesn&#39;t&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;</span><span class="se">\&quot;</span><span class="s2">Yes,</span><span class="se">\&quot;</span><span class="s2"> they said.&quot;</span>
<span class="go">&#39;&quot;Yes,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Isn\&#39;t,&quot; they said.&#39;</span>
</pre></div>
</div>
<p>In the interactive interpreter, the output string is enclosed in quotes and
special characters are escaped with backslashes.  While this might sometimes
look different from the input (the enclosing quotes could change), the two
strings are equivalent.  The string is enclosed in double quotes if
the string contains a single quote and no double quotes, otherwise it is
enclosed in single quotes.  The <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement produces a more
readable output, by omitting the enclosing quotes and by printing escaped
and special characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span>
<span class="go">&#39;&quot;Isn\&#39;t,&quot; they said.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;&quot;Isn</span><span class="se">\&#39;</span><span class="s1">t,&quot; they said.&#39;</span>
<span class="go">&quot;Isn&#39;t,&quot; they said.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;First line.</span><span class="se">\n</span><span class="s1">Second line.&#39;</span>  <span class="c1"># \n means newline</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span>  <span class="c1"># without print, \n is included in the output</span>
<span class="go">&#39;First line.\nSecond line.&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">s</span>  <span class="c1"># with print, \n produces a new line</span>
<span class="go">First line.</span>
<span class="go">Second line.</span>
</pre></div>
</div>
<p>If you don’t want characters prefaced by <code class="docutils literal notranslate"><span class="pre">\</span></code> to be interpreted as
special characters, you can use <em>raw strings</em> by adding an <code class="docutils literal notranslate"><span class="pre">r</span></code> before
the first quote:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;C:\some</span><span class="se">\n</span><span class="s1">ame&#39;</span>  <span class="c1"># here \n means newline!</span>
<span class="go">C:\some</span>
<span class="go">ame</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="sa">r</span><span class="s1">&#39;C:\some\name&#39;</span>  <span class="c1"># note the r before the quote</span>
<span class="go">C:\some\name</span>
</pre></div>
</div>
<p>String literals can span multiple lines.  One way is using triple-quotes:
<code class="docutils literal notranslate"><span class="pre">&quot;&quot;&quot;...&quot;&quot;&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">'''...'''</span></code>.  End of lines are automatically
included in the string, but it’s possible to prevent this by adding a <code class="docutils literal notranslate"><span class="pre">\</span></code> at
the end of the line.  The following example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="s2">&quot;&quot;&quot;</span><span class="se">\</span>
<span class="s2">Usage: thingy [OPTIONS]</span>
<span class="s2">     -h                        Display this usage message</span>
<span class="s2">     -H hostname               Hostname to connect to</span>
<span class="s2">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>produces the following output (note that the initial newline is not included):</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
</pre></div>
</div>
<p>Strings can be concatenated (glued together) with the <code class="docutils literal notranslate"><span class="pre">+</span></code> operator, and
repeated with <code class="docutils literal notranslate"><span class="pre">*</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># 3 times &#39;un&#39;, followed by &#39;ium&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">3</span> <span class="o">*</span> <span class="s1">&#39;un&#39;</span> <span class="o">+</span> <span class="s1">&#39;ium&#39;</span>
<span class="go">&#39;unununium&#39;</span>
</pre></div>
</div>
<p>Two or more <em>string literals</em> (i.e. the ones enclosed between quotes) next
to each other are automatically concatenated.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Py&#39;</span> <span class="s1">&#39;thon&#39;</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>This feature is particularly useful when you want to break long strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">text</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;Put several strings within parentheses &#39;</span>
<span class="gp">... </span>        <span class="s1">&#39;to have them joined together.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">text</span>
<span class="go">&#39;Put several strings within parentheses to have them joined together.&#39;</span>
</pre></div>
</div>
<p>This only works with two literals though, not with variables or expressions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="o">=</span> <span class="s1">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="s1">&#39;thon&#39;</span>  <span class="c1"># can&#39;t concatenate a variable and a string literal</span>
<span class="go">  ...</span>
<span class="go">SyntaxError: invalid syntax</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;un&#39;</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)</span> <span class="s1">&#39;ium&#39;</span>
<span class="go">  ...</span>
<span class="go">SyntaxError: invalid syntax</span>
</pre></div>
</div>
<p>If you want to concatenate variables or a variable and a literal, use <code class="docutils literal notranslate"><span class="pre">+</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">prefix</span> <span class="o">+</span> <span class="s1">&#39;thon&#39;</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>Strings can be <em>indexed</em> (subscripted), with the first character having index 0.
There is no separate character type; a character is simply a string of size
one:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span> <span class="o">=</span> <span class="s1">&#39;Python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  <span class="c1"># character in position 0</span>
<span class="go">&#39;P&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span>  <span class="c1"># character in position 5</span>
<span class="go">&#39;n&#39;</span>
</pre></div>
</div>
<p>Indices may also be negative numbers, to start counting from the right:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>  <span class="c1"># last character</span>
<span class="go">&#39;n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span>  <span class="c1"># second-last character</span>
<span class="go">&#39;o&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">6</span><span class="p">]</span>
<span class="go">&#39;P&#39;</span>
</pre></div>
</div>
<p>Note that since -0 is the same as 0, negative indices start from -1.</p>
<p>In addition to indexing, <em>slicing</em> is also supported.  While indexing is used
to obtain individual characters, <em>slicing</em> allows you to obtain a substring:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span>  <span class="c1"># characters from position 0 (included) to 2 (excluded)</span>
<span class="go">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>  <span class="c1"># characters from position 2 (included) to 5 (excluded)</span>
<span class="go">&#39;tho&#39;</span>
</pre></div>
</div>
<p>Note how the start is always included, and the end always excluded.  This
makes sure that <code class="docutils literal notranslate"><span class="pre">s[:i]</span> <span class="pre">+</span> <span class="pre">s[i:]</span></code> is always equal to <code class="docutils literal notranslate"><span class="pre">s</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span>
<span class="go">&#39;Python&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">4</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span>
<span class="go">&#39;Python&#39;</span>
</pre></div>
</div>
<p>Slice indices have useful defaults; an omitted first index defaults to zero, an
omitted second index defaults to the size of the string being sliced.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span>   <span class="c1"># character from the beginning to position 2 (excluded)</span>
<span class="go">&#39;Py&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span>   <span class="c1"># characters from position 4 (included) to the end</span>
<span class="go">&#39;on&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">:]</span>  <span class="c1"># characters from the second-last (included) to the end</span>
<span class="go">&#39;on&#39;</span>
</pre></div>
</div>
<p>One way to remember how slices work is to think of the indices as pointing
<em>between</em> characters, with the left edge of the first character numbered 0.
Then the right edge of the last character of a string of <em>n</em> characters has
index <em>n</em>, for example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span> <span class="o">+---+---+---+---+---+---+</span>
 <span class="o">|</span> <span class="n">P</span> <span class="o">|</span> <span class="n">y</span> <span class="o">|</span> <span class="n">t</span> <span class="o">|</span> <span class="n">h</span> <span class="o">|</span> <span class="n">o</span> <span class="o">|</span> <span class="n">n</span> <span class="o">|</span>
 <span class="o">+---+---+---+---+---+---+</span>
 <span class="mi">0</span>   <span class="mi">1</span>   <span class="mi">2</span>   <span class="mi">3</span>   <span class="mi">4</span>   <span class="mi">5</span>   <span class="mi">6</span>
<span class="o">-</span><span class="mi">6</span>  <span class="o">-</span><span class="mi">5</span>  <span class="o">-</span><span class="mi">4</span>  <span class="o">-</span><span class="mi">3</span>  <span class="o">-</span><span class="mi">2</span>  <span class="o">-</span><span class="mi">1</span>
</pre></div>
</div>
<p>The first row of numbers gives the position of the indices 0…6 in the string;
the second row gives the corresponding negative indices. The slice from <em>i</em> to
<em>j</em> consists of all characters between the edges labeled <em>i</em> and <em>j</em>,
respectively.</p>
<p>For non-negative indices, the length of a slice is the difference of the
indices, if both are within bounds.  For example, the length of <code class="docutils literal notranslate"><span class="pre">word[1:3]</span></code> is
2.</p>
<p>Attempting to use an index that is too large will result in an error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">]</span>  <span class="c1"># the word only has 6 characters</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">IndexError</span>: <span class="n">string index out of range</span>
</pre></div>
</div>
<p>However, out of range slice indexes are handled gracefully when used for
slicing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:</span><span class="mi">42</span><span class="p">]</span>
<span class="go">&#39;on&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">:]</span>
<span class="go">&#39;&#39;</span>
</pre></div>
</div>
<p>Python strings cannot be changed — they are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>.
Therefore, assigning to an indexed position in the string results in an error:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;J&#39;</span>
<span class="go">  ...</span>
<span class="go">TypeError: &#39;str&#39; object does not support item assignment</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span> <span class="o">=</span> <span class="s1">&#39;py&#39;</span>
<span class="go">  ...</span>
<span class="go">TypeError: &#39;str&#39; object does not support item assignment</span>
</pre></div>
</div>
<p>If you need a different string, you should create a new one:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;J&#39;</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
<span class="go">&#39;Jython&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="s1">&#39;py&#39;</span>
<span class="go">&#39;Pypy&#39;</span>
</pre></div>
</div>
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the length of a string:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;supercalifragilisticexpialidocious&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">34</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/stdtypes.html#typesseq"><span class="std std-ref">Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange</span></a></dt>
<dd>Strings, and the Unicode strings described in the next section, are
examples of <em>sequence types</em>, and support the common operations supported
by such types.</dd>
<dt><a class="reference internal" href="../library/stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a></dt>
<dd>Both strings and Unicode strings support a large number of methods for
basic transformations and searching.</dd>
<dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt>
<dd>Information about string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.</dd>
<dt><a class="reference internal" href="../library/stdtypes.html#string-formatting"><span class="std std-ref">String Formatting Operations</span></a></dt>
<dd>The old formatting operations invoked when strings and Unicode strings are
the left operand of the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator are described in more detail here.</dd>
</dl>
</div>
</div>
<div class="section" id="unicode-strings">
<span id="tut-unicodestrings"></span><h3>3.1.3. Unicode Strings<a class="headerlink" href="#unicode-strings" title="Permalink to this headline">¶</a></h3>
<p>Starting with Python 2.0 a new data type for storing text data is available to
the programmer: the Unicode object. It can be used to store and manipulate
Unicode data (see <a class="reference external" href="http://www.unicode.org/">http://www.unicode.org/</a>) and integrates well with the existing
string objects, providing auto-conversions where necessary.</p>
<p>Unicode has the advantage of providing one ordinal for every character in every
script used in modern and ancient texts. Previously, there were only 256
possible ordinals for script characters. Texts were typically bound to a code
page which mapped the ordinals to script characters. This lead to very much
confusion especially with respect to internationalization (usually written as
<code class="docutils literal notranslate"><span class="pre">i18n</span></code> — <code class="docutils literal notranslate"><span class="pre">'i'</span></code> + 18 characters + <code class="docutils literal notranslate"><span class="pre">'n'</span></code>) of software.  Unicode solves
these problems by defining one code page for all scripts.</p>
<p>Creating Unicode strings in Python is just as simple as creating normal
strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s1">&#39;Hello World !&#39;</span>
<span class="go">u&#39;Hello World !&#39;</span>
</pre></div>
</div>
<p>The small <code class="docutils literal notranslate"><span class="pre">'u'</span></code> in front of the quote indicates that a Unicode string is
supposed to be created. If you want to include special characters in the string,
you can do so by using the Python <em>Unicode-Escape</em> encoding. The following
example shows how:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s1">&#39;Hello</span><span class="se">\u0020</span><span class="s1">World !&#39;</span>
<span class="go">u&#39;Hello World !&#39;</span>
</pre></div>
</div>
<p>The escape sequence <code class="docutils literal notranslate"><span class="pre">\u0020</span></code> indicates to insert the Unicode character with
the ordinal value 0x0020 (the space character) at the given position.</p>
<p>Other characters are interpreted by using their respective ordinal values
directly as Unicode ordinals.  If you have literal strings in the standard
Latin-1 encoding that is used in many Western countries, you will find it
convenient that the lower 256 characters of Unicode are the same as the 256
characters of Latin-1.</p>
<p>For experts, there is also a raw mode just like the one for normal strings. You
have to prefix the opening quote with ‘ur’ to have Python use the
<em>Raw-Unicode-Escape</em> encoding. It will only apply the above <code class="docutils literal notranslate"><span class="pre">\uXXXX</span></code>
conversion if there is an uneven number of backslashes in front of the small
‘u’.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">ur</span><span class="s1">&#39;Hello\u0020World !&#39;</span>
<span class="go">u&#39;Hello World !&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">ur</span><span class="s1">&#39;Hello</span><span class="se">\\</span><span class="s1">u0020World !&#39;</span>
<span class="go">u&#39;Hello\\\\u0020World !&#39;</span>
</pre></div>
</div>
<p>The raw mode is most useful when you have to enter lots of backslashes, as can
be necessary in regular expressions.</p>
<p>Apart from these standard encodings, Python provides a whole set of other ways
of creating Unicode strings on the basis of a known encoding.</p>
<p id="index-0">The built-in function <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> provides access to all registered Unicode
codecs (COders and DECoders). Some of the more well known encodings which these
codecs can convert are <em>Latin-1</em>, <em>ASCII</em>, <em>UTF-8</em>, and <em>UTF-16</em>. The latter two
are variable-length encodings that store each Unicode character in one or more
bytes. The default encoding is normally set to ASCII, which passes through
characters in the range 0 to 127 and rejects any other characters with an error.
When a Unicode string is printed, written to a file, or converted with
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>, conversion takes place using this default encoding.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s2">&quot;abc&quot;</span>
<span class="go">u&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="sa">u</span><span class="s2">&quot;abc&quot;</span><span class="p">)</span>
<span class="go">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s2">&quot;äöü&quot;</span>
<span class="go">u&#39;\xe4\xf6\xfc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">str</span><span class="p">(</span><span class="sa">u</span><span class="s2">&quot;äöü&quot;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">UnicodeEncodeError</span>: <span class="n">&#39;ascii&#39; codec can&#39;t encode characters in position 0-2: ordinal not in range(128)</span>
</pre></div>
</div>
<p>To convert a Unicode string into an 8-bit string using a specific encoding,
Unicode objects provide an <code class="xref py py-func docutils literal notranslate"><span class="pre">encode()</span></code> method that takes one argument, the
name of the encoding.  Lowercase names for encodings are preferred.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s2">&quot;äöü&quot;</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="go">&#39;\xc3\xa4\xc3\xb6\xc3\xbc&#39;</span>
</pre></div>
</div>
<p>If you have data in a specific encoding and want to produce a corresponding
Unicode string from it, you can use the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> function with the
encoding name as the second argument.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="s1">&#39;</span><span class="se">\xc3\xa4\xc3\xb6\xc3\xbc</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="go">u&#39;\xe4\xf6\xfc&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="lists">
<span id="tut-lists"></span><h3>3.1.4. Lists<a class="headerlink" href="#lists" title="Permalink to this headline">¶</a></h3>
<p>Python knows a number of <em>compound</em> data types, used to group together other
values.  The most versatile is the <em>list</em>, which can be written as a list of
comma-separated values (items) between square brackets.  Lists might contain
items of different types, but usually the items all have the same type.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">25</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span>
<span class="go">[1, 4, 9, 16, 25]</span>
</pre></div>
</div>
<p>Like strings (and all other built-in <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> type), lists can be
indexed and sliced:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>  <span class="c1"># indexing returns the item</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">25</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">:]</span>  <span class="c1"># slicing returns a new list</span>
<span class="go">[9, 16, 25]</span>
</pre></div>
</div>
<p>All slice operations return a new list containing the requested elements.  This
means that the following slice returns a new (shallow) copy of the list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span><span class="p">[:]</span>
<span class="go">[1, 4, 9, 16, 25]</span>
</pre></div>
</div>
<p>Lists also supports operations like concatenation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">squares</span> <span class="o">+</span> <span class="p">[</span><span class="mi">36</span><span class="p">,</span> <span class="mi">49</span><span class="p">,</span> <span class="mi">64</span><span class="p">,</span> <span class="mi">81</span><span class="p">,</span> <span class="mi">100</span><span class="p">]</span>
<span class="go">[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</span>
</pre></div>
</div>
<p>Unlike strings, which are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, lists are a <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>
type, i.e. it is possible to change their content:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">27</span><span class="p">,</span> <span class="mi">65</span><span class="p">,</span> <span class="mi">125</span><span class="p">]</span>  <span class="c1"># something&#39;s wrong here</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">4</span> <span class="o">**</span> <span class="mi">3</span>  <span class="c1"># the cube of 4 is 64, not 65!</span>
<span class="go">64</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">64</span>  <span class="c1"># replace the wrong value</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span>
<span class="go">[1, 8, 27, 64, 125]</span>
</pre></div>
</div>
<p>You can also add new items at the end of the list, by using
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> <em>method</em> (we will see more about methods later):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">216</span><span class="p">)</span>  <span class="c1"># add the cube of 6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span> <span class="o">**</span> <span class="mi">3</span><span class="p">)</span>  <span class="c1"># and the cube of 7</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cubes</span>
<span class="go">[1, 8, 27, 64, 125, 216, 343]</span>
</pre></div>
</div>
<p>Assignment to slices is also possible, and this can even change the size of the
list or clear it entirely:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="s1">&#39;e&#39;</span><span class="p">,</span> <span class="s1">&#39;f&#39;</span><span class="p">,</span> <span class="s1">&#39;g&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># replace some values</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;C&#39;</span><span class="p">,</span> <span class="s1">&#39;D&#39;</span><span class="p">,</span> <span class="s1">&#39;E&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># now remove them</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;f&#39;, &#39;g&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># clear the list by replacing all the elements with an empty list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> also applies to lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;d&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">letters</span><span class="p">)</span>
<span class="go">4</span>
</pre></div>
</div>
<p>It is possible to nest lists (create lists containing other lists), for
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span> <span class="n">n</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">[[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;], [1, 2, 3]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;b&#39;</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="first-steps-towards-programming">
<span id="tut-firststeps"></span><h2>3.2. First Steps Towards Programming<a class="headerlink" href="#first-steps-towards-programming" title="Permalink to this headline">¶</a></h2>
<p>Of course, we can use Python for more complicated tasks than adding two and two
together.  For instance, we can write an initial sub-sequence of the <em>Fibonacci</em>
series as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Fibonacci series:</span>
<span class="gp">... </span><span class="c1"># the sum of two elements defines the next</span>
<span class="gp">... </span><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">b</span> <span class="o">&lt;</span> <span class="mi">10</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">b</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">...</span>
<span class="go">1</span>
<span class="go">1</span>
<span class="go">2</span>
<span class="go">3</span>
<span class="go">5</span>
<span class="go">8</span>
</pre></div>
</div>
<p>This example introduces several new features.</p>
<ul>
<li><p class="first">The first line contains a <em>multiple assignment</em>: the variables <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>
simultaneously get the new values 0 and 1.  On the last line this is used again,
demonstrating that the expressions on the right-hand side are all evaluated
first before any of the assignments take place.  The right-hand side expressions
are evaluated  from the left to the right.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop executes as long as the condition (here: <code class="docutils literal notranslate"><span class="pre">b</span> <span class="pre">&lt;</span> <span class="pre">10</span></code>)
remains true.  In Python, like in C, any non-zero integer value is true; zero is
false.  The condition may also be a string or list value, in fact any sequence;
anything with a non-zero length is true, empty sequences are false.  The test
used in the example is a simple comparison.  The standard comparison operators
are written the same as in C: <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> (less than), <code class="docutils literal notranslate"><span class="pre">&gt;</span></code> (greater than), <code class="docutils literal notranslate"><span class="pre">==</span></code>
(equal to), <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> (less than or equal to), <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> (greater than or equal to)
and <code class="docutils literal notranslate"><span class="pre">!=</span></code> (not equal to).</p>
</li>
<li><p class="first">The <em>body</em> of the loop is <em>indented</em>: indentation is Python’s way of grouping
statements.  At the interactive prompt, you have to type a tab or space(s) for
each indented line.  In practice you will prepare more complicated input
for Python with a text editor; all decent text editors have an auto-indent
facility.  When a compound statement is entered interactively, it must be
followed by a blank line to indicate completion (since the parser cannot
guess when you have typed the last line).  Note that each line within a basic
block must be indented by the same amount.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement writes the value of the expression(s) it is
given.  It differs from just writing the expression you want to write (as we did
earlier in the calculator examples) in the way it handles multiple expressions
and strings.  Strings are printed without quotes, and a space is inserted
between items, so you can format things nicely, like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="mi">256</span><span class="o">*</span><span class="mi">256</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;The value of i is&#39;</span><span class="p">,</span> <span class="n">i</span>
<span class="go">The value of i is 65536</span>
</pre></div>
</div>
<p>A trailing comma avoids the newline after the output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">while</span> <span class="n">b</span> <span class="o">&lt;</span> <span class="mi">1000</span><span class="p">:</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">b</span><span class="p">,</span>
<span class="gp">... </span>    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="gp">...</span>
<span class="go">1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987</span>
</pre></div>
</div>
<p>Note that the interpreter inserts a newline before it prints the next prompt if
the last line was not completed.</p>
</li>
</ul>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id3" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>Since <code class="docutils literal notranslate"><span class="pre">**</span></code> has higher precedence than <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">-3**2</span></code> will be
interpreted as <code class="docutils literal notranslate"><span class="pre">-(3**2)</span></code> and thus result in <code class="docutils literal notranslate"><span class="pre">-9</span></code>.  To avoid this
and get <code class="docutils literal notranslate"><span class="pre">9</span></code>, you can use <code class="docutils literal notranslate"><span class="pre">(-3)**2</span></code>.</td></tr>
</tbody>
</table>
<table class="docutils footnote" frame="void" id="id4" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id2">[2]</a></td><td>Unlike other languages, special characters such as <code class="docutils literal notranslate"><span class="pre">\n</span></code> have the
same meaning with both single (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) and double (<code class="docutils literal notranslate"><span class="pre">&quot;...&quot;</span></code>) quotes.
The only difference between the two is that within single quotes you don’t
need to escape <code class="docutils literal notranslate"><span class="pre">&quot;</span></code> (but you have to escape <code class="docutils literal notranslate"><span class="pre">\'</span></code>) and vice versa.</td></tr>
</tbody>
</table>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. An Informal Introduction to Python</a><ul>
<li><a class="reference internal" href="#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
<li><a class="reference internal" href="#numbers">3.1.1. Numbers</a></li>
<li><a class="reference internal" href="#strings">3.1.2. Strings</a></li>
<li><a class="reference internal" href="#unicode-strings">3.1.3. Unicode Strings</a></li>
<li><a class="reference internal" href="#lists">3.1.4. Lists</a></li>
</ul>
</li>
<li><a class="reference internal" href="#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="interpreter.html"
                        title="previous chapter">2. Using the Python Interpreter</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="controlflow.html"
                        title="next chapter">4. More Control Flow Tools</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/introduction.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="controlflow.html" title="4. More Control Flow Tools"
             >next</a> |</li>
        <li class="right" >
          <a href="interpreter.html" title="2. Using the Python Interpreter"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\!�q,����html/tutorial/modules.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>6. Modules &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="7. Input and Output" href="inputoutput.html" />
    <link rel="prev" title="5. Data Structures" href="datastructures.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/modules.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="modules">
<span id="tut-modules"></span><h1>6. Modules<a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h1>
<p>If you quit from the Python interpreter and enter it again, the definitions you
have made (functions and variables) are lost. Therefore, if you want to write a
somewhat longer program, you are better off using a text editor to prepare the
input for the interpreter and running it with that file as input instead.  This
is known as creating a <em>script</em>.  As your program gets longer, you may want to
split it into several files for easier maintenance.  You may also want to use a
handy function that you’ve written in several programs without copying its
definition into each program.</p>
<p>To support this, Python has a way to put definitions in a file and use them in a
script or in an interactive instance of the interpreter. Such a file is called a
<em>module</em>; definitions from a module can be <em>imported</em> into other modules or into
the <em>main</em> module (the collection of variables that you have access to in a
script executed at the top level and in calculator mode).</p>
<p>A module is a file containing Python definitions and statements.  The file name
is the module name with the suffix <code class="file docutils literal notranslate"><span class="pre">.py</span></code> appended.  Within a module, the
module’s name (as a string) is available as the value of the global variable
<code class="docutils literal notranslate"><span class="pre">__name__</span></code>.  For instance, use your favorite text editor to create a file
called <code class="file docutils literal notranslate"><span class="pre">fibo.py</span></code> in the current directory with the following contents:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Fibonacci numbers module</span>

<span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>    <span class="c1"># write Fibonacci series up to n</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">b</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">b</span><span class="p">,</span>
        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>

<span class="k">def</span> <span class="nf">fib2</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>   <span class="c1"># return Fibonacci series up to n</span>
    <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
    <span class="k">while</span> <span class="n">b</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
        <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
        <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
    <span class="k">return</span> <span class="n">result</span>
</pre></div>
</div>
<p>Now enter the Python interpreter and import this module with the following
command:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
</pre></div>
</div>
<p>This does not enter the names of the functions defined in <code class="docutils literal notranslate"><span class="pre">fibo</span></code>  directly in
the current symbol table; it only enters the module name <code class="docutils literal notranslate"><span class="pre">fibo</span></code> there. Using
the module name you can access the functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
<span class="go">1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="n">fib2</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="go">[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="vm">__name__</span>
<span class="go">&#39;fibo&#39;</span>
</pre></div>
</div>
<p>If you intend to use a function often you can assign it to a local name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<div class="section" id="more-on-modules">
<span id="tut-moremodules"></span><h2>6.1. More on Modules<a class="headerlink" href="#more-on-modules" title="Permalink to this headline">¶</a></h2>
<p>A module can contain executable statements as well as function definitions.
These statements are intended to initialize the module. They are executed only
the <em>first</em> time the module name is encountered in an import statement. <a class="footnote-reference" href="#id2" id="id1">[1]</a>
(They are also run if the file is executed as a script.)</p>
<p>Each module has its own private symbol table, which is used as the global symbol
table by all functions defined in the module. Thus, the author of a module can
use global variables in the module without worrying about accidental clashes
with a user’s global variables. On the other hand, if you know what you are
doing you can touch a module’s global variables with the same notation used to
refer to its functions, <code class="docutils literal notranslate"><span class="pre">modname.itemname</span></code>.</p>
<p>Modules can import other modules.  It is customary but not required to place all
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements at the beginning of a module (or script, for that
matter).  The imported module names are placed in the importing module’s global
symbol table.</p>
<p>There is a variant of the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement that imports names from a
module directly into the importing module’s symbol table.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This does not introduce the module name from which the imports are taken in the
local symbol table (so in the example, <code class="docutils literal notranslate"><span class="pre">fibo</span></code> is not defined).</p>
<p>There is even a variant to import all names that a module defines:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This imports all names except those beginning with an underscore (<code class="docutils literal notranslate"><span class="pre">_</span></code>).</p>
<p>Note that in general the practice of importing <code class="docutils literal notranslate"><span class="pre">*</span></code> from a module or package is
frowned upon, since it often causes poorly readable code. However, it is okay to
use it to save typing in interactive sessions.</p>
<p>If the module name is followed by <a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a>, then the name
following <a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> is bound directly to the imported module.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span> <span class="k">as</span> <span class="nn">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<p>This is effectively importing the module in the same way that <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">fibo</span></code>
will do, with the only difference of it being available as <code class="docutils literal notranslate"><span class="pre">fib</span></code>.</p>
<p>It can also be used when utilising <a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> with similar effects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="k">import</span> <span class="n">fib</span> <span class="k">as</span> <span class="n">fibonacci</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fibonacci</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">For efficiency reasons, each module is only imported once per interpreter
session.  Therefore, if you change your modules, you must restart the
interpreter – or, if it’s just one module you want to test interactively,
use <a class="reference internal" href="../library/functions.html#reload" title="reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">reload()</span></code></a>, e.g. <code class="docutils literal notranslate"><span class="pre">reload(modulename)</span></code>.</p>
</div>
<div class="section" id="executing-modules-as-scripts">
<span id="tut-modulesasscripts"></span><h3>6.1.1. Executing modules as scripts<a class="headerlink" href="#executing-modules-as-scripts" title="Permalink to this headline">¶</a></h3>
<p>When you run a Python module with</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">fibo</span><span class="o">.</span><span class="n">py</span> <span class="o">&lt;</span><span class="n">arguments</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>the code in the module will be executed, just as if you imported it, but with
the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> set to <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>.  That means that by adding this code at
the end of your module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">sys</span>
    <span class="n">fib</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
</pre></div>
</div>
<p>you can make the file usable as a script as well as an importable module,
because the code that parses the command line only runs if the module is
executed as the “main” file:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> python fibo.py <span class="m">50</span>
<span class="go">1 1 2 3 5 8 13 21 34</span>
</pre></div>
</div>
<p>If the module is imported, the code is not run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>This is often used either to provide a convenient user interface to a module, or
for testing purposes (running the module as a script executes a test suite).</p>
</div>
<div class="section" id="the-module-search-path">
<span id="tut-searchpath"></span><h3>6.1.2. The Module Search Path<a class="headerlink" href="#the-module-search-path" title="Permalink to this headline">¶</a></h3>
<p id="index-0">When a module named <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> is imported, the interpreter first searches for
a built-in module with that name. If not found, it then searches for a file
named <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> in a list of directories given by the variable
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.  <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is initialized from these locations:</p>
<ul class="simple">
<li>the directory containing the input script (or the current directory).</li>
<li><span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> (a list of directory names, with the same syntax as the
shell variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>).</li>
<li>the installation-dependent default.</li>
</ul>
<p>After initialization, Python programs can modify <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.  The
directory containing the script being run is placed at the beginning of the
search path, ahead of the standard library path. This means that scripts in that
directory will be loaded instead of modules of the same name in the library
directory. This is an error unless the replacement is intended.  See section
<a class="reference internal" href="#tut-standardmodules"><span class="std std-ref">Standard Modules</span></a> for more information.</p>
</div>
<div class="section" id="compiled-python-files">
<h3>6.1.3. “Compiled” Python files<a class="headerlink" href="#compiled-python-files" title="Permalink to this headline">¶</a></h3>
<p>As an important speed-up of the start-up time for short programs that use a lot
of standard modules, if a file called <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> exists in the directory
where <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> is found, this is assumed to contain an
already-“byte-compiled” version of the module <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code>. The modification time
of the version of <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> used to create <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> is recorded in
<code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code>, and the <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> file is ignored if these don’t match.</p>
<p>Normally, you don’t need to do anything to create the <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> file.
Whenever <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> is successfully compiled, an attempt is made to write
the compiled version to <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code>.  It is not an error if this attempt
fails; if for any reason the file is not written completely, the resulting
<code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> file will be recognized as invalid and thus ignored later.  The
contents of the <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> file are platform independent, so a Python
module directory can be shared by machines of different architectures.</p>
<p>Some tips for experts:</p>
<ul>
<li><p class="first">When the Python interpreter is invoked with the <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> flag, optimized
code is generated and stored in <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files.  The optimizer currently
doesn’t help much; it only removes <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statements.  When
<a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> is used, <em>all</em> <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> is optimized; <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files are
ignored and <code class="docutils literal notranslate"><span class="pre">.py</span></code> files are compiled to optimized bytecode.</p>
</li>
<li><p class="first">Passing two <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> flags to the Python interpreter (<a class="reference internal" href="../using/cmdline.html#cmdoption-oo"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a>) will
cause the bytecode compiler to perform optimizations that could in some rare
cases result in malfunctioning programs.  Currently only <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> strings are
removed from the bytecode, resulting in more compact <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files.  Since
some programs may rely on having these available, you should only use this
option if you know what you’re doing.</p>
</li>
<li><p class="first">A program doesn’t run any faster when it is read from a <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or
<code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> file than when it is read from a <code class="file docutils literal notranslate"><span class="pre">.py</span></code> file; the only thing
that’s faster about <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files is the speed with which
they are loaded.</p>
</li>
<li><p class="first">When a script is run by giving its name on the command line, the bytecode for
the script is never written to a <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> file.  Thus, the
startup time of a script may be reduced by moving most of its code to a module
and having a small bootstrap script that imports that module.  It is also
possible to name a <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> file directly on the command
line.</p>
</li>
<li><p class="first">It is possible to have a file called <code class="file docutils literal notranslate"><span class="pre">spam.pyc</span></code> (or <code class="file docutils literal notranslate"><span class="pre">spam.pyo</span></code>
when <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> is used) without a file <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> for the same module.
This can be used to distribute a library of Python code in a form that is
moderately hard to reverse engineer.</p>
</li>
<li id="index-3"><p class="first">The module <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> can create <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files (or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code>
files when <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> is used) for all modules in a directory.</p>
</li>
</ul>
</div>
</div>
<div class="section" id="standard-modules">
<span id="tut-standardmodules"></span><h2>6.2. Standard Modules<a class="headerlink" href="#standard-modules" title="Permalink to this headline">¶</a></h2>
<p id="index-4">Python comes with a library of standard modules, described in a separate
document, the Python Library Reference (“Library Reference” hereafter).  Some
modules are built into the interpreter; these provide access to operations that
are not part of the core of the language but are nevertheless built in, either
for efficiency or to provide access to operating system primitives such as
system calls.  The set of such modules is a configuration option which also
depends on the underlying platform.  For example, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">winreg</span></code> module is only
provided on Windows systems. One particular module deserves some attention:
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, which is built into every Python interpreter.  The variables
<code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code> define the strings used as primary and secondary
prompts:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span>
<span class="go">&#39;&gt;&gt;&gt; &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps2</span>
<span class="go">&#39;... &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span> <span class="o">=</span> <span class="s1">&#39;C&gt; &#39;</span>
<span class="go">C&gt; print &#39;Yuck!&#39;</span>
<span class="go">Yuck!</span>
<span class="go">C&gt;</span>
</pre></div>
</div>
<p>These two variables are only defined if the interpreter is in interactive mode.</p>
<p>The variable <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is a list of strings that determines the interpreter’s
search path for modules. It is initialized to a default path taken from the
environment variable <span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>, or from a built-in default if
<span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is not set.  You can modify it using standard list
operations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;/ufs/guido/lib/python&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-dir-function">
<span id="tut-dir"></span><h2>6.3. The <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> Function<a class="headerlink" href="#the-dir-function" title="Permalink to this headline">¶</a></h2>
<p>The built-in function <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> is used to find out which names a module
defines.  It returns a sorted list of strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span><span class="o">,</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">fibo</span><span class="p">)</span>
<span class="go">[&#39;__name__&#39;, &#39;fib&#39;, &#39;fib2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>  
<span class="go">[&#39;__displayhook__&#39;, &#39;__doc__&#39;, &#39;__excepthook__&#39;, &#39;__name__&#39;, &#39;__package__&#39;,</span>
<span class="go"> &#39;__stderr__&#39;, &#39;__stdin__&#39;, &#39;__stdout__&#39;, &#39;_clear_type_cache&#39;,</span>
<span class="go"> &#39;_current_frames&#39;, &#39;_getframe&#39;, &#39;_mercurial&#39;, &#39;api_version&#39;, &#39;argv&#39;,</span>
<span class="go"> &#39;builtin_module_names&#39;, &#39;byteorder&#39;, &#39;call_tracing&#39;, &#39;callstats&#39;,</span>
<span class="go"> &#39;copyright&#39;, &#39;displayhook&#39;, &#39;dont_write_bytecode&#39;, &#39;exc_clear&#39;, &#39;exc_info&#39;,</span>
<span class="go"> &#39;exc_traceback&#39;, &#39;exc_type&#39;, &#39;exc_value&#39;, &#39;excepthook&#39;, &#39;exec_prefix&#39;,</span>
<span class="go"> &#39;executable&#39;, &#39;exit&#39;, &#39;flags&#39;, &#39;float_info&#39;, &#39;float_repr_style&#39;,</span>
<span class="go"> &#39;getcheckinterval&#39;, &#39;getdefaultencoding&#39;, &#39;getdlopenflags&#39;,</span>
<span class="go"> &#39;getfilesystemencoding&#39;, &#39;getobjects&#39;, &#39;getprofile&#39;, &#39;getrecursionlimit&#39;,</span>
<span class="go"> &#39;getrefcount&#39;, &#39;getsizeof&#39;, &#39;gettotalrefcount&#39;, &#39;gettrace&#39;, &#39;hexversion&#39;,</span>
<span class="go"> &#39;long_info&#39;, &#39;maxint&#39;, &#39;maxsize&#39;, &#39;maxunicode&#39;, &#39;meta_path&#39;, &#39;modules&#39;,</span>
<span class="go"> &#39;path&#39;, &#39;path_hooks&#39;, &#39;path_importer_cache&#39;, &#39;platform&#39;, &#39;prefix&#39;, &#39;ps1&#39;,</span>
<span class="go"> &#39;py3kwarning&#39;, &#39;setcheckinterval&#39;, &#39;setdlopenflags&#39;, &#39;setprofile&#39;,</span>
<span class="go"> &#39;setrecursionlimit&#39;, &#39;settrace&#39;, &#39;stderr&#39;, &#39;stdin&#39;, &#39;stdout&#39;, &#39;subversion&#39;,</span>
<span class="go"> &#39;version&#39;, &#39;version_info&#39;, &#39;warnoptions&#39;]</span>
</pre></div>
</div>
<p>Without arguments, <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> lists the names you have defined currently:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">()</span>
<span class="go">[&#39;__builtins__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;a&#39;, &#39;fib&#39;, &#39;fibo&#39;, &#39;sys&#39;]</span>
</pre></div>
</div>
<p>Note that it lists all types of names: variables, modules, functions, etc.</p>
<p id="index-7"><a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> does not list the names of built-in functions and variables.  If you
want a list of those, they are defined in the standard module
<a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">__builtin__</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">__builtin__</span><span class="p">)</span>  
<span class="go">[&#39;ArithmeticError&#39;, &#39;AssertionError&#39;, &#39;AttributeError&#39;, &#39;BaseException&#39;,</span>
<span class="go"> &#39;BufferError&#39;, &#39;BytesWarning&#39;, &#39;DeprecationWarning&#39;, &#39;EOFError&#39;,</span>
<span class="go"> &#39;Ellipsis&#39;, &#39;EnvironmentError&#39;, &#39;Exception&#39;, &#39;False&#39;, &#39;FloatingPointError&#39;,</span>
<span class="go"> &#39;FutureWarning&#39;, &#39;GeneratorExit&#39;, &#39;IOError&#39;, &#39;ImportError&#39;, &#39;ImportWarning&#39;,</span>
<span class="go"> &#39;IndentationError&#39;, &#39;IndexError&#39;, &#39;KeyError&#39;, &#39;KeyboardInterrupt&#39;,</span>
<span class="go"> &#39;LookupError&#39;, &#39;MemoryError&#39;, &#39;NameError&#39;, &#39;None&#39;, &#39;NotImplemented&#39;,</span>
<span class="go"> &#39;NotImplementedError&#39;, &#39;OSError&#39;, &#39;OverflowError&#39;,</span>
<span class="go"> &#39;PendingDeprecationWarning&#39;, &#39;ReferenceError&#39;, &#39;RuntimeError&#39;,</span>
<span class="go"> &#39;RuntimeWarning&#39;, &#39;StandardError&#39;, &#39;StopIteration&#39;, &#39;SyntaxError&#39;,</span>
<span class="go"> &#39;SyntaxWarning&#39;, &#39;SystemError&#39;, &#39;SystemExit&#39;, &#39;TabError&#39;, &#39;True&#39;,</span>
<span class="go"> &#39;TypeError&#39;, &#39;UnboundLocalError&#39;, &#39;UnicodeDecodeError&#39;,</span>
<span class="go"> &#39;UnicodeEncodeError&#39;, &#39;UnicodeError&#39;, &#39;UnicodeTranslateError&#39;,</span>
<span class="go"> &#39;UnicodeWarning&#39;, &#39;UserWarning&#39;, &#39;ValueError&#39;, &#39;Warning&#39;,</span>
<span class="go"> &#39;ZeroDivisionError&#39;, &#39;_&#39;, &#39;__debug__&#39;, &#39;__doc__&#39;, &#39;__import__&#39;,</span>
<span class="go"> &#39;__name__&#39;, &#39;__package__&#39;, &#39;abs&#39;, &#39;all&#39;, &#39;any&#39;, &#39;apply&#39;, &#39;basestring&#39;,</span>
<span class="go"> &#39;bin&#39;, &#39;bool&#39;, &#39;buffer&#39;, &#39;bytearray&#39;, &#39;bytes&#39;, &#39;callable&#39;, &#39;chr&#39;,</span>
<span class="go"> &#39;classmethod&#39;, &#39;cmp&#39;, &#39;coerce&#39;, &#39;compile&#39;, &#39;complex&#39;, &#39;copyright&#39;,</span>
<span class="go"> &#39;credits&#39;, &#39;delattr&#39;, &#39;dict&#39;, &#39;dir&#39;, &#39;divmod&#39;, &#39;enumerate&#39;, &#39;eval&#39;,</span>
<span class="go"> &#39;execfile&#39;, &#39;exit&#39;, &#39;file&#39;, &#39;filter&#39;, &#39;float&#39;, &#39;format&#39;, &#39;frozenset&#39;,</span>
<span class="go"> &#39;getattr&#39;, &#39;globals&#39;, &#39;hasattr&#39;, &#39;hash&#39;, &#39;help&#39;, &#39;hex&#39;, &#39;id&#39;, &#39;input&#39;,</span>
<span class="go"> &#39;int&#39;, &#39;intern&#39;, &#39;isinstance&#39;, &#39;issubclass&#39;, &#39;iter&#39;, &#39;len&#39;, &#39;license&#39;,</span>
<span class="go"> &#39;list&#39;, &#39;locals&#39;, &#39;long&#39;, &#39;map&#39;, &#39;max&#39;, &#39;memoryview&#39;, &#39;min&#39;, &#39;next&#39;,</span>
<span class="go"> &#39;object&#39;, &#39;oct&#39;, &#39;open&#39;, &#39;ord&#39;, &#39;pow&#39;, &#39;print&#39;, &#39;property&#39;, &#39;quit&#39;,</span>
<span class="go"> &#39;range&#39;, &#39;raw_input&#39;, &#39;reduce&#39;, &#39;reload&#39;, &#39;repr&#39;, &#39;reversed&#39;, &#39;round&#39;,</span>
<span class="go"> &#39;set&#39;, &#39;setattr&#39;, &#39;slice&#39;, &#39;sorted&#39;, &#39;staticmethod&#39;, &#39;str&#39;, &#39;sum&#39;, &#39;super&#39;,</span>
<span class="go"> &#39;tuple&#39;, &#39;type&#39;, &#39;unichr&#39;, &#39;unicode&#39;, &#39;vars&#39;, &#39;xrange&#39;, &#39;zip&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="packages">
<span id="tut-packages"></span><h2>6.4. Packages<a class="headerlink" href="#packages" title="Permalink to this headline">¶</a></h2>
<p>Packages are a way of structuring Python’s module namespace by using “dotted
module names”.  For example, the module name <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B</span></code> designates a submodule
named <code class="docutils literal notranslate"><span class="pre">B</span></code> in a package named <code class="docutils literal notranslate"><span class="pre">A</span></code>.  Just like the use of modules saves the
authors of different modules from having to worry about each other’s global
variable names, the use of dotted module names saves the authors of multi-module
packages like NumPy or Pillow from having to worry about
each other’s module names.</p>
<p>Suppose you want to design a collection of modules (a “package”) for the uniform
handling of sound files and sound data.  There are many different sound file
formats (usually recognized by their extension, for example: <code class="file docutils literal notranslate"><span class="pre">.wav</span></code>,
<code class="file docutils literal notranslate"><span class="pre">.aiff</span></code>, <code class="file docutils literal notranslate"><span class="pre">.au</span></code>), so you may need to create and maintain a growing
collection of modules for the conversion between the various file formats.
There are also many different operations you might want to perform on sound data
(such as mixing, adding echo, applying an equalizer function, creating an
artificial stereo effect), so in addition you will be writing a never-ending
stream of modules to perform these operations.  Here’s a possible structure for
your package (expressed in terms of a hierarchical filesystem):</p>
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...
</pre></div>
</div>
<p>When importing the package, Python searches through the directories on
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> looking for the package subdirectory.</p>
<p>The <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> files are required to make Python treat the directories
as containing packages; this is done to prevent directories with a common name,
such as <code class="docutils literal notranslate"><span class="pre">string</span></code>, from unintentionally hiding valid modules that occur later
on the module search path. In the simplest case, <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> can just be
an empty file, but it can also execute initialization code for the package or
set the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> variable, described later.</p>
<p>Users of the package can import individual modules from the package, for
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
</pre></div>
</div>
<p>This loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects.echo</span></code>.  It must be referenced with
its full name.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sound</span><span class="o">.</span><span class="n">effects</span><span class="o">.</span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>An alternative way of importing the submodule is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects</span> <span class="k">import</span> <span class="n">echo</span>
</pre></div>
</div>
<p>This also loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, and makes it available without its
package prefix, so it can be used as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Yet another variation is to import the desired function or variable directly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects.echo</span> <span class="k">import</span> <span class="n">echofilter</span>
</pre></div>
</div>
<p>Again, this loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, but this makes its function
<code class="xref py py-func docutils literal notranslate"><span class="pre">echofilter()</span></code> directly available:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that when using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">item</span></code>, the item can be either a
submodule (or subpackage) of the package, or some  other name defined in the
package, like a function, class or variable.  The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement first
tests whether the item is defined in the package; if not, it assumes it is a
module and attempts to load it.  If it fails to find it, an <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>
exception is raised.</p>
<p>Contrarily, when using syntax like <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">item.subitem.subsubitem</span></code>, each item
except for the last must be a package; the last item can be a module or a
package but can’t be a class or function or variable defined in the previous
item.</p>
<div class="section" id="importing-from-a-package">
<span id="tut-pkg-import-star"></span><h3>6.4.1. Importing * From a Package<a class="headerlink" href="#importing-from-a-package" title="Permalink to this headline">¶</a></h3>
<p id="index-8">Now what happens when the user writes <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>?  Ideally,
one would hope that this somehow goes out to the filesystem, finds which
submodules are present in the package, and imports them all.  This could take a
long time and importing sub-modules might have unwanted side-effects that should
only happen when the sub-module is explicitly imported.</p>
<p>The only solution is for the package author to provide an explicit index of the
package.  The <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement uses the following convention: if a package’s
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> code defines a list named <code class="docutils literal notranslate"><span class="pre">__all__</span></code>, it is taken to be the
list of module names that should be imported when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">*</span></code> is
encountered.  It is up to the package author to keep this list up-to-date when a
new version of the package is released.  Package authors may also decide not to
support it, if they don’t see a use for importing * from their package.  For
example, the file <code class="file docutils literal notranslate"><span class="pre">sound/effects/__init__.py</span></code> could contain the following
code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="s2">&quot;surround&quot;</span><span class="p">,</span> <span class="s2">&quot;reverse&quot;</span><span class="p">]</span>
</pre></div>
</div>
<p>This would mean that <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code> would import the three
named submodules of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound</span></code> package.</p>
<p>If <code class="docutils literal notranslate"><span class="pre">__all__</span></code> is not defined, the statement <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>
does <em>not</em> import all submodules from the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> into the
current namespace; it only ensures that the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> has
been imported (possibly running any initialization code in <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>)
and then imports whatever names are defined in the package.  This includes any
names defined (and submodules explicitly loaded) by <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>.  It
also includes any submodules of the package that were explicitly loaded by
previous <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements.  Consider this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
<span class="kn">import</span> <span class="nn">sound.effects.surround</span>
<span class="kn">from</span> <span class="nn">sound.effects</span> <span class="k">import</span> <span class="o">*</span>
</pre></div>
</div>
<p>In this example, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> modules are imported in the
current namespace because they are defined in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package
when the <code class="docutils literal notranslate"><span class="pre">from...import</span></code> statement is executed.  (This also works when
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> is defined.)</p>
<p>Although certain modules are designed to export only names that follow certain
patterns when you use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">*</span></code>, it is still considered bad practice in
production code.</p>
<p>Remember, there is nothing wrong with using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">Package</span> <span class="pre">import</span>
<span class="pre">specific_submodule</span></code>!  In fact, this is the recommended notation unless the
importing module needs to use submodules with the same name from different
packages.</p>
</div>
<div class="section" id="intra-package-references">
<h3>6.4.2. Intra-package References<a class="headerlink" href="#intra-package-references" title="Permalink to this headline">¶</a></h3>
<p>The submodules often need to refer to each other.  For example, the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> module might use the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> module.  In fact, such
references are so common that the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement first looks in the
containing package before looking in the standard module search path. Thus, the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> module can simply use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">echo</span></code> or <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">echo</span> <span class="pre">import</span>
<span class="pre">echofilter</span></code>.  If the imported module is not found in the current package (the
package of which the current module is a submodule), the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>
statement looks for a top-level module with the given name.</p>
<p>When packages are structured into subpackages (as with the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound</span></code> package
in the example), you can use absolute imports to refer to submodules of siblings
packages.  For example, if the module <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.filters.vocoder</span></code> needs to use
the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> module in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package, it can use <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">echo</span></code>.</p>
<p>Starting with Python 2.5, in addition to the implicit relative imports described
above, you can write explicit relative imports with the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span>
<span class="pre">name</span></code> form of import statement. These explicit relative imports use leading
dots to indicate the current and parent packages involved in the relative
import. From the <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> module for example, you might use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">echo</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="k">import</span> <span class="n">formats</span>
<span class="kn">from</span> <span class="nn">..filters</span> <span class="k">import</span> <span class="n">equalizer</span>
</pre></div>
</div>
<p>Note that both explicit and implicit relative imports are based on the name of
the current module. Since the name of the main module is always <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>,
modules intended for use as the main module of a Python application should
always use absolute imports.</p>
</div>
<div class="section" id="packages-in-multiple-directories">
<h3>6.4.3. Packages in Multiple Directories<a class="headerlink" href="#packages-in-multiple-directories" title="Permalink to this headline">¶</a></h3>
<p>Packages support one more special attribute, <code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code>.  This is
initialized to be a list containing the name of the directory holding the
package’s <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> before the code in that file is executed.  This
variable can be modified; doing so affects future searches for modules and
subpackages contained in the package.</p>
<p>While this feature is not often needed, it can be used to extend the set of
modules found in a package.</p>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>In fact function definitions are also ‘statements’ that are ‘executed’; the
execution of a module-level function definition enters the function name in
the module’s global symbol table.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">6. Modules</a><ul>
<li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
<li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
<li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
<li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
</ul>
</li>
<li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
<li><a class="reference internal" href="#the-dir-function">6.3. The <code class="docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
<li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
<li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
<li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
<li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="datastructures.html"
                        title="previous chapter">5. Data Structures</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="inputoutput.html"
                        title="next chapter">7. Input and Output</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/modules.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="inputoutput.html" title="7. Input and Output"
             >next</a> |</li>
        <li class="right" >
          <a href="datastructures.html" title="5. Data Structures"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�������html/tutorial/stdlib.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>10. Brief Tour of the Standard Library &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
    <link rel="prev" title="9. Classes" href="classes.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/stdlib.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="brief-tour-of-the-standard-library">
<span id="tut-brieftour"></span><h1>10. Brief Tour of the Standard Library<a class="headerlink" href="#brief-tour-of-the-standard-library" title="Permalink to this headline">¶</a></h1>
<div class="section" id="operating-system-interface">
<span id="tut-os-interface"></span><h2>10.1. Operating System Interface<a class="headerlink" href="#operating-system-interface" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module provides dozens of functions for interacting with the
operating system:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">()</span>      <span class="c1"># Return the current working directory</span>
<span class="go">&#39;C:\\Python26&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s1">&#39;/server/accesslogs&#39;</span><span class="p">)</span>   <span class="c1"># Change current working directory</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s1">&#39;mkdir today&#39;</span><span class="p">)</span>   <span class="c1"># Run the command mkdir in the system shell</span>
<span class="go">0</span>
</pre></div>
</div>
<p>Be sure to use the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">os</span></code> style instead of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">os</span> <span class="pre">import</span> <span class="pre">*</span></code>.  This
will keep <a class="reference internal" href="../library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> from shadowing the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function which
operates much differently.</p>
<p id="index-0">The built-in <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> and <a class="reference internal" href="../library/functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> functions are useful as interactive
aids for working with large modules like <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">os</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
<span class="go">&lt;returns a list of all module functions&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">help</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
<span class="go">&lt;returns an extensive manual page created from the module&#39;s docstrings&gt;</span>
</pre></div>
</div>
<p>For daily file and directory management tasks, the <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module provides
a higher level interface that is easier to use:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">shutil</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shutil</span><span class="o">.</span><span class="n">copyfile</span><span class="p">(</span><span class="s1">&#39;data.db&#39;</span><span class="p">,</span> <span class="s1">&#39;archive.db&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">shutil</span><span class="o">.</span><span class="n">move</span><span class="p">(</span><span class="s1">&#39;/build/executables&#39;</span><span class="p">,</span> <span class="s1">&#39;installdir&#39;</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="file-wildcards">
<span id="tut-file-wildcards"></span><h2>10.2. File Wildcards<a class="headerlink" href="#file-wildcards" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> module provides a function for making file lists from directory
wildcard searches:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">glob</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">&#39;*.py&#39;</span><span class="p">)</span>
<span class="go">[&#39;primes.py&#39;, &#39;random.py&#39;, &#39;quote.py&#39;]</span>
</pre></div>
</div>
</div>
<div class="section" id="command-line-arguments">
<span id="tut-command-line-arguments"></span><h2>10.3. Command Line Arguments<a class="headerlink" href="#command-line-arguments" title="Permalink to this headline">¶</a></h2>
<p>Common utility scripts often need to process command line arguments. These
arguments are stored in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module’s <em>argv</em> attribute as a list.  For
instance the following output results from running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">demo.py</span> <span class="pre">one</span> <span class="pre">two</span>
<span class="pre">three</span></code> at the command line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span>
<span class="go">[&#39;demo.py&#39;, &#39;one&#39;, &#39;two&#39;, &#39;three&#39;]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module processes <em>sys.argv</em> using the conventions of the Unix
<a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> function.  More powerful and flexible command line processing is
provided by the <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module.</p>
</div>
<div class="section" id="error-output-redirection-and-program-termination">
<span id="tut-stderr"></span><h2>10.4. Error Output Redirection and Program Termination<a class="headerlink" href="#error-output-redirection-and-program-termination" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module also has attributes for <em>stdin</em>, <em>stdout</em>, and <em>stderr</em>.
The latter is useful for emitting warnings and error messages to make them
visible even when <em>stdout</em> has been redirected:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;Warning, log file not found starting a new one</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">Warning, log file not found starting a new one</span>
</pre></div>
</div>
<p>The most direct way to terminate a script is to use <code class="docutils literal notranslate"><span class="pre">sys.exit()</span></code>.</p>
</div>
<div class="section" id="string-pattern-matching">
<span id="tut-string-pattern-matching"></span><h2>10.5. String Pattern Matching<a class="headerlink" href="#string-pattern-matching" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides regular expression tools for advanced string
processing. For complex matching and manipulation, regular expressions offer
succinct, optimized solutions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">re</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;\bf[a-z]*&#39;</span><span class="p">,</span> <span class="s1">&#39;which foot or hand fell fastest&#39;</span><span class="p">)</span>
<span class="go">[&#39;foot&#39;, &#39;fell&#39;, &#39;fastest&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">&#39;(\b[a-z]+) \1&#39;</span><span class="p">,</span> <span class="sa">r</span><span class="s1">&#39;\1&#39;</span><span class="p">,</span> <span class="s1">&#39;cat in the the hat&#39;</span><span class="p">)</span>
<span class="go">&#39;cat in the hat&#39;</span>
</pre></div>
</div>
<p>When only simple capabilities are needed, string methods are preferred because
they are easier to read and debug:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;tea for too&#39;</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;too&#39;</span><span class="p">,</span> <span class="s1">&#39;two&#39;</span><span class="p">)</span>
<span class="go">&#39;tea for two&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="mathematics">
<span id="tut-mathematics"></span><h2>10.6. Mathematics<a class="headerlink" href="#mathematics" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module gives access to the underlying C library functions for
floating point math:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">cos</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">/</span> <span class="mf">4.0</span><span class="p">)</span>
<span class="go">0.70710678118654757</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="mi">1024</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">10.0</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module provides tools for making random selections:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">random</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">([</span><span class="s1">&#39;apple&#39;</span><span class="p">,</span> <span class="s1">&#39;pear&#39;</span><span class="p">,</span> <span class="s1">&#39;banana&#39;</span><span class="p">])</span>
<span class="go">&#39;apple&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="mi">100</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span>   <span class="c1"># sampling without replacement</span>
<span class="go">[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span>    <span class="c1"># random float</span>
<span class="go">0.17970987693706186</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>    <span class="c1"># random integer chosen from range(6)</span>
<span class="go">4</span>
</pre></div>
</div>
</div>
<div class="section" id="internet-access">
<span id="tut-internet-access"></span><h2>10.7. Internet Access<a class="headerlink" href="#internet-access" title="Permalink to this headline">¶</a></h2>
<p>There are a number of modules for accessing the internet and processing internet
protocols. Two of the simplest are <a class="reference internal" href="../library/urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> for retrieving data from URLs
and <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> for sending mail:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://tycho.usno.navy.mil/cgi-bin/timer.pl&#39;</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="s1">&#39;EST&#39;</span> <span class="ow">in</span> <span class="n">line</span> <span class="ow">or</span> <span class="s1">&#39;EDT&#39;</span> <span class="ow">in</span> <span class="n">line</span><span class="p">:</span>  <span class="c1"># look for Eastern Time</span>
<span class="gp">... </span>        <span class="nb">print</span> <span class="n">line</span>

<span class="go">&lt;BR&gt;Nov. 25, 09:43:32 PM EST</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">smtplib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">&#39;localhost&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="s1">&#39;soothsayer@example.org&#39;</span><span class="p">,</span> <span class="s1">&#39;jcaesar@example.org&#39;</span><span class="p">,</span>
<span class="gp">... </span><span class="sd">&quot;&quot;&quot;To: jcaesar@example.org</span>
<span class="gp">... </span><span class="sd">From: soothsayer@example.org</span>
<span class="gp">...</span><span class="sd"></span>
<span class="gp">... </span><span class="sd">Beware the Ides of March.</span>
<span class="gp">... </span><span class="sd">&quot;&quot;&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
</pre></div>
</div>
<p>(Note that the second example needs a mailserver running on localhost.)</p>
</div>
<div class="section" id="dates-and-times">
<span id="tut-dates-and-times"></span><h2>10.8. Dates and Times<a class="headerlink" href="#dates-and-times" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module supplies classes for manipulating dates and times in
both simple and complex ways. While date and time arithmetic is supported, the
focus of the implementation is on efficient member extraction for output
formatting and manipulation.  The module also supports objects that are timezone
aware.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># dates are easily constructed and formatted</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">date</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span>
<span class="go">datetime.date(2003, 12, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">&quot;%m-</span><span class="si">%d</span><span class="s2">-%y. </span><span class="si">%d</span><span class="s2"> %b %Y is a %A on the </span><span class="si">%d</span><span class="s2"> day of %B.&quot;</span><span class="p">)</span>
<span class="go">&#39;12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># dates support calendar arithmetic</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">birthday</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="mi">1964</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">31</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">age</span> <span class="o">=</span> <span class="n">now</span> <span class="o">-</span> <span class="n">birthday</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">age</span><span class="o">.</span><span class="n">days</span>
<span class="go">14368</span>
</pre></div>
</div>
</div>
<div class="section" id="data-compression">
<span id="tut-data-compression"></span><h2>10.9. Data Compression<a class="headerlink" href="#data-compression" title="Permalink to this headline">¶</a></h2>
<p>Common data archiving and compression formats are directly supported by modules
including: <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a>, <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a>, <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a>, <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> and
<a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">zlib</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s1">&#39;witch which has which witches wrist watch&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">41</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">zlib</span><span class="o">.</span><span class="n">compress</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zlib</span><span class="o">.</span><span class="n">decompress</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="go">&#39;witch which has which witches wrist watch&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">zlib</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="go">226805979</span>
</pre></div>
</div>
</div>
<div class="section" id="performance-measurement">
<span id="tut-performance-measurement"></span><h2>10.10. Performance Measurement<a class="headerlink" href="#performance-measurement" title="Permalink to this headline">¶</a></h2>
<p>Some Python users develop a deep interest in knowing the relative performance of
different approaches to the same problem. Python provides a measurement tool
that answers those questions immediately.</p>
<p>For example, it may be tempting to use the tuple packing and unpacking feature
instead of the traditional approach to swapping arguments. The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>
module quickly demonstrates a modest performance advantage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">timeit</span> <span class="k">import</span> <span class="n">Timer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;t=a; a=b; b=t&#39;</span><span class="p">,</span> <span class="s1">&#39;a=1; b=2&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
<span class="go">0.57535828626024577</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;a,b = b,a&#39;</span><span class="p">,</span> <span class="s1">&#39;a=1; b=2&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
<span class="go">0.54962537085770791</span>
</pre></div>
</div>
<p>In contrast to <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>’s fine level of granularity, the <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and
<a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> modules provide tools for identifying time critical sections in
larger blocks of code.</p>
</div>
<div class="section" id="quality-control">
<span id="tut-quality-control"></span><h2>10.11. Quality Control<a class="headerlink" href="#quality-control" title="Permalink to this headline">¶</a></h2>
<p>One approach for developing high quality software is to write tests for each
function as it is developed and to run those tests frequently during the
development process.</p>
<p>The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module provides a tool for scanning a module and validating
tests embedded in a program’s docstrings.  Test construction is as simple as
cutting-and-pasting a typical call along with its results into the docstring.
This improves the documentation by providing the user with an example and it
allows the doctest module to make sure the code remains true to the
documentation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">average</span><span class="p">(</span><span class="n">values</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;Computes the arithmetic mean of a list of numbers.</span>

<span class="sd">    &gt;&gt;&gt; print average([20, 30, 70])</span>
<span class="sd">    40.0</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">values</span><span class="p">,</span> <span class="mf">0.0</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>

<span class="kn">import</span> <span class="nn">doctest</span>
<span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">()</span>   <span class="c1"># automatically validate the embedded tests</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module is not as effortless as the <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module,
but it allows a more comprehensive set of tests to be maintained in a separate
file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">unittest</span>

<span class="k">class</span> <span class="nc">TestStatisticalFunctions</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>

    <span class="k">def</span> <span class="nf">test_average</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">]),</span> <span class="mf">40.0</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">]),</span> <span class="mi">1</span><span class="p">),</span> <span class="mf">4.3</span><span class="p">)</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">ZeroDivisionError</span><span class="p">):</span>
            <span class="n">average</span><span class="p">([])</span>
        <span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
            <span class="n">average</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">)</span>

<span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span>  <span class="c1"># Calling from the command line invokes all tests</span>
</pre></div>
</div>
</div>
<div class="section" id="batteries-included">
<span id="tut-batteries-included"></span><h2>10.12. Batteries Included<a class="headerlink" href="#batteries-included" title="Permalink to this headline">¶</a></h2>
<p>Python has a “batteries included” philosophy.  This is best seen through the
sophisticated and robust capabilities of its larger packages. For example:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> and <a class="reference internal" href="../library/simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> modules make implementing
remote procedure calls into an almost trivial task.  Despite the modules
names, no direct knowledge or handling of XML is needed.</li>
<li>The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is a library for managing email messages, including
MIME and other RFC 2822-based message documents. Unlike <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> and
<a class="reference internal" href="../library/poplib.html#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> which actually send and receive messages, the email package has
a complete toolset for building or decoding complex message structures
(including attachments) and for implementing internet encoding and header
protocols.</li>
<li>The <a class="reference internal" href="../library/xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> and <a class="reference internal" href="../library/xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> packages provide robust support for
parsing this popular data interchange format. Likewise, the <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module
supports direct reads and writes in a common database format. Together, these
modules and packages greatly simplify data interchange between Python
applications and other tools.</li>
<li>Internationalization is supported by a number of modules including
<a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a>, <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a>, and the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> package.</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">10. Brief Tour of the Standard Library</a><ul>
<li><a class="reference internal" href="#operating-system-interface">10.1. Operating System Interface</a></li>
<li><a class="reference internal" href="#file-wildcards">10.2. File Wildcards</a></li>
<li><a class="reference internal" href="#command-line-arguments">10.3. Command Line Arguments</a></li>
<li><a class="reference internal" href="#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
<li><a class="reference internal" href="#string-pattern-matching">10.5. String Pattern Matching</a></li>
<li><a class="reference internal" href="#mathematics">10.6. Mathematics</a></li>
<li><a class="reference internal" href="#internet-access">10.7. Internet Access</a></li>
<li><a class="reference internal" href="#dates-and-times">10.8. Dates and Times</a></li>
<li><a class="reference internal" href="#data-compression">10.9. Data Compression</a></li>
<li><a class="reference internal" href="#performance-measurement">10.10. Performance Measurement</a></li>
<li><a class="reference internal" href="#quality-control">10.11. Quality Control</a></li>
<li><a class="reference internal" href="#batteries-included">10.12. Batteries Included</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="classes.html"
                        title="previous chapter">9. Classes</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="stdlib2.html"
                        title="next chapter">11. Brief Tour of the Standard Library — Part II</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/stdlib.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
             >next</a> |</li>
        <li class="right" >
          <a href="classes.html" title="9. Classes"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�]��html/tutorial/stdlib2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>11. Brief Tour of the Standard Library — Part II &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="12. What Now?" href="whatnow.html" />
    <link rel="prev" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/stdlib2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now?"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="brief-tour-of-the-standard-library-part-ii">
<span id="tut-brieftourtwo"></span><h1>11. Brief Tour of the Standard Library — Part II<a class="headerlink" href="#brief-tour-of-the-standard-library-part-ii" title="Permalink to this headline">¶</a></h1>
<p>This second tour covers more advanced modules that support professional
programming needs.  These modules rarely occur in small scripts.</p>
<div class="section" id="output-formatting">
<span id="tut-output-formatting"></span><h2>11.1. Output Formatting<a class="headerlink" href="#output-formatting" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-mod docutils literal notranslate"><span class="pre">repr</span></code></a> module provides a version of <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> customized for
abbreviated displays of large or deeply nested containers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">repr</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">repr</span><span class="o">.</span><span class="n">repr</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="s1">&#39;supercalifragilisticexpialidocious&#39;</span><span class="p">))</span>
<span class="go">&quot;set([&#39;a&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, ...])&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/pprint.html#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module offers more sophisticated control over printing both
built-in and user defined objects in a way that is readable by the interpreter.
When the result is longer than one line, the “pretty printer” adds line breaks
and indentation to more clearly reveal data structure:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">[[[[</span><span class="s1">&#39;black&#39;</span><span class="p">,</span> <span class="s1">&#39;cyan&#39;</span><span class="p">],</span> <span class="s1">&#39;white&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;green&#39;</span><span class="p">,</span> <span class="s1">&#39;red&#39;</span><span class="p">]],</span> <span class="p">[[</span><span class="s1">&#39;magenta&#39;</span><span class="p">,</span>
<span class="gp">... </span>    <span class="s1">&#39;yellow&#39;</span><span class="p">],</span> <span class="s1">&#39;blue&#39;</span><span class="p">]]]</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
<span class="go">[[[[&#39;black&#39;, &#39;cyan&#39;],</span>
<span class="go">   &#39;white&#39;,</span>
<span class="go">   [&#39;green&#39;, &#39;red&#39;]],</span>
<span class="go">  [[&#39;magenta&#39;, &#39;yellow&#39;],</span>
<span class="go">   &#39;blue&#39;]]]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module formats paragraphs of text to fit a given screen
width:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">textwrap</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">doc</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;The wrap() method is just like fill() except that it returns</span>
<span class="gp">... </span><span class="s2">a list of strings instead of one big string with newlines to separate</span>
<span class="gp">... </span><span class="s2">the wrapped lines.&quot;&quot;&quot;</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">doc</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">40</span><span class="p">)</span>
<span class="go">The wrap() method is just like fill()</span>
<span class="go">except that it returns a list of strings</span>
<span class="go">instead of one big string with newlines</span>
<span class="go">to separate the wrapped lines.</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module accesses a database of culture specific data formats.
The grouping attribute of locale’s format function provides a direct way of
formatting numbers with group separators:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">locale</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">&#39;English_United States.1252&#39;</span><span class="p">)</span>
<span class="go">&#39;English_United States.1252&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">conv</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">localeconv</span><span class="p">()</span>          <span class="c1"># get a mapping of conventions</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1234567.8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%d</span><span class="s2">&quot;</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;1,234,567&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s%.*f</span><span class="s2">&quot;</span><span class="p">,</span> <span class="p">(</span><span class="n">conv</span><span class="p">[</span><span class="s1">&#39;currency_symbol&#39;</span><span class="p">],</span>
<span class="gp">... </span>                     <span class="n">conv</span><span class="p">[</span><span class="s1">&#39;frac_digits&#39;</span><span class="p">],</span> <span class="n">x</span><span class="p">),</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="go">&#39;$1,234,567.80&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="templating">
<span id="tut-templating"></span><h2>11.2. Templating<a class="headerlink" href="#templating" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module includes a versatile <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class
with a simplified syntax suitable for editing by end-users.  This allows users
to customize their applications without having to alter the application.</p>
<p>The format uses placeholder names formed by <code class="docutils literal notranslate"><span class="pre">$</span></code> with valid Python identifiers
(alphanumeric characters and underscores).  Surrounding the placeholder with
braces allows it to be followed by more alphanumeric letters with no intervening
spaces.  Writing <code class="docutils literal notranslate"><span class="pre">$$</span></code> creates a single escaped <code class="docutils literal notranslate"><span class="pre">$</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">string</span> <span class="k">import</span> <span class="n">Template</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$</span><span class="si">{village}</span><span class="s1">folk send $$10 to $cause.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">village</span><span class="o">=</span><span class="s1">&#39;Nottingham&#39;</span><span class="p">,</span> <span class="n">cause</span><span class="o">=</span><span class="s1">&#39;the ditch fund&#39;</span><span class="p">)</span>
<span class="go">&#39;Nottinghamfolk send $10 to the ditch fund.&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a> method raises a <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> when a
placeholder is not supplied in a dictionary or a keyword argument.  For
mail-merge style applications, user supplied data may be incomplete and the
<a class="reference internal" href="../library/string.html#string.Template.safe_substitute" title="string.Template.safe_substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code></a> method may be more appropriate —
it will leave placeholders unchanged if data is missing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">&#39;Return the $item to $owner.&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">item</span><span class="o">=</span><span class="s1">&#39;unladen swallow&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">KeyError</span>: <span class="n">&#39;owner&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">&#39;Return the unladen swallow to $owner.&#39;</span>
</pre></div>
</div>
<p>Template subclasses can specify a custom delimiter.  For example, a batch
renaming utility for a photo browser may elect to use percent signs for
placeholders such as the current date, image sequence number, or file format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">time</span><span class="o">,</span> <span class="nn">os.path</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">photofiles</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;img_1074.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;img_1076.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;img_1077.jpg&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">BatchRename</span><span class="p">(</span><span class="n">Template</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">delimiter</span> <span class="o">=</span> <span class="s1">&#39;%&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="n">raw_input</span><span class="p">(</span><span class="s1">&#39;Enter rename style (</span><span class="si">%d</span><span class="s1">-date %n-seqnum </span><span class="si">%f</span><span class="s1">-format):  &#39;</span><span class="p">)</span>
<span class="go">Enter rename style (%d-date %n-seqnum %f-format):  Ashley_%n%f</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">BatchRename</span><span class="p">(</span><span class="n">fmt</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">date</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%d</span><span class="s1">%b%y&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">filename</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">photofiles</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">base</span><span class="p">,</span> <span class="n">ext</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">splitext</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="gp">... </span>    <span class="n">newname</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="o">=</span><span class="n">date</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">f</span><span class="o">=</span><span class="n">ext</span><span class="p">)</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">{0}</span><span class="s1"> --&gt; </span><span class="si">{1}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">newname</span><span class="p">)</span>

<span class="go">img_1074.jpg --&gt; Ashley_0.jpg</span>
<span class="go">img_1076.jpg --&gt; Ashley_1.jpg</span>
<span class="go">img_1077.jpg --&gt; Ashley_2.jpg</span>
</pre></div>
</div>
<p>Another application for templating is separating program logic from the details
of multiple output formats.  This makes it possible to substitute custom
templates for XML files, plain text reports, and HTML web reports.</p>
</div>
<div class="section" id="working-with-binary-data-record-layouts">
<span id="tut-binary-formats"></span><h2>11.3. Working with Binary Data Record Layouts<a class="headerlink" href="#working-with-binary-data-record-layouts" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module provides <a class="reference internal" href="../library/struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> and
<a class="reference internal" href="../library/struct.html#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> functions for working with variable length binary
record formats.  The following example shows
how to loop through header information in a ZIP file without using the
<a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module.  Pack codes <code class="docutils literal notranslate"><span class="pre">&quot;H&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;I&quot;</span></code> represent two and four
byte unsigned numbers respectively.  The <code class="docutils literal notranslate"><span class="pre">&quot;&lt;&quot;</span></code> indicates that they are
standard size and in little-endian byte order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">struct</span>

<span class="n">data</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;myfile.zip&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
<span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>                      <span class="c1"># show the first 3 file headers</span>
    <span class="n">start</span> <span class="o">+=</span> <span class="mi">14</span>
    <span class="n">fields</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">&#39;&lt;IIIHH&#39;</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="mi">16</span><span class="p">])</span>
    <span class="n">crc32</span><span class="p">,</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">,</span> <span class="n">filenamesize</span><span class="p">,</span> <span class="n">extra_size</span> <span class="o">=</span> <span class="n">fields</span>

    <span class="n">start</span> <span class="o">+=</span> <span class="mi">16</span>
    <span class="n">filename</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">filenamesize</span><span class="p">]</span>
    <span class="n">start</span> <span class="o">+=</span> <span class="n">filenamesize</span>
    <span class="n">extra</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">extra_size</span><span class="p">]</span>
    <span class="nb">print</span> <span class="n">filename</span><span class="p">,</span> <span class="nb">hex</span><span class="p">(</span><span class="n">crc32</span><span class="p">),</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span>

    <span class="n">start</span> <span class="o">+=</span> <span class="n">extra_size</span> <span class="o">+</span> <span class="n">comp_size</span>     <span class="c1"># skip to the next header</span>
</pre></div>
</div>
</div>
<div class="section" id="multi-threading">
<span id="tut-multi-threading"></span><h2>11.4. Multi-threading<a class="headerlink" href="#multi-threading" title="Permalink to this headline">¶</a></h2>
<p>Threading is a technique for decoupling tasks which are not sequentially
dependent.  Threads can be used to improve the responsiveness of applications
that accept user input while other tasks run in the background.  A related use
case is running I/O in parallel with computations in another thread.</p>
<p>The following code shows how the high level <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module can run
tasks in background while the main program continues to run:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span><span class="o">,</span> <span class="nn">zipfile</span>

<span class="k">class</span> <span class="nc">AsyncZip</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">infile</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
        <span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">infile</span> <span class="o">=</span> <span class="n">infile</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">outfile</span> <span class="o">=</span> <span class="n">outfile</span>

    <span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">f</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">outfile</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">,</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZIP_DEFLATED</span><span class="p">)</span>
        <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
        <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
        <span class="nb">print</span> <span class="s1">&#39;Finished background zip of: &#39;</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">infile</span>

<span class="n">background</span> <span class="o">=</span> <span class="n">AsyncZip</span><span class="p">(</span><span class="s1">&#39;mydata.txt&#39;</span><span class="p">,</span> <span class="s1">&#39;myarchive.zip&#39;</span><span class="p">)</span>
<span class="n">background</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
<span class="nb">print</span> <span class="s1">&#39;The main program continues to run in foreground.&#39;</span>

<span class="n">background</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>    <span class="c1"># Wait for the background task to finish</span>
<span class="nb">print</span> <span class="s1">&#39;Main program waited until background was done.&#39;</span>
</pre></div>
</div>
<p>The principal challenge of multi-threaded applications is coordinating threads
that share data or other resources.  To that end, the threading module provides
a number of synchronization primitives including locks, events, condition
variables, and semaphores.</p>
<p>While those tools are powerful, minor design errors can result in problems that
are difficult to reproduce.  So, the preferred approach to task coordination is
to concentrate all access to a resource in a single thread and then use the
<a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module to feed that thread with requests from other threads.
Applications using <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue.Queue</span></code></a> objects for inter-thread communication
and coordination are easier to design, more readable, and more reliable.</p>
</div>
<div class="section" id="logging">
<span id="tut-logging"></span><h2>11.5. Logging<a class="headerlink" href="#logging" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module offers a full featured and flexible logging system.
At its simplest, log messages are sent to a file or to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Debugging information&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Informational message&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Warning:config file </span><span class="si">%s</span><span class="s1"> not found&#39;</span><span class="p">,</span> <span class="s1">&#39;server.conf&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Error occurred&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Critical error -- shutting down&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Warning:config file server.conf not found
ERROR:root:Error occurred
CRITICAL:root:Critical error -- shutting down
</pre></div>
</div>
<p>By default, informational and debugging messages are suppressed and the output
is sent to standard error.  Other output options include routing messages
through email, datagrams, sockets, or to an HTTP Server.  New filters can select
different routing based on message priority: <code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code>,
and <code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code>.</p>
<p>The logging system can be configured directly from Python or can be loaded from
a user editable configuration file for customized logging without altering the
application.</p>
</div>
<div class="section" id="weak-references">
<span id="tut-weak-references"></span><h2>11.6. Weak References<a class="headerlink" href="#weak-references" title="Permalink to this headline">¶</a></h2>
<p>Python does automatic memory management (reference counting for most objects and
<a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> to eliminate cycles).  The memory is freed shortly
after the last reference to it has been eliminated.</p>
<p>This approach works fine for most applications but occasionally there is a need
to track objects only as long as they are being used by something else.
Unfortunately, just tracking them creates a reference that makes them permanent.
The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module provides tools for tracking objects without creating a
reference.  When the object is no longer needed, it is automatically removed
from a weakref table and a callback is triggered for weakref objects.  Typical
applications include caching objects that are expensive to create:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">weakref</span><span class="o">,</span> <span class="nn">gc</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>                   <span class="c1"># create a reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span>            <span class="c1"># does not create a reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span>                <span class="c1"># fetch the object if it is still alive</span>
<span class="go">10</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span>                       <span class="c1"># remove the one reference</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span>                <span class="c1"># run garbage collection right away</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span>                <span class="c1"># entry was automatically removed</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
    <span class="n">d</span><span class="p">[</span><span class="s1">&#39;primary&#39;</span><span class="p">]</span>                <span class="c1"># entry was automatically removed</span>
  File <span class="nb">&quot;C:/python26/lib/weakref.py&quot;</span>, line <span class="m">46</span>, in <span class="n">__getitem__</span>
    <span class="n">o</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="n">key</span><span class="p">]()</span>
<span class="gr">KeyError</span>: <span class="n">&#39;primary&#39;</span>
</pre></div>
</div>
</div>
<div class="section" id="tools-for-working-with-lists">
<span id="tut-list-tools"></span><h2>11.7. Tools for Working with Lists<a class="headerlink" href="#tools-for-working-with-lists" title="Permalink to this headline">¶</a></h2>
<p>Many data structure needs can be met with the built-in list type. However,
sometimes there is a need for alternative implementations with different
performance trade-offs.</p>
<p>The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module provides an <a class="reference internal" href="../library/array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array()</span></code></a> object that is like
a list that stores only homogeneous data and stores it more compactly.  The
following example shows an array of numbers stored as two byte unsigned binary
numbers (typecode <code class="docutils literal notranslate"><span class="pre">&quot;H&quot;</span></code>) rather than the usual 16 bytes per entry for regular
lists of Python int objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">array</span> <span class="k">import</span> <span class="n">array</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">&#39;H&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">4000</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">22222</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="go">26932</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
<span class="go">array(&#39;H&#39;, [10, 700])</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module provides a <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque()</span></code></a> object
that is like a list with faster appends and pops from the left side but slower
lookups in the middle. These objects are well suited for implementing queues
and breadth first tree searches:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">&quot;task1&quot;</span><span class="p">,</span> <span class="s2">&quot;task2&quot;</span><span class="p">,</span> <span class="s2">&quot;task3&quot;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">&quot;task4&quot;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s2">&quot;Handling&quot;</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
<span class="go">Handling task1</span>
</pre></div>
</div>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">unsearched</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="n">starting_node</span><span class="p">])</span>
<span class="k">def</span> <span class="nf">breadth_first_search</span><span class="p">(</span><span class="n">unsearched</span><span class="p">):</span>
    <span class="n">node</span> <span class="o">=</span> <span class="n">unsearched</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">gen_moves</span><span class="p">(</span><span class="n">node</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">is_goal</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">m</span>
        <span class="n">unsearched</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
</pre></div>
</div>
<p>In addition to alternative list implementations, the library also offers other
tools such as the <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> module with functions for manipulating sorted
lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">bisect</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scores</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">100</span><span class="p">,</span> <span class="s1">&#39;perl&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s1">&#39;tcl&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">400</span><span class="p">,</span> <span class="s1">&#39;lua&#39;</span><span class="p">),</span> <span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="s1">&#39;python&#39;</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bisect</span><span class="o">.</span><span class="n">insort</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="p">(</span><span class="mi">300</span><span class="p">,</span> <span class="s1">&#39;ruby&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scores</span>
<span class="go">[(100, &#39;perl&#39;), (200, &#39;tcl&#39;), (300, &#39;ruby&#39;), (400, &#39;lua&#39;), (500, &#39;python&#39;)]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides functions for implementing heaps based on
regular lists.  The lowest valued entry is always kept at position zero.  This
is useful for applications which repeatedly access the smallest element but do
not want to run a full list sort:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">heapq</span> <span class="k">import</span> <span class="n">heapify</span><span class="p">,</span> <span class="n">heappop</span><span class="p">,</span> <span class="n">heappush</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapify</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>                      <span class="c1"># rearrange the list into heap order</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heappush</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">)</span>                 <span class="c1"># add a new entry</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">heappop</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span>  <span class="c1"># fetch the three smallest entries</span>
<span class="go">[-5, 0, 1]</span>
</pre></div>
</div>
</div>
<div class="section" id="decimal-floating-point-arithmetic">
<span id="tut-decimal-fp"></span><h2>11.8. Decimal Floating Point Arithmetic<a class="headerlink" href="#decimal-floating-point-arithmetic" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module offers a <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> datatype for
decimal floating point arithmetic.  Compared to the built-in <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>
implementation of binary floating point, the class is especially helpful for</p>
<ul class="simple">
<li>financial applications and other uses which require exact decimal
representation,</li>
<li>control over precision,</li>
<li>control over rounding to meet legal or regulatory requirements,</li>
<li>tracking of significant decimal places, or</li>
<li>applications where the user expects the results to match calculations done by
hand.</li>
</ul>
<p>For example, calculating a 5% tax on a 70 cent phone charge gives different
results in decimal floating point and binary floating point. The difference
becomes significant if the results are rounded to the nearest cent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="o">*</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.70&#39;</span><span class="p">)</span> <span class="o">*</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.05&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span>
<span class="go">Decimal(&#39;0.7350&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">x</span><span class="o">.</span><span class="n">quantize</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.01&#39;</span><span class="p">))</span>  <span class="c1"># round to nearest cent</span>
<span class="go">Decimal(&#39;0.74&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">round</span><span class="p">(</span><span class="o">.</span><span class="mi">70</span> <span class="o">*</span> <span class="mf">1.05</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>         <span class="c1"># same calculation with floats</span>
<span class="go">0.73</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> result keeps a trailing zero, automatically
inferring four place significance from multiplicands with two place
significance.  Decimal reproduces mathematics as done by hand and avoids
issues that can arise when binary floating point cannot exactly represent
decimal quantities.</p>
<p>Exact representation enables the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class to perform
modulo calculations and equality tests that are unsuitable for binary floating
point:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.00&#39;</span><span class="p">)</span> <span class="o">%</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;.10&#39;</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.00&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mf">1.00</span> <span class="o">%</span> <span class="mf">0.10</span>
<span class="go">0.09999999999999995</span>

<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;0.1&#39;</span><span class="p">)]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.0&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sum</span><span class="p">([</span><span class="mf">0.1</span><span class="p">]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1.0</span>
<span class="go">False</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides arithmetic with as much precision as needed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">36</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&#39;0.142857142857142857142857142857142857&#39;)</span>
</pre></div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
<li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
<li><a class="reference internal" href="#templating">11.2. Templating</a></li>
<li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
<li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
<li><a class="reference internal" href="#logging">11.5. Logging</a></li>
<li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
<li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
<li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="stdlib.html"
                        title="previous chapter">10. Brief Tour of the Standard Library</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="whatnow.html"
                        title="next chapter">12. What Now?</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/stdlib2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whatnow.html" title="12. What Now?"
             >next</a> |</li>
        <li class="right" >
          <a href="stdlib.html" title="10. Brief Tour of the Standard Library"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�V��'�'html/tutorial/whatnow.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>12. What Now? &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="13. Interactive Input Editing and History Substitution" href="interactive.html" />
    <link rel="prev" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/tutorial/whatnow.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="interactive.html" title="13. Interactive Input Editing and History Substitution"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-now">
<span id="tut-whatnow"></span><h1>12. What Now?<a class="headerlink" href="#what-now" title="Permalink to this headline">¶</a></h1>
<p>Reading this tutorial has probably reinforced your interest in using Python —
you should be eager to apply Python to solving your real-world problems. Where
should you go to learn more?</p>
<p>This tutorial is part of Python’s documentation set.   Some other documents in
the set are:</p>
<ul>
<li><p class="first"><a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>:</p>
<p>You should browse through this manual, which gives complete (though terse)
reference material about types, functions, and the modules in the standard
library.  The standard Python distribution includes a <em>lot</em> of additional code.
There are modules to read Unix mailboxes, retrieve documents via HTTP, generate
random numbers, parse command-line options, write CGI programs, compress data,
and many other tasks. Skimming through the Library Reference will give you an
idea of what’s available.</p>
</li>
<li><p class="first"><a class="reference internal" href="../install/index.html#install-index"><span class="std std-ref">Installing Python Modules (Legacy version)</span></a> explains how to install external modules written by other
Python users.</p>
</li>
<li><p class="first"><a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a>: A detailed explanation of Python’s syntax and
semantics.  It’s heavy reading, but is useful as a complete guide to the
language itself.</p>
</li>
</ul>
<p>More Python resources:</p>
<ul class="simple">
<li><a class="reference external" href="https://www.python.org">https://www.python.org</a>:  The major Python Web site.  It contains code,
documentation, and pointers to Python-related pages around the Web.  This Web
site is mirrored in various places around the world, such as Europe, Japan, and
Australia; a mirror may be faster than the main site, depending on your
geographical location.</li>
<li><a class="reference external" href="https://docs.python.org">https://docs.python.org</a>:  Fast access to Python’s  documentation.</li>
<li><a class="reference external" href="https://pypi.org">https://pypi.org</a>: The Python Package Index, previously also nicknamed
the Cheese Shop, is an index of user-created Python modules that are available
for download.  Once you begin releasing code, you can register it here so that
others can find it.</li>
<li><a class="reference external" href="https://code.activestate.com/recipes/langs/python/">https://code.activestate.com/recipes/langs/python/</a>: The Python Cookbook is a
sizable collection of code examples, larger modules, and useful scripts.
Particularly notable contributions are collected in a book also titled Python
Cookbook (O’Reilly &amp; Associates, ISBN 0-596-00797-3.)</li>
</ul>
<p>For Python-related questions and problem reports, you can post to the newsgroup
<em class="newsgroup">comp.lang.python</em>, or send them to the mailing list at
<a class="reference external" href="mailto:python-list&#37;&#52;&#48;python&#46;org">python-list<span>&#64;</span>python<span>&#46;</span>org</a>.  The newsgroup and mailing list are gatewayed, so
messages posted to one will automatically be forwarded to the other.  There are
around 120 postings a day (with peaks up to several hundred), asking (and
answering) questions, suggesting new features, and announcing new modules.
Before posting, be sure to check the list of <a class="reference internal" href="../faq/index.html#faq-index"><span class="std std-ref">Frequently Asked Questions</span></a> (also called the FAQ).  Mailing list
archives are available at <a class="reference external" href="https://mail.python.org/pipermail/">https://mail.python.org/pipermail/</a>. The FAQ answers
many of the questions that come up again and again, and may already contain the
solution for your problem.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="stdlib2.html"
                        title="previous chapter">11. Brief Tour of the Standard Library — Part II</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="interactive.html"
                        title="next chapter">13. Interactive Input Editing and History Substitution</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/tutorial/whatnow.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="interactive.html" title="13. Interactive Input Editing and History Substitution"
             >next</a> |</li>
        <li class="right" >
          <a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��html/using/cmdline.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>1. Command line and environment &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="2. Using Python on Unix platforms" href="unix.html" />
    <link rel="prev" title="Python Setup and Usage" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/using/cmdline.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unix.html" title="2. Using Python on Unix platforms"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python Setup and Usage"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="command-line-and-environment">
<span id="using-on-general"></span><h1>1. Command line and environment<a class="headerlink" href="#command-line-and-environment" title="Permalink to this headline">¶</a></h1>
<p>The CPython interpreter scans the command line and the environment for various
settings.</p>
<div class="impl-detail compound">
<p><strong>CPython implementation detail:</strong> Other implementations’ command line schemes may differ.  See
<a class="reference internal" href="../reference/introduction.html#implementations"><span class="std std-ref">Alternate Implementations</span></a> for further resources.</p>
</div>
<div class="section" id="command-line">
<span id="using-on-cmdline"></span><h2>1.1. Command line<a class="headerlink" href="#command-line" title="Permalink to this headline">¶</a></h2>
<p>When invoking Python, you may specify any of these options:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>python <span class="o">[</span>-bBdEiOQsRStuUvVWxX3?<span class="o">]</span> <span class="o">[</span>-c <span class="nb">command</span> <span class="p">|</span> -m module-name <span class="p">|</span> script <span class="p">|</span> - <span class="o">]</span> <span class="o">[</span>args<span class="o">]</span>
</pre></div>
</div>
<p>The most common use case is, of course, a simple invocation of a script:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>python myscript.py
</pre></div>
</div>
<div class="section" id="interface-options">
<span id="using-on-interface-options"></span><h3>1.1.1. Interface options<a class="headerlink" href="#interface-options" title="Permalink to this headline">¶</a></h3>
<p>The interpreter interface resembles that of the UNIX shell, but provides some
additional methods of invocation:</p>
<ul class="simple">
<li>When called with standard input connected to a tty device, it prompts for
commands and executes them until an EOF (an end-of-file character, you can
produce that with <kbd class="kbd docutils literal notranslate">Ctrl-D</kbd> on UNIX or <kbd class="kbd docutils literal notranslate">Ctrl-Z, Enter</kbd> on Windows) is read.</li>
<li>When called with a file name argument or with a file as standard input, it
reads and executes a script from that file.</li>
<li>When called with a directory name argument, it reads and executes an
appropriately named script from that directory.</li>
<li>When called with <code class="docutils literal notranslate"><span class="pre">-c</span> <span class="pre">command</span></code>, it executes the Python statement(s) given as
<em>command</em>.  Here <em>command</em> may contain multiple statements separated by
newlines. Leading whitespace is significant in Python statements!</li>
<li>When called with <code class="docutils literal notranslate"><span class="pre">-m</span> <span class="pre">module-name</span></code>, the given module is located on the
Python module path and executed as a script.</li>
</ul>
<p>In non-interactive mode, the entire input is parsed before it is executed.</p>
<p>An interface option terminates the list of options consumed by the interpreter,
all consecutive arguments will end up in <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> – note that the first
element, subscript zero (<code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code>), is a string reflecting the program’s
source.</p>
<dl class="cmdoption">
<dt id="cmdoption-c">
<code class="descname">-c</code><code class="descclassname"> &lt;command&gt;</code><a class="headerlink" href="#cmdoption-c" title="Permalink to this definition">¶</a></dt>
<dd><p>Execute the Python code in <em>command</em>.  <em>command</em> can be one or more
statements separated by newlines, with significant leading whitespace as in
normal module code.</p>
<p>If this option is given, the first element of <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> will be
<code class="docutils literal notranslate"><span class="pre">&quot;-c&quot;</span></code> and the current directory will be added to the start of
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> (allowing modules in that directory to be imported as top
level modules).</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-m">
<code class="descname">-m</code><code class="descclassname"> &lt;module-name&gt;</code><a class="headerlink" href="#cmdoption-m" title="Permalink to this definition">¶</a></dt>
<dd><p>Search <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> for the named module and execute its contents as
the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.</p>
<p>Since the argument is a <em>module</em> name, you must not give a file extension
(<code class="docutils literal notranslate"><span class="pre">.py</span></code>).  The <code class="docutils literal notranslate"><span class="pre">module-name</span></code> should be a valid Python module name, but
the implementation may not always enforce this (e.g. it may allow you to
use a name that includes a hyphen).</p>
<p>Package names are also permitted. When a package name is supplied instead
of a normal module, the interpreter will execute <code class="docutils literal notranslate"><span class="pre">&lt;pkg&gt;.__main__</span></code> as
the main module. This behaviour is deliberately similar to the handling
of directories and zipfiles that are passed to the interpreter as the
script argument.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">This option cannot be used with built-in modules and extension modules
written in C, since they do not have Python module files. However, it
can still be used for precompiled modules, even if the original source
file is not available.</p>
</div>
<p>If this option is given, the first element of <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> will be the
full path to the module file. As with the <a class="reference internal" href="#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option, the current
directory will be added to the start of <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<p>Many standard library modules contain code that is invoked on their execution
as a script.  An example is the <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>python -mtimeit -s <span class="s1">&#39;setup here&#39;</span> <span class="s1">&#39;benchmarked code here&#39;</span>
python -mtimeit -h <span class="c1"># for details</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference internal" href="../library/runpy.html#runpy.run_module" title="runpy.run_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">runpy.run_module()</span></code></a></dt>
<dd>Equivalent functionality directly available to Python code</dd>
</dl>
<p class="last"><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0338"><strong>PEP 338</strong></a> – Executing modules as scripts</p>
</div>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The named module can now be located inside a package.</p>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7: </span>Supply the package name to run a <code class="docutils literal notranslate"><span class="pre">__main__</span></code> submodule.
sys.argv[0] is now set to <code class="docutils literal notranslate"><span class="pre">&quot;-m&quot;</span></code> while searching for the module
(it was previously incorrectly set to <code class="docutils literal notranslate"><span class="pre">&quot;-c&quot;</span></code>)</p>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">-</code></dt>
<dd><p>Read commands from standard input (<a class="reference internal" href="../library/sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a>).  If standard input is
a terminal, <a class="reference internal" href="#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> is implied.</p>
<p>If this option is given, the first element of <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> will be
<code class="docutils literal notranslate"><span class="pre">&quot;-&quot;</span></code> and the current directory will be added to the start of
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/runpy.html#runpy.run_path" title="runpy.run_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">runpy.run_path()</span></code></a></dt>
<dd>Equivalent functionality directly available to Python code</dd>
</dl>
</div>
</dd></dl>

<dl class="describe">
<dt>
<code class="descname">&lt;script&gt;</code></dt>
<dd><p>Execute the Python code contained in <em>script</em>, which must be a filesystem
path (absolute or relative) referring to either a Python file, a directory
containing a <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file, or a zipfile containing a
<code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file.</p>
<p>If this option is given, the first element of <a class="reference internal" href="../library/sys.html#sys.argv" title="sys.argv"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.argv</span></code></a> will be the
script name as given on the command line.</p>
<p>If the script name refers directly to a Python file, the directory
containing that file is added to the start of <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>, and the
file is executed as the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.</p>
<p>If the script name refers to a directory or zipfile, the script name is
added to the start of <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> and the <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file in
that location is executed as the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>Directories and zipfiles containing a <code class="docutils literal notranslate"><span class="pre">__main__.py</span></code> file at the top
level are now considered valid Python scripts.</p>
</div>
</dd></dl>

<p>If no interface option is given, <a class="reference internal" href="#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> is implied, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is
an empty string (<code class="docutils literal notranslate"><span class="pre">&quot;&quot;</span></code>) and the current directory will be added to the
start of <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference internal" href="../tutorial/interpreter.html#tut-invoking"><span class="std std-ref">Invoking the Interpreter</span></a></p>
</div>
</div>
<div class="section" id="generic-options">
<h3>1.1.2. Generic options<a class="headerlink" href="#generic-options" title="Permalink to this headline">¶</a></h3>
<dl class="cmdoption">
<dt id="cmdoption">
<code class="descname">-?</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption" title="Permalink to this definition">¶</a></dt>
<dt id="cmdoption-h">
<code class="descname">-h</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-h" title="Permalink to this definition">¶</a></dt>
<dt id="cmdoption-help">
<code class="descname">--help</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-help" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a short description of all command line options.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <code class="docutils literal notranslate"><span class="pre">--help</span></code> variant.</p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-v">
<code class="descname">-V</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-v" title="Permalink to this definition">¶</a></dt>
<dt id="cmdoption-version">
<code class="descname">--version</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-version" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the Python version number and exit.  Example output could be:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>Python <span class="m">2</span>.5.1
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.5: </span>The <code class="docutils literal notranslate"><span class="pre">--version</span></code> variant.</p>
</div>
</dd></dl>

</div>
<div class="section" id="miscellaneous-options">
<h3>1.1.3. Miscellaneous options<a class="headerlink" href="#miscellaneous-options" title="Permalink to this headline">¶</a></h3>
<dl class="cmdoption">
<dt id="cmdoption-b">
<code class="descname">-b</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-b" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning when comparing <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> with <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a>.
Issue an error when the option is given twice (<code class="xref std std-option docutils literal notranslate"><span class="pre">-bb</span></code>).</p>
<p>Note that, unlike the corresponding Python 3.x flag, this will <strong>not</strong> emit
warnings for comparisons between <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> and <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a>.
Instead, the <code class="docutils literal notranslate"><span class="pre">str</span></code> instance will be implicitly decoded to <code class="docutils literal notranslate"><span class="pre">unicode</span></code> and
Unicode comparison used.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="id1">
<code class="descname">-B</code><code class="descclassname"></code><a class="headerlink" href="#id1" title="Permalink to this definition">¶</a></dt>
<dd><p>If given, Python won’t try to write <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="docutils literal notranslate"><span class="pre">.pyo</span></code> files on the
import of source modules.  See also <span class="target" id="index-1"></span><a class="reference internal" href="#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-d">
<code class="descname">-d</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-d" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn on parser debugging output (for wizards only, depending on compilation
options).  See also <span class="target" id="index-2"></span><a class="reference internal" href="#envvar-PYTHONDEBUG"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDEBUG</span></code></a>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-e">
<code class="descname">-E</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-e" title="Permalink to this definition">¶</a></dt>
<dd><p>Ignore all <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHON*</span></code> environment variables, e.g.
<span class="target" id="index-4"></span><a class="reference internal" href="#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> and <span class="target" id="index-5"></span><a class="reference internal" href="#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a>, that might be set.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.2.</span></p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-i">
<code class="descname">-i</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-i" title="Permalink to this definition">¶</a></dt>
<dd><p>When a script is passed as first argument or the <a class="reference internal" href="#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option is used,
enter interactive mode after executing the script or the command, even when
<a class="reference internal" href="../library/sys.html#sys.stdin" title="sys.stdin"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stdin</span></code></a> does not appear to be a terminal.  The
<span class="target" id="index-6"></span><a class="reference internal" href="#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> file is not read.</p>
<p>This can be useful to inspect global variables or a stack trace when a script
raises an exception.  See also <span class="target" id="index-7"></span><a class="reference internal" href="#envvar-PYTHONINSPECT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONINSPECT</span></code></a>.</p>
</dd></dl>

<span class="target" id="using-on-optimizations"></span><dl class="cmdoption">
<dt id="cmdoption-o">
<code class="descname">-O</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-o" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn on basic optimizations.  This changes the filename extension for
compiled (<a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>) files from <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> to <code class="docutils literal notranslate"><span class="pre">.pyo</span></code>.  See also
<span class="target" id="index-8"></span><a class="reference internal" href="#envvar-PYTHONOPTIMIZE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONOPTIMIZE</span></code></a>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-oo">
<code class="descname">-OO</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-oo" title="Permalink to this definition">¶</a></dt>
<dd><p>Discard docstrings in addition to the <a class="reference internal" href="#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> optimizations.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-q">
<code class="descname">-Q</code><code class="descclassname"> &lt;arg&gt;</code><a class="headerlink" href="#cmdoption-q" title="Permalink to this definition">¶</a></dt>
<dd><p>Division control. The argument must be one of the following:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">old</span></code></dt>
<dd>division of int/int and long/long return an int or long (<em>default</em>)</dd>
<dt><code class="docutils literal notranslate"><span class="pre">new</span></code></dt>
<dd>new division semantics, i.e. division of int/int and long/long returns a
float</dd>
<dt><code class="docutils literal notranslate"><span class="pre">warn</span></code></dt>
<dd>old division semantics with a warning for int/int and long/long</dd>
<dt><code class="docutils literal notranslate"><span class="pre">warnall</span></code></dt>
<dd>old division semantics with a warning for all uses of the division operator</dd>
</dl>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><code class="file docutils literal notranslate"><span class="pre">Tools/scripts/fixdiv.py</span></code></dt>
<dd>for a use of <code class="docutils literal notranslate"><span class="pre">warnall</span></code></dd>
</dl>
<p class="last"><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a> – Changing the division operator</p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-r">
<code class="descname">-R</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-r" title="Permalink to this definition">¶</a></dt>
<dd><p>Turn on hash randomization, so that the <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> values of str,
bytes and datetime objects are “salted” with an unpredictable random value.
Although they remain constant within an individual Python process, they are
not predictable between repeated invocations of Python.</p>
<p>This is intended to provide protection against a denial-of-service caused by
carefully-chosen inputs that exploit the worst case performance of a dict
construction, O(n^2) complexity.  See
<a class="reference external" href="http://www.ocert.org/advisories/ocert-2011-003.html">http://www.ocert.org/advisories/ocert-2011-003.html</a> for details.</p>
<p>Changing hash values affects the order in which keys are retrieved from a
dict.  Although Python has never made guarantees about this ordering (and it
typically varies between 32-bit and 64-bit builds), enough real-world code
implicitly relies on this non-guaranteed behavior that the randomization is
disabled by default.</p>
<p>See also <span class="target" id="index-10"></span><a class="reference internal" href="#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHASHSEED</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.8.</span></p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-s">
<code class="descname">-s</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-s" title="Permalink to this definition">¶</a></dt>
<dd><p>Don’t add the <a class="reference internal" href="../library/site.html#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">user</span> <span class="pre">site-packages</span> <span class="pre">directory</span></code></a> to
<a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> – Per user site-packages directory</p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="id2">
<code class="descname">-S</code><code class="descclassname"></code><a class="headerlink" href="#id2" title="Permalink to this definition">¶</a></dt>
<dd><p>Disable the import of the module <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> and the site-dependent
manipulations of <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> that it entails.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-t">
<code class="descname">-t</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-t" title="Permalink to this definition">¶</a></dt>
<dd><p>Issue a warning when a source file mixes tabs and spaces for indentation in a
way that makes it depend on the worth of a tab expressed in spaces.  Issue an
error when the option is given twice (<code class="xref std std-option docutils literal notranslate"><span class="pre">-tt</span></code>).</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-u">
<code class="descname">-u</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-u" title="Permalink to this definition">¶</a></dt>
<dd><p>Force stdin, stdout and stderr to be totally unbuffered.  On systems where it
matters, also put stdin, stdout and stderr in binary mode.</p>
<p>Note that there is internal buffering in <a class="reference internal" href="../library/stdtypes.html#file.readlines" title="file.readlines"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.readlines()</span></code></a> and
<a class="reference internal" href="../library/stdtypes.html#bltin-file-objects"><span class="std std-ref">File Objects</span></a> (<code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">sys.stdin</span></code>) which is not influenced
by this option.  To work around this, you will want to use
<a class="reference internal" href="../library/stdtypes.html#file.readline" title="file.readline"><code class="xref py py-meth docutils literal notranslate"><span class="pre">file.readline()</span></code></a> inside a <code class="docutils literal notranslate"><span class="pre">while</span> <span class="pre">1:</span></code> loop.</p>
<p>See also <span class="target" id="index-12"></span><a class="reference internal" href="#envvar-PYTHONUNBUFFERED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUNBUFFERED</span></code></a>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="id3">
<code class="descname">-v</code><code class="descclassname"></code><a class="headerlink" href="#id3" title="Permalink to this definition">¶</a></dt>
<dd><p>Print a message each time a module is initialized, showing the place
(filename or built-in module) from which it is loaded.  When given twice
(<code class="xref std std-option docutils literal notranslate"><span class="pre">-vv</span></code>), print a message for each file that is checked for when
searching for a module.  Also provides information on module cleanup at exit.
See also <span class="target" id="index-13"></span><a class="reference internal" href="#envvar-PYTHONVERBOSE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONVERBOSE</span></code></a>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-w">
<code class="descname">-W</code><code class="descclassname"> arg</code><a class="headerlink" href="#cmdoption-w" title="Permalink to this definition">¶</a></dt>
<dd><p>Warning control.  Python’s warning machinery by default prints warning
messages to <a class="reference internal" href="../library/sys.html#sys.stderr" title="sys.stderr"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.stderr</span></code></a>.  A typical warning message has the following
form:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>file:line: category: message
</pre></div>
</div>
<p>By default, each warning is printed once for each source line where it
occurs.  This option controls how often warnings are printed.</p>
<p>Multiple <a class="reference internal" href="#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> options may be given; when a warning matches more than
one option, the action for the last matching option is performed.  Invalid
<a class="reference internal" href="#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> options are ignored (though, a warning message is printed about
invalid options when the first warning is issued).</p>
<p>Starting from Python 2.7, <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and its descendants
are ignored by default.  The <code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code> option can be used to re-enable
them.</p>
<p>Warnings can also be controlled from within a Python program using the
<a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module.</p>
<p>The simplest form of argument is one of the following action strings (or a
unique abbreviation) by themselves:</p>
<dl class="docutils">
<dt><code class="docutils literal notranslate"><span class="pre">ignore</span></code></dt>
<dd>Ignore all warnings.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">default</span></code></dt>
<dd>Explicitly request the default behavior (printing each warning once per
source line).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">all</span></code></dt>
<dd>Print a warning each time it occurs (this may generate many messages if a
warning is triggered repeatedly for the same source line, such as inside a
loop).</dd>
<dt><code class="docutils literal notranslate"><span class="pre">module</span></code></dt>
<dd>Print each warning only the first time it occurs in each module.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">once</span></code></dt>
<dd>Print each warning only the first time it occurs in the program.</dd>
<dt><code class="docutils literal notranslate"><span class="pre">error</span></code></dt>
<dd>Raise an exception instead of printing a warning message.</dd>
</dl>
<p>The full form of argument is:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>action:message:category:module:line
</pre></div>
</div>
<p>Here, <em>action</em> is as explained above but only applies to messages that match
the remaining fields.  Empty fields match all values; trailing empty fields
may be omitted.  The <em>message</em> field matches the start of the warning message
printed; this match is case-insensitive.  The <em>category</em> field matches the
warning category.  This must be a class name; the match tests whether the
actual warning category of the message is a subclass of the specified warning
category.  The full class name must be given.  The <em>module</em> field matches the
(fully-qualified) module name; this match is case-sensitive.  The <em>line</em>
field matches the line number, where zero matches all line numbers and is
thus equivalent to an omitted line number.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p><a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> – the warnings module</p>
<p><span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0230"><strong>PEP 230</strong></a> – Warning framework</p>
<p class="last"><span class="target" id="index-15"></span><a class="reference internal" href="#envvar-PYTHONWARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONWARNINGS</span></code></a></p>
</div>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-x">
<code class="descname">-x</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-x" title="Permalink to this definition">¶</a></dt>
<dd><p>Skip the first line of the source, allowing use of non-Unix forms of
<code class="docutils literal notranslate"><span class="pre">#!cmd</span></code>.  This is intended for a DOS specific hack only.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="cmdoption-3">
<code class="descname">-3</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-3" title="Permalink to this definition">¶</a></dt>
<dd><p>Warn about Python 3.x possible incompatibilities by emitting a
<a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> for features that are removed or significantly
changed in Python 3 and can’t be detected using static code analysis.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<p>See <a class="reference internal" href="../howto/pyporting.html"><span class="doc">Porting Python 2 Code to Python 3</span></a> for more details.</p>
</dd></dl>

</div>
<div class="section" id="options-you-shouldn-t-use">
<h3>1.1.4. Options you shouldn’t use<a class="headerlink" href="#options-you-shouldn-t-use" title="Permalink to this headline">¶</a></h3>
<dl class="cmdoption">
<dt id="cmdoption-j">
<code class="descname">-J</code><code class="descclassname"></code><a class="headerlink" href="#cmdoption-j" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for use by <a class="reference external" href="http://www.jython.org/">Jython</a>.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="id4">
<code class="descname">-U</code><code class="descclassname"></code><a class="headerlink" href="#id4" title="Permalink to this definition">¶</a></dt>
<dd><p>Turns all string literals into unicodes globally.  Do not be tempted to use
this option as it will probably break your world.  It also produces
<code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files with a different magic number than normal.  Instead, you can
enable unicode literals on a per-module basis by using:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>from __future__ import unicode_literals
</pre></div>
</div>
<p>at the top of the file.  See <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a> for details.</p>
</dd></dl>

<dl class="cmdoption">
<dt id="id5">
<code class="descname">-X</code><code class="descclassname"></code><a class="headerlink" href="#id5" title="Permalink to this definition">¶</a></dt>
<dd><p>Reserved for alternative implementations of Python to use for their own
purposes.</p>
</dd></dl>

</div>
</div>
<div class="section" id="environment-variables">
<span id="using-on-envvars"></span><h2>1.2. Environment variables<a class="headerlink" href="#environment-variables" title="Permalink to this headline">¶</a></h2>
<p>These environment variables influence Python’s behavior, they are processed
before the command-line switches other than -E.  It is customary that
command-line switches override environmental variables where there is a
conflict.</p>
<dl class="envvar">
<dt id="envvar-PYTHONHOME">
<code class="descname">PYTHONHOME</code><a class="headerlink" href="#envvar-PYTHONHOME" title="Permalink to this definition">¶</a></dt>
<dd><p>Change the location of the standard Python libraries.  By default, the
libraries are searched in <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">version</span></em></code> and
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">version</span></em></code>, where <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em></code> are installation-dependent directories, both defaulting
to <code class="file docutils literal notranslate"><span class="pre">/usr/local</span></code>.</p>
<p>When <span class="target" id="index-16"></span><a class="reference internal" href="#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> is set to a single directory, its value replaces
both <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em></code> and <code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em></code>.  To specify different values
for these, set <span class="target" id="index-17"></span><a class="reference internal" href="#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> to <code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">:</span><em><span class="pre">exec_prefix</span></em></code>.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONPATH">
<code class="descname">PYTHONPATH</code><a class="headerlink" href="#envvar-PYTHONPATH" title="Permalink to this definition">¶</a></dt>
<dd><p>Augment the default search path for module files.  The format is the same as
the shell’s <span class="target" id="index-18"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>: one or more directory pathnames separated by
<a class="reference internal" href="../library/os.html#os.pathsep" title="os.pathsep"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.pathsep</span></code></a> (e.g. colons on Unix or semicolons on Windows).
Non-existent directories are silently ignored.</p>
<p>In addition to normal directories, individual <span class="target" id="index-19"></span><a class="reference internal" href="#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> entries
may refer to zipfiles containing pure Python modules (in either source or
compiled form). Extension modules cannot be imported from zipfiles.</p>
<p>The default search path is installation dependent, but generally begins with
<code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">version</span></em></code> (see <span class="target" id="index-20"></span><a class="reference internal" href="#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> above).  It
is <em>always</em> appended to <span class="target" id="index-21"></span><a class="reference internal" href="#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>.</p>
<p>An additional directory will be inserted in the search path in front of
<span class="target" id="index-22"></span><a class="reference internal" href="#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> as described above under
<a class="reference internal" href="#using-on-interface-options"><span class="std std-ref">Interface options</span></a>. The search path can be manipulated from
within a Python program as the variable <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONSTARTUP">
<code class="descname">PYTHONSTARTUP</code><a class="headerlink" href="#envvar-PYTHONSTARTUP" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is the name of a readable file, the Python commands in that file are
executed before the first prompt is displayed in interactive mode.  The file
is executed in the same namespace where interactive commands are executed so
that objects defined or imported in it can be used without qualification in
the interactive session.  You can also change the prompts <a class="reference internal" href="../library/sys.html#sys.ps1" title="sys.ps1"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.ps1</span></code></a> and
<a class="reference internal" href="../library/sys.html#sys.ps2" title="sys.ps2"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.ps2</span></code></a> in this file.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONY2K">
<code class="descname">PYTHONY2K</code><a class="headerlink" href="#envvar-PYTHONY2K" title="Permalink to this definition">¶</a></dt>
<dd><p>Set this to a non-empty string to cause the <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module to require
dates specified as strings to include 4-digit years, otherwise 2-digit years
are converted based on rules described in the <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module
documentation.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONOPTIMIZE">
<code class="descname">PYTHONOPTIMIZE</code><a class="headerlink" href="#envvar-PYTHONOPTIMIZE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set to a non-empty string it is equivalent to specifying the
<a class="reference internal" href="#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> option.  If set to an integer, it is equivalent to specifying
<a class="reference internal" href="#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> multiple times.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONDEBUG">
<code class="descname">PYTHONDEBUG</code><a class="headerlink" href="#envvar-PYTHONDEBUG" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set to a non-empty string it is equivalent to specifying the
<a class="reference internal" href="#cmdoption-d"><code class="xref std std-option docutils literal notranslate"><span class="pre">-d</span></code></a> option.  If set to an integer, it is equivalent to specifying
<a class="reference internal" href="#cmdoption-d"><code class="xref std std-option docutils literal notranslate"><span class="pre">-d</span></code></a> multiple times.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONINSPECT">
<code class="descname">PYTHONINSPECT</code><a class="headerlink" href="#envvar-PYTHONINSPECT" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set to a non-empty string it is equivalent to specifying the
<a class="reference internal" href="#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> option.</p>
<p>This variable can also be modified by Python code using <a class="reference internal" href="../library/os.html#os.environ" title="os.environ"><code class="xref py py-data docutils literal notranslate"><span class="pre">os.environ</span></code></a>
to force inspect mode on program termination.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONUNBUFFERED">
<code class="descname">PYTHONUNBUFFERED</code><a class="headerlink" href="#envvar-PYTHONUNBUFFERED" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set to a non-empty string it is equivalent to specifying the
<a class="reference internal" href="#cmdoption-u"><code class="xref std std-option docutils literal notranslate"><span class="pre">-u</span></code></a> option.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONVERBOSE">
<code class="descname">PYTHONVERBOSE</code><a class="headerlink" href="#envvar-PYTHONVERBOSE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set to a non-empty string it is equivalent to specifying the
<a class="reference internal" href="#id3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code></a> option.  If set to an integer, it is equivalent to specifying
<a class="reference internal" href="#id3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code></a> multiple times.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONCASEOK">
<code class="descname">PYTHONCASEOK</code><a class="headerlink" href="#envvar-PYTHONCASEOK" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set, Python ignores case in <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements.  This
only works on Windows, OS X, OS/2, and RiscOS.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONDONTWRITEBYTECODE">
<code class="descname">PYTHONDONTWRITEBYTECODE</code><a class="headerlink" href="#envvar-PYTHONDONTWRITEBYTECODE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set, Python won’t try to write <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="docutils literal notranslate"><span class="pre">.pyo</span></code> files on the
import of source modules.  This is equivalent to specifying the <a class="reference internal" href="#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a>
option.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONHASHSEED">
<code class="descname">PYTHONHASHSEED</code><a class="headerlink" href="#envvar-PYTHONHASHSEED" title="Permalink to this definition">¶</a></dt>
<dd><p>If this variable is set to <code class="docutils literal notranslate"><span class="pre">random</span></code>, the effect is the same as specifying
the <a class="reference internal" href="#cmdoption-r"><code class="xref std std-option docutils literal notranslate"><span class="pre">-R</span></code></a> option: a random value is used to seed the hashes of str,
bytes and datetime objects.</p>
<p>If <span class="target" id="index-23"></span><a class="reference internal" href="#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHASHSEED</span></code></a> is set to an integer value, it is used as a
fixed seed for generating the hash() of the types covered by the hash
randomization.</p>
<p>Its purpose is to allow repeatable hashing, such as for selftests for the
interpreter itself, or to allow a cluster of python processes to share hash
values.</p>
<p>The integer must be a decimal number in the range [0,4294967295].
Specifying the value 0 will lead to the same hash values as when hash
randomization is disabled.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.8.</span></p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONIOENCODING">
<code class="descname">PYTHONIOENCODING</code><a class="headerlink" href="#envvar-PYTHONIOENCODING" title="Permalink to this definition">¶</a></dt>
<dd><p>Overrides the encoding used for stdin/stdout/stderr, in the syntax
<code class="docutils literal notranslate"><span class="pre">encodingname:errorhandler</span></code>.  The <code class="docutils literal notranslate"><span class="pre">:errorhandler</span></code> part is optional and
has the same meaning as in <a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><code class="xref py py-func docutils literal notranslate"><span class="pre">str.encode()</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONNOUSERSITE">
<code class="descname">PYTHONNOUSERSITE</code><a class="headerlink" href="#envvar-PYTHONNOUSERSITE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this is set, Python won’t add the <a class="reference internal" href="../library/site.html#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">user</span> <span class="pre">site-packages</span> <span class="pre">directory</span></code></a> to <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><span class="target" id="index-24"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> – Per user site-packages directory</p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONUSERBASE">
<code class="descname">PYTHONUSERBASE</code><a class="headerlink" href="#envvar-PYTHONUSERBASE" title="Permalink to this definition">¶</a></dt>
<dd><p>Defines the <a class="reference internal" href="../library/site.html#site.USER_BASE" title="site.USER_BASE"><code class="xref py py-data docutils literal notranslate"><span class="pre">user</span> <span class="pre">base</span> <span class="pre">directory</span></code></a>, which is used to
compute the path of the <a class="reference internal" href="../library/site.html#site.USER_SITE" title="site.USER_SITE"><code class="xref py py-data docutils literal notranslate"><span class="pre">user</span> <span class="pre">site-packages</span> <span class="pre">directory</span></code></a>
and <a class="reference internal" href="../install/index.html#inst-alt-install-user"><span class="std std-ref">Distutils installation paths</span></a> for <code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">install</span> <span class="pre">--user</span></code>.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.6.</span></p>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> – Per user site-packages directory</p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONEXECUTABLE">
<code class="descname">PYTHONEXECUTABLE</code><a class="headerlink" href="#envvar-PYTHONEXECUTABLE" title="Permalink to this definition">¶</a></dt>
<dd><p>If this environment variable is set, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> will be set to its
value instead of the value got through the C runtime.  Only works on
Mac OS X.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONWARNINGS">
<code class="descname">PYTHONWARNINGS</code><a class="headerlink" href="#envvar-PYTHONWARNINGS" title="Permalink to this definition">¶</a></dt>
<dd><p>This is equivalent to the <a class="reference internal" href="#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> option. If set to a comma
separated string, it is equivalent to specifying <a class="reference internal" href="#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> multiple
times.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONHTTPSVERIFY">
<code class="descname">PYTHONHTTPSVERIFY</code><a class="headerlink" href="#envvar-PYTHONHTTPSVERIFY" title="Permalink to this definition">¶</a></dt>
<dd><p>If this environment variable is set specifically to <code class="docutils literal notranslate"><span class="pre">0</span></code>, then it is
equivalent to implicitly calling <a class="reference internal" href="../library/ssl.html#ssl._https_verify_certificates" title="ssl._https_verify_certificates"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl._https_verify_certificates()</span></code></a> with
<code class="docutils literal notranslate"><span class="pre">enable=False</span></code> when <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> is first imported.</p>
<p>Refer to the documentation of <a class="reference internal" href="../library/ssl.html#ssl._https_verify_certificates" title="ssl._https_verify_certificates"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl._https_verify_certificates()</span></code></a> for
details.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.12.</span></p>
</div>
</dd></dl>

<div class="section" id="debug-mode-variables">
<h3>1.2.1. Debug-mode variables<a class="headerlink" href="#debug-mode-variables" title="Permalink to this headline">¶</a></h3>
<p>Setting these variables only has an effect in a debug build of Python, that is,
if Python was configured with the <code class="docutils literal notranslate"><span class="pre">--with-pydebug</span></code> build option.</p>
<dl class="envvar">
<dt id="envvar-PYTHONTHREADDEBUG">
<code class="descname">PYTHONTHREADDEBUG</code><a class="headerlink" href="#envvar-PYTHONTHREADDEBUG" title="Permalink to this definition">¶</a></dt>
<dd><p>If set, Python will print threading debug info.</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.6: </span>Previously, this variable was called <code class="docutils literal notranslate"><span class="pre">THREADDEBUG</span></code>.</p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONDUMPREFS">
<code class="descname">PYTHONDUMPREFS</code><a class="headerlink" href="#envvar-PYTHONDUMPREFS" title="Permalink to this definition">¶</a></dt>
<dd><p>If set, Python will dump objects and reference counts still alive after
shutting down the interpreter.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONMALLOCSTATS">
<code class="descname">PYTHONMALLOCSTATS</code><a class="headerlink" href="#envvar-PYTHONMALLOCSTATS" title="Permalink to this definition">¶</a></dt>
<dd><p>If set, Python will print memory allocation statistics every time a new
object arena is created, and on shutdown.</p>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONSHOWALLOCCOUNT">
<code class="descname">PYTHONSHOWALLOCCOUNT</code><a class="headerlink" href="#envvar-PYTHONSHOWALLOCCOUNT" title="Permalink to this definition">¶</a></dt>
<dd><p>If set and Python was compiled with <code class="docutils literal notranslate"><span class="pre">COUNT_ALLOCS</span></code> defined, Python will
dump allocations counts into stderr on shutdown.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.15.</span></p>
</div>
</dd></dl>

<dl class="envvar">
<dt id="envvar-PYTHONSHOWREFCOUNT">
<code class="descname">PYTHONSHOWREFCOUNT</code><a class="headerlink" href="#envvar-PYTHONSHOWREFCOUNT" title="Permalink to this definition">¶</a></dt>
<dd><p>If set, Python will print the total reference count when the program
finishes or after each statement in the interactive interpreter.</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.15.</span></p>
</div>
</dd></dl>

</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">1. Command line and environment</a><ul>
<li><a class="reference internal" href="#command-line">1.1. Command line</a><ul>
<li><a class="reference internal" href="#interface-options">1.1.1. Interface options</a></li>
<li><a class="reference internal" href="#generic-options">1.1.2. Generic options</a></li>
<li><a class="reference internal" href="#miscellaneous-options">1.1.3. Miscellaneous options</a></li>
<li><a class="reference internal" href="#options-you-shouldn-t-use">1.1.4. Options you shouldn’t use</a></li>
</ul>
</li>
<li><a class="reference internal" href="#environment-variables">1.2. Environment variables</a><ul>
<li><a class="reference internal" href="#debug-mode-variables">1.2.1. Debug-mode variables</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">Python Setup and Usage</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="unix.html"
                        title="next chapter">2. Using Python on Unix platforms</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/using/cmdline.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="unix.html" title="2. Using Python on Unix platforms"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Python Setup and Usage"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\����,�,html/using/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python Setup and Usage &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="1. Command line and environment" href="cmdline.html" />
    <link rel="prev" title="15. Appendix" href="../tutorial/appendix.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/using/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmdline.html" title="1. Command line and environment"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../tutorial/appendix.html" title="15. Appendix"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-setup-and-usage">
<span id="using-index"></span><h1>Python Setup and Usage<a class="headerlink" href="#python-setup-and-usage" title="Permalink to this headline">¶</a></h1>
<p>This part of the documentation is devoted to general information on the setup
of the Python environment on different platforms, the invocation of the
interpreter and things that make working with Python easier.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="cmdline.html">1. Command line and environment</a><ul>
<li class="toctree-l2"><a class="reference internal" href="cmdline.html#command-line">1.1. Command line</a><ul>
<li class="toctree-l3"><a class="reference internal" href="cmdline.html#interface-options">1.1.1. Interface options</a></li>
<li class="toctree-l3"><a class="reference internal" href="cmdline.html#generic-options">1.1.2. Generic options</a></li>
<li class="toctree-l3"><a class="reference internal" href="cmdline.html#miscellaneous-options">1.1.3. Miscellaneous options</a></li>
<li class="toctree-l3"><a class="reference internal" href="cmdline.html#options-you-shouldn-t-use">1.1.4. Options you shouldn’t use</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="cmdline.html#environment-variables">1.2. Environment variables</a><ul>
<li class="toctree-l3"><a class="reference internal" href="cmdline.html#debug-mode-variables">1.2.1. Debug-mode variables</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="unix.html">2. Using Python on Unix platforms</a><ul>
<li class="toctree-l2"><a class="reference internal" href="unix.html#getting-and-installing-the-latest-version-of-python">2.1. Getting and installing the latest version of Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="unix.html#on-linux">2.1.1. On Linux</a></li>
<li class="toctree-l3"><a class="reference internal" href="unix.html#on-freebsd-and-openbsd">2.1.2. On FreeBSD and OpenBSD</a></li>
<li class="toctree-l3"><a class="reference internal" href="unix.html#on-opensolaris">2.1.3. On OpenSolaris</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="unix.html#building-python">2.2. Building Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="unix.html#python-related-paths-and-files">2.3. Python-related paths and files</a></li>
<li class="toctree-l2"><a class="reference internal" href="unix.html#miscellaneous">2.4. Miscellaneous</a></li>
<li class="toctree-l2"><a class="reference internal" href="unix.html#editors-and-ides">2.5. Editors and IDEs</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="windows.html">3. Using Python on Windows</a><ul>
<li class="toctree-l2"><a class="reference internal" href="windows.html#installing-python">3.1. Installing Python</a></li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#alternative-bundles">3.2. Alternative bundles</a></li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#configuring-python">3.3. Configuring Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="windows.html#excursus-setting-environment-variables">3.3.1. Excursus: Setting environment variables</a></li>
<li class="toctree-l3"><a class="reference internal" href="windows.html#finding-the-python-executable">3.3.2. Finding the Python executable</a></li>
<li class="toctree-l3"><a class="reference internal" href="windows.html#finding-modules">3.3.3. Finding modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="windows.html#executing-scripts">3.3.4. Executing scripts</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#additional-modules">3.4. Additional modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="windows.html#pywin32">3.4.1. PyWin32</a></li>
<li class="toctree-l3"><a class="reference internal" href="windows.html#py2exe">3.4.2. Py2exe</a></li>
<li class="toctree-l3"><a class="reference internal" href="windows.html#wconio">3.4.3. WConio</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#compiling-python-on-windows">3.5. Compiling Python on Windows</a></li>
<li class="toctree-l2"><a class="reference internal" href="windows.html#other-resources">3.6. Other resources</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="mac.html">4. Using Python on a Macintosh</a><ul>
<li class="toctree-l2"><a class="reference internal" href="mac.html#getting-and-installing-macpython">4.1. Getting and Installing MacPython</a><ul>
<li class="toctree-l3"><a class="reference internal" href="mac.html#how-to-run-a-python-script">4.1.1. How to run a Python script</a></li>
<li class="toctree-l3"><a class="reference internal" href="mac.html#running-scripts-with-a-gui">4.1.2. Running scripts with a GUI</a></li>
<li class="toctree-l3"><a class="reference internal" href="mac.html#configuration">4.1.3. Configuration</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="mac.html#the-ide">4.2. The IDE</a></li>
<li class="toctree-l2"><a class="reference internal" href="mac.html#installing-additional-python-packages">4.3. Installing Additional Python Packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="mac.html#gui-programming-on-the-mac">4.4. GUI Programming on the Mac</a></li>
<li class="toctree-l2"><a class="reference internal" href="mac.html#distributing-python-applications-on-the-mac">4.5. Distributing Python Applications on the Mac</a></li>
<li class="toctree-l2"><a class="reference internal" href="mac.html#other-resources">4.6. Other Resources</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../tutorial/appendix.html"
                        title="previous chapter">15. Appendix</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="cmdline.html"
                        title="next chapter">1. Command line and environment</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/using/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="cmdline.html" title="1. Command line and environment"
             >next</a> |</li>
        <li class="right" >
          <a href="../tutorial/appendix.html" title="15. Appendix"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ۙ�C�M�Mhtml/using/mac.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>4. Using Python on a Macintosh &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="The Python Language Reference" href="../reference/index.html" />
    <link rel="prev" title="3. Using Python on Windows" href="windows.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/using/mac.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../reference/index.html" title="The Python Language Reference"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="3. Using Python on Windows"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="using-python-on-a-macintosh">
<span id="using-on-mac"></span><h1>4. Using Python on a Macintosh<a class="headerlink" href="#using-python-on-a-macintosh" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">Bob Savage &lt;<a class="reference external" href="mailto:bobsavage&#37;&#52;&#48;mac&#46;com">bobsavage<span>&#64;</span>mac<span>&#46;</span>com</a>&gt;</td>
</tr>
</tbody>
</table>
<p>Python on a Macintosh running Mac OS X is in principle very similar to Python on
any other Unix platform, but there are a number of additional features such as
the IDE and the Package Manager that are worth pointing out.</p>
<p>The Mac-specific modules are documented in <a class="reference internal" href="../library/mac.html#mac-specific-services"><span class="std std-ref">Mac OS X specific services</span></a>.</p>
<p>Python on Mac OS 9 or earlier can be quite different from Python on Unix or
Windows, but is beyond the scope of this manual, as that platform is no longer
supported, starting with Python 2.4. See <a class="reference external" href="http://www.cwi.nl/~jack/macpython">http://www.cwi.nl/~jack/macpython</a> for
installers for the latest 2.3 release for Mac OS 9 and related documentation.</p>
<div class="section" id="getting-and-installing-macpython">
<span id="getting-osx"></span><h2>4.1. Getting and Installing MacPython<a class="headerlink" href="#getting-and-installing-macpython" title="Permalink to this headline">¶</a></h2>
<p>Mac OS X 10.8 comes with Python 2.7 pre-installed by Apple.  If you wish, you
are invited to install the most recent version of Python from the Python website
(<a class="reference external" href="https://www.python.org">https://www.python.org</a>).  A current “universal binary” build of Python, which
runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there.</p>
<p>What you get after installing is a number of things:</p>
<ul class="simple">
<li>A <code class="file docutils literal notranslate"><span class="pre">MacPython</span> <span class="pre">2.7</span></code> folder in your <code class="file docutils literal notranslate"><span class="pre">Applications</span></code> folder. In here
you find IDLE, the development environment that is a standard part of official
Python distributions; PythonLauncher, which handles double-clicking Python
scripts from the Finder; and the “Build Applet” tool, which allows you to
package Python scripts as standalone applications on your system.</li>
<li>A framework <code class="file docutils literal notranslate"><span class="pre">/Library/Frameworks/Python.framework</span></code>, which includes the
Python executable and libraries. The installer adds this location to your shell
path. To uninstall MacPython, you can simply remove these three things. A
symlink to the Python executable is placed in /usr/local/bin/.</li>
</ul>
<p>The Apple-provided build of Python is installed in
<code class="file docutils literal notranslate"><span class="pre">/System/Library/Frameworks/Python.framework</span></code> and <code class="file docutils literal notranslate"><span class="pre">/usr/bin/python</span></code>,
respectively. You should never modify or delete these, as they are
Apple-controlled and are used by Apple- or third-party software.  Remember that
if you choose to install a newer Python version from python.org, you will have
two different but functional Python installations on your computer, so it will
be important that your paths and usages are consistent with what you want to do.</p>
<p>IDLE includes a help menu that allows you to access Python documentation. If you
are completely new to Python you should start reading the tutorial introduction
in that document.</p>
<p>If you are familiar with Python on other Unix platforms you should read the
section on running Python scripts from the Unix shell.</p>
<div class="section" id="how-to-run-a-python-script">
<h3>4.1.1. How to run a Python script<a class="headerlink" href="#how-to-run-a-python-script" title="Permalink to this headline">¶</a></h3>
<p>Your best way to get started with Python on Mac OS X is through the IDLE
integrated development environment, see section <a class="reference internal" href="#ide"><span class="std std-ref">The IDE</span></a> and use the Help menu
when the IDE is running.</p>
<p>If you want to run Python scripts from the Terminal window command line or from
the Finder you first need an editor to create your script. Mac OS X comes with a
number of standard Unix command line editors, <strong class="program">vim</strong> and
<strong class="program">emacs</strong> among them. If you want a more Mac-like editor,
<strong class="program">BBEdit</strong> or <strong class="program">TextWrangler</strong> from Bare Bones Software (see
<a class="reference external" href="http://www.barebones.com/products/bbedit/index.html">http://www.barebones.com/products/bbedit/index.html</a>) are good choices, as is
<strong class="program">TextMate</strong> (see <a class="reference external" href="https://macromates.com/">https://macromates.com/</a>). Other editors include
<strong class="program">Gvim</strong> (<a class="reference external" href="http://macvim.org">http://macvim.org</a>) and <strong class="program">Aquamacs</strong>
(<a class="reference external" href="http://aquamacs.org/">http://aquamacs.org/</a>).</p>
<p>To run your script from the Terminal window you must make sure that
<code class="file docutils literal notranslate"><span class="pre">/usr/local/bin</span></code> is in your shell search path.</p>
<p>To run your script from the Finder you have two options:</p>
<ul class="simple">
<li>Drag it to <strong class="program">PythonLauncher</strong></li>
<li>Select <strong class="program">PythonLauncher</strong> as the default application to open your
script (or any .py script) through the finder Info window and double-click it.
<strong class="program">PythonLauncher</strong> has various preferences to control how your script is
launched. Option-dragging allows you to change these for one invocation, or use
its Preferences menu to change things globally.</li>
</ul>
</div>
<div class="section" id="running-scripts-with-a-gui">
<span id="osx-gui-scripts"></span><h3>4.1.2. Running scripts with a GUI<a class="headerlink" href="#running-scripts-with-a-gui" title="Permalink to this headline">¶</a></h3>
<p>With older versions of Python, there is one Mac OS X quirk that you need to be
aware of: programs that talk to the Aqua window manager (in other words,
anything that has a GUI) need to be run in a special way. Use <strong class="program">pythonw</strong>
instead of <strong class="program">python</strong> to start such scripts.</p>
<p>With Python 2.7, you can use either <strong class="program">python</strong> or <strong class="program">pythonw</strong>.</p>
</div>
<div class="section" id="configuration">
<h3>4.1.3. Configuration<a class="headerlink" href="#configuration" title="Permalink to this headline">¶</a></h3>
<p>Python on OS X honors all standard Unix environment variables such as
<span class="target" id="index-0"></span><a class="reference internal" href="cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>, but setting these variables for programs started from the
Finder is non-standard as the Finder does not read your <code class="file docutils literal notranslate"><span class="pre">.profile</span></code> or
<code class="file docutils literal notranslate"><span class="pre">.cshrc</span></code> at startup. You need to create a file
<code class="file docutils literal notranslate"><span class="pre">~/.MacOSX/environment.plist</span></code>. See Apple’s Technical Document QA1067 for
details.</p>
<p>For more information on installation Python packages in MacPython, see section
<a class="reference internal" href="#mac-package-manager"><span class="std std-ref">Installing Additional Python Packages</span></a>.</p>
</div>
</div>
<div class="section" id="the-ide">
<span id="ide"></span><h2>4.2. The IDE<a class="headerlink" href="#the-ide" title="Permalink to this headline">¶</a></h2>
<p>MacPython ships with the standard IDLE development environment. A good
introduction to using IDLE can be found at
<a class="reference external" href="https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html">https://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html</a>.</p>
</div>
<div class="section" id="installing-additional-python-packages">
<span id="mac-package-manager"></span><h2>4.3. Installing Additional Python Packages<a class="headerlink" href="#installing-additional-python-packages" title="Permalink to this headline">¶</a></h2>
<p>There are several methods to install additional Python packages:</p>
<ul class="simple">
<li>Packages can be installed via the standard Python distutils mode (<code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">install</span></code>).</li>
<li>Many packages can also be installed via the <strong class="program">setuptools</strong> extension
or <strong class="program">pip</strong> wrapper, see <a class="reference external" href="https://pip.pypa.io/">https://pip.pypa.io/</a>.</li>
</ul>
</div>
<div class="section" id="gui-programming-on-the-mac">
<h2>4.4. GUI Programming on the Mac<a class="headerlink" href="#gui-programming-on-the-mac" title="Permalink to this headline">¶</a></h2>
<p>There are several options for building GUI applications on the Mac with Python.</p>
<p><em>PyObjC</em> is a Python binding to Apple’s Objective-C/Cocoa framework, which is
the foundation of most modern Mac development. Information on PyObjC is
available from <a class="reference external" href="https://pythonhosted.org/pyobjc/">https://pythonhosted.org/pyobjc/</a>.</p>
<p>The standard Python GUI toolkit is <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a>, based on the cross-platform
Tk toolkit (<a class="reference external" href="https://www.tcl.tk">https://www.tcl.tk</a>). An Aqua-native version of Tk is bundled with OS
X by Apple, and the latest version can be downloaded and installed from
<a class="reference external" href="https://www.activestate.com">https://www.activestate.com</a>; it can also be built from source.</p>
<p><em>wxPython</em> is another popular cross-platform GUI toolkit that runs natively on
Mac OS X. Packages and documentation are available from <a class="reference external" href="http://www.wxpython.org">http://www.wxpython.org</a>.</p>
<p><em>PyQt</em> is another popular cross-platform GUI toolkit that runs natively on Mac
OS X. More information can be found at
<a class="reference external" href="https://riverbankcomputing.com/software/pyqt/intro">https://riverbankcomputing.com/software/pyqt/intro</a>.</p>
</div>
<div class="section" id="distributing-python-applications-on-the-mac">
<h2>4.5. Distributing Python Applications on the Mac<a class="headerlink" href="#distributing-python-applications-on-the-mac" title="Permalink to this headline">¶</a></h2>
<p>The “Build Applet” tool that is placed in the MacPython 2.7 folder is fine for
packaging small Python scripts on your own machine to run as a standard Mac
application. This tool, however, is not robust enough to distribute Python
applications to other users.</p>
<p>The standard tool for deploying standalone Python applications on the Mac is
<strong class="program">py2app</strong>. More information on installing and using py2app can be found
at <a class="reference external" href="http://undefined.org/python/#py2app">http://undefined.org/python/#py2app</a>.</p>
</div>
<div class="section" id="other-resources">
<h2>4.6. Other Resources<a class="headerlink" href="#other-resources" title="Permalink to this headline">¶</a></h2>
<p>The MacPython mailing list is an excellent support resource for Python users and
developers on the Mac:</p>
<p><a class="reference external" href="https://www.python.org/community/sigs/current/pythonmac-sig/">https://www.python.org/community/sigs/current/pythonmac-sig/</a></p>
<p>Another useful resource is the MacPython wiki:</p>
<p><a class="reference external" href="https://wiki.python.org/moin/MacPython">https://wiki.python.org/moin/MacPython</a></p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">4. Using Python on a Macintosh</a><ul>
<li><a class="reference internal" href="#getting-and-installing-macpython">4.1. Getting and Installing MacPython</a><ul>
<li><a class="reference internal" href="#how-to-run-a-python-script">4.1.1. How to run a Python script</a></li>
<li><a class="reference internal" href="#running-scripts-with-a-gui">4.1.2. Running scripts with a GUI</a></li>
<li><a class="reference internal" href="#configuration">4.1.3. Configuration</a></li>
</ul>
</li>
<li><a class="reference internal" href="#the-ide">4.2. The IDE</a></li>
<li><a class="reference internal" href="#installing-additional-python-packages">4.3. Installing Additional Python Packages</a></li>
<li><a class="reference internal" href="#gui-programming-on-the-mac">4.4. GUI Programming on the Mac</a></li>
<li><a class="reference internal" href="#distributing-python-applications-on-the-mac">4.5. Distributing Python Applications on the Mac</a></li>
<li><a class="reference internal" href="#other-resources">4.6. Other Resources</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="windows.html"
                        title="previous chapter">3. Using Python on Windows</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../reference/index.html"
                        title="next chapter">The Python Language Reference</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/using/mac.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../reference/index.html" title="The Python Language Reference"
             >next</a> |</li>
        <li class="right" >
          <a href="windows.html" title="3. Using Python on Windows"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��3C3Chtml/using/unix.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>2. Using Python on Unix platforms &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="3. Using Python on Windows" href="windows.html" />
    <link rel="prev" title="1. Command line and environment" href="cmdline.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/using/unix.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="3. Using Python on Windows"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="cmdline.html" title="1. Command line and environment"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="using-python-on-unix-platforms">
<span id="using-on-unix"></span><h1>2. Using Python on Unix platforms<a class="headerlink" href="#using-python-on-unix-platforms" title="Permalink to this headline">¶</a></h1>
<div class="section" id="getting-and-installing-the-latest-version-of-python">
<h2>2.1. Getting and installing the latest version of Python<a class="headerlink" href="#getting-and-installing-the-latest-version-of-python" title="Permalink to this headline">¶</a></h2>
<div class="section" id="on-linux">
<h3>2.1.1. On Linux<a class="headerlink" href="#on-linux" title="Permalink to this headline">¶</a></h3>
<p>Python comes preinstalled on most Linux distributions, and is available as a
package on all others.  However there are certain features you might want to use
that are not available on your distro’s package.  You can easily compile the
latest version of Python from source.</p>
<p>In the event that Python doesn’t come preinstalled and isn’t in the repositories as
well, you can easily make packages for your own distro.  Have a look at the
following links:</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://www.debian.org/doc/manuals/maint-guide/first.en.html">https://www.debian.org/doc/manuals/maint-guide/first.en.html</a></dt>
<dd>for Debian users</dd>
<dt><a class="reference external" href="https://en.opensuse.org/Portal:Packaging">https://en.opensuse.org/Portal:Packaging</a></dt>
<dd>for OpenSuse users</dd>
<dt><a class="reference external" href="https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html">https://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-creating-rpms.html</a></dt>
<dd>for Fedora users</dd>
<dt><a class="reference external" href="http://www.slackbook.org/html/package-management-making-packages.html">http://www.slackbook.org/html/package-management-making-packages.html</a></dt>
<dd>for Slackware users</dd>
</dl>
</div>
</div>
<div class="section" id="on-freebsd-and-openbsd">
<h3>2.1.2. On FreeBSD and OpenBSD<a class="headerlink" href="#on-freebsd-and-openbsd" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">FreeBSD users, to add the package use:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>pkg install python3
</pre></div>
</div>
</li>
<li><p class="first">OpenBSD users, to add the package use:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>pkg_add -r python

pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/&lt;insert your architecture here&gt;/python-&lt;version&gt;.tgz
</pre></div>
</div>
<p>For example i386 users get the 2.5.1 version of Python using:</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz
</pre></div>
</div>
</li>
</ul>
</div>
<div class="section" id="on-opensolaris">
<h3>2.1.3. On OpenSolaris<a class="headerlink" href="#on-opensolaris" title="Permalink to this headline">¶</a></h3>
<p>You can get Python from <a class="reference external" href="https://www.opencsw.org/">OpenCSW</a>.  Various versions
of Python are available and can be installed with e.g. <code class="docutils literal notranslate"><span class="pre">pkgutil</span> <span class="pre">-i</span> <span class="pre">python27</span></code>.</p>
</div>
</div>
<div class="section" id="building-python">
<span id="building-python-on-unix"></span><h2>2.2. Building Python<a class="headerlink" href="#building-python" title="Permalink to this headline">¶</a></h2>
<p>If you want to compile CPython yourself, first thing you should do is get the
<a class="reference external" href="https://www.python.org/downloads/source/">source</a>. You can download either the
latest release’s source or just grab a fresh <a class="reference external" href="https://docs.python.org/devguide/setup.html#getting-the-source-code">clone</a>.  (If you want
to contribute patches, you will need a clone.)</p>
<p>The build process consists in the usual</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>./configure
make
make install
</pre></div>
</div>
<p>invocations. Configuration options and caveats for specific Unix platforms are
extensively documented in the <a class="reference external" href="https://github.com/python/cpython/tree/2.7/README">README</a> file in the root of the Python
source tree.</p>
<div class="admonition warning">
<p class="first admonition-title">Warning</p>
<p class="last"><code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">install</span></code> can overwrite or masquerade the <code class="file docutils literal notranslate"><span class="pre">python</span></code> binary.
<code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">altinstall</span></code> is therefore recommended instead of <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">install</span></code>
since it only installs <code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/bin/python</span><em><span class="pre">version</span></em></code>.</p>
</div>
</div>
<div class="section" id="python-related-paths-and-files">
<h2>2.3. Python-related paths and files<a class="headerlink" href="#python-related-paths-and-files" title="Permalink to this headline">¶</a></h2>
<p>These are subject to difference depending on local installation conventions;
<span class="target" id="index-0"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">prefix</span></code> (<code class="docutils literal notranslate"><span class="pre">${prefix}</span></code>) and <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">exec_prefix</span></code> (<code class="docutils literal notranslate"><span class="pre">${exec_prefix}</span></code>)
are installation-dependent and should be interpreted as for GNU software; they
may be the same.</p>
<p>For example, on most Linux systems, the default for both is <code class="file docutils literal notranslate"><span class="pre">/usr</span></code>.</p>
<table border="1" class="docutils">
<colgroup>
<col width="53%" />
<col width="47%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">File/directory</th>
<th class="head">Meaning</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/bin/python</span></code></td>
<td>Recommended location of the interpreter.</td>
</tr>
<tr class="row-odd"><td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">version</span></em></code>,
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/lib/python</span><em><span class="pre">version</span></em></code></td>
<td>Recommended locations of the directories
containing the standard modules.</td>
</tr>
<tr class="row-even"><td><code class="file docutils literal notranslate"><em><span class="pre">prefix</span></em><span class="pre">/include/python</span><em><span class="pre">version</span></em></code>,
<code class="file docutils literal notranslate"><em><span class="pre">exec_prefix</span></em><span class="pre">/include/python</span><em><span class="pre">version</span></em></code></td>
<td>Recommended locations of the directories
containing the include files needed for
developing Python extensions and
embedding the interpreter.</td>
</tr>
<tr class="row-odd"><td><code class="file docutils literal notranslate"><span class="pre">~/.pythonrc.py</span></code></td>
<td>User-specific initialization file loaded
by the user module; not used by default
or by most applications.</td>
</tr>
</tbody>
</table>
</div>
<div class="section" id="miscellaneous">
<h2>2.4. Miscellaneous<a class="headerlink" href="#miscellaneous" title="Permalink to this headline">¶</a></h2>
<p>To easily use Python scripts on Unix, you need to make them executable,
e.g. with</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span>$ chmod +x script
</pre></div>
</div>
<p>and put an appropriate Shebang line at the top of the script.  A good choice is
usually</p>
<div class="highlight-sh notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
</pre></div>
</div>
<p>which searches for the Python interpreter in the whole <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>.  However,
some Unices may not have the <strong class="program">env</strong> command, so you may need to hardcode
<code class="docutils literal notranslate"><span class="pre">/usr/bin/python</span></code> as the interpreter path.</p>
<p>To use shell commands in your Python scripts, look at the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module.</p>
</div>
<div class="section" id="editors-and-ides">
<h2>2.5. Editors and IDEs<a class="headerlink" href="#editors-and-ides" title="Permalink to this headline">¶</a></h2>
<p>There are a number of IDEs that support Python programming language.
Many editors and IDEs provide syntax highlighting, debugging tools, and <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0008"><strong>PEP 8</strong></a> checks.</p>
<p>Please go to <a class="reference external" href="https://wiki.python.org/moin/PythonEditors">Python Editors</a> and
<a class="reference external" href="https://wiki.python.org/moin/IntegratedDevelopmentEnvironments">Integrated Development Environments</a>
for a comprehensive list.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">2. Using Python on Unix platforms</a><ul>
<li><a class="reference internal" href="#getting-and-installing-the-latest-version-of-python">2.1. Getting and installing the latest version of Python</a><ul>
<li><a class="reference internal" href="#on-linux">2.1.1. On Linux</a></li>
<li><a class="reference internal" href="#on-freebsd-and-openbsd">2.1.2. On FreeBSD and OpenBSD</a></li>
<li><a class="reference internal" href="#on-opensolaris">2.1.3. On OpenSolaris</a></li>
</ul>
</li>
<li><a class="reference internal" href="#building-python">2.2. Building Python</a></li>
<li><a class="reference internal" href="#python-related-paths-and-files">2.3. Python-related paths and files</a></li>
<li><a class="reference internal" href="#miscellaneous">2.4. Miscellaneous</a></li>
<li><a class="reference internal" href="#editors-and-ides">2.5. Editors and IDEs</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="cmdline.html"
                        title="previous chapter">1. Command line and environment</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="windows.html"
                        title="next chapter">3. Using Python on Windows</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/using/unix.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="windows.html" title="3. Using Python on Windows"
             >next</a> |</li>
        <li class="right" >
          <a href="cmdline.html" title="1. Command line and environment"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\+̒�ptpthtml/using/windows.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>3. Using Python on Windows &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="4. Using Python on a Macintosh" href="mac.html" />
    <link rel="prev" title="2. Using Python on Unix platforms" href="unix.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/using/windows.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mac.html" title="4. Using Python on a Macintosh"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="unix.html" title="2. Using Python on Unix platforms"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="using-python-on-windows">
<span id="using-on-windows"></span><h1>3. Using Python on Windows<a class="headerlink" href="#using-python-on-windows" title="Permalink to this headline">¶</a></h1>
<p>This document aims to give an overview of Windows-specific behaviour you should
know about when using Python on Microsoft Windows.</p>
<div class="section" id="installing-python">
<h2>3.1. Installing Python<a class="headerlink" href="#installing-python" title="Permalink to this headline">¶</a></h2>
<p>Unlike most Unix systems and services, Windows does not require Python natively
and thus does not pre-install a version of Python.  However, the CPython team
has compiled Windows installers (MSI packages) with every <a class="reference external" href="https://www.python.org/download/releases/">release</a> for many years.</p>
<p>With ongoing development of Python, some platforms that used to be supported
earlier are no longer supported (due to the lack of users or developers).
Check <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0011"><strong>PEP 11</strong></a> for details on all unsupported platforms.</p>
<ul class="simple">
<li>DOS and Windows 3.x are deprecated since Python 2.0 and code specific to these
systems was removed in Python 2.1.</li>
<li>Up to 2.5, Python was still compatible with Windows 95, 98 and ME (but already
raised a deprecation warning on installation).  For Python 2.6 (and all
following releases), this support was dropped and new releases are just
expected to work on the Windows NT family.</li>
<li><a class="reference external" href="http://pythonce.sourceforge.net/">Windows CE</a> is still supported.</li>
<li>The <a class="reference external" href="https://cygwin.com/">Cygwin</a> installer offers to install the Python
interpreter as well (cf. <a class="reference external" href="ftp://ftp.uni-erlangen.de/pub/pc/gnuwin32/cygwin/mirrors/cygnus/release/python">Cygwin package source</a>, <a class="reference external" href="http://www.tishler.net/jason/software/python/">Maintainer releases</a>)</li>
</ul>
<p>See <a class="reference external" href="https://www.python.org/download/windows/">Python for Windows (and DOS)</a>
for detailed information about platforms with precompiled installers.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://dooling.com/index.php/2006/03/14/python-on-xp-7-minutes-to-hello-world/">Python on XP</a></dt>
<dd>“7 Minutes to “Hello World!””
by Richard Dooling, 2006</dd>
<dt><a class="reference external" href="http://www.diveintopython.net/installing_python/windows.html">Installing on Windows</a></dt>
<dd>in “<a class="reference external" href="http://www.diveintopython.net/">Dive into Python: Python from novice to pro</a>”
by Mark Pilgrim, 2004,
ISBN 1-59059-356-1</dd>
<dt><a class="reference external" href="http://python.swaroopch.com/installation.html#installation-on-windows">For Windows users</a></dt>
<dd>in “Installing Python”
in “<a class="reference external" href="http://python.swaroopch.com/">A Byte of Python</a>”
by Swaroop C H, 2003</dd>
</dl>
</div>
</div>
<div class="section" id="alternative-bundles">
<h2>3.2. Alternative bundles<a class="headerlink" href="#alternative-bundles" title="Permalink to this headline">¶</a></h2>
<p>Besides the standard CPython distribution, there are modified packages including
additional functionality.  The following is a list of popular versions and their
key features:</p>
<dl class="docutils">
<dt><a class="reference external" href="https://www.activestate.com/activepython/">ActivePython</a></dt>
<dd>Installer with multi-platform compatibility, documentation, PyWin32</dd>
<dt><a class="reference external" href="https://www.enthought.com/products/epd/">Enthought Python Distribution</a></dt>
<dd>Popular modules (such as PyWin32) with their respective documentation, tool
suite for building extensible Python applications</dd>
</dl>
<p>Notice that these packages are likely to install <em>older</em> versions of Python.</p>
</div>
<div class="section" id="configuring-python">
<h2>3.3. Configuring Python<a class="headerlink" href="#configuring-python" title="Permalink to this headline">¶</a></h2>
<p>In order to run Python flawlessly, you might have to change certain environment
settings in Windows.</p>
<div class="section" id="excursus-setting-environment-variables">
<span id="setting-envvars"></span><h3>3.3.1. Excursus: Setting environment variables<a class="headerlink" href="#excursus-setting-environment-variables" title="Permalink to this headline">¶</a></h3>
<p>Windows has a built-in dialog for changing environment variables (following
guide applies to XP classical view): Right-click the icon for your machine
(usually located on your Desktop and called “My Computer”) and choose
<span class="menuselection">Properties</span> there.  Then, open the <span class="guilabel">Advanced</span> tab
and click the <span class="guilabel">Environment Variables</span> button.</p>
<p>In short, your path is:</p>
<blockquote>
<div><span class="menuselection">My Computer
‣ Properties
‣ Advanced
‣ Environment Variables</span></div></blockquote>
<p>In this dialog, you can add or modify User and System variables. To change
System variables, you need non-restricted access to your machine
(i.e. Administrator rights).</p>
<p>Another way of adding variables to your environment is using the <strong class="command">set</strong>
command:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
</pre></div>
</div>
<p>To make this setting permanent, you could add the corresponding command line to
your <code class="file docutils literal notranslate"><span class="pre">autoexec.bat</span></code>. <strong class="program">msconfig</strong> is a graphical interface to this
file.</p>
<p>Viewing environment variables can also be done more straight-forward: The
command prompt will expand strings wrapped into percent signs automatically:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>echo %PATH%
</pre></div>
</div>
<p>Consult <strong class="command">set /?</strong> for details on this behaviour.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://support.microsoft.com/kb/100843">https://support.microsoft.com/kb/100843</a></dt>
<dd>Environment variables in Windows NT</dd>
<dt><a class="reference external" href="https://support.microsoft.com/kb/310519">https://support.microsoft.com/kb/310519</a></dt>
<dd>How To Manage Environment Variables in Windows XP</dd>
<dt><a class="reference external" href="https://www.chem.gla.ac.uk/~louis/software/faq/q1.html">https://www.chem.gla.ac.uk/~louis/software/faq/q1.html</a></dt>
<dd>Setting Environment variables, Louis J. Farrugia</dd>
</dl>
</div>
</div>
<div class="section" id="finding-the-python-executable">
<h3>3.3.2. Finding the Python executable<a class="headerlink" href="#finding-the-python-executable" title="Permalink to this headline">¶</a></h3>
<p>Besides using the automatically created start menu entry for the Python
interpreter, you might want to start Python in the DOS prompt.  To make this
work, you need to set your <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">%PATH%</span></code> environment variable to include the
directory of your Python distribution, delimited by a semicolon from other
entries.  An example variable could look like this (assuming the first two
entries are Windows’ default):</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>C:\WINDOWS\system32;C:\WINDOWS;C:\Python25
</pre></div>
</div>
<p>Typing <strong class="command">python</strong> on your command prompt will now fire up the Python
interpreter.  Thus, you can also execute your scripts with command line options,
see <a class="reference internal" href="cmdline.html#using-on-cmdline"><span class="std std-ref">Command line</span></a> documentation.</p>
</div>
<div class="section" id="finding-modules">
<h3>3.3.3. Finding modules<a class="headerlink" href="#finding-modules" title="Permalink to this headline">¶</a></h3>
<p>Python usually stores its library (and thereby your site-packages folder) in the
installation directory.  So, if you had installed Python to
<code class="file docutils literal notranslate"><span class="pre">C:\Python\</span></code>, the default library would reside in
<code class="file docutils literal notranslate"><span class="pre">C:\Python\Lib\</span></code> and third-party modules should be stored in
<code class="file docutils literal notranslate"><span class="pre">C:\Python\Lib\site-packages\</span></code>.</p>
<p>This is how <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is populated on Windows:</p>
<ul class="simple">
<li>An empty entry is added at the start, which corresponds to the current
directory.</li>
<li>If the environment variable <span class="target" id="index-2"></span><a class="reference internal" href="cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> exists, as described in
<a class="reference internal" href="cmdline.html#using-on-envvars"><span class="std std-ref">Environment variables</span></a>, its entries are added next.  Note that on Windows,
paths in this variable must be separated by semicolons, to distinguish them
from the colon used in drive identifiers (<code class="docutils literal notranslate"><span class="pre">C:\</span></code> etc.).</li>
<li>Additional “application paths” can be added in the registry as subkeys of
<code class="samp docutils literal notranslate"><span class="pre">\SOFTWARE\Python\PythonCore\</span><em><span class="pre">version</span></em><span class="pre">\PythonPath</span></code> under both the
<code class="docutils literal notranslate"><span class="pre">HKEY_CURRENT_USER</span></code> and <code class="docutils literal notranslate"><span class="pre">HKEY_LOCAL_MACHINE</span></code> hives.  Subkeys which have
semicolon-delimited path strings as their default value will cause each path
to be added to <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>.  (Note that all known installers only use
HKLM, so HKCU is typically empty.)</li>
<li>If the environment variable <span class="target" id="index-3"></span><a class="reference internal" href="cmdline.html#envvar-PYTHONHOME"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHOME</span></code></a> is set, it is assumed as
“Python Home”.  Otherwise, the path of the main Python executable is used to
locate a “landmark file” (<code class="docutils literal notranslate"><span class="pre">Lib\os.py</span></code>) to deduce the “Python Home”.  If a
Python home is found, the relevant sub-directories added to <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>
(<code class="docutils literal notranslate"><span class="pre">Lib</span></code>, <code class="docutils literal notranslate"><span class="pre">plat-win</span></code>, etc) are based on that folder.  Otherwise, the core
Python path is constructed from the PythonPath stored in the registry.</li>
<li>If the Python Home cannot be located, no <span class="target" id="index-4"></span><a class="reference internal" href="cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is specified in
the environment, and no registry entries can be found, a default path with
relative entries is used (e.g. <code class="docutils literal notranslate"><span class="pre">.\Lib;.\plat-win</span></code>, etc).</li>
</ul>
<p>The end result of all this is:</p>
<ul class="simple">
<li>When running <code class="file docutils literal notranslate"><span class="pre">python.exe</span></code>, or any other .exe in the main Python
directory (either an installed version, or directly from the PCbuild
directory), the core path is deduced, and the core paths in the registry are
ignored.  Other “application paths” in the registry are always read.</li>
<li>When Python is hosted in another .exe (different directory, embedded via COM,
etc), the “Python Home” will not be deduced, so the core path from the
registry is used.  Other “application paths” in the registry are always read.</li>
<li>If Python can’t find its home and there is no registry (eg, frozen .exe, some
very strange installation setup) you get a path with some default, but
relative, paths.</li>
</ul>
</div>
<div class="section" id="executing-scripts">
<h3>3.3.4. Executing scripts<a class="headerlink" href="#executing-scripts" title="Permalink to this headline">¶</a></h3>
<p>Python scripts (files with the extension <code class="docutils literal notranslate"><span class="pre">.py</span></code>) will be executed by
<strong class="program">python.exe</strong> by default.  This executable opens a terminal, which stays
open even if the program uses a GUI.  If you do not want this to happen, use the
extension <code class="docutils literal notranslate"><span class="pre">.pyw</span></code> which will cause the script to be executed by
<strong class="program">pythonw.exe</strong> by default (both executables are located in the top-level
of your Python installation directory).  This suppresses the terminal window on
startup.</p>
<p>You can also make all <code class="docutils literal notranslate"><span class="pre">.py</span></code> scripts execute with <strong class="program">pythonw.exe</strong>,
setting this through the usual facilities, for example (might require
administrative rights):</p>
<ol class="arabic">
<li><p class="first">Launch a command prompt.</p>
</li>
<li><p class="first">Associate the correct file group with <code class="docutils literal notranslate"><span class="pre">.py</span></code> scripts:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>assoc .py=Python.File
</pre></div>
</div>
</li>
<li><p class="first">Redirect all Python files to the new executable:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>ftype Python.File=C:\Path\to\pythonw.exe &quot;%1&quot; %*
</pre></div>
</div>
</li>
</ol>
</div>
</div>
<div class="section" id="additional-modules">
<h2>3.4. Additional modules<a class="headerlink" href="#additional-modules" title="Permalink to this headline">¶</a></h2>
<p>Even though Python aims to be portable among all platforms, there are features
that are unique to Windows.  A couple of modules, both in the standard library
and external, and snippets exist to use these features.</p>
<p>The Windows-specific standard modules are documented in
<a class="reference internal" href="../library/windows.html#mswin-specific-services"><span class="std std-ref">MS Windows Specific Services</span></a>.</p>
<div class="section" id="pywin32">
<h3>3.4.1. PyWin32<a class="headerlink" href="#pywin32" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference external" href="https://pypi.org/project/pywin32">PyWin32</a> module by Mark Hammond
is a collection of modules for advanced Windows-specific support.  This includes
utilities for:</p>
<ul class="simple">
<li><a class="reference external" href="https://www.microsoft.com/com/">Component Object Model</a> (COM)</li>
<li>Win32 API calls</li>
<li>Registry</li>
<li>Event log</li>
<li><a class="reference external" href="https://msdn.microsoft.com/en-us/library/fe1cf721%28VS.80%29.aspx">Microsoft Foundation Classes</a> (MFC)
user interfaces</li>
</ul>
<p><a class="reference external" href="https://web.archive.org/web/20060524042422/https://www.python.org/windows/pythonwin/">PythonWin</a> is a sample MFC application
shipped with PyWin32.  It is an embeddable IDE with a built-in debugger.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://timgolden.me.uk/python/win32_how_do_i.html">Win32 How Do I…?</a></dt>
<dd>by Tim Golden</dd>
<dt><a class="reference external" href="http://www.boddie.org.uk/python/COM.html">Python and COM</a></dt>
<dd>by David and Paul Boddie</dd>
</dl>
</div>
</div>
<div class="section" id="py2exe">
<h3>3.4.2. Py2exe<a class="headerlink" href="#py2exe" title="Permalink to this headline">¶</a></h3>
<p><a class="reference external" href="http://www.py2exe.org/">Py2exe</a> is a <a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> extension (see
<a class="reference internal" href="../distutils/extending.html#extending-distutils"><span class="std std-ref">Extending Distutils</span></a>) which wraps Python scripts into executable Windows
programs (<code class="file docutils literal notranslate"><em><span class="pre">*</span></em><span class="pre">.exe</span></code> files).  When you have done this, you can distribute
your application without requiring your users to install Python.</p>
</div>
<div class="section" id="wconio">
<h3>3.4.3. WConio<a class="headerlink" href="#wconio" title="Permalink to this headline">¶</a></h3>
<p>Since Python’s advanced terminal handling layer, <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a>, is restricted to
Unix-like systems, there is a library exclusive to Windows as well: Windows
Console I/O for Python.</p>
<p><a class="reference external" href="http://newcenturycomputers.net/projects/wconio.html">WConio</a> is a wrapper for
Turbo-C’s <code class="file docutils literal notranslate"><span class="pre">CONIO.H</span></code>, used to create text user interfaces.</p>
</div>
</div>
<div class="section" id="compiling-python-on-windows">
<h2>3.5. Compiling Python on Windows<a class="headerlink" href="#compiling-python-on-windows" title="Permalink to this headline">¶</a></h2>
<p>If you want to compile CPython yourself, first thing you should do is get the
<a class="reference external" href="https://www.python.org/downloads/source/">source</a>. You can download either the
latest release’s source or just grab a fresh <a class="reference external" href="https://docs.python.org/devguide/setup.html#getting-the-source-code">checkout</a>.</p>
<p>For Microsoft Visual C++, which is the compiler with which official Python
releases are built, the source tree contains solutions/project files.  View the
<code class="file docutils literal notranslate"><span class="pre">readme.txt</span></code> in their respective directories:</p>
<table border="1" class="docutils">
<colgroup>
<col width="35%" />
<col width="25%" />
<col width="40%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Directory</th>
<th class="head">MSVC version</th>
<th class="head">Visual Studio version</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="file docutils literal notranslate"><span class="pre">PC/VC6/</span></code></td>
<td>6.0</td>
<td>97</td>
</tr>
<tr class="row-odd"><td><code class="file docutils literal notranslate"><span class="pre">PC/VS7.1/</span></code></td>
<td>7.1</td>
<td>2003</td>
</tr>
<tr class="row-even"><td><code class="file docutils literal notranslate"><span class="pre">PC/VS8.0/</span></code></td>
<td>8.0</td>
<td>2005</td>
</tr>
<tr class="row-odd"><td><code class="file docutils literal notranslate"><span class="pre">PCbuild/</span></code></td>
<td>9.0</td>
<td>2008</td>
</tr>
</tbody>
</table>
<p>Note that not all of these build directories are fully supported.  Read the
release notes to see which compiler version the official releases for your
version are built with.</p>
<p>Check <code class="file docutils literal notranslate"><span class="pre">PC/readme.txt</span></code> for general information on the build process.</p>
<p>For extension modules, consult <a class="reference internal" href="../extending/windows.html#building-on-windows"><span class="std std-ref">Building C and C++ Extensions on Windows</span></a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://sebsauvage.net/python/mingw.html">Python + Windows + distutils + SWIG + gcc MinGW</a></dt>
<dd>or “Creating Python extensions in C/C++ with SWIG and compiling them with
MinGW gcc under Windows” or “Installing Python extension with distutils
and without Microsoft Visual C++” by Sébastien Sauvage, 2003</dd>
<dt><a class="reference external" href="http://oldwiki.mingw.org/index.php/Python%20extensions">MingW – Python extensions</a></dt>
<dd>by Trent Apted et al, 2007</dd>
</dl>
</div>
</div>
<div class="section" id="other-resources">
<h2>3.6. Other resources<a class="headerlink" href="#other-resources" title="Permalink to this headline">¶</a></h2>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://shop.oreilly.com/product/9781565926219.do">Python Programming On Win32</a></dt>
<dd>“Help for Windows Programmers”
by Mark Hammond and Andy Robinson, O’Reilly Media, 2000,
ISBN 1-56592-621-8</dd>
<dt><a class="reference external" href="http://www.imladris.com/Scripts/PythonForWindows.html">A Python for Windows Tutorial</a></dt>
<dd>by Amanda Birmingham, 2004</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">3. Using Python on Windows</a><ul>
<li><a class="reference internal" href="#installing-python">3.1. Installing Python</a></li>
<li><a class="reference internal" href="#alternative-bundles">3.2. Alternative bundles</a></li>
<li><a class="reference internal" href="#configuring-python">3.3. Configuring Python</a><ul>
<li><a class="reference internal" href="#excursus-setting-environment-variables">3.3.1. Excursus: Setting environment variables</a></li>
<li><a class="reference internal" href="#finding-the-python-executable">3.3.2. Finding the Python executable</a></li>
<li><a class="reference internal" href="#finding-modules">3.3.3. Finding modules</a></li>
<li><a class="reference internal" href="#executing-scripts">3.3.4. Executing scripts</a></li>
</ul>
</li>
<li><a class="reference internal" href="#additional-modules">3.4. Additional modules</a><ul>
<li><a class="reference internal" href="#pywin32">3.4.1. PyWin32</a></li>
<li><a class="reference internal" href="#py2exe">3.4.2. Py2exe</a></li>
<li><a class="reference internal" href="#wconio">3.4.3. WConio</a></li>
</ul>
</li>
<li><a class="reference internal" href="#compiling-python-on-windows">3.5. Compiling Python on Windows</a></li>
<li><a class="reference internal" href="#other-resources">3.6. Other resources</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="unix.html"
                        title="previous chapter">2. Using Python on Unix platforms</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="mac.html"
                        title="next chapter">4. Using Python on a Macintosh</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/using/windows.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="mac.html" title="4. Using Python on a Macintosh"
             >next</a> |</li>
        <li class="right" >
          <a href="unix.html" title="2. Using Python on Unix platforms"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >Python Setup and Usage</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\%)����html/whatsnew/2.0.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.0 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="The Python Tutorial" href="../tutorial/index.html" />
    <link rel="prev" title="What’s New in Python 2.1" href="2.1.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.0.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../tutorial/index.html" title="The Python Tutorial"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.1.html" title="What’s New in Python 2.1"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-0">
<h1>What’s New in Python 2.0<a class="headerlink" href="#what-s-new-in-python-2-0" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling and Moshe Zadka</td>
</tr>
</tbody>
</table>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>A new release of Python, version 2.0, was released on October 16, 2000. This
article covers the exciting new features in 2.0, highlights some other useful
changes, and points out a few incompatible changes that may require rewriting
code.</p>
<p>Python’s development never completely stops between releases, and a steady flow
of bug fixes and improvements are always being submitted. A host of minor fixes,
a few optimizations, additional docstrings, and better error messages went into
2.0; to list them all would be impossible, but they’re certainly significant.
Consult the publicly-available CVS logs if you want to see the full list.  This
progress is due to the five developers working for  PythonLabs are now getting
paid to spend their days fixing bugs, and also due to the improved communication
resulting  from moving to SourceForge.</p>
</div>
<div class="section" id="what-about-python-1-6">
<h2>What About Python 1.6?<a class="headerlink" href="#what-about-python-1-6" title="Permalink to this headline">¶</a></h2>
<p>Python 1.6 can be thought of as the Contractual Obligations Python release.
After the core development team left CNRI in May 2000, CNRI requested that a 1.6
release be created, containing all the work on Python that had been performed at
CNRI.  Python 1.6 therefore represents the state of the CVS tree as of May 2000,
with the most significant new feature being Unicode support.  Development
continued after May, of course, so the 1.6 tree received a few fixes to ensure
that it’s forward-compatible with Python 2.0.  1.6 is therefore part of Python’s
evolution, and not a side branch.</p>
<p>So, should you take much interest in Python 1.6?  Probably not.  The 1.6final
and 2.0beta1 releases were made on the same day (September 5, 2000), the plan
being to finalize Python 2.0 within a month or so.  If you have applications to
maintain, there seems little point in breaking things by moving to 1.6, fixing
them, and then having another round of breakage within a month by moving to 2.0;
you’re better off just going straight to 2.0.  Most of the really interesting
features described in this document are only in 2.0, because a lot of work was
done between May and September.</p>
</div>
<div class="section" id="new-development-process">
<h2>New Development Process<a class="headerlink" href="#new-development-process" title="Permalink to this headline">¶</a></h2>
<p>The most important change in Python 2.0 may not be to the code at all, but to
how Python is developed: in May 2000 the Python developers began using the tools
made available by SourceForge for storing  source code, tracking bug reports,
and managing the queue of patch submissions.  To report bugs or submit patches
for Python 2.0, use the bug tracking and patch manager tools available from
Python’s project page, located at <a class="reference external" href="https://sourceforge.net/projects/python/">https://sourceforge.net/projects/python/</a>.</p>
<p>The most important of the services now hosted at SourceForge is the Python CVS
tree, the version-controlled repository containing the source code for Python.
Previously, there were roughly 7 or so people who had write access to the CVS
tree, and all patches had to be inspected and checked in by one of the people on
this short list. Obviously, this wasn’t very scalable.  By moving the CVS tree
to SourceForge, it became possible to grant write access to more people; as of
September 2000 there were 27 people able to check in changes, a fourfold
increase.  This makes possible large-scale changes that wouldn’t be attempted if
they’d have to be filtered through the small group of core developers.  For
example, one day Peter Schneider-Kamp took it into his head to drop K&amp;R C
compatibility and convert the C source for Python to ANSI C. After getting
approval on the python-dev mailing list, he launched into a flurry of checkins
that lasted about a week, other developers joined in to help, and the job was
done.  If there were only 5 people with write access, probably that task would
have been viewed as “nice, but not worth the time and effort needed” and it
would never have gotten done.</p>
<p>The shift to using SourceForge’s services has resulted in a remarkable increase
in the speed of development.  Patches now get submitted, commented on, revised
by people other than the original submitter, and bounced back and forth between
people until the patch is deemed worth checking in.  Bugs are tracked in one
central location and can be assigned to a specific person for fixing, and we can
count the number of open bugs to measure progress.  This didn’t come without a
cost: developers now have more e-mail to deal with, more mailing lists to
follow, and special tools had to be written for the new environment. For
example, SourceForge sends default patch and bug notification e-mail messages
that are completely unhelpful, so Ka-Ping Yee wrote an HTML screen-scraper that
sends more useful messages.</p>
<p>The ease of adding code caused a few initial growing pains, such as code was
checked in before it was ready or without getting clear agreement from the
developer group.  The approval process that has emerged is somewhat similar to
that used by the Apache group. Developers can vote +1, +0, -0, or -1 on a patch;
+1 and -1 denote acceptance or rejection, while +0 and -0 mean the developer is
mostly indifferent to the change, though with a slight positive or negative
slant.  The most significant change from the Apache model is that the voting is
essentially advisory, letting Guido van Rossum, who has Benevolent Dictator For
Life status, know what the general opinion is. He can still ignore the result of
a vote, and approve or reject a change even if the community disagrees with him.</p>
<p>Producing an actual patch is the last step in adding a new feature, and is
usually easy compared to the earlier task of coming up with a good design.
Discussions of new features can often explode into lengthy mailing list threads,
making the discussion hard to follow, and no one can read every posting to
python-dev.  Therefore, a relatively formal process has been set up to write
Python Enhancement Proposals (PEPs), modelled on the Internet RFC process.  PEPs
are draft documents that describe a proposed new feature, and are continually
revised until the community reaches a consensus, either accepting or rejecting
the proposal.  Quoting from the introduction to PEP 1, “PEP Purpose and
Guidelines”:</p>
<blockquote class="epigraph">
<div><p>PEP stands for Python Enhancement Proposal.  A PEP is a design document
providing information to the Python community, or describing a new feature for
Python.  The PEP should provide a concise technical specification of the feature
and a rationale for the feature.</p>
<p>We intend PEPs to be the primary mechanisms for proposing new features, for
collecting community input on an issue, and for documenting the design decisions
that have gone into Python.  The PEP author is responsible for building
consensus within the community and documenting dissenting opinions.</p>
</div></blockquote>
<p>Read the rest of PEP 1 for the details of the PEP editorial process, style, and
format.  PEPs are kept in the Python CVS tree on SourceForge, though they’re not
part of the Python 2.0 distribution, and are also available in HTML form from
<a class="reference external" href="https://www.python.org/dev/peps/">https://www.python.org/dev/peps/</a>.  As of September 2000, there are 25 PEPS, ranging
from PEP 201, “Lockstep Iteration”, to PEP 225, “Elementwise/Objectwise
Operators”.</p>
</div>
<div class="section" id="unicode">
<h2>Unicode<a class="headerlink" href="#unicode" title="Permalink to this headline">¶</a></h2>
<p>The largest new feature in Python 2.0 is a new fundamental data type: Unicode
strings.  Unicode uses 16-bit numbers to represent characters instead of the
8-bit number used by ASCII, meaning that 65,536 distinct characters can be
supported.</p>
<p>The final interface for Unicode support was arrived at through countless
often-stormy discussions on the python-dev mailing list, and mostly implemented by
Marc-André Lemburg, based on a Unicode string type implementation by Fredrik
Lundh.  A detailed explanation of the interface was written up as <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0100"><strong>PEP 100</strong></a>,
“Python Unicode Integration”. This article will simply cover the most
significant points about the Unicode interfaces.</p>
<p>In Python source code, Unicode strings are written as <code class="docutils literal notranslate"><span class="pre">u&quot;string&quot;</span></code>.  Arbitrary
Unicode characters can be written using a new escape sequence, <code class="docutils literal notranslate"><span class="pre">\uHHHH</span></code>, where
<em>HHHH</em> is a 4-digit hexadecimal number from 0000 to FFFF.  The existing
<code class="docutils literal notranslate"><span class="pre">\xHHHH</span></code> escape sequence can also be used, and octal escapes can be used for
characters up to U+01FF, which is represented by <code class="docutils literal notranslate"><span class="pre">\777</span></code>.</p>
<p>Unicode strings, just like regular strings, are an immutable sequence type.
They can be indexed and sliced, but not modified in place. Unicode strings have
an <code class="docutils literal notranslate"><span class="pre">encode(</span> <span class="pre">[encoding]</span> <span class="pre">)</span></code> method that returns an 8-bit string in the desired
encoding.  Encodings are named by strings, such as <code class="docutils literal notranslate"><span class="pre">'ascii'</span></code>, <code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'iso-8859-1'</span></code>, or whatever.  A codec API is defined for implementing and
registering new encodings that are then available throughout a Python program.
If an encoding isn’t specified, the default encoding is usually 7-bit ASCII,
though it can be changed for your Python installation by calling the
<code class="docutils literal notranslate"><span class="pre">sys.setdefaultencoding(encoding)</span></code> function in a customised version of
<code class="file docutils literal notranslate"><span class="pre">site.py</span></code>.</p>
<p>Combining 8-bit and Unicode strings always coerces to Unicode, using the default
ASCII encoding; the result of <code class="docutils literal notranslate"><span class="pre">'a'</span> <span class="pre">+</span> <span class="pre">u'bc'</span></code> is <code class="docutils literal notranslate"><span class="pre">u'abc'</span></code>.</p>
<p>New built-in functions have been added, and existing built-ins modified to
support Unicode:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">unichr(ch)</span></code> returns a Unicode string 1 character long, containing the
character <em>ch</em>.</li>
<li><code class="docutils literal notranslate"><span class="pre">ord(u)</span></code>, where <em>u</em> is a 1-character regular or Unicode string, returns the
number of the character as an integer.</li>
<li><code class="docutils literal notranslate"><span class="pre">unicode(string</span> <span class="pre">[,</span> <span class="pre">encoding]</span>&#160; <span class="pre">[,</span> <span class="pre">errors]</span> <span class="pre">)</span></code> creates a Unicode string
from an 8-bit string.  <code class="docutils literal notranslate"><span class="pre">encoding</span></code> is a string naming the encoding to use. The
<code class="docutils literal notranslate"><span class="pre">errors</span></code> parameter specifies the treatment of characters that are invalid for
the current encoding; passing <code class="docutils literal notranslate"><span class="pre">'strict'</span></code> as the value causes an exception to
be raised on any encoding error, while <code class="docutils literal notranslate"><span class="pre">'ignore'</span></code> causes errors to be silently
ignored and <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> uses U+FFFD, the official replacement character, in
case of any problems.</li>
<li>The <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement, and various built-ins such as <code class="docutils literal notranslate"><span class="pre">eval()</span></code>,
<code class="docutils literal notranslate"><span class="pre">getattr()</span></code>, and <code class="docutils literal notranslate"><span class="pre">setattr()</span></code> will also accept Unicode strings as well as
regular strings.  (It’s possible that the process of fixing this missed some
built-ins; if you find a built-in function that accepts strings but doesn’t
accept Unicode strings at all, please report it as a bug.)</li>
</ul>
<p>A new module, <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a>, provides an interface to Unicode character
properties.  For example, <code class="docutils literal notranslate"><span class="pre">unicodedata.category(u'A')</span></code> returns the 2-character
string ‘Lu’, the ‘L’ denoting it’s a letter, and ‘u’ meaning that it’s
uppercase. <code class="docutils literal notranslate"><span class="pre">unicodedata.bidirectional(u'\u0660')</span></code> returns ‘AN’, meaning that
U+0660 is an Arabic number.</p>
<p>The <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module contains functions to look up existing encodings and
register new ones.  Unless you want to implement a new encoding, you’ll most
often use the <code class="docutils literal notranslate"><span class="pre">codecs.lookup(encoding)</span></code> function, which returns a
4-element tuple: <code class="docutils literal notranslate"><span class="pre">(encode_func,</span> <span class="pre">decode_func,</span> <span class="pre">stream_reader,</span> <span class="pre">stream_writer)</span></code>.</p>
<ul class="simple">
<li><em>encode_func</em> is a function that takes a Unicode string, and returns a 2-tuple
<code class="docutils literal notranslate"><span class="pre">(string,</span> <span class="pre">length)</span></code>.  <em>string</em> is an 8-bit string containing a portion (perhaps
all) of the Unicode string converted into the given encoding, and <em>length</em> tells
you how much of the Unicode string was converted.</li>
<li><em>decode_func</em> is the opposite of <em>encode_func</em>, taking an 8-bit string and
returning a 2-tuple <code class="docutils literal notranslate"><span class="pre">(ustring,</span> <span class="pre">length)</span></code>, consisting of the resulting Unicode
string <em>ustring</em> and the integer <em>length</em> telling how much of the 8-bit string
was consumed.</li>
<li><em>stream_reader</em> is a class that supports decoding input from a stream.
<em>stream_reader(file_obj)</em> returns an object that supports the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>,
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code> methods.  These methods will all
translate from the given encoding and return Unicode strings.</li>
<li><em>stream_writer</em>, similarly, is a class that supports encoding output to a
stream.  <em>stream_writer(file_obj)</em> returns an object that supports the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">writelines()</span></code> methods.  These methods expect Unicode
strings, translating them to the given encoding on output.</li>
</ul>
<p>For example, the following code writes a Unicode string into a file,  encoding
it as UTF-8:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">codecs</span>

<span class="n">unistr</span> <span class="o">=</span> <span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u0660\u2000</span><span class="s1">ab ...&#39;</span>

<span class="p">(</span><span class="n">UTF8_encode</span><span class="p">,</span> <span class="n">UTF8_decode</span><span class="p">,</span>
 <span class="n">UTF8_streamreader</span><span class="p">,</span> <span class="n">UTF8_streamwriter</span><span class="p">)</span> <span class="o">=</span> <span class="n">codecs</span><span class="o">.</span><span class="n">lookup</span><span class="p">(</span><span class="s1">&#39;UTF-8&#39;</span><span class="p">)</span>

<span class="n">output</span> <span class="o">=</span> <span class="n">UTF8_streamwriter</span><span class="p">(</span> <span class="nb">open</span><span class="p">(</span> <span class="s1">&#39;/tmp/output&#39;</span><span class="p">,</span> <span class="s1">&#39;wb&#39;</span><span class="p">)</span> <span class="p">)</span>
<span class="n">output</span><span class="o">.</span><span class="n">write</span><span class="p">(</span> <span class="n">unistr</span> <span class="p">)</span>
<span class="n">output</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The following code would then read UTF-8 input from the file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">input</span> <span class="o">=</span> <span class="n">UTF8_streamreader</span><span class="p">(</span> <span class="nb">open</span><span class="p">(</span> <span class="s1">&#39;/tmp/output&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span> <span class="p">)</span>
<span class="nb">print</span> <span class="nb">repr</span><span class="p">(</span><span class="nb">input</span><span class="o">.</span><span class="n">read</span><span class="p">())</span>
<span class="nb">input</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Unicode-aware regular expressions are available through the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module,
which has a new underlying implementation called SRE written by Fredrik Lundh of
Secret Labs AB.</p>
<p>A <code class="docutils literal notranslate"><span class="pre">-U</span></code> command line option was added which causes the Python compiler to
interpret all string literals as Unicode string literals. This is intended to be
used in testing and future-proofing your Python code, since some future version
of Python may drop support for 8-bit strings and provide only Unicode strings.</p>
</div>
<div class="section" id="list-comprehensions">
<h2>List Comprehensions<a class="headerlink" href="#list-comprehensions" title="Permalink to this headline">¶</a></h2>
<p>Lists are a workhorse data type in Python, and many programs manipulate a list
at some point.  Two common operations on lists are to loop over them, and either
pick out the elements that meet a certain criterion, or apply some function to
each element.  For example, given a list of strings, you might want to pull out
all the strings containing a given substring, or strip off trailing whitespace
from each line.</p>
<p>The existing <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> and <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a> functions can be used for this
purpose, but they require a function as one of their arguments.  This is fine if
there’s an existing built-in function that can be passed directly, but if there
isn’t, you have to create a little function to do the required work, and
Python’s scoping rules make the result ugly if the little function needs
additional information.  Take the first example in the previous paragraph,
finding all the strings in the list containing a given substring.  You could
write the following to do it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Given the list L, make a list of all strings</span>
<span class="c1"># containing the substring S.</span>
<span class="n">sublist</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span> <span class="k">lambda</span> <span class="n">s</span><span class="p">,</span> <span class="n">substring</span><span class="o">=</span><span class="n">S</span><span class="p">:</span>
                     <span class="n">string</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">substring</span><span class="p">)</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span><span class="p">,</span>
                  <span class="n">L</span><span class="p">)</span>
</pre></div>
</div>
<p>Because of Python’s scoping rules, a default argument is used so that the
anonymous function created by the <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> statement knows what
substring is being searched for.  List comprehensions make this cleaner:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sublist</span> <span class="o">=</span> <span class="p">[</span> <span class="n">s</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">L</span> <span class="k">if</span> <span class="n">string</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">S</span><span class="p">)</span> <span class="o">!=</span> <span class="o">-</span><span class="mi">1</span> <span class="p">]</span>
</pre></div>
</div>
<p>List comprehensions have the form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span> <span class="n">expression</span> <span class="k">for</span> <span class="n">expr</span> <span class="ow">in</span> <span class="n">sequence1</span>
             <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span> <span class="o">...</span>
             <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span>
             <span class="k">if</span> <span class="n">condition</span> <span class="p">]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>…<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> clauses contain the sequences to be
iterated over.  The sequences do not have to be the same length, because they
are <em>not</em> iterated over in parallel, but from left to right; this is explained
more clearly in the following paragraphs.  The elements of the generated list
will be the successive values of <em>expression</em>.  The final <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> clause
is optional; if present, <em>expression</em> is only evaluated and added to the result
if <em>condition</em> is true.</p>
<p>To make the semantics very clear, a list comprehension is equivalent to the
following Python code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">expr1</span> <span class="ow">in</span> <span class="n">sequence1</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">expr2</span> <span class="ow">in</span> <span class="n">sequence2</span><span class="p">:</span>
    <span class="o">...</span>
        <span class="k">for</span> <span class="n">exprN</span> <span class="ow">in</span> <span class="n">sequenceN</span><span class="p">:</span>
             <span class="k">if</span> <span class="p">(</span><span class="n">condition</span><span class="p">):</span>
                  <span class="c1"># Append the value of</span>
                  <span class="c1"># the expression to the</span>
                  <span class="c1"># resulting list.</span>
</pre></div>
</div>
<p>This means that when there are multiple <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a>…<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>
clauses, the resulting list will be equal to the product of the lengths of all
the sequences.  If you have two lists of length 3, the output list is 9 elements
long:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">seq1</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
<span class="n">seq2</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">)</span>
<span class="o">&gt;&gt;&gt;</span> <span class="p">[</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
<span class="p">[(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)]</span>
</pre></div>
</div>
<p>To avoid introducing an ambiguity into Python’s grammar, if <em>expression</em> is
creating a tuple, it must be surrounded with parentheses.  The first list
comprehension below is a syntax error, while the second one is correct:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Syntax error</span>
<span class="p">[</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
<span class="c1"># Correct</span>
<span class="p">[</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">seq1</span> <span class="k">for</span> <span class="n">y</span> <span class="ow">in</span> <span class="n">seq2</span><span class="p">]</span>
</pre></div>
</div>
<p>The idea of list comprehensions originally comes from the functional programming
language Haskell (<a class="reference external" href="https://www.haskell.org">https://www.haskell.org</a>).  Greg Ewing argued most effectively
for adding them to Python and wrote the initial list comprehension patch, which
was then discussed for a seemingly endless time on the python-dev mailing list
and kept up-to-date by Skip Montanaro.</p>
</div>
<div class="section" id="augmented-assignment">
<h2>Augmented Assignment<a class="headerlink" href="#augmented-assignment" title="Permalink to this headline">¶</a></h2>
<p>Augmented assignment operators, another long-requested feature, have been added
to Python 2.0.  Augmented assignment operators include <code class="docutils literal notranslate"><span class="pre">+=</span></code>, <code class="docutils literal notranslate"><span class="pre">-=</span></code>, <code class="docutils literal notranslate"><span class="pre">*=</span></code>,
and so forth.  For example, the statement <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">+=</span> <span class="pre">2</span></code> increments the value of the
variable  <code class="docutils literal notranslate"><span class="pre">a</span></code> by 2, equivalent to the slightly lengthier <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">a</span> <span class="pre">+</span> <span class="pre">2</span></code>.</p>
<p>The full list of supported assignment operators is <code class="docutils literal notranslate"><span class="pre">+=</span></code>, <code class="docutils literal notranslate"><span class="pre">-=</span></code>, <code class="docutils literal notranslate"><span class="pre">*=</span></code>,
<code class="docutils literal notranslate"><span class="pre">/=</span></code>, <code class="docutils literal notranslate"><span class="pre">%=</span></code>, <code class="docutils literal notranslate"><span class="pre">**=</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;=</span></code>, <code class="docutils literal notranslate"><span class="pre">|=</span></code>, <code class="docutils literal notranslate"><span class="pre">^=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;=</span></code>, and <code class="docutils literal notranslate"><span class="pre">&lt;&lt;=</span></code>.  Python
classes can override the augmented assignment operators by defining methods
named <a class="reference internal" href="../reference/datamodel.html#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__isub__" title="object.__isub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__isub__()</span></code></a>, etc.  For example, the following
<code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code> class stores a number and supports using += to create a new
instance with an incremented value.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Number</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
    <span class="k">def</span> <span class="nf">__iadd__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">increment</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">Number</span><span class="p">(</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">+</span> <span class="n">increment</span><span class="p">)</span>

<span class="n">n</span> <span class="o">=</span> <span class="n">Number</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="n">n</span> <span class="o">+=</span> <span class="mi">3</span>
<span class="nb">print</span> <span class="n">n</span><span class="o">.</span><span class="n">value</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> special method is called with the value of the increment,
and should return a new instance with an appropriately modified value; this
return value is bound as the new value of the variable on the left-hand side.</p>
<p>Augmented assignment operators were first introduced in the C programming
language, and most C-derived languages, such as <strong class="program">awk</strong>, C++, Java, Perl,
and PHP also support them.  The augmented assignment patch was implemented by
Thomas Wouters.</p>
</div>
<div class="section" id="string-methods">
<h2>String Methods<a class="headerlink" href="#string-methods" title="Permalink to this headline">¶</a></h2>
<p>Until now string-manipulation functionality was in the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module,
which was usually a front-end for the <code class="xref py py-mod docutils literal notranslate"><span class="pre">strop</span></code> module written in C.  The
addition of Unicode posed a difficulty for the <code class="xref py py-mod docutils literal notranslate"><span class="pre">strop</span></code> module, because the
functions would all need to be rewritten in order to accept either 8-bit or
Unicode strings.  For functions such as <a class="reference internal" href="../library/string.html#string.replace" title="string.replace"><code class="xref py py-func docutils literal notranslate"><span class="pre">string.replace()</span></code></a>, which takes 3
string arguments, that means eight possible permutations, and correspondingly
complicated code.</p>
<p>Instead, Python 2.0 pushes the problem onto the string type, making string
manipulation functionality available through methods on both 8-bit strings and
Unicode strings.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;andrew&#39;</span><span class="o">.</span><span class="n">capitalize</span><span class="p">()</span>
<span class="go">&#39;Andrew&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;hostname&#39;</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">&#39;os&#39;</span><span class="p">,</span> <span class="s1">&#39;linux&#39;</span><span class="p">)</span>
<span class="go">&#39;hlinuxtname&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;moshe&#39;</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="s1">&#39;sh&#39;</span><span class="p">)</span>
<span class="go">2</span>
</pre></div>
</div>
<p>One thing that hasn’t changed, a noteworthy April Fools’ joke notwithstanding,
is that Python strings are immutable. Thus, the string methods return new
strings, and do not modify the string on which they operate.</p>
<p>The old <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module is still around for backwards compatibility, but it
mostly acts as a front-end to the new string methods.</p>
<p>Two methods which have no parallel in pre-2.0 versions, although they did exist
in JPython for quite some time, are <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code>.
<code class="docutils literal notranslate"><span class="pre">s.startswith(t)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s[:len(t)]</span> <span class="pre">==</span> <span class="pre">t</span></code>, while
<code class="docutils literal notranslate"><span class="pre">s.endswith(t)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">s[-len(t):]</span> <span class="pre">==</span> <span class="pre">t</span></code>.</p>
<p>One other method which deserves special mention is <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code>.  The
<code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method of a string receives one parameter, a sequence of strings,
and is equivalent to the <a class="reference internal" href="../library/string.html#string.join" title="string.join"><code class="xref py py-func docutils literal notranslate"><span class="pre">string.join()</span></code></a> function from the old <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a>
module, with the arguments reversed. In other words, <code class="docutils literal notranslate"><span class="pre">s.join(seq)</span></code> is
equivalent to the old <code class="docutils literal notranslate"><span class="pre">string.join(seq,</span> <span class="pre">s)</span></code>.</p>
</div>
<div class="section" id="garbage-collection-of-cycles">
<h2>Garbage Collection of Cycles<a class="headerlink" href="#garbage-collection-of-cycles" title="Permalink to this headline">¶</a></h2>
<p>The C implementation of Python uses reference counting to implement garbage
collection.  Every Python object maintains a count of the number of references
pointing to itself, and adjusts the count as references are created or
destroyed.  Once the reference count reaches zero, the object is no longer
accessible, since you need to have a reference to an object to access it, and if
the count is zero, no references exist any longer.</p>
<p>Reference counting has some pleasant properties: it’s easy to understand and
implement, and the resulting implementation is portable, fairly fast, and reacts
well with other libraries that implement their own memory handling schemes.  The
major problem with reference counting is that it sometimes doesn’t realise that
objects are no longer accessible, resulting in a memory leak.  This happens when
there are cycles of references.</p>
<p>Consider the simplest possible cycle,  a class instance which has a reference to
itself:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">instance</span> <span class="o">=</span> <span class="n">SomeClass</span><span class="p">()</span>
<span class="n">instance</span><span class="o">.</span><span class="n">myself</span> <span class="o">=</span> <span class="n">instance</span>
</pre></div>
</div>
<p>After the above two lines of code have been executed, the reference count of
<code class="docutils literal notranslate"><span class="pre">instance</span></code> is 2; one reference is from the variable named <code class="docutils literal notranslate"><span class="pre">'instance'</span></code>, and
the other is from the <code class="docutils literal notranslate"><span class="pre">myself</span></code> attribute of the instance.</p>
<p>If the next line of code is <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">instance</span></code>, what happens?  The reference count
of <code class="docutils literal notranslate"><span class="pre">instance</span></code> is decreased by 1, so it has a reference count of 1; the
reference in the <code class="docutils literal notranslate"><span class="pre">myself</span></code> attribute still exists.  Yet the instance is no
longer accessible through Python code, and it could be deleted.  Several objects
can participate in a cycle if they have references to each other, causing all of
the objects to be leaked.</p>
<p>Python 2.0 fixes this problem by periodically executing a cycle detection
algorithm which looks for inaccessible cycles and deletes the objects involved.
A new <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module provides functions to perform a garbage collection,
obtain debugging statistics, and tuning the collector’s parameters.</p>
<p>Running the cycle detection algorithm takes some time, and therefore will result
in some additional overhead.  It is hoped that after we’ve gotten experience
with the cycle collection from using 2.0, Python 2.1 will be able to minimize
the overhead with careful tuning.  It’s not yet obvious how much performance is
lost, because benchmarking this is tricky and depends crucially on how often the
program creates and destroys objects.  The detection of cycles can be disabled
when Python is compiled, if you can’t afford even a tiny speed penalty or
suspect that the cycle collection is buggy, by specifying the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--without-cycle-gc</span></code> switch when running the <strong class="program">configure</strong>
script.</p>
<p>Several people tackled this problem and contributed to a solution.  An early
implementation of the cycle detection approach was written by Toby Kelsey.  The
current algorithm was suggested by Eric Tiedemann during a visit to CNRI, and
Guido van Rossum and Neil Schemenauer wrote two different implementations, which
were later integrated by Neil.  Lots of other people offered suggestions along
the way; the March 2000 archives of the python-dev mailing list contain most of
the relevant discussion, especially in the threads titled “Reference cycle
collection for Python” and “Finalization again”.</p>
</div>
<div class="section" id="other-core-changes">
<h2>Other Core Changes<a class="headerlink" href="#other-core-changes" title="Permalink to this headline">¶</a></h2>
<p>Various minor changes have been made to Python’s syntax and built-in functions.
None of the changes are very far-reaching, but they’re handy conveniences.</p>
<div class="section" id="minor-language-changes">
<h3>Minor Language Changes<a class="headerlink" href="#minor-language-changes" title="Permalink to this headline">¶</a></h3>
<p>A new syntax makes it more convenient to call a given function with a tuple of
arguments and/or a dictionary of keyword arguments. In Python 1.5 and earlier,
you’d use the <a class="reference internal" href="../library/functions.html#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a> built-in function: <code class="docutils literal notranslate"><span class="pre">apply(f,</span> <span class="pre">args,</span> <span class="pre">kw)</span></code> calls the
function <code class="xref py py-func docutils literal notranslate"><span class="pre">f()</span></code> with the argument tuple <em>args</em> and the keyword arguments in
the dictionary <em>kw</em>.  <a class="reference internal" href="../library/functions.html#apply" title="apply"><code class="xref py py-func docutils literal notranslate"><span class="pre">apply()</span></code></a>  is the same in 2.0, but thanks to a patch
from Greg Ewing, <code class="docutils literal notranslate"><span class="pre">f(*args,</span> <span class="pre">**kw)</span></code> is a shorter and clearer way to achieve the
same effect.  This syntax is symmetrical with the syntax for defining
functions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
    <span class="c1"># args is a tuple of positional args,</span>
    <span class="c1"># kw is a dictionary of keyword args</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement can now have its output directed to a file-like
object by following the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> with  <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span> <span class="pre">file</span></code>, similar to the
redirection operator in Unix shells. Previously you’d either have to use the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code> method of the file-like object, which lacks the convenience and
simplicity of <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a>, or you could assign a new value to
<code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and then restore the old value.  For sending output to standard
error, it’s much easier to write this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="o">&gt;&gt;</span> <span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">,</span> <span class="s2">&quot;Warning: action field not supplied&quot;</span>
</pre></div>
</div>
<p>Modules can now be renamed on importing them, using the syntax <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">module</span>
<span class="pre">as</span> <span class="pre">name</span></code> or <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">name</span> <span class="pre">as</span> <span class="pre">othername</span></code>.  The patch was submitted
by Thomas Wouters.</p>
<p>A new format style is available when using the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator; ‘%r’ will insert
the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> of its argument.  This was also added from symmetry
considerations, this time for symmetry with the existing ‘%s’ format style,
which inserts the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of its argument.  For example, <code class="docutils literal notranslate"><span class="pre">'%r</span> <span class="pre">%s'</span> <span class="pre">%</span> <span class="pre">('abc',</span>
<span class="pre">'abc')</span></code> returns a string containing <code class="docutils literal notranslate"><span class="pre">'abc'</span> <span class="pre">abc</span></code>.</p>
<p>Previously there was no way to implement a class that overrode Python’s built-in
<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator and implemented a custom version.  <code class="docutils literal notranslate"><span class="pre">obj</span> <span class="pre">in</span> <span class="pre">seq</span></code> returns
true if <em>obj</em> is present in the sequence <em>seq</em>; Python computes this by simply
trying every index of the sequence until either <em>obj</em> is found or an
<a class="reference internal" href="../library/exceptions.html#exceptions.IndexError" title="exceptions.IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> is encountered.  Moshe Zadka contributed a patch which adds a
<a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> magic method for providing a custom implementation for
<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>. Additionally, new built-in objects written in C can define what
<a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> means for them via a new slot in the sequence protocol.</p>
<p>Earlier versions of Python used a recursive algorithm for deleting objects.
Deeply nested data structures could cause the interpreter to fill up the C stack
and crash; Christian Tismer rewrote the deletion logic to fix this problem.  On
a related note, comparing recursive objects recursed infinitely and crashed;
Jeremy Hylton rewrote the code to no longer crash, producing a useful result
instead.  For example, after this code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">b</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">a</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
</pre></div>
</div>
<p>The comparison <code class="docutils literal notranslate"><span class="pre">a==b</span></code> returns true, because the two recursive data structures
are isomorphic. See the thread “trashcan and PR#7” in the April 2000 archives of
the python-dev mailing list for the discussion leading up to this
implementation, and some useful relevant links.    Note that comparisons can now
also raise exceptions. In earlier versions of Python, a comparison operation
such as <code class="docutils literal notranslate"><span class="pre">cmp(a,b)</span></code> would always produce an answer, even if a user-defined
<a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method encountered an error, since the resulting exception would
simply be silently swallowed.</p>
<p>Work has been done on porting Python to 64-bit Windows on the Itanium processor,
mostly by Trent Mick of ActiveState.  (Confusingly, <code class="docutils literal notranslate"><span class="pre">sys.platform</span></code> is still
<code class="docutils literal notranslate"><span class="pre">'win32'</span></code> on Win64 because it seems that for ease of porting, MS Visual C++
treats code as 32 bit on Itanium.) PythonWin also supports Windows CE; see the
Python CE page at <a class="reference external" href="http://pythonce.sourceforge.net/">http://pythonce.sourceforge.net/</a> for more information.</p>
<p>Another new platform is Darwin/MacOS X; initial support for it is in Python 2.0.
Dynamic loading works, if you specify “configure –with-dyld –with-suffix=.x”.
Consult the README in the Python source distribution for more instructions.</p>
<p>An attempt has been made to alleviate one of Python’s warts, the often-confusing
<a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception when code refers to a local variable before the
variable has been assigned a value.  For example, the following code raises an
exception on the <a class="reference internal" href="../reference/simple_stmts.html#print"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">print</span></code></a> statement in both 1.5.2 and 2.0; in 1.5.2 a
<a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception is raised, while 2.0 raises a new
<a class="reference internal" href="../library/exceptions.html#exceptions.UnboundLocalError" title="exceptions.UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> exception. <a class="reference internal" href="../library/exceptions.html#exceptions.UnboundLocalError" title="exceptions.UnboundLocalError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnboundLocalError</span></code></a> is a subclass of
<a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>, so any existing code that expects <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> to be
raised should still work.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="nb">print</span> <span class="s2">&quot;i=&quot;</span><span class="p">,</span><span class="n">i</span>
    <span class="n">i</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">1</span>
<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>Two new exceptions, <a class="reference internal" href="../library/exceptions.html#exceptions.TabError" title="exceptions.TabError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TabError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.IndentationError" title="exceptions.IndentationError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndentationError</span></code></a>, have been
introduced.  They’re both subclasses of <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a>, and are raised when
Python code is found to be improperly indented.</p>
</div>
<div class="section" id="changes-to-built-in-functions">
<h3>Changes to Built-in Functions<a class="headerlink" href="#changes-to-built-in-functions" title="Permalink to this headline">¶</a></h3>
<p>A new built-in, <code class="docutils literal notranslate"><span class="pre">zip(seq1,</span> <span class="pre">seq2,</span> <span class="pre">...)</span></code>, has been added.  <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a>
returns a list of tuples where each tuple contains the i-th element from each of
the argument sequences.  The difference between <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> and <code class="docutils literal notranslate"><span class="pre">map(None,</span>
<span class="pre">seq1,</span> <span class="pre">seq2)</span></code> is that <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a> pads the sequences with <code class="docutils literal notranslate"><span class="pre">None</span></code> if the
sequences aren’t all of the same length, while <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> truncates the
returned list to the length of the shortest argument sequence.</p>
<p>The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> functions now accept an optional “base”
parameter when the first argument is a string. <code class="docutils literal notranslate"><span class="pre">int('123',</span> <span class="pre">10)</span></code> returns 123,
while <code class="docutils literal notranslate"><span class="pre">int('123',</span> <span class="pre">16)</span></code> returns 291.  <code class="docutils literal notranslate"><span class="pre">int(123,</span> <span class="pre">16)</span></code> raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception with the message “can’t convert non-string with
explicit base”.</p>
<p>A new variable holding more detailed version information has been added to the
<a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module.  <code class="docutils literal notranslate"><span class="pre">sys.version_info</span></code> is a tuple <code class="docutils literal notranslate"><span class="pre">(major,</span> <span class="pre">minor,</span> <span class="pre">micro,</span>
<span class="pre">level,</span> <span class="pre">serial)</span></code> For example, in a hypothetical 2.0.1beta1, <code class="docutils literal notranslate"><span class="pre">sys.version_info</span></code>
would be <code class="docutils literal notranslate"><span class="pre">(2,</span> <span class="pre">0,</span> <span class="pre">1,</span> <span class="pre">'beta',</span> <span class="pre">1)</span></code>. <em>level</em> is a string such as <code class="docutils literal notranslate"><span class="pre">&quot;alpha&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;beta&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;final&quot;</span></code> for a final release.</p>
<p>Dictionaries have an odd new method, <code class="docutils literal notranslate"><span class="pre">setdefault(key,</span> <span class="pre">default)</span></code>, which
behaves similarly to the existing <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code> method.  However, if the key is
missing, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code> both returns the value of <em>default</em> as <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>
would do, and also inserts it into the dictionary as the value for <em>key</em>.  Thus,
the following lines of code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="nb">dict</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span> <span class="n">key</span> <span class="p">):</span> <span class="k">return</span> <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">return</span> <span class="nb">dict</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
</pre></div>
</div>
<p>can be reduced to a single <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">dict.setdefault(key,</span> <span class="pre">[])</span></code> statement.</p>
<p>The interpreter sets a maximum recursion depth in order to catch runaway
recursion before filling the C stack and causing a core dump or GPF..
Previously this limit was fixed when you compiled Python, but in 2.0 the maximum
recursion depth can be read and modified using <a class="reference internal" href="../library/sys.html#sys.getrecursionlimit" title="sys.getrecursionlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getrecursionlimit()</span></code></a> and
<a class="reference internal" href="../library/sys.html#sys.setrecursionlimit" title="sys.setrecursionlimit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setrecursionlimit()</span></code></a>. The default value is 1000, and a rough maximum
value for a given platform can be found by running a new script,
<code class="file docutils literal notranslate"><span class="pre">Misc/find_recursionlimit.py</span></code>.</p>
</div>
</div>
<div class="section" id="porting-to-2-0">
<h2>Porting to 2.0<a class="headerlink" href="#porting-to-2-0" title="Permalink to this headline">¶</a></h2>
<p>New Python releases try hard to be compatible with previous releases, and the
record has been pretty good.  However, some changes are considered useful
enough, usually because they fix initial design decisions that turned out to be
actively mistaken, that breaking backward compatibility can’t always be avoided.
This section lists the changes in Python 2.0 that may cause old Python code to
break.</p>
<p>The change which will probably break the most code is tightening up the
arguments accepted by some methods.  Some methods would take multiple arguments
and treat them as a tuple, particularly various list methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">insert()</span></code>. In earlier versions of Python, if <code class="docutils literal notranslate"><span class="pre">L</span></code> is
a list, <code class="docutils literal notranslate"><span class="pre">L.append(</span> <span class="pre">1,2</span> <span class="pre">)</span></code> appends the tuple <code class="docutils literal notranslate"><span class="pre">(1,2)</span></code> to the list.  In Python
2.0 this causes a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception to be raised, with the message:
‘append requires exactly 1 argument; 2 given’.  The fix is to simply add an
extra set of parentheses to pass both values as a tuple:  <code class="docutils literal notranslate"><span class="pre">L.append(</span> <span class="pre">(1,2)</span> <span class="pre">)</span></code>.</p>
<p>The earlier versions of these methods were more forgiving because they used an
old function in Python’s C interface to parse their arguments; 2.0 modernizes
them to use <code class="xref py py-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code>, the current argument parsing function,
which provides more helpful error messages and treats multi-argument calls as
errors.  If you absolutely must use 2.0 but can’t fix your code, you can edit
<code class="file docutils literal notranslate"><span class="pre">Objects/listobject.c</span></code> and define the preprocessor symbol
<code class="docutils literal notranslate"><span class="pre">NO_STRICT_LIST_APPEND</span></code> to preserve the old behaviour; this isn’t recommended.</p>
<p>Some of the functions in the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module are still forgiving in this
way.  For example, <code class="xref py py-func docutils literal notranslate"><span class="pre">socket.connect(</span> <span class="pre">('hostname',</span> <span class="pre">25)</span> <span class="pre">)()</span></code> is the correct
form, passing a tuple representing an IP address, but <code class="xref py py-func docutils literal notranslate"><span class="pre">socket.connect(</span>
<span class="pre">'hostname',</span> <span class="pre">25</span> <span class="pre">)()</span></code> also works. <code class="xref py py-func docutils literal notranslate"><span class="pre">socket.connect_ex()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">socket.bind()</span></code>
are similarly easy-going.  2.0alpha1 tightened these functions up, but because
the documentation actually used the erroneous multiple argument form, many
people wrote code which would break with the stricter checking.  GvR backed out
the changes in the face of public reaction, so for the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module, the
documentation was fixed and the multiple argument form is simply marked as
deprecated; it <em>will</em> be tightened up again in a future Python version.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">\x</span></code> escape in string literals now takes exactly 2 hex digits.  Previously
it would consume all the hex digits following the ‘x’ and take the lowest 8 bits
of the result, so <code class="docutils literal notranslate"><span class="pre">\x123456</span></code> was equivalent to <code class="docutils literal notranslate"><span class="pre">\x56</span></code>.</p>
<p>The <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exceptions have a more friendly
error message, whose text will be something like <code class="docutils literal notranslate"><span class="pre">'Spam'</span> <span class="pre">instance</span> <span class="pre">has</span> <span class="pre">no</span>
<span class="pre">attribute</span> <span class="pre">'eggs'</span></code> or <code class="docutils literal notranslate"><span class="pre">name</span> <span class="pre">'eggs'</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">defined</span></code>.  Previously the error
message was just the missing attribute name <code class="docutils literal notranslate"><span class="pre">eggs</span></code>, and code written to take
advantage of this fact will break in 2.0.</p>
<p>Some work has been done to make integers and long integers a bit more
interchangeable.  In 1.5.2, large-file support was added for Solaris, to allow
reading files larger than 2 GiB; this made the <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code> method of file
objects return a long integer instead of a regular integer.  Some code would
subtract two file offsets and attempt to use the result to multiply a sequence
or slice a string, but this raised a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  In 2.0, long integers
can be used to multiply or slice a sequence, and it’ll behave as you’d
intuitively expect it to; <code class="docutils literal notranslate"><span class="pre">3L</span> <span class="pre">*</span> <span class="pre">'abc'</span></code> produces ‘abcabcabc’, and
<code class="docutils literal notranslate"><span class="pre">(0,1,2,3)[2L:4L]</span></code> produces (2,3). Long integers can also be used in various
contexts where previously only integers were accepted, such as in the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code> method of file objects, and in the formats supported by the <code class="docutils literal notranslate"><span class="pre">%</span></code>
operator (<code class="docutils literal notranslate"><span class="pre">%d</span></code>, <code class="docutils literal notranslate"><span class="pre">%i</span></code>, <code class="docutils literal notranslate"><span class="pre">%x</span></code>, etc.).  For example, <code class="docutils literal notranslate"><span class="pre">&quot;%d&quot;</span> <span class="pre">%</span> <span class="pre">2L**64</span></code> will
produce the string <code class="docutils literal notranslate"><span class="pre">18446744073709551616</span></code>.</p>
<p>The subtlest long integer change of all is that the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of a long
integer no longer has a trailing ‘L’ character, though <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> still
includes it.  The ‘L’ annoyed many people who wanted to print long integers that
looked just like regular integers, since they had to go out of their way to chop
off the character.  This is no longer a problem in 2.0, but code which does
<code class="docutils literal notranslate"><span class="pre">str(longval)[:-1]</span></code> and assumes the ‘L’ is there, will now lose the final
digit.</p>
<p>Taking the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> of a float now uses a different formatting precision
than <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.  <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> uses <code class="docutils literal notranslate"><span class="pre">%.17g</span></code> format string for C’s
<code class="xref py py-func docutils literal notranslate"><span class="pre">sprintf()</span></code>, while <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> uses <code class="docutils literal notranslate"><span class="pre">%.12g</span></code> as before.  The effect is that
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> may occasionally show more decimal places than  <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>, for
certain numbers.  For example, the number 8.1 can’t be represented exactly in
binary, so <code class="docutils literal notranslate"><span class="pre">repr(8.1)</span></code> is <code class="docutils literal notranslate"><span class="pre">'8.0999999999999996'</span></code>, while str(8.1) is
<code class="docutils literal notranslate"><span class="pre">'8.1'</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">-X</span></code> command-line option, which turned all standard exceptions into
strings instead of classes, has been removed; the standard exceptions will now
always be classes.  The <a class="reference internal" href="../library/exceptions.html#module-exceptions" title="exceptions: Standard exception classes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">exceptions</span></code></a> module containing the standard
exceptions was translated from Python to a built-in C module, written by Barry
Warsaw and Fredrik Lundh.</p>
</div>
<div class="section" id="extending-embedding-changes">
<h2>Extending/Embedding Changes<a class="headerlink" href="#extending-embedding-changes" title="Permalink to this headline">¶</a></h2>
<p>Some of the changes are under the covers, and will only be apparent to people
writing C extension modules or embedding a Python interpreter in a larger
application.  If you aren’t dealing with Python’s C API, you can safely skip
this section.</p>
<p>The version number of the Python C API was incremented, so C extensions compiled
for 1.5.2 must be recompiled in order to work with 2.0.  On Windows, it’s not
possible for Python 2.0 to import a third party extension built for Python 1.5.x
due to how Windows DLLs work, so Python will raise an exception and the import
will fail.</p>
<p>Users of Jim Fulton’s ExtensionClass module will be pleased to find out that
hooks have been added so that ExtensionClasses are now supported by
<a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>. This means you no longer have to
remember to write code such as <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">type(obj)</span> <span class="pre">==</span> <span class="pre">myExtensionClass</span></code>, but can use
the more natural <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">isinstance(obj,</span> <span class="pre">myExtensionClass)</span></code>.</p>
<p>The <code class="file docutils literal notranslate"><span class="pre">Python/importdl.c</span></code> file, which was a mass of #ifdefs to support
dynamic loading on many different platforms, was cleaned up and reorganised by
Greg Stein.  <code class="file docutils literal notranslate"><span class="pre">importdl.c</span></code> is now quite small, and platform-specific code
has been moved into a bunch of <code class="file docutils literal notranslate"><span class="pre">Python/dynload_*.c</span></code> files.  Another
cleanup: there were also a number of <code class="file docutils literal notranslate"><span class="pre">my*.h</span></code> files in the Include/
directory that held various portability hacks; they’ve been merged into a single
file, <code class="file docutils literal notranslate"><span class="pre">Include/pyport.h</span></code>.</p>
<p>Vladimir Marangozov’s long-awaited malloc restructuring was completed, to make
it easy to have the Python interpreter use a custom allocator instead of C’s
standard <code class="xref py py-func docutils literal notranslate"><span class="pre">malloc()</span></code>.  For documentation, read the comments in
<code class="file docutils literal notranslate"><span class="pre">Include/pymem.h</span></code> and <code class="file docutils literal notranslate"><span class="pre">Include/objimpl.h</span></code>.  For the lengthy
discussions during which the interface was hammered out, see the Web archives of
the ‘patches’ and ‘python-dev’ lists at python.org.</p>
<p>Recent versions of the GUSI development environment for MacOS support POSIX
threads.  Therefore, Python’s POSIX threading support now works on the
Macintosh.  Threading support using the user-space GNU <code class="docutils literal notranslate"><span class="pre">pth</span></code> library was also
contributed.</p>
<p>Threading support on Windows was enhanced, too.  Windows supports thread locks
that use kernel objects only in case of contention; in the common case when
there’s no contention, they use simpler functions which are an order of
magnitude faster.  A threaded version of Python 1.5.2 on NT is twice as slow as
an unthreaded version; with the 2.0 changes, the difference is only 10%.  These
improvements were contributed by Yakov Markovitch.</p>
<p>Python 2.0’s source now uses only ANSI C prototypes, so compiling Python now
requires an ANSI C compiler, and can no longer be done using a compiler that
only supports K&amp;R C.</p>
<p>Previously the Python virtual machine used 16-bit numbers in its bytecode,
limiting the size of source files.  In particular, this affected the maximum
size of literal lists and dictionaries in Python source; occasionally people who
are generating Python code would run into this limit.  A patch by Charles G.
Waldman raises the limit from <code class="docutils literal notranslate"><span class="pre">2^16</span></code> to <code class="docutils literal notranslate"><span class="pre">2^{32}</span></code>.</p>
<p>Three new convenience functions intended for adding constants to a module’s
dictionary at module initialization time were added: <code class="xref py py-func docutils literal notranslate"><span class="pre">PyModule_AddObject()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">PyModule_AddIntConstant()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">PyModule_AddStringConstant()</span></code>.  Each
of these functions takes a module object, a null-terminated C string containing
the name to be added, and a third argument for the value to be assigned to the
name.  This third argument is, respectively, a Python object, a C long, or a C
string.</p>
<p>A wrapper API was added for Unix-style signal handlers. <code class="xref py py-func docutils literal notranslate"><span class="pre">PyOS_getsig()</span></code> gets
a signal handler and <code class="xref py py-func docutils literal notranslate"><span class="pre">PyOS_setsig()</span></code> will set a new handler.</p>
</div>
<div class="section" id="distutils-making-modules-easy-to-install">
<h2>Distutils: Making Modules Easy to Install<a class="headerlink" href="#distutils-making-modules-easy-to-install" title="Permalink to this headline">¶</a></h2>
<p>Before Python 2.0, installing modules was a tedious affair – there was no way
to figure out automatically where Python is installed, or what compiler options
to use for extension modules.  Software authors had to go through an arduous
ritual of editing Makefiles and configuration files, which only really work on
Unix and leave Windows and MacOS unsupported.  Python users faced wildly
differing installation instructions which varied between different extension
packages, which made administering a Python installation something of  a chore.</p>
<p>The SIG for distribution utilities, shepherded by Greg Ward, has created the
Distutils, a system to make package installation much easier.  They form the
<a class="reference internal" href="../library/distutils.html#module-distutils" title="distutils: Support for building and installing Python modules into an existing Python installation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">distutils</span></code></a> package, a new part of Python’s standard library. In the best
case, installing a Python module from source will require the same steps: first
you simply mean unpack the tarball or zip archive, and the run “<code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">install</span></code>”.  The platform will be automatically detected, the compiler
will be recognized, C extension modules will be compiled, and the distribution
installed into the proper directory.  Optional command-line arguments provide
more control over the installation process, the distutils package offers many
places to override defaults – separating the build from the install, building
or installing in non-default directories, and more.</p>
<p>In order to use the Distutils, you need to write a <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script.  For
the simple case, when the software contains only .py files, a minimal
<code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> can be just a few lines long:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span> <span class="p">(</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="n">version</span> <span class="o">=</span> <span class="s2">&quot;1.0&quot;</span><span class="p">,</span>
       <span class="n">py_modules</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;module1&quot;</span><span class="p">,</span> <span class="s2">&quot;module2&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>The <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> file isn’t much more complicated if the software consists
of a few packages:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span>
<span class="n">setup</span> <span class="p">(</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="n">version</span> <span class="o">=</span> <span class="s2">&quot;1.0&quot;</span><span class="p">,</span>
       <span class="n">packages</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;package&quot;</span><span class="p">,</span> <span class="s2">&quot;package.subpackage&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>A C extension can be the most complicated case; here’s an example taken from
the PyXML package:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils.core</span> <span class="k">import</span> <span class="n">setup</span><span class="p">,</span> <span class="n">Extension</span>

<span class="n">expat_extension</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s1">&#39;xml.parsers.pyexpat&#39;</span><span class="p">,</span>
     <span class="n">define_macros</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;XML_NS&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)],</span>
     <span class="n">include_dirs</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">&#39;extensions/expat/xmltok&#39;</span><span class="p">,</span>
                      <span class="s1">&#39;extensions/expat/xmlparse&#39;</span> <span class="p">],</span>
     <span class="n">sources</span> <span class="o">=</span> <span class="p">[</span> <span class="s1">&#39;extensions/pyexpat.c&#39;</span><span class="p">,</span>
                 <span class="s1">&#39;extensions/expat/xmltok/xmltok.c&#39;</span><span class="p">,</span>
                 <span class="s1">&#39;extensions/expat/xmltok/xmlrole.c&#39;</span><span class="p">,</span> <span class="p">]</span>
       <span class="p">)</span>
<span class="n">setup</span> <span class="p">(</span><span class="n">name</span> <span class="o">=</span> <span class="s2">&quot;PyXML&quot;</span><span class="p">,</span> <span class="n">version</span> <span class="o">=</span> <span class="s2">&quot;0.5.4&quot;</span><span class="p">,</span>
       <span class="n">ext_modules</span> <span class="o">=</span><span class="p">[</span> <span class="n">expat_extension</span> <span class="p">]</span> <span class="p">)</span>
</pre></div>
</div>
<p>The Distutils can also take care of creating source and binary distributions.
The “sdist” command, run by “<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">sdist</span></code>’, builds a source
distribution such as <code class="file docutils literal notranslate"><span class="pre">foo-1.0.tar.gz</span></code>. Adding new commands isn’t
difficult, “bdist_rpm” and “bdist_wininst” commands have already been
contributed to create an RPM distribution and a Windows installer for the
software, respectively.  Commands to create other distribution formats such as
Debian packages and Solaris <code class="file docutils literal notranslate"><span class="pre">.pkg</span></code> files are in various stages of
development.</p>
<p>All this is documented in a new manual, <em>Distributing Python Modules</em>, that
joins the basic set of Python documentation.</p>
</div>
<div class="section" id="xml-modules">
<h2>XML Modules<a class="headerlink" href="#xml-modules" title="Permalink to this headline">¶</a></h2>
<p>Python 1.5.2 included a simple XML parser in the form of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">xmllib</span></code>
module, contributed by Sjoerd Mullender.  Since 1.5.2’s release, two different
interfaces for processing XML have become common: SAX2 (version 2 of the Simple
API for XML) provides an event-driven interface with some similarities to
<code class="xref py py-mod docutils literal notranslate"><span class="pre">xmllib</span></code>, and the DOM (Document Object Model) provides a tree-based
interface, transforming an XML document into a tree of nodes that can be
traversed and modified.  Python 2.0 includes a SAX2 interface and a stripped-down
DOM interface as part of the <a class="reference internal" href="../library/xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package. Here we will give a brief
overview of these new interfaces; consult the Python documentation or the source
code for complete details. The Python XML SIG is also working on improved
documentation.</p>
<div class="section" id="sax2-support">
<h3>SAX2 Support<a class="headerlink" href="#sax2-support" title="Permalink to this headline">¶</a></h3>
<p>SAX defines an event-driven interface for parsing XML.  To use SAX, you must
write a SAX handler class.  Handler classes inherit from various classes
provided by SAX, and override various methods that will then be called by the
XML parser.  For example, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">startElement()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">endElement()</span></code>
methods are called for every starting and end tag encountered by the parser, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">characters()</span></code> method is called for every chunk of character data, and so
forth.</p>
<p>The advantage of the event-driven approach is that the whole document doesn’t
have to be resident in memory at any one time, which matters if you are
processing really huge documents.  However, writing the SAX handler class can
get very complicated if you’re trying to modify the document structure in some
elaborate way.</p>
<p>For example, this little example program defines a handler that prints a message
for every starting and ending tag, and then parses the file <code class="file docutils literal notranslate"><span class="pre">hamlet.xml</span></code>
using it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml</span> <span class="k">import</span> <span class="n">sax</span>

<span class="k">class</span> <span class="nc">SimpleHandler</span><span class="p">(</span><span class="n">sax</span><span class="o">.</span><span class="n">ContentHandler</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">startElement</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">attrs</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;Start of element:&#39;</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="n">attrs</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>

    <span class="k">def</span> <span class="nf">endElement</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;End of element:&#39;</span><span class="p">,</span> <span class="n">name</span>

<span class="c1"># Create a parser object</span>
<span class="n">parser</span> <span class="o">=</span> <span class="n">sax</span><span class="o">.</span><span class="n">make_parser</span><span class="p">()</span>

<span class="c1"># Tell it what handler to use</span>
<span class="n">handler</span> <span class="o">=</span> <span class="n">SimpleHandler</span><span class="p">()</span>
<span class="n">parser</span><span class="o">.</span><span class="n">setContentHandler</span><span class="p">(</span> <span class="n">handler</span> <span class="p">)</span>

<span class="c1"># Parse a file!</span>
<span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span> <span class="s1">&#39;hamlet.xml&#39;</span> <span class="p">)</span>
</pre></div>
</div>
<p>For more information, consult the Python documentation, or the XML HOWTO at
<a class="reference external" href="http://pyxml.sourceforge.net/topics/howto/xml-howto.html">http://pyxml.sourceforge.net/topics/howto/xml-howto.html</a>.</p>
</div>
<div class="section" id="dom-support">
<h3>DOM Support<a class="headerlink" href="#dom-support" title="Permalink to this headline">¶</a></h3>
<p>The Document Object Model is a tree-based representation for an XML document.  A
top-level <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> instance is the root of the tree, and has a single
child which is the top-level <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> instance. This <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code>
has children nodes representing character data and any sub-elements, which may
have further children of their own, and so forth.  Using the DOM you can
traverse the resulting tree any way you like, access element and attribute
values, insert and delete nodes, and convert the tree back into XML.</p>
<p>The DOM is useful for modifying XML documents, because you can create a DOM
tree, modify it by adding new nodes or rearranging subtrees, and then produce a
new XML document as output.  You can also construct a DOM tree manually and
convert it to XML, which can be a more flexible way of producing XML output than
simply writing <code class="docutils literal notranslate"><span class="pre">&lt;tag1&gt;</span></code>…<code class="docutils literal notranslate"><span class="pre">&lt;/tag1&gt;</span></code> to a file.</p>
<p>The DOM implementation included with Python lives in the <a class="reference internal" href="../library/xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a>
module.  It’s a lightweight implementation of the Level 1 DOM with support for
XML namespaces.  The  <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">parseString()</span></code> convenience
functions are provided for generating a DOM tree:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.dom</span> <span class="k">import</span> <span class="n">minidom</span>
<span class="n">doc</span> <span class="o">=</span> <span class="n">minidom</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s1">&#39;hamlet.xml&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">doc</span></code> is a <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code> instance.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code>, like all the other
DOM classes such as <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Text</span></code>, is a subclass of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> base class.  All the nodes in a DOM tree therefore support certain
common methods, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">toxml()</span></code> which returns a string containing the XML
representation of the node and its children.  Each class also has special
methods of its own; for example, <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Document</span></code>
instances have a method to find all child elements with a given tag name.
Continuing from the previous 2-line example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">perslist</span> <span class="o">=</span> <span class="n">doc</span><span class="o">.</span><span class="n">getElementsByTagName</span><span class="p">(</span> <span class="s1">&#39;PERSONA&#39;</span> <span class="p">)</span>
<span class="nb">print</span> <span class="n">perslist</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">toxml</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">perslist</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">toxml</span><span class="p">()</span>
</pre></div>
</div>
<p>For the <em>Hamlet</em> XML file, the above few lines output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&lt;</span><span class="n">PERSONA</span><span class="o">&gt;</span><span class="n">CLAUDIUS</span><span class="p">,</span> <span class="n">king</span> <span class="n">of</span> <span class="n">Denmark</span><span class="o">.</span> <span class="o">&lt;/</span><span class="n">PERSONA</span><span class="o">&gt;</span>
<span class="o">&lt;</span><span class="n">PERSONA</span><span class="o">&gt;</span><span class="n">HAMLET</span><span class="p">,</span> <span class="n">son</span> <span class="n">to</span> <span class="n">the</span> <span class="n">late</span><span class="p">,</span> <span class="ow">and</span> <span class="n">nephew</span> <span class="n">to</span> <span class="n">the</span> <span class="n">present</span> <span class="n">king</span><span class="o">.&lt;/</span><span class="n">PERSONA</span><span class="o">&gt;</span>
</pre></div>
</div>
<p>The root element of the document is available as <code class="docutils literal notranslate"><span class="pre">doc.documentElement</span></code>, and
its children can be easily modified by deleting, adding, or removing nodes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">root</span> <span class="o">=</span> <span class="n">doc</span><span class="o">.</span><span class="n">documentElement</span>

<span class="c1"># Remove the first child</span>
<span class="n">root</span><span class="o">.</span><span class="n">removeChild</span><span class="p">(</span> <span class="n">root</span><span class="o">.</span><span class="n">childNodes</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="p">)</span>

<span class="c1"># Move the new first child to the end</span>
<span class="n">root</span><span class="o">.</span><span class="n">appendChild</span><span class="p">(</span> <span class="n">root</span><span class="o">.</span><span class="n">childNodes</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="p">)</span>

<span class="c1"># Insert the new first child (originally,</span>
<span class="c1"># the third child) before the 20th child.</span>
<span class="n">root</span><span class="o">.</span><span class="n">insertBefore</span><span class="p">(</span> <span class="n">root</span><span class="o">.</span><span class="n">childNodes</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">root</span><span class="o">.</span><span class="n">childNodes</span><span class="p">[</span><span class="mi">20</span><span class="p">]</span> <span class="p">)</span>
</pre></div>
</div>
<p>Again, I will refer you to the Python documentation for a complete listing of
the different <code class="xref py py-class docutils literal notranslate"><span class="pre">Node</span></code> classes and their various methods.</p>
</div>
<div class="section" id="relationship-to-pyxml">
<h3>Relationship to PyXML<a class="headerlink" href="#relationship-to-pyxml" title="Permalink to this headline">¶</a></h3>
<p>The XML Special Interest Group has been working on XML-related Python code for a
while.  Its code distribution, called PyXML, is available from the SIG’s Web
pages at <a class="reference external" href="https://www.python.org/community/sigs/current/xml-sig">https://www.python.org/community/sigs/current/xml-sig</a>. The PyXML distribution also used
the package name <code class="docutils literal notranslate"><span class="pre">xml</span></code>.  If you’ve written programs that used PyXML, you’re
probably wondering about its compatibility with the 2.0 <a class="reference internal" href="../library/xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package.</p>
<p>The answer is that Python 2.0’s <a class="reference internal" href="../library/xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package isn’t compatible with PyXML,
but can be made compatible by installing a recent version PyXML.  Many
applications can get by with the XML support that is included with Python 2.0,
but more complicated applications will require that the full PyXML package will
be installed.  When installed, PyXML versions 0.6.0 or greater will replace the
<a class="reference internal" href="../library/xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package shipped with Python, and will be a strict superset of the
standard package, adding a bunch of additional features.  Some of the additional
features in PyXML include:</p>
<ul class="simple">
<li>4DOM, a full DOM implementation from FourThought, Inc.</li>
<li>The xmlproc validating parser, written by Lars Marius Garshol.</li>
<li>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">sgmlop</span></code> parser accelerator module, written by Fredrik Lundh.</li>
</ul>
</div>
</div>
<div class="section" id="module-changes">
<h2>Module changes<a class="headerlink" href="#module-changes" title="Permalink to this headline">¶</a></h2>
<p>Lots of improvements and bugfixes were made to Python’s extensive standard
library; some of the affected modules include <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a>,
<a class="reference internal" href="../library/configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a>, <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a>, <a class="reference internal" href="../library/calendar.html#module-calendar" title="calendar: Functions for working with calendars, including some emulation of the Unix cal program."><code class="xref py py-mod docutils literal notranslate"><span class="pre">calendar</span></code></a>, <a class="reference internal" href="../library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a>, <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">xmllib</span></code>, <a class="reference internal" href="../library/aifc.html#module-aifc" title="aifc: Read and write audio files in AIFF or AIFC format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">aifc</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">chunk,</span> <span class="pre">wave</span></code>, <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a>, <a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>,
and <a class="reference internal" href="../library/nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a>.  Consult the CVS logs for the exact patch-by-patch details.</p>
<p>Brian Gallew contributed OpenSSL support for the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module.  OpenSSL
is an implementation of the Secure Socket Layer, which encrypts the data being
sent over a socket.  When compiling Python, you can edit <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code>
to include SSL support, which adds an additional function to the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a>
module: <code class="docutils literal notranslate"><span class="pre">socket.ssl(socket,</span> <span class="pre">keyfile,</span> <span class="pre">certfile)</span></code>, which takes a socket
object and returns an SSL socket.  The <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> and <a class="reference internal" href="../library/urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> modules
were also changed to support <code class="docutils literal notranslate"><span class="pre">https://</span></code> URLs, though no one has implemented
FTP or SMTP over SSL.</p>
<p>The <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> module has been rewritten by Greg Stein to support HTTP/1.1.
Backward compatibility with the 1.5 version of <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> is provided,
though using HTTP/1.1 features such as pipelining will require rewriting code to
use a different set of interfaces.</p>
<p>The <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module now supports Tcl/Tk version 8.1, 8.2, or 8.3, and
support for the older 7.x versions has been dropped.  The Tkinter module now
supports displaying Unicode strings in Tk widgets. Also, Fredrik Lundh
contributed an optimization which makes operations like <code class="docutils literal notranslate"><span class="pre">create_line</span></code> and
<code class="docutils literal notranslate"><span class="pre">create_polygon</span></code> much faster, especially when using lots of coordinates.</p>
<p>The <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module has been greatly extended, starting from Oliver
Andrich’s enhanced version, to provide many additional functions from ncurses
and SYSV curses, such as colour, alternative character set support, pads, and
mouse support.  This means the module is no longer compatible with operating
systems that only have BSD curses, but there don’t seem to be any currently
maintained OSes that fall into this category.</p>
<p>As mentioned in the earlier discussion of 2.0’s Unicode support, the underlying
implementation of the regular expressions provided by the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module has
been changed.  SRE, a new regular expression engine written by Fredrik Lundh and
partially funded by Hewlett Packard, supports matching against both 8-bit
strings and Unicode strings.</p>
</div>
<div class="section" id="new-modules">
<h2>New modules<a class="headerlink" href="#new-modules" title="Permalink to this headline">¶</a></h2>
<p>A number of new modules were added.  We’ll simply list them with brief
descriptions; consult the 2.0 documentation for the details of a particular
module.</p>
<ul class="simple">
<li><a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a>:  For registering functions to be called before the Python
interpreter exits. Code that currently sets <code class="docutils literal notranslate"><span class="pre">sys.exitfunc</span></code> directly should be
changed to  use the <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module instead, importing <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> and
calling <a class="reference internal" href="../library/atexit.html#atexit.register" title="atexit.register"><code class="xref py py-func docutils literal notranslate"><span class="pre">atexit.register()</span></code></a> with  the function to be called on exit.
(Contributed by Skip Montanaro.)</li>
<li><a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">encodings</span></code>, <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a>:  Added as part of the new
Unicode support.</li>
<li><a class="reference internal" href="../library/filecmp.html#module-filecmp" title="filecmp: Compare files efficiently."><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code></a>: Supersedes the old <a class="reference internal" href="../library/functions.html#cmp" title="cmp"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmp</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cmpcache</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">dircmp</span></code> modules, which have now become deprecated. (Contributed by Gordon
MacMillan and Moshe Zadka.)</li>
<li><a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a>: This module provides internationalization (I18N) and
localization (L10N) support for Python programs by providing an interface to the
GNU gettext message catalog library. (Integrated by Barry Warsaw, from separate
contributions by Martin  von Löwis, Peter Funk, and James Henstridge.)</li>
<li><code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code>: Support for the <code class="file docutils literal notranslate"><span class="pre">/dev/audio</span></code> device on Linux, a
twin to the existing <a class="reference internal" href="../library/sunaudio.html#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a> module. (Contributed by Peter Bosch,
with fixes by Jeremy Hylton.)</li>
<li><a class="reference internal" href="../library/mmap.html#module-mmap" title="mmap: Interface to memory-mapped files for Unix and Windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mmap</span></code></a>: An interface to memory-mapped files on both Windows and Unix.  A
file’s contents can be mapped directly into memory, at which point it behaves
like a mutable string, so its contents can be read and modified.  They can even
be passed to functions that expect ordinary strings, such as the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
module. (Contributed by Sam Rushing, with some extensions by A.M. Kuchling.)</li>
<li><code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code>: An interface to the Expat XML parser. (Contributed by Paul
Prescod.)</li>
<li><a class="reference internal" href="../library/robotparser.html#module-robotparser" title="robotparser: Loads a robots.txt file and answers questions about fetchability of other URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">robotparser</span></code></a>: Parse a <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> file, which is used for writing
Web spiders that politely avoid certain areas of a Web site.  The parser accepts
the contents of a <code class="file docutils literal notranslate"><span class="pre">robots.txt</span></code> file, builds a set of rules from it, and
can then answer questions about the fetchability of a given URL.  (Contributed
by Skip Montanaro.)</li>
<li><a class="reference internal" href="../library/tabnanny.html#module-tabnanny" title="tabnanny: Tool for detecting white space related problems in Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tabnanny</span></code></a>: A module/script to  check Python source code for ambiguous
indentation. (Contributed by Tim Peters.)</li>
<li><a class="reference internal" href="../library/userdict.html#module-UserString" title="UserString: Class wrapper for string objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserString</span></code></a>: A base class useful for deriving objects that behave like
strings.</li>
<li><a class="reference internal" href="../library/webbrowser.html#module-webbrowser" title="webbrowser: Easy-to-use controller for Web browsers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">webbrowser</span></code></a>: A module that provides a platform independent way to launch
a web browser on a specific URL. For each platform, various browsers are tried
in a specific order. The user can alter which browser is launched by setting the
<em>BROWSER</em> environment variable.  (Originally inspired by Eric S. Raymond’s patch
to <a class="reference internal" href="../library/urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> which added similar functionality, but the final module comes
from code originally  implemented by Fred Drake as
<code class="file docutils literal notranslate"><span class="pre">Tools/idle/BrowserControl.py</span></code>, and adapted for the standard library by
Fred.)</li>
<li><a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a>: An interface to the Windows registry.  <a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> is an
adaptation of functions that have been part of PythonWin since 1995, but has now
been added to the core  distribution, and enhanced to support Unicode.
<a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> was written by Bill Tutt and Mark Hammond.</li>
<li><a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a>: A module for reading and writing ZIP-format archives.  These
are archives produced by <strong class="program">PKZIP</strong> on DOS/Windows or <strong class="program">zip</strong> on
Unix, not to be confused with <strong class="program">gzip</strong>-format files (which are
supported by the <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module) (Contributed by James C. Ahlstrom.)</li>
<li><a class="reference internal" href="../library/imputil.html#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a>: A module that provides a simpler way for writing customised
import hooks, in comparison to the existing <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> module.  (Implemented
by Greg Stein, with much discussion on python-dev along the way.)</li>
</ul>
</div>
<div class="section" id="idle-improvements">
<h2>IDLE Improvements<a class="headerlink" href="#idle-improvements" title="Permalink to this headline">¶</a></h2>
<p>IDLE is the official Python cross-platform IDE, written using Tkinter. Python
2.0 includes IDLE 0.6, which adds a number of new features and improvements.  A
partial list:</p>
<ul class="simple">
<li>UI improvements and optimizations, especially in the area of syntax
highlighting and auto-indentation.</li>
<li>The class browser now shows more information, such as the top level functions
in a module.</li>
<li>Tab width is now a user settable option. When opening an existing Python file,
IDLE automatically detects the indentation conventions, and adapts.</li>
<li>There is now support for calling browsers on various platforms, used to open
the Python documentation in a browser.</li>
<li>IDLE now has a command line, which is largely similar to  the vanilla Python
interpreter.</li>
<li>Call tips were added in many places.</li>
<li>IDLE can now be installed as a package.</li>
<li>In the editor window, there is now a line/column bar at the bottom.</li>
<li>Three new keystroke commands: Check module (<kbd class="kbd docutils literal notranslate">Alt-F5</kbd>), Import module (<kbd class="kbd docutils literal notranslate">F5</kbd>) and
Run script (<kbd class="kbd docutils literal notranslate">Ctrl-F5</kbd>).</li>
</ul>
</div>
<div class="section" id="deleted-and-deprecated-modules">
<h2>Deleted and Deprecated Modules<a class="headerlink" href="#deleted-and-deprecated-modules" title="Permalink to this headline">¶</a></h2>
<p>A few modules have been dropped because they’re obsolete, or because there are
now better ways to do the same thing.  The <code class="xref py py-mod docutils literal notranslate"><span class="pre">stdwin</span></code> module is gone; it was
for a platform-independent windowing toolkit that’s no longer developed.</p>
<p>A number of modules have been moved to the <code class="file docutils literal notranslate"><span class="pre">lib-old</span></code> subdirectory:
<a class="reference internal" href="../library/functions.html#cmp" title="cmp"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmp</span></code></a>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">cmpcache</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">dircmp</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">dump</span></code>,  <code class="xref py py-mod docutils literal notranslate"><span class="pre">find</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">grep</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">packmail</span></code>,  <code class="xref py py-mod docutils literal notranslate"><span class="pre">poly</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">util</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">whatsound</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">zmod</span></code>.  If you have code which relies on a module  that’s been moved to
<code class="file docutils literal notranslate"><span class="pre">lib-old</span></code>, you can simply add that directory to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>   to get them
back, but you’re encouraged to update any code that uses these modules.</p>
</div>
<div class="section" id="acknowledgements">
<h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The authors would like to thank the following people for offering suggestions on
various drafts of this article: David Bolen, Mark Hammond, Gregg Hauser, Jeremy
Hylton, Fredrik Lundh, Detlef Lannert, Aahz Maruch, Skip Montanaro, Vladimir
Marangozov, Tobias Polzin, Guido van Rossum, Neil Schemenauer, and Russ Schmidt.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.0</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#what-about-python-1-6">What About Python 1.6?</a></li>
<li><a class="reference internal" href="#new-development-process">New Development Process</a></li>
<li><a class="reference internal" href="#unicode">Unicode</a></li>
<li><a class="reference internal" href="#list-comprehensions">List Comprehensions</a></li>
<li><a class="reference internal" href="#augmented-assignment">Augmented Assignment</a></li>
<li><a class="reference internal" href="#string-methods">String Methods</a></li>
<li><a class="reference internal" href="#garbage-collection-of-cycles">Garbage Collection of Cycles</a></li>
<li><a class="reference internal" href="#other-core-changes">Other Core Changes</a><ul>
<li><a class="reference internal" href="#minor-language-changes">Minor Language Changes</a></li>
<li><a class="reference internal" href="#changes-to-built-in-functions">Changes to Built-in Functions</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-2-0">Porting to 2.0</a></li>
<li><a class="reference internal" href="#extending-embedding-changes">Extending/Embedding Changes</a></li>
<li><a class="reference internal" href="#distutils-making-modules-easy-to-install">Distutils: Making Modules Easy to Install</a></li>
<li><a class="reference internal" href="#xml-modules">XML Modules</a><ul>
<li><a class="reference internal" href="#sax2-support">SAX2 Support</a></li>
<li><a class="reference internal" href="#dom-support">DOM Support</a></li>
<li><a class="reference internal" href="#relationship-to-pyxml">Relationship to PyXML</a></li>
</ul>
</li>
<li><a class="reference internal" href="#module-changes">Module changes</a></li>
<li><a class="reference internal" href="#new-modules">New modules</a></li>
<li><a class="reference internal" href="#idle-improvements">IDLE Improvements</a></li>
<li><a class="reference internal" href="#deleted-and-deprecated-modules">Deleted and Deprecated Modules</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.1.html"
                        title="previous chapter">What’s New in Python 2.1</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../tutorial/index.html"
                        title="next chapter">The Python Tutorial</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.0.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../tutorial/index.html" title="The Python Tutorial"
             >next</a> |</li>
        <li class="right" >
          <a href="2.1.html" title="What’s New in Python 2.1"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\l�V�>�>html/whatsnew/2.1.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.1 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.0" href="2.0.html" />
    <link rel="prev" title="What’s New in Python 2.2" href="2.2.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.1.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.0.html" title="What’s New in Python 2.0"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.2.html" title="What’s New in Python 2.2"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-1">
<h1>What’s New in Python 2.1<a class="headerlink" href="#what-s-new-in-python-2-1" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>This article explains the new features in Python 2.1.  While there aren’t as
many changes in 2.1 as there were in Python 2.0, there are still some pleasant
surprises in store.  2.1 is the first release to be steered through the use of
Python Enhancement Proposals, or PEPs, so most of the sizable changes have
accompanying PEPs that provide more complete documentation and a design
rationale for the change.  This article doesn’t attempt to document the new
features completely, but simply provides an overview of the new features for
Python programmers. Refer to the Python 2.1 documentation, or to the specific
PEP, for more details about any new feature that particularly interests you.</p>
<p>One recent goal of the Python development team has been to accelerate the pace
of new releases, with a new release coming every 6 to 9 months. 2.1 is the first
release to come out at this faster pace, with the first alpha appearing in
January, 3 months after the final version of 2.0 was released.</p>
<p>The final release of Python 2.1 was made on April 17, 2001.</p>
</div>
<div class="section" id="pep-227-nested-scopes">
<h2>PEP 227: Nested Scopes<a class="headerlink" href="#pep-227-nested-scopes" title="Permalink to this headline">¶</a></h2>
<p>The largest change in Python 2.1 is to Python’s scoping rules.  In Python 2.0,
at any given time there are at most three namespaces used to look up variable
names: local, module-level, and the built-in namespace.  This often surprised
people because it didn’t match their intuitive expectations.  For example, a
nested recursive function definition doesn’t work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
        <span class="o">...</span>
        <span class="k">return</span> <span class="n">g</span><span class="p">(</span><span class="n">value</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The function <code class="xref py py-func docutils literal notranslate"><span class="pre">g()</span></code> will always raise a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception, because
the binding of the name <code class="docutils literal notranslate"><span class="pre">g</span></code> isn’t in either its local namespace or in the
module-level namespace.  This isn’t much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> statement clumsier, and this was a problem in practice.
In code which uses <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> you can often find local variables being
copied by passing them as the default values of arguments.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">find</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
    <span class="s2">&quot;Return list of any entries equal to &#39;name&#39;&quot;</span>
    <span class="n">L</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">:</span> <span class="n">x</span> <span class="o">==</span> <span class="n">name</span><span class="p">,</span>
               <span class="bp">self</span><span class="o">.</span><span class="n">list_attribute</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>
</pre></div>
</div>
<p>The readability of Python code written in a strongly functional style suffers
greatly as a result.</p>
<p>The most significant change to Python 2.1 is that static scoping has been added
to the language to fix this problem.  As a first effect, the <code class="docutils literal notranslate"><span class="pre">name=name</span></code>
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>, <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>, or <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.</p>
<p>This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.</p>
<p>One side effect of the change is that the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> and
<a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> and <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> expressions with free variables, the compiler
will flag this by raising a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> exception.</p>
<p>To make the preceding explanation a bit clearer, here’s an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="c1"># The next line is a syntax error</span>
    <span class="n">exec</span> <span class="s1">&#39;x=2&#39;</span>
    <span class="k">def</span> <span class="nf">g</span><span class="p">():</span>
        <span class="k">return</span> <span class="n">x</span>
</pre></div>
</div>
<p>Line 4 containing the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement is a syntax error, since
<a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> would define a new local variable named <code class="docutils literal notranslate"><span class="pre">x</span></code> whose value should
be accessed by <code class="xref py py-func docutils literal notranslate"><span class="pre">g()</span></code>.</p>
<p>This shouldn’t be much of a limitation, since <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> is rarely used in
most Python code (and when it is used, it’s often a sign of a poor design
anyway).</p>
<p>Compatibility concerns have led to nested scopes being introduced gradually; in
Python 2.1, they aren’t enabled by default, but can be turned on within a module
by using a future statement as described in PEP 236.  (See the following section
for further discussion of PEP 236.)  In Python 2.2, nested scopes will become
the default and there will be no way to turn them off, but users will have had
all of 2.1’s lifetime to fix any breakage resulting from their introduction.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0227"><strong>PEP 227</strong></a> - Statically Nested Scopes</dt>
<dd>Written and implemented by Jeremy Hylton.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-236-future-directives">
<h2>PEP 236: __future__ Directives<a class="headerlink" href="#pep-236-future-directives" title="Permalink to this headline">¶</a></h2>
<p>The reaction to nested scopes was widespread concern about the dangers of
breaking code with the 2.1 release, and it was strong enough to make the
Pythoneers take a more conservative approach.  This approach consists of
introducing a convention for enabling optional functionality in release N that
will become compulsory in release N+1.</p>
<p>The syntax uses a <code class="docutils literal notranslate"><span class="pre">from...import</span></code> statement using the reserved module name
<a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a>.  Nested scopes can be enabled by the following statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">nested_scopes</span>
</pre></div>
</div>
<p>While it looks like a normal <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, it’s not; there are
strict rules on where such a future statement can be put. They can only be at
the top of a module, and must precede any Python code or regular
<a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements.  This is because such statements can affect how
the Python bytecode compiler parses code and generates bytecode, so they must
precede any statement that will result in bytecodes being produced.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0236"><strong>PEP 236</strong></a> - Back to the <a class="reference internal" href="../library/__future__.html#module-__future__" title="__future__: Future statement definitions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">__future__</span></code></a></dt>
<dd>Written by Tim Peters, and primarily implemented by Jeremy Hylton.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-207-rich-comparisons">
<h2>PEP 207: Rich Comparisons<a class="headerlink" href="#pep-207-rich-comparisons" title="Permalink to this headline">¶</a></h2>
<p>In earlier versions, Python’s support for implementing comparisons on user-defined
classes and extension types was quite simple. Classes could implement a
<a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method that was given two instances of a class, and could only
return 0 if they were equal or +1 or -1 if they weren’t; the method couldn’t
raise an exception or return anything other than a Boolean value.  Users of
Numeric Python often found this model too weak and restrictive, because in the
number-crunching programs that numeric Python is used for, it would be more
useful to be able to perform elementwise comparisons of two matrices, returning
a matrix containing the results of a given comparison for each element.  If the
two matrices are of different sizes, then the compare has to be able to raise an
exception to signal the error.</p>
<p>In Python 2.1, rich comparisons were added in order to support this need.
Python classes can now individually overload each of the <code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">==</span></code>, and <code class="docutils literal notranslate"><span class="pre">!=</span></code> operations.  The new magic method names are:</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Method name</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&lt;</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&lt;=</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">&gt;</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">&gt;=</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a></td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">==</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a></td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">!=</span></code></td>
<td><a class="reference internal" href="../reference/datamodel.html#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a></td>
</tr>
</tbody>
</table>
<p>(The magic methods are named after the corresponding Fortran operators <code class="docutils literal notranslate"><span class="pre">.LT.</span></code>.
<code class="docutils literal notranslate"><span class="pre">.LE.</span></code>, &amp;c.  Numeric programmers are almost certainly quite familiar with
these names and will find them easy to remember.)</p>
<p>Each of these magic methods is of the form <code class="docutils literal notranslate"><span class="pre">method(self,</span> <span class="pre">other)</span></code>, where
<code class="docutils literal notranslate"><span class="pre">self</span></code> will be the object on the left-hand side of the operator, while
<code class="docutils literal notranslate"><span class="pre">other</span></code> will be the object on the right-hand side.  For example, the
expression <code class="docutils literal notranslate"><span class="pre">A</span> <span class="pre">&lt;</span> <span class="pre">B</span></code> will cause <code class="docutils literal notranslate"><span class="pre">A.__lt__(B)</span></code> to be called.</p>
<p>Each of these magic methods can return anything at all: a Boolean, a matrix, a
list, or any other Python object.  Alternatively they can raise an exception if
the comparison is impossible, inconsistent, or otherwise meaningless.</p>
<p>The built-in <code class="docutils literal notranslate"><span class="pre">cmp(A,B)</span></code> function can use the rich comparison machinery,
and now accepts an optional argument specifying which comparison operation to
use; this is given as one of the strings <code class="docutils literal notranslate"><span class="pre">&quot;&lt;&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;&lt;=&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;&gt;&quot;</span></code>, <code class="docutils literal notranslate"><span class="pre">&quot;&gt;=&quot;</span></code>,
<code class="docutils literal notranslate"><span class="pre">&quot;==&quot;</span></code>, or <code class="docutils literal notranslate"><span class="pre">&quot;!=&quot;</span></code>.  If called without the optional third argument,
<a class="reference internal" href="../library/functions.html#cmp" title="cmp"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp()</span></code></a> will only return -1, 0, or +1 as in previous versions of Python;
otherwise it will call the appropriate method and can return any Python object.</p>
<p>There are also corresponding changes of interest to C programmers; there’s a new
slot <code class="docutils literal notranslate"><span class="pre">tp_richcmp</span></code> in type objects and an API for performing a given rich
comparison.  I won’t cover the C API here, but will refer you to PEP 207, or to
2.1’s C API documentation, for the full list of related functions.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0207"><strong>PEP 207</strong></a> - Rich Comparisons</dt>
<dd>Written by Guido van Rossum, heavily based on earlier work by David Ascher, and
implemented by Guido van Rossum.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-230-warning-framework">
<h2>PEP 230: Warning Framework<a class="headerlink" href="#pep-230-warning-framework" title="Permalink to this headline">¶</a></h2>
<p>Over its 10 years of existence, Python has accumulated a certain number of
obsolete modules and features along the way.  It’s difficult to know when a
feature is safe to remove, since there’s no way of knowing how much code uses it
— perhaps no programs depend on the feature, or perhaps many do.  To enable
removing old features in a more structured way, a warning framework was added.
When the Python developers want to get rid of a feature, it will first trigger a
warning in the next version of Python.  The following Python version can then
drop the feature, and users will have had a full release cycle to remove uses of
the old feature.</p>
<p>Python 2.1 adds the warning framework to be used in this scheme.  It adds a
<a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module that provide functions to issue warnings, and to filter
out warnings that you don’t want to be displayed. Third-party modules can also
use this framework to deprecate old features that they no longer wish to
support.</p>
<p>For example, in Python 2.1 the <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module is deprecated, so importing
it causes a warning to be printed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">regex</span>
<span class="go">__main__:1: DeprecationWarning: the regex module</span>
<span class="go">         is deprecated; please use the re module</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Warnings can be issued by calling the <a class="reference internal" href="../library/warnings.html#warnings.warn" title="warnings.warn"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.warn()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span><span class="s2">&quot;feature X no longer supported&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>The first parameter is the warning message; an additional optional parameters
can be used to specify a particular warning category.</p>
<p>Filters can be added to disable certain warnings; a regular expression pattern
can be applied to the message or to the module name in order to suppress a
warning.  For example, you may have a program that uses the <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module
and not want to spare the time to convert it to use the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module right
now.  The warning can be suppressed by calling</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">warnings</span>
<span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="n">action</span> <span class="o">=</span> <span class="s1">&#39;ignore&#39;</span><span class="p">,</span>
                        <span class="n">message</span><span class="o">=</span><span class="s1">&#39;.*regex module is deprecated&#39;</span><span class="p">,</span>
                        <span class="n">category</span><span class="o">=</span><span class="ne">DeprecationWarning</span><span class="p">,</span>
                        <span class="n">module</span> <span class="o">=</span> <span class="s1">&#39;__main__&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This adds a filter that will apply only to warnings of the class
<code class="xref py py-class docutils literal notranslate"><span class="pre">DeprecationWarning</span></code> triggered in the <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> module, and applies
a regular expression to only match the message about the <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> module
being deprecated, and will cause such warnings to be ignored.  Warnings can also
be printed only once, printed every time the offending code is executed, or
turned into exceptions that will cause the program to stop (unless the
exceptions are caught in the usual way, of course).</p>
<p>Functions were also added to Python’s C API for issuing warnings; refer to PEP
230 or to Python’s API documentation for the details.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0005"><strong>PEP 5</strong></a> - Guidelines for Language Evolution</dt>
<dd>Written by Paul Prescod, to specify procedures to be followed when removing old
features from Python.  The policy described in this PEP hasn’t been officially
adopted, but the eventual policy probably won’t be too different from Prescod’s
proposal.</dd>
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0230"><strong>PEP 230</strong></a> - Warning Framework</dt>
<dd>Written and implemented by Guido van Rossum.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-229-new-build-system">
<h2>PEP 229: New Build System<a class="headerlink" href="#pep-229-new-build-system" title="Permalink to this headline">¶</a></h2>
<p>When compiling Python, the user had to go in and edit the <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code>
file in order to enable various additional modules; the default set is
relatively small and limited to modules that compile on most Unix platforms.
This means that on Unix platforms with many more features, most notably Linux,
Python installations often don’t contain all useful modules they could.</p>
<p>Python 2.0 added the Distutils, a set of modules for distributing and installing
extensions.  In Python 2.1, the Distutils are used to compile much of the
standard library of extension modules, autodetecting which ones are supported on
the current machine.  It’s hoped that this will make Python installations easier
and more featureful.</p>
<p>Instead of having to edit the <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code> file in order to enable
modules, a <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script in the top directory of the Python source
distribution is run at build time, and attempts to discover which modules can be
enabled by examining the modules and header files on the system.  If a module is
configured in <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code>, the <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> script won’t attempt
to compile that module and will defer to the <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code> file’s
contents.  This provides a way to specific any strange command-line flags or
libraries that are required for a specific platform.</p>
<p>In another far-reaching change to the build mechanism, Neil Schemenauer
restructured things so Python now uses a single makefile that isn’t recursive,
instead of makefiles in the top directory and in each of the <code class="file docutils literal notranslate"><span class="pre">Python/</span></code>,
<code class="file docutils literal notranslate"><span class="pre">Parser/</span></code>, <code class="file docutils literal notranslate"><span class="pre">Objects/</span></code>, and <code class="file docutils literal notranslate"><span class="pre">Modules/</span></code> subdirectories.  This
makes building Python faster and also makes hacking the Makefiles clearer and
simpler.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0229"><strong>PEP 229</strong></a> - Using Distutils to Build Python</dt>
<dd>Written and implemented by A.M. Kuchling.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-205-weak-references">
<h2>PEP 205: Weak References<a class="headerlink" href="#pep-205-weak-references" title="Permalink to this headline">¶</a></h2>
<p>Weak references, available through the <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module, are a minor but
useful new data type in the Python programmer’s toolbox.</p>
<p>Storing a reference to an object (say, in a dictionary or a list) has the side
effect of keeping that object alive forever.  There are a few specific cases
where this behaviour is undesirable, object caches being the most common one,
and another being circular references in data structures such as trees.</p>
<p>For example, consider a memoizing function that caches the results of another
function <code class="docutils literal notranslate"><span class="pre">f(x)</span></code> by storing the function’s argument and its result in a
dictionary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">_cache</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">def</span> <span class="nf">memoize</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">_cache</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">_cache</span><span class="p">[</span><span class="n">x</span><span class="p">]</span>

    <span class="n">retval</span> <span class="o">=</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>

    <span class="c1"># Cache the returned object</span>
    <span class="n">_cache</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">retval</span>

    <span class="k">return</span> <span class="n">retval</span>
</pre></div>
</div>
<p>This version works for simple things such as integers, but it has a side effect;
the <code class="docutils literal notranslate"><span class="pre">_cache</span></code> dictionary holds a reference to the return values, so they’ll
never be deallocated until the Python process exits and cleans up This isn’t
very noticeable for integers, but if <code class="xref py py-func docutils literal notranslate"><span class="pre">f()</span></code> returns an object, or a data
structure that takes up a lot of memory, this can be a problem.</p>
<p>Weak references provide a way to implement a cache that won’t keep objects alive
beyond their time.  If an object is only accessible through weak references, the
object will be deallocated and the weak references will now indicate that the
object it referred to no longer exists.  A weak reference to an object <em>obj</em> is
created by calling <code class="docutils literal notranslate"><span class="pre">wr</span> <span class="pre">=</span> <span class="pre">weakref.ref(obj)</span></code>.  The object being referred to is
returned by calling the weak reference as if it were a function: <code class="docutils literal notranslate"><span class="pre">wr()</span></code>.  It
will return the referenced object, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the object no longer exists.</p>
<p>This makes it possible to write a <code class="xref py py-func docutils literal notranslate"><span class="pre">memoize()</span></code> function whose cache doesn’t
keep objects alive, by storing weak references in the cache.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">_cache</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">def</span> <span class="nf">memoize</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">_cache</span><span class="o">.</span><span class="n">has_key</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
        <span class="n">obj</span> <span class="o">=</span> <span class="n">_cache</span><span class="p">[</span><span class="n">x</span><span class="p">]()</span>
        <span class="c1"># If weak reference object still exists,</span>
        <span class="c1"># return it</span>
        <span class="k">if</span> <span class="n">obj</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span> <span class="k">return</span> <span class="n">obj</span>

    <span class="n">retval</span> <span class="o">=</span> <span class="n">f</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>

    <span class="c1"># Cache a weak reference</span>
    <span class="n">_cache</span><span class="p">[</span><span class="n">x</span><span class="p">]</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">ref</span><span class="p">(</span><span class="n">retval</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">retval</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module also allows creating proxy objects which behave like
weak references — an object referenced only by proxy objects is deallocated –
but instead of requiring an explicit call to retrieve the object, the proxy
transparently forwards all operations to the object as long as the object still
exists.  If the object is deallocated, attempting to use a proxy will cause a
<a class="reference internal" href="../library/weakref.html#weakref.ReferenceError" title="weakref.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">weakref.ReferenceError</span></code></a> exception to be raised.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">proxy</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">proxy</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
<span class="n">proxy</span><span class="o">.</span><span class="n">attr</span>   <span class="c1"># Equivalent to obj.attr</span>
<span class="n">proxy</span><span class="o">.</span><span class="n">meth</span><span class="p">()</span> <span class="c1"># Equivalent to obj.meth()</span>
<span class="k">del</span> <span class="n">obj</span>
<span class="n">proxy</span><span class="o">.</span><span class="n">attr</span>   <span class="c1"># raises weakref.ReferenceError</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0205"><strong>PEP 205</strong></a> - Weak References</dt>
<dd>Written and implemented by Fred L. Drake, Jr.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-232-function-attributes">
<h2>PEP 232: Function Attributes<a class="headerlink" href="#pep-232-function-attributes" title="Permalink to this headline">¶</a></h2>
<p>In Python 2.1, functions can now have arbitrary information attached to them.
People were often using docstrings to hold information about functions and
methods, because the <code class="docutils literal notranslate"><span class="pre">__doc__</span></code> attribute was the only way of attaching any
information to a function.  For example, in the Zope Web application server,
functions are marked as safe for public access by having a docstring, and in
John Aycock’s SPARK parsing framework, docstrings hold parts of the BNF grammar
to be parsed.  This overloading is unfortunate, since docstrings are really
intended to hold a function’s documentation; for example, it means you can’t
properly document functions intended for private use in Zope.</p>
<p>Arbitrary attributes can now be set and retrieved on functions using the regular
Python syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">pass</span>

<span class="n">f</span><span class="o">.</span><span class="n">publish</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">f</span><span class="o">.</span><span class="n">secure</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">f</span><span class="o">.</span><span class="n">grammar</span> <span class="o">=</span> <span class="s2">&quot;A ::= B (C D)*&quot;</span>
</pre></div>
</div>
<p>The dictionary containing attributes can be accessed as the function’s
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. Unlike the <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute of class instances, in
functions you can actually assign a new dictionary to <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>, though
the new value is restricted to a regular Python dictionary; you <em>can’t</em> be
tricky and set it to a <a class="reference internal" href="../library/userdict.html#UserDict.UserDict" title="UserDict.UserDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserDict</span></code></a> instance, or any other random object
that behaves like a mapping.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0232"><strong>PEP 232</strong></a> - Function Attributes</dt>
<dd>Written and implemented by Barry Warsaw.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-235-importing-modules-on-case-insensitive-platforms">
<h2>PEP 235: Importing Modules on Case-Insensitive Platforms<a class="headerlink" href="#pep-235-importing-modules-on-case-insensitive-platforms" title="Permalink to this headline">¶</a></h2>
<p>Some operating systems have filesystems that are case-insensitive, MacOS and
Windows being the primary examples; on these systems, it’s impossible to
distinguish the filenames <code class="docutils literal notranslate"><span class="pre">FILE.PY</span></code> and <code class="docutils literal notranslate"><span class="pre">file.py</span></code>, even though they do store
the file’s name  in its original case (they’re case-preserving, too).</p>
<p>In Python 2.1, the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement will work to simulate case-sensitivity
on case-insensitive platforms.  Python will now search for the first
case-sensitive match by default, raising an <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> if no such file
is found, so <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">file</span></code> will not import a module named <code class="docutils literal notranslate"><span class="pre">FILE.PY</span></code>.
Case-insensitive matching can be requested by setting the <span class="target" id="index-8"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONCASEOK"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONCASEOK</span></code></a>
environment variable before starting the Python interpreter.</p>
</div>
<div class="section" id="pep-217-interactive-display-hook">
<h2>PEP 217: Interactive Display Hook<a class="headerlink" href="#pep-217-interactive-display-hook" title="Permalink to this headline">¶</a></h2>
<p>When using the Python interpreter interactively, the output of commands is
displayed using the built-in <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function. In Python 2.1, the variable
<a class="reference internal" href="../library/sys.html#sys.displayhook" title="sys.displayhook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.displayhook()</span></code></a> can be set to a callable object which will be called
instead of <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>. For example, you can set it to a special
pretty-printing function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Create a recursive data structure</span>
<span class="gp">... </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="c1"># Show Python&#39;s default output</span>
<span class="go">[1, 2, 3, [...]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Use pprint.pprint() as the display function</span>
<span class="gp">... </span><span class="kn">import</span> <span class="nn">sys</span><span class="o">,</span> <span class="nn">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">displayhook</span> <span class="o">=</span> <span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[1, 2, 3,  &lt;Recursion on list with id=135143996&gt;]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0217"><strong>PEP 217</strong></a> - Display Hook for Interactive Use</dt>
<dd>Written and implemented by Moshe Zadka.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-208-new-coercion-model">
<h2>PEP 208: New Coercion Model<a class="headerlink" href="#pep-208-new-coercion-model" title="Permalink to this headline">¶</a></h2>
<p>How numeric coercion is done at the C level was significantly modified.  This
will only affect the authors of C extensions to Python, allowing them more
flexibility in writing extension types that support numeric operations.</p>
<p>Extension types can now set the type flag <code class="docutils literal notranslate"><span class="pre">Py_TPFLAGS_CHECKTYPES</span></code> in their
<code class="docutils literal notranslate"><span class="pre">PyTypeObject</span></code> structure to indicate that they support the new coercion model.
In such extension types, the numeric slot functions can no longer assume that
they’ll be passed two arguments of the same type; instead they may be passed two
arguments of differing types, and can then perform their own internal coercion.
If the slot function is passed a type it can’t handle, it can indicate the
failure by returning a reference to the <code class="docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code> singleton value.
The numeric functions of the other type will then be tried, and perhaps they can
handle the operation; if the other type also returns <code class="docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code>, then
a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> will be raised.  Numeric methods written in Python can also
return <code class="docutils literal notranslate"><span class="pre">Py_NotImplemented</span></code>, causing the interpreter to act as if the method
did not exist (perhaps raising a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>, perhaps trying another
object’s numeric methods).</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0208"><strong>PEP 208</strong></a> - Reworking the Coercion Model</dt>
<dd>Written and implemented by Neil Schemenauer, heavily based upon earlier work by
Marc-André Lemburg.  Read this to understand the fine points of how numeric
operations will now be processed at the C level.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-241-metadata-in-python-packages">
<h2>PEP 241: Metadata in Python Packages<a class="headerlink" href="#pep-241-metadata-in-python-packages" title="Permalink to this headline">¶</a></h2>
<p>A common complaint from Python users is that there’s no single catalog of all
the Python modules in existence.  T. Middleton’s Vaults of Parnassus at
<a class="reference external" href="http://www.vex.net/parnassus/">http://www.vex.net/parnassus/</a> are the largest catalog of Python modules, but
registering software at the Vaults is optional, and many people don’t bother.</p>
<p>As a first small step toward fixing the problem, Python software packaged using
the Distutils <strong class="command">sdist</strong> command will include a file named
<code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> containing information about the package such as its name,
version, and author (metadata, in cataloguing terminology).  PEP 241 contains
the full list of fields that can be present in the <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> file.  As
people began to package their software using Python 2.1, more and more packages
will include metadata, making it possible to build automated cataloguing systems
and experiment with them.  With the result experience, perhaps it’ll be possible
to design a really good catalog and then build support for it into Python 2.2.
For example, the Distutils <strong class="command">sdist</strong> and <strong class="command">bdist_*</strong> commands
could support an <code class="docutils literal notranslate"><span class="pre">upload</span></code> option that would automatically upload your
package to a catalog server.</p>
<p>You can start creating packages containing <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> even if you’re not
using Python 2.1, since a new release of the Distutils will be made for users of
earlier Python versions.  Version 1.0.2 of the Distutils includes the changes
described in PEP 241, as well as various bugfixes and enhancements.  It will be
available from the Distutils SIG at <a class="reference external" href="https://www.python.org/community/sigs/current/distutils-sig/">https://www.python.org/community/sigs/current/distutils-sig/</a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0241"><strong>PEP 241</strong></a> - Metadata for Python Software Packages</dt>
<dd>Written and implemented by A.M. Kuchling.</dd>
<dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0243"><strong>PEP 243</strong></a> - Module Repository Upload Mechanism</dt>
<dd>Written by Sean Reifschneider, this draft PEP describes a proposed mechanism for
uploading  Python packages to a central server.</dd>
</dl>
</div>
</div>
<div class="section" id="new-and-improved-modules">
<h2>New and Improved Modules<a class="headerlink" href="#new-and-improved-modules" title="Permalink to this headline">¶</a></h2>
<ul>
<li><p class="first">Ka-Ping Yee contributed two new modules: <code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect.py</span></code>, a module for
getting information about live Python code, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc.py</span></code>, a module for
interactively converting docstrings to HTML or text.  As a bonus,
<code class="file docutils literal notranslate"><span class="pre">Tools/scripts/pydoc</span></code>, which is now automatically installed, uses
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc.py</span></code> to display documentation given a Python module, package, or
class name.  For example, <code class="docutils literal notranslate"><span class="pre">pydoc</span> <span class="pre">xml.dom</span></code> displays the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Python</span> <span class="n">Library</span> <span class="n">Documentation</span><span class="p">:</span> <span class="n">package</span> <span class="n">xml</span><span class="o">.</span><span class="n">dom</span> <span class="ow">in</span> <span class="n">xml</span>

<span class="n">NAME</span>
    <span class="n">xml</span><span class="o">.</span><span class="n">dom</span> <span class="o">-</span> <span class="n">W3C</span> <span class="n">Document</span> <span class="n">Object</span> <span class="n">Model</span> <span class="n">implementation</span> <span class="k">for</span> <span class="n">Python</span><span class="o">.</span>

<span class="n">FILE</span>
    <span class="o">/</span><span class="n">usr</span><span class="o">/</span><span class="n">local</span><span class="o">/</span><span class="n">lib</span><span class="o">/</span><span class="n">python2</span><span class="o">.</span><span class="mi">1</span><span class="o">/</span><span class="n">xml</span><span class="o">/</span><span class="n">dom</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">pyc</span>

<span class="n">DESCRIPTION</span>
    <span class="n">The</span> <span class="n">Python</span> <span class="n">mapping</span> <span class="n">of</span> <span class="n">the</span> <span class="n">Document</span> <span class="n">Object</span> <span class="n">Model</span> <span class="ow">is</span> <span class="n">documented</span> <span class="ow">in</span> <span class="n">the</span>
    <span class="n">Python</span> <span class="n">Library</span> <span class="n">Reference</span> <span class="ow">in</span> <span class="n">the</span> <span class="n">section</span> <span class="n">on</span> <span class="n">the</span> <span class="n">xml</span><span class="o">.</span><span class="n">dom</span> <span class="n">package</span><span class="o">.</span>

    <span class="n">This</span> <span class="n">package</span> <span class="n">contains</span> <span class="n">the</span> <span class="n">following</span> <span class="n">modules</span><span class="p">:</span>
      <span class="o">...</span>
</pre></div>
</div>
<p><code class="file docutils literal notranslate"><span class="pre">pydoc</span></code> also includes a Tk-based interactive help browser.   <code class="file docutils literal notranslate"><span class="pre">pydoc</span></code>
quickly becomes addictive; try it out!</p>
</li>
<li><p class="first">Two different modules for unit testing were added to the standard library.
The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module, contributed by Tim Peters, provides a testing
framework based on running embedded examples in docstrings and comparing the
results against the expected output.  PyUnit, contributed by Steve Purcell, is a
unit testing framework inspired by JUnit, which was in turn an adaptation of
Kent Beck’s Smalltalk testing framework.  See <a class="reference external" href="http://pyunit.sourceforge.net/">http://pyunit.sourceforge.net/</a> for
more information about PyUnit.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module contains a class, <code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code>, which
compares two sequences and computes the changes required to transform one
sequence into the other.  For example, this module can be used to write a tool
similar to the Unix <strong class="program">diff</strong> program, and in fact the sample program
<code class="file docutils literal notranslate"><span class="pre">Tools/scripts/ndiff.py</span></code> demonstrates how to write such a script.</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/curses.panel.html#module-curses.panel" title="curses.panel: A panel stack extension that adds depth to  curses windows."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.panel</span></code></a>, a wrapper for the panel library, part of ncurses and of
SYSV curses, was contributed by Thomas Gellekum.  The panel library provides
windows with the additional feature of depth. Windows can be moved higher or
lower in the depth ordering, and the panel library figures out where panels
overlap and which sections are visible.</p>
</li>
<li><p class="first">The PyXML package has gone through a few releases since Python 2.0, and Python
2.1 includes an updated version of the <a class="reference internal" href="../library/xml.html#module-xml" title="xml: Package containing XML processing modules"><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml</span></code></a> package.  Some of the
noteworthy changes include support for Expat 1.2 and later versions, the ability
for Expat parsers to handle files in any encoding supported by Python, and
various bugfixes for SAX, DOM, and the <code class="xref py py-mod docutils literal notranslate"><span class="pre">minidom</span></code> module.</p>
</li>
<li><p class="first">Ping also contributed another hook for handling uncaught exceptions.
<a class="reference internal" href="../library/sys.html#sys.excepthook" title="sys.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.excepthook()</span></code></a> can be set to a callable object.  When an exception isn’t
caught by any <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks, the exception will be
passed to <a class="reference internal" href="../library/sys.html#sys.excepthook" title="sys.excepthook"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.excepthook()</span></code></a>, which can then do whatever it likes.  At the
Ninth Python Conference, Ping demonstrated an application for this hook:
printing an extended traceback that not only lists the stack frames, but also
lists the function arguments and the local variables for each frame.</p>
</li>
<li><p class="first">Various functions in the <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module, such as <code class="xref py py-func docutils literal notranslate"><span class="pre">asctime()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code>, require a floating point argument containing the time in
seconds since the epoch.  The most common use of these functions is to work with
the current time, so the floating point argument has been made optional; when a
value isn’t provided, the current time will be used.  For example, log file
entries usually need a string containing the current time; in Python 2.1,
<code class="docutils literal notranslate"><span class="pre">time.asctime()</span></code> can be used, instead of the lengthier
<code class="docutils literal notranslate"><span class="pre">time.asctime(time.localtime(time.time()))</span></code> that was previously required.</p>
<p>This change was proposed and implemented by Thomas Wouters.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> module now defaults to retrieving files in passive mode,
because passive mode is more likely to work from behind a firewall.  This
request came from the Debian bug tracking system, since other Debian packages
use <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> to retrieve files and then don’t work from behind a firewall.
It’s deemed unlikely that this will cause problems for anyone, because Netscape
defaults to passive mode and few people complain, but if passive mode is
unsuitable for your application or network setup, call <code class="docutils literal notranslate"><span class="pre">set_pasv(0)</span></code> on
FTP objects to disable passive mode.</p>
</li>
<li><p class="first">Support for raw socket access has been added to the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module,
contributed by Grant Edwards.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module now contains a simple interactive statistics browser
for displaying timing profiles for Python programs, invoked when the module is
run as a script.  Contributed by  Eric S. Raymond.</p>
</li>
<li><p class="first">A new implementation-dependent function, <code class="docutils literal notranslate"><span class="pre">sys._getframe([depth])</span></code>, has
been added to return a given frame object from the current call stack.
<a class="reference internal" href="../library/sys.html#sys._getframe" title="sys._getframe"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys._getframe()</span></code></a> returns the frame at the top of the call stack;  if the
optional integer argument <em>depth</em> is supplied, the function returns the frame
that is <em>depth</em> calls below the top of the stack.  For example,
<code class="docutils literal notranslate"><span class="pre">sys._getframe(1)</span></code> returns the caller’s frame object.</p>
<p>This function is only present in CPython, not in Jython or the .NET
implementation.  Use it for debugging, and resist the temptation to put it into
production code.</p>
</li>
</ul>
</div>
<div class="section" id="other-changes-and-fixes">
<h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<p>There were relatively few smaller changes made in Python 2.1 due to the shorter
release cycle.  A search through the CVS change logs turns up 117 patches
applied, and 136 bugs fixed; both figures are likely to be underestimates.  Some
of the more notable changes are:</p>
<ul>
<li><p class="first">A specialized object allocator is now optionally available, that should be
faster than the system <code class="xref py py-func docutils literal notranslate"><span class="pre">malloc()</span></code> and have less memory overhead.  The
allocator uses C’s <code class="xref py py-func docutils literal notranslate"><span class="pre">malloc()</span></code> function to get large pools of memory, and
then fulfills smaller memory requests from these pools.  It can be enabled by
providing the <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-pymalloc</span></code> option to the <strong class="program">configure</strong>
script; see <code class="file docutils literal notranslate"><span class="pre">Objects/obmalloc.c</span></code> for the implementation details.</p>
<p>Authors of C extension modules should test their code with the object allocator
enabled, because some incorrect code may break, causing core dumps at runtime.
There are a bunch of memory allocation functions in Python’s C API that have
previously been just aliases for the C library’s <code class="xref py py-func docutils literal notranslate"><span class="pre">malloc()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">free()</span></code>, meaning that if you accidentally called mismatched functions, the
error wouldn’t be noticeable.  When the object allocator is enabled, these
functions aren’t aliases of <code class="xref py py-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">free()</span></code> any more, and
calling the wrong function to free memory will get you a core dump.  For
example, if memory was allocated using <code class="xref py py-func docutils literal notranslate"><span class="pre">PyMem_New()</span></code>, it has to be freed
using <code class="xref py py-func docutils literal notranslate"><span class="pre">PyMem_Del()</span></code>, not <code class="xref py py-func docutils literal notranslate"><span class="pre">free()</span></code>.  A few modules included with Python
fell afoul of this and had to be fixed; doubtless there are more third-party
modules that will have the same problem.</p>
<p>The object allocator was contributed by Vladimir Marangozov.</p>
</li>
<li><p class="first">The speed of line-oriented file I/O has been improved because people often
complain about its lack of speed, and because it’s often been used as a naïve
benchmark.  The <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method of file objects has therefore been
rewritten to be much faster.  The exact amount of the speedup will vary from
platform to platform depending on how slow the C library’s <code class="xref py py-func docutils literal notranslate"><span class="pre">getc()</span></code> was, but
is around 66%, and potentially much faster on some particular operating systems.
Tim Peters did much of the benchmarking and coding for this change, motivated by
a discussion in comp.lang.python.</p>
<p>A new module and method for file objects was also added, contributed by Jeff
Epler. The new method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">xreadlines()</span></code>, is similar to the existing
<a class="reference internal" href="../library/functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> built-in.  <code class="xref py py-func docutils literal notranslate"><span class="pre">xreadlines()</span></code> returns an opaque sequence object
that only supports being iterated over, reading a line on every iteration but
not reading the entire file into memory as the existing <code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code> method
does. You’d use it like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdin</span><span class="o">.</span><span class="n">xreadlines</span><span class="p">():</span>
    <span class="c1"># ... do something for each line ...</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>For a fuller discussion of the line I/O changes, see the python-dev summary for
January 1–15, 2001 at <a class="reference external" href="https://mail.python.org/pipermail/python-dev/2001-January/">https://mail.python.org/pipermail/python-dev/2001-January/</a>.</p>
</li>
<li><p class="first">A new method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code>, was added to dictionaries to enable
destructively iterating through the contents of a dictionary; this can be faster
for large dictionaries because there’s no need to construct a list containing
all the keys or values. <code class="docutils literal notranslate"><span class="pre">D.popitem()</span></code> removes a random <code class="docutils literal notranslate"><span class="pre">(key,</span> <span class="pre">value)</span></code> pair
from the dictionary <code class="docutils literal notranslate"><span class="pre">D</span></code> and returns it as a 2-tuple.  This was implemented
mostly by Tim Peters and Guido van Rossum, after a suggestion and preliminary
patch by Moshe Zadka.</p>
</li>
<li><p class="first">Modules can now control which names are imported when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code>
is used, by defining an <code class="docutils literal notranslate"><span class="pre">__all__</span></code> attribute containing a list of names that
will be imported.  One common complaint is that if the module imports other
modules such as <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> or <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a>, <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> will add
them to the importing module’s namespace.  To fix this, simply list the public
names in <code class="docutils literal notranslate"><span class="pre">__all__</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># List public names</span>
<span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Database&#39;</span><span class="p">,</span> <span class="s1">&#39;open&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>A stricter version of this patch was first suggested and implemented by Ben
Wolfson, but after some python-dev discussion, a weaker final version was
checked in.</p>
</li>
<li><p class="first">Applying <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> to strings previously used octal escapes for
non-printable characters; for example, a newline was <code class="docutils literal notranslate"><span class="pre">'\012'</span></code>.  This was a
vestigial trace of Python’s C ancestry, but today octal is of very little
practical use.  Ka-Ping Yee suggested using hex escapes instead of octal ones,
and using the <code class="docutils literal notranslate"><span class="pre">\n</span></code>, <code class="docutils literal notranslate"><span class="pre">\t</span></code>, <code class="docutils literal notranslate"><span class="pre">\r</span></code> escapes for the appropriate characters,
and implemented this new formatting.</p>
</li>
<li><p class="first">Syntax errors detected at compile-time can now raise exceptions containing the
filename and line number of the error, a pleasant side effect of the compiler
reorganization done by Jeremy Hylton.</p>
</li>
<li><p class="first">C extensions which import other modules have been changed to use
<code class="xref py py-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code>, which means that they will use any import hooks
that have been installed.  This is also encouraged for third-party extensions
that need to import some other module from C code.</p>
</li>
<li><p class="first">The size of the Unicode character database was shrunk by another 340K thanks
to Fredrik Lundh.</p>
</li>
<li><p class="first">Some new ports were contributed: MacOS X (by Steven Majewski), Cygwin (by
Jason Tishler); RISCOS (by Dietmar Schwertberger); Unixware 7  (by Billy G.
Allie).</p>
</li>
</ul>
<p>And there’s the usual list of minor bugfixes, minor memory leaks, docstring
edits, and other tweaks, too lengthy to be worth itemizing; see the CVS logs for
the full details if you want them.</p>
</div>
<div class="section" id="acknowledgements">
<h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions on
various drafts of this article: Graeme Cross, David Goodger, Jay Graves, Michael
Hudson, Marc-André Lemburg, Fredrik Lundh, Neil Schemenauer, Thomas Wouters.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.1</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li><a class="reference internal" href="#pep-236-future-directives">PEP 236: __future__ Directives</a></li>
<li><a class="reference internal" href="#pep-207-rich-comparisons">PEP 207: Rich Comparisons</a></li>
<li><a class="reference internal" href="#pep-230-warning-framework">PEP 230: Warning Framework</a></li>
<li><a class="reference internal" href="#pep-229-new-build-system">PEP 229: New Build System</a></li>
<li><a class="reference internal" href="#pep-205-weak-references">PEP 205: Weak References</a></li>
<li><a class="reference internal" href="#pep-232-function-attributes">PEP 232: Function Attributes</a></li>
<li><a class="reference internal" href="#pep-235-importing-modules-on-case-insensitive-platforms">PEP 235: Importing Modules on Case-Insensitive Platforms</a></li>
<li><a class="reference internal" href="#pep-217-interactive-display-hook">PEP 217: Interactive Display Hook</a></li>
<li><a class="reference internal" href="#pep-208-new-coercion-model">PEP 208: New Coercion Model</a></li>
<li><a class="reference internal" href="#pep-241-metadata-in-python-packages">PEP 241: Metadata in Python Packages</a></li>
<li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a></li>
<li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.2.html"
                        title="previous chapter">What’s New in Python 2.2</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.0.html"
                        title="next chapter">What’s New in Python 2.0</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.1.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.0.html" title="What’s New in Python 2.0"
             >next</a> |</li>
        <li class="right" >
          <a href="2.2.html" title="What’s New in Python 2.2"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�p.�l(l(html/whatsnew/2.2.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.2 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.1" href="2.1.html" />
    <link rel="prev" title="What’s New in Python 2.3" href="2.3.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.2.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.1.html" title="What’s New in Python 2.1"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.3.html" title="What’s New in Python 2.3"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-2">
<h1>What’s New in Python 2.2<a class="headerlink" href="#what-s-new-in-python-2-2" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<div class="section" id="introduction">
<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>This article explains the new features in Python 2.2.2, released on October 14,
2002.  Python 2.2.2 is a bugfix release of Python 2.2, originally released on
December 21, 2001.</p>
<p>Python 2.2 can be thought of as the “cleanup release”.  There are some features
such as generators and iterators that are completely new, but most of the
changes, significant and far-reaching though they may be, are aimed at cleaning
up irregularities and dark corners of the language design.</p>
<p>This article doesn’t attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.2, such as the <a class="reference external" href="https://docs.python.org/2.2/lib/lib.html">Python Library
Reference</a> and the <a class="reference external" href="https://docs.python.org/2.2/ref/ref.html">Python
Reference Manual</a>.  If you want to
understand the complete implementation and design rationale for a change, refer
to the PEP for a particular new feature.</p>
</div>
<div class="section" id="peps-252-and-253-type-and-class-changes">
<h2>PEPs 252 and 253: Type and Class Changes<a class="headerlink" href="#peps-252-and-253-type-and-class-changes" title="Permalink to this headline">¶</a></h2>
<p>The largest and most far-reaching changes in Python 2.2 are to Python’s model of
objects and classes.  The changes should be backward compatible, so it’s likely
that your code will continue to run unchanged, but the changes provide some
amazing new capabilities. Before beginning this, the longest and most
complicated section of this article, I’ll provide an overview of the changes and
offer some comments.</p>
<p>A long time ago I wrote a Web page listing flaws in Python’s design.  One of the
most significant flaws was that it’s impossible to subclass Python types
implemented in C.  In particular, it’s not possible to subclass built-in types,
so you can’t just subclass, say, lists in order to add a single useful method to
them. The <a class="reference internal" href="../library/userdict.html#module-UserList" title="UserList: Class wrapper for list objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserList</span></code></a> module provides a class that supports all of the
methods of lists and that can be subclassed further, but there’s lots of C code
that expects a regular Python list and won’t accept a <a class="reference internal" href="../library/userdict.html#UserList.UserList" title="UserList.UserList"><code class="xref py py-class docutils literal notranslate"><span class="pre">UserList</span></code></a>
instance.</p>
<p>Python 2.2 fixes this, and in the process adds some exciting new capabilities.
A brief summary:</p>
<ul class="simple">
<li>You can subclass built-in types such as lists and even integers, and your
subclasses should work in every place that requires the original type.</li>
<li>It’s now possible to define static and class methods, in addition to the
instance methods available in previous versions of Python.</li>
<li>It’s also possible to automatically call methods on accessing or setting an
instance attribute by using a new mechanism called <em class="dfn">properties</em>.  Many uses
of <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> can be rewritten to use properties instead, making the
resulting code simpler and faster.  As a small side benefit, attributes can now
have docstrings, too.</li>
<li>The list of legal attributes for an instance can be limited to a particular
set using <em class="dfn">slots</em>, making it possible to safeguard against typos and
perhaps make more optimizations possible in future versions of Python.</li>
</ul>
<p>Some users have voiced concern about all these changes.  Sure, they say, the new
features are neat and lend themselves to all sorts of tricks that weren’t
possible in previous versions of Python, but they also make the language more
complicated.  Some people have said that they’ve always recommended Python for
its simplicity, and feel that its simplicity is being lost.</p>
<p>Personally, I think there’s no need to worry.  Many of the new features are
quite esoteric, and you can write a lot of Python code without ever needed to be
aware of them.  Writing a simple class is no more difficult than it ever was, so
you don’t need to bother learning or teaching them unless they’re actually
needed.  Some very complicated tasks that were previously only possible from C
will now be possible in pure Python, and to my mind that’s all for the better.</p>
<p>I’m not going to attempt to cover every single corner case and small change that
were required to make the new features work.  Instead this section will paint
only the broad strokes.  See section <a class="reference internal" href="#sect-rellinks"><span class="std std-ref">Related Links</span></a>, “Related Links”, for
further sources of information about Python 2.2’s new object model.</p>
<div class="section" id="old-and-new-classes">
<h3>Old and New Classes<a class="headerlink" href="#old-and-new-classes" title="Permalink to this headline">¶</a></h3>
<p>First, you should know that Python 2.2 really has two kinds of classes: classic
or old-style classes, and new-style classes.  The old-style class model is
exactly the same as the class model in earlier versions of Python.  All the new
features described in this section apply only to new-style classes. This
divergence isn’t intended to last forever; eventually old-style classes will be
dropped, possibly in Python 3.0.</p>
<p>So how do you define a new-style class?  You do it by subclassing an existing
new-style class.  Most of Python’s built-in types, such as integers, lists,
dictionaries, and even files, are new-style classes now.  A new-style class
named <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>, the base class for all built-in types, has also been
added so if no built-in type is suitable, you can just subclass
<a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__init__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This means that <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statements that don’t have any base classes are
always classic classes in Python 2.2.  (Actually you can also change this by
setting a module-level variable named <a class="reference internal" href="../reference/datamodel.html#__metaclass__" title="__metaclass__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__metaclass__</span></code></a> — see <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0253"><strong>PEP 253</strong></a>
for the details — but it’s easier to just subclass <a class="reference internal" href="../c-api/object.html#object"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">object</span></code></a>.)</p>
<p>The type objects for the built-in types are available as built-ins, named using
a clever trick.  Python has always had built-in functions named <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>,
<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>, and <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.  In 2.2, they aren’t functions any more, but
type objects that behave as factories when called.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span>
<span class="go">&lt;type &#39;int&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">)</span>
<span class="go">123</span>
</pre></div>
</div>
<p>To make the set of types complete, new type objects such as <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> and
<a class="reference internal" href="../library/functions.html#file" title="file"><code class="xref py py-func docutils literal notranslate"><span class="pre">file()</span></code></a> have been added.  Here’s a more interesting example, adding a
<code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code> method to file objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">LockableFile</span><span class="p">(</span><span class="n">file</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">lock</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">operation</span><span class="p">,</span> <span class="n">length</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">whence</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
        <span class="kn">import</span> <span class="nn">fcntl</span>
        <span class="k">return</span> <span class="n">fcntl</span><span class="o">.</span><span class="n">lockf</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">fileno</span><span class="p">(),</span> <span class="n">operation</span><span class="p">,</span>
                           <span class="n">length</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">whence</span><span class="p">)</span>
</pre></div>
</div>
<p>The now-obsolete <a class="reference internal" href="../library/posixfile.html#module-posixfile" title="posixfile: A file-like object with support for locking. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code></a> module contained a class that emulated all of
a file object’s methods and also added a <code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code> method, but this class
couldn’t be passed to internal functions that expected a built-in file,
something which is possible with our new <code class="xref py py-class docutils literal notranslate"><span class="pre">LockableFile</span></code>.</p>
</div>
<div class="section" id="descriptors">
<h3>Descriptors<a class="headerlink" href="#descriptors" title="Permalink to this headline">¶</a></h3>
<p>In previous versions of Python, there was no consistent way to discover what
attributes and methods were supported by an object. There were some informal
conventions, such as defining <code class="xref py py-attr docutils literal notranslate"><span class="pre">__members__</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__methods__</span></code>
attributes that were lists of names, but often the author of an extension type
or a class wouldn’t bother to define them.  You could fall back on inspecting
the <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> of an object, but when class inheritance or an arbitrary
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> hook were in use this could still be inaccurate.</p>
<p>The one big idea underlying the new class model is that an API for describing
the attributes of an object using <em class="dfn">descriptors</em> has been formalized.
Descriptors specify the value of an attribute, stating whether it’s a method or
a field.  With the descriptor API, static methods and class methods become
possible, as well as more exotic constructs.</p>
<p>Attribute descriptors are objects that live inside class objects, and have a few
attributes of their own:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> is the attribute’s name.</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the attribute’s docstring.</li>
<li><code class="docutils literal notranslate"><span class="pre">__get__(object)</span></code> is a method that retrieves the attribute value from
<em>object</em>.</li>
<li><code class="docutils literal notranslate"><span class="pre">__set__(object,</span> <span class="pre">value)</span></code> sets the attribute on <em>object</em> to <em>value</em>.</li>
<li><code class="docutils literal notranslate"><span class="pre">__delete__(object,</span> <span class="pre">value)</span></code> deletes the <em>value</em>  attribute of <em>object</em>.</li>
</ul>
<p>For example, when you write <code class="docutils literal notranslate"><span class="pre">obj.x</span></code>, the steps that Python actually performs
are:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">descriptor</span> <span class="o">=</span> <span class="n">obj</span><span class="o">.</span><span class="vm">__class__</span><span class="o">.</span><span class="n">x</span>
<span class="n">descriptor</span><span class="o">.</span><span class="fm">__get__</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
</pre></div>
</div>
<p>For methods, <code class="xref py py-meth docutils literal notranslate"><span class="pre">descriptor.__get__()</span></code> returns a temporary object that’s
callable, and wraps up the instance and the method to be called on it. This is
also why static methods and class methods are now possible; they have
descriptors that wrap up just the method, or the method and the class.  As a
brief explanation of these new kinds of methods, static methods aren’t passed
the instance, and therefore resemble regular functions.  Class methods are
passed the class of the object, but not the object itself.  Static and class
methods are defined like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="n">f</span> <span class="o">=</span> <span class="nb">staticmethod</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="n">g</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> function takes the function <code class="xref py py-func docutils literal notranslate"><span class="pre">f()</span></code>, and returns it
wrapped up in a descriptor so it can be stored in the class object.  You might
expect there to be special syntax for creating such methods (<code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">static</span> <span class="pre">f</span></code>,
<code class="docutils literal notranslate"><span class="pre">defstatic</span> <span class="pre">f()</span></code>, or something like that) but no such syntax has been defined
yet; that’s been left for future versions of Python.</p>
<p>More new features, such as slots and properties, are also implemented as new
kinds of descriptors, and it’s not difficult to write a descriptor class that
does something novel.  For example, it would be possible to write a descriptor
class that made it possible to write Eiffel-style preconditions and
postconditions for a method.  A class that used this feature might be defined
like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">eiffel</span> <span class="k">import</span> <span class="n">eiffelmethod</span>

<span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg1</span><span class="p">,</span> <span class="n">arg2</span><span class="p">):</span>
        <span class="c1"># The actual function</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">pre_f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Check preconditions</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">post_f</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Check postconditions</span>
        <span class="o">...</span>

    <span class="n">f</span> <span class="o">=</span> <span class="n">eiffelmethod</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">pre_f</span><span class="p">,</span> <span class="n">post_f</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that a person using the new <code class="xref py py-func docutils literal notranslate"><span class="pre">eiffelmethod()</span></code> doesn’t have to understand
anything about descriptors.  This is why I think the new features don’t increase
the basic complexity of the language. There will be a few wizards who need to
know about it in order to write <code class="xref py py-func docutils literal notranslate"><span class="pre">eiffelmethod()</span></code> or the ZODB or whatever,
but most users will just write code on top of the resulting libraries and ignore
the implementation details.</p>
</div>
<div class="section" id="multiple-inheritance-the-diamond-rule">
<h3>Multiple Inheritance: The Diamond Rule<a class="headerlink" href="#multiple-inheritance-the-diamond-rule" title="Permalink to this headline">¶</a></h3>
<p>Multiple inheritance has also been made more useful through changing the rules
under which names are resolved.  Consider this set of classes (diagram taken
from <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0253"><strong>PEP 253</strong></a> by Guido van Rossum):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>      <span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
        <span class="o">^</span> <span class="o">^</span>  <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span>
       <span class="o">/</span>   \
      <span class="o">/</span>     \
     <span class="o">/</span>       \
    <span class="o">/</span>         \
<span class="k">class</span> <span class="nc">B</span>     <span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="o">^</span>         <span class="o">^</span>  <span class="k">def</span> <span class="nf">save</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span>
     \       <span class="o">/</span>
      \     <span class="o">/</span>
       \   <span class="o">/</span>
        \ <span class="o">/</span>
      <span class="k">class</span> <span class="nc">D</span>
</pre></div>
</div>
<p>The lookup rule for classic classes is simple but not very smart; the base
classes are searched depth-first, going from left to right.  A reference to
<code class="xref py py-meth docutils literal notranslate"><span class="pre">D.save()</span></code> will search the classes <code class="xref py py-class docutils literal notranslate"><span class="pre">D</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">B</span></code>, and then
<code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code>, where <code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code> would be found and returned.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">C.save()</span></code>
would never be found at all.  This is bad, because if <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code>
method is saving some internal state specific to <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, not calling it will
result in that state never getting saved.</p>
<p>New-style classes follow a different algorithm that’s a bit more complicated to
explain, but does the right thing in this situation. (Note that Python 2.3
changes this algorithm to one that produces the same results in most cases, but
produces more useful results for really complicated inheritance graphs.)</p>
<ol class="arabic simple">
<li>List all the base classes, following the classic lookup rule and include a
class multiple times if it’s visited repeatedly.  In the above example, the list
of visited classes is [<code class="xref py py-class docutils literal notranslate"><span class="pre">D</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">B</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>,
<code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code>].</li>
<li>Scan the list for duplicated classes.  If any are found, remove all but one
occurrence, leaving the <em>last</em> one in the list.  In the above example, the list
becomes [<code class="xref py py-class docutils literal notranslate"><span class="pre">D</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">B</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">A</span></code>] after dropping
duplicates.</li>
</ol>
<p>Following this rule, referring to <code class="xref py py-meth docutils literal notranslate"><span class="pre">D.save()</span></code> will return <code class="xref py py-meth docutils literal notranslate"><span class="pre">C.save()</span></code>,
which is the behaviour we’re after.  This lookup rule is the same as the one
followed by Common Lisp.  A new built-in function, <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>, provides a way
to get at a class’s superclasses without having to reimplement Python’s
algorithm. The most commonly used form will be  <code class="docutils literal notranslate"><span class="pre">super(class,</span> <span class="pre">obj)</span></code>, which
returns  a bound superclass object (not the actual class object).  This form
will be used in methods to call a method in the superclass; for example,
<code class="xref py py-class docutils literal notranslate"><span class="pre">D</span></code>’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">save()</span></code> method would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">D</span> <span class="p">(</span><span class="n">B</span><span class="p">,</span><span class="n">C</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">save</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Call superclass .save()</span>
        <span class="nb">super</span><span class="p">(</span><span class="n">D</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
        <span class="c1"># Save D&#39;s private information here</span>
        <span class="o">...</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> can also return unbound superclass objects when called as
<code class="docutils literal notranslate"><span class="pre">super(class)</span></code> or <code class="docutils literal notranslate"><span class="pre">super(class1,</span> <span class="pre">class2)</span></code>, but this probably won’t
often be useful.</p>
</div>
<div class="section" id="attribute-access">
<h3>Attribute Access<a class="headerlink" href="#attribute-access" title="Permalink to this headline">¶</a></h3>
<p>A fair number of sophisticated Python classes define hooks for attribute access
using <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>; most commonly this is done for convenience, to make
code more readable by automatically mapping an attribute access such as
<code class="docutils literal notranslate"><span class="pre">obj.parent</span></code> into a method call such as <code class="docutils literal notranslate"><span class="pre">obj.get_parent</span></code>.  Python 2.2 adds
some new ways of controlling attribute access.</p>
<p>First, <code class="docutils literal notranslate"><span class="pre">__getattr__(attr_name)</span></code> is still supported by new-style classes,
and nothing about it has changed.  As before, it will be called when an attempt
is made to access <code class="docutils literal notranslate"><span class="pre">obj.foo</span></code> and no attribute named <code class="docutils literal notranslate"><span class="pre">foo</span></code> is found in the
instance’s dictionary.</p>
<p>New-style classes also support a new method,
<code class="docutils literal notranslate"><span class="pre">__getattribute__(attr_name)</span></code>.  The difference between the two methods is
that <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> is <em>always</em> called whenever any attribute is
accessed, while the old <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> is only called if <code class="docutils literal notranslate"><span class="pre">foo</span></code> isn’t
found in the instance’s dictionary.</p>
<p>However, Python 2.2’s support for <em class="dfn">properties</em> will often be a simpler way
to trap attribute references.  Writing a <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method is
complicated because to avoid recursion you can’t use regular attribute accesses
inside them, and instead have to mess around with the contents of
<a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> methods also end up being called by Python
when it checks for other methods such as <a class="reference internal" href="../reference/datamodel.html#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a>,
and so have to be written with this in mind. Finally, calling a function on
every attribute access results in a sizable performance loss.</p>
<p><a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-class docutils literal notranslate"><span class="pre">property</span></code></a> is a new built-in type that packages up three functions that
get, set, or delete an attribute, and a docstring.  For example, if you want to
define a <code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code> attribute that’s computed, but also settable, you could
write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_size</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">result</span> <span class="o">=</span> <span class="o">...</span> <span class="n">computation</span> <span class="o">...</span>
        <span class="k">return</span> <span class="n">result</span>
    <span class="k">def</span> <span class="nf">set_size</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">size</span><span class="p">):</span>
        <span class="o">...</span> <span class="n">compute</span> <span class="n">something</span> <span class="n">based</span> <span class="n">on</span> <span class="n">the</span> <span class="n">size</span>
        <span class="ow">and</span> <span class="nb">set</span> <span class="n">internal</span> <span class="n">state</span> <span class="n">appropriately</span> <span class="o">...</span>

    <span class="c1"># Define a property.  The &#39;delete this attribute&#39;</span>
    <span class="c1"># method is defined as None, so the attribute</span>
    <span class="c1"># can&#39;t be deleted.</span>
    <span class="n">size</span> <span class="o">=</span> <span class="nb">property</span><span class="p">(</span><span class="n">get_size</span><span class="p">,</span> <span class="n">set_size</span><span class="p">,</span>
                    <span class="kc">None</span><span class="p">,</span>
                    <span class="s2">&quot;Storage size of this instance&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>That is certainly clearer and easier to write than a pair of
<a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>/<a class="reference internal" href="../reference/datamodel.html#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> methods that check for the <code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code>
attribute and handle it specially while retrieving all other attributes from the
instance’s <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.  Accesses to <code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code> are also the only ones
which have to perform the work of calling a function, so references to other
attributes run at their usual speed.</p>
<p>Finally, it’s possible to constrain the list of attributes that can be
referenced on an object using the new <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code> class attribute. Python
objects are usually very dynamic; at any time it’s possible to define a new
attribute on an instance by just doing <code class="docutils literal notranslate"><span class="pre">obj.new_attr=1</span></code>.   A new-style class
can define a class attribute named <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code> to limit the legal
attributes  to a particular set of names.  An example will make this clear:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
<span class="gp">... </span>    <span class="vm">__slots__</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;template&#39;</span><span class="p">,</span> <span class="s1">&#39;name&#39;</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">obj</span><span class="o">.</span><span class="n">template</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span><span class="o">.</span><span class="n">template</span> <span class="o">=</span> <span class="s1">&#39;Test&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">obj</span><span class="o">.</span><span class="n">template</span>
<span class="go">Test</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span><span class="o">.</span><span class="n">newattr</span> <span class="o">=</span> <span class="kc">None</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">AttributeError</span>: <span class="n">&#39;C&#39; object has no attribute &#39;newattr&#39;</span>
</pre></div>
</div>
<p>Note how you get an <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> on the attempt to assign to an
attribute not listed in <code class="xref py py-attr docutils literal notranslate"><span class="pre">__slots__</span></code>.</p>
</div>
<div class="section" id="related-links">
<span id="sect-rellinks"></span><h3>Related Links<a class="headerlink" href="#related-links" title="Permalink to this headline">¶</a></h3>
<p>This section has just been a quick overview of the new features, giving enough
of an explanation to start you programming, but many details have been
simplified or ignored.  Where should you go to get a more complete picture?</p>
<p><a class="reference external" href="https://docs.python.org/dev/howto/descriptor.html">https://docs.python.org/dev/howto/descriptor.html</a> is a lengthy tutorial introduction to
the descriptor features, written by Guido van Rossum. If my description has
whetted your appetite, go read this tutorial next, because it goes into much
more detail about the new features while still remaining quite easy to read.</p>
<p>Next, there are two relevant PEPs, <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0252"><strong>PEP 252</strong></a> and <span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0253"><strong>PEP 253</strong></a>.  <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0252"><strong>PEP 252</strong></a> is
titled “Making Types Look More Like Classes”, and covers the descriptor API.
<span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0253"><strong>PEP 253</strong></a> is titled “Subtyping Built-in Types”, and describes the changes to
type objects that make it possible to subtype built-in objects.  <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0253"><strong>PEP 253</strong></a> is
the more complicated PEP of the two, and at a few points the necessary
explanations of types and meta-types may cause your head to explode.  Both PEPs
were written and implemented by Guido van Rossum, with substantial assistance
from the rest of the Zope Corp. team.</p>
<p>Finally, there’s the ultimate authority: the source code.  Most of the machinery
for the type handling is in <code class="file docutils literal notranslate"><span class="pre">Objects/typeobject.c</span></code>, but you should only
resort to it after all other avenues have been exhausted, including posting a
question to python-list or python-dev.</p>
</div>
</div>
<div class="section" id="pep-234-iterators">
<h2>PEP 234: Iterators<a class="headerlink" href="#pep-234-iterators" title="Permalink to this headline">¶</a></h2>
<p>Another significant addition to 2.2 is an iteration interface at both the C and
Python levels.  Objects can define how they can be looped over by callers.</p>
<p>In Python versions up to 2.1, the usual way to make <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">item</span> <span class="pre">in</span> <span class="pre">obj</span></code> work is
to define a <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method that looks something like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">index</span><span class="p">):</span>
    <span class="k">return</span> <span class="o">&lt;</span><span class="nb">next</span> <span class="n">item</span><span class="o">&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> is more properly used to define an indexing operation on an
object so that you can write <code class="docutils literal notranslate"><span class="pre">obj[5]</span></code> to retrieve the sixth element.  It’s a
bit misleading when you’re using this only to support <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loops.
Consider some file-like object that wants to be looped over; the <em>index</em>
parameter is essentially meaningless, as the class probably assumes that a
series of <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> calls will be made with <em>index</em> incrementing by
one each time.  In other words, the presence of the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method
doesn’t mean that using <code class="docutils literal notranslate"><span class="pre">file[5]</span></code>  to randomly access the sixth element will
work, though it really should.</p>
<p>In Python 2.2, iteration can be implemented separately, and <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>
methods can be limited to classes that really do support random access.  The
basic idea of iterators is  simple.  A new built-in function, <code class="docutils literal notranslate"><span class="pre">iter(obj)</span></code>
or <code class="docutils literal notranslate"><span class="pre">iter(C,</span> <span class="pre">sentinel)</span></code>, is used to get an iterator. <code class="docutils literal notranslate"><span class="pre">iter(obj)</span></code> returns
an iterator for the object <em>obj</em>, while <code class="docutils literal notranslate"><span class="pre">iter(C,</span> <span class="pre">sentinel)</span></code> returns an
iterator that will invoke the callable object <em>C</em> until it returns <em>sentinel</em> to
signal that the iterator is done.</p>
<p>Python classes can define an <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method, which should create and
return a new iterator for the object; if the object is its own iterator, this
method can just return <code class="docutils literal notranslate"><span class="pre">self</span></code>.  In particular, iterators will usually be their
own iterators.  Extension types implemented in C can implement a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a>
function in order to return an iterator, and extension types that want to behave
as iterators can define a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iternext</span></code></a> function.</p>
<p>So, after all this, what do iterators actually do?  They have one required
method, <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a>, which takes no arguments and returns the next value.  When
there are no more values to be returned, calling <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> should raise the
<a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">i</span>
<span class="go">&lt;iterator object at 0x8116870&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">StopIteration</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>In 2.2, Python’s <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> statement no longer expects a sequence; it
expects something for which <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> will return an iterator. For backward
compatibility and convenience, an iterator is automatically constructed for
sequences that don’t implement <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> or a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code class="xref c c-member docutils literal notranslate"><span class="pre">tp_iter</span></code></a> slot, so
<code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">[1,2,3]</span></code> will still work.  Wherever the Python interpreter loops
over a sequence, it’s been changed to use the iterator protocol.  This means you
can do things like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span> <span class="o">=</span> <span class="n">i</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">,</span><span class="n">b</span><span class="p">,</span><span class="n">c</span>
<span class="go">(1, 2, 3)</span>
</pre></div>
</div>
<p>Iterator support has been added to some of Python’s basic types.   Calling
<a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on a dictionary will return an iterator which loops over its keys:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;Jan&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;Feb&#39;</span><span class="p">:</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;Mar&#39;</span><span class="p">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;Apr&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;May&#39;</span><span class="p">:</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;Jun&#39;</span><span class="p">:</span> <span class="mi">6</span><span class="p">,</span>
<span class="gp">... </span>     <span class="s1">&#39;Jul&#39;</span><span class="p">:</span> <span class="mi">7</span><span class="p">,</span> <span class="s1">&#39;Aug&#39;</span><span class="p">:</span> <span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;Sep&#39;</span><span class="p">:</span> <span class="mi">9</span><span class="p">,</span> <span class="s1">&#39;Oct&#39;</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="s1">&#39;Nov&#39;</span><span class="p">:</span> <span class="mi">11</span><span class="p">,</span> <span class="s1">&#39;Dec&#39;</span><span class="p">:</span> <span class="mi">12</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key</span> <span class="ow">in</span> <span class="n">m</span><span class="p">:</span> <span class="nb">print</span> <span class="n">key</span><span class="p">,</span> <span class="n">m</span><span class="p">[</span><span class="n">key</span><span class="p">]</span>
<span class="gp">...</span>
<span class="go">Mar 3</span>
<span class="go">Feb 2</span>
<span class="go">Aug 8</span>
<span class="go">Sep 9</span>
<span class="go">May 5</span>
<span class="go">Jun 6</span>
<span class="go">Jul 7</span>
<span class="go">Jan 1</span>
<span class="go">Apr 4</span>
<span class="go">Nov 11</span>
<span class="go">Dec 12</span>
<span class="go">Oct 10</span>
</pre></div>
</div>
<p>That’s just the default behaviour.  If you want to iterate over keys, values, or
key/value pairs, you can explicitly call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code>, or <code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code> methods to get an appropriate iterator.
In a minor related change, the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator now works on dictionaries,
so <code class="docutils literal notranslate"><span class="pre">key</span> <span class="pre">in</span> <span class="pre">dict</span></code> is now equivalent to <code class="docutils literal notranslate"><span class="pre">dict.has_key(key)</span></code>.</p>
<p>Files also provide an iterator, which calls the <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method until
there are no more lines in the file.  This means you can now read each line of a
file using code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">file</span><span class="p">:</span>
    <span class="c1"># do something for each line</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Note that you can only go forward in an iterator; there’s no way to get the
previous element, reset the iterator, or make a copy of it. An iterator object
could provide such additional capabilities, but the iterator protocol only
requires a <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0234"><strong>PEP 234</strong></a> - Iterators</dt>
<dd>Written by Ka-Ping Yee and GvR; implemented  by the Python Labs crew, mostly by
GvR and Tim Peters.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-255-simple-generators">
<h2>PEP 255: Simple Generators<a class="headerlink" href="#pep-255-simple-generators" title="Permalink to this headline">¶</a></h2>
<p>Generators are another new feature, one that interacts with the introduction of
iterators.</p>
<p>You’re doubtless familiar with how function calls work in Python or C.  When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren’t thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.</p>
<p>Here’s the simplest example of a generator function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">i</span>
</pre></div>
</div>
<p>A new keyword, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>, was introduced for generators.  Any function
containing a <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is a generator function; this is
detected by Python’s bytecode compiler which compiles the function specially as
a result.  Because a new keyword was introduced, generators must be explicitly
enabled in a module by including a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">generators</span></code>
statement near the top of the module’s source code.  In Python 2.3 this
statement will become unnecessary.</p>
<p>When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the generator outputs the value of <code class="docutils literal notranslate"><span class="pre">i</span></code>,
similar to a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement.  The big difference between
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> and a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement is that on reaching a
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> the generator’s state of execution is suspended and local
variables are preserved.  On the next call to the generator’s <code class="docutils literal notranslate"><span class="pre">next()</span></code> method,
the function will resume executing immediately after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
statement.  (For complicated reasons, the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement isn’t
allowed inside the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> block of a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement; read <span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> for a full explanation of the
interaction between <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> and exceptions.)</p>
<p>Here’s a sample usage of the <code class="xref py py-func docutils literal notranslate"><span class="pre">generate_ints()</span></code> generator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span>
<span class="go">&lt;generator object at 0x8117f90&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>You could equally write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></code>, or <code class="docutils literal notranslate"><span class="pre">a,b,c</span> <span class="pre">=</span>
<span class="pre">generate_ints(3)</span></code>.</p>
<p>Inside a generator function, the <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> with a value, such
as <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">5</span></code>, is a syntax error inside a generator function.  The end of the
generator’s results can also be indicated by raising <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
manually, or by just letting the flow of execution fall off the bottom of the
function.</p>
<p>You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting <code class="docutils literal notranslate"><span class="pre">self.count</span></code> to
0, and having the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method increment <code class="docutils literal notranslate"><span class="pre">self.count</span></code> and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># A recursive generator that generates Tree leaves in in-order.</span>
<span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">t</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
        <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
<p>Two other examples in <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight’s Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).</p>
<p>The idea of generators comes from other programming languages, especially Icon
(<a class="reference external" href="https://www.cs.arizona.edu/icon/">https://www.cs.arizona.edu/icon/</a>), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from “An Overview of the Icon Programming Language” at
<a class="reference external" href="https://www.cs.arizona.edu/icon/docs/ipd266.htm">https://www.cs.arizona.edu/icon/docs/ipd266.htm</a> gives an idea of what this looks
like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sentence</span> <span class="p">:</span><span class="o">=</span> <span class="s2">&quot;Store it in the neighboring harbor&quot;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="p">:</span><span class="o">=</span> <span class="n">find</span><span class="p">(</span><span class="s2">&quot;or&quot;</span><span class="p">,</span> <span class="n">sentence</span><span class="p">))</span> <span class="o">&gt;</span> <span class="mi">5</span> <span class="n">then</span> <span class="n">write</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>In Icon the <code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code> function returns the indexes at which the substring
“or” is found: 3, 23, 33.  In the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, <code class="docutils literal notranslate"><span class="pre">i</span></code> is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.</p>
<p>Python doesn’t go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered a new part of the core Python language, but
learning or using them isn’t compulsory; if they don’t solve any problems that
you have, feel free to ignore them. One novel feature of Python’s interface as
compared to Icon’s is that a generator’s state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-237-unifying-long-integers-and-integers">
<h2>PEP 237: Unifying Long Integers and Integers<a class="headerlink" href="#pep-237-unifying-long-integers-and-integers" title="Permalink to this headline">¶</a></h2>
<p>In recent versions, the distinction between regular integers, which are 32-bit
values on most machines, and long integers, which can be of arbitrary size, was
becoming an annoyance.  For example, on platforms that support files larger than
<code class="docutils literal notranslate"><span class="pre">2**32</span></code> bytes, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code> method of file objects has to return a long
integer. However, there were various bits of Python that expected plain integers
and would raise an error if a long integer was provided instead.  For example,
in Python 1.5, only regular integers could be used as a slice index, and
<code class="docutils literal notranslate"><span class="pre">'abc'[1L:]</span></code> would raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception with the message ‘slice
index must be int’.</p>
<p>Python 2.2 will shift values from short to long integers as required. The ‘L’
suffix is no longer needed to indicate a long integer literal, as now the
compiler will choose the appropriate type.  (Using the ‘L’ suffix will be
discouraged in future 2.x versions of Python, triggering a warning in Python
2.4, and probably dropped in Python 3.0.)  Many operations that used to raise an
<a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> will now return a long integer as their result.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1234567890123</span>
<span class="go">1234567890123L</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">2</span> <span class="o">**</span> <span class="mi">64</span>
<span class="go">18446744073709551616L</span>
</pre></div>
</div>
<p>In most cases, integers and long integers will now be treated identically.  You
can still distinguish them with the <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> built-in function, but that’s
rarely needed.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a> - Unifying Long Integers and Integers</dt>
<dd>Written by Moshe Zadka and Guido van Rossum.  Implemented mostly by Guido van
Rossum.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-238-changing-the-division-operator">
<h2>PEP 238: Changing the Division Operator<a class="headerlink" href="#pep-238-changing-the-division-operator" title="Permalink to this headline">¶</a></h2>
<p>The most controversial change in Python 2.2 heralds the start of an effort to
fix an old design flaw that’s been in Python from the beginning. Currently
Python’s division operator, <code class="docutils literal notranslate"><span class="pre">/</span></code>, behaves like C’s division operator when
presented with two integer arguments: it returns an integer result that’s
truncated down when there would be a fractional part.  For example, <code class="docutils literal notranslate"><span class="pre">3/2</span></code> is
1, not 1.5, and <code class="docutils literal notranslate"><span class="pre">(-1)/2</span></code> is -1, not -0.5.  This means that the results of
division can vary unexpectedly depending on the type of the two operands and
because Python is dynamically typed, it can be difficult to determine the
possible types of the operands.</p>
<p>(The controversy is over whether this is <em>really</em> a design flaw, and whether
it’s worth breaking existing code to fix this.  It’s caused endless discussions
on python-dev, and in July 2001 erupted into a storm of acidly sarcastic
postings on <em class="newsgroup">comp.lang.python</em>. I won’t argue for either side here
and will stick to describing what’s  implemented in 2.2.  Read <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a> for a
summary of arguments and counter-arguments.)</p>
<p>Because this change might break code, it’s being introduced very gradually.
Python 2.2 begins the transition, but the switch won’t be complete until Python
3.0.</p>
<p>First, I’ll borrow some terminology from <span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a>.  “True division” is the
division that most non-programmers are familiar with: 3/2 is 1.5, 1/4 is 0.25,
and so forth.  “Floor division” is what Python’s <code class="docutils literal notranslate"><span class="pre">/</span></code> operator currently does
when given integer operands; the result is the floor of the value returned by
true division.  “Classic division” is the current mixed behaviour of <code class="docutils literal notranslate"><span class="pre">/</span></code>; it
returns the result of floor division when the operands are integers, and returns
the result of true division when one of the operands is a floating-point number.</p>
<p>Here are the changes 2.2 introduces:</p>
<ul>
<li><p class="first">A new operator, <code class="docutils literal notranslate"><span class="pre">//</span></code>, is the floor division operator. (Yes, we know it looks
like C++’s comment symbol.)  <code class="docutils literal notranslate"><span class="pre">//</span></code> <em>always</em> performs floor division no matter
what the types of its operands are, so <code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">//</span> <span class="pre">2</span></code> is 0 and <code class="docutils literal notranslate"><span class="pre">1.0</span> <span class="pre">//</span> <span class="pre">2.0</span></code> is
also 0.0.</p>
<p><code class="docutils literal notranslate"><span class="pre">//</span></code> is always available in Python 2.2; you don’t need to enable it using a
<code class="docutils literal notranslate"><span class="pre">__future__</span></code> statement.</p>
</li>
<li><p class="first">By including a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code> in a module, the <code class="docutils literal notranslate"><span class="pre">/</span></code>
operator will be changed to return the result of true division, so <code class="docutils literal notranslate"><span class="pre">1/2</span></code> is
0.5.  Without the <code class="docutils literal notranslate"><span class="pre">__future__</span></code> statement, <code class="docutils literal notranslate"><span class="pre">/</span></code> still means classic division.
The default meaning of <code class="docutils literal notranslate"><span class="pre">/</span></code> will not change until Python 3.0.</p>
</li>
<li><p class="first">Classes can define methods called <a class="reference internal" href="../reference/datamodel.html#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a>
to overload the two division operators.  At the C level, there are also slots in
the <a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure so extension types can define the two
operators.</p>
</li>
<li><p class="first">Python 2.2 supports some command-line arguments for testing whether code will
work with the changed division semantics.  Running python with <a class="reference internal" href="../using/cmdline.html#cmdoption-q"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Q</span>
<span class="pre">warn</span></code></a> will cause a warning to be issued whenever division is applied to two
integers.  You can use this to find code that’s affected by the change and fix
it.  By default, Python 2.2 will simply perform classic division without a
warning; the warning will be turned on by default in Python 2.3.</p>
</li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0238"><strong>PEP 238</strong></a> - Changing the Division Operator</dt>
<dd>Written by Moshe Zadka and  Guido van Rossum.  Implemented by Guido van Rossum..</dd>
</dl>
</div>
</div>
<div class="section" id="unicode-changes">
<h2>Unicode Changes<a class="headerlink" href="#unicode-changes" title="Permalink to this headline">¶</a></h2>
<p>Python’s Unicode support has been enhanced a bit in 2.2.  Unicode strings are
usually stored as UCS-2, as 16-bit unsigned integers. Python 2.2 can also be
compiled to use UCS-4, 32-bit unsigned integers, as its internal encoding by
supplying <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-unicode=ucs4</span></code> to the configure script.   (It’s also
possible to specify <code class="xref std std-option docutils literal notranslate"><span class="pre">--disable-unicode</span></code> to completely disable Unicode
support.)</p>
<p>When built to use UCS-4 (a “wide Python”), the interpreter can natively handle
Unicode characters from U+000000 to U+110000, so the range of legal values for
the <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a> function is expanded accordingly.  Using an interpreter
compiled to use UCS-2 (a “narrow Python”), values greater than 65535 will still
cause <a class="reference internal" href="../library/functions.html#unichr" title="unichr"><code class="xref py py-func docutils literal notranslate"><span class="pre">unichr()</span></code></a> to raise a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception. This is all
described in <span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0261"><strong>PEP 261</strong></a>, “Support for ‘wide’ Unicode characters”; consult it for
further details.</p>
<p>Another change is simpler to explain. Since their introduction, Unicode strings
have supported an <code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code> method to convert the string to a selected
encoding such as UTF-8 or Latin-1.  A symmetric <code class="docutils literal notranslate"><span class="pre">decode([*encoding*])</span></code>
method has been added to 8-bit strings (though not to Unicode strings) in 2.2.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code> assumes that the string is in the specified encoding and decodes
it, returning whatever is returned by the codec.</p>
<p>Using this new feature, codecs have been added for tasks not directly related to
Unicode.  For example, codecs have been added for uu-encoding, MIME’s base64
encoding, and compression with the <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Here is a lengthy piece of redundant, overly verbose,</span>
<span class="gp">... </span><span class="s2">and repetitive text.</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;zlib&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span>
<span class="go">&#39;x\x9c\r\xc9\xc1\r\x80 \x10\x04\xc0?Ul...&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s1">&#39;zlib&#39;</span><span class="p">)</span>
<span class="go">&#39;Here is a lengthy piece of redundant, overly verbose,\nand repetitive text.\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">s</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;uu&#39;</span><span class="p">)</span>
<span class="go">begin 666 &lt;data&gt;</span>
<span class="go">M2&amp;5R92!I&lt;R!A(&amp;QE;F=T:&#39;D@&lt;&amp;EE8V4@;V8@&lt;F5D=6YD86YT+&quot;!O=F5R;&#39;D@</span>
<span class="go">&gt;=F5R8F]S92P*86YD(&#39;)E&lt;&amp;5T:71I=F4@=&amp;5X=&quot;X*</span>

<span class="go">end</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;sheesh&quot;</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s1">&#39;rot-13&#39;</span><span class="p">)</span>
<span class="go">&#39;furrfu&#39;</span>
</pre></div>
</div>
<p>To convert a class instance to Unicode, a <a class="reference internal" href="../reference/datamodel.html#object.__unicode__" title="object.__unicode__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__unicode__()</span></code></a> method can be
defined by a class, analogous to <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>.</p>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">encode()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code>, and <a class="reference internal" href="../reference/datamodel.html#object.__unicode__" title="object.__unicode__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__unicode__()</span></code></a> were implemented by
Marc-André Lemburg.  The changes to support using UCS-4 internally were
implemented by Fredrik Lundh and Martin von Löwis.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0261"><strong>PEP 261</strong></a> - Support for ‘wide’ Unicode characters</dt>
<dd>Written by Paul Prescod.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-227-nested-scopes">
<h2>PEP 227: Nested Scopes<a class="headerlink" href="#pep-227-nested-scopes" title="Permalink to this headline">¶</a></h2>
<p>In Python 2.1, statically nested scopes were added as an optional feature, to be
enabled by a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">nested_scopes</span></code> directive.  In 2.2 nested
scopes no longer need to be specially enabled, and are now always present.  The
rest of this section is a copy of the description of nested scopes from my
“What’s New in Python 2.1” document; if you read it when 2.1 came out, you can
skip the rest of this section.</p>
<p>The largest change introduced in Python 2.1, and made complete in 2.2, is to
Python’s scoping rules.  In Python 2.0, at any given time there are at most
three namespaces used to look up variable names: local, module-level, and the
built-in namespace.  This often surprised people because it didn’t match their
intuitive expectations.  For example, a nested recursive function definition
doesn’t work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">g</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
        <span class="o">...</span>
        <span class="k">return</span> <span class="n">g</span><span class="p">(</span><span class="n">value</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The function <code class="xref py py-func docutils literal notranslate"><span class="pre">g()</span></code> will always raise a <a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> exception, because
the binding of the name <code class="docutils literal notranslate"><span class="pre">g</span></code> isn’t in either its local namespace or in the
module-level namespace.  This isn’t much of a problem in practice (how often do
you recursively define interior functions like this?), but this also made using
the <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> statement clumsier, and this was a problem in practice.
In code which uses <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> you can often find local variables being
copied by passing them as the default values of arguments.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">find</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">name</span><span class="p">):</span>
    <span class="s2">&quot;Return list of any entries equal to &#39;name&#39;&quot;</span>
    <span class="n">L</span> <span class="o">=</span> <span class="nb">filter</span><span class="p">(</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="n">name</span><span class="p">:</span> <span class="n">x</span> <span class="o">==</span> <span class="n">name</span><span class="p">,</span>
               <span class="bp">self</span><span class="o">.</span><span class="n">list_attribute</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">L</span>
</pre></div>
</div>
<p>The readability of Python code written in a strongly functional style suffers
greatly as a result.</p>
<p>The most significant change to Python 2.2 is that static scoping has been added
to the language to fix this problem.  As a first effect, the <code class="docutils literal notranslate"><span class="pre">name=name</span></code>
default argument is now unnecessary in the above example.  Put simply, when a
given variable name is not assigned a value within a function (by an assignment,
or the <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a>, <a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a>, or <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements),
references to the variable will be looked up in the local namespace of the
enclosing scope.  A more detailed explanation of the rules, and a dissection of
the implementation, can be found in the PEP.</p>
<p>This change may cause some compatibility problems for code where the same
variable name is used both at the module level and as a local variable within a
function that contains further function definitions. This seems rather unlikely
though, since such code would have been pretty confusing to read in the first
place.</p>
<p>One side effect of the change is that the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> and
<a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statements have been made illegal inside a function scope under
certain conditions.  The Python reference manual has said all along that <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> is only legal at the top level of a module, but the CPython
interpreter has never enforced this before.  As part of the implementation of
nested scopes, the compiler which turns Python source into bytecodes has to
generate different code to access variables in a containing scope.  <code class="docutils literal notranslate"><span class="pre">from</span>
<span class="pre">module</span> <span class="pre">import</span> <span class="pre">*</span></code> and <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> make it impossible for the compiler to
figure this out, because they add names to the local namespace that are
unknowable at compile time. Therefore, if a function contains function
definitions or <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> expressions with free variables, the compiler
will flag this by raising a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxError" title="exceptions.SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> exception.</p>
<p>To make the preceding explanation a bit clearer, here’s an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="c1"># The next line is a syntax error</span>
    <span class="n">exec</span> <span class="s1">&#39;x=2&#39;</span>
    <span class="k">def</span> <span class="nf">g</span><span class="p">():</span>
        <span class="k">return</span> <span class="n">x</span>
</pre></div>
</div>
<p>Line 4 containing the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement is a syntax error, since
<a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> would define a new local variable named <code class="docutils literal notranslate"><span class="pre">x</span></code> whose value should
be accessed by <code class="xref py py-func docutils literal notranslate"><span class="pre">g()</span></code>.</p>
<p>This shouldn’t be much of a limitation, since <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> is rarely used in
most Python code (and when it is used, it’s often a sign of a poor design
anyway).</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0227"><strong>PEP 227</strong></a> - Statically Nested Scopes</dt>
<dd>Written and implemented by Jeremy Hylton.</dd>
</dl>
</div>
</div>
<div class="section" id="new-and-improved-modules">
<h2>New and Improved Modules<a class="headerlink" href="#new-and-improved-modules" title="Permalink to this headline">¶</a></h2>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module was contributed to the standard library by Fredrik
Lundh, providing support for writing XML-RPC clients.  XML-RPC is a simple
remote procedure call protocol built on top of HTTP and XML. For example, the
following snippet retrieves a list of RSS channels from the O’Reilly Network,
and then  lists the recent headlines for one channel:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">xmlrpclib</span>
<span class="n">s</span> <span class="o">=</span> <span class="n">xmlrpclib</span><span class="o">.</span><span class="n">Server</span><span class="p">(</span>
      <span class="s1">&#39;http://www.oreillynet.com/meerkat/xml-rpc/server.php&#39;</span><span class="p">)</span>
<span class="n">channels</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">meerkat</span><span class="o">.</span><span class="n">getChannels</span><span class="p">()</span>
<span class="c1"># channels is a list of dictionaries, like this:</span>
<span class="c1"># [{&#39;id&#39;: 4, &#39;title&#39;: &#39;Freshmeat Daily News&#39;}</span>
<span class="c1">#  {&#39;id&#39;: 190, &#39;title&#39;: &#39;32Bits Online&#39;},</span>
<span class="c1">#  {&#39;id&#39;: 4549, &#39;title&#39;: &#39;3DGamers&#39;}, ... ]</span>

<span class="c1"># Get the items for one channel</span>
<span class="n">items</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">meerkat</span><span class="o">.</span><span class="n">getItems</span><span class="p">(</span> <span class="p">{</span><span class="s1">&#39;channel&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">}</span> <span class="p">)</span>

<span class="c1"># &#39;items&#39; is another list of dictionaries, like this:</span>
<span class="c1"># [{&#39;link&#39;: &#39;http://freshmeat.net/releases/52719/&#39;,</span>
<span class="c1">#   &#39;description&#39;: &#39;A utility which converts HTML to XSL FO.&#39;,</span>
<span class="c1">#   &#39;title&#39;: &#39;html2fo 0.3 (Default)&#39;}, ... ]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> module makes it easy to create straightforward
XML-RPC servers.  See <a class="reference external" href="http://www.xmlrpc.com/">http://www.xmlrpc.com/</a> for more information about XML-RPC.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/hmac.html#module-hmac" title="hmac: Keyed-Hashing for Message Authentication (HMAC) implementation"><code class="xref py py-mod docutils literal notranslate"><span class="pre">hmac</span></code></a> module implements the HMAC algorithm described by
<span class="target" id="index-17"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2104.html"><strong>RFC 2104</strong></a>. (Contributed by Gerhard Häring.)</p>
</li>
<li><p class="first">Several functions that originally returned lengthy tuples now return
pseudo-sequences that still behave like tuples but also have mnemonic attributes such
as memberst_mtime or <code class="xref py py-attr docutils literal notranslate"><span class="pre">tm_year</span></code>. The enhanced functions include
<a class="reference internal" href="../library/stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-func docutils literal notranslate"><span class="pre">stat()</span></code></a>, <code class="xref py py-func docutils literal notranslate"><span class="pre">fstat()</span></code>, <a class="reference internal" href="../library/statvfs.html#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-func docutils literal notranslate"><span class="pre">statvfs()</span></code></a>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">fstatvfs()</span></code> in the
<a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module, and <code class="xref py py-func docutils literal notranslate"><span class="pre">localtime()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">gmtime()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code> in
the <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module.</p>
<p>For example, to obtain a file’s size using the old tuples, you’d end up writing
something like <code class="docutils literal notranslate"><span class="pre">file_size</span> <span class="pre">=</span> <span class="pre">os.stat(filename)[stat.ST_SIZE]</span></code>, but now this can
be written more clearly as <code class="docutils literal notranslate"><span class="pre">file_size</span> <span class="pre">=</span> <span class="pre">os.stat(filename).st_size</span></code>.</p>
<p>The original patch for this feature was contributed by Nick Mathewson.</p>
</li>
<li><p class="first">The Python profiler has been extensively reworked and various errors in its
output have been corrected.  (Contributed by Fred L. Drake, Jr. and Tim Peters.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module can be compiled to support IPv6; specify the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-ipv6</span></code> option to Python’s configure script.  (Contributed by
Jun-ichiro “itojun” Hagino.)</p>
</li>
<li><p class="first">Two new format characters were added to the <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module for 64-bit
integers on platforms that support the C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> type.  <code class="docutils literal notranslate"><span class="pre">q</span></code> is for
a signed 64-bit integer, and <code class="docutils literal notranslate"><span class="pre">Q</span></code> is for an unsigned one.  The value is
returned in Python’s long integer type.  (Contributed by Tim Peters.)</p>
</li>
<li><p class="first">In the interpreter’s interactive mode, there’s a new built-in function
<a class="reference internal" href="../library/functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> that uses the <a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module introduced in Python 2.1 to
provide interactive help. <code class="docutils literal notranslate"><span class="pre">help(object)</span></code> displays any available help text
about <em>object</em>.  <a class="reference internal" href="../library/functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> with no argument puts you in an online help
utility, where you can enter the names of functions, classes, or modules to read
their help text. (Contributed by Guido van Rossum, using Ka-Ping Yee’s
<a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module.)</p>
</li>
<li><p class="first">Various bugfixes and performance improvements have been made to the SRE engine
underlying the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module.  For example, the <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.sub()</span></code></a> and
<a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">re.split()</span></code></a> functions have been rewritten in C.  Another contributed patch
speeds up certain Unicode character ranges by a factor of two, and a new
<code class="xref py py-meth docutils literal notranslate"><span class="pre">finditer()</span></code>  method that returns an iterator over all the non-overlapping
matches in  a given string.  (SRE is maintained by Fredrik Lundh.  The
BIGCHARSET patch was contributed by Martin von Löwis.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module now supports <span class="target" id="index-18"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2487.html"><strong>RFC 2487</strong></a>, “Secure SMTP over TLS”, so
it’s now possible to encrypt the SMTP traffic between a Python program and the
mail transport agent being handed a message.  <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> also supports SMTP
authentication.  (Contributed by Gerhard Häring.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module, maintained by Piers Lauder, has support for several
new extensions: the NAMESPACE extension defined in <span class="target" id="index-19"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2342.html"><strong>RFC 2342</strong></a>, SORT, GETACL and
SETACL.  (Contributed by Anthony Baxter and Michel Pelletier.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module’s parsing of email addresses is now compliant with
<span class="target" id="index-20"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2822.html"><strong>RFC 2822</strong></a>, an update to <span class="target" id="index-21"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc822.html"><strong>RFC 822</strong></a>.  (The module’s name is <em>not</em> going to be
changed to <code class="docutils literal notranslate"><span class="pre">rfc2822</span></code>.)  A new package, <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>, has also been added for
parsing and generating e-mail messages.  (Contributed by Barry Warsaw, and
arising out of his work on Mailman.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module now contains a new <code class="xref py py-class docutils literal notranslate"><span class="pre">Differ</span></code> class for
producing human-readable lists of changes (a “delta”) between two sequences of
lines of text.  There are also two generator functions, <code class="xref py py-func docutils literal notranslate"><span class="pre">ndiff()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">restore()</span></code>, which respectively return a delta from two sequences, or one of
the original sequences from a delta. (Grunt work contributed by David Goodger,
from ndiff.py code by Tim Peters who then did the generatorization.)</p>
</li>
<li><p class="first">New constants <code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_letters</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_lowercase</span></code>, and
<code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_uppercase</span></code> were added to the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module.  There were
several modules in the standard library that used <a class="reference internal" href="../library/string.html#string.letters" title="string.letters"><code class="xref py py-const docutils literal notranslate"><span class="pre">string.letters</span></code></a> to
mean the ranges A-Za-z, but that assumption is incorrect when locales are in
use, because <a class="reference internal" href="../library/string.html#string.letters" title="string.letters"><code class="xref py py-const docutils literal notranslate"><span class="pre">string.letters</span></code></a> varies depending on the set of legal
characters defined by the current locale.  The buggy modules have all been fixed
to use <code class="xref py py-const docutils literal notranslate"><span class="pre">ascii_letters</span></code> instead. (Reported by an unknown person; fixed by
Fred L. Drake, Jr.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/mimetypes.html#module-mimetypes" title="mimetypes: Mapping of filename extensions to MIME types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetypes</span></code></a> module now makes it easier to use alternative MIME-type
databases by the addition of a <code class="xref py py-class docutils literal notranslate"><span class="pre">MimeTypes</span></code> class, which takes a list of
filenames to be parsed.  (Contributed by Fred L. Drake, Jr.)</p>
</li>
<li><p class="first">A <code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code> class was added to the <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module that allows
scheduling an activity to happen at some future time.  (Contributed by Itamar
Shtull-Trauring.)</p>
</li>
</ul>
</div>
<div class="section" id="interpreter-changes-and-fixes">
<h2>Interpreter Changes and Fixes<a class="headerlink" href="#interpreter-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<p>Some of the changes only affect people who deal with the Python interpreter at
the C level because they’re writing Python extension modules, embedding the
interpreter, or just hacking on the interpreter itself. If you only write Python
code, none of the changes described here will affect you very much.</p>
<ul>
<li><p class="first">Profiling and tracing functions can now be implemented in C, which can operate
at much higher speeds than Python-based functions and should reduce the overhead
of profiling and tracing.  This  will be of interest to authors of development
environments for Python.  Two new C functions were added to Python’s API,
<a class="reference internal" href="../c-api/init.html#c.PyEval_SetProfile" title="PyEval_SetProfile"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetProfile()</span></code></a> and <a class="reference internal" href="../c-api/init.html#c.PyEval_SetTrace" title="PyEval_SetTrace"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_SetTrace()</span></code></a>. The existing
<a class="reference internal" href="../library/sys.html#sys.setprofile" title="sys.setprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setprofile()</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.settrace" title="sys.settrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.settrace()</span></code></a> functions still exist, and have
simply been changed to use the new C-level interface.  (Contributed by Fred L.
Drake, Jr.)</p>
</li>
<li><p class="first">Another low-level API, primarily of interest to implementors of Python
debuggers and development tools, was added. <a class="reference internal" href="../c-api/init.html#c.PyInterpreterState_Head" title="PyInterpreterState_Head"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInterpreterState_Head()</span></code></a> and
<a class="reference internal" href="../c-api/init.html#c.PyInterpreterState_Next" title="PyInterpreterState_Next"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInterpreterState_Next()</span></code></a> let a caller walk through all the existing
interpreter objects; <a class="reference internal" href="../c-api/init.html#c.PyInterpreterState_ThreadHead" title="PyInterpreterState_ThreadHead"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyInterpreterState_ThreadHead()</span></code></a> and
<a class="reference internal" href="../c-api/init.html#c.PyThreadState_Next" title="PyThreadState_Next"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyThreadState_Next()</span></code></a> allow looping over all the thread states for a given
interpreter.  (Contributed by David Beazley.)</p>
</li>
<li><p class="first">The C-level interface to the garbage collector has been changed to make it
easier to write extension types that support garbage collection and to debug
misuses of the functions. Various functions have slightly different semantics,
so a bunch of functions had to be renamed.  Extensions that use the old API will
still compile but will <em>not</em> participate in garbage collection, so updating them
for 2.2 should be considered fairly high priority.</p>
<p>To upgrade an extension module to the new API, perform the following steps:</p>
</li>
<li><p class="first">Rename <code class="xref c c-func docutils literal notranslate"><span class="pre">Py_TPFLAGS_GC()</span></code> to <code class="xref c c-func docutils literal notranslate"><span class="pre">PyTPFLAGS_HAVE_GC()</span></code>.</p>
</li>
<li><dl class="first docutils">
<dt>Use <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_New" title="PyObject_GC_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_New()</span></code></a> or <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_NewVar" title="PyObject_GC_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_NewVar()</span></code></a> to allocate</dt>
<dd><p class="first last">objects, and <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_Del" title="PyObject_GC_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Del()</span></code></a> to deallocate them.</p>
</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt>Rename <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Init()</span></code> to <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_Track" title="PyObject_GC_Track"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Track()</span></code></a> and</dt>
<dd><p class="first last"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_Fini()</span></code> to <a class="reference internal" href="../c-api/gcsupport.html#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GC_UnTrack()</span></code></a>.</p>
</dd>
</dl>
</li>
<li><p class="first">Remove <code class="xref c c-func docutils literal notranslate"><span class="pre">PyGC_HEAD_SIZE()</span></code> from object size calculations.</p>
</li>
<li><p class="first">Remove calls to <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_AS_GC()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_FROM_GC()</span></code>.</p>
</li>
<li><p class="first">A new <code class="docutils literal notranslate"><span class="pre">et</span></code> format sequence was added to <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>; <code class="docutils literal notranslate"><span class="pre">et</span></code>
takes both a parameter and an encoding name, and converts the parameter to the
given encoding if the parameter turns out to be a Unicode string, or leaves it
alone if it’s an 8-bit string, assuming it to already be in the desired
encoding.  This differs from the <code class="docutils literal notranslate"><span class="pre">es</span></code> format character, which assumes that
8-bit strings are in Python’s default ASCII encoding and converts them to the
specified new encoding. (Contributed by M.-A. Lemburg, and used for the MBCS
support on Windows described in the following section.)</p>
</li>
<li><p class="first">A different argument parsing function, <a class="reference internal" href="../c-api/arg.html#c.PyArg_UnpackTuple" title="PyArg_UnpackTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_UnpackTuple()</span></code></a>, has been
added that’s simpler and presumably faster.  Instead of specifying a format
string, the caller simply gives the minimum and maximum number of arguments
expected, and a set of pointers to <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject*</span></code></a> variables that will be
filled in with argument values.</p>
</li>
<li><p class="first">Two new flags <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a> and <a class="reference internal" href="../c-api/structures.html#METH_O" title="METH_O"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_O</span></code></a> are available in method
definition tables to simplify implementation of methods with no arguments or a
single untyped argument. Calling such methods is more efficient than calling a
corresponding method that uses <a class="reference internal" href="../c-api/structures.html#METH_VARARGS" title="METH_VARARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_VARARGS</span></code></a>.  Also, the old
<a class="reference internal" href="../c-api/structures.html#METH_OLDARGS" title="METH_OLDARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_OLDARGS</span></code></a> style of writing C methods is  now officially deprecated.</p>
</li>
<li><p class="first">Two new wrapper functions, <a class="reference internal" href="../c-api/conversion.html#c.PyOS_snprintf" title="PyOS_snprintf"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_snprintf()</span></code></a> and <a class="reference internal" href="../c-api/conversion.html#c.PyOS_vsnprintf" title="PyOS_vsnprintf"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_vsnprintf()</span></code></a>
were added to provide  cross-platform implementations for the relatively new
<code class="xref c c-func docutils literal notranslate"><span class="pre">snprintf()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">vsnprintf()</span></code> C lib APIs. In contrast to the standard
<code class="xref c c-func docutils literal notranslate"><span class="pre">sprintf()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">vsprintf()</span></code> functions, the Python versions check the
bounds of the buffer used to protect against buffer overruns. (Contributed by
M.-A. Lemburg.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../c-api/tuple.html#c._PyTuple_Resize" title="_PyTuple_Resize"><code class="xref c c-func docutils literal notranslate"><span class="pre">_PyTuple_Resize()</span></code></a> function has lost an unused parameter, so now it
takes 2 parameters instead of 3.  The third argument was never used, and can
simply be discarded when porting code from earlier versions to Python 2.2.</p>
</li>
</ul>
</div>
<div class="section" id="other-changes-and-fixes">
<h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<p>As usual there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 527 patches applied and 683 bugs fixed between Python 2.1 and 2.2; 2.2.1
applied 139 patches and fixed 143 bugs; 2.2.2 applied 106 patches and fixed 82
bugs.  These figures are likely to be underestimates.</p>
<p>Some of the more notable changes are:</p>
<ul>
<li><p class="first">The code for the MacOS port for Python, maintained by Jack Jansen, is now kept
in the main Python CVS tree, and many changes have been made to support MacOS X.</p>
<p>The most significant change is the ability to build Python as a framework,
enabled by supplying the <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-framework</span></code> option to the configure
script when compiling Python.  According to Jack Jansen, “This installs a
self-contained Python installation plus the OS X framework “glue” into
<code class="file docutils literal notranslate"><span class="pre">/Library/Frameworks/Python.framework</span></code> (or another location of choice).
For now there is little immediate added benefit to this (actually, there is the
disadvantage that you have to change your PATH to be able to find Python), but
it is the basis for creating a full-blown Python application, porting the
MacPython IDE, possibly using Python as a standard OSA scripting language and
much more.”</p>
<p>Most of the MacPython toolbox modules, which interface to MacOS APIs such as
windowing, QuickTime, scripting, etc. have been ported to OS X, but they’ve been
left commented out in <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code>.  People who want to experiment with
these modules can uncomment them manually.</p>
</li>
<li><p class="first">Keyword arguments passed to built-in functions that don’t take them now cause a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception to be raised, with the message “<em>function</em> takes no
keyword arguments”.</p>
</li>
<li><p class="first">Weak references, added in Python 2.1 as an extension module, are now part of
the core because they’re used in the implementation of new-style classes.  The
<a class="reference internal" href="../library/exceptions.html#exceptions.ReferenceError" title="exceptions.ReferenceError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ReferenceError</span></code></a> exception has therefore moved from the <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a>
module to become a built-in exception.</p>
</li>
<li><p class="first">A new script, <code class="file docutils literal notranslate"><span class="pre">Tools/scripts/cleanfuture.py</span></code> by Tim Peters,
automatically removes obsolete <code class="docutils literal notranslate"><span class="pre">__future__</span></code> statements from Python source
code.</p>
</li>
<li><p class="first">An additional <em>flags</em> argument has been added to the built-in function
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a>, so the behaviour of <code class="docutils literal notranslate"><span class="pre">__future__</span></code> statements can now be
correctly observed in simulated shells, such as those presented by IDLE and
other development environments.  This is described in <span class="target" id="index-22"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0264"><strong>PEP 264</strong></a>. (Contributed
by Michael Hudson.)</p>
</li>
<li><p class="first">The new license introduced with Python 1.6 wasn’t GPL-compatible.  This is
fixed by some minor textual changes to the 2.2 license, so it’s now legal to
embed Python inside a GPLed program again.  Note that Python itself is not
GPLed, but instead is under a license that’s essentially equivalent to the BSD
license, same as it always was.  The license changes were also applied to the
Python 2.0.1 and 2.1.1 releases.</p>
</li>
<li><p class="first">When presented with a Unicode filename on Windows, Python will now convert it
to an MBCS encoded string, as used by the Microsoft file APIs.  As MBCS is
explicitly used by the file APIs, Python’s choice of ASCII as the default
encoding turns out to be an annoyance.  On Unix, the locale’s character set is
used if <code class="docutils literal notranslate"><span class="pre">locale.nl_langinfo(CODESET)</span></code> is available.  (Windows support was
contributed by Mark Hammond with assistance from Marc-André Lemburg. Unix
support was added by Martin von Löwis.)</p>
</li>
<li><p class="first">Large file support is now enabled on Windows.  (Contributed by Tim Peters.)</p>
</li>
<li><p class="first">The <code class="file docutils literal notranslate"><span class="pre">Tools/scripts/ftpmirror.py</span></code> script now parses a <code class="file docutils literal notranslate"><span class="pre">.netrc</span></code>
file, if you have one. (Contributed by Mike Romberg.)</p>
</li>
<li><p class="first">Some features of the object returned by the <a class="reference internal" href="../library/functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> function are now
deprecated, and trigger warnings when they’re accessed; they’ll disappear in
Python 2.3. <a class="reference internal" href="../library/functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a> objects tried to pretend they were full sequence
types by supporting slicing, sequence multiplication, and the <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>
operator, but these features were rarely used and therefore buggy.  The
<code class="xref py py-meth docutils literal notranslate"><span class="pre">tolist()</span></code> method and the <code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code>
attributes are also being deprecated.  At the C level, the fourth argument to
the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyRange_New()</span></code> function, <code class="docutils literal notranslate"><span class="pre">repeat</span></code>, has also been deprecated.</p>
</li>
<li><p class="first">There were a bunch of patches to the dictionary implementation, mostly to fix
potential core dumps if a dictionary contains objects that sneakily changed
their hash value, or mutated the dictionary they were contained in. For a while
python-dev fell into a gentle rhythm of Michael Hudson finding a case that
dumped core, Tim Peters fixing the bug, Michael finding another case, and round
and round it went.</p>
</li>
<li><p class="first">On Windows, Python can now be compiled with Borland C thanks to a number of
patches contributed by Stephen Hansen, though the result isn’t fully functional
yet.  (But this <em>is</em> progress…)</p>
</li>
<li><p class="first">Another Windows enhancement: Wise Solutions generously offered PythonLabs use
of their InstallerMaster 8.1 system.  Earlier PythonLabs Windows installers used
Wise 5.0a, which was beginning to show its age.  (Packaged up by Tim Peters.)</p>
</li>
<li><p class="first">Files ending in <code class="docutils literal notranslate"><span class="pre">.pyw</span></code> can now be imported on Windows. <code class="docutils literal notranslate"><span class="pre">.pyw</span></code> is a
Windows-only thing, used to indicate that a script needs to be run using
PYTHONW.EXE instead of PYTHON.EXE in order to prevent a DOS console from popping
up to display the output.  This patch makes it possible to import such scripts,
in case they’re also usable as modules.  (Implemented by David Bolen.)</p>
</li>
<li><p class="first">On platforms where Python uses the C <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> function  to load
extension modules, it’s now possible to set the flags used  by <code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code>
using the <a class="reference internal" href="../library/sys.html#sys.getdlopenflags" title="sys.getdlopenflags"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getdlopenflags()</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.setdlopenflags" title="sys.setdlopenflags"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.setdlopenflags()</span></code></a> functions.
(Contributed by Bram Stolk.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> built-in function no longer supports 3 arguments when
floating-point numbers are supplied. <code class="docutils literal notranslate"><span class="pre">pow(x,</span> <span class="pre">y,</span> <span class="pre">z)</span></code> returns <code class="docutils literal notranslate"><span class="pre">(x**y)</span> <span class="pre">%</span> <span class="pre">z</span></code>,
but this is never useful for floating point numbers, and the final result varies
unpredictably depending on the platform.  A call such as <code class="docutils literal notranslate"><span class="pre">pow(2.0,</span> <span class="pre">8.0,</span> <span class="pre">7.0)</span></code>
will now raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.</p>
</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Fred Bremmer,
Keith Briggs, Andrew Dalke, Fred L. Drake, Jr., Carel Fellinger, David Goodger,
Mark Hammond, Stephen Hansen, Michael Hudson, Jack Jansen, Marc-André Lemburg,
Martin von Löwis, Fredrik Lundh, Michael McLay, Nick Mathewson, Paul Moore,
Gustavo Niemeyer, Don O’Donnell, Joonas Paalasma, Tim Peters, Jens Quade, Tom
Reinhardt, Neil Schemenauer, Guido van Rossum, Greg Ward, Edward Welbourne.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.2</a><ul>
<li><a class="reference internal" href="#introduction">Introduction</a></li>
<li><a class="reference internal" href="#peps-252-and-253-type-and-class-changes">PEPs 252 and 253: Type and Class Changes</a><ul>
<li><a class="reference internal" href="#old-and-new-classes">Old and New Classes</a></li>
<li><a class="reference internal" href="#descriptors">Descriptors</a></li>
<li><a class="reference internal" href="#multiple-inheritance-the-diamond-rule">Multiple Inheritance: The Diamond Rule</a></li>
<li><a class="reference internal" href="#attribute-access">Attribute Access</a></li>
<li><a class="reference internal" href="#related-links">Related Links</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-234-iterators">PEP 234: Iterators</a></li>
<li><a class="reference internal" href="#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li><a class="reference internal" href="#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li><a class="reference internal" href="#pep-238-changing-the-division-operator">PEP 238: Changing the Division Operator</a></li>
<li><a class="reference internal" href="#unicode-changes">Unicode Changes</a></li>
<li><a class="reference internal" href="#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a></li>
<li><a class="reference internal" href="#interpreter-changes-and-fixes">Interpreter Changes and Fixes</a></li>
<li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.3.html"
                        title="previous chapter">What’s New in Python 2.3</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.1.html"
                        title="next chapter">What’s New in Python 2.1</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.2.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.1.html" title="What’s New in Python 2.1"
             >next</a> |</li>
        <li class="right" >
          <a href="2.3.html" title="What’s New in Python 2.3"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\;J�>�>�html/whatsnew/2.3.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.3 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.2" href="2.2.html" />
    <link rel="prev" title="What’s New in Python 2.4" href="2.4.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.3.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.2.html" title="What’s New in Python 2.2"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-3">
<h1>What’s New in Python 2.3<a class="headerlink" href="#what-s-new-in-python-2-3" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.3.  Python 2.3 was released
on July 29, 2003.</p>
<p>The main themes for Python 2.3 are polishing some of the features added in 2.2,
adding various small but useful enhancements to the core language, and expanding
the standard library.  The new object model introduced in the previous version
has benefited from 18 months of bugfixes and from optimization efforts that have
improved the performance of new-style classes.  A few new built-in functions
have been added such as <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> and <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>.  The <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a>
operator can now be used for substring searches (e.g. <code class="docutils literal notranslate"><span class="pre">&quot;ab&quot;</span> <span class="pre">in</span> <span class="pre">&quot;abc&quot;</span></code> returns
<a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>).</p>
<p>Some of the many new library features include Boolean, set, heap, and date/time
data types, the ability to import modules from ZIP-format archives, metadata
support for the long-awaited Python catalog, an updated version of IDLE, and
modules for logging messages, wrapping text, parsing CSV files, processing
command-line options, using BerkeleyDB databases…  the list of new and
enhanced modules is lengthy.</p>
<p>This article doesn’t attempt to provide a complete specification of the new
features, but instead provides a convenient overview.  For full details, you
should refer to the documentation for Python 2.3, such as the Python Library
Reference and the Python Reference Manual.  If you want to understand the
complete implementation and design rationale, refer to the PEP for a particular
new feature.</p>
<div class="section" id="pep-218-a-standard-set-datatype">
<h2>PEP 218: A Standard Set Datatype<a class="headerlink" href="#pep-218-a-standard-set-datatype" title="Permalink to this headline">¶</a></h2>
<p>The new <a class="reference internal" href="../library/sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module contains an implementation of a set datatype.  The
<code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code> class is for mutable sets, sets that can have members added and
removed.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code> class is for sets that can’t be modified,
and instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code> can therefore be used as dictionary keys.
Sets are built on top of dictionaries, so the elements within a set must be
hashable.</p>
<p>Here’s a simple example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sets</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S</span>
<span class="go">Set([1, 2, 3])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="ow">in</span> <span class="n">S</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mi">0</span> <span class="ow">in</span> <span class="n">S</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S</span>
<span class="go">Set([1, 2, 5])</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The union and intersection of sets can be computed with the <code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code> methods; an alternative notation uses the bitwise operators
<code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code>. Mutable sets also have in-place versions of these methods,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">union_update()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">union</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">|</span> <span class="n">S2</span>                  <span class="c1"># Alternative notation</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">&amp;</span> <span class="n">S2</span>                  <span class="c1"># Alternative notation</span>
<span class="go">Set([])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">union_update</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span>
<span class="go">Set([1, 2, 3, 4, 5, 6])</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>It’s also possible to take the symmetric difference of two sets.  This is the
set of all elements in the union that aren’t in the intersection.  Another way
of putting it is that the symmetric difference contains all elements that are in
exactly one set.  Again, there’s an alternative notation (<code class="docutils literal notranslate"><span class="pre">^</span></code>), and an
in-place version with the ungainly name <code class="xref py py-meth docutils literal notranslate"><span class="pre">symmetric_difference_update()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">symmetric_difference</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">Set([1, 2, 5, 6])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">^</span> <span class="n">S2</span>
<span class="go">Set([1, 2, 5, 6])</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>There are also <code class="xref py py-meth docutils literal notranslate"><span class="pre">issubset()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">issuperset()</span></code> methods for checking
whether one set is a subset or superset of another:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span> <span class="o">=</span> <span class="n">sets</span><span class="o">.</span><span class="n">Set</span><span class="p">([</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S2</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">issubset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">S1</span><span class="o">.</span><span class="n">issuperset</span><span class="p">(</span><span class="n">S2</span><span class="p">)</span>
<span class="go">True</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0218"><strong>PEP 218</strong></a> - Adding a Built-In Set Object Type</dt>
<dd>PEP written by Greg V. Wilson. Implemented by Greg V. Wilson, Alex Martelli, and
GvR.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-255-simple-generators">
<span id="section-generators"></span><h2>PEP 255: Simple Generators<a class="headerlink" href="#pep-255-simple-generators" title="Permalink to this headline">¶</a></h2>
<p>In Python 2.2, generators were added as an optional feature, to be enabled by a
<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">generators</span></code> directive.  In 2.3 generators no longer
need to be specially enabled, and are now always present; this means that
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> is now always a keyword.  The rest of this section is a copy of
the description of generators from the “What’s New in Python 2.2” document; if
you read it back when Python 2.2 came out, you can skip the rest of this
section.</p>
<p>You’re doubtless familiar with how function calls work in Python or C. When you
call a function, it gets a private namespace where its local variables are
created.  When the function reaches a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, the local
variables are destroyed and the resulting value is returned to the caller.  A
later call to the same function will get a fresh new set of local variables.
But, what if the local variables weren’t thrown away on exiting a function?
What if you could later resume the function where it left off?  This is what
generators provide; they can be thought of as resumable functions.</p>
<p>Here’s the simplest example of a generator function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">generate_ints</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">N</span><span class="p">):</span>
        <span class="k">yield</span> <span class="n">i</span>
</pre></div>
</div>
<p>A new keyword, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>, was introduced for generators.  Any function
containing a <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is a generator function; this is
detected by Python’s bytecode compiler which compiles the function specially as
a result.</p>
<p>When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol.  On executing
the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the generator outputs the value of <code class="docutils literal notranslate"><span class="pre">i</span></code>,
similar to a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement.  The big difference between
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> and a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement is that on reaching a
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> the generator’s state of execution is suspended and local
variables are preserved.  On the next call to the generator’s <code class="docutils literal notranslate"><span class="pre">.next()</span></code>
method, the function will resume executing immediately after the
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement.  (For complicated reasons, the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
statement isn’t allowed inside the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> block of a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>…<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement; read <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> for a full explanation of the
interaction between <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> and exceptions.)</p>
<p>Here’s a sample usage of the <code class="xref py py-func docutils literal notranslate"><span class="pre">generate_ints()</span></code> generator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span> <span class="o">=</span> <span class="n">generate_ints</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span>
<span class="go">&lt;generator object at 0x8117f90&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">gen</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">2</span>, in <span class="n">generate_ints</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p>You could equally write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">generate_ints(5)</span></code>, or <code class="docutils literal notranslate"><span class="pre">a,b,c</span> <span class="pre">=</span>
<span class="pre">generate_ints(3)</span></code>.</p>
<p>Inside a generator function, the <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement can only be used
without a value, and signals the end of the procession of values; afterwards the
generator cannot return any further values. <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> with a value, such
as <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">5</span></code>, is a syntax error inside a generator function.  The end of the
generator’s results can also be indicated by raising <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>
manually, or by just letting the flow of execution fall off the bottom of the
function.</p>
<p>You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables.  For
example, returning a list of integers could be done by setting <code class="docutils literal notranslate"><span class="pre">self.count</span></code> to
0, and having the <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method increment <code class="docutils literal notranslate"><span class="pre">self.count</span></code> and return it.
However, for a moderately complicated generator, writing a corresponding class
would be much messier. <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> contains a number of
more interesting examples.  The simplest one implements an in-order traversal of
a tree using generators recursively.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># A recursive generator that generates Tree leaves in in-order.</span>
<span class="k">def</span> <span class="nf">inorder</span><span class="p">(</span><span class="n">t</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">t</span><span class="p">:</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">left</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
        <span class="k">yield</span> <span class="n">t</span><span class="o">.</span><span class="n">label</span>
        <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">inorder</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">right</span><span class="p">):</span>
            <span class="k">yield</span> <span class="n">x</span>
</pre></div>
</div>
<p>Two other examples in <code class="file docutils literal notranslate"><span class="pre">Lib/test/test_generators.py</span></code> produce solutions for
the N-Queens problem (placing $N$ queens on an $NxN$ chess board so that no
queen threatens another) and the Knight’s Tour (a route that takes a knight to
every square of an $NxN$ chessboard without visiting any square twice).</p>
<p>The idea of generators comes from other programming languages, especially Icon
(<a class="reference external" href="https://www.cs.arizona.edu/icon/">https://www.cs.arizona.edu/icon/</a>), where the idea of generators is central.  In
Icon, every expression and function call behaves like a generator.  One example
from “An Overview of the Icon Programming Language” at
<a class="reference external" href="https://www.cs.arizona.edu/icon/docs/ipd266.htm">https://www.cs.arizona.edu/icon/docs/ipd266.htm</a> gives an idea of what this looks
like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sentence</span> <span class="p">:</span><span class="o">=</span> <span class="s2">&quot;Store it in the neighboring harbor&quot;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">i</span> <span class="p">:</span><span class="o">=</span> <span class="n">find</span><span class="p">(</span><span class="s2">&quot;or&quot;</span><span class="p">,</span> <span class="n">sentence</span><span class="p">))</span> <span class="o">&gt;</span> <span class="mi">5</span> <span class="n">then</span> <span class="n">write</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>In Icon the <code class="xref py py-func docutils literal notranslate"><span class="pre">find()</span></code> function returns the indexes at which the substring
“or” is found: 3, 23, 33.  In the <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, <code class="docutils literal notranslate"><span class="pre">i</span></code> is first
assigned a value of 3, but 3 is less than 5, so the comparison fails, and Icon
retries it with the second value of 23.  23 is greater than 5, so the comparison
now succeeds, and the code prints the value 23 to the screen.</p>
<p>Python doesn’t go nearly as far as Icon in adopting generators as a central
concept.  Generators are considered part of the core Python language, but
learning or using them isn’t compulsory; if they don’t solve any problems that
you have, feel free to ignore them. One novel feature of Python’s interface as
compared to Icon’s is that a generator’s state is represented as a concrete
object (the iterator) that can be passed around to other functions or stored in
a data structure.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0255"><strong>PEP 255</strong></a> - Simple Generators</dt>
<dd>Written by Neil Schemenauer, Tim Peters, Magnus Lie Hetland.  Implemented mostly
by Neil Schemenauer and Tim Peters, with other fixes from the Python Labs crew.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-263-source-code-encodings">
<span id="section-encodings"></span><h2>PEP 263: Source Code Encodings<a class="headerlink" href="#pep-263-source-code-encodings" title="Permalink to this headline">¶</a></h2>
<p>Python source files can now be declared as being in different character set
encodings.  Encodings are declared by including a specially formatted comment in
the first or second line of the source file.  For example, a UTF-8 file can be
declared with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python</span>
<span class="c1"># -*- coding: UTF-8 -*-</span>
</pre></div>
</div>
<p>Without such an encoding declaration, the default encoding used is 7-bit ASCII.
Executing or importing modules that contain string literals with 8-bit
characters and have no encoding declaration will result in a
<a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> being signalled by Python 2.3; in 2.4 this will be a
syntax error.</p>
<p>The encoding declaration only affects Unicode string literals, which will be
converted to Unicode using the specified encoding.  Note that Python identifiers
are still restricted to ASCII characters, so you can’t have variable names that
use characters outside of the usual alphanumerics.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a> - Defining Python Source Code Encodings</dt>
<dd>Written by Marc-André Lemburg and Martin von Löwis; implemented by Suzuki Hisao
and Martin von Löwis.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-273-importing-modules-from-zip-archives">
<h2>PEP 273: Importing Modules from ZIP Archives<a class="headerlink" href="#pep-273-importing-modules-from-zip-archives" title="Permalink to this headline">¶</a></h2>
<p>The new <a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module adds support for importing modules from a
ZIP-format archive.  You don’t need to import the module explicitly; it will be
automatically imported if a ZIP archive’s filename is added to <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.
For example:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">amk@nyman:~/src/python$</span> unzip -l /tmp/example.zip
<span class="go">Archive:  /tmp/example.zip</span>
<span class="go">  Length     Date   Time    Name</span>
<span class="go"> --------    ----   ----    ----</span>
<span class="go">     8467  11-26-02 22:30   jwzthreading.py</span>
<span class="go"> --------                   -------</span>
<span class="go">     8467                   1 file</span>
<span class="gp">amk@nyman:~/src/python$</span> ./python
<span class="go">Python 2.3 (#1, Aug 1 2003, 19:54:32)</span>
<span class="gp">&gt;</span>&gt;&gt; import sys
<span class="gp">&gt;</span>&gt;&gt; sys.path.insert<span class="o">(</span><span class="m">0</span>, <span class="s1">&#39;/tmp/example.zip&#39;</span><span class="o">)</span>  <span class="c1"># Add .zip file to front of path</span>
<span class="gp">&gt;</span>&gt;&gt; import jwzthreading
<span class="gp">&gt;</span>&gt;&gt; jwzthreading.__file__
<span class="go">&#39;/tmp/example.zip/jwzthreading.py&#39;</span>
<span class="gp">&gt;</span>&gt;&gt;
</pre></div>
</div>
<p>An entry in <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> can now be the filename of a ZIP archive. The ZIP
archive can contain any kind of files, but only files named <code class="file docutils literal notranslate"><span class="pre">*.py</span></code>,
<code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code>, or <code class="file docutils literal notranslate"><span class="pre">*.pyo</span></code> can be imported.  If an archive only contains
<code class="file docutils literal notranslate"><span class="pre">*.py</span></code> files, Python will not attempt to modify the archive by adding the
corresponding <code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code> file, meaning that if a ZIP archive doesn’t contain
<code class="file docutils literal notranslate"><span class="pre">*.pyc</span></code> files, importing may be rather slow.</p>
<p>A path within the archive can also be specified to only import from a
subdirectory; for example, the path <code class="file docutils literal notranslate"><span class="pre">/tmp/example.zip/lib/</span></code> would only
import from the <code class="file docutils literal notranslate"><span class="pre">lib/</span></code> subdirectory within the archive.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0273"><strong>PEP 273</strong></a> - Import Modules from Zip Archives</dt>
<dd>Written by James C. Ahlstrom,  who also provided an implementation. Python 2.3
follows the specification in <span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0273"><strong>PEP 273</strong></a>,  but uses an implementation written by
Just van Rossum  that uses the import hooks described in <span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a>. See section
<a class="reference internal" href="#section-pep302"><span class="std std-ref">PEP 302: New Import Hooks</span></a> for a description of the new import hooks.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-277-unicode-file-name-support-for-windows-nt">
<h2>PEP 277: Unicode file name support for Windows NT<a class="headerlink" href="#pep-277-unicode-file-name-support-for-windows-nt" title="Permalink to this headline">¶</a></h2>
<p>On Windows NT, 2000, and XP, the system stores file names as Unicode strings.
Traditionally, Python has represented file names as byte strings, which is
inadequate because it renders some file names inaccessible.</p>
<p>Python now allows using arbitrary Unicode strings (within the limitations of the
file system) for all functions that expect file names, most notably the
<a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> built-in function. If a Unicode string is passed to
<a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a>, Python now returns a list of Unicode strings.  A new
function, <a class="reference internal" href="../library/os.html#os.getcwdu" title="os.getcwdu"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.getcwdu()</span></code></a>, returns the current directory as a Unicode string.</p>
<p>Byte strings still work as file names, and on Windows Python will transparently
convert them to Unicode using the <code class="docutils literal notranslate"><span class="pre">mbcs</span></code> encoding.</p>
<p>Other systems also allow Unicode strings as file names but convert them to byte
strings before passing them to the system, which can cause a <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>
to be raised. Applications can test whether arbitrary Unicode strings are
supported as file names by checking <a class="reference internal" href="../library/os.path.html#os.path.supports_unicode_filenames" title="os.path.supports_unicode_filenames"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.path.supports_unicode_filenames</span></code></a>,
a Boolean value.</p>
<p>Under MacOS, <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> may now return Unicode filenames.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0277"><strong>PEP 277</strong></a> - Unicode file name support for Windows NT</dt>
<dd>Written by Neil Hodgson; implemented by Neil Hodgson, Martin von Löwis, and Mark
Hammond.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-278-universal-newline-support">
<span id="index-8"></span><h2>PEP 278: Universal Newline Support<a class="headerlink" href="#pep-278-universal-newline-support" title="Permalink to this headline">¶</a></h2>
<p>The three major operating systems used today are Microsoft Windows, Apple’s
Macintosh OS, and the various Unix derivatives.  A minor irritation of
cross-platform work  is that these three platforms all use different characters to
mark the ends of lines in text files.  Unix uses the linefeed (ASCII character
10), MacOS uses the carriage return (ASCII character 13), and Windows uses a
two-character sequence of a carriage return plus a newline.</p>
<p>Python’s file objects can now support end of line conventions other than the
one followed by the platform on which Python is running. Opening a file with
the mode <code class="docutils literal notranslate"><span class="pre">'U'</span></code> or <code class="docutils literal notranslate"><span class="pre">'rU'</span></code> will open a file for reading in <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal
newlines</span></a> mode.  All three line ending conventions will be translated to a
<code class="docutils literal notranslate"><span class="pre">'\n'</span></code> in the strings returned by the various file methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>.</p>
<p>Universal newline support is also used when importing modules and when executing
a file with the <a class="reference internal" href="../library/functions.html#execfile" title="execfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">execfile()</span></code></a> function.  This means that Python modules can
be shared between all three operating systems without needing to convert the
line-endings.</p>
<p>This feature can be disabled when compiling Python by specifying the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--without-universal-newlines</span></code> switch when running Python’s
<strong class="program">configure</strong> script.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0278"><strong>PEP 278</strong></a> - Universal Newline Support</dt>
<dd>Written and implemented by Jack Jansen.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-279-enumerate">
<span id="section-enumerate"></span><h2>PEP 279: enumerate()<a class="headerlink" href="#pep-279-enumerate" title="Permalink to this headline">¶</a></h2>
<p>A new built-in function, <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a>, will make certain loops a bit
clearer.  <code class="docutils literal notranslate"><span class="pre">enumerate(thing)</span></code>, where <em>thing</em> is either an iterator or a
sequence, returns an iterator that will return <code class="docutils literal notranslate"><span class="pre">(0,</span> <span class="pre">thing[0])</span></code>, <code class="docutils literal notranslate"><span class="pre">(1,</span>
<span class="pre">thing[1])</span></code>, <code class="docutils literal notranslate"><span class="pre">(2,</span> <span class="pre">thing[2])</span></code>, and so forth.</p>
<p>A common idiom to change every element of a list looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">L</span><span class="p">)):</span>
    <span class="n">item</span> <span class="o">=</span> <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
    <span class="c1"># ... compute some result based on item ...</span>
    <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
</pre></div>
</div>
<p>This can be rewritten using <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">item</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">L</span><span class="p">):</span>
    <span class="c1"># ... compute some result based on item ...</span>
    <span class="n">L</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">result</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0279"><strong>PEP 279</strong></a> - The enumerate() built-in function</dt>
<dd>Written and implemented by Raymond D. Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-282-the-logging-package">
<h2>PEP 282: The logging Package<a class="headerlink" href="#pep-282-the-logging-package" title="Permalink to this headline">¶</a></h2>
<p>A standard package for writing logs, <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a>, has been added to Python
2.3.  It provides a powerful and flexible mechanism for generating logging
output which can then be filtered and processed in various ways.  A
configuration file written in a standard format can be used to control the
logging behavior of a program.  Python includes handlers that will write log
records to standard error or to a file or socket, send them to the system log,
or even e-mail them to a particular address; of course, it’s also possible to
write your own handler classes.</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> class is the primary class. Most application code will deal
with one or more <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> objects, each one used by a particular
subsystem of the application. Each <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> is identified by a name, and
names are organized into a hierarchy using <code class="docutils literal notranslate"><span class="pre">.</span></code>  as the component separator.
For example, you might have <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> instances named <code class="docutils literal notranslate"><span class="pre">server</span></code>,
<code class="docutils literal notranslate"><span class="pre">server.auth</span></code> and <code class="docutils literal notranslate"><span class="pre">server.network</span></code>.  The latter two instances are below
<code class="docutils literal notranslate"><span class="pre">server</span></code> in the hierarchy.  This means that if you turn up the verbosity for
<code class="docutils literal notranslate"><span class="pre">server</span></code> or direct <code class="docutils literal notranslate"><span class="pre">server</span></code> messages to a different handler, the changes
will also apply to records logged to <code class="docutils literal notranslate"><span class="pre">server.auth</span></code> and <code class="docutils literal notranslate"><span class="pre">server.network</span></code>.
There’s also a root <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> that’s the parent of all other loggers.</p>
<p>For simple uses, the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package contains some convenience functions
that always use the root log:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>

<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">&#39;Debugging information&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Informational message&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">&#39;Warning:config file </span><span class="si">%s</span><span class="s1"> not found&#39;</span><span class="p">,</span> <span class="s1">&#39;server.conf&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Error occurred&#39;</span><span class="p">)</span>
<span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Critical error -- shutting down&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">WARNING</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="ne">Warning</span><span class="p">:</span><span class="n">config</span> <span class="n">file</span> <span class="n">server</span><span class="o">.</span><span class="n">conf</span> <span class="ow">not</span> <span class="n">found</span>
<span class="n">ERROR</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Error</span> <span class="n">occurred</span>
<span class="n">CRITICAL</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Critical</span> <span class="n">error</span> <span class="o">--</span> <span class="n">shutting</span> <span class="n">down</span>
</pre></div>
</div>
<p>In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable the display
of informational and debugging messages by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">setLevel()</span></code> method
on the root logger.</p>
<p>Notice the <code class="xref py py-func docutils literal notranslate"><span class="pre">warning()</span></code> call’s use of string formatting operators; all of the
functions for logging messages take the arguments <code class="docutils literal notranslate"><span class="pre">(msg,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> and
log the string resulting from <code class="docutils literal notranslate"><span class="pre">msg</span> <span class="pre">%</span> <span class="pre">(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code>.</p>
<p>There’s also an <code class="xref py py-func docutils literal notranslate"><span class="pre">exception()</span></code> function that records the most recent
traceback.  Any of the other functions will also record the traceback if you
specify a true value for the keyword argument <em>exc_info</em>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span>
    <span class="k">try</span><span class="p">:</span>    <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
    <span class="k">except</span><span class="p">:</span> <span class="n">logging</span><span class="o">.</span><span class="n">exception</span><span class="p">(</span><span class="s1">&#39;Problem recorded&#39;</span><span class="p">)</span>

<span class="n">f</span><span class="p">()</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ERROR</span><span class="p">:</span><span class="n">root</span><span class="p">:</span><span class="n">Problem</span> <span class="n">recorded</span>
<span class="n">Traceback</span> <span class="p">(</span><span class="n">most</span> <span class="n">recent</span> <span class="n">call</span> <span class="n">last</span><span class="p">):</span>
  <span class="n">File</span> <span class="s2">&quot;t.py&quot;</span><span class="p">,</span> <span class="n">line</span> <span class="mi">6</span><span class="p">,</span> <span class="ow">in</span> <span class="n">f</span>
    <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
<span class="ne">ZeroDivisionError</span><span class="p">:</span> <span class="n">integer</span> <span class="n">division</span> <span class="ow">or</span> <span class="n">modulo</span> <span class="n">by</span> <span class="n">zero</span>
</pre></div>
</div>
<p>Slightly more advanced programs will use a logger other than the root logger.
The <code class="docutils literal notranslate"><span class="pre">getLogger(name)</span></code> function is used to get a particular log, creating
it if it doesn’t exist yet. <code class="docutils literal notranslate"><span class="pre">getLogger(None)</span></code> returns the root logger.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">log</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
 <span class="o">...</span>
<span class="n">log</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">&#39;Listening on port </span><span class="si">%i</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
 <span class="o">...</span>
<span class="n">log</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">&#39;Disk full&#39;</span><span class="p">)</span>
 <span class="o">...</span>
</pre></div>
</div>
<p>Log records are usually propagated up the hierarchy, so a message logged to
<code class="docutils literal notranslate"><span class="pre">server.auth</span></code> is also seen by <code class="docutils literal notranslate"><span class="pre">server</span></code> and <code class="docutils literal notranslate"><span class="pre">root</span></code>, but a <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code>
can prevent this by setting its <code class="xref py py-attr docutils literal notranslate"><span class="pre">propagate</span></code> attribute to <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
<p>There are more classes provided by the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package that can be
customized.  When a <code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code> instance is told to log a message, it
creates a <code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code> instance that is sent to any number of different
<code class="xref py py-class docutils literal notranslate"><span class="pre">Handler</span></code> instances.  Loggers and handlers can also have an attached list
of filters, and each filter can cause the <code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code> to be ignored or
can modify the record before passing it along.  When they’re finally output,
<code class="xref py py-class docutils literal notranslate"><span class="pre">LogRecord</span></code> instances are converted to text by a <code class="xref py py-class docutils literal notranslate"><span class="pre">Formatter</span></code>
class.  All of these classes can be replaced by your own specially-written
classes.</p>
<p>With all of these features the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package should provide enough
flexibility for even the most complicated applications.  This is only an
incomplete overview of its features, so please see the package’s reference
documentation for all of the details.  Reading <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> will also be helpful.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0282"><strong>PEP 282</strong></a> - A Logging System</dt>
<dd>Written by Vinay Sajip and Trent Mick; implemented by Vinay Sajip.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-285-a-boolean-type">
<span id="section-bool"></span><h2>PEP 285: A Boolean Type<a class="headerlink" href="#pep-285-a-boolean-type" title="Permalink to this headline">¶</a></h2>
<p>A Boolean type was added to Python 2.3.  Two new constants were added to the
<a class="reference internal" href="../library/__builtin__.html#module-__builtin__" title="__builtin__: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__builtin__</span></code></a> module, <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.  (<a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and
<a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> constants were added to the built-ins in Python 2.2.1, but the
2.2.1 versions are simply set to integer values of 1 and 0 and aren’t a
different type.)</p>
<p>The type object for this new type is named <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>; the constructor for it
takes any Python value and converts it to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> or <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">([])</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bool</span><span class="p">(</span> <span class="p">(</span><span class="mi">1</span><span class="p">,)</span> <span class="p">)</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Most of the standard library modules and built-in functions have been changed to
return Booleans.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">obj</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s1">&#39;append&#39;</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">list</span><span class="p">)</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">)</span>
<span class="go">False</span>
</pre></div>
</div>
<p>Python’s Booleans were added with the primary goal of making code clearer.  For
example, if you’re reading a function and encounter the statement <code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">1</span></code>,
you might wonder whether the <code class="docutils literal notranslate"><span class="pre">1</span></code> represents a Boolean truth value, an index,
or a coefficient that multiplies some other quantity.  If the statement is
<code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">True</span></code>, however, the meaning of the return value is quite clear.</p>
<p>Python’s Booleans were <em>not</em> added for the sake of strict type-checking.  A very
strict language such as Pascal would also prevent you performing arithmetic with
Booleans, and would require that the expression in an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement
always evaluate to a Boolean result.  Python is not this strict and never will
be, as <span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0285"><strong>PEP 285</strong></a> explicitly says.  This means you can still use any expression
in an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement, even ones that evaluate to a list or tuple or
some random object.  The Boolean type is a subclass of the <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> class so
that arithmetic using a Boolean still works.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kc">True</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kc">False</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kc">False</span> <span class="o">*</span> <span class="mi">75</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kc">True</span> <span class="o">*</span> <span class="mi">75</span>
<span class="go">75</span>
</pre></div>
</div>
<p>To sum up <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> in a sentence: they’re alternative
ways to spell the integer values 1 and 0, with the single difference that
<a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> and <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> return the strings <code class="docutils literal notranslate"><span class="pre">'True'</span></code> and <code class="docutils literal notranslate"><span class="pre">'False'</span></code>
instead of <code class="docutils literal notranslate"><span class="pre">'1'</span></code> and <code class="docutils literal notranslate"><span class="pre">'0'</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0285"><strong>PEP 285</strong></a> - Adding a bool type</dt>
<dd>Written and implemented by GvR.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-293-codec-error-handling-callbacks">
<h2>PEP 293: Codec Error Handling Callbacks<a class="headerlink" href="#pep-293-codec-error-handling-callbacks" title="Permalink to this headline">¶</a></h2>
<p>When encoding a Unicode string into a byte string, unencodable characters may be
encountered.  So far, Python has allowed specifying the error processing as
either “strict” (raising <a class="reference internal" href="../library/exceptions.html#exceptions.UnicodeError" title="exceptions.UnicodeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">UnicodeError</span></code></a>), “ignore” (skipping the
character), or “replace” (using a question mark in the output string), with
“strict” being the default behavior. It may be desirable to specify alternative
processing of such errors, such as inserting an XML character reference or HTML
entity reference into the converted string.</p>
<p>Python now has a flexible framework to add different processing strategies.  New
error handlers can be added with <a class="reference internal" href="../library/codecs.html#codecs.register_error" title="codecs.register_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.register_error()</span></code></a>, and codecs then
can access the error handler with <a class="reference internal" href="../library/codecs.html#codecs.lookup_error" title="codecs.lookup_error"><code class="xref py py-func docutils literal notranslate"><span class="pre">codecs.lookup_error()</span></code></a>. An equivalent C
API has been added for codecs written in C. The error handler gets the necessary
state information such as the string being converted, the position in the string
where the error was detected, and the target encoding.  The handler can then
either raise an exception or return a replacement string.</p>
<p>Two additional error handlers have been implemented using this framework:
“backslashreplace” uses Python backslash quoting to represent unencodable
characters and “xmlcharrefreplace” emits XML character references.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0293"><strong>PEP 293</strong></a> - Codec Error Handling Callbacks</dt>
<dd>Written and implemented by Walter Dörwald.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-301-package-index-and-metadata-for-distutils">
<span id="section-pep301"></span><h2>PEP 301: Package Index and Metadata for Distutils<a class="headerlink" href="#pep-301-package-index-and-metadata-for-distutils" title="Permalink to this headline">¶</a></h2>
<p>Support for the long-requested Python catalog makes its first appearance in 2.3.</p>
<p>The heart of the catalog is the new Distutils <strong class="command">register</strong> command.
Running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span> <span class="pre">register</span></code> will collect the metadata describing a
package, such as its name, version, maintainer, description, &amp;c., and send it to
a central catalog server.  The resulting catalog is available from
<a class="reference external" href="https://pypi.org">https://pypi.org</a>.</p>
<p>To make the catalog a bit more useful, a new optional <em>classifiers</em> keyword
argument has been added to the Distutils <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function.  A list of
<a class="reference external" href="http://catb.org/~esr/trove/">Trove</a>-style strings can be supplied to help
classify the software.</p>
<p>Here’s an example <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> with classifiers, written to be compatible
with older versions of the Distutils:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils</span> <span class="k">import</span> <span class="n">core</span>
<span class="n">kw</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;name&#39;</span><span class="p">:</span> <span class="s2">&quot;Quixote&quot;</span><span class="p">,</span>
      <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="s2">&quot;0.5.1&quot;</span><span class="p">,</span>
      <span class="s1">&#39;description&#39;</span><span class="p">:</span> <span class="s2">&quot;A highly Pythonic Web application framework&quot;</span><span class="p">,</span>
      <span class="c1"># ...</span>
      <span class="p">}</span>

<span class="k">if</span> <span class="p">(</span><span class="nb">hasattr</span><span class="p">(</span><span class="n">core</span><span class="p">,</span> <span class="s1">&#39;setup_keywords&#39;</span><span class="p">)</span> <span class="ow">and</span>
    <span class="s1">&#39;classifiers&#39;</span> <span class="ow">in</span> <span class="n">core</span><span class="o">.</span><span class="n">setup_keywords</span><span class="p">):</span>
    <span class="n">kw</span><span class="p">[</span><span class="s1">&#39;classifiers&#39;</span><span class="p">]</span> <span class="o">=</span> \
        <span class="p">[</span><span class="s1">&#39;Topic :: Internet :: WWW/HTTP :: Dynamic Content&#39;</span><span class="p">,</span>
         <span class="s1">&#39;Environment :: No Input/Output (Daemon)&#39;</span><span class="p">,</span>
         <span class="s1">&#39;Intended Audience :: Developers&#39;</span><span class="p">],</span>

<span class="n">core</span><span class="o">.</span><span class="n">setup</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
</pre></div>
</div>
<p>The full list of classifiers can be obtained by running  <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">setup.py</span>
<span class="pre">register</span> <span class="pre">--list-classifiers</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0301"><strong>PEP 301</strong></a> - Package Index and Metadata for Distutils</dt>
<dd>Written and implemented by Richard Jones.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-302-new-import-hooks">
<span id="section-pep302"></span><h2>PEP 302: New Import Hooks<a class="headerlink" href="#pep-302-new-import-hooks" title="Permalink to this headline">¶</a></h2>
<p>While it’s been possible to write custom import hooks ever since the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> module was introduced in Python 1.3, no one has ever been really
happy with it because writing new import hooks is difficult and messy.  There
have been various proposed alternatives such as the <a class="reference internal" href="../library/imputil.html#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">iu</span></code>
modules, but none of them has ever gained much acceptance, and none of them were
easily usable from C code.</p>
<p><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> borrows ideas from its predecessors, especially from Gordon
McMillan’s <code class="xref py py-mod docutils literal notranslate"><span class="pre">iu</span></code> module.  Three new items  are added to the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>
module:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">sys.path_hooks</span></code> is a list of callable objects; most  often they’ll be
classes.  Each callable takes a string containing a path and either returns an
importer object that will handle imports from this path or raises an
<a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> exception if it can’t handle this path.</li>
<li><code class="docutils literal notranslate"><span class="pre">sys.path_importer_cache</span></code> caches importer objects for each path, so
<code class="docutils literal notranslate"><span class="pre">sys.path_hooks</span></code> will only need to be traversed once for each path.</li>
<li><code class="docutils literal notranslate"><span class="pre">sys.meta_path</span></code> is a list of importer objects that will be traversed before
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is checked.  This list is initially empty, but user code can add
objects to it.  Additional built-in and frozen modules can be imported by an
object added to this list.</li>
</ul>
<p>Importer objects must have a single method, <code class="docutils literal notranslate"><span class="pre">find_module(fullname,</span>
<span class="pre">path=None)</span></code>.  <em>fullname</em> will be a module or package name, e.g. <code class="docutils literal notranslate"><span class="pre">string</span></code> or
<code class="docutils literal notranslate"><span class="pre">distutils.core</span></code>.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">find_module()</span></code> must return a loader object that has a
single method, <code class="docutils literal notranslate"><span class="pre">load_module(fullname)</span></code>, that creates and returns the
corresponding module object.</p>
<p>Pseudo-code for Python’s new import logic, therefore, looks something like this
(simplified a bit; see <span class="target" id="index-18"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> for the full details):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">mp</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">meta_path</span><span class="p">:</span>
    <span class="n">loader</span> <span class="o">=</span> <span class="n">mp</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">loader</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>

<span class="k">for</span> <span class="n">path</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">hook</span> <span class="ow">in</span> <span class="n">sys</span><span class="o">.</span><span class="n">path_hooks</span><span class="p">:</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">importer</span> <span class="o">=</span> <span class="n">hook</span><span class="p">(</span><span class="n">path</span><span class="p">)</span>
        <span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
            <span class="c1"># ImportError, so try the other path hooks</span>
            <span class="k">pass</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">loader</span> <span class="o">=</span> <span class="n">importer</span><span class="o">.</span><span class="n">find_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>
            <span class="o">&lt;</span><span class="n">module</span><span class="o">&gt;</span> <span class="o">=</span> <span class="n">loader</span><span class="o">.</span><span class="n">load_module</span><span class="p">(</span><span class="n">fullname</span><span class="p">)</span>

<span class="c1"># Not found!</span>
<span class="k">raise</span> <span class="ne">ImportError</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-19"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0302"><strong>PEP 302</strong></a> - New Import Hooks</dt>
<dd>Written by Just van Rossum and Paul Moore. Implemented by Just van Rossum.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-305-comma-separated-files">
<span id="section-pep305"></span><h2>PEP 305: Comma-separated Files<a class="headerlink" href="#pep-305-comma-separated-files" title="Permalink to this headline">¶</a></h2>
<p>Comma-separated files are a format frequently used for exporting data from
databases and spreadsheets.  Python 2.3 adds a parser for comma-separated files.</p>
<p>Comma-separated format is deceptively simple at first glance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Costs</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span>
</pre></div>
</div>
<p>Read a line and call <code class="docutils literal notranslate"><span class="pre">line.split(',')</span></code>: what could be simpler? But toss in
string data that can contain commas, and things get more complicated:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="s2">&quot;Costs&quot;</span><span class="p">,</span><span class="mi">150</span><span class="p">,</span><span class="mi">200</span><span class="p">,</span><span class="mf">3.95</span><span class="p">,</span><span class="s2">&quot;Includes taxes, shipping, and sundry items&quot;</span>
</pre></div>
</div>
<p>A big ugly regular expression can parse this, but using the new  <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a>
package is much simpler:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">csv</span>

<span class="nb">input</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;datafile&#39;</span><span class="p">,</span> <span class="s1">&#39;rb&#39;</span><span class="p">)</span>
<span class="n">reader</span> <span class="o">=</span> <span class="n">csv</span><span class="o">.</span><span class="n">reader</span><span class="p">(</span><span class="nb">input</span><span class="p">)</span>
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">reader</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">line</span>
</pre></div>
</div>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">reader()</span></code> function takes a number of different options. The field
separator isn’t limited to the comma and can be changed to any character, and so
can the quoting and line-ending characters.</p>
<p>Different dialects of comma-separated files can be defined and registered;
currently there are two dialects, both used by Microsoft Excel. A separate
<a class="reference internal" href="../library/csv.html#csv.writer" title="csv.writer"><code class="xref py py-class docutils literal notranslate"><span class="pre">csv.writer</span></code></a> class will generate comma-separated files from a succession
of tuples or lists, quoting strings that contain the delimiter.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-20"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0305"><strong>PEP 305</strong></a> - CSV File API</dt>
<dd>Written and implemented  by Kevin Altis, Dave Cole, Andrew McNamara, Skip
Montanaro, Cliff Wells.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-307-pickle-enhancements">
<span id="section-pep307"></span><h2>PEP 307: Pickle Enhancements<a class="headerlink" href="#pep-307-pickle-enhancements" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> modules received some attention during the
2.3 development cycle.  In 2.2, new-style classes could be pickled without
difficulty, but they weren’t pickled very compactly; <span class="target" id="index-21"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> quotes a trivial
example where a new-style class results in a pickled string three times longer
than that for a classic class.</p>
<p>The solution was to invent a new pickle protocol.  The <a class="reference internal" href="../library/pickle.html#pickle.dumps" title="pickle.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">pickle.dumps()</span></code></a>
function has supported a text-or-binary flag  for a long time.  In 2.3, this
flag is redefined from a Boolean to an integer: 0 is the old text-mode pickle
format, 1 is the old binary format, and now 2 is a new 2.3-specific format.  A
new constant, <a class="reference internal" href="../library/pickle.html#pickle.HIGHEST_PROTOCOL" title="pickle.HIGHEST_PROTOCOL"><code class="xref py py-const docutils literal notranslate"><span class="pre">pickle.HIGHEST_PROTOCOL</span></code></a>, can be used to select the
fanciest protocol available.</p>
<p>Unpickling is no longer considered a safe operation.  2.2’s <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>
provided hooks for trying to prevent unsafe classes from being unpickled
(specifically, a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__safe_for_unpickling__</span></code> attribute), but none of this
code was ever audited and therefore it’s all been ripped out in 2.3.  You should
not unpickle untrusted data in any version of Python.</p>
<p>To reduce the pickling overhead for new-style classes, a new interface for
customizing pickling was added using three special methods:
<a class="reference internal" href="../library/pickle.html#object.__getstate__" title="object.__getstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getstate__()</span></code></a>, <a class="reference internal" href="../library/pickle.html#object.__setstate__" title="object.__setstate__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setstate__()</span></code></a>, and <a class="reference internal" href="../library/pickle.html#object.__getnewargs__" title="object.__getnewargs__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getnewargs__()</span></code></a>.  Consult
<span class="target" id="index-22"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> for the full semantics  of these methods.</p>
<p>As a way to compress pickles yet further, it’s now possible to use integer codes
instead of long strings to identify pickled classes. The Python Software
Foundation will maintain a list of standardized codes; there’s also a range of
codes for private use.  Currently no codes have been specified.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0307"><strong>PEP 307</strong></a> - Extensions to the pickle protocol</dt>
<dd>Written and implemented  by Guido van Rossum and Tim Peters.</dd>
</dl>
</div>
</div>
<div class="section" id="extended-slices">
<span id="section-slices"></span><h2>Extended Slices<a class="headerlink" href="#extended-slices" title="Permalink to this headline">¶</a></h2>
<p>Ever since Python 1.4, the slicing syntax has supported an optional third “step”
or “stride” argument.  For example, these are all legal Python syntax:
<code class="docutils literal notranslate"><span class="pre">L[1:10:2]</span></code>, <code class="docutils literal notranslate"><span class="pre">L[:-1:1]</span></code>, <code class="docutils literal notranslate"><span class="pre">L[::-1]</span></code>.  This was added to Python at the
request of the developers of Numerical Python, which uses the third argument
extensively.  However, Python’s built-in list, tuple, and string sequence types
have never supported this feature, raising a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if you tried it.
Michael Hudson contributed a patch to fix this shortcoming.</p>
<p>For example, you can now easily extract the elements of a list that have even
indexes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2, 4, 6, 8]</span>
</pre></div>
</div>
<p>Negative values also work to make a copy of the same list in reverse order:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]</span>
</pre></div>
</div>
<p>This also works for tuples, arrays, and strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;abcd&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">&#39;ac&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="go">&#39;dcba&#39;</span>
</pre></div>
</div>
<p>If you have a mutable sequence such as a list or an array you can assign to or
delete an extended slice, but there are some differences between assignment to
extended and regular slices.  Assignment to a regular slice can be used to
change the length of the sequence:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[0, 1, 2]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[0, 4, 5, 6]</span>
</pre></div>
</div>
<p>Extended slices aren’t this flexible.  When assigning to an extended slice, the
list on the right hand side of the statement must contain the same number of
items as the slice it is replacing:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[0, 1, 2, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[0, 1, -1, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">]</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">ValueError</span>: <span class="n">attempt to assign sequence of size 3 to extended slice of size 2</span>
</pre></div>
</div>
<p>Deletion is more straightforward:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">range</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[0, 1, 2, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="go">[0, 2]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">a</span><span class="p">[::</span><span class="mi">2</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">[1, 3]</span>
</pre></div>
</div>
<p>One can also now pass slice objects to the <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> methods of the
built-in sequences:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">(</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[0, 2, 4]</span>
</pre></div>
</div>
<p>Or use slice objects directly in subscripts:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)[</span><span class="nb">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">)]</span>
<span class="go">[0, 2, 4]</span>
</pre></div>
</div>
<p>To simplify implementing sequences that support extended slicing, slice objects
now have a method <code class="docutils literal notranslate"><span class="pre">indices(length)</span></code> which, given the length of a sequence,
returns a <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code> tuple that can be passed directly to
<a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a>. <code class="xref py py-meth docutils literal notranslate"><span class="pre">indices()</span></code> handles omitted and out-of-bounds indices in a
manner consistent with regular slices (and this innocuous phrase hides a welter
of confusing details!).  The method is intended to be used like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">FakeSeq</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">calc_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">i</span><span class="p">):</span>
        <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">item</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">item</span><span class="p">,</span> <span class="nb">slice</span><span class="p">):</span>
            <span class="n">indices</span> <span class="o">=</span> <span class="n">item</span><span class="o">.</span><span class="n">indices</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
            <span class="k">return</span> <span class="n">FakeSeq</span><span class="p">([</span><span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="o">*</span><span class="n">indices</span><span class="p">)])</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">calc_item</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>From this example you can also see that the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> object is
now the type object for the slice type, and is no longer a function.  This is
consistent with Python 2.2, where <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>, <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, etc., underwent
the same change.</p>
</div>
<div class="section" id="other-language-changes">
<h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Here are all of the changes that Python 2.3 makes to the core Python language.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is now always a keyword, as described in
section <a class="reference internal" href="#section-generators"><span class="std std-ref">PEP 255: Simple Generators</span></a> of this document.</p>
</li>
<li><p class="first">A new built-in function <a class="reference internal" href="../library/functions.html#enumerate" title="enumerate"><code class="xref py py-func docutils literal notranslate"><span class="pre">enumerate()</span></code></a> was added, as described in section
<a class="reference internal" href="#section-enumerate"><span class="std std-ref">PEP 279: enumerate()</span></a> of this document.</p>
</li>
<li><p class="first">Two new constants, <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> and <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> were added along with the
built-in <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a> type, as described in section <a class="reference internal" href="#section-bool"><span class="std std-ref">PEP 285: A Boolean Type</span></a> of this
document.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type constructor will now return a long integer instead of
raising an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> when a string or floating-point number is too
large to fit into an integer.  This can lead to the paradoxical result that
<code class="docutils literal notranslate"><span class="pre">isinstance(int(expression),</span> <span class="pre">int)</span></code> is false, but that seems unlikely to cause
problems in practice.</p>
</li>
<li><p class="first">Built-in types now support the extended slicing syntax, as described in
section <a class="reference internal" href="#section-slices"><span class="std std-ref">Extended Slices</span></a> of this document.</p>
</li>
<li><p class="first">A new built-in function, <code class="docutils literal notranslate"><span class="pre">sum(iterable,</span> <span class="pre">start=0)</span></code>,  adds up the numeric
items in the iterable object and returns their sum.  <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> only accepts
numbers, meaning that you can’t use it to concatenate a bunch of strings.
(Contributed by Alex Martelli.)</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">list.insert(pos,</span> <span class="pre">value)</span></code> used to  insert <em>value</em> at the front of the list
when <em>pos</em> was negative.  The behaviour has now been changed to be consistent
with slice indexing, so when <em>pos</em> is -1 the value will be inserted before the
last element, and so forth.</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">list.index(value)</span></code>, which searches for <em>value</em>  within the list and returns
its index, now takes optional  <em>start</em> and <em>stop</em> arguments to limit the search
to  only part of the list.</p>
</li>
<li><p class="first">Dictionaries have a new method, <code class="docutils literal notranslate"><span class="pre">pop(key[,</span> <span class="pre">*default*])</span></code>, that returns
the value corresponding to <em>key</em> and removes that key/value pair from the
dictionary.  If the requested key isn’t present in the dictionary, <em>default</em> is
returned if it’s specified and <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> raised if it isn’t.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="p">{</span><span class="mi">1</span><span class="p">:</span><span class="mi">2</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{1: 2}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">KeyError</span>: <span class="n">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="go">2</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;stdin&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
<span class="gr">KeyError</span>: <span class="n">&#39;pop(): dictionary is empty&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{}</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>There’s also a new class method,  <code class="docutils literal notranslate"><span class="pre">dict.fromkeys(iterable,</span> <span class="pre">value)</span></code>, that
creates a dictionary with keys taken from the supplied iterator <em>iterable</em> and
all values set to <em>value</em>, defaulting to <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>(Patches contributed by Raymond Hettinger.)</p>
<p>Also, the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-func docutils literal notranslate"><span class="pre">dict()</span></code></a> constructor now accepts keyword arguments to simplify
creating small dictionaries:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">black</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="go">{&#39;blue&#39;: 2, &#39;black&#39;: 4, &#39;green&#39;: 3, &#39;red&#39;: 1}</span>
</pre></div>
</div>
<p>(Contributed by Just van Rossum.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/simple_stmts.html#assert"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">assert</span></code></a> statement no longer checks the <code class="docutils literal notranslate"><span class="pre">__debug__</span></code> flag, so
you can no longer disable assertions by assigning to <code class="docutils literal notranslate"><span class="pre">__debug__</span></code>. Running
Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> switch will still generate code that doesn’t
execute any assertions.</p>
</li>
<li><p class="first">Most type objects are now callable, so you can use them to create new objects
such as functions, classes, and modules.  (This means that the <a class="reference internal" href="../library/new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a> module
can be deprecated in a future Python version, because you can now use the type
objects available in the <a class="reference internal" href="../library/types.html#module-types" title="types: Names for built-in types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">types</span></code></a> module.) For example, you can create a new
module object with the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">types</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="n">types</span><span class="o">.</span><span class="n">ModuleType</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span><span class="s1">&#39;docstring&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>
<span class="go">&lt;module &#39;abc&#39; (built-in)&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="o">.</span><span class="vm">__doc__</span>
<span class="go">&#39;docstring&#39;</span>
</pre></div>
</div>
</li>
<li><p class="first">A new warning, <a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a> was added to indicate features
which are in the process of being deprecated.  The warning will <em>not</em> be printed
by default.  To check for use of features that will be deprecated in the future,
supply <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Walways::PendingDeprecationWarning::</span></code></a> on the command line or
use <a class="reference internal" href="../library/warnings.html#warnings.filterwarnings" title="warnings.filterwarnings"><code class="xref py py-func docutils literal notranslate"><span class="pre">warnings.filterwarnings()</span></code></a>.</p>
</li>
<li><p class="first">The process of deprecating string-based exceptions, as in <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">&quot;Error</span>
<span class="pre">occurred&quot;</span></code>, has begun.  Raising a string will now trigger
<a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a>.</p>
</li>
<li><p class="first">Using <code class="docutils literal notranslate"><span class="pre">None</span></code> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a>
warning.  In a future version of Python, <code class="docutils literal notranslate"><span class="pre">None</span></code> may finally become a keyword.</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">xreadlines()</span></code> method of file objects, introduced in Python 2.1, is no
longer necessary because files now behave as their own iterator.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">xreadlines()</span></code> was originally introduced as a faster way to loop over all
the lines in a file, but now you can simply write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file_obj</span></code>.
File objects also have a new read-only <code class="xref py py-attr docutils literal notranslate"><span class="pre">encoding</span></code> attribute that gives the
encoding used by the file; Unicode strings written to the file will be
automatically  converted to bytes using the given encoding.</p>
</li>
<li><p class="first">The method resolution order used by new-style classes has changed, though
you’ll only notice the difference if you have a really complicated inheritance
hierarchy.  Classic classes are unaffected by this change.  Python 2.2
originally used a topological sort of a class’s ancestors, but 2.3 now uses the
C3 algorithm as described in the paper <a class="reference external" href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.3910">“A Monotonic Superclass Linearization
for Dylan”</a>. To
understand the motivation for this change,  read Michele Simionato’s article
<a class="reference external" href="http://www.phyast.pitt.edu/~micheles/mro.html">“Python 2.3 Method Resolution Order”</a>, or
read the thread on python-dev starting with the message at
<a class="reference external" href="https://mail.python.org/pipermail/python-dev/2002-October/029035.html">https://mail.python.org/pipermail/python-dev/2002-October/029035.html</a>. Samuele
Pedroni first pointed out the problem and also implemented the fix by coding the
C3 algorithm.</p>
</li>
<li><p class="first">Python runs multithreaded programs by switching between threads after
executing N bytecodes.  The default value for N has been increased from 10 to
100 bytecodes, speeding up single-threaded applications by reducing the
switching overhead.  Some multithreaded applications may suffer slower response
time, but that’s easily fixed by setting the limit back to a lower number using
<code class="docutils literal notranslate"><span class="pre">sys.setcheckinterval(N)</span></code>. The limit can be retrieved with the new
<a class="reference internal" href="../library/sys.html#sys.getcheckinterval" title="sys.getcheckinterval"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getcheckinterval()</span></code></a> function.</p>
</li>
<li><p class="first">One minor but far-reaching change is that the names of extension types defined
by the modules included with Python now contain the module and a <code class="docutils literal notranslate"><span class="pre">'.'</span></code> in
front of the type name.  For example, in Python 2.2, if you created a socket and
printed its <code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code>, you’d get this output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">socket</span><span class="o">.</span><span class="n">socket</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="vm">__class__</span>
<span class="go">&lt;type &#39;socket&#39;&gt;</span>
</pre></div>
</div>
<p>In 2.3, you get this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="vm">__class__</span>
<span class="go">&lt;type &#39;_socket.socket&#39;&gt;</span>
</pre></div>
</div>
</li>
<li><p class="first">One of the noted incompatibilities between old- and new-style classes has been
removed: you can now assign to the <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a>
attributes of new-style classes.  There are some restrictions on what can be
assigned to <a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a> along the lines of those relating to assigning to
an instance’s <a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> attribute.</p>
</li>
</ul>
<div class="section" id="string-changes">
<h3>String Changes<a class="headerlink" href="#string-changes" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">The <a class="reference internal" href="../reference/expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> operator now works differently for strings. Previously, when
evaluating <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code> where <em>X</em> and <em>Y</em> are strings, <em>X</em> could only be a single
character. That’s now changed; <em>X</em> can be a string of any length, and <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code>
will return <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> if <em>X</em> is a substring of <em>Y</em>.  If <em>X</em> is the empty
string, the result is always <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ab&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
<span class="go">True</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;ad&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span> <span class="ow">in</span> <span class="s1">&#39;abcd&#39;</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Note that this doesn’t tell you where the substring starts; if you need that
information, use the <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code> string method.</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">strip()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">lstrip()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">rstrip()</span></code> string methods now have
an optional argument for specifying the characters to strip.  The default is
still to remove all whitespace characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;   abc &#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">()</span>
<span class="go">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&gt;&lt;&gt;&lt;abc&lt;&gt;&lt;&gt;&lt;&gt;&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="p">)</span>
<span class="go">&#39;abc&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&gt;&lt;&gt;&lt;abc&lt;&gt;&lt;&gt;&lt;&gt;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="s1">&#39;&lt;&gt;&#39;</span><span class="p">)</span>
<span class="go">&#39;abc&lt;&gt;&lt;&gt;&lt;&gt;\n&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u4000\u4001</span><span class="s1">abc</span><span class="se">\u4000</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">strip</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u4000</span><span class="s1">&#39;</span><span class="p">)</span>
<span class="go">u&#39;\u4001abc&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>(Suggested by Simon Brunning and implemented by Walter Dörwald.)</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code> string methods now accept negative
numbers for the <em>start</em> and <em>end</em> parameters.</p>
</li>
<li><p class="first">Another new string method is <code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code>, originally a function in the
<a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code> pads a numeric string with zeros on the
left until it’s the specified width. Note that the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator is still more
flexible and powerful than <code class="xref py py-meth docutils literal notranslate"><span class="pre">zfill()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;45&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">&#39;0045&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;12345&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="go">&#39;12345&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;goofy&#39;</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span>
<span class="go">&#39;0goofy&#39;</span>
</pre></div>
</div>
<p>(Contributed by Walter Dörwald.)</p>
</li>
<li><p class="first">A new type object, <a class="reference internal" href="../library/functions.html#basestring" title="basestring"><code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code></a>, has been added. Both 8-bit strings and
Unicode strings inherit from this type, so <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">basestring)</span></code> will
return <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> for either kind of string.  It’s a completely abstract
type, so you can’t create <a class="reference internal" href="../library/functions.html#basestring" title="basestring"><code class="xref py py-class docutils literal notranslate"><span class="pre">basestring</span></code></a> instances.</p>
</li>
<li><p class="first">Interned strings are no longer immortal and will now be garbage-collected in
the usual way when the only reference to them is from the internal dictionary of
interned strings.  (Implemented by Oren Tirosh.)</p>
</li>
</ul>
</div>
<div class="section" id="optimizations">
<h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The creation of new-style class instances has been made much faster; they’re
now faster than classic classes!</li>
<li>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method of list objects has been extensively rewritten by Tim
Peters, and the implementation is significantly faster.</li>
<li>Multiplication of large long integers is now much faster thanks to an
implementation of Karatsuba multiplication, an algorithm that scales better than
the O(n*n) required for the grade-school multiplication algorithm.  (Original
patch by Christopher A. Craig, and significantly reworked by Tim Peters.)</li>
<li>The <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code> opcode is now gone.  This may provide a small speed
increase, depending on your compiler’s idiosyncrasies. See section
<a class="reference internal" href="#section-other"><span class="std std-ref">Other Changes and Fixes</span></a> for a longer explanation. (Removed by Michael Hudson.)</li>
<li><a class="reference internal" href="../library/functions.html#xrange" title="xrange"><code class="xref py py-func docutils literal notranslate"><span class="pre">xrange()</span></code></a> objects now have their own iterator, making <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span>
<span class="pre">xrange(n)</span></code> slightly faster than <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">range(n)</span></code>.  (Patch by Raymond
Hettinger.)</li>
<li>A number of small rearrangements have been made in various hotspots to improve
performance, such as inlining a function or removing some code.  (Implemented
mostly by GvR, but lots of people have contributed single changes.)</li>
</ul>
<p>The net result of the 2.3 optimizations is that Python 2.3 runs the  pystone
benchmark around 25% faster than Python 2.2.</p>
</div>
</div>
<div class="section" id="new-improved-and-deprecated-modules">
<h2>New, Improved, and Deprecated Modules<a class="headerlink" href="#new-improved-and-deprecated-modules" title="Permalink to this headline">¶</a></h2>
<p>As usual, Python’s standard library received a number of enhancements and bug
fixes.  Here’s a partial list of the most notable changes, sorted alphabetically
by module name. Consult the <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module now supports arrays of Unicode characters using the
<code class="docutils literal notranslate"><span class="pre">'u'</span></code> format character.  Arrays also now support using the <code class="docutils literal notranslate"><span class="pre">+=</span></code> assignment
operator to add another array’s contents, and the <code class="docutils literal notranslate"><span class="pre">*=</span></code> assignment operator to
repeat an array. (Contributed by Jason Orendorff.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module has been replaced by version 4.1.6 of the <a class="reference external" href="http://pybsddb.sourceforge.net">PyBSDDB</a> package, providing a more complete interface
to the transactional features of the BerkeleyDB library.</p>
<p>The old version of the module has been renamed to  <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb185</span></code> and is no
longer built automatically; you’ll  have to edit <code class="file docutils literal notranslate"><span class="pre">Modules/Setup</span></code> to enable
it.  Note that the new <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> package is intended to be compatible with
the  old module, so be sure to file bugs if you discover any incompatibilities.
When upgrading to Python 2.3, if the new interpreter is compiled with a new
version of  the underlying BerkeleyDB library, you will almost certainly have to
convert your database files to the new version.  You can do this fairly easily
with the new scripts <code class="file docutils literal notranslate"><span class="pre">db2pickle.py</span></code> and <code class="file docutils literal notranslate"><span class="pre">pickle2db.py</span></code> which you
will find in the distribution’s <code class="file docutils literal notranslate"><span class="pre">Tools/scripts</span></code> directory.  If you’ve
already been using the PyBSDDB package and importing it as <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb3</span></code>, you
will have to change your <code class="docutils literal notranslate"><span class="pre">import</span></code> statements to import it as <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a>.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> module is an interface to the bz2 data compression library.
bz2-compressed data is usually smaller than  corresponding <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a>-compressed data. (Contributed by Gustavo Niemeyer.)</p>
</li>
<li><p class="first">A set of standard date/time types has been added in the new <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a>
module.  See the following section for more details.</p>
</li>
<li><p class="first">The Distutils <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> class now supports an extra constructor
argument named <em>depends</em> for listing additional source files that an extension
depends on.  This lets Distutils recompile the module if any of the dependency
files are modified.  For example, if <code class="file docutils literal notranslate"><span class="pre">sampmodule.c</span></code> includes the header
file <code class="file docutils literal notranslate"><span class="pre">sample.h</span></code>, you would create the <code class="xref py py-class docutils literal notranslate"><span class="pre">Extension</span></code> object like
this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">ext</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="s2">&quot;samp&quot;</span><span class="p">,</span>
                <span class="n">sources</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;sampmodule.c&quot;</span><span class="p">],</span>
                <span class="n">depends</span><span class="o">=</span><span class="p">[</span><span class="s2">&quot;sample.h&quot;</span><span class="p">])</span>
</pre></div>
</div>
<p>Modifying <code class="file docutils literal notranslate"><span class="pre">sample.h</span></code> would then cause the module to be recompiled.
(Contributed by Jeremy Hylton.)</p>
</li>
<li><p class="first">Other minor changes to Distutils: it now checks for the <span class="target" id="index-24"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CC</span></code>,
<span class="target" id="index-25"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CFLAGS</span></code>, <span class="target" id="index-26"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CPP</span></code>, <span class="target" id="index-27"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LDFLAGS</span></code>, and <span class="target" id="index-28"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">CPPFLAGS</span></code>
environment variables, using them to override the settings in Python’s
configuration (contributed by Robert Weber).</p>
</li>
<li><p class="first">Previously the <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module would only search the docstrings of
public methods and functions for test cases, but it now also examines private
ones as well.  The <code class="xref py py-func docutils literal notranslate"><span class="pre">DocTestSuite()</span></code> function creates a
<a class="reference internal" href="../library/unittest.html#unittest.TestSuite" title="unittest.TestSuite"><code class="xref py py-class docutils literal notranslate"><span class="pre">unittest.TestSuite</span></code></a> object from a set of <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> tests.</p>
</li>
<li><p class="first">The new <code class="docutils literal notranslate"><span class="pre">gc.get_referents(object)</span></code> function returns a list of all the
objects referenced by <em>object</em>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module gained a new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">gnu_getopt()</span></code>, that
supports the same arguments as the existing <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> function but uses
GNU-style scanning mode. The existing <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-func docutils literal notranslate"><span class="pre">getopt()</span></code></a> stops processing options as
soon as a non-option argument is encountered, but in GNU-style mode processing
continues, meaning that options and arguments can be mixed.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;filename&#39;</span><span class="p">,</span> <span class="s1">&#39;output&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">],</span> <span class="s1">&#39;f:v&#39;</span><span class="p">)</span>
<span class="go">([(&#39;-f&#39;, &#39;filename&#39;)], [&#39;output&#39;, &#39;-v&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getopt</span><span class="o">.</span><span class="n">gnu_getopt</span><span class="p">([</span><span class="s1">&#39;-f&#39;</span><span class="p">,</span> <span class="s1">&#39;filename&#39;</span><span class="p">,</span> <span class="s1">&#39;output&#39;</span><span class="p">,</span> <span class="s1">&#39;-v&#39;</span><span class="p">],</span> <span class="s1">&#39;f:v&#39;</span><span class="p">)</span>
<span class="go">([(&#39;-f&#39;, &#39;filename&#39;), (&#39;-v&#39;, &#39;&#39;)], [&#39;output&#39;])</span>
</pre></div>
</div>
<p>(Contributed by Peter Åstrand.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/grp.html#module-grp" title="grp: The group database (getgrnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">grp</span></code></a>, <a class="reference internal" href="../library/pwd.html#module-pwd" title="pwd: The password database (getpwnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pwd</span></code></a>, and <a class="reference internal" href="../library/resource.html#module-resource" title="resource: An interface to provide resource usage information on the current process. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">resource</span></code></a> modules now return enhanced
tuples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">grp</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">g</span> <span class="o">=</span> <span class="n">grp</span><span class="o">.</span><span class="n">getgrnam</span><span class="p">(</span><span class="s1">&#39;amk&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">g</span><span class="o">.</span><span class="n">gr_name</span><span class="p">,</span> <span class="n">g</span><span class="o">.</span><span class="n">gr_gid</span>
<span class="go">(&#39;amk&#39;, 500)</span>
</pre></div>
</div>
</li>
<li><p class="first">The <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module can now handle files exceeding 2 GiB.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module contains an implementation of a heap queue
algorithm.  A heap is an array-like data structure that keeps items in a
partially sorted order such that, for every index <em>k</em>, <code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span>
<span class="pre">heap[2*k+1]</span></code> and <code class="docutils literal notranslate"><span class="pre">heap[k]</span> <span class="pre">&lt;=</span> <span class="pre">heap[2*k+2]</span></code>.  This makes it quick to remove the
smallest item, and inserting a new item while maintaining the heap property is
O(lg n).  (See <a class="reference external" href="https://xlinux.nist.gov/dads//HTML/priorityque.html">https://xlinux.nist.gov/dads//HTML/priorityque.html</a> for more
information about the priority queue data structure.)</p>
<p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides <code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code> functions
for adding and removing items while maintaining the heap property on top of some
other mutable Python sequence type.  Here’s an example that uses a Python list:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">heapq</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">1</span><span class="p">]:</span>
<span class="gp">... </span>   <span class="n">heapq</span><span class="o">.</span><span class="n">heappush</span><span class="p">(</span><span class="n">heap</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span>
<span class="go">[1, 3, 5, 11, 7]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">heappop</span><span class="p">(</span><span class="n">heap</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heap</span>
<span class="go">[5, 7, 11]</span>
</pre></div>
</div>
<p>(Contributed by Kevin O’Connor.)</p>
</li>
<li><p class="first">The IDLE integrated development environment has been updated using the code
from the IDLEfork project (<a class="reference external" href="http://idlefork.sourceforge.net">http://idlefork.sourceforge.net</a>).  The most notable feature is
that the code being developed is now executed in a subprocess, meaning that
there’s no longer any need for manual <code class="docutils literal notranslate"><span class="pre">reload()</span></code> operations. IDLE’s core code
has been incorporated into the standard library as the <code class="xref py py-mod docutils literal notranslate"><span class="pre">idlelib</span></code> package.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module now supports IMAP over SSL. (Contributed by Piers
Lauder and Tino Lange.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> contains a number of useful functions for use with
iterators, inspired by various functions provided by the ML and Haskell
languages.  For example, <code class="docutils literal notranslate"><span class="pre">itertools.ifilter(predicate,</span> <span class="pre">iterator)</span></code> returns all
elements in the iterator for which the function <code class="xref py py-func docutils literal notranslate"><span class="pre">predicate()</span></code> returns
<a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">itertools.repeat(obj,</span> <span class="pre">N)</span></code> returns <code class="docutils literal notranslate"><span class="pre">obj</span></code> <em>N</em> times.
There are a number of other functions in the module; see the package’s reference
documentation for details.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Two new functions in the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module, <code class="docutils literal notranslate"><span class="pre">degrees(rads)</span></code> and
<code class="docutils literal notranslate"><span class="pre">radians(degs)</span></code>, convert between radians and degrees.  Other functions in
the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module such as <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> and <a class="reference internal" href="../library/math.html#math.cos" title="math.cos"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.cos()</span></code></a> have always
required input values measured in radians.  Also, an optional <em>base</em> argument
was added to <a class="reference internal" href="../library/math.html#math.log" title="math.log"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.log()</span></code></a> to make it easier to compute logarithms for bases
other than <code class="docutils literal notranslate"><span class="pre">e</span></code> and <code class="docutils literal notranslate"><span class="pre">10</span></code>.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Several new POSIX functions (<code class="xref py py-func docutils literal notranslate"><span class="pre">getpgid()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">killpg()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">lchown()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">loadavg()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">major()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">makedev()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">minor()</span></code>, and
<code class="xref py py-func docutils literal notranslate"><span class="pre">mknod()</span></code>) were added to the <a class="reference internal" href="../library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> module that underlies the
<a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module. (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
Otkidach.)</p>
</li>
<li><p class="first">In the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module, the <code class="xref py py-func docutils literal notranslate"><span class="pre">*stat()</span></code> family of functions can now report
fractions of a second in a timestamp.  Such time stamps are represented as
floats, similar to the value returned by <a class="reference internal" href="../library/time.html#time.time" title="time.time"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.time()</span></code></a>.</p>
<p>During testing, it was found that some applications will break if time stamps
are floats.  For compatibility, when using the tuple interface of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">stat_result</span></code> time stamps will be represented as integers. When using
named fields (a feature first introduced in Python 2.2), time stamps are still
represented as integers, unless <a class="reference internal" href="../library/os.html#os.stat_float_times" title="os.stat_float_times"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat_float_times()</span></code></a> is invoked to enable
float return values:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s2">&quot;/tmp&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
<span class="go">1034791200</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">stat_float_times</span><span class="p">(</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="s2">&quot;/tmp&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">st_mtime</span>
<span class="go">1034791200.6335014</span>
</pre></div>
</div>
<p>In Python 2.4, the default will change to always returning floats.</p>
<p>Application developers should enable this feature only if all their libraries
work properly when confronted with floating point time stamps, or if they use
the tuple API. If used, the feature should be activated on an application level
instead of trying to enable it on a per-use basis.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module contains a new parser for command-line arguments
that can convert option values to a particular Python type  and will
automatically generate a usage message.  See the following section for  more
details.</p>
</li>
<li><p class="first">The old and never-documented <code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code> module has been deprecated,
and a new version named <a class="reference internal" href="../library/ossaudiodev.html#module-ossaudiodev" title="ossaudiodev: Access to OSS-compatible audio devices. (Linux, FreeBSD)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ossaudiodev</span></code></a> has been added.  The module was
renamed because the OSS sound drivers can be used on platforms other than Linux,
and the interface has also been tidied and brought up to date in various ways.
(Contributed by Greg Ward and Nicholas FitzRoy-Dale.)</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-mod docutils literal notranslate"><span class="pre">platform</span></code></a> module contains a number of functions that try to
determine various properties of the platform you’re running on.  There are
functions for getting the architecture, CPU type, the Windows OS version, and
even the Linux distribution version. (Contributed by Marc-André Lemburg.)</p>
</li>
<li><p class="first">The parser objects provided by the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module can now optionally
buffer character data, resulting in fewer calls to your character data handler
and therefore faster performance.  Setting the parser object’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_text</span></code> attribute to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> will enable buffering.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">sample(population,</span> <span class="pre">k)</span></code> function was added to the <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a>
module.  <em>population</em> is a sequence or <a class="reference internal" href="../library/functions.html#xrange" title="xrange"><code class="xref py py-class docutils literal notranslate"><span class="pre">xrange</span></code></a> object containing the
elements of a population, and <code class="xref py py-func docutils literal notranslate"><span class="pre">sample()</span></code> chooses <em>k</em> elements from the
population without replacing chosen elements.  <em>k</em> can be any value up to
<code class="docutils literal notranslate"><span class="pre">len(population)</span></code>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">days</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Mo&#39;</span><span class="p">,</span> <span class="s1">&#39;Tu&#39;</span><span class="p">,</span> <span class="s1">&#39;We&#39;</span><span class="p">,</span> <span class="s1">&#39;Th&#39;</span><span class="p">,</span> <span class="s1">&#39;Fr&#39;</span><span class="p">,</span> <span class="s1">&#39;St&#39;</span><span class="p">,</span> <span class="s1">&#39;Sn&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>      <span class="c1"># Choose 3 elements</span>
<span class="go">[&#39;St&#39;, &#39;Sn&#39;, &#39;Th&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span>      <span class="c1"># Choose 7 elements</span>
<span class="go">[&#39;Tu&#39;, &#39;Th&#39;, &#39;Mo&#39;, &#39;We&#39;, &#39;St&#39;, &#39;Fr&#39;, &#39;Sn&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">7</span><span class="p">)</span>      <span class="c1"># Choose 7 again</span>
<span class="go">[&#39;We&#39;, &#39;Mo&#39;, &#39;Sn&#39;, &#39;Fr&#39;, &#39;Tu&#39;, &#39;St&#39;, &#39;Th&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">days</span><span class="p">,</span> <span class="mi">8</span><span class="p">)</span>      <span class="c1"># Can&#39;t choose eight</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">?</span>
  File <span class="nb">&quot;random.py&quot;</span>, line <span class="m">414</span>, in <span class="n">sample</span>
      <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">,</span> <span class="s2">&quot;sample larger than population&quot;</span>
<span class="gr">ValueError</span>: <span class="n">sample larger than population</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">10000</span><span class="p">,</span><span class="mi">2</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span>   <span class="c1"># Choose ten odd nos. under 10000</span>
<span class="go">[3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module now uses a new algorithm, the Mersenne Twister,
implemented in C.  It’s faster and more extensively studied than the previous
algorithm.</p>
<p>(All changes contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module also gained a number of new functions:
<code class="xref py py-func docutils literal notranslate"><span class="pre">get_history_item()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">get_current_history_length()</span></code>, and
<code class="xref py py-func docutils literal notranslate"><span class="pre">redisplay()</span></code>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> and <a class="reference internal" href="../library/bastion.html#module-Bastion" title="Bastion: Providing restricted access to objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Bastion</span></code></a> modules have been declared dead, and
attempts to import them will fail with a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>.  New-style classes
provide new ways to break out of the restricted execution environment provided
by <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a>, and no one has interest in fixing them or time to do so.  If
you have applications using <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a>, rewrite them to use something else.</p>
<p>(Sticking with Python 2.2 or 2.1 will not make your applications any safer
because there are known bugs in the <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a> module in those versions.  To
repeat: if you’re using <a class="reference internal" href="../library/rexec.html#module-rexec" title="rexec: Basic restricted execution framework. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rexec</span></code></a>, stop using it immediately.)</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">rotor</span></code> module has been deprecated because the  algorithm it uses for
encryption is not believed to be secure.  If you need encryption, use one of the
several AES Python modules that are available separately.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module gained a <code class="docutils literal notranslate"><span class="pre">move(src,</span> <span class="pre">dest)</span></code> function that
recursively moves a file or directory to a new location.</p>
</li>
<li><p class="first">Support for more advanced POSIX signal handling was added to the <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a>
but then removed again as it proved impossible to make it work reliably across
platforms.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now supports timeouts.  You can call the
<code class="docutils literal notranslate"><span class="pre">settimeout(t)</span></code> method on a socket object to set a timeout of <em>t</em> seconds.
Subsequent socket operations that take longer than <em>t</em> seconds to complete will
abort and raise a <a class="reference internal" href="../library/socket.html#socket.timeout" title="socket.timeout"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.timeout</span></code></a> exception.</p>
<p>The original timeout implementation was by Tim O’Malley.  Michael Gilfix
integrated it into the Python <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module and shepherded it through a
lengthy review.  After the code was checked in, Guido van Rossum rewrote parts
of it.  (This is a good example of a collaborative development process in
action.)</p>
</li>
<li><p class="first">On Windows, the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now ships with Secure  Sockets Layer
(SSL) support.</p>
</li>
<li><p class="first">The value of the C <code class="xref py py-const docutils literal notranslate"><span class="pre">PYTHON_API_VERSION</span></code> macro is now exposed at the
Python level as <code class="docutils literal notranslate"><span class="pre">sys.api_version</span></code>.  The current exception can be cleared by
calling the new <a class="reference internal" href="../library/sys.html#sys.exc_clear" title="sys.exc_clear"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_clear()</span></code></a> function.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module  allows reading from and writing to
<strong class="program">tar</strong>-format archive files. (Contributed by Lars Gustäbel.)</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module contains functions for wrapping strings
containing paragraphs of text.  The <code class="docutils literal notranslate"><span class="pre">wrap(text,</span> <span class="pre">width)</span></code> function takes a
string and returns a list containing the text split into lines of no more than
the chosen width.  The <code class="docutils literal notranslate"><span class="pre">fill(text,</span> <span class="pre">width)</span></code> function returns a single
string, reformatted to fit into lines no longer than the chosen width. (As you
can guess, <code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code> is built on top of <code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code>.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">textwrap</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">paragraph</span> <span class="o">=</span> <span class="s2">&quot;Not a whit, we defy augury: ... more text ...&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">textwrap</span><span class="o">.</span><span class="n">wrap</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">60</span><span class="p">)</span>
<span class="go">[&quot;Not a whit, we defy augury: there&#39;s a special providence in&quot;,</span>
<span class="go"> &quot;the fall of a sparrow. If it be now, &#39;tis not to come; if it&quot;,</span>
<span class="go"> ...]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">paragraph</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
<span class="go">Not a whit, we defy augury: there&#39;s</span>
<span class="go">a special providence in the fall of</span>
<span class="go">a sparrow. If it be now, &#39;tis not</span>
<span class="go">to come; if it be not to come, it</span>
<span class="go">will be now; if it be not now, yet</span>
<span class="go">it will come: the readiness is all.</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The module also contains a <code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code> class that actually implements
the text wrapping strategy.   Both the <code class="xref py py-class docutils literal notranslate"><span class="pre">TextWrapper</span></code> class and the
<code class="xref py py-func docutils literal notranslate"><span class="pre">wrap()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">fill()</span></code> functions support a number of additional keyword
arguments for fine-tuning the formatting; consult the module’s documentation
for details. (Contributed by Greg Ward.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> and <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> modules now have companion modules,
<a class="reference internal" href="../library/dummy_thread.html#module-dummy_thread" title="dummy_thread: Drop-in replacement for the thread module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_thread</span></code></a> and <a class="reference internal" href="../library/dummy_threading.html#module-dummy_threading" title="dummy_threading: Drop-in replacement for the threading module."><code class="xref py py-mod docutils literal notranslate"><span class="pre">dummy_threading</span></code></a>, that provide a do-nothing
implementation of the <a class="reference internal" href="../library/thread.html#module-thread" title="thread: Create multiple threads of control within one interpreter."><code class="xref py py-mod docutils literal notranslate"><span class="pre">thread</span></code></a> module’s interface for platforms where
threads are not supported.  The intention is to simplify thread-aware modules
(ones that <em>don’t</em> rely on threads to run) by putting the following code at the
top:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">threading</span> <span class="k">as</span> <span class="nn">_threading</span>
<span class="k">except</span> <span class="ne">ImportError</span><span class="p">:</span>
    <span class="kn">import</span> <span class="nn">dummy_threading</span> <span class="k">as</span> <span class="nn">_threading</span>
</pre></div>
</div>
<p>In this example, <code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading</span></code> is used as the module name to make it clear
that the module being used is not necessarily the actual <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a>
module. Code can call functions and use classes in <code class="xref py py-mod docutils literal notranslate"><span class="pre">_threading</span></code> whether or
not threads are supported, avoiding an <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement and making the
code slightly clearer.  This module will not magically make multithreaded code
run without threads; code that waits for another thread to return or to do
something will simply hang forever.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/time.html#module-time" title="time: Time access and conversions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">time</span></code></a> module’s <code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code> function has long been an annoyance
because it uses the platform C library’s <code class="xref py py-func docutils literal notranslate"><span class="pre">strptime()</span></code> implementation, and
different platforms sometimes have odd bugs.  Brett Cannon contributed a
portable implementation that’s written in pure Python and should behave
identically on all platforms.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module helps measure how long snippets of Python code
take to execute.  The <code class="file docutils literal notranslate"><span class="pre">timeit.py</span></code> file can be run directly from the
command line, or the module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code> class can be imported and used
directly.  Here’s a short example that figures out whether it’s faster to
convert an 8-bit string to Unicode by appending an empty Unicode string to it or
by using the <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-func docutils literal notranslate"><span class="pre">unicode()</span></code></a> function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">timeit</span>

<span class="n">timer1</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;unicode(&quot;abc&quot;)&#39;</span><span class="p">)</span>
<span class="n">timer2</span> <span class="o">=</span> <span class="n">timeit</span><span class="o">.</span><span class="n">Timer</span><span class="p">(</span><span class="s1">&#39;&quot;abc&quot; + u&quot;&quot;&#39;</span><span class="p">)</span>

<span class="c1"># Run three trials</span>
<span class="nb">print</span> <span class="n">timer1</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">timer2</span><span class="o">.</span><span class="n">repeat</span><span class="p">(</span><span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">number</span><span class="o">=</span><span class="mi">100000</span><span class="p">)</span>

<span class="c1"># On my laptop this outputs:</span>
<span class="c1"># [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]</span>
<span class="c1"># [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]</span>
</pre></div>
</div>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tix.html#module-Tix" title="Tix: Tk Extension Widgets for Tkinter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tix</span></code></a> module has received various bug fixes and updates for the
current version of the Tix package.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module now works with a thread-enabled  version of Tcl.
Tcl’s threading model requires that widgets only be accessed from the thread in
which they’re created; accesses from another thread can cause Tcl to panic.  For
certain Tcl interfaces, <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> will now automatically avoid this  when a
widget is accessed from a different thread by marshalling a command, passing it
to the correct thread, and waiting for the results.  Other interfaces can’t be
handled automatically but <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> will now raise an exception on such an
access so that you can at least find out about the problem.  See
<a class="reference external" href="https://mail.python.org/pipermail/python-dev/2002-December/031107.html">https://mail.python.org/pipermail/python-dev/2002-December/031107.html</a> for a more
detailed explanation of this change.  (Implemented by Martin von Löwis.)</p>
</li>
<li><p class="first">Calling Tcl methods through <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> no longer  returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a <code class="xref py py-class docutils literal notranslate"><span class="pre">_tkinter.Tcl_Obj</span></code>
object if no Python equivalent exists. This behavior can be controlled through
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">wantobjects()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">tkapp</span></code> objects.</p>
<p>When using <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> through the <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module (as most Tkinter
applications will), this feature is always activated. It should not cause
compatibility problems, since Tkinter would always convert string results to
Python types where possible.</p>
<p>If any incompatibilities are found, the old behavior can be restored by setting
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">wantobjects</span></code> variable in the <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module to false before
creating the first <code class="xref py py-class docutils literal notranslate"><span class="pre">tkapp</span></code> object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">Tkinter</span>
<span class="n">Tkinter</span><span class="o">.</span><span class="n">wantobjects</span> <span class="o">=</span> <span class="mi">0</span>
</pre></div>
</div>
<p>Any breakage caused by this change should be reported as a bug.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/userdict.html#module-UserDict" title="UserDict: Class wrapper for dictionary objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">UserDict</span></code></a> module has a new <code class="xref py py-class docutils literal notranslate"><span class="pre">DictMixin</span></code> class which defines
all dictionary methods for classes that already have a minimum mapping
interface.  This greatly simplifies writing classes that need to be
substitutable for dictionaries, such as the classes in  the <a class="reference internal" href="../library/shelve.html#module-shelve" title="shelve: Python object persistence."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shelve</span></code></a>
module.</p>
<p>Adding the mix-in as a superclass provides the full dictionary interface
whenever the class defines <a class="reference internal" href="../reference/datamodel.html#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>,
<a class="reference internal" href="../reference/datamodel.html#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">UserDict</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">SeqDict</span><span class="p">(</span><span class="n">UserDict</span><span class="o">.</span><span class="n">DictMixin</span><span class="p">):</span>
<span class="gp">... </span>    <span class="sd">&quot;&quot;&quot;Dictionary lookalike implemented with lists.&quot;&quot;&quot;</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span> <span class="o">=</span> <span class="p">[]</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__getitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>            <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">raise</span> <span class="ne">KeyError</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__setitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>            <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span>            <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
<span class="gp">... </span>        <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span>            <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span>            <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">value</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__delitem__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">try</span><span class="p">:</span>
<span class="gp">... </span>            <span class="n">i</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">key</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
<span class="gp">... </span>            <span class="k">raise</span> <span class="ne">KeyError</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">valuelist</span><span class="o">.</span><span class="n">pop</span><span class="p">(</span><span class="n">i</span><span class="p">)</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">keys</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">list</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">keylist</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="n">SeqDict</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>      <span class="c1"># See that other dictionary methods are implemented</span>
<span class="go">[&#39;__cmp__&#39;, &#39;__contains__&#39;, &#39;__delitem__&#39;, &#39;__doc__&#39;, &#39;__getitem__&#39;,</span>
<span class="go"> &#39;__init__&#39;, &#39;__iter__&#39;, &#39;__len__&#39;, &#39;__module__&#39;, &#39;__repr__&#39;,</span>
<span class="go"> &#39;__setitem__&#39;, &#39;clear&#39;, &#39;get&#39;, &#39;has_key&#39;, &#39;items&#39;, &#39;iteritems&#39;,</span>
<span class="go"> &#39;iterkeys&#39;, &#39;itervalues&#39;, &#39;keylist&#39;, &#39;keys&#39;, &#39;pop&#39;, &#39;popitem&#39;,</span>
<span class="go"> &#39;setdefault&#39;, &#39;update&#39;, &#39;valuelist&#39;, &#39;values&#39;]</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The DOM implementation in <a class="reference internal" href="../library/xml.dom.minidom.html#module-xml.dom.minidom" title="xml.dom.minidom: Minimal Document Object Model (DOM) implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code></a> can now generate XML output
in a particular encoding by providing an optional encoding argument to the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">toxml()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">toprettyxml()</span></code> methods of DOM nodes.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module now supports an XML-RPC extension for handling nil
data values such as Python’s <code class="docutils literal notranslate"><span class="pre">None</span></code>.  Nil values are always supported on
unmarshalling an XML-RPC response.  To generate requests containing <code class="docutils literal notranslate"><span class="pre">None</span></code>,
you must supply a true value for the <em>allow_none</em> parameter when creating a
<code class="xref py py-class docutils literal notranslate"><span class="pre">Marshaller</span></code> instance.</p>
</li>
<li><p class="first">The new <a class="reference internal" href="../library/docxmlrpcserver.html#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a> module allows writing self-documenting XML-RPC
servers. Run it in demo mode (as a program) to see it in action.   Pointing the
Web browser to the RPC server produces pydoc-style documentation; pointing
xmlrpclib to the server allows invoking the actual methods. (Contributed by
Brian Quinlan.)</p>
</li>
<li><p class="first">Support for internationalized domain names (RFCs 3454, 3490, 3491, and 3492)
has been added. The “idna” encoding can be used to convert between a Unicode
domain name and the ASCII-compatible encoding (ACE) of that name.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">&gt;</span><span class="p">{}</span><span class="o">&gt;</span><span class="p">{}</span><span class="o">&gt;</span> <span class="sa">u</span><span class="s2">&quot;www.Alliancefrançaise.nu&quot;</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s2">&quot;idna&quot;</span><span class="p">)</span>
<span class="s1">&#39;www.xn--alliancefranaise-npb.nu&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module has also been extended to transparently convert
Unicode hostnames to the ACE version before passing them to the C library.
Modules that deal with hostnames such as <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> and <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a>)
also support Unicode host names; <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> also sends HTTP <code class="docutils literal notranslate"><span class="pre">Host</span></code>
headers using the ACE version of the domain name.  <a class="reference internal" href="../library/urllib.html#module-urllib" title="urllib: Open an arbitrary network resource by URL (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib</span></code></a> supports
Unicode URLs with non-ASCII host names as long as the <code class="docutils literal notranslate"><span class="pre">path</span></code> part of the URL
is ASCII only.</p>
<p>To implement this change, the <a class="reference internal" href="../library/stringprep.html#module-stringprep" title="stringprep: String preparation, as per RFC 3453"><code class="xref py py-mod docutils literal notranslate"><span class="pre">stringprep</span></code></a> module, the  <code class="docutils literal notranslate"><span class="pre">mkstringprep</span></code>
tool and the <code class="docutils literal notranslate"><span class="pre">punycode</span></code> encoding have been added.</p>
</li>
</ul>
<div class="section" id="date-time-type">
<h3>Date/Time Type<a class="headerlink" href="#date-time-type" title="Permalink to this headline">¶</a></h3>
<p>Date and time types suitable for expressing timestamps were added as the
<a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module.  The types don’t support different calendars or many
fancy features, and just stick to the basics of representing time.</p>
<p>The three primary types are: <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code>, representing a day, month, and year;
<a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>, consisting of hour, minute, and second; and <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>,
which contains all the attributes of both <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>.
There’s also a <code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code> class representing differences between two
points in time, and time zone logic is implemented by classes inheriting from
the abstract <code class="xref py py-class docutils literal notranslate"><span class="pre">tzinfo</span></code> class.</p>
<p>You can create instances of <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a> by either supplying
keyword arguments to the appropriate constructor, e.g.
<code class="docutils literal notranslate"><span class="pre">datetime.date(year=1972,</span> <span class="pre">month=10,</span> <span class="pre">day=15)</span></code>, or by using one of a number of
class methods.  For example, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">date.today()</span></code> class method returns the
current local date.</p>
<p>Once created, instances of the date/time classes are all immutable. There are a
number of methods for producing formatted strings from objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">datetime</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">isoformat</span><span class="p">()</span>
<span class="go">&#39;2002-12-30T21:27:03.994956&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">ctime</span><span class="p">()</span>  <span class="c1"># Only available on date, datetime</span>
<span class="go">&#39;Mon Dec 30 21:27:03 2002&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">&#39;%Y </span><span class="si">%d</span><span class="s1"> %b&#39;</span><span class="p">)</span>
<span class="go">&#39;2002 30 Dec&#39;</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code> method allows modifying one or more fields  of a
<code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> or <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instance, returning a new instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">year</span><span class="o">=</span><span class="mi">2001</span><span class="p">,</span> <span class="n">hour</span> <span class="o">=</span> <span class="mi">12</span><span class="p">)</span>
<span class="go">datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Instances can be compared, hashed, and converted to strings (the result is the
same as that of <code class="xref py py-meth docutils literal notranslate"><span class="pre">isoformat()</span></code>).  <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>
instances can be subtracted from each other, and added to <code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code>
instances.  The largest missing feature is that there’s no standard library
support for parsing strings and getting back a <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> or
<a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a>.</p>
<p>For more information, refer to the module’s reference documentation.
(Contributed by Tim Peters.)</p>
</div>
<div class="section" id="the-optparse-module">
<h3>The optparse Module<a class="headerlink" href="#the-optparse-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module provides simple parsing of command-line arguments.  The
new <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module (originally named Optik) provides more elaborate
command-line parsing that follows the Unix conventions, automatically creates
the output for <code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code>, and can perform different actions for different
options.</p>
<p>You start by creating an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code> and telling it what
your program’s options are.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">optparse</span> <span class="k">import</span> <span class="n">OptionParser</span>

<span class="n">op</span> <span class="o">=</span> <span class="n">OptionParser</span><span class="p">()</span>
<span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-i&#39;</span><span class="p">,</span> <span class="s1">&#39;--input&#39;</span><span class="p">,</span>
              <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;string&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;input&#39;</span><span class="p">,</span>
              <span class="n">help</span><span class="o">=</span><span class="s1">&#39;set input filename&#39;</span><span class="p">)</span>
<span class="n">op</span><span class="o">.</span><span class="n">add_option</span><span class="p">(</span><span class="s1">&#39;-l&#39;</span><span class="p">,</span> <span class="s1">&#39;--length&#39;</span><span class="p">,</span>
              <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;length&#39;</span><span class="p">,</span>
              <span class="n">help</span><span class="o">=</span><span class="s1">&#39;set maximum length of output&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Parsing a command line is then done by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">parse_args()</span></code> method.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">options</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">op</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:])</span>
<span class="nb">print</span> <span class="n">options</span>
<span class="nb">print</span> <span class="n">args</span>
</pre></div>
</div>
<p>This returns an object containing all of the option values, and a list of
strings containing the remaining arguments.</p>
<p>Invoking the script with the various arguments now works as you’d expect it to.
Note that the length argument is automatically converted to an integer.</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> ./python opt.py -i data arg1
<span class="go">&lt;Values at 0x400cad4c: {&#39;input&#39;: &#39;data&#39;, &#39;length&#39;: None}&gt;</span>
<span class="go">[&#39;arg1&#39;]</span>
<span class="gp">$</span> ./python opt.py --input<span class="o">=</span>data --length<span class="o">=</span><span class="m">4</span>
<span class="go">&lt;Values at 0x400cad2c: {&#39;input&#39;: &#39;data&#39;, &#39;length&#39;: 4}&gt;</span>
<span class="go">[]</span>
<span class="gp">$</span>
</pre></div>
</div>
<p>The help message is automatically generated for you:</p>
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$</span> ./python opt.py --help
<span class="go">usage: opt.py [options]</span>

<span class="go">options:</span>
<span class="go">  -h, --help            show this help message and exit</span>
<span class="go">  -iINPUT, --input=INPUT</span>
<span class="go">                        set input filename</span>
<span class="go">  -lLENGTH, --length=LENGTH</span>
<span class="go">                        set maximum length of output</span>
<span class="gp">$</span>
</pre></div>
</div>
<p>See the module’s documentation for more details.</p>
<p>Optik was written by Greg Ward, with suggestions from the readers of the Getopt
SIG.</p>
</div>
</div>
<div class="section" id="pymalloc-a-specialized-object-allocator">
<span id="section-pymalloc"></span><h2>Pymalloc: A Specialized Object Allocator<a class="headerlink" href="#pymalloc-a-specialized-object-allocator" title="Permalink to this headline">¶</a></h2>
<p>Pymalloc, a specialized object allocator written by Vladimir Marangozov, was a
feature added to Python 2.1.  Pymalloc is intended to be faster than the system
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and to have less memory overhead for allocation patterns typical
of Python programs. The allocator uses C’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> function to get large
pools of memory and then fulfills smaller memory requests from these pools.</p>
<p>In 2.1 and 2.2, pymalloc was an experimental feature and wasn’t enabled by
default; you had to explicitly enable it when compiling Python by providing the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-pymalloc</span></code> option to the <strong class="program">configure</strong> script.  In 2.3,
pymalloc has had further enhancements and is now enabled by default; you’ll have
to supply <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-pymalloc</span></code> to disable it.</p>
<p>This change is transparent to code written in Python; however, pymalloc may
expose bugs in C extensions.  Authors of C extension modules should test their
code with pymalloc enabled, because some incorrect code may cause core dumps at
runtime.</p>
<p>There’s one particularly common error that causes problems.  There are a number
of memory allocation functions in Python’s C API that have previously just been
aliases for the C library’s <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>, meaning that if
you accidentally called mismatched functions the error wouldn’t be noticeable.
When the object allocator is enabled, these functions aren’t aliases of
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> any more, and calling the wrong function to
free memory may get you a core dump.  For example, if memory was allocated using
<a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, it has to be freed using <a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a>, not
<code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.  A few modules included with Python fell afoul of this and had to
be fixed; doubtless there are more third-party modules that will have the same
problem.</p>
<p>As part of this change, the confusing multiple interfaces for allocating memory
have been consolidated down into two API families. Memory allocated with one
family must not be manipulated with functions from the other family.  There is
one family for allocating chunks of memory and another family of functions
specifically for allocating Python objects.</p>
<ul class="simple">
<li>To allocate and free an undistinguished chunk of memory use the “raw memory”
family: <a class="reference internal" href="../c-api/memory.html#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a>.</li>
<li>The “object memory” family is the interface to the pymalloc facility described
above and is biased towards a large number of “small” allocations:
<a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a>.</li>
<li>To allocate and free Python objects, use the “object” family
<a class="reference internal" href="../c-api/allocation.html#c.PyObject_New" title="PyObject_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_New()</span></code></a>, <a class="reference internal" href="../c-api/allocation.html#c.PyObject_NewVar" title="PyObject_NewVar"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_NewVar()</span></code></a>, and <a class="reference internal" href="../c-api/allocation.html#c.PyObject_Del" title="PyObject_Del"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Del()</span></code></a>.</li>
</ul>
<p>Thanks to lots of work by Tim Peters, pymalloc in 2.3 also provides debugging
features to catch memory overwrites and doubled frees in both extension modules
and in the interpreter itself.  To enable this support, compile a debugging
version of the Python interpreter by running <strong class="program">configure</strong> with
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-pydebug</span></code>.</p>
<p>To aid extension writers, a header file <code class="file docutils literal notranslate"><span class="pre">Misc/pymemcompat.h</span></code> is
distributed with the source to Python 2.3 that allows Python extensions to use
the 2.3 interfaces to memory allocation while compiling against any version of
Python since 1.5.2.  You would copy the file from Python’s source distribution
and bundle it with the source of your extension.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://hg.python.org/cpython/file/default/Objects/obmalloc.c">https://hg.python.org/cpython/file/default/Objects/obmalloc.c</a></dt>
<dd>For the full details of the pymalloc implementation, see the comments at
the top of the file <code class="file docutils literal notranslate"><span class="pre">Objects/obmalloc.c</span></code> in the Python source code.
The above link points to the file within the python.org SVN browser.</dd>
</dl>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
<p>Changes to Python’s build process and to the C API include:</p>
<ul class="simple">
<li>The cycle detection implementation used by the garbage collection has proven
to be stable, so it’s now been made mandatory.  You can no longer compile Python
without it, and the <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-cycle-gc</span></code> switch to <strong class="program">configure</strong> has
been removed.</li>
<li>Python can now optionally be built as a shared library
(<code class="file docutils literal notranslate"><span class="pre">libpython2.3.so</span></code>) by supplying <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-shared</span></code> when running
Python’s <strong class="program">configure</strong> script.  (Contributed by Ondrej Palkovsky.)</li>
<li>The <code class="xref c c-macro docutils literal notranslate"><span class="pre">DL_EXPORT</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">DL_IMPORT</span></code> macros are now deprecated.
Initialization functions for Python extension modules should now be declared
using the new macro <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyMODINIT_FUNC</span></code>, while the Python core will
generally use the <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyAPI_FUNC</span></code> and <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyAPI_DATA</span></code> macros.</li>
<li>The interpreter can be compiled without any docstrings for the built-in
functions and modules by supplying <code class="xref std std-option docutils literal notranslate"><span class="pre">--without-doc-strings</span></code> to the
<strong class="program">configure</strong> script. This makes the Python executable about 10% smaller,
but will also mean that you can’t get help for Python’s built-ins.  (Contributed
by Gustavo Niemeyer.)</li>
<li>The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_NoArgs()</span></code> macro is now deprecated, and code that uses it
should be changed.  For Python 2.2 and later, the method definition table can
specify the <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a> flag, signalling that there are no arguments,
and the argument checking can then be removed.  If compatibility with pre-2.2
versions of Python is important, the code could use <code class="docutils literal notranslate"><span class="pre">PyArg_ParseTuple(args,</span>
<span class="pre">&quot;&quot;)</span></code> instead, but this will be slower than using <a class="reference internal" href="../c-api/structures.html#METH_NOARGS" title="METH_NOARGS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_NOARGS</span></code></a>.</li>
<li><a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> accepts new format characters for various sizes of
unsigned integers: <code class="docutils literal notranslate"><span class="pre">B</span></code> for <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">char</span></code>, <code class="docutils literal notranslate"><span class="pre">H</span></code> for <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span>
<span class="pre">short</span> <span class="pre">int</span></code>,  <code class="docutils literal notranslate"><span class="pre">I</span></code> for <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span> <span class="pre">int</span></code>,  and <code class="docutils literal notranslate"><span class="pre">K</span></code> for <code class="xref c c-type docutils literal notranslate"><span class="pre">unsigned</span>
<span class="pre">long</span> <span class="pre">long</span></code>.</li>
<li>A new function, <code class="docutils literal notranslate"><span class="pre">PyObject_DelItemString(mapping,</span> <span class="pre">char</span> <span class="pre">*key)</span></code> was added
as shorthand for <code class="docutils literal notranslate"><span class="pre">PyObject_DelItem(mapping,</span> <span class="pre">PyString_New(key))</span></code>.</li>
<li>File objects now manage their internal string buffer differently, increasing
it exponentially when needed.  This results in the benchmark tests in
<code class="file docutils literal notranslate"><span class="pre">Lib/test/test_bufio.py</span></code> speeding up considerably (from 57 seconds to 1.7
seconds, according to one measurement).</li>
<li>It’s now possible to define class and static methods for a C extension type by
setting either the <a class="reference internal" href="../c-api/structures.html#METH_CLASS" title="METH_CLASS"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_CLASS</span></code></a> or <a class="reference internal" href="../c-api/structures.html#METH_STATIC" title="METH_STATIC"><code class="xref py py-const docutils literal notranslate"><span class="pre">METH_STATIC</span></code></a> flags in a
method’s <a class="reference internal" href="../c-api/structures.html#c.PyMethodDef" title="PyMethodDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMethodDef</span></code></a> structure.</li>
<li>Python now includes a copy of the Expat XML parser’s source code, removing any
dependence on a system version or local installation of Expat.</li>
<li>If you dynamically allocate type objects in your extension, you should be
aware of a change in the rules relating to the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> and
<a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> attributes.  In summary, you will want to ensure the type’s
dictionary contains a <code class="docutils literal notranslate"><span class="pre">'__module__'</span></code> key; making the module name the part of
the type name leading up to the final period will no longer have the desired
effect.  For more detail, read the API reference documentation or the  source.</li>
</ul>
<div class="section" id="port-specific-changes">
<h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
<p>Support for a port to IBM’s OS/2 using the EMX runtime environment was merged
into the main Python source tree.  EMX is a POSIX emulation layer over the OS/2
system APIs.  The Python port for EMX tries to support all the POSIX-like
capability exposed by the EMX runtime, and mostly succeeds; <code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code> and
<a class="reference internal" href="../library/fcntl.html#module-fcntl" title="fcntl: The fcntl() and ioctl() system calls. (Unix)"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl()</span></code></a> are restricted by the limitations of the underlying emulation
layer.  The standard OS/2 port, which uses IBM’s Visual Age compiler, also
gained support for case-sensitive import semantics as part of the integration of
the EMX port into CVS.  (Contributed by Andrew MacIntyre.)</p>
<p>On MacOS, most toolbox modules have been weaklinked to improve backward
compatibility.  This means that modules will no longer fail to load if a single
routine is missing on the current OS version. Instead calling the missing
routine will raise an exception. (Contributed by Jack Jansen.)</p>
<p>The RPM spec files, found in the <code class="file docutils literal notranslate"><span class="pre">Misc/RPM/</span></code> directory in the Python
source distribution, were updated for 2.3.  (Contributed by Sean Reifschneider.)</p>
<p>Other new platforms now supported by Python include AtheOS
(<a class="reference external" href="http://atheos.cx/">http://atheos.cx/</a>), GNU/Hurd, and OpenVMS.</p>
</div>
</div>
<div class="section" id="other-changes-and-fixes">
<span id="section-other"></span><h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<p>As usual, there were a bunch of other improvements and bugfixes scattered
throughout the source tree.  A search through the CVS change logs finds there
were 523 patches applied and 514 bugs fixed between Python 2.2 and 2.3.  Both
figures are likely to be underestimates.</p>
<p>Some of the more notable changes are:</p>
<ul>
<li><p class="first">If the <span class="target" id="index-29"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONINSPECT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONINSPECT</span></code></a> environment variable is set, the Python
interpreter will enter the interactive prompt after running a Python program, as
if Python had been invoked with the <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a> option. The environment
variable can be set before running the Python interpreter, or it can be set by
the Python program as part of its execution.</p>
</li>
<li><p class="first">The <code class="file docutils literal notranslate"><span class="pre">regrtest.py</span></code> script now provides a way to allow “all resources
except <em>foo</em>.”  A resource name passed to the <code class="xref std std-option docutils literal notranslate"><span class="pre">-u</span></code> option can now be
prefixed with a hyphen (<code class="docutils literal notranslate"><span class="pre">'-'</span></code>) to mean “remove this resource.”  For example,
the option ‘<code class="docutils literal notranslate"><span class="pre">-uall,-bsddb</span></code>’ could be used to enable the use of all resources
except <code class="docutils literal notranslate"><span class="pre">bsddb</span></code>.</p>
</li>
<li><p class="first">The tools used to build the documentation now work under Cygwin as well as
Unix.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code> opcode has been removed.  Back in the mists of time, this
opcode was needed to produce line numbers in tracebacks and support trace
functions (for, e.g., <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a>). Since Python 1.5, the line numbers in
tracebacks have been computed using a different mechanism that works with
“python -O”.  For Python 2.3 Michael Hudson implemented a similar scheme to
determine when to call the trace function, removing the need for <code class="docutils literal notranslate"><span class="pre">SET_LINENO</span></code>
entirely.</p>
<p>It would be difficult to detect any resulting difference from Python code, apart
from a slight speed up when Python is run without <a class="reference internal" href="../using/cmdline.html#cmdoption-o"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a>.</p>
<p>C extensions that access the <code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code> field of frame objects should
instead call <code class="docutils literal notranslate"><span class="pre">PyCode_Addr2Line(f-&gt;f_code,</span> <span class="pre">f-&gt;f_lasti)</span></code>. This will have the
added effect of making the code work as desired under “python -O” in earlier
versions of Python.</p>
<p>A nifty new feature is that trace functions can now assign to the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">f_lineno</span></code> attribute of frame objects, changing the line that will be
executed next.  A <code class="docutils literal notranslate"><span class="pre">jump</span></code> command has been added to the <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> debugger
taking advantage of this new feature. (Implemented by Richie Hindle.)</p>
</li>
</ul>
</div>
<div class="section" id="porting-to-python-2-3">
<h2>Porting to Python 2.3<a class="headerlink" href="#porting-to-python-2-3" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes that may require changes to your
code:</p>
<ul>
<li><p class="first"><a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> is now always a keyword; if it’s used as a variable name in
your code, a different name must be chosen.</p>
</li>
<li><p class="first">For strings <em>X</em> and <em>Y</em>, <code class="docutils literal notranslate"><span class="pre">X</span> <span class="pre">in</span> <span class="pre">Y</span></code> now works if <em>X</em> is more than one
character long.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> type constructor will now return a long integer instead of
raising an <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a> when a string or floating-point number is too
large to fit into an integer.</p>
</li>
<li><p class="first">If you have Unicode strings that contain 8-bit characters, you must declare
the file’s encoding (UTF-8, Latin-1, or whatever) by adding a comment to the top
of the file.  See section <a class="reference internal" href="#section-encodings"><span class="std std-ref">PEP 263: Source Code Encodings</span></a> for more information.</p>
</li>
<li><p class="first">Calling Tcl methods through <code class="xref py py-mod docutils literal notranslate"><span class="pre">_tkinter</span></code> no longer  returns only strings.
Instead, if Tcl returns other objects those objects are converted to their
Python equivalent, if one exists, or wrapped with a <code class="xref py py-class docutils literal notranslate"><span class="pre">_tkinter.Tcl_Obj</span></code>
object if no Python equivalent exists.</p>
</li>
<li><p class="first">Large octal and hex literals such as <code class="docutils literal notranslate"><span class="pre">0xffffffff</span></code> now trigger a
<a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a>. Currently they’re stored as 32-bit numbers and result in a
negative value, but in Python 2.4 they’ll become positive long integers.</p>
<p>There are a few ways to fix this warning.  If you really need a positive number,
just add an <code class="docutils literal notranslate"><span class="pre">L</span></code> to the end of the literal.  If you’re trying to get a 32-bit
integer with low bits set and have previously used an expression such as <code class="docutils literal notranslate"><span class="pre">~(1</span>
<span class="pre">&lt;&lt;</span> <span class="pre">31)</span></code>, it’s probably clearest to start with all bits set and clear the
desired upper bits. For example, to clear just the top bit (bit 31), you could
write <code class="docutils literal notranslate"><span class="pre">0xffffffffL</span> <span class="pre">&amp;~(1L&lt;&lt;31)</span></code>.</p>
</li>
<li><p class="first">You can no longer disable assertions by assigning to <code class="docutils literal notranslate"><span class="pre">__debug__</span></code>.</p>
</li>
<li><p class="first">The Distutils <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code> function has gained various new keyword arguments
such as <em>depends</em>.  Old versions of the Distutils will abort if passed unknown
keywords.  A solution is to check for the presence of the new
<code class="xref py py-func docutils literal notranslate"><span class="pre">get_distutil_options()</span></code> function in your <code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> and only uses the
new keywords with a version of the Distutils that supports them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">distutils</span> <span class="k">import</span> <span class="n">core</span>

<span class="n">kw</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;sources&#39;</span><span class="p">:</span> <span class="s1">&#39;foo.c&#39;</span><span class="p">,</span> <span class="o">...</span><span class="p">}</span>
<span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">core</span><span class="p">,</span> <span class="s1">&#39;get_distutil_options&#39;</span><span class="p">):</span>
    <span class="n">kw</span><span class="p">[</span><span class="s1">&#39;depends&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;foo.h&#39;</span><span class="p">]</span>
<span class="n">ext</span> <span class="o">=</span> <span class="n">Extension</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">Using <code class="docutils literal notranslate"><span class="pre">None</span></code> as a variable name will now result in a <a class="reference internal" href="../library/exceptions.html#exceptions.SyntaxWarning" title="exceptions.SyntaxWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxWarning</span></code></a>
warning.</p>
</li>
<li><p class="first">Names of extension types defined by the modules included with Python now
contain the module and a <code class="docutils literal notranslate"><span class="pre">'.'</span></code> in front of the type name.</p>
</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<span id="acks"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Jeff Bauer,
Simon Brunning, Brett Cannon, Michael Chermside, Andrew Dalke, Scott David
Daniels, Fred L. Drake, Jr., David Fraser,  Kelly Gerber, Raymond Hettinger,
Michael Hudson, Chris Lambert, Detlef Lannert, Martin von Löwis, Andrew
MacIntyre, Lalo Martins, Chad Netzer, Gustavo Niemeyer, Neal Norwitz, Hans
Nowak, Chris Reedy, Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman
Suzi, Jason Tishler, Just van Rossum.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.3</a><ul>
<li><a class="reference internal" href="#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
<li><a class="reference internal" href="#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li><a class="reference internal" href="#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
<li><a class="reference internal" href="#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
<li><a class="reference internal" href="#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
<li><a class="reference internal" href="#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
<li><a class="reference internal" href="#pep-279-enumerate">PEP 279: enumerate()</a></li>
<li><a class="reference internal" href="#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
<li><a class="reference internal" href="#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
<li><a class="reference internal" href="#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
<li><a class="reference internal" href="#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
<li><a class="reference internal" href="#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
<li><a class="reference internal" href="#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
<li><a class="reference internal" href="#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
<li><a class="reference internal" href="#extended-slices">Extended Slices</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#string-changes">String Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
<li><a class="reference internal" href="#date-time-type">Date/Time Type</a></li>
<li><a class="reference internal" href="#the-optparse-module">The optparse Module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li><a class="reference internal" href="#porting-to-python-2-3">Porting to Python 2.3</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.4.html"
                        title="previous chapter">What’s New in Python 2.4</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.2.html"
                        title="next chapter">What’s New in Python 2.2</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.3.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.2.html" title="What’s New in Python 2.2"
             >next</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\N������html/whatsnew/2.4.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.4 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.3" href="2.3.html" />
    <link rel="prev" title="What’s New in Python 2.5" href="2.5.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.4.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.3.html" title="What’s New in Python 2.3"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.5.html" title="What’s New in Python 2.5"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-4">
<h1>What’s New in Python 2.4<a class="headerlink" href="#what-s-new-in-python-2-4" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.4.1, released on March 30,
2005.</p>
<p>Python 2.4 is a medium-sized release.  It doesn’t introduce as many changes as
the radical Python 2.2, but introduces more features than the conservative 2.3
release.  The most significant new language features are function decorators and
generator expressions; most other changes are to the standard library.</p>
<p>According to the CVS change logs, there were 481 patches applied and 502 bugs
fixed between Python 2.3 and 2.4.  Both figures are likely to be underestimates.</p>
<p>This article doesn’t attempt to provide a complete specification of every single
new feature, but instead provides a brief introduction to each feature.  For
full details, you should refer to the documentation for Python 2.4, such as the
Python Library Reference and the Python Reference Manual.  Often you will be
referred to the PEP for a particular new feature for explanations of the
implementation and design rationale.</p>
<div class="section" id="pep-218-built-in-set-objects">
<h2>PEP 218: Built-In Set Objects<a class="headerlink" href="#pep-218-built-in-set-objects" title="Permalink to this headline">¶</a></h2>
<p>Python 2.3 introduced the <a class="reference internal" href="../library/sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module.  C implementations of set data
types have now been added to the Python core as two new built-in types,
<code class="docutils literal notranslate"><span class="pre">set(iterable)</span></code> and <code class="docutils literal notranslate"><span class="pre">frozenset(iterable)</span></code>.  They provide high speed
operations for membership testing, for eliminating duplicates from sequences,
and for mathematical operations like unions, intersections, differences, and
symmetric differences.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;abracadabra&#39;</span><span class="p">)</span>              <span class="c1"># form a set from a string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;z&#39;</span> <span class="ow">in</span> <span class="n">a</span>                            <span class="c1"># fast membership testing</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>                                   <span class="c1"># unique letters in a</span>
<span class="go">set([&#39;a&#39;, &#39;r&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;&#39;</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>                          <span class="c1"># convert back into a string</span>
<span class="go">&#39;arbcd&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">set</span><span class="p">(</span><span class="s1">&#39;alacazam&#39;</span><span class="p">)</span>                 <span class="c1"># form a second set</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">-</span> <span class="n">b</span>                               <span class="c1"># letters in a but not in b</span>
<span class="go">set([&#39;r&#39;, &#39;d&#39;, &#39;b&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">|</span> <span class="n">b</span>                               <span class="c1"># letters in either a or b</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;, &#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">&amp;</span> <span class="n">b</span>                               <span class="c1"># letters in both a and b</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">^</span> <span class="n">b</span>                               <span class="c1"># letters in a or b but not both</span>
<span class="go">set([&#39;r&#39;, &#39;d&#39;, &#39;b&#39;, &#39;m&#39;, &#39;z&#39;, &#39;l&#39;])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="s1">&#39;z&#39;</span><span class="p">)</span>                          <span class="c1"># add a new element</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">update</span><span class="p">(</span><span class="s1">&#39;wxy&#39;</span><span class="p">)</span>                     <span class="c1"># add multiple new elements</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;, &#39;b&#39;, &#39;d&#39;, &#39;r&#39;, &#39;w&#39;, &#39;y&#39;, &#39;x&#39;, &#39;z&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">remove</span><span class="p">(</span><span class="s1">&#39;x&#39;</span><span class="p">)</span>                       <span class="c1"># take one element out</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span>
<span class="go">set([&#39;a&#39;, &#39;c&#39;, &#39;b&#39;, &#39;d&#39;, &#39;r&#39;, &#39;w&#39;, &#39;y&#39;, &#39;z&#39;])</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> type is an immutable version of <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a>. Since it is
immutable and hashable, it may be used as a dictionary key or as a member of
another set.</p>
<p>The <a class="reference internal" href="../library/sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module remains in the standard library, and may be useful if you
wish to subclass the <code class="xref py py-class docutils literal notranslate"><span class="pre">Set</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">ImmutableSet</span></code> classes.  There are
currently no plans to deprecate the module.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0218"><strong>PEP 218</strong></a> - Adding a Built-In Set Object Type</dt>
<dd>Originally proposed by Greg Wilson and ultimately implemented by Raymond
Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-237-unifying-long-integers-and-integers">
<h2>PEP 237: Unifying Long Integers and Integers<a class="headerlink" href="#pep-237-unifying-long-integers-and-integers" title="Permalink to this headline">¶</a></h2>
<p>The lengthy transition process for this PEP, begun in Python 2.2, takes another
step forward in Python 2.4.  In 2.3, certain integer operations that would
behave differently after int/long unification triggered <a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a>
warnings and returned values limited to 32 or 64 bits (depending on your
platform).  In 2.4, these expressions no longer produce a warning and instead
produce a different result that’s usually a long integer.</p>
<p>The problematic expressions are primarily left shifts and lengthy hexadecimal
and octal constants.  For example, <code class="docutils literal notranslate"><span class="pre">2</span> <span class="pre">&lt;&lt;</span> <span class="pre">32</span></code> results in a warning in 2.3,
evaluating to 0 on 32-bit platforms.  In Python 2.4, this expression now returns
the correct answer, 8589934592.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a> - Unifying Long Integers and Integers</dt>
<dd>Original PEP written by Moshe Zadka and GvR.  The changes for 2.4 were
implemented by  Kalle Svensson.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-289-generator-expressions">
<h2>PEP 289: Generator Expressions<a class="headerlink" href="#pep-289-generator-expressions" title="Permalink to this headline">¶</a></h2>
<p>The iterator feature introduced in Python 2.2 and the <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module
make it easier to write programs that loop through large data sets without
having the entire data set in memory at one time.  List comprehensions don’t fit
into this picture very well because they produce a Python list object containing
all of the items.  This unavoidably pulls all of the objects into memory, which
can be a problem if your data set is very large.  When trying to write a
functionally-styled program, it would be natural to write something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">links</span> <span class="o">=</span> <span class="p">[</span><span class="n">link</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">]</span>
<span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>instead of</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">():</span>
    <span class="k">if</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">:</span>
        <span class="k">continue</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The first form is more concise and perhaps more readable, but if you’re dealing
with a large number of link objects you’d have to write the second form to avoid
having all link objects in memory at the same time.</p>
<p>Generator expressions work similarly to list comprehensions but don’t
materialize the entire list; instead they create a generator that will return
elements one by one.  The above example could be written as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">links</span> <span class="o">=</span> <span class="p">(</span><span class="n">link</span> <span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">get_all_links</span><span class="p">()</span> <span class="k">if</span> <span class="ow">not</span> <span class="n">link</span><span class="o">.</span><span class="n">followed</span><span class="p">)</span>
<span class="k">for</span> <span class="n">link</span> <span class="ow">in</span> <span class="n">links</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Generator expressions always have to be written inside parentheses, as in the
above example.  The parentheses signalling a function call also count, so if you
want to create an iterator that will be immediately passed to a function you
could write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">print</span> <span class="nb">sum</span><span class="p">(</span><span class="n">obj</span><span class="o">.</span><span class="n">count</span> <span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">list_all_objects</span><span class="p">())</span>
</pre></div>
</div>
<p>Generator expressions differ from list comprehensions in various small ways.
Most notably, the loop variable (<em>obj</em> in the above example) is not accessible
outside of the generator expression.  List comprehensions leave the variable
assigned to its last value; future versions of Python will change this, making
list comprehensions match generator expressions in this respect.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a> - Generator Expressions</dt>
<dd>Proposed by Raymond Hettinger and implemented by Jiwon Seo with early efforts
steered by Hye-Shik Chang.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-292-simpler-string-substitutions">
<h2>PEP 292: Simpler String Substitutions<a class="headerlink" href="#pep-292-simpler-string-substitutions" title="Permalink to this headline">¶</a></h2>
<p>Some new classes in the standard library provide an alternative mechanism for
substituting variables into strings; this style of substitution may be better
for applications where untrained users need to edit templates.</p>
<p>The usual way of substituting variables by name is the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">%(page)i</span><span class="s1">: </span><span class="si">%(title)s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">{</span><span class="s1">&#39;page&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;title&#39;</span><span class="p">:</span> <span class="s1">&#39;The Best of Times&#39;</span><span class="p">}</span>
<span class="go">&#39;2: The Best of Times&#39;</span>
</pre></div>
</div>
<p>When writing the template string, it can be easy to forget the <code class="docutils literal notranslate"><span class="pre">i</span></code> or <code class="docutils literal notranslate"><span class="pre">s</span></code>
after the closing parenthesis.  This isn’t a big problem if the template is in a
Python module, because you run the code, get an “Unsupported format character”
<a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, and fix the problem.  However, consider an application such
as Mailman where template strings or translations are being edited by users who
aren’t aware of the Python language.  The format string’s syntax is complicated
to explain to such users, and if they make a mistake, it’s difficult to provide
helpful feedback to them.</p>
<p>PEP 292 adds a <code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code> class to the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module that uses
<code class="docutils literal notranslate"><span class="pre">$</span></code> to indicate a substitution:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$page: $title&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">({</span><span class="s1">&#39;page&#39;</span><span class="p">:</span><span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;title&#39;</span><span class="p">:</span> <span class="s1">&#39;The Best of Times&#39;</span><span class="p">})</span>
<span class="go">&#39;2: The Best of Times&#39;</span>
</pre></div>
</div>
<p>If a key is missing from the dictionary, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code> method will
raise a <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>.  There’s also a <code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code> method that
ignores missing keys:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="n">string</span><span class="o">.</span><span class="n">Template</span><span class="p">(</span><span class="s1">&#39;$page: $title&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">({</span><span class="s1">&#39;page&#39;</span><span class="p">:</span><span class="mi">3</span><span class="p">})</span>
<span class="go">&#39;3: $title&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0292"><strong>PEP 292</strong></a> - Simpler String Substitutions</dt>
<dd>Written and implemented  by Barry Warsaw.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-318-decorators-for-functions-and-methods">
<h2>PEP 318: Decorators for Functions and Methods<a class="headerlink" href="#pep-318-decorators-for-functions-and-methods" title="Permalink to this headline">¶</a></h2>
<p>Python 2.2 extended Python’s object model by adding static methods and class
methods, but it didn’t extend Python’s syntax to provide any new way of defining
static or class methods.  Instead, you had to write a <a class="reference internal" href="../reference/compound_stmts.html#def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">def</span></code></a> statement
in the usual way, and pass the resulting method to a <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> or
<a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> function that would wrap up the function as a method of the
new type. Your code would look like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
   <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
       <span class="o">...</span>

   <span class="n">meth</span> <span class="o">=</span> <span class="nb">classmethod</span><span class="p">(</span><span class="n">meth</span><span class="p">)</span>   <span class="c1"># Rebind name to wrapped-up class method</span>
</pre></div>
</div>
<p>If the method was very long, it would be easy to miss or forget the
<a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> invocation after the function body.</p>
<p>The intention was always to add some syntax to make such definitions more
readable, but at the time of 2.2’s release a good syntax was not obvious.  Today
a good syntax <em>still</em> isn’t obvious but users are asking for easier access to
the feature; a new syntactic feature has been added to meet this need.</p>
<p>The new feature is called “function decorators”.  The name comes from the idea
that <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a>, <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a>, and friends are storing
additional information on a function object; they’re <em>decorating</em> functions with
more details.</p>
<p>The notation borrows from Java and uses the <code class="docutils literal notranslate"><span class="pre">'&#64;'</span></code> character as an indicator.
Using the new syntax, the example above would be written:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>

   <span class="nd">@classmethod</span>
   <span class="k">def</span> <span class="nf">meth</span> <span class="p">(</span><span class="bp">cls</span><span class="p">):</span>
       <span class="o">...</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">&#64;classmethod</span></code> is shorthand for the <code class="docutils literal notranslate"><span class="pre">meth=classmethod(meth)</span></code> assignment.
More generally, if you have the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@A</span>
<span class="nd">@B</span>
<span class="nd">@C</span>
<span class="k">def</span> <span class="nf">f</span> <span class="p">():</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>It’s equivalent to the following pre-decorator code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="o">...</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="n">B</span><span class="p">(</span><span class="n">C</span><span class="p">(</span><span class="n">f</span><span class="p">)))</span>
</pre></div>
</div>
<p>Decorators must come on the line before a function definition, one decorator per
line, and can’t be on the same line as the def statement, meaning that <code class="docutils literal notranslate"><span class="pre">&#64;A</span> <span class="pre">def</span>
<span class="pre">f():</span> <span class="pre">...</span></code> is illegal.  You can only decorate function definitions, either at
the module level or inside a class; you can’t decorate class definitions.</p>
<p>A decorator is just a function that takes the function to be decorated as an
argument and returns either the same function or some new object.  The return
value of the decorator need not be callable (though it typically is), unless
further decorators will be applied to the result.  It’s easy to write your own
decorators.  The following simple example just sets an attribute on the function
object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">deco</span><span class="p">(</span><span class="n">func</span><span class="p">):</span>
<span class="gp">... </span>   <span class="n">func</span><span class="o">.</span><span class="n">attr</span> <span class="o">=</span> <span class="s1">&#39;decorated&#39;</span>
<span class="gp">... </span>   <span class="k">return</span> <span class="n">func</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nd">@deco</span>
<span class="gp">... </span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span>
<span class="go">&lt;function f at 0x402ef0d4&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="o">.</span><span class="n">attr</span>
<span class="go">&#39;decorated&#39;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>As a slightly more realistic example, the following decorator checks that the
supplied argument is an integer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">require_int</span> <span class="p">(</span><span class="n">func</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">wrapper</span> <span class="p">(</span><span class="n">arg</span><span class="p">):</span>
        <span class="k">assert</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="nb">int</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">func</span><span class="p">(</span><span class="n">arg</span><span class="p">)</span>

    <span class="k">return</span> <span class="n">wrapper</span>

<span class="nd">@require_int</span>
<span class="k">def</span> <span class="nf">p1</span> <span class="p">(</span><span class="n">arg</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">arg</span>

<span class="nd">@require_int</span>
<span class="k">def</span> <span class="nf">p2</span><span class="p">(</span><span class="n">arg</span><span class="p">):</span>
    <span class="nb">print</span> <span class="n">arg</span><span class="o">*</span><span class="mi">2</span>
</pre></div>
</div>
<p>An example in <span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a> contains a fancier version of this idea that lets you
both specify the required type and check the returned type.</p>
<p>Decorator functions can take arguments.  If arguments are supplied, your
decorator function is called with only those arguments and must return a new
decorator function; this function must take a single function and return a
function, as previously described.  In other words, <code class="docutils literal notranslate"><span class="pre">&#64;A</span> <span class="pre">&#64;B</span> <span class="pre">&#64;C(args)</span></code> becomes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span><span class="p">():</span> <span class="o">...</span>
<span class="n">_deco</span> <span class="o">=</span> <span class="n">C</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
<span class="n">f</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="n">B</span><span class="p">(</span><span class="n">_deco</span><span class="p">(</span><span class="n">f</span><span class="p">)))</span>
</pre></div>
</div>
<p>Getting this right can be slightly brain-bending, but it’s not too difficult.</p>
<p>A small related change makes the <code class="xref py py-attr docutils literal notranslate"><span class="pre">func_name</span></code> attribute of functions
writable.  This attribute is used to display function names in tracebacks, so
decorators should change the name of any new function that’s constructed and
returned.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a> - Decorators for Functions, Methods and Classes</dt>
<dd>Written  by Kevin D. Smith, Jim Jewett, and Skip Montanaro.  Several people
wrote patches implementing function decorators, but the one that was actually
checked in was patch #979728, written by Mark Russell.</dd>
<dt><a class="reference external" href="https://wiki.python.org/moin/PythonDecoratorLibrary">https://wiki.python.org/moin/PythonDecoratorLibrary</a></dt>
<dd>This Wiki page contains several examples of decorators.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-322-reverse-iteration">
<h2>PEP 322: Reverse Iteration<a class="headerlink" href="#pep-322-reverse-iteration" title="Permalink to this headline">¶</a></h2>
<p>A new built-in function, <code class="docutils literal notranslate"><span class="pre">reversed(seq)</span></code>, takes a sequence and returns an
iterator that loops over the elements of the sequence  in reverse order.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="n">xrange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">4</span><span class="p">)):</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">i</span>
<span class="gp">...</span>
<span class="go">3</span>
<span class="go">2</span>
<span class="go">1</span>
</pre></div>
</div>
<p>Compared to extended slicing, such as <code class="docutils literal notranslate"><span class="pre">range(1,4)[::-1]</span></code>, <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> is
easier to read, runs faster, and uses substantially less memory.</p>
<p>Note that <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> only accepts sequences, not arbitrary iterators.  If
you want to reverse an iterator, first convert it to  a list with <code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">input</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">reversed</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="nb">input</span><span class="p">)):</span>
<span class="gp">... </span>  <span class="nb">print</span> <span class="n">line</span>
<span class="gp">...</span>
<span class="go">root:*:0:0:System Administrator:/var/root:/bin/tcsh</span>
<span class="go">  ...</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0322"><strong>PEP 322</strong></a> - Reverse Iteration</dt>
<dd>Written and implemented by Raymond Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-324-new-subprocess-module">
<h2>PEP 324: New subprocess Module<a class="headerlink" href="#pep-324-new-subprocess-module" title="Permalink to this headline">¶</a></h2>
<p>The standard library provides a number of ways to execute a subprocess, offering
different features and different levels of complexity.
<code class="docutils literal notranslate"><span class="pre">os.system(command)</span></code> is easy to use, but slow (it runs a shell process
which executes the command) and dangerous (you have to be careful about escaping
the shell’s metacharacters).  The <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module offers classes that can
capture standard output and standard error from the subprocess, but the naming
is confusing.  The <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module cleans  this up, providing a unified
interface that offers all the features you might need.</p>
<p>Instead of <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a>’s collection of classes, <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> contains a
single class called <code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code>  whose constructor supports a number of
different keyword arguments.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Popen</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="n">bufsize</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">executable</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
            <span class="n">stdin</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">stdout</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">stderr</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
            <span class="n">preexec_fn</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">close_fds</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
            <span class="n">cwd</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">env</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">universal_newlines</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span>
            <span class="n">startupinfo</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">creationflags</span><span class="o">=</span><span class="mi">0</span><span class="p">):</span>
</pre></div>
</div>
<p><em>args</em> is commonly a sequence of strings that will be the arguments to the
program executed as the subprocess.  (If the <em>shell</em> argument is true, <em>args</em>
can be a string which will then be passed on to the shell for interpretation,
just as <a class="reference internal" href="../library/os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a> does.)</p>
<p><em>stdin</em>, <em>stdout</em>, and <em>stderr</em> specify what the subprocess’s input, output, and
error streams will be.  You can provide a file object or a file descriptor, or
you can use the constant <code class="docutils literal notranslate"><span class="pre">subprocess.PIPE</span></code> to create a pipe between the
subprocess and the parent.</p>
<p id="index-7">The constructor has a number of handy options:</p>
<ul class="simple">
<li><em>close_fds</em> requests that all file descriptors be closed before running the
subprocess.</li>
<li><em>cwd</em> specifies the working directory in which the subprocess will be executed
(defaulting to whatever the parent’s working directory is).</li>
<li><em>env</em> is a dictionary specifying environment variables.</li>
<li><em>preexec_fn</em> is a function that gets called before the child is started.</li>
<li><em>universal_newlines</em> opens the child’s input and output using Python’s
<a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a> feature.</li>
</ul>
<p>Once you’ve created the <code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code> instance,  you can call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code>
method to pause until the subprocess has exited, <code class="xref py py-meth docutils literal notranslate"><span class="pre">poll()</span></code> to check if it’s
exited without pausing,  or <code class="docutils literal notranslate"><span class="pre">communicate(data)</span></code> to send the string <em>data</em>
to the subprocess’s standard input.   <code class="docutils literal notranslate"><span class="pre">communicate(data)</span></code>  then reads any
data that the subprocess has sent to its standard output  or standard error,
returning a tuple <code class="docutils literal notranslate"><span class="pre">(stdout_data,</span> <span class="pre">stderr_data)</span></code>.</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">call()</span></code> is a shortcut that passes its arguments along to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code>
constructor, waits for the command to complete, and returns the status code of
the subprocess.  It can serve as a safer analog to <a class="reference internal" href="../library/os.html#os.system" title="os.system"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.system()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sts</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">([</span><span class="s1">&#39;dpkg&#39;</span><span class="p">,</span> <span class="s1">&#39;-i&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp/new-package.deb&#39;</span><span class="p">])</span>
<span class="k">if</span> <span class="n">sts</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
    <span class="c1"># Success</span>
    <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
    <span class="c1"># dpkg returned an error</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The command is invoked without use of the shell.  If you really do want to  use
the shell, you can add <code class="docutils literal notranslate"><span class="pre">shell=True</span></code> as a keyword argument and provide a string
instead of a sequence:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">sts</span> <span class="o">=</span> <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="s1">&#39;dpkg -i /tmp/new-package.deb&#39;</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>The PEP takes various examples of shell and Python code and shows how they’d be
translated into Python code that uses <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>.  Reading this section
of the PEP is highly recommended.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0324"><strong>PEP 324</strong></a> - subprocess - New process module</dt>
<dd>Written and implemented by Peter Åstrand, with assistance from Fredrik Lundh and
others.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-327-decimal-data-type">
<h2>PEP 327: Decimal Data Type<a class="headerlink" href="#pep-327-decimal-data-type" title="Permalink to this headline">¶</a></h2>
<p>Python has always supported floating-point (FP) numbers, based on the underlying
C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> type, as a data type.  However, while most programming
languages provide a floating-point type, many people (even programmers) are
unaware that floating-point numbers don’t represent certain decimal fractions
accurately.  The new <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> type can represent these fractions
accurately, up to a user-specified precision limit.</p>
<div class="section" id="why-is-decimal-needed">
<h3>Why is Decimal needed?<a class="headerlink" href="#why-is-decimal-needed" title="Permalink to this headline">¶</a></h3>
<p>The limitations arise from the representation used for floating-point numbers.
FP numbers are made up of three components:</p>
<ul class="simple">
<li>The sign, which is positive or negative.</li>
<li>The mantissa, which is a single-digit binary number   followed by a fractional
part.  For example, <code class="docutils literal notranslate"><span class="pre">1.01</span></code> in base-2 notation is <code class="docutils literal notranslate"><span class="pre">1</span> <span class="pre">+</span> <span class="pre">0/2</span> <span class="pre">+</span> <span class="pre">1/4</span></code>, or 1.25 in
decimal notation.</li>
<li>The exponent, which tells where the decimal point is located in the number
represented.</li>
</ul>
<p>For example, the number 1.25 has positive sign, a mantissa value of 1.01 (in
binary), and an exponent of 0 (the decimal point doesn’t need to be shifted).
The number 5 has the same sign and mantissa, but the exponent is 2 because the
mantissa is multiplied by 4 (2 to the power of the exponent 2); 1.25 * 4 equals
5.</p>
<p>Modern systems usually provide floating-point support that conforms to a
standard called IEEE 754.  C’s <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> type is usually implemented as a
64-bit IEEE 754 number, which uses 52 bits of space for the mantissa.  This
means that numbers can only be specified to 52 bits of precision.  If you’re
trying to represent numbers whose expansion repeats endlessly, the expansion is
cut off after 52 bits. Unfortunately, most software needs to produce output in
base 10, and common fractions in base 10 are often repeating decimals in binary.
For example, 1.1 decimal is binary <code class="docutils literal notranslate"><span class="pre">1.0001100110011</span> <span class="pre">...</span></code>; .1 = 1/16 + 1/32 +
1/256 plus an infinite number of additional terms.  IEEE 754 has to chop off
that infinitely repeated decimal after 52 digits, so the representation is
slightly inaccurate.</p>
<p>Sometimes you can see this inaccuracy when the number is printed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mf">1.1</span>
<span class="go">1.1000000000000001</span>
</pre></div>
</div>
<p>The inaccuracy isn’t always visible when you print the number because the
FP-to-decimal-string conversion is provided by the C library, and most C libraries try
to produce sensible output.  Even if it’s not displayed, however, the inaccuracy
is still there and subsequent operations can magnify the error.</p>
<p>For many applications this doesn’t matter.  If I’m plotting points and
displaying them on my monitor, the difference between 1.1 and 1.1000000000000001
is too small to be visible.  Reports often limit output to a certain number of
decimal places, and if you round the number to two or three or even eight
decimal places, the error is never apparent.  However, for applications where it
does matter,  it’s a lot of work to implement your own custom arithmetic
routines.</p>
<p>Hence, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> type was created.</p>
</div>
<div class="section" id="the-decimal-type">
<h3>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> type<a class="headerlink" href="#the-decimal-type" title="Permalink to this headline">¶</a></h3>
<p>A new module, <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a>, was added to Python’s standard library.  It
contains two classes, <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code>.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code>
instances represent numbers, and <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> instances are used to wrap up
various settings such as the precision and default rounding mode.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> instances are immutable, like regular Python integers and FP
numbers; once it’s been created, you can’t change the value an instance
represents.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> instances can be created from integers or
strings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">decimal</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1972</span><span class="p">)</span>
<span class="go">Decimal(&quot;1972&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s2">&quot;1.1&quot;</span><span class="p">)</span>
<span class="go">Decimal(&quot;1.1&quot;)</span>
</pre></div>
</div>
<p>You can also provide tuples containing the sign, the mantissa represented  as a
tuple of decimal digits, and the exponent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">((</span><span class="mi">1</span><span class="p">,</span> <span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">5</span><span class="p">),</span> <span class="o">-</span><span class="mi">2</span><span class="p">))</span>
<span class="go">Decimal(&quot;-14.75&quot;)</span>
</pre></div>
</div>
<p>Cautionary note: the sign bit is a Boolean value, so 0 is positive and 1 is
negative.</p>
<p>Converting from floating-point numbers poses a bit of a problem: should the FP
number representing 1.1 turn into the decimal number for exactly 1.1, or for 1.1
plus whatever inaccuracies are introduced? The decision was to dodge the issue
and leave such a conversion out of the API.  Instead, you should convert the
floating-point number into a string using the desired precision and pass the
string to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> constructor:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">f</span> <span class="o">=</span> <span class="mf">1.1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">f</span><span class="p">))</span>
<span class="go">Decimal(&quot;1.1&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;</span><span class="si">%.12f</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="n">f</span><span class="p">)</span>
<span class="go">Decimal(&quot;1.100000000000&quot;)</span>
</pre></div>
</div>
<p>Once you have <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> instances, you can perform the usual mathematical
operations on them.  One limitation: exponentiation requires an integer
exponent:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;35.72&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;1.73&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="go">Decimal(&quot;37.45&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">-</span><span class="n">b</span>
<span class="go">Decimal(&quot;33.99&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">*</span><span class="n">b</span>
<span class="go">Decimal(&quot;61.7956&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">/</span><span class="n">b</span>
<span class="go">Decimal(&quot;20.64739884393063583815028902&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">**</span> <span class="mi">2</span>
<span class="go">Decimal(&quot;1275.9184&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">**</span><span class="n">b</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">decimal.InvalidOperation</span>: <span class="n">x ** (non-integer)</span>
</pre></div>
</div>
<p>You can combine <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> instances with integers, but not with
floating-point numbers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">+</span> <span class="mi">4</span>
<span class="go">Decimal(&quot;39.72&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">+</span> <span class="mf">4.5</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">You can interact Decimal only with int, long or Decimal data types.</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> numbers can be used with the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> and <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a>
modules, but note that they’ll be immediately converted to  floating-point
numbers before the operation is performed, resulting in a possible loss of
precision and accuracy.  You’ll also get back a regular floating-point number
and not a <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">math</span><span class="o">,</span> <span class="nn">cmath</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;123456789012.345&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">math</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
<span class="go">351364.18288201344</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">cmath</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="o">-</span><span class="n">d</span><span class="p">)</span>
<span class="go">351364.18288201344j</span>
</pre></div>
</div>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> instances have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">sqrt()</span></code> method that returns a
<code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code>, but if you need other things such as trigonometric functions
you’ll have to implement them.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
<span class="go">Decimal(&quot;351364.1828820134592177245001&quot;)</span>
</pre></div>
</div>
</div>
<div class="section" id="the-context-type">
<h3>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> type<a class="headerlink" href="#the-context-type" title="Permalink to this headline">¶</a></h3>
<p>Instances of the <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> class encapsulate several settings for
decimal operations:</p>
<ul class="simple">
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">prec</span></code> is the precision, the number of decimal places.</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">rounding</span></code> specifies the rounding mode.  The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module has
constants for the various possibilities: <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_DOWN</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_CEILING</span></code>,  <code class="xref py py-const docutils literal notranslate"><span class="pre">ROUND_HALF_EVEN</span></code>, and various others.</li>
<li><code class="xref py py-attr docutils literal notranslate"><span class="pre">traps</span></code> is a dictionary specifying what happens on encountering certain
error conditions: either  an exception is raised or  a value is returned.  Some
examples of error conditions are division by zero, loss of precision, and
overflow.</li>
</ul>
<p>There’s a thread-local default context available by calling <code class="xref py py-func docutils literal notranslate"><span class="pre">getcontext()</span></code>;
you can change the properties of this context to alter the default precision,
rounding, or trap handling.  The following example shows the effect of changing
the precision of the default context:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span>
<span class="go">28</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&quot;0.1428571428571428571428571429&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
<span class="go">Decimal(&quot;0.142857143&quot;)</span>
</pre></div>
</div>
<p>The default action for error conditions is selectable; the module can either
return a special value such as infinity or not-a-number, or exceptions can be
raised:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">decimal.DivisionByZero</span>: <span class="n">x / 0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">traps</span><span class="p">[</span><span class="n">decimal</span><span class="o">.</span><span class="n">DivisionByZero</span><span class="p">]</span> <span class="o">=</span> <span class="kc">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">decimal</span><span class="o">.</span><span class="n">Decimal</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">Decimal(&quot;Infinity&quot;)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> instance also has various methods for formatting  numbers
such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">to_eng_string()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">to_sci_string()</span></code>.</p>
<p>For more information, see the documentation for the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module, which
includes a quick-start tutorial and a reference.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0327"><strong>PEP 327</strong></a> - Decimal Data Type</dt>
<dd>Written by Facundo Batista and implemented by Facundo Batista, Eric Price,
Raymond Hettinger, Aahz, and Tim Peters.</dd>
<dt><a class="reference external" href="http://www.lahey.com/float.htm">http://www.lahey.com/float.htm</a></dt>
<dd>The article uses Fortran code to illustrate many of the problems that
floating-point inaccuracy can cause.</dd>
<dt><a class="reference external" href="http://speleotrove.com/decimal/">http://speleotrove.com/decimal/</a></dt>
<dd>A description of a decimal-based representation.  This representation is being
proposed as a standard, and underlies the new Python decimal type.  Much of this
material was written by Mike Cowlishaw, designer of the Rexx language.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="pep-328-multi-line-imports">
<h2>PEP 328: Multi-line Imports<a class="headerlink" href="#pep-328-multi-line-imports" title="Permalink to this headline">¶</a></h2>
<p>One language change is a small syntactic tweak aimed at making it easier to
import many names from a module.  In a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">names</span></code> statement,
<em>names</em> is a sequence of names separated by commas.  If the sequence is  very
long, you can either write multiple imports from the same module, or you can use
backslashes to escape the line endings like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="n">SimpleXMLRPCServer</span><span class="p">,</span>\
            <span class="n">SimpleXMLRPCRequestHandler</span><span class="p">,</span>\
            <span class="n">CGIXMLRPCRequestHandler</span><span class="p">,</span>\
            <span class="n">resolve_dotted_attribute</span>
</pre></div>
</div>
<p>The syntactic change in Python 2.4 simply allows putting the names within
parentheses.  Python ignores newlines within a parenthesized expression, so the
backslashes are no longer needed:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">SimpleXMLRPCServer</span> <span class="k">import</span> <span class="p">(</span><span class="n">SimpleXMLRPCServer</span><span class="p">,</span>
                                <span class="n">SimpleXMLRPCRequestHandler</span><span class="p">,</span>
                                <span class="n">CGIXMLRPCRequestHandler</span><span class="p">,</span>
                                <span class="n">resolve_dotted_attribute</span><span class="p">)</span>
</pre></div>
</div>
<p>The PEP also proposes that all <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements be absolute imports,
with a leading <code class="docutils literal notranslate"><span class="pre">.</span></code> character to indicate a relative import.  This part of the
PEP was not implemented for Python 2.4, but was completed for Python 2.5.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt>
<dd>Written by Aahz.  Multi-line imports were implemented by Dima Dorfman.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-331-locale-independent-float-string-conversions">
<h2>PEP 331: Locale-Independent Float/String Conversions<a class="headerlink" href="#pep-331-locale-independent-float-string-conversions" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> modules lets Python software select various conversions and
display conventions that are localized to a particular country or language.
However, the module was careful to not change the numeric locale because various
functions in Python’s implementation required that the numeric locale remain set
to the <code class="docutils literal notranslate"><span class="pre">'C'</span></code> locale.  Often this was because the code was using the C
library’s <code class="xref c c-func docutils literal notranslate"><span class="pre">atof()</span></code> function.</p>
<p>Not setting the numeric locale caused trouble for extensions that used third-party
C libraries, however, because they wouldn’t have the correct locale set.
The motivating example was GTK+, whose user interface widgets weren’t displaying
numbers in the current locale.</p>
<p>The solution described in the PEP is to add three new functions to the Python
API that perform ASCII-only conversions, ignoring the locale setting:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">PyOS_ascii_strtod(str,</span> <span class="pre">ptr)</span></code>  and <code class="docutils literal notranslate"><span class="pre">PyOS_ascii_atof(str,</span> <span class="pre">ptr)</span></code>
both convert a string to a C <code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code>.</li>
<li><code class="docutils literal notranslate"><span class="pre">PyOS_ascii_formatd(buffer,</span> <span class="pre">buf_len,</span> <span class="pre">format,</span> <span class="pre">d)</span></code> converts a
<code class="xref c c-type docutils literal notranslate"><span class="pre">double</span></code> to an ASCII string.</li>
</ul>
<p>The code for these functions came from the GLib library
(<a class="reference external" href="https://developer.gnome.org/glib/stable/">https://developer.gnome.org/glib/stable/</a>), whose developers kindly
relicensed the relevant functions and donated them to the Python Software
Foundation.  The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module  can now change the numeric locale,
letting extensions such as GTK+  produce the correct results.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0331"><strong>PEP 331</strong></a> - Locale-Independent Float/String Conversions</dt>
<dd>Written by Christian R. Reis, and implemented by Gustavo Carneiro.</dd>
</dl>
</div>
</div>
<div class="section" id="other-language-changes">
<h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Here are all of the changes that Python 2.4 makes to the core Python language.</p>
<ul>
<li><p class="first">Decorators for functions and methods were added (<span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0318"><strong>PEP 318</strong></a>).</p>
</li>
<li><p class="first">Built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> types were  added (<span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0218"><strong>PEP 218</strong></a>).
Other new built-ins include the <code class="docutils literal notranslate"><span class="pre">reversed(seq)</span></code> function (<span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0322"><strong>PEP 322</strong></a>).</p>
</li>
<li><p class="first">Generator expressions were added (<span class="target" id="index-15"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0289"><strong>PEP 289</strong></a>).</p>
</li>
<li><p class="first">Certain numeric expressions no longer return values restricted to 32 or 64
bits (<span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0237"><strong>PEP 237</strong></a>).</p>
</li>
<li><p class="first">You can now put parentheses around the list of names in a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span>
<span class="pre">names</span></code> statement (<span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a>).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/stdtypes.html#dict.update" title="dict.update"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.update()</span></code></a> method now accepts the same argument forms as the
<a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> constructor.  This includes any mapping, any iterable of key/value
pairs, and keyword arguments. (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The string methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">ljust()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">rjust()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">center()</span></code> now take
an optional argument for specifying a fill character other than a space.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Strings also gained an <code class="xref py py-meth docutils literal notranslate"><span class="pre">rsplit()</span></code> method that works like the <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code>
method but splits from the end of the string.   (Contributed by Sean
Reifschneider.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="go">[&#39;www&#39;, &#39;python.org&#39;]</span>
<span class="go">&#39;www.python.org&#39;.rsplit(&#39;.&#39;, 1)</span>
<span class="go">[&#39;www.python&#39;, &#39;org&#39;]</span>
</pre></div>
</div>
</li>
<li><p class="first">Three keyword parameters, <em>cmp</em>, <em>key</em>, and <em>reverse</em>, were added to the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method of lists. These parameters make some common usages of
<code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> simpler. All of these parameters are optional.</p>
<p>For the <em>cmp</em> parameter, the value should be a comparison function that takes
two parameters and returns -1, 0, or +1 depending on how the parameters compare.
This function will then be used to sort the list.  Previously this was the only
parameter that could be provided to <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code>.</p>
<p><em>key</em> should be a single-parameter function that takes a list element and
returns a comparison key for the element.  The list is then sorted using the
comparison keys.  The following example sorts a list case-insensitively:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;A&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;D&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>                 <span class="c1"># Case-sensitive sort</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[&#39;A&#39;, &#39;D&#39;, &#39;b&#39;, &#39;c&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Using &#39;key&#39; parameter to sort list</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[&#39;A&#39;, &#39;b&#39;, &#39;c&#39;, &#39;D&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Old-fashioned way</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="nb">cmp</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">:</span> <span class="nb">cmp</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">lower</span><span class="p">(),</span> <span class="n">y</span><span class="o">.</span><span class="n">lower</span><span class="p">()))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[&#39;A&#39;, &#39;b&#39;, &#39;c&#39;, &#39;D&#39;]</span>
</pre></div>
</div>
<p>The last example, which uses the <em>cmp</em> parameter, is the old way to perform a
case-insensitive sort.  It works but is slower than using a <em>key</em> parameter.
Using <em>key</em> calls <code class="xref py py-meth docutils literal notranslate"><span class="pre">lower()</span></code> method once for each element in the list while
using <em>cmp</em> will call it twice for each comparison, so using <em>key</em> saves on
invocations of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">lower()</span></code> method.</p>
<p>For simple key functions and comparison functions, it is often possible to avoid
a <a class="reference internal" href="../reference/expressions.html#lambda"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">lambda</span></code></a> expression by using an unbound method instead.  For example,
the above case-insensitive sort is best written as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span><span class="o">.</span><span class="n">sort</span><span class="p">(</span><span class="n">key</span><span class="o">=</span><span class="nb">str</span><span class="o">.</span><span class="n">lower</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>
<span class="go">[&#39;A&#39;, &#39;b&#39;, &#39;c&#39;, &#39;D&#39;]</span>
</pre></div>
</div>
<p>Finally, the <em>reverse</em> parameter takes a Boolean value.  If the value is true,
the list will be sorted into reverse order. Instead of <code class="docutils literal notranslate"><span class="pre">L.sort();</span>
<span class="pre">L.reverse()</span></code>, you can now write <code class="docutils literal notranslate"><span class="pre">L.sort(reverse=True)</span></code>.</p>
<p>The results of sorting are now guaranteed to be stable.  This means that two
entries with equal keys will be returned in the same order as they were input.
For example, you can sort a list of people by name, and then sort the list by
age, resulting in a list sorted by age where people with the same age are in
name-sorted order.</p>
<p>(All changes to <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">There is a new built-in function <code class="docutils literal notranslate"><span class="pre">sorted(iterable)</span></code> that works like the
in-place <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method but can be used in expressions.  The
differences are:</p>
</li>
<li><p class="first">the input may be any iterable;</p>
</li>
<li><p class="first">a newly formed copy is sorted, leaving the original intact; and</p>
</li>
<li><p class="first">the expression returns the new sorted copy</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">9</span><span class="p">,</span><span class="mi">7</span><span class="p">,</span><span class="mi">8</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">6</span><span class="p">,</span><span class="mi">5</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="mi">10</span><span class="o">+</span><span class="n">i</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">L</span><span class="p">)]</span>       <span class="c1"># usable in a list comprehension</span>
<span class="go">[11, 12, 13, 14, 15, 16, 17, 18, 19]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span>                               <span class="c1"># original is left unchanged</span>
<span class="go">[9,7,8,3,2,4,1,6,5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="s1">&#39;Monty Python&#39;</span><span class="p">)</span>          <span class="c1"># any iterable may be an input</span>
<span class="go">[&#39; &#39;, &#39;M&#39;, &#39;P&#39;, &#39;h&#39;, &#39;n&#39;, &#39;n&#39;, &#39;o&#39;, &#39;o&#39;, &#39;t&#39;, &#39;t&#39;, &#39;y&#39;, &#39;y&#39;]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># List the contents of a dict sorted by key values</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">colormap</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">red</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">blue</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">green</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">black</span><span class="o">=</span><span class="mi">4</span><span class="p">,</span> <span class="n">yellow</span><span class="o">=</span><span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">colormap</span><span class="o">.</span><span class="n">iteritems</span><span class="p">()):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
<span class="gp">...</span>
<span class="go">black 4</span>
<span class="go">blue 2</span>
<span class="go">green 3</span>
<span class="go">red 1</span>
<span class="go">yellow 5</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Integer operations will no longer trigger an <code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowWarning</span></code>. The
<code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowWarning</span></code> warning will disappear in Python 2.5.</p>
</li>
<li><p class="first">The interpreter gained a new switch, <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a>, that takes a name, searches
for the corresponding  module on <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, and runs the module as a script.
For example,  you can now run the Python profiler with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">profile</span></code>.
(Contributed by Nick Coghlan.)</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">eval(expr,</span> <span class="pre">globals,</span> <span class="pre">locals)</span></code> and <code class="docutils literal notranslate"><span class="pre">execfile(filename,</span> <span class="pre">globals,</span>
<span class="pre">locals)</span></code> functions and the <a class="reference internal" href="../reference/simple_stmts.html#exec"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">exec</span></code></a> statement now accept any mapping type
for the <em>locals</em> parameter.  Previously this had to be a regular Python
dictionary.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> built-in function and <a class="reference internal" href="../library/itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a> now return an
empty list if called with no arguments. Previously they raised a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception.  This makes them more suitable for use with variable
length argument lists:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">transpose</span><span class="p">(</span><span class="n">array</span><span class="p">):</span>
<span class="gp">... </span>   <span class="k">return</span> <span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">array</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transpose</span><span class="p">([(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">)])</span>
<span class="go">[(1, 4), (2, 5), (3, 6)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transpose</span><span class="p">([])</span>
<span class="go">[]</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Encountering a failure while importing a module no longer leaves a partially-initialized
module object in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.  The incomplete module object left
behind would fool further imports of the same module into succeeding, leading to
confusing errors.   (Fixed by Tim Peters.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is now a constant; code that binds a new value to  the name
<code class="docutils literal notranslate"><span class="pre">None</span></code> is now a syntax error. (Contributed by Raymond Hettinger.)</p>
</li>
</ul>
<div class="section" id="optimizations">
<h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The inner loops for list and tuple slicing were optimized and now run about
one-third faster.  The inner loops for dictionaries were also optimized,
resulting in performance boosts for <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">itervalues()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">iteritems()</span></code>. (Contributed by
Raymond Hettinger.)</li>
<li>The machinery for growing and shrinking lists was optimized for speed and for
space efficiency.  Appending and popping from lists now runs faster due to more
efficient code paths and less frequent use of the underlying system
<code class="xref c c-func docutils literal notranslate"><span class="pre">realloc()</span></code>.  List comprehensions also benefit.   <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.extend()</span></code> was
also optimized and no longer converts its argument into a temporary list before
extending the base list.  (Contributed by Raymond Hettinger.)</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code>, <a class="reference internal" href="../library/functions.html#tuple" title="tuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">tuple()</span></code></a>, <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>, <a class="reference internal" href="../library/functions.html#filter" title="filter"><code class="xref py py-func docutils literal notranslate"><span class="pre">filter()</span></code></a>, and <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> now
run several times faster with non-sequence arguments that supply a
<a class="reference internal" href="../reference/datamodel.html#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> method.  (Contributed by Raymond Hettinger.)</li>
<li>The methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.__getitem__()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.__getitem__()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">dict.__contains__()</span></code> are now implemented as <code class="xref py py-class docutils literal notranslate"><span class="pre">method_descriptor</span></code>
objects rather than <code class="xref py py-class docutils literal notranslate"><span class="pre">wrapper_descriptor</span></code> objects.  This form of  access
doubles their performance and makes them more suitable for use as arguments to
functionals: <code class="docutils literal notranslate"><span class="pre">map(mydict.__getitem__,</span> <span class="pre">keylist)</span></code>. (Contributed by Raymond
Hettinger.)</li>
<li>Added a new opcode, <code class="docutils literal notranslate"><span class="pre">LIST_APPEND</span></code>, that simplifies the generated bytecode
for list comprehensions and speeds them up by about a third.  (Contributed by
Raymond Hettinger.)</li>
<li>The peephole bytecode optimizer has been improved to  produce shorter, faster
bytecode; remarkably, the resulting bytecode is  more readable.  (Enhanced by
Raymond Hettinger.)</li>
<li>String concatenations in statements of the form <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">=</span> <span class="pre">s</span> <span class="pre">+</span> <span class="pre">&quot;abc&quot;</span></code> and <code class="docutils literal notranslate"><span class="pre">s</span> <span class="pre">+=</span>
<span class="pre">&quot;abc&quot;</span></code> are now performed more efficiently in certain circumstances.  This
optimization won’t be present in other Python implementations such as Jython, so
you shouldn’t rely on it; using the <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method of strings is still
recommended when you want to efficiently glue a large number of strings
together. (Contributed by Armin Rigo.)</li>
</ul>
<p>The net result of the 2.4 optimizations is that Python 2.4 runs the pystone
benchmark around 5% faster than Python 2.3 and 35% faster than Python 2.2.
(pystone is not a particularly good benchmark, but it’s the most commonly used
measurement of Python’s performance.  Your own applications may show greater or
smaller benefits from Python 2.4.)</p>
</div>
</div>
<div class="section" id="new-improved-and-deprecated-modules">
<h2>New, Improved, and Deprecated Modules<a class="headerlink" href="#new-improved-and-deprecated-modules" title="Permalink to this headline">¶</a></h2>
<p>As usual, Python’s standard library received a number of enhancements and bug
fixes.  Here’s a partial list of the most notable changes, sorted alphabetically
by module name. Consult the <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more
complete list of changes, or look through the CVS logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> module’s <code class="xref py py-func docutils literal notranslate"><span class="pre">loop()</span></code> function now has a <em>count</em> parameter
that lets you perform a limited number of passes through the polling loop.  The
default is still to loop forever.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/base64.html#module-base64" title="base64: RFC 3548: Base16, Base32, Base64 Data Encodings"><code class="xref py py-mod docutils literal notranslate"><span class="pre">base64</span></code></a> module now has more complete RFC 3548 support for Base64,
Base32, and Base16 encoding and decoding, including optional case folding and
optional alternative alphabets. (Contributed by Barry Warsaw.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> module now has an underlying C implementation for improved
performance. (Contributed by Dmitry Vasiliev.)</p>
</li>
<li><p class="first">The CJKCodecs collections of East Asian codecs, maintained by Hye-Shik Chang,
was integrated into 2.4.   The new encodings are:</p>
</li>
<li><p class="first">Chinese (PRC): gb2312, gbk, gb18030, big5hkscs, hz</p>
</li>
<li><p class="first">Chinese (ROC): big5, cp950</p>
</li>
<li><dl class="first docutils">
<dt>Japanese: cp932, euc-jis-2004, euc-jp, euc-jisx0213, iso-2022-jp,</dt>
<dd><p class="first last">iso-2022-jp-1, iso-2022-jp-2, iso-2022-jp-3, iso-2022-jp-ext, iso-2022-jp-2004,
shift-jis, shift-jisx0213, shift-jis-2004</p>
</dd>
</dl>
</li>
<li><p class="first">Korean: cp949, euc-kr, johab, iso-2022-kr</p>
</li>
<li><p class="first">Some other new encodings were added: HP Roman8,  ISO_8859-11, ISO_8859-16,
PCTP-154, and TIS-620.</p>
</li>
<li><p class="first">The UTF-8 and UTF-16 codecs now cope better with receiving partial input.
Previously the <code class="xref py py-class docutils literal notranslate"><span class="pre">StreamReader</span></code> class would try to read more data, making
it impossible to resume decoding from the stream.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> method will
now return as much data as it can and future calls will resume decoding where
previous ones left off.  (Implemented by Walter Dörwald.)</p>
</li>
<li><p class="first">There is a new <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module for  various specialized collection
datatypes.  Currently it contains just one type, <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code>, a double-ended
queue that supports efficiently adding and removing elements from either
end:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">(</span><span class="s1">&#39;ghi&#39;</span><span class="p">)</span>        <span class="c1"># make a new deque with three items</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;j&#39;</span><span class="p">)</span>           <span class="c1"># add a new entry to the right side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">appendleft</span><span class="p">(</span><span class="s1">&#39;f&#39;</span><span class="p">)</span>       <span class="c1"># add a new entry to the left side</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>                       <span class="c1"># show the representation of the deque</span>
<span class="go">deque([&#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">pop</span><span class="p">()</span>                 <span class="c1"># return and remove the rightmost item</span>
<span class="go">&#39;j&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>             <span class="c1"># return and remove the leftmost item</span>
<span class="go">&#39;f&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>                 <span class="c1"># list the contents of the deque</span>
<span class="go">[&#39;g&#39;, &#39;h&#39;, &#39;i&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;h&#39;</span> <span class="ow">in</span> <span class="n">d</span>                <span class="c1"># search the deque</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Several modules, such as the <a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> and <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> modules, now take
advantage of <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a> for improved performance.  (Contributed
by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> classes have been enhanced slightly. The <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>
method now returns a list of the files that were successfully parsed, and the
<a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-meth docutils literal notranslate"><span class="pre">set()</span></code></a> method raises <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if passed a <em>value</em> argument that
isn’t a string.   (Contributed by John Belmonte and David Goodger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module now supports the ncurses extension
<code class="xref py py-func docutils literal notranslate"><span class="pre">use_default_colors()</span></code>.  On platforms where the terminal supports
transparency, this makes it possible to use a transparent background.
(Contributed by Jörg Lehmann.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module now includes an <code class="xref py py-class docutils literal notranslate"><span class="pre">HtmlDiff</span></code> class that creates
an HTML table showing a side by side comparison of two versions of a text.
(Contributed by Dan Gass.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package was updated to version 3.0,  which dropped various
deprecated APIs and removes support for Python versions earlier than 2.3.  The
3.0 version of the package uses a new incremental parser for MIME messages,
available in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">email.FeedParser</span></code> module.  The new parser doesn’t require
reading the entire message into memory, and doesn’t raise exceptions if a
message is malformed; instead it records any problems in the  <code class="xref py py-attr docutils literal notranslate"><span class="pre">defect</span></code>
attribute of the message.  (Developed by Anthony Baxter, Barry Warsaw, Thomas
Wouters, and others.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module has been converted to C.  The resulting tenfold
improvement in speed makes the module suitable for handling high volumes of
data.  In addition, the module has two new functions <code class="xref py py-func docutils literal notranslate"><span class="pre">nlargest()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">nsmallest()</span></code> that use heaps to find the N largest or smallest values in a
dataset without the expense of a full sort.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> module now contains constants for HTTP status codes defined
in various HTTP-related RFC documents.  Constants have names such as
<code class="xref py py-const docutils literal notranslate"><span class="pre">OK</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">CREATED</span></code>, <code class="xref py py-const docutils literal notranslate"><span class="pre">CONTINUE</span></code>, and
<code class="xref py py-const docutils literal notranslate"><span class="pre">MOVED_PERMANENTLY</span></code>; use pydoc to get a full list.  (Contributed by
Andrew Eland.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module now supports IMAP’s THREAD command (contributed by
Yves Dionne) and new <code class="xref py py-meth docutils literal notranslate"><span class="pre">deleteacl()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">myrights()</span></code> methods (contributed
by Arnaud Mazin).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module gained a <code class="docutils literal notranslate"><span class="pre">groupby(iterable[,</span> <span class="pre">*func*])</span></code>
function. <em>iterable</em> is something that can be iterated over to return a stream
of elements, and the optional <em>func</em> parameter is a function that takes an
element and returns a key value; if omitted, the key is simply the element
itself.  <code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code> then groups the elements into subsequences which have
matching values of the key, and returns a series of 2-tuples containing the key
value and an iterator over the subsequence.</p>
<p>Here’s an example to make this clearer.  The <em>key</em> function simply returns
whether a number is even or odd, so the result of <code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code> is to return
consecutive runs of odd or even numbers.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">itertools</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">11</span><span class="p">,</span> <span class="mi">12</span><span class="p">,</span> <span class="mi">14</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">key_val</span><span class="p">,</span> <span class="n">it</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span> <span class="o">%</span> <span class="mi">2</span><span class="p">):</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">key_val</span><span class="p">,</span> <span class="nb">list</span><span class="p">(</span><span class="n">it</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">0 [2, 4, 6]</span>
<span class="go">1 [7]</span>
<span class="go">0 [8]</span>
<span class="go">1 [9, 11]</span>
<span class="go">0 [12, 14]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code> is typically used with sorted input.  The logic for
<code class="xref py py-func docutils literal notranslate"><span class="pre">groupby()</span></code> is similar to the Unix <code class="docutils literal notranslate"><span class="pre">uniq</span></code> filter which makes it handy for
eliminating, counting, or identifying duplicate elements:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">word</span> <span class="o">=</span> <span class="s1">&#39;abracadabra&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span> <span class="o">=</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">word</span><span class="p">)</span>   <span class="c1"># Turn string into a sorted list of letters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">letters</span>
<span class="go">[&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;b&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;r&#39;, &#39;r&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">itertools</span><span class="o">.</span><span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">):</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="nb">list</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>
<span class="gp">...</span>
<span class="go">a [&#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;, &#39;a&#39;]</span>
<span class="go">b [&#39;b&#39;, &#39;b&#39;]</span>
<span class="go">c [&#39;c&#39;]</span>
<span class="go">d [&#39;d&#39;]</span>
<span class="go">r [&#39;r&#39;, &#39;r&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># List unique letters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[</span><span class="n">k</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">)]</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;r&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Count letter occurrences</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">[(</span><span class="n">k</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">g</span><span class="p">)))</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">g</span> <span class="ow">in</span> <span class="n">groupby</span><span class="p">(</span><span class="n">letters</span><span class="p">)]</span>
<span class="go">[(&#39;a&#39;, 5), (&#39;b&#39;, 2), (&#39;c&#39;, 1), (&#39;d&#39;, 1), (&#39;r&#39;, 2)]</span>
</pre></div>
</div>
<p>(Contributed by Hye-Shik Chang.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> also gained a function named <code class="docutils literal notranslate"><span class="pre">tee(iterator,</span> <span class="pre">N)</span></code> that
returns <em>N</em> independent iterators that replicate <em>iterator</em>.  If <em>N</em> is omitted,
the default is 2.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i1</span><span class="p">,</span> <span class="n">i2</span> <span class="o">=</span> <span class="n">itertools</span><span class="o">.</span><span class="n">tee</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">i1</span><span class="p">,</span><span class="n">i2</span>
<span class="go">(&lt;itertools.tee object at 0x402c2080&gt;, &lt;itertools.tee object at 0x402c2090&gt;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">i1</span><span class="p">)</span>               <span class="c1"># Run the first iterator to exhaustion</span>
<span class="go">[1, 2, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">i2</span><span class="p">)</span>               <span class="c1"># Run the second iterator to exhaustion</span>
<span class="go">[1, 2, 3]</span>
</pre></div>
</div>
<p>Note that <code class="xref py py-func docutils literal notranslate"><span class="pre">tee()</span></code> has to keep copies of the values returned  by the
iterator; in the worst case, it may need to keep all of them.   This should
therefore be used carefully if the leading iterator can run far ahead of the
trailing iterator in a long stream of inputs. If the separation is large, then
you might as well use  <code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code> instead.  When the iterators track closely
with one another, <code class="xref py py-func docutils literal notranslate"><span class="pre">tee()</span></code> is ideal.  Possible applications include
bookmarking, windowing, or lookahead iterators. (Contributed by Raymond
Hettinger.)</p>
</li>
<li><p class="first">A number of functions were added to the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a>  module, such as
<code class="xref py py-func docutils literal notranslate"><span class="pre">bind_textdomain_codeset()</span></code> to specify a particular encoding and a family of
<code class="xref py py-func docutils literal notranslate"><span class="pre">l*gettext()</span></code> functions that return messages in the chosen encoding.
(Contributed by Gustavo Niemeyer.)</p>
</li>
<li><p class="first">Some keyword arguments were added to the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package’s
<code class="xref py py-func docutils literal notranslate"><span class="pre">basicConfig()</span></code> function to simplify log configuration.  The default
behavior is to log messages to standard error, but various keyword arguments can
be specified to log to a particular file, change the logging format, or set the
logging level. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="n">logging</span><span class="o">.</span><span class="n">basicConfig</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s1">&#39;/var/log/application.log&#39;</span><span class="p">,</span>
    <span class="n">level</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>  <span class="c1"># Log all messages</span>
    <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;%(levelname):%(process):%(thread):%(message)&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Other additions to the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> package include a <code class="docutils literal notranslate"><span class="pre">log(level,</span> <span class="pre">msg)</span></code>
convenience method, as well as a <code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> class that
rotates its log files at a timed interval.  The module already had
<code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code>, which rotated logs once the file exceeded a
certain size.  Both classes derive from a new <code class="xref py py-class docutils literal notranslate"><span class="pre">BaseRotatingHandler</span></code> class
that can be used to implement other rotating handlers.</p>
<p>(Changes implemented by Vinay Sajip.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a> module now shares interned strings on unpacking a  data
structure.  This may shrink the size of certain pickle strings, but the primary
effect is to make <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> files significantly smaller. (Contributed by
Martin von Löwis.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">NNTP</span></code> class gained <code class="xref py py-meth docutils literal notranslate"><span class="pre">description()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">descriptions()</span></code> methods to retrieve  newsgroup descriptions for a single
group or for a range of groups. (Contributed by Jürgen A. Erhard.)</p>
</li>
<li><p class="first">Two new functions were added to the <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module,
<code class="docutils literal notranslate"><span class="pre">attrgetter(attr)</span></code> and <code class="docutils literal notranslate"><span class="pre">itemgetter(index)</span></code>. Both functions return
callables that take a single argument and return the corresponding attribute or
item; these callables make excellent data extractors when used with <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-func docutils literal notranslate"><span class="pre">map()</span></code></a>
or <a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">0</span><span class="p">),</span> <span class="n">L</span><span class="p">)</span>
<span class="go">[&#39;c&#39;, &#39;d&#39;, &#39;a&#39;, &#39;b&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">map</span><span class="p">(</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">L</span><span class="p">)</span>
<span class="go">[2, 1, 4, 3]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">sorted</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">operator</span><span class="o">.</span><span class="n">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="c1"># Sort list by second tuple item</span>
<span class="go">[(&#39;d&#39;, 1), (&#39;c&#39;, 2), (&#39;b&#39;, 3), (&#39;a&#39;, 4)]</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module was updated in various ways.  The module now passes
its messages through <a class="reference internal" href="../library/gettext.html#gettext.gettext" title="gettext.gettext"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettext.gettext()</span></code></a>, making it possible to
internationalize Optik’s help and error messages.  Help messages for options can
now include the string <code class="docutils literal notranslate"><span class="pre">'%default'</span></code>, which will be replaced by the option’s
default value.  (Contributed by Greg Ward.)</p>
</li>
<li><p class="first">The long-term plan is to deprecate the <a class="reference internal" href="../library/rfc822.html#module-rfc822" title="rfc822: Parse 2822 style mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">rfc822</span></code></a> module in some future
Python release in favor of the <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package. To this end, the
<code class="xref py py-func docutils literal notranslate"><span class="pre">email.Utils.formatdate()</span></code> function has been changed to make it usable as a
replacement for <code class="xref py py-func docutils literal notranslate"><span class="pre">rfc822.formatdate()</span></code>.  You may want to write new e-mail
processing code with this in mind.  (Change implemented by Anthony Baxter.)</p>
</li>
<li><p class="first">A new <code class="docutils literal notranslate"><span class="pre">urandom(n)</span></code> function was added to the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module, returning
a string containing <em>n</em> bytes of random data.  This function provides access to
platform-specific sources of randomness such as <code class="file docutils literal notranslate"><span class="pre">/dev/urandom</span></code> on Linux or
the Windows CryptoAPI.  (Contributed by Trevor Perrin.)</p>
</li>
<li><p class="first">Another new function: <code class="docutils literal notranslate"><span class="pre">os.path.lexists(path)</span></code>  returns true if the file
specified by <em>path</em> exists, whether or not it’s a symbolic link.  This differs
from the existing <code class="docutils literal notranslate"><span class="pre">os.path.exists(path)</span></code> function, which returns false if
<em>path</em> is a symlink that points to a destination that doesn’t exist.
(Contributed by Beni Cherniavsky.)</p>
</li>
<li><p class="first">A new <code class="xref py py-func docutils literal notranslate"><span class="pre">getsid()</span></code> function was added to the <a class="reference internal" href="../library/posix.html#module-posix" title="posix: The most common POSIX system calls (normally used via module os). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posix</span></code></a> module that
underlies the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module. (Contributed by J. Raynor.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/poplib.html#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> module now supports POP over SSL.  (Contributed by Hector
Urtubia.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module can now profile C extension functions. (Contributed
by Nick Bastin.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module has a new method called <code class="docutils literal notranslate"><span class="pre">getrandbits(N)</span></code> that
returns a long integer <em>N</em> bits in length.  The existing <code class="xref py py-meth docutils literal notranslate"><span class="pre">randrange()</span></code>
method now uses <code class="xref py py-meth docutils literal notranslate"><span class="pre">getrandbits()</span></code> where appropriate, making generation of
arbitrarily large random numbers more efficient.  (Contributed by Raymond
Hettinger.)</p>
</li>
<li><p class="first">The regular expression language accepted by the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module was extended
with simple conditional expressions, written as <code class="docutils literal notranslate"><span class="pre">(?(group)A|B)</span></code>.  <em>group</em> is
either a numeric group ID or a group name defined with <code class="docutils literal notranslate"><span class="pre">(?P&lt;group&gt;...)</span></code>
earlier in the expression.  If the specified group matched, the regular
expression pattern <em>A</em> will be tested against the string; if the group didn’t
match, the pattern <em>B</em> will be used instead. (Contributed by Gustavo Niemeyer.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module is also no longer recursive, thanks to a massive amount
of work by Gustavo Niemeyer.  In a recursive regular expression engine, certain
patterns result in a large amount of C stack space being consumed, and it was
possible to overflow the stack. For example, if you matched a 30000-byte string
of <code class="docutils literal notranslate"><span class="pre">a</span></code> characters against the expression <code class="docutils literal notranslate"><span class="pre">(a|b)+</span></code>, one stack frame was
consumed per character.  Python 2.3 tried to check for stack overflow and raise
a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> exception, but certain patterns could sidestep the
checking and if you were unlucky Python could segfault. Python 2.4’s regular
expression engine can match this pattern without problems.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module now performs tighter error-checking on the parameters
to the <a class="reference internal" href="../library/signal.html#signal.signal" title="signal.signal"><code class="xref py py-func docutils literal notranslate"><span class="pre">signal.signal()</span></code></a> function.  For example, you can’t set a handler on
the <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGKILL</span></code> signal; previous versions of Python would quietly accept
this, but 2.4 will raise a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> exception.</p>
</li>
<li><p class="first">Two new functions were added to the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module. <code class="xref py py-func docutils literal notranslate"><span class="pre">socketpair()</span></code>
returns a pair of connected sockets and <code class="docutils literal notranslate"><span class="pre">getservbyport(port)</span></code> looks up the
service name for a given port number. (Contributed by Dave Cole and Barry
Warsaw.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/sys.html#sys.exitfunc" title="sys.exitfunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exitfunc()</span></code></a> function has been deprecated.  Code should be using
the existing <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a> module, which correctly handles calling multiple exit
functions.  Eventually <a class="reference internal" href="../library/sys.html#sys.exitfunc" title="sys.exitfunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exitfunc()</span></code></a> will become a purely internal
interface, accessed only by <a class="reference internal" href="../library/atexit.html#module-atexit" title="atexit: Register and execute cleanup functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">atexit</span></code></a>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module now generates GNU-format tar files by default.
(Contributed by Lars Gustaebel.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module now has an elegantly simple way to support
thread-local data.  The module contains a <code class="xref py py-class docutils literal notranslate"><span class="pre">local</span></code> class whose attribute
values are local to different threads.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">threading</span>

<span class="n">data</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">local</span><span class="p">()</span>
<span class="n">data</span><span class="o">.</span><span class="n">number</span> <span class="o">=</span> <span class="mi">42</span>
<span class="n">data</span><span class="o">.</span><span class="n">url</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;www.python.org&#39;</span><span class="p">,</span> <span class="mi">80</span><span class="p">)</span>
</pre></div>
</div>
<p>Other threads can assign and retrieve their own values for the <code class="xref py py-attr docutils literal notranslate"><span class="pre">number</span></code>
and <code class="xref py py-attr docutils literal notranslate"><span class="pre">url</span></code> attributes.  You can subclass <code class="xref py py-class docutils literal notranslate"><span class="pre">local</span></code> to initialize
attributes or to add methods. (Contributed by Jim Fulton.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module now automatically disables periodic garbage
collection during the timing loop.  This change makes consecutive timings more
comparable.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module now supports a wider variety of objects including
Python functions, class instances, sets, frozensets, deques, arrays, files,
sockets, and regular expression pattern objects. (Contributed by Raymond
Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module now supports a multi-call extension for
transmitting multiple XML-RPC calls in a single HTTP operation. (Contributed by
Brian Quinlan.)</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">mpz</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">rotor</span></code>, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">xreadlines</span></code> modules have  been
removed.</p>
</li>
</ul>
<div class="section" id="cookielib">
<h3>cookielib<a class="headerlink" href="#cookielib" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> library supports client-side handling for HTTP cookies,
mirroring the <a class="reference internal" href="../library/cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module’s server-side cookie support. Cookies are
stored in cookie jars; the library transparently stores cookies offered by the
web server in the cookie jar, and fetches the cookie from the jar when
connecting to the server. As in web browsers, policy objects control whether
cookies are accepted or not.</p>
<p>In order to store cookies across sessions, two implementations of cookie jars
are provided: one that stores cookies in the Netscape format so applications can
use the Mozilla or Lynx cookie files, and one that stores cookies in the same
format as the Perl libwww library.</p>
<p><a class="reference internal" href="../library/urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> has been changed to interact with <a class="reference internal" href="../library/cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a>:
<code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPCookieProcessor</span></code> manages a cookie jar that is used when accessing
URLs.</p>
<p>This module was contributed by John J. Lee.</p>
</div>
<div class="section" id="doctest">
<h3>doctest<a class="headerlink" href="#doctest" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module underwent considerable refactoring thanks to Edward
Loper and Tim Peters.  Testing can still be as simple as running
<a class="reference internal" href="../library/doctest.html#doctest.testmod" title="doctest.testmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">doctest.testmod()</span></code></a>, but the refactorings allow customizing the module’s
operation in various ways</p>
<p>The new <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestFinder</span></code> class extracts the tests from a given  object’s
docstrings:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">f</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;&gt;&gt;&gt; f(2,2)</span>
<span class="sd">4</span>
<span class="sd">&gt;&gt;&gt; f(3,2)</span>
<span class="sd">6</span>
<span class="sd">    &quot;&quot;&quot;</span>
    <span class="k">return</span> <span class="n">x</span><span class="o">*</span><span class="n">y</span>

<span class="n">finder</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestFinder</span><span class="p">()</span>

<span class="c1"># Get list of DocTest instances</span>
<span class="n">tests</span> <span class="o">=</span> <span class="n">finder</span><span class="o">.</span><span class="n">find</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
</pre></div>
</div>
<p>The new <code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code> class then runs individual tests and can produce
a summary of the results:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">runner</span> <span class="o">=</span> <span class="n">doctest</span><span class="o">.</span><span class="n">DocTestRunner</span><span class="p">()</span>
<span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="n">tests</span><span class="p">:</span>
    <span class="n">tried</span><span class="p">,</span> <span class="n">failed</span> <span class="o">=</span> <span class="n">runner</span><span class="o">.</span><span class="n">run</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>

<span class="n">runner</span><span class="o">.</span><span class="n">summarize</span><span class="p">(</span><span class="n">verbose</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
</pre></div>
</div>
<p>The above example produces the following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="n">items</span> <span class="n">passed</span> <span class="nb">all</span> <span class="n">tests</span><span class="p">:</span>
   <span class="mi">2</span> <span class="n">tests</span> <span class="ow">in</span> <span class="n">f</span>
<span class="mi">2</span> <span class="n">tests</span> <span class="ow">in</span> <span class="mi">1</span> <span class="n">items</span><span class="o">.</span>
<span class="mi">2</span> <span class="n">passed</span> <span class="ow">and</span> <span class="mi">0</span> <span class="n">failed</span><span class="o">.</span>
<span class="n">Test</span> <span class="n">passed</span><span class="o">.</span>
</pre></div>
</div>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">DocTestRunner</span></code> uses an instance of the <code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code> class to
compare the expected output with the actual output.  This class takes a number
of different flags that customize its behaviour; ambitious users can also write
a completely new subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">OutputChecker</span></code>.</p>
<p>The default output checker provides a number of handy features. For example,
with the <a class="reference internal" href="../library/doctest.html#doctest.ELLIPSIS" title="doctest.ELLIPSIS"><code class="xref py py-const docutils literal notranslate"><span class="pre">doctest.ELLIPSIS</span></code></a> option flag, an ellipsis (<code class="docutils literal notranslate"><span class="pre">...</span></code>) in the
expected output matches any substring,  making it easier to accommodate outputs
that vary in minor ways:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">o</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;&gt;&gt;&gt; o(1)</span>
<span class="sd">&lt;__main__.C instance at 0x...&gt;</span>
<span class="sd">&gt;&gt;&gt;</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>Another special string, <code class="docutils literal notranslate"><span class="pre">&lt;BLANKLINE&gt;</span></code>, matches a blank line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">p</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;&gt;&gt;&gt; p(1)</span>
<span class="sd">&lt;BLANKLINE&gt;</span>
<span class="sd">&gt;&gt;&gt;</span>
<span class="sd">&quot;&quot;&quot;</span>
</pre></div>
</div>
<p>Another new capability is producing a diff-style display of the output by
specifying the <a class="reference internal" href="../library/doctest.html#doctest.REPORT_UDIFF" title="doctest.REPORT_UDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">doctest.REPORT_UDIFF</span></code></a> (unified diffs),
<a class="reference internal" href="../library/doctest.html#doctest.REPORT_CDIFF" title="doctest.REPORT_CDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">doctest.REPORT_CDIFF</span></code></a> (context diffs), or <a class="reference internal" href="../library/doctest.html#doctest.REPORT_NDIFF" title="doctest.REPORT_NDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">doctest.REPORT_NDIFF</span></code></a>
(delta-style) option flags.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">g</span> <span class="p">(</span><span class="n">n</span><span class="p">):</span>
    <span class="sd">&quot;&quot;&quot;&gt;&gt;&gt; g(4)</span>
<span class="sd">here</span>
<span class="sd">is</span>
<span class="sd">a</span>
<span class="sd">lengthy</span>
<span class="sd">&gt;&gt;&gt;&quot;&quot;&quot;</span>
    <span class="n">L</span> <span class="o">=</span> <span class="s1">&#39;here is a rather lengthy list of words&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
    <span class="k">for</span> <span class="n">word</span> <span class="ow">in</span> <span class="n">L</span><span class="p">[:</span><span class="n">n</span><span class="p">]:</span>
        <span class="nb">print</span> <span class="n">word</span>
</pre></div>
</div>
<p>Running the above function’s tests with <a class="reference internal" href="../library/doctest.html#doctest.REPORT_UDIFF" title="doctest.REPORT_UDIFF"><code class="xref py py-const docutils literal notranslate"><span class="pre">doctest.REPORT_UDIFF</span></code></a> specified,
you get the following output:</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>**********************************************************************
File &quot;t.py&quot;, line 15, in g
Failed example:
    g(4)
Differences (unified diff with -expected +actual):
    @@ -2,3 +2,3 @@
     is
     a
    -lengthy
    +rather
**********************************************************************
</pre></div>
</div>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
<p>Some of the changes to Python’s build process and to the C API are:</p>
<ul class="simple">
<li>Three new convenience macros were added for common return values from
extension functions: <a class="reference internal" href="../c-api/none.html#c.Py_RETURN_NONE" title="Py_RETURN_NONE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_NONE</span></code></a>, <a class="reference internal" href="../c-api/bool.html#c.Py_RETURN_TRUE" title="Py_RETURN_TRUE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_TRUE</span></code></a>, and
<a class="reference internal" href="../c-api/bool.html#c.Py_RETURN_FALSE" title="Py_RETURN_FALSE"><code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_RETURN_FALSE</span></code></a>. (Contributed by Brett Cannon.)</li>
<li>Another new macro, <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_CLEAR(obj)</span></code>,  decreases the reference count of
<em>obj</em> and sets <em>obj</em> to the null pointer.  (Contributed by Jim Fulton.)</li>
<li>A new function, <code class="docutils literal notranslate"><span class="pre">PyTuple_Pack(N,</span> <span class="pre">obj1,</span> <span class="pre">obj2,</span> <span class="pre">...,</span> <span class="pre">objN)</span></code>, constructs
tuples from a variable length argument list of Python objects.  (Contributed by
Raymond Hettinger.)</li>
<li>A new function, <code class="docutils literal notranslate"><span class="pre">PyDict_Contains(d,</span> <span class="pre">k)</span></code>, implements fast dictionary
lookups without masking exceptions raised during the look-up process.
(Contributed by Raymond Hettinger.)</li>
<li>The <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_IS_NAN(X)</span></code> macro returns 1 if  its float or double argument
<em>X</em> is a NaN.   (Contributed by Tim Peters.)</li>
<li>C code can avoid unnecessary locking by using the new
<a class="reference internal" href="../c-api/init.html#c.PyEval_ThreadsInitialized" title="PyEval_ThreadsInitialized"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyEval_ThreadsInitialized()</span></code></a> function to tell  if any thread operations
have been performed.  If this function  returns false, no lock operations are
needed. (Contributed by Nick Coghlan.)</li>
<li>A new function, <a class="reference internal" href="../c-api/arg.html#c.PyArg_VaParseTupleAndKeywords" title="PyArg_VaParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_VaParseTupleAndKeywords()</span></code></a>, is the same as
<a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTupleAndKeywords()</span></code></a> but takes a  <code class="xref c c-type docutils literal notranslate"><span class="pre">va_list</span></code> instead of a
number of arguments. (Contributed by Greg Chapman.)</li>
<li>A new method flag, <code class="xref py py-const docutils literal notranslate"><span class="pre">METH_COEXISTS</span></code>, allows a function defined in slots
to co-exist with a <a class="reference internal" href="../c-api/structures.html#c.PyCFunction" title="PyCFunction"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCFunction</span></code></a> having the same name.  This can halve
the access time for a method such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">set.__contains__()</span></code>.  (Contributed by
Raymond Hettinger.)</li>
<li>Python can now be built with additional profiling for the interpreter itself,
intended as an aid to people developing the Python core.  Providing
<code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-profiling</span></code> to the <strong class="program">configure</strong> script will let you
profile the interpreter with <strong class="program">gprof</strong>, and providing the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-tsc</span></code> switch enables profiling using the Pentium’s
Time-Stamp-Counter register.  Note that the <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-tsc</span></code> switch is slightly
misnamed, because the profiling feature also works on the PowerPC platform,
though that processor architecture doesn’t call that register “the TSC
register”.  (Contributed by Jeremy Hylton.)</li>
<li>The <code class="xref c c-type docutils literal notranslate"><span class="pre">tracebackobject</span></code> type has been renamed to
<code class="xref c c-type docutils literal notranslate"><span class="pre">PyTracebackObject</span></code>.</li>
</ul>
<div class="section" id="port-specific-changes">
<h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The Windows port now builds under MSVC++ 7.1 as well as version 6.
(Contributed by Martin von Löwis.)</li>
</ul>
</div>
</div>
<div class="section" id="porting-to-python-2-4">
<h2>Porting to Python 2.4<a class="headerlink" href="#porting-to-python-2-4" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes that may require changes to your
code:</p>
<ul class="simple">
<li>Left shifts and hexadecimal/octal constants that are too  large no longer
trigger a <a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a> and return  a value limited to 32 or 64 bits;
instead they return a long integer.</li>
<li>Integer operations will no longer trigger an <code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowWarning</span></code>. The
<code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowWarning</span></code> warning will disappear in Python 2.5.</li>
<li>The <a class="reference internal" href="../library/functions.html#zip" title="zip"><code class="xref py py-func docutils literal notranslate"><span class="pre">zip()</span></code></a> built-in function and <a class="reference internal" href="../library/itertools.html#itertools.izip" title="itertools.izip"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.izip()</span></code></a> now return  an
empty list instead of raising a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception if called with no
arguments.</li>
<li>You can no longer compare the <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instances
provided by the <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module.  Two  instances of different classes
will now always be unequal, and  relative comparisons (<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>) will raise
a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</li>
<li><a class="reference internal" href="../library/dircache.html#dircache.listdir" title="dircache.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dircache.listdir()</span></code></a> now passes exceptions to the caller instead of
returning empty lists.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">LexicalHandler.startDTD()</span></code> used to receive the public and system IDs in
the wrong order.  This has been corrected; applications relying on the wrong
order need to be fixed.</li>
<li><a class="reference internal" href="../library/fcntl.html#fcntl.ioctl" title="fcntl.ioctl"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.ioctl()</span></code></a> now warns if the <em>mutate</em>  argument is omitted and
relevant.</li>
<li>The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module now generates GNU-format tar files by default.</li>
<li>Encountering a failure while importing a module no longer leaves a
partially-initialized module object in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>.</li>
<li><a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a> is now a constant; code that binds a new value to  the name
<code class="docutils literal notranslate"><span class="pre">None</span></code> is now a syntax error.</li>
<li>The <code class="xref py py-func docutils literal notranslate"><span class="pre">signals.signal()</span></code> function now raises a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> exception
for certain illegal values; previously these errors would pass silently.  For
example, you can no longer set a handler on the <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGKILL</span></code> signal.</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<span id="acks"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Koray Can,
Hye-Shik Chang, Michael Dyck, Raymond Hettinger, Brian Hurt, Hamish Lawson,
Fredrik Lundh, Sean Reifschneider, Sadruddin Rejeb.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.4</a><ul>
<li><a class="reference internal" href="#pep-218-built-in-set-objects">PEP 218: Built-In Set Objects</a></li>
<li><a class="reference internal" href="#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li><a class="reference internal" href="#pep-289-generator-expressions">PEP 289: Generator Expressions</a></li>
<li><a class="reference internal" href="#pep-292-simpler-string-substitutions">PEP 292: Simpler String Substitutions</a></li>
<li><a class="reference internal" href="#pep-318-decorators-for-functions-and-methods">PEP 318: Decorators for Functions and Methods</a></li>
<li><a class="reference internal" href="#pep-322-reverse-iteration">PEP 322: Reverse Iteration</a></li>
<li><a class="reference internal" href="#pep-324-new-subprocess-module">PEP 324: New subprocess Module</a></li>
<li><a class="reference internal" href="#pep-327-decimal-data-type">PEP 327: Decimal Data Type</a><ul>
<li><a class="reference internal" href="#why-is-decimal-needed">Why is Decimal needed?</a></li>
<li><a class="reference internal" href="#the-decimal-type">The <code class="docutils literal notranslate"><span class="pre">Decimal</span></code> type</a></li>
<li><a class="reference internal" href="#the-context-type">The <code class="docutils literal notranslate"><span class="pre">Context</span></code> type</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-328-multi-line-imports">PEP 328: Multi-line Imports</a></li>
<li><a class="reference internal" href="#pep-331-locale-independent-float-string-conversions">PEP 331: Locale-Independent Float/String Conversions</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
<li><a class="reference internal" href="#cookielib">cookielib</a></li>
<li><a class="reference internal" href="#doctest">doctest</a></li>
</ul>
</li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-4">Porting to Python 2.4</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.5.html"
                        title="previous chapter">What’s New in Python 2.5</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.3.html"
                        title="next chapter">What’s New in Python 2.3</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.4.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.3.html" title="What’s New in Python 2.3"
             >next</a> |</li>
        <li class="right" >
          <a href="2.5.html" title="What’s New in Python 2.5"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\ŎŤ���html/whatsnew/2.5.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.5 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.4" href="2.4.html" />
    <link rel="prev" title="What’s New in Python 2.6" href="2.6.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.5.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-5">
<h1>What’s New in Python 2.5<a class="headerlink" href="#what-s-new-in-python-2-5" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.5.  The final release of
Python 2.5 is scheduled for August 2006; <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0356"><strong>PEP 356</strong></a> describes the planned
release schedule.</p>
<p>The changes in Python 2.5 are an interesting mix of language and library
improvements. The library enhancements will be more important to Python’s user
community, I think, because several widely-useful packages were added.  New
modules include ElementTree for XML processing (<code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>),
the SQLite database module (<code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite</span></code>), and the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a>
module for calling C functions.</p>
<p>The language changes are of middling significance.  Some pleasant new features
were added, but most of them aren’t features that you’ll use every day.
Conditional expressions were finally added to the language using a novel syntax;
see section <a class="reference internal" href="#pep-308"><span class="std std-ref">PEP 308: Conditional Expressions</span></a>.  The new ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will make
writing cleanup code easier (section <a class="reference internal" href="#pep-343"><span class="std std-ref">PEP 343: The ‘with’ statement</span></a>).  Values can now be passed
into generators (section <a class="reference internal" href="#pep-342"><span class="std std-ref">PEP 342: New Generator Features</span></a>).  Imports are now visible as either
absolute or relative (section <a class="reference internal" href="#pep-328"><span class="std std-ref">PEP 328: Absolute and Relative Imports</span></a>).  Some corner cases of exception
handling are handled better (section <a class="reference internal" href="#pep-341"><span class="std std-ref">PEP 341: Unified try/except/finally</span></a>).  All these improvements
are worthwhile, but they’re improvements to one specific language feature or
another; none of them are broad modifications to Python’s semantics.</p>
<p>As well as the language and library additions, other improvements and bugfixes
were made throughout the source tree.  A search through the SVN change logs
finds there were 353 patches applied and 458 bugs fixed between Python 2.4 and
2.5.  (Both figures are likely to be underestimates.)</p>
<p>This article doesn’t try to be a complete specification of the new features;
instead changes are briefly introduced using helpful examples.  For full
details, you should always refer to the documentation for Python 2.5 at
<a class="reference external" href="https://docs.python.org">https://docs.python.org</a>. If you want to understand the complete implementation
and design rationale, refer to the PEP for a particular new feature.</p>
<p>Comments, suggestions, and error reports for this document are welcome; please
e-mail them to the author or open a bug in the Python bug tracker.</p>
<div class="section" id="pep-308-conditional-expressions">
<span id="pep-308"></span><h2>PEP 308: Conditional Expressions<a class="headerlink" href="#pep-308-conditional-expressions" title="Permalink to this headline">¶</a></h2>
<p>For a long time, people have been requesting a way to write conditional
expressions, which are expressions that return value A or value B depending on
whether a Boolean value is true or false.  A conditional expression lets you
write a single assignment statement that has the same effect as the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">condition</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span>
<span class="k">else</span><span class="p">:</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">false_value</span>
</pre></div>
</div>
<p>There have been endless tedious discussions of syntax on both python-dev and
comp.lang.python.  A vote was even held that found the majority of voters wanted
conditional expressions in some form, but there was no syntax that was preferred
by a clear majority. Candidates included C’s <code class="docutils literal notranslate"><span class="pre">cond</span> <span class="pre">?</span> <span class="pre">true_v</span> <span class="pre">:</span> <span class="pre">false_v</span></code>, <code class="docutils literal notranslate"><span class="pre">if</span>
<span class="pre">cond</span> <span class="pre">then</span> <span class="pre">true_v</span> <span class="pre">else</span> <span class="pre">false_v</span></code>, and 16 other variations.</p>
<p>Guido van Rossum eventually chose a surprising syntax:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">true_value</span> <span class="k">if</span> <span class="n">condition</span> <span class="k">else</span> <span class="n">false_value</span>
</pre></div>
</div>
<p>Evaluation is still lazy as in existing Boolean expressions, so the order of
evaluation jumps around a bit.  The <em>condition</em> expression in the middle is
evaluated first, and the <em>true_value</em> expression is evaluated only if the
condition was true.  Similarly, the <em>false_value</em> expression is only evaluated
when the condition is false.</p>
<p>This syntax may seem strange and backwards; why does the condition go in the
<em>middle</em> of the expression, and not in the front as in C’s <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">?</span> <span class="pre">x</span> <span class="pre">:</span> <span class="pre">y</span></code>?  The
decision was checked by applying the new syntax to the modules in the standard
library and seeing how the resulting code read.  In many cases where a
conditional expression is used, one value seems to be the ‘common case’ and one
value is an ‘exceptional case’, used only on rarer occasions when the condition
isn’t met.  The conditional syntax makes this pattern a bit more obvious:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">contents</span> <span class="o">=</span> <span class="p">((</span><span class="n">doc</span> <span class="o">+</span> <span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">doc</span> <span class="k">else</span> <span class="s1">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>I read the above statement as meaning “here <em>contents</em> is  usually assigned a
value of <code class="docutils literal notranslate"><span class="pre">doc+'\n'</span></code>; sometimes  <em>doc</em> is empty, in which special case an empty
string is returned.”   I doubt I will use conditional expressions very often
where there  isn’t a clear common and uncommon case.</p>
<p>There was some discussion of whether the language should require surrounding
conditional expressions with parentheses.  The decision was made to <em>not</em>
require parentheses in the Python language’s grammar, but as a matter of style I
think you should always use them. Consider these two statements:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># First version -- no parens</span>
<span class="n">level</span> <span class="o">=</span> <span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span>

<span class="c1"># Second version -- with parens</span>
<span class="n">level</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span> <span class="k">if</span> <span class="n">logging</span> <span class="k">else</span> <span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
<p>In the first version, I think a reader’s eye might group the statement into
‘level = 1’, ‘if logging’, ‘else 0’, and think that the condition decides
whether the assignment to <em>level</em> is performed.  The second version reads
better, in my opinion, because it makes it clear that the assignment is always
performed and the choice is being made between two values.</p>
<p>Another reason for including the brackets: a few odd combinations of list
comprehensions and lambdas could look like incorrect conditional expressions.
See <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> for some examples.  If you put parentheses around your
conditional expressions, you won’t run into this case.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0308"><strong>PEP 308</strong></a> - Conditional Expressions</dt>
<dd>PEP written by Guido van Rossum and Raymond D. Hettinger; implemented by Thomas
Wouters.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-309-partial-function-application">
<span id="pep-309"></span><h2>PEP 309: Partial Function Application<a class="headerlink" href="#pep-309-partial-function-application" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module is intended to contain tools for functional-style
programming.</p>
<p>One useful tool in this module is the <code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> function. For programs
written in a functional style, you’ll sometimes want to construct variants of
existing functions that have some of the parameters filled in.  Consider a
Python function <code class="docutils literal notranslate"><span class="pre">f(a,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>; you could create a new function <code class="docutils literal notranslate"><span class="pre">g(b,</span> <span class="pre">c)</span></code> that
was equivalent to <code class="docutils literal notranslate"><span class="pre">f(1,</span> <span class="pre">b,</span> <span class="pre">c)</span></code>.  This is called “partial function
application”.</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">partial()</span></code> takes the arguments <code class="docutils literal notranslate"><span class="pre">(function,</span> <span class="pre">arg1,</span> <span class="pre">arg2,</span> <span class="pre">...</span> <span class="pre">kwarg1=value1,</span>
<span class="pre">kwarg2=value2)</span></code>.  The resulting object is callable, so you can just call it to
invoke <em>function</em> with the filled-in arguments.</p>
<p>Here’s a small but realistic example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">functools</span>

<span class="k">def</span> <span class="nf">log</span> <span class="p">(</span><span class="n">message</span><span class="p">,</span> <span class="n">subsystem</span><span class="p">):</span>
    <span class="s2">&quot;Write the contents of &#39;message&#39; to the specified subsystem.&quot;</span>
    <span class="nb">print</span> <span class="s1">&#39;</span><span class="si">%s</span><span class="s1">: </span><span class="si">%s</span><span class="s1">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">subsystem</span><span class="p">,</span> <span class="n">message</span><span class="p">)</span>
    <span class="o">...</span>

<span class="n">server_log</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="n">log</span><span class="p">,</span> <span class="n">subsystem</span><span class="o">=</span><span class="s1">&#39;server&#39;</span><span class="p">)</span>
<span class="n">server_log</span><span class="p">(</span><span class="s1">&#39;Unable to open socket&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Here’s another example, from a program that uses PyGTK.  Here a context-sensitive
pop-up menu is being constructed dynamically.  The callback provided
for the menu option is a partially applied version of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">open_item()</span></code>
method, where the first argument has been provided.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="k">class</span> <span class="nc">Application</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">open_item</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">path</span><span class="p">):</span>
       <span class="o">...</span>
    <span class="k">def</span> <span class="nf">init</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="n">open_func</span> <span class="o">=</span> <span class="n">functools</span><span class="o">.</span><span class="n">partial</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">open_item</span><span class="p">,</span> <span class="n">item_path</span><span class="p">)</span>
        <span class="n">popup_menu</span><span class="o">.</span><span class="n">append</span><span class="p">(</span> <span class="p">(</span><span class="s2">&quot;Open&quot;</span><span class="p">,</span> <span class="n">open_func</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="p">)</span>
</pre></div>
</div>
<p>Another function in the <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module is the
<code class="docutils literal notranslate"><span class="pre">update_wrapper(wrapper,</span> <span class="pre">wrapped)</span></code> function that helps you write
well-behaved decorators.  <code class="xref py py-func docutils literal notranslate"><span class="pre">update_wrapper()</span></code> copies the name, module, and
docstring attribute to a wrapper function so that tracebacks inside the wrapped
function are easier to understand.  For example, you might write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;Calling decorated function&#39;</span>
        <span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
    <span class="n">functools</span><span class="o">.</span><span class="n">update_wrapper</span><span class="p">(</span><span class="n">wrapper</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">wraps()</span></code> is a decorator that can be used inside your own decorators to copy
the wrapped function’s information.  An alternate  version of the previous
example would be:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">my_decorator</span><span class="p">(</span><span class="n">f</span><span class="p">):</span>
    <span class="nd">@functools</span><span class="o">.</span><span class="n">wraps</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
    <span class="k">def</span> <span class="nf">wrapper</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">):</span>
        <span class="nb">print</span> <span class="s1">&#39;Calling decorated function&#39;</span>
        <span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kwds</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">wrapper</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0309"><strong>PEP 309</strong></a> - Partial Function Application</dt>
<dd>PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang and Nick
Coghlan, with adaptations by Raymond Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-314-metadata-for-python-software-packages-v1-1">
<span id="pep-314"></span><h2>PEP 314: Metadata for Python Software Packages v1.1<a class="headerlink" href="#pep-314-metadata-for-python-software-packages-v1-1" title="Permalink to this headline">¶</a></h2>
<p>Some simple dependency support was added to Distutils.  The <code class="xref py py-func docutils literal notranslate"><span class="pre">setup()</span></code>
function now has <code class="docutils literal notranslate"><span class="pre">requires</span></code>, <code class="docutils literal notranslate"><span class="pre">provides</span></code>, and <code class="docutils literal notranslate"><span class="pre">obsoletes</span></code> keyword
parameters.  When you build a source distribution using the <code class="docutils literal notranslate"><span class="pre">sdist</span></code> command,
the dependency information will be recorded in the <code class="file docutils literal notranslate"><span class="pre">PKG-INFO</span></code> file.</p>
<p>Another new keyword parameter is <code class="docutils literal notranslate"><span class="pre">download_url</span></code>, which should be set to a URL
for the package’s source code.  This means it’s now possible to look up an entry
in the package index, determine the dependencies for a package, and download the
required packages.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">VERSION</span> <span class="o">=</span> <span class="s1">&#39;1.0&#39;</span>
<span class="n">setup</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;PyPackage&#39;</span><span class="p">,</span>
      <span class="n">version</span><span class="o">=</span><span class="n">VERSION</span><span class="p">,</span>
      <span class="n">requires</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;numarray&#39;</span><span class="p">,</span> <span class="s1">&#39;zlib (&gt;=1.1.4)&#39;</span><span class="p">],</span>
      <span class="n">obsoletes</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;OldPackage&#39;</span><span class="p">]</span>
      <span class="n">download_url</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;http://www.example.com/pypackage/dist/pkg-</span><span class="si">%s</span><span class="s1">.tar.gz&#39;</span>
                    <span class="o">%</span> <span class="n">VERSION</span><span class="p">),</span>
     <span class="p">)</span>
</pre></div>
</div>
<p>Another new enhancement to the Python package index at
<a class="reference external" href="https://pypi.org">https://pypi.org</a> is storing source and binary archives for a
package.  The new <strong class="command">upload</strong> Distutils command will upload a package to
the repository.</p>
<p>Before a package can be uploaded, you must be able to build a distribution using
the <strong class="command">sdist</strong> Distutils command.  Once that works, you can run <code class="docutils literal notranslate"><span class="pre">python</span>
<span class="pre">setup.py</span> <span class="pre">upload</span></code> to add your package to the PyPI archive.  Optionally you can
GPG-sign the package by supplying the <code class="xref std std-option docutils literal notranslate"><span class="pre">--sign</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--identity</span></code>
options.</p>
<p>Package uploading was implemented by Martin von Löwis and Richard Jones.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0314"><strong>PEP 314</strong></a> - Metadata for Python Software Packages v1.1</dt>
<dd>PEP proposed and written by A.M. Kuchling, Richard Jones, and Fred Drake;
implemented by Richard Jones and Fred Drake.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-328-absolute-and-relative-imports">
<span id="pep-328"></span><h2>PEP 328: Absolute and Relative Imports<a class="headerlink" href="#pep-328-absolute-and-relative-imports" title="Permalink to this headline">¶</a></h2>
<p>The simpler part of PEP 328 was implemented in Python 2.4: parentheses could now
be used to enclose the names imported from a module using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span>
<span class="pre">...</span></code> statement, making it easier to import many different names.</p>
<p>The more complicated part has been implemented in Python 2.5: importing a module
can be specified to use absolute or package-relative imports.  The plan is to
move toward making absolute imports the default in future versions of Python.</p>
<p>Let’s say you have a package directory like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">pkg</span><span class="o">/</span>
<span class="n">pkg</span><span class="o">/</span><span class="fm">__init__</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">main</span><span class="o">.</span><span class="n">py</span>
<span class="n">pkg</span><span class="o">/</span><span class="n">string</span><span class="o">.</span><span class="n">py</span>
</pre></div>
</div>
<p>This defines a package named <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg</span></code> containing the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> submodules.</p>
<p>Consider the code in the <code class="file docutils literal notranslate"><span class="pre">main.py</span></code> module.  What happens if it executes
the statement <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code>?  In Python 2.4 and earlier, it will first look
in the package’s directory to perform a relative import, finds
<code class="file docutils literal notranslate"><span class="pre">pkg/string.py</span></code>, imports the contents of that file as the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> module, and that module is bound to the name <code class="docutils literal notranslate"><span class="pre">string</span></code> in the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> module’s namespace.</p>
<p>That’s fine if <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> was what you wanted.  But what if you wanted
Python’s standard <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module?  There’s no clean way to ignore
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code> and look for the standard module; generally you had to look at
the contents of <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code>, which is slightly unclean.    Holger Krekel’s
<code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package provides a tidier way to perform imports from the standard
library, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">py;</span> <span class="pre">py.std.string.join()</span></code>, but that package isn’t available
on all Python installations.</p>
<p>Reading code which relies on relative imports is also less clear, because a
reader may be confused about which module, <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> or <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>,
is intended to be used.  Python users soon learned not to duplicate the names of
standard library modules in the names of their packages’ submodules, but you
can’t protect against having your submodule’s name being used for a new module
added in a future version of Python.</p>
<p>In Python 2.5, you can switch <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>’s behaviour to  absolute imports
using a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">absolute_import</span></code> directive.  This absolute-import
behaviour will become the default in a future version (probably Python
2.7).  Once absolute imports  are the default, <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">string</span></code> will always
find the standard library’s version. It’s suggested that users should begin
using absolute imports as much as possible, so it’s preferable to begin writing
<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">pkg</span> <span class="pre">import</span> <span class="pre">string</span></code> in your code.</p>
<p>Relative imports are still possible by adding a leading period  to the module
name when using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Import names from pkg.string</span>
<span class="kn">from</span> <span class="nn">.string</span> <span class="k">import</span> <span class="n">name1</span><span class="p">,</span> <span class="n">name2</span>
<span class="c1"># Import pkg.string</span>
<span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">string</span>
</pre></div>
</div>
<p>This imports the <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module relative to the current package, so in
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.main</span></code> this will import <em>name1</em> and <em>name2</em> from <code class="xref py py-mod docutils literal notranslate"><span class="pre">pkg.string</span></code>.
Additional leading periods perform the relative import starting from the parent
of the current package.  For example, code in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B.C</span></code> module can do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="k">import</span> <span class="n">D</span>                 <span class="c1"># Imports A.B.D</span>
<span class="kn">from</span> <span class="nn">..</span> <span class="k">import</span> <span class="n">E</span>                <span class="c1"># Imports A.E</span>
<span class="kn">from</span> <span class="nn">..F</span> <span class="k">import</span> <span class="n">G</span>               <span class="c1"># Imports A.F.G</span>
</pre></div>
</div>
<p>Leading periods cannot be used with the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">modname</span></code>  form of the import
statement, only the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">...</span> <span class="pre">import</span></code> form.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0328"><strong>PEP 328</strong></a> - Imports: Multi-Line and Absolute/Relative</dt>
<dd>PEP written by Aahz; implemented by Thomas Wouters.</dd>
<dt><a class="reference external" href="https://pylib.readthedocs.org/">https://pylib.readthedocs.org/</a></dt>
<dd>The py library by Holger Krekel, which contains the <code class="xref py py-mod docutils literal notranslate"><span class="pre">py.std</span></code> package.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-338-executing-modules-as-scripts">
<span id="pep-338"></span><h2>PEP 338: Executing Modules as Scripts<a class="headerlink" href="#pep-338-executing-modules-as-scripts" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch added in Python 2.4 to execute a module as a script
gained a few more abilities.  Instead of being implemented in C code inside the
Python interpreter, the switch now uses an implementation in a new module,
<a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a>.</p>
<p>The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module implements a more sophisticated import mechanism so that
it’s now possible to run modules in a package such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">pychecker.checker</span></code>.
The module also supports alternative import mechanisms such as the
<a class="reference internal" href="../library/zipimport.html#module-zipimport" title="zipimport: support for importing Python modules from ZIP archives."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipimport</span></code></a> module.  This means you can add a .zip archive’s path to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and then use the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch to execute code from the
archive.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0338"><strong>PEP 338</strong></a> - Executing modules as scripts</dt>
<dd>PEP written and  implemented by Nick Coghlan.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-341-unified-try-except-finally">
<span id="pep-341"></span><h2>PEP 341: Unified try/except/finally<a class="headerlink" href="#pep-341-unified-try-except-finally" title="Permalink to this headline">¶</a></h2>
<p>Until Python 2.5, the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement came in two flavours. You could
use a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block to ensure that code is always executed, or one or
more <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks to catch  specific exceptions.  You couldn’t
combine both <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block, because
generating the right bytecode for the combined version was complicated and it
wasn’t clear what the semantics of the combined statement should be.</p>
<p>Guido van Rossum spent some time working with Java, which does support the
equivalent of combining <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks and a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> block,
and this clarified what the statement should mean.  In Python 2.5, you can now
write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">block</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception1</span><span class="p">:</span>
    <span class="n">handler</span><span class="o">-</span><span class="mi">1</span> <span class="o">...</span>
<span class="k">except</span> <span class="n">Exception2</span><span class="p">:</span>
    <span class="n">handler</span><span class="o">-</span><span class="mi">2</span> <span class="o">...</span>
<span class="k">else</span><span class="p">:</span>
    <span class="k">else</span><span class="o">-</span><span class="n">block</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">final</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The code in <em>block-1</em> is executed.  If the code raises an exception, the various
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> blocks are tested: if the exception is of class
<code class="xref py py-class docutils literal notranslate"><span class="pre">Exception1</span></code>, <em>handler-1</em> is executed; otherwise if it’s of class
<code class="xref py py-class docutils literal notranslate"><span class="pre">Exception2</span></code>, <em>handler-2</em> is executed, and so forth.  If no exception is
raised, the <em>else-block</em> is executed.</p>
<p>No matter what happened previously, the <em>final-block</em> is executed once the code
block is complete and any raised exceptions handled. Even if there’s an error in
an exception handler or the <em>else-block</em> and a new exception is raised, the code
in the <em>final-block</em> is still run.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0341"><strong>PEP 341</strong></a> - Unifying try-except and try-finally</dt>
<dd>PEP written by Georg Brandl;  implementation by Thomas Lee.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-342-new-generator-features">
<span id="pep-342"></span><h2>PEP 342: New Generator Features<a class="headerlink" href="#pep-342-new-generator-features" title="Permalink to this headline">¶</a></h2>
<p>Python 2.5 adds a simple way to pass values <em>into</em> a generator. As introduced in
Python 2.3, generators only produce output; once a generator’s code was invoked
to create an iterator, there was no way to pass any new information into the
function when its execution is resumed.  Sometimes the ability to pass in some
information would be useful.  Hackish solutions to this include making the
generator’s code look at a global variable and then changing the global
variable’s value, or passing in some mutable object that callers then modify.</p>
<p>To refresh your memory of basic generators, here’s a simple example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">i</span>
        <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>When you call <code class="docutils literal notranslate"><span class="pre">counter(10)</span></code>, the result is an iterator that returns the values
from 0 up to 9.  On encountering the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement, the iterator
returns the provided value and suspends the function’s execution, preserving the
local variables. Execution resumes on the following call to the iterator’s
<a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method, picking up after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement.</p>
<p>In Python 2.3, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> was a statement; it didn’t return any value.  In
2.5, <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> is now an expression, returning a value that can be
assigned to a variable or otherwise operated on:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
</pre></div>
</div>
<p>I recommend that you always put parentheses around a <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression
when you’re doing something with the returned value, as in the above example.
The parentheses aren’t always necessary, but it’s easier to always add them
instead of having to remember when they’re needed.</p>
<p>(<span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> explains the exact rules, which are that a <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>-expression must always be parenthesized except when it occurs at the top-level
expression on the right-hand side of an assignment.  This means you can write
<code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">i</span></code> but have to use parentheses when there’s an operation, as in
<code class="docutils literal notranslate"><span class="pre">val</span> <span class="pre">=</span> <span class="pre">(yield</span> <span class="pre">i)</span> <span class="pre">+</span> <span class="pre">12</span></code>.)</p>
<p>Values are sent into a generator by calling its <code class="docutils literal notranslate"><span class="pre">send(value)</span></code> method.  The
generator’s code is then resumed and the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression returns the
specified <em>value</em>.  If the regular <a class="reference internal" href="../library/functions.html#next" title="next"><code class="xref py py-meth docutils literal notranslate"><span class="pre">next()</span></code></a> method is called, the
<a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> returns <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p>
<p>Here’s the previous example, modified to allow changing the value of the
internal counter.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">counter</span> <span class="p">(</span><span class="n">maximum</span><span class="p">):</span>
    <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">while</span> <span class="n">i</span> <span class="o">&lt;</span> <span class="n">maximum</span><span class="p">:</span>
        <span class="n">val</span> <span class="o">=</span> <span class="p">(</span><span class="k">yield</span> <span class="n">i</span><span class="p">)</span>
        <span class="c1"># If value provided, change counter</span>
        <span class="k">if</span> <span class="n">val</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="n">val</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
</pre></div>
</div>
<p>And here’s an example of changing the counter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">it</span> <span class="o">=</span> <span class="n">counter</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">0</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">send</span><span class="p">(</span><span class="mi">8</span><span class="p">)</span>
<span class="go">8</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="go">9</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;t.py&quot;</span>, line <span class="m">15</span>, in <span class="n">?</span>
    <span class="nb">print</span> <span class="n">it</span><span class="o">.</span><span class="n">next</span><span class="p">()</span>
<span class="gr">StopIteration</span>
</pre></div>
</div>
<p><a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will usually return <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>, so you should always check
for this case.  Don’t just use its value in expressions unless you’re sure that
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code> method will be the only method used to resume your generator
function.</p>
<p>In addition to <code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code>, there are two other new methods on generators:</p>
<ul>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">throw(type,</span> <span class="pre">value=None,</span> <span class="pre">traceback=None)</span></code> is used to raise an exception
inside the generator; the exception is raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression
where the generator’s execution is paused.</p>
</li>
<li><p class="first"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> raises a new <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception inside the generator
to terminate the iteration.  On receiving this exception, the generator’s code
must either raise <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> or <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>.  Catching the
<a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception and returning a value is illegal and will trigger
a <a class="reference internal" href="../library/exceptions.html#exceptions.RuntimeError" title="exceptions.RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a>; if the function raises some other exception, that
exception is propagated to the caller.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> will also be called by
Python’s garbage collector when the generator is garbage-collected.</p>
<p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> occurs, I suggest
using a <code class="docutils literal notranslate"><span class="pre">try:</span> <span class="pre">...</span> <span class="pre">finally:</span></code> suite instead of  catching <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.</p>
</li>
</ul>
<p>The cumulative effect of these changes is to turn generators from one-way
producers of information into both producers and consumers.</p>
<p>Generators also become <em>coroutines</em>, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement), but coroutines can be entered,
exited, and resumed at many different points (the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statements).
We’ll have to figure out patterns for using coroutines effectively in Python.</p>
<p>The addition of the <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method has one side effect that isn’t obvious.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> is called when a generator is garbage-collected, so this means the
generator’s code gets one last chance to run before the generator is destroyed.
This last chance means that <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> statements in generators can now
be guaranteed to work; the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause will now always get a
chance to run.  The syntactic restriction that you couldn’t mix <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a>
statements with a <code class="docutils literal notranslate"><span class="pre">try...finally</span></code> suite has therefore been removed.  This
seems like a minor bit of language trivia, but using generators and
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> is actually necessary in order to implement the
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement described by PEP 343.  I’ll look at this new statement
in the following  section.</p>
<p>Another even more esoteric effect of this change: previously, the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> attribute of a generator was always a frame object. It’s now
possible for <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> to be <code class="docutils literal notranslate"><span class="pre">None</span></code> once the generator has been
exhausted.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> - Coroutines via Enhanced Generators</dt>
<dd><p class="first">PEP written by  Guido van Rossum and Phillip J. Eby; implemented by Phillip J.
Eby.  Includes examples of  some fancier uses of generators as coroutines.</p>
<p class="last">Earlier versions of these features were proposed in  <span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0288"><strong>PEP 288</strong></a> by Raymond
Hettinger and <span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0325"><strong>PEP 325</strong></a> by Samuele Pedroni.</p>
</dd>
<dt><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a></dt>
<dd>The Wikipedia entry for  coroutines.</dd>
<dt><a class="reference external" href="http://www.sidhe.org/~dan/blog/archives/000178.html">http://www.sidhe.org/~dan/blog/archives/000178.html</a></dt>
<dd>An explanation of coroutines from a Perl point of view, written by Dan Sugalski.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-343-the-with-statement">
<span id="pep-343"></span><h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement clarifies code that previously would use
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed.  In this
section, I’ll discuss the statement as it will commonly be used.  In the next
section, I’ll examine the implementation details and show how to write objects
for use with this statement.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is a new control-flow structure whose basic
structure is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">expression</span> <span class="p">[</span><span class="k">as</span> <span class="n">variable</span><span class="p">]:</span>
    <span class="k">with</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods.</p>
<p>The object’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is called before <em>with-block</em> is executed and
therefore can run set-up code. It also may return a value that is bound to the
name <em>variable</em>, if given.  (Note carefully that <em>variable</em> is <em>not</em> assigned
the result of <em>expression</em>.)</p>
<p>After execution of the <em>with-block</em> is finished, the object’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>To enable the statement in Python 2.5, you need to add the following directive
to your module:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">with_statement</span>
</pre></div>
</div>
<p>The statement will always be enabled in Python 2.6.</p>
<p>Some standard Python objects now support the context management protocol and can
be used with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement. File objects are one example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span>
        <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>After this statement has executed, the file object in <em>f</em> will have been
automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop raised an exception
part-way through the block.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In this case, <em>f</em> is the same object created by <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, because
<code class="xref py py-meth docutils literal notranslate"><span class="pre">file.__enter__()</span></code> returns <em>self</em>.</p>
</div>
<p>The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module’s locks and condition variables  also support the
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
    <span class="c1"># Critical section of code</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The lock is acquired before the block is executed and always released once  the
block is complete.</p>
<p>The new <code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code> function in the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">Context</span><span class="p">,</span> <span class="n">localcontext</span>

<span class="c1"># Displays with default precision of 28 digits</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;578&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>

<span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">16</span><span class="p">)):</span>
    <span class="c1"># All code in this block uses a precision of 16 digits.</span>
    <span class="c1"># The original context is restored on exiting the block.</span>
    <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="writing-context-managers">
<span id="new-25-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Permalink to this headline">¶</a></h3>
<p>Under the hood, the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is fairly complicated. Most
people will only use ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.</p>
<p>A high-level explanation of the context management protocol is:</p>
<ul class="simple">
<li>The expression is evaluated and should result in an object called a “context
manager”.  The context manager must have <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods.</li>
<li>The context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is called.  The value returned
is assigned to <em>VAR</em>.  If no <code class="docutils literal notranslate"><span class="pre">'as</span> <span class="pre">VAR'</span></code> clause is present, the value is simply
discarded.</li>
<li>The code in <em>BLOCK</em> is executed.</li>
<li>If <em>BLOCK</em> raises an exception, the <code class="docutils literal notranslate"><span class="pre">__exit__(type,</span> <span class="pre">value,</span> <span class="pre">traceback)</span></code>
is called with the exception details, the same values returned by
<a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>.  The method’s return value controls whether the exception
is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
in suppressing it.  You’ll only rarely want to suppress the exception, because
if you do the author of the code containing the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will
never realize anything went wrong.</li>
<li>If <em>BLOCK</em> didn’t raise an exception,  the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is still
called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
</ul>
<p>Let’s think through an example.  I won’t present detailed code but will only
sketch the methods necessary for a database that supports transactions.</p>
<p>(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)</p>
<p>Let’s assume there’s an object representing a database connection. Our goal will
be to let the user write code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_connection</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into ...&#39;</span><span class="p">)</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;delete from ...&#39;</span><span class="p">)</span>
    <span class="c1"># ... more operations ...</span>
</pre></div>
</div>
<p>The transaction should be committed if the code in the block runs flawlessly or
rolled back if there’s an exception. Here’s the basic interface for
<code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="c1"># Database interface</span>
    <span class="k">def</span> <span class="nf">cursor</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Returns a cursor object and starts a new transaction&quot;</span>
    <span class="k">def</span> <span class="nf">commit</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Commits current transaction&quot;</span>
    <span class="k">def</span> <span class="nf">rollback</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Rolls back current transaction&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">cursor</span></code> to
their ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement to bind the cursor to a variable name.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__enter__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Code to start a new transaction</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cursor</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is the most complicated because it’s where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.</p>
<p>In the code below, execution will just fall off the end of the function,
returning the default value of <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement at the marked location.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__exit__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">type</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="c1"># No exception, so commit</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Exception occurred, so rollback.</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
            <span class="c1"># return False</span>
</pre></div>
</div>
</div>
<div class="section" id="the-contextlib-module">
<span id="contextlibmod"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this headline">¶</a></h3>
<p>The new <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module provides some functions and a decorator that
are useful for writing objects for use with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.</p>
<p>The decorator is called <code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code>, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be executed as the
<a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method, and the value yielded will be the method’s return
value that will get bound to the variable in the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement’s
<a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause, if any.  The code after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be
executed in the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method.  Any exception raised in the block will
be raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement.</p>
<p>Our database example from the previous section could be written  using this
decorator as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">db_transaction</span> <span class="p">(</span><span class="n">connection</span><span class="p">):</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">cursor</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
        <span class="k">raise</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">)</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module also has a <code class="docutils literal notranslate"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)</span></code> function
that combines a number of context managers so you don’t need to write nested
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statements.  In this example, the single ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’
statement both starts a database transaction and acquires a thread lock:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">nested</span> <span class="p">(</span><span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">),</span> <span class="n">lock</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">locked</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Finally, the <code class="docutils literal notranslate"><span class="pre">closing(object)</span></code> function returns <em>object</em> so that it can be
bound to a variable, and calls <code class="docutils literal notranslate"><span class="pre">object.close</span></code> at the end of the block.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">closing</span>

<span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.yahoo.com&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
<dd>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement, which can be helpful in learning how the statement
works.</dd>
</dl>
<p class="last">The documentation  for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module.</p>
</div>
</div>
</div>
<div class="section" id="pep-352-exceptions-as-new-style-classes">
<span id="pep-352"></span><h2>PEP 352: Exceptions as New-Style Classes<a class="headerlink" href="#pep-352-exceptions-as-new-style-classes" title="Permalink to this headline">¶</a></h2>
<p>Exception classes can now be new-style classes, not just classic classes, and
the built-in <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class and all the standard built-in exceptions
(<a class="reference internal" href="../library/exceptions.html#exceptions.NameError" title="exceptions.NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>, etc.) are now new-style classes.</p>
<p>The inheritance hierarchy for exceptions has been rearranged a bit. In 2.5, the
inheritance relationships are:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="ne">BaseException</span>       <span class="c1"># New in Python 2.5</span>
<span class="o">|-</span> <span class="ne">KeyboardInterrupt</span>
<span class="o">|-</span> <span class="ne">SystemExit</span>
<span class="o">|-</span> <span class="ne">Exception</span>
   <span class="o">|-</span> <span class="p">(</span><span class="nb">all</span> <span class="n">other</span> <span class="n">current</span> <span class="n">built</span><span class="o">-</span><span class="ow">in</span> <span class="n">exceptions</span><span class="p">)</span>
</pre></div>
</div>
<p>This rearrangement was done because people often want to catch all exceptions
that indicate program errors.  <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>
aren’t errors, though, and usually represent an explicit action such as the user
hitting <kbd class="kbd docutils literal notranslate">Control-C</kbd> or code calling <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>.  A bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> will
catch all exceptions, so you commonly need to list <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and
<a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> in order to re-raise them.  The usual pattern is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
<span class="k">except</span> <span class="p">(</span><span class="ne">KeyboardInterrupt</span><span class="p">,</span> <span class="ne">SystemExit</span><span class="p">):</span>
    <span class="k">raise</span>
<span class="k">except</span><span class="p">:</span>
    <span class="c1"># Log error...</span>
    <span class="c1"># Continue running program...</span>
</pre></div>
</div>
<p>In Python 2.5, you can now write <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception</span></code> to achieve the same
result, catching all the exceptions that usually indicate errors  but leaving
<a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> alone.  As in previous versions,
a bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> still catches all exceptions.</p>
<p>The goal for Python 3.0 is to require any class raised as an exception to derive
from <a class="reference internal" href="../library/exceptions.html#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> or some descendant of <a class="reference internal" href="../library/exceptions.html#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a>, and future
releases in the Python 2.x series may begin to enforce this constraint.
Therefore, I suggest you begin making all your exception classes derive from
<a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> now.  It’s been suggested that the bare <code class="docutils literal notranslate"><span class="pre">except:</span></code> form should
be removed in Python 3.0, but Guido van Rossum hasn’t decided whether to do this
or not.</p>
<p>Raising of strings as exceptions, as in the statement <code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">&quot;Error</span>
<span class="pre">occurred&quot;</span></code>, is deprecated in Python 2.5 and will trigger a warning.  The aim is
to be able to remove the string-exception feature in a few releases.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-13"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0352"><strong>PEP 352</strong></a> - Required Superclass for Exceptions</dt>
<dd>PEP written by  Brett Cannon and Guido van Rossum; implemented by Brett Cannon.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-353-using-ssize-t-as-the-index-type">
<span id="pep-353"></span><h2>PEP 353: Using ssize_t as the index type<a class="headerlink" href="#pep-353-using-ssize-t-as-the-index-type" title="Permalink to this headline">¶</a></h2>
<p>A wide-ranging change to Python’s C API, using a new  <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> type
definition instead of <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>,  will permit the interpreter to handle more
data on 64-bit platforms. This change doesn’t affect Python’s capacity on 32-bit
platforms.</p>
<p>Various pieces of the Python interpreter used C’s <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> type to store
sizes or counts; for example, the number of items in a list or tuple were stored
in an <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>.  The C compilers for most 64-bit platforms still define
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> as a 32-bit type, so that meant that lists could only hold up to
<code class="docutils literal notranslate"><span class="pre">2**31</span> <span class="pre">-</span> <span class="pre">1</span></code> = 2147483647 items. (There are actually a few different
programming models that 64-bit C compilers can use – see
<a class="reference external" href="http://www.unix.org/version2/whatsnew/lp64_wp.html">http://www.unix.org/version2/whatsnew/lp64_wp.html</a> for a discussion – but the
most commonly available model leaves <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> as 32 bits.)</p>
<p>A limit of 2147483647 items doesn’t really matter on a 32-bit platform because
you’ll run out of memory before hitting the length limit. Each list item
requires space for a pointer, which is 4 bytes, plus space for a
<a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span></code></a> representing the item.  2147483647*4 is already more bytes
than a 32-bit address space can contain.</p>
<p>It’s possible to address that much memory on a 64-bit platform, however.  The
pointers for a list that size would only require 16 GiB of space, so it’s not
unreasonable that Python programmers might construct lists that large.
Therefore, the Python interpreter had to be changed to use some type other than
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>, and this will be a 64-bit type on 64-bit platforms.  The change
will cause incompatibilities on 64-bit machines, so it was deemed worth making
the transition now, while the number of 64-bit users is still relatively small.
(In 5 or 10 years, we may <em>all</em> be on 64-bit machines, and the transition would
be more painful then.)</p>
<p>This change most strongly affects authors of C extension modules.   Python
strings and container types such as lists and tuples  now use
<code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> to store their size.   Functions such as
<a class="reference internal" href="../c-api/list.html#c.PyList_Size" title="PyList_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyList_Size()</span></code></a>  now return <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.  Code in extension modules
may therefore need to have some variables changed to <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.</p>
<p>The <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a> and <a class="reference internal" href="../c-api/arg.html#c.Py_BuildValue" title="Py_BuildValue"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_BuildValue()</span></code></a> functions have a new
conversion code, <code class="docutils literal notranslate"><span class="pre">n</span></code>, for <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.   <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>’s
<code class="docutils literal notranslate"><span class="pre">s#</span></code> and <code class="docutils literal notranslate"><span class="pre">t#</span></code> still output <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> by default, but you can define the
macro  <code class="xref c c-macro docutils literal notranslate"><span class="pre">PY_SSIZE_T_CLEAN</span></code> before including <code class="file docutils literal notranslate"><span class="pre">Python.h</span></code>  to make
them return <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>.</p>
<p><span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a> has a section on conversion guidelines that  extension authors should
read to learn about supporting 64-bit platforms.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a> - Using ssize_t as the index type</dt>
<dd>PEP written and implemented by Martin von Löwis.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-357-the-index-method">
<span id="pep-357"></span><h2>PEP 357: The ‘__index__’ method<a class="headerlink" href="#pep-357-the-index-method" title="Permalink to this headline">¶</a></h2>
<p>The NumPy developers had a problem that could only be solved by adding a new
special method, <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a>.  When using slice notation, as in
<code class="docutils literal notranslate"><span class="pre">[start:stop:step]</span></code>, the values of the <em>start</em>, <em>stop</em>, and <em>step</em> indexes
must all be either integers or long integers.  NumPy defines a variety of
specialized integer types corresponding to unsigned and signed integers of 8,
16, 32, and 64 bits, but there was no way to signal that these types could be
used as slice indexes.</p>
<p>Slicing can’t just use the existing <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> method because that method
is also used to implement coercion to integers.  If slicing used
<a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a>, floating-point numbers would also become legal slice indexes
and that’s clearly an undesirable behaviour.</p>
<p>Instead, a new special method called <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> was added.  It takes no
arguments and returns an integer giving the slice index to use.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span>
    <span class="k">def</span> <span class="nf">__index__</span> <span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span>
</pre></div>
</div>
<p>The return value must be either a Python integer or long integer. The
interpreter will check that the type returned is correct, and raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> if this requirement isn’t met.</p>
<p>A corresponding <code class="xref py py-attr docutils literal notranslate"><span class="pre">nb_index</span></code> slot was added to the C-level
<a class="reference internal" href="../c-api/typeobj.html#c.PyNumberMethods" title="PyNumberMethods"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyNumberMethods</span></code></a> structure to let C extensions implement this protocol.
<code class="docutils literal notranslate"><span class="pre">PyNumber_Index(obj)</span></code> can be used in extension code to call the
<a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> function and retrieve its result.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0357"><strong>PEP 357</strong></a> - Allowing Any Object to be Used for Slicing</dt>
<dd>PEP written  and implemented by Travis Oliphant.</dd>
</dl>
</div>
</div>
<div class="section" id="other-language-changes">
<span id="other-lang"></span><h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Here are all of the changes that Python 2.5 makes to the core Python language.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> type has a new hook for letting subclasses provide a default
value when a key isn’t contained in the dictionary. When a key isn’t found, the
dictionary’s <code class="docutils literal notranslate"><span class="pre">__missing__(key)</span></code> method will be called.  This hook is used
to implement the new <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code> class in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module.  The following example defines a dictionary  that returns zero for any
missing key:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">zerodict</span> <span class="p">(</span><span class="nb">dict</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">__missing__</span> <span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
        <span class="k">return</span> <span class="mi">0</span>

<span class="n">d</span> <span class="o">=</span> <span class="n">zerodict</span><span class="p">({</span><span class="mi">1</span><span class="p">:</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">:</span><span class="mi">2</span><span class="p">})</span>
<span class="nb">print</span> <span class="n">d</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="n">d</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span>   <span class="c1"># Prints 1, 2</span>
<span class="nb">print</span> <span class="n">d</span><span class="p">[</span><span class="mi">3</span><span class="p">],</span> <span class="n">d</span><span class="p">[</span><span class="mi">4</span><span class="p">]</span>   <span class="c1"># Prints 0, 0</span>
</pre></div>
</div>
</li>
<li><p class="first">Both 8-bit and Unicode strings have new <code class="docutils literal notranslate"><span class="pre">partition(sep)</span></code>  and
<code class="docutils literal notranslate"><span class="pre">rpartition(sep)</span></code> methods that simplify a common use case.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">find(S)</span></code> method is often used to get an index which is then used to
slice the string and obtain the pieces that are before and after the separator.
<code class="docutils literal notranslate"><span class="pre">partition(sep)</span></code> condenses this pattern into a single method call that
returns a 3-tuple containing the substring before the separator, the separator
itself, and the substring after the separator.  If the separator isn’t found,
the first element of the tuple is the entire string and the other two elements
are empty.  <code class="docutils literal notranslate"><span class="pre">rpartition(sep)</span></code> also returns a 3-tuple but starts searching
from the end of the string; the <code class="docutils literal notranslate"><span class="pre">r</span></code> stands for ‘reverse’.</p>
<p>Some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;http://www.python.org&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;://&#39;</span><span class="p">)</span>
<span class="go">(&#39;http&#39;, &#39;://&#39;, &#39;www.python.org&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">&#39;file:/usr/share/doc/index.html&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;://&#39;</span><span class="p">)</span>
<span class="go">(&#39;file:/usr/share/doc/index.html&#39;, &#39;&#39;, &#39;&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;Subject: a quick question&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">partition</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">)</span>
<span class="go">(u&#39;Subject&#39;, u&#39;:&#39;, u&#39; a quick question&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s1">&#39;.&#39;</span><span class="p">)</span>
<span class="go">(&#39;www.python&#39;, &#39;.&#39;, &#39;org&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;www.python.org&#39;</span><span class="o">.</span><span class="n">rpartition</span><span class="p">(</span><span class="s1">&#39;:&#39;</span><span class="p">)</span>
<span class="go">(&#39;&#39;, &#39;&#39;, &#39;www.python.org&#39;)</span>
</pre></div>
</div>
<p>(Implemented by Fredrik Lundh following a suggestion by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code> methods of string types now accept
tuples of strings to check for.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">is_image_file</span> <span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">filename</span><span class="o">.</span><span class="n">endswith</span><span class="p">((</span><span class="s1">&#39;.gif&#39;</span><span class="p">,</span> <span class="s1">&#39;.jpg&#39;</span><span class="p">,</span> <span class="s1">&#39;.tiff&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>(Implemented by Georg Brandl following a suggestion by Tom Lynn.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> built-in functions gained a <code class="docutils literal notranslate"><span class="pre">key</span></code> keyword
parameter analogous to the <code class="docutils literal notranslate"><span class="pre">key</span></code> argument for <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code>.  This parameter
supplies a function that takes a single argument and is called for every value
in the list; <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> will return the element with the
smallest/largest return value from this function. For example, to find the
longest string in a list, you can do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;medium&#39;</span><span class="p">,</span> <span class="s1">&#39;longest&#39;</span><span class="p">,</span> <span class="s1">&#39;short&#39;</span><span class="p">]</span>
<span class="c1"># Prints &#39;longest&#39;</span>
<span class="nb">print</span> <span class="nb">max</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="nb">len</span><span class="p">)</span>
<span class="c1"># Prints &#39;short&#39;, because lexicographically &#39;short&#39; has the largest value</span>
<span class="nb">print</span> <span class="nb">max</span><span class="p">(</span><span class="n">L</span><span class="p">)</span>
</pre></div>
</div>
<p>(Contributed by Steven Bethard and Raymond Hettinger.)</p>
</li>
<li><p class="first">Two new built-in functions, <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> and <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a>, evaluate whether an
iterator contains any true or false values.  <a class="reference internal" href="../library/functions.html#any" title="any"><code class="xref py py-func docutils literal notranslate"><span class="pre">any()</span></code></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a>
if any value returned by the iterator is true; otherwise it will return
<a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a>.  <a class="reference internal" href="../library/functions.html#all" title="all"><code class="xref py py-func docutils literal notranslate"><span class="pre">all()</span></code></a> returns <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> only if all of the values
returned by the iterator evaluate as true. (Suggested by Guido van Rossum, and
implemented by Raymond Hettinger.)</p>
</li>
<li><p class="first">The result of a class’s <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method can now be either a long
integer or a regular integer.  If a long integer is returned, the hash of that
value is taken.  In earlier versions the hash value was required to be a
regular integer, but in 2.5 the <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> built-in was changed to always
return non-negative numbers, and users often seem to use <code class="docutils literal notranslate"><span class="pre">id(self)</span></code> in
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> methods (though this is discouraged).</p>
</li>
<li><p class="first">ASCII is now the default encoding for modules.  It’s now  a syntax error if a
module contains string literals with 8-bit characters but doesn’t have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.  See <span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0263"><strong>PEP 263</strong></a>  for how to declare a module’s encoding; for example, you
might add  a line like this near the top of the source file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: latin1 -*-</span>
</pre></div>
</div>
</li>
<li><p class="first">A new warning, <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code>, is triggered when  you attempt to
compare a Unicode string and an 8-bit string  that can’t be converted to Unicode
using the default ASCII encoding.   The result of the comparison is false:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">chr</span><span class="p">(</span><span class="mi">128</span><span class="p">)</span> <span class="o">==</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">128</span><span class="p">)</span>   <span class="c1"># Can&#39;t convert chr(128) to Unicode</span>
<span class="go">__main__:1: UnicodeWarning: Unicode equal comparison failed</span>
<span class="go">  to convert both arguments to Unicode - interpreting them</span>
<span class="go">  as being unequal</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">chr</span><span class="p">(</span><span class="mi">127</span><span class="p">)</span> <span class="o">==</span> <span class="n">unichr</span><span class="p">(</span><span class="mi">127</span><span class="p">)</span>   <span class="c1"># chr(127) can be converted</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Previously this would raise a <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code> exception, but in 2.5
this could result in puzzling problems when accessing a dictionary.  If you
looked up <code class="docutils literal notranslate"><span class="pre">unichr(128)</span></code> and <code class="docutils literal notranslate"><span class="pre">chr(128)</span></code> was being used as a key, you’d get a
<code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code> exception.  Other changes in 2.5 resulted in this
exception being raised instead of suppressed by the code in <code class="file docutils literal notranslate"><span class="pre">dictobject.c</span></code>
that implements dictionaries.</p>
<p>Raising an exception for such a comparison is strictly correct, but the change
might have broken code, so instead  <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code> was introduced.</p>
<p>(Implemented by Marc-André Lemburg.)</p>
</li>
<li><p class="first">One error that Python programmers sometimes make is forgetting to include an
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> module in a package directory. Debugging this mistake can be
confusing, and usually requires running Python with the <a class="reference internal" href="../using/cmdline.html#id3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-v</span></code></a> switch to
log all the paths searched. In Python 2.5, a new <a class="reference internal" href="../library/exceptions.html#exceptions.ImportWarning" title="exceptions.ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a> warning is
triggered when an import would have picked up a directory as a package but no
<code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> was found.  This warning is silently ignored by default;
provide the <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code></a> option when running the Python executable to display
the warning message. (Implemented by Thomas Wouters.)</p>
</li>
<li><p class="first">The list of base classes in a class definition can now be empty.   As an
example, this is now legal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">():</span>
    <span class="k">pass</span>
</pre></div>
</div>
<p>(Implemented by Brett Cannon.)</p>
</li>
</ul>
<div class="section" id="interactive-interpreter-changes">
<span id="interactive"></span><h3>Interactive Interpreter Changes<a class="headerlink" href="#interactive-interpreter-changes" title="Permalink to this headline">¶</a></h3>
<p>In the interactive interpreter, <code class="docutils literal notranslate"><span class="pre">quit</span></code> and <code class="docutils literal notranslate"><span class="pre">exit</span></code>  have long been strings so
that new users get a somewhat helpful message when they try to quit:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">quit</span>
<span class="go">&#39;Use Ctrl-D (i.e. EOF) to exit.&#39;</span>
</pre></div>
</div>
<p>In Python 2.5, <code class="docutils literal notranslate"><span class="pre">quit</span></code> and <code class="docutils literal notranslate"><span class="pre">exit</span></code> are now objects that still produce string
representations of themselves, but are also callable. Newbies who try <code class="docutils literal notranslate"><span class="pre">quit()</span></code>
or <code class="docutils literal notranslate"><span class="pre">exit()</span></code> will now exit the interpreter as they expect.  (Implemented by
Georg Brandl.)</p>
<p>The Python executable now accepts the standard long options  <a class="reference internal" href="../using/cmdline.html#cmdoption-help"><code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code></a>
and <a class="reference internal" href="../using/cmdline.html#cmdoption-version"><code class="xref std std-option docutils literal notranslate"><span class="pre">--version</span></code></a>; on Windows,  it also accepts the <a class="reference internal" href="../using/cmdline.html#cmdoption"><code class="xref std std-option docutils literal notranslate"><span class="pre">/?</span></code></a> option
for displaying a help message. (Implemented by Georg Brandl.)</p>
</div>
<div class="section" id="optimizations">
<span id="opts"></span><h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<p>Several of the optimizations were developed at the NeedForSpeed sprint, an event
held in Reykjavik, Iceland, from May 21–28 2006. The sprint focused on speed
enhancements to the CPython implementation and was funded by EWT LLC with local
support from CCP Games.  Those optimizations added at this sprint are specially
marked in the following list.</p>
<ul class="simple">
<li>When they were introduced  in Python 2.4, the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and
<a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types were built on top of Python’s dictionary type.   In 2.5
the internal data structure has been customized for implementing sets, and as a
result sets will use a third less memory and are somewhat faster. (Implemented
by Raymond Hettinger.)</li>
<li>The speed of some Unicode operations, such as finding substrings, string
splitting, and character map encoding and decoding, has been improved.
(Substring search and splitting improvements were added by Fredrik Lundh and
Andrew Dalke at the NeedForSpeed sprint. Character maps were improved by Walter
Dörwald and Martin von Löwis.)</li>
<li>The <code class="docutils literal notranslate"><span class="pre">long(str,</span> <span class="pre">base)</span></code> function is now faster on long digit strings
because fewer intermediate results are calculated.  The peak is for strings of
around 800–1000 digits where  the function is 6 times faster. (Contributed by
Alan McIntyre and committed at the NeedForSpeed sprint.)</li>
<li>It’s now illegal to mix iterating over a file  with <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">line</span> <span class="pre">in</span> <span class="pre">file</span></code> and
calling  the file object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>/<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">readlines()</span></code>
methods.  Iteration uses an internal buffer and the  <code class="xref py py-meth docutils literal notranslate"><span class="pre">read*()</span></code> methods
don’t use that buffer.   Instead they would return the data following the
buffer, causing the data to appear out of order.  Mixing iteration and these
methods will now trigger a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> from the <code class="xref py py-meth docutils literal notranslate"><span class="pre">read*()</span></code> method.
(Implemented by Thomas Wouters.)</li>
<li>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module now compiles structure format  strings into an
internal representation and caches this representation, yielding a 20% speedup.
(Contributed by Bob Ippolito at the NeedForSpeed sprint.)</li>
<li>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module got a 1 or 2% speedup by switching to  Python’s allocator
functions instead of the system’s  <code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code>.
(Contributed by Jack Diederich at the NeedForSpeed sprint.)</li>
<li>The code generator’s peephole optimizer now performs simple constant folding
in expressions.  If you write something like <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">2+3</span></code>, the code generator
will do the arithmetic and produce code corresponding to <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">5</span></code>.  (Proposed
and implemented  by Raymond Hettinger.)</li>
<li>Function calls are now faster because code objects now keep  the most recently
finished frame (a “zombie frame”) in an internal field of the code object,
reusing it the next time the code object is invoked.  (Original patch by Michael
Hudson, modified by Armin Rigo and Richard Jones; committed at the NeedForSpeed
sprint.)  Frame objects are also slightly smaller, which may improve cache
locality and reduce memory usage a bit.  (Contributed by Neal Norwitz.)</li>
<li>Python’s built-in exceptions are now new-style classes, a change that speeds
up instantiation considerably.  Exception handling in Python 2.5 is therefore
about 30% faster than in 2.4. (Contributed by Richard Jones, Georg Brandl and
Sean Reifschneider at the NeedForSpeed sprint.)</li>
<li>Importing now caches the paths tried, recording whether  they exist or not so
that the interpreter makes fewer  <code class="xref c c-func docutils literal notranslate"><span class="pre">open()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">stat()</span></code> calls on
startup. (Contributed by Martin von Löwis and Georg Brandl.)</li>
</ul>
</div>
</div>
<div class="section" id="new-improved-and-removed-modules">
<span id="modules"></span><h2>New, Improved, and Removed Modules<a class="headerlink" href="#new-improved-and-removed-modules" title="Permalink to this headline">¶</a></h2>
<p>The standard library received many enhancements and bug fixes in Python 2.5.
Here’s a partial list of the most notable changes, sorted alphabetically by
module name. Consult the <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more
complete list of changes, or look through the SVN logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/audioop.html#module-audioop" title="audioop: Manipulate raw audio data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">audioop</span></code></a> module now supports the a-LAW encoding, and the code for
u-LAW encoding has been improved.  (Contributed by Lars Immisch.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module gained support for incremental codecs.  The
<code class="xref py py-func docutils literal notranslate"><span class="pre">codec.lookup()</span></code> function now returns a <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> instance instead
of a tuple. <code class="xref py py-class docutils literal notranslate"><span class="pre">CodecInfo</span></code> instances behave like a 4-tuple to preserve
backward compatibility but also have the attributes <code class="xref py py-attr docutils literal notranslate"><span class="pre">encode</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">decode</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">incrementalencoder</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">incrementaldecoder</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">streamwriter</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">streamreader</span></code>.  Incremental codecs  can receive
input and produce output in multiple chunks; the output is the same as if the
entire input was fed to the non-incremental codec. See the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> module
documentation for details. (Designed and implemented by Walter Dörwald.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module gained a new type, <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code>, that
subclasses the standard <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a> type.  The new type mostly behaves like a
dictionary but constructs a default value when a key isn’t present,
automatically adding it to the dictionary for the requested key value.</p>
<p>The first argument to <code class="xref py py-class docutils literal notranslate"><span class="pre">defaultdict</span></code>’s constructor is a factory function
that gets called whenever a key is requested but not found. This factory
function receives no arguments, so you can use built-in type constructors such
as <code class="xref py py-func docutils literal notranslate"><span class="pre">list()</span></code> or <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>.  For example,  you can make an index of words
based on their initial letter like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">words</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;Nel mezzo del cammin di nostra vita</span>
<span class="s2">mi ritrovai per una selva oscura</span>
<span class="s2">che la diritta via era smarrita&quot;&quot;&quot;</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>

<span class="n">index</span> <span class="o">=</span> <span class="n">defaultdict</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span>

<span class="k">for</span> <span class="n">w</span> <span class="ow">in</span> <span class="n">words</span><span class="p">:</span>
    <span class="n">init_letter</span> <span class="o">=</span> <span class="n">w</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
    <span class="n">index</span><span class="p">[</span><span class="n">init_letter</span><span class="p">]</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">w</span><span class="p">)</span>
</pre></div>
</div>
<p>Printing <code class="docutils literal notranslate"><span class="pre">index</span></code> results in the following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">defaultdict</span><span class="p">(</span><span class="o">&lt;</span><span class="nb">type</span> <span class="s1">&#39;list&#39;</span><span class="o">&gt;</span><span class="p">,</span> <span class="p">{</span><span class="s1">&#39;c&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;cammin&#39;</span><span class="p">,</span> <span class="s1">&#39;che&#39;</span><span class="p">],</span> <span class="s1">&#39;e&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;era&#39;</span><span class="p">],</span>
        <span class="s1">&#39;d&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;del&#39;</span><span class="p">,</span> <span class="s1">&#39;di&#39;</span><span class="p">,</span> <span class="s1">&#39;diritta&#39;</span><span class="p">],</span> <span class="s1">&#39;m&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;mezzo&#39;</span><span class="p">,</span> <span class="s1">&#39;mi&#39;</span><span class="p">],</span>
        <span class="s1">&#39;l&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;la&#39;</span><span class="p">],</span> <span class="s1">&#39;o&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;oscura&#39;</span><span class="p">],</span> <span class="s1">&#39;n&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;nel&#39;</span><span class="p">,</span> <span class="s1">&#39;nostra&#39;</span><span class="p">],</span>
        <span class="s1">&#39;p&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;per&#39;</span><span class="p">],</span> <span class="s1">&#39;s&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;selva&#39;</span><span class="p">,</span> <span class="s1">&#39;smarrita&#39;</span><span class="p">],</span>
        <span class="s1">&#39;r&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;ritrovai&#39;</span><span class="p">],</span> <span class="s1">&#39;u&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;una&#39;</span><span class="p">],</span> <span class="s1">&#39;v&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;vita&#39;</span><span class="p">,</span> <span class="s1">&#39;via&#39;</span><span class="p">]}</span>
</pre></div>
</div>
<p>(Contributed by Guido van Rossum.)</p>
</li>
<li><p class="first">The <code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> double-ended queue type supplied by the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module now has a <code class="docutils literal notranslate"><span class="pre">remove(value)</span></code> method that removes the first occurrence
of <em>value</em> in the queue, raising <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> if the value isn’t found.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">New module: The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module contains helper functions for use
with the new ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.  See section <a class="reference internal" href="#contextlibmod"><span class="std std-ref">The contextlib module</span></a>
for more about this module.</p>
</li>
<li><p class="first">New module: The <a class="reference internal" href="../library/profile.html#module-cProfile" title="cProfile"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cProfile</span></code></a> module is a C implementation of  the existing
<a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module that has much lower overhead. The module’s interface is
the same as <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a>: you run <code class="docutils literal notranslate"><span class="pre">cProfile.run('main()')</span></code> to profile a
function, can save profile data to a file, etc.  It’s not yet known if the
Hotshot profiler, which is also written in C but doesn’t match the
<a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> module’s interface, will continue to be maintained in future
versions of Python.  (Contributed by Armin Rigo.)</p>
<p>Also, the <a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> module for analyzing the data measured by the profiler
now supports directing the output to any file object by supplying a <em>stream</em>
argument to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Stats</span></code> constructor. (Contributed by Skip Montanaro.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module, which parses files in comma-separated value format,
received several enhancements and a number of bugfixes.  You can now set the
maximum size in bytes of a field by calling the
<code class="docutils literal notranslate"><span class="pre">csv.field_size_limit(new_limit)</span></code> function; omitting the <em>new_limit</em>
argument will return the currently-set limit.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">reader</span></code> class now has
a <code class="xref py py-attr docutils literal notranslate"><span class="pre">line_num</span></code> attribute that counts the number of physical lines read from
the source; records can span multiple physical lines, so <code class="xref py py-attr docutils literal notranslate"><span class="pre">line_num</span></code> is not
the same as the number of records read.</p>
<p>The CSV parser is now stricter about multi-line quoted fields. Previously, if a
line ended within a quoted field without a terminating newline character, a
newline would be inserted into the returned field. This behavior caused problems
when reading files that contained carriage return characters within fields, so
the code was changed to return the field without inserting newlines. As a
consequence, if newlines embedded within fields are important, the input should
be split into lines in a manner that preserves the newline characters.</p>
<p>(Contributed by Skip Montanaro and Andrew McNamara.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> class in the <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a>  module now has a
<code class="docutils literal notranslate"><span class="pre">strptime(string,</span> <span class="pre">format)</span></code>  method for parsing date strings, contributed
by Josh Spoerri. It uses the same format characters as <a class="reference internal" href="../library/time.html#time.strptime" title="time.strptime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strptime()</span></code></a> and
<a class="reference internal" href="../library/time.html#time.strftime" title="time.strftime"><code class="xref py py-func docutils literal notranslate"><span class="pre">time.strftime()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">datetime</span> <span class="k">import</span> <span class="n">datetime</span>

<span class="n">ts</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">strptime</span><span class="p">(</span><span class="s1">&#39;10:13:15 2006-03-07&#39;</span><span class="p">,</span>
                       <span class="s1">&#39;%H:%M:%S %Y-%m-</span><span class="si">%d</span><span class="s1">&#39;</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">SequenceMatcher.get_matching_blocks()</span></code> method in the <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a>
module now guarantees to return a minimal list of blocks describing matching
subsequences.  Previously, the algorithm would occasionally break a block of
matching elements into two list entries. (Enhancement by Tim Peters.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module gained a <code class="docutils literal notranslate"><span class="pre">SKIP</span></code> option that keeps an example from
being executed at all.  This is intended for code snippets that are usage
examples intended for the reader and aren’t actually test cases.</p>
<p>An <em>encoding</em> parameter was added to the <code class="xref py py-func docutils literal notranslate"><span class="pre">testfile()</span></code> function and the
<code class="xref py py-class docutils literal notranslate"><span class="pre">DocFileSuite</span></code> class to specify the file’s encoding.  This makes it
easier to use non-ASCII characters in  tests contained within a docstring.
(Contributed by Bjorn Tillenius.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package has been updated to version 4.0. (Contributed by
Barry Warsaw.)</p>
</li>
<li id="index-18"><p class="first">The <a class="reference internal" href="../library/fileinput.html#module-fileinput" title="fileinput: Loop over standard input or a list of files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fileinput</span></code></a> module was made more flexible. Unicode filenames are now
supported, and a <em>mode</em> parameter that defaults to <code class="docutils literal notranslate"><span class="pre">&quot;r&quot;</span></code> was added to the
<a class="reference internal" href="../library/functions.html#input" title="input"><code class="xref py py-func docutils literal notranslate"><span class="pre">input()</span></code></a> function to allow opening files in binary or <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal
newlines</span></a> mode.  Another new parameter, <em>openhook</em>, lets you use a function
other than <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>  to open the input files.  Once you’re iterating over
the set of files, the <code class="xref py py-class docutils literal notranslate"><span class="pre">FileInput</span></code> object’s new <code class="xref py py-meth docutils literal notranslate"><span class="pre">fileno()</span></code> returns
the file descriptor for the currently opened file. (Contributed by Georg
Brandl.)</p>
</li>
<li><p class="first">In the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module, the new <code class="xref py py-func docutils literal notranslate"><span class="pre">get_count()</span></code> function returns a 3-tuple
containing the current collection counts for the three GC generations.  This is
accounting information for the garbage collector; when these counts reach a
specified threshold, a garbage collection sweep will be made.  The existing
<a class="reference internal" href="../library/gc.html#gc.collect" title="gc.collect"><code class="xref py py-func docutils literal notranslate"><span class="pre">gc.collect()</span></code></a> function now takes an optional <em>generation</em> argument of 0, 1,
or 2 to specify which generation to collect. (Contributed by Barry Warsaw.)</p>
</li>
<li><p class="first">The <code class="xref py py-func docutils literal notranslate"><span class="pre">nsmallest()</span></code> and  <code class="xref py py-func docutils literal notranslate"><span class="pre">nlargest()</span></code> functions in the <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a>
module  now support a <code class="docutils literal notranslate"><span class="pre">key</span></code> keyword parameter similar to the one provided by
the <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a>/<a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a> functions and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> methods.  For
example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">heapq</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">L</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;short&quot;</span><span class="p">,</span> <span class="s1">&#39;medium&#39;</span><span class="p">,</span> <span class="s1">&#39;longest&#39;</span><span class="p">,</span> <span class="s1">&#39;longer still&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">nsmallest</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">L</span><span class="p">)</span>  <span class="c1"># Return two lowest elements, lexicographically</span>
<span class="go">[&#39;longer still&#39;, &#39;longest&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">heapq</span><span class="o">.</span><span class="n">nsmallest</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">L</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="nb">len</span><span class="p">)</span>   <span class="c1"># Return two shortest elements</span>
<span class="go">[&#39;short&#39;, &#39;medium&#39;]</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#itertools.islice" title="itertools.islice"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.islice()</span></code></a> function now accepts <code class="docutils literal notranslate"><span class="pre">None</span></code> for the start and
step arguments.  This makes it more compatible with the attributes of slice
objects, so that you can now write the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="nb">slice</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>     <span class="c1"># Create slice object</span>
<span class="n">itertools</span><span class="o">.</span><span class="n">islice</span><span class="p">(</span><span class="n">iterable</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">start</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">stop</span><span class="p">,</span> <span class="n">s</span><span class="o">.</span><span class="n">step</span><span class="p">)</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> function in the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module has been modified and
two new functions were added, <code class="xref py py-func docutils literal notranslate"><span class="pre">format_string()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">currency()</span></code>.</p>
<p>The <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> function’s <em>val</em> parameter could previously be a string as
long as no more than one %char specifier appeared; now the parameter must be
exactly one %char specifier with no surrounding text.  An optional <em>monetary</em>
parameter was also added which, if <code class="docutils literal notranslate"><span class="pre">True</span></code>, will use the locale’s rules for
formatting currency in placing a separator between groups of three digits.</p>
<p>To format strings with multiple %char specifiers, use the new
<code class="xref py py-func docutils literal notranslate"><span class="pre">format_string()</span></code> function that works like <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> but also supports
mixing %char specifiers with arbitrary text.</p>
<p>A new <code class="xref py py-func docutils literal notranslate"><span class="pre">currency()</span></code> function was also added that formats a number according
to the current locale’s settings.</p>
<p>(Contributed by Georg Brandl.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module underwent a massive rewrite to add the capability to
modify mailboxes in addition to reading them.  A new set of classes that include
<code class="xref py py-class docutils literal notranslate"><span class="pre">mbox</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">MH</span></code>, and <code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code> are used to read mailboxes, and
have an <code class="docutils literal notranslate"><span class="pre">add(message)</span></code> method to add messages, <code class="docutils literal notranslate"><span class="pre">remove(key)</span></code> to
remove messages, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">lock()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">unlock()</span></code> to lock/unlock the mailbox.
The following example converts a maildir-format mailbox into an mbox-format
one:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">mailbox</span>

<span class="c1"># &#39;factory=None&#39; uses email.Message.Message as the class representing</span>
<span class="c1"># individual messages.</span>
<span class="n">src</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">Maildir</span><span class="p">(</span><span class="s1">&#39;maildir&#39;</span><span class="p">,</span> <span class="n">factory</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
<span class="n">dest</span> <span class="o">=</span> <span class="n">mailbox</span><span class="o">.</span><span class="n">mbox</span><span class="p">(</span><span class="s1">&#39;/tmp/mbox&#39;</span><span class="p">)</span>

<span class="k">for</span> <span class="n">msg</span> <span class="ow">in</span> <span class="n">src</span><span class="p">:</span>
    <span class="n">dest</span><span class="o">.</span><span class="n">add</span><span class="p">(</span><span class="n">msg</span><span class="p">)</span>
</pre></div>
</div>
<p>(Contributed by Gregory K. Johnson.  Funding was provided by Google’s 2005
Summer of Code.)</p>
</li>
<li><p class="first">New module: the <a class="reference internal" href="../library/msilib.html#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> module allows creating Microsoft Installer
<code class="file docutils literal notranslate"><span class="pre">.msi</span></code> files and CAB files.  Some support for reading the <code class="file docutils literal notranslate"><span class="pre">.msi</span></code>
database is also included. (Contributed by Martin von Löwis.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/nis.html#module-nis" title="nis: Interface to Sun's NIS (Yellow Pages) library. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">nis</span></code></a> module now supports accessing domains other than the system
default domain by supplying a <em>domain</em> argument to the <a class="reference internal" href="../library/nis.html#nis.match" title="nis.match"><code class="xref py py-func docutils literal notranslate"><span class="pre">nis.match()</span></code></a> and
<a class="reference internal" href="../library/nis.html#nis.maps" title="nis.maps"><code class="xref py py-func docutils literal notranslate"><span class="pre">nis.maps()</span></code></a> functions. (Contributed by Ben Bell.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module’s <code class="xref py py-func docutils literal notranslate"><span class="pre">itemgetter()</span></code>  and <code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code>
functions now support multiple fields.   A call such as
<code class="docutils literal notranslate"><span class="pre">operator.attrgetter('a',</span> <span class="pre">'b')</span></code> will return a function  that retrieves the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">a</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">b</span></code> attributes.  Combining  this new feature with the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code> method’s <code class="docutils literal notranslate"><span class="pre">key</span></code> parameter  lets you easily sort lists using
multiple fields. (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module was updated to version 1.5.1 of the Optik library.
The <code class="xref py py-class docutils literal notranslate"><span class="pre">OptionParser</span></code> class gained an <code class="xref py py-attr docutils literal notranslate"><span class="pre">epilog</span></code> attribute, a string
that will be printed after the help message, and a <code class="xref py py-meth docutils literal notranslate"><span class="pre">destroy()</span></code> method to
break reference cycles created by the object. (Contributed by Greg Ward.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module underwent several changes.  The <code class="xref py py-attr docutils literal notranslate"><span class="pre">stat_float_times</span></code>
variable now defaults to true, meaning that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> will now return time
values as floats.  (This doesn’t necessarily mean that <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> will
return times that are precise to fractions of a second; not all systems support
such precision.)</p>
<p>Constants named <a class="reference internal" href="../library/os.html#os.SEEK_SET" title="os.SEEK_SET"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.SEEK_SET</span></code></a>, <a class="reference internal" href="../library/os.html#os.SEEK_CUR" title="os.SEEK_CUR"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.SEEK_CUR</span></code></a>, and
<a class="reference internal" href="../library/os.html#os.SEEK_END" title="os.SEEK_END"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.SEEK_END</span></code></a> have been added; these are the parameters to the
<a class="reference internal" href="../library/os.html#os.lseek" title="os.lseek"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.lseek()</span></code></a> function.  Two new constants for locking are
<a class="reference internal" href="../library/os.html#os.O_SHLOCK" title="os.O_SHLOCK"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.O_SHLOCK</span></code></a> and <a class="reference internal" href="../library/os.html#os.O_EXLOCK" title="os.O_EXLOCK"><code class="xref py py-attr docutils literal notranslate"><span class="pre">os.O_EXLOCK</span></code></a>.</p>
<p>Two new functions, <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code>, were added.  They’re similar
the <code class="xref py py-func docutils literal notranslate"><span class="pre">waitpid()</span></code> function which waits for a child process to exit and returns
a tuple of the process ID and its exit status, but <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">wait4()</span></code> return additional information.  <code class="xref py py-func docutils literal notranslate"><span class="pre">wait3()</span></code> doesn’t take a
process ID as input, so it waits for any child process to exit and returns a
3-tuple of <em>process-id</em>, <em>exit-status</em>, <em>resource-usage</em> as returned from the
<a class="reference internal" href="../library/resource.html#resource.getrusage" title="resource.getrusage"><code class="xref py py-func docutils literal notranslate"><span class="pre">resource.getrusage()</span></code></a> function. <code class="docutils literal notranslate"><span class="pre">wait4(pid)</span></code> does take a process ID.
(Contributed by Chad J. Schroeder.)</p>
<p>On FreeBSD, the <a class="reference internal" href="../library/os.html#os.stat" title="os.stat"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.stat()</span></code></a> function now returns  times with nanosecond
resolution, and the returned object now has <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_gen</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">st_birthtime</span></code>. The <code class="xref py py-attr docutils literal notranslate"><span class="pre">st_flags</span></code> attribute is also available, if the
platform supports it. (Contributed by Antti Louko and  Diego Pettenò.)</p>
</li>
<li><p class="first">The Python debugger provided by the <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> module can now store lists of
commands to execute when a breakpoint is reached and execution stops.  Once
breakpoint #1 has been created, enter <code class="docutils literal notranslate"><span class="pre">commands</span> <span class="pre">1</span></code> and enter a series of
commands to be executed, finishing the list with <code class="docutils literal notranslate"><span class="pre">end</span></code>.  The command list can
include commands that resume execution, such as <code class="docutils literal notranslate"><span class="pre">continue</span></code> or <code class="docutils literal notranslate"><span class="pre">next</span></code>.
(Contributed by Grégoire Dooms.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> modules no longer accept a return value
of <code class="docutils literal notranslate"><span class="pre">None</span></code> from the <a class="reference internal" href="../library/pickle.html#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method; the method must return a tuple
of arguments instead.  The ability to return <code class="docutils literal notranslate"><span class="pre">None</span></code> was deprecated in Python
2.4, so this completes the removal of the feature.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pkgutil.html#module-pkgutil" title="pkgutil: Utilities for the import system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pkgutil</span></code></a> module, containing various utility functions for finding
packages, was enhanced to support PEP 302’s import hooks and now also works for
packages stored in ZIP-format archives. (Contributed by Phillip J. Eby.)</p>
</li>
<li><p class="first">The pybench benchmark suite by Marc-André Lemburg is now included in the
<code class="file docutils literal notranslate"><span class="pre">Tools/pybench</span></code> directory.  The pybench suite is an improvement on the
commonly used <code class="file docutils literal notranslate"><span class="pre">pystone.py</span></code> program because pybench provides a more
detailed measurement of the interpreter’s speed.  It times particular operations
such as function calls, tuple slicing, method lookups, and numeric operations,
instead of performing many different operations and reducing the result to a
single number as <code class="file docutils literal notranslate"><span class="pre">pystone.py</span></code> does.</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module now uses version 2.0 of the Expat parser.
(Contributed by Trent Mick.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> class provided by the <a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module gained two new
methods.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> blocks until all items in the queue have been retrieved
and all processing work on the items  have been completed.  Worker threads call
the other new method,  <code class="xref py py-meth docutils literal notranslate"><span class="pre">task_done()</span></code>, to signal that processing for an item
has been completed.  (Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The old <code class="xref py py-mod docutils literal notranslate"><span class="pre">regex</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">regsub</span></code> modules, which have been  deprecated
ever since Python 2.0, have finally been deleted.   Other deleted modules:
<code class="xref py py-mod docutils literal notranslate"><span class="pre">statcache</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">tzparse</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">whrandom</span></code>.</p>
</li>
<li><p class="first">Also deleted: the <code class="file docutils literal notranslate"><span class="pre">lib-old</span></code> directory, which includes ancient modules
such as <code class="xref py py-mod docutils literal notranslate"><span class="pre">dircmp</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">ni</span></code>, was removed.  <code class="file docutils literal notranslate"><span class="pre">lib-old</span></code> wasn’t on the
default <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, so unless your programs explicitly added the directory to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, this removal shouldn’t affect your code.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module is no longer  dependent on importing the
<a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">readline</span></code></a> module and therefore now works on non-Unix platforms. (Patch
from Robert Kiendl.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> and <a class="reference internal" href="../library/docxmlrpcserver.html#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a>  classes now have a
<code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> attribute that constrains XML-RPC operations to a limited set
of URL paths; the default is to allow only <code class="docutils literal notranslate"><span class="pre">'/'</span></code> and <code class="docutils literal notranslate"><span class="pre">'/RPC2'</span></code>.  Setting
<code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> or an empty tuple disables  this path checking.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now supports <code class="xref py py-const docutils literal notranslate"><span class="pre">AF_NETLINK</span></code> sockets on Linux,
thanks to a patch from Philippe Biondi.   Netlink sockets are a Linux-specific
mechanism for communications between a user-space process and kernel code; an
introductory  article about them is at <a class="reference external" href="https://www.linuxjournal.com/article/7356">https://www.linuxjournal.com/article/7356</a>.
In Python code, netlink addresses are represented as a tuple of 2 integers,
<code class="docutils literal notranslate"><span class="pre">(pid,</span> <span class="pre">group_mask)</span></code>.</p>
<p>Two new methods on socket objects, <code class="docutils literal notranslate"><span class="pre">recv_into(buffer)</span></code> and
<code class="docutils literal notranslate"><span class="pre">recvfrom_into(buffer)</span></code>, store the received data in an object  that
supports the buffer protocol instead of returning the data as a string.  This
means you can put the data directly into an array or a memory-mapped file.</p>
<p>Socket objects also gained <code class="xref py py-meth docutils literal notranslate"><span class="pre">getfamily()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">gettype()</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getproto()</span></code> accessor methods to retrieve the family, type, and protocol
values for the socket.</p>
</li>
<li><p class="first">New module: the <a class="reference internal" href="../library/spwd.html#module-spwd" title="spwd: The shadow password database (getspnam() and friends). (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">spwd</span></code></a> module provides functions for accessing the shadow
password database on systems that support  shadow passwords.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> is now faster because it  compiles format strings into
<code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects with <code class="xref py py-meth docutils literal notranslate"><span class="pre">pack()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">unpack()</span></code> methods.  This is
similar to how the <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module lets you create compiled regular expression
objects.  You can still use the module-level  <code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code>
functions; they’ll create  <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects and cache them.  Or you can
use  <code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> instances directly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">Struct</span><span class="p">(</span><span class="s1">&#39;ih3s&#39;</span><span class="p">)</span>

<span class="n">data</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">pack</span><span class="p">(</span><span class="mi">1972</span><span class="p">,</span> <span class="mi">187</span><span class="p">,</span> <span class="s1">&#39;abc&#39;</span><span class="p">)</span>
<span class="n">year</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">name</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also pack and unpack data to and from buffer objects directly using the
<code class="docutils literal notranslate"><span class="pre">pack_into(buffer,</span> <span class="pre">offset,</span> <span class="pre">v1,</span> <span class="pre">v2,</span> <span class="pre">...)</span></code> and <code class="docutils literal notranslate"><span class="pre">unpack_from(buffer,</span>
<span class="pre">offset)</span></code> methods.  This lets you store data directly into an array or a
memory-mapped file.</p>
<p>(<code class="xref py py-class docutils literal notranslate"><span class="pre">Struct</span></code> objects were implemented by Bob Ippolito at the NeedForSpeed
sprint.  Support for buffer objects was added by Martin Blais, also at the
NeedForSpeed sprint.)</p>
</li>
<li><p class="first">The Python developers switched from CVS to Subversion during the 2.5
development process.  Information about the exact build version is available as
the <code class="docutils literal notranslate"><span class="pre">sys.subversion</span></code> variable, a 3-tuple of <code class="docutils literal notranslate"><span class="pre">(interpreter-name,</span> <span class="pre">branch-name,</span>
<span class="pre">revision-range)</span></code>.  For example, at the time of writing my copy of 2.5 was
reporting <code class="docutils literal notranslate"><span class="pre">('CPython',</span> <span class="pre">'trunk',</span> <span class="pre">'45313:45315')</span></code>.</p>
<p>This information is also available to C extensions via the
<a class="reference internal" href="../c-api/init.html#c.Py_GetBuildInfo" title="Py_GetBuildInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetBuildInfo()</span></code></a> function that returns a  string of build information
like this: <code class="docutils literal notranslate"><span class="pre">&quot;trunk:45355:45356M,</span> <span class="pre">Apr</span> <span class="pre">13</span> <span class="pre">2006,</span> <span class="pre">07:42:19&quot;</span></code>.   (Contributed by
Barry Warsaw.)</p>
</li>
<li><p class="first">Another new function, <a class="reference internal" href="../library/sys.html#sys._current_frames" title="sys._current_frames"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys._current_frames()</span></code></a>, returns the current stack
frames for all running threads as a dictionary mapping thread identifiers to the
topmost stack frame currently active in that thread at the time the function is
called.  (Contributed by Tim Peters.)</p>
</li>
<li><p class="first">The <code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code> class in the <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module now has an
<code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code> method that extracts all members from the archive into the
current working directory.  It’s also possible to set a different directory as
the extraction target, and to unpack only a subset of the archive’s members.</p>
<p>The compression used for a tarfile opened in stream mode can now be autodetected
using the mode <code class="docutils literal notranslate"><span class="pre">'r|*'</span></code>. (Contributed by Lars Gustäbel.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module now lets you set the stack size used when new
threads are created. The <code class="docutils literal notranslate"><span class="pre">stack_size([*size*])</span></code> function returns the
currently configured stack size, and supplying the optional <em>size</em> parameter
sets a new value.  Not all platforms support changing the stack size, but
Windows, POSIX threading, and OS/2 all do. (Contributed by Andrew MacIntyre.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module has been updated to use version 4.1.0 of the
Unicode character database.  Version 3.2.0 is required  by some specifications,
so it’s still available as  <a class="reference internal" href="../library/unicodedata.html#unicodedata.ucd_3_2_0" title="unicodedata.ucd_3_2_0"><code class="xref py py-attr docutils literal notranslate"><span class="pre">unicodedata.ucd_3_2_0</span></code></a>.</p>
</li>
<li><p class="first">New module: the  <a class="reference internal" href="../library/uuid.html#module-uuid" title="uuid: UUID objects (universally unique identifiers) according to RFC 4122"><code class="xref py py-mod docutils literal notranslate"><span class="pre">uuid</span></code></a> module generates  universally unique identifiers
(UUIDs) according to <span class="target" id="index-19"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a>.  The RFC defines several different UUID
versions that are generated from a starting string, from system properties, or
purely randomly.  This module contains a <code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code> class and  functions
named <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid1()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid3()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid4()</span></code>,  and  <code class="xref py py-func docutils literal notranslate"><span class="pre">uuid5()</span></code> to
generate different versions of UUID.  (Version 2 UUIDs  are not specified in
<span class="target" id="index-20"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc4122.html"><strong>RFC 4122</strong></a> and are not supported by this module.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">uuid</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID based on the host ID and current time</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid1</span><span class="p">()</span>
<span class="go">UUID(&#39;a8098c1a-f86e-11da-bd1a-00112444be1e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using an MD5 hash of a namespace UUID and a name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid3</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;6fa459ea-ee8a-3ca4-894e-db77e160355e&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a random UUID</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid4</span><span class="p">()</span>
<span class="go">UUID(&#39;16fd2706-8baf-433b-82eb-8c7fada847da&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># make a UUID using a SHA-1 hash of a namespace UUID and a name</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">uuid</span><span class="o">.</span><span class="n">uuid5</span><span class="p">(</span><span class="n">uuid</span><span class="o">.</span><span class="n">NAMESPACE_DNS</span><span class="p">,</span> <span class="s1">&#39;python.org&#39;</span><span class="p">)</span>
<span class="go">UUID(&#39;886313e1-3b8a-5372-9b90-0c9aee199e5d&#39;)</span>
</pre></div>
</div>
<p>(Contributed by Ka-Ping Yee.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code> types gained new methods for iterating over the
weak references contained in the dictionary.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeyrefs()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keyrefs()</span></code> methods were added to <code class="xref py py-class docutils literal notranslate"><span class="pre">WeakKeyDictionary</span></code>, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">itervaluerefs()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">valuerefs()</span></code> were added to
<code class="xref py py-class docutils literal notranslate"><span class="pre">WeakValueDictionary</span></code>.  (Contributed by Fred L. Drake, Jr.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/webbrowser.html#module-webbrowser" title="webbrowser: Easy-to-use controller for Web browsers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">webbrowser</span></code></a> module received a number of enhancements. It’s now
usable as a script with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">webbrowser</span></code>, taking a URL as the argument;
there are a number of switches  to control the behaviour (<code class="xref std std-option docutils literal notranslate"><span class="pre">-n</span></code> for a new
browser window,  <code class="xref std std-option docutils literal notranslate"><span class="pre">-t</span></code> for a new tab).  New module-level functions,
<code class="xref py py-func docutils literal notranslate"><span class="pre">open_new()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">open_new_tab()</span></code>, were added  to support this.  The
module’s <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function supports an additional feature, an <em>autoraise</em>
parameter that signals whether to raise the open window when possible. A number
of additional browsers were added to the supported list such as Firefox, Opera,
Konqueror, and elinks.  (Contributed by Oleg Broytmann and Georg Brandl.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module now supports returning  <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> objects
for the XML-RPC date type.  Supply  <code class="docutils literal notranslate"><span class="pre">use_datetime=True</span></code> to the <code class="xref py py-func docutils literal notranslate"><span class="pre">loads()</span></code>
function or the <code class="xref py py-class docutils literal notranslate"><span class="pre">Unmarshaller</span></code> class to enable this feature. (Contributed
by Skip Montanaro.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module now supports the ZIP64 version of the  format,
meaning that a .zip archive can now be larger than 4 GiB and can contain
individual files larger than 4 GiB.  (Contributed by Ronald Oussoren.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Compress</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Decompress</span></code> objects now
support a <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a> method that makes a copy of the  object’s internal state
and returns a new  <code class="xref py py-class docutils literal notranslate"><span class="pre">Compress</span></code> or <code class="xref py py-class docutils literal notranslate"><span class="pre">Decompress</span></code> object.
(Contributed by Chris AtLee.)</p>
</li>
</ul>
<div class="section" id="the-ctypes-package">
<span id="module-ctypes"></span><h3>The ctypes package<a class="headerlink" href="#the-ctypes-package" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> package, written by Thomas Heller, has been added  to the
standard library.  <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> lets you call arbitrary functions  in shared
libraries or DLLs.  Long-time users may remember the <a class="reference internal" href="../library/dl.html#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a> module, which
provides functions for loading shared libraries and calling functions in them.
The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> package is much fancier.</p>
<p>To load a shared library or DLL, you must create an instance of the
<code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code> class and provide the name or path of the shared library or DLL.
Once that’s done, you can call arbitrary functions by accessing them as
attributes of the <code class="xref py py-class docutils literal notranslate"><span class="pre">CDLL</span></code> object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>

<span class="n">libc</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">CDLL</span><span class="p">(</span><span class="s1">&#39;libc.so.6&#39;</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">libc</span><span class="o">.</span><span class="n">printf</span><span class="p">(</span><span class="s2">&quot;Line of output</span><span class="se">\n</span><span class="s2">&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Type constructors for the various C types are provided: <code class="xref py py-func docutils literal notranslate"><span class="pre">c_int()</span></code>,
<code class="xref py py-func docutils literal notranslate"><span class="pre">c_float()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">c_double()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">c_char_p()</span></code> (equivalent to <code class="xref c c-type docutils literal notranslate"><span class="pre">char</span>
<span class="pre">*</span></code>), and so forth.  Unlike Python’s types, the C versions are all mutable; you
can assign to their <code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code> attribute to change the wrapped value.  Python
integers and strings will be automatically converted to the corresponding C
types, but for other types you  must call the correct type constructor.  (And I
mean <em>must</em>;  getting it wrong will often result in the interpreter crashing
with a segmentation fault.)</p>
<p>You shouldn’t use <code class="xref py py-func docutils literal notranslate"><span class="pre">c_char_p()</span></code> with a Python string when the C function will
be modifying the memory area, because Python strings are  supposed to be
immutable; breaking this rule will cause puzzling bugs.  When you need a
modifiable memory area, use <code class="xref py py-func docutils literal notranslate"><span class="pre">create_string_buffer()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">s</span> <span class="o">=</span> <span class="s2">&quot;this is a string&quot;</span>
<span class="n">buf</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">create_string_buffer</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
<span class="n">libc</span><span class="o">.</span><span class="n">strfry</span><span class="p">(</span><span class="n">buf</span><span class="p">)</span>
</pre></div>
</div>
<p>C functions are assumed to return integers, but you can set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">restype</span></code>
attribute of the function object to  change this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="p">(</span><span class="s1">&#39;2.71828&#39;</span><span class="p">)</span>
<span class="go">-1783957616</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="o">.</span><span class="n">restype</span> <span class="o">=</span> <span class="n">ctypes</span><span class="o">.</span><span class="n">c_double</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">libc</span><span class="o">.</span><span class="n">atof</span><span class="p">(</span><span class="s1">&#39;2.71828&#39;</span><span class="p">)</span>
<span class="go">2.71828</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> also provides a wrapper for Python’s C API  as the
<code class="docutils literal notranslate"><span class="pre">ctypes.pythonapi</span></code> object.  This object does <em>not</em>  release the global
interpreter lock before calling a function, because the lock must be held when
calling into the interpreter’s code.   There’s a <code class="xref py py-class docutils literal notranslate"><span class="pre">py_object()</span></code> type
constructor that will create a  <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyObject</span> <span class="pre">*</span></code></a> pointer.  A simple usage:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ctypes</span>

<span class="n">d</span> <span class="o">=</span> <span class="p">{}</span>
<span class="n">ctypes</span><span class="o">.</span><span class="n">pythonapi</span><span class="o">.</span><span class="n">PyObject_SetItem</span><span class="p">(</span><span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="n">d</span><span class="p">),</span>
          <span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="s2">&quot;abc&quot;</span><span class="p">),</span>  <span class="n">ctypes</span><span class="o">.</span><span class="n">py_object</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span>
<span class="c1"># d is now {&#39;abc&#39;, 1}.</span>
</pre></div>
</div>
<p>Don’t forget to use <code class="xref py py-class docutils literal notranslate"><span class="pre">py_object()</span></code>; if it’s omitted you end  up with a
segmentation fault.</p>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> has been around for a while, but people still write  and
distribution hand-coded extension modules because you can’t rely on
<a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> being present. Perhaps developers will begin to write  Python
wrappers atop a library accessed through <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> instead of extension
modules, now that <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> is included with core Python.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference external" href="http://starship.python.net/crew/theller/ctypes/">http://starship.python.net/crew/theller/ctypes/</a></dt>
<dd>The ctypes web page, with a tutorial, reference, and FAQ.</dd>
</dl>
<p class="last">The documentation  for the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module.</p>
</div>
</div>
<div class="section" id="the-elementtree-package">
<span id="module-etree"></span><h3>The ElementTree package<a class="headerlink" href="#the-elementtree-package" title="Permalink to this headline">¶</a></h3>
<p>A subset of Fredrik Lundh’s ElementTree library for processing XML has been
added to the standard library as <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>.  The available modules are
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementTree</span></code>, <code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementPath</span></code>, and <code class="xref py py-mod docutils literal notranslate"><span class="pre">ElementInclude</span></code> from
ElementTree 1.2.6.    The <code class="xref py py-mod docutils literal notranslate"><span class="pre">cElementTree</span></code> accelerator module is also
included.</p>
<p>The rest of this section will provide a brief overview of using ElementTree.
Full documentation for ElementTree is available at
<a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a>.</p>
<p>ElementTree represents an XML document as a tree of element nodes. The text
content of the document is stored as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">text</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">tail</span></code>
attributes of  (This is one of the major differences between ElementTree and
the Document Object Model; in the DOM there are many different types of node,
including <code class="xref py py-class docutils literal notranslate"><span class="pre">TextNode</span></code>.)</p>
<p>The most commonly used parsing function is <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code>, that takes either a
string (assumed to contain a filename) or a file-like object and returns an
<code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code> instance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.etree</span> <span class="k">import</span> <span class="n">ElementTree</span> <span class="k">as</span> <span class="n">ET</span>

<span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s1">&#39;ex-1.xml&#39;</span><span class="p">)</span>

<span class="n">feed</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span>
          <span class="s1">&#39;http://planet.python.org/rss10.xml&#39;</span><span class="p">)</span>
<span class="n">tree</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="n">feed</span><span class="p">)</span>
</pre></div>
</div>
<p>Once you have an <code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code> instance, you can call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">getroot()</span></code>
method to get the root <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> node.</p>
<p>There’s also an <code class="xref py py-func docutils literal notranslate"><span class="pre">XML()</span></code> function that takes a string literal and returns an
<code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> node (not an <code class="xref py py-class docutils literal notranslate"><span class="pre">ElementTree</span></code>).   This function provides a
tidy way to incorporate XML fragments, approaching the convenience of an XML
literal:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">svg</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;svg width=&quot;10px&quot; version=&quot;1.0&quot;&gt;</span>
<span class="s2">             &lt;/svg&gt;&quot;&quot;&quot;</span><span class="p">)</span>
<span class="n">svg</span><span class="o">.</span><span class="n">set</span><span class="p">(</span><span class="s1">&#39;height&#39;</span><span class="p">,</span> <span class="s1">&#39;320px&#39;</span><span class="p">)</span>
<span class="n">svg</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">elem1</span><span class="p">)</span>
</pre></div>
</div>
<p>Each XML element supports some dictionary-like and some list-like access
methods.  Dictionary-like operations are used to access attribute values, and
list-like operations are used to access child nodes.</p>
<table border="1" class="docutils">
<colgroup>
<col width="41%" />
<col width="59%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Operation</th>
<th class="head">Result</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">elem[n]</span></code></td>
<td>Returns n’th child element.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">elem[m:n]</span></code></td>
<td>Returns list of m’th through n’th child
elements.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">len(elem)</span></code></td>
<td>Returns number of child elements.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">list(elem)</span></code></td>
<td>Returns list of child elements.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">elem.append(elem2)</span></code></td>
<td>Adds <em>elem2</em> as a child.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">elem.insert(index,</span> <span class="pre">elem2)</span></code></td>
<td>Inserts <em>elem2</em> at the specified location.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">elem[n]</span></code></td>
<td>Deletes n’th child element.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">elem.keys()</span></code></td>
<td>Returns list of attribute names.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">elem.get(name)</span></code></td>
<td>Returns value of attribute <em>name</em>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">elem.set(name,</span> <span class="pre">value)</span></code></td>
<td>Sets new value for attribute <em>name</em>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">elem.attrib</span></code></td>
<td>Retrieves the dictionary containing
attributes.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">elem.attrib[name]</span></code></td>
<td>Deletes attribute <em>name</em>.</td>
</tr>
</tbody>
</table>
<p>Comments and processing instructions are also represented as <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code>
nodes.  To check if a node is a comment or processing instructions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="n">elem</span><span class="o">.</span><span class="n">tag</span> <span class="ow">is</span> <span class="n">ET</span><span class="o">.</span><span class="n">Comment</span><span class="p">:</span>
    <span class="o">...</span>
<span class="k">elif</span> <span class="n">elem</span><span class="o">.</span><span class="n">tag</span> <span class="ow">is</span> <span class="n">ET</span><span class="o">.</span><span class="n">ProcessingInstruction</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>To generate XML output, you should call the <code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code> method.
Like <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code>, it can take either a string or a file-like object:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Encoding is US-ASCII</span>
<span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">)</span>

<span class="c1"># Encoding is UTF-8</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;output.xml&#39;</span><span class="p">,</span> <span class="s1">&#39;w&#39;</span><span class="p">)</span>
<span class="n">tree</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>(Caution: the default encoding used for output is ASCII.  For general XML work,
where an element’s name may contain arbitrary Unicode characters, ASCII isn’t a
very useful encoding because it will raise an exception if an element’s name
contains any characters with values greater than 127.  Therefore, it’s best to
specify a different encoding such as UTF-8 that can handle any Unicode
character.)</p>
<p>This section is only a partial description of the ElementTree interfaces. Please
read the package’s official documentation for more details.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://effbot.org/zone/element-index.htm">http://effbot.org/zone/element-index.htm</a></dt>
<dd>Official documentation for ElementTree.</dd>
</dl>
</div>
</div>
<div class="section" id="the-hashlib-package">
<span id="module-hashlib"></span><h3>The hashlib package<a class="headerlink" href="#the-hashlib-package" title="Permalink to this headline">¶</a></h3>
<p>A new <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module, written by Gregory P. Smith,  has been added to
replace the <a class="reference internal" href="../library/md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> and <a class="reference internal" href="../library/sha.html#module-sha" title="sha: NIST's secure hash algorithm, SHA. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code></a> modules.  <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> adds support for
additional secure hashes (SHA-224, SHA-256, SHA-384, and SHA-512). When
available, the module uses OpenSSL for fast platform optimized implementations
of algorithms.</p>
<p>The old <a class="reference internal" href="../library/md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> and <a class="reference internal" href="../library/sha.html#module-sha" title="sha: NIST's secure hash algorithm, SHA. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code></a> modules still exist as wrappers around hashlib
to preserve backwards compatibility.  The new module’s interface is very close
to that of the old modules, but not identical. The most significant difference
is that the constructor functions for creating new hashing objects are named
differently.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Old versions</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">md5</span><span class="o">.</span><span class="n">md5</span><span class="p">()</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">md5</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>

<span class="c1"># New version</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">md5</span><span class="p">()</span>

<span class="c1"># Old versions</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">sha</span><span class="o">.</span><span class="n">sha</span><span class="p">()</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">sha</span><span class="o">.</span><span class="n">new</span><span class="p">()</span>

<span class="c1"># New version</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha1</span><span class="p">()</span>

<span class="c1"># Hash that weren&#39;t previously available</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha224</span><span class="p">()</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha256</span><span class="p">()</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha384</span><span class="p">()</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">sha512</span><span class="p">()</span>

<span class="c1"># Alternative form</span>
<span class="n">h</span> <span class="o">=</span> <span class="n">hashlib</span><span class="o">.</span><span class="n">new</span><span class="p">(</span><span class="s1">&#39;md5&#39;</span><span class="p">)</span>          <span class="c1"># Provide algorithm as a string</span>
</pre></div>
</div>
<p>Once a hash object has been created, its methods are the same as before:
<code class="docutils literal notranslate"><span class="pre">update(string)</span></code> hashes the specified string into the  current digest
state, <code class="xref py py-meth docutils literal notranslate"><span class="pre">digest()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">hexdigest()</span></code> return the digest value as a binary
string or a string of hex digits, and <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a> returns a new hashing object
with the same digest state.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The documentation  for the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module.</p>
</div>
</div>
<div class="section" id="the-sqlite3-package">
<span id="module-sqlite"></span><h3>The sqlite3 package<a class="headerlink" href="#the-sqlite3-package" title="Permalink to this headline">¶</a></h3>
<p>The pysqlite module (<a class="reference external" href="http://www.pysqlite.org">http://www.pysqlite.org</a>), a wrapper for the SQLite embedded
database, has been added to the standard library under the package name
<a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a>.</p>
<p>SQLite is a C library that provides a lightweight disk-based database that
doesn’t require a separate server process and allows accessing the database
using a nonstandard variant of the SQL query language. Some applications can use
SQLite for internal data storage.  It’s also possible to prototype an
application using SQLite and then port the code to a larger database such as
PostgreSQL or Oracle.</p>
<p>pysqlite was written by Gerhard Häring and provides a SQL interface compliant
with the DB-API 2.0 specification described by <span class="target" id="index-21"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>.</p>
<p>If you’re compiling the Python source yourself, note that the source tree
doesn’t include the SQLite code, only the wrapper module. You’ll need to have
the SQLite libraries and headers installed before compiling Python, and the
build process will compile the module when the necessary headers are available.</p>
<p>To use the module, you must first create a <a class="reference internal" href="../library/multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a> object that
represents the database.  Here the data will be stored in the
<code class="file docutils literal notranslate"><span class="pre">/tmp/example</span></code> file:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">conn</span> <span class="o">=</span> <span class="n">sqlite3</span><span class="o">.</span><span class="n">connect</span><span class="p">(</span><span class="s1">&#39;/tmp/example&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also supply the special name <code class="docutils literal notranslate"><span class="pre">:memory:</span></code> to create a database in RAM.</p>
<p>Once you have a <a class="reference internal" href="../library/multiprocessing.html#Connection" title="Connection"><code class="xref py py-class docutils literal notranslate"><span class="pre">Connection</span></code></a>, you can create a <code class="xref py py-class docutils literal notranslate"><span class="pre">Cursor</span></code>  object
and call its <code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code> method to perform SQL commands:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>

<span class="c1"># Create table</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;&#39;&#39;create table stocks</span>
<span class="s1">(date text, trans text, symbol text,</span>
<span class="s1"> qty real, price real)&#39;&#39;&#39;</span><span class="p">)</span>

<span class="c1"># Insert a row of data</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;insert into stocks</span>
<span class="s2">          values (&#39;2006-01-05&#39;,&#39;BUY&#39;,&#39;RHAT&#39;,100,35.14)&quot;&quot;&quot;</span><span class="p">)</span>
</pre></div>
</div>
<p>Usually your SQL operations will need to use values from Python variables.  You
shouldn’t assemble your query using Python’s string operations because doing so
is insecure; it makes your program vulnerable to an SQL injection attack.</p>
<p>Instead, use the DB-API’s parameter substitution.  Put <code class="docutils literal notranslate"><span class="pre">?</span></code> as a placeholder
wherever you want to use a value, and then provide a tuple of values as the
second argument to the cursor’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">execute()</span></code> method.  (Other database modules
may use a different placeholder, such as <code class="docutils literal notranslate"><span class="pre">%s</span></code> or <code class="docutils literal notranslate"><span class="pre">:1</span></code>.) For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Never do this -- insecure!</span>
<span class="n">symbol</span> <span class="o">=</span> <span class="s1">&#39;IBM&#39;</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s2">&quot;... where symbol = &#39;</span><span class="si">%s</span><span class="s2">&#39;&quot;</span> <span class="o">%</span> <span class="n">symbol</span><span class="p">)</span>

<span class="c1"># Do this instead</span>
<span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="n">symbol</span><span class="p">,)</span>
<span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select * from stocks where symbol=?&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>

<span class="c1"># Larger example</span>
<span class="k">for</span> <span class="n">t</span> <span class="ow">in</span> <span class="p">((</span><span class="s1">&#39;2006-03-28&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">45.00</span><span class="p">),</span>
          <span class="p">(</span><span class="s1">&#39;2006-04-05&#39;</span><span class="p">,</span> <span class="s1">&#39;BUY&#39;</span><span class="p">,</span> <span class="s1">&#39;MSOFT&#39;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mf">72.00</span><span class="p">),</span>
          <span class="p">(</span><span class="s1">&#39;2006-04-06&#39;</span><span class="p">,</span> <span class="s1">&#39;SELL&#39;</span><span class="p">,</span> <span class="s1">&#39;IBM&#39;</span><span class="p">,</span> <span class="mi">500</span><span class="p">,</span> <span class="mf">53.00</span><span class="p">),</span>
         <span class="p">):</span>
    <span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into stocks values (?,?,?,?,?)&#39;</span><span class="p">,</span> <span class="n">t</span><span class="p">)</span>
</pre></div>
</div>
<p>To retrieve data after executing a SELECT statement, you can either  treat the
cursor as an iterator, call the cursor’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchone()</span></code> method to retrieve a
single matching row,  or call <code class="xref py py-meth docutils literal notranslate"><span class="pre">fetchall()</span></code> to get a list of the matching
rows.</p>
<p>This example uses the iterator form:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">conn</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;select * from stocks order by price&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">c</span><span class="p">:</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="n">row</span>
<span class="gp">...</span>
<span class="go">(u&#39;2006-01-05&#39;, u&#39;BUY&#39;, u&#39;RHAT&#39;, 100, 35.140000000000001)</span>
<span class="go">(u&#39;2006-03-28&#39;, u&#39;BUY&#39;, u&#39;IBM&#39;, 1000, 45.0)</span>
<span class="go">(u&#39;2006-04-06&#39;, u&#39;SELL&#39;, u&#39;IBM&#39;, 500, 53.0)</span>
<span class="go">(u&#39;2006-04-05&#39;, u&#39;BUY&#39;, u&#39;MSOFT&#39;, 1000, 72.0)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>For more information about the SQL dialect supported by SQLite, see
<a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><a class="reference external" href="http://www.pysqlite.org">http://www.pysqlite.org</a></dt>
<dd>The pysqlite web page.</dd>
<dt><a class="reference external" href="https://www.sqlite.org">https://www.sqlite.org</a></dt>
<dd>The SQLite web page; the documentation describes the syntax and the available
data types for the supported SQL dialect.</dd>
</dl>
<p>The documentation  for the <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module.</p>
<dl class="last docutils">
<dt><span class="target" id="index-22"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a> - Database API Specification 2.0</dt>
<dd>PEP written by Marc-André Lemburg.</dd>
</dl>
</div>
</div>
<div class="section" id="the-wsgiref-package">
<span id="module-wsgiref"></span><h3>The wsgiref package<a class="headerlink" href="#the-wsgiref-package" title="Permalink to this headline">¶</a></h3>
<p>The Web Server Gateway Interface (WSGI) v1.0 defines a standard interface
between web servers and Python web applications and is described in <span class="target" id="index-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a>.
The <a class="reference internal" href="../library/wsgiref.html#module-wsgiref" title="wsgiref: WSGI Utilities and Reference Implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">wsgiref</span></code></a> package is a reference implementation of the WSGI
specification.</p>
<p>The package includes a basic HTTP server that will run a WSGI application; this
server is useful for debugging but isn’t intended for  production use.  Setting
up a server takes only a few lines of code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">wsgiref</span> <span class="k">import</span> <span class="n">simple_server</span>

<span class="n">wsgi_app</span> <span class="o">=</span> <span class="o">...</span>

<span class="n">host</span> <span class="o">=</span> <span class="s1">&#39;&#39;</span>
<span class="n">port</span> <span class="o">=</span> <span class="mi">8000</span>
<span class="n">httpd</span> <span class="o">=</span> <span class="n">simple_server</span><span class="o">.</span><span class="n">make_server</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">,</span> <span class="n">wsgi_app</span><span class="p">)</span>
<span class="n">httpd</span><span class="o">.</span><span class="n">serve_forever</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.wsgi.org">http://www.wsgi.org</a></dt>
<dd>A central web site for WSGI-related resources.</dd>
<dt><span class="target" id="index-24"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0333"><strong>PEP 333</strong></a> - Python Web Server Gateway Interface v1.0</dt>
<dd>PEP written by Phillip J. Eby.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<span id="build-api"></span><h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
<p>Changes to Python’s build process and to the C API include:</p>
<ul>
<li><p class="first">The Python source tree was converted from CVS to Subversion,  in a complex
migration procedure that was supervised and flawlessly carried out by Martin von
Löwis.  The procedure was developed as <span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0347"><strong>PEP 347</strong></a>.</p>
</li>
<li><p class="first">Coverity, a company that markets a source code analysis tool called Prevent,
provided the results of their examination of the Python source code.  The
analysis found about 60 bugs that  were quickly fixed.  Many of the bugs were
refcounting problems, often occurring in error-handling code.  See
<a class="reference external" href="https://scan.coverity.com">https://scan.coverity.com</a> for the statistics.</p>
</li>
<li><p class="first">The largest change to the C API came from <span class="target" id="index-26"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0353"><strong>PEP 353</strong></a>, which modifies the
interpreter to use a <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code> type definition instead of
<code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code>.  See the earlier section <a class="reference internal" href="#pep-353"><span class="std std-ref">PEP 353: Using ssize_t as the index type</span></a> for a discussion of this
change.</p>
</li>
<li><p class="first">The design of the bytecode compiler has changed a great deal,  no longer
generating bytecode by traversing the parse tree.  Instead the parse tree is
converted to an abstract syntax tree (or AST), and it is  the abstract syntax
tree that’s traversed to produce the bytecode.</p>
<p>It’s possible for Python code to obtain AST objects by using the
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in and specifying <code class="docutils literal notranslate"><span class="pre">_ast.PyCF_ONLY_AST</span></code> as the value of
the  <em>flags</em> parameter:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">_ast</span> <span class="k">import</span> <span class="n">PyCF_ONLY_AST</span>
<span class="n">ast</span> <span class="o">=</span> <span class="nb">compile</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;a=0</span>
<span class="s2">for i in range(10):</span>
<span class="s2">    a += i</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">,</span> <span class="s2">&quot;&lt;string&gt;&quot;</span><span class="p">,</span> <span class="s1">&#39;exec&#39;</span><span class="p">,</span> <span class="n">PyCF_ONLY_AST</span><span class="p">)</span>

<span class="n">assignment</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">body</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="n">for_loop</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">body</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
</pre></div>
</div>
<p>No official documentation has been written for the AST code yet, but <span class="target" id="index-27"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0339"><strong>PEP 339</strong></a>
discusses the design.  To start learning about the code, read the definition of
the various AST nodes in <code class="file docutils literal notranslate"><span class="pre">Parser/Python.asdl</span></code>.  A Python script reads this
file and generates a set of C structure definitions in
<code class="file docutils literal notranslate"><span class="pre">Include/Python-ast.h</span></code>.  The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_ASTFromString()</span></code> and
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyParser_ASTFromFile()</span></code>, defined in <code class="file docutils literal notranslate"><span class="pre">Include/pythonrun.h</span></code>, take
Python source as input and return the root of an AST representing the contents.
This AST can then be turned into a code object by <code class="xref c c-func docutils literal notranslate"><span class="pre">PyAST_Compile()</span></code>.  For
more information, read the source code, and then ask questions on python-dev.</p>
<p>The AST code was developed under Jeremy Hylton’s management, and implemented by
(in alphabetical order) Brett Cannon, Nick Coghlan, Grant Edwards, John
Ehresman, Kurt Kaiser, Neal Norwitz, Tim Peters, Armin Rigo, and Neil
Schemenauer, plus the participants in a number of AST sprints at conferences
such as PyCon.</p>
</li>
<li><p class="first">Evan Jones’s patch to obmalloc, first described in a talk at PyCon DC 2005,
was applied.  Python 2.4 allocated small objects in 256K-sized arenas, but never
freed arenas.  With this patch, Python will free arenas when they’re empty.  The
net effect is that on some platforms, when you allocate many objects, Python’s
memory usage may actually drop when you delete them and the memory may be
returned to the operating system.  (Implemented by Evan Jones, and reworked by
Tim Peters.)</p>
<p>Note that this change means extension modules must be more careful when
allocating memory.  Python’s API has many different functions for allocating
memory that are grouped into families.  For example, <a class="reference internal" href="../c-api/memory.html#c.PyMem_Malloc" title="PyMem_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Malloc()</span></code></a>,
<a class="reference internal" href="../c-api/memory.html#c.PyMem_Realloc" title="PyMem_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Realloc()</span></code></a>, and <a class="reference internal" href="../c-api/memory.html#c.PyMem_Free" title="PyMem_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_Free()</span></code></a> are one family that allocates
raw memory, while <a class="reference internal" href="../c-api/memory.html#c.PyObject_Malloc" title="PyObject_Malloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Malloc()</span></code></a>, <a class="reference internal" href="../c-api/memory.html#c.PyObject_Realloc" title="PyObject_Realloc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Realloc()</span></code></a>, and
<a class="reference internal" href="../c-api/memory.html#c.PyObject_Free" title="PyObject_Free"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_Free()</span></code></a> are another family that’s supposed to be used for
creating Python objects.</p>
<p>Previously these different families all reduced to the platform’s
<code class="xref c c-func docutils literal notranslate"><span class="pre">malloc()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">free()</span></code> functions.  This meant  it didn’t matter if
you got things wrong and allocated memory with the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem()</span></code> function but
freed it with the <a class="reference internal" href="../c-api/structures.html#c.PyObject" title="PyObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject()</span></code></a> function.  With 2.5’s changes to obmalloc,
these families now do different things and mismatches will probably result in a
segfault.  You should carefully test your C extension modules with Python 2.5.</p>
</li>
<li><p class="first">The built-in set types now have an official C API.  Call <a class="reference internal" href="../c-api/set.html#c.PySet_New" title="PySet_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_New()</span></code></a>
and <a class="reference internal" href="../c-api/set.html#c.PyFrozenSet_New" title="PyFrozenSet_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFrozenSet_New()</span></code></a> to create a new set, <a class="reference internal" href="../c-api/set.html#c.PySet_Add" title="PySet_Add"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Add()</span></code></a> and
<a class="reference internal" href="../c-api/set.html#c.PySet_Discard" title="PySet_Discard"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Discard()</span></code></a> to add and remove elements, and <a class="reference internal" href="../c-api/set.html#c.PySet_Contains" title="PySet_Contains"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Contains()</span></code></a>
and <a class="reference internal" href="../c-api/set.html#c.PySet_Size" title="PySet_Size"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySet_Size()</span></code></a> to examine the set’s state. (Contributed by Raymond
Hettinger.)</p>
</li>
<li><p class="first">C code can now obtain information about the exact revision of the Python
interpreter by calling the  <a class="reference internal" href="../c-api/init.html#c.Py_GetBuildInfo" title="Py_GetBuildInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_GetBuildInfo()</span></code></a> function that returns a
string of build information like this: <code class="docutils literal notranslate"><span class="pre">&quot;trunk:45355:45356M,</span> <span class="pre">Apr</span> <span class="pre">13</span> <span class="pre">2006,</span>
<span class="pre">07:42:19&quot;</span></code>.   (Contributed by Barry Warsaw.)</p>
</li>
<li><p class="first">Two new macros can be used to indicate C functions that are local to the
current file so that a faster calling convention can be used.
<code class="docutils literal notranslate"><span class="pre">Py_LOCAL(type)</span></code> declares the function as returning a value of the
specified <em>type</em> and uses a fast-calling qualifier.
<code class="docutils literal notranslate"><span class="pre">Py_LOCAL_INLINE(type)</span></code> does the same thing and also requests the
function be inlined.  If <code class="xref c c-func docutils literal notranslate"><span class="pre">PY_LOCAL_AGGRESSIVE()</span></code> is defined before
<code class="file docutils literal notranslate"><span class="pre">python.h</span></code> is included, a set of more aggressive optimizations are enabled
for the module; you should benchmark the results to find out if these
optimizations actually make the code faster.  (Contributed by Fredrik Lundh at
the NeedForSpeed sprint.)</p>
</li>
<li><p class="first"><code class="docutils literal notranslate"><span class="pre">PyErr_NewException(name,</span> <span class="pre">base,</span> <span class="pre">dict)</span></code> can now accept a tuple of base
classes as its <em>base</em> argument.  (Contributed by Georg Brandl.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Warn" title="PyErr_Warn"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Warn()</span></code></a> function for issuing warnings is now deprecated in
favour of <code class="docutils literal notranslate"><span class="pre">PyErr_WarnEx(category,</span> <span class="pre">message,</span> <span class="pre">stacklevel)</span></code> which lets you
specify the number of stack frames separating this function and the caller.  A
<em>stacklevel</em> of 1 is the function calling <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_WarnEx" title="PyErr_WarnEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_WarnEx()</span></code></a>, 2 is the
function above that, and so forth.  (Added by Neal Norwitz.)</p>
</li>
<li><p class="first">The CPython interpreter is still written in C, but  the code can now be
compiled with a C++ compiler without errors.   (Implemented by Anthony Baxter,
Martin von Löwis, Skip Montanaro.)</p>
</li>
<li><p class="first">The <code class="xref c c-func docutils literal notranslate"><span class="pre">PyRange_New()</span></code> function was removed.  It was never documented, never
used in the core code, and had dangerously lax error checking.  In the unlikely
case that your extensions were using it, you can replace it by something like
the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nb">range</span> <span class="o">=</span> <span class="n">PyObject_CallFunction</span><span class="p">((</span><span class="n">PyObject</span><span class="o">*</span><span class="p">)</span> <span class="o">&amp;</span><span class="n">PyRange_Type</span><span class="p">,</span> <span class="s2">&quot;lll&quot;</span><span class="p">,</span>
                              <span class="n">start</span><span class="p">,</span> <span class="n">stop</span><span class="p">,</span> <span class="n">step</span><span class="p">);</span>
</pre></div>
</div>
</li>
</ul>
<div class="section" id="port-specific-changes">
<span id="ports"></span><h3>Port-Specific Changes<a class="headerlink" href="#port-specific-changes" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>MacOS X (10.3 and higher): dynamic loading of modules now uses the
<code class="xref c c-func docutils literal notranslate"><span class="pre">dlopen()</span></code> function instead of MacOS-specific functions.</li>
<li>MacOS X: an <code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-universalsdk</span></code> switch was added to the
<strong class="program">configure</strong> script that compiles the interpreter as a universal binary
able to run on both PowerPC and Intel processors. (Contributed by Ronald
Oussoren; <a class="reference external" href="https://bugs.python.org/issue2573">bpo-2573</a>.)</li>
<li>Windows: <code class="file docutils literal notranslate"><span class="pre">.dll</span></code> is no longer supported as a filename extension for
extension modules.  <code class="file docutils literal notranslate"><span class="pre">.pyd</span></code> is now the only filename extension that will be
searched for.</li>
</ul>
</div>
</div>
<div class="section" id="porting-to-python-2-5">
<span id="porting"></span><h2>Porting to Python 2.5<a class="headerlink" href="#porting-to-python-2-5" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes that may require changes to your
code:</p>
<ul class="simple">
<li>ASCII is now the default encoding for modules.  It’s now  a syntax error if a
module contains string literals with 8-bit characters but doesn’t have an
encoding declaration.  In Python 2.4 this triggered a warning, not a syntax
error.</li>
<li>Previously, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> attribute of a generator was always a frame
object.  Because of the <span class="target" id="index-28"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0342"><strong>PEP 342</strong></a> changes described in section <a class="reference internal" href="#pep-342"><span class="std std-ref">PEP 342: New Generator Features</span></a>,
it’s now possible for <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_frame</span></code> to be <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
<li>A new warning, <code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeWarning</span></code>, is triggered when  you attempt to
compare a Unicode string and an 8-bit string that can’t be converted to Unicode
using the default ASCII encoding.  Previously such comparisons would raise a
<code class="xref py py-class docutils literal notranslate"><span class="pre">UnicodeDecodeError</span></code> exception.</li>
<li>Library: the <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module is now stricter about multi-line quoted fields.
If your files contain newlines embedded within fields, the input should be split
into lines in a manner which preserves the newline characters.</li>
<li>Library: the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module’s  <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> function’s would
previously  accept any string as long as no more than one %char specifier
appeared.  In Python 2.5, the argument must be exactly one %char specifier with
no surrounding text.</li>
<li>Library: The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> modules no longer accept a
return value of <code class="docutils literal notranslate"><span class="pre">None</span></code> from the <a class="reference internal" href="../library/pickle.html#object.__reduce__" title="object.__reduce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reduce__()</span></code></a> method; the method must
return a tuple of arguments instead.  The modules also no longer accept the
deprecated <em>bin</em> keyword parameter.</li>
<li>Library: The <a class="reference internal" href="../library/simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> and <a class="reference internal" href="../library/docxmlrpcserver.html#module-DocXMLRPCServer" title="DocXMLRPCServer: Self-documenting XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a>  classes now
have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> attribute that constrains XML-RPC operations to a
limited set of URL paths; the default is to allow only <code class="docutils literal notranslate"><span class="pre">'/'</span></code> and <code class="docutils literal notranslate"><span class="pre">'/RPC2'</span></code>.
Setting  <code class="xref py py-attr docutils literal notranslate"><span class="pre">rpc_paths</span></code> to <code class="docutils literal notranslate"><span class="pre">None</span></code> or an empty tuple disables  this path
checking.</li>
<li>C API: Many functions now use <code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code>  instead of <code class="xref c c-type docutils literal notranslate"><span class="pre">int</span></code> to
allow processing more data on 64-bit machines.  Extension code may need to make
the same change to avoid warnings and to support 64-bit machines.  See the
earlier section <a class="reference internal" href="#pep-353"><span class="std std-ref">PEP 353: Using ssize_t as the index type</span></a> for a discussion of this change.</li>
<li>C API:  The obmalloc changes mean that  you must be careful to not mix usage
of the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyMem_*()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_*()</span></code> families of functions. Memory
allocated with  one family’s <code class="xref c c-func docutils literal notranslate"><span class="pre">*_Malloc()</span></code> must be  freed with the
corresponding family’s <code class="xref c c-func docutils literal notranslate"><span class="pre">*_Free()</span></code> function.</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering suggestions,
corrections and assistance with various drafts of this article: Georg Brandl,
Nick Coghlan, Phillip J. Eby, Lars Gustäbel, Raymond Hettinger, Ralf W.
Grosse-Kunstleve, Kent Johnson, Iain Lowe, Martin von Löwis, Fredrik Lundh, Andrew
McNamara, Skip Montanaro, Gustavo Niemeyer, Paul Prescod, James Pryor, Mike
Rovner, Scott Weikart, Barry Warsaw, Thomas Wouters.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.5</a><ul>
<li><a class="reference internal" href="#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
<li><a class="reference internal" href="#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
<li><a class="reference internal" href="#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
<li><a class="reference internal" href="#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
<li><a class="reference internal" href="#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
<li><a class="reference internal" href="#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
<li><a class="reference internal" href="#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
<li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
<li><a class="reference internal" href="#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
<li><a class="reference internal" href="#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
<li><a class="reference internal" href="#the-ctypes-package">The ctypes package</a></li>
<li><a class="reference internal" href="#the-elementtree-package">The ElementTree package</a></li>
<li><a class="reference internal" href="#the-hashlib-package">The hashlib package</a></li>
<li><a class="reference internal" href="#the-sqlite3-package">The sqlite3 package</a></li>
<li><a class="reference internal" href="#the-wsgiref-package">The wsgiref package</a></li>
</ul>
</li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-5">Porting to Python 2.5</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.6.html"
                        title="previous chapter">What’s New in Python 2.6</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.4.html"
                        title="next chapter">What’s New in Python 2.4</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.5.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.4.html" title="What’s New in Python 2.4"
             >next</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��(�(�html/whatsnew/2.6.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.6 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.5" href="2.5.html" />
    <link rel="prev" title="What’s New in Python 2.7" href="2.7.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.6.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.5.html" title="What’s New in Python 2.5"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="2.7.html" title="What’s New in Python 2.7"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-6">
<h1>What’s New in Python 2.6<a class="headerlink" href="#what-s-new-in-python-2-6" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling (amk at amk.ca)</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.6, released on October 1
2008.  The release schedule is described in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0361"><strong>PEP 361</strong></a>.</p>
<p>The major theme of Python 2.6 is preparing the migration path to
Python 3.0, a major redesign of the language.  Whenever possible,
Python 2.6 incorporates new features and syntax from 3.0 while
remaining compatible with existing code by not removing older features
or syntax.  When it’s not possible to do that, Python 2.6 tries to do
what it can, adding compatibility functions in a
<a class="reference internal" href="../library/future_builtins.html#module-future_builtins" title="future_builtins"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code></a> module and a <a class="reference internal" href="../using/cmdline.html#cmdoption-3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code></a> switch to warn about
usages that will become unsupported in 3.0.</p>
<p>Some significant new packages have been added to the standard library,
such as the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> and <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> modules, but
there aren’t many new features that aren’t related to Python 3.0 in
some way.</p>
<p>Python 2.6 also sees a number of improvements and bugfixes throughout
the source.  A search through the change logs finds there were 259
patches applied and 612 bugs fixed between Python 2.5 and 2.6.  Both
figures are likely to be underestimates.</p>
<p>This article doesn’t attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.6. If
you want to understand the rationale for the design and
implementation, refer to the PEP for a particular new feature.
Whenever possible, “What’s New in Python” links to the bug/patch item
for each change.</p>
<div class="section" id="python-3-0">
<h2>Python 3.0<a class="headerlink" href="#python-3-0" title="Permalink to this headline">¶</a></h2>
<p>The development cycle for Python versions 2.6 and 3.0 was
synchronized, with the alpha and beta releases for both versions being
made on the same days.  The development of 3.0 has influenced many
features in 2.6.</p>
<p>Python 3.0 is a far-ranging redesign of Python that breaks
compatibility with the 2.x series.  This means that existing Python
code will need some conversion in order to run on
Python 3.0.  However, not all the changes in 3.0 necessarily break
compatibility.  In cases where new features won’t cause existing code
to break, they’ve been backported to 2.6 and are described in this
document in the appropriate place.  Some of the 3.0-derived features
are:</p>
<ul class="simple">
<li>A <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> method for converting objects to a complex number.</li>
<li>Alternate syntax for catching exceptions: <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">TypeError</span> <span class="pre">as</span> <span class="pre">exc</span></code>.</li>
<li>The addition of <a class="reference internal" href="../library/functools.html#functools.reduce" title="functools.reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.reduce()</span></code></a> as a synonym for the built-in
<a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> function.</li>
</ul>
<p>Python 3.0 adds several new built-in functions and changes the
semantics of some existing builtins.  Functions that are new in 3.0
such as <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a> have simply been added to Python 2.6, but existing
builtins haven’t been changed; instead, the <a class="reference internal" href="../library/future_builtins.html#module-future_builtins" title="future_builtins"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code></a>
module has versions with the new 3.0 semantics.  Code written to be
compatible with 3.0 can do <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">future_builtins</span> <span class="pre">import</span> <span class="pre">hex,</span> <span class="pre">map</span></code> as
necessary.</p>
<p>A new command-line switch, <a class="reference internal" href="../using/cmdline.html#cmdoption-3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code></a>, enables warnings
about features that will be removed in Python 3.0.  You can run code
with this switch to see how much work will be necessary to port
code to 3.0.  The value of this switch is available
to Python code as the boolean variable <a class="reference internal" href="../library/sys.html#sys.py3kwarning" title="sys.py3kwarning"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.py3kwarning</span></code></a>,
and to C extension code as <code class="xref c c-data docutils literal notranslate"><span class="pre">Py_Py3kWarningFlag</span></code>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The 3xxx series of PEPs, which contains proposals for Python 3.0.
<span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3000"><strong>PEP 3000</strong></a> describes the development process for Python 3.0.
Start with <span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3100"><strong>PEP 3100</strong></a> that describes the general goals for Python
3.0, and then explore the higher-numbered PEPS that propose
specific features.</p>
</div>
</div>
<div class="section" id="changes-to-the-development-process">
<h2>Changes to the Development Process<a class="headerlink" href="#changes-to-the-development-process" title="Permalink to this headline">¶</a></h2>
<p>While 2.6 was being developed, the Python development process
underwent two significant changes: we switched from SourceForge’s
issue tracker to a customized Roundup installation, and the
documentation was converted from LaTeX to reStructuredText.</p>
<div class="section" id="new-issue-tracker-roundup">
<h3>New Issue Tracker: Roundup<a class="headerlink" href="#new-issue-tracker-roundup" title="Permalink to this headline">¶</a></h3>
<p>For a long time, the Python developers had been growing increasingly
annoyed by SourceForge’s bug tracker.  SourceForge’s hosted solution
doesn’t permit much customization; for example, it wasn’t possible to
customize the life cycle of issues.</p>
<p>The infrastructure committee of the Python Software Foundation
therefore posted a call for issue trackers, asking volunteers to set
up different products and import some of the bugs and patches from
SourceForge.  Four different trackers were examined: <a class="reference external" href="https://www.atlassian.com/software/jira/">Jira</a>,
<a class="reference external" href="https://launchpad.net/">Launchpad</a>,
<a class="reference external" href="http://roundup.sourceforge.net/">Roundup</a>, and
<a class="reference external" href="https://trac.edgewall.org/">Trac</a>.
The committee eventually settled on Jira
and Roundup as the two candidates.  Jira is a commercial product that
offers no-cost hosted instances to free-software projects; Roundup
is an open-source project that requires volunteers
to administer it and a server to host it.</p>
<p>After posting a call for volunteers, a new Roundup installation was
set up at <a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a>.  One installation of Roundup can
host multiple trackers, and this server now also hosts issue trackers
for Jython and for the Python web site.  It will surely find
other uses in the future.  Where possible,
this edition of “What’s New in Python” links to the bug/patch
item for each change.</p>
<p>Hosting of the Python bug tracker is kindly provided by
<a class="reference external" href="http://www.upfrontsystems.co.za/">Upfront Systems</a>
of Stellenbosch, South Africa.  Martin von Loewis put a
lot of effort into importing existing bugs and patches from
SourceForge; his scripts for this import operation are at
<a class="reference external" href="http://svn.python.org/view/tracker/importer/">http://svn.python.org/view/tracker/importer/</a> and may be useful to
other projects wishing to move from SourceForge to Roundup.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a></dt>
<dd>The Python bug tracker.</dd>
<dt><a class="reference external" href="http://bugs.jython.org">http://bugs.jython.org</a>:</dt>
<dd>The Jython bug tracker.</dd>
<dt><a class="reference external" href="http://roundup.sourceforge.net/">http://roundup.sourceforge.net/</a></dt>
<dd>Roundup downloads and documentation.</dd>
<dt><a class="reference external" href="http://svn.python.org/view/tracker/importer/">http://svn.python.org/view/tracker/importer/</a></dt>
<dd>Martin von Loewis’s conversion scripts.</dd>
</dl>
</div>
</div>
<div class="section" id="new-documentation-format-restructuredtext-using-sphinx">
<h3>New Documentation Format: reStructuredText Using Sphinx<a class="headerlink" href="#new-documentation-format-restructuredtext-using-sphinx" title="Permalink to this headline">¶</a></h3>
<p>The Python documentation was written using LaTeX since the project
started around 1989.  In the 1980s and early 1990s, most documentation
was printed out for later study, not viewed online. LaTeX was widely
used because it provided attractive printed output while remaining
straightforward to write once the basic rules of the markup were
learned.</p>
<p>Today LaTeX is still used for writing publications destined for
printing, but the landscape for programming tools has shifted.  We no
longer print out reams of documentation; instead, we browse through it
online and HTML has become the most important format to support.
Unfortunately, converting LaTeX to HTML is fairly complicated and Fred
L. Drake Jr., the long-time Python documentation editor, spent a lot
of time maintaining the conversion process.  Occasionally people would
suggest converting the documentation into SGML and later XML, but
performing a good conversion is a major task and no one ever committed
the time required to finish the job.</p>
<p>During the 2.6 development cycle, Georg Brandl put a lot of effort
into building a new toolchain for processing the documentation.  The
resulting package is called Sphinx, and is available from
<a class="reference external" href="http://sphinx-doc.org/">http://sphinx-doc.org/</a>.</p>
<p>Sphinx concentrates on HTML output, producing attractively styled and
modern HTML; printed output is still supported through conversion to
LaTeX.  The input format is reStructuredText, a markup syntax
supporting custom extensions and directives that is commonly used in
the Python community.</p>
<p>Sphinx is a standalone package that can be used for writing, and
almost two dozen other projects
(<a class="reference external" href="http://sphinx-doc.org/examples.html">listed on the Sphinx web site</a>)
have adopted Sphinx as their documentation tool.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="https://docs.python.org/devguide/documenting.html">Documenting Python</a></dt>
<dd>Describes how to write for Python’s documentation.</dd>
<dt><a class="reference external" href="http://sphinx-doc.org/">Sphinx</a></dt>
<dd>Documentation and code for the Sphinx toolchain.</dd>
<dt><a class="reference external" href="http://docutils.sourceforge.net">Docutils</a></dt>
<dd>The underlying reStructuredText parser and toolset.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="pep-343-the-with-statement">
<h2>PEP 343: The ‘with’ statement<a class="headerlink" href="#pep-343-the-with-statement" title="Permalink to this headline">¶</a></h2>
<p>The previous version, Python 2.5, added the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’
statement as an optional feature, to be enabled by a <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span>
<span class="pre">import</span> <span class="pre">with_statement</span></code> directive.  In 2.6 the statement no longer needs to
be specially enabled; this means that <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> is now always a
keyword.  The rest of this section is a copy of the corresponding
section from the “What’s New in Python 2.5” document; if you’re
familiar with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement
from Python 2.5, you can skip this section.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement clarifies code that previously would use
<code class="docutils literal notranslate"><span class="pre">try...finally</span></code> blocks to ensure that clean-up code is executed.  In this
section, I’ll discuss the statement as it will commonly be used.  In the next
section, I’ll examine the implementation details and show how to write objects
for use with this statement.</p>
<p>The ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is a control-flow structure whose basic
structure is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">expression</span> <span class="p">[</span><span class="k">as</span> <span class="n">variable</span><span class="p">]:</span>
    <span class="k">with</span><span class="o">-</span><span class="n">block</span>
</pre></div>
</div>
<p>The expression is evaluated, and it should result in an object that supports the
context management protocol (that is, has <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods).</p>
<p>The object’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> is called before <em>with-block</em> is executed and
therefore can run set-up code. It also may return a value that is bound to the
name <em>variable</em>, if given.  (Note carefully that <em>variable</em> is <em>not</em> assigned
the result of <em>expression</em>.)</p>
<p>After execution of the <em>with-block</em> is finished, the object’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
method is called, even if the block raised an exception, and can therefore run
clean-up code.</p>
<p>Some standard Python objects now support the context management protocol and can
be used with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement. File objects are one example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">&#39;/etc/passwd&#39;</span><span class="p">,</span> <span class="s1">&#39;r&#39;</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="nb">print</span> <span class="n">line</span>
        <span class="o">...</span> <span class="n">more</span> <span class="n">processing</span> <span class="n">code</span> <span class="o">...</span>
</pre></div>
</div>
<p>After this statement has executed, the file object in <em>f</em> will have been
automatically closed, even if the <a class="reference internal" href="../reference/compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loop raised an exception
part-way through the block.</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">In this case, <em>f</em> is the same object created by <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>, because
<code class="xref py py-meth docutils literal notranslate"><span class="pre">file.__enter__()</span></code> returns <em>self</em>.</p>
</div>
<p>The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module’s locks and condition variables  also support the
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">lock</span><span class="p">:</span>
    <span class="c1"># Critical section of code</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The lock is acquired before the block is executed and always released once  the
block is complete.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">localcontext()</span></code> function in the <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module makes it easy
to save and restore the current decimal context, which encapsulates the desired
precision and rounding characteristics for computations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">decimal</span> <span class="k">import</span> <span class="n">Decimal</span><span class="p">,</span> <span class="n">Context</span><span class="p">,</span> <span class="n">localcontext</span>

<span class="c1"># Displays with default precision of 28 digits</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">&#39;578&#39;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>

<span class="k">with</span> <span class="n">localcontext</span><span class="p">(</span><span class="n">Context</span><span class="p">(</span><span class="n">prec</span><span class="o">=</span><span class="mi">16</span><span class="p">)):</span>
    <span class="c1"># All code in this block uses a precision of 16 digits.</span>
    <span class="c1"># The original context is restored on exiting the block.</span>
    <span class="nb">print</span> <span class="n">v</span><span class="o">.</span><span class="n">sqrt</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="writing-context-managers">
<span id="new-26-context-managers"></span><h3>Writing Context Managers<a class="headerlink" href="#writing-context-managers" title="Permalink to this headline">¶</a></h3>
<p>Under the hood, the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement is fairly complicated. Most
people will only use ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ in company with existing objects and
don’t need to know these details, so you can skip the rest of this section if
you like.  Authors of new objects will need to understand the details of the
underlying implementation and should keep reading.</p>
<p>A high-level explanation of the context management protocol is:</p>
<ul class="simple">
<li>The expression is evaluated and should result in an object called a “context
manager”.  The context manager must have <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>
methods.</li>
<li>The context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is called.  The value returned
is assigned to <em>VAR</em>.  If no <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">VAR</span></code> clause is present, the value is simply
discarded.</li>
<li>The code in <em>BLOCK</em> is executed.</li>
<li>If <em>BLOCK</em> raises an exception, the context manager’s <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method
is called with three arguments, the exception details (<code class="docutils literal notranslate"><span class="pre">type,</span> <span class="pre">value,</span> <span class="pre">traceback</span></code>,
the same values returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>, which can also be <code class="docutils literal notranslate"><span class="pre">None</span></code>
if no exception occurred).  The method’s return value controls whether an exception
is re-raised: any false value re-raises the exception, and <code class="docutils literal notranslate"><span class="pre">True</span></code> will result
in suppressing it.  You’ll only rarely want to suppress the exception, because
if you do the author of the code containing the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement will
never realize anything went wrong.</li>
<li>If <em>BLOCK</em> didn’t raise an exception,  the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is still
called, but <em>type</em>, <em>value</em>, and <em>traceback</em> are all <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
</ul>
<p>Let’s think through an example.  I won’t present detailed code but will only
sketch the methods necessary for a database that supports transactions.</p>
<p>(For people unfamiliar with database terminology: a set of changes to the
database are grouped into a transaction.  Transactions can be either committed,
meaning that all the changes are written into the database, or rolled back,
meaning that the changes are all discarded and the database is unchanged.  See
any database textbook for more information.)</p>
<p>Let’s assume there’s an object representing a database connection. Our goal will
be to let the user write code like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">db_connection</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_connection</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;insert into ...&#39;</span><span class="p">)</span>
    <span class="n">cursor</span><span class="o">.</span><span class="n">execute</span><span class="p">(</span><span class="s1">&#39;delete from ...&#39;</span><span class="p">)</span>
    <span class="c1"># ... more operations ...</span>
</pre></div>
</div>
<p>The transaction should be committed if the code in the block runs flawlessly or
rolled back if there’s an exception. Here’s the basic interface for
<code class="xref py py-class docutils literal notranslate"><span class="pre">DatabaseConnection</span></code> that I’ll assume:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="c1"># Database interface</span>
    <span class="k">def</span> <span class="nf">cursor</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Returns a cursor object and starts a new transaction&quot;</span>
    <span class="k">def</span> <span class="nf">commit</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Commits current transaction&quot;</span>
    <span class="k">def</span> <span class="nf">rollback</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="s2">&quot;Rolls back current transaction&quot;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method is pretty easy, having only to start a new
transaction.  For this application the resulting cursor object would be a useful
result, so the method will return it.  The user can then add <code class="docutils literal notranslate"><span class="pre">as</span> <span class="pre">cursor</span></code> to
their ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement to bind the cursor to a variable name.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__enter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="c1"># Code to start a new transaction</span>
        <span class="n">cursor</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
        <span class="k">return</span> <span class="n">cursor</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method is the most complicated because it’s where most of
the work has to be done.  The method has to check if an exception occurred.  If
there was no exception, the transaction is committed.  The transaction is rolled
back if there was an exception.</p>
<p>In the code below, execution will just fall off the end of the function,
returning the default value of <code class="docutils literal notranslate"><span class="pre">None</span></code>.  <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, so the exception
will be re-raised automatically.  If you wished, you could be more explicit and
add a <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement at the marked location.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">DatabaseConnection</span><span class="p">:</span>
    <span class="o">...</span>
    <span class="k">def</span> <span class="nf">__exit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="nb">type</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span>
        <span class="k">if</span> <span class="n">tb</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>
            <span class="c1"># No exception, so commit</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="c1"># Exception occurred, so rollback.</span>
            <span class="bp">self</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
            <span class="c1"># return False</span>
</pre></div>
</div>
</div>
<div class="section" id="the-contextlib-module">
<span id="module-contextlib"></span><h3>The contextlib module<a class="headerlink" href="#the-contextlib-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module provides some functions and a decorator that
are useful when writing objects for use with the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement.</p>
<p>The decorator is called <code class="xref py py-func docutils literal notranslate"><span class="pre">contextmanager()</span></code>, and lets you write a single
generator function instead of defining a new class.  The generator should yield
exactly one value.  The code up to the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be executed as the
<a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> method, and the value yielded will be the method’s return
value that will get bound to the variable in the ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement’s
<a class="reference internal" href="../reference/compound_stmts.html#as"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code></a> clause, if any.  The code after the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> will be
executed in the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method.  Any exception raised in the block will
be raised by the <a class="reference internal" href="../reference/simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement.</p>
<p>Using this decorator, our database example from the previous section
could be written as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">contextmanager</span>

<span class="nd">@contextmanager</span>
<span class="k">def</span> <span class="nf">db_transaction</span><span class="p">(</span><span class="n">connection</span><span class="p">):</span>
    <span class="n">cursor</span> <span class="o">=</span> <span class="n">connection</span><span class="o">.</span><span class="n">cursor</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="k">yield</span> <span class="n">cursor</span>
    <span class="k">except</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
        <span class="k">raise</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">connection</span><span class="o">.</span><span class="n">commit</span><span class="p">()</span>

<span class="n">db</span> <span class="o">=</span> <span class="n">DatabaseConnection</span><span class="p">()</span>
<span class="k">with</span> <span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">)</span> <span class="k">as</span> <span class="n">cursor</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module also has a <code class="docutils literal notranslate"><span class="pre">nested(mgr1,</span> <span class="pre">mgr2,</span> <span class="pre">...)</span></code> function
that combines a number of context managers so you don’t need to write nested
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statements.  In this example, the single ‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’
statement both starts a database transaction and acquires a thread lock:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">lock</span> <span class="o">=</span> <span class="n">threading</span><span class="o">.</span><span class="n">Lock</span><span class="p">()</span>
<span class="k">with</span> <span class="n">nested</span> <span class="p">(</span><span class="n">db_transaction</span><span class="p">(</span><span class="n">db</span><span class="p">),</span> <span class="n">lock</span><span class="p">)</span> <span class="k">as</span> <span class="p">(</span><span class="n">cursor</span><span class="p">,</span> <span class="n">locked</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Finally, the <code class="xref py py-func docutils literal notranslate"><span class="pre">closing()</span></code> function returns its argument so that it can be
bound to a variable, and calls the argument’s <code class="docutils literal notranslate"><span class="pre">.close()</span></code> method at the end
of the block.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib</span><span class="o">,</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">contextlib</span> <span class="k">import</span> <span class="n">closing</span>

<span class="k">with</span> <span class="n">closing</span><span class="p">(</span><span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;http://www.yahoo.com&#39;</span><span class="p">))</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0343"><strong>PEP 343</strong></a> - The “with” statement</dt>
<dd>PEP written by Guido van Rossum and Nick Coghlan; implemented by Mike Bland,
Guido van Rossum, and Neal Norwitz.  The PEP shows the code generated for a
‘<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>’ statement, which can be helpful in learning how the statement
works.</dd>
</dl>
<p class="last">The documentation  for the <a class="reference internal" href="../library/contextlib.html#module-contextlib" title="contextlib: Utilities for with-statement contexts."><code class="xref py py-mod docutils literal notranslate"><span class="pre">contextlib</span></code></a> module.</p>
</div>
</div>
</div>
<div class="section" id="pep-366-explicit-relative-imports-from-a-main-module">
<span id="pep-0366"></span><h2>PEP 366: Explicit Relative Imports From a Main Module<a class="headerlink" href="#pep-366-explicit-relative-imports-from-a-main-module" title="Permalink to this headline">¶</a></h2>
<p>Python’s <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch allows running a module as a script.
When you ran a module that was located inside a package, relative
imports didn’t work correctly.</p>
<p>The fix for Python 2.6 adds a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> attribute to
modules.  When this attribute is present, relative imports will be
relative to the value of this attribute instead of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> attribute.</p>
<p>PEP 302-style importers can then set <code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> as necessary.
The <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module that implements the <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> switch now
does this, so relative imports will now work correctly in scripts
running from inside a package.</p>
</div>
<div class="section" id="pep-370-per-user-site-packages-directory">
<span id="pep-0370"></span><h2>PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory<a class="headerlink" href="#pep-370-per-user-site-packages-directory" title="Permalink to this headline">¶</a></h2>
<p>When you run Python, the module search path <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> usually
includes a directory whose path ends in <code class="docutils literal notranslate"><span class="pre">&quot;site-packages&quot;</span></code>.  This
directory is intended to hold locally-installed packages available to
all users using a machine or a particular site installation.</p>
<p>Python 2.6 introduces a convention for user-specific site directories.
The directory varies depending on the platform:</p>
<ul class="simple">
<li>Unix and Mac OS X: <code class="file docutils literal notranslate"><span class="pre">~/.local/</span></code></li>
<li>Windows: <code class="file docutils literal notranslate"><span class="pre">%APPDATA%/Python</span></code></li>
</ul>
<p>Within this directory, there will be version-specific subdirectories,
such as <code class="file docutils literal notranslate"><span class="pre">lib/python2.6/site-packages</span></code> on Unix/Mac OS and
<code class="file docutils literal notranslate"><span class="pre">Python26/site-packages</span></code> on Windows.</p>
<p>If you don’t like the default directory, it can be overridden by an
environment variable.  <span class="target" id="index-4"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONUSERBASE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONUSERBASE</span></code></a> sets the root
directory used for all Python versions supporting this feature.  On
Windows, the directory for application-specific data can be changed by
setting the <span class="target" id="index-5"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">APPDATA</span></code> environment variable.  You can also
modify the <code class="file docutils literal notranslate"><span class="pre">site.py</span></code> file for your Python installation.</p>
<p>The feature can be disabled entirely by running Python with the
<a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option or setting the <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNOUSERSITE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNOUSERSITE</span></code></a>
environment variable.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0370"><strong>PEP 370</strong></a> - Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</dt>
<dd>PEP written and implemented by Christian Heimes.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-371-the-multiprocessing-package">
<span id="pep-0371"></span><h2>PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package<a class="headerlink" href="#pep-371-the-multiprocessing-package" title="Permalink to this headline">¶</a></h2>
<p>The new <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> package lets Python programs create new
processes that will perform a computation and return a result to the
parent.  The parent and child processes can communicate using queues
and pipes, synchronize their operations using locks and semaphores,
and can share simple arrays of data.</p>
<p>The <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module started out as an exact emulation of
the <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module using processes instead of threads.  That
goal was discarded along the path to Python 2.6, but the general
approach of the module is still similar.  The fundamental class
is the <code class="xref py py-class docutils literal notranslate"><span class="pre">Process</span></code>, which is passed a callable object and
a collection of arguments.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">start()</span></code> method
sets the callable running in a subprocess, after which you can call
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">is_alive()</span></code> method to check whether the subprocess is still running
and the <code class="xref py py-meth docutils literal notranslate"><span class="pre">join()</span></code> method to wait for the process to exit.</p>
<p>Here’s a simple example where the subprocess will calculate a
factorial.  The function doing the calculation is written strangely so
that it takes significantly longer when the input argument is a
multiple of 4.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Process</span><span class="p">,</span> <span class="n">Queue</span>


<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="c1"># If N is a multiple of 4, this function will take much longer.</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">N</span> <span class="o">%</span> <span class="mi">4</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
        <span class="n">time</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="o">.</span><span class="mi">05</span> <span class="o">*</span> <span class="n">N</span><span class="o">/</span><span class="mi">4</span><span class="p">)</span>

    <span class="c1"># Calculate the result</span>
    <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>

    <span class="c1"># Put the result on the queue</span>
    <span class="n">queue</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="n">fact</span><span class="p">)</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">queue</span> <span class="o">=</span> <span class="n">Queue</span><span class="p">()</span>

    <span class="n">N</span> <span class="o">=</span> <span class="mi">5</span>

    <span class="n">p</span> <span class="o">=</span> <span class="n">Process</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">factorial</span><span class="p">,</span> <span class="n">args</span><span class="o">=</span><span class="p">(</span><span class="n">queue</span><span class="p">,</span> <span class="n">N</span><span class="p">))</span>
    <span class="n">p</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="n">result</span> <span class="o">=</span> <span class="n">queue</span><span class="o">.</span><span class="n">get</span><span class="p">()</span>
    <span class="nb">print</span> <span class="s1">&#39;Factorial&#39;</span><span class="p">,</span> <span class="n">N</span><span class="p">,</span> <span class="s1">&#39;=&#39;</span><span class="p">,</span> <span class="n">result</span>
</pre></div>
</div>
<p>A <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> is used to communicate the result of the factorial.
The <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> object is stored in a global variable.
The child process will use the value of the variable when the child
was created; because it’s a <a class="reference internal" href="../library/queue.html#Queue.Queue" title="Queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a>, parent and child can use
the object to communicate.  (If the parent were to change the value of
the global variable, the child’s value would be unaffected, and vice
versa.)</p>
<p>Two other classes, <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>, provide
higher-level interfaces.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> will create a fixed number of
worker processes, and requests can then be distributed to the workers
by calling <a class="reference internal" href="../library/functions.html#apply" title="apply"><code class="xref py py-meth docutils literal notranslate"><span class="pre">apply()</span></code></a> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">apply_async()</span></code> to add a single request,
and <a class="reference internal" href="../library/functions.html#map" title="map"><code class="xref py py-meth docutils literal notranslate"><span class="pre">map()</span></code></a> or <code class="xref py py-meth docutils literal notranslate"><span class="pre">map_async()</span></code> to add a number of
requests.  The following code uses a <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> to spread requests
across 5 worker processes and retrieve a list of results:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Pool</span>

<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="o">...</span>
<span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="n">result</span> <span class="o">=</span> <span class="n">p</span><span class="o">.</span><span class="n">map</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">))</span>
<span class="k">for</span> <span class="n">v</span> <span class="ow">in</span> <span class="n">result</span><span class="p">:</span>
    <span class="nb">print</span> <span class="n">v</span>
</pre></div>
</div>
<p>This produces the following output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span>
<span class="mi">39916800</span>
<span class="mi">51090942171709440000</span>
<span class="mi">8222838654177922817725562880000000</span>
<span class="mi">33452526613163807108170062053440751665152000000000</span>
<span class="o">...</span>
</pre></div>
</div>
<p>The other high-level interface, the <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code> class, creates a
separate server process that can hold master copies of Python data
structures.  Other processes can then access and modify these data
structures using proxy objects.  The following example creates a
shared dictionary by calling the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">dict()</span></code></a> method; the worker
processes then insert values into the dictionary.  (Locking is not
done for you automatically, which doesn’t matter in this example.
<code class="xref py py-class docutils literal notranslate"><span class="pre">Manager</span></code>’s methods also include <code class="xref py py-meth docutils literal notranslate"><span class="pre">Lock()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">RLock()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">Semaphore()</span></code> to create shared locks.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">time</span>
<span class="kn">from</span> <span class="nn">multiprocessing</span> <span class="k">import</span> <span class="n">Pool</span><span class="p">,</span> <span class="n">Manager</span>

<span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">dictionary</span><span class="p">):</span>
    <span class="s2">&quot;Compute a factorial.&quot;</span>
    <span class="c1"># Calculate the result</span>
    <span class="n">fact</span> <span class="o">=</span> <span class="mi">1</span><span class="n">L</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">N</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="n">fact</span> <span class="o">=</span> <span class="n">fact</span> <span class="o">*</span> <span class="n">i</span>

    <span class="c1"># Store result in dictionary</span>
    <span class="n">dictionary</span><span class="p">[</span><span class="n">N</span><span class="p">]</span> <span class="o">=</span> <span class="n">fact</span>

<span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s1">&#39;__main__&#39;</span><span class="p">:</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">Pool</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
    <span class="n">mgr</span> <span class="o">=</span> <span class="n">Manager</span><span class="p">()</span>
    <span class="n">d</span> <span class="o">=</span> <span class="n">mgr</span><span class="o">.</span><span class="n">dict</span><span class="p">()</span>         <span class="c1"># Create shared dictionary</span>

    <span class="c1"># Run tasks using the pool</span>
    <span class="k">for</span> <span class="n">N</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">1000</span><span class="p">,</span> <span class="mi">10</span><span class="p">):</span>
        <span class="n">p</span><span class="o">.</span><span class="n">apply_async</span><span class="p">(</span><span class="n">factorial</span><span class="p">,</span> <span class="p">(</span><span class="n">N</span><span class="p">,</span> <span class="n">d</span><span class="p">))</span>

    <span class="c1"># Mark pool as closed -- no more tasks can be added.</span>
    <span class="n">p</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

    <span class="c1"># Wait for tasks to exit</span>
    <span class="n">p</span><span class="o">.</span><span class="n">join</span><span class="p">()</span>

    <span class="c1"># Output results</span>
    <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()):</span>
        <span class="nb">print</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span>
</pre></div>
</div>
<p>This will produce the output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="mi">1</span>
<span class="mi">11</span> <span class="mi">39916800</span>
<span class="mi">21</span> <span class="mi">51090942171709440000</span>
<span class="mi">31</span> <span class="mi">8222838654177922817725562880000000</span>
<span class="mi">41</span> <span class="mi">33452526613163807108170062053440751665152000000000</span>
<span class="mi">51</span> <span class="mf">15511187532873822802242430164693032110632597200169861120000.</span><span class="o">..</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p>The documentation for the <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module.</p>
<dl class="last docutils">
<dt><span class="target" id="index-8"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0371"><strong>PEP 371</strong></a> - Addition of the multiprocessing package</dt>
<dd>PEP written by Jesse Noller and Richard Oudkerk;
implemented by Richard Oudkerk and Jesse Noller.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3101-advanced-string-formatting">
<span id="pep-3101"></span><h2>PEP 3101: Advanced String Formatting<a class="headerlink" href="#pep-3101-advanced-string-formatting" title="Permalink to this headline">¶</a></h2>
<p>In Python 3.0, the <cite>%</cite> operator is supplemented by a more powerful string
formatting method, <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a>.  Support for the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method
has been backported to Python 2.6.</p>
<p>In 2.6, both 8-bit and Unicode strings have a <cite>.format()</cite> method that
treats the string as a template and takes the arguments to be formatted.
The formatting template uses curly brackets (<cite>{</cite>, <cite>}</cite>) as special characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Substitute positional argument 0 into the string.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{0}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s2">&quot;root&quot;</span><span class="p">)</span>
<span class="go">&#39;User ID: root&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Use the named keyword arguments</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;User ID: </span><span class="si">{uid}</span><span class="s2">   Last seen: </span><span class="si">{last_login}</span><span class="s2">&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
<span class="gp">... </span>   <span class="n">uid</span><span class="o">=</span><span class="s2">&quot;root&quot;</span><span class="p">,</span>
<span class="gp">... </span>   <span class="n">last_login</span> <span class="o">=</span> <span class="s2">&quot;5 Mar 2008 07:20&quot;</span><span class="p">)</span>
<span class="go">&#39;User ID: root   Last seen: 5 Mar 2008 07:20&#39;</span>
</pre></div>
</div>
<p>Curly brackets can be escaped by doubling them:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s2">&quot;Empty dict: {{}}&quot;</span><span class="o">.</span><span class="n">format</span><span class="p">()</span>
<span class="go">&quot;Empty dict: {}&quot;</span>
</pre></div>
</div>
<p>Field names can be integers indicating positional arguments, such as
<code class="docutils literal notranslate"><span class="pre">{0}</span></code>, <code class="docutils literal notranslate"><span class="pre">{1}</span></code>, etc. or names of keyword arguments.  You can also
supply compound field names that read attributes or access dictionary keys:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="s1">&#39;Platform: </span><span class="si">{0.platform}</span><span class="se">\n</span><span class="s1">Python version: </span><span class="si">{0.version}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
<span class="go">Platform: darwin</span>
<span class="go">Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)</span>
<span class="go">[GCC 4.0.1 (Apple Computer, Inc. build 5367)]&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">mimetypes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;Content-type: </span><span class="si">{0[.mp4]}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">mimetypes</span><span class="o">.</span><span class="n">types_map</span><span class="p">)</span>
<span class="go">&#39;Content-type: video/mp4&#39;</span>
</pre></div>
</div>
<p>Note that when using dictionary-style notation such as <code class="docutils literal notranslate"><span class="pre">[.mp4]</span></code>, you
don’t need to put any quotation marks around the string; it will look
up the value using <code class="docutils literal notranslate"><span class="pre">.mp4</span></code> as the key.  Strings beginning with a
number will be converted to an integer.  You can’t write more
complicated expressions inside a format string.</p>
<p>So far we’ve shown how to specify which field to substitute into the
resulting string.  The precise formatting used is also controllable by
adding a colon followed by a format specifier.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 0: left justify, pad to 15 characters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Field 1: right justify, pad to 6 characters</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="si">{0:15}</span><span class="s1"> $</span><span class="si">{1:&gt;6}</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Registration&#39;</span><span class="p">,</span> <span class="mi">35</span><span class="p">)</span>
<span class="go">&#39;Registration    $    35&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Tutorial&#39;</span><span class="p">,</span> <span class="mi">50</span><span class="p">)</span>
<span class="go">&#39;Tutorial        $    50&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Banquet&#39;</span><span class="p">,</span> <span class="mi">125</span><span class="p">)</span>
<span class="go">&#39;Banquet         $   125&#39;</span>
</pre></div>
</div>
<p>Format specifiers can reference other fields through nesting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span> <span class="o">=</span> <span class="s1">&#39;{0:</span><span class="si">{1}</span><span class="s1">}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">15</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
<span class="go">&#39;Invoice #1234  &#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">width</span> <span class="o">=</span> <span class="mi">35</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">fmt</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">&#39;Invoice #1234&#39;</span><span class="p">,</span> <span class="n">width</span><span class="p">)</span>
<span class="go">&#39;Invoice #1234                      &#39;</span>
</pre></div>
</div>
<p>The alignment of a field within the desired width can be specified:</p>
<table border="1" class="docutils">
<colgroup>
<col width="27%" />
<col width="73%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Character</th>
<th class="head">Effect</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td>&lt; (default)</td>
<td>Left-align</td>
</tr>
<tr class="row-odd"><td>&gt;</td>
<td>Right-align</td>
</tr>
<tr class="row-even"><td>^</td>
<td>Center</td>
</tr>
<tr class="row-odd"><td>=</td>
<td>(For numeric types only) Pad after the sign.</td>
</tr>
</tbody>
</table>
<p>Format specifiers can also include a presentation type, which
controls how the value is formatted.  For example, floating-point numbers
can be formatted as a general number or in exponential notation:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:g}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
<span class="go">&#39;3.75&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{0:e}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">3.75</span><span class="p">)</span>
<span class="go">&#39;3.750000e+00&#39;</span>
</pre></div>
</div>
<p>A variety of presentation types are available.  Consult the 2.6
documentation for a <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">complete list</span></a>; here’s a sample:</p>
<table border="1" class="docutils">
<colgroup>
<col width="6%" />
<col width="94%" />
</colgroup>
<tbody valign="top">
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">b</span></code></td>
<td>Binary. Outputs the number in base 2.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">c</span></code></td>
<td>Character. Converts the integer to the corresponding Unicode character
before printing.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">d</span></code></td>
<td>Decimal Integer. Outputs the number in base 10.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">o</span></code></td>
<td>Octal format. Outputs the number in base 8.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">x</span></code></td>
<td>Hex format. Outputs the number in base 16, using lower-case letters for
the digits above 9.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">e</span></code></td>
<td>Exponent notation. Prints the number in scientific notation using the
letter ‘e’ to indicate the exponent.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">g</span></code></td>
<td>General format. This prints the number as a fixed-point number, unless
the number is too large, in which case it switches to ‘e’ exponent
notation.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">n</span></code></td>
<td>Number. This is the same as ‘g’ (for floats) or ‘d’ (for integers),
except that it uses the current locale setting to insert the appropriate
number separator characters.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">%</span></code></td>
<td>Percentage. Multiplies the number by 100 and displays in fixed (‘f’)
format, followed by a percent sign.</td>
</tr>
</tbody>
</table>
<p>Classes and types can define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method to control how they’re
formatted.  It receives a single argument, the format specifier:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">__format__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">format_spec</span><span class="p">):</span>
    <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">format_spec</span><span class="p">,</span> <span class="n">unicode</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">))</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
</pre></div>
</div>
<p>There’s also a <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> builtin that will format a single
value.  It calls the type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method with the
provided specifier:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">format</span><span class="p">(</span><span class="mf">75.6564</span><span class="p">,</span> <span class="s1">&#39;.2f&#39;</span><span class="p">)</span>
<span class="go">&#39;75.66&#39;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt>
<dd>The reference documentation for format fields.</dd>
<dt><span class="target" id="index-9"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3101"><strong>PEP 3101</strong></a> - Advanced String Formatting</dt>
<dd>PEP written by Talin. Implemented by Eric Smith.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3105-print-as-a-function">
<span id="pep-3105"></span><h2>PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function<a class="headerlink" href="#pep-3105-print-as-a-function" title="Permalink to this headline">¶</a></h2>
<p>The <code class="docutils literal notranslate"><span class="pre">print</span></code> statement becomes the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function in Python 3.0.
Making <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> a function makes it possible to replace the function
by doing <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">print(...)</span></code> or importing a new function from somewhere else.</p>
<p>Python 2.6 has a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> import that removes <code class="docutils literal notranslate"><span class="pre">print</span></code> as language
syntax, letting you use the functional form instead.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">print_function</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="s1">&#39;# of entries&#39;</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">dictionary</span><span class="p">),</span> <span class="n">file</span><span class="o">=</span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="p">)</span>
</pre></div>
</div>
<p>The signature of the new function is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">print</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;</span><span class="se">\n</span><span class="s1">&#39;</span><span class="p">,</span> <span class="n">file</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>The parameters are:</p>
<blockquote>
<div><ul class="simple">
<li><em>args</em>: positional arguments whose values will be printed out.</li>
<li><em>sep</em>: the separator, which will be printed between arguments.</li>
<li><em>end</em>: the ending text, which will be printed after all of the
arguments have been output.</li>
<li><em>file</em>: the file object to which the output will be sent.</li>
</ul>
</div></blockquote>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-10"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3105"><strong>PEP 3105</strong></a> - Make print a function</dt>
<dd>PEP written by Georg Brandl.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3110-exception-handling-changes">
<span id="pep-3110"></span><h2>PEP 3110: Exception-Handling Changes<a class="headerlink" href="#pep-3110-exception-handling-changes" title="Permalink to this headline">¶</a></h2>
<p>One error that Python programmers occasionally make
is writing the following code:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
<span class="k">except</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">:</span>  <span class="c1"># Wrong!</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>The author is probably trying to catch both <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and
<a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exceptions, but this code actually does something
different: it will catch <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> and bind the resulting
exception object to the local name <code class="docutils literal notranslate"><span class="pre">&quot;ValueError&quot;</span></code>.  The
<a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception will not be caught at all.  The correct
code specifies a tuple of exceptions:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
<span class="k">except</span> <span class="p">(</span><span class="ne">TypeError</span><span class="p">,</span> <span class="ne">ValueError</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>This error happens because the use of the comma here is ambiguous:
does it indicate two different nodes in the parse tree, or a single
node that’s a tuple?</p>
<p>Python 3.0 makes this unambiguous by replacing the comma with the word
“as”.  To catch an exception and store the exception object in the
variable <code class="docutils literal notranslate"><span class="pre">exc</span></code>, you must write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="o">...</span>
<span class="k">except</span> <span class="ne">TypeError</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Python 3.0 will only support the use of “as”, and therefore interprets
the first example as catching two different exceptions.  Python 2.6
supports both the comma and “as”, so existing code will continue to
work.  We therefore suggest using “as” when writing new Python code
that will only be executed with 2.6.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-11"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3110"><strong>PEP 3110</strong></a> - Catching Exceptions in Python 3000</dt>
<dd>PEP written and implemented by Collin Winter.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3112-byte-literals">
<span id="pep-3112"></span><h2>PEP 3112: Byte Literals<a class="headerlink" href="#pep-3112-byte-literals" title="Permalink to this headline">¶</a></h2>
<p>Python 3.0 adopts Unicode as the language’s fundamental string type and
denotes 8-bit literals differently, either as <code class="docutils literal notranslate"><span class="pre">b'string'</span></code>
or using a <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> constructor.  For future compatibility,
Python 2.6 adds <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> as a synonym for the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> type,
and it also supports the <code class="docutils literal notranslate"><span class="pre">b''</span></code> notation.</p>
<p>The 2.6 <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> differs from 3.0’s <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> type in various
ways; most notably, the constructor is completely different.  In 3.0,
<code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> is 3 elements long, containing the bytes
representing <code class="docutils literal notranslate"><span class="pre">ABC</span></code>; in 2.6, <code class="docutils literal notranslate"><span class="pre">bytes([65,</span> <span class="pre">66,</span> <span class="pre">67])</span></code> returns the
12-byte string representing the <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> of the list.</p>
<p>The primary use of <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> in 2.6 will be to write tests of
object type such as <code class="docutils literal notranslate"><span class="pre">isinstance(x,</span> <span class="pre">bytes)</span></code>.  This will help the 2to3
converter, which can’t tell whether 2.x code intends strings to
contain either characters or 8-bit bytes; you can now
use either <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> or <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a> to represent your intention
exactly, and the resulting code will also be correct in Python 3.0.</p>
<p>There’s also a <code class="docutils literal notranslate"><span class="pre">__future__</span></code> import that causes all string literals
to become Unicode strings.  This means that <code class="docutils literal notranslate"><span class="pre">\u</span></code> escape sequences
can be used to include Unicode characters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">unicode_literals</span>

<span class="n">s</span> <span class="o">=</span> <span class="p">(</span><span class="s1">&#39;</span><span class="se">\u751f\u3080\u304e\u3000\u751f\u3054</span><span class="s1">&#39;</span>
     <span class="s1">&#39;</span><span class="se">\u3081\u3000\u751f\u305f\u307e\u3054</span><span class="s1">&#39;</span><span class="p">)</span>

<span class="nb">print</span> <span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>               <span class="c1"># 12 Unicode characters</span>
</pre></div>
</div>
<p>At the C level, Python 3.0 will rename the existing 8-bit
string type, called <a class="reference internal" href="../c-api/string.html#c.PyStringObject" title="PyStringObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyStringObject</span></code></a> in Python 2.x,
to <code class="xref c c-type docutils literal notranslate"><span class="pre">PyBytesObject</span></code>.  Python 2.6 uses <code class="docutils literal notranslate"><span class="pre">#define</span></code>
to support using the names <code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytesObject()</span></code>,
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_Check()</span></code>, <code class="xref c c-func docutils literal notranslate"><span class="pre">PyBytes_FromStringAndSize()</span></code>,
and all the other functions and macros used with strings.</p>
<p>Instances of the <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> type are immutable just
as strings are.  A new <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> type stores a mutable
sequence of bytes:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">bytearray</span><span class="p">([</span><span class="mi">65</span><span class="p">,</span> <span class="mi">66</span><span class="p">,</span> <span class="mi">67</span><span class="p">])</span>
<span class="go">bytearray(b&#39;ABC&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="sa">u</span><span class="s1">&#39;</span><span class="se">\u21ef\u3244</span><span class="s1">&#39;</span><span class="p">,</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;\xe2\x87\xaf\xe3\x89\x84&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;</span><span class="se">\xe3</span><span class="s1">&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;\xe3\x87\xaf\xe3\x89\x84&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">unicode</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">b</span><span class="p">),</span> <span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="go">u&#39;\u31ef \u3244&#39;</span>
</pre></div>
</div>
<p>Byte arrays support most of the methods of string types, such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">startswith()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">endswith()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code>/<code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code>,
and some of the methods of lists, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>,  and <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="s1">&#39;ABC&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;d&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="nb">ord</span><span class="p">(</span><span class="s1">&#39;e&#39;</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;ABCde&#39;)</span>
</pre></div>
</div>
<p>There’s also a corresponding C API, with
<a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromObject" title="PyByteArray_FromObject"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromObject()</span></code></a>,
<a class="reference internal" href="../c-api/bytearray.html#c.PyByteArray_FromStringAndSize" title="PyByteArray_FromStringAndSize"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyByteArray_FromStringAndSize()</span></code></a>,
and various other functions.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-12"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3112"><strong>PEP 3112</strong></a> - Bytes literals in Python 3000</dt>
<dd>PEP written by Jason Orendorff; backported to 2.6 by Christian Heimes.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3116-new-i-o-library">
<span id="pep-3116"></span><h2>PEP 3116: New I/O Library<a class="headerlink" href="#pep-3116-new-i-o-library" title="Permalink to this headline">¶</a></h2>
<p>Python’s built-in file objects support a number of methods, but
file-like objects don’t necessarily support all of them.  Objects that
imitate files usually support <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, but they
may not support <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a>, for example.  Python 3.0 introduces
a layered I/O library in the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module that separates buffering
and text-handling features from the fundamental read and write
operations.</p>
<p>There are three levels of abstract base classes provided by
the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module:</p>
<ul>
<li><p class="first"><code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code> defines raw I/O operations: <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">readinto()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">tell()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code>,
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code>.
Most of the methods of this class will often map to a single system call.
There are also <code class="xref py py-meth docutils literal notranslate"><span class="pre">readable()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">writable()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">seekable()</span></code>
methods for determining what operations a given object will allow.</p>
<p>Python 3.0 has concrete implementations of this class for files and
sockets, but Python 2.6 hasn’t restructured its file and socket objects
in this way.</p>
</li>
<li><p class="first"><code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedIOBase</span></code> is an abstract base class that
buffers data in memory to reduce the number of
system calls used, making I/O processing more efficient.
It supports all of the methods of <code class="xref py py-class docutils literal notranslate"><span class="pre">RawIOBase</span></code>,
and adds a <code class="xref py py-attr docutils literal notranslate"><span class="pre">raw</span></code> attribute holding the underlying raw object.</p>
<p>There are five concrete classes implementing this ABC.
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedWriter</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedReader</span></code> are for objects
that support write-only or read-only usage that have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">seek()</span></code>
method for random access.  <code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRandom</span></code> objects support
read and write access upon the same underlying stream, and
<code class="xref py py-class docutils literal notranslate"><span class="pre">BufferedRWPair</span></code> is for objects such as TTYs that have both
read and write operations acting upon unconnected streams of data.
The <code class="xref py py-class docutils literal notranslate"><span class="pre">BytesIO</span></code> class supports reading, writing, and seeking
over an in-memory buffer.</p>
</li>
<li id="index-13"><p class="first"><code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code>: Provides functions for reading and writing
strings (remember, strings will be Unicode in Python 3.0),
and supporting <a class="reference internal" href="../glossary.html#term-universal-newlines"><span class="xref std std-term">universal newlines</span></a>.  <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOBase</span></code> defines
the <a class="reference internal" href="../library/readline.html#module-readline" title="readline: GNU readline support for Python. (Unix)"><code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code></a> method and supports iteration upon
objects.</p>
<p>There are two concrete implementations.  <code class="xref py py-class docutils literal notranslate"><span class="pre">TextIOWrapper</span></code>
wraps a buffered I/O object, supporting all of the methods for
text I/O and adding a <a class="reference internal" href="../library/functions.html#buffer" title="buffer"><code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer</span></code></a> attribute for access
to the underlying object.  <a class="reference internal" href="../library/stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> simply buffers
everything in memory without ever writing anything to disk.</p>
<p>(In Python 2.6, <a class="reference internal" href="../library/io.html#io.StringIO" title="io.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.StringIO</span></code></a> is implemented in
pure Python, so it’s pretty slow.   You should therefore stick with the
existing <a class="reference internal" href="../library/stringio.html#module-StringIO" title="StringIO: Read and write strings as if they were files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">StringIO</span></code></a> module or <a class="reference internal" href="../library/stringio.html#module-cStringIO" title="cStringIO: Faster version of StringIO, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cStringIO</span></code></a> for now.  At some
point Python 3.0’s <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module will be rewritten into C for speed,
and perhaps the C implementation will be  backported to the 2.x releases.)</p>
</li>
</ul>
<p>In Python 2.6, the underlying implementations haven’t been
restructured to build on top of the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> module’s classes.  The
module is being provided to make it easier to write code that’s
forward-compatible with 3.0, and to save developers the effort of writing
their own implementations of buffering and text I/O.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-14"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3116"><strong>PEP 3116</strong></a> - New I/O</dt>
<dd>PEP written by Daniel Stutzbach, Mike Verdone, and Guido van Rossum.
Code by Guido van Rossum, Georg Brandl, Walter Doerwald,
Jeremy Hylton, Martin von Loewis, Tony Lownds, and others.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3118-revised-buffer-protocol">
<span id="pep-3118"></span><h2>PEP 3118: Revised Buffer Protocol<a class="headerlink" href="#pep-3118-revised-buffer-protocol" title="Permalink to this headline">¶</a></h2>
<p>The buffer protocol is a C-level API that lets Python types
exchange pointers into their internal representations.  A
memory-mapped file can be viewed as a buffer of characters, for
example, and this lets another module such as <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
treat memory-mapped files as a string of characters to be searched.</p>
<p>The primary users of the buffer protocol are numeric-processing
packages such as NumPy, which expose the internal representation
of arrays so that callers can write data directly into an array instead
of going through a slower API.  This PEP updates the buffer protocol in light of experience
from NumPy development, adding a number of new features
such as indicating the shape of an array or locking a memory region.</p>
<p>The most important new C API function is
<code class="docutils literal notranslate"><span class="pre">PyObject_GetBuffer(PyObject</span> <span class="pre">*obj,</span> <span class="pre">Py_buffer</span> <span class="pre">*view,</span> <span class="pre">int</span> <span class="pre">flags)</span></code>, which
takes an object and a set of flags, and fills in the
<code class="docutils literal notranslate"><span class="pre">Py_buffer</span></code> structure with information
about the object’s memory representation.  Objects
can use this operation to lock memory in place
while an external caller could be modifying the contents,
so there’s a corresponding <code class="docutils literal notranslate"><span class="pre">PyBuffer_Release(Py_buffer</span> <span class="pre">*view)</span></code> to
indicate that the external caller is done.</p>
<p>The <em>flags</em> argument to <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> specifies
constraints upon the memory returned.  Some examples are:</p>
<blockquote>
<div><ul class="simple">
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_WRITABLE</span></code> indicates that the memory must be writable.</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_LOCK</span></code> requests a read-only or exclusive lock on the memory.</li>
<li><code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_C_CONTIGUOUS</span></code> and <code class="xref py py-const docutils literal notranslate"><span class="pre">PyBUF_F_CONTIGUOUS</span></code>
requests a C-contiguous (last dimension varies the fastest) or
Fortran-contiguous (first dimension varies the fastest) array layout.</li>
</ul>
</div></blockquote>
<p>Two new argument codes for <a class="reference internal" href="../c-api/arg.html#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyArg_ParseTuple()</span></code></a>,
<code class="docutils literal notranslate"><span class="pre">s*</span></code> and <code class="docutils literal notranslate"><span class="pre">z*</span></code>, return locked buffer objects for a parameter.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-15"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3118"><strong>PEP 3118</strong></a> - Revising the buffer protocol</dt>
<dd>PEP written by Travis Oliphant and Carl Banks; implemented by
Travis Oliphant.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3119-abstract-base-classes">
<span id="pep-3119"></span><h2>PEP 3119: Abstract Base Classes<a class="headerlink" href="#pep-3119-abstract-base-classes" title="Permalink to this headline">¶</a></h2>
<p>Some object-oriented languages such as Java support interfaces,
declaring that a class has a given set of methods or supports a given
access protocol.  Abstract Base Classes (or ABCs) are an equivalent
feature for Python. The ABC support consists of an <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to PEP 3119."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module
containing a metaclass called <code class="xref py py-class docutils literal notranslate"><span class="pre">ABCMeta</span></code>, special handling of
this metaclass by the <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a>
builtins, and a collection of basic ABCs that the Python developers
think will be widely useful.  Future versions of Python will probably
add more ABCs.</p>
<p>Let’s say you have a particular class and wish to know whether it supports
dictionary-style access.  The phrase “dictionary-style” is vague, however.
It probably means that accessing items with <code class="docutils literal notranslate"><span class="pre">obj[1]</span></code> works.
Does it imply that setting items with <code class="docutils literal notranslate"><span class="pre">obj[2]</span> <span class="pre">=</span> <span class="pre">value</span></code> works?
Or that the object will have <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>
methods?  What about the iterative variants  such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">iterkeys()</span></code>?  <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code></a>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>?  Iterating over the object with <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a>?</p>
<p>The Python 2.6 <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module includes a number of
different ABCs that represent these distinctions.  <code class="xref py py-class docutils literal notranslate"><span class="pre">Iterable</span></code>
indicates that a class defines <a class="reference internal" href="../reference/datamodel.html#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, and
<code class="xref py py-class docutils literal notranslate"><span class="pre">Container</span></code> means the class defines a <a class="reference internal" href="../reference/datamodel.html#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>
method and therefore supports <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">in</span> <span class="pre">y</span></code> expressions.  The basic
dictionary interface of getting items, setting items, and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, is defined by the
<code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code> ABC.</p>
<p>You can derive your own classes from a particular ABC
to indicate they support that ABC’s interface:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>

<span class="k">class</span> <span class="nc">Storage</span><span class="p">(</span><span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Alternatively, you could write the class without deriving from
the desired ABC and instead register the class by
calling the ABC’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code> method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">collections</span>

<span class="k">class</span> <span class="nc">Storage</span><span class="p">:</span>
    <span class="o">...</span>

<span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="n">Storage</span><span class="p">)</span>
</pre></div>
</div>
<p>For classes that you write, deriving from the ABC is probably clearer.
The <code class="xref py py-meth docutils literal notranslate"><span class="pre">register()</span></code>  method is useful when you’ve written a new
ABC that can describe an existing type or class, or if you want
to declare that some third-party class implements an ABC.
For example, if you defined a <code class="xref py py-class docutils literal notranslate"><span class="pre">PrintableType</span></code> ABC,
it’s legal to do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Register Python&#39;s types</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">float</span><span class="p">)</span>
<span class="n">PrintableType</span><span class="o">.</span><span class="n">register</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span>
</pre></div>
</div>
<p>Classes should obey the semantics specified by an ABC, but
Python can’t check this; it’s up to the class author to
understand the ABC’s requirements and to implement the code accordingly.</p>
<p>To check whether an object supports a particular interface, you can
now write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">d</span><span class="p">):</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">d</span><span class="p">,</span> <span class="n">collections</span><span class="o">.</span><span class="n">MutableMapping</span><span class="p">):</span>
        <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">&quot;Mapping object expected, not </span><span class="si">%r</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="n">d</span><span class="p">)</span>
</pre></div>
</div>
<p>Don’t feel that you must now begin writing lots of checks as in the
above example.  Python has a strong tradition of duck-typing, where
explicit type-checking is never done and code simply calls methods on
an object, trusting that those methods will be there and raising an
exception if they aren’t.  Be judicious in checking for ABCs and only
do it where it’s absolutely necessary.</p>
<p>You can write your own ABCs by using <code class="docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code> as the
metaclass in a class definition:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="k">import</span> <span class="n">ABCMeta</span><span class="p">,</span> <span class="n">abstractmethod</span>

<span class="k">class</span> <span class="nc">Drawable</span><span class="p">():</span>
    <span class="n">__metaclass__</span> <span class="o">=</span> <span class="n">ABCMeta</span>

    <span class="nd">@abstractmethod</span>
    <span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">1.0</span><span class="p">):</span>
        <span class="k">pass</span>

    <span class="k">def</span> <span class="nf">draw_doubled</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">draw</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="o">=</span><span class="mf">2.0</span><span class="p">)</span>


<span class="k">class</span> <span class="nc">Square</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">draw</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">scale</span><span class="p">):</span>
        <span class="o">...</span>
</pre></div>
</div>
<p>In the <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code> ABC above, the <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code> method
renders the object at twice its size and can be implemented in terms
of other methods described in <code class="xref py py-class docutils literal notranslate"><span class="pre">Drawable</span></code>.  Classes implementing
this ABC therefore don’t need to provide their own implementation
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw_doubled()</span></code>, though they can do so.  An implementation
of <code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> is necessary, though; the ABC can’t provide
a useful generic implementation.</p>
<p>You can apply the <code class="docutils literal notranslate"><span class="pre">&#64;abstractmethod</span></code> decorator to methods such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">draw()</span></code> that must be implemented; Python will then raise an
exception for classes that don’t define the method.
Note that the exception is only raised when you actually
try to create an instance of a subclass lacking the method:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Circle</span><span class="p">(</span><span class="n">Drawable</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Circle</span><span class="p">()</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">Can&#39;t instantiate abstract class Circle with abstract methods draw</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>Abstract data attributes can be declared using the
<code class="docutils literal notranslate"><span class="pre">&#64;abstractproperty</span></code> decorator:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">abc</span> <span class="k">import</span> <span class="n">abstractproperty</span>
<span class="o">...</span>

<span class="nd">@abstractproperty</span>
<span class="k">def</span> <span class="nf">readonly</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
   <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>
</pre></div>
</div>
<p>Subclasses must then define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">readonly()</span></code> property.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3119"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt>
<dd>PEP written by Guido van Rossum and Talin.
Implemented by Guido van Rossum.
Backported to 2.6 by Benjamin Aranguren, with Alex Martelli.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3127-integer-literal-support-and-syntax">
<span id="pep-3127"></span><h2>PEP 3127: Integer Literal Support and Syntax<a class="headerlink" href="#pep-3127-integer-literal-support-and-syntax" title="Permalink to this headline">¶</a></h2>
<p>Python 3.0 changes the syntax for octal (base-8) integer literals,
prefixing them with “0o” or “0O” instead of a leading zero, and adds
support for binary (base-2) integer literals, signalled by a “0b” or
“0B” prefix.</p>
<p>Python 2.6 doesn’t drop support for a leading 0 signalling
an octal number, but it does add support for “0o” and “0b”:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mo">0o21</span><span class="p">,</span> <span class="mi">2</span><span class="o">*</span><span class="mi">8</span> <span class="o">+</span> <span class="mi">1</span>
<span class="go">(17, 17)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="mb">0b101111</span>
<span class="go">47</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> builtin still returns numbers
prefixed with a leading zero, and a new <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a>
builtin returns the binary representation for a number:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;052&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">future_builtins</span><span class="o">.</span><span class="n">oct</span><span class="p">(</span><span class="mi">42</span><span class="p">)</span>
<span class="go">&#39;0o52&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="mi">173</span><span class="p">)</span>
<span class="go">&#39;0b10101101&#39;</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> builtins will now accept the “0o”
and “0b” prefixes when base-8 or base-2 are requested, or when the
<em>base</em> argument is zero (signalling that the base used should be
determined from the string):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span> <span class="p">(</span><span class="s1">&#39;0o52&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">42</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="go">13</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="p">(</span><span class="s1">&#39;0b1101&#39;</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
<span class="go">13</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3127"><strong>PEP 3127</strong></a> - Integer Literal Support and Syntax</dt>
<dd>PEP written by Patrick Maupin; backported to 2.6 by
Eric Smith.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3129-class-decorators">
<span id="pep-3129"></span><h2>PEP 3129: Class Decorators<a class="headerlink" href="#pep-3129-class-decorators" title="Permalink to this headline">¶</a></h2>
<p>Decorators have been extended from functions to classes.  It’s now legal to
write:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="nd">@foo</span>
<span class="nd">@bar</span>
<span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
  <span class="k">pass</span>
</pre></div>
</div>
<p>This is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span>
  <span class="k">pass</span>

<span class="n">A</span> <span class="o">=</span> <span class="n">foo</span><span class="p">(</span><span class="n">bar</span><span class="p">(</span><span class="n">A</span><span class="p">))</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-18"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3129"><strong>PEP 3129</strong></a> - Class Decorators</dt>
<dd>PEP written by Collin Winter.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3141-a-type-hierarchy-for-numbers">
<span id="pep-3141"></span><h2>PEP 3141: A Type Hierarchy for Numbers<a class="headerlink" href="#pep-3141-a-type-hierarchy-for-numbers" title="Permalink to this headline">¶</a></h2>
<p>Python 3.0 adds several abstract base classes for numeric types
inspired by Scheme’s numeric tower.  These classes were backported to
2.6 as the <a class="reference internal" href="../library/numbers.html#module-numbers" title="numbers: Numeric abstract base classes (Complex, Real, Integral, etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">numbers</span></code></a> module.</p>
<p>The most general ABC is <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>.  It defines no operations at
all, and only exists to allow checking if an object is a number by
doing <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">Number)</span></code>.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code> is a subclass of <code class="xref py py-class docutils literal notranslate"><span class="pre">Number</span></code>.  Complex numbers
can undergo the basic operations of addition, subtraction,
multiplication, division, and exponentiation, and you can retrieve the
real and imaginary parts and obtain a number’s conjugate.  Python’s built-in
complex type is an implementation of <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code> further derives from <code class="xref py py-class docutils literal notranslate"><span class="pre">Complex</span></code>, and adds
operations that only work on real numbers: <code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code>,
rounding, taking the remainder mod N, floor division,
and comparisons.</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Real</span></code>, have
<code class="xref py py-attr docutils literal notranslate"><span class="pre">numerator</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">denominator</span></code> properties, and can be
converted to floats.  Python 2.6 adds a simple rational-number class,
<code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code>, in the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module.  (It’s called
<code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> instead of <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code> to avoid
a name clash with <a class="reference internal" href="../library/numbers.html#numbers.Rational" title="numbers.Rational"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Rational</span></code></a>.)</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> numbers derive from <code class="xref py py-class docutils literal notranslate"><span class="pre">Rational</span></code>, and
can be shifted left and right with <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code> and <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>,
combined using bitwise operations such as <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> and <code class="docutils literal notranslate"><span class="pre">|</span></code>,
and can be used as array indexes and slice boundaries.</p>
<p>In Python 3.0, the PEP slightly redefines the existing builtins
<a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a>, <a class="reference internal" href="../library/math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.floor()</span></code></a>, <a class="reference internal" href="../library/math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.ceil()</span></code></a>, and adds a new
one, <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a>, that’s been backported to Python 2.6.
<a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.trunc()</span></code></a> rounds toward zero, returning the closest
<code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that’s between the function’s argument and zero.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="docutils">
<dt><span class="target" id="index-19"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3141"><strong>PEP 3141</strong></a> - A Type Hierarchy for Numbers</dt>
<dd>PEP written by Jeffrey Yasskin.</dd>
</dl>
<p><a class="reference external" href="https://www.gnu.org/software/guile/manual/html_node/Numerical-Tower.html#Numerical-Tower">Scheme’s numerical tower</a>, from the Guile manual.</p>
<p class="last"><a class="reference external" href="http://schemers.org/Documents/Standards/R5RS/HTML/r5rs-Z-H-9.html#%_sec_6.2">Scheme’s number datatypes</a> from the R5RS Scheme specification.</p>
</div>
<div class="section" id="the-fractions-module">
<h3>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> Module<a class="headerlink" href="#the-fractions-module" title="Permalink to this headline">¶</a></h3>
<p>To fill out the hierarchy of numeric types, the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a>
module provides a rational-number class.  Rational numbers store their
values as a numerator and denominator forming a fraction, and can
exactly represent numbers such as <code class="docutils literal notranslate"><span class="pre">2/3</span></code> that floating-point numbers
can only approximate.</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code> constructor takes two <code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> values
that will be the numerator and denominator of the resulting fraction.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fractions</span> <span class="k">import</span> <span class="n">Fraction</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="n">Fraction</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">a</span><span class="p">),</span> <span class="nb">float</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="go">(0.66666666666666663, 0.40000000000000002)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">+</span><span class="n">b</span>
<span class="go">Fraction(16, 15)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">/</span><span class="n">b</span>
<span class="go">Fraction(5, 3)</span>
</pre></div>
</div>
<p>For converting floating-point numbers to rationals,
the float type now has an <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_integer_ratio()</span></code> method that returns
the numerator and denominator for a fraction that evaluates to the same
floating-point value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">2.5</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(5, 2)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">3.1415</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(7074029114692207L, 2251799813685248L)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span><span class="p">)</span> <span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
<span class="go">(6004799503160661L, 18014398509481984L)</span>
</pre></div>
</div>
<p>Note that values that can only be approximated by floating-point
numbers, such as 1./3, are not simplified to the number being
approximated; the fraction attempts to match the floating-point value
<strong>exactly</strong>.</p>
<p>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module is based upon an implementation by Sjoerd
Mullender that was in Python’s <code class="file docutils literal notranslate"><span class="pre">Demo/classes/</span></code> directory for a
long time.  This implementation was significantly updated by Jeffrey
Yasskin.</p>
</div>
</div>
<div class="section" id="other-language-changes">
<h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Some smaller changes made to the core Python language are:</p>
<ul>
<li><p class="first">Directories and zip archives containing a <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code> file
can now be executed directly by passing their name to the
interpreter. The directory or zip archive is automatically inserted
as the first entry in sys.path.  (Suggestion and initial patch by
Andy Chu, subsequently revised by Phillip J. Eby and Nick Coghlan;
<a class="reference external" href="https://bugs.python.org/issue1739468">bpo-1739468</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> function was catching and ignoring all errors,
under the assumption that they meant a <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method
was failing somehow and the return value of <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a> would
therefore be <code class="docutils literal notranslate"><span class="pre">False</span></code>.  This logic shouldn’t be applied to
<a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> and <a class="reference internal" href="../library/exceptions.html#exceptions.SystemExit" title="exceptions.SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a>, however; Python 2.6
will no longer discard such exceptions when <a class="reference internal" href="../library/functions.html#hasattr" title="hasattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">hasattr()</span></code></a>
encounters them.  (Fixed by Benjamin Peterson; <a class="reference external" href="https://bugs.python.org/issue2196">bpo-2196</a>.)</p>
</li>
<li><p class="first">When calling a function using the <code class="docutils literal notranslate"><span class="pre">**</span></code> syntax to provide keyword
arguments, you are no longer required to use a Python dictionary;
any mapping will now work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">... </span>   <span class="nb">print</span> <span class="nb">sorted</span><span class="p">(</span><span class="n">kw</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="o">=</span><span class="n">UserDict</span><span class="o">.</span><span class="n">UserDict</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;a&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ud</span><span class="p">[</span><span class="s1">&#39;b&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;string&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="o">**</span><span class="n">ud</span><span class="p">)</span>
<span class="go">[&#39;a&#39;, &#39;b&#39;]</span>
</pre></div>
</div>
<p>(Contributed by Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue1686487">bpo-1686487</a>.)</p>
<p>It’s also become legal to provide keyword arguments after a <code class="docutils literal notranslate"><span class="pre">*args</span></code> argument
to a function call.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">,</span> <span class="o">**</span><span class="n">kw</span><span class="p">):</span>
<span class="gp">... </span>    <span class="nb">print</span> <span class="n">args</span><span class="p">,</span> <span class="n">kw</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span> <span class="o">*</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">),</span> <span class="n">keyword</span><span class="o">=</span><span class="mi">13</span><span class="p">)</span>
<span class="go">(1, 2, 3, 4, 5, 6) {&#39;keyword&#39;: 13}</span>
</pre></div>
</div>
<p>Previously this would have been a syntax error.
(Contributed by Amaury Forgeot d’Arc; <a class="reference external" href="https://bugs.python.org/issue3473">bpo-3473</a>.)</p>
</li>
<li><p class="first">A new builtin, <code class="docutils literal notranslate"><span class="pre">next(iterator,</span> <span class="pre">[default])</span></code> returns the next item
from the specified iterator.  If the <em>default</em> argument is supplied,
it will be returned if <em>iterator</em> has been exhausted; otherwise,
the <a class="reference internal" href="../library/exceptions.html#exceptions.StopIteration" title="exceptions.StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception will be raised.  (Backported
in <a class="reference external" href="https://bugs.python.org/issue2719">bpo-2719</a>.)</p>
</li>
<li><p class="first">Tuples now have <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods matching the
list type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code> methods:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">t</span> <span class="o">=</span> <span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="go">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">t</span><span class="o">.</span><span class="n">count</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="go">2</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger)</p>
</li>
<li><p class="first">The built-in types now have improved support for extended slicing syntax,
accepting various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code>.
Previously, the support was partial and certain corner cases wouldn’t work.
(Implemented by Thomas Wouters.)</p>
</li>
<li><p class="first">Properties now have three attributes, <code class="xref py py-attr docutils literal notranslate"><span class="pre">getter</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">setter</span></code>
and <code class="xref py py-attr docutils literal notranslate"><span class="pre">deleter</span></code>, that are decorators providing useful shortcuts
for adding a getter, setter or deleter function to an existing
property. You would use them like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span>
    <span class="nd">@property</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>

    <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span>

    <span class="nd">@x</span><span class="o">.</span><span class="n">deleter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">del</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span>

<span class="k">class</span> <span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
    <span class="nd">@C</span><span class="o">.</span><span class="n">x</span><span class="o">.</span><span class="n">getter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">*</span> <span class="mi">2</span>

    <span class="nd">@x</span><span class="o">.</span><span class="n">setter</span>
    <span class="k">def</span> <span class="nf">x</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">_x</span> <span class="o">=</span> <span class="n">value</span> <span class="o">/</span> <span class="mi">2</span>
</pre></div>
</div>
</li>
<li><p class="first">Several methods of the built-in set types now accept multiple iterables:
<code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">intersection_update()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">union()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">difference()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">difference_update()</span></code>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">=</span><span class="nb">set</span><span class="p">(</span><span class="s1">&#39;1234567890&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">intersection</span><span class="p">(</span><span class="s1">&#39;abc123&#39;</span><span class="p">,</span> <span class="s1">&#39;cdf246&#39;</span><span class="p">)</span>  <span class="c1"># Intersection between all inputs</span>
<span class="go">set([&#39;2&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">s</span><span class="o">.</span><span class="n">difference</span><span class="p">(</span><span class="s1">&#39;246&#39;</span><span class="p">,</span> <span class="s1">&#39;789&#39;</span><span class="p">)</span>
<span class="go">set([&#39;1&#39;, &#39;0&#39;, &#39;3&#39;, &#39;5&#39;])</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Many floating-point features were added.  The <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> function
will now turn the string <code class="docutils literal notranslate"><span class="pre">nan</span></code> into an
IEEE 754 Not A Number value, and <code class="docutils literal notranslate"><span class="pre">+inf</span></code> and <code class="docutils literal notranslate"><span class="pre">-inf</span></code> into
positive or negative infinity.  This works on any platform with
IEEE 754 semantics.  (Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1635">bpo-1635</a>.)</p>
<p>Other functions in the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module, <code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> and
<code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code>, return true if their floating-point argument is
infinite or Not A Number.  (<a class="reference external" href="https://bugs.python.org/issue1640">bpo-1640</a>)</p>
<p>Conversion functions were added to convert floating-point numbers
into hexadecimal strings (<a class="reference external" href="https://bugs.python.org/issue3008">bpo-3008</a>).  These functions
convert floats to and from a string representation without
introducing rounding errors from the conversion between decimal and
binary.  Floats have a <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">hex()</span></code></a> method that returns a string
representation, and the <code class="docutils literal notranslate"><span class="pre">float.fromhex()</span></code> method converts a string
back into a number:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="mf">3.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">a</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;0x1.e000000000000p+1&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">&#39;0x1.e000000000000p+1&#39;</span><span class="p">)</span>
<span class="go">3.75</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">=</span><span class="mf">1.</span><span class="o">/</span><span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
<span class="go">&#39;0x1.5555555555555p-2&#39;</span>
</pre></div>
</div>
</li>
<li><p class="first">A numerical nicety: when creating a complex number from two floats
on systems that support signed zeros (-0 and +0), the
<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor will now preserve the sign
of the zero.  (Fixed by Mark T. Dickinson; <a class="reference external" href="https://bugs.python.org/issue1507">bpo-1507</a>.)</p>
</li>
<li><p class="first">Classes that inherit a <a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method from a parent class
can set <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> to indicate that the class isn’t
hashable.  This will make <code class="docutils literal notranslate"><span class="pre">hash(obj)</span></code> raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>
and the class will not be indicated as implementing the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Hashable</span></code> ABC.</p>
<p>You should do this when you’ve defined a <a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> or
<a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method that compares objects by their value rather
than by identity.  All objects have a default hash method that uses
<code class="docutils literal notranslate"><span class="pre">id(obj)</span></code> as the hash value.  There’s no tidy way to remove the
<a class="reference internal" href="../reference/datamodel.html#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method inherited from a parent class, so
assigning <code class="docutils literal notranslate"><span class="pre">None</span></code> was implemented as an override.  At the
C level, extensions can set <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> to
<a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.
(Fixed by Nick Coghlan and Amaury Forgeot d’Arc; <a class="reference external" href="https://bugs.python.org/issue2235">bpo-2235</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> exception now subclasses
<a class="reference internal" href="../library/exceptions.html#exceptions.BaseException" title="exceptions.BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> instead of <a class="reference internal" href="../library/exceptions.html#exceptions.Exception" title="exceptions.Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>.  This means
that an exception handler that does <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">Exception:</span></code>
will not inadvertently catch <a class="reference internal" href="../library/exceptions.html#exceptions.GeneratorExit" title="exceptions.GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a>.
(Contributed by Chad Austin; <a class="reference external" href="https://bugs.python.org/issue1537">bpo-1537</a>.)</p>
</li>
<li><p class="first">Generator objects now have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">gi_code</span></code> attribute that refers to
the original code object backing the generator.
(Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue1473257">bpo-1473257</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in function now accepts keyword arguments
as well as positional parameters.  (Contributed by Thomas Wouters;
<a class="reference external" href="https://bugs.python.org/issue1444529">bpo-1444529</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> constructor now accepts strings containing
parenthesized complex numbers, meaning that <code class="docutils literal notranslate"><span class="pre">complex(repr(cplx))</span></code>
will now round-trip values.  For example, <code class="docutils literal notranslate"><span class="pre">complex('(3+4j)')</span></code>
now returns the value (3+4j).  (<a class="reference external" href="https://bugs.python.org/issue1491866">bpo-1491866</a>)</p>
</li>
<li><p class="first">The string <code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code> method now accepts <code class="docutils literal notranslate"><span class="pre">None</span></code> as the
translation table parameter, which is treated as the identity
transformation.   This makes it easier to carry out operations
that only delete characters.  (Contributed by Bengt Richter and
implemented by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue1193128">bpo-1193128</a>.)</p>
</li>
<li><p class="first">The built-in <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> function now checks for a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__dir__()</span></code>
method on the objects it receives.  This method must return a list
of strings containing the names of valid attributes for the object,
and lets the object control the value that <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> produces.
Objects that have <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a>
methods can use this to advertise pseudo-attributes they will honor.
(<a class="reference external" href="https://bugs.python.org/issue1591665">bpo-1591665</a>)</p>
</li>
<li><p class="first">Instance method objects have new attributes for the object and function
comprising the method; the new synonym for <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_self</span></code> is
<code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">im_func</span></code> is also available as <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code>.
The old names are still supported in Python 2.6, but are gone in 3.0.</p>
</li>
<li><p class="first">An obscure change: when you use the <a class="reference internal" href="../library/functions.html#locals" title="locals"><code class="xref py py-func docutils literal notranslate"><span class="pre">locals()</span></code></a> function inside a
<a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statement, the resulting dictionary no longer returns free
variables.  (Free variables, in this case, are variables referenced in the
<a class="reference internal" href="../reference/compound_stmts.html#class"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">class</span></code></a> statement  that aren’t attributes of the class.)</p>
</li>
</ul>
<div class="section" id="optimizations">
<h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module has been rewritten in C.  This makes
it possible to invoke warnings from the parser, and may also
make the interpreter’s startup faster.
(Contributed by Neal Norwitz and Brett Cannon; <a class="reference external" href="https://bugs.python.org/issue1631171">bpo-1631171</a>.)</p>
</li>
<li><p class="first">Type objects now have a cache of methods that can reduce
the work required to find the correct method implementation
for a particular class; once cached, the interpreter doesn’t need to
traverse base classes to figure out the right method to call.
The cache is cleared if a base class or the class itself is modified,
so the cache should remain correct even in the face of Python’s dynamic
nature.
(Original optimization implemented by Armin Rigo, updated for
Python 2.6 by Kevin Jacobs; <a class="reference external" href="https://bugs.python.org/issue1700288">bpo-1700288</a>.)</p>
<p>By default, this change is only applied to types that are included with
the Python core.  Extension modules may not necessarily be compatible with
this cache,
so they must explicitly add <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TPFLAGS_HAVE_VERSION_TAG</span></code>
to the module’s <code class="docutils literal notranslate"><span class="pre">tp_flags</span></code> field to enable the method cache.
(To be compatible with the method cache, the extension module’s code
must not directly access and modify the <code class="docutils literal notranslate"><span class="pre">tp_dict</span></code> member of
any of the types it implements.  Most modules don’t do this,
but it’s impossible for the Python interpreter to determine that.
See <a class="reference external" href="https://bugs.python.org/issue1878">bpo-1878</a> for some discussion.)</p>
</li>
<li><p class="first">Function calls that use keyword arguments are significantly faster
by doing a quick pointer comparison, usually saving the time of a
full string comparison.  (Contributed by Raymond Hettinger, after an
initial implementation by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue1819">bpo-1819</a>.)</p>
</li>
<li><p class="first">All of the functions in the <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module have been rewritten in
C, thanks to work at the Need For Speed sprint.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Some of the standard built-in types now set a bit in their type
objects.  This speeds up checking whether an object is a subclass of
one of these types.  (Contributed by Neal Norwitz.)</p>
</li>
<li><p class="first">Unicode strings now use faster code for detecting
whitespace and line breaks; this speeds up the <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code> method
by about 25% and <code class="xref py py-meth docutils literal notranslate"><span class="pre">splitlines()</span></code> by 35%.
(Contributed by Antoine Pitrou.)  Memory usage is reduced
by using pymalloc for the Unicode string’s data.</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement now stores the <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> method on the stack,
producing a small speedup.  (Implemented by Jeffrey Yasskin.)</p>
</li>
<li><p class="first">To reduce memory usage, the garbage collector will now clear internal
free lists when garbage-collecting the highest generation of objects.
This may return memory to the operating system sooner.</p>
</li>
</ul>
</div>
<div class="section" id="interpreter-changes">
<span id="new-26-interpreter"></span><h3>Interpreter Changes<a class="headerlink" href="#interpreter-changes" title="Permalink to this headline">¶</a></h3>
<p>Two command-line options have been reserved for use by other Python
implementations.  The <a class="reference internal" href="../using/cmdline.html#cmdoption-j"><code class="xref std std-option docutils literal notranslate"><span class="pre">-J</span></code></a> switch has been reserved for use by
Jython for Jython-specific options, such as switches that are passed to
the underlying JVM.  <a class="reference internal" href="../using/cmdline.html#id5"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> has been reserved for options
specific to a particular implementation of Python such as CPython,
Jython, or IronPython.  If either option is used with Python 2.6, the
interpreter will report that the option isn’t currently used.</p>
<p>Python can now be prevented from writing <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code>
files by supplying the <a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a> switch to the Python interpreter,
or by setting the <span class="target" id="index-20"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment
variable before running the interpreter.  This setting is available to
Python programs as the <code class="docutils literal notranslate"><span class="pre">sys.dont_write_bytecode</span></code> variable, and
Python code can change the value to modify the interpreter’s
behaviour.  (Contributed by Neal Norwitz and Georg Brandl.)</p>
<p>The encoding used for standard input, output, and standard error can
be specified by setting the <span class="target" id="index-21"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONIOENCODING"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONIOENCODING</span></code></a> environment
variable before running the interpreter.  The value should be a string
in the form <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;</span></code> or <code class="docutils literal notranslate"><span class="pre">&lt;encoding&gt;:&lt;errorhandler&gt;</span></code>.
The <em>encoding</em> part specifies the encoding’s name, e.g. <code class="docutils literal notranslate"><span class="pre">utf-8</span></code> or
<code class="docutils literal notranslate"><span class="pre">latin-1</span></code>; the optional <em>errorhandler</em> part specifies
what to do with characters that can’t be handled by the encoding,
and  should be one of “error”, “ignore”, or “replace”.   (Contributed
by Martin von Loewis.)</p>
</div>
</div>
<div class="section" id="new-and-improved-modules">
<h2>New and Improved Modules<a class="headerlink" href="#new-and-improved-modules" title="Permalink to this headline">¶</a></h2>
<p>As in every release, Python’s standard library received a number of
enhancements and bug fixes.  Here’s a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
<code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/asyncore.html#module-asyncore" title="asyncore: A base class for developing asynchronous socket handling services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncore</span></code></a> and <a class="reference internal" href="../library/asynchat.html#module-asynchat" title="asynchat: Support for asynchronous command/response protocols."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asynchat</span></code></a> modules are
being actively maintained again, and a number of patches and bugfixes
were applied.  (Maintained by Josiah Carlson; see <a class="reference external" href="https://bugs.python.org/issue1736190">bpo-1736190</a> for
one patch.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module also has a new maintainer, Jesús Cea Avion, and the package
is now available as a standalone package.  The web page for the package is
<a class="reference external" href="https://www.jcea.es/programacion/pybsddb.htm">www.jcea.es/programacion/pybsddb.htm</a>.
The plan is to remove the package from the standard library
in Python 3.0, because its pace of releases is much more frequent than
Python’s.</p>
<p>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb.dbshelve</span></code> module now uses the highest pickling protocol
available, instead of restricting itself to protocol 1.
(Contributed by W. Barnes.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module will now read variables from the query string
of an HTTP POST request.  This makes it possible to use form actions
with URLs that include query strings such as
“/cgi-bin/add.py?category=1”.  (Contributed by Alexandre Fiori and
Nubis; <a class="reference external" href="https://bugs.python.org/issue1817">bpo-1817</a>.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qs()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">parse_qsl()</span></code> functions have been
relocated from the <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module to the <a class="reference internal" href="../library/urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module.
The versions still available in the <a class="reference internal" href="../library/cgi.html#module-cgi" title="cgi: Helpers for running Python scripts via the Common Gateway Interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cgi</span></code></a> module will
trigger <a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a> messages in 2.6
(<a class="reference external" href="https://bugs.python.org/issue600362">bpo-600362</a>).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module underwent extensive revision,
contributed by Mark Dickinson and Christian Heimes.
Five new functions were added:</p>
<ul class="simple">
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">polar()</span></code> converts a complex number to polar form, returning
the modulus and argument of the complex number.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">rect()</span></code> does the opposite, turning a modulus, argument pair
back into the corresponding complex number.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">phase()</span></code> returns the argument (also called the angle) of a complex
number.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code> returns True if either
the real or imaginary part of its argument is a NaN.</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code> returns True if either the real or imaginary part of
its argument is infinite.</li>
</ul>
<p>The revisions also improved the numerical soundness of the
<a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module.  For all functions, the real and imaginary
parts of the results are accurate to within a few units of least
precision (ulps) whenever possible.  See <a class="reference external" href="https://bugs.python.org/issue1381">bpo-1381</a> for the
details.  The branch cuts for <code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code>: and
<code class="xref py py-func docutils literal notranslate"><span class="pre">atan()</span></code> have also been corrected.</p>
<p>The tests for the module have been greatly expanded; nearly 2000 new
test cases exercise the algebraic functions.</p>
<p>On IEEE 754 platforms, the <a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module now handles IEEE 754
special values and floating-point exceptions in a manner consistent
with Annex ‘G’ of the C99 standard.</p>
</li>
<li><p class="first">A new data type in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module: <code class="xref py py-class docutils literal notranslate"><span class="pre">namedtuple(typename,</span>
<span class="pre">fieldnames)</span></code> is a factory function that creates subclasses of the standard tuple
whose fields are accessible by name as well as index.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span> <span class="o">=</span> <span class="n">collections</span><span class="o">.</span><span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;variable&#39;</span><span class="p">,</span>
<span class="gp">... </span>            <span class="s1">&#39;id name type size&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Names are separated by spaces or commas.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># &#39;id, name, type, size&#39; would also work.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">var_type</span><span class="o">.</span><span class="n">_fields</span>
<span class="go">(&#39;id&#39;, &#39;name&#39;, &#39;type&#39;, &#39;size&#39;)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">var</span> <span class="o">=</span> <span class="n">var_type</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;frequency&#39;</span><span class="p">,</span> <span class="s1">&#39;int&#39;</span><span class="p">,</span> <span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">id</span>    <span class="c1"># Equivalent</span>
<span class="go">1 1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">var</span><span class="p">[</span><span class="mi">2</span><span class="p">],</span> <span class="n">var</span><span class="o">.</span><span class="n">type</span>  <span class="c1"># Equivalent</span>
<span class="go">int int</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">var</span><span class="o">.</span><span class="n">_asdict</span><span class="p">()</span>
<span class="go">{&#39;size&#39;: 4, &#39;type&#39;: &#39;int&#39;, &#39;id&#39;: 1, &#39;name&#39;: &#39;frequency&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span> <span class="o">=</span> <span class="n">var</span><span class="o">.</span><span class="n">_replace</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s1">&#39;amplitude&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">v2</span>
<span class="go">variable(id=1, name=&#39;amplitude&#39;, type=&#39;int&#39;, size=4)</span>
</pre></div>
</div>
<p>Several places in the standard library that returned tuples have
been modified to return <code class="xref py py-class docutils literal notranslate"><span class="pre">namedtuple</span></code> instances.  For example,
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">Decimal.as_tuple()</span></code> method now returns a named tuple with
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> fields.</p>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">Another change to the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module is that the
<code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code> type now supports an optional <em>maxlen</em> parameter;
if supplied, the deque’s size will be restricted to no more
than <em>maxlen</em> items.  Adding more items to a full deque causes
old items to be discarded.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">deque</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">=</span><span class="n">deque</span><span class="p">(</span><span class="n">maxlen</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([], maxlen=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">2</span><span class="p">);</span> <span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([1, 2, 3], maxlen=3)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">dq</span>
<span class="go">deque([2, 3, 4], maxlen=3)</span>
</pre></div>
</div>
<p>(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Morsel</span></code> objects now support an
<code class="xref py py-attr docutils literal notranslate"><span class="pre">httponly</span></code> attribute.  In some browsers. cookies with this attribute
set cannot be accessed or manipulated by JavaScript code.
(Contributed by Arvin Schnell; <a class="reference external" href="https://bugs.python.org/issue1638033">bpo-1638033</a>.)</p>
</li>
<li><p class="first">A new window method in the <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> module,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">chgat()</span></code>, changes the display attributes for a certain number of
characters on a single line.  (Contributed by Fabian Kreutz.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="c1"># Boldface text starting at y=0,x=21</span>
<span class="c1"># and affecting the rest of the line.</span>
<span class="n">stdscr</span><span class="o">.</span><span class="n">chgat</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">21</span><span class="p">,</span> <span class="n">curses</span><span class="o">.</span><span class="n">A_BOLD</span><span class="p">)</span>
</pre></div>
</div>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> class in the <a class="reference internal" href="../library/curses.html#module-curses.textpad" title="curses.textpad: Emacs-like input editing in a curses window."><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses.textpad</span></code></a> module
now supports editing in insert mode as well as overwrite mode.
Insert mode is enabled by supplying a true value for the <em>insert_mode</em>
parameter when creating the <code class="xref py py-class docutils literal notranslate"><span class="pre">Textbox</span></code> instance.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">strftime()</span></code> methods now support a
<code class="docutils literal notranslate"><span class="pre">%f</span></code> format code that expands to the number of microseconds in the
object, zero-padded on
the left to six places.  (Contributed by Skip Montanaro; <a class="reference external" href="https://bugs.python.org/issue1158">bpo-1158</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic  Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module was updated to version 1.66 of
<a class="reference external" href="http://speleotrove.com/decimal/decarith.html">the General Decimal Specification</a>.  New features
include some methods for some basic mathematical functions such as
<code class="xref py py-meth docutils literal notranslate"><span class="pre">exp()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">log10()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">exp</span><span class="p">()</span>
<span class="go">Decimal(&quot;2.718281828459045235360287471&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="s2">&quot;2.7182818&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">ln</span><span class="p">()</span>
<span class="go">Decimal(&quot;0.9999999895305022877376682436&quot;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span><span class="o">.</span><span class="n">log10</span><span class="p">()</span>
<span class="go">Decimal(&quot;3&quot;)</span>
</pre></div>
</div>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">as_tuple()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> objects now returns a
named tuple with <code class="xref py py-attr docutils literal notranslate"><span class="pre">sign</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">digits</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">exponent</span></code> fields.</p>
<p>(Implemented by Facundo Batista and Mark Dickinson.  Named tuple
support added by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">SequenceMatcher</span></code> class
now returns named tuples representing matches,
with <code class="xref py py-attr docutils literal notranslate"><span class="pre">a</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">b</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">size</span></code> attributes.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
seconds, was added to the <a class="reference internal" href="../library/ftplib.html#ftplib.FTP" title="ftplib.FTP"><code class="xref py py-class docutils literal notranslate"><span class="pre">ftplib.FTP</span></code></a> class constructor as
well as the <code class="xref py py-meth docutils literal notranslate"><span class="pre">connect()</span></code> method.  (Added by Facundo Batista.)
Also, the <code class="xref py py-class docutils literal notranslate"><span class="pre">FTP</span></code> class’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">storbinary()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">storlines()</span></code> now take an optional <em>callback</em> parameter that
will be called with each block of data after the data has been sent.
(Contributed by Phil Schwartz; <a class="reference external" href="https://bugs.python.org/issue1221598">bpo-1221598</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> built-in function is also available in the
<a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a> module.  In Python 3.0, the builtin has been
dropped and <a class="reference internal" href="../library/functions.html#reduce" title="reduce"><code class="xref py py-func docutils literal notranslate"><span class="pre">reduce()</span></code></a> is only available from <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a>;
currently there are no plans to drop the builtin in the 2.x series.
(Patched by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1739906">bpo-1739906</a>.)</p>
</li>
<li><p class="first">When possible, the <a class="reference internal" href="../library/getpass.html#module-getpass" title="getpass: Portable reading of passwords and retrieval of the userid."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getpass</span></code></a> module will now use
<code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> to print a prompt message and read the password,
falling back to standard error and standard input.  If the
password may be echoed to the terminal, a warning is printed before
the prompt is displayed.  (Contributed by Gregory P. Smith.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/glob.html#glob.glob" title="glob.glob"><code class="xref py py-func docutils literal notranslate"><span class="pre">glob.glob()</span></code></a> function can now return Unicode filenames if
a Unicode path was used and Unicode filenames are matched within the
directory.  (<a class="reference external" href="https://bugs.python.org/issue1001604">bpo-1001604</a>)</p>
</li>
<li><p class="first">A new function in the <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module, <code class="docutils literal notranslate"><span class="pre">merge(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...)</span></code>,
takes any number of iterables returning data in sorted
order, and returns a new generator that returns the contents of all
the iterators, also in sorted order.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">heapq</span><span class="o">.</span><span class="n">merge</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">9</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">16</span><span class="p">]))</span>
<span class="go">[1, 2, 3, 5, 8, 9, 16]</span>
</pre></div>
</div>
<p>Another new function, <code class="docutils literal notranslate"><span class="pre">heappushpop(heap,</span> <span class="pre">item)</span></code>,
pushes <em>item</em> onto <em>heap</em>, then pops off and returns the smallest item.
This is more efficient than making a call to <code class="xref py py-func docutils literal notranslate"><span class="pre">heappush()</span></code> and then
<code class="xref py py-func docutils literal notranslate"><span class="pre">heappop()</span></code>.</p>
<p><a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> is now implemented to only use less-than comparison,
instead of the less-than-or-equal comparison it previously used.
This makes <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a>’s usage of a type match the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">list.sort()</span></code> method.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter, specifying a timeout measured in
seconds, was added to the <a class="reference internal" href="../library/httplib.html#httplib.HTTPConnection" title="httplib.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">httplib.HTTPConnection</span></code></a> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSConnection</span></code> class constructors.  (Added by Facundo
Batista.)</p>
</li>
<li><p class="first">Most of the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module’s functions, such as
<code class="xref py py-func docutils literal notranslate"><span class="pre">getmoduleinfo()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getargs()</span></code>, now return named tuples.
In addition to behaving like tuples, the elements of the  return value
can also be accessed as attributes.
(Contributed by Raymond Hettinger.)</p>
<p>Some new functions in the module include
<code class="xref py py-func docutils literal notranslate"><span class="pre">isgenerator()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">isgeneratorfunction()</span></code>,
and <code class="xref py py-func docutils literal notranslate"><span class="pre">isabstract()</span></code>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> module gained several new functions.</p>
<p><code class="docutils literal notranslate"><span class="pre">izip_longest(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...[,</span> <span class="pre">fillvalue])</span></code> makes tuples from
each of the elements; if some of the iterables are shorter than
others, the missing values are set to <em>fillvalue</em>.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">tuple</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">izip_longest</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">]))</span>
<span class="go">((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">product(iter1,</span> <span class="pre">iter2,</span> <span class="pre">...,</span> <span class="pre">[repeat=N])</span></code> returns the Cartesian product
of the supplied iterables, a set of tuples containing
every possible combination of the elements returned from each iterable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">]))</span>
<span class="go">[(1, 4), (1, 5), (1, 6),</span>
<span class="go"> (2, 4), (2, 5), (2, 6),</span>
<span class="go"> (3, 4), (3, 5), (3, 6)]</span>
</pre></div>
</div>
<p>The optional <em>repeat</em> keyword argument is used for taking the
product of an iterable or a set of iterables with themselves,
repeated <em>N</em> times.  With a single iterable argument, <em>N</em>-tuples
are returned:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">3</span><span class="p">))</span>
<span class="go">[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),</span>
<span class="go"> (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]</span>
</pre></div>
</div>
<p>With two iterables, <em>2N</em>-tuples are returned.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">product</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">],</span> <span class="p">[</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="n">repeat</span><span class="o">=</span><span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),</span>
<span class="go"> (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),</span>
<span class="go"> (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),</span>
<span class="go"> (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">combinations(iterable,</span> <span class="pre">r)</span></code> returns sub-sequences of length <em>r</em> from
the elements of <em>iterable</em>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;), (&#39;1&#39;, &#39;3&#39;), (&#39;2&#39;, &#39;3&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;123&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations</span><span class="p">(</span><span class="s1">&#39;1234&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="go">[(&#39;1&#39;, &#39;2&#39;, &#39;3&#39;), (&#39;1&#39;, &#39;2&#39;, &#39;4&#39;),</span>
<span class="go"> (&#39;1&#39;, &#39;3&#39;, &#39;4&#39;), (&#39;2&#39;, &#39;3&#39;, &#39;4&#39;)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">permutations(iter[,</span> <span class="pre">r])</span></code> returns all the permutations of length <em>r</em> of
the iterable’s elements.  If <em>r</em> is not specified, it will default to the
number of elements produced by the iterable.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">permutations</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">,</span><span class="mi">4</span><span class="p">],</span> <span class="mi">2</span><span class="p">))</span>
<span class="go">[(1, 2), (1, 3), (1, 4),</span>
<span class="go"> (2, 1), (2, 3), (2, 4),</span>
<span class="go"> (3, 1), (3, 2), (3, 4),</span>
<span class="go"> (4, 1), (4, 2), (4, 3)]</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">itertools.chain(*iterables)</span></code> is an existing function in
<a class="reference internal" href="../library/itertools.html#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code class="xref py py-mod docutils literal notranslate"><span class="pre">itertools</span></code></a> that gained a new constructor in Python 2.6.
<code class="docutils literal notranslate"><span class="pre">itertools.chain.from_iterable(iterable)</span></code> takes a single
iterable that should return other iterables.  <code class="xref py py-func docutils literal notranslate"><span class="pre">chain()</span></code> will
then return all the elements of the first iterable, then
all the elements of the second, and so on.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">itertools</span><span class="o">.</span><span class="n">chain</span><span class="o">.</span><span class="n">from_iterable</span><span class="p">([[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">],</span> <span class="p">[</span><span class="mi">4</span><span class="p">,</span><span class="mi">5</span><span class="p">,</span><span class="mi">6</span><span class="p">]]))</span>
<span class="go">[1, 2, 3, 4, 5, 6]</span>
</pre></div>
</div>
<p>(All contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">FileHandler</span></code> class
and its subclasses <code class="xref py py-class docutils literal notranslate"><span class="pre">WatchedFileHandler</span></code>, <code class="xref py py-class docutils literal notranslate"><span class="pre">RotatingFileHandler</span></code>,
and <code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> now
have an optional <em>delay</em> parameter to their constructors.  If <em>delay</em>
is true, opening of the log file is deferred until the first
<code class="xref py py-meth docutils literal notranslate"><span class="pre">emit()</span></code> call is made.  (Contributed by Vinay Sajip.)</p>
<p><code class="xref py py-class docutils literal notranslate"><span class="pre">TimedRotatingFileHandler</span></code> also has a <em>utc</em> constructor
parameter.  If the argument is true, UTC time will be used
in determining when midnight occurs and in generating filenames;
otherwise local time will be used.</p>
</li>
<li><p class="first">Several new functions were added to the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/math.html#math.isinf" title="math.isinf"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinf()</span></code></a> and <a class="reference internal" href="../library/math.html#math.isnan" title="math.isnan"><code class="xref py py-func docutils literal notranslate"><span class="pre">isnan()</span></code></a> determine whether a given float
is a (positive or negative) infinity or a NaN (Not a Number), respectively.</li>
<li><a class="reference internal" href="../library/math.html#math.copysign" title="math.copysign"><code class="xref py py-func docutils literal notranslate"><span class="pre">copysign()</span></code></a> copies the sign bit of an IEEE 754 number,
returning the absolute value of <em>x</em> combined with the sign bit of
<em>y</em>.  For example, <code class="docutils literal notranslate"><span class="pre">math.copysign(1,</span> <span class="pre">-0.0)</span></code> returns -1.0.
(Contributed by Christian Heimes.)</li>
<li><a class="reference internal" href="../library/math.html#math.factorial" title="math.factorial"><code class="xref py py-func docutils literal notranslate"><span class="pre">factorial()</span></code></a> computes the factorial of a number.
(Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue2138">bpo-2138</a>.)</li>
<li><a class="reference internal" href="../library/math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">fsum()</span></code></a> adds up the stream of numbers from an iterable,
and is careful to avoid loss of precision through using partial sums.
(Contributed by Jean Brouwers, Raymond Hettinger, and Mark Dickinson;
<a class="reference external" href="https://bugs.python.org/issue2819">bpo-2819</a>.)</li>
<li><a class="reference internal" href="../library/math.html#math.acosh" title="math.acosh"><code class="xref py py-func docutils literal notranslate"><span class="pre">acosh()</span></code></a>, <a class="reference internal" href="../library/math.html#math.asinh" title="math.asinh"><code class="xref py py-func docutils literal notranslate"><span class="pre">asinh()</span></code></a>
and <a class="reference internal" href="../library/math.html#math.atanh" title="math.atanh"><code class="xref py py-func docutils literal notranslate"><span class="pre">atanh()</span></code></a> compute the inverse hyperbolic functions.</li>
<li><a class="reference internal" href="../library/math.html#math.log1p" title="math.log1p"><code class="xref py py-func docutils literal notranslate"><span class="pre">log1p()</span></code></a> returns the natural logarithm of <em>1+x</em>
(base <em>e</em>).</li>
<li><code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code> rounds a number toward zero, returning the closest
<code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code> that’s between the function’s argument and zero.
Added as part of the backport of
<a class="reference external" href="#pep-3141">PEP 3141’s type hierarchy for numbers</a>.</li>
</ul>
</li>
<li><p class="first">The <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module has been improved to give more consistent
behaviour across platforms, especially with respect to handling of
floating-point exceptions and IEEE 754 special values.</p>
<p>Whenever possible, the module follows the recommendations of the C99
standard about 754’s special values.  For example, <code class="docutils literal notranslate"><span class="pre">sqrt(-1.)</span></code>
should now give a <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> across almost all platforms,
while <code class="docutils literal notranslate"><span class="pre">sqrt(float('NaN'))</span></code> should return a NaN on all IEEE 754
platforms.  Where Annex ‘F’ of the C99 standard recommends signaling
‘divide-by-zero’ or ‘invalid’, Python will raise <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a>.
Where Annex ‘F’ of the C99 standard recommends signaling ‘overflow’,
Python will raise <a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>.  (See <a class="reference external" href="https://bugs.python.org/issue711019">bpo-711019</a> and
<a class="reference external" href="https://bugs.python.org/issue1640">bpo-1640</a>.)</p>
<p>(Contributed by Christian Heimes and Mark Dickinson.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/mmap.html#mmap.mmap" title="mmap.mmap"><code class="xref py py-class docutils literal notranslate"><span class="pre">mmap</span></code></a> objects now have a <code class="xref py py-meth docutils literal notranslate"><span class="pre">rfind()</span></code> method that searches for a
substring beginning at the end of the string and searching
backwards.  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">find()</span></code> method also gained an <em>end</em> parameter
giving an index at which to stop searching.
(Contributed by John Lenton.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/operator.html#module-operator" title="operator: Functions corresponding to the standard operators."><code class="xref py py-mod docutils literal notranslate"><span class="pre">operator</span></code></a> module gained a
<code class="xref py py-func docutils literal notranslate"><span class="pre">methodcaller()</span></code> function that takes a name and an optional
set of arguments, returning a callable that will call
the named function on any arguments passed to it.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># Equivalent to lambda s: s.replace(&#39;old&#39;, &#39;new&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">methodcaller</span><span class="p">(</span><span class="s1">&#39;replace&#39;</span><span class="p">,</span> <span class="s1">&#39;old&#39;</span><span class="p">,</span> <span class="s1">&#39;new&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">replacer</span><span class="p">(</span><span class="s1">&#39;old wine in old bottles&#39;</span><span class="p">)</span>
<span class="go">&#39;new wine in new bottles&#39;</span>
</pre></div>
</div>
<p>(Contributed by Georg Brandl, after a suggestion by Gregory Petrosyan.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">attrgetter()</span></code> function now accepts dotted names and performs
the corresponding attribute lookups:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span> <span class="o">=</span> <span class="n">operator</span><span class="o">.</span><span class="n">attrgetter</span><span class="p">(</span>
<span class="gp">... </span>       <span class="s1">&#39;__class__.__name__&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="s1">&#39;&#39;</span><span class="p">)</span>
<span class="go">&#39;str&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">inst_name</span><span class="p">(</span><span class="n">help</span><span class="p">)</span>
<span class="go">&#39;_Helper&#39;</span>
</pre></div>
</div>
<p>(Contributed by Georg Brandl, after a suggestion by Barry Warsaw.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module now wraps several new system calls.
<code class="docutils literal notranslate"><span class="pre">fchmod(fd,</span> <span class="pre">mode)</span></code> and <code class="docutils literal notranslate"><span class="pre">fchown(fd,</span> <span class="pre">uid,</span> <span class="pre">gid)</span></code> change the mode
and ownership of an opened file, and <code class="docutils literal notranslate"><span class="pre">lchmod(path,</span> <span class="pre">mode)</span></code> changes
the mode of a symlink.  (Contributed by Georg Brandl and Christian
Heimes.)</p>
<p><code class="xref py py-func docutils literal notranslate"><span class="pre">chflags()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">lchflags()</span></code> are wrappers for the
corresponding system calls (where they’re available), changing the
flags set on a file.  Constants for the flag values are defined in
the <a class="reference internal" href="../library/stat.html#module-stat" title="stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat()."><code class="xref py py-mod docutils literal notranslate"><span class="pre">stat</span></code></a> module; some possible values include
<code class="xref py py-const docutils literal notranslate"><span class="pre">UF_IMMUTABLE</span></code> to signal the file may not be changed and
<code class="xref py py-const docutils literal notranslate"><span class="pre">UF_APPEND</span></code> to indicate that data can only be appended to the
file.  (Contributed by M. Levinson.)</p>
<p><code class="docutils literal notranslate"><span class="pre">os.closerange(low,</span> <span class="pre">high)</span></code> efficiently closes all file descriptors
from <em>low</em> to <em>high</em>, ignoring any errors and not including <em>high</em> itself.
This function is now used by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module to make starting
processes faster.  (Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue1663329">bpo-1663329</a>.)</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">os.environ</span></code> object’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code> method will now unset the
environment variables using <a class="reference internal" href="../library/os.html#os.unsetenv" title="os.unsetenv"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unsetenv()</span></code></a> in addition to clearing
the object’s keys.  (Contributed by Martin Horcicka; <a class="reference external" href="https://bugs.python.org/issue1181">bpo-1181</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/os.html#os.walk" title="os.walk"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.walk()</span></code></a> function now has a <code class="docutils literal notranslate"><span class="pre">followlinks</span></code> parameter. If
set to True, it will follow symlinks pointing to directories and
visit the directory’s contents.  For backward compatibility, the
parameter’s default value is false.  Note that the function can fall
into an infinite recursion if there’s a symlink that points to a
parent directory.  (<a class="reference external" href="https://bugs.python.org/issue1273829">bpo-1273829</a>)</p>
</li>
<li><p class="first">In the <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, the <code class="xref py py-func docutils literal notranslate"><span class="pre">splitext()</span></code> function
has been changed to not split on leading period characters.
This produces better results when operating on Unix’s dot-files.
For example, <code class="docutils literal notranslate"><span class="pre">os.path.splitext('.ipython')</span></code>
now returns <code class="docutils literal notranslate"><span class="pre">('.ipython',</span> <span class="pre">'')</span></code> instead of <code class="docutils literal notranslate"><span class="pre">('',</span> <span class="pre">'.ipython')</span></code>.
(<a class="reference external" href="https://bugs.python.org/issue1115886">bpo-1115886</a>)</p>
<p>A new function, <code class="docutils literal notranslate"><span class="pre">os.path.relpath(path,</span> <span class="pre">start='.')</span></code>, returns a relative path
from the <code class="docutils literal notranslate"><span class="pre">start</span></code> path, if it’s supplied, or from the current
working directory to the destination <code class="docutils literal notranslate"><span class="pre">path</span></code>.  (Contributed by
Richard Barran; <a class="reference external" href="https://bugs.python.org/issue1339796">bpo-1339796</a>.)</p>
<p>On Windows, <a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables
given in the form “%var%”, and “~user” will be expanded into the
user’s home directory path.  (Contributed by Josiah Carlson;
<a class="reference external" href="https://bugs.python.org/issue957650">bpo-957650</a>.)</p>
</li>
<li><p class="first">The Python debugger provided by the <a class="reference internal" href="../library/pdb.html#module-pdb" title="pdb: The Python debugger for interactive interpreters."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pdb</span></code></a> module
gained a new command: “run” restarts the Python program being debugged
and can optionally take new command-line arguments for the program.
(Contributed by Rocky Bernstein; <a class="reference external" href="https://bugs.python.org/issue1393667">bpo-1393667</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pdb.html#pdb.post_mortem" title="pdb.post_mortem"><code class="xref py py-func docutils literal notranslate"><span class="pre">pdb.post_mortem()</span></code></a> function, used to begin debugging a
traceback, will now use the traceback returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>
if no traceback is supplied.   (Contributed by Facundo Batista;
<a class="reference external" href="https://bugs.python.org/issue1106316">bpo-1106316</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pickletools.html#module-pickletools" title="pickletools: Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickletools</span></code></a> module now has an <code class="xref py py-func docutils literal notranslate"><span class="pre">optimize()</span></code> function
that takes a string containing a pickle and removes some unused
opcodes, returning a shorter pickle that contains the same data structure.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">A <code class="xref py py-func docutils literal notranslate"><span class="pre">get_data()</span></code> function was added to the <a class="reference internal" href="../library/pkgutil.html#module-pkgutil" title="pkgutil: Utilities for the import system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pkgutil</span></code></a>
module that returns the contents of resource files included
with an installed Python package.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">pkgutil</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">pkgutil</span><span class="o">.</span><span class="n">get_data</span><span class="p">(</span><span class="s1">&#39;test&#39;</span><span class="p">,</span> <span class="s1">&#39;exception_hierarchy.txt&#39;</span><span class="p">)</span>
<span class="go">BaseException</span>
<span class="go"> +-- SystemExit</span>
<span class="go"> +-- KeyboardInterrupt</span>
<span class="go"> +-- GeneratorExit</span>
<span class="go"> +-- Exception</span>
<span class="go">      +-- StopIteration</span>
<span class="go">      +-- StandardError</span>
<span class="go"> ...</span>
</pre></div>
</div>
<p>(Contributed by Paul Moore; <a class="reference external" href="https://bugs.python.org/issue2439">bpo-2439</a>.)</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Parser</span></code> objects now allow setting
their <code class="xref py py-attr docutils literal notranslate"><span class="pre">buffer_size</span></code> attribute to change the size of the buffer
used to hold character data.
(Contributed by Achim Gaedke; <a class="reference external" href="https://bugs.python.org/issue1137">bpo-1137</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/queue.html#module-Queue" title="Queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Queue</span></code></a> module now provides queue variants that retrieve entries
in different orders.  The <code class="xref py py-class docutils literal notranslate"><span class="pre">PriorityQueue</span></code> class stores
queued items in a heap and retrieves them in priority order,
and <code class="xref py py-class docutils literal notranslate"><span class="pre">LifoQueue</span></code> retrieves the most recently added entries first,
meaning that it behaves like a stack.
(Contributed by Raymond Hettinger.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can
now be pickled on a 32-bit system and unpickled on a 64-bit
system, and vice versa.  Unfortunately, this change also means
that Python 2.6’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Random</span></code> objects can’t be unpickled correctly
on earlier versions of Python.
(Contributed by Shawn Ligocki; <a class="reference external" href="https://bugs.python.org/issue1727780">bpo-1727780</a>.)</p>
<p>The new <code class="docutils literal notranslate"><span class="pre">triangular(low,</span> <span class="pre">high,</span> <span class="pre">mode)</span></code> function returns random
numbers following a triangular distribution.   The returned values
are between <em>low</em> and <em>high</em>, not including <em>high</em> itself, and
with <em>mode</em> as the most frequently occurring value
in the distribution.  (Contributed by Wladmir van der Laan and
Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue1681432">bpo-1681432</a>.)</p>
</li>
<li><p class="first">Long regular expression searches carried out by the  <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a>
module will check for signals being delivered, so
time-consuming searches can now be interrupted.
(Contributed by Josh Hoyt and Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue846388">bpo-846388</a>.)</p>
<p>The regular expression module is implemented by compiling bytecodes
for a tiny regex-specific virtual machine.  Untrusted code
could create malicious strings of bytecode directly and cause crashes,
so Python 2.6 includes a verifier for the regex bytecode.
(Contributed by Guido van Rossum from work for Google App Engine;
<a class="reference external" href="https://bugs.python.org/issue3487">bpo-3487</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/rlcompleter.html#module-rlcompleter" title="rlcompleter: Python identifier completion, suitable for the GNU readline library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">rlcompleter</span></code></a> module’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">Completer.complete()</span></code> method
will now ignore exceptions triggered while evaluating a name.
(Fixed by Lorenz Quack; <a class="reference external" href="https://bugs.python.org/issue2250">bpo-2250</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/sched.html#module-sched" title="sched: General purpose event scheduler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sched</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">scheduler</span></code> instances now
have a read-only <code class="xref py py-attr docutils literal notranslate"><span class="pre">queue</span></code> attribute that returns the
contents of the scheduler’s queue, represented as a list of
named tuples with the fields <code class="docutils literal notranslate"><span class="pre">(time,</span> <span class="pre">priority,</span> <span class="pre">action,</span> <span class="pre">argument)</span></code>.
(Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue1861">bpo-1861</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/select.html#module-select" title="select: Wait for I/O completion on multiple streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">select</span></code></a> module now has wrapper functions
for the Linux <code class="xref c c-func docutils literal notranslate"><span class="pre">epoll()</span></code> and BSD <code class="xref c c-func docutils literal notranslate"><span class="pre">kqueue()</span></code> system calls.
<code class="xref py py-meth docutils literal notranslate"><span class="pre">modify()</span></code> method was added to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">poll</span></code>
objects; <code class="docutils literal notranslate"><span class="pre">pollobj.modify(fd,</span> <span class="pre">eventmask)</span></code> takes a file descriptor
or file object and an event mask, modifying the recorded event mask
for that file.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1657">bpo-1657</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">shutil.copytree()</span></code></a> function now has an optional <em>ignore</em> argument
that takes a callable object.  This callable will receive each directory path
and a list of the directory’s contents, and returns a list of names that
will be ignored, not copied.</p>
<p>The <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module also provides an <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
function for use with this new parameter.  <code class="xref py py-func docutils literal notranslate"><span class="pre">ignore_patterns()</span></code>
takes an arbitrary number of glob-style patterns and returns a
callable that will ignore any files and directories that match any
of these patterns.  The following example copies a directory tree,
but skips both <code class="file docutils literal notranslate"><span class="pre">.svn</span></code> directories and Emacs backup files,
which have names ending with ‘~’:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">shutil</span><span class="o">.</span><span class="n">copytree</span><span class="p">(</span><span class="s1">&#39;Doc/library&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp/library&#39;</span><span class="p">,</span>
                <span class="n">ignore</span><span class="o">=</span><span class="n">shutil</span><span class="o">.</span><span class="n">ignore_patterns</span><span class="p">(</span><span class="s1">&#39;*~&#39;</span><span class="p">,</span> <span class="s1">&#39;.svn&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>(Contributed by Tarek Ziadé; <a class="reference external" href="https://bugs.python.org/issue2663">bpo-2663</a>.)</p>
</li>
<li><p class="first">Integrating signal handling with GUI handling event loops
like those used by Tkinter or GTk+ has long been a problem; most
software ends up polling, waking up every fraction of a second to check
if any GUI events have occurred.
The <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module can now make this more efficient.
Calling <code class="docutils literal notranslate"><span class="pre">signal.set_wakeup_fd(fd)</span></code> sets a file descriptor
to be used; when a signal is received, a byte is written to that
file descriptor.  There’s also a C-level function,
<a class="reference internal" href="../c-api/exceptions.html#c.PySignal_SetWakeupFd" title="PySignal_SetWakeupFd"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySignal_SetWakeupFd()</span></code></a>, for setting the descriptor.</p>
<p>Event loops will use this by opening a pipe to create two descriptors,
one for reading and one for writing.  The writable descriptor
will be passed to <code class="xref py py-func docutils literal notranslate"><span class="pre">set_wakeup_fd()</span></code>, and the readable descriptor
will be added to the list of descriptors monitored by the event loop via
<code class="xref c c-func docutils literal notranslate"><span class="pre">select()</span></code> or <code class="xref c c-func docutils literal notranslate"><span class="pre">poll()</span></code>.
On receiving a signal, a byte will be written and the main event loop
will be woken up, avoiding the need to poll.</p>
<p>(Contributed by Adam Olsen; <a class="reference external" href="https://bugs.python.org/issue1583">bpo-1583</a>.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">siginterrupt()</span></code> function is now available from Python code,
and allows changing whether signals can interrupt system calls or not.
(Contributed by Ralf Schmitt.)</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">getitimer()</span></code> functions have also been
added (where they’re available).  <code class="xref py py-func docutils literal notranslate"><span class="pre">setitimer()</span></code>
allows setting interval timers that will cause a signal to be
delivered to the process after a specified time, measured in
wall-clock time, consumed process time, or combined process+system
time.  (Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue2240">bpo-2240</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> module now supports SMTP over SSL thanks to the
addition of the <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP_SSL</span></code> class. This class supports an
interface identical to the existing <code class="xref py py-class docutils literal notranslate"><span class="pre">SMTP</span></code> class.
(Contributed by Monty Taylor.)  Both class constructors also have an
optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter that specifies a timeout for the
initial connection attempt, measured in seconds.  (Contributed by
Facundo Batista.)</p>
<p>An implementation of the LMTP protocol (<span class="target" id="index-22"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2033.html"><strong>RFC 2033</strong></a>) was also added
to the module.  LMTP is used in place of SMTP when transferring
e-mail between agents that don’t manage a mail queue.  (LMTP
implemented by Leif Hedstrom; <a class="reference external" href="https://bugs.python.org/issue957003">bpo-957003</a>.)</p>
<p><code class="xref py py-meth docutils literal notranslate"><span class="pre">SMTP.starttls()</span></code> now complies with <span class="target" id="index-23"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3207.html"><strong>RFC 3207</strong></a> and forgets any
knowledge obtained from the server not obtained from the TLS
negotiation itself.  (Patch contributed by Bill Fenner;
<a class="reference external" href="https://bugs.python.org/issue829951">bpo-829951</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module now supports TIPC (<a class="reference external" href="http://tipc.sourceforge.net/">http://tipc.sourceforge.net/</a>),
a high-performance non-IP-based protocol designed for use in clustered
environments.  TIPC addresses are 4- or 5-tuples.
(Contributed by Alberto Bertogli; <a class="reference external" href="https://bugs.python.org/issue1646">bpo-1646</a>.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code>, takes an address and
connects to it using an optional timeout value, returning the
connected socket object.  This function also looks up the address’s
type and connects to it using IPv4 or IPv6 as appropriate.  Changing
your code to use <code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code> instead of
<code class="docutils literal notranslate"><span class="pre">socket(socket.AF_INET,</span> <span class="pre">...)</span></code> may be all that’s required to make
your code work with IPv6.</p>
</li>
<li><p class="first">The base classes in the <a class="reference internal" href="../library/socketserver.html#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> module now support
calling a <code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code> method after a span of inactivity
specified by the server’s <code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code> attribute.  (Contributed
by Michael Pomraning.)  The <code class="xref py py-meth docutils literal notranslate"><span class="pre">serve_forever()</span></code> method
now takes an optional poll interval measured in seconds,
controlling how often the server will check for a shutdown request.
(Contributed by Pedro Werneck and Jeffrey Yasskin;
<a class="reference external" href="https://bugs.python.org/issue742598">bpo-742598</a>, <a class="reference external" href="https://bugs.python.org/issue1193577">bpo-1193577</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module, maintained by Gerhard Haering,
has been updated from version 2.3.2 in Python 2.5 to
version 2.4.1.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module now supports the C99 <code class="xref c c-type docutils literal notranslate"><span class="pre">_Bool</span></code> type,
using the format character <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.
(Contributed by David Remahl.)</p>
</li>
<li><p class="first">The <code class="xref py py-class docutils literal notranslate"><span class="pre">Popen</span></code> objects provided by the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module
now have <code class="xref py py-meth docutils literal notranslate"><span class="pre">terminate()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">kill()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code> methods.
On Windows, <code class="xref py py-meth docutils literal notranslate"><span class="pre">send_signal()</span></code> only supports the <code class="xref py py-const docutils literal notranslate"><span class="pre">SIGTERM</span></code>
signal, and all these methods are aliases for the Win32 API function
<code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code>.
(Contributed by Christian Heimes.)</p>
</li>
<li><p class="first">A new variable in the <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a> module, <code class="xref py py-attr docutils literal notranslate"><span class="pre">float_info</span></code>, is an
object containing information derived from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file
about the platform’s floating-point support.  Attributes of this
object include <code class="xref py py-attr docutils literal notranslate"><span class="pre">mant_dig</span></code> (number of digits in the mantissa),
<code class="xref py py-attr docutils literal notranslate"><span class="pre">epsilon</span></code> (smallest difference between 1.0 and the next
largest value representable), and several others.  (Contributed by
Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1534">bpo-1534</a>.)</p>
<p>Another new variable, <code class="xref py py-attr docutils literal notranslate"><span class="pre">dont_write_bytecode</span></code>, controls whether Python
writes any <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> files on importing a module.
If this variable is true, the compiled files are not written.  The
variable is initially set on start-up by supplying the <a class="reference internal" href="../using/cmdline.html#id1"><code class="xref std std-option docutils literal notranslate"><span class="pre">-B</span></code></a>
switch to the Python interpreter, or by setting the
<span class="target" id="index-24"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONDONTWRITEBYTECODE</span></code></a> environment variable before
running the interpreter.  Python code can subsequently
change the value of this variable to control whether bytecode files
are written or not.
(Contributed by Neal Norwitz and Georg Brandl.)</p>
<p>Information about the command-line arguments supplied to the Python
interpreter is available by reading attributes of a named
tuple available as <code class="docutils literal notranslate"><span class="pre">sys.flags</span></code>.  For example, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">verbose</span></code>
attribute is true if Python
was executed in verbose mode, <code class="xref py py-attr docutils literal notranslate"><span class="pre">debug</span></code> is true in debugging mode, etc.
These attributes are all read-only.
(Contributed by Christian Heimes.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">getsizeof()</span></code>, takes a Python object and returns
the amount of memory used by the object, measured in bytes.  Built-in
objects return correct results; third-party extensions may not,
but can define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__sizeof__()</span></code> method to return the
object’s size.
(Contributed by Robert Schuppenies; <a class="reference external" href="https://bugs.python.org/issue2898">bpo-2898</a>.)</p>
<p>It’s now possible to determine the current profiler and tracer functions
by calling <a class="reference internal" href="../library/sys.html#sys.getprofile" title="sys.getprofile"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getprofile()</span></code></a> and <a class="reference internal" href="../library/sys.html#sys.gettrace" title="sys.gettrace"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.gettrace()</span></code></a>.
(Contributed by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue1648">bpo-1648</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module now supports POSIX.1-2001 (pax) tarfiles in
addition to the POSIX.1-1988 (ustar) and GNU tar formats that were
already supported.  The default format is GNU tar; specify the
<code class="docutils literal notranslate"><span class="pre">format</span></code> parameter to open a file using a different format:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">tar</span> <span class="o">=</span> <span class="n">tarfile</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="s2">&quot;output.tar&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">,</span>
                   <span class="nb">format</span><span class="o">=</span><span class="n">tarfile</span><span class="o">.</span><span class="n">PAX_FORMAT</span><span class="p">)</span>
</pre></div>
</div>
<p>The new <code class="docutils literal notranslate"><span class="pre">encoding</span></code> and <code class="docutils literal notranslate"><span class="pre">errors</span></code> parameters specify an encoding and
an error handling scheme for character conversions.  <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>, and <code class="docutils literal notranslate"><span class="pre">'replace'</span></code> are the three standard ways Python can
handle errors,;
<code class="docutils literal notranslate"><span class="pre">'utf-8'</span></code> is a special value that replaces bad characters with
their UTF-8 representation.  (Character conversions occur because the
PAX format supports Unicode filenames, defaulting to UTF-8 encoding.)</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">TarFile.add()</span></code> method now accepts an <code class="docutils literal notranslate"><span class="pre">exclude</span></code> argument that’s
a function that can be used to exclude certain filenames from
an archive.
The function must take a filename and return true if the file
should be excluded or false if it should be archived.
The function is applied to both the name initially passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>
and to the names of files in recursively-added directories.</p>
<p>(All changes contributed by Lars Gustäbel).</p>
</li>
<li><p class="first">An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter was added to the
<a class="reference internal" href="../library/telnetlib.html#telnetlib.Telnet" title="telnetlib.Telnet"><code class="xref py py-class docutils literal notranslate"><span class="pre">telnetlib.Telnet</span></code></a> class constructor, specifying a timeout
measured in seconds.  (Added by Facundo Batista.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tempfile.html#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">tempfile.NamedTemporaryFile</span></code></a> class usually deletes
the temporary file it created when the file is closed.  This
behaviour can now be changed by passing <code class="docutils literal notranslate"><span class="pre">delete=False</span></code> to the
constructor.  (Contributed by Damien Miller; <a class="reference external" href="https://bugs.python.org/issue1537850">bpo-1537850</a>.)</p>
<p>A new class, <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code>, behaves like
a temporary file but stores its data in memory until a maximum size is
exceeded.  On reaching that limit, the contents will be written to
an on-disk temporary file.  (Contributed by Dustin J. Mitchell.)</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">NamedTemporaryFile</span></code> and <code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code> classes
both work as context managers, so you can write
<code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">tempfile.NamedTemporaryFile()</span> <span class="pre">as</span> <span class="pre">tmp:</span> <span class="pre">...</span></code>.
(Contributed by Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue2021">bpo-2021</a>.)</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">test.test_support</span></code> module gained a number
of context managers useful for writing tests.
<code class="xref py py-func docutils literal notranslate"><span class="pre">EnvironmentVarGuard()</span></code> is a
context manager that temporarily changes environment variables and
automatically restores them to their old values.</p>
<p>Another context manager, <code class="xref py py-class docutils literal notranslate"><span class="pre">TransientResource</span></code>, can surround calls
to resources that may or may not be available; it will catch and
ignore a specified list of exceptions.  For example,
a network test may ignore certain failures when connecting to an
external web site:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">TransientResource</span><span class="p">(</span><span class="ne">IOError</span><span class="p">,</span>
                                <span class="n">errno</span><span class="o">=</span><span class="n">errno</span><span class="o">.</span><span class="n">ETIMEDOUT</span><span class="p">):</span>
    <span class="n">f</span> <span class="o">=</span> <span class="n">urllib</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s1">&#39;https://sf.net&#39;</span><span class="p">)</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>Finally, <code class="xref py py-func docutils literal notranslate"><span class="pre">check_warnings()</span></code> resets the <code class="xref py py-mod docutils literal notranslate"><span class="pre">warning</span></code> module’s
warning filters and returns an object that will record all warning
messages triggered (<a class="reference external" href="https://bugs.python.org/issue3781">bpo-3781</a>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">test_support</span><span class="o">.</span><span class="n">check_warnings</span><span class="p">()</span> <span class="k">as</span> <span class="n">wrec</span><span class="p">:</span>
    <span class="n">warnings</span><span class="o">.</span><span class="n">simplefilter</span><span class="p">(</span><span class="s2">&quot;always&quot;</span><span class="p">)</span>
    <span class="c1"># ... code that triggers a warning ...</span>
    <span class="k">assert</span> <span class="nb">str</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">message</span><span class="p">)</span> <span class="o">==</span> <span class="s2">&quot;function is outdated&quot;</span>
    <span class="k">assert</span> <span class="nb">len</span><span class="p">(</span><span class="n">wrec</span><span class="o">.</span><span class="n">warnings</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">,</span> <span class="s2">&quot;Multiple warnings raised&quot;</span>
</pre></div>
</div>
<p>(Contributed by Brett Cannon.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module can now preserve existing whitespace
at the beginnings and ends of the newly-created lines
by specifying <code class="docutils literal notranslate"><span class="pre">drop_whitespace=False</span></code>
as an argument:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">S</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;This  sentence  has a bunch   of</span>
<span class="gp">... </span><span class="s2">  extra   whitespace.&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">S</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="go">This  sentence</span>
<span class="go">has a bunch</span>
<span class="go">of    extra</span>
<span class="go">whitespace.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">S</span><span class="p">,</span> <span class="n">drop_whitespace</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="go">This  sentence</span>
<span class="go">  has a bunch</span>
<span class="go">   of    extra</span>
<span class="go">   whitespace.</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>(Contributed by Dwayne Bailey; <a class="reference external" href="https://bugs.python.org/issue1581073">bpo-1581073</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module API is being changed to use properties
such as <code class="xref py py-attr docutils literal notranslate"><span class="pre">daemon</span></code> instead of <code class="xref py py-meth docutils literal notranslate"><span class="pre">setDaemon()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isDaemon()</span></code> methods, and some methods have been renamed to use
underscores instead of camel-case; for example, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">activeCount()</span></code> method is renamed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">active_count()</span></code>.  Both
the 2.6 and 3.0 versions of the module support the same properties
and renamed methods, but don’t remove the old methods.  No date has been set
for the deprecation of the old APIs in Python 3.x; the old APIs won’t
be removed in any 2.x version.
(Carried out by several people, most notably Benjamin Peterson.)</p>
<p>The <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Thread</span></code> objects
gained an <code class="xref py py-attr docutils literal notranslate"><span class="pre">ident</span></code> property that returns the thread’s
identifier, a nonzero integer.  (Contributed by Gregory P. Smith;
<a class="reference external" href="https://bugs.python.org/issue2871">bpo-2871</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a> module now accepts callables as well as strings
for the statement being timed and for the setup code.
Two convenience functions were added for creating
<code class="xref py py-class docutils literal notranslate"><span class="pre">Timer</span></code> instances:
<code class="docutils literal notranslate"><span class="pre">repeat(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">repeat,</span> <span class="pre">number)</span></code> and
<code class="docutils literal notranslate"><span class="pre">timeit(stmt,</span> <span class="pre">setup,</span> <span class="pre">time,</span> <span class="pre">number)</span></code> create an instance and call
the corresponding method. (Contributed by Erik Demaine;
<a class="reference external" href="https://bugs.python.org/issue1533909">bpo-1533909</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tkinter.html#module-Tkinter" title="Tkinter: Interface to Tcl/Tk for graphical user interfaces"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Tkinter</span></code></a> module now accepts lists and tuples for options,
separating the elements by spaces before passing the resulting value to
Tcl/Tk.
(Contributed by Guilherme Polo; <a class="reference external" href="https://bugs.python.org/issue2906">bpo-2906</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/turtle.html#module-turtle" title="turtle: Turtle graphics for Tk"><code class="xref py py-mod docutils literal notranslate"><span class="pre">turtle</span></code></a> module for turtle graphics was greatly enhanced by
Gregor Lingl.  New features in the module include:</p>
<ul class="simple">
<li>Better animation of turtle movement and rotation.</li>
<li>Control over turtle movement using the new <code class="xref py py-meth docutils literal notranslate"><span class="pre">delay()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">tracer()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">speed()</span></code> methods.</li>
<li>The ability to set new shapes for the turtle, and to
define a new coordinate system.</li>
<li>Turtles now have an <code class="xref py py-meth docutils literal notranslate"><span class="pre">undo()</span></code> method that can roll back actions.</li>
<li>Simple support for reacting to input events such as mouse and keyboard
activity, making it possible to write simple games.</li>
<li>A <code class="file docutils literal notranslate"><span class="pre">turtle.cfg</span></code> file can be used to customize the starting appearance
of the turtle’s screen.</li>
<li>The module’s docstrings can be replaced by new docstrings that have been
translated into another language.</li>
</ul>
<p>(<a class="reference external" href="https://bugs.python.org/issue1513695">bpo-1513695</a>)</p>
</li>
<li><p class="first">An optional <code class="docutils literal notranslate"><span class="pre">timeout</span></code> parameter was added to the
<a class="reference internal" href="../library/urllib.html#urllib.urlopen" title="urllib.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib.urlopen()</span></code></a> function and the
<code class="xref py py-class docutils literal notranslate"><span class="pre">urllib.ftpwrapper</span></code> class constructor, as well as the
<a class="reference internal" href="../library/urllib2.html#urllib2.urlopen" title="urllib2.urlopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">urllib2.urlopen()</span></code></a> function.  The parameter specifies a timeout
measured in seconds.   For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">u</span> <span class="o">=</span> <span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;http://slow.example.com&quot;</span><span class="p">,</span>
<span class="go">                        timeout=3)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">urllib2.URLError</span>: <span class="n">&lt;urlopen error timed out&gt;</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p>(Added by Facundo Batista.)</p>
</li>
<li><p class="first">The Unicode database provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module
has been updated to version 5.1.0.  (Updated by
Martin von Loewis; <a class="reference external" href="https://bugs.python.org/issue3811">bpo-3811</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module’s <code class="xref py py-func docutils literal notranslate"><span class="pre">formatwarning()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">showwarning()</span></code>
gained an optional <em>line</em> argument that can be used to supply the
line of source code.  (Added as part of <a class="reference external" href="https://bugs.python.org/issue1631171">bpo-1631171</a>, which re-implemented
part of the <a class="reference internal" href="../library/warnings.html#module-warnings" title="warnings: Issue warning messages and control their disposition."><code class="xref py py-mod docutils literal notranslate"><span class="pre">warnings</span></code></a> module in C code.)</p>
<p>A new function, <code class="xref py py-func docutils literal notranslate"><span class="pre">catch_warnings()</span></code>, is a context manager
intended for testing purposes that lets you temporarily modify the
warning filters and then restore their original values (<a class="reference external" href="https://bugs.python.org/issue3781">bpo-3781</a>).</p>
</li>
<li><p class="first">The XML-RPC <a class="reference internal" href="../library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> and <a class="reference internal" href="../library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer" title="DocXMLRPCServer.DocXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code></a>
classes can now be prevented from immediately opening and binding to
their socket by passing <code class="docutils literal notranslate"><span class="pre">False</span></code> as the <em>bind_and_activate</em>
constructor parameter.  This can be used to modify the instance’s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">allow_reuse_address</span></code> attribute before calling the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">server_bind()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">server_activate()</span></code> methods to
open the socket and begin listening for connections.
(Contributed by Peter Parente; <a class="reference external" href="https://bugs.python.org/issue1599845">bpo-1599845</a>.)</p>
<p><a class="reference internal" href="../library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer" title="SimpleXMLRPCServer.SimpleXMLRPCServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> also has a <code class="xref py py-attr docutils literal notranslate"><span class="pre">_send_traceback_header</span></code>
attribute; if true, the exception and formatted traceback are returned
as HTTP headers “X-Exception” and “X-Traceback”.  This feature is
for debugging purposes only and should not be used on production servers
because the tracebacks might reveal passwords or other sensitive
information.  (Contributed by Alan McIntyre as part of his
project for Google’s Summer of Code 2007.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module no longer automatically converts
<a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> to the
<a class="reference internal" href="../library/xmlrpclib.html#xmlrpclib.DateTime" title="xmlrpclib.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code></a> type; the conversion semantics were
not necessarily correct for all applications.  Code using
<a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>
instances. (<a class="reference external" href="https://bugs.python.org/issue1330538">bpo-1330538</a>)  The code can also handle
dates before 1900 (contributed by Ralf Schmitt; <a class="reference external" href="https://bugs.python.org/issue2014">bpo-2014</a>)
and 64-bit integers represented by using <code class="docutils literal notranslate"><span class="pre">&lt;i8&gt;</span></code> in XML-RPC responses
(contributed by Riku Lindblad; <a class="reference external" href="https://bugs.python.org/issue2985">bpo-2985</a>).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code> class now has
<code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extractall()</span></code> methods that will unpack
a single file or all the files in the archive to the current directory, or
to a specified directory:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">z</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="s1">&#39;python-251.zip&#39;</span><span class="p">)</span>

<span class="c1"># Unpack a single file, writing it relative</span>
<span class="c1"># to the /tmp directory.</span>
<span class="n">z</span><span class="o">.</span><span class="n">extract</span><span class="p">(</span><span class="s1">&#39;Python/sysmodule.c&#39;</span><span class="p">,</span> <span class="s1">&#39;/tmp&#39;</span><span class="p">)</span>

<span class="c1"># Unpack all the files in the archive.</span>
<span class="n">z</span><span class="o">.</span><span class="n">extractall</span><span class="p">()</span>
</pre></div>
</div>
<p>(Contributed by Alan McIntyre; <a class="reference external" href="https://bugs.python.org/issue467924">bpo-467924</a>.)</p>
<p>The <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-meth docutils literal notranslate"><span class="pre">open()</span></code></a>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">extract()</span></code> methods can now
take either a filename or a <code class="xref py py-class docutils literal notranslate"><span class="pre">ZipInfo</span></code> object.  This is useful when an
archive accidentally contains a duplicated filename.
(Contributed by Graham Horler; <a class="reference external" href="https://bugs.python.org/issue1775025">bpo-1775025</a>.)</p>
<p>Finally, <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> now supports using Unicode filenames
for archived files.  (Contributed by Alexey Borzenkov; <a class="reference external" href="https://bugs.python.org/issue1734346">bpo-1734346</a>.)</p>
</li>
</ul>
<div class="section" id="the-ast-module">
<h3>The <a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module<a class="headerlink" href="#the-ast-module" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/ast.html#module-ast" title="ast: Abstract Syntax Tree classes and manipulation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ast</span></code></a> module provides an Abstract Syntax Tree
representation of Python code, and Armin Ronacher
contributed a set of helper functions that perform a variety of
common tasks.  These will be useful for HTML templating
packages, code analyzers, and similar tools that process
Python code.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">parse()</span></code> function takes an expression and returns an AST.
The <code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code> function outputs a representation of a tree, suitable
for debugging:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">ast</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">ast</span><span class="o">.</span><span class="n">parse</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;</span>
<span class="s2">d = </span><span class="si">{}</span><span class="s2"></span>
<span class="s2">for i in &#39;abcdefghijklm&#39;:</span>
<span class="s2">    d[i + i] = ord(i) - ord(&#39;a&#39;) + 1</span>
<span class="s2">print d</span>
<span class="s2">&quot;&quot;&quot;</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
</pre></div>
</div>
<p>This outputs a deeply nested tree:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">Module</span><span class="p">(</span><span class="n">body</span><span class="o">=</span><span class="p">[</span>
  <span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
    <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
   <span class="p">],</span> <span class="n">value</span><span class="o">=</span><span class="n">Dict</span><span class="p">(</span><span class="n">keys</span><span class="o">=</span><span class="p">[],</span> <span class="n">values</span><span class="o">=</span><span class="p">[]))</span>
  <span class="n">For</span><span class="p">(</span><span class="n">target</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">()),</span>
      <span class="nb">iter</span><span class="o">=</span><span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;abcdefghijklm&#39;</span><span class="p">),</span> <span class="n">body</span><span class="o">=</span><span class="p">[</span>
    <span class="n">Assign</span><span class="p">(</span><span class="n">targets</span><span class="o">=</span><span class="p">[</span>
      <span class="n">Subscript</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
        <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span>
          <span class="nb">slice</span><span class="o">=</span>
          <span class="n">Index</span><span class="p">(</span><span class="n">value</span><span class="o">=</span>
            <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span>
             <span class="n">right</span><span class="o">=</span><span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()))),</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Store</span><span class="p">())</span>
     <span class="p">],</span> <span class="n">value</span><span class="o">=</span>
     <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
      <span class="n">BinOp</span><span class="p">(</span><span class="n">left</span><span class="o">=</span>
       <span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
        <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
          <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;i&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
         <span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">),</span>
       <span class="n">op</span><span class="o">=</span><span class="n">Sub</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Call</span><span class="p">(</span><span class="n">func</span><span class="o">=</span>
        <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;ord&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">()),</span> <span class="n">args</span><span class="o">=</span><span class="p">[</span>
          <span class="n">Str</span><span class="p">(</span><span class="n">s</span><span class="o">=</span><span class="s1">&#39;a&#39;</span><span class="p">)</span>
         <span class="p">],</span> <span class="n">keywords</span><span class="o">=</span><span class="p">[],</span> <span class="n">starargs</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">kwargs</span><span class="o">=</span><span class="kc">None</span><span class="p">)),</span>
       <span class="n">op</span><span class="o">=</span><span class="n">Add</span><span class="p">(),</span> <span class="n">right</span><span class="o">=</span><span class="n">Num</span><span class="p">(</span><span class="n">n</span><span class="o">=</span><span class="mi">1</span><span class="p">)))</span>
    <span class="p">],</span> <span class="n">orelse</span><span class="o">=</span><span class="p">[])</span>
   <span class="n">Print</span><span class="p">(</span><span class="n">dest</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">values</span><span class="o">=</span><span class="p">[</span>
     <span class="n">Name</span><span class="p">(</span><span class="nb">id</span><span class="o">=</span><span class="s1">&#39;d&#39;</span><span class="p">,</span> <span class="n">ctx</span><span class="o">=</span><span class="n">Load</span><span class="p">())</span>
   <span class="p">],</span> <span class="n">nl</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
 <span class="p">])</span>
</pre></div>
</div>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> method takes a string or an AST
representing a literal expression, parses and evaluates it, and
returns the resulting value.  A literal expression is a Python
expression containing only strings, numbers, dictionaries,
etc. but no statements or function calls.  If you need to
evaluate an expression but cannot accept the security risk of using an
<a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> call, <code class="xref py py-func docutils literal notranslate"><span class="pre">literal_eval()</span></code> will handle it safely:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">literal</span> <span class="o">=</span> <span class="s1">&#39;(&quot;a&quot;, &quot;b&quot;, {2:4, 3:8, 1:2})&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="n">literal</span><span class="p">)</span>
<span class="go">(&#39;a&#39;, &#39;b&#39;, {1: 2, 2: 4, 3: 8})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">ast</span><span class="o">.</span><span class="n">literal_eval</span><span class="p">(</span><span class="s1">&#39;&quot;a&quot; + &quot;b&quot;&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">ValueError</span>: <span class="n">malformed string</span>
</pre></div>
</div>
<p>The module also includes <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeVisitor</span></code> and
<code class="xref py py-class docutils literal notranslate"><span class="pre">NodeTransformer</span></code> classes for traversing and modifying an AST,
and functions for common transformations such as changing line
numbers.</p>
</div>
<div class="section" id="the-future-builtins-module">
<h3>The <a class="reference internal" href="../library/future_builtins.html#module-future_builtins" title="future_builtins"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code></a> module<a class="headerlink" href="#the-future-builtins-module" title="Permalink to this headline">¶</a></h3>
<p>Python 3.0 makes many changes to the repertoire of built-in
functions, and most of the changes can’t be introduced in the Python
2.x series because they would break compatibility.
The <a class="reference internal" href="../library/future_builtins.html#module-future_builtins" title="future_builtins"><code class="xref py py-mod docutils literal notranslate"><span class="pre">future_builtins</span></code></a> module provides versions
of these built-in functions that can be imported when writing
3.0-compatible code.</p>
<p>The functions in this module currently include:</p>
<ul class="simple">
<li><code class="docutils literal notranslate"><span class="pre">ascii(obj)</span></code>: equivalent to <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>.  In Python 3.0,
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> will return a Unicode string, while <code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code> will
return a pure ASCII bytestring.</li>
<li><code class="docutils literal notranslate"><span class="pre">filter(predicate,</span> <span class="pre">iterable)</span></code>,
<code class="docutils literal notranslate"><span class="pre">map(func,</span> <span class="pre">iterable1,</span> <span class="pre">...)</span></code>: the 3.0 versions
return iterators, unlike the 2.x builtins which return lists.</li>
<li><code class="docutils literal notranslate"><span class="pre">hex(value)</span></code>, <code class="docutils literal notranslate"><span class="pre">oct(value)</span></code>: instead of calling the
<a class="reference internal" href="../reference/datamodel.html#object.__hex__" title="object.__hex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hex__()</span></code></a> or <a class="reference internal" href="../reference/datamodel.html#object.__oct__" title="object.__oct__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__oct__()</span></code></a> methods, these versions will
call the <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> method and convert the result to hexadecimal
or octal.  <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> will use the new <code class="docutils literal notranslate"><span class="pre">0o</span></code> notation for its
result.</li>
</ul>
</div>
<div class="section" id="the-json-module-javascript-object-notation">
<h3>The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module: JavaScript Object Notation<a class="headerlink" href="#the-json-module-javascript-object-notation" title="Permalink to this headline">¶</a></h3>
<p>The new <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module supports the encoding and decoding of Python types in
JSON (Javascript Object Notation). JSON is a lightweight interchange format
often used in web applications. For more information about JSON, see
<a class="reference external" href="http://www.json.org">http://www.json.org</a>.</p>
<p><a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> comes with support for decoding and encoding most built-in Python
types. The following example encodes and decodes a dictionary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">json</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s2">&quot;spam&quot;</span><span class="p">:</span> <span class="s2">&quot;foo&quot;</span><span class="p">,</span> <span class="s2">&quot;parrot&quot;</span><span class="p">:</span> <span class="mi">42</span><span class="p">}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># Encode the data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">in_json</span>
<span class="go">&#39;{&quot;parrot&quot;: 42, &quot;spam&quot;: &quot;foo&quot;}&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">json</span><span class="o">.</span><span class="n">loads</span><span class="p">(</span><span class="n">in_json</span><span class="p">)</span> <span class="c1"># Decode into a Python object</span>
<span class="go">{&quot;spam&quot;: &quot;foo&quot;, &quot;parrot&quot;: 42}</span>
</pre></div>
</div>
<p>It’s also possible to write your own decoders and encoders to support
more types. Pretty-printing of the JSON strings is also supported.</p>
<p><a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> (originally called simplejson) was written by Bob
Ippolito.</p>
</div>
<div class="section" id="the-plistlib-module-a-property-list-parser">
<h3>The <a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Mac OS X plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> module: A Property-List Parser<a class="headerlink" href="#the-plistlib-module-a-property-list-parser" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">.plist</span></code> format is commonly used on Mac OS X to
store basic data types (numbers, strings, lists,
and dictionaries) by serializing them into an XML-based format.
It resembles the XML-RPC serialization of data types.</p>
<p>Despite being primarily used on Mac OS X, the format
has nothing Mac-specific about it and the Python implementation works
on any platform that Python supports, so the <a class="reference internal" href="../library/plistlib.html#module-plistlib" title="plistlib: Generate and parse Mac OS X plist files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">plistlib</span></code></a> module
has been promoted to the standard library.</p>
<p>Using the module is simple:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">import</span> <span class="nn">plistlib</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="c1"># Create data structure</span>
<span class="n">data_struct</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">lastAccessed</span><span class="o">=</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">(),</span>
                   <span class="n">version</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span>
                   <span class="n">categories</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;Personal&#39;</span><span class="p">,</span><span class="s1">&#39;Shared&#39;</span><span class="p">,</span><span class="s1">&#39;Private&#39;</span><span class="p">))</span>

<span class="c1"># Create string containing XML.</span>
<span class="n">plist_str</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">writePlistToString</span><span class="p">(</span><span class="n">data_struct</span><span class="p">)</span>
<span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlistFromString</span><span class="p">(</span><span class="n">plist_str</span><span class="p">)</span>
<span class="nb">print</span> <span class="n">data_struct</span>
<span class="nb">print</span> <span class="n">new_struct</span>

<span class="c1"># Write data structure to a file and read it back.</span>
<span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>
<span class="n">new_struct</span> <span class="o">=</span> <span class="n">plistlib</span><span class="o">.</span><span class="n">readPlist</span><span class="p">(</span><span class="s1">&#39;/tmp/customizations.plist&#39;</span><span class="p">)</span>

<span class="c1"># read/writePlist accepts file-like objects as well as paths.</span>
<span class="n">plistlib</span><span class="o">.</span><span class="n">writePlist</span><span class="p">(</span><span class="n">data_struct</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">stdout</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="ctypes-enhancements">
<h3>ctypes Enhancements<a class="headerlink" href="#ctypes-enhancements" title="Permalink to this headline">¶</a></h3>
<p>Thomas Heller continued to maintain and enhance the
<a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module.</p>
<p><a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> now supports a <code class="xref py py-class docutils literal notranslate"><span class="pre">c_bool</span></code> datatype
that represents the C99 <code class="docutils literal notranslate"><span class="pre">bool</span></code> type.  (Contributed by David Remahl;
<a class="reference external" href="https://bugs.python.org/issue1649190">bpo-1649190</a>.)</p>
<p>The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> string, buffer and array types have improved
support for extended slicing syntax,
where various combinations of <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">stop,</span> <span class="pre">step)</span></code> are supplied.
(Implemented by Thomas Wouters.)</p>
<p>All <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> data types now support
<code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code>
methods that create a ctypes instance based on a
provided buffer object.  <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer_copy()</span></code> copies
the contents of the object,
while <code class="xref py py-meth docutils literal notranslate"><span class="pre">from_buffer()</span></code> will share the same memory area.</p>
<p>A new calling convention tells <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> to clear the <code class="docutils literal notranslate"><span class="pre">errno</span></code> or
Win32 LastError variables at the outset of each wrapped call.
(Implemented by Thomas Heller; <a class="reference external" href="https://bugs.python.org/issue1798">bpo-1798</a>.)</p>
<p>You can now retrieve the Unix <code class="docutils literal notranslate"><span class="pre">errno</span></code> variable after a function
call.  When creating a wrapped function, you can supply
<code class="docutils literal notranslate"><span class="pre">use_errno=True</span></code> as a keyword parameter to the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code> function
and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_errno()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">get_errno()</span></code> to set and retrieve the error value.</p>
<p>The Win32 LastError variable is similarly supported by
the <code class="xref py py-func docutils literal notranslate"><span class="pre">DLL()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">OleDLL()</span></code>, and <code class="xref py py-func docutils literal notranslate"><span class="pre">WinDLL()</span></code> functions.
You supply <code class="docutils literal notranslate"><span class="pre">use_last_error=True</span></code> as a keyword parameter
and then call the module-level methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">set_last_error()</span></code>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">get_last_error()</span></code>.</p>
<p>The <code class="xref py py-func docutils literal notranslate"><span class="pre">byref()</span></code> function, used to retrieve a pointer to a ctypes
instance, now has an optional <em>offset</em> parameter that is a byte
count that will be added to the returned pointer.</p>
</div>
<div class="section" id="improved-ssl-support">
<h3>Improved SSL Support<a class="headerlink" href="#improved-ssl-support" title="Permalink to this headline">¶</a></h3>
<p>Bill Janssen made extensive improvements to Python 2.6’s support for
the Secure Sockets Layer by adding a new module, <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a>, that’s
built atop the <a class="reference external" href="https://www.openssl.org/">OpenSSL</a> library.
This new module provides more control over the protocol negotiated,
the X.509 certificates used, and has better support for writing SSL
servers (as opposed to clients) in Python.  The existing SSL support
in the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module hasn’t been removed and continues to work,
though it will be removed in Python 3.0.</p>
<p>To use the new module, you must first create a TCP connection in the
usual way and then pass it to the <a class="reference internal" href="../library/ssl.html#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.wrap_socket()</span></code></a> function.
It’s possible to specify whether a certificate is required, and to
obtain certificate info by calling the <code class="xref py py-meth docutils literal notranslate"><span class="pre">getpeercert()</span></code> method.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last">The documentation for the <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module.</p>
</div>
</div>
</div>
<div class="section" id="deprecations-and-removals">
<h2>Deprecations and Removals<a class="headerlink" href="#deprecations-and-removals" title="Permalink to this headline">¶</a></h2>
<ul>
<li><p class="first">String exceptions have been removed.  Attempting to use them raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</li>
<li><p class="first">Changes to the <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code> interface
as dictated by <span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0352"><strong>PEP 352</strong></a> continue to be made.  For 2.6,
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">message</span></code> attribute is being deprecated in favor of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">args</span></code> attribute.</p>
</li>
<li><p class="first">(3.0-warning mode) Python 3.0 will feature a reorganized standard
library that will drop many outdated modules and rename others.
Python 2.6 running in 3.0-warning mode will warn about these modules
when they are imported.</p>
<p>The list of deprecated modules is:
<code class="xref py py-mod docutils literal notranslate"><span class="pre">audiodev</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bgenlocations</span></code>,
<a class="reference internal" href="../library/undoc.html#module-buildtools" title="buildtools: Helper module for BuildApplet, BuildApplication and macfreeze. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">buildtools</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">bundlebuilder</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Canvas</span></code>,
<a class="reference internal" href="../library/compiler.html#module-compiler" title="compiler: Python code compiler written in Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">compiler</span></code></a>,
<a class="reference internal" href="../library/dircache.html#module-dircache" title="dircache: Return directory listing, with cache mechanism. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dircache</span></code></a>,
<a class="reference internal" href="../library/dl.html#module-dl" title="dl: Call C functions in shared objects. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dl</span></code></a>,
<a class="reference internal" href="../library/fpformat.html#module-fpformat" title="fpformat: General floating point formatting functions. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fpformat</span></code></a>,
<a class="reference internal" href="../library/gensuitemodule.html#module-gensuitemodule" title="gensuitemodule: Create a stub package from an OSA dictionary (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gensuitemodule</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code>,
<a class="reference internal" href="../library/imageop.html#module-imageop" title="imageop: Manipulate raw image data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imageop</span></code></a>,
<a class="reference internal" href="../library/imgfile.html#module-imgfile" title="imgfile: Support for SGI imglib files. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imgfile</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">linuxaudiodev</span></code>,
<a class="reference internal" href="../library/mhlib.html#module-mhlib" title="mhlib: Manipulate MH mailboxes from Python. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mhlib</span></code></a>,
<a class="reference internal" href="../library/mimetools.html#module-mimetools" title="mimetools: Tools for parsing MIME-style message bodies. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimetools</span></code></a>,
<a class="reference internal" href="../library/multifile.html#module-multifile" title="multifile: Support for reading files which contain distinct parts, such as some MIME data. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multifile</span></code></a>,
<a class="reference internal" href="../library/new.html#module-new" title="new: Interface to the creation of runtime implementation objects. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">new</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pure</span></code>,
<a class="reference internal" href="../library/statvfs.html#module-statvfs" title="statvfs: Constants for interpreting the result of os.statvfs(). (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statvfs</span></code></a>,
<a class="reference internal" href="../library/sunaudio.html#module-sunaudiodev" title="sunaudiodev: Access to Sun audio hardware. (deprecated) (SunOS)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">test.testall</span></code>, and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">toaiff</span></code>.</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">gopherlib</span></code> module has been removed.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/mimewriter.html#module-MimeWriter" title="MimeWriter: Write MIME format files. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MimeWriter</span></code></a> module and <a class="reference internal" href="../library/mimify.html#module-mimify" title="mimify: Mimification and unmimification of mail messages. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mimify</span></code></a> module
have been deprecated; use the <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a>
package instead.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/md5.html#module-md5" title="md5: RSA's MD5 message digest algorithm. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">md5</span></code></a> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
instead.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/posixfile.html#module-posixfile" title="posixfile: A file-like object with support for locking. (deprecated) (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">posixfile</span></code></a> module has been deprecated; <a class="reference internal" href="../library/fcntl.html#fcntl.lockf" title="fcntl.lockf"><code class="xref py py-func docutils literal notranslate"><span class="pre">fcntl.lockf()</span></code></a>
provides better locking.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/popen2.html#module-popen2" title="popen2: Subprocesses with accessible standard I/O streams. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">popen2</span></code></a> module has been deprecated; use the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a>
module.</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">rgbimg</span></code> module has been removed.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/sets.html#module-sets" title="sets: Implementation of sets of unique elements. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sets</span></code></a> module has been deprecated; it’s better to
use the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a> types.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/sha.html#module-sha" title="sha: NIST's secure hash algorithm, SHA. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sha</span></code></a> module has been deprecated; use the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module
instead.</p>
</li>
</ul>
</div>
<div class="section" id="build-and-c-api-changes">
<h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
<p>Changes to Python’s build process and to the C API include:</p>
<ul>
<li><p class="first">Python now must be compiled with C89 compilers (after 19
years!).  This means that the Python source tree has dropped its
own implementations of <code class="xref c c-func docutils literal notranslate"><span class="pre">memmove()</span></code> and <code class="xref c c-func docutils literal notranslate"><span class="pre">strerror()</span></code>, which
are in the C89 standard library.</p>
</li>
<li><p class="first">Python 2.6 can be built with Microsoft Visual Studio 2008 (version
9.0), and this is the new default compiler.  See the
<code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory for the build files.  (Implemented by
Christian Heimes.)</p>
</li>
<li><p class="first">On Mac OS X, Python 2.6 can be compiled as a 4-way universal build.
The <strong class="program">configure</strong> script
can take a <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-universal-archs=[32-bit|64-bit|all]</span></code>
switch, controlling whether the binaries are built for 32-bit
architectures (x86, PowerPC), 64-bit (x86-64 and PPC-64), or both.
(Contributed by Ronald Oussoren.)</p>
</li>
<li><p class="first">The BerkeleyDB module now has a C API object, available as
<code class="docutils literal notranslate"><span class="pre">bsddb.db.api</span></code>.   This object can be used by other C extensions
that wish to use the <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module for their own purposes.
(Contributed by Duncan Grisby.)</p>
</li>
<li><p class="first">The new buffer interface, previously described in
<a class="reference external" href="#pep-3118-revised-buffer-protocol">the PEP 3118 section</a>,
adds <a class="reference internal" href="../c-api/buffer.html#c.PyObject_GetBuffer" title="PyObject_GetBuffer"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_GetBuffer()</span></code></a> and <a class="reference internal" href="../c-api/buffer.html#c.PyBuffer_Release" title="PyBuffer_Release"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyBuffer_Release()</span></code></a>,
as well as a few other functions.</p>
</li>
<li><p class="first">Python’s use of the C stdio library is now thread-safe, or at least
as thread-safe as the underlying library is.  A long-standing potential
bug occurred if one thread closed a file object while another thread
was reading from or writing to the object.  In 2.6 file objects
have a reference count, manipulated by the
<a class="reference internal" href="../c-api/file.html#c.PyFile_IncUseCount" title="PyFile_IncUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code></a> and <a class="reference internal" href="../c-api/file.html#c.PyFile_DecUseCount" title="PyFile_DecUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code></a>
functions.  File objects can’t be closed unless the reference count
is zero.  <a class="reference internal" href="../c-api/file.html#c.PyFile_IncUseCount" title="PyFile_IncUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_IncUseCount()</span></code></a> should be called while the GIL
is still held, before carrying out an I/O operation using the
<code class="docutils literal notranslate"><span class="pre">FILE</span> <span class="pre">*</span></code> pointer, and <a class="reference internal" href="../c-api/file.html#c.PyFile_DecUseCount" title="PyFile_DecUseCount"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFile_DecUseCount()</span></code></a> should be called
immediately after the GIL is re-acquired.
(Contributed by Antoine Pitrou and Gregory P. Smith.)</p>
</li>
<li><p class="first">Importing modules simultaneously in two different threads no longer
deadlocks; it will now raise an <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.  A new API
function, <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModuleNoBlock" title="PyImport_ImportModuleNoBlock"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModuleNoBlock()</span></code></a>, will look for a
module in <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> first, then try to import it after
acquiring an import lock.  If the import lock is held by another
thread, an <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a> is raised.
(Contributed by Christian Heimes.)</p>
</li>
<li><p class="first">Several functions return information about the platform’s
floating-point support.  <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMax" title="PyFloat_GetMax"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMax()</span></code></a> returns
the maximum representable floating point value,
and <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetMin" title="PyFloat_GetMin"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetMin()</span></code></a> returns the minimum
positive value.  <a class="reference internal" href="../c-api/float.html#c.PyFloat_GetInfo" title="PyFloat_GetInfo"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFloat_GetInfo()</span></code></a> returns an object
containing more information from the <code class="file docutils literal notranslate"><span class="pre">float.h</span></code> file, such as
<code class="docutils literal notranslate"><span class="pre">&quot;mant_dig&quot;</span></code> (number of digits in the mantissa), <code class="docutils literal notranslate"><span class="pre">&quot;epsilon&quot;</span></code>
(smallest difference between 1.0 and the next largest value
representable), and several others.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1534">bpo-1534</a>.)</p>
</li>
<li><p class="first">C functions and methods that use
<a class="reference internal" href="../c-api/complex.html#c.PyComplex_AsCComplex" title="PyComplex_AsCComplex"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyComplex_AsCComplex()</span></code></a> will now accept arguments that
have a <a class="reference internal" href="../reference/datamodel.html#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> method.  In particular, the functions in the
<a class="reference internal" href="../library/cmath.html#module-cmath" title="cmath: Mathematical functions for complex numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cmath</span></code></a> module will now accept objects with this method.
This is a backport of a Python 3.0 change.
(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue1675423">bpo-1675423</a>.)</p>
</li>
<li><p class="first">Python’s C API now includes two functions for case-insensitive string
comparisons, <code class="docutils literal notranslate"><span class="pre">PyOS_stricmp(char*,</span> <span class="pre">char*)</span></code>
and <code class="docutils literal notranslate"><span class="pre">PyOS_strnicmp(char*,</span> <span class="pre">char*,</span> <span class="pre">Py_ssize_t)</span></code>.
(Contributed by Christian Heimes; <a class="reference external" href="https://bugs.python.org/issue1635">bpo-1635</a>.)</p>
</li>
<li><p class="first">Many C extensions define their own little macro for adding
integers and strings to the module’s dictionary in the
<code class="docutils literal notranslate"><span class="pre">init*</span></code> function.  Python 2.6 finally defines standard macros
for adding values to a module, <a class="reference internal" href="../c-api/module.html#c.PyModule_AddStringMacro" title="PyModule_AddStringMacro"><code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddStringMacro</span></code></a>
and <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyModule_AddIntMacro()</span></code>.  (Contributed by
Christian Heimes.)</p>
</li>
<li><p class="first">Some macros were renamed in both 3.0 and 2.6 to make it clearer that
they are macros,
not functions.  <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Size()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_SIZE()</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Type()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TYPE()</span></code>, and
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_Refcnt()</span></code> became <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_REFCNT()</span></code>.
The mixed-case macros are still available
in Python 2.6 for backward compatibility.
(<a class="reference external" href="https://bugs.python.org/issue1629">bpo-1629</a>)</p>
</li>
<li><p class="first">Distutils now places C extensions it builds in a
different directory when running on a debug version of Python.
(Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue1530959">bpo-1530959</a>.)</p>
</li>
<li><p class="first">Several basic data types, such as integers and strings, maintain
internal free lists of objects that can be re-used.  The data
structures for these free lists now follow a naming convention: the
variable is always named <code class="docutils literal notranslate"><span class="pre">free_list</span></code>, the counter is always named
<code class="docutils literal notranslate"><span class="pre">numfree</span></code>, and a macro <code class="docutils literal notranslate"><span class="pre">Py&lt;typename&gt;_MAXFREELIST</span></code> is
always defined.</p>
</li>
<li><p class="first">A new Makefile target, “make patchcheck”, prepares the Python source tree
for making a patch: it fixes trailing whitespace in all modified
<code class="docutils literal notranslate"><span class="pre">.py</span></code> files, checks whether the documentation has been changed,
and reports whether the <code class="file docutils literal notranslate"><span class="pre">Misc/ACKS</span></code> and <code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> files
have been updated.
(Contributed by Brett Cannon.)</p>
<p>Another new target, “make profile-opt”, compiles a Python binary
using GCC’s profile-guided optimization.  It compiles Python with
profiling enabled, runs the test suite to obtain a set of profiling
results, and then compiles using these results for optimization.
(Contributed by Gregory P. Smith.)</p>
</li>
</ul>
<div class="section" id="port-specific-changes-windows">
<h3>Port-Specific Changes: Windows<a class="headerlink" href="#port-specific-changes-windows" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">The support for Windows 95, 98, ME and NT4 has been dropped.
Python 2.6 requires at least Windows 2000 SP4.</p>
</li>
<li><p class="first">The new default compiler on Windows is Visual Studio 2008 (version
9.0). The build directories for Visual Studio 2003 (version 7.1) and
2005 (version 8.0) were moved into the PC/ directory. The new
<code class="file docutils literal notranslate"><span class="pre">PCbuild</span></code> directory supports cross compilation for X64, debug
builds and Profile Guided Optimization (PGO). PGO builds are roughly
10% faster than normal builds.  (Contributed by Christian Heimes
with help from Amaury Forgeot d’Arc and Martin von Loewis.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/msvcrt.html#module-msvcrt" title="msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msvcrt</span></code></a> module now supports
both the normal and wide char variants of the console I/O
API.  The <code class="xref py py-func docutils literal notranslate"><span class="pre">getwch()</span></code> function reads a keypress and returns a Unicode
value, as does the <code class="xref py py-func docutils literal notranslate"><span class="pre">getwche()</span></code> function.  The <code class="xref py py-func docutils literal notranslate"><span class="pre">putwch()</span></code> function
takes a Unicode character and writes it to the console.
(Contributed by Christian Heimes.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/os.path.html#os.path.expandvars" title="os.path.expandvars"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.path.expandvars()</span></code></a> will now expand environment variables in
the form “%var%”, and “~user” will be expanded into the user’s home
directory path.  (Contributed by Josiah Carlson; <a class="reference external" href="https://bugs.python.org/issue957650">bpo-957650</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module’s socket objects now have an
<code class="xref py py-meth docutils literal notranslate"><span class="pre">ioctl()</span></code> method that provides a limited interface to the
<code class="xref c c-func docutils literal notranslate"><span class="pre">WSAIoctl()</span></code> system interface.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> module now has a function,
<code class="xref py py-func docutils literal notranslate"><span class="pre">ExpandEnvironmentStrings()</span></code>,
that expands environment variable references such as <code class="docutils literal notranslate"><span class="pre">%NAME%</span></code>
in an input string.  The handle objects provided by this
module now support the context protocol, so they can be used
in <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements. (Contributed by Christian Heimes.)</p>
<p><a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> also has better support for x64 systems,
exposing the <code class="xref py py-func docutils literal notranslate"><span class="pre">DisableReflectionKey()</span></code>, <code class="xref py py-func docutils literal notranslate"><span class="pre">EnableReflectionKey()</span></code>,
and <code class="xref py py-func docutils literal notranslate"><span class="pre">QueryReflectionKey()</span></code> functions, which enable and disable
registry reflection for 32-bit processes running on 64-bit systems.
(<a class="reference external" href="https://bugs.python.org/issue1753245">bpo-1753245</a>)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/msilib.html#module-msilib" title="msilib: Creation of Microsoft Installer files, and CAB files. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msilib</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Record</span></code> object
gained <code class="xref py py-meth docutils literal notranslate"><span class="pre">GetInteger()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">GetString()</span></code> methods that
return field values as an integer or a string.
(Contributed by Floris Bruynooghe; <a class="reference external" href="https://bugs.python.org/issue2125">bpo-2125</a>.)</p>
</li>
</ul>
</div>
<div class="section" id="port-specific-changes-mac-os-x">
<h3>Port-Specific Changes: Mac OS X<a class="headerlink" href="#port-specific-changes-mac-os-x" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>When compiling a framework build of Python, you can now specify the
framework name to be used by providing the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-framework-name=</span></code> option to the
<strong class="program">configure</strong> script.</li>
<li>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> module has been removed.  This in turn required the
<a class="reference internal" href="../library/macostools.html#macostools.touched" title="macostools.touched"><code class="xref py py-func docutils literal notranslate"><span class="pre">macostools.touched()</span></code></a> function to be removed because it depended on the
<code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code> module.  (<a class="reference external" href="https://bugs.python.org/issue1490190">bpo-1490190</a>)</li>
<li>Many other Mac OS modules have been deprecated and will be removed in
Python 3.0:
<code class="xref py py-mod docutils literal notranslate"><span class="pre">_builtinSuites</span></code>,
<a class="reference internal" href="../library/aepack.html#module-aepack" title="aepack: Conversion between Python variables and AppleEvent data containers. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aepack</span></code></a>,
<a class="reference internal" href="../library/aetools.html#module-aetools" title="aetools: Basic support for sending Apple Events (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetools</span></code></a>,
<a class="reference internal" href="../library/aetypes.html#module-aetypes" title="aetypes: Python representation of the Apple Event Object Model. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">aetypes</span></code></a>,
<a class="reference internal" href="../library/undoc.html#module-applesingle" title="applesingle: Rudimentary decoder for AppleSingle format files. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">applesingle</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrawmain</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">appletrunner</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">argvemulator</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Audio_mac</span></code>,
<a class="reference internal" href="../library/autogil.html#module-autoGIL" title="autoGIL: Global Interpreter Lock handling in event loops. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">autoGIL</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Carbon</span></code>,
<a class="reference internal" href="../library/undoc.html#module-cfmfile" title="cfmfile: Code Fragment Resource module. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cfmfile</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">CodeWarrior</span></code>,
<a class="reference internal" href="../library/colorpicker.html#module-ColorPicker" title="ColorPicker: Interface to the standard color selection dialog. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ColorPicker</span></code></a>,
<a class="reference internal" href="../library/easydialogs.html#module-EasyDialogs" title="EasyDialogs: Basic Macintosh dialogs. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">EasyDialogs</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Explorer</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Finder</span></code>,
<a class="reference internal" href="../library/framework.html#module-FrameWork" title="FrameWork: Interactive application framework. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FrameWork</span></code></a>,
<a class="reference internal" href="../library/macostools.html#module-findertools" title="findertools: Wrappers around the finder's Apple Events interface. (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">findertools</span></code></a>,
<a class="reference internal" href="../library/ic.html#module-ic" title="ic: Access to the Mac OS X Internet Config. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ic</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">icglue</span></code>,
<a class="reference internal" href="../library/undoc.html#module-icopen" title="icopen: Internet Config replacement for open(). (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">icopen</span></code></a>,
<a class="reference internal" href="../library/undoc.html#module-macerrors" title="macerrors: Constant definitions for many Mac OS error codes. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macerrors</span></code></a>,
<a class="reference internal" href="../library/macos.html#module-MacOS" title="MacOS: Access to Mac OS-specific interpreter features. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MacOS</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">macfs</span></code>,
<a class="reference internal" href="../library/macostools.html#module-macostools" title="macostools: Convenience routines for file manipulation. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macostools</span></code></a>,
<a class="reference internal" href="../library/undoc.html#module-macresource" title="macresource: Locate script resources. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">macresource</span></code></a>,
<a class="reference internal" href="../library/miniaeframe.html#module-MiniAEFrame" title="MiniAEFrame: Support to act as an Open Scripting Architecture (OSA) server (&quot;Apple Events&quot;). (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">MiniAEFrame</span></code></a>,
<a class="reference internal" href="../library/undoc.html#module-Nav" title="Nav: Interface to Navigation Services. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">Nav</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Netscape</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">OSATerminology</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">pimp</span></code>,
<a class="reference internal" href="../library/undoc.html#module-PixMapWrapper" title="PixMapWrapper: Wrapper for PixMap objects. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">PixMapWrapper</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">StdSuites</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">SystemEvents</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">Terminal</span></code>, and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">terminalcommand</span></code>.</li>
</ul>
</div>
<div class="section" id="port-specific-changes-irix">
<h3>Port-Specific Changes: IRIX<a class="headerlink" href="#port-specific-changes-irix" title="Permalink to this headline">¶</a></h3>
<p>A number of old IRIX-specific modules were deprecated and will
be removed in Python 3.0:
<a class="reference internal" href="../library/al.html#module-al" title="al: Audio functions on the SGI. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">al</span></code></a> and <a class="reference internal" href="../library/al.html#module-AL" title="AL: Constants used with the al module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">AL</span></code></a>,
<a class="reference internal" href="../library/cd.html#module-cd" title="cd: Interface to the CD-ROM on Silicon Graphics systems. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">cd</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">cddb</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">cdplayer</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">CL</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">cl</span></code>,
<a class="reference internal" href="../library/gl.html#module-DEVICE" title="DEVICE: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">DEVICE</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ERRNO</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">FILE</span></code>,
<a class="reference internal" href="../library/fl.html#module-FL" title="FL: Constants used with the fl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">FL</span></code></a> and <a class="reference internal" href="../library/fl.html#module-fl" title="fl: FORMS library for applications with graphical user interfaces. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fl</span></code></a>,
<a class="reference internal" href="../library/fl.html#module-flp" title="flp: Functions for loading stored FORMS designs. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">flp</span></code></a>,
<a class="reference internal" href="../library/fm.html#module-fm" title="fm: Font Manager interface for SGI workstations. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">fm</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">GET</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">GLWS</span></code>,
<a class="reference internal" href="../library/gl.html#module-GL" title="GL: Constants used with the gl module. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">GL</span></code></a> and <a class="reference internal" href="../library/gl.html#module-gl" title="gl: Functions from the Silicon Graphics Graphics Library. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">gl</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">IN</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">IOCTL</span></code>,
<a class="reference internal" href="../library/jpeg.html#module-jpeg" title="jpeg: Read and write image files in compressed JPEG format. (deprecated) (IRIX)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">jpeg</span></code></a>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">panelparser</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">readcd</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">SV</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">sv</span></code>,
<code class="xref py py-mod docutils literal notranslate"><span class="pre">torgb</span></code>,
<a class="reference internal" href="../library/undoc.html#module-videoreader" title="videoreader: Read QuickTime movies frame by frame for further processing. (deprecated) (Mac)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">videoreader</span></code></a>, and
<code class="xref py py-mod docutils literal notranslate"><span class="pre">WAIT</span></code>.</p>
</div>
</div>
<div class="section" id="porting-to-python-2-6">
<h2>Porting to Python 2.6<a class="headerlink" href="#porting-to-python-2-6" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes and other bugfixes
that may require changes to your code:</p>
<ul>
<li><p class="first">Classes that aren’t supposed to be hashable should
set <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> in their definitions to indicate
the fact.</p>
</li>
<li><p class="first">String exceptions have been removed.  Attempting to use them raises a
<a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method of <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.deque</span></code></a>
now clears any existing contents of the deque
before adding elements from the iterable.  This change makes the
behavior match <code class="docutils literal notranslate"><span class="pre">list.__init__()</span></code>.</p>
</li>
<li><p class="first"><a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__init__()</span></code></a> previously accepted arbitrary arguments and
keyword arguments, ignoring them.  In Python 2.6, this is no longer
allowed and will result in a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.  This will affect
<a class="reference internal" href="../reference/datamodel.html#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> methods that end up calling the corresponding
method on <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> (perhaps through using <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>).
See <a class="reference external" href="https://bugs.python.org/issue1683368">bpo-1683368</a> for discussion.</p>
</li>
<li><p class="first">The <code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> constructor now accepts leading and trailing
whitespace when passed a string.  Previously it would raise an
<code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidOperation</span></code> exception.  On the other hand, the
<code class="xref py py-meth docutils literal notranslate"><span class="pre">create_decimal()</span></code> method of <code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code> objects now
explicitly disallows extra whitespace, raising a
<code class="xref py py-exc docutils literal notranslate"><span class="pre">ConversionSyntax</span></code> exception.</p>
</li>
<li><p class="first">Due to an implementation accident, if you passed a file path to
the built-in  <a class="reference internal" href="../library/functions.html#__import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a> function, it would actually import
the specified file.  This was never intended to work, however, and
the implementation now explicitly checks for this case and raises
an <a class="reference internal" href="../library/exceptions.html#exceptions.ImportError" title="exceptions.ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>.</p>
</li>
<li><p class="first">C API: the <a class="reference internal" href="../c-api/import.html#c.PyImport_Import" title="PyImport_Import"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_Import()</span></code></a> and <a class="reference internal" href="../c-api/import.html#c.PyImport_ImportModule" title="PyImport_ImportModule"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyImport_ImportModule()</span></code></a>
functions now default to absolute imports, not relative imports.
This will affect C extensions that import other modules.</p>
</li>
<li><p class="first">C API: extension data types that shouldn’t be hashable
should define their <code class="docutils literal notranslate"><span class="pre">tp_hash</span></code> slot to
<a class="reference internal" href="../c-api/object.html#c.PyObject_HashNotImplemented" title="PyObject_HashNotImplemented"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyObject_HashNotImplemented()</span></code></a>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module exception <a class="reference internal" href="../library/socket.html#socket.error" title="socket.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">socket.error</span></code></a> now inherits
from <a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.  Previously it wasn’t a subclass of
<a class="reference internal" href="../library/exceptions.html#exceptions.StandardError" title="exceptions.StandardError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StandardError</span></code></a> but now it is, through <a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a>.
(Implemented by Gregory P. Smith; <a class="reference external" href="https://bugs.python.org/issue1706815">bpo-1706815</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> module no longer automatically converts
<a class="reference internal" href="../library/datetime.html#datetime.date" title="datetime.date"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.date</span></code></a> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime.time</span></code></a> to the
<a class="reference internal" href="../library/xmlrpclib.html#xmlrpclib.DateTime" title="xmlrpclib.DateTime"><code class="xref py py-class docutils literal notranslate"><span class="pre">xmlrpclib.DateTime</span></code></a> type; the conversion semantics were
not necessarily correct for all applications.  Code using
<a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> should convert <code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code> and <a class="reference internal" href="../library/datetime.html#datetime.time" title="datetime.time"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a>
instances. (<a class="reference external" href="https://bugs.python.org/issue1330538">bpo-1330538</a>)</p>
</li>
<li><p class="first">(3.0-warning mode) The <code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code> class now warns
when accessed using slicing or index access; having
<code class="xref py py-class docutils literal notranslate"><span class="pre">Exception</span></code> behave like a tuple is being phased out.</p>
</li>
<li><p class="first">(3.0-warning mode) inequality comparisons between two dictionaries
or two objects that don’t implement comparison methods are reported
as warnings.  <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">==</span> <span class="pre">dict2</span></code> still works, but <code class="docutils literal notranslate"><span class="pre">dict1</span> <span class="pre">&lt;</span> <span class="pre">dict2</span></code>
is being phased out.</p>
<p>Comparisons between cells, which are an implementation detail of Python’s
scoping rules, also cause warnings because such comparisons are forbidden
entirely in 3.0.</p>
</li>
</ul>
</div>
<div class="section" id="acknowledgements">
<span id="acks"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
article: Georg Brandl, Steve Brown, Nick Coghlan, Ralph Corderoy,
Jim Jewett, Kent Johnson, Chris Lambacher,  Martin Michlmayr,
Antoine Pitrou, Brian Warner.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.6</a><ul>
<li><a class="reference internal" href="#python-3-0">Python 3.0</a></li>
<li><a class="reference internal" href="#changes-to-the-development-process">Changes to the Development Process</a><ul>
<li><a class="reference internal" href="#new-issue-tracker-roundup">New Issue Tracker: Roundup</a></li>
<li><a class="reference internal" href="#new-documentation-format-restructuredtext-using-sphinx">New Documentation Format: reStructuredText Using Sphinx</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li><a class="reference internal" href="#writing-context-managers">Writing Context Managers</a></li>
<li><a class="reference internal" href="#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
<li><a class="reference internal" href="#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
<li><a class="reference internal" href="#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
<li><a class="reference internal" href="#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
<li><a class="reference internal" href="#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
<li><a class="reference internal" href="#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
<li><a class="reference internal" href="#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
<li><a class="reference internal" href="#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
<li><a class="reference internal" href="#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
<li><a class="reference internal" href="#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
<li><a class="reference internal" href="#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
<li><a class="reference internal" href="#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
<li><a class="reference internal" href="#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a><ul>
<li><a class="reference internal" href="#the-fractions-module">The <code class="docutils literal notranslate"><span class="pre">fractions</span></code> Module</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
<li><a class="reference internal" href="#interpreter-changes">Interpreter Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a><ul>
<li><a class="reference internal" href="#the-ast-module">The <code class="docutils literal notranslate"><span class="pre">ast</span></code> module</a></li>
<li><a class="reference internal" href="#the-future-builtins-module">The <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> module</a></li>
<li><a class="reference internal" href="#the-json-module-javascript-object-notation">The <code class="docutils literal notranslate"><span class="pre">json</span></code> module: JavaScript Object Notation</a></li>
<li><a class="reference internal" href="#the-plistlib-module-a-property-list-parser">The <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> module: A Property-List Parser</a></li>
<li><a class="reference internal" href="#ctypes-enhancements">ctypes Enhancements</a></li>
<li><a class="reference internal" href="#improved-ssl-support">Improved SSL Support</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deprecations-and-removals">Deprecations and Removals</a></li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
<li><a class="reference internal" href="#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
<li><a class="reference internal" href="#port-specific-changes-irix">Port-Specific Changes: IRIX</a></li>
</ul>
</li>
<li><a class="reference internal" href="#porting-to-python-2-6">Porting to Python 2.6</a></li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="2.7.html"
                        title="previous chapter">What’s New in Python 2.7</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.5.html"
                        title="next chapter">What’s New in Python 2.5</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.6.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.5.html" title="What’s New in Python 2.5"
             >next</a> |</li>
        <li class="right" >
          <a href="2.7.html" title="What’s New in Python 2.7"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�^�html/whatsnew/2.7.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python 2.7 &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.6" href="2.6.html" />
    <link rel="prev" title="What’s New in Python" href="index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/2.7.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="What’s New in Python"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">What’s New in Python</a> &#187;</li> 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python-2-7">
<h1>What’s New in Python 2.7<a class="headerlink" href="#what-s-new-in-python-2-7" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field-odd field"><th class="field-name">Author:</th><td class="field-body">A.M. Kuchling (amk at amk.ca)</td>
</tr>
</tbody>
</table>
<p>This article explains the new features in Python 2.7.  Python 2.7 was released
on July 3, 2010.</p>
<p>Numeric handling has been improved in many ways, for both
floating-point numbers and for the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class.
There are some useful additions to the standard library, such as a
greatly enhanced <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module, the <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module
for parsing command-line options, convenient <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a>
and <a class="reference internal" href="../library/collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> classes in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module,
and many other improvements.</p>
<p>Python 2.7 is planned to be the last of the 2.x releases, so we worked
on making it a good release for the long term.  To help with porting
to Python 3, several new features from the Python 3.x series have been
included in 2.7.</p>
<p>This article doesn’t attempt to provide a complete specification of
the new features, but instead provides a convenient overview.  For
full details, you should refer to the documentation for Python 2.7 at
<a class="reference external" href="https://docs.python.org">https://docs.python.org</a>. If you want to understand the rationale for
the design and implementation, refer to the PEP for a particular new
feature or the issue on <a class="reference external" href="https://bugs.python.org">https://bugs.python.org</a> in which a change was
discussed.  Whenever possible, “What’s New in Python” links to the
bug/patch item for each change.</p>
<div class="section" id="the-future-for-python-2-x">
<span id="whatsnew27-python31"></span><h2>The Future for Python 2.x<a class="headerlink" href="#the-future-for-python-2-x" title="Permalink to this headline">¶</a></h2>
<p>Python 2.7 is the last major release in the 2.x series, as the Python
maintainers have shifted the focus of their new feature development efforts
to the Python 3.x series. This means that while Python 2 continues to
receive bug fixes, and to be updated to build correctly on new hardware and
versions of supported operated systems, there will be no new full feature
releases for the language or standard library.</p>
<p>However, while there is a large common subset between Python 2.7 and Python
3, and many of the changes involved in migrating to that common subset, or
directly to Python 3, can be safely automated, some other changes (notably
those associated with Unicode handling) may require careful consideration,
and preferably robust automated regression test suites, to migrate
effectively.</p>
<p>This means that Python 2.7 will remain in place for a long time, providing a
stable and supported base platform for production systems that have not yet
been ported to Python 3. The full expected lifecycle of the Python 2.7
series is detailed in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0373"><strong>PEP 373</strong></a>.</p>
<p>Some key consequences of the long-term significance of 2.7 are:</p>
<ul class="simple">
<li>As noted above, the 2.7 release has a much longer period of maintenance
when compared to earlier 2.x versions. Python 2.7 is currently expected to
remain supported by the core development team (receiving security updates
and other bug fixes) until at least 2020 (10 years after its initial
release, compared to the more typical support period of 18–24 months).</li>
<li>As the Python 2.7 standard library ages, making effective use of the
Python Package Index (either directly or via a redistributor) becomes
more important for Python 2 users. In addition to a wide variety of third
party packages for various tasks, the available packages include backports
of new modules and features from the Python 3 standard library that are
compatible with Python 2, as well as various tools and libraries that can
make it easier to migrate to Python 3. The <a class="reference external" href="https://packaging.python.org">Python Packaging User Guide</a> provides guidance on downloading and
installing software from the Python Package Index.</li>
<li>While the preferred approach to enhancing Python 2 is now the publication
of new packages on the Python Package Index, this approach doesn’t
necessarily work in all cases, especially those related to network
security. In exceptional cases that cannot be handled adequately by
publishing new or updated packages on PyPI, the Python Enhancement
Proposal process may be used to make the case for adding new features
directly to the Python 2 standard library. Any such additions, and the
maintenance releases where they were added, will be noted in the
<a class="reference internal" href="#py27-maintenance-enhancements"><span class="std std-ref">New Features Added to Python 2.7 Maintenance Releases</span></a> section below.</li>
</ul>
<p>For projects wishing to migrate from Python 2 to Python 3, or for library
and framework developers wishing to support users on both Python 2 and
Python 3, there are a variety of tools and guides available to help decide
on a suitable approach and manage some of the technical details involved.
The recommended starting point is the <a class="reference internal" href="../howto/pyporting.html#pyporting-howto"><span class="std std-ref">Porting Python 2 Code to Python 3</span></a> HOWTO guide.</p>
</div>
<div class="section" id="changes-to-the-handling-of-deprecation-warnings">
<h2>Changes to the Handling of Deprecation Warnings<a class="headerlink" href="#changes-to-the-handling-of-deprecation-warnings" title="Permalink to this headline">¶</a></h2>
<p>For Python 2.7, a policy decision was made to silence warnings only of
interest to developers by default.  <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> and its
descendants are now ignored unless otherwise requested, preventing
users from seeing warnings triggered by an application.  This change
was also made in the branch that became Python 3.2. (Discussed
on stdlib-sig and carried out in <a class="reference external" href="https://bugs.python.org/issue7319">bpo-7319</a>.)</p>
<p>In previous releases, <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> messages were
enabled by default, providing Python developers with a clear
indication of where their code may break in a future major version
of Python.</p>
<p>However, there are increasingly many users of Python-based
applications who are not directly involved in the development of
those applications.  <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> messages are
irrelevant to such users, making them worry about an application
that’s actually working correctly and burdening application developers
with responding to these concerns.</p>
<p>You can re-enable display of <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> messages by
running Python with the <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wdefault</span></code></a> (short form:
<a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Wd</span></code></a>) switch, or by setting the <span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONWARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONWARNINGS</span></code></a>
environment variable to <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code> (or <code class="docutils literal notranslate"><span class="pre">&quot;d&quot;</span></code>) before running
Python.  Python code can also re-enable them
by calling <code class="docutils literal notranslate"><span class="pre">warnings.simplefilter('default')</span></code>.</p>
<p>The <code class="docutils literal notranslate"><span class="pre">unittest</span></code> module also automatically reenables deprecation warnings
when running tests.</p>
</div>
<div class="section" id="python-3-1-features">
<h2>Python 3.1 Features<a class="headerlink" href="#python-3-1-features" title="Permalink to this headline">¶</a></h2>
<p>Much as Python 2.6 incorporated features from Python 3.0,
version 2.7 incorporates some of the new features
in Python 3.1.  The 2.x series continues to provide tools
for migrating to the 3.x series.</p>
<p>A partial list of 3.1 features that were backported to 2.7:</p>
<ul class="simple">
<li>The syntax for set literals (<code class="docutils literal notranslate"><span class="pre">{1,2,3}</span></code> is a mutable set).</li>
<li>Dictionary and set comprehensions (<code class="docutils literal notranslate"><span class="pre">{i:</span> <span class="pre">i*2</span> <span class="pre">for</span> <span class="pre">i</span> <span class="pre">in</span> <span class="pre">range(3)}</span></code>).</li>
<li>Multiple context managers in a single <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</li>
<li>A new version of the <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> library, rewritten in C for performance.</li>
<li>The ordered-dictionary type described in <a class="reference internal" href="#pep-0372"><span class="std std-ref">PEP 372: Adding an Ordered Dictionary to collections</span></a>.</li>
<li>The new <code class="docutils literal notranslate"><span class="pre">&quot;,&quot;</span></code> format specifier described in <a class="reference internal" href="#pep-0378"><span class="std std-ref">PEP 378: Format Specifier for Thousands Separator</span></a>.</li>
<li>The <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object.</li>
<li>A small subset of the <a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> module,
<a class="reference external" href="#importlib-section">described below</a>.</li>
<li>The <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> of a float <code class="docutils literal notranslate"><span class="pre">x</span></code> is shorter in many cases: it’s now
based on the shortest decimal string that’s guaranteed to round back
to <code class="docutils literal notranslate"><span class="pre">x</span></code>.  As in previous versions of Python, it’s guaranteed that
<code class="docutils literal notranslate"><span class="pre">float(repr(x))</span></code> recovers <code class="docutils literal notranslate"><span class="pre">x</span></code>.</li>
<li>Float-to-string and string-to-float conversions are correctly rounded.
The <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function is also now correctly rounded.</li>
<li>The <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule" title="PyCapsule"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCapsule</span></code></a> type, used to provide a C API for extension modules.</li>
<li>The <a class="reference internal" href="../c-api/long.html#c.PyLong_AsLongAndOverflow" title="PyLong_AsLongAndOverflow"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_AsLongAndOverflow()</span></code></a> C API function.</li>
</ul>
<p>Other new Python3-mode warnings include:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/operator.html#operator.isCallable" title="operator.isCallable"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.isCallable()</span></code></a> and <a class="reference internal" href="../library/operator.html#operator.sequenceIncludes" title="operator.sequenceIncludes"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.sequenceIncludes()</span></code></a>,
which are not supported in 3.x, now trigger warnings.</li>
<li>The <a class="reference internal" href="../using/cmdline.html#cmdoption-3"><code class="xref std std-option docutils literal notranslate"><span class="pre">-3</span></code></a> switch now automatically
enables the <a class="reference internal" href="../using/cmdline.html#cmdoption-q"><code class="xref std std-option docutils literal notranslate"><span class="pre">-Qwarn</span></code></a> switch that causes warnings
about using classic division with integers and long integers.</li>
</ul>
</div>
<div class="section" id="pep-372-adding-an-ordered-dictionary-to-collections">
<span id="pep-0372"></span><h2>PEP 372: Adding an Ordered Dictionary to collections<a class="headerlink" href="#pep-372-adding-an-ordered-dictionary-to-collections" title="Permalink to this headline">¶</a></h2>
<p>Regular Python dictionaries iterate over key/value pairs in arbitrary order.
Over the years, a number of authors have written alternative implementations
that remember the order that the keys were originally inserted.  Based on
the experiences from those implementations, 2.7 introduces a new
<a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> class in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module.</p>
<p>The <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> API provides the same interface as regular
dictionaries but iterates over keys and values in a guaranteed order
depending on when a key was first inserted:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">OrderedDict</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="p">([(</span><span class="s1">&#39;first&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>                 <span class="p">(</span><span class="s1">&#39;second&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span>
<span class="gp">... </span>                 <span class="p">(</span><span class="s1">&#39;third&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;first&#39;, 1), (&#39;second&#39;, 2), (&#39;third&#39;, 3)]</span>
</pre></div>
</div>
<p>If a new entry overwrites an existing entry, the original insertion
position is left unchanged:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;second&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;first&#39;, 1), (&#39;second&#39;, 4), (&#39;third&#39;, 3)]</span>
</pre></div>
</div>
<p>Deleting an entry and reinserting it will move it to the end:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">d</span><span class="p">[</span><span class="s1">&#39;second&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="s1">&#39;second&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">items</span><span class="p">()</span>
<span class="go">[(&#39;first&#39;, 1), (&#39;third&#39;, 3), (&#39;second&#39;, 5)]</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/collections.html#collections.OrderedDict.popitem" title="collections.OrderedDict.popitem"><code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code></a> method has an optional <em>last</em>
argument that defaults to <code class="docutils literal notranslate"><span class="pre">True</span></code>.  If <em>last</em> is true, the most recently
added key is returned and removed; if it’s false, the
oldest key is selected:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">od</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="p">([(</span><span class="n">x</span><span class="p">,</span><span class="mi">0</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">20</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od</span><span class="o">.</span><span class="n">popitem</span><span class="p">()</span>
<span class="go">(19, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od</span><span class="o">.</span><span class="n">popitem</span><span class="p">()</span>
<span class="go">(18, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od</span><span class="o">.</span><span class="n">popitem</span><span class="p">(</span><span class="n">last</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">(0, 0)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od</span><span class="o">.</span><span class="n">popitem</span><span class="p">(</span><span class="n">last</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="go">(1, 0)</span>
</pre></div>
</div>
<p>Comparing two ordered dictionaries checks both the keys and values,
and requires that the insertion order was the same:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">od1</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="p">([(</span><span class="s1">&#39;first&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>                   <span class="p">(</span><span class="s1">&#39;second&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span>
<span class="gp">... </span>                   <span class="p">(</span><span class="s1">&#39;third&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od2</span> <span class="o">=</span> <span class="n">OrderedDict</span><span class="p">([(</span><span class="s1">&#39;third&#39;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span>
<span class="gp">... </span>                   <span class="p">(</span><span class="s1">&#39;first&#39;</span><span class="p">,</span> <span class="mi">1</span><span class="p">),</span>
<span class="gp">... </span>                   <span class="p">(</span><span class="s1">&#39;second&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od1</span> <span class="o">==</span> <span class="n">od2</span>
<span class="go">False</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Move &#39;third&#39; key to the end</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">del</span> <span class="n">od2</span><span class="p">[</span><span class="s1">&#39;third&#39;</span><span class="p">];</span> <span class="n">od2</span><span class="p">[</span><span class="s1">&#39;third&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">3</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">od1</span> <span class="o">==</span> <span class="n">od2</span>
<span class="go">True</span>
</pre></div>
</div>
<p>Comparing an <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> with a regular dictionary
ignores the insertion order and just compares the keys and values.</p>
<p>How does the <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> work?  It maintains a
doubly-linked list of keys, appending new keys to the list as they’re inserted.
A secondary dictionary maps keys to their corresponding list node, so
deletion doesn’t have to traverse the entire linked list and therefore
remains O(1).</p>
<p>The standard library now supports use of ordered dictionaries in several
modules.</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> module uses them by default, meaning that
configuration files can now be read, modified, and then written back
in their original order.</li>
<li>The <a class="reference internal" href="../library/collections.html#collections.somenamedtuple._asdict" title="collections.somenamedtuple._asdict"><code class="xref py py-meth docutils literal notranslate"><span class="pre">_asdict()</span></code></a> method for
<a class="reference internal" href="../library/collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-func docutils literal notranslate"><span class="pre">collections.namedtuple()</span></code></a> now returns an ordered dictionary with the
values appearing in the same order as the underlying tuple indices.</li>
<li>The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module’s <a class="reference internal" href="../library/json.html#json.JSONDecoder" title="json.JSONDecoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONDecoder</span></code></a> class
constructor was extended with an <em>object_pairs_hook</em> parameter to
allow <code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code> instances to be built by the decoder.
Support was also added for third-party tools like
<a class="reference external" href="http://pyyaml.org/">PyYAML</a>.</li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0372"><strong>PEP 372</strong></a> - Adding an ordered dictionary to collections</dt>
<dd>PEP written by Armin Ronacher and Raymond Hettinger;
implemented by Raymond Hettinger.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-378-format-specifier-for-thousands-separator">
<span id="pep-0378"></span><h2>PEP 378: Format Specifier for Thousands Separator<a class="headerlink" href="#pep-378-format-specifier-for-thousands-separator" title="Permalink to this headline">¶</a></h2>
<p>To make program output more readable, it can be useful to add
separators to large numbers, rendering them as
18,446,744,073,709,551,616 instead of 18446744073709551616.</p>
<p>The fully general solution for doing this is the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module,
which can use different separators (“,” in North America, “.” in
Europe) and different grouping sizes, but <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> is complicated
to use and unsuitable for multi-threaded applications where different
threads are producing output for different locales.</p>
<p>Therefore, a simple comma-grouping mechanism has been added to the
mini-language used by the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.  When
formatting a floating-point number, simply include a comma between the
width and the precision:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:20,.2f}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mf">18446744073709551616.0</span><span class="p">)</span>
<span class="go">&#39;18,446,744,073,709,551,616.00&#39;</span>
</pre></div>
</div>
<p>When formatting an integer, include the comma after the width:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{:20,d}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">18446744073709551616</span><span class="p">)</span>
<span class="go">&#39;18,446,744,073,709,551,616&#39;</span>
</pre></div>
</div>
<p>This mechanism is not adaptable at all; commas are always used as the
separator and the grouping is always into three-digit groups.  The
comma-formatting mechanism isn’t as general as the <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a>
module, but it’s easier to use.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-3"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0378"><strong>PEP 378</strong></a> - Format Specifier for Thousands Separator</dt>
<dd>PEP written by Raymond Hettinger; implemented by Eric Smith.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-389-the-argparse-module-for-parsing-command-lines">
<h2>PEP 389: The argparse Module for Parsing Command Lines<a class="headerlink" href="#pep-389-the-argparse-module-for-parsing-command-lines" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module for parsing command-line arguments was
added as a more powerful replacement for the
<a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> module.</p>
<p>This means Python now supports three different modules for parsing
command-line arguments: <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a>, <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>, and
<a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>.  The <a class="reference internal" href="../library/getopt.html#module-getopt" title="getopt: Portable parser for command line options; support both short and long option names."><code class="xref py py-mod docutils literal notranslate"><span class="pre">getopt</span></code></a> module closely resembles the C
library’s <code class="xref c c-func docutils literal notranslate"><span class="pre">getopt()</span></code> function, so it remains useful if you’re writing a
Python prototype that will eventually be rewritten in C.
<a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a> becomes redundant, but there are no plans to remove it
because there are many scripts still using it, and there’s no
automated way to update these scripts.  (Making the <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a>
API consistent with <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>’s interface was discussed but
rejected as too messy and difficult.)</p>
<p>In short, if you’re writing a new script and don’t need to worry
about compatibility with earlier versions of Python, use
<a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> instead of <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>.</p>
<p>Here’s an example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">argparse</span>

<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s1">&#39;Command-line example.&#39;</span><span class="p">)</span>

<span class="c1"># Add optional switches</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-v&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store_true&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;is_verbose&#39;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;produce verbose output&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-o&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;output&#39;</span><span class="p">,</span>
                    <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;FILE&#39;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;direct output to FILE instead of stdout&#39;</span><span class="p">)</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">&#39;-C&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;context&#39;</span><span class="p">,</span>
                    <span class="n">metavar</span><span class="o">=</span><span class="s1">&#39;NUM&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;display NUM lines of added context&#39;</span><span class="p">)</span>

<span class="c1"># Allow any number of additional arguments.</span>
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="n">nargs</span><span class="o">=</span><span class="s1">&#39;*&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s1">&#39;store&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s1">&#39;inputs&#39;</span><span class="p">,</span>
                    <span class="n">help</span><span class="o">=</span><span class="s1">&#39;input filenames (default is stdin)&#39;</span><span class="p">)</span>

<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
<span class="nb">print</span> <span class="n">args</span><span class="o">.</span><span class="vm">__dict__</span>
</pre></div>
</div>
<p>Unless you override it, <code class="xref std std-option docutils literal notranslate"><span class="pre">-h</span></code> and <code class="xref std std-option docutils literal notranslate"><span class="pre">--help</span></code> switches
are automatically added, and produce neatly formatted output:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-&gt;</span> <span class="o">./</span><span class="n">python</span><span class="o">.</span><span class="n">exe</span> <span class="n">argparse</span><span class="o">-</span><span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="o">--</span><span class="n">help</span>
<span class="n">usage</span><span class="p">:</span> <span class="n">argparse</span><span class="o">-</span><span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="p">[</span><span class="o">-</span><span class="n">h</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">v</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">o</span> <span class="n">FILE</span><span class="p">]</span> <span class="p">[</span><span class="o">-</span><span class="n">C</span> <span class="n">NUM</span><span class="p">]</span> <span class="p">[</span><span class="n">inputs</span> <span class="p">[</span><span class="n">inputs</span> <span class="o">...</span><span class="p">]]</span>

<span class="n">Command</span><span class="o">-</span><span class="n">line</span> <span class="n">example</span><span class="o">.</span>

<span class="n">positional</span> <span class="n">arguments</span><span class="p">:</span>
  <span class="n">inputs</span>      <span class="nb">input</span> <span class="n">filenames</span> <span class="p">(</span><span class="n">default</span> <span class="ow">is</span> <span class="n">stdin</span><span class="p">)</span>

<span class="n">optional</span> <span class="n">arguments</span><span class="p">:</span>
  <span class="o">-</span><span class="n">h</span><span class="p">,</span> <span class="o">--</span><span class="n">help</span>  <span class="n">show</span> <span class="n">this</span> <span class="n">help</span> <span class="n">message</span> <span class="ow">and</span> <span class="n">exit</span>
  <span class="o">-</span><span class="n">v</span>          <span class="n">produce</span> <span class="n">verbose</span> <span class="n">output</span>
  <span class="o">-</span><span class="n">o</span> <span class="n">FILE</span>     <span class="n">direct</span> <span class="n">output</span> <span class="n">to</span> <span class="n">FILE</span> <span class="n">instead</span> <span class="n">of</span> <span class="n">stdout</span>
  <span class="o">-</span><span class="n">C</span> <span class="n">NUM</span>      <span class="n">display</span> <span class="n">NUM</span> <span class="n">lines</span> <span class="n">of</span> <span class="n">added</span> <span class="n">context</span>
</pre></div>
</div>
<p>As with <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>, the command-line switches and arguments
are returned as an object with attributes named by the <em>dest</em> parameters:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">-&gt;</span> <span class="o">./</span><span class="n">python</span><span class="o">.</span><span class="n">exe</span> <span class="n">argparse</span><span class="o">-</span><span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">v</span>
<span class="p">{</span><span class="s1">&#39;output&#39;</span><span class="p">:</span> <span class="kc">None</span><span class="p">,</span>
 <span class="s1">&#39;is_verbose&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
 <span class="s1">&#39;context&#39;</span><span class="p">:</span> <span class="mi">0</span><span class="p">,</span>
 <span class="s1">&#39;inputs&#39;</span><span class="p">:</span> <span class="p">[]}</span>

<span class="o">-&gt;</span> <span class="o">./</span><span class="n">python</span><span class="o">.</span><span class="n">exe</span> <span class="n">argparse</span><span class="o">-</span><span class="n">example</span><span class="o">.</span><span class="n">py</span> <span class="o">-</span><span class="n">v</span> <span class="o">-</span><span class="n">o</span> <span class="o">/</span><span class="n">tmp</span><span class="o">/</span><span class="n">output</span> <span class="o">-</span><span class="n">C</span> <span class="mi">4</span> <span class="n">file1</span> <span class="n">file2</span>
<span class="p">{</span><span class="s1">&#39;output&#39;</span><span class="p">:</span> <span class="s1">&#39;/tmp/output&#39;</span><span class="p">,</span>
 <span class="s1">&#39;is_verbose&#39;</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span>
 <span class="s1">&#39;context&#39;</span><span class="p">:</span> <span class="mi">4</span><span class="p">,</span>
 <span class="s1">&#39;inputs&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;file1&#39;</span><span class="p">,</span> <span class="s1">&#39;file2&#39;</span><span class="p">]}</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> has much fancier validation than <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>; you
can specify an exact number of arguments as an integer, 0 or more
arguments by passing <code class="docutils literal notranslate"><span class="pre">'*'</span></code>, 1 or more by passing <code class="docutils literal notranslate"><span class="pre">'+'</span></code>, or an
optional argument with <code class="docutils literal notranslate"><span class="pre">'?'</span></code>.  A top-level parser can contain
sub-parsers to define subcommands that have different sets of
switches, as in <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">commit</span></code>, <code class="docutils literal notranslate"><span class="pre">svn</span> <span class="pre">checkout</span></code>, etc.  You can
specify an argument’s type as <a class="reference internal" href="../library/argparse.html#argparse.FileType" title="argparse.FileType"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileType</span></code></a>, which will
automatically open files for you and understands that <code class="docutils literal notranslate"><span class="pre">'-'</span></code> means
standard input or output.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> documentation</dt>
<dd>The documentation page of the argparse module.</dd>
<dt><a class="reference internal" href="../library/argparse.html#argparse-from-optparse"><span class="std std-ref">Upgrading optparse code</span></a></dt>
<dd>Part of the Python documentation, describing how to convert
code that uses <a class="reference internal" href="../library/optparse.html#module-optparse" title="optparse: Command-line option parsing library. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">optparse</span></code></a>.</dd>
<dt><span class="target" id="index-4"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0389"><strong>PEP 389</strong></a> - argparse - New Command Line Parsing Module</dt>
<dd>PEP written and implemented by Steven Bethard.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-391-dictionary-based-configuration-for-logging">
<h2>PEP 391: Dictionary-Based Configuration For Logging<a class="headerlink" href="#pep-391-dictionary-based-configuration-for-logging" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module is very flexible; applications can define
a tree of logging subsystems, and each logger in this tree can filter
out certain messages, format them differently, and direct messages to
a varying number of handlers.</p>
<p>All this flexibility can require a lot of configuration.  You can
write Python statements to create objects and set their properties,
but a complex set-up requires verbose but boring code.
<a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> also supports a <code class="xref py py-func docutils literal notranslate"><span class="pre">fileConfig()</span></code>
function that parses a file, but the file format doesn’t support
configuring filters, and it’s messier to generate programmatically.</p>
<p>Python 2.7 adds a <code class="xref py py-func docutils literal notranslate"><span class="pre">dictConfig()</span></code> function that
uses a dictionary to configure logging.  There are many ways to
produce a dictionary from different sources: construct one with code;
parse a file containing JSON; or use a YAML parsing library if one is
installed.  For more information see <a class="reference internal" href="../library/logging.config.html#logging-config-api"><span class="std std-ref">Configuration functions</span></a>.</p>
<p>The following example configures two loggers, the root logger and a
logger named “network”.  Messages sent to the root logger will be
sent to the system log using the syslog protocol, and messages
to the “network” logger will be written to a <code class="file docutils literal notranslate"><span class="pre">network.log</span></code> file
that will be rotated once the log reaches 1MB.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">logging</span>
<span class="kn">import</span> <span class="nn">logging.config</span>

<span class="n">configdict</span> <span class="o">=</span> <span class="p">{</span>
 <span class="s1">&#39;version&#39;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>    <span class="c1"># Configuration schema in use; must be 1 for now</span>
 <span class="s1">&#39;formatters&#39;</span><span class="p">:</span> <span class="p">{</span>
     <span class="s1">&#39;standard&#39;</span><span class="p">:</span> <span class="p">{</span>
         <span class="s1">&#39;format&#39;</span><span class="p">:</span> <span class="p">(</span><span class="s1">&#39;</span><span class="si">%(asctime)s</span><span class="s1"> </span><span class="si">%(name)-15s</span><span class="s1"> &#39;</span>
                    <span class="s1">&#39;</span><span class="si">%(levelname)-8s</span><span class="s1"> </span><span class="si">%(message)s</span><span class="s1">&#39;</span><span class="p">)}},</span>

 <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;netlog&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;backupCount&#39;</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span>
                     <span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;logging.handlers.RotatingFileHandler&#39;</span><span class="p">,</span>
                     <span class="s1">&#39;filename&#39;</span><span class="p">:</span> <span class="s1">&#39;/logs/network.log&#39;</span><span class="p">,</span>
                     <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;standard&#39;</span><span class="p">,</span>
                     <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;INFO&#39;</span><span class="p">,</span>
                     <span class="s1">&#39;maxBytes&#39;</span><span class="p">:</span> <span class="mi">1000000</span><span class="p">},</span>
              <span class="s1">&#39;syslog&#39;</span><span class="p">:</span> <span class="p">{</span><span class="s1">&#39;class&#39;</span><span class="p">:</span> <span class="s1">&#39;logging.handlers.SysLogHandler&#39;</span><span class="p">,</span>
                         <span class="s1">&#39;formatter&#39;</span><span class="p">:</span> <span class="s1">&#39;standard&#39;</span><span class="p">,</span>
                         <span class="s1">&#39;level&#39;</span><span class="p">:</span> <span class="s1">&#39;ERROR&#39;</span><span class="p">}},</span>

 <span class="c1"># Specify all the subordinate loggers</span>
 <span class="s1">&#39;loggers&#39;</span><span class="p">:</span> <span class="p">{</span>
             <span class="s1">&#39;network&#39;</span><span class="p">:</span> <span class="p">{</span>
                         <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;netlog&#39;</span><span class="p">]</span>
             <span class="p">}</span>
 <span class="p">},</span>
 <span class="c1"># Specify properties of the root logger</span>
 <span class="s1">&#39;root&#39;</span><span class="p">:</span> <span class="p">{</span>
          <span class="s1">&#39;handlers&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s1">&#39;syslog&#39;</span><span class="p">]</span>
 <span class="p">},</span>
<span class="p">}</span>

<span class="c1"># Set up configuration</span>
<span class="n">logging</span><span class="o">.</span><span class="n">config</span><span class="o">.</span><span class="n">dictConfig</span><span class="p">(</span><span class="n">configdict</span><span class="p">)</span>

<span class="c1"># As an example, log two error messages</span>
<span class="n">logger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;/&#39;</span><span class="p">)</span>
<span class="n">logger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Database not found&#39;</span><span class="p">)</span>

<span class="n">netlogger</span> <span class="o">=</span> <span class="n">logging</span><span class="o">.</span><span class="n">getLogger</span><span class="p">(</span><span class="s1">&#39;network&#39;</span><span class="p">)</span>
<span class="n">netlogger</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">&#39;Connection failed&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Three smaller enhancements to the <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module, all
implemented by Vinay Sajip, are:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/logging.handlers.html#logging.handlers.SysLogHandler" title="logging.handlers.SysLogHandler"><code class="xref py py-class docutils literal notranslate"><span class="pre">SysLogHandler</span></code></a> class now supports
syslogging over TCP.  The constructor has a <em>socktype</em> parameter
giving the type of socket to use, either <a class="reference internal" href="../library/socket.html#socket.SOCK_DGRAM" title="socket.SOCK_DGRAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_DGRAM</span></code></a>
for UDP or <a class="reference internal" href="../library/socket.html#socket.SOCK_STREAM" title="socket.SOCK_STREAM"><code class="xref py py-const docutils literal notranslate"><span class="pre">socket.SOCK_STREAM</span></code></a> for TCP.  The default
protocol remains UDP.</li>
<li><a class="reference internal" href="../library/logging.html#logging.Logger" title="logging.Logger"><code class="xref py py-class docutils literal notranslate"><span class="pre">Logger</span></code></a> instances gained a <a class="reference internal" href="../library/logging.html#logging.Logger.getChild" title="logging.Logger.getChild"><code class="xref py py-meth docutils literal notranslate"><span class="pre">getChild()</span></code></a>
method that retrieves a descendant logger using a relative path.
For example, once you retrieve a logger by doing <code class="docutils literal notranslate"><span class="pre">log</span> <span class="pre">=</span> <span class="pre">getLogger('app')</span></code>,
calling <code class="docutils literal notranslate"><span class="pre">log.getChild('network.listen')</span></code> is equivalent to
<code class="docutils literal notranslate"><span class="pre">getLogger('app.network.listen')</span></code>.</li>
<li>The <a class="reference internal" href="../library/logging.html#logging.LoggerAdapter" title="logging.LoggerAdapter"><code class="xref py py-class docutils literal notranslate"><span class="pre">LoggerAdapter</span></code></a> class gained an
<code class="xref py py-meth docutils literal notranslate"><span class="pre">isEnabledFor()</span></code> method that takes a
<em>level</em> and returns whether the underlying logger would
process a message of that level of importance.</li>
</ul>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-5"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0391"><strong>PEP 391</strong></a> - Dictionary-Based Configuration For Logging</dt>
<dd>PEP written and implemented by Vinay Sajip.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3106-dictionary-views">
<h2>PEP 3106: Dictionary Views<a class="headerlink" href="#pep-3106-dictionary-views" title="Permalink to this headline">¶</a></h2>
<p>The dictionary methods <a class="reference internal" href="../library/stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>, and
<a class="reference internal" href="../library/stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a> are different in Python 3.x.  They return an object
called a <em class="dfn">view</em> instead of a fully materialized list.</p>
<p>It’s not possible to change the return values of <a class="reference internal" href="../library/stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>,
<a class="reference internal" href="../library/stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>, and <a class="reference internal" href="../library/stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a> in Python 2.7 because
too much code would break.  Instead the 3.x versions were added
under the new names <a class="reference internal" href="../library/stdtypes.html#dict.viewkeys" title="dict.viewkeys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewkeys()</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#dict.viewvalues" title="dict.viewvalues"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewvalues()</span></code></a>,
and <a class="reference internal" href="../library/stdtypes.html#dict.viewitems" title="dict.viewitems"><code class="xref py py-meth docutils literal notranslate"><span class="pre">viewitems()</span></code></a>.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">i</span><span class="o">*</span><span class="mi">10</span><span class="p">,</span> <span class="nb">chr</span><span class="p">(</span><span class="mi">65</span><span class="o">+</span><span class="n">i</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">26</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span>
<span class="go">{0: &#39;A&#39;, 130: &#39;N&#39;, 10: &#39;B&#39;, 140: &#39;O&#39;, 20: ..., 250: &#39;Z&#39;}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span>
<span class="go">dict_keys([0, 130, 10, 140, 20, 150, 30, ..., 250])</span>
</pre></div>
</div>
<p>Views can be iterated over, but the key and item views also behave
like sets.  The <code class="docutils literal notranslate"><span class="pre">&amp;</span></code> operator performs intersection, and <code class="docutils literal notranslate"><span class="pre">|</span></code>
performs a union:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">d1</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">i</span><span class="o">*</span><span class="mi">10</span><span class="p">,</span> <span class="nb">chr</span><span class="p">(</span><span class="mi">65</span><span class="o">+</span><span class="n">i</span><span class="p">))</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">26</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d2</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">((</span><span class="n">i</span><span class="o">**.</span><span class="mi">5</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1000</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d1</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span> <span class="o">&amp;</span> <span class="n">d2</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span>
<span class="go">set([0.0, 10.0, 20.0, 30.0])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d1</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span> <span class="o">|</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">30</span><span class="p">)</span>
<span class="go">set([0, 1, 130, 3, 4, 5, 6, ..., 120, 250])</span>
</pre></div>
</div>
<p>The view keeps track of the dictionary and its contents change as the
dictionary is modified:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">vk</span> <span class="o">=</span> <span class="n">d</span><span class="o">.</span><span class="n">viewkeys</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vk</span>
<span class="go">dict_keys([0, 130, 10, ..., 250])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">d</span><span class="p">[</span><span class="mi">260</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;&amp;&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">vk</span>
<span class="go">dict_keys([0, 130, 260, 10, ..., 250])</span>
</pre></div>
</div>
<p>However, note that you can’t add or remove keys while you’re iterating
over the view:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">vk</span><span class="p">:</span>
<span class="gp">... </span>    <span class="n">d</span><span class="p">[</span><span class="n">k</span><span class="o">*</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">k</span>
<span class="gp">...</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">RuntimeError</span>: <span class="n">dictionary changed size during iteration</span>
</pre></div>
</div>
<p>You can use the view methods in Python 2.x code, and the 2to3
converter will change them to the standard <a class="reference internal" href="../library/stdtypes.html#dict.keys" title="dict.keys"><code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code></a>,
<a class="reference internal" href="../library/stdtypes.html#dict.values" title="dict.values"><code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code></a>, and <a class="reference internal" href="../library/stdtypes.html#dict.items" title="dict.items"><code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code></a> methods.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-6"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3106"><strong>PEP 3106</strong></a> - Revamping dict.keys(), .values() and .items()</dt>
<dd>PEP written by Guido van Rossum.
Backported to 2.7 by Alexandre Vassalotti; <a class="reference external" href="https://bugs.python.org/issue1967">bpo-1967</a>.</dd>
</dl>
</div>
</div>
<div class="section" id="pep-3137-the-memoryview-object">
<h2>PEP 3137: The memoryview Object<a class="headerlink" href="#pep-3137-the-memoryview-object" title="Permalink to this headline">¶</a></h2>
<p>The <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object provides a view of another object’s
memory content that matches the <code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code> type’s interface.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">string</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">string</span><span class="o">.</span><span class="n">letters</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span>
<span class="go">&lt;memory at 0x37f850&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>           <span class="c1"># Returns length of underlying object</span>
<span class="go">52</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">m</span><span class="p">[</span><span class="mi">25</span><span class="p">],</span> <span class="n">m</span><span class="p">[</span><span class="mi">26</span><span class="p">]</span>   <span class="c1"># Indexing returns one byte</span>
<span class="go">(&#39;a&#39;, &#39;z&#39;, &#39;A&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span> <span class="o">=</span> <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">26</span><span class="p">]</span>         <span class="c1"># Slicing returns another memoryview</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span>
<span class="go">&lt;memory at 0x37f080&gt;</span>
</pre></div>
</div>
<p>The content of the view can be converted to a string of bytes or
a list of integers:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span><span class="o">.</span><span class="n">tobytes</span><span class="p">()</span>
<span class="go">&#39;abcdefghijklmnopqrstuvwxyz&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span><span class="o">.</span><span class="n">tolist</span><span class="p">()</span>
<span class="go">[97, 98, 99, 100, 101, 102, 103, ... 121, 122]</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> objects allow modifying the underlying object if
it’s a mutable object.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">m2</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mi">75</span>
<span class="gt">Traceback (most recent call last):</span>
  File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
<span class="gr">TypeError</span>: <span class="n">cannot modify read-only memory</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span> <span class="o">=</span> <span class="nb">bytearray</span><span class="p">(</span><span class="n">string</span><span class="o">.</span><span class="n">letters</span><span class="p">)</span>  <span class="c1"># Creating a mutable object</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span>
<span class="go">bytearray(b&#39;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mb</span> <span class="o">=</span> <span class="nb">memoryview</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">mb</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;*&#39;</span>         <span class="c1"># Assign to view, changing the bytearray.</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">b</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span>              <span class="c1"># The bytearray has been changed.</span>
<span class="go">bytearray(b&#39;*bcde&#39;)</span>
<span class="go">&gt;&gt;&gt;</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-7"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-3137"><strong>PEP 3137</strong></a> - Immutable Bytes and Mutable Buffer</dt>
<dd>PEP written by Guido van Rossum.
Implemented by Travis Oliphant, Antoine Pitrou and others.
Backported to 2.7 by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue2396">bpo-2396</a>.</dd>
</dl>
</div>
</div>
<div class="section" id="other-language-changes">
<h2>Other Language Changes<a class="headerlink" href="#other-language-changes" title="Permalink to this headline">¶</a></h2>
<p>Some smaller changes made to the core Python language are:</p>
<ul>
<li><p class="first">The syntax for set literals has been backported from Python 3.x.
Curly brackets are used to surround the contents of the resulting
mutable set; set literals are
distinguished from dictionaries by not containing colons and values.
<code class="docutils literal notranslate"><span class="pre">{}</span></code> continues to represent an empty dictionary; use
<code class="docutils literal notranslate"><span class="pre">set()</span></code> for an empty set.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">}</span>
<span class="go">set([1, 2, 3, 4, 5])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">set</span><span class="p">()</span> <span class="c1"># empty set</span>
<span class="go">set([])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">{}</span>    <span class="c1"># empty dict</span>
<span class="go">{}</span>
</pre></div>
</div>
<p>Backported by Alexandre Vassalotti; <a class="reference external" href="https://bugs.python.org/issue2335">bpo-2335</a>.</p>
</li>
<li><p class="first">Dictionary and set comprehensions are another feature backported from
3.x, generalizing list/generator comprehensions to use
the literal syntax for sets and dictionaries.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="p">{</span><span class="n">x</span><span class="p">:</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)}</span>
<span class="go">{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">{(</span><span class="s1">&#39;a&#39;</span><span class="o">*</span><span class="n">x</span><span class="p">)</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">6</span><span class="p">)}</span>
<span class="go">set([&#39;&#39;, &#39;a&#39;, &#39;aa&#39;, &#39;aaa&#39;, &#39;aaaa&#39;, &#39;aaaaa&#39;])</span>
</pre></div>
</div>
<p>Backported by Alexandre Vassalotti; <a class="reference external" href="https://bugs.python.org/issue2333">bpo-2333</a>.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement can now use multiple context managers
in one statement.  Context managers are processed from left to right
and each one is treated as beginning a new <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.
This means that:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">,</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
    <span class="o">...</span> <span class="n">suite</span> <span class="n">of</span> <span class="n">statements</span> <span class="o">...</span>
</pre></div>
</div>
<p>is equivalent to:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">A</span><span class="p">()</span> <span class="k">as</span> <span class="n">a</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">B</span><span class="p">()</span> <span class="k">as</span> <span class="n">b</span><span class="p">:</span>
        <span class="o">...</span> <span class="n">suite</span> <span class="n">of</span> <span class="n">statements</span> <span class="o">...</span>
</pre></div>
</div>
<p>The <a class="reference internal" href="../library/contextlib.html#contextlib.nested" title="contextlib.nested"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextlib.nested()</span></code></a> function provides a very similar
function, so it’s no longer necessary and has been deprecated.</p>
<p>(Proposed in <a class="reference external" href="https://codereview.appspot.com/53094">https://codereview.appspot.com/53094</a>; implemented by
Georg Brandl.)</p>
</li>
<li><p class="first">Conversions between floating-point numbers and strings are
now correctly rounded on most platforms.  These conversions occur
in many different places: <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> on
floats and complex numbers; the <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a> and <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>
constructors;
numeric formatting; serializing and
deserializing floats and complex numbers using the
<a class="reference internal" href="../library/marshal.html#module-marshal" title="marshal: Convert Python objects to streams of bytes and back (with different constraints)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">marshal</span></code></a>, <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a>
and <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> modules;
parsing of float and imaginary literals in Python code;
and <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>-to-float conversion.</p>
<p>Related to this, the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> of a floating-point number <em>x</em>
now returns a result based on the shortest decimal string that’s
guaranteed to round back to <em>x</em> under correct rounding (with
round-half-to-even rounding mode).  Previously it gave a string
based on rounding x to 17 decimal digits.</p>
<p>The rounding library responsible for this improvement works on
Windows and on Unix platforms using the gcc, icc, or suncc
compilers.  There may be a small number of platforms where correct
operation of this code cannot be guaranteed, so the code is not
used on such systems.  You can find out which code is being used
by checking <a class="reference internal" href="../library/sys.html#sys.float_repr_style" title="sys.float_repr_style"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.float_repr_style</span></code></a>,  which will be <code class="docutils literal notranslate"><span class="pre">short</span></code>
if the new code is in use and <code class="docutils literal notranslate"><span class="pre">legacy</span></code> if it isn’t.</p>
<p>Implemented by Eric Smith and Mark Dickinson, using David Gay’s
<code class="file docutils literal notranslate"><span class="pre">dtoa.c</span></code> library; <a class="reference external" href="https://bugs.python.org/issue7117">bpo-7117</a>.</p>
</li>
<li><p class="first">Conversions from long integers and regular integers to floating
point now round differently, returning the floating-point number
closest to the number.  This doesn’t matter for small integers that
can be converted exactly, but for large numbers that will
unavoidably lose precision, Python 2.7 now approximates more
closely.  For example, Python 2.6 computed the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">295147905179352891391</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">2.9514790517935283e+20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">-</span> <span class="n">long</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>
<span class="go">65535L</span>
</pre></div>
</div>
<p>Python 2.7’s floating-point result is larger, but much closer to the
true value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">295147905179352891391</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">2.9514790517935289e+20</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">-</span> <span class="n">long</span><span class="p">(</span><span class="nb">float</span><span class="p">(</span><span class="n">n</span><span class="p">))</span>
<span class="go">-1L</span>
</pre></div>
</div>
<p>(Implemented by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue3166">bpo-3166</a>.)</p>
<p>Integer division is also more accurate in its rounding behaviours.  (Also
implemented by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue1811">bpo-1811</a>.)</p>
</li>
<li><p class="first">Implicit coercion for complex numbers has been removed; the interpreter
will no longer ever attempt to call a <a class="reference internal" href="../reference/datamodel.html#object.__coerce__" title="object.__coerce__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__coerce__()</span></code></a> method on complex
objects.  (Removed by Meador Inge and Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue5211">bpo-5211</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method now supports automatic numbering of the replacement
fields.  This makes using <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> more closely resemble using
<code class="docutils literal notranslate"><span class="pre">%s</span></code> formatting:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{}</span><span class="s1">:</span><span class="si">{}</span><span class="s1">:</span><span class="si">{}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">04</span><span class="p">,</span> <span class="s1">&#39;Sunday&#39;</span><span class="p">)</span>
<span class="go">&#39;2009:4:Sunday&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="s1">&#39;</span><span class="si">{}</span><span class="s1">:</span><span class="si">{}</span><span class="s1">:</span><span class="si">{day}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="n">day</span><span class="o">=</span><span class="s1">&#39;Sunday&#39;</span><span class="p">)</span>
<span class="go">&#39;2009:4:Sunday&#39;</span>
</pre></div>
</div>
<p>The auto-numbering takes the fields from left to right, so the first <code class="docutils literal notranslate"><span class="pre">{...}</span></code>
specifier will use the first argument to <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, the next
specifier will use the next argument, and so on.  You can’t mix auto-numbering
and explicit numbering – either number all of your specifier fields or none
of them – but you can mix auto-numbering and named fields, as in the second
example above.  (Contributed by Eric Smith; <a class="reference external" href="https://bugs.python.org/issue5237">bpo-5237</a>.)</p>
<p>Complex numbers now correctly support usage with <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a>,
and default to being right-aligned.
Specifying a precision or comma-separation applies to both the real
and imaginary parts of the number, but a specified field width and
alignment is applied to the whole of the resulting <code class="docutils literal notranslate"><span class="pre">1.5+3j</span></code>
output.  (Contributed by Eric Smith; <a class="reference external" href="https://bugs.python.org/issue1588">bpo-1588</a> and <a class="reference external" href="https://bugs.python.org/issue7988">bpo-7988</a>.)</p>
<p>The ‘F’ format code now always formats its output using uppercase characters,
so it will now produce ‘INF’ and ‘NAN’.
(Contributed by Eric Smith; <a class="reference external" href="https://bugs.python.org/issue3382">bpo-3382</a>.)</p>
<p>A low-level change: the <code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__format__()</span></code> method now triggers
a <a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a> if it’s passed a format string,
because the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code> method for <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> converts
the object to a string representation and formats that.  Previously
the method silently applied the format string to the string
representation, but that could hide mistakes in Python code.  If
you’re supplying formatting information such as an alignment or
precision, presumably you’re expecting the formatting to be applied
in some object-specific way.  (Fixed by Eric Smith; <a class="reference external" href="https://bugs.python.org/issue7994">bpo-7994</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a> and <a class="reference internal" href="../library/functions.html#long" title="long"><code class="xref py py-func docutils literal notranslate"><span class="pre">long()</span></code></a> types gained a <code class="docutils literal notranslate"><span class="pre">bit_length</span></code>
method that returns the number of bits necessary to represent
its argument in binary:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">37</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">bin</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="go">&#39;0b100101&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">6</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span> <span class="o">=</span> <span class="mi">2</span><span class="o">**</span><span class="mi">123</span><span class="o">-</span><span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">n</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">123</span>
<span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="n">n</span><span class="o">+</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="n">bit_length</span><span class="p">()</span>
<span class="go">124</span>
</pre></div>
</div>
<p>(Contributed by Fredrik Johansson and Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue3439">bpo-3439</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement will no longer try an absolute import
if a relative import (e.g. <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">.os</span> <span class="pre">import</span> <span class="pre">sep</span></code>) fails.  This
fixes a bug, but could possibly break certain <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a>
statements that were only working by accident.  (Fixed by Meador Inge;
<a class="reference external" href="https://bugs.python.org/issue7902">bpo-7902</a>.)</p>
</li>
<li><p class="first">It’s now possible for a subclass of the built-in <a class="reference internal" href="../library/functions.html#unicode" title="unicode"><code class="xref py py-class docutils literal notranslate"><span class="pre">unicode</span></code></a> type
to override the <a class="reference internal" href="../reference/datamodel.html#object.__unicode__" title="object.__unicode__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__unicode__()</span></code></a> method.  (Implemented by
Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue1583863">bpo-1583863</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> type’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">translate()</span></code> method now accepts
<code class="docutils literal notranslate"><span class="pre">None</span></code> as its first argument.  (Fixed by Georg Brandl;
<a class="reference external" href="https://bugs.python.org/issue4759">bpo-4759</a>.)</p>
</li>
<li><p class="first">When using <code class="docutils literal notranslate"><span class="pre">&#64;classmethod</span></code> and <code class="docutils literal notranslate"><span class="pre">&#64;staticmethod</span></code> to wrap
methods as class or static methods, the wrapper object now
exposes the wrapped function as their <code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code> attribute.
(Contributed by Amaury Forgeot d’Arc, after a suggestion by
George Sakkis; <a class="reference external" href="https://bugs.python.org/issue5982">bpo-5982</a>.)</p>
</li>
<li><p class="first">When a restricted set of attributes were set using <code class="docutils literal notranslate"><span class="pre">__slots__</span></code>,
deleting an unset attribute would not raise <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>
as you would expect.  Fixed by Benjamin Peterson; <a class="reference external" href="https://bugs.python.org/issue7604">bpo-7604</a>.)</p>
</li>
<li><p class="first">Two new encodings are now supported: “cp720”, used primarily for
Arabic text; and “cp858”, a variant of CP 850 that adds the euro
symbol.  (CP720 contributed by Alexander Belchenko and Amaury
Forgeot d’Arc in <a class="reference external" href="https://bugs.python.org/issue1616979">bpo-1616979</a>; CP858 contributed by Tim Hatch in
<a class="reference external" href="https://bugs.python.org/issue8016">bpo-8016</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/functions.html#file" title="file"><code class="xref py py-class docutils literal notranslate"><span class="pre">file</span></code></a> object will now set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">filename</span></code> attribute
on the <a class="reference internal" href="../library/exceptions.html#exceptions.IOError" title="exceptions.IOError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IOError</span></code></a> exception when trying to open a directory
on POSIX platforms (noted by Jan Kaliszewski; <a class="reference external" href="https://bugs.python.org/issue4764">bpo-4764</a>), and
now explicitly checks for and forbids writing to read-only file objects
instead of trusting the C library to catch and report the error
(fixed by Stefan Krah; <a class="reference external" href="https://bugs.python.org/issue5677">bpo-5677</a>).</p>
</li>
<li><p class="first">The Python tokenizer now translates line endings itself, so the
<a class="reference internal" href="../library/functions.html#compile" title="compile"><code class="xref py py-func docutils literal notranslate"><span class="pre">compile()</span></code></a> built-in function now accepts code using any
line-ending convention.  Additionally, it no longer requires that the
code end in a newline.</p>
</li>
<li><p class="first">Extra parentheses in function definitions are illegal in Python 3.x,
meaning that you get a syntax error from <code class="docutils literal notranslate"><span class="pre">def</span> <span class="pre">f((x)):</span> <span class="pre">pass</span></code>.  In
Python3-warning mode, Python 2.7 will now warn about this odd usage.
(Noted by James Lingard; <a class="reference external" href="https://bugs.python.org/issue7362">bpo-7362</a>.)</p>
</li>
<li><p class="first">It’s now possible to create weak references to old-style class
objects.  New-style classes were always weak-referenceable.  (Fixed
by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue8268">bpo-8268</a>.)</p>
</li>
<li><p class="first">When a module object is garbage-collected, the module’s dictionary is
now only cleared if no one else is holding a reference to the
dictionary (<a class="reference external" href="https://bugs.python.org/issue7140">bpo-7140</a>).</p>
</li>
</ul>
<div class="section" id="interpreter-changes">
<span id="new-27-interpreter"></span><h3>Interpreter Changes<a class="headerlink" href="#interpreter-changes" title="Permalink to this headline">¶</a></h3>
<p>A new environment variable, <span class="target" id="index-8"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONWARNINGS"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONWARNINGS</span></code></a>,
allows controlling warnings.  It should be set to a string
containing warning settings, equivalent to those
used with the <a class="reference internal" href="../using/cmdline.html#cmdoption-w"><code class="xref std std-option docutils literal notranslate"><span class="pre">-W</span></code></a> switch, separated by commas.
(Contributed by Brian Curtin; <a class="reference external" href="https://bugs.python.org/issue7301">bpo-7301</a>.)</p>
<p>For example, the following setting will print warnings every time
they occur, but turn warnings from the <a class="reference internal" href="../library/cookie.html#module-Cookie" title="Cookie: Support for HTTP state management (cookies)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">Cookie</span></code></a> module into an
error.  (The exact syntax for setting an environment variable varies
across operating systems and shells.)</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">export</span> <span class="n">PYTHONWARNINGS</span><span class="o">=</span><span class="nb">all</span><span class="p">,</span><span class="n">error</span><span class="p">:::</span><span class="n">Cookie</span><span class="p">:</span><span class="mi">0</span>
</pre></div>
</div>
</div>
<div class="section" id="optimizations">
<h3>Optimizations<a class="headerlink" href="#optimizations" title="Permalink to this headline">¶</a></h3>
<p>Several performance enhancements have been added:</p>
<ul>
<li><p class="first">A new opcode was added to perform the initial setup for
<a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statements, looking up the <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods.  (Contributed by Benjamin Peterson.)</p>
</li>
<li><p class="first">The garbage collector now performs better for one common usage
pattern: when many objects are being allocated without deallocating
any of them.  This would previously take quadratic
time for garbage collection, but now the number of full garbage collections
is reduced as the number of objects on the heap grows.
The new logic only performs a full garbage collection pass when
the middle generation has been collected 10 times and when the
number of survivor objects from the middle generation exceeds 10% of
the number of objects in the oldest generation.  (Suggested by Martin
von Löwis and implemented by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue4074">bpo-4074</a>.)</p>
</li>
<li><p class="first">The garbage collector tries to avoid tracking simple containers
which can’t be part of a cycle. In Python 2.7, this is now true for
tuples and dicts containing atomic types (such as ints, strings,
etc.). Transitively, a dict containing tuples of atomic types won’t
be tracked either. This helps reduce the cost of each
garbage collection by decreasing the number of objects to be
considered and traversed by the collector.
(Contributed by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue4688">bpo-4688</a>.)</p>
</li>
<li><p class="first">Long integers are now stored internally either in base 2**15 or in base
2**30, the base being determined at build time.  Previously, they
were always stored in base 2**15.  Using base 2**30 gives
significant performance improvements on 64-bit machines, but
benchmark results on 32-bit machines have been mixed.  Therefore,
the default is to use base 2**30 on 64-bit machines and base 2**15
on 32-bit machines; on Unix, there’s a new configure option
<code class="xref std std-option docutils literal notranslate"><span class="pre">--enable-big-digits</span></code> that can be used to override this default.</p>
<p>Apart from the performance improvements this change should be
invisible to end users, with one exception: for testing and
debugging purposes there’s a new structseq <a class="reference internal" href="../library/sys.html#sys.long_info" title="sys.long_info"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.long_info</span></code></a> that
provides information about the internal format, giving the number of
bits per digit and the size in bytes of the C type used to store
each digit:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">long_info</span>
<span class="go">sys.long_info(bits_per_digit=30, sizeof_digit=4)</span>
</pre></div>
</div>
<p>(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue4258">bpo-4258</a>.)</p>
<p>Another set of changes made long objects a few bytes smaller: 2 bytes
smaller on 32-bit systems and 6 bytes on 64-bit.
(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue5260">bpo-5260</a>.)</p>
</li>
<li><p class="first">The division algorithm for long integers has been made faster
by tightening the inner loop, doing shifts instead of multiplications,
and fixing an unnecessary extra iteration.
Various benchmarks show speedups of between 50% and 150% for long
integer divisions and modulo operations.
(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue5512">bpo-5512</a>.)
Bitwise operations are also significantly faster (initial patch by
Gregory Smith; <a class="reference external" href="https://bugs.python.org/issue1087418">bpo-1087418</a>).</p>
</li>
<li><p class="first">The implementation of <code class="docutils literal notranslate"><span class="pre">%</span></code> checks for the left-side operand being
a Python string and special-cases it; this results in a 1–3%
performance increase for applications that frequently use <code class="docutils literal notranslate"><span class="pre">%</span></code>
with strings, such as templating libraries.
(Implemented by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue5176">bpo-5176</a>.)</p>
</li>
<li><p class="first">List comprehensions with an <code class="docutils literal notranslate"><span class="pre">if</span></code> condition are compiled into
faster bytecode.  (Patch by Antoine Pitrou, back-ported to 2.7
by Jeffrey Yasskin; <a class="reference external" href="https://bugs.python.org/issue4715">bpo-4715</a>.)</p>
</li>
<li><p class="first">Converting an integer or long integer to a decimal string was made
faster by special-casing base 10 instead of using a generalized
conversion function that supports arbitrary bases.
(Patch by Gawain Bolton; <a class="reference external" href="https://bugs.python.org/issue6713">bpo-6713</a>.)</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">split()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">replace()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">rindex()</span></code>,
<code class="xref py py-meth docutils literal notranslate"><span class="pre">rpartition()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">rsplit()</span></code> methods of string-like types
(strings, Unicode strings, and <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> objects) now use a
fast reverse-search algorithm instead of a character-by-character
scan.  This is sometimes faster by a factor of 10.  (Added by
Florent Xicluna; <a class="reference external" href="https://bugs.python.org/issue7462">bpo-7462</a> and <a class="reference external" href="https://bugs.python.org/issue7622">bpo-7622</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> and <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> modules now automatically
intern the strings used for attribute names, reducing memory usage
of the objects resulting from unpickling.  (Contributed by Jake
McGuire; <a class="reference external" href="https://bugs.python.org/issue5084">bpo-5084</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pickle.html#module-cPickle" title="cPickle: Faster version of pickle, but not subclassable."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cPickle</span></code></a> module now special-cases dictionaries,
nearly halving the time required to pickle them.
(Contributed by Collin Winter; <a class="reference external" href="https://bugs.python.org/issue5670">bpo-5670</a>.)</p>
</li>
</ul>
</div>
</div>
<div class="section" id="new-and-improved-modules">
<h2>New and Improved Modules<a class="headerlink" href="#new-and-improved-modules" title="Permalink to this headline">¶</a></h2>
<p>As in every release, Python’s standard library received a number of
enhancements and bug fixes.  Here’s a partial list of the most notable
changes, sorted alphabetically by module name. Consult the
<code class="file docutils literal notranslate"><span class="pre">Misc/NEWS</span></code> file in the source tree for a more complete list of
changes, or look through the Subversion logs for all the details.</p>
<ul>
<li><p class="first">The <a class="reference internal" href="../library/bdb.html#module-bdb" title="bdb: Debugger framework."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bdb</span></code></a> module’s base debugging class <a class="reference internal" href="../library/bdb.html#bdb.Bdb" title="bdb.Bdb"><code class="xref py py-class docutils literal notranslate"><span class="pre">Bdb</span></code></a>
gained a feature for skipping modules.  The constructor
now takes an iterable containing glob-style patterns such as
<code class="docutils literal notranslate"><span class="pre">django.*</span></code>; the debugger will not step into stack frames
from a module that matches one of these patterns.
(Contributed by Maru Newby after a suggestion by
Senthil Kumaran; <a class="reference external" href="https://bugs.python.org/issue5142">bpo-5142</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/binascii.html#module-binascii" title="binascii: Tools for converting between binary and various ASCII-encoded binary representations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">binascii</span></code></a> module now supports the buffer API, so it can be
used with <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> instances and other similar buffer objects.
(Backported from 3.x by Florent Xicluna; <a class="reference external" href="https://bugs.python.org/issue7703">bpo-7703</a>.)</p>
</li>
<li><p class="first">Updated module: the <a class="reference internal" href="../library/bsddb.html#module-bsddb" title="bsddb: Interface to Berkeley DB database library"><code class="xref py py-mod docutils literal notranslate"><span class="pre">bsddb</span></code></a> module has been updated from 4.7.2devel9
to version 4.8.4 of
<a class="reference external" href="https://www.jcea.es/programacion/pybsddb.htm">the pybsddb package</a>.
The new version features better Python 3.x compatibility, various bug fixes,
and adds several new BerkeleyDB flags and methods.
(Updated by Jesús Cea Avión; <a class="reference external" href="https://bugs.python.org/issue8156">bpo-8156</a>.  The pybsddb
changelog can be read at <a class="reference external" href="http://hg.jcea.es/pybsddb/file/tip/ChangeLog">http://hg.jcea.es/pybsddb/file/tip/ChangeLog</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interface to compression and decompression routines compatible with bzip2."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a> module’s <a class="reference internal" href="../library/bz2.html#bz2.BZ2File" title="bz2.BZ2File"><code class="xref py py-class docutils literal notranslate"><span class="pre">BZ2File</span></code></a> now supports the context
management protocol, so you can write <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">bz2.BZ2File(...)</span> <span class="pre">as</span> <span class="pre">f:</span></code>.
(Contributed by Hagen Fürstenau; <a class="reference external" href="https://bugs.python.org/issue3860">bpo-3860</a>.)</p>
</li>
<li><p class="first">New class: the <a class="reference internal" href="../library/collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> class in the <a class="reference internal" href="../library/collections.html#module-collections" title="collections: High-performance datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a>
module is useful for tallying data.  <a class="reference internal" href="../library/collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> instances
behave mostly like dictionaries but return zero for missing keys instead of
raising a <a class="reference internal" href="../library/exceptions.html#exceptions.KeyError" title="exceptions.KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a>:</p>
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">Counter</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">Counter</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">letter</span> <span class="ow">in</span> <span class="s1">&#39;here is a sample of english text&#39;</span><span class="p">:</span>
<span class="gp">... </span>  <span class="n">c</span><span class="p">[</span><span class="n">letter</span><span class="p">]</span> <span class="o">+=</span> <span class="mi">1</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span>
<span class="go">Counter({&#39; &#39;: 6, &#39;e&#39;: 5, &#39;s&#39;: 3, &#39;a&#39;: 2, &#39;i&#39;: 2, &#39;h&#39;: 2,</span>
<span class="go">&#39;l&#39;: 2, &#39;t&#39;: 2, &#39;g&#39;: 1, &#39;f&#39;: 1, &#39;m&#39;: 1, &#39;o&#39;: 1, &#39;n&#39;: 1,</span>
<span class="go">&#39;p&#39;: 1, &#39;r&#39;: 1, &#39;x&#39;: 1})</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;e&#39;</span><span class="p">]</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;z&#39;</span><span class="p">]</span>
<span class="go">0</span>
</pre></div>
</div>
<p>There are three additional <a class="reference internal" href="../library/collections.html#collections.Counter" title="collections.Counter"><code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code></a> methods.
<a class="reference internal" href="../library/collections.html#collections.Counter.most_common" title="collections.Counter.most_common"><code class="xref py py-meth docutils literal notranslate"><span class="pre">most_common()</span></code></a> returns the N most common
elements and their counts.  <a class="reference internal" href="../library/collections.html#collections.Counter.elements" title="collections.Counter.elements"><code class="xref py py-meth docutils literal notranslate"><span class="pre">elements()</span></code></a>
returns an iterator over the contained elements, repeating each
element as many times as its count.
<a class="reference internal" href="../library/collections.html#collections.Counter.subtract" title="collections.Counter.subtract"><code class="xref py py-meth docutils literal notranslate"><span class="pre">subtract()</span></code></a> takes an iterable and
subtracts one for each element instead of adding; if the argument is
a dictionary or another <code class="xref py py-class docutils literal notranslate"><span class="pre">Counter</span></code>, the counts are
subtracted.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">most_common</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
<span class="go">[(&#39; &#39;, 6), (&#39;e&#39;, 5), (&#39;s&#39;, 3), (&#39;a&#39;, 2), (&#39;i&#39;, 2)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">elements</span><span class="p">()</span> <span class="o">-&gt;</span>
<span class="go">   &#39;a&#39;, &#39;a&#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;, &#39; &#39;,</span>
<span class="go">   &#39;e&#39;, &#39;e&#39;, &#39;e&#39;, &#39;e&#39;, &#39;e&#39;, &#39;g&#39;, &#39;f&#39;, &#39;i&#39;, &#39;i&#39;,</span>
<span class="go">   &#39;h&#39;, &#39;h&#39;, &#39;m&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;, &#39;n&#39;, &#39;p&#39;, &#39;s&#39;,</span>
<span class="go">   &#39;s&#39;, &#39;s&#39;, &#39;r&#39;, &#39;t&#39;, &#39;t&#39;, &#39;x&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;e&#39;</span><span class="p">]</span>
<span class="go">5</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="n">subtract</span><span class="p">(</span><span class="s1">&#39;very heavy on the letter e&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="p">[</span><span class="s1">&#39;e&#39;</span><span class="p">]</span>    <span class="c1"># Count is now lower</span>
<span class="go">-1</span>
</pre></div>
</div>
<p>Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue1696199">bpo-1696199</a>.</p>
<p>New class: <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrderedDict</span></code></a> is described in the earlier
section <a class="reference internal" href="#pep-0372"><span class="std std-ref">PEP 372: Adding an Ordered Dictionary to collections</span></a>.</p>
<p>New method: The <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> data type now has a
<a class="reference internal" href="../library/collections.html#collections.deque.count" title="collections.deque.count"><code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code></a> method that returns the number of
contained elements equal to the supplied argument <em>x</em>, and a
<a class="reference internal" href="../library/collections.html#collections.deque.reverse" title="collections.deque.reverse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code></a> method that reverses the elements
of the deque in-place.  <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> also exposes its maximum
length as the read-only <a class="reference internal" href="../library/collections.html#collections.deque.maxlen" title="collections.deque.maxlen"><code class="xref py py-attr docutils literal notranslate"><span class="pre">maxlen</span></code></a> attribute.
(Both features added by Raymond Hettinger.)</p>
<p>The <a class="reference internal" href="../library/collections.html#collections.namedtuple" title="collections.namedtuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">namedtuple</span></code></a> class now has an optional <em>rename</em> parameter.
If <em>rename</em> is true, field names that are invalid because they’ve
been repeated or aren’t legal Python identifiers will be
renamed to legal names that are derived from the field’s
position within the list of fields:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">collections</span> <span class="k">import</span> <span class="n">namedtuple</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">T</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">&#39;T&#39;</span><span class="p">,</span> <span class="p">[</span><span class="s1">&#39;field1&#39;</span><span class="p">,</span> <span class="s1">&#39;$illegal&#39;</span><span class="p">,</span> <span class="s1">&#39;for&#39;</span><span class="p">,</span> <span class="s1">&#39;field2&#39;</span><span class="p">],</span> <span class="n">rename</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">T</span><span class="o">.</span><span class="n">_fields</span>
<span class="go">(&#39;field1&#39;, &#39;_1&#39;, &#39;_2&#39;, &#39;field2&#39;)</span>
</pre></div>
</div>
<p>(Added by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue1818">bpo-1818</a>.)</p>
<p>Finally, the <a class="reference internal" href="../library/collections.html#collections.Mapping" title="collections.Mapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code></a> abstract base class now
returns <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-const docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if a mapping is compared to
another type that isn’t a <code class="xref py py-class docutils literal notranslate"><span class="pre">Mapping</span></code>.
(Fixed by Daniel Stutzbach; <a class="reference external" href="https://bugs.python.org/issue8729">bpo-8729</a>.)</p>
</li>
<li><p class="first">Constructors for the parsing classes in the <a class="reference internal" href="../library/configparser.html#module-ConfigParser" title="ConfigParser: Configuration file parser."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ConfigParser</span></code></a> module now
take an <em>allow_no_value</em> parameter, defaulting to false; if true,
options without values will be allowed.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">ConfigParser</span><span class="o">,</span> <span class="nn">StringIO</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">sample_config</span> <span class="o">=</span> <span class="s2">&quot;&quot;&quot;</span>
<span class="gp">... </span><span class="s2">[mysqld]</span>
<span class="gp">... </span><span class="s2">user = mysql</span>
<span class="gp">... </span><span class="s2">pid-file = /var/run/mysqld/mysqld.pid</span>
<span class="gp">... </span><span class="s2">skip-bdb</span>
<span class="gp">... </span><span class="s2">&quot;&quot;&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span> <span class="o">=</span> <span class="n">ConfigParser</span><span class="o">.</span><span class="n">RawConfigParser</span><span class="p">(</span><span class="n">allow_no_value</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">readfp</span><span class="p">(</span><span class="n">StringIO</span><span class="o">.</span><span class="n">StringIO</span><span class="p">(</span><span class="n">sample_config</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;mysqld&#39;</span><span class="p">,</span> <span class="s1">&#39;user&#39;</span><span class="p">)</span>
<span class="go">&#39;mysql&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;mysqld&#39;</span><span class="p">,</span> <span class="s1">&#39;skip-bdb&#39;</span><span class="p">)</span>
<span class="go">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span> <span class="n">config</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;mysqld&#39;</span><span class="p">,</span> <span class="s1">&#39;unknown&#39;</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
  <span class="c">...</span>
<span class="gr">NoOptionError</span>: <span class="n">No option &#39;unknown&#39; in section: &#39;mysqld&#39;</span>
</pre></div>
</div>
<p>(Contributed by Mats Kindahl; <a class="reference external" href="https://bugs.python.org/issue7005">bpo-7005</a>.)</p>
</li>
<li><p class="first">Deprecated function: <a class="reference internal" href="../library/contextlib.html#contextlib.nested" title="contextlib.nested"><code class="xref py py-func docutils literal notranslate"><span class="pre">contextlib.nested()</span></code></a>, which allows
handling more than one context manager with a single <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a>
statement, has been deprecated, because the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
now supports multiple context managers.</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/cookielib.html#module-cookielib" title="cookielib: Classes for automatic handling of HTTP cookies."><code class="xref py py-mod docutils literal notranslate"><span class="pre">cookielib</span></code></a> module now ignores cookies that have an invalid
version field, one that doesn’t contain an integer value.  (Fixed by
John J. Lee; <a class="reference external" href="https://bugs.python.org/issue3924">bpo-3924</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/copy.html#module-copy" title="copy: Shallow and deep copy operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">copy</span></code></a> module’s <a class="reference internal" href="../library/copy.html#copy.deepcopy" title="copy.deepcopy"><code class="xref py py-func docutils literal notranslate"><span class="pre">deepcopy()</span></code></a> function will now
correctly copy bound instance methods.  (Implemented by
Robert Collins; <a class="reference external" href="https://bugs.python.org/issue1515">bpo-1515</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module now always converts <code class="docutils literal notranslate"><span class="pre">None</span></code> to a C NULL
pointer for arguments declared as pointers.  (Changed by Thomas
Heller; <a class="reference external" href="https://bugs.python.org/issue4606">bpo-4606</a>.)  The underlying <a class="reference external" href="https://sourceware.org/libffi/">libffi library</a> has been updated to version
3.0.9, containing various fixes for different platforms.  (Updated
by Matthias Klose; <a class="reference external" href="https://bugs.python.org/issue8142">bpo-8142</a>.)</p>
</li>
<li><p class="first">New method: the <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module’s <a class="reference internal" href="../library/datetime.html#datetime.timedelta" title="datetime.timedelta"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a> class
gained a <a class="reference internal" href="../library/datetime.html#datetime.timedelta.total_seconds" title="datetime.timedelta.total_seconds"><code class="xref py py-meth docutils literal notranslate"><span class="pre">total_seconds()</span></code></a> method that returns the
number of seconds in the duration.  (Contributed by Brian Quinlan; <a class="reference external" href="https://bugs.python.org/issue5788">bpo-5788</a>.)</p>
</li>
<li><p class="first">New method: the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class gained a
<a class="reference internal" href="../library/decimal.html#decimal.Decimal.from_float" title="decimal.Decimal.from_float"><code class="xref py py-meth docutils literal notranslate"><span class="pre">from_float()</span></code></a> class method that performs an exact
conversion of a floating-point number to a <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>.
This exact conversion strives for the
closest decimal approximation to the floating-point representation’s value;
the resulting decimal value will therefore still include the inaccuracy,
if any.
For example, <code class="docutils literal notranslate"><span class="pre">Decimal.from_float(0.1)</span></code> returns
<code class="docutils literal notranslate"><span class="pre">Decimal('0.1000000000000000055511151231257827021181583404541015625')</span></code>.
(Implemented by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue4796">bpo-4796</a>.)</p>
<p>Comparing instances of <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> with floating-point
numbers now produces sensible results based on the numeric values
of the operands.  Previously such comparisons would fall back to
Python’s default rules for comparing objects, which produced arbitrary
results based on their type.  Note that you still cannot combine
<code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code> and floating-point in other operations such as addition,
since you should be explicitly choosing how to convert between float and
<a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>.  (Fixed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue2531">bpo-2531</a>.)</p>
<p>The constructor for <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> now accepts
floating-point numbers (added by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue8257">bpo-8257</a>)
and non-European Unicode characters such as Arabic-Indic digits
(contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue6595">bpo-6595</a>).</p>
<p>Most of the methods of the <a class="reference internal" href="../library/decimal.html#decimal.Context" title="decimal.Context"><code class="xref py py-class docutils literal notranslate"><span class="pre">Context</span></code></a> class now accept integers
as well as <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances; the only exceptions are the
<a class="reference internal" href="../library/decimal.html#decimal.Context.canonical" title="decimal.Context.canonical"><code class="xref py py-meth docutils literal notranslate"><span class="pre">canonical()</span></code></a> and <a class="reference internal" href="../library/decimal.html#decimal.Context.is_canonical" title="decimal.Context.is_canonical"><code class="xref py py-meth docutils literal notranslate"><span class="pre">is_canonical()</span></code></a>
methods.  (Patch by Juan José Conti; <a class="reference external" href="https://bugs.python.org/issue7633">bpo-7633</a>.)</p>
<p>When using <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances with a string’s
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> method, the default alignment was previously
left-alignment.  This has been changed to right-alignment, which is
more sensible for numeric types.  (Changed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue6857">bpo-6857</a>.)</p>
<p>Comparisons involving a signaling NaN value (or <code class="docutils literal notranslate"><span class="pre">sNAN</span></code>) now signal
<code class="xref py py-const docutils literal notranslate"><span class="pre">InvalidOperation</span></code> instead of silently returning a true or
false value depending on the comparison operator.  Quiet NaN values
(or <code class="docutils literal notranslate"><span class="pre">NaN</span></code>) are now hashable.  (Fixed by Mark Dickinson;
<a class="reference external" href="https://bugs.python.org/issue7279">bpo-7279</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/difflib.html#module-difflib" title="difflib: Helpers for computing differences between objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">difflib</span></code></a> module now produces output that is more
compatible with modern <strong class="command">diff</strong>/<strong class="command">patch</strong> tools
through one small change, using a tab character instead of spaces as
a separator in the header giving the filename.  (Fixed by Anatoly
Techtonik; <a class="reference external" href="https://bugs.python.org/issue7585">bpo-7585</a>.)</p>
</li>
<li><p class="first">The Distutils <code class="docutils literal notranslate"><span class="pre">sdist</span></code> command now always regenerates the
<code class="file docutils literal notranslate"><span class="pre">MANIFEST</span></code> file, since even if the <code class="file docutils literal notranslate"><span class="pre">MANIFEST.in</span></code> or
<code class="file docutils literal notranslate"><span class="pre">setup.py</span></code> files haven’t been modified, the user might have
created some new files that should be included.
(Fixed by Tarek Ziadé; <a class="reference external" href="https://bugs.python.org/issue8688">bpo-8688</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module’s <code class="xref py py-const docutils literal notranslate"><span class="pre">IGNORE_EXCEPTION_DETAIL</span></code> flag
will now ignore the name of the module containing the exception
being tested.  (Patch by Lennart Regebro; <a class="reference external" href="https://bugs.python.org/issue7490">bpo-7490</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages, including MIME documents."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> module’s <a class="reference internal" href="../library/email.message.html#email.message.Message" title="email.message.Message"><code class="xref py py-class docutils literal notranslate"><span class="pre">Message</span></code></a> class will
now accept a Unicode-valued payload, automatically converting the
payload to the encoding specified by <code class="xref py py-attr docutils literal notranslate"><span class="pre">output_charset</span></code>.
(Added by R. David Murray; <a class="reference external" href="https://bugs.python.org/issue1368247">bpo-1368247</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a> class now accepts a single float or
<a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instance, or two rational numbers, as
arguments to its constructor.  (Implemented by Mark Dickinson;
rationals added in <a class="reference external" href="https://bugs.python.org/issue5812">bpo-5812</a>, and float/decimal in
<a class="reference external" href="https://bugs.python.org/issue8294">bpo-8294</a>.)</p>
<p>Ordering comparisons (<code class="docutils literal notranslate"><span class="pre">&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code>) between
fractions and complex numbers now raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
This fixes an oversight, making the <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a>
match the other numeric types.</p>
</li>
<li><p class="first">New class: <a class="reference internal" href="../library/ftplib.html#ftplib.FTP_TLS" title="ftplib.FTP_TLS"><code class="xref py py-class docutils literal notranslate"><span class="pre">FTP_TLS</span></code></a> in
the <a class="reference internal" href="../library/ftplib.html#module-ftplib" title="ftplib: FTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ftplib</span></code></a> module provides secure FTP
connections using TLS encapsulation of authentication as well as
subsequent control and data transfers.
(Contributed by Giampaolo Rodola; <a class="reference external" href="https://bugs.python.org/issue2054">bpo-2054</a>.)</p>
<p>The <a class="reference internal" href="../library/ftplib.html#ftplib.FTP.storbinary" title="ftplib.FTP.storbinary"><code class="xref py py-meth docutils literal notranslate"><span class="pre">storbinary()</span></code></a> method for binary uploads can now restart
uploads thanks to an added <em>rest</em> parameter (patch by Pablo Mouzo;
<a class="reference external" href="https://bugs.python.org/issue6845">bpo-6845</a>.)</p>
</li>
<li><p class="first">New class decorator: <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">total_ordering()</span></code></a> in the <a class="reference internal" href="../library/functools.html#module-functools" title="functools: Higher-order functions and operations on callable objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">functools</span></code></a>
module takes a class that defines an <a class="reference internal" href="../reference/datamodel.html#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method and one of
<a class="reference internal" href="../reference/datamodel.html#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a>, <a class="reference internal" href="../reference/datamodel.html#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a>, or <a class="reference internal" href="../reference/datamodel.html#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a>,
and generates the missing comparison methods.  Since the
<a class="reference internal" href="../reference/datamodel.html#object.__cmp__" title="object.__cmp__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__cmp__()</span></code></a> method is being deprecated in Python 3.x,
this decorator makes it easier to define ordered classes.
(Added by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue5479">bpo-5479</a>.)</p>
<p>New function: <a class="reference internal" href="../library/functools.html#functools.cmp_to_key" title="functools.cmp_to_key"><code class="xref py py-func docutils literal notranslate"><span class="pre">cmp_to_key()</span></code></a> will take an old-style comparison
function that expects two arguments and return a new callable that
can be used as the <em>key</em> parameter to functions such as
<a class="reference internal" href="../library/functions.html#sorted" title="sorted"><code class="xref py py-func docutils literal notranslate"><span class="pre">sorted()</span></code></a>, <a class="reference internal" href="../library/functions.html#min" title="min"><code class="xref py py-func docutils literal notranslate"><span class="pre">min()</span></code></a> and <a class="reference internal" href="../library/functions.html#max" title="max"><code class="xref py py-func docutils literal notranslate"><span class="pre">max()</span></code></a>, etc.  The primary
intended use is to help with making code compatible with Python 3.x.
(Added by Raymond Hettinger.)</p>
</li>
<li><p class="first">New function: the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module’s <a class="reference internal" href="../library/gc.html#gc.is_tracked" title="gc.is_tracked"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_tracked()</span></code></a> returns
true if a given instance is tracked by the garbage collector, false
otherwise. (Contributed by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue4688">bpo-4688</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module’s <a class="reference internal" href="../library/gzip.html#gzip.GzipFile" title="gzip.GzipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">GzipFile</span></code></a> now supports the context
management protocol, so you can write <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">gzip.GzipFile(...)</span> <span class="pre">as</span> <span class="pre">f:</span></code>
(contributed by Hagen Fürstenau; <a class="reference external" href="https://bugs.python.org/issue3860">bpo-3860</a>), and it now implements
the <a class="reference internal" href="../library/io.html#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BufferedIOBase</span></code></a> ABC, so you can wrap it with
<a class="reference internal" href="../library/io.html#io.BufferedReader" title="io.BufferedReader"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BufferedReader</span></code></a> for faster processing
(contributed by Nir Aides; <a class="reference external" href="https://bugs.python.org/issue7471">bpo-7471</a>).
It’s also now possible to override the modification time
recorded in a gzipped file by providing an optional timestamp to
the constructor.  (Contributed by Jacques Frechet; <a class="reference external" href="https://bugs.python.org/issue4272">bpo-4272</a>.)</p>
<p>Files in gzip format can be padded with trailing zero bytes; the
<a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a> module will now consume these trailing bytes.  (Fixed by
Tadek Pietraszek and Brian Curtin; <a class="reference external" href="https://bugs.python.org/issue2846">bpo-2846</a>.)</p>
</li>
<li><p class="first">New attribute: the <a class="reference internal" href="../library/hashlib.html#module-hashlib" title="hashlib: Secure hash and message digest algorithms."><code class="xref py py-mod docutils literal notranslate"><span class="pre">hashlib</span></code></a> module now has an <a class="reference internal" href="../library/hashlib.html#hashlib.hashlib.algorithms" title="hashlib.hashlib.algorithms"><code class="xref py py-attr docutils literal notranslate"><span class="pre">algorithms</span></code></a>
attribute containing a tuple naming the supported algorithms.
In Python 2.7, <code class="docutils literal notranslate"><span class="pre">hashlib.algorithms</span></code> contains
<code class="docutils literal notranslate"><span class="pre">('md5',</span> <span class="pre">'sha1',</span> <span class="pre">'sha224',</span> <span class="pre">'sha256',</span> <span class="pre">'sha384',</span> <span class="pre">'sha512')</span></code>.
(Contributed by Carl Chenet; <a class="reference external" href="https://bugs.python.org/issue7418">bpo-7418</a>.)</p>
</li>
<li><p class="first">The default <a class="reference internal" href="../library/httplib.html#httplib.HTTPResponse" title="httplib.HTTPResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPResponse</span></code></a> class used by the <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> module now
supports buffering, resulting in much faster reading of HTTP responses.
(Contributed by Kristján Valur Jónsson; <a class="reference external" href="https://bugs.python.org/issue4879">bpo-4879</a>.)</p>
<p>The <a class="reference internal" href="../library/httplib.html#httplib.HTTPConnection" title="httplib.HTTPConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPConnection</span></code></a> and <a class="reference internal" href="../library/httplib.html#httplib.HTTPSConnection" title="httplib.HTTPSConnection"><code class="xref py py-class docutils literal notranslate"><span class="pre">HTTPSConnection</span></code></a> classes
now support a <em>source_address</em> parameter, a <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> 2-tuple
giving the source address that will be used for the connection.
(Contributed by Eldon Ziegler; <a class="reference external" href="https://bugs.python.org/issue3972">bpo-3972</a>.)</p>
</li>
<li><p class="first">The <code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> module now supports relative imports.  Note that
<code class="xref py py-mod docutils literal notranslate"><span class="pre">ihooks</span></code> is an older module for customizing imports,
superseded by the <a class="reference internal" href="../library/imputil.html#module-imputil" title="imputil: Manage and augment the import process. (deprecated)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">imputil</span></code></a> module added in Python 2.0.
(Relative import support added by Neil Schemenauer.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/imaplib.html#module-imaplib" title="imaplib: IMAP4 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">imaplib</span></code></a> module now supports IPv6 addresses.
(Contributed by Derek Morr; <a class="reference external" href="https://bugs.python.org/issue1655">bpo-1655</a>.)</p>
</li>
<li><p class="first">New function: the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module’s <a class="reference internal" href="../library/inspect.html#inspect.getcallargs" title="inspect.getcallargs"><code class="xref py py-func docutils literal notranslate"><span class="pre">getcallargs()</span></code></a>
takes a callable and its positional and keyword arguments,
and figures out which of the callable’s parameters will receive each argument,
returning a dictionary mapping argument names to their values.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">inspect</span> <span class="k">import</span> <span class="n">getcallargs</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="o">*</span><span class="n">pos</span><span class="p">,</span> <span class="o">**</span><span class="n">named</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">pass</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: 1, &#39;b&#39;: 2, &#39;pos&#39;: (3,), &#39;named&#39;: {}}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">a</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">x</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
<span class="go">{&#39;a&#39;: 2, &#39;b&#39;: 1, &#39;pos&#39;: (), &#39;named&#39;: {&#39;x&#39;: 4}}</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">getcallargs</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="gt">Traceback (most recent call last):</span>
<span class="c">...</span>
<span class="gr">TypeError</span>: <span class="n">f() takes at least 1 argument (0 given)</span>
</pre></div>
</div>
<p>Contributed by George Sakkis; <a class="reference external" href="https://bugs.python.org/issue3135">bpo-3135</a>.</p>
</li>
<li><p class="first">Updated module: The <a class="reference internal" href="../library/io.html#module-io" title="io: Core tools for working with streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">io</span></code></a> library has been upgraded to the version shipped with
Python 3.1.  For 3.1, the I/O library was entirely rewritten in C
and is 2 to 20 times faster depending on the task being performed.  The
original Python version was renamed to the <code class="xref py py-mod docutils literal notranslate"><span class="pre">_pyio</span></code> module.</p>
<p>One minor resulting change: the <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOBase</span></code></a> class now
has an <code class="xref py py-attr docutils literal notranslate"><span class="pre">errors</span></code> attribute giving the error setting
used for encoding and decoding errors (one of <code class="docutils literal notranslate"><span class="pre">'strict'</span></code>, <code class="docutils literal notranslate"><span class="pre">'replace'</span></code>,
<code class="docutils literal notranslate"><span class="pre">'ignore'</span></code>).</p>
<p>The <a class="reference internal" href="../library/io.html#io.FileIO" title="io.FileIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.FileIO</span></code></a> class now raises an <a class="reference internal" href="../library/exceptions.html#exceptions.OSError" title="exceptions.OSError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OSError</span></code></a> when passed
an invalid file descriptor.  (Implemented by Benjamin Peterson;
<a class="reference external" href="https://bugs.python.org/issue4991">bpo-4991</a>.)  The <a class="reference internal" href="../library/io.html#io.IOBase.truncate" title="io.IOBase.truncate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code></a> method now preserves the
file position; previously it would change the file position to the
end of the new file.  (Fixed by Pascal Chambon; <a class="reference external" href="https://bugs.python.org/issue6939">bpo-6939</a>.)</p>
</li>
<li><p class="first">New function: <code class="docutils literal notranslate"><span class="pre">itertools.compress(data,</span> <span class="pre">selectors)</span></code> takes two
iterators.  Elements of <em>data</em> are returned if the corresponding
value in <em>selectors</em> is true:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">compress</span><span class="p">(</span><span class="s1">&#39;ABCDEF&#39;</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">1</span><span class="p">,</span><span class="mi">1</span><span class="p">])</span> <span class="o">=&gt;</span>
  <span class="n">A</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">E</span><span class="p">,</span> <span class="n">F</span>
</pre></div>
</div>
<p>New function: <code class="docutils literal notranslate"><span class="pre">itertools.combinations_with_replacement(iter,</span> <span class="pre">r)</span></code>
returns all the possible <em>r</em>-length combinations of elements from the
iterable <em>iter</em>.  Unlike <a class="reference internal" href="../library/itertools.html#itertools.combinations" title="itertools.combinations"><code class="xref py py-func docutils literal notranslate"><span class="pre">combinations()</span></code></a>, individual elements
can be repeated in the generated combinations:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">itertools</span><span class="o">.</span><span class="n">combinations_with_replacement</span><span class="p">(</span><span class="s1">&#39;abc&#39;</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="o">=&gt;</span>
  <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;a&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;a&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">),</span>
  <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;b&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">),</span> <span class="p">(</span><span class="s1">&#39;c&#39;</span><span class="p">,</span> <span class="s1">&#39;c&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that elements are treated as unique depending on their position
in the input, not their actual values.</p>
<p>The <a class="reference internal" href="../library/itertools.html#itertools.count" title="itertools.count"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.count()</span></code></a> function now has a <em>step</em> argument that
allows incrementing by values other than 1.  <a class="reference internal" href="../library/itertools.html#itertools.count" title="itertools.count"><code class="xref py py-func docutils literal notranslate"><span class="pre">count()</span></code></a> also
now allows keyword arguments, and using non-integer values such as
floats or <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances.  (Implemented by Raymond
Hettinger; <a class="reference external" href="https://bugs.python.org/issue5032">bpo-5032</a>.)</p>
<p><a class="reference internal" href="../library/itertools.html#itertools.combinations" title="itertools.combinations"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.combinations()</span></code></a> and <a class="reference internal" href="../library/itertools.html#itertools.product" title="itertools.product"><code class="xref py py-func docutils literal notranslate"><span class="pre">itertools.product()</span></code></a>
previously raised <a class="reference internal" href="../library/exceptions.html#exceptions.ValueError" title="exceptions.ValueError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> for values of <em>r</em> larger than
the input iterable.  This was deemed a specification error, so they
now return an empty iterator.  (Fixed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue4816">bpo-4816</a>.)</p>
</li>
<li><p class="first">Updated module: The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module was upgraded to version 2.0.9 of the
simplejson package, which includes a C extension that makes
encoding and decoding faster.
(Contributed by Bob Ippolito; <a class="reference external" href="https://bugs.python.org/issue4136">bpo-4136</a>.)</p>
<p>To support the new <a class="reference internal" href="../library/collections.html#collections.OrderedDict" title="collections.OrderedDict"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.OrderedDict</span></code></a> type, <a class="reference internal" href="../library/json.html#json.load" title="json.load"><code class="xref py py-func docutils literal notranslate"><span class="pre">json.load()</span></code></a>
now has an optional <em>object_pairs_hook</em> parameter that will be called
with any object literal that decodes to a list of pairs.
(Contributed by Raymond Hettinger; <a class="reference external" href="https://bugs.python.org/issue5381">bpo-5381</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/mailbox.html#module-mailbox" title="mailbox: Manipulate mailboxes in various formats"><code class="xref py py-mod docutils literal notranslate"><span class="pre">mailbox</span></code></a> module’s <a class="reference internal" href="../library/mailbox.html#mailbox.Maildir" title="mailbox.Maildir"><code class="xref py py-class docutils literal notranslate"><span class="pre">Maildir</span></code></a> class now records the
timestamp on the directories it reads, and only re-reads them if the
modification time has subsequently changed.  This improves
performance by avoiding unneeded directory scans.  (Fixed by
A.M. Kuchling and Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue1607951">bpo-1607951</a>, <a class="reference external" href="https://bugs.python.org/issue6896">bpo-6896</a>.)</p>
</li>
<li><p class="first">New functions: the <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module gained
<a class="reference internal" href="../library/math.html#math.erf" title="math.erf"><code class="xref py py-func docutils literal notranslate"><span class="pre">erf()</span></code></a> and <a class="reference internal" href="../library/math.html#math.erfc" title="math.erfc"><code class="xref py py-func docutils literal notranslate"><span class="pre">erfc()</span></code></a> for the error function and the complementary error function,
<a class="reference internal" href="../library/math.html#math.expm1" title="math.expm1"><code class="xref py py-func docutils literal notranslate"><span class="pre">expm1()</span></code></a> which computes <code class="docutils literal notranslate"><span class="pre">e**x</span> <span class="pre">-</span> <span class="pre">1</span></code> with more precision than
using <a class="reference internal" href="../library/math.html#math.exp" title="math.exp"><code class="xref py py-func docutils literal notranslate"><span class="pre">exp()</span></code></a> and subtracting 1,
<a class="reference internal" href="../library/math.html#math.gamma" title="math.gamma"><code class="xref py py-func docutils literal notranslate"><span class="pre">gamma()</span></code></a> for the Gamma function, and
<a class="reference internal" href="../library/math.html#math.lgamma" title="math.lgamma"><code class="xref py py-func docutils literal notranslate"><span class="pre">lgamma()</span></code></a> for the natural log of the Gamma function.
(Contributed by Mark Dickinson and nirinA raseliarison; <a class="reference external" href="https://bugs.python.org/issue3366">bpo-3366</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/multiprocessing.html#module-multiprocessing" title="multiprocessing: Process-based &quot;threading&quot; interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">Manager*</span></code> classes
can now be passed a callable that will be called whenever
a subprocess is started, along with a set of arguments that will be
passed to the callable.
(Contributed by lekma; <a class="reference external" href="https://bugs.python.org/issue5585">bpo-5585</a>.)</p>
<p>The <code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> class, which controls a pool of worker processes,
now has an optional <em>maxtasksperchild</em> parameter.  Worker processes
will perform the specified number of tasks and then exit, causing the
<code class="xref py py-class docutils literal notranslate"><span class="pre">Pool</span></code> to start a new worker.  This is useful if tasks may leak
memory or other resources, or if some tasks will cause the worker to
become very large.
(Contributed by Charles Cazabon; <a class="reference external" href="https://bugs.python.org/issue6963">bpo-6963</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/nntplib.html#module-nntplib" title="nntplib: NNTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">nntplib</span></code></a> module now supports IPv6 addresses.
(Contributed by Derek Morr; <a class="reference external" href="https://bugs.python.org/issue1664">bpo-1664</a>.)</p>
</li>
<li><p class="first">New functions: the <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module wraps the following POSIX system
calls: <a class="reference internal" href="../library/os.html#os.getresgid" title="os.getresgid"><code class="xref py py-func docutils literal notranslate"><span class="pre">getresgid()</span></code></a> and <a class="reference internal" href="../library/os.html#os.getresuid" title="os.getresuid"><code class="xref py py-func docutils literal notranslate"><span class="pre">getresuid()</span></code></a>, which return the
real, effective, and saved GIDs and UIDs;
<a class="reference internal" href="../library/os.html#os.setresgid" title="os.setresgid"><code class="xref py py-func docutils literal notranslate"><span class="pre">setresgid()</span></code></a> and <a class="reference internal" href="../library/os.html#os.setresuid" title="os.setresuid"><code class="xref py py-func docutils literal notranslate"><span class="pre">setresuid()</span></code></a>, which set
real, effective, and saved GIDs and UIDs to new values;
<a class="reference internal" href="../library/os.html#os.initgroups" title="os.initgroups"><code class="xref py py-func docutils literal notranslate"><span class="pre">initgroups()</span></code></a>, which initialize the group access list
for the current process.  (GID/UID functions
contributed by Travis H.; <a class="reference external" href="https://bugs.python.org/issue6508">bpo-6508</a>.  Support for initgroups added
by Jean-Paul Calderone; <a class="reference external" href="https://bugs.python.org/issue7333">bpo-7333</a>.)</p>
<p>The <a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a> function now re-initializes the import lock in
the child process; this fixes problems on Solaris when <a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code></a>
is called from a thread.  (Fixed by Zsolt Cserna; <a class="reference external" href="https://bugs.python.org/issue7242">bpo-7242</a>.)</p>
</li>
<li><p class="first">In the <a class="reference internal" href="../library/os.path.html#module-os.path" title="os.path: Operations on pathnames."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os.path</span></code></a> module, the <a class="reference internal" href="../library/os.path.html#os.path.normpath" title="os.path.normpath"><code class="xref py py-func docutils literal notranslate"><span class="pre">normpath()</span></code></a> and
<a class="reference internal" href="../library/os.path.html#os.path.abspath" title="os.path.abspath"><code class="xref py py-func docutils literal notranslate"><span class="pre">abspath()</span></code></a> functions now preserve Unicode; if their input path
is a Unicode string, the return value is also a Unicode string.
(<a class="reference internal" href="../library/os.path.html#os.path.normpath" title="os.path.normpath"><code class="xref py py-meth docutils literal notranslate"><span class="pre">normpath()</span></code></a> fixed by Matt Giuca in <a class="reference external" href="https://bugs.python.org/issue5827">bpo-5827</a>;
<a class="reference internal" href="../library/os.path.html#os.path.abspath" title="os.path.abspath"><code class="xref py py-meth docutils literal notranslate"><span class="pre">abspath()</span></code></a> fixed by Ezio Melotti in <a class="reference external" href="https://bugs.python.org/issue3426">bpo-3426</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a> module now has help for the various symbols that Python
uses.  You can now do <code class="docutils literal notranslate"><span class="pre">help('&lt;&lt;')</span></code> or <code class="docutils literal notranslate"><span class="pre">help('&#64;')</span></code>, for example.
(Contributed by David Laban; <a class="reference external" href="https://bugs.python.org/issue4739">bpo-4739</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module’s <a class="reference internal" href="../library/re.html#re.split" title="re.split"><code class="xref py py-func docutils literal notranslate"><span class="pre">split()</span></code></a>, <a class="reference internal" href="../library/re.html#re.sub" title="re.sub"><code class="xref py py-func docutils literal notranslate"><span class="pre">sub()</span></code></a>, and <a class="reference internal" href="../library/re.html#re.subn" title="re.subn"><code class="xref py py-func docutils literal notranslate"><span class="pre">subn()</span></code></a>
now accept an optional <em>flags</em> argument, for consistency with the
other functions in the module.  (Added by Gregory P. Smith.)</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../library/runpy.html#runpy.run_path" title="runpy.run_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_path()</span></code></a> in the <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> module
will execute the code at a provided <em>path</em> argument.  <em>path</em> can be
the path of a Python source file (<code class="file docutils literal notranslate"><span class="pre">example.py</span></code>), a compiled
bytecode file (<code class="file docutils literal notranslate"><span class="pre">example.pyc</span></code>), a directory
(<code class="file docutils literal notranslate"><span class="pre">./package/</span></code>), or a zip archive (<code class="file docutils literal notranslate"><span class="pre">example.zip</span></code>).  If a
directory or zip path is provided, it will be added to the front of
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> and the module <a class="reference internal" href="../library/__main__.html#module-__main__" title="__main__: The environment where the top-level script is run."><code class="xref py py-mod docutils literal notranslate"><span class="pre">__main__</span></code></a> will be imported.  It’s
expected that the directory or zip contains a <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code>;
if it doesn’t, some other <code class="file docutils literal notranslate"><span class="pre">__main__.py</span></code> might be imported from
a location later in <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>.  This makes more of the machinery
of <a class="reference internal" href="../library/runpy.html#module-runpy" title="runpy: Locate and run Python modules without importing them first."><code class="xref py py-mod docutils literal notranslate"><span class="pre">runpy</span></code></a> available to scripts that want to mimic the way
Python’s command line processes an explicit path name.
(Added by Nick Coghlan; <a class="reference external" href="https://bugs.python.org/issue6816">bpo-6816</a>.)</p>
</li>
<li><p class="first">New function: in the <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module, <a class="reference internal" href="../library/shutil.html#shutil.make_archive" title="shutil.make_archive"><code class="xref py py-func docutils literal notranslate"><span class="pre">make_archive()</span></code></a>
takes a filename, archive type (zip or tar-format), and a directory
path, and creates an archive containing the directory’s contents.
(Added by Tarek Ziadé.)</p>
<p><a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a>’s <a class="reference internal" href="../library/shutil.html#shutil.copyfile" title="shutil.copyfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">copyfile()</span></code></a> and <a class="reference internal" href="../library/shutil.html#shutil.copytree" title="shutil.copytree"><code class="xref py py-func docutils literal notranslate"><span class="pre">copytree()</span></code></a>
functions now raise a <code class="xref py py-exc docutils literal notranslate"><span class="pre">SpecialFileError</span></code> exception when
asked to copy a named pipe.  Previously the code would treat
named pipes like a regular file by opening them for reading, and
this would block indefinitely.  (Fixed by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue3002">bpo-3002</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/signal.html#module-signal" title="signal: Set handlers for asynchronous events."><code class="xref py py-mod docutils literal notranslate"><span class="pre">signal</span></code></a> module no longer re-installs the signal handler
unless this is truly necessary, which fixes a bug that could make it
impossible to catch the EINTR signal robustly.  (Fixed by
Charles-Francois Natali; <a class="reference external" href="https://bugs.python.org/issue8354">bpo-8354</a>.)</p>
</li>
<li><p class="first">New functions: in the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module, three new functions
return various site- and user-specific paths.
<a class="reference internal" href="../library/site.html#site.getsitepackages" title="site.getsitepackages"><code class="xref py py-func docutils literal notranslate"><span class="pre">getsitepackages()</span></code></a> returns a list containing all
global site-packages directories,
<a class="reference internal" href="../library/site.html#site.getusersitepackages" title="site.getusersitepackages"><code class="xref py py-func docutils literal notranslate"><span class="pre">getusersitepackages()</span></code></a> returns the path of the user’s
site-packages directory, and
<a class="reference internal" href="../library/site.html#site.getuserbase" title="site.getuserbase"><code class="xref py py-func docutils literal notranslate"><span class="pre">getuserbase()</span></code></a> returns the value of the <span class="target" id="index-9"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">USER_BASE</span></code>
environment variable, giving the path to a directory that can be used
to store data.
(Contributed by Tarek Ziadé; <a class="reference external" href="https://bugs.python.org/issue6693">bpo-6693</a>.)</p>
<p>The <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module now reports exceptions occurring
when the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sitecustomize</span></code> module is imported, and will no longer
catch and swallow the <a class="reference internal" href="../library/exceptions.html#exceptions.KeyboardInterrupt" title="exceptions.KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.  (Fixed by
Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue3137">bpo-3137</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socket.html#socket.create_connection" title="socket.create_connection"><code class="xref py py-func docutils literal notranslate"><span class="pre">create_connection()</span></code></a> function
gained a <em>source_address</em> parameter, a <code class="docutils literal notranslate"><span class="pre">(host,</span> <span class="pre">port)</span></code> 2-tuple
giving the source address that will be used for the connection.
(Contributed by Eldon Ziegler; <a class="reference external" href="https://bugs.python.org/issue3972">bpo-3972</a>.)</p>
<p>The <a class="reference internal" href="../library/socket.html#socket.socket.recv_into" title="socket.socket.recv_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recv_into()</span></code></a> and <a class="reference internal" href="../library/socket.html#socket.socket.recvfrom_into" title="socket.socket.recvfrom_into"><code class="xref py py-meth docutils literal notranslate"><span class="pre">recvfrom_into()</span></code></a>
methods will now write into objects that support the buffer API, most usefully
the <a class="reference internal" href="../library/functions.html#bytearray" title="bytearray"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytearray</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> objects.  (Implemented by
Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue8104">bpo-8104</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/socketserver.html#module-SocketServer" title="SocketServer: A framework for network servers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SocketServer</span></code></a> module’s <a class="reference internal" href="../library/socketserver.html#SocketServer.TCPServer" title="SocketServer.TCPServer"><code class="xref py py-class docutils literal notranslate"><span class="pre">TCPServer</span></code></a> class now
supports socket timeouts and disabling the Nagle algorithm.
The <code class="xref py py-attr docutils literal notranslate"><span class="pre">disable_nagle_algorithm</span></code> class attribute
defaults to <code class="docutils literal notranslate"><span class="pre">False</span></code>; if overridden to be true,
new request connections will have the TCP_NODELAY option set to
prevent buffering many small sends into a single TCP packet.
The <a class="reference internal" href="../library/socketserver.html#SocketServer.BaseServer.timeout" title="SocketServer.BaseServer.timeout"><code class="xref py py-attr docutils literal notranslate"><span class="pre">timeout</span></code></a> class attribute can hold
a timeout in seconds that will be applied to the request socket; if
no request is received within that time, <a class="reference internal" href="../library/socketserver.html#SocketServer.BaseServer.handle_timeout" title="SocketServer.BaseServer.handle_timeout"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_timeout()</span></code></a>
will be called and <a class="reference internal" href="../library/socketserver.html#SocketServer.BaseServer.handle_request" title="SocketServer.BaseServer.handle_request"><code class="xref py py-meth docutils literal notranslate"><span class="pre">handle_request()</span></code></a> will return.
(Contributed by Kristján Valur Jónsson; <a class="reference external" href="https://bugs.python.org/issue6192">bpo-6192</a> and <a class="reference external" href="https://bugs.python.org/issue6267">bpo-6267</a>.)</p>
</li>
<li><p class="first">Updated module: the <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module has been updated to
version 2.6.0 of the <a class="reference external" href="https://github.com/ghaering/pysqlite">pysqlite package</a>. Version 2.6.0 includes a number of bugfixes, and adds
the ability to load SQLite extensions from shared libraries.
Call the <code class="docutils literal notranslate"><span class="pre">enable_load_extension(True)</span></code> method to enable extensions,
and then call <a class="reference internal" href="../library/sqlite3.html#sqlite3.Connection.load_extension" title="sqlite3.Connection.load_extension"><code class="xref py py-meth docutils literal notranslate"><span class="pre">load_extension()</span></code></a> to load a particular shared library.
(Updated by Gerhard Häring.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module’s <code class="xref py py-class docutils literal notranslate"><span class="pre">SSLSocket</span></code> objects now support the
buffer API, which fixed a test suite failure (fix by Antoine Pitrou;
<a class="reference external" href="https://bugs.python.org/issue7133">bpo-7133</a>) and automatically set
OpenSSL’s <code class="xref c c-macro docutils literal notranslate"><span class="pre">SSL_MODE_AUTO_RETRY</span></code>, which will prevent an error
code being returned from <code class="xref py py-meth docutils literal notranslate"><span class="pre">recv()</span></code> operations that trigger an SSL
renegotiation (fix by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue8222">bpo-8222</a>).</p>
<p>The <a class="reference internal" href="../library/ssl.html#ssl.wrap_socket" title="ssl.wrap_socket"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl.wrap_socket()</span></code></a> constructor function now takes a
<em>ciphers</em> argument that’s a string listing the encryption algorithms
to be allowed; the format of the string is described
<a class="reference external" href="https://www.openssl.org/docs/manmaster/man1/ciphers.html#CIPHER-LIST-FORMAT">in the OpenSSL documentation</a>.
(Added by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue8322">bpo-8322</a>.)</p>
<p>Another change makes the extension load all of OpenSSL’s ciphers and
digest algorithms so that they’re all available.  Some SSL
certificates couldn’t be verified, reporting an “unknown algorithm”
error.  (Reported by Beda Kosata, and fixed by Antoine Pitrou;
<a class="reference external" href="https://bugs.python.org/issue8484">bpo-8484</a>.)</p>
<p>The version of OpenSSL being used is now available as the module
attributes <a class="reference internal" href="../library/ssl.html#ssl.OPENSSL_VERSION" title="ssl.OPENSSL_VERSION"><code class="xref py py-data docutils literal notranslate"><span class="pre">ssl.OPENSSL_VERSION</span></code></a> (a string),
<a class="reference internal" href="../library/ssl.html#ssl.OPENSSL_VERSION_INFO" title="ssl.OPENSSL_VERSION_INFO"><code class="xref py py-data docutils literal notranslate"><span class="pre">ssl.OPENSSL_VERSION_INFO</span></code></a> (a 5-tuple), and
<a class="reference internal" href="../library/ssl.html#ssl.OPENSSL_VERSION_NUMBER" title="ssl.OPENSSL_VERSION_NUMBER"><code class="xref py py-data docutils literal notranslate"><span class="pre">ssl.OPENSSL_VERSION_NUMBER</span></code></a> (an integer).  (Added by Antoine
Pitrou; <a class="reference external" href="https://bugs.python.org/issue8321">bpo-8321</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret strings as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module will no longer silently ignore overflow
errors when a value is too large for a particular integer format
code (one of <code class="docutils literal notranslate"><span class="pre">bBhHiIlLqQ</span></code>); it now always raises a
<a class="reference internal" href="../library/struct.html#struct.error" title="struct.error"><code class="xref py py-exc docutils literal notranslate"><span class="pre">struct.error</span></code></a> exception.  (Changed by Mark Dickinson;
<a class="reference external" href="https://bugs.python.org/issue1523">bpo-1523</a>.)  The <a class="reference internal" href="../library/struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> function will also
attempt to use <a class="reference internal" href="../reference/datamodel.html#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> to convert and pack non-integers
before trying the <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> method or reporting an error.
(Changed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue8300">bpo-8300</a>.)</p>
</li>
<li><p class="first">New function: the <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module’s
<a class="reference internal" href="../library/subprocess.html#subprocess.check_output" title="subprocess.check_output"><code class="xref py py-func docutils literal notranslate"><span class="pre">check_output()</span></code></a> runs a command with a specified set of arguments
and returns the command’s output as a string when the command runs without
error, or raises a <a class="reference internal" href="../library/subprocess.html#subprocess.CalledProcessError" title="subprocess.CalledProcessError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CalledProcessError</span></code></a> exception otherwise.</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">([</span><span class="s1">&#39;df&#39;</span><span class="p">,</span> <span class="s1">&#39;-h&#39;</span><span class="p">,</span> <span class="s1">&#39;.&#39;</span><span class="p">])</span>
<span class="go">&#39;Filesystem     Size   Used  Avail Capacity  Mounted on\n</span>
<span class="go">/dev/disk0s2    52G    49G   3.0G    94%    /\n&#39;</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">subprocess</span><span class="o">.</span><span class="n">check_output</span><span class="p">([</span><span class="s1">&#39;df&#39;</span><span class="p">,</span> <span class="s1">&#39;-h&#39;</span><span class="p">,</span> <span class="s1">&#39;/bogus&#39;</span><span class="p">])</span>
<span class="go">  ...</span>
<span class="go">subprocess.CalledProcessError: Command &#39;[&#39;df&#39;, &#39;-h&#39;, &#39;/bogus&#39;]&#39; returned non-zero exit status 1</span>
</pre></div>
</div>
<p>(Contributed by Gregory P. Smith.)</p>
<p>The <a class="reference internal" href="../library/subprocess.html#module-subprocess" title="subprocess: Subprocess management."><code class="xref py py-mod docutils literal notranslate"><span class="pre">subprocess</span></code></a> module will now retry its internal system calls
on receiving an <code class="xref py py-const docutils literal notranslate"><span class="pre">EINTR</span></code> signal.  (Reported by several people; final
patch by Gregory P. Smith in <a class="reference external" href="https://bugs.python.org/issue1068268">bpo-1068268</a>.)</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../library/symtable.html#symtable.Symbol.is_declared_global" title="symtable.Symbol.is_declared_global"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_declared_global()</span></code></a> in the <a class="reference internal" href="../library/symtable.html#module-symtable" title="symtable: Interface to the compiler's internal symbol tables."><code class="xref py py-mod docutils literal notranslate"><span class="pre">symtable</span></code></a> module
returns true for variables that are explicitly declared to be global,
false for ones that are implicitly global.
(Contributed by Jeremy Hylton.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/syslog.html#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">syslog</span></code></a> module will now use the value of <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> as the
identifier instead of the previous default value of <code class="docutils literal notranslate"><span class="pre">'python'</span></code>.
(Changed by Sean Reifschneider; <a class="reference external" href="https://bugs.python.org/issue8451">bpo-8451</a>.)</p>
</li>
<li><p class="first">The <code class="docutils literal notranslate"><span class="pre">sys.version_info</span></code> value is now a named tuple, with attributes
named <code class="xref py py-attr docutils literal notranslate"><span class="pre">major</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">minor</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">micro</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">releaselevel</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">serial</span></code>.  (Contributed by Ross
Light; <a class="reference external" href="https://bugs.python.org/issue4285">bpo-4285</a>.)</p>
<p><a class="reference internal" href="../library/sys.html#sys.getwindowsversion" title="sys.getwindowsversion"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.getwindowsversion()</span></code></a> also returns a named tuple,
with attributes named <code class="xref py py-attr docutils literal notranslate"><span class="pre">major</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">minor</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">build</span></code>,
<a class="reference internal" href="../library/platform.html#module-platform" title="platform: Retrieves as much platform identifying data as possible."><code class="xref py py-attr docutils literal notranslate"><span class="pre">platform</span></code></a>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">service_pack</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">service_pack_major</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">service_pack_minor</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">suite_mask</span></code>, and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">product_type</span></code>.  (Contributed by Brian Curtin; <a class="reference external" href="https://bugs.python.org/issue7766">bpo-7766</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module’s default error handling has changed, to
no longer suppress fatal errors.  The default error level was previously 0,
which meant that errors would only result in a message being written to the
debug log, but because the debug log is not activated by default,
these errors go unnoticed.  The default error level is now 1,
which raises an exception if there’s an error.
(Changed by Lars Gustäbel; <a class="reference external" href="https://bugs.python.org/issue7357">bpo-7357</a>.)</p>
<p><a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> now supports filtering the <a class="reference internal" href="../library/tarfile.html#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a>
objects being added to a tar file.  When you call <a class="reference internal" href="../library/tarfile.html#tarfile.TarFile.add" title="tarfile.TarFile.add"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code></a>,
you may supply an optional <em>filter</em> argument
that’s a callable.  The <em>filter</em> callable will be passed the
<a class="reference internal" href="../library/tarfile.html#tarfile.TarInfo" title="tarfile.TarInfo"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarInfo</span></code></a> for every file being added, and can modify and return it.
If the callable returns <code class="docutils literal notranslate"><span class="pre">None</span></code>, the file will be excluded from the
resulting archive.  This is more powerful than the existing
<em>exclude</em> argument, which has therefore been deprecated.
(Added by Lars Gustäbel; <a class="reference external" href="https://bugs.python.org/issue6856">bpo-6856</a>.)
The <a class="reference internal" href="../library/tarfile.html#tarfile.TarFile" title="tarfile.TarFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TarFile</span></code></a> class also now supports the context management protocol.
(Added by Lars Gustäbel; <a class="reference external" href="https://bugs.python.org/issue7232">bpo-7232</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/threading.html#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> method of the <a class="reference internal" href="../library/threading.html#threading.Event" title="threading.Event"><code class="xref py py-class docutils literal notranslate"><span class="pre">threading.Event</span></code></a> class
now returns the internal flag on exit.  This means the method will usually
return true because <a class="reference internal" href="../library/threading.html#threading.Event.wait" title="threading.Event.wait"><code class="xref py py-meth docutils literal notranslate"><span class="pre">wait()</span></code></a> is supposed to block until the
internal flag becomes true.  The return value will only be false if
a timeout was provided and the operation timed out.
(Contributed by Tim Lesher; <a class="reference external" href="https://bugs.python.org/issue1674032">bpo-1674032</a>.)</p>
</li>
<li><p class="first">The Unicode database provided by the <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> module is
now used internally to determine which characters are numeric,
whitespace, or represent line breaks.  The database also
includes information from the <code class="file docutils literal notranslate"><span class="pre">Unihan.txt</span></code> data file (patch
by Anders Chrigström and Amaury Forgeot d’Arc; <a class="reference external" href="https://bugs.python.org/issue1571184">bpo-1571184</a>)
and has been updated to version 5.2.0 (updated by
Florent Xicluna; <a class="reference external" href="https://bugs.python.org/issue8024">bpo-8024</a>).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module’s <a class="reference internal" href="../library/urlparse.html#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> now handles
unknown URL schemes in a fashion compliant with <span class="target" id="index-10"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3986.html"><strong>RFC 3986</strong></a>: if the
URL is of the form <code class="docutils literal notranslate"><span class="pre">&quot;&lt;something&gt;://...&quot;</span></code>, the text before the
<code class="docutils literal notranslate"><span class="pre">://</span></code> is treated as the scheme, even if it’s a made-up scheme that
the module doesn’t know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="s1">&#39;invented://host/filename?query&#39;</span><span class="p">)</span>
<span class="go">(&#39;invented&#39;, &#39;&#39;, &#39;//host/filename?query&#39;, &#39;&#39;, &#39;&#39;)</span>
</pre></div>
</div>
<p>Python 2.7 (and Python 2.6.5) will return:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="s1">&#39;invented://host/filename?query&#39;</span><span class="p">)</span>
<span class="go">(&#39;invented&#39;, &#39;host&#39;, &#39;/filename?query&#39;, &#39;&#39;, &#39;&#39;)</span>
</pre></div>
</div>
<p>(Python 2.7 actually produces slightly different output, since it
returns a named tuple instead of a standard tuple.)</p>
<p>The <a class="reference internal" href="../library/urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module also supports IPv6 literal addresses as defined by
<span class="target" id="index-11"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc2732.html"><strong>RFC 2732</strong></a> (contributed by Senthil Kumaran; <a class="reference external" href="https://bugs.python.org/issue2987">bpo-2987</a>).</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="o">.</span><span class="n">urlparse</span><span class="p">(</span><span class="s1">&#39;http://[1080::8:800:200C:417A]/foo&#39;</span><span class="p">)</span>
<span class="go">ParseResult(scheme=&#39;http&#39;, netloc=&#39;[1080::8:800:200C:417A]&#39;,</span>
<span class="go">            path=&#39;/foo&#39;, params=&#39;&#39;, query=&#39;&#39;, fragment=&#39;&#39;)</span>
</pre></div>
</div>
</li>
<li><p class="first">New class: the <a class="reference internal" href="../library/weakref.html#weakref.WeakSet" title="weakref.WeakSet"><code class="xref py py-class docutils literal notranslate"><span class="pre">WeakSet</span></code></a> class in the <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a>
module is a set that only holds weak references to its elements; elements
will be removed once there are no references pointing to them.
(Originally implemented in Python 3.x by Raymond Hettinger, and backported
to 2.7 by Michael Foord.)</p>
</li>
<li><p class="first">The ElementTree library, <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>, no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like <code class="docutils literal notranslate"><span class="pre">&lt;?xml-stylesheet</span> <span class="pre">href=&quot;#style1&quot;?&gt;</span></code>)
or comment (which looks like <code class="docutils literal notranslate"><span class="pre">&lt;!--</span> <span class="pre">comment</span> <span class="pre">--&gt;</span></code>).
(Patch by Neil Muller; <a class="reference external" href="https://bugs.python.org/issue2746">bpo-2746</a>.)</p>
</li>
<li><p class="first">The XML-RPC client and server, provided by the <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a> and
<a class="reference internal" href="../library/simplexmlrpcserver.html#module-SimpleXMLRPCServer" title="SimpleXMLRPCServer: Basic XML-RPC server implementation."><code class="xref py py-mod docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code></a> modules, have improved performance by
supporting HTTP/1.1 keep-alive and by optionally using gzip encoding
to compress the XML being exchanged.  The gzip compression is
controlled by the <code class="xref py py-attr docutils literal notranslate"><span class="pre">encode_threshold</span></code> attribute of
<code class="xref py py-class docutils literal notranslate"><span class="pre">SimpleXMLRPCRequestHandler</span></code>, which contains a size in bytes;
responses larger than this will be compressed.
(Contributed by Kristján Valur Jónsson; <a class="reference external" href="https://bugs.python.org/issue6267">bpo-6267</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module’s <a class="reference internal" href="../library/zipfile.html#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> now supports the context
management protocol, so you can write <code class="docutils literal notranslate"><span class="pre">with</span> <span class="pre">zipfile.ZipFile(...)</span> <span class="pre">as</span> <span class="pre">f:</span></code>.
(Contributed by Brian Curtin; <a class="reference external" href="https://bugs.python.org/issue5511">bpo-5511</a>.)</p>
<p><a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> now also supports archiving empty directories and
extracts them correctly.  (Fixed by Kuba Wieczorek; <a class="reference external" href="https://bugs.python.org/issue4710">bpo-4710</a>.)
Reading files out of an archive is faster, and interleaving
<a class="reference internal" href="../library/zipfile.html#zipfile.ZipFile.read" title="zipfile.ZipFile.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> now works correctly.
(Contributed by Nir Aides; <a class="reference external" href="https://bugs.python.org/issue7610">bpo-7610</a>.)</p>
<p>The <a class="reference internal" href="../library/zipfile.html#zipfile.is_zipfile" title="zipfile.is_zipfile"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_zipfile()</span></code></a> function now
accepts a file object, in addition to the path names accepted in earlier
versions.  (Contributed by Gabriel Genellina; <a class="reference external" href="https://bugs.python.org/issue4756">bpo-4756</a>.)</p>
<p>The <a class="reference internal" href="../library/zipfile.html#zipfile.ZipFile.writestr" title="zipfile.ZipFile.writestr"><code class="xref py py-meth docutils literal notranslate"><span class="pre">writestr()</span></code></a> method now has an optional <em>compress_type</em> parameter
that lets you override the default compression method specified in the
<a class="reference internal" href="../library/zipfile.html#zipfile.ZipFile" title="zipfile.ZipFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">ZipFile</span></code></a> constructor.  (Contributed by Ronald Oussoren;
<a class="reference external" href="https://bugs.python.org/issue6003">bpo-6003</a>.)</p>
</li>
</ul>
<div class="section" id="new-module-importlib">
<span id="importlib-section"></span><h3>New module: importlib<a class="headerlink" href="#new-module-importlib" title="Permalink to this headline">¶</a></h3>
<p>Python 3.1 includes the <a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> package, a re-implementation
of the logic underlying Python’s <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement.
<a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> is useful for implementors of Python interpreters and
to users who wish to write new importers that can participate in the
import process.  Python 2.7 doesn’t contain the complete
<a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> package, but instead has a tiny subset that contains
a single function, <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">import_module()</span></code></a>.</p>
<p><code class="docutils literal notranslate"><span class="pre">import_module(name,</span> <span class="pre">package=None)</span></code> imports a module.  <em>name</em> is
a string containing the module or package’s name.  It’s possible to do
relative imports by providing a string that begins with a <code class="docutils literal notranslate"><span class="pre">.</span></code>
character, such as <code class="docutils literal notranslate"><span class="pre">..utils.errors</span></code>.  For relative imports, the
<em>package</em> argument must be provided and is the name of the package that
will be used as the anchor for
the relative import.  <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">import_module()</span></code></a> both inserts the imported
module into <code class="docutils literal notranslate"><span class="pre">sys.modules</span></code> and returns the module object.</p>
<p>Here are some examples:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">importlib</span> <span class="k">import</span> <span class="n">import_module</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">anydbm</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="s1">&#39;anydbm&#39;</span><span class="p">)</span>  <span class="c1"># Standard absolute import</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">anydbm</span>
<span class="go">&lt;module &#39;anydbm&#39; from &#39;/p/python/Lib/anydbm.py&#39;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Relative import</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">file_util</span> <span class="o">=</span> <span class="n">import_module</span><span class="p">(</span><span class="s1">&#39;..file_util&#39;</span><span class="p">,</span> <span class="s1">&#39;distutils.command&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">file_util</span>
<span class="go">&lt;module &#39;distutils.file_util&#39; from &#39;/python/Lib/distutils/file_util.pyc&#39;&gt;</span>
</pre></div>
</div>
<p><a class="reference internal" href="../library/importlib.html#module-importlib" title="importlib: Convenience wrappers for __import__"><code class="xref py py-mod docutils literal notranslate"><span class="pre">importlib</span></code></a> was implemented by Brett Cannon and introduced in
Python 3.1.</p>
</div>
<div class="section" id="new-module-sysconfig">
<h3>New module: sysconfig<a class="headerlink" href="#new-module-sysconfig" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> module has been pulled out of the Distutils
package, becoming a new top-level module in its own right.
<a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> provides functions for getting information about
Python’s build process: compiler switches, installation paths, the
platform name, and whether Python is running from its source
directory.</p>
<p>Some of the functions in the module are:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/sysconfig.html#sysconfig.get_config_var" title="sysconfig.get_config_var"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_var()</span></code></a> returns variables from Python’s
Makefile and the <code class="file docutils literal notranslate"><span class="pre">pyconfig.h</span></code> file.</li>
<li><a class="reference internal" href="../library/sysconfig.html#sysconfig.get_config_vars" title="sysconfig.get_config_vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_config_vars()</span></code></a> returns a dictionary containing
all of the configuration variables.</li>
<li><a class="reference internal" href="../library/sysconfig.html#sysconfig.get_path" title="sysconfig.get_path"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_path()</span></code></a> returns the configured path for
a particular type of module: the standard library,
site-specific modules, platform-specific modules, etc.</li>
<li><a class="reference internal" href="../library/sysconfig.html#sysconfig.is_python_build" title="sysconfig.is_python_build"><code class="xref py py-func docutils literal notranslate"><span class="pre">is_python_build()</span></code></a> returns true if you’re running a
binary from a Python source tree, and false otherwise.</li>
</ul>
<p>Consult the <a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> documentation for more details and for
a complete list of functions.</p>
<p>The Distutils package and <a class="reference internal" href="../library/sysconfig.html#module-sysconfig" title="sysconfig: Python's configuration information"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sysconfig</span></code></a> are now maintained by Tarek
Ziadé, who has also started a Distutils2 package (source repository at
<a class="reference external" href="https://hg.python.org/distutils2/">https://hg.python.org/distutils2/</a>) for developing a next-generation
version of Distutils.</p>
</div>
<div class="section" id="ttk-themed-widgets-for-tk">
<h3>ttk: Themed Widgets for Tk<a class="headerlink" href="#ttk-themed-widgets-for-tk" title="Permalink to this headline">¶</a></h3>
<p>Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk
widgets but have a more customizable appearance and can therefore more
closely resemble the native platform’s widgets.  This widget
set was originally called Tile, but was renamed to Ttk (for “themed Tk”)
on being added to Tcl/Tck release 8.5.</p>
<p>To learn more, read the <a class="reference internal" href="../library/ttk.html#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> module documentation.  You may also
wish to read the Tcl/Tk manual page describing the
Ttk theme engine, available at
<a class="reference external" href="https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm">https://www.tcl.tk/man/tcl8.5/TkCmd/ttk_intro.htm</a>. Some
screenshots of the Python/Ttk code in use are at
<a class="reference external" href="https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki">https://code.google.com/archive/p/python-ttk/wikis/Screenshots.wiki</a>.</p>
<p>The <a class="reference internal" href="../library/ttk.html#module-ttk" title="ttk: Tk themed widget set"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ttk</span></code></a> module was written by Guilherme Polo and added in
<a class="reference external" href="https://bugs.python.org/issue2983">bpo-2983</a>.  An alternate version called <code class="docutils literal notranslate"><span class="pre">Tile.py</span></code>, written by
Martin Franklin and maintained by Kevin Walzer, was proposed for
inclusion in <a class="reference external" href="https://bugs.python.org/issue2618">bpo-2618</a>, but the authors argued that Guilherme
Polo’s work was more comprehensive.</p>
</div>
<div class="section" id="updated-module-unittest">
<span id="unittest-section"></span><h3>Updated module: unittest<a class="headerlink" href="#updated-module-unittest" title="Permalink to this headline">¶</a></h3>
<p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module was greatly enhanced; many
new features were added.  Most of these features were implemented
by Michael Foord, unless otherwise noted.  The enhanced version of
the module is downloadable separately for use with Python versions 2.4 to 2.6,
packaged as the <code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest2</span></code> package, from
<a class="reference external" href="https://pypi.org/project/unittest2">https://pypi.org/project/unittest2</a>.</p>
<p>When used from the command line, the module can automatically discover
tests.  It’s not as fancy as <a class="reference external" href="http://pytest.org">py.test</a> or
<a class="reference external" href="https://nose.readthedocs.io/">nose</a>, but provides a
simple way to run tests kept within a set of package directories.  For example,
the following command will search the <code class="file docutils literal notranslate"><span class="pre">test/</span></code> subdirectory for
any importable test files named <code class="docutils literal notranslate"><span class="pre">test*.py</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">unittest</span> <span class="n">discover</span> <span class="o">-</span><span class="n">s</span> <span class="n">test</span>
</pre></div>
</div>
<p>Consult the <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module documentation for more details.
(Developed in <a class="reference external" href="https://bugs.python.org/issue6001">bpo-6001</a>.)</p>
<p>The <a class="reference internal" href="../library/unittest.html#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">main()</span></code></a> function supports some other new options:</p>
<ul>
<li><p class="first"><a class="reference internal" href="../library/unittest.html#cmdoption-unittest-b"><code class="xref std std-option docutils literal notranslate"><span class="pre">-b</span></code></a> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--buffer</span></code> will buffer the standard output
and standard error streams during each test.  If the test passes,
any resulting output will be discarded; on failure, the buffered
output will be displayed.</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/unittest.html#cmdoption-unittest-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--catch</span></code> will cause the control-C interrupt
to be handled more gracefully.  Instead of interrupting the test
process immediately, the currently running test will be completed
and then the partial results up to the interruption will be reported.
If you’re impatient, a second press of control-C will cause an immediate
interruption.</p>
<p>This control-C handler tries to avoid causing problems when the code
being tested or the tests being run have defined a signal handler of
their own, by noticing that a signal handler was already set and
calling it.  If this doesn’t work for you, there’s a
<a class="reference internal" href="../library/unittest.html#unittest.removeHandler" title="unittest.removeHandler"><code class="xref py py-func docutils literal notranslate"><span class="pre">removeHandler()</span></code></a> decorator that can be used to mark tests that
should have the control-C handling disabled.</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/unittest.html#cmdoption-unittest-f"><code class="xref std std-option docutils literal notranslate"><span class="pre">-f</span></code></a> or <code class="xref std std-option docutils literal notranslate"><span class="pre">--failfast</span></code> makes
test execution stop immediately when a test fails instead of
continuing to execute further tests.  (Suggested by Cliff Dyer and
implemented by Michael Foord; <a class="reference external" href="https://bugs.python.org/issue8074">bpo-8074</a>.)</p>
</li>
</ul>
<p>The progress messages now show ‘x’ for expected failures
and ‘u’ for unexpected successes when run in verbose mode.
(Contributed by Benjamin Peterson.)</p>
<p>Test cases can raise the <a class="reference internal" href="../library/unittest.html#unittest.SkipTest" title="unittest.SkipTest"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SkipTest</span></code></a> exception to skip a
test (<a class="reference external" href="https://bugs.python.org/issue1034053">bpo-1034053</a>).</p>
<p>The error messages for <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>,
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertTrue" title="unittest.TestCase.assertTrue"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTrue()</span></code></a>, and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertFalse" title="unittest.TestCase.assertFalse"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertFalse()</span></code></a>
failures now provide more information.  If you set the
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.longMessage" title="unittest.TestCase.longMessage"><code class="xref py py-attr docutils literal notranslate"><span class="pre">longMessage</span></code></a> attribute of your <a class="reference internal" href="../library/unittest.html#unittest.TestCase" title="unittest.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> classes to
true, both the standard error message and any additional message you
provide will be printed for failures.  (Added by Michael Foord; <a class="reference external" href="https://bugs.python.org/issue5663">bpo-5663</a>.)</p>
<p>The <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertRaises" title="unittest.TestCase.assertRaises"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaises()</span></code></a> method now
returns a context handler when called without providing a callable
object to run.  For example, you can write this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">KeyError</span><span class="p">):</span>
    <span class="p">{}[</span><span class="s1">&#39;foo&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>(Implemented by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue4444">bpo-4444</a>.)</p>
<p>Module- and class-level setup and teardown fixtures are now supported.
Modules can contain <code class="xref py py-func docutils literal notranslate"><span class="pre">setUpModule()</span></code> and <code class="xref py py-func docutils literal notranslate"><span class="pre">tearDownModule()</span></code>
functions.  Classes can have <a class="reference internal" href="../library/unittest.html#unittest.TestCase.setUpClass" title="unittest.TestCase.setUpClass"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUpClass()</span></code></a> and
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.tearDownClass" title="unittest.TestCase.tearDownClass"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDownClass()</span></code></a> methods that must be defined as class methods
(using <code class="docutils literal notranslate"><span class="pre">&#64;classmethod</span></code> or equivalent).  These functions and
methods are invoked when the test runner switches to a test case in a
different module or class.</p>
<p>The methods <a class="reference internal" href="../library/unittest.html#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addCleanup()</span></code></a> and
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.doCleanups" title="unittest.TestCase.doCleanups"><code class="xref py py-meth docutils literal notranslate"><span class="pre">doCleanups()</span></code></a> were added.
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.addCleanup" title="unittest.TestCase.addCleanup"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addCleanup()</span></code></a> lets you add cleanup functions that
will be called unconditionally (after <a class="reference internal" href="../library/unittest.html#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> if
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.setUp" title="unittest.TestCase.setUp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">setUp()</span></code></a> fails, otherwise after <a class="reference internal" href="../library/unittest.html#unittest.TestCase.tearDown" title="unittest.TestCase.tearDown"><code class="xref py py-meth docutils literal notranslate"><span class="pre">tearDown()</span></code></a>). This allows
for much simpler resource allocation and deallocation during tests
(<a class="reference external" href="https://bugs.python.org/issue5679">bpo-5679</a>).</p>
<p>A number of new methods were added that provide more specialized
tests.  Many of these methods were written by Google engineers
for use in their test suites; Gregory P. Smith, Michael Foord, and
GvR worked on merging them into Python’s version of <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a>.</p>
<ul class="simple">
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIsNone" title="unittest.TestCase.assertIsNone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNone()</span></code></a> and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIsNotNone" title="unittest.TestCase.assertIsNotNone"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNotNone()</span></code></a> take one
expression and verify that the result is or is not <code class="docutils literal notranslate"><span class="pre">None</span></code>.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIs" title="unittest.TestCase.assertIs"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIs()</span></code></a> and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIsNot" title="unittest.TestCase.assertIsNot"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsNot()</span></code></a>
take two values and check whether the two values evaluate to the same object or not.
(Added by Michael Foord; <a class="reference external" href="https://bugs.python.org/issue2578">bpo-2578</a>.)</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIsInstance" title="unittest.TestCase.assertIsInstance"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIsInstance()</span></code></a> and
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertNotIsInstance" title="unittest.TestCase.assertNotIsInstance"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotIsInstance()</span></code></a> check whether
the resulting object is an instance of a particular class, or of
one of a tuple of classes.  (Added by Georg Brandl; <a class="reference external" href="https://bugs.python.org/issue7031">bpo-7031</a>.)</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertGreater" title="unittest.TestCase.assertGreater"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertGreater()</span></code></a>, <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertGreaterEqual" title="unittest.TestCase.assertGreaterEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertGreaterEqual()</span></code></a>,
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertLess" title="unittest.TestCase.assertLess"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertLess()</span></code></a>, and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertLessEqual" title="unittest.TestCase.assertLessEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertLessEqual()</span></code></a> compare
two quantities.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertMultiLineEqual" title="unittest.TestCase.assertMultiLineEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertMultiLineEqual()</span></code></a> compares two strings, and if they’re
not equal, displays a helpful comparison that highlights the
differences in the two strings.  This comparison is now used by
default when Unicode strings are compared with <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertRegexpMatches" title="unittest.TestCase.assertRegexpMatches"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRegexpMatches()</span></code></a> and
<a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertNotRegexpMatches" title="unittest.TestCase.assertNotRegexpMatches"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotRegexpMatches()</span></code></a> checks whether the
first argument is a string matching or not matching the regular
expression provided as the second argument (<a class="reference external" href="https://bugs.python.org/issue8038">bpo-8038</a>).</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertRaisesRegexp" title="unittest.TestCase.assertRaisesRegexp"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertRaisesRegexp()</span></code></a> checks whether a particular exception
is raised, and then also checks that the string representation of
the exception matches the provided regular expression.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertIn" title="unittest.TestCase.assertIn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertIn()</span></code></a> and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertNotIn" title="unittest.TestCase.assertNotIn"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotIn()</span></code></a>
tests whether <em>first</em> is or is not in  <em>second</em>.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertItemsEqual" title="unittest.TestCase.assertItemsEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertItemsEqual()</span></code></a> tests whether two provided sequences
contain the same elements.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertSetEqual" title="unittest.TestCase.assertSetEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertSetEqual()</span></code></a> compares whether two sets are equal, and
only reports the differences between the sets in case of error.</li>
<li>Similarly, <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertListEqual" title="unittest.TestCase.assertListEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertListEqual()</span></code></a> and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertTupleEqual" title="unittest.TestCase.assertTupleEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertTupleEqual()</span></code></a>
compare the specified types and explain any differences without necessarily
printing their full values; these methods are now used by default
when comparing lists and tuples using <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.
More generally, <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertSequenceEqual" title="unittest.TestCase.assertSequenceEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertSequenceEqual()</span></code></a> compares two sequences
and can optionally check whether both sequences are of a
particular type.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertDictEqual" title="unittest.TestCase.assertDictEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertDictEqual()</span></code></a> compares two dictionaries and reports the
differences; it’s now used by default when you compare two dictionaries
using <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a>.  <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertDictContainsSubset" title="unittest.TestCase.assertDictContainsSubset"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertDictContainsSubset()</span></code></a> checks whether
all of the key/value pairs in <em>first</em> are found in <em>second</em>.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertAlmostEqual" title="unittest.TestCase.assertAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertAlmostEqual()</span></code></a> and <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertNotAlmostEqual" title="unittest.TestCase.assertNotAlmostEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertNotAlmostEqual()</span></code></a> test
whether <em>first</em> and <em>second</em> are approximately equal.  This method
can either round their difference to an optionally-specified number
of <em>places</em> (the default is 7) and compare it to zero, or require
the difference to be smaller than a supplied <em>delta</em> value.</li>
<li><a class="reference internal" href="../library/unittest.html#unittest.TestLoader.loadTestsFromName" title="unittest.TestLoader.loadTestsFromName"><code class="xref py py-meth docutils literal notranslate"><span class="pre">loadTestsFromName()</span></code></a> properly honors the
<a class="reference internal" href="../library/unittest.html#unittest.TestLoader.suiteClass" title="unittest.TestLoader.suiteClass"><code class="xref py py-attr docutils literal notranslate"><span class="pre">suiteClass</span></code></a> attribute of
the <a class="reference internal" href="../library/unittest.html#unittest.TestLoader" title="unittest.TestLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestLoader</span></code></a>. (Fixed by Mark Roddy; <a class="reference external" href="https://bugs.python.org/issue6866">bpo-6866</a>.)</li>
<li>A new hook lets you extend the <a class="reference internal" href="../library/unittest.html#unittest.TestCase.assertEqual" title="unittest.TestCase.assertEqual"><code class="xref py py-meth docutils literal notranslate"><span class="pre">assertEqual()</span></code></a> method to handle
new data types.  The <a class="reference internal" href="../library/unittest.html#unittest.TestCase.addTypeEqualityFunc" title="unittest.TestCase.addTypeEqualityFunc"><code class="xref py py-meth docutils literal notranslate"><span class="pre">addTypeEqualityFunc()</span></code></a> method takes a type
object and a function. The function will be used when both of the
objects being compared are of the specified type.  This function
should compare the two objects and raise an exception if they don’t
match; it’s a good idea for the function to provide additional
information about why the two objects aren’t matching, much as the new
sequence comparison methods do.</li>
</ul>
<p><a class="reference internal" href="../library/unittest.html#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">unittest.main()</span></code></a> now takes an optional <code class="docutils literal notranslate"><span class="pre">exit</span></code> argument.  If
false, <a class="reference internal" href="../library/unittest.html#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">main()</span></code></a> doesn’t call <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exit()</span></code></a>, allowing
<a class="reference internal" href="../library/unittest.html#unittest.main" title="unittest.main"><code class="xref py py-func docutils literal notranslate"><span class="pre">main()</span></code></a> to be used from the interactive interpreter.
(Contributed by J. Pablo Fernández; <a class="reference external" href="https://bugs.python.org/issue3379">bpo-3379</a>.)</p>
<p><a class="reference internal" href="../library/unittest.html#unittest.TestResult" title="unittest.TestResult"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestResult</span></code></a> has new <a class="reference internal" href="../library/unittest.html#unittest.TestResult.startTestRun" title="unittest.TestResult.startTestRun"><code class="xref py py-meth docutils literal notranslate"><span class="pre">startTestRun()</span></code></a> and
<a class="reference internal" href="../library/unittest.html#unittest.TestResult.stopTestRun" title="unittest.TestResult.stopTestRun"><code class="xref py py-meth docutils literal notranslate"><span class="pre">stopTestRun()</span></code></a> methods that are called immediately before
and after a test run.  (Contributed by Robert Collins; <a class="reference external" href="https://bugs.python.org/issue5728">bpo-5728</a>.)</p>
<p>With all these changes, the <code class="file docutils literal notranslate"><span class="pre">unittest.py</span></code> was becoming awkwardly
large, so the module was turned into a package and the code split into
several files (by Benjamin Peterson).  This doesn’t affect how the
module is imported or used.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.voidspace.org.uk/python/articles/unittest2.shtml">http://www.voidspace.org.uk/python/articles/unittest2.shtml</a></dt>
<dd>Describes the new features, how to use them, and the
rationale for various design decisions.  (By Michael Foord.)</dd>
</dl>
</div>
</div>
<div class="section" id="updated-module-elementtree-1-3">
<span id="elementtree-section"></span><h3>Updated module: ElementTree 1.3<a class="headerlink" href="#updated-module-elementtree-1-3" title="Permalink to this headline">¶</a></h3>
<p>The version of the ElementTree library included with Python was updated to
version 1.3.  Some of the new features are:</p>
<ul>
<li><p class="first">The various parsing functions now take a <em>parser</em> keyword argument
giving an <a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser" title="xml.etree.ElementTree.XMLParser"><code class="xref py py-class docutils literal notranslate"><span class="pre">XMLParser</span></code></a> instance that will
be used.  This makes it possible to override the file’s internal encoding:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">p</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XMLParser</span><span class="p">(</span><span class="n">encoding</span><span class="o">=</span><span class="s1">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;root/&gt;&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">parser</span><span class="o">=</span><span class="n">p</span><span class="p">)</span>
</pre></div>
</div>
<p>Errors in parsing XML now raise a <code class="xref py py-exc docutils literal notranslate"><span class="pre">ParseError</span></code> exception, whose
instances have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">position</span></code> attribute
containing a (<em>line</em>, <em>column</em>) tuple giving the location of the problem.</p>
</li>
<li><p class="first">ElementTree’s code for converting trees to a string has been
significantly reworked, making it roughly twice as fast in many
cases.  The <a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" title="xml.etree.ElementTree.ElementTree.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">ElementTree.write()</span></code></a>
and <code class="xref py py-meth docutils literal notranslate"><span class="pre">Element.write()</span></code> methods now have a <em>method</em> parameter that can be
“xml” (the default), “html”, or “text”.  HTML mode will output empty
elements as <code class="docutils literal notranslate"><span class="pre">&lt;empty&gt;&lt;/empty&gt;</span></code> instead of <code class="docutils literal notranslate"><span class="pre">&lt;empty/&gt;</span></code>, and text
mode will skip over elements and only output the text chunks.  If
you set the <code class="xref py py-attr docutils literal notranslate"><span class="pre">tag</span></code> attribute of an element to <code class="docutils literal notranslate"><span class="pre">None</span></code> but
leave its children in place, the element will be omitted when the
tree is written out, so you don’t need to do more extensive rearrangement
to remove a single element.</p>
<p>Namespace handling has also been improved.  All <code class="docutils literal notranslate"><span class="pre">xmlns:&lt;whatever&gt;</span></code>
declarations are now output on the root element, not scattered throughout
the resulting XML.  You can set the default namespace for a tree
by setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">default_namespace</span></code> attribute and can
register new prefixes with <a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace" title="xml.etree.ElementTree.register_namespace"><code class="xref py py-meth docutils literal notranslate"><span class="pre">register_namespace()</span></code></a>.  In XML mode,
you can use the true/false <em>xml_declaration</em> parameter to suppress the
XML declaration.</p>
</li>
<li><p class="first">New <a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.Element" title="xml.etree.ElementTree.Element"><code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code></a> method:
<a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.extend" title="xml.etree.ElementTree.Element.extend"><code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code></a> appends the items from a
sequence to the element’s children.  Elements themselves behave like
sequences, so it’s easy to move children from one element to
another:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">xml.etree</span> <span class="k">import</span> <span class="n">ElementTree</span> <span class="k">as</span> <span class="n">ET</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;list&gt;</span>
<span class="s2">  &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt;  &lt;item&gt;3&lt;/item&gt;</span>
<span class="s2">&lt;/list&gt;&quot;&quot;&quot;</span><span class="p">)</span>
<span class="n">new</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s1">&#39;&lt;root/&gt;&#39;</span><span class="p">)</span>
<span class="n">new</span><span class="o">.</span><span class="n">extend</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>

<span class="c1"># Outputs &lt;root&gt;&lt;item&gt;1&lt;/item&gt;...&lt;/root&gt;</span>
<span class="nb">print</span> <span class="n">ET</span><span class="o">.</span><span class="n">tostring</span><span class="p">(</span><span class="n">new</span><span class="p">)</span>
</pre></div>
</div>
</li>
<li><p class="first">New <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> method:
<a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter" title="xml.etree.ElementTree.Element.iter"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iter()</span></code></a> yields the children of the
element as a generator.  It’s also possible to write <code class="docutils literal notranslate"><span class="pre">for</span> <span class="pre">child</span> <span class="pre">in</span>
<span class="pre">elem:</span></code> to loop over an element’s children.  The existing method
<code class="xref py py-meth docutils literal notranslate"><span class="pre">getiterator()</span></code> is now deprecated, as is <code class="xref py py-meth docutils literal notranslate"><span class="pre">getchildren()</span></code>
which constructs and returns a list of children.</p>
</li>
<li><p class="first">New <code class="xref py py-class docutils literal notranslate"><span class="pre">Element</span></code> method:
<a class="reference internal" href="../library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext" title="xml.etree.ElementTree.Element.itertext"><code class="xref py py-meth docutils literal notranslate"><span class="pre">itertext()</span></code></a> yields all chunks of
text that are descendants of the element.  For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">t</span> <span class="o">=</span> <span class="n">ET</span><span class="o">.</span><span class="n">XML</span><span class="p">(</span><span class="s2">&quot;&quot;&quot;&lt;list&gt;</span>
<span class="s2">  &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt;  &lt;item&gt;3&lt;/item&gt;</span>
<span class="s2">&lt;/list&gt;&quot;&quot;&quot;</span><span class="p">)</span>

<span class="c1"># Outputs [&#39;\n  &#39;, &#39;1&#39;, &#39; &#39;, &#39;2&#39;, &#39;  &#39;, &#39;3&#39;, &#39;\n&#39;]</span>
<span class="nb">print</span> <span class="nb">list</span><span class="p">(</span><span class="n">t</span><span class="o">.</span><span class="n">itertext</span><span class="p">())</span>
</pre></div>
</div>
</li>
<li><p class="first">Deprecated: using an element as a Boolean (i.e., <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">elem:</span></code>) would
return true if the element had any children, or false if there were
no children.  This behaviour is confusing – <code class="docutils literal notranslate"><span class="pre">None</span></code> is false, but
so is a childless element? – so it will now trigger a
<a class="reference internal" href="../library/exceptions.html#exceptions.FutureWarning" title="exceptions.FutureWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">FutureWarning</span></code></a>.  In your code, you should be explicit: write
<code class="docutils literal notranslate"><span class="pre">len(elem)</span> <span class="pre">!=</span> <span class="pre">0</span></code> if you’re interested in the number of children,
or <code class="docutils literal notranslate"><span class="pre">elem</span> <span class="pre">is</span> <span class="pre">not</span> <span class="pre">None</span></code>.</p>
</li>
</ul>
<p>Fredrik Lundh develops ElementTree and produced the 1.3 version;
you can read his article describing 1.3 at
<a class="reference external" href="http://effbot.org/zone/elementtree-13-intro.htm">http://effbot.org/zone/elementtree-13-intro.htm</a>.
Florent Xicluna updated the version included with
Python, after discussions on python-dev and in <a class="reference external" href="https://bugs.python.org/issue6472">bpo-6472</a>.)</p>
</div>
</div>
<div class="section" id="build-and-c-api-changes">
<h2>Build and C API Changes<a class="headerlink" href="#build-and-c-api-changes" title="Permalink to this headline">¶</a></h2>
<p>Changes to Python’s build process and to the C API include:</p>
<ul>
<li><p class="first">The latest release of the GNU Debugger, GDB 7, can be <a class="reference external" href="https://sourceware.org/gdb/current/onlinedocs/gdb/Python.html">scripted
using Python</a>.
When you begin debugging an executable program P, GDB will look for
a file named <code class="docutils literal notranslate"><span class="pre">P-gdb.py</span></code> and automatically read it.  Dave Malcolm
contributed a <code class="file docutils literal notranslate"><span class="pre">python-gdb.py</span></code> that adds a number of
commands useful when debugging Python itself.  For example,
<code class="docutils literal notranslate"><span class="pre">py-up</span></code> and <code class="docutils literal notranslate"><span class="pre">py-down</span></code> go up or down one Python stack frame,
which usually corresponds to several C stack frames.  <code class="docutils literal notranslate"><span class="pre">py-print</span></code>
prints the value of a Python variable, and <code class="docutils literal notranslate"><span class="pre">py-bt</span></code> prints the
Python stack trace.  (Added as a result of <a class="reference external" href="https://bugs.python.org/issue8032">bpo-8032</a>.)</p>
</li>
<li><p class="first">If you use the <code class="file docutils literal notranslate"><span class="pre">.gdbinit</span></code> file provided with Python,
the “pyo” macro in the 2.7 version now works correctly when the thread being
debugged doesn’t hold the GIL; the macro now acquires it before printing.
(Contributed by Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue3632">bpo-3632</a>.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../c-api/init.html#c.Py_AddPendingCall" title="Py_AddPendingCall"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_AddPendingCall()</span></code></a> is now thread-safe, letting any
worker thread submit notifications to the main Python thread.  This
is particularly useful for asynchronous IO operations.
(Contributed by Kristján Valur Jónsson; <a class="reference external" href="https://bugs.python.org/issue4293">bpo-4293</a>.)</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../c-api/code.html#c.PyCode_NewEmpty" title="PyCode_NewEmpty"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCode_NewEmpty()</span></code></a> creates an empty code object;
only the filename, function name, and first line number are required.
This is useful for extension modules that are attempting to
construct a more useful traceback stack.  Previously such
extensions needed to call <a class="reference internal" href="../c-api/code.html#c.PyCode_New" title="PyCode_New"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCode_New()</span></code></a>, which had many
more arguments.  (Added by Jeffrey Yasskin.)</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NewExceptionWithDoc" title="PyErr_NewExceptionWithDoc"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewExceptionWithDoc()</span></code></a> creates a new
exception class, just as the existing <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_NewException" title="PyErr_NewException"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_NewException()</span></code></a> does,
but takes an extra <code class="docutils literal notranslate"><span class="pre">char</span> <span class="pre">*</span></code> argument containing the docstring for the
new exception class.  (Added by ‘lekma’ on the Python bug tracker;
<a class="reference external" href="https://bugs.python.org/issue7033">bpo-7033</a>.)</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../c-api/reflection.html#c.PyFrame_GetLineNumber" title="PyFrame_GetLineNumber"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyFrame_GetLineNumber()</span></code></a> takes a frame object
and returns the line number that the frame is currently executing.
Previously code would need to get the index of the bytecode
instruction currently executing, and then look up the line number
corresponding to that address.  (Added by Jeffrey Yasskin.)</p>
</li>
<li><p class="first">New functions: <a class="reference internal" href="../c-api/long.html#c.PyLong_AsLongAndOverflow" title="PyLong_AsLongAndOverflow"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_AsLongAndOverflow()</span></code></a> and
<a class="reference internal" href="../c-api/long.html#c.PyLong_AsLongLongAndOverflow" title="PyLong_AsLongLongAndOverflow"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyLong_AsLongLongAndOverflow()</span></code></a>  approximates a Python long
integer as a C <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span></code> or <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code>.
If the number is too large to fit into
the output type, an <em>overflow</em> flag is set and returned to the caller.
(Contributed by Case Van Horsen; <a class="reference external" href="https://bugs.python.org/issue7528">bpo-7528</a> and <a class="reference external" href="https://bugs.python.org/issue7767">bpo-7767</a>.)</p>
</li>
<li><p class="first">New function: stemming from the rewrite of string-to-float conversion,
a new <a class="reference internal" href="../c-api/conversion.html#c.PyOS_string_to_double" title="PyOS_string_to_double"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_string_to_double()</span></code></a> function was added.  The old
<a class="reference internal" href="../c-api/conversion.html#c.PyOS_ascii_strtod" title="PyOS_ascii_strtod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ascii_strtod()</span></code></a> and <a class="reference internal" href="../c-api/conversion.html#c.PyOS_ascii_atof" title="PyOS_ascii_atof"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ascii_atof()</span></code></a> functions
are now deprecated.</p>
</li>
<li><p class="first">New function: <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a> sets the value of
<code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> and can optionally update <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> to include the
directory containing the script named by <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> depending
on the value of an <em>updatepath</em> parameter.</p>
<p>This function was added to close a security hole for applications
that embed Python.  The old function, <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgv" title="PySys_SetArgv"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code></a>, would
always update <code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, and sometimes it would add the current
directory.  This meant that, if you ran an application embedding
Python in a directory controlled by someone else, attackers could
put a Trojan-horse module in the directory (say, a file named
<code class="file docutils literal notranslate"><span class="pre">os.py</span></code>) that your application would then import and run.</p>
<p>If you maintain a C/C++ application that embeds Python, check
whether you’re calling <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgv" title="PySys_SetArgv"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code></a> and carefully consider
whether the application should be using <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a>
with <em>updatepath</em> set to false.</p>
<p>Security issue reported as <a class="reference external" href="https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983">CVE-2008-5983</a>;
discussed in <a class="reference external" href="https://bugs.python.org/issue5753">bpo-5753</a>, and fixed by Antoine Pitrou.</p>
</li>
<li><p class="first">New macros: the Python header files now define the following macros:
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISALNUM</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISALPHA</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISDIGIT</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISLOWER</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISSPACE</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISUPPER</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_ISXDIGIT</span></code>,
<code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TOLOWER</span></code>, and <code class="xref c c-macro docutils literal notranslate"><span class="pre">Py_TOUPPER</span></code>.
All of these functions are analogous to the C
standard macros for classifying characters, but ignore the current
locale setting, because in
several places Python needs to analyze characters in a
locale-independent way.  (Added by Eric Smith;
<a class="reference external" href="https://bugs.python.org/issue5793">bpo-5793</a>.)</p>
</li>
<li><p class="first">Removed function: <code class="xref c c-macro docutils literal notranslate"><span class="pre">PyEval_CallObject</span></code> is now only available
as a macro.  A function version was being kept around to preserve
ABI linking compatibility, but that was in 1997; it can certainly be
deleted by now.  (Removed by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue8276">bpo-8276</a>.)</p>
</li>
<li><p class="first">New format codes: the <code class="xref c c-func docutils literal notranslate"><span class="pre">PyFormat_FromString()</span></code>,
<code class="xref c c-func docutils literal notranslate"><span class="pre">PyFormat_FromStringV()</span></code>, and <a class="reference internal" href="../c-api/exceptions.html#c.PyErr_Format" title="PyErr_Format"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyErr_Format()</span></code></a> functions now
accept <code class="docutils literal notranslate"><span class="pre">%lld</span></code> and <code class="docutils literal notranslate"><span class="pre">%llu</span></code> format codes for displaying
C’s <code class="xref c c-type docutils literal notranslate"><span class="pre">long</span> <span class="pre">long</span></code> types.
(Contributed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue7228">bpo-7228</a>.)</p>
</li>
<li><p class="first">The complicated interaction between threads and process forking has
been changed.  Previously, the child process created by
<a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a> might fail because the child is created with only a
single thread running, the thread performing the <a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a>.
If other threads were holding a lock, such as Python’s import lock,
when the fork was performed, the lock would still be marked as
“held” in the new process.  But in the child process nothing would
ever release the lock, since the other threads weren’t replicated,
and the child process would no longer be able to perform imports.</p>
<p>Python 2.7 acquires the import lock before performing an
<a class="reference internal" href="../library/os.html#os.fork" title="os.fork"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fork()</span></code></a>, and will also clean up any locks created using the
<a class="reference internal" href="../library/threading.html#module-threading" title="threading: Higher-level threading interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module.  C extension modules that have internal
locks, or that call <code class="xref c c-func docutils literal notranslate"><span class="pre">fork()</span></code> themselves, will not benefit
from this clean-up.</p>
<p>(Fixed by Thomas Wouters; <a class="reference external" href="https://bugs.python.org/issue1590864">bpo-1590864</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../c-api/init.html#c.Py_Finalize" title="Py_Finalize"><code class="xref c c-func docutils literal notranslate"><span class="pre">Py_Finalize()</span></code></a> function now calls the internal
<code class="xref py py-func docutils literal notranslate"><span class="pre">threading._shutdown()</span></code> function; this prevents some exceptions from
being raised when an interpreter shuts down.
(Patch by Adam Olsen; <a class="reference external" href="https://bugs.python.org/issue1722344">bpo-1722344</a>.)</p>
</li>
<li><p class="first">When using the <a class="reference internal" href="../c-api/structures.html#c.PyMemberDef" title="PyMemberDef"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyMemberDef</span></code></a> structure to define attributes
of a type, Python will no longer let you try to delete or set a
<code class="xref py py-const docutils literal notranslate"><span class="pre">T_STRING_INPLACE</span></code> attribute.</p>
</li>
<li><p class="first">Global symbols defined by the <a class="reference internal" href="../library/ctypes.html#module-ctypes" title="ctypes: A foreign function library for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ctypes</span></code></a> module are now prefixed
with <code class="docutils literal notranslate"><span class="pre">Py</span></code>, or with <code class="docutils literal notranslate"><span class="pre">_ctypes</span></code>.  (Implemented by Thomas
Heller; <a class="reference external" href="https://bugs.python.org/issue3102">bpo-3102</a>.)</p>
</li>
<li><p class="first">New configure option: the <code class="xref std std-option docutils literal notranslate"><span class="pre">--with-system-expat</span></code> switch allows
building the <code class="xref py py-mod docutils literal notranslate"><span class="pre">pyexpat</span></code> module to use the system Expat library.
(Contributed by Arfrever Frehtes Taifersar Arahesis; <a class="reference external" href="https://bugs.python.org/issue7609">bpo-7609</a>.)</p>
</li>
<li><p class="first">New configure option: the
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-valgrind</span></code> option will now disable the pymalloc
allocator, which is difficult for the Valgrind memory-error detector
to analyze correctly.
Valgrind will therefore be better at detecting memory leaks and
overruns. (Contributed by James Henstridge; <a class="reference external" href="https://bugs.python.org/issue2422">bpo-2422</a>.)</p>
</li>
<li><p class="first">New configure option: you can now supply an empty string to
<code class="xref std std-option docutils literal notranslate"><span class="pre">--with-dbmliborder=</span></code> in order to disable all of the various
DBM modules.  (Added by Arfrever Frehtes Taifersar Arahesis;
<a class="reference external" href="https://bugs.python.org/issue6491">bpo-6491</a>.)</p>
</li>
<li><p class="first">The <strong class="program">configure</strong> script now checks for floating-point rounding bugs
on certain 32-bit Intel chips and defines a <code class="xref c c-macro docutils literal notranslate"><span class="pre">X87_DOUBLE_ROUNDING</span></code>
preprocessor definition.  No code currently uses this definition,
but it’s available if anyone wishes to use it.
(Added by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue2937">bpo-2937</a>.)</p>
<p><strong class="program">configure</strong> also now sets a <span class="target" id="index-12"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">LDCXXSHARED</span></code> Makefile
variable for supporting C++ linking.  (Contributed by Arfrever
Frehtes Taifersar Arahesis; <a class="reference external" href="https://bugs.python.org/issue1222585">bpo-1222585</a>.)</p>
</li>
<li><p class="first">The build process now creates the necessary files for pkg-config
support.  (Contributed by Clinton Roy; <a class="reference external" href="https://bugs.python.org/issue3585">bpo-3585</a>.)</p>
</li>
<li><p class="first">The build process now supports Subversion 1.7.  (Contributed by
Arfrever Frehtes Taifersar Arahesis; <a class="reference external" href="https://bugs.python.org/issue6094">bpo-6094</a>.)</p>
</li>
</ul>
<div class="section" id="capsules">
<span id="whatsnew27-capsules"></span><h3>Capsules<a class="headerlink" href="#capsules" title="Permalink to this headline">¶</a></h3>
<p>Python 3.1 adds a new C datatype, <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule" title="PyCapsule"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCapsule</span></code></a>, for providing a
C API to an extension module.  A capsule is essentially the holder of
a C <code class="docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> pointer, and is made available as a module attribute; for
example, the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a> module’s API is exposed as <code class="docutils literal notranslate"><span class="pre">socket.CAPI</span></code>,
and <a class="reference internal" href="../library/unicodedata.html#module-unicodedata" title="unicodedata: Access the Unicode Database."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unicodedata</span></code></a> exposes <code class="docutils literal notranslate"><span class="pre">ucnhash_CAPI</span></code>.  Other extensions
can import the module, access its dictionary to get the capsule
object, and then get the <code class="docutils literal notranslate"><span class="pre">void</span> <span class="pre">*</span></code> pointer, which will usually point
to an array of pointers to the module’s various API functions.</p>
<p>There is an existing data type already used for this,
<a class="reference internal" href="../c-api/cobject.html#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a>, but it doesn’t provide type safety.  Evil code
written in pure Python could cause a segmentation fault by taking a
<a class="reference internal" href="../c-api/cobject.html#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> from module A and somehow substituting it for the
<a class="reference internal" href="../c-api/cobject.html#c.PyCObject" title="PyCObject"><code class="xref c c-type docutils literal notranslate"><span class="pre">PyCObject</span></code></a> in module B.   Capsules know their own name,
and getting the pointer requires providing the name:</p>
<div class="highlight-c notranslate"><div class="highlight"><pre><span></span><span class="kt">void</span> <span class="o">*</span><span class="n">vtable</span><span class="p">;</span>

<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">PyCapsule_IsValid</span><span class="p">(</span><span class="n">capsule</span><span class="p">,</span> <span class="s">&quot;mymodule.CAPI&quot;</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">PyErr_SetString</span><span class="p">(</span><span class="n">PyExc_ValueError</span><span class="p">,</span> <span class="s">&quot;argument type invalid&quot;</span><span class="p">);</span>
        <span class="k">return</span> <span class="nb">NULL</span><span class="p">;</span>
<span class="p">}</span>

<span class="n">vtable</span> <span class="o">=</span> <span class="n">PyCapsule_GetPointer</span><span class="p">(</span><span class="n">capsule</span><span class="p">,</span> <span class="s">&quot;mymodule.CAPI&quot;</span><span class="p">);</span>
</pre></div>
</div>
<p>You are assured that <code class="docutils literal notranslate"><span class="pre">vtable</span></code> points to whatever you’re expecting.
If a different capsule was passed in, <a class="reference internal" href="../c-api/capsule.html#c.PyCapsule_IsValid" title="PyCapsule_IsValid"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCapsule_IsValid()</span></code></a> would
detect the mismatched name and return false.  Refer to
<a class="reference internal" href="../extending/extending.html#using-capsules"><span class="std std-ref">Providing a C API for an Extension Module</span></a> for more information on using these objects.</p>
<p>Python 2.7 now uses capsules internally to provide various
extension-module APIs, but the <a class="reference internal" href="../c-api/cobject.html#c.PyCObject_AsVoidPtr" title="PyCObject_AsVoidPtr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCObject_AsVoidPtr()</span></code></a> was
modified to handle capsules, preserving compile-time compatibility
with the <code class="xref c c-type docutils literal notranslate"><span class="pre">CObject</span></code> interface.  Use of
<a class="reference internal" href="../c-api/cobject.html#c.PyCObject_AsVoidPtr" title="PyCObject_AsVoidPtr"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyCObject_AsVoidPtr()</span></code></a> will signal a
<a class="reference internal" href="../library/exceptions.html#exceptions.PendingDeprecationWarning" title="exceptions.PendingDeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PendingDeprecationWarning</span></code></a>, which is silent by default.</p>
<p>Implemented in Python 3.1 and backported to 2.7 by Larry Hastings;
discussed in <a class="reference external" href="https://bugs.python.org/issue5630">bpo-5630</a>.</p>
</div>
<div class="section" id="port-specific-changes-windows">
<h3>Port-Specific Changes: Windows<a class="headerlink" href="#port-specific-changes-windows" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>The <a class="reference internal" href="../library/msvcrt.html#module-msvcrt" title="msvcrt: Miscellaneous useful routines from the MS VC++ runtime. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">msvcrt</span></code></a> module now contains some constants from
the <code class="file docutils literal notranslate"><span class="pre">crtassem.h</span></code> header file:
<code class="xref py py-data docutils literal notranslate"><span class="pre">CRT_ASSEMBLY_VERSION</span></code>,
<code class="xref py py-data docutils literal notranslate"><span class="pre">VC_ASSEMBLY_PUBLICKEYTOKEN</span></code>,
and <code class="xref py py-data docutils literal notranslate"><span class="pre">LIBRARIES_ASSEMBLY_NAME_PREFIX</span></code>.
(Contributed by David Cournapeau; <a class="reference external" href="https://bugs.python.org/issue4365">bpo-4365</a>.)</li>
<li>The <a class="reference internal" href="../library/_winreg.html#module-_winreg" title="_winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">_winreg</span></code></a> module for accessing the registry now implements
the <a class="reference internal" href="../library/_winreg.html#_winreg.CreateKeyEx" title="_winreg.CreateKeyEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">CreateKeyEx()</span></code></a> and <a class="reference internal" href="../library/_winreg.html#_winreg.DeleteKeyEx" title="_winreg.DeleteKeyEx"><code class="xref py py-func docutils literal notranslate"><span class="pre">DeleteKeyEx()</span></code></a>
functions, extended versions of previously-supported functions that
take several extra arguments.  The <a class="reference internal" href="../library/_winreg.html#_winreg.DisableReflectionKey" title="_winreg.DisableReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">DisableReflectionKey()</span></code></a>,
<a class="reference internal" href="../library/_winreg.html#_winreg.EnableReflectionKey" title="_winreg.EnableReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">EnableReflectionKey()</span></code></a>, and <a class="reference internal" href="../library/_winreg.html#_winreg.QueryReflectionKey" title="_winreg.QueryReflectionKey"><code class="xref py py-func docutils literal notranslate"><span class="pre">QueryReflectionKey()</span></code></a>
were also tested and documented.
(Implemented by Brian Curtin: <a class="reference external" href="https://bugs.python.org/issue7347">bpo-7347</a>.)</li>
<li>The new <code class="xref c c-func docutils literal notranslate"><span class="pre">_beginthreadex()</span></code> API is used to start threads, and
the native thread-local storage functions are now used.
(Contributed by Kristján Valur Jónsson; <a class="reference external" href="https://bugs.python.org/issue3582">bpo-3582</a>.)</li>
<li>The <a class="reference internal" href="../library/os.html#os.kill" title="os.kill"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.kill()</span></code></a> function now works on Windows.  The signal value
can be the constants <code class="xref py py-const docutils literal notranslate"><span class="pre">CTRL_C_EVENT</span></code>,
<code class="xref py py-const docutils literal notranslate"><span class="pre">CTRL_BREAK_EVENT</span></code>, or any integer.  The first two constants
will send <kbd class="kbd docutils literal notranslate">Control-C</kbd> and <kbd class="kbd docutils literal notranslate">Control-Break</kbd> keystroke events to
subprocesses; any other value will use the <code class="xref c c-func docutils literal notranslate"><span class="pre">TerminateProcess()</span></code>
API.  (Contributed by Miki Tebeka; <a class="reference external" href="https://bugs.python.org/issue1220212">bpo-1220212</a>.)</li>
<li>The <a class="reference internal" href="../library/os.html#os.listdir" title="os.listdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.listdir()</span></code></a> function now correctly fails
for an empty path.  (Fixed by Hirokazu Yamamoto; <a class="reference external" href="https://bugs.python.org/issue5913">bpo-5913</a>.)</li>
<li>The <code class="xref py py-mod docutils literal notranslate"><span class="pre">mimelib</span></code> module will now read the MIME database from
the Windows registry when initializing.
(Patch by Gabriel Genellina; <a class="reference external" href="https://bugs.python.org/issue4969">bpo-4969</a>.)</li>
</ul>
</div>
<div class="section" id="port-specific-changes-mac-os-x">
<h3>Port-Specific Changes: Mac OS X<a class="headerlink" href="#port-specific-changes-mac-os-x" title="Permalink to this headline">¶</a></h3>
<ul>
<li><p class="first">The path <code class="docutils literal notranslate"><span class="pre">/Library/Python/2.7/site-packages</span></code> is now appended to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code>, in order to share added packages between the system
installation and a user-installed copy of the same version.
(Changed by Ronald Oussoren; <a class="reference external" href="https://bugs.python.org/issue4865">bpo-4865</a>.)</p>
<blockquote>
<div><div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.13: </span>As of 2.7.13, this change was removed.
<code class="docutils literal notranslate"><span class="pre">/Library/Python/2.7/site-packages</span></code>, the site-packages directory
used by the Apple-supplied system Python 2.7 is no longer appended to
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> for user-installed Pythons such as from the python.org
installers.  As of macOS 10.12, Apple changed how the system
site-packages directory is configured, which could cause installation
of pip components, like setuptools, to fail.  Packages installed for
the system Python will no longer be shared with user-installed
Pythons. (<a class="reference external" href="https://bugs.python.org/issue28440">bpo-28440</a>)</p>
</div>
</div></blockquote>
</li>
</ul>
</div>
<div class="section" id="port-specific-changes-freebsd">
<h3>Port-Specific Changes: FreeBSD<a class="headerlink" href="#port-specific-changes-freebsd" title="Permalink to this headline">¶</a></h3>
<ul class="simple">
<li>FreeBSD 7.1’s <code class="xref py py-const docutils literal notranslate"><span class="pre">SO_SETFIB</span></code> constant, used with
<code class="xref py py-func docutils literal notranslate"><span class="pre">getsockopt()</span></code>/<code class="xref py py-func docutils literal notranslate"><span class="pre">setsockopt()</span></code> to select an
alternate routing table, is now available in the <a class="reference internal" href="../library/socket.html#module-socket" title="socket: Low-level networking interface."><code class="xref py py-mod docutils literal notranslate"><span class="pre">socket</span></code></a>
module.  (Added by Kyle VanderBeek; <a class="reference external" href="https://bugs.python.org/issue8235">bpo-8235</a>.)</li>
</ul>
</div>
</div>
<div class="section" id="other-changes-and-fixes">
<h2>Other Changes and Fixes<a class="headerlink" href="#other-changes-and-fixes" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li>Two benchmark scripts, <code class="file docutils literal notranslate"><span class="pre">iobench</span></code> and <code class="file docutils literal notranslate"><span class="pre">ccbench</span></code>, were
added to the <code class="file docutils literal notranslate"><span class="pre">Tools</span></code> directory.  <code class="file docutils literal notranslate"><span class="pre">iobench</span></code> measures the
speed of the built-in file I/O objects returned by <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>
while performing various operations, and <code class="file docutils literal notranslate"><span class="pre">ccbench</span></code> is a
concurrency benchmark that tries to measure computing throughput,
thread switching latency, and IO processing bandwidth when
performing several tasks using a varying number of threads.</li>
<li>The <code class="file docutils literal notranslate"><span class="pre">Tools/i18n/msgfmt.py</span></code> script now understands plural
forms in <code class="file docutils literal notranslate"><span class="pre">.po</span></code> files.  (Fixed by Martin von Löwis;
<a class="reference external" href="https://bugs.python.org/issue5464">bpo-5464</a>.)</li>
<li>When importing a module from a <code class="file docutils literal notranslate"><span class="pre">.pyc</span></code> or <code class="file docutils literal notranslate"><span class="pre">.pyo</span></code> file
with an existing <code class="file docutils literal notranslate"><span class="pre">.py</span></code> counterpart, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">co_filename</span></code>
attributes of the resulting code objects are overwritten when the
original filename is obsolete.  This can happen if the file has been
renamed, moved, or is accessed through different paths.  (Patch by
Ziga Seilnacht and Jean-Paul Calderone; <a class="reference external" href="https://bugs.python.org/issue1180193">bpo-1180193</a>.)</li>
<li>The <code class="file docutils literal notranslate"><span class="pre">regrtest.py</span></code> script now takes a <code class="xref std std-option docutils literal notranslate"><span class="pre">--randseed=</span></code>
switch that takes an integer that will be used as the random seed
for the <code class="xref std std-option docutils literal notranslate"><span class="pre">-r</span></code> option that executes tests in random order.
The <code class="xref std std-option docutils literal notranslate"><span class="pre">-r</span></code> option also reports the seed that was used
(Added by Collin Winter.)</li>
<li>Another <code class="file docutils literal notranslate"><span class="pre">regrtest.py</span></code> switch is <code class="xref std std-option docutils literal notranslate"><span class="pre">-j</span></code>, which
takes an integer specifying how many tests run in parallel. This
allows reducing the total runtime on multi-core machines.
This option is compatible with several other options, including the
<code class="xref std std-option docutils literal notranslate"><span class="pre">-R</span></code> switch which is known to produce long runtimes.
(Added by Antoine Pitrou, <a class="reference external" href="https://bugs.python.org/issue6152">bpo-6152</a>.)  This can also be used
with a new <code class="xref std std-option docutils literal notranslate"><span class="pre">-F</span></code> switch that runs selected tests in a loop
until they fail.  (Added by Antoine Pitrou; <a class="reference external" href="https://bugs.python.org/issue7312">bpo-7312</a>.)</li>
<li>When executed as a script, the <code class="file docutils literal notranslate"><span class="pre">py_compile.py</span></code> module now
accepts <code class="docutils literal notranslate"><span class="pre">'-'</span></code> as an argument, which will read standard input for
the list of filenames to be compiled.  (Contributed by Piotr
Ożarowski; <a class="reference external" href="https://bugs.python.org/issue8233">bpo-8233</a>.)</li>
</ul>
</div>
<div class="section" id="porting-to-python-2-7">
<h2>Porting to Python 2.7<a class="headerlink" href="#porting-to-python-2-7" title="Permalink to this headline">¶</a></h2>
<p>This section lists previously described changes and other bugfixes
that may require changes to your code:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../library/functions.html#range" title="range"><code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code></a> function processes its arguments more
consistently; it will now call <a class="reference internal" href="../reference/datamodel.html#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> on non-float,
non-integer arguments that are supplied to it.  (Fixed by Alexander
Belopolsky; <a class="reference external" href="https://bugs.python.org/issue1533">bpo-1533</a>.)</li>
<li>The string <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> method changed the default precision used
for floating-point and complex numbers from 6 decimal
places to 12, which matches the precision used by <a class="reference internal" href="../library/functions.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>.
(Changed by Eric Smith; <a class="reference external" href="https://bugs.python.org/issue5920">bpo-5920</a>.)</li>
<li>Because of an optimization for the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, the special
methods <a class="reference internal" href="../reference/datamodel.html#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a> and <a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> must belong to the object’s
type, and cannot be directly attached to the object’s instance.  This
affects new-style classes (derived from <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a>) and C extension
types.  (<a class="reference external" href="https://bugs.python.org/issue6101">bpo-6101</a>.)</li>
<li>Due to a bug in Python 2.6, the <em>exc_value</em> parameter to
<a class="reference internal" href="../reference/datamodel.html#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods was often the string representation of the
exception, not an instance.  This was fixed in 2.7, so <em>exc_value</em>
will be an instance as expected.  (Fixed by Florent Xicluna;
<a class="reference external" href="https://bugs.python.org/issue7853">bpo-7853</a>.)</li>
<li>When a restricted set of attributes were set using <code class="docutils literal notranslate"><span class="pre">__slots__</span></code>,
deleting an unset attribute would not raise <a class="reference internal" href="../library/exceptions.html#exceptions.AttributeError" title="exceptions.AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>
as you would expect.  Fixed by Benjamin Peterson; <a class="reference external" href="https://bugs.python.org/issue7604">bpo-7604</a>.)</li>
</ul>
<p>In the standard library:</p>
<ul>
<li><p class="first">Operations with <a class="reference internal" href="../library/datetime.html#datetime.datetime" title="datetime.datetime"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a> instances that resulted in a year
falling outside the supported range didn’t always raise
<a class="reference internal" href="../library/exceptions.html#exceptions.OverflowError" title="exceptions.OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>.  Such errors are now checked more carefully
and will now raise the exception. (Reported by Mark Leander, patch
by Anand B. Pillai and Alexander Belopolsky; <a class="reference external" href="https://bugs.python.org/issue7150">bpo-7150</a>.)</p>
</li>
<li><p class="first">When using <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> instances with a string’s
<a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">format()</span></code></a> method, the default alignment was previously
left-alignment.  This has been changed to right-alignment, which might
change the output of your programs.
(Changed by Mark Dickinson; <a class="reference external" href="https://bugs.python.org/issue6857">bpo-6857</a>.)</p>
<p>Comparisons involving a signaling NaN value (or <code class="docutils literal notranslate"><span class="pre">sNAN</span></code>) now signal
<a class="reference internal" href="../library/decimal.html#decimal.InvalidOperation" title="decimal.InvalidOperation"><code class="xref py py-const docutils literal notranslate"><span class="pre">InvalidOperation</span></code></a> instead of silently returning a true or
false value depending on the comparison operator.  Quiet NaN values
(or <code class="docutils literal notranslate"><span class="pre">NaN</span></code>) are now hashable.  (Fixed by Mark Dickinson;
<a class="reference external" href="https://bugs.python.org/issue7279">bpo-7279</a>.)</p>
</li>
<li><p class="first">The ElementTree library, <code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree</span></code>, no longer escapes
ampersands and angle brackets when outputting an XML processing
instruction (which looks like <cite>&lt;?xml-stylesheet href=”#style1”?&gt;</cite>)
or comment (which looks like <cite>&lt;!– comment –&gt;</cite>).
(Patch by Neil Muller; <a class="reference external" href="https://bugs.python.org/issue2746">bpo-2746</a>.)</p>
</li>
<li><p class="first">The <code class="xref py py-meth docutils literal notranslate"><span class="pre">readline()</span></code> method of <a class="reference internal" href="../library/stringio.html#StringIO.StringIO" title="StringIO.StringIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">StringIO</span></code></a> objects now does
nothing when a negative length is requested, as other file-like
objects do.  (<a class="reference external" href="https://bugs.python.org/issue7348">bpo-7348</a>).</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/syslog.html#module-syslog" title="syslog: An interface to the Unix syslog library routines. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">syslog</span></code></a> module will now use the value of <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> as the
identifier instead of the previous default value of <code class="docutils literal notranslate"><span class="pre">'python'</span></code>.
(Changed by Sean Reifschneider; <a class="reference external" href="https://bugs.python.org/issue8451">bpo-8451</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a> module’s default error handling has changed, to
no longer suppress fatal errors.  The default error level was previously 0,
which meant that errors would only result in a message being written to the
debug log, but because the debug log is not activated by default,
these errors go unnoticed.  The default error level is now 1,
which raises an exception if there’s an error.
(Changed by Lars Gustäbel; <a class="reference external" href="https://bugs.python.org/issue7357">bpo-7357</a>.)</p>
</li>
<li><p class="first">The <a class="reference internal" href="../library/urlparse.html#module-urlparse" title="urlparse: Parse URLs into or assemble them from components."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urlparse</span></code></a> module’s <a class="reference internal" href="../library/urlparse.html#urlparse.urlsplit" title="urlparse.urlsplit"><code class="xref py py-func docutils literal notranslate"><span class="pre">urlsplit()</span></code></a> now handles
unknown URL schemes in a fashion compliant with <span class="target" id="index-13"></span><a class="rfc reference external" href="https://tools.ietf.org/html/rfc3986.html"><strong>RFC 3986</strong></a>: if the
URL is of the form <code class="docutils literal notranslate"><span class="pre">&quot;&lt;something&gt;://...&quot;</span></code>, the text before the
<code class="docutils literal notranslate"><span class="pre">://</span></code> is treated as the scheme, even if it’s a made-up scheme that
the module doesn’t know about.  This change may break code that
worked around the old behaviour.  For example, Python 2.6.4 or 2.5
will return the following:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="s1">&#39;invented://host/filename?query&#39;</span><span class="p">)</span>
<span class="go">(&#39;invented&#39;, &#39;&#39;, &#39;//host/filename?query&#39;, &#39;&#39;, &#39;&#39;)</span>
</pre></div>
</div>
<p>Python 2.7 (and Python 2.6.5) will return:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">urlparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">urlparse</span><span class="o">.</span><span class="n">urlsplit</span><span class="p">(</span><span class="s1">&#39;invented://host/filename?query&#39;</span><span class="p">)</span>
<span class="go">(&#39;invented&#39;, &#39;host&#39;, &#39;/filename?query&#39;, &#39;&#39;, &#39;&#39;)</span>
</pre></div>
</div>
<p>(Python 2.7 actually produces slightly different output, since it
returns a named tuple instead of a standard tuple.)</p>
</li>
</ul>
<p>For C extensions:</p>
<ul class="simple">
<li>C extensions that use integer format codes with the <code class="docutils literal notranslate"><span class="pre">PyArg_Parse*</span></code>
family of functions will now raise a <a class="reference internal" href="../library/exceptions.html#exceptions.TypeError" title="exceptions.TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> exception
instead of triggering a <a class="reference internal" href="../library/exceptions.html#exceptions.DeprecationWarning" title="exceptions.DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> (<a class="reference external" href="https://bugs.python.org/issue5080">bpo-5080</a>).</li>
<li>Use the new <a class="reference internal" href="../c-api/conversion.html#c.PyOS_string_to_double" title="PyOS_string_to_double"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_string_to_double()</span></code></a> function instead of the old
<a class="reference internal" href="../c-api/conversion.html#c.PyOS_ascii_strtod" title="PyOS_ascii_strtod"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ascii_strtod()</span></code></a> and <a class="reference internal" href="../c-api/conversion.html#c.PyOS_ascii_atof" title="PyOS_ascii_atof"><code class="xref c c-func docutils literal notranslate"><span class="pre">PyOS_ascii_atof()</span></code></a> functions,
which are now deprecated.</li>
</ul>
<p>For applications that embed Python:</p>
<ul class="simple">
<li>The <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a> function was added, letting
applications close a security hole when the existing
<a class="reference internal" href="../c-api/init.html#c.PySys_SetArgv" title="PySys_SetArgv"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code></a> function was used.  Check whether you’re
calling <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgv" title="PySys_SetArgv"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgv()</span></code></a> and carefully consider whether the
application should be using <a class="reference internal" href="../c-api/init.html#c.PySys_SetArgvEx" title="PySys_SetArgvEx"><code class="xref c c-func docutils literal notranslate"><span class="pre">PySys_SetArgvEx()</span></code></a> with
<em>updatepath</em> set to false.</li>
</ul>
</div>
<div class="section" id="new-features-added-to-python-2-7-maintenance-releases">
<span id="py27-maintenance-enhancements"></span><h2>New Features Added to Python 2.7 Maintenance Releases<a class="headerlink" href="#new-features-added-to-python-2-7-maintenance-releases" title="Permalink to this headline">¶</a></h2>
<p>New features may be added to Python 2.7 maintenance releases when the
situation genuinely calls for it. Any such additions must go through
the Python Enhancement Proposal process, and make a compelling case for why
they can’t be adequately addressed by either adding the new feature solely to
Python 3, or else by publishing it on the Python Package Index.</p>
<p>In addition to the specific proposals listed below, there is a general
exemption allowing new <code class="docutils literal notranslate"><span class="pre">-3</span></code> warnings to be added in any Python 2.7
maintenance release.</p>
<div class="section" id="two-new-environment-variables-for-debug-mode">
<h3>Two new environment variables for debug mode<a class="headerlink" href="#two-new-environment-variables-for-debug-mode" title="Permalink to this headline">¶</a></h3>
<p>In debug mode, the <code class="docutils literal notranslate"><span class="pre">[xxx</span> <span class="pre">refs]</span></code> statistic is not written by default, the
<span class="target" id="index-14"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSHOWREFCOUNT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSHOWREFCOUNT</span></code></a> environment variable now must also be set.
(Contributed by Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue31733">bpo-31733</a>.)</p>
<p>When Python is compiled with <code class="docutils literal notranslate"><span class="pre">COUNT_ALLOC</span></code> defined, allocation counts are no
longer dumped by default anymore: the <span class="target" id="index-15"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSHOWALLOCCOUNT"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSHOWALLOCCOUNT</span></code></a> environment
variable must now also be set. Moreover, allocation counts are now dumped into
stderr, rather than stdout. (Contributed by Victor Stinner; <a class="reference external" href="https://bugs.python.org/issue31692">bpo-31692</a>.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.15.</span></p>
</div>
</div>
<div class="section" id="pep-434-idle-enhancement-exception-for-all-branches">
<h3>PEP 434: IDLE Enhancement Exception for All Branches<a class="headerlink" href="#pep-434-idle-enhancement-exception-for-all-branches" title="Permalink to this headline">¶</a></h3>
<p><span class="target" id="index-16"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0434"><strong>PEP 434</strong></a> describes a general exemption for changes made to the IDLE
development environment shipped along with Python. This exemption makes it
possible for the IDLE developers to provide a more consistent user
experience across all supported versions of Python 2 and 3.</p>
<p>For details of any IDLE changes, refer to the NEWS file for the specific
release.</p>
</div>
<div class="section" id="pep-466-network-security-enhancements-for-python-2-7">
<h3>PEP 466: Network Security Enhancements for Python 2.7<a class="headerlink" href="#pep-466-network-security-enhancements-for-python-2-7" title="Permalink to this headline">¶</a></h3>
<p><span class="target" id="index-17"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0466"><strong>PEP 466</strong></a> describes a number of network security enhancement proposals
that have been approved for inclusion in Python 2.7 maintenance releases,
with the first of those changes appearing in the Python 2.7.7 release.</p>
<p><span class="target" id="index-18"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0466"><strong>PEP 466</strong></a> related features added in Python 2.7.7:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/hmac.html#hmac.compare_digest" title="hmac.compare_digest"><code class="xref py py-func docutils literal notranslate"><span class="pre">hmac.compare_digest()</span></code></a> was backported from Python 3 to make a timing
attack resistant comparison operation available to Python 2 applications.
(Contributed by Alex Gaynor; <a class="reference external" href="https://bugs.python.org/issue21306">bpo-21306</a>.)</li>
<li>OpenSSL 1.0.1g was upgraded in the official Windows installers published on
python.org. (Contributed by Zachary Ware; <a class="reference external" href="https://bugs.python.org/issue21462">bpo-21462</a>.)</li>
</ul>
<p><span class="target" id="index-19"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0466"><strong>PEP 466</strong></a> related features added in Python 2.7.8:</p>
<ul class="simple">
<li><a class="reference internal" href="../library/hashlib.html#hashlib.pbkdf2_hmac" title="hashlib.pbkdf2_hmac"><code class="xref py py-func docutils literal notranslate"><span class="pre">hashlib.pbkdf2_hmac()</span></code></a> was backported from Python 3 to make a hashing
algorithm suitable for secure password storage broadly available to Python
2 applications. (Contributed by Alex Gaynor; <a class="reference external" href="https://bugs.python.org/issue21304">bpo-21304</a>.)</li>
<li>OpenSSL 1.0.1h was upgraded for the official Windows installers published on
python.org. (contributed by Zachary Ware in <a class="reference external" href="https://bugs.python.org/issue21671">bpo-21671</a> for CVE-2014-0224)</li>
</ul>
<p><span class="target" id="index-20"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0466"><strong>PEP 466</strong></a> related features added in Python 2.7.9:</p>
<ul>
<li><p class="first">Most of Python 3.4’s <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a> module was backported. This means <a class="reference internal" href="../library/ssl.html#module-ssl" title="ssl: TLS/SSL wrapper for socket objects"><code class="xref py py-mod docutils literal notranslate"><span class="pre">ssl</span></code></a>
now supports Server Name Indication, TLS1.x settings, access to the platform
certificate store, the <a class="reference internal" href="../library/ssl.html#ssl.SSLContext" title="ssl.SSLContext"><code class="xref py py-class docutils literal notranslate"><span class="pre">SSLContext</span></code></a> class, and other
features. (Contributed by Alex Gaynor and David Reid; <a class="reference external" href="https://bugs.python.org/issue21308">bpo-21308</a>.)</p>
<p>Refer to the “Version added: 2.7.9” notes in the module documentation for
specific details.</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/os.html#os.urandom" title="os.urandom"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.urandom()</span></code></a> was changed to cache a file descriptor to <code class="docutils literal notranslate"><span class="pre">/dev/urandom</span></code>
instead of reopening <code class="docutils literal notranslate"><span class="pre">/dev/urandom</span></code> on every call. (Contributed by Alex
Gaynor; <a class="reference external" href="https://bugs.python.org/issue21305">bpo-21305</a>.)</p>
</li>
<li><p class="first"><a class="reference internal" href="../library/hashlib.html#hashlib.algorithms_guaranteed" title="hashlib.algorithms_guaranteed"><code class="xref py py-data docutils literal notranslate"><span class="pre">hashlib.algorithms_guaranteed</span></code></a> and
<a class="reference internal" href="../library/hashlib.html#hashlib.algorithms_available" title="hashlib.algorithms_available"><code class="xref py py-data docutils literal notranslate"><span class="pre">hashlib.algorithms_available</span></code></a> were backported from Python 3 to make
it easier for Python 2 applications to select the strongest available hash
algorithm. (Contributed by Alex Gaynor in <a class="reference external" href="https://bugs.python.org/issue21307">bpo-21307</a>)</p>
</li>
</ul>
</div>
<div class="section" id="pep-477-backport-ensurepip-pep-453-to-python-2-7">
<h3>PEP 477: Backport ensurepip (PEP 453) to Python 2.7<a class="headerlink" href="#pep-477-backport-ensurepip-pep-453-to-python-2-7" title="Permalink to this headline">¶</a></h3>
<p><span class="target" id="index-21"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0477"><strong>PEP 477</strong></a> approves the inclusion of the <span class="target" id="index-22"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0453"><strong>PEP 453</strong></a> ensurepip module and the
improved documentation that was enabled by it in the Python 2.7 maintenance
releases, appearing first in the Python 2.7.9 release.</p>
<div class="section" id="bootstrapping-pip-by-default">
<h4>Bootstrapping pip By Default<a class="headerlink" href="#bootstrapping-pip-by-default" title="Permalink to this headline">¶</a></h4>
<p>The new <a class="reference internal" href="../library/ensurepip.html#module-ensurepip" title="ensurepip: Bootstrapping the ``pip`` installer into an existing Python installation or virtual environment."><code class="xref py py-mod docutils literal notranslate"><span class="pre">ensurepip</span></code></a> module (defined in <span class="target" id="index-23"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0453"><strong>PEP 453</strong></a>) provides a standard
cross-platform mechanism to bootstrap the pip installer into Python
installations. The version of <code class="docutils literal notranslate"><span class="pre">pip</span></code> included with Python 2.7.9 is <code class="docutils literal notranslate"><span class="pre">pip</span></code>
1.5.6, and future 2.7.x maintenance releases will update the bundled version to
the latest version of <code class="docutils literal notranslate"><span class="pre">pip</span></code> that is available at the time of creating the
release candidate.</p>
<p>By default, the commands <code class="docutils literal notranslate"><span class="pre">pip</span></code>, <code class="docutils literal notranslate"><span class="pre">pipX</span></code> and <code class="docutils literal notranslate"><span class="pre">pipX.Y</span></code> will be installed on
all platforms (where X.Y stands for the version of the Python installation),
along with the <code class="docutils literal notranslate"><span class="pre">pip</span></code> Python package and its dependencies.</p>
<p>For CPython <a class="reference internal" href="../using/unix.html#building-python-on-unix"><span class="std std-ref">source builds on POSIX systems</span></a>,
the <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">install</span></code> and <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">altinstall</span></code> commands do not bootstrap <code class="docutils literal notranslate"><span class="pre">pip</span></code>
by default.  This behaviour can be controlled through configure options, and
overridden through Makefile options.</p>
<p>On Windows and Mac OS X, the CPython installers now default to installing
<code class="docutils literal notranslate"><span class="pre">pip</span></code> along with CPython itself (users may opt out of installing it
during the installation process). Window users will need to opt in to the
automatic <code class="docutils literal notranslate"><span class="pre">PATH</span></code> modifications to have <code class="docutils literal notranslate"><span class="pre">pip</span></code> available from the command
line by default, otherwise it can still be accessed through the Python
launcher for Windows as <code class="docutils literal notranslate"><span class="pre">py</span> <span class="pre">-m</span> <span class="pre">pip</span></code>.</p>
<p>As <a class="reference external" href="https://www.python.org/dev/peps/pep-0477/#disabling-ensurepip-by-downstream-distributors">discussed in the PEP</a>, platform packagers may choose not to install
these commands by default, as long as, when invoked, they provide clear and
simple directions on how to install them on that platform (usually using
the system package manager).</p>
</div>
<div class="section" id="documentation-changes">
<h4>Documentation Changes<a class="headerlink" href="#documentation-changes" title="Permalink to this headline">¶</a></h4>
<p>As part of this change, the <a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a> and
<a class="reference internal" href="../distributing/index.html#distributing-index"><span class="std std-ref">Distributing Python Modules</span></a> sections of the documentation have been
completely redesigned as short getting started and FAQ documents. Most
packaging documentation has now been moved out to the Python Packaging
Authority maintained <a class="reference external" href="http://packaging.python.org">Python Packaging User Guide</a> and the documentation of the individual
projects.</p>
<p>However, as this migration is currently still incomplete, the legacy
versions of those guides remaining available as <a class="reference internal" href="../install/index.html#install-index"><span class="std std-ref">Installing Python Modules (Legacy version)</span></a>
and <a class="reference internal" href="../distutils/index.html#distutils-index"><span class="std std-ref">Distributing Python Modules (Legacy version)</span></a>.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><span class="target" id="index-24"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0453"><strong>PEP 453</strong></a> – Explicit bootstrapping of pip in Python installations</dt>
<dd>PEP written by Donald Stufft and Nick Coghlan, implemented by
Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.</dd>
</dl>
</div>
</div>
</div>
<div class="section" id="pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients">
<h3>PEP 476: Enabling certificate verification by default for stdlib http clients<a class="headerlink" href="#pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients" title="Permalink to this headline">¶</a></h3>
<p><span class="target" id="index-25"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0476"><strong>PEP 476</strong></a> updated <a class="reference internal" href="../library/httplib.html#module-httplib" title="httplib: HTTP and HTTPS protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">httplib</span></code></a> and modules which use it, such as
<a class="reference internal" href="../library/urllib2.html#module-urllib2" title="urllib2: Next generation URL opening library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib2</span></code></a> and <a class="reference internal" href="../library/xmlrpclib.html#module-xmlrpclib" title="xmlrpclib: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpclib</span></code></a>, to now verify that the server
presents a certificate which is signed by a Certificate Authority in the
platform trust store and whose hostname matches the hostname being requested
by default, significantly improving security for many applications. This
change was made in the Python 2.7.9 release.</p>
<p>For applications which require the old previous behavior, they can pass an
alternate context:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">urllib2</span>
<span class="kn">import</span> <span class="nn">ssl</span>

<span class="c1"># This disables all verification</span>
<span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">_create_unverified_context</span><span class="p">()</span>

<span class="c1"># This allows using a specific certificate for the host, which doesn&#39;t need</span>
<span class="c1"># to be in the trust store</span>
<span class="n">context</span> <span class="o">=</span> <span class="n">ssl</span><span class="o">.</span><span class="n">create_default_context</span><span class="p">(</span><span class="n">cafile</span><span class="o">=</span><span class="s2">&quot;/path/to/file.crt&quot;</span><span class="p">)</span>

<span class="n">urllib2</span><span class="o">.</span><span class="n">urlopen</span><span class="p">(</span><span class="s2">&quot;https://invalid-cert&quot;</span><span class="p">,</span> <span class="n">context</span><span class="o">=</span><span class="n">context</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="pep-493-https-verification-migration-tools-for-python-2-7">
<h3>PEP 493: HTTPS verification migration tools for Python 2.7<a class="headerlink" href="#pep-493-https-verification-migration-tools-for-python-2-7" title="Permalink to this headline">¶</a></h3>
<p><span class="target" id="index-26"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0493"><strong>PEP 493</strong></a> provides additional migration tools to support a more incremental
infrastructure upgrade process for environments containing applications and
services relying on the historically permissive processing of server
certificates when establishing client HTTPS connections.  These additions were
made in the Python 2.7.12 release.</p>
<p>These tools are intended for use in cases where affected applications and
services can’t be modified to explicitly pass a more permissive SSL context
when establishing the connection.</p>
<p>For applications and services which can’t be modified at all, the new
<code class="docutils literal notranslate"><span class="pre">PYTHONHTTPSVERIFY</span></code> environment variable may be set to <code class="docutils literal notranslate"><span class="pre">0</span></code> to revert an
entire Python process back to the default permissive behaviour of Python 2.7.8
and earlier.</p>
<p>For cases where the connection establishment code can’t be modified, but the
overall application can be, the new <a class="reference internal" href="../library/ssl.html#ssl._https_verify_certificates" title="ssl._https_verify_certificates"><code class="xref py py-func docutils literal notranslate"><span class="pre">ssl._https_verify_certificates()</span></code></a>
function can be used to adjust the default behaviour at runtime.</p>
</div>
<div class="section" id="new-make-regen-all-build-target">
<h3>New <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">regen-all</span></code> build target<a class="headerlink" href="#new-make-regen-all-build-target" title="Permalink to this headline">¶</a></h3>
<p>To simplify cross-compilation, and to ensure that CPython can reliably be
compiled without requiring an existing version of Python to already be
available, the autotools-based build system no longer attempts to implicitly
recompile generated files based on file modification times.</p>
<p>Instead, a new <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">regen-all</span></code> command has been added to force regeneration
of these files when desired (e.g. after an initial version of Python has
already been built based on the pregenerated versions).</p>
<p>More selective regeneration targets are also defined - see
<a class="reference external" href="https://github.com/python/cpython/tree/2.7/Makefile.pre.in">Makefile.pre.in</a> for details.</p>
<p>(Contributed by Victor Stinner in <a class="reference external" href="https://bugs.python.org/issue23404">bpo-23404</a>.)</p>
<div class="versionadded">
<p><span class="versionmodified">New in version 2.7.14.</span></p>
</div>
</div>
<div class="section" id="removal-of-make-touch-build-target">
<h3>Removal of <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">touch</span></code> build target<a class="headerlink" href="#removal-of-make-touch-build-target" title="Permalink to this headline">¶</a></h3>
<p>The <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">touch</span></code> build target previously used to request implicit regeneration
of generated files by updating their modification times has been removed.</p>
<p>It has been replaced by the new <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">regen-all</span></code> target.</p>
<p>(Contributed by Victor Stinner in <a class="reference external" href="https://bugs.python.org/issue23404">bpo-23404</a>.)</p>
<div class="versionchanged">
<p><span class="versionmodified">Changed in version 2.7.14.</span></p>
</div>
</div>
</div>
<div class="section" id="acknowledgements">
<span id="acks27"></span><h2>Acknowledgements<a class="headerlink" href="#acknowledgements" title="Permalink to this headline">¶</a></h2>
<p>The author would like to thank the following people for offering
suggestions, corrections and assistance with various drafts of this
article: Nick Coghlan, Philip Jenvey, Ryan Lovett, R. David Murray,
Hugh Secker-Walker.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">What’s New in Python 2.7</a><ul>
<li><a class="reference internal" href="#the-future-for-python-2-x">The Future for Python 2.x</a></li>
<li><a class="reference internal" href="#changes-to-the-handling-of-deprecation-warnings">Changes to the Handling of Deprecation Warnings</a></li>
<li><a class="reference internal" href="#python-3-1-features">Python 3.1 Features</a></li>
<li><a class="reference internal" href="#pep-372-adding-an-ordered-dictionary-to-collections">PEP 372: Adding an Ordered Dictionary to collections</a></li>
<li><a class="reference internal" href="#pep-378-format-specifier-for-thousands-separator">PEP 378: Format Specifier for Thousands Separator</a></li>
<li><a class="reference internal" href="#pep-389-the-argparse-module-for-parsing-command-lines">PEP 389: The argparse Module for Parsing Command Lines</a></li>
<li><a class="reference internal" href="#pep-391-dictionary-based-configuration-for-logging">PEP 391: Dictionary-Based Configuration For Logging</a></li>
<li><a class="reference internal" href="#pep-3106-dictionary-views">PEP 3106: Dictionary Views</a></li>
<li><a class="reference internal" href="#pep-3137-the-memoryview-object">PEP 3137: The memoryview Object</a></li>
<li><a class="reference internal" href="#other-language-changes">Other Language Changes</a><ul>
<li><a class="reference internal" href="#interpreter-changes">Interpreter Changes</a></li>
<li><a class="reference internal" href="#optimizations">Optimizations</a></li>
</ul>
</li>
<li><a class="reference internal" href="#new-and-improved-modules">New and Improved Modules</a><ul>
<li><a class="reference internal" href="#new-module-importlib">New module: importlib</a></li>
<li><a class="reference internal" href="#new-module-sysconfig">New module: sysconfig</a></li>
<li><a class="reference internal" href="#ttk-themed-widgets-for-tk">ttk: Themed Widgets for Tk</a></li>
<li><a class="reference internal" href="#updated-module-unittest">Updated module: unittest</a></li>
<li><a class="reference internal" href="#updated-module-elementtree-1-3">Updated module: ElementTree 1.3</a></li>
</ul>
</li>
<li><a class="reference internal" href="#build-and-c-api-changes">Build and C API Changes</a><ul>
<li><a class="reference internal" href="#capsules">Capsules</a></li>
<li><a class="reference internal" href="#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
<li><a class="reference internal" href="#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
<li><a class="reference internal" href="#port-specific-changes-freebsd">Port-Specific Changes: FreeBSD</a></li>
</ul>
</li>
<li><a class="reference internal" href="#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li><a class="reference internal" href="#porting-to-python-2-7">Porting to Python 2.7</a></li>
<li><a class="reference internal" href="#new-features-added-to-python-2-7-maintenance-releases">New Features Added to Python 2.7 Maintenance Releases</a><ul>
<li><a class="reference internal" href="#two-new-environment-variables-for-debug-mode">Two new environment variables for debug mode</a></li>
<li><a class="reference internal" href="#pep-434-idle-enhancement-exception-for-all-branches">PEP 434: IDLE Enhancement Exception for All Branches</a></li>
<li><a class="reference internal" href="#pep-466-network-security-enhancements-for-python-2-7">PEP 466: Network Security Enhancements for Python 2.7</a></li>
<li><a class="reference internal" href="#pep-477-backport-ensurepip-pep-453-to-python-2-7">PEP 477: Backport ensurepip (PEP 453) to Python 2.7</a><ul>
<li><a class="reference internal" href="#bootstrapping-pip-by-default">Bootstrapping pip By Default</a></li>
<li><a class="reference internal" href="#documentation-changes">Documentation Changes</a></li>
</ul>
</li>
<li><a class="reference internal" href="#pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients">PEP 476: Enabling certificate verification by default for stdlib http clients</a></li>
<li><a class="reference internal" href="#pep-493-https-verification-migration-tools-for-python-2-7">PEP 493: HTTPS verification migration tools for Python 2.7</a></li>
<li><a class="reference internal" href="#new-make-regen-all-build-target">New <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">regen-all</span></code> build target</a></li>
<li><a class="reference internal" href="#removal-of-make-touch-build-target">Removal of <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">touch</span></code> build target</a></li>
</ul>
</li>
<li><a class="reference internal" href="#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="index.html"
                        title="previous chapter">What’s New in Python</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.6.html"
                        title="next chapter">What’s New in Python 2.6</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/2.7.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.6.html" title="What’s New in Python 2.6"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="What’s New in Python"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >What’s New in Python</a> &#187;</li> 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�T8eehtml/whatsnew/index.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>What’s New in Python &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="../_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="What’s New in Python 2.7" href="2.7.html" />
    <link rel="prev" title="Python Documentation contents" href="../contents.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/whatsnew/index.html" />
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.7.html" title="What’s New in Python 2.7"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../contents.html" title="Python Documentation contents"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="what-s-new-in-python">
<span id="whatsnew-index"></span><h1>What’s New in Python<a class="headerlink" href="#what-s-new-in-python" title="Permalink to this headline">¶</a></h1>
<p>The “What’s New in Python” series of essays takes tours through the most
important changes between major Python versions.  They are a “must read” for
anyone wishing to stay up-to-date after a new release.</p>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="2.7.html">What’s New in Python 2.7</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#the-future-for-python-2-x">The Future for Python 2.x</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#changes-to-the-handling-of-deprecation-warnings">Changes to the Handling of Deprecation Warnings</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#python-3-1-features">Python 3.1 Features</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-372-adding-an-ordered-dictionary-to-collections">PEP 372: Adding an Ordered Dictionary to collections</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-378-format-specifier-for-thousands-separator">PEP 378: Format Specifier for Thousands Separator</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-389-the-argparse-module-for-parsing-command-lines">PEP 389: The argparse Module for Parsing Command Lines</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-391-dictionary-based-configuration-for-logging">PEP 391: Dictionary-Based Configuration For Logging</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-3106-dictionary-views">PEP 3106: Dictionary Views</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#pep-3137-the-memoryview-object">PEP 3137: The memoryview Object</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#other-language-changes">Other Language Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#build-and-c-api-changes">Build and C API Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#porting-to-python-2-7">Porting to Python 2.7</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#new-features-added-to-python-2-7-maintenance-releases">New Features Added to Python 2.7 Maintenance Releases</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.7.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.6.html">What’s New in Python 2.6</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#python-3-0">Python 3.0</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#changes-to-the-development-process">Changes to the Development Process</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#other-language-changes">Other Language Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#deprecations-and-removals">Deprecations and Removals</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#build-and-c-api-changes">Build and C API Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#porting-to-python-2-6">Porting to Python 2.6</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.6.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.5.html">What’s New in Python 2.5</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#other-language-changes">Other Language Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#new-improved-and-removed-modules">New, Improved, and Removed Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#build-and-c-api-changes">Build and C API Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#porting-to-python-2-5">Porting to Python 2.5</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.5.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.4.html">What’s New in Python 2.4</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-218-built-in-set-objects">PEP 218: Built-In Set Objects</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-289-generator-expressions">PEP 289: Generator Expressions</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-292-simpler-string-substitutions">PEP 292: Simpler String Substitutions</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-318-decorators-for-functions-and-methods">PEP 318: Decorators for Functions and Methods</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-322-reverse-iteration">PEP 322: Reverse Iteration</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-324-new-subprocess-module">PEP 324: New subprocess Module</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-327-decimal-data-type">PEP 327: Decimal Data Type</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-328-multi-line-imports">PEP 328: Multi-line Imports</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#pep-331-locale-independent-float-string-conversions">PEP 331: Locale-Independent Float/String Conversions</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#other-language-changes">Other Language Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#build-and-c-api-changes">Build and C API Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#porting-to-python-2-4">Porting to Python 2.4</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.4.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.3.html">What’s New in Python 2.3</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-279-enumerate">PEP 279: enumerate()</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#extended-slices">Extended Slices</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#other-language-changes">Other Language Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#build-and-c-api-changes">Build and C API Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#porting-to-python-2-3">Porting to Python 2.3</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.3.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.2.html">What’s New in Python 2.2</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#introduction">Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#peps-252-and-253-type-and-class-changes">PEPs 252 and 253: Type and Class Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#pep-234-iterators">PEP 234: Iterators</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#pep-238-changing-the-division-operator">PEP 238: Changing the Division Operator</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#unicode-changes">Unicode Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#interpreter-changes-and-fixes">Interpreter Changes and Fixes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.2.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.1.html">What’s New in Python 2.1</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#introduction">Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-236-future-directives">PEP 236: __future__ Directives</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-207-rich-comparisons">PEP 207: Rich Comparisons</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-230-warning-framework">PEP 230: Warning Framework</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-229-new-build-system">PEP 229: New Build System</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-205-weak-references">PEP 205: Weak References</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-232-function-attributes">PEP 232: Function Attributes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-235-importing-modules-on-case-insensitive-platforms">PEP 235: Importing Modules on Case-Insensitive Platforms</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-217-interactive-display-hook">PEP 217: Interactive Display Hook</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-208-new-coercion-model">PEP 208: New Coercion Model</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#pep-241-metadata-in-python-packages">PEP 241: Metadata in Python Packages</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.1.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="2.0.html">What’s New in Python 2.0</a><ul>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#introduction">Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#what-about-python-1-6">What About Python 1.6?</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#new-development-process">New Development Process</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#unicode">Unicode</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#list-comprehensions">List Comprehensions</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#augmented-assignment">Augmented Assignment</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#string-methods">String Methods</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#garbage-collection-of-cycles">Garbage Collection of Cycles</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#other-core-changes">Other Core Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#porting-to-2-0">Porting to 2.0</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#extending-embedding-changes">Extending/Embedding Changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#distutils-making-modules-easy-to-install">Distutils: Making Modules Easy to Install</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#xml-modules">XML Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#module-changes">Module changes</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#new-modules">New modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#idle-improvements">IDLE Improvements</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#deleted-and-deprecated-modules">Deleted and Deprecated Modules</a></li>
<li class="toctree-l2"><a class="reference internal" href="2.0.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="../contents.html"
                        title="previous chapter">Python Documentation contents</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="2.7.html"
                        title="next chapter">What’s New in Python 2.7</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/whatsnew/index.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="2.7.html" title="What’s New in Python 2.7"
             >next</a> |</li>
        <li class="right" >
          <a href="../contents.html" title="Python Documentation contents"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="../index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��011html/about.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>About these documents &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="#" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="next" title="Reporting Bugs" href="bugs.html" />
    <link rel="prev" title="Glossary" href="glossary.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/about.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bugs.html" title="Reporting Bugs"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="glossary.html" title="Glossary"
             accesskey="P">previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="about-these-documents">
<h1>About these documents<a class="headerlink" href="#about-these-documents" title="Permalink to this headline">¶</a></h1>
<p>These documents are generated from <a class="reference external" href="http://docutils.sourceforge.net/rst.html">reStructuredText</a> sources by <a class="reference external" href="http://sphinx-doc.org/">Sphinx</a>, a
document processor specifically written for the Python documentation.</p>
<p>Development of the documentation and its toolchain is an entirely volunteer
effort, just like Python itself.  If you want to contribute, please take a
look at the <a class="reference internal" href="bugs.html#reporting-bugs"><span class="std std-ref">Reporting Bugs</span></a> page for information on how to do so.  New
volunteers are always welcome!</p>
<p>Many thanks go to:</p>
<ul class="simple">
<li>Fred L. Drake, Jr., the creator of the original Python documentation toolset
and writer of much of the content;</li>
<li>the <a class="reference external" href="http://docutils.sourceforge.net/">Docutils</a> project for creating
reStructuredText and the Docutils suite;</li>
<li>Fredrik Lundh for his <a class="reference external" href="http://effbot.org/zone/pyref.htm">Alternative Python Reference</a> project from which Sphinx got many good
ideas.</li>
</ul>
<div class="section" id="contributors-to-the-python-documentation">
<h2>Contributors to the Python Documentation<a class="headerlink" href="#contributors-to-the-python-documentation" title="Permalink to this headline">¶</a></h2>
<p>Many people have contributed to the Python language, the Python standard
library, and the Python documentation.  See <a class="reference external" href="https://github.com/python/cpython/tree/2.7/Misc/ACKS">Misc/ACKS</a> in the Python
source distribution for a partial list of contributors.</p>
<p>It is only with the input and contributions of the Python community
that Python has such wonderful documentation – Thank You!</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">About these documents</a><ul>
<li><a class="reference internal" href="#contributors-to-the-python-documentation">Contributors to the Python Documentation</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="glossary.html"
                        title="previous chapter">Glossary</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="bugs.html"
                        title="next chapter">Reporting Bugs</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/about.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="bugs.html" title="Reporting Bugs"
             >next</a> |</li>
        <li class="right" >
          <a href="glossary.html" title="Glossary"
             >previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\6w��,�,html/bugs.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Reporting Bugs &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="next" title="Copyright" href="copyright.html" />
    <link rel="prev" title="About these documents" href="about.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/bugs.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copyright.html" title="Copyright"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="about.html" title="About these documents"
             accesskey="P">previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="reporting-bugs">
<span id="id1"></span><h1>Reporting Bugs<a class="headerlink" href="#reporting-bugs" title="Permalink to this headline">¶</a></h1>
<p>Python is a mature programming language which has established a reputation for
stability.  In order to maintain this reputation, the developers would like to
know of any deficiencies you find in Python.</p>
<div class="section" id="documentation-bugs">
<h2>Documentation bugs<a class="headerlink" href="#documentation-bugs" title="Permalink to this headline">¶</a></h2>
<p>If you find a bug in this documentation or would like to propose an improvement,
please submit a bug report on the <a class="reference internal" href="#using-the-tracker"><span class="std std-ref">tracker</span></a>.  If you
have a suggestion on how to fix it, include that as well.</p>
<p>If you’re short on time, you can also email documentation bug reports to
<a class="reference external" href="mailto:docs&#37;&#52;&#48;python&#46;org">docs<span>&#64;</span>python<span>&#46;</span>org</a> (behavioral bugs can be sent to <a class="reference external" href="mailto:python-list&#37;&#52;&#48;python&#46;org">python-list<span>&#64;</span>python<span>&#46;</span>org</a>).
‘docs&#64;’ is a mailing list run by volunteers; your request will be noticed,
though it may take a while to be processed.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<p class="last"><a class="reference external" href="https://bugs.python.org/issue?&#64;filter=status&amp;&#64;filter=components&amp;components=4&amp;status=1&amp;&#64;columns=id,activity,title,status&amp;&#64;sort=-activity">Documentation bugs</a> on the Python issue tracker</p>
</div>
</div>
<div class="section" id="using-the-python-issue-tracker">
<span id="using-the-tracker"></span><h2>Using the Python issue tracker<a class="headerlink" href="#using-the-python-issue-tracker" title="Permalink to this headline">¶</a></h2>
<p>Bug reports for Python itself should be submitted via the Python Bug Tracker
(<a class="reference external" href="https://bugs.python.org/">https://bugs.python.org/</a>).  The bug tracker offers a Web form which allows
pertinent information to be entered and submitted to the developers.</p>
<p>The first step in filing a report is to determine whether the problem has
already been reported.  The advantage in doing so, aside from saving the
developers time, is that you learn what has been done to fix it; it may be that
the problem has already been fixed for the next release, or additional
information is needed (in which case you are welcome to provide it if you can!).
To do this, search the bug database using the search box on the top of the page.</p>
<p>If the problem you’re reporting is not already in the bug tracker, go back to
the Python Bug Tracker and log in.  If you don’t already have a tracker account,
select the “Register” link or, if you use OpenID, one of the OpenID provider
logos in the sidebar.  It is not possible to submit a bug report anonymously.</p>
<p>Being now logged in, you can submit a bug.  Select the “Create New” link in the
sidebar to open the bug reporting form.</p>
<p>The submission form has a number of fields.  For the “Title” field, enter a
<em>very</em> short description of the problem; less than ten words is good.  In the
“Type” field, select the type of your problem; also select the “Component” and
“Versions” to which the bug relates.</p>
<p>In the “Comment” field, describe the problem in detail, including what you
expected to happen and what did happen.  Be sure to include whether any
extension modules were involved, and what hardware and software platform you
were using (including version information as appropriate).</p>
<p>Each bug report will be assigned to a developer who will determine what needs to
be done to correct the problem.  You will receive an update each time action is
taken on the bug.</p>
<div class="admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://www.chiark.greenend.org.uk/~sgtatham/bugs.html">How to Report Bugs Effectively</a></dt>
<dd>Article which goes into some detail about how to create a useful bug report.
This describes what kind of information is useful and why it is useful.</dd>
<dt><a class="reference external" href="https://developer.mozilla.org/en-US/docs/Mozilla/QA/Bug_writing_guidelines">Bug Writing Guidelines</a></dt>
<dd>Information about writing a good bug report.  Some of this is specific to the
Mozilla project, but describes general good practices.</dd>
</dl>
</div>
</div>
<div class="section" id="getting-started-contributing-to-python-yourself">
<h2>Getting started contributing to Python yourself<a class="headerlink" href="#getting-started-contributing-to-python-yourself" title="Permalink to this headline">¶</a></h2>
<p>Beyond just reporting bugs that you find, you are also welcome to submit
patches to fix them.  You can find more information on how to get started
patching Python in the <a class="reference external" href="https://devguide.python.org/">Python Developer’s Guide</a>.  If you have questions,
the <a class="reference external" href="https://mail.python.org/mailman3/lists/core-mentorship.python.org/">core-mentorship mailing list</a> is a friendly place to get answers to
any and all questions pertaining to the process of fixing issues in Python.</p>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Reporting Bugs</a><ul>
<li><a class="reference internal" href="#documentation-bugs">Documentation bugs</a></li>
<li><a class="reference internal" href="#using-the-python-issue-tracker">Using the Python issue tracker</a></li>
<li><a class="reference internal" href="#getting-started-contributing-to-python-yourself">Getting started contributing to Python yourself</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="about.html"
                        title="previous chapter">About these documents</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="copyright.html"
                        title="next chapter">Copyright</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/bugs.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="copyright.html" title="Copyright"
             >next</a> |</li>
        <li class="right" >
          <a href="about.html" title="About these documents"
             >previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="#">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��9��html/contents.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Python Documentation contents &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="next" title="What’s New in Python" href="whatsnew/index.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/contents.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whatsnew/index.html" title="What’s New in Python"
             accesskey="N">next</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="python-documentation-contents">
<h1>Python Documentation contents<a class="headerlink" href="#python-documentation-contents" title="Permalink to this headline">¶</a></h1>
<div class="toctree-wrapper compound">
<ul>
<li class="toctree-l1"><a class="reference internal" href="whatsnew/index.html">What’s New in Python</a><ul>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.7.html">What’s New in Python 2.7</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#the-future-for-python-2-x">The Future for Python 2.x</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#changes-to-the-handling-of-deprecation-warnings">Changes to the Handling of Deprecation Warnings</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#python-3-1-features">Python 3.1 Features</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections">PEP 372: Adding an Ordered Dictionary to collections</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-378-format-specifier-for-thousands-separator">PEP 378: Format Specifier for Thousands Separator</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-389-the-argparse-module-for-parsing-command-lines">PEP 389: The argparse Module for Parsing Command Lines</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-391-dictionary-based-configuration-for-logging">PEP 391: Dictionary-Based Configuration For Logging</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-3106-dictionary-views">PEP 3106: Dictionary Views</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#pep-3137-the-memoryview-object">PEP 3137: The memoryview Object</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#other-language-changes">Other Language Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#interpreter-changes">Interpreter Changes</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#optimizations">Optimizations</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#new-and-improved-modules">New and Improved Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#new-module-importlib">New module: importlib</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#new-module-sysconfig">New module: sysconfig</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#ttk-themed-widgets-for-tk">ttk: Themed Widgets for Tk</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#updated-module-unittest">Updated module: unittest</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#updated-module-elementtree-1-3">Updated module: ElementTree 1.3</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#build-and-c-api-changes">Build and C API Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#capsules">Capsules</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#port-specific-changes-freebsd">Port-Specific Changes: FreeBSD</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#porting-to-python-2-7">Porting to Python 2.7</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#new-features-added-to-python-2-7-maintenance-releases">New Features Added to Python 2.7 Maintenance Releases</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#two-new-environment-variables-for-debug-mode">Two new environment variables for debug mode</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#pep-434-idle-enhancement-exception-for-all-branches">PEP 434: IDLE Enhancement Exception for All Branches</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#pep-466-network-security-enhancements-for-python-2-7">PEP 466: Network Security Enhancements for Python 2.7</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#pep-477-backport-ensurepip-pep-453-to-python-2-7">PEP 477: Backport ensurepip (PEP 453) to Python 2.7</a><ul>
<li class="toctree-l5"><a class="reference internal" href="whatsnew/2.7.html#bootstrapping-pip-by-default">Bootstrapping pip By Default</a></li>
<li class="toctree-l5"><a class="reference internal" href="whatsnew/2.7.html#documentation-changes">Documentation Changes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#pep-476-enabling-certificate-verification-by-default-for-stdlib-http-clients">PEP 476: Enabling certificate verification by default for stdlib http clients</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#pep-493-https-verification-migration-tools-for-python-2-7">PEP 493: HTTPS verification migration tools for Python 2.7</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#new-make-regen-all-build-target">New <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">regen-all</span></code> build target</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.7.html#removal-of-make-touch-build-target">Removal of <code class="docutils literal notranslate"><span class="pre">make</span> <span class="pre">touch</span></code> build target</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.7.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.6.html">What’s New in Python 2.6</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#python-3-0">Python 3.0</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#changes-to-the-development-process">Changes to the Development Process</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#new-issue-tracker-roundup">New Issue Tracker: Roundup</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#new-documentation-format-restructuredtext-using-sphinx">New Documentation Format: reStructuredText Using Sphinx</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#writing-context-managers">Writing Context Managers</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-366-explicit-relative-imports-from-a-main-module">PEP 366: Explicit Relative Imports From a Main Module</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-370-per-user-site-packages-directory">PEP 370: Per-user <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> Directory</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-371-the-multiprocessing-package">PEP 371: The <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> Package</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3101-advanced-string-formatting">PEP 3101: Advanced String Formatting</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3105-print-as-a-function">PEP 3105: <code class="docutils literal notranslate"><span class="pre">print</span></code> As a Function</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3110-exception-handling-changes">PEP 3110: Exception-Handling Changes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3112-byte-literals">PEP 3112: Byte Literals</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3116-new-i-o-library">PEP 3116: New I/O Library</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3118-revised-buffer-protocol">PEP 3118: Revised Buffer Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3119-abstract-base-classes">PEP 3119: Abstract Base Classes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3127-integer-literal-support-and-syntax">PEP 3127: Integer Literal Support and Syntax</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3129-class-decorators">PEP 3129: Class Decorators</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#pep-3141-a-type-hierarchy-for-numbers">PEP 3141: A Type Hierarchy for Numbers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-fractions-module">The <code class="docutils literal notranslate"><span class="pre">fractions</span></code> Module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#other-language-changes">Other Language Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#optimizations">Optimizations</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#interpreter-changes">Interpreter Changes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#new-and-improved-modules">New and Improved Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-ast-module">The <code class="docutils literal notranslate"><span class="pre">ast</span></code> module</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-future-builtins-module">The <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> module</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-json-module-javascript-object-notation">The <code class="docutils literal notranslate"><span class="pre">json</span></code> module: JavaScript Object Notation</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#the-plistlib-module-a-property-list-parser">The <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> module: A Property-List Parser</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#ctypes-enhancements">ctypes Enhancements</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#improved-ssl-support">Improved SSL Support</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#deprecations-and-removals">Deprecations and Removals</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#build-and-c-api-changes">Build and C API Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#port-specific-changes-windows">Port-Specific Changes: Windows</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#port-specific-changes-mac-os-x">Port-Specific Changes: Mac OS X</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.6.html#port-specific-changes-irix">Port-Specific Changes: IRIX</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#porting-to-python-2-6">Porting to Python 2.6</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.6.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.5.html">What’s New in Python 2.5</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-308-conditional-expressions">PEP 308: Conditional Expressions</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-309-partial-function-application">PEP 309: Partial Function Application</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-314-metadata-for-python-software-packages-v1-1">PEP 314: Metadata for Python Software Packages v1.1</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-328-absolute-and-relative-imports">PEP 328: Absolute and Relative Imports</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-338-executing-modules-as-scripts">PEP 338: Executing Modules as Scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-341-unified-try-except-finally">PEP 341: Unified try/except/finally</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-342-new-generator-features">PEP 342: New Generator Features</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-343-the-with-statement">PEP 343: The ‘with’ statement</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#writing-context-managers">Writing Context Managers</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-contextlib-module">The contextlib module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-352-exceptions-as-new-style-classes">PEP 352: Exceptions as New-Style Classes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-353-using-ssize-t-as-the-index-type">PEP 353: Using ssize_t as the index type</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#pep-357-the-index-method">PEP 357: The ‘__index__’ method</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#other-language-changes">Other Language Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#interactive-interpreter-changes">Interactive Interpreter Changes</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#optimizations">Optimizations</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#new-improved-and-removed-modules">New, Improved, and Removed Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-ctypes-package">The ctypes package</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-elementtree-package">The ElementTree package</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-hashlib-package">The hashlib package</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-sqlite3-package">The sqlite3 package</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#the-wsgiref-package">The wsgiref package</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#build-and-c-api-changes">Build and C API Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.5.html#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#porting-to-python-2-5">Porting to Python 2.5</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.5.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.4.html">What’s New in Python 2.4</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-218-built-in-set-objects">PEP 218: Built-In Set Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-289-generator-expressions">PEP 289: Generator Expressions</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-292-simpler-string-substitutions">PEP 292: Simpler String Substitutions</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods">PEP 318: Decorators for Functions and Methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-322-reverse-iteration">PEP 322: Reverse Iteration</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-324-new-subprocess-module">PEP 324: New subprocess Module</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-327-decimal-data-type">PEP 327: Decimal Data Type</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#why-is-decimal-needed">Why is Decimal needed?</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#the-decimal-type">The <code class="docutils literal notranslate"><span class="pre">Decimal</span></code> type</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#the-context-type">The <code class="docutils literal notranslate"><span class="pre">Context</span></code> type</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-328-multi-line-imports">PEP 328: Multi-line Imports</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#pep-331-locale-independent-float-string-conversions">PEP 331: Locale-Independent Float/String Conversions</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#other-language-changes">Other Language Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#optimizations">Optimizations</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#cookielib">cookielib</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#doctest">doctest</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#build-and-c-api-changes">Build and C API Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.4.html#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#porting-to-python-2-4">Porting to Python 2.4</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.4.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.3.html">What’s New in Python 2.3</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-218-a-standard-set-datatype">PEP 218: A Standard Set Datatype</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-263-source-code-encodings">PEP 263: Source Code Encodings</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-273-importing-modules-from-zip-archives">PEP 273: Importing Modules from ZIP Archives</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-277-unicode-file-name-support-for-windows-nt">PEP 277: Unicode file name support for Windows NT</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-278-universal-newline-support">PEP 278: Universal Newline Support</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-279-enumerate">PEP 279: enumerate()</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-282-the-logging-package">PEP 282: The logging Package</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-285-a-boolean-type">PEP 285: A Boolean Type</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-293-codec-error-handling-callbacks">PEP 293: Codec Error Handling Callbacks</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-301-package-index-and-metadata-for-distutils">PEP 301: Package Index and Metadata for Distutils</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-302-new-import-hooks">PEP 302: New Import Hooks</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-305-comma-separated-files">PEP 305: Comma-separated Files</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pep-307-pickle-enhancements">PEP 307: Pickle Enhancements</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#extended-slices">Extended Slices</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#other-language-changes">Other Language Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.3.html#string-changes">String Changes</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.3.html#optimizations">Optimizations</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#new-improved-and-deprecated-modules">New, Improved, and Deprecated Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.3.html#date-time-type">Date/Time Type</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.3.html#the-optparse-module">The optparse Module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#pymalloc-a-specialized-object-allocator">Pymalloc: A Specialized Object Allocator</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#build-and-c-api-changes">Build and C API Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.3.html#port-specific-changes">Port-Specific Changes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#porting-to-python-2-3">Porting to Python 2.3</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.3.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.2.html">What’s New in Python 2.2</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#introduction">Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#peps-252-and-253-type-and-class-changes">PEPs 252 and 253: Type and Class Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.2.html#old-and-new-classes">Old and New Classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.2.html#descriptors">Descriptors</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.2.html#multiple-inheritance-the-diamond-rule">Multiple Inheritance: The Diamond Rule</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.2.html#attribute-access">Attribute Access</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.2.html#related-links">Related Links</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#pep-234-iterators">PEP 234: Iterators</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#pep-255-simple-generators">PEP 255: Simple Generators</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#pep-237-unifying-long-integers-and-integers">PEP 237: Unifying Long Integers and Integers</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#pep-238-changing-the-division-operator">PEP 238: Changing the Division Operator</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#unicode-changes">Unicode Changes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#interpreter-changes-and-fixes">Interpreter Changes and Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.2.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.1.html">What’s New in Python 2.1</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#introduction">Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-227-nested-scopes">PEP 227: Nested Scopes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-236-future-directives">PEP 236: __future__ Directives</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-207-rich-comparisons">PEP 207: Rich Comparisons</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-230-warning-framework">PEP 230: Warning Framework</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-229-new-build-system">PEP 229: New Build System</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-205-weak-references">PEP 205: Weak References</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-232-function-attributes">PEP 232: Function Attributes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-235-importing-modules-on-case-insensitive-platforms">PEP 235: Importing Modules on Case-Insensitive Platforms</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-217-interactive-display-hook">PEP 217: Interactive Display Hook</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-208-new-coercion-model">PEP 208: New Coercion Model</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#pep-241-metadata-in-python-packages">PEP 241: Metadata in Python Packages</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#new-and-improved-modules">New and Improved Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#other-changes-and-fixes">Other Changes and Fixes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.1.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="whatsnew/2.0.html">What’s New in Python 2.0</a><ul>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#introduction">Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#what-about-python-1-6">What About Python 1.6?</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#new-development-process">New Development Process</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#unicode">Unicode</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#list-comprehensions">List Comprehensions</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#augmented-assignment">Augmented Assignment</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#string-methods">String Methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#garbage-collection-of-cycles">Garbage Collection of Cycles</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#other-core-changes">Other Core Changes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.0.html#minor-language-changes">Minor Language Changes</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.0.html#changes-to-built-in-functions">Changes to Built-in Functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#porting-to-2-0">Porting to 2.0</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#extending-embedding-changes">Extending/Embedding Changes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#distutils-making-modules-easy-to-install">Distutils: Making Modules Easy to Install</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#xml-modules">XML Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.0.html#sax2-support">SAX2 Support</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.0.html#dom-support">DOM Support</a></li>
<li class="toctree-l4"><a class="reference internal" href="whatsnew/2.0.html#relationship-to-pyxml">Relationship to PyXML</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#module-changes">Module changes</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#new-modules">New modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#idle-improvements">IDLE Improvements</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#deleted-and-deprecated-modules">Deleted and Deprecated Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="whatsnew/2.0.html#acknowledgements">Acknowledgements</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="tutorial/index.html">The Python Tutorial</a><ul>
<li class="toctree-l2"><a class="reference internal" href="tutorial/appetite.html">1. Whetting Your Appetite</a></li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/interpreter.html">2. Using the Python Interpreter</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interpreter.html#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/interpreter.html#argument-passing">2.1.1. Argument Passing</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/interpreter.html#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interpreter.html#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/interpreter.html#source-code-encoding">2.2.1. Source Code Encoding</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/introduction.html">3. An Informal Introduction to Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/introduction.html#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/introduction.html#numbers">3.1.1. Numbers</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/introduction.html#strings">3.1.2. Strings</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/introduction.html#unicode-strings">3.1.3. Unicode Strings</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/introduction.html#lists">3.1.4. Lists</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/introduction.html#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/controlflow.html">4. More Control Flow Tools</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#if-statements">4.1. <code class="docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#for-statements">4.2. <code class="docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#the-range-function">4.3. The <code class="docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops">4.4. <code class="docutils literal notranslate"><span class="pre">break</span></code> and <code class="docutils literal notranslate"><span class="pre">continue</span></code> Statements, and <code class="docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#pass-statements">4.5. <code class="docutils literal notranslate"><span class="pre">pass</span></code> Statements</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#defining-functions">4.6. Defining Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#more-on-defining-functions">4.7. More on Defining Functions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#default-argument-values">4.7.1. Default Argument Values</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#keyword-arguments">4.7.2. Keyword Arguments</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#arbitrary-argument-lists">4.7.3. Arbitrary Argument Lists</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#unpacking-argument-lists">4.7.4. Unpacking Argument Lists</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#lambda-expressions">4.7.5. Lambda Expressions</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/controlflow.html#documentation-strings">4.7.6. Documentation Strings</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/controlflow.html#intermezzo-coding-style">4.8. Intermezzo: Coding Style</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/datastructures.html">5. Data Structures</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#more-on-lists">5.1. More on Lists</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/datastructures.html#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/datastructures.html#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/datastructures.html#functional-programming-tools">5.1.3. Functional Programming Tools</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/datastructures.html#list-comprehensions">5.1.4. List Comprehensions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="tutorial/datastructures.html#nested-list-comprehensions">5.1.4.1. Nested List Comprehensions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#the-del-statement">5.2. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#sets">5.4. Sets</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#dictionaries">5.5. Dictionaries</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#looping-techniques">5.6. Looping Techniques</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#more-on-conditions">5.7. More on Conditions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/datastructures.html#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/modules.html">6. Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/modules.html#more-on-modules">6.1. More on Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#the-module-search-path">6.1.2. The Module Search Path</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/modules.html#standard-modules">6.2. Standard Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/modules.html#the-dir-function">6.3. The <code class="docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/modules.html#packages">6.4. Packages</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#intra-package-references">6.4.2. Intra-package References</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/modules.html#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/inputoutput.html">7. Input and Output</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/inputoutput.html#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/inputoutput.html#old-string-formatting">7.1.1. Old string formatting</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/inputoutput.html#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/inputoutput.html#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/inputoutput.html#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="docutils literal notranslate"><span class="pre">json</span></code></a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/errors.html">8. Errors and Exceptions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#syntax-errors">8.1. Syntax Errors</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#exceptions">8.2. Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#handling-exceptions">8.3. Handling Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#raising-exceptions">8.4. Raising Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#user-defined-exceptions">8.5. User-defined Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#defining-clean-up-actions">8.6. Defining Clean-up Actions</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/errors.html#predefined-clean-up-actions">8.7. Predefined Clean-up Actions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/classes.html">9. Classes</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#class-objects">9.3.2. Class Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#instance-objects">9.3.3. Instance Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#method-objects">9.3.4. Method Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#random-remarks">9.4. Random Remarks</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#inheritance">9.5. Inheritance</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/classes.html#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#private-variables-and-class-local-references">9.6. Private Variables and Class-local References</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#odds-and-ends">9.7. Odds and Ends</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#exceptions-are-classes-too">9.8. Exceptions Are Classes Too</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#iterators">9.9. Iterators</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#generators">9.10. Generators</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/classes.html#generator-expressions">9.11. Generator Expressions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/stdlib.html">10. Brief Tour of the Standard Library</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#operating-system-interface">10.1. Operating System Interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#file-wildcards">10.2. File Wildcards</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#command-line-arguments">10.3. Command Line Arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#string-pattern-matching">10.5. String Pattern Matching</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#mathematics">10.6. Mathematics</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#internet-access">10.7. Internet Access</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#dates-and-times">10.8. Dates and Times</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#data-compression">10.9. Data Compression</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#performance-measurement">10.10. Performance Measurement</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#quality-control">10.11. Quality Control</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib.html#batteries-included">10.12. Batteries Included</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/stdlib2.html">11. Brief Tour of the Standard Library — Part II</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#output-formatting">11.1. Output Formatting</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#templating">11.2. Templating</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#multi-threading">11.4. Multi-threading</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#logging">11.5. Logging</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#weak-references">11.6. Weak References</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/stdlib2.html#decimal-floating-point-arithmetic">11.8. Decimal Floating Point Arithmetic</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/whatnow.html">12. What Now?</a></li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/interactive.html">13. Interactive Input Editing and History Substitution</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interactive.html#line-editing">13.1. Line Editing</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interactive.html#history-substitution">13.2. History Substitution</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interactive.html#key-bindings">13.3. Key Bindings</a></li>
<li class="toctree-l3"><a class="reference internal" href="tutorial/interactive.html#alternatives-to-the-interactive-interpreter">13.4. Alternatives to the Interactive Interpreter</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/floatingpoint.html">14. Floating Point Arithmetic:  Issues and Limitations</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/floatingpoint.html#representation-error">14.1. Representation Error</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="tutorial/appendix.html">15. Appendix</a><ul>
<li class="toctree-l3"><a class="reference internal" href="tutorial/appendix.html#interactive-mode">15.1. Interactive Mode</a><ul>
<li class="toctree-l4"><a class="reference internal" href="tutorial/appendix.html#error-handling">15.1.1. Error Handling</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/appendix.html#executable-python-scripts">15.1.2. Executable Python Scripts</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/appendix.html#the-interactive-startup-file">15.1.3. The Interactive Startup File</a></li>
<li class="toctree-l4"><a class="reference internal" href="tutorial/appendix.html#the-customization-modules">15.1.4. The Customization Modules</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="using/index.html">Python Setup and Usage</a><ul>
<li class="toctree-l2"><a class="reference internal" href="using/cmdline.html">1. Command line and environment</a><ul>
<li class="toctree-l3"><a class="reference internal" href="using/cmdline.html#command-line">1.1. Command line</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/cmdline.html#interface-options">1.1.1. Interface options</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/cmdline.html#generic-options">1.1.2. Generic options</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/cmdline.html#miscellaneous-options">1.1.3. Miscellaneous options</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/cmdline.html#options-you-shouldn-t-use">1.1.4. Options you shouldn’t use</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using/cmdline.html#environment-variables">1.2. Environment variables</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/cmdline.html#debug-mode-variables">1.2.1. Debug-mode variables</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="using/unix.html">2. Using Python on Unix platforms</a><ul>
<li class="toctree-l3"><a class="reference internal" href="using/unix.html#getting-and-installing-the-latest-version-of-python">2.1. Getting and installing the latest version of Python</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/unix.html#on-linux">2.1.1. On Linux</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/unix.html#on-freebsd-and-openbsd">2.1.2. On FreeBSD and OpenBSD</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/unix.html#on-opensolaris">2.1.3. On OpenSolaris</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using/unix.html#building-python">2.2. Building Python</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/unix.html#python-related-paths-and-files">2.3. Python-related paths and files</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/unix.html#miscellaneous">2.4. Miscellaneous</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/unix.html#editors-and-ides">2.5. Editors and IDEs</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="using/windows.html">3. Using Python on Windows</a><ul>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#installing-python">3.1. Installing Python</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#alternative-bundles">3.2. Alternative bundles</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#configuring-python">3.3. Configuring Python</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#excursus-setting-environment-variables">3.3.1. Excursus: Setting environment variables</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#finding-the-python-executable">3.3.2. Finding the Python executable</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#finding-modules">3.3.3. Finding modules</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#executing-scripts">3.3.4. Executing scripts</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#additional-modules">3.4. Additional modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#pywin32">3.4.1. PyWin32</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#py2exe">3.4.2. Py2exe</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/windows.html#wconio">3.4.3. WConio</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#compiling-python-on-windows">3.5. Compiling Python on Windows</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/windows.html#other-resources">3.6. Other resources</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="using/mac.html">4. Using Python on a Macintosh</a><ul>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#getting-and-installing-macpython">4.1. Getting and Installing MacPython</a><ul>
<li class="toctree-l4"><a class="reference internal" href="using/mac.html#how-to-run-a-python-script">4.1.1. How to run a Python script</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/mac.html#running-scripts-with-a-gui">4.1.2. Running scripts with a GUI</a></li>
<li class="toctree-l4"><a class="reference internal" href="using/mac.html#configuration">4.1.3. Configuration</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#the-ide">4.2. The IDE</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#installing-additional-python-packages">4.3. Installing Additional Python Packages</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#gui-programming-on-the-mac">4.4. GUI Programming on the Mac</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#distributing-python-applications-on-the-mac">4.5. Distributing Python Applications on the Mac</a></li>
<li class="toctree-l3"><a class="reference internal" href="using/mac.html#other-resources">4.6. Other Resources</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="reference/index.html">The Python Language Reference</a><ul>
<li class="toctree-l2"><a class="reference internal" href="reference/introduction.html">1. Introduction</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/introduction.html#alternate-implementations">1.1. Alternate Implementations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/introduction.html#notation">1.2. Notation</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/lexical_analysis.html">2. Lexical analysis</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#line-structure">2.1. Line structure</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#logical-lines">2.1.1. Logical lines</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#physical-lines">2.1.2. Physical lines</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#comments">2.1.3. Comments</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#encoding-declarations">2.1.4. Encoding declarations</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#explicit-line-joining">2.1.5. Explicit line joining</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#implicit-line-joining">2.1.6. Implicit line joining</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#blank-lines">2.1.7. Blank lines</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#indentation">2.1.8. Indentation</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#whitespace-between-tokens">2.1.9. Whitespace between tokens</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#other-tokens">2.2. Other tokens</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#identifiers">2.3. Identifiers and keywords</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#keywords">2.3.1. Keywords</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#reserved-classes-of-identifiers">2.3.2. Reserved classes of identifiers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#literals">2.4. Literals</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#string-literals">2.4.1. String literals</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#string-literal-concatenation">2.4.2. String literal concatenation</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#numeric-literals">2.4.3. Numeric literals</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#integer-and-long-integer-literals">2.4.4. Integer and long integer literals</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#floating-point-literals">2.4.5. Floating point literals</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/lexical_analysis.html#imaginary-literals">2.4.6. Imaginary literals</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#operators">2.5. Operators</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/lexical_analysis.html#delimiters">2.6. Delimiters</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/datamodel.html">3. Data model</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/datamodel.html#objects-values-and-types">3.1. Objects, values and types</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/datamodel.html#the-standard-type-hierarchy">3.2. The standard type hierarchy</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/datamodel.html#new-style-and-classic-classes">3.3. New-style and classic classes</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/datamodel.html#special-method-names">3.4. Special method names</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#basic-customization">3.4.1. Basic customization</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#customizing-attribute-access">3.4.2. Customizing attribute access</a><ul>
<li class="toctree-l5"><a class="reference internal" href="reference/datamodel.html#more-attribute-access-for-new-style-classes">3.4.2.1. More attribute access for new-style classes</a></li>
<li class="toctree-l5"><a class="reference internal" href="reference/datamodel.html#implementing-descriptors">3.4.2.2. Implementing Descriptors</a></li>
<li class="toctree-l5"><a class="reference internal" href="reference/datamodel.html#invoking-descriptors">3.4.2.3. Invoking Descriptors</a></li>
<li class="toctree-l5"><a class="reference internal" href="reference/datamodel.html#slots">3.4.2.4. __slots__</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#customizing-class-creation">3.4.3. Customizing class creation</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#customizing-instance-and-subclass-checks">3.4.4. Customizing instance and subclass checks</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#emulating-callable-objects">3.4.5. Emulating callable objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#emulating-container-types">3.4.6. Emulating container types</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#additional-methods-for-emulation-of-sequence-types">3.4.7. Additional methods for emulation of sequence types</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#emulating-numeric-types">3.4.8. Emulating numeric types</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#coercion-rules">3.4.9. Coercion rules</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#with-statement-context-managers">3.4.10. With Statement Context Managers</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#special-method-lookup-for-old-style-classes">3.4.11. Special method lookup for old-style classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/datamodel.html#special-method-lookup-for-new-style-classes">3.4.12. Special method lookup for new-style classes</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/executionmodel.html">4. Execution model</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/executionmodel.html#naming-and-binding">4.1. Naming and binding</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/executionmodel.html#interaction-with-dynamic-features">4.1.1. Interaction with dynamic features</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/executionmodel.html#exceptions">4.2. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/expressions.html">5. Expressions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#arithmetic-conversions">5.1. Arithmetic conversions</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#atoms">5.2. Atoms</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#atom-identifiers">5.2.1. Identifiers (Names)</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#literals">5.2.2. Literals</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#parenthesized-forms">5.2.3. Parenthesized forms</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#list-displays">5.2.4. List displays</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#displays-for-sets-and-dictionaries">5.2.5. Displays for sets and dictionaries</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#generator-expressions">5.2.6. Generator expressions</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#dictionary-displays">5.2.7. Dictionary displays</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#set-displays">5.2.8. Set displays</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#string-conversions">5.2.9. String conversions</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#yield-expressions">5.2.10. Yield expressions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="reference/expressions.html#generator-iterator-methods">5.2.10.1. Generator-iterator methods</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#primaries">5.3. Primaries</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#attribute-references">5.3.1. Attribute references</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#subscriptions">5.3.2. Subscriptions</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#slicings">5.3.3. Slicings</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#calls">5.3.4. Calls</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#the-power-operator">5.4. The power operator</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#unary-arithmetic-and-bitwise-operations">5.5. Unary arithmetic and bitwise operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#binary-arithmetic-operations">5.6. Binary arithmetic operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#shifting-operations">5.7. Shifting operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#binary-bitwise-operations">5.8. Binary bitwise operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#comparisons">5.9. Comparisons</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#value-comparisons">5.9.1. Value comparisons</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#membership-test-operations">5.9.2. Membership test operations</a></li>
<li class="toctree-l4"><a class="reference internal" href="reference/expressions.html#is-not">5.9.3. Identity comparisons</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#boolean-operations">5.10. Boolean operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#conditional-expressions">5.11. Conditional Expressions</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#lambda">5.12. Lambdas</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#expression-lists">5.13. Expression lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#evaluation-order">5.14. Evaluation order</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/expressions.html#operator-precedence">5.15. Operator precedence</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/simple_stmts.html">6. Simple statements</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#expression-statements">6.1. Expression statements</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#assignment-statements">6.2. Assignment statements</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/simple_stmts.html#augmented-assignment-statements">6.2.1. Augmented assignment statements</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-assert-statement">6.3. The <code class="docutils literal notranslate"><span class="pre">assert</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-pass-statement">6.4. The <code class="docutils literal notranslate"><span class="pre">pass</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-del-statement">6.5. The <code class="docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-print-statement">6.6. The <code class="docutils literal notranslate"><span class="pre">print</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-return-statement">6.7. The <code class="docutils literal notranslate"><span class="pre">return</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-yield-statement">6.8. The <code class="docutils literal notranslate"><span class="pre">yield</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-raise-statement">6.9. The <code class="docutils literal notranslate"><span class="pre">raise</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-break-statement">6.10. The <code class="docutils literal notranslate"><span class="pre">break</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-continue-statement">6.11. The <code class="docutils literal notranslate"><span class="pre">continue</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-import-statement">6.12. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement</a><ul>
<li class="toctree-l4"><a class="reference internal" href="reference/simple_stmts.html#future-statements">6.12.1. Future statements</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-global-statement">6.13. The <code class="docutils literal notranslate"><span class="pre">global</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/simple_stmts.html#the-exec-statement">6.14. The <code class="docutils literal notranslate"><span class="pre">exec</span></code> statement</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/compound_stmts.html">7. Compound statements</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#the-if-statement">7.1. The <code class="docutils literal notranslate"><span class="pre">if</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#the-while-statement">7.2. The <code class="docutils literal notranslate"><span class="pre">while</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#the-for-statement">7.3. The <code class="docutils literal notranslate"><span class="pre">for</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#the-try-statement">7.4. The <code class="docutils literal notranslate"><span class="pre">try</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#the-with-statement">7.5. The <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#function-definitions">7.6. Function definitions</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/compound_stmts.html#class-definitions">7.7. Class definitions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/toplevel_components.html">8. Top-level components</a><ul>
<li class="toctree-l3"><a class="reference internal" href="reference/toplevel_components.html#complete-python-programs">8.1. Complete Python programs</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/toplevel_components.html#file-input">8.2. File input</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/toplevel_components.html#interactive-input">8.3. Interactive input</a></li>
<li class="toctree-l3"><a class="reference internal" href="reference/toplevel_components.html#expression-input">8.4. Expression input</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="reference/grammar.html">9. Full Grammar specification</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="library/index.html">The Python Standard Library</a><ul>
<li class="toctree-l2"><a class="reference internal" href="library/intro.html">1. Introduction</a></li>
<li class="toctree-l2"><a class="reference internal" href="library/functions.html">2. Built-in Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="library/functions.html#non-essential-built-in-functions">3. Non-essential Built-in Functions</a></li>
<li class="toctree-l2"><a class="reference internal" href="library/constants.html">4. Built-in Constants</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/constants.html#constants-added-by-the-site-module">4.1. Constants added by the <code class="docutils literal notranslate"><span class="pre">site</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/stdtypes.html">5. Built-in Types</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#truth-value-testing">5.1. Truth Value Testing</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#boolean-operations-and-or-not">5.2. Boolean Operations — <code class="docutils literal notranslate"><span class="pre">and</span></code>, <code class="docutils literal notranslate"><span class="pre">or</span></code>, <code class="docutils literal notranslate"><span class="pre">not</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#comparisons">5.3. Comparisons</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#numeric-types-int-float-long-complex">5.4. Numeric Types — <code class="docutils literal notranslate"><span class="pre">int</span></code>, <code class="docutils literal notranslate"><span class="pre">float</span></code>, <code class="docutils literal notranslate"><span class="pre">long</span></code>, <code class="docutils literal notranslate"><span class="pre">complex</span></code></a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#bitwise-operations-on-integer-types">5.4.1. Bitwise Operations on Integer Types</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#additional-methods-on-integer-types">5.4.2. Additional Methods on Integer Types</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#additional-methods-on-float">5.4.3. Additional Methods on Float</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#iterator-types">5.5. Iterator Types</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#generator-types">5.5.1. Generator Types</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange">5.6. Sequence Types — <code class="docutils literal notranslate"><span class="pre">str</span></code>, <code class="docutils literal notranslate"><span class="pre">unicode</span></code>, <code class="docutils literal notranslate"><span class="pre">list</span></code>, <code class="docutils literal notranslate"><span class="pre">tuple</span></code>, <code class="docutils literal notranslate"><span class="pre">bytearray</span></code>, <code class="docutils literal notranslate"><span class="pre">buffer</span></code>, <code class="docutils literal notranslate"><span class="pre">xrange</span></code></a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#string-methods">5.6.1. String Methods</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#string-formatting-operations">5.6.2. String Formatting Operations</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#xrange-type">5.6.3. XRange Type</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#mutable-sequence-types">5.6.4. Mutable Sequence Types</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#set-types-set-frozenset">5.7. Set Types — <code class="docutils literal notranslate"><span class="pre">set</span></code>, <code class="docutils literal notranslate"><span class="pre">frozenset</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#mapping-types-dict">5.8. Mapping Types — <code class="docutils literal notranslate"><span class="pre">dict</span></code></a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#dictionary-view-objects">5.8.1. Dictionary view objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#file-objects">5.9. File Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#memoryview-type">5.10. memoryview type</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#context-manager-types">5.11. Context Manager Types</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#other-built-in-types">5.12. Other Built-in Types</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#modules">5.12.1. Modules</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#classes-and-class-instances">5.12.2. Classes and Class Instances</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#functions">5.12.3. Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#methods">5.12.4. Methods</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#code-objects">5.12.5. Code Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#type-objects">5.12.6. Type Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#the-null-object">5.12.7. The Null Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#the-ellipsis-object">5.12.8. The Ellipsis Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#the-notimplemented-object">5.12.9. The NotImplemented Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#boolean-values">5.12.10. Boolean Values</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/stdtypes.html#internal-objects">5.12.11. Internal Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stdtypes.html#special-attributes">5.13. Special Attributes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/exceptions.html">6. Built-in Exceptions</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/exceptions.html#exception-hierarchy">6.1. Exception hierarchy</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/strings.html">7. String Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/string.html">7.1. <code class="docutils literal notranslate"><span class="pre">string</span></code> — Common string operations</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#string-constants">7.1.1. String constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#custom-string-formatting">7.1.2. Custom String Formatting</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#format-string-syntax">7.1.3. Format String Syntax</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/string.html#format-specification-mini-language">7.1.3.1. Format Specification Mini-Language</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/string.html#format-examples">7.1.3.2. Format examples</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#template-strings">7.1.4. Template strings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#string-functions">7.1.5. String functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/string.html#deprecated-string-functions">7.1.6. Deprecated string functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/re.html">7.2. <code class="docutils literal notranslate"><span class="pre">re</span></code> — Regular expression operations</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/re.html#regular-expression-syntax">7.2.1. Regular Expression Syntax</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/re.html#module-contents">7.2.2. Module Contents</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/re.html#regular-expression-objects">7.2.3. Regular Expression Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/re.html#match-objects">7.2.4. Match Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/re.html#examples">7.2.5. Examples</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#checking-for-a-pair">7.2.5.1. Checking For a Pair</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#simulating-scanf">7.2.5.2. Simulating scanf()</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#search-vs-match">7.2.5.3. search() vs. match()</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#making-a-phonebook">7.2.5.4. Making a Phonebook</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#text-munging">7.2.5.5. Text Munging</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#finding-all-adverbs">7.2.5.6. Finding all Adverbs</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#finding-all-adverbs-and-their-positions">7.2.5.7. Finding all Adverbs and their Positions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/re.html#raw-string-notation">7.2.5.8. Raw String Notation</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/struct.html">7.3. <code class="docutils literal notranslate"><span class="pre">struct</span></code> — Interpret strings as packed binary data</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/struct.html#functions-and-exceptions">7.3.1. Functions and Exceptions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/struct.html#format-strings">7.3.2. Format Strings</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/struct.html#byte-order-size-and-alignment">7.3.2.1. Byte Order, Size, and Alignment</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/struct.html#format-characters">7.3.2.2. Format Characters</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/struct.html#examples">7.3.2.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/struct.html#classes">7.3.3. Classes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/difflib.html">7.4. <code class="docutils literal notranslate"><span class="pre">difflib</span></code> — Helpers for computing deltas</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/difflib.html#sequencematcher-objects">7.4.1. SequenceMatcher Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/difflib.html#sequencematcher-examples">7.4.2. SequenceMatcher Examples</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/difflib.html#differ-objects">7.4.3. Differ Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/difflib.html#differ-example">7.4.4. Differ Example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/difflib.html#a-command-line-interface-to-difflib">7.4.5. A command-line interface to difflib</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/stringio.html">7.5. <code class="docutils literal notranslate"><span class="pre">StringIO</span></code> — Read and write strings as files</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stringio.html#module-cStringIO">7.6. <code class="docutils literal notranslate"><span class="pre">cStringIO</span></code> — Faster version of <code class="docutils literal notranslate"><span class="pre">StringIO</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/textwrap.html">7.7. <code class="docutils literal notranslate"><span class="pre">textwrap</span></code> — Text wrapping and filling</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/codecs.html">7.8. <code class="docutils literal notranslate"><span class="pre">codecs</span></code> — Codec registry and base classes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#codec-base-classes">7.8.1. Codec Base Classes</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#codec-objects">7.8.1.1. Codec Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#incrementalencoder-objects">7.8.1.2. IncrementalEncoder Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#incrementaldecoder-objects">7.8.1.3. IncrementalDecoder Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#streamwriter-objects">7.8.1.4. StreamWriter Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#streamreader-objects">7.8.1.5. StreamReader Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#streamreaderwriter-objects">7.8.1.6. StreamReaderWriter Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/codecs.html#streamrecoder-objects">7.8.1.7. StreamRecoder Objects</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#encodings-and-unicode">7.8.2. Encodings and Unicode</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#standard-encodings">7.8.3. Standard Encodings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#python-specific-encodings">7.8.4. Python Specific Encodings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#module-encodings.idna">7.8.5. <code class="docutils literal notranslate"><span class="pre">encodings.idna</span></code> — Internationalized Domain Names in Applications</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/codecs.html#module-encodings.utf_8_sig">7.8.6. <code class="docutils literal notranslate"><span class="pre">encodings.utf_8_sig</span></code> — UTF-8 codec with BOM signature</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/unicodedata.html">7.9. <code class="docutils literal notranslate"><span class="pre">unicodedata</span></code> — Unicode Database</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stringprep.html">7.10. <code class="docutils literal notranslate"><span class="pre">stringprep</span></code> — Internet String Preparation</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fpformat.html">7.11. <code class="docutils literal notranslate"><span class="pre">fpformat</span></code> — Floating point conversions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/datatypes.html">8. Data Types</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/datetime.html">8.1. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> — Basic date and time types</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#available-types">8.1.1. Available Types</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#timedelta-objects">8.1.2. <code class="docutils literal notranslate"><span class="pre">timedelta</span></code> Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#date-objects">8.1.3. <code class="docutils literal notranslate"><span class="pre">date</span></code> Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#datetime-objects">8.1.4. <code class="docutils literal notranslate"><span class="pre">datetime</span></code> Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#time-objects">8.1.5. <code class="docutils literal notranslate"><span class="pre">time</span></code> Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#tzinfo-objects">8.1.6. <code class="docutils literal notranslate"><span class="pre">tzinfo</span></code> Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/datetime.html#strftime-and-strptime-behavior">8.1.7. <code class="docutils literal notranslate"><span class="pre">strftime()</span></code> and <code class="docutils literal notranslate"><span class="pre">strptime()</span></code> Behavior</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/calendar.html">8.2. <code class="docutils literal notranslate"><span class="pre">calendar</span></code> — General calendar-related functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/collections.html">8.3. <code class="docutils literal notranslate"><span class="pre">collections</span></code> — High-performance container datatypes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#counter-objects">8.3.1. <code class="docutils literal notranslate"><span class="pre">Counter</span></code> objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#deque-objects">8.3.2. <code class="docutils literal notranslate"><span class="pre">deque</span></code> objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/collections.html#deque-recipes">8.3.2.1. <code class="docutils literal notranslate"><span class="pre">deque</span></code> Recipes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#defaultdict-objects">8.3.3. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/collections.html#defaultdict-examples">8.3.3.1. <code class="docutils literal notranslate"><span class="pre">defaultdict</span></code> Examples</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields">8.3.4. <code class="docutils literal notranslate"><span class="pre">namedtuple()</span></code> Factory Function for Tuples with Named Fields</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#ordereddict-objects">8.3.5. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/collections.html#ordereddict-examples-and-recipes">8.3.5.1. <code class="docutils literal notranslate"><span class="pre">OrderedDict</span></code> Examples and Recipes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/collections.html#collections-abstract-base-classes">8.3.6. Collections Abstract Base Classes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/heapq.html">8.4. <code class="docutils literal notranslate"><span class="pre">heapq</span></code> — Heap queue algorithm</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/heapq.html#basic-examples">8.4.1. Basic Examples</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/heapq.html#priority-queue-implementation-notes">8.4.2. Priority Queue Implementation Notes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/heapq.html#theory">8.4.3. Theory</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/bisect.html">8.5. <code class="docutils literal notranslate"><span class="pre">bisect</span></code> — Array bisection algorithm</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/bisect.html#searching-sorted-lists">8.5.1. Searching Sorted Lists</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/bisect.html#other-examples">8.5.2. Other Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/array.html">8.6. <code class="docutils literal notranslate"><span class="pre">array</span></code> — Efficient arrays of numeric values</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/sets.html">8.7. <code class="docutils literal notranslate"><span class="pre">sets</span></code> — Unordered collections of unique elements</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sets.html#set-objects">8.7.1. Set Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sets.html#example">8.7.2. Example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sets.html#protocol-for-automatic-conversion-to-immutable">8.7.3. Protocol for automatic conversion to immutable</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sets.html#comparison-to-the-built-in-set-types">8.7.4. Comparison to the built-in <code class="docutils literal notranslate"><span class="pre">set</span></code> types</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/sched.html">8.8. <code class="docutils literal notranslate"><span class="pre">sched</span></code> — Event scheduler</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sched.html#scheduler-objects">8.8.1. Scheduler Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mutex.html">8.9. <code class="docutils literal notranslate"><span class="pre">mutex</span></code> — Mutual exclusion support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mutex.html#mutex-objects">8.9.1. Mutex Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/queue.html">8.10. <code class="docutils literal notranslate"><span class="pre">Queue</span></code> — A synchronized queue class</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/queue.html#queue-objects">8.10.1. Queue Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/weakref.html">8.11. <code class="docutils literal notranslate"><span class="pre">weakref</span></code> — Weak references</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/weakref.html#weak-reference-objects">8.11.1. Weak Reference Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/weakref.html#example">8.11.2. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/userdict.html">8.12. <code class="docutils literal notranslate"><span class="pre">UserDict</span></code> — Class wrapper for dictionary objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/userdict.html#module-UserList">8.13. <code class="docutils literal notranslate"><span class="pre">UserList</span></code> — Class wrapper for list objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/userdict.html#module-UserString">8.14. <code class="docutils literal notranslate"><span class="pre">UserString</span></code> — Class wrapper for string objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/types.html">8.15. <code class="docutils literal notranslate"><span class="pre">types</span></code> — Names for built-in types</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/new.html">8.16. <code class="docutils literal notranslate"><span class="pre">new</span></code> — Creation of runtime internal objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/copy.html">8.17. <code class="docutils literal notranslate"><span class="pre">copy</span></code> — Shallow and deep copy operations</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pprint.html">8.18. <code class="docutils literal notranslate"><span class="pre">pprint</span></code> — Data pretty printer</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/pprint.html#prettyprinter-objects">8.18.1. PrettyPrinter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pprint.html#pprint-example">8.18.2. pprint Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/repr.html">8.19. <code class="docutils literal notranslate"><span class="pre">repr</span></code> — Alternate <code class="docutils literal notranslate"><span class="pre">repr()</span></code> implementation</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/repr.html#repr-objects">8.19.1. Repr Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/repr.html#subclassing-repr-objects">8.19.2. Subclassing Repr Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/numeric.html">9. Numeric and Mathematical Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/numbers.html">9.1. <code class="docutils literal notranslate"><span class="pre">numbers</span></code> — Numeric abstract base classes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/numbers.html#the-numeric-tower">9.1.1. The numeric tower</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/numbers.html#notes-for-type-implementors">9.1.2. Notes for type implementors</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/numbers.html#adding-more-numeric-abcs">9.1.2.1. Adding More Numeric ABCs</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/numbers.html#implementing-the-arithmetic-operations">9.1.2.2. Implementing the arithmetic operations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/math.html">9.2. <code class="docutils literal notranslate"><span class="pre">math</span></code> — Mathematical functions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#number-theoretic-and-representation-functions">9.2.1. Number-theoretic and representation functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#power-and-logarithmic-functions">9.2.2. Power and logarithmic functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#trigonometric-functions">9.2.3. Trigonometric functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#angular-conversion">9.2.4. Angular conversion</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#hyperbolic-functions">9.2.5. Hyperbolic functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#special-functions">9.2.6. Special functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/math.html#constants">9.2.7. Constants</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/cmath.html">9.3. <code class="docutils literal notranslate"><span class="pre">cmath</span></code> — Mathematical functions for complex numbers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#conversions-to-and-from-polar-coordinates">9.3.1. Conversions to and from polar coordinates</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#power-and-logarithmic-functions">9.3.2. Power and logarithmic functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#trigonometric-functions">9.3.3. Trigonometric functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#hyperbolic-functions">9.3.4. Hyperbolic functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#classification-functions">9.3.5. Classification functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cmath.html#constants">9.3.6. Constants</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/decimal.html">9.4. <code class="docutils literal notranslate"><span class="pre">decimal</span></code> — Decimal fixed point and floating point arithmetic</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#quick-start-tutorial">9.4.1. Quick-start Tutorial</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#decimal-objects">9.4.2. Decimal objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/decimal.html#logical-operands">9.4.2.1. Logical operands</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#context-objects">9.4.3. Context objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#signals">9.4.4. Signals</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#floating-point-notes">9.4.5. Floating Point Notes</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/decimal.html#mitigating-round-off-error-with-increased-precision">9.4.5.1. Mitigating round-off error with increased precision</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/decimal.html#special-values">9.4.5.2. Special values</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#working-with-threads">9.4.6. Working with threads</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#recipes">9.4.7. Recipes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/decimal.html#decimal-faq">9.4.8. Decimal FAQ</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/fractions.html">9.5. <code class="docutils literal notranslate"><span class="pre">fractions</span></code> — Rational numbers</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/random.html">9.6. <code class="docutils literal notranslate"><span class="pre">random</span></code> — Generate pseudo-random numbers</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/itertools.html">9.7. <code class="docutils literal notranslate"><span class="pre">itertools</span></code> — Functions creating iterators for efficient looping</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/itertools.html#itertool-functions">9.7.1. Itertool functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/itertools.html#recipes">9.7.2. Recipes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/functools.html">9.8. <code class="docutils literal notranslate"><span class="pre">functools</span></code> — Higher-order functions and operations on callable objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/functools.html#partial-objects">9.8.1. <code class="docutils literal notranslate"><span class="pre">partial</span></code> Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/operator.html">9.9. <code class="docutils literal notranslate"><span class="pre">operator</span></code> — Standard operators as functions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/operator.html#mapping-operators-to-functions">9.9.1. Mapping Operators to Functions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/filesys.html">10. File and Directory Access</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/os.path.html">10.1. <code class="docutils literal notranslate"><span class="pre">os.path</span></code> — Common pathname manipulations</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fileinput.html">10.2. <code class="docutils literal notranslate"><span class="pre">fileinput</span></code> — Iterate over lines from multiple input streams</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/stat.html">10.3. <code class="docutils literal notranslate"><span class="pre">stat</span></code> — Interpreting <code class="docutils literal notranslate"><span class="pre">stat()</span></code> results</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/statvfs.html">10.4. <code class="docutils literal notranslate"><span class="pre">statvfs</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">os.statvfs()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/filecmp.html">10.5. <code class="docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/filecmp.html#the-dircmp-class">10.5.1. The <code class="docutils literal notranslate"><span class="pre">dircmp</span></code> class</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/tempfile.html">10.6. <code class="docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/glob.html">10.7. <code class="docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fnmatch.html">10.8. <code class="docutils literal notranslate"><span class="pre">fnmatch</span></code> — Unix filename pattern matching</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/linecache.html">10.9. <code class="docutils literal notranslate"><span class="pre">linecache</span></code> — Random access to text lines</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/shutil.html">10.10. <code class="docutils literal notranslate"><span class="pre">shutil</span></code> — High-level file operations</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/shutil.html#directory-and-files-operations">10.10.1. Directory and files operations</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/shutil.html#copytree-example">10.10.1.1. copytree example</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/shutil.html#archiving-operations">10.10.2. Archiving operations</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/shutil.html#archiving-example">10.10.2.1. Archiving example</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/dircache.html">10.11. <code class="docutils literal notranslate"><span class="pre">dircache</span></code> — Cached directory listings</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/macpath.html">10.12. <code class="docutils literal notranslate"><span class="pre">macpath</span></code> — Mac OS 9 path manipulation functions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/persistence.html">11. Data Persistence</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/pickle.html">11.1. <code class="docutils literal notranslate"><span class="pre">pickle</span></code> — Python object serialization</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#relationship-to-other-python-modules">11.1.1. Relationship to other Python modules</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#data-stream-format">11.1.2. Data stream format</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#usage">11.1.3. Usage</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#what-can-be-pickled-and-unpickled">11.1.4. What can be pickled and unpickled?</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#the-pickle-protocol">11.1.5. The pickle protocol</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/pickle.html#pickling-and-unpickling-normal-class-instances">11.1.5.1. Pickling and unpickling normal class instances</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/pickle.html#pickling-and-unpickling-extension-types">11.1.5.2. Pickling and unpickling extension types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/pickle.html#pickling-and-unpickling-external-objects">11.1.5.3. Pickling and unpickling external objects</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#subclassing-unpicklers">11.1.6. Subclassing Unpicklers</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pickle.html#example">11.1.7. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/pickle.html#module-cPickle">11.2. <code class="docutils literal notranslate"><span class="pre">cPickle</span></code> — A faster <code class="docutils literal notranslate"><span class="pre">pickle</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/copy_reg.html">11.3. <code class="docutils literal notranslate"><span class="pre">copy_reg</span></code> — Register <code class="docutils literal notranslate"><span class="pre">pickle</span></code> support functions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/copy_reg.html#example">11.3.1. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/shelve.html">11.4. <code class="docutils literal notranslate"><span class="pre">shelve</span></code> — Python object persistence</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/shelve.html#restrictions">11.4.1. Restrictions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/shelve.html#example">11.4.2. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/marshal.html">11.5. <code class="docutils literal notranslate"><span class="pre">marshal</span></code> — Internal Python object serialization</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/anydbm.html">11.6. <code class="docutils literal notranslate"><span class="pre">anydbm</span></code> — Generic access to DBM-style databases</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/whichdb.html">11.7. <code class="docutils literal notranslate"><span class="pre">whichdb</span></code> — Guess which DBM module created a database</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/dbm.html">11.8. <code class="docutils literal notranslate"><span class="pre">dbm</span></code> — Simple “database” interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gdbm.html">11.9. <code class="docutils literal notranslate"><span class="pre">gdbm</span></code> — GNU’s reinterpretation of dbm</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/dbhash.html">11.10. <code class="docutils literal notranslate"><span class="pre">dbhash</span></code> — DBM-style interface to the BSD database library</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/dbhash.html#database-objects">11.10.1. Database Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/bsddb.html">11.11. <code class="docutils literal notranslate"><span class="pre">bsddb</span></code> — Interface to Berkeley DB library</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/bsddb.html#hash-btree-and-record-objects">11.11.1. Hash, BTree and Record Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/dumbdbm.html">11.12. <code class="docutils literal notranslate"><span class="pre">dumbdbm</span></code> — Portable DBM implementation</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/dumbdbm.html#dumbdbm-objects">11.12.1. Dumbdbm Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/sqlite3.html">11.13. <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> — DB-API 2.0 interface for SQLite databases</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#module-functions-and-constants">11.13.1. Module functions and constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#connection-objects">11.13.2. Connection Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#cursor-objects">11.13.3. Cursor Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#row-objects">11.13.4. Row Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#sqlite-and-python-types">11.13.5. SQLite and Python types</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#introduction">11.13.5.1. Introduction</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#using-adapters-to-store-additional-python-types-in-sqlite-databases">11.13.5.2. Using adapters to store additional Python types in SQLite databases</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/sqlite3.html#letting-your-object-adapt-itself">11.13.5.2.1. Letting your object adapt itself</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/sqlite3.html#registering-an-adapter-callable">11.13.5.2.2. Registering an adapter callable</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#converting-sqlite-values-to-custom-python-types">11.13.5.3. Converting SQLite values to custom Python types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#default-adapters-and-converters">11.13.5.4. Default adapters and converters</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#controlling-transactions">11.13.6. Controlling Transactions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#using-sqlite3-efficiently">11.13.7. Using <code class="docutils literal notranslate"><span class="pre">sqlite3</span></code> efficiently</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#using-shortcut-methods">11.13.7.1. Using shortcut methods</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#accessing-columns-by-name-instead-of-by-index">11.13.7.2. Accessing columns by name instead of by index</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#using-the-connection-as-a-context-manager">11.13.7.3. Using the connection as a context manager</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/sqlite3.html#common-issues">11.13.8. Common issues</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/sqlite3.html#multithreading">11.13.8.1. Multithreading</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/archiving.html">12. Data Compression and Archiving</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/zlib.html">12.1. <code class="docutils literal notranslate"><span class="pre">zlib</span></code> — Compression compatible with <strong class="program">gzip</strong></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gzip.html">12.2. <code class="docutils literal notranslate"><span class="pre">gzip</span></code> — Support for <strong class="program">gzip</strong> files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/gzip.html#examples-of-usage">12.2.1. Examples of usage</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/bz2.html">12.3. <code class="docutils literal notranslate"><span class="pre">bz2</span></code> — Compression compatible with <strong class="program">bzip2</strong></a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/bz2.html#de-compression-of-files">12.3.1. (De)compression of files</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/bz2.html#sequential-de-compression">12.3.2. Sequential (de)compression</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/bz2.html#one-shot-de-compression">12.3.3. One-shot (de)compression</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/zipfile.html">12.4. <code class="docutils literal notranslate"><span class="pre">zipfile</span></code> — Work with ZIP archives</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/zipfile.html#zipfile-objects">12.4.1. ZipFile Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/zipfile.html#pyzipfile-objects">12.4.2. PyZipFile Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/zipfile.html#zipinfo-objects">12.4.3. ZipInfo Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/zipfile.html#command-line-interface">12.4.4. Command-Line Interface</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/zipfile.html#command-line-options">12.4.4.1. Command-line options</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/tarfile.html">12.5. <code class="docutils literal notranslate"><span class="pre">tarfile</span></code> — Read and write tar archive files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/tarfile.html#tarfile-objects">12.5.1. TarFile Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tarfile.html#tarinfo-objects">12.5.2. TarInfo Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tarfile.html#examples">12.5.3. Examples</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tarfile.html#supported-tar-formats">12.5.4. Supported tar formats</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tarfile.html#unicode-issues">12.5.5. Unicode issues</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/fileformats.html">13. File Formats</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/csv.html">13.1. <code class="docutils literal notranslate"><span class="pre">csv</span></code> — CSV File Reading and Writing</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/csv.html#module-contents">13.1.1. Module Contents</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/csv.html#dialects-and-formatting-parameters">13.1.2. Dialects and Formatting Parameters</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/csv.html#reader-objects">13.1.3. Reader Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/csv.html#writer-objects">13.1.4. Writer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/csv.html#examples">13.1.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/configparser.html">13.2. <code class="docutils literal notranslate"><span class="pre">ConfigParser</span></code> — Configuration file parser</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/configparser.html#rawconfigparser-objects">13.2.1. RawConfigParser Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/configparser.html#configparser-objects">13.2.2. ConfigParser Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/configparser.html#safeconfigparser-objects">13.2.3. SafeConfigParser Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/configparser.html#examples">13.2.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/robotparser.html">13.3. <code class="docutils literal notranslate"><span class="pre">robotparser</span></code> —  Parser for robots.txt</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/netrc.html">13.4. <code class="docutils literal notranslate"><span class="pre">netrc</span></code> — netrc file processing</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/netrc.html#netrc-objects">13.4.1. netrc Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xdrlib.html">13.5. <code class="docutils literal notranslate"><span class="pre">xdrlib</span></code> — Encode and decode XDR data</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xdrlib.html#packer-objects">13.5.1. Packer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xdrlib.html#unpacker-objects">13.5.2. Unpacker Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xdrlib.html#exceptions">13.5.3. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/plistlib.html">13.6. <code class="docutils literal notranslate"><span class="pre">plistlib</span></code> — Generate and parse Mac OS X <code class="docutils literal notranslate"><span class="pre">.plist</span></code> files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/plistlib.html#examples">13.6.1. Examples</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/crypto.html">14. Cryptographic Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/hashlib.html">14.1. <code class="docutils literal notranslate"><span class="pre">hashlib</span></code> — Secure hashes and message digests</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/hashlib.html#key-derivation">14.1.1. Key derivation</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/hmac.html">14.2. <code class="docutils literal notranslate"><span class="pre">hmac</span></code> — Keyed-Hashing for Message Authentication</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/md5.html">14.3. <code class="docutils literal notranslate"><span class="pre">md5</span></code> — MD5 message digest algorithm</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/sha.html">14.4. <code class="docutils literal notranslate"><span class="pre">sha</span></code> — SHA-1 message digest algorithm</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/allos.html">15. Generic Operating System Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/os.html">15.1. <code class="docutils literal notranslate"><span class="pre">os</span></code> — Miscellaneous operating system interfaces</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#process-parameters">15.1.1. Process Parameters</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#file-object-creation">15.1.2. File Object Creation</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#file-descriptor-operations">15.1.3. File Descriptor Operations</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/os.html#open-flag-constants">15.1.3.1. <code class="docutils literal notranslate"><span class="pre">open()</span></code> flag constants</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#files-and-directories">15.1.4. Files and Directories</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#process-management">15.1.5. Process Management</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#miscellaneous-system-information">15.1.6. Miscellaneous System Information</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/os.html#miscellaneous-functions">15.1.7. Miscellaneous Functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/io.html">15.2. <code class="docutils literal notranslate"><span class="pre">io</span></code> — Core tools for working with streams</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#module-interface">15.2.1. Module Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#i-o-base-classes">15.2.2. I/O Base Classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#raw-file-i-o">15.2.3. Raw File I/O</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#buffered-streams">15.2.4. Buffered Streams</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#text-i-o">15.2.5. Text I/O</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/io.html#advanced-topics">15.2.6. Advanced topics</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/io.html#performance">15.2.6.1. Performance</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/io.html#binary-i-o">15.2.6.1.1. Binary I/O</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/io.html#id1">15.2.6.1.2. Text I/O</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/io.html#multi-threading">15.2.6.2. Multi-threading</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/io.html#reentrancy">15.2.6.3. Reentrancy</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/time.html">15.3. <code class="docutils literal notranslate"><span class="pre">time</span></code> — Time access and conversions</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/argparse.html">15.4. <code class="docutils literal notranslate"><span class="pre">argparse</span></code> — Parser for command-line options, arguments and sub-commands</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#example">15.4.1. Example</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#creating-a-parser">15.4.1.1. Creating a parser</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#adding-arguments">15.4.1.2. Adding arguments</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#parsing-arguments">15.4.1.3. Parsing arguments</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#argumentparser-objects">15.4.2. ArgumentParser objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#prog">15.4.2.1. prog</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#usage">15.4.2.2. usage</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#description">15.4.2.3. description</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#epilog">15.4.2.4. epilog</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#parents">15.4.2.5. parents</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#formatter-class">15.4.2.6. formatter_class</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#prefix-chars">15.4.2.7. prefix_chars</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#fromfile-prefix-chars">15.4.2.8. fromfile_prefix_chars</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#argument-default">15.4.2.9. argument_default</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#conflict-handler">15.4.2.10. conflict_handler</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#add-help">15.4.2.11. add_help</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#the-add-argument-method">15.4.3. The add_argument() method</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#name-or-flags">15.4.3.1. name or flags</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#action">15.4.3.2. action</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#nargs">15.4.3.3. nargs</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#const">15.4.3.4. const</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#default">15.4.3.5. default</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#type">15.4.3.6. type</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#choices">15.4.3.7. choices</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#required">15.4.3.8. required</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#help">15.4.3.9. help</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#metavar">15.4.3.10. metavar</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#dest">15.4.3.11. dest</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#action-classes">15.4.3.12. Action classes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#the-parse-args-method">15.4.4. The parse_args() method</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#option-value-syntax">15.4.4.1. Option value syntax</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#invalid-arguments">15.4.4.2. Invalid arguments</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#arguments-containing">15.4.4.3. Arguments containing <code class="docutils literal notranslate"><span class="pre">-</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#argument-abbreviations-prefix-matching">15.4.4.4. Argument abbreviations (prefix matching)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#beyond-sys-argv">15.4.4.5. Beyond <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#the-namespace-object">15.4.4.6. The Namespace object</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#other-utilities">15.4.5. Other utilities</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#sub-commands">15.4.5.1. Sub-commands</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#filetype-objects">15.4.5.2. FileType objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#argument-groups">15.4.5.3. Argument groups</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#mutual-exclusion">15.4.5.4. Mutual exclusion</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#parser-defaults">15.4.5.5. Parser defaults</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#printing-help">15.4.5.6. Printing help</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#partial-parsing">15.4.5.7. Partial parsing</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#customizing-file-parsing">15.4.5.8. Customizing file parsing</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/argparse.html#exiting-methods">15.4.5.9. Exiting methods</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/argparse.html#upgrading-optparse-code">15.4.6. Upgrading optparse code</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/optparse.html">15.5. <code class="docutils literal notranslate"><span class="pre">optparse</span></code> — Parser for command line options</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/optparse.html#background">15.5.1. Background</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#terminology">15.5.1.1. Terminology</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#what-are-options-for">15.5.1.2. What are options for?</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#what-are-positional-arguments-for">15.5.1.3. What are positional arguments for?</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/optparse.html#tutorial">15.5.2. Tutorial</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#understanding-option-actions">15.5.2.1. Understanding option actions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#the-store-action">15.5.2.2. The store action</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#handling-boolean-flag-options">15.5.2.3. Handling boolean (flag) options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#other-actions">15.5.2.4. Other actions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#default-values">15.5.2.5. Default values</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#generating-help">15.5.2.6. Generating help</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/optparse.html#grouping-options">15.5.2.6.1. Grouping Options</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#printing-a-version-string">15.5.2.7. Printing a version string</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#how-optparse-handles-errors">15.5.2.8. How <code class="docutils literal notranslate"><span class="pre">optparse</span></code> handles errors</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#putting-it-all-together">15.5.2.9. Putting it all together</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/optparse.html#reference-guide">15.5.3. Reference Guide</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#creating-the-parser">15.5.3.1. Creating the parser</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#populating-the-parser">15.5.3.2. Populating the parser</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#defining-options">15.5.3.3. Defining options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#option-attributes">15.5.3.4. Option attributes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#standard-option-actions">15.5.3.5. Standard option actions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#standard-option-types">15.5.3.6. Standard option types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#parsing-arguments">15.5.3.7. Parsing arguments</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#querying-and-manipulating-your-option-parser">15.5.3.8. Querying and manipulating your option parser</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#conflicts-between-options">15.5.3.9. Conflicts between options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#cleanup">15.5.3.10. Cleanup</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#other-methods">15.5.3.11. Other methods</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/optparse.html#option-callbacks">15.5.4. Option Callbacks</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#defining-a-callback-option">15.5.4.1. Defining a callback option</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#how-callbacks-are-called">15.5.4.2. How callbacks are called</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#raising-errors-in-a-callback">15.5.4.3. Raising errors in a callback</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-1-trivial-callback">15.5.4.4. Callback example 1: trivial callback</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-2-check-option-order">15.5.4.5. Callback example 2: check option order</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-3-check-option-order-generalized">15.5.4.6. Callback example 3: check option order (generalized)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-4-check-arbitrary-condition">15.5.4.7. Callback example 4: check arbitrary condition</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-5-fixed-arguments">15.5.4.8. Callback example 5: fixed arguments</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#callback-example-6-variable-arguments">15.5.4.9. Callback example 6: variable arguments</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/optparse.html#extending-optparse">15.5.5. Extending <code class="docutils literal notranslate"><span class="pre">optparse</span></code></a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#adding-new-types">15.5.5.1. Adding new types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/optparse.html#adding-new-actions">15.5.5.2. Adding new actions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/getopt.html">15.6. <code class="docutils literal notranslate"><span class="pre">getopt</span></code> — C-style parser for command line options</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/logging.html">15.7. <code class="docutils literal notranslate"><span class="pre">logging</span></code> — Logging facility for Python</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#logger-objects">15.7.1. Logger Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#logging-levels">15.7.2. Logging Levels</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#handler-objects">15.7.3. Handler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#formatter-objects">15.7.4. Formatter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#filter-objects">15.7.5. Filter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#logrecord-objects">15.7.6. LogRecord Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#logrecord-attributes">15.7.7. LogRecord attributes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#loggeradapter-objects">15.7.8. LoggerAdapter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#thread-safety">15.7.9. Thread Safety</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#module-level-functions">15.7.10. Module-Level Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.html#integration-with-the-warnings-module">15.7.11. Integration with the warnings module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/logging.config.html">15.8. <code class="docutils literal notranslate"><span class="pre">logging.config</span></code> — Logging configuration</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/logging.config.html#configuration-functions">15.8.1. Configuration functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.config.html#configuration-dictionary-schema">15.8.2. Configuration dictionary schema</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#dictionary-schema-details">15.8.2.1. Dictionary Schema Details</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#incremental-configuration">15.8.2.2. Incremental Configuration</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#object-connections">15.8.2.3. Object connections</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#user-defined-objects">15.8.2.4. User-defined objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#access-to-external-objects">15.8.2.5. Access to external objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#access-to-internal-objects">15.8.2.6. Access to internal objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/logging.config.html#import-resolution-and-custom-importers">15.8.2.7. Import resolution and custom importers</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.config.html#configuration-file-format">15.8.3. Configuration file format</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/logging.handlers.html">15.9. <code class="docutils literal notranslate"><span class="pre">logging.handlers</span></code> — Logging handlers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#streamhandler">15.9.1. StreamHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#filehandler">15.9.2. FileHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#nullhandler">15.9.3. NullHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#watchedfilehandler">15.9.4. WatchedFileHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#rotatingfilehandler">15.9.5. RotatingFileHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#timedrotatingfilehandler">15.9.6. TimedRotatingFileHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#sockethandler">15.9.7. SocketHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#datagramhandler">15.9.8. DatagramHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#sysloghandler">15.9.9. SysLogHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#nteventloghandler">15.9.10. NTEventLogHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#smtphandler">15.9.11. SMTPHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#memoryhandler">15.9.12. MemoryHandler</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/logging.handlers.html#httphandler">15.9.13. HTTPHandler</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/getpass.html">15.10. <code class="docutils literal notranslate"><span class="pre">getpass</span></code> — Portable password input</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/curses.html">15.11. <code class="docutils literal notranslate"><span class="pre">curses</span></code> — Terminal handling for character-cell displays</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/curses.html#functions">15.11.1. Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/curses.html#window-objects">15.11.2. Window Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/curses.html#constants">15.11.3. Constants</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/curses.html#module-curses.textpad">15.12. <code class="docutils literal notranslate"><span class="pre">curses.textpad</span></code> — Text input widget for curses programs</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/curses.html#textbox-objects">15.12.1. Textbox objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/curses.ascii.html">15.13. <code class="docutils literal notranslate"><span class="pre">curses.ascii</span></code> — Utilities for ASCII characters</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/curses.panel.html">15.14. <code class="docutils literal notranslate"><span class="pre">curses.panel</span></code> — A panel stack extension for curses</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/curses.panel.html#functions">15.14.1. Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/curses.panel.html#panel-objects">15.14.2. Panel Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/platform.html">15.15. <code class="docutils literal notranslate"><span class="pre">platform</span></code> —  Access to underlying platform’s identifying data</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/platform.html#cross-platform">15.15.1. Cross Platform</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/platform.html#java-platform">15.15.2. Java Platform</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/platform.html#windows-platform">15.15.3. Windows Platform</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/platform.html#win95-98-specific">15.15.3.1. Win95/98 specific</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/platform.html#mac-os-platform">15.15.4. Mac OS Platform</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/platform.html#unix-platforms">15.15.5. Unix Platforms</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/errno.html">15.16. <code class="docutils literal notranslate"><span class="pre">errno</span></code> — Standard errno system symbols</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/ctypes.html">15.17. <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> — A foreign function library for Python</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ctypes.html#ctypes-tutorial">15.17.1. ctypes tutorial</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#loading-dynamic-link-libraries">15.17.1.1. Loading dynamic link libraries</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#accessing-functions-from-loaded-dlls">15.17.1.2. Accessing functions from loaded dlls</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#calling-functions">15.17.1.3. Calling functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#fundamental-data-types">15.17.1.4. Fundamental data types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#calling-functions-continued">15.17.1.5. Calling functions, continued</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#calling-functions-with-your-own-custom-data-types">15.17.1.6. Calling functions with your own custom data types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#specifying-the-required-argument-types-function-prototypes">15.17.1.7. Specifying the required argument types (function prototypes)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#return-types">15.17.1.8. Return types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#passing-pointers-or-passing-parameters-by-reference">15.17.1.9. Passing pointers (or: passing parameters by reference)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#structures-and-unions">15.17.1.10. Structures and unions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#structure-union-alignment-and-byte-order">15.17.1.11. Structure/union alignment and byte order</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#bit-fields-in-structures-and-unions">15.17.1.12. Bit fields in structures and unions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#arrays">15.17.1.13. Arrays</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#pointers">15.17.1.14. Pointers</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#type-conversions">15.17.1.15. Type conversions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#incomplete-types">15.17.1.16. Incomplete Types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#callback-functions">15.17.1.17. Callback functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#accessing-values-exported-from-dlls">15.17.1.18. Accessing values exported from dlls</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#surprises">15.17.1.19. Surprises</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#variable-sized-data-types">15.17.1.20. Variable-sized data types</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ctypes.html#ctypes-reference">15.17.2. ctypes reference</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#finding-shared-libraries">15.17.2.1. Finding shared libraries</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#loading-shared-libraries">15.17.2.2. Loading shared libraries</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#foreign-functions">15.17.2.3. Foreign functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#function-prototypes">15.17.2.4. Function prototypes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#utility-functions">15.17.2.5. Utility functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#data-types">15.17.2.6. Data types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#ctypes-fundamental-data-types-2">15.17.2.7. Fundamental data types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#structured-data-types">15.17.2.8. Structured data types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ctypes.html#arrays-and-pointers">15.17.2.9. Arrays and pointers</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/someos.html">16. Optional Operating System Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/select.html">16.1. <code class="docutils literal notranslate"><span class="pre">select</span></code> — Waiting for I/O completion</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/select.html#edge-and-level-trigger-polling-epoll-objects">16.1.1. Edge and Level Trigger Polling (epoll) Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/select.html#polling-objects">16.1.2. Polling Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/select.html#kqueue-objects">16.1.3. Kqueue Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/select.html#kevent-objects">16.1.4. Kevent Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/threading.html">16.2. <code class="docutils literal notranslate"><span class="pre">threading</span></code> — Higher-level threading interface</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#thread-objects">16.2.1. Thread Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#lock-objects">16.2.2. Lock Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#rlock-objects">16.2.3. RLock Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#condition-objects">16.2.4. Condition Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#semaphore-objects">16.2.5. Semaphore Objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/threading.html#semaphore-example">16.2.5.1. <code class="docutils literal notranslate"><span class="pre">Semaphore</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#event-objects">16.2.6. Event Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#timer-objects">16.2.7. Timer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#using-locks-conditions-and-semaphores-in-the-with-statement">16.2.8. Using locks, conditions, and semaphores in the <code class="docutils literal notranslate"><span class="pre">with</span></code> statement</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/threading.html#importing-in-threaded-code">16.2.9. Importing in threaded code</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/thread.html">16.3. <code class="docutils literal notranslate"><span class="pre">thread</span></code> — Multiple threads of control</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/dummy_threading.html">16.4. <code class="docutils literal notranslate"><span class="pre">dummy_threading</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">threading</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/dummy_thread.html">16.5. <code class="docutils literal notranslate"><span class="pre">dummy_thread</span></code> — Drop-in replacement for the <code class="docutils literal notranslate"><span class="pre">thread</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/multiprocessing.html">16.6. <code class="docutils literal notranslate"><span class="pre">multiprocessing</span></code> — Process-based “threading” interface</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/multiprocessing.html#introduction">16.6.1. Introduction</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#the-process-class">16.6.1.1. The <code class="docutils literal notranslate"><span class="pre">Process</span></code> class</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#exchanging-objects-between-processes">16.6.1.2. Exchanging objects between processes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#synchronization-between-processes">16.6.1.3. Synchronization between processes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#sharing-state-between-processes">16.6.1.4. Sharing state between processes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#using-a-pool-of-workers">16.6.1.5. Using a pool of workers</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/multiprocessing.html#reference">16.6.2. Reference</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#process-and-exceptions">16.6.2.1. <code class="docutils literal notranslate"><span class="pre">Process</span></code> and exceptions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#pipes-and-queues">16.6.2.2. Pipes and Queues</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#miscellaneous">16.6.2.3. Miscellaneous</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#connection-objects">16.6.2.4. Connection Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#synchronization-primitives">16.6.2.5. Synchronization primitives</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#shared-ctypes-objects">16.6.2.6. Shared <code class="docutils literal notranslate"><span class="pre">ctypes</span></code> Objects</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/multiprocessing.html#module-multiprocessing.sharedctypes">16.6.2.6.1. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.sharedctypes</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#managers">16.6.2.7. Managers</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/multiprocessing.html#customized-managers">16.6.2.7.1. Customized managers</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/multiprocessing.html#using-a-remote-manager">16.6.2.7.2. Using a remote manager</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#proxy-objects">16.6.2.8. Proxy Objects</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/multiprocessing.html#cleanup">16.6.2.8.1. Cleanup</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#module-multiprocessing.pool">16.6.2.9. Process Pools</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#module-multiprocessing.connection">16.6.2.10. Listeners and Clients</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/multiprocessing.html#address-formats">16.6.2.10.1. Address Formats</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#authentication-keys">16.6.2.11. Authentication keys</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#logging">16.6.2.12. Logging</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#module-multiprocessing.dummy">16.6.2.13. The <code class="docutils literal notranslate"><span class="pre">multiprocessing.dummy</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/multiprocessing.html#programming-guidelines">16.6.3. Programming guidelines</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#all-platforms">16.6.3.1. All platforms</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/multiprocessing.html#windows">16.6.3.2. Windows</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/multiprocessing.html#examples">16.6.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mmap.html">16.7. <code class="docutils literal notranslate"><span class="pre">mmap</span></code> — Memory-mapped file support</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/readline.html">16.8. <code class="docutils literal notranslate"><span class="pre">readline</span></code> — GNU readline interface</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#init-file">16.8.1. Init file</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#line-buffer">16.8.2. Line buffer</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#history-file">16.8.3. History file</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#history-list">16.8.4. History list</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#startup-hooks">16.8.5. Startup hooks</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#completion">16.8.6. Completion</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/readline.html#example">16.8.7. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/rlcompleter.html">16.9. <code class="docutils literal notranslate"><span class="pre">rlcompleter</span></code> — Completion function for GNU readline</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/rlcompleter.html#completer-objects">16.9.1. Completer Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/ipc.html">17. Interprocess Communication and Networking</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/subprocess.html">17.1. <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> — Subprocess management</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/subprocess.html#using-the-subprocess-module">17.1.1. Using the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#frequently-used-arguments">17.1.1.1. Frequently Used Arguments</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#popen-constructor">17.1.1.2. Popen Constructor</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#exceptions">17.1.1.3. Exceptions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#security">17.1.1.4. Security</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/subprocess.html#popen-objects">17.1.2. Popen Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/subprocess.html#windows-popen-helpers">17.1.3. Windows Popen Helpers</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#constants">17.1.3.1. Constants</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/subprocess.html#replacing-older-functions-with-the-subprocess-module">17.1.4. Replacing Older Functions with the <code class="docutils literal notranslate"><span class="pre">subprocess</span></code> Module</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-bin-sh-shell-backquote">17.1.4.1. Replacing /bin/sh shell backquote</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-shell-pipeline">17.1.4.2. Replacing shell pipeline</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-os-system">17.1.4.3. Replacing <code class="docutils literal notranslate"><span class="pre">os.system()</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-the-os-spawn-family">17.1.4.4. Replacing the <code class="docutils literal notranslate"><span class="pre">os.spawn</span></code> family</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-os-popen-os-popen2-os-popen3">17.1.4.5. Replacing <code class="docutils literal notranslate"><span class="pre">os.popen()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen2()</span></code>, <code class="docutils literal notranslate"><span class="pre">os.popen3()</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#replacing-functions-from-the-popen2-module">17.1.4.6. Replacing functions from the <code class="docutils literal notranslate"><span class="pre">popen2</span></code> module</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/subprocess.html#notes">17.1.5. Notes</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/subprocess.html#converting-an-argument-sequence-to-a-string-on-windows">17.1.5.1. Converting an argument sequence to a string on Windows</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/socket.html">17.2. <code class="docutils literal notranslate"><span class="pre">socket</span></code> — Low-level networking interface</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/socket.html#socket-objects">17.2.1. Socket Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/socket.html#example">17.2.2. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/ssl.html">17.3. <code class="docutils literal notranslate"><span class="pre">ssl</span></code> — TLS/SSL wrapper for socket objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#functions-constants-and-exceptions">17.3.1. Functions, Constants, and Exceptions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#socket-creation">17.3.1.1. Socket creation</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#context-creation">17.3.1.2. Context creation</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#random-generation">17.3.1.3. Random generation</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#certificate-handling">17.3.1.4. Certificate handling</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#constants">17.3.1.5. Constants</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#ssl-sockets">17.3.2. SSL Sockets</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#ssl-contexts">17.3.3. SSL Contexts</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#certificates">17.3.4. Certificates</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#certificate-chains">17.3.4.1. Certificate chains</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#ca-certificates">17.3.4.2. CA certificates</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#combined-key-and-certificate">17.3.4.3. Combined key and certificate</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#self-signed-certificates">17.3.4.4. Self-signed certificates</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#examples">17.3.5. Examples</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#testing-for-ssl-support">17.3.5.1. Testing for SSL support</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#client-side-operation">17.3.5.2. Client-side operation</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#server-side-operation">17.3.5.3. Server-side operation</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#notes-on-non-blocking-sockets">17.3.6. Notes on non-blocking sockets</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#security-considerations">17.3.7. Security considerations</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#best-defaults">17.3.7.1. Best defaults</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#manual-settings">17.3.7.2. Manual settings</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/ssl.html#verifying-certificates">17.3.7.2.1. Verifying certificates</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/ssl.html#protocol-versions">17.3.7.2.2. Protocol versions</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/ssl.html#cipher-selection">17.3.7.2.3. Cipher selection</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/ssl.html#multi-processing">17.3.7.3. Multi-processing</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ssl.html#libressl-support">17.3.8. LibreSSL support</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/signal.html">17.4. <code class="docutils literal notranslate"><span class="pre">signal</span></code> — Set handlers for asynchronous events</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/signal.html#example">17.4.1. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/popen2.html">17.5. <code class="docutils literal notranslate"><span class="pre">popen2</span></code> — Subprocesses with accessible I/O streams</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/popen2.html#popen3-and-popen4-objects">17.5.1. Popen3 and Popen4 Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/popen2.html#flow-control-issues">17.5.2. Flow Control Issues</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/asyncore.html">17.6. <code class="docutils literal notranslate"><span class="pre">asyncore</span></code> — Asynchronous socket handler</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/asyncore.html#asyncore-example-basic-http-client">17.6.1. asyncore Example basic HTTP client</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/asyncore.html#asyncore-example-basic-echo-server">17.6.2. asyncore Example basic echo server</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/asynchat.html">17.7. <code class="docutils literal notranslate"><span class="pre">asynchat</span></code> — Asynchronous socket command/response handler</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/asynchat.html#asynchat-auxiliary-classes">17.7.1. asynchat - Auxiliary Classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/asynchat.html#asynchat-example">17.7.2. asynchat Example</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/netdata.html">18. Internet Data Handling</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/email.html">18.1. <code class="docutils literal notranslate"><span class="pre">email</span></code> — An email and MIME handling package</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/email.message.html">18.1.1. <code class="docutils literal notranslate"><span class="pre">email.message</span></code>: Representing an email message</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.parser.html">18.1.2. <code class="docutils literal notranslate"><span class="pre">email.parser</span></code>: Parsing email messages</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/email.parser.html#feedparser-api">18.1.2.1. FeedParser API</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/email.parser.html#parser-class-api">18.1.2.2. Parser class API</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/email.parser.html#additional-notes">18.1.2.3. Additional notes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/email.generator.html">18.1.3. <code class="docutils literal notranslate"><span class="pre">email.generator</span></code>: Generating MIME documents</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.mime.html">18.1.4. <code class="docutils literal notranslate"><span class="pre">email.mime</span></code>: Creating email and MIME objects from scratch</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.header.html">18.1.5. <code class="docutils literal notranslate"><span class="pre">email.header</span></code>: Internationalized headers</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.charset.html">18.1.6. <code class="docutils literal notranslate"><span class="pre">email.charset</span></code>: Representing character sets</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.encoders.html">18.1.7. <code class="docutils literal notranslate"><span class="pre">email.encoders</span></code>: Encoders</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.errors.html">18.1.8. <code class="docutils literal notranslate"><span class="pre">email.errors</span></code>: Exception and Defect classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.utils.html">18.1.9. <code class="docutils literal notranslate"><span class="pre">email.utils</span></code>: Miscellaneous utilities</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.iterators.html">18.1.10. <code class="docutils literal notranslate"><span class="pre">email.iterators</span></code>: Iterators</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email-examples.html">18.1.11. <code class="docutils literal notranslate"><span class="pre">email</span></code>: Examples</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.html#package-history">18.1.12. Package History</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/email.html#differences-from-mimelib">18.1.13. Differences from <code class="docutils literal notranslate"><span class="pre">mimelib</span></code></a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/json.html">18.2. <code class="docutils literal notranslate"><span class="pre">json</span></code> — JSON encoder and decoder</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/json.html#basic-usage">18.2.1. Basic Usage</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/json.html#encoders-and-decoders">18.2.2. Encoders and Decoders</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/json.html#standard-compliance-and-interoperability">18.2.3. Standard Compliance and Interoperability</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/json.html#character-encodings">18.2.3.1. Character Encodings</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/json.html#infinite-and-nan-number-values">18.2.3.2. Infinite and NaN Number Values</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/json.html#repeated-names-within-an-object">18.2.3.3. Repeated Names Within an Object</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/json.html#top-level-non-object-non-array-values">18.2.3.4. Top-level Non-Object, Non-Array Values</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/json.html#implementation-limitations">18.2.3.5. Implementation Limitations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mailcap.html">18.3. <code class="docutils literal notranslate"><span class="pre">mailcap</span></code> — Mailcap file handling</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/mailbox.html">18.4. <code class="docutils literal notranslate"><span class="pre">mailbox</span></code> — Manipulate mailboxes in various formats</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mailbox.html#mailbox-objects">18.4.1. <code class="docutils literal notranslate"><span class="pre">Mailbox</span></code> objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#maildir">18.4.1.1. <code class="docutils literal notranslate"><span class="pre">Maildir</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mbox">18.4.1.2. <code class="docutils literal notranslate"><span class="pre">mbox</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mh">18.4.1.3. <code class="docutils literal notranslate"><span class="pre">MH</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#babyl">18.4.1.4. <code class="docutils literal notranslate"><span class="pre">Babyl</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mmdf">18.4.1.5. <code class="docutils literal notranslate"><span class="pre">MMDF</span></code></a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/mailbox.html#message-objects">18.4.2. <code class="docutils literal notranslate"><span class="pre">Message</span></code> objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#maildirmessage">18.4.2.1. <code class="docutils literal notranslate"><span class="pre">MaildirMessage</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mboxmessage">18.4.2.2. <code class="docutils literal notranslate"><span class="pre">mboxMessage</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mhmessage">18.4.2.3. <code class="docutils literal notranslate"><span class="pre">MHMessage</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#babylmessage">18.4.2.4. <code class="docutils literal notranslate"><span class="pre">BabylMessage</span></code></a></li>
<li class="toctree-l5"><a class="reference internal" href="library/mailbox.html#mmdfmessage">18.4.2.5. <code class="docutils literal notranslate"><span class="pre">MMDFMessage</span></code></a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/mailbox.html#exceptions">18.4.3. Exceptions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/mailbox.html#deprecated-classes-and-methods">18.4.4. Deprecated classes and methods</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/mailbox.html#examples">18.4.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mhlib.html">18.5. <code class="docutils literal notranslate"><span class="pre">mhlib</span></code> — Access to MH mailboxes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mhlib.html#mh-objects">18.5.1. MH Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/mhlib.html#folder-objects">18.5.2. Folder Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/mhlib.html#message-objects">18.5.3. Message Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mimetools.html">18.6. <code class="docutils literal notranslate"><span class="pre">mimetools</span></code> — Tools for parsing MIME messages</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mimetools.html#additional-methods-of-message-objects">18.6.1. Additional Methods of Message Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mimetypes.html">18.7. <code class="docutils literal notranslate"><span class="pre">mimetypes</span></code> — Map filenames to MIME types</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mimetypes.html#mimetypes-objects">18.7.1. MimeTypes Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mimewriter.html">18.8. <code class="docutils literal notranslate"><span class="pre">MimeWriter</span></code> — Generic MIME file writer</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/mimewriter.html#mimewriter-objects">18.8.1. MimeWriter Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/mimify.html">18.9. <code class="docutils literal notranslate"><span class="pre">mimify</span></code> — MIME processing of mail messages</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/multifile.html">18.10. <code class="docutils literal notranslate"><span class="pre">multifile</span></code> — Support for files containing distinct parts</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/multifile.html#multifile-objects">18.10.1. MultiFile Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/multifile.html#multifile-example">18.10.2. <code class="docutils literal notranslate"><span class="pre">MultiFile</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/rfc822.html">18.11. <code class="docutils literal notranslate"><span class="pre">rfc822</span></code> — Parse RFC 2822 mail headers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/rfc822.html#message-objects">18.11.1. Message Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/rfc822.html#addresslist-objects">18.11.2. AddressList Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/base64.html">18.12. <code class="docutils literal notranslate"><span class="pre">base64</span></code> — RFC 3548: Base16, Base32, Base64 Data Encodings</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/binhex.html">18.13. <code class="docutils literal notranslate"><span class="pre">binhex</span></code> — Encode and decode binhex4 files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/binhex.html#notes">18.13.1. Notes</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/binascii.html">18.14. <code class="docutils literal notranslate"><span class="pre">binascii</span></code> — Convert between binary and ASCII</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/quopri.html">18.15. <code class="docutils literal notranslate"><span class="pre">quopri</span></code> — Encode and decode MIME quoted-printable data</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/uu.html">18.16. <code class="docutils literal notranslate"><span class="pre">uu</span></code> — Encode and decode uuencode files</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/markup.html">19. Structured Markup Processing Tools</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/htmlparser.html">19.1. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> — Simple HTML and XHTML parser</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/htmlparser.html#example-html-parser-application">19.1.1. Example HTML Parser Application</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/htmlparser.html#htmlparser-methods">19.1.2. <code class="docutils literal notranslate"><span class="pre">HTMLParser</span></code> Methods</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/htmlparser.html#examples">19.1.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/sgmllib.html">19.2. <code class="docutils literal notranslate"><span class="pre">sgmllib</span></code> — Simple SGML parser</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/htmllib.html">19.3. <code class="docutils literal notranslate"><span class="pre">htmllib</span></code> — A parser for HTML documents</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/htmllib.html#htmlparser-objects">19.3.1. HTMLParser Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/htmllib.html#module-htmlentitydefs">19.4. <code class="docutils literal notranslate"><span class="pre">htmlentitydefs</span></code> — Definitions of HTML general entities</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.html">19.5. XML Processing Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.html#xml-vulnerabilities">19.6. XML vulnerabilities</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.html#defused-packages">19.6.1. defused packages</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.etree.elementtree.html">19.7. <code class="docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code> — The ElementTree XML API</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.etree.elementtree.html#tutorial">19.7.1. Tutorial</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#xml-tree-and-elements">19.7.1.1. XML tree and elements</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#parsing-xml">19.7.1.2. Parsing XML</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#finding-interesting-elements">19.7.1.3. Finding interesting elements</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#modifying-an-xml-file">19.7.1.4. Modifying an XML File</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#building-xml-documents">19.7.1.5. Building XML documents</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#parsing-xml-with-namespaces">19.7.1.6. Parsing XML with Namespaces</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#additional-resources">19.7.1.7. Additional resources</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.etree.elementtree.html#xpath-support">19.7.2. XPath support</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#example">19.7.2.1. Example</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#supported-xpath-syntax">19.7.2.2. Supported XPath syntax</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.etree.elementtree.html#reference">19.7.3. Reference</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#functions">19.7.3.1. Functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#element-objects">19.7.3.2. Element Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#elementtree-objects">19.7.3.3. ElementTree Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#qname-objects">19.7.3.4. QName Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#treebuilder-objects">19.7.3.5. TreeBuilder Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.etree.elementtree.html#xmlparser-objects">19.7.3.6. XMLParser Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.dom.html">19.8. <code class="docutils literal notranslate"><span class="pre">xml.dom</span></code> — The Document Object Model API</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.html#module-contents">19.8.1. Module Contents</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.html#objects-in-the-dom">19.8.2. Objects in the DOM</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#domimplementation-objects">19.8.2.1. DOMImplementation Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#node-objects">19.8.2.2. Node Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#nodelist-objects">19.8.2.3. NodeList Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#documenttype-objects">19.8.2.4. DocumentType Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#document-objects">19.8.2.5. Document Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#element-objects">19.8.2.6. Element Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#attr-objects">19.8.2.7. Attr Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#namednodemap-objects">19.8.2.8. NamedNodeMap Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#comment-objects">19.8.2.9. Comment Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#text-and-cdatasection-objects">19.8.2.10. Text and CDATASection Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#processinginstruction-objects">19.8.2.11. ProcessingInstruction Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#exceptions">19.8.2.12. Exceptions</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.html#conformance">19.8.3. Conformance</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#type-mapping">19.8.3.1. Type Mapping</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/xml.dom.html#accessor-methods">19.8.3.2. Accessor Methods</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.dom.minidom.html">19.9. <code class="docutils literal notranslate"><span class="pre">xml.dom.minidom</span></code> — Minimal DOM implementation</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.minidom.html#dom-objects">19.9.1. DOM Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.minidom.html#dom-example">19.9.2. DOM Example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.minidom.html#minidom-and-the-dom-standard">19.9.3. minidom and the DOM standard</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.dom.pulldom.html">19.10. <code class="docutils literal notranslate"><span class="pre">xml.dom.pulldom</span></code> — Support for building partial DOM trees</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.dom.pulldom.html#domeventstream-objects">19.10.1. DOMEventStream Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.sax.html">19.11. <code class="docutils literal notranslate"><span class="pre">xml.sax</span></code> — Support for SAX2 parsers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.html#saxexception-objects">19.11.1. SAXException Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.sax.handler.html">19.12. <code class="docutils literal notranslate"><span class="pre">xml.sax.handler</span></code> — Base classes for SAX handlers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.handler.html#contenthandler-objects">19.12.1. ContentHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.handler.html#dtdhandler-objects">19.12.2. DTDHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.handler.html#entityresolver-objects">19.12.3. EntityResolver Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.handler.html#errorhandler-objects">19.12.4. ErrorHandler Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.sax.utils.html">19.13. <code class="docutils literal notranslate"><span class="pre">xml.sax.saxutils</span></code> — SAX Utilities</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/xml.sax.reader.html">19.14. <code class="docutils literal notranslate"><span class="pre">xml.sax.xmlreader</span></code> — Interface for XML parsers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#xmlreader-objects">19.14.1. XMLReader Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#incrementalparser-objects">19.14.2. IncrementalParser Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#locator-objects">19.14.3. Locator Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#inputsource-objects">19.14.4. InputSource Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#the-attributes-interface">19.14.5. The <code class="docutils literal notranslate"><span class="pre">Attributes</span></code> Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xml.sax.reader.html#the-attributesns-interface">19.14.6. The <code class="docutils literal notranslate"><span class="pre">AttributesNS</span></code> Interface</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/pyexpat.html">19.15. <code class="docutils literal notranslate"><span class="pre">xml.parsers.expat</span></code> — Fast XML parsing using Expat</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/pyexpat.html#xmlparser-objects">19.15.1. XMLParser Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pyexpat.html#expaterror-exceptions">19.15.2. ExpatError Exceptions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pyexpat.html#example">19.15.3. Example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pyexpat.html#content-model-descriptions">19.15.4. Content Model Descriptions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pyexpat.html#expat-error-constants">19.15.5. Expat error constants</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/internet.html">20. Internet Protocols and Support</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/webbrowser.html">20.1. <code class="docutils literal notranslate"><span class="pre">webbrowser</span></code> — Convenient Web-browser controller</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/webbrowser.html#browser-controller-objects">20.1.1. Browser Controller Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/cgi.html">20.2. <code class="docutils literal notranslate"><span class="pre">cgi</span></code> — Common Gateway Interface support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#introduction">20.2.1. Introduction</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#using-the-cgi-module">20.2.2. Using the cgi module</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#higher-level-interface">20.2.3. Higher Level Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#old-classes">20.2.4. Old classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#functions">20.2.5. Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#caring-about-security">20.2.6. Caring about security</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#installing-your-cgi-script-on-a-unix-system">20.2.7. Installing your CGI script on a Unix system</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#testing-your-cgi-script">20.2.8. Testing your CGI script</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#debugging-cgi-scripts">20.2.9. Debugging CGI scripts</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cgi.html#common-problems-and-solutions">20.2.10. Common problems and solutions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/cgitb.html">20.3. <code class="docutils literal notranslate"><span class="pre">cgitb</span></code> — Traceback manager for CGI scripts</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/wsgiref.html">20.4. <code class="docutils literal notranslate"><span class="pre">wsgiref</span></code> — WSGI Utilities and Reference Implementation</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#module-wsgiref.util">20.4.1. <code class="docutils literal notranslate"><span class="pre">wsgiref.util</span></code> – WSGI environment utilities</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#module-wsgiref.headers">20.4.2. <code class="docutils literal notranslate"><span class="pre">wsgiref.headers</span></code> – WSGI response header tools</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#module-wsgiref.simple_server">20.4.3. <code class="docutils literal notranslate"><span class="pre">wsgiref.simple_server</span></code> – a simple WSGI HTTP server</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#module-wsgiref.validate">20.4.4. <code class="docutils literal notranslate"><span class="pre">wsgiref.validate</span></code> — WSGI conformance checker</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#module-wsgiref.handlers">20.4.5. <code class="docutils literal notranslate"><span class="pre">wsgiref.handlers</span></code> – server/gateway base classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wsgiref.html#examples">20.4.6. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/urllib.html">20.5. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> — Open arbitrary resources by URL</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/urllib.html#high-level-interface">20.5.1. High-level interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib.html#utility-functions">20.5.2. Utility functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib.html#url-opener-objects">20.5.3. URL Opener objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib.html#urllib-restrictions">20.5.4. <code class="docutils literal notranslate"><span class="pre">urllib</span></code> Restrictions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib.html#examples">20.5.5. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/urllib2.html">20.6. <code class="docutils literal notranslate"><span class="pre">urllib2</span></code> — extensible library for opening URLs</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#request-objects">20.6.1. Request Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#openerdirector-objects">20.6.2. OpenerDirector Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#basehandler-objects">20.6.3. BaseHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httpredirecthandler-objects">20.6.4. HTTPRedirectHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httpcookieprocessor-objects">20.6.5. HTTPCookieProcessor Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#proxyhandler-objects">20.6.6. ProxyHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httppasswordmgr-objects">20.6.7. HTTPPasswordMgr Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#abstractbasicauthhandler-objects">20.6.8. AbstractBasicAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httpbasicauthhandler-objects">20.6.9. HTTPBasicAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#proxybasicauthhandler-objects">20.6.10. ProxyBasicAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#abstractdigestauthhandler-objects">20.6.11. AbstractDigestAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httpdigestauthhandler-objects">20.6.12. HTTPDigestAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#proxydigestauthhandler-objects">20.6.13. ProxyDigestAuthHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httphandler-objects">20.6.14. HTTPHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httpshandler-objects">20.6.15. HTTPSHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#filehandler-objects">20.6.16. FileHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#ftphandler-objects">20.6.17. FTPHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#cacheftphandler-objects">20.6.18. CacheFTPHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#unknownhandler-objects">20.6.19. UnknownHandler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#httperrorprocessor-objects">20.6.20. HTTPErrorProcessor Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/urllib2.html#examples">20.6.21. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/httplib.html">20.7. <code class="docutils literal notranslate"><span class="pre">httplib</span></code> — HTTP protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/httplib.html#httpconnection-objects">20.7.1. HTTPConnection Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/httplib.html#httpresponse-objects">20.7.2. HTTPResponse Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/httplib.html#examples">20.7.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/ftplib.html">20.8. <code class="docutils literal notranslate"><span class="pre">ftplib</span></code> — FTP protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ftplib.html#ftp-objects">20.8.1. FTP Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ftplib.html#ftp-tls-objects">20.8.2. FTP_TLS Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/poplib.html">20.9. <code class="docutils literal notranslate"><span class="pre">poplib</span></code> — POP3 protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/poplib.html#pop3-objects">20.9.1. POP3 Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/poplib.html#pop3-example">20.9.2. POP3 Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/imaplib.html">20.10. <code class="docutils literal notranslate"><span class="pre">imaplib</span></code> — IMAP4 protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/imaplib.html#imap4-objects">20.10.1. IMAP4 Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/imaplib.html#imap4-example">20.10.2. IMAP4 Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/nntplib.html">20.11. <code class="docutils literal notranslate"><span class="pre">nntplib</span></code> — NNTP protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/nntplib.html#nntp-objects">20.11.1. NNTP Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/smtplib.html">20.12. <code class="docutils literal notranslate"><span class="pre">smtplib</span></code> — SMTP protocol client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/smtplib.html#smtp-objects">20.12.1. SMTP Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/smtplib.html#smtp-example">20.12.2. SMTP Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/smtpd.html">20.13. <code class="docutils literal notranslate"><span class="pre">smtpd</span></code> — SMTP Server</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/smtpd.html#smtpserver-objects">20.13.1. SMTPServer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/smtpd.html#debuggingserver-objects">20.13.2. DebuggingServer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/smtpd.html#pureproxy-objects">20.13.3. PureProxy Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/smtpd.html#mailmanproxy-objects">20.13.4. MailmanProxy Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/telnetlib.html">20.14. <code class="docutils literal notranslate"><span class="pre">telnetlib</span></code> — Telnet client</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/telnetlib.html#telnet-objects">20.14.1. Telnet Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/telnetlib.html#telnet-example">20.14.2. Telnet Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/uuid.html">20.15. <code class="docutils literal notranslate"><span class="pre">uuid</span></code> — UUID objects according to RFC 4122</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/uuid.html#example">20.15.1. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/urlparse.html">20.16. <code class="docutils literal notranslate"><span class="pre">urlparse</span></code> — Parse URLs into components</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/urlparse.html#results-of-urlparse-and-urlsplit">20.16.1. Results of <code class="docutils literal notranslate"><span class="pre">urlparse()</span></code> and <code class="docutils literal notranslate"><span class="pre">urlsplit()</span></code></a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/socketserver.html">20.17. <code class="docutils literal notranslate"><span class="pre">SocketServer</span></code> — A framework for network servers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/socketserver.html#server-creation-notes">20.17.1. Server Creation Notes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/socketserver.html#server-objects">20.17.2. Server Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/socketserver.html#request-handler-objects">20.17.3. Request Handler Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/socketserver.html#examples">20.17.4. Examples</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/socketserver.html#socketserver-tcpserver-example">20.17.4.1. <code class="docutils literal notranslate"><span class="pre">SocketServer.TCPServer</span></code> Example</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/socketserver.html#socketserver-udpserver-example">20.17.4.2. <code class="docutils literal notranslate"><span class="pre">SocketServer.UDPServer</span></code> Example</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/socketserver.html#asynchronous-mixins">20.17.4.3. Asynchronous Mixins</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/basehttpserver.html">20.18. <code class="docutils literal notranslate"><span class="pre">BaseHTTPServer</span></code> — Basic HTTP server</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/basehttpserver.html#more-examples">20.18.1. More examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/simplehttpserver.html">20.19. <code class="docutils literal notranslate"><span class="pre">SimpleHTTPServer</span></code> — Simple HTTP request handler</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/cgihttpserver.html">20.20. <code class="docutils literal notranslate"><span class="pre">CGIHTTPServer</span></code> — CGI-capable HTTP request handler</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/cookielib.html">20.21. <code class="docutils literal notranslate"><span class="pre">cookielib</span></code> — Cookie handling for HTTP clients</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#cookiejar-and-filecookiejar-objects">20.21.1. CookieJar and FileCookieJar Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#filecookiejar-subclasses-and-co-operation-with-web-browsers">20.21.2. FileCookieJar subclasses and co-operation with web browsers</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#cookiepolicy-objects">20.21.3. CookiePolicy Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#defaultcookiepolicy-objects">20.21.4. DefaultCookiePolicy Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#cookie-objects">20.21.5. Cookie Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookielib.html#examples">20.21.6. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/cookie.html">20.22. <code class="docutils literal notranslate"><span class="pre">Cookie</span></code> — HTTP state management</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cookie.html#cookie-objects">20.22.1. Cookie Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookie.html#morsel-objects">20.22.2. Morsel Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cookie.html#example">20.22.3. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/xmlrpclib.html">20.23. <code class="docutils literal notranslate"><span class="pre">xmlrpclib</span></code> — XML-RPC client access</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#serverproxy-objects">20.23.1. ServerProxy Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#boolean-objects">20.23.2. Boolean Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#datetime-objects">20.23.3. DateTime Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#binary-objects">20.23.4. Binary Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#fault-objects">20.23.5. Fault Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#protocolerror-objects">20.23.6. ProtocolError Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#multicall-objects">20.23.7. MultiCall Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#convenience-functions">20.23.8. Convenience Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#example-of-client-usage">20.23.9. Example of Client Usage</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/xmlrpclib.html#example-of-client-and-server-usage">20.23.10. Example of Client and Server Usage</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/simplexmlrpcserver.html">20.24. <code class="docutils literal notranslate"><span class="pre">SimpleXMLRPCServer</span></code> — Basic XML-RPC server</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/simplexmlrpcserver.html#simplexmlrpcserver-objects">20.24.1. SimpleXMLRPCServer Objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/simplexmlrpcserver.html#simplexmlrpcserver-example">20.24.1.1. SimpleXMLRPCServer Example</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/simplexmlrpcserver.html#cgixmlrpcrequesthandler">20.24.2. CGIXMLRPCRequestHandler</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/docxmlrpcserver.html">20.25. <code class="docutils literal notranslate"><span class="pre">DocXMLRPCServer</span></code> — Self-documenting XML-RPC server</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/docxmlrpcserver.html#docxmlrpcserver-objects">20.25.1. DocXMLRPCServer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/docxmlrpcserver.html#doccgixmlrpcrequesthandler">20.25.2. DocCGIXMLRPCRequestHandler</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/mm.html">21. Multimedia Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/audioop.html">21.1. <code class="docutils literal notranslate"><span class="pre">audioop</span></code> — Manipulate raw audio data</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/imageop.html">21.2. <code class="docutils literal notranslate"><span class="pre">imageop</span></code> — Manipulate raw image data</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/aifc.html">21.3. <code class="docutils literal notranslate"><span class="pre">aifc</span></code> — Read and write AIFF and AIFC files</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/sunau.html">21.4. <code class="docutils literal notranslate"><span class="pre">sunau</span></code> — Read and write Sun AU files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sunau.html#au-read-objects">21.4.1. AU_read Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sunau.html#au-write-objects">21.4.2. AU_write Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/wave.html">21.5. <code class="docutils literal notranslate"><span class="pre">wave</span></code> — Read and write WAV files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/wave.html#wave-read-objects">21.5.1. Wave_read Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/wave.html#wave-write-objects">21.5.2. Wave_write Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/chunk.html">21.6. <code class="docutils literal notranslate"><span class="pre">chunk</span></code> — Read IFF chunked data</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/colorsys.html">21.7. <code class="docutils literal notranslate"><span class="pre">colorsys</span></code> — Conversions between color systems</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/imghdr.html">21.8. <code class="docutils literal notranslate"><span class="pre">imghdr</span></code> — Determine the type of an image</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/sndhdr.html">21.9. <code class="docutils literal notranslate"><span class="pre">sndhdr</span></code> — Determine type of sound file</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/ossaudiodev.html">21.10. <code class="docutils literal notranslate"><span class="pre">ossaudiodev</span></code> — Access to OSS-compatible audio devices</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ossaudiodev.html#audio-device-objects">21.10.1. Audio Device Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ossaudiodev.html#mixer-device-objects">21.10.2. Mixer Device Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/i18n.html">22. Internationalization</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/gettext.html">22.1. <code class="docutils literal notranslate"><span class="pre">gettext</span></code> — Multilingual internationalization services</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/gettext.html#gnu-gettext-api">22.1.1. GNU <strong class="program">gettext</strong> API</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/gettext.html#class-based-api">22.1.2. Class-based API</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#the-nulltranslations-class">22.1.2.1. The <code class="docutils literal notranslate"><span class="pre">NullTranslations</span></code> class</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#the-gnutranslations-class">22.1.2.2. The <code class="docutils literal notranslate"><span class="pre">GNUTranslations</span></code> class</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#solaris-message-catalog-support">22.1.2.3. Solaris message catalog support</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#the-catalog-constructor">22.1.2.4. The Catalog constructor</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/gettext.html#internationalizing-your-programs-and-modules">22.1.3. Internationalizing your programs and modules</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#localizing-your-module">22.1.3.1. Localizing your module</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#localizing-your-application">22.1.3.2. Localizing your application</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#changing-languages-on-the-fly">22.1.3.3. Changing languages on the fly</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#deferred-translations">22.1.3.4. Deferred translations</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/gettext.html#gettext-vs-lgettext">22.1.3.5. <code class="docutils literal notranslate"><span class="pre">gettext()</span></code> vs. <code class="docutils literal notranslate"><span class="pre">lgettext()</span></code></a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/gettext.html#acknowledgements">22.1.4. Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/locale.html">22.2. <code class="docutils literal notranslate"><span class="pre">locale</span></code> — Internationalization services</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/locale.html#background-details-hints-tips-and-caveats">22.2.1. Background, details, hints, tips and caveats</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/locale.html#for-extension-writers-and-programs-that-embed-python">22.2.2. For extension writers and programs that embed Python</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/locale.html#access-to-message-catalogs">22.2.3. Access to message catalogs</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/frameworks.html">23. Program Frameworks</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/cmd.html">23.1. <code class="docutils literal notranslate"><span class="pre">cmd</span></code> — Support for line-oriented command interpreters</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cmd.html#cmd-objects">23.1.1. Cmd Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/shlex.html">23.2. <code class="docutils literal notranslate"><span class="pre">shlex</span></code> — Simple lexical analysis</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/shlex.html#shlex-objects">23.2.1. shlex Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/shlex.html#parsing-rules">23.2.2. Parsing Rules</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/tk.html">24. Graphical User Interfaces with Tk</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/tkinter.html">24.1. <code class="docutils literal notranslate"><span class="pre">Tkinter</span></code> — Python interface to Tcl/Tk</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#tkinter-modules">24.1.1. Tkinter Modules</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#tkinter-life-preserver">24.1.2. Tkinter Life Preserver</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#how-to-use-this-section">24.1.2.1. How To Use This Section</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#a-simple-hello-world-program">24.1.2.2. A Simple Hello World Program</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#a-very-quick-look-at-tcl-tk">24.1.3. A (Very) Quick Look at Tcl/Tk</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#mapping-basic-tk-into-tkinter">24.1.4. Mapping Basic Tk into Tkinter</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#how-tk-and-tkinter-are-related">24.1.5. How Tk and Tkinter are Related</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#handy-reference">24.1.6. Handy Reference</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#setting-options">24.1.6.1. Setting Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#the-packer">24.1.6.2. The Packer</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#packer-options">24.1.6.3. Packer Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#coupling-widget-variables">24.1.6.4. Coupling Widget Variables</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#the-window-manager">24.1.6.5. The Window Manager</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#tk-option-data-types">24.1.6.6. Tk Option Data Types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#bindings-and-events">24.1.6.7. Bindings and Events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#the-index-parameter">24.1.6.8. The index Parameter</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tkinter.html#images">24.1.6.9. Images</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/tkinter.html#file-handlers">24.1.7. File Handlers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/ttk.html">24.2. <code class="docutils literal notranslate"><span class="pre">ttk</span></code> — Tk themed widgets</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#using-ttk">24.2.1. Using Ttk</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#ttk-widgets">24.2.2. Ttk Widgets</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#widget">24.2.3. Widget</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#standard-options">24.2.3.1. Standard Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#scrollable-widget-options">24.2.3.2. Scrollable Widget Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#label-options">24.2.3.3. Label Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#compatibility-options">24.2.3.4. Compatibility Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#widget-states">24.2.3.5. Widget States</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#ttk-widget">24.2.3.6. ttk.Widget</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#combobox">24.2.4. Combobox</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#options">24.2.4.1. Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#virtual-events">24.2.4.2. Virtual events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#ttk-combobox">24.2.4.3. ttk.Combobox</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#notebook">24.2.5. Notebook</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id1">24.2.5.1. Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#tab-options">24.2.5.2. Tab Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#tab-identifiers">24.2.5.3. Tab Identifiers</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id2">24.2.5.4. Virtual Events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#ttk-notebook">24.2.5.5. ttk.Notebook</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#progressbar">24.2.6. Progressbar</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id3">24.2.6.1. Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#ttk-progressbar">24.2.6.2. ttk.Progressbar</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#separator">24.2.7. Separator</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id4">24.2.7.1. Options</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#sizegrip">24.2.8. Sizegrip</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#platform-specific-notes">24.2.8.1. Platform-specific notes</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#bugs">24.2.8.2. Bugs</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#treeview">24.2.9. Treeview</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id5">24.2.9.1. Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#item-options">24.2.9.2. Item Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#tag-options">24.2.9.3. Tag Options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#column-identifiers">24.2.9.4. Column Identifiers</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#id6">24.2.9.5. Virtual Events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#ttk-treeview">24.2.9.6. ttk.Treeview</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/ttk.html#ttk-styling">24.2.10. Ttk Styling</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/ttk.html#layouts">24.2.10.1. Layouts</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/tix.html">24.3. <code class="docutils literal notranslate"><span class="pre">Tix</span></code> — Extension widgets for Tk</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/tix.html#using-tix">24.3.1. Using Tix</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/tix.html#tix-widgets">24.3.2. Tix Widgets</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#basic-widgets">24.3.2.1. Basic Widgets</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#file-selectors">24.3.2.2. File Selectors</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#hierarchical-listbox">24.3.2.3. Hierarchical ListBox</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#tabular-listbox">24.3.2.4. Tabular ListBox</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#manager-widgets">24.3.2.5. Manager Widgets</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#image-types">24.3.2.6. Image Types</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#miscellaneous-widgets">24.3.2.7. Miscellaneous Widgets</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/tix.html#form-geometry-manager">24.3.2.8. Form Geometry Manager</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/tix.html#tix-commands">24.3.3. Tix Commands</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/scrolledtext.html">24.4. <code class="docutils literal notranslate"><span class="pre">ScrolledText</span></code> — Scrolled Text Widget</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/turtle.html">24.5. <code class="docutils literal notranslate"><span class="pre">turtle</span></code> — Turtle graphics for Tk</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#introduction">24.5.1. Introduction</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#overview-over-available-turtle-and-screen-methods">24.5.2. Overview over available Turtle and Screen methods</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#turtle-methods">24.5.2.1. Turtle methods</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#methods-of-turtlescreen-screen">24.5.2.2. Methods of TurtleScreen/Screen</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#methods-of-rawturtle-turtle-and-corresponding-functions">24.5.3. Methods of RawTurtle/Turtle and corresponding functions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#turtle-motion">24.5.3.1. Turtle motion</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#tell-turtle-s-state">24.5.3.2. Tell Turtle’s state</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#settings-for-measurement">24.5.3.3. Settings for measurement</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#pen-control">24.5.3.4. Pen control</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#drawing-state">24.5.3.4.1. Drawing state</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#color-control">24.5.3.4.2. Color control</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#filling">24.5.3.4.3. Filling</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#more-drawing-control">24.5.3.4.4. More drawing control</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#turtle-state">24.5.3.5. Turtle state</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#visibility">24.5.3.5.1. Visibility</a></li>
<li class="toctree-l6"><a class="reference internal" href="library/turtle.html#appearance">24.5.3.5.2. Appearance</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#using-events">24.5.3.6. Using events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#special-turtle-methods">24.5.3.7. Special Turtle methods</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#excursus-about-the-use-of-compound-shapes">24.5.3.8. Excursus about the use of compound shapes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#methods-of-turtlescreen-screen-and-corresponding-functions">24.5.4. Methods of TurtleScreen/Screen and corresponding functions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#window-control">24.5.4.1. Window control</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#animation-control">24.5.4.2. Animation control</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#using-screen-events">24.5.4.3. Using screen events</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#settings-and-special-methods">24.5.4.4. Settings and special methods</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#methods-specific-to-screen-not-inherited-from-turtlescreen">24.5.4.5. Methods specific to Screen, not inherited from TurtleScreen</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#the-public-classes-of-the-module-turtle">24.5.5. The public classes of the module <code class="docutils literal notranslate"><span class="pre">turtle</span></code></a></li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#help-and-configuration">24.5.6. Help and configuration</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#how-to-use-help">24.5.6.1. How to use help</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#translation-of-docstrings-into-different-languages">24.5.6.2. Translation of docstrings into different languages</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/turtle.html#how-to-configure-screen-and-turtles">24.5.6.3. How to configure Screen and Turtles</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/turtle.html#demo-scripts">24.5.7. Demo scripts</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/idle.html">24.6. IDLE</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/idle.html#menus">24.6.1. Menus</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#file-menu-shell-and-editor">24.6.1.1. File menu (Shell and Editor)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#edit-menu-shell-and-editor">24.6.1.2. Edit menu (Shell and Editor)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#format-menu-editor-window-only">24.6.1.3. Format menu (Editor window only)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#run-menu-editor-window-only">24.6.1.4. Run menu (Editor window only)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#shell-menu-shell-window-only">24.6.1.5. Shell menu (Shell window only)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#debug-menu-shell-window-only">24.6.1.6. Debug menu (Shell window only)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#options-menu-shell-and-editor">24.6.1.7. Options menu (Shell and Editor)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#window-menu-shell-and-editor">24.6.1.8. Window menu (Shell and Editor)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#help-menu-shell-and-editor">24.6.1.9. Help menu (Shell and Editor)</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#context-menus">24.6.1.10. Context Menus</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/idle.html#editing-and-navigation">24.6.2. Editing and navigation</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#automatic-indentation">24.6.2.1. Automatic indentation</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#completions">24.6.2.2. Completions</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#calltips">24.6.2.3. Calltips</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#python-shell-window">24.6.2.4. Python Shell window</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#text-colors">24.6.2.5. Text colors</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/idle.html#startup-and-code-execution">24.6.3. Startup and code execution</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#command-line-usage">24.6.3.1. Command line usage</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#idle-console-differences">24.6.3.2. IDLE-console differences</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#running-without-a-subprocess">24.6.3.3. Running without a subprocess</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/idle.html#help-and-preferences">24.6.4. Help and preferences</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#additional-help-sources">24.6.4.1. Additional help sources</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#setting-preferences">24.6.4.2. Setting preferences</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/idle.html#extensions">24.6.4.3. Extensions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/othergui.html">24.7. Other Graphical User Interface Packages</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/development.html">25. Development Tools</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/pydoc.html">25.1. <code class="docutils literal notranslate"><span class="pre">pydoc</span></code> — Documentation generator and online help system</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/doctest.html">25.2. <code class="docutils literal notranslate"><span class="pre">doctest</span></code> — Test interactive Python examples</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#simple-usage-checking-examples-in-docstrings">25.2.1. Simple Usage: Checking Examples in Docstrings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#simple-usage-checking-examples-in-a-text-file">25.2.2. Simple Usage: Checking Examples in a Text File</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#how-it-works">25.2.3. How It Works</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#which-docstrings-are-examined">25.2.3.1. Which Docstrings Are Examined?</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#how-are-docstring-examples-recognized">25.2.3.2. How are Docstring Examples Recognized?</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#what-s-the-execution-context">25.2.3.3. What’s the Execution Context?</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#what-about-exceptions">25.2.3.4. What About Exceptions?</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#option-flags">25.2.3.5. Option Flags</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#directives">25.2.3.6. Directives</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#warnings">25.2.3.7. Warnings</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#basic-api">25.2.4. Basic API</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#unittest-api">25.2.5. Unittest API</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#advanced-api">25.2.6. Advanced API</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#doctest-objects">25.2.6.1. DocTest Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#example-objects">25.2.6.2. Example Objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#doctestfinder-objects">25.2.6.3. DocTestFinder objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#doctestparser-objects">25.2.6.4. DocTestParser objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#doctestrunner-objects">25.2.6.5. DocTestRunner objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/doctest.html#outputchecker-objects">25.2.6.6. OutputChecker objects</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#debugging">25.2.7. Debugging</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/doctest.html#soapbox">25.2.8. Soapbox</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/unittest.html">25.3. <code class="docutils literal notranslate"><span class="pre">unittest</span></code> — Unit testing framework</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#basic-example">25.3.1. Basic example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#command-line-interface">25.3.2. Command-Line Interface</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#command-line-options">25.3.2.1. Command-line options</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#test-discovery">25.3.3. Test Discovery</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#organizing-test-code">25.3.4. Organizing test code</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#re-using-old-test-code">25.3.5. Re-using old test code</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#skipping-tests-and-expected-failures">25.3.6. Skipping tests and expected failures</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#classes-and-functions">25.3.7. Classes and functions</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#test-cases">25.3.7.1. Test cases</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/unittest.html#deprecated-aliases">25.3.7.1.1. Deprecated aliases</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#grouping-tests">25.3.7.2. Grouping tests</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#loading-and-running-tests">25.3.7.3. Loading and running tests</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/unittest.html#load-tests-protocol">25.3.7.3.1. load_tests Protocol</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#class-and-module-fixtures">25.3.8. Class and Module Fixtures</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#setupclass-and-teardownclass">25.3.8.1. setUpClass and tearDownClass</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/unittest.html#setupmodule-and-teardownmodule">25.3.8.2. setUpModule and tearDownModule</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/unittest.html#signal-handling">25.3.9. Signal Handling</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/2to3.html">25.4. 2to3 - Automated Python 2 to 3 code translation</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/2to3.html#using-2to3">25.4.1. Using 2to3</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/2to3.html#fixers">25.4.2. Fixers</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/2to3.html#module-lib2to3">25.4.3. <code class="docutils literal notranslate"><span class="pre">lib2to3</span></code> - 2to3’s library</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/test.html">25.5. <code class="docutils literal notranslate"><span class="pre">test</span></code> — Regression tests package for Python</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/test.html#writing-unit-tests-for-the-test-package">25.5.1. Writing Unit Tests for the <code class="docutils literal notranslate"><span class="pre">test</span></code> package</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/test.html#running-tests-using-the-command-line-interface">25.5.2. Running tests using the command-line interface</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/test.html#module-test.support">25.6. <code class="docutils literal notranslate"><span class="pre">test.support</span></code> — Utility functions for tests</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/debug.html">26. Debugging and Profiling</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/bdb.html">26.1. <code class="docutils literal notranslate"><span class="pre">bdb</span></code> — Debugger framework</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pdb.html">26.2. <code class="docutils literal notranslate"><span class="pre">pdb</span></code> — The Python Debugger</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pdb.html#debugger-commands">26.3. Debugger Commands</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/profile.html">26.4. The Python Profilers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#introduction-to-the-profilers">26.4.1. Introduction to the profilers</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#instant-user-s-manual">26.4.2. Instant User’s Manual</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#module-cProfile">26.4.3. <code class="docutils literal notranslate"><span class="pre">profile</span></code> and <code class="docutils literal notranslate"><span class="pre">cProfile</span></code> Module Reference</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#the-stats-class">26.4.4. The <code class="docutils literal notranslate"><span class="pre">Stats</span></code> Class</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#what-is-deterministic-profiling">26.4.5. What Is Deterministic Profiling?</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#limitations">26.4.6. Limitations</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#calibration">26.4.7. Calibration</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/profile.html#using-a-custom-timer">26.4.8. Using a custom timer</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/hotshot.html">26.5. <code class="docutils literal notranslate"><span class="pre">hotshot</span></code> — High performance logging profiler</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/hotshot.html#profile-objects">26.5.1. Profile Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/hotshot.html#module-hotshot.stats">26.5.2. Using hotshot data</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/hotshot.html#example-usage">26.5.3. Example Usage</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/timeit.html">26.6. <code class="docutils literal notranslate"><span class="pre">timeit</span></code> — Measure execution time of small code snippets</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/timeit.html#basic-examples">26.6.1. Basic Examples</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/timeit.html#python-interface">26.6.2. Python Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/timeit.html#command-line-interface">26.6.3. Command-Line Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/timeit.html#examples">26.6.4. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/trace.html">26.7. <code class="docutils literal notranslate"><span class="pre">trace</span></code> — Trace or track Python statement execution</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/trace.html#command-line-usage">26.7.1. Command-Line Usage</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/trace.html#main-options">26.7.1.1. Main options</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/trace.html#modifiers">26.7.1.2. Modifiers</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/trace.html#filters">26.7.1.3. Filters</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/trace.html#programmatic-interface">26.7.2. Programmatic Interface</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/distribution.html">27. Software Packaging and Distribution</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/distutils.html">27.1. <code class="docutils literal notranslate"><span class="pre">distutils</span></code> — Building and installing Python modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/ensurepip.html">27.2. <code class="docutils literal notranslate"><span class="pre">ensurepip</span></code> — Bootstrapping the <code class="docutils literal notranslate"><span class="pre">pip</span></code> installer</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ensurepip.html#command-line-interface">27.2.1. Command line interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ensurepip.html#module-api">27.2.2. Module API</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/python.html">28. Python Runtime Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/sys.html">28.1. <code class="docutils literal notranslate"><span class="pre">sys</span></code> — System-specific parameters and functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/sysconfig.html">28.2. <code class="docutils literal notranslate"><span class="pre">sysconfig</span></code> — Provide access to Python’s configuration information</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sysconfig.html#configuration-variables">28.2.1. Configuration variables</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sysconfig.html#installation-paths">28.2.2. Installation paths</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/sysconfig.html#other-functions">28.2.3. Other functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/__builtin__.html">28.3. <code class="docutils literal notranslate"><span class="pre">__builtin__</span></code> — Built-in objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/future_builtins.html">28.4. <code class="docutils literal notranslate"><span class="pre">future_builtins</span></code> — Python 3 builtins</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/__main__.html">28.5. <code class="docutils literal notranslate"><span class="pre">__main__</span></code> — Top-level script environment</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/warnings.html">28.6. <code class="docutils literal notranslate"><span class="pre">warnings</span></code> — Warning control</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#warning-categories">28.6.1. Warning Categories</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#the-warnings-filter">28.6.2. The Warnings Filter</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/warnings.html#default-warning-filters">28.6.2.1. Default Warning Filters</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#temporarily-suppressing-warnings">28.6.3. Temporarily Suppressing Warnings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#testing-warnings">28.6.4. Testing Warnings</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#updating-code-for-new-versions-of-python">28.6.5. Updating Code For New Versions of Python</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#available-functions">28.6.6. Available Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/warnings.html#available-context-managers">28.6.7. Available Context Managers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/contextlib.html">28.7. <code class="docutils literal notranslate"><span class="pre">contextlib</span></code> — Utilities for <code class="docutils literal notranslate"><span class="pre">with</span></code>-statement contexts</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/abc.html">28.8. <code class="docutils literal notranslate"><span class="pre">abc</span></code> — Abstract Base Classes</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/atexit.html">28.9. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> — Exit handlers</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/atexit.html#atexit-example">28.9.1. <code class="docutils literal notranslate"><span class="pre">atexit</span></code> Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/traceback.html">28.10. <code class="docutils literal notranslate"><span class="pre">traceback</span></code> — Print or retrieve a stack traceback</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/traceback.html#traceback-examples">28.10.1. Traceback Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/__future__.html">28.11. <code class="docutils literal notranslate"><span class="pre">__future__</span></code> — Future statement definitions</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gc.html">28.12. <code class="docutils literal notranslate"><span class="pre">gc</span></code> — Garbage Collector interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/inspect.html">28.13. <code class="docutils literal notranslate"><span class="pre">inspect</span></code> — Inspect live objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/inspect.html#types-and-members">28.13.1. Types and members</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/inspect.html#retrieving-source-code">28.13.2. Retrieving source code</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/inspect.html#classes-and-functions">28.13.3. Classes and functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/inspect.html#the-interpreter-stack">28.13.4. The interpreter stack</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/site.html">28.14. <code class="docutils literal notranslate"><span class="pre">site</span></code> — Site-specific configuration hook</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/user.html">28.15. <code class="docutils literal notranslate"><span class="pre">user</span></code> — User-specific configuration hook</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fpectl.html">28.16. <code class="docutils literal notranslate"><span class="pre">fpectl</span></code> — Floating point exception control</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/fpectl.html#example">28.16.1. Example</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/fpectl.html#limitations-and-other-considerations">28.16.2. Limitations and other considerations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/custominterp.html">29. Custom Python Interpreters</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/code.html">29.1. <code class="docutils literal notranslate"><span class="pre">code</span></code> — Interpreter base classes</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/code.html#interactive-interpreter-objects">29.1.1. Interactive Interpreter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/code.html#interactive-console-objects">29.1.2. Interactive Console Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/codeop.html">29.2. <code class="docutils literal notranslate"><span class="pre">codeop</span></code> — Compile Python code</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/restricted.html">30. Restricted Execution</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/rexec.html">30.1. <code class="docutils literal notranslate"><span class="pre">rexec</span></code> — Restricted execution framework</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/rexec.html#rexec-objects">30.1.1. RExec Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/rexec.html#defining-restricted-environments">30.1.2. Defining restricted environments</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/rexec.html#an-example">30.1.3. An example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/bastion.html">30.2. <code class="docutils literal notranslate"><span class="pre">Bastion</span></code> — Restricting access to objects</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/modules.html">31. Importing Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/imp.html">31.1. <code class="docutils literal notranslate"><span class="pre">imp</span></code> — Access the <code class="docutils literal notranslate"><span class="pre">import</span></code> internals</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/imp.html#examples">31.1.1. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/importlib.html">31.2. <code class="docutils literal notranslate"><span class="pre">importlib</span></code> — Convenience wrappers for <code class="docutils literal notranslate"><span class="pre">__import__()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="library/imputil.html">31.3. <code class="docutils literal notranslate"><span class="pre">imputil</span></code> — Import utilities</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/imputil.html#examples">31.3.1. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/zipimport.html">31.4. <code class="docutils literal notranslate"><span class="pre">zipimport</span></code> — Import modules from Zip archives</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/zipimport.html#zipimporter-objects">31.4.1. zipimporter Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/zipimport.html#examples">31.4.2. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/pkgutil.html">31.5. <code class="docutils literal notranslate"><span class="pre">pkgutil</span></code> — Package extension utility</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/modulefinder.html">31.6. <code class="docutils literal notranslate"><span class="pre">modulefinder</span></code> — Find modules used by a script</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/modulefinder.html#example-usage-of-modulefinder">31.6.1. Example usage of <code class="docutils literal notranslate"><span class="pre">ModuleFinder</span></code></a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/runpy.html">31.7. <code class="docutils literal notranslate"><span class="pre">runpy</span></code> — Locating and executing Python modules</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/language.html">32. Python Language Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/parser.html">32.1. <code class="docutils literal notranslate"><span class="pre">parser</span></code> — Access Python parse trees</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#creating-st-objects">32.1.1. Creating ST Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#converting-st-objects">32.1.2. Converting ST Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#queries-on-st-objects">32.1.3. Queries on ST Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#exceptions-and-error-handling">32.1.4. Exceptions and Error Handling</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#st-objects">32.1.5. ST Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/parser.html#example-emulation-of-compile">32.1.6. Example: Emulation of <code class="docutils literal notranslate"><span class="pre">compile()</span></code></a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/ast.html">32.2. <code class="docutils literal notranslate"><span class="pre">ast</span></code> — Abstract Syntax Trees</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ast.html#node-classes">32.2.1. Node classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ast.html#abstract-grammar">32.2.2. Abstract Grammar</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/ast.html#ast-helpers">32.2.3. <code class="docutils literal notranslate"><span class="pre">ast</span></code> Helpers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/symtable.html">32.3. <code class="docutils literal notranslate"><span class="pre">symtable</span></code> — Access to the compiler’s symbol tables</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/symtable.html#generating-symbol-tables">32.3.1. Generating Symbol Tables</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/symtable.html#examining-symbol-tables">32.3.2. Examining Symbol Tables</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/symbol.html">32.4. <code class="docutils literal notranslate"><span class="pre">symbol</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/token.html">32.5. <code class="docutils literal notranslate"><span class="pre">token</span></code> — Constants used with Python parse trees</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/keyword.html">32.6. <code class="docutils literal notranslate"><span class="pre">keyword</span></code> — Testing for Python keywords</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/tokenize.html">32.7. <code class="docutils literal notranslate"><span class="pre">tokenize</span></code> — Tokenizer for Python source</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/tabnanny.html">32.8. <code class="docutils literal notranslate"><span class="pre">tabnanny</span></code> — Detection of ambiguous indentation</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pyclbr.html">32.9. <code class="docutils literal notranslate"><span class="pre">pyclbr</span></code> — Python class browser support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/pyclbr.html#class-objects">32.9.1. Class Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/pyclbr.html#function-objects">32.9.2. Function Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/py_compile.html">32.10. <code class="docutils literal notranslate"><span class="pre">py_compile</span></code> — Compile Python source files</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/compileall.html">32.11. <code class="docutils literal notranslate"><span class="pre">compileall</span></code> — Byte-compile Python libraries</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/compileall.html#command-line-use">32.11.1. Command-line use</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/compileall.html#public-functions">32.11.2. Public functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/dis.html">32.12. <code class="docutils literal notranslate"><span class="pre">dis</span></code> — Disassembler for Python bytecode</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/dis.html#python-bytecode-instructions">32.12.1. Python Bytecode Instructions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/pickletools.html">32.13. <code class="docutils literal notranslate"><span class="pre">pickletools</span></code> — Tools for pickle developers</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/compiler.html">33. Python compiler package</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/compiler.html#module-compiler">33.1. The basic interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/compiler.html#limitations">33.2. Limitations</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/compiler.html#python-abstract-syntax">33.3. Python Abstract Syntax</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/compiler.html#module-compiler.ast">33.3.1. AST Nodes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/compiler.html#assignment-nodes">33.3.2. Assignment nodes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/compiler.html#examples">33.3.3. Examples</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/compiler.html#module-compiler.visitor">33.4. Using Visitors to Walk ASTs</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/compiler.html#bytecode-generation">33.5. Bytecode Generation</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/misc.html">34. Miscellaneous Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/formatter.html">34.1. <code class="docutils literal notranslate"><span class="pre">formatter</span></code> — Generic output formatting</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/formatter.html#the-formatter-interface">34.1.1. The Formatter Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/formatter.html#formatter-implementations">34.1.2. Formatter Implementations</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/formatter.html#the-writer-interface">34.1.3. The Writer Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/formatter.html#writer-implementations">34.1.4. Writer Implementations</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/windows.html">35. MS Windows Specific Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/msilib.html">35.1. <code class="docutils literal notranslate"><span class="pre">msilib</span></code> — Read and write Microsoft Installer files</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#database-objects">35.1.1. Database Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#view-objects">35.1.2. View Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#summary-information-objects">35.1.3. Summary Information Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#record-objects">35.1.4. Record Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#errors">35.1.5. Errors</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#cab-objects">35.1.6. CAB Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#directory-objects">35.1.7. Directory Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#features">35.1.8. Features</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#gui-classes">35.1.9. GUI classes</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msilib.html#precomputed-tables">35.1.10. Precomputed tables</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/msvcrt.html">35.2. <code class="docutils literal notranslate"><span class="pre">msvcrt</span></code> — Useful routines from the MS VC++ runtime</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/msvcrt.html#file-operations">35.2.1. File Operations</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msvcrt.html#console-i-o">35.2.2. Console I/O</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/msvcrt.html#other-functions">35.2.3. Other Functions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/_winreg.html">35.3. <code class="docutils literal notranslate"><span class="pre">_winreg</span></code> — Windows registry access</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/_winreg.html#constants">35.3.1. Constants</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/_winreg.html#hkey-constants">35.3.1.1. HKEY_* Constants</a></li>
<li class="toctree-l5"><a class="reference internal" href="library/_winreg.html#access-rights">35.3.1.2. Access Rights</a><ul>
<li class="toctree-l6"><a class="reference internal" href="library/_winreg.html#bit-specific">35.3.1.2.1. 64-bit Specific</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="library/_winreg.html#value-types">35.3.1.3. Value Types</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="library/_winreg.html#registry-handle-objects">35.3.2. Registry Handle Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/winsound.html">35.4. <code class="docutils literal notranslate"><span class="pre">winsound</span></code> — Sound-playing interface for Windows</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/unix.html">36. Unix Specific Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/posix.html">36.1. <code class="docutils literal notranslate"><span class="pre">posix</span></code> — The most common POSIX system calls</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/posix.html#large-file-support">36.1.1. Large File Support</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/posix.html#notable-module-contents">36.1.2. Notable Module Contents</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/pwd.html">36.2. <code class="docutils literal notranslate"><span class="pre">pwd</span></code> — The password database</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/spwd.html">36.3. <code class="docutils literal notranslate"><span class="pre">spwd</span></code> — The shadow password database</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/grp.html">36.4. <code class="docutils literal notranslate"><span class="pre">grp</span></code> — The group database</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/crypt.html">36.5. <code class="docutils literal notranslate"><span class="pre">crypt</span></code> — Function to check Unix passwords</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/dl.html">36.6. <code class="docutils literal notranslate"><span class="pre">dl</span></code> — Call C functions in shared objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/dl.html#dl-objects">36.6.1. Dl Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/termios.html">36.7. <code class="docutils literal notranslate"><span class="pre">termios</span></code> — POSIX style tty control</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/termios.html#example">36.7.1. Example</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/tty.html">36.8. <code class="docutils literal notranslate"><span class="pre">tty</span></code> — Terminal control functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pty.html">36.9. <code class="docutils literal notranslate"><span class="pre">pty</span></code> — Pseudo-terminal utilities</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fcntl.html">36.10. <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> — The <code class="docutils literal notranslate"><span class="pre">fcntl</span></code> and <code class="docutils literal notranslate"><span class="pre">ioctl</span></code> system calls</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/pipes.html">36.11. <code class="docutils literal notranslate"><span class="pre">pipes</span></code> — Interface to shell pipelines</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/pipes.html#template-objects">36.11.1. Template Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/posixfile.html">36.12. <code class="docutils literal notranslate"><span class="pre">posixfile</span></code> — File-like objects with locking support</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/resource.html">36.13. <code class="docutils literal notranslate"><span class="pre">resource</span></code> — Resource usage information</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/resource.html#resource-limits">36.13.1. Resource Limits</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/resource.html#resource-usage">36.13.2. Resource Usage</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/nis.html">36.14. <code class="docutils literal notranslate"><span class="pre">nis</span></code> — Interface to Sun’s NIS (Yellow Pages)</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/syslog.html">36.15. <code class="docutils literal notranslate"><span class="pre">syslog</span></code> — Unix syslog library routines</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/syslog.html#examples">36.15.1. Examples</a><ul>
<li class="toctree-l5"><a class="reference internal" href="library/syslog.html#simple-example">36.15.1.1. Simple example</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/commands.html">36.16. <code class="docutils literal notranslate"><span class="pre">commands</span></code> — Utilities for running commands</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/mac.html">37. Mac OS X specific services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/ic.html">37.1. <code class="docutils literal notranslate"><span class="pre">ic</span></code> — Access to the Mac OS X Internet Config</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/ic.html#ic-objects">37.1.1. IC Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/macos.html">37.2. <code class="docutils literal notranslate"><span class="pre">MacOS</span></code> — Access to Mac OS interpreter features</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/macostools.html">37.3. <code class="docutils literal notranslate"><span class="pre">macostools</span></code> — Convenience routines for file manipulation</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/macostools.html#module-findertools">37.4. <code class="docutils literal notranslate"><span class="pre">findertools</span></code> — The <strong class="program">finder</strong>’s Apple Events interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/easydialogs.html">37.5. <code class="docutils literal notranslate"><span class="pre">EasyDialogs</span></code> — Basic Macintosh dialogs</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/easydialogs.html#progressbar-objects">37.5.1. ProgressBar Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/framework.html">37.6. <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code> — Interactive application framework</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/framework.html#application-objects">37.6.1. Application Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/framework.html#window-objects">37.6.2. Window Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/framework.html#controlswindow-object">37.6.3. ControlsWindow Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/framework.html#scrolledwindow-object">37.6.4. ScrolledWindow Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/framework.html#dialogwindow-objects">37.6.5. DialogWindow Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/autogil.html">37.7. <code class="docutils literal notranslate"><span class="pre">autoGIL</span></code> — Global Interpreter Lock handling in event loops</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/carbon.html">37.8. Mac OS Toolbox Modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.AE">37.8.1. <code class="docutils literal notranslate"><span class="pre">Carbon.AE</span></code> — Apple Events</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.AH">37.8.2. <code class="docutils literal notranslate"><span class="pre">Carbon.AH</span></code> — Apple Help</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.App">37.8.3. <code class="docutils literal notranslate"><span class="pre">Carbon.App</span></code> — Appearance Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Appearance">37.8.4. <code class="docutils literal notranslate"><span class="pre">Carbon.Appearance</span></code> — Appearance Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CF">37.8.5. <code class="docutils literal notranslate"><span class="pre">Carbon.CF</span></code> — Core Foundation</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CG">37.8.6. <code class="docutils literal notranslate"><span class="pre">Carbon.CG</span></code> — Core Graphics</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CarbonEvt">37.8.7. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvt</span></code> — Carbon Event Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CarbonEvents">37.8.8. <code class="docutils literal notranslate"><span class="pre">Carbon.CarbonEvents</span></code> — Carbon Event Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Cm">37.8.9. <code class="docutils literal notranslate"><span class="pre">Carbon.Cm</span></code> — Component Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Components">37.8.10. <code class="docutils literal notranslate"><span class="pre">Carbon.Components</span></code> — Component Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.ControlAccessor">37.8.11. <code class="docutils literal notranslate"><span class="pre">Carbon.ControlAccessor</span></code> — Control Manager accssors</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Controls">37.8.12. <code class="docutils literal notranslate"><span class="pre">Carbon.Controls</span></code> — Control Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CoreFounation">37.8.13. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreFounation</span></code> — CoreFounation constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.CoreGraphics">37.8.14. <code class="docutils literal notranslate"><span class="pre">Carbon.CoreGraphics</span></code> — CoreGraphics constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Ctl">37.8.15. <code class="docutils literal notranslate"><span class="pre">Carbon.Ctl</span></code> — Control Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Dialogs">37.8.16. <code class="docutils literal notranslate"><span class="pre">Carbon.Dialogs</span></code> — Dialog Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Dlg">37.8.17. <code class="docutils literal notranslate"><span class="pre">Carbon.Dlg</span></code> — Dialog Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Drag">37.8.18. <code class="docutils literal notranslate"><span class="pre">Carbon.Drag</span></code> — Drag and Drop Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Dragconst">37.8.19. <code class="docutils literal notranslate"><span class="pre">Carbon.Dragconst</span></code> — Drag and Drop Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Events">37.8.20. <code class="docutils literal notranslate"><span class="pre">Carbon.Events</span></code> — Event Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Evt">37.8.21. <code class="docutils literal notranslate"><span class="pre">Carbon.Evt</span></code> — Event Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.File">37.8.22. <code class="docutils literal notranslate"><span class="pre">Carbon.File</span></code> — File Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Files">37.8.23. <code class="docutils literal notranslate"><span class="pre">Carbon.Files</span></code> — File Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Fm">37.8.24. <code class="docutils literal notranslate"><span class="pre">Carbon.Fm</span></code> — Font Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Folder">37.8.25. <code class="docutils literal notranslate"><span class="pre">Carbon.Folder</span></code> — Folder Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Folders">37.8.26. <code class="docutils literal notranslate"><span class="pre">Carbon.Folders</span></code> — Folder Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Fonts">37.8.27. <code class="docutils literal notranslate"><span class="pre">Carbon.Fonts</span></code> — Font Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Help">37.8.28. <code class="docutils literal notranslate"><span class="pre">Carbon.Help</span></code> — Help Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.IBCarbon">37.8.29. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbon</span></code> — Carbon InterfaceBuilder</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.IBCarbonRuntime">37.8.30. <code class="docutils literal notranslate"><span class="pre">Carbon.IBCarbonRuntime</span></code> — Carbon InterfaceBuilder constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Icns">37.8.31. <code class="docutils literal notranslate"><span class="pre">Carbon.Icn</span></code> — Carbon Icon Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Icons">37.8.32. <code class="docutils literal notranslate"><span class="pre">Carbon.Icons</span></code> — Carbon Icon Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Launch">37.8.33. <code class="docutils literal notranslate"><span class="pre">Carbon.Launch</span></code> — Carbon Launch Services</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.LaunchServices">37.8.34. <code class="docutils literal notranslate"><span class="pre">Carbon.LaunchServices</span></code> — Carbon Launch Services constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.List">37.8.35. <code class="docutils literal notranslate"><span class="pre">Carbon.List</span></code> — List Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Lists">37.8.36. <code class="docutils literal notranslate"><span class="pre">Carbon.Lists</span></code> — List Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.MacHelp">37.8.37. <code class="docutils literal notranslate"><span class="pre">Carbon.MacHelp</span></code> — Help Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.MediaDescr">37.8.38. <code class="docutils literal notranslate"><span class="pre">Carbon.MediaDescr</span></code> — Parsers and generators for Quicktime Media descriptors</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Menu">37.8.39. <code class="docutils literal notranslate"><span class="pre">Carbon.Menu</span></code> — Menu Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Menus">37.8.40. <code class="docutils literal notranslate"><span class="pre">Carbon.Menus</span></code> — Menu Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Mlte">37.8.41. <code class="docutils literal notranslate"><span class="pre">Carbon.Mlte</span></code> — MultiLingual Text Editor</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.OSA">37.8.42. <code class="docutils literal notranslate"><span class="pre">Carbon.OSA</span></code> — Carbon OSA Interface</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.OSAconst">37.8.43. <code class="docutils literal notranslate"><span class="pre">Carbon.OSAconst</span></code> — Carbon OSA Interface constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.QDOffscreen">37.8.44. <code class="docutils literal notranslate"><span class="pre">Carbon.QDOffscreen</span></code> — QuickDraw Offscreen constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Qd">37.8.45. <code class="docutils literal notranslate"><span class="pre">Carbon.Qd</span></code> — QuickDraw</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Qdoffs">37.8.46. <code class="docutils literal notranslate"><span class="pre">Carbon.Qdoffs</span></code> — QuickDraw Offscreen</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Qt">37.8.47. <code class="docutils literal notranslate"><span class="pre">Carbon.Qt</span></code> — QuickTime</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.QuickDraw">37.8.48. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickDraw</span></code> — QuickDraw constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.QuickTime">37.8.49. <code class="docutils literal notranslate"><span class="pre">Carbon.QuickTime</span></code> — QuickTime constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Res">37.8.50. <code class="docutils literal notranslate"><span class="pre">Carbon.Res</span></code> — Resource Manager and Handles</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Resources">37.8.51. <code class="docutils literal notranslate"><span class="pre">Carbon.Resources</span></code> — Resource Manager and Handles constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Scrap">37.8.52. <code class="docutils literal notranslate"><span class="pre">Carbon.Scrap</span></code> — Scrap Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Snd">37.8.53. <code class="docutils literal notranslate"><span class="pre">Carbon.Snd</span></code> — Sound Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Sound">37.8.54. <code class="docutils literal notranslate"><span class="pre">Carbon.Sound</span></code> — Sound Manager constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.TE">37.8.55. <code class="docutils literal notranslate"><span class="pre">Carbon.TE</span></code> — TextEdit</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.TextEdit">37.8.56. <code class="docutils literal notranslate"><span class="pre">Carbon.TextEdit</span></code> — TextEdit constants</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Win">37.8.57. <code class="docutils literal notranslate"><span class="pre">Carbon.Win</span></code> — Window Manager</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/carbon.html#module-Carbon.Windows">37.8.58. <code class="docutils literal notranslate"><span class="pre">Carbon.Windows</span></code> — Window Manager constants</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/colorpicker.html">37.9. <code class="docutils literal notranslate"><span class="pre">ColorPicker</span></code> — Color selection dialog</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/macosa.html">38. MacPython OSA Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/gensuitemodule.html">38.1. <code class="docutils literal notranslate"><span class="pre">gensuitemodule</span></code> — Generate OSA stub packages</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/aetools.html">38.2. <code class="docutils literal notranslate"><span class="pre">aetools</span></code> — OSA client support</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/aepack.html">38.3. <code class="docutils literal notranslate"><span class="pre">aepack</span></code> — Conversion between Python variables and AppleEvent data containers</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/aetypes.html">38.4. <code class="docutils literal notranslate"><span class="pre">aetypes</span></code> — AppleEvent objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/miniaeframe.html">38.5. <code class="docutils literal notranslate"><span class="pre">MiniAEFrame</span></code> — Open Scripting Architecture server support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/miniaeframe.html#aeserver-objects">38.5.1. AEServer Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/sgi.html">39. SGI IRIX Specific Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/al.html">39.1. <code class="docutils literal notranslate"><span class="pre">al</span></code> — Audio functions on the SGI</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/al.html#configuration-objects">39.1.1. Configuration Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/al.html#port-objects">39.1.2. Port Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/al.html#module-AL">39.2. <code class="docutils literal notranslate"><span class="pre">AL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">al</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/cd.html">39.3. <code class="docutils literal notranslate"><span class="pre">cd</span></code> — CD-ROM access on SGI systems</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/cd.html#player-objects">39.3.1. Player Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/cd.html#parser-objects">39.3.2. Parser Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/fl.html">39.4. <code class="docutils literal notranslate"><span class="pre">fl</span></code> — FORMS library for graphical user interfaces</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/fl.html#functions-defined-in-module-fl">39.4.1. Functions Defined in Module <code class="docutils literal notranslate"><span class="pre">fl</span></code></a></li>
<li class="toctree-l4"><a class="reference internal" href="library/fl.html#form-objects">39.4.2. Form Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/fl.html#forms-objects">39.4.3. FORMS Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/fl.html#module-FL">39.5. <code class="docutils literal notranslate"><span class="pre">FL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">fl</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fl.html#module-flp">39.6. <code class="docutils literal notranslate"><span class="pre">flp</span></code> — Functions for loading stored FORMS designs</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/fm.html">39.7. <code class="docutils literal notranslate"><span class="pre">fm</span></code> — <em>Font Manager</em> interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gl.html">39.8. <code class="docutils literal notranslate"><span class="pre">gl</span></code> — <em>Graphics Library</em> interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gl.html#module-DEVICE">39.9. <code class="docutils literal notranslate"><span class="pre">DEVICE</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/gl.html#module-GL">39.10. <code class="docutils literal notranslate"><span class="pre">GL</span></code> — Constants used with the <code class="docutils literal notranslate"><span class="pre">gl</span></code> module</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/imgfile.html">39.11. <code class="docutils literal notranslate"><span class="pre">imgfile</span></code> — Support for SGI imglib files</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/jpeg.html">39.12. <code class="docutils literal notranslate"><span class="pre">jpeg</span></code> — Read and write JPEG files</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/sun.html">40. SunOS Specific Services</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/sunaudio.html">40.1. <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code> — Access to Sun audio hardware</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/sunaudio.html#audio-device-objects">40.1.1. Audio Device Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/sunaudio.html#module-SUNAUDIODEV">40.2. <code class="docutils literal notranslate"><span class="pre">SUNAUDIODEV</span></code> — Constants used with <code class="docutils literal notranslate"><span class="pre">sunaudiodev</span></code></a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="library/undoc.html">41. Undocumented Modules</a><ul>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#miscellaneous-useful-utilities">41.1. Miscellaneous useful utilities</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#platform-specific-modules">41.2. Platform specific modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#multimedia">41.3. Multimedia</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#undocumented-mac-os-modules">41.4. Undocumented Mac OS modules</a><ul>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-applesingle">41.4.1. <code class="docutils literal notranslate"><span class="pre">applesingle</span></code> — AppleSingle decoder</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-buildtools">41.4.2. <code class="docutils literal notranslate"><span class="pre">buildtools</span></code> — Helper module for BuildApplet and Friends</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-cfmfile">41.4.3. <code class="docutils literal notranslate"><span class="pre">cfmfile</span></code> — Code Fragment Resource module</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-icopen">41.4.4. <code class="docutils literal notranslate"><span class="pre">icopen</span></code> — Internet Config replacement for <code class="docutils literal notranslate"><span class="pre">open()</span></code></a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-macerrors">41.4.5. <code class="docutils literal notranslate"><span class="pre">macerrors</span></code> — Mac OS Errors</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-macresource">41.4.6. <code class="docutils literal notranslate"><span class="pre">macresource</span></code> — Locate script resources</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-Nav">41.4.7. <code class="docutils literal notranslate"><span class="pre">Nav</span></code> — NavServices calls</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-PixMapWrapper">41.4.8. <code class="docutils literal notranslate"><span class="pre">PixMapWrapper</span></code> — Wrapper for PixMap objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-videoreader">41.4.9. <code class="docutils literal notranslate"><span class="pre">videoreader</span></code> — Read QuickTime movies</a></li>
<li class="toctree-l4"><a class="reference internal" href="library/undoc.html#module-W">41.4.10. <code class="docutils literal notranslate"><span class="pre">W</span></code> — Widgets built on <code class="docutils literal notranslate"><span class="pre">FrameWork</span></code></a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#obsolete">41.5. Obsolete</a></li>
<li class="toctree-l3"><a class="reference internal" href="library/undoc.html#sgi-specific-extension-modules">41.6. SGI-specific Extension modules</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="extending/index.html">Extending and Embedding the Python Interpreter</a><ul>
<li class="toctree-l2"><a class="reference internal" href="extending/extending.html">1. Extending Python with C or C++</a><ul>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#a-simple-example">1.1. A Simple Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#intermezzo-errors-and-exceptions">1.2. Intermezzo: Errors and Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#back-to-the-example">1.3. Back to the Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#the-module-s-method-table-and-initialization-function">1.4. The Module’s Method Table and Initialization Function</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#compilation-and-linkage">1.5. Compilation and Linkage</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#calling-python-functions-from-c">1.6. Calling Python Functions from C</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#extracting-parameters-in-extension-functions">1.7. Extracting Parameters in Extension Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#keyword-parameters-for-extension-functions">1.8. Keyword Parameters for Extension Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#building-arbitrary-values">1.9. Building Arbitrary Values</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#reference-counts">1.10. Reference Counts</a><ul>
<li class="toctree-l4"><a class="reference internal" href="extending/extending.html#reference-counting-in-python">1.10.1. Reference Counting in Python</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/extending.html#ownership-rules">1.10.2. Ownership Rules</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/extending.html#thin-ice">1.10.3. Thin Ice</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/extending.html#null-pointers">1.10.4. NULL Pointers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#writing-extensions-in-c">1.11. Writing Extensions in C++</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/extending.html#providing-a-c-api-for-an-extension-module">1.12. Providing a C API for an Extension Module</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="extending/newtypes.html">2. Defining New Types</a><ul>
<li class="toctree-l3"><a class="reference internal" href="extending/newtypes.html#the-basics">2.1. The Basics</a><ul>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#adding-data-and-methods-to-the-basic-example">2.1.1. Adding data and methods to the Basic example</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#providing-finer-control-over-data-attributes">2.1.2. Providing finer control over data attributes</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#supporting-cyclic-garbage-collection">2.1.3. Supporting cyclic garbage collection</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#subclassing-other-types">2.1.4. Subclassing other types</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="extending/newtypes.html#type-methods">2.2. Type Methods</a><ul>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#finalization-and-de-allocation">2.2.1. Finalization and De-allocation</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#object-presentation">2.2.2. Object Presentation</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#attribute-management">2.2.3. Attribute Management</a><ul>
<li class="toctree-l5"><a class="reference internal" href="extending/newtypes.html#generic-attribute-management">2.2.3.1. Generic Attribute Management</a></li>
<li class="toctree-l5"><a class="reference internal" href="extending/newtypes.html#type-specific-attribute-management">2.2.3.2. Type-specific Attribute Management</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#object-comparison">2.2.4. Object Comparison</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#abstract-protocol-support">2.2.5. Abstract Protocol Support</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#weak-reference-support">2.2.6. Weak Reference Support</a></li>
<li class="toctree-l4"><a class="reference internal" href="extending/newtypes.html#more-suggestions">2.2.7. More Suggestions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="extending/building.html">3. Building C and C++ Extensions with distutils</a><ul>
<li class="toctree-l3"><a class="reference internal" href="extending/building.html#distributing-your-extension-modules">3.1. Distributing your extension modules</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="extending/windows.html">4. Building C and C++ Extensions on Windows</a><ul>
<li class="toctree-l3"><a class="reference internal" href="extending/windows.html#a-cookbook-approach">4.1. A Cookbook Approach</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/windows.html#differences-between-unix-and-windows">4.2. Differences Between Unix and Windows</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/windows.html#using-dlls-in-practice">4.3. Using DLLs in Practice</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="extending/embedding.html">5. Embedding Python in Another Application</a><ul>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#very-high-level-embedding">5.1. Very High Level Embedding</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#beyond-very-high-level-embedding-an-overview">5.2. Beyond Very High Level Embedding: An overview</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#pure-embedding">5.3. Pure Embedding</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#extending-embedded-python">5.4. Extending Embedded Python</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#embedding-python-in-c">5.5. Embedding Python in C++</a></li>
<li class="toctree-l3"><a class="reference internal" href="extending/embedding.html#compiling-and-linking-under-unix-like-systems">5.6. Compiling and Linking under Unix-like systems</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="c-api/index.html">Python/C API Reference Manual</a><ul>
<li class="toctree-l2"><a class="reference internal" href="c-api/intro.html">Introduction</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/intro.html#include-files">Include Files</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/intro.html#objects-types-and-reference-counts">Objects, Types and Reference Counts</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/intro.html#reference-counts">Reference Counts</a><ul>
<li class="toctree-l5"><a class="reference internal" href="c-api/intro.html#reference-count-details">Reference Count Details</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="c-api/intro.html#types">Types</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/intro.html#exceptions">Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/intro.html#embedding-python">Embedding Python</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/intro.html#debugging-builds">Debugging Builds</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/veryhigh.html">The Very High Level Layer</a></li>
<li class="toctree-l2"><a class="reference internal" href="c-api/refcounting.html">Reference Counting</a></li>
<li class="toctree-l2"><a class="reference internal" href="c-api/exceptions.html">Exception Handling</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/exceptions.html#unicode-exception-objects">Unicode Exception Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/exceptions.html#recursion-control">Recursion Control</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/exceptions.html#standard-exceptions">Standard Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/exceptions.html#standard-warning-categories">Standard Warning Categories</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/exceptions.html#string-exceptions">String Exceptions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/utilities.html">Utilities</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/sys.html">Operating System Utilities</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/sys.html#system-functions">System Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/sys.html#process-control">Process Control</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/import.html">Importing Modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/marshal.html">Data marshalling support</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/arg.html">Parsing arguments and building values</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/conversion.html">String conversion and formatting</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/reflection.html">Reflection</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/codec.html">Codec registry and support functions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/codec.html#codec-lookup-api">Codec lookup API</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/codec.html#registry-api-for-unicode-encoding-error-handlers">Registry API for Unicode encoding error handlers</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/abstract.html">Abstract Objects Layer</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/object.html">Object Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/number.html">Number Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/sequence.html">Sequence Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/mapping.html">Mapping Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/iter.html">Iterator Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/objbuffer.html">Old Buffer Protocol</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/concrete.html">Concrete Objects Layer</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/concrete.html#fundamental-objects">Fundamental Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/type.html">Type Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/none.html">The <code class="docutils literal notranslate"><span class="pre">None</span></code> Object</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/concrete.html#numeric-objects">Numeric Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/int.html">Plain Integer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/bool.html">Boolean Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/long.html">Long Integer Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/float.html">Floating Point Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/complex.html">Complex Number Objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="c-api/complex.html#complex-numbers-as-c-structures">Complex Numbers as C Structures</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/complex.html#complex-numbers-as-python-objects">Complex Numbers as Python Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/concrete.html#sequence-objects">Sequence Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/bytearray.html">Byte Array Objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="c-api/bytearray.html#type-check-macros">Type check macros</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/bytearray.html#direct-api-functions">Direct API functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/bytearray.html#macros">Macros</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="c-api/string.html">String/Bytes Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/unicode.html">Unicode Objects and Codecs</a><ul>
<li class="toctree-l5"><a class="reference internal" href="c-api/unicode.html#unicode-objects">Unicode Objects</a><ul>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#unicode-type">Unicode Type</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#unicode-character-properties">Unicode Character Properties</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#plain-py-unicode">Plain Py_UNICODE</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#wchar-t-support">wchar_t Support</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="c-api/unicode.html#built-in-codecs">Built-in Codecs</a><ul>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#generic-codecs">Generic Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#utf-8-codecs">UTF-8 Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#utf-32-codecs">UTF-32 Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#utf-16-codecs">UTF-16 Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#utf-7-codecs">UTF-7 Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#unicode-escape-codecs">Unicode-Escape Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#raw-unicode-escape-codecs">Raw-Unicode-Escape Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#latin-1-codecs">Latin-1 Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#ascii-codecs">ASCII Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#character-map-codecs">Character Map Codecs</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#mbcs-codecs-for-windows">MBCS codecs for Windows</a></li>
<li class="toctree-l6"><a class="reference internal" href="c-api/unicode.html#methods-slots">Methods &amp; Slots</a></li>
</ul>
</li>
<li class="toctree-l5"><a class="reference internal" href="c-api/unicode.html#methods-and-slot-functions">Methods and Slot Functions</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="c-api/buffer.html">Buffers and Memoryview Objects</a><ul>
<li class="toctree-l5"><a class="reference internal" href="c-api/buffer.html#the-new-style-py-buffer-struct">The new-style Py_buffer struct</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/buffer.html#buffer-related-functions">Buffer related functions</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/buffer.html#memoryview-objects">MemoryView objects</a></li>
<li class="toctree-l5"><a class="reference internal" href="c-api/buffer.html#old-style-buffer-objects">Old-style buffer objects</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="c-api/tuple.html">Tuple Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/list.html">List Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/concrete.html#mapping-objects">Mapping Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/dict.html">Dictionary Objects</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/concrete.html#other-objects">Other Objects</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/class.html">Class and Instance Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/function.html">Function Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/method.html">Method Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/file.html">File Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/module.html">Module Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/iterator.html">Iterator Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/descriptor.html">Descriptor Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/slice.html">Slice Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/slice.html#ellipsis-object">Ellipsis Object</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/weakref.html">Weak Reference Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/capsule.html">Capsules</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/cobject.html">CObjects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/cell.html">Cell Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/gen.html">Generator Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/datetime.html">DateTime Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/set.html">Set Objects</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/code.html">Code Objects</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/init.html">Initialization, Finalization, and Threads</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#initializing-and-finalizing-the-interpreter">Initializing and finalizing the interpreter</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#process-wide-parameters">Process-wide parameters</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#thread-state-and-the-global-interpreter-lock">Thread State and the Global Interpreter Lock</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/init.html#releasing-the-gil-from-extension-code">Releasing the GIL from extension code</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/init.html#non-python-created-threads">Non-Python created threads</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/init.html#high-level-api">High-level API</a></li>
<li class="toctree-l4"><a class="reference internal" href="c-api/init.html#low-level-api">Low-level API</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#sub-interpreter-support">Sub-interpreter support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="c-api/init.html#bugs-and-caveats">Bugs and caveats</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#asynchronous-notifications">Asynchronous Notifications</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#profiling-and-tracing">Profiling and Tracing</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/init.html#advanced-debugger-support">Advanced Debugger Support</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/memory.html">Memory Management</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/memory.html#overview">Overview</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/memory.html#memory-interface">Memory Interface</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/memory.html#object-allocators">Object allocators</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/memory.html#the-pymalloc-allocator">The pymalloc allocator</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/memory.html#examples">Examples</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="c-api/objimpl.html">Object Implementation Support</a><ul>
<li class="toctree-l3"><a class="reference internal" href="c-api/allocation.html">Allocating Objects on the Heap</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/structures.html">Common Object Structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/typeobj.html">Type Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/typeobj.html#number-object-structures">Number Object Structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/typeobj.html#mapping-object-structures">Mapping Object Structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/typeobj.html#sequence-object-structures">Sequence Object Structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/typeobj.html#buffer-object-structures">Buffer Object Structures</a></li>
<li class="toctree-l3"><a class="reference internal" href="c-api/gcsupport.html">Supporting Cyclic Garbage Collection</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="distributing/index.html">Distributing Python Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="distributing/index.html#key-terms">Key terms</a></li>
<li class="toctree-l2"><a class="reference internal" href="distributing/index.html#open-source-licensing-and-collaboration">Open source licensing and collaboration</a></li>
<li class="toctree-l2"><a class="reference internal" href="distributing/index.html#installing-the-tools">Installing the tools</a></li>
<li class="toctree-l2"><a class="reference internal" href="distributing/index.html#reading-the-guide">Reading the guide</a></li>
<li class="toctree-l2"><a class="reference internal" href="distributing/index.html#how-do-i">How do I…?</a><ul>
<li class="toctree-l3"><a class="reference internal" href="distributing/index.html#choose-a-name-for-my-project">… choose a name for my project?</a></li>
<li class="toctree-l3"><a class="reference internal" href="distributing/index.html#create-and-distribute-binary-extensions">… create and distribute binary extensions?</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="installing/index.html">Installing Python Modules</a><ul>
<li class="toctree-l2"><a class="reference internal" href="installing/index.html#key-terms">Key terms</a></li>
<li class="toctree-l2"><a class="reference internal" href="installing/index.html#basic-usage">Basic usage</a></li>
<li class="toctree-l2"><a class="reference internal" href="installing/index.html#how-do-i">How do I …?</a><ul>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#install-pip-in-versions-of-python-prior-to-python-2-7-9">… install <code class="docutils literal notranslate"><span class="pre">pip</span></code> in versions of Python prior to Python 2.7.9?</a></li>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#install-packages-just-for-the-current-user">… install packages just for the current user?</a></li>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#install-scientific-python-packages">… install scientific Python packages?</a></li>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#work-with-multiple-versions-of-python-installed-in-parallel">… work with multiple versions of Python installed in parallel?</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="installing/index.html#common-installation-issues">Common installation issues</a><ul>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#installing-into-the-system-python-on-linux">Installing into the system Python on Linux</a></li>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#pip-not-installed">Pip not installed</a></li>
<li class="toctree-l3"><a class="reference internal" href="installing/index.html#installing-binary-extensions">Installing binary extensions</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="howto/index.html">Python HOWTOs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="howto/pyporting.html">Porting Python 2 Code to Python 3</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/pyporting.html#the-short-explanation">The Short Explanation</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/pyporting.html#details">Details</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#drop-support-for-python-2-6-and-older">Drop support for Python 2.6 and older</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#make-sure-you-specify-the-proper-version-support-in-your-setup-py-file">Make sure you specify the proper version support in your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#have-good-test-coverage">Have good test coverage</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#learn-the-differences-between-python-2-3">Learn the differences between Python 2 &amp; 3</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#update-your-code">Update your code</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/pyporting.html#division">Division</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/pyporting.html#text-versus-binary-data">Text versus binary data</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/pyporting.html#use-feature-detection-instead-of-version-detection">Use feature detection instead of version detection</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#prevent-compatibility-regressions">Prevent compatibility regressions</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#check-which-dependencies-block-your-transition">Check which dependencies block your transition</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#update-your-setup-py-file-to-denote-python-3-compatibility">Update your <code class="docutils literal notranslate"><span class="pre">setup.py</span></code> file to denote Python 3 compatibility</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#use-continuous-integration-to-stay-compatible">Use continuous integration to stay compatible</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/pyporting.html#consider-using-optional-static-type-checking">Consider using optional static type checking</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/cporting.html">Porting Extension Modules to Python 3</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/cporting.html#conditional-compilation">Conditional compilation</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/cporting.html#changes-to-object-apis">Changes to Object APIs</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/cporting.html#str-unicode-unification">str/unicode Unification</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/cporting.html#long-int-unification">long/int Unification</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/cporting.html#module-initialization-and-state">Module initialization and state</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/cporting.html#cobject-replaced-with-capsule">CObject replaced with Capsule</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/cporting.html#other-options">Other options</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/curses.html">Curses Programming with Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#what-is-curses">What is curses?</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/curses.html#the-python-curses-module">The Python curses module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#starting-and-ending-a-curses-application">Starting and ending a curses application</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#windows-and-pads">Windows and Pads</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#displaying-text">Displaying Text</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/curses.html#attributes-and-color">Attributes and Color</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#user-input">User Input</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/curses.html#for-more-information">For More Information</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/descriptor.html">Descriptor HowTo Guide</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#abstract">Abstract</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#definition-and-introduction">Definition and Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#descriptor-protocol">Descriptor Protocol</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#invoking-descriptors">Invoking Descriptors</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#descriptor-example">Descriptor Example</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#properties">Properties</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#functions-and-methods">Functions and Methods</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/descriptor.html#static-methods-and-class-methods">Static Methods and Class Methods</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/doanddont.html">Idioms and Anti-Idioms in Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/doanddont.html#language-constructs-you-should-not-use">Language Constructs You Should Not Use</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/doanddont.html#from-module-import">from module import *</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/doanddont.html#inside-function-definitions">Inside Function Definitions</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/doanddont.html#at-module-level">At Module Level</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/doanddont.html#when-it-is-just-fine">When It Is Just Fine</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/doanddont.html#unadorned-exec-execfile-and-friends">Unadorned <code class="docutils literal notranslate"><span class="pre">exec</span></code>, <code class="docutils literal notranslate"><span class="pre">execfile()</span></code> and friends</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/doanddont.html#from-module-import-name1-name2">from module import name1, name2</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/doanddont.html#except">except:</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/doanddont.html#exceptions">Exceptions</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/doanddont.html#using-the-batteries">Using the Batteries</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/doanddont.html#using-backslash-to-continue-statements">Using Backslash to Continue Statements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/functional.html">Functional Programming HOWTO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#introduction">Introduction</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#formal-provability">Formal provability</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#modularity">Modularity</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#ease-of-debugging-and-testing">Ease of debugging and testing</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#composability">Composability</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#iterators">Iterators</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#data-types-that-support-iterators">Data Types That Support Iterators</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#generator-expressions-and-list-comprehensions">Generator expressions and list comprehensions</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#generators">Generators</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#passing-values-into-a-generator">Passing values into a generator</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#built-in-functions">Built-in functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#small-functions-and-the-lambda-expression">Small functions and the lambda expression</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#the-itertools-module">The itertools module</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#creating-new-iterators">Creating new iterators</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#calling-functions-on-elements">Calling functions on elements</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#selecting-elements">Selecting elements</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#grouping-elements">Grouping elements</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#the-functools-module">The functools module</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#the-operator-module">The operator module</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#revision-history-and-acknowledgements">Revision History and Acknowledgements</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/functional.html#references">References</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#general">General</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#python-specific">Python-specific</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/functional.html#python-documentation">Python documentation</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/logging.html">Logging HOWTO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#basic-logging-tutorial">Basic Logging Tutorial</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#when-to-use-logging">When to use logging</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#a-simple-example">A simple example</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#logging-to-a-file">Logging to a file</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#logging-from-multiple-modules">Logging from multiple modules</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#logging-variable-data">Logging variable data</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#changing-the-format-of-displayed-messages">Changing the format of displayed messages</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#displaying-the-date-time-in-messages">Displaying the date/time in messages</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#next-steps">Next Steps</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#advanced-logging-tutorial">Advanced Logging Tutorial</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#logging-flow">Logging Flow</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#loggers">Loggers</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#handlers">Handlers</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#formatters">Formatters</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#configuring-logging">Configuring Logging</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#what-happens-if-no-configuration-is-provided">What happens if no configuration is provided</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#configuring-logging-for-a-library">Configuring Logging for a Library</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#logging-levels">Logging Levels</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/logging.html#custom-levels">Custom Levels</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#useful-handlers">Useful Handlers</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#exceptions-raised-during-logging">Exceptions raised during logging</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#using-arbitrary-objects-as-messages">Using arbitrary objects as messages</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging.html#optimization">Optimization</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/logging-cookbook.html">Logging Cookbook</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#using-logging-in-multiple-modules">Using logging in multiple modules</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#logging-from-multiple-threads">Logging from multiple threads</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#multiple-handlers-and-formatters">Multiple handlers and formatters</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#logging-to-multiple-destinations">Logging to multiple destinations</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#configuration-server-example">Configuration server example</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network">Sending and receiving logging events across a network</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#adding-contextual-information-to-your-logging-output">Adding contextual information to your logging output</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/logging-cookbook.html#using-loggeradapters-to-impart-contextual-information">Using LoggerAdapters to impart contextual information</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/logging-cookbook.html#using-objects-other-than-dicts-to-pass-contextual-information">Using objects other than dicts to pass contextual information</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/logging-cookbook.html#using-filters-to-impart-contextual-information">Using Filters to impart contextual information</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes">Logging to a single file from multiple processes</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#using-file-rotation">Using file rotation</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#an-example-dictionary-based-configuration">An example dictionary-based configuration</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#inserting-a-bom-into-messages-sent-to-a-sysloghandler">Inserting a BOM into messages sent to a SysLogHandler</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#implementing-structured-logging">Implementing structured logging</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#customizing-handlers-with-dictconfig">Customizing handlers with <code class="docutils literal notranslate"><span class="pre">dictConfig()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#configuring-filters-with-dictconfig">Configuring filters with <code class="docutils literal notranslate"><span class="pre">dictConfig()</span></code></a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#customized-exception-formatting">Customized exception formatting</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#speaking-logging-messages">Speaking logging messages</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#buffering-logging-messages-and-outputting-them-conditionally">Buffering logging messages and outputting them conditionally</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#formatting-times-using-utc-gmt-via-configuration">Formatting times using UTC (GMT) via configuration</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/logging-cookbook.html#using-a-context-manager-for-selective-logging">Using a context manager for selective logging</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/regex.html">Regular Expression HOWTO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#introduction">Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#simple-patterns">Simple Patterns</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#matching-characters">Matching Characters</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#repeating-things">Repeating Things</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#using-regular-expressions">Using Regular Expressions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#compiling-regular-expressions">Compiling Regular Expressions</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#the-backslash-plague">The Backslash Plague</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#performing-matches">Performing Matches</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#module-level-functions">Module-Level Functions</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#compilation-flags">Compilation Flags</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#more-pattern-power">More Pattern Power</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#more-metacharacters">More Metacharacters</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#grouping">Grouping</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#non-capturing-and-named-groups">Non-capturing and Named Groups</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#lookahead-assertions">Lookahead Assertions</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#modifying-strings">Modifying Strings</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#splitting-strings">Splitting Strings</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#search-and-replace">Search and Replace</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#common-problems">Common Problems</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#use-string-methods">Use String Methods</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#match-versus-search">match() versus search()</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#greedy-versus-non-greedy">Greedy versus Non-Greedy</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/regex.html#using-re-verbose">Using re.VERBOSE</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/regex.html#feedback">Feedback</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/sockets.html">Socket Programming HOWTO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/sockets.html#sockets">Sockets</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/sockets.html#history">History</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/sockets.html#creating-a-socket">Creating a Socket</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/sockets.html#ipc">IPC</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/sockets.html#using-a-socket">Using a Socket</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/sockets.html#binary-data">Binary Data</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/sockets.html#disconnecting">Disconnecting</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/sockets.html#when-sockets-die">When Sockets Die</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/sockets.html#non-blocking-sockets">Non-blocking Sockets</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/sockets.html#performance">Performance</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/sorting.html">Sorting HOW TO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#sorting-basics">Sorting Basics</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#key-functions">Key Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#operator-module-functions">Operator Module Functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#ascending-and-descending">Ascending and Descending</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#sort-stability-and-complex-sorts">Sort Stability and Complex Sorts</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#the-old-way-using-decorate-sort-undecorate">The Old Way Using Decorate-Sort-Undecorate</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#the-old-way-using-the-cmp-parameter">The Old Way Using the <em>cmp</em> Parameter</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/sorting.html#odd-and-ends">Odd and Ends</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/unicode.html">Unicode HOWTO</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/unicode.html#introduction-to-unicode">Introduction to Unicode</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#history-of-character-codes">History of Character Codes</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#definitions">Definitions</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#encodings">Encodings</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#references">References</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/unicode.html#python-2-x-s-unicode-support">Python 2.x’s Unicode Support</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#the-unicode-type">The Unicode Type</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#unicode-literals-in-python-source-code">Unicode Literals in Python Source Code</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#unicode-properties">Unicode Properties</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#id1">References</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/unicode.html#reading-and-writing-unicode-data">Reading and Writing Unicode Data</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#unicode-filenames">Unicode filenames</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#tips-for-writing-unicode-aware-programs">Tips for Writing Unicode-aware Programs</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/unicode.html#id2">References</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/unicode.html#revision-history-and-acknowledgements">Revision History and Acknowledgements</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/urllib2.html">HOWTO Fetch Internet Resources Using urllib2</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#introduction">Introduction</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#fetching-urls">Fetching URLs</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/urllib2.html#data">Data</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/urllib2.html#headers">Headers</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#handling-exceptions">Handling Exceptions</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/urllib2.html#urlerror">URLError</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/urllib2.html#httperror">HTTPError</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/urllib2.html#error-codes">Error Codes</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/urllib2.html#wrapping-it-up">Wrapping it Up</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/urllib2.html#number-1">Number 1</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/urllib2.html#number-2">Number 2</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#info-and-geturl">info and geturl</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#openers-and-handlers">Openers and Handlers</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#id6">Basic Authentication</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#proxies">Proxies</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#sockets-and-layers">Sockets and Layers</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/urllib2.html#footnotes">Footnotes</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/webservers.html">HOWTO Use Python in the web</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/webservers.html#the-low-level-view">The Low-Level View</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#common-gateway-interface">Common Gateway Interface</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#simple-script-for-testing-cgi">Simple script for testing CGI</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#setting-up-cgi-on-your-own-server">Setting up CGI on your own server</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#common-problems-with-cgi-scripts">Common problems with CGI scripts</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#mod-python">mod_python</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#fastcgi-and-scgi">FastCGI and SCGI</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#setting-up-fastcgi">Setting up FastCGI</a></li>
</ul>
</li>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#mod-wsgi">mod_wsgi</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/webservers.html#step-back-wsgi">Step back: WSGI</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#wsgi-servers">WSGI Servers</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#case-study-moinmoin">Case study: MoinMoin</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/webservers.html#model-view-controller">Model-View-Controller</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/webservers.html#ingredients-for-websites">Ingredients for Websites</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#templates">Templates</a></li>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#data-persistence">Data persistence</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/webservers.html#frameworks">Frameworks</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/webservers.html#some-notable-frameworks">Some notable frameworks</a><ul>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#django">Django</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#turbogears">TurboGears</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#zope">Zope</a></li>
<li class="toctree-l5"><a class="reference internal" href="howto/webservers.html#other-notable-frameworks">Other notable frameworks</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="howto/argparse.html">Argparse Tutorial</a><ul>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#concepts">Concepts</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#the-basics">The basics</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#introducing-positional-arguments">Introducing Positional arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#introducing-optional-arguments">Introducing Optional arguments</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/argparse.html#short-options">Short options</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#combining-positional-and-optional-arguments">Combining Positional and Optional arguments</a></li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#getting-a-little-more-advanced">Getting a little more advanced</a><ul>
<li class="toctree-l4"><a class="reference internal" href="howto/argparse.html#conflicting-options">Conflicting options</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="howto/argparse.html#conclusion">Conclusion</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="faq/index.html">Python Frequently Asked Questions</a><ul>
<li class="toctree-l2"><a class="reference internal" href="faq/general.html">General Python FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/general.html#general-information">General Information</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/general.html#python-in-the-real-world">Python in the real world</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/general.html#upgrading-python">Upgrading Python</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/programming.html">Programming FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#general-questions">General Questions</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#core-language">Core Language</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#numbers-and-strings">Numbers and strings</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#sequences-tuples-lists">Sequences (Tuples/Lists)</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#dictionaries">Dictionaries</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#objects">Objects</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/programming.html#modules">Modules</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/design.html">Design and History FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-does-python-use-indentation-for-grouping-of-statements">Why does Python use indentation for grouping of statements?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-am-i-getting-strange-results-with-simple-arithmetic-operations">Why am I getting strange results with simple arithmetic operations?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-are-floating-point-calculations-so-inaccurate">Why are floating point calculations so inaccurate?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-are-python-strings-immutable">Why are Python strings immutable?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls">Why must ‘self’ be used explicitly in method definitions and calls?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-can-t-i-use-an-assignment-in-an-expression">Why can’t I use an assignment in an expression?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list">Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-is-join-a-string-method-instead-of-a-list-or-tuple-method">Why is join() a string method instead of a list or tuple method?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#how-fast-are-exceptions">How fast are exceptions?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python">Why isn’t there a switch or case statement in Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#can-t-you-emulate-threads-in-the-interpreter-instead-of-relying-on-an-os-specific-thread-implementation">Can’t you emulate threads in the interpreter instead of relying on an OS-specific thread implementation?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-can-t-lambda-expressions-contain-statements">Why can’t lambda expressions contain statements?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#can-python-be-compiled-to-machine-code-c-or-some-other-language">Can Python be compiled to machine code, C or some other language?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#how-does-python-manage-memory">How does Python manage memory?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-isn-t-all-memory-freed-when-python-exits">Why isn’t all memory freed when Python exits?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-are-there-separate-tuple-and-list-data-types">Why are there separate tuple and list data types?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#how-are-lists-implemented-in-cpython">How are lists implemented in CPython?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#how-are-dictionaries-implemented-in-cpython">How are dictionaries implemented in CPython?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-must-dictionary-keys-be-immutable">Why must dictionary keys be immutable?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-doesn-t-list-sort-return-the-sorted-list">Why doesn’t list.sort() return the sorted list?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#how-do-you-specify-and-enforce-an-interface-spec-in-python">How do you specify and enforce an interface spec in Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-is-there-no-goto">Why is there no goto?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-can-t-raw-strings-r-strings-end-with-a-backslash">Why can’t raw strings (r-strings) end with a backslash?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-doesn-t-python-have-a-with-statement-for-attribute-assignments">Why doesn’t Python have a “with” statement for attribute assignments?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-are-colons-required-for-the-if-while-def-class-statements">Why are colons required for the if/while/def/class statements?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/design.html#why-does-python-allow-commas-at-the-end-of-lists-and-tuples">Why does Python allow commas at the end of lists and tuples?</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/library.html">Library and Extension FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#general-library-questions">General Library Questions</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#common-tasks">Common tasks</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#threads">Threads</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#input-and-output">Input and Output</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#network-internet-programming">Network/Internet Programming</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#databases">Databases</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/library.html#mathematics-and-numerics">Mathematics and Numerics</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/extending.html">Extending/Embedding FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#can-i-create-my-own-functions-in-c">Can I create my own functions in C?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#id1">Can I create my own functions in C++?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#writing-c-is-hard-are-there-any-alternatives">Writing C is hard; are there any alternatives?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-can-i-execute-arbitrary-python-statements-from-c">How can I execute arbitrary Python statements from C?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-can-i-evaluate-an-arbitrary-python-expression-from-c">How can I evaluate an arbitrary Python expression from C?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-extract-c-values-from-a-python-object">How do I extract C values from a Python object?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-use-py-buildvalue-to-create-a-tuple-of-arbitrary-length">How do I use Py_BuildValue() to create a tuple of arbitrary length?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-call-an-object-s-method-from-c">How do I call an object’s method from C?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr">How do I catch the output from PyErr_Print() (or anything that prints to stdout/stderr)?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-access-a-module-written-in-python-from-c">How do I access a module written in Python from C?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-interface-to-c-objects-from-python">How do I interface to C++ objects from Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#i-added-a-module-using-the-setup-file-and-the-make-fails-why">I added a module using the Setup file and the make fails; why?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-debug-an-extension">How do I debug an extension?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#i-want-to-compile-a-python-module-on-my-linux-system-but-some-files-are-missing-why">I want to compile a Python module on my Linux system, but some files are missing. Why?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#what-does-systemerror-pyimport-fixupextension-module-yourmodule-not-loaded-mean">What does “SystemError: _PyImport_FixupExtension: module yourmodule not loaded” mean?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-tell-incomplete-input-from-invalid-input">How do I tell “incomplete input” from “invalid input”?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#how-do-i-find-undefined-g-symbols-builtin-new-or-pure-virtual">How do I find undefined g++ symbols __builtin_new or __pure_virtual?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#can-i-create-an-object-class-with-some-methods-implemented-in-c-and-others-in-python-e-g-through-inheritance">Can I create an object class with some methods implemented in C and others in Python (e.g. through inheritance)?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/extending.html#when-importing-module-x-why-do-i-get-undefined-symbol-pyunicodeucs2">When importing module X, why do I get “undefined symbol: PyUnicodeUCS2*”?</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/windows.html">Python on Windows FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-run-a-python-program-under-windows">How do I run a Python program under Windows?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-make-python-scripts-executable">How do I make Python scripts executable?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#why-does-python-sometimes-take-so-long-to-start">Why does Python sometimes take so long to start?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-make-an-executable-from-a-python-script">How do I make an executable from a Python script?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#is-a-pyd-file-the-same-as-a-dll">Is a <code class="docutils literal notranslate"><span class="pre">*.pyd</span></code> file the same as a DLL?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-can-i-embed-python-into-a-windows-application">How can I embed Python into a Windows application?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-keep-editors-from-inserting-tabs-into-my-python-source">How do I keep editors from inserting tabs into my Python source?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-check-for-a-keypress-without-blocking">How do I check for a keypress without blocking?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-emulate-os-kill-in-windows">How do I emulate os.kill() in Windows?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/windows.html#how-do-i-extract-the-downloaded-documentation-on-windows">How do I extract the downloaded documentation on Windows?</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/gui.html">Graphic User Interface FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/gui.html#what-platform-independent-gui-toolkits-exist-for-python">What platform-independent GUI toolkits exist for Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/gui.html#what-platform-specific-gui-toolkits-exist-for-python">What platform-specific GUI toolkits exist for Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/gui.html#tkinter-questions">Tkinter questions</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="faq/installed.html">“Why is Python Installed on my Computer?” FAQ</a><ul>
<li class="toctree-l3"><a class="reference internal" href="faq/installed.html#what-is-python">What is Python?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/installed.html#why-is-python-installed-on-my-machine">Why is Python installed on my machine?</a></li>
<li class="toctree-l3"><a class="reference internal" href="faq/installed.html#can-i-delete-python">Can I delete Python?</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="glossary.html">Glossary</a></li>
<li class="toctree-l1"><a class="reference internal" href="about.html">About these documents</a><ul>
<li class="toctree-l2"><a class="reference internal" href="about.html#contributors-to-the-python-documentation">Contributors to the Python Documentation</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="bugs.html">Reporting Bugs</a><ul>
<li class="toctree-l2"><a class="reference internal" href="bugs.html#documentation-bugs">Documentation bugs</a></li>
<li class="toctree-l2"><a class="reference internal" href="bugs.html#using-the-python-issue-tracker">Using the Python issue tracker</a></li>
<li class="toctree-l2"><a class="reference internal" href="bugs.html#getting-started-contributing-to-python-yourself">Getting started contributing to Python yourself</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="copyright.html">Copyright</a></li>
<li class="toctree-l1"><a class="reference internal" href="license.html">History and License</a><ul>
<li class="toctree-l2"><a class="reference internal" href="license.html#history-of-the-software">History of the software</a></li>
<li class="toctree-l2"><a class="reference internal" href="license.html#terms-and-conditions-for-accessing-or-otherwise-using-python">Terms and conditions for accessing or otherwise using Python</a><ul>
<li class="toctree-l3"><a class="reference internal" href="license.html#psf-license-agreement-for-python-release">PSF LICENSE AGREEMENT FOR PYTHON 2.7.16</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#beopen-com-license-agreement-for-python-2-0">BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#cnri-license-agreement-for-python-1-6-1">CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#cwi-license-agreement-for-python-0-9-0-through-1-2">CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="license.html#licenses-and-acknowledgements-for-incorporated-software">Licenses and Acknowledgements for Incorporated Software</a><ul>
<li class="toctree-l3"><a class="reference internal" href="license.html#mersenne-twister">Mersenne Twister</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#sockets">Sockets</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#floating-point-exception-control">Floating point exception control</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#md5-message-digest-algorithm">MD5 message digest algorithm</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#asynchronous-socket-services">Asynchronous socket services</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#cookie-management">Cookie management</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#execution-tracing">Execution tracing</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#uuencode-and-uudecode-functions">UUencode and UUdecode functions</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#xml-remote-procedure-calls">XML Remote Procedure Calls</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#test-epoll">test_epoll</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#select-kqueue">Select kqueue</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#strtod-and-dtoa">strtod and dtoa</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#openssl">OpenSSL</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#expat">expat</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#libffi">libffi</a></li>
<li class="toctree-l3"><a class="reference internal" href="license.html#zlib">zlib</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="toctree-wrapper compound">
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Next topic</h4>
  <p class="topless"><a href="whatsnew/index.html"
                        title="next chapter">What’s New in Python</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/contents.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="whatsnew/index.html" title="What’s New in Python"
             >next</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�3VKhtml/copyright.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Copyright &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="#" />
    <link rel="next" title="History and License" href="license.html" />
    <link rel="prev" title="Reporting Bugs" href="bugs.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/copyright.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="license.html" title="History and License"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="bugs.html" title="Reporting Bugs"
             accesskey="P">previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="copyright">
<h1>Copyright<a class="headerlink" href="#copyright" title="Permalink to this headline">¶</a></h1>
<p>Python and this documentation is:</p>
<p>Copyright © 2001-2019 Python Software Foundation. All rights reserved.</p>
<p>Copyright © 2000 BeOpen.com. All rights reserved.</p>
<p>Copyright © 1995-2000 Corporation for National Research Initiatives. All rights
reserved.</p>
<p>Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.</p>
<hr class="docutils" />
<p>See <a class="reference internal" href="license.html#history-and-license"><span class="std std-ref">History and License</span></a> for complete license and permissions information.</p>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h4>Previous topic</h4>
  <p class="topless"><a href="bugs.html"
                        title="previous chapter">Reporting Bugs</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="license.html"
                        title="next chapter">History and License</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="_sources/copyright.rst.txt"
            rel="nofollow">Show Source</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="license.html" title="History and License"
             >next</a> |</li>
        <li class="right" >
          <a href="bugs.html" title="Reporting Bugs"
             >previous</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="#">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\4����html/download.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Download &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/download.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
<h1>Download Python 2.7.16 Documentation</h1>


  <p><b>Last updated on: Mar 27, 2019.</b></p>


<p>To download an archive containing all the documents for
this version of Python in one of various formats, follow one of links
in this table. The numbers in the table are the size of the download
files in megabytes.</p>

<table class="docutils">
  <tr><th>Format</th>
    <th>Packed as .zip</th>
    <th>Packed as .tar.bz2</th>
  </tr>
  <tr><td>PDF (US-Letter paper size)</td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-pdf-letter.zip">
        Download
      </a> (ca. 11 MB)
    </td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-pdf-letter.tar.bz2">
        Download
      </a> (ca. 11 MB)
    </td>
  </tr>
  <tr><td>PDF (A4 paper size)</td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-pdf-a4.zip">
        Download
      </a> (ca. 11 MB)</td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-pdf-a4.tar.bz2">
        Download
      </a> (ca. 11 MB)</td>
  </tr>
  <tr><td>HTML</td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-html.zip">
        Download
      </a> (ca. 7.5 MB)
    </td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-html.tar.bz2">
        Download
      </a> (ca. 5 MB)
    </td>
  </tr>
  <tr>
    <td>Plain Text</td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-text.zip">
        Download
      </a> (ca. 2.5 MB)
    </td>
    <td>
      <a href="https://docs.python.org/ftp/python/doc/2.7.16/python-2.7.16-docs-text.tar.bz2">
        Download
      </a> (ca. 2 MB)
    </td>
  </tr>
</table>

<p>These archives contain all the content in the
documentation.</p>

<p>HTML Help
(<tt>.chm</tt>) files are made available in the "Files" section
on the <a href="https://www.python.org/downloads/release/python-2716/">Python download page</a>.</p>


<h2>Unpacking</h2>

<p>Unix users should download the .tar.bz2 archives; these
are bzipped tar archives and can be handled in the usual way using tar
and the bzip2 program. The <a href="http://www.info-zip.org">InfoZIP</a> unzip
program can be used to handle the ZIP archives if desired. The
.tar.bz2 archives provide the best compression and fastest download
times.</p>

<p>Windows users can use the ZIP archives since those are
customary on that platform. These are created on Unix using the
InfoZIP zip program.</p>


<h2>Problems</h2>

<p>If you have comments or suggestions for the Python
documentation, please send email to
<a href="mailto:docs@python.org">docs@python.org</a>.</p>

          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�y�����html/genindex-A.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-A.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; A</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/aifc.html#index-1">A-LAW</a>, <a href="library/sndhdr.html#index-0">[1]</a>
</li>
      <li><a href="library/audioop.html#index-0">a-LAW</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_base64">a2b_base64() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_hex">a2b_hex() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_hqx">a2b_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_qp">a2b_qp() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.a2b_uu">a2b_uu() (in module binascii)</a>
</li>
      <li><a href="library/abc.html#module-abc">abc (module)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta">ABCMeta (class in abc)</a>
</li>
      <li><a href="c-api/sys.html#index-0">abort()</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.abort">(ftplib.FTP method)</a>
</li>
        <li><a href="library/os.html#os.abort">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.above">above() (curses.panel.Panel method)</a>
</li>
      <li>
    abs

      <ul>
        <li><a href="c-api/number.html#index-2">built-in function</a>, <a href="reference/datamodel.html#index-93">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#abs">abs() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.abs">(decimal.Context method)</a>
</li>
        <li><a href="library/operator.html#operator.abs">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.abspath">abspath() (in module os.path)</a>
</li>
      <li><a href="glossary.html#term-abstract-base-class"><strong>abstract base class</strong></a>
</li>
      <li><a href="library/urllib2.html#urllib2.AbstractBasicAuthHandler">AbstractBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.AbstractDigestAuthHandler">AbstractDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/formatter.html#formatter.AbstractFormatter">AbstractFormatter (class in formatter)</a>
</li>
      <li><a href="library/abc.html#abc.abstractmethod">abstractmethod() (in module abc)</a>
</li>
      <li><a href="library/abc.html#abc.abstractproperty">abstractproperty() (in module abc)</a>
</li>
      <li><a href="library/formatter.html#formatter.AbstractWriter">AbstractWriter (class in formatter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.accept">accept() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.accept">(multiprocessing.connection.Listener method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.accept">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/time.html#time.accept2dyear">accept2dyear (in module time)</a>
</li>
      <li><a href="library/os.html#os.access">access() (in module os)</a>
</li>
      <li><a href="library/cmath.html#cmath.acos">acos() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.acos">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.acosh">acosh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.acosh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Handler.acquire">acquire() (logging.Handler method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Lock.acquire">(multiprocessing.Lock method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.RLock.acquire">(multiprocessing.RLock method)</a>
</li>
        <li><a href="library/thread.html#thread.lock.acquire">(thread.lock method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.acquire">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Lock.acquire">(threading.Lock method)</a>
</li>
        <li><a href="library/threading.html#threading.RLock.acquire">(threading.RLock method)</a>
</li>
        <li><a href="library/threading.html#threading.Semaphore.acquire">(threading.Semaphore method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.acquire_lock">acquire_lock() (in module imp)</a>
</li>
      <li><a href="library/argparse.html#argparse.Action">Action (class in argparse)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.action">action (optparse.Option attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.ACTIONS">ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.activate_form">activate_form() (fl.form method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.active_children">active_children() (in module multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.active_count">active_count() (in module threading)</a>
</li>
      <li><a href="library/threading.html#threading.activeCount">activeCount() (in module threading)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.add">add() (decimal.Context method)</a>

      <ul>
        <li><a href="library/stdtypes.html#frozenset.add">(frozenset method)</a>
</li>
        <li><a href="library/audioop.html#audioop.add">(in module audioop)</a>
</li>
        <li><a href="library/operator.html#operator.add">(in module operator)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.add">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.add">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/msilib.html#msilib.RadioButtonGroup.add">(msilib.RadioButtonGroup method)</a>
</li>
        <li><a href="library/profile.html#pstats.Stats.add">(pstats.Stats method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.add">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.add">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.add_alias">add_alias() (in module email.charset)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_argument">add_argument() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_argument_group">add_argument_group() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_box">add_box() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_browser">add_browser() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_button">add_button() (fl.form method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.add_cgi_vars">add_cgi_vars() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.add_charset">add_charset() (in module email.charset)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_choice">add_choice() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_clock">add_clock() (fl.form method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.add_codec">add_codec() (in module email.charset)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.add_cookie_header">add_cookie_header() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_counter">add_counter() (fl.form method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_data">add_data() (in module msilib)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.add_data">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.add_dial">add_dial() (fl.form method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.add_fallback">add_fallback() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Directory.add_file">add_file() (msilib.Directory method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.add_flag">add_flag() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.add_flag">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.add_flag">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.add_flowing_data">add_flowing_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.add_folder">add_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.add_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.OpenerDirector.add_handler">add_handler() (urllib2.OpenerDirector method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.add_header">add_header() (email.message.Message method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.add_header">(urllib2.Request method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.headers.Headers.add_header">(wsgiref.headers.Headers method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.add_history">add_history() (in module readline)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_hor_rule">add_hor_rule() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_include_dir">add_include_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_input">add_input() (fl.form method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.add_label">add_label() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_label_data">add_label_data() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_library">add_library() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_library_dir">add_library_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_lightbutton">add_lightbutton() (fl.form method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_line_break">add_line_break() (formatter.formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_link_object">add_link_object() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.add_literal_data">add_literal_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_menu">add_menu() (fl.form method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_mutually_exclusive_group">add_mutually_exclusive_group() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.add_option">add_option() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.add_parent">add_parent() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr.add_password">add_password() (urllib2.HTTPPasswordMgr method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_positioner">add_positioner() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_roundbutton">add_roundbutton() (fl.form method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.add_runtime_library_dir">add_runtime_library_dir() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.add_section">add_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage.add_sequence">add_sequence() (mailbox.MHMessage method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_slider">add_slider() (fl.form method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_stream">add_stream() (in module msilib)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.add_subparsers">add_subparsers() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager.add_suffix">add_suffix() (imputil.ImportManager method)</a>
</li>
      <li><a href="library/msilib.html#msilib.add_tables">add_tables() (in module msilib)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_text">add_text() (fl.form method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_timer">add_timer() (fl.form method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.add_type">add_type() (in module mimetypes)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.add_unredirected_header">add_unredirected_header() (urllib2.Request method)</a>
</li>
      <li><a href="library/fl.html#fl.form.add_valslider">add_valslider() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.window.addch">addch() (curses.window method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.addCleanup">addCleanup() (unittest.TestCase method)</a>
</li>
      <li><a href="library/turtle.html#turtle.Shape.addcomponent">addcomponent() (turtle.Shape method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addError">addError() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addExpectedFailure">addExpectedFailure() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addFailure">addFailure() (unittest.TestResult method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.addfile">addfile() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.addFilter">addFilter() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.addFilter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger.addHandler">addHandler() (logging.Logger method)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.addheader">addheader() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile.addinfo">addinfo() (hotshot.Profile method)</a>
</li>
      <li><a href="reference/expressions.html#index-56">addition</a>
</li>
      <li><a href="library/logging.html#logging.addLevelName">addLevelName() (in module logging)</a>
</li>
      <li><a href="library/curses.html#curses.window.addnstr">addnstr() (curses.window method)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.AddPackagePath">AddPackagePath() (in module modulefinder)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.address">address (multiprocessing.connection.Listener attribute)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.address">(multiprocessing.managers.BaseManager attribute)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.address_family">address_family (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.address_string">address_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.AddressList">AddressList (class in rfc822)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.AddressList.addresslist">addresslist (rfc822.AddressList attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.addressof">addressof() (in module ctypes)</a>
</li>
      <li><a href="library/turtle.html#turtle.addshape">addshape() (in module turtle)</a>
</li>
      <li><a href="library/site.html#site.addsitedir">addsitedir() (in module site)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addSkip">addSkip() (unittest.TestResult method)</a>
</li>
      <li><a href="library/curses.html#curses.window.addstr">addstr() (curses.window method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addSuccess">addSuccess() (unittest.TestResult method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite.addTest">addTest() (unittest.TestSuite method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestSuite.addTests">addTests() (unittest.TestSuite method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.addTypeEqualityFunc">addTypeEqualityFunc() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.addUnexpectedSuccess">addUnexpectedSuccess() (unittest.TestResult method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.adjusted">adjusted() (decimal.Decimal method)</a>
</li>
      <li><a href="library/zlib.html#zlib.adler32">adler32() (in module zlib)</a>
</li>
      <li><a href="library/audioop.html#index-0">ADPCM, Intel/DVI</a>
</li>
      <li><a href="library/audioop.html#audioop.adpcm2lin">adpcm2lin() (in module audioop)</a>
</li>
      <li><a href="library/aepack.html#module-aepack">aepack (module)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer">AEServer (class in MiniAEFrame)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.AEText">AEText (class in aetypes)</a>
</li>
      <li><a href="library/aetools.html#module-aetools">aetools (module)</a>
</li>
      <li><a href="library/aetypes.html#module-aetypes">aetypes (module)</a>
</li>
      <li><a href="library/socket.html#socket.AF_INET">AF_INET (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.AF_INET6">AF_INET6 (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.AF_UNIX">AF_UNIX (in module socket)</a>
</li>
      <li><a href="library/aifc.html#module-aifc">aifc (module)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.aifc">aifc() (aifc.aifc method)</a>
</li>
      <li><a href="library/aifc.html#index-0">AIFF</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.aiff">aiff() (aifc.aifc method)</a>
</li>
      <li><a href="library/aifc.html#index-0">AIFF-C</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li>
    AL

      <ul>
        <li><a href="library/al.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/al.html#module-AL">AL (module)</a>
</li>
      <li><a href="library/al.html#module-al">al (module)</a>
</li>
      <li><a href="library/signal.html#signal.alarm">alarm() (in module signal)</a>
</li>
      <li><a href="library/audioop.html#audioop.alaw2lin">alaw2lin() (in module audioop)</a>
</li>
      <li><a href="library/ssl.html#ssl.ALERT_DESCRIPTION_HANDSHAKE_FAILURE">ALERT_DESCRIPTION_HANDSHAKE_FAILURE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.ALERT_DESCRIPTION_INTERNAL_ERROR">ALERT_DESCRIPTION_INTERNAL_ERROR (in module ssl)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.algorithms_available">algorithms_available (in module hashlib)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.algorithms_guaranteed">algorithms_guaranteed (in module hashlib)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.alignment">alignment() (in module ctypes)</a>
</li>
      <li><a href="library/functions.html#all">all() (built-in function)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.all_errors">all_errors (in module ftplib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.all_features">all_features (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.all_properties">all_properties (in module xml.sax.handler)</a>
</li>
      <li><a href="library/thread.html#thread.allocate_lock">allocate_lock() (in module thread)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.allow_reuse_address">allow_reuse_address (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.allowed_domains">allowed_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.alt">alt() (in module curses.ascii)</a>
</li>
      <li><a href="library/locale.html#locale.ALT_DIGITS">ALT_DIGITS (in module locale)</a>
</li>
      <li><a href="library/os.html#os.altsep">altsep (in module os)</a>
</li>
      <li><a href="library/time.html#time.altzone">altzone (in module time)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.ALWAYS_TYPED_ACTIONS">ALWAYS_TYPED_ACTIONS (optparse.Option attribute)</a>
</li>
      <li><a href="library/token.html#token.AMPER">AMPER (in module token)</a>
</li>
      <li><a href="library/token.html#token.AMPEREQUAL">AMPEREQUAL (in module token)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.anchor_bgn">anchor_bgn() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.anchor_end">anchor_end() (htmllib.HTMLParser method)</a>
</li>
      <li>
    and

      <ul>
        <li><a href="reference/expressions.html#index-61">bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-6">operator</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-71">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.and_">and_() (in module operator)</a>
</li>
      <li><a href="library/dircache.html#dircache.annotate">annotate() (in module dircache)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.announce">announce() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    anonymous

      <ul>
        <li><a href="reference/expressions.html#index-75">function</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.answer_challenge">answer_challenge() (in module multiprocessing.connection)</a>
</li>
      <li><a href="library/functions.html#any">any() (built-in function)</a>
</li>
      <li><a href="library/anydbm.html#module-anydbm">anydbm (module)</a>
</li>
      <li><a href="library/sys.html#sys.api_version">api_version (in module sys)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.apop">apop() (poplib.POP3 method)</a>
</li>
      <li><a href="whatsnew/2.6.html#index-5">APPDATA</a>
</li>
      <li><a href="library/array.html#array.array.append">append() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.append">(collections.deque method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.append">(email.header.Header method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.append">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/msilib.html#msilib.CAB.append">(msilib.CAB method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.append">(pipes.Template method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.append">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.appendChild">appendChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/collections.html#collections.deque.appendleft">appendleft() (collections.deque method)</a>
</li>
      <li><a href="library/macostools.html#index-0">AppleEvents</a>, <a href="library/miniaeframe.html#index-0">[1]</a>
</li>
      <li><a href="library/undoc.html#module-applesingle">applesingle (module)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application">Application() (in module FrameWork)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.application_uri">application_uri() (in module wsgiref.util)</a>
</li>
      <li>
    apply

      <ul>
        <li><a href="c-api/object.html#index-6">built-in function</a>, <a href="c-api/object.html#index-7">[1]</a>, <a href="c-api/object.html#index-8">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-apply">apply (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#apply">apply() (built-in function)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.apply_async">apply_async() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/platform.html#platform.architecture">architecture() (in module platform)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.archive">archive (zipimport.zipimporter attribute)</a>
</li>
      <li><a href="library/repr.html#repr.aRepr">aRepr (in module repr)</a>
</li>
      <li><a href="library/argparse.html#module-argparse">argparse (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BaseException.args">args (exceptions.BaseException attribute)</a>

      <ul>
        <li><a href="library/functools.html#functools.partial.args">(functools.partial attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.argtypes">argtypes (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="glossary.html#term-argument"><strong>argument</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-38">call semantics</a>
</li>
        <li><a href="faq/programming.html#index-1">difference from parameter</a>
</li>
        <li><a href="reference/datamodel.html#index-35">function</a>
</li>
        <li><a href="reference/compound_stmts.html#index-20">function definition</a>
</li>
      </ul></li>
      <li><a href="library/argparse.html#argparse.ArgumentDefaultsHelpFormatter">ArgumentDefaultsHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.ArgumentError">ArgumentError</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser">ArgumentParser (class in argparse)</a>
</li>
      <li><a href="c-api/init.html#index-10">argv (in module sys)</a>, <a href="library/sys.html#sys.argv">[1]</a>
</li>
      <li><a href="library/stdtypes.html#index-15">arithmetic</a>

      <ul>
        <li><a href="reference/expressions.html#index-3">conversion</a>
</li>
        <li><a href="reference/expressions.html#index-52">operation, binary</a>
</li>
        <li><a href="reference/expressions.html#index-47">operation, unary</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.ArithmeticError">ArithmeticError</a>
</li>
      <li>
    array

      <ul>
        <li><a href="reference/datamodel.html#index-28">module</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array">array (class in array)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.Array">Array (class in ctypes)</a>
</li>
      <li><a href="library/array.html#module-array">array (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Array">Array() (in module multiprocessing)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.Array">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Array">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#index-0">arrays</a>
</li>
      <li><a href="library/array.html#array.ArrayType">ArrayType (in module array)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.article">article() (nntplib.NNTP method)</a>
</li>
      <li>
    as

      <ul>
        <li><a href="reference/simple_stmts.html#index-38">import statement</a>
</li>
        <li><a href="reference/compound_stmts.html#index-15">with statement</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#float.as_integer_ratio">as_integer_ratio() (float method)</a>
</li>
      <li><a href="library/formatter.html#formatter.AS_IS">AS_IS (in module formatter)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.as_string">as_string() (email.message.Message method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.as_tuple">as_tuple() (decimal.Decimal method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ascii">ascii() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.ascii">(in module future_builtins)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-21">ASCII@ASCII</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/introduction.html#index-1">[2]</a>, <a href="reference/lexical_analysis.html#index-13">[3]</a>, <a href="reference/lexical_analysis.html#index-16">[4]</a>, <a href="reference/lexical_analysis.html#index-21">[5]</a>
</li>
      <li><a href="library/string.html#string.ascii_letters">ascii_letters (in module string)</a>
</li>
      <li><a href="library/string.html#string.ascii_lowercase">ascii_lowercase (in module string)</a>
</li>
      <li><a href="library/string.html#string.ascii_uppercase">ascii_uppercase (in module string)</a>
</li>
      <li><a href="library/time.html#time.asctime">asctime() (in module time)</a>
</li>
      <li><a href="library/cmath.html#cmath.asin">asin() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.asin">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.asinh">asinh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.asinh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFileForOpen">AskFileForOpen() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFileForSave">AskFileForSave() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskFolder">AskFolder() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskPassword">AskPassword() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskString">AskString() (in module EasyDialogs)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.AskYesNoCancel">AskYesNoCancel() (in module EasyDialogs)</a>
</li>
      <li>
    assert

      <ul>
        <li><a href="library/exceptions.html#index-2">statement</a>, <a href="reference/simple_stmts.html#index-15">[1]</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.assert_line_data">assert_line_data() (formatter.formatter method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertAlmostEqual">assertAlmostEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertDictContainsSubset">assertDictContainsSubset() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertDictEqual">assertDictEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertEqual">assertEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertFalse">assertFalse() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertGreater">assertGreater() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertGreaterEqual">assertGreaterEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIn">assertIn() (unittest.TestCase method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.AssertionError">AssertionError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-16">exception</a>
</li>
      </ul></li>
      <li>
    assertions

      <ul>
        <li><a href="reference/simple_stmts.html#index-15">debugging</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIs">assertIs() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsInstance">assertIsInstance() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNone">assertIsNone() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNot">assertIsNot() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertIsNotNone">assertIsNotNone() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertItemsEqual">assertItemsEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertLess">assertLess() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertLessEqual">assertLessEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertListEqual">assertListEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertMultiLineEqual">assertMultiLineEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotAlmostEqual">assertNotAlmostEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotEqual">assertNotEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotIn">assertNotIn() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotIsInstance">assertNotIsInstance() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertNotRegexpMatches">assertNotRegexpMatches() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRaises">assertRaises() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRaisesRegexp">assertRaisesRegexp() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertRegexpMatches">assertRegexpMatches() (unittest.TestCase method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-asserts">asserts (2to3 fixer)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertSequenceEqual">assertSequenceEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertSetEqual">assertSetEqual() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertTrue">assertTrue() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.assertTupleEqual">assertTupleEqual() (unittest.TestCase method)</a>
</li>
      <li>
    assignment

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">attribute</a>, <a href="reference/simple_stmts.html#index-9">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-14">augmented</a>
</li>
        <li><a href="reference/datamodel.html#index-51">class attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-55">class instance attribute</a>
</li>
        <li><a href="library/stdtypes.html#index-30">extended slice</a>
</li>
        <li><a href="library/stdtypes.html#index-30">slice</a>
</li>
        <li><a href="reference/simple_stmts.html#index-13">slicing</a>
</li>
        <li><a href="reference/datamodel.html#index-25">statement</a>, <a href="reference/simple_stmts.html#index-3">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-30">subscript</a>
</li>
        <li><a href="reference/simple_stmts.html#index-10">subscription</a>
</li>
        <li><a href="reference/simple_stmts.html#index-6">target list</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.AST">AST (class in ast)</a>
</li>
      <li><a href="library/ast.html#module-ast">ast (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.astimezone">astimezone() (datetime.datetime method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor">ASTVisitor (class in compiler.visitor)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat">async_chat (class in asynchat)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.ac_in_buffer_size">async_chat.ac_in_buffer_size (in module asynchat)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.ac_out_buffer_size">async_chat.ac_out_buffer_size (in module asynchat)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.asyncevents">asyncevents() (FrameWork.Application method)</a>
</li>
      <li><a href="library/asynchat.html#module-asynchat">asynchat (module)</a>
</li>
      <li><a href="library/asyncore.html#module-asyncore">asyncore (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult">AsyncResult (class in multiprocessing.pool)</a>
</li>
      <li><a href="library/token.html#token.AT">AT (in module token)</a>
</li>
      <li><a href="library/cmath.html#cmath.atan">atan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.atan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.atan2">atan2() (in module math)</a>
</li>
      <li><a href="library/cmath.html#cmath.atanh">atanh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.atanh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/atexit.html#module-atexit">atexit (module)</a>
</li>
      <li><a href="library/cd.html#cd.atime">atime (in module cd)</a>
</li>
      <li><a href="library/locale.html#locale.atof">atof() (in module locale)</a>

      <ul>
        <li><a href="library/string.html#string.atof">(in module string)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.atoi">atoi() (in module locale)</a>

      <ul>
        <li><a href="library/string.html#string.atoi">(in module string)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.atol">atol() (in module string)</a>
</li>
      <li><a href="reference/expressions.html#index-4">atom</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.attach">attach() (email.message.Message method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.AttlistDeclHandler">AttlistDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/operator.html#operator.attrgetter">attrgetter() (in module operator)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.attrib">attrib (xml.etree.ElementTree.Element attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-5">attribute</a>, <a href="glossary.html#term-attribute"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">assignment</a>, <a href="reference/simple_stmts.html#index-9">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-51">assignment, class</a>
</li>
        <li><a href="reference/datamodel.html#index-55">assignment, class instance</a>
</li>
        <li><a href="reference/datamodel.html#index-50">class</a>
</li>
        <li><a href="reference/datamodel.html#index-54">class instance</a>
</li>
        <li><a href="reference/simple_stmts.html#index-21">deletion</a>
</li>
        <li><a href="reference/datamodel.html#index-5">generic special</a>
</li>
        <li><a href="reference/expressions.html#index-29">reference</a>
</li>
        <li><a href="reference/datamodel.html#index-5">special</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.AttributeError">AttributeError</a>

      <ul>
        <li><a href="reference/expressions.html#index-30">exception</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.attributes">attributes (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesImpl">AttributesImpl (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNSImpl">AttributesNSImpl (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/curses.html#curses.window.attroff">attroff() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.attron">attron() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.attrset">attrset() (curses.window method)</a>
</li>
      <li><a href="library/cd.html#cd.audio">audio (in module cd)</a>
</li>
      <li><a href="library/aifc.html#index-0">Audio Interchange File Format</a>, <a href="library/chunk.html#index-0">[1]</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G721">AUDIO_FILE_ENCODING_ADPCM_G721 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G722">AUDIO_FILE_ENCODING_ADPCM_G722 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_3">AUDIO_FILE_ENCODING_ADPCM_G723_3 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ADPCM_G723_5">AUDIO_FILE_ENCODING_ADPCM_G723_5 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_ALAW_8">AUDIO_FILE_ENCODING_ALAW_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_DOUBLE">AUDIO_FILE_ENCODING_DOUBLE (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_FLOAT">AUDIO_FILE_ENCODING_FLOAT (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_16">AUDIO_FILE_ENCODING_LINEAR_16 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_24">AUDIO_FILE_ENCODING_LINEAR_24 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_32">AUDIO_FILE_ENCODING_LINEAR_32 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_LINEAR_8">AUDIO_FILE_ENCODING_LINEAR_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_ENCODING_MULAW_8">AUDIO_FILE_ENCODING_MULAW_8 (in module sunau)</a>
</li>
      <li><a href="library/sunau.html#sunau.AUDIO_FILE_MAGIC">AUDIO_FILE_MAGIC (in module sunau)</a>
</li>
      <li><a href="library/ossaudiodev.html#index-0">AUDIODEV</a>
</li>
      <li><a href="library/audioop.html#module-audioop">audioop (module)</a>
</li>
      <li>
    augmented

      <ul>
        <li><a href="reference/simple_stmts.html#index-14">assignment</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.auth">auth() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.authenticate">authenticate() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.AuthenticationError">AuthenticationError</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.authenticators">authenticators() (netrc.netrc method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.authkey">authkey (multiprocessing.Process attribute)</a>
</li>
      <li><a href="library/autogil.html#module-autoGIL">autoGIL (module)</a>
</li>
      <li><a href="library/autogil.html#autoGIL.AutoGILError">AutoGILError</a>
</li>
      <li><a href="library/audioop.html#audioop.avg">avg() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.avgpp">avgpp() (in module audioop)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\w�/x����html/genindex-B.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-B.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; B</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/base64.html#base64.b16decode">b16decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b16encode">b16encode() (in module base64)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_base64">b2a_base64() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_hex">b2a_hex() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_hqx">b2a_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_qp">b2a_qp() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.b2a_uu">b2a_uu() (in module binascii)</a>
</li>
      <li><a href="library/base64.html#base64.b32decode">b32decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b32encode">b32encode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b64decode">b64decode() (in module base64)</a>
</li>
      <li><a href="library/base64.html#base64.b64encode">b64encode() (in module base64)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl">Babyl (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMailbox">BabylMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage">BabylMessage (class in mailbox)</a>
</li>
      <li><a href="library/turtle.html#turtle.back">back() (in module turtle)</a>
</li>
      <li><a href="reference/datamodel.html#index-77">back-quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      <li><a href="library/token.html#token.BACKQUOTE">BACKQUOTE (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-5">backslash character</a>
</li>
      <li><a href="library/codecs.html#codecs.backslashreplace_errors">backslashreplace_errors() (in module codecs)</a>
</li>
      <li>
    backward

      <ul>
        <li><a href="reference/datamodel.html#index-77">quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.backward">backward() (in module turtle)</a>
</li>
      <li><a href="library/imageop.html#imageop.backward_compatible">backward_compatible (in module imageop)</a>
</li>
      <li><a href="library/httplib.html#httplib.BadStatusLine">BadStatusLine</a>
</li>
      <li><a href="library/zipfile.html#zipfile.BadZipfile">BadZipfile</a>
</li>
      <li><a href="library/tix.html#Tix.Balloon">Balloon (class in Tix)</a>
</li>
      <li><a href="howto/doanddont.html#index-0">bare except</a>
</li>
      <li>
    base64

      <ul>
        <li><a href="library/base64.html#index-0">encoding</a>
</li>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/base64.html#module-base64">base64 (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseCGIHandler">BaseCGIHandler (class in wsgiref.handlers)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie">BaseCookie (class in Cookie)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BaseException">BaseException</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler">BaseHandler (class in urllib2)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler">(class in wsgiref.handlers)</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler">BaseHTTPRequestHandler (class in BaseHTTPServer)</a>
</li>
      <li><a href="library/basehttpserver.html#module-BaseHTTPServer">BaseHTTPServer (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager">BaseManager (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/os.path.html#os.path.basename">basename() (in module os.path)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseProxy">BaseProxy (class in multiprocessing.managers)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler">BaseRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer">BaseServer (class in SocketServer)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-basestring">basestring (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#basestring">basestring() (built-in function)</a>
</li>
      <li><a href="library/logging.html#logging.basicConfig">basicConfig() (in module logging)</a>
</li>
      <li><a href="library/decimal.html#decimal.BasicContext">BasicContext (class in decimal)</a>
</li>
      <li><a href="library/bastion.html#module-Bastion">Bastion (module)</a>
</li>
      <li><a href="library/bastion.html#Bastion.Bastion">Bastion() (in module Bastion)</a>
</li>
      <li><a href="library/bastion.html#Bastion.BastionClass">BastionClass (class in Bastion)</a>
</li>
      <li><a href="library/curses.html#curses.baudrate">baudrate() (in module curses)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.bbox">bbox() (ttk.Treeview method)</a>
</li>
      <li>
    bdb

      <ul>
        <li><a href="library/pdb.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb">Bdb (class in bdb)</a>
</li>
      <li><a href="library/bdb.html#module-bdb">bdb (module)</a>
</li>
      <li><a href="library/bdb.html#bdb.BdbQuit">BdbQuit</a>
</li>
      <li><a href="glossary.html#term-bdfl"><strong>BDFL</strong></a>
</li>
      <li><a href="distutils/apiref.html#distutils.command.bdist_msi.bdist_msi">bdist_msi (class in distutils.command.bdist_msi)</a>
</li>
      <li><a href="library/curses.html#curses.beep">beep() (in module curses)</a>
</li>
      <li><a href="library/winsound.html#winsound.Beep">Beep() (in module winsound)</a>
</li>
      <li><a href="library/turtle.html#turtle.begin_fill">begin_fill() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.begin_poly">begin_poly() (in module turtle)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.below">below() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/timeit.html#index-0">Benchmarking</a>
</li>
      <li><a href="library/time.html#index-8">benchmarking</a>
</li>
      <li><a href="library/random.html#random.betavariate">betavariate() (in module random)</a>
</li>
      <li><a href="library/turtle.html#turtle.bgcolor">bgcolor() (in module turtle)</a>
</li>
      <li><a href="library/fl.html#fl.form.bgn_group">bgn_group() (fl.form method)</a>
</li>
      <li><a href="library/turtle.html#turtle.bgpic">bgpic() (in module turtle)</a>
</li>
      <li><a href="library/audioop.html#audioop.bias">bias() (in module audioop)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.bidirectional">bidirectional() (in module unicodedata)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.BigEndianStructure">BigEndianStructure (class in ctypes)</a>
</li>
      <li><a href="library/functions.html#bin">bin() (built-in function)</a>
</li>
      <li>
    binary

      <ul>
        <li><a href="reference/expressions.html#index-52">arithmetic operation</a>
</li>
        <li><a href="reference/expressions.html#index-60">bitwise operation</a>
</li>
        <li><a href="library/struct.html#index-0">data, packing</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Binary">Binary (class in msilib)</a>

      <ul>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary">(class in xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">binary literal</a>
</li>
      <li><a href="library/thread.html#index-0">binary semaphores</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_ADD">BINARY_ADD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_AND">BINARY_AND (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_DIVIDE">BINARY_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_FLOOR_DIVIDE">BINARY_FLOOR_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_LSHIFT">BINARY_LSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_MODULO">BINARY_MODULO (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_MULTIPLY">BINARY_MULTIPLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_OR">BINARY_OR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_POWER">BINARY_POWER (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_RSHIFT">BINARY_RSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_SUBSCR">BINARY_SUBSCR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_SUBTRACT">BINARY_SUBTRACT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_TRUE_DIVIDE">BINARY_TRUE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BINARY_XOR">BINARY_XOR (opcode)</a>
</li>
      <li><a href="library/binascii.html#module-binascii">binascii (module)</a>
</li>
      <li><a href="library/tkinter.html#index-3">bind (widgets)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.bind">bind() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.bind">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.bind_textdomain_codeset">bind_textdomain_codeset() (in module gettext)</a>
</li>
      <li>
    binding

      <ul>
        <li><a href="reference/simple_stmts.html#index-54">global name</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">name</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/executionmodel.html#index-2">[2]</a>, <a href="reference/simple_stmts.html#index-3">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>, <a href="reference/simple_stmts.html#index-48">[5]</a>
</li>
      </ul></li>
      <li><a href="library/gettext.html#gettext.bindtextdomain">bindtextdomain() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.bindtextdomain">(in module locale)</a>
</li>
      </ul></li>
      <li>
    binhex

      <ul>
        <li><a href="library/binascii.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/binhex.html#module-binhex">binhex (module)</a>
</li>
      <li><a href="library/binhex.html#binhex.binhex">binhex() (in module binhex)</a>
</li>
      <li><a href="library/bisect.html#module-bisect">bisect (module)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect">bisect() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect_left">bisect_left() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.bisect_right">bisect_right() (in module bisect)</a>
</li>
      <li><a href="library/stdtypes.html#int.bit_length">bit_length() (int method)</a>

      <ul>
        <li><a href="library/stdtypes.html#long.bit_length">(long method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog.bitmap">bitmap() (msilib.Dialog method)</a>
</li>
      <li>
    bitwise

      <ul>
        <li><a href="reference/expressions.html#index-61">and</a>
</li>
        <li><a href="reference/expressions.html#index-60">operation, binary</a>
</li>
        <li><a href="reference/expressions.html#index-47">operation, unary</a>
</li>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
        <li><a href="reference/expressions.html#index-63">or</a>
</li>
        <li><a href="reference/expressions.html#index-62">xor</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.bk">bk() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.window.bkgd">bkgd() (curses.window method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/curses.html#curses.window.bkgdset">bkgdset() (curses.window method)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-6">blank line</a>
</li>
      <li><a href="reference/executionmodel.html#index-3">block</a>

      <ul>
        <li><a href="reference/executionmodel.html#index-1">code</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.blocked_domains">blocked_domains() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/io.html#io.BlockingIOError">BlockingIOError</a>
</li>
      <li><a href="library/cd.html#cd.BLOCKSIZE">BLOCKSIZE (in module cd)</a>
</li>
      <li><a href="library/sha.html#sha.blocksize">blocksize (in module sha)</a>
</li>
      <li><a href="reference/expressions.html#index-1">BNF</a>, <a href="reference/introduction.html#index-0">[1]</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.body">body() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.body_encode">body_encode() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.body_encoding">body_encoding (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/email.iterators.html#email.iterators.body_line_iterator">body_line_iterator() (in module email.iterators)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM">BOM (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_BE">BOM_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_LE">BOM_LE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16">BOM_UTF16 (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16_BE">BOM_UTF16_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF16_LE">BOM_UTF16_LE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32">BOM_UTF32 (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32_BE">BOM_UTF32_BE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF32_LE">BOM_UTF32_LE (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.BOM_UTF8">BOM_UTF8 (in module codecs)</a>
</li>
      <li><a href="library/functions.html#bool">bool (built-in class)</a>
</li>
      <li>
    Boolean

      <ul>
        <li><a href="library/stdtypes.html#index-13">object</a>, <a href="reference/datamodel.html#index-13">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-69">operation</a>
</li>
        <li><a href="library/stdtypes.html#index-2">operations</a>, <a href="library/stdtypes.html#index-7">[1]</a>
</li>
        <li><a href="library/functions.html#index-0">type</a>
</li>
        <li><a href="library/stdtypes.html#index-43">values</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Boolean">Boolean (class in aetypes)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.boolean">boolean() (in module xmlrpclib)</a>
</li>
      <li><a href="library/types.html#types.BooleanType">BooleanType (in module types)</a>
</li>
      <li><a href="library/ensurepip.html#ensurepip.bootstrap">bootstrap() (in module ensurepip)</a>
</li>
      <li><a href="library/curses.html#curses.window.border">border() (curses.window method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.bottom">bottom() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.bottom_panel">bottom_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.BoundaryError">BoundaryError</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.BoundedSemaphore">BoundedSemaphore (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.BoundedSemaphore">BoundedSemaphore() (in module threading)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.BoundedSemaphore">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.box">box() (curses.window method)</a>
</li>
      <li>
    break

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-33">[4]</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.break_anywhere">break_anywhere() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.break_here">break_here() (bdb.Bdb method)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.break_long_words">break_long_words (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/dis.html#opcode-BREAK_LOOP">BREAK_LOOP (opcode)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.break_on_hyphens">break_on_hyphens (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint">Breakpoint (class in bdb)</a>
</li>
      <li><a href="library/idle.html#index-4">breakpoints</a>
</li>
      <li><a href="library/webbrowser.html#index-0">BROWSER</a>, <a href="library/webbrowser.html#index-1">[1]</a>
</li>
      <li>
    bsddb

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/dbhash.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
      </ul></li>
      <li><a href="library/bsddb.html#module-bsddb">bsddb (module)</a>
</li>
      <li><a href="library/shelve.html#shelve.BsdDbShelf">BsdDbShelf (class in shelve)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.btopen">btopen() (in module bsddb)</a>
</li>
      <li>
    buffer

      <ul>
        <li><a href="library/types.html#index-4">built-in function</a>
</li>
        <li><a href="c-api/buffer.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-buffer">buffer (2to3 fixer)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.buffer">(io.TextIOBase attribute)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.buffer">(unittest.TestResult attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/buffer.html#index-0">buffer interface</a>
</li>
      <li><a href="library/functions.html#index-4">buffer size, I/O</a>
</li>
      <li><a href="library/functions.html#buffer">buffer() (built-in function)</a>
</li>
      <li><a href="library/array.html#array.array.buffer_info">buffer_info() (array.array method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_size">buffer_size (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_text">buffer_text (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.buffer_used">buffer_used (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase">BufferedIOBase (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedRandom">BufferedRandom (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedReader">BufferedReader (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedRWPair">BufferedRWPair (class in io)</a>
</li>
      <li><a href="library/io.html#io.BufferedWriter">BufferedWriter (class in io)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.BufferError">BufferError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler">BufferingHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.BufferTooShort">BufferTooShort</a>, <a href="library/multiprocessing.html#multiprocessing.connection.BufferTooShort">[1]</a>
</li>
      <li><a href="c-api/buffer.html#index-2">BufferType (in module types)</a>, <a href="library/types.html#types.BufferType">[1]</a>
</li>
      <li><a href="library/macostools.html#macostools.BUFSIZ">BUFSIZ (in module macostools)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.bufsize">bufsize() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_CLASS">BUILD_CLASS (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_LIST">BUILD_LIST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_MAP">BUILD_MAP (opcode)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.build_opener">build_opener() (in module urllib2)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_SET">BUILD_SET (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_SLICE">BUILD_SLICE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-BUILD_TUPLE">BUILD_TUPLE (opcode)</a>
</li>
      <li><a href="library/undoc.html#module-buildtools">buildtools (module)</a>
</li>
      <li>
    built-in

      <ul>
        <li><a href="reference/datamodel.html#index-45">method</a>
</li>
        <li><a href="library/stdtypes.html#index-0">types</a>
</li>
      </ul></li>
      <li>
    built-in function

      <ul>
        <li><a href="c-api/import.html#index-1">__import__</a>
</li>
        <li><a href="c-api/number.html#index-2">abs</a>, <a href="reference/datamodel.html#index-93">[1]</a>
</li>
        <li><a href="c-api/object.html#index-6">apply</a>, <a href="c-api/object.html#index-7">[1]</a>, <a href="c-api/object.html#index-8">[2]</a>
</li>
        <li><a href="library/types.html#index-4">buffer</a>
</li>
        <li><a href="c-api/object.html#index-4">bytes</a>
</li>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="reference/datamodel.html#index-21">chr</a>, <a href="reference/datamodel.html#index-22">[1]</a>
</li>
        <li><a href="c-api/structures.html#index-0">classmethod</a>
</li>
        <li><a href="c-api/object.html#index-0">cmp</a>, <a href="c-api/object.html#index-1">[1]</a>, <a href="library/locale.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-80">[3]</a>
</li>
        <li><a href="c-api/number.html#index-4">coerce</a>
</li>
        <li><a href="c-api/import.html#index-4">compile</a>, <a href="library/parser.html#index-2">[1]</a>, <a href="library/stdtypes.html#index-40">[2]</a>, <a href="library/types.html#index-1">[3]</a>, <a href="reference/simple_stmts.html#index-55">[4]</a>
</li>
        <li><a href="library/stdtypes.html#index-15">complex</a>, <a href="reference/datamodel.html#index-94">[1]</a>
</li>
        <li><a href="c-api/number.html#index-0">divmod</a>, <a href="reference/datamodel.html#index-90">[1]</a>, <a href="reference/datamodel.html#index-91">[2]</a>
</li>
        <li><a href="library/parser.html#index-1">eval</a>, <a href="library/pprint.html#index-0">[1]</a>, <a href="library/pprint.html#index-1">[2]</a>, <a href="library/stdtypes.html#index-41">[3]</a>, <a href="library/string.html#index-7">[4]</a>, <a href="reference/simple_stmts.html#index-55">[5]</a>, <a href="reference/simple_stmts.html#index-58">[6]</a>, <a href="reference/toplevel_components.html#index-6">[7]</a>
</li>
        <li><a href="library/user.html#index-2">execfile</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-34">file</a>
</li>
        <li><a href="c-api/number.html#index-7">float</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-5">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-58">globals</a>
</li>
        <li><a href="c-api/object.html#index-9">hash</a>, <a href="c-api/typeobj.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-81">[2]</a>
</li>
        <li><a href="tutorial/stdlib.html#index-0">help</a>
</li>
        <li><a href="reference/datamodel.html#index-95">hex</a>
</li>
        <li><a href="reference/datamodel.html#index-1">id</a>
</li>
        <li><a href="library/sys.html#index-14">input</a>, <a href="reference/toplevel_components.html#index-7">[1]</a>
</li>
        <li><a href="c-api/number.html#index-5">int</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-94">[2]</a>
</li>
        <li><a href="c-api/dict.html#index-3">len</a>, <a href="c-api/list.html#index-1">[1]</a>, <a href="c-api/mapping.html#index-0">[2]</a>, <a href="c-api/object.html#index-11">[3]</a>, <a href="c-api/sequence.html#index-0">[4]</a>, <a href="c-api/set.html#index-1">[5]</a>, <a href="library/stdtypes.html#index-22">[6]</a>, <a href="library/stdtypes.html#index-32">[7]</a>, <a href="reference/datamodel.html#index-17">[8]</a>, <a href="reference/datamodel.html#index-29">[9]</a>, <a href="reference/datamodel.html#index-32">[10]</a>, <a href="reference/datamodel.html#index-88">[11]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-58">locals</a>
</li>
        <li><a href="c-api/number.html#index-6">long</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-8">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="library/stdtypes.html#index-22">max</a>
</li>
        <li><a href="library/stdtypes.html#index-22">min</a>
</li>
        <li><a href="reference/datamodel.html#index-44">object</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-95">oct</a>
</li>
        <li><a href="reference/datamodel.html#index-58">open</a>, <a href="tutorial/inputoutput.html#index-0">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-21">ord</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>
</li>
        <li><a href="c-api/number.html#index-1">pow</a>, <a href="c-api/number.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-90">[2]</a>, <a href="reference/datamodel.html#index-90">[3]</a>, <a href="reference/datamodel.html#index-91">[4]</a>, <a href="reference/datamodel.html#index-92">[5]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-8">range</a>
</li>
        <li><a href="library/sys.html#index-14">raw_input</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
        <li><a href="c-api/import.html#index-3">reload</a>, <a href="library/imp.html#index-2">[1]</a>, <a href="library/imp.html#index-5">[2]</a>, <a href="library/sys.html#index-5">[3]</a>
</li>
        <li><a href="c-api/object.html#index-2">repr</a>, <a href="c-api/typeobj.html#index-1">[1]</a>, <a href="extending/newtypes.html#index-2">[2]</a>, <a href="reference/datamodel.html#index-76">[3]</a>, <a href="reference/expressions.html#index-21">[4]</a>, <a href="reference/simple_stmts.html#index-2">[5]</a>
</li>
        <li><a href="library/dis.html#index-0">slice</a>, <a href="library/types.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-69">[2]</a>
</li>
        <li><a href="c-api/structures.html#index-1">staticmethod</a>
</li>
        <li><a href="c-api/object.html#index-3">str</a>, <a href="extending/newtypes.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-78">[2]</a>, <a href="reference/expressions.html#index-21">[3]</a>
</li>
        <li><a href="c-api/list.html#index-2">tuple</a>, <a href="c-api/sequence.html#index-1">[1]</a>
</li>
        <li><a href="c-api/object.html#index-10">type</a>, <a href="library/stdtypes.html#index-42">[1]</a>, <a href="library/types.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-1">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">unichr</a>
</li>
        <li><a href="c-api/object.html#index-5">unicode</a>, <a href="reference/datamodel.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-83">[2]</a>, <a href="tutorial/introduction.html#index-0">[3]</a>
</li>
        <li><a href="library/types.html#index-2">xrange</a>
</li>
      </ul></li>
      <li>
    built-in method

      <ul>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="reference/datamodel.html#index-45">object</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.builtin_module_names">builtin_module_names (in module sys)</a>
</li>
      <li><a href="library/types.html#types.BuiltinFunctionType">BuiltinFunctionType (in module types)</a>
</li>
      <li><a href="library/imputil.html#imputil.BuiltinImporter">BuiltinImporter (class in imputil)</a>
</li>
      <li><a href="library/types.html#types.BuiltinMethodType">BuiltinMethodType (in module types)</a>
</li>
      <li>
    builtins

      <ul>
        <li><a href="c-api/init.html#index-21">module</a>
</li>
      </ul></li>
      <li><a href="library/tix.html#Tix.ButtonBox">ButtonBox (class in Tix)</a>
</li>
      <li><a href="library/turtle.html#turtle.bye">bye() (in module turtle)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.byref">byref() (in module ctypes)</a>
</li>
      <li><a href="reference/datamodel.html#index-21">byte</a>
</li>
      <li>
    byte-code

      <ul>
        <li><a href="library/imp.html#index-1">file</a>, <a href="library/imp.html#index-3">[1]</a>, <a href="library/py_compile.html#index-0">[2]</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.byte_compile">byte_compile() (in module distutils.util)</a>
</li>
      <li><a href="reference/datamodel.html#index-27">bytearray</a>

      <ul>
        <li><a href="c-api/bytearray.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#bytearray">bytearray (built-in class)</a>
</li>
      <li><a href="reference/datamodel.html#index-60">bytecode</a>, <a href="glossary.html#term-bytecode"><strong>[1]</strong></a>
</li>
      <li><a href="library/sys.html#sys.byteorder">byteorder (in module sys)</a>
</li>
      <li>
    bytes

      <ul>
        <li><a href="c-api/object.html#index-4">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.bytes">bytes (uuid.UUID attribute)</a>
</li>
      <li><a href="glossary.html#term-bytes-like-object"><strong>bytes-like object</strong></a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.bytes_le">bytes_le (uuid.UUID attribute)</a>
</li>
      <li><a href="library/io.html#io.BytesIO">BytesIO (class in io)</a>
</li>
      <li><a href="library/array.html#array.array.byteswap">byteswap() (array.array method)</a>
</li>
      <li><a href="library/bz2.html#module-bz2">bz2 (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor">BZ2Compressor (class in bz2)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Decompressor">BZ2Decompressor (class in bz2)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File">BZ2File (class in bz2)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\T��miZiZhtml/genindex-C.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-C.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; C</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/lexical_analysis.html#index-15">C</a>

      <ul>
        <li><a href="library/stdtypes.html#index-13">language</a>, <a href="reference/datamodel.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-4">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-65">[4]</a>
</li>
        <li><a href="library/struct.html#index-0">structures</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.c_bool">c_bool (class in ctypes)</a>
</li>
      <li><a href="library/imp.html#imp.C_BUILTIN">C_BUILTIN (in module imp)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_byte">c_byte (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_char">c_char (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_char_p">c_char_p (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_double">c_double (class in ctypes)</a>
</li>
      <li><a href="library/imp.html#imp.C_EXTENSION">C_EXTENSION (in module imp)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_float">c_float (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int">c_int (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int16">c_int16 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int32">c_int32 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int64">c_int64 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_int8">c_int8 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_long">c_long (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_longdouble">c_longdouble (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_longlong">c_longlong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_short">c_short (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_size_t">c_size_t (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ssize_t">c_ssize_t (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ubyte">c_ubyte (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint">c_uint (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint16">c_uint16 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint32">c_uint32 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint64">c_uint64 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_uint8">c_uint8 (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ulong">c_ulong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ulonglong">c_ulonglong (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_ushort">c_ushort (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_void_p">c_void_p (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_wchar">c_wchar (class in ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.c_wchar_p">c_wchar_p (class in ctypes)</a>
</li>
      <li><a href="library/msilib.html#msilib.CAB">CAB (class in msilib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.CacheFTPHandler">CacheFTPHandler (class in urllib2)</a>
</li>
      <li><a href="library/struct.html#struct.calcsize">calcsize() (in module struct)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar">Calendar (class in calendar)</a>
</li>
      <li><a href="library/calendar.html#module-calendar">calendar (module)</a>
</li>
      <li><a href="library/calendar.html#calendar.calendar">calendar() (in module calendar)</a>
</li>
      <li><a href="reference/expressions.html#index-38">call</a>

      <ul>
        <li><a href="reference/expressions.html#index-43">built-in function</a>
</li>
        <li><a href="reference/expressions.html#index-43">built-in method</a>
</li>
        <li><a href="reference/expressions.html#index-45">class instance</a>
</li>
        <li><a href="reference/datamodel.html#index-46">class object</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-52">[2]</a>, <a href="reference/expressions.html#index-44">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-35">function</a>, <a href="reference/expressions.html#index-42">[1]</a>, <a href="reference/expressions.html#index-43">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-87">instance</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-43">method</a>
</li>
        <li><a href="reference/simple_stmts.html#index-2">procedure</a>
</li>
        <li><a href="reference/expressions.html#index-42">user-defined function</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#dl.dl.call">call() (dl.dl method)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.call">(in module subprocess)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION">CALL_FUNCTION (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_KW">CALL_FUNCTION_KW (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_VAR">CALL_FUNCTION_VAR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-CALL_FUNCTION_VAR_KW">CALL_FUNCTION_VAR_KW (opcode)</a>
</li>
      <li><a href="library/sys.html#sys.call_tracing">call_tracing() (in module sys)</a>
</li>
      <li>
    callable

      <ul>
        <li><a href="reference/datamodel.html#index-35">object</a>, <a href="reference/expressions.html#index-38">[1]</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Callable">Callable (class in collections)</a>
</li>
      <li><a href="library/functions.html#callable">callable() (built-in function)</a>
</li>
      <li><a href="library/weakref.html#weakref.CallableProxyType">CallableProxyType (in module weakref)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback">callback (optparse.Option attribute)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer.callback">callback() (MiniAEFrame.AEServer method)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback_args">callback_args (optparse.Option attribute)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.callback_kwargs">callback_kwargs (optparse.Option attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError">CalledProcessError</a>
</li>
      <li><a href="c-api/memory.html#index-0">calloc()</a>
</li>
      <li><a href="library/curses.html#curses.can_change_color">can_change_color() (in module curses)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.can_fetch">can_fetch() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.cancel">cancel() (sched.scheduler method)</a>

      <ul>
        <li><a href="library/threading.html#threading.Timer.cancel">(threading.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.cancel_join_thread">cancel_join_thread() (multiprocessing.Queue method)</a>
</li>
      <li><a href="library/httplib.html#httplib.CannotSendHeader">CannotSendHeader</a>
</li>
      <li><a href="library/httplib.html#httplib.CannotSendRequest">CannotSendRequest</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.canonic">canonic() (bdb.Bdb method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.canonical">canonical() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.canonical">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.capitalize">capitalize() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.capitalize">(str method)</a>
</li>
      </ul></li>
      <li>
    Capsule

      <ul>
        <li><a href="c-api/capsule.html#index-0">object</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.captured_stdout">captured_stdout() (in module test.support)</a>
</li>
      <li><a href="library/logging.html#logging.captureWarnings">captureWarnings() (in module logging)</a>
</li>
      <li><a href="library/string.html#string.capwords">capwords() (in module string)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.AE">Carbon.AE (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.AH">Carbon.AH (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.App">Carbon.App (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Appearance">Carbon.Appearance (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CarbonEvents">Carbon.CarbonEvents (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CarbonEvt">Carbon.CarbonEvt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CF">Carbon.CF (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CG">Carbon.CG (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Cm">Carbon.Cm (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Components">Carbon.Components (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.ControlAccessor">Carbon.ControlAccessor (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Controls">Carbon.Controls (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CoreFounation">Carbon.CoreFounation (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.CoreGraphics">Carbon.CoreGraphics (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Ctl">Carbon.Ctl (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dialogs">Carbon.Dialogs (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dlg">Carbon.Dlg (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Drag">Carbon.Drag (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Dragconst">Carbon.Dragconst (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Events">Carbon.Events (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Evt">Carbon.Evt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.File">Carbon.File (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Files">Carbon.Files (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Fm">Carbon.Fm (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Folder">Carbon.Folder (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Folders">Carbon.Folders (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Fonts">Carbon.Fonts (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Help">Carbon.Help (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.IBCarbon">Carbon.IBCarbon (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.IBCarbonRuntime">Carbon.IBCarbonRuntime (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Icns">Carbon.Icns (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Icons">Carbon.Icons (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Launch">Carbon.Launch (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.LaunchServices">Carbon.LaunchServices (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.List">Carbon.List (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Lists">Carbon.Lists (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.MacHelp">Carbon.MacHelp (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.MediaDescr">Carbon.MediaDescr (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Menu">Carbon.Menu (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Menus">Carbon.Menus (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Mlte">Carbon.Mlte (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.OSA">Carbon.OSA (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.OSAconst">Carbon.OSAconst (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qd">Carbon.Qd (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qdoffs">Carbon.Qdoffs (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QDOffscreen">Carbon.QDOffscreen (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Qt">Carbon.Qt (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QuickDraw">Carbon.QuickDraw (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.QuickTime">Carbon.QuickTime (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Res">Carbon.Res (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Resources">Carbon.Resources (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Scrap">Carbon.Scrap (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Snd">Carbon.Snd (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Sound">Carbon.Sound (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.TE">Carbon.TE (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.TextEdit">Carbon.TextEdit (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Win">Carbon.Win (module)</a>
</li>
      <li><a href="library/carbon.html#module-Carbon.Windows">Carbon.Windows (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.cast">cast() (in module ctypes)</a>
</li>
      <li><a href="library/nis.html#nis.cat">cat() (in module nis)</a>
</li>
      <li><a href="library/cd.html#cd.catalog">catalog (in module cd)</a>
</li>
      <li><a href="library/warnings.html#warnings.catch_warnings">catch_warnings (class in warnings)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.category">category() (in module unicodedata)</a>
</li>
      <li><a href="library/curses.html#curses.cbreak">cbreak() (in module curses)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-24">CC</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler">CCompiler (class in distutils.ccompiler)</a>
</li>
      <li><a href="library/cd.html#module-cd">cd (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.CDLL">CDLL (class in ctypes)</a>
</li>
      <li><a href="library/cd.html#cd.CDROM">CDROM (in module cd)</a>
</li>
      <li><a href="library/math.html#math.ceil">ceil() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/string.html#string.center">center() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.center">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.CERT_NONE">CERT_NONE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CERT_OPTIONAL">CERT_OPTIONAL (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CERT_REQUIRED">CERT_REQUIRED (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.cert_store_stats">cert_store_stats() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ssl.html#ssl.cert_time_to_seconds">cert_time_to_seconds() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.CertificateError">CertificateError</a>
</li>
      <li><a href="library/ssl.html#index-15">certificates</a>
</li>
      <li><a href="install/index.html#index-10">CFLAGS</a>, <a href="install/index.html#index-9">[1]</a>, <a href="whatsnew/2.3.html#index-25">[2]</a>
</li>
      <li><a href="library/undoc.html#module-cfmfile">cfmfile (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.CFUNCTYPE">CFUNCTYPE() (in module ctypes)</a>
</li>
      <li>
    CGI

      <ul>
        <li><a href="library/cgi.html#index-4">debugging</a>
</li>
        <li><a href="library/cgitb.html#index-0">exceptions</a>
</li>
        <li><a href="library/cgi.html#index-0">protocol</a>
</li>
        <li><a href="library/cgi.html#index-1">security</a>
</li>
        <li><a href="library/cgitb.html#index-0">tracebacks</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#module-cgi">cgi (module)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler.cgi_directories">cgi_directories (CGIHTTPServer.CGIHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.CGIHandler">CGIHandler (class in wsgiref.handlers)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler">CGIHTTPRequestHandler (class in CGIHTTPServer)</a>
</li>
      <li>
    CGIHTTPServer

      <ul>
        <li><a href="library/basehttpserver.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/cgihttpserver.html#module-CGIHTTPServer">CGIHTTPServer (module)</a>
</li>
      <li><a href="library/cgitb.html#module-cgitb">cgitb (module)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler">CGIXMLRPCRequestHandler (class in SimpleXMLRPCServer)</a>
</li>
      <li><a href="library/itertools.html#itertools.chain">chain() (in module itertools)</a>
</li>
      <li>
    chaining

      <ul>
        <li><a href="library/stdtypes.html#index-9">comparisons</a>, <a href="reference/expressions.html#index-66">[1]</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.util.change_root">change_root() (in module distutils.util)</a>
</li>
      <li><a href="library/ssl.html#ssl.CHANNEL_BINDING_TYPES">CHANNEL_BINDING_TYPES (in module ssl)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.channels">channels() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/locale.html#locale.CHAR_MAX">CHAR_MAX (in module locale)</a>
</li>
      <li><a href="library/unicodedata.html#index-0">character</a>, <a href="reference/datamodel.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>, <a href="reference/expressions.html#index-33">[3]</a>
</li>
      <li><a href="reference/datamodel.html#index-22">character set</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CharacterDataHandler">CharacterDataHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.characters">characters() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/io.html#io.BlockingIOError.characters_written">characters_written (io.BlockingIOError attribute)</a>
</li>
      <li><a href="c-api/typeobj.html#c.charbufferproc">charbufferproc (C type)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset">Charset (class in email.charset)</a>
</li>
      <li><a href="library/mimify.html#mimify.CHARSET">CHARSET (in module mimify)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.charset">charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/os.html#os.chdir">chdir() (in module os)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.check">check() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/tabnanny.html#tabnanny.check">(in module tabnanny)</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.check_call">check_call() (in module subprocess)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.check_environ">check_environ() (in module distutils.util)</a>
</li>
      <li><a href="library/fl.html#fl.check_forms">check_forms() (in module fl)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.check_hostname">check_hostname (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker.check_output">check_output() (doctest.OutputChecker method)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.check_output">(in module subprocess)</a>
</li>
      </ul></li>
      <li><a href="library/test.html#test.support.check_py3k_warnings">check_py3k_warnings() (in module test.support)</a>
</li>
      <li><a href="library/string.html#string.Formatter.check_unused_args">check_unused_args() (string.Formatter method)</a>
</li>
      <li><a href="library/test.html#test.support.check_warnings">check_warnings() (in module test.support)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.checkbox">checkbox() (msilib.Dialog method)</a>
</li>
      <li><a href="library/linecache.html#linecache.checkcache">checkcache() (in module linecache)</a>
</li>
      <li><a href="library/bdb.html#bdb.checkfuncname">checkfuncname() (in module bdb)</a>
</li>
      <li><a href="library/tix.html#Tix.CheckList">CheckList (class in Tix)</a>
</li>
      <li>
    checksum

      <ul>
        <li><a href="library/zlib.html#index-0">Cyclic Redundancy Check</a>
</li>
        <li><a href="library/md5.html#index-0">MD5</a>
</li>
        <li><a href="library/sha.html#index-0">SHA</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.chflags">chflags() (in module os)</a>
</li>
      <li><a href="library/curses.html#curses.window.chgat">chgat() (curses.window method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.childerr">childerr (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.childNodes">childNodes (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/os.html#os.chmod">chmod() (in module os)</a>
</li>
      <li><a href="library/random.html#random.choice">choice() (in module random)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.choices">choices (optparse.Option attribute)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.choose_boundary">choose_boundary() (in module mimetools)</a>
</li>
      <li><a href="library/os.html#os.chown">chown() (in module os)</a>
</li>
      <li>
    chr

      <ul>
        <li><a href="reference/datamodel.html#index-21">built-in function</a>, <a href="reference/datamodel.html#index-22">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#chr">chr() (built-in function)</a>
</li>
      <li><a href="library/os.html#os.chroot">chroot() (in module os)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk">Chunk (class in chunk)</a>
</li>
      <li><a href="library/chunk.html#module-chunk">chunk (module)</a>
</li>
      <li>
    cipher

      <ul>
        <li><a href="library/crypt.html#index-0">DES</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLSocket.cipher">cipher() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.circle">circle() (in module turtle)</a>
</li>
      <li><a href="library/token.html#token.CIRCUMFLEX">CIRCUMFLEX (in module token)</a>
</li>
      <li><a href="library/token.html#token.CIRCUMFLEXEQUAL">CIRCUMFLEXEQUAL (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Clamped">Clamped (class in decimal)</a>
</li>
      <li><a href="glossary.html#term-class"><strong>class</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-50">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-51">attribute assignment</a>
</li>
        <li><a href="reference/datamodel.html#index-71">classic</a>
</li>
        <li><a href="reference/datamodel.html#index-74">constructor</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">definition</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-54">instance</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">name</a>
</li>
        <li><a href="reference/datamodel.html#index-71">new-style</a>
</li>
        <li><a href="c-api/class.html#index-0">object</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-46">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/expressions.html#index-44">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-71">old-style</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">statement</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Class">Class (class in symtable)</a>
</li>
      <li><a href="library/idle.html#index-1">Class browser</a>
</li>
      <li>
    class instance

      <ul>
        <li><a href="reference/datamodel.html#index-54">attribute</a>
</li>
        <li><a href="reference/datamodel.html#index-55">attribute assignment</a>
</li>
        <li><a href="reference/expressions.html#index-45">call</a>
</li>
        <li><a href="reference/datamodel.html#index-46">object</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-54">[2]</a>, <a href="reference/expressions.html#index-45">[3]</a>
</li>
      </ul></li>
      <li>
    class object

      <ul>
        <li><a href="reference/datamodel.html#index-46">call</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-52">[2]</a>, <a href="reference/expressions.html#index-44">[3]</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-classic-class"><strong>classic class</strong></a>
</li>
      <li>
    classmethod

      <ul>
        <li><a href="c-api/structures.html#index-0">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#classmethod">classmethod() (built-in function)</a>
</li>
      <li><a href="library/new.html#new.classobj">classobj() (in module new)</a>
</li>
      <li><a href="c-api/class.html#index-1">ClassType (in module types)</a>, <a href="library/types.html#types.ClassType">[1]</a>
</li>
      <li><a href="reference/compound_stmts.html#index-1">clause</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.clean">clean() (mailbox.Maildir method)</a>
</li>
      <li><a href="library/inspect.html#inspect.cleandoc">cleandoc() (in module inspect)</a>
</li>
      <li><a href="c-api/sys.html#index-2">cleanup functions</a>
</li>
      <li><a href="library/idle.html#index-4">Clear Breakpoint</a>
</li>
      <li><a href="library/collections.html#collections.deque.clear">clear() (collections.deque method)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.CookieJar.clear">(cookielib.CookieJar method)</a>
</li>
        <li><a href="library/curses.html#curses.window.clear">(curses.window method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.clear">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.clear">(frozenset method)</a>
</li>
        <li><a href="library/turtle.html#turtle.clear">(in module turtle)</a>, <a href="library/turtle.html#turtle.clear">[1]</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.clear">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/threading.html#threading.Event.clear">(threading.Event method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.clear">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_all_breaks">clear_all_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_all_file_breaks">clear_all_file_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_bpbynumber">clear_bpbynumber() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.clear_break">clear_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.clear_flags">clear_flags() (decimal.Context method)</a>
</li>
      <li><a href="library/readline.html#readline.clear_history">clear_history() (in module readline)</a>
</li>
      <li><a href="library/pickle.html#pickle.Pickler.clear_memo">clear_memo() (pickle.Pickler method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.clear_session_cookies">clear_session_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/linecache.html#linecache.clearcache">clearcache() (in module linecache)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.ClearData">ClearData() (msilib.Record method)</a>
</li>
      <li><a href="library/curses.html#curses.window.clearok">clearok() (curses.window method)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearscreen">clearscreen() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearstamp">clearstamp() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.clearstamps">clearstamps() (in module turtle)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Client">Client() (in module multiprocessing.connection)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.client_address">client_address (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/time.html#time.clock">clock() (in module time)</a>
</li>
      <li><a href="library/email.generator.html#email.generator.Generator.clone">clone() (email.generator.Generator method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.clone">(in module turtle)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.clone">(pipes.Template method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.Node.cloneNode">cloneNode() (xml.dom.minidom.Node method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Node.cloneNode">(xml.dom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.Close">Close() (_winreg.PyHKEY method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.close">close() (aifc.aifc method)</a>, <a href="library/aifc.html#aifc.aifc.close">[1]</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.close">(Connection method)</a>
</li>
        <li><a href="library/framework.html#FrameWork.Window.close">(FrameWork.Window method)</a>
</li>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.close">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/asyncore.html#asyncore.dispatcher.close">(asyncore.dispatcher method)</a>
</li>
        <li><a href="library/bsddb.html#bsddb.bsddbobject.close">(bsddb.bsddbobject method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.close">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.close">(chunk.Chunk method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.close">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/dl.html#dl.dl.close">(dl.dl method)</a>
</li>
        <li><a href="library/email.parser.html#email.parser.FeedParser.close">(email.parser.FeedParser method)</a>
</li>
        <li><a href="library/stdtypes.html#file.close">(file method)</a>
</li>
        <li><a href="library/ftplib.html#ftplib.FTP.close">(ftplib.FTP method)</a>
</li>
        <li><a href="reference/expressions.html#generator.close">(generator method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.close">(hotshot.Profile method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.close">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.close">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/anydbm.html#anydbm.close">(in module anydbm)</a>
</li>
        <li><a href="library/dbm.html#dbm.close">(in module dbm)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.close">(in module dumbdbm)</a>
</li>
        <li><a href="library/fileinput.html#fileinput.close">(in module fileinput)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.close">(in module gdbm)</a>
</li>
        <li><a href="c-api/init.html#index-23">(in module os)</a>, <a href="library/os.html#os.close">[1]</a>
</li>
        <li><a href="library/io.html#io.IOBase.close">(io.IOBase method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.FileHandler.close">(logging.FileHandler method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.close">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.close">(logging.handlers.MemoryHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.close">(logging.handlers.NTEventLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.close">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.close">(logging.handlers.SysLogHandler method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.close">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.close">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.close">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.close">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.View.Close">Close() (msilib.View method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.close">close() (multiprocessing.connection.Listener method)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO.close">(StringIO.StringIO method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.close">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.close">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.close">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.close">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/select.html#select.epoll.close">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.close">(select.kqueue method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.close">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/shelve.html#shelve.Shelf.close">(shelve.Shelf method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.close">(socket.socket method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.Connection.close">(sqlite3.Connection method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.close">(sunau.AU_read method)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_write.close">(sunau.AU_write method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.close">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.close">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.BaseHandler.close">(urllib2.BaseHandler method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.close">(wave.Wave_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_write.close">(wave.Wave_write method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.close">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.close">(xml.etree.ElementTree.XMLParser method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.close">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.close">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/asynchat.html#asynchat.async_chat.close_when_done">close_when_done() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/stdtypes.html#file.closed">closed (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.closed">(io.IOBase attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.closed">(ossaudiodev.oss_audio_device attribute)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.CloseKey">CloseKey() (in module _winreg)</a>
</li>
      <li><a href="library/syslog.html#syslog.closelog">closelog() (in module syslog)</a>
</li>
      <li><a href="library/os.html#os.closerange">closerange() (in module os)</a>
</li>
      <li><a href="library/contextlib.html#contextlib.closing">closing() (in module contextlib)</a>
</li>
      <li><a href="library/curses.html#curses.window.clrtobot">clrtobot() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.clrtoeol">clrtoeol() (curses.window method)</a>
</li>
      <li><a href="library/cmath.html#module-cmath">cmath (module)</a>
</li>
      <li>
    cmd

      <ul>
        <li><a href="library/pdb.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd">Cmd (class in cmd)</a>
</li>
      <li><a href="library/cmd.html#module-cmd">cmd (module)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.CalledProcessError.cmd">(subprocess.CalledProcessError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.cmdloop">cmdloop() (cmd.Cmd method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.cmdqueue">cmdqueue (cmd.Cmd attribute)</a>
</li>
      <li>
    cmp

      <ul>
        <li><a href="c-api/object.html#index-0">built-in function</a>, <a href="c-api/object.html#index-1">[1]</a>, <a href="library/locale.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-80">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#cmp">cmp() (built-in function)</a>

      <ul>
        <li><a href="library/filecmp.html#filecmp.cmp">(in module filecmp)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#dis.cmp_op">cmp_op (in module dis)</a>
</li>
      <li><a href="library/functools.html#functools.cmp_to_key">cmp_to_key() (in module functools)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.cmpfiles">cmpfiles() (in module filecmp)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_argcount (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_cellvars (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_code (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_consts (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_filename (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_firstlineno (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_flags (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_freevars (code object attribute)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.CO_FUTURE_DIVISION">CO_FUTURE_DIVISION (C variable)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_lnotab (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_name (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_names (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_nlocals (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_stacksize (code object attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-61">co_varnames (code object attribute)</a>
</li>
      <li>
    CObject

      <ul>
        <li><a href="c-api/cobject.html#index-0">object</a>
</li>
      </ul></li>
      <li>
    code

      <ul>
        <li><a href="reference/executionmodel.html#index-1">block</a>
</li>
      </ul></li>
      <li><a href="library/code.html#module-code">code (module)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPError.code">(urllib2.HTTPError attribute)</a>
</li>
        <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.code">(xml.parsers.expat.ExpatError attribute)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="c-api/code.html#index-0">code object</a>, <a href="library/marshal.html#index-1">[1]</a>, <a href="library/stdtypes.html#index-39">[2]</a>, <a href="reference/datamodel.html#index-60">[3]</a>
</li>
      <li><a href="library/new.html#new.code">code() (in module new)</a>
</li>
      <li><a href="library/codecs.html#index-0">Codecs</a>

      <ul>
        <li><a href="library/codecs.html#index-0">decode</a>
</li>
        <li><a href="library/codecs.html#index-0">encode</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#module-codecs">codecs (module)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.coded_value">coded_value (Cookie.Morsel attribute)</a>
</li>
      <li><a href="library/codeop.html#module-codeop">codeop (module)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.codepoint2name">codepoint2name (in module htmlentitydefs)</a>
</li>
      <li><a href="library/locale.html#locale.CODESET">CODESET (in module locale)</a>
</li>
      <li><a href="library/types.html#types.CodeType">CodeType (in module types)</a>
</li>
      <li>
    coding

      <ul>
        <li><a href="tutorial/controlflow.html#index-5">style</a>
</li>
      </ul></li>
      <li>
    coerce

      <ul>
        <li><a href="c-api/number.html#index-4">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#coerce">coerce() (built-in function)</a>
</li>
      <li><a href="glossary.html#term-coercion"><strong>coercion</strong></a>
</li>
      <li><a href="library/ast.html#ast.AST.col_offset">col_offset (ast.AST attribute)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.collapse_rfc2231_value">collapse_rfc2231_value() (in module email.utils)</a>
</li>
      <li><a href="library/gc.html#gc.collect">collect() (in module gc)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.collect_incoming_data">collect_incoming_data() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/collections.html#module-collections">collections (module)</a>
</li>
      <li><a href="library/token.html#token.COLON">COLON (in module token)</a>
</li>
      <li><a href="library/fl.html#fl.color">color() (in module fl)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.color">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.color_content">color_content() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.color_pair">color_pair() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.colormode">colormode() (in module turtle)</a>
</li>
      <li><a href="library/colorpicker.html#module-ColorPicker">ColorPicker (module)</a>
</li>
      <li><a href="library/colorsys.html#module-colorsys">colorsys (module)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.column">column() (ttk.Treeview method)</a>
</li>
      <li><a href="library/curses.html#index-4">COLUMNS</a>, <a href="library/curses.html#index-6">[1]</a>
</li>
      <li><a href="library/itertools.html#itertools.combinations">combinations() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.combinations_with_replacement">combinations_with_replacement() (in module itertools)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.combine">combine() (datetime.datetime class method)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.combining">combining() (in module unicodedata)</a>
</li>
      <li><a href="library/tix.html#Tix.ComboBox">ComboBox (class in Tix)</a>
</li>
      <li><a href="library/ttk.html#ttk.Combobox">Combobox (class in ttk)</a>
</li>
      <li><a href="reference/expressions.html#index-12">comma</a>

      <ul>
        <li><a href="reference/expressions.html#index-78">trailing</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.COMMA">COMMA (in module token)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.command">command (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command">Command (class in distutils.cmd)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.core.Command">(class in distutils.core)</a>
</li>
      </ul></li>
      <li><a href="reference/toplevel_components.html#index-4">command line</a>
</li>
      <li>
    command line option

      <ul>
        <li><a href="using/cmdline.html#cmdoption-help">--help</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-version">--version</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-3">-3</a>
</li>
        <li><a href="using/cmdline.html#cmdoption">-?</a>
</li>
        <li><a href="using/cmdline.html#id1">-B</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-e">-E</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-j">-J</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-o">-O</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-oo">-OO</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-q">-Q &lt;arg&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-r">-R</a>
</li>
        <li><a href="using/cmdline.html#id2">-S</a>
</li>
        <li><a href="using/cmdline.html#id4">-U</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-v">-V</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-w">-W arg</a>
</li>
        <li><a href="using/cmdline.html#id5">-X</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-b">-b</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-c">-c &lt;command&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-d">-d</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-h">-h</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-i">-i</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-m">-m &lt;module-name&gt;</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-s">-s</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-t">-t</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-u">-u</a>
</li>
        <li><a href="using/cmdline.html#id3">-v</a>
</li>
        <li><a href="using/cmdline.html#cmdoption-x">-x</a>
</li>
      </ul></li>
      <li><a href="library/codeop.html#codeop.CommandCompiler">CommandCompiler (class in codeop)</a>
</li>
      <li><a href="library/commands.html#module-commands">commands (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-3">comment</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.comment">(cookielib.Cookie attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tokenize.html#tokenize.COMMENT">COMMENT (in module tokenize)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.comment">comment (zipfile.ZipFile attribute)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipInfo.comment">(zipfile.ZipInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Comment">Comment() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.comment_url">comment_url (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.commenters">commenters (shlex.shlex attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CommentHandler">CommentHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.CAB.commit">commit() (msilib.CAB method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.Commit">Commit() (msilib.Database method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.commit">commit() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common">common (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/cgi.html#index-0">Common Gateway Interface</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_dirs">common_dirs (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_files">common_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.common_funny">common_funny (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.common_types">common_types (in module mimetypes)</a>
</li>
      <li><a href="library/os.path.html#os.path.commonprefix">commonprefix() (in module os.path)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen.communicate">communicate() (subprocess.Popen method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.compare">compare() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare">(decimal.Decimal method)</a>
</li>
        <li><a href="library/difflib.html#difflib.Differ.compare">(difflib.Differ method)</a>
</li>
      </ul></li>
      <li><a href="library/hmac.html#hmac.compare_digest">compare_digest() (in module hmac)</a>
</li>
      <li><a href="library/dis.html#opcode-COMPARE_OP">COMPARE_OP (opcode)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.compare_signal">compare_signal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_signal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.compare_total">compare_total() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_total">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.compare_total_mag">compare_total_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.compare_total_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li>
    comparing

      <ul>
        <li><a href="library/stdtypes.html#index-10">objects</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-64">comparison</a>

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>
</li>
        <li><a href="reference/datamodel.html#index-22">string</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Comparison">Comparison (class in aetypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.COMPARISON_FLAGS">COMPARISON_FLAGS (in module doctest)</a>
</li>
      <li><a href="reference/datamodel.html#index-79">comparisons</a>, <a href="reference/datamodel.html#index-80">[1]</a>

      <ul>
        <li><a href="library/stdtypes.html#index-9">chaining</a>, <a href="reference/expressions.html#index-66">[1]</a>
</li>
      </ul></li>
      <li>
    compile

      <ul>
        <li><a href="c-api/import.html#index-4">built-in function</a>, <a href="library/parser.html#index-2">[1]</a>, <a href="library/stdtypes.html#index-40">[2]</a>, <a href="library/types.html#index-1">[3]</a>, <a href="reference/simple_stmts.html#index-55">[4]</a>
</li>
      </ul></li>
      <li><a href="library/codeop.html#codeop.Compile">Compile (class in codeop)</a>
</li>
      <li><a href="library/functions.html#compile">compile() (built-in function)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.compile">(distutils.ccompiler.CCompiler method)</a>
</li>
        <li><a href="library/compiler.html#compiler.compile">(in module compiler)</a>
</li>
        <li><a href="library/py_compile.html#py_compile.compile">(in module py_compile)</a>
</li>
        <li><a href="library/re.html#re.compile">(in module re)</a>
</li>
        <li><a href="library/parser.html#parser.ST.compile">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/code.html#code.compile_command">compile_command() (in module code)</a>

      <ul>
        <li><a href="library/codeop.html#codeop.compile_command">(in module codeop)</a>
</li>
      </ul></li>
      <li><a href="library/compileall.html#compileall.compile_dir">compile_dir() (in module compileall)</a>
</li>
      <li><a href="library/compileall.html#compileall.compile_file">compile_file() (in module compileall)</a>
</li>
      <li><a href="library/compileall.html#compileall.compile_path">compile_path() (in module compileall)</a>
</li>
      <li>
    compileall

      <ul>
        <li><a href="tutorial/modules.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/compileall.html#module-compileall">compileall (module)</a>
</li>
      <li>
    compileall command line option

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-d">-d destdir</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-f">-f</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-i">-i list</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-l">-l</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-q">-q</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-x">-x regex</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-directory">directory ...</a>
</li>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-file">file ...</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#compiler.compileFile">compileFile() (in module compiler)</a>
</li>
      <li><a href="library/compiler.html#module-compiler">compiler (module)</a>
</li>
      <li><a href="library/compiler.html#module-compiler.ast">compiler.ast (module)</a>
</li>
      <li><a href="library/compiler.html#module-compiler.visitor">compiler.visitor (module)</a>
</li>
      <li><a href="library/parser.html#parser.compilest">compilest() (in module parser)</a>
</li>
      <li><a href="library/rlcompleter.html#rlcompleter.Completer.complete">complete() (rlcompleter.Completer method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.complete_statement">complete_statement() (in module sqlite3)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.completedefault">completedefault() (cmd.Cmd method)</a>
</li>
      <li>
    complex

      <ul>
        <li><a href="library/stdtypes.html#index-15">built-in function</a>, <a href="reference/datamodel.html#index-94">[1]</a>
</li>
        <li><a href="reference/lexical_analysis.html#index-18">literal</a>
</li>
        <li><a href="reference/datamodel.html#index-16">number</a>
</li>
        <li><a href="reference/datamodel.html#index-16">object</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#complex">complex (built-in class)</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex">Complex (class in numbers)</a>
</li>
      <li><a href="glossary.html#term-complex-number"><strong>complex number</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="c-api/complex.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.ComplexType">ComplexType (in module types)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.ComponentItem">ComponentItem (class in aetypes)</a>
</li>
      <li>
    compound

      <ul>
        <li><a href="reference/compound_stmts.html#index-0">statement</a>
</li>
      </ul></li>
      <li>
    comprehensions

      <ul>
        <li><a href="reference/expressions.html#index-13">list</a>, <a href="reference/expressions.html#index-14">[1]</a>
</li>
      </ul></li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor.compress">compress() (bz2.BZ2Compressor method)</a>

      <ul>
        <li><a href="library/bz2.html#bz2.compress">(in module bz2)</a>
</li>
        <li><a href="library/itertools.html#itertools.compress">(in module itertools)</a>
</li>
        <li><a href="library/jpeg.html#jpeg.compress">(in module jpeg)</a>
</li>
        <li><a href="library/zlib.html#zlib.compress">(in module zlib)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.compress">(zlib.Compress method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.compress_size">compress_size (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.compress_type">compress_type (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.compression">compression() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.CompressionError">CompressionError</a>
</li>
      <li><a href="library/zlib.html#zlib.compressobj">compressobj() (in module zlib)</a>
</li>
      <li><a href="library/os.html#index-29">COMSPEC</a>, <a href="library/subprocess.html#index-2">[1]</a>
</li>
      <li><a href="library/operator.html#operator.concat">concat() (in module operator)</a>
</li>
      <li>
    concatenation

      <ul>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Condition">Condition (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Condition">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Control.condition">condition() (msilib.Control method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Condition">Condition() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li>
    Conditional

      <ul>
        <li><a href="reference/expressions.html#index-69">expression</a>
</li>
      </ul></li>
      <li>
    conditional

      <ul>
        <li><a href="reference/expressions.html#index-73">expression</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser">ConfigParser (class in ConfigParser)</a>

      <ul>
        <li><a href="library/configparser.html#module-ConfigParser">(module)</a>
</li>
      </ul></li>
      <li>
    configuration

      <ul>
        <li><a href="library/configparser.html#index-0">file</a>
</li>
        <li><a href="library/pdb.html#index-2">file, debugger</a>
</li>
        <li><a href="library/site.html#index-2">file, path</a>
</li>
        <li><a href="library/user.html#index-0">file, user</a>
</li>
      </ul></li>
      <li><a href="library/sysconfig.html#index-0">configuration information</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.configure">configure() (ttk.Style method)</a>
</li>
      <li><a href="library/os.html#os.confstr">confstr() (in module os)</a>
</li>
      <li><a href="library/os.html#os.confstr_names">confstr_names (in module os)</a>
</li>
      <li><a href="library/stdtypes.html#index-16">conjugate() (complex number method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.conjugate">(decimal.Decimal method)</a>
</li>
        <li><a href="library/numbers.html#numbers.Complex.conjugate">(numbers.Complex method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.connect">connect() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.connect">(ftplib.FTP method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPConnection.connect">(httplib.HTTPConnection method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.connect">(in module sqlite3)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.connect">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.connect">(smtplib.SMTP method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.connect">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.socket.connect_ex">connect_ex() (socket.socket method)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection">Connection (built-in class)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Connection">(class in sqlite3)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.connection">connection (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.ConnectRegistry">ConnectRegistry() (in module _winreg)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.const">const (optparse.Option attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-11">constant</a>
</li>
      <li>
    constructor

      <ul>
        <li><a href="reference/datamodel.html#index-74">class</a>
</li>
      </ul></li>
      <li><a href="library/copy_reg.html#copy_reg.constructor">constructor() (in module copy_reg)</a>
</li>
      <li><a href="reference/datamodel.html#index-3">container</a>, <a href="reference/datamodel.html#index-50">[1]</a>

      <ul>
        <li><a href="library/stdtypes.html#index-20">iteration over</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Container">Container (class in collections)</a>
</li>
      <li><a href="library/operator.html#operator.contains">contains() (in module operator)</a>
</li>
      <li>
    content type

      <ul>
        <li><a href="library/mimetypes.html#index-0">MIME</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler">ContentHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._Pointer.contents">contents (ctypes._Pointer attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.ContentTooShortError">ContentTooShortError</a>
</li>
      <li><a href="library/decimal.html#decimal.Context">Context (class in decimal)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.context">context (ssl.SSLSocket attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-37">context management protocol</a>
</li>
      <li><a href="library/stdtypes.html#index-37">context manager</a>, <a href="reference/datamodel.html#index-96">[1]</a>, <a href="glossary.html#term-context-manager"><strong>[2]</strong></a>
</li>
      <li><a href="library/difflib.html#difflib.context_diff">context_diff() (in module difflib)</a>
</li>
      <li><a href="library/contextlib.html#module-contextlib">contextlib (module)</a>
</li>
      <li><a href="library/contextlib.html#contextlib.contextmanager">contextmanager() (in module contextlib)</a>
</li>
      <li>
    continue

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/compound_stmts.html#index-5">[2]</a>, <a href="reference/compound_stmts.html#index-7">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-CONTINUE_LOOP">CONTINUE_LOOP (opcode)</a>
</li>
      <li><a href="library/msilib.html#msilib.Control">Control (class in msilib)</a>

      <ul>
        <li><a href="library/tix.html#Tix.Control">(class in Tix)</a>
</li>
      </ul></li>
      <li><a href="library/cd.html#cd.control">control (in module cd)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.control">control() (msilib.Dialog method)</a>

      <ul>
        <li><a href="library/select.html#select.kqueue.control">(select.kqueue method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.controlnames">controlnames (in module curses.ascii)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.controls">controls() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li>
    conversion

      <ul>
        <li><a href="reference/expressions.html#index-3">arithmetic</a>
</li>
        <li><a href="reference/datamodel.html#index-77">string</a>, <a href="reference/expressions.html#index-19">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.ConversionError">ConversionError</a>
</li>
      <li>
    conversions

      <ul>
        <li><a href="library/stdtypes.html#index-18">numeric</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.convert">convert() (email.charset.Charset method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.convert_arg_line_to_args">convert_arg_line_to_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_charref">convert_charref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_codepoint">convert_codepoint() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.convert_entityref">convert_entityref() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.convert_field">convert_field() (string.Formatter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.convert_path">convert_path() (in module distutils.util)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie">Cookie (class in cookielib)</a>

      <ul>
        <li><a href="library/cookie.html#module-Cookie">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.CookieError">CookieError</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar">CookieJar (class in cookielib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPCookieProcessor.cookiejar">cookiejar (urllib2.HTTPCookieProcessor attribute)</a>
</li>
      <li><a href="library/cookielib.html#module-cookielib">cookielib (module)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy">CookiePolicy (class in cookielib)</a>
</li>
      <li><a href="library/time.html#index-5">Coordinated Universal Time</a>
</li>
      <li><a href="library/idle.html#index-4">Copy</a>
</li>
      <li>
    copy

      <ul>
        <li><a href="library/copy_reg.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/copy.html#module-copy">copy (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy">copy() (decimal.Context method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.copy">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.copy">(frozenset method)</a>
</li>
        <li><a href="library/hashlib.html#hashlib.hash.copy">(hashlib.hash method)</a>
</li>
        <li><a href="library/hmac.html#hmac.HMAC.copy">(hmac.HMAC method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.copy">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/copy.html#copy.copy">(in module copy)</a>
</li>
        <li><a href="library/macostools.html#findertools.copy">(in module findertools)</a>
</li>
        <li><a href="library/macostools.html#macostools.copy">(in module macostools)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.copy">(in module multiprocessing.sharedctypes)</a>
</li>
        <li><a href="library/shutil.html#shutil.copy">(in module shutil)</a>
</li>
        <li><a href="library/md5.html#md5.md5.copy">(md5.md5 method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.copy">(pipes.Template method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.copy">(sha.sha method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.copy">(zlib.Compress method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.copy">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/shutil.html#shutil.copy2">copy2() (in module shutil)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_abs">copy_abs() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_abs">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.copy_decimal">copy_decimal() (decimal.Context method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.file_util.copy_file">copy_file() (in module distutils.file_util)</a>
</li>
      <li><a href="library/ast.html#ast.copy_location">copy_location() (in module ast)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_negate">copy_negate() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_negate">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/copy_reg.html#module-copy_reg">copy_reg (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.copy_sign">copy_sign() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.copy_sign">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.dir_util.copy_tree">copy_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.copybinary">copybinary() (in module mimetools)</a>
</li>
      <li><a href="library/shutil.html#shutil.copyfile">copyfile() (in module shutil)</a>
</li>
      <li><a href="library/shutil.html#shutil.copyfileobj">copyfileobj() (in module shutil)</a>
</li>
      <li><a href="library/shutil.html#index-0">copying files</a>
</li>
      <li><a href="library/mimetools.html#mimetools.copyliteral">copyliteral() (in module mimetools)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.copymessage">copymessage() (mhlib.Folder method)</a>
</li>
      <li><a href="library/shutil.html#shutil.copymode">copymode() (in module shutil)</a>
</li>
      <li><a href="library/constants.html#copyright">copyright (built-in variable)</a>

      <ul>
        <li><a href="c-api/init.html#index-7">(in module sys)</a>, <a href="library/sys.html#sys.copyright">[1]</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.copysign">copysign() (in module math)</a>
</li>
      <li><a href="library/shutil.html#shutil.copystat">copystat() (in module shutil)</a>
</li>
      <li><a href="library/macostools.html#macostools.copytree">copytree() (in module macostools)</a>

      <ul>
        <li><a href="library/shutil.html#shutil.copytree">(in module shutil)</a>
</li>
      </ul></li>
      <li><a href="reference/expressions.html#index-23">coroutine</a>
</li>
      <li><a href="library/cmath.html#cmath.cos">cos() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.cos">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.cosh">cosh() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.cosh">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.count">count() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.count">(collections.deque method)</a>
</li>
        <li><a href="library/itertools.html#itertools.count">(in module itertools)</a>
</li>
        <li><a href="library/string.html#string.count">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/stdtypes.html#str.count">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Counter">Counter (class in collections)</a>
</li>
      <li><a href="library/operator.html#operator.countOf">countOf() (in module operator)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.countTestCases">countTestCases() (unittest.TestCase method)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.TestSuite.countTestCases">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.CoverageResults">CoverageResults (class in trace)</a>
</li>
      <li>
    cPickle

      <ul>
        <li><a href="library/copy_reg.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#module-cPickle">cPickle (module)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-26">CPP</a>
</li>
      <li><a href="whatsnew/2.3.html#index-28">CPPFLAGS</a>
</li>
      <li><a href="library/profile.html#module-cProfile">cProfile (module)</a>
</li>
      <li><a href="library/time.html#index-8">CPU time</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.cpu_count">cpu_count() (in module multiprocessing)</a>
</li>
      <li><a href="glossary.html#term-cpython"><strong>CPython</strong></a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.CRC">CRC (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/binascii.html#binascii.crc32">crc32() (in module binascii)</a>

      <ul>
        <li><a href="library/zlib.html#zlib.crc32">(in module zlib)</a>
</li>
      </ul></li>
      <li><a href="library/binascii.html#binascii.crc_hqx">crc_hqx() (in module binascii)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.create">create() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_aggregate">create_aggregate() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_collation">create_collation() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/socket.html#socket.create_connection">create_connection() (in module socket)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.create_decimal">create_decimal() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.create_decimal_from_float">create_decimal_from_float() (decimal.Context method)</a>
</li>
      <li><a href="library/ssl.html#ssl.create_default_context">create_default_context() (in module ssl)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.create_function">create_function() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CREATE_NEW_CONSOLE">CREATE_NEW_CONSOLE (in module subprocess)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CREATE_NEW_PROCESS_GROUP">CREATE_NEW_PROCESS_GROUP (in module subprocess)</a>
</li>
      <li><a href="distutils/builtdist.html#create_shortcut">create_shortcut() (built-in function)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.create_socket">create_socket() (asyncore.dispatcher method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.create_static_lib">create_static_lib() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.create_stats">create_stats() (profile.Profile method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.create_string_buffer">create_string_buffer() (in module ctypes)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.create_system">create_system (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dir_util.create_tree">create_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.create_unicode_buffer">create_unicode_buffer() (in module ctypes)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.create_version">create_version (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createAttribute">createAttribute() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createAttributeNS">createAttributeNS() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createComment">createComment() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.createDocument">createDocument() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.createDocumentType">createDocumentType() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createElement">createElement() (xml.dom.Document method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createElementNS">createElementNS() (xml.dom.Document method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Widget.tk.createfilehandler">createfilehandler() (Tkinter.Widget.tk method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.CreateKey">CreateKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.CreateKeyEx">CreateKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.createLock">createLock() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.NullHandler.createLock">(logging.NullHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/cd.html#cd.createparser">createparser() (in module cd)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createProcessingInstruction">createProcessingInstruction() (xml.dom.Document method)</a>
</li>
      <li><a href="library/msilib.html#msilib.CreateRecord">CreateRecord() (in module msilib)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.createSocket">createSocket() (logging.handlers.SocketHandler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.createTextNode">createTextNode() (xml.dom.Document method)</a>
</li>
      <li><a href="library/constants.html#credits">credits (built-in variable)</a>
</li>
      <li><a href="library/logging.html#logging.critical">critical() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.critical">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.CRNCYSTR">CRNCYSTR (in module locale)</a>
</li>
      <li><a href="library/imageop.html#imageop.crop">crop() (in module imageop)</a>
</li>
      <li><a href="library/audioop.html#audioop.cross">cross() (in module audioop)</a>
</li>
      <li>
    crypt

      <ul>
        <li><a href="library/pwd.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/crypt.html#module-crypt">crypt (module)</a>
</li>
      <li><a href="library/crypt.html#crypt.crypt">crypt() (in module crypt)</a>
</li>
      <li><a href="library/crypt.html#index-0">crypt(3)</a>, <a href="library/crypt.html#index-1">[1]</a>, <a href="library/crypt.html#index-2">[2]</a>
</li>
      <li><a href="library/crypto.html#index-0">cryptography</a>
</li>
      <li><a href="library/stringio.html#module-cStringIO">cStringIO (module)</a>
</li>
      <li><a href="library/csv.html#index-0">csv</a>

      <ul>
        <li><a href="library/csv.html#module-csv">(module)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.ctermid">ctermid() (in module os)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.ctime">ctime() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.ctime">(datetime.datetime method)</a>
</li>
        <li><a href="library/time.html#time.ctime">(in module time)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.ctrl">ctrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/signal.html#signal.CTRL_BREAK_EVENT">CTRL_BREAK_EVENT (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.CTRL_C_EVENT">CTRL_C_EVENT (in module signal)</a>
</li>
      <li><a href="library/ctypes.html#module-ctypes">ctypes (module)</a>
</li>
      <li><a href="library/os.html#os.curdir">curdir (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.currency">currency() (in module locale)</a>
</li>
      <li><a href="library/ttk.html#ttk.Combobox.current">current() (ttk.Combobox method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.current_process">current_process() (in module multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.current_thread">current_thread() (in module threading)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentByteIndex">CurrentByteIndex (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentColumnNumber">CurrentColumnNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/inspect.html#inspect.currentframe">currentframe() (in module inspect)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.CurrentLineNumber">CurrentLineNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/threading.html#threading.currentThread">currentThread() (in module threading)</a>
</li>
      <li><a href="library/curses.html#curses.curs_set">curs_set() (in module curses)</a>
</li>
      <li><a href="library/curses.html#module-curses">curses (module)</a>
</li>
      <li><a href="library/curses.ascii.html#module-curses.ascii">curses.ascii (module)</a>
</li>
      <li><a href="library/curses.panel.html#module-curses.panel">curses.panel (module)</a>
</li>
      <li><a href="library/curses.html#module-curses.textpad">curses.textpad (module)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor">Cursor (class in sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.cursor">cursor() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/curses.html#curses.window.cursyncup">cursyncup() (curses.window method)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.curval">curval (EasyDialogs.ProgressBar attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.customize_compiler">customize_compiler() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/idle.html#index-4">Cut</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.cwd">cwd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/itertools.html#itertools.cycle">cycle() (in module itertools)</a>
</li>
      <li><a href="library/zlib.html#index-0">Cyclic Redundancy Check</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��{����html/genindex-D.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-D.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; D</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/locale.html#locale.D_FMT">D_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.D_T_FMT">D_T_FMT (in module locale)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.daemon">daemon (multiprocessing.Process attribute)</a>

      <ul>
        <li><a href="library/threading.html#threading.Thread.daemon">(threading.Thread attribute)</a>
</li>
      </ul></li>
      <li>
    dangling

      <ul>
        <li><a href="reference/compound_stmts.html#index-2">else</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-0">data</a>

      <ul>
        <li><a href="library/struct.html#index-0">packing binary</a>
</li>
        <li><a href="library/csv.html#index-0">tabular</a>
</li>
        <li><a href="reference/datamodel.html#index-4">type</a>
</li>
        <li><a href="reference/expressions.html#index-9">type, immutable</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#plistlib.Data">Data (class in plistlib)</a>
</li>
      <li><a href="library/select.html#select.kevent.data">data (select.kevent attribute)</a>

      <ul>
        <li><a href="library/userdict.html#UserDict.IterableUserDict.data">(UserDict.IterableUserDict attribute)</a>
</li>
        <li><a href="library/userdict.html#UserList.UserList.data">(UserList.UserList attribute)</a>
</li>
        <li><a href="library/userdict.html#UserString.MutableString.data">(UserString.MutableString attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Comment.data">(xml.dom.Comment attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.ProcessingInstruction.data">(xml.dom.ProcessingInstruction attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Text.data">(xml.dom.Text attribute)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.data">(xmlrpclib.Binary attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.data">data() (xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      <li>
    database

      <ul>
        <li><a href="library/unicodedata.html#index-0">Unicode</a>
</li>
      </ul></li>
      <li><a href="library/dumbdbm.html#index-0">databases</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler">DatagramHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.DatagramRequestHandler">DatagramRequestHandler (class in SocketServer)</a>
</li>
      <li><a href="library/cd.html#cd.DATASIZE">DATASIZE (in module cd)</a>
</li>
      <li><a href="library/datetime.html#datetime.date">date (class in datetime)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.date">date() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.date">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.date_time">date_time (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.date_time_string">date_time_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime">datetime (class in datetime)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime">DateTime (class in xmlrpclib)</a>
</li>
      <li><a href="library/datetime.html#module-datetime">datetime (module)</a>
</li>
      <li><a href="reference/expressions.html#index-16">datum</a>
</li>
      <li><a href="library/datetime.html#datetime.date.day">day (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.day">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.day_abbr">day_abbr (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.day_name">day_name (in module calendar)</a>
</li>
      <li><a href="library/time.html#time.daylight">daylight (in module time)</a>
</li>
      <li><a href="library/time.html#index-6">Daylight Saving Time</a>
</li>
      <li><a href="library/shelve.html#shelve.DbfilenameShelf">DbfilenameShelf (class in shelve)</a>
</li>
      <li>
    dbhash

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/dbhash.html#module-dbhash">dbhash (module)</a>
</li>
      <li>
    dbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/gdbm.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
      </ul></li>
      <li><a href="library/dbm.html#module-dbm">dbm (module)</a>
</li>
      <li><a href="library/locale.html#locale.dcgettext">dcgettext() (in module locale)</a>
</li>
      <li><a href="library/fl.html#fl.form.deactivate_form">deactivate_form() (fl.form method)</a>
</li>
      <li><a href="extending/newtypes.html#index-0">deallocation, object</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.debug">debug (imaplib.IMAP4 attribute)</a>
</li>
      <li><a href="library/re.html#re.DEBUG">DEBUG (in module re)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.debug">debug (shlex.shlex attribute)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.debug">(zipfile.ZipFile attribute)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.debug">debug() (in module doctest)</a>

      <ul>
        <li><a href="library/logging.html#logging.debug">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.debug">(logging.Logger method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.debug">(pipes.Template method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestCase.debug">(unittest.TestCase method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.debug">(unittest.TestSuite method)</a>
</li>
      </ul></li>
      <li><a href="library/gc.html#gc.DEBUG_COLLECTABLE">DEBUG_COLLECTABLE (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_INSTANCES">DEBUG_INSTANCES (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_LEAK">DEBUG_LEAK (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_OBJECTS">DEBUG_OBJECTS (in module gc)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.debug_print">debug_print() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_SAVEALL">DEBUG_SAVEALL (in module gc)</a>
</li>
      <li><a href="library/doctest.html#doctest.debug_src">debug_src() (in module doctest)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_STATS">DEBUG_STATS (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.DEBUG_UNCOLLECTABLE">DEBUG_UNCOLLECTABLE (in module gc)</a>
</li>
      <li><a href="library/idle.html#index-3">debugger</a>, <a href="library/sys.html#index-13">[1]</a>, <a href="library/sys.html#index-3">[2]</a>

      <ul>
        <li><a href="library/pdb.html#index-2">configuration file</a>
</li>
      </ul></li>
      <li><a href="library/pdb.html#index-0">debugging</a>

      <ul>
        <li><a href="library/cgi.html#index-4">CGI</a>
</li>
        <li><a href="reference/simple_stmts.html#index-15">assertions</a>
</li>
      </ul></li>
      <li><a href="library/smtpd.html#smtpd.DebuggingServer">DebuggingServer (class in smtpd)</a>
</li>
      <li><a href="library/doctest.html#doctest.DebugRunner">DebugRunner (class in doctest)</a>
</li>
      <li><a href="library/macos.html#MacOS.DebugStr">DebugStr() (in module MacOS)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal">Decimal (class in decimal)</a>
</li>
      <li><a href="library/decimal.html#module-decimal">decimal (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">decimal literal</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.decimal">decimal() (in module unicodedata)</a>
</li>
      <li><a href="library/decimal.html#decimal.DecimalException">DecimalException (class in decimal)</a>
</li>
      <li>
    decode

      <ul>
        <li><a href="library/codecs.html#index-0">Codecs</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.Codec.decode">decode() (codecs.Codec method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.IncrementalDecoder.decode">(codecs.IncrementalDecoder method)</a>
</li>
        <li><a href="library/base64.html#base64.decode">(in module base64)</a>
</li>
        <li><a href="library/codecs.html#codecs.decode">(in module codecs)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.decode">(in module mimetools)</a>
</li>
        <li><a href="library/quopri.html#quopri.decode">(in module quopri)</a>
</li>
        <li><a href="library/uu.html#uu.decode">(in module uu)</a>
</li>
        <li><a href="library/json.html#json.JSONDecoder.decode">(json.JSONDecoder method)</a>
</li>
        <li><a href="library/stdtypes.html#str.decode">(str method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.decode">(xmlrpclib.Binary method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime.decode">(xmlrpclib.DateTime method)</a>
</li>
      </ul></li>
      <li><a href="library/email.header.html#email.header.decode_header">decode_header() (in module email.header)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.decode_params">decode_params() (in module email.utils)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.decode_rfc2231">decode_rfc2231() (in module email.utils)</a>
</li>
      <li><a href="library/email.generator.html#email.generator.DecodedGenerator">DecodedGenerator (class in email.generator)</a>
</li>
      <li><a href="library/base64.html#base64.decodestring">decodestring() (in module base64)</a>

      <ul>
        <li><a href="library/quopri.html#quopri.decodestring">(in module quopri)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.decomposition">decomposition() (in module unicodedata)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Decompressor.decompress">decompress() (bz2.BZ2Decompressor method)</a>

      <ul>
        <li><a href="library/bz2.html#bz2.decompress">(in module bz2)</a>
</li>
        <li><a href="library/jpeg.html#jpeg.decompress">(in module jpeg)</a>
</li>
        <li><a href="library/zlib.html#zlib.decompress">(in module zlib)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.decompress">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/zlib.html#zlib.decompressobj">decompressobj() (in module zlib)</a>
</li>
      <li><a href="glossary.html#term-decorator"><strong>decorator</strong></a>
</li>
      <li><a href="library/token.html#token.DEDENT">DEDENT (in module token)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-2">DEDENT token</a>, <a href="reference/lexical_analysis.html#index-8">[1]</a>
</li>
      <li><a href="library/textwrap.html#textwrap.dedent">dedent() (in module textwrap)</a>
</li>
      <li><a href="library/copy.html#copy.deepcopy">deepcopy() (in module copy)</a>
</li>
      <li>
    def

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">statement</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.def_prog_mode">def_prog_mode() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.def_shell_mode">def_shell_mode() (in module curses)</a>
</li>
      <li>
    default

      <ul>
        <li><a href="reference/compound_stmts.html#index-20">parameter value</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.default">default (optparse.Option attribute)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.default">default() (cmd.Cmd method)</a>

      <ul>
        <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.default">(compiler.visitor.ASTVisitor method)</a>
</li>
        <li><a href="library/json.html#json.JSONEncoder.default">(json.JSONEncoder method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.DEFAULT_BUFFER_SIZE">DEFAULT_BUFFER_SIZE (in module io)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.default_bufsize">default_bufsize (in module xml.dom.pulldom)</a>
</li>
      <li><a href="library/collections.html#collections.defaultdict.default_factory">default_factory (collections.defaultdict attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.DEFAULT_FORMAT">DEFAULT_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.default_open">default_open() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/timeit.html#timeit.default_timer">default_timer() (in module timeit)</a>
</li>
      <li><a href="library/decimal.html#decimal.DefaultContext">DefaultContext (class in decimal)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy">DefaultCookiePolicy (class in cookielib)</a>
</li>
      <li><a href="library/collections.html#collections.defaultdict">defaultdict (class in collections)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.DefaultHandler">DefaultHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.DefaultHandlerExpand">DefaultHandlerExpand() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.defaults">defaults() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/unittest.html#unittest.defaultTestLoader">defaultTestLoader (in module unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.defaultTestResult">defaultTestResult() (unittest.TestCase method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.defects">defects (email.message.Message attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.define_macro">define_macro() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    definition

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">class</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">function</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.defpath">defpath (in module os)</a>
</li>
      <li><a href="library/math.html#math.degrees">degrees() (in module math)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.degrees">(in module turtle)</a>
</li>
      </ul></li>
      <li>
    del

      <ul>
        <li><a href="library/stdtypes.html#index-30">statement</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-75">[2]</a>, <a href="reference/simple_stmts.html#index-18">[3]</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.del_param">del_param() (email.message.Message method)</a>
</li>
      <li><a href="library/functions.html#delattr">delattr() (built-in function)</a>
</li>
      <li><a href="library/turtle.html#turtle.delay">delay() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.delay_output">delay_output() (in module curses)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.delayload">delayload (cookielib.FileCookieJar attribute)</a>
</li>
      <li><a href="library/curses.html#curses.window.delch">delch() (curses.window method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.dele">dele() (poplib.POP3 method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.delete">delete() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.delete">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.delete">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-DELETE_ATTR">DELETE_ATTR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_FAST">DELETE_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_GLOBAL">DELETE_GLOBAL (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_NAME">DELETE_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+0">DELETE_SLICE+0 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+1">DELETE_SLICE+1 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+2">DELETE_SLICE+2 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SLICE+3">DELETE_SLICE+3 (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DELETE_SUBSCR">DELETE_SUBSCR (opcode)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.deleteacl">deleteacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.Widget.tk.deletefilehandler">deletefilehandler() (Tkinter.Widget.tk method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.deletefolder">deletefolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteKey">DeleteKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteKeyEx">DeleteKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.window.deleteln">deleteln() (curses.window method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.deleteMe">deleteMe() (bdb.Breakpoint method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DeleteValue">DeleteValue() (in module _winreg)</a>
</li>
      <li>
    deletion

      <ul>
        <li><a href="reference/simple_stmts.html#index-21">attribute</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">target</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">target list</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.delimiter">delimiter (csv.Dialect attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-20">delimiters</a>
</li>
      <li><a href="library/operator.html#operator.delitem">delitem() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.deliver_challenge">deliver_challenge() (in module multiprocessing.connection)</a>
</li>
      <li><a href="library/operator.html#operator.delslice">delslice() (in module operator)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.demo_app">demo_app() (in module wsgiref.simple_server)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational.denominator">denominator (numbers.Rational attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.DeprecationWarning">DeprecationWarning</a>
</li>
      <li><a href="library/collections.html#collections.deque">deque (class in collections)</a>
</li>
      <li><a href="library/ssl.html#ssl.DER_cert_to_PEM_cert">DER_cert_to_PEM_cert() (in module ssl)</a>
</li>
      <li><a href="library/curses.html#curses.window.derwin">derwin() (curses.window method)</a>
</li>
      <li>
    DES

      <ul>
        <li><a href="library/crypt.html#index-0">cipher</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.description">description (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.description">description() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.descriptions">descriptions() (nntplib.NNTP method)</a>
</li>
      <li><a href="glossary.html#term-descriptor"><strong>descriptor</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-35">file</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.dest">dest (optparse.Option attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-75">destructor</a>, <a href="reference/simple_stmts.html#index-8">[1]</a>
</li>
      <li><a href="library/_winreg.html#_winreg.PyHKEY.Detach">Detach() (_winreg.PyHKEY method)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase.detach">detach() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.detach">(io.TextIOBase method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.detach">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.detect_language">detect_language() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/profile.html#index-0">deterministic profiling</a>
</li>
      <li><a href="library/gl.html#module-DEVICE">DEVICE (module)</a>
</li>
      <li><a href="library/os.html#os.devnull">devnull (in module os)</a>
</li>
      <li><a href="library/gettext.html#gettext.dgettext">dgettext() (in module gettext)</a>

      <ul>
        <li><a href="library/locale.html#locale.dgettext">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect">Dialect (class in csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.dialect">dialect (csv.csvreader attribute)</a>

      <ul>
        <li><a href="library/csv.html#csv.csvwriter.dialect">(csv.csvwriter attribute)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Dialog">Dialog (class in msilib)</a>
</li>
      <li><a href="library/framework.html#FrameWork.DialogWindow">DialogWindow() (in module FrameWork)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-dict">dict (2to3 fixer)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict">(built-in class)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.dict">dict() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/logging.config.html#logging.config.dictConfig">dictConfig() (in module logging.config)</a>
</li>
      <li><a href="glossary.html#term-dictionary"><strong>dictionary</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-16">display</a>
</li>
        <li><a href="c-api/dict.html#index-0">object</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-33">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/datamodel.html#index-81">[4]</a>, <a href="reference/expressions.html#index-16">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/simple_stmts.html#index-12">[7]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">type, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-dictionary-view"><strong>dictionary view</strong></a>
</li>
      <li><a href="c-api/dict.html#index-1">DictionaryType (in module types)</a>, <a href="library/types.html#types.DictionaryType">[1]</a>
</li>
      <li><a href="library/userdict.html#UserDict.DictMixin">DictMixin (class in UserDict)</a>
</li>
      <li><a href="library/types.html#types.DictProxyType">DictProxyType (in module types)</a>
</li>
      <li><a href="library/csv.html#csv.DictReader">DictReader (class in csv)</a>
</li>
      <li><a href="c-api/dict.html#index-1">DictType (in module types)</a>, <a href="library/types.html#types.DictType">[1]</a>
</li>
      <li><a href="library/csv.html#csv.DictWriter">DictWriter (class in csv)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.diff_files">diff_files (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/difflib.html#difflib.Differ">Differ (class in difflib)</a>, <a href="library/difflib.html#difflib.Differ">[1]</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.difference">difference() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.difference_update">difference_update() (frozenset method)</a>
</li>
      <li><a href="library/difflib.html#module-difflib">difflib (module)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.digest">digest() (hashlib.hash method)</a>

      <ul>
        <li><a href="library/hmac.html#hmac.HMAC.digest">(hmac.HMAC method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.digest">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.digest">(sha.sha method)</a>
</li>
      </ul></li>
      <li><a href="library/md5.html#md5.digest_size">digest_size (in module md5)</a>

      <ul>
        <li><a href="library/sha.html#sha.digest_size">(in module sha)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.digit">digit() (in module unicodedata)</a>
</li>
      <li><a href="library/string.html#string.digits">digits (in module string)</a>
</li>
      <li><a href="library/functions.html#dir">dir() (built-in function)</a>

      <ul>
        <li><a href="library/ftplib.html#ftplib.FTP.dir">(ftplib.FTP method)</a>
</li>
      </ul></li>
      <li><a href="library/dircache.html#module-dircache">dircache (module)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp">dircmp (class in filecmp)</a>
</li>
      <li>
    directory

      <ul>
        <li><a href="library/os.html#index-13">changing</a>
</li>
        <li><a href="library/os.html#index-14">creating</a>
</li>
        <li><a href="library/os.html#index-15">deleting</a>, <a href="library/shutil.html#index-1">[1]</a>
</li>
        <li><a href="library/site.html#index-1">site-packages</a>
</li>
        <li><a href="library/site.html#index-1">site-python</a>
</li>
        <li><a href="library/os.html#index-20">traversal</a>
</li>
        <li><a href="library/os.html#index-20">walking</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/msilib.html#msilib.Directory">Directory (class in msilib)</a>
</li>
      <li>
    directory ...

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-directory">compileall command line option</a>
</li>
      </ul></li>
      <li><a href="distutils/builtdist.html#directory_created">directory_created() (built-in function)</a>
</li>
      <li><a href="library/tix.html#Tix.DirList">DirList (class in Tix)</a>
</li>
      <li><a href="library/os.path.html#os.path.dirname">dirname() (in module os.path)</a>
</li>
      <li><a href="library/tix.html#Tix.DirSelectBox">DirSelectBox (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.DirSelectDialog">DirSelectDialog (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.DirTree">DirTree (class in Tix)</a>
</li>
      <li><a href="library/dis.html#module-dis">dis (module)</a>
</li>
      <li><a href="library/dis.html#dis.dis">dis() (in module dis)</a>

      <ul>
        <li><a href="library/pickletools.html#pickletools.dis">(in module pickletools)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Breakpoint.disable">disable() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/gc.html#gc.disable">(in module gc)</a>
</li>
        <li><a href="library/logging.html#logging.disable">(in module logging)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.disable">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.OptionParser.disable_interspersed_args">disable_interspersed_args() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.DisableReflectionKey">DisableReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/dis.html#dis.disassemble">disassemble() (in module dis)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.discard">discard (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.discard">discard() (frozenset method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.discard">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.discard">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/asynchat.html#asynchat.async_chat.discard_buffers">discard_buffers() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/dis.html#dis.disco">disco() (in module dis)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.discover">discover() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.dispatch">dispatch() (compiler.visitor.ASTVisitor method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_call">dispatch_call() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_exception">dispatch_exception() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_line">dispatch_line() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.dispatch_return">dispatch_return() (bdb.Bdb method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher">dispatcher (class in asyncore)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher_with_send">dispatcher_with_send (class in asyncore)</a>
</li>
      <li>
    display

      <ul>
        <li><a href="reference/expressions.html#index-16">dictionary</a>
</li>
        <li><a href="reference/expressions.html#index-13">list</a>
</li>
        <li><a href="reference/expressions.html#index-18">set</a>
</li>
        <li><a href="reference/expressions.html#index-12">tuple</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.displayhook">displayhook() (in module sys)</a>
</li>
      <li><a href="library/platform.html#platform.dist">dist() (in module platform)</a>
</li>
      <li><a href="library/turtle.html#turtle.distance">distance() (in module turtle)</a>
</li>
      <li><a href="library/dis.html#dis.distb">distb() (in module dis)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.Distribution">Distribution (class in distutils.core)</a>
</li>
      <li><a href="library/distutils.html#module-distutils">distutils (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.archive_util">distutils.archive_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.bcppcompiler">distutils.bcppcompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.ccompiler">distutils.ccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.cmd">distutils.cmd (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command">distutils.command (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist">distutils.command.bdist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_dumb">distutils.command.bdist_dumb (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_msi">distutils.command.bdist_msi (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_packager">distutils.command.bdist_packager (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_rpm">distutils.command.bdist_rpm (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.bdist_wininst">distutils.command.bdist_wininst (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build">distutils.command.build (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_clib">distutils.command.build_clib (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_ext">distutils.command.build_ext (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_py">distutils.command.build_py (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.build_scripts">distutils.command.build_scripts (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.check">distutils.command.check (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.clean">distutils.command.clean (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.config">distutils.command.config (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install">distutils.command.install (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_data">distutils.command.install_data (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_headers">distutils.command.install_headers (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_lib">distutils.command.install_lib (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.install_scripts">distutils.command.install_scripts (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.register">distutils.command.register (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.command.sdist">distutils.command.sdist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.core">distutils.core (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.cygwinccompiler">distutils.cygwinccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.debug">distutils.debug (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dep_util">distutils.dep_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dir_util">distutils.dir_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.dist">distutils.dist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.emxccompiler">distutils.emxccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.errors">distutils.errors (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.extension">distutils.extension (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.fancy_getopt">distutils.fancy_getopt (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.file_util">distutils.file_util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.filelist">distutils.filelist (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.log">distutils.log (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.msvccompiler">distutils.msvccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.spawn">distutils.spawn (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.sysconfig">distutils.sysconfig (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.text_file">distutils.text_file (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.unixccompiler">distutils.unixccompiler (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.util">distutils.util (module)</a>
</li>
      <li><a href="distutils/apiref.html#module-distutils.version">distutils.version (module)</a>
</li>
      <li><a href="distutils/setupscript.html#index-0">DISTUTILS_DEBUG</a>
</li>
      <li><a href="library/imageop.html#imageop.dither2grey2">dither2grey2() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.dither2mono">dither2mono() (in module imageop)</a>
</li>
      <li><a href="library/operator.html#operator.div">div() (in module operator)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.divide">divide() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.divide_int">divide_int() (decimal.Context method)</a>
</li>
      <li><a href="reference/expressions.html#index-54">division</a>

      <ul>
        <li><a href="library/stdtypes.html#index-17">integer</a>
</li>
        <li><a href="library/stdtypes.html#index-17">long integer</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.DivisionByZero">DivisionByZero (class in decimal)</a>
</li>
      <li>
    divmod

      <ul>
        <li><a href="c-api/number.html#index-0">built-in function</a>, <a href="reference/datamodel.html#index-90">[1]</a>, <a href="reference/datamodel.html#index-91">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#divmod">divmod() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.divmod">(decimal.Context method)</a>
</li>
      </ul></li>
      <li><a href="library/dl.html#module-dl">dl (module)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.DllCanUnloadNow">DllCanUnloadNow() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.DllGetClassObject">DllGetClassObject() (in module ctypes)</a>
</li>
      <li><a href="library/sys.html#sys.dllhandle">dllhandle (in module sys)</a>
</li>
      <li><a href="library/gettext.html#gettext.dngettext">dngettext() (in module gettext)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_activate">do_activate() (FrameWork.ScrolledWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.Window.do_activate">(FrameWork.Window method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.do_char">do_char() (FrameWork.Application method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.do_clear">do_clear() (bdb.Bdb method)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.do_command">do_command() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Window.do_contentclick">do_contentclick() (FrameWork.Window method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ControlsWindow.do_controlhit">do_controlhit() (FrameWork.ControlsWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_controlhit">(FrameWork.ScrolledWindow method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.do_dialogevent">do_dialogevent() (FrameWork.Application method)</a>
</li>
      <li><a href="library/fl.html#fl.do_forms">do_forms() (in module fl)</a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET">do_GET() (SimpleHTTPServer.SimpleHTTPRequestHandler method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.do_handshake">do_handshake() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.do_HEAD">do_HEAD() (SimpleHTTPServer.SimpleHTTPRequestHandler method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.DialogWindow.do_itemhit">do_itemhit() (FrameWork.DialogWindow method)</a>
</li>
      <li><a href="library/cgihttpserver.html#CGIHTTPServer.CGIHTTPRequestHandler.do_POST">do_POST() (CGIHTTPServer.CGIHTTPRequestHandler method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.do_postresize">do_postresize() (FrameWork.ScrolledWindow method)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.Window.do_postresize">(FrameWork.Window method)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Window.do_update">do_update() (FrameWork.Window method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.doc_header">doc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocCGIXMLRPCRequestHandler">DocCGIXMLRPCRequestHandler (class in DocXMLRPCServer)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocFileSuite">DocFileSuite() (in module doctest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.doCleanups">doCleanups() (unittest.TestCase method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.docmd">docmd() (smtplib.SMTP method)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-23">docstring</a>, <a href="glossary.html#term-docstring"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.docstring">(doctest.DocTest attribute)</a>
</li>
      </ul></li>
      <li><a href="tutorial/controlflow.html#index-1">docstrings</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTest">DocTest (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#module-doctest">doctest (module)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure">DocTestFailure</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFinder">DocTestFinder (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser">DocTestParser (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner">DocTestRunner (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestSuite">DocTestSuite() (in module doctest)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.doctype">doctype() (xml.etree.ElementTree.TreeBuilder method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.doctype">(xml.etree.ElementTree.XMLParser method)</a>
</li>
      </ul></li>
      <li>
    documentation

      <ul>
        <li><a href="library/pydoc.html#index-0">generation</a>
</li>
        <li><a href="library/pydoc.html#index-0">online</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-63">documentation string</a>
</li>
      <li><a href="tutorial/controlflow.html#index-1">documentation strings</a>, <a href="tutorial/controlflow.html#index-4">[1]</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.documentElement">documentElement (xml.dom.Document attribute)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCRequestHandler">DocXMLRPCRequestHandler (class in DocXMLRPCServer)</a>
</li>
      <li><a href="library/docxmlrpcserver.html#DocXMLRPCServer.DocXMLRPCServer">DocXMLRPCServer (class in DocXMLRPCServer)</a>

      <ul>
        <li><a href="library/docxmlrpcserver.html#module-DocXMLRPCServer">(module)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.domain_initial_dot">domain_initial_dot (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.domain_return_ok">domain_return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.domain_specified">domain_specified (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainLiberal">DomainLiberal (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainRFC2965Match">DomainRFC2965Match (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrict">DomainStrict (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrictNoDots">DomainStrictNoDots (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.DomainStrictNonDomain">DomainStrictNonDomain (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream">DOMEventStream (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMException">DOMException</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DomstringSizeErr">DomstringSizeErr</a>
</li>
      <li><a href="library/turtle.html#turtle.done">done() (in module turtle)</a>

      <ul>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.done">(xdrlib.Unpacker method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DONT_ACCEPT_BLANKLINE">DONT_ACCEPT_BLANKLINE (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DONT_ACCEPT_TRUE_FOR_1">DONT_ACCEPT_TRUE_FOR_1 (in module doctest)</a>
</li>
      <li><a href="library/sys.html#sys.dont_write_bytecode">dont_write_bytecode (in module sys)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler.doRollover">doRollover() (logging.handlers.RotatingFileHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler.doRollover">(logging.handlers.TimedRotatingFileHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.DOT">DOT (in module token)</a>
</li>
      <li><a href="library/turtle.html#turtle.dot">dot() (in module turtle)</a>
</li>
      <li><a href="library/re.html#re.DOTALL">DOTALL (in module re)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.doublequote">doublequote (csv.Dialect attribute)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESLASH">DOUBLESLASH (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESLASHEQUAL">DOUBLESLASHEQUAL (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESTAR">DOUBLESTAR (in module token)</a>
</li>
      <li><a href="library/token.html#token.DOUBLESTAREQUAL">DOUBLESTAREQUAL (in module token)</a>
</li>
      <li><a href="library/curses.html#curses.doupdate">doupdate() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.down">down() (in module turtle)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.drop_whitespace">drop_whitespace (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/itertools.html#itertools.dropwhile">dropwhile() (in module itertools)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.dst">dst() (datetime.datetime method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.dst">(datetime.time method)</a>
</li>
        <li><a href="library/datetime.html#datetime.tzinfo.dst">(datetime.tzinfo method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler">DTDHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="glossary.html#term-duck-typing"><strong>duck-typing</strong></a>
</li>
      <li>
    dumbdbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/dumbdbm.html#module-dumbdbm">dumbdbm (module)</a>
</li>
      <li><a href="library/formatter.html#formatter.DumbWriter">DumbWriter (class in formatter)</a>
</li>
      <li><a href="library/dummy_thread.html#module-dummy_thread">dummy_thread (module)</a>
</li>
      <li><a href="library/dummy_threading.html#module-dummy_threading">dummy_threading (module)</a>
</li>
      <li><a href="library/ast.html#ast.dump">dump() (in module ast)</a>

      <ul>
        <li><a href="library/json.html#json.dump">(in module json)</a>
</li>
        <li><a href="library/marshal.html#marshal.dump">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.dump">(in module pickle)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.dump">(in module xml.etree.ElementTree)</a>
</li>
        <li><a href="library/pickle.html#pickle.Pickler.dump">(pickle.Pickler method)</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#rfc822.dump_address_pair">dump_address_pair() (in module rfc822)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.dump_stats">dump_stats() (profile.Profile method)</a>

      <ul>
        <li><a href="library/profile.html#pstats.Stats.dump_stats">(pstats.Stats method)</a>
</li>
      </ul></li>
      <li><a href="library/json.html#json.dumps">dumps() (in module json)</a>

      <ul>
        <li><a href="library/marshal.html#marshal.dumps">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.dumps">(in module pickle)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.dumps">(in module xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.dup">dup() (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.dup">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.dup2">dup2() (in module os)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.dup2">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-DUP_TOP">DUP_TOP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-DUP_TOPX">DUP_TOPX (opcode)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.DuplicateSectionError">DuplicateSectionError</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.dwFlags">dwFlags (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/imputil.html#imputil.DynLoadSuffixImporter">DynLoadSuffixImporter (class in imputil)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�^�N N html/genindex-E.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-E.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; E</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/cmath.html#cmath.e">e (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.e">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.E2BIG">E2BIG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EACCES">EACCES (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADDRINUSE">EADDRINUSE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADDRNOTAVAIL">EADDRNOTAVAIL (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EADV">EADV (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EAFNOSUPPORT">EAFNOSUPPORT (in module errno)</a>
</li>
      <li><a href="glossary.html#term-eafp"><strong>EAFP</strong></a>
</li>
      <li><a href="library/errno.html#errno.EAGAIN">EAGAIN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EALREADY">EALREADY (in module errno)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.east_asian_width">east_asian_width() (in module unicodedata)</a>
</li>
      <li><a href="library/easydialogs.html#module-EasyDialogs">EasyDialogs (module)</a>
</li>
      <li><a href="library/errno.html#errno.EBADE">EBADE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADF">EBADF (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADFD">EBADFD (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADMSG">EBADMSG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADR">EBADR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADRQC">EBADRQC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBADSLT">EBADSLT (in module errno)</a>
</li>
      <li><a href="reference/datamodel.html#index-22">EBCDIC</a>
</li>
      <li><a href="library/errno.html#errno.EBFONT">EBFONT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EBUSY">EBUSY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECHILD">ECHILD (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.echo">echo() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.window.echochar">echochar() (curses.window method)</a>
</li>
      <li><a href="library/errno.html#errno.ECHRNG">ECHRNG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECOMM">ECOMM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNABORTED">ECONNABORTED (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNREFUSED">ECONNREFUSED (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ECONNRESET">ECONNRESET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDEADLK">EDEADLK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDEADLOCK">EDEADLOCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDESTADDRREQ">EDESTADDRREQ (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.edit">edit() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/errno.html#errno.EDOM">EDOM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDOTDOT">EDOTDOT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EDQUOT">EDQUOT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EEXIST">EEXIST (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EFAULT">EFAULT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EFBIG">EFBIG (in module errno)</a>
</li>
      <li><a href="library/bdb.html#bdb.effective">effective() (in module bdb)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.ehlo">ehlo() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.ehlo_or_helo_if_needed">ehlo_or_helo_if_needed() (smtplib.SMTP method)</a>
</li>
      <li><a href="library/errno.html#errno.EHOSTDOWN">EHOSTDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EHOSTUNREACH">EHOSTUNREACH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EIDRM">EIDRM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EILSEQ">EILSEQ (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINPROGRESS">EINPROGRESS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINTR">EINTR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EINVAL">EINVAL (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EIO">EIO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISCONN">EISCONN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISDIR">EISDIR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EISNAM">EISNAM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL2HLT">EL2HLT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL2NSYNC">EL2NSYNC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL3HLT">EL3HLT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EL3RST">EL3RST (in module errno)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element">Element (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_create">element_create() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_names">element_names() (ttk.Style method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Style.element_options">element_options() (ttk.Style method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ElementDeclHandler">ElementDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.elements">elements() (collections.Counter method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree">ElementTree (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBACC">ELIBACC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBBAD">ELIBBAD (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBEXEC">ELIBEXEC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBMAX">ELIBMAX (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELIBSCN">ELIBSCN (in module errno)</a>
</li>
      <li>
    elif

      <ul>
        <li><a href="reference/compound_stmts.html#index-3">keyword</a>
</li>
      </ul></li>
      <li><a href="library/uu.html#index-0">Ellinghouse, Lance</a>
</li>
      <li>
    Ellipsis

      <ul>
        <li><a href="reference/datamodel.html#index-8">object</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#Ellipsis">Ellipsis (built-in variable)</a>
</li>
      <li><a href="library/doctest.html#doctest.ELLIPSIS">ELLIPSIS (in module doctest)</a>
</li>
      <li><a href="library/types.html#types.EllipsisType">EllipsisType (in module types)</a>
</li>
      <li><a href="library/errno.html#errno.ELNRNG">ELNRNG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ELOOP">ELOOP (in module errno)</a>
</li>
      <li>
    else

      <ul>
        <li><a href="reference/compound_stmts.html#index-2">dangling</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">keyword</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>, <a href="reference/compound_stmts.html#index-4">[2]</a>, <a href="reference/compound_stmts.html#index-6">[3]</a>, <a href="reference/simple_stmts.html#index-34">[4]</a>
</li>
      </ul></li>
      <li><a href="library/email.html#module-email">email (module)</a>
</li>
      <li><a href="library/email.charset.html#module-email.charset">email.charset (module)</a>
</li>
      <li><a href="library/email.encoders.html#module-email.encoders">email.encoders (module)</a>
</li>
      <li><a href="library/email.errors.html#module-email.errors">email.errors (module)</a>
</li>
      <li><a href="library/email.generator.html#module-email.generator">email.generator (module)</a>
</li>
      <li><a href="library/email.header.html#module-email.header">email.header (module)</a>
</li>
      <li><a href="library/email.iterators.html#module-email.iterators">email.iterators (module)</a>
</li>
      <li><a href="library/email.message.html#module-email.message">email.message (module)</a>
</li>
      <li><a href="library/email.mime.html#module-email.mime">email.mime (module)</a>
</li>
      <li><a href="library/email.parser.html#module-email.parser">email.parser (module)</a>
</li>
      <li><a href="library/email.utils.html#module-email.utils">email.utils (module)</a>
</li>
      <li><a href="library/errno.html#errno.EMFILE">EMFILE (in module errno)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.FileHandler.emit">emit() (logging.FileHandler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Handler.emit">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.NullHandler.emit">(logging.NullHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.StreamHandler.emit">(logging.StreamHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.emit">(logging.handlers.BufferingHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.emit">(logging.handlers.DatagramHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler.emit">(logging.handlers.HTTPHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.emit">(logging.handlers.NTEventLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler.emit">(logging.handlers.RotatingFileHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler.emit">(logging.handlers.SMTPHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.emit">(logging.handlers.SocketHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.emit">(logging.handlers.SysLogHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.TimedRotatingFileHandler.emit">(logging.handlers.TimedRotatingFileHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.WatchedFileHandler.emit">(logging.handlers.WatchedFileHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EMLINK">EMLINK (in module errno)</a>
</li>
      <li><a href="library/queue.html#Queue.Empty">Empty</a>
</li>
      <li>
    empty

      <ul>
        <li><a href="reference/expressions.html#index-14">list</a>
</li>
        <li><a href="reference/datamodel.html#index-24">tuple</a>, <a href="reference/expressions.html#index-11">[1]</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.empty">empty() (multiprocessing.multiprocessing.queues.SimpleQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.empty">(Queue.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.empty">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/sched.html#sched.scheduler.empty">(sched.scheduler method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.EMPTY_NAMESPACE">EMPTY_NAMESPACE (in module xml.dom)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.emptyline">emptyline() (cmd.Cmd method)</a>
</li>
      <li><a href="library/errno.html#errno.EMSGSIZE">EMSGSIZE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EMULTIHOP">EMULTIHOP (in module errno)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.enable">enable() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/cgitb.html#cgitb.enable">(in module cgitb)</a>
</li>
        <li><a href="library/gc.html#gc.enable">(in module gc)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.enable">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.enable_callback_tracebacks">enable_callback_tracebacks() (in module sqlite3)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.enable_interspersed_args">enable_interspersed_args() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.enable_load_extension">enable_load_extension() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.enable_traversal">enable_traversal() (ttk.Notebook method)</a>
</li>
      <li><a href="library/site.html#site.ENABLE_USER_SITE">ENABLE_USER_SITE (in module site)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.EnableReflectionKey">EnableReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/errno.html#errno.ENAMETOOLONG">ENAMETOOLONG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENAVAIL">ENAVAIL (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.window.enclose">enclose() (curses.window method)</a>
</li>
      <li>
    encode

      <ul>
        <li><a href="library/codecs.html#index-0">Codecs</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.Codec.encode">encode() (codecs.Codec method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.IncrementalEncoder.encode">(codecs.IncrementalEncoder method)</a>
</li>
        <li><a href="library/email.header.html#email.header.Header.encode">(email.header.Header method)</a>
</li>
        <li><a href="library/base64.html#base64.encode">(in module base64)</a>
</li>
        <li><a href="library/codecs.html#codecs.encode">(in module codecs)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.encode">(in module mimetools)</a>
</li>
        <li><a href="library/quopri.html#quopri.encode">(in module quopri)</a>
</li>
        <li><a href="library/uu.html#uu.encode">(in module uu)</a>
</li>
        <li><a href="library/json.html#json.JSONEncoder.encode">(json.JSONEncoder method)</a>
</li>
        <li><a href="library/stdtypes.html#str.encode">(str method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Binary.encode">(xmlrpclib.Binary method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.Boolean.encode">(xmlrpclib.Boolean method)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.DateTime.encode">(xmlrpclib.DateTime method)</a>
</li>
      </ul></li>
      <li><a href="library/email.encoders.html#email.encoders.encode_7or8bit">encode_7or8bit() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_base64">encode_base64() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_noop">encode_noop() (in module email.encoders)</a>
</li>
      <li><a href="library/email.encoders.html#email.encoders.encode_quopri">encode_quopri() (in module email.encoders)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.encode_rfc2231">encode_rfc2231() (in module email.utils)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.encode_threshold">encode_threshold (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler attribute)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.encoded_header_len">encoded_header_len() (email.charset.Charset method)</a>
</li>
      <li><a href="library/codecs.html#codecs.EncodedFile">EncodedFile() (in module codecs)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.encodePriority">encodePriority() (logging.handlers.SysLogHandler method)</a>
</li>
      <li><a href="library/base64.html#base64.encodestring">encodestring() (in module base64)</a>

      <ul>
        <li><a href="library/quopri.html#quopri.encodestring">(in module quopri)</a>
</li>
      </ul></li>
      <li>
    encoding

      <ul>
        <li><a href="library/base64.html#index-0">base64</a>
</li>
        <li><a href="library/quopri.html#index-0">quoted-printable</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.encoding">encoding (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.encoding">(file attribute)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.ENCODING">ENCODING (in module tarfile)</a>
</li>
      <li><a href="library/io.html#io.TextIOBase.encoding">encoding (io.TextIOBase attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-4">encoding declarations (source file)</a>
</li>
      <li><a href="library/codecs.html#module-encodings.idna">encodings.idna (module)</a>
</li>
      <li><a href="library/codecs.html#module-encodings.utf_8_sig">encodings.utf_8_sig (module)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.encodings_map">encodings_map (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.encodings_map">(mimetypes.MimeTypes attribute)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.end">end (exceptions.UnicodeError attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.end">end() (re.MatchObject method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.TreeBuilder.end">(xml.etree.ElementTree.TreeBuilder method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.end_fill">end_fill() (in module turtle)</a>
</li>
      <li><a href="library/dis.html#opcode-END_FINALLY">END_FINALLY (opcode)</a>
</li>
      <li><a href="library/fl.html#fl.form.end_group">end_group() (fl.form method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.end_headers">end_headers() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.end_marker">end_marker() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.end_paragraph">end_paragraph() (formatter.formatter method)</a>
</li>
      <li><a href="library/turtle.html#turtle.end_poly">end_poly() (in module turtle)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndCdataSectionHandler">EndCdataSectionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndDoctypeDeclHandler">EndDoctypeDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endDocument">endDocument() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endElement">endElement() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndElementHandler">EndElementHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endElementNS">endElementNS() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.endheaders">endheaders() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/token.html#token.ENDMARKER">ENDMARKER (in module token)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EndNamespaceDeclHandler">EndNamespaceDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/gl.html#gl.endpick">endpick() (in module gl)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.endpos">endpos (re.MatchObject attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.endPrefixMapping">endPrefixMapping() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/gl.html#gl.endselect">endselect() (in module gl)</a>
</li>
      <li><a href="library/stdtypes.html#str.endswith">endswith() (str method)</a>
</li>
      <li><a href="library/curses.html#curses.endwin">endwin() (in module curses)</a>
</li>
      <li><a href="library/errno.html#errno.ENETDOWN">ENETDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENETRESET">ENETRESET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENETUNREACH">ENETUNREACH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENFILE">ENFILE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOANO">ENOANO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOBUFS">ENOBUFS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOCSI">ENOCSI (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENODATA">ENODATA (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENODEV">ENODEV (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOENT">ENOENT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOEXEC">ENOEXEC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOLCK">ENOLCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOLINK">ENOLINK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOMEM">ENOMEM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOMSG">ENOMSG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENONET">ENONET (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOPKG">ENOPKG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOPROTOOPT">ENOPROTOOPT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSPC">ENOSPC (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSR">ENOSR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSTR">ENOSTR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOSYS">ENOSYS (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTBLK">ENOTBLK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTCONN">ENOTCONN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTDIR">ENOTDIR (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTEMPTY">ENOTEMPTY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTNAM">ENOTNAM (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTSOCK">ENOTSOCK (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTTY">ENOTTY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ENOTUNIQ">ENOTUNIQ (in module errno)</a>
</li>
      <li><a href="library/ensurepip.html#module-ensurepip">ensurepip (module)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.enter">enter() (sched.scheduler method)</a>
</li>
      <li><a href="library/sched.html#sched.scheduler.enterabs">enterabs() (sched.scheduler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.entities">entities (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.EntityDeclHandler">EntityDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.entitydefs">entitydefs (in module htmlentitydefs)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.EntityResolver">EntityResolver (class in xml.sax.handler)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Enum">Enum (class in aetypes)</a>
</li>
      <li><a href="library/ssl.html#ssl.enum_certificates">enum_certificates() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.enum_crls">enum_crls() (in module ssl)</a>
</li>
      <li><a href="library/functions.html#enumerate">enumerate() (built-in function)</a>

      <ul>
        <li><a href="library/fm.html#fm.enumerate">(in module fm)</a>
</li>
        <li><a href="library/threading.html#threading.enumerate">(in module threading)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.EnumKey">EnumKey() (in module _winreg)</a>
</li>
      <li><a href="library/aetools.html#aetools.enumsubst">enumsubst() (in module aetools)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.EnumValue">EnumValue() (in module _winreg)</a>
</li>
      <li><a href="library/os.html#os.environ">environ (in module os)</a>

      <ul>
        <li><a href="library/posix.html#posix.environ">(in module posix)</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-6">environment</a>
</li>
      <li>
    environment variable

      <ul>
        <li><a href="using/windows.html#index-1">%PATH%</a>
</li>
        <li><a href="library/urllib2.html#index-2">&lt;protocol&gt;_proxy</a>
</li>
        <li><a href="whatsnew/2.6.html#index-5">APPDATA</a>
</li>
        <li><a href="library/ossaudiodev.html#index-0">AUDIODEV</a>
</li>
        <li><a href="library/webbrowser.html#index-0">BROWSER</a>, <a href="library/webbrowser.html#index-1">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-24">CC</a>
</li>
        <li><a href="install/index.html#index-10">CFLAGS</a>, <a href="install/index.html#index-9">[1]</a>, <a href="whatsnew/2.3.html#index-25">[2]</a>
</li>
        <li><a href="library/curses.html#index-4">COLUMNS</a>, <a href="library/curses.html#index-6">[1]</a>
</li>
        <li><a href="library/os.html#index-29">COMSPEC</a>, <a href="library/subprocess.html#index-2">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-26">CPP</a>
</li>
        <li><a href="whatsnew/2.3.html#index-28">CPPFLAGS</a>
</li>
        <li><a href="distutils/setupscript.html#index-0">DISTUTILS_DEBUG</a>
</li>
        <li><a href="distutils/apiref.html#index-1">HOME</a>, <a href="install/index.html#index-4">[1]</a>, <a href="install/index.html#index-5">[2]</a>, <a href="library/os.path.html#index-2">[3]</a>, <a href="library/os.path.html#index-3">[4]</a>, <a href="library/user.html#index-3">[5]</a>
</li>
        <li><a href="install/index.html#index-7">HOMEDRIVE</a>, <a href="library/os.path.html#index-6">[1]</a>
</li>
        <li><a href="install/index.html#index-8">HOMEPATH</a>, <a href="library/os.path.html#index-5">[1]</a>
</li>
        <li><a href="library/idle.html#index-5">IDLESTARTUP</a>
</li>
        <li><a href="library/webbrowser.html#index-2">KDEDIR</a>
</li>
        <li><a href="library/gettext.html#index-3">LANG</a>, <a href="library/gettext.html#index-7">[1]</a>, <a href="library/locale.html#index-1">[2]</a>, <a href="library/locale.html#index-2">[3]</a>, <a href="library/locale.html#index-3">[4]</a>
</li>
        <li><a href="library/gettext.html#index-0">LANGUAGE</a>, <a href="library/gettext.html#index-4">[1]</a>
</li>
        <li><a href="library/gettext.html#index-1">LC_ALL</a>, <a href="library/gettext.html#index-5">[1]</a>
</li>
        <li><a href="library/gettext.html#index-2">LC_MESSAGES</a>, <a href="library/gettext.html#index-6">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-12">LDCXXSHARED</a>
</li>
        <li><a href="whatsnew/2.3.html#index-27">LDFLAGS</a>
</li>
        <li><a href="library/curses.html#index-0">LINES</a>, <a href="library/curses.html#index-3">[1]</a>, <a href="library/curses.html#index-5">[2]</a>
</li>
        <li><a href="library/getpass.html#index-2">LNAME</a>
</li>
        <li><a href="library/getpass.html#index-0">LOGNAME</a>, <a href="library/os.html#index-2">[1]</a>
</li>
        <li><a href="library/ossaudiodev.html#index-1">MIXERDEV</a>
</li>
        <li><a href="library/pdb.html#index-3">PAGER</a>, <a href="library/pydoc.html#index-1">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-22">PATH</a>, <a href="c-api/intro.html#index-23">[1]</a>, <a href="distutils/packageindex.html#index-1">[2]</a>, <a href="faq/library.html#index-0">[3]</a>, <a href="faq/library.html#index-1">[4]</a>, <a href="library/cgi.html#index-2">[5]</a>, <a href="library/cgi.html#index-5">[6]</a>, <a href="library/os.html#index-21">[7]</a>, <a href="library/os.html#index-22">[8]</a>, <a href="library/os.html#index-23">[9]</a>, <a href="library/os.html#index-26">[10]</a>, <a href="library/os.html#index-27">[11]</a>, <a href="library/os.html#index-28">[12]</a>, <a href="library/os.html#index-30">[13]</a>, <a href="library/webbrowser.html#index-3">[14]</a>, <a href="tutorial/appendix.html#index-0">[15]</a>, <a href="tutorial/modules.html#index-2">[16]</a>, <a href="using/cmdline.html#index-18">[17]</a>, <a href="using/unix.html#index-2">[18]</a>
</li>
        <li><a href="distutils/apiref.html#index-2">PLAT</a>
</li>
        <li><a href="library/getopt.html#index-0">POSIXLY_CORRECT</a>
</li>
        <li><a href="using/cmdline.html#index-3">PYTHON*</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONCASEOK">PYTHONCASEOK</a>, <a href="whatsnew/2.1.html#index-8">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONDEBUG">PYTHONDEBUG</a>, <a href="using/cmdline.html#index-2">[1]</a>
</li>
        <li><a href="library/pydoc.html#index-2">PYTHONDOCS</a>
</li>
        <li><a href="library/sys.html#index-0">PYTHONDONTWRITEBYTECODE</a>, <a href="using/cmdline.html#envvar-PYTHONDONTWRITEBYTECODE">[1]</a>, <a href="using/cmdline.html#index-1">[2]</a>, <a href="whatsnew/2.6.html#index-20">[3]</a>, <a href="whatsnew/2.6.html#index-24">[4]</a>
</li>
        <li><a href="c-api/typeobj.html#index-0">PYTHONDUMPREFS</a>, <a href="using/cmdline.html#envvar-PYTHONDUMPREFS">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONEXECUTABLE">PYTHONEXECUTABLE</a>
</li>
        <li><a href="library/random.html#index-0">PYTHONHASHSEED</a>, <a href="using/cmdline.html#envvar-PYTHONHASHSEED">[1]</a>, <a href="using/cmdline.html#index-10">[2]</a>, <a href="using/cmdline.html#index-23">[3]</a>
</li>
        <li><a href="c-api/init.html#index-11">PYTHONHOME</a>, <a href="c-api/init.html#index-12">[1]</a>, <a href="c-api/intro.html#index-24">[2]</a>, <a href="c-api/intro.html#index-27">[3]</a>, <a href="install/index.html#index-0">[4]</a>, <a href="install/index.html#index-1">[5]</a>, <a href="using/cmdline.html#envvar-PYTHONHOME">[6]</a>, <a href="using/cmdline.html#index-16">[7]</a>, <a href="using/cmdline.html#index-17">[8]</a>, <a href="using/cmdline.html#index-20">[9]</a>, <a href="using/cmdline.html#index-5">[10]</a>, <a href="using/windows.html#index-3">[11]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONHTTPSVERIFY">PYTHONHTTPSVERIFY</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONINSPECT">PYTHONINSPECT</a>, <a href="using/cmdline.html#index-7">[1]</a>, <a href="whatsnew/2.3.html#index-29">[2]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONIOENCODING">PYTHONIOENCODING</a>, <a href="whatsnew/2.6.html#index-21">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONMALLOCSTATS">PYTHONMALLOCSTATS</a>
</li>
        <li><a href="library/site.html#index-5">PYTHONNOUSERSITE</a>, <a href="library/site.html#index-8">[1]</a>, <a href="using/cmdline.html#envvar-PYTHONNOUSERSITE">[2]</a>, <a href="whatsnew/2.6.html#index-6">[3]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONOPTIMIZE">PYTHONOPTIMIZE</a>, <a href="using/cmdline.html#index-8">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-25">PYTHONPATH</a>, <a href="c-api/intro.html#index-28">[1]</a>, <a href="install/index.html#index-2">[2]</a>, <a href="install/index.html#index-3">[3]</a>, <a href="library/cgi.html#index-3">[4]</a>, <a href="library/sys.html#index-7">[5]</a>, <a href="library/sys.html#index-8">[6]</a>, <a href="tutorial/modules.html#index-1">[7]</a>, <a href="tutorial/modules.html#index-5">[8]</a>, <a href="tutorial/modules.html#index-6">[9]</a>, <a href="using/cmdline.html#envvar-PYTHONPATH">[10]</a>, <a href="using/cmdline.html#index-19">[11]</a>, <a href="using/cmdline.html#index-21">[12]</a>, <a href="using/cmdline.html#index-22">[13]</a>, <a href="using/cmdline.html#index-4">[14]</a>, <a href="using/mac.html#index-0">[15]</a>, <a href="using/windows.html#index-2">[16]</a>, <a href="using/windows.html#index-4">[17]</a>
</li>
        <li><a href="c-api/typeobj.html#index-3">PYTHONSHOWALLOCCOUNT</a>, <a href="using/cmdline.html#envvar-PYTHONSHOWALLOCCOUNT">[1]</a>, <a href="whatsnew/2.7.html#index-15">[2]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONSHOWREFCOUNT">PYTHONSHOWREFCOUNT</a>, <a href="whatsnew/2.7.html#index-14">[1]</a>
</li>
        <li><a href="library/idle.html#index-6">PYTHONSTARTUP</a>, <a href="library/readline.html#index-0">[1]</a>, <a href="library/rlcompleter.html#index-0">[2]</a>, <a href="library/user.html#index-1">[3]</a>, <a href="tutorial/appendix.html#index-1">[4]</a>, <a href="tutorial/interactive.html#index-1">[5]</a>, <a href="using/cmdline.html#envvar-PYTHONSTARTUP">[6]</a>, <a href="using/cmdline.html#index-6">[7]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONTHREADDEBUG">PYTHONTHREADDEBUG</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONUNBUFFERED">PYTHONUNBUFFERED</a>, <a href="using/cmdline.html#index-12">[1]</a>
</li>
        <li><a href="library/site.html#index-6">PYTHONUSERBASE</a>, <a href="library/site.html#index-7">[1]</a>, <a href="using/cmdline.html#envvar-PYTHONUSERBASE">[2]</a>, <a href="whatsnew/2.6.html#index-4">[3]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONVERBOSE">PYTHONVERBOSE</a>, <a href="using/cmdline.html#index-13">[1]</a>
</li>
        <li><a href="using/cmdline.html#envvar-PYTHONWARNINGS">PYTHONWARNINGS</a>, <a href="using/cmdline.html#index-15">[1]</a>, <a href="whatsnew/2.7.html#index-1">[2]</a>, <a href="whatsnew/2.7.html#index-8">[3]</a>
</li>
        <li><a href="library/time.html#index-3">PYTHONY2K</a>, <a href="library/time.html#index-4">[1]</a>, <a href="library/time.html#index-7">[2]</a>, <a href="using/cmdline.html#envvar-PYTHONY2K">[3]</a>
</li>
        <li><a href="library/xml.dom.html#index-0">PYTHON_DOM</a>
</li>
        <li><a href="library/ssl.html#index-18">SSL_CERT_FILE</a>
</li>
        <li><a href="library/ssl.html#index-19">SSL_CERT_PATH</a>
</li>
        <li><a href="library/subprocess.html#index-3">SystemRoot</a>
</li>
        <li><a href="faq/gui.html#index-0">TCL_LIBRARY</a>
</li>
        <li><a href="library/tempfile.html#index-2">TEMP</a>
</li>
        <li><a href="library/curses.html#index-1">TERM</a>, <a href="library/curses.html#index-2">[1]</a>
</li>
        <li><a href="library/tix.html#index-1">TIX_LIBRARY</a>
</li>
        <li><a href="faq/gui.html#index-1">TK_LIBRARY</a>
</li>
        <li><a href="library/os.html#index-19">TMP</a>, <a href="library/tempfile.html#index-3">[1]</a>
</li>
        <li><a href="library/os.html#index-18">TMPDIR</a>, <a href="library/tempfile.html#index-1">[1]</a>
</li>
        <li><a href="library/time.html#index-10">TZ</a>, <a href="library/time.html#index-11">[1]</a>, <a href="library/time.html#index-12">[2]</a>, <a href="library/time.html#index-13">[3]</a>, <a href="library/time.html#index-14">[4]</a>, <a href="library/time.html#index-15">[5]</a>
</li>
        <li><a href="library/getpass.html#index-1">USER</a>
</li>
        <li><a href="library/getpass.html#index-3">USERNAME</a>
</li>
        <li><a href="install/index.html#index-6">USERPROFILE</a>, <a href="library/os.path.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-9">USER_BASE</a>
</li>
        <li><a href="library/tempfile.html#index-4">Wimp$ScrapDir</a>
</li>
        <li><a href="c-api/intro.html#index-1">exec_prefix</a>, <a href="c-api/intro.html#index-4">[1]</a>, <a href="using/unix.html#index-1">[2]</a>
</li>
        <li><a href="library/urllib.html#index-3">ftp_proxy</a>
</li>
        <li><a href="howto/urllib2.html#index-1">http_proxy</a>, <a href="library/urllib.html#index-2">[1]</a>, <a href="library/urllib2.html#index-0">[2]</a>, <a href="library/urllib2.html#index-6">[3]</a>
</li>
        <li><a href="library/urllib.html#index-4">no_proxy</a>, <a href="library/urllib.html#index-6">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-0">prefix</a>, <a href="c-api/intro.html#index-2">[1]</a>, <a href="c-api/intro.html#index-3">[2]</a>, <a href="using/unix.html#index-0">[3]</a>
</li>
      </ul></li>
      <li>
    environment variables

      <ul>
        <li><a href="library/os.html#index-10">deleting</a>
</li>
        <li><a href="library/os.html#index-7">setting</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.EnvironmentError">EnvironmentError</a>
</li>
      <li><a href="library/test.html#test.support.EnvironmentVarGuard">EnvironmentVarGuard (class in test.support)</a>
</li>
      <li><a href="library/errno.html#errno.ENXIO">ENXIO (in module errno)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.eof">eof (shlex.shlex attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.EOFError">EOFError</a>

      <ul>
        <li><a href="c-api/file.html#index-3">(built-in exception)</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EOPNOTSUPP">EOPNOTSUPP (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EOVERFLOW">EOVERFLOW (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPERM">EPERM (in module errno)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/errno.html#errno.EPFNOSUPPORT">EPFNOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.epilogue">epilogue (email.message.Message attribute)</a>
</li>
      <li><a href="library/errno.html#errno.EPIPE">EPIPE (in module errno)</a>
</li>
      <li><a href="library/time.html#index-0">epoch</a>
</li>
      <li><a href="library/select.html#select.epoll">epoll() (in module select)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTO">EPROTO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTONOSUPPORT">EPROTONOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EPROTOTYPE">EPROTOTYPE (in module errno)</a>
</li>
      <li><a href="library/operator.html#operator.eq">eq() (in module operator)</a>
</li>
      <li><a href="library/token.html#token.EQEQUAL">EQEQUAL (in module token)</a>
</li>
      <li><a href="library/token.html#token.EQUAL">EQUAL (in module token)</a>
</li>
      <li><a href="library/locale.html#locale.ERA">ERA (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_D_FMT">ERA_D_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_D_T_FMT">ERA_D_T_FMT (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.ERA_T_FMT">ERA_T_FMT (in module locale)</a>
</li>
      <li><a href="library/errno.html#errno.ERANGE">ERANGE (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.window.erase">erase() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.erasechar">erasechar() (in module curses)</a>
</li>
      <li><a href="library/errno.html#errno.EREMCHG">EREMCHG (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EREMOTE">EREMOTE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EREMOTEIO">EREMOTEIO (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ERESTART">ERESTART (in module errno)</a>
</li>
      <li><a href="library/math.html#math.erf">erf() (in module math)</a>
</li>
      <li><a href="library/math.html#math.erfc">erfc() (in module math)</a>
</li>
      <li><a href="library/errno.html#errno.EROFS">EROFS (in module errno)</a>
</li>
      <li><a href="library/curses.html#curses.ERR">ERR (in module curses)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.errcheck">errcheck (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.errcode">errcode (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.errmsg">errmsg (xmlrpclib.ProtocolError attribute)</a>
</li>
      <li>
    errno

      <ul>
        <li><a href="library/exceptions.html#index-3">module</a>, <a href="library/socket.html#index-2">[1]</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#module-errno">errno (module)</a>
</li>
      <li><a href="library/binascii.html#binascii.Error">Error</a>, <a href="library/binhex.html#binhex.Error">[1]</a>, <a href="library/configparser.html#ConfigParser.Error">[2]</a>, <a href="library/csv.html#csv.Error">[3]</a>, <a href="library/locale.html#locale.Error">[4]</a>, <a href="library/macos.html#MacOS.Error">[5]</a>, <a href="library/mailbox.html#mailbox.Error">[6]</a>, <a href="library/shutil.html#shutil.Error">[7]</a>, <a href="library/sunau.html#sunau.Error">[8]</a>, <a href="library/uu.html#uu.Error">[9]</a>, <a href="library/wave.html#wave.Error">[10]</a>, <a href="library/webbrowser.html#webbrowser.Error">[11]</a>, <a href="library/xdrlib.html#xdrlib.Error">[12]</a>
</li>
      <li><a href="library/anydbm.html#anydbm.error">error</a>, <a href="library/audioop.html#audioop.error">[1]</a>, <a href="library/cd.html#cd.error">[2]</a>, <a href="library/copy.html#copy.error">[3]</a>, <a href="library/curses.html#curses.error">[4]</a>, <a href="library/dbhash.html#dbhash.error">[5]</a>, <a href="library/dbm.html#dbm.error">[6]</a>, <a href="library/dl.html#dl.error">[7]</a>, <a href="library/dumbdbm.html#dumbdbm.error">[8]</a>, <a href="library/gdbm.html#gdbm.error">[9]</a>, <a href="library/getopt.html#getopt.error">[10]</a>, <a href="library/ic.html#ic.error">[11]</a>, <a href="library/imageop.html#imageop.error">[12]</a>, <a href="library/imgfile.html#imgfile.error">[13]</a>, <a href="library/jpeg.html#jpeg.error">[14]</a>, <a href="library/nis.html#nis.error">[15]</a>, <a href="library/os.html#os.error">[16]</a>, <a href="library/pyexpat.html#xml.parsers.expat.error">[17]</a>, <a href="library/re.html#re.error">[18]</a>, <a href="library/resource.html#resource.error">[19]</a>, <a href="library/select.html#select.error">[20]</a>, <a href="library/socket.html#socket.error">[21]</a>, <a href="library/struct.html#struct.error">[22]</a>, <a href="library/sunaudio.html#sunaudiodev.error">[23]</a>, <a href="library/thread.html#thread.error">[24]</a>, <a href="library/zlib.html#zlib.error">[25]</a>
</li>
      <li><a href="library/cd.html#cd.ERROR">ERROR (in module cd)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">error handling</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.error">error() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/logging.html#logging.error">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.error">(logging.Logger method)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.Folder.error">(mhlib.Folder method)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.MH.error">(mhlib.MH method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.OpenerDirector.error">(urllib2.OpenerDirector method)</a>
</li>
        <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.error">(xml.sax.handler.ErrorHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_body">error_body (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.error_content_type">error_content_type (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_headers">error_headers (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.error_leader">error_leader() (shlex.shlex method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.error_message_format">error_message_format (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_output">error_output() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_perm">error_perm</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_proto">error_proto</a>, <a href="library/poplib.html#poplib.error_proto">[1]</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_reply">error_reply</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.error_status">error_status (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.error_temp">error_temp</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorByteIndex">ErrorByteIndex (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/errno.html#errno.errorcode">errorcode (in module errno)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorCode">ErrorCode (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorColumnNumber">ErrorColumnNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler">ErrorHandler (class in xml.sax.handler)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ErrorLineNumber">ErrorLineNumber (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li>
    Errors

      <ul>
        <li><a href="library/logging.html#index-0">logging</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-13">errors</a>

      <ul>
        <li><a href="library/stdtypes.html#file.errors">(file attribute)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.errors">(io.TextIOBase attribute)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestResult.errors">(unittest.TestResult attribute)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ErrorString">ErrorString() (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/token.html#token.ERRORTOKEN">ERRORTOKEN (in module token)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.escape">escape (shlex.shlex attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-15">escape sequence</a>
</li>
      <li><a href="library/cgi.html#cgi.escape">escape() (in module cgi)</a>

      <ul>
        <li><a href="library/re.html#re.escape">(in module re)</a>
</li>
        <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.escape">(in module xml.sax.saxutils)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.Dialect.escapechar">escapechar (csv.Dialect attribute)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.escapedquotes">escapedquotes (shlex.shlex attribute)</a>
</li>
      <li><a href="library/errno.html#errno.ESHUTDOWN">ESHUTDOWN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESOCKTNOSUPPORT">ESOCKTNOSUPPORT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESPIPE">ESPIPE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESRCH">ESRCH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESRMNT">ESRMNT (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESTALE">ESTALE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ESTRPIPE">ESTRPIPE (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ETIME">ETIME (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.ETIMEDOUT">ETIMEDOUT (in module errno)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.Etiny">Etiny() (decimal.Context method)</a>
</li>
      <li><a href="library/errno.html#errno.ETOOMANYREFS">ETOOMANYREFS (in module errno)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.Etop">Etop() (decimal.Context method)</a>
</li>
      <li><a href="library/errno.html#errno.ETXTBSY">ETXTBSY (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUCLEAN">EUCLEAN (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUNATCH">EUNATCH (in module errno)</a>
</li>
      <li><a href="library/errno.html#errno.EUSERS">EUSERS (in module errno)</a>
</li>
      <li>
    eval

      <ul>
        <li><a href="library/parser.html#index-1">built-in function</a>, <a href="library/pprint.html#index-0">[1]</a>, <a href="library/pprint.html#index-1">[2]</a>, <a href="library/stdtypes.html#index-41">[3]</a>, <a href="library/string.html#index-7">[4]</a>, <a href="reference/simple_stmts.html#index-55">[5]</a>, <a href="reference/simple_stmts.html#index-58">[6]</a>, <a href="reference/toplevel_components.html#index-6">[7]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#eval">eval() (built-in function)</a>
</li>
      <li>
    evaluation

      <ul>
        <li><a href="reference/expressions.html#index-79">order</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Event">Event (class in multiprocessing)</a>

      <ul>
        <li><a href="library/threading.html#threading.Event">(class in threading)</a>
</li>
      </ul></li>
      <li><a href="library/sched.html#index-0">event scheduling</a>
</li>
      <li><a href="library/msilib.html#msilib.Control.event">event() (msilib.Control method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Event">Event() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/tkinter.html#index-3">events (widgets)</a>
</li>
      <li><a href="library/errno.html#errno.EWOULDBLOCK">EWOULDBLOCK (in module errno)</a>
</li>
      <li><a href="library/os.html#os.EX_CANTCREAT">EX_CANTCREAT (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_CONFIG">EX_CONFIG (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_DATAERR">EX_DATAERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_IOERR">EX_IOERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOHOST">EX_NOHOST (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOINPUT">EX_NOINPUT (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOPERM">EX_NOPERM (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOTFOUND">EX_NOTFOUND (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_NOUSER">EX_NOUSER (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OK">EX_OK (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OSERR">EX_OSERR (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_OSFILE">EX_OSFILE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_PROTOCOL">EX_PROTOCOL (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_SOFTWARE">EX_SOFTWARE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_TEMPFAIL">EX_TEMPFAIL (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_UNAVAILABLE">EX_UNAVAILABLE (in module os)</a>
</li>
      <li><a href="library/os.html#os.EX_USAGE">EX_USAGE (in module os)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example">Example (class in doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.example">example (doctest.DocTestFailure attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.UnexpectedException.example">(doctest.UnexpectedException attribute)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTest.examples">examples (doctest.DocTest attribute)</a>
</li>
      <li><a href="library/sys.html#sys.exc_clear">exc_clear() (in module sys)</a>
</li>
      <li><a href="library/doctest.html#doctest.UnexpectedException.exc_info">exc_info (doctest.UnexpectedException attribute)</a>

      <ul>
        <li><a href="reference/datamodel.html#index-67">(in module sys)</a>
</li>
      </ul></li>
      <li><a href="c-api/intro.html#index-15">exc_info() (in module sys)</a>, <a href="library/sys.html#sys.exc_info">[1]</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.exc_msg">exc_msg (doctest.Example attribute)</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_traceback (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_traceback">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/datamodel.html#index-67">[4]</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_type (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_type">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>
</li>
      <li><a href="c-api/exceptions.html#index-0">exc_value (in module sys)</a>, <a href="c-api/intro.html#index-14">[1]</a>, <a href="library/sys.html#sys.exc_value">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>
</li>
      <li><a href="library/csv.html#csv.excel">excel (class in csv)</a>
</li>
      <li><a href="library/csv.html#csv.excel_tab">excel_tab (class in csv)</a>
</li>
      <li>
    except

      <ul>
        <li><a href="howto/doanddont.html#index-0">bare</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">keyword</a>
</li>
        <li><a href="library/exceptions.html#index-0">statement</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-except">except (2to3 fixer)</a>
</li>
      <li><a href="library/cgitb.html#index-1">excepthook() (in module sys)</a>, <a href="library/sys.html#sys.excepthook">[1]</a>
</li>
      <li><a href="library/exceptions.html#exceptions.Exception">Exception</a>
</li>
      <li><a href="reference/executionmodel.html#index-12">exception</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-16">AssertionError</a>
</li>
        <li><a href="reference/expressions.html#index-30">AttributeError</a>
</li>
        <li><a href="reference/expressions.html#index-26">GeneratorExit</a>
</li>
        <li><a href="reference/simple_stmts.html#index-44">ImportError</a>, <a href="reference/simple_stmts.html#index-47">[1]</a>, <a href="reference/simple_stmts.html#index-48">[2]</a>
</li>
        <li><a href="reference/expressions.html#index-6">NameError</a>
</li>
        <li><a href="reference/simple_stmts.html#index-24">RuntimeError</a>
</li>
        <li><a href="reference/expressions.html#index-25">StopIteration</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-51">TypeError</a>
</li>
        <li><a href="reference/expressions.html#index-59">ValueError</a>
</li>
        <li><a href="reference/expressions.html#index-54">ZeroDivisionError</a>
</li>
        <li><a href="reference/datamodel.html#index-67">handler</a>
</li>
        <li><a href="reference/simple_stmts.html#index-31">raising</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#Tkinter.EXCEPTION">EXCEPTION (in module Tkinter)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">exception handler</a>
</li>
      <li><a href="library/logging.html#logging.exception">exception() (in module logging)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.exception">(logging.Logger method)</a>
</li>
      </ul></li>
      <li>
    exceptions

      <ul>
        <li><a href="library/cgitb.html#index-0">in CGI scripts</a>
</li>
        <li><a href="c-api/intro.html#index-20">module</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#module-exceptions">exceptions (module)</a>
</li>
      <li>
    exclusive

      <ul>
        <li><a href="reference/expressions.html#index-62">or</a>
</li>
      </ul></li>
      <li><a href="library/errno.html#errno.EXDEV">EXDEV (in module errno)</a>
</li>
      <li>
    exec

      <ul>
        <li><a href="library/stdtypes.html#index-41">statement</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>, <a href="reference/simple_stmts.html#index-56">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-exec">exec (2to3 fixer)</a>
</li>
      <li><a href="c-api/intro.html#index-1">exec_prefix</a>, <a href="c-api/intro.html#index-4">[1]</a>, <a href="using/unix.html#index-1">[2]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.EXEC_PREFIX">EXEC_PREFIX (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sys.html#sys.exec_prefix">exec_prefix (in module sys)</a>
</li>
      <li><a href="library/dis.html#opcode-EXEC_STMT">EXEC_STMT (opcode)</a>
</li>
      <li>
    execfile

      <ul>
        <li><a href="library/user.html#index-2">built-in function</a>, <a href="reference/simple_stmts.html#index-55">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-execfile">execfile (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#execfile">execfile() (built-in function)</a>
</li>
      <li><a href="library/os.html#os.execl">execl() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execle">execle() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execlp">execlp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execlpe">execlpe() (in module os)</a>
</li>
      <li><a href="c-api/init.html#index-3">executable (in module sys)</a>, <a href="library/sys.html#sys.executable">[1]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.executable_filename">executable_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.execute">execute() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.util.execute">(in module distutils.util)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.View.Execute">Execute() (msilib.View method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.execute">execute() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.execute">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.executemany">executemany() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.executemany">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.executescript">executescript() (sqlite3.Connection method)</a>

      <ul>
        <li><a href="library/sqlite3.html#sqlite3.Cursor.executescript">(sqlite3.Cursor method)</a>
</li>
      </ul></li>
      <li>
    execution

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">frame</a>, <a href="reference/executionmodel.html#index-4">[1]</a>
</li>
        <li><a href="reference/executionmodel.html#index-10">restricted</a>
</li>
        <li><a href="reference/datamodel.html#index-67">stack</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-0">execution model</a>
</li>
      <li><a href="library/os.html#os.execv">execv() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execve">execve() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execvp">execvp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.execvpe">execvpe() (in module os)</a>
</li>
      <li><a href="library/tix.html#Tix.ExFileSelectBox">ExFileSelectBox (class in Tix)</a>
</li>
      <li><a href="library/errno.html#errno.EXFULL">EXFULL (in module errno)</a>
</li>
      <li><a href="library/os.path.html#os.path.exists">exists() (in module os.path)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.exists">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#exit">exit (built-in variable)</a>
</li>
      <li><a href="c-api/sys.html#index-1">exit()</a>

      <ul>
        <li><a href="library/argparse.html#argparse.ArgumentParser.exit">(argparse.ArgumentParser method)</a>
</li>
        <li><a href="library/sys.html#sys.exit">(in module sys)</a>
</li>
        <li><a href="library/thread.html#thread.exit">(in module thread)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.exitcode">exitcode (multiprocessing.Process attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-exitfunc">exitfunc (2to3 fixer)</a>

      <ul>
        <li><a href="library/sys.html#sys.exitfunc">(in module sys)</a>
</li>
        <li><a href="library/atexit.html#index-0">(in sys)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.exitonclick">exitonclick() (in module turtle)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.exp">exp() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.exp">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.exp">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.exp">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/re.html#re.MatchObject.expand">expand() (re.MatchObject method)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.expand_tabs">expand_tabs (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.ExpandEnvironmentStrings">ExpandEnvironmentStrings() (in module _winreg)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.expandNode">expandNode() (xml.dom.pulldom.DOMEventStream method)</a>
</li>
      <li><a href="library/string.html#string.expandtabs">expandtabs() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.expandtabs">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.expanduser">expanduser() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.expandvars">expandvars() (in module os.path)</a>
</li>
      <li><a href="library/pyexpat.html#index-0">Expat</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError">ExpatError</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.expect">expect() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/unittest.html#unittest.expectedFailure">expectedFailure() (in module unittest)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.expectedFailures">expectedFailures (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.expires">expires (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/math.html#math.expm1">expm1() (in module math)</a>
</li>
      <li><a href="library/random.html#random.expovariate">expovariate() (in module random)</a>
</li>
      <li><a href="library/parser.html#parser.expr">expr() (in module parser)</a>
</li>
      <li><a href="reference/expressions.html#index-0">expression</a>, <a href="glossary.html#term-expression"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-69">Conditional</a>
</li>
        <li><a href="reference/expressions.html#index-73">conditional</a>
</li>
        <li><a href="reference/expressions.html#index-15">generator</a>
</li>
        <li><a href="reference/compound_stmts.html#index-22">lambda</a>, <a href="reference/expressions.html#index-75">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-76">list</a>, <a href="reference/simple_stmts.html#index-1">[1]</a>, <a href="reference/simple_stmts.html#index-4">[2]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-1">statement</a>
</li>
        <li><a href="reference/expressions.html#index-22">yield</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.expunge">expunge() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/array.html#array.array.extend">extend() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.extend">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.extend">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/pkgutil.html#pkgutil.extend_path">extend_path() (in module pkgutil)</a>
</li>
      <li>
    extended

      <ul>
        <li><a href="reference/expressions.html#index-36">slicing</a>
</li>
      </ul></li>
      <li><a href="reference/simple_stmts.html#index-25">extended print statement</a>
</li>
      <li>
    extended slice

      <ul>
        <li><a href="library/stdtypes.html#index-30">assignment</a>
</li>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-19">extended slicing</a>
</li>
      <li><a href="library/dis.html#opcode-EXTENDED_ARG">EXTENDED_ARG (opcode)</a>
</li>
      <li><a href="library/decimal.html#decimal.ExtendedContext">ExtendedContext (class in decimal)</a>
</li>
      <li><a href="library/collections.html#collections.deque.extendleft">extendleft() (collections.deque method)</a>
</li>
      <li>
    extension

      <ul>
        <li><a href="reference/datamodel.html#index-4">module</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.core.Extension">Extension (class in distutils.core)</a>
</li>
      <li><a href="glossary.html#term-extension-module"><strong>extension module</strong></a>
</li>
      <li><a href="library/simplehttpserver.html#SimpleHTTPServer.SimpleHTTPRequestHandler.extensions_map">extensions_map (SimpleHTTPServer.SimpleHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/pickle.html#index-1">External Data Representation</a>, <a href="library/xdrlib.html#index-0">[1]</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.external_attr">external_attr (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.ExternalClashError">ExternalClashError</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ExternalEntityParserCreate">ExternalEntityParserCreate() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ExternalEntityRefHandler">ExternalEntityRefHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.extra">extra (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extract">extract() (tarfile.TarFile method)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.extract">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.extract_cookies">extract_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/traceback.html#traceback.extract_stack">extract_stack() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.extract_tb">extract_tb() (in module traceback)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.extract_version">extract_version (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extractall">extractall() (tarfile.TarFile method)</a>

      <ul>
        <li><a href="library/zipfile.html#zipfile.ZipFile.extractall">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.ExtractError">ExtractError</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.extractfile">extractfile() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/os.html#os.extsep">extsep (in module os)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\V�:�s�s�html/genindex-F.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-F.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; F</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="reference/datamodel.html#index-65">f_back (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BAVAIL">F_BAVAIL (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BFREE">F_BFREE (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BLOCKS">F_BLOCKS (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_BSIZE">F_BSIZE (in module statvfs)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_builtins (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_code (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_traceback (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_type (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_exc_value (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FAVAIL">F_FAVAIL (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FFREE">F_FFREE (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FILES">F_FILES (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FLAG">F_FLAG (in module statvfs)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_FRSIZE">F_FRSIZE (in module statvfs)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_globals (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_lasti (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_lineno (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_locals (frame attribute)</a>
</li>
      <li><a href="library/statvfs.html#statvfs.F_NAMEMAX">F_NAMEMAX (in module statvfs)</a>
</li>
      <li><a href="library/os.html#os.F_OK">F_OK (in module os)</a>
</li>
      <li><a href="reference/datamodel.html#index-65">f_restricted (frame attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-66">f_trace (frame attribute)</a>
</li>
      <li><a href="library/math.html#math.fabs">fabs() (in module math)</a>
</li>
      <li><a href="library/math.html#math.factorial">factorial() (in module math)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.fail">fail() (unittest.TestCase method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.failfast">failfast (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.failureException">failureException (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestResult.failures">failures (unittest.TestResult attribute)</a>
</li>
      <li><a href="library/stdtypes.html#index-43">False</a>, <a href="library/stdtypes.html#index-6">[1]</a>, <a href="reference/datamodel.html#index-13">[2]</a>
</li>
      <li><a href="library/stdtypes.html#index-2">false</a>
</li>
      <li><a href="library/stdtypes.html#index-4">False (Built-in object)</a>

      <ul>
        <li><a href="library/constants.html#False">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.socket.family">family (socket.socket attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.fancy_getopt">fancy_getopt() (in module distutils.fancy_getopt)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt">FancyGetopt (class in distutils.fancy_getopt)</a>
</li>
      <li><a href="library/urllib.html#urllib.FancyURLopener">FancyURLopener (class in urllib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ErrorHandler.fatalError">fatalError() (xml.sax.handler.ErrorHandler method)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault">Fault (class in xmlrpclib)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault.faultCode">faultCode (xmlrpclib.Fault attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.Fault.faultString">faultString (xmlrpclib.Fault attribute)</a>
</li>
      <li><a href="library/os.html#os.fchdir">fchdir() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fchmod">fchmod() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fchown">fchown() (in module os)</a>
</li>
      <li><a href="library/msilib.html#msilib.FCICreate">FCICreate() (in module msilib)</a>
</li>
      <li>
    fcntl

      <ul>
        <li><a href="library/stdtypes.html#index-35">module</a>
</li>
      </ul></li>
      <li><a href="library/fcntl.html#module-fcntl">fcntl (module)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.fcntl">fcntl() (in module fcntl)</a>, <a href="library/posixfile.html#index-1">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.fd">fd() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.fdatasync">fdatasync() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fdopen">fdopen() (in module os)</a>
</li>
      <li><a href="library/msilib.html#msilib.Feature">Feature (class in msilib)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_external_ges">feature_external_ges (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_external_pes">feature_external_pes (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_namespace_prefixes">feature_namespace_prefixes (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_namespaces">feature_namespaces (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_string_interning">feature_string_interning (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.feature_validation">feature_validation (in module xml.sax.handler)</a>
</li>
      <li><a href="library/email.parser.html#email.parser.FeedParser.feed">feed() (email.parser.FeedParser method)</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.feed">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.feed">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.XMLParser.feed">(xml.etree.ElementTree.XMLParser method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.feed">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
      </ul></li>
      <li><a href="library/email.parser.html#email.parser.FeedParser">FeedParser (class in email.parser)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.fetch">fetch() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.Fetch">Fetch() (msilib.View method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchall">fetchall() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchmany">fetchmany() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.fetchone">fetchone() (sqlite3.Cursor method)</a>
</li>
      <li><a href="library/select.html#select.kevent.fflags">fflags (select.kevent attribute)</a>
</li>
      <li><a href="library/csv.html#csv.field_size_limit">field_size_limit() (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.fieldnames">fieldnames (csv.csvreader attribute)</a>
</li>
      <li><a href="library/uuid.html#uuid.UUID.fields">fields (uuid.UUID attribute)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo">fifo (class in asynchat)</a>
</li>
      <li>
    file

      <ul>
        <li><a href="library/configparser.html#index-0">.ini</a>
</li>
        <li><a href="library/pdb.html#index-2">.pdbrc</a>
</li>
        <li><a href="library/user.html#index-0">.pythonrc.py</a>
</li>
        <li><a href="library/stdtypes.html#index-34">built-in function</a>
</li>
        <li><a href="library/imp.html#index-1">byte-code</a>, <a href="library/imp.html#index-3">[1]</a>, <a href="library/py_compile.html#index-0">[2]</a>
</li>
        <li><a href="library/configparser.html#index-0">configuration</a>
</li>
        <li><a href="library/shutil.html#index-0">copying</a>
</li>
        <li><a href="library/pdb.html#index-2">debugger configuration</a>
</li>
        <li><a href="library/stdtypes.html#index-35">descriptor</a>
</li>
        <li><a href="library/posix.html#index-1">large files</a>
</li>
        <li><a href="library/mimetypes.html#index-2">mime.types</a>
</li>
        <li><a href="c-api/file.html#index-0">object</a>, <a href="library/stdtypes.html#index-34">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/toplevel_components.html#index-8">[3]</a>, <a href="tutorial/inputoutput.html#index-0">[4]</a>
</li>
        <li><a href="library/site.html#index-2">path configuration</a>
</li>
        <li><a href="library/plistlib.html#index-0">plist</a>
</li>
        <li><a href="library/tempfile.html#index-0">temporary</a>
</li>
        <li><a href="library/user.html#index-0">user configuration</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.file">file (pyclbr.Class attribute)</a>

      <ul>
        <li><a href="library/pyclbr.html#pyclbr.Function.file">(pyclbr.Function attribute)</a>
</li>
      </ul></li>
      <li>
    file ...

      <ul>
        <li><a href="library/compileall.html#cmdoption-compileall-arg-file">compileall command line option</a>
</li>
      </ul></li>
      <li>
    file control

      <ul>
        <li><a href="library/fcntl.html#index-0">UNIX</a>
</li>
      </ul></li>
      <li>
    file name

      <ul>
        <li><a href="library/tempfile.html#index-0">temporary</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-file-object"><strong>file object</strong></a>

      <ul>
        <li><a href="library/posixfile.html#index-0">POSIX</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#file">file() (built-in function)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.file">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-file-like-object"><strong>file-like object</strong></a>
</li>
      <li><a href="distutils/builtdist.html#file_created">file_created() (built-in function)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.file_dispatcher">file_dispatcher (class in asyncore)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FileHandler.file_open">file_open() (urllib2.FileHandler method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.file_size">file_size (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.file_wrapper">file_wrapper (class in asyncore)</a>
</li>
      <li><a href="library/filecmp.html#module-filecmp">filecmp (module)</a>
</li>
      <li><a href="library/logging.config.html#logging.config.fileConfig">fileConfig() (in module logging.config)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar">FileCookieJar (class in cookielib)</a>
</li>
      <li><a href="library/tix.html#Tix.FileEntry">FileEntry (class in Tix)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.FileHandler">FileHandler (class in logging)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.FileHandler">(class in urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.FileInput">FileInput (class in fileinput)</a>
</li>
      <li><a href="library/fileinput.html#module-fileinput">fileinput (module)</a>
</li>
      <li><a href="library/io.html#io.FileIO">FileIO (class in io)</a>
</li>
      <li><a href="library/fileinput.html#fileinput.filelineno">filelineno() (in module fileinput)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.filename">filename (cookielib.FileCookieJar attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.filename">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipInfo.filename">(zipfile.ZipInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.filename">filename() (in module fileinput)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.filename_only">filename_only (in module tabnanny)</a>
</li>
      <li>
    filenames

      <ul>
        <li><a href="library/glob.html#index-0">pathname expansion</a>
</li>
        <li><a href="library/fnmatch.html#index-0">wildcard expansion</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.fileno">fileno() (Connection method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.fileno">(SocketServer.BaseServer method)</a>
</li>
        <li><a href="library/stdtypes.html#file.fileno">(file method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.fileno">(hotshot.Profile method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPResponse.fileno">(httplib.HTTPResponse method)</a>
</li>
        <li><a href="library/fileinput.html#fileinput.fileno">(in module fileinput)</a>
</li>
        <li><a href="library/io.html#io.IOBase.fileno">(io.IOBase method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.fileno">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.fileno">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/select.html#select.epoll.fileno">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.fileno">(select.kqueue method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.fileno">(socket.socket method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.fileno">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#posixfile.fileopen">fileopen() (in module posixfile)</a>
</li>
      <li><a href="library/tix.html#Tix.FileSelectBox">FileSelectBox (class in Tix)</a>
</li>
      <li><a href="library/argparse.html#argparse.FileType">FileType (class in argparse)</a>

      <ul>
        <li><a href="c-api/file.html#index-1">(in module types)</a>, <a href="library/types.html#types.FileType">[1]</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.FileWrapper">FileWrapper (class in wsgiref.util)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.fill">fill() (in module textwrap)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.fill">(in module turtle)</a>
</li>
        <li><a href="library/textwrap.html#textwrap.TextWrapper.fill">(textwrap.TextWrapper method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.fillcolor">fillcolor() (in module turtle)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-filter">filter (2to3 fixer)</a>
</li>
      <li><a href="library/logging.html#logging.Filter">Filter (class in logging)</a>
</li>
      <li><a href="library/select.html#select.kevent.filter">filter (select.kevent attribute)</a>
</li>
      <li><a href="library/functions.html#filter">filter() (built-in function)</a>

      <ul>
        <li><a href="library/curses.html#curses.filter">(in module curses)</a>
</li>
        <li><a href="library/fnmatch.html#fnmatch.filter">(in module fnmatch)</a>
</li>
        <li><a href="library/future_builtins.html#future_builtins.filter">(in module future_builtins)</a>
</li>
        <li><a href="library/logging.html#logging.Filter.filter">(logging.Filter method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.filter">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.filter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/warnings.html#warnings.filterwarnings">filterwarnings() (in module warnings)</a>
</li>
      <li><a href="extending/newtypes.html#index-0">finalization, of objects</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.finalize_options">finalize_options() (distutils.cmd.Command method)</a>
</li>
      <li>
    finally

      <ul>
        <li><a href="reference/compound_stmts.html#index-10">keyword</a>, <a href="reference/compound_stmts.html#index-13">[1]</a>, <a href="reference/simple_stmts.html#index-27">[2]</a>, <a href="reference/simple_stmts.html#index-36">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.DocTestFinder.find">find() (doctest.DocTestFinder method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.find">(in module gettext)</a>
</li>
        <li><a href="library/string.html#string.find">(in module string)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.find">(mmap.mmap method)</a>
</li>
        <li><a href="library/stdtypes.html#str.find">(str method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.find">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.find">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.form.find_first">find_first() (fl.form method)</a>
</li>
      <li><a href="library/pickle.html#index-4">find_global() (pickle protocol)</a>
</li>
      <li><a href="library/fl.html#fl.form.find_last">find_last() (fl.form method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.util.find_library">find_library() (in module ctypes.util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.find_library_file">find_library_file() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.find_loader">find_loader() (in module pkgutil)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.find_longest_match">find_longest_match() (difflib.SequenceMatcher method)</a>
</li>
      <li>
    find_module

      <ul>
        <li><a href="reference/simple_stmts.html#index-41">finder</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.NullImporter.find_module">find_module() (imp.NullImporter method)</a>

      <ul>
        <li><a href="library/imp.html#imp.find_module">(in module imp)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.find_module">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.util.find_msvcrt">find_msvcrt() (in module ctypes.util)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr.find_user_password">find_user_password() (urllib2.HTTPPasswordMgr method)</a>
</li>
      <li><a href="library/re.html#re.findall">findall() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.findall">(re.RegexObject method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findall">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findall">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger.findCaller">findCaller() (logging.Logger method)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-41">finder</a>, <a href="glossary.html#term-finder"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-41">find_module</a>
</li>
      </ul></li>
      <li><a href="library/macostools.html#module-findertools">findertools (module)</a>
</li>
      <li><a href="library/audioop.html#audioop.findfactor">findfactor() (in module audioop)</a>
</li>
      <li><a href="library/test.html#test.support.findfile">findfile() (in module test.support)</a>
</li>
      <li><a href="library/audioop.html#audioop.findfit">findfit() (in module audioop)</a>
</li>
      <li><a href="library/fm.html#fm.findfont">findfont() (in module fm)</a>
</li>
      <li><a href="library/re.html#re.finditer">finditer() (in module re)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.finditer">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#dis.findlabels">findlabels() (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.findlinestarts">findlinestarts() (in module dis)</a>
</li>
      <li><a href="library/mailcap.html#mailcap.findmatch">findmatch() (in module mailcap)</a>
</li>
      <li><a href="library/audioop.html#audioop.findmax">findmax() (in module audioop)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.findtext">findtext() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.findtext">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.finish">finish() (SocketServer.BaseRequestHandler method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.finish_request">finish_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo.first">first() (asynchat.fifo method)</a>

      <ul>
        <li><a href="library/bsddb.html#bsddb.bsddbobject.first">(bsddb.bsddbobject method)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.dbhash.first">(dbhash.dbhash method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.firstChild">firstChild (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.firstkey">firstkey() (in module gdbm)</a>
</li>
      <li><a href="library/calendar.html#calendar.firstweekday">firstweekday() (in module calendar)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.fix">fix() (in module fpformat)</a>
</li>
      <li><a href="library/ast.html#ast.fix_missing_locations">fix_missing_locations() (in module ast)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.fix_sentence_endings">fix_sentence_endings (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/fl.html#module-FL">FL (module)</a>
</li>
      <li><a href="library/fl.html#module-fl">fl (module)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.flag_bits">flag_bits (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/sys.html#sys.flags">flags (in module sys)</a>

      <ul>
        <li><a href="library/re.html#re.RegexObject.flags">(re.RegexObject attribute)</a>
</li>
        <li><a href="library/select.html#select.kevent.flags">(select.kevent attribute)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#posixfile.posixfile.flags">flags() (posixfile.posixfile method)</a>
</li>
      <li><a href="library/curses.html#curses.flash">flash() (in module curses)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/email.generator.html#email.generator.Generator.flatten">flatten() (email.generator.Generator method)</a>
</li>
      <li>
    flattening

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li>
    float

      <ul>
        <li><a href="c-api/number.html#index-7">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-5">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#float">float (built-in class)</a>
</li>
      <li><a href="library/sys.html#sys.float_info">float_info (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.float_repr_style">float_repr_style (in module sys)</a>
</li>
      <li>
    floating point

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="reference/datamodel.html#index-15">number</a>
</li>
        <li><a href="c-api/float.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-15">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">floating point literal</a>
</li>
      <li><a href="library/exceptions.html#exceptions.FloatingPointError">FloatingPointError</a>, <a href="library/fpectl.html#fpectl.FloatingPointError">[1]</a>
</li>
      <li><a href="library/types.html#types.FloatType">FloatType (in module types)</a>

      <ul>
        <li><a href="c-api/float.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/fcntl.html#fcntl.flock">flock() (in module fcntl)</a>
</li>
      <li><a href="glossary.html#term-floor-division"><strong>floor division</strong></a>
</li>
      <li><a href="library/math.html#math.floor">floor() (in module math)</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      <li><a href="library/operator.html#operator.floordiv">floordiv() (in module operator)</a>
</li>
      <li><a href="library/fl.html#module-flp">flp (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2Compressor.flush">flush() (bz2.BZ2Compressor method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.flush">(file method)</a>
</li>
        <li><a href="library/formatter.html#formatter.writer.flush">(formatter.writer method)</a>
</li>
        <li><a href="library/io.html#io.BufferedWriter.flush">(io.BufferedWriter method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.flush">(io.IOBase method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.flush">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.StreamHandler.flush">(logging.StreamHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.BufferingHandler.flush">(logging.handlers.BufferingHandler method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler.flush">(logging.handlers.MemoryHandler method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.flush">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.flush">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.flush">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.flush">(mmap.mmap method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Compress.flush">(zlib.Compress method)</a>
</li>
        <li><a href="library/zlib.html#zlib.Decompress.flush">(zlib.Decompress method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.flush_softspace">flush_softspace() (formatter.formatter method)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.flushheaders">flushheaders() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/curses.html#curses.flushinp">flushinp() (in module curses)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.FlushKey">FlushKey() (in module _winreg)</a>
</li>
      <li><a href="library/fm.html#module-fm">fm (module)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.fma">fma() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.fma">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.fmod">fmod() (in module math)</a>
</li>
      <li><a href="library/fnmatch.html#module-fnmatch">fnmatch (module)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.fnmatch">fnmatch() (in module fnmatch)</a>
</li>
      <li><a href="library/fnmatch.html#fnmatch.fnmatchcase">fnmatchcase() (in module fnmatch)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.focus">focus() (ttk.Treeview method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder">Folder (class in mhlib)</a>
</li>
      <li><a href="library/fm.html#index-0">Font Manager, IRIS</a>
</li>
      <li><a href="library/fm.html#fm.fontpath">fontpath() (in module fm)</a>
</li>
      <li><a href="c-api/file.html#index-2">fopen()</a>
</li>
      <li>
    for

      <ul>
        <li><a href="reference/compound_stmts.html#index-6">statement</a>, <a href="reference/simple_stmts.html#index-33">[1]</a>, <a href="reference/simple_stmts.html#index-37">[2]</a>, <a href="tutorial/controlflow.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-0">[4]</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-FOR_ITER">FOR_ITER (opcode)</a>
</li>
      <li><a href="library/test.html#test.support.forget">forget() (in module test.support)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Notebook.forget">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.fork">fork() (in module os)</a>

      <ul>
        <li><a href="library/pty.html#pty.fork">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.ForkingMixIn">ForkingMixIn (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ForkingTCPServer">ForkingTCPServer (class in SocketServer)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.ForkingUDPServer">ForkingUDPServer (class in SocketServer)</a>
</li>
      <li><a href="library/os.html#os.forkpty">forkpty() (in module os)</a>
</li>
      <li><a href="library/tix.html#Tix.Form">Form (class in Tix)</a>
</li>
      <li>
    format

      <ul>
        <li><a href="library/functions.html#index-3">str</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#memoryview.format">format (memoryview attribute)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.format">(struct.Struct attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#format">format() (built-in function)</a>

      <ul>
        <li><a href="library/locale.html#locale.format">(in module locale)</a>
</li>
        <li><a href="library/logging.html#logging.Formatter.format">(logging.Formatter method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.format">(logging.Handler method)</a>
</li>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.format">(pprint.PrettyPrinter method)</a>
</li>
        <li><a href="library/stdtypes.html#str.format">(str method)</a>
</li>
        <li><a href="library/string.html#string.Formatter.format">(string.Formatter method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.format_exc">format_exc() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_exception">format_exception() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_exception_only">format_exception_only() (in module traceback)</a>
</li>
      <li><a href="library/string.html#string.Formatter.format_field">format_field() (string.Formatter method)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.format_help">format_help() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_list">format_list() (in module traceback)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_stack">format_stack() (in module traceback)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.format_stack_entry">format_stack_entry() (bdb.Bdb method)</a>
</li>
      <li><a href="library/locale.html#locale.format_string">format_string() (in module locale)</a>
</li>
      <li><a href="library/traceback.html#traceback.format_tb">format_tb() (in module traceback)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.format_usage">format_usage() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.formataddr">formataddr() (in module email.utils)</a>
</li>
      <li><a href="library/inspect.html#inspect.formatargspec">formatargspec() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.formatargvalues">formatargvalues() (in module inspect)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.formatdate">formatdate() (in module email.utils)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.FormatError">FormatError</a>
</li>
      <li><a href="library/ctypes.html#ctypes.FormatError">FormatError() (in module ctypes)</a>
</li>
      <li><a href="library/logging.html#logging.Formatter.formatException">formatException() (logging.Formatter method)</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatmonth">formatmonth() (calendar.HTMLCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.TextCalendar.formatmonth">(calendar.TextCalendar method)</a>
</li>
      </ul></li>
      <li>
    formatter

      <ul>
        <li><a href="library/htmllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Formatter">Formatter (class in logging)</a>

      <ul>
        <li><a href="library/string.html#string.Formatter">(class in string)</a>
</li>
      </ul></li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.formatter">formatter (htmllib.HTMLParser attribute)</a>

      <ul>
        <li><a href="library/formatter.html#module-formatter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Formatter.formatTime">formatTime() (logging.Formatter method)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">formatting, string (%)</a>
</li>
      <li><a href="library/warnings.html#warnings.formatwarning">formatwarning() (in module warnings)</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatyear">formatyear() (calendar.HTMLCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.TextCalendar.formatyear">(calendar.TextCalendar method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar.formatyearpage">formatyearpage() (calendar.HTMLCalendar method)</a>
</li>
      <li><a href="library/fl.html#index-0">FORMS Library</a>
</li>
      <li><a href="library/turtle.html#turtle.forward">forward() (in module turtle)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.found_terminator">found_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.fp">fp (rfc822.Message attribute)</a>
</li>
      <li><a href="library/os.html#os.fpathconf">fpathconf() (in module os)</a>
</li>
      <li><a href="library/fpectl.html#module-fpectl">fpectl (module)</a>
</li>
      <li><a href="library/fpformat.html#module-fpformat">fpformat (module)</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction">Fraction (class in fractions)</a>
</li>
      <li><a href="library/fractions.html#module-fractions">fractions (module)</a>
</li>
      <li>
    frame

      <ul>
        <li><a href="reference/compound_stmts.html#index-23">execution</a>, <a href="reference/executionmodel.html#index-4">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-64">object</a>
</li>
      </ul></li>
      <li><a href="library/scrolledtext.html#ScrolledText.ScrolledText.frame">frame (ScrolledText.ScrolledText attribute)</a>
</li>
      <li><a href="library/types.html#types.FrameType">FrameType (in module types)</a>
</li>
      <li>
    FrameWork

      <ul>
        <li><a href="library/miniaeframe.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#module-FrameWork">FrameWork (module)</a>
</li>
      <li>
    free

      <ul>
        <li><a href="reference/executionmodel.html#index-7">variable</a>, <a href="reference/simple_stmts.html#index-20">[1]</a>
</li>
      </ul></li>
      <li><a href="c-api/memory.html#index-0">free()</a>
</li>
      <li><a href="c-api/import.html#index-5">freeze utility</a>
</li>
      <li><a href="library/fl.html#fl.form.freeze_form">freeze_form() (fl.form method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.freeze_support">freeze_support() (in module multiprocessing)</a>
</li>
      <li><a href="library/math.html#math.frexp">frexp() (in module math)</a>
</li>
      <li>
    from

      <ul>
        <li><a href="reference/simple_stmts.html#index-38">keyword</a>
</li>
        <li><a href="reference/executionmodel.html#index-9">statement</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._CData.from_address">from_address() (ctypes._CData method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_buffer">from_buffer() (ctypes._CData method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_buffer_copy">from_buffer_copy() (ctypes._CData method)</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction.from_decimal">from_decimal() (fractions.Fraction method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Decimal.from_float">from_float() (decimal.Decimal method)</a>

      <ul>
        <li><a href="library/fractions.html#fractions.Fraction.from_float">(fractions.Fraction method)</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.chain.from_iterable">from_iterable() (itertools.chain class method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes._CData.from_param">from_param() (ctypes._CData method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.from_splittable">from_splittable() (email.charset.Charset method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.frombuf">frombuf() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/popen2.html#popen2.Popen3.fromchild">fromchild (popen2.Popen3 attribute)</a>
</li>
      <li><a href="library/socket.html#socket.fromfd">fromfd() (in module socket)</a>

      <ul>
        <li><a href="library/select.html#select.epoll.fromfd">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.kqueue.fromfd">(select.kqueue method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromfile">fromfile() (array.array method)</a>
</li>
      <li><a href="library/stdtypes.html#float.fromhex">fromhex() (float method)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.fromkeys">fromkeys() (collections.Counter method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.fromkeys">(dict method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromlist">fromlist() (array.array method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.fromordinal">fromordinal() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.fromordinal">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromstring">fromstring() (array.array method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstring">(in module xml.etree.ElementTree)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.fromstringlist">fromstringlist() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.fromtarfile">fromtarfile() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.fromtimestamp">fromtimestamp() (datetime.date class method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.fromtimestamp">(datetime.datetime class method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.fromunicode">fromunicode() (array.array method)</a>
</li>
      <li><a href="library/datetime.html#datetime.tzinfo.fromutc">fromutc() (datetime.tzinfo method)</a>
</li>
      <li>
    frozenset

      <ul>
        <li><a href="c-api/set.html#index-0">object</a>, <a href="reference/datamodel.html#index-31">[1]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset">frozenset (built-in class)</a>
</li>
      <li><a href="library/os.html#os.fstat">fstat() (in module os)</a>
</li>
      <li><a href="library/os.html#os.fstatvfs">fstatvfs() (in module os)</a>
</li>
      <li><a href="library/math.html#math.fsum">fsum() (in module math)</a>
</li>
      <li><a href="library/os.html#os.fsync">fsync() (in module os)</a>
</li>
      <li><a href="library/urllib.html#index-10">FTP</a>

      <ul>
        <li><a href="library/ftplib.html#index-0">ftplib (standard module)</a>
</li>
        <li><a href="library/ftplib.html#index-0">protocol</a>, <a href="library/urllib.html#index-8">[1]</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP">FTP (class in ftplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FTPHandler.ftp_open">ftp_open() (urllib2.FTPHandler method)</a>
</li>
      <li><a href="library/urllib.html#index-3">ftp_proxy</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS">FTP_TLS (class in ftplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.FTPHandler">FTPHandler (class in urllib2)</a>
</li>
      <li><a href="library/ftplib.html#module-ftplib">ftplib (module)</a>
</li>
      <li><a href="library/ftplib.html#index-3">ftpmirror.py</a>
</li>
      <li><a href="library/os.html#os.ftruncate">ftruncate() (in module os)</a>
</li>
      <li><a href="library/queue.html#Queue.Full">Full</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.full">full() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.full">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/functools.html#functools.partial.func">func (functools.partial attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_closure (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_code (function attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-40">(function object attribute)</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-37">func_defaults (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_dict (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_doc (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_globals (function attribute)</a>
</li>
      <li><a href="reference/datamodel.html#index-37">func_name (function attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-funcattrs">funcattrs (2to3 fixer)</a>
</li>
      <li><a href="glossary.html#term-function"><strong>function</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-75">anonymous</a>
</li>
        <li><a href="reference/datamodel.html#index-35">argument</a>
</li>
        <li><a href="reference/datamodel.html#index-35">call</a>, <a href="reference/expressions.html#index-42">[1]</a>, <a href="reference/expressions.html#index-43">[2]</a>
</li>
        <li><a href="reference/expressions.html#index-42">call, user-defined</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">definition</a>, <a href="reference/simple_stmts.html#index-26">[1]</a>
</li>
        <li><a href="reference/expressions.html#index-22">generator</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">name</a>
</li>
        <li><a href="c-api/function.html#index-0">object</a>, <a href="reference/compound_stmts.html#index-18">[1]</a>, <a href="reference/datamodel.html#index-36">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-42">[4]</a>, <a href="reference/expressions.html#index-43">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-36">user-defined</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Function">Function (class in symtable)</a>
</li>
      <li><a href="library/new.html#new.function">function() (in module new)</a>
</li>
      <li><a href="library/unittest.html#unittest.FunctionTestCase">FunctionTestCase (class in unittest)</a>
</li>
      <li><a href="library/types.html#types.FunctionType">FunctionType (in module types)</a>
</li>
      <li><a href="library/functools.html#module-functools">functools (module)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.funny_files">funny_files (filecmp.dircmp attribute)</a>
</li>
      <li>
    future

      <ul>
        <li><a href="reference/simple_stmts.html#index-52">statement</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-future">future (2to3 fixer)</a>
</li>
      <li><a href="library/future_builtins.html#module-future_builtins">future_builtins (module)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.FutureWarning">FutureWarning</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\]hZc{{html/genindex-G.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-G.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; G</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/aifc.html#index-1">G.722</a>
</li>
      <li><a href="library/socket.html#socket.gaierror">gaierror</a>
</li>
      <li><a href="library/math.html#math.gamma">gamma() (in module math)</a>
</li>
      <li><a href="library/random.html#random.gammavariate">gammavariate() (in module random)</a>
</li>
      <li><a href="library/gc.html#gc.garbage">garbage (in module gc)</a>
</li>
      <li><a href="reference/datamodel.html#index-2">garbage collection</a>, <a href="glossary.html#term-garbage-collection"><strong>[1]</strong></a>
</li>
      <li><a href="library/curses.html#curses.textpad.Textbox.gather">gather() (curses.textpad.Textbox method)</a>
</li>
      <li><a href="library/random.html#random.gauss">gauss() (in module random)</a>
</li>
      <li><a href="library/gc.html#module-gc">gc (module)</a>
</li>
      <li><a href="library/fractions.html#fractions.gcd">gcd() (in module fractions)</a>
</li>
      <li>
    gdbm

      <ul>
        <li><a href="library/anydbm.html#index-0">module</a>, <a href="library/shelve.html#index-1">[1]</a>, <a href="reference/datamodel.html#index-34">[2]</a>
</li>
      </ul></li>
      <li><a href="library/gdbm.html#module-gdbm">gdbm (module)</a>
</li>
      <li><a href="library/operator.html#operator.ge">ge() (in module operator)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.gen_lib_options">gen_lib_options() (in module distutils.ccompiler)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.gen_preprocess_options">gen_preprocess_options() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/msilib.html#msilib.gen_uuid">gen_uuid() (in module msilib)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.generate_help">generate_help() (distutils.fancy_getopt.FancyGetopt method)</a>
</li>
      <li><a href="library/tokenize.html#tokenize.generate_tokens">generate_tokens() (in module tokenize)</a>
</li>
      <li><a href="glossary.html#index-3">generator</a>, <a href="glossary.html#term-generator"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-15">expression</a>
</li>
        <li><a href="reference/datamodel.html#index-43">function</a>, <a href="reference/expressions.html#index-22">[1]</a>, <a href="reference/simple_stmts.html#index-28">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-43">iterator</a>, <a href="reference/simple_stmts.html#index-28">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-62">object</a>, <a href="reference/expressions.html#index-15">[1]</a>, <a href="reference/expressions.html#index-24">[2]</a>
</li>
      </ul></li>
      <li><a href="library/email.generator.html#email.generator.Generator">Generator (class in email.generator)</a>
</li>
      <li><a href="glossary.html#index-4">generator expression</a>, <a href="glossary.html#term-generator-expression"><strong>[1]</strong></a>
</li>
      <li><a href="library/exceptions.html#exceptions.GeneratorExit">GeneratorExit</a>

      <ul>
        <li><a href="reference/expressions.html#index-26">exception</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.GeneratorType">GeneratorType (in module types)</a>
</li>
      <li>
    generic

      <ul>
        <li><a href="reference/datamodel.html#index-5">special attribute</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.NodeVisitor.generic_visit">generic_visit() (ast.NodeVisitor method)</a>
</li>
      <li><a href="library/pickletools.html#pickletools.genops">genops() (in module pickletools)</a>
</li>
      <li><a href="library/gensuitemodule.html#module-gensuitemodule">gensuitemodule (module)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser.get">get() (ConfigParser.ConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.get">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/queue.html#Queue.Queue.get">(Queue.Queue method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.get">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.get">(email.message.Message method)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.get">(in module webbrowser)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.get">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.get">(multiprocessing.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.get">(multiprocessing.multiprocessing.queues.SimpleQueue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.get">(multiprocessing.pool.AsyncResult method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.get">(ossaudiodev.oss_mixer_device method)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.Message.get">(rfc822.Message method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Combobox.get">(ttk.Combobox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_all">get_all() (email.message.Message method)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.headers.Headers.get_all">(wsgiref.headers.Headers method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.get_all_breaks">get_all_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIServer.get_app">get_app() (wsgiref.simple_server.WSGIServer method)</a>
</li>
      <li><a href="library/shutil.html#shutil.get_archive_formats">get_archive_formats() (in module shutil)</a>
</li>
      <li><a href="library/readline.html#readline.get_begidx">get_begidx() (in module readline)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.get_body_encoding">get_body_encoding() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_boundary">get_boundary() (email.message.Message method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_break">get_break() (bdb.Bdb method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_breaks">get_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.get_buffer">get_buffer() (xdrlib.Packer method)</a>

      <ul>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.get_buffer">(xdrlib.Unpacker method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.get_ca_certs">get_ca_certs() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.get_channel_binding">get_channel_binding() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_charset">get_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_charsets">get_charsets() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_children">get_children() (symtable.SymbolTable method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.get_children">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.get_close_matches">get_close_matches() (in module difflib)</a>
</li>
      <li><a href="library/imputil.html#imputil.BuiltinImporter.get_code">get_code() (imputil.BuiltinImporter method)</a>

      <ul>
        <li><a href="library/imputil.html#imputil.Importer.get_code">(imputil.Importer method)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_code">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.get_completer">get_completer() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_completer_delims">get_completer_delims() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_completion_type">get_completion_type() (in module readline)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_h_filename">get_config_h_filename() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_h_filename">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_var">get_config_var() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_var">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_config_vars">get_config_vars() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_config_vars">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_content_charset">get_content_charset() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_maintype">get_content_maintype() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_subtype">get_content_subtype() (email.message.Message method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_content_type">get_content_type() (email.message.Message method)</a>
</li>
      <li><a href="library/gc.html#gc.get_count">get_count() (in module gc)</a>
</li>
      <li><a href="library/readline.html#readline.get_current_history_length">get_current_history_length() (in module readline)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_data">get_data() (in module pkgutil)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.get_data">(urllib2.Request method)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_data">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_date">get_date() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/gc.html#gc.get_debug">get_debug() (in module gc)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.get_default">get_default() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.get_default_compiler">get_default_compiler() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/nis.html#nis.get_default_domain">get_default_domain() (in module nis)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_default_type">get_default_type() (email.message.Message method)</a>
</li>
      <li><a href="library/ssl.html#ssl.get_default_verify_paths">get_default_verify_paths() (in module ssl)</a>
</li>
      <li><a href="library/csv.html#csv.get_dialect">get_dialect() (in module csv)</a>
</li>
      <li><a href="library/fl.html#fl.get_directory">get_directory() (in module fl)</a>
</li>
      <li><a href="library/ast.html#ast.get_docstring">get_docstring() (in module ast)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.get_doctest">get_doctest() (doctest.DocTestParser method)</a>
</li>
      <li><a href="library/readline.html#readline.get_endidx">get_endidx() (in module readline)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.get_environ">get_environ() (wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.get_errno">get_errno() (in module ctypes)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.get_examples">get_examples() (doctest.DocTestParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.get_field">get_field() (string.Formatter method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.get_file">get_file() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.get_file">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.get_file">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.get_file">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.get_file">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.get_file">(mailbox.mbox method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.get_file_breaks">get_file_breaks() (bdb.Bdb method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_filename">get_filename() (email.message.Message method)</a>

      <ul>
        <li><a href="library/fl.html#fl.get_filename">(in module fl)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.get_filename">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_flags">get_flags() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.get_flags">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.get_flags">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Maildir.get_folder">get_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.get_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Function.get_frees">get_frees() (symtable.Function method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage.get_from">get_from() (mailbox.mboxMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.get_from">(mailbox.MMDFMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.Request.get_full_url">get_full_url() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_globals">get_globals() (symtable.Function method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_grouped_opcodes">get_grouped_opcodes() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_header">get_header() (urllib2.Request method)</a>
</li>
      <li><a href="library/readline.html#readline.get_history_item">get_history_item() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.get_history_length">get_history_length() (in module readline)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_host">get_host() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_id">get_id() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/thread.html#thread.get_ident">get_ident() (in module thread)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_identifiers">get_identifiers() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_importer">get_importer() (in module pkgutil)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_info">get_info() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/dis.html#opcode-GET_ITER">GET_ITER (opcode)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.get_labels">get_labels() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.BabylMessage.get_labels">(mailbox.BabylMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.get_last_error">get_last_error() (in module ctypes)</a>
</li>
      <li><a href="library/readline.html#readline.get_line_buffer">get_line_buffer() (in module readline)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_lineno">get_lineno() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.get_loader">get_loader() (in module pkgutil)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_locals">get_locals() (symtable.Function method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.get_logger">get_logger() (in module multiprocessing)</a>
</li>
      <li><a href="library/imp.html#imp.get_magic">get_magic() (in module imp)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_makefile_filename">get_makefile_filename() (in module distutils.sysconfig)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_makefile_filename">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_matching_blocks">get_matching_blocks() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Mailbox.get_message">get_message() (mailbox.Mailbox method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_method">get_method() (urllib2.Request method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Class.get_methods">get_methods() (symtable.Class method)</a>
</li>
      <li><a href="library/fl.html#fl.get_mouse">get_mouse() (in module fl)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.get_name">get_name() (symtable.Symbol method)</a>

      <ul>
        <li><a href="library/symtable.html#symtable.SymbolTable.get_name">(symtable.SymbolTable method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.get_namespace">get_namespace() (symtable.Symbol method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.get_namespaces">get_namespaces() (symtable.Symbol method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.get_nonstandard_attr">get_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.get_nowait">get_nowait() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.get_nowait">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/gc.html#gc.get_objects">get_objects() (in module gc)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.get_opcodes">get_opcodes() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_option">get_option() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_option_group">get_option_group() (optparse.OptionParser method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.get_option_order">get_option_order() (distutils.fancy_getopt.FancyGetopt method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_origin_req_host">get_origin_req_host() (urllib2.Request method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.get_osfhandle">get_osfhandle() (in module msvcrt)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.get_output_charset">get_output_charset() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_param">get_param() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Function.get_parameters">get_parameters() (symtable.Function method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_params">get_params() (email.message.Message method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_path">get_path() (in module sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_path_names">get_path_names() (in module sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_paths">get_paths() (in module sysconfig)</a>
</li>
      <li><a href="library/fl.html#fl.get_pattern">get_pattern() (in module fl)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.get_payload">get_payload() (email.message.Message method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.get_platform">get_platform() (in module distutils.util)</a>

      <ul>
        <li><a href="library/sysconfig.html#sysconfig.get_platform">(in module sysconfig)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.get_poly">get_poly() (in module turtle)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Unpacker.get_position">get_position() (xdrlib.Unpacker method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_python_inc">get_python_inc() (in module distutils.sysconfig)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.get_python_lib">get_python_lib() (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_python_version">get_python_version() (in module sysconfig)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.get_recsrc">get_recsrc() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/gc.html#gc.get_referents">get_referents() (in module gc)</a>
</li>
      <li><a href="library/gc.html#gc.get_referrers">get_referrers() (in module gc)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.get_request">get_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/fl.html#fl.get_rgbmode">get_rgbmode() (in module fl)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_scheme">get_scheme() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.get_scheme_names">get_scheme_names() (in module sysconfig)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.get_selector">get_selector() (urllib2.Request method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH.get_sequences">get_sequences() (mailbox.MH method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MHMessage.get_sequences">(mailbox.MHMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.get_server">get_server() (multiprocessing.managers.BaseManager method)</a>
</li>
      <li><a href="library/ssl.html#ssl.get_server_certificate">get_server_certificate() (in module ssl)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.get_socket">get_socket() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.get_source">get_source() (zipimport.zipimporter method)</a>
</li>
      <li><a href="distutils/builtdist.html#get_special_folder_path">get_special_folder_path() (built-in function)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.get_stack">get_stack() (bdb.Bdb method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.get_starttag_text">get_starttag_text() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.get_starttag_text">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_stderr">get_stderr() (wsgiref.handlers.BaseHandler method)</a>

      <ul>
        <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.get_stderr">(wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.get_stdin">get_stdin() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Mailbox.get_string">get_string() (mailbox.Mailbox method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.get_subdir">get_subdir() (mailbox.MaildirMessage method)</a>
</li>
      <li><a href="library/imp.html#imp.get_suffixes">get_suffixes() (in module imp)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_symbols">get_symbols() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.get_terminator">get_terminator() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/gc.html#gc.get_threshold">get_threshold() (in module gc)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.get_token">get_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.get_type">get_type() (symtable.SymbolTable method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.get_type">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/email.message.html#email.message.Message.get_unixfrom">get_unixfrom() (email.message.Message method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_usage">get_usage() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/string.html#string.Formatter.get_value">get_value() (string.Formatter method)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser.get_version">get_version() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.get_visible">get_visible() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.getabouttext">getabouttext() (FrameWork.Application method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getacl">getacl() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getaddr">getaddr() (rfc822.Message method)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.getaddresses">getaddresses() (in module email.utils)</a>
</li>
      <li><a href="library/socket.html#socket.getaddrinfo">getaddrinfo() (in module socket)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getaddrlist">getaddrlist() (rfc822.Message method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getallmatchingheaders">getallmatchingheaders() (rfc822.Message method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getannotation">getannotation() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getargspec">getargspec() (in module inspect)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.GetArgv">GetArgv() (in module EasyDialogs)</a>
</li>
      <li><a href="library/inspect.html#inspect.getargvalues">getargvalues() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.getatime">getatime() (in module os.path)</a>
</li>
      <li><a href="library/functions.html#getattr">getattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttribute">getAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNode">getAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNodeNS">getAttributeNodeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.getAttributeNS">getAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.GetBase">GetBase() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/curses.html#curses.window.getbegyx">getbegyx() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.getbkgd">getbkgd() (curses.window method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getboolean">getboolean() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getByteStream">getByteStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getcallargs">getcallargs() (in module inspect)</a>
</li>
      <li><a href="library/turtle.html#turtle.getcanvas">getcanvas() (in module turtle)</a>
</li>
      <li><a href="library/mailcap.html#mailcap.getcaps">getcaps() (in module mailcap)</a>
</li>
      <li><a href="library/curses.html#curses.window.getch">getch() (curses.window method)</a>

      <ul>
        <li><a href="library/msvcrt.html#msvcrt.getch">(in module msvcrt)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getCharacterStream">getCharacterStream() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getche">getche() (in module msvcrt)</a>
</li>
      <li><a href="library/sys.html#sys.getcheckinterval">getcheckinterval() (in module sys)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.getChild">getChild() (logging.Logger method)</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node.getChildNodes">getChildNodes() (compiler.ast.Node method)</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node.getChildren">getChildren() (compiler.ast.Node method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getchildren">getchildren() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getclasstree">getclasstree() (in module inspect)</a>
</li>
      <li><a href="library/colorpicker.html#ColorPicker.GetColor">GetColor() (in module ColorPicker)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.GetColumnInfo">GetColumnInfo() (msilib.View method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getColumnNumber">getColumnNumber() (xml.sax.xmlreader.Locator method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getcomments">getcomments() (in module inspect)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getcompname">getcompname() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getcompname">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getcompname">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getcomptype">getcomptype() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getcomptype">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getcomptype">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getContentHandler">getContentHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/decimal.html#decimal.getcontext">getcontext() (in module decimal)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.getcontext">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.GetCreatorAndType">GetCreatorAndType() (in module MacOS)</a>
</li>
      <li><a href="library/os.path.html#os.path.getctime">getctime() (in module os.path)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getcurrent">getcurrent() (mhlib.Folder method)</a>
</li>
      <li><a href="library/os.html#os.getcwd">getcwd() (in module os)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-getcwdu">getcwdu (2to3 fixer)</a>
</li>
      <li><a href="library/os.html#os.getcwdu">getcwdu() (in module os)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getdate">getdate() (rfc822.Message method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getdate_tz">getdate_tz() (rfc822.Message method)</a>
</li>
      <li><a href="library/codecs.html#codecs.getdecoder">getdecoder() (in module codecs)</a>
</li>
      <li><a href="library/sys.html#sys.getdefaultencoding">getdefaultencoding() (in module sys)</a>
</li>
      <li><a href="library/locale.html#locale.getdefaultlocale">getdefaultlocale() (in module locale)</a>
</li>
      <li><a href="library/socket.html#socket.getdefaulttimeout">getdefaulttimeout() (in module socket)</a>
</li>
      <li><a href="library/sys.html#sys.getdlopenflags">getdlopenflags() (in module sys)</a>
</li>
      <li><a href="library/inspect.html#inspect.getdoc">getdoc() (in module inspect)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.getDOMImplementation">getDOMImplementation() (in module xml.dom)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getDTDHandler">getDTDHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.getEffectiveLevel">getEffectiveLevel() (logging.Logger method)</a>
</li>
      <li><a href="library/os.html#os.getegid">getegid() (in module os)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Document.getElementsByTagName">getElementsByTagName() (xml.dom.Document method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Element.getElementsByTagName">(xml.dom.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Document.getElementsByTagNameNS">getElementsByTagNameNS() (xml.dom.Document method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Element.getElementsByTagNameNS">(xml.dom.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.getencoder">getencoder() (in module codecs)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getencoding">getencoding() (mimetools.Message method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getEncoding">getEncoding() (xml.sax.xmlreader.InputSource method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getEntityResolver">getEntityResolver() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/os.html#os.getenv">getenv() (in module os)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getErrorHandler">getErrorHandler() (xml.sax.xmlreader.XMLReader method)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/macos.html#MacOS.GetErrorString">GetErrorString() (in module MacOS)</a>
</li>
      <li><a href="library/os.html#os.geteuid">geteuid() (in module os)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.getEvent">getEvent() (xml.dom.pulldom.DOMEventStream method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getEventCategory">getEventCategory() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getEventType">getEventType() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.SAXException.getException">getException() (xml.sax.SAXException method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getFeature">getFeature() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetFieldCount">GetFieldCount() (msilib.Record method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getfile">getfile() (in module inspect)</a>
</li>
      <li><a href="library/sys.html#sys.getfilesystemencoding">getfilesystemencoding() (in module sys)</a>
</li>
      <li><a href="library/cgi.html#cgi.FieldStorage.getfirst">getfirst() (cgi.FieldStorage method)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getfirstmatchingheader">getfirstmatchingheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getfloat">getfloat() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.getfmts">getfmts() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/socket.html#socket.getfqdn">getfqdn() (in module socket)</a>
</li>
      <li><a href="library/inspect.html#inspect.getframeinfo">getframeinfo() (in module inspect)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getframerate">getframerate() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getframerate">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getframerate">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.getfullname">getfullname() (mhlib.Folder method)</a>
</li>
      <li><a href="library/os.html#os.getgid">getgid() (in module os)</a>
</li>
      <li><a href="library/grp.html#grp.getgrall">getgrall() (in module grp)</a>
</li>
      <li><a href="library/grp.html#grp.getgrgid">getgrgid() (in module grp)</a>
</li>
      <li><a href="library/grp.html#grp.getgrnam">getgrnam() (in module grp)</a>
</li>
      <li><a href="library/os.html#os.getgroups">getgroups() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.getheader">getheader() (httplib.HTTPResponse method)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.Message.getheader">(rfc822.Message method)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.getheaders">getheaders() (httplib.HTTPResponse method)</a>
</li>
      <li><a href="library/os.html#index-9">gethostbyaddr() (in module socket)</a>, <a href="library/socket.html#socket.gethostbyaddr">[1]</a>
</li>
      <li><a href="library/socket.html#socket.gethostbyname">gethostbyname() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.gethostbyname_ex">gethostbyname_ex() (in module socket)</a>
</li>
      <li><a href="library/os.html#index-9">gethostname() (in module socket)</a>, <a href="library/socket.html#socket.gethostname">[1]</a>
</li>
      <li><a href="library/codecs.html#codecs.getincrementaldecoder">getincrementaldecoder() (in module codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.getincrementalencoder">getincrementalencoder() (in module codecs)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.getinfo">getinfo() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getinnerframes">getinnerframes() (in module inspect)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.GetInputContext">GetInputContext() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.getint">getint() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetInteger">GetInteger() (msilib.Record method)</a>
</li>
      <li><a href="library/operator.html#operator.getitem">getitem() (in module operator)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator">getiterator() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.getiterator">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/signal.html#signal.getitimer">getitimer() (in module signal)</a>
</li>
      <li><a href="library/curses.html#curses.window.getkey">getkey() (curses.window method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getlast">getlast() (mhlib.Folder method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.GetLastError">GetLastError() (in module ctypes)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getLength">getLength() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/logging.html#logging.getLevelName">getLevelName() (in module logging)</a>
</li>
      <li><a href="library/linecache.html#linecache.getline">getline() (in module linecache)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getLineNumber">getLineNumber() (xml.sax.xmlreader.Locator method)</a>
</li>
      <li><a href="library/cgi.html#cgi.FieldStorage.getlist">getlist() (cgi.FieldStorage method)</a>
</li>
      <li><a href="library/os.html#os.getloadavg">getloadavg() (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.getlocale">getlocale() (in module locale)</a>
</li>
      <li><a href="library/logging.html#logging.getLogger">getLogger() (in module logging)</a>
</li>
      <li><a href="library/logging.html#logging.getLoggerClass">getLoggerClass() (in module logging)</a>
</li>
      <li><a href="library/os.html#os.getlogin">getlogin() (in module os)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getmaintype">getmaintype() (mimetools.Message method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getmark">getmark() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getmark">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getmark">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getmarkers">getmarkers() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getmarkers">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getmarkers">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.getmaxyx">getmaxyx() (curses.window method)</a>
</li>
      <li><a href="library/fl.html#fl.getmcolor">getmcolor() (in module fl)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.getmember">getmember() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmembers">getmembers() (in module inspect)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarFile.getmembers">(tarfile.TarFile method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.LogRecord.getMessage">getMessage() (logging.LogRecord method)</a>

      <ul>
        <li><a href="library/xml.sax.html#xml.sax.SAXException.getMessage">(xml.sax.SAXException method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.getmessagefilename">getmessagefilename() (mhlib.Folder method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler.getMessageID">getMessageID() (logging.handlers.NTEventLogHandler method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmodule">getmodule() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmoduleinfo">getmoduleinfo() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmodulename">getmodulename() (in module inspect)</a>
</li>
      <li><a href="library/curses.html#curses.getmouse">getmouse() (in module curses)</a>
</li>
      <li><a href="library/inspect.html#inspect.getmro">getmro() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.getmtime">getmtime() (in module os.path)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.getname">getname() (chunk.Chunk method)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.getName">getName() (threading.Thread method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getNameByQName">getNameByQName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/socket.html#socket.getnameinfo">getnameinfo() (in module socket)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.getnames">getnames() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getNames">getNames() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getnchannels">getnchannels() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getnchannels">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getnchannels">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.getnframes">getnframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getnframes">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getnframes">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#index-1">getnode</a>
</li>
      <li><a href="library/uuid.html#uuid.getnode">getnode() (in module uuid)</a>
</li>
      <li><a href="library/getopt.html#module-getopt">getopt (module)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.fancy_getopt.FancyGetopt.getopt">getopt() (distutils.fancy_getopt.FancyGetopt method)</a>

      <ul>
        <li><a href="library/getopt.html#getopt.getopt">(in module getopt)</a>
</li>
      </ul></li>
      <li><a href="library/getopt.html#getopt.GetoptError">GetoptError</a>
</li>
      <li><a href="library/inspect.html#inspect.getouterframes">getouterframes() (in module inspect)</a>
</li>
      <li><a href="library/commands.html#commands.getoutput">getoutput() (in module commands)</a>
</li>
      <li><a href="library/resource.html#resource.getpagesize">getpagesize() (in module resource)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getparam">getparam() (mimetools.Message method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getparams">getparams() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/al.html#al.getparams">(in module al)</a>
</li>
        <li><a href="library/sunau.html#sunau.AU_read.getparams">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getparams">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.getparyx">getparyx() (curses.window method)</a>
</li>
      <li><a href="library/getpass.html#module-getpass">getpass (module)</a>
</li>
      <li><a href="library/getpass.html#getpass.getpass">getpass() (in module getpass)</a>
</li>
      <li><a href="library/getpass.html#getpass.GetPassWarning">GetPassWarning</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.getpath">getpath() (mhlib.MH method)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLSocket.getpeercert">getpeercert() (ssl.SSLSocket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getpeername">getpeername() (socket.socket method)</a>
</li>
      <li><a href="library/turtle.html#turtle.getpen">getpen() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.getpgid">getpgid() (in module os)</a>
</li>
      <li><a href="library/os.html#os.getpgrp">getpgrp() (in module os)</a>
</li>
      <li><a href="library/os.html#os.getpid">getpid() (in module os)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getplist">getplist() (mimetools.Message method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.getpos">getpos() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/os.html#os.getppid">getppid() (in module os)</a>
</li>
      <li><a href="library/locale.html#locale.getpreferredencoding">getpreferredencoding() (in module locale)</a>
</li>
      <li><a href="library/sys.html#sys.getprofile">getprofile() (in module sys)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH.getprofile">(mhlib.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.GetProperty">GetProperty() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.getProperty">getProperty() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.GetPropertyCount">GetPropertyCount() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/socket.html#socket.getprotobyname">getprotobyname() (in module socket)</a>
</li>
      <li><a href="library/urllib.html#urllib.getproxies">getproxies() (in module urllib)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getPublicId">getPublicId() (xml.sax.xmlreader.InputSource method)</a>

      <ul>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getPublicId">(xml.sax.xmlreader.Locator method)</a>
</li>
      </ul></li>
      <li><a href="library/pwd.html#pwd.getpwall">getpwall() (in module pwd)</a>
</li>
      <li><a href="library/pwd.html#pwd.getpwnam">getpwnam() (in module pwd)</a>
</li>
      <li><a href="library/pwd.html#pwd.getpwuid">getpwuid() (in module pwd)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getQNameByName">getQNameByName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getQNames">getQNames() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getquota">getquota() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.getquotaroot">getquotaroot() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/random.html#random.getrandbits">getrandbits() (in module random)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.getrawheader">getrawheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/codecs.html#codecs.getreader">getreader() (in module codecs)</a>
</li>
      <li><a href="library/sys.html#sys.getrecursionlimit">getrecursionlimit() (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.getrefcount">getrefcount() (in module sys)</a>
</li>
      <li><a href="library/os.html#os.getresgid">getresgid() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.getresponse">getresponse() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/os.html#os.getresuid">getresuid() (in module os)</a>
</li>
      <li><a href="library/resource.html#resource.getrlimit">getrlimit() (in module resource)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.getroot">getroot() (xml.etree.ElementTree.ElementTree method)</a>
</li>
      <li><a href="library/resource.html#resource.getrusage">getrusage() (in module resource)</a>
</li>
      <li><a href="library/audioop.html#audioop.getsample">getsample() (in module audioop)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.getsampwidth">getsampwidth() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.getsampwidth">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.getsampwidth">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.getscreen">getscreen() (in module turtle)</a>
</li>
      <li><a href="library/framework.html#FrameWork.ScrolledWindow.getscrollbarvalues">getscrollbarvalues() (FrameWork.ScrolledWindow method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getsequences">getsequences() (mhlib.Folder method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.getsequencesfilename">getsequencesfilename() (mhlib.Folder method)</a>
</li>
      <li><a href="library/socket.html#socket.getservbyname">getservbyname() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.getservbyport">getservbyport() (in module socket)</a>
</li>
      <li><a href="library/types.html#types.GetSetDescriptorType">GetSetDescriptorType (in module types)</a>
</li>
      <li><a href="library/turtle.html#turtle.getshapes">getshapes() (in module turtle)</a>
</li>
      <li><a href="library/os.html#os.getsid">getsid() (in module os)</a>
</li>
      <li><a href="library/signal.html#signal.getsignal">getsignal() (in module signal)</a>
</li>
      <li><a href="library/site.html#site.getsitepackages">getsitepackages() (in module site)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.getsize">getsize() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/os.path.html#os.path.getsize">(in module os.path)</a>
</li>
      </ul></li>
      <li><a href="library/sys.html#sys.getsizeof">getsizeof() (in module sys)</a>
</li>
      <li><a href="library/imgfile.html#imgfile.getsizes">getsizes() (in module imgfile)</a>
</li>
      <li><a href="library/operator.html#operator.getslice">getslice() (in module operator)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getsockname">getsockname() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.getsockopt">getsockopt() (socket.socket method)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsource">getsource() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsourcefile">getsourcefile() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.getsourcelines">getsourcelines() (in module inspect)</a>
</li>
      <li><a href="library/spwd.html#spwd.getspall">getspall() (in module spwd)</a>
</li>
      <li><a href="library/spwd.html#spwd.getspnam">getspnam() (in module spwd)</a>
</li>
      <li><a href="library/random.html#random.getstate">getstate() (in module random)</a>
</li>
      <li><a href="library/commands.html#commands.getstatus">getstatus() (in module commands)</a>
</li>
      <li><a href="library/commands.html#commands.getstatusoutput">getstatusoutput() (in module commands)</a>
</li>
      <li><a href="library/curses.html#curses.window.getstr">getstr() (curses.window method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Record.GetString">GetString() (msilib.Record method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SMTPHandler.getSubject">getSubject() (logging.handlers.SMTPHandler method)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.getsubtype">getsubtype() (mimetools.Message method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.GetSummaryInformation">GetSummaryInformation() (msilib.Database method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource.getSystemId">getSystemId() (xml.sax.xmlreader.InputSource method)</a>

      <ul>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator.getSystemId">(xml.sax.xmlreader.Locator method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.getsyx">getsyx() (in module curses)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.gettarinfo">gettarinfo() (tarfile.TarFile method)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.gettempdir">gettempdir() (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.gettempprefix">gettempprefix() (in module tempfile)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.getTestCaseNames">getTestCaseNames() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/gettext.html#module-gettext">gettext (module)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.gettext">gettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.gettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.gettext">(in module gettext)</a>
</li>
        <li><a href="library/locale.html#locale.gettext">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.GetTicks">GetTicks() (in module MacOS)</a>
</li>
      <li><a href="library/socket.html#socket.socket.gettimeout">gettimeout() (socket.socket method)</a>
</li>
      <li><a href="library/sys.html#sys.gettrace">gettrace() (in module sys)</a>
</li>
      <li><a href="library/turtle.html#turtle.getturtle">getturtle() (in module turtle)</a>
</li>
      <li><a href="library/mimetools.html#mimetools.Message.gettype">gettype() (mimetools.Message method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getType">getType() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/os.html#os.getuid">getuid() (in module os)</a>
</li>
      <li><a href="library/urlparse.html#urlparse.ParseResult.geturl">geturl() (urlparse.ParseResult method)</a>
</li>
      <li><a href="library/getpass.html#getpass.getuser">getuser() (in module getpass)</a>
</li>
      <li><a href="library/site.html#site.getuserbase">getuserbase() (in module site)</a>
</li>
      <li><a href="library/site.html#site.getusersitepackages">getusersitepackages() (in module site)</a>
</li>
      <li><a href="library/io.html#io.BytesIO.getvalue">getvalue() (io.BytesIO method)</a>

      <ul>
        <li><a href="library/stringio.html#StringIO.StringIO.getvalue">(StringIO.StringIO method)</a>
</li>
        <li><a href="library/io.html#io.StringIO.getvalue">(io.StringIO method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Attributes.getValue">getValue() (xml.sax.xmlreader.Attributes method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.AttributesNS.getValueByQName">getValueByQName() (xml.sax.xmlreader.AttributesNS method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getwch">getwch() (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.getwche">getwche() (in module msvcrt)</a>
</li>
      <li><a href="library/weakref.html#weakref.getweakrefcount">getweakrefcount() (in module weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.getweakrefs">getweakrefs() (in module weakref)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.getwelcome">getwelcome() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.getwelcome">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.getwelcome">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.getwin">getwin() (in module curses)</a>
</li>
      <li><a href="library/sys.html#sys.getwindowsversion">getwindowsversion() (in module sys)</a>
</li>
      <li><a href="library/codecs.html#codecs.getwriter">getwriter() (in module codecs)</a>
</li>
      <li><a href="library/curses.html#curses.window.getyx">getyx() (curses.window method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.gid">gid (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="c-api/init.html#index-13">GIL</a>, <a href="glossary.html#term-gil"><strong>[1]</strong></a>
</li>
      <li><a href="library/gl.html#module-GL">GL (module)</a>
</li>
      <li><a href="library/gl.html#module-gl">gl (module)</a>
</li>
      <li>
    glob

      <ul>
        <li><a href="library/fnmatch.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/glob.html#module-glob">glob (module)</a>
</li>
      <li><a href="library/glob.html#glob.glob">glob() (in module glob)</a>

      <ul>
        <li><a href="library/msilib.html#msilib.Directory.glob">(msilib.Directory method)</a>
</li>
      </ul></li>
      <li>
    global

      <ul>
        <li><a href="reference/simple_stmts.html#index-54">name binding</a>
</li>
        <li><a href="reference/datamodel.html#index-37">namespace</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">statement</a>, <a href="reference/simple_stmts.html#index-54">[1]</a>, <a href="reference/simple_stmts.html#index-7">[2]</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-13">global interpreter lock</a>, <a href="glossary.html#term-global-interpreter-lock"><strong>[1]</strong></a>
</li>
      <li>
    globals

      <ul>
        <li><a href="reference/simple_stmts.html#index-58">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#globals">globals() (built-in function)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTest.globs">globs (doctest.DocTest attribute)</a>
</li>
      <li><a href="library/time.html#time.gmtime">gmtime() (in module time)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.gname">gname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/gettext.html#index-9">GNOME</a>
</li>
      <li><a href="library/tarfile.html#tarfile.GNU_FORMAT">GNU_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/getopt.html#getopt.gnu_getopt">gnu_getopt() (in module getopt)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestFailure.got">got (doctest.DocTestFailure attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.goto">goto() (in module turtle)</a>
</li>
      <li><a href="reference/introduction.html#index-0">grammar</a>
</li>
      <li><a href="library/tk.html#index-0">Graphical User Interface</a>
</li>
      <li><a href="library/token.html#token.GREATER">GREATER (in module token)</a>
</li>
      <li><a href="library/token.html#token.GREATEREQUAL">GREATEREQUAL (in module token)</a>
</li>
      <li><a href="library/time.html#index-5">Greenwich Mean Time</a>
</li>
      <li><a href="library/imageop.html#imageop.grey22grey">grey22grey() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2grey2">grey2grey2() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2grey4">grey2grey4() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey2mono">grey2mono() (in module imageop)</a>
</li>
      <li><a href="library/imageop.html#imageop.grey42grey">grey42grey() (in module imageop)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.group">group() (nntplib.NNTP method)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.group">(re.MatchObject method)</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.groupby">groupby() (in module itertools)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.groupdict">groupdict() (re.MatchObject method)</a>
</li>
      <li><a href="library/re.html#re.RegexObject.groupindex">groupindex (re.RegexObject attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">grouping</a>
</li>
      <li><a href="library/re.html#re.RegexObject.groups">groups (re.RegexObject attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.groups">groups() (re.MatchObject method)</a>
</li>
      <li><a href="library/grp.html#module-grp">grp (module)</a>
</li>
      <li><a href="library/operator.html#operator.gt">gt() (in module operator)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.guess_all_extensions">guess_all_extensions() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_all_extensions">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.guess_extension">guess_extension() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_extension">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/wsgiref.html#wsgiref.util.guess_scheme">guess_scheme() (in module wsgiref.util)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.guess_type">guess_type() (in module mimetypes)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.guess_type">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/tk.html#index-0">GUI</a>
</li>
      <li><a href="library/gzip.html#module-gzip">gzip (module)</a>
</li>
      <li><a href="library/gzip.html#gzip.GzipFile">GzipFile (class in gzip)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\��V_�|�|html/genindex-H.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-H.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; H</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/curses.html#curses.halfdelay">halfdelay() (in module curses)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">handle an exception</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.handle">handle() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseRequestHandler.handle">(SocketServer.BaseRequestHandler method)</a>
</li>
        <li><a href="library/logging.html#logging.Handler.handle">(logging.Handler method)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.handle">(logging.Logger method)</a>
</li>
        <li><a href="library/logging.handlers.html#logging.NullHandler.handle">(logging.NullHandler method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.simple_server.WSGIRequestHandler.handle">(wsgiref.simple_server.WSGIRequestHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_accept">handle_accept() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_charref">handle_charref() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_charref">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_close">handle_close() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_comment">handle_comment() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_comment">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_connect">handle_connect() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_data">handle_data() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_data">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_decl">handle_decl() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_decl">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_endtag">handle_endtag() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_endtag">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_entityref">handle_entityref() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_entityref">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_error">handle_error() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_error">(SocketServer.BaseServer method)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_expt">handle_expt() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.handle_image">handle_image() (htmllib.HTMLParser method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request">handle_one_request() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_pi">handle_pi() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_read">handle_read() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.handle_request">handle_request() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_request">(SocketServer.BaseServer method)</a>
</li>
      </ul></li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_startendtag">handle_startendtag() (HTMLParser.HTMLParser method)</a>
</li>
      <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.handle_starttag">handle_starttag() (HTMLParser.HTMLParser method)</a>

      <ul>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.handle_starttag">(sgmllib.SGMLParser method)</a>
</li>
      </ul></li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.handle_timeout">handle_timeout() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.handle_write">handle_write() (asyncore.dispatcher method)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.handleError">handleError() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.handleError">(logging.handlers.SocketHandler method)</a>
</li>
      </ul></li>
      <li>
    handler

      <ul>
        <li><a href="reference/datamodel.html#index-67">exception</a>
</li>
      </ul></li>
      <li><a href="library/cgitb.html#cgitb.handler">handler() (in module cgitb)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_ALPN">HAS_ALPN (in module ssl)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_children">has_children() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/curses.html#curses.has_colors">has_colors() (in module curses)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.has_data">has_data() (urllib2.Request method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_ECDH">HAS_ECDH (in module ssl)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_exec">has_exec() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.has_extn">has_extn() (smtplib.SMTP method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.has_function">has_function() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/csv.html#csv.Sniffer.has_header">has_header() (csv.Sniffer method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.Request.has_header">(urllib2.Request method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.has_ic">has_ic() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.has_il">has_il() (in module curses)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.has_import_star">has_import_star() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/socket.html#socket.has_ipv6">has_ipv6 (in module socket)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-has_key">has_key (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.has_key">has_key() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.has_key">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.has_key">(email.message.Message method)</a>
</li>
        <li><a href="library/curses.html#curses.has_key">(in module curses)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.has_key">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.has_nonstandard_attr">has_nonstandard_attr() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_NPN">HAS_NPN (in module ssl)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.has_option">has_option() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.has_option">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.has_section">has_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_SNI">HAS_SNI (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.HAS_TLSv1_3">HAS_TLSv1_3 (in module ssl)</a>
</li>
      <li><a href="library/functions.html#hasattr">hasattr() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.hasAttribute">hasAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.hasAttributeNS">hasAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.hasAttributes">hasAttributes() (xml.dom.Node method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.hasChildNodes">hasChildNodes() (xml.dom.Node method)</a>
</li>
      <li><a href="library/dis.html#dis.hascompare">hascompare (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasconst">hasconst (in module dis)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DOMImplementation.hasFeature">hasFeature() (xml.dom.DOMImplementation method)</a>
</li>
      <li><a href="library/dis.html#dis.hasfree">hasfree (in module dis)</a>
</li>
      <li>
    hash

      <ul>
        <li><a href="c-api/object.html#index-9">built-in function</a>, <a href="c-api/typeobj.html#index-2">[1]</a>, <a href="reference/datamodel.html#index-81">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-3">hash character</a>
</li>
      <li><a href="library/functions.html#hash">hash() (built-in function)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.block_size">hash.block_size (in module hashlib)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.digest_size">hash.digest_size (in module hashlib)</a>
</li>
      <li><a href="reference/expressions.html#index-17">hashable</a>, <a href="glossary.html#term-hashable"><strong>[1]</strong></a>
</li>
      <li><a href="library/collections.html#collections.Hashable">Hashable (class in collections)</a>
</li>
      <li><a href="library/hashlib.html#module-hashlib">hashlib (module)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hashlib.algorithms">hashlib.algorithms (in module hashlib)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.hashopen">hashopen() (in module bsddb)</a>
</li>
      <li><a href="library/dis.html#dis.hasjabs">hasjabs (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasjrel">hasjrel (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.haslocal">haslocal (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.hasname">hasname (in module dis)</a>
</li>
      <li><a href="library/dis.html#opcode-HAVE_ARGUMENT">HAVE_ARGUMENT (opcode)</a>
</li>
      <li><a href="library/test.html#test.support.have_unicode">have_unicode (in module test.support)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.head">head() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/email.header.html#email.header.Header">Header (class in email.header)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.header_encode">header_encode() (email.charset.Charset method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.header_encoding">header_encoding (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.header_items">header_items() (urllib2.Request method)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.header_offset">header_offset (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.HeaderError">HeaderError</a>
</li>
      <li><a href="library/email.errors.html#email.errors.HeaderParseError">HeaderParseError</a>
</li>
      <li>
    headers

      <ul>
        <li><a href="library/cgi.html#index-0">MIME</a>, <a href="library/mimetypes.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.headers">headers (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.headers.Headers">Headers (class in wsgiref.headers)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.headers">headers (rfc822.Message attribute)</a>

      <ul>
        <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError.headers">(xmlrpclib.ProtocolError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.heading">heading() (in module turtle)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.heading">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/heapq.html#heapq.heapify">heapify() (in module heapq)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.heapmin">heapmin() (in module msvcrt)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappop">heappop() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappush">heappush() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#heapq.heappushpop">heappushpop() (in module heapq)</a>
</li>
      <li><a href="library/heapq.html#module-heapq">heapq (module)</a>
</li>
      <li><a href="library/heapq.html#heapq.heapreplace">heapreplace() (in module heapq)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.SMTP.helo">helo() (smtplib.SMTP method)</a>
</li>
      <li>
    help

      <ul>
        <li><a href="tutorial/stdlib.html#index-0">built-in function</a>
</li>
        <li><a href="library/pydoc.html#index-0">online</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.help">help (optparse.Option attribute)</a>
</li>
      <li><a href="library/functions.html#help">help() (built-in function)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.help">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.herror">herror</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    hex

      <ul>
        <li><a href="reference/datamodel.html#index-95">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/uuid.html#uuid.UUID.hex">hex (uuid.UUID attribute)</a>
</li>
      <li><a href="library/functions.html#hex">hex() (built-in function)</a>

      <ul>
        <li><a href="library/stdtypes.html#float.hex">(float method)</a>
</li>
        <li><a href="library/future_builtins.html#future_builtins.hex">(in module future_builtins)</a>
</li>
      </ul></li>
      <li>
    hexadecimal

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">hexadecimal literal</a>
</li>
      <li><a href="library/binhex.html#binhex.hexbin">hexbin() (in module binhex)</a>
</li>
      <li><a href="library/hashlib.html#hashlib.hash.hexdigest">hexdigest() (hashlib.hash method)</a>

      <ul>
        <li><a href="library/hmac.html#hmac.HMAC.hexdigest">(hmac.HMAC method)</a>
</li>
        <li><a href="library/md5.html#md5.md5.hexdigest">(md5.md5 method)</a>
</li>
        <li><a href="library/sha.html#sha.sha.hexdigest">(sha.sha method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.hexdigits">hexdigits (in module string)</a>
</li>
      <li><a href="library/binascii.html#binascii.hexlify">hexlify() (in module binascii)</a>
</li>
      <li><a href="library/sys.html#sys.hexversion">hexversion (in module sys)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.hidden">hidden() (curses.panel.Panel method)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.hide">hide() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Notebook.hide">(ttk.Notebook method)</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.hide_cookie2">hide_cookie2 (cookielib.CookiePolicy attribute)</a>
</li>
      <li><a href="library/fl.html#fl.form.hide_form">hide_form() (fl.form method)</a>
</li>
      <li><a href="library/turtle.html#turtle.hideturtle">hideturtle() (in module turtle)</a>
</li>
      <li>
    hierarchy

      <ul>
        <li><a href="reference/datamodel.html#index-4">type</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.HierarchyRequestErr">HierarchyRequestErr</a>
</li>
      <li><a href="library/pickle.html#pickle.HIGHEST_PROTOCOL">HIGHEST_PROTOCOL (in module pickle)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CLASSES_ROOT">HKEY_CLASSES_ROOT (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CURRENT_CONFIG">HKEY_CURRENT_CONFIG (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_CURRENT_USER">HKEY_CURRENT_USER (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_DYN_DATA">HKEY_DYN_DATA (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_LOCAL_MACHINE">HKEY_LOCAL_MACHINE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_PERFORMANCE_DATA">HKEY_PERFORMANCE_DATA (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.HKEY_USERS">HKEY_USERS (in module _winreg)</a>
</li>
      <li><a href="library/curses.html#curses.window.hline">hline() (curses.window method)</a>
</li>
      <li><a href="library/tix.html#Tix.HList">HList (class in Tix)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.hls_to_rgb">hls_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/hmac.html#module-hmac">hmac (module)</a>
</li>
      <li><a href="distutils/apiref.html#index-1">HOME</a>, <a href="install/index.html#index-4">[1]</a>, <a href="install/index.html#index-5">[2]</a>, <a href="library/os.path.html#index-2">[3]</a>, <a href="library/os.path.html#index-3">[4]</a>, <a href="library/user.html#index-3">[5]</a>
</li>
      <li><a href="library/turtle.html#turtle.home">home() (in module turtle)</a>
</li>
      <li><a href="install/index.html#index-7">HOMEDRIVE</a>, <a href="library/os.path.html#index-6">[1]</a>
</li>
      <li><a href="install/index.html#index-8">HOMEPATH</a>, <a href="library/os.path.html#index-5">[1]</a>
</li>
      <li><a href="library/fileinput.html#fileinput.hook_compressed">hook_compressed() (in module fileinput)</a>
</li>
      <li><a href="library/fileinput.html#fileinput.hook_encoded">hook_encoded() (in module fileinput)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.hosts">hosts (netrc.netrc attribute)</a>
</li>
      <li><a href="library/hotshot.html#module-hotshot">hotshot (module)</a>
</li>
      <li><a href="library/hotshot.html#module-hotshot.stats">hotshot.stats (module)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.hour">hour (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.hour">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.HRESULT">HRESULT (class in ctypes)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdError">hStdError (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdInput">hStdInput (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.STARTUPINFO.hStdOutput">hStdOutput (subprocess.STARTUPINFO attribute)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.hsv_to_rgb">hsv_to_rgb() (in module colorsys)</a>
</li>
      <li><a href="library/turtle.html#turtle.ht">ht() (in module turtle)</a>
</li>
      <li><a href="library/htmllib.html#index-0">HTML</a>, <a href="library/htmlparser.html#index-0">[1]</a>, <a href="library/urllib.html#index-9">[2]</a>
</li>
      <li><a href="library/calendar.html#calendar.HTMLCalendar">HTMLCalendar (class in calendar)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff">HtmlDiff (class in difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.__init__">HtmlDiff.__init__() (in module difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.make_file">HtmlDiff.make_file() (in module difflib)</a>
</li>
      <li><a href="library/difflib.html#difflib.HtmlDiff.make_table">HtmlDiff.make_table() (in module difflib)</a>
</li>
      <li><a href="library/htmllib.html#module-htmlentitydefs">htmlentitydefs (module)</a>
</li>
      <li>
    htmllib

      <ul>
        <li><a href="library/urllib.html#index-9">module</a>
</li>
      </ul></li>
      <li><a href="library/htmllib.html#module-htmllib">htmllib (module)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParseError">HTMLParseError</a>, <a href="library/htmlparser.html#HTMLParser.HTMLParseError">[1]</a>
</li>
      <li><a href="library/formatter.html#index-0">HTMLParser (class in htmllib)</a>, <a href="library/htmllib.html#htmllib.HTMLParser">[1]</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser">(class in HTMLParser)</a>
</li>
        <li><a href="library/htmlparser.html#module-HTMLParser">(module)</a>
</li>
      </ul></li>
      <li><a href="library/socket.html#socket.htonl">htonl() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.htons">htons() (in module socket)</a>
</li>
      <li>
    HTTP

      <ul>
        <li><a href="library/httplib.html#index-0">httplib (standard module)</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">protocol</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/httplib.html#index-0">[2]</a>, <a href="library/urllib.html#index-8">[3]</a>, <a href="library/urllib.html#index-9">[4]</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_301">http_error_301() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_302">http_error_302() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_303">http_error_303() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.http_error_307">http_error_307() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPBasicAuthHandler.http_error_401">http_error_401() (urllib2.HTTPBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPDigestAuthHandler.http_error_401">(urllib2.HTTPDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.ProxyBasicAuthHandler.http_error_407">http_error_407() (urllib2.ProxyBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.ProxyDigestAuthHandler.http_error_407">(urllib2.ProxyDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.AbstractBasicAuthHandler.http_error_auth_reqed">http_error_auth_reqed() (urllib2.AbstractBasicAuthHandler method)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.AbstractDigestAuthHandler.http_error_auth_reqed">(urllib2.AbstractDigestAuthHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.http_error_default">http_error_default() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.http_error_nnn">http_error_nnn() (urllib2.BaseHandler method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPHandler.http_open">http_open() (urllib2.HTTPHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTP_PORT">HTTP_PORT (in module httplib)</a>
</li>
      <li><a href="howto/urllib2.html#index-1">http_proxy</a>, <a href="library/urllib.html#index-2">[1]</a>, <a href="library/urllib2.html#index-0">[2]</a>, <a href="library/urllib2.html#index-6">[3]</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor.http_response">http_response() (urllib2.HTTPErrorProcessor method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.http_version">http_version (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPBasicAuthHandler">HTTPBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection">HTTPConnection (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPCookieProcessor">HTTPCookieProcessor (class in urllib2)</a>
</li>
      <li><a href="library/basehttpserver.html#index-0">httpd</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPDefaultErrorHandler">HTTPDefaultErrorHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPDigestAuthHandler">HTTPDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPError">HTTPError</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor">HTTPErrorProcessor (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPException">HTTPException</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler">HTTPHandler (class in logging.handlers)</a>

      <ul>
        <li><a href="library/urllib2.html#urllib2.HTTPHandler">(class in urllib2)</a>
</li>
      </ul></li>
      <li><a href="library/httplib.html#module-httplib">httplib (module)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPMessage">HTTPMessage (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgr">HTTPPasswordMgr (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPPasswordMgrWithDefaultRealm">HTTPPasswordMgrWithDefaultRealm (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler">HTTPRedirectHandler (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse">HTTPResponse (class in httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPSHandler.https_open">https_open() (urllib2.HTTPSHandler method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPS_PORT">HTTPS_PORT (in module httplib)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPErrorProcessor.https_response">https_response() (urllib2.HTTPErrorProcessor method)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPSConnection">HTTPSConnection (class in httplib)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.HTTPServer">HTTPServer (class in BaseHTTPServer)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPSHandler">HTTPSHandler (class in urllib2)</a>
</li>
      <li><a href="library/htmllib.html#index-0">hypertext</a>
</li>
      <li><a href="library/math.html#math.hypot">hypot() (in module math)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�o>�>�html/genindex-I.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-I.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; I</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.I">I (in module re)</a>
</li>
      <li>
    I/O control

      <ul>
        <li><a href="library/termios.html#index-0">POSIX</a>
</li>
        <li><a href="library/fcntl.html#index-0">UNIX</a>
</li>
        <li><a href="library/functions.html#index-4">buffering</a>, <a href="library/os.html#index-11">[1]</a>, <a href="library/socket.html#index-3">[2]</a>
</li>
        <li><a href="library/termios.html#index-0">tty</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.iadd">iadd() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.iand">iand() (in module operator)</a>
</li>
      <li><a href="library/ic.html#ic.IC">IC (class in ic)</a>
</li>
      <li><a href="library/ic.html#module-ic">ic (module)</a>
</li>
      <li>
    icglue

      <ul>
        <li><a href="library/ic.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.iconcat">iconcat() (in module operator)</a>
</li>
      <li><a href="library/undoc.html#module-icopen">icopen (module)</a>
</li>
      <li>
    id

      <ul>
        <li><a href="reference/datamodel.html#index-1">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#id">id() (built-in function)</a>

      <ul>
        <li><a href="library/unittest.html#unittest.TestCase.id">(unittest.TestCase method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.idcok">idcok() (curses.window method)</a>
</li>
      <li><a href="library/cd.html#cd.ident">ident (in module cd)</a>

      <ul>
        <li><a href="library/select.html#select.kevent.ident">(select.kevent attribute)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.ident">(threading.Thread attribute)</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.identchars">identchars (cmd.Cmd attribute)</a>
</li>
      <li><a href="reference/expressions.html#index-5">identifier</a>, <a href="reference/lexical_analysis.html#index-9">[1]</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook.identify">identify() (ttk.Notebook method)</a>

      <ul>
        <li><a href="library/ttk.html#ttk.Treeview.identify">(ttk.Treeview method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Widget.identify">(ttk.Widget method)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_column">identify_column() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_element">identify_element() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_region">identify_region() (ttk.Treeview method)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.identify_row">identify_row() (ttk.Treeview method)</a>
</li>
      <li>
    identity

      <ul>
        <li><a href="reference/expressions.html#index-68">test</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">identity of an object</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-idioms">idioms (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.idiv">idiv() (in module operator)</a>
</li>
      <li><a href="library/idle.html#index-0">IDLE</a>, <a href="glossary.html#term-idle"><strong>[1]</strong></a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.idle">idle() (FrameWork.Application method)</a>
</li>
      <li><a href="library/idle.html#index-5">IDLESTARTUP</a>
</li>
      <li><a href="library/curses.html#curses.window.idlok">idlok() (curses.window method)</a>
</li>
      <li><a href="library/fpectl.html#index-0">IEEE-754</a>
</li>
      <li>
    if

      <ul>
        <li><a href="library/stdtypes.html#index-2">statement</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>
</li>
      </ul></li>
      <li><a href="library/itertools.html#itertools.ifilter">ifilter() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.ifilterfalse">ifilterfalse() (in module itertools)</a>
</li>
      <li><a href="library/operator.html#operator.ifloordiv">ifloordiv() (in module operator)</a>
</li>
      <li><a href="library/glob.html#glob.iglob">iglob() (in module glob)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.ignorableWhitespace">ignorableWhitespace() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/codecs.html#codecs.ignore_errors">ignore_errors() (in module codecs)</a>
</li>
      <li><a href="library/doctest.html#doctest.IGNORE_EXCEPTION_DETAIL">IGNORE_EXCEPTION_DETAIL (in module doctest)</a>
</li>
      <li><a href="library/shutil.html#shutil.ignore_patterns">ignore_patterns() (in module shutil)</a>
</li>
      <li><a href="library/re.html#re.IGNORECASE">IGNORECASE (in module re)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.ihave">ihave() (nntplib.NNTP method)</a>
</li>
      <li>
    ihooks

      <ul>
        <li><a href="c-api/import.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.ilshift">ilshift() (in module operator)</a>
</li>
      <li><a href="reference/datamodel.html#index-40">im_class (method attribute)</a>, <a href="reference/datamodel.html#index-42">[1]</a>
</li>
      <li><a href="reference/datamodel.html#index-39">im_func (method attribute)</a>, <a href="reference/datamodel.html#index-40">[1]</a>, <a href="reference/datamodel.html#index-41">[2]</a>, <a href="reference/datamodel.html#index-42">[3]</a>
</li>
      <li><a href="reference/datamodel.html#index-39">im_self (method attribute)</a>, <a href="reference/datamodel.html#index-40">[1]</a>, <a href="reference/datamodel.html#index-42">[2]</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex.imag">imag (numbers.Complex attribute)</a>
</li>
      <li><a href="library/imageop.html#module-imageop">imageop (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">imaginary literal</a>
</li>
      <li><a href="library/itertools.html#itertools.imap">imap() (in module itertools)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.imap">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      </ul></li>
      <li>
    IMAP4

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4">IMAP4 (class in imaplib)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.abort">IMAP4.abort</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.error">IMAP4.error</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.readonly">IMAP4.readonly</a>
</li>
      <li>
    IMAP4_SSL

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_SSL">IMAP4_SSL (class in imaplib)</a>
</li>
      <li>
    IMAP4_stream

      <ul>
        <li><a href="library/imaplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4_stream">IMAP4_stream (class in imaplib)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.imap_unordered">imap_unordered() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/imaplib.html#module-imaplib">imaplib (module)</a>
</li>
      <li><a href="library/imgfile.html#module-imgfile">imgfile (module)</a>
</li>
      <li><a href="library/imghdr.html#module-imghdr">imghdr (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.immedok">immedok() (curses.window method)</a>
</li>
      <li><a href="glossary.html#term-immutable"><strong>immutable</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-9">data type</a>
</li>
        <li><a href="reference/datamodel.html#index-20">object</a>, <a href="reference/expressions.html#index-17">[1]</a>, <a href="reference/expressions.html#index-9">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">immutable object</a>
</li>
      <li>
    immutable sequence

      <ul>
        <li><a href="reference/datamodel.html#index-20">object</a>
</li>
      </ul></li>
      <li>
    immutable types

      <ul>
        <li><a href="reference/datamodel.html#index-73">subclassing</a>
</li>
      </ul></li>
      <li><a href="library/sets.html#sets.ImmutableSet">ImmutableSet (class in sets)</a>
</li>
      <li><a href="library/operator.html#operator.imod">imod() (in module operator)</a>
</li>
      <li>
    imp

      <ul>
        <li><a href="library/functions.html#index-8">module</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#module-imp">imp (module)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.ImpImporter">ImpImporter (class in pkgutil)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.ImpLoader">ImpLoader (class in pkgutil)</a>
</li>
      <li>
    import

      <ul>
        <li><a href="library/functions.html#index-8">statement</a>, <a href="library/imp.html#index-0">[1]</a>, <a href="library/imputil.html#index-0">[2]</a>, <a href="reference/datamodel.html#index-47">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-import">import (2to3 fixer)</a>
</li>
      <li><a href="library/imputil.html#imputil.DynLoadSuffixImporter.import_file">import_file() (imputil.DynLoadSuffixImporter method)</a>
</li>
      <li><a href="library/test.html#test.support.import_fresh_module">import_fresh_module() (in module test.support)</a>
</li>
      <li><a href="library/dis.html#opcode-IMPORT_FROM">IMPORT_FROM (opcode)</a>
</li>
      <li><a href="library/importlib.html#importlib.import_module">import_module() (in module importlib)</a>

      <ul>
        <li><a href="library/test.html#test.support.import_module">(in module test.support)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-IMPORT_NAME">IMPORT_NAME (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-IMPORT_STAR">IMPORT_STAR (opcode)</a>
</li>
      <li><a href="library/imputil.html#imputil.Importer.import_top">import_top() (imputil.Importer method)</a>
</li>
      <li><a href="glossary.html#term-importer"><strong>importer</strong></a>
</li>
      <li><a href="library/imputil.html#imputil.Importer">Importer (class in imputil)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ImportError">ImportError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">exception</a>, <a href="reference/simple_stmts.html#index-47">[1]</a>, <a href="reference/simple_stmts.html#index-48">[2]</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-importing"><strong>importing</strong></a>
</li>
      <li><a href="library/importlib.html#module-importlib">importlib (module)</a>
</li>
      <li><a href="library/imputil.html#imputil.ImportManager">ImportManager (class in imputil)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-imports">imports (2to3 fixer)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-imports2">imports2 (2to3 fixer)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ImportWarning">ImportWarning</a>
</li>
      <li><a href="library/httplib.html#httplib.ImproperConnectionState">ImproperConnectionState</a>
</li>
      <li><a href="library/imputil.html#module-imputil">imputil (module)</a>
</li>
      <li><a href="library/operator.html#operator.imul">imul() (in module operator)</a>
</li>
      <li>
    in

      <ul>
        <li><a href="reference/compound_stmts.html#index-6">keyword</a>
</li>
        <li><a href="library/stdtypes.html#index-12">operator</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._CData.in_dll">in_dll() (ctypes._CData method)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_a1">in_table_a1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_b1">in_table_b1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c11">in_table_c11() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c11_c12">in_table_c11_c12() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c12">in_table_c12() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c21">in_table_c21() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c21_c22">in_table_c21_c22() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c22">in_table_c22() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c3">in_table_c3() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c4">in_table_c4() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c5">in_table_c5() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c6">in_table_c6() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c7">in_table_c7() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c8">in_table_c8() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_c9">in_table_c9() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_d1">in_table_d1() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.in_table_d2">in_table_d2() (in module stringprep)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.inc">inc() (EasyDialogs.ProgressBar method)</a>
</li>
      <li><a href="library/curses.html#curses.window.inch">inch() (curses.window method)</a>
</li>
      <li>
    inclusive

      <ul>
        <li><a href="reference/expressions.html#index-63">or</a>
</li>
      </ul></li>
      <li><a href="library/binascii.html#binascii.Incomplete">Incomplete</a>
</li>
      <li><a href="library/httplib.html#httplib.IncompleteRead">IncompleteRead</a>
</li>
      <li><a href="c-api/intro.html#index-17">incr_item()</a>, <a href="c-api/intro.html#index-18">[1]</a>
</li>
      <li><a href="library/ast.html#ast.increment_lineno">increment_lineno() (in module ast)</a>
</li>
      <li><a href="library/codecs.html#codecs.IncrementalDecoder">IncrementalDecoder (class in codecs)</a>
</li>
      <li><a href="library/codecs.html#codecs.IncrementalEncoder">IncrementalEncoder (class in codecs)</a>
</li>
      <li><a href="library/io.html#io.IncrementalNewlineDecoder">IncrementalNewlineDecoder (class in io)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser">IncrementalParser (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.indent">indent (doctest.Example attribute)</a>
</li>
      <li><a href="library/token.html#token.INDENT">INDENT (in module token)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-8">INDENT token</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">indentation</a>
</li>
      <li><a href="library/exceptions.html#exceptions.IndentationError">IndentationError</a>
</li>
      <li><a href="library/jpeg.html#index-0">Independent JPEG Group</a>
</li>
      <li><a href="library/cd.html#cd.index">index (in module cd)</a>
</li>
      <li><a href="reference/datamodel.html#index-17">index operation</a>
</li>
      <li><a href="library/array.html#array.array.index">index() (array.array method)</a>

      <ul>
        <li><a href="library/operator.html#operator.index">(in module operator)</a>
</li>
        <li><a href="library/string.html#string.index">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/stdtypes.html#str.index">(str method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.index">(ttk.Notebook method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.index">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.IndexError">IndexError</a>
</li>
      <li><a href="library/operator.html#operator.indexOf">indexOf() (in module operator)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.IndexSizeErr">IndexSizeErr</a>
</li>
      <li><a href="reference/datamodel.html#slice.indices">indices() (slice method)</a>
</li>
      <li><a href="library/socket.html#socket.inet_aton">inet_aton() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_ntoa">inet_ntoa() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_ntop">inet_ntop() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.inet_pton">inet_pton() (in module socket)</a>
</li>
      <li><a href="library/decimal.html#decimal.Inexact">Inexact (class in decimal)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.infile">infile (shlex.shlex attribute)</a>
</li>
      <li><a href="library/functions.html#index-2">Infinity</a>, <a href="library/string.html#index-6">[1]</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.info">info() (gettext.NullTranslations method)</a>

      <ul>
        <li><a href="library/logging.html#logging.info">(in module logging)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.info">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.infolist">infolist() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/carbon.html#Carbon.Scrap.InfoScrap">InfoScrap() (in module Carbon.Scrap)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-23">inheritance</a>
</li>
      <li><a href="library/configparser.html#index-0">ini file</a>
</li>
      <li><a href="library/fm.html#fm.init">init() (in module fm)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.init">(in module mimetypes)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.init_builtin">init_builtin() (in module imp)</a>
</li>
      <li><a href="library/curses.html#curses.init_color">init_color() (in module curses)</a>
</li>
      <li><a href="library/msilib.html#msilib.init_database">init_database() (in module msilib)</a>
</li>
      <li><a href="library/imp.html#imp.init_frozen">init_frozen() (in module imp)</a>
</li>
      <li><a href="library/curses.html#curses.init_pair">init_pair() (in module curses)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.inited">inited (in module mimetypes)</a>
</li>
      <li><a href="library/os.html#os.initgroups">initgroups() (in module os)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.initial_indent">initial_indent (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.cmd.Command.initialize_options">initialize_options() (distutils.cmd.Command method)</a>
</li>
      <li><a href="library/curses.html#curses.initscr">initscr() (in module curses)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_ADD">INPLACE_ADD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_AND">INPLACE_AND (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_DIVIDE">INPLACE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_FLOOR_DIVIDE">INPLACE_FLOOR_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_LSHIFT">INPLACE_LSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_MODULO">INPLACE_MODULO (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_MULTIPLY">INPLACE_MULTIPLY (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_OR">INPLACE_OR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_POWER">INPLACE_POWER (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_RSHIFT">INPLACE_RSHIFT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_SUBTRACT">INPLACE_SUBTRACT (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_TRUE_DIVIDE">INPLACE_TRUE_DIVIDE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-INPLACE_XOR">INPLACE_XOR (opcode)</a>
</li>
      <li><a href="reference/toplevel_components.html#index-5">input</a>

      <ul>
        <li><a href="library/sys.html#index-14">built-in function</a>, <a href="reference/toplevel_components.html#index-7">[1]</a>
</li>
        <li><a href="reference/toplevel_components.html#index-8">raw</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-input">input (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#input">input() (built-in function)</a>

      <ul>
        <li><a href="library/fileinput.html#fileinput.input">(in module fileinput)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.input_charset">input_charset (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.input_codec">input_codec (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/tix.html#Tix.InputOnly">InputOnly (class in Tix)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.InputSource">InputSource (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/stringio.html#cStringIO.InputType">InputType (in module cStringIO)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.inquiry">inquiry (C type)</a>
</li>
      <li><a href="library/curses.html#curses.window.insch">insch() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.insdelln">insdelln() (curses.window method)</a>
</li>
      <li><a href="library/array.html#array.array.insert">insert() (array.array method)</a>

      <ul>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Notebook.insert">(ttk.Notebook method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.insert">(ttk.Treeview method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.insert">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.insert_text">insert_text() (in module readline)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.insertBefore">insertBefore() (xml.dom.Node method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.InsertionLoc">InsertionLoc (class in aetypes)</a>
</li>
      <li><a href="library/curses.html#curses.window.insertln">insertln() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.insnstr">insnstr() (curses.window method)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort">insort() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort_left">insort_left() (in module bisect)</a>
</li>
      <li><a href="library/bisect.html#bisect.insort_right">insort_right() (in module bisect)</a>
</li>
      <li><a href="library/inspect.html#module-inspect">inspect (module)</a>
</li>
      <li><a href="library/curses.html#curses.window.insstr">insstr() (curses.window method)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.install">install() (gettext.NullTranslations method)</a>

      <ul>
        <li><a href="library/imputil.html#imputil.ImportManager.install">(imputil.ImportManager method)</a>
</li>
        <li><a href="library/gettext.html#gettext.install">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.install_opener">install_opener() (in module urllib2)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.AEServer.installaehandler">installaehandler() (MiniAEFrame.AEServer method)</a>
</li>
      <li><a href="library/autogil.html#autoGIL.installAutoGIL">installAutoGIL() (in module autoGIL)</a>
</li>
      <li><a href="library/unittest.html#unittest.installHandler">installHandler() (in module unittest)</a>
</li>
      <li>
    instance

      <ul>
        <li><a href="reference/datamodel.html#index-87">call</a>, <a href="reference/expressions.html#index-46">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-54">class</a>
</li>
        <li><a href="c-api/class.html#index-2">object</a>, <a href="reference/datamodel.html#index-46">[1]</a>, <a href="reference/datamodel.html#index-50">[2]</a>, <a href="reference/datamodel.html#index-54">[3]</a>, <a href="reference/expressions.html#index-45">[4]</a>
</li>
      </ul></li>
      <li><a href="library/new.html#new.instance">instance() (in module new)</a>
</li>
      <li><a href="library/new.html#new.instancemethod">instancemethod() (in module new)</a>
</li>
      <li><a href="library/types.html#types.InstanceType">InstanceType (in module types)</a>
</li>
      <li><a href="library/ttk.html#ttk.Widget.instate">instate() (ttk.Widget method)</a>
</li>
      <li><a href="library/curses.html#curses.window.instr">instr() (curses.window method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.instream">instream (shlex.shlex attribute)</a>
</li>
      <li>
    int

      <ul>
        <li><a href="c-api/number.html#index-5">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-94">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#int">int (built-in class)</a>

      <ul>
        <li><a href="library/uuid.html#uuid.UUID.int">(uuid.UUID attribute)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.Int2AP">Int2AP() (in module imaplib)</a>
</li>
      <li><a href="reference/datamodel.html#index-23">integer</a>

      <ul>
        <li><a href="library/stdtypes.html#index-17">division</a>
</li>
        <li><a href="library/stdtypes.html#index-17">division, long</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals, long</a>
</li>
        <li><a href="c-api/int.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-10">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-14">representation</a>
</li>
        <li><a href="library/stdtypes.html#index-19">types, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-integer-division"><strong>integer division</strong></a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">integer literal</a>
</li>
      <li><a href="library/numbers.html#numbers.Integral">Integral (class in numbers)</a>
</li>
      <li><a href="library/idle.html#index-0">Integrated Development Environment</a>
</li>
      <li><a href="library/audioop.html#index-0">Intel/DVI ADPCM</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole.interact">interact() (code.InteractiveConsole method)</a>

      <ul>
        <li><a href="library/code.html#code.interact">(in module code)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.interact">(telnetlib.Telnet method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-interactive"><strong>interactive</strong></a>
</li>
      <li><a href="reference/toplevel_components.html#index-3">interactive mode</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole">InteractiveConsole (class in code)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter">InteractiveInterpreter (class in code)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-intern">intern (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#intern">intern() (built-in function)</a>
</li>
      <li><a href="reference/datamodel.html#index-59">internal type</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.internal_attr">internal_attr (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.Internaldate2tuple">Internaldate2tuple() (in module imaplib)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.internalSubset">internalSubset (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/internet.html#index-0">Internet</a>
</li>
      <li><a href="library/urllib.html#index-5">Internet Config</a>
</li>
      <li><a href="library/stdtypes.html#index-25">interpolation, string (%)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationDepthError">InterpolationDepthError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationError">InterpolationError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationMissingOptionError">InterpolationMissingOptionError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.InterpolationSyntaxError">InterpolationSyntaxError</a>
</li>
      <li><a href="glossary.html#term-interpreted"><strong>interpreted</strong></a>
</li>
      <li><a href="reference/toplevel_components.html#index-0">interpreter</a>
</li>
      <li><a href="c-api/init.html#index-13">interpreter lock</a>
</li>
      <li><a href="library/sys.html#index-11">interpreter prompts</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.interrupt">interrupt() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/thread.html#thread.interrupt_main">interrupt_main() (in module thread)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.intersection">intersection() (frozenset method)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.intersection_update">intersection_update() (frozenset method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.IntlText">IntlText (class in aetypes)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.IntlWritingCode">IntlWritingCode (class in aetypes)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.intro">intro (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/types.html#types.IntType">IntType (in module types)</a>

      <ul>
        <li><a href="c-api/int.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.InuseAttributeErr">InuseAttributeErr</a>
</li>
      <li><a href="library/operator.html#operator.inv">inv() (in module operator)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidAccessErr">InvalidAccessErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidCharacterErr">InvalidCharacterErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidModificationErr">InvalidModificationErr</a>
</li>
      <li><a href="library/decimal.html#decimal.InvalidOperation">InvalidOperation (class in decimal)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.InvalidStateErr">InvalidStateErr</a>
</li>
      <li><a href="library/httplib.html#httplib.InvalidURL">InvalidURL</a>
</li>
      <li><a href="reference/expressions.html#index-50">inversion</a>
</li>
      <li><a href="library/operator.html#operator.invert">invert() (in module operator)</a>
</li>
      <li><a href="reference/datamodel.html#index-35">invocation</a>
</li>
      <li><a href="library/io.html#module-io">io (module)</a>
</li>
      <li><a href="library/io.html#io.IOBase">IOBase (class in io)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.ioctl">ioctl() (in module fcntl)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.ioctl">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/exceptions.html#exceptions.IOError">IOError</a>
</li>
      <li><a href="library/operator.html#operator.ior">ior() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.ipow">ipow() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.irepeat">irepeat() (in module operator)</a>
</li>
      <li><a href="library/fm.html#index-0">IRIS Font Manager</a>
</li>
      <li>
    IRIX

      <ul>
        <li><a href="library/thread.html#index-3">threads</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.irshift">irshift() (in module operator)</a>
</li>
      <li>
    is

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
      </ul></li>
      <li>
    is not

      <ul>
        <li><a href="library/stdtypes.html#index-9">operator</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.is_">is_() (in module operator)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.is_alive">is_alive() (multiprocessing.Process method)</a>

      <ul>
        <li><a href="library/threading.html#threading.Thread.is_alive">(threading.Thread method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_assigned">is_assigned() (symtable.Symbol method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.is_blocked">is_blocked() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/imp.html#imp.is_builtin">is_builtin() (in module imp)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_canonical">is_canonical() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_canonical">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/difflib.html#difflib.IS_CHARACTER_JUNK">IS_CHARACTER_JUNK() (in module difflib)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.is_data">is_data() (multifile.MultiFile method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_declared_global">is_declared_global() (symtable.Symbol method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.fifo.is_empty">is_empty() (asynchat.fifo method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.is_expired">is_expired() (cookielib.Cookie method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_finite">is_finite() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_finite">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_free">is_free() (symtable.Symbol method)</a>
</li>
      <li><a href="library/imp.html#imp.is_frozen">is_frozen() (in module imp)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_global">is_global() (symtable.Symbol method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.is_hop_by_hop">is_hop_by_hop() (in module wsgiref.util)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_imported">is_imported() (symtable.Symbol method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_infinite">is_infinite() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_infinite">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#float.is_integer">is_integer() (float method)</a>
</li>
      <li><a href="library/test.html#test.support.is_jython">is_jython (in module test.support)</a>
</li>
      <li><a href="library/difflib.html#difflib.IS_LINE_JUNK">IS_LINE_JUNK() (in module difflib)</a>
</li>
      <li><a href="library/curses.html#curses.window.is_linetouched">is_linetouched() (curses.window method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_local">is_local() (symtable.Symbol method)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.is_multipart">is_multipart() (email.message.Message method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_namespace">is_namespace() (symtable.Symbol method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_nan">is_nan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_nan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.SymbolTable.is_nested">is_nested() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_normal">is_normal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_normal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.is_not">is_not() (in module operator)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.is_not_allowed">is_not_allowed() (cookielib.DefaultCookiePolicy method)</a>
</li>
      <li><a href="library/symtable.html#symtable.SymbolTable.is_optimized">is_optimized() (symtable.SymbolTable method)</a>
</li>
      <li><a href="library/zipimport.html#zipimport.zipimporter.is_package">is_package() (zipimport.zipimporter method)</a>
</li>
      <li><a href="library/symtable.html#symtable.Symbol.is_parameter">is_parameter() (symtable.Symbol method)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.is_python_build">is_python_build() (in module sysconfig)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_qnan">is_qnan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_qnan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/symtable.html#symtable.Symbol.is_referenced">is_referenced() (symtable.Symbol method)</a>
</li>
      <li><a href="library/test.html#test.support.is_resource_enabled">is_resource_enabled() (in module test.support)</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.is_scriptable">is_scriptable() (in module gensuitemodule)</a>
</li>
      <li><a href="library/threading.html#threading.Event.is_set">is_set() (threading.Event method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_signed">is_signed() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_signed">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.is_snan">is_snan() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_snan">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.is_subnormal">is_subnormal() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_subnormal">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.is_tarfile">is_tarfile() (in module tarfile)</a>
</li>
      <li><a href="library/curses.html#curses.is_term_resized">is_term_resized() (in module curses)</a>
</li>
      <li><a href="library/gc.html#gc.is_tracked">is_tracked() (in module gc)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.Request.is_unverifiable">is_unverifiable() (urllib2.Request method)</a>
</li>
      <li><a href="library/curses.html#curses.window.is_wintouched">is_wintouched() (curses.window method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.is_zero">is_zero() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.is_zero">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/zipfile.html#zipfile.is_zipfile">is_zipfile() (in module zipfile)</a>
</li>
      <li><a href="library/os.path.html#os.path.isabs">isabs() (in module os.path)</a>
</li>
      <li><a href="library/inspect.html#inspect.isabstract">isabstract() (in module inspect)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.isAlive">isAlive() (threading.Thread method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isalnum">isalnum() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isalnum">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isalpha">isalpha() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isalpha">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isascii">isascii() (in module curses.ascii)</a>
</li>
      <li><a href="library/chunk.html#chunk.Chunk.isatty">isatty() (chunk.Chunk method)</a>

      <ul>
        <li><a href="library/stdtypes.html#file.isatty">(file method)</a>
</li>
        <li><a href="library/os.html#os.isatty">(in module os)</a>
</li>
        <li><a href="library/io.html#io.IOBase.isatty">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isblank">isblank() (in module curses.ascii)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isblk">isblk() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isbuiltin">isbuiltin() (in module inspect)</a>
</li>
      <li><a href="library/operator.html#operator.isCallable">isCallable() (in module operator)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.ischr">ischr() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isclass">isclass() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.iscntrl">iscntrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/inspect.html#inspect.iscode">iscode() (in module inspect)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.iscomment">iscomment() (rfc822.Message method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isctrl">isctrl() (in module curses.ascii)</a>
</li>
      <li><a href="library/threading.html#threading.Thread.isDaemon">isDaemon() (threading.Thread method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isdatadescriptor">isdatadescriptor() (in module inspect)</a>
</li>
      <li><a href="library/stdtypes.html#unicode.isdecimal">isdecimal() (unicode method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isdev">isdev() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isdigit">isdigit() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isdigit">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/os.path.html#os.path.isdir">isdir() (in module os.path)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.isdir">(tarfile.TarInfo method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset.isdisjoint">isdisjoint() (frozenset method)</a>
</li>
      <li><a href="library/turtle.html#turtle.isdown">isdown() (in module turtle)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.iselement">iselement() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/gc.html#gc.isenabled">isenabled() (in module gc)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.isEnabledFor">isEnabledFor() (logging.Logger method)</a>
</li>
      <li><a href="library/curses.html#curses.isendwin">isendwin() (in module curses)</a>
</li>
      <li><a href="library/token.html#token.ISEOF">ISEOF() (in module token)</a>
</li>
      <li><a href="library/parser.html#parser.isexpr">isexpr() (in module parser)</a>

      <ul>
        <li><a href="library/parser.html#parser.ST.isexpr">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isfifo">isfifo() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/os.path.html#os.path.isfile">isfile() (in module os.path)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.isfile">(tarfile.TarInfo method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.isfirstline">isfirstline() (in module fileinput)</a>
</li>
      <li><a href="library/inspect.html#inspect.isframe">isframe() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isfunction">isfunction() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgenerator">isgenerator() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgeneratorfunction">isgeneratorfunction() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.isgetsetdescriptor">isgetsetdescriptor() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isgraph">isgraph() (in module curses.ascii)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.isheader">isheader() (rfc822.Message method)</a>
</li>
      <li><a href="library/cmath.html#cmath.isinf">isinf() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.isinf">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-isinstance">isinstance (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#isinstance">isinstance() (built-in function)</a>
</li>
      <li><a href="library/keyword.html#keyword.iskeyword">iskeyword() (in module keyword)</a>
</li>
      <li><a href="library/rfc822.html#rfc822.Message.islast">islast() (rfc822.Message method)</a>
</li>
      <li><a href="library/calendar.html#calendar.isleap">isleap() (in module calendar)</a>
</li>
      <li><a href="library/itertools.html#itertools.islice">islice() (in module itertools)</a>
</li>
      <li><a href="library/os.path.html#os.path.islink">islink() (in module os.path)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.islnk">islnk() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.islower">islower() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.islower">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.isMappingType">isMappingType() (in module operator)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismemberdescriptor">ismemberdescriptor() (in module inspect)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ismeta">ismeta() (in module curses.ascii)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismethod">ismethod() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismethoddescriptor">ismethoddescriptor() (in module inspect)</a>
</li>
      <li><a href="library/inspect.html#inspect.ismodule">ismodule() (in module inspect)</a>
</li>
      <li><a href="library/os.path.html#os.path.ismount">ismount() (in module os.path)</a>
</li>
      <li><a href="library/cmath.html#cmath.isnan">isnan() (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.isnan">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.ISNONTERMINAL">ISNONTERMINAL() (in module token)</a>
</li>
      <li><a href="library/operator.html#operator.isNumberType">isNumberType() (in module operator)</a>
</li>
      <li><a href="library/stdtypes.html#unicode.isnumeric">isnumeric() (unicode method)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.isocalendar">isocalendar() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isocalendar">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.isoformat">isoformat() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isoformat">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.isoformat">(datetime.time method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.isolation_level">isolation_level (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.isoweekday">isoweekday() (datetime.date method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.isoweekday">(datetime.datetime method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.ascii.html#curses.ascii.isprint">isprint() (in module curses.ascii)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.ispunct">ispunct() (in module curses.ascii)</a>
</li>
      <li><a href="library/fl.html#fl.isqueued">isqueued() (in module fl)</a>
</li>
      <li><a href="library/pprint.html#pprint.isreadable">isreadable() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.isreadable">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/pprint.html#pprint.isrecursive">isrecursive() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.isrecursive">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.isreg">isreg() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.isReservedKey">isReservedKey() (Cookie.Morsel method)</a>
</li>
      <li><a href="library/inspect.html#inspect.isroutine">isroutine() (in module inspect)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.isSameNode">isSameNode() (xml.dom.Node method)</a>
</li>
      <li><a href="library/operator.html#operator.isSequenceType">isSequenceType() (in module operator)</a>
</li>
      <li><a href="library/threading.html#threading.Event.isSet">isSet() (threading.Event method)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isspace">isspace() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isspace">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.isstdin">isstdin() (in module fileinput)</a>
</li>
      <li><a href="library/functions.html#issubclass">issubclass() (built-in function)</a>
</li>
      <li><a href="library/stdtypes.html#frozenset.issubset">issubset() (frozenset method)</a>
</li>
      <li><a href="library/parser.html#parser.issuite">issuite() (in module parser)</a>

      <ul>
        <li><a href="library/parser.html#parser.ST.issuite">(parser.ST method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#frozenset.issuperset">issuperset() (frozenset method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.issym">issym() (tarfile.TarInfo method)</a>
</li>
      <li><a href="library/token.html#token.ISTERMINAL">ISTERMINAL() (in module token)</a>
</li>
      <li><a href="library/stdtypes.html#str.istitle">istitle() (str method)</a>
</li>
      <li><a href="library/inspect.html#inspect.istraceback">istraceback() (in module inspect)</a>
</li>
      <li><a href="library/operator.html#operator.isub">isub() (in module operator)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isupper">isupper() (in module curses.ascii)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.isupper">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.isvisible">isvisible() (in module turtle)</a>
</li>
      <li><a href="library/curses.ascii.html#curses.ascii.isxdigit">isxdigit() (in module curses.ascii)</a>
</li>
      <li>
    item

      <ul>
        <li><a href="reference/expressions.html#index-32">sequence</a>
</li>
        <li><a href="reference/expressions.html#index-33">string</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-17">item selection</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.item">item() (ttk.Treeview method)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.NamedNodeMap.item">(xml.dom.NamedNodeMap method)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.NodeList.item">(xml.dom.NodeList method)</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.itemgetter">itemgetter() (in module operator)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.ConfigParser.items">items() (ConfigParser.ConfigParser method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.items">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.items">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.items">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.items">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.items">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.itemsize">itemsize (array.array attribute)</a>

      <ul>
        <li><a href="library/stdtypes.html#memoryview.itemsize">(memoryview attribute)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.ItemsView">ItemsView (class in collections)</a>
</li>
      <li><a href="library/functions.html#iter">iter() (built-in function)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iter">(xml.etree.ElementTree.Element method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.iter">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/ast.html#ast.iter_child_nodes">iter_child_nodes() (in module ast)</a>
</li>
      <li><a href="library/ast.html#ast.iter_fields">iter_fields() (in module ast)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.iter_importers">iter_importers() (in module pkgutil)</a>
</li>
      <li><a href="library/pkgutil.html#pkgutil.iter_modules">iter_modules() (in module pkgutil)</a>
</li>
      <li><a href="glossary.html#term-iterable"><strong>iterable</strong></a>
</li>
      <li><a href="library/collections.html#collections.Iterable">Iterable (class in collections)</a>
</li>
      <li><a href="library/userdict.html#UserDict.IterableUserDict">IterableUserDict (class in UserDict)</a>
</li>
      <li><a href="glossary.html#term-iterator"><strong>iterator</strong></a>
</li>
      <li><a href="library/collections.html#collections.Iterator">Iterator (class in collections)</a>
</li>
      <li><a href="library/stdtypes.html#index-20">iterator protocol</a>
</li>
      <li><a href="library/codecs.html#codecs.iterdecode">iterdecode() (in module codecs)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.iterdump">iterdump (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/codecs.html#codecs.iterencode">iterencode() (in module codecs)</a>

      <ul>
        <li><a href="library/json.html#json.JSONEncoder.iterencode">(json.JSONEncoder method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.iterfind">iterfind() (xml.etree.ElementTree.Element method)</a>

      <ul>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.iterfind">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#dict.iteritems">iteritems() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.iteritems">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary.iterkeyrefs">iterkeyrefs() (weakref.WeakKeyDictionary method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.iterkeys">iterkeys() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.iterkeys">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdates">itermonthdates() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdays">itermonthdays() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.itermonthdays2">itermonthdays2() (calendar.Calendar method)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.iterparse">iterparse() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.itertext">itertext() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-itertools">itertools (2to3 fixer)</a>

      <ul>
        <li><a href="library/itertools.html#module-itertools">(module)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-itertools_imports">itertools_imports (2to3 fixer)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakValueDictionary.itervaluerefs">itervaluerefs() (weakref.WeakValueDictionary method)</a>
</li>
      <li><a href="library/stdtypes.html#dict.itervalues">itervalues() (dict method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Mailbox.itervalues">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.Calendar.iterweekdays">iterweekdays() (calendar.Calendar method)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_PROF">ITIMER_PROF (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_REAL">ITIMER_REAL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ITIMER_VIRTUAL">ITIMER_VIRTUAL (in module signal)</a>
</li>
      <li><a href="library/signal.html#signal.ItimerError">ItimerError</a>
</li>
      <li><a href="library/operator.html#operator.itruediv">itruediv() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.ixor">ixor() (in module operator)</a>
</li>
      <li><a href="library/itertools.html#itertools.izip">izip() (in module itertools)</a>
</li>
      <li><a href="library/itertools.html#itertools.izip_longest">izip_longest() (in module itertools)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�s�{��html/genindex-J.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-J.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; J</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/uu.html#index-0">Jansen, Jack</a>
</li>
      <li>
    Java

      <ul>
        <li><a href="reference/datamodel.html#index-15">language</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.java_ver">java_ver() (in module platform)</a>
</li>
      <li><a href="library/jpeg.html#index-2">JFIF</a>, <a href="library/jpeg.html#index-3">[1]</a>
</li>
      <li><a href="library/os.path.html#os.path.join">join() (in module os.path)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.join">(Queue.Queue method)</a>
</li>
        <li><a href="library/string.html#string.join">(in module string)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue.join">(multiprocessing.JoinableQueue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.join">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.join">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/stdtypes.html#str.join">(str method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.join">(threading.Thread method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.join_thread">join_thread() (multiprocessing.Queue method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.JoinableQueue">JoinableQueue (class in multiprocessing)</a>
</li>
      <li><a href="library/string.html#string.joinfields">joinfields() (in module string)</a>
</li>
      <li><a href="library/jpeg.html#module-jpeg">jpeg (module)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.js_output">js_output() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.js_output">(Cookie.Morsel method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    json

      <ul>
        <li><a href="tutorial/inputoutput.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/json.html#module-json">json (module)</a>
</li>
      <li><a href="library/json.html#json.JSONDecoder">JSONDecoder (class in json)</a>
</li>
      <li><a href="library/json.html#json.JSONEncoder">JSONEncoder (class in json)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_ABSOLUTE">JUMP_ABSOLUTE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_FORWARD">JUMP_FORWARD (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_IF_FALSE_OR_POP">JUMP_IF_FALSE_OR_POP (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-JUMP_IF_TRUE_OR_POP">JUMP_IF_TRUE_OR_POP (opcode)</a>
</li>
      <li><a href="library/random.html#random.jumpahead">jumpahead() (in module random)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\-N�Z(Z(html/genindex-K.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-K.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; K</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/msvcrt.html#msvcrt.kbhit">kbhit() (in module msvcrt)</a>
</li>
      <li><a href="library/webbrowser.html#index-2">KDEDIR</a>
</li>
      <li><a href="library/select.html#select.kevent">kevent() (in module select)</a>
</li>
      <li><a href="reference/expressions.html#index-16">key</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.key">(Cookie.Morsel attribute)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-key-function"><strong>key function</strong></a>
</li>
      <li><a href="reference/expressions.html#index-16">key/datum pair</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_ALL_ACCESS">KEY_ALL_ACCESS (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_CREATE_LINK">KEY_CREATE_LINK (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_CREATE_SUB_KEY">KEY_CREATE_SUB_KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_ENUMERATE_SUB_KEYS">KEY_ENUMERATE_SUB_KEYS (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_EXECUTE">KEY_EXECUTE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_NOTIFY">KEY_NOTIFY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_QUERY_VALUE">KEY_QUERY_VALUE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_READ">KEY_READ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_SET_VALUE">KEY_SET_VALUE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WOW64_32KEY">KEY_WOW64_32KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WOW64_64KEY">KEY_WOW64_64KEY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.KEY_WRITE">KEY_WRITE (in module _winreg)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.KeyboardInterrupt">KeyboardInterrupt</a>

      <ul>
        <li><a href="c-api/exceptions.html#index-2">(built-in exception)</a>, <a href="c-api/exceptions.html#index-3">[1]</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/exceptions.html#exceptions.KeyError">KeyError</a>
</li>
      <li><a href="library/curses.html#curses.keyname">keyname() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.window.keypad">keypad() (curses.window method)</a>
</li>
      <li><a href="library/weakref.html#weakref.WeakKeyDictionary.keyrefs">keyrefs() (weakref.WeakKeyDictionary method)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.keys">keys() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.keys">(dict method)</a>
</li>
        <li><a href="library/email.message.html#email.message.Message.keys">(email.message.Message method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.keys">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/sqlite3.html#sqlite3.Row.keys">(sqlite3.Row method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.keys">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/aetools.html#aetools.keysubst">keysubst() (in module aetools)</a>
</li>
      <li><a href="library/collections.html#collections.KeysView">KeysView (class in collections)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-10">keyword</a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-3">elif</a>
</li>
        <li><a href="reference/compound_stmts.html#index-12">else</a>, <a href="reference/compound_stmts.html#index-3">[1]</a>, <a href="reference/compound_stmts.html#index-4">[2]</a>, <a href="reference/compound_stmts.html#index-6">[3]</a>, <a href="reference/simple_stmts.html#index-34">[4]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">except</a>
</li>
        <li><a href="reference/compound_stmts.html#index-10">finally</a>, <a href="reference/compound_stmts.html#index-13">[1]</a>, <a href="reference/simple_stmts.html#index-27">[2]</a>, <a href="reference/simple_stmts.html#index-36">[3]</a>, <a href="reference/simple_stmts.html#index-37">[4]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-38">from</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">in</a>
</li>
        <li><a href="reference/expressions.html#index-22">yield</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Keyword">Keyword (class in aetypes)</a>
</li>
      <li><a href="library/keyword.html#module-keyword">keyword (module)</a>
</li>
      <li><a href="glossary.html#term-keyword-argument"><strong>keyword argument</strong></a>
</li>
      <li><a href="library/functools.html#functools.partial.keywords">keywords (functools.partial attribute)</a>
</li>
      <li><a href="library/os.html#os.kill">kill() (in module os)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.kill">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.killchar">killchar() (in module curses)</a>
</li>
      <li><a href="library/os.html#os.killpg">killpg() (in module os)</a>
</li>
      <li>
    knee

      <ul>
        <li><a href="library/imp.html#index-5">module</a>, <a href="library/imputil.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/mimetypes.html#mimetypes.knownfiles">knownfiles (in module mimetypes)</a>
</li>
      <li><a href="library/select.html#select.kqueue">kqueue() (in module select)</a>
</li>
      <li><a href="library/keyword.html#keyword.kwlist">kwlist (in module keyword)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�o�9�9�html/genindex-L.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-L.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; L</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.L">L (in module re)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.label">label() (EasyDialogs.ProgressBar method)</a>
</li>
      <li><a href="library/tix.html#Tix.LabelEntry">LabelEntry (class in Tix)</a>
</li>
      <li><a href="library/tix.html#Tix.LabelFrame">LabelFrame (class in Tix)</a>
</li>
      <li><a href="glossary.html#term-lambda"><strong>lambda</strong></a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-22">expression</a>, <a href="reference/expressions.html#index-75">[1]</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.LambdaType">LambdaType (in module types)</a>
</li>
      <li><a href="library/gettext.html#index-3">LANG</a>, <a href="library/gettext.html#index-7">[1]</a>, <a href="library/locale.html#index-1">[2]</a>, <a href="library/locale.html#index-2">[3]</a>, <a href="library/locale.html#index-3">[4]</a>
</li>
      <li><a href="library/gettext.html#index-0">LANGUAGE</a>, <a href="library/gettext.html#index-4">[1]</a>
</li>
      <li>
    language

      <ul>
        <li><a href="library/stdtypes.html#index-13">C</a>, <a href="reference/datamodel.html#index-15">[1]</a>, <a href="reference/datamodel.html#index-4">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-65">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-15">Java</a>
</li>
        <li><a href="reference/compound_stmts.html#index-8">Pascal</a>
</li>
      </ul></li>
      <li><a href="library/posix.html#index-1">large files</a>
</li>
      <li><a href="library/zipfile.html#zipfile.LargeZipFile">LargeZipFile</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.last">last (multifile.MultiFile attribute)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.last">last() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.last">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.last">(nntplib.NNTP method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener.last_accepted">last_accepted (multiprocessing.connection.Listener attribute)</a>
</li>
      <li><a href="library/sys.html#sys.last_traceback">last_traceback (in module sys)</a>, <a href="reference/datamodel.html#index-67">[1]</a>
</li>
      <li><a href="library/sys.html#sys.last_type">last_type (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.last_value">last_value (in module sys)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.lastChild">lastChild (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.lastcmd">lastcmd (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.lastgroup">lastgroup (re.MatchObject attribute)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.lastindex">lastindex (re.MatchObject attribute)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.lastpart">lastpart() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.lastrowid">lastrowid (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/macostools.html#findertools.launch">launch() (in module findertools)</a>
</li>
      <li><a href="library/ic.html#ic.IC.launchurl">launchurl() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.launchurl">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Style.layout">layout() (ttk.Style method)</a>
</li>
      <li><a href="library/token.html#token.LBRACE">LBRACE (in module token)</a>
</li>
      <li><a href="glossary.html#term-lbyl"><strong>LBYL</strong></a>
</li>
      <li><a href="library/gettext.html#index-1">LC_ALL</a>, <a href="library/gettext.html#index-5">[1]</a>

      <ul>
        <li><a href="library/locale.html#locale.LC_ALL">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.LC_COLLATE">LC_COLLATE (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_CTYPE">LC_CTYPE (in module locale)</a>
</li>
      <li><a href="library/gettext.html#index-2">LC_MESSAGES</a>, <a href="library/gettext.html#index-6">[1]</a>

      <ul>
        <li><a href="library/locale.html#locale.LC_MESSAGES">(in module locale)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.LC_MONETARY">LC_MONETARY (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_NUMERIC">LC_NUMERIC (in module locale)</a>
</li>
      <li><a href="library/locale.html#locale.LC_TIME">LC_TIME (in module locale)</a>
</li>
      <li><a href="library/os.html#os.lchflags">lchflags() (in module os)</a>
</li>
      <li><a href="library/os.html#os.lchmod">lchmod() (in module os)</a>
</li>
      <li><a href="library/os.html#os.lchown">lchown() (in module os)</a>
</li>
      <li><a href="whatsnew/2.7.html#index-12">LDCXXSHARED</a>
</li>
      <li><a href="library/math.html#math.ldexp">ldexp() (in module math)</a>
</li>
      <li><a href="whatsnew/2.3.html#index-27">LDFLAGS</a>
</li>
      <li><a href="library/gettext.html#gettext.ldgettext">ldgettext() (in module gettext)</a>
</li>
      <li><a href="library/gettext.html#gettext.ldngettext">ldngettext() (in module gettext)</a>
</li>
      <li><a href="library/operator.html#operator.le">le() (in module operator)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-7">leading whitespace</a>
</li>
      <li><a href="library/calendar.html#calendar.leapdays">leapdays() (in module calendar)</a>
</li>
      <li><a href="library/curses.html#curses.window.leaveok">leaveok() (curses.window method)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left">left (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.left">left() (in module turtle)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left_list">left_list (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.left_only">left_only (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/token.html#token.LEFTSHIFT">LEFTSHIFT (in module token)</a>
</li>
      <li><a href="library/token.html#token.LEFTSHIFTEQUAL">LEFTSHIFTEQUAL (in module token)</a>
</li>
      <li>
    len

      <ul>
        <li><a href="c-api/dict.html#index-3">built-in function</a>, <a href="c-api/list.html#index-1">[1]</a>, <a href="c-api/mapping.html#index-0">[2]</a>, <a href="c-api/object.html#index-11">[3]</a>, <a href="c-api/sequence.html#index-0">[4]</a>, <a href="c-api/set.html#index-1">[5]</a>, <a href="library/stdtypes.html#index-22">[6]</a>, <a href="library/stdtypes.html#index-32">[7]</a>, <a href="reference/datamodel.html#index-17">[8]</a>, <a href="reference/datamodel.html#index-29">[9]</a>, <a href="reference/datamodel.html#index-32">[10]</a>, <a href="reference/datamodel.html#index-88">[11]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#len">len() (built-in function)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NamedNodeMap.length">length (xml.dom.NamedNodeMap attribute)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.NodeList.length">(xml.dom.NodeList attribute)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.LESS">LESS (in module token)</a>
</li>
      <li><a href="library/token.html#token.LESSEQUAL">LESSEQUAL (in module token)</a>
</li>
      <li><a href="library/string.html#string.letters">letters (in module string)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile.level">level (multifile.MultiFile attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">lexical analysis</a>
</li>
      <li><a href="reference/introduction.html#index-1">lexical definitions</a>
</li>
      <li><a href="library/os.path.html#os.path.lexists">lexists() (in module os.path)</a>
</li>
      <li><a href="library/math.html#math.lgamma">lgamma() (in module math)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.lgettext">lgettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.lgettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.lgettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#module-lib2to3">lib2to3 (module)</a>
</li>
      <li><a href="library/platform.html#platform.libc_ver">libc_ver() (in module platform)</a>
</li>
      <li><a href="library/dbm.html#dbm.library">library (in module dbm)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLError.library">(ssl.SSLError attribute)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_dir_option">library_dir_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_filename">library_filename() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.library_option">library_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.LibraryLoader">LibraryLoader (class in ctypes)</a>
</li>
      <li><a href="library/constants.html#license">license (built-in variable)</a>
</li>
      <li><a href="library/queue.html#Queue.LifoQueue">LifoQueue (class in Queue)</a>
</li>
      <li><a href="library/thread.html#index-0">light-weight processes</a>
</li>
      <li><a href="library/fractions.html#fractions.Fraction.limit_denominator">limit_denominator() (fractions.Fraction method)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2adpcm">lin2adpcm() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2alaw">lin2alaw() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2lin">lin2lin() (in module audioop)</a>
</li>
      <li><a href="library/audioop.html#audioop.lin2ulaw">lin2ulaw() (in module audioop)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-5">line continuation</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-2">line joining</a>, <a href="reference/lexical_analysis.html#index-5">[1]</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-1">line structure</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.line">line() (msilib.Dialog method)</a>
</li>
      <li><a href="library/functions.html#index-4">line-buffered I/O</a>
</li>
      <li><a href="library/io.html#io.TextIOWrapper.line_buffering">line_buffering (io.TextIOWrapper attribute)</a>
</li>
      <li><a href="library/csv.html#csv.csvreader.line_num">line_num (csv.csvreader attribute)</a>
</li>
      <li><a href="library/linecache.html#module-linecache">linecache (module)</a>
</li>
      <li><a href="library/ast.html#ast.AST.lineno">lineno (ast.AST attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.lineno">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/doctest.html#doctest.Example.lineno">(doctest.Example attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Class.lineno">(pyclbr.Class attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Function.lineno">(pyclbr.Function attribute)</a>
</li>
        <li><a href="library/shlex.html#shlex.shlex.lineno">(shlex.shlex attribute)</a>
</li>
        <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.lineno">(xml.parsers.expat.ExpatError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.lineno">lineno() (in module fileinput)</a>
</li>
      <li><a href="library/curses.html#index-0">LINES</a>, <a href="library/curses.html#index-3">[1]</a>, <a href="library/curses.html#index-5">[2]</a>
</li>
      <li><a href="library/os.html#os.linesep">linesep (in module os)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.lineterminator">lineterminator (csv.Dialect attribute)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link">link() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="library/os.html#os.link">(in module os)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_executable">link_executable() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_shared_lib">link_shared_lib() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.link_shared_object">link_shared_object() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/macos.html#MacOS.linkmodel">linkmodel (in module MacOS)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.linkname">linkname (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/platform.html#platform.linux_distribution">linux_distribution() (in module platform)</a>
</li>
      <li><a href="glossary.html#term-list"><strong>list</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-6">assignment, target</a>
</li>
        <li><a href="reference/expressions.html#index-13">comprehensions</a>, <a href="reference/expressions.html#index-14">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-18">deletion target</a>
</li>
        <li><a href="reference/expressions.html#index-13">display</a>
</li>
        <li><a href="reference/expressions.html#index-14">empty</a>
</li>
        <li><a href="reference/expressions.html#index-76">expression</a>, <a href="reference/simple_stmts.html#index-1">[1]</a>, <a href="reference/simple_stmts.html#index-4">[2]</a>
</li>
        <li><a href="c-api/list.html#index-0">object</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="library/stdtypes.html#index-29">[2]</a>, <a href="reference/datamodel.html#index-26">[3]</a>, <a href="reference/expressions.html#index-14">[4]</a>, <a href="reference/expressions.html#index-30">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/expressions.html#index-35">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="reference/compound_stmts.html#index-6">target</a>, <a href="reference/simple_stmts.html#index-5">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-30">type, operations on</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-list-comprehension"><strong>list comprehension</strong></a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.list">list() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.list">(multiprocessing.managers.SyncManager method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.list">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.list">(poplib.POP3 method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.list">(tarfile.TarFile method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LIST_APPEND">LIST_APPEND (opcode)</a>
</li>
      <li><a href="library/csv.html#csv.list_dialects">list_dialects() (in module csv)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir.list_folders">list_folders() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.list_folders">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.MH.listallfolders">listallfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listallsubfolders">listallsubfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/dircache.html#dircache.listdir">listdir() (in module dircache)</a>

      <ul>
        <li><a href="library/os.html#os.listdir">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.listen">listen() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/logging.config.html#logging.config.listen">(in module logging.config)</a>
</li>
        <li><a href="library/turtle.html#turtle.listen">(in module turtle)</a>
</li>
        <li><a href="library/socket.html#socket.socket.listen">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.Listener">Listener (class in multiprocessing.connection)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listfolders">listfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.listmessages">listmessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.listMethods">listMethods() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li><a href="library/tix.html#Tix.ListNoteBook">ListNoteBook (class in Tix)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.listsubfolders">listsubfolders() (mhlib.MH method)</a>
</li>
      <li><a href="library/types.html#types.ListType">ListType (in module types)</a>
</li>
      <li><a href="reference/expressions.html#index-8">literal</a>, <a href="reference/lexical_analysis.html#index-11">[1]</a>
</li>
      <li><a href="library/ast.html#ast.literal_eval">literal_eval() (in module ast)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li>
    literals

      <ul>
        <li><a href="library/stdtypes.html#index-14">complex number</a>
</li>
        <li><a href="library/stdtypes.html#index-14">floating point</a>
</li>
        <li><a href="library/stdtypes.html#index-14">hexadecimal</a>
</li>
        <li><a href="library/stdtypes.html#index-14">integer</a>
</li>
        <li><a href="library/stdtypes.html#index-14">long integer</a>
</li>
        <li><a href="library/stdtypes.html#index-14">numeric</a>
</li>
        <li><a href="library/stdtypes.html#index-14">octal</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.LittleEndianStructure">LittleEndianStructure (class in ctypes)</a>
</li>
      <li><a href="library/string.html#string.ljust">ljust() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.ljust">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.LK_LOCK">LK_LOCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_NBLCK">LK_NBLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_NBRLCK">LK_NBRLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_RLCK">LK_RLCK (in module msvcrt)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.LK_UNLCK">LK_UNLCK (in module msvcrt)</a>
</li>
      <li><a href="library/smtplib.html#smtplib.LMTP">LMTP (class in smtplib)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.ln">ln() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.ln">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/getpass.html#index-2">LNAME</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.lngettext">lngettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.lngettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.lngettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.load">load() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.FileCookieJar.load">(cookielib.FileCookieJar method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.stats.load">(in module hotshot.stats)</a>
</li>
        <li><a href="library/json.html#json.load">(in module json)</a>
</li>
        <li><a href="library/marshal.html#marshal.load">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.load">(in module pickle)</a>
</li>
        <li><a href="library/pickle.html#pickle.Unpickler.load">(pickle.Unpickler method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LOAD_ATTR">LOAD_ATTR (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_cert_chain">load_cert_chain() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_CLOSURE">LOAD_CLOSURE (opcode)</a>
</li>
      <li><a href="library/imp.html#imp.load_compiled">load_compiled() (in module imp)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_CONST">LOAD_CONST (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_default_certs">load_default_certs() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_DEREF">LOAD_DEREF (opcode)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_dh_params">load_dh_params() (ssl.SSLContext method)</a>
</li>
      <li><a href="library/imp.html#imp.load_dynamic">load_dynamic() (in module imp)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.load_extension">load_extension() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_FAST">LOAD_FAST (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_GLOBAL">LOAD_GLOBAL (opcode)</a>
</li>
      <li><a href="library/pickle.html#index-4">load_global() (pickle protocol)</a>
</li>
      <li><a href="library/dis.html#opcode-LOAD_LOCALS">LOAD_LOCALS (opcode)</a>
</li>
      <li>
    load_module

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">loader</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.load_module">load_module() (in module imp)</a>

      <ul>
        <li><a href="library/zipimport.html#zipimport.zipimporter.load_module">(zipimport.zipimporter method)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-LOAD_NAME">LOAD_NAME (opcode)</a>
</li>
      <li><a href="library/imp.html#imp.load_source">load_source() (in module imp)</a>
</li>
      <li><a href="library/ssl.html#ssl.SSLContext.load_verify_locations">load_verify_locations() (ssl.SSLContext method)</a>
</li>
      <li><a href="reference/simple_stmts.html#index-44">loader</a>, <a href="glossary.html#term-loader"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-44">load_module</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.LoadError">LoadError</a>
</li>
      <li><a href="library/_winreg.html#_winreg.LoadKey">LoadKey() (in module _winreg)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.LibraryLoader.LoadLibrary">LoadLibrary() (ctypes.LibraryLoader method)</a>
</li>
      <li><a href="library/json.html#json.loads">loads() (in module json)</a>

      <ul>
        <li><a href="library/marshal.html#marshal.loads">(in module marshal)</a>
</li>
        <li><a href="library/pickle.html#pickle.loads">(in module pickle)</a>
</li>
        <li><a href="library/xmlrpclib.html#xmlrpclib.loads">(in module xmlrpclib)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromModule">loadTestsFromModule() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromName">loadTestsFromName() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromNames">loadTestsFromNames() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestLoader.loadTestsFromTestCase">loadTestsFromTestCase() (unittest.TestLoader method)</a>
</li>
      <li><a href="library/threading.html#threading.local">local (class in threading)</a>
</li>
      <li><a href="library/decimal.html#decimal.localcontext">localcontext() (in module decimal)</a>
</li>
      <li><a href="library/re.html#re.LOCALE">LOCALE (in module re)</a>
</li>
      <li><a href="library/locale.html#module-locale">locale (module)</a>
</li>
      <li><a href="library/locale.html#locale.localeconv">localeconv() (in module locale)</a>
</li>
      <li><a href="library/calendar.html#calendar.LocaleHTMLCalendar">LocaleHTMLCalendar (class in calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.LocaleTextCalendar">LocaleTextCalendar (class in calendar)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Attr.localName">localName (xml.dom.Attr attribute)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Node.localName">(xml.dom.Node attribute)</a>
</li>
      </ul></li>
      <li>
    locals

      <ul>
        <li><a href="reference/simple_stmts.html#index-58">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#locals">locals() (built-in function)</a>
</li>
      <li><a href="library/time.html#time.localtime">localtime() (in module time)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.Locator">Locator (class in xml.sax.xmlreader)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Lock">Lock (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.Lock">Lock() (in module threading)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Babyl.lock">lock() (mailbox.Babyl method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.lock">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MMDF.lock">(mailbox.MMDF method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.lock">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Maildir.lock">(mailbox.Maildir method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mbox.lock">(mailbox.mbox method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Lock">Lock() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex.lock">lock() (mutex.mutex method)</a>

      <ul>
        <li><a href="library/posixfile.html#posixfile.posixfile.lock">(posixfile.posixfile method)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#index-13">lock, interpreter</a>
</li>
      <li><a href="library/imp.html#imp.lock_held">lock_held() (in module imp)</a>
</li>
      <li><a href="library/thread.html#thread.lock.locked">locked() (thread.lock method)</a>
</li>
      <li><a href="library/fcntl.html#fcntl.lockf">lockf() (in module fcntl)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.locking">locking() (in module msvcrt)</a>
</li>
      <li><a href="library/thread.html#thread.LockType">LockType (in module thread)</a>
</li>
      <li><a href="library/cmath.html#cmath.log">log() (in module cmath)</a>

      <ul>
        <li><a href="library/logging.html#logging.log">(in module logging)</a>
</li>
        <li><a href="library/math.html#math.log">(in module math)</a>
</li>
        <li><a href="library/logging.html#logging.Logger.log">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.log10">log10() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.log10">(decimal.Decimal method)</a>
</li>
        <li><a href="library/cmath.html#cmath.log10">(in module cmath)</a>
</li>
        <li><a href="library/math.html#math.log10">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/math.html#math.log1p">log1p() (in module math)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_date_time_string">log_date_time_string() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_error">log_error() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.log_exception">log_exception() (wsgiref.handlers.BaseHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_message">log_message() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_request">log_request() (BaseHTTPServer.BaseHTTPRequestHandler method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.log_to_stderr">log_to_stderr() (in module multiprocessing)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.logb">logb() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logb">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#logging.Logger">Logger (class in logging)</a>
</li>
      <li><a href="library/logging.html#logging.LoggerAdapter">LoggerAdapter (class in logging)</a>
</li>
      <li>
    logging

      <ul>
        <li><a href="library/logging.html#index-0">Errors</a>
</li>
      </ul></li>
      <li><a href="library/logging.html#module-logging">logging (module)</a>
</li>
      <li><a href="library/logging.config.html#module-logging.config">logging.config (module)</a>
</li>
      <li><a href="library/logging.handlers.html#module-logging.handlers">logging.handlers (module)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Logical">Logical (class in aetypes)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-2">logical line</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.logical_and">logical_and() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_and">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_invert">logical_invert() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_invert">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_or">logical_or() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_or">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.logical_xor">logical_xor() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.logical_xor">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.login">login() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.login">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.login">(smtplib.SMTP method)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.login_cram_md5">login_cram_md5() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/getpass.html#index-0">LOGNAME</a>, <a href="library/os.html#index-2">[1]</a>
</li>
      <li><a href="library/random.html#random.lognormvariate">lognormvariate() (in module random)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.logout">logout() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/logging.html#logging.LogRecord">LogRecord (class in logging)</a>
</li>
      <li>
    long

      <ul>
        <li><a href="c-api/number.html#index-6">built-in function</a>, <a href="library/stdtypes.html#index-15">[1]</a>, <a href="library/string.html#index-8">[2]</a>, <a href="reference/datamodel.html#index-94">[3]</a>
</li>
        <li><a href="library/stdtypes.html#index-17">integer division</a>
</li>
        <li><a href="library/stdtypes.html#index-14">integer literals</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-long">long (2to3 fixer)</a>

      <ul>
        <li><a href="library/functions.html#long">(built-in class)</a>
</li>
      </ul></li>
      <li>
    long integer

      <ul>
        <li><a href="c-api/long.html#index-0">object</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-12">[2]</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">long integer literal</a>
</li>
      <li><a href="library/sys.html#sys.long_info">long_info (in module sys)</a>
</li>
      <li><a href="c-api/int.html#index-2">LONG_MAX</a>, <a href="c-api/long.html#index-2">[1]</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.longMessage">longMessage (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/curses.html#curses.longname">longname() (in module curses)</a>
</li>
      <li><a href="library/types.html#types.LongType">LongType (in module types)</a>

      <ul>
        <li><a href="c-api/long.html#index-1">(in modules types)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.lookup">lookup() (in module codecs)</a>

      <ul>
        <li><a href="library/unicodedata.html#unicodedata.lookup">(in module unicodedata)</a>
</li>
        <li><a href="library/symtable.html#symtable.SymbolTable.lookup">(symtable.SymbolTable method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Style.lookup">(ttk.Style method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.lookup_error">lookup_error() (in module codecs)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.LookupError">LookupError</a>
</li>
      <li>
    loop

      <ul>
        <li><a href="reference/compound_stmts.html#index-9">over mutable sequence</a>
</li>
        <li><a href="reference/compound_stmts.html#index-4">statement</a>, <a href="reference/compound_stmts.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-33">[2]</a>, <a href="reference/simple_stmts.html#index-37">[3]</a>
</li>
      </ul></li>
      <li>
    loop control

      <ul>
        <li><a href="reference/simple_stmts.html#index-35">target</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.loop">loop() (in module asyncore)</a>
</li>
      <li><a href="library/string.html#string.lower">lower() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.lower">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.lowercase">lowercase (in module string)</a>
</li>
      <li><a href="library/token.html#token.LPAR">LPAR (in module token)</a>
</li>
      <li><a href="library/os.html#os.lseek">lseek() (in module os)</a>
</li>
      <li><a href="library/operator.html#operator.lshift">lshift() (in module operator)</a>
</li>
      <li><a href="library/token.html#token.LSQB">LSQB (in module token)</a>
</li>
      <li><a href="library/os.html#os.lstat">lstat() (in module os)</a>
</li>
      <li><a href="library/string.html#string.lstrip">lstrip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.lstrip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.lsub">lsub() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/operator.html#operator.lt">lt() (in module operator)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.lt">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">Lundh, Fredrik</a>
</li>
      <li><a href="library/cookielib.html#cookielib.LWPCookieJar">LWPCookieJar (class in cookielib)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�	�N����html/genindex-M.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-M.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; M</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/re.html#re.M">M (in module re)</a>
</li>
      <li><a href="library/platform.html#platform.mac_ver">mac_ver() (in module platform)</a>
</li>
      <li>
    macerrors

      <ul>
        <li><a href="library/macos.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/undoc.html#module-macerrors">macerrors (module)</a>
</li>
      <li><a href="library/platform.html#platform.machine">machine() (in module platform)</a>
</li>
      <li><a href="library/macos.html#module-MacOS">MacOS (module)</a>
</li>
      <li><a href="library/macostools.html#module-macostools">macostools (module)</a>
</li>
      <li><a href="library/macpath.html#module-macpath">macpath (module)</a>
</li>
      <li><a href="library/undoc.html#module-macresource">macresource (module)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc.macros">macros (netrc.netrc attribute)</a>
</li>
      <li>
    mailbox

      <ul>
        <li><a href="library/rfc822.html#index-3">module</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Mailbox">Mailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#module-mailbox">mailbox (module)</a>
</li>
      <li><a href="library/mailcap.html#module-mailcap">mailcap (module)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.Maildir">Maildir (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage">MaildirMessage (class in mailbox)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.MailmanProxy">MailmanProxy (class in smtpd)</a>
</li>
      <li><a href="c-api/init.html#index-1">main()</a>, <a href="c-api/init.html#index-10">[1]</a>

      <ul>
        <li><a href="library/py_compile.html#py_compile.main">(in module py_compile)</a>
</li>
        <li><a href="library/unittest.html#unittest.main">(in module unittest)</a>
</li>
      </ul></li>
      <li><a href="library/framework.html#FrameWork.Application.mainloop">mainloop() (FrameWork.Application method)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.mainloop">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.major">major() (in module os)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_archive">make_archive() (in module distutils.archive_util)</a>

      <ul>
        <li><a href="library/shutil.html#shutil.make_archive">(in module shutil)</a>
</li>
      </ul></li>
      <li><a href="library/dis.html#opcode-MAKE_CLOSURE">MAKE_CLOSURE (opcode)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookieJar.make_cookies">make_cookies() (cookielib.CookieJar method)</a>
</li>
      <li><a href="library/fl.html#fl.make_form">make_form() (in module fl)</a>
</li>
      <li><a href="library/dis.html#opcode-MAKE_FUNCTION">MAKE_FUNCTION (opcode)</a>
</li>
      <li><a href="library/email.header.html#email.header.make_header">make_header() (in module email.header)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.make_msgid">make_msgid() (in module email.utils)</a>
</li>
      <li><a href="library/xml.sax.html#xml.sax.make_parser">make_parser() (in module xml.sax)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.simple_server.make_server">make_server() (in module wsgiref.simple_server)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_tarball">make_tarball() (in module distutils.archive_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.archive_util.make_zipfile">make_zipfile() (in module distutils.archive_util)</a>
</li>
      <li><a href="library/os.html#os.makedev">makedev() (in module os)</a>
</li>
      <li><a href="library/os.html#os.makedirs">makedirs() (in module os)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.makeelement">makeelement() (xml.etree.ElementTree.Element method)</a>
</li>
      <li><a href="reference/datamodel.html#index-58">makefile() (socket method)</a>

      <ul>
        <li><a href="library/socket.html#socket.socket.makefile">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.MH.makefolder">makefolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/logging.html#logging.makeLogRecord">makeLogRecord() (in module logging)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.makePickle">makePickle() (logging.handlers.SocketHandler method)</a>
</li>
      <li><a href="library/logging.html#logging.Logger.makeRecord">makeRecord() (logging.Logger method)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.DatagramHandler.makeSocket">makeSocket() (logging.handlers.DatagramHandler method)</a>

      <ul>
        <li><a href="library/logging.handlers.html#logging.handlers.SocketHandler.makeSocket">(logging.handlers.SocketHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.maketrans">maketrans() (in module string)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Application.makeusermenus">makeusermenus() (FrameWork.Application method)</a>
</li>
      <li><a href="c-api/memory.html#index-0">malloc()</a>
</li>
      <li>
    mangling

      <ul>
        <li><a href="reference/expressions.html#index-7">name</a>, <a href="tutorial/classes.html#index-1">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-map">map (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#map">map() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.map">(in module future_builtins)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map">(multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Style.map">(ttk.Style method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool.map_async">map_async() (multiprocessing.pool.multiprocessing.Pool method)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.map_table_b2">map_table_b2() (in module stringprep)</a>
</li>
      <li><a href="library/stringprep.html#stringprep.map_table_b3">map_table_b3() (in module stringprep)</a>
</li>
      <li><a href="library/fl.html#fl.mapcolor">mapcolor() (in module fl)</a>
</li>
      <li><a href="library/ic.html#ic.IC.mapfile">mapfile() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.mapfile">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/logging.handlers.html#logging.handlers.HTTPHandler.mapLogRecord">mapLogRecord() (logging.handlers.HTTPHandler method)</a>
</li>
      <li><a href="glossary.html#term-mapping"><strong>mapping</strong></a>

      <ul>
        <li><a href="c-api/concrete.html#index-2">object</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/expressions.html#index-32">[4]</a>, <a href="reference/simple_stmts.html#index-12">[5]</a>
</li>
        <li><a href="library/stdtypes.html#index-32">types, operations on</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.Mapping">Mapping (class in collections)</a>
</li>
      <li><a href="library/msilib.html#msilib.Control.mapping">mapping() (msilib.Control method)</a>
</li>
      <li><a href="library/collections.html#collections.MappingView">MappingView (class in collections)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.SysLogHandler.mapPriority">mapPriority() (logging.handlers.SysLogHandler method)</a>
</li>
      <li><a href="library/nis.html#nis.maps">maps() (in module nis)</a>
</li>
      <li><a href="library/ic.html#ic.IC.maptypecreator">maptypecreator() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.maptypecreator">(in module ic)</a>
</li>
      </ul></li>
      <li><a href="library/marshal.html#module-marshal">marshal (module)</a>
</li>
      <li>
    marshalling

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li>
    masking

      <ul>
        <li><a href="library/stdtypes.html#index-19">operations</a>
</li>
      </ul></li>
      <li><a href="library/nis.html#nis.match">match() (in module nis)</a>

      <ul>
        <li><a href="library/re.html#re.match">(in module re)</a>
</li>
        <li><a href="library/re.html#re.RegexObject.match">(re.RegexObject method)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.match_hostname">match_hostname() (in module ssl)</a>
</li>
      <li><a href="library/re.html#re.MatchObject">MatchObject (class in re)</a>
</li>
      <li>
    math

      <ul>
        <li><a href="library/cmath.html#index-0">module</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
      </ul></li>
      <li><a href="library/math.html#module-math">math (module)</a>
</li>
      <li>
    max

      <ul>
        <li><a href="library/stdtypes.html#index-22">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.max">max (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.max">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.max">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.max">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#max">max() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.max">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.max">(decimal.Decimal method)</a>
</li>
        <li><a href="library/audioop.html#audioop.max">(in module audioop)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.MAX_INTERPOLATION_DEPTH">MAX_INTERPOLATION_DEPTH (in module ConfigParser)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.max_mag">max_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.max_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/repr.html#repr.Repr.maxarray">maxarray (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxdeque">maxdeque (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxdict">maxdict (repr.Repr attribute)</a>
</li>
      <li><a href="library/unittest.html#unittest.TestCase.maxDiff">maxDiff (unittest.TestCase attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxfrozenset">maxfrozenset (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxint">maxint (in module sys)</a>
</li>
      <li><a href="library/collections.html#collections.deque.maxlen">maxlen (collections.deque attribute)</a>
</li>
      <li><a href="library/mimify.html#mimify.MAXLEN">MAXLEN (in module mimify)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlevel">maxlevel (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlist">maxlist (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxlong">maxlong (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxother">maxother (repr.Repr attribute)</a>
</li>
      <li><a href="library/audioop.html#audioop.maxpp">maxpp() (in module audioop)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxset">maxset (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxsize">maxsize (in module sys)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxstring">maxstring (repr.Repr attribute)</a>
</li>
      <li><a href="library/repr.html#repr.Repr.maxtuple">maxtuple (repr.Repr attribute)</a>
</li>
      <li><a href="library/sys.html#sys.maxunicode">maxunicode (in module sys)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar.maxval">maxval (EasyDialogs.ProgressBar attribute)</a>
</li>
      <li><a href="library/datetime.html#datetime.MAXYEAR">MAXYEAR (in module datetime)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONASTERISK">MB_ICONASTERISK (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONEXCLAMATION">MB_ICONEXCLAMATION (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONHAND">MB_ICONHAND (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_ICONQUESTION">MB_ICONQUESTION (in module winsound)</a>
</li>
      <li><a href="library/winsound.html#winsound.MB_OK">MB_OK (in module winsound)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mbox">mbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.mboxMessage">mboxMessage (class in mailbox)</a>
</li>
      <li><a href="library/md5.html#module-md5">md5 (module)</a>
</li>
      <li><a href="library/md5.html#md5.md5">md5() (in module md5)</a>
</li>
      <li><a href="library/types.html#types.MemberDescriptorType">MemberDescriptorType (in module types)</a>
</li>
      <li>
    membership

      <ul>
        <li><a href="reference/expressions.html#index-67">test</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes.memmove">memmove() (in module ctypes)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.MemoryError">MemoryError</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.MemoryHandler">MemoryHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview">memoryview (built-in class)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.memset">memset() (in module ctypes)</a>
</li>
      <li><a href="library/framework.html#FrameWork.Menu">Menu() (in module FrameWork)</a>
</li>
      <li><a href="library/framework.html#FrameWork.MenuBar">MenuBar() (in module FrameWork)</a>
</li>
      <li><a href="library/framework.html#FrameWork.MenuItem">MenuItem() (in module FrameWork)</a>
</li>
      <li><a href="library/heapq.html#heapq.merge">merge() (in module heapq)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message">Message (class in email.message)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.Message">(class in mailbox)</a>
</li>
        <li><a href="library/mhlib.html#mhlib.Message">(class in mhlib)</a>
</li>
        <li><a href="library/mimetools.html#mimetools.Message">(class in mimetools)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.Message">(class in rfc822)</a>
</li>
        <li><a href="library/basehttpserver.html#index-1">(in module mimetools)</a>
</li>
      </ul></li>
      <li><a href="library/hashlib.html#index-0">message digest, MD5</a>, <a href="library/md5.html#index-0">[1]</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.Message">Message() (in module EasyDialogs)</a>
</li>
      <li><a href="library/email.parser.html#email.message_from_file">message_from_file() (in module email)</a>
</li>
      <li><a href="library/email.parser.html#email.message_from_string">message_from_string() (in module email)</a>
</li>
      <li><a href="library/winsound.html#winsound.MessageBeep">MessageBeep() (in module winsound)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.MessageClass">MessageClass (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MessageError">MessageError</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MessageParseError">MessageParseError</a>
</li>
      <li><a href="library/curses.html#curses.meta">meta() (in module curses)</a>
</li>
      <li><a href="library/sys.html#sys.meta_path">meta_path (in module sys)</a>
</li>
      <li><a href="glossary.html#term-metaclass"><strong>metaclass</strong></a>

      <ul>
        <li><a href="library/2to3.html#2to3fixer-metaclass">(2to3 fixer)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.Option.metavar">metavar (optparse.Option attribute)</a>
</li>
      <li><a href="library/tix.html#Tix.Meter">Meter (class in Tix)</a>
</li>
      <li><a href="c-api/structures.html#METH_CLASS">METH_CLASS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_COEXIST">METH_COEXIST (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_KEYWORDS">METH_KEYWORDS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_NOARGS">METH_NOARGS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_O">METH_O (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_OLDARGS">METH_OLDARGS (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_STATIC">METH_STATIC (built-in variable)</a>
</li>
      <li><a href="c-api/structures.html#METH_VARARGS">METH_VARARGS (built-in variable)</a>
</li>
      <li><a href="glossary.html#term-method"><strong>method</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-45">built-in</a>
</li>
        <li><a href="reference/expressions.html#index-43">call</a>
</li>
        <li><a href="c-api/method.html#index-0">object</a>, <a href="library/stdtypes.html#index-38">[1]</a>, <a href="reference/datamodel.html#index-38">[2]</a>, <a href="reference/datamodel.html#index-45">[3]</a>, <a href="reference/expressions.html#index-43">[4]</a>, <a href="tutorial/classes.html#index-0">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-38">user-defined</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-method-resolution-order"><strong>method resolution order</strong></a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/2to3.html#2to3fixer-methodattrs">methodattrs (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.methodcaller">methodcaller() (in module operator)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.methodHelp">methodHelp() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li>
    methods

      <ul>
        <li><a href="library/stdtypes.html#index-23">string</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.methods">methods (pyclbr.Class attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ServerProxy.system.methodSignature">methodSignature() (xmlrpclib.ServerProxy.system method)</a>
</li>
      <li><a href="c-api/function.html#index-1">MethodType (in module types)</a>, <a href="c-api/method.html#index-1">[1]</a>, <a href="library/types.html#types.MethodType">[2]</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MH">MH (class in mailbox)</a>

      <ul>
        <li><a href="library/mhlib.html#mhlib.MH">(class in mhlib)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#module-mhlib">mhlib (module)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMailbox">MHMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage">MHMessage (class in mailbox)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.microsecond">microsecond (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.microsecond">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li>
    MIME

      <ul>
        <li><a href="library/base64.html#index-0">base64 encoding</a>
</li>
        <li><a href="library/mimetypes.html#index-0">content type</a>
</li>
        <li><a href="library/cgi.html#index-0">headers</a>, <a href="library/mimetypes.html#index-1">[1]</a>
</li>
        <li><a href="library/quopri.html#index-0">quoted-printable encoding</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#mimify.mime_decode_header">mime_decode_header() (in module mimify)</a>
</li>
      <li><a href="library/mimify.html#mimify.mime_encode_header">mime_encode_header() (in module mimify)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.application.MIMEApplication">MIMEApplication (class in email.mime.application)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.audio.MIMEAudio">MIMEAudio (class in email.mime.audio)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.base.MIMEBase">MIMEBase (class in email.mime.base)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.image.MIMEImage">MIMEImage (class in email.mime.image)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.message.MIMEMessage">MIMEMessage (class in email.mime.message)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.multipart.MIMEMultipart">MIMEMultipart (class in email.mime.multipart)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.nonmultipart.MIMENonMultipart">MIMENonMultipart (class in email.mime.nonmultipart)</a>
</li>
      <li><a href="library/email.mime.html#email.mime.text.MIMEText">MIMEText (class in email.mime.text)</a>
</li>
      <li>
    mimetools

      <ul>
        <li><a href="library/urllib.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/mimetools.html#module-mimetools">mimetools (module)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes">MimeTypes (class in mimetypes)</a>
</li>
      <li><a href="library/mimetypes.html#module-mimetypes">mimetypes (module)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter">MimeWriter (class in MimeWriter)</a>

      <ul>
        <li><a href="library/mimewriter.html#module-MimeWriter">(module)</a>
</li>
      </ul></li>
      <li><a href="library/mimify.html#module-mimify">mimify (module)</a>
</li>
      <li><a href="library/mimify.html#mimify.mimify">mimify() (in module mimify)</a>
</li>
      <li>
    min

      <ul>
        <li><a href="library/stdtypes.html#index-22">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.date.min">min (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.min">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.min">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.min">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#min">min() (built-in function)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.min">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.min">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.min_mag">min_mag() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.min_mag">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.MINEQUAL">MINEQUAL (in module token)</a>
</li>
      <li><a href="library/miniaeframe.html#module-MiniAEFrame">MiniAEFrame (module)</a>
</li>
      <li><a href="library/miniaeframe.html#MiniAEFrame.MiniApplication">MiniApplication (class in MiniAEFrame)</a>
</li>
      <li><a href="library/audioop.html#audioop.minmax">minmax() (in module audioop)</a>
</li>
      <li><a href="library/os.html#os.minor">minor() (in module os)</a>
</li>
      <li><a href="reference/expressions.html#index-48">minus</a>
</li>
      <li><a href="library/token.html#token.MINUS">MINUS (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.minus">minus() (decimal.Context method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.minute">minute (datetime.datetime attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.time.minute">(datetime.time attribute)</a>
</li>
      </ul></li>
      <li><a href="library/datetime.html#datetime.MINYEAR">MINYEAR (in module datetime)</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.mirrored">mirrored() (in module unicodedata)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.misc_header">misc_header (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.MissingSectionHeaderError">MissingSectionHeaderError</a>
</li>
      <li><a href="library/ossaudiodev.html#index-1">MIXERDEV</a>
</li>
      <li><a href="library/macostools.html#macostools.mkalias">mkalias() (in module macostools)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.mkd">mkd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/os.html#os.mkdir">mkdir() (in module os)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.mkdtemp">mkdtemp() (in module tempfile)</a>
</li>
      <li><a href="library/os.html#os.mkfifo">mkfifo() (in module os)</a>
</li>
      <li><a href="library/os.html#os.mknod">mknod() (in module os)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.mkpath">mkpath() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.dir_util.mkpath">(in module distutils.dir_util)</a>
</li>
      </ul></li>
      <li><a href="library/tempfile.html#tempfile.mkstemp">mkstemp() (in module tempfile)</a>
</li>
      <li><a href="library/tempfile.html#tempfile.mktemp">mktemp() (in module tempfile)</a>
</li>
      <li><a href="library/time.html#time.mktime">mktime() (in module time)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.mktime_tz">mktime_tz() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.mktime_tz">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/mmap.html#mmap.mmap">mmap (class in mmap)</a>

      <ul>
        <li><a href="library/mmap.html#module-mmap">(module)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MMDF">MMDF (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MmdfMailbox">MmdfMailbox (class in mailbox)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MMDFMessage">MMDFMessage (class in mailbox)</a>
</li>
      <li><a href="library/operator.html#operator.mod">mod() (in module operator)</a>
</li>
      <li><a href="library/stdtypes.html#file.mode">mode (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.FileIO.mode">(io.FileIO attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.mode">(ossaudiodev.oss_audio_device attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.mode">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.mode">mode() (in module turtle)</a>
</li>
      <li><a href="library/math.html#math.modf">modf() (in module math)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.modified">modified() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/msilib.html#msilib.View.Modify">Modify() (msilib.View method)</a>
</li>
      <li><a href="library/select.html#select.epoll.modify">modify() (select.epoll method)</a>

      <ul>
        <li><a href="library/select.html#select.poll.modify">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-module"><strong>module</strong></a>

      <ul>
        <li><a href="library/al.html#index-0">AL</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">CGIHTTPServer</a>
</li>
        <li><a href="library/miniaeframe.html#index-0">FrameWork</a>
</li>
        <li><a href="library/sunaudio.html#index-1">SUNAUDIODEV</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">SimpleHTTPServer</a>
</li>
        <li><a href="c-api/init.html#index-0">__builtin__</a>, <a href="c-api/intro.html#index-20">[1]</a>, <a href="reference/simple_stmts.html#index-57">[2]</a>, <a href="reference/toplevel_components.html#index-2">[3]</a>, <a href="tutorial/modules.html#index-7">[4]</a>
</li>
        <li><a href="c-api/init.html#index-0">__main__</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/runpy.html#index-0">[3]</a>, <a href="library/runpy.html#index-3">[4]</a>, <a href="reference/executionmodel.html#index-11">[5]</a>, <a href="reference/toplevel_components.html#index-2">[6]</a>, <a href="reference/toplevel_components.html#index-3">[7]</a>
</li>
        <li><a href="library/locale.html#index-0">_locale</a>
</li>
        <li><a href="reference/datamodel.html#index-28">array</a>
</li>
        <li><a href="library/binascii.html#index-0">base64</a>
</li>
        <li><a href="library/pdb.html#index-1">bdb</a>
</li>
        <li><a href="library/binascii.html#index-0">binhex</a>
</li>
        <li><a href="library/anydbm.html#index-0">bsddb</a>, <a href="library/dbhash.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
        <li><a href="c-api/init.html#index-21">builtins</a>
</li>
        <li><a href="library/copy_reg.html#index-0">cPickle</a>
</li>
        <li><a href="library/pdb.html#index-1">cmd</a>
</li>
        <li><a href="tutorial/modules.html#index-3">compileall</a>
</li>
        <li><a href="library/copy_reg.html#index-0">copy</a>
</li>
        <li><a href="library/pwd.html#index-0">crypt</a>
</li>
        <li><a href="library/anydbm.html#index-0">dbhash</a>
</li>
        <li><a href="library/anydbm.html#index-0">dbm</a>, <a href="library/gdbm.html#index-0">[1]</a>, <a href="library/shelve.html#index-1">[2]</a>, <a href="reference/datamodel.html#index-34">[3]</a>
</li>
        <li><a href="library/anydbm.html#index-0">dumbdbm</a>
</li>
        <li><a href="library/exceptions.html#index-3">errno</a>, <a href="library/socket.html#index-2">[1]</a>
</li>
        <li><a href="c-api/intro.html#index-20">exceptions</a>
</li>
        <li><a href="reference/datamodel.html#index-4">extension</a>
</li>
        <li><a href="library/stdtypes.html#index-35">fcntl</a>
</li>
        <li><a href="library/htmllib.html#index-1">formatter</a>
</li>
        <li><a href="library/anydbm.html#index-0">gdbm</a>, <a href="library/shelve.html#index-1">[1]</a>, <a href="reference/datamodel.html#index-34">[2]</a>
</li>
        <li><a href="library/fnmatch.html#index-2">glob</a>
</li>
        <li><a href="library/urllib.html#index-9">htmllib</a>
</li>
        <li><a href="library/ic.html#index-0">icglue</a>
</li>
        <li><a href="c-api/import.html#index-2">ihooks</a>
</li>
        <li><a href="library/functions.html#index-8">imp</a>
</li>
        <li><a href="reference/simple_stmts.html#index-38">importing</a>
</li>
        <li><a href="tutorial/inputoutput.html#index-1">json</a>
</li>
        <li><a href="library/imp.html#index-5">knee</a>, <a href="library/imputil.html#index-1">[1]</a>
</li>
        <li><a href="library/macos.html#index-0">macerrors</a>
</li>
        <li><a href="library/rfc822.html#index-3">mailbox</a>
</li>
        <li><a href="library/cmath.html#index-0">math</a>, <a href="library/stdtypes.html#index-18">[1]</a>
</li>
        <li><a href="library/urllib.html#index-1">mimetools</a>
</li>
        <li><a href="reference/datamodel.html#index-49">namespace</a>
</li>
        <li><a href="c-api/module.html#index-0">object</a>, <a href="reference/datamodel.html#index-47">[1]</a>, <a href="reference/expressions.html#index-30">[2]</a>
</li>
        <li><a href="library/posix.html#index-0">os</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/copy.html#index-0">pickle</a>, <a href="library/copy_reg.html#index-0">[1]</a>, <a href="library/marshal.html#index-0">[2]</a>, <a href="library/pickle.html#index-5">[3]</a>, <a href="library/shelve.html#index-0">[4]</a>
</li>
        <li><a href="library/os.html#index-12">pty</a>
</li>
        <li><a href="library/os.path.html#index-1">pwd</a>
</li>
        <li><a href="library/pyexpat.html#index-1">pyexpat</a>
</li>
        <li><a href="library/fnmatch.html#index-1">re</a>, <a href="library/stdtypes.html#index-27">[1]</a>, <a href="library/string.html#index-0">[2]</a>
</li>
        <li><a href="tutorial/interactive.html#index-0">readline</a>
</li>
        <li><a href="c-api/import.html#index-2">rexec</a>
</li>
        <li><a href="library/mimetools.html#index-0">rfc822</a>
</li>
        <li><a href="tutorial/interactive.html#index-0">rlcompleter</a>
</li>
        <li><a href="c-api/init.html#index-0">search path</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
        <li><a href="library/htmllib.html#index-1">sgmllib</a>
</li>
        <li><a href="library/marshal.html#index-0">shelve</a>
</li>
        <li><a href="c-api/exceptions.html#index-2">signal</a>, <a href="library/thread.html#index-2">[1]</a>
</li>
        <li><a href="library/site.html#index-3">sitecustomize</a>
</li>
        <li><a href="library/internet.html#index-1">socket</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
        <li><a href="library/os.html#index-16">stat</a>
</li>
        <li><a href="library/os.html#index-17">statvfs</a>
</li>
        <li><a href="library/locale.html#index-7">string</a>, <a href="library/locale.html#index-8">[1]</a>, <a href="library/stdtypes.html#index-27">[2]</a>
</li>
        <li><a href="library/socket.html#index-4">struct</a>
</li>
        <li><a href="library/sunaudio.html#index-2">sunaudiodev</a>
</li>
        <li><a href="c-api/init.html#index-0">sys</a>, <a href="c-api/init.html#index-21">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="reference/compound_stmts.html#index-11">[3]</a>, <a href="reference/simple_stmts.html#index-24">[4]</a>, <a href="reference/toplevel_components.html#index-2">[5]</a>, <a href="tutorial/modules.html#index-4">[6]</a>
</li>
        <li><a href="c-api/init.html#index-20">thread</a>
</li>
        <li><a href="library/stdtypes.html#index-42">types</a>
</li>
        <li><a href="library/httplib.html#index-1">urllib</a>
</li>
        <li><a href="library/urllib.html#index-11">urlparse</a>
</li>
        <li><a href="library/site.html#index-4">usercustomize</a>
</li>
        <li><a href="library/binascii.html#index-0">uu</a>
</li>
      </ul></li>
      <li><a href="library/pyclbr.html#pyclbr.Class.module">module (pyclbr.Class attribute)</a>

      <ul>
        <li><a href="library/pyclbr.html#pyclbr.Function.module">(pyclbr.Function attribute)</a>
</li>
      </ul></li>
      <li><a href="library/new.html#new.module">module() (in module new)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ModuleFinder">ModuleFinder (class in modulefinder)</a>
</li>
      <li><a href="library/modulefinder.html#module-modulefinder">modulefinder (module)</a>
</li>
      <li><a href="c-api/import.html#index-0">modules (in module sys)</a>, <a href="c-api/init.html#index-0">[1]</a>, <a href="library/sys.html#sys.modules">[2]</a>

      <ul>
        <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.modules">(modulefinder.ModuleFinder attribute)</a>
</li>
      </ul></li>
      <li><a href="c-api/module.html#index-1">ModuleType (in module types)</a>, <a href="library/types.html#types.ModuleType">[1]</a>
</li>
      <li><a href="reference/expressions.html#index-55">modulo</a>
</li>
      <li><a href="library/imageop.html#imageop.mono2grey">mono2grey() (in module imageop)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.month">month (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.month">(datetime.datetime attribute)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.month">month() (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.month_abbr">month_abbr (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.month_name">month_name (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.monthcalendar">monthcalendar() (in module calendar)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdatescalendar">monthdatescalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdays2calendar">monthdays2calendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.Calendar.monthdayscalendar">monthdayscalendar() (calendar.Calendar method)</a>
</li>
      <li><a href="library/calendar.html#calendar.monthrange">monthrange() (in module calendar)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel">Morsel (class in Cookie)</a>
</li>
      <li><a href="library/collections.html#collections.Counter.most_common">most_common() (collections.Counter method)</a>
</li>
      <li><a href="library/curses.html#curses.mouseinterval">mouseinterval() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.mousemask">mousemask() (in module curses)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.move">move() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/curses.html#curses.window.move">(curses.window method)</a>
</li>
        <li><a href="library/macostools.html#findertools.move">(in module findertools)</a>
</li>
        <li><a href="library/shutil.html#shutil.move">(in module shutil)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.move">(mmap.mmap method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.move">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.move_file">move_file() (distutils.ccompiler.CCompiler method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.file_util.move_file">(in module distutils.file_util)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.movemessage">movemessage() (mhlib.Folder method)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.MozillaCookieJar">MozillaCookieJar (class in cookielib)</a>
</li>
      <li><a href="glossary.html#term-mro"><strong>MRO</strong></a>
</li>
      <li><a href="library/stdtypes.html#class.mro">mro() (class method)</a>
</li>
      <li><a href="library/cd.html#cd.msftoframe">msftoframe() (in module cd)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPResponse.msg">msg (httplib.HTTPResponse attribute)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.msg">msg() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/msilib.html#index-0">msi</a>
</li>
      <li><a href="library/msilib.html#module-msilib">msilib (module)</a>
</li>
      <li><a href="library/msvcrt.html#module-msvcrt">msvcrt (module)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.mt_interact">mt_interact() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarInfo.mtime">mtime (tarfile.TarInfo attribute)</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser.mtime">mtime() (robotparser.RobotFileParser method)</a>
</li>
      <li><a href="library/audioop.html#audioop.mul">mul() (in module audioop)</a>

      <ul>
        <li><a href="library/operator.html#operator.mul">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.MultiCall">MultiCall (class in xmlrpclib)</a>
</li>
      <li><a href="library/multifile.html#multifile.MultiFile">MultiFile (class in multifile)</a>
</li>
      <li><a href="library/multifile.html#module-multifile">multifile (module)</a>
</li>
      <li><a href="library/re.html#re.MULTILINE">MULTILINE (in module re)</a>
</li>
      <li><a href="library/email.errors.html#email.errors.MultipartConversionError">MultipartConversionError</a>
</li>
      <li><a href="reference/expressions.html#index-53">multiplication</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.multiply">multiply() (decimal.Context method)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing">multiprocessing (module)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.connection">multiprocessing.connection (module)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.dummy">multiprocessing.dummy (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.multiprocessing.Manager">multiprocessing.Manager() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.managers">multiprocessing.managers (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool">multiprocessing.Pool (class in multiprocessing.pool)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.pool">multiprocessing.pool (module)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue">multiprocessing.queues.SimpleQueue (class in multiprocessing)</a>
</li>
      <li><a href="library/multiprocessing.html#module-multiprocessing.sharedctypes">multiprocessing.sharedctypes (module)</a>
</li>
      <li><a href="glossary.html#term-mutable"><strong>mutable</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-25">object</a>, <a href="reference/simple_stmts.html#index-10">[1]</a>, <a href="reference/simple_stmts.html#index-3">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-29">sequence types</a>
</li>
      </ul></li>
      <li><a href="reference/datamodel.html#index-1">mutable object</a>
</li>
      <li>
    mutable sequence

      <ul>
        <li><a href="reference/compound_stmts.html#index-9">loop over</a>
</li>
        <li><a href="reference/datamodel.html#index-25">object</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.MutableMapping">MutableMapping (class in collections)</a>
</li>
      <li><a href="library/collections.html#collections.MutableSequence">MutableSequence (class in collections)</a>
</li>
      <li><a href="library/collections.html#collections.MutableSet">MutableSet (class in collections)</a>
</li>
      <li><a href="library/userdict.html#UserString.MutableString">MutableString (class in UserString)</a>
</li>
      <li><a href="library/mutex.html#mutex.mutex">mutex (class in mutex)</a>

      <ul>
        <li><a href="library/mutex.html#module-mutex">(module)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.mvderwin">mvderwin() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.mvwin">mvwin() (curses.window method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.myrights">myrights() (imaplib.IMAP4 method)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�Z�[s[shtml/genindex-N.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-N.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; N</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/token.html#token.N_TOKENS">N_TOKENS (in module token)</a>
</li>
      <li><a href="reference/executionmodel.html#index-2">name</a>, <a href="reference/expressions.html#index-5">[1]</a>, <a href="reference/lexical_analysis.html#index-9">[2]</a>

      <ul>
        <li><a href="reference/compound_stmts.html#index-18">binding</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/executionmodel.html#index-2">[2]</a>, <a href="reference/simple_stmts.html#index-3">[3]</a>, <a href="reference/simple_stmts.html#index-38">[4]</a>, <a href="reference/simple_stmts.html#index-48">[5]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-54">binding, global</a>
</li>
        <li><a href="reference/compound_stmts.html#index-23">class</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">function</a>
</li>
        <li><a href="reference/expressions.html#index-7">mangling</a>, <a href="tutorial/classes.html#index-1">[1]</a>
</li>
        <li><a href="reference/simple_stmts.html#index-3">rebinding</a>
</li>
        <li><a href="reference/simple_stmts.html#index-19">unbinding</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.name">name (cookielib.Cookie attribute)</a>

      <ul>
        <li><a href="library/doctest.html#doctest.DocTest.name">(doctest.DocTest attribute)</a>
</li>
        <li><a href="library/stdtypes.html#file.name">(file attribute)</a>
</li>
        <li><a href="library/os.html#os.name">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.NAME">NAME (in module token)</a>
</li>
      <li><a href="library/io.html#io.FileIO.name">name (io.FileIO attribute)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.name">(multiprocessing.Process attribute)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.name">(ossaudiodev.oss_audio_device attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Class.name">(pyclbr.Class attribute)</a>
</li>
        <li><a href="library/pyclbr.html#pyclbr.Function.name">(pyclbr.Function attribute)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarInfo.name">(tarfile.TarInfo attribute)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.name">(threading.Thread attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Attr.name">(xml.dom.Attr attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.DocumentType.name">(xml.dom.DocumentType attribute)</a>
</li>
      </ul></li>
      <li><a href="library/unicodedata.html#unicodedata.name">name() (in module unicodedata)</a>
</li>
      <li><a href="library/htmllib.html#htmlentitydefs.name2codepoint">name2codepoint (in module htmlentitydefs)</a>
</li>
      <li><a href="glossary.html#term-named-tuple"><strong>named tuple</strong></a>
</li>
      <li><a href="library/tempfile.html#tempfile.NamedTemporaryFile">NamedTemporaryFile() (in module tempfile)</a>
</li>
      <li><a href="library/collections.html#collections.namedtuple">namedtuple() (in module collections)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.NameError">NameError</a>

      <ul>
        <li><a href="reference/expressions.html#index-6">exception</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-8">NameError (built-in exception)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.namelist">namelist() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/codecs.html#encodings.idna.nameprep">nameprep() (in module encodings.idna)</a>
</li>
      <li>
    names

      <ul>
        <li><a href="reference/expressions.html#index-7">private</a>
</li>
      </ul></li>
      <li><a href="reference/executionmodel.html#index-1">namespace</a>, <a href="glossary.html#term-namespace"><strong>[1]</strong></a>

      <ul>
        <li><a href="reference/datamodel.html#index-37">global</a>
</li>
        <li><a href="reference/datamodel.html#index-49">module</a>
</li>
      </ul></li>
      <li><a href="library/argparse.html#argparse.Namespace">Namespace (class in argparse)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.Namespace">(class in multiprocessing.managers)</a>
</li>
      </ul></li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.namespace">namespace() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Namespace">Namespace() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_DNS">NAMESPACE_DNS (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_OID">NAMESPACE_OID (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_URL">NAMESPACE_URL (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.NAMESPACE_X500">NAMESPACE_X500 (in module uuid)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NamespaceErr">NamespaceErr</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.namespaceURI">namespaceURI (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/functions.html#index-2">NaN</a>, <a href="library/string.html#index-6">[1]</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.NannyNag">NannyNag</a>
</li>
      <li><a href="library/curses.html#curses.napms">napms() (in module curses)</a>
</li>
      <li><a href="library/optparse.html#optparse.Option.nargs">nargs (optparse.Option attribute)</a>
</li>
      <li><a href="library/undoc.html#module-Nav">Nav (module)</a>
</li>
      <li><a href="library/easydialogs.html#index-0">Navigation Services</a>
</li>
      <li><a href="library/difflib.html#difflib.ndiff">ndiff() (in module difflib)</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.ndim">ndim (memoryview attribute)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-ne">ne (2to3 fixer)</a>
</li>
      <li><a href="library/operator.html#operator.ne">ne() (in module operator)</a>
</li>
      <li><a href="library/operator.html#operator.neg">neg() (in module operator)</a>
</li>
      <li><a href="reference/expressions.html#index-48">negation</a>
</li>
      <li><a href="glossary.html#term-nested-scope"><strong>nested scope</strong></a>
</li>
      <li><a href="library/contextlib.html#contextlib.nested">nested() (in module contextlib)</a>
</li>
      <li><a href="library/netrc.html#netrc.netrc">netrc (class in netrc)</a>

      <ul>
        <li><a href="library/netrc.html#module-netrc">(module)</a>
</li>
      </ul></li>
      <li><a href="library/netrc.html#netrc.NetrcParseError">NetrcParseError</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.netscape">netscape (cookielib.CookiePolicy attribute)</a>
</li>
      <li><a href="library/nntplib.html#index-0">Network News Transfer Protocol</a>
</li>
      <li><a href="library/new.html#module-new">new (module)</a>
</li>
      <li><a href="library/hmac.html#hmac.new">new() (in module hmac)</a>

      <ul>
        <li><a href="library/md5.html#md5.new">(in module md5)</a>
</li>
        <li><a href="library/sha.html#sha.new">(in module sha)</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-new-style-class"><strong>new-style class</strong></a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_alignment">new_alignment() (formatter.writer method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.new_compiler">new_compiler() (in module distutils.ccompiler)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_font">new_font() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_margin">new_margin() (formatter.writer method)</a>
</li>
      <li><a href="library/imp.html#imp.new_module">new_module() (in module imp)</a>
</li>
      <li><a href="library/curses.panel.html#curses.panel.new_panel">new_panel() (in module curses.panel)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_spacing">new_spacing() (formatter.writer method)</a>
</li>
      <li><a href="library/formatter.html#formatter.writer.new_styles">new_styles() (formatter.writer method)</a>
</li>
      <li><a href="library/al.html#al.newconfig">newconfig() (in module al)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer">newer() (in module distutils.dep_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer_group">newer_group() (in module distutils.dep_util)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dep_util.newer_pairwise">newer_pairwise() (in module distutils.dep_util)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.newgroups">newgroups() (nntplib.NNTP method)</a>
</li>
      <li>
    newline

      <ul>
        <li><a href="reference/simple_stmts.html#index-23">suppression</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.NEWLINE">NEWLINE (in module token)</a>
</li>
      <li><a href="reference/compound_stmts.html#index-2">NEWLINE token</a>, <a href="reference/lexical_analysis.html#index-2">[1]</a>
</li>
      <li><a href="library/stdtypes.html#file.newlines">newlines (file attribute)</a>

      <ul>
        <li><a href="library/io.html#io.TextIOBase.newlines">(io.TextIOBase attribute)</a>
</li>
      </ul></li>
      <li><a href="library/nntplib.html#nntplib.NNTP.newnews">newnews() (nntplib.NNTP method)</a>
</li>
      <li><a href="library/curses.html#curses.newpad">newpad() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.newwin">newwin() (in module curses)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-next">next (2to3 fixer)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.next">next() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/functions.html#next">(built-in function)</a>
</li>
        <li><a href="library/csv.html#csv.csvreader.next">(csv.csvreader method)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.dbhash.next">(dbhash.dbhash method)</a>
</li>
        <li><a href="library/stdtypes.html#file.next">(file method)</a>
</li>
        <li><a href="reference/expressions.html#generator.next">(generator method)</a>
</li>
        <li><a href="library/stdtypes.html#iterator.next">(iterator method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.oldmailbox.next">(mailbox.oldmailbox method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.next">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/nntplib.html#nntplib.NNTP.next">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.next">(tarfile.TarFile method)</a>
</li>
        <li><a href="library/ttk.html#ttk.Treeview.next">(ttk.Treeview method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_minus">next_minus() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_minus">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_plus">next_plus() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_plus">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.next_toward">next_toward() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.next_toward">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/fileinput.html#fileinput.nextfile">nextfile() (in module fileinput)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.nextkey">nextkey() (in module gdbm)</a>
</li>
      <li><a href="library/mimewriter.html#MimeWriter.MimeWriter.nextpart">nextpart() (MimeWriter.MimeWriter method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nextSibling">nextSibling (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.GNUTranslations.ngettext">ngettext() (gettext.GNUTranslations method)</a>

      <ul>
        <li><a href="library/gettext.html#gettext.NullTranslations.ngettext">(gettext.NullTranslations method)</a>
</li>
        <li><a href="library/gettext.html#gettext.ngettext">(in module gettext)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.nice">nice() (in module os)</a>
</li>
      <li><a href="library/nis.html#module-nis">nis (module)</a>
</li>
      <li><a href="library/sha.html#index-0">NIST</a>
</li>
      <li><a href="library/tokenize.html#tokenize.NL">NL (in module tokenize)</a>
</li>
      <li><a href="library/curses.html#curses.nl">nl() (in module curses)</a>
</li>
      <li><a href="library/locale.html#locale.nl_langinfo">nl_langinfo() (in module locale)</a>
</li>
      <li><a href="library/heapq.html#heapq.nlargest">nlargest() (in module heapq)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.nlst">nlst() (ftplib.FTP method)</a>
</li>
      <li>
    NNTP

      <ul>
        <li><a href="library/nntplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/nntplib.html#nntplib.NNTP">NNTP (class in nntplib)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPDataError">NNTPDataError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPError">NNTPError</a>
</li>
      <li><a href="library/nntplib.html#module-nntplib">nntplib (module)</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPPermanentError">NNTPPermanentError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPProtocolError">NNTPProtocolError</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTPReplyError">NNTPReplyError</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/nntplib.html#nntplib.NNTPTemporaryError">NNTPTemporaryError</a>
</li>
      <li><a href="library/urllib.html#index-4">no_proxy</a>, <a href="library/urllib.html#index-6">[1]</a>
</li>
      <li><a href="library/curses.html#curses.nocbreak">nocbreak() (in module curses)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NoDataAllowedErr">NoDataAllowedErr</a>
</li>
      <li><a href="library/compiler.html#compiler.ast.Node">Node (class in compiler.ast)</a>
</li>
      <li><a href="library/platform.html#platform.node">node() (in module platform)</a>
</li>
      <li><a href="library/curses.html#curses.window.nodelay">nodelay() (curses.window method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeName">nodeName (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/ast.html#ast.NodeTransformer">NodeTransformer (class in ast)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeType">nodeType (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.nodeValue">nodeValue (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/ast.html#ast.NodeVisitor">NodeVisitor (class in ast)</a>
</li>
      <li><a href="library/cd.html#cd.NODISC">NODISC (in module cd)</a>
</li>
      <li><a href="library/curses.html#curses.noecho">noecho() (in module curses)</a>
</li>
      <li><a href="library/locale.html#locale.NOEXPR">NOEXPR (in module locale)</a>
</li>
      <li><a href="library/htmllib.html#htmllib.HTMLParser.nofill">nofill (htmllib.HTMLParser attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.nok_builtin_names">nok_builtin_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/pickle.html#pickle.Unpickler.noload">noload() (pickle.Unpickler method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NoModificationAllowedErr">NoModificationAllowedErr</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.nonblock">nonblock() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li>
    None

      <ul>
        <li><a href="c-api/none.html#index-0">object</a>, <a href="reference/datamodel.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#index-3">None (Built-in object)</a>

      <ul>
        <li><a href="library/constants.html#None">(built-in variable)</a>
</li>
      </ul></li>
      <li><a href="library/types.html#types.NoneType">NoneType (in module types)</a>
</li>
      <li><a href="library/curses.html#curses.nonl">nonl() (in module curses)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-nonzero">nonzero (2to3 fixer)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.noop">noop() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/poplib.html#poplib.POP3.noop">(poplib.POP3 method)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.NoOptionError">NoOptionError</a>
</li>
      <li><a href="library/dis.html#opcode-NOP">NOP (opcode)</a>
</li>
      <li><a href="library/curses.html#curses.noqiflush">noqiflush() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.noraw">noraw() (in module curses)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.normalize">normalize() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.normalize">(decimal.Decimal method)</a>
</li>
        <li><a href="library/locale.html#locale.normalize">(in module locale)</a>
</li>
        <li><a href="library/unicodedata.html#unicodedata.normalize">(in module unicodedata)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Node.normalize">(xml.dom.Node method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.NORMALIZE_WHITESPACE">NORMALIZE_WHITESPACE (in module doctest)</a>
</li>
      <li><a href="library/random.html#random.normalvariate">normalvariate() (in module random)</a>
</li>
      <li><a href="library/os.path.html#os.path.normcase">normcase() (in module os.path)</a>
</li>
      <li><a href="library/os.path.html#os.path.normpath">normpath() (in module os.path)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.NoSectionError">NoSectionError</a>
</li>
      <li><a href="library/mailbox.html#mailbox.NoSuchMailboxError">NoSuchMailboxError</a>
</li>
      <li>
    not

      <ul>
        <li><a href="library/stdtypes.html#index-8">operator</a>, <a href="reference/expressions.html#index-70">[1]</a>
</li>
      </ul></li>
      <li>
    not in

      <ul>
        <li><a href="library/stdtypes.html#index-12">operator</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.not_">not_() (in module operator)</a>
</li>
      <li><a href="library/fpformat.html#fpformat.NotANumber">NotANumber</a>
</li>
      <li><a href="reference/introduction.html#index-0">notation</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.DTDHandler.notationDecl">notationDecl() (xml.sax.handler.DTDHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.NotationDeclHandler">NotationDeclHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.notations">notations (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/httplib.html#httplib.NotConnected">NotConnected</a>
</li>
      <li><a href="library/tix.html#Tix.NoteBook">NoteBook (class in Tix)</a>
</li>
      <li><a href="library/ttk.html#ttk.Notebook">Notebook (class in ttk)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.NotEmptyError">NotEmptyError</a>
</li>
      <li><a href="library/token.html#token.NOTEQUAL">NOTEQUAL (in module token)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NotFoundErr">NotFoundErr</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notify">notify() (threading.Condition method)</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notify_all">notify_all() (threading.Condition method)</a>
</li>
      <li><a href="library/threading.html#threading.Condition.notifyAll">notifyAll() (threading.Condition method)</a>
</li>
      <li><a href="library/curses.html#curses.window.notimeout">notimeout() (curses.window method)</a>
</li>
      <li>
    NotImplemented

      <ul>
        <li><a href="reference/datamodel.html#index-7">object</a>
</li>
      </ul></li>
      <li><a href="library/constants.html#NotImplemented">NotImplemented (built-in variable)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.NotImplementedError">NotImplementedError</a>
</li>
      <li><a href="library/types.html#types.NotImplementedType">NotImplementedType (in module types)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.NotStandaloneHandler">NotStandaloneHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.NotSupportedErr">NotSupportedErr</a>
</li>
      <li><a href="library/curses.html#curses.window.noutrefresh">noutrefresh() (curses.window method)</a>
</li>
      <li><a href="library/datetime.html#datetime.datetime.now">now() (datetime.datetime class method)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.NProperty">NProperty (class in aetypes)</a>
</li>
      <li><a href="library/signal.html#signal.NSIG">NSIG (in module signal)</a>
</li>
      <li><a href="library/heapq.html#heapq.nsmallest">nsmallest() (in module heapq)</a>
</li>
      <li><a href="library/token.html#token.NT_OFFSET">NT_OFFSET (in module token)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.handlers.NTEventLogHandler">NTEventLogHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/socket.html#socket.ntohl">ntohl() (in module socket)</a>
</li>
      <li><a href="library/socket.html#socket.ntohs">ntohs() (in module socket)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.ntransfercmd">ntransfercmd() (ftplib.FTP method)</a>
</li>
      <li>
    null

      <ul>
        <li><a href="reference/simple_stmts.html#index-17">operation</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.NullFormatter">NullFormatter (class in formatter)</a>
</li>
      <li><a href="library/logging.handlers.html#logging.NullHandler">NullHandler (class in logging)</a>
</li>
      <li><a href="library/imp.html#imp.NullImporter">NullImporter (class in imp)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations">NullTranslations (class in gettext)</a>
</li>
      <li><a href="library/formatter.html#formatter.NullWriter">NullWriter (class in formatter)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-18">number</a>

      <ul>
        <li><a href="reference/datamodel.html#index-16">complex</a>
</li>
        <li><a href="reference/datamodel.html#index-15">floating point</a>
</li>
      </ul></li>
      <li><a href="library/numbers.html#numbers.Number">Number (class in numbers)</a>
</li>
      <li><a href="library/token.html#token.NUMBER">NUMBER (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.number_class">number_class() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.number_class">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/numbers.html#module-numbers">numbers (module)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational.numerator">numerator (numbers.Rational attribute)</a>
</li>
      <li>
    numeric

      <ul>
        <li><a href="library/stdtypes.html#index-18">conversions</a>
</li>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
        <li><a href="c-api/concrete.html#index-0">object</a>, <a href="library/stdtypes.html#index-10">[1]</a>, <a href="library/stdtypes.html#index-13">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/datamodel.html#index-9">[4]</a>
</li>
        <li><a href="library/stdtypes.html#index-16">types, operations on</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">numeric literal</a>
</li>
      <li><a href="library/unicodedata.html#unicodedata.numeric">numeric() (in module unicodedata)</a>
</li>
      <li><a href="library/functions.html#index-6">Numerical Python</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-numliterals">numliterals (2to3 fixer)</a>
</li>
      <li><a href="library/gl.html#gl.nurbscurve">nurbscurve() (in module gl)</a>
</li>
      <li><a href="library/gl.html#gl.nurbssurface">nurbssurface() (in module gl)</a>
</li>
      <li><a href="library/gl.html#gl.nvarray">nvarray() (in module gl)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\nA������html/genindex-O.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-O.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; O</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/os.html#os.O_APPEND">O_APPEND (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_ASYNC">O_ASYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_BINARY">O_BINARY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_CREAT">O_CREAT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DIRECT">O_DIRECT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DIRECTORY">O_DIRECTORY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_DSYNC">O_DSYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_EXCL">O_EXCL (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_EXLOCK">O_EXLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NDELAY">O_NDELAY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOATIME">O_NOATIME (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOCTTY">O_NOCTTY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOFOLLOW">O_NOFOLLOW (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NOINHERIT">O_NOINHERIT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_NONBLOCK">O_NONBLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RANDOM">O_RANDOM (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RDONLY">O_RDONLY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RDWR">O_RDWR (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_RSYNC">O_RSYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SEQUENTIAL">O_SEQUENTIAL (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SHLOCK">O_SHLOCK (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SHORT_LIVED">O_SHORT_LIVED (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_SYNC">O_SYNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TEMPORARY">O_TEMPORARY (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TEXT">O_TEXT (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_TRUNC">O_TRUNC (in module os)</a>
</li>
      <li><a href="library/os.html#os.O_WRONLY">O_WRONLY (in module os)</a>
</li>
      <li><a href="reference/datamodel.html#index-0">object</a>, <a href="glossary.html#term-object"><strong>[1]</strong></a>

      <ul>
        <li><a href="library/stdtypes.html#index-13">Boolean</a>, <a href="reference/datamodel.html#index-13">[1]</a>
</li>
        <li><a href="c-api/cobject.html#index-0">CObject</a>
</li>
        <li><a href="c-api/capsule.html#index-0">Capsule</a>
</li>
        <li><a href="reference/datamodel.html#index-8">Ellipsis</a>
</li>
        <li><a href="c-api/none.html#index-0">None</a>, <a href="reference/datamodel.html#index-6">[1]</a>, <a href="reference/simple_stmts.html#index-2">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-7">NotImplemented</a>
</li>
        <li><a href="library/stdtypes.html#index-21">Unicode</a>
</li>
        <li><a href="c-api/buffer.html#index-0">buffer</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-44">built-in function</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-45">built-in method</a>, <a href="reference/expressions.html#index-43">[1]</a>
</li>
        <li><a href="c-api/bytearray.html#index-0">bytearray</a>, <a href="library/stdtypes.html#index-21">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-35">callable</a>, <a href="reference/expressions.html#index-38">[1]</a>
</li>
        <li><a href="c-api/class.html#index-0">class</a>, <a href="reference/compound_stmts.html#index-23">[1]</a>, <a href="reference/datamodel.html#index-46">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/expressions.html#index-44">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-46">class instance</a>, <a href="reference/datamodel.html#index-50">[1]</a>, <a href="reference/datamodel.html#index-54">[2]</a>, <a href="reference/expressions.html#index-45">[3]</a>
</li>
        <li><a href="c-api/code.html#index-0">code</a>, <a href="library/marshal.html#index-1">[1]</a>, <a href="library/stdtypes.html#index-39">[2]</a>, <a href="reference/datamodel.html#index-60">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-16">complex</a>
</li>
        <li><a href="c-api/complex.html#index-0">complex number</a>, <a href="library/stdtypes.html#index-13">[1]</a>
</li>
        <li><a href="extending/newtypes.html#index-0">deallocation</a>
</li>
        <li><a href="c-api/dict.html#index-0">dictionary</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-33">[2]</a>, <a href="reference/datamodel.html#index-50">[3]</a>, <a href="reference/datamodel.html#index-81">[4]</a>, <a href="reference/expressions.html#index-16">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/simple_stmts.html#index-12">[7]</a>
</li>
        <li><a href="c-api/file.html#index-0">file</a>, <a href="library/stdtypes.html#index-34">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>, <a href="reference/toplevel_components.html#index-8">[3]</a>, <a href="tutorial/inputoutput.html#index-0">[4]</a>
</li>
        <li><a href="extending/newtypes.html#index-0">finalization</a>
</li>
        <li><a href="c-api/float.html#index-0">floating point</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-15">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-64">frame</a>
</li>
        <li><a href="c-api/set.html#index-0">frozenset</a>, <a href="reference/datamodel.html#index-31">[1]</a>
</li>
        <li><a href="c-api/function.html#index-0">function</a>, <a href="reference/compound_stmts.html#index-18">[1]</a>, <a href="reference/datamodel.html#index-36">[2]</a>, <a href="reference/datamodel.html#index-44">[3]</a>, <a href="reference/expressions.html#index-42">[4]</a>, <a href="reference/expressions.html#index-43">[5]</a>
</li>
        <li><a href="reference/datamodel.html#index-62">generator</a>, <a href="reference/expressions.html#index-15">[1]</a>, <a href="reference/expressions.html#index-24">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-20">immutable</a>, <a href="reference/expressions.html#index-17">[1]</a>, <a href="reference/expressions.html#index-9">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-20">immutable sequence</a>
</li>
        <li><a href="c-api/class.html#index-2">instance</a>, <a href="reference/datamodel.html#index-46">[1]</a>, <a href="reference/datamodel.html#index-50">[2]</a>, <a href="reference/datamodel.html#index-54">[3]</a>, <a href="reference/expressions.html#index-45">[4]</a>
</li>
        <li><a href="c-api/int.html#index-0">integer</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-10">[2]</a>
</li>
        <li><a href="c-api/list.html#index-0">list</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="library/stdtypes.html#index-29">[2]</a>, <a href="reference/datamodel.html#index-26">[3]</a>, <a href="reference/expressions.html#index-14">[4]</a>, <a href="reference/expressions.html#index-30">[5]</a>, <a href="reference/expressions.html#index-32">[6]</a>, <a href="reference/expressions.html#index-35">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="c-api/long.html#index-0">long integer</a>, <a href="library/stdtypes.html#index-13">[1]</a>, <a href="reference/datamodel.html#index-12">[2]</a>
</li>
        <li><a href="c-api/concrete.html#index-2">mapping</a>, <a href="library/stdtypes.html#index-32">[1]</a>, <a href="reference/datamodel.html#index-32">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/expressions.html#index-32">[4]</a>, <a href="reference/simple_stmts.html#index-12">[5]</a>
</li>
        <li><a href="c-api/method.html#index-0">method</a>, <a href="library/stdtypes.html#index-38">[1]</a>, <a href="reference/datamodel.html#index-38">[2]</a>, <a href="reference/datamodel.html#index-45">[3]</a>, <a href="reference/expressions.html#index-43">[4]</a>, <a href="tutorial/classes.html#index-0">[5]</a>
</li>
        <li><a href="c-api/module.html#index-0">module</a>, <a href="reference/datamodel.html#index-47">[1]</a>, <a href="reference/expressions.html#index-30">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">mutable</a>, <a href="reference/simple_stmts.html#index-10">[1]</a>, <a href="reference/simple_stmts.html#index-3">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-25">mutable sequence</a>
</li>
        <li><a href="c-api/concrete.html#index-0">numeric</a>, <a href="library/stdtypes.html#index-10">[1]</a>, <a href="library/stdtypes.html#index-13">[2]</a>, <a href="reference/datamodel.html#index-56">[3]</a>, <a href="reference/datamodel.html#index-9">[4]</a>
</li>
        <li><a href="reference/datamodel.html#index-11">plain integer</a>
</li>
        <li><a href="reference/expressions.html#index-20">recursive</a>
</li>
        <li><a href="c-api/concrete.html#index-1">sequence</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/compound_stmts.html#index-6">[2]</a>, <a href="reference/datamodel.html#index-17">[3]</a>, <a href="reference/datamodel.html#index-56">[4]</a>, <a href="reference/expressions.html#index-32">[5]</a>, <a href="reference/expressions.html#index-35">[6]</a>, <a href="reference/expressions.html#index-67">[7]</a>, <a href="reference/simple_stmts.html#index-11">[8]</a>
</li>
        <li><a href="c-api/set.html#index-0">set</a>, <a href="library/stdtypes.html#index-31">[1]</a>, <a href="reference/datamodel.html#index-30">[2]</a>, <a href="reference/expressions.html#index-18">[3]</a>
</li>
        <li><a href="reference/datamodel.html#index-29">set type</a>
</li>
        <li><a href="reference/datamodel.html#index-89">slice</a>
</li>
        <li><a href="library/socket.html#index-1">socket</a>
</li>
        <li><a href="c-api/string.html#index-0">string</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-21">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>
</li>
        <li><a href="library/sys.html#index-1">traceback</a>, <a href="library/traceback.html#index-0">[1]</a>, <a href="reference/compound_stmts.html#index-11">[2]</a>, <a href="reference/datamodel.html#index-67">[3]</a>, <a href="reference/simple_stmts.html#index-32">[4]</a>
</li>
        <li><a href="c-api/tuple.html#index-0">tuple</a>, <a href="library/stdtypes.html#index-21">[1]</a>, <a href="reference/datamodel.html#index-24">[2]</a>, <a href="reference/expressions.html#index-32">[3]</a>, <a href="reference/expressions.html#index-35">[4]</a>, <a href="reference/expressions.html#index-77">[5]</a>
</li>
        <li><a href="c-api/intro.html#index-5">type</a>, <a href="c-api/type.html#index-0">[1]</a>, <a href="library/functions.html#index-7">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-23">unicode</a>
</li>
        <li><a href="reference/compound_stmts.html#index-18">user-defined function</a>, <a href="reference/datamodel.html#index-36">[1]</a>, <a href="reference/expressions.html#index-42">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-38">user-defined method</a>
</li>
        <li><a href="library/stdtypes.html#index-21">xrange</a>, <a href="library/stdtypes.html#index-28">[1]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#object">object (built-in class)</a>

      <ul>
        <li><a href="library/exceptions.html#exceptions.UnicodeError.object">(exceptions.UnicodeError attribute)</a>
</li>
      </ul></li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.object_filenames">object_filenames() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li>
    objects

      <ul>
        <li><a href="library/stdtypes.html#index-10">comparing</a>
</li>
        <li><a href="library/pickle.html#index-0">flattening</a>
</li>
        <li><a href="library/pickle.html#index-0">marshalling</a>
</li>
        <li><a href="library/pickle.html#index-0">persistent</a>
</li>
        <li><a href="library/pickle.html#index-0">pickling</a>
</li>
        <li><a href="library/pickle.html#index-0">serializing</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.ObjectSpecifier">ObjectSpecifier (class in aetypes)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.obufcount">obufcount() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.obuffree">obuffree() (ossaudiodev.oss_audio_device method)</a>
</li>
      <li>
    oct

      <ul>
        <li><a href="reference/datamodel.html#index-95">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#oct">oct() (built-in function)</a>

      <ul>
        <li><a href="library/future_builtins.html#future_builtins.oct">(in module future_builtins)</a>
</li>
      </ul></li>
      <li>
    octal

      <ul>
        <li><a href="library/stdtypes.html#index-14">literals</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">octal literal</a>
</li>
      <li><a href="library/string.html#string.octdigits">octdigits (in module string)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ExpatError.offset">offset (xml.parsers.expat.ExpatError attribute)</a>
</li>
      <li><a href="library/curses.html#curses.OK">OK (in module curses)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_builtin_modules">ok_builtin_modules (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_file_types">ok_file_types (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_path">ok_path (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_posix_names">ok_posix_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.ok_sys_names">ok_sys_names (rexec.RExec attribute)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.OleDLL">OleDLL (class in ctypes)</a>
</li>
      <li><a href="library/turtle.html#turtle.onclick">onclick() (in module turtle)</a>, <a href="library/turtle.html#turtle.onclick">[1]</a>
</li>
      <li><a href="library/turtle.html#turtle.ondrag">ondrag() (in module turtle)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.onecmd">onecmd() (cmd.Cmd method)</a>
</li>
      <li><a href="library/turtle.html#turtle.onkey">onkey() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.onrelease">onrelease() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.onscreenclick">onscreenclick() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.ontimer">ontimer() (in module turtle)</a>
</li>
      <li><a href="library/token.html#token.OP">OP (in module token)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_ALL">OP_ALL (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_CIPHER_SERVER_PREFERENCE">OP_CIPHER_SERVER_PREFERENCE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_ENABLE_MIDDLEBOX_COMPAT">OP_ENABLE_MIDDLEBOX_COMPAT (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_COMPRESSION">OP_NO_COMPRESSION (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_SSLv2">OP_NO_SSLv2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_SSLv3">OP_NO_SSLv3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1">OP_NO_TLSv1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_1">OP_NO_TLSv1_1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_2">OP_NO_TLSv1_2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_NO_TLSv1_3">OP_NO_TLSv1_3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_SINGLE_DH_USE">OP_SINGLE_DH_USE (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OP_SINGLE_ECDH_USE">OP_SINGLE_ECDH_USE (in module ssl)</a>
</li>
      <li>
    open

      <ul>
        <li><a href="reference/datamodel.html#index-58">built-in function</a>, <a href="tutorial/inputoutput.html#index-0">[1]</a>
</li>
      </ul></li>
      <li><a href="library/miniaeframe.html#index-0">Open Scripting Architecture</a>
</li>
      <li><a href="library/functions.html#open">open() (built-in function)</a>

      <ul>
        <li><a href="library/framework.html#FrameWork.DialogWindow.open">(FrameWork.DialogWindow method)</a>
</li>
        <li><a href="library/framework.html#FrameWork.Window.open">(FrameWork.Window method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.open">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.open">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/aifc.html#aifc.open">(in module aifc)</a>
</li>
        <li><a href="library/anydbm.html#anydbm.open">(in module anydbm)</a>
</li>
        <li><a href="library/cd.html#cd.open">(in module cd)</a>
</li>
        <li><a href="library/codecs.html#codecs.open">(in module codecs)</a>
</li>
        <li><a href="library/dbhash.html#dbhash.open">(in module dbhash)</a>
</li>
        <li><a href="library/dbm.html#dbm.open">(in module dbm)</a>
</li>
        <li><a href="library/dl.html#dl.open">(in module dl)</a>
</li>
        <li><a href="library/dumbdbm.html#dumbdbm.open">(in module dumbdbm)</a>
</li>
        <li><a href="library/gdbm.html#gdbm.open">(in module gdbm)</a>
</li>
        <li><a href="library/gzip.html#gzip.open">(in module gzip)</a>
</li>
        <li><a href="library/io.html#io.open">(in module io)</a>
</li>
        <li><a href="library/os.html#os.open">(in module os)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.open">(in module ossaudiodev)</a>
</li>
        <li><a href="library/posixfile.html#posixfile.open">(in module posixfile)</a>
</li>
        <li><a href="library/shelve.html#shelve.open">(in module shelve)</a>
</li>
        <li><a href="library/sunau.html#sunau.open">(in module sunau)</a>
</li>
        <li><a href="library/sunaudio.html#sunaudiodev.open">(in module sunaudiodev)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.open">(in module tarfile)</a>
</li>
        <li><a href="library/wave.html#wave.open">(in module wave)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.open">(in module webbrowser)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.open">(pipes.Template method)</a>
</li>
        <li><a href="library/tarfile.html#tarfile.TarFile.open">(tarfile.TarFile class method)</a>
</li>
        <li><a href="library/telnetlib.html#telnetlib.Telnet.open">(telnetlib.Telnet method)</a>
</li>
        <li><a href="library/urllib.html#urllib.URLopener.open">(urllib.URLopener method)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.OpenerDirector.open">(urllib2.OpenerDirector method)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.controller.open">(webbrowser.controller method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.open">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/webbrowser.html#webbrowser.open_new">open_new() (in module webbrowser)</a>

      <ul>
        <li><a href="library/webbrowser.html#webbrowser.controller.open_new">(webbrowser.controller method)</a>
</li>
      </ul></li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/webbrowser.html#webbrowser.open_new_tab">open_new_tab() (in module webbrowser)</a>

      <ul>
        <li><a href="library/webbrowser.html#webbrowser.controller.open_new_tab">(webbrowser.controller method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.open_osfhandle">open_osfhandle() (in module msvcrt)</a>
</li>
      <li><a href="library/urllib.html#urllib.URLopener.open_unknown">open_unknown() (urllib.URLopener method)</a>
</li>
      <li><a href="library/msilib.html#msilib.OpenDatabase">OpenDatabase() (in module msilib)</a>
</li>
      <li><a href="library/dircache.html#dircache.opendir">opendir() (in module dircache)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.OpenerDirector">OpenerDirector (class in urllib2)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.MH.openfolder">openfolder() (mhlib.MH method)</a>
</li>
      <li><a href="library/sunau.html#sunau.openfp">openfp() (in module sunau)</a>

      <ul>
        <li><a href="library/wave.html#wave.openfp">(in module wave)</a>
</li>
      </ul></li>
      <li><a href="library/gl.html#index-0">OpenGL</a>
</li>
      <li><a href="library/_winreg.html#_winreg.OpenKey">OpenKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.OpenKeyEx">OpenKeyEx() (in module _winreg)</a>
</li>
      <li><a href="library/syslog.html#syslog.openlog">openlog() (in module syslog)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Message.openmessage">openmessage() (mhlib.Message method)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.openmixer">openmixer() (in module ossaudiodev)</a>
</li>
      <li><a href="library/al.html#al.openport">openport() (in module al)</a>
</li>
      <li><a href="library/os.html#os.openpty">openpty() (in module os)</a>

      <ul>
        <li><a href="library/pty.html#pty.openpty">(in module pty)</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.openrf">openrf() (in module MacOS)</a>
</li>
      <li>
    OpenSSL

      <ul>
        <li><a href="library/hashlib.html#index-2">(use in module hashlib)</a>
</li>
        <li><a href="library/ssl.html#index-0">(use in module ssl)</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION">OPENSSL_VERSION (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION_INFO">OPENSSL_VERSION_INFO (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.OPENSSL_VERSION_NUMBER">OPENSSL_VERSION_NUMBER (in module ssl)</a>
</li>
      <li><a href="library/msilib.html#msilib.Database.OpenView">OpenView() (msilib.Database method)</a>
</li>
      <li>
    operation

      <ul>
        <li><a href="reference/expressions.html#index-69">Boolean</a>
</li>
        <li><a href="reference/expressions.html#index-52">binary arithmetic</a>
</li>
        <li><a href="reference/expressions.html#index-60">binary bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-22">concatenation</a>
</li>
        <li><a href="library/stdtypes.html#index-22">extended slice</a>
</li>
        <li><a href="reference/simple_stmts.html#index-17">null</a>
</li>
        <li><a href="library/stdtypes.html#index-22">repetition</a>
</li>
        <li><a href="reference/expressions.html#index-58">shifting</a>
</li>
        <li><a href="library/stdtypes.html#index-22">slice</a>
</li>
        <li><a href="library/stdtypes.html#index-22">subscript</a>
</li>
        <li><a href="reference/expressions.html#index-47">unary arithmetic</a>
</li>
        <li><a href="reference/expressions.html#index-47">unary bitwise</a>
</li>
      </ul></li>
      <li>
    operations

      <ul>
        <li><a href="library/stdtypes.html#index-2">Boolean</a>, <a href="library/stdtypes.html#index-7">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-19">bitwise</a>
</li>
        <li><a href="library/stdtypes.html#index-19">masking</a>
</li>
        <li><a href="library/stdtypes.html#index-19">shifting</a>
</li>
      </ul></li>
      <li>
    operations on

      <ul>
        <li><a href="library/stdtypes.html#index-32">dictionary type</a>
</li>
        <li><a href="library/stdtypes.html#index-19">integer types</a>
</li>
        <li><a href="library/stdtypes.html#index-30">list type</a>
</li>
        <li><a href="library/stdtypes.html#index-32">mapping types</a>
</li>
        <li><a href="library/stdtypes.html#index-16">numeric types</a>
</li>
        <li><a href="library/stdtypes.html#index-22">sequence types</a>, <a href="library/stdtypes.html#index-30">[1]</a>
</li>
      </ul></li>
      <li>
    operator

      <ul>
        <li><a href="library/stdtypes.html#index-9">!=</a>
</li>
        <li><a href="library/stdtypes.html#index-15">%</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&amp;</a>
</li>
        <li><a href="library/stdtypes.html#index-15">*</a>
</li>
        <li><a href="library/stdtypes.html#index-15">**</a>
</li>
        <li><a href="library/stdtypes.html#index-15">+</a>
</li>
        <li><a href="library/stdtypes.html#index-15">-</a>
</li>
        <li><a href="library/stdtypes.html#index-15">/</a>
</li>
        <li><a href="library/stdtypes.html#index-15">//</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&lt;</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&lt;&lt;</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&lt;=</a>
</li>
        <li><a href="library/stdtypes.html#index-9">==</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&gt;</a>
</li>
        <li><a href="library/stdtypes.html#index-9">&gt;=</a>
</li>
        <li><a href="library/stdtypes.html#index-19">&gt;&gt;</a>
</li>
        <li><a href="library/stdtypes.html#index-19">^</a>
</li>
        <li><a href="library/stdtypes.html#index-6">and</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-71">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">comparison</a>
</li>
        <li><a href="library/stdtypes.html#index-12">in</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">is</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-9">is not</a>, <a href="reference/expressions.html#index-68">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-8">not</a>, <a href="reference/expressions.html#index-70">[1]</a>
</li>
        <li><a href="library/stdtypes.html#index-12">not in</a>, <a href="library/stdtypes.html#index-22">[1]</a>, <a href="reference/expressions.html#index-67">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-6">or</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-72">[2]</a>
</li>
        <li><a href="reference/datamodel.html#index-72">overloading</a>
</li>
        <li><a href="reference/expressions.html#index-80">precedence</a>
</li>
        <li><a href="reference/expressions.html#index-73">ternary</a>
</li>
        <li><a href="library/stdtypes.html#index-19">|</a>
</li>
        <li><a href="library/stdtypes.html#index-19">~</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#module-operator">operator (module)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-19">operators</a>
</li>
      <li><a href="library/dis.html#dis.opmap">opmap (in module dis)</a>
</li>
      <li><a href="library/dis.html#dis.opname">opname (in module dis)</a>
</li>
      <li><a href="library/pickletools.html#pickletools.optimize">optimize() (in module pickletools)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionGroup">OptionGroup (class in optparse)</a>
</li>
      <li><a href="library/tix.html#Tix.OptionMenu">OptionMenu (class in Tix)</a>
</li>
      <li><a href="library/optparse.html#optparse.OptionParser">OptionParser (class in optparse)</a>
</li>
      <li><a href="library/doctest.html#doctest.Example.options">options (doctest.Example attribute)</a>

      <ul>
        <li><a href="library/ssl.html#ssl.SSLContext.options">(ssl.SSLContext attribute)</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.options">options() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.optionxform">optionxform() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/optparse.html#module-optparse">optparse (module)</a>
</li>
      <li>
    or

      <ul>
        <li><a href="reference/expressions.html#index-63">bitwise</a>
</li>
        <li><a href="reference/expressions.html#index-62">exclusive</a>
</li>
        <li><a href="reference/expressions.html#index-63">inclusive</a>
</li>
        <li><a href="library/stdtypes.html#index-6">operator</a>, <a href="library/stdtypes.html#index-8">[1]</a>, <a href="reference/expressions.html#index-72">[2]</a>
</li>
      </ul></li>
      <li><a href="library/operator.html#operator.or_">or_() (in module operator)</a>
</li>
      <li>
    ord

      <ul>
        <li><a href="reference/datamodel.html#index-21">built-in function</a>, <a href="reference/datamodel.html#index-22">[1]</a>, <a href="reference/datamodel.html#index-23">[2]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#ord">ord() (built-in function)</a>
</li>
      <li>
    order

      <ul>
        <li><a href="reference/expressions.html#index-79">evaluation</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ordered_attributes">ordered_attributes (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li><a href="library/collections.html#collections.OrderedDict">OrderedDict (class in collections)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.Ordinal">Ordinal (class in aetypes)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.origin_server">origin_server (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li>
    os

      <ul>
        <li><a href="library/posix.html#index-0">module</a>, <a href="library/stdtypes.html#index-34">[1]</a>
</li>
      </ul></li>
      <li><a href="library/os.html#module-os">os (module)</a>
</li>
      <li><a href="library/os.path.html#module-os.path">os.path (module)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.os_environ">os_environ (wsgiref.handlers.BaseHandler attribute)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.OSError">OSError</a>
</li>
      <li><a href="library/ossaudiodev.html#module-ossaudiodev">ossaudiodev (module)</a>
</li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.OSSAudioError">OSSAudioError</a>
</li>
      <li><a href="reference/simple_stmts.html#index-2">output</a>, <a href="reference/simple_stmts.html#index-23">[1]</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">standard</a>, <a href="reference/simple_stmts.html#index-24">[1]</a>
</li>
      </ul></li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError.output">output (subprocess.CalledProcessError attribute)</a>
</li>
      <li><a href="library/cookie.html#Cookie.BaseCookie.output">output() (Cookie.BaseCookie method)</a>

      <ul>
        <li><a href="library/cookie.html#Cookie.Morsel.output">(Cookie.Morsel method)</a>
</li>
      </ul></li>
      <li><a href="library/email.charset.html#email.charset.Charset.output_charset">output_charset (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/gettext.html#gettext.NullTranslations.output_charset">output_charset() (gettext.NullTranslations method)</a>
</li>
      <li><a href="library/email.charset.html#email.charset.Charset.output_codec">output_codec (email.charset.Charset attribute)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker.output_difference">output_difference() (doctest.OutputChecker method)</a>
</li>
      <li><a href="library/doctest.html#doctest.OutputChecker">OutputChecker (class in doctest)</a>
</li>
      <li><a href="library/cookie.html#Cookie.Morsel.OutputString">OutputString() (Cookie.Morsel method)</a>
</li>
      <li><a href="library/stringio.html#cStringIO.OutputType">OutputType (in module cStringIO)</a>
</li>
      <li><a href="library/decimal.html#decimal.Overflow">Overflow (class in decimal)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.OverflowError">OverflowError</a>

      <ul>
        <li><a href="c-api/long.html#index-2">(built-in exception)</a>, <a href="c-api/long.html#index-3">[1]</a>, <a href="c-api/long.html#index-4">[2]</a>, <a href="c-api/long.html#index-5">[3]</a>, <a href="c-api/long.html#index-6">[4]</a>, <a href="reference/datamodel.html#index-11">[5]</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.window.overlay">overlay() (curses.window method)</a>
</li>
      <li>
    overloading

      <ul>
        <li><a href="reference/datamodel.html#index-72">operator</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#index-0">Overmars, Mark</a>
</li>
      <li><a href="library/curses.html#curses.window.overwrite">overwrite() (curses.window method)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�����html/genindex-P.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-P.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; P</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/os.html#os.P_DETACH">P_DETACH (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_NOWAIT">P_NOWAIT (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_NOWAITO">P_NOWAITO (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_OVERLAY">P_OVERLAY (in module os)</a>
</li>
      <li><a href="library/os.html#os.P_WAIT">P_WAIT (in module os)</a>
</li>
      <li><a href="library/aepack.html#aepack.pack">pack() (in module aepack)</a>

      <ul>
        <li><a href="library/struct.html#struct.pack">(in module struct)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.pack">(mailbox.MH method)</a>
</li>
        <li><a href="library/struct.html#struct.Struct.pack">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_array">pack_array() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_bytes">pack_bytes() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_double">pack_double() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_farray">pack_farray() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_float">pack_float() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_fopaque">pack_fopaque() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_fstring">pack_fstring() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/struct.html#struct.pack_into">pack_into() (in module struct)</a>

      <ul>
        <li><a href="library/struct.html#struct.Struct.pack_into">(struct.Struct method)</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_list">pack_list() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_opaque">pack_opaque() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/xdrlib.html#xdrlib.Packer.pack_string">pack_string() (xdrlib.Packer method)</a>
</li>
      <li><a href="library/site.html#index-2">package</a>, <a href="reference/simple_stmts.html#index-39">[1]</a>, <a href="glossary.html#term-package"><strong>[2]</strong></a>
</li>
      <li>
    package variable

      <ul>
        <li><a href="c-api/import.html#index-0">__all__</a>
</li>
      </ul></li>
      <li><a href="library/xdrlib.html#xdrlib.Packer">Packer (class in xdrlib)</a>
</li>
      <li><a href="library/aetools.html#aetools.packevent">packevent() (in module aetools)</a>
</li>
      <li>
    packing

      <ul>
        <li><a href="library/struct.html#index-0">binary data</a>
</li>
      </ul></li>
      <li><a href="library/tkinter.html#index-0">packing (widgets)</a>
</li>
      <li><a href="library/pdb.html#index-3">PAGER</a>, <a href="library/pydoc.html#index-1">[1]</a>
</li>
      <li><a href="library/curses.html#curses.pair_content">pair_content() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.pair_number">pair_number() (in module curses)</a>
</li>
      <li><a href="library/tix.html#Tix.PanedWindow">PanedWindow (class in Tix)</a>
</li>
      <li><a href="glossary.html#term-parameter"><strong>parameter</strong></a>

      <ul>
        <li><a href="reference/expressions.html#index-39">call semantics</a>
</li>
        <li><a href="faq/programming.html#index-1">difference from argument</a>
</li>
        <li><a href="reference/compound_stmts.html#index-17">function definition</a>
</li>
        <li><a href="reference/compound_stmts.html#index-20">value, default</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.pardir">pardir (in module os)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-paren">paren (2to3 fixer)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.BaseHandler.parent">parent (urllib2.BaseHandler attribute)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.parent">parent() (ttk.Treeview method)</a>
</li>
      <li><a href="reference/expressions.html#index-10">parenthesized form</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.parentNode">parentNode (xml.dom.Node attribute)</a>
</li>
      <li><a href="library/random.html#random.paretovariate">paretovariate() (in module random)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestParser.parse">parse() (doctest.DocTestParser method)</a>

      <ul>
        <li><a href="library/email.parser.html#email.parser.Parser.parse">(email.parser.Parser method)</a>
</li>
        <li><a href="library/ast.html#ast.parse">(in module ast)</a>
</li>
        <li><a href="library/cgi.html#cgi.parse">(in module cgi)</a>
</li>
        <li><a href="library/compiler.html#compiler.parse">(in module compiler)</a>
</li>
        <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.parse">(in module xml.dom.minidom)</a>
</li>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.parse">(in module xml.dom.pulldom)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.parse">(in module xml.etree.ElementTree)</a>
</li>
        <li><a href="library/xml.sax.html#xml.sax.parse">(in module xml.sax)</a>
</li>
        <li><a href="library/robotparser.html#robotparser.RobotFileParser.parse">(robotparser.RobotFileParser method)</a>
</li>
        <li><a href="library/string.html#string.Formatter.parse">(string.Formatter method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.parse">(xml.etree.ElementTree.ElementTree method)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.Parse">Parse() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.XMLReader.parse">parse() (xml.sax.xmlreader.XMLReader method)</a>
</li>
      <li><a href="library/readline.html#readline.parse_and_bind">parse_and_bind() (in module readline)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.parse_args">parse_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.PARSE_COLNAMES">PARSE_COLNAMES (in module sqlite3)</a>
</li>
      <li><a href="library/sysconfig.html#sysconfig.parse_config_h">parse_config_h() (in module sysconfig)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.PARSE_DECLTYPES">PARSE_DECLTYPES (in module sqlite3)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_header">parse_header() (in module cgi)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.parse_known_args">parse_known_args() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_multipart">parse_multipart() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.parse_qs">parse_qs() (in module cgi)</a>

      <ul>
        <li><a href="library/urlparse.html#urlparse.parse_qs">(in module urlparse)</a>
</li>
      </ul></li>
      <li><a href="library/cgi.html#cgi.parse_qsl">parse_qsl() (in module cgi)</a>

      <ul>
        <li><a href="library/urlparse.html#urlparse.parse_qsl">(in module urlparse)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parseaddr">parseaddr() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parseaddr">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parsedate">parsedate() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parsedate">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/email.utils.html#email.utils.parsedate_tz">parsedate_tz() (in module email.utils)</a>

      <ul>
        <li><a href="library/rfc822.html#rfc822.parsedate_tz">(in module rfc822)</a>
</li>
      </ul></li>
      <li><a href="library/compiler.html#compiler.parseFile">parseFile() (in module compiler)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ParseFile">ParseFile() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.ParseFlags">ParseFlags() (in module imaplib)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-0">parser</a>
</li>
      <li><a href="library/email.parser.html#email.parser.Parser">Parser (class in email.parser)</a>
</li>
      <li><a href="library/parser.html#module-parser">parser (module)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.ParserCreate">ParserCreate() (in module xml.parsers.expat)</a>
</li>
      <li><a href="library/parser.html#parser.ParserError">ParserError</a>
</li>
      <li><a href="library/urlparse.html#urlparse.ParseResult">ParseResult (class in urlparse)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.parsesequence">parsesequence() (mhlib.Folder method)</a>
</li>
      <li><a href="library/email.parser.html#email.parser.Parser.parsestr">parsestr() (email.parser.Parser method)</a>
</li>
      <li><a href="library/xml.dom.minidom.html#xml.dom.minidom.parseString">parseString() (in module xml.dom.minidom)</a>

      <ul>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.parseString">(in module xml.dom.pulldom)</a>
</li>
        <li><a href="library/xml.sax.html#xml.sax.parseString">(in module xml.sax)</a>
</li>
      </ul></li>
      <li><a href="library/ic.html#ic.IC.parseurl">parseurl() (ic.IC method)</a>

      <ul>
        <li><a href="library/ic.html#ic.parseurl">(in module ic)</a>
</li>
      </ul></li>
      <li>
    parsing

      <ul>
        <li><a href="library/parser.html#index-0">Python source code</a>
</li>
        <li><a href="library/urlparse.html#index-0">URL</a>
</li>
      </ul></li>
      <li><a href="library/configparser.html#ConfigParser.ParsingError">ParsingError</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.partial">partial() (imaplib.IMAP4 method)</a>

      <ul>
        <li><a href="library/functools.html#functools.partial">(in module functools)</a>
</li>
      </ul></li>
      <li><a href="library/stdtypes.html#str.partition">partition() (str method)</a>
</li>
      <li>
    Pascal

      <ul>
        <li><a href="reference/compound_stmts.html#index-8">language</a>
</li>
      </ul></li>
      <li>
    pass

      <ul>
        <li><a href="reference/simple_stmts.html#index-17">statement</a>
</li>
      </ul></li>
      <li><a href="library/poplib.html#poplib.POP3.pass_">pass_() (poplib.POP3 method)</a>
</li>
      <li><a href="library/idle.html#index-4">Paste</a>
</li>
      <li><a href="c-api/intro.html#index-22">PATH</a>, <a href="c-api/intro.html#index-23">[1]</a>, <a href="distutils/packageindex.html#index-1">[2]</a>, <a href="faq/library.html#index-0">[3]</a>, <a href="faq/library.html#index-1">[4]</a>, <a href="library/cgi.html#index-2">[5]</a>, <a href="library/cgi.html#index-5">[6]</a>, <a href="library/os.html#index-21">[7]</a>, <a href="library/os.html#index-22">[8]</a>, <a href="library/os.html#index-23">[9]</a>, <a href="library/os.html#index-26">[10]</a>, <a href="library/os.html#index-27">[11]</a>, <a href="library/os.html#index-28">[12]</a>, <a href="library/os.html#index-30">[13]</a>, <a href="library/webbrowser.html#index-3">[14]</a>, <a href="tutorial/appendix.html#index-0">[15]</a>, <a href="tutorial/modules.html#index-2">[16]</a>, <a href="using/cmdline.html#index-18">[17]</a>, <a href="using/unix.html#index-2">[18]</a>
</li>
      <li>
    path

      <ul>
        <li><a href="library/site.html#index-2">configuration file</a>
</li>
        <li><a href="c-api/init.html#index-0">module search</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/linecache.html#index-0">[3]</a>, <a href="library/site.html#index-0">[4]</a>, <a href="library/sys.html#index-6">[5]</a>, <a href="tutorial/modules.html#index-0">[6]</a>
</li>
        <li><a href="library/os.path.html#index-0">operations</a>
</li>
      </ul></li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.path">path (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/cookielib.html#cookielib.Cookie.path">(cookielib.Cookie attribute)</a>
</li>
        <li><a href="c-api/init.html#index-0">(in module sys)</a>, <a href="c-api/init.html#index-4">[1]</a>, <a href="c-api/intro.html#index-20">[2]</a>, <a href="library/sys.html#sys.path">[3]</a>
</li>
      </ul></li>
      <li><a href="library/idle.html#index-1">Path browser</a>
</li>
      <li><a href="library/sys.html#sys.path_hooks">path_hooks (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.path_importer_cache">path_importer_cache (in module sys)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.path_return_ok">path_return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/os.html#os.pathconf">pathconf() (in module os)</a>
</li>
      <li><a href="library/os.html#os.pathconf_names">pathconf_names (in module os)</a>
</li>
      <li><a href="library/urllib.html#urllib.pathname2url">pathname2url() (in module urllib)</a>
</li>
      <li><a href="library/os.html#os.pathsep">pathsep (in module os)</a>
</li>
      <li><a href="library/re.html#re.RegexObject.pattern">pattern (re.RegexObject attribute)</a>
</li>
      <li><a href="library/signal.html#signal.pause">pause() (in module signal)</a>
</li>
      <li><a href="library/cd.html#cd.PAUSED">PAUSED (in module cd)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.PAX_FORMAT">PAX_FORMAT (in module tarfile)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.TarFile.pax_headers">pax_headers (tarfile.TarFile attribute)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarInfo.pax_headers">(tarfile.TarInfo attribute)</a>
</li>
      </ul></li>
      <li><a href="library/hashlib.html#hashlib.pbkdf2_hmac">pbkdf2_hmac() (in module hashlib)</a>
</li>
      <li><a href="library/turtle.html#turtle.pd">pd() (in module turtle)</a>
</li>
      <li><a href="library/pdb.html#index-1">Pdb (class in pdb)</a>, <a href="library/pdb.html#pdb.Pdb">[1]</a>
</li>
      <li><a href="library/pdb.html#module-pdb">pdb (module)</a>
</li>
      <li><a href="library/io.html#io.BufferedReader.peek">peek() (io.BufferedReader method)</a>
</li>
      <li><a href="library/ssl.html#ssl.PEM_cert_to_DER_cert">PEM_cert_to_DER_cert() (in module ssl)</a>
</li>
      <li><a href="library/turtle.html#turtle.pen">pen() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.pencolor">pencolor() (in module turtle)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.PendingDeprecationWarning">PendingDeprecationWarning</a>
</li>
      <li><a href="library/turtle.html#turtle.pendown">pendown() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.pensize">pensize() (in module turtle)</a>
</li>
      <li><a href="library/turtle.html#turtle.penup">penup() (in module turtle)</a>
</li>
      <li><a href="glossary.html#term-pep"><strong>PEP</strong></a>
</li>
      <li><a href="library/token.html#token.PERCENT">PERCENT (in module token)</a>
</li>
      <li><a href="library/token.html#token.PERCENTEQUAL">PERCENTEQUAL (in module token)</a>
</li>
      <li><a href="library/timeit.html#index-0">Performance</a>
</li>
      <li><a href="library/itertools.html#itertools.permutations">permutations() (in module itertools)</a>
</li>
      <li><a href="library/msilib.html#msilib.SummaryInformation.Persist">Persist() (msilib.SummaryInformation method)</a>
</li>
      <li><a href="library/pickle.html#index-0">persistence</a>
</li>
      <li>
    persistent

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#index-3">persistent_id (pickle protocol)</a>
</li>
      <li><a href="library/pickle.html#index-3">persistent_load (pickle protocol)</a>
</li>
      <li><a href="library/pprint.html#pprint.pformat">pformat() (in module pprint)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.pformat">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/cmath.html#cmath.phase">phase() (in module cmath)</a>
</li>
      <li><a href="extending/extending.html#index-3">Philbrick, Geoff</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-15">physical line</a>, <a href="reference/lexical_analysis.html#index-2">[1]</a>, <a href="reference/lexical_analysis.html#index-5">[2]</a>
</li>
      <li><a href="library/cmath.html#cmath.pi">pi (in module cmath)</a>

      <ul>
        <li><a href="library/math.html#math.pi">(in module math)</a>
</li>
      </ul></li>
      <li><a href="library/gl.html#gl.pick">pick() (in module gl)</a>
</li>
      <li>
    pickle

      <ul>
        <li><a href="library/copy.html#index-0">module</a>, <a href="library/copy_reg.html#index-0">[1]</a>, <a href="library/marshal.html#index-0">[2]</a>, <a href="library/pickle.html#index-5">[3]</a>, <a href="library/shelve.html#index-0">[4]</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#module-pickle">pickle (module)</a>
</li>
      <li><a href="library/copy_reg.html#copy_reg.pickle">pickle() (in module copy_reg)</a>
</li>
      <li><a href="library/pickle.html#pickle.PickleError">PickleError</a>
</li>
      <li><a href="library/pickle.html#pickle.Pickler">Pickler (class in pickle)</a>
</li>
      <li><a href="library/pickletools.html#module-pickletools">pickletools (module)</a>
</li>
      <li>
    pickling

      <ul>
        <li><a href="library/pickle.html#index-0">objects</a>
</li>
      </ul></li>
      <li><a href="library/pickle.html#pickle.PicklingError">PicklingError</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process.pid">pid (multiprocessing.Process attribute)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.Popen3.pid">(popen2.Popen3 attribute)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.pid">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">PIL (the Python Imaging Library)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.PIPE">PIPE (in module subprocess)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Pipe">Pipe() (in module multiprocessing)</a>
</li>
      <li><a href="library/os.html#os.pipe">pipe() (in module os)</a>
</li>
      <li><a href="library/select.html#select.select.PIPE_BUF">PIPE_BUF (select.select attribute)</a>
</li>
      <li><a href="library/pipes.html#module-pipes">pipes (module)</a>
</li>
      <li><a href="library/undoc.html#module-PixMapWrapper">PixMapWrapper (module)</a>
</li>
      <li><a href="library/imp.html#imp.PKG_DIRECTORY">PKG_DIRECTORY (in module imp)</a>
</li>
      <li><a href="library/pkgutil.html#module-pkgutil">pkgutil (module)</a>
</li>
      <li>
    plain integer

      <ul>
        <li><a href="reference/datamodel.html#index-11">object</a>
</li>
      </ul></li>
      <li><a href="reference/lexical_analysis.html#index-18">plain integer literal</a>
</li>
      <li><a href="distutils/apiref.html#index-2">PLAT</a>
</li>
      <li><a href="c-api/init.html#index-6">platform (in module sys)</a>, <a href="library/sys.html#sys.platform">[1]</a>

      <ul>
        <li><a href="library/platform.html#module-platform">(module)</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.platform">platform() (in module platform)</a>
</li>
      <li><a href="library/cd.html#cd.PLAYING">PLAYING (in module cd)</a>
</li>
      <li><a href="library/winsound.html#winsound.PlaySound">PlaySound() (in module winsound)</a>
</li>
      <li>
    plist

      <ul>
        <li><a href="library/plistlib.html#index-0">file</a>
</li>
      </ul></li>
      <li><a href="library/plistlib.html#module-plistlib">plistlib (module)</a>
</li>
      <li><a href="library/os.html#os.plock">plock() (in module os)</a>
</li>
      <li><a href="reference/expressions.html#index-49">plus</a>
</li>
      <li><a href="library/token.html#token.PLUS">PLUS (in module token)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.plus">plus() (decimal.Context method)</a>
</li>
      <li><a href="library/token.html#token.PLUSEQUAL">PLUSEQUAL (in module token)</a>
</li>
      <li><a href="library/pdb.html#pdb.pm">pm() (in module pdb)</a>
</li>
      <li><a href="library/cd.html#cd.pnum">pnum (in module cd)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.POINTER">POINTER() (in module ctypes)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.pointer">pointer() (in module ctypes)</a>
</li>
      <li><a href="library/cmath.html#cmath.polar">polar() (in module cmath)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection.poll">poll() (Connection method)</a>

      <ul>
        <li><a href="library/select.html#select.poll">(in module select)</a>
</li>
        <li><a href="library/popen2.html#popen2.Popen3.poll">(popen2.Popen3 method)</a>
</li>
        <li><a href="library/select.html#select.epoll.poll">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.poll.poll">(select.poll method)</a>
</li>
        <li><a href="library/subprocess.html#subprocess.Popen.poll">(subprocess.Popen method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.pop">pop() (array.array method)</a>

      <ul>
        <li><a href="library/asynchat.html#asynchat.fifo.pop">(asynchat.fifo method)</a>
</li>
        <li><a href="library/collections.html#collections.deque.pop">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#dict.pop">(dict method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.pop">(frozenset method)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.pop">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.pop">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li>
    POP3

      <ul>
        <li><a href="library/poplib.html#index-0">protocol</a>
</li>
      </ul></li>
      <li><a href="library/poplib.html#poplib.POP3">POP3 (class in poplib)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3_SSL">POP3_SSL (class in poplib)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_alignment">pop_alignment() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_BLOCK">POP_BLOCK (opcode)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_font">pop_font() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_JUMP_IF_FALSE">POP_JUMP_IF_FALSE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_JUMP_IF_TRUE">POP_JUMP_IF_TRUE (opcode)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_margin">pop_margin() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.pop_source">pop_source() (shlex.shlex method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.pop_style">pop_style() (formatter.formatter method)</a>
</li>
      <li><a href="library/dis.html#opcode-POP_TOP">POP_TOP (opcode)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.Popen">Popen (class in subprocess)</a>
</li>
      <li><a href="library/os.html#os.popen">popen() (in module os)</a>, <a href="library/select.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-58">[2]</a>

      <ul>
        <li><a href="library/platform.html#platform.popen">(in module platform)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#module-popen2">popen2 (module)</a>
</li>
      <li><a href="library/os.html#os.popen2">popen2() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen2">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#popen2.Popen3">Popen3 (class in popen2)</a>
</li>
      <li><a href="library/os.html#os.popen3">popen3() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen3">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/popen2.html#popen2.Popen4">Popen4 (class in popen2)</a>
</li>
      <li><a href="library/os.html#os.popen4">popen4() (in module os)</a>

      <ul>
        <li><a href="library/popen2.html#popen2.popen4">(in module popen2)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.OrderedDict.popitem">popitem() (collections.OrderedDict method)</a>

      <ul>
        <li><a href="library/stdtypes.html#dict.popitem">(dict method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.popitem">(mailbox.Mailbox method)</a>
</li>
      </ul></li>
      <li><a href="library/collections.html#collections.deque.popleft">popleft() (collections.deque method)</a>
</li>
      <li><a href="library/poplib.html#module-poplib">poplib (module)</a>
</li>
      <li><a href="library/tix.html#Tix.PopupMenu">PopupMenu (class in Tix)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.port">port (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.Cookie.port_specified">port_specified (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.PortableUnixMailbox">PortableUnixMailbox (class in mailbox)</a>
</li>
      <li><a href="library/re.html#re.MatchObject.pos">pos (re.MatchObject attribute)</a>
</li>
      <li><a href="library/operator.html#operator.pos">pos() (in module operator)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.pos">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.position">position() (in module turtle)</a>
</li>
      <li><a href="glossary.html#term-positional-argument"><strong>positional argument</strong></a>
</li>
      <li>
    POSIX

      <ul>
        <li><a href="library/termios.html#index-0">I/O control</a>
</li>
        <li><a href="library/posixfile.html#index-0">file object</a>
</li>
        <li><a href="library/thread.html#index-1">threads</a>
</li>
      </ul></li>
      <li><a href="library/posix.html#module-posix">posix (module)</a>

      <ul>
        <li><a href="library/tarfile.html#tarfile.TarFile.posix">(tarfile.TarFile attribute)</a>
</li>
      </ul></li>
      <li><a href="library/posixfile.html#module-posixfile">posixfile (module)</a>
</li>
      <li><a href="library/getopt.html#index-0">POSIXLY_CORRECT</a>
</li>
      <li><a href="library/nntplib.html#nntplib.NNTP.post">post() (nntplib.NNTP method)</a>

      <ul>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.post">(ossaudiodev.oss_audio_device method)</a>
</li>
      </ul></li>
      <li><a href="library/pdb.html#pdb.post_mortem">post_mortem() (in module pdb)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.postcmd">postcmd() (cmd.Cmd method)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.postloop">postloop() (cmd.Cmd method)</a>
</li>
      <li>
    pow

      <ul>
        <li><a href="c-api/number.html#index-1">built-in function</a>, <a href="c-api/number.html#index-3">[1]</a>, <a href="reference/datamodel.html#index-90">[2]</a>, <a href="reference/datamodel.html#index-90">[3]</a>, <a href="reference/datamodel.html#index-91">[4]</a>, <a href="reference/datamodel.html#index-92">[5]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#pow">pow() (built-in function)</a>

      <ul>
        <li><a href="library/math.html#math.pow">(in module math)</a>
</li>
        <li><a href="library/operator.html#operator.pow">(in module operator)</a>
</li>
      </ul></li>
      <li><a href="library/decimal.html#decimal.Context.power">power() (decimal.Context method)</a>
</li>
      <li><a href="library/pprint.html#module-pprint">pprint (module)</a>
</li>
      <li><a href="library/bdb.html#bdb.Breakpoint.pprint">pprint() (bdb.Breakpoint method)</a>

      <ul>
        <li><a href="library/pprint.html#pprint.pprint">(in module pprint)</a>
</li>
        <li><a href="library/pprint.html#pprint.PrettyPrinter.pprint">(pprint.PrettyPrinter method)</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.prcal">prcal() (in module calendar)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.preamble">preamble (email.message.Message attribute)</a>
</li>
      <li>
    precedence

      <ul>
        <li><a href="reference/expressions.html#index-80">operator</a>
</li>
      </ul></li>
      <li><a href="library/cmd.html#cmd.Cmd.precmd">precmd() (cmd.Cmd method)</a>
</li>
      <li><a href="c-api/intro.html#index-0">prefix</a>, <a href="c-api/intro.html#index-2">[1]</a>, <a href="c-api/intro.html#index-3">[2]</a>, <a href="using/unix.html#index-0">[3]</a>
</li>
      <li><a href="distutils/apiref.html#distutils.sysconfig.PREFIX">PREFIX (in module distutils.sysconfig)</a>
</li>
      <li><a href="library/sys.html#sys.prefix">prefix (in module sys)</a>

      <ul>
        <li><a href="library/xml.dom.html#xml.dom.Attr.prefix">(xml.dom.Attr attribute)</a>
</li>
        <li><a href="library/xml.dom.html#xml.dom.Node.prefix">(xml.dom.Node attribute)</a>
</li>
        <li><a href="library/zipimport.html#zipimport.zipimporter.prefix">(zipimport.zipimporter attribute)</a>
</li>
      </ul></li>
      <li><a href="library/site.html#site.PREFIXES">PREFIXES (in module site)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.preloop">preloop() (cmd.Cmd method)</a>
</li>
      <li><a href="library/compiler.html#compiler.visitor.ASTVisitor.preorder">preorder() (compiler.visitor.ASTVisitor method)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.prepare_input_source">prepare_input_source() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/pipes.html#pipes.Template.prepend">prepend() (pipes.Template method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.preprocess">preprocess() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/pprint.html#pprint.PrettyPrinter">PrettyPrinter (class in pprint)</a>
</li>
      <li><a href="library/ttk.html#ttk.Treeview.prev">prev() (ttk.Treeview method)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.bsddbobject.previous">previous() (bsddb.bsddbobject method)</a>

      <ul>
        <li><a href="library/dbhash.html#dbhash.dbhash.previous">(dbhash.dbhash method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.dom.html#xml.dom.Node.previousSibling">previousSibling (xml.dom.Node attribute)</a>
</li>
      <li><a href="reference/expressions.html#index-28">primary</a>
</li>
      <li>
    print

      <ul>
        <li><a href="library/stdtypes.html#index-1">statement</a>, <a href="reference/datamodel.html#index-78">[1]</a>, <a href="reference/simple_stmts.html#index-22">[2]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-print">print (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#print">print() (built-in function)</a>
</li>
      <li><a href="library/macostools.html#findertools.Print">Print() (in module findertools)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats.print_callees">print_callees() (pstats.Stats method)</a>
</li>
      <li><a href="library/profile.html#pstats.Stats.print_callers">print_callers() (pstats.Stats method)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_directory">print_directory() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_environ">print_environ() (in module cgi)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_environ_usage">print_environ_usage() (in module cgi)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_exc">print_exc() (in module traceback)</a>

      <ul>
        <li><a href="library/timeit.html#timeit.Timer.print_exc">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.print_exception">print_exception() (in module traceback)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_EXPR">PRINT_EXPR (opcode)</a>
</li>
      <li><a href="library/cgi.html#cgi.print_form">print_form() (in module cgi)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.print_help">print_help() (argparse.ArgumentParser method)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_ITEM">PRINT_ITEM (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_ITEM_TO">PRINT_ITEM_TO (opcode)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_last">print_last() (in module traceback)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_NEWLINE">PRINT_NEWLINE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-PRINT_NEWLINE_TO">PRINT_NEWLINE_TO (opcode)</a>
</li>
      <li><a href="library/traceback.html#traceback.print_stack">print_stack() (in module traceback)</a>
</li>
      <li><a href="library/profile.html#profile.Profile.print_stats">print_stats() (profile.Profile method)</a>

      <ul>
        <li><a href="library/profile.html#pstats.Stats.print_stats">(pstats.Stats method)</a>
</li>
      </ul></li>
      <li><a href="library/traceback.html#traceback.print_tb">print_tb() (in module traceback)</a>
</li>
      <li><a href="library/argparse.html#argparse.ArgumentParser.print_usage">print_usage() (argparse.ArgumentParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.print_usage">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/optparse.html#optparse.OptionParser.print_version">print_version() (optparse.OptionParser method)</a>
</li>
      <li><a href="library/string.html#string.printable">printable (in module string)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipFile.printdir">printdir() (zipfile.ZipFile method)</a>
</li>
      <li><a href="library/stdtypes.html#index-25">printf-style formatting</a>
</li>
      <li><a href="library/queue.html#Queue.PriorityQueue">PriorityQueue (class in Queue)</a>
</li>
      <li>
    private

      <ul>
        <li><a href="reference/expressions.html#index-7">names</a>
</li>
      </ul></li>
      <li><a href="library/calendar.html#calendar.TextCalendar.prmonth">prmonth() (calendar.TextCalendar method)</a>

      <ul>
        <li><a href="library/calendar.html#calendar.prmonth">(in module calendar)</a>
</li>
      </ul></li>
      <li>
    procedure

      <ul>
        <li><a href="reference/simple_stmts.html#index-2">call</a>
</li>
      </ul></li>
      <li>
    process

      <ul>
        <li><a href="library/os.html#index-1">group</a>, <a href="library/os.html#index-3">[1]</a>
</li>
        <li><a href="library/os.html#index-4">id</a>
</li>
        <li><a href="library/os.html#index-5">id of parent</a>
</li>
        <li><a href="library/os.html#index-24">killing</a>, <a href="library/os.html#index-25">[1]</a>
</li>
        <li><a href="library/os.html#index-24">signalling</a>, <a href="library/os.html#index-25">[1]</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Process">Process (class in multiprocessing)</a>
</li>
      <li><a href="library/logging.html#logging.LoggerAdapter.process">process() (logging.LoggerAdapter method)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.SMTPServer.process_message">process_message() (smtpd.SMTPServer method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.process_request">process_request() (SocketServer.BaseServer method)</a>
</li>
      <li><a href="library/tabnanny.html#tabnanny.process_tokens">process_tokens() (in module tabnanny)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.connection.ProcessError">ProcessError</a>
</li>
      <li><a href="library/thread.html#index-0">processes, light-weight</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.processfile">processfile() (in module gensuitemodule)</a>
</li>
      <li><a href="library/gensuitemodule.html#gensuitemodule.processfile_fromresource">processfile_fromresource() (in module gensuitemodule)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.ProcessingInstruction">ProcessingInstruction() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.ContentHandler.processingInstruction">processingInstruction() (xml.sax.handler.ContentHandler method)</a>
</li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.ProcessingInstructionHandler">ProcessingInstructionHandler() (xml.parsers.expat.xmlparser method)</a>
</li>
      <li><a href="library/time.html#index-8">processor time</a>
</li>
      <li><a href="library/platform.html#platform.processor">processor() (in module platform)</a>
</li>
      <li><a href="library/itertools.html#itertools.product">product() (in module itertools)</a>
</li>
      <li><a href="library/hotshot.html#hotshot.Profile">Profile (class in hotshot)</a>

      <ul>
        <li><a href="library/profile.html#profile.Profile">(class in profile)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#module-profile">profile (module)</a>
</li>
      <li><a href="library/sys.html#index-12">profile function</a>, <a href="library/sys.html#index-2">[1]</a>, <a href="library/threading.html#index-2">[2]</a>
</li>
      <li><a href="library/sys.html#index-12">profiler</a>, <a href="library/sys.html#index-2">[1]</a>
</li>
      <li><a href="library/profile.html#index-0">profiling, deterministic</a>
</li>
      <li><a href="reference/toplevel_components.html#index-1">program</a>
</li>
      <li><a href="library/ttk.html#ttk.Progressbar">Progressbar (class in ttk)</a>
</li>
      <li><a href="library/easydialogs.html#EasyDialogs.ProgressBar">ProgressBar() (in module EasyDialogs)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.prompt">prompt (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/urllib.html#urllib.FancyURLopener.prompt_user_passwd">prompt_user_passwd() (urllib.FancyURLopener method)</a>
</li>
      <li><a href="library/sys.html#index-11">prompts, interpreter</a>
</li>
      <li><a href="library/logging.html#logging.Logger.propagate">propagate (logging.Logger attribute)</a>
</li>
      <li><a href="library/functions.html#property">property (built-in class)</a>
</li>
      <li><a href="library/plistlib.html#index-0">property list</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_declaration_handler">property_declaration_handler (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_dom_node">property_dom_node (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_lexical_handler">property_lexical_handler (in module xml.sax.handler)</a>
</li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.property_xml_string">property_xml_string (in module xml.sax.handler)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.prot_c">prot_c() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP_TLS.prot_p">prot_p() (ftplib.FTP_TLS method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.proto">proto (socket.socket attribute)</a>
</li>
      <li>
    protocol

      <ul>
        <li><a href="library/cgi.html#index-0">CGI</a>
</li>
        <li><a href="library/ftplib.html#index-0">FTP</a>, <a href="library/urllib.html#index-8">[1]</a>
</li>
        <li><a href="library/basehttpserver.html#index-0">HTTP</a>, <a href="library/cgi.html#index-0">[1]</a>, <a href="library/httplib.html#index-0">[2]</a>, <a href="library/urllib.html#index-8">[3]</a>, <a href="library/urllib.html#index-9">[4]</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4_SSL</a>
</li>
        <li><a href="library/imaplib.html#index-0">IMAP4_stream</a>
</li>
        <li><a href="library/nntplib.html#index-0">NNTP</a>
</li>
        <li><a href="library/poplib.html#index-0">POP3</a>
</li>
        <li><a href="library/smtplib.html#index-0">SMTP</a>
</li>
        <li><a href="library/telnetlib.html#index-0">Telnet</a>
</li>
        <li><a href="library/stdtypes.html#index-37">context management</a>
</li>
        <li><a href="library/stdtypes.html#index-20">iterator</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.SSLContext.protocol">protocol (ssl.SSLContext attribute)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv2">PROTOCOL_SSLv2 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv23">PROTOCOL_SSLv23 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_SSLv3">PROTOCOL_SSLv3 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLS">PROTOCOL_TLS (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1">PROTOCOL_TLSv1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1_1">PROTOCOL_TLSv1_1 (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.PROTOCOL_TLSv1_2">PROTOCOL_TLSv1_2 (in module ssl)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.protocol_version">protocol_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.PROTOCOL_VERSION">PROTOCOL_VERSION (imaplib.IMAP4 attribute)</a>
</li>
      <li><a href="library/xmlrpclib.html#xmlrpclib.ProtocolError">ProtocolError (class in xmlrpclib)</a>
</li>
      <li><a href="library/weakref.html#weakref.proxy">proxy() (in module weakref)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.proxyauth">proxyauth() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyBasicAuthHandler">ProxyBasicAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyDigestAuthHandler">ProxyDigestAuthHandler (class in urllib2)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.ProxyHandler">ProxyHandler (class in urllib2)</a>
</li>
      <li><a href="library/weakref.html#weakref.ProxyType">ProxyType (in module weakref)</a>
</li>
      <li><a href="library/weakref.html#weakref.ProxyTypes">ProxyTypes (in module weakref)</a>
</li>
      <li><a href="library/fm.html#fm.prstr">prstr() (in module fm)</a>
</li>
      <li><a href="library/calendar.html#calendar.TextCalendar.pryear">pryear() (calendar.TextCalendar method)</a>
</li>
      <li><a href="library/sys.html#sys.ps1">ps1 (in module sys)</a>
</li>
      <li><a href="library/sys.html#sys.ps2">ps2 (in module sys)</a>
</li>
      <li><a href="library/profile.html#module-pstats">pstats (module)</a>
</li>
      <li><a href="library/thread.html#index-1">pthreads</a>
</li>
      <li><a href="library/cd.html#cd.ptime">ptime (in module cd)</a>
</li>
      <li>
    pty

      <ul>
        <li><a href="library/os.html#index-12">module</a>
</li>
      </ul></li>
      <li><a href="library/pty.html#module-pty">pty (module)</a>
</li>
      <li><a href="library/turtle.html#turtle.pu">pu() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.DocumentType.publicId">publicId (xml.dom.DocumentType attribute)</a>
</li>
      <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.PullDOM">PullDOM (class in xml.dom.pulldom)</a>
</li>
      <li><a href="library/string.html#string.punctuation">punctuation (in module string)</a>
</li>
      <li><a href="library/smtpd.html#smtpd.PureProxy">PureProxy (class in smtpd)</a>
</li>
      <li><a href="library/re.html#re.purge">purge() (in module re)</a>
</li>
      <li><a href="library/ssl.html#ssl.Purpose.CLIENT_AUTH">Purpose.CLIENT_AUTH (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.Purpose.SERVER_AUTH">Purpose.SERVER_AUTH (in module ssl)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.push">push() (asynchat.async_chat method)</a>

      <ul>
        <li><a href="library/asynchat.html#asynchat.fifo.push">(asynchat.fifo method)</a>
</li>
        <li><a href="library/code.html#code.InteractiveConsole.push">(code.InteractiveConsole method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.push">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/formatter.html#formatter.formatter.push_alignment">push_alignment() (formatter.formatter method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_font">push_font() (formatter.formatter method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_margin">push_margin() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.push_source">push_source() (shlex.shlex method)</a>
</li>
      <li><a href="library/formatter.html#formatter.formatter.push_style">push_style() (formatter.formatter method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.push_token">push_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/asynchat.html#asynchat.async_chat.push_with_producer">push_with_producer() (asynchat.async_chat method)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.pushbutton">pushbutton() (msilib.Dialog method)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.multiprocessing.queues.SimpleQueue.put">put() (multiprocessing.multiprocessing.queues.SimpleQueue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.put">(Queue.Queue method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Queue.put">(multiprocessing.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.put_nowait">put_nowait() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.put_nowait">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/msvcrt.html#msvcrt.putch">putch() (in module msvcrt)</a>
</li>
      <li><a href="library/os.html#os.putenv">putenv() (in module os)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.putheader">putheader() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/curses.html#curses.putp">putp() (in module curses)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.putrequest">putrequest() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.putsequences">putsequences() (mhlib.Folder method)</a>
</li>
      <li><a href="library/msvcrt.html#msvcrt.putwch">putwch() (in module msvcrt)</a>
</li>
      <li><a href="library/curses.html#curses.window.putwin">putwin() (curses.window method)</a>
</li>
      <li>
    pwd

      <ul>
        <li><a href="library/os.path.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="library/pwd.html#module-pwd">pwd (module)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.pwd">pwd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/gl.html#gl.pwlcurve">pwlcurve() (in module gl)</a>
</li>
      <li><a href="library/sys.html#sys.py3kwarning">py3kwarning (in module sys)</a>
</li>
      <li><a href="c-api/init.html#c.Py_AddPendingCall">Py_AddPendingCall (C function)</a>
</li>
      <li><a href="c-api/init.html#index-25">Py_AddPendingCall()</a>
</li>
      <li><a href="c-api/sys.html#c.Py_AtExit">Py_AtExit (C function)</a>
</li>
      <li><a href="c-api/init.html#index-16">Py_BEGIN_ALLOW_THREADS</a>

      <ul>
        <li><a href="c-api/init.html#c.Py_BEGIN_ALLOW_THREADS">(C macro)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#c.Py_BLOCK_THREADS">Py_BLOCK_THREADS (C macro)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer">Py_buffer (C type)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.buf">Py_buffer.buf (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.internal">Py_buffer.internal (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.itemsize">Py_buffer.itemsize (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.ndim">Py_buffer.ndim (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.readonly">Py_buffer.readonly (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.shape">Py_buffer.shape (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.strides">Py_buffer.strides (C member)</a>
</li>
      <li><a href="c-api/buffer.html#c.Py_buffer.suboffsets">Py_buffer.suboffsets (C member)</a>
</li>
      <li><a href="c-api/arg.html#c.Py_BuildValue">Py_BuildValue (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_CLEAR">Py_CLEAR (C function)</a>
</li>
      <li><a href="library/py_compile.html#module-py_compile">py_compile (module)</a>
</li>
      <li><a href="library/imp.html#imp.PY_COMPILED">PY_COMPILED (in module imp)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_CompileString">Py_CompileString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#index-0">Py_CompileString()</a>, <a href="c-api/veryhigh.html#index-1">[1]</a>, <a href="c-api/veryhigh.html#index-2">[2]</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_CompileStringFlags">Py_CompileStringFlags (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.Py_complex">Py_complex (C type)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_DECREF">Py_DECREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-6">Py_DECREF()</a>
</li>
      <li><a href="c-api/slice.html#c.Py_Ellipsis">Py_Ellipsis (C variable)</a>
</li>
      <li><a href="c-api/init.html#index-16">Py_END_ALLOW_THREADS</a>

      <ul>
        <li><a href="c-api/init.html#c.Py_END_ALLOW_THREADS">(C macro)</a>
</li>
      </ul></li>
      <li><a href="c-api/buffer.html#c.Py_END_OF_BUFFER">Py_END_OF_BUFFER (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_EndInterpreter">Py_EndInterpreter (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.Py_EnterRecursiveCall">Py_EnterRecursiveCall (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_eval_input">Py_eval_input (C variable)</a>
</li>
      <li><a href="c-api/sys.html#c.Py_Exit">Py_Exit (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_False">Py_False (C variable)</a>
</li>
      <li><a href="c-api/sys.html#c.Py_FatalError">Py_FatalError (C function)</a>
</li>
      <li><a href="c-api/init.html#index-10">Py_FatalError()</a>
</li>
      <li><a href="c-api/sys.html#c.Py_FdIsInteractive">Py_FdIsInteractive (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_file_input">Py_file_input (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_Finalize">Py_Finalize (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">Py_Finalize()</a>, <a href="c-api/init.html#index-22">[1]</a>, <a href="c-api/init.html#index-24">[2]</a>, <a href="c-api/sys.html#index-1">[3]</a>, <a href="c-api/sys.html#index-2">[4]</a>
</li>
      <li><a href="c-api/structures.html#c.Py_FindMethod">Py_FindMethod (C function)</a>
</li>
      <li><a href="library/imp.html#imp.PY_FROZEN">PY_FROZEN (in module imp)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetBuildInfo">Py_GetBuildInfo (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetCompiler">Py_GetCompiler (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetCopyright">Py_GetCopyright (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetExecPrefix">Py_GetExecPrefix (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetExecPrefix()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPath">Py_GetPath (C function)</a>
</li>
      <li><a href="c-api/init.html#index-1">Py_GetPath()</a>, <a href="c-api/intro.html#index-26">[1]</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPlatform">Py_GetPlatform (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPrefix">Py_GetPrefix (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetPrefix()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetProgramFullPath">Py_GetProgramFullPath (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-26">Py_GetProgramFullPath()</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetProgramName">Py_GetProgramName (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetPythonHome">Py_GetPythonHome (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_GetVersion">Py_GetVersion (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_INCREF">Py_INCREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-6">Py_INCREF()</a>
</li>
      <li><a href="c-api/init.html#c.Py_Initialize">Py_Initialize (C function)</a>
</li>
      <li><a href="c-api/init.html#index-1">Py_Initialize()</a>, <a href="c-api/init.html#index-19">[1]</a>, <a href="c-api/init.html#index-22">[2]</a>, <a href="c-api/intro.html#index-20">[3]</a>
</li>
      <li><a href="c-api/init.html#c.Py_InitializeEx">Py_InitializeEx (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule">Py_InitModule (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule3">Py_InitModule3 (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.Py_InitModule4">Py_InitModule4 (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_IsInitialized">Py_IsInitialized (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-29">Py_IsInitialized()</a>
</li>
      <li><a href="c-api/exceptions.html#c.Py_LeaveRecursiveCall">Py_LeaveRecursiveCall (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_Main">Py_Main (C function)</a>
</li>
      <li><a href="c-api/init.html#c.Py_NewInterpreter">Py_NewInterpreter (C function)</a>
</li>
      <li><a href="c-api/none.html#c.Py_None">Py_None (C variable)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.py_object">py_object (class in ctypes)</a>
</li>
      <li><a href="c-api/file.html#index-6">Py_PRINT_RAW</a>
</li>
      <li><a href="c-api/structures.html#c.Py_REFCNT">Py_REFCNT (C macro)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_RETURN_FALSE">Py_RETURN_FALSE (C macro)</a>
</li>
      <li><a href="c-api/none.html#c.Py_RETURN_NONE">Py_RETURN_NONE (C macro)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_RETURN_TRUE">Py_RETURN_TRUE (C macro)</a>
</li>
      <li><a href="c-api/init.html#c.Py_SetProgramName">Py_SetProgramName (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">Py_SetProgramName()</a>, <a href="c-api/init.html#index-2">[1]</a>, <a href="c-api/init.html#index-3">[2]</a>, <a href="c-api/intro.html#index-26">[3]</a>
</li>
      <li><a href="c-api/init.html#c.Py_SetPythonHome">Py_SetPythonHome (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.Py_single_input">Py_single_input (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.Py_SIZE">Py_SIZE (C macro)</a>
</li>
      <li><a href="library/imp.html#imp.PY_SOURCE">PY_SOURCE (in module imp)</a>
</li>
      <li><a href="c-api/long.html#index-3">PY_SSIZE_T_MAX</a>
</li>
      <li><a href="library/imputil.html#imputil.py_suffix_importer">py_suffix_importer() (in module imputil)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_BASETYPE">Py_TPFLAGS_BASETYPE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_CHECKTYPES">Py_TPFLAGS_CHECKTYPES (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_DEFAULT">Py_TPFLAGS_DEFAULT (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_GC">Py_TPFLAGS_GC (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_CLASS">Py_TPFLAGS_HAVE_CLASS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GC">Py_TPFLAGS_HAVE_GC (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GETCHARBUFFER">Py_TPFLAGS_HAVE_GETCHARBUFFER (built-in variable)</a>, <a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_GETCHARBUFFER">[1]</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_INPLACEOPS">Py_TPFLAGS_HAVE_INPLACEOPS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_ITER">Py_TPFLAGS_HAVE_ITER (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_RICHCOMPARE">Py_TPFLAGS_HAVE_RICHCOMPARE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_SEQUENCE_IN">Py_TPFLAGS_HAVE_SEQUENCE_IN (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HAVE_WEAKREFS">Py_TPFLAGS_HAVE_WEAKREFS (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_HEAPTYPE">Py_TPFLAGS_HEAPTYPE (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_READY">Py_TPFLAGS_READY (built-in variable)</a>
</li>
      <li><a href="c-api/typeobj.html#Py_TPFLAGS_READYING">Py_TPFLAGS_READYING (built-in variable)</a>
</li>
      <li><a href="c-api/init.html#c.Py_tracefunc">Py_tracefunc (C type)</a>
</li>
      <li><a href="c-api/bool.html#c.Py_True">Py_True (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.Py_TYPE">Py_TYPE (C macro)</a>
</li>
      <li><a href="c-api/init.html#c.Py_UNBLOCK_THREADS">Py_UNBLOCK_THREADS (C macro)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE">Py_UNICODE (C type)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISALNUM">Py_UNICODE_ISALNUM (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISALPHA">Py_UNICODE_ISALPHA (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISDECIMAL">Py_UNICODE_ISDECIMAL (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISDIGIT">Py_UNICODE_ISDIGIT (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISLINEBREAK">Py_UNICODE_ISLINEBREAK (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISLOWER">Py_UNICODE_ISLOWER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISNUMERIC">Py_UNICODE_ISNUMERIC (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISSPACE">Py_UNICODE_ISSPACE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISTITLE">Py_UNICODE_ISTITLE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_ISUPPER">Py_UNICODE_ISUPPER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TODECIMAL">Py_UNICODE_TODECIMAL (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TODIGIT">Py_UNICODE_TODIGIT (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOLOWER">Py_UNICODE_TOLOWER (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TONUMERIC">Py_UNICODE_TONUMERIC (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOTITLE">Py_UNICODE_TOTITLE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.Py_UNICODE_TOUPPER">Py_UNICODE_TOUPPER (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.Py_VaBuildValue">Py_VaBuildValue (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.Py_VISIT">Py_VISIT (C function)</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_XDECREF">Py_XDECREF (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-19">Py_XDECREF()</a>
</li>
      <li><a href="c-api/refcounting.html#c.Py_XINCREF">Py_XINCREF (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyAnySet_Check">PyAnySet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyAnySet_CheckExact">PyAnySet_CheckExact (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_Parse">PyArg_Parse (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_ParseTuple">PyArg_ParseTuple (C function)</a>
</li>
      <li><a href="extending/extending.html#index-1">PyArg_ParseTuple()</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_ParseTupleAndKeywords">PyArg_ParseTupleAndKeywords (C function)</a>
</li>
      <li><a href="extending/extending.html#index-2">PyArg_ParseTupleAndKeywords()</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_UnpackTuple">PyArg_UnpackTuple (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_VaParse">PyArg_VaParse (C function)</a>
</li>
      <li><a href="c-api/arg.html#c.PyArg_VaParseTupleAndKeywords">PyArg_VaParseTupleAndKeywords (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.PyBool_Check">PyBool_Check (C function)</a>
</li>
      <li><a href="c-api/bool.html#c.PyBool_FromLong">PyBool_FromLong (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Check">PyBuffer_Check (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FillContiguousStrides">PyBuffer_FillContiguousStrides (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FillInfo">PyBuffer_FillInfo (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromMemory">PyBuffer_FromMemory (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromObject">PyBuffer_FromObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromReadWriteMemory">PyBuffer_FromReadWriteMemory (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_FromReadWriteObject">PyBuffer_FromReadWriteObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_IsContiguous">PyBuffer_IsContiguous (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_New">PyBuffer_New (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Release">PyBuffer_Release (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_SizeFromFormat">PyBuffer_SizeFromFormat (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBuffer_Type">PyBuffer_Type (C variable)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyBufferObject">PyBufferObject (C type)</a>
</li>
      <li><a href="c-api/buffer.html#index-1">PyBufferProcs</a>

      <ul>
        <li><a href="c-api/typeobj.html#c.PyBufferProcs">(C type)</a>
</li>
      </ul></li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_AS_STRING">PyByteArray_AS_STRING (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_AsString">PyByteArray_AsString (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Check">PyByteArray_Check (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_CheckExact">PyByteArray_CheckExact (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Concat">PyByteArray_Concat (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_FromObject">PyByteArray_FromObject (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_FromStringAndSize">PyByteArray_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_GET_SIZE">PyByteArray_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Resize">PyByteArray_Resize (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Size">PyByteArray_Size (C function)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArray_Type">PyByteArray_Type (C variable)</a>
</li>
      <li><a href="c-api/bytearray.html#c.PyByteArrayObject">PyByteArrayObject (C type)</a>
</li>
      <li><a href="c-api/object.html#c.PyCallable_Check">PyCallable_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_Check">PyCallIter_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_New">PyCallIter_New (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PyCallIter_Type">PyCallIter_Type (C variable)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule">PyCapsule (C type)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_CheckExact">PyCapsule_CheckExact (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_Destructor">PyCapsule_Destructor (C type)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetContext">PyCapsule_GetContext (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetDestructor">PyCapsule_GetDestructor (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetName">PyCapsule_GetName (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_GetPointer">PyCapsule_GetPointer (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_Import">PyCapsule_Import (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_IsValid">PyCapsule_IsValid (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_New">PyCapsule_New (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetContext">PyCapsule_SetContext (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetDestructor">PyCapsule_SetDestructor (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetName">PyCapsule_SetName (C function)</a>
</li>
      <li><a href="c-api/capsule.html#c.PyCapsule_SetPointer">PyCapsule_SetPointer (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Check">PyCell_Check (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_GET">PyCell_GET (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Get">PyCell_Get (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_New">PyCell_New (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_SET">PyCell_SET (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Set">PyCell_Set (C function)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCell_Type">PyCell_Type (C variable)</a>
</li>
      <li><a href="c-api/cell.html#c.PyCellObject">PyCellObject (C type)</a>
</li>
      <li><a href="c-api/structures.html#c.PyCFunction">PyCFunction (C type)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_Check">PyClass_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_IsSubclass">PyClass_IsSubclass (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyClass_Type">PyClass_Type (C variable)</a>
</li>
      <li><a href="c-api/class.html#c.PyClassObject">PyClassObject (C type)</a>
</li>
      <li><a href="library/pyclbr.html#module-pyclbr">pyclbr (module)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject">PyCObject (C type)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_AsVoidPtr">PyCObject_AsVoidPtr (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_Check">PyCObject_Check (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_FromVoidPtr">PyCObject_FromVoidPtr (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_FromVoidPtrAndDesc">PyCObject_FromVoidPtrAndDesc (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_GetDesc">PyCObject_GetDesc (C function)</a>
</li>
      <li><a href="c-api/cobject.html#c.PyCObject_SetVoidPtr">PyCObject_SetVoidPtr (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_Check">PyCode_Check (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_GetNumFree">PyCode_GetNumFree (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_New">PyCode_New (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_NewEmpty">PyCode_NewEmpty (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCode_Type">PyCode_Type (C variable)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_BackslashReplaceErrors">PyCodec_BackslashReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Decode">PyCodec_Decode (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Decoder">PyCodec_Decoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Encode">PyCodec_Encode (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Encoder">PyCodec_Encoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IgnoreErrors">PyCodec_IgnoreErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IncrementalDecoder">PyCodec_IncrementalDecoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_IncrementalEncoder">PyCodec_IncrementalEncoder (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_KnownEncoding">PyCodec_KnownEncoding (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_LookupError">PyCodec_LookupError (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_Register">PyCodec_Register (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_RegisterError">PyCodec_RegisterError (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_ReplaceErrors">PyCodec_ReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StreamReader">PyCodec_StreamReader (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StreamWriter">PyCodec_StreamWriter (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_StrictErrors">PyCodec_StrictErrors (C function)</a>
</li>
      <li><a href="c-api/codec.html#c.PyCodec_XMLCharRefReplaceErrors">PyCodec_XMLCharRefReplaceErrors (C function)</a>
</li>
      <li><a href="c-api/code.html#c.PyCodeObject">PyCodeObject (C type)</a>
</li>
      <li><a href="library/py_compile.html#py_compile.PyCompileError">PyCompileError</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyCompilerFlags">PyCompilerFlags (C type)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_AsCComplex">PyComplex_AsCComplex (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_Check">PyComplex_Check (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_CheckExact">PyComplex_CheckExact (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_FromCComplex">PyComplex_FromCComplex (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_FromDoubles">PyComplex_FromDoubles (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_ImagAsDouble">PyComplex_ImagAsDouble (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_RealAsDouble">PyComplex_RealAsDouble (C function)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplex_Type">PyComplex_Type (C variable)</a>
</li>
      <li><a href="c-api/complex.html#c.PyComplexObject">PyComplexObject (C type)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_Check">PyDate_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_CheckExact">PyDate_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_FromDate">PyDate_FromDate (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDate_FromTimestamp">PyDate_FromTimestamp (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_Check">PyDateTime_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_CheckExact">PyDateTime_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_HOUR">PyDateTime_DATE_GET_HOUR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_MICROSECOND">PyDateTime_DATE_GET_MICROSECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_MINUTE">PyDateTime_DATE_GET_MINUTE (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_DATE_GET_SECOND">PyDateTime_DATE_GET_SECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_FromDateAndTime">PyDateTime_FromDateAndTime (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_FromTimestamp">PyDateTime_FromTimestamp (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_DAY">PyDateTime_GET_DAY (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_MONTH">PyDateTime_GET_MONTH (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_GET_YEAR">PyDateTime_GET_YEAR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_HOUR">PyDateTime_TIME_GET_HOUR (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_MICROSECOND">PyDateTime_TIME_GET_MICROSECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_MINUTE">PyDateTime_TIME_GET_MINUTE (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDateTime_TIME_GET_SECOND">PyDateTime_TIME_GET_SECOND (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_Check">PyDelta_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_CheckExact">PyDelta_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyDelta_FromDSU">PyDelta_FromDSU (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_IsData">PyDescr_IsData (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewClassMethod">PyDescr_NewClassMethod (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewGetSet">PyDescr_NewGetSet (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewMember">PyDescr_NewMember (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewMethod">PyDescr_NewMethod (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyDescr_NewWrapper">PyDescr_NewWrapper (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Check">PyDict_Check (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_CheckExact">PyDict_CheckExact (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Clear">PyDict_Clear (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Contains">PyDict_Contains (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Copy">PyDict_Copy (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_DelItem">PyDict_DelItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_DelItemString">PyDict_DelItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_GetItem">PyDict_GetItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_GetItemString">PyDict_GetItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Items">PyDict_Items (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Keys">PyDict_Keys (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Merge">PyDict_Merge (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_MergeFromSeq2">PyDict_MergeFromSeq2 (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_New">PyDict_New (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Next">PyDict_Next (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_SetItem">PyDict_SetItem (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_SetItemString">PyDict_SetItemString (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Size">PyDict_Size (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Type">PyDict_Type (C variable)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Update">PyDict_Update (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDict_Values">PyDict_Values (C function)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDictObject">PyDictObject (C type)</a>
</li>
      <li><a href="c-api/dict.html#c.PyDictProxy_New">PyDictProxy_New (C function)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PyDLL">PyDLL (class in ctypes)</a>
</li>
      <li><a href="library/pydoc.html#module-pydoc">pydoc (module)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_BadArgument">PyErr_BadArgument (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_BadInternalCall">PyErr_BadInternalCall (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_CheckSignals">PyErr_CheckSignals (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Clear">PyErr_Clear (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-13">PyErr_Clear()</a>, <a href="c-api/intro.html#index-19">[1]</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_ExceptionMatches">PyErr_ExceptionMatches (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-19">PyErr_ExceptionMatches()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Fetch">PyErr_Fetch (C function)</a>
</li>
      <li><a href="extending/newtypes.html#index-1">PyErr_Fetch()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Format">PyErr_Format (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_GivenExceptionMatches">PyErr_GivenExceptionMatches (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NewException">PyErr_NewException (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NewExceptionWithDoc">PyErr_NewExceptionWithDoc (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NoMemory">PyErr_NoMemory (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_NormalizeException">PyErr_NormalizeException (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Occurred">PyErr_Occurred (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-12">PyErr_Occurred()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Print">PyErr_Print (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_PrintEx">PyErr_PrintEx (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Restore">PyErr_Restore (C function)</a>
</li>
      <li><a href="extending/newtypes.html#index-1">PyErr_Restore()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErr">PyErr_SetExcFromWindowsErr (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErrWithFilename">PyErr_SetExcFromWindowsErrWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetExcFromWindowsErrWithFilenameObject">PyErr_SetExcFromWindowsErrWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrno">PyErr_SetFromErrno (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrnoWithFilename">PyErr_SetFromErrnoWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromErrnoWithFilenameObject">PyErr_SetFromErrnoWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErr">PyErr_SetFromWindowsErr (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErrWithFilename">PyErr_SetFromWindowsErrWithFilename (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetFromWindowsErrWithFilenameObject">PyErr_SetFromWindowsErrWithFilenameObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetInterrupt">PyErr_SetInterrupt (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetNone">PyErr_SetNone (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetObject">PyErr_SetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_SetString">PyErr_SetString (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-13">PyErr_SetString()</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_Warn">PyErr_Warn (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnEx">PyErr_WarnEx (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnExplicit">PyErr_WarnExplicit (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WarnPy3k">PyErr_WarnPy3k (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyErr_WriteUnraisable">PyErr_WriteUnraisable (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_AcquireLock">PyEval_AcquireLock (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_AcquireLock()</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_AcquireThread">PyEval_AcquireThread (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalCode">PyEval_EvalCode (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalCodeEx">PyEval_EvalCodeEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalFrame">PyEval_EvalFrame (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_EvalFrameEx">PyEval_EvalFrameEx (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetBuiltins">PyEval_GetBuiltins (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_GetCallStats">PyEval_GetCallStats (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFrame">PyEval_GetFrame (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFuncDesc">PyEval_GetFuncDesc (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetFuncName">PyEval_GetFuncName (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetGlobals">PyEval_GetGlobals (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetLocals">PyEval_GetLocals (C function)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyEval_GetRestricted">PyEval_GetRestricted (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_InitThreads">PyEval_InitThreads (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_InitThreads()</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyEval_MergeCompilerFlags">PyEval_MergeCompilerFlags (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReInitThreads">PyEval_ReInitThreads (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReleaseLock">PyEval_ReleaseLock (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PyEval_ReleaseLock()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ReleaseThread">PyEval_ReleaseThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-18">PyEval_ReleaseThread()</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_RestoreThread">PyEval_RestoreThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-17">PyEval_RestoreThread()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SaveThread">PyEval_SaveThread (C function)</a>
</li>
      <li><a href="c-api/init.html#index-17">PyEval_SaveThread()</a>, <a href="c-api/init.html#index-18">[1]</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SetProfile">PyEval_SetProfile (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_SetTrace">PyEval_SetTrace (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyEval_ThreadsInitialized">PyEval_ThreadsInitialized (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ArithmeticError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_AssertionError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_AttributeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_BaseException</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_BufferError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_BytesWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_DeprecationWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_EnvironmentError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_EOFError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_Exception</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_FloatingPointError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_FutureWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_GeneratorExit</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ImportError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_ImportWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IndentationError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IndexError</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="c-api/exceptions.html#index-4">PyExc_IOError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_KeyboardInterrupt</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_KeyError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_LookupError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_MemoryError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_NameError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_NotImplementedError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_OSError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_OverflowError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_PendingDeprecationWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ReferenceError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_RuntimeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_RuntimeWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_StandardError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_StopIteration</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SyntaxError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_SyntaxWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SystemError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_SystemExit</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_TabError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_TypeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnboundLocalError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeDecodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeEncodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_UnicodeTranslateError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_UnicodeWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_UserWarning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ValueError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_VMSError</a>
</li>
      <li><a href="c-api/exceptions.html#index-5">PyExc_Warning</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_WindowsError</a>
</li>
      <li><a href="c-api/exceptions.html#index-4">PyExc_ZeroDivisionError</a>
</li>
      <li>
    pyexpat

      <ul>
        <li><a href="library/pyexpat.html#index-1">module</a>
</li>
      </ul></li>
      <li><a href="c-api/file.html#c.PyFile_AsFile">PyFile_AsFile (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Check">PyFile_Check (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_CheckExact">PyFile_CheckExact (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_DecUseCount">PyFile_DecUseCount (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_FromFile">PyFile_FromFile (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_FromString">PyFile_FromString (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_GetLine">PyFile_GetLine (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_IncUseCount">PyFile_IncUseCount (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Name">PyFile_Name (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetBufSize">PyFile_SetBufSize (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetEncoding">PyFile_SetEncoding (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SetEncodingAndErrors">PyFile_SetEncodingAndErrors (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_SoftSpace">PyFile_SoftSpace (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_Type">PyFile_Type (C variable)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_WriteObject">PyFile_WriteObject (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFile_WriteString">PyFile_WriteString (C function)</a>
</li>
      <li><a href="c-api/file.html#c.PyFileObject">PyFileObject (C type)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AS_DOUBLE">PyFloat_AS_DOUBLE (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsDouble">PyFloat_AsDouble (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsReprString">PyFloat_AsReprString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_AsString">PyFloat_AsString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_Check">PyFloat_Check (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_CheckExact">PyFloat_CheckExact (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_ClearFreeList">PyFloat_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_FromDouble">PyFloat_FromDouble (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_FromString">PyFloat_FromString (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetInfo">PyFloat_GetInfo (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetMax">PyFloat_GetMax (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_GetMin">PyFloat_GetMin (C function)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloat_Type">PyFloat_Type (C variable)</a>
</li>
      <li><a href="c-api/float.html#c.PyFloatObject">PyFloatObject (C type)</a>
</li>
      <li><a href="c-api/reflection.html#c.PyFrame_GetLineNumber">PyFrame_GetLineNumber (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_Check">PyFrozenSet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_CheckExact">PyFrozenSet_CheckExact (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_New">PyFrozenSet_New (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PyFrozenSet_Type">PyFrozenSet_Type (C variable)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_Check">PyFunction_Check (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetClosure">PyFunction_GetClosure (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetCode">PyFunction_GetCode (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetDefaults">PyFunction_GetDefaults (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetGlobals">PyFunction_GetGlobals (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_GetModule">PyFunction_GetModule (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_New">PyFunction_New (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_SetClosure">PyFunction_SetClosure (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_SetDefaults">PyFunction_SetDefaults (C function)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunction_Type">PyFunction_Type (C variable)</a>
</li>
      <li><a href="c-api/function.html#c.PyFunctionObject">PyFunctionObject (C type)</a>
</li>
      <li><a href="library/ctypes.html#ctypes.PYFUNCTYPE">PYFUNCTYPE() (in module ctypes)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_Check">PyGen_Check (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_CheckExact">PyGen_CheckExact (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_New">PyGen_New (C function)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGen_Type">PyGen_Type (C variable)</a>
</li>
      <li><a href="c-api/gen.html#c.PyGenObject">PyGenObject (C type)</a>
</li>
      <li><a href="c-api/structures.html#c.PyGetSetDef">PyGetSetDef (C type)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_Ensure">PyGILState_Ensure (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_GetThisThreadState">PyGILState_GetThisThreadState (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyGILState_Release">PyGILState_Release (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_AddModule">PyImport_AddModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_AppendInittab">PyImport_AppendInittab (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_Cleanup">PyImport_Cleanup (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExecCodeModule">PyImport_ExecCodeModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExecCodeModuleEx">PyImport_ExecCodeModuleEx (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ExtendInittab">PyImport_ExtendInittab (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_FrozenModules">PyImport_FrozenModules (C variable)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetImporter">PyImport_GetImporter (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetMagicNumber">PyImport_GetMagicNumber (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_GetModuleDict">PyImport_GetModuleDict (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_Import">PyImport_Import (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportFrozenModule">PyImport_ImportFrozenModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModule">PyImport_ImportModule (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleEx">PyImport_ImportModuleEx (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleLevel">PyImport_ImportModuleLevel (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ImportModuleNoBlock">PyImport_ImportModuleNoBlock (C function)</a>
</li>
      <li><a href="c-api/import.html#c.PyImport_ReloadModule">PyImport_ReloadModule (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyIndex_Check">PyIndex_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_Check">PyInstance_Check (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_New">PyInstance_New (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_NewRaw">PyInstance_NewRaw (C function)</a>
</li>
      <li><a href="c-api/class.html#c.PyInstance_Type">PyInstance_Type (C variable)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AS_LONG">PyInt_AS_LONG (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsLong">PyInt_AsLong (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsSsize_t">PyInt_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsUnsignedLongLongMask">PyInt_AsUnsignedLongLongMask (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_AsUnsignedLongMask">PyInt_AsUnsignedLongMask (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_Check">PyInt_Check (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_CheckExact">PyInt_CheckExact (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_ClearFreeList">PyInt_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromLong">PyInt_FromLong (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromSize_t">PyInt_FromSize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromSsize_t">PyInt_FromSsize_t (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_FromString">PyInt_FromString (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_GetMax">PyInt_GetMax (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyInt_Type">PyInt_Type (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState">PyInterpreterState (C type)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Clear">PyInterpreterState_Clear (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Delete">PyInterpreterState_Delete (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Head">PyInterpreterState_Head (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_New">PyInterpreterState_New (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_Next">PyInterpreterState_Next (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyInterpreterState_ThreadHead">PyInterpreterState_ThreadHead (C function)</a>
</li>
      <li><a href="c-api/int.html#c.PyIntObject">PyIntObject (C type)</a>
</li>
      <li><a href="c-api/iter.html#c.PyIter_Check">PyIter_Check (C function)</a>
</li>
      <li><a href="c-api/iter.html#c.PyIter_Next">PyIter_Next (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Append">PyList_Append (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_AsTuple">PyList_AsTuple (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Check">PyList_Check (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_CheckExact">PyList_CheckExact (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GET_ITEM">PyList_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GET_SIZE">PyList_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GetItem">PyList_GetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-9">PyList_GetItem()</a>
</li>
      <li><a href="c-api/list.html#c.PyList_GetSlice">PyList_GetSlice (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Insert">PyList_Insert (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_New">PyList_New (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Reverse">PyList_Reverse (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SET_ITEM">PyList_SET_ITEM (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SetItem">PyList_SetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-7">PyList_SetItem()</a>
</li>
      <li><a href="c-api/list.html#c.PyList_SetSlice">PyList_SetSlice (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Size">PyList_Size (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Sort">PyList_Sort (C function)</a>
</li>
      <li><a href="c-api/list.html#c.PyList_Type">PyList_Type (C variable)</a>
</li>
      <li><a href="c-api/list.html#c.PyListObject">PyListObject (C type)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsDouble">PyLong_AsDouble (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLong">PyLong_AsLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongAndOverflow">PyLong_AsLongAndOverflow (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongLong">PyLong_AsLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsLongLongAndOverflow">PyLong_AsLongLongAndOverflow (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsSsize_t">PyLong_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLong">PyLong_AsUnsignedLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongLong">PyLong_AsUnsignedLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongLongMask">PyLong_AsUnsignedLongLongMask (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsUnsignedLongMask">PyLong_AsUnsignedLongMask (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_AsVoidPtr">PyLong_AsVoidPtr (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_Check">PyLong_Check (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_CheckExact">PyLong_CheckExact (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromDouble">PyLong_FromDouble (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromLong">PyLong_FromLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromLongLong">PyLong_FromLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromSize_t">PyLong_FromSize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromSsize_t">PyLong_FromSsize_t (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromString">PyLong_FromString (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnicode">PyLong_FromUnicode (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnsignedLong">PyLong_FromUnsignedLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromUnsignedLongLong">PyLong_FromUnsignedLongLong (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_FromVoidPtr">PyLong_FromVoidPtr (C function)</a>
</li>
      <li><a href="c-api/long.html#c.PyLong_Type">PyLong_Type (C variable)</a>
</li>
      <li><a href="c-api/long.html#c.PyLongObject">PyLongObject (C type)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Check">PyMapping_Check (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_DelItem">PyMapping_DelItem (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_DelItemString">PyMapping_DelItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_GetItemString">PyMapping_GetItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_HasKey">PyMapping_HasKey (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_HasKeyString">PyMapping_HasKeyString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Items">PyMapping_Items (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Keys">PyMapping_Keys (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Length">PyMapping_Length (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_SetItemString">PyMapping_SetItemString (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Size">PyMapping_Size (C function)</a>
</li>
      <li><a href="c-api/mapping.html#c.PyMapping_Values">PyMapping_Values (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods">PyMappingMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_ass_subscript">PyMappingMethods.mp_ass_subscript (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_length">PyMappingMethods.mp_length (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyMappingMethods.mp_subscript">PyMappingMethods.mp_subscript (C member)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadLastObjectFromFile">PyMarshal_ReadLastObjectFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadLongFromFile">PyMarshal_ReadLongFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadObjectFromFile">PyMarshal_ReadObjectFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadObjectFromString">PyMarshal_ReadObjectFromString (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_ReadShortFromFile">PyMarshal_ReadShortFromFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteLongToFile">PyMarshal_WriteLongToFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteObjectToFile">PyMarshal_WriteObjectToFile (C function)</a>
</li>
      <li><a href="c-api/marshal.html#c.PyMarshal_WriteObjectToString">PyMarshal_WriteObjectToString (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Del">PyMem_Del (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Free">PyMem_Free (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Malloc">PyMem_Malloc (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_New">PyMem_New (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Realloc">PyMem_Realloc (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyMem_Resize">PyMem_Resize (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyMemberDef">PyMemberDef (C type)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_Check">PyMemoryView_Check (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_FromBuffer">PyMemoryView_FromBuffer (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_FromObject">PyMemoryView_FromObject (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_GET_BUFFER">PyMemoryView_GET_BUFFER (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyMemoryView_GetContiguous">PyMemoryView_GetContiguous (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Check">PyMethod_Check (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Class">PyMethod_Class (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_ClearFreeList">PyMethod_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Function">PyMethod_Function (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_CLASS">PyMethod_GET_CLASS (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_FUNCTION">PyMethod_GET_FUNCTION (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_GET_SELF">PyMethod_GET_SELF (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_New">PyMethod_New (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Self">PyMethod_Self (C function)</a>
</li>
      <li><a href="c-api/method.html#c.PyMethod_Type">PyMethod_Type (C variable)</a>
</li>
      <li><a href="c-api/structures.html#c.PyMethodDef">PyMethodDef (C type)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddIntConstant">PyModule_AddIntConstant (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddIntMacro">PyModule_AddIntMacro (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddObject">PyModule_AddObject (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddStringConstant">PyModule_AddStringConstant (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_AddStringMacro">PyModule_AddStringMacro (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_Check">PyModule_Check (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_CheckExact">PyModule_CheckExact (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetDict">PyModule_GetDict (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetFilename">PyModule_GetFilename (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_GetName">PyModule_GetName (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_New">PyModule_New (C function)</a>
</li>
      <li><a href="c-api/module.html#c.PyModule_Type">PyModule_Type (C variable)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Absolute">PyNumber_Absolute (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Add">PyNumber_Add (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_And">PyNumber_And (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_AsSsize_t">PyNumber_AsSsize_t (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Check">PyNumber_Check (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Coerce">PyNumber_Coerce (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_CoerceEx">PyNumber_CoerceEx (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Divide">PyNumber_Divide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Divmod">PyNumber_Divmod (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Float">PyNumber_Float (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_FloorDivide">PyNumber_FloorDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Index">PyNumber_Index (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceAdd">PyNumber_InPlaceAdd (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceAnd">PyNumber_InPlaceAnd (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceDivide">PyNumber_InPlaceDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceFloorDivide">PyNumber_InPlaceFloorDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceLshift">PyNumber_InPlaceLshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceMultiply">PyNumber_InPlaceMultiply (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceOr">PyNumber_InPlaceOr (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlacePower">PyNumber_InPlacePower (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceRemainder">PyNumber_InPlaceRemainder (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceRshift">PyNumber_InPlaceRshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceSubtract">PyNumber_InPlaceSubtract (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceTrueDivide">PyNumber_InPlaceTrueDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_InPlaceXor">PyNumber_InPlaceXor (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Int">PyNumber_Int (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Invert">PyNumber_Invert (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Long">PyNumber_Long (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Lshift">PyNumber_Lshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Multiply">PyNumber_Multiply (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Negative">PyNumber_Negative (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Or">PyNumber_Or (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Positive">PyNumber_Positive (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Power">PyNumber_Power (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Remainder">PyNumber_Remainder (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Rshift">PyNumber_Rshift (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Subtract">PyNumber_Subtract (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_ToBase">PyNumber_ToBase (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_TrueDivide">PyNumber_TrueDivide (C function)</a>
</li>
      <li><a href="c-api/number.html#c.PyNumber_Xor">PyNumber_Xor (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyNumberMethods">PyNumberMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyNumberMethods.nb_coerce">PyNumberMethods.nb_coerce (C member)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject">PyObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject._ob_next">PyObject._ob_next (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject._ob_prev">PyObject._ob_prev (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject.ob_refcnt">PyObject.ob_refcnt (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyObject.ob_type">PyObject.ob_type (C member)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsCharBuffer">PyObject_AsCharBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_AsFileDescriptor">PyObject_AsFileDescriptor (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsReadBuffer">PyObject_AsReadBuffer (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_AsWriteBuffer">PyObject_AsWriteBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Bytes">PyObject_Bytes (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Call">PyObject_Call (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallFunction">PyObject_CallFunction (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallFunctionObjArgs">PyObject_CallFunctionObjArgs (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallMethod">PyObject_CallMethod (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallMethodObjArgs">PyObject_CallMethodObjArgs (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_CallObject">PyObject_CallObject (C function)</a>
</li>
      <li><a href="extending/extending.html#index-0">PyObject_CallObject()</a>
</li>
      <li><a href="c-api/buffer.html#c.PyObject_CheckBuffer">PyObject_CheckBuffer (C function)</a>
</li>
      <li><a href="c-api/objbuffer.html#c.PyObject_CheckReadBuffer">PyObject_CheckReadBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Cmp">PyObject_Cmp (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Compare">PyObject_Compare (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_Del">PyObject_Del (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelAttr">PyObject_DelAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelAttrString">PyObject_DelAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_DelItem">PyObject_DelItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Dir">PyObject_Dir (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Free">PyObject_Free (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Del">PyObject_GC_Del (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_New">PyObject_GC_New (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_NewVar">PyObject_GC_NewVar (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Resize">PyObject_GC_Resize (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_Track">PyObject_GC_Track (C function)</a>
</li>
      <li><a href="c-api/gcsupport.html#c.PyObject_GC_UnTrack">PyObject_GC_UnTrack (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GenericGetAttr">PyObject_GenericGetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GenericSetAttr">PyObject_GenericSetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetAttr">PyObject_GetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetAttrString">PyObject_GetAttrString (C function)</a>
</li>
      <li><a href="c-api/buffer.html#c.PyObject_GetBuffer">PyObject_GetBuffer (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetItem">PyObject_GetItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_GetIter">PyObject_GetIter (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HasAttr">PyObject_HasAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HasAttrString">PyObject_HasAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Hash">PyObject_Hash (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_HashNotImplemented">PyObject_HashNotImplemented (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_HEAD">PyObject_HEAD (C macro)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_HEAD_INIT">PyObject_HEAD_INIT (C macro)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_Init">PyObject_Init (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_InitVar">PyObject_InitVar (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsInstance">PyObject_IsInstance (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsSubclass">PyObject_IsSubclass (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_IsTrue">PyObject_IsTrue (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Length">PyObject_Length (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Malloc">PyObject_Malloc (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_New">PyObject_New (C function)</a>
</li>
      <li><a href="c-api/allocation.html#c.PyObject_NewVar">PyObject_NewVar (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Not">PyObject_Not (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Print">PyObject_Print (C function)</a>
</li>
      <li><a href="c-api/memory.html#c.PyObject_Realloc">PyObject_Realloc (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Repr">PyObject_Repr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_RichCompare">PyObject_RichCompare (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_RichCompareBool">PyObject_RichCompareBool (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetAttr">PyObject_SetAttr (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetAttrString">PyObject_SetAttrString (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_SetItem">PyObject_SetItem (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Size">PyObject_Size (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Str">PyObject_Str (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Type">PyObject_Type (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_TypeCheck">PyObject_TypeCheck (C function)</a>
</li>
      <li><a href="c-api/object.html#c.PyObject_Unicode">PyObject_Unicode (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyObject_VAR_HEAD">PyObject_VAR_HEAD (C macro)</a>
</li>
      <li><a href="library/gl.html#index-0">PyOpenGL</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_AfterFork">PyOS_AfterFork (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_atof">PyOS_ascii_atof (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_formatd">PyOS_ascii_formatd (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_ascii_strtod">PyOS_ascii_strtod (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_CheckStack">PyOS_CheckStack (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_double_to_string">PyOS_double_to_string (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_getsig">PyOS_getsig (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PyOS_setsig">PyOS_setsig (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_snprintf">PyOS_snprintf (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_stricmp">PyOS_stricmp (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_string_to_double">PyOS_string_to_double (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_strnicmp">PyOS_strnicmp (C function)</a>
</li>
      <li><a href="c-api/conversion.html#c.PyOS_vsnprintf">PyOS_vsnprintf (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseFile">PyParser_SimpleParseFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseFileFlags">PyParser_SimpleParseFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseString">PyParser_SimpleParseString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseStringFlags">PyParser_SimpleParseStringFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyParser_SimpleParseStringFlagsFilename">PyParser_SimpleParseStringFlagsFilename (C function)</a>
</li>
      <li>
    PyPI

      <ul>
        <li><a href="distutils/packageindex.html#index-0">(see Python Package Index (PyPI))</a>
</li>
      </ul></li>
      <li><a href="c-api/descriptor.html#c.PyProperty_Type">PyProperty_Type (C variable)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFile">PyRun_AnyFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileEx">PyRun_AnyFileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileExFlags">PyRun_AnyFileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_AnyFileFlags">PyRun_AnyFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_File">PyRun_File (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileEx">PyRun_FileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileExFlags">PyRun_FileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_FileFlags">PyRun_FileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveLoop">PyRun_InteractiveLoop (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveLoopFlags">PyRun_InteractiveLoopFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveOne">PyRun_InteractiveOne (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_InteractiveOneFlags">PyRun_InteractiveOneFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFile">PyRun_SimpleFile (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileEx">PyRun_SimpleFileEx (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileExFlags">PyRun_SimpleFileExFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleFileFlags">PyRun_SimpleFileFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleString">PyRun_SimpleString (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_SimpleStringFlags">PyRun_SimpleStringFlags (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_String">PyRun_String (C function)</a>
</li>
      <li><a href="c-api/veryhigh.html#c.PyRun_StringFlags">PyRun_StringFlags (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_Check">PySeqIter_Check (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_New">PySeqIter_New (C function)</a>
</li>
      <li><a href="c-api/iterator.html#c.PySeqIter_Type">PySeqIter_Type (C variable)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Check">PySequence_Check (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Concat">PySequence_Concat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Contains">PySequence_Contains (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Count">PySequence_Count (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_DelItem">PySequence_DelItem (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_DelSlice">PySequence_DelSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast">PySequence_Fast (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_GET_ITEM">PySequence_Fast_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_GET_SIZE">PySequence_Fast_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Fast_ITEMS">PySequence_Fast_ITEMS (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_GetItem">PySequence_GetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-9">PySequence_GetItem()</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_GetSlice">PySequence_GetSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Index">PySequence_Index (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_InPlaceConcat">PySequence_InPlaceConcat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_InPlaceRepeat">PySequence_InPlaceRepeat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_ITEM">PySequence_ITEM (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Length">PySequence_Length (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_List">PySequence_List (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Repeat">PySequence_Repeat (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_SetItem">PySequence_SetItem (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_SetSlice">PySequence_SetSlice (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Size">PySequence_Size (C function)</a>
</li>
      <li><a href="c-api/sequence.html#c.PySequence_Tuple">PySequence_Tuple (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods">PySequenceMethods (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_ass_item">PySequenceMethods.sq_ass_item (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_concat">PySequenceMethods.sq_concat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_contains">PySequenceMethods.sq_contains (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_inplace_concat">PySequenceMethods.sq_inplace_concat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_inplace_repeat">PySequenceMethods.sq_inplace_repeat (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_item">PySequenceMethods.sq_item (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_length">PySequenceMethods.sq_length (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PySequenceMethods.sq_repeat">PySequenceMethods.sq_repeat (C member)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Add">PySet_Add (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Check">PySet_Check (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Clear">PySet_Clear (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Contains">PySet_Contains (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Discard">PySet_Discard (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_GET_SIZE">PySet_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_New">PySet_New (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Pop">PySet_Pop (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Size">PySet_Size (C function)</a>
</li>
      <li><a href="c-api/set.html#c.PySet_Type">PySet_Type (C variable)</a>
</li>
      <li><a href="c-api/set.html#c.PySetObject">PySetObject (C type)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PySignal_SetWakeupFd">PySignal_SetWakeupFd (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_Check">PySlice_Check (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_GetIndices">PySlice_GetIndices (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_GetIndicesEx">PySlice_GetIndicesEx (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_New">PySlice_New (C function)</a>
</li>
      <li><a href="c-api/slice.html#c.PySlice_Type">PySlice_Type (C variable)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AS_STRING">PyString_AS_STRING (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsDecodedObject">PyString_AsDecodedObject (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsEncodedObject">PyString_AsEncodedObject (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsString">PyString_AsString (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_AsStringAndSize">PyString_AsStringAndSize (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Check">PyString_Check (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_CheckExact">PyString_CheckExact (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Concat">PyString_Concat (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_ConcatAndDel">PyString_ConcatAndDel (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Decode">PyString_Decode (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Encode">PyString_Encode (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Format">PyString_Format (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromFormat">PyString_FromFormat (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromFormatV">PyString_FromFormatV (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromString">PyString_FromString (C function)</a>
</li>
      <li><a href="c-api/dict.html#index-2">PyString_FromString()</a>
</li>
      <li><a href="c-api/string.html#c.PyString_FromStringAndSize">PyString_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_GET_SIZE">PyString_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_InternFromString">PyString_InternFromString (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_InternInPlace">PyString_InternInPlace (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Size">PyString_Size (C function)</a>
</li>
      <li><a href="c-api/string.html#c.PyString_Type">PyString_Type (C variable)</a>
</li>
      <li><a href="c-api/string.html#c.PyStringObject">PyStringObject (C type)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_AddWarnOption">PySys_AddWarnOption (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_GetFile">PySys_GetFile (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_GetObject">PySys_GetObject (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_ResetWarnOptions">PySys_ResetWarnOptions (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PySys_SetArgv">PySys_SetArgv (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PySys_SetArgv()</a>
</li>
      <li><a href="c-api/init.html#c.PySys_SetArgvEx">PySys_SetArgvEx (C function)</a>
</li>
      <li><a href="c-api/init.html#index-0">PySys_SetArgvEx()</a>, <a href="c-api/intro.html#index-21">[1]</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_SetObject">PySys_SetObject (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_SetPath">PySys_SetPath (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_WriteStderr">PySys_WriteStderr (C function)</a>
</li>
      <li><a href="c-api/sys.html#c.PySys_WriteStdout">PySys_WriteStdout (C function)</a>
</li>
      <li><a href="glossary.html#term-python-3000"><strong>Python 3000</strong></a>
</li>
      <li><a href="library/idle.html#index-0">Python Editor</a>
</li>
      <li>
    Python Enhancement Proposals

      <ul>
        <li><a href="glossary.html#index-6">PEP 1</a>
</li>
        <li><a href="whatsnew/2.0.html#index-0">PEP 100</a>
</li>
        <li><a href="using/windows.html#index-0">PEP 11</a>
</li>
        <li><a href="library/weakref.html#index-0">PEP 205</a>, <a href="whatsnew/2.1.html#index-6">[1]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-2">PEP 207</a>
</li>
        <li><a href="whatsnew/2.1.html#index-10">PEP 208</a>
</li>
        <li><a href="whatsnew/2.1.html#index-9">PEP 217</a>
</li>
        <li><a href="whatsnew/2.3.html#index-0">PEP 218</a>, <a href="whatsnew/2.4.html#index-0">[1]</a>, <a href="whatsnew/2.4.html#index-13">[2]</a>
</li>
        <li><a href="library/__future__.html#index-0">PEP 227</a>, <a href="whatsnew/2.1.html#index-0">[1]</a>, <a href="whatsnew/2.2.html#index-16">[2]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-5">PEP 229</a>
</li>
        <li><a href="using/cmdline.html#index-14">PEP 230</a>, <a href="whatsnew/2.1.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-7">PEP 232</a>
</li>
        <li><a href="whatsnew/2.2.html#index-7">PEP 234</a>
</li>
        <li><a href="library/functions.html#index-1">PEP 236</a>, <a href="reference/simple_stmts.html#index-53">[1]</a>, <a href="whatsnew/2.1.html#index-1">[2]</a>
</li>
        <li><a href="library/stdtypes.html#index-26">PEP 237</a>, <a href="whatsnew/2.2.html#index-10">[1]</a>, <a href="whatsnew/2.4.html#index-1">[2]</a>, <a href="whatsnew/2.4.html#index-16">[3]</a>
</li>
        <li><a href="c-api/veryhigh.html#index-3">PEP 238</a>, <a href="glossary.html#index-2">[1]</a>, <a href="library/__future__.html#index-2">[2]</a>, <a href="using/cmdline.html#index-9">[3]</a>, <a href="whatsnew/2.2.html#index-11">[4]</a>, <a href="whatsnew/2.2.html#index-12">[5]</a>, <a href="whatsnew/2.2.html#index-13">[6]</a>
</li>
        <li><a href="whatsnew/2.1.html#index-11">PEP 241</a>
</li>
        <li><a href="whatsnew/2.1.html#index-12">PEP 243</a>
</li>
        <li><a href="library/sqlite3.html#index-0">PEP 249</a>, <a href="library/sqlite3.html#index-1">[1]</a>, <a href="whatsnew/2.5.html#index-21">[2]</a>, <a href="whatsnew/2.5.html#index-22">[3]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-2">PEP 252</a>, <a href="whatsnew/2.2.html#index-4">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-0">PEP 253</a>, <a href="whatsnew/2.2.html#index-1">[1]</a>, <a href="whatsnew/2.2.html#index-3">[2]</a>, <a href="whatsnew/2.2.html#index-5">[3]</a>, <a href="whatsnew/2.2.html#index-6">[4]</a>
</li>
        <li><a href="library/__future__.html#index-1">PEP 255</a>, <a href="reference/simple_stmts.html#index-29">[1]</a>, <a href="whatsnew/2.2.html#index-8">[2]</a>, <a href="whatsnew/2.2.html#index-9">[3]</a>, <a href="whatsnew/2.3.html#index-1">[4]</a>, <a href="whatsnew/2.3.html#index-2">[5]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-14">PEP 261</a>, <a href="whatsnew/2.2.html#index-15">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-3">PEP 263</a>, <a href="whatsnew/2.5.html#index-17">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-22">PEP 264</a>
</li>
        <li><a href="library/zipimport.html#index-0">PEP 273</a>, <a href="whatsnew/2.3.html#index-4">[1]</a>, <a href="whatsnew/2.3.html#index-5">[2]</a>
</li>
        <li><a href="faq/design.html#index-0">PEP 275</a>
</li>
        <li><a href="whatsnew/2.3.html#index-7">PEP 277</a>
</li>
        <li><a href="glossary.html#index-7">PEP 278</a>, <a href="whatsnew/2.3.html#index-9">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-10">PEP 279</a>
</li>
        <li><a href="library/logging.html#index-1">PEP 282</a>, <a href="library/shutil.html#index-2">[1]</a>, <a href="whatsnew/2.3.html#index-11">[2]</a>, <a href="whatsnew/2.3.html#index-12">[3]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-13">PEP 285</a>, <a href="whatsnew/2.3.html#index-14">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-10">PEP 288</a>
</li>
        <li><a href="howto/functional.html#index-0">PEP 289</a>, <a href="whatsnew/2.4.html#index-15">[1]</a>, <a href="whatsnew/2.4.html#index-2">[2]</a>
</li>
        <li><a href="library/string.html#index-4">PEP 292</a>, <a href="whatsnew/2.4.html#index-3">[1]</a>
</li>
        <li><a href="whatsnew/2.3.html#index-15">PEP 293</a>
</li>
        <li><a href="whatsnew/2.6.html#index-1">PEP 3000</a>
</li>
        <li><a href="distutils/apiref.html#index-4">PEP 301</a>, <a href="whatsnew/2.3.html#index-16">[1]</a>
</li>
        <li><a href="glossary.html#index-1">PEP 302</a>, <a href="glossary.html#index-5">[1]</a>, <a href="library/functions.html#index-9">[2]</a>, <a href="library/imp.html#index-4">[3]</a>, <a href="library/linecache.html#index-1">[4]</a>, <a href="library/pkgutil.html#index-0">[5]</a>, <a href="library/pkgutil.html#index-1">[6]</a>, <a href="library/pkgutil.html#index-10">[7]</a>, <a href="library/pkgutil.html#index-11">[8]</a>, <a href="library/pkgutil.html#index-2">[9]</a>, <a href="library/pkgutil.html#index-3">[10]</a>, <a href="library/pkgutil.html#index-4">[11]</a>, <a href="library/pkgutil.html#index-5">[12]</a>, <a href="library/pkgutil.html#index-6">[13]</a>, <a href="library/pkgutil.html#index-7">[14]</a>, <a href="library/pkgutil.html#index-8">[15]</a>, <a href="library/pkgutil.html#index-9">[16]</a>, <a href="library/runpy.html#index-1">[17]</a>, <a href="library/runpy.html#index-2">[18]</a>, <a href="library/runpy.html#index-4">[19]</a>, <a href="library/sys.html#index-10">[20]</a>, <a href="library/sys.html#index-4">[21]</a>, <a href="library/sys.html#index-9">[22]</a>, <a href="library/zipimport.html#index-1">[23]</a>, <a href="reference/simple_stmts.html#index-42">[24]</a>, <a href="reference/simple_stmts.html#index-45">[25]</a>, <a href="whatsnew/2.3.html#index-17">[26]</a>, <a href="whatsnew/2.3.html#index-18">[27]</a>, <a href="whatsnew/2.3.html#index-19">[28]</a>, <a href="whatsnew/2.3.html#index-6">[29]</a>
</li>
        <li><a href="library/csv.html#index-1">PEP 305</a>, <a href="whatsnew/2.3.html#index-20">[1]</a>
</li>
        <li><a href="library/pickle.html#index-2">PEP 307</a>, <a href="whatsnew/2.3.html#index-21">[1]</a>, <a href="whatsnew/2.3.html#index-22">[2]</a>, <a href="whatsnew/2.3.html#index-23">[3]</a>
</li>
        <li><a href="reference/expressions.html#index-74">PEP 308</a>, <a href="whatsnew/2.5.html#index-1">[1]</a>, <a href="whatsnew/2.5.html#index-2">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-3">PEP 309</a>
</li>
        <li><a href="whatsnew/2.6.html#index-2">PEP 3100</a>
</li>
        <li><a href="library/string.html#index-1">PEP 3101</a>, <a href="library/string.html#index-2">[1]</a>, <a href="whatsnew/2.6.html#index-9">[2]</a>
</li>
        <li><a href="library/__future__.html#index-5">PEP 3105</a>, <a href="whatsnew/2.6.html#index-10">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-6">PEP 3106</a>
</li>
        <li><a href="whatsnew/2.6.html#index-11">PEP 3110</a>
</li>
        <li><a href="library/__future__.html#index-6">PEP 3112</a>, <a href="whatsnew/2.6.html#index-12">[1]</a>
</li>
        <li><a href="glossary.html#index-8">PEP 3116</a>, <a href="whatsnew/2.6.html#index-14">[1]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-15">PEP 3118</a>
</li>
        <li><a href="library/abc.html#index-0">PEP 3119</a>, <a href="library/collections.html#index-0">[1]</a>, <a href="reference/datamodel.html#index-86">[2]</a>, <a href="whatsnew/2.6.html#index-16">[3]</a>
</li>
        <li><a href="howto/cporting.html#index-0">PEP 3121</a>
</li>
        <li><a href="whatsnew/2.6.html#index-17">PEP 3127</a>
</li>
        <li><a href="whatsnew/2.6.html#index-18">PEP 3129</a>
</li>
        <li><a href="whatsnew/2.7.html#index-7">PEP 3137</a>
</li>
        <li><a href="distutils/apiref.html#index-0">PEP 314</a>, <a href="whatsnew/2.5.html#index-4">[1]</a>
</li>
        <li><a href="library/abc.html#index-1">PEP 3141</a>, <a href="library/numbers.html#index-0">[1]</a>, <a href="whatsnew/2.6.html#index-19">[2]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-12">PEP 318</a>, <a href="whatsnew/2.4.html#index-4">[1]</a>, <a href="whatsnew/2.4.html#index-5">[2]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-14">PEP 322</a>, <a href="whatsnew/2.4.html#index-6">[1]</a>
</li>
        <li><a href="library/subprocess.html#index-0">PEP 324</a>, <a href="whatsnew/2.4.html#index-8">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-11">PEP 325</a>
</li>
        <li><a href="whatsnew/2.4.html#index-9">PEP 327</a>
</li>
        <li><a href="library/__future__.html#index-3">PEP 328</a>, <a href="reference/simple_stmts.html#index-51">[1]</a>, <a href="whatsnew/2.4.html#index-10">[2]</a>, <a href="whatsnew/2.4.html#index-17">[3]</a>, <a href="whatsnew/2.5.html#index-5">[4]</a>
</li>
        <li><a href="whatsnew/2.4.html#index-11">PEP 331</a>
</li>
        <li><a href="howto/webservers.html#index-0">PEP 333</a>, <a href="library/wsgiref.html#index-0">[1]</a>, <a href="library/wsgiref.html#index-1">[2]</a>, <a href="library/wsgiref.html#index-10">[3]</a>, <a href="library/wsgiref.html#index-11">[4]</a>, <a href="library/wsgiref.html#index-12">[5]</a>, <a href="library/wsgiref.html#index-13">[6]</a>, <a href="library/wsgiref.html#index-14">[7]</a>, <a href="library/wsgiref.html#index-2">[8]</a>, <a href="library/wsgiref.html#index-3">[9]</a>, <a href="library/wsgiref.html#index-4">[10]</a>, <a href="library/wsgiref.html#index-6">[11]</a>, <a href="library/wsgiref.html#index-7">[12]</a>, <a href="library/wsgiref.html#index-8">[13]</a>, <a href="library/wsgiref.html#index-9">[14]</a>, <a href="whatsnew/2.5.html#index-23">[15]</a>, <a href="whatsnew/2.5.html#index-24">[16]</a>
</li>
        <li><a href="library/runpy.html#index-5">PEP 338</a>, <a href="using/cmdline.html#index-0">[1]</a>, <a href="whatsnew/2.5.html#index-6">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-27">PEP 339</a>
</li>
        <li><a href="whatsnew/2.5.html#index-7">PEP 341</a>
</li>
        <li><a href="howto/functional.html#index-1">PEP 342</a>, <a href="reference/expressions.html#index-27">[1]</a>, <a href="reference/simple_stmts.html#index-30">[2]</a>, <a href="whatsnew/2.5.html#index-28">[3]</a>, <a href="whatsnew/2.5.html#index-8">[4]</a>, <a href="whatsnew/2.5.html#index-9">[5]</a>
</li>
        <li><a href="glossary.html#index-0">PEP 343</a>, <a href="library/__future__.html#index-4">[1]</a>, <a href="library/contextlib.html#index-0">[2]</a>, <a href="reference/compound_stmts.html#index-16">[3]</a>, <a href="reference/datamodel.html#index-97">[4]</a>, <a href="whatsnew/2.5.html#index-12">[5]</a>, <a href="whatsnew/2.6.html#index-3">[6]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-25">PEP 347</a>
</li>
        <li><a href="whatsnew/2.5.html#index-13">PEP 352</a>, <a href="whatsnew/2.6.html#index-25">[1]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-14">PEP 353</a>, <a href="whatsnew/2.5.html#index-15">[1]</a>, <a href="whatsnew/2.5.html#index-26">[2]</a>
</li>
        <li><a href="whatsnew/2.5.html#index-0">PEP 356</a>
</li>
        <li><a href="whatsnew/2.5.html#index-16">PEP 357</a>
</li>
        <li><a href="whatsnew/2.6.html#index-0">PEP 361</a>
</li>
        <li><a href="library/runpy.html#index-6">PEP 366</a>
</li>
        <li><a href="library/site.html#index-9">PEP 370</a>, <a href="using/cmdline.html#index-11">[1]</a>, <a href="using/cmdline.html#index-24">[2]</a>, <a href="using/cmdline.html#index-25">[3]</a>, <a href="whatsnew/2.6.html#index-7">[4]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-8">PEP 371</a>
</li>
        <li><a href="whatsnew/2.7.html#index-2">PEP 372</a>
</li>
        <li><a href="whatsnew/2.7.html#index-0">PEP 373</a>
</li>
        <li><a href="library/string.html#index-3">PEP 378</a>, <a href="whatsnew/2.7.html#index-3">[1]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-4">PEP 389</a>
</li>
        <li><a href="whatsnew/2.7.html#index-5">PEP 391</a>
</li>
        <li><a href="distributing/index.html#index-0">PEP 427</a>
</li>
        <li><a href="whatsnew/2.7.html#index-16">PEP 434</a>
</li>
        <li><a href="library/ensurepip.html#index-0">PEP 453</a>, <a href="whatsnew/2.7.html#index-22">[1]</a>, <a href="whatsnew/2.7.html#index-23">[2]</a>, <a href="whatsnew/2.7.html#index-24">[3]</a>
</li>
        <li><a href="whatsnew/2.7.html#index-17">PEP 466</a>, <a href="whatsnew/2.7.html#index-18">[1]</a>, <a href="whatsnew/2.7.html#index-19">[2]</a>, <a href="whatsnew/2.7.html#index-20">[3]</a>
</li>
        <li><a href="library/ssl.html#index-2">PEP 476</a>, <a href="whatsnew/2.7.html#index-25">[1]</a>
</li>
        <li><a href="library/ensurepip.html#index-1">PEP 477</a>, <a href="whatsnew/2.7.html#index-21">[1]</a>
</li>
        <li><a href="library/ssl.html#index-3">PEP 493</a>, <a href="whatsnew/2.7.html#index-26">[1]</a>
</li>
        <li><a href="faq/general.html#index-1">PEP 5</a>, <a href="whatsnew/2.1.html#index-3">[1]</a>
</li>
        <li><a href="faq/general.html#index-0">PEP 6</a>
</li>
        <li><a href="faq/programming.html#index-0">PEP 8</a>, <a href="faq/windows.html#index-0">[1]</a>, <a href="library/email.html#index-7">[2]</a>, <a href="library/threading.html#index-0">[3]</a>, <a href="tutorial/controlflow.html#index-6">[4]</a>, <a href="using/unix.html#index-3">[5]</a>
</li>
      </ul></li>
      <li><a href="library/jpeg.html#index-1">Python Imaging Library</a>
</li>
      <li><a href="distutils/packageindex.html#index-0">Python Package Index (PyPI)</a>

      <ul>
        <li><a href="distutils/packageindex.html#index-2">.pypirc file</a>
</li>
      </ul></li>
      <li><a href="using/cmdline.html#index-3">PYTHON*</a>
</li>
      <li><a href="library/platform.html#platform.python_branch">python_branch() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_build">python_build() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_compiler">python_compiler() (in module platform)</a>
</li>
      <li><a href="library/xml.dom.html#index-0">PYTHON_DOM</a>
</li>
      <li><a href="library/platform.html#platform.python_implementation">python_implementation() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_revision">python_revision() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_version">python_version() (in module platform)</a>
</li>
      <li><a href="library/platform.html#platform.python_version_tuple">python_version_tuple() (in module platform)</a>
</li>
      <li><a href="whatsnew/2.1.html#index-8">PYTHONCASEOK</a>
</li>
      <li><a href="using/cmdline.html#index-2">PYTHONDEBUG</a>
</li>
      <li><a href="library/pydoc.html#index-2">PYTHONDOCS</a>
</li>
      <li><a href="library/sys.html#index-0">PYTHONDONTWRITEBYTECODE</a>, <a href="using/cmdline.html#index-1">[1]</a>, <a href="whatsnew/2.6.html#index-20">[2]</a>, <a href="whatsnew/2.6.html#index-24">[3]</a>
</li>
      <li><a href="c-api/typeobj.html#index-0">PYTHONDUMPREFS</a>
</li>
      <li><a href="library/random.html#index-0">PYTHONHASHSEED</a>, <a href="using/cmdline.html#index-10">[1]</a>, <a href="using/cmdline.html#index-23">[2]</a>
</li>
      <li><a href="c-api/init.html#index-11">PYTHONHOME</a>, <a href="c-api/init.html#index-12">[1]</a>, <a href="c-api/intro.html#index-24">[2]</a>, <a href="c-api/intro.html#index-27">[3]</a>, <a href="install/index.html#index-0">[4]</a>, <a href="install/index.html#index-1">[5]</a>, <a href="using/cmdline.html#index-16">[6]</a>, <a href="using/cmdline.html#index-17">[7]</a>, <a href="using/cmdline.html#index-20">[8]</a>, <a href="using/cmdline.html#index-5">[9]</a>, <a href="using/windows.html#index-3">[10]</a>
</li>
      <li><a href="glossary.html#term-pythonic"><strong>Pythonic</strong></a>
</li>
      <li><a href="using/cmdline.html#index-7">PYTHONINSPECT</a>, <a href="whatsnew/2.3.html#index-29">[1]</a>
</li>
      <li><a href="whatsnew/2.6.html#index-21">PYTHONIOENCODING</a>
</li>
      <li><a href="library/site.html#index-5">PYTHONNOUSERSITE</a>, <a href="library/site.html#index-8">[1]</a>, <a href="whatsnew/2.6.html#index-6">[2]</a>
</li>
      <li><a href="using/cmdline.html#index-8">PYTHONOPTIMIZE</a>
</li>
      <li><a href="c-api/intro.html#index-25">PYTHONPATH</a>, <a href="c-api/intro.html#index-28">[1]</a>, <a href="install/index.html#index-2">[2]</a>, <a href="install/index.html#index-3">[3]</a>, <a href="library/cgi.html#index-3">[4]</a>, <a href="library/sys.html#index-7">[5]</a>, <a href="library/sys.html#index-8">[6]</a>, <a href="tutorial/modules.html#index-1">[7]</a>, <a href="tutorial/modules.html#index-5">[8]</a>, <a href="tutorial/modules.html#index-6">[9]</a>, <a href="using/cmdline.html#index-19">[10]</a>, <a href="using/cmdline.html#index-21">[11]</a>, <a href="using/cmdline.html#index-22">[12]</a>, <a href="using/cmdline.html#index-4">[13]</a>, <a href="using/mac.html#index-0">[14]</a>, <a href="using/windows.html#index-2">[15]</a>, <a href="using/windows.html#index-4">[16]</a>
</li>
      <li><a href="c-api/typeobj.html#index-3">PYTHONSHOWALLOCCOUNT</a>, <a href="whatsnew/2.7.html#index-15">[1]</a>
</li>
      <li><a href="whatsnew/2.7.html#index-14">PYTHONSHOWREFCOUNT</a>
</li>
      <li><a href="library/idle.html#index-6">PYTHONSTARTUP</a>, <a href="library/readline.html#index-0">[1]</a>, <a href="library/rlcompleter.html#index-0">[2]</a>, <a href="library/user.html#index-1">[3]</a>, <a href="tutorial/appendix.html#index-1">[4]</a>, <a href="tutorial/interactive.html#index-1">[5]</a>, <a href="using/cmdline.html#index-6">[6]</a>
</li>
      <li><a href="using/cmdline.html#index-12">PYTHONUNBUFFERED</a>
</li>
      <li><a href="library/site.html#index-6">PYTHONUSERBASE</a>, <a href="library/site.html#index-7">[1]</a>, <a href="whatsnew/2.6.html#index-4">[2]</a>
</li>
      <li><a href="using/cmdline.html#index-13">PYTHONVERBOSE</a>
</li>
      <li><a href="using/cmdline.html#index-15">PYTHONWARNINGS</a>, <a href="whatsnew/2.7.html#index-1">[1]</a>, <a href="whatsnew/2.7.html#index-8">[2]</a>
</li>
      <li><a href="library/time.html#index-3">PYTHONY2K</a>, <a href="library/time.html#index-4">[1]</a>, <a href="library/time.html#index-7">[2]</a>
</li>
      <li><a href="c-api/init.html#index-15">PyThreadState</a>, <a href="c-api/init.html#index-15">[1]</a>

      <ul>
        <li><a href="c-api/init.html#c.PyThreadState">(C type)</a>
</li>
      </ul></li>
      <li><a href="c-api/init.html#c.PyThreadState_Clear">PyThreadState_Clear (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Delete">PyThreadState_Delete (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Get">PyThreadState_Get (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_GetDict">PyThreadState_GetDict (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_New">PyThreadState_New (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Next">PyThreadState_Next (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_SetAsyncExc">PyThreadState_SetAsyncExc (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyThreadState_Swap">PyThreadState_Swap (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_Check">PyTime_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_CheckExact">PyTime_CheckExact (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTime_FromTime">PyTime_FromTime (C function)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_CALL">PyTrace_C_CALL (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_EXCEPTION">PyTrace_C_EXCEPTION (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_C_RETURN">PyTrace_C_RETURN (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_CALL">PyTrace_CALL (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_EXCEPTION">PyTrace_EXCEPTION (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_LINE">PyTrace_LINE (C variable)</a>
</li>
      <li><a href="c-api/init.html#c.PyTrace_RETURN">PyTrace_RETURN (C variable)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Check">PyTuple_Check (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_CheckExact">PyTuple_CheckExact (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_ClearFreeList">PyTuple_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GET_ITEM">PyTuple_GET_ITEM (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GET_SIZE">PyTuple_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GetItem">PyTuple_GetItem (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_GetSlice">PyTuple_GetSlice (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_New">PyTuple_New (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Pack">PyTuple_Pack (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_SET_ITEM">PyTuple_SET_ITEM (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_SetItem">PyTuple_SetItem (C function)</a>
</li>
      <li><a href="c-api/intro.html#index-7">PyTuple_SetItem()</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Size">PyTuple_Size (C function)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTuple_Type">PyTuple_Type (C variable)</a>
</li>
      <li><a href="c-api/tuple.html#c.PyTupleObject">PyTupleObject (C type)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Check">PyType_Check (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_CheckExact">PyType_CheckExact (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_ClearCache">PyType_ClearCache (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_GenericAlloc">PyType_GenericAlloc (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_GenericNew">PyType_GenericNew (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_HasFeature">PyType_HasFeature (C function)</a>
</li>
      <li><a href="c-api/typeobj.html#index-4">PyType_HasFeature()</a>
</li>
      <li><a href="c-api/type.html#c.PyType_IS_GC">PyType_IS_GC (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_IsSubtype">PyType_IsSubtype (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Modified">PyType_Modified (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Ready">PyType_Ready (C function)</a>
</li>
      <li><a href="c-api/type.html#c.PyType_Type">PyType_Type (C variable)</a>
</li>
      <li><a href="c-api/type.html#c.PyTypeObject">PyTypeObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_alloc">PyTypeObject.tp_alloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_allocs">PyTypeObject.tp_allocs (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_as_buffer">PyTypeObject.tp_as_buffer (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_base">PyTypeObject.tp_base (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_bases">PyTypeObject.tp_bases (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_basicsize">PyTypeObject.tp_basicsize (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_cache">PyTypeObject.tp_cache (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_call">PyTypeObject.tp_call (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_clear">PyTypeObject.tp_clear (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_compare">PyTypeObject.tp_compare (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dealloc">PyTypeObject.tp_dealloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_descr_get">PyTypeObject.tp_descr_get (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_descr_set">PyTypeObject.tp_descr_set (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dict">PyTypeObject.tp_dict (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_dictoffset">PyTypeObject.tp_dictoffset (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_doc">PyTypeObject.tp_doc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_flags">PyTypeObject.tp_flags (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_free">PyTypeObject.tp_free (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_frees">PyTypeObject.tp_frees (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getattr">PyTypeObject.tp_getattr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getattro">PyTypeObject.tp_getattro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_getset">PyTypeObject.tp_getset (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_hash">PyTypeObject.tp_hash (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_init">PyTypeObject.tp_init (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_is_gc">PyTypeObject.tp_is_gc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_itemsize">PyTypeObject.tp_itemsize (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_iter">PyTypeObject.tp_iter (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_iternext">PyTypeObject.tp_iternext (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_maxalloc">PyTypeObject.tp_maxalloc (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_members">PyTypeObject.tp_members (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_methods">PyTypeObject.tp_methods (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_mro">PyTypeObject.tp_mro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_name">PyTypeObject.tp_name (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_new">PyTypeObject.tp_new (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_next">PyTypeObject.tp_next (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_print">PyTypeObject.tp_print (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_repr">PyTypeObject.tp_repr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_richcompare">PyTypeObject.tp_richcompare (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_setattr">PyTypeObject.tp_setattr (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_setattro">PyTypeObject.tp_setattro (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_str">PyTypeObject.tp_str (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_subclasses">PyTypeObject.tp_subclasses (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_traverse">PyTypeObject.tp_traverse (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_weaklist">PyTypeObject.tp_weaklist (C member)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyTypeObject.tp_weaklistoffset">PyTypeObject.tp_weaklistoffset (C member)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTZInfo_Check">PyTZInfo_Check (C function)</a>
</li>
      <li><a href="c-api/datetime.html#c.PyTZInfo_CheckExact">PyTZInfo_CheckExact (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AS_DATA">PyUnicode_AS_DATA (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AS_UNICODE">PyUnicode_AS_UNICODE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsASCIIString">PyUnicode_AsASCIIString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsCharmapString">PyUnicode_AsCharmapString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsEncodedString">PyUnicode_AsEncodedString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsLatin1String">PyUnicode_AsLatin1String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsMBCSString">PyUnicode_AsMBCSString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsRawUnicodeEscapeString">PyUnicode_AsRawUnicodeEscapeString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUnicode">PyUnicode_AsUnicode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUnicodeEscapeString">PyUnicode_AsUnicodeEscapeString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF16String">PyUnicode_AsUTF16String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF32String">PyUnicode_AsUTF32String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsUTF8String">PyUnicode_AsUTF8String (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_AsWideChar">PyUnicode_AsWideChar (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Check">PyUnicode_Check (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_CheckExact">PyUnicode_CheckExact (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_ClearFreeList">PyUnicode_ClearFreeList (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Compare">PyUnicode_Compare (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Concat">PyUnicode_Concat (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Contains">PyUnicode_Contains (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Count">PyUnicode_Count (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Decode">PyUnicode_Decode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeASCII">PyUnicode_DecodeASCII (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeCharmap">PyUnicode_DecodeCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeLatin1">PyUnicode_DecodeLatin1 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeMBCS">PyUnicode_DecodeMBCS (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeMBCSStateful">PyUnicode_DecodeMBCSStateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeRawUnicodeEscape">PyUnicode_DecodeRawUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUnicodeEscape">PyUnicode_DecodeUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF16">PyUnicode_DecodeUTF16 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF16Stateful">PyUnicode_DecodeUTF16Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF32">PyUnicode_DecodeUTF32 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF32Stateful">PyUnicode_DecodeUTF32Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF7">PyUnicode_DecodeUTF7 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF7Stateful">PyUnicode_DecodeUTF7Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF8">PyUnicode_DecodeUTF8 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_DecodeUTF8Stateful">PyUnicode_DecodeUTF8Stateful (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Encode">PyUnicode_Encode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeASCII">PyUnicode_EncodeASCII (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeCharmap">PyUnicode_EncodeCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeLatin1">PyUnicode_EncodeLatin1 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeMBCS">PyUnicode_EncodeMBCS (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeRawUnicodeEscape">PyUnicode_EncodeRawUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUnicodeEscape">PyUnicode_EncodeUnicodeEscape (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF16">PyUnicode_EncodeUTF16 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF32">PyUnicode_EncodeUTF32 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF7">PyUnicode_EncodeUTF7 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_EncodeUTF8">PyUnicode_EncodeUTF8 (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Find">PyUnicode_Find (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Format">PyUnicode_Format (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromEncodedObject">PyUnicode_FromEncodedObject (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromFormat">PyUnicode_FromFormat (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromFormatV">PyUnicode_FromFormatV (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromObject">PyUnicode_FromObject (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromString">PyUnicode_FromString (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromStringAndSize">PyUnicode_FromStringAndSize (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromUnicode">PyUnicode_FromUnicode (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_FromWideChar">PyUnicode_FromWideChar (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GET_DATA_SIZE">PyUnicode_GET_DATA_SIZE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GET_SIZE">PyUnicode_GET_SIZE (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_GetSize">PyUnicode_GetSize (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Join">PyUnicode_Join (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Replace">PyUnicode_Replace (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_RichCompare">PyUnicode_RichCompare (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Split">PyUnicode_Split (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Splitlines">PyUnicode_Splitlines (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Tailmatch">PyUnicode_Tailmatch (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Translate">PyUnicode_Translate (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_TranslateCharmap">PyUnicode_TranslateCharmap (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicode_Type">PyUnicode_Type (C variable)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_Create">PyUnicodeDecodeError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetEncoding">PyUnicodeDecodeError_GetEncoding (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetEnd">PyUnicodeDecodeError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetObject">PyUnicodeDecodeError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetReason">PyUnicodeDecodeError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_GetStart">PyUnicodeDecodeError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetEnd">PyUnicodeDecodeError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetReason">PyUnicodeDecodeError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeDecodeError_SetStart">PyUnicodeDecodeError_SetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_Create">PyUnicodeEncodeError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetEncoding">PyUnicodeEncodeError_GetEncoding (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetEnd">PyUnicodeEncodeError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetObject">PyUnicodeEncodeError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetReason">PyUnicodeEncodeError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_GetStart">PyUnicodeEncodeError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetEnd">PyUnicodeEncodeError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetReason">PyUnicodeEncodeError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeEncodeError_SetStart">PyUnicodeEncodeError_SetStart (C function)</a>
</li>
      <li><a href="c-api/unicode.html#c.PyUnicodeObject">PyUnicodeObject (C type)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_Create">PyUnicodeTranslateError_Create (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetEnd">PyUnicodeTranslateError_GetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetObject">PyUnicodeTranslateError_GetObject (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetReason">PyUnicodeTranslateError_GetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_GetStart">PyUnicodeTranslateError_GetStart (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetEnd">PyUnicodeTranslateError_SetEnd (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetReason">PyUnicodeTranslateError_SetReason (C function)</a>
</li>
      <li><a href="c-api/exceptions.html#c.PyUnicodeTranslateError_SetStart">PyUnicodeTranslateError_SetStart (C function)</a>
</li>
      <li><a href="c-api/structures.html#c.PyVarObject">PyVarObject (C type)</a>
</li>
      <li><a href="c-api/typeobj.html#c.PyVarObject.ob_size">PyVarObject.ob_size (C member)</a>
</li>
      <li><a href="c-api/structures.html#c.PyVarObject_HEAD_INIT">PyVarObject_HEAD_INIT (C macro)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_Check">PyWeakref_Check (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_CheckProxy">PyWeakref_CheckProxy (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_CheckRef">PyWeakref_CheckRef (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_GET_OBJECT">PyWeakref_GET_OBJECT (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_GetObject">PyWeakref_GetObject (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_NewProxy">PyWeakref_NewProxy (C function)</a>
</li>
      <li><a href="c-api/weakref.html#c.PyWeakref_NewRef">PyWeakref_NewRef (C function)</a>
</li>
      <li><a href="c-api/descriptor.html#c.PyWrapper_New">PyWrapper_New (C function)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.PyZipFile">PyZipFile (class in zipfile)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�H��$�$html/genindex-Q.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-Q.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; Q</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/fl.html#fl.qdevice">qdevice() (in module fl)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.QDPoint">QDPoint (class in aetypes)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.QDRectangle">QDRectangle (class in aetypes)</a>
</li>
      <li><a href="library/fl.html#fl.qenter">qenter() (in module fl)</a>
</li>
      <li><a href="library/curses.html#curses.qiflush">qiflush() (in module curses)</a>
</li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.QName">QName (class in xml.etree.ElementTree)</a>
</li>
      <li><a href="library/fl.html#fl.qread">qread() (in module fl)</a>
</li>
      <li><a href="library/fl.html#fl.qreset">qreset() (in module fl)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue.qsize">qsize() (multiprocessing.Queue method)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue.qsize">(Queue.Queue method)</a>
</li>
      </ul></li>
      <li><a href="library/fl.html#fl.qtest">qtest() (in module fl)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.quantize">quantize() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.quantize">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/_winreg.html#_winreg.QueryInfoKey">QueryInfoKey() (in module _winreg)</a>
</li>
      <li><a href="library/al.html#al.queryparams">queryparams() (in module al)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryReflectionKey">QueryReflectionKey() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryValue">QueryValue() (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.QueryValueEx">QueryValueEx() (in module _winreg)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.Queue">Queue (class in multiprocessing)</a>

      <ul>
        <li><a href="library/queue.html#Queue.Queue">(class in Queue)</a>
</li>
        <li><a href="library/queue.html#module-Queue">(module)</a>
</li>
      </ul></li>
      <li><a href="library/sched.html#sched.scheduler.queue">queue (sched.scheduler attribute)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.Queue">Queue() (multiprocessing.managers.SyncManager method)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.quick_ratio">quick_ratio() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/constants.html#quit">quit (built-in variable)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.quit">quit() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/nntplib.html#nntplib.NNTP.quit">(nntplib.NNTP method)</a>
</li>
        <li><a href="library/poplib.html#poplib.POP3.quit">(poplib.POP3 method)</a>
</li>
        <li><a href="library/smtplib.html#smtplib.SMTP.quit">(smtplib.SMTP method)</a>
</li>
      </ul></li>
      <li><a href="library/quopri.html#module-quopri">quopri (module)</a>
</li>
      <li><a href="library/email.utils.html#email.utils.quote">quote() (in module email.utils)</a>

      <ul>
        <li><a href="library/pipes.html#pipes.quote">(in module pipes)</a>
</li>
        <li><a href="library/rfc822.html#rfc822.quote">(in module rfc822)</a>
</li>
        <li><a href="library/urllib.html#urllib.quote">(in module urllib)</a>
</li>
      </ul></li>
      <li><a href="library/csv.html#csv.QUOTE_ALL">QUOTE_ALL (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_MINIMAL">QUOTE_MINIMAL (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_NONE">QUOTE_NONE (in module csv)</a>
</li>
      <li><a href="library/csv.html#csv.QUOTE_NONNUMERIC">QUOTE_NONNUMERIC (in module csv)</a>
</li>
      <li><a href="library/urllib.html#urllib.quote_plus">quote_plus() (in module urllib)</a>
</li>
      <li><a href="library/xml.sax.utils.html#xml.sax.saxutils.quoteattr">quoteattr() (in module xml.sax.saxutils)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.quotechar">quotechar (csv.Dialect attribute)</a>
</li>
      <li>
    quoted-printable

      <ul>
        <li><a href="library/quopri.html#index-0">encoding</a>
</li>
      </ul></li>
      <li>
    quotes

      <ul>
        <li><a href="reference/datamodel.html#index-77">backward</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
        <li><a href="reference/datamodel.html#index-77">reverse</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/shlex.html#shlex.shlex.quotes">quotes (shlex.shlex attribute)</a>
</li>
      <li><a href="library/csv.html#csv.Dialect.quoting">quoting (csv.Dialect attribute)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�ޫ
html/genindex-R.htmlnu�[���

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Index &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/genindex-R.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    

  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            

<h1 id="index">Index &ndash; R</h1>

<table style="width: 100%" class="indextable"><tr>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/rexec.html#rexec.RExec.r_eval">r_eval() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_exec">r_exec() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_execfile">r_execfile() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_import">r_import() (rexec.RExec method)</a>
</li>
      <li><a href="library/os.html#os.R_OK">R_OK (in module os)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_open">r_open() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_reload">r_reload() (rexec.RExec method)</a>
</li>
      <li><a href="library/rexec.html#rexec.RExec.r_unload">r_unload() (rexec.RExec method)</a>
</li>
      <li><a href="library/math.html#math.radians">radians() (in module math)</a>

      <ul>
        <li><a href="library/turtle.html#turtle.radians">(in module turtle)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.RadioButtonGroup">RadioButtonGroup (class in msilib)</a>
</li>
      <li><a href="library/msilib.html#msilib.Dialog.radiogroup">radiogroup() (msilib.Dialog method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.radix">radix() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.radix">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/locale.html#locale.RADIXCHAR">RADIXCHAR (in module locale)</a>
</li>
      <li>
    raise

      <ul>
        <li><a href="library/exceptions.html#index-1">statement</a>, <a href="reference/simple_stmts.html#index-31">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-raise">raise (2to3 fixer)</a>
</li>
      <li><a href="reference/executionmodel.html#index-13">raise an exception</a>
</li>
      <li><a href="library/dis.html#opcode-RAISE_VARARGS">RAISE_VARARGS (opcode)</a>
</li>
      <li>
    raising

      <ul>
        <li><a href="reference/simple_stmts.html#index-31">exception</a>
</li>
      </ul></li>
      <li><a href="library/ssl.html#ssl.RAND_add">RAND_add() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.RAND_egd">RAND_egd() (in module ssl)</a>
</li>
      <li><a href="library/ssl.html#ssl.RAND_status">RAND_status() (in module ssl)</a>
</li>
      <li><a href="library/random.html#random.randint">randint() (in module random)</a>
</li>
      <li><a href="library/random.html#module-random">random (module)</a>
</li>
      <li><a href="library/random.html#random.random">random() (in module random)</a>
</li>
      <li><a href="library/random.html#random.randrange">randrange() (in module random)</a>
</li>
      <li>
    range

      <ul>
        <li><a href="reference/compound_stmts.html#index-8">built-in function</a>
</li>
      </ul></li>
      <li><a href="library/aetypes.html#aetypes.Range">Range (class in aetypes)</a>
</li>
      <li><a href="library/functions.html#range">range() (built-in function)</a>
</li>
      <li><a href="library/audioop.html#audioop.ratecv">ratecv() (in module audioop)</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.ratio">ratio() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="library/numbers.html#numbers.Rational">Rational (class in numbers)</a>
</li>
      <li><a href="library/io.html#io.BufferedIOBase.raw">raw (io.BufferedIOBase attribute)</a>
</li>
      <li><a href="reference/toplevel_components.html#index-8">raw input</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-14">raw string</a>
</li>
      <li><a href="library/curses.html#curses.raw">raw() (in module curses)</a>
</li>
      <li><a href="library/json.html#json.JSONDecoder.raw_decode">raw_decode() (json.JSONDecoder method)</a>
</li>
      <li>
    raw_input

      <ul>
        <li><a href="library/sys.html#index-14">built-in function</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-raw_input">raw_input (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#raw_input">raw_input() (built-in function)</a>

      <ul>
        <li><a href="library/code.html#code.InteractiveConsole.raw_input">(code.InteractiveConsole method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.RawArray">RawArray() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser">RawConfigParser (class in ConfigParser)</a>
</li>
      <li><a href="library/argparse.html#argparse.RawDescriptionHelpFormatter">RawDescriptionHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/io.html#io.RawIOBase">RawIOBase (class in io)</a>
</li>
      <li><a href="library/turtle.html#turtle.RawPen">RawPen (class in turtle)</a>
</li>
      <li><a href="library/argparse.html#argparse.RawTextHelpFormatter">RawTextHelpFormatter (class in argparse)</a>
</li>
      <li><a href="library/turtle.html#turtle.RawTurtle">RawTurtle (class in turtle)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.sharedctypes.RawValue">RawValue() (in module multiprocessing.sharedctypes)</a>
</li>
      <li><a href="library/token.html#token.RBRACE">RBRACE (in module token)</a>
</li>
      <li>
    re

      <ul>
        <li><a href="library/fnmatch.html#index-1">module</a>, <a href="library/stdtypes.html#index-27">[1]</a>, <a href="library/string.html#index-0">[2]</a>
</li>
      </ul></li>
      <li><a href="library/re.html#module-re">re (module)</a>

      <ul>
        <li><a href="library/re.html#re.MatchObject.re">(re.MatchObject attribute)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.read">read() (array.array method)</a>

      <ul>
        <li><a href="library/configparser.html#ConfigParser.RawConfigParser.read">(ConfigParser.RawConfigParser method)</a>
</li>
        <li><a href="library/bz2.html#bz2.BZ2File.read">(bz2.BZ2File method)</a>
</li>
        <li><a href="library/chunk.html#chunk.Chunk.read">(chunk.Chunk method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamReader.read">(codecs.StreamReader method)</a>
</li>
        <li><a href="library/stdtypes.html#file.read">(file method)</a>
</li>
        <li><a href="library/httplib.html#httplib.HTTPResponse.read">(httplib.HTTPResponse method)</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.read">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/imgfile.html#imgfile.read">(in module imgfile)</a>
</li>
        <li><a href="library/os.html#os.read">(in module os)</a>
</li>
        <li><a href="library/io.html#io.BufferedIOBase.read">(io.BufferedIOBase method)</a>
</li>
        <li><a href="library/io.html#io.BufferedReader.read">(io.BufferedReader method)</a>
</li>
        <li><a href="library/io.html#io.RawIOBase.read">(io.RawIOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.read">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.read">(mimetypes.MimeTypes method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.read">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.read">(multifile.MultiFile method)</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.read">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/robotparser.html#robotparser.RobotFileParser.read">(robotparser.RobotFileParser method)</a>
</li>
        <li><a href="library/zipfile.html#zipfile.ZipFile.read">(zipfile.ZipFile method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.BufferedIOBase.read1">read1() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.BufferedReader.read1">(io.BufferedReader method)</a>
</li>
        <li><a href="library/io.html#io.BytesIO.read1">(io.BytesIO method)</a>
</li>
      </ul></li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_all">read_all() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mmap.html#mmap.mmap.read_byte">read_byte() (mmap.mmap method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_eager">read_eager() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/readline.html#readline.read_history_file">read_history_file() (in module readline)</a>
</li>
      <li><a href="library/readline.html#readline.read_init_file">read_init_file() (in module readline)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_lazy">read_lazy() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.read_mime_types">read_mime_types() (in module mimetypes)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">READ_RESTRICTED</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_sb_data">read_sb_data() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_some">read_some() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/shlex.html#shlex.shlex.read_token">read_token() (shlex.shlex method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_until">read_until() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_very_eager">read_very_eager() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/telnetlib.html#telnetlib.Telnet.read_very_lazy">read_very_lazy() (telnetlib.Telnet method)</a>
</li>
      <li><a href="library/mimetypes.html#mimetypes.MimeTypes.read_windows_registry">read_windows_registry() (mimetypes.MimeTypes method)</a>
</li>
      <li><a href="library/tkinter.html#Tkinter.READABLE">READABLE (in module Tkinter)</a>
</li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.readable">readable() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/io.html#io.IOBase.readable">(io.IOBase method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.RawIOBase.readall">readall() (io.RawIOBase method)</a>
</li>
      <li><a href="c-api/typeobj.html#c.readbufferproc">readbufferproc (C type)</a>
</li>
      <li><a href="library/csv.html#csv.reader">reader() (in module csv)</a>
</li>
      <li><a href="library/tarfile.html#tarfile.ReadError">ReadError</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.readfp">readfp() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/mimetypes.html#mimetypes.MimeTypes.readfp">(mimetypes.MimeTypes method)</a>
</li>
      </ul></li>
      <li><a href="library/aifc.html#aifc.aifc.readframes">readframes() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.readframes">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.readframes">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/io.html#io.BufferedIOBase.readinto">readinto() (io.BufferedIOBase method)</a>

      <ul>
        <li><a href="library/io.html#io.RawIOBase.readinto">(io.RawIOBase method)</a>
</li>
      </ul></li>
      <li>
    readline

      <ul>
        <li><a href="tutorial/interactive.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#module-readline">readline (module)</a>
</li>
      <li><a href="library/bz2.html#bz2.BZ2File.readline">readline() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamReader.readline">(codecs.StreamReader method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.readline">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/stdtypes.html#file.readline">(file method)</a>, <a href="reference/toplevel_components.html#index-8">[1]</a>
</li>
        <li><a href="library/imaplib.html#imaplib.IMAP4.readline">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.readline">(io.IOBase method)</a>
</li>
        <li><a href="library/io.html#io.TextIOBase.readline">(io.TextIOBase method)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.readline">(mmap.mmap method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.readline">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/bz2.html#bz2.BZ2File.readlines">readlines() (bz2.BZ2File method)</a>

      <ul>
        <li><a href="library/codecs.html#codecs.StreamReader.readlines">(codecs.StreamReader method)</a>
</li>
        <li><a href="distutils/apiref.html#distutils.text_file.TextFile.readlines">(distutils.text_file.TextFile method)</a>
</li>
        <li><a href="library/stdtypes.html#file.readlines">(file method)</a>
</li>
        <li><a href="library/io.html#io.IOBase.readlines">(io.IOBase method)</a>
</li>
        <li><a href="library/multifile.html#multifile.MultiFile.readlines">(multifile.MultiFile method)</a>
</li>
      </ul></li>
      <li><a href="library/os.html#os.readlink">readlink() (in module os)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.readmodule">readmodule() (in module pyclbr)</a>
</li>
      <li><a href="library/pyclbr.html#pyclbr.readmodule_ex">readmodule_ex() (in module pyclbr)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">READONLY</a>
</li>
      <li><a href="library/stdtypes.html#memoryview.readonly">readonly (memoryview attribute)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlist">readPlist() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlistFromResource">readPlistFromResource() (in module plistlib)</a>
</li>
      <li><a href="library/plistlib.html#plistlib.readPlistFromString">readPlistFromString() (in module plistlib)</a>
</li>
      <li><a href="library/imgfile.html#imgfile.readscaled">readscaled() (in module imgfile)</a>
</li>
      <li><a href="library/cd.html#cd.READY">READY (in module cd)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.pool.AsyncResult.ready">ready() (multiprocessing.pool.AsyncResult method)</a>
</li>
      <li><a href="library/numbers.html#numbers.Real">Real (class in numbers)</a>
</li>
      <li><a href="library/numbers.html#numbers.Complex.real">real (numbers.Complex attribute)</a>
</li>
      <li><a href="library/chunk.html#index-0">Real Media File Format</a>
</li>
      <li><a href="library/difflib.html#difflib.SequenceMatcher.real_quick_ratio">real_quick_ratio() (difflib.SequenceMatcher method)</a>
</li>
      <li><a href="c-api/memory.html#index-0">realloc()</a>
</li>
      <li><a href="library/os.path.html#os.path.realpath">realpath() (in module os.path)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.UnicodeError.reason">reason (exceptions.UnicodeError attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.HTTPResponse.reason">(httplib.HTTPResponse attribute)</a>
</li>
        <li><a href="library/ssl.html#ssl.SSLError.reason">(ssl.SSLError attribute)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.HTTPError.reason">(urllib2.HTTPError attribute)</a>
</li>
        <li><a href="library/urllib2.html#urllib2.URLError.reason">(urllib2.URLError attribute)</a>
</li>
      </ul></li>
      <li><a href="library/ttk.html#ttk.Treeview.reattach">reattach() (ttk.Treeview method)</a>
</li>
      <li>
    rebinding

      <ul>
        <li><a href="reference/simple_stmts.html#index-3">name</a>
</li>
      </ul></li>
      <li><a href="library/ossaudiodev.html#ossaudiodev.oss_mixer_device.reccontrols">reccontrols() (ossaudiodev.oss_mixer_device method)</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.recent">recent() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/cmath.html#cmath.rect">rect() (in module cmath)</a>
</li>
      <li><a href="library/curses.html#curses.textpad.rectangle">rectangle() (in module curses.textpad)</a>
</li>
      <li>
    recursive

      <ul>
        <li><a href="reference/expressions.html#index-20">object</a>
</li>
      </ul></li>
      <li><a href="library/asyncore.html#asyncore.dispatcher.recv">recv() (asyncore.dispatcher method)</a>

      <ul>
        <li><a href="library/multiprocessing.html#Connection.recv">(Connection method)</a>
</li>
        <li><a href="library/socket.html#socket.socket.recv">(socket.socket method)</a>
</li>
      </ul></li>
      <li><a href="library/multiprocessing.html#Connection.recv_bytes">recv_bytes() (Connection method)</a>
</li>
      <li><a href="library/multiprocessing.html#Connection.recv_bytes_into">recv_bytes_into() (Connection method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recv_into">recv_into() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recvfrom">recvfrom() (socket.socket method)</a>
</li>
      <li><a href="library/socket.html#socket.socket.recvfrom_into">recvfrom_into() (socket.socket method)</a>
</li>
      <li><a href="library/urllib2.html#urllib2.HTTPRedirectHandler.redirect_request">redirect_request() (urllib2.HTTPRedirectHandler method)</a>
</li>
      <li><a href="library/readline.html#readline.redisplay">redisplay() (in module readline)</a>
</li>
      <li><a href="library/fl.html#fl.form.redraw_form">redraw_form() (fl.form method)</a>
</li>
      <li><a href="library/curses.html#curses.window.redrawln">redrawln() (curses.window method)</a>
</li>
      <li><a href="library/curses.html#curses.window.redrawwin">redrawwin() (curses.window method)</a>
</li>
      <li><a href="library/2to3.html#2to3fixer-reduce">reduce (2to3 fixer)</a>
</li>
      <li><a href="library/functions.html#reduce">reduce() (built-in function)</a>

      <ul>
        <li><a href="library/functools.html#functools.reduce">(in module functools)</a>
</li>
      </ul></li>
      <li><a href="library/weakref.html#weakref.ref">ref (class in weakref)</a>
</li>
      <li>
    reference

      <ul>
        <li><a href="reference/expressions.html#index-29">attribute</a>
</li>
      </ul></li>
      <li><a href="glossary.html#term-reference-count"><strong>reference count</strong></a>
</li>
      <li><a href="reference/datamodel.html#index-2">reference counting</a>
</li>
      <li><a href="library/exceptions.html#exceptions.ReferenceError">ReferenceError</a>, <a href="library/weakref.html#weakref.ReferenceError">[1]</a>
</li>
      <li><a href="library/weakref.html#weakref.ReferenceType">ReferenceType (in module weakref)</a>
</li>
      <li><a href="library/mhlib.html#mhlib.Folder.refilemessages">refilemessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/curses.html#curses.window.refresh">refresh() (curses.window method)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_BINARY">REG_BINARY (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD">REG_DWORD (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD_BIG_ENDIAN">REG_DWORD_BIG_ENDIAN (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_DWORD_LITTLE_ENDIAN">REG_DWORD_LITTLE_ENDIAN (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_EXPAND_SZ">REG_EXPAND_SZ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_FULL_RESOURCE_DESCRIPTOR">REG_FULL_RESOURCE_DESCRIPTOR (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_LINK">REG_LINK (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_MULTI_SZ">REG_MULTI_SZ (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_NONE">REG_NONE (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_RESOURCE_LIST">REG_RESOURCE_LIST (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_RESOURCE_REQUIREMENTS_LIST">REG_RESOURCE_REQUIREMENTS_LIST (in module _winreg)</a>
</li>
      <li><a href="library/_winreg.html#_winreg.REG_SZ">REG_SZ (in module _winreg)</a>
</li>
      <li><a href="library/re.html#re.RegexObject">RegexObject (class in re)</a>
</li>
      <li><a href="library/abc.html#abc.ABCMeta.register">register() (abc.ABCMeta method)</a>

      <ul>
        <li><a href="library/atexit.html#atexit.register">(in module atexit)</a>
</li>
        <li><a href="library/codecs.html#codecs.register">(in module codecs)</a>
</li>
        <li><a href="library/webbrowser.html#webbrowser.register">(in module webbrowser)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.BaseManager.register">(multiprocessing.managers.BaseManager method)</a>
</li>
        <li><a href="library/select.html#select.epoll.register">(select.epoll method)</a>
</li>
        <li><a href="library/select.html#select.poll.register">(select.poll method)</a>
</li>
      </ul></li>
      <li><a href="library/sqlite3.html#sqlite3.register_adapter">register_adapter() (in module sqlite3)</a>
</li>
      <li><a href="library/shutil.html#shutil.register_archive_format">register_archive_format() (in module shutil)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.register_converter">register_converter() (in module sqlite3)</a>
</li>
      <li><a href="library/csv.html#csv.register_dialect">register_dialect() (in module csv)</a>
</li>
      <li><a href="library/codecs.html#codecs.register_error">register_error() (in module codecs)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_function">register_function() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_function">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_instance">register_instance() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_instance">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_introspection_functions">register_introspection_functions() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_introspection_functions">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.CGIXMLRPCRequestHandler.register_multicall_functions">register_multicall_functions() (SimpleXMLRPCServer.CGIXMLRPCRequestHandler method)</a>

      <ul>
        <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCServer.register_multicall_functions">(SimpleXMLRPCServer.SimpleXMLRPCServer method)</a>
</li>
      </ul></li>
      <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace">register_namespace() (in module xml.etree.ElementTree)</a>
</li>
      <li><a href="library/doctest.html#doctest.register_optionflag">register_optionflag() (in module doctest)</a>
</li>
      <li><a href="library/turtle.html#turtle.register_shape">register_shape() (in module turtle)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.registerDOMImplementation">registerDOMImplementation() (in module xml.dom)</a>
</li>
      <li><a href="library/unittest.html#unittest.registerResult">registerResult() (in module unittest)</a>
</li>
      <li>
    relative

      <ul>
        <li><a href="library/urlparse.html#index-0">URL</a>
</li>
        <li><a href="reference/simple_stmts.html#index-50">import</a>
</li>
      </ul></li>
      <li><a href="library/platform.html#platform.release">release() (in module platform)</a>

      <ul>
        <li><a href="library/logging.html#logging.Handler.release">(logging.Handler method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Lock.release">(multiprocessing.Lock method)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.RLock.release">(multiprocessing.RLock method)</a>
</li>
        <li><a href="library/thread.html#thread.lock.release">(thread.lock method)</a>
</li>
        <li><a href="library/threading.html#threading.Condition.release">(threading.Condition method)</a>
</li>
        <li><a href="library/threading.html#threading.Lock.release">(threading.Lock method)</a>
</li>
        <li><a href="library/threading.html#threading.RLock.release">(threading.RLock method)</a>
</li>
        <li><a href="library/threading.html#threading.Semaphore.release">(threading.Semaphore method)</a>
</li>
      </ul></li>
      <li><a href="library/imp.html#imp.release_lock">release_lock() (in module imp)</a>
</li>
      <li>
    reload

      <ul>
        <li><a href="c-api/import.html#index-3">built-in function</a>, <a href="library/imp.html#index-2">[1]</a>, <a href="library/imp.html#index-5">[2]</a>, <a href="library/sys.html#index-5">[3]</a>
</li>
      </ul></li>
      <li><a href="library/functions.html#reload">reload() (built-in function)</a>
</li>
      <li><a href="library/os.path.html#os.path.relpath">relpath() (in module os.path)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.remainder">remainder() (decimal.Context method)</a>
</li>
      <li><a href="library/decimal.html#decimal.Context.remainder_near">remainder_near() (decimal.Context method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Decimal.remainder_near">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.remove">remove() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.remove">(collections.deque method)</a>
</li>
        <li><a href="library/stdtypes.html#frozenset.remove">(frozenset method)</a>
</li>
        <li><a href="library/os.html#os.remove">(in module os)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.MH.remove">(mailbox.MH method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.Mailbox.remove">(mailbox.Mailbox method)</a>
</li>
        <li><a href="library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.remove">(xml.etree.ElementTree.Element method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.MaildirMessage.remove_flag">remove_flag() (mailbox.MaildirMessage method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MMDFMessage.remove_flag">(mailbox.MMDFMessage method)</a>
</li>
        <li><a href="library/mailbox.html#mailbox.mboxMessage.remove_flag">(mailbox.mboxMessage method)</a>
</li>
      </ul></li>
      <li><a href="library/mailbox.html#mailbox.Maildir.remove_folder">remove_folder() (mailbox.Maildir method)</a>

      <ul>
        <li><a href="library/mailbox.html#mailbox.MH.remove_folder">(mailbox.MH method)</a>
</li>
      </ul></li>
      <li><a href="library/readline.html#readline.remove_history_item">remove_history_item() (in module readline)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.BabylMessage.remove_label">remove_label() (mailbox.BabylMessage method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.remove_option">remove_option() (ConfigParser.RawConfigParser method)</a>

      <ul>
        <li><a href="library/optparse.html#optparse.OptionParser.remove_option">(optparse.OptionParser method)</a>
</li>
      </ul></li>
      <li><a href="library/msilib.html#msilib.Directory.remove_pyc">remove_pyc() (msilib.Directory method)</a>
</li>
      <li><a href="library/configparser.html#ConfigParser.RawConfigParser.remove_section">remove_section() (ConfigParser.RawConfigParser method)</a>
</li>
      <li><a href="library/mailbox.html#mailbox.MHMessage.remove_sequence">remove_sequence() (mailbox.MHMessage method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.dir_util.remove_tree">remove_tree() (in module distutils.dir_util)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttribute">removeAttribute() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttributeNode">removeAttributeNode() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Element.removeAttributeNS">removeAttributeNS() (xml.dom.Element method)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.removeChild">removeChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/os.html#os.removedirs">removedirs() (in module os)</a>
</li>
      <li><a href="library/logging.html#logging.Handler.removeFilter">removeFilter() (logging.Handler method)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.removeFilter">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/unittest.html#unittest.removeHandler">removeHandler() (in module unittest)</a>

      <ul>
        <li><a href="library/logging.html#logging.Logger.removeHandler">(logging.Logger method)</a>
</li>
      </ul></li>
      <li><a href="library/mhlib.html#mhlib.Folder.removemessages">removemessages() (mhlib.Folder method)</a>
</li>
      <li><a href="library/unittest.html#unittest.removeResult">removeResult() (in module unittest)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.rename">rename() (ftplib.FTP method)</a>

      <ul>
        <li><a href="library/imaplib.html#imaplib.IMAP4.rename">(imaplib.IMAP4 method)</a>
</li>
        <li><a href="library/os.html#os.rename">(in module os)</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-renames">renames (2to3 fixer)</a>
</li>
  </ul></td>
  <td style="width: 33%; vertical-align: top;"><ul>
      <li><a href="library/os.html#os.renames">renames() (in module os)</a>
</li>
      <li><a href="library/gdbm.html#gdbm.reorganize">reorganize() (in module gdbm)</a>
</li>
      <li><a href="library/itertools.html#itertools.repeat">repeat() (in module itertools)</a>

      <ul>
        <li><a href="library/operator.html#operator.repeat">(in module operator)</a>
</li>
        <li><a href="library/timeit.html#timeit.repeat">(in module timeit)</a>
</li>
        <li><a href="library/timeit.html#timeit.Timer.repeat">(timeit.Timer method)</a>
</li>
      </ul></li>
      <li>
    repetition

      <ul>
        <li><a href="library/stdtypes.html#index-22">operation</a>
</li>
      </ul></li>
      <li><a href="library/curses.panel.html#curses.panel.Panel.replace">replace() (curses.panel.Panel method)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.date.replace">(datetime.date method)</a>
</li>
        <li><a href="library/datetime.html#datetime.datetime.replace">(datetime.datetime method)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.replace">(datetime.time method)</a>
</li>
        <li><a href="library/string.html#string.replace">(in module string)</a>
</li>
        <li><a href="library/stdtypes.html#str.replace">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/codecs.html#codecs.replace_errors">replace_errors() (in module codecs)</a>
</li>
      <li><a href="library/email.message.html#email.message.Message.replace_header">replace_header() (email.message.Message method)</a>
</li>
      <li><a href="library/readline.html#readline.replace_history_item">replace_history_item() (in module readline)</a>
</li>
      <li><a href="library/textwrap.html#textwrap.TextWrapper.replace_whitespace">replace_whitespace (textwrap.TextWrapper attribute)</a>
</li>
      <li><a href="library/xml.dom.html#xml.dom.Node.replaceChild">replaceChild() (xml.dom.Node method)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ReplacePackage">ReplacePackage() (in module modulefinder)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.report">report() (filecmp.dircmp method)</a>

      <ul>
        <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.report">(modulefinder.ModuleFinder method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.REPORT_CDIFF">REPORT_CDIFF (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_failure">report_failure() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.report_full_closure">report_full_closure() (filecmp.dircmp method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_NDIFF">REPORT_NDIFF (in module doctest)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_ONLY_FIRST_FAILURE">REPORT_ONLY_FIRST_FAILURE (in module doctest)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.report_partial_closure">report_partial_closure() (filecmp.dircmp method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_start">report_start() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_success">report_success() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORT_UDIFF">REPORT_UDIFF (in module doctest)</a>
</li>
      <li><a href="library/sgmllib.html#sgmllib.SGMLParser.report_unbalanced">report_unbalanced() (sgmllib.SGMLParser method)</a>
</li>
      <li><a href="library/doctest.html#doctest.DocTestRunner.report_unexpected_exception">report_unexpected_exception() (doctest.DocTestRunner method)</a>
</li>
      <li><a href="library/doctest.html#doctest.REPORTING_FLAGS">REPORTING_FLAGS (in module doctest)</a>
</li>
      <li>
    repr

      <ul>
        <li><a href="c-api/object.html#index-2">built-in function</a>, <a href="c-api/typeobj.html#index-1">[1]</a>, <a href="extending/newtypes.html#index-2">[2]</a>, <a href="reference/datamodel.html#index-76">[3]</a>, <a href="reference/expressions.html#index-21">[4]</a>, <a href="reference/simple_stmts.html#index-2">[5]</a>
</li>
      </ul></li>
      <li><a href="library/2to3.html#2to3fixer-repr">repr (2to3 fixer)</a>
</li>
      <li><a href="library/repr.html#repr.Repr">Repr (class in repr)</a>
</li>
      <li><a href="library/functions.html#repr">repr() (built-in function)</a>

      <ul>
        <li><a href="library/repr.html#repr.repr">(in module repr)</a>
</li>
        <li><a href="library/repr.html#repr.Repr.repr">(repr.Repr method)</a>
</li>
      </ul></li>
      <li><a href="library/repr.html#repr.Repr.repr1">repr1() (repr.Repr method)</a>
</li>
      <li>
    representation

      <ul>
        <li><a href="reference/datamodel.html#index-14">integer</a>
</li>
      </ul></li>
      <li><a href="library/urllib2.html#urllib2.Request">Request (class in urllib2)</a>
</li>
      <li><a href="library/httplib.html#httplib.HTTPConnection.request">request() (httplib.HTTPConnection method)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.request_queue_size">request_queue_size (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/wsgiref.html#wsgiref.util.request_uri">request_uri() (in module wsgiref.util)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.request_version">request_version (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/socketserver.html#SocketServer.BaseServer.RequestHandlerClass">RequestHandlerClass (SocketServer.BaseServer attribute)</a>
</li>
      <li><a href="library/test.html#test.support.requires">requires() (in module test.support)</a>
</li>
      <li><a href="library/zipfile.html#zipfile.ZipInfo.reserved">reserved (zipfile.ZipInfo attribute)</a>
</li>
      <li><a href="reference/lexical_analysis.html#index-10">reserved word</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_FUTURE">RESERVED_FUTURE (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_MICROSOFT">RESERVED_MICROSOFT (in module uuid)</a>
</li>
      <li><a href="library/uuid.html#uuid.RESERVED_NCS">RESERVED_NCS (in module uuid)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.reset">reset() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/htmlparser.html#HTMLParser.HTMLParser.reset">(HTMLParser.HTMLParser method)</a>
</li>
        <li><a href="library/codecs.html#codecs.IncrementalDecoder.reset">(codecs.IncrementalDecoder method)</a>
</li>
        <li><a href="library/codecs.html#codecs.IncrementalEncoder.reset">(codecs.IncrementalEncoder method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamReader.reset">(codecs.StreamReader method)</a>
</li>
        <li><a href="library/codecs.html#codecs.StreamWriter.reset">(codecs.StreamWriter method)</a>
</li>
        <li><a href="library/dircache.html#dircache.reset">(in module dircache)</a>
</li>
        <li><a href="library/turtle.html#turtle.reset">(in module turtle)</a>, <a href="library/turtle.html#turtle.reset">[1]</a>
</li>
        <li><a href="library/ossaudiodev.html#ossaudiodev.oss_audio_device.reset">(ossaudiodev.oss_audio_device method)</a>
</li>
        <li><a href="library/pipes.html#pipes.Template.reset">(pipes.Template method)</a>
</li>
        <li><a href="library/sgmllib.html#sgmllib.SGMLParser.reset">(sgmllib.SGMLParser method)</a>
</li>
        <li><a href="library/xdrlib.html#xdrlib.Packer.reset">(xdrlib.Packer method)</a>
</li>
        <li><a href="library/xdrlib.html#xdrlib.Unpacker.reset">(xdrlib.Unpacker method)</a>
</li>
        <li><a href="library/xml.dom.pulldom.html#xml.dom.pulldom.DOMEventStream.reset">(xml.dom.pulldom.DOMEventStream method)</a>
</li>
        <li><a href="library/xml.sax.reader.html#xml.sax.xmlreader.IncrementalParser.reset">(xml.sax.xmlreader.IncrementalParser method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.reset_prog_mode">reset_prog_mode() (in module curses)</a>
</li>
      <li><a href="library/curses.html#curses.reset_shell_mode">reset_shell_mode() (in module curses)</a>
</li>
      <li><a href="library/code.html#code.InteractiveConsole.resetbuffer">resetbuffer() (code.InteractiveConsole method)</a>
</li>
      <li><a href="library/locale.html#locale.resetlocale">resetlocale() (in module locale)</a>
</li>
      <li><a href="library/turtle.html#turtle.resetscreen">resetscreen() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.resetty">resetty() (in module curses)</a>
</li>
      <li><a href="library/warnings.html#warnings.resetwarnings">resetwarnings() (in module warnings)</a>
</li>
      <li><a href="library/curses.html#curses.window.resize">resize() (curses.window method)</a>

      <ul>
        <li><a href="library/ctypes.html#ctypes.resize">(in module ctypes)</a>
</li>
        <li><a href="library/mmap.html#mmap.mmap.resize">(mmap.mmap method)</a>
</li>
      </ul></li>
      <li><a href="library/curses.html#curses.resize_term">resize_term() (in module curses)</a>
</li>
      <li><a href="library/turtle.html#turtle.resizemode">resizemode() (in module turtle)</a>
</li>
      <li><a href="library/curses.html#curses.resizeterm">resizeterm() (in module curses)</a>
</li>
      <li><a href="library/datetime.html#datetime.date.resolution">resolution (datetime.date attribute)</a>

      <ul>
        <li><a href="library/datetime.html#datetime.datetime.resolution">(datetime.datetime attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.time.resolution">(datetime.time attribute)</a>
</li>
        <li><a href="library/datetime.html#datetime.timedelta.resolution">(datetime.timedelta attribute)</a>
</li>
      </ul></li>
      <li><a href="library/xml.sax.handler.html#xml.sax.handler.EntityResolver.resolveEntity">resolveEntity() (xml.sax.handler.EntityResolver method)</a>
</li>
      <li><a href="library/resource.html#module-resource">resource (module)</a>
</li>
      <li><a href="library/test.html#test.support.ResourceDenied">ResourceDenied</a>
</li>
      <li><a href="library/imaplib.html#imaplib.IMAP4.response">response() (imaplib.IMAP4 method)</a>
</li>
      <li><a href="library/httplib.html#httplib.ResponseNotReady">ResponseNotReady</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.responses">responses (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>

      <ul>
        <li><a href="library/httplib.html#httplib.responses">(in module httplib)</a>
</li>
      </ul></li>
      <li><a href="library/macostools.html#findertools.restart">restart() (in module findertools)</a>
</li>
      <li><a href="library/difflib.html#difflib.restore">restore() (in module difflib)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">RESTRICTED</a>
</li>
      <li>
    restricted

      <ul>
        <li><a href="reference/executionmodel.html#index-10">execution</a>
</li>
      </ul></li>
      <li><a href="library/ctypes.html#ctypes._FuncPtr.restype">restype (ctypes._FuncPtr attribute)</a>
</li>
      <li><a href="library/trace.html#trace.Trace.results">results() (trace.Trace method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.retr">retr() (poplib.POP3 method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.retrbinary">retrbinary() (ftplib.FTP method)</a>
</li>
      <li><a href="library/urllib.html#urllib.URLopener.retrieve">retrieve() (urllib.URLopener method)</a>
</li>
      <li><a href="library/ftplib.html#ftplib.FTP.retrlines">retrlines() (ftplib.FTP method)</a>
</li>
      <li>
    return

      <ul>
        <li><a href="reference/compound_stmts.html#index-12">statement</a>, <a href="reference/compound_stmts.html#index-14">[1]</a>, <a href="reference/simple_stmts.html#index-26">[2]</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.return_ok">return_ok() (cookielib.CookiePolicy method)</a>
</li>
      <li><a href="library/dis.html#opcode-RETURN_VALUE">RETURN_VALUE (opcode)</a>
</li>
      <li><a href="library/subprocess.html#subprocess.CalledProcessError.returncode">returncode (subprocess.CalledProcessError attribute)</a>

      <ul>
        <li><a href="library/subprocess.html#subprocess.Popen.returncode">(subprocess.Popen attribute)</a>
</li>
      </ul></li>
      <li><a href="library/pyexpat.html#xml.parsers.expat.xmlparser.returns_unicode">returns_unicode (xml.parsers.expat.xmlparser attribute)</a>
</li>
      <li>
    reverse

      <ul>
        <li><a href="reference/datamodel.html#index-77">quotes</a>, <a href="reference/expressions.html#index-19">[1]</a>
</li>
      </ul></li>
      <li><a href="library/array.html#array.array.reverse">reverse() (array.array method)</a>

      <ul>
        <li><a href="library/collections.html#collections.deque.reverse">(collections.deque method)</a>
</li>
        <li><a href="library/audioop.html#audioop.reverse">(in module audioop)</a>
</li>
        <li><a href="library/stdtypes.html#index-30">(list method)</a>
</li>
      </ul></li>
      <li><a href="library/profile.html#pstats.Stats.reverse_order">reverse_order() (pstats.Stats method)</a>
</li>
      <li><a href="library/functions.html#reversed">reversed() (built-in function)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.FileCookieJar.revert">revert() (cookielib.FileCookieJar method)</a>
</li>
      <li><a href="library/aifc.html#aifc.aifc.rewind">rewind() (aifc.aifc method)</a>

      <ul>
        <li><a href="library/sunau.html#sunau.AU_read.rewind">(sunau.AU_read method)</a>
</li>
        <li><a href="library/wave.html#wave.Wave_read.rewind">(wave.Wave_read method)</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#rfc822.Message.rewindbody">rewindbody() (rfc822.Message method)</a>
</li>
      <li>
    rexec

      <ul>
        <li><a href="c-api/import.html#index-2">module</a>
</li>
      </ul></li>
      <li><a href="library/rexec.html#rexec.RExec">RExec (class in rexec)</a>
</li>
      <li><a href="library/rexec.html#module-rexec">rexec (module)</a>
</li>
      <li>
    RFC

      <ul>
        <li><a href="library/xdrlib.html#index-1">RFC 1014</a>, <a href="library/xdrlib.html#index-2">[1]</a>
</li>
        <li><a href="library/time.html#index-18">RFC 1123</a>
</li>
        <li><a href="library/hashlib.html#index-1">RFC 1321</a>, <a href="library/md5.html#index-1">[1]</a>
</li>
        <li><a href="library/ssl.html#index-17">RFC 1422</a>
</li>
        <li><a href="library/base64.html#index-4">RFC 1521</a>, <a href="library/quopri.html#index-1">[1]</a>, <a href="library/quopri.html#index-3">[2]</a>
</li>
        <li><a href="library/quopri.html#index-2">RFC 1522</a>
</li>
        <li><a href="library/mailcap.html#index-0">RFC 1524</a>, <a href="library/mailcap.html#index-1">[1]</a>
</li>
        <li><a href="library/poplib.html#index-1">RFC 1725</a>
</li>
        <li><a href="library/imaplib.html#index-2">RFC 1730</a>
</li>
        <li><a href="library/urlparse.html#index-8">RFC 1738</a>
</li>
        <li><a href="library/ssl.html#index-4">RFC 1750</a>
</li>
        <li><a href="library/locale.html#index-4">RFC 1766</a>, <a href="library/locale.html#index-5">[1]</a>
</li>
        <li><a href="library/urlparse.html#index-1">RFC 1808</a>, <a href="library/urlparse.html#index-7">[1]</a>
</li>
        <li><a href="library/xdrlib.html#index-3">RFC 1832</a>, <a href="library/xdrlib.html#index-4">[1]</a>
</li>
        <li><a href="library/htmllib.html#index-2">RFC 1866</a>
</li>
        <li><a href="library/smtplib.html#index-2">RFC 1869</a>, <a href="library/smtplib.html#index-4">[1]</a>
</li>
        <li><a href="library/email.html#index-9">RFC 1894</a>
</li>
        <li><a href="whatsnew/2.6.html#index-22">RFC 2033</a>
</li>
        <li><a href="library/email.header.html#index-4">RFC 2045</a>, <a href="library/email.html#index-3">[1]</a>, <a href="library/email.message.html#index-3">[2]</a>, <a href="library/email.message.html#index-4">[3]</a>, <a href="library/email.message.html#index-5">[4]</a>, <a href="library/email.message.html#index-8">[5]</a>, <a href="library/multifile.html#index-0">[6]</a>
</li>
        <li><a href="library/email.header.html#index-5">RFC 2046</a>, <a href="library/email.html#index-4">[1]</a>
</li>
        <li><a href="library/email.header.html#index-11">RFC 2047</a>, <a href="library/email.header.html#index-13">[1]</a>, <a href="library/email.header.html#index-6">[2]</a>, <a href="library/email.header.html#index-8">[3]</a>, <a href="library/email.html#index-5">[4]</a>
</li>
        <li><a href="library/imaplib.html#index-1">RFC 2060</a>, <a href="library/imaplib.html#index-3">[1]</a>
</li>
        <li><a href="library/cookie.html#index-1">RFC 2068</a>
</li>
        <li><a href="library/hmac.html#index-0">RFC 2104</a>, <a href="whatsnew/2.2.html#index-17">[1]</a>
</li>
        <li><a href="library/cookie.html#index-0">RFC 2109</a>, <a href="library/cookie.html#index-2">[1]</a>, <a href="library/cookie.html#index-3">[2]</a>, <a href="library/cookie.html#index-4">[3]</a>, <a href="library/cookie.html#index-5">[4]</a>, <a href="library/cookielib.html#index-1">[5]</a>, <a href="library/cookielib.html#index-2">[6]</a>
</li>
        <li><a href="library/email.header.html#index-7">RFC 2231</a>, <a href="library/email.html#index-6">[1]</a>, <a href="library/email.html#index-8">[2]</a>, <a href="library/email.message.html#index-2">[3]</a>, <a href="library/email.message.html#index-6">[4]</a>, <a href="library/email.message.html#index-7">[5]</a>, <a href="library/email.message.html#index-9">[6]</a>, <a href="library/email.utils.html#index-4">[7]</a>, <a href="library/email.utils.html#index-5">[8]</a>, <a href="library/email.utils.html#index-6">[9]</a>, <a href="library/email.utils.html#index-7">[10]</a>, <a href="library/email.utils.html#index-8">[11]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-19">RFC 2342</a>
</li>
        <li><a href="library/urlparse.html#index-6">RFC 2368</a>
</li>
        <li><a href="library/urlparse.html#index-2">RFC 2396</a>, <a href="library/urlparse.html#index-5">[1]</a>
</li>
        <li><a href="whatsnew/2.2.html#index-18">RFC 2487</a>
</li>
        <li><a href="howto/urllib2.html#index-0">RFC 2616</a>, <a href="library/urllib.html#index-7">[1]</a>, <a href="library/urllib2.html#index-4">[2]</a>, <a href="library/urllib2.html#index-5">[3]</a>, <a href="library/wsgiref.html#index-5">[4]</a>
</li>
        <li><a href="library/urlparse.html#index-4">RFC 2732</a>, <a href="whatsnew/2.7.html#index-11">[1]</a>
</li>
        <li><a href="library/httplib.html#index-4">RFC 2774</a>
</li>
        <li><a href="library/httplib.html#index-3">RFC 2817</a>
</li>
        <li><a href="library/ssl.html#index-5">RFC 2818</a>
</li>
        <li><a href="library/email.html#index-1">RFC 2821</a>
</li>
        <li><a href="library/email.errors.html#index-0">RFC 2822</a>, <a href="library/email.errors.html#index-1">[1]</a>, <a href="library/email.errors.html#index-2">[2]</a>, <a href="library/email.errors.html#index-3">[3]</a>, <a href="library/email.generator.html#index-0">[4]</a>, <a href="library/email.generator.html#index-1">[5]</a>, <a href="library/email.header.html#index-0">[6]</a>, <a href="library/email.header.html#index-10">[7]</a>, <a href="library/email.header.html#index-12">[8]</a>, <a href="library/email.header.html#index-2">[9]</a>, <a href="library/email.header.html#index-3">[10]</a>, <a href="library/email.header.html#index-9">[11]</a>, <a href="library/email.html#index-0">[12]</a>, <a href="library/email.html#index-2">[13]</a>, <a href="library/email.message.html#index-0">[14]</a>, <a href="library/email.message.html#index-1">[15]</a>, <a href="library/email.parser.html#index-0">[16]</a>, <a href="library/email.utils.html#index-0">[17]</a>, <a href="library/email.utils.html#index-1">[18]</a>, <a href="library/email.utils.html#index-2">[19]</a>, <a href="library/email.utils.html#index-3">[20]</a>, <a href="library/email.utils.html#index-9">[21]</a>, <a href="library/mailbox.html#index-0">[22]</a>, <a href="library/rfc822.html#index-0">[23]</a>, <a href="library/rfc822.html#index-1">[24]</a>, <a href="library/rfc822.html#index-10">[25]</a>, <a href="library/rfc822.html#index-12">[26]</a>, <a href="library/rfc822.html#index-2">[27]</a>, <a href="library/rfc822.html#index-4">[28]</a>, <a href="library/rfc822.html#index-5">[29]</a>, <a href="library/rfc822.html#index-6">[30]</a>, <a href="library/rfc822.html#index-7">[31]</a>, <a href="library/rfc822.html#index-8">[32]</a>, <a href="library/smtpd.html#index-0">[33]</a>, <a href="library/time.html#index-19">[34]</a>, <a href="library/time.html#index-9">[35]</a>, <a href="whatsnew/2.2.html#index-20">[36]</a>
</li>
        <li><a href="library/cookielib.html#index-4">RFC 2964</a>
</li>
        <li><a href="library/cookielib.html#index-0">RFC 2965</a>, <a href="library/cookielib.html#index-3">[1]</a>, <a href="library/urllib2.html#index-1">[2]</a>, <a href="library/urllib2.html#index-3">[3]</a>
</li>
        <li><a href="whatsnew/2.6.html#index-23">RFC 3207</a>
</li>
        <li><a href="library/httplib.html#index-2">RFC 3229</a>
</li>
        <li><a href="library/ssl.html#index-11">RFC 3280</a>
</li>
        <li><a href="library/stringprep.html#index-0">RFC 3454</a>
</li>
        <li><a href="library/codecs.html#index-1">RFC 3490</a>, <a href="library/codecs.html#index-3">[1]</a>, <a href="library/codecs.html#index-5">[2]</a>, <a href="library/codecs.html#index-6">[3]</a>, <a href="library/codecs.html#index-7">[4]</a>
</li>
        <li><a href="library/codecs.html#index-2">RFC 3492</a>, <a href="library/codecs.html#index-4">[1]</a>
</li>
        <li><a href="library/socket.html#index-0">RFC 3493</a>
</li>
        <li><a href="library/base64.html#index-1">RFC 3548</a>, <a href="library/base64.html#index-2">[1]</a>, <a href="library/base64.html#index-3">[2]</a>, <a href="library/binascii.html#index-1">[3]</a>
</li>
        <li><a href="library/urlparse.html#index-3">RFC 3986</a>, <a href="whatsnew/2.7.html#index-10">[1]</a>, <a href="whatsnew/2.7.html#index-13">[2]</a>
</li>
        <li><a href="library/uuid.html#index-0">RFC 4122</a>, <a href="library/uuid.html#index-6">[1]</a>, <a href="library/uuid.html#index-7">[2]</a>, <a href="whatsnew/2.5.html#index-19">[3]</a>, <a href="whatsnew/2.5.html#index-20">[4]</a>
</li>
        <li><a href="library/ftplib.html#index-2">RFC 4217</a>
</li>
        <li><a href="library/ssl.html#index-9">RFC 4366</a>
</li>
        <li><a href="library/json.html#index-1">RFC 4627</a>, <a href="library/json.html#index-3">[1]</a>
</li>
        <li><a href="library/ssl.html#index-10">RFC 5246</a>
</li>
        <li><a href="library/ssl.html#index-7">RFC 5280</a>
</li>
        <li><a href="library/ssl.html#index-12">RFC 5929</a>
</li>
        <li><a href="library/ssl.html#index-14">RFC 6066</a>
</li>
        <li><a href="library/ssl.html#index-6">RFC 6125</a>
</li>
        <li><a href="library/json.html#index-0">RFC 7159</a>, <a href="library/json.html#index-2">[1]</a>, <a href="library/json.html#index-4">[2]</a>
</li>
        <li><a href="library/ssl.html#index-13">RFC 7301</a>, <a href="library/ssl.html#index-8">[1]</a>
</li>
        <li><a href="library/smtplib.html#index-1">RFC 821</a>, <a href="library/smtplib.html#index-3">[1]</a>
</li>
        <li><a href="distutils/apiref.html#index-3">RFC 822</a>, <a href="library/configparser.html#index-1">[1]</a>, <a href="library/email.header.html#index-1">[2]</a>, <a href="library/gettext.html#index-8">[3]</a>, <a href="library/httplib.html#index-5">[4]</a>, <a href="library/rfc822.html#index-11">[5]</a>, <a href="library/rfc822.html#index-13">[6]</a>, <a href="library/rfc822.html#index-9">[7]</a>, <a href="library/smtplib.html#index-5">[8]</a>, <a href="library/smtplib.html#index-6">[9]</a>, <a href="library/smtplib.html#index-7">[10]</a>, <a href="library/smtplib.html#index-8">[11]</a>, <a href="library/time.html#index-16">[12]</a>, <a href="library/time.html#index-17">[13]</a>, <a href="whatsnew/2.2.html#index-21">[14]</a>
</li>
        <li><a href="library/telnetlib.html#index-1">RFC 854</a>, <a href="library/telnetlib.html#index-2">[1]</a>
</li>
        <li><a href="library/ftplib.html#index-1">RFC 959</a>
</li>
        <li><a href="library/nntplib.html#index-1">RFC 977</a>
</li>
      </ul></li>
      <li><a href="library/cookielib.html#cookielib.Cookie.rfc2109">rfc2109 (cookielib.Cookie attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.DefaultCookiePolicy.rfc2109_as_netscape">rfc2109_as_netscape (cookielib.DefaultCookiePolicy attribute)</a>
</li>
      <li><a href="library/cookielib.html#cookielib.CookiePolicy.rfc2965">rfc2965 (cookielib.CookiePolicy attribute)</a>
</li>
      <li>
    rfc822

      <ul>
        <li><a href="library/mimetools.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/rfc822.html#module-rfc822">rfc822 (module)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.util.rfc822_escape">rfc822_escape() (in module distutils.util)</a>
</li>
      <li><a href="library/uuid.html#uuid.RFC_4122">RFC_4122 (in module uuid)</a>
</li>
      <li><a href="library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.rfile">rfile (BaseHTTPServer.BaseHTTPRequestHandler attribute)</a>
</li>
      <li><a href="library/string.html#string.rfind">rfind() (in module string)</a>

      <ul>
        <li><a href="library/mmap.html#mmap.mmap.rfind">(mmap.mmap method)</a>
</li>
        <li><a href="library/stdtypes.html#str.rfind">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_hls">rgb_to_hls() (in module colorsys)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_hsv">rgb_to_hsv() (in module colorsys)</a>
</li>
      <li><a href="library/colorsys.html#colorsys.rgb_to_yiq">rgb_to_yiq() (in module colorsys)</a>
</li>
      <li><a href="library/aetypes.html#aetypes.RGBColor">RGBColor (class in aetypes)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right">right (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/turtle.html#turtle.right">right() (in module turtle)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right_list">right_list (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/filecmp.html#filecmp.dircmp.right_only">right_only (filecmp.dircmp attribute)</a>
</li>
      <li><a href="library/token.html#token.RIGHTSHIFT">RIGHTSHIFT (in module token)</a>
</li>
      <li><a href="library/token.html#token.RIGHTSHIFTEQUAL">RIGHTSHIFTEQUAL (in module token)</a>
</li>
      <li><a href="library/string.html#string.rindex">rindex() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rindex">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/string.html#string.rjust">rjust() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rjust">(str method)</a>
</li>
      </ul></li>
      <li>
    rlcompleter

      <ul>
        <li><a href="tutorial/interactive.html#index-0">module</a>
</li>
      </ul></li>
      <li><a href="library/rlcompleter.html#module-rlcompleter">rlcompleter (module)</a>
</li>
      <li><a href="library/binascii.html#binascii.rlecode_hqx">rlecode_hqx() (in module binascii)</a>
</li>
      <li><a href="library/binascii.html#binascii.rledecode_hqx">rledecode_hqx() (in module binascii)</a>
</li>
      <li><a href="library/resource.html#resource.RLIM_INFINITY">RLIM_INFINITY (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_AS">RLIMIT_AS (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_CORE">RLIMIT_CORE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_CPU">RLIMIT_CPU (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_DATA">RLIMIT_DATA (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_FSIZE">RLIMIT_FSIZE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_MEMLOCK">RLIMIT_MEMLOCK (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_NOFILE">RLIMIT_NOFILE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_NPROC">RLIMIT_NPROC (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_OFILE">RLIMIT_OFILE (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_RSS">RLIMIT_RSS (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_STACK">RLIMIT_STACK (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RLIMIT_VMEM">RLIMIT_VMEM (in module resource)</a>
</li>
      <li><a href="library/multiprocessing.html#multiprocessing.RLock">RLock (class in multiprocessing)</a>
</li>
      <li><a href="library/threading.html#threading.RLock">RLock() (in module threading)</a>

      <ul>
        <li><a href="library/multiprocessing.html#multiprocessing.managers.SyncManager.RLock">(multiprocessing.managers.SyncManager method)</a>
</li>
      </ul></li>
      <li><a href="library/ftplib.html#ftplib.FTP.rmd">rmd() (ftplib.FTP method)</a>
</li>
      <li><a href="library/os.html#os.rmdir">rmdir() (in module os)</a>
</li>
      <li><a href="library/chunk.html#index-0">RMFF</a>
</li>
      <li><a href="library/audioop.html#audioop.rms">rms() (in module audioop)</a>
</li>
      <li><a href="library/shutil.html#shutil.rmtree">rmtree() (in module shutil)</a>
</li>
      <li><a href="library/bsddb.html#bsddb.rnopen">rnopen() (in module bsddb)</a>
</li>
      <li><a href="extending/newtypes.html#index-3">RO</a>
</li>
      <li><a href="library/robotparser.html#robotparser.RobotFileParser">RobotFileParser (class in robotparser)</a>
</li>
      <li><a href="library/robotparser.html#module-robotparser">robotparser (module)</a>
</li>
      <li><a href="library/robotparser.html#index-0">robots.txt</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.rollback">rollback() (sqlite3.Connection method)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_FOUR">ROT_FOUR (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_THREE">ROT_THREE (opcode)</a>
</li>
      <li><a href="library/dis.html#opcode-ROT_TWO">ROT_TWO (opcode)</a>
</li>
      <li><a href="library/collections.html#collections.deque.rotate">rotate() (collections.deque method)</a>

      <ul>
        <li><a href="library/decimal.html#decimal.Context.rotate">(decimal.Context method)</a>
</li>
        <li><a href="library/decimal.html#decimal.Decimal.rotate">(decimal.Decimal method)</a>
</li>
      </ul></li>
      <li><a href="library/logging.handlers.html#logging.handlers.RotatingFileHandler">RotatingFileHandler (class in logging.handlers)</a>
</li>
      <li><a href="library/functions.html#round">round() (built-in function)</a>
</li>
      <li><a href="library/decimal.html#decimal.Rounded">Rounded (class in decimal)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Row">Row (class in sqlite3)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Connection.row_factory">row_factory (sqlite3.Connection attribute)</a>
</li>
      <li><a href="library/sqlite3.html#sqlite3.Cursor.rowcount">rowcount (sqlite3.Cursor attribute)</a>
</li>
      <li><a href="library/token.html#token.RPAR">RPAR (in module token)</a>
</li>
      <li><a href="library/stdtypes.html#str.rpartition">rpartition() (str method)</a>
</li>
      <li><a href="library/simplexmlrpcserver.html#SimpleXMLRPCServer.SimpleXMLRPCRequestHandler.rpc_paths">rpc_paths (SimpleXMLRPCServer.SimpleXMLRPCRequestHandler attribute)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.rpop">rpop() (poplib.POP3 method)</a>
</li>
      <li><a href="library/poplib.html#poplib.POP3.rset">rset() (poplib.POP3 method)</a>
</li>
      <li><a href="library/operator.html#operator.rshift">rshift() (in module operator)</a>
</li>
      <li><a href="library/string.html#string.rsplit">rsplit() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rsplit">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/token.html#token.RSQB">RSQB (in module token)</a>
</li>
      <li><a href="library/string.html#string.rstrip">rstrip() (in module string)</a>

      <ul>
        <li><a href="library/stdtypes.html#str.rstrip">(str method)</a>
</li>
      </ul></li>
      <li><a href="library/turtle.html#turtle.rt">rt() (in module turtle)</a>
</li>
      <li><a href="library/dl.html#dl.RTLD_LAZY">RTLD_LAZY (in module dl)</a>
</li>
      <li><a href="library/dl.html#dl.RTLD_NOW">RTLD_NOW (in module dl)</a>
</li>
      <li><a href="library/cmd.html#cmd.Cmd.ruler">ruler (cmd.Cmd attribute)</a>
</li>
      <li><a href="library/idle.html#index-2">Run script</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.run">run() (bdb.Bdb method)</a>

      <ul>
        <li><a href="distutils/apiref.html#distutils.cmd.Command.run">(distutils.cmd.Command method)</a>
</li>
        <li><a href="library/doctest.html#doctest.DocTestRunner.run">(doctest.DocTestRunner method)</a>
</li>
        <li><a href="library/hotshot.html#hotshot.Profile.run">(hotshot.Profile method)</a>
</li>
        <li><a href="library/pdb.html#pdb.run">(in module pdb)</a>
</li>
        <li><a href="library/profile.html#profile.run">(in module profile)</a>
</li>
        <li><a href="library/multiprocessing.html#multiprocessing.Process.run">(multiprocessing.Process method)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.run">(pdb.Pdb method)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.run">(profile.Profile method)</a>
</li>
        <li><a href="library/sched.html#sched.scheduler.run">(sched.scheduler method)</a>
</li>
        <li><a href="library/threading.html#threading.Thread.run">(threading.Thread method)</a>
</li>
        <li><a href="library/trace.html#trace.Trace.run">(trace.Trace method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestCase.run">(unittest.TestCase method)</a>
</li>
        <li><a href="library/unittest.html#unittest.TestSuite.run">(unittest.TestSuite method)</a>
</li>
        <li><a href="library/wsgiref.html#wsgiref.handlers.BaseHandler.run">(wsgiref.handlers.BaseHandler method)</a>
</li>
      </ul></li>
      <li><a href="library/doctest.html#doctest.run_docstring_examples">run_docstring_examples() (in module doctest)</a>
</li>
      <li><a href="library/runpy.html#runpy.run_module">run_module() (in module runpy)</a>
</li>
      <li><a href="library/runpy.html#runpy.run_path">run_path() (in module runpy)</a>
</li>
      <li><a href="library/modulefinder.html#modulefinder.ModuleFinder.run_script">run_script() (modulefinder.ModuleFinder method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.core.run_setup">run_setup() (in module distutils.core)</a>
</li>
      <li><a href="library/test.html#test.support.run_unittest">run_unittest() (in module test.support)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.runcall">runcall() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/hotshot.html#hotshot.Profile.runcall">(hotshot.Profile method)</a>
</li>
        <li><a href="library/pdb.html#pdb.runcall">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.runcall">(pdb.Pdb method)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.runcall">(profile.Profile method)</a>
</li>
      </ul></li>
      <li><a href="library/code.html#code.InteractiveInterpreter.runcode">runcode() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="library/bdb.html#bdb.Bdb.runctx">runctx() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/hotshot.html#hotshot.Profile.runctx">(hotshot.Profile method)</a>
</li>
        <li><a href="library/profile.html#profile.runctx">(in module profile)</a>
</li>
        <li><a href="library/profile.html#profile.Profile.runctx">(profile.Profile method)</a>
</li>
        <li><a href="library/trace.html#trace.Trace.runctx">(trace.Trace method)</a>
</li>
      </ul></li>
      <li><a href="library/bdb.html#bdb.Bdb.runeval">runeval() (bdb.Bdb method)</a>

      <ul>
        <li><a href="library/pdb.html#pdb.runeval">(in module pdb)</a>
</li>
        <li><a href="library/pdb.html#pdb.Pdb.runeval">(pdb.Pdb method)</a>
</li>
      </ul></li>
      <li><a href="library/trace.html#trace.Trace.runfunc">runfunc() (trace.Trace method)</a>
</li>
      <li><a href="library/runpy.html#module-runpy">runpy (module)</a>
</li>
      <li><a href="library/code.html#code.InteractiveInterpreter.runsource">runsource() (code.InteractiveInterpreter method)</a>
</li>
      <li><a href="distutils/apiref.html#distutils.ccompiler.CCompiler.runtime_library_dir_option">runtime_library_dir_option() (distutils.ccompiler.CCompiler method)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.RuntimeError">RuntimeError</a>

      <ul>
        <li><a href="reference/simple_stmts.html#index-24">exception</a>
</li>
      </ul></li>
      <li><a href="library/macos.html#MacOS.runtimemodel">runtimemodel (in module MacOS)</a>
</li>
      <li><a href="library/exceptions.html#exceptions.RuntimeWarning">RuntimeWarning</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_BOTH">RUSAGE_BOTH (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_CHILDREN">RUSAGE_CHILDREN (in module resource)</a>
</li>
      <li><a href="library/resource.html#resource.RUSAGE_SELF">RUSAGE_SELF (in module resource)</a>
</li>
  </ul></td>
</tr></table>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
<div id="searchbox" style="display: none" role="search">
  <h3>Quick search</h3>
    <div class="searchformwrapper">
    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\�C�Ihtml/search.htmlnu�[���
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Search &#8212; Python 2.7.16 documentation</title>
    <link rel="stylesheet" href="_static/classic.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/underscore.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <script type="text/javascript" src="_static/searchtools.js"></script>
    <script type="text/javascript" src="_static/sidebar.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 2.7.16 documentation"
          href="_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="about.html" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="#" />
    <link rel="copyright" title="Copyright" href="copyright.html" />
  <script type="text/javascript">
    jQuery(function() { Search.loadIndex("searchindex.js"); });
  </script>
  
  <script type="text/javascript" id="searchindexloader"></script>
  
    <link rel="shortcut icon" type="image/png" href="_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/2/search.html" />
    <script type="text/javascript" src="_static/copybutton.js"></script>
    
 
    


  </head><body>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <h1 id="search-documentation">Search</h1>
  <div id="fallback" class="admonition warning">
  <script type="text/javascript">$('#fallback').hide();</script>
  <p>
    Please activate JavaScript to enable the search
    functionality.
  </p>
  </div>
  <p>
    From here you can search these documents. Enter your search
    words into the box below and click "search". Note that the search
    function will automatically search for all of the words. Pages
    containing fewer words won't appear in the result list.
  </p>
  <form action="" method="get">
    <input type="text" name="q" value="" />
    <input type="submit" value="search" />
    <span id="search-progress" style="padding-left: 10px"></span>
  </form>
  
  <div id="search-results">
  
  </div>

          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li><img src="_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <a href="index.html">Python 2.7.16 documentation</a> &#187;
        </li>
 
      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="copyright.html">Copyright</a> 1990-2019, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 27, 2019.
    <a href="bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.7.6.
    </div>

  </body>
</html>PK
%�\Ϸf%u
%u
HISTORYnu�[���Python History
--------------

This file contains the release messages for previous Python releases.
As you read on you go back to the dark ages of Python's history.
(Note: news about 2.5c2 and later 2.5 releases is in the Misc/NEWS
file of the release25-maint branch.)


======================================================================


What's New in Python 2.5 release candidate 1?
=============================================

*Release date: 17-AUG-2006*

Core and builtins
-----------------

- Unicode objects will no longer raise an exception when being
  compared equal or unequal to a string and a UnicodeDecodeError
  exception occurs, e.g. as result of a decoding failure.

  Instead, the equal (==) and unequal (!=) comparison operators will
  now issue a UnicodeWarning and interpret the two objects as
  unequal. The UnicodeWarning can be filtered as desired using
  the warning framework, e.g. silenced completely, turned into an
  exception, logged, etc.

  Note that compare operators other than equal and unequal will still
  raise UnicodeDecodeError exceptions as they've always done.

- Fix segfault when doing string formatting on subclasses of long.

- Fix bug related to __len__ functions using values > 2**32 on 64-bit machines
  with new-style classes.

- Fix bug related to __len__ functions returning negative values with
  classic classes.

- Patch #1538606, Fix __index__() clipping.  There were some problems
  discovered with the API and how integers that didn't fit into Py_ssize_t
  were handled.  This patch attempts to provide enough alternatives
  to effectively use __index__.

- Bug #1536021: __hash__ may now return long int; the final hash
  value is obtained by invoking hash on the long int.

- Bug #1536786: buffer comparison could emit a RuntimeWarning.

- Bug #1535165: fixed a segfault in input() and raw_input() when
  sys.stdin is closed.

- On Windows, the PyErr_Warn function is now exported from
  the Python dll again.

- Bug #1191458: tracing over for loops now produces a line event
  on each iteration.  Fixing this problem required changing the .pyc
  magic number.  This means that .pyc files generated before 2.5c1
  will be regenerated.

- Bug #1333982: string/number constants were inappropriately stored
  in the byte code and co_consts even if they were not used, ie
  immediately popped off the stack.

- Fixed a reference-counting problem in property().


Library
-------

- Fix a bug in the ``compiler`` package that caused invalid code to be
  generated for generator expressions.

- The distutils version has been changed to 2.5.0. The change to
  keep it programmatically in sync with the Python version running
  the code (introduced in 2.5b3) has been reverted. It will continue
  to be maintained manually as static string literal.

- If the Python part of a ctypes callback function returns None,
  and this cannot be converted to the required C type, an exception is
  printed with PyErr_WriteUnraisable.  Before this change, the C
  callback returned arbitrary values to the calling code.

- The __repr__ method of a NULL ctypes.py_object() no longer raises
  an exception.

- uuid.UUID now has a bytes_le attribute. This returns the UUID in
  little-endian byte order for Windows. In addition, uuid.py gained some
  workarounds for clocks with low resolution, to stop the code yielding
  duplicate UUIDs.

- Patch #1540892: site.py Quitter() class attempts to close sys.stdin
  before raising SystemExit, allowing IDLE to honor quit() and exit().

- Bug #1224621: make tabnanny recognize IndentationErrors raised by tokenize.

- Patch #1536071: trace.py should now find the full module name of a
  file correctly even on Windows.

- logging's atexit hook now runs even if the rest of the module has
  already been cleaned up.

- Bug #1112549, fix DoS attack on cgi.FieldStorage.

- Bug #1531405, format_exception no longer raises an exception if
  str(exception) raised an exception.

- Fix a bug in the ``compiler`` package that caused invalid code to be
  generated for nested functions.


Extension Modules
-----------------

- Patch #1511317: don't crash on invalid hostname (alias) info.

- Patch #1535500: fix segfault in BZ2File.writelines and make sure it
  raises the correct exceptions.

- Patch # 1536908: enable building ctypes on OpenBSD/AMD64.  The
  '-no-stack-protector' compiler flag for OpenBSD has been removed.

- Patch #1532975 was applied, which fixes Bug #1533481: ctypes now
  uses the _as_parameter_ attribute when objects are passed to foreign
  function calls.  The ctypes version number was changed to 1.0.1.

- Bug #1530559, struct.pack raises TypeError where it used to convert.
  Passing float arguments to struct.pack when integers are expected
  now triggers a DeprecationWarning.


Tests
-----

- test_socketserver should now work on cygwin and not fail sporadically
  on other platforms.

- test_mailbox should now work on cygwin versions 2006-08-10 and later.

- Bug #1535182: really test the xreadlines() method of bz2 objects.

- test_threading now skips testing alternate thread stack sizes on
  platforms that don't support changing thread stack size.


Documentation
-------------

- Patch #1534922: unittest docs were corrected and enhanced.


Build
-----

- Bug #1535502, build _hashlib on Windows, and use masm assembler
  code in OpenSSL.

- Bug #1534738, win32 debug version of _msi should be _msi_d.pyd.

- Bug #1530448, ctypes build failure on Solaris 10 was fixed.


C API
-----

- New API for Unicode rich comparisons: PyUnicode_RichCompare()

- Bug #1069160.  Internal correctness changes were made to
  ``PyThreadState_SetAsyncExc()``.  A test case was added, and
  the documentation was changed to state that the return value
  is always 1 (normal) or 0 (if the specified thread wasn't found).


What's New in Python 2.5 beta 3?
================================

*Release date: 03-AUG-2006*

Core and builtins
-----------------

- _PyWeakref_GetWeakrefCount() now returns a Py_ssize_t; it previously
  returned a long (see PEP 353).

- Bug #1515471: string.replace() accepts character buffers again.

- Add PyErr_WarnEx() so C code can pass the stacklevel to warnings.warn().
  This provides the proper warning for struct.pack().
  PyErr_Warn() is now deprecated in favor of PyErr_WarnEx().

- Patch #1531113: Fix augmented assignment with yield expressions.
  Also fix a SystemError when trying to assign to yield expressions.

- Bug #1529871: The speed enhancement patch #921466 broke Python's compliance
  with PEP 302.  This was fixed by adding an ``imp.NullImporter`` type that is
  used in ``sys.path_importer_cache`` to cache non-directory paths and avoid
  excessive filesystem operations during imports.

- Bug #1521947: When checking for overflow, ``PyOS_strtol()`` used some
  operations on signed longs that are formally undefined by C.
  Unfortunately, at least one compiler now cares about that, so complicated
  the code to make that compiler happy again.

- Bug #1524310: Properly report errors from FindNextFile in os.listdir.

- Patch #1232023: Stop including current directory in search
  path on Windows.

- Fix some potential crashes found with failmalloc.

- Fix warnings reported by Klocwork's static analysis tool.

- Bug #1512814, Fix incorrect lineno's when code within a function
  had more than 255 blank lines.

- Patch #1521179: Python now accepts the standard options ``--help`` and
  ``--version`` as well as ``/?`` on Windows.

- Bug #1520864: unpacking singleton tuples in a 'for' loop (for x, in) works
  again.  Fixing this problem required changing the .pyc magic number.
  This means that .pyc files generated before 2.5b3 will be regenerated.

- Bug #1524317:  Compiling Python ``--without-threads`` failed.
  The Python core compiles again, and, in a build without threads, the
  new ``sys._current_frames()`` returns a dictionary with one entry,
  mapping the faux "thread id" 0 to the current frame.

- Bug #1525447: build on MacOS X on a case-sensitive filesystem.


Library
-------

- Fix #1693149.  Now you can pass several modules separated by
  comma to trace.py in the same --ignore-module option.

- Correction of patch #1455898: In the mbcs decoder, set final=False
  for stream decoder, but final=True for the decode function.

- os.urandom no longer masks unrelated exceptions like SystemExit or
  KeyboardInterrupt.

- Bug #1525866: Don't copy directory stat times in
  shutil.copytree on Windows

- Bug #1002398: The documentation for os.path.sameopenfile now correctly
  refers to file descriptors, not file objects.

- The renaming of the xml package to xmlcore, and the import hackery done
  to make it appear at both names, has been removed.  Bug #1511497,
  #1513611, and probably others.

- Bug #1441397: The compiler module now recognizes module and function
  docstrings correctly as it did in Python 2.4.

- Bug #1529297:  The rewrite of doctest for Python 2.4 unintentionally
  lost that tests are sorted by name before being run.  This rarely
  matters for well-written tests, but can create baffling symptoms if
  side effects from one test to the next affect outcomes.  ``DocTestFinder``
  has been changed to sort the list of tests it returns.

- The distutils version has been changed to 2.5.0, and is now kept
  in sync with sys.version_info[:3].

- Bug #978833: Really close underlying socket in _socketobject.close.

- Bug #1459963: urllib and urllib2 now normalize HTTP header names with
  title().

- Patch #1525766: In pkgutil.walk_packages, correctly pass the onerror callback
  to recursive calls and call it with the failing package name.

- Bug #1525817: Don't truncate short lines in IDLE's tool tips.

- Patch #1515343: Fix printing of deprecated string exceptions with a
  value in the traceback module.

- Resync optparse with Optik 1.5.3: minor tweaks for/to tests.

- Patch #1524429: Use repr() instead of backticks in Tkinter again.

- Bug #1520914: Change time.strftime() to accept a zero for any position in its
  argument tuple.  For arguments where zero is illegal, the value is forced to
  the minimum value that is correct.  This is to support an undocumented but
  common way people used  to fill in inconsequential information in the time
  tuple pre-2.4.

- Patch #1220874: Update the binhex module for Mach-O.

- The email package has improved RFC 2231 support, specifically for
  recognizing the difference between encoded (name*0*=<blah>) and non-encoded
  (name*0=<blah>) parameter continuations.  This may change the types of
  values returned from email.message.Message.get_param() and friends.
  Specifically in some cases where non-encoded continuations were used,
  get_param() used to return a 3-tuple of (None, None, string) whereas now it
  will just return the string (since non-encoded continuations don't have
  charset and language parts).

  Also, whereas % values were decoded in all parameter continuations, they are
  now only decoded in encoded parameter parts.

- Bug #1517990: IDLE keybindings on MacOS X now work correctly

- Bug #1517996: IDLE now longer shows the default Tk menu when a
  path browser, class browser or debugger is the frontmost window on MacOS X

- Patch #1520294: Support for getset and member descriptors in types.py,
  inspect.py, and pydoc.py.  Specifically, this allows for querying the type
  of an object against these built-in types and more importantly, for getting
  their docstrings printed in the interactive interpreter's help() function.


Extension Modules
-----------------

- Patch #1519025 and bug #926423: If a KeyboardInterrupt occurs during
  a socket operation on a socket with a timeout, the exception will be
  caught correctly.  Previously, the exception was not caught.

- Patch #1529514: The _ctypes extension is now compiled on more
  openbsd target platforms.

- The ``__reduce__()`` method of the new ``collections.defaultdict`` had
  a memory leak, affecting pickles and deep copies.

- Bug #1471938: Fix curses module build problem on Solaris 8; patch by
  Paul Eggert.

- Patch #1448199: Release interpreter lock in _winreg.ConnectRegistry.

- Patch #1521817: Index range checking on ctypes arrays containing
  exactly one element enabled again.  This allows iterating over these
  arrays, without the need to check the array size before.

- Bug #1521375: When the code in ctypes.util.find_library was
  run with root privileges, it could overwrite or delete
  /dev/null in certain cases; this is now fixed.

- Bug #1467450: On Mac OS X 10.3, RTLD_GLOBAL is now used as the
  default mode for loading shared libraries in ctypes.

- Because of a misspelled preprocessor symbol, ctypes was always
  compiled without thread support; this is now fixed.

- pybsddb Bug #1527939: bsddb module DBEnv dbremove and dbrename
  methods now allow their database parameter to be None as the
  sleepycat API allows.

- Bug #1526460: Fix socketmodule compile on NetBSD as it has a different
  bluetooth API compared with Linux and FreeBSD.

Tests
-----

- Bug #1501330: Change test_ossaudiodev to be much more tolerant in terms of
  how long the test file should take to play.  Now accepts taking 2.93 secs
  (exact time) +/- 10% instead of the hard-coded 3.1 sec.

- Patch #1529686: The standard tests ``test_defaultdict``, ``test_iterlen``,
  ``test_uuid`` and ``test_email_codecs`` didn't actually run any tests when
  run via ``regrtest.py``. Now they do.

Build
-----

- Bug #1439538: Drop usage of test -e in configure as it is not portable.

Mac
---

- PythonLauncher now works correctly when the path to the script contains
  characters that are treated specially by the shell (such as quotes).

- Bug #1527397: PythonLauncher now launches scripts with the working directory
  set to the directory that contains the script instead of the user home
  directory. That latter was an implementation accident and not what users
  expect.


What's New in Python 2.5 beta 2?
================================

*Release date: 11-JUL-2006*

Core and builtins
-----------------

- Bug #1441486: The literal representation of -(sys.maxint - 1)
  again evaluates to an int object, not a long.

- Bug #1501934: The scope of global variables that are locally assigned
  using augmented assignment is now correctly determined.

- Bug #927248: Recursive method-wrapper objects can now safely
  be released.

- Bug #1417699: Reject locale-specific decimal point in float()
  and atof().

- Bug #1511381: codec_getstreamcodec() in codec.c is corrected to
  omit a default "error" argument for NULL pointer.  This allows
  the parser to take a codec from cjkcodecs again.

- Bug #1519018: 'as' is now validated properly in import statements.

- On 64 bit systems, int literals that use less than 64 bits are
  now ints rather than longs.

- Bug #1512814, Fix incorrect lineno's when code at module scope
  started after line 256.

- New function ``sys._current_frames()`` returns a dict mapping thread
  id to topmost thread stack frame.  This is for expert use, and is
  especially useful for debugging application deadlocks.  The functionality
  was previously available in Fazal Majid's ``threadframe`` extension
  module, but it wasn't possible to do this in a wholly threadsafe way from
  an extension.

Library
-------

- Bug #1257728: Mention Cygwin in distutils error message about a missing
  VS 2003.

- Patch #1519566: Update turtle demo, make begin_fill idempotent.

- Bug #1508010: msvccompiler now requires the DISTUTILS_USE_SDK
  environment variable to be set in order to the SDK environment
  for finding the compiler, include files, etc.

- Bug #1515998: Properly generate logical ids for files in bdist_msi.

- warnings.py now ignores ImportWarning by default

- string.Template() now correctly handles tuple-values. Previously,
  multi-value tuples would raise an exception and single-value tuples would
  be treated as the value they contain, instead.

- Bug #822974: Honor timeout in telnetlib.{expect,read_until}
  even if some data are received.

- Bug #1267547: Put proper recursive setup.py call into the
  spec file generated by bdist_rpm.

- Bug #1514693: Update turtle's heading when switching between
  degrees and radians.

- Reimplement turtle.circle using a polyline, to allow correct
  filling of arcs.

- Bug #1514703: Only setup canvas window in turtle when the canvas
  is created.

- Bug #1513223: .close() of a _socketobj now releases the underlying
  socket again, which then gets closed as it becomes unreferenced.

- Bug #1504333: Make sgmllib support angle brackets in quoted
  attribute values.

- Bug #853506: Fix IPv6 address parsing in unquoted attributes in
  sgmllib ('[' and ']' were not accepted).

- Fix a bug in the turtle module's end_fill function.

- Bug #1510580: The 'warnings' module improperly required that a Warning
  category be either a types.ClassType and a subclass of Warning.  The proper
  check is just that it is a subclass with Warning as the documentation states.

- The compiler module now correctly compiles the new try-except-finally
  statement (bug #1509132).

- The wsgiref package is now installed properly on Unix.

- A bug was fixed in logging.config.fileConfig() which caused a crash on
  shutdown when fileConfig() was called multiple times.

- The sqlite3 module did cut off data from the SQLite database at the first
  null character before sending it to a custom converter. This has been fixed
  now.

Extension Modules
-----------------

- #1494314: Fix a regression with high-numbered sockets in 2.4.3. This
  means that select() on sockets > FD_SETSIZE (typically 1024) work again.
  The patch makes sockets use poll() internally where available.

- Assigning None to pointer type fields in ctypes structures possible
  overwrote the wrong fields, this is fixed now.

- Fixed a segfault in _ctypes when ctypes.wintypes were imported
  on non-Windows platforms.

- Bug #1518190: The ctypes.c_void_p constructor now accepts any
  integer or long, without range checking.

- Patch #1517790: It is now possible to use custom objects in the ctypes
  foreign function argtypes sequence as long as they provide a from_param
  method, no longer is it required that the object is a ctypes type.

- The '_ctypes' extension module now works when Python is configured
  with the --without-threads option.

- Bug #1513646: os.access on Windows now correctly determines write
  access, again.

- Bug #1512695: cPickle.loads could crash if it was interrupted with
  a KeyboardInterrupt.

- Bug #1296433: parsing XML with a non-default encoding and
  a CharacterDataHandler could crash the interpreter in pyexpat.

- Patch #1516912: improve Modules support for OpenVMS.

Build
-----

- Automate Windows build process for the Win64 SSL module.

- 'configure' now detects the zlib library the same way as distutils.
  Previously, the slight difference could cause compilation errors of the
  'zlib' module on systems with more than one version of zlib.

- The MSI compileall step was fixed to also support a TARGETDIR
  with spaces in it.

- Bug #1517388: sqlite3.dll is now installed on Windows independent
  of Tcl/Tk.

- Bug #1513032: 'make install' failed on FreeBSD 5.3 due to lib-old
  trying to be installed even though it's empty.

Tests
-----

- Call os.waitpid() at the end of tests that spawn child processes in order
  to minimize resources (zombies).

Documentation
-------------

- Cover ImportWarning, PendingDeprecationWarning and simplefilter() in the
  documentation for the warnings module.

- Patch #1509163: MS Toolkit Compiler no longer available.

- Patch #1504046: Add documentation for xml.etree.


What's New in Python 2.5 beta 1?
================================

*Release date: 20-JUN-2006*

Core and builtins
-----------------

- Patch #1507676: Error messages returned by invalid abstract object operations
  (such as iterating over an integer) have been improved and now include the
  type of the offending object to help with debugging.

- Bug #992017: A classic class that defined a __coerce__() method that returned
  its arguments swapped would infinitely recurse and segfault the interpreter.

- Fix the socket tests so they can be run concurrently.

- Removed 5 integers from C frame objects (PyFrameObject).
  f_nlocals, f_ncells, f_nfreevars, f_stack_size, f_restricted.

- Bug #532646: object.__call__() will continue looking for the __call__
  attribute on objects until one without one is found.  This leads to recursion
  when you take a class and set its __call__ attribute to an instance of the
  class.  Originally fixed for classic classes, but this fix is for new-style.
  Removes the infinite_rec_3 crasher.

- The string and unicode methods startswith() and endswith() now accept
  a tuple of prefixes/suffixes to look for. Implements RFE #1491485.

- Buffer objects, at the C level, never used the char buffer
  implementation even when the char buffer for the wrapped object was
  explicitly requested (originally returned the read or write buffer).
  Now a TypeError is raised if the char buffer is not present but is
  requested.

- Patch #1346214: Statements like "if 0: suite" are now again optimized
  away like they were in Python 2.4.

- Builtin exceptions are now full-blown new-style classes instead of
  instances pretending to be classes, which speeds up exception handling
  by about 80% in comparison to 2.5a2.

- Patch #1494554: Update unicodedata.numeric and unicode.isnumeric to
  Unicode 4.1.

- Patch #921466: sys.path_importer_cache is now used to cache valid and
  invalid file paths for the built-in import machinery which leads to
  fewer open calls on startup.

- Patch #1442927: ``long(str, base)`` is now up to 6x faster for non-power-
  of-2 bases.  The largest speedup is for inputs with about 1000 decimal
  digits.  Conversion from non-power-of-2 bases remains quadratic-time in
  the number of input digits (it was and remains linear-time for bases
  2, 4, 8, 16 and 32).

- Bug #1334662: ``int(string, base)`` could deliver a wrong answer
  when ``base`` was not 2, 4, 8, 10, 16 or 32, and ``string`` represented
  an integer close to ``sys.maxint``.  This was repaired by patch
  #1335972, which also gives a nice speedup.

- Patch #1337051: reduced size of frame objects.

- PyErr_NewException now accepts a tuple of base classes as its
  "base" parameter.

- Patch #876206: function call speedup by retaining allocated frame
  objects.

- Bug #1462152: file() now checks more thoroughly for invalid mode
  strings and removes a possible "U" before passing the mode to the
  C library function.

- Patch #1488312, Fix memory alignment problem on SPARC in unicode

- Bug #1487966: Fix SystemError with conditional expression in assignment

- WindowsError now has two error code attributes: errno, which carries
  the error values from errno.h, and winerror, which carries the error
  values from winerror.h. Previous versions put the winerror.h values
  (from GetLastError()) into the errno attribute.

- Patch #1475845: Raise IndentationError for unexpected indent.

- Patch #1479181: split open() and file() from being aliases for each other.

- Patch #1497053 & bug #1275608: Exceptions occurring in ``__eq__()``
  methods were always silently ignored by dictionaries when comparing keys.
  They are now passed through (except when using the C API function
  ``PyDict_GetItem()``, whose semantics did not change).

- Bug #1456209: In some obscure cases it was possible for a class with a
  custom ``__eq__()`` method to confuse dict internals when class instances
  were used as a dict's keys and the ``__eq__()`` method mutated the dict.
  No, you don't have any code that did this ;-)

Extension Modules
-----------------

- Bug #1295808: expat symbols should be namespaced in pyexpat

- Patch #1462338: Upgrade pyexpat to expat 2.0.0

- Change binascii.hexlify to accept a read-only buffer instead of only a char
  buffer and actually follow its documentation.

- Fixed a potentially invalid memory access of CJKCodecs' shift-jis decoder.

- Patch #1478788 (modified version): The functional extension module has
  been renamed to _functools and a functools Python wrapper module added.
  This provides a home for additional function related utilities that are
  not specifically about functional programming. See PEP 309.

- Patch #1493701: performance enhancements for struct module.

- Patch #1490224: time.altzone is now set correctly on Cygwin.

- Patch #1435422: zlib's compress and decompress objects now have a
  copy() method.

- Patch #1454481: thread stack size is now tunable at runtime for thread
  enabled builds on Windows and systems with Posix threads support.

- On Win32, os.listdir now supports arbitrarily-long Unicode path names
  (up to the system limit of 32K characters).

- Use Win32 API to implement os.{access,chdir,chmod,mkdir,remove,rename,rmdir,utime}.
  As a result, these functions now raise WindowsError instead of OSError.

- ``time.clock()`` on Win64 should use the high-performance Windows
  ``QueryPerformanceCounter()`` now (as was already the case on 32-bit
  Windows platforms).

- Calling Tk_Init twice is refused if the first call failed as that
  may deadlock.

- bsddb: added the DB_ARCH_REMOVE flag and fixed db.DBEnv.log_archive() to
  accept it without potentially using an uninitialized pointer.

- bsddb: added support for the DBEnv.log_stat() and DBEnv.lsn_reset() methods
  assuming BerkeleyDB >= 4.0 and 4.4 respectively.  [pybsddb project SF
  patch numbers 1494885 and 1494902]

- bsddb: added an interface for the BerkeleyDB >= 4.3 DBSequence class.
  [pybsddb project SF patch number 1466734]

- bsddb: fix DBCursor.pget() bug with keyword argument names when no data
  parameter is supplied.  [SF pybsddb bug #1477863]

- bsddb: the __len__ method of a DB object has been fixed to return correct
  results.  It could previously incorrectly return 0 in some cases.
  Fixes SF bug 1493322 (pybsddb bug 1184012).

- bsddb: the bsddb.dbtables Modify method now raises the proper error and
  aborts the db transaction safely when a modifier callback fails.
  Fixes SF python patch/bug #1408584.

- bsddb: multithreaded DB access using the simple bsddb module interface
  now works reliably.  It has been updated to use automatic BerkeleyDB
  deadlock detection and the bsddb.dbutils.DeadlockWrap wrapper to retry
  database calls that would previously deadlock. [SF python bug #775414]

- Patch #1446489: add support for the ZIP64 extensions to zipfile.

- Patch #1506645: add Python wrappers for the curses functions
  is_term_resized, resize_term and resizeterm.

Library
-------

- Patch #815924: Restore ability to pass type= and icon= in tkMessageBox
  functions.

- Patch #812986: Update turtle output even if not tracing.

- Patch #1494750: Destroy master after deleting children in
  Tkinter.BaseWidget.

- Patch #1096231: Add ``default`` argument to Tkinter.Wm.wm_iconbitmap.

- Patch #763580: Add name and value arguments to Tkinter variable
  classes.

- Bug #1117556: SimpleHTTPServer now tries to find and use the system's
  mime.types file for determining MIME types.

- Bug #1339007: Shelf objects now don't raise an exception in their
  __del__ method when initialization failed.

- Patch #1455898: The MBCS codec now supports the incremental mode for
  double-byte encodings.

- ``difflib``'s ``SequenceMatcher.get_matching_blocks()`` was changed to
  guarantee that adjacent triples in the return list always describe
  non-adjacent blocks.  Previously, a pair of matching blocks could end
  up being described by multiple adjacent triples that formed a partition
  of the matching pair.

- Bug #1498146: fix optparse to handle Unicode strings in option help,
  description, and epilog.

- Bug #1366250: minor optparse documentation error.

- Bug #1361643: fix textwrap.dedent() so it handles tabs appropriately;
  clarify docs.

- The wsgiref package has been added to the standard library.

- The functions update_wrapper() and wraps() have been added to the functools
  module. These make it easier to copy relevant metadata from the original
  function when writing wrapper functions.

- The optional ``isprivate`` argument to ``doctest.testmod()``, and the
  ``doctest.is_private()`` function, both deprecated in 2.4, were removed.

- Patch #1359618: Speed up charmap encoder by using a trie structure
  for lookup.

- The functions in the ``pprint`` module now sort dictionaries by key
  before computing the display.  Before 2.5, ``pprint`` sorted a dictionary
  if and only if its display required more than one line, although that
  wasn't documented.  The new behavior increases predictability; e.g.,
  using ``pprint.pprint(a_dict)`` in a doctest is now reliable.

- Patch #1497027: try HTTP digest auth before basic auth in urllib2
  (thanks for J. J. Lee).

- Patch #1496206: improve urllib2 handling of passwords with respect to
  default HTTP and HTTPS ports.

- Patch #1080727: add "encoding" parameter to doctest.DocFileSuite.

- Patch #1281707: speed up gzip.readline.

- Patch #1180296: Two new functions were added to the locale module:
  format_string() to get the effect of  "format % items" but locale-aware,
  and currency() to format a monetary number with currency sign.

- Patch #1486962: Several bugs in the turtle Tk demo module were fixed
  and several features added, such as speed and geometry control.

- Patch #1488881: add support for external file objects in bz2 compressed
  tarfiles.

- Patch #721464: pdb.Pdb instances can now be given explicit stdin and
  stdout arguments, making it possible to redirect input and output
  for remote debugging.

- Patch #1484695: Update the tarfile module to version 0.8. This fixes
  a couple of issues, notably handling of long file names using the
  GNU LONGNAME extension.

- Patch #1478292. ``doctest.register_optionflag(name)`` shouldn't create a
  new flag when ``name`` is already the name of an option flag.

- Bug #1385040: don't allow "def foo(a=1, b): pass" in the compiler
  package.

- Patch #1472854: make the rlcompleter.Completer class usable on non-
  UNIX platforms.

- Patch #1470846: fix urllib2 ProxyBasicAuthHandler.

- Bug #1472827: correctly escape newlines and tabs in attribute values in
  the saxutils.XMLGenerator class.


Build
-----

- Bug #1502728: Correctly link against librt library on HP-UX.

- OpenBSD 3.9 is supported now.

- Patch #1492356: Port to Windows CE.

- Bug/Patch #1481770: Use .so extension for shared libraries on HP-UX for ia64.

- Patch #1471883: Add --enable-universalsdk.

C API
-----

Tests
-----

Tools
-----

Documentation
-------------



What's New in Python 2.5 alpha 2?
=================================

*Release date: 27-APR-2006*

Core and builtins
-----------------

- Bug #1465834: 'bdist_wininst preinstall script support' was fixed
  by converting these apis from macros into exported functions again:

    PyParser_SimpleParseFile PyParser_SimpleParseString PyRun_AnyFile
    PyRun_AnyFileEx PyRun_AnyFileFlags PyRun_File PyRun_FileEx
    PyRun_FileFlags PyRun_InteractiveLoop PyRun_InteractiveOne
    PyRun_SimpleFile PyRun_SimpleFileEx PyRun_SimpleString
    PyRun_String Py_CompileString

- Under COUNT_ALLOCS, types are not necessarily immortal anymore.

- All uses of PyStructSequence_InitType have been changed to initialize
  the type objects only once, even if the interpreter is initialized
  multiple times.

- Bug #1454485, array.array('u') could crash the interpreter.  This was
  due to PyArgs_ParseTuple(args, 'u#', ...) trying to convert buffers (strings)
  to unicode when it didn't make sense.  'u#' now requires a unicode string.

- Py_UNICODE is unsigned.  It was always documented as unsigned, but
  due to a bug had a signed value in previous versions.

- Patch #837242: ``id()`` of any Python object always gives a positive
  number now, which might be a long integer. ``PyLong_FromVoidPtr`` and
  ``PyLong_AsVoidPtr`` have been changed accordingly.  Note that it has
  never been correct to implement a ``__hash()__`` method that returns the
  ``id()`` of an object:

      def __hash__(self):
          return id(self)  # WRONG

  because a hash result must be a (short) Python int but it was always
  possible for ``id()`` to return a Python long.  However, because ``id()``
  could return negative values before, on a 32-bit box an ``id()`` result
  was always usable as a hash value before this patch.  That's no longer
  necessarily so.

- Python on OS X 10.3 and above now uses dlopen() (via dynload_shlib.c)
  to load extension modules and now provides the dl module. As a result,
  sys.setdlopenflags() now works correctly on these systems. (SF patch
  #1454844)

- Patch #1463867: enhanced garbage collection to allow cleanup of cycles
  involving generators that have paused outside of any ``try`` or ``with``
  blocks.  (In 2.5a1, a paused generator that was part of a reference
  cycle could not be garbage collected, regardless of whether it was
  paused in a ``try`` or ``with`` block.)

Extension Modules
-----------------

- Patch #1191065: Fix preprocessor problems on systems where recvfrom
  is a macro.

- Bug #1467952: os.listdir() now correctly raises an error if readdir()
  fails with an error condition.

- Fixed bsddb.db.DBError derived exceptions so they can be unpickled.

- Bug #1117761: bsddb.*open() no longer raises an exception when using
  the cachesize parameter.

- Bug #1149413: bsddb.*open() no longer raises an exception when using
  a temporary db (file=None) with the 'n' flag to truncate on open.

- Bug #1332852: bsddb module minimum BerkeleyDB version raised to 3.3
  as older versions cause excessive test failures.

- Patch #1062014: AF_UNIX sockets under Linux have a special
  abstract namespace that is now fully supported.

Library
-------

- Bug #1223937: subprocess.CalledProcessError reports the exit status
  of the process using the returncode attribute, instead of
  abusing errno.

- Patch #1475231: ``doctest`` has a new ``SKIP`` option, which causes
  a doctest to be skipped (the code is not run, and the expected output
  or exception is ignored).

- Fixed contextlib.nested to cope with exceptions being raised and
  caught inside exit handlers.

- Updated optparse module to Optik 1.5.1 (allow numeric constants in
  hex, octal, or binary; add ``append_const`` action; keep going if
  gettext cannot be imported; added ``OptionParser.destroy()`` method;
  added ``epilog`` for better help generation).

- Bug #1473760: ``tempfile.TemporaryFile()`` could hang on Windows, when
  called from a thread spawned as a side effect of importing a module.

- The pydoc module now supports documenting packages contained in
  .zip or .egg files.

- The pkgutil module now has several new utility functions, such
  as ``walk_packages()`` to support working with packages that are either
  in the filesystem or zip files.

- The mailbox module can now modify and delete messages from
  mailboxes, in addition to simply reading them.  Thanks to Gregory
  K. Johnson for writing the code, and to the 2005 Google Summer of
  Code for funding his work.

- The ``__del__`` method of class ``local`` in module ``_threading_local``
  returned before accomplishing any of its intended cleanup.

- Patch #790710: Add breakpoint command lists in pdb.

- Patch #1063914: Add Tkinter.Misc.clipboard_get().

- Patch #1191700: Adjust column alignment in bdb breakpoint lists.

- SimpleXMLRPCServer relied on the fcntl module, which is unavailable on
  Windows. Bug #1469163.

- The warnings, linecache, inspect, traceback, site, and doctest modules
  were updated to work correctly with modules imported from zipfiles or
  via other PEP 302 __loader__ objects.

- Patch #1467770: Reduce usage of subprocess._active to processes which
  the application hasn't waited on.

- Patch #1462222: Fix Tix.Grid.

- Fix exception when doing glob.glob('anything*/')

- The pstats.Stats class accepts an optional stream keyword argument to
  direct output to an alternate file-like object.

Build
-----

- The Makefile now has a reindent target, which runs reindent.py on
  the library.

- Patch #1470875: Building Python with MS Free Compiler

- Patch #1161914: Add a python-config script.

- Patch #1324762:Remove ccpython.cc; replace --with-cxx with
  --with-cxx-main. Link with C++ compiler only if --with-cxx-main was
  specified. (Can be overridden by explicitly setting LINKCC.) Decouple
  CXX from --with-cxx-main, see description in README.

- Patch #1429775: Link extension modules with the shared libpython.

- Fixed a libffi build problem on MIPS systems.

- ``PyString_FromFormat``, ``PyErr_Format``, and ``PyString_FromFormatV``
  now accept formats "%u" for unsigned ints, "%lu" for unsigned longs,
  and "%zu" for unsigned integers of type ``size_t``.

Tests
-----

- test_contextlib now checks contextlib.nested can cope with exceptions
  being raised and caught inside exit handlers.

- test_cmd_line now checks operation of the -m and -c command switches

- The test_contextlib test in 2.5a1 wasn't actually run unless you ran
  it separately and by hand.  It also wasn't cleaning up its changes to
  the current Decimal context.

- regrtest.py now has a -M option to run tests that test the new limits of
  containers, on 64-bit architectures. Running these tests is only sensible
  on 64-bit machines with more than two gigabytes of memory. The argument
  passed is the maximum amount of memory for the tests to use.

Tools
-----

- Added the Python benchmark suite pybench to the Tools/ directory;
  contributed by Marc-Andre Lemburg.

Documentation
-------------

- Patch #1473132: Improve docs for ``tp_clear`` and ``tp_traverse``.

- PEP 343: Added Context Types section to the library reference
  and attempted to bring other PEP 343 related documentation into
  line with the implementation and/or python-dev discussions.

- Bug #1337990: clarified that ``doctest`` does not support examples
  requiring both expected output and an exception.


What's New in Python 2.5 alpha 1?
=================================

*Release date: 05-APR-2006*

Core and builtins
-----------------

- PEP 338: -m command line switch now delegates to runpy.run_module
  allowing it to support modules in packages and zipfiles

- On Windows, .DLL is not an accepted file name extension for
  extension modules anymore; extensions are only found if they
  end in .PYD.

- Bug #1421664: sys.stderr.encoding is now set to the same value as
  sys.stdout.encoding.

- __import__ accepts keyword arguments.

- Patch #1460496: round() now accepts keyword arguments.

- Fixed bug #1459029 - unicode reprs were double-escaped.

- Patch #1396919: The system scope threads are reenabled on FreeBSD
  5.4 and later versions.

- Bug #1115379: Compiling a Unicode string with an encoding declaration
  now gives a SyntaxError.

- Previously, Python code had no easy way to access the contents of a
  cell object. Now, a ``cell_contents`` attribute has been added
  (closes patch #1170323).

- Patch #1123430: Python's small-object allocator now returns an arena to
  the system ``free()`` when all memory within an arena becomes unused
  again.  Prior to Python 2.5, arenas (256KB chunks of memory) were never
  freed.  Some applications will see a drop in virtual memory size now,
  especially long-running applications that, from time to time, temporarily
  use a large number of small objects.  Note that when Python returns an
  arena to the platform C's ``free()``, there's no guarantee that the
  platform C library will in turn return that memory to the operating system.
  The effect of the patch is to stop making that impossible, and in tests it
  appears to be effective at least on Microsoft C and gcc-based systems.
  Thanks to Evan Jones for hard work and patience.

- Patch #1434038: property() now uses the getter's docstring if there is
  no "doc" argument given. This makes it possible to legitimately use
  property() as a decorator to produce a read-only property.

- PEP 357, patch 1436368: add an __index__ method to int/long and a matching
  nb_index slot to the PyNumberMethods struct.  The slot is consulted instead
  of requiring an int or long in slicing and a few other contexts, enabling
  other objects (e.g. Numeric Python's integers) to be used as slice indices.

- Fixed various bugs reported by Coverity's Prevent tool.

- PEP 352, patch #1104669: Make exceptions new-style objects.  Introduced the
  new exception base class, BaseException, which has a new message attribute.
  KeyboardInterrupt and SystemExit to directly inherit from BaseException now.
  Raising a string exception now raises a DeprecationWarning.

- Patch #1438387, PEP 328: relative and absolute imports. Imports can now be
  explicitly relative, using 'from .module import name' to mean 'from the same
  package as this module is in. Imports without dots still default to the
  old relative-then-absolute, unless 'from __future__ import
  absolute_import' is used.

- Properly check if 'warnings' raises an exception (usually when a filter set
  to "error" is triggered) when raising a warning for raising string
  exceptions.

- CO_GENERATOR_ALLOWED is no longer defined. This behavior is the default.
  The name was removed from Include/code.h.

- PEP 308: conditional expressions were added: (x if cond else y).

- Patch 1433928:
  - The copy module now "copies" function objects (as atomic objects).
  - dict.__getitem__ now looks for a __missing__ hook before raising
    KeyError.

- PEP 343: with statement implemented. Needs ``from __future__ import
  with_statement``. Use of 'with' as a variable will generate a warning.
  Use of 'as' as a variable will also generate a warning (unless it's
  part of an import statement).
  The following objects have __context__ methods:
  - The built-in file type.
  - The thread.LockType type.
  - The following types defined by the threading module:
    Lock, RLock, Condition, Semaphore, BoundedSemaphore.
  - The decimal.Context class.

- Fix the encodings package codec search function to only search
  inside its own package. Fixes problem reported in patch #1433198.

  Note: Codec packages should implement and register their own
  codec search function. PEP 100 has the details.

- PEP 353: Using ``Py_ssize_t`` as the index type.

- ``PYMALLOC_DEBUG`` builds now add ``4*sizeof(size_t)`` bytes of debugging
  info to each allocated block, since the ``Py_ssize_t`` changes (PEP 353)
  now allow Python to make use of memory blocks exceeding 2**32 bytes for
  some purposes on 64-bit boxes.  A ``PYMALLOC_DEBUG`` build was limited
  to 4-byte allocations before.

- Patch #1400181, fix unicode string formatting to not use the locale.
  This is how string objects work.  u'%f' could use , instead of .
  for the decimal point.  Now both strings and unicode always use periods.

- Bug #1244610, #1392915, fix build problem on OpenBSD 3.7 and 3.8.
  configure would break checking curses.h.

- Bug #959576: The pwd module is now built in. This allows Python to be
  built on UNIX platforms without $HOME set.

- Bug #1072182, fix some potential problems if characters are signed.

- Bug #889500, fix line number on SyntaxWarning for global declarations.

- Bug #1378022, UTF-8 files with a leading BOM crashed the interpreter.

- Support for converting hex strings to floats no longer works.
  This was not portable.  float('0x3') now raises a ValueError.

- Patch #1382163: Expose Subversion revision number to Python.  New C API
  function Py_GetBuildNumber().  New attribute sys.subversion.  Build number
  is now displayed in interactive prompt banner.

- Implementation of PEP 341 - Unification of try/except and try/finally.
  "except" clauses can now be written together with a "finally" clause in
  one try statement instead of two nested ones.  Patch #1355913.

- Bug #1379994: Builtin unicode_escape and raw_unicode_escape codec
  now encodes backslash correctly.

- Patch #1350409: Work around signal handling bug in Visual Studio 2005.

- Bug #1281408: Py_BuildValue now works correctly even with unsigned longs
  and long longs.

- SF Bug #1350188, "setdlopenflags" leads to crash upon "import"
  It was possible for dlerror() to return a NULL pointer, so
  it will now use a default error message in this case.

- Replaced most Unicode charmap codecs with new ones using the
  new Unicode translate string feature in the built-in charmap
  codec; the codecs were created from the mapping tables available
  at ftp.unicode.org and contain a few updates (e.g. the Mac OS
  encodings now include a mapping for the Apple logo)

- Added a few more codecs for Mac OS encodings

- Sped up some Unicode operations.

- A new AST parser implementation was completed. The abstract
  syntax tree is available for read-only (non-compile) access
  to Python code; an _ast module was added.

- SF bug #1167751: fix incorrect code being produced for generator expressions.
  The following code now raises a SyntaxError:  foo(a = i for i in range(10))

- SF Bug #976608: fix SystemError when mtime of an imported file is -1.

- SF Bug #887946: fix segfault when redirecting stdin from a directory.
  Provide a warning when a directory is passed on the command line.

- Fix segfault with invalid coding.

- SF bug #772896: unknown encoding results in MemoryError.

- All iterators now have a Boolean value of True.  Formerly, some iterators
  supported a __len__() method which evaluated to False when the iterator
  was empty.

- On 64-bit platforms, when __len__() returns a value that cannot be
  represented as a C int, raise OverflowError.

- test__locale is skipped on OS X < 10.4 (only partial locale support is
  present).

- SF bug #893549: parsing keyword arguments was broken with a few format
  codes.

- Changes donated by Elemental Security to make it work on AIX 5.3
  with IBM's 64-bit compiler (SF patch #1284289).  This also closes SF
  bug #105470: test_pwd fails on 64bit system (Opteron).

- Changes donated by Elemental Security to make it work on HP-UX 11 on
  Itanium2 with HP's 64-bit compiler (SF patch #1225212).

- Disallow keyword arguments for type constructors that don't use them
  (fixes bug #1119418).

- Forward UnicodeDecodeError into SyntaxError for source encoding errors.

- SF bug #900092: When tracing (e.g. for hotshot), restore 'return' events for
  exceptions that cause a function to exit.

- The implementation of set() and frozenset() was revised to use its
  own internal data structure.  Memory consumption is reduced by 1/3
  and there are modest speed-ups as well.  The API is unchanged.

- SF bug #1238681:  freed pointer is used in longobject.c:long_pow().

- SF bug #1229429: PyObject_CallMethod failed to decrement some
  reference counts in some error exit cases.

- SF bug #1185883:  Python's small-object memory allocator took over
  a block managed by the platform C library whenever a realloc specified
  a small new size.  However, there's no portable way to know then how
  much of the address space following the pointer is valid, so there's no
  portable way to copy data from the C-managed block into Python's
  small-object space without risking a memory fault.  Python's small-object
  realloc now leaves such blocks under the control of the platform C
  realloc.

- SF bug #1232517: An overflow error was not detected properly when
  attempting to convert a large float to an int in os.utime().

- SF bug #1224347: hex longs now print with lowercase letters just
  like their int counterparts.

- SF bug #1163563: the original fix for bug #1010677 ("thread Module
  Breaks PyGILState_Ensure()") broke badly in the case of multiple
  interpreter states; back out that fix and do a better job (see
  http://mail.python.org/pipermail/python-dev/2005-June/054258.html
  for a longer write-up of the problem).

- SF patch #1180995: marshal now uses a binary format by default when
  serializing floats.

- SF patch #1181301: on platforms that appear to use IEEE 754 floats,
  the routines that promise to produce IEEE 754 binary representations
  of floats now simply copy bytes around.

- bug #967182: disallow opening files with 'wU' or 'aU' as specified by PEP
  278.

- patch #1109424: int, long, float, complex, and unicode now check for the
  proper magic slot for type conversions when subclassed.  Previously the
  magic slot was ignored during conversion.  Semantics now match the way
  subclasses of str always behaved.  int/long/float, conversion of an instance
  to the base class has been moved to the proper nb_* magic slot and out of
  PyNumber_*().
  Thanks Walter D�rwald.

- Descriptors defined in C with a PyGetSetDef structure, where the setter is
  NULL, now raise an AttributeError when attempting to set or delete the
  attribute.  Previously a TypeError was raised, but this was inconsistent
  with the equivalent pure-Python implementation.

- It is now safe to call PyGILState_Release() before
  PyEval_InitThreads() (note that if there is reason to believe there
  are multiple threads around you still must call PyEval_InitThreads()
  before using the Python API; this fix is for extension modules that
  have no way of knowing if Python is multi-threaded yet).

- Typing Ctrl-C whilst raw_input() was waiting in a build with threads
  disabled caused a crash.

- Bug #1165306: instancemethod_new allowed the creation of a method
  with im_class == im_self == NULL, which caused a crash when called.

- Move exception finalisation later in the shutdown process - this
  fixes the crash seen in bug #1165761

- Added two new builtins, any() and all().

- Defining a class with empty parentheses is now allowed
  (e.g., ``class C(): pass`` is no longer a syntax error).
  Patch #1176012 added support to the 'parser' module and 'compiler' package
  (thanks to logistix for that added support).

- Patch #1115086: Support PY_LONGLONG in structmember.

- Bug #1155938: new style classes did not check that __init__() was
  returning None.

- Patch #802188: Report characters after line continuation character
  ('\') with a specific error message.

- Bug #723201: Raise a TypeError for passing bad objects to 'L' format.

- Bug #1124295: the __name__ attribute of file objects was
  inadvertently made inaccessible in restricted mode.

- Bug #1074011: closing sys.std{out,err} now causes a flush() and
  an ferror() call.

- min() and max() now support key= arguments with the same meaning as in
  list.sort().

- The peephole optimizer now performs simple constant folding in expressions:
      (2+3) --> (5).

- set and frozenset objects can now be marshalled.  SF #1098985.

- Bug #1077106: Poor argument checking could cause memory corruption
  in calls to os.read().

- The parser did not complain about future statements in illegal
  positions.  It once again reports a syntax error if a future
  statement occurs after anything other than a doc string.

- Change the %s format specifier for str objects so that it returns a
  unicode instance if the argument is not an instance of basestring and
  calling __str__ on the argument returns a unicode instance.

- Patch #1413181:  changed ``PyThreadState_Delete()`` to forget about the
  current thread state when the auto-GIL-state machinery knows about
  it (since the thread state is being deleted, continuing to remember it
  can't help, but can hurt if another thread happens to get created with
  the same thread id).

Extension Modules
-----------------

- Patch #1380952: fix SSL objects timing out on consecutive read()s

- Patch #1309579: wait3 and wait4 were added to the posix module.

- Patch #1231053: The audioop module now supports encoding/decoding of alaw.
  In addition, the existing ulaw code was updated.

- RFE #567972: Socket objects' family, type and proto properties are
  now exposed via new attributes.

- Everything under lib-old was removed.  This includes the following modules:
    Para, addpack, cmp, cmpcache, codehack, dircmp, dump, find, fmt, grep,
    lockfile, newdir, ni, packmail, poly, rand, statcache, tb, tzparse,
    util, whatsound, whrandom, zmod

- The following modules were removed:  regsub, reconvert, regex, regex_syntax.

- re and sre were swapped, so help(re) provides full help.  importing sre
  is deprecated.  The undocumented re.engine variable no longer exists.

- Bug #1448490: Fixed a bug that ISO-2022 codecs could not handle
  SS2 (single-shift 2) escape sequences correctly.

- The unicodedata module was updated to the 4.1 version of the Unicode
  database. The 3.2 version is still available as unicodedata.db_3_2_0
  for applications that require this specific version (such as IDNA).

- The timing module is no longer built by default.  It was deprecated
  in PEP 4 in Python 2.0 or earlier.

- Patch 1433928: Added a new type, defaultdict, to the collections module.
  This uses the new __missing__ hook behavior added to dict (see above).

- Bug #854823: socketmodule now builds on Sun platforms even when
  INET_ADDRSTRLEN is not defined.

- Patch #1393157: os.startfile() now has an optional argument to specify
  a "command verb" to invoke on the file.

- Bug #876637, prevent stack corruption when socket descriptor
  is larger than FD_SETSIZE.

- Patch #1407135, bug #1424041: harmonize mmap behavior of anonymous memory.
  mmap.mmap(-1, size) now returns anonymous memory in both Unix and Windows.
  mmap.mmap(0, size) should not be used on Windows for anonymous memory.

- Patch #1422385: The nis module now supports access to domains other
  than the system default domain.

- Use Win32 API to implement os.stat/fstat. As a result, subsecond timestamps
  are reported, the limit on path name lengths is removed, and stat reports
  WindowsError now (instead of OSError).

- Add bsddb.db.DBEnv.set_tx_timestamp allowing time based database recovery.

- Bug #1413192, fix seg fault in bsddb if a transaction was deleted
  before the env.

- Patch #1103116: Basic AF_NETLINK support.

- Bug #1402308, (possible) segfault when using mmap.mmap(-1, ...)

- Bug #1400822, _curses over{lay,write} doesn't work when passing 6 ints.
  Also fix ungetmouse() which did not accept arguments properly.
  The code now conforms to the documented signature.

- Bug #1400115, Fix segfault when calling curses.panel.userptr()
  without prior setting of the userptr.

- Fix 64-bit problems in bsddb.

- Patch #1365916: fix some unsafe 64-bit mmap methods.

- Bug #1290333: Added a workaround for cjkcodecs' _codecs_cn build
  problem on AIX.

- Bug #869197: os.setgroups rejects long integer arguments

- Bug #1346533, select.poll() doesn't raise an error if timeout > sys.maxint

- Bug #1344508, Fix UNIX mmap leaking file descriptors

- Patch #1338314, Bug #1336623: fix tarfile so it can extract
  REGTYPE directories from tarfiles written by old programs.

- Patch #1407992, fixes broken bsddb module db associate when using
  BerkeleyDB 3.3, 4.0 or 4.1.

- Get bsddb module to build with BerkeleyDB version 4.4

- Get bsddb module to build with BerkeleyDB version 3.2

- Patch #1309009, Fix segfault in pyexpat when the XML document is in latin_1,
  but Python incorrectly assumes it is in UTF-8 format

- Fix parse errors in the readline module when compiling without threads.

- Patch #1288833: Removed thread lock from socket.getaddrinfo on
  FreeBSD 5.3 and later versions which got thread-safe getaddrinfo(3).

- Patches #1298449 and #1298499: Add some missing checks for error
  returns in cStringIO.c.

- Patch #1297028: fix segfault if call type on MultibyteCodec,
  MultibyteStreamReader, or MultibyteStreamWriter

- Fix memory leak in posix.access().

- Patch #1213831: Fix typo in unicodedata._getcode.

- Bug #1007046: os.startfile() did not accept unicode strings encoded in
  the file system encoding.

- Patch #756021: Special-case socket.inet_aton('255.255.255.255') for
  platforms that don't have inet_aton().

- Bug #1215928: Fix bz2.BZ2File.seek() for 64-bit file offsets.

- Bug #1191043: Fix bz2.BZ2File.(x)readlines for files containing one
  line without newlines.

- Bug #728515: mmap.resize() now resizes the file on Unix as it did
  on Windows.

- Patch #1180695: Add nanosecond stat resolution, and st_gen,
  st_birthtime for FreeBSD.

- Patch #1231069: The fcntl.ioctl function now uses the 'I' code for
  the request code argument, which results in more C-like behaviour
  for large or negative values.

- Bug #1234979: For the argument of thread.Lock.acquire, the Windows
  implementation treated all integer values except 1 as false.

- Bug #1194181: bz2.BZ2File didn't handle mode 'U' correctly.

- Patch #1212117: os.stat().st_flags is now accessible as an attribute
  if available on the platform.

- Patch #1103951: Expose O_SHLOCK and O_EXLOCK in the posix module if
  available on the platform.

- Bug #1166660: The readline module could segfault if hook functions
  were set in a different thread than that which called readline.

- collections.deque objects now support a remove() method.

- operator.itemgetter() and operator.attrgetter() now support retrieving
  multiple fields.  This provides direct support for sorting on multiple
  keys (primary, secondary, etc).

- os.access now supports Unicode path names on non-Win32 systems.

- Patches #925152, #1118602: Avoid reading after the end of the buffer
  in pyexpat.GetInputContext.

- Patches #749830, #1144555: allow UNIX mmap size to default to current
  file size.

- Added functional.partial().  See PEP309.

- Patch #1093585: raise a ValueError for negative history items in readline.
  {remove_history,replace_history}

- The spwd module has been added, allowing access to the shadow password
  database.

- stat_float_times is now True.

- array.array objects are now picklable.

- the cPickle module no longer accepts the deprecated None option in the
  args tuple returned by __reduce__().

- itertools.islice() now accepts None for the start and step arguments.
  This allows islice() to work more readily with slices:
      islice(s.start, s.stop, s.step)

- datetime.datetime() now has a strptime class method which can be used to
  create datetime object using a string and format.

- Patch #1117961: Replace the MD5 implementation from RSA Data Security Inc
  with the implementation from http://sourceforge.net/projects/libmd5-rfc/.

Library
-------

- Patch #1388073: Numerous __-prefixed attributes of unittest.TestCase have
  been renamed to have only a single underscore prefix.  This was done to
  make subclassing easier.

- PEP 338: new module runpy defines a run_module function to support
  executing modules which provide access to source code or a code object
  via the PEP 302 import mechanisms.

- The email module's parsedate_tz function now sets the daylight savings
  flag to -1 (unknown) since it can't tell from the date whether it should
  be set.

- Patch #624325: urlparse.urlparse() and urlparse.urlsplit() results
  now sport attributes that provide access to the parts of the result.

- Patch #1462498: sgmllib now handles entity and character references
  in attribute values.

- Added the sqlite3 package. This is based on pysqlite2.1.3, and provides
  a DB-API interface in the standard library. You'll need sqlite 3.0.8 or
  later to build this - if you have an earlier version, the C extension
  module will not be built.

- Bug #1460340: ``random.sample(dict)`` failed in various ways.  Dicts
  aren't officially supported here, and trying to use them will probably
  raise an exception some day.  But dicts have been allowed, and "mostly
  worked", so support for them won't go away without warning.

- Bug #1445068: getpass.getpass() can now be given an explicit stream
  argument to specify where to write the prompt.

- Patch #1462313, bug #1443328: the pickle modules now can handle classes
  that have __private names in their __slots__.

- Bug #1250170: mimetools now handles socket.gethostname() failures gracefully.

- patch #1457316: "setup.py upload" now supports --identity to select the
  key to be used for signing the uploaded code.

- Queue.Queue objects now support .task_done() and .join() methods
  to make it easier to monitor when daemon threads have completed
  processing all enqueued tasks.  Patch #1455676.

- popen2.Popen objects now preserve the command in a .cmd attribute.

- Added the ctypes ffi package.

- email 4.0 package now integrated.  This is largely the same as the email 3.0
  package that was included in Python 2.3, except that PEP 8 module names are
  now used (e.g. mail.message instead of email.Message).  The MIME classes
  have been moved to a subpackage (e.g. email.mime.text instead of
  email.MIMEText).  The old names are still supported for now.  Several
  deprecated Message methods have been removed and lots of bugs have been
  fixed.  More details can be found in the email package documentation.

- Patches #1436130/#1443155: codecs.lookup() now returns a CodecInfo object
  (a subclass of tuple) that provides incremental decoders and encoders
  (a way to use stateful codecs without the stream API). Python functions
  codecs.getincrementaldecoder() and codecs.getincrementalencoder() as well
  as C functions PyCodec_IncrementalEncoder() and PyCodec_IncrementalDecoder()
  have been added.

- Patch #1359365: Calling next() on a closed StringIO.String object raises
  a ValueError instead of a StopIteration now (like file and cString.String do).
  cStringIO.StringIO.isatty() will raise a ValueError now if close() has been
  called before (like file and StringIO.StringIO do).

- A regrtest option -w was added to re-run failed tests in verbose mode.

- Patch #1446372: quit and exit can now be called from the interactive
  interpreter to exit.

- The function get_count() has been added to the gc module, and gc.collect()
  grew an optional 'generation' argument.

- A library msilib to generate Windows Installer files, and a distutils
  command bdist_msi have been added.

- PEP 343: new module contextlib.py defines decorator @contextmanager
  and helpful context managers nested() and closing().

- The compiler package now supports future imports after the module docstring.

- Bug #1413790: zipfile now sanitizes absolute archive names that are
  not allowed by the specs.

- Patch #1215184: FileInput now can be given an opening hook which can
  be used to control how files are opened.

- Patch #1212287: fileinput.input() now has a mode parameter for
  specifying the file mode input files should be opened with.

- Patch #1215184: fileinput now has a fileno() function for getting the
  current file number.

- Patch #1349274: gettext.install() now optionally installs additional
  translation functions other than _() in the builtins namespace.

- Patch #1337756: fileinput now accepts Unicode filenames.

- Patch #1373643: The chunk module can now read chunks larger than
  two gigabytes.

- Patch #1417555: SimpleHTTPServer now returns Last-Modified headers.

- Bug #1430298: It is now possible to send a mail with an empty
  return address using smtplib.

- Bug #1432260: The names of lambda functions are now properly displayed
  in pydoc.

- Patch #1412872: zipfile now sets the creator system to 3 (Unix)
  unless the system is Win32.

- Patch #1349118: urllib now supports user:pass@ style proxy
  specifications, raises IOErrors when proxies for unsupported protocols
  are defined, and uses the https proxy on https redirections.

- Bug #902075: urllib2 now supports 'host:port' style proxy specifications.

- Bug #1407902: Add support for sftp:// URIs to urlparse.

- Bug #1371247: Update Windows locale identifiers in locale.py.

- Bug #1394565: SimpleHTTPServer now doesn't choke on query parameters
  any more.

- Bug #1403410: The warnings module now doesn't get confused
  when it can't find out the module name it generates a warning for.

- Patch #1177307: Added a new codec utf_8_sig for UTF-8 with a BOM signature.

- Patch #1157027: cookielib mishandles RFC 2109 cookies in Netscape mode

- Patch #1117398: cookielib.LWPCookieJar and .MozillaCookieJar now raise
  LoadError as documented, instead of IOError.  For compatibility,
  LoadError subclasses IOError.

- Added the hashlib module.  It provides secure hash functions for MD5 and
  SHA1, 224, 256, 384, and 512.  Note that recent developments make the
  historic MD5 and SHA1 unsuitable for cryptographic-strength applications.
  In <http://mail.python.org/pipermail/python-dev/2005-December/058850.html>
  Ronald L. Rivest offered this advice for Python:

      "The consensus of researchers in this area (at least as
      expressed at the NIST Hash Function Workshop 10/31/05),
      is that SHA-256 is a good choice for the time being, but
      that research should continue, and other alternatives may
      arise from this research.  The larger SHA's also seem OK."

- Added a subset of Fredrik Lundh's ElementTree package.  Available
  modules are xml.etree.ElementTree, xml.etree.ElementPath, and
  xml.etree.ElementInclude, from ElementTree 1.2.6.

- Patch #1162825: Support non-ASCII characters in IDLE window titles.

- Bug #1365984: urllib now opens "data:" URLs again.

- Patch #1314396: prevent deadlock for threading.Thread.join() when an exception
  is raised within the method itself on a previous call (e.g., passing in an
  illegal argument)

- Bug #1340337: change time.strptime() to always return ValueError when there
  is an error in the format string.

- Patch #754022: Greatly enhanced webbrowser.py (by Oleg Broytmann).

- Bug #729103: pydoc.py: Fix docother() method to accept additional
  "parent" argument.

- Patch #1300515: xdrlib.py: Fix pack_fstring() to really use null bytes
  for padding.

- Bug #1296004: httplib.py: Limit maximal amount of data read from the
  socket to avoid a MemoryError on Windows.

- Patch #1166948: locale.py: Prefer LC_ALL, LC_CTYPE and LANG over LANGUAGE
  to get the correct encoding.

- Patch #1166938: locale.py: Parse LANGUAGE as a colon separated list of
  languages.

- Patch #1268314: Cache lines in StreamReader.readlines for performance.

- Bug #1290505: Fix clearing the regex cache for time.strptime().

- Bug #1167128: Fix size of a symlink in a tarfile to be 0.

- Patch #810023: Fix off-by-one bug in urllib.urlretrieve reporthook
  functionality.

- Bug #1163178: Make IDNA return an empty string when the input is empty.

- Patch #848017: Make Cookie more RFC-compliant. Use CRLF as default output
  separator and do not output trailing semicolon.

- Patch #1062060: urllib.urlretrieve() now raises a new exception, named
  ContentTooShortException, when the actually downloaded size does not
  match the Content-Length header.

- Bug #1121494: distutils.dir_utils.mkpath now accepts Unicode strings.

- Bug #1178484: Return complete lines from codec stream readers
  even if there is an exception in later lines, resulting in
  correct line numbers for decoding errors in source code.

- Bug #1192315: Disallow negative arguments to clear() in pdb.

- Patch #827386: Support absolute source paths in msvccompiler.py.

- Patch #1105730: Apply the new implementation of commonprefix in posixpath
  to ntpath, macpath, os2emxpath and riscospath.

- Fix a problem in Tkinter introduced by SF patch #869468: delete bogus
  __hasattr__ and __delattr__ methods on class Tk that were breaking
  Tkdnd.

- Bug #1015140: disambiguated the term "article id" in nntplib docs and
  docstrings to either "article number" or "message id".

- Bug #1238170: threading.Thread.__init__ no longer has "kwargs={}" as a
  parameter, but uses the usual "kwargs=None".

- textwrap now processes text chunks at O(n) speed instead of O(n**2).
  Patch #1209527 (Contributed by Connelly).

- urllib2 has now an attribute 'httpresponses' mapping from HTTP status code
  to W3C name (404 -> 'Not Found'). RFE #1216944.

- Bug #1177468: Don't cache the /dev/urandom file descriptor for os.urandom,
  as this can cause problems with apps closing all file descriptors.

- Bug #839151: Fix an attempt to access sys.argv in the warnings module;
  it can be missing in embedded interpreters

- Bug #1155638: Fix a bug which affected HTTP 0.9 responses in httplib.

- Bug #1100201: Cross-site scripting was possible on BaseHTTPServer via
  error messages.

- Bug #1108948: Cookie.py produced invalid JavaScript code.

- The tokenize module now detects and reports indentation errors.
  Bug #1224621.

- The tokenize module has a new untokenize() function to support a full
  roundtrip from lexed tokens back to Python source code.  In addition,
  the generate_tokens() function now accepts a callable argument that
  terminates by raising StopIteration.

- Bug #1196315: fix weakref.WeakValueDictionary constructor.

- Bug #1213894: os.path.realpath didn't resolve symlinks that were the first
  component of the path.

- Patch #1120353: The xmlrpclib module provides better, more transparent,
  support for datetime.{datetime,date,time} objects.  With use_datetime set
  to True, applications shouldn't have to fiddle with the DateTime wrapper
  class at all.

- distutils.commands.upload was added to support uploading distribution
  files to PyPI.

- distutils.commands.register now encodes the data as UTF-8 before posting
  them to PyPI.

- decimal operator and comparison methods now return NotImplemented
  instead of raising a TypeError when interacting with other types.  This
  allows other classes to implement __radd__ style methods and have them
  work as expected.

- Bug #1163325:  Decimal infinities failed to hash.  Attempting to
  hash a NaN raised an InvalidOperation instead of a TypeError.

- Patch #918101: Add tarfile open mode r|* for auto-detection of the
  stream compression; add, for symmetry reasons, r:* as a synonym of r.

- Patch #1043890: Add extractall method to tarfile.

- Patch #1075887: Don't require MSVC in distutils if there is nothing
  to build.

- Patch #1103407: Properly deal with tarfile iterators when untarring
  symbolic links on Windows.

- Patch #645894: Use getrusage for computing the time consumption in
  profile.py if available.

- Patch #1046831: Use get_python_version where appropriate in sysconfig.py.

- Patch #1117454: Remove code to special-case cookies without values
  in LWPCookieJar.

- Patch #1117339: Add cookielib special name tests.

- Patch #1112812: Make bsddb/__init__.py more friendly for modulefinder.

- Patch #1110248: SYNC_FLUSH the zlib buffer for GZipFile.flush.

- Patch #1107973: Allow iterating over the lines of a tarfile.ExFileObject.

- Patch #1104111: Alter setup.py --help and --help-commands.

- Patch #1121234: Properly cleanup _exit and tkerror commands.

- Patch #1049151: xdrlib now unpacks booleans as True or False.

- Fixed bug in a NameError bug in cookielib.  Patch #1116583.

- Applied a security fix to SimpleXMLRPCserver (PSF-2005-001).  This
  disables recursive traversal through instance attributes, which can
  be exploited in various ways.

- Bug #1222790: in SimpleXMLRPCServer, set the reuse-address and close-on-exec
  flags on the HTTP listening socket.

- Bug #792570: SimpleXMLRPCServer had problems if the request grew too large.
  Fixed by reading the HTTP body in chunks instead of one big socket.read().

- Patches #893642, #1039083: add allow_none, encoding arguments to
  constructors of SimpleXMLRPCServer and CGIXMLRPCRequestHandler.

- Bug #1110478: Revert os.environ.update to do putenv again.

- Bug #1103844: fix distutils.install.dump_dirs() with negated options.

- os.{SEEK_SET, SEEK_CUR, SEEK_END} have been added for convenience.

- Enhancements to the csv module:

  + Dialects are now validated by the underlying C code, better
    reflecting its capabilities, and improving its compliance with
    PEP 305.
  + Dialect parameter parsing has been re-implemented to improve error
    reporting.
  + quotechar=None and quoting=QUOTE_NONE now work the way PEP 305
    dictates.
  + the parser now removes the escapechar prefix from escaped characters.
  + when quoting=QUOTE_NONNUMERIC, the writer now tests for numeric
    types, rather than any object that can be represented as a numeric.
  + when quoting=QUOTE_NONNUMERIC, the reader now casts unquoted fields
    to floats.
  + reader now allows \r characters to be quoted (previously it only allowed
    \n to be quoted).
  + writer doublequote handling improved.
  + Dialect classes passed to the module are no longer instantiated by
    the module before being parsed (the former validation scheme required
    this, but the mechanism was unreliable).
  + The dialect registry now contains instances of the internal
    C-coded dialect type, rather than references to python objects.
  + the internal c-coded dialect type is now immutable.
  + register_dialect now accepts the same keyword dialect specifications
    as the reader and writer, allowing the user to register dialects
    without first creating a dialect class.
  + a configurable limit to the size of parsed fields has been added -
    previously, an unmatched quote character could result in the entire
    file being read into the field buffer before an error was reported.
  + A new module method csv.field_size_limit() has been added that sets
    the parser field size limit (returning the former limit). The initial
    limit is 128kB.
  + A line_num attribute has been added to the reader object, which tracks
    the number of lines read from the source iterator. This is not
    the same as the number of records returned, as records can span
    multiple lines.
  + reader and writer objects were not being registered with the cyclic-GC.
    This has been fixed.

- _DummyThread objects in the threading module now delete self.__block that is
  inherited from _Thread since it uses up a lock allocated by 'thread'.  The
  lock primitives tend to be limited in number and thus should not be wasted on
  a _DummyThread object.  Fixes bug #1089632.

- The imghdr module now detects Exif files.

- StringIO.truncate() now correctly adjusts the size attribute.
  (Bug #951915).

- locale.py now uses an updated locale alias table (built using
  Tools/i18n/makelocalealias.py, a tool to parse the X11 locale
  alias file); the encoding lookup was enhanced to use Python's
  encoding alias table.

- moved deprecated modules to Lib/lib-old:  whrandom, tzparse, statcache.

- the pickle module no longer accepts the deprecated None option in the
  args tuple returned by __reduce__().

- optparse now optionally imports gettext.  This allows its use in setup.py.

- the pickle module no longer uses the deprecated bin parameter.

- the shelve module no longer uses the deprecated binary parameter.

- the pstats module no longer uses the deprecated ignore() method.

- the filecmp module no longer uses the deprecated use_statcache argument.

- unittest.TestCase.run() and unittest.TestSuite.run() can now be successfully
  extended or overridden by subclasses.  Formerly, the subclassed method would
  be ignored by the rest of the module.  (Bug #1078905).

- heapq.nsmallest() and heapq.nlargest() now support key= arguments with
  the same meaning as in list.sort().

- Bug #1076985: ``codecs.StreamReader.readline()`` now calls ``read()`` only
  once when a size argument is given. This prevents a buffer overflow in the
  tokenizer with very long source lines.

- Bug #1083110: ``zlib.decompress.flush()`` would segfault if called
  immediately after creating the object, without any intervening
  ``.decompress()`` calls.

- The reconvert.quote function can now emit triple-quoted strings.  The
  reconvert module now has some simple documentation.

- ``UserString.MutableString`` now supports negative indices in
  ``__setitem__`` and ``__delitem__``

- Bug #1149508: ``textwrap`` now handles hyphenated numbers (eg. "2004-03-05")
  correctly.

- Partial fixes for SF bugs #1163244 and #1175396: If a chunk read by
  ``codecs.StreamReader.readline()`` has a trailing "\r", read one more
  character even if the user has passed a size parameter to get a proper
  line ending. Remove the special handling of a "\r\n" that has been split
  between two lines.

- Bug #1251300: On UCS-4 builds the "unicode-internal" codec will now complain
  about illegal code points. The codec now supports PEP 293 style error
  handlers.

- Bug #1235646: ``codecs.StreamRecoder.next()`` now reencodes the data it reads
  from the input stream, so that the output is a byte string in the correct
  encoding instead of a unicode string.

- Bug #1202493: Fixing SRE parser to handle '{}' as perl does, rather than
  considering it exactly like a '*'.

- Bug #1245379: Add "unicode-1-1-utf-7" as an alias for "utf-7" to
  ``encodings.aliases``.

- ` uu.encode()`` and ``uu.decode()`` now support unicode filenames.

- Patch #1413711: Certain patterns of differences were making difflib
  touch the recursion limit.

- Bug #947906: An object oriented interface has been added to the calendar
  module. It's possible to generate HTML calendar now and the module can be
  called as a script (e.g. via ``python -mcalendar``). Localized month and
  weekday names can be output (even if an exotic encoding is used) using
  special classes that use unicode.

Build
-----

- Fix test_float, test_long, and test_struct failures on Tru64 with gcc
  by using -mieee gcc option.

- Patch #1432345: Make python compile on DragonFly.

- Build support for Win64-AMD64 was added.

- Patch #1428494: Prefer linking against ncursesw over ncurses library.

- Patch #881820: look for openpty and forkpty also in libbsd.

- The sources of zlib are now part of the Python distribution (zlib 1.2.3).
  The zlib module is now built in on Windows.

- Use -xcode=pic32 for CCSHARED on Solaris with SunPro.

- Bug #1189330: configure did not correctly determine the necessary
  value of LINKCC if python was built with GCC 4.0.

- Upgrade Windows build to zlib 1.2.3 which eliminates a potential security
  vulnerability in zlib 1.2.1 and 1.2.2.

- EXTRA_CFLAGS has been introduced as an environment variable to hold compiler
  flags that change binary compatibility.  Changes were also made to
  distutils.sysconfig to also use the environment variable when used during
  compilation of the interpreter and of C extensions through distutils.

- SF patch 1171735: Darwin 8's headers are anal about POSIX compliance,
  and linking has changed (prebinding is now deprecated, and libcc_dynamic
  no longer exists). This configure patch makes things right.

- Bug #1158607: Build with --disable-unicode again.

- spwdmodule.c is built only if either HAVE_GETSPNAM or HAVE_HAVE_GETSPENT is
  defined.  Discovered as a result of not being able to build on OS X.

- setup.py now uses the directories specified in LDFLAGS using the -L option
  and in CPPFLAGS using the -I option for adding library and include
  directories, respectively, for compiling extension modules against.  This has
  led to the core being compiled using the values in CPPFLAGS.  It also removes
  the need for the special-casing of both DarwinPorts and Fink for darwin since
  the proper directories can be specified in LDFLAGS (``-L/sw/lib`` for Fink,
  ``-L/opt/local/lib`` for DarwinPorts) and CPPFLAGS (``-I/sw/include`` for
  Fink, ``-I/opt/local/include`` for DarwinPorts).

- Test in configure.in that checks for tzset no longer dependent on tm->tm_zone
  to exist in the struct (not required by either ISO C nor the UNIX 2 spec).
  Tests for sanity in tzname when HAVE_TZNAME defined were also defined.
  Closes bug #1096244.  Thanks Gregory Bond.

C API
-----

- ``PyMem_{Del, DEL}`` and ``PyMem_{Free, FREE}`` no longer map to
  ``PyObject_{Free, FREE}``.  They map to the system ``free()`` now.  If memory
  is obtained via the ``PyObject_`` family, it must be released via the
  ``PyObject_`` family, and likewise for the ``PyMem_`` family.  This has
  always been officially true, but when Python's small-object allocator was
  introduced, an attempt was made to cater to a few extension modules
  discovered at the time that obtained memory via ``PyObject_New`` but
  released it via ``PyMem_DEL``.  It's years later, and if such code still
  exists it will fail now (probably with segfaults, but calling wrong
  low-level memory management functions can yield many symptoms).

- Added a C API for set and frozenset objects.

- Removed PyRange_New().

- Patch #1313939: PyUnicode_DecodeCharmap() accepts a unicode string as the
  mapping argument now. This string is used as a mapping table. Byte values
  greater than the length of the string and 0xFFFE are treated as undefined
  mappings.


Tests
-----

- In test_os, st_?time is now truncated before comparing it with ST_?TIME.

- Patch #1276356: New resource "urlfetch" is implemented.  This enables
  even impatient people to run tests that require remote files.


Documentation
-------------

- Bug #1402224: Add warning to dl docs about crashes.

- Bug #1396471: Document that Windows' ftell() can return invalid
  values for text files with UNIX-style line endings.

- Bug #1274828: Document os.path.splitunc().

- Bug #1190204: Clarify which directories are searched by site.py.

- Bug #1193849: Clarify os.path.expanduser() documentation.

- Bug #1243192: re.UNICODE and re.LOCALE affect \d, \D, \s and \S.

- Bug #755617: Document the effects of os.chown() on Windows.

- Patch #1180012: The documentation for modulefinder is now in the library reference.

- Patch #1213031: Document that os.chown() accepts argument values of -1.

- Bug #1190563: Document os.waitpid() return value with WNOHANG flag.

- Bug #1175022: Correct the example code for property().

- Document the IterableUserDict class in the UserDict module.
  Closes bug #1166582.

- Remove all latent references for "Macintosh" that referred to semantics for
  Mac OS 9 and change to reflect the state for OS X.
  Closes patch #1095802.  Thanks Jack Jansen.

Mac
---


New platforms
-------------

- FreeBSD 7 support is added.


Tools/Demos
-----------

- Created Misc/Vim/vim_syntax.py to auto-generate a python.vim file in that
  directory for syntax highlighting in Vim.  Vim directory was added and placed
  vimrc to it (was previous up a level).

- Added two new files to Tools/scripts: pysource.py, which recursively
  finds Python source files, and findnocoding.py, which finds Python
  source files that need an encoding declaration.
  Patch #784089, credits to Oleg Broytmann.

- Bug #1072853: pindent.py used an uninitialized variable.

- Patch #1177597: Correct Complex.__init__.

- Fixed a display glitch in Pynche, which could cause the right arrow to
  wiggle over by a pixel.


What's New in Python 2.4 final?
===============================

*Release date: 30-NOV-2004*

Core and builtins
-----------------

- Bug 875692: Improve signal handling, especially when using threads, by
  forcing an early re-execution of PyEval_EvalFrame() "periodic" code when
  things_to_do is not cleared by Py_MakePendingCalls().


What's New in Python 2.4 (release candidate 1)
==============================================

*Release date: 18-NOV-2004*

Core and builtins
-----------------

- Bug 1061968:  Fixes in 2.4a3 to address thread bug 1010677 reintroduced
  the years-old thread shutdown race bug 225673.  Numeric history lesson
  aside, all bugs in all three reports are fixed now.


Library
-------

- Bug 1052242: If exceptions are raised by an atexit handler function an
  attempt is made to execute the remaining handlers.  The last exception
  raised is re-raised.

- ``doctest``'s new support for adding ``pdb.set_trace()`` calls to
  doctests was broken in a dramatic but shallow way.  Fixed.

- Bug 1065388:  ``calendar``'s ``day_name``, ``day_abbr``, ``month_name``,
  and ``month_abbr`` attributes emulate sequences of locale-correct
  spellings of month and day names.  Because the locale can change at
  any time, the correct spelling is recomputed whenever one of these is
  indexed.  In the worst case, the index may be a slice object, so these
  recomputed every day or month name each time they were indexed.  This is
  much slower than necessary in the usual case, when the index is just an
  integer.  In that case, only the single spelling needed is recomputed
  now; and, when the index is a slice object, only the spellings needed
  by the slice are recomputed now.

- Patch 1061679: Added ``__all__`` to pickletools.py.

Build
-----

- Bug 1034277 / Patch 1035255: Remove compilation of core against CoreServices
  and CoreFoundation on OS X.  Involved removing PyMac_GetAppletScriptFile()
  which has no known users.  Thanks Bob Ippolito.

C API
-----

- The PyRange_New() function is deprecated.


What's New in Python 2.4 beta 2?
================================

*Release date: 03-NOV-2004*

License
-------

The Python Software Foundation changed the license under which Python
is released, to remove Python version numbers.  There were no other
changes to the license.  So, for example, wherever the license for
Python 2.3 said "Python 2.3", the new license says "Python".  The
intent is to make it possible to refer to the PSF license in a more
durable way.  For example, some people say they're confused by that
the Open Source Initiative's entry for the Python Software Foundation
License::

      http://www.opensource.org/licenses/PythonSoftFoundation.php

says "Python 2.1.1" all over it, wondering whether it applies only
to Python 2.1.1.

The official name of the new license is the Python Software Foundation
License Version 2.

Core and builtins
-----------------

- Bug #1055820 Cyclic garbage collection was not protecting against that
  calling a live weakref to a piece of cyclic trash could resurrect an
  insane mutation of the trash if any Python code ran during gc (via
  running a dead object's __del__ method, running another callback on a
  weakref to a dead object, or via any Python code run in any other thread
  that managed to obtain the GIL while a __del__ or callback was running
  in the thread doing gc).  The most likely symptom was "impossible"
  ``AttributeError`` exceptions, appearing seemingly at random, on weakly
  referenced objects.  The cure was to clear all weakrefs to unreachable
  objects before allowing any callbacks to run.

- Bug #1054139 _PyString_Resize() now invalidates its cached hash value.

Extension Modules
-----------------

- Bug #1048870:  the compiler now generates distinct code objects for
  functions with identical bodies.  This was producing confusing
  traceback messages which pointed to the function where the code
  object was first defined rather than the function being executed.

Library
-------

- Patch #1056967 changes the semantics of Template.safe_substitute() so that
  no ValueError is raised on an 'invalid' match group.  Now the delimiter is
  returned.

- Bug #1052503 pdb.runcall() was not passing along keyword arguments.

- Bug #902037: XML.sax.saxutils.prepare_input_source() now combines relative
  paths with a base path before checking os.path.isfile().

- The whichdb module can now be run from the command line.

- Bug #1045381: time.strptime() can now infer the date using %U or %W (week of
  the year) when the day of the week and year are also specified.

- Bug #1048816: fix bug in Ctrl-K at start of line in curses.textpad.Textbox

- Bug #1017553: fix bug in tarfile.filemode()

- Patch #737473: fix bug that old source code is shown in tracebacks even if
  the source code is updated and reloaded.

Build
-----

- Patch #1044395: --enable-shared is allowed in FreeBSD also.

What's New in Python 2.4 beta 1?
================================

*Release date: 15-OCT-2004*

Core and builtins
-----------------

- Patch #975056: Restartable signals were not correctly disabled on
  BSD systems. Consistently use PyOS_setsig() instead of signal().

- The internal portable implementation of thread-local storage (TLS), used
  by the ``PyGILState_Ensure()``/``PyGILState_Release()`` API, was not
  thread-correct.  This could lead to a variety of problems, up to and
  including segfaults.  See bug 1041645 for an example.

- Added a command line option, -m module, which searches sys.path for the
  module and then runs it.  (Contributed by Nick Coghlan.)

- The bytecode optimizer now folds tuples of constants into a single
  constant.

- SF bug #513866:  Float/long comparison anomaly.  Prior to 2.4b1, when
  an integer was compared to a float, the integer was coerced to a float.
  That could yield spurious overflow errors (if the integer was very
  large), and to anomalies such as
  ``long(1e200)+1 == 1e200 == long(1e200)-1``.  Coercion to float is no
  longer performed, and cases like ``long(1e200)-1 < 1e200``,
  ``long(1e200)+1 > 1e200`` and ``(1 << 20000) > 1e200`` are computed
  correctly now.

Extension modules
-----------------

- ``collections.deque`` objects didn't play quite right with garbage
  collection, which could lead to a segfault in a release build, or
  an assert failure in a debug build.  Also, added overflow checks,
  better detection of mutation during iteration, and shielded deque
  comparisons from unusual subclass overrides of the __iter__() method.

Library
-------

- Patch 1046644: distutils build_ext grew two new options - --swig for
  specifying the swig executable to use, and --swig-opts to specify
  options to pass to swig. --swig-opts="-c++" is the new way to spell
  --swig-cpp.

- Patch 983206: distutils now obeys environment variable LDSHARED, if
  it is set.

- Added Peter Astrand's subprocess.py module.  See PEP 324 for details.

- time.strptime() now properly escapes timezones and all other locale-specific
  strings for regex-specific symbols.  Was breaking under Japanese Windows when
  the timezone was specified as "Tokyo (standard time)".
  Closes bug #1039270.

- Updates for the email package:

  + email.Utils.formatdate() grew a 'usegmt' argument for HTTP support.
  + All deprecated APIs that in email 2.x issued warnings have been removed:
    _encoder argument to the MIMEText constructor, Message.add_payload(),
    Utils.dump_address_pair(), Utils.decode(), Utils.encode()
  + New deprecations: Generator.__call__(), Message.get_type(),
    Message.get_main_type(), Message.get_subtype(), the 'strict' argument to
    the Parser constructor.  These will be removed in email 3.1.
  + Support for Python earlier than 2.3 has been removed (see PEP 291).
  + All defect classes have been renamed to end in 'Defect'.
  + Some FeedParser fixes; also a MultipartInvariantViolationDefect will be
    added to messages that claim to be multipart but really aren't.
  + Updates to documentation.

- re's findall() and finditer() functions now take an optional flags argument
  just like the compile(), search(), and match() functions.  Also, documented
  the previously existing start and stop parameters for the findall() and
  finditer() methods of regular expression objects.

- rfc822 Messages now support iterating over the headers.

- The (undocumented) tarfile.Tarfile.membernames has been removed;
  applications should use the getmember function.

- httplib now offers symbolic constants for the HTTP status codes.

- SF bug #1028306:  Trying to compare a ``datetime.date`` to a
  ``datetime.datetime`` mistakenly compared only the year, month and day.
  Now it acts like a mixed-type comparison:  ``False`` for ``==``,
  ``True`` for ``!=``, and raises ``TypeError`` for other comparison
  operators.  Because datetime is a subclass of date, comparing only the
  base class (date) members can still be done, if that's desired, by
  forcing using of the appropriate date method; e.g.,
  ``a_date.__eq__(a_datetime)`` is true if and only if the year, month
  and day members of ``a_date`` and ``a_datetime`` are equal.

- bdist_rpm now supports command line options --force-arch,
  {pre,post}-install,  {pre,post}-uninstall, and
  {prep,build,install,clean,verify}-script.

- SF patch #998993: The UTF-8 and the UTF-16 stateful decoders now support
  decoding incomplete input (when the input stream is temporarily exhausted).
  ``codecs.StreamReader`` now implements buffering, which enables proper
  readline support for the UTF-16 decoders. ``codecs.StreamReader.read()``
  has a new argument ``chars`` which specifies the number of characters to
  return. ``codecs.StreamReader.readline()`` and
  ``codecs.StreamReader.readlines()`` have a new argument ``keepends``.
  Trailing "\n"s will be stripped from the lines if ``keepends`` is false.

- The documentation for doctest is greatly expanded, and now covers all
  the new public features (of which there are many).

- ``doctest.master`` was put back in, and ``doctest.testmod()`` once again
  updates it.  This isn't good, because every ``testmod()`` call
  contributes to bloating the "hidden" state of ``doctest.master``, but
  some old code apparently relies on it.  For now, all we can do is
  encourage people to stitch doctests together via doctest's unittest
  integration features instead.

- httplib now handles ipv6 address/port pairs.

- SF bug #1017864: ConfigParser now correctly handles default keys,
  processing them with ``ConfigParser.optionxform`` when supplied,
  consistent with the handling of config file entries and runtime-set
  options.

- SF bug #997050: Document, test, & check for non-string values in
  ConfigParser.  Moved the new string-only restriction added in
  rev. 1.65 to the SafeConfigParser class, leaving existing
  ConfigParser & RawConfigParser behavior alone, and documented the
  conditions under which non-string values work.

Build
-----

- Building on darwin now includes /opt/local/include and /opt/local/lib for
  building extension modules.  This is so as to include software installed as
  a DarwinPorts port <http://darwinports.opendarwin.org/>

- pyport.h now defines a Py_IS_NAN macro.  It works as-is when the
  platform C computes true for ``x != x`` if and only if X is a NaN.
  Other platforms can override the default definition with a platform-
  specific spelling in that platform's pyconfig.h.  You can also override
  pyport.h's default Py_IS_INFINITY definition now.

C API
-----

- SF patch 1044089:  New function ``PyEval_ThreadsInitialized()`` returns
  non-zero if PyEval_InitThreads() has been called.

- The undocumented and unused extern int ``_PyThread_Started`` was removed.

- The C API calls ``PyInterpreterState_New()`` and ``PyThreadState_New()``
  are two of the very few advertised as being safe to call without holding
  the GIL.  However, this wasn't true in a debug build, as bug 1041645
  demonstrated.  In a debug build, Python redirects the ``PyMem`` family
  of calls to Python's small-object allocator, to get the benefit of
  its extra debugging capabilities.  But Python's small-object allocator
  isn't threadsafe, relying on the GIL to avoid the expense of doing its
  own locking.  ``PyInterpreterState_New()`` and ``PyThreadState_New()``
  call the platform ``malloc()`` directly now, regardless of build type.

- PyLong_AsUnsignedLong[Mask] now support int objects as well.

- SF patch #998993: ``PyUnicode_DecodeUTF8Stateful`` and
  ``PyUnicode_DecodeUTF16Stateful`` have been added, which implement stateful
  decoding.

Tests
-----

- test__locale ported to unittest

Mac
---

- ``plistlib`` now supports non-dict root objects.  There is also a new
  interface for reading and writing plist files: ``readPlist(pathOrFile)``
  and ``writePlist(rootObject, pathOrFile)``

Tools/Demos
-----------

- The text file comparison scripts ``ndiff.py`` and ``diff.py`` now
  read the input files in universal-newline mode.  This spares them
  from consuming a great deal of time to deduce the useless result that,
  e.g., a file with Windows line ends and a file with Linux line ends
  have no lines in common.


What's New in Python 2.4 alpha 3?
=================================

*Release date: 02-SEP-2004*

Core and builtins
-----------------

- SF patch #1007189: ``from ... import ...`` statements now allow the name
  list to be surrounded by parentheses.

- Some speedups for long arithmetic, thanks to Trevor Perrin.  Gradeschool
  multiplication was sped a little by optimizing the C code.  Gradeschool
  squaring was sped by about a factor of 2, by exploiting that about half
  the digit products are duplicates in a square.  Because exponentiation
  uses squaring often, this also speeds long power.  For example, the time
  to compute 17**1000000 dropped from about 14 seconds to 9 on my box due
  to this much.  The cutoff for Karatsuba multiplication was raised,
  since gradeschool multiplication got quicker, and the cutoff was
  aggressively small regardless.  The exponentiation algorithm was switched
  from right-to-left to left-to-right, which is more efficient for small
  bases.  In addition, if the exponent is large, the algorithm now does
  5 bits (instead of 1 bit) at a time.  That cut the time to compute
  17**1000000 on my box in half again, down to about 4.5 seconds.

- OverflowWarning is no longer generated.  PEP 237 scheduled this to
  occur in Python 2.3, but since OverflowWarning was disabled by default,
  nobody realized it was still being generated.  On the chance that user
  code is still using them, the Python builtin OverflowWarning, and
  corresponding C API PyExc_OverflowWarning, will exist until Python 2.5.

- Py_InitializeEx has been added.

- Fix the order of application of decorators.  The proper order is bottom-up;
  the first decorator listed is the last one called.

- SF patch #1005778.  Fix a seg fault if the list size changed while
  calling list.index().  This could happen if a rich comparison function
  modified the list.

- The ``func_name`` (a.k.a. ``__name__``) attribute of user-defined
  functions is now writable.

- code_new (a.k.a new.code()) now checks its arguments sufficiently
  carefully that passing them on to PyCode_New() won't trigger calls
  to Py_FatalError() or PyErr_BadInternalCall().  It is still the case
  that the returned code object might be entirely insane.

- Subclasses of string can no longer be interned.  The semantics of
  interning were not clear here -- a subclass could be mutable, for
  example -- and had bugs.  Explicitly interning a subclass of string
  via intern() will raise a TypeError.  Internal operations that attempt
  to intern a string subclass will have no effect.

- Bug 1003935:  xrange() could report bogus OverflowErrors.  Documented
  what xrange() intends, and repaired tests accordingly.

Extension modules
-----------------

- difflib now supports HTML side-by-side diff.

- os.urandom has been added for systems that support sources of random
  data.

- Patch 1012740:  truncate() on a writeable cStringIO now resets the
  position to the end of the stream.  This is consistent with the original
  StringIO module and avoids inadvertently resurrecting data that was
  supposed to have been truncated away.

- Added socket.socketpair().

- Added CurrentByteIndex, CurrentColumnNumber, CurrentLineNumber
  members to xml.parsers.expat.XMLParser object.

- The mpz, rotor, and xreadlines modules, all deprecated in earlier
  versions of Python, have now been removed.

Library
-------

- Patch #934356: if a module defines __all__, believe that rather than using
  heuristics for filtering out imported names.

- Patch #941486: added os.path.lexists(), which returns True for broken
  symlinks, unlike os.path.exists().

- the random module now uses os.urandom() for seeding if it is available.
  Added a new generator based on os.urandom().

- difflib and diff.py can now generate HTML.

- bdist_rpm now includes version and release in the BuildRoot, and
  replaces - by ``_`` in version and release.

- distutils build/build_scripts now has an -e option to specify the
  path to the Python interpreter for installed scripts.

- PEP 292 classes Template and SafeTemplate are added to the string module.

- tarfile now generates GNU tar files by default.

- HTTPResponse has now a getheaders method.

- Patch #1006219: let inspect.getsource handle '@' decorators. Thanks Simon
  Percivall.

- logging.handlers.SMTPHandler.date_time has been removed;
  the class now uses email.Utils.formatdate to generate the time stamp.

- A new function tkFont.nametofont was added to return an existing
  font. The Font class constructor now has an additional exists argument
  which, if True, requests to return/configure an existing font, rather
  than creating a new one.

- Updated the decimal package's min() and max() methods to match the
  latest revision of the General Decimal Arithmetic Specification.
  Quiet NaNs are ignored and equal values are sorted based on sign
  and exponent.

- The decimal package's Context.copy() method now returns deep copies.

- Deprecated sys.exitfunc in favor of the atexit module.  The sys.exitfunc
  attribute will be kept around for backwards compatibility and atexit
  will just become the one preferred way to do it.

- patch #675551: Add get_history_item and replace_history_item functions
  to the readline module.

- bug #989672: pdb.doc and the help messages for the help_d and help_u methods
  of the pdb.Pdb class gives have been corrected. d(own) goes to a newer
  frame, u(p) to an older frame, not the other way around.

- bug #990669: os.path.realpath() will resolve symlinks before normalizing the
  path, as normalizing the path may alter the meaning of the path if it
  contains symlinks.

- bug #851123: shutil.copyfile will raise an exception when trying to copy a
  file onto a link to itself. Thanks Gregory Ball.

- bug #570300: Fix inspect to resolve file locations using os.path.realpath()
  so as to properly list all functions in a module when the module itself is
  reached through a symlink.  Thanks Johannes Gijsbers.

- doctest refactoring continued.  See the docs for details.  As part of
  this effort, some old and little- (never?) used features are now
  deprecated:  the Tester class, the module is_private() function, and the
  isprivate argument to testmod().  The Tester class supplied a feeble
  "by hand" way to combine multiple doctests, if you knew exactly what
  you were doing.  The newer doctest features for unittest integration
  already did a better job of that, are stronger now than ever, and the
  new DocTestRunner class is a saner foundation if you want to do it by
  hand.  The "private name" filtering gimmick was a mistake from the
  start, and testmod() changed long ago to ignore it by default.  If
  you want to filter out tests, the new DocTestFinder class can be used
  to return a list of all doctests, and you can filter that list by
  any computable criteria before passing it to a DocTestRunner instance.

- Bug #891637, patch #1005466: fix inspect.getargs() crash on def foo((bar)).

Tools/Demos
-----------

- IDLE's shortcut keys for windows are now case insensitive so that
  Control-V works the same as Control-v.

- pygettext.py: Generate POT-Creation-Date header in ISO format.

Build
-----

- Backward incompatibility:  longintrepr.h now triggers a compile-time
  error if SHIFT (the number of bits in a Python long "digit") isn't
  divisible by 5.  This new requirement allows simple code for the new
  5-bits-at-a-time long_pow() implementation.  If necessary, the
  restriction could be removed (by complicating long_pow(), or by
  falling back to the 1-bit-at-a-time algorithm), but there are no
  plans to do so.

- bug #991962: When building with --disable-toolbox-glue on Darwin no
  attempt to build Mac-specific modules occurs.

- The --with-tsc flag to configure to enable VM profiling with the
  processor's timestamp counter now works on PPC platforms.

- patch #1006629: Define _XOPEN_SOURCE to 500 on Solaris 8/9 to match
  GCC's definition and avoid redefinition warnings.

- Detect pthreads support (provided by gnu pth pthread emulation) on
  GNU/k*BSD systems.

- bug #1005737, #1007249: Fixed several build problems and warnings
  found on old/legacy C compilers of HP-UX, IRIX and Tru64.

C API
-----

..

Documentation
-------------

- patch #1005936, bug #1009373: fix index entries which contain
  an underscore when viewed with Acrobat.

- bug #990669: os.path.normpath may alter the meaning of a path if
  it contains symbolic links. This has been documented in a comment
  since 1992, but is now in the library reference as well.

New platforms
-------------

- FreeBSD 6 is now supported.

Tests
-----

..

Windows
-------

- Boosted the stack reservation for python.exe and pythonw.exe from
  the default 1MB to 2MB.  Stack frames under VC 7.1 for 2.4 are enough
  bigger than under VC 6.0 for 2.3.4 that deeply recursive progams
  within the default sys.getrecursionlimit() default value of 1000 were
  able to suffer undetected C stack overflows.  The standard test program
  test_compiler was one such program.  If a Python process on Windows
  "just vanishes" without a trace, and without an error message of any
  kind, but with an exit code of 128, undetected stack overflow may be
  the problem.

Mac
---

..


What's New in Python 2.4 alpha 2?
=================================

*Release date: 05-AUG-2004*

Core and builtins
-----------------

- Patch #980695:  Implements efficient string concatenation for statements
  of the form s=s+t and s+=t.  This will vary across implementations.
  Accordingly, the str.join() method is strongly preferred for performance
  sensitive code.

- PEP-0318, Function Decorators have been added to the language. These are
  implemented using the Java-style @decorator syntax, like so::

     @staticmethod
     def foo(bar):

  (The PEP needs to be updated to reflect the current state)

- When importing a module M raises an exception, Python no longer leaves M
  in sys.modules.  Before 2.4a2 it did, and a subsequent import of M would
  succeed, picking up a module object from sys.modules reflecting as much
  of the initialization of M as completed before the exception was raised.
  Subsequent imports got no indication that M was in a partially-
  initialized state, and the importers could get into arbitrarily bad
  trouble as a result (the M they got was in an unintended state,
  arbitrarily far removed from M's author's intent).  Now subsequent
  imports of M will continue raising exceptions (but if, for example, the
  source code for M is edited between import attempts, then perhaps later
  attempts will succeed, or raise a different exception).

  This can break existing code, but in such cases the code was probably
  working before by accident.  In the Python source, the only case of
  breakage discovered was in a test accidentally relying on a damaged
  module remaining in sys.modules.  Cases are also known where tests
  deliberately provoking import errors remove damaged modules from
  sys.modules themselves, and such tests will break now if they do an
  unconditional del sys.modules[M].

- u'%s' % obj will now try obj.__unicode__() first and fallback to
  obj.__str__() if no __unicode__ method can be found.

- Patch #550732: Add PyArg_VaParseTupleAndKeywords().  Analogous to
  PyArg_VaParse().  Both are now documented.  Thanks Greg Chapman.

- Allow string and unicode return types from .encode()/.decode()
  methods on string and unicode objects.  Added unicode.decode()
  which was missing for no apparent reason.

- An attempt to fix the mess that is Python's behaviour with
  signal handlers and threads, complicated by readline's behaviour.
  It's quite possible that there are still bugs here.

- Added C macros Py_CLEAR and Py_VISIT to ease the implementation of
  types that support garbage collection.

- Compiler now treats None as a constant.

- The type of values returned by __int__, __float__, __long__,
  __oct__, and __hex__ are now checked.  Returning an invalid type
  will cause a TypeError to be raised.  This matches the behavior of
  Jython.

- Implemented bind_textdomain_codeset() in locale module.

- Added a workaround for proper string operations in BSDs.  str.split
  and str.is* methods can now work correctly with UTF-8 locales.

- Bug #989185: unicode.iswide() and unicode.width() is dropped and
  the East Asian Width support is moved to unicodedata extension
  module.

- Patch #941229: The source code encoding in interactive mode
  now refers sys.stdin.encoding not just ISO-8859-1 anymore.  This
  allows for non-latin-1 users to write unicode strings directly.

Extension modules
-----------------

- cpickle now supports the same keyword arguments as pickle.

Library
-------

- Added new codecs and aliases for ISO_8859-11, ISO_8859-16 and
  TIS-620

- Thanks to Edward Loper, doctest has been massively refactored, and
  many new features were added.  Full docs will appear later.  For now
  the doctest module comments and new test cases give good coverage.
  The refactoring provides many hook points for customizing behavior
  (such as how to report errors, and how to compare expected to actual
  output).  New features include a <BLANKLINE> marker for expected
  output containing blank lines, options to produce unified or context
  diffs when actual output doesn't match expectations, an option to
  normalize whitespace before comparing, and an option to use an
  ellipsis to signify "don't care" regions of output.

- Tkinter now supports the wish -sync and -use options.

- The following methods in time support passing of None: ctime(), gmtime(),
  and localtime().  If None is provided, the current time is used (the
  same as when the argument is omitted).
  [SF bug 658254, patch 663482]

- nntplib does now allow ignoring a .netrc file.

- urllib2 now recognizes Basic authentication even if other authentication
  schemes are offered.

- Bug #1001053.  wave.open() now accepts unicode filenames.

- gzip.GzipFile has a new fileno() method, to retrieve the handle of the
  underlying file object (provided it has a fileno() method).  This is
  needed if you want to use os.fsync() on a GzipFile.

- imaplib has two new methods: deleteacl and myrights.

- nntplib has two new methods: description and descriptions. They
  use a more RFC-compliant way of getting a newsgroup description.

- Bug #993394.  Fix a possible red herring of KeyError in 'threading' being
  raised during interpreter shutdown from a registered function with atexit
  when dummy_threading is being used.

- Bug #857297/Patch #916874.  Fix an error when extracting a hard link
  from a tarfile.

- Patch #846659.  Fix an error in tarfile.py when using
  GNU longname/longlink creation.

- The obsolete FCNTL.py has been deleted.  The built-in fcntl module
  has been available (on platforms that support fcntl) since Python
  1.5a3, and all FCNTL.py did is export fcntl's names, after generating
  a deprecation warning telling you to use fcntl directly.

- Several new unicode codecs are added: big5hkscs, euc_jis_2004,
  iso2022_jp_2004, shift_jis_2004.

- Bug #788520.  Queue.{get, get_nowait, put, put_nowait} have new
  implementations, exploiting Conditions (which didn't exist at the time
  Queue was introduced).  A minor semantic change is that the Full and
  Empty exceptions raised by non-blocking calls now occur only if the
  queue truly was full or empty at the instant the queue was checked (of
  course the Queue may no longer be full or empty by the time a calling
  thread sees those exceptions, though).  Before, the exceptions could
  also be raised if it was "merely inconvenient" for the implementation
  to determine the true state of the Queue (because the Queue was locked
  by some other method in progress).

- Bugs #979794 and #980117: difflib.get_grouped_opcodes() now handles the
  case of comparing two empty lists.  This affected both context_diff() and
  unified_diff(),

- Bug #980938: smtplib now prints debug output to sys.stderr.

- Bug #930024: posixpath.realpath() now handles infinite loops in symlinks by
  returning the last point in the path that was not part of any loop.  Thanks
  AM Kuchling.

- Bug #980327: ntpath not handles compressing erroneous slashes between the
  drive letter and the rest of the path.  Also clearly handles UNC addresses now
  as well.  Thanks Paul Moore.

- bug #679953: zipfile.py should now work for files over 2 GB.  The packed data
  for file sizes (compressed and uncompressed) was being stored as signed
  instead of unsigned.

- decimal.py now only uses signals in the IBM spec.  The other conditions are
  no longer part of the public API.

- codecs module now has two new generic APIs: encode() and decode()
  which don't restrict the return types (unlike the unicode and
  string methods of the same name).

- Non-blocking SSL sockets work again; they were broken in Python 2.3.
  SF patch 945642.

- doctest unittest integration improvements:

  o Improved the unitest test output for doctest-based unit tests

  o Can now pass setUp and tearDown functions when creating
    DocTestSuites.

- The threading module has a new class, local, for creating objects
  that provide thread-local data.

- Bug #990307: when keep_empty_values is True, cgi.parse_qsl()
  no longer returns spurious empty fields.

- Implemented bind_textdomain_codeset() in gettext module.

- Introduced in gettext module the l*gettext() family of functions,
  which return translation strings encoded in the preferred encoding,
  as informed by locale module's getpreferredencoding().

- optparse module (and tests) upgraded to Optik 1.5a1.  Changes:

  - Add expansion of default values in help text: the string
    "%default" in an option's help string is expanded to str() of
    that option's default value, or "none" if no default value.

  - Bug #955889: option default values that happen to be strings are
    now processed in the same way as values from the command line; this
    allows generation of nicer help when using custom types.  Can
    be disabled with parser.set_process_default_values(False).

  - Bug #960515: don't crash when generating help for callback
    options that specify 'type', but not 'dest' or 'metavar'.

  - Feature #815264: change the default help format for short options
    that take an argument from e.g. "-oARG" to "-o ARG"; add
    set_short_opt_delimiter() and set_long_opt_delimiter() methods to
    HelpFormatter to allow (slight) customization of the formatting.

  - Patch #736940: internationalize Optik: all built-in user-
    targeted literal strings are passed through gettext.gettext().  (If
    you want translations (.po files), they're not included with Python
    -- you'll find them in the Optik source distribution from
    http://optik.sourceforge.net/ .)

  - Bug #878453: respect $COLUMNS environment variable for
    wrapping help output.

  - Feature #988122: expand "%prog" in the 'description' passed
    to OptionParser, just like in the 'usage' and 'version' strings.
    (This is *not* done in the 'description' passed to OptionGroup.)

C API
-----

- PyImport_ExecCodeModule() and PyImport_ExecCodeModuleEx():  if an
  error occurs while loading the module, these now delete the module's
  entry from sys.modules.  All ways of loading modules eventually call
  one of these, so this is an error-case change in semantics for all
  ways of loading modules.  In rare cases, a module loader may wish
  to keep a module object in sys.modules despite that the module's
  code cannot be executed.  In such cases, the module loader must
  arrange to reinsert the name and module object in sys.modules.
  PyImport_ReloadModule() has been changed to reinsert the original
  module object into sys.modules if the module reload fails, so that
  its visible semantics have not changed.

- A large pile of datetime field-extraction macros is now documented,
  thanks to Anthony Tuininga (patch #986010).

Documentation
-------------

- Improved the tutorial on creating types in C.

  - point out the importance of reassigning data members before
    assigning their values

  - correct my misconception about return values from visitprocs. Sigh.

  - mention the labor saving Py_VISIT and Py_CLEAR macros.

- Major rewrite of the math module docs, to address common confusions.

Tests
-----

- The test data files for the decimal test suite are now installed on
  platforms that use the Makefile.

- SF patch 995225:  The test file testtar.tar accidentally contained
  CVS keywords (like $Id$), which could cause spurious failures in
  test_tarfile.py depending on how the test file was checked out.


What's New in Python 2.4 alpha 1?
=================================

*Release date: 08-JUL-2004*

Core and builtins
-----------------

- weakref.ref is now the type object also known as
  weakref.ReferenceType; it can be subclassed like any other new-style
  class.  There's less per-entry overhead in WeakValueDictionary
  objects now (one object instead of three).

- Bug #951851: Python crashed when reading import table of certain
  Windows DLLs.

- Bug #215126.  The locals argument to eval(), execfile(), and exec now
  accept any mapping type.

- marshal now shares interned strings. This change introduces
  a new .pyc magic.

- Bug #966623. classes created with type() in an exec(, {}) don't
  have a __module__, but code in typeobject assumed it would always
  be there.

- Python no longer relies on the LC_NUMERIC locale setting to be
  the "C" locale; as a result, it no longer tries to prevent changing
  the LC_NUMERIC category.

- Bug #952807:  Unpickling pickled instances of subclasses of
  datetime.date, datetime.datetime and datetime.time could yield insane
  objects.  Thanks to Jiwon Seo for a fix.

- Bug #845802: Python crashes when __init__.py is a directory.

- Unicode objects received two new methods: iswide() and width().
  These query East Asian width information, as specified in Unicode
  TR11.

- Improved the tuple hashing algorithm to give fewer collisions in
  common cases.  Fixes bug  #942952.

- Implemented generator expressions (PEP 289).  Coded by Jiwon Seo.

- Enabled the profiling of C extension functions (and builtins) - check
  new documentation and modified profile and bdb modules for more details

- Set file.name to the object passed to open (instead of a new string)

- Moved tracebackobject into traceback.h and renamed to PyTracebackObject

- Optimized the byte coding for multiple assignments like "a,b=b,a" and
  "a,b,c=1,2,3".  Improves their speed by 25% to 30%.

- Limit the nested depth of a tuple for the second argument to isinstance()
  and issubclass() to the recursion limit of the interpreter.
  Fixes bug  #858016 .

- Optimized dict iterators, creating separate types for each
  and having them reveal their length.  Also optimized the
  methods:  keys(), values(), and items().

- Implemented a newcode opcode, LIST_APPEND, that simplifies
  the generated bytecode for list comprehensions and further
  improves their performance (about 35%).

- Implemented rich comparisons for floats, which seems to make
  comparisons involving NaNs somewhat less surprising when the
  underlying C compiler actually implements C99 semantics.

- Optimized list.extend() to save memory and no longer create
  intermediate sequences.  Also, extend() now pre-allocates the
  needed memory whenever the length of the iterable is known in
  advance -- this halves the time to extend the list.

- Optimized list resize operations to make fewer calls to the system
  realloc().  Significantly speeds up list appends, list pops,
  list comprehensions, and the list constructor (when the input iterable
  length is not known).

- Changed the internal list over-allocation scheme.  For larger lists,
  overallocation ranged between 3% and 25%.  Now, it is a constant 12%.
  For smaller lists (n<8), overallocation was upto eight elements.  Now,
  the overallocation is no more than three elements -- this improves space
  utilization for applications that have large numbers of small lists.

- Most list bodies now get re-used rather than freed.  Speeds up list
  instantiation and deletion by saving calls to malloc() and free().

- The dict.update() method now accepts all the same argument forms
  as the dict() constructor.  This now includes item lists and/or
  keyword arguments.

- Support for arbitrary objects supporting the read-only buffer
  interface as the co_code field of code objects (something that was
  only possible to create from C code) has been removed.

- Made omitted callback and None equivalent for weakref.ref() and
  weakref.proxy(); the None case wasn't handled correctly in all
  cases.

- Fixed problem where PyWeakref_NewRef() and PyWeakref_NewProxy()
  assumed that initial existing entries in an object's weakref list
  would not be removed while allocating a new weakref object.  Since
  GC could be invoked at that time, however, that assumption was
  invalid.  In a truly obscure case of GC being triggered during
  creation for a new weakref object for a referent which already
  has a weakref without a callback which is only referenced from
  cyclic trash, a memory error can occur.  This consistently created a
  segfault in a debug build, but provided less predictable behavior in
  a release build.

- input() built-in function now respects compiler flags such as
  __future__ statements.  SF patch 876178.

- Removed PendingDeprecationWarning from apply().  apply() remains
  deprecated, but the nuisance warning will not be issued.

- At Python shutdown time (Py_Finalize()), 2.3 called cyclic garbage
  collection twice, both before and after tearing down modules.  The
  call after tearing down modules has been disabled, because too much
  of Python has been torn down then for __del__ methods and weakref
  callbacks to execute sanely.  The most common symptom was a sequence
  of uninformative messages on stderr when Python shut down, produced
  by threads trying to raise exceptions, but unable to report the nature
  of their problems because too much of the sys module had already been
  destroyed.

- Removed FutureWarnings related to hex/oct literals and conversions
  and left shifts.  (Thanks to Kalle Svensson for SF patch 849227.)
  This addresses most of the remaining semantic changes promised by
  PEP 237, except for repr() of a long, which still shows the trailing
  'L'.  The PEP appears to promise warnings for operations that
  changed semantics compared to Python 2.3, but this is not
  implemented; we've suffered through enough warnings related to
  hex/oct literals and I think it's best to be silent now.

- For str and unicode objects, the ljust(), center(), and rjust()
  methods now accept an optional argument specifying a fill
  character other than a space.

- When method objects have an attribute that can be satisfied either
  by the function object or by the method object, the function
  object's attribute usually wins.  Christian Tismer pointed out that
  this is really a mistake, because this only happens for special
  methods (like __reduce__) where the method object's version is
  really more appropriate than the function's attribute.  So from now
  on, all method attributes will have precedence over function
  attributes with the same name.

- Critical bugfix, for SF bug 839548:  if a weakref with a callback,
  its callback, and its weakly referenced object, all became part of
  cyclic garbage during a single run of garbage collection, the order
  in which they were torn down was unpredictable.  It was possible for
  the callback to see partially-torn-down objects, leading to immediate
  segfaults, or, if the callback resurrected garbage objects, to
  resurrect insane objects that caused segfaults (or other surprises)
  later.  In one sense this wasn't surprising, because Python's cyclic gc
  had no knowledge of Python's weakref objects.  It does now.  When
  weakrefs with callbacks become part of cyclic garbage now, those
  weakrefs are cleared first.  The callbacks don't trigger then,
  preventing the problems.  If you need callbacks to trigger, then just
  as when cyclic gc is not involved, you need to write your code so
  that weakref objects outlive the objects they weakly reference.

- Critical bugfix, for SF bug 840829:  if cyclic garbage collection
  happened to occur during a weakref callback for a new-style class
  instance, subtle memory corruption was the result (in a release build;
  in a debug build, a segfault occurred reliably very soon after).
  This has been repaired.

- Compiler flags set in PYTHONSTARTUP are now active in __main__.

- Added two built-in types, set() and frozenset().

- Added a reversed() built-in function that returns a reverse iterator
  over a sequence.

- Added a sorted() built-in function that returns a new sorted list
  from any iterable.

- CObjects are now mutable (on the C level) through PyCObject_SetVoidPtr.

- list.sort() now supports three keyword arguments:  cmp, key, and reverse.
  The key argument can be a function of one argument that extracts a
  comparison key from the original record:  mylist.sort(key=str.lower).
  The reverse argument is a boolean value and if True will change the
  sort order as if the comparison arguments were reversed.  In addition,
  the documentation has been amended to provide a guarantee that all sorts
  starting with Py2.3 are guaranteed to be stable (the relative order of
  records with equal keys is unchanged).

- Added test whether wchar_t is signed or not. A signed wchar_t is not
  usable as internal unicode type base for Py_UNICODE since the
  unicode implementation assumes an unsigned type.

- Fixed a bug in the cache of length-one Unicode strings that could
  lead to a seg fault.  The specific problem occurred when an earlier,
  non-fatal error left an uninitialized Unicode object in the
  freelist.

- The % formatting operator now supports '%F' which is equivalent to
  '%f'.  This has always been documented but never implemented.

- complex(obj) could leak a little memory if obj wasn't a string or
  number.

- zip() with no arguments now returns an empty list instead of raising
  a TypeError exception.

- obj.__contains__() now returns True/False instead of 1/0.  SF patch
  820195.

- Python no longer tries to be smart about recursive comparisons.
  When comparing containers with cyclic references to themselves it
  will now just hit the recursion limit.  See SF patch 825639.

- str and unicode built-in types now have an rsplit() method that is
  same as split() except that it scans the string from the end
  working towards the beginning.  See SF feature request 801847.

- Fixed a bug in object.__reduce_ex__ when using protocol 2.  Failure
  to clear the error when attempts to get the __getstate__ attribute
  fail caused intermittent errors and odd behavior.

- buffer objects based on other objects no longer cache a pointer to
  the data and the data length.  Instead, the appropriate tp_as_buffer
  method is called as necessary.

- fixed: if a file is opened with an explicit buffer size >= 1, repeated
  close() calls would attempt to free() the buffer already free()ed on
  the first call.


Extension modules
-----------------

- Added socket.getservbyport(), and make the second argument in
  getservbyname() and getservbyport() optional.

- time module code that deals with input POSIX timestamps will now raise
  ValueError if more than a second is lost in precision when the
  timestamp is cast to the platform C time_t type.  There's no chance
  that the platform will do anything sensible with the result in such
  cases.  This includes ctime(), localtime() and gmtime().  Assorted
  fromtimestamp() and utcfromtimestamp() methods in the datetime module
  were also protected.  Closes bugs #919012 and 975996.

- fcntl.ioctl now warns if the mutate flag is not specified.

- nt now properly allows referring to UNC roots, e.g. in nt.stat().

- the weakref module now supports additional objects:  array.array,
  sre.pattern_objects, file objects, and sockets.

- operator.isMappingType() and operator.isSequenceType() now give
  fewer false positives.

- socket.sslerror is now a subclass of socket.error .  Also added
  socket.error to the socket module's C API.

- Bug #920575: A problem where the _locale module segfaults on
  nl_langinfo(ERA) caused by GNU libc's illegal NULL return is fixed.

- array objects now support the copy module.  Also, their resizing
  scheme has been updated to match that used for list objects.  This improves
  the performance (speed and memory usage) of append() operations.
  Also, array.array() and array.extend() now accept any iterable argument
  for repeated appends without needing to create another temporary array.

- cStringIO.writelines() now accepts any iterable argument and writes
  the lines one at a time rather than joining them and writing once.
  Made a parallel change to StringIO.writelines().  Saves memory and
  makes suitable for use with generator expressions.

- time.strftime() now checks that the values in its time tuple argument
  are within the proper boundaries to prevent possible crashes from the
  platform's C library implementation of strftime().  Can possibly
  break code that uses values outside the range that didn't cause
  problems previously (such as sitting day of year to 0).  Fixes bug
  #897625.

- The socket module now supports Bluetooth sockets, if the
  system has <bluetooth/bluetooth.h>

- Added a collections module containing a new datatype, deque(),
  offering high-performance, thread-safe, memory friendly appends
  and pops on either side of the deque.

- Several modules now take advantage of collections.deque() for
  improved performance:  Queue, mutex, shlex, threading, and pydoc.

- The operator module has two new functions, attrgetter() and
  itemgetter() which are useful for creating fast data extractor
  functions for map(), list.sort(), itertools.groupby(), and
  other functions that expect a function argument.

- socket.SHUT_{RD,WR,RDWR} was added.

- os.getsid was added.

- The pwd module incorrectly advertised its struct type as
  struct_pwent; this has been renamed to struct_passwd.  (The old name
  is still supported for backwards compatibility.)

- The xml.parsers.expat module now provides Expat 1.95.7.

- socket.IPPROTO_IPV6 was added.

- readline.clear_history was added.

- select.select() now accepts sequences for its first three arguments.

- cStringIO now supports the f.closed attribute.

- The signal module now exposes SIGRTMIN and SIGRTMAX (if available).

- curses module now supports use_default_colors().  [patch #739124]

- Bug #811028: ncurses.h breakage on FreeBSD/MacOS X

- Bug #814613: INET_ADDRSTRLEN fix needed for all compilers on SGI

- Implemented non-recursive SRE matching scheme (#757624).

- Implemented (?(id/name)yes|no) support in SRE (#572936).

- random.seed() with no arguments or None uses time.time() as a default
  seed.  Modified to match Py2.2 behavior and use fractional seconds so
  that successive runs are more likely to produce different sequences.

- random.Random has a new method, getrandbits(k), which returns an int
  with k random bits.  This method is now an optional part of the API
  for user defined generators.  Any generator that defines genrandbits()
  can now use randrange() for ranges with a length >= 2**53.  Formerly,
  randrange would return only even numbers for ranges that large (see
  SF bug #812202).  Generators that do not define genrandbits() now
  issue a warning when randrange() is called with a range that large.

- itertools has a new function, groupby() for aggregating iterables
  into groups sharing the same key (as determined by a key function).
  It offers some of functionality of SQL's groupby keyword and of
  the Unix uniq filter.

- itertools now has a new tee() function which produces two independent
  iterators from a single iterable.

- itertools.izip() with no arguments now returns an empty iterator instead
  of raising a TypeError exception.

- Fixed #853061: allow BZ2Compressor.compress() to receive an empty string
  as parameter.

Library
-------

- Added a new module: cProfile, a C profiler with the same interface as the
  profile module.  cProfile avoids some of the drawbacks of the hotshot
  profiler and provides a bit more information than the other two profilers.
  Based on "lsprof" (patch #1212837).

- Bug #1266283: The new function "lexists" is now in os.path.__all__.

- Bug #981530: Fix UnboundLocalError in shutil.rmtree().  This affects
  the documented behavior: the function passed to the onerror()
  handler can now also be os.listdir.

- Bug #754449: threading.Thread objects no longer mask exceptions raised during
  interpreter shutdown with another exception from attempting to handle the
  original exception.

- Added decimal.py per PEP 327.

- Bug #981299: rsync is now a recognized protocol in urlparse that uses a
  "netloc" portion of a URL.

- Bug #919012: shutil.move() will not try to move a directory into itself.
  Thanks Johannes Gijsbers.

- Bug #934282: pydoc.stripid() is now case-insensitive.  Thanks Robin Becker.

- Bug #823209:  cmath.log() now takes an optional base argument so that its
  API matches math.log().

- Bug #957381: distutils bdist_rpm no longer fails on recent RPM versions
  that generate a -debuginfo.rpm

- os.path.devnull has been added for all supported platforms.

- Fixed #877165: distutils now picks the right C++ compiler command
  on cygwin and mingw32.

- urllib.urlopen().readline() now handles HTTP/0.9 correctly.

- refactored site.py into functions.  Also wrote regression tests for the
  module.

- The distutils install command now supports the --home option and
  installation scheme for all platforms.

- asyncore.loop now has a repeat count parameter that defaults to
  looping forever.

- The distutils sdist command now ignores all .svn directories, in
  addition to CVS and RCS directories.  .svn directories hold
  administrative files for the Subversion source control system.

- Added a new module: cookielib.  Automatic cookie handling for HTTP
  clients.  Also, support for cookielib has been added to urllib2, so
  urllib2.urlopen() can transparently handle cookies.

- stringprep.py now uses built-in set() instead of sets.Set().

- Bug #876278: Unbounded recursion in modulefinder

- Bug #780300: Swap public and system ID in LexicalHandler.startDTD.
  Applications relying on the wrong order need to be corrected.

- Bug #926075: Fixed a bug that returns a wrong pattern object
  for a string or unicode object in sre.compile() when a different
  type pattern with the same value exists.

- Added countcallers arg to trace.Trace class (--trackcalls command line arg
  when run from the command prompt).

- Fixed a caching bug in platform.platform() where the argument of 'terse' was
  not taken into consideration when caching value.

- Added two new command-line arguments for profile (output file and
  default sort).

- Added global runctx function to profile module

- Add hlist missing entryconfigure and entrycget methods.

- The ptcp154 codec was added for Kazakh character set support.

- Support non-anonymous ftp URLs in urllib2.

- The encodings package will now apply codec name aliases
  first before starting to try the import of the codec module.
  This simplifies overriding built-in codecs with external
  packages, e.g. the included CJK codecs with the JapaneseCodecs
  package, by adjusting the aliases dictionary in encodings.aliases
  accordingly.

- base64 now supports RFC 3548 Base16, Base32, and Base64 encoding and
  decoding standards.

- urllib2 now supports processors.  A processor is a handler that
  implements an xxx_request or xxx_response method.  These methods are
  called for all requests.

- distutils compilers now compile source files in the same order as
  they are passed to the compiler.

- pprint.pprint() and pprint.pformat() now have additional parameters
  indent, width and depth.

- Patch #750542: pprint now will pretty print subclasses of list, tuple
  and dict too, as long as they don't overwrite __repr__().

- Bug #848614: distutils' msvccompiler fails to find the MSVC6
  compiler because of incomplete registry entries.

- httplib.HTTP.putrequest now offers to omit the implicit Accept-Encoding.

- Patch #841977: modulefinder didn't find extension modules in packages

- imaplib.IMAP4.thread was added.

- Plugged a minor hole in tempfile.mktemp() due to the use of
  os.path.exists(), switched to using os.lstat() directly if possible.

- bisect.py and heapq.py now have underlying C implementations
  for better performance.

- heapq.py has two new functions, nsmallest() and nlargest().

- traceback.format_exc has been added (similar to print_exc but it returns
  a string).

- xmlrpclib.MultiCall has been added.

- poplib.POP3_SSL has been added.

- tmpfile.mkstemp now returns an absolute path even if dir is relative.

- urlparse is RFC 2396 compliant.

- The fieldnames argument to the csv module's DictReader constructor is now
  optional.  If omitted, the first row of the file will be used as the
  list of fieldnames.

- encodings.bz2_codec was added for access to bz2 compression
  using "a long string".encode('bz2')

- Various improvements to unittest.py, realigned with PyUnit CVS.

- dircache now passes exceptions to the caller, instead of returning
  empty lists.

- The bsddb module and dbhash module now support the iterator and
  mapping protocols which make them more substitutable for dictionaries
  and shelves.

- The csv module's DictReader and DictWriter classes now accept keyword
  arguments.  This was an omission in the initial implementation.

- The email package handles some RFC 2231 parameters with missing
  CHARSET fields better.  It also includes a patch to parameter
  parsing when semicolons appear inside quotes.

- sets.py now runs under Py2.2.  In addition, the argument restrictions
  for most set methods (but not the operators) have been relaxed to
  allow any iterable.

- _strptime.py now has a behind-the-scenes caching mechanism for the most
  recent TimeRE instance used along with the last five unique directive
  patterns.  The overall module was also made more thread-safe.

- random.cunifvariate() and random.stdgamma() were deprecated in Py2.3
  and removed in Py2.4.

- Bug #823328: urllib2.py's HTTP Digest Auth support works again.

- Patch #873597: CJK codecs are imported into rank of default codecs.

Tools/Demos
-----------

- A hotshotmain script was added to the Tools/scripts directory that
  makes it easy to run a script under control of the hotshot profiler.

- The db2pickle and pickle2db scripts can now dump/load gdbm files.

- The file order on the command line of the pickle2db script was reversed.
  It is now [ picklefile ] dbfile.  This provides better symmetry with
  db2pickle.  The file arguments to both scripts are now source followed by
  destination in situations where both files are given.

- The pydoc script will display a link to the module documentation for
  modules determined to be part of the core distribution.  The documentation
  base directory defaults to http://www.python.org/doc/current/lib/ but can
  be changed by setting the PYTHONDOCS environment variable.

- texcheck.py now detects double word errors.

- md5sum.py mistakenly opened input files in text mode by default, a
  silent and dangerous change from previous releases.  It once again
  opens input files in binary mode by default.  The -t and -b flags
  remain for compatibility with the 2.3 release, but -b is the default
  now.

- py-electric-colon now works when pending-delete/delete-selection mode is
  in effect

- py-help-at-point is no longer bound to the F1 key - it's still bound to
  C-c C-h

- Pynche was fixed to not crash when there is no ~/.pynche file and no
  -d option was given.

Build
-----

- Bug #978645: Modules/getpath.c now builds properly in --disable-framework
  build under OS X.

- Profiling using gprof is now available if Python is configured with
  --enable-profiling.

- Profiling the VM using the Pentium TSC is now possible if Python
  is configured --with-tsc.

- In order to find libraries, setup.py now also looks in /lib64, for use
  on AMD64.

- Bug #934635: Fixed a bug where the configure script couldn't detect
  getaddrinfo() properly if the KAME stack had SCTP support.

- Support for missing ANSI C header files (limits.h, stddef.h, etc) was
  removed.

- Systems requiring the D4, D6 or D7 variants of pthreads are no longer
  supported (see PEP 11).

- Universal newline support can no longer be disabled (see PEP 11).

- Support for DGUX, SunOS 4, IRIX 4 and Minix was removed (see PEP 11).

- Support for systems requiring --with-dl-dld or --with-sgi-dl was removed
  (see PEP 11).

- Tests for sizeof(char) were removed since ANSI C mandates that
  sizeof(char) must be 1.

C API
-----

- Thanks to Anthony Tuininga, the datetime module now supplies a C API
  containing type-check macros and constructors.  See new docs in the
  Python/C API Reference Manual for details.

- Private function _PyTime_DoubleToTimet added, to convert a Python
  timestamp (C double) to platform time_t with some out-of-bounds
  checking.  Declared in new header file timefuncs.h.  It would be
  good to expose some other internal timemodule.c functions there.

- New public functions PyEval_EvaluateFrame and PyGen_New to expose
  generator objects.

- New public functions Py_IncRef() and Py_DecRef(), exposing the
  functionality of the Py_XINCREF() and Py_XDECREF macros. Useful for
  runtime dynamic embedding of Python.  See patch #938302, by Bob
  Ippolito.

- Added a new macro, PySequence_Fast_ITEMS, which retrieves a fast sequence's
  underlying array of PyObject pointers.  Useful for high speed looping.

- Created a new method flag, METH_COEXIST, which causes a method to be loaded
  even if already defined by a slot wrapper.  This allows a __contains__
  method, for example, to co-exist with a defined sq_contains slot.  This
  is helpful because the PyCFunction can take advantage of optimized calls
  whenever METH_O or METH_NOARGS flags are defined.

- Added a new function, PyDict_Contains(d, k) which is like
  PySequence_Contains() but is specific to dictionaries and executes
  about 10% faster.

- Added three new macros: Py_RETURN_NONE, Py_RETURN_TRUE, and Py_RETURN_FALSE.
  Each return the singleton they mention after Py_INCREF()ing them.

- Added a new function, PyTuple_Pack(n, ...) for constructing tuples from a
  variable length argument list of Python objects without having to invoke
  the more complex machinery of Py_BuildValue().  PyTuple_Pack(3, a, b, c)
  is equivalent to Py_BuildValue("(OOO)", a, b, c).

Windows
-------

- The _winreg module could segfault when reading very large registry
  values, due to unchecked alloca() calls (SF bug 851056).  The fix is
  uses either PyMem_Malloc(n) or PyString_FromStringAndSize(NULL, n),
  as appropriate, followed by a size check.

- file.truncate() could misbehave if the file was open for update
  (modes r+, rb+, w+, wb+), and the most recent file operation before
  the truncate() call was an input operation.  SF bug 801631.


What's New in Python 2.3 final?
===============================

*Release date: 29-Jul-2003*

IDLE
----

- Bug 778400:  IDLE hangs when selecting "Edit with IDLE" from explorer.
  This was unique to Windows, and was fixed by adding an -n switch to
  the command the Windows installer creates to execute "Edit with IDLE"
  context-menu actions.

- IDLE displays a new message upon startup:  some "personal firewall"
  kinds of programs (for example, ZoneAlarm) open a dialog of their
  own when any program opens a socket.  IDLE does use sockets, talking
  on the computer's internal loopback interface.  This connection is not
  visible on any external interface and no data is sent to or received
  from the Internet.  So, if you get such a dialog when opening IDLE,
  asking whether to let pythonw.exe talk to address 127.0.0.1, say yes,
  and rest assured no communication external to your machine is taking
  place.  If you don't allow it, IDLE won't be able to start.


What's New in Python 2.3 release candidate 2?
=============================================

*Release date: 24-Jul-2003*

Core and builtins
-----------------

- It is now possible to import from zipfiles containing additional
  data bytes before the zip compatible archive.  Zipfiles containing a
  comment at the end are still unsupported.

Extension modules
-----------------

- A longstanding bug in the parser module's initialization could cause
  fatal internal refcount confusion when the module got initialized more
  than once.  This has been fixed.

- Fixed memory leak in pyexpat; using the parser's ParseFile() method
  with open files that aren't instances of the standard file type
  caused an instance of the bound .read() method to be leaked on every
  call.

- Fixed some leaks in the locale module.

Library
-------

- Lib/encodings/rot_13.py when used as a script, now more properly
  uses the first Python interpreter on your path.

- Removed caching of TimeRE (and thus LocaleTime) in _strptime.py to
  fix a locale related bug in the test suite.  Although another patch
  was needed to actually fix the problem, the cache code was not
  restored.

IDLE
----

- Calltips patches.

Build
-----

- For MacOSX, added -mno-fused-madd to BASECFLAGS to fix test_coercion
  on Panther (OSX 10.3).

C API
-----

Windows
-------

- The tempfile module could do insane imports on Windows if PYTHONCASEOK
  was set, making temp file creation impossible.  Repaired.

- Add a patch to workaround pthread_sigmask() bugs in Cygwin.

Mac
---

- Various fixes to pimp.

- Scripts runs with pythonw no longer had full window manager access.

- Don't force boot-disk-only install, for reasons unknown it causes
  more problems than it solves.


What's New in Python 2.3 release candidate 1?
=============================================

*Release date: 18-Jul-2003*

Core and builtins
-----------------

- The new function sys.getcheckinterval() returns the last value set
  by sys.setcheckinterval().

- Several bugs in the symbol table phase of the compiler have been
  fixed.  Errors could be lost and compilation could fail without
  reporting an error.  SF patch 763201.

- The interpreter is now more robust about importing the warnings
  module.  In an executable generated by freeze or similar programs,
  earlier versions of 2.3 would fail if the warnings module could
  not be found on the file system.  Fixes SF bug 771097.

- A warning about assignments to module attributes that shadow
  builtins, present in earlier releases of 2.3, has been removed.

- It is not possible to create subclasses of built-in types like str
  and tuple that define an itemsize.  Earlier releases of Python 2.3
  allowed this by mistake, leading to crashes and other problems.

- The thread_id is now initialized to 0 in a non-thread build.  SF bug
  770247.

- SF bug 762891: "del p[key]" on proxy object no longer raises SystemError.

Extension modules
-----------------

- weakref.proxy() can now handle "del obj[i]" for proxy objects
  defining __delitem__.  Formerly, it generated a SystemError.

- SSL no longer crashes the interpreter when the remote side disconnects.

- On Unix the mmap module can again be used to map device files.

- time.strptime now exclusively uses the Python implementation
  contained within the _strptime module.

- The print slot of weakref proxy objects was removed, because it was
  not consistent with the object's repr slot.

- The mmap module only checks file size for regular files, not
  character or block devices.  SF patch 708374.

- The cPickle Pickler garbage collection support was fixed to traverse
  the find_class attribute, if present.

- There are several fixes for the bsddb3 wrapper module.

  bsddb3 no longer crashes if an environment is closed before a cursor
  (SF bug 763298).

  The DB and DBEnv set_get_returns_none function was extended to take
  a level instead of a boolean flag.  The new level 2 means that in
  addition, cursor.set()/.get() methods return None instead of raising
  an exception.

  A typo was fixed in DBCursor.join_item(), preventing a crash.

Library
-------

- distutils now supports MSVC 7.1

- doctest now examines all docstrings by default.  Previously, it would
  skip over functions with private names (as indicated by the underscore
  naming convention).  The old default created too much of a risk that
  user tests were being skipped inadvertently.  Note, this change could
  break code in the unlikely case that someone had intentionally put
  failing tests in the docstrings of private functions.  The breakage
  is easily fixable by specifying the old behavior when calling testmod()
  or Tester().

- There were several fixes to the way dumbdbms are closed.  It's vital
  that a dumbdbm database be closed properly, else the on-disk data
  and directory files can be left in mutually inconsistent states.
  dumbdbm.py's _Database.__del__() method attempted to close the
  database properly, but a shutdown race in _Database._commit() could
  prevent this from working, so that a program trusting __del__() to
  get the on-disk files in synch could be badly surprised.  The race
  has been repaired.  A sync() method was also added so that shelve
  can guarantee data is written to disk.

  The close() method can now be called more than once without complaint.

- The classes in threading.py are now new-style classes.  That they
  weren't before was an oversight.

- The urllib2 digest authentication handlers now define the correct
  auth_header.  The earlier versions would fail at runtime.

- SF bug 763023: fix uncaught ZeroDivisionError in difflib ratio methods
  when there are no lines.

- SF bug 763637: fix exception in Tkinter with after_cancel
  which could occur with Tk 8.4

- SF bug 770601: CGIHTTPServer.py now passes the entire environment
  to child processes.

- SF bug 765238: add filter to fnmatch's __all__.

- SF bug 748201: make time.strptime() error messages more helpful.

- SF patch 764470: Do not dump the args attribute of a Fault object in
  xmlrpclib.

- SF patch 549151: urllib and urllib2 now redirect POSTs on 301
  responses.

- SF patch 766650: The whichdb module was fixed to recognize dbm files
  generated by gdbm on OS/2 EMX.

- SF bugs 763047 and 763052: fixes bug of timezone value being left as
  -1 when ``time.tzname[0] == time.tzname[1] and not time.daylight``
  is true when it should only when time.daylight is true.

- SF bug 764548: re now allows subclasses of str and unicode to be
  used as patterns.

- SF bug 763637: In Tkinter, change after_cancel() to handle tuples
  of varying sizes.  Tk 8.4 returns a different number of values
  than Tk 8.3.

- SF bug 763023: difflib.ratio() did not catch zero division.

- The Queue module now has an __all__ attribute.

Tools/Demos
-----------

- See Lib/idlelib/NEWS.txt for IDLE news.

- SF bug 753592: webchecker/wsgui now handles user supplied directories.

- The trace.py script has been removed.  It is now in the standard library.

Build
-----

- Python now compiles with -fno-strict-aliasing if possible (SF bug 766696).

- The socket module compiles on IRIX 6.5.10.

- An irix64 system is treated the same way as an irix6 system (SF
  patch 764560).

- Several definitions were missing on FreeBSD 5.x unless the
  __BSD_VISIBLE symbol was defined.  configure now defines it as
  needed.

C API
-----

- Unicode objects now support mbcs as a built-in encoding, so the C
  API can use it without deferring to the encodings package.

Windows
-------

- The Windows implementation of PyThread_start_new_thread() never
  checked error returns from Windows functions correctly.  As a result,
  it could claim to start a new thread even when the Microsoft
  _beginthread() function failed (due to "too many threads" -- this is
  on the order of thousands when it happens).  In these cases, the
  Python exception ::

      thread.error: can't start new thread

  is raised now.

- SF bug 766669: Prevent a GPF on interpreter exit when sockets are in
  use.  The interpreter now calls WSACleanup() from Py_Finalize()
  instead of from DLL teardown.

Mac
---

- Bundlebuilder now inherits default values in the right way.  It was
  previously possible for app bundles to get a type of "BNDL" instead
  of "APPL."  Other improvements include, a --build-id option to
  specify the CFBundleIdentifier and using the --python option to set
  the executable in the bundle.

- Fixed two bugs in MacOSX framework handling.

- pythonw did not allow user interaction in 2.3rc1, this has been fixed.

- Python is now compiled with -mno-fused-madd, making all tests pass
  on Panther.

What's New in Python 2.3 beta 2?
================================

*Release date: 29-Jun-2003*

Core and builtins
-----------------

- A program can now set the environment variable PYTHONINSPECT to some
  string value in Python, and cause the interpreter to enter the
  interactive prompt at program exit, as if Python had been invoked
  with the -i option.

- list.index() now accepts optional start and stop arguments.  Similar
  changes were made to UserList.index(). SF feature request 754014.

- SF patch 751998 fixes an unwanted side effect of the previous fix
  for SF bug 742860 (the next item).

- SF bug 742860: "WeakKeyDictionary __delitem__ uses iterkeys".  This
  wasn't threadsafe, was very inefficient (expected time O(len(dict))
  instead of O(1)), and could raise a spurious RuntimeError if another
  thread mutated the dict during __delitem__, or if a comparison function
  mutated it.  It also neglected to raise KeyError when the key wasn't
  present; didn't raise TypeError when the key wasn't of a weakly
  referencable type; and broke various more-or-less obscure dict
  invariants by using a sequence of equality comparisons over the whole
  set of dict keys instead of computing the key's hash code to narrow
  the search to those keys with the same hash code.  All of these are
  considered to be bugs.  A new implementation of __delitem__ repairs all
  that, but note that fixing these bugs may change visible behavior in
  code relying (whether intentionally or accidentally) on old behavior.

- SF bug 734869: Fixed a compiler bug that caused a fatal error when
  compiling a list comprehension that contained another list comprehension
  embedded in a lambda expression.

- SF bug 705231:  builtin pow() no longer lets the platform C pow()
  raise -1.0 to integer powers, because (at least) glibc gets it wrong
  in some cases.  The result should be -1.0 if the power is odd and 1.0
  if the power is even, and any float with a sufficiently large exponent
  is (mathematically) an exact even integer.

- SF bug 759227: A new-style class that implements __nonzero__() must
  return a bool or int (but not an int subclass) from that method.  This
  matches the restriction on classic classes.

- The encoding attribute has been added for file objects, and set to
  the terminal encoding on Unix and Windows.

- The softspace attribute of file objects became read-only by oversight.
  It's writable again.

- Reverted a 2.3 beta 1 change to iterators for subclasses of list and
  tuple.  By default, the iterators now access data elements directly
  instead of going through __getitem__.  If __getitem__ access is
  preferred, then __iter__ can be overridden.

- SF bug 735247: The staticmethod and super types participate in
  garbage collection. Before this change, it was possible for leaks to
  occur in functions with non-global free variables that used these types.

Extension modules
-----------------

- the socket module has a new exception, socket.timeout, to allow
  timeouts to be handled separately from other socket errors.

- SF bug 751276: cPickle has fixed to propagate exceptions raised in
  user code.  In earlier versions, cPickle caught and ignored any
  exception when it performed operations that it expected to raise
  specific exceptions like AttributeError.

- cPickle Pickler and Unpickler objects now participate in garbage
  collection.

- mimetools.choose_boundary() could return duplicate strings at times,
  especially likely on Windows.  The strings returned are now guaranteed
  unique within a single program run.

- thread.interrupt_main() raises KeyboardInterrupt in the main thread.
  dummy_thread has also been modified to try to simulate the behavior.

- array.array.insert() now treats negative indices as being relative
  to the end of the array, just like list.insert() does. (SF bug #739313)

- The datetime module classes datetime, time, and timedelta are now
  properly subclassable.

- _tkinter.{get|set}busywaitinterval was added.

- itertools.islice() now accepts stop=None as documented.
  Fixes SF bug #730685.

- the bsddb185 module is built in one restricted instance -
  /usr/include/db.h exists and defines HASHVERSION to be 2.  This is true
  for many BSD-derived systems.


Library
-------

- Some happy doctest extensions from Jim Fulton have been added to
  doctest.py.  These are already being used in Zope3.  The two
  primary ones:

  doctest.debug(module, name) extracts the doctests from the named object
  in the given module, puts them in a temp file, and starts pdb running
  on that file.  This is great when a doctest fails.

  doctest.DocTestSuite(module=None) returns a synthesized unittest
  TestSuite instance, to be run by the unittest framework, which
  runs all the doctests in the module.  This allows writing tests in
  doctest style (which can be clearer and shorter than writing tests
  in unittest style), without losing unittest's powerful testing
  framework features (which doctest lacks).

- For compatibility with doctests created before 2.3, if an expected
  output block consists solely of "1" and the actual output block
  consists solely of "True", it's accepted as a match; similarly
  for "0" and "False".  This is quite un-doctest-like, but is practical.
  The behavior can be disabled by passing the new doctest module
  constant DONT_ACCEPT_TRUE_FOR_1 to the new optionflags optional
  argument.

- ZipFile.testzip() now only traps BadZipfile exceptions.  Previously,
  a bare except caught to much and reported all errors as a problem
  in the archive.

- The logging module now has a new function, makeLogRecord() making
  LogHandler easier to interact with DatagramHandler and SocketHandler.

- The cgitb module has been extended to support plain text display (SF patch
  569574).

- A brand new version of IDLE (from the IDLEfork project at
  SourceForge) is now included as Lib/idlelib.  The old Tools/idle is
  no more.

- Added a new module: trace (documentation missing).  This module used
  to be distributed in Tools/scripts.  It uses sys.settrace() to trace
  code execution -- either function calls or individual lines.  It can
  generate tracing output during execution or a post-mortem report of
  code coverage.

- The threading module has new functions settrace() and setprofile()
  that cooperate with the functions of the same name in the sys
  module.  A function registered with the threading module will
  be used for all threads it creates.  The new trace module uses this
  to provide tracing for code running in threads.

- copy.py: applied SF patch 707900, fixing bug 702858, by Steven
  Taschuk.  Copying a new-style class that had a reference to itself
  didn't work.  (The same thing worked fine for old-style classes.)
  Builtin functions are now treated as atomic, fixing bug #746304.

- difflib.py has two new functions:  context_diff() and unified_diff().

- More fixes to urllib (SF 549151): (a) When redirecting, always use
  GET.  This is common practice and more-or-less sanctioned by the
  HTTP standard. (b) Add a handler for 307 redirection, which becomes
  an error for POST, but a regular redirect for GET and HEAD

- Added optional 'onerror' argument to os.walk(), to control error
  handling.

- inspect.is{method|data}descriptor was added, to allow pydoc display
  __doc__ of data descriptors.

- Fixed socket speed loss caused by use of the _socketobject wrapper class
  in socket.py.

- timeit.py now checks the current directory for imports.

- urllib2.py now knows how to order proxy classes, so the user doesn't
  have to insert it in front of other classes, nor do dirty tricks like
  inserting a "dummy" HTTPHandler after a ProxyHandler when building an
  opener with proxy support.

- Iterators have been added for dbm keys.

- random.Random objects can now be pickled.

Tools/Demos
-----------

- pydoc now offers help on keywords and topics.

- Tools/idle is gone; long live Lib/idlelib.

- diff.py prints file diffs in context, unified, or ndiff formats,
  providing a command line interface to difflib.py.

- texcheck.py is a new script for making a rough validation of Python LaTeX
  files.

Build
-----

- Setting DESTDIR during 'make install' now allows specifying a
  different root directory.

C API
-----

- PyType_Ready():  If a type declares that it participates in gc
  (Py_TPFLAGS_HAVE_GC), and its base class does not, and its base class's
  tp_free slot is the default _PyObject_Del, and type does not define
  a tp_free slot itself, _PyObject_GC_Del is assigned to type->tp_free.
  Previously _PyObject_Del was inherited, which could at best lead to a
  segfault.  In addition, if even after this magic the type's tp_free
  slot is _PyObject_Del or NULL, and the type is a base type
  (Py_TPFLAGS_BASETYPE), TypeError is raised:  since the type is a base
  type, its dealloc function must call type->tp_free, and since the type
  is gc'able, tp_free must not be NULL or _PyObject_Del.

- PyThreadState_SetAsyncExc(): A new API (deliberately accessible only
  from C) to interrupt a thread by sending it an exception.  It is
  intentional that you have to write your own C extension to call it
  from Python.


New platforms
-------------

None this time.

Tests
-----

- test_imp rewritten so that it doesn't raise RuntimeError if run as a
  side effect of being imported ("import test.autotest").

Windows
-------

- The Windows installer ships with Tcl/Tk 8.4.3 (upgraded from 8.4.1).

- The installer always suggested that Python be installed on the C:
  drive, due to a hardcoded "C:" generated by the Wise installation
  wizard.  People with machines where C: is not the system drive
  usually want Python installed on whichever drive is their system drive
  instead.  We removed the hardcoded "C:", and two testers on machines
  where C: is not the system drive report that the installer now
  suggests their system drive.  Note that you can always select the
  directory you want in the "Select Destination Directory" dialog --
  that's what it's for.

Mac
---

- There's a new module called "autoGIL", which offers a mechanism to
  automatically release the Global Interpreter Lock when an event loop
  goes to sleep, allowing other threads to run. It's currently only
  supported on OSX, in the Mach-O version.
- The OSA modules now allow direct access to properties of the
  toplevel application class (in AppleScript terminology).
- The Package Manager can now update itself.

SourceForge Bugs and Patches Applied
------------------------------------

430160, 471893, 501716, 542562, 549151, 569574, 595837, 596434,
598163, 604210, 604716, 610332, 612627, 614770, 620190, 621891,
622042, 639139, 640236, 644345, 649742, 649742, 658233, 660022,
661318, 661676, 662807, 662923, 666219, 672855, 678325, 682347,
683486, 684981, 685773, 686254, 692776, 692959, 693094, 696777,
697989, 700827, 703666, 708495, 708604, 708901, 710733, 711902,
713722, 715782, 718286, 719359, 719367, 723136, 723831, 723962,
724588, 724767, 724767, 725942, 726150, 726446, 726869, 727051,
727719, 727719, 727805, 728277, 728563, 728656, 729096, 729103,
729293, 729297, 729300, 729317, 729395, 729622, 729817, 730170,
730296, 730594, 730685, 730826, 730963, 731209, 731403, 731504,
731514, 731626, 731635, 731643, 731644, 731644, 731689, 732124,
732143, 732234, 732284, 732284, 732479, 732761, 732783, 732951,
733667, 733781, 734118, 734231, 734869, 735051, 735293, 735527,
735613, 735694, 736962, 736962, 737970, 738066, 739313, 740055,
740234, 740301, 741806, 742126, 742741, 742860, 742860, 742911,
744041, 744104, 744238, 744687, 744877, 745055, 745478, 745525,
745620, 746012, 746304, 746366, 746801, 746953, 747348, 747667,
747954, 748846, 748849, 748973, 748975, 749191, 749210, 749759,
749831, 749911, 750008, 750092, 750542, 750595, 751038, 751107,
751276, 751451, 751916, 751941, 751956, 751998, 752671, 753451,
753602, 753617, 753845, 753925, 754014, 754340, 754447, 755031,
755087, 755147, 755245, 755683, 755987, 756032, 756996, 757058,
757229, 757818, 757821, 757822, 758112, 758910, 759227, 759889,
760257, 760703, 760792, 761104, 761337, 761519, 761830, 762455


What's New in Python 2.3 beta 1?
================================

*Release date: 25-Apr-2003*

Core and builtins
-----------------

- New format codes B, H, I, k and K have been implemented for
  PyArg_ParseTuple and PyBuild_Value.

- New built-in function sum(seq, start=0) returns the sum of all the
  items in iterable object seq, plus start (items are normally numbers,
  and cannot be strings).

- bool() called without arguments now returns False rather than
  raising an exception.  This is consistent with calling the
  constructors for the other built-in types -- called without argument
  they all return the false value of that type.  (SF patch #724135)

- In support of PEP 269 (making the pgen parser generator accessible
  from Python), some changes to the pgen code structure were made; a
  few files that used to be linked only with pgen are now linked with
  Python itself.

- The repr() of a weakref object now shows the __name__ attribute of
  the referenced object, if it has one.

- super() no longer ignores data descriptors, except __class__.  See
  the thread started at
  http://mail.python.org/pipermail/python-dev/2003-April/034338.html

- list.insert(i, x) now interprets negative i as it would be
  interpreted by slicing, so negative values count from the end of the
  list.  This was the only place where such an interpretation was not
  placed on a list index.

- range() now works even if the arguments are longs with magnitude
  larger than sys.maxint, as long as the total length of the sequence
  fits.  E.g., range(2**100, 2**101, 2**100) is the following list:
  [1267650600228229401496703205376L].  (SF patch #707427.)

- Some horridly obscure problems were fixed involving interaction
  between garbage collection and old-style classes with "ambitious"
  getattr hooks.  If an old-style instance didn't have a __del__ method,
  but did have a __getattr__ hook, and the instance became reachable
  only from an unreachable cycle, and the hook resurrected or deleted
  unreachable objects when asked to resolve "__del__", anything up to
  a segfault could happen.  That's been repaired.

- dict.pop now takes an optional argument specifying a default
  value to return if the key is not in the dict.  If a default is not
  given and the key is not found, a KeyError will still be raised.
  Parallel changes were made to UserDict.UserDict and UserDict.DictMixin.
  [SF patch #693753] (contributed by Michael Stone.)

- sys.getfilesystemencoding() was added to expose
  Py_FileSystemDefaultEncoding.

- New function sys.exc_clear() clears the current exception.  This is
  rarely needed, but can sometimes be useful to release objects
  referenced by the traceback held in sys.exc_info()[2].  (SF patch
  #693195.)

- On 64-bit systems, a dictionary could contain duplicate long/int keys
  if the key value was larger than 2**32.  See SF bug #689659.

- Fixed SF bug #663074. The codec system was using global static
  variables to store internal data. As a result, any attempts to use the
  unicode system with multiple active interpreters, or successive
  interpreter executions, would fail.

- "%c" % u"a" now returns a unicode string instead of raising a
  TypeError. u"%c" % 0xffffffff now raises an OverflowError instead
  of a ValueError to be consistent with "%c" % 256. See SF patch #710127.

Extension modules
-----------------

- The socket module now provides the functions inet_pton and inet_ntop
  for converting between string and packed representation of IP
  addresses.  There is also a new module variable, has_ipv6, which is
  True iff the current Python has IPv6 support.  See SF patch #658327.

- Tkinter wrappers around Tcl variables now pass objects directly
  to Tcl, instead of first converting them to strings.

- The .*? pattern in the re module is now special-cased to avoid the
  recursion limit.  (SF patch #720991 -- many thanks to Gary Herron
  and Greg Chapman.)

- New function sys.call_tracing() allows pdb to debug code
  recursively.

- New function gc.get_referents(obj) returns a list of objects
  directly referenced by obj.  In effect, it exposes what the object's
  tp_traverse slot does, and can be helpful when debugging memory
  leaks.

- The iconv module has been removed from this release.

- The platform-independent routines for packing floats in IEEE formats
  (struct.pack's <f, >f, <d, and >d codes; pickle and cPickle's protocol 1
  pickling of floats) ignored that rounding can cause a carry to
  propagate.  The worst consequence was that, in rare cases, <f and >f
  could produce strings that, when unpacked again, were a factor of 2
  away from the original float.  This has been fixed.  See SF bug
  #705836.

- New function time.tzset() provides access to the C library tzset()
  function, if supported.  (SF patch #675422.)

- Using createfilehandler, deletefilehandler, createtimerhandler functions
  on Tkinter.tkinter (_tkinter module) no longer crashes the interpreter.
  See SF bug #692416.

- Modified the fcntl.ioctl() function to allow modification of a passed
  mutable buffer (for details see the reference documentation).

- Made user requested changes to the itertools module.
  Subsumed the times() function into repeat().
  Added chain() and cycle().

- The rotor module is now deprecated; the encryption algorithm it uses
  is not believed to be secure, and including crypto code with Python
  has implications for exporting and importing it in various countries.

- The socket module now always uses the _socketobject wrapper class, even on
  platforms which have dup(2).  The makefile() method is built directly
  on top of the socket without duplicating the file descriptor, allowing
  timeouts to work properly.

Library
-------

- New generator function os.walk() is an easy-to-use alternative to
  os.path.walk().  See os module docs for details.  os.path.walk()
  isn't deprecated at this time, but may become deprecated in a
  future release.

- Added new module "platform" which provides a wide range of tools
  for querying platform dependent features.

- netrc now allows ASCII punctuation characters in passwords.

- shelve now supports the optional writeback argument, and exposes
  pickle protocol versions.

- Several methods of nntplib.NNTP have grown an optional file argument
  which specifies a file where to divert the command's output
  (already supported by the body() method).  (SF patch #720468)

- The self-documenting XML server library DocXMLRPCServer was added.

- Support for internationalized domain names has been added through
  the 'idna' and 'punycode' encodings, the 'stringprep' module, the
  'mkstringprep' tool, and enhancements to the socket and httplib
  modules.

- htmlentitydefs has two new dictionaries: name2codepoint maps
  HTML entity names to Unicode codepoints (as integers).
  codepoint2name is the reverse mapping. See SF patch #722017.

- pdb has a new command, "debug", which lets you step through
  arbitrary code from the debugger's (pdb) prompt.

- unittest.failUnlessEqual and its equivalent unittest.assertEqual now
  return 'not a == b' rather than 'a != b'.  This gives the desired
  result for classes that define __eq__ without defining __ne__.

- sgmllib now supports SGML marked sections, in particular the
  MS Office extensions.

- The urllib module now offers support for the iterator protocol.
  SF patch 698520 contributed by Brett Cannon.

- New module timeit provides a simple framework for timing the
  execution speed of expressions and statements.

- sets.Set objects now support mixed-type __eq__ and __ne__, instead
  of raising TypeError.  If x is a Set object and y is a non-Set object,
  x == y is False, and x != y is True.  This is akin to the change made
  for mixed-type comparisons of datetime objects in 2.3a2; more info
  about the rationale is in the NEWS entry for that.  See also SF bug
  report <http://www.python.org/sf/693121>.

- On Unix platforms, if os.listdir() is called with a Unicode argument,
  it now returns Unicode strings.  (This behavior was added earlier
  to the Windows NT/2k/XP version of os.listdir().)

- Distutils: both 'py_modules' and 'packages' keywords can now be specified
  in core.setup().  Previously you could supply one or the other, but
  not both of them.  (SF patch #695090 from Bernhard Herzog)

- New csv package makes it easy to read/write CSV files.

- Module shlex has been extended to allow posix-like shell parsings,
  including a split() function for easy spliting of quoted strings and
  commands. An iterator interface was also implemented.

Tools/Demos
-----------

- New script combinerefs.py helps analyze new PYTHONDUMPREFS output.
  See the module docstring for details.

Build
-----

- Fix problem building on OSF1 because the compiler only accepted
  preprocessor directives that start in column 1.  (SF bug #691793.)

C API
-----

- Added PyGC_Collect(), equivalent to calling gc.collect().

- PyThreadState_GetDict() was changed not to raise an exception or
  issue a fatal error when no current thread state is available.  This
  makes it possible to print dictionaries when no thread is active.

- LONG_LONG was renamed to PY_LONG_LONG.  Extensions that use this and
  need compatibility with previous versions can use this:

    #ifndef  PY_LONG_LONG
    #define  PY_LONG_LONG  LONG_LONG
    #endif

- Added PyObject_SelfIter() to fill the tp_iter slot for the
  typical case where the method returns its self argument.

- The extended type structure used for heap types (new-style
  classes defined by Python code using a class statement) is now
  exported from object.h as PyHeapTypeObject.  (SF patch #696193.)

New platforms
-------------

None this time.

Tests
-----

- test_timeout now requires -u network to be passed to regrtest to run.
  See SF bug #692988.

Windows
-------

- os.fsync() now exists on Windows, and calls the Microsoft _commit()
  function.

- New function winsound.MessageBeep() wraps the Win32 API
  MessageBeep().

Mac
---

- os.listdir() now returns Unicode strings on MacOS X when called with
  a Unicode argument. See the general news item under "Library".

- A new method MacOS.WMAvailable() returns true if it is safe to access
  the window manager, false otherwise.

- EasyDialogs dialogs are now movable-modal, and if the application is
  currently in the background they will ask to be moved to the foreground
  before displaying.

- OSA Scripting support has improved a lot, and gensuitemodule.py can now
  be used by mere mortals. The documentation is now also more or less
  complete.

- The IDE (in a framework build) now includes introductory documentation
  in Apple Help Viewer format.


What's New in Python 2.3 alpha 2?
=================================

*Release date: 19-Feb-2003*

Core and builtins
-----------------

- Negative positions returned from PEP 293 error callbacks are now
  treated as being relative to the end of the input string. Positions
  that are out of bounds raise an IndexError.

- sys.path[0] (the directory from which the script is loaded) is now
  turned into an absolute pathname, unless it is the empty string.
  (SF patch #664376.)

- Finally fixed the bug in compile() and exec where a string ending
  with an indented code block but no newline would raise SyntaxError.
  This would have been a four-line change in parsetok.c...  Except
  codeop.py depends on this behavior, so a compilation flag had to be
  invented that causes the tokenizer to revert to the old behavior;
  this required extra changes to 2 .h files, 2 .c files, and 2 .py
  files.  (Fixes SF bug #501622.)

- If a new-style class defines neither __new__ nor __init__, its
  constructor would ignore all arguments.  This is changed now: the
  constructor refuses arguments in this case.  This might break code
  that worked under Python 2.2.  The simplest fix is to add a no-op
  __init__: ``def __init__(self, *args, **kw): pass``.

- Through a bytecode optimizer bug (and I bet you didn't even know
  Python *had* a bytecode optimizer :-), "unsigned" hex/oct constants
  with a leading minus sign would come out with the wrong sign.
  ("Unsigned" hex/oct constants are those with a face value in the
  range sys.maxint+1 through sys.maxint*2+1, inclusive; these have
  always been interpreted as negative numbers through sign folding.)
  E.g. 0xffffffff is -1, and -(0xffffffff) is 1, but -0xffffffff would
  come out as -4294967295.  This was the case in Python 2.2 through
  2.2.2 and 2.3a1, and in Python 2.4 it will once again have that
  value, but according to PEP 237 it really needs to be 1 now.  This
  will be backported to Python 2.2.3 a well.  (SF #660455)

- int(s, base) sometimes sign-folds hex and oct constants; it only
  does this when base is 0 and s.strip() starts with a '0'.  When the
  sign is actually folded, as in int("0xffffffff", 0) on a 32-bit
  machine, which returns -1, a FutureWarning is now issued; in Python
  2.4, this will return 4294967295L, as do int("+0xffffffff", 0) and
  int("0xffffffff", 16) right now.  (PEP 347)

- super(X, x): x may now be a proxy for an X instance, i.e.
  issubclass(x.__class__, X) but not issubclass(type(x), X).

- isinstance(x, X): if X is a new-style class, this is now equivalent
  to issubclass(type(x), X) or issubclass(x.__class__, X).  Previously
  only type(x) was tested.  (For classic classes this was already the
  case.)

- compile(), eval() and the exec statement now fully support source code
  passed as unicode strings.

- int subclasses can be initialized with longs if the value fits in an int.
  See SF bug #683467.

- long(string, base) takes time linear in len(string) when base is a power
  of 2 now.  It used to take time quadratic in len(string).

- filter returns now Unicode results for Unicode arguments.

- raw_input can now return Unicode objects.

- List objects' sort() method now accepts None as the comparison function.
  Passing None is semantically identical to calling sort() with no
  arguments.

- Fixed crash when printing a subclass of str and __str__ returned self.
  See SF bug #667147.

- Fixed an invalid RuntimeWarning and an undetected error when trying
  to convert a long integer into a float which couldn't fit.
  See SF bug #676155.

- Function objects now have a __module__ attribute that is bound to
  the name of the module in which the function was defined.  This
  applies for C functions and methods as well as functions and methods
  defined in Python.  This attribute is used by pickle.whichmodule(),
  which changes the behavior of whichmodule slightly.  In Python 2.2
  whichmodule() returns "__main__" for functions that are not defined
  at the top-level of a module (examples: methods, nested functions).
  Now whichmodule() will return the proper module name.

Extension modules
-----------------

- operator.isNumberType() now checks that the object has a nb_int or
  nb_float slot, rather than simply checking whether it has a non-NULL
  tp_as_number pointer.

- The imp module now has ways to acquire and release the "import
  lock": imp.acquire_lock() and imp.release_lock().  Note: this is a
  reentrant lock, so releasing the lock only truly releases it when
  this is the last release_lock() call.  You can check with
  imp.lock_held().  (SF bug #580952 and patch #683257.)

- Change to cPickle to match pickle.py (see below and PEP 307).

- Fix some bugs in the parser module.  SF bug #678518.

- Thanks to Scott David Daniels, a subtle bug in how the zlib
  extension implemented flush() was fixed.  Scott also rewrote the
  zlib test suite using the unittest module.  (SF bug #640230 and
  patch #678531.)

- Added an itertools module containing high speed, memory efficient
  looping constructs inspired by tools from Haskell and SML.

- The SSL module now handles sockets with a timeout set correctly (SF
  patch #675750, fixing SF bug #675552).

- os/posixmodule has grown the sysexits.h constants (EX_OK and friends).

- Fixed broken threadstate swap in readline that could cause fatal
  errors when a readline hook was being invoked while a background
  thread was active.  (SF bugs #660476 and #513033.)

- fcntl now exposes the strops.h I_* constants.

- Fix a crash on Solaris that occurred when calling close() on
  an mmap'ed file which was already closed.  (SF patch #665913)

- Fixed several serious bugs in the zipimport implementation.

- datetime changes:

  The date class is now properly subclassable.  (SF bug #720908)

  The datetime and datetimetz classes have been collapsed into a single
  datetime class, and likewise the time and timetz classes into a single
  time class.  Previously, a datetimetz object with tzinfo=None acted
  exactly like a datetime object, and similarly for timetz.  This wasn't
  enough of a difference to justify distinct classes, and life is simpler
  now.

  today() and now() now round system timestamps to the closest
  microsecond <http://www.python.org/sf/661086>.  This repairs an
  irritation most likely seen on Windows systems.

  In dt.astimezone(tz), if tz.utcoffset(dt) returns a duration,
  ValueError is raised if tz.dst(dt) returns None (2.3a1 treated it
  as 0 instead, but a tzinfo subclass wishing to participate in
  time zone conversion has to take a stand on whether it supports
  DST; if you don't care about DST, then code dst() to return 0 minutes,
  meaning that DST is never in effect).

  The tzinfo methods utcoffset() and dst() must return a timedelta object
  (or None) now.  In 2.3a1 they could also return an int or long, but that
  was an unhelpfully redundant leftover from an earlier version wherein
  they couldn't return a timedelta.  TOOWTDI.

  The example tzinfo class for local time had a bug.  It was replaced
  by a later example coded by Guido.

  datetime.astimezone(tz) no longer raises an exception when the
  input datetime has no UTC equivalent in tz.  For typical "hybrid" time
  zones (a single tzinfo subclass modeling both standard and daylight
  time), this case can arise one hour per year, at the hour daylight time
  ends.  See new docs for details.  In short, the new behavior mimics
  the local wall clock's behavior of repeating an hour in local time.

  dt.astimezone() can no longer be used to convert between naive and aware
  datetime objects.  If you merely want to attach, or remove, a tzinfo
  object, without any conversion of date and time members, use
  dt.replace(tzinfo=whatever) instead, where "whatever" is None or a
  tzinfo subclass instance.

  A new method tzinfo.fromutc(dt) can be overridden in tzinfo subclasses
  to give complete control over how a UTC time is to be converted to
  a local time.  The default astimezone() implementation calls fromutc()
  as its last step, so a tzinfo subclass can affect that too by overriding
  fromutc().  It's expected that the default fromutc() implementation will
  be suitable as-is for "almost all" time zone subclasses, but the
  creativity of political time zone fiddling appears unbounded -- fromutc()
  allows the highly motivated to emulate any scheme expressible in Python.

  datetime.now():  The optional tzinfo argument was undocumented (that's
  repaired), and its name was changed to tz ("tzinfo" is overloaded enough
  already).  With a tz argument, now(tz) used to return the local date
  and time, and attach tz to it, without any conversion of date and time
  members.  This was less than useful.  Now now(tz) returns the current
  date and time as local time in tz's time zone, akin to ::

      tz.fromutc(datetime.utcnow().replace(tzinfo=utc))

  where "utc" is an instance of a tzinfo subclass modeling UTC.  Without
  a tz argument, now() continues to return the current local date and time,
  as a naive datetime object.

  datetime.fromtimestamp():  Like datetime.now() above, this had less than
  useful behavior when the optional tinzo argument was specified.  See
  also SF bug report <http://www.python.org/sf/660872>.

  date and datetime comparison:  In order to prevent comparison from
  falling back to the default compare-object-addresses strategy, these
  raised TypeError whenever they didn't understand the other object type.
  They still do, except when the other object has a "timetuple" attribute,
  in which case they return NotImplemented now.  This gives other
  datetime objects (e.g., mxDateTime) a chance to intercept the
  comparison.

  date, time, datetime and timedelta comparison:  When the exception
  for mixed-type comparisons in the last paragraph doesn't apply, if
  the comparison is == then False is returned, and if the comparison is
  != then True is returned.  Because dict lookup and the "in" operator
  only invoke __eq__, this allows, for example, ::

      if some_datetime in some_sequence:

  and ::

      some_dict[some_timedelta] = whatever

  to work as expected, without raising TypeError just because the
  sequence is heterogeneous, or the dict has mixed-type keys.  [This
  seems like a good idea to implement for all mixed-type comparisons
  that don't want to allow falling back to address comparison.]

  The constructors building a datetime from a timestamp could raise
  ValueError if the platform C localtime()/gmtime() inserted "leap
  seconds".  Leap seconds are ignored now.  On such platforms, it's
  possible to have timestamps that differ by a second, yet where
  datetimes constructed from them are equal.

  The pickle format of date, time and datetime objects has changed
  completely.  The undocumented pickler and unpickler functions no
  longer exist.  The undocumented __setstate__() and __getstate__()
  methods no longer exist either.

Library
-------

- The logging module was updated slightly; the WARN level was renamed
  to WARNING, and the matching function/method warn() to warning().

- The pickle and cPickle modules were updated with a new pickling
  protocol (documented by pickletools.py, see below) and several
  extensions to the pickle customization API (__reduce__, __setstate__
  etc.).  The copy module now uses more of the pickle customization
  API to copy objects that don't implement __copy__ or __deepcopy__.
  See PEP 307 for details.

- The distutils "register" command now uses http://www.python.org/pypi
  as the default repository.  (See PEP 301.)

- the platform dependent path related variables sep, altsep, extsep,
  pathsep, curdir, pardir and defpath are now defined in the platform
  dependent path modules (e.g. ntpath.py) rather than os.py, so these
  variables are now available via os.path.  They continue to be
  available from the os module.
  (see <http://www.python.org/sf/680789>).

- array.array was added to the types repr.py knows about (see
  <http://www.python.org/sf/680789>).

- The new pickletools.py contains lots of documentation about pickle
  internals, and supplies some helpers for working with pickles, such as
  a symbolic pickle disassembler.

- xmlrpclib.py now supports the built-in boolean type.

- py_compile has a new 'doraise' flag and a new PyCompileError
  exception.

- SimpleXMLRPCServer now supports CGI through the CGIXMLRPCRequestHandler
  class.

- The sets module now raises TypeError in __cmp__, to clarify that
  sets are not intended to be three-way-compared; the comparison
  operators are overloaded as subset/superset tests.

- Bastion.py and rexec.py are disabled.  These modules are not safe in
  Python 2.2. or 2.3.

- realpath is now exported when doing ``from poxixpath import *``.
  It is also exported for ntpath, macpath, and os2emxpath.
  See SF bug #659228.

- New module tarfile from Lars Gustäbel provides a comprehensive interface
  to tar archive files with transparent gzip and bzip2 compression.
  See SF patch #651082.

- urlparse can now parse imap:// URLs.  See SF feature request #618024.

- Tkinter.Canvas.scan_dragto() provides an optional parameter to support
  the gain value which is passed to Tk.  SF bug# 602259.

- Fix logging.handlers.SysLogHandler protocol when using UNIX domain sockets.
  See SF patch #642974.

- The dospath module was deleted.  Use the ntpath module when manipulating
  DOS paths from other platforms.

Tools/Demos
-----------

- Two new scripts (db2pickle.py and pickle2db.py) were added to the
  Tools/scripts directory to facilitate conversion from the old bsddb module
  to the new one.  While the user-visible API of the new module is
  compatible with the old one, it's likely that the version of the
  underlying database library has changed.  To convert from the old library,
  run the db2pickle.py script using the old version of Python to convert it
  to a pickle file.  After upgrading Python, run the pickle2db.py script
  using the new version of Python to reconstitute your database.  For
  example:

    % python2.2 db2pickle.py -h some.db > some.pickle
    % python2.3 pickle2db.py -h some.db.new < some.pickle

  Run the scripts without any args to get a usage message.


Build
-----

- The audio driver tests (test_ossaudiodev.py and
  test_linuxaudiodev.py) are no longer run by default.  This is
  because they don't always work, depending on your hardware and
  software.  To run these tests, you must use an invocation like ::

    ./python Lib/test/regrtest.py -u audio test_ossaudiodev

- On systems which build using the configure script, compiler flags which
  used to be lumped together using the OPT flag have been split into two
  groups, OPT and BASECFLAGS.  OPT is meant to carry just optimization- and
  debug-related flags like "-g" and "-O3".  BASECFLAGS is meant to carry
  compiler flags that are required to get a clean compile.  On some
  platforms (many Linux flavors in particular) BASECFLAGS will be empty by
  default.  On others, such as Mac OS X and SCO, it will contain required
  flags.  This change allows people building Python to override OPT without
  fear of clobbering compiler flags which are required to get a clean build.

- On Darwin/Mac OS X platforms, /sw/lib and /sw/include are added to the
  relevant search lists in setup.py.  This allows users building Python to
  take advantage of the many packages available from the fink project
  <http://fink.sf.net/>.

- A new Makefile target, scriptsinstall, installs a number of useful scripts
  from the Tools/scripts directory.

C API
-----

- PyEval_GetFrame() is now declared to return a ``PyFrameObject *``
  instead of a plain ``PyObject *``.  (SF patch #686601.)

- PyNumber_Check() now checks that the object has a nb_int or nb_float
  slot, rather than simply checking whether it has a non-NULL
  tp_as_number pointer.

- A C type that inherits from a base type that defines tp_as_buffer
  will now inherit the tp_as_buffer pointer if it doesn't define one.
  (SF #681367)

- The PyArg_Parse functions now issue a DeprecationWarning if a float
  argument is provided when an integer is specified (this affects the 'b',
  'B', 'h', 'H', 'i', and 'l' codes).  Future versions of Python will
  raise a TypeError.

Tests
-----

- Several tests weren't being run from regrtest.py (test_timeout.py,
  test_tarfile.py, test_netrc.py, test_multifile.py,
  test_importhooks.py and test_imp.py).  Now they are.  (Note to
  developers: please read Lib/test/README when creating a new test, to
  make sure to do it right!  All tests need to use either unittest or
  pydoc.)

- Added test_posix.py, a test suite for the posix module.

- Added test_hexoct.py, a test suite for hex/oct constant folding.

Windows
-------

- The timeout code for socket connect() didn't work right; this has
  now been fixed.  test_timeout.py should pass (at least most of the
  time).

- distutils' msvccompiler class now passes the preprocessor options to
  the resource compiler.  See SF patch #669198.

- The bsddb module now ships with Sleepycat's 4.1.25.NC, the latest
  release without strong cryptography.

- sys.path[0], if it contains a directory name, is now always an
  absolute pathname. (SF patch #664376.)

- The new logging package is now installed by the Windows installer.  It
  wasn't in 2.3a1 due to oversight.

Mac
---

- There are new dialogs EasyDialogs.AskFileForOpen, AskFileForSave
  and AskFolder. The old macfs.StandardGetFile and friends are deprecated.

- Most of the standard library now uses pathnames or FSRefs in preference
  of FSSpecs, and use the underlying Carbon.File and Carbon.Folder modules
  in stead of macfs. macfs will probably be deprecated in the future.

- Type Carbon.File.FSCatalogInfo and supporting methods have been implemented.
  This also makes macfs.FSSpec.SetDates() work again.

- There is a new module pimp, the package install manager for Python, and
  accompanying applet PackageManager. These allow you to easily download
  and install pretested extension packages either in source or binary
  form. Only in MacPython-OSX.

- Applets are now built with bundlebuilder in MacPython-OSX, which should make
  them more robust and also provides a path towards BuildApplication. The
  downside of this change is that applets can no longer be run from the
  Terminal window, this will hopefully be fixed in the 2.3b1.


What's New in Python 2.3 alpha 1?
=================================

*Release date: 31-Dec-2002*

Type/class unification and new-style classes
--------------------------------------------

- One can now assign to __bases__ and __name__ of new-style classes.

- dict() now accepts keyword arguments so that dict(one=1, two=2)
  is the equivalent of {"one": 1, "two": 2}.  Accordingly,
  the existing (but undocumented) 'items' keyword argument has
  been eliminated.  This means that dict(items=someMapping) now has
  a different meaning than before.

- int() now returns a long object if the argument is outside the
  integer range, so int("4" * 1000), int(1e200) and int(1L<<1000) will
  all return long objects instead of raising an OverflowError.

- Assignment to __class__ is disallowed if either the old or the new
  class is a statically allocated type object (such as defined by an
  extension module).  This prevents anomalies like 2.__class__ = bool.

- New-style object creation and deallocation have been sped up
  significantly; they are now faster than classic instance creation
  and deallocation.

- The __slots__ variable can now mention "private" names, and the
  right thing will happen (e.g. __slots__ = ["__foo"]).

- The built-ins slice() and buffer() are now callable types.  The
  types classobj (formerly class), code, function, instance, and
  instancemethod (formerly instance-method), which have no built-in
  names but are accessible through the types module, are now also
  callable.  The type dict-proxy is renamed to dictproxy.

- Cycles going through the __class__ link of a new-style instance are
  now detected by the garbage collector.

- Classes using __slots__ are now properly garbage collected.
  [SF bug 519621]

- Tightened the __slots__ rules: a slot name must be a valid Python
  identifier.

- The constructor for the module type now requires a name argument and
  takes an optional docstring argument.  Previously, this constructor
  ignored its arguments.  As a consequence, deriving a class from a
  module (not from the module type) is now illegal; previously this
  created an unnamed module, just like invoking the module type did.
  [SF bug 563060]

- A new type object, 'basestring', is added.  This is a common base type
  for 'str' and 'unicode', and can be used instead of
  types.StringTypes, e.g. to test whether something is "a string":
  isinstance(x, basestring) is True for Unicode and 8-bit strings.  This
  is an abstract base class and cannot be instantiated directly.

- Changed new-style class instantiation so that when C's __new__
  method returns something that's not a C instance, its __init__ is
  not called.  [SF bug #537450]

- Fixed super() to work correctly with class methods.  [SF bug #535444]

- If you try to pickle an instance of a class that has __slots__ but
  doesn't define or override __getstate__, a TypeError is now raised.
  This is done by adding a bozo __getstate__ to the class that always
  raises TypeError.  (Before, this would appear to be pickled, but the
  state of the slots would be lost.)

Core and builtins
-----------------

- Import from zipfiles is now supported.  The name of a zipfile placed
  on sys.path causes the import statement to look for importable Python
  modules (with .py, pyc and .pyo extensions) and packages inside the
  zipfile.  The zipfile import follows the specification (though not
  the sample implementation) of PEP 273.  The semantics of __path__ are
  compatible with those that have been implemented in Jython since
  Jython 2.1.

- PEP 302 has been accepted.  Although it was initially developed to
  support zipimport, it offers a new, general import hook mechanism.
  Several new variables have been added to the sys module:
  sys.meta_path, sys.path_hooks, and sys.path_importer_cache; these
  make extending the import statement much more convenient than
  overriding the __import__ built-in function.  For a description of
  these, see PEP 302.

- A frame object's f_lineno attribute can now be written to from a
  trace function to change which line will execute next.  A command to
  exploit this from pdb has been added.  [SF patch #643835]

- The _codecs support module for codecs.py was turned into a built-in
  module to assure that at least the built-in codecs are available
  to the Python parser for source code decoding according to PEP 263.

- issubclass now supports a tuple as the second argument, just like
  isinstance does. ``issubclass(X, (A, B))`` is equivalent to
  ``issubclass(X, A) or issubclass(X, B)``.

- Thanks to Armin Rigo, the last known way to provoke a system crash
  by cleverly arranging for a comparison function to mutate a list
  during a list.sort() operation has been fixed.  The effect of
  attempting to mutate a list, or even to inspect its contents or
  length, while a sort is in progress, is not defined by the language.
  The C implementation of Python 2.3 attempts to detect mutations,
  and raise ValueError if one occurs, but there's no guarantee that
  all mutations will be caught, or that any will be caught across
  releases or implementations.

- Unicode file name processing for Windows (PEP 277) is implemented.
  All platforms now have an os.path.supports_unicode_filenames attribute,
  which is set to True on Windows NT/2000/XP, and False elsewhere.

- Codec error handling callbacks (PEP 293) are implemented.
  Error handling in unicode.encode or str.decode can now be customized.

- A subtle change to the semantics of the built-in function intern():
  interned strings are no longer immortal.  You must keep a reference
  to the return value intern() around to get the benefit.

- Use of 'None' as a variable, argument or attribute name now
  issues a SyntaxWarning.  In the future, None may become a keyword.

- SET_LINENO is gone.  co_lnotab is now consulted to determine when to
  call the trace function.  C code that accessed f_lineno should call
  PyCode_Addr2Line instead (f_lineno is still there, but only kept up
  to date when there is a trace function set).

- There's a new warning category, FutureWarning.  This is used to warn
  about a number of situations where the value or sign of an integer
  result will change in Python 2.4 as a result of PEP 237 (integer
  unification).  The warnings implement stage B0 mentioned in that
  PEP.  The warnings are about the following situations:

    - Octal and hex literals without 'L' prefix in the inclusive range
      [0x80000000..0xffffffff]; these are currently negative ints, but
      in Python 2.4 they will be positive longs with the same bit
      pattern.

    - Left shifts on integer values that cause the outcome to lose
      bits or have a different sign than the left operand.  To be
      precise: x<<n where this currently doesn't yield the same value
      as long(x)<<n; in Python 2.4, the outcome will be long(x)<<n.

    - Conversions from ints to string that show negative values as
      unsigned ints in the inclusive range [0x80000000..0xffffffff];
      this affects the functions hex() and oct(), and the string
      formatting codes %u, %o, %x, and %X.  In Python 2.4, these will
      show signed values (e.g. hex(-1) currently returns "0xffffffff";
      in Python 2.4 it will return "-0x1").

- The bits manipulated under the cover by sys.setcheckinterval() have
  been changed.  Both the check interval and the ticker used to be
  per-thread values.  They are now just a pair of global variables.
  In addition, the default check interval was boosted from 10 to 100
  bytecode instructions.  This may have some effect on systems that
  relied on the old default value.  In particular, in multi-threaded
  applications which try to be highly responsive, response time will
  increase by some (perhaps imperceptible) amount.

- When multiplying very large integers, a version of the so-called
  Karatsuba algorithm is now used.  This is most effective if the
  inputs have roughly the same size.  If they both have about N digits,
  Karatsuba multiplication has O(N**1.58) runtime (the exponent is
  log_base_2(3)) instead of the previous O(N**2).  Measured results may
  be better or worse than that, depending on platform quirks.  Besides
  the O() improvement in raw instruction count, the Karatsuba algorithm
  appears to have much better cache behavior on extremely large integers
  (starting in the ballpark of a million bits).  Note that this is a
  simple implementation, and there's no intent here to compete with,
  e.g., GMP.  It gives a very nice speedup when it applies, but a package
  devoted to fast large-integer arithmetic should run circles around it.

- u'%c' will now raise a ValueError in case the argument is an
  integer outside the valid range of Unicode code point ordinals.

- The tempfile module has been overhauled for enhanced security.  The
  mktemp() function is now deprecated; new, safe replacements are
  mkstemp() (for files) and mkdtemp() (for directories), and the
  higher-level functions NamedTemporaryFile() and TemporaryFile().
  Use of some global variables in this module is also deprecated; the
  new functions have keyword arguments to provide the same
  functionality.  All Lib, Tools and Demo modules that used the unsafe
  interfaces have been updated to use the safe replacements.  Thanks
  to Zack Weinberg!

- When x is an object whose class implements __mul__ and __rmul__,
  1.0*x would correctly invoke __rmul__, but 1*x would erroneously
  invoke __mul__.  This was due to the sequence-repeat code in the int
  type.  This has been fixed now.

- Previously, "str1 in str2" required str1 to be a string of length 1.
  This restriction has been relaxed to allow str1 to be a string of
  any length.  Thus "'el' in 'hello world'" returns True now.

- File objects are now their own iterators.  For a file f, iter(f) now
  returns f (unless f is closed), and f.next() is similar to
  f.readline() when EOF is not reached; however, f.next() uses a
  readahead buffer that messes up the file position, so mixing
  f.next() and f.readline() (or other methods) doesn't work right.
  Calling f.seek() drops the readahead buffer, but other operations
  don't.  It so happens that this gives a nice additional speed boost
  to "for line in file:"; the xreadlines method and corresponding
  module are now obsolete.  Thanks to Oren Tirosh!

- Encoding declarations (PEP 263, phase 1) have been implemented.  A
  comment of the form "# -*- coding: <encodingname> -*-" in the first
  or second line of a Python source file indicates the encoding.

- list.sort() has a new implementation.  While cross-platform results
  may vary, and in data-dependent ways, this is much faster on many
  kinds of partially ordered lists than the previous implementation,
  and reported to be just as fast on randomly ordered lists on
  several major platforms.  This sort is also stable (if A==B and A
  precedes B in the list at the start, A precedes B after the sort too),
  although the language definition does not guarantee stability.  A
  potential drawback is that list.sort() may require temp space of
  len(list)*2 bytes (``*4`` on a 64-bit machine).  It's therefore possible
  for list.sort() to raise MemoryError now, even if a comparison function
  does not.  See <http://www.python.org/sf/587076> for full details.

- All standard iterators now ensure that, once StopIteration has been
  raised, all future calls to next() on the same iterator will also
  raise StopIteration.  There used to be various counterexamples to
  this behavior, which could have caused confusion or subtle program
  breakage, without any benefits.  (Note that this is still an
  iterator's responsibility; the iterator framework does not enforce
  this.)

- Ctrl+C handling on Windows has been made more consistent with
  other platforms.  KeyboardInterrupt can now reliably be caught,
  and Ctrl+C at an interactive prompt no longer terminates the
  process under NT/2k/XP (it never did under Win9x).  Ctrl+C will
  interrupt time.sleep() in the main thread, and any child processes
  created via the popen family (on win2k; we can't make win9x work
  reliably) are also interrupted (as generally happens on for Linux/Unix.)
  [SF bugs 231273, 439992 and 581232]

- sys.getwindowsversion() has been added on Windows.  This
  returns a tuple with information about the version of Windows
  currently running.

- Slices and repetitions of buffer objects now consistently return
  a string.  Formerly, strings would be returned most of the time,
  but a buffer object would be returned when the repetition count
  was one or when the slice range was all inclusive.

- Unicode objects in sys.path are no longer ignored but treated
  as directory names.

- Fixed string.startswith and string.endswith built-in methods
  so they accept negative indices.  [SF bug 493951]

- Fixed a bug with a continue inside a try block and a yield in the
  finally clause.  [SF bug 567538]

- Most built-in sequences now support "extended slices", i.e. slices
  with a third "stride" parameter.  For example, "hello world"[::-1]
  gives "dlrow olleh".

- A new warning PendingDeprecationWarning was added to provide
  direction on features which are in the process of being deprecated.
  The warning will not be printed by default.  To see the pending
  deprecations, use -Walways::PendingDeprecationWarning::
  as a command line option or warnings.filterwarnings() in code.

- Deprecated features of xrange objects have been removed as
  promised.  The start, stop, and step attributes and the tolist()
  method no longer exist.  xrange repetition and slicing have been
  removed.

- New built-in function enumerate(x), from PEP 279.  Example:
  enumerate("abc") is an iterator returning (0,"a"), (1,"b"), (2,"c").
  The argument can be an arbitrary iterable object.

- The assert statement no longer tests __debug__ at runtime.  This means
  that assert statements cannot be disabled by assigning a false value
  to __debug__.

- A method zfill() was added to str and unicode, that fills a numeric
  string to the left with zeros.  For example,
  "+123".zfill(6) -> "+00123".

- Complex numbers supported divmod() and the // and % operators, but
  these make no sense.  Since this was documented, they're being
  deprecated now.

- String and unicode methods lstrip(), rstrip() and strip() now take
  an optional argument that specifies the characters to strip.  For
  example, "Foo!!!?!?!?".rstrip("?!") -> "Foo".

- There's a new dictionary constructor (a class method of the dict
  class), dict.fromkeys(iterable, value=None).  It constructs a
  dictionary with keys taken from the iterable and all values set to a
  single value.  It can be used for building sets and for removing
  duplicates from sequences.

- Added a new dict method pop(key).  This removes and returns the
  value corresponding to key.  [SF patch #539949]

- A new built-in type, bool, has been added, as well as built-in
  names for its two values, True and False.  Comparisons and sundry
  other operations that return a truth value have been changed to
  return a bool instead.  Read PEP 285 for an explanation of why this
  is backward compatible.

- Fixed two bugs reported as SF #535905: under certain conditions,
  deallocating a deeply nested structure could cause a segfault in the
  garbage collector, due to interaction with the "trashcan" code;
  access to the current frame during destruction of a local variable
  could access a pointer to freed memory.

- The optional object allocator ("pymalloc") has been enabled by
  default.  The recommended practice for memory allocation and
  deallocation has been streamlined.  A header file is included,
  Misc/pymemcompat.h, which can be bundled with 3rd party extensions
  and lets them use the same API with Python versions from 1.5.2
  onwards.

- PyErr_Display will provide file and line information for all exceptions
  that have an attribute print_file_and_line, not just SyntaxErrors.

- The UTF-8 codec will now encode and decode Unicode surrogates
  correctly and without raising exceptions for unpaired ones.

- Universal newlines (PEP 278) is implemented.  Briefly, using 'U'
  instead of 'r' when opening a text file for reading changes the line
  ending convention so that any of '\r', '\r\n', and '\n' is
  recognized (even mixed in one file); all three are converted to
  '\n', the standard Python line end character.

- file.xreadlines() now raises a ValueError if the file is closed:
  Previously, an xreadlines object was returned which would raise
  a ValueError when the xreadlines.next() method was called.

- sys.exit() inadvertently allowed more than one argument.
  An exception will now be raised if more than one argument is used.

- Changed evaluation order of dictionary literals to conform to the
  general left to right evaluation order rule. Now {f1(): f2()} will
  evaluate f1 first.

- Fixed bug #521782: when a file was in non-blocking mode, file.read()
  could silently lose data or wrongly throw an unknown error.

- The sq_repeat, sq_inplace_repeat, sq_concat and sq_inplace_concat
  slots are now always tried after trying the corresponding nb_* slots.
  This fixes a number of minor bugs (see bug #624807).

- Fix problem with dynamic loading on 64-bit AIX (see bug #639945).

Extension modules
-----------------

- Added three operators to the operator module:
    operator.pow(a,b) which is equivalent to:  a**b.
    operator.is_(a,b) which is equivalent to:  a is b.
    operator.is_not(a,b) which is equivalent to:  a is not b.

- posix.openpty now works on all systems that have /dev/ptmx.

- A module zipimport exists to support importing code from zip
  archives.

- The new datetime module supplies classes for manipulating dates and
  times.  The basic design came from the Zope "fishbowl process", and
  favors practical commercial applications over calendar esoterica.  See

      http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage

- _tkinter now returns Tcl objects, instead of strings. Objects which
  have Python equivalents are converted to Python objects, other objects
  are wrapped. This can be configured through the wantobjects method,
  or Tkinter.wantobjects.

- The PyBSDDB wrapper around the Sleepycat Berkeley DB library has
  been added as the package bsddb.  The traditional bsddb module is
  still available in source code, but not built automatically anymore,
  and is now named bsddb185.  This supports Berkeley DB versions from
  3.0 to 4.1.  For help converting your databases from the old module (which
  probably used an obsolete version of Berkeley DB) to the new module, see
  the db2pickle.py and pickle2db.py scripts described in the Tools/Demos
  section above.

- unicodedata was updated to Unicode 3.2. It supports normalization
  and names for Hangul syllables and CJK unified ideographs.

- resource.getrlimit() now returns longs instead of ints.

- readline now dynamically adjusts its input/output stream if
  sys.stdin/stdout changes.

- The _tkinter module (and hence Tkinter) has dropped support for
  Tcl/Tk 8.0 and 8.1.  Only Tcl/Tk versions 8.2, 8.3 and 8.4 are
  supported.

- cPickle.BadPickleGet is now a class.

- The time stamps in os.stat_result are floating point numbers
  after stat_float_times has been called.

- If the size passed to mmap.mmap() is larger than the length of the
  file on non-Windows platforms, a ValueError is raised. [SF bug 585792]

- The xreadlines module is slated for obsolescence.

- The strptime function in the time module is now always available (a
  Python implementation is used when the C library doesn't define it).

- The 'new' module is no longer an extension, but a Python module that
  only exists for backwards compatibility.  Its contents are no longer
  functions but callable type objects.

- The bsddb.*open functions can now take 'None' as a filename.
  This will create a temporary in-memory bsddb that won't be
  written to disk.

- posix.getloadavg, posix.lchown, posix.killpg, posix.mknod, and
  posix.getpgid have been added where available.

- The locale module now exposes the C library's gettext interface. It
  also has a new function getpreferredencoding.

- A security hole ("double free") was found in zlib-1.1.3, a popular
  third party compression library used by some Python modules.  The
  hole was quickly plugged in zlib-1.1.4, and the Windows build of
  Python now ships with zlib-1.1.4.

- pwd, grp, and resource return enhanced tuples now, with symbolic
  field names.

- array.array is now a type object. A new format character
  'u' indicates Py_UNICODE arrays. For those, .tounicode and
  .fromunicode methods are available. Arrays now support __iadd__
  and __imul__.

- dl now builds on every system that has dlfcn.h.  Failure in case
  of sizeof(int)!=sizeof(long)!=sizeof(void*) is delayed until dl.open
  is called.

- The sys module acquired a new attribute, api_version, which evaluates
  to the value of the PYTHON_API_VERSION macro with which the
  interpreter was compiled.

- Fixed bug #470582: sre module would return a tuple (None, 'a', 'ab')
  when applying the regular expression '^((a)c)?(ab)$' on 'ab'. It now
  returns (None, None, 'ab'), as expected. Also fixed handling of
  lastindex/lastgroup match attributes in similar cases. For example,
  when running the expression r'(a)(b)?b' over 'ab', lastindex must be
  1, not 2.

- Fixed bug #581080: sre scanner was not checking the buffer limit
  before increasing the current pointer. This was creating an infinite
  loop in the search function, once the pointer exceeded the buffer
  limit.

- The os.fdopen function now enforces a file mode starting with the
  letter 'r', 'w' or 'a', otherwise a ValueError is raised. This fixes
  bug #623464.

- The linuxaudiodev module is now deprecated; it is being replaced by
  ossaudiodev.  The interface has been extended to cover a lot more of
  OSS (see www.opensound.com), including most DSP ioctls and the
  OSS mixer API.  Documentation forthcoming in 2.3a2.

Library
-------

- imaplib.py now supports SSL (Tino Lange and Piers Lauder).

- Freeze's modulefinder.py has been moved to the standard library;
  slightly improved so it will issue less false missing submodule
  reports (see sf path #643711 for details).  Documentation will follow
  with Python 2.3a2.

- os.path exposes getctime.

- unittest.py now has two additional methods called assertAlmostEqual()
  and failIfAlmostEqual().  They implement an approximate comparison
  by rounding the difference between the two arguments and comparing
  the result to zero.  Approximate comparison is essential for
  unit tests of floating point results.

- calendar.py now depends on the new datetime module rather than
  the time module.  As a result, the range of allowable dates
  has been increased.

- pdb has a new 'j(ump)' command to select the next line to be
  executed.

- The distutils created windows installers now can run a
  postinstallation script.

- doctest.testmod can now be called without argument, which means to
  test the current module.

- When canceling a server that implemented threading with a keyboard
  interrupt, the server would shut down but not terminate (waiting on
  client threads). A new member variable, daemon_threads, was added to
  the ThreadingMixIn class in SocketServer.py to make it explicit that
  this behavior needs to be controlled.

- A new module, optparse, provides a fancy alternative to getopt for
  command line parsing.  It is a slightly modified version of Greg
  Ward's Optik package.

- UserDict.py now defines a DictMixin class which defines all dictionary
  methods for classes that already have a minimum mapping interface.
  This greatly simplifies writing classes that need to be substitutable
  for dictionaries (such as the shelve module).

- shelve.py now subclasses from UserDict.DictMixin.  Now shelve supports
  all dictionary methods.  This eases the transition to persistent
  storage for scripts originally written with dictionaries in mind.

- shelve.open and the various classes in shelve.py now accept an optional
  binary flag, which defaults to False.  If True, the values stored in the
  shelf are binary pickles.

- A new package, logging, implements the logging API defined by PEP
  282.  The code is written by Vinay Sajip.

- StreamReader, StreamReaderWriter and StreamRecoder in the codecs
  modules are iterators now.

- gzip.py now handles files exceeding 2GB.  Files over 4GB also work
  now (provided the OS supports it, and Python is configured with large
  file support), but in that case the underlying gzip file format can
  record only the least-significant 32 bits of the file size, so that
  some tools working with gzipped files may report an incorrect file
  size.

- xml.sax.saxutils.unescape has been added, to replace entity references
  with their entity value.

- Queue.Queue.{put,get} now support an optional timeout argument.

- Various features of Tk 8.4 are exposed in Tkinter.py. The multiple
  option of tkFileDialog is exposed as function askopenfile{,name}s.

- Various configure methods of Tkinter have been stream-lined, so that
  tag_configure, image_configure, window_configure now return a
  dictionary when invoked with no argument.

- Importing the readline module now no longer has the side effect of
  calling setlocale(LC_CTYPE, "").  The initial "C" locale, or
  whatever locale is explicitly set by the user, is preserved.  If you
  want repr() of 8-bit strings in your preferred encoding to preserve
  all printable characters of that encoding, you have to add the
  following code to your $PYTHONSTARTUP file or to your application's
  main():

    import locale
    locale.setlocale(locale.LC_CTYPE, "")

- shutil.move was added. shutil.copytree now reports errors as an
  exception at the end, instead of printing error messages.

- Encoding name normalization was generalized to not only
  replace hyphens with underscores, but also all other non-alphanumeric
  characters (with the exception of the dot which is used for Python
  package names during lookup). The aliases.py mapping was updated
  to the new standard.

- mimetypes has two new functions: guess_all_extensions() which
  returns a list of all known extensions for a mime type, and
  add_type() which adds one mapping between a mime type and
  an extension to the database.

- New module: sets, defines the class Set that implements a mutable
  set type using the keys of a dict to represent the set.  There's
  also a class ImmutableSet which is useful when you need sets of sets
  or when you need to use sets as dict keys, and a class BaseSet which
  is the base class of the two.

- Added random.sample(population,k) for random sampling without replacement.
  Returns a k length list of unique elements chosen from the population.

- random.randrange(-sys.maxint-1, sys.maxint) no longer raises
  OverflowError.  That is, it now accepts any combination of 'start'
  and 'stop' arguments so long as each is in the range of Python's
  bounded integers.

- Thanks to Raymond Hettinger, random.random() now uses a new core
  generator.  The Mersenne Twister algorithm is implemented in C,
  threadsafe, faster than the previous generator, has an astronomically
  large period (2**19937-1), creates random floats to full 53-bit
  precision, and may be the most widely tested random number generator
  in existence.

  The random.jumpahead(n) method has different semantics for the new
  generator.  Instead of jumping n steps ahead, it uses n and the
  existing state to create a new state.  This means that jumpahead()
  continues to support multi-threaded code needing generators of
  non-overlapping sequences.  However, it will break code which relies
  on jumpahead moving a specific number of steps forward.

  The attributes random.whseed and random.__whseed have no meaning for
  the new generator.  Code using these attributes should switch to a
  new class, random.WichmannHill which is provided for backward
  compatibility and to make an alternate generator available.

- New "algorithms" module: heapq, implements a heap queue.  Thanks to
  Kevin O'Connor for the code and François Pinard for an entertaining
  write-up explaining the theory and practical uses of heaps.

- New encoding for the Palm OS character set: palmos.

- binascii.crc32() and the zipfile module had problems on some 64-bit
  platforms.  These have been fixed.  On a platform with 8-byte C longs,
  crc32() now returns a signed-extended 4-byte result, so that its value
  as a Python int is equal to the value computed a 32-bit platform.

- xml.dom.minidom.toxml and toprettyxml now take an optional encoding
  argument.

- Some fixes in the copy module: when an object is copied through its
  __reduce__ method, there was no check for a __setstate__ method on
  the result [SF patch 565085]; deepcopy should treat instances of
  custom metaclasses the same way it treats instances of type 'type'
  [SF patch 560794].

- Sockets now support timeout mode.  After s.settimeout(T), where T is
  a float expressing seconds, subsequent operations raise an exception
  if they cannot be completed within T seconds.  To disable timeout
  mode, use s.settimeout(None).  There's also a module function,
  socket.setdefaulttimeout(T), which sets the default for all sockets
  created henceforth.

- getopt.gnu_getopt was added.  This supports GNU-style option
  processing, where options can be mixed with non-option arguments.

- Stop using strings for exceptions.  String objects used for
  exceptions are now classes deriving from Exception.  The objects
  changed were: Tkinter.TclError, bdb.BdbQuit, macpath.norm_error,
  tabnanny.NannyNag, and xdrlib.Error.

- Constants BOM_UTF8, BOM_UTF16, BOM_UTF16_LE, BOM_UTF16_BE,
  BOM_UTF32, BOM_UTF32_LE and BOM_UTF32_BE that represent the Byte
  Order Mark in UTF-8, UTF-16 and UTF-32 encodings for little and
  big endian systems were added to the codecs module. The old names
  BOM32_* and BOM64_* were off by a factor of 2.

- Added conversion functions math.degrees() and math.radians().

- math.log() now takes an optional argument:  math.log(x[, base]).

- ftplib.retrlines() now tests for callback is None rather than testing
  for False.  Was causing an error when given a callback object which
  was callable but also returned len() as zero.  The change may
  create new breakage if the caller relied on the undocumented behavior
  and called with callback set to [] or some other False value not
  identical to None.

- random.gauss() uses a piece of hidden state used by nothing else,
  and the .seed() and .whseed() methods failed to reset it.  In other
  words, setting the seed didn't completely determine the sequence of
  results produced by random.gauss().  It does now.  Programs repeatedly
  mixing calls to a seed method with calls to gauss() may see different
  results now.

- The pickle.Pickler class grew a clear_memo() method to mimic that
  provided by cPickle.Pickler.

- difflib's SequenceMatcher class now does a dynamic analysis of
  which elements are so frequent as to constitute noise.  For
  comparing files as sequences of lines, this generally works better
  than the IS_LINE_JUNK function, and function ndiff's linejunk
  argument defaults to None now as a result.  A happy benefit is
  that SequenceMatcher may run much faster now when applied
  to large files with many duplicate lines (for example, C program
  text with lots of repeated "}" and "return NULL;" lines).

- New Text.dump() method in Tkinter module.

- New distutils commands for building packagers were added to
  support pkgtool on Solaris and swinstall on HP-UX.

- distutils now has a new abstract binary packager base class
  command/bdist_packager, which simplifies writing packagers.
  This will hopefully provide the missing bits to encourage
  people to submit more packagers, e.g. for Debian, FreeBSD
  and other systems.

- The UTF-16, -LE and -BE stream readers now raise a
  NotImplementedError for all calls to .readline(). Previously, they
  used to just produce garbage or fail with an encoding error --
  UTF-16 is a 2-byte encoding and the C lib's line reading APIs don't
  work well with these.

- compileall now supports quiet operation.

- The BaseHTTPServer now implements optional HTTP/1.1 persistent
  connections.

- socket module: the SSL support was broken out of the main
  _socket module C helper and placed into a new _ssl helper
  which now gets imported by socket.py if available and working.

- encodings package: added aliases for all supported IANA character
  sets

- ftplib: to safeguard the user's privacy, anonymous login will use
  "anonymous@" as default password, rather than the real user and host
  name.

- webbrowser: tightened up the command passed to os.system() so that
  arbitrary shell code can't be executed because a bogus URL was
  passed in.

- gettext.translation has an optional fallback argument, and
  gettext.find an optional all argument. Translations will now fallback
  on a per-message basis. The module supports plural forms, by means
  of gettext.[d]ngettext and Translation.[u]ngettext.

- distutils bdist commands now offer a --skip-build option.

- warnings.warn now accepts a Warning instance as first argument.

- The xml.sax.expatreader.ExpatParser class will no longer create
  circular references by using itself as the locator that gets passed
  to the content handler implementation.  [SF bug #535474]

- The email.Parser.Parser class now properly parses strings regardless
  of their line endings, which can be any of \r, \n, or \r\n (CR, LF,
  or CRLF).  Also, the Header class's constructor default arguments
  has changed slightly so that an explicit maxlinelen value is always
  honored, and so unicode conversion error handling can be specified.

- distutils' build_ext command now links C++ extensions with the C++
  compiler available in the Makefile or CXX environment variable, if
  running under \*nix.

- New module bz2: provides a comprehensive interface for the bz2 compression
  library.  It implements a complete file interface, one-shot (de)compression
  functions, and types for sequential (de)compression.

- New pdb command 'pp' which is like 'p' except that it pretty-prints
  the value of its expression argument.

- Now bdist_rpm distutils command understands a verify_script option in
  the config file, including the contents of the referred filename in
  the "%verifyscript" section of the rpm spec file.

- Fixed bug #495695: webbrowser module would run graphic browsers in a
  unix environment even if DISPLAY was not set. Also, support for
  skipstone browser was included.

- Fixed bug #636769: rexec would run unallowed code if subclasses of
  strings were used as parameters for certain functions.

Tools/Demos
-----------

- pygettext.py now supports globbing on Windows, and accepts module
  names in addition to accepting file names.

- The SGI demos (Demo/sgi) have been removed.  Nobody thought they
  were interesting any more.  (The SGI library modules and extensions
  are still there; it is believed that at least some of these are
  still used and useful.)

- IDLE supports the new encoding declarations (PEP 263); it can also
  deal with legacy 8-bit files if they use the locale's encoding. It
  allows non-ASCII strings in the interactive shell and executes them
  in the locale's encoding.

- freeze.py now produces binaries which can import shared modules,
  unlike before when this failed due to missing symbol exports in
  the generated binary.

Build
-----

- On Unix, IDLE is now installed automatically.

- The fpectl module is not built by default; it's dangerous or useless
  except in the hands of experts.

- The public Python C API will generally be declared using PyAPI_FUNC
  and PyAPI_DATA macros, while Python extension module init functions
  will be declared with PyMODINIT_FUNC.  DL_EXPORT/DL_IMPORT macros
  are deprecated.

- A bug was fixed that could cause COUNT_ALLOCS builds to segfault, or
  get into infinite loops, when a new-style class got garbage-collected.
  Unfortunately, to avoid this, the way COUNT_ALLOCS works requires
  that new-style classes be immortal in COUNT_ALLOCS builds.  Note that
  COUNT_ALLOCS is not enabled by default, in either release or debug
  builds, and that new-style classes are immortal only in COUNT_ALLOCS
  builds.

- Compiling out the cyclic garbage collector is no longer an option.
  The old symbol WITH_CYCLE_GC is now ignored, and Python.h arranges
  that it's always defined (for the benefit of any extension modules
  that may be conditionalizing on it).  A bonus is that any extension
  type participating in cyclic gc can choose to participate in the
  Py_TRASHCAN mechanism now too; in the absence of cyclic gc, this used
  to require editing the core to teach the trashcan mechanism about the
  new type.

- According to Annex F of the current C standard,

    The Standard C macro HUGE_VAL and its float and long double analogs,
    HUGE_VALF and HUGE_VALL, expand to expressions whose values are
    positive infinities.

  Python only uses the double HUGE_VAL, and only to #define its own symbol
  Py_HUGE_VAL.  Some platforms have incorrect definitions for HUGE_VAL.
  pyport.h used to try to worm around that, but the workarounds triggered
  other bugs on other platforms, so we gave up.  If your platform defines
  HUGE_VAL incorrectly, you'll need to #define Py_HUGE_VAL to something
  that works on your platform.  The only instance of this I'm sure about
  is on an unknown subset of Cray systems, described here:

  http://www.cray.com/swpubs/manuals/SN-2194_2.0/html-SN-2194_2.0/x3138.htm

  Presumably 2.3a1 breaks such systems.  If anyone uses such a system, help!

- The configure option --without-doc-strings can be used to remove the
  doc strings from the built-in functions and modules; this reduces the
  size of the executable.

- The universal newlines option (PEP 278) is on by default.  On Unix
  it can be disabled by passing --without-universal-newlines to the
  configure script.  On other platforms, remove
  WITH_UNIVERSAL_NEWLINES from pyconfig.h.

- On Unix, a shared libpython2.3.so can be created with --enable-shared.

- All uses of the CACHE_HASH, INTERN_STRINGS, and DONT_SHARE_SHORT_STRINGS
  preprocessor symbols were eliminated.  The internal decisions they
  controlled stopped being experimental long ago.

- The tools used to build the documentation now work under Cygwin as
  well as Unix.

- The bsddb and dbm module builds have been changed to try and avoid version
  skew problems and disable linkage with Berkeley DB 1.85 unless the
  installer knows what s/he's doing.  See the section on building these
  modules in the README file for details.

C API
-----

- PyNumber_Check() now returns true for string and unicode objects.
  This is a result of these types having a partially defined
  tp_as_number slot.  (This is not a feature, but an indication that
  PyNumber_Check() is not very useful to determine numeric behavior.
  It may be deprecated.)

- The string object's layout has changed: the pointer member
  ob_sinterned has been replaced by an int member ob_sstate.  On some
  platforms (e.g. most 64-bit systems) this may change the offset of
  the ob_sval member, so as a precaution the API_VERSION has been
  incremented.  The apparently unused feature of "indirect interned
  strings", supported by the ob_sinterned member, is gone.  Interned
  strings are now usually mortal; there is a new API,
  PyString_InternImmortal() that creates immortal interned strings.
  (The ob_sstate member can only take three values; however, while
  making it a char saves a few bytes per string object on average, in
  it also slowed things down a bit because ob_sval was no longer
  aligned.)

- The Py_InitModule*() functions now accept NULL for the 'methods'
  argument.  Modules without global functions are becoming more common
  now that factories can be types rather than functions.

- New C API PyUnicode_FromOrdinal() which exposes unichr() at C
  level.

- New functions PyErr_SetExcFromWindowsErr() and
  PyErr_SetExcFromWindowsErrWithFilename(). Similar to
  PyErr_SetFromWindowsErrWithFilename() and
  PyErr_SetFromWindowsErr(), but they allow specifying
  the exception type to raise. Available on Windows.

- Py_FatalError() is now declared as taking a const char* argument.  It
  was previously declared without const.  This should not affect working
  code.

- Added new macro PySequence_ITEM(o, i) that directly calls
  sq_item without rechecking that o is a sequence and without
  adjusting for negative indices.

- PyRange_New() now raises ValueError if the fourth argument is not 1.
  This is part of the removal of deprecated features of the xrange
  object.

- PyNumber_Coerce() and PyNumber_CoerceEx() now also invoke the type's
  coercion if both arguments have the same type but this type has the
  CHECKTYPES flag set.  This is to better support proxies.

- The type of tp_free has been changed from "``void (*)(PyObject *)``" to
  "``void (*)(void *)``".

- PyObject_Del, PyObject_GC_Del are now functions instead of macros.

- A type can now inherit its metatype from its base type.  Previously,
  when PyType_Ready() was called, if ob_type was found to be NULL, it
  was always set to &PyType_Type; now it is set to base->ob_type,
  where base is tp_base, defaulting to &PyObject_Type.

- PyType_Ready() accidentally did not inherit tp_is_gc; now it does.

- The PyCore_* family of APIs have been removed.

- The "u#" parser marker will now pass through Unicode objects as-is
  without going through the buffer API.

- The enumerators of cmp_op have been renamed to use the prefix ``PyCmp_``.

- An old #define of ANY as void has been removed from pyport.h.  This
  hasn't been used since Python's pre-ANSI days, and the #define has
  been marked as obsolete since then.  SF bug 495548 says it created
  conflicts with other packages, so keeping it around wasn't harmless.

- Because Python's magic number scheme broke on January 1st, we decided
  to stop Python development.  Thanks for all the fish!

- Some of us don't like fish, so we changed Python's magic number
  scheme to a new one. See Python/import.c for details.

New platforms
-------------

- OpenVMS is now supported.

- AtheOS is now supported.

- the EMX runtime environment on OS/2 is now supported.

- GNU/Hurd is now supported.

Tests
-----

- The regrtest.py script's -u option now provides a way to say "allow
  all resources except this one."  For example, to allow everything
  except bsddb, give the option '-uall,-bsddb'.

Windows
-------

- The Windows distribution now ships with version 4.0.14 of the
  Sleepycat Berkeley database library.  This should be a huge
  improvement over the previous Berkeley DB 1.85, which had many
  bugs.
  XXX What are the licensing issues here?
  XXX If a user has a database created with a previous version of
  XXX     Python, what must they do to convert it?
  XXX I'm still not sure how to link this thing (see PCbuild/readme.txt).
  XXX The version # is likely to change before 2.3a1.

- The Windows distribution now ships with a Secure Sockets Library (SLL)
   module (_ssl.pyd)

- The Windows distribution now ships with Tcl/Tk version 8.4.1 (it
  previously shipped with Tcl/Tk 8.3.2).

- When Python is built under a Microsoft compiler, sys.version now
  includes the compiler version number (_MSC_VER).  For example, under
  MSVC 6, sys.version contains the substring "MSC v.1200 ".  1200 is
  the value of _MSC_VER under MSVC 6.

- Sometimes the uninstall executable (UNWISE.EXE) vanishes.  One cause
  of that has been fixed in the installer (disabled Wise's "delete in-
  use files" uninstall option).

- Fixed a bug in urllib's proxy handling in Windows.  [SF bug #503031]

- The installer now installs Start menu shortcuts under (the local
  equivalent of) "All Users" when doing an Admin install.

- file.truncate([newsize]) now works on Windows for all newsize values.
  It used to fail if newsize didn't fit in 32 bits, reflecting a
  limitation of MS _chsize (which is no longer used).

- os.waitpid() is now implemented for Windows, and can be used to block
  until a specified process exits.  This is similar to, but not exactly
  the same as, os.waitpid() on POSIX systems.  If you're waiting for
  a specific process whose pid was obtained from one of the spawn()
  functions, the same Python os.waitpid() code works across platforms.
  See the docs for details.  The docs were changed to clarify that
  spawn functions return, and waitpid requires, a process handle on
  Windows (not the same thing as a Windows process id).

- New tempfile.TemporaryFile implementation for Windows:  this doesn't
  need a TemporaryFileWrapper wrapper anymore, and should be immune
  to a nasty problem:  before 2.3, if you got a temp file on Windows, it
  got wrapped in an object whose close() method first closed the
  underlying file, then deleted the file.  This usually worked fine.
  However, the spawn family of functions on Windows create (at a low C
  level) the same set of open files in the spawned process Q as were
  open in the spawning process P.  If a temp file f was among them, then
  doing f.close() in P first closed P's C-level file handle on f, but Q's
  C-level file handle on f remained open, so the attempt in P to delete f
  blew up with a "Permission denied" error (Windows doesn't allow
  deleting open files).  This was surprising, subtle, and difficult to
  work around.

- The os module now exports all the symbolic constants usable with the
  low-level os.open() on Windows:  the new constants in 2.3 are
  O_NOINHERIT, O_SHORT_LIVED, O_TEMPORARY, O_RANDOM and O_SEQUENTIAL.
  The others were also available in 2.2:  O_APPEND, O_BINARY, O_CREAT,
  O_EXCL, O_RDONLY, O_RDWR, O_TEXT, O_TRUNC and O_WRONLY.  Contrary
  to Microsoft docs, O_SHORT_LIVED does not seem to imply O_TEMPORARY
  (so specify both if you want both; note that neither is useful unless
  specified with O_CREAT too).

Mac
----

- Mac/Relnotes is gone, the release notes are now here.

- Python (the OSX-only, unix-based version, not the OS9-compatible CFM
  version) now fully supports unicode strings as arguments to various file
  system calls, eg. open(), file(), os.stat() and os.listdir().

- The current naming convention for Python on the Macintosh is that MacPython
  refers to the unix-based OSX-only version, and MacPython-OS9 refers to the
  CFM-based version that runs on both OS9 and OSX.

- All MacPython-OS9 functionality is now available in an OSX unix build,
  including the Carbon modules, the IDE, OSA support, etc. A lot of this
  will only work correctly in a framework build, though, because you cannot
  talk to the window manager unless your application is run from a .app
  bundle. There is a command line tool "pythonw" that runs your script
  with an interpreter living in such a .app bundle, this interpreter should
  be used to run any Python script using the window manager (including
  Tkinter or wxPython scripts).

- Most of Mac/Lib has moved to Lib/plat-mac, which is again used both in
  MacPython-OSX and MacPython-OS9. The only modules remaining in Mac/Lib
  are specifically for MacPython-OS9 (CFM support, preference resources, etc).

- A new utility PythonLauncher will start a Python interpreter when a .py or
  .pyw script is double-clicked in the Finder. By default .py scripts are
  run with a normal Python interpreter in a Terminal window and .pyw
  files are run with a window-aware pythonw interpreter without a Terminal
  window, but all this can be customized.

- MacPython-OS9 is now Carbon-only, so it runs on Mac OS 9 or Mac OS X and
  possibly on Mac OS 8.6 with the right CarbonLib installed, but not on earlier
  releases.

- Many tools such as BuildApplet.py and gensuitemodule.py now support a command
  line interface too.

- All the Carbon classes are now PEP253 compliant, meaning that you can
  subclass them from Python. Most of the attributes have gone, you should
  now use the accessor function call API, which is also what Apple's
  documentation uses. Some attributes such as grafport.visRgn are still
  available for convenience.

- New Carbon modules File (implementing the APIs in Files.h and Aliases.h)
  and Folder (APIs from Folders.h). The old macfs built-in module is
  gone, and replaced by a Python wrapper around the new modules.

- Pathname handling should now be fully consistent: MacPython-OSX always uses
  unix pathnames and MacPython-OS9 always uses colon-separated Mac pathnames
  (also when running on Mac OS X).

- New Carbon modules Help and AH give access to the Carbon Help Manager.
  There are hooks in the IDE to allow accessing the Python documentation
  (and Apple's Carbon and Cocoa documentation) through the Help Viewer.
  See Mac/OSX/README for converting the Python documentation to a
  Help Viewer compatible form and installing it.

- OSA support has been redesigned and the generated Python classes now
  mirror the inheritance defined by the underlying OSA classes.

- MacPython no longer maps both \r and \n to \n on input for any text file.
  This feature has been replaced by universal newline support (PEP278).

- The default encoding for Python sourcefiles in MacPython-OS9 is no longer
  mac-roman (or whatever your local Mac encoding was) but "ascii", like on
  other platforms. If you really need sourcefiles with Mac characters in them
  you can change this in site.py.


What's New in Python 2.2 final?
===============================

*Release date: 21-Dec-2001*

Type/class unification and new-style classes
--------------------------------------------

- pickle.py, cPickle: allow pickling instances of new-style classes
  with a custom metaclass.

Core and builtins
-----------------

- weakref proxy object: when comparing, unwrap both arguments if both
  are proxies.

Extension modules
-----------------

- binascii.b2a_base64(): fix a potential buffer overrun when encoding
  very short strings.

- cPickle: the obscure "fast" mode was suspected of causing stack
  overflows on the Mac.  Hopefully fixed this by setting the recursion
  limit much smaller.  If the limit is too low (it only affects
  performance), you can change it by defining PY_CPICKLE_FAST_LIMIT
  when compiling cPickle.c (or in pyconfig.h).

Library
-------

- dumbdbm.py: fixed a dumb old bug (the file didn't get synched at
  close or delete time).

- rfc822.py: fixed a bug where the address '<>' was converted to None
  instead of an empty string (also fixes the email.Utils module).

- xmlrpclib.py: version 1.0.0; uses precision for doubles.

- test suite: the pickle and cPickle tests were not executing any code
  when run from the standard regression test.

Tools/Demos
-----------

Build
-----

C API
-----

New platforms
-------------

Tests
-----

Windows
-------

- distutils package: fixed broken Windows installers (bdist_wininst).

- tempfile.py: prevent mysterious warnings when TemporaryFileWrapper
  instances are deleted at process exit time.

- socket.py: prevent mysterious warnings when socket instances are
  deleted at process exit time.

- posixmodule.c: fix a Windows crash with stat() of a filename ending
  in backslash.

Mac
----

- The Carbon toolbox modules have been upgraded to Universal Headers
  3.4, and experimental CoreGraphics and CarbonEvents modules have
  been added.  All only for framework-enabled MacOSX.


What's New in Python 2.2c1?
===========================

*Release date: 14-Dec-2001*

Type/class unification and new-style classes
--------------------------------------------

- Guido's tutorial introduction to the new type/class features has
  been extensively updated.  See

      http://www.python.org/2.2/descrintro.html

  That remains the primary documentation in this area.

- Fixed a leak: instance variables declared with __slots__ were never
  deleted!

- The "delete attribute" method of descriptor objects is called
  __delete__, not __del__.  In previous releases, it was mistakenly
  called __del__, which created an unfortunate overloading condition
  with finalizers.  (The "get attribute" and "set attribute" methods
  are still called __get__ and __set__, respectively.)

- Some subtle issues with the super built-in were fixed:

  (a) When super itself is subclassed, its __get__ method would still
      return an instance of the base class (i.e., of super).

  (b) super(C, C()).__class__ would return C rather than super.  This
      is confusing.  To fix this, I decided to change the semantics of
      super so that it only applies to code attributes, not to data
      attributes.  After all, overriding data attributes is not
      supported anyway.

  (c) The __get__ method didn't check whether the argument was an
      instance of the type used in creation of the super instance.

- Previously, hash() of an instance of a subclass of a mutable type
  (list or dictionary) would return some value, rather than raising
  TypeError.  This has been fixed.  Also, directly calling
  dict.__hash__ and list.__hash__ now raises the same TypeError
  (previously, these were the same as object.__hash__).

- New-style objects now support deleting their __dict__.  This is for
  all intents and purposes equivalent to assigning a brand new empty
  dictionary, but saves space if the object is not used further.

Core and builtins
-----------------

- -Qnew now works as documented in PEP 238:  when -Qnew is passed on
  the command line, all occurrences of "/" use true division instead
  of classic division.  See the PEP for details.  Note that "all"
  means all instances in library and 3rd-party modules, as well as in
  your own code.  As the PEP says, -Qnew is intended for use only in
  educational environments with control over the libraries in use.
  Note that test_coercion.py in the standard Python test suite fails
  under -Qnew; this is expected, and won't be repaired until true
  division becomes the default (in the meantime, test_coercion is
  testing the current rules).

- complex() now only allows the first argument to be a string
  argument, and raises TypeError if either the second arg is a string
  or if the second arg is specified when the first is a string.

Extension modules
-----------------

- gc.get_referents was renamed to gc.get_referrers.

Library
-------

- Functions in the os.spawn() family now release the global interpreter
  lock around calling the platform spawn.  They should always have done
  this, but did not before 2.2c1.  Multithreaded programs calling
  an os.spawn function with P_WAIT will no longer block all Python threads
  until the spawned program completes.  It's possible that some programs
  relies on blocking, although more likely by accident than by design.

- webbrowser defaults to netscape.exe on OS/2 now.

- Tix.ResizeHandle exposes detach_widget, hide, and show.

- The charset alias windows_1252 has been added.

- types.StringTypes is a tuple containing the defined string types;
  usually this will be (str, unicode), but if Python was compiled
  without Unicode support it will be just (str,).

- The pulldom and minidom modules were synchronized to PyXML.

Tools/Demos
-----------

- A new script called Tools/scripts/google.py was added, which fires
  off a search on Google.

Build
-----

- Note that release builds of Python should arrange to define the
  preprocessor symbol NDEBUG on the command line (or equivalent).
  In the 2.2 pre-release series we tried to define this by magic in
  Python.h instead, but it proved to cause problems for extension
  authors.  The Unix, Windows and Mac builds now all define NDEBUG in
  release builds via cmdline (or equivalent) instead.  Ports to
  other platforms should do likewise.

- It is no longer necessary to use --with-suffix when building on a
  case-insensitive file system (such as Mac OS X HFS+). In the build
  directory an extension is used, but not in the installed python.

C API
-----

- New function PyDict_MergeFromSeq2() exposes the built-in dict
  constructor's logic for updating a dictionary from an iterable object
  producing key-value pairs.

- PyArg_ParseTupleAndKeywords() requires that the number of entries in
  the keyword list equal the number of argument specifiers.  This
  wasn't checked correctly, and PyArg_ParseTupleAndKeywords could even
  dump core in some bad cases.  This has been repaired.  As a result,
  PyArg_ParseTupleAndKeywords may raise RuntimeError in bad cases that
  previously went unchallenged.

New platforms
-------------

Tests
-----

Windows
-------

Mac
----

- In unix-Python on Mac OS X (and darwin) sys.platform is now "darwin",
  without any trailing digits.

- Changed logic for finding python home in Mac OS X framework Pythons.
  Now sys.executable points to the executable again, in stead of to
  the shared library. The latter is used only for locating the python
  home.


What's New in Python 2.2b2?
===========================

*Release date: 16-Nov-2001*

Type/class unification and new-style classes
--------------------------------------------

- Multiple inheritance mixing new-style and classic classes in the
  list of base classes is now allowed, so this works now:

      class Classic: pass
      class Mixed(Classic, object): pass

  The MRO (method resolution order) for each base class is respected
  according to its kind, but the MRO for the derived class is computed
  using new-style MRO rules if any base class is a new-style class.
  This needs to be documented.

- The new built-in dictionary() constructor, and dictionary type, have
  been renamed to dict.  This reflects a decade of common usage.

- dict() now accepts an iterable object producing 2-sequences.  For
  example, dict(d.items()) == d for any dictionary d.  The argument,
  and the elements of the argument, can be any iterable objects.

- New-style classes can now have a __del__ method, which is called
  when the instance is deleted (just like for classic classes).

- Assignment to object.__dict__ is now possible, for objects that are
  instances of new-style classes that have a __dict__ (unless the base
  class forbids it).

- Methods of built-in types now properly check for keyword arguments
  (formerly these were silently ignored).  The only built-in methods
  that take keyword arguments are __call__, __init__ and __new__.

- The socket function has been converted to a type; see below.

Core and builtins
-----------------

- Assignment to __debug__ raises SyntaxError at compile-time.  This
  was promised when 2.1c1 was released as "What's New in Python 2.1c1"
  (see below) says.

- Clarified the error messages for unsupported operands to an operator
  (like 1 + '').

Extension modules
-----------------

- mmap has a new keyword argument, "access", allowing a uniform way for
  both Windows and Unix users to create read-only, write-through and
  copy-on-write memory mappings.  This was previously possible only on
  Unix.  A new keyword argument was required to support this in a
  uniform way because the mmap() signatures had diverged across
  platforms.  Thanks to Jay T Miller for repairing this!

- By default, the gc.garbage list now contains only those instances in
  unreachable cycles that have __del__ methods; in 2.1 it contained all
  instances in unreachable cycles.  "Instances" here has been generalized
  to include instances of both new-style and old-style classes.

- The socket module defines a new method for socket objects,
  sendall().  This is like send() but may make multiple calls to
  send() until all data has been sent.  Also, the socket function has
  been converted to a subclassable type, like list and tuple (etc.)
  before it; socket and SocketType are now the same thing.

- Various bugfixes to the curses module.  There is now a test suite
  for the curses module (you have to run it manually).

- binascii.b2a_base64 no longer places an arbitrary restriction of 57
  bytes on its input.

Library
-------

- tkFileDialog exposes a Directory class and askdirectory
  convenience function.

- Symbolic group names in regular expressions must be unique.  For
  example, the regexp r'(?P<abc>)(?P<abc>)' is not allowed, because a
  single name can't mean both "group 1" and "group 2" simultaneously.
  Python 2.2 detects this error at regexp compilation time;
  previously, the error went undetected, and results were
  unpredictable.  Also in sre, the pattern.split(), pattern.sub(), and
  pattern.subn() methods have been rewritten in C.  Also, an
  experimental function/method finditer() has been added, which works
  like findall() but returns an iterator.

- Tix exposes more commands through the classes DirSelectBox,
  DirSelectDialog, ListNoteBook, Meter, CheckList, and the
  methods tix_addbitmapdir, tix_cget, tix_configure, tix_filedialog,
  tix_getbitmap, tix_getimage, tix_option_get, and tix_resetoptions.

- Traceback objects are now scanned by cyclic garbage collection, so
  cycles created by casual use of sys.exc_info() no longer cause
  permanent memory leaks (provided garbage collection is enabled).

- os.extsep -- a new variable needed by the RISCOS support.  It is the
  separator used by extensions, and is '.' on all platforms except
  RISCOS, where it is '/'.  There is no need to use this variable
  unless you have a masochistic desire to port your code to RISCOS.

- mimetypes.py has optional support for non-standard, but commonly
  found types.  guess_type() and guess_extension() now accept an
  optional 'strict' flag, defaulting to true, which controls whether
  recognize non-standard types or not.  A few non-standard types we
  know about have been added.  Also, when run as a script, there are
  new -l and -e options.

- statcache is now deprecated.

- email.Utils.formatdate() now produces the preferred RFC 2822 style
  dates with numeric timezones (it used to produce obsolete dates
  hard coded to "GMT" timezone).  An optional 'localtime' flag is
  added to produce dates in the local timezone, with daylight savings
  time properly taken into account.

- In pickle and cPickle, instead of masking errors in load() by
  transforming them into SystemError, we let the original exception
  propagate out.  Also, implement support for __safe_for_unpickling__
  in pickle, as it already was supported in cPickle.

Tools/Demos
-----------

Build
-----

- The dbm module is built using libdb1 if available.  The bsddb module
  is built with libdb3 if available.

- Misc/Makefile.pre.in has been removed by BDFL pronouncement.

C API
-----

- New function PySequence_Fast_GET_SIZE() returns the size of a non-
  NULL result from PySequence_Fast(), more quickly than calling
  PySequence_Size().

- New argument unpacking function PyArg_UnpackTuple() added.

- New functions PyObject_CallFunctionObjArgs() and
  PyObject_CallMethodObjArgs() have been added to make it more
  convenient and efficient to call functions and methods from C.

- PyArg_ParseTupleAndKeywords() no longer masks errors, so it's
  possible that this will propagate errors it didn't before.

- New function PyObject_CheckReadBuffer(), which returns true if its
  argument supports the single-segment readable buffer interface.

New platforms
-------------

- We've finally confirmed that this release builds on HP-UX 11.00,
  *with* threads, and passes the test suite.

- Thanks to a series of patches from Michael Muller, Python may build
  again under OS/2 Visual Age C++.

- Updated RISCOS port by Dietmar Schwertberger.

Tests
-----

- Added a test script for the curses module.  It isn't run automatically;
  regrtest.py must be run with '-u curses' to enable it.

Windows
-------

Mac
----

- PythonScript has been moved to unsupported and is slated to be
  removed completely in the next release.

- It should now be possible to build applets that work on both OS9 and
  OSX.

- The core is now linked with CoreServices not Carbon; as a side
  result, default 8bit encoding on OSX is now ASCII.

- Python should now build on OSX 10.1.1


What's New in Python 2.2b1?
===========================

*Release date: 19-Oct-2001*

Type/class unification and new-style classes
--------------------------------------------

- New-style classes are now always dynamic (except for built-in and
  extension types).  There is no longer a performance penalty, and I
  no longer see another reason to keep this baggage around.  One relic
  remains: the __dict__ of a new-style class is a read-only proxy; you
  must set the class's attribute to modify it.  As a consequence, the
  __defined__ attribute of new-style types no longer exists, for lack
  of need: there is once again only one __dict__ (although in the
  future a __cache__ may be resurrected with a similar function, if I
  can prove that it actually speeds things up).

- C.__doc__ now works as expected for new-style classes (in 2.2a4 it
  always returned None, even when there was a class docstring).

- doctest now finds and runs docstrings attached to new-style classes,
  class methods, static methods, and properties.

Core and builtins
-----------------

- A very subtle syntactical pitfall in list comprehensions was fixed.
  For example: [a+b for a in 'abc', for b in 'def'].  The comma in
  this example is a mistake.  Previously, this would silently let 'a'
  iterate over the singleton tuple ('abc',), yielding ['abcd', 'abce',
  'abcf'] rather than the intended ['ad', 'ae', 'af', 'bd', 'be',
  'bf', 'cd', 'ce', 'cf'].  Now, this is flagged as a syntax error.
  Note that [a for a in <singleton>] is a convoluted way to say
  [<singleton>] anyway, so it's not like any expressiveness is lost.

- getattr(obj, name, default) now only catches AttributeError, as
  documented, rather than returning the default value for all
  exceptions (which could mask bugs in a __getattr__ hook, for
  example).

- Weak reference objects are now part of the core and offer a C API.
  A bug which could allow a core dump when binary operations involved
  proxy reference has been fixed.  weakref.ReferenceError is now a
  built-in exception.

- unicode(obj) now behaves more like str(obj), accepting arbitrary
  objects, and calling a __unicode__ method if it exists.
  unicode(obj, encoding) and unicode(obj, encoding, errors) still
  require an 8-bit string or character buffer argument.

- isinstance() now allows any object as the first argument and a
  class, a type or something with a __bases__ tuple attribute for the
  second argument.  The second argument may also be a tuple of a
  class, type, or something with __bases__, in which case isinstance()
  will return true if the first argument is an instance of any of the
  things contained in the second argument tuple.  E.g.

  isinstance(x, (A, B))

  returns true if x is an instance of A or B.

Extension modules
-----------------

- thread.start_new_thread() now returns the thread ID (previously None).

- binascii has now two quopri support functions, a2b_qp and b2a_qp.

- readline now supports setting the startup_hook and the
  pre_event_hook, and adds the add_history() function.

- os and posix supports chroot(), setgroups() and unsetenv() where
  available.  The stat(), fstat(), statvfs() and fstatvfs() functions
  now return "pseudo-sequences" -- the various fields can now be
  accessed as attributes (e.g. os.stat("/").st_mtime) but for
  backwards compatibility they also behave as a fixed-length sequence.
  Some platform-specific fields (e.g. st_rdev) are only accessible as
  attributes.

- time: localtime(), gmtime() and strptime() now return a
  pseudo-sequence similar to the os.stat() return value, with
  attributes like tm_year etc.

- Decompression objects in the zlib module now accept an optional
  second parameter to decompress() that specifies the maximum amount
  of memory to use for the uncompressed data.

- optional SSL support in the socket module now exports OpenSSL
  functions RAND_add(), RAND_egd(), and RAND_status().  These calls
  are useful on platforms like Solaris where OpenSSL does not
  automatically seed its PRNG.  Also, the keyfile and certfile
  arguments to socket.ssl() are now optional.

- posixmodule (and by extension, the os module on POSIX platforms) now
  exports O_LARGEFILE, O_DIRECT, O_DIRECTORY, and O_NOFOLLOW.

Library
-------

- doctest now excludes functions and classes not defined by the module
  being tested, thanks to Tim Hochberg.

- HotShot, a new profiler implemented using a C-based callback, has
  been added.  This substantially reduces the overhead of profiling,
  but it is still quite preliminary.  Support modules and
  documentation will be added in upcoming releases (before 2.2 final).

- profile now produces correct output in situations where an exception
  raised in Python is cleared by C code (e.g. hasattr()).  This used
  to cause wrong output, including spurious claims of recursive
  functions and attribution of time spent to the wrong function.

  The code and documentation for the derived OldProfile and HotProfile
  profiling classes was removed.  The code hasn't worked for years (if
  you tried to use them, they raised exceptions).  OldProfile
  intended to reproduce the behavior of the profiler Python used more
  than 7 years ago, and isn't interesting anymore.  HotProfile intended
  to provide a faster profiler (but producing less information), and
  that's a worthy goal we intend to meet via a different approach (but
  without losing information).

- Profile.calibrate() has a new implementation that should deliver
  a much better system-specific calibration constant.  The constant can
  now be specified in an instance constructor, or as a Profile class or
  instance variable, instead of by editing profile.py's source code.
  Calibration must still be done manually (see the docs for the profile
  module).

  Note that Profile.calibrate() must be overridden by subclasses.
  Improving the accuracy required exploiting detailed knowledge of
  profiler internals; the earlier method abstracted away the details
  and measured a simplified model instead, but consequently computed
  a constant too small by a factor of 2 on some modern machines.

- quopri's encode and decode methods take an optional header parameter,
  which indicates whether output is intended for the header 'Q'
  encoding.

- The SocketServer.ThreadingMixIn class now closes the request after
  finish_request() returns.  (Not when it errors out though.)

- The nntplib module's NNTP.body() method has grown a 'file' argument
  to allow saving the message body to a file.

- The email package has added a class email.Parser.HeaderParser which
  only parses headers and does not recurse into the message's body.
  Also, the module/class MIMEAudio has been added for representing
  audio data (contributed by Anthony Baxter).

- ftplib should be able to handle files > 2GB.

- ConfigParser.getboolean() now also interprets TRUE, FALSE, YES, NO,
  ON, and OFF.

- xml.dom.minidom NodeList objects now support the length attribute
  and item() method as required by the DOM specifications.

Tools/Demos
-----------

- Demo/dns was removed.  It no longer serves any purpose; a package
  derived from it is now maintained by Anthony Baxter, see
  http://PyDNS.SourceForge.net.

- The freeze tool has been made more robust, and two new options have
  been added: -X and -E.

Build
-----

- configure will use CXX in LINKCC if CXX is used to build main() and
  the system requires to link a C++ main using the C++ compiler.

C API
-----

- The documentation for the tp_compare slot is updated to require that
  the return value must be -1, 0, 1; an arbitrary number <0 or >0 is
  not correct.  This is not yet enforced but will be enforced in
  Python 2.3; even later, we may use -2 to indicate errors and +2 for
  "NotImplemented".  Right now, -1 should be used for an error return.

- PyLong_AsLongLong() now accepts int (as well as long) arguments.
  Consequently, PyArg_ParseTuple's 'L' code also accepts int (as well
  as long) arguments.

- PyThread_start_new_thread() now returns a long int giving the thread
  ID, if one can be calculated; it returns -1 for error, 0 if no
  thread ID is calculated (this is an incompatible change, but only
  the thread module used this API).  This code has only really been
  tested on Linux and Windows; other platforms please beware (and
  report any bugs or strange behavior).

- PyUnicode_FromEncodedObject() no longer accepts Unicode objects as
  input.

New platforms
-------------

Tests
-----

Windows
-------

- Installer:  If you install IDLE, and don't disable file-extension
  registration, a new "Edit with IDLE" context (right-click) menu entry
  is created for .py and .pyw files.

- The signal module now supports SIGBREAK on Windows, thanks to Steven
  Scott.  Note that SIGBREAK is unique to Windows.  The default SIGBREAK
  action remains to call Win32 ExitProcess().  This can be changed via
  signal.signal().  For example::

      # Make Ctrl+Break raise KeyboardInterrupt, like Python's default Ctrl+C
      # (SIGINT) behavior.
      import signal
      signal.signal(signal.SIGBREAK, signal.default_int_handler)

      try:
          while 1:
              pass
      except KeyboardInterrupt:
          # We get here on Ctrl+C or Ctrl+Break now; if we had not changed
          # SIGBREAK, only on Ctrl+C (and Ctrl+Break would terminate the
          # program without the possibility for any Python-level cleanup).
          print "Clean exit"


What's New in Python 2.2a4?
===========================

*Release date: 28-Sep-2001*

Type/class unification and new-style classes
--------------------------------------------

- pydoc and inspect are now aware of new-style classes;
  e.g. help(list) at the interactive prompt now shows proper
  documentation for all operations on list objects.

- Applications using Jim Fulton's ExtensionClass module can now safely
  be used with Python 2.2.  In particular, Zope 2.4.1 now works with
  Python 2.2 (as well as with Python 2.1.1).  The Demo/metaclass
  examples also work again.  It is hoped that Gtk and Boost also work
  with 2.2a4 and beyond.  (If you can confirm this, please write
  webmaster@python.org; if there are still problems, please open a bug
  report on SourceForge.)

- property() now takes 4 keyword arguments:  fget, fset, fdel and doc.
  These map to read-only attributes 'fget', 'fset', 'fdel', and '__doc__'
  in the constructed property object.  fget, fset and fdel weren't
  discoverable from Python in 2.2a3.  __doc__ is new, and allows
  associating a docstring with a property.

- Comparison overloading is now more completely implemented.  For
  example, a str subclass instance can properly be compared to a str
  instance, and it can properly overload comparison.  Ditto for most
  other built-in object types.

- The repr() of new-style classes has changed; instead of <type
  'M.Foo'> a new-style class is now rendered as <class 'M.Foo'>,
  *except* for built-in types, which are still rendered as <type
  'Foo'> (to avoid upsetting existing code that might parse or
  otherwise rely on repr() of certain type objects).

- The repr() of new-style objects is now always <Foo object at XXX>;
  previously, it was sometimes <Foo instance at XXX>.

- For new-style classes, what was previously called __getattr__ is now
  called __getattribute__.  This method, if defined, is called for
  *every* attribute access.  A new __getattr__ hook more similar to the
  one in classic classes is defined which is called only if regular
  attribute access raises AttributeError; to catch *all* attribute
  access, you can use __getattribute__ (for new-style classes).  If
  both are defined, __getattribute__ is called first, and if it raises
  AttributeError, __getattr__ is called.

- The __class__ attribute of new-style objects can be assigned to.
  The new class must have the same C-level object layout as the old
  class.

- The built-in file type can be subclassed now.  In the usual pattern,
  "file" is the name of the built-in type, and file() is a new built-in
  constructor, with the same signature as the built-in open() function.
  file() is now the preferred way to open a file.

- Previously, __new__ would only see sequential arguments passed to
  the type in a constructor call; __init__ would see both sequential
  and keyword arguments.  This made no sense whatsoever any more, so
  now both __new__ and __init__ see all arguments.

- Previously, hash() applied to an instance of a subclass of str or
  unicode always returned 0.  This has been repaired.

- Previously, an operation on an instance of a subclass of an
  immutable type (int, long, float, complex, tuple, str, unicode),
  where the subtype didn't override the operation (and so the
  operation was handled by the built-in type), could return that
  instance instead a value of the base type.  For example, if s was of
  a str subclass type, s[:] returned s as-is.  Now it returns a str
  with the same value as s.

- Provisional support for pickling new-style objects has been added.

Core
----

- file.writelines() now accepts any iterable object producing strings.

- PyUnicode_FromEncodedObject() now works very much like
  PyObject_Str(obj) in that it tries to use __str__/tp_str
  on the object if the object is not a string or buffer. This
  makes unicode() behave like str() when applied to non-string/buffer
  objects.

- PyFile_WriteObject now passes Unicode objects to the file's write
  method. As a result, all file-like objects which may be the target
  of a print statement must support Unicode objects, i.e. they must
  at least convert them into ASCII strings.

- Thread scheduling on Solaris should be improved; it is no longer
  necessary to insert a small sleep at the start of a thread in order
  to let other runnable threads be scheduled.

Library
-------

- StringIO.StringIO instances and cStringIO.StringIO instances support
  read character buffer compatible objects for their .write() methods.
  These objects are converted to strings and then handled as such
  by the instances.

- The "email" package has been added.  This is basically a port of the
  mimelib package <http://sf.net/projects/mimelib> with API changes
  and some implementations updated to use iterators and generators.

- difflib.ndiff() and difflib.Differ.compare() are generators now.  This
  restores the ability of Tools/scripts/ndiff.py to start producing output
  before the entire comparison is complete.

- StringIO.StringIO instances and cStringIO.StringIO instances support
  iteration just like file objects (i.e. their .readline() method is
  called for each iteration until it returns an empty string).

- The codecs module has grown four new helper APIs to access
  built-in codecs: getencoder(), getdecoder(), getreader(),
  getwriter().

- SimpleXMLRPCServer: a new module (based upon SimpleHTMLServer)
  simplifies writing XML RPC servers.

- os.path.realpath(): a new function that returns the absolute pathname
  after interpretation of symbolic links.  On non-Unix systems, this
  is an alias for os.path.abspath().

- operator.indexOf() (PySequence_Index() in the C API) now works with any
  iterable object.

- smtplib now supports various authentication and security features of
  the SMTP protocol through the new login() and starttls() methods.

- hmac: a new module implementing keyed hashing for message
  authentication.

- mimetypes now recognizes more extensions and file types.  At the
  same time, some mappings not sanctioned by IANA were removed.

- The "compiler" package has been brought up to date to the state of
  Python 2.2 bytecode generation.  It has also been promoted from a
  Tool to a standard library package.  (Tools/compiler still exists as
  a sample driver.)

Build
-----

- Large file support (LFS) is now automatic when the platform supports
  it; no more manual configuration tweaks are needed.  On Linux, at
  least, it's possible to have a system whose C library supports large
  files but whose kernel doesn't; in this case, large file support is
  still enabled but doesn't do you any good unless you upgrade your
  kernel or share your Python executable with another system whose
  kernel has large file support.

- The configure script now supplies plausible defaults in a
  cross-compilation environment.  This doesn't mean that the supplied
  values are always correct, or that cross-compilation now works
  flawlessly -- but it's a first step (and it shuts up most of
  autoconf's warnings about AC_TRY_RUN).

- The Unix build is now a bit less chatty, courtesy of the parser
  generator.  The build is completely silent (except for errors) when
  using "make -s", thanks to a -q option to setup.py.

C API
-----

- The "structmember" API now supports some new flag bits to deny read
  and/or write access to attributes in restricted execution mode.

New platforms
-------------

- Compaq's iPAQ handheld, running the "familiar" Linux distribution
  (http://familiar.handhelds.org).

Tests
-----

- The "classic" standard tests, which work by comparing stdout to
  an expected-output file under Lib/test/output/, no longer stop at
  the first mismatch.  Instead the test is run to completion, and a
  variant of ndiff-style comparison is used to report all differences.
  This is much easier to understand than the previous style of reporting.

- The unittest-based standard tests now use regrtest's test_main()
  convention, instead of running as a side-effect of merely being
  imported.  This allows these tests to be run in more natural and
  flexible ways as unittests, outside the regrtest framework.

- regrtest.py is much better integrated with unittest and doctest now,
  especially in regard to reporting errors.

Windows
-------

- Large file support now also works for files > 4GB, on filesystems
  that support it (NTFS under Windows 2000).  See "What's New in
  Python 2.2a3" for more detail.


What's New in Python 2.2a3?
===========================

*Release Date: 07-Sep-2001*

Core
----

- Conversion of long to float now raises OverflowError if the long is too
  big to represent as a C double.

- The 3-argument builtin pow() no longer allows a third non-None argument
  if either of the first two arguments is a float, or if both are of
  integer types and the second argument is negative (in which latter case
  the arguments are converted to float, so this is really the same
  restriction).

- The builtin dir() now returns more information, and sometimes much
  more, generally naming all attributes of an object, and all attributes
  reachable from the object via its class, and from its class's base
  classes, and so on from them too.  Example:  in 2.2a2, dir([]) returned
  an empty list.  In 2.2a3,

  >>> dir([])
  ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
   '__eq__', '__ge__', '__getattr__', '__getitem__', '__getslice__',
   '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__le__',
   '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__repr__',
   '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__',
   'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
   'reverse', 'sort']

  dir(module) continues to return only the module's attributes, though.

- Overflowing operations on plain ints now return a long int rather
  than raising OverflowError.  This is a partial implementation of PEP
  237.  You can use -Wdefault::OverflowWarning to enable a warning for
  this situation, and -Werror::OverflowWarning to revert to the old
  OverflowError exception.

- A new command line option, -Q<arg>, is added to control run-time
  warnings for the use of classic division.  (See PEP 238.)  Possible
  values are -Qold, -Qwarn, -Qwarnall, and -Qnew.  The default is
  -Qold, meaning the / operator has its classic meaning and no
  warnings are issued.  Using -Qwarn issues a run-time warning about
  all uses of classic division for int and long arguments; -Qwarnall
  also warns about classic division for float and complex arguments
  (for use with fixdiv.py).
  [Note:  the remainder of this item (preserved below) became
  obsolete in 2.2c1 -- -Qnew has global effect in 2.2] ::

    Using -Qnew is questionable; it turns on new division by default, but
    only in the __main__ module.  You can usefully combine -Qwarn or
    -Qwarnall and -Qnew: this gives the __main__ module new division, and
    warns about classic division everywhere else.

- Many built-in types can now be subclassed.  This applies to int,
  long, float, str, unicode, and tuple.  (The types complex, list and
  dictionary can also be subclassed; this was introduced earlier.)
  Note that restrictions apply when subclassing immutable built-in
  types: you can only affect the value of the instance by overloading
  __new__.  You can add mutable attributes, and the subclass instances
  will have a __dict__ attribute, but you cannot change the "value"
  (as implemented by the base class) of an immutable subclass instance
  once it is created.

- The dictionary constructor now takes an optional argument, a
  mapping-like object, and initializes the dictionary from its
  (key, value) pairs.

- A new built-in type, super, has been added.  This facilitates making
  "cooperative super calls" in a multiple inheritance setting.  For an
  explanation, see http://www.python.org/2.2/descrintro.html#cooperation

- A new built-in type, property, has been added.  This enables the
  creation of "properties".  These are attributes implemented by
  getter and setter functions (or only one of these for read-only or
  write-only attributes), without the need to override __getattr__.
  See http://www.python.org/2.2/descrintro.html#property

- The syntax of floating-point and imaginary literals has been
  liberalized, to allow leading zeroes.  Examples of literals now
  legal that were SyntaxErrors before:

      00.0    0e3   0100j   07.5   00000000000000000008.

- An old tokenizer bug allowed floating point literals with an incomplete
  exponent, such as 1e and 3.1e-.  Such literals now raise SyntaxError.

Library
-------

- telnetlib includes symbolic names for the options, and support for
  setting an option negotiation callback. It also supports processing
  of suboptions.

- The new C standard no longer requires that math libraries set errno to
  ERANGE on overflow.  For platform libraries that exploit this new
  freedom, Python's overflow-checking was wholly broken.  A new overflow-
  checking scheme attempts to repair that, but may not be reliable on all
  platforms (C doesn't seem to provide anything both useful and portable
  in this area anymore).

- Asynchronous timeout actions are available through the new class
  threading.Timer.

- math.log and math.log10 now return sensible results for even huge
  long arguments.  For example, math.log10(10 ** 10000) ~= 10000.0.

- A new function, imp.lock_held(), returns 1 when the import lock is
  currently held.  See the docs for the imp module.

- pickle, cPickle and marshal on 32-bit platforms can now correctly read
  dumps containing ints written on platforms where Python ints are 8 bytes.
  When read on a box where Python ints are 4 bytes, such values are
  converted to Python longs.

- In restricted execution mode (using the rexec module), unmarshalling
  code objects is no longer allowed.  This plugs a security hole.

- unittest.TestResult instances no longer store references to tracebacks
  generated by test failures. This prevents unexpected dangling references
  to objects that should be garbage collected between tests.

Tools
-----

- Tools/scripts/fixdiv.py has been added which can be used to fix
  division operators as per PEP 238.

Build
-----

- If you are an adventurous person using Mac OS X you may want to look at
  Mac/OSX. There is a Makefile there that will build Python as a real Mac
  application, which can be used for experimenting with Carbon or Cocoa.
  Discussion of this on pythonmac-sig, please.

C API
-----

- New function PyObject_Dir(obj), like Python __builtin__.dir(obj).

- Note that PyLong_AsDouble can fail!  This has always been true, but no
  callers checked for it.  It's more likely to fail now, because overflow
  errors are properly detected now.  The proper way to check::

      double x = PyLong_AsDouble(some_long_object);
      if (x == -1.0 && PyErr_Occurred()) {
              /* The conversion failed. */
      }

- The GC API has been changed.  Extensions that use the old API will still
  compile but will not participate in GC.  To upgrade an extension
  module:

    - rename Py_TPFLAGS_GC to PyTPFLAGS_HAVE_GC

    - use PyObject_GC_New or PyObject_GC_NewVar to allocate objects and
      PyObject_GC_Del to deallocate them

    - rename PyObject_GC_Init to PyObject_GC_Track and PyObject_GC_Fini
      to PyObject_GC_UnTrack

    - remove PyGC_HEAD_SIZE from object size calculations

    - remove calls to PyObject_AS_GC and PyObject_FROM_GC

- Two new functions: PyString_FromFormat() and PyString_FromFormatV().
  These can be used safely to construct string objects from a
  sprintf-style format string (similar to the format string supported
  by PyErr_Format()).

New platforms
-------------

- Stephen Hansen contributed patches sufficient to get a clean compile
  under Borland C (Windows), but he reports problems running it and ran
  out of time to complete the port.  Volunteers?  Expect a MemoryError
  when importing the types module; this is probably shallow, and
  causing later failures too.

Tests
-----

Windows
-------

- Large file support is now enabled on Win32 platforms as well as on
  Win64.  This means that, for example, you can use f.tell() and f.seek()
  to manipulate files larger than 2 gigabytes (provided you have enough
  disk space, and are using a Windows filesystem that supports large
  partitions).  Windows filesystem limits:  FAT has a 2GB (gigabyte)
  filesize limit, and large file support makes no difference there.
  FAT32's limit is 4GB, and files >= 2GB are easier to use from Python now.
  NTFS has no practical limit on file size, and files of any size can be
  used from Python now.

- The w9xpopen hack is now used on Windows NT and 2000 too when COMPSPEC
  points to command.com (patch from Brian Quinlan).


What's New in Python 2.2a2?
===========================

*Release Date: 22-Aug-2001*

Build
-----

- Tim Peters developed a brand new Windows installer using Wise 8.1,
  generously donated to us by Wise Solutions.

- configure supports a new option --enable-unicode, with the values
  ucs2 and ucs4 (new in 2.2a1). With --disable-unicode, the Unicode
  type and supporting code is completely removed from the interpreter.

- A new configure option --enable-framework builds a Mac OS X framework,
  which "make frameworkinstall" will install. This provides a starting
  point for more mac-like functionality, join pythonmac-sig@python.org
  if you are interested in helping.

- The NeXT platform is no longer supported.

- The 'new' module is now statically linked.

Tools
-----

- The new Tools/scripts/cleanfuture.py can be used to automatically
  edit out obsolete future statements from Python source code.  See
  the module docstring for details.

Tests
-----

- regrtest.py now knows which tests are expected to be skipped on some
  platforms, allowing clearer test result output to be given.  regrtest
  also has optional --use/-u switch to run normally disabled tests
  which require network access or consume significant disk resources.

- Several new tests in the standard test suite, with special thanks to
  Nick Mathewson.

Core
----

- The floor division operator // has been added as outlined in PEP
  238.  The / operator still provides classic division (and will until
  Python 3.0) unless "from __future__ import division" is included, in
  which case the / operator will provide true division.  The operator
  module provides truediv() and floordiv() functions.  Augmented
  assignment variants are included, as are the equivalent overloadable
  methods and C API methods.  See the PEP for a full discussion:
  <http://python.sf.net/peps/pep-0238.html>

- Future statements are now effective in simulated interactive shells
  (like IDLE).  This should "just work" by magic, but read Michael
  Hudson's "Future statements in simulated shells" PEP 264 for full
  details:  <http://python.sf.net/peps/pep-0264.html>.

- The type/class unification (PEP 252-253) was integrated into the
  trunk and is not so tentative any more (the exact specification of
  some features is still tentative).  A lot of work has done on fixing
  bugs and adding robustness and features (performance still has to
  come a long way).

- Warnings about a mismatch in the Python API during extension import
  now use the Python warning framework (which makes it possible to
  write filters for these warnings).

- A function's __dict__ (aka func_dict) will now always be a
  dictionary.  It used to be possible to delete it or set it to None,
  but now both actions raise TypeErrors.  It is still legal to set it
  to a dictionary object.  Getting func.__dict__ before any attributes
  have been assigned now returns an empty dictionary instead of None.

- A new command line option, -E, was added which disables the use of
  all environment variables, or at least those that are specifically
  significant to Python.  Usually those have a name starting with
  "PYTHON".  This was used to fix a problem where the tests fail if
  the user happens to have PYTHONHOME or PYTHONPATH pointing to an
  older distribution.

Library
-------

- New class Differ and new functions ndiff() and restore() in difflib.py.
  These package the algorithms used by the popular Tools/scripts/ndiff.py,
  for programmatic reuse.

- New function xml.sax.saxutils.quoteattr():  Quote an XML attribute
  value using the minimal quoting required for the value; more
  reliable than using xml.sax.saxutils.escape() for attribute values.

- Readline completion support for cmd.Cmd was added.

- Calling os.tempnam() or os.tmpnam() generate RuntimeWarnings.

- Added function threading.BoundedSemaphore()

- Added Ka-Ping Yee's cgitb.py module.

- The 'new' module now exposes the CO_xxx flags.

- The gc module offers the get_referents function.

New platforms
-------------

C API
-----

- Two new APIs PyOS_snprintf() and PyOS_vsnprintf() were added
  which provide a cross-platform implementations for the
  relatively new snprintf()/vsnprintf() C lib APIs. In contrast to
  the standard sprintf() and vsprintf() C lib APIs, these versions
  apply bounds checking on the used buffer which enhances protection
  against buffer overruns.

- Unicode APIs now use name mangling to assure that mixing interpreters
  and extensions using different Unicode widths is rendered next to
  impossible. Trying to import an incompatible Unicode-aware extension
  will result in an ImportError.  Unicode extensions writers must make
  sure to check the Unicode width compatibility in their extensions by
  using at least one of the mangled Unicode APIs in the extension.

- Two new flags METH_NOARGS and METH_O are available in method definition
  tables to simplify implementation of methods with no arguments and a
  single untyped argument. Calling such methods is more efficient than
  calling corresponding METH_VARARGS methods. METH_OLDARGS is now
  deprecated.

Windows
-------

- "import module" now compiles module.pyw if it exists and nothing else
  relevant is found.


What's New in Python 2.2a1?
===========================

*Release date: 18-Jul-2001*

Core
----

- TENTATIVELY, a large amount of code implementing much of what's
  described in PEP 252 (Making Types Look More Like Classes) and PEP
  253 (Subtyping Built-in Types) was added.  This will be released
  with Python 2.2a1.  Documentation will be provided separately
  through http://www.python.org/2.2/.  The purpose of releasing this
  with Python 2.2a1 is to test backwards compatibility.  It is
  possible, though not likely, that a decision is made not to release
  this code as part of 2.2 final, if any serious backwards
  incompatibilities are found during alpha testing that cannot be
  repaired.

- Generators were added; this is a new way to create an iterator (see
  below) using what looks like a simple function containing one or
  more 'yield' statements.  See PEP 255.  Since this adds a new
  keyword to the language, this feature must be enabled by including a
  future statement: "from __future__ import generators" (see PEP 236).
  Generators will become a standard feature in a future release
  (probably 2.3).  Without this future statement, 'yield' remains an
  ordinary identifier, but a warning is issued each time it is used.
  (These warnings currently don't conform to the warnings framework of
  PEP 230; we intend to fix this in 2.2a2.)

- The UTF-16 codec was modified to be more RFC compliant. It will now
  only remove BOM characters at the start of the string and then
  only if running in native mode (UTF-16-LE and -BE won't remove a
  leading BMO character).

- Strings now have a new method .decode() to complement the already
  existing .encode() method. These two methods provide direct access
  to the corresponding decoders and encoders of the registered codecs.

  To enhance the usability of the .encode() method, the special
  casing of Unicode object return values was dropped (Unicode objects
  were auto-magically converted to string using the default encoding).

  Both methods will now return whatever the codec in charge of the
  requested encoding returns as object, e.g. Unicode codecs will
  return Unicode objects when decoding is requested ("äöü".decode("latin-1")
  will return u"äöü"). This enables codec writer to create codecs
  for various simple to use conversions.

  New codecs were added to demonstrate these new features (the .encode()
  and .decode() columns indicate the type of the returned objects):

  +---------+-----------+-----------+-----------------------------+
  |Name     | .encode() | .decode() | Description                 |
  +=========+===========+===========+=============================+
  |uu       | string    | string    | UU codec (e.g. for email)   |
  +---------+-----------+-----------+-----------------------------+
  |base64   | string    | string    | base64 codec                |
  +---------+-----------+-----------+-----------------------------+
  |quopri   | string    | string    | quoted-printable codec      |
  +---------+-----------+-----------+-----------------------------+
  |zlib     | string    | string    | zlib compression            |
  +---------+-----------+-----------+-----------------------------+
  |hex      | string    | string    | 2-byte hex codec            |
  +---------+-----------+-----------+-----------------------------+
  |rot-13   | string    | Unicode   | ROT-13 Unicode charmap codec|
  +---------+-----------+-----------+-----------------------------+

- Some operating systems now support the concept of a default Unicode
  encoding for file system operations.  Notably, Windows supports 'mbcs'
  as the default.  The Macintosh will also adopt this concept in the medium
  term, although the default encoding for that platform will be other than
  'mbcs'.

  On operating system that support non-ASCII filenames, it is common for
  functions that return filenames (such as os.listdir()) to return Python
  string objects pre-encoded using the default file system encoding for
  the platform.  As this encoding is likely to be different from Python's
  default encoding, converting this name to a Unicode object before passing
  it back to the Operating System would result in a Unicode error, as Python
  would attempt to use its default encoding (generally ASCII) rather than
  the default encoding for the file system.

  In general, this change simply removes surprises when working with
  Unicode and the file system, making these operations work as you expect,
  increasing the transparency of Unicode objects in this context.
  See [????] for more details, including examples.

- Float (and complex) literals in source code were evaluated to full
  precision only when running from a .py file; the same code loaded from a
  .pyc (or .pyo) file could suffer numeric differences starting at about the
  12th significant decimal digit.  For example, on a machine with IEEE-754
  floating arithmetic,

      x = 9007199254740992.0
      print long(x)

  printed 9007199254740992 if run directly from .py, but 9007199254740000
  if from a compiled (.pyc or .pyo) file.  This was due to marshal using
  str(float) instead of repr(float) when building code objects.  marshal
  now uses repr(float) instead, which should reproduce floats to full
  machine precision (assuming the platform C float<->string I/O conversion
  functions are of good quality).

  This may cause floating-point results to change in some cases, and
  usually for the better, but may also cause numerically unstable
  algorithms to break.

- The implementation of dicts suffers fewer collisions, which has speed
  benefits.  However, the order in which dict entries appear in dict.keys(),
  dict.values() and dict.items() may differ from previous releases for a
  given dict.  Nothing is defined about this order, so no program should
  rely on it.  Nevertheless, it's easy to write test cases that rely on the
  order by accident, typically because of printing the str() or repr() of a
  dict to an "expected results" file.  See Lib/test/test_support.py's new
  sortdict(dict) function for a simple way to display a dict in sorted
  order.

- Many other small changes to dicts were made, resulting in faster
  operation along the most common code paths.

- Dictionary objects now support the "in" operator: "x in dict" means
  the same as dict.has_key(x).

- The update() method of dictionaries now accepts generic mapping
  objects.  Specifically the argument object must support the .keys()
  and __getitem__() methods.  This allows you to say, for example,
  {}.update(UserDict())

- Iterators were added; this is a generalized way of providing values
  to a for loop.  See PEP 234.  There's a new built-in function iter()
  to return an iterator.  There's a new protocol to get the next value
  from an iterator using the next() method (in Python) or the
  tp_iternext slot (in C).  There's a new protocol to get iterators
  using the __iter__() method (in Python) or the tp_iter slot (in C).
  Iterating (i.e. a for loop) over a dictionary generates its keys.
  Iterating over a file generates its lines.

- The following functions were generalized to work nicely with iterator
  arguments::

    map(), filter(), reduce(), zip()
    list(), tuple() (PySequence_Tuple() and PySequence_Fast() in C API)
    max(), min()
    join() method of strings
    extend() method of lists
    'x in y' and 'x not in y' (PySequence_Contains() in C API)
    operator.countOf() (PySequence_Count() in C API)
    right-hand side of assignment statements with multiple targets, such as ::
        x, y, z = some_iterable_object_returning_exactly_3_values

- Accessing module attributes is significantly faster (for example,
  random.random or os.path or yourPythonModule.yourAttribute).

- Comparing dictionary objects via == and != is faster, and now works even
  if the keys and values don't support comparisons other than ==.

- Comparing dictionaries in ways other than == and != is slower:  there were
  insecurities in the dict comparison implementation that could cause Python
  to crash if the element comparison routines for the dict keys and/or
  values mutated the dicts.  Making the code bulletproof slowed it down.

- Collisions in dicts are resolved via a new approach, which can help
  dramatically in bad cases.  For example, looking up every key in a dict
  d with d.keys() == [i << 16 for i in range(20000)] is approximately 500x
  faster now.  Thanks to Christian Tismer for pointing out the cause and
  the nature of an effective cure (last December! better late than never).

- repr() is much faster for large containers (dict, list, tuple).


Library
-------

- The constants ascii_letters, ascii_lowercase. and ascii_uppercase
  were added to the string module.  These a locale-independent
  constants, unlike letters, lowercase, and uppercase.  These are now
  use in appropriate locations in the standard library.

- The flags used in dlopen calls can now be configured using
  sys.setdlopenflags and queried using sys.getdlopenflags.

- Fredrik Lundh's xmlrpclib is now a standard library module.  This
  provides full client-side XML-RPC support.  In addition,
  Demo/xmlrpc/ contains two server frameworks (one SocketServer-based,
  one asyncore-based).  Thanks to Eric Raymond for the documentation.

- The xrange() object is simplified: it no longer supports slicing,
  repetition, comparisons, efficient 'in' checking, the tolist()
  method, or the start, stop and step attributes.  See PEP 260.

- A new function fnmatch.filter to filter lists of file names was added.

- calendar.py uses month and day names based on the current locale.

- strop is now *really* obsolete (this was announced before with 1.6),
  and issues DeprecationWarning when used (except for the four items
  that are still imported into string.py).

- Cookie.py now sorts key+value pairs by key in output strings.

- pprint.isrecursive(object) didn't correctly identify recursive objects.
  Now it does.

- pprint functions now much faster for large containers (tuple, list, dict).

- New 'q' and 'Q' format codes in the struct module, corresponding to C
  types "long long" and "unsigned long long" (on Windows, __int64).  In
  native mode, these can be used only when the platform C compiler supports
  these types (when HAVE_LONG_LONG is #define'd by the Python config
  process), and then they inherit the sizes and alignments of the C types.
  In standard mode, 'q' and 'Q' are supported on all platforms, and are
  8-byte integral types.

- The site module installs a new built-in function 'help' that invokes
  pydoc.help.  It must be invoked as 'help()'; when invoked as 'help',
  it displays a message reminding the user to use 'help()' or
  'help(object)'.

Tests
-----

- New test_mutants.py runs dict comparisons where the key and value
  comparison operators mutate the dicts randomly during comparison.  This
  rapidly causes Python to crash under earlier releases (not for the faint
  of heart:  it can also cause Win9x to freeze or reboot!).

- New test_pprint.py verifies that pprint.isrecursive() and
  pprint.isreadable() return sensible results.  Also verifies that simple
  cases produce correct output.

C API
-----

- Removed the unused last_is_sticky argument from the internal
  _PyTuple_Resize().  If this affects you, you were cheating.

What's New in Python 2.1 (final)?
=================================

We only changed a few things since the last release candidate, all in
Python library code:

- A bug in the locale module was fixed that affected locales which
  define no grouping for numeric formatting.

- A few bugs in the weakref module's implementations of weak
  dictionaries (WeakValueDictionary and WeakKeyDictionary) were fixed,
  and the test suite was updated to check for these bugs.

- An old bug in the os.path.walk() function (introduced in Python
  2.0!) was fixed: a non-existent file would cause an exception
  instead of being ignored.

- Fixed a few bugs in the new symtable module found by Neil Norwitz's
  PyChecker.


What's New in Python 2.1c2?
===========================

A flurry of small changes, and one showstopper fixed in the nick of
time made it necessary to release another release candidate.  The list
here is the *complete* list of patches (except version updates):

Core

- Tim discovered a nasty bug in the dictionary code, caused by
  PyDict_Next() calling dict_resize(), and the GC code's use of
  PyDict_Next() violating an assumption in dict_items().  This was
  fixed with considerable amounts of band-aid, but the net effect is a
  saner and more robust implementation.

- Made a bunch of symbols static that were accidentally global.

Build and Ports

- The setup.py script didn't check for a new enough version of zlib
  (1.1.3 is needed).  Now it does.

- Changed "make clean" target to also remove shared libraries.

- Added a more general warning about the SGI Irix optimizer to README.

Library

- Fix a bug in urllib.basejoin("http://host", "../file.html") which
  omitted the slash between host and file.html.

- The mailbox module's _Mailbox class contained a completely broken
  and undocumented seek() method.  Ripped it out.

- Fixed a bunch of typos in various library modules (urllib2, smtpd,
  sgmllib, netrc, chunk) found by Neil Norwitz's PyChecker.

- Fixed a few last-minute bugs in unittest.

Extensions

- Reverted the patch to the OpenSSL code in socketmodule.c to support
  RAND_status() and the EGD, and the subsequent patch that tried to
  fix it for pre-0.9.5 versions; the problem with the patch is that on
  some systems it issues a warning whenever socket is imported, and
  that's unacceptable.

Tests

- Fixed the pickle tests to work with "import test.test_pickle".

- Tweaked test_locale.py to actually run the test Windows.

- In distutils/archive_util.py, call zipfile.ZipFile() with mode "w",
  not "wb" (which is not a valid mode at all).

- Fix pstats browser crashes.  Import readline if it exists to make
  the user interface nicer.

- Add "import thread" to the top of test modules that import the
  threading module (test_asynchat and test_threadedtempfile).  This
  prevents test failures caused by a broken threading module resulting
  from a previously caught failed import.

- Changed test_asynchat.py to set the SO_REUSEADDR option; this was
  needed on some platforms (e.g. Solaris 8) when the tests are run
  twice in succession.

- Skip rather than fail test_sunaudiodev if no audio device is found.


What's New in Python 2.1c1?
===========================

This list was significantly updated when 2.1c2 was released; the 2.1c1
release didn't mention most changes that were actually part of 2.1c1:

Legal

- Copyright was assigned to the Python Software Foundation (PSF) and a
  PSF license (very similar to the CNRI license) was added.

- The CNRI copyright notice was updated to include 2001.

Core

- After a public outcry, assignment to __debug__ is no longer illegal;
  instead, a warning is issued.  It will become illegal in 2.2.

- Fixed a core dump with "%#x" % 0, and changed the semantics so that
  "%#x" now always prepends "0x", even if the value is zero.

- Fixed some nits in the bytecode compiler.

- Fixed core dumps when calling certain kinds of non-functions.

- Fixed various core dumps caused by reference count bugs.

Build and Ports

- Use INSTALL_SCRIPT to install script files.

- New port: SCO Unixware 7, by Billy G. Allie.

- Updated RISCOS port.

- Updated BeOS port and notes.

- Various other porting problems resolved.

Library

- The TERMIOS and SOCKET modules are now truly obsolete and
  unnecessary.  Their symbols are incorporated in the termios and
  socket modules.

- Fixed some 64-bit bugs in pickle, cPickle, and struct, and added
  better tests for pickling.

- threading: make Condition.wait() robust against KeyboardInterrupt.

- zipfile: add support to zipfile to support opening an archive
  represented by an open file rather than a file name.  Fix bug where
  the archive was not properly closed.  Fixed a bug in this bugfix
  where flush() was called for a read-only file.

- imputil: added an uninstall() method to the ImportManager.

- Canvas: fixed bugs in lower() and tkraise() methods.

- SocketServer: API change (added overridable close_request() method)
  so that the TCP server can explicitly close the request.

- pstats: Eric Raymond added a simple interactive statistics browser,
  invoked when the module is run as a script.

- locale: fixed a problem in format().

- webbrowser: made it work when the BROWSER environment variable has a
  value like "/usr/bin/netscape".  Made it auto-detect Konqueror for
  KDE 2.  Fixed some other nits.

- unittest: changes to allow using a different exception than
  AssertionError, and added a few more function aliases.  Some other
  small changes.

- urllib, urllib2: fixed redirect problems and a coupleof other nits.

- asynchat: fixed a critical bug in asynchat that slipped through the
  2.1b2 release.  Fixed another rare bug.

- Fix some unqualified except: clauses (always a bad code example).

XML

- pyexpat: new API get_version_string().

- Fixed some minidom bugs.

Extensions

- Fixed a core dump in _weakref.  Removed the weakref.mapping()
  function (it adds nothing to the API).

- Rationalized the use of header files in the readline module, to make
  it compile (albeit with some warnings) with the very recent readline
  4.2, without breaking for earlier versions.

- Hopefully fixed a buffering problem in linuxaudiodev.

- Attempted a fix to make the OpenSSL support in the socket module
  work again with pre-0.9.5 versions of OpenSSL.

Tests

- Added a test case for asynchat and asyncore.

- Removed coupling between tests where one test failing could break
  another.

Tools

- Ping added an interactive help browser to pydoc, fixed some nits
  in the rest of the pydoc code, and added some features to his
  inspect module.

- An updated python-mode.el version 4.1 which integrates Ken
  Manheimer's pdbtrack.el.  This makes debugging Python code via pdb
  much nicer in XEmacs and Emacs.  When stepping through your program
  with pdb, in either the shell window or the *Python* window, the
  source file and line will be tracked by an arrow.  Very cool!

- IDLE: syntax warnings in interactive mode are changed into errors.

- Some improvements to Tools/webchecker (ignore some more URL types,
  follow some more links).

- Brought the Tools/compiler package up to date.


What's New in Python 2.1 beta 2?
================================

(Unlisted are many fixed bugs, more documentation, etc.)

Core language, builtins, and interpreter

- The nested scopes work (enabled by "from __future__ import
  nested_scopes") is completed; in particular, the future now extends
  into code executed through exec, eval() and execfile(), and into the
  interactive interpreter.

- When calling a base class method (e.g. BaseClass.__init__(self)),
  this is now allowed even if self is not strictly spoken a class
  instance (e.g. when using metaclasses or the Don Beaudry hook).

- Slice objects are now comparable but not hashable; this prevents
  dict[:] from being accepted but meaningless.

- Complex division is now calculated using less braindead algorithms.
  This doesn't change semantics except it's more likely to give useful
  results in extreme cases.  Complex repr() now uses full precision
  like float repr().

- sgmllib.py now calls handle_decl() for simple <!...> declarations.

- It is illegal to assign to the name __debug__, which is set when the
  interpreter starts.  It is effectively a compile-time constant.

- A warning will be issued if a global statement for a variable
  follows a use or assignment of that variable.

Standard library

- unittest.py, a unit testing framework by Steve Purcell (PyUNIT,
  inspired by JUnit), is now part of the standard library.  You now
  have a choice of two testing frameworks: unittest requires you to
  write testcases as separate code, doctest gathers them from
  docstrings.  Both approaches have their advantages and
  disadvantages.

- A new module Tix was added, which wraps the Tix extension library
  for Tk.  With that module, it is not necessary to statically link
  Tix with _tkinter, since Tix will be loaded with Tcl's "package
  require" command.  See Demo/tix/.

- tzparse.py is now obsolete.

- In gzip.py, the seek() and tell() methods are removed -- they were
  non-functional anyway, and it's better if callers can test for their
  existence with hasattr().

Python/C API

- PyDict_Next(): it is now safe to call PyDict_SetItem() with a key
  that's already in the dictionary during a PyDict_Next() iteration.
  This used to fail occasionally when a dictionary resize operation
  could be triggered that would rehash all the keys.  All other
  modifications to the dictionary are still off-limits during a
  PyDict_Next() iteration!

- New extended APIs related to passing compiler variables around.

- New abstract APIs PyObject_IsInstance(), PyObject_IsSubclass()
  implement isinstance() and issubclass().

- Py_BuildValue() now has a "D" conversion to create a Python complex
  number from a Py_complex C value.

- Extensions types which support weak references must now set the
  field allocated for the weak reference machinery to NULL themselves;
  this is done to avoid the cost of checking each object for having a
  weakly referencable type in PyObject_INIT(), since most types are
  not weakly referencable.

- PyFrame_FastToLocals() and PyFrame_LocalsToFast() copy bindings for
  free variables and cell variables to and from the frame's f_locals.

- Variants of several functions defined in pythonrun.h have been added
  to support the nested_scopes future statement.  The variants all end
  in Flags and take an extra argument, a PyCompilerFlags *; examples:
  PyRun_AnyFileExFlags(), PyRun_InteractiveLoopFlags().  These
  variants may be removed in Python 2.2, when nested scopes are
  mandatory.

Distutils

- the sdist command now writes a PKG-INFO file, as described in PEP 241,
  into the release tree.

- several enhancements to the bdist_wininst command from Thomas Heller
  (an uninstaller, more customization of the installer's display)

- from Jack Jansen: added Mac-specific code to generate a dialog for
  users to specify the command-line (because providing a command-line with
  MacPython is awkward).  Jack also made various fixes for the Mac
  and the Metrowerks compiler.

- added 'platforms' and 'keywords' to the set of metadata that can be
  specified for a distribution.

- applied patches from Jason Tishler to make the compiler class work with
  Cygwin.


What's New in Python 2.1 beta 1?
================================

Core language, builtins, and interpreter

- Following an outcry from the community about the amount of code
  broken by the nested scopes feature introduced in 2.1a2, we decided
  to make this feature optional, and to wait until Python 2.2 (or at
  least 6 months) to make it standard.  The option can be enabled on a
  per-module basis by adding "from __future__ import nested_scopes" at
  the beginning of a module (before any other statements, but after
  comments and an optional docstring).  See PEP 236 (Back to the
  __future__) for a description of the __future__ statement.  PEP 227
  (Statically Nested Scopes) has been updated to reflect this change,
  and to clarify the semantics in a number of endcases.

- The nested scopes code, when enabled, has been hardened, and most
  bugs and memory leaks in it have been fixed.

- Compile-time warnings are now generated for a number of conditions
  that will break or change in meaning when nested scopes are enabled:

  - Using "from...import *" or "exec" without in-clause in a function
    scope that also defines a lambda or nested function with one or
    more free (non-local) variables.  The presence of the import* or
    bare exec makes it impossible for the compiler to determine the
    exact set of local variables in the outer scope, which makes it
    impossible to determine the bindings for free variables in the
    inner scope.  To avoid the warning about import *, change it into
    an import of explicitly name object, or move the import* statement
    to the global scope; to avoid the warning about bare exec, use
    exec...in... (a good idea anyway -- there's a possibility that
    bare exec will be deprecated in the future).

  - Use of a global variable in a nested scope with the same name as a
    local variable in a surrounding scope.  This will change in
    meaning with nested scopes: the name in the inner scope will
    reference the variable in the outer scope rather than the global
    of the same name.  To avoid the warning, either rename the outer
    variable, or use a global statement in the inner function.

- An optional object allocator has been included.  This allocator is
  optimized for Python objects and should be faster and use less memory
  than the standard system allocator.  It is not enabled by default
  because of possible thread safety problems.  The allocator is only
  protected by the Python interpreter lock and it is possible that some
  extension modules require a thread safe allocator.  The object
  allocator can be enabled by providing the "--with-pymalloc" option to
  configure.

Standard library

- pyexpat now detects the expat version if expat.h defines it. A
  number of additional handlers are provided, which are only available
  since expat 1.95. In addition, the methods SetParamEntityParsing and
  GetInputContext of Parser objects are available with 1.95.x
  only. Parser objects now provide the ordered_attributes and
  specified_attributes attributes. A new module expat.model was added,
  which offers a number of additional constants if 1.95.x is used.

- xml.dom offers the new functions registerDOMImplementation and
  getDOMImplementation.

- xml.dom.minidom offers a toprettyxml method. A number of DOM
  conformance issues have been resolved. In particular, Element now
  has a hasAttributes method, and the handling of namespaces was
  improved.

- Ka-Ping Yee contributed two new modules: inspect.py, a module for
  getting information about live Python code, and pydoc.py, a module
  for interactively converting docstrings to HTML or text.
  Tools/scripts/pydoc, which is now automatically installed into
  <prefix>/bin, uses pydoc.py to display documentation; try running
  "pydoc -h" for instructions.  "pydoc -g" pops up a small GUI that
  lets you browse the module docstrings using a web browser.

- New library module difflib.py, primarily packaging the SequenceMatcher
  class at the heart of the popular ndiff.py file-comparison tool.

- doctest.py (a framework for verifying Python code examples in docstrings)
  is now part of the std library.

Windows changes

- A new entry in the Start menu, "Module Docs", runs "pydoc -g" -- a
  small GUI that lets you browse the module docstrings using your
  default web browser.

- Import is now case-sensitive.  PEP 235 (Import on Case-Insensitive
  Platforms) is implemented.  See

      http://python.sourceforge.net/peps/pep-0235.html

  for full details, especially the "Current Lower-Left Semantics" section.
  The new Windows import rules are simpler than before:

  A. If the PYTHONCASEOK environment variable exists, same as
     before:  silently accept the first case-insensitive match of any
     kind; raise ImportError if none found.

  B. Else search sys.path for the first case-sensitive match; raise
     ImportError if none found.

  The same rules have been implemented on other platforms with case-
  insensitive but case-preserving filesystems too (including Cygwin, and
  several flavors of Macintosh operating systems).

- winsound module:  Under Win9x, winsound.Beep() now attempts to simulate
  what it's supposed to do (and does do under NT and 2000) via direct
  port manipulation.  It's unknown whether this will work on all systems,
  but it does work on my Win98SE systems now and was known to be useless on
  all Win9x systems before.

- Build:  Subproject _test (effectively) renamed to _testcapi.

New platforms

- 2.1 should compile and run out of the box under MacOS X, even using HFS+.
  Thanks to Steven Majewski!

- 2.1 should compile and run out of the box on Cygwin.  Thanks to Jason
  Tishler!

- 2.1 contains new files and patches for RISCOS, thanks to Dietmar
  Schwertberger!  See RISCOS/README for more information -- it seems
  that because of the bizarre filename conventions on RISCOS, no port
  to that platform is easy.


What's New in Python 2.1 alpha 2?
=================================

Core language, builtins, and interpreter

- Scopes nest.  If a name is used in a function or class, but is not
  local, the definition in the nearest enclosing function scope will
  be used.  One consequence of this change is that lambda statements
  could reference variables in the namespaces where the lambda is
  defined.  In some unusual cases, this change will break code.

  In all previous version of Python, names were resolved in exactly
  three namespaces -- the local namespace, the global namespace, and
  the builtins namespace.  According to this old definition, if a
  function A is defined within a function B, the names bound in B are
  not visible in A.  The new rules make names bound in B visible in A,
  unless A contains a name binding that hides the binding in B.

  Section 4.1 of the reference manual describes the new scoping rules
  in detail.  The test script in Lib/test/test_scope.py demonstrates
  some of the effects of the change.

  The new rules will cause existing code to break if it defines nested
  functions where an outer function has local variables with the same
  name as globals or builtins used by the inner function.  Example:

    def munge(str):
        def helper(x):
            return str(x)
        if type(str) != type(''):
            str = helper(str)
        return str.strip()

  Under the old rules, the name str in helper() is bound to the
  built-in function str().  Under the new rules, it will be bound to
  the argument named str and an error will occur when helper() is
  called.

- The compiler will report a SyntaxError if "from ... import *" occurs
  in a function or class scope.  The language reference has documented
  that this case is illegal, but the compiler never checked for it.
  The recent introduction of nested scope makes the meaning of this
  form of name binding ambiguous.  In a future release, the compiler
  may allow this form when there is no possibility of ambiguity.

- repr(string) is easier to read, now using hex escapes instead of octal,
  and using \t, \n and \r instead of \011, \012 and \015 (respectively):

  >>> "\texample \r\n" + chr(0) + chr(255)
  '\texample \r\n\x00\xff'         # in 2.1
  '\011example \015\012\000\377'   # in 2.0

- Functions are now compared and hashed by identity, not by value, since
  the func_code attribute is writable.

- Weak references (PEP 205) have been added.  This involves a few
  changes in the core, an extension module (_weakref), and a Python
  module (weakref).  The weakref module is the public interface.  It
  includes support for "explicit" weak references, proxy objects, and
  mappings with weakly held values.

- A 'continue' statement can now appear in a try block within the body
  of a loop.  It is still not possible to use continue in a finally
  clause.

Standard library

- mailbox.py now has a new class, PortableUnixMailbox which is
  identical to UnixMailbox but uses a more portable scheme for
  determining From_ separators.  Also, the constructors for all the
  classes in this module have a new optional `factory' argument, which
  is a callable used when new message classes must be instantiated by
  the next() method.

- random.py is now self-contained, and offers all the functionality of
  the now-deprecated whrandom.py.  See the docs for details.  random.py
  also supports new functions getstate() and setstate(), for saving
  and restoring the internal state of the generator; and jumpahead(n),
  for quickly forcing the internal state to be the same as if n calls to
  random() had been made.  The latter is particularly useful for multi-
  threaded programs, creating one instance of the random.Random() class for
  each thread, then using .jumpahead() to force each instance to use a
  non-overlapping segment of the full period.

- random.py's seed() function is new.  For bit-for-bit compatibility with
  prior releases, use the whseed function instead.  The new seed function
  addresses two problems:  (1) The old function couldn't produce more than
  about 2**24 distinct internal states; the new one about 2**45 (the best
  that can be done in the Wichmann-Hill generator).  (2) The old function
  sometimes produced identical internal states when passed distinct
  integers, and there was no simple way to predict when that would happen;
  the new one guarantees to produce distinct internal states for all
  arguments in [0, 27814431486576L).

- The socket module now supports raw packets on Linux.  The socket
  family is AF_PACKET.

- test_capi.py is a start at running tests of the Python C API.  The tests
  are implemented by the new Modules/_testmodule.c.

- A new extension module, _symtable, provides provisional access to the
  internal symbol table used by the Python compiler.  A higher-level
  interface will be added on top of _symtable in a future release.

- Removed the obsolete soundex module.

- xml.dom.minidom now uses the standard DOM exceptions. Node supports
  the isSameNode method; NamedNodeMap the get method.

- xml.sax.expatreader supports the lexical handler property; it
  generates comment, startCDATA, and endCDATA events.

Windows changes

- Build procedure:  the zlib project is built in a different way that
  ensures the zlib header files used can no longer get out of synch with
  the zlib binary used.  See PCbuild\readme.txt for details.  Your old
  zlib-related directories can be deleted; you'll need to download fresh
  source for zlib and unpack it into a new directory.

- Build:  New subproject _test for the benefit of test_capi.py (see above).

- Build:  New subproject _symtable, for new DLL _symtable.pyd (a nascent
  interface to some Python compiler internals).

- Build:  Subproject ucnhash is gone, since the code was folded into the
  unicodedata subproject.

What's New in Python 2.1 alpha 1?
=================================

Core language, builtins, and interpreter

- There is a new Unicode companion to the PyObject_Str() API
  called PyObject_Unicode(). It behaves in the same way as the
  former, but assures that the returned value is a Unicode object
  (applying the usual coercion if necessary).

- The comparison operators support "rich comparison overloading" (PEP
  207).  C extension types can provide a rich comparison function in
  the new tp_richcompare slot in the type object.  The cmp() function
  and the C function PyObject_Compare() first try the new rich
  comparison operators before trying the old 3-way comparison.  There
  is also a new C API PyObject_RichCompare() (which also falls back on
  the old 3-way comparison, but does not constrain the outcome of the
  rich comparison to a Boolean result).

  The rich comparison function takes two objects (at least one of
  which is guaranteed to have the type that provided the function) and
  an integer indicating the opcode, which can be Py_LT, Py_LE, Py_EQ,
  Py_NE, Py_GT, Py_GE (for <, <=, ==, !=, >, >=), and returns a Python
  object, which may be NotImplemented (in which case the tp_compare
  slot function is used as a fallback, if defined).

  Classes can overload individual comparison operators by defining one
  or more of the methods__lt__, __le__, __eq__, __ne__, __gt__,
  __ge__.  There are no explicit "reflected argument" versions of
  these; instead, __lt__ and __gt__ are each other's reflection,
  likewise for__le__ and __ge__; __eq__ and __ne__ are their own
  reflection (similar at the C level).  No other implications are
  made; in particular, Python does not assume that == is the Boolean
  inverse of !=, or that < is the Boolean inverse of >=.  This makes
  it possible to define types with partial orderings.

  Classes or types that want to implement (in)equality tests but not
  the ordering operators (i.e. unordered types) should implement ==
  and !=, and raise an error for the ordering operators.

  It is possible to define types whose rich comparison results are not
  Boolean; e.g. a matrix type might want to return a matrix of bits
  for A < B, giving elementwise comparisons.  Such types should ensure
  that any interpretation of their value in a Boolean context raises
  an exception, e.g. by defining __nonzero__ (or the tp_nonzero slot
  at the C level) to always raise an exception.

- Complex numbers use rich comparisons to define == and != but raise
  an exception for <, <=, > and >=.  Unfortunately, this also means
  that cmp() of two complex numbers raises an exception when the two
  numbers differ.  Since it is not mathematically meaningful to compare
  complex numbers except for equality, I hope that this doesn't break
  too much code.

- The outcome of comparing non-numeric objects of different types is
  not defined by the language, other than that it's arbitrary but
  consistent (see the Reference Manual).  An implementation detail changed
  in 2.1a1 such that None now compares less than any other object.  Code
  relying on this new behavior (like code that relied on the previous
  behavior) does so at its own risk.

- Functions and methods now support getting and setting arbitrarily
  named attributes (PEP 232).  Functions have a new __dict__
  (a.k.a. func_dict) which hold the function attributes.  Methods get
  and set attributes on their underlying im_func.  It is a TypeError
  to set an attribute on a bound method.

- The xrange() object implementation has been improved so that
  xrange(sys.maxint) can be used on 64-bit platforms.  There's still a
  limitation that in this case len(xrange(sys.maxint)) can't be
  calculated, but the common idiom "for i in xrange(sys.maxint)" will
  work fine as long as the index i doesn't actually reach 2**31.
  (Python uses regular ints for sequence and string indices; fixing
  that is much more work.)

- Two changes to from...import:

  1) "from M import X" now works even if (after loading module M)
     sys.modules['M'] is not a real module; it's basically a getattr()
     operation with AttributeError exceptions changed into ImportError.

  2) "from M import *" now looks for M.__all__ to decide which names to
     import; if M.__all__ doesn't exist, it uses M.__dict__.keys() but
     filters out names starting with '_' as before.  Whether or not
     __all__ exists, there's no restriction on the type of M.

- File objects have a new method, xreadlines().  This is the fastest
  way to iterate over all lines in a file:

  for line in file.xreadlines():
      ...do something to line...

  See the xreadlines module (mentioned below) for how to do this for
  other file-like objects.

- Even if you don't use file.xreadlines(), you may expect a speedup on
  line-by-line input.  The file.readline() method has been optimized
  quite a bit in platform-specific ways:  on systems (like Linux) that
  support flockfile(), getc_unlocked(), and funlockfile(), those are
  used by default.  On systems (like Windows) without getc_unlocked(),
  a complicated (but still thread-safe) method using fgets() is used by
  default.

  You can force use of the fgets() method by #define'ing
  USE_FGETS_IN_GETLINE at build time (it may be faster than
  getc_unlocked()).

  You can force fgets() not to be used by #define'ing
  DONT_USE_FGETS_IN_GETLINE (this is the first thing to try if std test
  test_bufio.py fails -- and let us know if it does!).

- In addition, the fileinput module, while still slower than the other
  methods on most platforms, has been sped up too, by using
  file.readlines(sizehint).

- Support for run-time warnings has been added, including a new
  command line option (-W) to specify the disposition of warnings.
  See the description of the warnings module below.

- Extensive changes have been made to the coercion code.  This mostly
  affects extension modules (which can now implement mixed-type
  numerical operators without having to use coercion), but
  occasionally, in boundary cases the coercion semantics have changed
  subtly.  Since this was a terrible gray area of the language, this
  is considered an improvement.  Also note that __rcmp__ is no longer
  supported -- instead of calling __rcmp__, __cmp__ is called with
  reflected arguments.

- In connection with the coercion changes, a new built-in singleton
  object, NotImplemented is defined.  This can be returned for
  operations that wish to indicate they are not implemented for a
  particular combination of arguments.  From C, this is
  Py_NotImplemented.

- The interpreter accepts now bytecode files on the command line even
  if they do not have a .pyc or .pyo extension. On Linux, after executing

import imp,sys,string
magic = string.join(["\\x%.2x" % ord(c) for c in imp.get_magic()],"")
reg = ':pyc:M::%s::%s:' % (magic, sys.executable)
open("/proc/sys/fs/binfmt_misc/register","wb").write(reg)

  any byte code file can be used as an executable (i.e. as an argument
  to execve(2)).

- %[xXo] formats of negative Python longs now produce a sign
  character.  In 1.6 and earlier, they never produced a sign,
  and raised an error if the value of the long was too large
  to fit in a Python int.  In 2.0, they produced a sign if and
  only if too large to fit in an int.  This was inconsistent
  across platforms (because the size of an int varies across
  platforms), and inconsistent with hex() and oct().  Example:

  >>> "%x" % -0x42L
  '-42'      # in 2.1
  'ffffffbe' # in 2.0 and before, on 32-bit machines
  >>> hex(-0x42L)
  '-0x42L'   # in all versions of Python

  The behavior of %d formats for negative Python longs remains
  the same as in 2.0 (although in 1.6 and before, they raised
  an error if the long didn't fit in a Python int).

  %u formats don't make sense for Python longs, but are allowed
  and treated the same as %d in 2.1.  In 2.0, a negative long
  formatted via %u produced a sign if and only if too large to
  fit in an int.  In 1.6 and earlier, a negative long formatted
  via %u raised an error if it was too big to fit in an int.

- Dictionary objects have an odd new method, popitem().  This removes
  an arbitrary item from the dictionary and returns it (in the form of
  a (key, value) pair).  This can be useful for algorithms that use a
  dictionary as a bag of "to do" items and repeatedly need to pick one
  item.  Such algorithms normally end up running in quadratic time;
  using popitem() they can usually be made to run in linear time.

Standard library

- In the time module, the time argument to the functions strftime,
  localtime, gmtime, asctime and ctime is now optional, defaulting to
  the current time (in the local timezone).

- The ftplib module now defaults to passive mode, which is deemed a
  more useful default given that clients are often inside firewalls
  these days.  Note that this could break if ftplib is used to connect
  to a *server* that is inside a firewall, from outside; this is
  expected to be a very rare situation.  To fix that, you can call
  ftp.set_pasv(0).

- The module site now treats .pth files not only for path configuration,
  but also supports extensions to the initialization code: Lines starting
  with import are executed.

- There's a new module, warnings, which implements a mechanism for
  issuing and filtering warnings.  There are some new built-in
  exceptions that serve as warning categories, and a new command line
  option, -W, to control warnings (e.g. -Wi ignores all warnings, -We
  turns warnings into errors).  warnings.warn(message[, category])
  issues a warning message; this can also be called from C as
  PyErr_Warn(category, message).

- A new module xreadlines was added.  This exports a single factory
  function, xreadlines().  The intention is that this code is the
  absolutely fastest way to iterate over all lines in an open
  file(-like) object:

  import xreadlines
  for line in xreadlines.xreadlines(file):
      ...do something to line...

  This is equivalent to the previous the speed record holder using
  file.readlines(sizehint).  Note that if file is a real file object
  (as opposed to a file-like object), this is equivalent:

  for line in file.xreadlines():
      ...do something to line...

- The bisect module has new functions bisect_left, insort_left,
  bisect_right and insort_right.  The old names bisect and insort
  are now aliases for bisect_right and insort_right.  XXX_right
  and XXX_left methods differ in what happens when the new element
  compares equal to one or more elements already in the list:  the
  XXX_left methods insert to the left, the XXX_right methods to the
  right.  Code that doesn't care where equal elements end up should
  continue to use the old, short names ("bisect" and "insort").

- The new curses.panel module wraps the panel library that forms part
  of SYSV curses and ncurses.  Contributed by Thomas Gellekum.

- The SocketServer module now sets the allow_reuse_address flag by
  default in the TCPServer class.

- A new function, sys._getframe(), returns the stack frame pointer of
  the caller.  This is intended only as a building block for
  higher-level mechanisms such as string interpolation.

- The pyexpat module supports a number of new handlers, which are
  available only in expat 1.2. If invocation of a callback fails, it
  will report an additional frame in the traceback. Parser objects
  participate now in garbage collection. If expat reports an unknown
  encoding, pyexpat will try to use a Python codec; that works only
  for single-byte charsets. The parser type objects is exposed as
  XMLParserObject.

- xml.dom now offers standard definitions for symbolic node type and
  exception code constants, and a hierarchy of DOM exceptions. minidom
  was adjusted to use them.

- The conformance of xml.dom.minidom to the DOM specification was
  improved. It detects a number of additional error cases; the
  previous/next relationship works even when the tree is modified;
  Node supports the normalize() method; NamedNodeMap, DocumentType and
  DOMImplementation classes were added; Element supports the
  hasAttribute and hasAttributeNS methods; and Text supports the splitText
  method.

Build issues

- For Unix (and Unix-compatible) builds, configuration and building of
  extension modules is now greatly automated.  Rather than having to
  edit the Modules/Setup file to indicate which modules should be
  built and where their include files and libraries are, a
  distutils-based setup.py script now takes care of building most
  extension modules.  All extension modules built this way are built
  as shared libraries.  Only a few modules that must be linked
  statically are still listed in the Setup file; you won't need to
  edit their configuration.

- Python should now build out of the box on Cygwin.  If it doesn't,
  mail to Jason Tishler (jlt63 at users.sourceforge.net).

- Python now always uses its own (renamed) implementation of getopt()
  -- there's too much variation among C library getopt()
  implementations.

- C++ compilers are better supported; the CXX macro is always set to a
  C++ compiler if one is found.

Windows changes

- select module:  By default under Windows, a select() call
  can specify no more than 64 sockets.  Python now boosts
  this Microsoft default to 512.  If you need even more than
  that, see the MS docs (you'll need to #define FD_SETSIZE
  and recompile Python from source).

- Support for Windows 3.1, DOS and OS/2 is gone.  The Lib/dos-8x3
  subdirectory is no more!


What's New in Python 2.0?
=========================

Below is a list of all relevant changes since release 1.6.  Older
changes are in the file HISTORY.  If you are making the jump directly
from Python 1.5.2 to 2.0, make sure to read the section for 1.6 in the
HISTORY file!  Many important changes listed there.

Alternatively, a good overview of the changes between 1.5.2 and 2.0 is
the document "What's New in Python 2.0" by Kuchling and Moshe Zadka:
http://www.amk.ca/python/2.0/.

--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)

======================================================================

What's new in 2.0 (since release candidate 1)?
==============================================

Standard library

- The copy_reg module was modified to clarify its intended use: to
  register pickle support for extension types, not for classes.
  pickle() will raise a TypeError if it is passed a class.

- Fixed a bug in gettext's "normalize and expand" code that prevented
  it from finding an existing .mo file.

- Restored support for HTTP/0.9 servers in httplib.

- The math module was changed to stop raising OverflowError in case of
  underflow, and return 0 instead in underflow cases.  Whether Python
  used to raise OverflowError in case of underflow was platform-
  dependent (it did when the platform math library set errno to ERANGE
  on underflow).

- Fixed a bug in StringIO that occurred when the file position was not
  at the end of the file and write() was called with enough data to
  extend past the end of the file.

- Fixed a bug that caused Tkinter error messages to get lost on
  Windows.  The bug was fixed by replacing direct use of
  interp->result with Tcl_GetStringResult(interp).

- Fixed bug in urllib2 that caused it to fail when it received an HTTP
  redirect response.

- Several changes were made to distutils: Some debugging code was
  removed from util.  Fixed the installer used when an external zip
  program (like WinZip) is not found; the source code for this
  installer is in Misc/distutils.  check_lib() was modified to behave
  more like AC_CHECK_LIB by add other_libraries() as a parameter.  The
  test for whether installed modules are on sys.path was changed to
  use both normcase() and normpath().

- Several minor bugs were fixed in the xml package (the minidom,
  pulldom, expatreader, and saxutils modules).

- The regression test driver (regrtest.py) behavior when invoked with
  -l changed: It now reports a count of objects that are recognized as
  garbage but not freed by the garbage collector.

- The regression test for the math module was changed to test
  exceptional behavior when the test is run in verbose mode.  Python
  cannot yet guarantee consistent exception behavior across platforms,
  so the exception part of test_math is run only in verbose mode, and
  may fail on your platform.

Internals

- PyOS_CheckStack() has been disabled on Win64, where it caused
  test_sre to fail.

Build issues

- Changed compiler flags, so that gcc is always invoked with -Wall and
  -Wstrict-prototypes.  Users compiling Python with GCC should see
  exactly one warning, except if they have passed configure the
  --with-pydebug flag.  The expected warning is for getopt() in
  Modules/main.c.  This warning will be fixed for Python 2.1.

- Fixed configure to add -threads argument during linking on OSF1.

Tools and other miscellany

- The compiler in Tools/compiler was updated to support the new
  language features introduced in 2.0: extended print statement, list
  comprehensions, and augmented assignments.  The new compiler should
  also be backwards compatible with Python 1.5.2; the compiler will
  always generate code for the version of the interpreter it runs
  under.

What's new in 2.0 release candidate 1 (since beta 2)?
=====================================================

What is release candidate 1?

We believe that release candidate 1 will fix all known bugs that we
intend to fix for the 2.0 final release.  This release should be a bit
more stable than the previous betas.  We would like to see even more
widespread testing before the final release, so we are producing this
release candidate.  The final release will be exactly the same unless
any show-stopping (or brown bag) bugs are found by testers of the
release candidate.

All the changes since the last beta release are bug fixes or changes
to support building Python for specific platforms.

Core language, builtins, and interpreter

- A bug that caused crashes when __coerce__ was used with augmented
  assignment, e.g. +=, was fixed.

- Raise ZeroDivisionError when raising zero to a negative number,
  e.g. 0.0 ** -2.0.  Note that math.pow is unrelated to the built-in
  power operator and the result of math.pow(0.0, -2.0) will vary by
  platform.  On Linux, it raises a ValueError.

- A bug in Unicode string interpolation was fixed that occasionally
  caused errors with formats including "%%".  For example, the
  following expression "%% %s" % u"abc" no longer raises a TypeError.

- Compilation of deeply nested expressions raises MemoryError instead
  of SyntaxError, e.g. eval("[" * 50 + "]" * 50).

- In 2.0b2 on Windows, the interpreter wrote .pyc files in text mode,
  rendering them useless.  They are now written in binary mode again.

Standard library

- Keyword arguments are now accepted for most pattern and match object
  methods in SRE, the standard regular expression engine.

- In SRE, fixed error with negative lookahead and lookbehind that
  manifested itself as a runtime error in patterns like "(?<!abc)(def)".

- Several bugs in the Unicode handling and error handling in _tkinter
  were fixed.

- Fix memory management errors in Merge() and Tkapp_Call() routines.

- Several changes were made to cStringIO to make it compatible with
  the file-like object interface and with StringIO.  If operations are
  performed on a closed object, an exception is raised.  The truncate
  method now accepts a position argument and readline accepts a size
  argument.

- There were many changes made to the linuxaudiodev module and its
  test suite; as a result, a short, unexpected audio sample should now
  play when the regression test is run.

  Note that this module is named poorly, because it should work
  correctly on any platform that supports the Open Sound System
  (OSS).

  The module now raises exceptions when errors occur instead of
  crashing.  It also defines the AFMT_A_LAW format (logarithmic A-law
  audio) and defines a getptr() method that calls the
  SNDCTL_DSP_GETxPTR ioctl defined in the OSS Programmer's Guide.

- The library_version attribute, introduced in an earlier beta, was
  removed because it can not be supported with early versions of the C
  readline library, which provides no way to determine the version at
  compile-time.

- The binascii module is now enabled on Win64.

- tokenize.py no longer suffers "recursion depth" errors when parsing
  programs with very long string literals.

Internals

- Fixed several buffer overflow vulnerabilities in calculate_path(),
  which is called when the interpreter starts up to determine where
  the standard library is installed.  These vulnerabilities affect all
  previous versions of Python and can be exploited by setting very
  long values for PYTHONHOME or argv[0].  The risk is greatest for a
  setuid Python script, although use of the wrapper in
  Misc/setuid-prog.c will eliminate the vulnerability.

- Fixed garbage collection bugs in instance creation that were
  triggered when errors occurred during initialization.  The solution,
  applied in cPickle and in PyInstance_New(), is to call
  PyObject_GC_Init() after the initialization of the object's
  container attributes is complete.

- pyexpat adds definitions of PyModule_AddStringConstant and
  PyModule_AddObject if the Python version is less than 2.0, which
  provides compatibility with PyXML on Python 1.5.2.

- If the platform has a bogus definition for LONG_BIT (the number of
  bits in a long), an error will be reported at compile time.

- Fix bugs in _PyTuple_Resize() which caused hard-to-interpret garbage
  collection crashes and possibly other, unreported crashes.

- Fixed a memory leak in _PyUnicode_Fini().

Build issues

- configure now accepts a --with-suffix option that specifies the
  executable suffix.  This is useful for builds on Cygwin and Mac OS
  X, for example.

- The mmap.PAGESIZE constant is now initialized using sysconf when
  possible, which eliminates a dependency on -lucb for Reliant UNIX.

- The md5 file should now compile on all platforms.

- The select module now compiles on platforms that do not define
  POLLRDNORM and related constants.

- Darwin (Mac OS X):  Initial support for static builds on this
  platform.

- BeOS: A number of changes were made to the build and installation
  process.  ar-fake now operates on a directory of object files.
  dl_export.h is gone, and its macros now appear on the mwcc command
  line during build on PPC BeOS.

- Platform directory in lib/python2.0 is "plat-beos5" (or
  "plat-beos4", if building on BeOS 4.5), rather than "plat-beos".

- Cygwin: Support for shared libraries, Tkinter, and sockets.

- SunOS 4.1.4_JL: Fix test for directory existence in configure.

Tools and other miscellany

- Removed debugging prints from main used with freeze.

- IDLE auto-indent no longer crashes when it encounters Unicode
  characters.

What's new in 2.0 beta 2 (since beta 1)?
========================================

Core language, builtins, and interpreter

- Add support for unbounded ints in %d,i,u,x,X,o formats; for example
  "%d" % 2L**64 == "18446744073709551616".

- Add -h and -V command line options to print the usage message and
  Python version number and exit immediately.

- eval() and exec accept Unicode objects as code parameters.

- getattr() and setattr() now also accept Unicode objects for the
  attribute name, which are converted to strings using the default
  encoding before lookup.

- Multiplication on string and Unicode now does proper bounds
  checking; e.g. 'a' * 65536 * 65536 will raise ValueError, "repeated
  string is too long."

- Better error message when continue is found in try statement in a
  loop.


Standard library and extensions

- socket module: the OpenSSL code now adds support for RAND_status()
  and EGD (Entropy Gathering Device).

- array: reverse() method of array now works.  buffer_info() now does
  argument checking; it still takes no arguments.

- asyncore/asynchat: Included most recent version from Sam Rushing.

- cgi: Accept '&' or ';' as separator characters when parsing form data.

- CGIHTTPServer: Now works on Windows (and perhaps even Mac).

- ConfigParser: When reading the file, options spelled in upper case
  letters are now correctly converted to lowercase.

- copy: Copy Unicode objects atomically.

- cPickle: Fail gracefully when copy_reg can't be imported.

- cStringIO: Implemented readlines() method.

- dbm: Add get() and setdefault() methods to dbm object.  Add constant
  `library' to module that names the library used.  Added doc strings
  and method names to error messages.  Uses configure to determine
  which ndbm.h file to include; Berkeley DB's nbdm and GDBM's ndbm is
  now available options.

- distutils: Update to version 0.9.3.

- dl: Add several dl.RTLD_ constants.

- fpectl: Now supported on FreeBSD.

- gc: Add DEBUG_SAVEALL option.  When enabled all garbage objects
  found by the collector will be saved in gc.garbage.  This is useful
  for debugging a program that creates reference cycles.

- httplib: Three changes: Restore support for set_debuglevel feature
  of HTTP class.  Do not close socket on zero-length response.  Do not
  crash when server sends invalid content-length header.

- mailbox: Mailbox class conforms better to qmail specifications.

- marshal: When reading a short, sign-extend on platforms where shorts
  are bigger than 16 bits.  When reading a long, repair the unportable
  sign extension that was being done for 64-bit machines.  (It assumed
  that signed right shift sign-extends.)

- operator: Add contains(), invert(), __invert__() as aliases for
  __contains__(), inv(), and __inv__() respectively.

- os: Add support for popen2() and popen3() on all platforms where
  fork() exists.  (popen4() is still in the works.)

- os: (Windows only:) Add startfile() function that acts like double-
  clicking on a file in Explorer (or passing the file name to the
  DOS "start" command).

- os.path: (Windows, DOS:) Treat trailing colon correctly in
  os.path.join.  os.path.join("a:", "b") yields "a:b".

- pickle: Now raises ValueError when an invalid pickle that contains
  a non-string repr where a string repr was expected.  This behavior
  matches cPickle.

- posixfile: Remove broken __del__() method.

- py_compile: support CR+LF line terminators in source file.

- readline: Does not immediately exit when ^C is hit when readline and
  threads are configured.  Adds definition of rl_library_version.  (The
  latter addition requires GNU readline 2.2 or later.)

- rfc822: Domain literals returned by AddrlistClass method
  getdomainliteral() are now properly wrapped in brackets.

- site: sys.setdefaultencoding() should only be called in case the
  standard default encoding ("ascii") is changed. This saves quite a
  few cycles during startup since the first call to
  setdefaultencoding() will initialize the codec registry and the
  encodings package.

- socket: Support for size hint in readlines() method of object returned
  by makefile().

- sre: Added experimental expand() method to match objects.  Does not
  use buffer interface on Unicode strings.  Does not hang if group id
  is followed by whitespace.

- StringIO: Size hint in readlines() is now supported as documented.

- struct: Check ranges for bytes and shorts.

- urllib: Improved handling of win32 proxy settings. Fixed quote and
  quote_plus functions so that the always encode a comma.

- Tkinter: Image objects are now guaranteed to have unique ids.  Set
  event.delta to zero if Tk version doesn't support mousewheel.
  Removed some debugging prints.

- UserList: now implements __contains__().

- webbrowser: On Windows, use os.startfile() instead of os.popen(),
  which works around a bug in Norton AntiVirus 2000 that leads directly
  to a Blue Screen freeze.

- xml: New version detection code allows PyXML to override standard
  XML package if PyXML version is greater than 0.6.1.

- xml.dom: DOM level 1 support for basic XML.  Includes xml.dom.minidom
  (conventional DOM), and xml.dom.pulldom, which allows building the DOM
  tree only for nodes which are sufficiently interesting to a specific
  application.  Does not provide the HTML-specific extensions.  Still
  undocumented.

- xml.sax: SAX 2 support for Python, including all the handler
  interfaces needed to process XML 1.0 compliant XML.  Some
  documentation is already available.

- pyexpat: Renamed to xml.parsers.expat since this is part of the new,
  packagized XML support.


C API

- Add three new convenience functions for module initialization --
  PyModule_AddObject(), PyModule_AddIntConstant(), and
  PyModule_AddStringConstant().

- Cleaned up definition of NULL in C source code; all definitions were
  removed and add #error to Python.h if NULL isn't defined after
  #include of stdio.h.

- Py_PROTO() macros that were removed in 2.0b1 have been restored for
  backwards compatibility (at the source level) with old extensions.

- A wrapper API was added for signal() and sigaction().  Instead of
  either function, always use PyOS_getsig() to get a signal handler
  and PyOS_setsig() to set one.  A new convenience typedef
  PyOS_sighandler_t is defined for the type of signal handlers.

- Add PyString_AsStringAndSize() function that provides access to the
  internal data buffer and size of a string object -- or the default
  encoded version of a Unicode object.

- PyString_Size() and PyString_AsString() accept Unicode objects.

- The standard header <limits.h> is now included by Python.h (if it
  exists).  INT_MAX and LONG_MAX will always be defined, even if
  <limits.h> is not available.

- PyFloat_FromString takes a second argument, pend, that was
  effectively useless.  It is now officially useless but preserved for
  backwards compatibility.  If the pend argument is not NULL, *pend is
  set to NULL.

- PyObject_GetAttr() and PyObject_SetAttr() now accept Unicode objects
  for the attribute name.  See note on getattr() above.

- A few bug fixes to argument processing for Unicode.
  PyArg_ParseTupleAndKeywords() now accepts "es#" and "es".
  PyArg_Parse() special cases "s#" for Unicode objects; it returns a
  pointer to the default encoded string data instead of to the raw
  UTF-16.

- Py_BuildValue accepts B format (for bgen-generated code).


Internals

- On Unix, fix code for finding Python installation directory so that
  it works when argv[0] is a relative path.

- Added a true unicode_internal_encode() function and fixed the
  unicode_internal_decode function() to support Unicode objects directly
  rather than by generating a copy of the object.

- Several of the internal Unicode tables are much smaller now, and
  the source code should be much friendlier to weaker compilers.

- In the garbage collector: Fixed bug in collection of tuples.  Fixed
  bug that caused some instances to be removed from the container set
  while they were still live.  Fixed parsing in gc.set_debug() for
  platforms where sizeof(long) > sizeof(int).

- Fixed refcount problem in instance deallocation that only occurred
  when Py_REF_DEBUG was defined and Py_TRACE_REFS was not.

- On Windows, getpythonregpath is now protected against null data in
  registry key.

- On Unix, create .pyc/.pyo files with O_EXCL flag to avoid a race
  condition.


Build and platform-specific issues

- Better support of GNU Pth via --with-pth configure option.

- Python/C API now properly exposed to dynamically-loaded extension
  modules on Reliant UNIX.

- Changes for the benefit of SunOS 4.1.4 (really!).  mmapmodule.c:
  Don't define MS_SYNC to be zero when it is undefined.  Added missing
  prototypes in posixmodule.c.

- Improved support for HP-UX build.  Threads should now be correctly
  configured (on HP-UX 10.20 and 11.00).

- Fix largefile support on older NetBSD systems and OpenBSD by adding
  define for TELL64.


Tools and other miscellany

- ftpmirror: Call to main() is wrapped in if __name__ == "__main__".

- freeze: The modulefinder now works with 2.0 opcodes.

- IDLE:
  Move hackery of sys.argv until after the Tk instance has been
  created, which allows the application-specific Tkinter
  initialization to be executed if present; also pass an explicit
  className parameter to the Tk() constructor.


What's new in 2.0 beta 1?
=========================

Source Incompatibilities
------------------------

None.  Note that 1.6 introduced several incompatibilities with 1.5.2,
such as single-argument append(), connect() and bind(), and changes to
str(long) and repr(float).


Binary Incompatibilities
------------------------

- Third party extensions built for Python 1.5.x or 1.6 cannot be used
with Python 2.0; these extensions will have to be rebuilt for Python
2.0.

- On Windows, attempting to import a third party extension built for
Python 1.5.x or 1.6 results in an immediate crash; there's not much we
can do about this.  Check your PYTHONPATH environment variable!

- Python bytecode files (*.pyc and *.pyo) are not compatible between
releases.


Overview of Changes Since 1.6
-----------------------------

There are many new modules (including brand new XML support through
the xml package, and i18n support through the gettext module); a list
of all new modules is included below.  Lots of bugs have been fixed.

The process for making major new changes to the language has changed
since Python 1.6.  Enhancements must now be documented by a Python
Enhancement Proposal (PEP) before they can be accepted.

There are several important syntax enhancements, described in more
detail below:

  - Augmented assignment, e.g. x += 1

  - List comprehensions, e.g. [x**2 for x in range(10)]

  - Extended import statement, e.g. import Module as Name

  - Extended print statement, e.g. print >> file, "Hello"

Other important changes:

  - Optional collection of cyclical garbage

Python Enhancement Proposal (PEP)
---------------------------------

PEP stands for Python Enhancement Proposal.  A PEP is a design
document providing information to the Python community, or describing
a new feature for Python.  The PEP should provide a concise technical
specification of the feature and a rationale for the feature.

We intend PEPs to be the primary mechanisms for proposing new
features, for collecting community input on an issue, and for
documenting the design decisions that have gone into Python.  The PEP
author is responsible for building consensus within the community and
documenting dissenting opinions.

The PEPs are available at http://python.sourceforge.net/peps/.

Augmented Assignment
--------------------

This must have been the most-requested feature of the past years!
Eleven new assignment operators were added:

    += -= *= /= %= **= <<= >>= &= ^= |=

For example,

    A += B

is similar to

    A = A + B

except that A is evaluated only once (relevant when A is something
like dict[index].attr).

However, if A is a mutable object, A may be modified in place.  Thus,
if A is a number or a string, A += B has the same effect as A = A+B
(except A is only evaluated once); but if a is a list, A += B has the
same effect as A.extend(B)!

Classes and built-in object types can override the new operators in
order to implement the in-place behavior; the not-in-place behavior is
used automatically as a fallback when an object doesn't implement the
in-place behavior.  For classes, the method name is derived from the
method name for the corresponding not-in-place operator by inserting
an 'i' in front of the name, e.g. __iadd__ implements in-place
__add__.

Augmented assignment was implemented by Thomas Wouters.


List Comprehensions
-------------------

This is a flexible new notation for lists whose elements are computed
from another list (or lists).  The simplest form is:

    [<expression> for <variable> in <sequence>]

For example, [i**2 for i in range(4)] yields the list [0, 1, 4, 9].
This is more efficient than a for loop with a list.append() call.

You can also add a condition:

    [<expression> for <variable> in <sequence> if <condition>]

For example, [w for w in words if w == w.lower()] would yield the list
of words that contain no uppercase characters.  This is more efficient
than a for loop with an if statement and a list.append() call.

You can also have nested for loops and more than one 'if' clause.  For
example, here's a function that flattens a sequence of sequences::

    def flatten(seq):
        return [x for subseq in seq for x in subseq]

    flatten([[0], [1,2,3], [4,5], [6,7,8,9], []])

This prints

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions originated as a patch set from Greg Ewing; Skip
Montanaro and Thomas Wouters also contributed.  Described by PEP 202.


Extended Import Statement
-------------------------

Many people have asked for a way to import a module under a different
name.  This can be accomplished like this:

    import foo
    bar = foo
    del foo

but this common idiom gets old quickly.  A simple extension of the
import statement now allows this to be written as follows:

    import foo as bar

There's also a variant for 'from ... import':

    from foo import bar as spam

This also works with packages; e.g. you can write this:

    import test.regrtest as regrtest

Note that 'as' is not a new keyword -- it is recognized only in this
context (this is only possible because the syntax for the import
statement doesn't involve expressions).

Implemented by Thomas Wouters.  Described by PEP 221.


Extended Print Statement
------------------------

Easily the most controversial new feature, this extension to the print
statement adds an option to make the output go to a different file
than the default sys.stdout.

For example, to write an error message to sys.stderr, you can now
write:

    print >> sys.stderr, "Error: bad dog!"

As a special feature, if the expression used to indicate the file
evaluates to None, the current value of sys.stdout is used.  Thus:

    print >> None, "Hello world"

is equivalent to

    print "Hello world"

Design and implementation by Barry Warsaw.  Described by PEP 214.


Optional Collection of Cyclical Garbage
---------------------------------------

Python is now equipped with a garbage collector that can hunt down
cyclical references between Python objects.  It's no replacement for
reference counting; in fact, it depends on the reference counts being
correct, and decides that a set of objects belong to a cycle if all
their reference counts can be accounted for from their references to
each other.  This devious scheme was first proposed by Eric Tiedemann,
and brought to implementation by Neil Schemenauer.

There's a module "gc" that lets you control some parameters of the
garbage collection.  There's also an option to the configure script
that lets you enable or disable the garbage collection.  In 2.0b1,
it's on by default, so that we (hopefully) can collect decent user
experience with this new feature.  There are some questions about its
performance.  If it proves to be too much of a problem, we'll turn it
off by default in the final 2.0 release.


Smaller Changes
---------------

A new function zip() was added.  zip(seq1, seq2, ...) is equivalent to
map(None, seq1, seq2, ...) when the sequences have the same length;
i.e. zip([1,2,3], [10,20,30]) returns [(1,10), (2,20), (3,30)].  When
the lists are not all the same length, the shortest list wins:
zip([1,2,3], [10,20]) returns [(1,10), (2,20)].  See PEP 201.

sys.version_info is a tuple (major, minor, micro, level, serial).

Dictionaries have an odd new method, setdefault(key, default).
dict.setdefault(key, default) returns dict[key] if it exists; if not,
it sets dict[key] to default and returns that value.  Thus:

    dict.setdefault(key, []).append(item)

does the same work as this common idiom:

    if not dict.has_key(key):
        dict[key] = []
    dict[key].append(item)

There are two new variants of SyntaxError that are raised for
indentation-related errors: IndentationError and TabError.

Changed \x to consume exactly two hex digits; see PEP 223.  Added \U
escape that consumes exactly eight hex digits.

The limits on the size of expressions and file in Python source code
have been raised from 2**16 to 2**32.  Previous versions of Python
were limited because the maximum argument size the Python VM accepted
was 2**16.  This limited the size of object constructor expressions,
e.g. [1,2,3] or {'a':1, 'b':2}, and the size of source files.  This
limit was raised thanks to a patch by Charles Waldman that effectively
fixes the problem.  It is now much more likely that you will be
limited by available memory than by an arbitrary limit in Python.

The interpreter's maximum recursion depth can be modified by Python
programs using sys.getrecursionlimit and sys.setrecursionlimit.  This
limit is the maximum number of recursive calls that can be made by
Python code.  The limit exists to prevent infinite recursion from
overflowing the C stack and causing a core dump.  The default value is
1000.  The maximum safe value for a particular platform can be found
by running Tools/scripts/find_recursionlimit.py.

New Modules and Packages
------------------------

atexit - for registering functions to be called when Python exits.

imputil - Greg Stein's alternative API for writing custom import
hooks.

pyexpat - an interface to the Expat XML parser, contributed by Paul
Prescod.

xml - a new package with XML support code organized (so far) in three
subpackages: xml.dom, xml.sax, and xml.parsers.  Describing these
would fill a volume.  There's a special feature whereby a
user-installed package named _xmlplus overrides the standard
xmlpackage; this is intended to give the XML SIG a hook to distribute
backwards-compatible updates to the standard xml package.

webbrowser - a platform-independent API to launch a web browser.


Changed Modules
---------------

array -- new methods for array objects: count, extend, index, pop, and
remove

binascii -- new functions b2a_hex and a2b_hex that convert between
binary data and its hex representation

calendar -- Many new functions that support features including control
over which day of the week is the first day, returning strings instead
of printing them.  Also new symbolic constants for days of week,
e.g. MONDAY, ..., SUNDAY.

cgi -- FieldStorage objects have a getvalue method that works like a
dictionary's get method and returns the value attribute of the object.

ConfigParser -- The parser object has new methods has_option,
remove_section, remove_option, set, and write.  They allow the module
to be used for writing config files as well as reading them.

ftplib -- ntransfercmd(), transfercmd(), and retrbinary() all now
optionally support the RFC 959 REST command.

gzip -- readline and readlines now accept optional size arguments

httplib -- New interfaces and support for HTTP/1.1 by Greg Stein.  See
the module doc strings for details.

locale -- implement getdefaultlocale for Win32 and Macintosh

marshal -- no longer dumps core when marshaling deeply nested or
recursive data structures

os -- new functions isatty, seteuid, setegid, setreuid, setregid

os/popen2 -- popen2/popen3/popen4 support under Windows.  popen2/popen3
support under Unix.

os/pty -- support for openpty and forkpty

os.path -- fix semantics of os.path.commonprefix

smtplib -- support for sending very long messages

socket -- new function getfqdn()

readline -- new functions to read, write and truncate history files.
The readline section of the library reference manual contains an
example.

select -- add interface to poll system call

shutil -- new copyfileobj function

SimpleHTTPServer, CGIHTTPServer -- Fix problems with buffering in the
HTTP server.

Tkinter -- optimization of function flatten

urllib -- scans environment variables for proxy configuration,
e.g. http_proxy.

whichdb -- recognizes dumbdbm format


Obsolete Modules
----------------

None.  However note that 1.6 made a whole slew of modules obsolete:
stdwin, soundex, cml, cmpcache, dircache, dump, find, grep, packmail,
poly, zmod, strop, util, whatsound.


Changed, New, Obsolete Tools
----------------------------

None.


C-level Changes
---------------

Several cleanup jobs were carried out throughout the source code.

All C code was converted to ANSI C; we got rid of all uses of the
Py_PROTO() macro, which makes the header files a lot more readable.

Most of the portability hacks were moved to a new header file,
pyport.h; several other new header files were added and some old
header files were removed, in an attempt to create a more rational set
of header files.  (Few of these ever need to be included explicitly;
they are all included by Python.h.)

Trent Mick ensured portability to 64-bit platforms, under both Linux
and Win64, especially for the new Intel Itanium processor.  Mick also
added large file support for Linux64 and Win64.

The C APIs to return an object's size have been update to consistently
use the form PyXXX_Size, e.g. PySequence_Size and PyDict_Size.  In
previous versions, the abstract interfaces used PyXXX_Length and the
concrete interfaces used PyXXX_Size.  The old names,
e.g. PyObject_Length, are still available for backwards compatibility
at the API level, but are deprecated.

The PyOS_CheckStack function has been implemented on Windows by
Fredrik Lundh.  It prevents Python from failing with a stack overflow
on Windows.

The GC changes resulted in creation of two new slots on object,
tp_traverse and tp_clear.  The augmented assignment changes result in
the creation of a new slot for each in-place operator.

The GC API creates new requirements for container types implemented in
C extension modules.  See Include/objimpl.h for details.

PyErr_Format has been updated to automatically calculate the size of
the buffer needed to hold the formatted result string.  This change
prevents crashes caused by programmer error.

New C API calls: PyObject_AsFileDescriptor, PyErr_WriteUnraisable.

PyRun_AnyFileEx, PyRun_SimpleFileEx, PyRun_FileEx -- New functions
that are the same as their non-Ex counterparts except they take an
extra flag argument that tells them to close the file when done.

XXX There were other API changes that should be fleshed out here.


Windows Changes
---------------

New popen2/popen3/peopen4 in os module (see Changed Modules above).

os.popen is much more usable on Windows 95 and 98.  See Microsoft
Knowledge Base article Q150956.  The Win9x workaround described there
is implemented by the new w9xpopen.exe helper in the root of your
Python installation.  Note that Python uses this internally; it is not
a standalone program.

Administrator privileges are no longer required to install Python
on Windows NT or Windows 2000.  If you have administrator privileges,
Python's registry info will be written under HKEY_LOCAL_MACHINE.
Otherwise the installer backs off to writing Python's registry info
under HKEY_CURRENT_USER.  The latter is sufficient for all "normal"
uses of Python, but will prevent some advanced uses from working
(for example, running a Python script as an NT service, or possibly
from CGI).

[This was new in 1.6] The installer no longer runs a separate Tcl/Tk
installer; instead, it installs the needed Tcl/Tk files directly in the
Python directory.  If you already have a Tcl/Tk installation, this
wastes some disk space (about 4 Megs) but avoids problems with
conflicting Tcl/Tk installations, and makes it much easier for Python
to ensure that Tcl/Tk can find all its files.

[This was new in 1.6] The Windows installer now installs by default in
\Python20\ on the default volume, instead of \Program Files\Python-2.0\.


Updates to the changes between 1.5.2 and 1.6
--------------------------------------------

The 1.6 NEWS file can't be changed after the release is done, so here
is some late-breaking news:

New APIs in locale.py: normalize(), getdefaultlocale(), resetlocale(),
and changes to getlocale() and setlocale().

The new module is now enabled per default.

It is not true that the encodings codecs cannot be used for normal
strings: the string.encode() (which is also present on 8-bit strings
!) allows using them for 8-bit strings too, e.g. to convert files from
cp1252 (Windows) to latin-1 or vice-versa.

Japanese codecs are available from Tamito KAJIYAMA:
http://pseudo.grad.sccs.chukyo-u.ac.jp/~kajiyama/python/


======================================================================


=======================================
==> Release 1.6 (September 5, 2000) <==
=======================================

What's new in release 1.6?
==========================

Below is a list of all relevant changes since release 1.5.2.


Source Incompatibilities
------------------------

Several small incompatible library changes may trip you up:

  - The append() method for lists can no longer be invoked with more
  than one argument.  This used to append a single tuple made out of
  all arguments, but was undocumented.  To append a tuple, use
  e.g. l.append((a, b, c)).

  - The connect(), connect_ex() and bind() methods for sockets require
  exactly one argument.  Previously, you could call s.connect(host,
  port), but this was undocumented. You must now write
  s.connect((host, port)).

  - The str() and repr() functions are now different more often.  For
  long integers, str() no longer appends a 'L'.  Thus, str(1L) == '1',
  which used to be '1L'; repr(1L) is unchanged and still returns '1L'.
  For floats, repr() now gives 17 digits of precision, to ensure no
  precision is lost (on all current hardware).

  - The -X option is gone.  Built-in exceptions are now always
  classes.  Many more library modules also have been converted to
  class-based exceptions.


Binary Incompatibilities
------------------------

- Third party extensions built for Python 1.5.x cannot be used with
Python 1.6; these extensions will have to be rebuilt for Python 1.6.

- On Windows, attempting to import a third party extension built for
Python 1.5.x results in an immediate crash; there's not much we can do
about this.  Check your PYTHONPATH environment variable!


Overview of Changes since 1.5.2
-------------------------------

For this overview, I have borrowed from the document "What's New in
Python 2.0" by Andrew Kuchling and Moshe Zadka:
http://www.amk.ca/python/2.0/ .

There are lots of new modules and lots of bugs have been fixed.  A
list of all new modules is included below.

Probably the most pervasive change is the addition of Unicode support.
We've added a new fundamental datatype, the Unicode string, a new
built-in function unicode(), a numerous C APIs to deal with Unicode
and encodings.  See the file Misc/unicode.txt for details, or
http://starship.python.net/crew/lemburg/unicode-proposal.txt.

Two other big changes, related to the Unicode support, are the
addition of string methods and (yet another) new regular expression
engine.

  - String methods mean that you can now say s.lower() etc. instead of
  importing the string module and saying string.lower(s) etc.  One
  peculiarity is that the equivalent of string.join(sequence,
  delimiter) is delimiter.join(sequence).  Use " ".join(sequence) for
  the effect of string.join(sequence); to make this more readable, try
  space=" " first.  Note that the maxsplit argument defaults in
  split() and replace() have changed from 0 to -1.

  - The new regular expression engine, SRE by Fredrik Lundh, is fully
  backwards compatible with the old engine, and is in fact invoked
  using the same interface (the "re" module).  You can explicitly
  invoke the old engine by import pre, or the SRE engine by importing
  sre.  SRE is faster than pre, and supports Unicode (which was the
  main reason to put effort in yet another new regular expression
  engine -- this is at least the fourth!).


Other Changes
-------------

Other changes that won't break code but are nice to know about:

Deleting objects is now safe even for deeply nested data structures.

Long/int unifications: long integers can be used in seek() calls, as
slice indexes.

String formatting (s % args) has a new formatting option, '%r', which
acts like '%s' but inserts repr(arg) instead of str(arg). (Not yet in
alpha 1.)

Greg Ward's "distutils" package is included: this will make
installing, building and distributing third party packages much
simpler.

There's now special syntax that you can use instead of the apply()
function.  f(*args, **kwds) is equivalent to apply(f, args, kwds).
You can also use variations f(a1, a2, *args, **kwds) and you can leave
one or the other out: f(*args), f(**kwds).

The built-ins int() and long() take an optional second argument to
indicate the conversion base -- of course only if the first argument
is a string.  This makes string.atoi() and string.atol() obsolete.
(string.atof() was already obsolete).

When a local variable is known to the compiler but undefined when
used, a new exception UnboundLocalError is raised.  This is a class
derived from NameError so code catching NameError should still work.
The purpose is to provide better diagnostics in the following example:
  x = 1
  def f():
      print x
      x = x+1
This used to raise a NameError on the print statement, which confused
even experienced Python programmers (especially if there are several
hundreds of lines of code between the reference and the assignment to
x :-).

You can now override the 'in' operator by defining a __contains__
method.  Note that it has its arguments backwards: x in a causes
a.__contains__(x) to be called.  That's why the name isn't __in__.

The exception AttributeError will have a more friendly error message,
e.g.: <code>'Spam' instance has no attribute 'eggs'</code>.  This may
<b>break code</b> that expects the message to be exactly the attribute
name.


New Modules in 1.6
------------------

UserString - base class for deriving from the string type.

distutils - tools for distributing Python modules.

robotparser - parse a robots.txt file, for writing web spiders.
(Moved from Tools/webchecker/.)

linuxaudiodev - audio for Linux.

mmap - treat a file as a memory buffer.  (Windows and Unix.)

sre - regular expressions (fast, supports unicode).  Currently, this
code is very rough.  Eventually, the re module will be reimplemented
using sre (without changes to the re API).

filecmp - supersedes the old cmp.py and dircmp.py modules.

tabnanny - check Python sources for tab-width dependance.  (Moved from
Tools/scripts/.)

urllib2 - new and improved but incompatible version of urllib (still
experimental).

zipfile - read and write zip archives.

codecs - support for Unicode encoders/decoders.

unicodedata - provides access to the Unicode 3.0 database.

_winreg - Windows registry access.

encodings - package which provides a large set of standard codecs --
currently only for the new Unicode support. It has a drop-in extension
mechanism which allows you to add new codecs by simply copying them
into the encodings package directory. Asian codec support will
probably be made available as separate distribution package built upon
this technique and the new distutils package.


Changed Modules
---------------

readline, ConfigParser, cgi, calendar, posix, readline, xmllib, aifc,
chunk, wave, random, shelve, nntplib - minor enhancements.

socket, httplib, urllib - optional OpenSSL support (Unix only).

_tkinter - support for 8.0 up to 8.3.  Support for versions older than
8.0 has been dropped.

string - most of this module is deprecated now that strings have
methods.  This no longer uses the built-in strop module, but takes
advantage of the new string methods to provide transparent support for
both Unicode and ordinary strings.


Changes on Windows
------------------

The installer no longer runs a separate Tcl/Tk installer; instead, it
installs the needed Tcl/Tk files directly in the Python directory.  If
you already have a Tcl/Tk installation, this wastes some disk space
(about 4 Megs) but avoids problems with conflincting Tcl/Tk
installations, and makes it much easier for Python to ensure that
Tcl/Tk can find all its files.  Note: the alpha installers don't
include the documentation.

The Windows installer now installs by default in \Python16\ on the
default volume, instead of \Program Files\Python-1.6\.


Changed Tools
-------------

IDLE - complete overhaul.  See the <a href="../idle/">IDLE home
page</a> for more information.  (Python 1.6 alpha 1 will come with
IDLE 0.6.)

Tools/i18n/pygettext.py - Python equivalent of xgettext(1).  A message
text extraction tool used for internationalizing applications written
in Python.


Obsolete Modules
----------------

stdwin and everything that uses it.  (Get Python 1.5.2 if you need
it. :-)

soundex.  (Skip Montanaro has a version in Python but it won't be
included in the Python release.)

cmp, cmpcache, dircmp.  (Replaced by filecmp.)

dump.  (Use pickle.)

find.  (Easily coded using os.walk().)

grep.  (Not very useful as a library module.)

packmail.  (No longer has any use.)

poly, zmod.  (These were poor examples at best.)

strop.  (No longer needed by the string module.)

util.  (This functionality was long ago built in elsewhere).

whatsound.  (Use sndhdr.)


Detailed Changes from 1.6b1 to 1.6
----------------------------------

- Slight changes to the CNRI license.  A copyright notice has been
added; the requirement to indicate the nature of modifications now
applies when making a derivative work available "to others" instead of
just "to the public"; the version and date are updated.  The new
license has a new handle.

- Added the Tools/compiler package.  This is a project led by Jeremy
Hylton to write the Python bytecode generator in Python.

- The function math.rint() is removed.

- In Python.h, "#define _GNU_SOURCE 1" was added.

- Version 0.9.1 of Greg Ward's distutils is included (instead of
version 0.9).

- A new version of SRE is included.  It is more stable, and more
compatible with the old RE module.  Non-matching ranges are indicated
by -1, not None.  (The documentation said None, but the PRE
implementation used -1; changing to None would break existing code.)

- The winreg module has been renamed to _winreg.  (There are plans for
a higher-level API called winreg, but this has not yet materialized in
a form that is acceptable to the experts.)

- The _locale module is enabled by default.

- Fixed the configuration line for the _curses module.

- A few crashes have been fixed, notably <file>.writelines() with a
list containing non-string objects would crash, and there were
situations where a lost SyntaxError could dump core.

- The <list>.extend() method now accepts an arbitrary sequence
argument.

- If __str__() or __repr__() returns a Unicode object, this is
converted to an 8-bit string.

- Unicode string comparisons is no longer aware of UTF-16
encoding peculiarities; it's a straight 16-bit compare.

- The Windows installer now installs the LICENSE file and no longer
registers the Python DLL version in the registry (this is no longer
needed).  It now uses Tcl/Tk 8.3.2.

- A few portability problems have been fixed, in particular a
compilation error involving socklen_t.

- The PC configuration is slightly friendlier to non-Microsoft
compilers.


======================================================================


======================================
==> Release 1.5.2 (April 13, 1999) <==
======================================

From 1.5.2c1 to 1.5.2 (final)
=============================

Tue Apr 13 15:44:49 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* PCbuild/python15.wse: Bump version to 1.5.2 (final)

	* PCbuild/python15.dsp: Added shamodule.c

	* PC/config.c: Added sha module!

	* README, Include/patchlevel.h: Prepare for final release.

	* Misc/ACKS:
	More (Cameron Laird is honorary; the others are 1.5.2c1 testers).

	* Python/thread_solaris.h:
	While I can't really test this thoroughly, Pat Knight and the Solaris
	man pages suggest that the proper thing to do is to add THR_NEW_LWP to
	the flags on thr_create(), and that there really isn't a downside, so
	I'll do that.

	* Misc/ACKS:
	Bunch of new names who helped iron out the last wrinkles of 1.5.2.

	* PC/python_nt.rc:
	Bump the myusterious M$ version number from 1,5,2,1 to 1,5,2,3.
	(I can't even display this on NT, maybe Win/98 can?)

	* Lib/pstats.py:
	Fix mysterious references to jprofile that were in the source since
	its creation.  I'm assuming these were once valid references to "Jim
	Roskind's profile"...

	* Lib/Attic/threading_api.py:
	Removed; since long subsumed in Doc/lib/libthreading.tex

	* Modules/socketmodule.c:
	Put back __osf__ support for gethostbyname_r(); the real bug was that
	it was being used even without threads.  This of course might be an
	all-platform problem so now we only use the _r variant when we are
	using threads.

Mon Apr 12 22:51:20 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Modules/cPickle.c:
	Fix accidentally reversed NULL test in load_mark().  Suggested by
	Tamito Kajiyama.  (This caused a bug only on platforms where malloc(0)
	returns NULL.)

	* README:
	Add note about popen2 problem on Linux noticed by Pablo Bleyer.

	* README: Add note about -D_REENTRANT for HP-UX 10.20.

	* Modules/Makefile.pre.in: 'clean' target should remove hassignal.

	* PC/Attic/vc40.mak, PC/readme.txt:
	Remove all VC++ info (except VC 1.5) from readme.txt;
	remove the VC++ 4.0 project file; remove the unused _tkinter extern defs.

	* README: Clarify PC build instructions (point to PCbuild).

	* Modules/zlibmodule.c: Cast added by Jack Jansen (for Mac port).

	* Lib/plat-sunos5/CDIO.py, Lib/plat-linux2/CDROM.py:
	Forgot to add this file.  CDROM device parameters.

	* Lib/gzip.py: Two different changes.

	1. Jack Jansen reports that on the Mac, the time may be negative, and
	solves this by adding a write32u() function that writes an unsigned
	long.

	2. On 64-bit platforms the CRC comparison fails; I've fixed this by
	casting both values to be compared to "unsigned long" i.e. modulo
	0x100000000L.

Sat Apr 10 18:42:02 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* PC/Attic/_tkinter.def: No longer needed.

	* Misc/ACKS: Correct missed character in Andrew Dalke's name.

	* README: Add DEC Ultrix notes (from Donn Cave's email).

	* configure: The usual

	* configure.in:
	Quote a bunch of shell variables used in test, related to long-long.

	* Objects/fileobject.c, Modules/shamodule.c, Modules/regexpr.c:
	casts for picky compilers.

	* Modules/socketmodule.c:
	3-arg gethostbyname_r doesn't really work on OSF/1.

	* PC/vc15_w31/_.c, PC/vc15_lib/_.c, Tools/pynche/__init__.py:
	Avoid totally empty files.

Fri Apr  9 14:56:35 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/scripts/fixps.py: Use re instead of regex.
	Don't rewrite the file in place.
	(Reported by Andy Dustman.)

	* Lib/netrc.py, Lib/shlex.py: Get rid of #! line

Thu Apr  8 23:13:37 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* PCbuild/python15.wse: Use the Tcl 8.0.5 installer.
	Add a variable %_TCL_% that makes it easier to switch to a different version.


======================================================================


From 1.5.2b2 to 1.5.2c1
=======================

Thu Apr  8 23:13:37 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* PCbuild/python15.wse:
	Release 1.5.2c1.  Add IDLE and Uninstall to program group.
	Don't distribute zlib.dll.  Tweak some comments.

	* PCbuild/zlib.dsp: Now using static zlib 1.1.3

	* Lib/dos-8x3/userdict.py, Lib/dos-8x3/userlist.py, Lib/dos-8x3/test_zli.py, Lib/dos-8x3/test_use.py, Lib/dos-8x3/test_pop.py, Lib/dos-8x3/test_pic.py, Lib/dos-8x3/test_ntp.py, Lib/dos-8x3/test_gzi.py, Lib/dos-8x3/test_fcn.py, Lib/dos-8x3/test_cpi.py, Lib/dos-8x3/test_bsd.py, Lib/dos-8x3/posixfil.py, Lib/dos-8x3/mimetype.py, Lib/dos-8x3/nturl2pa.py, Lib/dos-8x3/compilea.py, Lib/dos-8x3/exceptio.py, Lib/dos-8x3/basehttp.py:
	The usual

	* Include/patchlevel.h: Release 1.5.2c1

	* README: Release 1.5.2c1.

	* Misc/NEWS: News for the 1.5.2c1 release.

	* Lib/test/test_strftime.py:
	On Windows, we suddenly find, strftime() may return "" for an
	unsupported format string.  (I guess this is because the logic for
	deciding whether to reallocate the buffer or not has been improved.)
	This caused the test code to crash on result[0].  Fix this by assuming
	an empty result also means the format is not supported.

	* Demo/tkinter/matt/window-creation-w-location.py:
	This demo imported some private code from Matt.  Make it cripple along.

	* Lib/lib-tk/Tkinter.py:
	Delete an accidentally checked-in feature that actually broke more
	than was worth it: when deleting a canvas item, it would try to
	automatically delete the bindings for that item.  Since there's
	nothing that says you can't reuse the tag and still have the bindings,
	this is not correct.  Also, it broke at least one demo
	(Demo/tkinter/matt/rubber-band-box-demo-1.py).

	* Python/thread_wince.h: Win/CE thread support by Mark Hammond.

Wed Apr  7 20:23:17 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Modules/zlibmodule.c:
	Patch by Andrew Kuchling to unflush() (flush() for deflating).
	Without this, if inflate() returned Z_BUF_ERROR asking for more output
	space, we would report the error; now, we increase the buffer size and
	try again, just as for Z_OK.

	* Lib/test/test_gzip.py: Use binary mode for all gzip files we open.

	* Tools/idle/ChangeLog: New change log.

	* Tools/idle/README.txt, Tools/idle/NEWS.txt: New version.

	* Python/pythonrun.c:
	Alas, get rid of the Win specific hack to ask the user to press Return
	before exiting when an error happened.  This didn't work right when
	Python is invoked from a daemon.

	* Tools/idle/idlever.py: Version bump awaiting impending new release.
	(Not much has changed :-( )

	* Lib/lib-tk/Tkinter.py:
	lower, tkraise/lift hide Misc.lower, Misc.tkraise/lift,
	so the preferred name for them is tag_lower, tag_raise
	(similar to tag_bind, and similar to the Text widget);
	unfortunately can't delete the old ones yet (maybe in 1.6)

	* Python/thread.c, Python/strtod.c, Python/mystrtoul.c, Python/import.c, Python/ceval.c:
	Changes by Mark Hammond for Windows CE.  Mostly of the form
	  #ifdef DONT_HAVE_header_H ... #endif around #include <header.h>.

	* Python/bltinmodule.c:
	Remove unused variable from complex_from_string() code.

	* Include/patchlevel.h:
	Add the possibility of a gamma release (release candidate).
	Add '+' to string version number to indicate we're beyond b2 now.

	* Modules/posixmodule.c: Add extern decl for fsync() for SunOS 4.x.

	* Lib/smtplib.py: Changes by Per Cederquist and The Dragon.

	Per writes:

	"""
	The application where Signum Support uses smtplib needs to be able to
	report good error messages to the user when sending email fails.  To
	help in diagnosing problems it is useful to be able to report the
	entire message sent by the server, not only the SMTP error code of the
	offending command.

	A lot of the functions in sendmail.py unfortunately discards the
	message, leaving only the code.  The enclosed patch fixes that
	problem.

	The enclosed patch also introduces a base class for exceptions that
	include an SMTP error code and error message, and make the code and
	message available on separate attributes, so that surrounding code can
	deal with them in whatever way it sees fit.  I've also added some
	documentation to the exception classes.

	The constructor will now raise an exception if it cannot connect to
	the SMTP server.

	The data() method will raise an SMTPDataError if it doesn't receive
	the expected 354 code in the middle of the exchange.

	According to section 5.2.10 of RFC 1123 a smtp client must accept "any
	text, including no text at all" after the error code.  If the response
	of a HELO command contains no text self.helo_resp will be set to the
	empty string ("").  The patch fixes the test in the sendmail() method
	so that helo_resp is tested against None; if it has the empty string
	as value the sendmail() method would invoke the helo() method again.

	The code no longer accepts a -1 reply from the ehlo() method in
	sendmail().

	[Text about removing SMTPRecipientsRefused deleted --GvR]
	"""

	and also:

	"""
	smtplib.py appends an extra blank line to the outgoing mail if the
	`msg' argument to the sendmail method already contains a trailing
	newline.  This patch should fix the problem.
	"""

	The Dragon writes:

	"""
		Mostly I just re-added the SMTPRecipientsRefused exception
	(the exeption object now has the appropriate info in it ) [Per had
	removed this in his patch --GvR] and tweaked the behavior of the
	sendmail method whence it throws the newly added SMTPHeloException (it
	was closing the connection, which it shouldn't.  whatever catches the
	exception should do that. )

		I pondered the change of the return values to tuples all around,
	and after some thinking I decided that regularizing the return values was
	too much of the Right Thing (tm) to not do.

		My one concern is that code expecting an integer & getting a tuple
	may fail silently.

	(i.e. if it's doing :

	      x.somemethod() >= 400:
	expecting an integer, the expression will always be true if it gets a
	tuple instead. )

		However, most smtplib code I've seen only really uses the
	sendmail() method, so this wouldn't bother it.  Usually code I've seen
	that calls the other methods usually only calls helo() and ehlo() for
	doing ESMTP, a feature which was not in the smtplib included with 1.5.1,
	and thus I would think not much code uses it yet.
	"""

Tue Apr  6 19:38:18 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/test_ntpath.py:
	Fix the tests now that splitdrive() no longer treats UNC paths special.
	(Some tests converted to splitunc() tests.)

	* Lib/ntpath.py:
	Withdraw the UNC support from splitdrive().  Instead, a new function
	splitunc() parses UNC paths.  The contributor of the UNC parsing in
	splitdrive() doesn't like it, but I haven't heard a good reason to
	keep it, and it causes some problems.  (I think there's a
	philosophical problem -- to me, the split*() functions are purely
	syntactical, and the fact that \\foo is not a valid path doesn't mean
	that it shouldn't be considered an absolute path.)

	Also (quite separately, but strangely related to the philosophical
	issue above) fix abspath() so that if win32api exists, it doesn't fail
	when the path doesn't actually exist -- if GetFullPathName() fails,
	fall back on the old strategy (join with getcwd() if necessary, and
	then use normpath()).

	* configure.in, configure, config.h.in, acconfig.h:
	For BeOS PowerPC.  Chris Herborth.

Mon Apr  5 21:54:14 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Modules/timemodule.c:
	Jonathan Giddy notes, and Chris Lawrence agrees, that some comments on
	#else/#endif are wrong, and that #if HAVE_TM_ZONE should be #ifdef.

	* Misc/ACKS:
	Bunch of new contributors, including 9 who contributed to the Docs,
	reported by Fred.

Mon Apr  5 18:37:59 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/gzip.py:
	Oops, missed mode parameter to open().

	* Lib/gzip.py:
	Made the default mode 'rb' instead of 'r', for better cross-platform
	support.  (Based on comment on the documentation by Bernhard Reiter
	<bernhard@csd.uwm.edu>).

Fri Apr  2 22:18:25 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/scripts/dutree.py:
	For reasons I dare not explain, this script should always execute
	main() when imported (in other words, it is not usable as a module).

Thu Apr  1 15:32:30 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/test_cpickle.py: Jonathan Giddy write:

	In test_cpickle.py, the module os got imported, but the line to remove
	the temp file has gone missing.

Tue Mar 30 20:17:31 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/BaseHTTPServer.py: Per Cederqvist writes:

	If you send something like "PUT / HTTP/1.0" to something derived from
	BaseHTTPServer that doesn't define do_PUT, you will get a response
	that begins like this:

		HTTP/1.0 501 Unsupported method ('do_PUT')
		Server: SimpleHTTP/0.3 Python/1.5
		Date: Tue, 30 Mar 1999 18:53:53 GMT

	The server should complain about 'PUT' instead of 'do_PUT'.  This
	patch should fix the problem.

Mon Mar 29 20:33:21 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/smtplib.py: Patch by Per Cederqvist, who writes:

	"""
	 - It needlessly used the makefile() method for each response that is
	   read from the SMTP server.

	 - If the remote SMTP server closes the connection unexpectedly the
	   code raised an IndexError.  It now raises an SMTPServerDisconnected
	   exception instead.

	 - The code now checks that all lines in a multiline response actually
	   contains an error code.
	"""

	The Dragon approves.

Mon Mar 29 20:25:40 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/compileall.py:
	When run as a script, report failures in the exit code as well.
	Patch largely based on changes by Andrew Dalke, as discussed in the
	distutils-sig.

Mon Mar 29 20:23:41 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urllib.py:
	Hack so that if a 302 or 301 redirect contains a relative URL, the
	right thing "just happens" (basejoin() with old URL).

	* Modules/cPickle.c:
	Protection against picling to/from closed (real) file.
	The problem was reported by Moshe Zadka.

	* Lib/test/test_cpickle.py:
	Test protection against picling to/from closed (real) file.

	* Modules/timemodule.c: Chris Lawrence writes:

	"""
	The GNU folks, in their infinite wisdom, have decided not to implement
	altzone in libc6; this would not be horrible, except that timezone
	(which is implemented) includes the current DST setting (i.e. timezone
	for Central is 18000 in summer and 21600 in winter).  So Python's
	timezone and altzone variables aren't set correctly during DST.

	Here's a patch relative to 1.5.2b2 that (a) makes timezone and altzone
	show the "right" thing on Linux (by using the tm_gmtoff stuff
	available in BSD, which is how the GLIBC manual claims things should
	be done) and (b) should cope with the southern hemisphere.  In pursuit
	of (b), I also took the liberty of renaming the "summer" and "winter"
	variables to "july" and "jan".  This patch should also make certain
	time calculations on Linux actually work right (like the tz-aware
	functions in the rfc822 module).

	(It's hard to find DST that's currently being used in the southern
	hemisphere; I tested using Africa/Windhoek.)
	"""

	* Lib/test/output/test_gzip:
	Jonathan Giddy discovered this file was missing.

	* Modules/shamodule.c:
	Avoid warnings from AIX compiler.  Reported by Vladimir (AIX is my
	middlename) Marangozov, patch coded by Greg Stein.

	* Tools/idle/ScriptBinding.py, Tools/idle/PyShell.py:
	At Tim Peters' recommendation, add a dummy flush() method to PseudoFile.

Sun Mar 28 17:55:32 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/scripts/ndiff.py: Tim Peters writes:

	I should have waited overnight <wink/sigh>.  Nothing wrong with the one I
	sent, but I couldn't resist going on to add new -r1 / -r2 cmdline options
	for recreating the original files from ndiff's output.  That's attached, if
	you're game!  Us Windows guys don't usually have a sed sitting around
	<wink>.

Sat Mar 27 13:34:01 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/scripts/ndiff.py: Tim Peters writes:

	Attached is a cleaned-up version of ndiff (added useful module
	docstring, now echo'ed in case of cmd line mistake); added -q option
	to suppress initial file identification lines; + other minor cleanups,
	& a slightly faster match engine.

Fri Mar 26 22:36:00 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Tools/scripts/dutree.py:
	During display, if EPIPE is raised, it's probably because a pager was
	killed.  Discard the error in that case, but propagate it otherwise.

Fri Mar 26 16:20:45 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/output/test_userlist, Lib/test/test_userlist.py:
	Test suite for UserList.

	* Lib/UserList.py: Use isinstance() where appropriate.
	Reformatted with 4-space indent.

Fri Mar 26 16:11:40 1999  Barry Warsaw  <bwarsaw@eric.cnri.reston.va.us>

	* Tools/pynche/PyncheWidget.py:
	Helpwin.__init__(): The text widget should get focus.

	* Tools/pynche/pyColorChooser.py:
	Removed unnecessary import `from PyncheWidget import PyncheWidget'

Fri Mar 26 15:32:05 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/output/test_userdict, Lib/test/test_userdict.py:
	Test suite for UserDict

	* Lib/UserDict.py: Improved a bunch of things.
	The constructor now takes an optional dictionary.
	Use isinstance() where appropriate.

Thu Mar 25 22:38:49 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/output/test_pickle, Lib/test/output/test_cpickle, Lib/test/test_pickle.py, Lib/test/test_cpickle.py:
	Basic regr tests for pickle/cPickle

	* Lib/pickle.py:
	Don't use "exec" in find_class().  It's slow, unnecessary, and (as AMK
	points out) it doesn't work in JPython Applets.

Thu Mar 25 21:50:27 1999  Andrew Kuchling  <akuchlin@eric.cnri.reston.va.us>

	* Lib/test/test_gzip.py:
	Added a simple test suite for gzip.  It simply opens a temp file,
	writes a chunk of compressed data, closes it, writes another chunk, and
	reads the contents back to verify that they are the same.

	* Lib/gzip.py:
	Based on a suggestion from bruce@hams.com, make a trivial change to
	allow using the 'a' flag as a mode for opening a GzipFile.  gzip
	files, surprisingly enough, can be concatenated and then decompressed;
	the effect is to concatenate the two chunks of data.

	If we support it on writing, it should also be supported on reading.
	This *wasn't* trivial, and required rearranging the code in the
	reading path, particularly the _read() method.

	Raise IOError instead of RuntimeError in two cases, 'Not a gzipped file'
	and 'Unknown compression method'

Thu Mar 25 21:25:01 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/test_b1.py:
	Add tests for float() and complex() with string args (Nick/Stephanie
	Lockwood).

Thu Mar 25 21:21:08 1999  Andrew Kuchling  <akuchlin@eric.cnri.reston.va.us>

	* Modules/zlibmodule.c:
	Add an .unused_data attribute to decompressor objects.  If .unused_data
	is not an empty string, this means that you have arrived at the
	end of the stream of compressed data, and the contents of .unused_data are
	whatever follows the compressed stream.

Thu Mar 25 21:16:07 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Python/bltinmodule.c:
	Patch by Nick and Stephanie Lockwood to implement complex() with a string
	argument.  This closes TODO item 2.19.

Wed Mar 24 19:09:00 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/webchecker/wcnew.py: Added Samuel Bayer's new webchecker.
	Unfortunately his code breaks wcgui.py in a way that's not easy
	to fix.  I expect that this is a temporary situation --
	eventually Sam's changes will be merged back in.
	(The changes add a -t option to specify exceptions to the -x
	option, and explicit checking for #foo style fragment ids.)

	* Objects/dictobject.c:
	Vladimir Marangozov contributed updated comments.

	* Objects/bufferobject.c: Folded long lines.

	* Lib/test/output/test_sha, Lib/test/test_sha.py:
	Added Jeremy's test code for the sha module.

	* Modules/shamodule.c, Modules/Setup.in:
	Added Greg Stein and Andrew Kuchling's sha module.
	Fix comments about zlib version and URL.

	* Lib/test/test_bsddb.py: Remove the temp file when we're done.

	* Include/pythread.h: Conform to standard boilerplate.

	* configure.in, configure, BeOS/linkmodule, BeOS/ar-fake:
	Chris Herborth: the new compiler in R4.1 needs some new options to work...

	* Modules/socketmodule.c:
	Implement two suggestions by Jonathan Giddy: (1) in AIX, clear the
	data struct before calling gethostby{name,addr}_r(); (2) ignore the
	3/5/6 args determinations made by the configure script and switch on
	platform identifiers instead:

	AIX, OSF have 3 args
	Sun, SGI have 5 args
	Linux has 6 args

	On all other platforms, undef HAVE_GETHOSTBYNAME_R altogether.

	* Modules/socketmodule.c:
	Vladimir Marangozov implements the AIX 3-arg gethostbyname_r code.

	* Lib/mailbox.py:
	Add readlines() to _Subfile class.  Not clear who would need it, but
	Chris Lawrence sent me a broken version; this one is a tad simpler and
	more conforming to the standard.

Tue Mar 23 23:05:34 1999  Jeremy Hylton  <jhylton@eric.cnri.reston.va.us>

	* Lib/gzip.py: use struct instead of bit-manipulate in Python

Tue Mar 23 19:00:55 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Modules/Makefile.pre.in:
	Add $(EXE) to various occurrences of python so it will work on Cygwin
	with egcs (after setting EXE=.exe).  Patch by Norman Vine.

	* configure, configure.in:
	Ack!  It never defined HAVE_GETHOSTBYNAME_R so that code was never tested!

Mon Mar 22 22:25:39 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Include/thread.h:
	Adding thread.h -- unused but for b/w compatibility.
	As requested by Bill Janssen.

	* configure.in, configure:
	Add code to test for all sorts of gethostbyname_r variants,
	donated by David Arnold.

	* config.h.in, acconfig.h:
	Add symbols for gethostbyname_r variants (sigh).

	* Modules/socketmodule.c: Clean up pass for the previous patches.

	- Use HAVE_GETHOSTBYNAME_R_6_ARG instead of testing for Linux and
	glibc2.

	- If gethostbyname takes 3 args, undefine HAVE_GETHOSTBYNAME_R --
	don't know what code should be used.

	- New symbol USE_GETHOSTBYNAME_LOCK defined iff the lock should be used.

	- Modify the gethostbyaddr() code to also hold on to the lock until
	after it is safe to release, overlapping with the Python lock.

	(Note: I think that it could in theory be possible that Python code
	executed while gethostbyname_lock is held could attempt to reacquire
	the lock -- e.g. in a signal handler or destructor.  I will simply say
	"don't do that then.")

	* Modules/socketmodule.c: Jonathan Giddy writes:

	Here's a patch to fix the race condition, which wasn't fixed by Rob's
	patch.  It holds the gethostbyname lock until the results are copied out,
	which means that this lock and the Python global lock are held at the same
	time.  This shouldn't be a problem as long as the gethostbyname lock is
	always acquired when the global lock is not held.

Mon Mar 22 19:25:30 1999  Andrew Kuchling  <akuchlin@eric.cnri.reston.va.us>

	* Modules/zlibmodule.c:
	Fixed the flush() method of compression objects; the test for
	    the end of loop was incorrect, and failed when the flushmode != Z_FINISH.
	    Logic cleaned up and commented.

	* Lib/test/test_zlib.py:
	Added simple test for the flush() method of compression objects, trying the
	    different flush values Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FULL_FLUSH.

Mon Mar 22 15:28:08 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/shlex.py:
	Bug reported by Tobias Thelen: missing "self." in assignment target.

Fri Mar 19 21:50:11 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Modules/arraymodule.c:
	Use an unsigned cast to avoid a warning in VC++.

	* Lib/dospath.py, Lib/ntpath.py:
	New code for split() by Tim Peters, behaves more like posixpath.split().

	* Objects/floatobject.c:
	Fix a problem with Vladimir's PyFloat_Fini code: clear the free list; if
	a block cannot be freed, add its free items back to the free list.
	This is necessary to avoid leaking when Python is reinitialized later.

	* Objects/intobject.c:
	Fix a problem with Vladimir's PyInt_Fini code: clear the free list; if
	a block cannot be freed, add its free items back to the free list, and
	add its valid ints back to the small_ints array if they are in range.
	This is necessary to avoid leaking when Python is reinitialized later.

	* Lib/types.py:
	Added BufferType, the type returned by the new builtin buffer().  Greg Stein.

	* Python/bltinmodule.c:
	New builtin buffer() creates a derived read-only buffer from any
	object that supports the buffer interface (e.g. strings, arrays).

	* Objects/bufferobject.c:
	Added check for negative offset for PyBuffer_FromObject and check for
	negative size for PyBuffer_FromMemory.  Greg Stein.

Thu Mar 18 15:10:44 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urlparse.py: Sjoerd Mullender writes:

	If a filename on Windows starts with \\, it is converted to a URL
	which starts with ////.  If this URL is passed to urlparse.urlparse
	you get a path that starts with // (and an empty netloc).  If you pass
	the result back to urlparse.urlunparse, you get a URL that starts with
	//, which is parsed differently by urlparse.urlparse.  The fix is to
	add the (empty) netloc with accompanying slashes if the path in
	urlunparse starts with //.  Do this for all schemes that use a netloc.

	* Lib/nturl2path.py: Sjoerd Mullender writes:

	Pathnames of files on other hosts in the same domain
	(\\host\path\to\file) are not translated correctly to URLs and back.
	The URL should be something like file:////host/path/to/file.
	Note that a combination of drive letter and remote host is not
	possible.

Wed Mar 17 22:30:10 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urlparse.py:
	Delete non-standard-conforming code in urljoin() that would use the
	netloc from the base url as the default netloc for the resulting url
	even if the schemes differ.

	Once upon a time, when the web was wild, this was a valuable hack
	because some people had a URL referencing an ftp server colocated with
	an http server without having the host in the ftp URL (so they could
	replicate it or change the hostname easily).

	More recently, after the file: scheme got added back to the list of
	schemes that accept a netloc, it turns out that this caused weirdness
	when joining an http: URL with a file: URL -- the resulting file: URL
	would always inherit the host from the http: URL because the file:
	scheme supports a netloc but in practice never has one.

	There are two reasons to get rid of the old, once-valuable hack,
	instead of removing the file: scheme from the uses_netloc list.  One,
	the RFC says that file: uses the netloc syntax, and does not endorse
	the old hack.  Two, neither netscape 4.5 nor IE 4.0 support the old
	hack.

	* Include/ceval.h, Include/abstract.h:
	Add DLL level b/w compat for PySequence_In and PyEval_CallObject

Tue Mar 16 21:54:50 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/lib-tk/Tkinter.py: Bug reported by Jim Robinson:

	An attempt to execute grid_slaves with arguments (0,0) results in
	*all* of the slaves being returned, not just the slave associated with
	row 0, column 0.  This is because the test for arguments in the method
	does not test to see if row (and column) does not equal None, but
	rather just whether is evaluates to non-false.  A value of 0 fails
	this test.

Tue Mar 16 14:17:48 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Modules/cmathmodule.c:
	Docstring fix:  acosh() returns the hyperbolic arccosine, not the
	hyperbolic cosine.  Problem report via David Ascher by one of his
	students.

Mon Mar 15 21:40:59 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* configure.in:
	Should test for gethost*by*name_r, not for gethostname_r (which
	doesn't exist and doesn't make sense).

	* Modules/socketmodule.c:
	Patch by Rob Riggs for Linux -- glibc2 has a different argument
	converntion for gethostbyname_r() etc. than Solaris!

	* Python/thread_pthread.h: Rob Riggs wrote:

	"""
	Spec says that on success pthread_create returns 0. It does not say
	that an error code will be < 0. Linux glibc2 pthread_create() returns
	ENOMEM (12) when one exceed process limits. (It looks like it should
	return EAGAIN, but that's another story.)

	For reference, see:
	http://www.opengroup.org/onlinepubs/7908799/xsh/pthread_create.html
	"""

	[I have a feeling that similar bugs were fixed before; perhaps someone
	could check that all error checks no check for != 0?]

	* Tools/bgen/bgen/bgenObjectDefinition.py:
	New mixin class that defines cmp and hash that use
	the ob_itself pointer.  This allows (when using the mixin)
	different Python objects pointing to the same C object and
	behaving well as dictionary keys.

	Or so sez Jack Jansen...

	* Lib/urllib.py: Yet another patch by Sjoerd Mullender:

	Don't convert URLs to URLs using pathname2url.

Fri Mar 12 22:15:43 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/cmd.py: Patch by Michael Scharf.  He writes:

	    The module cmd requires for each do_xxx command a help_xxx
	    function. I think this is a little old fashioned.

	    Here is a patch: use the docstring as help if no help_xxx
	    function can be found.

	[I'm tempted to rip out all the help_* functions from pdb, but I'll
	resist it.  Any takers?  --Guido]

	* Tools/freeze/freeze.py: Bug submitted by Wayne Knowles, who writes:

	   Under Windows, python freeze.py -o hello hello.py
	   creates all the correct files in the hello subdirectory, but the
	   Makefile has the directory prefix in it for frozen_extensions.c
	   nmake fails because it tries to locate hello/frozen_extensions.c

	(His fix adds a call to os.path.basename() in the appropriate place.)

	* Objects/floatobject.c, Objects/intobject.c:
	Vladimir has restructured his code somewhat so that the blocks are now
	represented by an explicit structure.  (There are still too many casts
	in the code, but that may be unavoidable.)

	Also added code so that with -vv it is very chatty about what it does.

	* Demo/zlib/zlibdemo.py, Demo/zlib/minigzip.py:
	Change #! line to modern usage; also chmod +x

	* Demo/pdist/rrcs, Demo/pdist/rcvs, Demo/pdist/rcsbump:
	Change #! line to modern usage

	* Lib/nturl2path.py, Lib/urllib.py: From: Sjoerd Mullender

	The filename to URL conversion didn't properly quote special
	characters.
	The URL to filename didn't properly unquote special chatacters.

	* Objects/floatobject.c:
	OK, try again.  Vladimir gave me a fix for the alignment bus error,
	so here's his patch again.  This time it works (at least on Solaris,
	Linux and Irix).

Thu Mar 11 23:21:23 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Tools/idle/PathBrowser.py:
	Don't crash when sys.path contains an empty string.

	* Tools/idle/PathBrowser.py:
	- Don't crash in the case where a superclass is a string instead of a
	pyclbr.Class object; this can happen when the superclass is
	unrecognizable (to pyclbr), e.g. when module renaming is used.

	- Show a watch cursor when calling pyclbr (since it may take a while
	recursively parsing imported modules!).

Thu Mar 11 16:04:04 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/mimetypes.py:
	Added .rdf and .xsl as application/xml types.  (.rdf is for the
	Resource Description Framework, a metadata encoding, and .xsl is for
	the Extensible Stylesheet Language.)

Thu Mar 11 13:26:23 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/test/output/test_popen2, Lib/test/test_popen2.py:
	Test for popen2 module, by Chris Tismer.

	* Objects/floatobject.c:
	Alas, Vladimir's patch caused a bus error (probably double
	alignment?), and I didn't test it.  Withdrawing it for now.

Wed Mar 10 22:55:47 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Objects/floatobject.c:
	Patch by Vladimir Marangoz to allow freeing of the allocated blocks of
	floats on finalization.

	* Objects/intobject.c:
	Patch by Vladimir Marangoz to allow freeing of the allocated blocks of
	integers on finalization.

	* Tools/idle/EditorWindow.py, Tools/idle/Bindings.py:
	Add PathBrowser to File module

	* Tools/idle/PathBrowser.py:
	"Path browser" - 4 scrolled lists displaying:
	    directories on sys.path
	    modules in selected directory
	    classes in selected module
	    methods of selected class

	Sinlge clicking in a directory, module or class item updates the next
	column with info about the selected item.  Double clicking in a
	module, class or method item opens the file (and selects the clicked
	item if it is a class or method).

	I guess eventually I should be using a tree widget for this, but the
	ones I've seen don't work well enough, so for now I use the old
	Smalltalk or NeXT style multi-column hierarchical browser.

	* Tools/idle/MultiScrolledLists.py:
	New utility: multiple scrolled lists in parallel

	* Tools/idle/ScrolledList.py: - White background.
	- Display "(None)" (or text of your choosing) when empty.
	- Don't set the focus.

Tue Mar  9 19:31:21 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urllib.py:
	open_http also had the 'data is None' test backwards.  don't call with the
	extra argument if data is None.

	* Demo/embed/demo.c:
	Call Py_SetProgramName() instead of redefining getprogramname(),
	reflecting changes in the runtime around 1.5 or earlier.

	* Python/ceval.c:
	Always test for an error return (usually NULL or -1) without setting
	an exception.

	* Modules/timemodule.c: Patch by Chris Herborth for BeOS code.
	He writes:

	I had an off-by-1000 error in floatsleep(),
	and the problem with time.clock() is that it's not implemented properly
	on QNX... ANSI says it's supposed to return _CPU_ time used by the
	process, but on QNX it returns the amount of real time used... so I was
	confused.

	* Tools/bgen/bgen/macsupport.py: Small change by Jack Jansen.
	Test for self.returntype behaving like OSErr rather than being it.

Thu Feb 25 16:14:58 1999  Jeremy Hylton  <jhylton@eric.cnri.reston.va.us>

	* Lib/urllib.py:
	http_error had the 'data is None' test backwards.  don't call with the
	extra argument if data is None.

	* Lib/urllib.py: change indentation from 8 spaces to 4 spaces

	* Lib/urllib.py: pleasing the tabnanny

Thu Feb 25 14:26:02 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/colorsys.py:
	Oops, one more "x, y, z" to convert...

	* Lib/colorsys.py:
	Adjusted comment at the top to be less confusing, following Fredrik
	Lundh's example.

	Converted comment to docstring.

Wed Feb 24 18:49:15 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/toaiff.py:
	Use sndhdr instead of the obsolete whatsound module.

Wed Feb 24 18:42:38 1999  Jeremy Hylton  <jhylton@eric.cnri.reston.va.us>

	* Lib/urllib.py:
	When performing a POST request, i.e. when the second argument to
	urlopen is used to specify form data, make sure the second argument is
	threaded through all of the http_error_NNN calls.  This allows error
	handlers like the redirect and authorization handlers to properly
	re-start the connection.

Wed Feb 24 16:25:17 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/mhlib.py: Patch by Lars Wirzenius:

		o the initial comment is wrong: creating messages is already
		  implemented

		o Message.getbodytext: if the mail or it's part contains an
		  empty content-transfer-encoding header, the code used to
		  break; the change below treats an empty encoding value the same
		  as the other types that do not need decoding

		o SubMessage.getbodytext was missing the decode argument; the
		  change below adds it; I also made it unconditionally return
		  the raw text if decoding was not desired, because my own
		  routines needed that (and it was easier than rewriting my
		  own routines ;-)

Wed Feb 24 00:35:43 1999  Barry Warsaw  <bwarsaw@eric.cnri.reston.va.us>

	* Python/bltinmodule.c (initerrors):
	Make sure that the exception tuples ("base-classes" when
	string-based exceptions are used) reflect the real class hierarchy,
	i.e. that SystemExit derives from Exception not StandardError.

	* Lib/exceptions.py:
	Document the correct class hierarchy for SystemExit.  It is not an
	error and so it derives from Exception and not SystemError.  The
	docstring was incorrect but the implementation was fine.

Tue Feb 23 23:07:51 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/shutil.py:
	Add import sys, needed by reference to sys.exc_info() in rmtree().
	Discovered by Mitch Chapman.

	* config.h.in:
	Now that we don't have AC_CHECK_LIB(m, pow), the HAVE_LIBM symbol
	disappears.  It wasn't used anywhere anyway...

	* Modules/arraymodule.c:
	Carefully check for overflow when allocating the memory for fromfile
	-- someone tried to pass in sys.maxint and got bitten by the bogus
	calculations.

	* configure.in:
	Get rid of AC_CHECK_LIB(m, pow) since this is taken care of later with
	LIBM (from --with-libm=...); this actually broke the customizability
	offered by the latter option.  Thanks go to Clay Spence for reporting
	this.

	* Lib/test/test_dl.py:
	1. Print the error message (carefully) when a dl.open() fails in verbose mode.
	2. When no test case worked, raise ImportError instead of failing.

	* Python/bltinmodule.c:
	Patch by Tim Peters to improve the range checks for range() and
	xrange(), especially for platforms where int and long are different
	sizes (so sys.maxint isn't actually the theoretical limit for the
	length of a list, but the largest C int is -- sys.maxint is the
	largest Python int, which is actually a C long).

	* Makefile.in:
	1. Augment the DG/UX rule so it doesn't break the BeOS build.
	2. Add $(EXE) to various occurrences of python so it will work on
	   Cygwin with egcs (after setting EXE=.exe).  These patches by
	   Norman Vine.

	* Lib/posixfile.py:
	According to Jeffrey Honig, bsd/os 2.0 - 4.0 should be added to the
	list (of bsd variants that have a different lock structure).

	* Lib/test/test_fcntl.py:
	According to Jeffrey Honig, bsd/os 4.0 should be added to the list.

	* Modules/timemodule.c:
	Patch by Tadayoshi Funaba (with some changes) to be smarter about
	guessing what happened when strftime() returns 0.  Is it buffer
	overflow or was the result simply 0 bytes long?  (This happens for an
	empty format string, or when the format string is a single %Z and the
	timezone is unknown.)  if the buffer is at least 256 times as long as
	the format, assume the latter.

Mon Feb 22 19:01:42 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urllib.py:
	As Des Barry points out, we need to call pathname2url(file) in two
	calls to addinfourl() in open_file().

	* Modules/Setup.in: Document *static* -- in two places!

	* Modules/timemodule.c:
	We don't support leap seconds, so the seconds field of a time 9-tuple
	should be in the range [0-59].  Noted by Tadayoshi Funaba.

	* Modules/stropmodule.c:
	In atoi(), don't use isxdigit() to test whether the last character
	converted was a "digit" -- use isalnum().  This test is there only to
	guard against "+" or "-" being interpreted as a valid int literal.
	Reported by Takahiro Nakayama.

	* Lib/os.py:
	As Finn Bock points out, _P_WAIT etc. don't have a leading underscore
	so they don't need to be treated specially here.

Mon Feb 22 15:38:58 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Misc/NEWS:
	Typo:  "apparentlt" --> "apparently"

Mon Feb 22 15:38:46 1999  Guido van Rossum  <guido@eric.cnri.reston.va.us>

	* Lib/urlparse.py: Steve Clift pointed out that 'file' allows a netloc.

	* Modules/posixmodule.c:
	The docstring for ttyname(..) claims a second "mode" argument. The
	actual code does not allow such an argument.  (Finn Bock.)

	* Lib/lib-old/poly.py:
	Dang.  Even though this is obsolete code, somebody found a bug, and I
	fix it.  Oh well.

Thu Feb 18 20:51:50 1999  Fred Drake  <fdrake@eric.cnri.reston.va.us>

	* Lib/pyclbr.py:
	Bow to font-lock at the end of the docstring, since it throws stuff
	off.

	Make sure the path parameter to readmodule() is a list before adding it
	with sys.path, or the addition could fail.


======================================================================


From 1.5.2b1 to 1.5.2b2
=======================

General
-------

- Many memory leaks fixed.

- Many small bugs fixed.

- Command line option -OO (or -O -O) suppresses inclusion of doc
strings in resulting bytecode.

Windows-specific changes
------------------------

- New built-in module winsound provides an interface to the Win32
PlaySound() call.

- Re-enable the audioop module in the config.c file.

- On Windows, support spawnv() and associated P_* symbols.

- Fixed the conversion of times() return values on Windows.

- Removed freeze from the installer -- it doesn't work without the
source tree.  (See FAQ 8.11.)

- On Windows 95/98, the Tkinter module now is smart enough to find
Tcl/Tk even when the PATH environment variable hasn't been set -- when
the import of _tkinter fails, it searches in a standard locations,
patches os.environ["PATH"], and tries again.  When it still fails, a
clearer error message is produced.  This should avoid most
installation problems with Tkinter use (e.g. in IDLE).

- The -i option doesn't make any calls to set[v]buf() for stdin --
this apparently screwed up _kbhit() and the _tkinter main loop.

- The ntpath module (and hence, os.path on Windows) now parses out UNC
paths (e.g. \\host\mountpoint\dir\file) as "drive letters", so that
splitdrive() will \\host\mountpoint as the drive and \dir\file as the
path.  ** EXPERIMENTAL **

- Added a hack to the exit code so that if (1) the exit status is
nonzero and (2) we think we have our own DOS box (i.e. we're not
started from a command line shell), we print a message and wait for
the user to hit a key before the DOS box is closed.

- Updated the installer to WISE 5.0g.  Added a dialog warning about
the imminent Tcl installation.  Added a dialog to specify the program
group name in the start menu.  Upgraded the Tcl installer to Tcl
8.0.4.

Changes to intrinsics
---------------------

- The repr() or str() of a module object now shows the __file__
attribute (i.e., the file which it was loaded), or the string
"(built-in)" if there is no __file__ attribute.

- The range() function now avoids overflow during its calculations (if
at all possible).

- New info string sys.hexversion, which is an integer encoding the
version in hexadecimal.  In other words, hex(sys.hexversion) ==
0x010502b2 for Python 1.5.2b2.

New or improved ports
---------------------

- Support for Nextstep descendants (future Mac systems).

- Improved BeOS support.

- Support dynamic loading of shared libraries on NetBSD platforms that 
use ELF (i.e., MIPS and Alpha systems).

Configuration/build changes
---------------------------

- The Lib/test directory is no longer included in the default module
search path (sys.path) -- "test" has been a package ever since 1.5.

- Now using autoconf 2.13.

New library modules
-------------------

- New library modules asyncore and asynchat: these form Sam Rushing's
famous asynchronous socket library.  Sam has gracefully allowed me to
incorporate these in the standard Python library.

- New module statvfs contains indexing constants for [f]statvfs()
return tuple.

Changes to the library
----------------------

- The wave module (platform-independent support for Windows sound
files) has been fixed to actually make it work.

- The sunau module (platform-independent support for Sun/NeXT sound
files) has been fixed to work across platforms.  Also, a weird
encoding bug in the header of the audio test data file has been
corrected.

- Fix a bug in the urllib module that occasionally tripped up
webchecker and other ftp retrieves.

- ConfigParser's get() method now accepts an optional keyword argument
(vars) that is substituted on top of the defaults that were setup in
__init__.  You can now also have recusive references in your
configuration file.

- Some improvements to the Queue module, including a put_nowait()
module and an optional "block" second argument, to get() and put(),
defaulting to 1.

- The updated xmllib module is once again compatible with the version
present in Python 1.5.1 (this was accidentally broken in 1.5.2b1).

- The bdb module (base class for the debugger) now supports
canonicalizing pathnames used in breakpoints.  The derived class must
override the new canonical() method for this to work.  Also changed
clear_break() to the backwards compatible old signature, and added
clear_bpbynumber() for the new functionality.

- In sgmllib (and hence htmllib), recognize attributes even if they
don't have space in front of them.  I.e.  '<a
name="foo"href="bar.html">' will now have two attributes recognized.

- In the debugger (pdb), change clear syntax to support three
alternatives: clear; clear file:line; clear bpno bpno ...

- The os.path module now pretends to be a submodule within the os
"package", so you can do things like "from os.path import exists".

- The standard exceptions now have doc strings.

- In the smtplib module, exceptions are now classes.  Also avoid
inserting a non-standard space after "TO" in rcpt() command.

- The rfc822 module's getaddrlist() method now uses all occurrences of
the specified header instead of just the first.  Some other bugfixes
too (to handle more weird addresses found in a very large test set,
and to avoid crashes on certain invalid dates), and a small test
module has been added.

- Fixed bug in urlparse in the common-case code for HTTP URLs; it
would lose the query, fragment, and/or parameter information.

- The sndhdr module no longer supports whatraw() -- it depended on a
rare extenral program.

- The UserList module/class now supports the extend() method, like
real list objects.

- The uu module now deals better with trailing garbage generated by
some broke uuencoders.

- The telnet module now has a my_interact() method which uses threads
instead of select.  The interact() method uses this by default on
Windows (where the single-threaded version doesn't work).

- Add a class to mailbox.py for dealing with qmail directory
mailboxes.  The test code was extended to notice these being used as
well.

Changes to extension modules
----------------------------

- Support for the [f]statvfs() system call, where it exists.

- Fixed some bugs in cPickle where bad input could cause it to dump
core.

- Fixed cStringIO to make the writelines() function actually work.

- Added strop.expandtabs() so string.expandtabs() is now much faster.

- Added fsync() and fdatasync(), if they appear to exist.

- Support for "long files" (64-bit seek pointers).

- Fixed a bug in the zlib module's flush() function.

- Added access() system call.  It returns 1 if access granted, 0 if
not.

- The curses module implements an optional nlines argument to
w.scroll().  (It then calls wscrl(win, nlines) instead of scoll(win).)

Changes to tools
----------------

- Some changes to IDLE; see Tools/idle/NEWS.txt.

- Latest version of Misc/python-mode.el included.

Changes to Tkinter
------------------

- Avoid tracebacks when an image is deleted after its root has been
destroyed.

Changes to the Python/C API
---------------------------

- When parentheses are used in a PyArg_Parse[Tuple]() call, any
sequence is now accepted, instead of requiring a tuple.  This is in
line with the general trend towards accepting arbitrary sequences.

- Added PyModule_GetFilename().

- In PyNumber_Power(), remove unneeded and even harmful test for float
to the negative power (which is already and better done in
floatobject.c).

- New version identification symbols; read patchlevel.h for info.  The
version numbers are now exported by Python.h.

- Rolled back the API version change -- it's back to 1007!

- The frozenmain.c function calls PyInitFrozenExtensions().

- Added 'N' format character to Py_BuildValue -- like 'O' but doesn't
INCREF.


======================================================================


From 1.5.2a2 to 1.5.2b1
=======================

Changes to intrinsics
---------------------

- New extension NotImplementedError, derived from RuntimeError.  Not
used, but recommended use is for "abstract" methods to raise this.

- The parser will now spit out a warning or error when -t or -tt is
used for parser input coming from a string, too.

- The code generator now inserts extra SET_LINENO opcodes when
compiling multi-line argument lists.

- When comparing bound methods, use identity test on the objects, not
equality test.

New or improved ports
---------------------

- Chris Herborth has redone his BeOS port; it now works on PowerPC
(R3/R4) and x86 (R4 only).  Threads work too in this port.

Renaming
--------

- Thanks to Chris Herborth, the thread primitives now have proper Py*
names in the source code (they already had those for the linker,
through some smart macros; but the source still had the old, un-Py
names).

Configuration/build changes
---------------------------

- Improved support for FreeBSD/3.

- Check for pthread_detach instead of pthread_create in libc.

- The makesetup script now searches EXECINCLUDEPY before INCLUDEPY.

- Misc/Makefile.pre.in now also looks at Setup.thread and Setup.local.
Otherwise modules such as thread didn't get incorporated in extensions.

New library modules
-------------------

- shlex.py by Eric Raymond provides a lexical analyzer class for
simple shell-like syntaxes.

- netrc.py by Eric Raymond provides a parser for .netrc files.  (The
undocumented Netrc class in ftplib.py is now obsolete.)

- codeop.py is a new module that contains the compile_command()
function that was previously in code.py.  This is so that JPython can
provide its own version of this function, while still sharing the
higher-level classes in code.py.

- turtle.py is a new module for simple turtle graphics.  I'm still
working on it; let me know if you use this to teach Python to children 
or other novices without prior programming experience.

Obsoleted library modules
-------------------------

- poly.py and zmod.py have been moved to Lib/lib-old to emphasize
their status of obsoleteness.  They don't do a particularly good job
and don't seem particularly relevant to the Python core.

New tools
---------

- I've added IDLE: my Integrated DeveLopment Environment for Python.
Requires Tcl/Tk (and Tkinter).  Works on Windows and Unix (and should
work on Macintosh, but I haven't been able to test it there; it does
depend on new features in 1.5.2 and perhaps even new features in
1.5.2b1, especially the new code module).  This is very much a work in
progress.  I'd like to hear how people like it compared to PTUI (or
any other IDE they are familiar with).

- New tools by Barry Warsaw:

  = audiopy: controls the Solaris Audio device
  = pynche:  The PYthonically Natural Color and Hue Editor
  = world:   Print mappings between country names and DNS country codes

New demos
---------

- Demo/scripts/beer.py prints the lyrics to an arithmetic drinking
song.

- Demo/tkinter/guido/optionmenu.py shows how to do an option menu in
Tkinter.  (By Fredrik Lundh -- not by me!)

Changes to the library
----------------------

- compileall.py now avoids recompiling .py files that haven't changed;
it adds a -f option to force recompilation.

- New version of xmllib.py by Sjoerd Mullender (0.2 with latest
patches).

- nntplib.py: statparse() no longer lowercases the message-id.

- types.py: use type(__stdin__) for FileType.

- urllib.py: fix translations for filenames with "funny" characters.
Patch by Sjoerd Mullender.  Note that if you subclass one of the
URLopener classes, and you have copied code from the old urllib.py,
your subclass may stop working.  A long-term solution is to provide
more methods so that you don't have to copy code.

- cgi.py: In read_multi, allow a subclass to override the class we
instantiate when we create a recursive instance, by setting the class
variable 'FieldStorageClass' to the desired class.  By default, this
is set to None, in which case we use self.__class__ (as before).
Also, a patch by Jim Fulton to pass additional arguments to recursive
calls to the FieldStorage constructor from its read_multi method.

- UserList.py: In __getslice__, use self.__class__ instead of
UserList.

- In SimpleHTTPServer.py, the server specified in test() should be
BaseHTTPServer.HTTPServer, in case the request handler should want to
reference the two attributes added by BaseHTTPServer.server_bind.  (By
Jeff Rush, for Bobo).  Also open the file in binary mode, so serving
images from a Windows box might actually work.

- In CGIHTTPServer.py, the list of acceptable formats is -split-
on spaces but -joined- on commas, resulting in double commas
in the joined text.  (By Jeff Rush.)

- SocketServer.py, patch by Jeff Bauer: a minor change to declare two
new threaded versions of Unix Server classes, using the ThreadingMixIn
class: ThreadingUnixStreamServer, ThreadingUnixDatagramServer.

- bdb.py: fix bomb on deleting a temporary breakpoint: there's no
method do_delete(); do_clear() was meant.  By Greg Ward.

- getopt.py: accept a non-list sequence for the long options (request
by Jack Jansen).  Because it might be a common mistake to pass a
single string, this situation is treated separately.  Also added
docstrings (copied from the library manual) and removed the (now
redundant) module comments.

- tempfile.py: improvements to avoid security leaks.

- code.py: moved compile_command() to new module codeop.py.

- pickle.py: support pickle format 1.3 (binary float added).  By Jim
Fulton. Also get rid of the undocumented obsolete Pickler dump_special
method.

- uu.py: Move 'import sys' to top of module, as noted by Tim Peters.

- imaplib.py: fix problem with some versions of IMAP4 servers that
choose to mix the case in their CAPABILITIES response.

- cmp.py: use (f1, f2) as cache key instead of f1 + ' ' + f2.  Noted
by Fredrik Lundh.

Changes to extension modules
----------------------------

- More doc strings for several modules were contributed by Chris
Petrilli: math, cmath, fcntl.

- Fixed a bug in zlibmodule.c that could cause core dumps on
decompression of rarely occurring input.

- cPickle.c: new version from Jim Fulton, with Open Source copyright
notice.  Also, initialize self->safe_constructors early on to prevent
crash in early dealloc.

- cStringIO.c: new version from Jim Fulton, with Open Source copyright
notice.  Also fixed a core dump in cStringIO.c when doing seeks.

- mpzmodule.c: fix signed character usage in mpz.mpz(stringobjecty).

- readline.c: Bernard Herzog pointed out that rl_parse_and_bind
modifies its argument string (bad function!), so we make a temporary
copy.

- sunaudiodev.c: Barry Warsaw added more smarts to get the device and
control pseudo-device, per audio(7I).

Changes to tools
----------------

- New, improved version of Barry Warsaw's Misc/python-mode.el (editing 
support for Emacs).

- tabnanny.py: added a -q ('quiet') option to tabnanny, which causes
only the names of offending files to be printed.

- freeze: when printing missing modules, also print the module they
were imported from.

- untabify.py: patch by Detlef Lannert to implement -t option
(set tab size).

Changes to Tkinter
------------------

- grid_bbox(): support new Tk API: grid bbox ?column row? ?column2
row2?

- _tkinter.c: RajGopal Srinivasan noted that the latest code (1.5.2a2)
doesn't work when running in a non-threaded environment.  He added
some #ifdefs that fix this.

Changes to the Python/C API
---------------------------

- Bumped API version number to 1008 -- enough things have changed!

- There's a new macro, PyThreadState_GET(), which does the same work
as PyThreadState_Get() without the overhead of a function call (it
also avoids the error check).  The two top calling locations of
PyThreadState_Get() have been changed to use this macro.

- All symbols intended for export from a DLL or shared library are now
marked as such (with the DL_IMPORT() macro) in the header file that
declares them.  This was needed for the BeOS port, and should also
make some other ports easier.  The PC port no longer needs the file
with exported symbols (PC/python_nt.def).  There's also a DL_EXPORT
macro which is only used for init methods in extension modules, and
for Py_Main().

Invisible changes to internals
------------------------------

- Fixed a bug in new_buffersize() in fileobject.c which could
return a buffer size that was way too large.

- Use PySys_WriteStderr instead of fprintf in most places.

- dictobject.c: remove dead code discovered by Vladimir Marangozov.

- tupleobject.c: make tuples less hungry -- an extra item was
allocated but never used.  Tip by Vladimir Marangozov.

- mymath.h: Metrowerks PRO4 finally fixes the hypot snafu.  (Jack
Jansen)

- import.c: Jim Fulton fixes a reference count bug in
PyEval_GetGlobals.

- glmodule.c: check in the changed version after running the stubber
again -- this solves the conflict with curses over the 'clear' entry
point much nicer.  (Jack Jansen had checked in the changes to cstubs
eons ago, but I never regenrated glmodule.c :-( )

- frameobject.c: fix reference count bug in PyFrame_New.  Vladimir
Marangozov.

- stropmodule.c: add a missing DECREF in an error exit.  Submitted by
Jonathan Giddy.


======================================================================


From 1.5.2a1 to 1.5.2a2
=======================

General
-------

- It is now a syntax error to have a function argument without a
default following one with a default.

- __file__ is now set to the .py file if it was parsed (it used to
always be the .pyc/.pyo file).

- Don't exit with a fatal error during initialization when there's a
problem with the exceptions.py module.

- New environment variable PYTHONOPTIMIZE can be used to set -O.

- New version of python-mode.el for Emacs.

Miscellaneous fixed bugs
------------------------

- No longer print the (confusing) error message about stack underflow
while compiling.

- Some threading and locking bugs fixed.

- When errno is zero, report "Error", not "Success".

Documentation
-------------

- Documentation will be released separately.

- Doc strings added to array and md5 modules by Chris Petrilli.

Ports and build procedure
-------------------------

- Stop installing when a move or copy fails.

- New version of the OS/2 port code by Jeff Rush.

- The makesetup script handles absolute filenames better.

- The 'new' module is now enabled by default in the Setup file.

- I *think* I've solved the problem with the Linux build blowing up
sometimes due to a conflict between sigcheck/intrcheck and
signalmodule.

Built-in functions
------------------

- The second argument to apply() can now be any sequence, not just a
tuple.

Built-in types
--------------

- Lists have a new method: L1.extend(L2) is equivalent to the common
idiom L1[len(L1):] = L2.

- Better error messages when a sequence is indexed with a non-integer.

- Bettter error message when calling a non-callable object (include
the type in the message).

Python services
---------------

- New version of cPickle.c fixes some bugs.

- pickle.py: improved instantiation error handling.

- code.py: reworked quite a bit.  New base class
InteractiveInterpreter and derived class InteractiveConsole.  Fixed
several problems in compile_command().

- py_compile.py: print error message and continue on syntax errors.
Also fixed an old bug with the fstat code (it was never used).

- pyclbr.py: support submodules of packages.

String Services
---------------

- StringIO.py: raise the right exception (ValueError) for attempted
I/O on closed StringIO objects.

- re.py: fixed a bug in subn(), which caused .groups() to fail inside
the replacement function called by sub().

- The struct module has a new format 'P': void * in native mode.

Generic OS Services
-------------------

- Module time: Y2K robustness.  2-digit year acceptance depends on
value of time.accept2dyear, initialized from env var PYTHONY2K,
default 0.  Years 00-68 mean 2000-2068, while 69-99 mean 1969-1999
(POSIX or X/Open recommendation).

- os.path: normpath(".//x") should return "x", not "/x".

- getpass.py: fall back on default_getpass() when sys.stdin.fileno()
doesn't work.

- tempfile.py: regenerate the template after a fork() call.

Optional OS Services
--------------------

- In the signal module, disable restarting interrupted system calls
when we have siginterrupt().

Debugger
--------

- No longer set __args__; this feature is no longer supported and can
affect the debugged code.

- cmd.py, pdb.py and bdb.py have been overhauled by Richard Wolff, who
added aliases and some other useful new features, e.g. much better
breakpoint support: temporary breakpoint, disabled breakpoints,
breakpoints with ignore counts, and conditions; breakpoints can be set
on a file before it is loaded.

Profiler
--------

- Changes so that JPython can use it.  Also fix the calibration code
so it actually works again
.
Internet Protocols and Support
------------------------------

- imaplib.py: new version from Piers Lauder.

- smtplib.py: change sendmail() method to accept a single string or a
list or strings as the destination (commom newbie mistake).

- poplib.py: LIST with a msg argument fixed.

- urlparse.py: some optimizations for common case (http).

- urllib.py: support content-length in info() for ftp protocol;
support for a progress meter through a third argument to
urlretrieve(); commented out gopher test (the test site is dead).

Internet Data handling
----------------------

- sgmllib.py: support tags with - or . in their name.

- mimetypes.py: guess_type() understands 'data' URLs.

Restricted Execution
--------------------

- The classes rexec.RModuleLoader and rexec.RModuleImporter no
longer exist.

Tkinter
-------

- When reporting an exception, store its info in sys.last_*.  Also,
write all of it to stderr.

- Added NS, EW, and NSEW constants, for grid's sticky option.

- Fixed last-minute bug in 1.5.2a1 release: need to include "mytime.h".

- Make bind variants without a sequence return a tuple of sequences
(formerly it returned a string, which wasn't very convenient).

- Add image commands to the Text widget (these are new in Tk 8.0).

- Added new listbox and canvas methods: {xview,yview}_{scroll,moveto}.)

- Improved the thread code (but you still can't call update() from
another thread on Windows).

- Fixed unnecessary references to _default_root in the new dialog
modules.

- Miscellaneous problems fixed.


Windows General
---------------

- Call LoadLibraryEx(..., ..., LOAD_WITH_ALTERED_SEARCH_PATH) to
search for dependent dlls in the directory containing the .pyd.

- In debugging mode, call DebugBreak() in Py_FatalError().

Windows Installer
-----------------

- Install zlib.dll in the DLLs directory instead of in the win32
system directory, to avoid conflicts with other applications that have 
their own zlib.dll.

Test Suite
----------

- test_long.py: new test for long integers, by Tim Peters.

- regrtest.py: improved so it can be used for other test suites as
well.

- test_strftime.py: use re to compare test results, to support legal
variants (e.g. on Linux).

Tools and Demos
---------------

- Four new scripts in Tools/scripts: crlf.py and lfcr.py (to
remove/add Windows style '\r\n' line endings), untabify.py (to remove
tabs), and rgrep.yp (reverse grep).

- Improvements to Tools/freeze/.  Each Python module is now written to
its own C file.  This prevents some compilers or assemblers from
blowing up on large frozen programs, and saves recompilation time if
only a few modules are changed.  Other changes too, e.g. new command
line options -x and -i.

- Much improved (and smaller!) version of Tools/scripts/mailerdaemon.py.

Python/C API
------------

- New mechanism to support extensions of the type object while
remaining backward compatible with extensions compiled for previous
versions of Python 1.5.  A flags field indicates presence of certain
fields.

- Addition to the buffer API to differentiate access to bytes and
8-bit characters (in anticipation of Unicode characters).

- New argument parsing format t# ("text") to indicate 8-bit
characters; s# simply means 8-bit bytes, for backwards compatibility.

- New object type, bufferobject.c is an example and can be used to
create buffers from memory.

- Some support for 64-bit longs, including some MS platforms.

- Many calls to fprintf(stderr, ...) have been replaced with calls to
PySys_WriteStderr(...).

- The calling context for PyOS_Readline() has changed: it must now be
called with the interpreter lock held!  It releases the lock around
the call to the function pointed to by PyOS_ReadlineFunctionPointer
(default PyOS_StdioReadline()).

- New APIs PyLong_FromVoidPtr() and PyLong_AsVoidPtr().

- Renamed header file "thread.h" to "pythread.h".

- The code string of code objects may now be anything that supports the
buffer API.


======================================================================


From 1.5.1 to 1.5.2a1
=====================

General
-------

- When searching for the library, a landmark that is a compiled module
(string.pyc or string.pyo) is also accepted.

- When following symbolic links to the python executable, use a loop
so that a symlink to a symlink can work.

- Added a hack so that when you type 'quit' or 'exit' at the
interpreter, you get a friendly explanation of how to press Ctrl-D (or 
Ctrl-Z) to exit.

- New and improved Misc/python-mode.el (Python mode for Emacs).

- Revert a new feature in Unix dynamic loading: for one or two
revisions, modules were loaded using the RTLD_GLOBAL flag.  It turned
out to be a bad idea.

Miscellaneous fixed bugs
------------------------

- All patches on the patch page have been integrated.  (But much more
has been done!)

- Several memory leaks plugged (e.g. the one for classes with a
__getattr__ method).

- Removed the only use of calloc().  This triggered an obscure bug on
multiprocessor Sparc Solaris 2.6.

- Fix a peculiar bug that would allow "import sys.time" to succeed
(believing the built-in time module to be a part of the sys package).

- Fix a bug in the overflow checking when converting a Python long to
a C long (failed to convert -2147483648L, and some other cases).

Documentation
-------------

- Doc strings have been added to many extension modules: __builtin__,
errno, select, signal, socket, sys, thread, time.  Also to methods of
list objects (try [].append.__doc__).  A doc string on a type will now
automatically be propagated to an instance if the instance has methods
that are accessed in the usual way.

- The documentation has been expanded and the formatting improved.
(Remember that the documentation is now unbundled and has its own
release cycle though; see http://www.python.org/doc/.)

- Added Misc/Porting -- a mini-FAQ on porting to a new platform.

Ports and build procedure
-------------------------

- The BeOS port is now integrated.  Courtesy Chris Herborth.

- Symbol files for FreeBSD 2.x and 3.x have been contributed
(Lib/plat-freebsd[23]/*).

- Support HPUX 10.20 DCE threads.

- Finally fixed the configure script so that (on SGI) if -OPT:Olimit=0
works, it won't also use -Olimit 1500 (which gives a warning for every
file).  Also support the SGI_ABI environment variable better.

- The makesetup script now understands absolute pathnames ending in .o
in the module -- it assumes it's a file for which we have no source.

- Other miscellaneous improvements to the configure script and
Makefiles.

- The test suite now uses a different sound sample.

Built-in functions
------------------

- Better checks for invalid input to int(), long(), string.atoi(),
string.atol().  (Formerly, a sign without digits would be accepted as
a legal ways to spell zero.)

- Changes to map() and filter() to use the length of a sequence only
as a hint -- if an IndexError happens earlier, take that.  (Formerly,
this was considered an error.)

- Experimental feature in getattr(): a third argument can specify a
default (instead of raising AttributeError).

- Implement round() slightly different, so that for negative ndigits
no additional errors happen in the last step.

- The open() function now adds the filename to the exception when it
fails.

Built-in exceptions
-------------------

- New standard exceptions EnvironmentError and PosixError.
EnvironmentError is the base class for IOError and PosixError;
PosixError is the same as os.error.  All this so that either exception
class can be instantiated with a third argument indicating a filename.
The built-in function open() and most os/posix functions that take a
filename argument now use this.

Built-in types
--------------

- List objects now have an experimental pop() method; l.pop() returns
and removes the last item; l.pop(i) returns and removes the item at
i.  Also, the sort() method is faster again.  Sorting is now also
safer: it is impossible for the sorting function to modify the list
while the sort is going on (which could cause core dumps).

- Changes to comparisons: numbers are now smaller than any other type.
This is done to prevent the circularity where [] < 0L < 1 < [] is
true.  As a side effect, cmp(None, 0) is now positive instead of
negative.  This *shouldn't* affect any working code, but I've found
that the change caused several "sleeping" bugs to become active, so
beware!

- Instance methods may now have other callable objects than just
Python functions as their im_func.  Use new.instancemethod() or write
your own C code to create them; new.instancemethod() may be called
with None for the instance to create an unbound method.

- Assignment to __name__, __dict__ or __bases__ of a class object is
now allowed (with stringent type checks); also allow assignment to
__getattr__ etc.  The cached values for __getattr__ etc. are
recomputed after such assignments (but not for derived classes :-( ).

- Allow assignment to some attributes of function objects: func_code,
func_defaults and func_doc / __doc__.  (With type checks except for
__doc__ / func_doc .)

Python services
---------------

- New tests (in Lib/test): reperf.py (regular expression benchmark),
sortperf.py (list sorting benchmark), test_MimeWriter.py (test case
for the MimeWriter module).

- Generalized test/regrtest.py so that it is useful for testing other
packages.

- The ihooks.py module now understands package imports.

- In code.py, add a class that subsumes Fredrik Lundh's
PythonInterpreter class.  The interact() function now uses this.

- In rlcompleter.py, in completer(), return None instead of raising an
IndexError when there are no more completions left.

- Fixed the marshal module to test for certain common kinds of invalid
input.  (It's still not foolproof!)

- In the operator module, add an alias (now the preferred name)
"contains" for "sequenceincludes".

String Services
---------------

- In the string and strop modules, in the replace() function, treat an
empty pattern as an error (since it's not clear what was meant!).

- Some speedups to re.py, especially the string substitution and split
functions.  Also added new function/method findall(), to find all
occurrences of a given substring.

- In cStringIO, add better argument type checking and support the
readonly 'closed' attribute (like regular files).

- In the struct module, unsigned 1-2 byte sized formats no longer
result in long integer values.

Miscellaneous services
----------------------

- In whrandom.py, added new method and function randrange(), same as
choice(range(start, stop, step)) but faster.  This addresses the
problem that randint() was accidentally defined as taking an inclusive
range.  Also, randint(a, b) is now redefined as randrange(a, b+1),
adding extra range and type checking to its arguments!

- Add some semi-thread-safety to random.gauss() (it used to be able to 
crash when invoked from separate threads; now the worst it can do is
give a duplicate result occasionally).

- Some restructuring and generalization done to cmd.py.

- Major upgrade to ConfigParser.py; converted to using 're', added new 
exceptions, support underscore in section header and option name.  No
longer add 'name' option to every section; instead, add '__name__'.

- In getpass.py, don't use raw_input() to ask for the password -- we
don't want it to show up in the readline history!  Also don't catch
interrupts (the try-finally already does all necessary cleanup).

Generic OS Services
-------------------

- New functions in os.py: makedirs(), removedirs(), renames().  New
variable: linesep (the line separator as found in binary files,
i.e. '\n' on Unix, '\r\n' on DOS/Windows, '\r' on Mac.  Do *not* use
this with files opened in (default) text mode; the line separator used
will always be '\n'!

- Changes to the 'os.path' submodule of os.py: added getsize(),
getmtime(), getatime() -- these fetch the most popular items from the
stat return tuple.

- In the time module, add strptime(), if it exists.  (This parses a
time according to a format -- the inverse of strftime().)  Also,
remove the call to mktime() from strftime() -- it messed up the
formatting of some non-local times.

- In the socket module, added a new function gethostbyname_ex().
Also, don't use #ifdef to test for some symbols that are enums on some
platforms (and should exist everywhere).

Optional OS Services
--------------------

- Some fixes to gzip.py.  In particular, the readlines() method now
returns the lines *with* trailing newline characters, like readlines()
of regular file objects.  Also, it didn't work together with cPickle;
fixed that.

- In whichdb.py, support byte-swapped dbhash (bsddb) files.

- In anydbm.py, look at the type of an existing database to determine
which module to use to open it.  (The anydbm.error exception is now a
tuple.)

Unix Services
-------------

- In the termios module, in tcsetattr(), initialize the structure vy
calling tcgetattr().

- Added some of the "wait status inspection" macros as functions to
the posix module (and thus to the os module): WEXITSTATUS(),
WIFEXITED(), WIFSIGNALED(), WIFSTOPPED(), WSTOPSIG(), WTERMSIG().

- In the syslog module, make the default facility more intuitive
(matching the docs).

Debugger
--------

- In pdb.py, support for setting breaks on files/modules that haven't
been loaded yet.

Internet Protocols and Support
------------------------------

- Changes in urllib.py; sped up unquote() and quote().  Fixed an
obscure bug in quote_plus().  Added urlencode(dict) -- convenience
function for sending a POST request with urlopen().  Use the getpass
module to ask for a password.  Rewrote the (test) main program so that
when used as a script, it can retrieve one or more URLs to stdout.
Use -t to run the self-test.  Made the proxy code work again.

- In cgi.py, treat "HEAD" the same as "GET", so that CGI scripts don't
fail when someone asks for their HEAD.  Also, for POST, set the
default content-type to application/x-www-form-urlencoded.  Also, in
FieldStorage.__init__(), when method='GET', always get the query
string from environ['QUERY_STRING'] or sys.argv[1] -- ignore an
explicitly passed in fp.

- The smtplib.py module now supports ESMTP and has improved standard
compliance, for picky servers.

- Improved imaplib.py.

- Fixed UDP support in SocketServer.py (it never worked).

- Fixed a small bug in CGIHTTPServer.py.

Internet Data handling
----------------------

- In rfc822.py, add a new class AddressList.  Also support a new
overridable method, isheader().  Also add a get() method similar to
dictionaries (and make getheader() an alias for it).  Also, be smarter
about seekable (test whether fp.tell() works) and test for presence of
unread() method before trying seeks.

- In sgmllib.py, restore the call to report_unbalanced() that was lost
long ago.  Also some other improvements: handle <? processing
instructions >, allow . and - in entity names, and allow \r\n as line
separator.

- Some restructuring and generalization done to multifile.py; support
a 'seekable' flag.

Restricted Execution
--------------------

- Improvements to rexec.py: package support; support a (minimal)
sys.exc_info().  Also made the (test) main program a bit fancier (you
can now use it to run arbitrary Python scripts in restricted mode).

Tkinter
-------

- On Unix, Tkinter can now safely be used from a multi-threaded
application.  (Formerly, no threads would make progress while
Tkinter's mainloop() was active, because it didn't release the Python
interpreter lock.)  Unfortunately, on Windows, threads other than the
main thread should not call update() or update_idletasks() because
this will deadlock the application.

- An interactive interpreter that uses readline and Tkinter no longer
uses up all available CPU time.

- Even if readline is not used, Tk windows created in an interactive
interpreter now get continuously updated.  (This even works in Windows
as long as you don't hit a key.)

- New demos in Demo/tkinter/guido/: brownian.py, redemo.py, switch.py.

- No longer register Tcl_finalize() as a low-level exit handler.  It
may call back into Python, and that's a bad idea.

- Allow binding of Tcl commands (given as a string).

- Some minor speedups; replace explicitly coded getint() with int() in
most places.

- In FileDialog.py, remember the directory of the selected file, if
given.

- Change the names of all methods in the Wm class: they are now
wm_title(), etc.  The old names (title() etc.) are still defined as
aliases.

- Add a new method of interpreter objects, interpaddr().  This returns
the address of the Tcl interpreter object, as an integer.  Not very
useful for the Python programmer, but this can be called by another C
extension that needs to make calls into the Tcl/Tk C API and needs to
get the address of the Tcl interpreter object.  A simple cast of the
return value to (Tcl_Interp *) will do the trick.

Windows General
---------------

- Don't insist on proper case for module source files if the filename
is all uppercase (e.g. FOO.PY now matches foo; but FOO.py still
doesn't).  This should address problems with this feature on
oldfashioned filesystems (Novell servers?).

Windows Library
---------------

- os.environ is now all uppercase, but accesses are case insensitive,
and the putenv() calls made as a side effect of changing os.environ
are case preserving.

- Removed samefile(), sameopenfile(), samestat() from os.path (aka
ntpath.py) -- these cannot be made to work reliably (at least I
wouldn't know how).

- Fixed os.pipe() so that it returns file descriptors acceptable to
os.read() and os.write() (like it does on Unix), rather than Windows
file handles.

- Added a table of WSA error codes to socket.py.

- In the select module, put the (huge) file descriptor arrays on the
heap.

- The getpass module now raises KeyboardInterrupt when it sees ^C.

- In mailbox.py, fix tell/seek when using files opened in text mode.

- In rfc822.py, fix tell/seek when using files opened in text mode.

- In the msvcrt extension module, release the interpreter lock for
calls that may block: _locking(), _getch(), _getche().  Also fix a
bogus error return when open_osfhandle() doesn't have the right
argument list.

Windows Installer
-----------------

- The registry key used is now "1.5" instead of "1.5.x" -- so future
versions of 1.5 and Mark Hammond's win32all installer don't need to be 
resynchronized.

Windows Tools
-------------

- Several improvements to freeze specifically for Windows.

Windows Build Procedure
-----------------------

- The VC++ project files and the WISE installer have been moved to the
PCbuild subdirectory, so they are distributed in the same subdirectory
where they must be used.  This avoids confusion.

- New project files for Windows 3.1 port by Jim Ahlstrom.

- Got rid of the obsolete subdirectory PC/setup_nt/.

- The projects now use distinct filenames for the .exe, .dll, .lib and
.pyd files built in debug mode (by appending "_d" to the base name,
before the extension).  This makes it easier to switch between the two
and get the right versions.  There's a pragma in config.h that directs
the linker to include the appropriate .lib file (so python15.lib no
longer needs to be explicit in your project).

- The installer now installs more files (e.g. config.h).  The idea is
that you shouldn't need the source distribution if you want build your
own extensions in C or C++.

Tools and Demos
---------------

- New script nm2def.py by Marc-Andre Lemburg, to construct
PC/python_nt.def automatically (some hand editing still required).

- New tool ndiff.py: Tim Peters' text diffing tool.

- Various and sundry improvements to the freeze script.

- The script texi2html.py (which was part of the Doc tree but is no
longer used there) has been moved to the Tools/scripts subdirectory.

- Some generalizations in the webchecker code.  There's now a
primnitive gui for websucker.py: wsgui.py.  (In Tools/webchecker/.)

- The ftpmirror.py script now handles symbolic links properly, and
also files with multiple spaces in their names.

- The 1.5.1 tabnanny.py suffers an assert error if fed a script whose
last line is both indented and lacks a newline.  This is now fixed.

Python/C API
------------

- Added missing prototypes for PyEval_CallFunction() and
PyEval_CallMethod().

- New macro PyList_SET_ITEM().

- New macros to access object members for PyFunction, PyCFunction
objects.

- New APIs PyImport_AppendInittab() and PyImport_ExtendInittab() to
dynamically add one or many entries to the table of built-in modules.

- New macro Py_InitModule3(name, methods, doc) which calls
Py_InitModule4() with appropriate arguments.  (The -4 variant requires 
you to pass an obscure version number constant which is always the same.)

- New APIs PySys_WriteStdout() and PySys_WriteStderr() to write to
sys.stdout or sys.stderr using a printf-like interface.  (Used in
_tkinter.c, for example.)

- New APIs for conversion between Python longs and C 'long long' if
your compiler supports it.

- PySequence_In() is now called PySequence_Contains().
(PySequence_In() is still supported for b/w compatibility; it is
declared obsolete because its argument order is confusing.)

- PyDict_GetItem() and PyDict_GetItemString() are changed so that they
*never* raise an exception -- (even if the hash() fails, simply clear
the error).  This was necessary because there is lots of code out
there that already assumes this.

- Changes to PySequence_Tuple() and PySequence_List() to use the
length of a sequence only as a hint -- if an IndexError happens
earlier, take that.  (Formerly, this was considered an error.)

- Reformatted abstract.c to give it a more familiar "look" and fixed
many error checking bugs.

- Add NULL pointer checks to all calls of a C function through a type
object and extensions (e.g. nb_add).

- The code that initializes sys.path now calls Py_GetPythonHome()
instead of getenv("PYTHONHOME").  This, together with the new API
Py_SetPythonHome(), makes it easier for embedding applications to
change the notion of Python's "home" directory (where the libraries
etc. are sought).

- Fixed a very old bug in the parsing of "O?" format specifiers.


======================================================================


========================================
==> Release 1.5.1 (October 31, 1998) <==
========================================

From 1.5 to 1.5.1
=================

General
-------

- The documentation is now unbundled.  It has also been extensively
modified (mostly to implement a new and more uniform formatting
style).  We figure that most people will prefer to download one of the
preformatted documentation sets (HTML, PostScript or PDF) and that
only a minority have a need for the LaTeX or FrameMaker sources.  Of
course, the unbundled documentation sources still released -- just not
in the same archive file, and perhaps not on the same date.

- All bugs noted on the errors page (and many unnoted) are fixed.  All
new bugs take their places.

- No longer a core dump when attempting to print (or repr(), or str())
a list or dictionary that contains an instance of itself; instead, the
recursive entry is printed as [...] or {...}.  See Py_ReprEnter() and
Py_ReprLeave() below.  Comparisons of such objects still go beserk,
since this requires a different kind of fix; fortunately, this is a
less common scenario in practice.

Syntax change
-------------

- The raise statement can now be used without arguments, to re-raise 
a previously set exception.  This should be used after catching an
exception with an except clause only, either in the except clause or
later in the same function.

Import and module handling
--------------------------

- The implementation of import has changed to use a mutex (when
threading is supported).  This means that when two threads
simultaneously import the same module, the import statements are
serialized.  Recursive imports are not affected.

- Rewrote the finalization code almost completely, to be much more
careful with the order in which modules are destroyed.  Destructors
will now generally be able to reference built-in names such as None
without trouble.

- Case-insensitive platforms such as Mac and Windows require the case
of a module's filename to match the case of the module name as
specified in the import statement (see below).

- The code for figuring out the default path now distinguishes between
files, modules, executable files, and directories.  When expecting a
module, we also look for the .pyc or .pyo file.

Parser/tokenizer changes
------------------------

- The tokenizer can now warn you when your source code mixes tabs and
spaces for indentation in a manner that depends on how much a tab is
worth in spaces.  Use "python -t" or "python -v" to enable this
option.  Use "python -tt" to turn the warnings into errors.  (See also
tabnanny.py and tabpolice.py below.)

- Return unsigned characters from tok_nextc(), so '\377' isn't
mistaken for an EOF character.

- Fixed two pernicious bugs in the tokenizer that only affected AIX.
One was actually a general bug that was triggered by AIX's smaller I/O
buffer size.  The other was a bug in the AIX optimizer's loop
unrolling code; swapping two statements made the problem go away.

Tools, demos and miscellaneous files
------------------------------------

- There's a new version of Misc/python-mode.el (the Emacs mode for
Python) which is much smarter about guessing the indentation style
used in a particular file.  Lots of other cool features too!

- There are two new tools in Tools/scripts: tabnanny.py and
tabpolice.py, implementing two different ways of checking whether a
file uses indentation in a way that is sensitive to the interpretation
of a tab.  The preferred module is tabnanny.py (by Tim Peters).

- Some new demo programs:

	Demo/tkinter/guido/paint.py -- Dave Mitchell
	Demo/sockets/unixserver.py -- Piet van Oostrum
	

- Much better freeze support.  The freeze script can now freeze
hierarchical module names (with a corresponding change to import.c),
and has a few extra options (e.g. to suppress freezing specific
modules).  It also does much more on Windows NT.

- Version 1.0 of the faq wizard is included (only very small changes
since version 0.9.0).

- New feature for the ftpmirror script: when removing local files
(i.e., only when -r is used), do a recursive delete.

Configuring and building Python
-------------------------------

- Get rid of the check for -linet -- recent Sequent Dynix systems don't
need this any more and apparently it screws up their configuration.

- Some changes because gcc on SGI doesn't support '-all'.

- Changed the build rules to use $(LIBRARY) instead of
  -L.. -lpython$(VERSION)
since the latter trips up the SunOS 4.1.x linker (sigh).

- Fix the bug where the '# dgux is broken' comment in the Makefile
tripped over Make on some platforms.

- Changes for AIX: install the python.exp file; properly use
$(srcdir); the makexp_aix script now removes C++ entries of the form
Class::method.

- Deleted some Makefile targets only used by the (long obsolete)
gMakefile hacks.

Extension modules
-----------------

- Performance and threading improvements to the socket and bsddb
modules, by Christopher Lindblad of Infoseek.

- Added operator.__not__ and operator.not_.

- In the thread module, when a thread exits due to an unhandled
exception, don't store the exception information in sys.last_*; it
prevents proper calling of destructors of local variables.

- Fixed a number of small bugs in the cPickle module.

- Changed find() and rfind() in the strop module so that
find("x","",2) returns -1, matching the implementation in string.py.

- In the time module, be more careful with the result of ctime(), and
test for HAVE_MKTIME before usinmg mktime().

- Doc strings contributed by Mitch Chapman to the termios, pwd, gdbm
modules.

- Added the LOG_SYSLOG constant to the syslog module, if defined.

Standard library modules
------------------------

- All standard library modules have been converted to an indentation
style using either only tabs or only spaces -- never a mixture -- if
they weren't already consistent according to tabnanny.  This means
that the new -t option (see above) won't complain about standard
library modules.

- New standard library modules:

	threading -- GvR and the thread-sig
		Java style thread objects -- USE THIS!!!

	getpass -- Piers Lauder
		simple utilities to prompt for a password and to
		retrieve the current username

	imaplib -- Piers Lauder
		interface for the IMAP4 protocol

	poplib -- David Ascher, Piers Lauder
		interface for the POP3 protocol

	smtplib -- Dragon De Monsyne
		interface for the SMTP protocol

- Some obsolete modules moved to a separate directory (Lib/lib-old)
which is *not* in the default module search path:

	Para
	addpack
	codehack
	fmt
	lockfile
	newdir
	ni
	rand
	tb

- New version of the PCRE code (Perl Compatible Regular Expressions --
the re module and the supporting pcre extension) by Andrew Kuchling.
Incompatible new feature in re.sub(): the handling of escapes in the
replacement string has changed.

- Interface change in the copy module: a __deepcopy__ method is now
called with the memo dictionary as an argument.

- Feature change in the tokenize module: differentiate between NEWLINE
token (an official newline) and NL token (a newline that the grammar
ignores).

- Several bugfixes to the urllib module.  It is now truly thread-safe,
and several bugs and a portability problem have been fixed.  New
features, all due to Sjoerd Mullender: When creating a temporary file,
it gives it an appropriate suffix.  Support the "data:" URL scheme.
The open() method uses the tempcache.

- New version of the xmllib module (this time with a test suite!) by
Sjoerd Mullender.

- Added debugging code to the telnetlib module, to be able to trace
the actual traffic.

- In the rfc822 module, added support for deleting a header (still no
support for adding headers, though).  Also fixed a bug where an
illegal address would cause a crash in getrouteaddr(), fixed a
sign reversal in mktime_tz(), and use the local timezone by default
(the latter two due to Bill van Melle).

- The normpath() function in the dospath and ntpath modules no longer
does case normalization -- for that, use the separate function
normcase() (which always existed); normcase() has been sped up and
fixed (it was the cause of a crash in Mark Hammond's installer in
certain locales).

- New command supported by the ftplib module: rmd(); also fixed some
minor bugs.

- The profile module now uses a different timer function by default -- 
time.clock() is generally better than os.times().  This makes it work
better on Windows NT, too.

- The tempfile module now recovers when os.getcwd() raises an
exception.

- Fixed some bugs in the random module; gauss() was subtly wrong, and
vonmisesvariate() should return a full circle.  Courtesy Mike Miller,
Lambert Meertens (gauss()), and Magnus Kessler (vonmisesvariate()).

- Better default seed in the whrandom module, courtesy Andrew Kuchling.

- Fix slow close() in shelve module.

- The Unix mailbox class in the mailbox module is now more robust when
a line begins with the string "From " but is definitely not the start
of a new message.  The pattern used can be changed by overriding a
method or class variable.

- Added a rmtree() function to the copy module.

- Fixed several typos in the pickle module.  Also fixed problems when
unpickling in restricted execution environments.

- Added docstrings and fixed a typo in the py_compile and compileall
modules.  At Mark Hammond's repeated request, py_compile now append a
newline to the source if it needs one.  Both modules support an extra
parameter to specify the purported source filename (to be used in
error messages).

- Some performance tweaks by Jeremy Hylton to the gzip module.

- Fixed a bug in the merge order of dictionaries in the ConfigParser
module.  Courtesy Barry Warsaw.

- In the multifile module, support the optional second parameter to
seek() when possible.

- Several fixes to the gopherlib module by Lars Marius Garshol.  Also, 
urlparse now correctly handles Gopher URLs with query strings.

- Fixed a tiny bug in format_exception() in the traceback module.
Also rewrite tb_lineno() to be compatible with JPython (and not
disturb the current exception!); by Jim Hugunin.

- The httplib module is more robust when servers send a short response 
-- courtesy Tim O'Malley.

Tkinter and friends
-------------------

- Various typos and bugs fixed.

- New module Tkdnd implements a drag-and-drop protocol (within one
application only).

- The event_*() widget methods have been restructured slightly -- they
no longer use the default root.

- The interfaces for the bind*() and unbind() widget methods have been
redesigned; the bind*() methods now return the name of the Tcl command 
created for the callback, and this can be passed as an optional
argument to unbind() in order to delete the command (normally, such
commands are automatically unbound when the widget is destroyed, but
for some applications this isn't enough).

- Variable objects now have trace methods to interface to Tcl's
variable tracing facilities.

- Image objects now have an optional keyword argument, 'master', to
specify a widget (tree) to which they belong.  The image_names() and
image_types() calls are now also widget methods.

- There's a new global call, Tkinter.NoDefaultRoot(), which disables
all use of the default root by the Tkinter library.  This is useful to
debug applications that are in the process of being converted from
relying on the default root to explicit specification of the root
widget.

- The 'exit' command is deleted from the Tcl interpreter, since it
provided a loophole by which one could (accidentally) exit the Python
interpreter without invoking any cleanup code.

- Tcl_Finalize() is now registered as a Python low-level exit handle,
so Tcl will be finalized when Python exits.

The Python/C API
----------------

- New function PyThreadState_GetDict() returns a per-thread dictionary
intended for storing thread-local global variables.

- New functions Py_ReprEnter() and Py_ReprLeave() use the per-thread
dictionary to allow recursive container types to detect recursion in
their repr(), str() and print implementations.

- New function PyObject_Not(x) calculates (not x) according to Python's 
standard rules (basically, it negates the outcome PyObject_IsTrue(x).

- New function _PyModule_Clear(), which clears a module's dictionary
carefully without removing the __builtins__ entry.  This is implied
when a module object is deallocated (this used to clear the dictionary
completely).

- New function PyImport_ExecCodeModuleEx(), which extends
PyImport_ExecCodeModule() by adding an extra parameter to pass it the
true file.

- New functions Py_GetPythonHome() and Py_SetPythonHome(), intended to
allow embedded applications to force a different value for PYTHONHOME.

- New global flag Py_FrozenFlag is set when this is a "frozen" Python
binary; it suppresses warnings about not being able to find the
standard library directories.

- New global flag Py_TabcheckFlag is incremented by the -t option and
causes the tokenizer to issue warnings or errors about inconsistent
mixing of tabs and spaces for indentation.

Miscellaneous minor changes and bug fixes
-----------------------------------------

- Improved the error message when an attribute of an attribute-less
object is requested -- include the name of the attribute and the type
of the object in the message.

- Sped up int(), long(), float() a bit.

- Fixed a bug in list.sort() that would occasionally dump core.

- Fixed a bug in PyNumber_Power() that caused numeric arrays to fail
when taken tothe real power.

- Fixed a number of bugs in the file reading code, at least one of
which could cause a core dump on NT, and one of which would
occasionally cause file.read() to return less than the full contents
of the file.

- Performance hack by Vladimir Marangozov for stack frame creation.

- Make sure setvbuf() isn't used unless HAVE_SETVBUF is defined.

Windows 95/NT
-------------

- The .lib files are now part of the distribution; they are collected
in the subdirectory "libs" of the installation directory.

- The extension modules (.pyd files) are now collected in a separate
subdirectory of the installation directory named "DLLs".

- The case of a module's filename must now match the case of the
module name as specified in the import statement.  This is an
experimental feature -- if it turns out to break in too many
situations, it will be removed (or disabled by default) in the future.
It can be disabled on a per-case basis by setting the environment
variable PYTHONCASEOK (to any value).


======================================================================


=====================================
==> Release 1.5 (January 3, 1998) <==
=====================================


From 1.5b2 to 1.5
=================

- Newly documentated module: BaseHTTPServer.py, thanks to Greg Stein.

- Added doc strings to string.py, stropmodule.c, structmodule.c,
thanks to Charles Waldman.

- Many nits fixed in the manuals, thanks to Fred Drake and many others
(especially Rob Hooft and Andrew Kuchling).  The HTML version now uses
HTML markup instead of inline GIF images for tables; only two images
are left (for obsure bits of math).  The index of the HTML version has
also been much improved.  Finally, it is once again possible to
generate an Emacs info file from the library manual (but I don't
commit to supporting this in future versions).

- New module: telnetlib.py (a simple telnet client library).

- New tool: Tools/versioncheck/, by Jack Jansen.

- Ported zlibmodule.c and bsddbmodule.c to NT; The project file for MS
DevStudio 5.0 now includes new subprojects to build the zlib and bsddb
extension modules.

- Many small changes again to Tkinter.py -- mostly bugfixes and adding
missing routines.  Thanks to Greg McFarlane for reporting a bunch of
problems and proofreading my fixes.

- The re module and its documentation are up to date with the latest
version released to the string-sig (Dec. 22).

- Stop test_grp.py from failing when the /etc/group file is empty
(yes, this happens!).

- Fix bug in integer conversion (mystrtoul.c) that caused
4294967296==0 to be true!

- The VC++ 4.2 project file should be complete again.

- In tempfile.py, use a better template on NT, and add a new optional
argument "suffix" with default "" to specify a specific extension for
the temporary filename (needed sometimes on NT but perhaps also handy
elsewhere).

- Fixed some bugs in the FAQ wizard, and converted it to use re
instead of regex.

- Fixed a mysteriously undetected error in dlmodule.c (it was using a
totally bogus routine name to raise an exception).

- Fixed bug in import.c which wasn't using the new "dos-8x3" name yet.

- Hopefully harmless changes to the build process to support shared
libraries on DG/UX.  This adds a target to create
libpython$(VERSION).so; however this target is *only* for DG/UX.

- Fixed a bug in the new format string error checking in getargs.c.

- A simple fix for infinite recursion when printing __builtins__:
reset '_' to None before printing and set it to the printed variable
*after* printing (and only when printing is successful).

- Fixed lib-tk/SimpleDialog.py to keep the dialog visible even if the
parent window is not (Skip Montanaro).

- Fixed the two most annoying problems with ftp URLs in
urllib.urlopen(); an empty file now correctly raises an error, and it
is no longer required to explicitly close the returned "file" object
before opening another ftp URL to the same host and directory.


======================================================================


From 1.5b1 to 1.5b2
===================

- Fixed a bug in cPickle.c that caused it to crash right away because
the version string had a different format.

- Changes in pickle.py and cPickle.c: when unpickling an instance of a
class that doesn't define the __getinitargs__() method, the __init__()
constructor is no longer called.  This makes a much larger group of
classes picklable by default, but may occasionally change semantics.
To force calling __init__() on unpickling, define a __getinitargs__()
method.  Other changes too, in particular cPickle now handles classes
defined in packages correctly.  The same change applies to copying
instances with copy.py.  The cPickle.c changes and some pickle.py
changes are courtesy Jim Fulton.

- Locale support in he "re" (Perl regular expressions) module.  Use 
the flag re.L (or re.LOCALE) to enable locale-specific matching
rules for \w and \b.  The in-line syntax for this flag is (?L).

- The built-in function isinstance(x, y) now also succeeds when y is
a type object and type(x) is y.

- repr() and str() of class and instance objects now reflect the
package/module in which the class is defined.

- Module "ni" has been removed.  (If you really need it, it's been
renamed to "ni1".  Let me know if this causes any problems for you.
Package authors are encouraged to write __init__.py files that
support both ni and 1.5 package support, so the same version can be
used with Python 1.4 as well as 1.5.)

- The thread module is now automatically included when threads are
configured.  (You must remove it from your existing Setup file,
since it is now in its own Setup.thread file.)

- New command line option "-x" to skip the first line of the script;
handy to make executable scripts on non-Unix platforms.

- In importdl.c, add the RTLD_GLOBAL to the dlopen() flags.  I
haven't checked how this affects things, but it should make symbols
in one shared library available to the next one.

- The Windows installer now installs in the "Program Files" folder on
the proper volume by default.

- The Windows configuration adds a new main program, "pythonw", and
registers a new extension, ".pyw" that invokes this.  This is a
pstandard Python interpreter that does not pop up a console window;
handy for pure Tkinter applications.  All output to the original
stdout and stderr is lost; reading from the original stdin yields
EOF.  Also, both python.exe and pythonw.exe now have a pretty icon
(a green snake in a box, courtesy Mark Hammond).

- Lots of improvements to emacs-mode.el again.  See Barry's web page:
http://www.python.org/ftp/emacs/pmdetails.html.

- Lots of improvements and additions to the library reference manual;
many by Fred Drake.

- Doc strings for the following modules: rfc822.py, posixpath.py,
ntpath.py, httplib.py.  Thanks to Mitch Chapman and Charles Waldman.

- Some more regression testing.

- An optional 4th (maxsplit) argument to strop.replace().

- Fixed handling of maxsplit in string.splitfields().

- Tweaked os.environ so it can be pickled and copied.

- The portability problems caused by indented preprocessor commands
and C++ style comments should be gone now.

- In random.py, added Pareto and Weibull distributions.

- The crypt module is now disabled in Modules/Setup.in by default; it
is rarely needed and causes errors on some systems where users often
don't know how to deal with those.

- Some improvements to the _tkinter build line suggested by Case Roole.

- A full suite of platform specific files for NetBSD 1.x, submitted by 
Anders Andersen.

- New Solaris specific header STROPTS.py.

- Moved a confusing occurrence of *shared* from the comments in
Modules/Setup.in (people would enable this one instead of the real
one, and get disappointing results).

- Changed the default mode for directories to be group-writable when
the installation process creates them.

- Check for pthread support in "-l_r" for FreeBSD/NetBSD, and support
shared libraries for both.

- Support FreeBSD and NetBSD in posixfile.py.

- Support for the "event" command, new in Tk 4.2.  By Case Roole.

- Add Tix_SafeInit() support to tkappinit.c.

- Various bugs fixed in "re.py" and "pcre.c".

- Fixed a bug (broken use of the syntax table) in the old "regexpr.c".

- In frozenmain.c, stdin is made unbuffered too when PYTHONUNBUFFERED
is set.

- Provide default blocksize for retrbinary in ftplib.py (Skip
Montanaro).

- In NT, pick the username up from different places in user.py (Jeff
Bauer).

- Patch to urlparse.urljoin() for ".." and "..#1", Marc Lemburg.

- Many small improvements to Jeff Rush' OS/2 support.

- ospath.py is gone; it's been obsolete for so many years now...

- The reference manual is now set up to prepare better HTML (still
using webmaker, alas).

- Add special handling to /Tools/freeze for Python modules that are
imported implicitly by the Python runtime: 'site' and 'exceptions'.

- Tools/faqwiz 0.8.3 -- add an option to suppress URL processing
inside <PRE>, by "Scott".

- Added ConfigParser.py, a generic parser for sectioned configuration
files.

- In _localemodule.c, LC_MESSAGES is not always defined; put it
between #ifdefs.

- Typo in resource.c: RUSAGE_CHILDERN -> RUSAGE_CHILDREN.

- Demo/scripts/newslist.py: Fix the way the version number is gotten
out of the RCS revision.

- PyArg_Parse[Tuple] now explicitly check for bad characters at the
end of the format string.

- Revamped PC/example_nt to support VC++ 5.x.

- <listobject>.sort() now uses a modified quicksort by Raymund Galvin,
after studying the GNU libg++ quicksort.  This should be much faster
if there are lots of duplicates, and otherwise at least as good.

- Added "uue" as an alias for "uuencode" to mimetools.py.  (Hm, the
uudecode bug where it complaints about trailing garbage is still there 
:-( ).

- pickle.py requires integers in text mode to be in decimal notation
(it used to accept octal and hex, even though it would only generate
decimal numbers).

- In string.atof(), don't fail when the "re" module is unavailable.
Plug the ensuing security leak by supplying an empty __builtins__
directory to eval().

- A bunch of small fixes and improvements to Tkinter.py.

- Fixed a buffer overrun in PC/getpathp.c.


======================================================================


From 1.5a4 to 1.5b1
===================

- The Windows NT/95 installer now includes full HTML of all manuals.
It also has a checkbox that lets you decide whether to install the
interpreter and library.  The WISE installer script for the installer
is included in the source tree as PC/python15.wse, and so are the
icons used for Python files.  The config.c file for the Windows build
is now complete with the pcre module.

- sys.ps1 and sys.ps2 can now arbitrary objects; their str() is
evaluated for the prompt.

- The reference manual is brought up to date (more or less -- it still
needs work, e.g. in the area of package import).

- The icons used by latex2html are now included in the Doc
subdirectory (mostly so that tarring up the HTML files can be fully
automated).  A simple index.html is also added to Doc (it only works
after you have successfully run latex2html).

- For all you would-be proselytizers out there: a new version of
Misc/BLURB describes Python more concisely, and Misc/comparisons
compares Python to several other languages.  Misc/BLURB.WINDOWS
contains a blurb specifically aimed at Windows programmers (by Mark
Hammond).

- A new version of the Python mode for Emacs is included as
Misc/python-mode.el.  There are too many new features to list here.
See http://www.python.org/ftp/emacs/pmdetails.html for more info.

- New module fileinput makes iterating over the lines of a list of
files easier.  (This still needs some more thinking to make it more
extensible.)

- There's full OS/2 support, courtesy Jeff Rush.  To build the OS/2
version, see PC/readme.txt and PC/os2vacpp.  This is for IBM's Visual
Age C++ compiler.  I expect that Jeff will also provide a binary
release for this platform.

- On Linux, the configure script now uses '-Xlinker -export-dynamic'
instead of '-rdynamic' to link the main program so that it exports its
symbols to shared libraries it loads dynamically.  I hope this doesn't
break on older Linux versions; it is needed for mklinux and appears to
work on Linux 2.0.30.

- Some Tkinter resstructuring: the geometry methods that apply to a
master are now properly usable on toplevel master widgets.  There's a
new (internal) widget class, BaseWidget.  New, longer "official" names
for the geometry manager methods have been added,
e.g. "grid_columnconfigure()" instead of "columnconfigure()".  The old
shorter names still work, and where there's ambiguity, pack wins over
place wins over grid.  Also, the bind_class method now returns its
value.

- New, RFC-822 conformant parsing of email addresses and address lists
in the rfc822 module, courtesy Ben Escoto.

- New, revamped tkappinit.c with support for popular packages (PIL,
TIX, BLT, TOGL).  For the last three, you need to execute the Tcl
command "load {} Tix" (or Blt, or Togl) to gain access to them.
The Modules/Setup line for the _tkinter module has been rewritten
using the cool line-breaking feature of most Bourne shells.

- New socket method connect_ex() returns the error code from connect()
instead of raising an exception on errors; this makes the logic
required for asynchronous connects simpler and more efficient.

- New "locale" module with (still experimental) interface to the
standard C library locale interface, courtesy Martin von Loewis.  This
does not repeat my mistake in 1.5a4 of always calling
setlocale(LC_ALL, "").  In fact, we've pretty much decided that
Python's standard numerical formatting operations should always use
the conventions for the C locale; the locale module contains utility
functions to format numbers according to the user specified locale.
(All this is accomplished by an explicit call to setlocale(LC_NUMERIC,
"C") after locale-changing calls.)  See the library manual. (Alas, the
promised changes to the "re" module for locale support have not been
materialized yet.  If you care, volunteer!)

- Memory leak plugged in Py_BuildValue when building a dictionary.

- Shared modules can now live inside packages (hierarchical module
namespaces).  No changes to the shared module itself are needed.

- Improved policy for __builtins__: this is a module in __main__ and a
dictionary everywhere else.

- Python no longer catches SIGHUP and SIGTERM by default.  This was
impossible to get right in the light of thread contexts.  If you want
your program to clean up when a signal happens, use the signal module
to set up your own signal handler.

- New Python/C API PyNumber_CoerceEx() does not return an exception
when no coercion is possible.  This is used to fix a problem where
comparing incompatible numbers for equality would raise an exception
rather than return false as in Python 1.4 -- it once again will return
false.

- The errno module is changed again -- the table of error messages
(errorstr) is removed.  Instead, you can use os.strerror().  This
removes redundance and a potential locale dependency.

- New module xmllib, to parse XML files.  By Sjoerd Mullender.

- New C API PyOS_AfterFork() is called after fork() in posixmodule.c.
It resets the signal module's notion of what the current process ID
and thread are, so that signal handlers will work after (and across)
calls to os.fork().

- Fixed most occurrences of fatal errors due to missing thread state.

- For vgrind (a flexible source pretty printer) fans, there's a simple
Python definition in Misc/vgrindefs, courtesy Neale Pickett.

- Fixed memory leak in exec statement.

- The test.pystone module has a new function, pystones(loops=LOOPS),
which returns a (benchtime, stones) tuple.  The main() function now
calls this and prints the report.

- Package directories now *require* the presence of an __init__.py (or
__init__.pyc) file before they are considered as packages.  This is
done to prevent accidental subdirectories with common names from
overriding modules with the same name.

- Fixed some strange exceptions in __del__ methods in library modules
(e.g. urllib).  This happens because the built-in names are already
deleted by the time __del__ is called.  The solution (a hack, but it
works) is to set some instance variables to 0 instead of None.

- The table of built-in module initializers is replaced by a pointer
variable.  This makes it possible to switch to a different table at
run time, e.g. when a collection of modules is loaded from a shared
library.  (No example code of how to do this is given, but it is
possible.)  The table is still there of course, its name prefixed with
an underscore and used to initialize the pointer.

- The warning about a thread still having a frame now only happens in
verbose mode.

- Change the signal finalization so that it also resets the signal
handlers.  After this has been called, our signal handlers are no
longer active!

- New version of tokenize.py (by Ka-Ping Yee) recognizes raw string
literals.  There's now also a test fort this module.

- The copy module now also uses __dict__.update(state) instead of
going through individual attribute assignments, for class instances
without a __setstate__ method.

- New module reconvert translates old-style (regex module) regular
expressions to new-style (re module, Perl-style) regular expressions.

- Most modules that used to use the regex module now use the re
module.  The grep module has a new pgrep() function which uses
Perl-style regular expressions.

- The (very old, backwards compatibility) regexp.py module has been
deleted.

- Restricted execution (rexec): added the pcre module (support for the
re module) to the list of trusted extension modules.

- New version of Jim Fulton's CObject object type, adds
PyCObject_FromVoidPtrAndDesc() and PyCObject_GetDesc() APIs.

- Some patches to Lee Busby's fpectl mods that accidentally didn't
make it into 1.5a4.

- In the string module, add an optional 4th argument to count(),
matching find() etc.

- Patch for the nntplib module by Charles Waldman to add optional user
and password arguments to NNTP.__init__(), for nntp servers that need
them.

- The str() function for class objects now returns
"modulename.classname" instead of returning the same as repr().

- The parsing of \xXX escapes no longer relies on sscanf().

- The "sharedmodules" subdirectory of the installation is renamed to
"lib-dynload".  (You may have to edit your Modules/Setup file to fix
this in an existing installation!)

- Fixed Don Beaudry's mess-up with the OPT test in the configure
script.  Certain SGI platforms will still issue a warning for each
compile; there's not much I can do about this since the compiler's
exit status doesn't indicate that I was using an obsolete option.

- Fixed Barry's mess-up with {}.get(), and added test cases for it.

- Shared libraries didn't quite work under AIX because of the change
in status of the GNU readline interface.  Fix due to by Vladimir
Marangozov.


======================================================================


From 1.5a3 to 1.5a4
===================

- faqwiz.py: version 0.8; Recognize https:// as URL; <html>...</html>
feature; better install instructions; removed faqmain.py (which was an
older version).

- nntplib.py: Fixed some bugs reported by Lars Wirzenius (to Debian)
about the treatment of lines starting with '.'.  Added a minimal test
function.

- struct module: ignore most whitespace in format strings.

- urllib.py: close the socket and temp file in URLopener.retrieve() so
that multiple retrievals using the same connection work.

- All standard exceptions are now classes by default; use -X to make
them strings (for backward compatibility only).

- There's a new standard exception hierarchy, defined in the standard
library module exceptions.py (which you never need to import
explicitly).  See
http://grail.cnri.reston.va.us/python/essays/stdexceptions.html for
more info.

- Three new C API functions:

  - int PyErr_GivenExceptionMatches(obj1, obj2)

    Returns 1 if obj1 and obj2 are the same object, or if obj1 is an
    instance of type obj2, or of a class derived from obj2

  - int PyErr_ExceptionMatches(obj)

    Higher level wrapper around PyErr_GivenExceptionMatches() which uses
    PyErr_Occurred() as obj1.  This will be the more commonly called
    function.

  - void PyErr_NormalizeException(typeptr, valptr, tbptr)

    Normalizes exceptions, and places the normalized values in the
    arguments.  If type is not a class, this does nothing.  If type is a
    class, then it makes sure that value is an instance of the class by:

    1. if instance is of the type, or a class derived from type, it does
       nothing.

    2. otherwise it instantiates the class, using the value as an
       argument.  If value is None, it uses an empty arg tuple, and if
       the value is a tuple, it uses just that.

- Another new C API function: PyErr_NewException() creates a new
exception class derived from Exception; when -X is given, it creates a
new string exception.

- core interpreter: remove the distinction between tuple and list
unpacking; allow an arbitrary sequence on the right hand side of any
unpack instruction.  (UNPACK_LIST and UNPACK_TUPLE now do the same
thing, which should really be called UNPACK_SEQUENCE.)

- classes: Allow assignments to an instance's __dict__ or __class__,
so you can change ivars (including shared ivars -- shock horror) and
change classes dynamically.  Also make the check on read-only
attributes of classes less draconic -- only the specials names
__dict__, __bases__, __name__ and __{get,set,del}attr__ can't be
assigned.

- Two new built-in functions: issubclass() and isinstance().  Both
take classes as their second arguments.  The former takes a class as
the first argument and returns true iff first is second, or is a
subclass of second.  The latter takes any object as the first argument
and returns true iff first is an instance of the second, or any
subclass of second.

- configure: Added configuration tests for presence of alarm(),
pause(), and getpwent().

- Doc/Makefile: changed latex2html targets.

- classes: Reverse the search order for the Don Beaudry hook so that
the first class with an applicable hook wins.  Makes more sense.

- Changed the checks made in Py_Initialize() and Py_Finalize().  It is
now legal to call these more than once.  The first call to
Py_Initialize() initializes, the first call to Py_Finalize()
finalizes.  There's also a new API, Py_IsInitialized() which checks
whether we are already initialized (in case you want to leave things
as they were).

- Completely disable the declarations for malloc(), realloc() and
free().  Any 90's C compiler has these in header files, and the tests
to decide whether to suppress the declarations kept failing on some
platforms.

- *Before* (instead of after) signalmodule.o is added, remove both
intrcheck.o and sigcheck.o.  This should get rid of warnings in ar or
ld on various systems.

- Added reop to PC/config.c

- configure: Decided to use -Aa -D_HPUX_SOURCE on HP-UX platforms.
Removed outdated HP-UX comments from README.  Added Cray T3E comments.

- Various renames of statically defined functions that had name
conflicts on some systems, e.g. strndup (GNU libc), join (Cray),
roundup (sys/types.h).

- urllib.py: Interpret three slashes in file: URL as local file (for
Netscape on Windows/Mac).

- copy.py: Make sure the objects returned by __getinitargs__() are
kept alive (in the memo) to avoid a certain kind of nasty crash.  (Not
easily reproducible because it requires a later call to
__getinitargs__() to return a tuple that happens to be allocated at
the same address.)

- Added definition of AR to toplevel Makefile.  Renamed @buildno temp
file to buildno1.

- Moved Include/assert.h to Parser/assert.h, which seems to be the
only place where it's needed.

- Tweaked the dictionary lookup code again for some more speed
(Vladimir Marangozov).

- NT build: Changed the way python15.lib is included in the other
projects.  Per Mark Hammond's suggestion, add it to the extra libs in
Settings instead of to the project's source files.

- regrtest.py: Change default verbosity so that there are only three
levels left: -q, default and -v.  In default mode, the name of each
test is now printed.  -v is the same as the old -vv.  -q is more quiet
than the old default mode.

- Removed the old FAQ from the distribution.  You now have to get it
from the web!

- Removed the PC/make_nt.in file from the distribution; it is no
longer needed.

- Changed the build sequence so that shared modules are built last.
This fixes things for AIX and doesn't hurt elsewhere.

- Improved test for GNU MP v1 in mpzmodule.c

- fileobject.c: ftell() on Linux discards all buffered data; changed
read() code to use lseek() instead to get the same effect

- configure.in, configure, importdl.c: NeXT sharedlib fixes

- tupleobject.c: PyTuple_SetItem asserts refcnt==1

- resource.c: Different strategy regarding whether to declare
getrusage() and getpagesize() -- #ifdef doesn't work, Linux has
conflicting decls in its headers.  Choice: only declare the return
type, not the argument prototype, and not on Linux.

- importdl.c, configure*: set sharedlib extensions properly for NeXT

- configure*, Makefile.in, Modules/Makefile.pre.in: AIX shared libraries
fixed; moved addition of PURIFY to LINKCC to configure

- reopmodule.c, regexmodule.c, regexpr.c, zlibmodule.c: needed casts
added to shup up various compilers.

- _tkinter.c: removed buggy mac #ifndef

- Doc: various Mac documentation changes, added docs for 'ic' module

- PC/make_nt.in: deleted

- test_time.py, test_strftime.py: tweaks to catch %Z (which may return
"")

- test_rotor.py: print b -> print `b`

- Tkinter.py: (tagOrId) -> (tagOrId,)

- Tkinter.py: the Tk class now also has a configure() method and
friends (they have been moved to the Misc class to accomplish this).

- dict.get(key[, default]) returns dict[key] if it exists, or default
if it doesn't.  The default defaults to None.  This is quicker for
some applications than using either has_key() or try:...except
KeyError:....

- Tools/webchecker/: some small changes to webchecker.py; added
websucker.py (a simple web site mirroring script).

- Dictionary objects now have a get() method (also in UserDict.py).
dict.get(key, default) returns dict[key] if it exists and default
otherwise; default defaults to None.

- Tools/scripts/logmerge.py: print the author, too.

- Changes to import: support for "import a.b.c" is now built in.  See
http://grail.cnri.reston.va.us/python/essays/packages.html
for more info.  Most important deviations from "ni.py": __init__.py is
executed in the package's namespace instead of as a submodule; and
there's no support for "__" or "__domain__".  Note that "ni.py" is not
changed to match this -- it is simply declared obsolete (while at the
same time, it is documented...:-( ).
Unfortunately, "ihooks.py" has not been upgraded (but see "knee.py"
for an example implementation of hierarchical module import written in
Python).

- More changes to import: the site.py module is now imported by
default when Python is initialized; use -S to disable it.  The site.py
module extends the path with several more directories: site-packages
inside the lib/python1.5/ directory, site-python in the lib/
directory, and pathnames mentioned in *.pth files found in either of
those directories.  See
http://grail.cnri.reston.va.us/python/essays/packages.html
for more info.

- Changes to standard library subdirectory names: those subdirectories
that are not packages have been renamed with a hypen in their name,
e.g. lib-tk, lib-stdwin, plat-win, plat-linux2, plat-sunos5, dos-8x3.
The test suite is now a package -- to run a test, you must now use
"import test.test_foo".

- A completely new re.py module is provided (thanks to Andrew
Kuchling, Tim Peters and Jeffrey Ollie) which uses Philip Hazel's
"pcre" re compiler and engine.  For a while, the "old" re.py (which
was new in 1.5a3!) will be kept around as re1.py.  The "old" regex
module and underlying parser and engine are still present -- while
regex is now officially obsolete, it will probably take several major
release cycles before it can be removed.

- The posix module now has a strerror() function which translates an
error code to a string.

- The emacs.py module (which was long obsolete) has been removed.

- The universal makefile Misc/Makefile.pre.in now features an
"install" target.  By default, installed shared libraries go into
$exec_prefix/lib/python$VERSION/site-packages/.

- The install-sh script is installed with the other configuration
specific files (in the config/ subdirectory).

- It turns out whatsound.py and sndhdr.py were identical modules.
Since there's also an imghdr.py file, I propose to make sndhdr.py the
official one.  For compatibility, whatsound.py imports * from
sndhdr.py.

- Class objects have a new attribute, __module__, giving the name of
the module in which they were declared.  This is useful for pickle and
for printing the full name of a class exception.

- Many extension modules no longer issue a fatal error when their
initialization fails; the importing code now checks whether an error
occurred during module initialization, and correctly propagates the
exception to the import statement.

- Most extension modules now raise class-based exceptions (except when
-X is used).

- Subtle changes to PyEval_{Save,Restore}Thread(): always swap the
thread state -- just don't manipulate the lock if it isn't there.

- Fixed a bug in Python/getopt.c that made it do the wrong thing when
an option was a single '-'.  Thanks to Andrew Kuchling.

- New module mimetypes.py will guess a MIME type from a filename's
extension.

- Windows: the DLL version is now settable via a resource rather than
being hardcoded.  This can be used for "branding" a binary Python
distribution.

- urllib.py is now threadsafe -- it now uses re instead of regex, and
sys.exc_info() instead of sys.exc_{type,value}.

- Many other library modules that used to use
sys.exc_{type,value,traceback} are now more thread-safe by virtue of
using sys.exc_info().

- The functions in popen2 have an optional buffer size parameter.
Also, the command argument can now be either a string (passed to the
shell) or a list of arguments (passed directly to execv).

- Alas, the thread support for _tkinter released with 1.5a3 didn't
work.  It's been rewritten.  The bad news is that it now requires a
modified version of a file in the standard Tcl distribution, which you
must compile with a -I option pointing to the standard Tcl source
tree.  For this reason, the thread support is disabled by default.

- The errno extension module adds two tables: errorcode maps errno
numbers to errno names (e.g. EINTR), and errorstr maps them to
message strings.  (The latter is redundant because the new call
posix.strerror() now does the same, but alla...)  (Marc-Andre Lemburg)

- The readline extension module now provides some interfaces to
internal readline routines that make it possible to write a completer
in Python.  An example completer, rlcompleter.py, is provided.

	When completing a simple identifier, it completes keywords,
	built-ins and globals in __main__; when completing
	NAME.NAME..., it evaluates (!) the expression up to the last
	dot and completes its attributes.

	It's very cool to do "import string" type "string.", hit the
	completion key (twice), and see the list of names defined by
	the string module!

	Tip: to use the tab key as the completion key, call

	    readline.parse_and_bind("tab: complete")

- The traceback.py module has a new function tb_lineno() by Marc-Andre
Lemburg which extracts the line number from the linenumber table in
the code object.  Apparently the traceback object doesn't contain the
right linenumber when -O is used.  Rather than guessing whether -O is
on or off, the module itself uses tb_lineno() unconditionally.

- Fixed Demo/tkinter/matt/canvas-moving-or-creating.py: change bind()
to tag_bind() so it works again.

- The pystone script is now a standard library module.  Example use:
"import test.pystone; test.pystone.main()".

- The import of the readline module in interactive mode is now also
attempted when -i is specified.  (Yes, I know, giving in to Marc-Andre
Lemburg, who asked for this. :-)

- rfc822.py: Entirely rewritten parseaddr() function by Sjoerd
Mullender, to be closer to the standard.  This fixes the getaddr()
method.  Unfortunately, getaddrlist() is as broken as ever, since it
splits on commas without regard for RFC 822 quoting conventions.

- pprint.py: correctly emit trailing "," in singleton tuples.

- _tkinter.c: export names for its type objects, TkappType and
TkttType.

- pickle.py: use __module__ when defined; fix a particularly hard to
reproduce bug that confuses the memo when temporary objects are
returned by custom pickling interfaces; and a semantic change: when
unpickling the instance variables of an instance, use
inst.__dict__.update(value) instead of a for loop with setattr() over
the value.keys().  This is more consistent (the pickling doesn't use
getattr() either but pickles inst.__dict__) and avoids problems with
instances that have a __setattr__ hook.  But it *is* a semantic change
(because the setattr hook is no longer used).  So beware!

- config.h is now installed (at last) in
$exec_prefix/include/python1.5/.  For most sites, this means that it
is actually in $prefix/include/python1.5/, with all the other Python
include files, since $prefix and $exec_prefix are the same by
default.

- The imp module now supports parts of the functionality to implement
import of hierarchical module names.  It now supports find_module()
and load_module() for all types of modules.  Docstrings have been
added for those functions in the built-in imp module that are still
relevant (some old interfaces are obsolete).  For a sample
implementation of hierarchical module import in Python, see the new
library module knee.py.

- The % operator on string objects now allows arbitrary nested parens
in a %(...)X style format.  (Brad Howes)

- Reverse the order in which Setup and Setup.local are passed to the
makesetup script.  This allows variable definitions in Setup.local to
override definitions in Setup.  (But you'll still have to edit Setup
if you want to disable modules that are enabled by default, or if such
modules need non-standard options.)

- Added PyImport_ImportModuleEx(name, globals, locals, fromlist); this
is like PyImport_ImporModule(name) but receives the globals and locals
dict and the fromlist arguments as well.  (The name is a char*; the
others are PyObject*s).

- The 'p' format in the struct extension module alloded to above is
new in 1.5a4.

- The types.py module now uses try-except in a few places to make it
more likely that it can be imported in restricted mode.  Some type
names are undefined in that case, e.g. CodeType (inaccessible),
FileType (not always accessible), and TracebackType and FrameType
(inaccessible).

- In urllib.py: added separate administration of temporary files
created y URLopener.retrieve() so cleanup() can properly remove them.
The old code removed everything in tempcache which was a bad idea if
the user had passed a non-temp file into it.  Also, in basejoin(),
interpret relative paths starting in "../".  This is necessary if the
server uses symbolic links.

- The Windows build procedure and project files are now based on
Microsoft Visual C++ 5.x.  The build now takes place in the PCbuild
directory.  It is much more robust, and properly builds separate Debug
and Release versions.  (The installer will be added shortly.)

- Added casts and changed some return types in regexpr.c to avoid
compiler warnings or errors on some platforms.

- The AIX build tools for shared libraries now supports VPATH.  (Donn
Cave)

- By default, disable the "portable" multimedia modules audioop,
imageop, and rgbimg, since they don't work on 64-bit platforms.

- Fixed a nasty bug in cStringIO.c when code was actually using the
close() method (the destructors would try to free certain fields a
second time).

- For those who think they need it, there's a "user.py" module.  This
is *not* imported by default, but can be imported to run user-specific
setup commands, ~/.pythonrc.py.

- Various speedups suggested by Fredrik Lundh, Marc-Andre Lemburg,
Vladimir Marangozov, and others.

- Added os.altsep; this is '/' on DOS/Windows, and None on systems
with a sane filename syntax.

- os.py: Write out the dynamic OS choice, to avoid exec statements.
Adding support for a new OS is now a bit more work, but I bet that
'dos' or 'nt' will cover most situations...

- The obsolete exception AccessError is now really gone.

- Tools/faqwiz/: New installation instructions show how to maintain
multiple FAQs.  Removed bootstrap script from end of faqwiz.py module.
Added instructions to bootstrap script, too.  Version bumped to 0.8.1.
Added <html>...</html> feature suggested by Skip Montanaro.  Added
leading text for Roulette, default to 'Hit Reload ...'.  Fix typo in
default SRCDIR.

- Documentation for the relatively new modules "keyword" and "symbol"
has been added (to the end of the section on the parser extension
module).

- In module bisect.py, but functions have two optional argument 'lo'
and 'hi' which allow you to specify a subsequence of the array to
operate on.

- In ftplib.py, changed most methods to return their status (even when
it is always "200 OK") rather than swallowing it.

- main() now calls setlocale(LC_ALL, ""), if setlocale() and
<locale.h> are defined.

- Changes to configure.in, the configure script, and both
Makefile.pre.in files, to support SGI's SGI_ABI platform selection
environment variable.


======================================================================


From 1.4 to 1.5a3
=================

Security
--------

- If you are using the setuid script C wrapper (Misc/setuid-prog.c),
please use the new version.  The old version has a huge security leak.

Miscellaneous
-------------

- Because of various (small) incompatible changes in the Python
bytecode interpreter, the magic number for .pyc files has changed
again.

- The default module search path is now much saner.  Both on Unix and
Windows, it is essentially derived from the path to the executable
(which can be overridden by setting the environment variable
$PYTHONHOME).  The value of $PYTHONPATH on Windows is now inserted in
front of the default path, like in Unix (instead of overriding the
default path).  On Windows, the directory containing the executable is
added to the end of the path.

- A new version of python-mode.el for Emacs has been included.  Also,
a new file ccpy-style.el has been added to configure Emacs cc-mode for
the preferred style in Python C sources.

- On Unix, when using sys.argv[0] to insert the script directory in
front of sys.path, expand a symbolic link.  You can now install a
program in a private directory and have a symbolic link to it in a
public bin directory, and it will put the private directory in the
module search path.  Note that the symlink is expanded in sys.path[0]
but not in sys.argv[0], so you can still tell the name by which you
were invoked.

- It is now recommended to use ``#!/usr/bin/env python'' instead of
``#!/usr/local/bin/python'' at the start of executable scripts, except
for CGI scripts.  It has been determined that the use of /usr/bin/env
is more portable than that of /usr/local/bin/python -- scripts almost
never have to be edited when the Python interpreter lives in a
non-standard place.  Note that this doesn't work for CGI scripts since
the python executable often doesn't live in the HTTP server's default
search path.

- The silly -s command line option and the corresponding
PYTHONSUPPRESS environment variable (and the Py_SuppressPrint global
flag in the Python/C API) are gone.

- Most problems on 64-bit platforms should now be fixed.  Andrew
Kuchling helped.  Some uncommon extension modules are still not
clean (image and audio ops?).

- Fixed a bug where multiple anonymous tuple arguments would be mixed up
when using the debugger or profiler (reported by Just van Rossum).
The simplest example is ``def f((a,b),(c,d)): print a,b,c,d''; this
would print the wrong value when run under the debugger or profiler.

- The hacks that the dictionary implementation used to speed up
repeated lookups of the same C string were removed; these were a
source of subtle problems and don't seem to serve much of a purpose
any longer.

- All traces of support for the long dead access statement have been
removed from the sources.

- Plugged the two-byte memory leak in the tokenizer when reading an
interactive EOF.

- There's a -O option to the interpreter that removes SET_LINENO
instructions and assert statements (see below); it uses and produces
.pyo files instead of .pyc files.  The speedup is only a few percent
in most cases.  The line numbers are still available in the .pyo file,
as a separate table (which is also available in .pyc files).  However,
the removal of the SET_LINENO instructions means that the debugger
(pdb) can't set breakpoints on lines in -O mode.  The traceback module
contains a function to extract a line number from the code object
referenced in a traceback object.  In the future it should be possible
to write external bytecode optimizers that create better optimized
.pyo files, and there should be more control over optimization;
consider the -O option a "teaser".  Without -O, the assert statement
actually generates code that first checks __debug__; if this variable
is false, the assertion is not checked.  __debug__ is a built-in
variable whose value is initialized to track the -O flag (it's true
iff -O is not specified).  With -O, no code is generated for assert
statements, nor for code of the form ``if __debug__: <something>''.
Sorry, no further constant folding happens.


Performance
-----------

- It's much faster (almost twice for pystone.py -- see
Tools/scripts).  See the entry on string interning below.

- Some speedup by using separate free lists for method objects (both
the C and the Python variety) and for floating point numbers.

- Big speedup by allocating frame objects with a single malloc() call.
The Python/C API for frames is changed (you shouldn't be using this
anyway).

- Significant speedup by inlining some common opcodes for common operand 
types (e.g.  i+i, i-i, and list[i]).  Fredrik Lundh.

- Small speedup by reordering the method tables of some common
objects (e.g. list.append is now first).

- Big optimization to the read() method of file objects.  A read()
without arguments now attempts to use fstat to allocate a buffer of
the right size; for pipes and sockets, it will fall back to doubling
the buffer size.  While that the improvement is real on all systems,
it is most dramatic on Windows.


Documentation
-------------

- Many new pieces of library documentation were contributed, mostly by
Andrew Kuchling.  Even cmath is now documented!  There's also a
chapter of the library manual, "libundoc.tex", which provides a
listing of all undocumented modules, plus their status (e.g. internal,
obsolete, or in need of documentation).  Also contributions by Sue
Williams, Skip Montanaro, and some module authors who succumbed to
pressure to document their own contributed modules :-).  Note that
printing the documentation now kills fewer trees -- the margins have
been reduced.

- I have started documenting the Python/C API. Unfortunately this project 
hasn't been completed yet.  It will be complete before the final release of 
Python 1.5, though.  At the moment, it's better to read the LaTeX source 
than to attempt to run it through LaTeX and print the resulting dvi file.

- The posix module (and hence os.py) now has doc strings!  Thanks to Neil 
Schemenauer.  I received a few other contributions of doc strings.  In most 
other places, doc strings are still wishful thinking...


Language changes
----------------

- Private variables with leading double underscore are now a permanent 
feature of the language.  (These were experimental in release 1.4.  I have 
favorable experience using them; I can't label them "experimental" 
forever.)

- There's new string literal syntax for "raw strings".  Prefixing a string 
literal with the letter r (or R) disables all escape processing in the 
string; for example, r'\n' is a two-character string consisting of a 
backslash followed by the letter n.  This combines with all forms of string 
quotes; it is actually useful for triple quoted doc strings which might 
contain references to \n or \t.  An embedded quote prefixed with a 
backslash does not terminate the string, but the backslash is still 
included in the string; for example, r'\'' is a two-character string 
consisting of a backslash and a quote.  (Raw strings are also 
affectionately known as Robin strings, after their inventor, Robin 
Friedrich.)

- There's a simple assert statement, and a new exception
AssertionError.  For example, ``assert foo > 0'' is equivalent to ``if
not foo > 0: raise AssertionError''.  Sorry, the text of the asserted
condition is not available; it would be too complicated to generate
code for this (since the code is generated from a parse tree).
However, the text is displayed as part of the traceback!

- The raise statement has a new feature: when using "raise SomeClass,
somevalue" where somevalue is not an instance of SomeClass, it
instantiates SomeClass(somevalue).  In 1.5a4, if somevalue is an
instance of a *derived* class of SomeClass, the exception class raised
is set to somevalue.__class__, and SomeClass is ignored after that.

- Duplicate keyword arguments are now detected at compile time;
f(a=1,a=2) is now a syntax error.


Changes to built-in features
----------------------------

- There's a new exception FloatingPointError (used only by Lee Busby's
patches to catch floating point exceptions, at the moment).

- The obsolete exception ConflictError (presumably used by the long
obsolete access statement) has been deleted.

- There's a new function sys.exc_info() which returns the tuple 
(sys.exc_type, sys.exc_value, sys.exc_traceback) in a thread-safe way.

- There's a new variable sys.executable, pointing to the executable file 
for the Python interpreter.

- The sort() methods for lists no longer uses the C library qsort(); I
wrote my own quicksort implementation, with lots of help (in the form
of a kind of competition) from Tim Peters.  This solves a bug in
dictionary comparisons on some Solaris versions when Python is built
with threads, and makes sorting lists even faster.

- The semantics of comparing two dictionaries have changed, to make
comparison of unequal dictionaries faster.  A shorter dictionary is
always considered smaller than a larger dictionary.  For dictionaries
of the same size, the smallest differing element determines the
outcome (which yields the same results as before in this case, without
explicit sorting).  Thanks to Aaron Watters for suggesting something
like this.

- The semantics of try-except have changed subtly so that calling a
function in an exception handler that itself raises and catches an
exception no longer overwrites the sys.exc_* variables.  This also
alleviates the problem that objects referenced in a stack frame that
caught an exception are kept alive until another exception is caught
-- the sys.exc_* variables are restored to their previous value when
returning from a function that caught an exception.

- There's a new "buffer" interface.  Certain objects (e.g. strings and
arrays) now support the "buffer" protocol.  Buffer objects are acceptable 
whenever formerly a string was required for a write operation; mutable 
buffer objects can be the target of a read operation using the call
f.readinto(buffer).  A cool feature is that regular expression matching now 
also work on array objects.  Contribution by Jack Jansen.  (Needs 
documentation.)

- String interning: dictionary lookups are faster when the lookup
string object is the same object as the key in the dictionary, not
just a string with the same value.  This is done by having a pool of
"interned" strings.  Most names generated by the interpreter are now
automatically interned, and there's a new built-in function intern(s)
that returns the interned version of a string.  Interned strings are
not a different object type, and interning is totally optional, but by
interning most keys a speedup of about 15% was obtained for the
pystone benchmark.

- Dictionary objects have several new methods; clear() and copy() have
the obvious semantics, while update(d) merges the contents of another
dictionary d into this one, overriding existing keys.  The dictionary
implementation file is now called dictobject.c rather than the
confusing mappingobject.c.

- The intrinsic function dir() is much smarter; it looks in __dict__,
__members__ and __methods__.

- The intrinsic functions int(), long() and float() can now take a
string argument and then do the same thing as string.atoi(),
string.atol(), and string.atof().  No second 'base' argument is
allowed, and complex() does not take a string (nobody cared enough).

- When a module is deleted, its globals are now deleted in two phases.
In the first phase, all variables whose name begins with exactly one
underscore are replaced by None; in the second phase, all variables
are deleted.  This makes it possible to have global objects whose
destructors depend on other globals.  The deletion order within each
phase is still random.

- It is no longer an error for a function to be called without a
global variable __builtins__ -- an empty directory will be provided
by default.

- Guido's corollary to the "Don Beaudry hook": it is now possible to
do metaprogramming by using an instance as a base class.  Not for the
faint of heart; and undocumented as yet, but basically if a base class
is an instance, its class will be instantiated to create the new
class.  Jim Fulton will love it -- it also works with instances of his
"extension classes", since it is triggered by the presence of a
__class__ attribute on the purported base class.  See
Demo/metaclasses/index.html for an explanation and see that directory
for examples.

- Another change is that the Don Beaudry hook is now invoked when
*any* base class is special.  (Up to 1.5a3, the *last* special base
class is used; in 1.5a4, the more rational choice of the *first*
special base class is used.)

- New optional parameter to the readlines() method of file objects.
This indicates the number of bytes to read (the actual number of bytes
read will be somewhat larger due to buffering reading until the end of
the line).  Some optimizations have also been made to speed it up (but
not as much as read()).

- Complex numbers no longer have the ".conj" pseudo attribute; use
z.conjugate() instead, or complex(z.real, -z.imag).  Complex numbers
now *do* support the __members__ and __methods__ special attributes.

- The complex() function now looks for a __complex__() method on class
instances before giving up.

- Long integers now support arbitrary shift counts, so you can now
write 1L<<1000000, memory permitting.  (Python 1.4 reports "outrageous
shift count for this.)

- The hex() and oct() functions have been changed so that for regular
integers, they never emit a minus sign.  For example, on a 32-bit
machine, oct(-1) now returns '037777777777' and hex(-1) returns
'0xffffffff'.  While this may seem inconsistent, it is much more
useful.  (For long integers, a minus sign is used as before, to fit
the result in memory :-)

- The hash() function computes better hashes for several data types,
including strings, floating point numbers, and complex numbers.


New extension modules
---------------------

- New extension modules cStringIO.c and cPickle.c, written by Jim
Fulton and other folks at Digital Creations.  These are much more
efficient than their Python counterparts StringIO.py and pickle.py,
but don't support subclassing.  cPickle.c clocks up to 1000 times
faster than pickle.py; cStringIO.c's improvement is less dramatic but
still significant.

- New extension module zlibmodule.c, interfacing to the free zlib
library (gzip compatible compression).  There's also a module gzip.py
which provides a higher level interface.  Written by Andrew Kuchling
and Jeremy Hylton.

- New module readline; see the "miscellaneous" section above.

- New Unix extension module resource.c, by Jeremy Hylton, provides
access to getrlimit(), getrusage(), setrusage(), getpagesize(), and
related symbolic constants.

- New extension puremodule.c, by Barry Warsaw, which interfaces to the
Purify(TM) C API.  See also the file Misc/PURIFY.README.  It is also
possible to enable Purify by simply setting the PURIFY Makefile
variable in the Modules/Setup file.


Changes in extension modules
----------------------------

- The struct extension module has several new features to control byte
order and word size.  It supports reading and writing IEEE floats even
on platforms where this is not the native format.  It uses uppercase
format codes for unsigned integers of various sizes (always using
Python long ints for 'I' and 'L'), 's' with a size prefix for strings,
and 'p' for "Pascal strings" (with a leading length byte, included in
the size; blame Hannu Krosing; new in 1.5a4).  A prefix '>' forces
big-endian data and '<' forces little-endian data; these also select
standard data sizes and disable automatic alignment (use pad bytes as
needed).

- The array module supports uppercase format codes for unsigned data
formats (like the struct module).

- The fcntl extension module now exports the needed symbolic
constants.  (Formerly these were in FCNTL.py which was not available
or correct for all platforms.)

- The extension modules dbm, gdbm and bsddb now check that the
database is still open before making any new calls.

- The dbhash module is no more.  Use bsddb instead.  (There's a third
party interface for the BSD 2.x code somewhere on the web; support for
bsddb will be deprecated.)

- The gdbm module now supports a sync() method.

- The socket module now has some new functions: getprotobyname(), and
the set {ntoh,hton}{s,l}().

- Various modules now export their type object: socket.SocketType,
array.ArrayType.

- The socket module's accept() method now returns unknown addresses as
a tuple rather than raising an exception.  (This can happen in
promiscuous mode.)  Theres' also a new function getprotobyname().

- The pthread support for the thread module now works on most platforms.

- STDWIN is now officially obsolete.  Support for it will eventually
be removed from the distribution.

- The binascii extension module is now hopefully fully debugged.
(XXX Oops -- Fredrik Lundh promised me a uuencode fix that I never
received.)

- audioop.c: added a ratecv() function; better handling of overflow in
add().

- posixmodule.c: now exports the O_* flags (O_APPEND etc.).  On
Windows, also O_TEXT and O_BINARY.  The 'error' variable (the
exception is raises) is renamed -- its string value is now "os.error",
so newbies don't believe they have to import posix (or nt) to catch
it when they see os.error reported as posix.error.  The execve()
function now accepts any mapping object for the environment.

- A new version of the al (audio library) module for SGI was
contributed by Sjoerd Mullender.

- The regex module has a new function get_syntax() which retrieves the
syntax setting set by set_syntax().  The code was also sanitized,
removing worries about unclean error handling.  See also below for its
successor, re.py.

- The "new" module (which creates new objects of various types) once
again has a fully functioning new.function() method.  Dangerous as
ever!  Also, new.code() has several new arguments.

- A problem has been fixed in the rotor module: on systems with signed
characters, rotor-encoded data was not portable when the key contained
8-bit characters.  Also, setkey() now requires its argument rather
than having broken code to default it.

- The sys.builtin_module_names variable is now a tuple.  Another new
variables in sys is sys.executable (the full path to the Python
binary, if known).

- The specs for time.strftime() have undergone some revisions.  It
appears that not all format characters are supported in the same way
on all platforms.  Rather than reimplement it, we note these
differences in the documentation, and emphasize the shared set of
features.  There's also a thorough test set (that occasionally finds
problems in the C library implementation, e.g. on some Linuxes),
thanks to Skip Montanaro.

- The nis module seems broken when used with NIS+; unfortunately
nobody knows how to fix it.  It should still work with old NIS.


New library modules
-------------------

- New (still experimental) Perl-style regular expression module,
re.py, which uses a new interface for matching as well as a new
syntax; the new interface avoids the thread-unsafety of the regex
interface.  This comes with a helper extension reopmodule.c and vastly
rewritten regexpr.c.  Most work on this was done by Jeffrey Ollie, Tim
Peters, and Andrew Kuchling.  See the documentation libre.tex.  In
1.5, the old regex module is still fully supported; in the future, it
will become obsolete.

- New module gzip.py; see zlib above.

- New module keyword.py exports knowledge about Python's built-in
keywords.  (New version by Ka-Ping Yee.)

- New module pprint.py (with documentation) which supports
pretty-printing of lists, tuples, & dictionaries recursively.  By Fred
Drake.

- New module code.py.  The function code.compile_command() can
determine whether an interactively entered command is complete or not,
distinguishing incomplete from invalid input.  (XXX Unfortunately,
this seems broken at this moment, and I don't have the time to fix
it.  It's probably better to add an explicit interface to the parser
for this.)

- There is now a library module xdrlib.py which can read and write the
XDR data format as used by Sun RPC, for example.  It uses the struct
module.


Changes in library modules
--------------------------

- Module codehack.py is now completely obsolete.

- The pickle.py module has been updated to make it compatible with the
new binary format that cPickle.c produces.  By default it produces the
old all-ASCII format compatible with the old pickle.py, still much
faster than pickle.py; it will read both formats automatically.  A few
other updates have been made.

- A new helper module, copy_reg.py, is provided to register extensions
to the pickling code.

- Revamped module tokenize.py is much more accurate and has an
interface that makes it a breeze to write code to colorize Python
source code.  Contributed by Ka-Ping Yee.

- In ihooks.py, ModuleLoader.load_module() now closes the file under
all circumstances.

- The tempfile.py module has a new class, TemporaryFile, which creates
an open temporary file that will be deleted automatically when
closed.  This works on Windows and MacOS as well as on Unix.  (Jim
Fulton.)

- Changes to the cgi.py module: Most imports are now done at the
top of the module, which provides a speedup when using ni (Jim
Fulton).  The problem with file upload to a Windows platform is solved
by using the new tempfile.TemporaryFile class; temporary files are now
always opened in binary mode (Jim Fulton).  The cgi.escape() function
now takes an optional flag argument that quotes '"' to '&quot;'.  It
is now possible to invoke cgi.py from a command line script, to test
cgi scripts more easily outside an http server.  There's an optional
limit to the size of uploads to POST (Skip Montanaro).  Added a
'strict_parsing' option to all parsing functions (Jim Fulton).  The
function parse_qs() now uses urllib.unquote() on the name as well as
the value of fields (Clarence Gardner).  The FieldStorage class now
has a __len__() method.

- httplib.py: the socket object is no longer closed; all HTTP/1.*
responses are now accepted; and it is now thread-safe (by not using
the regex module).

- BaseHTTPModule.py: treat all HTTP/1.* versions the same.

- The popen2.py module is now rewritten using a class, which makes
access to the standard error stream and the process id of the
subprocess possible.

- Added timezone support to the rfc822.py module, in the form of a
getdate_tz() method and a parsedate_tz() function; also a mktime_tz().
Also added recognition of some non-standard date formats, by Lars
Wirzenius, and RFC 850 dates (Chris Lawrence).

- mhlib.py: various enhancements, including almost compatible parsing
of message sequence specifiers without invoking a subprocess.  Also
added a createmessage() method by Lars Wirzenius.

- The StringIO.StringIO class now supports readline(nbytes).  (Lars 
Wirzenius.)  (Of course, you should be using cStringIO for performance.)

- UserDict.py supports the new dictionary methods as well.

- Improvements for whrandom.py by Tim Peters: use 32-bit arithmetic to
speed it up, and replace 0 seed values by 1 to avoid degeneration.
A bug was fixed in the test for invalid arguments.

- Module ftplib.py: added support for parsing a .netrc file (Fred
Drake).  Also added an ntransfercmd() method to the FTP class, which
allows access to the expected size of a transfer when available, and a
parse150() function to the module which parses the corresponding 150
response.

- urllib.py: the ftp cache is now limited to 10 entries.  Added
quote_plus() and unquote_plus() functions which are like quote() and
unquote() but also replace spaces with '+' or vice versa, for
encoding/decoding CGI form arguments.  Catch all errors from the ftp
module.  HTTP requests now add the Host: header line.  The proxy
variable names are now mapped to lower case, for Windows.  The
spliturl() function no longer erroneously throws away all data past
the first newline.  The basejoin() function now intereprets "../"
correctly.  I *believe* that the problems with "exception raised in
__del__" under certain circumstances have been fixed (mostly by
changes elsewher in the interpreter).

- In urlparse.py, there is a cache for results in urlparse.urlparse();
its size limit is set to 20.  Also, new URL schemes shttp, https, and
snews are "supported".

- shelve.py: use cPickle and cStringIO when available.  Also added
a sync() method, which calls the database's sync() method if there is
one.

- The mimetools.py module now uses the available Python modules for
decoding quoted-printable, uuencode and base64 formats, rather than
creating a subprocess.

- The python debugger (pdb.py, and its base class bdb.py) now support
conditional breakpoints.  See the docs.

- The modules base64.py, uu.py and quopri.py can now be used as simple
command line utilities.

- Various small fixes to the nntplib.py module that I can't bother to
document in detail.

- Sjoerd Mullender's mimify.py module now supports base64 encoding and 
includes functions to handle the funny encoding you sometimes see in mail 
headers.  It is now documented.

- mailbox.py: Added BabylMailbox.  Improved the way the mailbox is
gotten from the environment.

- Many more modules now correctly open files in binary mode when this
is necessary on non-Unix platforms.

- The copying functions in the undocumented module shutil.py are
smarter.

- The Writer classes in the formatter.py module now have a flush()
method.

- The sgmllib.py module accepts hyphens and periods in the middle of
attribute names.  While this is against the SGML standard, there is
some HTML out there that uses this...

- The interface for the Python bytecode disassembler module, dis.py,
has been enhanced quite a bit.  There's now one main function,
dis.dis(), which takes almost any kind of object (function, module,
class, instance, method, code object) and disassembles it; without
arguments it disassembles the last frame of the last traceback.  The
other functions have changed slightly, too.

- The imghdr.py module recognizes new image types: BMP, PNG.

- The string.py module has a new function replace(str, old, new,
[maxsplit]) which does substring replacements.  It is actually
implemented in C in the strop module.  The functions [r]find() an
[r]index() have an optional 4th argument indicating the end of the
substring to search, alsoo implemented by their strop counterparts.
(Remember, never import strop -- import string uses strop when
available with zero overhead.)

- The string.join() function now accepts any sequence argument, not
just lists and tuples.

- The string.maketrans() requires its first two arguments to be
present.  The old version didn't require them, but there's not much
point without them, and the documentation suggests that they are
required, so we fixed the code to match the documentation.

- The regsub.py module has a function clear_cache(), which clears its
internal cache of compiled regular expressions.  Also, the cache now
takes the current syntax setting into account.  (However, this module
is now obsolete -- use the sub() or subn() functions or methods in the
re module.)

- The undocumented module Complex.py has been removed, now that Python
has built-in complex numbers.  A similar module remains as
Demo/classes/Complex.py, as an example.


Changes to the build process
----------------------------

- The way GNU readline is configured is totally different.  The
--with-readline configure option is gone.  It is now an extension
module, which may be loaded dynamically.  You must enable it (and
specify the correct libraries to link with) in the Modules/Setup file.
Importing the module installs some hooks which enable command line
editing.  When the interpreter shell is invoked interactively, it
attempts to import the readline module; when this fails, the default
input mechanism is used.  The hook variables are PyOS_InputHook and
PyOS_ReadlineFunctionPointer.  (Code contributed by Lee Busby, with
ideas from William Magro.)

- New build procedure: a single library, libpython1.5.a, is now built,
which contains absolutely everything except for a one-line main()
program (which calls Py_Main(argc, argv) to start the interpreter
shell).  This makes life much simpler for applications that need to
embed Python.  The serial number of the build is now included in the
version string (sys.version).

- As far as I can tell, neither gcc -Wall nor the Microsoft compiler
emits a single warning any more when compiling Python.

- A number of new Makefile variables have been added for special
situations, e.g. LDLAST is appended to the link command.  These are
used by editing the Makefile or passing them on the make command
line.

- A set of patches from Lee Busby has been integrated that make it
possible to catch floating point exceptions.  Use the configure option
--with-fpectl to enable the patches; the extension modules fpectl and
fpetest provide control to enable/disable and test the feature,
respectively.

- The support for shared libraries under AIX is now simpler and more
robust.  Thanks to Vladimir Marangozov for revamping his own patches!

- The Modules/makesetup script now reads a file Setup.local as well as
a file Setup.  Most changes to the Setup script can be done by editing
Setup.local instead, which makes it easier to carry a particular setup
over from one release to the next.

- The Modules/makesetup script now copies any "include" lines it
encounters verbatim into the output Makefile.  It also recognizes .cxx
and .cpp as C++ source files.

- The configure script is smarter about C compiler options; e.g. with
gcc it uses -O2 and -g when possible, and on some other platforms it
uses -Olimit 1500 to avoid a warning from the optimizer about the main
loop in ceval.c (which has more than 1000 basic blocks).

- The configure script now detects whether malloc(0) returns a NULL
pointer or a valid block (of length zero).  This avoids the nonsense
of always adding one byte to all malloc() arguments on most platforms.

- The configure script has a new option, --with-dec-threads, to enable
DEC threads on DEC Alpha platforms.  Also, --with-threads is now an
alias for --with-thread (this was the Most Common Typo in configure
arguments).

- Many changes in Doc/Makefile; amongst others, latex2html is now used
to generate HTML from all latex documents.


Change to the Python/C API
--------------------------

- Because some interfaces have changed, the PYTHON_API macro has been
bumped.  Most extensions built for the old API version will still run,
but I can't guarantee this.  Python prints a warning message on
version mismatches; it dumps core when the version mismatch causes a
serious problem :-)

- I've completed the Grand Renaming, with the help of Roger Masse and
Barry Warsaw.  This makes reading or debugging the code much easier.
Many other unrelated code reorganizations have also been carried out.
The allobjects.h header file is gone; instead, you would have to
include Python.h followed by rename2.h.  But you're better off running
Tools/scripts/fixcid.py -s Misc/RENAME on your source, so you can omit
the rename2.h; it will disappear in the next release.

- Various and sundry small bugs in the "abstract" interfaces have been
fixed.  Thanks to all the (involuntary) testers of the Python 1.4
version!  Some new functions have been added, e.g. PySequence_List(o),
equivalent to list(o) in Python.

- New API functions PyLong_FromUnsignedLong() and
PyLong_AsUnsignedLong().

- The API functions in the file cgensupport.c are no longer
supported.  This file has been moved to Modules and is only ever
compiled when the SGI specific 'gl' module is built.

- PyObject_Compare() can now raise an exception.  Check with
PyErr_Occurred().  The comparison function in an object type may also
raise an exception.

- The slice interface uses an upper bound of INT_MAX when no explicit
upper bound is given (e.x. for a[1:]).  It used to ask the object for
its length and do the calculations.

- Support for multiple independent interpreters.  See Doc/api.tex,
functions Py_NewInterpreter() and Py_EndInterpreter().  Since the
documentation is incomplete, also see the new Demo/pysvr example
(which shows how to use these in a threaded application) and the
source code.

- There is now a Py_Finalize() function which "de-initializes"
Python.  It is possible to completely restart the interpreter
repeatedly by calling Py_Finalize() followed by Py_Initialize().  A
change of functionality in Py_Initialize() means that it is now a
fatal error to call it while the interpreter is already initialized.
The old, half-hearted Py_Cleanup() routine is gone.  Use of Py_Exit()
is deprecated (it is nothing more than Py_Finalize() followed by
exit()).

- There are no known memory leaks left.  While Py_Finalize() doesn't
free *all* allocated memory (some of it is hard to track down),
repeated calls to Py_Finalize() and Py_Initialize() do not create
unaccessible heap blocks.

- There is now explicit per-thread state.  (Inspired by, but not the
same as, Greg Stein's free threading patches.)

- There is now better support for threading C applications.  There are
now explicit APIs to manipulate the interpreter lock.  Read the source
or the Demo/pysvr example; the new functions are
PyEval_{Acquire,Release}{Lock,Thread}().

- The test macro DEBUG has changed to Py_DEBUG, to avoid interference
with other libraries' DEBUG macros.  Likewise for any other test
macros that didn't yet start with Py_.

- New wrappers around malloc() and friends: Py_Malloc() etc. call
malloc() and call PyErr_NoMemory() when it fails; PyMem_Malloc() call
just malloc().  Use of these wrappers could be essential if multiple
memory allocators exist (e.g. when using certain DLL setups under
Windows).  (Idea by Jim Fulton.)

- New C API PyImport_Import() which uses whatever __import__() hook
that is installed for the current execution environment.  By Jim
Fulton.

- It is now possible for an extension module's init function to fail
non-fatally, by calling one of the PyErr_* functions and returning.

- The PyInt_AS_LONG() and PyFloat_AS_DOUBLE() macros now cast their
argument to the proper type, like the similar PyString macros already
did.  (Suggestion by Marc-Andre Lemburg.)  Similar for PyList_GET_SIZE
and PyList_GET_ITEM.

- Some of the Py_Get* function, like Py_GetVersion() (but not yet
Py_GetPath()) are now declared as returning a const char *.  (More
should follow.)

- Changed the run-time library to check for exceptions after object
comparisons.  PyObject_Compare() can now return an exception; use
PyErr_Occurred() to check (there is *no* special return value).

- PyFile_WriteString() and Py_Flushline() now return error indicators
instead of clearing exceptions.  This fixes an obscure bug where using
these would clear a pending exception, discovered by Just van Rossum.

- There's a new function, PyArg_ParseTupleAndKeywords(), which parses
an argument list including keyword arguments.  Contributed by Geoff
Philbrick.

- PyArg_GetInt() is gone.

- It's no longer necessary to include graminit.h when calling one of
the extended parser API functions.  The three public grammar start
symbols are now in Python.h as Py_single_input, Py_file_input, and
Py_eval_input.

- The CObject interface has a new function,
PyCObject_Import(module, name).  It calls PyCObject_AsVoidPtr()
on the object referenced by "module.name".


Tkinter
-------

- On popular demand, _tkinter once again installs a hook for readline
that processes certain Tk events while waiting for the user to type
(using PyOS_InputHook).

- A patch by Craig McPheeters plugs the most obnoxious memory leaks,
caused by command definitions referencing widget objects beyond their
lifetime.

- New standard dialog modules: tkColorChooser.py, tkCommonDialog.py,
tkMessageBox.py, tkFileDialog.py, tkSimpleDialog.py These interface
with the new Tk dialog scripts, and provide more "native platform"
style file selection dialog boxes on some platforms.  Contributed by
Fredrik Lundh.

- Tkinter.py: when the first Tk object is destroyed, it sets the
hiddel global _default_root to None, so that when another Tk object is
created it becomes the new default root.  Other miscellaneous
changes and fixes.

- The Image class now has a configure method.

- Added a bunch of new winfo options to Tkinter.py; we should now be
up to date with Tk 4.2.  The new winfo options supported are:
mananger, pointerx, pointerxy, pointery, server, viewable, visualid,
visualsavailable.

- The broken bind() method on Canvas objects defined in the Canvas.py
module has been fixed.  The CanvasItem and Group classes now also have
an unbind() method.

- The problem with Tkinter.py falling back to trying to import
"tkinter" when "_tkinter" is not found has been fixed -- it no longer
tries "tkinter", ever.  This makes diagnosing the problem "_tkinter
not configured" much easier and will hopefully reduce the newsgroup
traffic on this topic.

- The ScrolledText module once again supports the 'cnf' parameter, to
be compatible with the examples in Mark Lutz' book (I know, I know,
too late...)

- The _tkinter.c extension module has been revamped.  It now support
Tk versions 4.1 through 8.0; support for 4.0 has been dropped.  It
works well under Windows and Mac (with the latest Tk ports to those
platforms).  It also supports threading -- it is safe for one
(Python-created) thread to be blocked in _tkinter.mainloop() while
other threads modify widgets.  To make the changes visible, those
threads must use update_idletasks()method.  (The patch for threading
in 1.5a3 was broken; in 1.5a4, it is back in a different version,
which requires access to the Tcl sources to get it to work -- hence it
is disabled by default.)

- A bug in _tkinter.c has been fixed, where Split() with a string
containing an unmatched '"' could cause an exception or core dump.

- Unfortunately, on Windows and Mac, Tk 8.0 no longer supports
CreateFileHandler, so _tkinter.createfilehandler is not available on
those platforms when using Tk 8.0 or later.  I will have to rethink
how to interface with Tcl's lower-level event mechanism, or with its
channels (which are like Python's file-like objects).  Jack Jansen has
provided a fix for the Mac, so createfilehandler *is* actually
supported there; maybe I can adapt his fix for Windows.


Tools and Demos
---------------

- A new regression test suite is provided, which tests most of the
standard and built-in modules.  The regression test is run by invoking
the script Lib/test/regrtest.py.  Barry Warsaw wrote the test harnass;
he and Roger Masse contributed most of the new tests.

- New tool: faqwiz -- the CGI script that is used to maintain the
Python FAQ (http://grail.cnri.reston.va.us/cgi-bin/faqw.py).  In
Tools/faqwiz.

- New tool: webchecker -- a simple extensible web robot that, when
aimed at a web server, checks that server for dead links.  Available
are a command line utility as well as a Tkinter based GUI version.  In
Tools/webchecker.  A simplified version of this program is dissected
in my article in O'Reilly's WWW Journal, the issue on Scripting
Languages (Vol 2, No 2); Scripting the Web with Python (pp 97-120).
Includes a parser for robots.txt files by Skip Montanaro.

- New small tools: cvsfiles.py (prints a list of all files under CVS
n a particular directory tree), treesync.py (a rather Guido-specific
script to synchronize two source trees, one on Windows NT, the other
one on Unix under CVS but accessible from the NT box), and logmerge.py
(sort a collection of RCS or CVS logs by date).  In Tools/scripts.

- The freeze script now also works under Windows (NT).  Another
feature allows the -p option to be pointed at the Python source tree
instead of the installation prefix.  This was loosely based on part of
xfreeze by Sam Rushing and Bill Tutt.

- New examples (Demo/extend) that show how to use the generic
extension makefile (Misc/Makefile.pre.in).

- Tools/scripts/h2py.py now supports C++ comments.

- Tools/scripts/pystone.py script is upgraded to version 1.1; there
was a bug in version 1.0 (distributed with Python 1.4) that leaked
memory.  Also, in 1.1, the LOOPS variable is incremented to 10000.

- Demo/classes/Rat.py completely rewritten by Sjoerd Mullender.


Windows (NT and 95)
-------------------

- New project files for Developer Studio (Visual C++) 5.0 for Windows
NT (the old VC++ 4.2 Makefile is also still supported, but will
eventually be withdrawn due to its bulkiness).

- See the note on the new module search path in the "Miscellaneous" section 
above.

- Support for Win32s (the 32-bit Windows API under Windows 3.1) is
basically withdrawn.  If it still works for you, you're lucky.

- There's a new extension module, msvcrt.c, which provides various 
low-level operations defined in the Microsoft Visual C++ Runtime Library.  
These include locking(), setmode(), get_osfhandle(), set_osfhandle(), and 
console I/O functions like kbhit(), getch() and putch().

- The -u option not only sets the standard I/O streams to unbuffered
status, but also sets them in binary mode.  (This can also be done
using msvcrt.setmode(), by the way.)

- The, sys.prefix and sys.exec_prefix variables point to the directory 
where Python is installed, or to the top of the source tree, if it was run 
from there.

- The various os.path modules (posixpath, ntpath, macpath) now support
passing more than two arguments to the join() function, so
os.path.join(a, b, c) is the same as os.path.join(a, os.path.join(b,
c)).

- The ntpath module (normally used as os.path) supports ~ to $HOME 
expansion in expanduser().

- The freeze tool now works on Windows.

- See also the Tkinter category for a sad note on
_tkinter.createfilehandler().

- The truncate() method for file objects now works on Windows.

- Py_Initialize() is no longer called when the DLL is loaded.  You
must call it yourself.

- The time module's clock() function now has good precision through
the use of the Win32 API QueryPerformanceCounter().

- Mark Hammond will release Python 1.5 versions of PythonWin and his
other Windows specific code: the win32api extensions, COM/ActiveX
support, and the MFC interface.


Mac
---

- As always, the Macintosh port will be done by Jack Jansen.  He will
make a separate announcement for the Mac specific source code and the
binary distribution(s) when these are ready.


======================================================================


=====================================
==> Release 1.4 (October 25 1996) <==
=====================================

(Starting in reverse chronological order:)

- Changed disclaimer notice.

- Added SHELL=/bin/sh to Misc/Makefile.pre.in -- some Make versions
default to the user's login shell.

- In Lib/tkinter/Tkinter.py, removed bogus binding of <Delete> in Text
widget, and bogus bspace() function.

- In Lib/cgi.py, bumped __version__ to 2.0 and restored a truncated
paragraph.

- Fixed the NT Makefile (PC/vc40.mak) for VC 4.0 to set /MD for all
subprojects, and to remove the (broken) experimental NumPy
subprojects.

- In Lib/py_compile.py, cast mtime to long() so it will work on Mac
(where os.stat() returns mtimes as floats.)
- Set self.rfile unbuffered (like self.wfile) in SocketServer.py, to
fix POST in CGIHTTPServer.py.

- Version 2.83 of Misc/python-mode.el for Emacs is included.

- In Modules/regexmodule.c, fixed symcomp() to correctly handle a new
group starting immediately after a group tag.

- In Lib/SocketServer.py, changed the mode for rfile to unbuffered.

- In Objects/stringobject.c, fixed the compare function to do the
first char comparison in unsigned mode, for consistency with the way
other characters are compared by memcmp().

- In Lib/tkinter/Tkinter.py, fixed Scale.get() to support floats.

- In Lib/urllib.py, fix another case where openedurl wasn't set.

(XXX Sorry, the rest is in totally random order.  No time to fix it.)

- SyntaxError exceptions detected during code generation
(e.g. assignment to an expression) now include a line number.

- Don't leave trailing / or \ in script directory inserted in front of
sys.path.

- Added a note to Tools/scripts/classfix.py abouts its historical
importance.

- Added Misc/Makefile.pre.in, a universal Makefile for extensions
built outside the distribution.

- Rewritten Misc/faq2html.py, by Ka-Ping Yee.

- Install shared modules with mode 555 (needed for performance on some
platforms).

- Some changes to standard library modules to avoid calling append()
with more than one argument -- while supported, this should be
outlawed, and I don't want to set a bad example.

- bdb.py (and hence pdb.py) supports calling run() with a code object
instead of a code string.

- Fixed an embarrassing bug cgi.py which prevented correct uploading
of binary files from Netscape (which doesn't distinguish between
binary and text files).  Also added dormant logging support, which
makes it easier to debug the cgi module itself.

- Added default writer to constructor of NullFormatter class.

- Use binary mode for socket.makefile() calls in ftplib.py.

- The ihooks module no longer "installs" itself upon import -- this
was an experimental feature that helped ironing out some bugs but that
slowed down code that imported it without the need to install it
(e.g. the rexec module).  Also close the file in some cases and add
the __file__ attribute to loaded modules.

- The test program for mailbox.py is now more useful.

- Added getparamnames() to Message class in mimetools.py -- it returns
the names of parameters to the content-type header.

- Fixed a typo in ni that broke the loop stripping "__." from names.

- Fix sys.path[0] for scripts run via pdb.py's new main program.

- profile.py can now also run a script, like pdb.

- Fix a small bug in pyclbr -- don't add names starting with _ when
emulating from ... import *.

- Fixed a series of embarrassing typos in rexec's handling of standard
I/O redirection.  Added some more "safe" built-in modules: cmath,
errno, operator.

- Fixed embarrassing typo in shelve.py.

- Added SliceType and EllipsisType to types.py.

- In urllib.py, added handling for error 301 (same as 302); added
geturl() method to get the URL after redirection.

- Fixed embarrassing typo in xdrlib.py.  Also fixed typo in Setup.in
for _xdrmodule.c and removed redundant #include from _xdrmodule.c.

- Fixed bsddbmodule.c to add binary mode indicator on platforms that
have it.  This should make it working on Windows NT.

- Changed last uses of #ifdef NT to #ifdef MS_WINDOWS or MS_WIN32,
whatever applies.  Also rationalized some other tests for various MS
platforms.

- Added the sources for the NT installer script used for Python
1.4beta3.  Not tested with this release, but better than nothing.

- A compromise in pickle's defenses against Trojan horses: a
user-defined function is now okay where a class is expected.  A
built-in function is not okay, to prevent pickling something that
will execute os.system("rm -f *") when unpickling.

- dis.py will print the name of local variables referenced by local
load/store/delete instructions.

- Improved portability of SimpleHTTPServer module to non-Unix
platform.

- The thread.h interface adds an extra argument to down_sema().  This
only affects other C code that uses thread.c; the Python thread module
doesn't use semaphores (which aren't provided on all platforms where
Python threads are supported).  Note: on NT, this change is not
implemented.

- Fixed some typos in abstract.h; corrected signature of
PyNumber_Coerce, added PyMapping_DelItem.  Also fixed a bug in
abstract.c's PyObject_CallMethod().

- apply(classname, (), {}) now works even if the class has no
__init__() method.

- Implemented complex remainder and divmod() (these would dump core!).
Conversion of complex numbers to int, long int or float now raises an
exception, since there is no meaningful way to do it without losing
information.

- Fixed bug in built-in complex() function which gave the wrong result
for two real arguments.

- Change the hash algorithm for strings -- the multiplier is now
1000003 instead of 3, which gives better spread for short strings.

- New default path for Windows NT, the registry structure now supports
default paths for different install packages.  (Mark Hammond -- the
next PythonWin release will use this.)

- Added more symbols to the python_nt.def file.

- When using GNU readline, set rl_readline_name to "python".

- The Ellipses built-in name has been renamed to Ellipsis -- this is
the correct singular form.  Thanks to Ka-Ping Yee, who saved us from
eternal embarrassment.

- Bumped the PYTHON_API_VERSION to 1006, due to the Ellipses ->
Ellipsis name change.

- Updated the library reference manual.  Added documentation of
restricted mode (rexec, Bastion) and the formatter module (for use
with the htmllib module).  Fixed the documentation of htmllib
(finally).

- The reference manual is now maintained in FrameMaker.

- Upgraded scripts Doc/partparse.py and Doc/texi2html.py.

- Slight improvements to Doc/Makefile.

- Added fcntl.lockf(). This should be used for Unix file locking
instead of the posixfile module; lockf() is more portable.

- The getopt module now supports long option names, thanks to Lars
Wizenius.

- Plenty of changes to Tkinter and Canvas, mostly due to Fred Drake
and Nils Fischbeck.

- Use more bits of time.time() in whrandom's default seed().

- Performance hack for regex module's regs attribute.

- Don't close already closed socket in socket module.

- Correctly handle separators containing embedded nulls in
strop.split, strop.find and strop.rfind.  Also added more detail to
error message for strop.atoi and friends.

- Moved fallback definition for hypot() to Python/hypot.c.

- Added fallback definition for strdup, in Python/strdup.c.

- Fixed some bugs where a function would return 0 to indicate an error
where it should return -1.

- Test for error returned by time.localtime(), and rationalized its MS
tests.

- Added Modules/Setup.local file, which is processed after Setup.

- Corrected bug in toplevel Makefile.in -- execution of regen script
would not use the right PATH and PYTHONPATH.

- Various and sundry NeXT configuration changes (sigh).

- Support systems where libreadline needs neither termcap nor curses.

- Improved ld_so_aix script and python.exp file (for AIX).

- More stringent test for working <stdarg.h> in configure script.

- Removed Demo/www subdirectory -- it was totally out of date.

- Improved demos and docs for Fred Drake's parser module; fixed one
typo in the module itself.


=========================================
==> Release 1.4beta3 (August 26 1996) <==
=========================================


(XXX This is less readable that it should.  I promise to restructure
it for the final 1.4 release.)


What's new in 1.4beta3 (since beta2)?
-------------------------------------

- Name mangling to implement a simple form of class-private variables.
A name of the form "__spam" can't easily be used outside the class.
(This was added in 1.4beta3, but left out of the 1.4beta3 release
message.)

- In urllib.urlopen(): HTTP URLs containing user:passwd@host are now
handled correctly when using a proxy server.

- In ntpath.normpath(): don't truncate to 8+3 format.

- In mimetools.choose_boundary(): don't die when getuid() or getpid()
aren't defined.

- Module urllib: some optimizations to (un)quoting.

- New module MimeWriter for writing MIME documents.

- More changes to formatter module.

- The freeze script works once again and is much more robust (using
sys.prefix etc.).  It also supports a -o option to specify an
output directory.

- New module whichdb recognizes dbm, gdbm and bsddb/dbhash files.

- The Doc/Makefile targets have been reorganized somewhat to remove the 
insistence on always generating PostScript.

- The texinfo to html filter (Doc/texi2html.py) has been improved somewhat.

- "errors.h" has been renamed to "pyerrors.h" to resolve a long-standing 
name conflict on the Mac.

- Linking a module compiled with a different setting for Py_TRACE_REFS now 
generates a linker error rather than a core dump.

- The cgi module has a new convenience function print_exception(), which 
formats a python exception using HTML.  It also fixes a bug in the 
compatibility code and adds a dubious feature which makes it possible to 
have two query strings, one in the URL and one in the POST data.

- A subtle change in the unpickling of class instances makes it possible 
to unpickle in restricted execution mode, where the __dict__ attribute is 
not available (but setattr() is).

- Documentation for os.path.splitext() (== posixpath.splitext()) has been 
cleared up.  It splits at the *last* dot.

- posixfile locking is now also correctly supported on AIX.

- The tempfile module once again honors an initial setting of tmpdir.  It 
now works on Windows, too.

- The traceback module has some new functions to extract, format and print 
the active stack.

- Some translation functions in the urllib module have been made a little 
less sluggish.

- The addtag_* methods for Canvas widgets in Tkinter as well as in the 
separate Canvas class have been fixed so they actually do something 
meaningful.

- A tiny _test() function has been added to Tkinter.py.

- A generic Makefile for dynamically loaded modules is provided in the Misc 
subdirectory (Misc/gMakefile).

- A new version of python-mode.el for Emacs is provided.  See
http://www.python.org/ftp/emacs/pmdetails.html for details.  The
separate file pyimenu.el is no longer needed, imenu support is folded
into python-mode.el.

- The configure script can finally correctly find the readline library in a 
non-standard location.  The LDFLAGS variable is passed on the Makefiles 
from the configure script.

- Shared libraries are now installed as programs (i.e. with executable 
permission).  This is required on HP-UX and won't hurt on other systems.

- The objc.c module is no longer part of the distribution.  Objective-C 
support may become available as contributed software on the ftp site.

- The sybase module is no longer part of the distribution.  A much
improved sybase module is available as contributed software from the
ftp site.

- _tkinter is now compatible with Tcl 7.5 / Tk 4.1 patch1 on Windows and 
Mac (don't use unpatched Tcl/Tk!).  The default line in the Setup.in file 
now links with Tcl 7.5 / Tk 4.1 rather than 7.4/4.0.

- In Setup, you can now write "*shared*" instead of "*noconfig*", and you 
can use *.so and *.sl as shared libraries.

- Some more fidgeting for AIX shared libraries.

- The mpz module is now compatible with GMP 2.x.  (Not tested by me.)
(Note -- a complete replacement by Niels Mo"ller, called gpmodule, is
available from the contrib directory on the ftp site.)

- A warning is written to sys.stderr when a __del__ method raises an 
exception (formerly, such exceptions were completely ignored).

- The configure script now defines HAVE_OLD_CPP if the C preprocessor is 
incapable of ANSI style token concatenation and stringification.

- All source files (except a few platform specific modules) are once again 
compatible with K&R C compilers as well as ANSI compilers.  In particular,
ANSI-isms have been removed or made conditional in complexobject.c, 
getargs.c and operator.c.

- The abstract object API has three new functions, PyObject_DelItem, 
PySequence_DelItem, and PySequence_DelSlice.

- The operator module has new functions delitem and delslice, and the 
functions "or" and "and" are renamed to "or_" and "and_" (since "or" and 
"and" are reserved words).  ("__or__" and "__and__" are unchanged.)

- The environment module is no longer supported; putenv() is now a function 
in posixmodule (also under NT).

- Error in filter(<function>, "") has been fixed.

- Unrecognized keyword arguments raise TypeError, not KeyError.

- Better portability, fewer bugs and memory leaks, fewer compiler warnings, 
some more documentation.

- Bug in float power boundary case (0.0 to the negative integer power) 
fixed.

- The test of negative number to the float power has been moved from the 
built-in pow() function to floatobject.c (so complex numbers can yield the
correct result).

- The bug introduced in beta2 where shared libraries loaded (using 
dlopen()) from the current directory would fail, has been fixed.

- Modules imported as shared libraries now also have a __file__ attribute, 
giving the filename from which they were loaded.  The only modules without 
a __file__ attribute now are built-in modules.

- On the Mac, dynamically loaded modules can end in either ".slb" or 
".<platform>.slb" where <platform> is either "CFM68K" or "ppc".  The ".slb" 
extension should only be used for "fat" binaries.

- C API addition: marshal.c now supports 
PyMarshal_WriteObjectToString(object).

- C API addition: getargs.c now supports
PyArg_ParseTupleAndKeywords(args, kwdict, format, kwnames, ...)
to parse keyword arguments.

- The PC versioning scheme (sys.winver) has changed once again.  the 
version number is now "<digit>.<digit>.<digit>.<apiversion>", where the 
first three <digit>s are the Python version (e.g. "1.4.0" for Python 1.4, 
"1.4.1" for Python 1.4.1 -- the beta level is not included) and 
<apiversion> is the four-digit PYTHON_API_VERSION (currently 1005).

- h2py.py accepts whitespace before the # in CPP directives

- On Solaris 2.5, it should now be possible to use either Posix threads or 
Solaris threads (XXX: how do you select which is used???).  (Note: the 
Python pthreads interface doesn't fully support semaphores yet -- anyone 
care to fix this?)

- Thread support should now work on AIX, using either DCE threads or 
pthreads.

- New file Demo/sockets/unicast.py

- Working Mac port, with CFM68K support, with Tk 4.1 support (though not 
both) (XXX)

- New project setup for PC port, now compatible with PythonWin, with 
_tkinter and NumPy support (XXX)

- New module site.py (XXX)

- New module xdrlib.py and optional support module _xdrmodule.c (XXX)

- parser module adapted to new grammar, complete w/ Doc & Demo (XXX)

- regen script fixed (XXX)

- new machdep subdirectories Lib/{aix3,aix4,next3_3,freebsd2,linux2} (XXX)

- testall now also tests math module (XXX)

- string.atoi c.s. now raise an exception for an empty input string.

- At last, it is no longer necessary to define HAVE_CONFIG_H in order to 
have config.h included at various places.

- Unrecognized keyword arguments now raise TypeError rather than KeyError.

- The makesetup script recognizes files with extension .so or .sl as
(shared) libraries.

- 'access' is no longer a reserved word, and all code related to its 
implementation is gone (or at least #ifdef'ed out).  This should make 
Python a little speedier too!

- Performance enhancements suggested by Sjoerd Mullender.  This includes 
the introduction of two new optional function pointers in type object, 
getattro and setattro, which are like getattr and setattr but take a 
string object instead of a C string pointer.

- New operations in string module: lstrip(s) and rstrip(s) strip whitespace 
only on the left or only on the right, A new optional third argument to 
split() specifies the maximum number of separators honored (so 
splitfields(s, sep, n) returns a list of at most n+1 elements).  (Since 
1.3, splitfields(s, None) is totally equivalent to split(s).)
string.capwords() has an optional second argument specifying the 
separator (which is passed to split()).

- regsub.split() has the same addition as string.split().  regsub.splitx(s, 
sep, maxsep) implements the functionality that was regsub.split(s, 1) in 
1.4beta2 (return a list containing the delimiters as well as the words).

- Final touch for AIX loading, rewritten Misc/AIX-NOTES.

- In Modules/_tkinter.c, when using Tk 4.1 or higher, use className
argument to _tkinter.create() to set Tcl's argv0 variable, so X
resources use the right resource class again.

- Add #undef fabs to Modules/mathmodule.c for macintosh.

- Added some macro renames for AIX in Modules/operator.c.

- Removed spurious 'E' from Doc/liberrno.tex.

- Got rid of some cruft in Misc/ (dlMakefile, pyimenu.el); added new
Misc/gMakefile and new version of Misc/python-mode.el.

- Fixed typo in Lib/ntpath.py (islink has "return false" which gives a
NameError).

- Added missing "from types import *" to Lib/tkinter/Canvas.py.

- Added hint about using default args for __init__ to pickle docs.

- Corrected typo in Inclide/abstract.h: PySequence_Lenth ->
PySequence_Length.

- Some improvements to Doc/texi2html.py.

- In Python/import.c, Cast unsigned char * in struct _frozen to char *
in calls to rds_object().

- In doc/ref4.tex, added note about scope of lambda bodies.

What's new in 1.4beta2 (since beta1)?
-------------------------------------

- Portability bug in the md5.h header solved.

- The PC build procedure now really works, and sets sys.platform to a
meaningful value (a few things were botched in beta 1).  Lib/dos_8x3
is now a standard part of the distribution (alas).

- More improvements to the installation procedure.  Typing "make install" 
now inserts the version number in the pathnames of almost everything 
installed, and creates the machine dependent modules (FCNTL.py etc.) if not 
supplied by the distribution.  (XXX There's still a problem with the latter 
because the "regen" script requires that Python is installed.  Some manual 
intervention may still be required.) (This has been fixed in 1.4beta3.)

- New modules: errno, operator (XXX).

- Changes for use with Numerical Python: built-in function slice() and
Ellipses object, and corresponding syntax:

	x[lo:hi:stride]		==	x[slice(lo, hi, stride)]
	x[a, ..., z]		==	x[(a, Ellipses, z)]

- New documentation for errno and cgi modules.

- The directory containing the script passed to the interpreter is
inserted in from of sys.path; "." is no longer a default path
component.

- Optional third string argument to string.translate() specifies
characters to delete.  New function string.maketrans() creates a
translation table for translate() or for regex.compile().

- Module posix (and hence module os under Unix) now supports putenv().
Moreover, module os is enhanced so that if putenv() is supported,
assignments to os.environ entries make the appropriate putenv() call.
(XXX the putenv() implementation can leak a small amount of memory per
call.)

- pdb.py can now be invoked from the command line to debug a script:
python pdb.py <script> <arg> ...

- Much improved parseaddr() in rfc822.

- In cgi.py, you can now pass an alternative value for environ to
nearly all functions.

- You can now assign to instance variables whose name begins and ends
with '__'.

- New version of Fred Drake's parser module and associates (token,
symbol, AST).

- New PYTHON_API_VERSION value and .pyc file magic number (again!).

- The "complex" internal structure type is now called "Py_complex" to
avoid name conflicts.

- Numerous small bugs fixed.

- Slight pickle speedups.

- Some slight speedups suggested by Sjoerd (more coming in 1.4 final).

- NeXT portability mods by Bill Bumgarner integrated.

- Modules regexmodule.c, bsddbmodule.c and xxmodule.c have been
converted to new naming style.


What's new in 1.4beta1 (since 1.3)?
-----------------------------------

- Added sys.platform and sys.exec_platform for Bill Janssen.

- Installation has been completely overhauled.  "make install" now installs 
everything, not just the python binary.  Installation uses the install-sh 
script (borrowed from X11) to install each file.

- New functions in the posix module: mkfifo, plock, remove (== unlink),
and ftruncate.  More functions are also available under NT.

- New function in the fcntl module: flock.

- Shared library support for FreeBSD.

- The --with-readline option can now be used without a DIRECTORY argument, 
for systems where libreadline.* is in one of the standard places.  It is 
also possible for it to be a shared library.

- The extension tkinter has been renamed to _tkinter, to avoid confusion 
with Tkinter.py oncase insensitive file systems.  It now supports Tk 4.1 as 
well as 4.0.

- Author's change of address from CWI in Amsterdam, The Netherlands, to 
CNRI in Reston, VA, USA.

- The math.hypot() function is now always available (if it isn't found in 
the C math library, Python provides its own implementation).

- The latex documentation is now compatible with latex2e, thanks to David 
Ascher.

- The expression x**y is now equivalent to pow(x, y).

- The indexing expression x[a, b, c] is now equivalent to x[(a, b, c)].

- Complex numbers are now supported.  Imaginary constants are written with 
a 'j' or 'J' prefix, general complex numbers can be formed by adding a real 
part to an imaginary part, like 3+4j.  Complex numbers are always stored in 
floating point form, so this is equivalent to 3.0+4.0j.  It is also 
possible to create complex numbers with the new built-in function 
complex(re, [im]).  For the footprint-conscious, complex number support can 
be disabled by defining the symbol WITHOUT_COMPLEX.

- New built-in function list() is the long-awaited counterpart of tuple().

- There's a new "cmath" module which provides the same functions as the 
"math" library but with complex arguments and results.  (There are very 
good reasons why math.sqrt(-1) still raises an exception -- you have to use 
cmath.sqrt(-1) to get 1j for an answer.)

- The Python.h header file (which is really the same as allobjects.h except 
it disables support for old style names) now includes several more files, 
so you have to have fewer #include statements in the average extension.

- The NDEBUG symbol is no longer used.  Code that used to be dependent on 
the presence of NDEBUG is now present on the absence of DEBUG.  TRACE_REFS 
and REF_DEBUG have been renamed to Py_TRACE_REFS and Py_REF_DEBUG, 
respectively.  At long last, the source actually compiles and links without 
errors when this symbol is defined.

- Several symbols that didn't follow the new naming scheme have been 
renamed (usually by adding to rename2.h) to use a Py or _Py prefix.  There 
are no external symbols left without a Py or _Py prefix, not even those 
defined by sources that were incorporated from elsewhere (regexpr.c, 
md5c.c).  (Macros are a different story...)

- There are now typedefs for the structures defined in config.c and 
frozen.c.

- New PYTHON_API_VERSION value and .pyc file magic number.

- New module Bastion.  (XXX)

- Improved performance of StringIO module.

- UserList module now supports + and * operators.

- The binhex and binascii modules now actually work.

- The cgi module has been almost totally rewritten and documented.
It now supports file upload and a new data type to handle forms more 
flexibly.

- The formatter module (for use with htmllib) has been overhauled (again).

- The ftplib module now supports passive mode and has doc strings.

- In (ideally) all places where binary files are read or written, the file 
is now correctly opened in binary mode ('rb' or 'wb') so the code will work 
on Mac or PC.

- Dummy versions of os.path.expandvars() and expanduser() are now provided 
on non-Unix platforms.

- Module urllib now has two new functions url2pathname and pathname2url 
which turn local filenames into "file:..." URLs using the same rules as 
Netscape (why be different).  it also supports urlretrieve() with a 
pathname parameter, and honors the proxy environment variables (http_proxy 
etc.).  The URL parsing has been improved somewhat, too.

- Micro improvements to urlparse.  Added urlparse.urldefrag() which 
removes a trailing ``#fragment'' if any.

- The mailbox module now supports MH style message delimiters as well.

- The mhlib module contains some new functionality: setcontext() to set the 
current folder and parsesequence() to parse a sequence as commonly passed 
to MH commands (e.g. 1-10 or last:5).

- New module mimify for conversion to and from MIME format of email 
messages.

- Module ni now automatically installs itself when first imported -- this 
is against the normal rule that modules should define classes and functions 
but not invoke them, but appears more useful in the case that two 
different, independent modules want to use ni's features.

- Some small performance enhancements in module pickle.

- Small interface change to the profile.run*() family of functions -- more 
sensible handling of return values.

- The officially registered Mac creator for Python files is 'Pyth'.  This 
replaces 'PYTH' which was used before but never registered.

- Added regsub.capwords().  (XXX)

- Added string.capwords(), string.capitalize() and string.translate().  
(XXX)

- Fixed an interface bug in the rexec module: it was impossible to pass a 
hooks instance to the RExec class.  rexec now also supports the dynamic 
loading of modules from shared libraries.  Some other interfaces have been 
added too.

- Module rfc822 now caches the headers in a dictionary for more efficient 
lookup.

- The sgmllib module now understands a limited number of SGML "shorthands" 
like <A/.../ for <A>...</A>.  (It's not clear that this was a good idea...)

- The tempfile module actually tries a number of different places to find a 
usable temporary directory.  (This was prompted by certain Linux 
installations that appear to be missing a /usr/tmp directory.) [A bug in 
the implementation that would ignore a pre-existing tmpdir global has been 
fixed in beta3.]

- Much improved and enhanved FileDialog module for Tkinter.

- Many small changes to Tkinter, to bring it more in line with Tk 4.0 (as 
well as Tk 4.1).

- New socket interfaces include ntohs(), ntohl(), htons(), htonl(), and 
s.dup().  Sockets now work correctly on Windows.  On Windows, the built-in 
extension is called _socket and a wrapper module win/socket.py provides 
"makefile()" and "dup()" functionality.  On Windows, the select module 
works only with socket objects.

- Bugs in bsddb module fixed (e.g. missing default argument values).

- The curses extension now includes <ncurses.h> when available.

- The gdbm module now supports opening databases in "fast" mode by 
specifying 'f' as the second character or the mode string.

- new variables sys.prefix and sys.exec_prefix pass corresponding 
configuration options / Makefile variables to the Python programmer.

- The ``new'' module now supports creating new user-defined classes as well 
as instances thereof.

- The soundex module now sports get_soundex() to get the soundex value for an 
arbitrary string (formerly it would only do soundex-based string 
comparison) as well as doc strings.

- New object type "cobject" to safely wrap void pointers for passing them 
between various extension modules.

- More efficient computation of float**smallint.

- The mysterious bug whereby "x.x" (two occurrences of the same 
one-character name) typed from the commandline would sometimes fail 
mysteriously.

- The initialization of the readline function can now be invoked by a C 
extension through PyOS_ReadlineInit().

- There's now an externally visible pointer PyImport_FrozenModules which 
can be changed by an embedding application.

- The argument parsing functions now support a new format character 'D' to 
specify complex numbers.

- Various memory leaks plugged and bugs fixed.

- Improved support for posix threads (now that real implementations are 
beginning to apepar).  Still no fully functioning semaphores.

- Some various and sundry improvements and new entries in the Tools 
directory.


=====================================
==> Release 1.3 (13 October 1995) <==
=====================================

Major change
============

Two words: Keyword Arguments.  See the first section of Chapter 12 of
the Tutorial.

(The rest of this file is textually the same as the remaining sections
of that chapter.)


Changes to the WWW and Internet tools
=====================================

The "htmllib" module has been rewritten in an incompatible fashion.
The new version is considerably more complete (HTML 2.0 except forms,
but including all ISO-8859-1 entity definitions), and easy to use.
Small changes to "sgmllib" have also been made, to better match the
tokenization of HTML as recognized by other web tools.

A new module "formatter" has been added, for use with the new
"htmllib" module.

The "urllib"and "httplib" modules have been changed somewhat to allow
overriding unknown URL types and to support authentication.  They now
use "mimetools.Message" instead of "rfc822.Message" to parse headers.
The "endrequest()" method has been removed from the HTTP class since
it breaks the interaction with some servers.

The "rfc822.Message" class has been changed to allow a flag to be
passed in that says that the file is unseekable.

The "ftplib" module has been fixed to be (hopefully) more robust on
Linux.

Several new operations that are optionally supported by servers have
been added to "nntplib": "xover", "xgtitle", "xpath" and "date".

Other Language Changes
======================

The "raise" statement now takes an optional argument which specifies
the traceback to be used when printing the exception's stack trace.
This must be a traceback object, such as found in "sys.exc_traceback".
When omitted or given as "None", the old behavior (to generate a stack
trace entry for the current stack frame) is used.

The tokenizer is now more tolerant of alien whitespace.  Control-L in
the leading whitespace of a line resets the column number to zero,
while Control-R just before the end of the line is ignored.

Changes to Built-in Operations
==============================

For file objects, "f.read(0)" and "f.readline(0)" now return an empty
string rather than reading an unlimited number of bytes.  For the
latter, omit the argument altogether or pass a negative value.

A new system variable, "sys.platform", has been added.  It specifies
the current platform, e.g. "sunos5" or "linux1".

The built-in functions "input()" and "raw_input()" now use the GNU
readline library when it has been configured (formerly, only
interactive input to the interpreter itself was read using GNU
readline).  The GNU readline library provides elaborate line editing
and history.  The Python debugger ("pdb") is the first beneficiary of
this change.

Two new built-in functions, "globals()" and "locals()", provide access
to dictionaries containming current global and local variables,
respectively.  (These augment rather than replace "vars()", which
returns the current local variables when called without an argument,
and a module's global variables when called with an argument of type
module.)

The built-in function "compile()" now takes a third possible value for
the kind of code to be compiled: specifying "'single'" generates code
for a single interactive statement, which prints the output of
expression statements that evaluate to something else than "None".

Library Changes
===============

There are new module "ni" and "ihooks" that support importing modules
with hierarchical names such as "A.B.C".  This is enabled by writing
"import ni; ni.ni()" at the very top of the main program.  These
modules are amply documented in the Python source.

The module "rexec" has been rewritten (incompatibly) to define a class
and to use "ihooks".

The "string.split()" and "string.splitfields()" functions are now the
same function (the presence or absence of the second argument
determines which operation is invoked); similar for "string.join()"
and "string.joinfields()".

The "Tkinter" module and its helper "Dialog" have been revamped to use
keyword arguments.  Tk 4.0 is now the standard.  A new module
"FileDialog" has been added which implements standard file selection
dialogs.

The optional built-in modules "dbm" and "gdbm" are more coordinated
--- their "open()" functions now take the same values for their "flag"
argument, and the "flag" and "mode" argument have default values (to
open the database for reading only, and to create the database with
mode "0666" minuse the umask, respectively).  The memory leaks have
finally been fixed.

A new dbm-like module, "bsddb", has been added, which uses the BSD DB
package's hash method.

A portable (though slow) dbm-clone, implemented in Python, has been
added for systems where none of the above is provided.  It is aptly
dubbed "dumbdbm".

The module "anydbm" provides a unified interface to "bsddb", "gdbm",
"dbm", and "dumbdbm", choosing the first one available.

A new extension module, "binascii", provides a variety of operations
for conversion of text-encoded binary data.

There are three new or rewritten companion modules implemented in
Python that can encode and decode the most common such formats: "uu"
(uuencode), "base64" and "binhex".

A module to handle the MIME encoding quoted-printable has also been
added: "quopri".

The parser module (which provides an interface to the Python parser's
abstract syntax trees) has been rewritten (incompatibly) by Fred
Drake.  It now lets you change the parse tree and compile the result!

The \code{syslog} module has been upgraded and documented.

Other Changes
=============

The dynamic module loader recognizes the fact that different filenames
point to the same shared library and loads the library only once, so
you can have a single shared library that defines multiple modules.
(SunOS / SVR4 style shared libraries only.)

Jim Fulton's ``abstract object interface'' has been incorporated into
the run-time API.  For more detailes, read the files
"Include/abstract.h" and "Objects/abstract.c".

The Macintosh version is much more robust now.

Numerous things I have forgotten or that are so obscure no-one will
notice them anyway :-)


===================================
==> Release 1.2 (13 April 1995) <==
===================================

- Changes to Misc/python-mode.el:
  - Wrapping and indentation within triple quote strings should work
    properly now.
  - `Standard' bug reporting mechanism (use C-c C-b)
  - py-mark-block was moved to C-c C-m
  - C-c C-v shows you the python-mode version
  - a basic python-font-lock-keywords has been added for Emacs 19
    font-lock colorizations.
  - proper interaction with pending-del and del-sel modes.
  - New py-electric-colon (:) command for improved outdenting.  Also
    py-indent-line (TAB) should handle outdented lines better.
  - New commands py-outdent-left (C-c C-l) and py-indent-right (C-c C-r)

- The Library Reference has been restructured, and many new and
existing modules are now documented, in particular the debugger and
the profiler, as well as the persistency and the WWW/Internet support
modules.

- All known bugs have been fixed.  For example the pow(2,2,3L) bug on
Linux has been fixed.  Also the re-entrancy problems with __del__ have
been fixed.

- All known memory leaks have been fixed.

- Phase 2 of the Great Renaming has been executed.  The header files
now use the new names (PyObject instead of object, etc.).  The linker
also sees the new names.  Most source files still use the old names,
by virtue of the rename2.h header file.  If you include Python.h, you
only see the new names.  Dynamically linked modules have to be
recompiled.  (Phase 3, fixing the rest of the sources, will be
executed gradually with the release later versions.)

- The hooks for implementing "safe-python" (better called "restricted
execution") are in place.  Specifically, the import statement is
implemented by calling the built-in function __import__, and the
built-in names used in a particular scope are taken from the
dictionary __builtins__ in that scope's global dictionary.  See also
the new (unsupported, undocumented) module rexec.py.

- The import statement now supports the syntax "import a.b.c" and
"from a.b.c import name".  No officially supported implementation
exists, but one can be prototyped by replacing the built-in __import__
function.  A proposal by Ken Manheimer is provided as newimp.py.

- All machinery used by the import statement (or the built-in
__import__ function) is now exposed through the new built-in module
"imp" (see the library reference manual).  All dynamic loading
machinery is moved to the new file importdl.c.

- Persistent storage is supported through the use of the modules
"pickle" and "shelve" (implemented in Python).  There's also a "copy"
module implementing deepcopy and normal (shallow) copy operations.
See the library reference manual.

- Documentation strings for many object types are accessible through
the __doc__ attribute.  Modules, classes and functions support special
syntax to initialize the __doc__ attribute: if the first statement
consists of just a string literal, that string literal becomes the
value of the __doc__ attribute.  The default __doc__ attribute is
None.  Documentation strings are also supported for built-in
functions, types and modules; however this feature hasn't been widely
used yet.  See the 'new' module for an example.  (Basically, the type
object's tp_doc field contains the doc string for the type, and the
4th member of the methodlist structure contains the doc string for the
method.)

- The __coerce__ and __cmp__ methods for user-defined classes once
again work as expected.  As an example, there's a new standard class
Complex in the library.

- The functions posix.popen() and posix.fdopen() now have an optional
third argument to specify the buffer size, and default their second
(mode) argument to 'r' -- in analogy to the built-in open() function.
The same applies to posixfile.open() and the socket method makefile().

- The thread.exit_thread() function now raises SystemExit so that
'finally' clauses are honored and a memory leak is plugged.

- Improved X11 and Motif support, by Sjoerd Mullender.  This extension
is being maintained and distributed separately.

- Improved support for the Apple Macintosh, in part by Jack Jansen,
e.g. interfaces to (a few) resource mananger functions, get/set file
type and creator, gestalt, sound manager, speech manager, MacTCP, comm
toolbox, and the think C console library.  This is being maintained
and distributed separately.

- Improved version for Windows NT, by Mark Hammond.  This is being
maintained and distributed separately.

- Used autoconf 2.0 to generate the configure script.  Adapted
configure.in to use the new features in autoconf 2.0.

- It now builds on the NeXT without intervention, even on the 3.3
Sparc pre-release.

- Characters passed to isspace() and friends are masked to nonnegative
values.

- Correctly compute pow(-3.0, 3).

- Fix portability problems with getopt (configure now checks for a
non-GNU getopt).

- Don't add frozenmain.o to libPython.a.

- Exceptions can now be classes.  ALl built-in exceptions are still
string objects, but this will change in the future.

- The socket module exports a long list of socket related symbols.
(More built-in modules will export their symbolic constants instead of
relying on a separately generated Python module.)

- When a module object is deleted, it clears out its own dictionary.
This fixes a circularity in the references between functions and
their global dictionary.

- Changed the error handling by [new]getargs() e.g. for "O&".

- Dynamic loading of modules using shared libraries is supported for
several new platforms.

- Support "O&", "[...]" and "{...}" in mkvalue().

- Extension to findmethod(): findmethodinchain() (where a chain is a
linked list of methodlist arrays).  The calling interface for
findmethod() has changed: it now gets a pointer to the (static!)
methodlist structure rather than just to the function name -- this
saves copying flags etc. into the (short-lived) method object.

- The callable() function is now public.

- Object types can define a few new operations by setting function
pointers in the type object structure: tp_call defines how an object
is called, and tp_str defines how an object's str() is computed.


===================================
==> Release 1.1.1 (10 Nov 1994) <==
===================================

This is a pure bugfix release again.  See the ChangeLog file for details.

One exception: a few new features were added to tkinter.


=================================
==> Release 1.1 (11 Oct 1994) <==
=================================

This release adds several new features, improved configuration and
portability, and fixes more bugs than I can list here (including some
memory leaks).

The source compiles and runs out of the box on more platforms than
ever -- including Windows NT.  Makefiles or projects for a variety of
non-UNIX platforms are provided.

APOLOGY: some new features are badly documented or not at all.  I had
the choice -- postpone the new release indefinitely, or release it
now, with working code but some undocumented areas.  The problem with
postponing the release is that people continue to suffer from existing
bugs, and send me patches based on the previous release -- which I
can't apply directly because my own source has changed.  Also, some
new modules (like signal) have been ready for release for quite some
time, and people are anxiously waiting for them.  In the case of
signal, the interface is simple enough to figure out without
documentation (if you're anxious enough :-).  In this case it was not
simple to release the module on its own, since it relies on many small
patches elsewhere in the source.

For most new Python modules, the source code contains comments that
explain how to use them.  Documentation for the Tk interface, written
by Matt Conway, is available as tkinter-doc.tar.gz from the Python
home and mirror ftp sites (see Misc/FAQ for ftp addresses).  For the
new operator overloading facilities, have a look at Demo/classes:
Complex.py and Rat.py show how to implement a numeric type without and
with __coerce__ method.  Also have a look at the end of the Tutorial
document (Doc/tut.tex).  If you're still confused: use the newsgroup
or mailing list.


New language features:

    - More flexible operator overloading for user-defined classes
    (INCOMPATIBLE WITH PREVIOUS VERSIONS!)  See end of tutorial.

    - Classes can define methods named __getattr__, __setattr__ and
    __delattr__ to trap attribute accesses.  See end of tutorial.

    - Classes can define method __call__ so instances can be called
    directly.  See end of tutorial.


New support facilities:

    - The Makefiles (for the base interpreter as well as for extensions)
    now support creating dynamically loadable modules if the platform
    supports shared libraries.

    - Passing the interpreter a .pyc file as script argument will execute
    the code in that file.  (On the Mac such files can be double-clicked!)

    - New Freeze script, to create independently distributable "binaries"
    of Python programs -- look in Demo/freeze

    - Improved h2py script (in Demo/scripts) follows #includes and
    supports macros with one argument

    - New module compileall generates .pyc files for all modules in a
    directory (tree) without also executing them

    - Threads should work on more platforms


New built-in modules:

    - tkinter (support for Tcl's Tk widget set) is now part of the base
    distribution

    - signal allows catching or ignoring UNIX signals (unfortunately still
    undocumented -- any taker?)

    - termios provides portable access to POSIX tty settings

    - curses provides an interface to the System V curses library

    - syslog provides an interface to the (BSD?) syslog daemon

    - 'new' provides interfaces to create new built-in object types
    (e.g. modules and functions)

    - sybase provides an interface to SYBASE database


New/obsolete built-in methods:

    - callable(x) tests whether x can be called

    - sockets now have a setblocking() method

    - sockets no longer have an allowbroadcast() method

    - socket methods send() and sendto() return byte count


New standard library modules:

    - types.py defines standard names for built-in types, e.g. StringType

    - urlparse.py parses URLs according to the latest Internet draft

    - uu.py does uuencode/uudecode (not the fastest in the world, but
    quicker than installing uuencode on a non-UNIX machine :-)

    - New, faster and more powerful profile module.py

    - mhlib.py provides interface to MH folders and messages


New facilities for extension writers (unfortunately still
undocumented):

    - newgetargs() supports optional arguments and improved error messages

    - O!, O& O? formats for getargs allow more versatile type checking of
    non-standard types

    - can register pending asynchronous callback, to be called the next
    time the Python VM begins a new instruction (Py_AddPendingCall)

    - can register cleanup routines to be called when Python exits
    (Py_AtExit)

    - makesetup script understands C++ files in Setup file (use file.C
    or file.cc)

    - Make variable OPT is passed on to sub-Makefiles

    - An init<module>() routine may signal an error by not entering
    the module in the module table and raising an exception instead

    - For long module names, instead of foobarbletchmodule.c you can
    use foobarbletch.c

    - getintvalue() and getfloatvalue() try to convert any object
    instead of requiring an "intobject" or "floatobject"

    - All the [new]getargs() formats that retrieve an integer value
    will now also work if a float is passed

    - C function listtuple() converts list to tuple, fast

    - You should now call sigcheck() instead of intrcheck();
    sigcheck() also sets an exception when it returns nonzero


====================================
==> Release 1.0.3 (14 July 1994) <==
====================================

This release consists entirely of bug fixes to the C sources; see the
head of ../ChangeLog for a complete list.  Most important bugs fixed:

- Sometimes the format operator (string%expr) would drop the last
character of the format string

- Tokenizer looped when last line did not end in \n

- Bug when triple-quoted string ended in quote plus newline

- Typo in socketmodule (listen) (== instead of =)

- typing vars() at the >>> prompt would cause recursive output


==================================
==> Release 1.0.2 (4 May 1994) <==
==================================

Overview of the most visible changes.  Bug fixes are not listed.  See
also ChangeLog.

Tokens
------

* String literals follow Standard C rules: they may be continued on
the next line using a backslash; adjacent literals are concatenated
at compile time.

* A new kind of string literals, surrounded by triple quotes (""" or
'''), can be continued on the next line without a backslash.

Syntax
------

* Function arguments may have a default value, e.g. def f(a, b=1);
defaults are evaluated at function definition time.  This also applies
to lambda.

* The try-except statement has an optional else clause, which is
executed when no exception occurs in the try clause.

Interpreter
-----------

* The result of a statement-level expression is no longer printed,
except_ for expressions entered interactively.  Consequently, the -k
command line option is gone.

* The result of the last printed interactive expression is assigned to
the variable '_'.

* Access to implicit global variables has been speeded up by removing
an always-failing dictionary lookup in the dictionary of local
variables (mod suggested by Steve Makewski and Tim Peters).

* There is a new command line option, -u, to force stdout and stderr
to be unbuffered.

* Incorporated Steve Majewski's mods to import.c for dynamic loading
under AIX.

* Fewer chances of dumping core when trying to reload or re-import
static built-in, dynamically loaded built-in, or frozen modules.

* Loops over sequences now don't ask for the sequence's length when
they start, but try to access items 0, 1, 2, and so on until they hit
an IndexError.  This makes it possible to create classes that generate
infinite or indefinite sequences a la Steve Majewski.  This affects
for loops, the (not) in operator, and the built-in functions filter(),
map(), max(), min(), reduce().

Changed Built-in operations
---------------------------

* The '%' operator on strings (printf-style formatting) supports a new
feature (adapted from a patch by Donald Beaudry) to allow
'%(<key>)<format>' % {...} to take values from a dictionary by name
instead of from a tuple by position (see also the new function
vars()).

* The '%s' formatting operator is changed to accept any type and
convert it to a string using str().

* Dictionaries with more than 20,000 entries can now be created
(thanks to Steve Kirsch).

New Built-in Functions
----------------------

* vars() returns a dictionary containing the local variables; vars(m)
returns a dictionary containing the variables of module m.  Note:
dir(x) is now equivalent to vars(x).keys().

Changed Built-in Functions
--------------------------

* open() has an optional third argument to specify the buffer size: 0
for unbuffered, 1 for line buffered, >1 for explicit buffer size, <0
for default.

* open()'s second argument is now optional; it defaults to "r".

* apply() now checks that its second argument is indeed a tuple.

New Built-in Modules
--------------------

Changed Built-in Modules
------------------------

The thread module no longer supports exit_prog().

New Python Modules
------------------

* Module addpack contains a standard interface to modify sys.path to
find optional packages (groups of related modules).

* Module urllib contains a number of functions to access
World-Wide-Web files specified by their URL.

* Module httplib implements the client side of the HTTP protocol used
by World-Wide-Web servers.

* Module gopherlib implements the client side of the Gopher protocol.

* Module mailbox (by Jack Jansen) contains a parser for UNIX and MMDF
style mailbox files.

* Module random contains various random distributions, e.g. gauss().

* Module lockfile locks and unlocks open files using fcntl (inspired
by a similar module by Andy Bensky).

* Module ntpath (by Jaap Vermeulen) implements path operations for
Windows/NT.

* Module test_thread (in Lib/test) contains a small test set for the
thread module.

Changed Python Modules
----------------------

* The string module's expandvars() function is now documented and is
implemented in Python (using regular expressions) instead of forking
off a shell process.

* Module rfc822 now supports accessing the header fields using the
mapping/dictionary interface, e.g. h['subject'].

* Module pdb now makes it possible to set a break on a function
(syntax: break <expression>, where <expression> yields a function
object).

Changed Demos
-------------

* The Demo/scripts/freeze.py script is working again (thanks to Jaap
Vermeulen).

New Demos
---------

* Demo/threads/Generator.py is a proposed interface for restartable
functions a la Tim Peters.

* Demo/scripts/newslist.py, by Quentin Stafford-Fraser, generates a
directory full of HTML pages which between them contain links to all
the newsgroups available on your server.

* Demo/dns contains a DNS (Domain Name Server) client.

* Demo/lutz contains miscellaneous demos by Mark Lutz (e.g. psh.py, a
nice enhanced Python shell!!!).

* Demo/turing contains a Turing machine by Amrit Prem.

Documentation
-------------

* Documented new language features mentioned above (but not all new
modules).

* Added a chapter to the Tutorial describing recent additions to
Python.

* Clarified some sentences in the reference manual,
e.g. break/continue, local/global scope, slice assignment.

Source Structure
----------------

* Moved Include/tokenizer.h to Parser/tokenizer.h.

* Added Python/getopt.c for systems that don't have it.

Emacs mode
----------

* Indentation of continuated lines is done more intelligently;
consequently the variable py-continuation-offset is gone.


========================================
==> Release 1.0.1 (15 February 1994) <==
========================================

* Many portability fixes should make it painless to build Python on
several new platforms, e.g. NeXT, SEQUENT, WATCOM, DOS, and Windows.

* Fixed test for <stdarg.h> -- this broke on some platforms.

* Fixed test for shared library dynalic loading -- this broke on SunOS
4.x using the GNU loader.

* Changed order and number of SVR4 networking libraries (it is now
-lsocket -linet -lnsl, if these libraries exist).

* Installing the build intermediate stages with "make libainstall" now
also installs config.c.in, Setup and makesetup, which are used by the
new Extensions mechanism.

* Improved README file contains more hints and new troubleshooting
section.

* The built-in module strop now defines fast versions of three more
functions of the standard string module: atoi(), atol() and atof().
The strop versions of atoi() and atol() support an optional second
argument to specify the base (default 10).  NOTE: you don't have to
explicitly import strop to use the faster versions -- the string
module contains code to let versions from stop override the default
versions.

* There is now a working Lib/dospath.py for those who use Python under
DOS (or Windows).  Thanks, Jaap!

* There is now a working Modules/dosmodule.c for DOS (or Windows)
system calls.

* Lib.os.py has been reorganized (making it ready for more operating
systems).

* Lib/ospath.py is now obsolete (use os.path instead).

* Many fixes to the tutorial to make it match Python 1.0.  Thanks,
Tim!

* Fixed Doc/Makefile, Doc/README and various scripts there.

* Added missing description of fdopen to Doc/libposix.tex.

* Made cleanup() global, for the benefit of embedded applications.

* Added parsing of addresses and dates to Lib/rfc822.py.

* Small fixes to Lib/aifc.py, Lib/sunau.py, Lib/tzparse.py to make
them usable at all.

* New module Lib/wave.py reads RIFF (*.wav) audio files.

* Module Lib/filewin.py moved to Lib/stdwin/filewin.py where it
belongs.

* New options and comments for Modules/makesetup (used by new
Extension mechanism).

* Misc/HYPE contains text of announcement of 1.0.0 in comp.lang.misc
and elsewhere.

* Fixed coredump in filter(None, 'abcdefg').


=======================================
==> Release 1.0.0 (26 January 1994) <==
=======================================

As is traditional, so many things have changed that I can't pretend to
be complete in these release notes, but I'll try anyway :-)

Note that the very last section is labeled "remaining bugs".


Source organization and build process
-------------------------------------

* The sources have finally been split: instead of a single src
subdirectory there are now separate directories Include, Parser,
Grammar, Objects, Python and Modules.  Other directories also start
with a capital letter: Misc, Doc, Lib, Demo.

* A few extensions (notably Amoeba and X support) have been moved to a
separate subtree Extensions, which is no longer in the core
distribution, but separately ftp'able as extensions.tar.Z.  (The
distribution contains a placeholder Ext-dummy with a description of
the Extensions subtree as well as the most recent versions of the
scripts used there.)

* A few large specialized demos (SGI video and www) have been
moved to a separate subdirectory Demo2, which is no longer in the core
distribution, but separately ftp'able as demo2.tar.Z.

* Parts of the standard library have been moved to subdirectories:
there are now standard subdirectories stdwin, test, sgi and sun4.

* The configuration process has radically changed: I now use GNU
autoconf.  This makes it much easier to build on new Unix flavors, as
well as fully supporting VPATH (if your Make has it).  The scripts
Configure.py and Addmodule.sh are no longer needed.  Many source files
have been adapted in order to work with the symbols that the configure
script generated by autoconf defines (or not); the resulting source is
much more portable to different C compilers and operating systems,
even non Unix systems (a Mac port was done in an afternoon).  See the
toplevel README file for a description of the new build process.

* GNU readline (a slightly newer version) is now a subdirectory of the
Python toplevel.  It is still not automatically configured (being
totally autoconf-unaware :-).  One problem has been solved: typing
Control-C to a readline prompt will now work.  The distribution no
longer contains a "super-level" directory (above the python toplevel
directory), and dl, dl-dld and GNU dld are no longer part of the
Python distribution (you can still ftp them from
ftp.cwi.nl:/pub/dynload).

* The DOS functions have been taken out of posixmodule.c and moved
into a separate file dosmodule.c.

* There's now a separate file version.c which contains nothing but
the version number.

* The actual main program is now contained in config.c (unless NO_MAIN
is defined); pythonmain.c now contains a function realmain() which is
called from config.c's main().

* All files needed to use the built-in module md5 are now contained in
the distribution.  The module has been cleaned up considerably.


Documentation
-------------

* The library manual has been split into many more small latex files,
so it is easier to edit Doc/lib.tex file to create a custom library
manual, describing only those modules supported on your system.  (This
is not automated though.)

* A fourth manual has been added, titled "Extending and Embedding the
Python Interpreter" (Doc/ext.tex), which collects information about
the interpreter which was previously spread over several files in the
misc subdirectory.

* The entire documentation is now also available on-line for those who
have a WWW browser (e.g. NCSA Mosaic).  Point your browser to the URL
"http://www.cwi.nl/~guido/Python.html".


Syntax
------

* Strings may now be enclosed in double quotes as well as in single
quotes.  There is no difference in interpretation.  The repr() of
string objects will use double quotes if the string contains a single
quote and no double quotes.  Thanks to Amrit Prem for these changes!

* There is a new keyword 'exec'.  This replaces the exec() built-in
function.  If a function contains an exec statement, local variable
optimization is not performed for that particular function, thus
making assignment to local variables in exec statements less
confusing.  (As a consequence, os.exec and python.exec have been
renamed to execv.)

* There is a new keyword 'lambda'.  An expression of the form

	lambda <parameters> : <expression>

yields an anonymous function.  This is really only syntactic sugar;
you can just as well define a local function using

	def some_temporary_name(<parameters>): return <expression>

Lambda expressions are particularly useful in combination with map(),
filter() and reduce(), described below.  Thanks to Amrit Prem for
submitting this code (as well as map(), filter(), reduce() and
xrange())!


Built-in functions
------------------

* The built-in module containing the built-in functions is called
__builtin__ instead of builtin.

* New built-in functions map(), filter() and reduce() perform standard
functional programming operations (though not lazily):

- map(f, seq) returns a new sequence whose items are the items from
seq with f() applied to them.

- filter(f, seq) returns a subsequence of seq consisting of those
items for which f() is true.

- reduce(f, seq, initial) returns a value computed as follows:
	acc = initial
	for item in seq: acc = f(acc, item)
	return acc

* New function xrange() creates a "range object".  Its arguments are
the same as those of range(), and when used in a for loop a range
objects also behaves identical.  The advantage of xrange() over
range() is that its representation (if the range contains many
elements) is much more compact than that of range().  The disadvantage
is that the result cannot be used to initialize a list object or for
the "Python idiom" [RED, GREEN, BLUE] = range(3).  On some modern
architectures, benchmarks have shown that "for i in range(...): ..."
actually executes *faster* than "for i in xrange(...): ...", but on
memory starved machines like PCs running DOS range(100000) may be just
too big to be represented at all...

* Built-in function exec() has been replaced by the exec statement --
see above.


The interpreter
---------------

* Syntax errors are now not printed to stderr by the parser, but
rather the offending line and other relevant information are packed up
in the SyntaxError exception argument.  When the main loop catches a
SyntaxError exception it will print the error in the same format as
previously, but at the proper position in the stack traceback.

* You can now set a maximum to the number of traceback entries
printed by assigning to sys.tracebacklimit.  The default is 1000.

* The version number in .pyc files has changed yet again.

* It is now possible to have a .pyc file without a corresponding .py
file.  (Warning: this may break existing installations if you have an
old .pyc file lingering around somewhere on your module search path
without a corresponding .py file, when there is a .py file for a
module of the same name further down the path -- the new interpreter
will find the first .pyc file and complain about it, while the old
interpreter would ignore it and use the .py file further down.)

* The list sys.builtin_module_names is now sorted and also contains
the names of a few hardwired built-in modules (sys, __main__ and
__builtin__).

* A module can now find its own name by accessing the global variable
__name__.  Assigning to this variable essentially renames the module
(it should also be stored under a different key in sys.modules).
A neat hack follows from this: a module that wants to execute a main
program when called as a script no longer needs to compare
sys.argv[0]; it can simply do "if __name__ == '__main__': main()".

* When an object is printed by the print statement, its implementation
of str() is used.  This means that classes can define __str__(self) to
direct how their instances are printed.  This is different from
__repr__(self), which should define an unambigous string
representation of the instance.  (If __str__() is not defined, it
defaults to __repr__().)

* Functions and code objects can now be compared meaningfully.

* On systems supporting SunOS or SVR4 style shared libraries, dynamic
loading of modules using shared libraries is automatically configured.
Thanks to Bill Jansen and Denis Severson for contributing this change!


Built-in objects
----------------

* File objects have acquired a new method writelines() which is the
reverse of readlines().  (It does not actually write lines, just a
list of strings, but the symmetry makes the choice of name OK.)


Built-in modules
----------------

* Socket objects no longer support the avail() method.  Use the select
module instead, or use this function to replace it:

	def avail(f):
		import select
		return f in select.select([f], [], [], 0)[0]

* Initialization of stdwin is done differently.  It actually modifies
sys.argv (taking out the options the X version of stdwin recognizes)
the first time it is imported.

* A new built-in module parser provides a rudimentary interface to the
python parser.  Corresponding standard library modules token and symbol
defines the numeric values of tokens and non-terminal symbols.

* The posix module has acquired new functions setuid(), setgid(),
execve(), and exec() has been renamed to execv().

* The array module is extended with 8-byte object swaps, the 'i'
format character, and a reverse() method.  The read() and write()
methods are renamed to fromfile() and tofile().

* The rotor module has freed of portability bugs.  This introduces a
backward compatibility problem: strings encoded with the old rotor
module can't be decoded by the new version.

* For select.select(), a timeout (4th) argument of None means the same
as leaving the timeout argument out.

* Module strop (and hence standard library module string) has acquired
a new function: rindex().  Thanks to Amrit Prem!

* Module regex defines a new function symcomp() which uses an extended
regular expression syntax: parenthesized subexpressions may be labeled
using the form "\(<labelname>...\)", and the group() method can return
sub-expressions by name.  Thanks to Tracy Tims for these changes!

* Multiple threads are now supported on Solaris 2.  Thanks to Sjoerd
Mullender!


Standard library modules
------------------------

* The library is now split in several subdirectories: all stuff using
stdwin is in Lib/stdwin, all SGI specific (or SGI Indigo or GL) stuff
is in Lib/sgi, all Sun Sparc specific stuff is in Lib/sun4, and all
test modules are in Lib/test.  The default module search path will
include all relevant subdirectories by default.

* Module os now knows about trying to import dos.  It defines
functions execl(), execle(), execlp() and execvp().

* New module dospath (should be attacked by a DOS hacker though).

* All modules defining classes now define __init__() constructors
instead of init() methods.  THIS IS AN INCOMPATIBLE CHANGE!

* Some minor changes and bugfixes module ftplib (mostly Steve
Majewski's suggestions); the debug() method is renamed to
set_debuglevel().

* Some new test modules (not run automatically by testall though):
test_audioop, test_md5, test_rgbimg, test_select.

* Module string now defines rindex() and rfind() in analogy of index()
and find().  It also defines atof() and atol() (and corresponding
exceptions) in analogy to atoi().

* Added help() functions to modules profile and pdb.

* The wdb debugger (now in Lib/stdwin) now shows class or instance
variables on a double click.  Thanks to Sjoerd Mullender!

* The (undocumented) module lambda has gone -- you couldn't import it
any more, and it was basically more a demo than a library module...


Multimedia extensions
---------------------

* The optional built-in modules audioop and imageop are now standard
parts of the interpreter.  Thanks to Sjoerd Mullender and Jack Jansen
for contributing this code!

* There's a new operation in audioop: minmax().

* There's a new built-in module called rgbimg which supports portable
efficient reading of SGI RCG image files.  Thanks also to Paul
Haeberli for the original code!  (Who will contribute a GIF reader?)

* The module aifc is gone -- you should now always use aifc, which has
received a facelift.

* There's a new module sunau., for reading Sun (and NeXT) audio files.

* There's a new module audiodev which provides a uniform interface to
(SGI Indigo and Sun Sparc) audio hardware.

* There's a new module sndhdr which recognizes various sound files by
looking in their header and checking for various magic words.


Optimizations
-------------

* Most optimizations below can be configured by compile-time flags.
Thanks to Sjoerd Mullender for submitting these optimizations!

* Small integers (default -1..99) are shared -- i.e. if two different
functions compute the same value it is possible (but not
guaranteed!!!) that they return the same *object*.  Python programs
can detect this but should *never* rely on it.

* Empty tuples (which all compare equal) are shared in the same
manner.

* Tuples of size up to 20 (default) are put in separate free lists
when deallocated.

* There is a compile-time option to cache a string's hash function,
but this appeared to have a negligeable effect, and as it costs 4
bytes per string it is disabled by default.


Embedding Python
----------------

* The initialization interface has been simplified somewhat.  You now
only call "initall()" to initialize the interpreter.

* The previously announced renaming of externally visible identifiers
has not been carried out.  It will happen in a later release.  Sorry.


Miscellaneous bugs that have been fixed
---------------------------------------

* All known portability bugs.

* Version 0.9.9 dumped core in <listobject>.sort() which has been
fixed.  Thanks to Jaap Vermeulen for fixing this and posting the fix
on the mailing list while I was away!

* Core dump on a format string ending in '%', e.g. in the expression
'%' % None.

* The array module yielded a bogus result for concatenation (a+b would
yield a+a).

* Some serious memory leaks in strop.split() and strop.splitfields().

* Several problems with the nis module.

* Subtle problem when copying a class method from another class
through assignment (the method could not be called).


Remaining bugs
--------------

* One problem with 64-bit machines remains -- since .pyc files are
portable and use only 4 bytes to represent an integer object, 64-bit
integer literals are silently truncated when written into a .pyc file.
Work-around: use eval('123456789101112').

* The freeze script doesn't work any more.  A new and more portable
one can probably be cooked up using tricks from Extensions/mkext.py.

* The dos support hasn't been tested yet.  (Really Soon Now we should
have a PC with a working C compiler!)


===================================
==> Release 0.9.9 (29 Jul 1993) <==
===================================

I *believe* these are the main user-visible changes in this release,
but there may be others.  SGI users may scan the {src,lib}/ChangeLog
files for improvements of some SGI specific modules, e.g. aifc and
cl.  Developers of extension modules should also read src/ChangeLog.


Naming of C symbols used by the Python interpreter
--------------------------------------------------

* This is the last release using the current naming conventions.  New
naming conventions are explained in the file misc/NAMING.
Summarizing, all externally visible symbols get (at least) a "Py"
prefix, and most functions are renamed to the standard form
PyModule_FunctionName.

* Writers of extensions are urged to start using the new naming
conventions.  The next release will use the new naming conventions
throughout (it will also have a different source directory
structure).

* As a result of the preliminary work for the great renaming, many
functions that were accidentally global have been made static.


BETA X11 support
----------------

* There are now modules interfacing to the X11 Toolkit Intrinsics, the
Athena widgets, and the Motif 1.1 widget set.  These are not yet
documented except through the examples and README file in the demo/x11
directory.  It is expected that this interface will be replaced by a
more powerful and correct one in the future, which may or may not be
backward compatible.  In other words, this part of the code is at most
BETA level software!  (Note: the rest of Python is rock solid as ever!)

* I understand that the above may be a bit of a disappointment,
however my current schedule does not allow me to change this situation
before putting the release out of the door.  By releasing it
undocumented and buggy, at least some of the (working!) demo programs,
like itr (my Internet Talk Radio browser) become available to a larger
audience.

* There are also modules interfacing to SGI's "Glx" widget (a GL
window wrapped in a widget) and to NCSA's "HTML" widget (which can
format HyperText Markup Language, the document format used by the
World Wide Web).

* I've experienced some problems when building the X11 support.  In
particular, the Xm and Xaw widget sets don't go together, and it
appears that using X11R5 is better than using X11R4.  Also the threads
module and its link time options may spoil things.  My own strategy is
to build two Python binaries: one for use with X11 and one without
it, which can contain a richer set of built-in modules.  Don't even
*think* of loading the X11 modules dynamically...


Environmental changes
---------------------

* Compiled files (*.pyc files) created by this Python version are
incompatible with those created by the previous version.  Both
versions detect this and silently create a correct version, but it
means that it is not a good idea to use the same library directory for
an old and a new interpreter, since they will start to "fight" over
the *.pyc files...

* When a stack trace is printed, the exception is printed last instead
of first.  This means that if the beginning of the stack trace
scrolled out of your window you can still see what exception caused
it.

* Sometimes interrupting a Python operation does not work because it
hangs in a blocking system call.  You can now kill the interpreter by
interrupting it three times.  The second time you interrupt it, a
message will be printed telling you that the third interrupt will kill
the interpreter.  The "sys.exitfunc" feature still makes limited
clean-up possible in this case.


Changes to the command line interface
-------------------------------------

* The python usage message is now much more informative.

* New option -i enters interactive mode after executing a script --
useful for debugging.

* New option -k raises an exception when an expression statement
yields a value other than None.

* For each option there is now also a corresponding environment
variable.


Using Python as an embedded language
------------------------------------

* The distribution now contains (some) documentation on the use of
Python as an "embedded language" in other applications, as well as a
simple example.  See the file misc/EMBEDDING and the directory embed/.


Speed improvements
------------------

* Function local variables are now generally stored in an array and
accessed using an integer indexing operation, instead of through a
dictionary lookup.  (This compensates the somewhat slower dictionary
lookup caused by the generalization of the dictionary module.)


Changes to the syntax
---------------------

* Continuation lines can now *sometimes* be written without a
backslash: if the continuation is contained within nesting (), [] or
{} brackets the \ may be omitted.  There's a much improved
python-mode.el in the misc directory which knows about this as well.

* You can no longer use an empty set of parentheses to define a class
without base classes.  That is, you no longer write this:

	class Foo(): # syntax error
		...

You must write this instead:

	class Foo:
		...

This was already the preferred syntax in release 0.9.8 but many
people seemed not to have picked it up.  There's a Python script that
fixes old code: demo/scripts/classfix.py.

* There's a new reserved word: "access".  The syntax and semantics are
still subject of research and debate (as well as undocumented), but
the parser knows about the keyword so you must not use it as a
variable, function, or attribute name.


Changes to the semantics of the language proper
-----------------------------------------------

* The following compatibility hack is removed: if a function was
defined with two or more arguments, and called with a single argument
that was a tuple with just as many arguments, the items of this tuple
would be used as the arguments.  This is no longer supported.


Changes to the semantics of classes and instances
-------------------------------------------------

* Class variables are now also accessible as instance variables for
reading (assignment creates an instance variable which overrides the
class variable of the same name though).

* If a class attribute is a user-defined function, a new kind of
object is returned: an "unbound method".  This contains a pointer to
the class and can only be called with a first argument which is a
member of that class (or a derived class).

* If a class defines a method __init__(self, arg1, ...) then this
method is called when a class instance is created by the classname()
construct.  Arguments passed to classname() are passed to the
__init__() method.  The __init__() methods of base classes are not
automatically called; the derived __init__() method must call these if
necessary (this was done so the derived __init__() method can choose
the call order and arguments for the base __init__() methods).

* If a class defines a method __del__(self) then this method is called
when an instance of the class is about to be destroyed.  This makes it
possible to implement clean-up of external resources attached to the
instance.  As with __init__(), the __del__() methods of base classes
are not automatically called.  If __del__ manages to store a reference
to the object somewhere, its destruction is postponed; when the object
is again about to be destroyed its __del__() method will be called
again.

* Classes may define a method __hash__(self) to allow their instances
to be used as dictionary keys.  This must return a 32-bit integer.


Minor improvements
------------------

* Function and class objects now know their name (the name given in
the 'def' or 'class' statement that created them).

* Class instances now know their class name.


Additions to built-in operations
--------------------------------

* The % operator with a string left argument implements formatting
similar to sprintf() in C.  The right argument is either a single
value or a tuple of values.  All features of Standard C sprintf() are
supported except %p.

* Dictionaries now support almost any key type, instead of just
strings.  (The key type must be an immutable type or must be a class
instance where the class defines a method __hash__(), in order to
avoid losing track of keys whose value may change.)

* Built-in methods are now compared properly: when comparing x.meth1
and y.meth2, if x is equal to y and the methods are defined by the
same function, x.meth1 compares equal to y.meth2.


Additions to built-in functions
-------------------------------

* str(x) returns a string version of its argument.  If the argument is
a string it is returned unchanged, otherwise it returns `x`.

* repr(x) returns the same as `x`.  (Some users found it easier to
have this as a function.)

* round(x) returns the floating point number x rounded to a whole
number, represented as a floating point number.  round(x, n) returns x
rounded to n digits.

* hasattr(x, name) returns true when x has an attribute with the given
name.

* hash(x) returns a hash code (32-bit integer) of an arbitrary
immutable object's value.

* id(x) returns a unique identifier (32-bit integer) of an arbitrary
object.

* compile() compiles a string to a Python code object.

* exec() and eval() now support execution of code objects.


Changes to the documented part of the library (standard modules)
----------------------------------------------------------------

* os.path.normpath() (a.k.a. posixpath.normpath()) has been fixed so
the border case '/foo/..' returns '/' instead of ''.

* A new function string.find() is added with similar semantics to
string.index(); however when it does not find the given substring it
returns -1 instead of raising string.index_error.


Changes to built-in modules
---------------------------

* New optional module 'array' implements operations on sequences of
integers or floating point numbers of a particular size.  This is
useful to manipulate large numerical arrays or to read and write
binary files consisting of numerical data.

* Regular expression objects created by module regex now support a new
method named group(), which returns one or more \(...\) groups by number.
The number of groups is increased from 10 to 100.

* Function compile() in module regex now supports an optional mapping
argument; a variable casefold is added to the module which can be used
as a standard uppercase to lowercase mapping.

* Module time now supports many routines that are defined in the
Standard C time interface (<time.h>): gmtime(), localtime(),
asctime(), ctime(), mktime(), as well as these variables (taken from
System V): timezone, altzone, daylight and tzname.  (The corresponding
functions in the undocumented module calendar have been removed; the
undocumented and unfinished module tzparse is now obsolete and will
disappear in a future release.)

* Module strop (the fast built-in version of standard module string)
now uses C's definition of whitespace instead of fixing it to space,
tab and newline; in practice this usually means that vertical tab,
form feed and return are now also considered whitespace.  It exports
the string of characters that are considered whitespace as well as the
characters that are considered lowercase or uppercase.

* Module sys now defines the variable builtin_module_names, a list of
names of modules built into the current interpreter (including not
yet imported, but excluding two special modules that always have to be
defined -- sys and builtin).

* Objects created by module sunaudiodev now also support flush() and
close() methods.

* Socket objects created by module socket now support an optional
flags argument for their methods sendto() and recvfrom().

* Module marshal now supports dumping to and loading from strings,
through the functions dumps() and loads().

* Module stdwin now supports some new functionality.  You may have to
ftp the latest version: ftp.cwi.nl:/pub/stdwin/stdwinforviews.tar.Z.)


Bugs fixed
----------

* Fixed comparison of negative long integers.

* The tokenizer no longer botches input lines longer than BUFSIZ.

* Fixed several severe memory leaks in module select.

* Fixed memory leaks in modules socket and sv.

* Fixed memory leak in divmod() for long integers.

* Problems with definition of floatsleep() on Suns fixed.

* Many portability bugs fixed (and undoubtedly new ones added :-).


Changes to the build procedure
------------------------------

* The Makefile supports some new targets: "make default" and "make
all".  Both are by normally equivalent to "make python".

* The Makefile no longer uses $> since it's not supported by all
versions of Make.

* The header files now all contain #ifdef constructs designed to make
it safe to include the same header file twice, as well as support for
inclusion from C++ programs (automatic extern "C" { ... } added).


Freezing Python scripts
-----------------------

* There is now some support for "freezing" a Python script as a
stand-alone executable binary file.  See the script
demo/scripts/freeze.py.  It will require some site-specific tailoring
of the script to get this working, but is quite worthwhile if you write
Python code for other who may not have built and installed Python.


MS-DOS
------

* A new MS-DOS port has been done, using MSC 6.0 (I believe).  Thanks,
Marcel van der Peijl!  This requires fewer compatibility hacks in
posixmodule.c.  The executable is not yet available but will be soon
(check the mailing list).

* The default PYTHONPATH has changed.


Changes for developers of extension modules
-------------------------------------------

* Read src/ChangeLog for full details.


SGI specific changes
--------------------

* Read src/ChangeLog for full details.


==================================
==> Release 0.9.8 (9 Jan 1993) <==
==================================

I claim no completeness here, but I've tried my best to scan the log
files throughout my source tree for interesting bits of news.  A more
complete account of the changes is to be found in the various
ChangeLog files. See also "News for release 0.9.7beta" below if you're
still using release 0.9.6, and the file HISTORY if you have an even
older release.

	--Guido


Changes to the language proper
------------------------------

There's only one big change: the conformance checking for function
argument lists (of user-defined functions only) is stricter.  Earlier,
you could get away with the following:

	(a) define a function of one argument and call it with any
	    number of arguments; if the actual argument count wasn't
	    one, the function would receive a tuple containing the
	    arguments (an empty tuple if there were none).

	(b) define a function of two arguments, and call it with more
	    than two arguments; if there were more than two arguments,
	    the second argument would be passed as a tuple containing
	    the second and further actual arguments.

(Note that an argument (formal or actual) that is a tuple is counted as
one; these rules don't apply inside such tuples, only at the top level
of the argument list.)

Case (a) was needed to accommodate variable-length argument lists;
there is now an explicit "varargs" feature (precede the last argument
with a '*').  Case (b) was needed for compatibility with old class
definitions: up to release 0.9.4 a method with more than one argument
had to be declared as "def meth(self, (arg1, arg2, ...)): ...".
Version 0.9.6 provide better ways to handle both casees, bot provided
backward compatibility; version 0.9.8 retracts the compatibility hacks
since they also cause confusing behavior if a function is called with
the wrong number of arguments.

There's a script that helps converting classes that still rely on (b),
provided their methods' first argument is called "self":
demo/scripts/methfix.py.

If this change breaks lots of code you have developed locally, try
#defining COMPAT_HACKS in ceval.c.

(There's a third compatibility hack, which is the reverse of (a): if a
function is defined with two or more arguments, and called with a
single argument that is a tuple with just as many arguments, the items
of this tuple will be used as the arguments.  Although this can (and
should!) be done using the built-in function apply() instead, it isn't
withdrawn yet.)


One minor change: comparing instance methods works like expected, so
that if x is an instance of a user-defined class and has a method m,
then (x.m==x.m) yields 1.


The following was already present in 0.9.7beta, but not explicitly
mentioned in the NEWS file: user-defined classes can now define types
that behave in almost allrespects like numbers.  See
demo/classes/Rat.py for a simple example.


Changes to the build process
----------------------------

The Configure.py script and the Makefile has been made somewhat more
bullet-proof, after reports of (minor) trouble on certain platforms.

There is now a script to patch Makefile and config.c to add a new
optional built-in module: Addmodule.sh.  Read the script before using!

Using Addmodule.sh, all optional modules can now be configured at
compile time using Configure.py, so there are no modules left that
require dynamic loading.

The Makefile has been fixed to make it easier to use with the VPATH
feature of some Make versions (e.g. SunOS).


Changes affecting portability
-----------------------------

Several minor portability problems have been solved, e.g. "malloc.h"
has been renamed to "mymalloc.h", "strdup.c" is no longer used, and
the system now tolerates malloc(0) returning 0.

For dynamic loading on the SGI, Jack Jansen's dl 1.6 is now
distributed with Python.  This solves several minor problems, in
particular scripts invoked using #! can now use dynamic loading.


Changes to the interpreter interface
------------------------------------

On popular demand, there's finally a "profile" feature for interactive
use of the interpreter.  If the environment variable $PYTHONSTARTUP is
set to the name of an existing file, Python statements in this file
are executed when the interpreter is started in interactive mode.

There is a new clean-up mechanism, complementing try...finally: if you
assign a function object to sys.exitfunc, it will be called when
Python exits or receives a SIGTERM or SIGHUP signal.

The interpreter is now generally assumed to live in
/usr/local/bin/python (as opposed to /usr/local/python).  The script
demo/scripts/fixps.py will update old scripts in place (you can easily
modify it to do other similar changes).

Most I/O that uses sys.stdin/stdout/stderr will now use any object
assigned to those names as long as the object supports readline() or
write() methods.

The parser stack has been increased to 500 to accommodate more
complicated expressions (7 levels used to be the practical maximum,
it's now about 38).

The limit on the size of the *run-time* stack has completely been
removed -- this means that tuple or list displays can contain any
number of elements (formerly more than 50 would crash the
interpreter). 


Changes to existing built-in functions and methods
--------------------------------------------------

The built-in functions int(), long(), float(), oct() and hex() now
also apply to class instalces that define corresponding methods
(__int__ etc.).


New built-in functions
----------------------

The new functions str() and repr() convert any object to a string.
The function repr(x) is in all respects equivalent to `x` -- some
people prefer a function for this.  The function str(x) does the same
except if x is already a string -- then it returns x unchanged
(repr(x) adds quotes and escapes "funny" characters as octal escapes).

The new function cmp(x, y) returns -1 if x<y, 0 if x==y, 1 if x>y.


Changes to general built-in modules
-----------------------------------

The time module's functions are more general: time() returns a
floating point number and sleep() accepts one.  Their accuracies
depends on the precision of the system clock.  Millisleep is no longer
needed (although it still exists for now), but millitimer is still
needed since on some systems wall clock time is only available with
seconds precision, while a source of more precise time exists that
isn't synchronized with the wall clock.  (On UNIX systems that support
the BSD gettimeofday() function, time.time() is as time.millitimer().)

The string representation of a file object now includes an address:
'<file 'filename', mode 'r' at #######>' where ###### is a hex number
(the object's address) to make it unique.

New functions added to posix: nice(), setpgrp(), and if your system
supports them: setsid(), setpgid(), tcgetpgrp(), tcsetpgrp().

Improvements to the socket module: socket objects have new methods
getpeername() and getsockname(), and the {get,set}sockopt methods can
now get/set any kind of option using strings built with the new struct
module.  And there's a new function fromfd() which creates a socket
object given a file descriptor (useful for servers started by inetd,
which have a socket connected to stdin and stdout).


Changes to SGI-specific built-in modules
----------------------------------------

The FORMS library interface (fl) now requires FORMS 2.1a.  Some new
functions have been added and some bugs have been fixed.

Additions to al (audio library interface): added getname(),
getdefault() and getminmax().

The gl modules doesn't call "foreground()" when initialized (this
caused some problems) like it dit in 0.9.7beta (but not before).
There's a new gl function 'gversion() which returns a version string.

The interface to sv (Indigo video interface) has totally changed.
(Sorry, still no documentation, but see the examples in
demo/sgi/{sv,video}.)


Changes to standard library modules
-----------------------------------

Most functions in module string are now much faster: they're actually
implemented in C.  The module containing the C versions is called
"strop" but you should still import "string" since strop doesn't
provide all the interfaces defined in string (and strop may be renamed
to string when it is complete in a future release).

string.index() now accepts an optional third argument giving an index
where to start searching in the first argument, so you can find second
and further occurrences (this is similar to the regular expression
functions in regex).

The definition of what string.splitfields(anything, '') should return
is changed for the last time: it returns a singleton list containing
its whole first argument unchanged.  This is compatible with
regsub.split() which also ignores empty delimiter matches.

posixpath, macpath: added dirname() and normpath() (and basename() to
macpath).

The mainloop module (for use with stdwin) can now demultiplex input
from other sources, as long as they can be polled with select().


New built-in modules
--------------------

Module struct defines functions to pack/unpack values to/from strings
representing binary values in native byte order.

Module strop implements C versions of many functions from string (see
above).

Optional module fcntl defines interfaces to fcntl() and ioctl() --
UNIX only.  (Not yet properly documented -- see however src/fcntl.doc.)

Optional module mpz defines an interface to an altaernative long
integer implementation, the GNU MPZ library.

Optional module md5 uses the GNU MPZ library to calculate MD5
signatures of strings.

There are also optional new modules specific to SGI machines: imageop
defines some simple operations to images represented as strings; sv
interfaces to the Indigo video board; cl interfaces to the (yet
unreleased) compression library.


New standard library modules
----------------------------

(Unfortunately the following modules are not all documented; read the
sources to find out more about them!)

autotest: run testall without showing any output unless it differs
from the expected output

bisect: use bisection to insert or find an item in a sorted list

colorsys: defines conversions between various color systems (e.g. RGB
<-> YUV)

nntplib: a client interface to NNTP servers

pipes: utility to construct pipeline from templates, e.g. for
conversion from one file format to another using several utilities.

regsub: contains three functions that are more or less compatible with
awk functions of the same name: sub() and gsub() do string
substitution, split() splits a string using a regular expression to
define how separators are define.

test_types: test operations on the built-in types of Python

toaiff: convert various audio file formats to AIFF format

tzparse: parse the TZ environment parameter (this may be less general
than it could be, let me know if you fix it).

(Note that the obsolete module "path" no longer exists.)


New SGI-specific library modules
--------------------------------

CL: constants for use with the built-in compression library interface (cl)

Queue: a multi-producer, multi-consumer queue class implemented for
use with the built-in thread module

SOCKET: constants for use with built-in module socket, e.g. to set/get
socket options.  This is SGI-specific because the constants to be
passed are system-dependent.  You can generate a version for your own
system by running the script demo/scripts/h2py.py with
/usr/include/sys/socket.h as input.

cddb: interface to the database used by the CD player

torgb: convert various image file types to rgb format (requires pbmplus)


New demos
---------

There's an experimental interface to define Sun RPC clients and
servers in demo/rpc.

There's a collection of interfaces to WWW, WAIS and Gopher (both
Python classes and program providing a user interface) in demo/www.
This includes a program texi2html.py which converts texinfo files to
HTML files (the format used hy WWW).

The ibrowse demo has moved from demo/stdwin/ibrowse to demo/ibrowse.

For SGI systems, there's a whole collection of programs and classes
that make use of the Indigo video board in demo/sgi/{sv,video}.  This
represents a significant amount of work that we're giving away!

There are demos "rsa" and "md5test" that exercise the mpz and md5
modules, respectively.  The rsa demo is a complete implementation of
the RSA public-key cryptosystem!

A bunch of games and examples submitted by Stoffel Erasmus have been
included in demo/stoffel.

There are miscellaneous new files in some existing demo
subdirectories: classes/bitvec.py, scripts/{fixps,methfix}.py,
sgi/al/cmpaf.py, sockets/{mcast,gopher}.py.

There are also many minor changes to existing files, but I'm too lazy
to run a diff and note the differences -- you can do this yourself if
you save the old distribution's demos.  One highlight: the
stdwin/python.py demo is much improved!


Changes to the documentation
----------------------------

The LaTeX source for the library uses different macros to enable it to
be converted to texinfo, and from there to INFO or HTML format so it
can be browsed as a hypertext.  The net result is that you can now
read the Python library documentation in Emacs info mode!


Changes to the source code that affect C extension writers
----------------------------------------------------------

The function strdup() no longer exists (it was used only in one places
and is somewhat of a portability problem since some systems have the
same function in their C library.

The functions NEW() and RENEW() allocate one spare byte to guard
against a NULL return from malloc(0) being taken for an error, but
this should not be relied upon.


=========================
==> Release 0.9.7beta <==
=========================


Changes to the language proper
------------------------------

User-defined classes can now implement operations invoked through
special syntax, such as x[i] or `x` by defining methods named
__getitem__(self, i) or __repr__(self), etc.


Changes to the build process
----------------------------

Instead of extensive manual editing of the Makefile to select
compile-time options, you can now run a Configure.py script.
The Makefile as distributed builds a minimal interpreter sufficient to
run Configure.py.  See also misc/BUILD

The Makefile now includes more "utility" targets, e.g. install and
tags/TAGS

Using the provided strtod.c and strtol.c are now separate options, as
on the Sun the provided strtod.c dumps core :-(

The regex module is now an option chosen by the Makefile, since some
(old) C compilers choke on regexpr.c


Changes affecting portability
-----------------------------

You need STDWIN version 0.9.7 (released 30 June 1992) for the stdwin
interface

Dynamic loading is now supported for Sun (and other non-COFF systems)
throug dld-3.2.3, as well as for SGI (a new version of Jack Jansen's
DL is out, 1.4)

The system-dependent code for the use of the select() system call is
moved to one file: myselect.h

Thanks to Jaap Vermeulen, the code should now port cleanly to the
SEQUENT


Changes to the interpreter interface
------------------------------------

The interpretation of $PYTHONPATH in the environment is different: it
is inserted in front of the default path instead of overriding it


Changes to existing built-in functions and methods
--------------------------------------------------

List objects now support an optional argument to their sort() method,
which is a comparison function similar to qsort(3) in C

File objects now have a method fileno(), used by the new select module
(see below)


New built-in function
---------------------

coerce(x, y): take two numbers and return a tuple containing them
both converted to a common type


Changes to built-in modules
---------------------------

sys: fixed core dumps in settrace() and setprofile()

socket: added socket methods setsockopt() and getsockopt(); and
fileno(), used by the new select module (see below)

stdwin: added fileno() == connectionnumber(), in support of new module
select (see below)

posix: added get{eg,eu,g,u}id(); waitpid() is now a separate function.

gl: added qgetfd()

fl: added several new functions, fixed several obscure bugs, adapted
to FORMS 2.1


Changes to standard modules
---------------------------

posixpath: changed implementation of ismount()

string: atoi() no longer mistakes leading zero for octal number

...


New built-in modules
--------------------

Modules marked "dynamic only" are not configured at compile time but
can be loaded dynamically.  You need to turn on the DL or DLD option in
the Makefile for support dynamic loading of modules (this requires
external code).

select: interfaces to the BSD select() system call

dbm: interfaces to the (new) dbm library (dynamic only)

nis: interfaces to some NIS functions (aka yellow pages)

thread: limited form of multiple threads (sgi only)

audioop: operations useful for audio programs, e.g. u-LAW and ADPCM
coding (dynamic only)

cd: interface to Indigo SCSI CDROM player audio library (sgi only)

jpeg: read files in JPEG format (dynamic only, sgi only; needs
external code)

imgfile: read SGI image files (dynamic only, sgi only)

sunaudiodev: interface to sun's /dev/audio (dynamic only, sun only)

sv: interface to Indigo video library (sgi only)

pc: a minimal set of MS-DOS interfaces (MS-DOS only)

rotor: encryption, by Lance Ellinghouse (dynamic only)


New standard modules
--------------------

Not all these modules are documented.  Read the source:
lib/<modulename>.py.  Sometimes a file lib/<modulename>.doc contains
additional documentation.

imghdr: recognizes image file headers

sndhdr: recognizes sound file headers

profile: print run-time statistics of Python code

readcd, cdplayer: companion modules for built-in module cd (sgi only)

emacs: interface to Emacs using py-connect.el (see below).

SOCKET: symbolic constant definitions for socket options

SUNAUDIODEV: symbolic constant definitions for sunaudiodef (sun only)

SV: symbolic constant definitions for sv (sgi only)

CD: symbolic constant definitions for cd (sgi only)


New demos
---------

scripts/pp.py: execute Python as a filter with a Perl-like command
line interface

classes/: examples using the new class features

threads/: examples using the new thread module

sgi/cd/: examples using the new cd module


Changes to the documentation
----------------------------

The last-minute syntax changes of release 0.9.6 are now reflected
everywhere in the manuals

The reference manual has a new section (3.2) on implementing new kinds
of numbers, sequences or mappings with user classes

Classes are now treated extensively in the tutorial (chapter 9)

Slightly restructured the system-dependent chapters of the library
manual

The file misc/EXTENDING incorporates documentation for mkvalue() and
a new section on error handling

The files misc/CLASSES and misc/ERRORS are no longer necessary

The doc/Makefile now creates PostScript files automatically


Miscellaneous changes
---------------------

Incorporated Tim Peters' changes to python-mode.el, it's now version
1.06

A python/Emacs bridge (provided by Terrence M. Brannon) lets a Python
program running in an Emacs buffer execute Emacs lisp code.  The
necessary Python code is in lib/emacs.py.  The Emacs code is
misc/py-connect.el (it needs some external Emacs lisp code)


Changes to the source code that affect C extension writers
----------------------------------------------------------

New service function mkvalue() to construct a Python object from C
values according to a "format" string a la getargs()

Most functions from pythonmain.c moved to new pythonrun.c which is
in libpython.a.  This should make embedded versions of Python easier

ceval.h is split in eval.h (which needs compile.h and only declares
eval_code) and ceval.h (which doesn't need compile.hand declares the
rest)

ceval.h defines macros BGN_SAVE / END_SAVE for use with threads (to
improve the parallellism of multi-threaded programs by letting other
Python code run when a blocking system call or something similar is
made)

In structmember.[ch], new member types BYTE, CHAR and unsigned
variants have been added

New file xxmodule.c is a template for new extension modules.


==================================
==> Release 0.9.6 (6 Apr 1992) <==
==================================

Misc news in 0.9.6:
- Restructured the misc subdirectory
- Reference manual completed, library manual much extended (with indexes!)
- the GNU Readline library is now distributed standard with Python
- the script "../demo/scripts/classfix.py" fixes Python modules using old
  class syntax
- Emacs python-mode.el (was python.el) vastly improved (thanks, Tim!)
- Because of the GNU copyleft business I am not using the GNU regular
  expression implementation but a free re-implementation by Tatu Ylonen
  that recently appeared in comp.sources.misc (Bravo, Tatu!)

New features in 0.9.6:
- stricter try stmt syntax: cannot mix except and finally clauses on 1 try
- New module 'os' supplants modules 'mac' and 'posix' for most cases;
  module 'path' is replaced by 'os.path'
- os.path.split() return value differs from that of old path.split()
- sys.exc_type, sys.exc_value, sys.exc_traceback are set to the exception
  currently being handled
- sys.last_type, sys.last_value, sys.last_traceback remember last unhandled
  exception
- New function string.expandtabs() expands tabs in a string
- Added times() interface to posix (user & sys time of process & children)
- Added uname() interface to posix (returns OS type, hostname, etc.)
- New built-in function execfile() is like exec() but from a file
- Functions exec() and eval() are less picky about whitespace/newlines
- New built-in functions getattr() and setattr() access arbitrary attributes
- More generic argument handling in built-in functions (see "./EXTENDING")
- Dynamic loading of modules written in C or C++ (see "./DYNLOAD")
- Division and modulo for long and plain integers with negative operands
  have changed; a/b is now floor(float(a)/float(b)) and a%b is defined
  as a-(a/b)*b.  So now the outcome of divmod(a,b) is the same as
  (a/b, a%b) for integers.  For floats, % is also changed, but of course
  / is unchanged, and divmod(x,y) does not yield (x/y, x%y)...
- A function with explicit variable-length argument list can be declared
  like this: def f(*args): ...; or even like this: def f(a, b, *rest): ...
- Code tracing and profiling features have been added, and two source
  code debuggers are provided in the library (pdb.py, tty-oriented,
  and wdb, window-oriented); you can now step through Python programs!
  See sys.settrace() and sys.setprofile(), and "../lib/pdb.doc"
- '==' is now the only equality operator; "../demo/scripts/eqfix.py" is
  a script that fixes old Python modules
- Plain integer right shift now uses sign extension
- Long integer shift/mask operations now simulate 2's complement
  to give more useful results for negative operands
- Changed/added range checks for long/plain integer shifts
- Options found after "-c command" are now passed to the command in sys.argv
  (note subtle incompatibility with "python -c command -- -options"!)
- Module stdwin is better protected against touching objects after they've
  been closed; menus can now also be closed explicitly
- Stdwin now uses its own exception (stdwin.error)

New features in 0.9.5 (released as Macintosh application only, 2 Jan 1992):
- dictionary objects can now be compared properly; e.g., {}=={} is true
- new exception SystemExit causes termination if not caught;
  it is raised by sys.exit() so that 'finally' clauses can clean up,
  and it may even be caught.  It does work interactively!
- new module "regex" implements GNU Emacs style regular expressions;
  module "regexp" is rewritten in Python for backward compatibility
- formal parameter lists may contain trailing commas

Bugs fixed in 0.9.6:
- assigning to or deleting a list item with a negative index dumped core
- divmod(-10L,5L) returned (-3L, 5L) instead of (-2L, 0L)

Bugs fixed in 0.9.5:
- masking operations involving negative long integers gave wrong results


===================================
==> Release 0.9.4 (24 Dec 1991) <==
===================================

- new function argument handling (see below)
- built-in apply(func, args) means func(args[0], args[1], ...)
- new, more refined exceptions
- new exception string values (NameError = 'NameError' etc.)
- better checking for math exceptions
- for sequences (string/tuple/list), x[-i] is now equivalent to x[len(x)-i]
- fixed list assignment bug: "a[1:1] = a" now works correctly
- new class syntax, without extraneous parentheses
- new 'global' statement to assign global variables from within a function


New class syntax
----------------

You can now declare a base class as follows:

	class B:			# Was: class B():
		def some_method(self): ...
		...

and a derived class thusly:

	class D(B):			# Was: class D() = B():
		def another_method(self, arg): ...

Multiple inheritance looks like this:

	class M(B, D):			# Was: class M() = B(), D():
		def this_or_that_method(self, arg): ...

The old syntax is still accepted by Python 0.9.4, but will disappear
in Python 1.0 (to be posted to comp.sources).


New 'global' statement
----------------------

Every now and then you have a global variable in a module that you
want to change from within a function in that module -- say, a count
of calls to a function, or an option flag, etc.  Until now this was
not directly possible.  While several kludges are known that
circumvent the problem, and often the need for a global variable can
be avoided by rewriting the module as a class, this does not always
lead to clearer code.

The 'global' statement solves this dilemma.  Its occurrence in a
function body means that, for the duration of that function, the
names listed there refer to global variables.  For instance:

	total = 0.0
	count = 0

	def add_to_total(amount):
		global total, count
		total = total + amount
		count = count + 1

'global' must be repeated in each function where it is needed.  The
names listed in a 'global' statement must not be used in the function
before the statement is reached.

Remember that you don't need to use 'global' if you only want to *use*
a global variable in a function; nor do you need ot for assignments to
parts of global variables (e.g., list or dictionary items or
attributes of class instances).  This has not changed; in fact
assignment to part of a global variable was the standard workaround.


New exceptions
--------------

Several new exceptions have been defined, to distinguish more clearly
between different types of errors.

name			meaning					was

AttributeError		reference to non-existing attribute	NameError
IOError			unexpected I/O error			RuntimeError
ImportError		import of non-existing module or name	NameError
IndexError		invalid string, tuple or list index	RuntimeError
KeyError		key not in dictionary			RuntimeError
OverflowError		numeric overflow			RuntimeError
SyntaxError		invalid syntax				RuntimeError
ValueError		invalid argument value			RuntimeError
ZeroDivisionError	division by zero			RuntimeError

The string value of each exception is now its name -- this makes it
easier to experimentally find out which operations raise which
exceptions; e.g.:

	>>> KeyboardInterrupt
	'KeyboardInterrupt'
	>>>


New argument passing semantics
------------------------------

Off-line discussions with Steve Majewski and Daniel LaLiberte have
convinced me that Python's parameter mechanism could be changed in a
way that made both of them happy (I hope), kept me happy, fixed a
number of outstanding problems, and, given some backward compatibility
provisions, would only break a very small amount of existing code --
probably all mine anyway.  In fact I suspect that most Python users
will hardly notice the difference.  And yet it has cost me at least
one sleepless night to decide to make the change...

Philosophically, the change is quite radical (to me, anyway): a
function is no longer called with either zero or one argument, which
is a tuple if there appear to be more arguments.  Every function now
has an argument list containing 0, 1 or more arguments.  This list is
always implemented as a tuple, and it is a (run-time) error if a
function is called with a different number of arguments than expected.

What's the difference? you may ask.  The answer is, very little unless
you want to write variadic functions -- functions that may be called
with a variable number of arguments.  Formerly, you could write a
function that accepted one or more arguments with little trouble, but
writing a function that could be called with either 0 or 1 argument
(or more) was next to impossible.  This is now a piece of cake: you
can simply declare an argument that receives the entire argument
tuple, and check its length -- it will be of size 0 if there are no
arguments.

Another anomaly of the old system was the way multi-argument methods
(in classes) had to be declared, e.g.:

	class Point():
		def init(self, (x, y, color)): ...
		def setcolor(self, color): ...
		dev moveto(self, (x, y)): ...
		def draw(self): ...

Using the new scheme there is no need to enclose the method arguments
in an extra set of parentheses, so the above class could become:

	class Point:
		def init(self, x, y, color): ...
		def setcolor(self, color): ...
		dev moveto(self, x, y): ...
		def draw(self): ...

That is, the equivalence rule between methods and functions has
changed so that now p.moveto(x,y) is equivalent to Point.moveto(p,x,y)
while formerly it was equivalent to Point.moveto(p,(x,y)).

A special backward compatibility rule makes that the old version also
still works: whenever a function with exactly two arguments (at the top
level) is called with more than two arguments, the second and further
arguments are packed into a tuple and passed as the second argument.
This rule is invoked independently of whether the function is actually a
method, so there is a slight chance that some erroneous calls of
functions expecting two arguments with more than that number of
arguments go undetected at first -- when the function tries to use the
second argument it may find it is a tuple instead of what was expected.
Note that this rule will be removed from future versions of the
language; it is a backward compatibility provision *only*.

Two other rules and a new built-in function handle conversion between
tuples and argument lists:

Rule (a): when a function with more than one argument is called with a
single argument that is a tuple of the right size, the tuple's items
are used as arguments.

Rule (b): when a function with exactly one argument receives no
arguments or more than one, that one argument will receive a tuple
containing the arguments (the tuple will be empty if there were no
arguments).


A new built-in function, apply(), was added to support functions that
need to call other functions with a constructed argument list.  The call

	apply(function, tuple)

is equivalent to

	function(tuple[0], tuple[1], ..., tuple[len(tuple)-1])


While no new argument syntax was added in this phase, it would now be
quite sensible to add explicit syntax to Python for default argument
values (as in C++ or Modula-3), or a "rest" argument to receive the
remaining arguments of a variable-length argument list.


========================================================
==> Release 0.9.3 (never made available outside CWI) <==
========================================================

- string sys.version shows current version (also printed on interactive entry)
- more detailed exceptions, e.g., IOError, ZeroDivisionError, etc.
- 'global' statement to declare module-global variables assigned in functions.
- new class declaration syntax: class C(Base1, Base2, ...): suite
  (the old syntax is still accepted -- be sure to convert your classes now!)
- C shifting and masking operators: << >> ~ & ^ | (for ints and longs).
- C comparison operators: == != (the old = and <> remain valid).
- floating point numbers may now start with a period (e.g., .14).
- definition of integer division tightened (always truncates towards zero).
- new builtins hex(x), oct(x) return hex/octal string from (long) integer.
- new list method l.count(x) returns the number of occurrences of x in l.
- new SGI module: al (Indigo and 4D/35 audio library).
- the FORMS interface (modules fl and FL) now uses FORMS 2.0
- module gl: added lrect{read,write}, rectzoom and pixmode;
  added (non-GL) functions (un)packrect.
- new socket method: s.allowbroadcast(flag).
- many objects support __dict__, __methods__ or __members__.
- dir() lists anything that has __dict__.
- class attributes are no longer read-only.
- classes support __bases__, instances support __class__ (and __dict__).
- divmod() now also works for floats.
- fixed obscure bug in eval('1            ').


===================================
==> Release 0.9.2 (Autumn 1991) <==
===================================

Highlights
----------

- tutorial now (almost) complete; library reference reorganized
- new syntax: continue statement; semicolons; dictionary constructors;
  restrictions on blank lines in source files removed
- dramatically improved module load time through precompiled modules
- arbitrary precision integers: compute 2 to the power 1000 and more...
- arithmetic operators now accept mixed type operands, e.g., 3.14/4
- more operations on list: remove, index, reverse; repetition
- improved/new file operations: readlines, seek, tell, flush, ...
- process management added to the posix module: fork/exec/wait/kill etc.
- BSD socket operations (with example servers and clients!)
- many new STDWIN features (color, fonts, polygons, ...)
- new SGI modules: font manager and FORMS library interface


Extended list of changes in 0.9.2
---------------------------------

Here is a summary of the most important user-visible changes in 0.9.2,
in somewhat arbitrary order.  Changes in later versions are listed in
the "highlights" section above.


1. Changes to the interpreter proper

- Simple statements can now be separated by semicolons.
  If you write "if t: s1; s2", both s1 and s2 are executed
  conditionally.
- The 'continue' statement was added, with semantics as in C.
- Dictionary displays are now allowed on input: {key: value, ...}.
- Blank lines and lines bearing only a comment no longer need to
  be indented properly.  (A completely empty line still ends a multi-
  line statement interactively.)
- Mixed arithmetic is supported, 1 compares equal to 1.0, etc.
- Option "-c command" to execute statements from the command line
- Compiled versions of modules are cached in ".pyc" files, giving a
  dramatic improvement of start-up time
- Other, smaller speed improvements, e.g., extracting characters from
  strings, looking up single-character keys, and looking up global
  variables
- Interrupting a print operation raises KeyboardInterrupt instead of
  only cancelling the print operation
- Fixed various portability problems (it now passes gcc with only
  warnings -- more Standard C compatibility will be provided in later
  versions)
- Source is prepared for porting to MS-DOS
- Numeric constants are now checked for overflow (this requires
  standard-conforming strtol() and strtod() functions; a correct
  strtol() implementation is provided, but the strtod() provided
  relies on atof() for everything, including error checking


2. Changes to the built-in types, functions and modules

- New module socket: interface to BSD socket primitives
- New modules pwd and grp: access the UNIX password and group databases
- (SGI only:) New module "fm" interfaces to the SGI IRIX Font Manager
- (SGI only:) New module "fl" interfaces to Mark Overmars' FORMS library
- New numeric type: long integer, for unlimited precision
	- integer constants suffixed with 'L' or 'l' are long integers
	- new built-in function long(x) converts int or float to long
	- int() and float() now also convert from long integers
- New built-in function:
	- pow(x, y) returns x to the power y
- New operation and methods for lists:
	- l*n returns a new list consisting of n concatenated copies of l
	- l.remove(x) removes the first occurrence of the value x from l
	- l.index(x) returns the index of the first occurrence of x in l
	- l.reverse() reverses l in place
- New operation for tuples:
	- t*n returns a tuple consisting of n concatenated copies of t
- Improved file handling:
	- f.readline() no longer restricts the line length, is faster,
	  and isn't confused by null bytes; same for raw_input()
	- f.read() without arguments reads the entire (rest of the) file
	- mixing of print and sys.stdout.write() has different effect
- New methods for files:
	- f.readlines() returns a list containing the lines of the file,
	  as read with f.readline()
	- f.flush(), f.tell(), f.seek() call their stdio counterparts
	- f.isatty() tests for "tty-ness"
- New posix functions:
	- _exit(), exec(), fork(), getpid(), getppid(), kill(), wait()
	- popen() returns a file object connected to a pipe
	- utime() replaces utimes() (the latter is not a POSIX name)
- New stdwin features, including:
	- font handling
	- color drawing
	- scroll bars made optional
	- polygons
	- filled and xor shapes
	- text editing objects now have a 'settext' method


3. Changes to the standard library

- Name change: the functions path.cat and macpath.cat are now called
  path.join and macpath.join
- Added new modules: formatter, mutex, persist, sched, mainloop
- Added some modules and functionality to the "widget set" (which is
  still under development, so please bear with me):
	DirList, FormSplit, TextEdit, WindowSched
- Fixed module testall to work non-interactively
- Module string:
	- added functions join() and joinfields()
	- fixed center() to work correct and make it "transitive"
- Obsolete modules were removed: util, minmax
- Some modules were moved to the demo directory


4. Changes to the demonstration programs

- Added new useful scipts: byteyears, eptags, fact, from, lfact,
  objgraph, pdeps, pi, primes, ptags, which
- Added a bunch of socket demos
- Doubled the speed of ptags
- Added new stdwin demos: microedit, miniedit
- Added a windowing interface to the Python interpreter: python (most
  useful on the Mac)
- Added a browser for Emacs info files: demo/stdwin/ibrowse
  (yes, I plan to put all STDWIN and Python documentation in texinfo
  form in the future)


5. Other changes to the distribution

- An Emacs Lisp file "python.el" is provided to facilitate editing
  Python programs in GNU Emacs (slightly improved since posted to
  gnu.emacs.sources)
- Some info on writing an extension in C is provided
- Some info on building Python on non-UNIX platforms is provided


=====================================
==> Release 0.9.1 (February 1991) <==
=====================================

- Micro changes only
- Added file "patchlevel.h"


=====================================
==> Release 0.9.0 (February 1991) <==
=====================================

Original posting to alt.sources.
PK
%�\@^KP�P�NEWSnu�[���+++++++++++
Python News
+++++++++++

What's New in Python 2.7.16 final?
==================================

*Release date: 2019-03-02*

IDLE
----

- bpo-32129: Avoid blurry IDLE application icon on macOS with Tk 8.6. Patch
  by Kevin Walzer.


What's New in Python 2.7.16 release candidate 1?
================================================

*Release date: 2019-02-16*

Security
--------

- bpo-35746: [CVE-2019-5010] Fix a NULL pointer deref in ssl module. The
  cert parser did not handle CRL distribution points with empty DP or URI
  correctly. A malicious or buggy certificate can result into segfault.
  Vulnerability (TALOS-2018-0758) reported by Colin Read and Nicolas Edet of
  Cisco.

- bpo-16039: CVE-2013-1752: Change use of ``readline()`` in
  :class:`imaplib.IMAP4_SSL` to limit line length.

- bpo-28043: SSLContext has improved default settings: OP_NO_SSLv2,
  OP_NO_SSLv3, OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE,
  OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE and HIGH ciphers without MD5.

- bpo-34791: The xml.sax and xml.dom.domreg no longer use environment
  variables to override parser implementations when
  sys.flags.ignore_environment is set by -E or -I arguments.

- bpo-34623: CVE-2018-14647: The C accelerated _elementtree module now
  initializes hash randomization salt from _Py_HashSecret instead of
  libexpat's default CSPRNG.

- bpo-34540: When ``shutil.make_archive`` falls back to the external ``zip``
  problem, it uses :mod:`subprocess` to invoke it rather than
  :mod:`distutils.spawn`. This closes a possible shell injection vector.

- bpo-34405: Updated to OpenSSL 1.0.2p for Windows builds.

Core and Builtins
-----------------

- bpo-35552: Format character ``%s`` in :c:func:`PyString_FromFormat` no
  longer read memory past the limit if *precision* is specified.

- bpo-35504: Fix segfaults and :exc:`SystemError`\ s when deleting certain
  attributes. Patch by Zackery Spytz.

- bpo-35368: :c:func:`PyMem_Malloc` is now also thread-safe in debug mode.

- bpo-35214: Fixed an out of bounds memory access when parsing a truncated
  unicode escape sequence at the end of a string such as ``u'\N'``.  It
  would read one byte beyond the end of the memory allocation.

- bpo-34974: The :class:`bytearray` constructor no longer convert unexpected
  exceptions (e.g. :exc:`MemoryError` and :exc:`KeyboardInterrupt`) to
  :exc:`TypeError`.

- bpo-22851: Fix a segfault when accessing
  ``generator.gi_frame.f_restricted`` when the generator is exhausted.
  Patch by Zackery Spytz.

- bpo-18560: Fix potential NULL pointer dereference in sum().

- bpo-34400: Fix undefined behavior in parsetok.c.  Patch by Zackery Spytz.

- bpo-25083: Adding I/O error checking when reading .py files and aborting
  importing on error.

- bpo-25943: Fix potential heap corruption in the :mod:`bsddb` module.
  Patch by Zackery Spytz.

- bpo-34068: In :meth:`io.IOBase.close`, ensure that the
  :attr:`~io.IOBase.closed` attribute is not set with a live exception.
  Patch by Zackery Spytz and Serhiy Storchaka.

- bpo-34080: Fixed a memory leak in the compiler when it raised some
  uncommon errors during tokenizing.

- bpo-33956: Update vendored Expat library copy to version 2.2.5.

- bpo-30654: Fixed reset of the SIGINT handler to SIG_DFL on interpreter
  shutdown even when there was a custom handler set previously. Patch by
  Philipp Kerling.

- bpo-33645: Fixed an "unknown parsing error" on parsing the "<>" operator
  when run Python with both options ``-3`` and ``-We``.

- bpo-33622: Fixed a leak when the garbage collector fails to add an object
  with the ``__del__`` method or referenced by it into the
  :data:`gc.garbage` list. :c:func:`PyGC_Collect` can now be called when an
  exception is set and preserves it.

- bpo-33391: Fix a leak in set_symmetric_difference().

- bpo-25750: Fix rare Python crash due to bad refcounting in
  ``type_getattro()`` if a descriptor deletes itself from the class. Patch
  by Jeroen Demeyer.

- bpo-25862: Fix assertion failures in the ``tell()`` method of
  ``io.TextIOWrapper``. Patch by Zackery Spytz.

Library
-------

- bpo-8765: The write() method of buffered and unbuffered binary streams in
  the io module emits now a DeprecationWarning in Py3k mode for unicode
  argument.

- bpo-35052: Fix xml.dom.minidom cloneNode() on a document with an entity:
  pass the correct arguments to the user data handler of an entity.

- bpo-10496: :func:`~distutils.utils.check_environ` of
  :mod:`distutils.utils` now catchs :exc:`KeyError` on calling
  :func:`pwd.getpwuid`: don't create the ``HOME`` environment variable in
  this case.

- bpo-10496: :func:`posixpath.expanduser` now returns the input *path*
  unchanged if the ``HOME`` environment variable is not set and the current
  user has no home directory (if the current user identifier doesn't exist
  in the password database). This change fix the :mod:`site` module if the
  current user doesn't exist in the password database (if the user has no
  home directory).

- bpo-24746: Avoid stripping trailing whitespace in doctest fancy diff.
  Orignial patch by R. David Murray & Jairo Trad. Enhanced by Sanyam
  Khurana.

- bpo-35277: Update ensurepip to install pip 18.1 and setuptools 40.6.2.

- bpo-35062: Fix incorrect parsing of
  :class:`_io.IncrementalNewlineDecoder`'s *translate* argument.

- bpo-35079: Improve difflib.SequenceManager.get_matching_blocks doc by
  adding 'non- overlapping' and changing '!=' to '<'.

- bpo-35017: :meth:`socketserver.BaseServer.serve_forever` now exits
  immediately if it's :meth:`~socketserver.BaseServer.shutdown` method is
  called while it is polling for new events.

- bpo-34794: Fixed a leak in Tkinter when pass the Python wrapper around
  Tcl_Obj back to Tcl/Tk.

- bpo-23420: Verify the value for the parameter '-s' of the cProfile CLI.
  Patch by Robert Kuska

- bpo-16965: The :term:`2to3` :2to3fixer:`execfile` fixer now opens the file
  with mode ``'rb'``.  Patch by Zackery Spytz.

- bpo-34936: Fix ``TclError`` in ``tkinter.Spinbox.selection_element()``.
  Patch by Juliette Monsel.

- bpo-34866: Adding ``max_num_fields`` to ``cgi.FieldStorage`` to make DOS
  attacks harder by limiting the number of ``MiniFieldStorage`` objects
  created by ``FieldStorage``.

- bpo-34738: ZIP files created by :mod:`distutils` will now include entries
  for directories.

- bpo-34652: Ensure :func:`os.lchmod` is never defined on Linux.

- bpo-34625: Update vendorized expat library version to 2.2.6.

- bpo-34610: Fixed iterator of :class:`multiprocessing.managers.DictProxy`.

- bpo-34530: ``distutils.spawn.find_executable()`` now falls back on
  :data:`os.defpath` if the ``PATH`` environment variable is not set.

- bpo-34472: Improved compatibility for streamed files in :mod:`zipfile`.
  Previously an optional signature was not being written and certain ZIP
  applications were not supported. Patch by Silas Sewell.

- bpo-6700: Fix inspect.getsourcelines for module level frames/tracebacks.
  Patch by Vladimir Matveev.

- bpo-31715: Associate ``.mjs`` file extension with
  ``application/javascript`` MIME Type.

- bpo-32947: Add OP_ENABLE_MIDDLEBOX_COMPAT and test workaround for TLSv1.3
  for future compatibility with OpenSSL 1.1.1.

- bpo-34341: Appending to the ZIP archive with the ZIP64 extension no longer
  grows the size of extra fields of existing entries.

- bpo-34052: :meth:`sqlite3.Connection.create_aggregate`,
  :meth:`sqlite3.Connection.create_function`,
  :meth:`sqlite3.Connection.set_authorizer`,
  :meth:`sqlite3.Connection.set_progress_handler` methods raises TypeError
  when unhashable objects are passed as callable. These methods now don't
  pass such objects to SQLite API. Previous behavior could lead to
  segfaults. Patch by Sergey Fedoseev.

- bpo-34019: webbrowser: Correct the arguments passed to Opera Browser when
  opening a new URL using the ``webbrowser`` module. Patch by Bumsik Kim.

- bpo-33974: Fixed passing lists and tuples of strings containing special
  characters ``"``, ``\``, ``{``, ``}`` and ``\n`` as options to
  :mod:`~tkinter.ttk` widgets.

- bpo-26544: Fixed implementation of :func:`platform.libc_ver`. It almost
  always returned version '2.9' for glibc.

- bpo-33767: The concatenation (``+``) and repetition (``*``) sequence
  operations now raise :exc:`TypeError` instead of :exc:`SystemError` when
  performed on :class:`mmap.mmap` objects.  Patch by Zackery Spytz.

- bpo-11874: Use a better regex when breaking usage into wrappable parts.
  Avoids bogus assertion errors from custom metavar strings.

- bpo-33570: Change TLS 1.3 cipher suite settings for compatibility with
  OpenSSL 1.1.1-pre6 and newer. OpenSSL 1.1.1 will have TLS 1.3 cipers
  enabled by default.

- bpo-33542: Prevent ``uuid.get_node`` from using a DUID instead of a MAC on
  Windows. Patch by Zvi Effron

- bpo-33096: Removed unintentionally backported from Python 3 Tkinter files.

- bpo-20087: Updated alias mapping with glibc 2.27 supported locales.

- bpo-33422: Fix trailing quotation marks getting deleted when looking up
  byte/string literals on pydoc. Patch by Andrés Delfino.

- bpo-33336: ``imaplib`` now allows ``MOVE`` command in ``IMAP4.uid()`` (RFC
  6851: IMAP MOVE Extension) and potentially as a name of supported method
  of ``IMAP4`` object.

- bpo-33359: Fix running ``python -m curses.has_key``.

- bpo-33131: Upgrade bundled version of pip to 10.0.1.

- bpo-33308: Fixed a crash in the :mod:`parser` module when converting an ST
  object to a tree of tuples or lists with ``line_info=False`` and
  ``col_info=True``.

- bpo-33256: Fix display of ``<module>`` call in the html produced by
  ``cgitb.html()``. Patch by Stéphane Blondon.

- bpo-32861: The urllib.robotparser's ``__str__`` representation now
  includes wildcard entries and the "Crawl-delay" and "Request-rate" fields.
  Patch by Michael Lazar.

- bpo-33038: gzip.GzipFile no longer produces an AttributeError exception
  when used with a file object with a non-string name attribute. Patch by Bo
  Bayles.

- bpo-32857: In :mod:`tkinter`, ``after_cancel(None)`` now raises a
  :exc:`ValueError` instead of canceling the first scheduled function.
  Patch by Cheryl Sabella.

- bpo-32502: uuid.uuid1 no longer raises an exception if a 64-bit hardware
  address is encountered.

- bpo-31608: Raise a ``TypeError`` instead of crashing if a
  ``collections.deque`` subclass returns a non-deque from ``__new__``. Patch
  by Oren Milman.

- bpo-16865: Support arrays >=2GiB in :mod:`ctypes`.  Patch by Segev Finer.

- bpo-29456: Fix bugs in hangul normalization: u1176, u11a7 and u11c3

Documentation
-------------

- bpo-35035: Rename documentation for :mod:`email.utils` to
  ``email.utils.rst``.

- bpo-34967: Use app.add_object_type() instead of the deprecated Sphinx
  function app.description_unit()

- bpo-13407: Add a note to :mod:`bz2` and :mod:`tarfile` stating that
  handling of multi-stream bzip2 files is not supported.

- bpo-33503: Fix broken pypi link

Tests
-----

- bpo-34279: :func:`test.support.run_unittest` no longer raise
  :exc:`TestDidNotRun` if the test result contains skipped tests. The
  exception is now only raised if no test have been run and no test have
  been skipped.

- bpo-34279: regrtest issue a warning when no tests have been executed in a
  particular test file. Also, a new final result state is issued if no test
  have been executed across all test files. Patch by Pablo Galindo.

- bpo-34661: Fix test_shutil if unzip doesn't support -t.

- bpo-34542: Use 3072 RSA keys and SHA-256 signature for test certs and
  keys.

- bpo-34391: Fix ftplib test for TLS 1.3 by reading from data socket.

- bpo-34399: Update all RSA keys and DH params to use at least 2048 bits.

- bpo-33901: Fix test_gdbm on macOS with gdbm 1.15: add a larger value to
  make sure that the file size changes.

- bpo-33873: Fix a bug in ``regrtest`` that caused an extra test to run if
  --huntrleaks/-R was used. Exit with error in case that invalid parameters
  are specified to --huntrleaks/-R (at least one warmup run and one
  repetition must be used).

- bpo-29512: Rename Lib/test/bisect.py to Lib/test/bisect_cmd.py. The old
  name was in conflict with Lib/bisect.py, causing test failures, depending
  how tests were run.

- bpo-32962: Fixed test_gdb when Python is compiled with flags -mcet
  -fcf-protection -O0.

- bpo-33354: Skip ``test_ssl.test_load_dh_params`` when Python filesystem
  encoding cannot encode the provided path.

- bpo-19417: Add test_bdb.py.

Build
-----

- bpo-35139: Fix a compiler error when statically linking `pyexpat` in
  `Modules/Setup`.

- bpo-34710: Fixed SSL module build with OpenSSL & pedantic CFLAGS.

- bpo-33015: Fix an undefined behaviour in the pthread implementation of
  :c:func:`PyThread_start_new_thread`: add a function wrapper to always
  return ``NULL``.

- bpo-30345: Add -g to LDFLAGS when compiling with LTO to get debug symbols.

Windows
-------

- bpo-35401: Updates Windows build to OpenSSL 1.0.2q

- bpo-34603: Fix returning structs from functions produced by MSVC

- bpo-33711: Fixed licence generation error when building the installer.

macOS
-----

- bpo-15663: The macOS 10.6+ installer now provides a private copy of Tcl/Tk
  8.6, like the 10.9+ installer does.

- bpo-35401: Update macOS installer to use OpenSSL 1.0.2q.

- bpo-34405: Update to OpenSSL 1.0.2p for macOS installer builds.

IDLE
----

- bpo-34275: Make IDLE calltips always visible on Mac. Some MacOS-tk
  combinations need .update_idletasks(). Patch by Kevin Walzer.

- bpo-34120: Fix unresponsiveness after closing certain windows and dialogs.

- bpo-33856: Add "help" in the welcome message of IDLE

- bpo-31500: Default fonts now are scaled on HiDPI displays.

Tools/Demos
-----------

- bpo-34989: python-gdb.py now handles errors on computing the line number
  of a Python frame.

- bpo-34500: Fix 2 ResourceWarning in difflib.py. Patch by Mickaël
  Schoentgen.

- bpo-29367: python-gdb.py now supports also method-wrapper (wrapperobject)
  objects.

- bpo-32962: python-gdb now catchs ``UnicodeDecodeError`` exceptions when
  calling ``string()``.

- bpo-32962: python-gdb now catchs ValueError on read_var(): when Python has
  no debug symbols for example.

C API
-----

- bpo-33817: Fixed :c:func:`_PyString_Resize` and
  :c:func:`_PyUnicode_Resize` for empty strings. This fixed also
  :c:func:`PyString_FromFormat` and :c:func:`PyUnicode_FromFormat` when they
  return an empty string (e.g. ``PyString_FromFormat("%s", "")``).

- bpo-34229: Check start and stop of slice object to be long when they are
  not int in :c:func:`PySlice_GetIndices`.

- bpo-23927: Fixed :exc:`SystemError` in
  :c:func:`PyArg_ParseTupleAndKeywords` when the ``w*`` format unit is used
  for optional parameter.


What's New in Python 2.7.15 final?
==================================

*Release date: 2018-04-29*

Core and Builtins
-----------------

- bpo-33374: Tweak the definition of PyGC_Head, so compilers do not believe
  it is always 16-byte aligned on x86. This prevents crashes with more
  aggressive optimizations present in GCC 8.


What's New in Python 2.7.15 release candidate 1?
================================================

*Release date: 2018-04-14*

Security
--------

- bpo-32997: A regex in fpformat was vulnerable to catastrophic
  backtracking. This regex was a potential DOS vector (REDOS). Based on
  typical uses of fpformat the risk seems low. The regex has been refactored
  and is now safe. Patch by Jamie Davis.

- bpo-32981: Regexes in difflib and poplib were vulnerable to catastrophic
  backtracking. These regexes formed potential DOS vectors (REDOS). They
  have been refactored. This resolves CVE-2018-1060 and CVE-2018-1061. Patch
  by Jamie Davis.

- bpo-31339: Rewrite time.asctime() and time.ctime(). Backport and adapt the
  _asctime() function from the master branch to not depend on the
  implementation of asctime() and ctime() from the external C library. This
  change fixes a bug when Python is run using the musl C library.

- bpo-30730: Prevent environment variables injection in subprocess on
  Windows.  Prevent passing other environment variables and command
  arguments.

- bpo-30694: Upgrade expat copy from 2.2.0 to 2.2.1 to get fixes of multiple
  security vulnerabilities including: CVE-2017-9233 (External entity
  infinite loop DoS), CVE-2016-9063 (Integer overflow, re-fix),
  CVE-2016-0718 (Fix regression bugs from 2.2.0's fix to CVE-2016-0718) and
  CVE-2012-0876 (Counter hash flooding with SipHash). Note: the
  CVE-2016-5300 (Use os-specific entropy sources like getrandom) doesn't
  impact Python, since Python already gets entropy from the OS to set the
  expat secret using ``XML_SetHashSalt()``.

- bpo-30500: Fix urllib.splithost() to correctly parse fragments. For
  example, ``splithost('//127.0.0.1#@evil.com/')`` now correctly returns the
  ``127.0.0.1`` host, instead of treating ``@evil.com`` as the host in an
  authentification (``login@host``).

- bpo-29591: Update expat copy from 2.1.1 to 2.2.0 to get fixes of
  CVE-2016-0718 and CVE-2016-4472. See
  https://sourceforge.net/p/expat/bugs/537/ for more information.

Core and Builtins
-----------------

- bpo-33026: Fixed jumping out of "with" block by setting f_lineno.

- bpo-17288: Prevent jumps from 'return' and 'exception' trace events.

- bpo-18533: ``repr()`` on a dict containing its own ``viewvalues()`` or
  ``viewitems()`` no longer raises ``RuntimeError``.  Instead, use ``...``,
  as for other recursive structures.  Patch by Ben North.

- bpo-10544: Yield expressions are now deprecated in comprehensions and
  generator expressions when checking Python 3 compatibility. They are still
  permitted in the definition of the outermost iterable, as that is
  evaluated directly in the enclosing scope.

- bpo-32137: The repr of deeply nested dict now raises a RecursionError
  instead of crashing due to a stack overflow.

- bpo-20047: Bytearray methods partition() and rpartition() now accept only
  bytes-like objects as separator, as documented.  In particular they now
  raise TypeError rather of returning a bogus result when an integer is
  passed as a separator.

- bpo-31733: Add a new PYTHONSHOWREFCOUNT environment variable. In debug
  mode, Python now only print the total reference count if
  PYTHONSHOWREFCOUNT is set.

- bpo-31692: Add a new PYTHONSHOWALLOCCOUNT environment variable. When
  Python is compiled with COUNT_ALLOCS, PYTHONSHOWALLOCCOUNT now has to be
  set to dump allocation counts into stderr on shutdown. Moreover,
  allocations statistics are now dumped into stderr rather than stdout.

- bpo-31478: Prevent unwanted behavior in `_random.Random.seed()` in case
  the argument has a bad ``__abs__()`` method. Patch by Oren Milman.

- bpo-31530: Fixed crashes when iterating over a file on multiple threads.

- bpo-31490: Fix an assertion failure in `ctypes` class definition, in case
  the class has an attribute whose name is specified in ``_anonymous_`` but
  not in ``_fields_``. Patch by Oren Milman.

- bpo-31411: Raise a TypeError instead of SystemError in case
  warnings.onceregistry is not a dictionary. Patch by Oren Milman.

- bpo-31343: Include sys/sysmacros.h for major(), minor(), and makedev().
  GNU C libray plans to remove the functions from sys/types.h.

- bpo-31311: Fix a crash in the ``__setstate__()`` method of
  `ctypes._CData`, in case of a bad ``__dict__``. Patch by Oren Milman.

- bpo-31243: Fix a crash in some methods of `io.TextIOWrapper`, when the
  decoder's state is invalid. Patch by Oren Milman.

- bpo-31095: Fix potential crash during GC caused by ``tp_dealloc`` which
  doesn't call ``PyObject_GC_UnTrack()``.

- bpo-30657: Fixed possible integer overflow in PyString_DecodeEscape. Patch
  by Jay Bosamiya.

- bpo-27945: Fixed various segfaults with dict when input collections are
  mutated during searching, inserting or comparing.  Based on patches by
  Duane Griffin and Tim Mitchell.

- bpo-25794: Fixed type.__setattr__() and type.__delattr__() for
  non-interned or unicode attribute names.  Based on patch by Eryk Sun.

- bpo-29935: Fixed error messages in the index() method of tuple and list
  when pass indices of wrong type.

- bpo-28598: Support __rmod__ for subclasses of str being called before
  str.__mod__. Patch by Martijn Pieters.

- bpo-29602: Fix incorrect handling of signed zeros in complex constructor
  for complex subclasses and for inputs having a __complex__ method. Patch
  by Serhiy Storchaka.

- bpo-29347: Fixed possibly dereferencing undefined pointers when creating
  weakref objects.

- bpo-14376: Allow sys.exit to accept longs as well as ints. Patch by Gareth
  Rees.

- bpo-29028: Fixed possible use-after-free bugs in the subscription of the
  buffer object with custom index object.

- bpo-29145: Fix overflow checks in string, bytearray and unicode. Patch by
  jan matejek and Xiang Zhang.

- bpo-28932: Do not include <sys/random.h> if it does not exist.

Library
-------

- bpo-33096: Allow ttk.Treeview.insert to insert iid that has a false
  boolean value. Note iid=0 and iid=False would be same. Patch by Garvit
  Khatri.

- bpo-33127: The ssl module now compiles with LibreSSL 2.7.1.

- bpo-30622: The ssl module now detects missing NPN support in LibreSSL.

- bpo-21060: Rewrite confusing message from setup.py upload from "No dist
  file created in earlier command" to the more helpful "Must create and
  upload files in one command".

- bpo-30157: Fixed guessing quote and delimiter in csv.Sniffer.sniff() when
  only the last field is quoted.  Patch by Jake Davis.

- bpo-32647: The ctypes module used to depend on indirect linking for
  dlopen. The shared extension is now explicitly linked against libdl on
  platforms with dl.

- bpo-32304: distutils' upload command no longer corrupts tar files ending
  with a CR byte, and no longer tries to convert CR to CRLF in any of the
  upload text fields.

- bpo-31848: Fix the error handling in Aifc_read.initfp() when the SSND
  chunk is not found. Patch by Zackery Spytz.

- bpo-32521: The nis module is now compatible with new libnsl and headers
  location.

- bpo-32539: Fix ``OSError`` for ``os.listdir`` with deep paths (starting
  with ``\\?\``) on windows.  Patch by Anthony Sottile.

- bpo-32521: glibc has removed Sun RPC. Use replacement libtirpc headers and
  library in nis module.

- bpo-18035: ``telnetlib``: ``select.error`` doesn't have an ``errno``
  attribute. Patch by Segev Finer.

- bpo-32185: The SSL module no longer sends IP addresses in SNI TLS
  extension on platforms with OpenSSL 1.0.2+ or inet_pton.

- bpo-32186: Creating io.FileIO() and builtin file() objects now release the
  GIL when checking the file descriptor. io.FileIO.readall(),
  io.FileIO.read(), and file.read() now release the GIL when getting the
  file size.  Fixed hang of all threads with inaccessible NFS server.  Patch
  by Nir Soffer.

- bpo-32110: ``codecs.StreamReader.read(n)`` now returns not more than *n*
  characters/bytes for non-negative *n*. This makes it compatible with
  ``read()`` methods of other file-like objects.

- bpo-21149: Silence a `'NoneType' object is not callable` in
  `_removeHandlerRef` error that could happen when a logging Handler is
  destroyed as part of cyclic garbage collection during process shutdown.

- bpo-31764: Prevent a crash in ``sqlite3.Cursor.close()`` in case the
  ``Cursor`` object is uninitialized. Patch by Oren Milman.

- bpo-31955: Fix CCompiler.set_executable() of distutils to handle properly
  Unicode strings.

- bpo-9678: Fixed determining the MAC address in the uuid module:

  * Using ifconfig on NetBSD and OpenBSD.
  * Using arp on Linux, FreeBSD, NetBSD and OpenBSD.

  Based on patch by Takayuki Shimizukawa.

- bpo-30057: Fix potential missed signal in signal.signal().

- bpo-31927: Fixed reading arbitrary data when parse a AF_BLUETOOTH address
  on NetBSD and DragonFly BSD.

- bpo-27666: Fixed stack corruption in curses.box() and curses.ungetmouse()
  when the size of types chtype or mmask_t is less than the size of C long.
  curses.box() now accepts characters as arguments.  Based on patch by Steve
  Fink.

- bpo-25720: Fix the method for checking pad state of curses WINDOW. Patch
  by Masayuki Yamamoto.

- bpo-31893: Fixed the layout of the kqueue_event structure on OpenBSD and
  NetBSD. Fixed the comparison of the kqueue_event objects.

- bpo-31891: Fixed building the curses module on NetBSD.

- bpo-30058: Fixed buffer overflow in select.kqueue.control().

- bpo-31770: Prevent a crash when calling the ``__init__()`` method of a
  ``sqlite3.Cursor`` object more than once. Patch by Oren Milman.

- bpo-31728: Prevent crashes in `_elementtree` due to unsafe cleanup of
  `Element.text` and `Element.tail`. Patch by Oren Milman.

- bpo-31752: Fix possible crash in timedelta constructor called with custom
  integers.

- bpo-31681: Fix pkgutil.get_data to avoid leaking open files.

- bpo-31675: Fixed memory leaks in Tkinter's methods splitlist() and split()
  when pass a string larger than 2 GiB.

- bpo-30806: Fix the string representation of a netrc object.

- bpo-30347: Stop crashes when concurrently iterate over itertools.groupby()
  iterators.

- bpo-25732: `functools.total_ordering()` now implements the `__ne__`
  method.

- bpo-31351: python -m ensurepip now exits with non-zero exit code if pip
  bootstrapping has failed.

- bpo-31544: The C accelerator module of ElementTree ignored exceptions
  raised when looking up TreeBuilder target methods in XMLParser().

- bpo-31455: The C accelerator module of ElementTree ignored exceptions
  raised when looking up TreeBuilder target methods in XMLParser().

- bpo-25404: SSLContext.load_dh_params() now supports non-ASCII path.

- bpo-28958: ssl.SSLContext() now uses OpenSSL error information when a
  context cannot be instantiated.

- bpo-27448: Work around a `gc.disable()` race condition in the `subprocess`
  module that could leave garbage collection disabled when multiple threads
  are spawning subprocesses at once.  Users are *strongly encouraged* to use
  the `subprocess32` module from PyPI on Python 2.7 instead, it is much more
  reliable.

- bpo-31170: expat: Update libexpat from 2.2.3 to 2.2.4. Fix copying of
  partial characters for UTF-8 input (libexpat bug 115):
  https://github.com/libexpat/libexpat/issues/115

- bpo-29136: Add TLS 1.3 cipher suites and OP_NO_TLSv1_3.

- bpo-31334: Fix ``poll.poll([timeout])`` in the ``select`` module for
  arbitrary negative timeouts on all OSes where it can only be a
  non-negative integer or -1. Patch by Riccardo Coccioli.

- bpo-10746: Fix ctypes producing wrong PEP 3118 type codes for integer
  types.

- bpo-30102: The ssl and hashlib modules now call
  OPENSSL_add_all_algorithms_noconf() on OpenSSL < 1.1.0. The function
  detects CPU features and enables optimizations on some CPU architectures
  such as POWER8. Patch is based on research from Gustavo Serra Scalet.

- bpo-30502: Fix handling of long oids in ssl.  Based on patch by Christian
  Heimes.

- bpo-25684: Change ``ttk.OptionMenu`` radiobuttons to be unique across
  instances of ``OptionMenu``.

- bpo-29169: Update zlib to 1.2.11.

- bpo-30746: Prohibited the '=' character in environment variable names in
  ``os.putenv()`` and ``os.spawn*()``.

- bpo-30418: On Windows, subprocess.Popen.communicate() now also ignore
  EINVAL on stdin.write() if the child process is still running but closed
  the pipe.

- bpo-30378: Fix the problem that logging.handlers.SysLogHandler cannot
  handle IPv6 addresses.

- bpo-29960: Preserve generator state when _random.Random.setstate() raises
  an exception. Patch by Bryan Olson.

- bpo-30310: tkFont now supports unicode options (e.g. font family).

- bpo-30414: multiprocessing.Queue._feed background running thread do not
  break from main loop on exception.

- bpo-30003: Fix handling escape characters in HZ codec.  Based on patch by
  Ma Lin.

- bpo-30375: Warnings emitted when compile a regular expression now always
  point to the line in the user code.  Previously they could point into
  inners of the re module if emitted from inside of groups or conditionals.

- bpo-30363: Running Python with the -3 option now warns about regular
  expression syntax that is invalid or has different semantic in Python 3 or
  will change the behavior in future Python versions.

- bpo-30365: Running Python with the -3 option now emits deprecation
  warnings for getchildren() and getiterator() methods of the Element class
  in the xml.etree.cElementTree module and when pass the html argument to
  xml.etree.ElementTree.XMLParser().

- bpo-30365: Fixed a deprecation warning about the doctype() method of the
  xml.etree.ElementTree.XMLParser class.  Now it is emitted only when define
  the doctype() method in the subclass of XMLParser.

- bpo-30329: imaplib now catchs the Windows socket WSAEINVAL error (code
  10022) on shutdown(SHUT_RDWR): An invalid operation was attempted. This
  error occurs sometimes on SSL connections.

- bpo-30342: Fix sysconfig.is_python_build() if Python is built with Visual
  Studio 2008 (VS 9.0).

- bpo-29990: Fix range checking in GB18030 decoder.  Original patch by Ma
  Lin.

- bpo-30243: Removed the __init__ methods of _json's scanner and encoder.
  Misusing them could cause memory leaks or crashes.  Now scanner and
  encoder objects are completely initialized in the __new__ methods.

- bpo-26293: Change resulted because of zipfile breakage. (See also:
  bpo-29094)

- bpo-30070: Fixed leaks and crashes in errors handling in the parser
  module.

- bpo-30061: Fixed crashes in IOBase methods next() and readlines() when
  readline() or next() respectively return non-sizeable object. Fixed
  possible other errors caused by not checking results of PyObject_Size(),
  PySequence_Size(), or PyMapping_Size().

- bpo-30011: Fixed race condition in HTMLParser.unescape().

- bpo-30068: _io._IOBase.readlines will check if it's closed first when hint
  is present.

- bpo-27863: Fixed multiple crashes in ElementTree caused by race conditions
  and wrong types.

- bpo-29942: Fix a crash in itertools.chain.from_iterable when encountering
  long runs of empty iterables.

- bpo-29861: Release references to tasks, their arguments and their results
  as soon as they are finished in multiprocessing.Pool.

- bpo-27880: Fixed integer overflow in cPickle when pickle large strings or
  too many objects.

- bpo-29110: Fix file object leak in aifc.open() when file is given as a
  filesystem path and is not in valid AIFF format. Original patch by Anthony
  Zhang.

- bpo-29354: Fixed inspect.getargs() for parameters which are cell
  variables.

- bpo-29335: Fix subprocess.Popen.wait() when the child process has exited
  to a stopped instead of terminated state (ex: when under ptrace).

- bpo-29219: Fixed infinite recursion in the repr of uninitialized
  ctypes.CDLL instances.

- bpo-29082: Fixed loading libraries in ctypes by unicode names on Windows.
  Original patch by Chi Hsuan Yen.

- bpo-29188: Support glibc 2.24 on Linux: don't use getentropy() function
  but read from /dev/urandom to get random bytes, for example in
  os.urandom(). On Linux, getentropy() is implemented which getrandom() is
  blocking mode, whereas os.urandom() should not block.

- bpo-29142: In urllib, suffixes in no_proxy environment variable with
  leading dots could match related hostnames again (e.g. .b.c matches
  a.b.c). Patch by Milan Oberkirch.

- bpo-13051: Fixed recursion errors in large or resized
  curses.textpad.Textbox.  Based on patch by Tycho Andersen.

- bpo-9770: curses.ascii predicates now work correctly with negative
  integers.

- bpo-28427: old keys should not remove new values from WeakValueDictionary
  when collecting from another thread.

- bpo-28998: More APIs now support longs as well as ints.

- bpo-28923: Remove editor artifacts from Tix.py, including encoding not
  recognized by codecs.lookup.

- bpo-29019: Fix dict.fromkeys(x) overallocates when x is sparce dict.
  Original patch by Rasmus Villemoes.

- bpo-19542: Fix bugs in WeakValueDictionary.setdefault() and
  WeakValueDictionary.pop() when a GC collection happens in another thread.

- bpo-28925: cPickle now correctly propagates errors when unpickle instances
  of old-style classes.

Documentation
-------------

- bpo-27212: Modify documentation for the :func:`islice` recipe to consume
  initial values up to the start index.

- bpo-32800: Update link to w3c doc for xml default namespaces.

- bpo-17799: Explain real behaviour of sys.settrace and sys.setprofile and
  their C-API counterparts regarding which type of events are received in
  each function. Patch by Pablo Galindo Salgado.

- bpo-8243: Add a note about curses.addch and curses.addstr exception
  behavior when writing outside a window, or pad.

- bpo-21649: Add RFC 7525 and Mozilla server side TLS links to SSL
  documentation.

- bpo-30176: Add missing attribute related constants in curses
  documentation.

- bpo-28929: Link the documentation to its source file on GitHub.

- bpo-26355: Add canonical header link on each page to corresponding major
  version of the documentation. Patch by Matthias Bussonnier.

- bpo-12067: Rewrite Comparisons section in the Expressions chapter of the
  language reference. Some of the details of comparing mixed types were
  incorrect or ambiguous. Added default behaviour and consistency
  suggestions for user-defined classes. Based on patch from Andy Maier.

Tests
-----

- bpo-31719: Fix test_regrtest.test_crashed() on s390x. Add a new
  _testcapi._read_null() function to crash Python in a reliable way on
  s390x. On s390x, ctypes.string_at(0) returns an empty string rather than
  crashing.

- bpo-31518: Debian Unstable has disabled TLS 1.0 and 1.1 for
  SSLv23_METHOD(). Change TLS/SSL protocol of some tests to PROTOCOL_TLS or
  PROTOCOL_TLSv1_2 to make them pass on Debian.

- bpo-25674: Remove sha256.tbs-internet.com ssl test

- bpo-11790: Fix sporadic failures in
  test_multiprocessing.WithProcessesTestCondition.

- bpo-30236: Backported test.regrtest options -m/--match and -G/--failfast
  from Python 3.

- bpo-30223: To unify running tests in Python 2.7 and Python 3, the test
  package can be run as a script.  This is equivalent to running the
  test.regrtest module as a script.

- bpo-30207: To simplify backports from Python 3, the test.test_support
  module was converted into a package and renamed to test.support.  The
  test.script_helper module was moved into the test.support package. Names
  test.test_support and test.script_helper are left as aliases to
  test.support and test.support.script_helper.

- bpo-30197: Enhanced function swap_attr() in the test.test_support module.
  It now works when delete replaced attribute inside the with statement.
  The old value of the attribute (or None if it doesn't exist) now will be
  assigned to the target of the "as" clause, if there is one. Also
  backported function swap_item().

- bpo-28087: Skip test_asyncore and test_eintr poll failures on macOS. Skip
  some tests of select.poll when running on macOS due to unresolved issues
  with the underlying system poll function on some macOS versions.

- bpo-15083: Convert ElementTree doctests to unittests.

Build
-----

- bpo-33163: Upgrade pip to 9.0.3 and setuptools to v39.0.1.

- bpo-32616: Disable computed gotos by default for clang < 5.0. It caused
  significant performance regression.

- bpo-32635: Fix segfault of the crypt module when libxcrypt is provided
  instead of libcrypt at the system.

- bpo-31934: Abort the build when building out of a not clean source tree.

- bpo-31474: Fix -Wint-in-bool-context warnings in PyMem_MALLOC and
  PyMem_REALLOC macros

- bpo-29243: Prevent unnecessary rebuilding of Python during ``make test``,
  ``make install`` and some other make targets when configured with
  ``--enable-optimizations``.

- bpo-23404: Don't regenerate generated files based on file modification
  time anymore: the action is now explicit. Replace ``make touch`` with
  ``make regen-all``.

- bpo-27593: sys.version and the platform module python_build(),
  python_branch(), and python_revision() functions now use git information
  rather than hg when building from a repo.

- bpo-29643: Fix ``--enable-optimization`` configure option didn't work.

- bpo-29572: Update Windows build and OS X installers to use OpenSSL 1.0.2k.

- bpo-28768: Fix implicit declaration of function _setmode. Patch by
  Masayuki Yamamoto

Windows
-------

- bpo-33184: Update Windows build to use OpenSSL 1.0.2o.

- bpo-32903: Fix a memory leak in os.chdir() on Windows if the current
  directory is set to a UNC path.

- bpo-30855: Bump Tcl/Tk to 8.5.19.

- bpo-30450: Pull build dependencies from GitHub rather than svn.python.org.

macOS
-----

- bpo-32726: Provide an additional, more modern macOS installer variant that
  supports macOS 10.9+ systems in 64-bit mode only. Upgrade the supplied
  third-party libraries to OpenSSL 1.0.2n and SQLite 3.22.0. The 10.9+
  installer now supplies its own private copy of Tcl/Tk 8.6.8.

- bpo-24414: Default macOS deployment target is now set by ``configure`` to
  the build system's OS version (as is done by Python 3), not ``10.4``;
  override with, for example, ``./configure MACOSX_DEPLOYMENT_TARGET=10.4``.

- bpo-17128: All 2.7 macOS installer variants now supply their own version
  of ``OpenSSL 1.0.2``; the Apple-supplied SSL libraries and root
  certificates are not longer used.  The ``Installer Certificate`` command
  in ``/Applications/Python 2.7`` may be used to download and install a
  default set of root certificates from the third-party ``certifi`` package.

- bpo-11485: python.org macOS Pythons no longer supply a default SDK value
  (e.g. ``-isysroot /``) or specific compiler version default (e.g.
  ``gcc-4.2``) when building extension modules.  Use ``CC``, ``SDKROOT``,
  and ``DEVELOPER_DIR`` environment variables to override compilers or to
  use an SDK.  See Apple's ``xcrun`` man page for more info.

- bpo-33184: Update macOS installer build to use OpenSSL 1.0.2o.

Tools/Demos
-----------

- bpo-31920: Fixed handling directories as arguments in the ``pygettext``
  script. Based on patch by Oleg Krasnikov.

- bpo-30109: Fixed Tools/scripts/reindent.py for non-ASCII files. It now
  processes files as binary streams. This also fixes "make reindent".

- bpo-24960: 2to3 and lib2to3 can now read pickled grammar files using
  pkgutil.get_data() rather than probing the filesystem. This lets 2to3 and
  lib2to3 work when run from a zipfile.

C API
-----

- bpo-20891: Fix PyGILState_Ensure(). When PyGILState_Ensure() is called in
  a non-Python thread before PyEval_InitThreads(), only call
  PyEval_InitThreads() after calling PyThreadState_New() to fix a crash.

- bpo-31626: When Python is built in debug mode, the memory debug hooks now
  fail with a fatal error if realloc() fails to shrink a memory block,
  because the debug hook just erased freed bytes without keeping a copy of
  them.


What's New in Python 2.7.14 release candidate 1?
================================================

*Release date: 2017-08-26*

Security
--------

- bpo-30947: Upgrade libexpat embedded copy from version 2.2.1 to 2.2.3 to
  get security fixes.

Core and Builtins
-----------------

- bpo-30765: Avoid blocking in pthread_mutex_lock() when
  PyThread_acquire_lock() is asked not to block.

Library
-------

- bpo-31135: ttk: Fix LabeledScale and OptionMenu destroy() method. Call the
  parent destroy() method even if the used attribute doesn't exist. The
  LabeledScale.destroy() method now also explicitly clears label and scale
  attributes to help the garbage collector to destroy all widgets.

- bpo-31107: Fix `copy_reg._slotnames()` mangled attribute calculation for
  classes whose name begins with an underscore. Patch by Shane Harvey.

- bpo-29519: Fix weakref spewing exceptions during interpreter shutdown when
  used with a rare combination of multiprocessing and custom codecs.

- bpo-30119: ftplib.FTP.putline() now throws ValueError on commands that
  contains CR or LF. Patch by Dong-hee Na.

- bpo-30595: multiprocessing.Queue.get() with a timeout now polls its reader
  in non-blocking mode if it succeeded to aquire the lock but the acquire
  took longer than the timeout.

- bpo-29902: Py3k deprecation warning now is emitted when pickling or
  copying some builtin and extension objects that don't support pickling
  explicitly and are pickled incorrectly by default (like memoryview or
  staticmethod).  This is a TypeError in Python 3.6.

- bpo-29854: Fix segfault in readline when using readline's history-size
  option.  Patch by Nir Soffer.

- bpo-30807: signal.setitimer() may disable the timer when passed a tiny
  value.

  Tiny values (such as 1e-6) are valid non-zero values for setitimer(),
  which is specified as taking microsecond-resolution intervals. However, on
  some platform, our conversion routine could convert 1e-6 into a zero
  interval, therefore disabling the timer instead of (re-)scheduling it.

Tests
-----

- bpo-30715: Address ALPN callback changes for OpenSSL 1.1.0f. The latest
  version behaves like OpenSSL 1.0.2 and no longer aborts handshake.

- bpo-30822: Fix regrtest command line parser to allow passing -u
  extralargefile to run test_zipfile64.

- bpo-30283: regrtest: Enhance regrtest and backport features from the
  master branch.

  Add options: --coverage, --testdir, --list-tests (list test files, don't
  run them), --list-cases (list test identifiers, don't run them,
  :issue:`30523`), --matchfile (load a list of test filters from a text
  file, :issue:`30540`), --slowest (alias to --slow).

  Enhance output: add timestamp, test result, currently running tests,
  "Tests result: xxx" summary with total duration, etc.

  Fix reference leak hunting in regrtest, --huntrleaks: regrtest now warms
  up caches, create explicitly all internal singletons which are created on
  demand to prevent false positives when checking for reference leaks.
  (:issue:`30675`).


What's New in Python 2.7.13 final?
==================================

*Release date: 2016-12-17*

Core and Builtins
-----------------

- bpo-5322: Revert a37cc3d926ec.


What's New in Python 2.7.13 release candidate 1?
================================================

*Release date: 2016-12-03*

Core and Builtins
-----------------

- bpo-5322: Fixed setting __new__ to a PyCFunction inside Python code.
  Original patch by Andreas Stührk.

- bpo-28847: dumbdbm no longer writes the index file in when it is not
  changed and supports reading read-only files.

- bpo-11145: Fixed miscellaneous issues with C-style formatting of types
  with custom __oct__ and __hex__.

- bpo-24469: Fixed memory leak caused by int subclasses without overridden
  tp_free (e.g. C-inherited Cython classes).

- bpo-19398: Extra slash no longer added to sys.path components in case of
  empty compile-time PYTHONPATH components.

- bpo-21720: Improve exception message when the type of fromlist is unicode.
  fromlist parameter of __import__() only accepts str in Python 2 and this
  will help to identify the problem especially when the unicode_literals
  future import is used.

- bpo-26906: Resolving special methods of uninitialized type now causes
  implicit initialization of the type instead of a fail.

- bpo-18287: PyType_Ready() now checks that tp_name is not NULL. Original
  patch by Niklas Koep.

- bpo-24098: Fixed possible crash when AST is changed in process of
  compiling it.

- bpo-28350: String constants with null character no longer interned.

- bpo-27942: String constants now interned recursively in tuples and
  frozensets.

- bpo-15578: Correctly incref the parent module while importing.

- bpo-26307: The profile-opt build now applies PGO to the built-in modules.

- bpo-26020: set literal evaluation order did not match documented
  behaviour.

- bpo-27870: A left shift of zero by a large integer no longer attempts to
  allocate large amounts of memory.

- bpo-25604: Fix a minor bug in integer true division; this bug could
  potentially have caused off-by-one-ulp results on platforms with
  unreliable ldexp implementations.

- bpo-27473: Fixed possible integer overflow in str, unicode and bytearray
  concatenations and repetitions.  Based on patch by Xiang Zhang.

- bpo-27507: Add integer overflow check in bytearray.extend().  Patch by
  Xiang Zhang.

- bpo-27581: Don't rely on wrapping for overflow check in
  PySequence_Tuple().  Patch by Xiang Zhang.

- bpo-23908: os functions, open() and the io.FileIO constructor now reject
  unicode paths with embedded null character on Windows instead of silently
  truncating them.

- bpo-27514: Make having too many statically nested blocks a SyntaxError
  instead of SystemError.

Library
-------

- bpo-25659: In ctypes, prevent a crash calling the from_buffer() and
  from_buffer_copy() methods on abstract classes like Array.

- bpo-28563: Fixed possible DoS and arbitrary code execution when handle
  plural form selections in the gettext module.  The expression parser now
  supports exact syntax supported by GNU gettext.

- bpo-28387: Fixed possible crash in _io.TextIOWrapper deallocator when the
  garbage collector is invoked in other thread.  Based on patch by Sebastian
  Cufre.

- bpo-28449: tarfile.open() with mode "r" or "r:" now tries to open a tar
  file with compression before trying to open it without compression.
  Otherwise it had 50% chance failed with ignore_zeros=True.

- bpo-25464: Fixed HList.header_exists() in Tix module by adding a
  workaround to Tix library bug.

- bpo-28488: shutil.make_archive() no longer adds entry "./" to ZIP archive.

- bpo-28480: Fix error building _sqlite3 module when multithreading is
  disabled.

- bpo-24452: Make webbrowser support Chrome on Mac OS X.

- bpo-26293: Fixed writing ZIP files that starts not from the start of the
  file.  Offsets in ZIP file now are relative to the start of the archive in
  conforming to the specification.

- Fix possible integer overflows and crashes in the mmap module with unusual
  usage patterns.

- bpo-27897: Fixed possible crash in sqlite3.Connection.create_collation()
  if pass invalid string-like object as a name.  Original patch by Xiang
  Zhang.

- bpo-1703178: Fix the ability to pass the --link-objects option to the
  distutils build_ext command.

- bpo-28253: Fixed calendar functions for extreme months: 0001-01 and
  9999-12.

  Methods itermonthdays() and itermonthdays2() are reimplemented so that
  they don't call itermonthdates() which can cause datetime.date
  under/overflow.

- bpo-27963: Fixed possible null pointer dereference in
  ctypes.set_conversion_mode(). Patch by Xiang Zhang.

- bpo-28284: Strengthen resistance of ``_json.encode_basestring_ascii()`` to
  integer overflow.

- bpo-27611: Fixed support of default root window in the Tix module.

- bpo-24363: When parsing HTTP header fields, if an invalid line is
  encountered, skip it and continue parsing.  Previously, no more header
  fields were parsed, which could lead to fields for HTTP framing like
  Content-Length and Transfer-Encoding being overlooked.

- bpo-27599: Fixed buffer overrun in binascii.b2a_qp() and
  binascii.a2b_qp().

- bpo-25969: Update the lib2to3 grammar to handle the unpacking
  generalizations added in 3.5.

- bpo-24594: Validates persist parameter when opening MSI database

- bpo-27570: Avoid zero-length memcpy() etc calls with null source pointers
  in the "ctypes" and "array" modules.

- bpo-22450: urllib now includes an "Accept: */*" header among the default
  headers.  This makes the results of REST API requests more consistent and
  predictable especially when proxy servers are involved.

- lib2to3.pgen3.driver.load_grammar() now creates a stable cache file
  between runs given the same Grammar.txt input regardless of the hash
  randomization setting.

- bpo-27691: Fix ssl module's parsing of GEN_RID subject alternative name
  fields in X.509 certs.

- bpo-27850: Remove 3DES from ssl module's default cipher list to counter
  measure sweet32 attack (CVE-2016-2183).

- bpo-27766: Add ChaCha20 Poly1305 to ssl module's default ciper list.
  (Required OpenSSL 1.1.0 or LibreSSL).

- bpo-26470: Port ssl and hashlib module to OpenSSL 1.1.0.

- bpo-27944: Fix some memory-corruption bugs in the log reading code of the
  _hotshot module.

- bpo-27934: Use ``float.__repr__`` instead of plain ``repr`` when JSON-
  encoding an instance of a float subclass. Thanks Eddie James.

- bpo-27861: Fixed a crash in sqlite3.Connection.cursor() when a factory
  creates not a cursor.  Patch by Xiang Zhang.

- bpo-19884: Avoid spurious output on OS X with Gnu Readline.

- bpo-10513: Fix a regression in Connection.commit().  Statements should not
  be reset after a commit.

- bpo-2466: posixpath.ismount now correctly recognizes mount points which
  the user does not have permission to access.

- bpo-27783: Fix possible usage of uninitialized memory in
  operator.methodcaller.

- bpo-27774: Fix possible Py_DECREF on unowned object in _sre.

- bpo-27760: Fix possible integer overflow in binascii.b2a_qp.

- In the curses module, raise an error if window.getstr() or window.instr()
  is passed a negative value.

- bpo-27758: Fix possible integer overflow in the _csv module for large
  record lengths.

- bpo-23369: Fixed possible integer overflow in
  _json.encode_basestring_ascii.

- bpo-27568: Prevent HTTPoxy attack (CVE-2016-1000110). Ignore the
  HTTP_PROXY variable when REQUEST_METHOD environment is set, which
  indicates that the script is in CGI mode.

- bpo-27130: In the "zlib" module, fix handling of large buffers (typically
  2 or 4 GiB). Previously, inputs were limited to 2 GiB, and compression and
  decompression operations did not properly handle results of 2 or 4 GiB.

- bpo-23804: Fix SSL zero-length recv() calls to not block and not raise an
  error about unclean EOF.

- bpo-27466: Change time format returned by http.cookie.time2netscape,
  confirming the netscape cookie format and making it consistent with
  documentation.

- bpo-22115: Fixed tracing Tkinter variables: trace_vdelete() with wrong
  mode no longer break tracing, trace_vinfo() now always returns a list of
  pairs of strings.

- bpo-27079: Fixed curses.ascii functions isblank(), iscntrl() and
  ispunct().

- bpo-22636: Avoid shell injection problems with ctypes.util.find_library().

- bpo-27330: Fixed possible leaks in the ctypes module.

- bpo-27238: Got rid of bare excepts in the turtle module.  Original patch
  by Jelle Zijlstra.

- bpo-26386: Fixed ttk.TreeView selection operations with item id's
  containing spaces.

- bpo-25455: Fixed a crash in repr of cElementTree.Element with recursive
  tag.

- bpo-21201: Improves readability of multiprocessing error message.  Thanks
  to Wojciech Walczak for patch.

IDLE
----

- bpo-27854: Make Help => IDLE Help work again on Windows. Include
  idlelib/help.html in 2.7 Windows installer.

- bpo-25507: Add back import needed for 2.x encoding warning box. Add
  pointer to 'Encoding declaration' in Language Reference.

- bpo-15308: Add 'interrupt execution' (^C) to Shell menu. Patch by Roger
  Serwy, updated by Bayard Randel.

- bpo-27922: Stop IDLE tests from 'flashing' gui widgets on the screen.

- bpo-17642: add larger font sizes for classroom projection.

- Add version to title of IDLE help window.

- bpo-25564: In section on IDLE -- console differences, mention that using
  exec means that __builtins__ is defined for each statement.

- bpo-27714: text_textview and test_autocomplete now pass when re-run in the
  same process.  This occurs when test_idle fails when run with the -w
  option but without -jn.  Fix warning from test_config.

- bpo-27452: add line counter and crc to IDLE configHandler test dump.

- bpo-27365: Allow non-ascii chars in IDLE NEWS.txt, for contributor names.

- bpo-27245: IDLE: Cleanly delete custom themes and key bindings.
  Previously, when IDLE was started from a console or by import, a cascade
  of warnings was emitted. Patch by Serhiy Storchaka.

Documentation
-------------

- bpo-28513: Documented command-line interface of zipfile.

- bpo-16484: Change the default PYTHONDOCS URL to "https:", and fix the
  resulting links to use lowercase.  Patch by Sean Rodman, test by Kaushik
  Nadikuditi.

Tests
-----

- bpo-28666: Now test.test_support.rmtree is able to remove unwritable or
  unreadable directories.

- bpo-23839: Various caches now are cleared before running every test file.

- bpo-27369: In test_pyexpat, avoid testing an error message detail that
  changed in Expat 2.2.0.

Build
-----

- bpo-10656: Fix out-of-tree building on AIX.  Patch by Tristan Carel and
  Michael Haubenwallner.

- bpo-26359: Rename --with-optimiations to --enable-optimizations.

- bpo-28248: Update Windows build and OS X installers to use OpenSSL 1.0.2j.

- bpo-28258: Fixed build with Estonian locale (distclean target in
  Makefile).  Patch by Arfrever Frehtes Taifersar Arahesis.

- bpo-26661: setup.py now detects system libffi with multiarch wrapper.

- bpo-15819: The Include directory in the build tree is already searched;
  drop unused code trying to add it again.

- bpo-27566: Fix clean target in freeze makefile (patch by Lisa Roach)

- bpo-27983: Cause lack of llvm-profdata tool when using clang as required
  for PGO linking to be a configure time error rather than make time when
  ``--with-optimizations`` is enabled.  Also improve our ability to find the
  llvm-profdata tool on MacOS and some Linuxes.

- bpo-26359: Add the --with-optimizations configure flag.

- bpo-10910: Avoid C++ compilation errors on FreeBSD and OS X. Also update
  FreedBSD version checks for the original ctype UTF-8 workaround.

- bpo-27806: Fix 32-bit builds on macOS Sierra 10.12 broken by removal of
  deprecated QuickTime/QuickTime.h header file.  Patch by Aleks Bunin.

- bpo-28676: Prevent missing 'getentropy' declaration warning on macOS.
  Initial patch by Gareth Rees.

Tools/Demos
-----------

- bpo-27952: Get Tools/scripts/fixcid.py working with the current "re"
  module, avoid invalid Python backslash escapes, and fix a bug parsing
  escaped C quote signs.

Windows
-------

- bpo-27932: Prevent memory leak in win32_ver().

- bpo-27888: Prevent Windows installer from displaying console windows and
  failing when pip cannot be installed/uninstalled.

macOS
-----

- bpo-28440: No longer add /Library/Python/site-packages, the Apple-supplied
  system Python site-packages directory, to sys.path for macOS framework
  builds. The coupling between the two Python instances often caused
  confusion and, as of macOS 10.12, changes to the site-packages layout can
  cause pip component installations to fail.  This change reverts the
  effects introduced in 2.7.0 by Issue #4865.  If you are using a package
  with both the Apple system Python 2.7 and a user-installed Python 2.7, you
  will need to ensure that copies of the package are installed with both
  Python instances.


What's New in Python 2.7.12 final?
==================================

*Release date: 2016-06-25*

Build
-----

- bpo-27641: The configure script now inserts comments into the makefile to
  prevent the pgen executable from being cross-compiled.

- bpo-26930: Update Windows builds to use OpenSSL 1.0.2h.

IDLE
----

- bpo-27365: Fix about dialog.


What's New in Python 2.7.12 release candidate 1?
================================================

*Release date: 2016-06-12*

Core and Builtins
-----------------

- bpo-20041: Fixed TypeError when frame.f_trace is set to None. Patch by
  Xavier de Gaye.

- bpo-25702: A --with-lto configure option has been added that will enable
  link time optimizations at build time during a make profile-opt. Some
  compilers and toolchains are known to not produce stable code when using
  LTO, be sure to test things thoroughly before relying on it. It can
  provide a few % speed up over profile-opt alone.

- bpo-26168: Fixed possible refleaks in failing Py_BuildValue() with the "N"
  format unit.

- bpo-27039: Fixed bytearray.remove() for values greater than 127.  Patch by
  Joe Jevnik.

- bpo-4806: Avoid masking the original TypeError exception when using star
  (*) unpacking and the exception was raised from a generator.  Based on
  patch by Hagen Fürstenau.

- bpo-26659: Make the builtin slice type support cycle collection.

- bpo-26718: super.__init__ no longer leaks memory if called multiple times.
  NOTE: A direct call of super.__init__ is not endorsed!

- bpo-13410: Fixed a bug in PyUnicode_Format where it failed to properly
  ignore errors from a __int__() method.

- bpo-26494: Fixed crash on iterating exhausting iterators. Affected classes
  are generic sequence iterators, iterators of bytearray, list, tuple, set,
  frozenset, dict, OrderedDict and corresponding views.

- bpo-26581: If coding cookie is specified multiple times on a line in
  Python source code file, only the first one is taken to account.

- bpo-22836: Ensure exception reports from PyErr_Display() and
  PyErr_WriteUnraisable() are sensible even when formatting them produces
  secondary errors.  This affects the reports produced by
  sys.__excepthook__() and when __del__() raises an exception.

- bpo-22847: Improve method cache efficiency.

- bpo-25843: When compiling code, don't merge constants if they are equal
  but have a different types. For example, ``f1, f2 = lambda: 1, lambda:
  1.0`` is now correctly compiled to two different functions: ``f1()``
  returns ``1`` (``int``) and ``f2()`` returns ``1.0`` (``int``), even if
  ``1`` and ``1.0`` are equal.

- bpo-22995: [UPDATE] Remove the one of the pickleability tests in
  _PyObject_GetState() due to regressions observed in Cython-based projects.

- bpo-25961: Disallowed null characters in the type name.

- bpo-22995: Instances of extension types with a state that aren't
  subclasses of list or dict and haven't implemented any pickle-related
  methods (__reduce__, __reduce_ex__, __getnewargs__, __getnewargs_ex__, or
  __getstate__), can no longer be pickled.  Including memoryview.

- bpo-20440: Massive replacing unsafe attribute setting code with special
  macro Py_SETREF.

- bpo-25421: __sizeof__ methods of builtin types now use dynamic basic size.
  This allows sys.getsize() to work correctly with their subclasses with
  __slots__ defined.

- bpo-19543: Added Py3k warning for decoding unicode.

- bpo-24097: Fixed crash in object.__reduce__() if slot name is freed inside
  __getattr__.

- bpo-24731: Fixed crash on converting objects with special methods __str__,
  __trunc__, and __float__ returning instances of subclasses of str, long,
  and float to subclasses of str, long, and float correspondingly.

- bpo-26478: Fix semantic bugs when using binary operators with dictionary
  views and tuples.

- bpo-26171: Fix possible integer overflow and heap corruption in
  zipimporter.get_data().

Library
-------

- bpo-26556: Update expat to 2.1.1, fixes CVE-2015-1283.

- Fix TLS stripping vulnerability in smptlib, CVE-2016-0772.  Reported by
  Team Oststrom

- bpo-7356: ctypes.util: Make parsing of ldconfig output independent of the
  locale.

- bpo-25738: Stop BaseHTTPServer.BaseHTTPRequestHandler.send_error() from
  sending a message body for 205 Reset Content.  Also, don't send the
  Content-Type header field in responses that don't have a body.  Based on
  patch by Susumu Koshiba.

- bpo-21313: Fix the "platform" module to tolerate when sys.version contains
  truncated build information.

- bpo-27211: Fix possible memory corruption in io.IOBase.readline().

- bpo-27114: Fix SSLContext._load_windows_store_certs fails with
  PermissionError

- bpo-14132: Fix urllib.request redirect handling when the target only has a
  query string.  Fix by Ján Janech.

- Removed the requirements for the ctypes and modulefinder modules to be
  compatible with earlier Python versions.

- bpo-22274: In the subprocess module, allow stderr to be redirected to
  stdout even when stdout is not redirected.  Patch by Akira Li.

- bpo-12045: Avoid duplicate execution of command in
  ctypes.util._get_soname(). Patch by Sijin Joseph.

- bpo-26960: Backported #16270 from Python 3 to Python 2, to prevent urllib
  from hanging when retrieving certain FTP files.

- bpo-25745: Fixed leaking a userptr in curses panel destructor.

- bpo-17765: weakref.ref() no longer silently ignores keyword arguments.
  Patch by Georg Brandl.

- bpo-26873: xmlrpclib now raises ResponseError on unsupported type tags
  instead of silently return incorrect result.

- bpo-24114: Fix an uninitialized variable in `ctypes.util`.

  The bug only occurs on SunOS when the ctypes implementation searches for
  the `crle` program.  Patch by Xiang Zhang.  Tested on SunOS by Kees Bos.

- bpo-26864: In urllib, change the proxy bypass host checking against
  no_proxy to be case-insensitive, and to not match unrelated host names
  that happen to have a bypassed hostname as a suffix.  Patch by Xiang
  Zhang.

- bpo-26804: urllib will prefer lower_case proxy environment variables over
  UPPER_CASE or Mixed_Case ones. Patch contributed by Hans-Peter Jansen.

- bpo-26837: assertSequenceEqual() now correctly outputs non-stringified
  differing items. This affects assertListEqual() and assertTupleEqual().

- bpo-26822: itemgetter, attrgetter and methodcaller objects no longer
  silently ignore keyword arguments.

- bpo-26657: Fix directory traversal vulnerability with SimpleHTTPServer on
  Windows. This fixes a regression that was introduced in 2.7.7.  Based on
  patch by Philipp Hagemeister.

- bpo-19377: Add .svg to mimetypes.types_map.

- bpo-13952: Add .csv to mimetypes.types_map.  Patch by Geoff Wilson.

- bpo-16329: Add .webm to mimetypes.types_map.  Patch by Giampaolo Rodola'.

- bpo-23735: Handle terminal resizing with Readline 6.3+ by installing our
  own SIGWINCH handler.  Patch by Eric Price.

- bpo-26644: Raise ValueError rather than SystemError when a negative length
  is passed to SSLSocket.recv() or read().

- bpo-23804: Fix SSL recv(0) and read(0) methods to return zero bytes
  instead of up to 1024.

- bpo-24266: Ctrl+C during Readline history search now cancels the search
  mode when compiled with Readline 7.

- bpo-23857: Implement PEP 493, adding a Python-2-only ssl module API and
  environment variable to configure the default handling of SSL/TLS
  certificates for HTTPS connections.

- bpo-26313: ssl.py _load_windows_store_certs fails if windows cert store is
  empty. Patch by Baji.

- bpo-26513: Fixes platform module detection of Windows Server

- bpo-23718: Fixed parsing time in week 0 before Jan 1.  Original patch by
  Tamás Bence Gedai.

- bpo-26177: Fixed the keys() method for Canvas and Scrollbar widgets.

- bpo-15068: Got rid of excessive buffering in the fileinput module. The
  bufsize parameter is no longer used.

- bpo-2202: Fix UnboundLocalError in
  AbstractDigestAuthHandler.get_algorithm_impls. Initial patch by Mathieu
  Dupuy.

- bpo-26475: Fixed debugging output for regular expressions with the (?x)
  flag.

- bpo-26385: Remove the file if the internal fdopen() call in
  NamedTemporaryFile() fails. Based on patch by Silent Ghost.

- bpo-26309: In the "SocketServer" module, shut down the request (closing
  the connected socket) when verify_request() returns false.  Based on patch
  by Aviv Palivoda.

- bpo-25939: On Windows open the cert store readonly in
  ssl.enum_certificates.

- bpo-24303: Fix random EEXIST upon multiprocessing semaphores creation with
  Linux PID namespaces enabled.

- bpo-25698: Importing module if the stack is too deep no longer replaces
  imported module with the empty one.

- bpo-12923: Reset FancyURLopener's redirect counter even if there is an
  exception. Based on patches by Brian Brazil and Daniel Rocco.

- bpo-25945: Fixed a crash when unpickle the functools.partial object with
  wrong state. Fixed a leak in failed functools.partial constructor. "args"
  and "keywords" attributes of functools.partial have now always types tuple
  and dict correspondingly.

- bpo-19883: Fixed possible integer overflows in zipimport.

- bpo-26147: xmlrpclib now works with unicode not encodable with used
  non-UTF-8 encoding.

- bpo-16620: Fixed AttributeError in msilib.Directory.glob().

- bpo-21847: Fixed xmlrpclib on Unicode-disabled builds.

- bpo-6500: Fixed infinite recursion in urllib2.Request.__getattr__().

- bpo-26083: Workaround a subprocess bug that raises an incorrect
  "ValueError: insecure string pickle" exception instead of the actual
  exception on some platforms such as Mac OS X when an exception raised in
  the forked child process prior to the exec() was large enough that it
  overflowed the internal errpipe_read pipe buffer.

- bpo-24103: Fixed possible use after free in ElementTree.iterparse().

- bpo-20954: _args_from_interpreter_flags used by multiprocessing and some
  tests no longer behaves incorrectly in the presence of the PYTHONHASHSEED
  environment variable.

- bpo-14285: When executing a package with the "python -m package" option,
  and package initialization raises ImportError, a proper traceback is now
  reported.

- bpo-6478: _strptime's regexp cache now is reset after changing timezone
  with time.tzset().

- bpo-25718: Fixed copying object with state with boolean value is false.

- bpo-25742: :func:`locale.setlocale` now accepts a Unicode string for its
  second parameter.

- bpo-10131: Fixed deep copying of minidom documents.  Based on patch by
  Marian Ganisin.

- bpo-25725: Fixed a reference leak in cPickle.loads() when unpickling
  invalid data including tuple instructions.

- bpo-25663: In the Readline completer, avoid listing duplicate global
  names, and search the global namespace before searching builtins.

- bpo-25688: Fixed file leak in ElementTree.iterparse() raising an error.

- bpo-23914: Fixed SystemError raised by CPickle unpickler on broken data.

- bpo-25924: Avoid unnecessary serialization of getaddrinfo(3) calls on OS X
  versions 10.5 or higher.  Original patch by A. Jesse Jiryu Davis.

- bpo-26406: Avoid unnecessary serialization of getaddrinfo(3) calls on
  current versions of OpenBSD and NetBSD.  Patch by A. Jesse Jiryu Davis.

IDLE
----

- bpo-5124: Paste with text selected now replaces the selection on X11. This
  matches how paste works on Windows, Mac, most modern Linux apps, and ttk
  widgets. Original patch by Serhiy Storchaka.

- bpo-24759: Make clear in idlelib.idle_test.__init__ that the directory is
  a private implementation of test.test_idle and tool for maintainers.

- bpo-26673: When tk reports font size as 0, change to size 10. Such fonts
  on Linux prevented the configuration dialog from opening.

- bpo-27044: Add ConfigDialog.remove_var_callbacks to stop memory leaks.

- In the 'IDLE-console differences' section of the IDLE doc, clarify how
  running with IDLE affects sys.modules and the standard streams.

- bpo-25507: fix incorrect change in IOBinding that prevented printing.
  Change also prevented saving shell window with non-ascii characters.
  Augment IOBinding htest to include all major IOBinding functions.

- bpo-25905: Revert unwanted conversion of ' to ’ RIGHT SINGLE QUOTATION
  MARK in README.txt and open this and NEWS.txt with 'ascii'. Re-encode
  CREDITS.txt to utf-8 and open it with 'utf-8'.

- bpo-26417: Prevent spurious errors and incorrect defaults when installing
  IDLE 2.7 on OS X: default configuration settings are no longer installed
  from OS X specific copies.

Documentation
-------------

- bpo-26736: Used HTTPS for external links in the documentation if possible.

- bpo-6953: Rework the Readline module documentation to group related
  functions together, and add more details such as what underlying Readline
  functions and variables are accessed.

- bpo-26014: Guide users to the newer packaging documentation as was done
  for Python 3.x. In particular, the top-level 2.7 documentation page now
  links to the newer installer and distributions pages rather than the
  legacy install and Distutils pages; these are still linked to in the
  library/distutils doc page.

Tests
-----

- bpo-21916: Added tests for the turtle module.  Patch by ingrid, Gregory
  Loyse and Jelle Zijlstra.

- bpo-25940: Changed test_ssl to use self-signed.pythontest.net.  This
  avoids relying on svn.python.org, which recently changed root certificate.

- bpo-25616: Tests for OrderedDict are extracted from test_collections into
  separate file test_ordered_dict.

Build
-----

- bpo-22359: Avoid incorrect recursive $(MAKE), and disable the rules for
  running pgen when cross-compiling.  The pgen output is normally saved with
  the source code anyway, and is still regenerated when doing a native
  build. Patch by Jonas Wagner and Xavier de Gaye.

- bpo-19450: Update Windows builds to use SQLite 3.8.11.0.

- bpo-27229: Fix the cross-compiling pgen rule for in-tree builds.  Patch by
  Xavier de Gaye.

- bpo-17603: Avoid error about nonexistant fileblocks.o file by using a
  lower-level check for st_blocks in struct stat.

- bpo-26465: Update Windows builds to use OpenSSL 1.0.2g.

- bpo-24421: Compile Modules/_math.c once, before building extensions.
  Previously it could fail to compile properly if the math and cmath builds
  were concurrent.

- bpo-25824: Fixes sys.winver to not include any architecture suffix.

- bpo-25348: Added ``--pgo`` and ``--pgo-job`` arguments to
  ``PCbuild\build.bat`` for building with Profile-Guided Optimization.  The
  old ``PCbuild\build_pgo.bat`` script is now deprecated, and simply calls
  ``PCbuild\build.bat --pgo %*``.

- bpo-25827: Add support for building with ICC to ``configure``, including a
  new ``--with-icc`` flag.

- bpo-25696: Fix installation of Python on UNIX with make -j9.

- bpo-26930: Update OS X 10.5+ 32-bit-only installer to build and link with
  OpenSSL 1.0.2h.

- bpo-26268: Update Windows builds to use OpenSSL 1.0.2f.

- bpo-25136: Support Apple Xcode 7's new textual SDK stub libraries.

Tools/Demos
-----------

- bpo-26799: Fix python-gdb.py: don't get C types once when the Python code
  is loaded, but get C types on demand. The C types can change if
  python-gdb.py is loaded before the Python executable. Patch written by
  Thomas Ilsche.

C API
-----

- bpo-30255: PySlice_GetIndicesEx now clips the step to [-PY_SSIZE_T_MAX,
  PY_SSIZE_T_MAX] instead of [-PY_SSIZE_T_MAX-1, PY_SSIZE_T_MAX].  This
  makes it safe to do "step = -step" when reversing a slice.

- bpo-26476: Fixed compilation error when use PyErr_BadInternalCall() in
  C++. Patch by Jeroen Demeyer.

Windows
-------

- bpo-17500: Remove unused and outdated icons. (See also:
  https://github.com/python/pythondotorg/issues/945)


What's New in Python 2.7.11 final?
==================================

*Release date: 2015-12-05*

Library
-------

- bpo-25624: ZipFile now always writes a ZIP_STORED header for directory
  entries.  Patch by Dingyuan Wang.


What's New in Python 2.7.11 release candidate 1?
================================================

*Release date: 2015-11-21*

Core and Builtins
-----------------

- bpo-25678: Avoid buffer overreads when int(), long(), float(), and
  compile() are passed buffer objects.  These objects are not necessarily
  terminated by a null byte, but the functions assumed they were.

- bpo-25388: Fixed tokenizer hang when processing undecodable source code
  with a null byte.

- bpo-22995: Default implementation of __reduce__ and __reduce_ex__ now
  rejects builtin types with not defined __new__.

- bpo-7267: format(int, 'c') now raises OverflowError when the argument is
  not in range(0, 256).

- bpo-24806: Prevent builtin types that are not allowed to be subclassed
  from being subclassed through multiple inheritance.

- bpo-24848: Fixed a number of bugs in UTF-7 decoding of misformed data.

- bpo-25003: os.urandom() doesn't use getentropy() on Solaris because
  getentropy() is blocking, whereas os.urandom() should not block.
  getentropy() is supported since Solaris 11.3.

- bpo-21167: NAN operations are now handled correctly when python is
  compiled with ICC even if -fp-model strict is not specified.

- bpo-24467: Fixed possible buffer over-read in bytearray. The bytearray
  object now always allocates place for trailing null byte and it's buffer
  now is always null-terminated.

- bpo-19543: encode() and decode() methods and constructors of str, unicode
  and bytearray classes now emit deprecation warning for known non-text
  encodings when Python is ran with the -3 option.

- bpo-24115: Update uses of PyObject_IsTrue(), PyObject_Not(),
  PyObject_IsInstance(), PyObject_RichCompareBool() and _PyDict_Contains()
  to check for and handle errors correctly.

- bpo-4753: On compilers where it is supported, use "computed gotos" for
  bytecode dispatch in the interpreter. This improves interpretation
  performance.

- bpo-22939: Fixed integer overflow in iterator object.  Original patch by
  Clement Rouault.

- bpo-24102: Fixed exception type checking in standard error handlers.

Library
-------

- bpo-10128: backport issue #10845's mitigation of incompatibilities between
  the multiprocessing module and directory and zipfile execution.
  Multiprocessing on Windows will now automatically skip rerunning __main__
  in spawned processes, rather than failing with AssertionError.

- bpo-25578: Fix (another) memory leak in SSLSocket.getpeercer().

- bpo-25590: In the Readline completer, only call getattr() once per
  attribute.

- bpo-25530: Disable the vulnerable SSLv3 protocol by default when creating
  ssl.SSLContext.

- bpo-25569: Fix memory leak in SSLSocket.getpeercert().

- bpo-7759: Fixed the mhlib module on filesystems that doesn't support link
  counting for directories.

- bpo-892902: Fixed pickling recursive objects.

- bpo-18010: Fix the pydoc GUI's search function to handle exceptions from
  importing packages.

- bpo-25515: Always use os.urandom as a source of randomness in uuid.uuid4.

- bpo-21827: Fixed textwrap.dedent() for the case when largest common
  whitespace is a substring of smallest leading whitespace. Based on patch
  by Robert Li.

- bpo-21709: Fix the logging module to not depend upon __file__ being set
  properly to get the filename of its caller from the stack.  This allows it
  to work if run in a frozen or embedded environment where the module's
  .__file__ attribute does not match its code object's .co_filename.

- bpo-25319: When threading.Event is reinitialized, the underlying condition
  should use a regular lock rather than a recursive lock.

- bpo-25232: Fix CGIRequestHandler to split the query from the URL at the
  first question mark (?) rather than the last. Patch from Xiang Zhang.

- bpo-24657: Prevent CGIRequestHandler from collapsing slashes in the query
  part of the URL as if it were a path. Patch from Xiang Zhang.

- bpo-22958: Constructor and update method of weakref.WeakValueDictionary
  now accept the self keyword argument.

- bpo-22609: Constructor and the update method of collections.UserDict now
  accept the self keyword argument.

- bpo-25203: Failed readline.set_completer_delims() no longer left the
  module in inconsistent state.

- bpo-19143: platform module now reads Windows version from kernel32.dll to
  avoid compatibility shims.

- bpo-25135: Make deque_clear() safer by emptying the deque before clearing.
  This helps avoid possible reentrancy issues.

- bpo-24684: socket.socket.getaddrinfo() now calls
  PyUnicode_AsEncodedString() instead of calling the encode() method of the
  host, to handle correctly custom unicode string with an encode() method
  which doesn't return a byte string. The encoder of the IDNA codec is now
  called directly instead of calling the encode() method of the string.

- bpo-24982: shutil.make_archive() with the "zip" format now adds entries
  for directories (including empty directories) in ZIP file.

- bpo-17849: Raise a sensible exception if an invalid response is received
  for a HTTP tunnel request, as seen with some servers that do not support
  tunnelling. Initial patch from Cory Benfield.

- bpo-16180: Exit pdb if file has syntax error, instead of trapping user in
  an infinite loop.  Patch by Xavier de Gaye.

- bpo-22812: Fix unittest discovery examples. Patch from Pam McA'Nulty.

- bpo-24634: Importing uuid should not try to load libc on Windows

- bpo-23652: Make it possible to compile the select module against the libc
  headers from the Linux Standard Base, which do not include some EPOLL
  macros.  Initial patch by Matt Frank.

- bpo-15138: Speed up base64.urlsafe_b64{en,de}code considerably.

- bpo-23319: Fix ctypes.BigEndianStructure, swap correctly bytes. Patch
  written by Matthieu Gautier.

- bpo-23254: Document how to close the TCPServer listening socket. Patch
  from Martin Panter.

- bpo-17527: Add PATCH to wsgiref.validator. Patch from Luca Sbardella.

- bpo-24613: Calling array.fromstring() with self is no longer allowed to
  prevent the use-after-free error.  Patch by John Leitch.

- bpo-24708: Fix possible integer overflow in strop.replace().

- bpo-24620: Random.setstate() now validates the value of state last
  element.

- bpo-13938: 2to3 converts StringTypes to a tuple. Patch from Mark Hammond.

- bpo-24611: Fixed compiling the posix module on non-Windows platforms
  without mknod() or makedev() (e.g. on Unixware).

- bpo-18684: Fixed reading out of the buffer in the re module.

- bpo-24259: tarfile now raises a ReadError if an archive is truncated
  inside a data segment.

- bpo-24514: tarfile now tolerates number fields consisting of only
  whitespace.

- bpo-20387: Restore semantic round-trip correctness in tokenize/untokenize
  for tab-indented blocks.

- bpo-24456: Fixed possible buffer over-read in adpcm2lin() and lin2adpcm()
  functions of the audioop module.  Fixed SystemError when the state is not
  a tuple.  Fixed possible memory leak.

- bpo-24481: Fix possible memory corruption with large profiler info strings
  in hotshot.

- bpo-24489: ensure a previously set C errno doesn't disturb cmath.polar().

- bpo-19543: io.TextIOWrapper (and hence io.open()) now uses the internal
  codec marking system added to emit deprecation warning for known non-text
  encodings at stream construction time when Python is ran with the -3
  option.

- bpo-24264: Fixed buffer overflow in the imageop module.

- bpo-5633: Fixed timeit when the statement is a string and the setup is
  not.

- bpo-24326: Fixed audioop.ratecv() with non-default weightB argument.
  Original patch by David Moore.

- bpo-22095: Fixed HTTPConnection.set_tunnel with default port.  The port
  value in the host header was set to "None".  Patch by Demian Brecht.

- bpo-24257: Fixed segmentation fault in sqlite3.Row constructor with faked
  cursor type.

- bpo-24286: Dict view were not registered with the MappingView abstract
  base classes. This caused key and item views in OrderedDict to not be
  equal to their regular dict counterparts.

- bpo-22107: tempfile.gettempdir() and tempfile.mkdtemp() now try again when
  a directory with the chosen name already exists on Windows as well as on
  Unix. tempfile.mkstemp() now fails early if parent directory is not valid
  (not exists or is a file) on Windows.

- bpo-6598: Increased time precision and random number range in
  email.utils.make_msgid() to strengthen the uniqueness of the message ID.

- bpo-24091: Fixed various crashes in corner cases in cElementTree.

- bpo-15267: HTTPConnection.request() now is compatible with old-style
  classes (such as TemporaryFile).  Original patch by Atsuo Ishimoto.

- bpo-20014: array.array() now accepts unicode typecodes.  Based on patch by
  Vajrasky Kok.

- bpo-23637: Showing a warning no longer fails with UnicodeError. Formatting
  unicode warning in the file with the path containing non-ascii characters
  no longer fails with UnicodeError.

- bpo-24134: Reverted issue #24134 changes.

IDLE
----

- bpo-15348: Stop the debugger engine (normally in a user process) before
  closing the debugger window (running in the IDLE process). This prevents
  the RuntimeErrors that were being caught and ignored.

- bpo-24455: Prevent IDLE from hanging when a) closing the shell while the
  debugger is active (15347); b) closing the debugger with the [X] button
  (15348); and c) activating the debugger when already active (24455). The
  patch by Mark Roseman does this by making two changes. 1. Suspend and
  resume the gui.interaction method with the tcl vwait mechanism intended
  for this purpose (instead of root.mainloop & .quit). 2. In gui.run, allow
  any existing interaction to terminate first.

- Change 'The program' to 'Your program' in an IDLE 'kill program?' message
  to make it clearer that the program referred to is the currently running
  user program, not IDLE itself.

- bpo-24750: Improve the appearance of the IDLE editor window status bar.
  Patch by Mark Roseman.

- bpo-25313: Change the handling of new built-in text color themes to better
  address the compatibility problem introduced by the addition of IDLE Dark.
  Consistently use the revised idleConf.CurrentTheme everywhere in idlelib.

- bpo-24782: Extension configuration is now a tab in the IDLE Preferences
  dialog rather than a separate dialog.   The former tabs are now a sorted
  list.  Patch by Mark Roseman.

- bpo-22726: Re-activate the config dialog help button with some content
  about the other buttons and the new IDLE Dark theme.

- bpo-24820: IDLE now has an 'IDLE Dark' built-in text color theme. It is
  more or less IDLE Classic inverted, with a cobalt blue background.
  Strings, comments, keywords, ... are still green, red, orange, ... . To
  use it with IDLEs released before November 2015, hit the 'Save as New
  Custom Theme' button and enter a new name, such as 'Custom Dark'.  The
  custom theme will work with any IDLE release, and can be modified.

- bpo-25224: README.txt is now an idlelib index for IDLE developers and
  curious users. The previous user content is now in the IDLE doc chapter.
  'IDLE' now means 'Integrated Development and Learning Environment'.

- bpo-24820: Users can now set breakpoint colors in Settings -> Custom
  Highlighting. Original patch by Mark Roseman.

- bpo-24972: Inactive selection background now matches active selection
  background, as configured by users, on all systems.  Found items are now
  always highlighted on Windows.  Initial patch by Mark Roseman.

- bpo-24570: Idle: make calltip and completion boxes appear on Macs affected
  by a tk regression.  Initial patch by Mark Roseman.

- bpo-24988: Idle ScrolledList context menus (used in debugger) now work on
  Mac Aqua. Patch by Mark Roseman.

- bpo-24801: Make right-click for context menu work on Mac Aqua. Patch by
  Mark Roseman.

- bpo-25173: Associate tkinter messageboxes with a specific widget. For Mac
  OSX, make them a 'sheet'.  Patch by Mark Roseman.

- bpo-25198: Enhance the initial html viewer now used for Idle Help. *
  Properly indent fixed-pitch text (patch by Mark Roseman). * Give code
  snippet a very Sphinx-like light blueish-gray background. * Re-use initial
  width and height set by users for shell and editor. * When the Table of
  Contents (TOC) menu is used, put the section header at the top of the
  screen.

- bpo-25225: Condense and rewrite Idle doc section on text colors.

- bpo-21995: Explain some differences between IDLE and console Python.

- bpo-22820: Explain need for *print* when running file from Idle editor.

- bpo-25224: Doc: augment Idle feature list and no-subprocess section.

- bpo-25219: Update doc for Idle command line options. Some were missing and
  notes were not correct.

- bpo-24861: Most of idlelib is private and subject to change. Use
  idleib.idle.* to start Idle. See idlelib.__init__.__doc__.

- bpo-25199: Idle: add synchronization comments for future maintainers.

- bpo-16893: Replace help.txt with help.html for Idle doc display. The new
  idlelib/help.html is rstripped Doc/build/html/library/idle.html. It looks
  better than help.txt and will better document Idle as released. The
  tkinter html viewer that works for this file was written by Mark Roseman.
  The now unused EditorWindow.HelpDialog class and helt.txt file are
  deprecated.

- bpo-24199: Deprecate unused idlelib.idlever with possible removal in 3.6.

- bpo-24790: Remove extraneous code (which also create 2 & 3 conflicts).

- bpo-23672: Allow Idle to edit and run files with astral chars in name.
  Patch by Mohd Sanad Zaki Rizvi.

- bpo-24745: Idle editor default font. Switch from Courier to
  platform-sensitive TkFixedFont.  This should not affect current customized
  font selections.  If there is a problem, edit
  $HOME/.idlerc/config-main.cfg and remove 'fontxxx' entries from [Editor
  Window].  Patch by Mark Roseman.

- bpo-21192: Idle editor. When a file is run, put its name in the restart
  bar. Do not print false prompts. Original patch by Adnan Umer.

- bpo-13884: Idle menus. Remove tearoff lines. Patch by Roger Serwy.

- bpo-15809: IDLE shell now uses locale encoding instead of Latin1 for
  decoding unicode literals.

Documentation
-------------

- bpo-24952: Clarify the default size argument of stack_size() in the
  "threading" and "thread" modules. Patch from Mattip.

- bpo-20769: Improve reload() docs. Patch by Dorian Pula.

- bpo-23589: Remove duplicate sentence from the FAQ.  Patch by Yongzhi Pan.

- bpo-22155: Add File Handlers subsection with createfilehandler to Tkinter
  doc.  Remove obsolete example from FAQ.  Patch by Martin Panter.

Tests
-----

- bpo-24751: When running regrtest with the ``-w`` command line option, a
  test run is no longer marked as a failure if all tests succeed when
  re-run.

- PCbuild\rt.bat now accepts an unlimited number of arguments to pass along
  to regrtest.py.  Previously there was a limit of 9.

Build
-----

- bpo-24915: When doing a PGO build, the test suite is now used instead of
  pybench; Clang support was also added as part off this work. Initial patch
  by Alecsandru Patrascu of Intel.

- bpo-24986: It is now possible to build Python on Windows without errors
  when external libraries are not available.

- bpo-24508: Backported the MSBuild project files from Python 3.5.  The
  backported files replace the old project files in PCbuild; the old files
  moved to PC/VS9.0 and remain supported.

- bpo-24603: Update Windows builds and OS X 10.5 installer to use OpenSSL
  1.0.2d.

Windows
-------

- bpo-25022: Removed very outdated PC/example_nt/ directory.


What's New in Python 2.7.10 final?
==================================

*Release date: 2015-05-23*

Library
-------

- bpo-22931: Allow '[' and ']' in cookie values.


What's New in Python 2.7.10 release candidate 1?
================================================

*Release date: 2015-05-10*

Core and Builtins
-----------------

- bpo-23971: Fix underestimated presizing in dict.fromkeys().

- bpo-23757: PySequence_Tuple() incorrectly called the concrete list API
  when the data was a list subclass.

- bpo-23629: Fix the default __sizeof__ implementation for variable-sized
  objects.

- bpo-23055: Fixed a buffer overflow in PyUnicode_FromFormatV.  Analysis and
  fix by Guido Vranken.

- bpo-23048: Fix jumping out of an infinite while loop in the pdb.

Library
-------

- The keywords attribute of functools.partial is now always a dictionary.

- bpo-20274: When calling a _sqlite.Connection, it now complains if passed
  any keyword arguments.  Previously it silently ignored them.

- bpo-20274: Remove ignored and erroneous "kwargs" parameters from three
  METH_VARARGS methods on _sqlite.Connection.

- bpo-24134: assertRaises() and assertRaisesRegexp() checks are not longer
  successful if the callable is None.

- bpo-23008: Fixed resolving attributes with boolean value is False in
  pydoc.

- bpo-24099: Fix use-after-free bug in heapq's siftup and siftdown
  functions. (See also: bpo-24100, bpo-24101)

- Backport collections.deque fixes from Python 3.5.  Prevents reentrant
  badness during deletion by deferring the decref until the container has
  been restored to a consistent state.

- bpo-23842: os.major(), os.minor() and os.makedev() now support ints again.

- bpo-23811: Add missing newline to the PyCompileError error message. Patch
  by Alex Shkop.

- bpo-17898: Fix exception in gettext.py when parsing certain plural forms.

- bpo-23865: close() methods in multiple modules now are idempotent and more
  robust at shutdown. If they need to release multiple resources, all are
  released even if errors occur.

- bpo-23881: urllib.ftpwrapper constructor now closes the socket if the FTP
  connection failed.

- bpo-15133: _tkinter.tkapp.getboolean() now supports long and Tcl_Obj and
  always returns bool.  tkinter.BooleanVar now validates input values
  (accepted bool, int, long, str, unicode, and Tcl_Obj).
  tkinter.BooleanVar.get() now always returns bool.

- bpo-23338: Fixed formatting ctypes error messages on Cygwin. Patch by
  Makoto Kato.

- bpo-16840: Tkinter now supports 64-bit integers added in Tcl 8.4 and
  arbitrary precision integers added in Tcl 8.5.

- bpo-23834: Fix socket.sendto(), use the C long type to store the result of
  sendto() instead of the C int type.

- bpo-21526: Tkinter now supports new boolean type in Tcl 8.5.

- bpo-23838: linecache now clears the cache and returns an empty result on
  MemoryError.

- bpo-23742: ntpath.expandvars() no longer loses unbalanced single quotes.

- bpo-21802: The reader in BufferedRWPair now is closed even when closing
  writer failed in BufferedRWPair.close().

- bpo-23671: string.Template now allows specifying the "self" parameter as a
  keyword argument.  string.Formatter now allows specifying the "self" and
  the "format_string" parameters as keyword arguments.

- bpo-21560: An attempt to write a data of wrong type no longer cause
  GzipFile corruption.  Original patch by Wolfgang Maier.

- bpo-23647: Increase impalib's MAXLINE to accommodate modern mailbox sizes.

- bpo-23539: If body is None, http.client.HTTPConnection.request now sets
  Content-Length to 0 for PUT, POST, and PATCH headers to avoid 411 errors
  from some web servers.

- bpo-23136: _strptime now uniformly handles all days in week 0, including
  Dec 30 of previous year.  Based on patch by Jim Carroll.

- bpo-23138: Fixed parsing cookies with absent keys or values in cookiejar.
  Patch by Demian Brecht.

- bpo-23051: multiprocessing.Pool methods imap() and imap_unordered() now
  handle exceptions raised by an iterator.  Patch by Alon Diamant and Davin
  Potts.

- bpo-22928: Disabled HTTP header injections in httplib. Original patch by
  Demian Brecht.

- bpo-23615: Module tarfile is now can be reloaded with imp.reload().

- bpo-22853: Fixed a deadlock when use multiprocessing.Queue at import time.
  Patch by Florian Finkernagel and Davin Potts.

- bpo-23476: In the ssl module, enable OpenSSL's X509_V_FLAG_TRUSTED_FIRST
  flag on certificate stores when it is available.

- bpo-23576: Avoid stalling in SSL reads when EOF has been reached in the
  SSL layer but the underlying connection hasn't been closed.

- bpo-23504: Added an __all__ to the types module.

- bpo-23458: On POSIX, the file descriptor kept open by os.urandom() is now
  set to non inheritable

- bpo-22113: struct.pack_into() now supports new buffer protocol (in
  particular accepts writable memoryview).

- bpo-814253: Warnings now are raised when group references and conditional
  group references are used in lookbehind assertions in regular expressions.
  (See also: bpo-9179)

- bpo-23215: Multibyte codecs with custom error handlers that ignores errors
  consumed too much memory and raised SystemError or MemoryError. Original
  patch by Aleksi Torhamo.

- bpo-5700: io.FileIO() called flush() after closing the file. flush() was
  not called in close() if closefd=False.

- bpo-21548: Fix pydoc.synopsis() and pydoc.apropos() on modules with empty
  docstrings. Initial patch by Yuyang Guo.

- bpo-22885: Fixed arbitrary code execution vulnerability in the dumbdbm
  module. Original patch by Claudiu Popa.

- bpo-23481: Remove RC4 from the SSL module's default cipher list.

- bpo-21849: Fixed xmlrpclib serialization of non-ASCII unicode strings in
  the multiprocessing module.

- bpo-21840: Fixed expanding unicode variables of form $var in
  posixpath.expandvars(). Fixed all os.path implementations on
  unicode-disabled builds.

- bpo-23367: Fix possible overflows in the unicodedata module.

- bpo-23363: Fix possible overflow in itertools.permutations.

- bpo-23364: Fix possible overflow in itertools.product.

- bpo-23365: Fixed possible integer overflow in
  itertools.combinations_with_replacement.

- bpo-23366: Fixed possible integer overflow in itertools.combinations.

- bpo-23191: fnmatch functions that use caching are now threadsafe.

- bpo-18518: timeit now rejects statements which can't be compiled outside a
  function or a loop (e.g. "return" or "break").

- bpo-19996: Make :mod:`httplib` ignore headers with no name rather than
  assuming the body has started.

- bpo-20188: Support Application-Layer Protocol Negotiation (ALPN) in the
  ssl module.

- bpo-23248: Update ssl error codes from latest OpenSSL git master.

- bpo-23098: 64-bit dev_t is now supported in the os module.

- bpo-23063: In the disutils' check command, fix parsing of reST with code
  or code-block directives.

- bpo-21356: Make ssl.RAND_egd() optional to support LibreSSL. The
  availability of the function is checked during the compilation. Patch
  written by Bernard Spil.

- Backport the context argument to ftplib.FTP_TLS.

- bpo-23111: Maximize compatibility in protocol versions of ftplib.FTP_TLS.

- bpo-23112: Fix SimpleHTTPServer to correctly carry the query string and
  fragment when it redirects to add a trailing slash.

- bpo-22585: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(),
  instead of reading /dev/urandom, to get pseudo-random bytes.

- bpo-23093: In the io, module allow more operations to work on detached
  streams.

- bpo-23071: Added missing names to codecs.__all__.  Patch by Martin Panter.

- bpo-23016: A warning no longer produces an AttributeError when sys.stderr
  is None.

- bpo-21032: Fixed socket leak if HTTPConnection.getresponse() fails.
  Original patch by Martin Panter.

- bpo-22609: Constructors and update methods of mapping classes in the
  collections module now accept the self keyword argument.

Documentation
-------------

- bpo-23006: Improve the documentation and indexing of dict.__missing__. Add
  an entry in the language datamodel special methods section. Revise and
  index its discussion in the stdtypes mapping/dict section. Backport the
  code example from 3.4.

- bpo-21514: The documentation of the json module now refers to new JSON RFC
  7159 instead of obsoleted RFC 4627.

Tools/Demos
-----------

- bpo-23330: h2py now supports arbitrary filenames in #include.

- bpo-6639: Module-level turtle functions no longer raise TclError after
  closing the window.

- bpo-22314: pydoc now works when the LINES environment variable is set.

- bpo-18905: "pydoc -p 0" now outputs actually used port.  Based on patch by
  Wieland Hoffmann.

- bpo-23345: Prevent test_ssl failures with large OpenSSL patch level values
  (like 0.9.8zc).

Tests
-----

- bpo-23799: Added test.test_support.start_threads() for running and
  cleaning up multiple threads.

- bpo-22390: test.regrtest now emits a warning if temporary files or
  directories are left after running a test.

- bpo-23583: Added tests for standard IO streams in IDLE.

- bpo-23392: Added tests for marshal C API that works with FILE*.

- bpo-18982: Add tests for CLI of the calendar module.

- bpo-19949: The test_xpickle test now tests compatibility with installed
  Python 2.7 and reports skipped tests.  Based on patch by Zachary Ware.

- bpo-11578: Backported test for the timeit module.

- bpo-22943: bsddb tests are locale independend now.

IDLE
----

- bpo-23583: Fixed writing unicode to standard output stream in IDLE.

- bpo-20577: Configuration of the max line length for the FormatParagraph
  extension has been moved from the General tab of the Idle preferences
  dialog to the FormatParagraph tab of the Config Extensions dialog. Patch
  by Tal Einat.

- bpo-16893: Update Idle doc chapter to match current Idle and add new
  information.

- bpo-23180: Rename IDLE "Windows" menu item to "Window". Patch by Al
  Sweigart.

Build
-----

- bpo-15506: Use standard PKG_PROG_PKG_CONFIG autoconf macro in the
  configure script.

- bpo-23032: Fix installer build failures on OS X 10.4 Tiger by disabling
  assembly code in the OpenSSL build.

- bpo-23686: Update OS X 10.5 installer and Windows builds to use OpenSSL
  1.0.2a.

C API
-----

- bpo-23998: PyImport_ReInitLock() now checks for lock allocation error

- bpo-22079: PyType_Ready() now checks that statically allocated type has no
  dynamically allocated bases.


What's New in Python 2.7.9 final?
=================================

*Release date: 2014-12-10*

Library
-------

- bpo-22959: Remove the *check_hostname* parameter of
  httplib.HTTPSConnection. The *context* parameter should be used instead.

- bpo-16043: Add a default limit for the amount of data
  xmlrpclib.gzip_decode will return. This resolves CVE-2013-1753.

- bpo-16042: CVE-2013-1752: smtplib: Limit amount of data read by limiting
  the call to readline().  Original patch by Christian Heimes.

- bpo-16041: In poplib, limit maximum line length read from the server to
  prevent CVE-2013-1752.

- bpo-22960: Add a context argument to xmlrpclib.ServerProxy.

Build
-----

- bpo-22935: Allow the ssl module to be compiled if openssl doesn't support
  SSL 3.

- bpo-17128: Use private version of OpenSSL for 2.7.9 OS X 10.5+ installer.


What's New in Python 2.7.9 release candidate 1?
===============================================

*Release date: 2014-11-25*

Core and Builtins
-----------------

- bpo-21963: backout issue #1856 patch (avoid crashes and lockups when
  daemon threads run while the interpreter is shutting down; instead, these
  threads are now killed when they try to take the GIL), as it seems to
  break some existing code.

- bpo-22604: Fix assertion error in debug mode when dividing a complex
  number by (nan+0j).

- bpo-22470: Fixed integer overflow issues in "backslashreplace" and
  "xmlcharrefreplace" error handlers.

- bpo-22526: Fix iterating through files with lines longer than 2^31 bytes.

- bpo-22519: Fix overflow checking in PyString_Repr.

- bpo-22518: Fix integer overflow issues in latin-1 encoding.

- bpo-22379: Fix empty exception message in a TypeError raised in
  ``str.join``.

- bpo-22221: Now the source encoding declaration on the second line isn't
  effective if the first line contains anything except a comment.

- bpo-22023: Fix ``%S``, ``%R`` and ``%V`` formats of
  :c:func:`PyUnicode_FromFormat`.

- bpo-21591: Correctly handle qualified exec statements in tuple form by
  moving compatibility layer from run-time to AST transformation.

Library
-------

- bpo-22417: Verify certificates by default in httplib (PEP 476).

- bpo-22927: Allow urllib.urlopen to take a *context* parameter to control
  SSL settings for HTTPS connections.

- bpo-22921: Allow SSLContext to take the *hostname* parameter even if
  OpenSSL doesn't support SNI.

- bpo-9003: httplib.HTTPSConnection, urllib2.HTTPSHandler and
  urllib2.urlopen now take optional arguments to allow for server
  certificate checking, as recommended in public uses of HTTPS. This
  backport is part of PEP 467. (See also: bpo-22366)

- bpo-12728: Different Unicode characters having the same uppercase but
  different lowercase are now matched in case-insensitive regular
  expressions.

- bpo-22821: Fixed fcntl() with integer argument on 64-bit big-endian
  platforms.

- bpo-17293: uuid.getnode() now determines MAC address on AIX using netstat.
  Based on patch by Aivars Kalvāns.

- bpo-22769: Fixed ttk.Treeview.tag_has() when called without arguments.

- bpo-22787: Allow the keyfile argument of SSLContext.load_cert_chain to be
  None.

- bpo-22775: Fixed unpickling of Cookie.SimpleCookie with protocol 2. Patch
  by Tim Graham.

- bpo-22776: Brought excluded code into the scope of a try block in
  SysLogHandler.emit().

- bpo-17381: Fixed ranges handling in case-insensitive regular expressions.

- bpo-19329: Optimized compiling charsets in regular expressions.

- bpo-22410: Module level functions in the re module now cache compiled
  locale-dependent regular expressions taking into account the locale.

- bpo-8876: distutils now falls back to copying files when hard linking
  doesn't work. This allows use with special filesystems such as VirtualBox
  shared folders.

- bpo-9351: Defaults set with set_defaults on an argparse subparser are no
  longer ignored when also set on the parent parser.

- bpo-20421: Add a .version() method to SSL sockets exposing the actual
  protocol version in use.

- bpo-22435: Fix a file descriptor leak when SocketServer bind fails.

- bpo-13664: GzipFile now supports non-ascii Unicode filenames.

- bpo-13096: Fixed segfault in CTypes POINTER handling of large values.

- bpo-11694: Raise ConversionError in xdrlib as documented.  Patch by Filip
  Gruszczyński and Claudiu Popa.

- bpo-1686: Fix string.Template when overriding the pattern attribute.

- bpo-11866: Eliminated race condition in the computation of names for new
  threads.

- bpo-22219: The zipfile module CLI now adds entries for directories
  (including empty directories) in ZIP file.

- bpo-22449: In the ssl.SSLContext.load_default_certs, consult the
  environmental variables SSL_CERT_DIR and SSL_CERT_FILE on Windows.

- bpo-8473: doctest.testfile now uses universal newline mode to read the
  test file.

- bpo-20076: Added non derived UTF-8 aliases to locale aliases table.

- bpo-20079: Added locales supported in glibc 2.18 to locale alias table.

- bpo-22530: Allow the ``group()`` method of regular expression match
  objects to take a ``long`` as an index.

- bpo-22517: When an io.BufferedRWPair object is deallocated, clear its
  weakrefs.

- bpo-10510: distutils register and upload methods now use HTML standards
  compliant CRLF line endings.

- bpo-9850: Fixed macpath.join() for empty first component.  Patch by Oleg
  Oshmyan.

- bpo-20912: Now directories added to ZIP file have correct Unix and MS-DOS
  directory attributes.

- bpo-21866: ZipFile.close() no longer writes ZIP64 central directory
  records if allowZip64 is false.

- bpo-22415: Fixed debugging output of the GROUPREF_EXISTS opcode in the re
  module.

- bpo-22423: Unhandled exception in thread no longer causes unhandled
  AttributeError when sys.stderr is None.

- bpo-22419: Limit the length of incoming HTTP request in wsgiref server to
  65536 bytes and send a 414 error code for higher lengths. Patch
  contributed by Devin Cook.

- Lax cookie parsing in http.cookies could be a security issue when combined
  with non-standard cookie handling in some Web browsers.  Reported by
  Sergey Bobrov.

- bpo-21147: sqlite3 now raises an exception if the request contains a null
  character instead of truncating it.  Based on patch by Victor Stinner.

- bpo-21951: Fixed a crash in Tkinter on AIX when called Tcl command with
  empty string or tuple argument.

- bpo-21951: Tkinter now most likely raises MemoryError instead of crash if
  the memory allocation fails.

- bpo-22226: First letter no longer is stripped from the "status" key in the
  result of Treeview.heading().

- bpo-22051: turtledemo no longer reloads examples to re-run them.
  Initialization of variables and gui setup should be done in main(), which
  is called each time a demo is run, but not on import.

- bpo-21597: The separator between the turtledemo text pane and the drawing
  canvas can now be grabbed and dragged with a mouse.  The code text pane
  can be widened to easily view or copy the full width of the text.  The
  canvas can be widened on small screens.  Original patches by Jan Kanis and
  Lita Cho.

- bpo-18132: Turtledemo buttons no longer disappear when the window is
  shrunk.  Original patches by Jan Kanis and Lita Cho.

- bpo-22312: Fix ntpath.splitdrive IndexError.

- bpo-22216: smtplib now resets its state more completely after a quit.  The
  most obvious consequence of the previous behavior was a STARTTLS failure
  during a connect/starttls/quit/connect/starttls sequence.

- bpo-21305: os.urandom now caches a fd to /dev/urandom. This is a PEP 466
  backport from Python 3.

- bpo-21307: As part of PEP 466, backport hashlib.algorithms_guaranteed and
  hashlib.algorithms_available.

- bpo-22259: Fix segfault when attempting to fopen a file descriptor
  corresponding to a directory.

- bpo-22236: Fixed Tkinter images copying operations in NoDefaultRoot mode.

- bpo-22191: Fixed warnings.__all__.

- bpo-21308: Backport numerous features from Python's ssl module. This is
  part of PEP 466.

- bpo-15696: Add a __sizeof__ implementation for mmap objects on Windows.

- bpo-8797: Raise HTTPError on failed Basic Authentication immediately.
  Initial patch by Sam Bull.

- bpo-22068: Avoided reference loops with Variables and Fonts in Tkinter.

- bpo-21448: Changed FeedParser feed() to avoid O(N**2) behavior when
  parsing long line. Original patch by Raymond Hettinger.

- bpo-17923: glob() patterns ending with a slash no longer match non-dirs on
  AIX.  Based on patch by Delhallt.

- bpo-21975: Fixed crash when using uninitialized sqlite3.Row (in particular
  when unpickling pickled sqlite3.Row).  sqlite3.Row is now initialized in
  the __new__() method.

- bpo-16037: HTTPMessage.readheaders() raises an HTTPException when more
  than 100 headers are read. Patch by Jyrki Pulliainen and Daniel Eriksson.

- bpo-21580: Now Tkinter correctly handles binary "data" and "maskdata"
  configure options of tkinter.PhotoImage.

- bpo-19612: subprocess.communicate() now also ignores EINVAL when using at
  least two pipes.

- Fix repr(_socket.socket) on Windows 64-bit: don't fail with OverflowError
  on closed socket.

- bpo-16133: The asynchat.async_chat.handle_read() method now ignores
  socket.error() exceptions with blocking I/O errors: EAGAIN, EALREADY,
  EINPROGRESS, or EWOULDBLOCK.

- bpo-21990: Clean-up unnecessary and slow inner class definition in
  saxutils (Contributed by Alex Gaynor).

- bpo-1730136: Fix the comparison between a tkFont.Font and an object of
  another kind.

- bpo-19884: readline: Disable the meta modifier key if stdout is not a
  terminal to not write the ANSI sequence "\033[1034h" into stdout. This
  sequence is used on some terminal (ex: TERM=xterm-256color") to enable
  support of 8 bit characters.

- bpo-22017: Correct reference counting error in the initialization of the
  _warnings module.

- bpo-21868: Prevent turtle crash when undo buffer set to a value less than
  one.

- bpo-21151: Fixed a segfault in the _winreg module when ``None`` is passed
  as a ``REG_BINARY`` value to SetValueEx.  Patch by John Ehresman.

- bpo-21090: io.FileIO.readall() does not ignore I/O errors anymore. Before,
  it ignored I/O errors if at least the first C call read() succeed.

- bpo-19870: BaseCookie now parses 'secure' and 'httponly' flags. Backport
  of issue #16611.

- bpo-21923: Prevent AttributeError in
  distutils.sysconfig.customize_compiler due to possible uninitialized
  _config_vars.

- bpo-21323: Fix CGIHTTPServer to again handle scripts in CGI
  subdirectories, broken by the fix for security issue #19435.  Patch by
  Zach Byrne.

- bpo-22199: Make get_makefile_filename() available in Lib/sysconfig.py for
  2.7 to match other versions of sysconfig.

IDLE
----

- bpo-3068: Add Idle extension configuration dialog to Options menu. Changes
  are written to HOME/.idlerc/config-extensions.cfg. Original patch by Tal
  Einat.

- bpo-16233: A module browser (File : Class Browser, Alt+C) requires an
  editor window with a filename.  When Class Browser is requested otherwise,
  from a shell, output window, or 'Untitled' editor, Idle no longer displays
  an error box. It now pops up an Open Module box (Alt+M). If a valid name
  is entered and a module is opened, a corresponding browser is also opened.

- bpo-4832: Save As to type Python files automatically adds .py to the name
  you enter (even if your system does not display it).  Some systems
  automatically add .txt when type is Text files.

- bpo-21986: Code objects are not normally pickled by the pickle module. To
  match this, they are no longer pickled when running under Idle.

- bpo-22221: IDLE now ignores the source encoding declaration on the second
  line if the first line contains anything except a comment.

- bpo-17390: Adjust Editor window title; remove 'Python', move version to
  end.

- bpo-14105: Idle debugger breakpoints no longer disappear when inserting or
  deleting lines.

Library
-------

- bpo-22381: Update zlib to 1.2.8.

- bpo-22176: Update the ctypes module's libffi to v3.1.  This release adds
  support for the Linux AArch64 and POWERPC ELF ABIv2 little endian
  architectures.

Tools/Demos
-----------

- bpo-10712: 2to3 has a new "asserts" fixer that replaces deprecated names
  of unittest methods (e.g. failUnlessEqual -> assertEqual).

- bpo-22221: 2to3 and the findnocoding.py script now ignore the source
  encoding declaration on the second line if the first line contains
  anything except a comment.

- bpo-22201: Command-line interface of the zipfile module now correctly
  extracts ZIP files with directory entries.  Patch by Ryan Wilson.

Tests
-----

- bpo-22236: Tkinter tests now don't reuse default root window.  New root
  window is created for every test class.

- bpo-18004: test_overflow in test_list by mistake consumed 40 GiB of memory
  on 64-bit systems.

- bpo-21976: Fix test_ssl to accept LibreSSL version strings.  Thanks to
  William Orr.

- bpo-22770: Prevent some Tk segfaults on OS X when running gui tests.

Build
-----

- bpo-20221: Removed conflicting (or circular) hypot definition when
  compiled with VS 2010 or above.  Initial patch by Tabrez Mohammed.

- bpo-16537: Check whether self.extensions is empty in setup.py. Patch by
  Jonathan Hosmer.

- The documentation Makefile no longer automatically downloads Sphinx. Users
  are now required to have Sphinx already installed to build the
  documentation.

- bpo-21958: Define HAVE_ROUND when building with Visual Studio 2013 and
  above.  Patch by Zachary Turner.

- bpo-15759: "make suspicious", "make linkcheck" and "make doctest" in Doc/
  now display special message when and only when there are failures.

- bpo-21166: Prevent possible segfaults and other random failures of python
  ``--generate-posix-vars`` in pybuilddir.txt build target.

- bpo-18096: Fix library order returned by python-config.

- bpo-17219: Add library build dir for Python extension cross-builds.

- bpo-22877: PEP 477 - OS X installer now installs pip.

- bpo-22878: PEP 477 - "make install" and "make altinstall" can now install
  or upgrade pip, using the bundled pip provided by the backported ensurepip
  module.  A configure option, --with-ensurepip[=upgrade|install|no], is
  available to set the option for subsequent installs; the default for
  Python 2 in "no" (do not install or upgrade pip).  The option can also be
  set with "make [alt]install ENSUREPIP=[upgrade|install|no]".

Windows
-------

- bpo-17896: The Windows build scripts now expect external library sources
  to be in ``PCbuild\..\externals`` rather than ``PCbuild\..\..``.

- bpo-17717: The Windows build scripts now use a copy of NASM pulled from
  svn.python.org to build OpenSSL.

- bpo-22644: The bundled version of OpenSSL has been updated to 1.0.1j.


What's New in Python 2.7.8 final?
=================================

*Release date: 2014-06-29*

Core and Builtins
-----------------

- bpo-4346: In PyObject_CallMethod and PyObject_CallMethodObjArgs, don't
  overwrite the error set in PyObject_GetAttr.

- bpo-21831: Avoid integer overflow when large sizes and offsets are given
  to the buffer type. CVE-2014-7185.

- bpo-19656: Running Python with the -3 option now also warns about
  non-ascii bytes literals.

- bpo-21642: If the conditional if-else expression, allow an integer written
  with no space between itself and the ``else`` keyword (e.g. ``True if
  42else False``) to be valid syntax.

- bpo-21523: Fix over-pessimistic computation of the stack effect of some
  opcodes in the compiler.  This also fixes a quadratic compilation time
  issue noticeable when compiling code with a large number of "and" and "or"
  operators.

Library
-------

- bpo-21652: Prevent mimetypes.type_map from containing unicode keys on
  Windows.

- bpo-21729: Used the "with" statement in the dbm.dumb module to ensure
  files closing.

- bpo-21672: Fix the behavior of ntpath.join on UNC-style paths.

- bpo-19145: The times argument for itertools.repeat now handles negative
  values the same way for keyword arguments as it does for positional
  arguments.

- bpo-21832: Require named tuple inputs to be exact strings.

- bpo-8343: Named group error messages in the re module did not show the
  name of the erroneous group.

- bpo-21491: SocketServer: Fix a race condition in child processes reaping.

- bpo-21635: The difflib SequenceMatcher.get_matching_blocks() method cache
  didn't match the actual result.  The former was a list of tuples and the
  latter was a list of named tuples.

- bpo-21722: The distutils "upload" command now exits with a non-zero return
  code when uploading fails.  Patch by Martin Dengler.

- bpo-21766: Prevent a security hole in CGIHTTPServer by URL unquoting paths
  before checking for a CGI script at that path.

- bpo-21310: Fixed possible resource leak in failed open().

- bpo-21304: Backport the key derivation function hashlib.pbkdf2_hmac from
  Python 3 per PEP 466.

- bpo-11709: Fix the pydoc.help function to not fail when sys.stdin is not a
  valid file.

- bpo-13223: Fix pydoc.writedoc so that the HTML documentation for methods
  that use 'self' in the example code is generated correctly.

- bpo-21552: Fixed possible integer overflow of too long string lengths in
  the tkinter module on 64-bit platforms.

- bpo-14315: The zipfile module now ignores extra fields in the central
  directory that are too short to be parsed instead of letting a
  struct.unpack error bubble up as this "bad data" appears in many real
  world zip files in the wild and is ignored by other zip tools.

- bpo-21402: Tkinter.ttk now works when default root window is not set.

- bpo-10203: sqlite3.Row now truly supports sequence protocol.  In particulr
  it supports reverse() and negative indices.  Original patch by Claudiu
  Popa.

- bpo-8743: Fix interoperability between set objects and the
  collections.Set() abstract base class.

- bpo-21481: Argparse equality and inequality tests now return
  NotImplemented when comparing to an unknown type.

IDLE
----

- bpo-21940: Add unittest for WidgetRedirector. Initial patch by Saimadhav
  Heblikar.

- bpo-18592: Add unittest for SearchDialogBase. Patch by Phil Webster.

- bpo-21694: Add unittest for ParenMatch. Patch by Saimadhav Heblikar.

- bpo-21686: add unittest for HyperParser. Original patch by Saimadhav
  Heblikar.

- bpo-12387: Add missing upper(lower)case versions of default Windows key
  bindings for Idle so Caps Lock does not disable them. Patch by Roger
  Serwy.

- bpo-21695: Closing a Find-in-files output window while the search is still
  in progress no longer closes Idle.

- bpo-18910: Add unittest for textView. Patch by Phil Webster.

- bpo-18292: Add unittest for AutoExpand. Patch by Saihadhav Heblikar.

- bpo-18409: Add unittest for AutoComplete. Patch by Phil Webster.

Tests
-----

- bpo-20155: Changed HTTP method names in failing tests in test_httpservers
  so that packet filtering software (specifically Windows Base Filtering
  Engine) does not interfere with the transaction semantics expected by the
  tests.

- bpo-19493: Refactored the ctypes test package to skip tests explicitly
  rather than silently.

- bpo-18492: All resources are now allowed when tests are not run by
  regrtest.py.

- bpo-21605: Added tests for Tkinter images.

- bpo-21493: Added test for ntpath.expanduser().  Original patch by Claudiu
  Popa.

- bpo-19925: Added tests for the spwd module. Original patch by Vajrasky
  Kok.

- bpo-13355: random.triangular() no longer fails with a ZeroDivisionError
  when low equals high.

- bpo-21522: Added Tkinter tests for Listbox.itemconfigure(),
  PanedWindow.paneconfigure(), and Menu.entryconfigure().

- bpo-20635: Added tests for Tk geometry managers.

Build
-----

- bpo-21811: Anticipated fixes to support OS X versions > 10.9.

Windows
-------

- bpo-21671: The bundled version of OpenSSL has been updated to 1.0.1h. (See
  also: CVE-2014-0224)


What's New in Python 2.7.7 final?
=================================

*Release date: 2014-05-31*

Build
-----

- bpo-21462: Build the Windows installers with OpenSSL 1.0.1g.

- bpo-19866: Include some test data in the Windows installers, so tests
  don't fail.


What's New in Python 2.7.7 release candidate 1?
===============================================

*Release date: 2014-05-17*

Core and Builtins
-----------------

- bpo-21350: Fix file.writelines() to accept arbitrary buffer objects, as
  advertised. Patch by Brian Kearns.

- bpo-20437: Fixed 43 potential bugs when deleting object references.

- bpo-21134: Fix segfault when str is called on an uninitialized
  UnicodeEncodeError, UnicodeDecodeError, or UnicodeTranslateError object.

- bpo-20494: Ensure that free()d memory arenas are really released on POSIX
  systems supporting anonymous memory mappings.  Patch by Charles-François
  Natali.

- bpo-17825: Cursor "^" is correctly positioned for SyntaxError and
  IndentationError.

- Raise a better error when non-unicode codecs are used for a file's coding
  cookie.

- bpo-17976: Fixed potential problem with file.write() not detecting IO
  error by inspecting the return value of fwrite().  Based on patches by
  Jaakko Moisio and Victor Stinner.

- bpo-14432: Generator now clears the borrowed reference to the thread
  state. Fix a crash when a generator is created in a C thread that is
  destroyed while the generator is still used. The issue was that a
  generator contains a frame, and the frame kept a reference to the Python
  state of the destroyed C thread. The crash occurs when a trace function is
  setup.

- bpo-19932: Fix typo in import.h, missing whitespaces in function
  prototypes.

- bpo-19638: Fix possible crash / undefined behaviour from huge (more than 2
  billion characters) input strings in _Py_dg_strtod.

- bpo-12546: Allow \x00 to be used as a fill character when using str, int,
  float, and complex __format__ methods.

Library
-------

- bpo-10744: Fix PEP 3118 format strings on ctypes objects with a nontrivial
  shape.

- bpo-7776: Backport Fix ``Host:'' header and reconnection when using
  http.client.HTTPConnection.set_tunnel() from Python 3.  Patch by Nikolaus
  Rath.

- bpo-21306: Backport hmac.compare_digest from Python 3. This is part of PEP
  466.

- bpo-21470: Do a better job seeding the random number generator by using
  enough bytes to span the full state space of the Mersenne Twister.

- bpo-21469: Reduced the risk of false positives in robotparser by checking
  to make sure that robots.txt has been read or does not exist prior to
  returning True in can_fetch().

- bpo-21321: itertools.islice() now releases the reference to the source
  iterator when the slice is exhausted.  Patch by Anton Afanasyev.

- bpo-9291: Do not attempt to re-encode mimetype data read from registry in
  ANSI mode. Initial patches by Dmitry Jemerov & Vladimir Iofik.

- bpo-21349: Passing a memoryview to _winreg.SetValueEx now correctly raises
  a TypeError where it previously crashed the interpreter. Patch by Brian
  Kearns

- bpo-21529: Fix arbitrary memory access in JSONDecoder.raw_decode with a
  negative second parameter. Bug reported by Guido Vranken. (See also:
  CVE-2014-4616)

- bpo-21172: isinstance check relaxed from dict to collections.Mapping.

- bpo-21191: In os.fdopen, never close the file descriptor when an exception
  happens.

- bpo-21149: Improved thread-safety in logging cleanup during interpreter
  shutdown. Thanks to Devin Jeanpierre for the patch.

- Fix possible overflow bug in strop.expandtabs. You shouldn't be using this
  module!

- bpo-20145: `assertRaisesRegex` now raises a TypeError if the second
  argument is not a string or compiled regex.

- bpo-21058: Fix a leak of file descriptor in tempfile.NamedTemporaryFile(),
  close the file descriptor if os.fdopen() fails

- bpo-20283: RE pattern methods now accept the string keyword parameters as
  documented. The pattern and source keyword parameters are left as
  deprecated aliases.

- bpo-11599: When an external command (e.g. compiler) fails, distutils now
  prints out the whole command line (instead of just the command name) if
  the environment variable DISTUTILS_DEBUG is set.

- bpo-4931: distutils should not produce unhelpful "error: None" messages
  anymore. distutils.util.grok_environment_error is kept but doc-deprecated.

- Improve the random module's default seeding to use 256 bits of entropy
  from os.urandom().  This was already done for Python 3, mildly improving
  security with a bigger seed space.

- bpo-15618: Make turtle.py compatible with 'from __future__ import
  unicode_literals'. Initial patch by Juancarlo Añez.

- bpo-20501: fileinput module no longer reads whole file into memory when
  using fileinput.hook_encoded.

- bpo-6815: os.path.expandvars() now supports non-ASCII Unicode environment
  variables names and values.

- bpo-20635: Fixed grid_columnconfigure() and grid_rowconfigure() methods of
  Tkinter widgets to work in wantobjects=True mode.

- bpo-17671: Fixed a crash when use non-initialized io.BufferedRWPair. Based
  on patch by Stephen Tu.

- bpo-8478: Untokenizer.compat processes first token from iterator input.
  Patch based on lines from Georg Brandl, Eric Snow, and Gareth Rees.

- bpo-20594: Avoid name clash with the libc function posix_close.

- bpo-19856: shutil.move() failed to move a directory to other directory on
  Windows if source name ends with os.altsep.

- bpo-14983: email.generator now always adds a line end after each MIME
  boundary marker, instead of doing so only when there is an epilogue.  This
  fixes an RFC compliance bug and solves an issue with signed MIME parts.

- bpo-20013: Some imap servers disconnect if the current mailbox is deleted,
  and imaplib did not handle that case gracefully.  Now it handles the 'bye'
  correctly.

- bpo-20426: When passing the re.DEBUG flag, re.compile() displays the debug
  output every time it is called, regardless of the compilation cache.

- bpo-20368: The null character now correctly passed from Tcl to Python (in
  unicode strings only).  Improved error handling in variables-related
  commands.

- bpo-20435: Fix _pyio.StringIO.getvalue() to take into account newline
  translation settings.

- bpo-20288: fix handling of invalid numeric charrefs in HTMLParser.

- bpo-19456: ntpath.join() now joins relative paths correctly when a drive
  is present.

- bpo-8260: The read(), readline() and readlines() methods of
  codecs.StreamReader returned incomplete data when were called after
  readline() or read(size). Based on patch by Amaury Forgeot d'Arc.

- bpo-20374: Fix build with GNU readline >= 6.3.

- bpo-14548: Make multiprocessing finalizers check pid before running to
  cope with possibility of gc running just after fork. (Backport from 3.x.)

- bpo-20262: Warnings are raised now when duplicate names are added in the
  ZIP file or too long ZIP file comment is truncated.

- bpo-20270: urllib and urlparse now support empty ports.

- bpo-20243: TarFile no longer raise ReadError when opened in write mode.

- bpo-20245: The open functions in the tarfile module now correctly handle
  empty mode.

- bpo-20086: Restored the use of locale-independent mapping instead of
  locale-dependent str.lower() in locale.normalize().

- bpo-20246: Fix buffer overflow in socket.recvfrom_into.

- bpo-19082: Working SimpleXMLRPCServer and xmlrpclib examples, both in
  modules and documentation.

- bpo-13107: argparse and optparse no longer raises an exception when output
  a help on environment with too small COLUMNS.  Based on patch by Elazar
  Gershuni.

- bpo-20207: Always disable SSLv2 except when PROTOCOL_SSLv2 is explicitly
  asked for.

- bpo-20072: Fixed multiple errors in tkinter with wantobjects is False.

- bpo-1065986: pydoc can now handle unicode strings.

- bpo-16039: CVE-2013-1752: Change use of readline in imaplib module to
  limit line length.  Patch by Emil Lind.

- bpo-19422: Explicitly disallow non-SOCK_STREAM sockets in the ssl module,
  rather than silently let them emit clear text data.

- bpo-20027: Fixed locale aliases for devanagari locales.

- bpo-20067: Tkinter variables now work when wantobjects is false.

- bpo-19020: Tkinter now uses splitlist() instead of split() in configure
  methods.

- bpo-12226: HTTPS is now used by default when connecting to PyPI.

- bpo-20048: Fixed ZipExtFile.peek() when it is called on the boundary of
  the uncompress buffer and read() goes through more than one readbuffer.

- bpo-20034: Updated alias mapping to most recent locale.alias file from
  X.org distribution using makelocalealias.py.

- bpo-5815: Fixed support for locales with modifiers.  Fixed support for
  locale encodings with hyphens.

- bpo-20026: Fix the sqlite module to handle correctly invalid isolation
  level (wrong type).

- bpo-18829: csv.Dialect() now checks type for delimiter, escapechar and
  quotechar fields.  Original patch by Vajrasky Kok.

- bpo-19855: uuid.getnode() on Unix now looks on the PATH for the
  executables used to find the mac address, with /sbin and /usr/sbin as
  fallbacks.

- bpo-20007: HTTPResponse.read(0) no more prematurely closes connection.
  Original patch by Simon Sapin.

- bpo-19912: Fixed numerous bugs in ntpath.splitunc().

- bpo-19623: Fixed writing to unseekable files in the aifc module. Fixed
  writing 'ulaw' (lower case) compressed AIFC files.

- bpo-17919: select.poll.register() again works with poll.POLLNVAL on AIX.
  Fixed integer overflow in the eventmask parameter.

- bpo-17200: telnetlib's read_until and expect timeout was broken by the fix
  to Issue #14635 in Python 2.7.4 to be interpreted as milliseconds instead
  of seconds when the platform supports select.poll (ie: everywhere). It is
  now treated as seconds once again.

- bpo-19099: The struct module now supports Unicode format strings.

- bpo-19878: Fix segfault in bz2 module after calling __init__ twice with
  non-existent filename. Initial patch by Vajrasky Kok.

- bpo-16373: Prevent infinite recursion for ABC Set class comparisons.

- bpo-19138: doctest's IGNORE_EXCEPTION_DETAIL now allows a match when no
  exception detail exists (no colon following the exception's name, or a
  colon does follow but no text follows the colon).

- bpo-16231: Fixed pickle.Pickler to only fallback to its default pickling
  behaviour when Pickler.persistent_id returns None, but not for any other
  false values. This allows false values other than None to be used as
  persistent IDs.  This behaviour is consistent with cPickle.

- bpo-11508: Fixed uuid.getnode() and uuid.uuid1() on environment with
  virtual interface. Original patch by Kent Frazier.

- bpo-11489: JSON decoder now accepts lone surrogates.

- Fix test.test_support.bind_port() to not cause an error when Python was
  compiled on a system with SO_REUSEPORT defined in the headers but run on a
  system with an OS kernel that does not support that new socket option.

- bpo-19633: Fixed writing not compressed 16- and 32-bit wave files on
  big-endian platforms.

- bpo-19449: in csv's writerow, handle non-string keys when generating the
  error message that certain keys are not in the 'fieldnames' list.

- bpo-12853: Fix NameError in distutils.command.upload.

- bpo-19523: Closed FileHandler leak which occurred when delay was set.

- bpo-1575020: Fixed support of 24-bit wave files on big-endian platforms.

- bpo-19480: HTMLParser now accepts all valid start-tag names as defined by
  the HTML5 standard.

- bpo-17827: Add the missing documentation for ``codecs.encode`` and
  ``codecs.decode``.

- bpo-6157: Fixed Tkinter.Text.debug().  Original patch by Guilherme Polo.

- bpo-6160: The bbox() method of tkinter.Spinbox now returns a tuple of
  integers instead of a string.  Based on patch by Guilherme Polo.

- bpo-19286: Directories in ``package_data`` are no longer added to the
  filelist, preventing failure outlined in the ticket.

- bpo-6676: Ensure a meaningful exception is raised when attempting to parse
  more than one XML document per pyexpat xmlparser instance. (Original
  patches by Hirokazu Yamamoto and Amaury Forgeot d'Arc, with suggested
  wording by David Gutteridge)

- bpo-21311: Avoid exception in _osx_support with non-standard compiler
  configurations. Patch by John Szakmeister.

Tools/Demos
-----------

- bpo-3561: The Windows installer now has an option, off by default, for
  placing the Python installation into the system "Path" environment
  variable. This was backported from Python 3.3.

- Add support for ``yield from`` to 2to3.

- Add support for the PEP 465 matrix multiplication operator to 2to3.

- bpo-19936: Added executable bits or shebang lines to Python scripts which
  requires them.  Disable executable bits and shebang lines in test and
  benchmark files in order to prevent using a random system python, and in
  source files of modules which don't provide command line interface.

IDLE
----

- bpo-18104: Add idlelib/idle_test/htest.py with a few sample tests to begin
  consolidating and improving human-validated tests of Idle. Change other
  files as needed to work with htest.  Running the module as __main__ runs
  all tests.

- bpo-21139: Change default paragraph width to 72, the PEP 8 recommendation.

- bpo-21284: Paragraph reformat test passes after user changes reformat
  width.

- bpo-20406: Use Python application icons for Idle window title bars. Patch
  mostly by Serhiy Storchaka.

- bpo-21029: Occurrences of "print" are now consistently colored as being a
  keyword (the colorizer doesn't know if print functions are enabled in the
  source).

- bpo-17721: Remove non-functional configuration dialog help button until we
  make it actually gives some help when clicked. Patch by Guilherme Simões.

- bpo-17390: Add Python version to Idle editor window title bar. Original
  patches by Edmond Burnett and Kent Johnson.

- bpo-20058: sys.stdin.readline() in IDLE now always returns only one line.

- bpo-19481: print() of unicode, str or bytearray subclass instance in IDLE
  no more hangs.

- bpo-18270: Prevent possible IDLE AttributeError on OS X when no initial
  shell window is present.

- bpo-17654: Ensure IDLE menus are customized properly on OS X for
  non-framework builds and for all variants of Tk.

Tests
-----

- bpo-17752: Fix distutils tests when run from the installed location.

- bpo-18604: Consolidated checks for GUI availability.  All platforms now at
  least check whether Tk can be instantiated when the GUI resource is
  requested.

- bpo-20946: Correct alignment assumptions of some ctypes tests.

- bpo-20743: Fix a reference leak in test_tcl.

- bpo-20510: Rewrote test_exit in test_sys to match existing comments, use
  modern unittest features, and use helpers from test.script_helper instead
  of using subprocess directly.  Initial patch by Gareth Rees.

- bpo-20532: Tests which use _testcapi now are marked as CPython only.

- bpo-19920: Added tests for TarFile.list().  Based on patch by Vajrasky
  Kok.

- bpo-19990: Added tests for the imghdr module.  Based on patch by Claudiu
  Popa.

- bpo-19804: The test_find_mac test in test_uuid is now skipped if the
  ifconfig executable is not available.

- bpo-19886: Use better estimated memory requirements for bigmem tests.

- Backported tests for Tkinter variables.

- bpo-19320: test_tcl no longer fails when wantobjects is false.

- bpo-19683: Removed empty tests from test_minidom.  Initial patch by
  Ajitesh Gupta.

- bpo-19928: Implemented a test for repr() of cell objects.

- bpo-19595: Re-enabled a long-disabled test in test_winsound. (See also:
  bpo-19987)

- bpo-19588: Fixed tests in test_random that were silently skipped most of
  the time. Patch by Julian Gindi.

- bpo-17883: Tweak test_tcl testLoadWithUNC to skip the test in the event of
  a permission error on Windows and to properly report other skip
  conditions.

- bpo-17883: Backported _is_gui_available() in test.test_support to avoid
  hanging Windows buildbots on test_ttk_guionly.

- bpo-18702: All skipped tests now reported as skipped. (See also:
  bpo-19572)

- bpo-19085: Added basic tests for all tkinter widget options.

- bpo-20605: Make test_socket getaddrinfo OS X segfault test more robust.

- bpo-20939: Avoid various network test failures due to new redirect of
  http://www.python.org/ to https://www.python.org: use
  http://www.example.com instead.

- bpo-21093: Prevent failures of ctypes test_macholib on OS X if a copy of
  libz exists in $HOME/lib or /usr/local/lib.

Build
-----

- bpo-21285: Refactor and fix curses configure check to always search in a
  ncursesw directory.

Documentation
-------------

- bpo-20255: Update the about and bugs pages.

- bpo-18840: Introduce the json module in the tutorial, and de-emphasize the
  pickle module.

- bpo-19795: Improved markup of True/False constants.

Windows
-------

- bpo-21303: Updated the version of Tcl/Tk included in the installer from
  8.5.2 to 8.5.15. (See also: bpo-20565)

macOS
-----

- As of 2.7.8, the 32-bit-only installer will support OS X 10.5 and later
  systems as is currently done for Python 3.x installers. For 2.7.7 only, we
  will provide three installers: the legacy deprecated 10.3+ 32-bit-only
  format; the newer 10.5+ 32-bit-only format; and the unchanged 10.6+
  64-/32-bit format. Although binary installers will no longer be available
  from python.org as of 2.7.8, it will still be possible to build from
  source on 10.3.9 and 10.4 systems if necessary. See
  Mac/BuildScript/README.txt for more information.


What's New in Python 2.7.6 final?
=================================

*Release date: 2013-11-10*

Library
-------

- bpo-19435: Fix directory traversal attack on CGIHttpRequestHandler.

IDLE
----

- bpo-19426: Fixed the opening of Python source file with specified
  encoding.

Tests
-----

- bpo-19457: Fixed xmlcharrefreplace tests on wide build when tests are
  loaded from .py[co] files.

Build
-----

- bpo-15663: Revert OS X installer built-in Tcl/Tk support for 2.7.6. Some
  third-party projects, such as Matplotlib and PIL/Pillow, depended on being
  able to build with Tcl and Tk frameworks in /Library/Frameworks.


What's New in Python 2.7.6 release candidate 1?
===============================================

*Release date: 2013-10-26*

Core and Builtins
-----------------

- bpo-18603: Ensure that PyOS_mystricmp and PyOS_mystrnicmp are in the
  Python executable and not removed by the linker's optimizer.

- bpo-19279: UTF-7 decoder no more produces illegal unicode strings.

- bpo-18739: Fix an inconsistency between math.log(n) and math.log(long(n));
  the results could be off from one another by a ulp or two.

- bpo-13461: Fix a crash in the "replace" error handler on 64-bit platforms.
  Patch by Yogesh Chaudhari.

- bpo-15866: The xmlcharrefreplace error handler no more produces two XML
  entities for a non-BMP character on narrow build.

- bpo-18184: PyUnicode_FromFormat() and PyUnicode_FromFormatV() now raise
  OverflowError when an argument of %c format is out of range.

- bpo-18137: Detect integer overflow on precision in float.__format__() and
  complex.__format__().

- bpo-18038: SyntaxError raised during compilation sources with illegal
  encoding now always contains an encoding name.

- bpo-18019: Fix crash in the repr of dictionaries containing their own
  views.

- bpo-18427: str.replace could crash the interpreter with huge strings.

Library
-------

- bpo-19393: Fix symtable.symtable function to not be confused when there
  are functions or classes named "top".

- bpo-19327: Fixed the working of regular expressions with too big charset.

- bpo-19350: Increasing the test coverage of macurl2path. Patch by Colin
  Williams.

- bpo-19352: Fix unittest discovery when a module can be reached through
  several paths (e.g. under Debian/Ubuntu with virtualenv).

- bpo-15207: Fix mimetypes to read from correct part of Windows registry
  Original patch by Dave Chambers

- bpo-8964: fix platform._sys_version to handle IronPython 2.6+. Patch by
  Martin Matusiak.

- bpo-16038: CVE-2013-1752: ftplib: Limit amount of data read by limiting
  the call to readline().  Original patch by Michał Jastrzębski and
  Giampaolo Rodola.

- bpo-19276: Fixed the wave module on 64-bit big-endian platforms.

- bpo-18458: Prevent crashes with newer versions of libedit.  Its readline
  emulation has changed from 0-based indexing to 1-based like gnu readline.
  Original patch by Ronald Oussoren.

- bpo-18919: If the close() method of a writer in the sunau or wave module
  failed, second invocation of close() and destructor no more raise an
  exception.  Second invocation of close() on sunau writer now has no
  effects. The aifc module now accepts lower case of names of the 'ulaw' and
  'alaw' codecs.

- bpo-19131: The aifc module now correctly reads and writes sampwidth of
  compressed streams.

- bpo-19158: A rare race in BoundedSemaphore could allow .release() too
  often.

- bpo-18037: 2to3 now escapes '\u' and '\U' in native strings.

- bpo-19137: The pprint module now correctly formats empty set and frozenset
  and instances of set and frozenset subclasses.

- bpo-16040: CVE-2013-1752: nntplib: Limit maximum line lengths to 2048 to
  prevent readline() calls from consuming too much memory.  Patch by Jyrki
  Pulliainen.

- bpo-12641: Avoid passing "-mno-cygwin" to the mingw32 compiler, except
  when necessary. Patch by Oscar Benjamin.

- Properly initialize all fields of a SSL object after allocation.

- bpo-4366: Fix building extensions on all platforms when --enable-shared is
  used.

- bpo-18950: Fix miscellaneous bugs in the sunau module.
  Au_read.readframes() now updates current file position and reads correct
  number of frames from multichannel stream.  Au_write.writeframesraw() now
  correctly updates current file position.  Au_read and Au_write now
  correctly work with file object if start file position is not a zero.

- bpo-18050: Fixed an incompatibility of the re module with Python 2.7.3 and
  older binaries.

- bpo-19037: The mailbox module now makes all changes to maildir files
  before moving them into place, to avoid race conditions with other
  programs that may be accessing the maildir directory.

- bpo-14984: On POSIX systems, when netrc is called without a filename
  argument (and therefore is reading the user's $HOME/.netrc file), it now
  enforces the same security rules as typical ftp clients: the .netrc file
  must be owned by the user that owns the process and must not be readable
  by any other user.

- bpo-17324: Fix http.server's request handling case on trailing '/'. Patch
  contributed by Vajrasky Kok.

- bpo-19018: The heapq.merge() function no longer suppresses IndexError in
  the underlying iterables.

- bpo-18784: The uuid module no more attempts to load libc via ctypes.CDLL,
  if all necessary functions are already found in libuuid. Patch by Evgeny
  Sologubov.

- bpo-14971: unittest test discovery no longer gets confused when a function
  has a different __name__ than its name in the TestCase class dictionary.

- bpo-18672: Fixed format specifiers for Py_ssize_t in debugging output in
  the _sre module.

- bpo-18830: inspect.getclasstree() no more produces duplicated entries even
  when input list contains duplicates.

- bpo-18909: Fix _tkinter.tkapp.interpaddr() on Windows 64-bit, don't cast
  64-bit pointer to long (32 bits).

- bpo-18876: The FileIO.mode attribute now better reflects the actual mode
  under which the file was opened.  Patch by Erik Bray.

- bpo-18851: Avoid a double close of subprocess pipes when the child process
  fails starting.

- bpo-18418: After fork(), reinit all threads states, not only active ones.
  Patch by A. Jesse Jiryu Davis.

- bpo-11973: Fix a problem in kevent. The flags and fflags fields are now
  properly handled as unsigned.

- bpo-16809: Fixed some tkinter incompatibilities with Tcl/Tk 8.6.

- bpo-16809: Tkinter's splitlist() and split() methods now accept Tcl_Obj
  argument.

- bpo-17119: Fixed integer overflows when processing large Unicode strings
  and tuples in the tkinter module.

- bpo-15233: Python now guarantees that callables registered with the atexit
  module will be called in a deterministic order.

- bpo-18747: Re-seed OpenSSL's pseudo-random number generator after fork. A
  pthread_atfork() parent handler is used to seed the PRNG with pid, time
  and some stack data.

- bpo-8865: Concurrent invocation of select.poll.poll() now raises a
  RuntimeError exception.  Patch by Christian Schubert.

- bpo-13461: Fix a crash in the TextIOWrapper.tell method on 64-bit
  platforms.  Patch by Yogesh Chaudhari.

- bpo-18777: The ssl module now uses the new CRYPTO_THREADID API of OpenSSL
  1.0.0+ instead of the deprecated CRYPTO id callback function.

- bpo-18768: Correct doc string of RAND_edg(). Patch by Vajrasky Kok.

- bpo-18178: Fix ctypes on BSD. dlmalloc.c was compiled twice which broke
  malloc weak symbols.

- bpo-18709: Fix CVE-2013-4238. The SSL module now handles NULL bytes inside
  subjectAltName correctly. Formerly the module has used OpenSSL's
  GENERAL_NAME_print() function to get the string representation of ASN.1
  strings for ``rfc822Name`` (email), ``dNSName`` (DNS) and
  ``uniformResourceIdentifier`` (URI).

- bpo-18756: Improve error reporting in os.urandom() when the failure is due
  to something else than /dev/urandom not existing (for example, exhausting
  the file descriptor limit).

- Fix tkinter regression introduced by the security fix in issue #16248.

- bpo-18676: Change 'positive' to 'non-negative' in queue.py put and get
  docstrings and ValueError messages. Patch by Zhongyue Luo

- bpo-17998: Fix an internal error in regular expression engine.

- bpo-17557: Fix os.getgroups() to work with the modified behavior of
  getgroups(2) on OS X 10.8.  Original patch by Mateusz Lenik.

- bpo-18455: multiprocessing should not retry connect() with same socket.

- bpo-18513: Fix behaviour of cmath.rect w.r.t. signed zeros on OS X 10.8 +
  gcc.

- bpo-18101: Tcl.split() now process Unicode strings nested in a tuple as it
  do with byte strings.

- bpo-18347: ElementTree's html serializer now preserves the case of closing
  tags.

- bpo-17261: Ensure multiprocessing's proxies use proper address.

- bpo-17097: Make multiprocessing ignore EINTR.

- bpo-18155: The csv module now correctly handles csv files that use a
  delimiter character that has a special meaning in regexes, instead of
  throwing an exception.

- bpo-18135: ssl.SSLSocket.write() now raises an OverflowError if the input
  string in longer than 2 gigabytes. The ssl module does not support partial
  write.

- bpo-18167: cgi.FieldStorage no longer fails to handle multipart/form-data
  when \r\n appears at end of 65535 bytes without other newlines.

- bpo-17403: urllib.parse.robotparser normalizes the urls before adding to
  ruleline. This helps in handling certain types invalid urls in a
  conservative manner. Patch contributed by Mher Movsisyan.

- Implement inequality on weakref.WeakSet.

- bpo-17981: Closed socket on error in SysLogHandler.

- bpo-18015: Fix unpickling of 2.7.3 and 2.7.4 namedtuples.

- bpo-17754: Make ctypes.util.find_library() independent of the locale.

- Fix typos in the multiprocessing module.

- bpo-17269: Workaround for socket.getaddrinfo crash on MacOS X with port
  None or "0" and flags AI_NUMERICSERV.

- bpo-18080: When building a C extension module on OS X, if the compiler is
  overridden with the CC environment variable, use the new compiler as the
  default for linking if LDSHARED is not also overridden.  This restores
  Distutils behavior introduced in 2.7.3 and inadvertently dropped in 2.7.4.

- bpo-18071: C extension module builds on OS X could fail with TypeError if
  the Xcode command line tools were not installed.

- bpo-18113: Fixed a refcount leak in the curses.panel module's
  set_userptr() method. Reported by Atsuo Ishimoto.

- bpo-18849: Fixed a Windows-specific tempfile bug where collision with an
  existing directory caused mkstemp and related APIs to fail instead of
  retrying. Report and fix by Vlad Shcherbina.

- bpo-19400: Prevent extension module build failures with Xcode 5 on OS X
  10.8+ when using a universal Python that included a PPC architecture, such
  as with a python.org 32-bit-only binary installer.

Tools/Demos
-----------

- bpo-18873: 2to3 and the findnocoding.py script now detect Python source
  code encoding only in comment lines.

- bpo-18817: Fix a resource warning in Lib/aifc.py demo.

- bpo-18439: Make patchcheck work on Windows for ACKS, NEWS.

- bpo-18448: Fix a typo in Demo/newmetaclasses/Eiffel.py.

- bpo-12990: The "Python Launcher" on OSX could not launch python scripts
  that have paths that include wide characters.

Build
-----

- bpo-16067: Add description into MSI file to replace installer's temporary
  name.

- bpo-18256: Compilation fix for recent AIX releases.  Patch by David
  Edelsohn.

- bpo-18098: The deprecated OS X Build Applet.app fails to build on OS X
  10.8 systems because the Apple-deprecated QuickDraw headers have been
  removed from Xcode 4.  Skip building it in this case.

- bpo-1584: Provide options to override default search paths for Tcl and Tk
  when building _tkinter.

- bpo-15663: Tcl/Tk 8.5.15 is now included with the OS X 10.6+ 64-bit/32-bit
  installer for 10.6+.  It is no longer necessary to install a third-party
  version of Tcl/Tk 8.5 to work around the problems in the Apple-supplied
  Tcl/Tk 8.5 shipped in OS X 10.6 and later releases.

- bpo-19019: Change the OS X installer build script to use CFLAGS instead of
  OPT for special build options.  By setting OPT, some compiler-specific
  options like -fwrapv were overridden and thus not used, which could result
  in broken interpreters when building with clang.

IDLE
----

- bpo-18873: IDLE now detects Python source code encoding only in comment
  lines.

- bpo-18988: The "Tab" key now works when a word is already autocompleted.

- bpo-18489: Add tests for SearchEngine. Original patch by Phil Webster.

- bpo-18429: Format / Format Paragraph, now works when comment blocks are
  selected. As with text blocks, this works best when the selection only
  includes complete lines.

- bpo-18226: Add docstrings and unittests for FormatParagraph.py. Original
  patches by Todd Rovito and Phil Webster.

- bpo-18279: Format - Strip trailing whitespace no longer marks a file as
  changed when it has not been changed. This fix followed the addition of a
  test file originally written by Phil Webster (the issue's main goal).

- bpo-18539: Calltips now work for float default arguments.

- bpo-7136: In the Idle File menu, "New Window" is renamed "New File". Patch
  by Tal Einat, Roget Serwy, and Todd Rovito.

- bpo-8515: Set __file__ when run file in IDLE. Initial patch by Bruce
  Frederiksen.

- bpo-5492: Avoid traceback when exiting IDLE caused by a race condition.

- bpo-17511: Keep IDLE find dialog open after clicking "Find Next". Original
  patch by Sarah K.

- bpo-15392: Create a unittest framework for IDLE. Preliminary patch by
  Rajagopalasarma Jayakrishnan See Lib/idlelib/idle_test/README.txt for how
  to run Idle tests.

- bpo-14146: Highlight source line while debugging on Windows.

- bpo-17532: Always include Options menu for IDLE on OS X. Patch by
  Guilherme Simões.

Tests
-----

- bpo-18919: Added tests for the sunau module.  Unified and extended tests
  for audio modules: aifc, sunau and wave.

- bpo-18792: Use "127.0.0.1" or "::1" instead of "localhost" as much as
  possible, since "localhost" goes through a DNS lookup under recent Windows
  versions.

- bpo-18357: add tests for dictview set difference. Patch by Fraser
  Tweedale.

- bpo-11185: Fix test_wait4 under AIX.  Patch by Sébastien Sablé.

- bpo-18094: test_uuid no more reports skipped tests as passed.

- bpo-11995: test_pydoc doesn't import all sys.path modules anymore.

Documentation
-------------

- bpo-18758: Fixed and improved cross-references.

- bpo-18718: datetime documentation contradictory on leap second support.

- bpo-17701: Improving strftime documentation.

- bpo-17844: Refactor a documentation of Python specific encodings. Add
  links to encoders and decoders for binary-to-binary codecs.


What's New in Python 2.7.5 final?
=================================

*Release date: 2013-05-12*

Core and Builtins
-----------------

- bpo-15535: Fixed regression in the pickling of named tuples by removing
  the __dict__ property introduced in 2.7.4.

- bpo-17857: Prevent build failures with pre-3.5.0 versions of sqlite3, such
  as was shipped with Centos 5 and Mac OS X 10.4.

- bpo-17703: Fix a regression where an illegal use of Py_DECREF() after
  interpreter finalization can cause a crash.

- bpo-16447: Fixed potential segmentation fault when setting __name__ on a
  class.

- bpo-17610: Don't rely on non-standard behavior of the C qsort() function.

Library
-------

- bpo-17979: Fixed the re module in build with --disable-unicode.

- bpo-17606: Fixed support of encoded byte strings in the XMLGenerator
  .characters() and ignorableWhitespace() methods.  Original patch by
  Sebastian Ortiz Vasquez.

- bpo-16601: Restarting iteration over tarfile no more continues from where
  it left off. Patch by Michael Birtwell.

- bpo-16584: in filecomp._cmp, catch IOError as well as os.error. Patch by
  Till Maas.

- bpo-17926: Fix dbm.__contains__ on 64-bit big-endian machines.

- bpo-19267: Fix support of multibyte encoding (ex: UTF-16) in the logging
  module.

- bpo-17918: When using SSLSocket.accept(), if the SSL handshake failed on
  the new socket, the socket would linger indefinitely.  Thanks to Peter
  Saveliev for reporting.

- bpo-17289: The readline module now plays nicer with external modules or
  applications changing the rl_completer_word_break_characters global
  variable.  Initial patch by Bradley Froehle.

- bpo-12181: select module: Fix struct kevent definition on OpenBSD 64-bit
  platforms. Patch by Federico Schwindt.

- bpo-14173: Avoid crashing when reading a signal handler during interpreter
  shutdown.

- bpo-16316: mimetypes now recognizes the .xz and .txz (.tar.xz) extensions.

- bpo-17192: Restore the patch for Issue #10309 which was ommitted in 2.7.4
  when updating the bundled version of libffi used by ctypes.

- bpo-17843: Removed test data file that was triggering false-positive virus
  warnings with certain antivirus software.

- bpo-17353: Plistlib emitted empty data tags with deeply nested
  datastructures

- bpo-11714: Use 'with' statements to assure a Semaphore releases a
  condition variable. Original patch by Thomas Rachel.

- bpo-17795: Reverted backwards-incompatible change in SysLogHandler with
  Unix domain sockets.

- bpo-17555: Fix ForkAwareThreadLock so that size of after fork registry
  does not grow exponentially with generation of process.

- bpo-17710: Fix cPickle raising a SystemError on bogus input.

- bpo-17341: Include the invalid name in the error messages from re about
  invalid group names.

- bpo-17016: Get rid of possible pointer wraparounds and integer overflows
  in the re module.  Patch by Nickolai Zeldovich.

- bpo-17536: Add to webbrowser's browser list: xdg-open, gvfs-open,
  www-browser, x-www-browser, chromium browsers, iceweasel, iceape.

- bpo-17656: Fix extraction of zip files with unicode member paths.

- bpo-17666: Fix reading gzip files with an extra field.

- bpo-13150: sysconfig no longer parses the Makefile and config.h files when
  imported, instead doing it at build time.  This makes importing sysconfig
  faster and reduces Python startup time by 20%. (See also: bpo-17512)

- bpo-13163: Rename operands in smtplib.SMTP._get_socket to correct names;
  fixes otherwise misleading output in tracebacks and when when debug is on.

- bpo-17526: fix an IndexError raised while passing code without filename to
  inspect.findsource().  Initial patch by Tyler Doyle.

Build
-----

- bpo-17547: In configure, explicitly pass -Wformat for the benefit for GCC
  4.8.

- bpo-17682: Add the _io module to Modules/Setup.dist (commented out).

- bpo-17086: Search the include and library directories provided by the
  compiler.

Tests
-----

- bpo-17928: Fix test_structmembers on 64-bit big-endian machines.

- bpo-17883: Fix buildbot testing of Tkinter on Windows. Patch by Zachary
  Ware.

- bpo-7855: Add tests for ctypes/winreg for issues found in IronPython.
  Initial patch by Dino Viehland.

- bpo-17712: Fix test_gdb failures on Ubuntu 13.04.

- bpo-17065: Use process-unique key for winreg tests to avoid failures if
  test is run multiple times in parallel (eg: on a buildbot host).

IDLE
----

- bpo-17838: Allow sys.stdin to be reassigned.

- bpo-14735: Update IDLE docs to omit "Control-z on Windows".

- bpo-17585: Fixed IDLE regression. Now closes when using exit() or quit().

- bpo-17657: Show full Tk version in IDLE's about dialog. Patch by Todd
  Rovito.

- bpo-17613: Prevent traceback when removing syntax colorizer in IDLE.

- bpo-1207589: Backwards-compatibility patch for right-click menu in IDLE.

- bpo-16887: IDLE now accepts Cancel in tabify/untabify dialog box.

- bpo-14254: IDLE now handles readline correctly across shell restarts.

- bpo-17614: IDLE no longer raises exception when quickly closing a file.

- bpo-6698: IDLE now opens just an editor window when configured to do so.

- bpo-8900: Using keyboard shortcuts in IDLE to open a file no longer raises
  an exception.

- bpo-6649: Fixed missing exit status in IDLE. Patch by Guilherme Polo.

- bpo-17390: Display Python version on Idle title bar. Initial patch by
  Edmond Burnett.

Documentation
-------------

- bpo-15940: Specify effect of locale on time functions.

- bpo-6696: add documentation for the Profile objects, and improve
  profile/cProfile docs.  Patch by Tom Pinckney.


What's New in Python 2.7.4 final?
=================================

*Release date: 2013-04-06*

Build
-----

- bpo-17550: Fix the --enable-profiling configure switch.

Core and Builtins
-----------------

- bpo-15801: With string % formatting, relax the type check for a mapping
  such that any type with a __getitem__ can be used on the right hand side.

IDLE
----

- bpo-17625: In IDLE, close the replace dialog after it is used.

Tests
-----

- bpo-17835: Fix test_io when the default OS pipe buffer size is larger than
  one million bytes.

- bpo-17531: Fix tests that thought group and user ids were always the int
  type. Also, always allow -1 as a valid group and user id.

- bpo-17533: Fix test_xpickle with older versions of Python 2.5.

Documentation
-------------

- bpo-17538: Document XML vulnerabilties


What's New in Python 2.7.4 release candidate 1?
===============================================

*Release date: 2013-03-23*

Core and Builtins
-----------------

- bpo-10211: Buffer objects expose the new buffer interface internally

- bpo-16445: Fixed potential segmentation fault when deleting an exception
  message.

- bpo-17275: Corrected class name in init error messages of the C version of
  BufferedWriter and BufferedRandom.

- bpo-7963: Fixed misleading error message that issued when object is called
  without arguments.

- bpo-5308: Raise ValueError when marshalling too large object (a sequence
  with size >= 2**31), instead of producing illegal marshal data.

- bpo-17043: The unicode-internal decoder no longer read past the end of
  input buffer.

- bpo-16979: Fix error handling bugs in the unicode-escape-decode decoder.

- bpo-10156: In the interpreter's initialization phase, unicode globals are
  now initialized dynamically as needed.

- bpo-16975: Fix error handling bug in the escape-decode decoder.

- bpo-14850: Now a charmap decoder treats U+FFFE as "undefined mapping" in
  any mapping, not only in a Unicode string.

- bpo-11461: Fix the incremental UTF-16 decoder. Original patch by Amaury
  Forgeot d'Arc.

- bpo-16367: Fix FileIO.readall() on Windows for files larger than 2 GB.

- bpo-15516: Fix a bug in PyString_FromFormat where it failed to properly
  ignore errors from a __int__() method.

- bpo-16839: Fix a segfault when calling unicode() on a classic class early
  in interpreter initialization.

- bpo-16761: Calling ``int()`` and ``long()`` with *base* argument only now
  raises TypeError.

- bpo-16759: Support the full DWORD (unsigned long) range in Reg2Py when
  retrieving a REG_DWORD value. This corrects functions like
  winreg.QueryValueEx that may have been returning truncated values.

- bpo-14420: Support the full DWORD (unsigned long) range in Py2Reg when
  passed a REG_DWORD value. Fixes ValueError in winreg.SetValueEx when given
  a long.

- bpo-13863: Work around buggy 'fstat' implementation on Windows / NTFS that
  lead to incorrect timestamps (off by one hour) being stored in .pyc files
  on some systems.

- bpo-16602: When a weakref's target was part of a long deallocation chain,
  the object could remain reachable through its weakref even though its
  refcount had dropped to zero.

- bpo-9011: Fix hacky AST code that modified the CST when compiling a
  negated numeric literal.

- bpo-16306: Fix multiple error messages when unknown command line
  parameters where passed to the interpreter.  Patch by Hieu Nguyen.

- bpo-15379: Fix passing of non-BMP characters as integers for the charmap
  decoder (already working as unicode strings).  Patch by Serhiy Storchaka.

- bpo-16453: Fix equality testing of dead weakref objects.

- bpo-9535: Fix pending signals that have been received but not yet handled
  by Python to not persist after os.fork() in the child process.

- bpo-15001: fix segfault on "del sys.modules['__main__']". Patch by Victor
  Stinner.

- bpo-5057: the peepholer no longer optimizes subscription on unicode
  literals (e.g. u'foo'[0]) in order to produce compatible pyc files between
  narrow and wide builds.

- bpo-8401: assigning an int to a bytearray slice (e.g. b[3:4] = 5) now
  raises an error.

- bpo-14700: Fix buggy overflow checks for large width and precision in
  string formatting operations.

- bpo-16345: Fix an infinite loop when ``fromkeys`` on a dict subclass
  received a nonempty dict from the constructor.

- bpo-6074: Ensure cached bytecode files can always be updated by the user
  that created them, even when the source file is read-only.

- bpo-14783: Improve int() and long() docstrings and switch docstrings for
  unicode(), slice(), range(), and xrange() to use multi-line signatures.

- bpo-16030: Fix overflow bug in computing the `repr` of an xrange object
  with large start, step or length.

- bpo-16029: Fix overflow bug occurring when pickling xranges with large
  start, step or length.

- bpo-16037: Limit httplib's _read_status() function to work around broken
  HTTP servers and reduce memory usage. It's actually a backport of a Python
  3.2 fix. Thanks to Adrien Kunysz.

- bpo-16588: Silence unused-but-set warnings in Python/thread_pthread

- bpo-13992: The trashcan mechanism is now thread-safe.  This eliminates
  sporadic crashes in multi-thread programs when several long deallocator
  chains ran concurrently and involved subclasses of built-in container
  types.

- bpo-15801: Make sure mappings passed to '%' formatting are actually
  subscriptable.

- bpo-15604: Update uses of PyObject_IsTrue() to check for and handle errors
  correctly. Patch by Serhiy Storchaka.

- bpo-14579: Fix error handling bug in the utf-16 decoder.  Patch by Serhiy
  Storchaka.

- bpo-15368: An issue that caused bytecode generation to be
  non-deterministic when using randomized hashing (-R) has been fixed.

- bpo-15897: zipimport.c doesn't check return value of fseek(). Patch by
  Felipe Cruz.

- bpo-16369: Global PyTypeObjects not initialized with PyType_Ready(...).

- bpo-15033: Fix the exit status bug when modules invoked using -m switch,
  return the proper failure return value (1). Patch contributed by Jeff
  Knupp.

- bpo-12268: File readline, readlines and read() methods no longer lose data
  when an underlying read system call is interrupted.  IOError is no longer
  raised due to a read system call returning EINTR from within these
  methods.

- bpo-13512: Create ~/.pypirc securely (CVE-2011-4944).  Initial patch by
  Philip Jenvey, tested by Mageia and Debian.

- bpo-7719: Make distutils ignore ``.nfs*`` files instead of choking later
  on.  Initial patch by SilentGhost and Jeff Ramnani.

- bpo-10053: Don't close FDs when FileIO.__init__ fails. Loosely based on
  the work by Hirokazu Yamamoto.

- bpo-14775: Fix a potential quadratic dict build-up due to the garbage
  collector repeatedly trying to untrack dicts.

- bpo-14494: Fix __future__.py and its documentation to note that absolute
  imports are the default behavior in 3.0 instead of 2.7. Patch by Sven
  Marnach.

- bpo-14761: Fix potential leak on an error case in the import machinery.

- bpo-14699: Fix calling the classmethod descriptor directly.

- bpo-11603: Setting __repr__ to __str__ now raises a RuntimeError when
  repr() or str() is called on such an object.

- bpo-14658: Fix binding a special method to a builtin implementation of a
  special method with a different name.

- bpo-14612: Fix jumping around with blocks by setting f_lineno.

- bpo-13889: Check and (if necessary) set FPU control word before calling
  any of the dtoa.c string <-> float conversion functions, on MSVC builds of
  Python. This fixes issues when embedding Python in a Delphi app.

- bpo-14505: Fix file descriptor leak when deallocating file objects created
  with PyFile_FromString().

- bpo-14474: Save and restore exception state in thread.start_new_thread()
  while writing error message if the thread leaves an unhandled exception.

- bpo-13019: Fix potential reference leaks in bytearray.extend().  Patch by
  Suman Saha.

- bpo-14378: Fix compiling ast.ImportFrom nodes with a "__future__" string
  as the module name that was not interned.

- bpo-14331: Use significantly less stack space when importing modules by
  allocating path buffers on the heap instead of the stack.

- bpo-14334: Prevent in a segfault in type.__getattribute__ when it was not
  passed strings. Also fix segfaults in the __getattribute__ and __setattr__
  methods of old-style classes.

- bpo-14161: fix the __repr__ of file objects to escape the file name.

- bpo-1469629: Allow cycles through an object's __dict__ slot to be
  collected. (For example if ``x.__dict__ is x``).

- bpo-13521: dict.setdefault() now does only one lookup for the given key,
  making it "atomic" for many purposes.  Patch by Filip Gruszczyński.

- bpo-1602133: on Mac OS X a shared library build (``--enable-shared``) now
  fills the ``os.environ`` variable correctly.

- bpo-10538: When using the "s*" code with PyArg_ParseTuple() to fill a
  Py_buffer structure with data from an object supporting only the old
  PyBuffer interface, a reference to the source objects is now properly
  added to the Py_buffer.obj member.

Library
-------

- bpo-12718: Fix interaction with winpdb overriding __import__ by setting
  importer attribute on BaseConfigurator instance.

- bpo-17521: Corrected non-enabling of logger following two calls to
  fileConfig().

- bpo-17508: Corrected MemoryHandler configuration in dictConfig() where the
  target handler wasn't configured first.

- bpo-10212: cStringIO and struct.unpack support new buffer objects.

- bpo-12098: multiprocessing on Windows now starts child processes using the
  same sys.flags as the current process.  Initial patch by Sergey Mezentsev.

- bpo-8862: Fixed curses cleanup when getkey is interrupted by a signal.

- bpo-9090: When a socket with a timeout fails with EWOULDBLOCK or EAGAIN,
  retry the select() loop instead of bailing out.  This is because select()
  can incorrectly report a socket as ready for reading (for example, if it
  received some data with an invalid checksum).

- bpo-1285086: Get rid of the refcounting hack and speed up
  urllib.unquote().

- bpo-17368: Fix an off-by-one error in the Python JSON decoder that caused
  a failure while decoding empty object literals when object_pairs_hook was
  specified.

- bpo-17278: Fix a crash in heapq.heappush() and heapq.heappop() when the
  list is being resized concurrently.

- bpo-17018: Make Process.join() retry if os.waitpid() fails with EINTR.

- bpo-14720: sqlite3: Convert datetime microseconds correctly. Patch by Lowe
  Thiderman.

- bpo-17225: JSON decoder now counts columns in the first line starting with
  1, as in other lines.

- bpo-7842: backported fix for py_compile.compile() syntax error handling.

- bpo-13153: Tkinter functions now raise TclError instead of ValueError when
  a unicode argument contains non-BMP character.

- bpo-9669: Protect re against infinite loops on zero-width matching in
  non-greedy repeat.  Patch by Matthew Barnett.

- bpo-13169: The maximal repetition number in a regular expression has been
  increased from 65534 to 2147483647 (on 32-bit platform) or 4294967294 (on
  64-bit).

- bpo-16743: Fix mmap overflow check on 32 bit Windows.

- bpo-11311: StringIO.readline(0) now returns an empty string as all other
  file-like objects.

- bpo-16800: tempfile.gettempdir() no longer left temporary files when the
  disk is full. Original patch by Amir Szekely.

- bpo-13555: cPickle now supports files larger than 2 GiB.

- bpo-17052: unittest discovery should use self.testLoader.

- bpo-4591: Uid and gid values larger than 2**31 are supported now.

- bpo-17141: random.vonmisesvariate() no more hangs for large kappas.

- bpo-17149: Fix random.vonmisesvariate to always return results in the
  range [0, 2*math.pi].

- bpo-1470548: XMLGenerator now works with UTF-16 and UTF-32 encodings.

- bpo-6975: os.path.realpath() now correctly resolves multiple nested
  symlinks on POSIX platforms.

- bpo-7358: cStringIO.StringIO now supports writing to and reading from a
  stream larger than 2 GiB on 64-bit systems.

- bpo-10355: In SpooledTemporaryFile class mode and name properties and
  xreadlines method now work for unrolled files.  encoding and newlines
  properties now removed as they have no sense and always produced
  AttributeError.

- bpo-16686: Fixed a lot of bugs in audioop module.  Fixed crashes in
  avgpp(), maxpp() and ratecv().  Fixed an integer overflow in add(),
  bias(), and ratecv(). reverse(), lin2lin() and ratecv() no more lose
  precision for 32-bit samples. max() and rms() no more returns a negative
  result and various other functions now work correctly with 32-bit sample
  -0x80000000.

- bpo-17073: Fix some integer overflows in sqlite3 module.

- bpo-6083: Fix multiple segmentation faults occurred when PyArg_ParseTuple
  parses nested mutating sequence.

- bpo-5289: Fix ctypes.util.find_library on Solaris.

- bpo-17106: Fix a segmentation fault in io.TextIOWrapper when an underlying
  stream or a decoder produces data of an unexpected type (i.e. when
  io.TextIOWrapper initialized with text stream or use bytes-to-bytes
  codec).

- bpo-13994: Add compatibility alias in distutils.ccompiler for
  distutils.sysconfig.customize_compiler.

- bpo-15633: httplib.HTTPResponse is now mark closed when the server sends
  less than the advertised Content-Length.

- bpo-15881: Fixed atexit hook in multiprocessing.

- bpo-14340: Upgrade the embedded expat library to version 2.1.0.

- bpo-11159: SAX parser now supports unicode file names.

- bpo-6972: The zipfile module no longer overwrites files outside of its
  destination path when extracting malicious zip files.

- bpo-17049: Localized calendar methods now return unicode if a locale
  includes an encoding and the result string contains month or weekday (was
  regression from Python 2.6).

- bpo-4844: ZipFile now raises BadZipfile when opens a ZIP file with an
  incomplete "End of Central Directory" record.  Original patch by Guilherme
  Polo and Alan McIntyre.

- bpo-15505: `unittest.installHandler` no longer assumes SIGINT handler is
  set to a callable object.

- bpo-17051: Fix a memory leak in os.path.isdir() on Windows. Patch by
  Robert Xiao.

- bpo-13454: Fix a crash when deleting an iterator created by
  itertools.tee() if all other iterators were very advanced before.

- bpo-16992: On Windows in signal.set_wakeup_fd, validate the file
  descriptor argument.

- bpo-15861: tkinter now correctly works with lists and tuples containing
  strings with whitespaces, backslashes or unbalanced braces.

- bpo-10527: Use poll() instead of select() for multiprocessing pipes.

- bpo-9720: zipfile now writes correct local headers for files larger than 4
  GiB.

- bpo-13899: \A, \Z, and \B now correctly match the A, Z, and B literals
  when used inside character classes (e.g. '[\A]').  Patch by Matthew
  Barnett.

- bpo-16398: Optimize deque.rotate() so that it only moves pointers and
  doesn't touch the underlying data with increfs and decrefs.

- bpo-15109: Fix regression in sqlite3's iterdump method where it would die
  with an encoding error if the database contained string values containing
  non-ASCII. (Regression was introduced by fix for 9750).

- bpo-15545: Fix regression in sqlite3's iterdump method where it was
  failing if the connection used a row factory (such as sqlite3.Row) that
  produced unsortable objects. (Regression was introduced by fix for 9750).

- bpo-16828: Fix error incorrectly raised by bz2.compress(''). Patch by
  Martin Packman.

- bpo-9586: Redefine SEM_FAILED on MacOSX to keep compiler happy.

- bpo-10527: make multiprocessing use poll() instead of select() if
  available.

- bpo-16485: Now file descriptors are closed if file header patching failed
  on closing an aifc file.

- bpo-12065: connect_ex() on an SSL socket now returns the original errno
  when the socket's timeout expires (it used to return None).

- bpo-16713: Fix the parsing of tel url with params using urlparse module.

- bpo-16443: Add docstrings to regular expression match objects. Patch by
  Anton Kasyanov.

- bpo-8853: Allow port to be of type long for socket.getaddrinfo().

- bpo-16597: In buffered and text IO, call close() on the underlying stream
  if invoking flush() fails.

- bpo-15701: Fix HTTPError info method call to return the headers
  information.

- bpo-16646: ftplib.FTP.makeport() might lose socket error details. (patch
  by Serhiy Storchaka)

- bpo-16626: Fix infinite recursion in glob.glob() on Windows when the
  pattern contains a wildcard in the drive or UNC path.  Patch by Serhiy
  Storchaka.

- bpo-16298: In HTTPResponse.read(), close the socket when there is no
  Content-Length and the incoming stream is finished.  Patch by Eran
  Rundstein.

- bpo-16248: Disable code execution from the user's home directory by
  tkinter when the -E flag is passed to Python.  Patch by Zachary Ware.

- bpo-16628: Fix a memory leak in ctypes.resize().

- bpo-13614: Fix setup.py register failure with invalid rst in description.
  Patch by Julien Courteau and Pierre Paul Lefebvre.

- bpo-10182: The re module doesn't truncate indices to 32 bits anymore.
  Patch by Serhiy Storchaka.

- bpo-16573: In 2to3, treat enumerate() like a consuming call, so
  superfluous list() calls aren't added to filter(), map(), and zip() which
  are directly passed enumerate().

- bpo-1160: Fix compiling large regular expressions on UCS2 builds. Patch by
  Serhiy Storchaka.

- bpo-14313: zipfile now raises NotImplementedError when the compression
  type is unknown.

- bpo-16408: Fix file descriptors not being closed in error conditions in
  the zipfile module.  Patch by Serhiy Storchaka.

- bpo-16327: The subprocess module no longer leaks file descriptors used for
  stdin/stdout/stderr pipes to the child when fork() fails.

- bpo-14396: Handle the odd rare case of waitpid returning 0 when not
  expected in subprocess.Popen.wait().

- bpo-16411: Fix a bug where zlib.decompressobj().flush() might try to
  access previously-freed memory. Patch by Serhiy Storchaka.

- bpo-16350: zlib.decompressobj().decompress() now accumulates data from
  successive calls after EOF in unused_data, instead of only saving the
  argument to the last call. decompressobj().flush() now correctly sets
  unused_data and unconsumed_tail. A bug in the handling of MemoryError when
  setting the unconsumed_tail attribute has also been fixed. Patch by Serhiy
  Storchaka.

- bpo-12759: sre_parse now raises a proper error when the name of the group
  is missing. Initial patch by Serhiy Storchaka.

- bpo-16152: fix tokenize to ignore whitespace at the end of the code when
  no newline is found.  Patch by Ned Batchelder.

- bpo-16230: Fix a crash in select.select() when one of the lists changes
  size while iterated on.  Patch by Serhiy Storchaka.

- bpo-16228: Fix a crash in the json module where a list changes size while
  it is being encoded.  Patch by Serhiy Storchaka.

- bpo-14897: Enhance error messages of struct.pack and struct.pack_into.
  Patch by Matti Mäki.

- bpo-12890: cgitb no longer prints spurious <p> tags in text mode when the
  logdir option is specified.

- bpo-14398: Fix size truncation and overflow bugs in the bz2 module.

- bpo-5148: Ignore 'U' in mode given to gzip.open() and gzip.GzipFile().

- bpo-16220: wsgiref now always calls close() on an iterable response. Patch
  by Brent Tubbs.

- bpo-16461: Wave library should be able to deal with 4GB wav files, and
  sample rate of 44100 Hz.

- bpo-16176: Properly identify Windows 8 via platform.platform()

- bpo-15756: subprocess.poll() now properly handles errno.ECHILD to return a
  returncode of 0 when the child has already exited or cannot be waited on.

- bpo-12376: Pass on parameters in TextTestResult.__init__ super call

- bpo-15222: Insert blank line after each message in mbox mailboxes

- bpo-16013: Fix CSV Reader parsing issue with ending quote characters.
  Patch by Serhiy Storchaka.

- bpo-15421: fix an OverflowError in Calendar.itermonthdates() after
  datetime.MAXYEAR. Patch by Cédric Krier.

- bpo-15970: xml.etree.ElementTree now serializes correctly the empty HTML
  elements 'meta' and 'param'.

- bpo-15676: Now "mmap" check for empty files before doing the offset check.
  Patch by Steven Willis.

- bpo-15340: Fix importing the random module when /dev/urandom cannot be
  opened.  This was a regression caused by the hash randomization patch.

- bpo-15841: The readable(), writable() and seekable() methods of io.BytesIO
  and io.StringIO objects now raise ValueError when the object has been
  closed. Patch by Alessandro Moura.

- bpo-16112: platform.architecture does not correctly escape argument to
  /usr/bin/file. Patch by David Benjamin.

- bpo-12776: call argparse type function (specified by add_argument) only
  once. Before, the type function was called twice in the case where the
  default was specified and the argument was given as well.  This was
  especially problematic for the FileType type, as a default file would
  always be opened, even if a file argument was specified on the command
  line. (See also: bpo-11839)

- bpo-15906: Fix a regression in argparse caused by the preceding change,
  when action='append', type='str' and default=[].

- bpo-13370: Ensure that ctypes works on Mac OS X when Python is compiled
  using the clang compiler

- bpo-15544: Fix Decimal.__float__ to work with payload-carrying NaNs.

- bpo-15199: Fix JavaScript's default MIME type to application/javascript.
  Patch by Bohuslav Kabrda.

- bpo-15477: In cmath and math modules, add workaround for platforms whose
  system-supplied log1p function doesn't respect signs of zeros.

- bpo-11062: Fix adding a message from file to Babyl mailbox.

- bpo-15646: Prevent equivalent of a fork bomb when using multiprocessing on
  Windows without the "if __name__ == '__main__'" idiom.

- bpo-15567: Fix NameError when running threading._test

- bpo-15424: Add a __sizeof__ implementation for array objects. Patch by
  Ludwig Hähne.

- bpo-15538: Fix compilation of the getnameinfo() / getaddrinfo() emulation
  code.  Patch by Philipp Hagemeister.

- bpo-12288: Consider '0' and '0.0' as valid initialvalue for tkinter
  SimpleDialog.

- bpo-15489: Add a __sizeof__ implementation for BytesIO objects. Patch by
  Serhiy Storchaka.

- bpo-15469: Add a __sizeof__ implementation for deque objects. Patch by
  Serhiy Storchaka.

- bpo-15487: Add a __sizeof__ implementation for buffered I/O objects. Patch
  by Serhiy Storchaka.

- bpo-15512: Add a __sizeof__ implementation for parser. Patch by Serhiy
  Storchaka.

- bpo-15402: An issue in the struct module that caused sys.getsizeof to
  return incorrect results for struct.Struct instances has been fixed.
  Initial patch by Serhiy Storchaka.

- bpo-15232: when mangle_from is True, email.Generator now correctly mangles
  lines that start with 'From ' that occur in a MIME preamble or epilog.

- bpo-13922: argparse no longer incorrectly strips '--'s that appear after
  the first one.

- bpo-12353: argparse now correctly handles null argument values.

- bpo-6493: An issue in ctypes on Windows that caused structure bitfields of
  type ctypes.c_uint32 and width 32 to incorrectly be set has been fixed.

- bpo-14635: telnetlib will use poll() rather than select() when possible to
  avoid failing due to the select() file descriptor limit.

- bpo-15247: FileIO now raises an error when given a file descriptor
  pointing to a directory.

- bpo-14591: Fix bug in Random.jumpahead that could produce an invalid
  Mersenne Twister state on 64-bit machines.

- bpo-5346: Preserve permissions of mbox, MMDF and Babyl mailbox files on
  flush().

- bpo-15219: Fix a reference leak when hashlib.new() is called with invalid
  parameters.

- bpo-9559: If messages were only added, a new file is no longer created and
  renamed over the old file when flush() is called on an mbox, MMDF or Babyl
  mailbox.

- bpo-14653: email.utils.mktime_tz() no longer relies on system mktime()
  when timezone offest is supplied.

- bpo-6056: Make multiprocessing use setblocking(True) on the sockets it
  uses.  Original patch by J Derek Wilson.

- bpo-15101: Make pool finalizer avoid joining current thread.

- bpo-15054: A bug in tokenize.tokenize that caused string literals with 'b'
  and 'br' prefixes to be incorrectly tokenized has been fixed. Patch by
  Serhiy Storchaka.

- bpo-15036: Mailbox no longer throws an error if a flush is done between
  operations when removing or changing multiple items in mbox, MMDF, or
  Babyl mailboxes.

- bpo-10133: Make multiprocessing deallocate buffer if socket read fails.
  Patch by Hallvard B Furuseth.

- bpo-13854: Make multiprocessing properly handle non-integer non-string
  argument to SystemExit.

- bpo-12157: Make pool.map() empty iterables correctly.  Initial patch by
  mouad.

- bpo-14036: Add an additional check to validate that port in urlparse does
  not go in illegal range and returns None.

- bpo-14888: Fix misbehaviour of the _md5 module when called on data larger
  than 2**32 bytes.

- bpo-15908: Fix misbehaviour of the sha1 module when called on data larger
  than 2**32 bytes.

- bpo-15910: Fix misbehaviour of _md5 and sha1 modules when "updating" on
  data larger than 2**32 bytes.

- bpo-14875: Use float('inf') instead of float('1e66666') in the json
  module.

- bpo-14572: Prevent build failures with pre-3.5.0 versions of sqlite3, such
  as was shipped with Centos 5 and Mac OS X 10.4.

- bpo-14426: Correct the Date format in Expires attribute of Set-Cookie
  Header in Cookie.py.

- bpo-14721: Send proper header, Content-length: 0 when the body is an empty
  string ''. Initial Patch contributed by Arve Knudsen.

- bpo-14072: Fix parsing of 'tel' URIs in urlparse by making the check for
  ports stricter.

- bpo-9374: Generic parsing of query and fragment portions of url for any
  scheme. Supported both by RFC3986 and RFC2396.

- bpo-14798: Fix the functions in pyclbr to raise an ImportError when the
  first part of a dotted name is not a package. Patch by Xavier de Gaye.

- bpo-14832: fixed the order of the argument references in the error message
  produced by unittest's assertItemsEqual.

- bpo-14829: Fix bisect issues under 64-bit Windows.

- bpo-14777: tkinter may return undecoded UTF-8 bytes as a string when
  accessing the Tk clipboard.  Modify clipboard_get() to first request type
  UTF8_STRING when no specific type is requested in an X11 windowing
  environment, falling back to the current default type STRING if that
  fails. Original patch by Thomas Kluyver.

- bpo-12541: Be lenient with quotes around Realm field with HTTP Basic
  Authentation in urllib2.

- bpo-14662: Prevent shutil failures on OS X when destination does not
  support chflag operations.  Patch by Hynek Schlawack.

- bpo-14157: Fix time.strptime failing without a year on February 29th.
  Patch by Hynek Schlawack.

- bpo-14768: os.path.expanduser('~/a') doesn't work correctly when HOME is
  '/'.

- bpo-13183: Fix pdb skipping frames after hitting a breakpoint and running
  step.  Patch by Xavier de Gaye.

- bpo-14664: It is now possible to use @unittest.skip{If,Unless} on a test
  class that doesn't inherit from TestCase (i.e. a mixin).

- bpo-14160: TarFile.extractfile() failed to resolve symbolic links when the
  links were not located in an archive subdirectory.

- bpo-14638: pydoc now treats non-string __name__ values as if they were
  missing, instead of raising an error.

- bpo-13684: Fix httplib tunnel issue of infinite loops for certain sites
  which send EOF without trailing \r\n.

- bpo-14308: Fix an exception when a "dummy" thread is in the threading
  module's active list after a fork().

- bpo-14538: HTMLParser can now parse correctly start tags that contain a
  bare '/'.

- bpo-14452: SysLogHandler no longer inserts a UTF-8 BOM into the message.

- bpo-13496: Fix potential overflow in bisect.bisect algorithm when applied
  to a collection of size > sys.maxsize / 2.

- bpo-14399: zipfile now recognizes that the archive has been modified even
  if only the comment is changed.  As a consequence of this fix, ZipFile is
  now a new style class.

- bpo-7978: SocketServer now restarts the select() call when EINTR is
  returned.  This avoids crashing the server loop when a signal is received.
  Patch by Jerzy Kozera.

- bpo-10340: asyncore - properly handle EINVAL in dispatcher constructor on
  OSX; avoid to call handle_connect in case of a disconnected socket which
  was not meant to connect.

- bpo-12757: Fix the skipping of doctests when python is run with -OO so
  that it works in unittest's verbose mode as well as non-verbose mode.

- bpo-13694: asynchronous connect in asyncore.dispatcher does not set addr
  attribute.

- bpo-10484: Fix the CGIHTTPServer's PATH_INFO handling problem.

- bpo-11199: Fix the with urllib which hangs on particular ftp urls.

- bpo-14252: Fix subprocess.Popen.terminate() to not raise an error under
  Windows when the child process has already exited.

- bpo-14195: An issue that caused weakref.WeakSet instances to incorrectly
  return True for a WeakSet instance 'a' in both 'a < a' and 'a > a' has
  been fixed.

- bpo-14159: Fix the len() of weak sets to return a better approximation
  when some objects are dead or dying.  Moreover, the implementation is now
  O(1) rather than O(n).

- bpo-2945: Make the distutils upload command aware of bdist_rpm products.

- bpo-6884: Fix long-standing bugs with MANIFEST.in parsing in distutils on
  Windows.

- bpo-16441: Avoid excessive memory usage working with large gzip files
  using the gzip module.

- bpo-15782: Prevent compile errors of OS X Carbon modules _Fm, _Qd, and
  _Qdoffs when compiling with an SDK of 10.7 or later.  The OS X APIs they
  wrap have long been deprecated and have now been removed with 10.7. These
  modules were already empty for 64-bit builds and have been removed in
  Python 3.

- bpo-17477: Update the bsddb module to pybsddb 5.3.0, supporting db-5.x,
  and dropping support for db-4.1 and db-4.2.

- bpo-17192: Update the ctypes module's libffi to v3.0.13.  This
  specifically addresses a stack misalignment issue on x86 and issues on
  some more recent platforms.

- bpo-12268: The io module file object write methods no longer abort early
  when a write system calls is interrupted (EINTR).

- Fix the leak of a dict in the time module when used in an embedded
  interpreter that is repeatedly initialized and shutdown and reinitialized.

- bpo-12268: File readline, readlines and read or readall methods no longer
  lose data when an underlying read system call is interrupted within an io
  module object.  IOError is no longer raised due to a read system call
  returning EINTR from within these methods.

- bpo-16012: Fix a regression in pyexpat. The parser's UseForeignDTD()
  method doesn't require an argument again.

- bpo-13590: OS X Xcode 4 - improve support for universal extension modules
  In particular, fix extension module build failures when trying to use
  32-bit-only installer Pythons on systems with Xcode 4 (currently OS X
  10.8, 10.7, and optionally 10.6). * Backport 3.3.0 fixes to 2.7 branch
  (for release in 2.7.4) * Since Xcode 4 removes ppc support, extension
  module builds now check for ppc compiler support and by default remove ppc
  and ppc64 archs when they are not available. * Extension module builds now
  revert to using system installed   headers and libs (/usr and
  /System/Library) if the SDK used   to build the interpreter is not
  installed or has moved. * Try to avoid building extension modules with
  deprecated and problematic Apple llvm-gcc compiler.  If original compiler
  is not available, use clang instead by default.

IDLE
----

- IDLE was displaying spurious SystemExit tracebacks when running scripts
  that terminated by raising SystemExit (i.e. unittest and turtledemo).

- bpo-9290: In IDLE the sys.std* streams now implement io.TextIOBase
  interface and support all mandatory methods and properties.

- bpo-16829: IDLE printing no longer fails if there are spaces or other
  special characters in the file path.

- bpo-16819: IDLE method completion now correctly works for unicode
  literals.

- bpo-16504: IDLE now catches SyntaxErrors raised by tokenizer. Patch by
  Roger Serwy.

- bpo-1207589: Add Cut/Copy/Paste items to IDLE right click Context Menu.
  Patch by Todd Rovito.

- bpo-13052: Fix IDLE crashing when replace string in Search/Replace dialog
  ended with '\'. Patch by Roger Serwy.

- bpo-9803: Don't close IDLE on saving if breakpoint is open. Patch by Roger
  Serwy.

- bpo-14958: Change IDLE systax highlighting to recognize all string and
  byte literals currently supported in Python 2.7.

- bpo-14962: Update text coloring in IDLE shell window after changing
  options.  Patch by Roger Serwy.

- bpo-10997: Prevent a duplicate entry in IDLE's "Recent Files" menu.

- bpo-12510: Attempting to get invalid tooltip no longer closes IDLE.
  Original patch by Roger Serwy.

- bpo-10365: File open dialog now works instead of crashing even when parent
  window is closed. Patch by Roger Serwy.

- bpo-14876: Use user-selected font for highlight configuration. Patch by
  Roger Serwy.

- bpo-14409: IDLE now properly executes commands in the Shell window when it
  cannot read the normal config files on startup and has to use the built-in
  default key bindings. There was previously a bug in one of the defaults.

- bpo-3573: IDLE hangs when passing invalid command line args
  (directory(ies) instead of file(s)) (Patch by Guilherme Polo)

- bpo-5219: Prevent event handler cascade in IDLE.

- bpo-15318: Prevent writing to sys.stdin.

- bpo-13532: Check that arguments to sys.stdout.write are strings. (See
  also: bpo-15319)

- bpo-10365: File open dialog now works instead of crashing even when parent
  window is closed while dialog is open.

- bpo-14018: Update checks for unstable system Tcl/Tk versions on OS X to
  include versions shipped with OS X 10.7 and 10.8 in addition to 10.6.

- bpo-15853: Prevent IDLE crash on OS X when opening Preferences menu with
  certain versions of Tk 8.5.  Initial patch by Kevin Walzer.

Tests
-----

- bpo-16702: test_urllib2_localnet tests now correctly ignores proxies for
  localhost tests.

- bpo-13447: Add a test file to host regression tests for bugs in the
  scripts found in the Tools directory.

- bpo-11420: make test suite pass with -B/DONTWRITEBYTECODE set. Initial
  patch by Thomas Wouters.

- bpo-17299: Add test coverage for cPickle with file objects and general IO
  objects. Original patch by Aman Shah.

- bpo-11963: remove human verification from test_parser and test_subprocess.

- bpo-17249: convert a test in test_capi to use unittest and reap threads.

- We now run both test_email.py and test_email_renamed.py when running the
  test_email regression test.  test_email_renamed contains some tests that
  test_email does not.

- bpo-17041: Fix testing when Python is configured with the
  --without-doc-strings option.

- bpo-15539: Added regression tests for Tools/scripts/pindent.py.

- bpo-15324: Fix regrtest parsing of --fromfile and --randomize options.

- bpo-16618: Add more regression tests for glob. Patch by Serhiy Storchaka.

- bpo-16664: Add regression tests for glob's behaviour concerning entries
  starting with a ".".  Patch by Sebastian Kreft.

- bpo-15747: ZFS always returns EOPNOTSUPP when attempting to set the
  UF_IMMUTABLE flag (via either chflags or lchflags); refactor affected
  tests in test_posix.py to account for this.

- bpo-16549: Add tests for json.tools.  Initial patch by Berker Peksag and
  Serhiy Storchaka.

- bpo-16559: Add more tests for the json module, including some from the
  official test suite at json.org.  Patch by Serhiy Storchaka.

- bpo-16274: Fix test_asyncore on Solaris.  Patch by Giampaolo Rodola'.

- bpo-15040: Close files in mailbox tests for PyPy compatibility. Original
  patch by Matti Picus.

- bpo-15802: Fix test logic in TestMaildir.test_create_tmp. Patch by Serhiy
  Storchaka.

- bpo-15765: Extend a previous fix to Solaris and OpenBSD for quirky
  getcwd() behaviour (issue #9185) to NetBSD as well.

- bpo-15615: Add some tests for the json module's handling of invalid input
  data.  Patch by Kushal Das.

- bpo-15496: Add directory removal helpers for tests on Windows. Patch by
  Jeremy Kloth.

- bpo-15043: test_gdb is now skipped entirely if gdb security settings block
  loading of the gdb hooks

- bpo-14589: Update certificate chain for sha256.tbs-internet.com, fixing a
  test failure in test_ssl.

- bpo-16698: Skip posix test_getgroups when built with OS X deployment
  target prior to 10.6.

- bpo-17111: Prevent test_surrogates (test_fileio) failure on OS X 10.4.

Build
-----

- bpo-17425: Build against openssl 0.9.8y on Windows.

- bpo-16004: Add `make touch`.

- bpo-5033: Fix building of the sqlite3 extension module when the SQLite
  library version has "beta" in it. Patch by Andreas Pelme.

- bpo-17228: Fix building without pymalloc.

- bpo-17086: Backport the patches from the 3.3 branch to cross-build the
  package.

- bpo-3754: fix typo in pthread AC_CACHE_VAL.

- bpo-17029: Let h2py search the multiarch system include directory.

- bpo-16953: Fix socket module compilation on platforms with
  HAVE_BROKEN_POLL. Patch by Jeffrey Armstrong.

- bpo-16836: Enable IPv6 support even if IPv6 is disabled on the build host.

- bpo-15923: fix a mistake in asdl_c.py that resulted in a TypeError after
  2801bf875a24 (see #15801).

- bpo-11715: Fix multiarch detection without having Debian development tools
  (dpkg-dev) installed.

- bpo-15819: Make sure we can build Python out-of-tree from a readonly
  source directory. (Somewhat related to Issue #9860.)

- bpo-15822: Ensure 2to3 grammar pickles are properly installed.

- bpo-15560: Fix building _sqlite3 extension on OS X with an SDK.

- bpo-8847: Disable COMDAT folding in Windows PGO builds.

- bpo-14018: Fix OS X Tcl/Tk framework checking when using OS X SDKs.

- bpo-16256: OS X installer now sets correct permissions for doc directory.

- bpo-8767: Restore building with --disable-unicode. Patch by Stefano
  Taschini.

- Build against bzip2 1.0.6 and openssl 0.9.8x on Windows.

- bpo-14557: Fix extensions build on HP-UX. Patch by Adi Roiban.

- bpo-14437: Fix building the _io module under Cygwin.

- bpo-15587: Enable Tk high-resolution text rendering on Macs with Retina
  displays. Applies to Tkinter apps, such as IDLE, on OS X framework builds
  linked with Cocoa Tk 8.5.

- bpo-17161: make install now also installs a python2 and python man page.

- bpo-16848: python-config now returns proper --ldflags values for OS X
  framework builds.

Tools/Demos
-----------

- bpo-17156: pygettext.py now correctly escapes non-ascii characters.

- bpo-15539: Fix a number of bugs in Tools/scripts/pindent.py.  Now
  pindent.py works with a "with" statement.  pindent.py no longer produces
  improper indentation. pindent.py now works with continued lines broken
  after "class" or "def" keywords and with continuations at the start of
  line.

- bpo-16476: Fix json.tool to avoid including trailing whitespace.

- bpo-13301: use ast.literal_eval() instead of eval() in
  Tools/i18n/msgfmt.py. Patch by Serhiy Storchaka.

Documentation
-------------

- bpo-15041: Update "see also" list in tkinter documentation.

- bpo-17412: update 2.7 Doc/make.bat to also use sphinx-1.0.7.

- bpo-17047: remove doubled words in docs and docstrings reported by Serhiy
  Storchaka and Matthew Barnett.

- bpo-16406: combine the pages for uploading and registering to PyPI.

- bpo-16403: Document how distutils uses the maintainer field in PKG-INFO.
  Patch by Jyrki Pulliainen.

- bpo-16695: Document how glob handles filenames starting with a dot.
  Initial patch by Jyrki Pulliainen.

- bpo-8890: Stop advertising an insecure practice by replacing uses of the
  /tmp directory with better alternatives in the documentation. Patch by
  Geoff Wilson.

- bpo-17203: add long option names to unittest discovery docs.

- bpo-13094: add "Why do lambdas defined in a loop with different values all
  return the same result?" programming FAQ.

- bpo-14901: Update portions of the Windows FAQ. Patch by Ashish Nitin
  Patil.

- bpo-15990: Improve argument/parameter documentation.

- bpo-16400: Update the description of which versions of a given package
  PyPI displays.

- bpo-15677: Document that zlib and gzip accept a compression level of 0 to
  mean 'no compression'. Patch by Brian Brazil.

- bpo-8040: added a version switcher to the documentation.  Patch by Yury
  Selivanov.

- bpo-16115: Improve subprocess.Popen() documentation around args, shell,
  and executable arguments.

- bpo-15979: Improve timeit documentation.

- bpo-16036: Improve documentation of built-in int()'s signature and
  arguments.

- bpo-15935: Clarification of argparse docs, re: add_argument() type and
  default arguments.  Patch contributed by Chris Jerdonek.

- bpo-13769: Document the effect of ensure_ascii to the return type of JSON
  decoding functions.

- bpo-14880: Fix kwargs notation in csv.reader, .writer & .register_dialect.
  Patch by Chris Rebert.

- bpo-14674: Add a discussion of the json module's standard compliance.
  Patch by Chris Rebert.

- bpo-15630: Add an example for "continue" stmt in the tutorial. Patch by
  Daniel Ellis.

- bpo-13557: Clarify effect of giving two different namespaces to exec or
  execfile().

- bpo-14034: added the argparse tutorial.

- bpo-15250: Document that filecmp.dircmp compares files shallowly. Patch
  contributed by Chris Jerdonek.

- bpo-15116: Remove references to appscript as it is no longer being
  supported.


What's New in Python 2.7.3 release candidate 2?
===============================================

*Release date: 2012-03-17*

Library
-------

- bpo-14234: CVE-2012-0876: Randomize hashes of xml attributes in the hash
  table internal to the pyexpat module's copy of the expat library to avoid
  a denial of service due to hash collisions.  Patch by David Malcolm with
  some modifications by the expat project.


What's New in Python 2.7.3 release candidate 1?
===============================================

*Release date: 2012-02-23*

Core and Builtins
-----------------

- bpo-13020: Fix a reference leak when allocating a structsequence object
  fails.  Patch by Suman Saha.

- bpo-13703: oCERT-2011-003: add -R command-line option and PYTHONHASHSEED
  environment variable, to provide an opt-in way to protect against denial
  of service attacks due to hash collisions within the dict and set types.
  Patch by David Malcolm, based on work by Victor Stinner.

- bpo-11235: Fix OverflowError when trying to import a source file whose
  modification time doesn't fit in a 32-bit timestamp.

- bpo-11638: Unicode strings in 'name' and 'version' no longer cause
  UnicodeDecodeErrors.

- Fix the fix for issue #12149: it was incorrect, although it had the side
  effect of appearing to resolve the issue.  Thanks to Mark Shannon for
  noticing.

- bpo-13546: Fixed an overflow issue that could crash the intepreter when
  calling sys.setrecursionlimit((1<<31)-1).

- bpo-13333: The UTF-7 decoder now accepts lone surrogates (the encoder
  already accepts them).

- bpo-10519: Avoid unnecessary recursive function calls in setobject.c.

- bpo-13268: Fix the assert statement when a tuple is passed as the message.

- bpo-13018: Fix reference leaks in error paths in dictobject.c. Patch by
  Suman Saha.

- bpo-12604: VTRACE macro expanded to no-op in _sre.c to avoid compiler
  warnings. Patch by Josh Triplett and Petri Lehtinen.

- bpo-7833: Extension modules built using distutils on Windows will no
  longer include a "manifest" to prevent them failing at import time in some
  embedded situations.

- bpo-13186: Fix __delitem__ on old-style instances when invoked through
  PySequence_DelItem.

- bpo-13156: Revert the patch for issue #10517 (reset TLS upon fork()),
  which was only relevant for the native pthread TLS implementation.

- bpo-7732: Fix a crash on importing a module if a directory has the same
  name than a Python module (e.g. "__init__.py"): don't close the file
  twice.

- bpo-12973: Fix overflow checks that invoked undefined behaviour in
  int.__pow__.  These overflow checks were causing int.__pow__ to produce
  incorrect results with recent versions of Clang, as a result of the
  compiler optimizing the check away.  Also fix similar overflow checks in
  list_repeat (listobject.c) and islice_next (itertoolsmodule.c).  These
  bugs caused test failures with recent versions of Clang.

- bpo-12266: Fix str.capitalize() to correctly uppercase/lowercase
  titlecased and cased non-letter characters.

- bpo-12610: Verify that user generated AST has correct string and
  identifier types before compiling. (See also: bpo-12609)

- bpo-11627: Fix segfault when __new__ on an exception returns a
  non-exception class.

- bpo-12149: Update the method cache after a type's dictionnary gets cleared
  by the garbage collector.  This fixes a segfault when an instance and its
  type get caught in a reference cycle, and the instance's deallocator calls
  one of the methods on the type (e.g. when subclassing IOBase).  Diagnosis
  and patch by Davide Rizzo.

- bpo-12501: Remove Py3k warning for callable. callable() is supported again
  in Python 3.2.

- bpo-9611: FileIO.read(), FileIO.readinto(), FileIO.write() and os.write()
  clamp the length to INT_MAX on Windows. (See also: bpo-9015)

- bpo-1195: my_fgets() now always clears errors before calling fgets(). Fix
  the following case: sys.stdin.read() stopped with CTRL+d (end of file),
  raw_input() interrupted by CTRL+c.

- bpo-10860: httplib now correctly handles an empty port after port
  delimiter in URLs.

- dict_proxy objects now display their contents rather than just the class
  name.

Library
-------

- bpo-8033: sqlite3: Fix 64-bit integer handling in user functions on 32-bit
  architectures. Initial patch by Philippe Devalkeneer.

- HTMLParser is now able to handle slashes in the start tag.

- bpo-14001: CVE-2012-0845: xmlrpc: Fix an endless loop in
  SimpleXMLRPCServer upon malformed POST request.

- bpo-2489: pty.spawn could consume 100% cpu when it encountered an EOF.

- bpo-13014: Fix a possible reference leak in SSLSocket.getpeercert().

- bpo-13987: HTMLParser is now able to handle EOFs in the middle of a
  construct and malformed start tags.

- bpo-13015: Fix a possible reference leak in defaultdict.__repr__. Patch by
  Suman Saha.

- bpo-13979: A bug in ctypes.util.find_library that caused the wrong library
  name to be returned has been fixed.

- bpo-1326113: distutils' build_ext command --libraries option now correctly
  parses multiple values separated by whitespace or commas.

- bpo-13993: HTMLParser is now able to handle broken end tags.

- bpo-13960: HTMLParser is now able to handle broken comments.

- bpo-9750: Fix sqlite3.Connection.iterdump on tables and fields with a name
  that is a keyword or contains quotes. Patch by Marko Kohtala.

- bpo-13994: Earlier partial revert of Distutils enhancements in 2.7 has
  left two versions of customize_compiler, the original in
  distutils.sysconfig and another copy in distutils.ccompiler, with some
  parts of distutils calling one and others using the other. Complete the
  revert back to only having one in distutils.sysconfig as is the case in
  3.x.

- bpo-13590: On OS X 10.7 and 10.6 with Xcode 4.2, building Distutils-based
  packages with C extension modules may fail because Apple has removed
  gcc-4.2, the version used to build python.org 64-bit/32-bit Pythons.  If
  the user does not explicitly override the default C compiler by setting
  the CC environment variable, Distutils will now attempt to compile
  extension modules with clang if gcc-4.2 is required but not found. Also as
  a convenience, if the user does explicitly set CC, substitute its value as
  the default compiler in the Distutils LDSHARED configuration variable for
  OS X. (Note, the python.org 32-bit-only Pythons use gcc-4.0 and the 10.4u
  SDK, neither of which are available in Xcode 4.  This change does not
  attempt to override settings to support their use with Xcode 4.)

- bpo-9021: Add an introduction to the copy module documentation.

- bpo-6005: Examples in the socket library documentation use sendall, where
  relevant, instead send method.

- bpo-10811: Fix recursive usage of cursors. Instead of crashing, raise a
  ProgrammingError now.

- bpo-13676: Handle strings with embedded zeros correctly in sqlite3.

- bpo-13806: The size check in audioop decompression functions was too
  strict and could reject valid compressed data.  Patch by Oleg Plakhotnyuk.

- bpo-13885: CVE-2011-3389: the _ssl module would always disable the CBC IV
  attack countermeasure.

- bpo-6631: Disallow relative file paths in urllib urlopen methods.

- bpo-13781: Prevent gzip.GzipFile from using the dummy filename provided by
  file objects opened with os.fdopen().

- bpo-13589: Fix some serialization primitives in the aifc module. Patch by
  Oleg Plakhotnyuk.

- bpo-13803: Under Solaris, distutils doesn't include bitness in the
  directory name.

- bpo-13642: Unquote before b64encoding user:password during Basic
  Authentication. Patch contributed by Joonas Kuorilehto and Michele Orrù.

- bpo-13636: Weak ciphers are now disabled by default in the ssl module
  (except when SSLv2 is explicitly asked for).

- bpo-12798: Updated the mimetypes documentation.

- bpo-13639: Accept unicode filenames in tarfile.open(mode="w|gz").

- bpo-1785: Fix inspect and pydoc with misbehaving descriptors.

- bpo-7502: Fix equality comparison for DocTestCase instances.  Patch by
  Cédric Krier.

- bpo-11870: threading: Properly reinitialize threads internal locks and
  condition variables to avoid deadlocks in child processes.

- bpo-8035: urllib: Fix a bug where the client could remain stuck after a
  redirection or an error.

- tarfile.py: Correctly detect bzip2 compressed streams with blocksizes
  other than 900k.

- bpo-13573: The csv.writer now uses the repr() for floats rather than
  str(). This allows floats to round-trip without loss of precision.

- bpo-13439: Fix many errors in turtle docstrings.

- bpo-12856: Ensure child processes do not inherit the parent's random seed
  for filename generation in the tempfile module.  Patch by Brian Harring.

- bpo-13458: Fix a memory leak in the ssl module when decoding a certificate
  with a subjectAltName.  Patch by Robert Xiao.

- bpo-13415: os.unsetenv() doesn't ignore errors anymore.

- bpo-13322: Fix BufferedWriter.write() to ensure that BlockingIOError is
  raised when the wrapped raw file is non-blocking and the write would
  block. Previous code assumed that the raw write() would raise
  BlockingIOError, but RawIOBase.write() is defined to returned None when
  the call would block. Patch by sbt.

- bpo-13358: HTMLParser now calls handle_data only once for each CDATA.

- bpo-4147: minidom's toprettyxml no longer adds whitespace around a text
  node when it is the only child of an element.  Initial patch by Dan
  Kenigsberg.

- bpo-1745761: HTMLParser now correctly handles non-valid attributes,
  including adjacent and unquoted attributes. (See also: bpo-755670,
  bpo-13357, bpo-12629, bpo-1200313)

- bpo-13373: multiprocessing.Queue.get() could sometimes block indefinitely
  when called with a timeout.  Patch by Arnaud Ysmal.

- bpo-3067: Enhance the documentation and docstring of locale.setlocale().

- bpo-13254: Fix Maildir initialization so that maildir contents are read
  correctly.

- bpo-13140: Fix the daemon_threads attribute of ThreadingMixIn.

- bpo-2892: preserve iterparse events in case of SyntaxError.

- bpo-670664: Fix HTMLParser to correctly handle the content of
  ``<script>...</script>`` and ``<style>...</style>``.

- bpo-10817: Fix urlretrieve function to raise ContentTooShortError even
  when reporthook is None. Patch by Jyrki Pulliainen.

- bpo-7334: close source files on ElementTree.parse and iterparse.

- bpo-13232: logging: Improved logging of exceptions in the presence of
  multiple encodings.

- bpo-10332: multiprocessing: fix a race condition when a Pool is closed
  before all tasks have completed.

- bpo-1548891: The cStringIO.StringIO() constructor now encodes unicode
  arguments with the system default encoding just like the write() method
  does, instead of converting it to a raw buffer.  This also fixes handling
  of unicode input in the shlex module (#6988, #1170).

- bpo-9168: now smtpd is able to bind privileged port.

- bpo-12529: fix cgi.parse_header issue on strings with double-quotes and
  semicolons together. Patch by Ben Darnell and Petri Lehtinen.

- bpo-6090: zipfile raises a ValueError when a document with a timestamp
  earlier than 1980 is provided. Patch contributed by Petri Lehtinen.

- bpo-13194: zlib.compressobj().copy() and zlib.decompressobj().copy() are
  now available on Windows.

- bpo-13114: Fix the distutils commands check and register when the long
  description is a Unicode string with non-ASCII characters.

- bpo-7367: Fix pkgutil.walk_paths to skip directories whose contents cannot
  be read.

- bpo-7425: Prevent pydoc -k failures due to module import errors. (Backport
  to 2.7 of existing 3.x fix)

- bpo-13099: Fix sqlite3.Cursor.lastrowid under a Turkish locale. Reported
  and diagnosed by Thomas Kluyver.

- bpo-7689: Allow pickling of dynamically created classes when their
  metaclass is registered with copy_reg.  Patch by Nicolas M. Thiéry and
  Craig Citro.

- bpo-13058: ossaudiodev: fix a file descriptor leak on error. Patch by
  Thomas Jarosch.

- bpo-12931: xmlrpclib now encodes Unicode URI to ISO-8859-1, instead of
  failing with a UnicodeDecodeError.

- bpo-8933: distutils' PKG-INFO files will now correctly report
  Metadata-Version: 1.1 instead of 1.0 if a Classifier or Download-URL field
  is present.

- bpo-8286: The distutils command sdist will print a warning message instead
  of crashing when an invalid path is given in the manifest template.

- bpo-12841: tarfile unnecessarily checked the existence of numerical user
  and group ids on extraction. If one of them did not exist the respective
  id of the current user (i.e. root) was used for the file and ownership
  information was lost.

- bpo-10946: The distutils commands bdist_dumb, bdist_wininst and bdist_msi
  now respect a --skip-build option given to bdist.

- bpo-12287: Fix a stack corruption in ossaudiodev module when the FD is
  greater than FD_SETSIZE.

- bpo-12839: Fix crash in zlib module due to version mismatch. Fix by
  Richard M. Tew.

- bpo-12786: Set communication pipes used by subprocess.Popen CLOEXEC to
  avoid them being inherited by other subprocesses.

- bpo-4106: Fix occasional exceptions printed out by multiprocessing on
  interpreter shutdown.

- bpo-11657: Fix sending file descriptors over 255 over a multiprocessing
  Pipe.

- bpo-12213: Fix a buffering bug with interleaved reads and writes that
  could appear on io.BufferedRandom streams.

- bpo-12326: sys.platform is now always 'linux2' on Linux, even if Python is
  compiled on Linux 3.

- bpo-13007: whichdb should recognize gdbm 1.9 magic numbers.

- bpo-9173: Let shutil._make_archive work if the logger argument is None.

- bpo-12650: Fix a race condition where a subprocess.Popen could leak
  resources (FD/zombie) when killed at the wrong time.

- bpo-12752: Fix regression which prevented locale.normalize() from
  accepting unicode strings.

- bpo-12683: urlparse updated to include svn as schemes that uses relative
  paths. (svn from 1.5 onwards support relative path).

- bpo-11933: Fix incorrect mtime comparison in distutils.

- bpo-11104: Fix the behavior of distutils' sdist command with
  manually-maintained MANIFEST files. (See also: bpo-8688)

- bpo-8887: "pydoc somebuiltin.somemethod" (or
  help('somebuiltin.somemethod') in Python code) now finds the doc of the
  method.

- bpo-12603: Fix pydoc.synopsis() on files with non-negative st_mtime.

- bpo-12514: Use try/finally to assure the timeit module restores garbage
  collections when it is done.

- bpo-12607: In subprocess, fix issue where if stdin, stdout or stderr is
  given as a low fd, it gets overwritten.

- bpo-12102: Document that buffered files must be flushed before being used
  with mmap. Patch by Steffen Daode Nurpmeso.

- bpo-12560: Build libpython.so on OpenBSD. Patch by Stefan Sperling.

- bpo-1813: Fix codec lookup and setting/getting locales under Turkish
  locales.

- bpo-10883: Fix socket leaks in urllib when using FTP.

- bpo-12592: Make Python build on OpenBSD 5 (and future major releases).

- bpo-12372: POSIX semaphores are broken on AIX: don't use them.

- bpo-12571: Add a plat-linux3 directory mirroring the plat-linux2
  directory, so that "import DLFCN" and other similar imports work on Linux
  3.0.

- bpo-7484: smtplib no longer puts <> around addresses in VRFY and EXPN
  commands; they aren't required and in fact postfix doesn't support that
  form.

- bpo-11603: Fix a crash when __str__ is rebound as __repr__.  Patch by
  Andreas Stührk.

- bpo-12502: asyncore: fix polling loop with AF_UNIX sockets.

- bpo-4376: ctypes now supports nested structures in an endian different
  than the parent structure. Patch by Vlad Riscutia.

- bpo-12493: subprocess: Popen.communicate() now also handles EINTR errors
  if the process has only one pipe.

- bpo-12467: warnings: fix a race condition if a warning is emitted at
  shutdown, if globals()['__file__'] is None.

- bpo-12352: Fix a deadlock in multiprocessing.Heap when a block is freed by
  the garbage collector while the Heap lock is held.

- bpo-9516: On Mac OS X, change Distutils to no longer globally attempt to
  check or set the MACOSX_DEPLOYMENT_TARGET environment variable for the
  interpreter process.  This could cause failures in non-Distutils
  subprocesses and was unreliable since tests or user programs could modify
  the interpreter environment after Distutils set it.  Instead, have
  Distutils set the deployment target only in the environment of each build
  subprocess.  It is still possible to globally override the default by
  setting MACOSX_DEPLOYMENT_TARGET before launching the interpreter; its
  value must be greater or equal to the default value, the value with which
  the interpreter was built.

- bpo-11802: The cache in filecmp now has a maximum size of 100 so that it
  won't grow without bound.

- bpo-12404: Remove C89 incompatible code from mmap module. Patch by Akira
  Kitada.

- bpo-11700: mailbox proxy object close methods can now be called multiple
  times without error, and _ProxyFile now closes the wrapped file.

- bpo-12133: AbstractHTTPHandler.do_open() of urllib.request closes the HTTP
  connection if its getresponse() method fails with a socket error. Patch
  written by Ezio Melotti.

- bpo-9284: Allow inspect.findsource() to find the source of doctest
  functions.

- bpo-10694: zipfile now ignores garbage at the end of a zipfile.

- bpo-11583: Speed up os.path.isdir on Windows by using GetFileAttributes
  instead of os.stat.

- bpo-12080: Fix a performance issue in Decimal._power_exact that caused
  some corner-case Decimal.__pow__ calls to take an unreasonably long time.

- Named tuples now work correctly with vars().

- sys.setcheckinterval() now updates the current ticker count as well as
  updating the check interval, so if the user decreases the check interval,
  the ticker doesn't have to wind down to zero from the old starting point
  before the new interval takes effect.  And if the user increases the
  interval, it makes sure the new limit takes effect right away rather have
  an early task switch before recognizing the new interval.

- bpo-12085: Fix an attribute error in subprocess.Popen destructor if the
  constructor has failed, e.g. because of an undeclared keyword argument.
  Patch written by Oleg Oshmyan.

- bpo-9041: An issue in ctypes.c_longdouble, ctypes.c_double, and
  ctypes.c_float that caused an incorrect exception to be returned in the
  case of overflow has been fixed.

- bsddb module: Erratic behaviour of "DBEnv->rep_elect()" because a typo.
  Possible crash.

- bpo-13774: json: Fix a SystemError when a bogus encoding is passed to
  json.loads().

- bpo-9975: socket: Fix incorrect use of flowinfo and scope_id. Patch by
  Vilmos Nebehaj.

- bpo-13159: FileIO, BZ2File, and the built-in file class now use a
  linear-time buffer growth strategy instead of a quadratic one.

- bpo-13070: Fix a crash when a TextIOWrapper caught in a reference cycle
  would be finalized after the reference to its underlying BufferedRWPair's
  writer got cleared by the GC.

- bpo-12881: ctypes: Fix segfault with large structure field names.

- bpo-13013: ctypes: Fix a reference leak in PyCArrayType_from_ctype. Thanks
  to Suman Saha for finding the bug and providing a patch.

- bpo-13022: Fix: _multiprocessing.recvfd() doesn't check that file
  descriptor was actually received.

- bpo-12483: ctypes: Fix a crash when the destruction of a callback object
  triggers the garbage collector.

- bpo-12950: Fix passing file descriptors in multiprocessing, under
  OpenIndiana/Illumos.

- bpo-12764: Fix a crash in ctypes when the name of a Structure field is not
  a string.

- bpo-9651: Fix a crash when ctypes.create_string_buffer(0) was passed to
  some functions like file.write().

- bpo-10309: Define _GNU_SOURCE so that mremap() gets the proper signature.
  Without this, architectures where sizeof void* != sizeof int are broken.
  Patch given by Hallvard B Furuseth.

IDLE
----

- bpo-964437: Make IDLE help window non-modal. Patch by Guilherme Polo and
  Roger Serwy.

- bpo-13933: IDLE auto-complete did not work with some imported module, like
  hashlib. (Patch by Roger Serwy)

- bpo-13506: Add '' to path for IDLE Shell when started and restarted with
  Restart Shell. Original patches by Marco Scataglini and Roger Serwy.

- bpo-4625: If IDLE cannot write to its recent file or breakpoint files,
  display a message popup and continue rather than crash. (original patch by
  Roger Serwy)

- bpo-8793: Prevent IDLE crash when given strings with invalid hex escape
  sequences.

- bpo-13296: Fix IDLE to clear compile __future__ flags on shell restart.
  (Patch by Roger Serwy)

- bpo-14409: IDLE now properly executes commands in the Shell window when it
  cannot read the normal config files on startup and has to use the built-in
  default key bindings. There was previously a bug in one of the defaults.

- bpo-3573: IDLE hangs when passing invalid command line args
  (directory(ies) instead of file(s)).

Build
-----

- bpo-6807: Run msisupport.mak earlier.

- bpo-10580: Minor grammar change in Windows installer.

- bpo-12627: Implement PEP 394 for Python 2.7 ("python2").

- bpo-8746: Correct faulty configure checks so that os.chflags() and
  os.lchflags() are once again built on systems that support these functions
  (*BSD and OS X). Also add new stat file flags for OS X (UF_HIDDEN and
  UF_COMPRESSED).

Tools/Demos
-----------

- bpo-14053: patchcheck.py ("make patchcheck") now works with MQ patches.
  Patch by Francisco Martín Brugué.

- bpo-13930: 2to3 is now able to write its converted output files to another
  directory tree as well as copying unchanged files and altering the file
  suffix.  See its new -o, -W and --add-suffix options.  This makes it more
  useful in many automated code translation workflows.

- bpo-10639: reindent.py no longer converts newlines and will raise an error
  if attempting to convert a file with mixed newlines.

- bpo-13628: python-gdb.py is now able to retrieve more frames in the Python
  traceback if Python is optimized.

Tests
-----

- bpo-15467: Move helpers for __sizeof__ tests into test_support. Patch by
  Serhiy Storchaka.

- bpo-11689: Fix a variable scoping error in an sqlite3 test. Initial patch
  by Torsten Landschoff.

- bpo-10881: Fix test_site failures with OS X framework builds.

- bpo-13901: Prevent test_distutils failures on OS X with --enable-shared.

- bpo-13304: Skip test case if user site-packages disabled (-s or
  PYTHONNOUSERSITE). (Patch by Carl Meyer)

- bpo-13218: Fix test_ssl failures on Debian/Ubuntu.

- bpo-12821: Fix test_fcntl failures on OpenBSD 5.

- bpo-12331: The test suite for lib2to3 can now run from an installed
  Python.

- bpo-12549: Correct test_platform to not fail when OS X returns 'x86_64' as
  the processor type on some Mac systems.

- Skip network tests when getaddrinfo() returns EAI_AGAIN, meaning a
  temporary failure in name resolution.

- bpo-11812: Solve transient socket failure to connect to 'localhost' in
  test_telnetlib.py.

- Solved a potential deadlock in test_telnetlib.py. Related to issue #11812.

- Avoid failing in test_robotparser when mueblesmoraleda.com is flaky and an
  overzealous DNS service (e.g. OpenDNS) redirects to a placeholder Web
  site.

- Avoid failing in test_urllibnet.test_bad_address when some overzealous DNS
  service (e.g. OpenDNS) resolves a non-existent domain name.  The test is
  now skipped instead.

- bpo-8716: Avoid crashes caused by Aqua Tk on OSX when attempting to run
  test_tk or test_ttk_guionly under a username that is not currently logged
  in to the console windowserver (as may be the case under buildbot or ssh).

- bpo-12141: Install a copy of template C module file so that test_build_ext
  of test_distutils is no longer silently skipped when run outside of a
  build directory.

- bpo-8746: Add additional tests for os.chflags() and os.lchflags(). Patch
  by Garrett Cooper.

- bpo-10736: Fix test_ttk test_widgets failures with Cocoa Tk 8.5.9 on Mac
  OS X.  (Patch by Ronald Oussoren)

- bpo-12057: Add tests for ISO 2022 codecs (iso2022_jp, iso2022_jp_2,
  iso2022_kr).

Documentation
-------------

- bpo-13491: Fix many errors in sqlite3 documentation. Initial patch for
  #13491 by Johannes Vogel. (See also: bpo-13995)

- bpo-13402: Document absoluteness of sys.executable.

- bpo-13883: PYTHONCASEOK also works on OS X, OS/2, and RiscOS.

- bpo-2134: The tokenize documentation has been clarified to explain why all
  operator and delimiter tokens are treated as token.OP tokens.

- bpo-13513: Fix io.IOBase documentation to correctly link to the
  io.IOBase.readline method instead of the readline module.

- bpo-13237: Reorganise subprocess documentation to emphasise convenience
  functions and the most commonly needed arguments to Popen.

- bpo-13141: Demonstrate recommended style for SocketServer examples.


What's New in Python 2.7.2 final?
=================================

*Release date: 2011-06-11*

Library
-------

- bpo-12009: Fixed regression in netrc file comment handling.

- bpo-1221: Make pyexpat.__version__ equal to the Python version.


What's New in Python 2.7.2 release candidate 1?
===============================================

*Release date: 2011-05-29*

Core and Builtins
-----------------

- bpo-9670: Increase the default stack size for secondary threads on Mac OS
  X and FreeBSD to reduce the chances of a crash instead of a "maximum
  recursion depth" RuntimeError exception. (patch by Ronald Oussoren)

- Correct lookup of __dir__ on objects. This allows old-style classes to
  have __dir__. It also causes errors besides AttributeError found on lookup
  to be propagated.

- bpo-1195: Fix input() if it is interrupted by CTRL+d and then CTRL+c,
  clear the end-of-file indicator after CTRL+d.

- bpo-8651: PyArg_Parse*() functions raise an OverflowError if the file
  doesn't have PY_SSIZE_T_CLEAN define and the size doesn't fit in an int
  (length bigger than 2^31-1 bytes).

- bpo-8651: Fix "z#" format of PyArg_Parse*() function: the size was not
  written if PY_SSIZE_T_CLEAN is defined.

- bpo-9756: When calling a method descriptor or a slot wrapper descriptor,
  the check of the object type doesn't read the __class__ attribute anymore.
  Fix a crash if a class override its __class__ attribute (e.g. a proxy of
  the str type). Patch written by Andreas Stührk.

- bpo-10517: After fork(), reinitialize the TLS used by the PyGILState_*
  APIs, to avoid a crash with the pthread implementation in RHEL 5.  Patch
  by Charles-François Natali.

- bpo-6780: fix starts/endswith error message to mention that tuples are
  accepted too.

- bpo-5057: fix a bug in the peepholer that led to non-portable pyc files
  between narrow and wide builds while optimizing BINARY_SUBSCR on non-BMP
  chars (e.g. u"\U00012345"[0]).

- bpo-11650: PyOS_StdioReadline() retries fgets() if it was interrupted
  (EINTR), for example if the program is stopped with CTRL+z on Mac OS X.
  Patch written by Charles-Francois Natali.

- bpo-11144: Ensure that int(a_float) returns an int whenever possible.
  Previously, there were some corner cases where a long was returned even
  though the result was within the range of an int.

- bpo-11450: Don't truncate hg version info in Py_GetBuildInfo() when there
  are many tags (e.g. when using mq).  Patch by Nadeem Vawda.

- bpo-10451: memoryview objects could allow mutating a readable buffer.
  Initial patch by Ross Lagerwall.

- bpo-10892: Don't segfault when trying to delete __abstractmethods__ from a
  class.

- bpo-8020: Avoid a crash where the small objects allocator would read
  non-Python managed memory while it is being modified by another thread.
  Patch by Matt Bandy.

- bpo-11004: Repaired edge case in deque.count().

- bpo-8278: On Windows and with a NTFS filesystem, os.stat() and os.utime()
  can now handle dates after 2038.

- bpo-4236: Py_InitModule4 now checks the import machinery directly rather
  than the Py_IsInitialized flag, avoiding a Fatal Python error in certain
  circumstances when an import is done in __del__.

- bpo-11828: startswith and endswith don't accept None as slice index. Patch
  by Torsten Becker.

- bpo-10674: Remove unused 'dictmaker' rule from grammar.

- bpo-10596: Fix float.__mod__ to have the same behaviour as
  float.__divmod__ with respect to signed zeros.  -4.0 % 4.0 should be 0.0,
  not -0.0.

- bpo-11386: bytearray.pop() now throws IndexError when the bytearray is
  empty, instead of OverflowError.

Library
-------

- bpo-12161: Cause StringIO.getvalue() to raise a ValueError when used on a
  closed StringIO instance.

- bpo-12182: Fix pydoc.HTMLDoc.multicolumn() if Python uses the new (true)
  division (python -Qnew). Patch written by Ralf W. Grosse-Kunstleve.

- bpo-12175: RawIOBase.readall() now returns None if read() returns None.

- bpo-12175: FileIO.readall() now raises a ValueError instead of an IOError
  if the file is closed.

- bpo-1441530: In imaplib, use makefile() to wrap the SSL socket to avoid
  heap fragmentation and MemoryError with some malloc implementations.

- bpo-12100: Don't reset incremental encoders of CJK codecs at each call to
  their encode() method anymore, but continue to call the reset() method if
  the final argument is True.

- bpo-12124: zipimport doesn't keep a reference to zlib.decompress() anymore
  to be able to unload the module.

- bpo-10154: change the normalization of UTF-8 to "UTF-8" instead of "UTF8"
  in the locale module as the latter is not supported MacOSX and OpenBSD.
  (See also: bpo-10090)

- bpo-9516: avoid errors in sysconfig when MACOSX_DEPLOYMENT_TARGET is set
  in shell.

- bpo-12050: zlib.decompressobj().decompress() now clears the
  unconsumed_tail attribute when called without a max_length argument.

- bpo-12062: In the `io` module, fix a flushing bug when doing a certain
  type of I/O sequence on a file opened in read+write mode (namely: reading,
  seeking a bit forward, writing, then seeking before the previous write but
  still within buffered data, and writing again).

- bpo-8498: In socket.accept(), allow specifying 0 as a backlog value in
  order to accept exactly one connection.  Patch by Daniel Evers.

- bpo-12012: ssl.PROTOCOL_SSLv2 becomes optional.

- bpo-11927: SMTP_SSL now uses port 465 by default as documented.  Patch by
  Kasun Herath.

- bpo-11999: fixed sporadic sync failure mailbox.Maildir due to its trying
  to detect mtime changes by comparing to the system clock instead of to the
  previous value of the mtime.

- bpo-10684: shutil.move used to delete a folder on case insensitive
  filesystems when the source and destination name where the same except for
  the case.

- bpo-11982: fix json.loads('""') to return u'' rather than ''.

- bpo-11277: mmap.mmap() calls fcntl(fd, F_FULLFSYNC) on Mac OS X to get
  around a mmap bug with sparse files. Patch written by Steffen Daode
  Nurpmeso.

- bpo-10761: Fix tarfile.extractall failure when symlinked files are
  present. Initial patch by Scott Leerssen.

- bpo-11763: don't use difflib in TestCase.assertMultiLineEqual if the
  strings are too long.

- bpo-11236: getpass.getpass responds to ctrl-c or ctrl-z on terminal.

- bpo-11768: The signal handler of the signal module only calls
  Py_AddPendingCall() for the first signal to fix a deadlock on reentrant or
  parallel calls. PyErr_SetInterrupt() writes also into the wake up file.

- bpo-11875: collections.OrderedDict's __reduce__ was temporarily mutating
  the object instead of just working on a copy.

- bpo-11442: Add a charset parameter to the Content-type in SimpleHTTPServer
  to avoid XSS attacks.

- bpo-11467: Fix urlparse behavior when handling urls which contains scheme
  specific part only digits. Patch by Santoso Wijaya.

- collections.Counter().copy() now works correctly for subclasses.

- bpo-11474: Fix the bug with url2pathname() handling of '/C|/' on Windows.
  Patch by Santoso Wijaya.

- bpo-9233: Fix json.loads('{}') to return a dict (instead of a list), when
  _json is not available.

- bpo-11703: urllib2.geturl() does not return correct url when the original
  url contains #fragment.

- bpo-10019: Fixed regression in json module where an indent of 0 stopped
  adding newlines and acted instead like 'None'.

- bpo-5162: Treat services like frozen executables to allow child spawning
  from multiprocessing.forking on Windows.

- bpo-4877: Fix a segfault in xml.parsers.expat while attempting to parse a
  closed file.

- bpo-11830: Remove unnecessary introspection code in the decimal module. It
  was causing a failed import in the Turkish locale where the locale
  sensitive str.upper() method caused a name mismatch.

- bpo-8428: Fix a race condition in multiprocessing.Pool when terminating
  worker processes: new processes would be spawned while the pool is being
  shut down. Patch by Charles-François Natali.

- bpo-7311: Fix HTMLParser to accept non-ASCII attribute values.

- bpo-10963: Ensure that subprocess.communicate() never raises EPIPE.

- bpo-11662: Make urllib and urllib2 ignore redirections if the scheme is
  not HTTP, HTTPS or FTP (CVE-2011-1521).

- bpo-11256: Fix inspect.getcallargs on functions that take only keyword
  arguments.

- bpo-11696: Fix ID generation in msilib.

- bpo-9696: Fix exception incorrectly raised by xdrlib.Packer.pack_int when
  trying to pack a negative (in-range) integer.

- bpo-11675: multiprocessing.[Raw]Array objects created from an integer size
  are now zeroed on creation.  This matches the behaviour specified by the
  documentation.

- bpo-7639: Fix short file name generation in bdist_msi.

- bpo-11666: let help() display named tuple attributes and methods that
  start with a leading underscore.

- bpo-11673: Fix multiprocessing Array and RawArray constructors to accept a
  size of type 'long', rather than only accepting 'int'.

- bpo-10042: Fixed the total_ordering decorator to handle cross-type
  comparisons that could lead to infinite recursion.

- bpo-10979: unittest stdout buffering now works with class and module setup
  and teardown.

- bpo-11569: use absolute path to the sysctl command in multiprocessing to
  ensure that it will be found regardless of the shell PATH. This ensures
  that multiprocessing.cpu_count works on default installs of MacOSX.

- bpo-11500: Fixed a bug in the os x proxy bypass code for fully qualified
  IP addresses in the proxy exception list.

- bpo-11131: Fix sign of zero in plus and minus operations when the context
  rounding mode is ROUND_FLOOR.

- bpo-5622: Fix curses.wrapper to raise correct exception if curses
  initialization fails.

- bpo-11391: Writing to a mmap object created with
  ``mmap.PROT_READ|mmap.PROT_EXEC`` would segfault instead of raising a
  TypeError.  Patch by Charles-François Natali.

- bpo-11306: mailbox in certain cases adapts to an inability to open certain
  files in read-write mode.  Previously it detected this by checking for
  EACCES, now it also checks for EROFS.

- bpo-11265: asyncore now correctly handles EPIPE, EBADF and EAGAIN errors
  on accept(), send() and recv().

- bpo-11326: Add the missing connect_ex() implementation for SSL sockets,
  and make it work for non-blocking connects.

- bpo-10956: Buffered I/O classes retry reading or writing after a signal
  has arrived and the handler returned successfully.

- bpo-10680: Fix mutually exclusive arguments for argument groups in
  argparse.

- bpo-4681: Allow mmap() to work on file sizes and offsets larger than 4GB,
  even on 32-bit builds.  Initial patch by Ross Lagerwall, adapted for
  32-bit Windows.

- bpo-10360: In WeakSet, do not raise TypeErrors when testing for membership
  of non-weakrefable objects.

- bpo-10549: Fix pydoc traceback when text-documenting certain classes.

- bpo-940286: pydoc.Helper.help() ignores input/output init parameters.

- bpo-11171: Fix detection of config/Makefile when --prefix !=
  --exec-prefix, which caused Python to not start.

- bpo-11116: any error during addition of a message to a mailbox now causes
  a rollback, instead of leaving the mailbox partially modified.

- bpo-8275: Fix passing of callback arguments with ctypes under Win64. Patch
  by Stan Mihai.

- bpo-10949: Improved robustness of rotating file handlers.

- bpo-10955: Fix a potential crash when trying to mmap() a file past its
  length.  Initial patch by Ross Lagerwall.

- bpo-10898: Allow compiling the posix module when the C library defines a
  symbol named FSTAT.

- bpo-10916: mmap should not segfault when a file is mapped using 0 as
  length and a non-zero offset, and an attempt to read past the end of file
  is made (IndexError is raised instead).  Patch by Ross Lagerwall.

- bpo-10875: Update Regular Expression HOWTO; patch by 'SilentGhost'.

- bpo-10827: Changed the rules for 2-digit years.  The time.asctime function
  will now format any year when ``time.accept2dyear`` is false and will
  accept years >= 1000 otherwise.  The year range accepted by
  ``time.mktime`` and ``time.strftime`` is still system dependent, but
  ``time.mktime`` will now accept full range supported by the OS.
  Conversion of 2-digit years to 4-digit is deprecated.

- bpo-10869: Fixed bug where ast.increment_lineno modified the root node
  twice.

- bpo-7858: Raise an error properly when os.utime() fails under Windows on
  an existing file.

- bpo-3839: wsgiref should not override a Content-Length header set by the
  application. Initial patch by Clovis Fabricio.

- bpo-10806: Fix subprocess pipes when some of the standard file descriptors
  (0, 1, 2) are closed in the parent process.  Initial patch by Ross
  Lagerwall. (See also: bpo-9905)

- bpo-4662: os.tempnam(), os.tmpfile() and os.tmpnam() now raise a py3k
  DeprecationWarning.

- Subclasses of collections.OrderedDict now work correctly with __missing__.

- bpo-10753: Characters ';', '=' and ',' in the PATH_INFO environment
  variable won't be quoted when the URI is constructed by the wsgiref.util
  's request_uri method. According to RFC 3986, these characters can be a
  part of params in PATH component of URI and need not be quoted.

- bpo-10738: Fix webbrowser.Opera.raise_opts

- bpo-9824: SimpleCookie now encodes , and ; in values to cater to how
  browsers actually parse cookies.

- bpo-1379416: eliminated a source of accidental unicode promotion in
  email.header.Header.encode.

- bpo-5258: if site.py encounters a .pth file that generates an error, it
  now prints the filename, line number, and traceback to stderr and skips
  the rest of that individual file, instead of stopping processing entirely.
  (See also: bpo-10642)

- bpo-10750: The ``raw`` attribute of buffered IO objects is now read-only.

- bpo-10242: unittest.TestCase.assertItemsEqual makes too many assumptions
  about input.

- bpo-10611: SystemExit should not cause a unittest test run to exit.

- bpo-6791: Limit header line length (to 65535 bytes) in http.client, to
  avoid denial of services from the other party.

- bpo-9907: Fix tab handling on OSX when using editline by calling
  rl_initialize first, then setting our custom defaults, then reading
  .editrc.

- bpo-4188: Avoid creating dummy thread objects when logging operations from
  the threading module (with the internal verbose flag activated).

- bpo-9721: Fix the behavior of urljoin when the relative url starts with a
  ';' character. Patch by Wes Chow.

- bpo-10714: Limit length of incoming request in http.server to 65536 bytes
  for security reasons.  Initial patch by Ross Lagerwall.

- bpo-9558: Fix distutils.command.build_ext with VS 8.0.

- bpo-10695: passing the port as a string value to telnetlib no longer
  causes debug mode to fail.

- bpo-10478: Reentrant calls inside buffered IO objects (for example by way
  of a signal handler) now raise a RuntimeError instead of freezing the
  current process.

- bpo-10497: Fix incorrect use of gettext in argparse.

- bpo-10464: netrc now correctly handles lines with embedded '#' characters.

- bpo-1731717: Fixed the problem where subprocess.wait() could cause an
  OSError exception when The OS had been told to ignore SIGCLD in our
  process or otherwise not wait for exiting child processes.

- bpo-9509: argparse now properly handles IOErrors raised by
  argparse.FileType.

- bpo-9348: Raise an early error if argparse nargs and metavar don't match.

- bpo-8982: Improve the documentation for the argparse Namespace object.

- bpo-9343: Document that argparse parent parsers must be configured before
  their children.

- bpo-9026: Fix order of argparse sub-commands in help messages.

- bpo-9347: Fix formatting for tuples in argparse type= error messages.

- Stop using the old interface for providing methods and attributes in the
  _sre module. Among other things, this gives these classes ``__class__``
  attributes. (See #12099)

- bpo-10169: Fix argument parsing in socket.sendto() to avoid error masking.

- bpo-12051: Fix segfault in json.dumps() while encoding highly-nested
  objects using the C accelerations.

- bpo-12017: Fix segfault in json.loads() while decoding highly-nested
  objects using the C accelerations.

- bpo-1838: Prevent segfault in ctypes, when _as_parameter_ on a class is
  set to an instance of the class.

- bpo-678250: Make mmap flush a noop on ACCESS_READ and ACCESS_COPY.

IDLE
----

- bpo-11718: IDLE's open module dialog couldn't find the __init__.py file in
  a package.

- bpo-12590: IDLE editor window now always displays the first line when
  opening a long file.  With Tk 8.5, the first line was hidden.

- bpo-11088: don't crash when using F5 to run a script in IDLE on MacOSX
  with Tk 8.5.

- bpo-10940: Workaround an IDLE hang on Mac OS X 10.6 when using the menu
  accelerators for Open Module, Go to Line, and New Indent Width. The
  accelerators still work but no longer appear in the menu items.

- bpo-10907: Warn OS X 10.6 IDLE users to use ActiveState Tcl/Tk 8.5, rather
  than the currently problematic Apple-supplied one, when running with the
  64-/32-bit installer variant.

- bpo-11052: Correct IDLE menu accelerators on Mac OS X for Save commands.

- bpo-6075: IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa
  AquaTk.

- bpo-10404: Use ctl-button-1 on OSX for the context menu in Idle.

- bpo-10107: Warn about unsaved files in IDLE on OSX.

- bpo-10406: Enable Rstrip IDLE extension on OSX (just like on other
  platforms).

- bpo-6378: Further adjust idle.bat to start associated Python

- bpo-11896: Save on Close failed despite selecting "Yes" in dialog.

- bpo-4676: <Home> toggle failing on Tk 8.5, causing IDLE exits and strange
  selection behavior.  Improve selection extension behaviour.

- bpo-3851: <Home> toggle non-functional when NumLock set on Windows.

Build
-----

- bpo-11217: For 64-bit/32-bit Mac OS X universal framework builds, ensure
  "make install" creates symlinks in --prefix bin for the "-32" files in the
  framework bin directory like the installer does.

- bpo-11411: Fix 'make DESTDIR=' with a relative destination.

- bpo-10709: Add updated AIX notes in Misc/README.AIX.

- bpo-11184: Fix large-file support on AIX.

- bpo-941346: Fix broken shared library build on AIX.

- bpo-11268: Prevent Mac OS X Installer failure if Documentation package had
  previously been installed.

- bpo-11079: The /Applications/Python x.x folder created by the Mac OS X
  installers now includes a link to the installed documentation.

- bpo-11054: Allow Mac OS X installer builds to again work on 10.5 with the
  system-provided Python.

- bpo-10843: Update third-party library versions used in OS X 32-bit
  installer builds: bzip2 1.0.6, readline 6.1.2, SQLite 3.7.4 (with
  FTS3/FTS4 and RTREE enabled), and ncursesw 5.5 (wide-char support
  enabled).

- Don't run pgen twice when using make -j.

- bpo-7716: Under Solaris, don't assume existence of /usr/xpg4/bin/grep in
  the configure script but use $GREP instead.  Patch by Fabian Groffen.

- bpo-10475: Don't hardcode compilers for LDSHARED/LDCXXSHARED on NetBSD and
  DragonFly BSD.  Patch by Nicolas Joly.

- bpo-10655: Fix the build on PowerPC on Linux with GCC when building with
  timestamp profiling (--with-tsc): the preprocessor test for the PowerPC
  support now looks for "__powerpc__" as well as "__ppc__": the latter seems
  to only be present on OS X; the former is the correct one for Linux with
  GCC.

- bpo-1099: Fix the build on MacOSX when building a framework with pydebug
  using GCC 4.0.

Tests
-----

- bpo-11164: Remove obsolete allnodes test from minidom test.

- bpo-12205: Fix test_subprocess failure due to uninstalled test data.

- bpo-5723: Improve json tests to be executed with and without
  accelerations.

- bpo-11910: Fix test_heapq to skip the C tests when _heapq is missing.

- Fix test_startfile to wait for child process to terminate before
  finishing.

- bpo-11719: Fix message about unexpected test_msilib skip on non-Windows
  platforms. Patch by Nadeem Vawda.

- bpo-7108: Fix test_commands to not fail when special attributes ('@' or
  '.') appear in 'ls -l' output.

- bpo-11490: test_subprocess:test_leaking_fds_on_error no longer gives a
  false positive if the last directory in the path is inaccessible.

- bpo-10822: Fix test_posix:test_getgroups failure under Solaris.  Patch by
  Ross Lagerwall.

- bpo-6293: Have regrtest.py echo back sys.flags.  This is done by default
  in whole runs and enabled selectively using ``--header`` when running an
  explicit list of tests.  Original patch by Collin Winter.

- bpo-775964: test_grp now skips YP/NIS entries instead of failing when
  encountering them.

- bpo-7110: regrtest now sends test failure reports and single-failure
  tracebacks to stderr rather than stdout.


What's New in Python 2.7.1 final?
=================================

*Release date: 2010-11-27*

Library
-------

- bpo-2236: distutils' mkpath ignored the mode parameter.

- Fix typo in one sdist option (medata-check).

- bpo-10323: itertools.islice() now consumes the minimum number of inputs
  before stopping.  Formerly, the final state of the underlying iterator was
  undefined.

- bpo-10565: The collections.Iterator ABC now checks for both ``__iter__``
  and ``next``.

- bpo-10092: Properly reset locale in calendar.Locale*Calendar classes.

- bpo-10459: Update CJK character names to Unicode 5.2.

- bpo-6098: Don't claim DOM level 3 conformance in minidom.

- bpo-10561: In pdb, clear the breakpoints by the breakpoint number.

- bpo-5762: Fix AttributeError raised by ``xml.dom.minidom`` when an empty
  XML namespace attribute is encountered.

- bpo-1710703: Write structures for an empty ZIP archive when a ZipFile is
  created in modes 'a' or 'w' and then closed without adding any files.
  Raise BadZipfile (rather than IOError) when opening small non-ZIP files.

- bpo-4493: urllib2 adds '/' in front of path components which does not
  start with '/. Common behavior exhibited by browsers and other clients.

- bpo-10407: Fix one NameError in distutils.

- bpo-10198: fix duplicate header written to wave files when writeframes()
  is called without data.

- bpo-10467: Fix BytesIO.readinto() after seeking into a position after the
  end of the file.

- bpo-5111: IPv6 Host in the Header is wrapped inside [ ]. Patch by Chandru.

IDLE
----

- bpo-6378: idle.bat now runs with the appropriate Python version rather
  than the system default. Patch by Sridhar Ratnakumar.

Build
-----

- Backport r83399 to allow test_distutils to pass on installed versions.

- bpo-1303434: Generate ZIP file containing all PDBs.

Tests
-----

- bpo-9424: Replace deprecated assert* methods in the Python test suite.

Documentation
-------------

- bpo-10299: List the built-in functions in a table in functions.rst.


What's New in Python 2.7.1 release candidate 1?
===============================================

*Release date: 2010-11-13*

Core and Builtins
-----------------

- bpo-10221: dict.pop(k) now has a key error message that includes the
  missing key (same message d[k] returns for missing keys).

- bpo-10125: Don't segfault when the iterator passed to
  ``file.writelines()`` closes the file.

- bpo-10186: Fix the SyntaxError caret when the offset is equal to the
  length of the offending line.

- bpo-9997: Don't let the name "top" have special significance in scope
  resolution.

- bpo-9862: Compensate for broken PIPE_BUF in AIX by hard coding its value
  as the default 512 when compiling on AIX.

- bpo-9675: CObject use is marked as a Py3k warning, not a deprecation
  warning.

- bpo-10068: Global objects which have reference cycles with their module's
  dict are now cleared again. This causes issue #7140 to appear again.

- bpo-9869: Make long() and PyNumber_Long return something of type long for
  a class whose __long__ method returns a plain int.  This fixes an
  interpreter crash when initializing an instance of a long subclass from an
  object whose __long__ method returns a plain int.

- bpo-10006: type.__abstractmethods__ now raises an AttributeError.

- bpo-9797: pystate.c wrongly assumed that zero couldn't be a valid
  thread-local storage key.

- bpo-4947: The write() method of sys.stdout and sys.stderr uses their
  encoding and errors attributes instead of using utf-8 in strict mode, to
  get the same behaviour than the print statement.

- bpo-9737: Fix a crash when trying to delete a slice or an item from a
  memoryview object.

- Restore GIL in nis_cat in case of error.

- bpo-9688: __basicsize__ and __itemsize__ must be accessed as Py_ssize_t.

- bpo-8530: Prevent stringlib fastsearch from reading beyond the front of an
  array.

- bpo-83755: Implicit set-to-frozenset conversion was not thread-safe.

- bpo-9416: Fix some issues with complex formatting where the output with no
  type specifier failed to match the str output:

  - format(complex(-0.0, 2.0), '-') omitted the real part from the output,
  - format(complex(0.0, 2.0), '-') included a sign and parentheses.

- bpo-7616: Fix copying of overlapping memoryview slices with the Intel
  compiler.

Library
-------

- bpo-9926: Wrapped TestSuite subclass does not get __call__ executed

- bpo-4471: Properly shutdown socket in IMAP.shutdown().  Patch by Lorenzo
  M. Catucci.

- bpo-10126: Fix distutils' test_build when Python was built with
  --enable-shared.

- Fix typo in one sdist option (medata-check).

- bpo-9199: Fix incorrect use of distutils.cmd.Command.announce.

- bpo-1718574: Fix options that were supposed to accept arguments but did
  not in build_clib.

- bpo-9281: Prevent race condition with mkdir in distutils.  Patch by
  Arfrever.

- bpo-10229: Fix caching error in gettext.

- bpo-10252: Close file objects in a timely manner in distutils code and
  tests.  Patch by Brian Brazil, completed by Éric Araujo.

- bpo-10311: The signal module now restores errno before returning from its
  low-level signal handler.  Patch by Hallvard B Furuseth.

- bpo-10038: json.loads() on str should always return unicode (regression
  from Python 2.6).  Patch by Walter Dörwald.

- bpo-120176: Wrapped TestSuite subclass does not get __call__ executed.

- bpo-6706: asyncore accept() method no longer raises
  EWOULDBLOCK/ECONNABORTED on incomplete connection attempt but returns None
  instead.

- bpo-10266: uu.decode didn't close in_file explicitly when it was given as
  a filename. Patch by Brian Brazil.

- bpo-10246: uu.encode didn't close file objects explicitly when filenames
  were given to it.  Patch by Brian Brazil.

- bpo-10253: FileIO leaks a file descriptor when trying to open a file for
  append that isn't seekable.  Patch by Brian Brazil.

- bpo-6105: json.dumps now respects OrderedDict's iteration order.

- bpo-9295: Fix a crash under Windows when calling close() on a file object
  with custom buffering from two threads at once.

- bpo-5027: The standard ``xml`` namespace is now understood by
  xml.sax.saxutils.XMLGenerator as being bound to
  http://www.w3.org/XML/1998/namespace.  Patch by Troy J. Farrell.

- bpo-10163: Skip unreadable registry keys during mimetypes initialization.

- bpo-5117: Fixed root directory related issue on posixpath.relpath() and
  ntpath.relpath().

- bpo-9409: Fix the regex to match all kind of filenames, for interactive
  debugging in doctests.

- bpo-6612: Fix site and sysconfig to catch os.getcwd() error, eg. if the
  current directory was deleted. Patch written by W. Trevor King.

- bpo-10045: Improved performance when writing after seeking past the end of
  the "file" in cStringIO.

- bpo-9948: Fixed problem of losing filename case information.

- bpo-9437: Fix building C extensions with non-default LDFLAGS.

- bpo-9759: GzipFile now raises ValueError when an operation is attempted
  after the file is closed.  Patch by Jeffrey Finkelstein.

- bpo-9042: Fix interaction of custom translation classes and caching in
  gettext.

- bpo-9065: tarfile no longer uses "root" as the default for the uname and
  gname field.

- bpo-1050268: parseaddr now correctly quotes double quote and backslash
  characters that appear inside quoted strings in email addresses.

- bpo-10004: quoprimime no longer generates a traceback when confronted with
  invalid characters after '=' in a Q-encoded word.

- bpo-9950: Fix socket.sendall() crash or misbehaviour when a signal is
  received.  Now sendall() properly calls signal handlers if necessary, and
  retries sending if these returned successfully, including on sockets with
  a timeout.

- bpo-9947: logging: Fixed locking bug in stopListening.

- bpo-9945: logging: Fixed locking bugs in addHandler/removeHandler.

- bpo-9936: Fixed executable lines' search in the trace module.

- bpo-9928: Properly initialize the types exported by the bz2 module.

- bpo-9854: The default read() implementation in io.RawIOBase now handles
  non-blocking readinto() returning None correctly.

- bpo-9729: Fix the signature of SSLSocket.recvfrom() and SSLSocket.sendto()
  to match the corresponding socket methods.  Also, fix various SSLSocket
  methods to raise socket.error rather than an unhelpful TypeError when
  called on an unconnected socket.  Original patch by Andrew Bennetts.

- bpo-9826: OrderedDict.__repr__ can now handle self-referential values:
  d['x'] = d.

- bpo-767645: Set os.path.supports_unicode_filenames to True on Mac OS X.

- bpo-9837: The read() method of ZipExtFile objects (as returned by
  ZipFile.open()) could return more bytes than requested.

- bpo-9825: removed __del__ from the definition of collections.OrderedDict.
  This prevents user-created self-referencing ordered dictionaries from
  becoming permanently uncollectable GC garbage.  The downside is that
  removing __del__ means that the internal doubly-linked list has to wait
  for GC collection rather than freeing memory immediately when the refcnt
  drops to zero.

- bpo-9816: random.Random.jumpahead(n) did not produce a sufficiently
  different internal state for small values of n.  Fixed by salting the
  value.

- bpo-9792: In case of connection failure, socket.create_connection() would
  swallow the exception and raise a new one, making it impossible to fetch
  the original errno, or to filter timeout errors.  Now the original error
  is re-raised.

- bpo-9758: When fcntl.ioctl() was called with mutable_flag set to True, and
  the passed buffer was exactly 1024 bytes long, the buffer wouldn't be
  updated back after the system call.  Original patch by Brian Brazil.

- bpo-1100562: Fix deep-copying of objects derived from the list and dict
  types.  Patch by Michele Orrù and Björn Lindqvist.

- bpo-7005: Fixed output of None values for RawConfigParser.write and
  ConfigParser.write.

- bpo-808164: Fixed socket.close to avoid references to globals, to avoid
  issues when socket.close is called from a __del__ method.

- bpo-2986: difflib.SequenceMatcher gets a new parameter, autojunk, which
  can be set to False to turn off the previously undocumented 'popularity'
  heuristic. Patch by Terry Reedy and Eli Bendersky

- bpo-8797: urllib2 does a retry for Basic Authentication failure instead of
  falling into recursion.

- bpo-1194222: email.utils.parsedate now returns RFC2822 compliant four
  character years even if the message contains RFC822 two character years.

- bpo-8750: Fixed MutableSet's methods to correctly handle reflexive
  operations, namely x -= x and x ^= x.

- bpo-9129: smtpd.py is vulnerable to DoS attacks deriving from missing
  error handling when accepting a new connection.

- bpo-658749: asyncore's connect() method now correctly interprets winsock
  errors.

- bpo-9501: Fixed logging regressions in cleanup code.

- bpo-9214: Set operations on KeysView or ItemsView in the collections
  module now correctly return a set.  (Patch by Eli Bendersky.)

- bpo-9617: Signals received during a low-level write operation aren't
  ignored by the buffered IO layer anymore.

- bpo-2521: Use weakrefs on for caching in the abc module, so that classes
  are not held onto after they are deleted elsewhere.

- bpo-9626: the view methods for collections.OrderedDict() were returning
  the unordered versions inherited from dict.  Those methods are now
  overridden to provide ordered views.

- bpo-8688: MANIFEST files created by distutils now include a magic comment
  indicating they are generated.  Manually maintained MANIFESTs without this
  marker will not be overwritten or removed.

- bpo-7467: when reading a file from a ZIP archive, its CRC is checked and a
  BadZipfile error is raised if it doesn't match (as used to be the case in
  Python 2.5 and earlier).

- bpo-9550: a BufferedReader could issue an additional read when the
  original read request had been satisfied, which could block indefinitely
  when the underlying raw IO channel was e.g. a socket.  Report and original
  patch by Jason V. Miller.

- bpo-9551: Don't raise TypeError when setting the value to None for
  SafeConfigParser instances constructed with allow_no_value == True.

- bpo-6915: Under Windows, os.listdir() didn't release the Global
  Interpreter Lock around all system calls.  Original patch by Ryan Kelly.

- bpo-3757: thread-local objects now support cyclic garbage collection.
  Thread-local objects involved in reference cycles will be deallocated
  timely by the cyclic GC, even if the underlying thread is still running.

- bpo-6231: Fix xml.etree.ElementInclude to include the tail of the current
  node.

- bpo-6869: Fix a refcount problem in the _ctypes extension.

- bpo-5504: ctypes should now work with systems where mmap can't be
  PROT_WRITE and PROT_EXEC.

- bpo-8280: urllib2's Request method will remove fragements in the url. This
  is how it is supposed to work, wget and curl do the same.  Previous
  behavior was wrong.

- bpo-2944: asyncore doesn't handle connection refused correctly.

- bpo-3196: email header decoding is now forgiving if an RFC2047 encoded
  word encoded in base64 is lacking padding.

- bpo-9444: Argparse now uses the first element of prefix_chars as the
  option character for the added 'h/help' option if prefix_chars does not
  contain a '-', instead of raising an error.

- bpo-9354: Provide getsockopt() in asyncore's file_wrapper.

- bpo-9428: Fix running scripts with the profile/cProfile modules from the
  command line.

- bpo-7781: Fix restricting stats by entry counts in the pstats interactive
  browser.

- bpo-9209: Do not crash in the pstats interactive browser on invalid
  regular expressions.

- bpo-7372: Fix pstats regression when stripping paths from profile data
  generated with the profile module.

- bpo-4108: In urllib.robotparser, if there are multiple 'User-agent: *'
  entries, consider the first one.

- bpo-8397: Raise an error when attempting to mix iteration and regular
  reads on a BZ2File object, rather than returning incorrect results.

- bpo-5294: Fix the behavior of pdb's "continue" command when called in the
  top-level debugged frame.

- bpo-5727: Restore the ability to use readline when calling into pdb in
  doctests.

- bpo-6719: In pdb, do not stop somewhere in the encodings machinery if the
  source file to be debugged is in a non-builtin encoding.

- bpo-8048: Prevent doctests from failing when sys.displayhook has been
  reassigned.

- bpo-8015: In pdb, do not crash when an empty line is entered as a
  breakpoint command.

- bpo-9448: Fix a leak of OS resources (mutexes or semaphores) when
  re-initializing a buffered IO object by calling its ``__init__`` method.

- bpo-7909: Do not touch paths with the special prefixes ``\\.\`` or
  ``\\?\`` in ntpath.normpath().

- bpo-5146: Handle UID THREAD command correctly in imaplib.

- bpo-5147: Fix the header generated for cookie files written by
  http.cookiejar.MozillaCookieJar.

- bpo-8198: In pydoc, output all help text to the correct stream when
  sys.stdout is reassigned.

- bpo-7395: Fix tracebacks in pstats interactive browser.

- bpo-8230: Fix Lib/test/sortperf.py.

- bpo-1713: Fix os.path.ismount(), which returned true for symbolic links
  across devices.

- bpo-8826: Properly load old-style "expires" attribute in http.cookies.

- bpo-1690103: Fix initial namespace for code run with trace.main().

- bpo-8471: In doctest, properly reset the output stream to an empty string
  when Unicode was previously output.

- bpo-8620: when a Cmd is fed input that reaches EOF without a final
  newline, it no longer truncates the last character of the last command
  line.

- bpo-6213: Implement getstate() and setstate() methods of utf-8-sig and
  utf-16 incremental encoders.

- bpo-7113: Speed up loading in ConfigParser. Patch by Łukasz Langa.

- bpo-3704: cookielib was not properly handling URLs with a / in the
  parameters.

- bpo-9032: XML-RPC client retries the request on EPIPE error. The EPIPE
  error occurs when the server closes the socket and the client sends a big
  XML-RPC request.

- bpo-5542: Remove special logic that closes HTTPConnection socket on EPIPE.

- bpo-4629: getopt raises an error if an argument ends with = whereas getopt
  doesn't except a value (eg. --help= is rejected if getopt uses ['help=']
  long options).

- bpo-7895: platform.mac_ver() no longer crashes after calling os.fork()

- bpo-5395: array.fromfile() would raise a spurious EOFError when an I/O
  error occurred. Now an IOError is raised instead.  Patch by chuck (Jan
  Hosang).

- bpo-7646: The fnmatch pattern cache no longer grows without bound.

- bpo-9136: Fix 'dictionary changed size during iteration' RuntimeError
  produced when profiling the decimal module.  This was due to a dangerous
  iteration over 'locals()' in Context.__init__.

- Fix extreme speed issue in Decimal.pow when the base is an exact power of
  10 and the exponent is tiny (for example, Decimal(10) **
  Decimal('1e-999999999')).

- bpo-9161: Fix regression in optparse's acceptance of unicode strings in
  add_option calls.

- bpo-9130: Fix validation of relative imports in parser module.

- bpo-9128: Fix validation of class decorators in parser module.

- bpo-9164: Ensure sysconfig handles dupblice archs while building on OSX

- bpo-9315: Fix for the trace module to record correct class name for
  tracing methods.

- bpo-9054: Fix a crash occurring when using the pyexpat module with expat
  version 2.0.1.

- bpo-10003: Allow handling of SIGBREAK on Windows. Fixes a regression
  introduced by issue #9324.

- bpo-8734: Avoid crash in msvcrt.get_osfhandle() when an invalid file
  descriptor is provided.  Patch by Pascal Chambon.

- bpo-7736: Release the GIL around calls to opendir() and closedir() in the
  posix module.  Patch by Marcin Bachry.

- As a result of issue #2521, the _weakref module is now compiled into the
  interpreter by default.

- bpo-9324: Add parameter validation to signal.signal on Windows in order to
  prevent crashes.

- bpo-9526: Remove some outdated (int) casts that were preventing the array
  module from working correctly with arrays of more than 2**31 elements.

- Fix memory leak in ssl._ssl._test_decode_cert.

- bpo-8065: Fix memory leak in readline module (from failure to free the
  result of history_get_history_state()).

- bpo-9450: Fix memory leak in readline.replace_history_item and
  readline.remove_history_item for readline version >= 5.0.

- bpo-8105: Validate file descriptor passed to mmap.mmap on Windows.

- bpo-1019882: Fix IndexError when loading certain hotshot stats.

- bpo-9422: Fix memory leak when re-initializing a struct.Struct object.

- bpo-7900: The getgroups(2) system call on MacOSX behaves rather oddly
  compared to other unix systems. In particular, os.getgroups() does not
  reflect any changes made using os.setgroups() but basically always returns
  the same information as the id command.

  os.getgroups() can now return more than 16 groups on MacOSX.

- bpo-9277: Fix bug in struct.pack for bools in standard mode (e.g.,
  struct.pack('>?')): if conversion to bool raised an exception then that
  exception wasn't properly propagated on machines where char is unsigned.

- bpo-7567: Don't call `setupterm' twice.

Tools/Demos
-----------

- bpo-7287: Demo/imputil/knee.py was removed.

- bpo-9188: The gdb extension now handles correctly narrow (UCS2) as well as
  wide (UCS4) unicode builds for both the host interpreter (embedded inside
  gdb) and the interpreter under test.

Build
-----

- bpo-8852: Allow the socket module to build on OpenSolaris.

- bpo-10054: Some platforms provide uintptr_t in inttypes.h.  Patch by Akira
  Kitada.

- bpo-10055: Make json C89-compliant in UCS4 mode.

- bpo-1633863: Don't ignore $CC under AIX.

- bpo-9810: Compile bzip2 source files in python's project file directly. It
  used to be built with bzip2's makefile.

- bpo-941346: Improve the build process under AIX and allow Python to be
  built as a shared library.  Patch by Sébastien Sablé.

- bpo-4026: Make the fcntl extension build under AIX.  Patch by Sébastien
  Sablé.

- bpo-3101: Helper functions _add_one_to_index_C() and _add_one_to_index_F()
  become _Py_add_one_to_index_C() and _Py_add_one_to_index_F(),
  respectively.

- bpo-9700: define HAVE_BROKEN_POSIX_SEMAPHORES under AIX 6.x.  Patch by
  Sébastien Sablé.

- bpo-9280: Make sharedinstall depend on sharedmods.

- bpo-9275: The OSX installer once again installs links to binaries in
  ``/usr/local/bin``.

- bpo-9392: A framework build on OSX will once again use a versioned name of
  the ``2to3`` tool, that is you can use ``2to3-2.7`` to select the Python
  2.7 edition of 2to3.

- bpo-9701: The MacOSX installer can patch the shell profile to ensure that
  the "bin" directory inside the framework is on the shell's search path.
  This feature now also supports the ZSH shell.

- bpo-7473: avoid link errors when building a framework with a different set
  of architectures than the one that is currently installed.

Tests
-----

- bpo-9978: Wait until subprocess completes initialization. (Win32KillTests
  in test_os)

- bpo-9894: Do not hardcode ENOENT in test_subprocess.

- bpo-9323: Make test.regrtest.__file__ absolute, this was not always the
  case when running profile or trace, for example.

- bpo-9315: Added tests for the trace module.  Patch by Eli Bendersky.

- Strengthen test_unicode with explicit type checking for assertEqual tests.

- bpo-8857: Provide a test case for socket.getaddrinfo.

- bpo-7564: Skip test_ioctl if another process is attached to /dev/tty.

- bpo-8433: Fix test_curses failure with newer versions of ncurses.

- bpo-9496: Provide a test suite for the rlcompleter module.  Patch by
  Michele Orrù.

- bpo-8605: Skip test_gdb if Python is compiled with optimizations.

- bpo-9568: Fix test_urllib2_localnet on OS X 10.3.

Documentation
-------------

- bpo-9817: Add expat COPYING file; add expat, libffi and expat licenses to
  Doc/license.rst.

- bpo-9524: Document that two CTRL* signals are meant for use only with
  os.kill.

- bpo-9255: Document that the 'test' package is for internal Python use
  only.

- bpo-7829: Document in dis that bytecode is an implementation detail.


What's New in Python 2.7 final?
===============================

*Release date: 2010-07-03*

Core and Builtins
-----------------

- Prevent assignment to set literals.

Library
-------

- bpo-1868: Eliminate subtle timing issues in thread-local objects by
  getting rid of the cached copy of thread-local attribute dictionary.

- bpo-9125: Add recognition of 'except ... as ...' syntax to parser module.

- bpo-7673: Fix security vulnerability (CVE-2010-2089) in the audioop
  module, ensure that the input string length is a multiple of the frame
  size.

- bpo-9075: In the ssl module, remove the setting of a ``debug`` flag on an
  OpenSSL structure.


What's New in Python 2.7 release candidate 2?
=============================================

*Release date: 2010-06-20*

Core and Builtins
-----------------

- bpo-9058: Remove assertions about INT_MAX in UnicodeDecodeError.

- bpo-8202: Previous change to ``sys.argv[0]`` handling for -m command line
  option reverted due to unintended side effects on handling of
  ``sys.path``. See tracker issue for details.

- bpo-8941: decoding big endian UTF-32 data in UCS-2 builds could crash the
  interpreter with characters outside the Basic Multilingual Plane (higher
  than 0x10000).

- In the unicode/str.format(), raise a ValueError when indexes to arguments
  are too large.

Build
-----

- bpo-8854: Fix finding Visual Studio 2008 on Windows x64.

Library
-------

- bpo-6589: cleanup asyncore.socket_map in case smtpd.SMTPServer constructor
  raises an exception.

- bpo-8959: fix regression caused by using unmodified libffi library on
  Windows.  ctypes does now again check the stack before and after calling
  foreign functions.

- bpo-8720: fix regression caused by fix for #4050 by making getsourcefile
  smart enough to find source files in the linecache.

- bpo-8986: math.erfc was incorrectly raising OverflowError for values
  between -27.3 and -30.0 on some platforms.

- bpo-8924: logging: Improved error handling for Unicode in exception text.

- bpo-8948: cleanup functions and class / module setups and teardowns are
  now honored in unittest debug methods.

Documentation
-------------

- bpo-8909: Added the size of the bitmap used in the installer created by
  distutils' bdist_wininst. Patch by Anatoly Techtonik.

Windows
-------

- bpo-8362: Add maintainers.rst: list of module maintainers


What's New in Python 2.7 release candidate 1?
=============================================

*Release date: 2010-06-05*

Core and Builtins
-----------------

- bpo-8271: during the decoding of an invalid UTF-8 byte sequence, only the
  start byte and the continuation byte(s) are now considered invalid,
  instead of the number of bytes specified by the start byte. E.g.:
  '\xf1\x80AB'.decode('utf-8', 'replace') now returns u'\ufffdAB' and
  replaces with U+FFFD only the start byte ('\xf1') and the continuation
  byte ('\x80') even if '\xf1' is the start byte of a 4-bytes sequence.
  Previous versions returned a single u'\ufffd'.

- bpo-8627: Remove bogus "Overriding __cmp__ blocks inheritance of __hash__
  in 3.x" warning.  Also fix "XXX undetected error" that arises from the
  "Overriding __eq__ blocks inheritance ..." warning when turned into an
  exception: in this case the exception simply gets ignored.

- bpo-8748: Fix two issues with comparisons between complex and integer
  objects.  (1) The comparison could incorrectly return True in some cases
  (2**53+1 == complex(2**53) == 2**53), breaking transivity of equality. (2)
  The comparison raised an OverflowError for large integers, leading to
  unpredictable exceptions when combining integers and complex objects in
  sets or dicts.

- bpo-5211: Implicit coercion for the complex type is now completely
  removed.  (Coercion for arithmetic operations was already removed in 2.7
  alpha 4, but coercion for rich comparisons was accidentally left in.)

- bpo-3798: Write sys.exit() message to sys.stderr to use stderr encoding
  and error handler, instead of writing to the C stderr file in utf-8

- bpo-7902: When using explicit relative import syntax, don't try implicit
  relative import semantics.

- bpo-7079: Fix a possible crash when closing a file object while using it
  from another thread.  Patch by Daniel Stutzbach.

- bpo-8868: Fix that ensures that python scripts have access to the Window
  Server again in a framework build on MacOSX 10.5 or earlier.

C API
-----

- bpo-5753: A new C API function, :cfunc:`PySys_SetArgvEx`, allows embedders
  of the interpreter to set sys.argv without also modifying sys.path.  This
  helps fix `CVE-2008-5983
  <http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-5983>`_.

Library
-------

- bpo-8302: SkipTest in unittest.TestCase.setUpClass or setUpModule is now
  reported as a skip rather than an error.

- bpo-8351: Excessively large diffs due to
  unittest.TestCase.assertSequenceEqual are no longer included in failure
  reports.

- bpo-8899: time.struct_time now has class and attribute docstrings.

- bpo-4487: email now accepts as charset aliases all codec aliases accepted
  by the codecs module.

- bpo-6470: Drop UNC prefix in FixTk.

- bpo-5610: feedparser no longer eats extra characters at the end of a body
  part if the body part ends with a \r\n.

- bpo-8833: tarfile created hard link entries with a size field != 0 by
  mistake.

- bpo-1368247: set_charset (and therefore MIMEText) now automatically
  encodes a unicode _payload to the output_charset.

- bpo-7150: Raise OverflowError if the result of adding or subtracting
  timedelta from date or datetime falls outside of the MINYEAR:MAXYEAR
  range.

- bpo-6662: Fix parsing of malformatted charref (&#bad;), patch written by
  Fredrik Håård

- bpo-8016: Add the CP858 codec.

- bpo-3924: Ignore cookies with invalid "version" field in cookielib.

- bpo-6268: Fix seek() method of codecs.open(), don't read or write the BOM
  twice after seek(0). Fix also reset() method of codecs, UTF-16, UTF-32 and
  StreamWriter classes.

- bpo-5640: Fix Shift-JIS incremental encoder for error handlers different
  than 'strict'.

- bpo-8782: Add a trailing newline in linecache.updatecache to the last line
  of files without one.

- bpo-8729: Return NotImplemented from ``collections.Mapping.__eq__()`` when
  comparing to a non-mapping.

- bpo-8759: Fix user paths in sysconfig for posix and os2 schemes.

- bpo-1285086: Speed up ``urllib.quote()`` and urllib.unquote for simple
  cases.

- bpo-8688: Distutils now recalculates MANIFEST every time.

- bpo-5099: The ``__del__()`` method of ``subprocess.Popen`` (and the
  methods it calls) referenced global objects, causing errors to pop up
  during interpreter shutdown.

- bpo-7384: If the system readline library is linked against ncurses, the
  curses module must be linked against ncurses as well. Otherwise it is not
  safe to load both the readline and curses modules in an application.

- bpo-2810: Fix cases where the Windows registry API returns
  ERROR_MORE_DATA, requiring a re-try in order to get the complete result.

- bpo-8674: Fixed a number of incorrect or undefined-behaviour-inducing
  overflow checks in the ``audioop`` module.

Tests
-----

- bpo-8889: test_support.transient_internet rewritten so that the new checks
  also work on FreeBSD, which lacks EAI_NODATA.

- bpo-8835: test_support.transient_internet() catches gaierror(EAI_NONAME)
  and gaierror(EAI_NODATA)

- bpo-7449: Skip test_socketserver if threading support is disabled

- On darwin, ``test_site`` assumed that a framework build was being used,
  leading to a failure where four directories were expected for
  site-packages instead of two in a non-framework build.

Build
-----

- Display installer warning that Windows 2000 won't be supported in future
  releases.

- bpo-1759169: Drop _XOPEN_SOURCE on Solaris, define it for multiprocessing
  only. (See also: bpo-8864)

Tools/Demos
-----------

- bpo-5464: Implement plural forms in msgfmt.py.


What's New in Python 2.7 beta 2?
================================

*Release date: 2010-05-08*

Core and Builtins
-----------------

- Run Clang 2.7's static analyzer for ``Objects/`` and ``Python/``.

- bpo-1533: Fix inconsistency in range function argument processing: any
  non-float non-integer argument is now converted to an integer (if
  possible) using its __int__ method.  Previously, only small arguments were
  treated this way; larger arguments (those whose __int__ was outside the
  range of a C long) would produce a TypeError.

- bpo-8202: ``sys.argv[0]`` is now set to '-m' instead of '-c' when
  searching for the module file to be executed with the -m command line
  option.

- bpo-7319: When -Q is used, do not silence DeprecationWarning.

- bpo-7332: Remove the 16KB stack-based buffer in
  ``PyMarshal_ReadLastObjectFromFile``, which doesn't bring any noticeable
  benefit compared to the dynamic memory allocation fallback.  Patch by
  Charles-François Natali.

- bpo-8417: Raise an OverflowError when an integer larger than sys.maxsize
  is passed to bytearray.

- bpo-7072: ``isspace(0xa0)`` is true on Mac OS X.

- bpo-8404: Fix set operations on dictionary views.

- bpo-8084: PEP 370 now conforms to system conventions for framework builds
  on MacOS X. That is, ``python setup.py install --user`` will install into
  ``~/Library/Python/2.7`` instead of ``~/.local``.

Library
-------

- bpo-8681: Make the zlib module's error messages more informative when the
  zlib itself doesn't give any detailed explanation.

- bpo-8571: Fix an internal error when compressing or decompressing a chunk
  larger than 1GB with the zlib module's compressor and decompressor
  objects.

- bpo-8573: asyncore ``_strerror()`` function might throw ValueError.

- bpo-8483: asyncore.dispatcher's __getattr__ method produced confusing
  error messages when accessing undefined class attributes because of the
  cheap inheritance with the underlying socket object.  The cheap
  inheritance has been deprecated.

- bpo-4265: ``shutil.copyfile()`` was leaking file descriptors when disk
  fills.  Patch by Tres Seaver.

- bpo-7755: Use an unencumbered audio file for tests.

- bpo-8621: ``uuid.uuid4()`` returned the same sequence of values in the
  parent and any children created using ``os.fork`` on Mac OS X 10.6.

- bpo-8313: ``traceback.format_exception_only()`` encodes unicode message to
  ASCII with backslashreplace error handler if ``str(value)`` failed.

- bpo-8567: Fix precedence of signals in Decimal module: when a Decimal
  operation raises multiple signals and more than one of those signals is
  trapped, the specification determines the order in which the signals
  should be handled. In many cases this order wasn't being followed, leading
  to the wrong Python exception being raised.

- bpo-7865: The close() method of :mod:`io` objects should not swallow
  exceptions raised by the implicit flush().  Also ensure that calling
  close() several times is supported.  Patch by Pascal Chambon.

- bpo-8576: logging updated to remove usage of find_unused_port().

- bpo-4687: Fix accuracy of garbage collection runtimes displayed with
  gc.DEBUG_STATS.

- bpo-8354: The siginterrupt setting is now preserved for all signals, not
  just SIGCHLD.

- bpo-7192: ``webbrowser.get("firefox")`` now works on Mac OS X, as does
  ``webbrowser.get("safari")``.

- bpo-8577: ``distutils.sysconfig.get_python_inc()`` now makes a difference
  between the build dir and the source dir when looking for "python.h" or
  "Include".

- bpo-8464: tarfile no longer creates files with execute permissions set
  when mode="w|" is used.

- bpo-7834: Fix connect() of Bluetooth L2CAP sockets with recent versions of
  the Linux kernel.  Patch by Yaniv Aknin.

- bpo-6312: Fix http HEAD request when the transfer encoding is chunked.  It
  should correctly return an empty response now.

- bpo-7490: To facilitate sharing of doctests between 2.x and 3.x test
  suites, the ``IGNORE_EXCEPTION_DETAIL`` directive now also ignores the
  module location of the raised exception.  Based on initial patch by
  Lennart Regebro.

- bpo-8086: In :func:`ssl.DER_cert_to_PEM_cert()`, fix missing newline
  before the certificate footer.  Patch by Kyle VanderBeek.

- bpo-8546: Reject None given as the buffering argument to ``_pyio.open()``.

- bpo-8549: Fix compiling the _ssl extension under AIX.  Patch by Sridhar
  Ratnakumar.

- bpo-6656: Fix locale.format_string to handle escaped percents and
  mappings.

- bpo-2302: Fix a race condition in SocketServer.BaseServer.shutdown, where
  the method could block indefinitely if called just before the event loop
  started running.  This also fixes the occasional freezes witnessed in
  test_httpservers.

- bpo-5103: SSL handshake would ignore the socket timeout and block
  indefinitely if the other end didn't respond.

- The do_handshake() method of SSL objects now adjusts the blocking mode of
  the SSL structure if necessary (as other methods already do).

- bpo-7507: Quote "!" in pipes.quote(); it is special to some shells.

- bpo-5238: Calling makefile() on an SSL object would prevent the underlying
  socket from being closed until all objects get truely destroyed.

- bpo-7943: Fix circular reference created when instantiating an SSL socket.
  Initial patch by Péter Szabó.

- bpo-8451: Syslog module now uses basename(sys.argv[0]) instead of the
  string "python" as the *ident*.  openlog() arguments are all optional and
  keywords.

- bpo-8108: Fix the unwrap() method of SSL objects when the socket has a
  non-infinite timeout.  Also make that method friendlier with applications
  wanting to continue using the socket in clear-text mode, by disabling
  OpenSSL's internal readahead.  Thanks to Darryl Miles for guidance.

- bpo-8484: Load all ciphers and digest algorithms when initializing the
  _ssl extension, such that verification of some SSL certificates doesn't
  fail because of an "unknown algorithm".

- bpo-8437: Fix test_gdb failures, patch written by Dave Malcolm

- bpo-4814: The timeout parameter is now applied also for connections
  resulting from PORT/EPRT commands.

- bpo-8463: Add missing reference to bztar in shutil's documentation.

- bpo-8438: Remove reference to the missing "surrogateescape" encoding error
  handler from the new IO library.

- bpo-3817: ftplib.FTP.abort() method now considers 225 a valid response
  code as stated in RFC-959 at chapter 5.4.

- bpo-8279: Fix test_gdb failures.

- bpo-8322: Add a *ciphers* argument to SSL sockets, so as to change the
  available cipher list.  Helps fix test_ssl with OpenSSL 1.0.0.

- bpo-2987: RFC 2732 support for urlparse (IPv6 addresses).  Patch by Tony
  Locke and Hans Ulrich Niedermann.

- bpo-7585: difflib context and unified diffs now place a tab between
  filename and date, conforming to the 'standards' they were originally
  designed to follow.  This improves compatibility with patch tools.

- bpo-7472: Fixed typo in email.encoders module; messages using ISO-2022
  character sets will now consistently use a Content-Transfer-Encoding of
  7bit rather than sometimes being marked as 8bit.

- bpo-8330: Fix expected output in test_gdb.

- bpo-8374: Update the internal alias table in the :mod:`locale` module to
  cover recent locale changes and additions.

- bpo-8644: Improved accuracy of ``timedelta.total_seconds()``.

- Use Clang 2.7's static analyzer to find places to clean up some code.

- Build the ossaudio extension on GNU/kFreeBSD.

- On Windows, ctypes no longer checks the stack before and after calling a
  foreign function.  This allows using the unmodified libffi library.

Tests
-----

- bpo-8672: Add a zlib test ensuring that an incomplete stream can be
  handled by a decompressor object without errors (it returns incomplete
  uncompressed data).

- bpo-8490: asyncore now has a more solid test suite which actually tests
  its API.

- bpo-8576: Remove use of find_unused_port() in test_smtplib and
  test_multiprocessing. Patch by Paul Moore.

- bpo-7449: Fix many tests to support Python compiled without thread
  support. Patches written by Jerry Seutter.

- bpo-8108: test_ftplib's non-blocking SSL server now has proper handling of
  SSL shutdowns.

Build
-----

- bpo-8625: Turn off optimization in ``--with-pydebug`` builds with gcc.
  (Optimization was unintentionally turned on in gcc --with-pydebug builds
  in 2.7 beta1 as a result of the issue #1628484 fix, combined with
  autoconf's strange choice of default CFLAGS produced by AC_PROG_CC for
  gcc.)

- bpo-8509: Fix quoting in help strings and code snippets in configure.in.

- bpo-3646: It is now easily possible to install a Python framework into
  your home directory on Mac OS X, see Mac/README for more information.

- bpo-8510: Update to autoconf 2.65.

Windows
-------

- Update the Vim syntax highlight file.


What's New in Python 2.7 beta 1?
================================

*Release date: 2010-04-10*

Core and Builtins
-----------------

- bpo-7301: Add environment variable $PYTHONWARNINGS.

- bpo-8329: Don't return the same lists from select.select when no fds are
  changed.

- bpo-8259: ``1L << (2**31)`` no longer produces an 'outrageous shift error'
  on 64-bit machines.  The shift count for either left or right shift is
  permitted to be up to sys.maxsize.

- Ensure that tokenization of identifiers is not affected by locale.

- bpo-1222585: Added LDCXXSHARED for C++ support.  Patch by Arfrever.

- Raise a TypeError when trying to delete a T_STRING_INPLACE struct member.

- bpo-7994: Issue a PendingDeprecationWarning if object.__format__ is called
  with a non-empty format string. This is an effort to future-proof user
  code. If a derived class does not currently implement __format__ but later
  adds its own __format__, it would most likely break user code that had
  supplied a format string. This will be changed to a DeprecationWarning in
  Python 3.3 and it will be an error in Python 3.4.

- bpo-8268: Old-style classes (not just instances) now support weak
  references.

- bpo-8211: Save/restore CFLAGS around AC_PROG_CC in configure.in, in case
  it is set.

- bpo-1583863: A unicode subclass can now override the __unicode__ method

- bpo-6474: Make error message from passing an inadequate number of keyword
  arguments to a function correct.

- bpo-8164: Don't allow lambda functions to have a docstring.

- bpo-3137: Don't ignore errors at startup, especially a keyboard interrupt
  (SIGINT). If an error occurs while importing the site module, the error is
  printed and Python exits.  Initialize the GIL before importing the site
  module.

- Code objects now support weak references.

Library
-------

- bpo-5277: Fix quote counting when parsing RFC 2231 encoded parameters.

- bpo-8321: Give access to OpenSSL version numbers from the `ssl` module,
  using the new attributes `ssl.OPENSSL_VERSION`, `ssl.OPENSSL_VERSION_INFO`
  and `ssl.OPENSSL_VERSION_NUMBER`.

- bpo-8310: Allow dis to examine new style classes.

- bpo-8257: The Decimal construct now accepts a float instance directly,
  converting that float to a Decimal of equal value:

  >>> Decimal(1.1)
  Decimal('1.100000000000000088817841970012523233890533447265625')

- collections.Counter() now supports a subtract() method.

- The functools module now has a total_ordering() class decorator to
  simplify the specification of rich comparisons.

- The functools module also adds cmp_to_key() as a tool to transition
  old-style comparison functions to new-style key-functions.

- bpo-8294: The Fraction constructor now accepts Decimal and float instances
  directly.

- bpo-7279: Comparisons involving a Decimal signaling NaN now signal
  InvalidOperation instead of returning False.  (Comparisons involving a
  quiet NaN are unchanged.)  Also, Decimal quiet NaNs are now hashable;
  Decimal signaling NaNs remain unhashable.

- bpo-2531: Comparison operations between floats and Decimal instances now
  return a result based on the numeric values of the operands; previously
  they returned an arbitrary result based on the relative ordering of
  id(float) and id(Decimal).

- bpo-8233: When run as a script, py_compile.py optionally takes a single
  argument `-` which tells it to read files to compile from stdin.  Each
  line is read on demand and the named file is compiled immediately.
  (Original patch by Piotr Ożarowski).

- bpo-3135: Add ``inspect.getcallargs()``, which binds arguments to a
  function like a normal call.

- Backwards incompatible change: Unicode codepoints line tabulation (0x0B)
  and form feed (0x0C) are now considered linebreaks, as specified in
  Unicode Standard Annex #14.  See issue #7643.
  http://www.unicode.org/reports/tr14/

- Comparisons using one of <, <=, >, >= between a complex instance and a
  Fractions instance now raise TypeError instead of returning True/False.
  This makes Fraction <=> complex comparisons consistent with int <=>
  complex, float <=> complex, and complex <=> complex comparisons.

- Addition of ``WeakSet`` to the ``weakref`` module.

- logging: Added LOG_FTP to SysLogHandler and updated documentation.

- bpo-8205: Remove the "Modules" directory from sys.path when Python is
  running from the build directory (POSIX only).

- bpo-7667: Fix doctest failures with non-ASCII paths.

- bpo-7512: shutil.copystat() could raise an OSError when the filesystem
  didn't support chflags() (for example ZFS under FreeBSD).  The error is
  now silenced.

- bpo-7703: ctypes supports both buffer() and memoryview().  The former is
  deprecated.

- bpo-7860: platform.uname now reports the correct 'machine' type when
  Python is running in WOW64 mode on 64 bit Windows.

- logging: Added getChild utility method to Logger and added isEnabledFor
  method to LoggerAdapter.

- bpo-8201: logging: Handle situation of non-ASCII and Unicode logger names
  existing at the same time, causing a Unicode error when configuration code
  attempted to sort the existing loggers.

- bpo-8200: logging: Handle errors when multiprocessing is not fully loaded
  when logging occurs.

- bpo-3890: Fix recv() and recv_into() on non-blocking SSL sockets. Also,
  enable the SSL_MODE_AUTO_RETRY flag on SSL sockets, so that blocking reads
  and writes are always retried by OpenSSL itself. (See also: bpo-8222)

- bpo-8179: Fix macpath.realpath() on a non-existing path.

- bpo-8024: Update the Unicode database to 5.2.

- bpo-8104: socket.recv_into() and socket.recvfrom_into() now support
  writing into objects supporting the new buffer API, for example bytearrays
  or memoryviews.

- bpo-4961: Inconsistent/wrong result of askyesno function in tkMessageBox
  with Tcl/Tk-8.5.

- bpo-8140: Extend compileall to compile single files.  Add -i option.

- bpo-7774: Set sys.executable to an empty string if ``argv[0]`` has been
  set to a non existent program name and Python is unable to retrieve the
  real program name.

- bpo-8117: logging: Improved algorithm for computing initial rollover time
  for ``TimedRotatingFileHandler`` by using the modification time of an
  existing log file to compute the next rollover time.  If the log file does
  not exist, the current time is used as the basis for the computation.

- bpo-6472: The ``xml.etree`` package is updated to ElementTree 1.3.  The
  cElementTree module is updated too.

- bpo-7880: Fix sysconfig when the python executable is a symbolic link.

- bpo-7624: Fix ``isinstance(foo(), collections.Callable)`` for old-style
  classes.

- bpo-7143: email: ``get_payload()`` used to strip any trailing newline from
  a base64 transfer-encoded payload *after* decoding it; it no longer does.
  This is a behavior change, so email's minor version number is now bumped,
  to version 4.0.2, for the 2.7 release.

- bpo-8235: _socket: Add the constant ``SO_SETFIB``.  SO_SETFIB is a socket
  option available on FreeBSD 7.1 and newer.

- bpo-8038: unittest.TestCase.assertNotRegexpMatches

- Addition of -b command line option to unittest for buffering stdout /
  stderr during test runs.

- bpo-1220212: Added os.kill support for Windows, including support for
  sending CTRL+C and CTRL+BREAK events to console subprocesses.

- bpo-8314: Fix unsigned long long bug in libffi on Sparc v8.

- bpo-1039: Fix os.execlp() crash with missing 2nd argument. (See also:
  bpo-8154)

- bpo-8156: bsddb module updated to version 4.8.4.
  http://www.jcea.es/programacion/pybsddb.htm#bsddb3-4.8.4.  This update
  drops support for Berkeley DB 4.0, and adds support for 4.8.

- bpo-3928: os.mknod() now available in Solaris, also.

- bpo-8142: Update libffi to the 3.0.9 release.

- bpo-8300: When passing a non-integer argument to struct.pack with any
  integer format code, struct.pack first attempts to convert the non-integer
  using its __index__ method.  If that method is non-existent or raises
  TypeError it goes on to try the __int__ method, as described below.

- bpo-1530559: When passing a non-integer argument to struct.pack with *any*
  integer format code (one of 'bBhHiIlLqQ'), struct.pack attempts to use the
  argument's __int__ method to convert to an integer before packing.  It
  also produces a DeprecationWarning in this case.  (In Python 2.6, the
  behaviour was inconsistent: __int__ was used for some integer codes but
  not for others, and the set of integer codes for which it was used
  differed between native packing and standard packing.)

- bpo-7347: _winreg: Add CreateKeyEx and DeleteKeyEx, as well as fix a bug
  in the return value of QueryReflectionKey.

Tools/Demos
-----------

- bpo-7993: Add a test of IO packet processing bandwidth to ccbench.  It
  measures the number of UDP packets processed per second depending on the
  number of background CPU-bound Python threads.

- python-config now supports multiple options on the same command line.

Build
-----

- bpo-8032: For gdb7, a python-gdb.py file is added to the build, allowing
  to use advanced gdb features when debugging Python.

- bpo-1628484: The Makefile doesn't ignore the CFLAGS environment variable
  anymore.  It also forwards the LDFLAGS settings to the linker when
  building a shared library.

- bpo-6716: Quote -x arguments of compileall in MSI installer.

- bpo-7705: Fix linking on FreeBSD.

- Make sure that the FreeBSD build of the included libffi uses the proper
  assembly file.

C API
-----

- bpo-8276: PyEval_CallObject() is now only available in macro form.  The
  function declaration, which was kept for backwards compatibility reasons,
  is now removed (the macro was introduced in 1997!).

- bpo-7992: A replacement PyCObject API, PyCapsule, has been backported from
  Python 3.1. All existing Python CObjects in the main distribution have
  been converted to capsules.  To address backwards-compatibility concerns,
  PyCObject_AsVoidPtr() was changed to understand capsules.

Tests
-----

- bpo-3864: Skip three test_signal tests on freebsd6 because they fail if
  any thread was previously started, most likely due to a platform bug.

- bpo-8348: Fix test ftp url in test_urllib2net.

- bpo-8204: Fix test_ttk notebook test by forcing focus.

- bpo-8344: Fix test_ttk bug on FreeBSD.

- bpo-8193: Fix test_zlib failure with zlib 1.2.4.

- bpo-8248: Add some tests for the bool type.  Patch by Gregory Nofi.

- bpo-8263: Now regrtest.py will report a failure if it receives a
  KeyboardInterrupt (SIGINT).

- bpo-8180: Fix test_pep277 on OS X and add more tests for special Unicode
  normalization cases. (See also: bpo-8207)

- bpo-7783: test.test_support.open_urlresource invalidates the outdated
  files from the local cache.


What's New in Python 2.7 alpha 4?
=================================

*Release date: 2010-03-06*

Core and Builtins
-----------------

- bpo-7544: Preallocate thread memory before creating the thread to avoid a
  fatal error in low memory condition.

- bpo-7820: The parser tokenizer restores all bytes in the right if the BOM
  check fails.

- bpo-7309: Fix unchecked attribute access when converting
  UnicodeEncodeError, UnicodeDecodeError, and UnicodeTranslateError to
  strings.

- bpo-7649: "u'%c' % char" now behaves like "u'%s' % char" and raises a
  UnicodeDecodeError if 'char' is a byte string that can't be decoded using
  the default encoding.

- bpo-6902: Fix problem with built-in types format incorrectly with 0
  padding.

- bpo-2560: Remove an unnecessary 'for' loop from ``my_fgets()`` in
  Parser/myreadline.c.

- bpo-7988: Fix default alignment to be right aligned for
  ``complex.__format__``.  Now it matches other numeric types.

- bpo-5211: The complex type no longer uses implicit coercion in mixed-type
  binary arithmetic operations.

Library
-------

- bpo-7904: Changes to urllib.parse.urlsplit to handle schemes as defined by
  RFC3986. Anything before :// is considered a scheme and is followed by an
  authority (or netloc) and by '/' led path, which is optional.

- bpo-1555570: email no longer inserts extra blank lines when a \r\n combo
  crosses an 8192 byte boundary.

- bpo-6906: Tk should not set Unicode environment variables on Windows.

- bpo-1054943: Fix ``unicodedata.normalize('NFC', text)`` for the Public
  Review Issue #29 (http://unicode.org/review/pr-29.html).

- bpo-7494: Fix a crash in ``_lsprof`` (cProfile) after clearing the
  profiler, reset also the pointer to the current pointer context.

- bpo-7232: Add support for the context management protocol to the
  ``tarfile.TarFile`` class.

- bpo-7250: Fix info leak of os.environ across multi-run uses of
  ``wsgiref.handlers.CGIHandler``.

- bpo-1729305: Fix doctest to handle encode error with "backslashreplace".

- bpo-691291: ``codecs.open()`` should not convert end of lines on reading
  and writing.

- bpo-7975: Correct regression in dict methods supported by bsddb.dbshelve.

- bpo-7959: ctypes callback functions are now registered correctly with the
  cycle garbage collector.

- bpo-7970: ``email.Generator.flatten`` now correctly flattens
  message/rfc822 messages parsed by ``email.Parser.HeaderParser``.

- bpo-3426: ``os.path.abspath`` now returns unicode when its arg is unicode.

- bpo-7633: In the decimal module, ``Context`` class methods (with the
  exception of canonical and is_canonical) now accept instances of int and
  long wherever a Decimal instance is accepted, and implicitly convert that
  argument to Decimal.  Previously only some arguments were converted.

- bpo-6003: Add an argument to ``zipfile.Zipfile.writestr`` to specify the
  compression type.

- bpo-7893: ``unittest.TextTestResult`` is made public and a ``resultclass``
  argument added to the TextTestRunner constructor allowing a different
  result class to be used without having to subclass.

- bpo-7588: ``unittest.TextTestResult.getDescription`` now includes the test
  name in failure reports even if the test has a docstring.

- bpo-5801: Remove spurious empty lines in wsgiref.

- bpo-1537721: Add a ``writeheader()`` method to ``csv.DictWriter``.

- bpo-7427: Improve the representation of httplib.BadStatusLine exceptions.

- bpo-7481: When a ``threading.Thread`` failed to start it would leave the
  instance stuck in initial state and present in ``threading.enumerate()``.

- bpo-1068268: The subprocess module now handles EINTR in internal
  ``os.waitpid()`` and ``os.read()`` system calls where appropriate.

- bpo-6729: Add ``ctypes.c_ssize_t`` to represent ssize_t.

- bpo-6247: The argparse module has been added to the standard library.

- The sqlite3 module was updated to pysqlite 2.6.0.  This fixes several
  obscure bugs and allows loading SQLite extensions from shared libraries.

- bpo-7808: Fix reference leaks in _bsddb and related tests.

- bpo-6544: Fix a reference leak in the kqueue implementation's error
  handling.

- Stop providing crtassem.h symbols when compiling with Visual Studio 2010,
  as msvcr100.dll is not a platform assembly anymore.

- bpo-7242: On Solaris 9 and earlier calling ``os.fork()`` from within a
  thread could raise an incorrect RuntimeError about not holding the import
  lock.  The import lock is now reinitialized after fork.

- bpo-7999: ``os.setreuid()`` and ``os.setregid()`` would refuse to accept a
  -1 parameter on some platforms such as OS X.

Tests
-----

- bpo-7849: The utility ``test.test_support.check_warnings()`` verifies if
  warnings are effectively raised.  A new utility ``check_py3k_warnings()``
  is available.

- The four path modules (genericpath, macpath, ntpath, posixpath) share a
  common TestCase for some tests: test_genericpath.CommonTest.

- Print platform information when running the whole test suite, or using the
  ``--verbose`` flag.

- bpo-767675: Enable test_pep277 on POSIX platforms with Unicode-friendly
  filesystem encoding.

- bpo-6292: For the moment at least, the test suite runs cleanly if python
  is run with the -OO flag.  Tests requiring docstrings are skipped.

- bpo-7712: test_support gained a new ``temp_cwd`` context manager which is
  now also used by regrtest to run all the tests in a temporary directory.
  The original CWD is saved in ``test.test_support.SAVEDCWD``.  Thanks to
  Florent Xicluna who helped with the patch.

Build
-----

- bpo-3920: Define _BSD_SOURCE on OpenBSD 4.4 through 4.9. (See also:
  bpo-7903)


What's New in Python 2.7 alpha 3?
=================================

*Release date: 2010-02-06*

Core and Builtins
-----------------

- bpo-5677: Explicitly forbid write operations on read-only file objects,
  and read operations on write-only file objects.  On Windows, the system C
  library would return a bogus result; on Solaris, it was possible to crash
  the interpreter.  Patch by Stefan Krah.

- bpo-7853: Normalize exceptions before they are passed to a context
  manager's ``__exit__()`` method.

- bpo-7385: Fix a crash in ``PyMemoryView_FromObject()`` when
  ``PyObject_GetBuffer()`` fails.  Patch by Florent Xicluna.

- bpo-7819: Check ``sys.call_tracing()`` arguments types.

- bpo-7788: Fix an interpreter crash produced by deleting a list slice with
  very large step value.

- bpo-7766: Change ``sys.getwindowsversion()`` return value to a named tuple
  and add the additional members returned in an OSVERSIONINFOEX structure.
  The new members are service_pack_major, service_pack_minor, suite_mask,
  and product_type.

- bpo-7561: Operations on empty bytearrays (such as ``int(bytearray())``)
  could crash in many places because of the ``PyByteArray_AS_STRING()``
  macro returning NULL. The macro now returns a statically allocated empty
  string instead.

- bpo-7622: Improve the split(), rsplit(), splitlines() and replace()
  methods of bytes, bytearray and unicode objects by using a common
  implementation based on stringlib's fast search.  Patch by Florent
  Xicluna.

- bpo-7632: Fix various str -> float conversion bugs present in 2.7 alpha 2,
  including:

  (1) a serious 'wrong output' bug that could occur for long (> 40 digit)
  input     strings, (2) a crash in dtoa.c that occurred in debug builds
  when parsing certain long     numeric strings corresponding to subnormal
  values, (3) a memory leak for some values large enough to cause overflow,
  and (4) a number of flaws that could lead to incorrectly rounded results.

- bpo-7319: Silence ``DeprecationWarning`` by default when the -3 option is
  not used. (See also: bpo-7770)

- bpo-2335: Backport set literals syntax from Python 3.x.

- bpo-2333: Backport set and dict comprehensions syntax from Python 3.x.

- bpo-1967: Backport dictionary views from Python 3.x.

Library
-------

- bpo-9137: Fix issue in MutableMapping.update, which incorrectly treated
  keyword arguments called 'self' or 'other' specially.

- bpo-7835: shelve should no longer produce mysterious warnings during
  interpreter shutdown.

- bpo-2746: Don't escape ampersands and angle brackets ("&", "<", ">") in
  XML processing instructions and comments.  These raw characters are
  allowed by the XML specification, and are necessary when outputting e.g.
  PHP code in a processing instruction.  Patch by Neil Muller.

- bpo-7869: logging: Improved diagnostic for format-time errors.

- bpo-7868: logging: Added loggerClass attribute to Manager.

- bpo-7851: logging: Clarification on logging configuration files.

- bpo-4772: Raise a ValueError when an unknown Bluetooth protocol is
  specified, rather than fall through to AF_PACKET (in the ``socket``
  module). Also, raise ValueError rather than TypeError when an unknown TIPC
  address type is specified.  Patch by Brian Curtin.

- logging: Implemented PEP 391.

- bpo-6939: Fix file I/O objects in the `io` module to keep the original
  file position when calling `truncate()`.  It would previously change the
  file position to the given argument, which goes against the tradition of
  ftruncate() and other truncation APIs.  Patch by Pascal Chambon.

- bpo-7610: Reworked implementation of the internal ``zipfile.ZipExtFile``
  class used to represent files stored inside an archive.  The new
  implementation is significantly faster and can be wrapped in an
  ``io.BufferedReader`` object for more speedups.  It also solves an issue
  where interleaved calls to ``read()`` and ``readline()`` give wrong
  results. Patch by Nir Aides.

- bpo-7792: Registering non-classes to ABCs raised an obscure error.

- Removed the deprecated functions ``verify()`` and ``vereq()`` from
  Lib/test/test_support.py.

- bpo-7773: Fix an UnboundLocalError in ``platform.linux_distribution()``
  when the release file is empty.

- bpo-7748: Since unicode values are supported for some metadata options in
  Distutils, the DistributionMetadata get_* methods will now return a utf-8
  encoded string for them.  This ensures that the upload and register
  commands send the correct values to PyPI without any error.

- bpo-1670765: Prevent ``email.generator.Generator`` from re-wrapping
  headers in multipart/signed MIME parts, which fixes one of the sources of
  invalid modifications to such parts by Generator.

- bpo-7701: Fix crash in ``binascii.b2a_uu()`` in debug mode when given a
  1-byte argument.  Patch by Victor Stinner.

- bpo-3299: Fix possible crash in the _sre module when given bad argument
  values in debug mode.  Patch by Victor Stinner.

- bpo-7703: Add support for the new buffer API to functions of the binascii
  module. Backported from py3k by Florent Xicluna, with some additional
  tests.

- bpo-2846: Add support for gzip.GzipFile reading zero-padded files.  Patch
  by Brian Curtin.

- bpo-5827: Make sure that normpath preserves unicode.  Initial patch by
  Matt Giuca.

- bpo-5372: Drop the reuse of .o files in Distutils' ccompiler (since
  Extension extra options may change the output without changing the .c
  file). Initial patch by Collin Winter.

- Expat: Fix DoS via XML document with malformed UTF-8 sequences
  (CVE_2009_3560).

Build
-----

- bpo-7632: When Py_USING_MEMORY_DEBUGGER is defined, disable the private
  memory allocation scheme in dtoa.c and use PyMem_Malloc and PyMem_Free
  instead. Also disable caching of powers of 5.

- bpo-7658: Ensure that the new pythonw executable works on OSX 10.4

- bpo-7714: Use ``gcc -dumpversion`` to detect the version of GCC on MacOSX.

- bpo-7661: Allow ctypes to be built from a non-ASCII directory path. Patch
  by Florent Xicluna.

Tools/Demos
-----------

- iobench (a file I/O benchmark) and ccbench (a concurrency benchmark) were
  added to the ``Tools`` directory.  They were previously living in the
  sandbox.

Tests
-----

- bpo-7728: test_timeout was changed to use ``test_support.bind_port()``
  instead of a hard coded port.

Documentation
-------------

- Updated "Using Python" documentation to include description of CPython's
  -J, -U and -X options.

- Updated Python manual page (options -B, -O0, -s, environment variables
  PYTHONDONTWRITEBYTECODE, PYTHONNOUSERSITE).


What's New in Python 2.7 alpha 2?
=================================

*Release date: 2010-01-09*

Core and Builtins
-----------------

- The ``__complex__()`` method is now looked up on the class of instances to
  make it consistent with other special methods.

- bpo-7462: Implement the stringlib fast search algorithm for the `rfind`,
  `rindex`, `rsplit` and `rpartition` methods.  Patch by Florent Xicluna.

- bpo-5080: A number of functions and methods previously produced a
  DeprecationWarning when passed a float argument where an integer was
  expected. These functions and methods now raise TypeError instead.  The
  majority of the effects of this change are in the extension modules, but
  some core functions and methods are affected: notably the 'chr', 'range'
  and 'xrange' builtins, and many unicode/str methods.

- bpo-7604: Deleting an unset slotted attribute did not raise an
  AttributeError.

- bpo-7534: Fix handling of IEEE specials (infinities, nans, negative zero)
  in ** operator.  The behaviour now conforms to that described in C99 Annex
  F.

- bpo-7579: The msvcrt module now has docstrings for all its functions.

- bpo-7413: Passing '\0' as the separator to datetime.datetime.isoformat()
  used to drop the time part of the result.

- bpo-1811: Improve accuracy and cross-platform consistency for true
  division of integers: the result of a/b is now correctly rounded for ints
  a and b (at least on IEEE 754 platforms), and in particular does not
  depend on the internal representation of a long.

- bpo-6108: ``unicode(exception)`` and ``str(exception)`` should return the
  same message when only ``__str__()`` (and not ``__unicode__()``) is
  overridden in the subclass.

- bpo-6834: Replace the implementation for the 'python' and 'pythonw'
  executables on OSX.

  These executables now work properly with the arch(1) command: ``arch -ppc
  python`` will start a universal binary version of python in PPC mode
  (unlike previous releases).

- bpo-1680159: Unicode coercion during an 'in' operation no longer masks the
  underlying error when the coercion fails for the left hand operand.

- bpo-7491: Metaclass's __cmp__ method was ignored.

- bpo-7466: Segmentation fault when the garbage collector is called in the
  middle of populating a tuple.  Patch by Florent Xicluna.

Library
-------

- bpo-6963: Added "maxtasksperchild" argument to ``multiprocessing.Pool``,
  allowing for a maximum number of tasks within the pool to be completed by
  the worker before that worker is terminated, and a new one created to
  replace it.

- bpo-7617: Make sure distutils.unixccompiler.UnixCCompiler recognizes gcc
  when it has a fully qualified configuration prefix.  Initial patch by
  Arfrever.

- bpo-7092: Remove py3k warning when importing cPickle.  2to3 handles
  renaming of `cPickle` to `pickle`.  The warning was annoying since there's
  no alternative to cPickle if you care about performance.  Patch by Florent
  Xicluna.

- bpo-7455: Fix possible crash in cPickle on invalid input.  Patch by Victor
  Stinner.

- bpo-7092: Fix the DeprecationWarnings emitted by the standard library when
  using the -3 flag.  Patch by Florent Xicluna.

- bpo-7471: Improve the performance of GzipFile's buffering mechanism, and
  make it implement the ``io.BufferedIOBase`` ABC to allow for further
  speedups by wrapping it in an ``io.BufferedReader``.  Patch by Nir Aides.

- bpo-3972: ``httplib.HTTPConnection`` now accepts an optional
  source_address parameter to allow specifying where your connections come
  from.

- ``socket.create_connection()`` now accepts an optional source_address
  parameter.

- bpo-5511: ``zipfile.ZipFile`` can now be used as a context manager.
  Initial patch by Brian Curtin.

- Distutils now correctly identifies the build architecture as "x86_64" when
  building on OSX 10.6 without "-arch" flags.

- bpo-7556: Distutils' msvc9compiler now opens the MSVC Manifest file in
  text mode.

- bpo-7552: Removed line feed in the base64 Authorization header in the
  Distutils upload command to avoid an error when PyPI reads it.  This
  occurs on long passwords.  Initial patch by JP St. Pierre.

- bpo-7231: urllib2 cannot handle https with proxy requiring auth.  Patch by
  Tatsuhiro Tsujikawa.

- bpo-7349: Make methods of file objects in the io module accept None as an
  argument where file-like objects (ie StringIO and BytesIO) accept them to
  mean the same as passing no argument.

- bpo-7348: ``StringIO.StringIO.readline(-1)`` now acts as if it got no
  argument like other file objects.

- bpo-7357: tarfile no longer suppresses fatal extraction errors by default.

- bpo-7470: logging: Fix bug in Unicode encoding fallback.

- bpo-5949: Fixed IMAP4_SSL hang when the IMAP server response is missing
  proper end-of-line termination.

- bpo-7457: Added a read_pkg_file method to
  ``distutils.dist.DistributionMetadata``.

- bpo-3745: Undo the 2.7a1 change to have hashlib to reject unicode and non
  buffer API supporting objects as input.  That behavior is for 3.x only.

C API
-----

- bpo-7767: New function ``PyLong_AsLongLongAndOverflow()`` added, analogous
  to ``PyLong_AsLongAndOverflow()``.

- bpo-5080: The argument parsing functions ``PyArg_ParseTuple()``,
  ``PyArg_ParseTupleAndKeywords()``, ``PyArg_VaParse()``,
  ``PyArg_VaParseTupleAndKeywords()`` and ``PyArg_Parse()`` no longer accept
  float arguments for integer format codes (other than 'L'): previously an
  attempt to pass a float resulted in a DeprecationWarning; now it gives a
  TypeError.  For the 'L' format code (which previously had no warning)
  there is now a DeprecationWarning.

- bpo-7033: Function ``PyErr_NewExceptionWithDoc()`` added.

Build
-----

- bpo-6491: Allow --with-dbmliborder to specify that no dbms will be built.

- bpo-6943: Use pkg-config to find the libffi headers when the
  ``--with-system-ffi`` flag is used.

- bpo-7609: Add a ``--with-system-expat`` option that causes the system's
  expat library to be used for the pyexpat module instead of the one
  included with Python.

- bpo-7589: Only build the nis module when the correct header files are
  found.

- Switch to OpenSSL 0.9.8l and sqlite 3.6.21 on Windows.

- bpo-7541: when using ``python-config`` with a framework install the
  compiler might use the wrong library.

Tests
-----

- bpo-7376: Instead of running a self-test (which was failing) when called
  with no arguments, doctest.py now gives a usage message.

- bpo-7396: Fix regrtest -s, which was broken by the -j enhancement.

- bpo-7498: test_multiprocessing now uses test_support.find_unused_port
  instead of a hardcoded port number in test_rapid_restart.


What's New in Python 2.7 alpha 1?
=================================

*Release date: 2009-12-05*

Core and Builtins
-----------------

- bpo-7419: ``locale.setlocale()`` could crash the interpreter on Windows
  when called with invalid values.

- bpo-3382: 'F' formatting for float and complex now convert the result to
  upper case. This only affects 'inf' and 'nan', since 'f' no longer
  converts to 'g' for large values.

- Remove switch from "%f" formatting to "%g" formatting for floats larger
  than 1e50 in absolute value.

- Remove restrictions on precision when formatting floats.  E.g., "%.120g" %
  1e-100 used to raise OverflowError, but now gives the requested 120
  significant digits instead.

- Add Py3k warnings for parameter names in parentheses.

- bpo-7362: Give a proper error message for ``def f((x)=3): pass``.

- bpo-7085: Fix crash when importing some extensions in a thread on MacOSX
  10.6.

- bpo-7117: ``repr(x)`` for a float x returns a result based on the shortest
  decimal string that's guaranteed to round back to x under correct rounding
  (with round-half-to-even rounding mode).  Previously it gave a string
  based on rounding x to 17 decimal digits.  repr(x) for a complex number
  behaves similarly.  On platforms where the correctly-rounded strtod and
  dtoa code is not supported (see below), repr is unchanged.

- bpo-7117: On almost all platforms: float-to-string and string-to-float
  conversions within Python are now correctly rounded.  Places these
  conversions occur include: str for floats and complex numbers; the float
  and complex constructors; old-style and new-style numeric formatting;
  serialization and deserialization of floats and complex numbers using
  marshal, pickle and json; parsing of float and imaginary literals in
  Python code; Decimal-to-float conversion.

  The conversions use a Python-adapted version of David Gay's well-known
  dtoa.c, providing correctly-rounded strtod and dtoa C functions.  This
  code is supported on Windows, and on Unix-like platforms using gcc, icc or
  suncc as the C compiler.  There may be a small number of platforms on
  which correct operation of this code cannot be guaranteed, so the code is
  not used: notably, this applies to platforms where the C double format is
  not IEEE 754 binary64, and to platforms on x86 hardware where the x87 FPU
  is set to 64-bit precision and Python's configure script is unable to
  determine how to change the FPU precision.  On these platforms conversions
  use the platform strtod and dtoa, as before.

- bpo-7117: Backport round implementation from Python 3.x.  ``round()`` now
  uses the correctly-rounded string <-> float conversions described above
  (when available), and so produces correctly rounded results that will
  display nicely under the float repr.  There are two related small changes:
  (1) round now accepts any class with an ``__index__()`` method for its
  second argument (but no longer accepts floats for the second argument),
  and (2) an excessively large second integer argument (e.g., ``round(1.234,
  10**100)``) no longer raises an exception.

- bpo-1757126: Fix the cyrillic-asian alias for the ptcp154 encoding.

- Fix several issues with ``compile()``.  The input can now contain Windows
  and Mac newlines and is no longer required to end in a newline.

- Remove length limitation when constructing a complex number from a unicode
  string.

- bpo-7244: ``itertools.izip_longest()`` no longer ignores exceptions raised
  during the formation of an output tuple.

- bpo-1087418: Boost performance of bitwise operations for longs.

- bpo-1722344: ``threading._shutdown()`` is now called in ``Py_Finalize()``,
  which fixes the problem of some exceptions being thrown at shutdown when
  the interpreter is killed.  Patch by Adam Olsen.

- bpo-7168: Document ``PyFloat_AsString()`` and ``PyFloat_AsReprString()``,
  and note that they are unsafe and deprecated.

- bpo-7120: logging: Remove import of multiprocessing which is causing crash
  in GAE.

- bpo-7140: The ``__dict__`` of a module should not be cleared unless the
  module is the only object holding a reference to it.

- bpo-1754094: Improve the stack depth calculation in the compiler.  There
  should be no other effect than a small decrease in memory use.  Patch by
  Christopher Tur Lesniewski-Laas.

- bpo-7084: Fix a (very unlikely) crash when printing a list from one
  thread, and mutating it from another one.  Patch by Scott Dial.

- bpo-1571184: The Unicode database contains properties for more characters.
  The tables for code points representing numeric values, white spaces or
  line breaks are now generated from the official Unicode Character Database
  files, and include information from the Unihan.txt file.

- bpo-7050: Fix a SystemError when trying to use unpacking and augmented
  assignment.

- bpo-5329: Fix ``os.popen*`` regression from 2.5 with commands as a
  sequence running through the shell.  Patch by Jean-Paul Calderone and Jani
  Hakala.

- bpo-7019: Raise ValueError when unmarshalling bad long data, instead of
  producing internally inconsistent Python longs.

- bpo-6990: Fix ``threading.local`` subclasses leaving old state around
  after a reference cycle GC which could be recycled by new locals.

- bpo-6300: unicode.encode, unicode.decode, str.decode, and str.encode now
  take keyword arguments.

- bpo-6922: Fix an infinite loop when trying to decode an invalid UTF-32
  stream with a non-raising error handler like "replace" or "ignore".

- bpo-6713: Improve performance of base 10 int -> string and long -> string
  conversions.

- bpo-1590864: Fix potential deadlock when mixing threads and fork().

- bpo-6844: Do not emit DeprecationWarnings when accessing a "message"
  attribute on exceptions that was set explicitly.

- bpo-6846: Fix bug where bytearray.pop() returns negative integers.

- ``classmethod()`` no longer checks if its argument is callable.

- bpo-6750: A text file opened with ``io.open()`` could duplicate its output
  when writing from multiple threads at the same time.

- bpo-6704: Improve the col_offset in AST for "for" statements with a target
  of tuple unpacking.

- bpo-6707: ``dir()`` on an uninitialized module caused a crash.

- bpo-6540: Fixed crash for ``bytearray.translate()`` with invalid
  parameters.

- bpo-6573: ``set.union()`` stopped processing inputs if an instance of self
  occurred in the argument chain.

- bpo-1616979: Added the cp720 (Arabic DOS) encoding.

- bpo-6070: On posix platforms import no longer copies the execute bit from
  the .py file to the .pyc file if it is set.  Patch by Marco N.

- bpo-4618: When unicode arguments are passed to ``print()``, the default
  separator and end should be unicode also.

- bpo-6119: Fixed an incorrect Py3k warning about order comparisons of
  built-in functions and methods.

- bpo-6347: Include inttypes.h as well as stdint.h in pyport.h.  This fixes
  a build failure on HP-UX: int32_t and uint32_t are defined in inttypes.h
  instead of stdint.h on that platform.

- bpo-4856: Remove checks for win NT.

- bpo-2016: Fixed a crash in a corner case where the dictionary of keyword
  arguments could be modified during the function call setup.

- Removed the ipaddr module.

- bpo-6329: Fixed iteration for memoryview objects (it was being blocked
  because it wasn't recognized as a sequence).

- bpo-6289: Encoding errors from ``compile()`` were being masked.

- When no module is given in a relative import, the module field of the
  ImportFrom AST node is now None instead of an empty string.

- Assignment to None using import statements now raises a SyntaxError.

- bpo-4547: When debugging a very large function, it was not always possible
  to update the lineno attribute of the current frame.

- bpo-5330: C functions called with keyword arguments were not reported by
  the various profiling modules (profile, cProfile).  Patch by Hagen
  Fürstenau.

- bpo-5982: staticmethod and classmethod now expose the wrapped function
  with ``__func__``.

- Added support for multiple context managers in the same with-statement.
  Deprecated ``contextlib.nested()`` which is no longer needed.

- bpo-6101: A new opcode, SETUP_WITH, has been added to speed up the with
  statement and correctly lookup the __enter__ and __exit__ special methods.

- bpo-5829: complex("1e500") no longer raises OverflowError.  This makes it
  consistent with float("1e500") and interpretation of real and imaginary
  literals.

- bpo-3527: Removed Py_WIN_WIDE_FILENAMES which is not used any more.

- ``__instancecheck__()`` and ``__subclasscheck__()`` are now completely
  ignored on classic classes and instances.

- bpo-5994: The marshal module now has docstrings.

- bpo-5981: Fix three minor inf/nan issues in float.fromhex:

  (1) inf and nan strings with trailing whitespace were incorrectly
  rejected; (2) parsing of strings representing infinities and nans was
  locale aware; and (3) the interpretation of fromhex('-nan') didn't match
  that of float('-nan').

- bpo-5920: For ``float.__format__()``, change the behavior with the empty
  presentation type (that is, not one of 'e', 'f', 'g', or 'n') to be like
  'g' but with at least one decimal point and with a default precision of
  12. Previously, the behavior the same but with a default precision of 6.
  This more closely matches ``str()``, and reduces surprises when adding
  alignment flags to the empty presentation type. This also affects the new
  complex.__format__ in the same way.

- bpo-5890: In subclasses of 'property' the __doc__ attribute was shadowed
  by classtype's, even if it was None.  property now inserts the __doc__
  into the subclass instance __dict__.

- bpo-4426: The UTF-7 decoder was too strict and didn't accept some legal
  sequences. Patch by Nick Barnes and Victor Stinner.

- bpo-1588: Add complex.__format__. For example, ``format(complex(1, 2./3),
  '.5')`` now produces a sensible result.

- bpo-5864: Fix empty format code formatting for floats so that it never
  gives more than the requested number of significant digits.

- bpo-5793: Rationalize isdigit / isalpha / tolower, etc. Includes new
  Py_ISDIGIT / Py_ISALPHA / Py_TOLOWER, etc. in pctypes.h.

- bpo-4971: Fix titlecase for characters that are their own titlecase, but
  not their own uppercase.

- bpo-5835: Deprecate PyOS_ascii_formatd and replace it with
  _PyOS_double_to_string or PyOS_double_to_string.

- bpo-5283: Setting __class__ in __del__ caused a segfault.

- bpo-5816: ``complex(repr(z))`` now recovers z exactly, even when z
  involves nans, infs or negative zeros.

- Implement PEP 378, Format Specifier for Thousands Separator, for floats,
  ints, and longs.

- bpo-5515: 'n' formatting for ints, longs, and floats handles leading zero
  formatting poorly.

- bpo-5772: For float.__format__, don't add a trailing ".0" if we're using
  no type code and we have an exponent.

- bpo-3166: Make long -> float (and int -> float) conversions correctly
  rounded.

- bpo-5787: ``object.__getattribute__(some_type, "__bases__")`` segfaulted
  on some built-in types.

- bpo-1869: Fix a couple of minor round() issues.  ``round(5e15+1)`` was
  giving 5e15+2; ``round(-0.0)`` was losing the sign of the zero.

- bpo-5759: float() didn't call __float__ on str subclasses.

- bpo-5704: The "-3" command-line option now implies "-t".

- bpo-2170: Refactored ``xml.dom.minidom.normalize``, increasing both its
  clarity and its speed.

- bpo-2396: The memoryview object was backported from Python 3.1.

- Fix a problem in PyErr_NormalizeException that leads to "undetected
  errors" when hitting the recursion limit under certain circumstances.

- bpo-1665206: Remove the last eager import in _warnings.c and make it lazy.

- bpo-4865: On MacOSX /Library/Python/2.7/site-packages is added to the end
  sys.path, for compatibility with the system install of Python.

- bpo-4688: Add a heuristic so that tuples and dicts containing only
  untrackable objects are not tracked by the garbage collector. This can
  reduce the size of collections and therefore the garbage collection
  overhead on long-running programs, depending on their particular use of
  datatypes.

- bpo-5512: Rewrite PyLong long division algorithm (x_divrem) to improve its
  performance.  Long divisions and remainder operations are now between 50%
  and 150% faster.

- bpo-4258: Make it possible to use base 2**30 instead of base 2**15 for the
  internal representation of integers, for performance reasons.  Base 2**30
  is enabled by default on 64-bit machines.  Add --enable-big-digits option
  to configure, which overrides the default.  Add sys.long_info structseq to
  provide information about the internal format.

- bpo-4034: Fix weird attribute error messages of the traceback object. (As
  a result traceback.__members__ no longer exists.)

- bpo-4474: PyUnicode_FromWideChar now converts characters outside the BMP
  to surrogate pairs, on systems with sizeof(wchar_t) == 4 and
  sizeof(Py_UNICODE) == 2.

- bpo-5237: Allow auto-numbered fields in str.format(). For example: ``'{}
  {}'.format(1, 2) == '1 2'``.

- bpo-3652: Make the 'line' argument for ``warnings.showwarning()`` a
  requirement. Means the DeprecationWarning from Python 2.6 can go away.

- bpo-5247: Improve error message when unknown format codes are used when
  using ``str.format()`` with str, unicode, long, int, and float arguments.

- Running Python with the -3 option now also warns about classic division
  for ints and longs.

- bpo-5260: Long integers now consume less memory: average saving is 2 bytes
  per long on a 32-bit system and 6 bytes per long on a 64-bit system.

- bpo-5186: Reduce hash collisions for objects with no __hash__ method by
  rotating the object pointer by 4 bits to the right.

- bpo-4575: Fix Py_IS_INFINITY macro to work correctly on x87 FPUs: it now
  forces its argument to double before testing for infinity.

- bpo-4978: Passing keyword arguments as unicode strings is now allowed.

- bpo-1242657: the __len__() and __length_hint__() calls in several tools
  were suppressing all exceptions.  These include list(), filter(), map(),
  zip(), and bytearray().

- os.ftruncate raises OSErrors instead of IOErrors for consistency with
  other os functions.

- bpo-4991: Passing invalid file descriptors to io.FileIO now raises an
  OSError.

- bpo-4807: Port the _winreg module to Windows CE.

- bpo-4935: The overflow checking code in the expandtabs() method common to
  str, bytes and bytearray could be optimized away by the compiler, letting
  the interpreter segfault instead of raising an error.

- bpo-3720: Fix a crash when an iterator modifies its class and removes its
  __next__ method.

- bpo-4893: Use NT threading on CE.

- bpo-4915: Port sysmodule to Windows CE.

- bpo-4074: Change the criteria for doing a full garbage collection (i.e.
  collecting the oldest generation) so that allocating lots of objects
  without destroying them does not show quadratic performance. Based on a
  proposal by Martin von Löwis at
  http://mail.python.org/pipermail/python-dev/2008-June/080579.html.

- bpo-4850: Change COUNT_ALLOCS variables to Py_ssize_t.

- bpo-1180193: When importing a module from a .pyc (or .pyo) file with an
  existing .py counterpart, override the co_filename attributes of all code
  objects if the original filename is obsolete (which can happen if the file
  has been renamed, moved, or if it is accessed through different paths).
  Patch by Ziga Seilnacht and Jean-Paul Calderone.

- bpo-4075: Use ``OutputDebugStringW()`` in Py_FatalError.

- bpo-4797: IOError.filename was not set when _fileio.FileIO failed to open
  file with `str' filename on Windows.

- bpo-3680: Reference cycles created through a dict, set or deque iterator
  did not get collected.

- bpo-4701: PyObject_Hash now implicitly calls PyType_Ready on types where
  the tp_hash and tp_dict slots are both NULL.

- bpo-4764: With io.open, IOError.filename is set when trying to open a
  directory on POSIX systems.

- bpo-4764: IOError.filename is set when trying to open a directory on POSIX
  systems.

- bpo-4759: None is now allowed as the first argument of
  ``bytearray.translate()``.  It was always allowed for
  ``bytes.translate()``.

- Added test case to ensure attempts to read from a file opened for writing
  fail.

- bpo-2467: gc.DEBUG_STATS reported invalid elapsed times. Also, always
  print elapsed times, not only when some objects are
  uncollectable/unreachable. Original patch by Neil Schemenauer.

- bpo-3439: Add a bit_length method to int and long.

- bpo-2183: Simplify and optimize bytecode for list comprehensions.
  Original patch by Neal Norwitz.

- bpo-4597: Fixed exception handling when the __exit__ function of a context
  manager returns a value that cannot be converted to a bool.

- bpo-4597: Fixed several opcodes that weren't always propagating
  exceptions.

- bpo-4445: Replace ``sizeof(PyStringObject)`` with
  ``offsetof(PyStringObject, ob_sval) + 1`` when allocating memory for str
  instances.  On a typical machine this saves 3 bytes of memory (on average)
  per string allocation.

- bpo-3996: On Windows, the PyOS_CheckStack function would cause the
  interpreter to abort ("Fatal Python error: Could not reset the stack!")
  instead of throwing a MemoryError.

- bpo-3689: The list reversed iterator now supports __length_hint__ instead
  of __len__. Behavior now matches other reversed iterators.

- bpo-4367: Python would segfault during compiling when the unicodedata
  module couldn't be imported and \N escapes were present.

- bpo-4233: Changed semantic of ``_fileio.FileIO``'s ``close()`` method on
  file objects with closefd=False. The file descriptor is still kept open
  but the file object behaves like a closed file. The ``FileIO`` object also
  got a new readonly attribute ``closefd``.

- bpo-4348: Some bytearray methods returned that didn't cause any change to
  the bytearray, returned the same bytearray instead of a copy.

- bpo-4317: Fixed a crash in the ``imageop.rgb2rgb8()`` function.

- bpo-4230: If ``__getattr__`` is a descriptor, it now functions correctly.

- bpo-4048: The parser module now correctly validates relative imports.

- bpo-4225: ``from __future__ import unicode_literals`` didn't work in an
  exec statement.

- bpo-4176: Fixed a crash when pickling an object which ``__reduce__``
  method does not return iterators for the 4th and 5th items.

- bpo-4209: Enabling unicode_literals and the print_function in the same
  __future__ import didn't work.

- Using ``nonlocal`` as a variable name will now raise a Py3k SyntaxWarning
  because it is a reserved word in 3.x.

- On windows, ``os.chdir()`` given unicode was not working if
  GetCurrentDirectoryW returned a path longer than MAX_PATH. (But It's
  doubtful this code path is really executed because I cannot move to such
  directory on win2k)

- bpo-4069: When ``set.remove(element)`` is used with a set element, the
  element is temporarily replaced with an equivalent frozenset.  But the
  eventual KeyError would always report the empty ``frozenset()`` as the
  missing key. Now it correctly refers to the initial element.

- bpo-4509: Various issues surrounding resize of bytearray objects to which
  there are buffer exports.

- bpo-4748: Lambda generators no longer return a value.

- bpo-3582: Use native TLS functions on Windows

- The re.sub(), re.subn() and re.split() functions now accept a flags
  parameter.

- bpo-3845: In PyRun_SimpleFileExFlags avoid invalid memory access with
  short file names.

- bpo-1113244: Py_XINCREF, Py_DECREF, Py_XDECREF: Add `do { ... } while (0)'
  to avoid compiler warnings.

- bpo-5705: os.setuid() would not accept values > 2**31-1 but pwd.getpwnam()
  returned them on 64bit platforms.

- bpo-5108: Handle %s like %S and %R in PyUnicode_FromFormatV(): Call
  PyUnicode_DecodeUTF8() once, remember the result and output it in a second
  step. This avoids problems with counting UTF-8 bytes that ignores the
  effect of using the replace error handler in PyUnicode_DecodeUTF8().

- bpo-3739: The unicode-internal encoder now reports the number of
  characters consumed like any other encoder (instead of the number of
  bytes).

- bpo-2422: When compiled with the ``--with-valgrind`` option, the pymalloc
  allocator will be automatically disabled when running under Valgrind.
  This gives improved memory leak detection when running under Valgrind,
  while taking advantage of pymalloc at other times.

Library
-------

- Add count() and reverse() methods to collections.deque().

- Fix variations of extending deques:  d.extend(d)  d.extendleft(d)  d+=d

- bpo-6986: Fix crash in the JSON C accelerator when called with the wrong
  parameter types.  Patch by Victor Stinner.

- logging: Added optional "secure" parameter to SMTPHandler, to enable use
  of TLS with authentication credentials.

- bpo-1923: Fixed the removal of meaningful spaces when PKG-INFO is
  generated in Distutils. Patch by Stephen Emslie.

- bpo-4120: Drop reference to CRT from manifest when building extensions
  with msvc9compiler.

- bpo-7333: The ``posix`` module gains an ``initgroups()`` function
  providing access to the initgroups(3) C library call on Unix systems which
  implement it. Patch by Jean-Paul Calderone.

- bpo-7408: Fixed distutils.tests.sdist so it doesn't check for group
  ownership when the group is not forced, because the group may be different
  from the user's group and inherit from its container when the test is run.

- bpo-1515: Enable use of deepcopy() with instance methods.  Patch by Robert
  Collins.

- bpo-7403: logging: Fixed possible race condition in lock creation.

- bpo-6845: Add restart support for binary upload in ftplib.  The
  ``storbinary()`` method of FTP and FTP_TLS objects gains an optional
  "rest" argument.  Patch by Pablo Mouzo.

- bpo-5788: ``datetime.timedelta`` objects get a new ``total_seconds()``
  method returning the total number of seconds in the duration.  Patch by
  Brian Quinlan.

- bpo-6615: logging: Used weakrefs in internal handler list.

- bpo-1488943: ``difflib.Differ`` doesn't always add hints for tab
  characters.

- bpo-6123: tarfile now opens empty archives correctly and consistently
  raises ReadError on empty files.

- bpo-7354: distutils.tests.test_msvc9compiler - dragfullwindows can be 2.

- bpo-5037: Proxy the __unicode__ special method to __unicode__ instead of
  __str__.

- bpo-7341: Close the internal file object in the TarFile constructor in
  case of an error.

- bpo-7293: ``distutils.test_msvc9compiler`` is fixed to work on any fresh
  Windows box. Help provided by David Bolen.

- bpo-7328: pydoc no longer corrupts sys.path when run with the '-m' switch.

- bpo-2054: ftplib now provides an FTP_TLS class to do secure FTP using TLS
  or SSL. Patch by Giampaolo Rodola'.

- bpo-4969: The mimetypes module now reads the MIME database from the
  registry under Windows.  Patch by Gabriel Genellina.

- bpo-6816: runpy now provides a run_path function that allows Python code
  to execute file paths that refer to source or compiled Python files as
  well as zipfiles, directories and other valid sys.path entries that
  contain a __main__.py file. This allows applications that run other Python
  scripts to support the same flexibility as the CPython command line
  itself.

- bpo-7318: multiprocessing now uses a timeout when it fails to establish a
  connection with another process, rather than looping endlessly. The
  default timeout is 20 seconds, which should be amply sufficient for local
  connections.

- bpo-7197: Allow unittest.TextTestRunner objects to be pickled and
  unpickled.  This fixes crashes under Windows when trying to run
  test_multiprocessing in verbose mode.

- bpo-7282: Fix a memory leak when an RLock was used in a thread other than
  those started through ``threading.Thread`` (for example, using
  ``thread.start_new_thread()``.

- bpo-7264: Fix a possible deadlock when deallocating thread-local objects
  which are part of a reference cycle.

- bpo-7211: Allow 64-bit values for the ``ident`` and ``data`` fields of
  kevent objects on 64-bit systems.  Patch by Michael Broghton.

- bpo-6896: ``mailbox.Maildir`` now invalidates its internal cache each time
  a modification is done through it.  This fixes inconsistencies and test
  failures on systems with slightly bogus mtime behaviour.

- bpo-7246: getpass now properly flushes input before reading from stdin so
  that existing input does not confuse it and lead to incorrect entry or an
  IOError.  It also properly flushes it afterwards to avoid the terminal
  echoing the input afterwards on OSes such as Solaris. (See also: bpo-7208)

- bpo-7233: Fix a number of two-argument Decimal methods to make sure that
  they accept an int or long as the second argument.  Also fix buggy
  handling of large arguments (those with coefficient longer than the
  current precision) in shift and rotate.

- bpo-4750: Store the basename of the original filename in the gzip FNAME
  header as required by RFC 1952.

- bpo-1180: Added a new global option to ignore ~/.pydistutils.cfg in
  Distutils.

- bpo-7218: Fix test_site for win32, the directory comparison was done with
  an uppercase.

- bpo-7205: Fix a possible deadlock when using a BZ2File object from several
  threads at once.

- bpo-7071: byte-compilation in Distutils is now done with respect to
  sys.dont_write_bytecode.

- bpo-7066: archive_util.make_archive now restores the cwd if an error is
  raised. Initial patch by Ezio Melotti.

- bpo-6218: io.StringIO and io.BytesIO instances are now picklable with
  protocol 2.

- bpo-7077: logging: SysLogHandler now treats Unicode as per RFC 5424.

- bpo-7099: Decimal.is_normal now returns True for numbers with exponent
  larger than emax.

- bpo-5833: Fix extra space character in readline completion with the GNU
  readline library version 6.0.

- bpo-7133: SSL objects now support the new buffer API.

- bpo-7149: urllib fails on OSX in the proxy detection code.

- bpo-7069: Make inspect.isabstract() return a boolean.

- Add support to the ``ihooks`` module for relative imports.

- bpo-6894: Fixed the issue urllib2 doesn't respect "no_proxy" environment.

- bpo-7086: Added TCP support to SysLogHandler, and tidied up some
  anachronisms in the code which were a relic of 1.5.2 compatibility.

- bpo-7082: When falling back to the MIME 'name' parameter, the correct
  place to look for it is the Content-Type header.

- bpo-7048: Force Decimal.logb to round its result when that result is too
  large to fit in the current precision.

- bpo-6516: Added owner/group support when creating tar archives in
  Distutils.

- bpo-7031: Add ``TestCase.assert(Not)IsInstance()`` methods.

- bpo-6790: Make it possible again to pass an ``array.array`` to
  ``httplib.HTTPConnection.send``.  Patch by Kirk McDonald.

- bpo-6236: Fix various failures in the `io` module under AIX and other
  platforms, when using a non-gcc compiler.  Patch by egreen. (See also:
  bpo-6348)

- bpo-6954: Fixed crash when using DISTUTILS_DEBUG flag in Distutils.

- bpo-6851: Fix urllib.urlopen crash on secondairy threads on OSX 10.6

- bpo-4606: Passing 'None' if ctypes argtype is set to POINTER(...) does now
  always result in NULL.

- bpo-5042: ctypes Structure sub-subclass does now initialize correctly with
  base class positional arguments.

- bpo-6938: Fix a TypeError in string formatting of a multiprocessing debug
  message.

- bpo-6635: Fix profiler printing usage message.

- bpo-6856: Add a filter keyword argument to TarFile.add().

- bpo-6163: Fixed HP-UX runtime library dir options in
  distutils.unixcompiler.  Initial patch by Sridhar Ratnakumar and Michael
  Haubenwallner.

- bpo-6857: Default format() alignment should be '>' for Decimal instances.

- bpo-6795: int(Decimal('nan')) now raises ValueError instead of returning
  NaN or raising InvalidContext.  Also, fix infinite recursion in
  long(Decimal('nan')).

- bpo-6850: Fix bug in Decimal._parse_format_specifier for formats with no
  type specifier.

- bpo-4937: plat-mac/bundlebuilder refers to non-existing version.plist.

- bpo-6838: Use a list to accumulate the value instead of repeatedly
  concatenating strings in httplib's HTTPResponse._read_chunked providing a
  significant speed increase when downloading large files servend with a
  Transfer-Encoding of 'chunked'.

- bpo-5275: In Cookie's Cookie.load(), properly handle non-string arguments
  as documented.

- bpo-2666: Handle BROWSER environment variable properly for unknown browser
  names in the webbrowser module.

- bpo-6054: Do not normalize stored pathnames in tarfile.

- bpo-6794: Fix Decimal.compare_total and Decimal.compare_total_mag: NaN
  payloads are now ordered by integer value rather than lexicographically.

- bpo-6693: New functions in site.py to get user/global site packages paths.

- The thread.lock type now supports weak references.

- bpo-1356969: Add missing info methods in Tix.HList.

- bpo-1522587: New constants and methods for the Tix.Grid widget.

- bpo-1250469: Fix the return value of Tix.PanedWindow.panes.

- bpo-1119673: Do not override Tkinter.Text methods when creating a
  ScrolledText.

- bpo-6665: Fix fnmatch to properly match filenames with newlines in them.

- bpo-1135: Add the XView and YView mix-ins to avoid duplicating the xview*
  and yview* methods.

- bpo-6629: Fix a data corruption issue in the new `io` package, which could
  occur when writing to a BufferedRandom object (e.g. a file opened in "rb+"
  or "wb+" mode) after having buffered a certain amount of data for reading.
  This bug was not present in the pure Python implementation.

- bpo-4660: If a multiprocessing.JoinableQueue.put() was preempted, it was
  possible to get a spurious 'task_done() called too many times' error.

- bpo-1628205: Socket file objects returned by socket.socket.makefile() now
  properly handles EINTR within the read, readline, write & flush methods.
  The socket.sendall() method now properly handles interrupted system calls.

- bpo-6595: The Decimal constructor now allows arbitrary Unicode decimal
  digits in input, as recommended by the standard.  Previously it was
  restricted to accepting [0-9].

- bpo-6511: ZipFile now raises BadZipfile (instead of an IOError) when
  opening an empty or very small file.

- bpo-6553: Fixed a crash in cPickle.load(), when given a file-like object
  containing incomplete data.

- bpo-6545: Removed assert statements in distutils.Extension, so the
  behavior is similar when used with -O.

- unittest has been split up into a package.  All old names should still
  work.

- bpo-6431: Make Fraction type return NotImplemented when it doesn't know
  how to handle a comparison without loss of precision.  Also add correct
  handling of infinities and nans for comparisons with float.

- bpo-6415: Fixed warnings.warn segfault on bad formatted string.

- bpo-6466: Now distutils.cygwinccompiler and distutils.emxccompiler uses
  the same refactored function to get gcc/ld/dllwrap versions numbers.  It's
  ``distutils.util.get_compiler_versions()``.  Added deprecation warnings
  for the obsolete get_versions() functions.

- bpo-6433: Fixed issues with multiprocessing.pool.map hanging on empty
  list.

- bpo-6314: logging: Extra checks on the "level" argument in more places.

- bpo-2622: Fixed an ImportError when importing email.messsage from a
  standalone application built with py2exe or py2app.

- bpo-6455: Fixed test_build_ext under win32.

- bpo-6377: Enabled the compiler option, and deprecate its usage as an
  attribute.

- bpo-6413: Fixed the log level in distutils.dist for announce.

- bpo-3392: The subprocess communicate() method no longer fails in select()
  when file descriptors are large; communicate() now uses poll() when
  possible.

- bpo-6403: Fixed package path usage in build_ext.

- bpo-5155: multiprocessing.Process._bootstrap was unconditionally calling
  "os.close(sys.stdin.fileno())" resulting in file descriptor errors. (See
  also: bpo-5313, bpo-5331)

- bpo-6365: Distutils build_ext inplace mode was copying the compiled
  extension in a subdirectory if the extension name had dots.

- bpo-6344: Fixed a crash of mmap.read() when passed a negative argument.

- bpo-5230: pydoc would report no documentation found if a module generated
  a 'not found' import error when loaded; it now reports the import errors.
  Thanks to Lucas Prado Melo for initial fix and collaboration on the tests.

- bpo-6314: ``logging.basicConfig()`` performs extra checks on the "level"
  argument.

- bpo-6164: Added an AIX specific linker argument in Distutils unixcompiler.
  Original patch by Sridhar Ratnakumar.

- bpo-6274: Fixed possible file descriptors leak in subprocess.py.

- bpo-6189: Restored compatibility of subprocess.py with Python 2.2.

- bpo-6287: Added the license field in Distutils documentation.

- bpo-6286: Now Distutils upload command is based on urllib2 instead of
  httplib, allowing the usage of http_proxy.

- bpo-6271: mmap tried to close invalid file handle (-1) for anonymous maps
  on Unix.

- bpo-6215: All bug fixes and enhancements from the Python 3.1 io library
  (including the fast C implementation) have been backported to the standard
  ``io`` module.

- bpo-6258: Support AMD64 in bdist_msi.

- bpo-6252: Fixed bug in next rollover time computation in
  TimedRotatingFileHandler.

- bpo-6263: Fixed syntax error in distutils.cygwincompiler.

- bpo-5201: distutils.sysconfig.parse_makefile() now understands ``$$`` in
  Makefiles. This prevents compile errors when using syntax like:
  ``LDFLAGS='-rpath=\$$LIB:/some/other/path'``.  Patch by Floris Bruynooghe.

- bpo-5767: Removed sgmlop support from xmlrpclib.

- bpo-6131: test_modulefinder leaked when run after test_distutils.  Patch
  by Hirokazu Yamamoto.

- bpo-6048: Now Distutils uses the tarfile module in archive_util.

- bpo-6121: pydoc now ignores leading and trailing spaces in the argument to
  the 'help' function.

- In unittest, using a skipping decorator on a class is now equivalent to
  skipping every test on the class.  The ClassTestSuite class has been
  removed.

- bpo-6050: Don't fail extracting a directory from a zipfile if the
  directory already exists.

- bpo-5311: bdist_msi can now build packages that do not depend on a
  specific Python version.

- bpo-1309352: fcntl now converts its third arguments to a C `long` rather
  than an int, which makes some operations possible under 64-bit Linux (e.g.
  DN_MULTISHOT with F_NOTIFY).

- bpo-1424152: Fix for httplib, urllib2 to support SSL while working through
  proxy. Original patch by Christopher Li, changes made by Senthil Kumaran.

- bpo-1983: Fix functions taking or returning a process identifier to use
  the dedicated C type ``pid_t`` instead of a C ``int``.  Some platforms
  have a process identifier type wider than the standard C integer type.

- bpo-4066: smtplib.SMTP_SSL._get_socket now correctly returns the socket.
  Patch by Farhan Ahmad, test by Marcin Bachry.

- bpo-6062: In distutils, fixed the package option of build_ext.  Feedback
  and tests on pywin32 by Tim Golden.

- bpo-6053: Fixed distutils tests on win32.  Patch by Hirokazu Yamamoto.

- bpo-6046: Fixed the library extension when distutils build_ext is used in
  place. Initial patch by Roumen Petrov.

- bpo-6041: Now distutils `sdist` and `register` commands use `check` as a
  subcommand.

- bpo-2116: Weak references and weak dictionaries now support copy()ing and
  deepcopy()ing.

- bpo-1655: Make imaplib IPv6-capable.  Patch by Derek Morr.

- bpo-5918: Fix a crash in the parser module.

- bpo-1664: Make nntplib IPv6-capable.  Patch by Derek Morr.

- bpo-6022: A test file was created in the current working directory by
  test_get_outputs in Distutils.

- bpo-4050: inspect.findsource/getsource now raise an IOError if the
  'source' file is a binary.  Patch by Brodie Rao, tests by Daniel Diniz.

- bpo-5977: distutils build_ext.get_outputs was not taking into account the
  inplace option.  Initial patch by kxroberto.

- bpo-5984: distutils.command.build_ext.check_extensions_list checks were
  broken for old-style extensions.

- bpo-5971: StreamHandler.handleError now swallows IOErrors which occur when
  trying to print a traceback.

- bpo-5976: Fixed Distutils test_check_environ.

- bpo-5900: Ensure RUNPATH is added to extension modules with RPATH if GNU
  ld is used. Original patch by Floris Bruynooghe.

- bpo-5941: Distutils build_clib command was not working anymore because of
  an incomplete customization of the archiver command.  Added ARFLAGS in the
  Makefile besides AR and make Distutils use it.  Original patch by David
  Cournapeau.

- bpo-5955: aifc's close method did not close the file it wrapped, now it
  does.  This also means getfp method now returns the real fp.

- bpo-4875: On win32, ctypes.util.find_library does no longer return
  directories.

- bpo-5142: Add the ability to skip modules while stepping to pdb.

- bpo-1309567: Fix linecache behavior of stripping subdirectories when
  looking for files given by a relative filename.

- bpo-5692: In ``zipfile.Zipfile``, fix wrong path calculation when
  extracting a file to the root directory.

- bpo-5913: ``os.listdir()`` should fail for empty path on windows.

- bpo-5084: Unpickling now interns the attribute names of pickled objects,
  saving memory and avoiding growth in size of subsequent pickles.  Proposal
  and original patch by Jake McGuire.

- bpo-3002: ``shutil.copyfile()`` and ``shutil.copytree()`` now raise an
  error when a named pipe is encountered, rather than blocking infinitely.

- bpo-3959: The ipaddr module has been added to the standard library.
  Contributed by Google.

- bpo-2245: aifc now skips chunk types it doesn't recognize, per spec.

- bpo-5874: distutils.tests.test_config_cmd is not locale-sensitive anymore.

- bpo-4305: ctypes should now build again on mipsel-linux-gnu

- bpo-1734234: Massively speedup ``unicodedata.normalize()`` when the string
  is already in normalized form, by performing a quick check beforehand.
  Original patch by Rauli Ruohonen.

- bpo-5853: Calling a function of the mimetypes module from several threads
  at once could hit the recursion limit if the mimetypes database hadn't
  been initialized before.

- bpo-5854: Updated __all__ to include some missing names and remove some
  names which should not be exported.

- bpo-5810: Fixed Distutils test_build_scripts so it uses
  ``sysconfig.get_config_vars()``.

- bpo-4951: Fixed failure in test_httpservers.

- bpo-3102: All global symbols that the _ctypes extension defines are now
  prefixed with 'Py' or '_ctypes'.

- bpo-5041: ctypes does now allow pickling wide character.

- bpo-5812: For the two-argument form of the Fraction constructor,
  ``Fraction(m, n)``, m and n are permitted to be arbitrary Rational
  instances.

- bpo-5812: Fraction('1e6') is valid: more generally, any string that's
  valid for float() is now valid for Fraction(), with the exception of
  strings representing NaNs and infinities.

- bpo-5795: Fixed test_distutils failure on Debian ppc.

- bpo-5768: Fixed bug in Unicode output logic and test case for same.

- bpo-1161031: Fix readwrite select flag handling: POLLPRI now results in a
  handle_expt_event call, not handle_read_event, and POLLERR and POLLNVAL
  now call handle_close, not handle_expt_event.  Also, dispatcher now has an
  'ignore_log_types' attribute for suppressing log messages, which is set to
  'warning' by default.

- bpo-5607: Fixed Distutils test_get_platform for Mac OS X fat binaries.

- bpo-5741: Don't disallow "%%" (which is an escape for "%") when setting a
  value in SafeConfigParser.

- bpo-5732: Added a new command in Distutils: check.

- bpo-5731: Distutils bdist_wininst no longer worked on non-Windows
  platforms.  Initial patch by Paul Moore.

- bpo-2254: Fix CGIHTTPServer information disclosure.  Relative paths are
  now collapsed within the url properly before looking in cgi_directories.

- bpo-5095: Added bdist_msi to the list of bdist supported formats.  Initial
  fix by Steven Bethard.

- bpo-1491431: Fixed distutils.filelist.glob_to_re for edge cases.  Initial
  fix by Wayne Davison.

- bpo-5693: TestSuite.__iter__ can now be consistently overridden in
  subclasses.

- bpo-5694: Removed spurious test output in Distutils (test_clean).

- bpo-5471: Fix os.path.expanduser() for $HOME set to '/'.

- bpo-1326077: Fix the formatting of SyntaxErrors by the traceback module.

- bpo-1726172: Fix IndexError in the case of and empty response in ftplib.

- bpo-2625: Added missing iteritems() call to the for loop in
  mailbox.MH.get_message().

- bpo-5585: Add the ability to call an initializer to
  multiprocessing.manager so that users can install custom handlers/etc.

- bpo-3551: Patch multiprocessing to raise a proper exception if the size of
  the object when writefile is called causes an ERROR_NO_SYSTEM_RESOURCES.
  Added docs to note the limitation.

- unittest.assertNotEqual() now uses the inequality operator (!=) instead of
  the equality operator.

- bpo-6001: Test discovery for unittest. Implemented in
  unittest.TestLoader.discover and from the command line.

- bpo-5679: The methods unittest.TestCase.addCleanup and doCleanups were
  added. addCleanup allows you to add cleanup functions that will be called
  unconditionally (after setUp if setUp fails, otherwise after tearDown).
  This allows for much simpler resource allocation and deallocation during
  tests.

- bpo-3379: unittest.main now takes an optional exit argument. If False main
  doesn't call sys.exit allowing it to be used from the interactive
  interpreter.

- bpo-5995: unittest.main now takes an optional verbosity argument allowing
  test modules to be run with a higher than default verbosity.

- bpo-5995: A fix to allow you to run "python -m unittest test_module" or
  "python -m unittest test_module.TestClass" from the command line.

- bpo-5728: unittest.TestResult has new startTestRun and stopTestRun
  methods; called immediately before and after a test run.

- bpo-5663: Better failure messages for unittest asserts. Default assertTrue
  and assertFalse messages are now useful. TestCase has a longMessage
  attribute. This defaults to False, but if set to True useful error
  messages are shown in addition to explicit messages passed to assert
  methods.

- bpo-3110: Add additional protect around SEM_VALUE_MAX for multiprocessing.

- In Pdb, prevent the reassignment of __builtin__._ by sys.displayhook on
  printing out values.

- bpo-4572: Added SEEK_* symbolic constants to io module.

- bpo-1665206: Move imports in cgitb to the top of the module instead of
  performing them in functions. Helps prevent import deadlocking in threads.

- bpo-5647: MutableSet.__iand__() no longer mutates self during iteration.

- Actually make the SimpleXMLRPCServer CGI handler work.

- bpo-2522: locale.format() now checks its first argument to ensure it has
  been passed only one pattern, avoiding mysterious errors where it appeared
  that it was failing to do localization.

- bpo-5583: Added optional extensions in Distutils.  Initial patch by Georg
  Brandl.

- bpo-5619: Multiprocessing children disobey the debug flag and causes
  popups on windows buildbots.  Patch applied to work around this issue.

- bpo-5632: Thread.ident was None for the main thread and threads not
  created with the threading module.

- bpo-5400: Added patch for multiprocessing on netbsd compilation/support.

- bpo-5387: Fixed mmap.move crash by integer overflow.

- bpo-5261: Patch multiprocessing's semaphore.c to support context manager
  use: "with multiprocessing.Lock()" works now.

- bpo-5177: Multiprocessing's SocketListener class now uses
  socket.SO_REUSEADDR on all connections so that the user no longer needs to
  wait 120 seconds for the socket to expire.

- Adjusted _tkinter to compile without warnings when WITH_THREAD is not
  defined (part of issue #5035).

- bpo-5561: Removed the sys.version_info shortcuts from platform's
  python_version() and python_version_tuple() since they produced different
  output compared to previous Python versions.

- bpo-1034053: unittest now supports skipping tests and expected failures.

- The unittest.TestCase.assertRaises() method now returns a context manager
  when not given a callable so that code to be tested can be written inline
  using a with statement.

- bpo-2578: The unittest.TestCase.assertEqual() now displays the differences
  in lists, tuples, dicts and sets on failure.  Many new handy type and
  comparison specific assert* methods have been added that fail with error
  messages actually useful for debugging.  Contributed in part by Google.

- bpo-5068: Fixed the tarfile._BZ2Proxy.read() method that would loop
  forever on incomplete input.  That caused tarfile.open() to hang when used
  with mode 'r' or 'r:bz2' and a fileobj argument that contained no data or
  partial bzip2 compressed data.

- bpo-5536: urllib.urlretrieve makes sure to close the file it's writing to
  even if an exception occurs.

- bpo-5381: Added object_pairs_hook to the json module.  This allows
  OrderedDicts to be built by the decoder.

- bpo-2110: Add support for thousands separator and 'n' type specifier to
  ``Decimal.__format__()``.

- Fix Decimal.__format__ bug that swapped the meanings of the '<' and '>'
  alignment characters.

- bpo-1222: ``locale.format()`` bug when the thousands separator is a space
  character.

- bpo-5472: Fixed distutils.test_util tear down. Original patch by Tim
  Golden.

- collections.deque objects now have a read-only attribute called maxlen.

- bpo-2638: Show a window constructed with tkSimpleDialog.Dialog only after
  it is has been populated and properly configured in order to prevent
  window flashing.

- bpo-4792: Prevent a segfault in _tkinter by using the guaranteed to be
  safe interp argument given to the PythonCmd in place of the Tcl
  interpreter taken from a PythonCmd_ClientData.

- bpo-5193: Guarantee that Tkinter.Text.search returns a string.

- bpo-5394: Removed > 2.3 syntax from distutils.msvc9compiler. Original
  patch by Akira Kitada.

- bpo-5385: Fixed mmap crash after resize failure on windows.

- bpo-5179: Fixed subprocess handle leak on failure on windows.

- PEP 372: Added collections.OrderedDict().

- The _asdict() for method for namedtuples now returns an OrderedDict().

- The configparser module now defaults to using an ordered dictionary.

- bpo-4308: httplib.IncompleteRead's repr doesn't include all of the data
  all ready received.

- bpo-5401: Fixed a performance problem in mimetypes when ``from mimetypes
  import guess_extension`` was used.

- bpo-1733986: Fixed mmap crash on Windows in accessing elements of second
  map object with same tagname but larger size than first map.

- bpo-5386: mmap.write_byte didn't check map size, so it could cause buffer
  overrun.

- bpo-1533164: Installed but not listed *.pyo was breaking Distutils
  bdist_rpm command.

- bpo-5378: Added --quiet option to Distutils bdist_rpm command.

- bpo-5052: Make Distutils compatible with 2.3 again.

- Deprecated methods of symtable.Symbol have been removed: is_keywordarg(),
  is_vararg(), and is_in_tuple().

- bpo-5316: Fixed buildbot failures introduced by multiple inheritance in
  Distutils tests.

- bpo-5287: Add exception handling around findCaller() call to help out
  IronPython.

- bpo-5282: Fixed mmap resize on 32bit Windows and Unix.  When ``offset >
  0``, the file was resized to wrong size.

- bpo-5292: Fixed mmap crash on its boundary access m[len(m)].

- bpo-2279: distutils.sdist.add_defaults now add files from the package_data
  and the data_files metadata.

- bpo-5257: Refactored all tests in distutils, so they use
  support.TempdirManager, to avoid writing in the tests directory.

- bpo-4524: distutils build_script command failed with --with-suffix=3.
  Initial patch by Amaury Forgeot d'Arc.

- bpo-2461: Added tests for distutils.util.

- bpo-1008086: Fixed socket.inet_aton() to always return 4 bytes even on
  LP64 platforms (most 64-bit Linux, bsd, unix systems).

- bpo-5203: Fixed ctypes segfaults when passing a unicode string to a
  function without argtypes (only occurs if HAVE_USABLE_WCHAR_T is false).

- bpo-3386: distutils.sysconfig.get_python_lib prefix argument was ignored
  under NT and OS2. Patch by Philip Jenvey.

- bpo-5128: Make compileall properly inspect bytecode to determine if needs
  to be recreated.  This avoids a timing hole thanks to the old reliance on
  the ctime of the files involved.

- bpo-5122: Synchronize tk load failure check to prevent a potential
  deadlock.

- bpo-1818: collections.namedtuple() now supports a keyword argument
  'rename' which lets invalid fieldnames be automatically converted to
  positional names in the form, _1, _2, ...

- bpo-4890: Handle empty text search pattern in Tkinter.Text.search.

- bpo-5170: Fixed Unicode output bug in logging and added test case.  This
  is a regression which did not occur in 2.5.

- bpo-4512: Promote ``ZipImporter._get_filename()`` to be a public
  documented method ``ZipImporter.get_filename()``.

- bpo-4195: The ``runpy`` module (and the ``-m`` switch) now support the
  execution of packages by looking for and executing a ``__main__``
  submodule when a package name is supplied. Initial patch by Andi Vajda.

- bpo-1731706: Call Tcl_ConditionFinalize for Tcl_Conditions that will not
  be used again (this requires Tcl/Tk 8.3.1), also fix a memory leak in
  Tkapp_Call when calling from a thread different than the one that created
  the Tcl interpreter.  Patch by Robert Hancock.

- bpo-1520877: Now distutils.sysconfig reads $AR from the
  environment/Makefile. Patch by Douglas Greiman.

- bpo-4285: Change sys.version_info to be a named tuple.  Patch by Ross
  Light.

- bpo-1276768: The verbose option was not used in the code of
  distutils.file_util and distutils.dir_util.

- bpo-5132: Fixed trouble building extensions under Solaris with
  --enabled-shared activated. Initial patch by Dave Peterson.

- bpo-1581476: Always use the Tcl global namespace when calling into Tcl.

- bpo-2047: shutil.move() could believe that its destination path was inside
  its source path if it began with the same letters (e.g. "src" vs.
  "src.new").

- bpo-4920: Fixed .next() vs .__next__() issues in the ABCs for Iterator and
  MutableSet.

- Added the ttk module. See issue #2983: Ttk support for Tkinter.

- bpo-5021: doctest.testfile() did not create __name__ and
  collections.namedtuple() relied on __name__ being defined.

- Backport importlib from Python 3.1. Only the import_module() function has
  been backported to help facilitate transitions from 2.7 to 3.1.

- bpo-1885: distutils: When running sdist with --formats=tar,gztar the tar
  file was overridden by the gztar one.

- bpo-4863: distutils.mwerkscompiler has been removed.

- Added new itertools functions: combinations_with_replacement() and
  compress().

- bpo-5032: Added a step argument to itertools.count() and allowed
  non-integer arguments.

- Fix and properly document the multiprocessing module's logging support,
  expose the internal levels and provide proper usage examples.

- bpo-1672332: Fix unpickling of subnormal floats, which was producing a
  ValueError on some platforms.

- bpo-3881: Help Tcl to load even when started through the unreadable local
  symlink to "Program Files" on Vista.

- bpo-4710: Extract directories properly in the zipfile module; allow adding
  directories to a zipfile.

- bpo-3807: _multiprocessing build fails when configure is passed
  --without-threads argument. When this occurs, _multiprocessing will be
  disabled, and not compiled.

- bpo-5008: When a file is opened in append mode with the new IO library, do
  an explicit seek to the end of file (so that e.g. tell() returns the file
  size rather than 0). This is consistent with the behaviour of the
  traditional 2.x file object.

- bpo-5013: Fixed a bug in FileHandler which occurred when the delay
  parameter was set.

- bpo-4998: The memory saving effect of __slots__ had been lost on Fractions
  which inherited from numbers.py which did not have __slots__ defined.  The
  numbers hierarchy now has its own __slots__ declarations.

- bpo-3321: _multiprocessing.Connection() doesn't check handle; added checks
  for *nix machines for negative handles and large int handles.  Without
  this check it is possible to segfault the interpreter.

- bpo-4449: AssertionError in mp_benchmarks.py, caused by an underlying
  issue in sharedctypes.py.

- bpo-1225107: inspect.isclass() returned True for instances with a custom
  __getattr__.

- bpo-3997: Zipfiles generated with more than 65536 files could not be
  opened with other applications.

- bpo-1162154: ``inspect.getmembers()`` now skips attributes that raise
  AttributeError, e.g. a __slots__ attribute which has not been set.

- bpo-1696199: Add collections.Counter() for rapid and convenient counting.

- bpo-3860: GzipFile and BZ2File now support the context management
  protocol.

- bpo-4272: Add an optional argument to the GzipFile constructor to override
  the timestamp in the gzip stream.  The default value remains the current
  time. The information can be used by e.g. gunzip when decompressing.
  Patch by Jacques Frechet.

- Restore Python 2.3 compatibility for decimal.py.

- bpo-1702551: distutils sdist was not excluding VCS directories under
  Windows. Initial solution by Guy Dalberto.

- The _tkinter module functions "createfilehandler", "deletefilehandler",
  "createtimerhandler", "mainloop", "dooneevent" and "quit" have been
  deprecated for removal in 3.x

- bpo-4796: Added Decimal.from_float() and
  Context.create_decimal_from_float() to the decimal module.

- bpo-4812: Add missing underscore prefix to some internal-use-only
  constants in the decimal module.  (Dec_0 becomes _Dec_0, etc.)

- bpo-4795: inspect.isgeneratorfunction() returns False instead of None when
  the function is not a generator.

- bpo-4702: Throwing a DistutilsPlatformError instead of IOError in case no
  MSVC compiler is found under Windows.  Original patch by Philip Jenvey.

- bpo-4646: distutils was choking on empty options arg in the setup
  function. Original patch by Thomas Heller.

- Fractions.from_float() no longer loses precision for integers too big to
  cast as floats.

- bpo-4790: The nsmallest() and nlargest() functions in the heapq module did
  unnecessary work in the common case where no key function was specified.

- bpo-3767: Convert Tk object to string in tkColorChooser.

- bpo-3248: Allow placing ScrolledText in a PanedWindow.

- bpo-4444: Allow assertRaises() to be used as a context handler, so that
  the code under test can be written inline if more practical.

- bpo-4739: Add pydoc help topics for symbols, so that e.g. help('@') works
  as expected in the interactive environment.

- bpo-4756: zipfile.is_zipfile() now supports file-like objects. Patch by
  Gabriel Genellina.

- bpo-4400: .pypirc default generated file was broken in distutils.

- bpo-4736: io.BufferedRWPair's closed property now functions properly.

- bpo-3954: Fix a potential SystemError in _hotshot.logreader error
  handling.

- bpo-4574: Fix a crash in io.IncrementalNewlineDecoder when a carriage
  return encodes to more than one byte in the source encoding (e.g. UTF-16)
  and gets split on a chunk boundary.

- bpo-4223: inspect.getsource() will now correctly display source code for
  packages loaded via zipimport (or any other conformant PEP 302 loader).
  Original patch by Alexander Belopolsky.

- bpo-4201: pdb can now access and display source code loaded via zipimport
  (or any other conformant PEP 302 loader).  Original patch by Alexander
  Belopolsky.

- bpo-4197: Doctests in modules loaded via zipimport (or any other PEP 302
  conformant loader) will now work correctly in most cases (they are still
  subject to the constraints that exist for all code running from inside a
  module loaded via a PEP 302 loader and attempting to perform IO operations
  based on __file__). Original patch by Alexander Belopolsky.

- bpo-4082: Add runpy support to zipimport in a manner that allows
  backporting to maintenance branches.  Original patch by Alexander
  Belopolsky. (See also: bpo-4512)

- bpo-4163: Use unicode-friendly word splitting in the textwrap functions
  when given a Unicode string.

- bpo-4616: TarFile.utime(): Restore directory times on Windows.

- bpo-4084: Fix max, min, max_mag and min_mag Decimal methods to give
  correct results in the case where one argument is a quiet NaN and the
  other is a finite number that requires rounding.

- bpo-1030250: Distutils created directories even when run with the
  --dry-run option.

- bpo-4483: _dbm module now builds on systems with gdbm & gdbm_compat libs.

- bpo-4529: Fix the parser module's validation of try-except-finally
  statements.

- bpo-4458: getopt.gnu_getopt() now recognizes a single "-" as an argument,
  not a malformed option.

- Added the subprocess.check_output() convenience function to get output
  from a subprocess on success or raise an exception on error.

- bpo-1055234: cgi.parse_header(): Fixed parsing of header parameters to
  support unusual filenames (such as those containing semi-colons) in
  Content-Disposition headers.

- bpo-4384: Added logging integration with warnings module using
  captureWarnings(). This change includes a NullHandler which does nothing;
  it will be of use to library developers who want to avoid the "No handlers
  could be found for logger XXX" message which can appear if the library
  user doesn't configure logging.

- bpo-3741: DISTUTILS_USE_SDK set causes msvc9compiler.py to raise an
  exception.

- bpo-4363: The uuid.uuid1() and uuid.uuid4() functions now work even if the
  ctypes module is not present.

- FileIO's mode attribute now always includes ``"b"``.

- bpo-4116: Resolve member name conflict in ScrolledCanvas.__init__.

- httplib.HTTPConnection.putheader() now accepts an arbitrary number of
  values for any header, matching what the documentation has claimed for a
  while.

- bpo-3774: Fixed an error when create a Tkinter menu item without command
  and then remove it.

- Fixed a modulefinder crash on certain relative imports.

- bpo-4150: Pdb's "up" command now works for generator frames in post-mortem
  debugging.

- bpo-4092: Return ArgInfo as promised in the documentation from
  inspect.getargvalues.

- bpo-3935: Properly support list subclasses in bisect's C implementation.

- bpo-4014: Don't claim that Python has an Alpha release status, in addition
  to claiming it is Mature.

- bpo-4730: Fixed the cPickle module to handle correctly astral characters
  when protocol 0 is used.

- bpo-1594: MacOS.GetCreatorAndType now always returns a big-endian result,
  to be consistent with Apple tools.

- bpo-900949: plat-mac/videoreader.py no longer relies on a non-existing
  module.

- bpo-16278952: plat-mac/videoreader.py now correctly imports MediaDescr

- bpo-1737832: plat-mac/EasyDialog.py no longer uses the broken aepack
  module.

- bpo-1149804: macostools.mkdirs now even works when another process creates
  one of the needed subdirectories.

- bpo-900506: added --no-zipimport flag to the bundlebuilder script.

- bpo-841800: bundlebuilder now works with 'python -O'.

- bpo-4861: ctypes.util.find_library(): Robustify. Fix library detection on
  biarch systems.  Try to rely on ldconfig only, without using objdump and
  gcc.

- bpo-5104: The socket module now raises OverflowError when 16-bit port and
  protocol numbers are supplied outside the allowed 0-65536 range on bind()
  and getservbyport().

- bpo-999042: The Python compiler now handles explict global statements
  correctly (should be assigned using STORE_GLOBAL opcode).

- bpo-2703: SimpleXMLRPCDispatcher.__init__: Provide default values for new
  arguments introduced in 2.5.

- bpo-5828: Fixed bogus logic in makeunicodedata.py and regenerated the
  Unicode database (This fixes u'\u1d79'.lower() == '\x00').

- Windows locale mapping updated to Vista.

IDLE
----

- bpo-5150: IDLE's format menu now has an option to strip trailing
  whitespace.

- bpo-5847: Remove -n switch on "Edit with IDLE" menu item.

- idle.py modified and simplified to better support developing experimental
  versions of IDLE which are not installed in the standard location.

- bpo-5559: OutputWindow/PyShell right click menu "Go to file/line" wasn't
  working with file paths containing spaces.

- bpo-5783: Windows: Version string for the .chm help file changed, file not
  being accessed.  Patch by Guilherme Polo/

- bpo-1529142: Allow multiple IDLE GUI/subprocess pairs to exist
  simultaneously. Thanks to David Scherer for suggesting the use of an
  ephemeral port for the GUI. Patch by Weeble.

- Remove port spec from run.py and fix bug where subprocess fails to extract
  port from command line when warnings are present.

- bpo-5129: Tk 8.5 Text widget requires 'wordprocessor' tabstyle attr to
  handle mixed space/tab properly. Patch by Guilherme Polo.

- bpo-3549: On MacOS the preferences menu was not present

Tools/Demos
-----------

- Ttk demos added in Demo/tkinter/ttk/.

- bpo-4677: Add two list comprehension tests to pybench.

Build
-----

- bpo-6603: Change READ_TIMESTAMP macro in ceval.c so that it compiles
  correctly under gcc on x86-64.  This fixes a reported problem with the
  --with-tsc build on x86-64.

- Add 2 new options to ``--with-universal-archs`` on MacOSX: ``intel``
  builds a distribution with ``i386`` and ``x86_64`` architectures, while
  ``3-way`` builds a distribution with the ``ppc``, ``i386`` and ``x86_64``
  architectures.

- bpo-6802: Fix build issues on MacOSX 10.6.

- bpo-6244: Allow detect_tkinter to look for Tcl/Tk 8.6.

- bpo-5390: Add uninstall icon independent of whether file extensions are
  installed.

- bpo-5809: Specifying both --enable-framework and --enable-shared is an
  error. Configure now explicitly tells you about this.

- bpo-3585: Add pkg-config support.  It creates a python-2.7.pc file and a
  python.pc symlink in the $(LIBDIR)/pkgconfig directory.  Patch by Clinton
  Roy.

- bpo-6094: Build correctly with Subversion 1.7.

- bpo-5726: Make Modules/ld_so_aix return the actual exit code of the
  linker, rather than always exit successfully.  Patch by Floris Bruynooghe.

- bpo-4587: Add configure option --with-dbmliborder=db1:db2:... to specify
  the order that backends for the dbm extension are checked.

- Link the shared python library with $(MODLIBS).

- bpo-5134: Silence compiler warnings when compiling sqlite with VC++.

- bpo-4494: Fix build with Py_NO_ENABLE_SHARED on Windows.

- bpo-4895: Use _strdup on Windows CE.

- bpo-4472: ``configure --enable-shared`` now works on OSX.

- bpo-4728: WORDS_BIGEDIAN is now correct in Universal builds. (See also:
  bpo-4060)

- bpo-4389: Add icon to the uninstall entry in "add-and-remove-programs".

- bpo-4289: Remove Cancel button from AdvancedDlg.

- bpo-1656675: Register a drop handler for .py* files on Windows.

- bpo-4120: Exclude manifest from extension modules in VS2008.

- bpo-4091: Install pythonxy.dll in system32 again.

- bpo-4018: Disable "for me" installations on Vista.

- bpo-3758: Add ``patchcheck`` build target to ``.PHONY``.

- bpo-4204: Fixed module build errors on FreeBSD 4.

Documentation
-------------

- bpo-6556: Fixed the Distutils configuration files location explanation for
  Windows.

- bpo-6801: symmetric_difference_update also accepts ``|``.  Thanks to Carl
  Chenet.

C API
-----

- bpo-7528: Add PyLong_AsLongAndOverflow (backported from py3k).

- bpo-7228: Add '%lld' and '%llu' support to PyString_FromFormat(V) and
  PyErr_Format, on machines with HAVE_LONG_LONG defined.

- Add new C-API function PyOS_string_to_double, and deprecated
  PyOS_ascii_atof and PyOS_ascii_strtod.

- Removed _PyOS_double_to_string. Use PyOS_double_to_string instead.  This
  is in preparation for (but not strictly related to) issue #7117, short
  float repr.

- bpo-6624: PyArg_ParseTuple with "s" format when parsing argument with
  NULL: Bogus TypeError detail string.

- bpo-5954: Add a PyFrame_GetLineNumber() function to replace most uses of
  PyCode_Addr2Line().

- bpo-5959: Add a PyCode_NewEmpty() function to create a new empty code
  object at a specified file, function, and line number.

- bpo-1419652: Change the first argument to PyImport_AppendInittab() to
  ``const char *`` as the string is stored beyond the call.

- Some PyBytes_* aliases have been removed because they don't exist in 3.x.

- bpo-5175: PyLong_AsUnsignedLongLong now raises OverflowError for negative
  arguments. Previously, it raised TypeError.

- bpo-4720: The format for PyArg_ParseTupleAndKeywords can begin with '|'.

- bpo-3632: From the gdb debugger, the 'pyo' macro can now be called when
  the GIL is released, or owned by another thread.

- bpo-4122: On Windows, fix a compilation error when using the
  Py_UNICODE_ISSPACE macro in an extension module.

- bpo-4293: Py_AddPendingCall() is now thread safe and can be used for
  asynchronous notifications to python from any thread.  Documentation
  added.

Library
-------

- bpo-6508: Add posix.{getresuid,getresgid,setresuid,setresgid}.

- bpo-7078: Set struct.__doc__ from _struct.__doc__.

- bpo-3366: Add erf, erfc, expm1, gamma, lgamma functions to math module.

- bpo-6823: Allow time.strftime() to accept a tuple with a isdst field
  outside of the range of [-1, 1] by normalizing the value to within that
  range.

- bpo-6877: Make it possible to link the readline extension to libedit on
  OSX.

- bpo-6944: Fix a SystemError when socket.getnameinfo() was called with
  something other than a tuple as first argument.

- bpo-6865: Fix reference counting issue in the initialization of the pwd
  module.

- bpo-6848: Fix curses module build failure on OS X 10.6.

- Fix a segfault in expat when given a specially crafted input lead to the
  tokenizer not stopping. CVE-2009-3720.

- bpo-6561: '\d' in a regex now matches only characters with Unicode
  category 'Nd' (Number, Decimal Digit).  Previously it also matched
  characters with category 'No'.

- bpo-1523: Remove deprecated overflow wrapping for struct.pack with an
  integer format code ('bBhHiIlLqQ').  Packing an out-of-range integer now
  consistently raises struct.error.

- bpo-1530559: Fix various struct.pack inconsistencies for the integer
  formats ('bBhHiIlLqQ').  In the following, '*' represents any of '=', '<',
  '>'.

  - Packing a float now always gives a Deprecation Warning.  Previously it
  only warned for 'I', 'L', '*B', '*H', '*I', '*L'.

  - If x is not an int, long or float, then packing x will always result in
  struct.error.  Previously an x with an __int__ method could be packed by
  'b', 'B', 'h', 'H', 'i', 'l', '*b', '*h' ,'*i', '*l', and an x with a
  __long__ method could be packed by 'q', 'Q', '*q', '*Q'; for x with
  neither __int__ nor __long__, TypeError used to be raised (with a
  confusing error message) for 'I', 'L', '*B', '*H', '*I', '*L', and
  struct.error in other cases.

  Note: as of Python 2.7 beta 1, the above is out of date.  In 2.7 beta 1,
  any argument with an __int__ method can be packed, but use of this feature
  triggers a DeprecationWarning. (See also: bpo-1741130)

- bpo-4873: Fix resource leaks in error cases of pwd and grp.

- bpo-4751: For hashlib algorithms provided by OpenSSL, the Python GIL is
  now released during computation on data lengths >= 2048 bytes.

- bpo-3745: Fix hashlib to always reject unicode and non buffer-api
  supporting objects as input no matter how it was compiled (built in
  implementations or external openssl library).  NOTE: Undone in 2.7a2.

- bpo-4397: Fix occasional test_socket failure on OS X.

- bpo-4279: Fix build of parsermodule under Cygwin.

- bpo-4051: Prevent conflict of UNICODE macros in cPickle.

- bpo-4228: Pack negative values the same way as 2.4 in struct's L format.

- bpo-1040026: Fix os.times result on systems where HZ is incorrect.

- bpo-3167: Fix test_math failures for log, log10 on Solaris, OpenBSD. (See
  also: bpo-3682)

- bpo-4365: Add crtassem.h constants to the msvcrt module.

- bpo-4396: The parser module now correctly validates the with statement.

- bpo-5228: Make functools.partial objects can now be pickled.

Tests
-----

- bpo-7431: Use TESTFN in test_linecache instead of trying to create a file
  in the Lib/test directory, which might be read-only for the user running
  the tests.

- bpo-7324: Add a sanity check to regrtest argument parsing to catch the
  case of an option with no handler.

- bpo-7312: Add a -F flag to run the selected tests in a loop until a test
  fails.  Can be combined with -j.

- bpo-7295: Do not use a hardcoded file name in test_tarfile.

- bpo-7270: Add some dedicated unit tests for multi-thread synchronization
  primitives such as Lock, RLock, Condition, Event and Semaphore.

- bpo-7222: Make thread "reaping" more reliable so that reference
  leak-chasing test runs give sensible results.  The previous method of
  reaping threads could return successfully while some Thread objects were
  still referenced.  This also introduces a new private function:
  ``thread._count()``.

- bpo-7151: Fixed regrtest -j so that output to stderr from a test no longer
  runs the risk of causing the worker thread to fail.

- bpo-7055: test___all__ now greedily detects all modules which have an
  __all__ attribute, rather than using a hardcoded and incomplete list.

- bpo-7058: Added save/restore for things like sys.argv and cwd to
  runtest_inner in regrtest, with warnings if the called test modifies them,
  and a new section in the summary report at the end.

- bpo-7042: Fix test_signal (test_itimer_virtual) failure on OS X 10.6.

- bpo-6806: test_platform failed under OS X 10.6.0 because ``sw_ver`` leaves
  off the trailing 0 in the version number.

- bpo-5450: Moved tests involving loading tk from Lib/test/test_tcl to
  Lib/lib-tk/test/test_tkinter/test_loadtk. With this, these tests
  demonstrate the same behaviour as test_ttkguionly (and now also test_tk)
  which is to skip the tests if DISPLAY is defined but can't be used.

- bpo-6152: New option '-j'/'--multiprocess' for regrtest allows running
  regression tests in parallel, shortening the total runtime.

- bpo-5354: New test support function import_fresh_module() makes it easy to
  import both normal and optimised versions of modules.  test_heapq and
  test_warnings have been adjusted to use it, tests for other modules with
  both C and Python implementations in the stdlib can be adjusted to use it
  over time.

- Fix test_warnings to no longer reset the warnings filter.

- Fix test_logging to no longer reset the warnings filter.

- bpo-5635: Fix running test_sys with tracing enabled.

- regrtest no longer treats ImportError as equivalent to SkipTest.  Imports
  that should cause a test to be skipped are now done using import_module
  from test support, which does the conversion.

- bpo-5083: New 'gui' resource for regrtest.

- bpo-5837: Certain sequences of calls to set() and unset() for
  support.EnvironmentVarGuard objects restored the environment variables
  incorrectly on __exit__.

- bpo-2389: Array objects are now pickled in a portable manner.

Windows
-------

- bpo-5611: Auto-detect whether a C file uses tabs or spaces in Vim.


What's New in Python 2.6 final?
===============================

*Release date: 01-Oct-2008*

Core and Builtins
-----------------

- bpo-3967: Fixed a crash in the count() and find() methods of string-like
  objects, when the "start" parameter is a huge value.

- bpo-3965: Fixed a crash on Windows when open() is given an invalid
  filename or mode, and the filename is a unicode string.

- bpo-3951: Py_USING_MEMORY_DEBUGGER should not be enabled by default.

Library
-------

- bpo-3965: Allow repeated calls to turtle.Screen, by making it a true
  singleton object.

- bpo-3895: It was possible to crash the interpreter when an external timer
  was used with cProfile that returned an object that could not be converted
  into a float.

- bpo-3950: Made turtle respect scale factors.

- bpo-3547: Fixed ctypes structures bitfields of varying integer sizes.

- bpo-3879: A regression in urllib.getproxies_environment was fixed.

- bpo-3863: Disabled a unit test of fork being called from a thread when
  running on platforms known to exhibit OS bugs when attempting that.

Build
-----

- bpo-3989: Package the 2to3 script (as 2to3.py) in the Windows installer.

- bpo-3887: Package x64 version of CRT for AMD64 Windows binaries.


What's New in Python 2.6 release candidate 2?
=============================================

*Release date: 17-Sep-2008*

Library
-------

- Security Issue #2: imageop did not validate arguments correctly and could
  segfault as a result.

- bpo-3886: Possible integer overflows in the _hashopenssl module were
  closed.

Tools/Demos
-----------

- bpo-3850: recursion tests in Tools/scripts/find_recursion_limit.py can
  raise AttributeError instead of RuntimeError, depending in which C API
  call exactly the recursion limit is exceeded. Consequently, both exception
  types are caught and silenced.

Build
-----

- bpo-3617: Include a licensing statement regarding the Microsoft C runtime
  in the Windows installer.


What's New in Python 2.6 release candidate 1?
=============================================

*Release date: 12-Sep-2008*

Core and Builtins
-----------------

- bpo-3642: Suppress warning in obmalloc when size_t is larger than uint.

- bpo-3743: In a few places, PY_FORMAT_SIZE_T was incorrectly used with
  PyString_FromFormat or PyErr_Format to display size_t values. The macro
  PY_FORMAT_SIZE_T is designed to select the correct format for the OS
  ``printf`` function, whereas PyString_FromFormat has an independent
  implementation and uses "%zd" on all platforms for size_t values. This
  makes a difference on win64, where ``printf`` needs "%Id" to display 64bit
  values.

- bpo-3634: _weakref.ref(Exception).__init__() gave invalid return value on
  error.

- bpo-3777: long() applied to a float object now always return a long
  object; previously an int would be returned for small values. the __long__
  method is allowed to return either an int or a long, but the behaviour of
  float objects should not change to respect backward compatibility.

- bpo-3751: str.rpartition would perform a left-partition when called with a
  unicode argument.

- bpo-3683: Fix compilation when --without-threads is given.

- bpo-3668: Fix a memory leak with the "s*" argument parser in
  PyArg_ParseTuple and friends, which occurred when the argument for "s*"
  was correctly parsed but parsing of subsequent arguments failed.

- bpo-2534: speed up isinstance() and issubclass() by 50-70%, so as to match
  Python 2.5 speed despite the __instancecheck__ / __subclasscheck__
  mechanism. In the process, fix a bug where isinstance() and issubclass(),
  when given a tuple of classes as second argument, were looking up
  __instancecheck__ / __subclasscheck__ on the tuple rather than on each
  type object.

- Fix crashes on memory allocation failure found with failmalloc.

- Fix memory leaks found with valgrind and update suppressions file.

- Fix compiler warnings in opt mode which would lead to invalid memory
  reads.

- Fix problem using wrong name in decimal module reported by pychecker.

- Silenced another compiler warning about a used but not defined function
  'stringlib_contains_obj'.

- Added warnings on the use of ``__getslice__``, ``__setslice__``, or
  ``__delslice__``.

- bpo-3678: Correctly pass LDFLAGS and LDLAST to the linker on shared
  library targets in the Makefile.

- bpo-1204: The configure script now tests for additional libraries that may
  be required when linking against readline.  This fixes issues with x86_64
  builds on some platforms (a few Linux flavors and OpenBSD).

C API
-----

- Aliased PyObject_Bytes to PyObject_Str.

Library
-------

- bpo-3640: Pickling a list or a dict uses less local variables, to reduce
  stack usage in the case of deeply nested objects.

- bpo-3629: Fix sre "bytecode" validator for an end case.

- bpo-3811: The Unicode database was updated to 5.1.

- bpo-3781: Further warnings.catch_warnings() cleanup to prevent silent
  misbehaviour when a single instance is nested in multiple with statements,
  or when the methods are invoked in the wrong order.

- bpo-3809: Fixed spurious 'test.blah' file left behind by test_logging.

- bpo-3781: Clean up the API for warnings.catch_warnings() by having it
  return a list or None rather than a custom object.

- bpo-1638033: Cookie.Morsel gained the httponly attribute.

- bpo-3535: zipfile couldn't read some zip files larger than 2GB.

- bpo-3776: Deprecate the bsddb package for removal in 3.0.

- bpo-3762: platform.architecture() fails if python is lanched via its
  symbolic link.

- bpo-3772: Fixed regression problem in StreamHandler.emit().

- bpo-600362: Relocated parse_qs() and parse_qsl(), from the cgi module to
  the urlparse one.  Added a PendingDeprecationWarning in the old module, it
  will be deprecated in the future.

- bpo-2562: Fix distutils PKG-INFO writing logic to allow having non-ascii
  characters and Unicode in setup.py meta-data.

- bpo-3726: Allow spaces in separators in logging configuration files.

- bpo-3719: platform.architecture() fails if there are spaces in the path to
  the Python binary.

- bpo-3602: Moved test.test_support.catch_warning() to
  warnings.catch_warnings() along with some API cleanup. Expanding the tests
  for catch_warnings() also led to an improvement in the raising of a
  DeprecationWarning related to warnings.warn_explicit().

- The deprecation warnings for the old camelCase threading API were removed.

- logging: fixed lack of use of encoding attribute specified on a stream.

- Silenced a trivial compiler warning in the sqlite module.

- Fixed two format strings in the _collections module.

- bpo-3703: _fileio.FileIO gave unhelpful error message when trying to open
  a directory.

- bpo-3708: os.urandom no longer goes into an infinite loop when passed a
  non-integer floating point number.

- bpo-3110: multiprocessing fails to compiel on solaris 10 due to missing
  SEM_VALUE_MAX.

- bpo-4301: Patch the logging module to add processName support, remove
  _check_logger_class from multiprocessing.

- bpo-2975: When compiling several extension modules with Visual Studio 2008
  from the same python interpreter, some environment variables would grow
  without limit.

- bpo-3643: Added a few more checks to _testcapi to prevent segfaults by
  exploitation of poor argument checking.

- sqlite3: Changed docstring of iterdump() to mark method as "Non-standard".

- bpo-3103: Reduced globals symbols used by sqlite3 module and made sure all
  remaining ones have "pysqlite_" prefix.

- bpo-3846: Release the GIL during sqlite3_prepare calls. This improves
  concurrent access to the same SQLite database from multiple
  threads/processes.

Tests
-----

- bpo-3781: Add test.test_support.check_warnings() as a convenience wrapper
  for warnings.catch_warnings() that makes it easier to check that expected
  warning messages are being reported.

- bpo-3796: Some tests functions were not enabled in test_float.

- bpo-3768: Move test_py3kwarn over to the new API for catch_warnings().

Build
-----

- bpo-3833: Use a different upgrade code for Win64 installers.

- bpo-2271: Set SecureCustomProperties so that installation will properly
  use the TARGETDIR even for unprivileged users.

- Allow passing the MSI file name to merge.py.

- bpo-3758: Rename the 'check' target to 'patchcheck' so as to not clash
  with GNU build target guidelines.


What's New in Python 2.6 beta 3?
================================

*Release date: 20-Aug-2008*

Core and Builtins
-----------------

- bpo-1878: Remove Py_TPFLAGS_HAVE_VERSION_TAG from Py_TPFLAGS_DEFAULT when
  not building the core.  This means 3rd party extensions do not
  automatically benefit from the class attribute cache; they will have to
  explicitly add Py_TPFLAGS_HAVE_VERSION_TAG to their tp_flags field if they
  care.  This is a backwards compatibility feature; in 3.0, all types will
  use the cache by default.

- Keyword arguments can now follow starred arguments. (``f(a, *args,
  keyword=23)`` is now valid syntax.)

- ctypes function pointers that are COM methods have a boolean True value
  again.

- bpo-3139: Make buffer-interface thread-safe wrt. PyArg_ParseTuple, by
  denying s# to parse objects that have a releasebuffer procedure, and
  introducing s*.

- bpo-3537: Fix an assertion failure when an empty but presized dict object
  was stored in the freelist.

- bpo-1481296: Make long(float('nan')) and int(float('nan')) raise
  ValueError consistently across platforms.

- bpo-3479: On platforms where sizeof(int) is smaller than sizeof(long)
  (64bit Unix, for example), unichr() would truncate its argument and return
  u'\x00' for unichr(2**32). Now it properly raises an OverflowError.

- Apply security patches from Apple.

- bpo-2542: Now that issubclass() may call arbitrary code, ensure that
  PyErr_ExceptionMatches returns 0 when an exception occurs there.

- bpo-1819: function calls with several named parameters are now on average
  35% faster (as measured by pybench).

- bpo-2378: An unexpected UnboundLocalError or NameError could appear when
  the python debugger steps into a class statement: the free variables
  (local variables defined in an outer scope) would be deleted from the
  outer scope.

- bpo-2620: Overflow checking when allocating or reallocating memory was not
  always being done properly in some python types and extension modules.
  PyMem_MALLOC, PyMem_REALLOC, PyMem_NEW and PyMem_RESIZE have all been
  updated to perform better checks and places in the code that would
  previously leak memory on the error path when such an allocation failed
  have been fixed.

Library
-------

- bpo-3612: Added some missing basic types in ctypes.wintypes.

- The methods ``is_in_tuple()``, ``is_vararg()``, and ``is_keywordarg()`` of
  symtable.Symbol have been deprecated for removal in 3.0 and the next
  release.

- bpo-2234: distutils failed for some versions of the cygwin compiler. The
  version reported by these tools does not necessarily follow the python
  version numbering scheme, so the module is less strict when parsing it.

- bpo-2235: Added Py3k warnings for types which will become unhashable under
  the stricter __hash__ inheritance rules in 3.0. Several types which did
  not meet the rules for hash invariants and were already unhashable in 3.0
  have now been explicitly flagged as unhashable in 2.6 as well
  (collections.Mapping, collections.Set, unittest.TestSuite,
  xml.dom.minidom.NamedNodeMap, numbers.Number, UserList.UserList)

- Update __all__ for cookielib, csv, os, urllib2, and weakref to include
  things imported into the module but exposed as part of the module's API.

- Remove an unneeded import of abc.ABCMeta from 'inspect'.

- Remove unneeded imports of 'sys' and 'warnings' from 'io'.

- Remove unneeded imports of 'warnings' from shelve, filecmp, and
  dummy_thread.

- bpo-3575: Incremental decoder's decode function now takes bytearray by
  using 's*' instead of 't#'.

- bpo-2222: Fixed reference leak when occurred os.rename() fails unicode
  conversion on 2nd parameter. (windows only)

- bpo-2464: urllib2 now supports a malformation in the URL received in a
  redirect.

- Silence the DeprecationWarning raised when importing mimetools in
  BaseHTTPServer, cgi (and rfc822), httplib.

- bpo-2776: fixed small issue when handling a URL with double slash after a
  302 response in the case of not going through a proxy.

- bpo-2676: in the email package, content-type parsing was hanging on
  pathological input because of quadratic or exponential behaviour of a
  regular expression.

- bpo-3476: binary buffered reading through the new "io" library is now
  thread-safe.

- Silence the DeprecationWarning of rfc822 when it is imported by mimetools
  since mimetools itself is deprecated. Because modules are cached, all
  subsequent imports of rfc822 will not raise a visible DeprecationWarning.

- bpo-3134: shutil referenced undefined WindowsError symbol.

- bpo-1342811: Fix leak in Tkinter.Menu.delete. Commands associated to menu
  entries were not deleted.

- Copied the implementation of reduce() to _functools.reduce() to have a
  version that did not raise a DeprecationWarning under -3.

- bpo-3205: When iterating over a BZ2File fails allocating memory, raise a
  MemoryError rather than silently stop the iteration.

- bpo-3487: sre "bytecode" validator.  Passing invalid "re-bytecode" to
  _sre.compile() will now be rejected.  This should not affect anybody since
  the re.compile() function never generates invalid re-bytecode.

- bpo-3436: Make csv.DictReader's fieldnames attribute a property so that
  upon first access it can be automatically initialized from the csv file if
  it wasn't initialized during instantiation.

- bpo-2338: Create imp.reload() to help with transitioning to Python 3.0 as
  the reload() built-in has been removed.

- Changed code in the following modules/packages to remove warnings raised
  while running under the ``-3`` flag: aifc, asynchat, asyncore, bdb, bsddb,
  ConfigParser, cookielib, csv, difflib, distutils, DocXMLRPCServer, email,
  filecmp, fileinput, inspect, logging, modulefinder, pdb, pickle, profile,
  pstats, pydoc, re, rlcompleter, SimpleXMLRPCServer, shelve, socket,
  subprocess, sqlite3, tarfile, Tkinter, test.test_support, textwrap,
  threading, tokenize, traceback, urlparse, wsgiref, xml, xmlrpclib.

- bpo-3039: Fix tarfile.TarFileCompat.writestr() which always raised an
  AttributeError.

- bpo-2523: Fix quadratic behaviour when read()ing a binary file without
  asking for a specific length. This problem only affected files opened
  using the new "io" module, not the built-in open() function.

- bpo-3449: Update decimal module to use most recent specification (v. 1.68)
  and tests (v. 2.58) from IBM.

- bpo-3437: Bug fix in robotparser parsing of Allow: lines.

- bpo-1592: Improve error reporting when operations are attempted on a
  closed shelf.

- Deprecate the "ast" parser function aliases.

- bpo-3120: On 64-bit Windows the subprocess module was truncating handles.

- bpo-3303: Fix a crash in locale.strcoll() when calling it with invalid
  arguments.

- bpo-3302: Fix several crashes when calling locale's gettext functions with
  None arguments.

- bpo-3389: Allow resolving dotted names for handlers in logging
  configuration files.

- Deprecate the sunaudio module for removal in Python 3.0.

- bpo-3394: zipfile.writestr sets external attributes when passed a file
  name rather than a ZipInfo instance, so files are extracted with mode 0600
  rather than 000 under Unix.

- bpo-1857: subprocess.Popen.poll gained an additional _deadstate keyword
  argument in python 2.5, this broke code that subclassed Popen to include
  its own poll method.  Fixed my moving _deadstate to an _internal_poll
  method.

Build
-----

- Generate the PatternGrammar pickle during "make install".

Documentation
-------------

- bpo-2235: the C API function PyObject_HashNotImplemented and its
  interaction with the tp_hash slot (added in 2.6b2) are now documented

- bpo-643841: The language reference now provides more detailed coverage of
  the lookup process for special methods. The disclaimers regarding lack of
  coverage of new-style classes have also been removed, since the coverage
  is now fairly reasonable.


What's New in Python 2.6 beta 2?
================================

*Release date: 17-Jul-2008*

Core and Builtins
-----------------

- bpo-3156: Fix inconsistent behavior of the bytearray type: all its methods
  now allow for items objects that can be converted to an integer using
  operator.index().

- bpo-3360: Fix incorrect parsing of '020000000000.0', which produced a
  ValueError instead of giving the correct float.

- bpo-3083: Add alternate (#) formatting for bin, oct, hex output for
  str.format(). This adds the prefix 0b, 0o, or 0x, respectively.

- bpo-3008: the float type has a new instance method 'float.hex' and a new
  class method 'float.fromhex' to convert floating-point numbers to and from
  hexadecimal strings, respectively.

- bpo-2235: __hash__ is once again inherited by default. To allow
  collections.Hashable to remain meaningful in the presence of the default
  hash implementation (object.__hash__), it is now possible to explicit
  block inheritance of hash by setting __hash__=None at the Python level, or
  tp_hash=PyObject_HashNotImplemented at the C level.

- bpo-3221: Issue a RuntimeWarning instead of raising SystemError if the
  parent module cannot be found while performing an absolute import. This
  means that an incorrectly defined __package__ attribute will now only
  prevent relative imports in that module rather than causing all imports
  from that module to fail.

- bpo-2517: Allow unicode messages in Exceptions again by correctly
  bypassing the instance dictionary when looking up __unicode__ on new-style
  classes.

- bpo-3242: Fix a crash inside the print statement, if sys.stdout is set to
  a custom object whose write() method happens to install another file in
  sys.stdout.

- bpo-3088: Corrected a race condition in classes derived from
  threading.local: the first member set by a thread could be saved in
  another thread's dictionary.

- bpo-3004: Minor change to slice.indices(): the start and stop arguments
  are now treated identically, making the behaviour easier to describe and
  understand. For example, slice(None, -10, 1).indices(9) now returns (0, 0,
  1) instead of (0, -1, 1), and slice(None, 10, -1).indices(10) returns (9,
  9, -1) instead of (9, 10, -1).

- bpo-3219: Calling a function with repeated keyword arguments, f(a=2,
  a=23), would not cause a syntax error.  This was a regression from 2.4
  caused by the switch to the new compiler.

- bpo-2862: Make int and float freelist management consistent with other
  freelists. Changes their CompactFreeList apis into ClearFreeList apis and
  calls them via gc.collect().

Library
-------

- bpo-3554: ctypes.string_at and ctypes.wstring_at did call Python api
  functions without holding the GIL, which could lead to a fatal error when
  they failed.

- bpo-799428: Fix Tkinter.Misc._nametowidget to unwrap Tcl command objects.

- bpo-3395: fix reference in test_multiprocessing to old debugInfo method

- bpo-3312: Fix two crashes in sqlite3.

- bpo-1608818: Fix misbehavior in os.listdir() if readdir() fails.

- bpo-3125: Remove copy_reg in multiprocessing and replace it with
  ForkingPickler.register() to resolve conflict with ctypes.

- bpo-3090: Fixed ARCHFLAGS parsing on OS/X

- bpo-3313: Fixed a crash when a failed dlopen() call does not set a valid
  dlerror() message.

- bpo-3258: Fixed a crash when a ctypes POINTER type to an incomplete
  structure was created.

- bpo-3339: dummy_thread.acquire() should not return None.

- bpo-3285: Fractions from_float() and from_decimal() accept Integral
  arguments.

- bpo-3301: Bisect module behaved badly when lo was negative.

- bpo-839496: SimpleHTTPServer used to open text files in text mode. This is
  both unnecessary (HTTP allows text content to be sent in several forms)
  and wrong because the actual transmitted size could differ from the
  content-length. The problem had been corrected in the 2.4 branch, but
  never merged into trunk.

- bpo-2663: add filtering capability to shutil.copytree().

- bpo-1622: Correct interpretation of various ZIP header fields.

- bpo-1526: Allow more than 64k files to be added to Zip64 file.

- bpo-1746: Correct handling of zipfile archive comments (previously
  archives with comments over 4k were flagged as invalid). Allow writing Zip
  files with archives by setting the 'comment' attribute of a ZipFile.

- bpo-449227: The rlcompleter module now adds "(" to callable objects when
  completed.

- bpo-3190: Pydoc now hides the automatic module attribute __package__ (the
  handling is now the same as that of other special attributes like
  __name__).

- bpo-2885: The urllib.urlopen() function has been deprecated for removal in
  Python 3.0 in favor of urllib2.urlopen().

- bpo-2113: Fix error in subprocess.Popen if the select system call is
  interrupted by a signal.

- bpo-3309: Fix bz2.BZFile iterator to release its internal lock properly
  when raising an exception due to the bz2file being closed. Prevents a
  deadlock.

- bpo-3094: httplib.HTTPSConnection Host: headers no longer include the
  redundant ":443" port number designation when the connection is using the
  default https port (443).

- bpo-874900: after an os.fork() call the threading module state is cleaned
  up in the child process to prevent deadlock and report proper thread
  counts if the new process uses the threading module.

Tests
-----

- test.test_support.catch_warning now keeps track of all warnings it sees
  and is now better documented. Explicit unit tests for this context manager
  have been added to test_warnings.

Build
-----

- bpo-3215: Build sqlite3 as sqlite3.dll, not sqlite3.pyd.

Documentation
-------------

- Document that robotparser has been renamed to urllib.robotparser in Python
  3.0.

- Document that urlparse has been renamed to urllib.parse in Python 3.0.

- Document that urllib2 is split across multiple modules and renamed in
  Python 3.0.

- Document that urllib is split across multiple modules and renamed in
  Python 3.0.


What's New in Python 2.6 beta 1?
================================

*Release date: 18-June-2008*

Core and Builtins
-----------------

- bpo-3211: warnings.warn_explicit() did not guard against its 'registry'
  argument being anything other than a dict or None. Also fixed a bug in
  error handling when 'message' and 'category' were both set to None,
  triggering a bus error.

- bpo-3100: Corrected a crash on deallocation of a subclassed weakref which
  holds the last (strong) reference to its referent.

- Add future_builtins.ascii().

- Several set methods now accept multiple arguments: update(), union(),
  intersection(), intersection_update(), difference(), and
  difference_update().

- bpo-2898: Added sys.getsizeof() to retrieve size of objects in bytes.

- New environment variable PYTHONIOENCODING.

- bpo-2488: Add sys.maxsize.

- bpo-2353: file.xreadlines() now emits a Py3k warning.

- bpo-2863: generators now have a ``gen.__name__`` attribute that equals
  ``gen.gi_code.co_name``, like ``func.__name___`` that equals
  ``func.func_code.co_name``.  The repr() of a generator now also contains
  this name.

- bpo-2831: enumerate() now has a ``start`` argument.

- bpo-2801: fix bug in the float.is_integer method where a ValueError was
  sometimes incorrectly raised.

- bpo-2790: sys.flags was not properly exposing its bytes_warning attribute.

- bpo-2196: hasattr() now lets exceptions which do not inherit Exception
  (KeyboardInterrupt, and SystemExit) propagate instead of ignoring them.

- Added checks for integer overflows, contributed by Google. Some are only
  available if asserts are left in the code, in cases where they can't be
  triggered from Python code.

Library
-------

- bpo-1179: [CVE-2007-4965] Integer overflow in imageop module.

- bpo-3116: marshal.dumps() had quadratic behavior for strings > 32Mb.

- bpo-2138: Add factorial() to the math module.

- The heapq module does comparisons using LT instead of LE.  This makes its
  implementation match that used by list.sort().

- bpo-2819: add full-precision summation function to math module, based on
  Hettinger's ASPN Python Cookbook recipe.

- bpo-2592: delegate nb_index and the floor/truediv slots in weakref.proxy.

- Support os.O_ASYNC and fcntl.FASYNC if the constants exist on the
  platform.

- Support for Windows 9x has been removed from the winsound module.

- bsddb module updated to version 4.7.3.
  http://www.jcea.es/programacion/pybsddb.htm#bsddb3-4.7.3. This code should
  be compatible with Python 3.0.

- bpo-2858: Fix potential memory corruption when bsddb.db.DBEnv.lock_get and
  other bsddb.db object constructors raised an exception.

- bpo-2669: bsddb/__init__.py iteration no longer silently fails when the
  database has changed size during iteration.  It now raises a RuntimeError
  in the same manner as a dictionary.

- bpo-2870: cmathmodule.c compile error.

- Added a threading.Thread.ident property.

- logging.config: Removed out-of-date comment in _install_handlers and used
  issubclass in place of equality comparison of classes.

- bpo-2722: Now the os.getcwd() supports very long path names.

- bpo-2888: Fixed the behaviour of pprint when working with nested
  structures, to match the behaviour of 2.5 and 3.0 (now follows the common
  sense).

- bpo-1817: cgi now correctly handles the querystring on POST requests

- bpo-3136: fileConfig()'s disabling of old loggers is now conditional via
  an optional disable_existing_loggers parameter, but the default value is
  such that the old behaviour is preserved. Thanks to Leandro Lucarella for
  the patch.

- bpo-3126: StreamHandler and FileHandler check before calling "flush" and
  "close" that the stream object has these, using hasattr (thanks to bobf
  for the patch).

- bpo-2912: platform.uname now tries to determine unknown information even
  if os.uname exists.

- The rfc822 module has been deprecated for removal in 3.0.

- The mimetools module has been deprecated for removal in 3.0.

- The ctypes.byref function now takes an optional second parameter which
  specifies an offset in bytes for the constructed pointer-like object.

- Added the ast module.

- Added the multiprocessing module, PEP 371.

- Factored out the indentation cleaning from inspect.getdoc() into
  inspect.cleandoc() to ease standalone use.

- bpo-1798: Add ctypes calling convention that allows safe access to errno.

- bpo-2404: ctypes objects support the new pep3118 buffer interface.

- bpo-2125: Add GetInteger and GetString methods for msilib.Record objects.

- bpo-2782: The datetime module's strftime methods now accept unicode format
  strings just as time.strftime always has.

- The sgmllib and htmllib modules have been deprecated for removal in Python
  3.0.

- bpo-3011: locale module alias table was updated to the latest version from
  the X.org locale.alias file.

- bpo-1797: ctypes NULL function pointers have a False boolean value now.

- bpo-2985: Allow 64-bit integer responses (``<i8>``) in XMLRPC transfers.

- bpo-2877: The UserString.MutableString class has been removed in Python
  3.0.

- Do not close external file objects passed to tarfile.open(mode='w:bz2')
  when the TarFile is closed.

- bpo-2959: For consistency with other file-like objects, gzip's
  GzipFile.close() can now be called multiple times without raising an
  exception.

- bpo-1390: Raise ValueError in toxml when an invalid comment would
  otherwise be produced.

- bpo-2914: TimedRotatingFileHandler now takes an optional keyword argument
  "utc" to use UTC time rather than local time.

- bpo-2929: TimedRotatingFileHandler was using the wrong path when deleting
  old log files (filename only instead of full path).

- bpo-1775025: You can now specify zipfile members to open(), read() or
  extract() via a ZipInfo instance.  This allows handling duplicate
  filenames in zipfiles.

- bpo-961805: Fix Text.edit_modified() in Tkinter.

- bpo-1793: Function ctypes.util.find_msvcrt() added that returns the name
  of the C runtime library that Python uses. ctypes.util.find_library(name)
  now call this function when name is 'm' or 'c'.

- The statvfs module has been deprecated for removal in Python 3.0.

- The sunaudiodev and SUNAUDIODEV modules have been deprecated for removal
  in Python 3.0.

- The WAIT module from IRIX has been deprecated for removal in Python 3.0.

- The torgb module from IRIX has been deprecated for removal in Python 3.0.

- The SV module from IRIX has been deprecated for removal in Python 3.0.

- The readcd module from IRIX has been deprecated for removal in Python 3.0.

- The panelparser module from IRIX has been deprecated for removal in Python
  3.0.

- The panel module from IRIX has been deprecated for removal in Python 3.0.

- The jpeg module from IRIX has been deprecated for removal in Python 3.0.

- The IOCTL module from IRIX has been deprecated for removal in Python 3.0.

- The IN module from IRIX has been deprecated for removal in Python 3.0.

- The imgfile module from IRIX has been deprecated for removal in Python
  3.0.

- The GLWS module from IRIX has been deprecated for removal in Python 3.0.

- The GET module from IRIX has been deprecated for removal in Python 3.0.

- The fm module from IRIX has been deprecated for removal in Python 3.0.

- The FL, flp, and fl modules from IRIX have been deprecated for removal in
  Python 3.0.

- The FILE module on IRIX has been deprecated for removal in Python 3.0.

- The ERRNO module on IRIX has been deprecated for removal in Python 3.0.

- The DEVICE, GL, gl, and cgen modules (which indirectly includes
  cgensupport) have been deprecated for removal in Python 3.0.

- The CL, CL_old, and cl modules for IRIX have been deprecated for removal
  in Python 3.0.

- The cdplayer module for IRIX has been deprecated for removal in Python
  3.0.

- The cddb module for IRIX has been deprecated for removal in Python 3.0.

- The cd and CD modules for IRIX have been deprecated for removal in Python
  3.0.

- The al and AL modules for IRIX have been deprecated for removal in Python
  3.0.

- bpo-1713041: fix pprint's handling of maximum depth.

- The timing module has been deprecated for removal in Python 3.0.

- The sv module has been deprecated for removal in Python 3.0.

- The multifile module has been deprecated as per PEP 4.

- The imageop module has been deprecated for removal in Python 3.0.

- bpo-2250: Exceptions raised during evaluation of names in rlcompleter's
  ``Completer.complete()`` method are now caught and ignored.

- bpo-2659: Added ``break_on_hyphens`` option to textwrap TextWrapper class.

- The mhlib module has been deprecated for removal in Python 3.0.

- The linuxaudiodev module has been deprecated for removal in Python 3.0.

- The ihooks module has been deprecated for removal in Python 3.0.

- The fpformat module has been deprecated for removal in Python 3.0.

- The dl module has been deprecated for removal in Python 3.0.

- The Canvas module has been deprecated for removal in Python 3.0.

- The compiler package has been deprecated for removal in Python 3.0.

- The Bastion and rexec modules have been deprecated for removal in Python
  3.0.

- The bsddb185 module has been deprecated for removal in Python 3.0.

- The pure module has been deprecated for removal in Python 3.0.

- bpo-2487: change the semantics of math.ldexp(x, n) when n is too large to
  fit in a C long.  ldexp(x, n) now returns a zero (with suitable sign) if n
  is large and negative; previously, it raised OverflowError.

- The toaiff module has been deprecated for removal in Python 3.0.

- The test.testall module has been deprecated for removal in Python 3.0.

- The new module has been deprecated for removal in Python 3.0.

- The user module has been deprecated for removal in Python 3.0.

- The stringold module has been deprecated for removal in Python 3.0.

- The mutex module has been deprecated for removal in Python 3.0.

- The imputil module has been deprecated for removal in Python 3.0.

- test.test_support.catch_warning() gained a 'record' argument.

- os.path.walk is deprecated in favor of os.walk.

- pdb gained the "until" command.

- The Mac Modules (including Carbon) have been deprecated for removal in
  Python 3.0.

- Library: on MacOS X you can now set ``ARCHFLAGS`` in the shell environment
  to control the '-arch' flags that are used to build an extension. This was
  added for compatibility with Apple's build of Python.

- The bundled OSX-specific copy of libbffi is now in sync with the version
  shipped with PyObjC 2.0 and includes support for x86_64 and ppc64
  platforms.

- The threading module gained aliases for names that will be removed in the
  3.x series.

Build
-----

- The Windows installer now includes Tk 8.5, bzip2 1.0.5, and SQLite 3.5.9.

- bpo-1722225: Support QNX 6.

- ``Lib/lib-old`` is now added to sys.path.

- On MacOS X it is now possible to install the framework in 64-bit mode or
  even as a 4-way universal binary (that is, PPC, i386, PPC64 and x86_64
  support in one binary).

  This is controlled by the configure argument ``--with-universal-archs``:

  - ``--with-universal-archs=all``: install 4-way universal

  - ``--with-universal-archs=32-bit``: install 2-way universal, 32-bit (the
  default)

  - ``--with-universal-archs=64-bit``: install 2-way universal, 64-bit

  This option should be used in combination with ``--enable-universalsdk=``.

  NOTE: 64-bit and 4-way builds are only suppported on Mac OS X 10.5 (or
  later).

C API
-----

- Add ``PyType_Modified()`` as a public API to clear the type cache.

- The PyBytes functions have been renamed to PyByteArray.

- The PyString functions have been renamed to PyBytes. A batch of defines
  were added so that the linker still sees the original PyString names.


What's New in Python 2.6 alpha 3?
=================================

*Release date: 08-May-2008*

Core and Builtins
-----------------

- bpo-2719: backported the ``next()`` builtin from Python 3.

- bpo-2681: The octal literal ``0o8`` was incorrecly acctepted. Now it
  properly raises a SyntaxError.

- bpo-2617: Reserved -J and -X arguments for Jython, IronPython and other
  implementations of Python.

- Implemented PEP 370: Per user site-packages directory.

Library
-------

- bpo-2670: Fix a failure in urllib2.build_opener(), when passed two
  handlers that derive the same default base class.

- Added kill, terminate and send_signal(sig) to subprocess.Popen.

- Added phase(z) -> phi, polar(z) -> r, phi and rect(r, phi) -> z to the
  cmath module.

- Four new methods were added to the math and cmath modules: acosh, asinh,
  atanh and log1p.

- zlib.decompressobj().flush(value) no longer crashes the interpreter when
  passed a value less than or equal to zero.

- bpo-1631171: Re-implement the 'warnings' module in C (the original Python
  code has been kept as backup). This will allow for using the 'warning's
  machinery in such places as the parser where use of pure Python code is
  not possible.  Both the ``showarning()`` and ``formatwarning()`` gain an
  optional 'line' argument which is not called by default for
  backwards-compatibility reasons. Setting ``warnings.showwarning()`` to an
  implementation that lacks support for the ``line`` argument will raise a
  DeprecationWarning.

- The audiodev module has been deprecated for removal in Python 3.0.

- bpo-2750: Add the 'json' package. Based on simplejson 1.9 and contributed
  by Bob Ippolito.

- bpo-1734346: Support Unicode file names for zipfiles.

- bpo-2581: distutils: Vista UAC/elevation support for bdist_wininst.

- bpo-2635: Fix bug in 'fix_sentence_endings' textwrap.fill option, where an
  extra space was added after a word containing (but not ending in) '.', '!'
  or '?'.

- Add from_buffer() and from_buffer_copy() class methods to ctypes data
  types.

- bpo-2682: ctypes callback functions no longer contain a cyclic reference
  to themselves.

- The getpass module has been improved on Unix.  It now uses /dev/tty by
  default and uses stderr instead of stdout.  A GetPassWarning is issued
  when input echo cannot be controlled.

- bpo-2014: Allow XML-RPC datetime objects to have dates before 1900-01-01.

- bpo-2439: Added new function pkgutil.get_data(), which is a convenience
  wrapper for the PEP 302 get_data() API.

- bpo-2616: The ctypes.pointer() and ctypes.POINTER() functions are now
  implemented in C for better performance.

- bpo-2408: The ``_types`` module, which was used as in implementation
  detail of the public ``types`` module, has been removed and replaced by
  pure python code.

- bpo-2513: distutils on Windows is now capable of cross-compiling extension
  modules between 32 and 64 bit platforms.  See the distutls build
  documentation for more information.

- bpo-815646: Individual file objects may now be used from multiple threads
  at once without fear of crashing the Python interpreter.  If file.close()
  is called while an object is in use by another thread an IOError exception
  will be raised and the file will not be closed.

- The bundled libffi copy is now in sync with the recently released
  libffi3.0.5 version, apart from some small changes to
  Modules/_ctypes/libffi/configure.ac.

- bpo-2385: distutils.core.run_script() makes __file__ available, so the
  controlled environment will more closely mirror the typical script
  environment.  This supports setup.py scripts that refer to data files.

Tests
-----

- bpo-2550: The approach used by client/server code for obtaining ports to
  listen on in network-oriented tests has been refined in an effort to
  facilitate running multiple instances of the entire regression test suite
  in parallel without issue. test_support.bind_port() has been fixed such
  that it will always return a unique port -- which wasn't always the case
  with the previous implementation, especially if socket options had been
  set that affected address reuse (i.e. SO_REUSEADDR, SO_REUSEPORT).  The
  new implementation of bind_port() will actually raise an exception if it
  is passed an AF_INET/SOCK_STREAM socket with either the SO_REUSEADDR or
  SO_REUSEPORT socket option set.  Furthermore, if available, bind_port()
  will set the SO_EXCLUSIVEADDRUSE option on the socket it's been passed.
  This currently only applies to Windows.  This option prevents any other
  sockets from binding to the host/port we've bound to, thus removing the
  possibility of the 'non-deterministic' behaviour, as Microsoft puts it,
  that occurs when a second SOCK_STREAM socket binds and accepts to a
  host/port that's already been bound by another socket.  The optional
  preferred port parameter to bind_port() has been removed.  Under no
  circumstances should tests be hard coding ports!

  test_support.find_unused_port() has also been introduced, which will pass
  a temporary socket object to bind_port() in order to obtain an unused
  port. The temporary socket object is then closed and deleted, and the port
  is returned.  This method should only be used for obtaining an unused port
  in order to pass to an external program (i.e. the -accept [port] argument
  to openssl's s_server mode) or as a parameter to a server-oriented class
  that doesn't give you direct access to the underlying socket used.

  Finally, test_support.HOST has been introduced, which should be used for
  the host argument of any relevant socket calls (i.e. bind and connect).

  The following tests were updated to following the new conventions:
  test_socket, test_smtplib, test_asyncore, test_ssl, test_httplib,
  test_poplib, test_ftplib, test_telnetlib, test_socketserver,
  test_asynchat and test_socket_ssl.

  It is now possible for multiple instances of the regression test suite to
  run in parallel without issue.

Build
-----

- bpo-1496032: On alpha, use -mieee when gcc is the compiler.

- bpo-2544: On HP-UX systems, use 'gcc -shared' for linking when gcc is used
  as compiler.

- bpo-2573: On MacOS X it is now possible to install the framework with a
  different name using --with-framework-name=NAME.

C API
-----

- Added implementation of copysign, acosh, asinh, atanh and log1p to the new
  files Include/pymath.h and Python/pymath.h for platforms which provide the
  functions through their libm. The files also contains several helpers and
  constants for math.

- Added a new convenience macro, PyErr_WarnPy3k, for issuing Py3k warnings.


What's New in Python 2.6 alpha 2?
=================================

*Release date: 02-Apr-2008*

Core and Builtins
-----------------

- bpo-1733757: The interpreter would hang on shutdown if the tracing
  function set by sys.settrace is still active and happens to call
  threading.currentThread().

- bpo-1442: properly report exceptions when the PYTHONSTARTUP file cannot be
  executed.

- The compilation of a class nested in another class used to leak one
  reference on the outer class name.

- bpo-1810: compile() can now compile _ast trees as returned by
  ``compile(..., PyCF_ONLY_AST)``.

- bpo-2426: Added sqlite3.Connection.iterdump method to allow easy dumping
  of databases. Contributed by Paul Kippes at PyCon 2008.

- bpo-2477: Added from __future__ import unicode_literals.

- Added backport of bytearray type.

- bpo-2355: add Py3k warning for buffer().

- bpo-1477: With narrow Unicode builds, the unicode escape sequence
  \Uxxxxxxxx did not accept values outside the Basic Multilingual Plane.
  This affected raw unicode literals and the 'raw-unicode-escape' codec.
  Now UTF-16 surrogates are generated in this case, like normal unicode
  literals and the 'unicode-escape' codec.

- bpo-2348: add Py3k warning for file.softspace.

- bpo-2346: add Py3k warnings for __methods__ and __members__. (See also:
  bpo-2347)

- bpo-2358: Add a Py3k warning on sys.exc_clear() usage.

- bpo-2400: Allow relative imports to "import *".

- bpo-1745: Backport print function with ``from __future__ import
  print_function``.

- bpo-2332: add new attribute names for instance method objects. The two
  changes are: im_self -> __self__ and im_func -> __func__

- bpo-2379: Raise a Py3K warning for __getitem__ or __getslice__ on
  exception instances.

- bpo-2371: Add a Py3k warning when catching an exception that doesn't
  derive from BaseException.

- bpo-2341: Add a Py3k warning when raising an exception that doesn't derive
  from BaseException.

- bpo-2321: use pymalloc for unicode object string data to reduce memory
  usage in some circumstances.

- PEP 3127: octal literals now start with "0o". Old-style octal literals are
  still valid. There are binary literals with a prefix of "0b".  This also
  affects int(x, 0).

- bpo-2359: Adding deprecation warnings for array.{read,write}.

- bpo-1779871: GNU gcc can now build Python on OS X because the flags
  -Wno-long-double, -no-cpp-precomp, and -mno-fused-madd are no longer
  passed.

- Add a warning when asserting a non-empty tuple which is always true.

- bpo-2179: speed up with statement execution by storing the exit method on
  the stack instead of in a temporary variable (patch by Jeffrey Yaskin)

- bpo-2238: Some syntax errors in *args and **kwargs expressions could give
  bogus error messages.

- bpo-2143: Fix embedded readline() hang on SSL socket EOF.

Library
-------

- bpo-2240: Implement signal.setitimer and signal.getitimer.

- bpo-2315: logging.handlers: TimedRotatingFileHandler now accounts for
  daylight savings time in calculating the next rollover.

- bpo-2316: logging.handlers: TimedRotatingFileHandler now calculates
  rollovers correctly even when nothing is logged for a while.

- bpo-2317: logging.handlers: TimedRotatingFileHandler now uses improved
  logic for removing old files.

- bpo-2495: tokenize.untokenize now inserts a space between two consecutive
  string literals; previously, ["" ""] was rendered as [""""], which is
  incorrect python code.

- bpo-2248: return the result of the QUIT command. from SMTP.quit().

- Backport of Python 3.0's io module.

- bpo-2482: Make sure that the coefficient of a Decimal is always stored as
  a str instance, not as a unicode instance.  This ensures that str(Decimal)
  is always an instance of str.

- bpo-2478: fix failure of decimal.Decimal(0).sqrt()

- bpo-2432: give DictReader the dialect and line_num attributes advertised
  in the docs.

- bpo-2460: Make Ellipsis object copyable.

- bpo-1681432: Add triangular distribution to the random module

- bpo-2136: urllib2's auth handler now allows single-quoted realms in the
  WWW-Authenticate header.

- bpo-2434: Enhanced platform.win32_ver() to also work on Python
  installation which do not have the win32all package installed.

- Added support to platform.uname() to also report the machine and processor
  information on Windows XP and later. As a result, platform.machine() and
  platform.processor() will report this information as well.

- The library implementing the 2to3 conversion, lib2to3, was added to the
  standard distribution.

- bpo-1747858: Fix chown to work with large uid's and gid's on 64-bit
  platforms.

- bpo-1202: zlib.crc32 and zlib.adler32 no longer return different values on
  32-bit vs. 64-bit python interpreters.  Both were correct, but they now
  both return a signed integer object for consistency.

- bpo-1158: add %f format (fractions of a second represented as
  microseconds) to datetime objects.  Understood by both strptime and
  strftime.

- bpo-705836: struct.pack(">f", x) now raises OverflowError on all platforms
  when x is too large to fit into an IEEE 754 float; previously it only
  raised OverflowError on non IEEE 754 platforms.

- bpo-2166: now distutils deals with HOME correctly under win32 (See also:
  bpo-1741, bpo-1531505)

- bpo-1858: distutils: added multiple server support in .pypirc

- bpo-1106316: pdb.post_mortem()'s parameter, "traceback", is now optional:
  it defaults to the traceback of the exception that is currently being
  handled (is mandatory to be in the middle of an exception, otherwise it
  raises ValueError).

- bpo-1193577: A .shutdown() method has been added to SocketServers which
  terminates the .serve_forever() loop.

- bpo-2220: handle rlcompleter attribute match failure more gracefully.

- bpo-2225: py_compile, when executed as a script, now returns a non- zero
  status code if not all files could be compiled successfully.

- bpo-1725737: In distutils' sdist, exclude RCS, CVS etc. also in the root
  directory, and also exclude .hg, .git, .bzr, and _darcs.

- bpo-1872: The struct module typecode for _Bool has been changed from 't'
  to '?'.

- The bundled libffi copy is now in sync with the recently released
  libffi3.0.4 version, apart from some small changes to
  Modules/_ctypes/libffi/configure.ac.  On OS X, preconfigured libffi files
  are used.  On all linux systems the --with-system-ffi configure option
  defaults to "yes".

- bpo-1577: shutil.move() now calls os.rename() if the destination is a
  directory instead of copying-then-remove-source.

Tests
-----

- test_nis no longer fails when test.test_support.verbose is true and NIS is
  not set up on the testing machine.

- Output comparison tests are no longer supported.

- Rewrite test_errno to use unittest and no longer be a no-op.

- GHOP 234: Convert test_extcall to doctest.

- GHOP 290: Convert test_dbm and test_dummy_threading to unittest.

- GHOP 293: Convert test_strftime, test_getargs, and test_pep247 to
  unittest.

- bpo-2055: Convert test_fcntl to unittest.

- bpo-1960: Convert test_gdbm to unittest.

- GHOP 294: Convert test_contains, test_crypt, and test_select to unittest.

- GHOP 238: Convert test_tokenize to use doctest.

- GHOP 237: Rewrite test_thread using unittest.

- bpo-2232: os.tmpfile might fail on Windows if the user has no permission
  to create files in the root directory.

Build
-----

- A new script 2to3 is now installed, to run the 2.x to 3.x converter.

- Python/memmove.c and Python/strerror.c have been removed; both functions
  are in the C89 standard library.

- bpo-2284: Add -x64 option to rt.bat.

C API
-----

- bpo-2477: Added PyParser_ParseFileFlagsEx() and
  PyParser_ParseStringFlagsFilenameEx().


What's New in Python 2.6 alpha 1?
=================================

*Release date: 29-Feb-2008*

Core and Builtins
-----------------

- bpo-2051: pyc and pyo files are no longer created with permission 644. The
  mode is now inherited from the py file.

- bpo-2067: file.__exit__() now calls subclasses' close() method.

- bpo-1759: Backport of PEP 3129 class decorators.

- bpo-1881: An internal parser limit has been increased. Also see issue
  #215555 for a discussion.

- Added the future_builtins module, which contains hex() and oct(). These
  are the PEP 3127 version of these functions, designed to be compatible
  with the hex() and oct() builtins from Python 3.0.  They differ slightly
  in their output formats from the existing, unchanged Python 2.6 builtins.
  The expected usage of the future_builtins module is:   from
  future_builtins import hex, oct

- bpo-1600: Modified PyOS_ascii_formatd to use at most 2 digit exponents for
  exponents with absolute value < 100.  Follows C99 standard.  This is a
  change on Windows, which would use 3 digits. Also, added 'n' to the
  formats that PyOS_ascii_formatd understands, so that any alterations it
  does to the resulting string will be available in stringlib/formatter.h
  (for float.__format__).

- Implemented PEP 3101, Advanced String Formatting.  This adds a new builtin
  format(); a format() method for str and unicode; a __format__() method to
  object, str, unicode, int, long, float, and datetime; the class
  string.Formatter; and the C API PyObject_Format().

- Fixed several potential crashes, all caused by specially crafted __del__
  methods exploiting objects in temporarily inconsistent state.

- bpo-2115: Important speedup in setting __slot__ attributes.  Also prevent
  a possible crash: an Abstract Base Class would try to access a slot on a
  registered virtual subclass.

- Fixed repr() and str() of complex numbers with infinity or nan as real or
  imaginary part.

- Clear all free lists during a gc.collect() of the highest generation in
  order to allow pymalloc to free more arenas. Python may give back memory
  to the OS earlier.

- bpo-2045: Fix an infinite recursion triggered when printing a subclass of
  collections.defaultdict, if its default_factory is set to a bound method.

- Fixed a minor memory leak in dictobject.c. The content of the free list
  was not freed on interpreter shutdown.

- Limit free list of method and built-in function objects to 256 entries
  each.

- bpo-1953: Added ``sys._compact_freelists()`` and the C API functions
  ``PyInt_CompactFreeList`` and ``PyFloat_CompactFreeList`` to compact the
  internal free lists of pre-allocted ints and floats.

- bpo-1983: Fixed return type of fork(), fork1() and forkpty() calls.
  Python expected the return type int but the fork familie returns pi_t.

- bpo-1678380: Fix a bug that identifies 0j and -0j when they appear in the
  same code unit.

- bpo-2025: Add tuple.count() and tuple.index() methods to comply with the
  collections.Sequence API.

- bpo-1970: Speedup unicode whitespace and linebreak detection.  (Patch by
  Antoine Pitrou.)

- Added ``PyType_ClearCache()`` and ``sys._clear_type_cache`` to clear the
  internal lookup cache for ref leak tests.

- bpo-1473257: generator objects gain a gi_code attribute. This is the same
  object as the func_code attribute of the function that produced the
  generator.

- bpo-1920: "while 0" statements were completely removed by the compiler,
  even in the presence of an "else" clause, which is supposed to be run when
  the condition is false. Now the compiler correctly emits bytecode for the
  "else" suite.

- A few crashers fixed: weakref_in_del.py (issue #1377858);
  loosing_dict_ref.py (issue #1303614, test67.py); borrowed_ref_[34].py (not
  in tracker).

- bpo-1069410: The "can't load dll" message box on Windows is suppressed
  while an extension is loaded by calling SetErrorMode in dynload_win.c. The
  error is still reported properly.

- bpo-1915: Python compiles with --enable-unicode=no again. However several
  extension methods and modules do not work without unicode support.

- bpo-1882: when compiling code from a string, encoding cookies in the
  second line of code were not always recognized correctly.

- bpo-1679: "0x" was taken as a valid integer literal.

- bpo-1865: ``bytes`` as an alias for ``str`` and b"" as an alias "" were
  added.

- sys.float_info / PyFloat_GetInfo: The floating point information object
  was converted from a dict to a specialized structseq object.

- bpo-1816: Added sys.flags structseq. It exposes the status of most command
  line arguments and PYTHON* environment variables.

- Objects/structseq.c: Implemented new structseq representation. The patch
  makes structseqs (e.g. the return value of os.stat) more readable.

- bpo-1700288: added a type attribute cache that caches method accesses,
  resulting in speedups in heavily object-oriented code.

- bpo-1776: __import__() no longer accepts filenames on any platform. The
  first parameter to __import__() must be a valid module name.

- bpo-1668: renamed THREADDEBUG envvar to PYTHONTHREADDEBUG.

- bpo-602345: Add -B command line option, PYTHONDONTWRITEBYTECODE envvar and
  sys.dont_write_bytecode attribute. All these can be set to forbid Python
  to attempt to write compiled bytecode files.

- Improve some exception messages when Windows fails to load an extension
  module. Now we get for example '%1 is not a valid Win32 application'
  instead of 'error code 193'.

- bpo-1481296: Fixed long(float('nan')) != 0L.

- bpo-1640: Added math.isinf(x), math.isnan(x) and math.copysign(x, y)
  functions.

- bpo-1635: Platform independent creation and representation of NaN and INF.
  float("nan"), float("inf") and float("-inf") now work on every platform
  with IEEE 754 semantics.

- Compiler now generates simpler and faster code for dictionary literals.
  The oparg for BUILD_MAP now indicates an estimated dictionary size.  There
  is a new opcode, STORE_MAP, for adding entries to the dictionary.

- bpo-1638: %zd configure test fails on Linux.

- bpo-1620: New property decorator syntax was modifying the decorator in
  place instead of creating a new decorator object.

- bpo-1538: Avoid copying string in split/rsplit if the split char is not
  found.

- bpo-1553: An erroneous __length_hint__ can make list() raise a
  SystemError.

- PEP 366: Allow explicit relative imports when executing modules inside
  packages with the -m switch via a new module level __package__ attribute.

- bpo-1402: Fix a crash on exit, when another thread is still running, and
  if the deallocation of its frames somehow calls the PyGILState_Ensure() /
  PyGILState_Release() functions.

- Expose the Py_Py3kWarningFlag as sys.py3kwarning.

- bpo-1445: Fix a SystemError when accessing the ``cell_contents`` attribute
  of an empty cell object.

- bpo-1460: The utf-7 incremental decoder did not accept truncated input.
  It now correctly saves its state between chunks of data.

- bpo-1739468: Directories and zipfiles containing a __main__.py file can
  now be directly executed by passing their name to the interpreter. The
  directory/zipfile is automatically inserted as the first entry in
  sys.path.

- bpo-1265: Fix a problem with sys.settrace, if the tracing function uses a
  generator expression when at the same time the executed code is closing a
  paused generator.

- sets and frozensets now have an isdisjoint() method.

- optimize the performance of builtin.sum().

- Fix warnings found by the new version of the Coverity checker.

- The enumerate() built-in function is no longer bounded to sequences
  smaller than LONG_MAX.  Formerly, it raised an OverflowError.  Now,
  automatically shifts from ints to longs.

- bpo-1686386: Tuple's tp_repr did not take into account the possibility of
  having a self-referential tuple, which is possible from C code.  Nor did
  object's tp_str consider that a type's tp_str could do something that
  could lead to an inifinite recursion. Py_ReprEnter() and
  Py_EnterRecursiveCall(), respectively, fixed the issues.

- bpo-1164: It was possible to trigger deadlock when using the 'print'
  statement to write to a file since the GIL was not released as needed.
  Now PyObject_Print() does the right thing along with various tp_print
  implementations of the built-in types and those in the collections module.

- bpo-1147: Exceptions were directly allowing string exceptions in their
  throw() method even though string exceptions no longer allowed.

- bpo-1096: Prevent a segfault from getting the repr of a very deeply nested
  list by using the recursion counter.

- bpo-1202533: Fix infinite recursion calls triggered by calls to
  PyObject_Call() never calling back out to Python code to trigger recursion
  depth updates/checks. Required the creation of a static RuntimeError
  instance in case normalizing an exception put the recursion check value
  past its limit.  Fixes crashers infinite_rec_(1|2|4|5).py.

- bpo-1031213: Decode source line in SyntaxErrors back to its original
  source encoding.

- bpo-1673759: add a missing overflow check when formatting floats with %G.

- Prevent expandtabs() on string and unicode objects from causing a segfault
  when a large width is passed on 32-bit platforms.

- bpo-1733488: Fix compilation of bufferobject.c on AIX.

- bpo-1722485: remove docstrings again when running with -OO.

- Add new attribute names for function objects.  All the func_* become __*__
  attributes.  (Some already existed, e.g., __doc__ and __name__.)

- Add -3 option to the interpreter to warn about features that are
  deprecated and will be changed/removed in Python 3.0.

- bpo-1686487: you can now pass any mapping after '**' in function calls.

- except clauses may now be spelled either "except E, target:" or "except E
  as target:". This is to provide forwards compatibility with Python 3.0.

- Deprecate BaseException.message as per PEP 352.

- bpo-1303614: don't expose object's __dict__ when the dict is inherited
  from a built-in base.

- When __slots__ are set to a unicode string, make it work the same as
  setting a plain string, ie don't expand to single letter identifiers.

- bpo-1191699: Slices can now be pickled.

- bpo-1193128: str.translate() now allows a None argument for translations
  that only remove characters without re-mapping the remaining characters.

- bpo-1682205: a TypeError while unpacking an iterable is no longer masked
  by a generic one with the message "unpack non-sequence".

- Remove unused file Python/fmod.c.

- bpo-1683368: The object.__init__() and object.__new__() methods are now
  stricter in rejecting excess arguments.  The only time when either allows
  excess arguments is when it is not overridden and the other one is.  For
  backwards compatibility, when both are overridden, it is a deprecation
  warning (for now; maybe a Py3k warning later).  Also, type.__init__()
  insists on the same signature as supported by type.__new__().

- bpo-1675423: PyComplex_AsCComplex() now tries to convert an object to
  complex using its __complex__() method before falling back to the
  __float__() method. Therefore, the functions in the cmath module now can
  operate on objects that define a __complex__() method.

- bpo-1623563: allow __class__ assignment for classes with __slots__.  The
  old and the new class are still required to have the same slot names.

- bpo-1642547: Fix an error/crash when encountering syntax errors in complex
  if statements.

- bpo-1462488: Python no longer segfaults when ``object.__reduce_ex__()`` is
  called with an object that is faking its type.

- bpo-1680015: Don't modify __slots__ tuple if it contains a unicode name.

- bpo-1444529: the builtin compile() now accepts keyword arguments.

- bpo-1678647: write a newline after printing an exception in any case, even
  when converting the value to a string failed.

- The dir() function has been extended to call the __dir__() method on its
  argument, if it exists. If not, it will work like before. This allows
  customizing the output of dir() in the presence of a __getattr__().

- bpo-922167: Python no longer segfaults when faced with infinitely
  self-recursive reload() calls (as reported by bug #742342).

- bpo-1675981: remove unreachable code from ``type.__new__()`` method.

- bpo-1491866: change the complex() constructor to allow parthensized forms.
  This means complex(repr(x)) now works instead of raising a ValueError.

- bpo-703779: unset __file__ in __main__ after running a file. This makes
  the filenames the warning module prints much more sensible when a
  PYTHONSTARTUP file is used.

- bpo-697613: Don't exit the interpreter on a SystemExit exception if the -i
  command line option or PYTHONINSPECT environment variable is given, but
  break into the interactive interpreter just like on other exceptions or
  normal program exit.

- bpo-1638879: don't accept strings with embedded NUL bytes in long().

- bpo-1674503: close the file opened by execfile() in an error condition.

- bpo-1674228: when assigning a slice (old-style), check for the
  sq_ass_slice instead of the sq_slice slot.

- When printing an unraisable error, don't print exceptions. before the
  name. This duplicates the behavior whening normally printing exceptions.

- bpo-1653736: Properly discard third argument to slot_nb_inplace_power.

- PEP 352: Raising a string exception now triggers a TypeError. Attempting
  to catch a string exception raises DeprecationWarning.

- bpo-1377858: Fix the segfaulting of the interpreter when an object created
  a weakref on itself during a __del__ call for new-style classes (classic
  classes still have the bug).

- bpo-1579370: Make PyTraceBack_Here use the current thread, not the frame's
  thread state.

- bpo-1630975: Fix crash when replacing sys.stdout in sitecustomize.py.

- Prevent seg fault on shutdown which could occur if an object raised a
  warning.

- bpo-1566280: Explicitly invoke threading._shutdown from Py_Main, to avoid
  relying on atexit.

- bpo-1590891: random.randrange don't return correct value for big number.

- bpo-1586791: Better exception messages for some operations on strings,
  tuples and lists.

- bpo-1067760: Deprecate passing floats to file.seek.

- bpo-1591996: Correctly forward exception in instance_contains().

- bpo-1588287: fix invalid assertion for `1,2` in debug builds.

- bpo-1576657: when setting a KeyError for a tuple key, make sure that the
  tuple isn't used as the "exception arguments tuple".

- bpo-1565514: SystemError not raised on too many nested blocks.

- bpo-1576174: WindowsError now displays the windows error code again, no
  longer the posix error code.

- bpo-1549049: Support long values in structmember, issue warnings if the
  assigned value for structmember fields gets truncated.

- Update the peephole optimizer to remove more dead code (jumps after
  returns) and inline unconditional jumps to returns.

- bpo-1545497: when given an explicit base, int() did ignore NULs embedded
  in the string to convert.

- bpo-1569998: break inside a try statement (outside a loop) is now
  recognized and rejected.

- list.pop(x) accepts any object x following the __index__ protocol.

- A number of places, including integer negation and absolute value, were
  fixed to not rely on undefined behaviour of the C compiler anymore.

- bpo-1566800: make sure that EnvironmentError can be called with any number
  of arguments, as was the case in Python 2.4.

- bpo-1567691: super() and new.instancemethod() now don't accept keyword
  arguments any more (previously they accepted them, but didn't use them).

- Fix a bug in the parser's future statement handling that led to "with" not
  being recognized as a keyword after, e.g., this statement: from __future__
  import division, with_statement

- bpo-1557232: fix seg fault with def f((((x)))) and def f(((x),)).

- Fix %zd string formatting on Mac OS X so it prints negative numbers.

- Allow exception instances to be directly sliced again.

- bpo-1551432: Exceptions do not define an explicit __unicode__ method.
  This allows calling unicode() on exceptions classes directly to succeed.

- bpo-1542051: Exceptions now correctly call PyObject_GC_UnTrack. Also make
  sure that every exception class has __module__ set to 'exceptions'.

- bpo-1550983: emit better error messages for erroneous relative imports (if
  not in package and if beyond toplevel package).

- Overflow checking code in integer division ran afoul of new gcc
  optimizations.  Changed to be more standard-conforming.

- bpo-1542451: disallow continue anywhere under a finally.

- bpo-1546288: fix seg fault in dict_equal due to ref counting bug.

- The return tuple from str.rpartition(sep) is (tail, sep, head) where head
  is the original string if sep was not found.

- bpo-1520864: unpacking singleton tuples in list comprehensions and
  generator expressions (x for x, in ... ) works again.  Fixing this problem
  required changing the .pyc magic number.  This means that .pyc files
  generated before 2.5c2 will be regenerated.

- ``with`` and ``as`` are now keywords.

- bpo-1664966: Fix crash in exec if Unicode filename can't be decoded.

- bpo-1537: Changed GeneratorExit's base class from Exception to
  BaseException.

- bpo-1703448: A joined thread could show up in the threading.enumerate()
  list after the join() for a brief period until it actually exited.

Library
-------

- bpo-2274: Add heapq.heappushpop().

- Add inspect.isabstract(object) to fix bug #2223

- Add a __format__ method to Decimal, to support PEP 3101.

- Add a timing parameter when using trace.Trace to print out timestamps.

- bpo-1627: httplib now ignores negative Content-Length headers.

- bpo-900744: If an invalid chunked-encoding header is sent by a server,
  httplib will now raise IncompleteRead and close the connection instead of
  raising ValueError.

- bpo-1492: The content type of BaseHTTPServer error messages can now be
  overridden.

- bpo-1781: ConfigParser now does not let you add the "default" section
  (ignore-case)

- Removed uses of dict.has_key() from distutils, and uses of callable() from
  copy_reg.py, so the interpreter now starts up without warnings when '-3'
  is given.  More work like this needs to be done in the rest of the stdlib.

- bpo-1916: added isgenerator() and isgeneratorfunction() to inspect.py.

- bpo-1224: Fixed bad url parsing when path begins with double slash.

- ctypes instances that are not or do not contain pointers can now be
  pickled.

- bpo-1966: Break infinite loop in httplib when the servers implements the
  chunked encoding incorrectly.

- Rename rational.py to fractions.py and the rational.Rational class to
  fractions.Fraction, to avoid the name clash with the abstract base class
  numbers.Rational.  See discussion in issue #1682.

- The pickletools module now provides an optimize() function that eliminates
  unused PUT opcodes from a pickle string.

- bpo-2021: Allow tempfile.NamedTemporaryFile and SpooledTemporaryFile to be
  used in with statements by correctly supporting the context management
  protocol.

- bpo-1979: Add rich comparisons to Decimal, and make Decimal comparisons
  involving a NaN follow the IEEE 754 standard.

- bpo-2004: tarfile.py: Use mode 0700 for temporary directories and default
  permissions for missing directories.

- bpo-175006: The debugger used to skip the condition of a "while" statement
  after the first iteration. Now it correctly steps on the expression, and
  breakpoints on the "while" statement are honored on each loop.

- bpo-1765140: add an optional delay argument to FileHandler and its
  subclasses. Defaults to false (existing behaviour), but if true, defers
  opening the file until the first call to emit().

- The pprint module now supports sets and frozensets.

- bpo-1221598: add optional callbacks to ftplib.FTP's storbinary() and
  storlines() methods. (Contributed by Phil Schwartz)

- bpo-1715: include sub-extension modules in pydoc's text output.

- bpo-1836: fix an off-by-one bug in TimedRotatingHandler's rollover time
  calculation.

- bpo-1021: fix a bug to allow basicConfig to accept NOTSET as a level.

- bpo-932563: add LoggerAdapter convenience class to make it easier to add
  contextual information in logging output.

- bpo-1760556: fix a bug to avoid FileHandler throwing an exception in
  flush().

- bpo-1530959: distutils' build command now uses different build directory
  when building extension modules against versions of Python compiled with
  ``--with-pydebug``.

- bpo-1555501: move plistlib from plat-mac directory to general library.

- bpo-1269: fix a bug in pstats.add_callers() and add a unit test file for
  pstats.

- bpo-1669: don't allow shutil.rmtree() to be called on a symlink to a
  directory.

- bpo-1664522: in urllib, don't read non-existing directories in ftp mode,
  returning a 0-byte file -- raise an IOError instead.

- bpo-856047: respect the ``no_proxy`` environment variable when using the
  ``http_proxy`` etc. environment variables in urllib.

- bpo-1178141: add a getcode() method to the addinfourls that urllib.open()
  returns so that you can retrieve the HTTP status code.

- bpo-1003: Fix zipfile decryption check, it would fail zip files with
  extended local headers.

- bpo-1189216: Fix the zipfile module to work on archives with headers past
  the 2**31 byte boundary.

- bpo-1336: fix a race condition in subprocess.Popen if the garbage
  collector kicked in at the wrong time that would cause the process to hang
  when the child wrote to stderr.

- bpo-1146: fix how textwrap breaks a long word that would start in the last
  column of a line.

- bpo-1693149: trace.py --ignore-module - accept multiple comma-separated
  modules to be given.

- bpo-1822: MIMEMultipart.is_multipart() behaves correctly for a
  just-created (and empty) instance. Thanks Jonathan Share.

- bpo-1861: Added an attribute to the sched module which returns an ordered
  list of upcoming events (displayed as named tuples).

- bpo-1837: The queue module now also supports a LIFO queue and a priority
  queue.

- bpo-1048820: Add insert-mode editing to curses.textpad.Textbox (patch by
  Stefan Wehr). Also, fix an off-by-one bug in Textbox.gather().

- bpo-1831: ctypes now raises a TypeError if conflicting positional and
  named arguments are passed to a Structure or Union initializer. When too
  many positional arguments are passed, also a TypeError is raised instead
  of a ValueError.

- Convert the internal ctypes array type cache to a WeakValueDict so that
  array types do not live longer than needed.

- bpo-1786: pdb should use its own stdin/stdout around an exec call and when
  creating a recursive instance.

- bpo-1698398: ZipFile.printdir() crashed because the format string expected
  a tuple type of length six instead of time.struct_time object.

- bpo-1780: The Decimal constructor now accepts arbitrary leading and
  trailing whitespace when constructing from a string.
  Context.create_decimal no longer accepts trailing newlines.

- Decimal.as_tuple(), difflib.find_longest_match() and inspect functions
  that returned a tuple now return a named tuple.

- Doctest now returns results as a named tuple for readability:     (0, 7)
  --> TestResults(failed=0, attempted=7)

- bpo-846388: re.match is interruptible now, which is particularly good for
  long regular expression matches.

- bpo-1137: allow setting buffer_size attribute on pyexpat Parser objects to
  set the character data buffer size.

- bpo-1757: The hash of a Decimal instance is no longer affected by the
  current context.

- bpo-467924: add ZipFile.extract() and ZipFile.extractall() in the zipfile
  module.

- bpo-1646: Make socket support the TIPC protocol.

- bpo-1742: return os.curdir from os.path.relpath() if both arguments are
  equal instead of raising an exception.

- bpo-1637: fix urlparse for URLs like 'http://x.com?arg=/foo'.

- bpo-1698: allow '@' in username parsed by urlparse.py.

- bpo-1735: TarFile.extractall() now correctly sets directory permissions
  and times.

- bpo-1713: posixpath.ismount() claims symlink to a mountpoint is a
  mountpoint.

- bpo-1687: Fxed plistlib.py restricts <integer> to Python int when writing

- bpo-1700: Regular expression inline flags incorrectly handle certain
  unicode characters.

- bpo-1689: PEP 3141, numeric abstract base classes.

- Tk issue #1851526: Return results from Python callbacks to Tcl as Tcl
  objects.

- bpo-1642: Fix segfault in ctypes when trying to delete attributes.

- bpo-1727780: Support loading pickles of random.Random objects created on
  32-bit systems on 64-bit systems, and vice versa. As a consequence of the
  change, Random pickles created by Python 2.6 cannot be loaded in Python
  2.5.

- bpo-1455: The distutils package now supports VS 2005 and VS 2008 for both
  the msvccompiler and cygwincompiler.

- bpo-1531: tarfile.py: Read fileobj from the current offset, do not seek to
  the start.

- bpo-1534: Added a dictionary sys.float_info with information about the
  internal floating point type to the sys module.

- bpo-1429818: patch for trace and doctest modules so they play nicely
  together.

- doctest made a bad assumption that a package's __loader__.get_data()
  method used universal newlines.

- bpo-1705170: contextlib.contextmanager was still swallowing StopIteration
  in some cases. This should no longer happen.

- bpo-1292: On alpha, arm, ppc, and s390 linux systems the --with-system-ffi
  configure option defaults to "yes".

- IN module for FreeBSD 8 is added and preexisting FreeBSD 6 and 7 files are
  updated.

- bpo-1181: unsetenv() is now called when the os.environ.pop() and
  os.environ.clear() methods are used. (See also: bpo-1287)

- ctypes will now work correctly on 32-bit systems when Python is configured
  with --with-system-ffi.

- bpo-1203: ctypes now does work on OS X when Python is built with
  ``--disable-toolbox-glue``.

- collections.deque() now supports a "maxlen" argument.

- itertools.count() is no longer bounded to LONG_MAX.  Formerly, it raised
  an OverflowError.  Now, automatically shifts from ints to longs.

- Added itertools.product() which forms the Cartesian product of the input
  iterables.

- Added itertools.combinations() and itertools.permutations().

- bpo-1541463: optimize performance of cgi.FieldStorage operations.

- Decimal is fully updated to the latest Decimal Specification (v1.66).

- bpo-1153: repr.repr() now doesn't require set and dictionary items to be
  orderable to properly represent them.

- A 'c_longdouble' type was added to the ctypes module.

- bpo-1709599: Run test_1565150 only if the file system is NTFS.

- When encountering a password-protected robots.txt file the RobotFileParser
  no longer prompts interactively for a username and password (bug 813986).

- TarFile.__init__() no longer fails if no name argument is passed and the
  fileobj argument has no usable name attribute (e.g. StringIO).

- The functools module now provides 'reduce', for forward compatibility with
  Python 3000.

- Server-side SSL support and cert verification added, by Bill Janssen.

- socket.ssl deprecated; use new ssl module instead.

- uuid creation is now threadsafe.

- EUC-KR codec now handles the cheot-ga-keut composed make-up hangul
  syllables.

- GB18030 codec now can encode additional two-byte characters that are
  missing in GBK.

- Add new codecs for UTF-32, UTF-32-LE and UTF-32-BE.

- bpo-1704793: Return UTF-16 pair if unicodedata.lookup cannot represent the
  result in a single character.

- bpo-978833: Close https sockets by releasing the _ssl object.

- Change location of the package index to pypi.python.org/pypi

- bpo-1701409: Fix a segfault in printing ctypes.c_char_p and
  ctypes.c_wchar_p when they point to an invalid location.  As a sideeffect
  the representation of these instances has changed.

- tarfile.py: Added "exclude" keyword argument to TarFile.add().

- bpo-1734723: Fix repr.Repr() so it doesn't ignore the maxtuple attribute.

- The urlopen function of urllib2 now has an optional timeout parameter
  (note that it actually works with HTTP, HTTPS, FTP and FTPS connections).

- In ftplib, the FTP.ntransfercmd method, when in passive mode, now uses the
  socket.create_connection function, using the timeout specified at
  connection time.

- bpo-1728403: Fix a bug that CJKCodecs StreamReader hangs when it reads a
  file that ends with incomplete sequence and sizehint argument for .read()
  is specified.

- bpo-1730389: Change time.strptime() to use ``\s+`` instead of ``\s*`` when
  matching spaces in the specified format argument.

- bpo-1668596: distutils now copies data files even if package_dir is empty.
  (See also: bpo-1720897)

- sha now raises a DeprecationWarning upon import.

- md5 now raises a DeprecationWarning upon import.

- bpo-1385: The hmac module now computes the correct hmac when using hashes
  with a block size other than 64 bytes (such as sha384 and sha512).

- mimify now raises a DeprecationWarning upon import.

- MimeWriter now raises a DeprecationWarning upon import.

- tarfile.py: Improved unicode support. Unicode input names are now
  officially supported. Added "errors" argument to the TarFile class.

- urllib.ftpwrapper class now accepts an optional timeout.

- shlex.split() now has an optional "posix" parameter.

- The posixfile module now raises a DeprecationWarning.

- Remove the gopherlib module.  This also leads to the removal of gopher
  support in urllib/urllib2.

- Fix bug in marshal where bad data would cause a segfault due to lack of an
  infinite recursion check.

- Removed plat-freebsd2 and plat-freebsd3 directories (and IN.py in the
  directories).

- HTML-escape the plain traceback in cgitb's HTML output, to prevent the
  traceback inadvertently or maliciously closing the comment and injecting
  HTML into the error page.

- The popen2 module and os.popen* are deprecated.  Use the subprocess
  module.

- Added an optional credentials argument to SMTPHandler, for use with SMTP
  servers which require authentication.

- bpo-1695948: Added optional timeout parameter to SocketHandler.

- bpo-1652788: Minor fix for currentframe.

- bpo-1598415: Added WatchedFileHandler to better support external log file
  rotation using e.g. newsyslog or logrotate. This handler is only useful in
  Unix/Linux environments.

- bpo-1706381: Specifying the SWIG option "-c++" in the setup.py file (as
  opposed to the command line) will now write file names ending in ".cpp"
  too.

- As specified in RFC 2616, an HTTP response like 2xx indicates that the
  client's request was successfully received, understood, and accepted.  Now
  in these cases no error is raised in urllib (issue #1177) and urllib2.

- bpo-1290505: time.strptime's internal cache of locale information is now
  properly recreated when the locale is changed.

- bpo-1685563: remove (don't add) duplicate paths in distutils.MSVCCompiler.

- Added a timeout parameter to the constructor of other protocols
  (telnetlib, ftplib, smtplib and poplib). This is second part of the work
  started with create_connection() and timeout in httplib, and closes patch
  #723312.

- bpo-1676823: Added create_connection() to socket.py, which may be called
  with a timeout, and use it from httplib (whose HTTPConnection and
  HTTPSConnection now accept an optional timeout).

- bpo-978833: Revert r50844, as it broke _socketobject.dup.

- bpo-1675967: re patterns pickled with Python 2.4 and earlier can now be
  unpickled with Python 2.5 and newer.

- bpo-1630118: add a SpooledTemporaryFile class to tempfile.py.

- bpo-1273829: os.walk() now has a "followlinks" parameter. If set to True
  (which is not the default), it visits symlinks pointing to directories.

- bpo-1681228: the webbrowser module now correctly uses the default GNOME or
  KDE browser, depending on whether there is a session of one of those
  present. Also, it tries the Windows default browser before trying Mozilla
  variants.

- bpo-1339796: add a relpath() function to os.path.

- bpo-1681153: the wave module now closes a file object it opened if
  initialization failed.

- bpo-767111: fix long-standing bug in urllib which caused an AttributeError
  instead of an IOError when the server's response didn't contain a valid
  HTTP status line.

- bpo-957650: "%var%" environment variable references are now properly
  expanded in ntpath.expandvars(), also "~user" home directory references
  are recognized and handled on Windows.

- bpo-1429539: pdb now correctly initializes the __main__ module for the
  debugged script, which means that imports from __main__ work correctly
  now.

- The nonobvious commands.getstatus() function is now deprecated.

- bpo-1393667: pdb now has a "run" command which restarts the debugged
  Python program, optionally with different arguments.

- bpo-1649190: Adding support for _Bool to ctypes as c_bool.

- bpo-1530482: add pydoc.render_doc() which returns the documentation for a
  thing instead of paging it to stdout, which pydoc.doc() does.

- bpo-1533909: the timeit module now accepts callables in addition to
  strings for the code to time and the setup code. Also added two
  convenience functions for instantiating a Timer and calling its methods.

- bpo-1537850: tempfile.NamedTemporaryFile now has a "delete" parameter
  which can be set to False to prevent the default delete-on-close behavior.

- bpo-1581073: add a flag to textwrap that prevents the dropping of
  whitespace while wrapping.

- bpo-1603688: ConfigParser.SafeConfigParser now checks values that are set
  for invalid interpolation sequences that would lead to errors on reading
  back those values.

- Added support for the POSIX.1-2001 (pax) format to tarfile.py. Extended
  and cleaned up the test suite. Added a new testtar.tar.

- bpo-1449244: Support Unicode strings in
  email.message.Message.{set_charset,get_content_charset}.

- bpo-1542681: add entries for "with", "as" and "CONTEXTMANAGERS" to pydoc's
  help keywords.

- bpo-1555098: use str.join() instead of repeated string concatenation in
  robotparser.

- bpo-1635454: the csv.DictWriter class now includes the offending field
  names in its exception message if you try to write a record with a
  dictionary containing fields not in the CSV field names list.

- bpo-1668100: urllib2 now correctly raises URLError instead of OSError if
  accessing a local file via the file:// protocol fails.

- bpo-1677862: Require a space or tab after import in .pth files.

- bpo-1192590: Fix pdb's "ignore" and "condition" commands so they trap the
  IndexError caused by passing in an invalid breakpoint number.

- bpo-1599845: Add an option to disable the implicit calls to server_bind()
  and server_activate() in the constructors for TCPServer,
  SimpleXMLRPCServer and DocXMLRPCServer.

- bpo-1531963: Make SocketServer.TCPServer's server_address always be equal
  to calling getsockname() on the server's socket. Fixed by patch #1545011.

- bpo-742598: Add .timeout attribute to SocketServer that calls
  .handle_timeout() when no requests are received.

- bpo-1651235: When a tuple was passed to a ctypes function call, Python
  would crash instead of raising an error.

- bpo-1646630: ctypes.string_at(buf, 0) and ctypes.wstring_at(buf, 0)
  returned string up to the first NUL character.

- bpo-957003: Implement smtplib.LMTP.

- bpo-1481079: add support for HTTP_REFERER to CGIHTTPServer.

- bpo-1675424: Added tests for uncovered code in the zipfile module.  The
  KeyError raised by Zipfile.getinfo for nonexistent names now has a
  descriptive message.

- bpo-1115886: os.path.splitext('.cshrc') gives now ('.cshrc', '').

- unittest now verifies more of its assumptions. In particular, TestCase and
  TestSuite subclasses (not instances) are no longer accepted in
  TestSuite.addTest(). This should cause no incompatibility since it never
  made sense with ordinary subclasses -- the failure just occurred later,
  with a more cumbersome exception.

- bpo-787789: allow passing custom TestRunner instances to unittest's main()
  function.

- bpo-1550273: fix a few bugs in unittest and add a comprehensive test suite
  for the module. (See also: bpo-1550272)

- bpo-1001604: glob.glob() now returns unicode filenames if it was given a
  unicode argument and os.listdir() returns unicode filenames.

- bpo-1673619: setup.py identifies extension modules it doesn't know how to
  build and those it knows how to build but that fail to build.

- bpo-912410: Replace HTML entity references for attribute values in
  HTMLParser.

- bpo-1663234: you can now run doctest on test files and modules using
  "python -m doctest [-v] filename ...".

- bpo-1121142: Implement ZipFile.open.

- Taught setup.py how to locate Berkeley DB on Macs using MacPorts.

- Added heapq.merge() for merging sorted input streams.

- Added collections.namedtuple() for assigning field names to tuples.

- Added itertools.izip_longest().

- Have the encoding package's search function dynamically import using
  absolute import semantics.

- bpo-1647484: Renamed GzipFile's filename attribute to name.

- bpo-1517891: Mode 'a' for ZipFile now creates the file if it doesn't
  exist.

- bpo-698833: Support file decryption in zipfile.

- bpo-685268: Consider a package's __path__ in imputil.

- bpo-1463026: Support default namespace in XMLGenerator.

- bpo-1571379: Make trace's --ignore-dir facility work in the face of
  relative directory names.

- bpo-1600860: Search for shared python library in LIBDIR, not
  lib/python/config, on "linux" and "gnu" systems.

- bpo-1652681: tarfile.py: create nonexistent files in append mode and allow
  appending to empty files.

- bpo-1124861: Automatically create pipes if GetStdHandle fails in
  subprocess.

- bpo-1634778: add missing encoding aliases for iso8859_15 and iso8859_16.

- bpo-1638243: the compiler package is now able to correctly compile a with
  statement; previously, executing code containing a with statement compiled
  by the compiler package crashed the interpreter.

- bpo-1643943: Fix time.strptime's support for the %U directive.

- bpo-1507247: tarfile.py: use current umask for intermediate directories.

- bpo-1627441: close sockets properly in urllib2.

- bpo-494589: make ntpath.expandvars behave according to its docstring.

- Changed platform module API python_version_tuple() to actually return a
  tuple (it used to return a list).

- Added new platform module APIs python_branch(), python_revision(),
  python_implementation() and linux_distribution().

- Added support for IronPython and Jython to the platform module.

- The sets module has been deprecated.  Use the built-in set/frozenset types
  instead.

- bpo-1610795: make ctypes.util.find_library work on BSD systems.

- Fixes for 64-bit Windows: In ctypes.wintypes, correct the definitions of
  HANDLE, WPARAM, LPARAM data types.  Make parameterless foreign function
  calls work.

- The version number of the ctypes package changed to "1.1.0".

- bpo-1627575: logging: Added _open() method to FileHandler which can be
  used to reopen files. The FileHandler instance now saves the encoding
  (which can be None) in an attribute called "encoding".

- bpo-411881: logging.handlers: bare except clause removed from
  SMTPHandler.emit. Now, only ImportError is trapped.

- bpo-411881: logging.handlers: bare except clause removed from
  SocketHandler.createSocket. Now, only socket.error is trapped.

- bpo-411881: logging: bare except clause removed from LogRecord.__init__.
  Now, only ValueError, TypeError and AttributeError are trapped.

- bpo-1504073: Fix tarfile.open() for mode "r" with a fileobj argument.

- bpo-1182394: Speed up ``HMAC.hexdigest``.  (Patch by Shane Holloway.)

- bpo-1262036: Prevent TarFiles from being added to themselves under certain
  conditions.

- bpo-1230446: tarfile.py: fix ExFileObject so that read() and tell() work
  correctly together with readline().

- bpo-1484695: The tarfile module now raises a HeaderError exception if a
  buffer given to frombuf() is invalid.

- bpo-1503765: Fix a problem in logging.config with spaces in comma-
  separated lists read from logging config files.

- bpo-1604907: Fix problems in logging.handlers caused at logging shutdown
  when syslog handlers fail to initialize because of syslogd problems.

- bpo-1608267: fix a race condition in os.makedirs() if the directory to be
  created is already there.

- bpo-1610437: fix a tarfile bug with long filename headers.

- bpo-1371075: Make ConfigParser accept optional dict type for ordering,
  sorting, etc.

- bpo-1563807: _ctypes built on AIX fails with ld ffi error.

- bpo-1598620: A ctypes Structure cannot contain itself.

- bpo-1070046: Marshal new-style objects like InstanceType in xmlrpclib.

- cStringIO.truncate(-1) now raises an IOError, like StringIO and regular
  files.

- bpo-1472877: Fix Tix subwidget name resolution.

- bpo-1594554: Always close a tkSimpleDialog on ok(), even if an exception
  occurs.

- bpo-1538878: Don't make tkSimpleDialog dialogs transient if the parent
  window is withdrawn.

- bpo-1597824: return the registered function from atexit.register() to
  facilitate usage as a decorator.

- bpo-1360200: Use unmangled_version RPM spec field to deal with file name
  mangling.

- bpo-1359217: Process 2xx response in an ftplib transfer that precedes an
  1xx response.

- bpo-1355023: support whence argument for GzipFile.seek.

- bpo-1065257: Support passing open files as body in
  HTTPConnection.request().

- bpo-1569790: mailbox.py: Maildir.get_folder() and MH.get_folder() weren't
  passing the message factory on to newly created Maildir/MH objects.

- bpo-1514543: mailbox.py: In the Maildir class, report errors if there's a
  filename clash instead of possibly losing a message. (Patch by David
  Watson.)

- bpo-1514544: Try to ensure that messages/indexes have been physically
  written to disk after calling .flush() or .close(). (Patch by David
  Watson.)

- bpo-1592250: Add elide argument to Tkinter.Text.search.

- bpo-838546: Make terminal become controlling in pty.fork().

- bpo-1351744: Add askyesnocancel helper for tkMessageBox.

- bpo-1060577: Extract list of RPM files from spec file in bdist_rpm.

- bpo-1586613: fix zlib and bz2 codecs' incremental en/decoders.

- bpo-1583880: fix tarfile's problems with long names and posix/ GNU modes.

- bpo-1586448: the compiler module now emits the same bytecode for list
  comprehensions as the built-in compiler, using the LIST_APPEND opcode.

- Fix codecs.EncodedFile which did not use file_encoding in 2.5.0, and fix
  all codecs file wrappers to work correctly with the "with" statement (bug
  #1586513).

- Lib/modulefinder.py now handles absolute and relative imports correctly.

- bpo-1567274: Support SMTP over TLS.

- bpo-1560695: Add .note.GNU-stack to ctypes' sysv.S so that ctypes isn't
  considered as requiring executable stacks.

- ctypes callback functions only support 'fundamental' data types as result
  type.  Raise an error when something else is used.  This is a partial fix
  for Bug #1574584.

- Fix turtle so that time.sleep is imported for the entire library. Allows
  the demo2 function to be executed on its own instead of only when the
  module is run as a script.

- bpo-1565150: Fix subsecond processing for os.utime on Windows.

- Support for MSVC 8 was added to bdist_wininst.

- bpo-1446043: correctly raise a LookupError if an encoding name given to
  encodings.search_function() contains a dot.

- bpo-1560617: in pyclbr, return full module name not only for classes, but
  also for functions.

- bpo-1457823: cgi.(Sv)FormContentDict's constructor now takes
  keep_blank_values and strict_parsing keyword arguments.

- bpo-1566602: correct failure of posixpath unittest when $HOME ends with a
  slash.

- bpo-1565661: in webbrowser, split() the command for the default GNOME
  browser in case it is a command with args.

- Made the error message for time.strptime when the data and format do match
  be more clear.

- Fix a bug in traceback.format_exception_only() that led to an error being
  raised when print_exc() was called without an exception set. In version
  2.4, this printed "None", restored that behavior.

- Make webbrowser.BackgroundBrowser usable in Windows (it wasn't because the
  close_fds arg to subprocess.Popen is not supported).

- bpo-1504333: Reverted change to sgmllib because it introduced an infinite
  loop.

- bpo-1553314: Fix the inspect.py slowdown that was hurting IPython & SAGE
  by adding smarter caching in inspect.getmodule()

- Fix missing import of the types module in logging.config.

- bpo-1550886: Fix decimal module context management implementation to match
  the localcontext() example from PEP 343.

- bpo-1545341: The 'classifier' keyword argument to the Distutils setup()
  function now accepts tuples as well as lists.

- bpo-1541863: uuid.uuid1 failed to generate unique identifiers on systems
  with low clock resolution.

- bpo-1531862: Do not close standard file descriptors in subprocess.

- Fix utf-8-sig incremental decoder, which didn't recognise a BOM when the
  first chunk fed to the decoder started with a BOM, but was longer than 3
  bytes.

- The implementation of UnicodeError objects has been simplified (start and
  end attributes are now stored directly as Py_ssize_t members).

- bpo-829951: In the smtplib module, SMTP.starttls() now complies with RFC
  3207 and forgets any knowledge obtained from the server not obtained from
  the TLS negotiation itself.  Patch contributed by Bill Fenner.

- bpo-1339: The smtplib.SMTP class has been refactored a bit such that the
  SMTP.starttls() caller no longer needs to call ehlo() beforehand.
  SMTP.starttls() now raises an exception of the server does not claim to
  support starttls.  Adds the SMTP.ehlo_or_helo_if_needed() method.  Patch
  contributed by Bill Fenner.

- bpo-1089358: Add signal.siginterrupt, a wrapper around siginterrupt(3).

- bpo-1657: added select.epoll and select.kqueue.

- bpo-1506171: added operator.methodcaller().

- bpo-1826: operator.attrgetter() now supports dotted attribute paths.

- bpo-1957: syslogmodule: Release GIL when calling syslog(3).

- bpo-2112: mmap.error is now a subclass of EnvironmentError and not a
  direct EnvironmentError.

- bpo-2111: mmap segfaults when trying to write a block opened with
  PROT_READ.

- bpo-2063: correct order of utime and stime in os.times() result on
  Windows.

- bpo-1736: Fix file name handling of _msi.FCICreate.

- Updated ``big5hkscs`` codec to the HKSCS revision of 2004.

- bpo-1940: make it possible to use curses.filter() before curses.initscr()
  as the documentation says.

- Backport of _fileio module from Python 3.0.

- bpo-1087741: mmap.mmap is now a class, not a factory function. It is also
  subclassable now.

- bpo-1648: added ``sys.getprofile()`` and ``sys.gettrace()``.

- bpo-1663329: added ``os.closerange()`` function to quickly close a range
  of file descriptors without considering errors.

- bpo-976880: ``mmap`` objects now have an ``rfind`` method that works as
  expected. ``mmap.find`` also takes an optional ``end`` parameter.

- _winreg's HKEY object has gained __enter__ and __exit__ methods to support
  the context management protocol.  The _winreg module also gained a new
  function ``ExpandEnvironmentStrings`` to expand REG_EXPAND_SZ keys.

- itertools.starmap() now accepts any iterable input. Previously, it
  required the function inputs to be tuples.

- itertools.chain() now has an alternate constructor, chain.from_iterable().

- bpo-1646: Make socket support TIPC. The socket module now has support for
  TIPC under Linux, see http://tipc.sf.net/ for more information.

- Added interface for Windows' WSAIoctl to socket object and added an
  example for a simple network sniffer.

- bpo-1301: Bad assert in _tkinter fixed.

- Added bdist_wininst executable for VS 2008.

- bpo-1604: collections.deque.__init__(iterable) now clears any prior
  contents before adding elements from the iterable.  This fix brings the
  behavior into line with that for list.__init__().

- Added wide char functions to msvcrt module: getwch, getwche, putwch and
  ungetwch. The functions accept or return unicode.

- os.access now returns True on Windows for any existing directory.

- Added warnpy3k function to the warnings module.

- Marshal.dumps() now expects exact type matches for int, long, float,
  complex, tuple, list, dict, set, and frozenset.  Formerly, it would
  silently miscode subclasses of those types.  Now, it raises a ValueError
  instead.

- bpo-1388440: Add set_completion_display_matches_hook and
  get_completion_type to readline.

- bpo-1649098: Avoid declaration of zero-sized array declaration in
  structure.

- Removed the rgbimg module; been deprecated since Python 2.5.

- bpo-1721309: prevent bsddb module from freeing random memory.

- bpo-1233: fix bsddb.dbshelve.DBShelf append method to work as intended for
  RECNO databases.

- pybsddb.sf.net Bug #477182: Load the database flags at database open time
  so that opening a database previously created with the DB_DUP or
  DB_DUPSORT flag set will keep the proper behavior on subsequent opens.
  Specifically: dictionary assignment to a DB object will replace all values
  for a given key when the database allows duplicate values.  DB users
  should use DB.put(k, v) when they want to store duplicates; not DB[k] = v.

- Add the bsddb.db.DBEnv.lock_id_free method.

- bpo-1686475: Support stat'ing open files on Windows again.

- bpo-1185447: binascii.b2a_qp() now correctly quotes binary characters with
  ASCII value less than 32. Also, it correctly quotes dots only if they
  occur on a single line, as opposed to the previous behavior of quoting
  dots if they are the second character of any line.

- bpo-1622896: fix a rare corner case where the bz2 module raised an error
  in spite of a succesful compression.

- bpo-1654417: make operator.{get,set,del}slice use the full range of
  Py_ssize_t.

- bpo-1646728: datetime.fromtimestamp fails with negative fractional times.
  With unittest.

- bpo-1490190: posixmodule now includes os.chflags() and os.lchflags()
  functions on platforms where the underlying system calls are available.

- bpo-1494140: Add documentation for the new struct.Struct object.

- bpo-1432399: Support the HCI protocol for bluetooth sockets

- bpo-1657276: Make NETLINK_DNRTMSG conditional.

- bpo-1653736: Complain about keyword arguments to time.isoformat.

- bpo-1486663: don't reject keyword arguments for subclasses of built-in
  types.

- bpo-1610575: The struct module now supports the 't' code, for C99 _Bool.

- bpo-1635058: ensure that htonl and friends never accept or return negative
  numbers, per the underlying C implementation.

- bpo-1544279: Improve thread-safety of the socket module by moving the
  sock_addr_t storage out of the socket object.

- bpo-1019808: fix bug that causes an incorrect error to be returned when a
  socket timeout is set and a connection attempt fails.

- Speed up function calls into the math module.

- bpo-1588217: don't parse "= " as a soft line break in binascii's a2b_qp()
  function, instead leave it in the string as quopri.decode() does.

- bpo-1599782: Fix segfault on bsddb.db.DB().type().

- bpo-1567666: Emulate GetFileAttributesExA for Win95.

- bpo-1576166: Support os.utime for directories on Windows NT+.

- bpo-1572724: fix typo ('=' instead of '==') in _msi.c.

- bpo-1572832: fix a bug in ISO-2022 codecs which may cause segfault when
  encoding non-BMP unicode characters.

- bpo-1556784: allow format strings longer than 127 characters in datetime's
  strftime function.

- Fix itertools.count(n) to work with negative numbers again.

- RLIMIT_SBSIZE was added to the resource module where available.

- bpo-1551427: fix a wrong NULL pointer check in the win32 version of
  os.urandom().

- bpo-1548092: fix curses.tparm seg fault on invalid input.

- bpo-1114: fix curses module compilation on 64-bit AIX, & possibly other
  64-bit LP64 platforms where attr_t is not the same size as a long.
  (Contributed by Luke Mewburn.)

- bpo-1550714: fix SystemError from itertools.tee on negative value for n.

- Fixed a few bugs on cjkcodecs: - gbk and gb18030 codec now handle U+30FB
  KATAKANA MIDDLE DOT   correctly. - iso2022_jp_2 codec now encodes into G0
  for KS X 1001, GB2312   codepoints to conform the standard. - iso2022_jp_3
  and iso2022_jp_2004 codec can encode JIS X 0213:2   codepoints now.

- bpo-1552726: in readline.c, avoid repeatedly polling in interactive mode
  by only placing a timeout on the select() if an input hook has been
  defined.  This prevents an interactive Python from waking up 10 times per
  second.  Patch by Richard Boulton.

- fixed a bug with bsddb.DB.stat: the flags and txn keyword arguments were
  transposed.

- Added support for linking the bsddb module against BerkeleyDB 4.5.x, 4.6.x
  and 4.7.x.

- bpo-1633621: if curses.resizeterm() or curses.resize_term() is called,
  update _curses.LINES, _curses.COLS, curses.LINES and curses.COLS.

- Fix an off-by-one bug in locale.strxfrm().

- Fix libffi configure for hppa*-*-linux* | parisc*-*-linux*.

- Build using system ffi library on arm*-linux*.

- bpo-1372: zlibmodule.c: int overflow in PyZlib_decompress

- bsddb module: Fix memory leak when using database cursors on databases
  without a DBEnv.

- The sqlite3 module was updated to pysqlite 2.4.1.

IDLE
----

- bpo-813342: Start the IDLE subprocess with -Qnew if the parent is started
  with that option.

- IDLE: Honor the "Cancel" action in the save dialog (Debian bug #299092).

Tests
-----

- bpo-30357: test_thread: setUp() now uses support.threading_setup() and
  support.threading_cleanup() to wait until threads complete to avoid random
  side effects on following tests. Initial patch written by Grzegorz
  Grzywacz.

- Refactor test_logging to use unittest.

- Refactor test_profile and test_cprofile to use the same code to profile.

- Make test_runpy reentrant by fixing _check_module to clear out any module
  being tested.  Was causing an error by __import__ doing a reload on the
  second run and thus suppressing bytecode recreation.

- Capture socket connection resets and timeouts in test_socket_ssl and
  test_urllib2net and raise test.test_support.ResourceDenied.

- bpo-1559413: Fix test_cmd_line if sys.executable contains a space.

- Added test.test_support.TransientResource which is a context manager to
  surround calls to resources that are not guaranteed to work even if
  test.test_support.requires says that the resource should exist.

- Added a test for slicing of an exception.

- Added test.test_support.EnvironmentVarGuard.  It's a class that provides a
  context manager so that one can temporarily set or unset environment
  variables.

- Added some tests for modulefinder.

- Converted test_imp to use unittest.

- Fix bsddb test_basics.test06_Transactions to check the version number
  properly.

- test.test_support.catch_warning is a new context manager that can be used
  to catch the warnings issued by the warning framework.

Tools/Demos
-----------

- Tools/scripts/reindent.py now creates the backup file using shutil.copy to
  preserve user/group and permissions. Added also a --nobackup option to not
  create the backup if the user is concerned regarding this.  Check issue
  #1050828 for more details.

- Tools/scripts/win_add2path.py was added. The simple script modifes the
  PATH environment var of the HKCU tree and adds the python bin and script
  directory.

- Tools/18n/pygettext.py was added to the list of scripts installed by
  Tools/scripts/setup.py (tracker item 642309).

- Added IronPython and Jython support to pybench (part of which was patch
  #1563844).

- Made some minor changes to pybench output to allow the user to see which
  Python version is running pybench.

- Added support for the new platform module feature
  platform.python_implementation(); this will now be saved in the benchmark
  pickle.

Documentation
-------------

- RFE #1765140: Updated documentation on FileHandler and subclasses to
  include new optional delay argument.

- bpo-932563: Added section on getting contextual information into logging
  output, and added documentation for the new LoggerAdapter class.

- bpo-1295: Added information about caching of formatted exception
  information in the LogRecord by Formatter.format().

- bpo-1637365: add subsection about "__name__ == __main__" to the Python
  tutorial.

- bpo-1698768: updated the "using Python on the Mac" intro.

- bpo-1569057: Document that calling file.next() when the file is open for
  writing is undefined.

- bpo-1489771: the syntax rules in Python Reference Manual were updated to
  reflect the current Python syntax.

- bpo-1686451: Fix return type for PySequence_{Count,Index,Fast_GET_SIZE}.

- bpo-1679379: add documentation for fnmatch.translate().

- bpo-1629566: clarify the docs on the return values of parsedate() and
  parsedate_tz() in email.utils and rfc822.

- bpo-1671450: add a section about subclassing built-in types to the
  "extending and embedding" tutorial.

- bpo-1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs.

- bpo-1565919: document set types in the Language Reference.

- bpo-1546052: clarify that PyString_FromString(AndSize) copies the string
  pointed to by its parameter.

- bpo-1566663: remove obsolete example from datetime docs.

- bpo-1541682: Fix example in the "Refcount details" API docs. Additionally,
  remove a faulty example showing PySequence_SetItem applied to a newly
  created list object and add notes that this isn't a good idea.

Tools/Demos
-----------

- bpo-1552024: add decorator support to unparse.py demo script.

- Make auto-generated python.vim file list built-ins and exceptions in
  alphatbetical order.  Makes output more deterministic and easier to tell
  if the file is stale or not.

- bpo-1546372: Fixed small bugglet in pybench that caused a missing file not
  to get reported properly.

Build
-----

- Have the search path for building extensions follow the declared order in
  $CPPFLAGS and $LDFLAGS when adding directories from those environment
  variables.

- bpo-1983: Added a check to pyport to verify that sizeof(pid_t) is smaller
  or equal sizeof(long).

- bpo-1234: Fixed semaphore errors on AIX 5.2

- bpo-1726: Remove Python/atof.c from PCBuild/pythoncore.vcproj.

- Removed PCbuild8/ directory and added a new build directory for VS 2005
  based on the VS 2008 build directory to PC/VS8.0. The script
  PCbuild/vs8to9.py was added to sync changes from PCbuild to PC/VS8.0.

- Moved PCbuild/ directory for VS 2003 to PC/VS7.1 and renamed PCBuild9/
  directory to PCBuild/.

- bpo-1699: Define _BSD_SOURCE only on OpenBSD.

- bpo-1608: use -fwrapv when GCC supports it.  This is important, newer GCC
  versions may optimize away overflow buffer overflow checks without this
  option!

- bpo-1418: Make the AC_REPLACE_FUNCS object files actually work.

- Add a FAST_LOOPS build option that speeds-up looping by trading away
  periodic threadstate and signal checking in tight loops.  By default, this
  option is turned-off.  It should only be enabled in debugged, performance
  critical applications.

- bpo-786737: Allow building in a tree of symlinks pointing to a readonly
  source.

- bpo-1737210: Change Manufacturer of Windows installer to PSF.

- bpo-1746880: Correctly install DLLs into system32 folder on Win64.

- Define _BSD_SOURCE, to get access to POSIX extensions on OpenBSD 4.1+.

- Stop supporting AtheOS and cause a build error in configure for the
  platform.

- bpo-1655392: don't add -L/usr/lib/pythonX.Y/config to the LDFLAGS returned
  by python-config if Python was built with --enable-shared because that
  prevented the shared library from being used.

- bpo-1569798: fix a bug in distutils when building Python from a directory
  within sys.exec_prefix.

- bpo-1675511: Use -Kpic instead of -xcode=pic32 on Solaris/x86.

- Disable _XOPEN_SOURCE on NetBSD 1.x.

- configure now checks whether gcc supports the PyArg_ParseTuple format
  attribute.

- bpo-1578513: Cross compilation was broken by a change to configure. Repair
  so that it's back to how it was in 2.4.3.

- bpo-1576954: Update VC6 build directory; remove redundant files in VC7.

- bpo-1568842: Fix test for uintptr_t.

- bpo-1540470: for OpenBSD 4.0.

- Fix build failure on kfreebsd and on the hurd.

- Fix the build of the library reference in info format.

- Allow Emacs 22 for building the documentation in info format.

- Makefile.pre.in(buildbottest): Run an optional script pybuildbot.identify
  to include some information about the build environment.

C API
-----

- Unified naming convention for free lists and their limits. All free lists
  in Object/ are named ``free_list``, the counter ``numfree`` and the upper
  limit is a macro ``PyName_MAXFREELIST`` inside an #ifndef block.

- ``PySet_Add()`` can now modify a newly created frozenset.  Similarly to
  ``PyTuple_SetItem``, it can be used to populate a brand new frozenset; but
  it does not steal a reference to the added item.

- Added ``PySet_Check()`` and ``PyFrozenSet_Check()`` to the set API.

- Backport of PyUnicode_FromString(), _FromStringAndSize(), _Format and
  _FormatV from Python 3.0. Made PyLong_AsSsize_t and PyLong_FromSsize_t
  public functions.

- bpo-1720595: add T_BOOL to the range of structmember types.

- bpo-1534: Added ``PyFloat_GetMax()``, ``PyFloat_GetMin()`` and
  ``PyFloat_GetInfo()`` to the float API.

- bpo-1521: On 64bit platforms, using PyArgs_ParseTuple with the t# of w#
  format code incorrectly truncated the length to an int, even when
  PY_SSIZE_T_CLEAN is set.  The str.decode method used to return incorrect
  results with huge strings.

- bpo-1629: Renamed Py_Size, Py_Type and Py_Refcnt to Py_SIZE, Py_TYPE and
  Py_REFCNT.

- PEP 3123: Provide forward compatibility with Python 3.0, while keeping
  backwards compatibility. Add Py_Refcnt, Py_Type, Py_Size, and
  PyVarObject_HEAD_INIT.

- Py_ssize_t fields work in structmember when HAVE_LONG_LONG is not defined.

- bpo-1733960: Allow T_LONGLONG to accept ints.

- T_PYSSIZET can now be used in PyMemberDef lists for Py_ssize_t members.

- Added a new API function ``PyImport_ImportModuleNoBlock``.

- bpo-1637022: Prefix AST symbols with _Py_.

- Fix some leftovers from the conversion from int to Py_ssize_t (relevant to
  strings and sequences of more than 2**31 items).

- Make _PyGILState_NoteThreadState() static, it was not used anywhere
  outside of pystate.c and should not be necessary.

- ``PyImport_Import`` and ``PyImport_ImportModule`` now always do absolute
  imports. In earlier versions they might have used relative imports under
  some conditions.

- Added case insensitive comparison methods ``PyOS_stricmp(char*, char*)``
  and ``PyOS_strnicmp(char*, char*, Py_ssize_t)``.

- bpo-1542693: remove semi-colon at end of PyImport_ImportModuleEx macro so
  it can be used as an expression.

Windows
-------

- bpo-1706: Drop support for Win9x, WinME and NT4. Python now requires
  Windows 2000 or greater. The _WINVER and NTDDI_VERSION macros are set to
  Win2k for x86/32bit builds and WinXP for AMD64 builds.

- Conditionalize definition of _CRT_SECURE_NO_DEPRECATE and
  _CRT_NONSTDC_NO_DEPRECATE.

- bpo-1216: Restore support for Visual Studio 2002.

macOS
-----

- cfmfile now raises a DeprecationWarning.

- buildtools now raises a DeprecationWarning.

- Removed the macfs module.  It had been deprecated since Python 2.5. This
  lead to the deprecation of macostools.touched() as it relied solely on
  macfs and was a no-op under OS X.


**(For information about older versions, consult the HISTORY file.)**
PK
%�\~Fm�P	P	READMEnu�[���Python Misc subdirectory
========================

This directory contains files that wouldn't fit in elsewhere.  Some
documents are only of historic importance.

Files found here
----------------

ACKS                    Acknowledgements
AIX-NOTES               Notes for building Python on AIX
BeOS-NOTES              Notes for building on BeOS
BeOS-setup.py           setup.py replacement for BeOS, see BeOS-NOTES
build.sh                Script to build and test latest Python from the repository
cheatsheet              Quick summary of Python by Ken Manheimer
developers.txt          A history of who got developer permissions, and why
gdbinit                 Handy stuff to put in your .gdbinit file, if you use gdb
HISTORY                 News from previous releases -- oldest last
indent.pro              GNU indent profile approximating my C style
maintainers.rst         A list of maintainers for library modules
NEWS                    News for this release (for some meaning of "this")
NEWS.help               How to edit NEWS
Porting                 Mini-FAQ on porting to new platforms
PURIFY.README           Information for Purify users
pymemcompat.h           Memory interface compatibility file.
python-config.in        Python script template for python-config
python.man              UNIX man page for the python interpreter
python-mode.el          Emacs mode for editing Python programs
python.pc.in            Package configuration info template for pkg-config
python-wing.wpr         Wing IDE project file
README                  The file you're reading now
README.coverity         Information about running Coverity's Prevent on Python
README.klocwork         Information about running Klocwork's K7 on Python
README.OpenBSD          Help for building problems on OpenBSD
README.valgrind         Information for Valgrind users, see valgrind-python.supp
RFD                     Request For Discussion about a Python newsgroup
setuid-prog.c           C helper program for set-uid Python scripts
SpecialBuilds.txt       Describes extra symbols you can set for debug builds
TextMate                A TextMate bundle for Python development
valgrind-python.supp    Valgrind suppression file, see README.valgrind
vgrindefs               Python configuration for vgrind (a generic pretty printer)
Vim                     Python development utilities for the Vim editor
PK
%�\��p4�4�
cheatsheetnu�[���                          Python 2.3 Quick Reference


 25 Jan 2003  upgraded by Raymond Hettinger for Python 2.3
 16 May 2001  upgraded by Richard Gruet and Simon Brunning for Python 2.0
 2000/07/18  upgraded by Richard Gruet, rgruet@intraware.com for Python 1.5.2
from V1.3 ref
1995/10/30, by Chris Hoffmann, choffman@vicorp.com

Based on:
    Python Bestiary, Author: Ken Manheimer, ken.manheimer@nist.gov
    Python manuals, Authors: Guido van Rossum and Fred Drake
    What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka
    python-mode.el, Author: Tim Peters, tim_one@email.msn.com

    and the readers of comp.lang.python

Python's nest: http://www.python.org     Developement: http://
python.sourceforge.net/    ActivePython : http://www.ActiveState.com/ASPN/
Python/
newsgroup: comp.lang.python  Help desk: help@python.org
Resources: http://starship.python.net/
           http://www.vex.net/parnassus/
           http://aspn.activestate.com/ASPN/Cookbook/Python
FAQ:       http://www.python.org/cgi-bin/faqw.py
Full documentation: http://www.python.org/doc/
Excellent reference books:
           Python Essential Reference by David Beazley (New Riders)
           Python Pocket Reference by Mark Lutz (O'Reilly)


Invocation Options

python [-diOStuUvxX?] [-c command | script | - ] [args]

                              Invocation Options
Option                                  Effect
-c cmd  program passed in as string (terminates option list)
-d      Outputs parser debugging information (also PYTHONDEBUG=x)
-E      ignore environment variables (such as PYTHONPATH)
-h      print this help message and exit
-i      Inspect interactively after running script (also PYTHONINSPECT=x) and
        force prompts, even if stdin appears not to be a terminal
-m mod  run library module as a script (terminates option list
-O      optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)
-OO     remove doc-strings in addition to the -O optimizations
-Q arg  division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-S      Don't perform 'import site' on initialization
-t      Issue warnings about inconsistent tab usage (-tt: issue errors)
-u      Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
-v      Verbose (trace import statements) (also PYTHONVERBOSE=x)
-W arg : warning control (arg is action:message:category:module:lineno)
-x      Skip first line of source, allowing use of non-unix Forms of #!cmd
-?      Help!
-3      warn about Python 3.x incompatibilities
-c      Specify the command to execute (see next section). This terminates the
command option list (following options are passed as arguments to the command).
        the name of a python file (.py) to execute read from stdin.
script  Anything afterward is passed as options to python script or command,
        not interpreted as an option to interpreter itself.
args    passed to script or command (in sys.argv[1:])
        If no script or command, Python enters interactive mode.

  * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin
    (Windows).



Environment variables

                             Environment variables
    Variable                                 Effect
PYTHONHOME       Alternate prefix directory (or prefix;exec_prefix). The
                 default module search path uses prefix/lib
                 Augments the default search path for module files. The format
                 is the same as the shell's $PATH: one or more directory
                 pathnames separated by ':' or ';' without spaces around
                 (semi-)colons!
PYTHONPATH       On Windows first search for Registry key HKEY_LOCAL_MACHINE\
                 Software\Python\PythonCore\x.y\PythonPath (default value). You
                 may also define a key named after your application with a
                 default string value giving the root directory path of your
                 app.
                 If this is the name of a readable file, the Python commands in
PYTHONSTARTUP    that file are executed before the first prompt is displayed in
                 interactive mode (no default).
PYTHONDEBUG      If non-empty, same as -d option
PYTHONINSPECT    If non-empty, same as -i option
PYTHONSUPPRESS   If non-empty, same as -s option
PYTHONUNBUFFERED If non-empty, same as -u option
PYTHONVERBOSE    If non-empty, same as -v option
PYTHONCASEOK     If non-empty, ignore case in file/module names (imports)




Notable lexical entities

Keywords

    and       del       for       is        raise
    assert    elif      from      lambda    return
    break     else      global    not       try
    class     except    if        or        while
    continue  exec      import    pass      yield
    def       finally   in        print

  * (list of keywords in std module: keyword)
  * Illegitimate Tokens (only valid in strings): @ $ ?
  * A statement must all be on a single line. To break a statement over
    multiple lines use "\", as with the C preprocessor.
    Exception: can always break when inside any (), [], or {} pair, or in
    triple-quoted strings.
  * More than one statement can appear on a line if they are separated with
    semicolons (";").
  * Comments start with "#" and continue to end of line.

Identifiers

        (letter | "_")  (letter | digit | "_")*

  * Python identifiers keywords, attributes, etc. are case-sensitive.
  * Special forms: _ident (not imported by 'from module import *'); __ident__
    (system defined name);
               __ident (class-private name mangling)

Strings

    "a string enclosed by double quotes"
    'another string delimited by single quotes and with a " inside'
    '''a string containing embedded newlines and quote (') marks, can be
    delimited with triple quotes.'''
    """ may also use 3- double quotes as delimiters """
    u'a unicode string'   U"Another unicode string"
    r'a raw string where \ are kept (literalized): handy for regular
    expressions and windows paths!'
    R"another raw string"    -- raw strings cannot end with a \
    ur'a unicode raw string'   UR"another raw unicode"

        Use \ at end of line to continue a string on next line.
        adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as
        'Monty Python'.
        u'hello' + ' world'  --> u'hello world'   (coerced to unicode)

    String Literal Escapes

     \newline  Ignored (escape newline)
     \\ Backslash (\)        \e Escape (ESC)        \v Vertical Tab (VT)
     \' Single quote (')     \f Formfeed (FF)       \OOO char with octal value OOO
     \" Double quote (")     \n Linefeed (LF)
     \a Bell (BEL)           \r Carriage Return (CR) \xHH  char with hex value HH
     \b Backspace (BS)       \t Horizontal Tab (TAB)
     \uHHHH  unicode char with hex value HHHH, can only be used in unicode string
     \UHHHHHHHH  unicode char with hex value HHHHHHHH, can only be used in unicode string
     \AnyOtherChar is left as-is

  * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in
    strings.
  * Strings (and tuples) are immutable: they cannot be modified.

Numbers

    Decimal integer: 1234, 1234567890546378940L        (or l)
    Octal integer: 0177, 0177777777777777777 (begin with a 0)
    Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFF (begin with 0x or 0X)
    Long integer (unlimited precision): 1234567890123456
    Float (double precision): 3.14e-10, .001, 10., 1E3
    Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and
    imaginary parts)

Sequences

  * String of length 0, 1, 2 (see above)
    '', '1', "12", 'hello\n'
  * Tuple of length 0, 1, 2, etc:
    () (1,) (1,2)     # parentheses are optional if len > 0
  * List of length 0, 1, 2, etc:
    [] [1] [1,2]

Indexing is 0-based. Negative indices (usually) mean count backwards from end
of sequence.

Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to
'0'; End defaults to 'sequence-length'.

a = (0,1,2,3,4,5,6,7)
    a[3] ==> 3
    a[-1] ==> 7
    a[2:4] ==> (2, 3)
    a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
    a[:3] ==> (0, 1, 2)
    a[:] ==> (0,1,2,3,4,5,6,7)  # makes a copy of the sequence.

Dictionaries (Mappings)

    {}                              # Zero length empty dictionary
    {1 : 'first'}                   # Dictionary with one (key, value) pair
    {1 : 'first',  'next': 'second'}
    dict([('one',1),('two',2)])     # Construct a dict from an item list
    dict('one'=1, 'two'=2)          # Construct a dict using keyword args
    dict.fromkeys(['one', 'keys'])  # Construct a dict from a sequence

Operators and their evaluation order

                     Operators and their evaluation order
Highest             Operator                             Comment
        (...) [...] {...} `...`           Tuple, list & dict. creation; string
                                          conv.
        s[i]  s[i:j]  s.attr f(...)       indexing & slicing; attributes, fct
                                          calls
        +x, -x, ~x                        Unary operators
        x**y                              Power
        x*y  x/y  x%y x//y                mult, division, modulo, floor division
        x+y  x-y                          addition, subtraction
        x<<y   x>>y                       Bit shifting
        x&y                               Bitwise and
        x^y                               Bitwise exclusive or
        x|y                               Bitwise or
        x<y  x<=y  x>y  x>=y  x==y x!=y   Comparison,
        x<>y                              identity,
        x is y   x is not y               membership
        x in s   x not in s
        not x                             boolean negation
        x and y                           boolean and
        x or y                            boolean or
Lowest  lambda args: expr                 anonymous function

Alternate names are defined in module operator (e.g. __add__ and add for +)
Most operators are overridable.

Many binary operators also support augmented assignment:
        x += 1                            # Same as x = x + 1


Basic Types and Their Operations

Comparisons (defined between *any* types)

               Comparisons
Comparison         Meaning          Notes
<          strictly less than        (1)
<=         less than or equal to
>          strictly greater than
>=         greater than or equal to
==         equal to
!= or <>   not equal to
is         object identity           (2)
is not     negated object identity   (2)

Notes :
    Comparison behavior can be overridden for a given class by defining special
method __cmp__.
    The above comparisons return True or False which are of type bool
(a subclass of int) and behave exactly as 1 or 0 except for their type and
that they print as True or False instead of 1 or 0.
    (1) X < Y < Z < W has expected meaning, unlike C
    (2) Compare object identities (i.e. id(object)), not object values.

Boolean values and operators

                         Boolean values and operators
              Value or Operator                         Returns           Notes
None, numeric zeros, empty sequences and      False
mappings
all other values                              True
not x                                         True if x is False, else
                                              True
x or y                                        if x is False then y, else   (1)
                                              x
x and y                                       if x is False then x, else   (1)
                                              y

Notes :
    Truth testing behavior can be overridden for a given class by defining
special method __nonzero__.
    (1) Evaluate second arg only if necessary to determine outcome.

None

    None is used as default return value on functions. Built-in single object
    with type NoneType.
    Input that evaluates to None does not print when running Python
    interactively.

Numeric types

Floats, integers and long integers.

    Floats are implemented with C doubles.
    Integers are implemented with C longs.
    Long integers have unlimited size (only limit is system resources)

Operators on all numeric types

           Operators on all numeric types
 Operation                    Result
abs(x)       the absolute value of x
int(x)       x converted to integer
long(x)      x converted to long integer
float(x)     x converted to floating point
-x           x negated
+x           x unchanged
x + y        the sum of x and y
x - y        difference of x and y
x * y        product of x and y
x / y        quotient of x and y
x % y        remainder of x / y
divmod(x, y) the tuple (x/y, x%y)
x ** y       x to the power y (the same as pow(x, y))

Bit operators on integers and long integers

              Bit operators
Operation             >Result
~x        the bits of x inverted
x ^ y     bitwise exclusive or of x and y
x & y     bitwise and of x and y
x | y     bitwise or of x and y
x << n    x shifted left by n bits
x >> n    x shifted right by n bits

Complex Numbers

  * represented as a pair of machine-level double precision floating point
    numbers.
  * The real and imaginary value of a complex number z can be retrieved through
    the attributes z.real and z.imag.

Numeric exceptions

TypeError
    raised on application of arithmetic operation to non-number
OverflowError
     numeric bounds exceeded
ZeroDivisionError
     raised when zero second argument of div or modulo op
FloatingPointError
     raised when a floating point operation fails

Operations on all sequence types (lists, tuples, strings)

                Operations on all sequence types
Operation                     Result                     Notes
x in s     True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
for x in s: loops over the sequence
s + t      the concatenation of s and t
s * n, n*s n copies of s concatenated
s[i]       i'th item of s, origin 0                       (1)
s[i:j]     slice of s from i (included) to j (excluded) (1), (2)
len(s)     length of s
min(s)     smallest item of s
max(s)     largest item of (s)
iter(s)    returns an iterator over s.  iterators define __iter__ and next()

Notes :
    (1) if i or j is negative, the index is relative to the end of the string,
ie len(s)+ i or len(s)+j is
         substituted. But note that -0 is still 0.
    (2) The slice of s from i to j is defined as the sequence of items with
index k such that i <= k < j.
          If i or j is greater than len(s), use len(s). If i is omitted, use
len(s). If i is greater than or
          equal to j, the slice is empty.

Operations on mutable (=modifiable) sequences (lists)

                 Operations on mutable sequences
   Operation                      Result                   Notes
s[i] =x          item i of s is replaced by x
s[i:j] = t       slice of s from i to j is replaced by t
del s[i:j]       same as s[i:j] = []
s.append(x)      same as s[len(s) : len(s)] = [x]
s.count(x)       return number of i's for which s[i] == x
s.extend(x)      same as s[len(s):len(s)]= x
s.index(x)       return smallest i such that s[i] == x      (1)
s.insert(i, x)   same as s[i:i] = [x] if i >= 0
s.pop([i])       same as x = s[i]; del s[i]; return x       (4)
s.remove(x)      same as del s[s.index(x)]                  (1)
s.reverse()      reverse the items of s in place            (3)
s.sort([cmpFct]) sort the items of s in place             (2), (3)

Notes :
    (1) raise a ValueError exception when x is not found in s (i.e. out of
range).
     (2) The sort() method takes an optional argument specifying a comparison
fct of 2 arguments (list items) which should
          return -1, 0, or 1 depending on whether the 1st argument is
considered smaller than, equal to, or larger than the 2nd
          argument. Note that this slows the sorting process down considerably.
     (3) The sort() and reverse() methods modify the list in place for economy
of space when sorting or reversing a large list.
           They don't return the sorted or reversed list to remind you of this
side effect.
     (4) [New 1.5.2] The optional  argument i defaults to -1, so that by default the last
item is removed and returned.



Operations on mappings (dictionaries)

                         Operations on mappings
        Operation                          Result                  Notes
len(d)                     the number of items in d
d[k]                       the item of d with key k                 (1)
d[k] = x                   set d[k] to x
del d[k]                   remove d[k] from d                       (1)
d.clear()                  remove all items from d
d.copy()                   a shallow copy of d
d.get(k,defaultval)        the item of d with key k                 (4)
d.has_key(k)               True if d has key k, else False
d.items()                  a copy of d's list of (key, item) pairs  (2)
d.iteritems()              an iterator over (key, value) pairs      (7)
d.iterkeys()               an iterator over the keys of d           (7)
d.itervalues()             an iterator over the values of d         (7)
d.keys()                   a copy of d's list of keys               (2)
d1.update(d2)              for k, v in d2.items(): d1[k] = v        (3)
d.values()                 a copy of d's list of values             (2)
d.pop(k)                   remove d[k] and return its value
d.popitem()                remove and return an arbitrary           (6)
                           (key, item) pair
d.setdefault(k,defaultval) the item of d with key k                 (5)

    Notes :
      TypeError is raised if key is not acceptable
      (1) KeyError is raised if key k is not in the map
      (2) Keys and values are listed in random order
      (3) d2 must be of the same type as d1
      (4) Never raises an exception if k is not in the map, instead it returns
    defaultVal.
          defaultVal is optional, when not provided and k is not in the map,
    None is returned.
      (5) Never raises an exception if k is not in the map, instead it returns
    defaultVal, and adds k to map with value defaultVal. defaultVal is
    optional. When not provided and k is not in the map, None is returned and
    added to map.
      (6) Raises a KeyError if the dictionary is empty.
      (7) While iterating over a dictionary, the values may be updated but
          the keys cannot be changed.

Operations on strings

Note that these string methods largely (but not completely) supersede the
functions available in the string module.


                             Operations on strings
    Operation                             Result                          Notes
s.capitalize()    return a copy of s with only its first character
                  capitalized.
s.center(width)   return a copy of s centered in a string of length width  (1)
                  .
s.count(sub[      return the number of occurrences of substring sub in     (2)
,start[,end]])    string s.
s.decode(([       return a decoded version of s.                           (3)
  encoding
  [,errors]])
s.encode([        return an encoded version of s. Default encoding is the
  encoding        current default string encoding.                         (3)
  [,errors]])
s.endswith(suffix return true if s ends with the specified suffix,         (2)
  [,start[,end]]) otherwise return False.
s.expandtabs([    return a copy of s where all tab characters are          (4)
tabsize])         expanded using spaces.
s.find(sub[,start return the lowest index in s where substring sub is      (2)
[,end]])          found. Return -1 if sub is not found.
s.index(sub[      like find(), but raise ValueError when the substring is  (2)
,start[,end]])    not found.
s.isalnum()       return True if all characters in s are alphanumeric,     (5)
                  False otherwise.
s.isalpha()       return True if all characters in s are alphabetic,       (5)
                  False otherwise.
s.isdigit()       return True if all characters in s are digit             (5)
                  characters, False otherwise.
s.islower()       return True if all characters in s are lowercase, False  (6)
                  otherwise.
s.isspace()       return True if all characters in s are whitespace        (5)
                  characters, False otherwise.
s.istitle()       return True if string s is a titlecased string, False    (7)
                  otherwise.
s.isupper()       return True if all characters in s are uppercase, False  (6)
                  otherwise.
s.join(seq)       return a concatenation of the strings in the sequence
                  seq, separated by 's's.
s.ljust(width)    return s left justified in a string of length width.    (1),
                                                                           (8)
s.lower()         return a copy of s converted to lowercase.
s.lstrip()        return a copy of s with leading whitespace removed.
s.replace(old,    return a copy of s with all occurrences of substring     (9)
new[, maxsplit])  old replaced by new.
s.rfind(sub[      return the highest index in s where substring sub is     (2)
,start[,end]])    found. Return -1 if sub is not found.
s.rindex(sub[     like rfind(), but raise ValueError when the substring    (2)
,start[,end]])    is not found.
s.rjust(width)    return s right justified in a string of length width.   (1),
                                                                           (8)
s.rstrip()        return a copy of s with trailing whitespace removed.
s.split([sep[     return a list of the words in s, using sep as the       (10)
,maxsplit]])      delimiter string.
s.splitlines([    return a list of the lines in s, breaking at line       (11)
keepends])        boundaries.
s.startswith      return true if s starts with the specified prefix,
(prefix[,start[   otherwise return false.                                  (2)
,end]])
s.strip()         return a copy of s with leading and trailing whitespace
                  removed.
s.swapcase()      return a copy of s with uppercase characters converted
                  to lowercase and vice versa.
                  return a titlecased copy of s, i.e. words start with
s.title()         uppercase characters, all remaining cased characters
                  are lowercase.
s.translate(table return a copy of s mapped through translation table     (12)
[,deletechars])   table.
s.upper()         return a copy of s converted to uppercase.
s.zfill(width)    return a string padded with zeroes on the left side and
                  sliding a minus sign left if necessary.  never truncates.

Notes :
    (1) Padding is done using spaces.
    (2) If optional argument start is supplied, substring s[start:] is
processed. If optional arguments start and end are supplied, substring s[start:
end] is processed.
    (3) Optional argument errors may be given to set a different error handling
scheme. The default for errors is 'strict', meaning that encoding errors raise
a ValueError. Other possible values are 'ignore' and 'replace'.
    (4) If optional argument tabsize is not given, a tab size of 8 characters
is assumed.
    (5) Returns false if string s does not contain at least one character.
    (6) Returns false if string s does not contain at least one cased
character.
    (7) A titlecased string is a string in which uppercase characters may only
follow uncased characters and lowercase characters only cased ones.
    (8) s is returned if width is less than len(s).
    (9) If the optional argument maxsplit is given, only the first maxsplit
occurrences are replaced.
    (10) If sep is not specified or None, any whitespace string is a separator.
If maxsplit is given, at most maxsplit splits are done.
    (11) Line breaks are not included in the resulting list unless keepends is
given and true.
    (12) table must be a string of length 256. All characters occurring in the
optional argument deletechars are removed prior to translation.

String formatting with the % operator

formatString % args--> evaluates to a string

  * formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E,
    f, g, G, r (details below).
  * Width and precision may be a * to specify that an integer argument gives
    the actual width or precision.
  * The flag characters -, +, blank, # and 0 are understood. (details below)
  * %s will convert any type argument to string (uses str() function)
  * args may be a single arg or a tuple of args

        '%s has %03d quote types.' % ('Python', 2)  # => 'Python has 002 quote types.'

  * Right-hand-side can also be a mapping:

        a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
(vars() function very handy to use on right-hand-side.)

                                 Format codes
Conversion                               Meaning
d          Signed integer decimal.
i          Signed integer decimal.
o          Unsigned octal.
u          Unsigned decimal.
x          Unsigned hexadecimal (lowercase).
X          Unsigned hexadecimal (uppercase).
e          Floating point exponential format (lowercase).
E          Floating point exponential format (uppercase).
f          Floating point decimal format.
F          Floating point decimal format.
g          Same as "e" if exponent is greater than -4 or less than precision,
           "f" otherwise.
G          Same as "E" if exponent is greater than -4 or less than precision,
           "F" otherwise.
c          Single character (accepts integer or single character string).
r          String (converts any python object using repr()).
s          String (converts any python object using str()).
%          No argument is converted, results in a "%" character in the result.
           (The complete specification is %%.)

                          Conversion flag characters
Flag                                  Meaning
#    The value conversion will use the ``alternate form''.
0    The conversion will be zero padded.
-    The converted value is left adjusted (overrides "-").
     (a space) A blank should be left before a positive number (or empty
     string) produced by a signed conversion.
+    A sign character ("+" or "-") will precede the conversion (overrides a
     "space" flag).

File Objects

Created with built-in function open; may be created by other modules' functions
as well.

Operators on file objects

                                File operations
    Operation                                Result
f.close()         Close file f.
f.fileno()        Get fileno (fd) for file f.
f.flush()         Flush file f's internal buffer.
f.isatty()        True if file f is connected to a tty-like dev, else False.
f.read([size])    Read at most size bytes from file f and return as a string
                  object. If size omitted, read to EOF.
f.readline()      Read one entire line from file f.
f.readlines()     Read until EOF with readline() and return list of lines read.
                  Set file f's position, like "stdio's fseek()".
f.seek(offset[,   whence == 0 then use absolute indexing.
whence=0])        whence == 1 then offset relative to current pos.
                  whence == 2 then offset relative to file end.
f.tell()          Return file f's current position (byte offset).
f.write(str)      Write string to file f.
f.writelines(list Write list of strings to file f.
)

File Exceptions

  EOFError
     End-of-file hit when reading (may be raised many times, e.g. if f is a
    tty).
  IOError
     Other I/O-related I/O operation failure.
  OSError
     OS system call failed.


    Advanced Types

    -See manuals for more details -
      + Module objects
      + Class objects
      + Class instance objects
      + Type objects (see module: types)
      + File objects (see above)
      + Slice objects
      + XRange objects
      + Callable types:
          o User-defined (written in Python):
              # User-defined Function objects
              # User-defined Method objects
          o Built-in (written in C):
              # Built-in Function objects
              # Built-in Method objects
      + Internal Types:
          o Code objects (byte-compile executable Python code: bytecode)
          o Frame objects (execution frames)
          o Traceback objects (stack trace of an exception)


    Statements

    pass            -- Null statement
    del name[,name]* -- Unbind name(s) from object. Object will be indirectly
                        (and automatically) deleted only if no longer referenced.
    print [>> fileobject,] [s1 [, s2 ]* [,]
                    -- Writes to sys.stdout, or to fileobject if supplied.
                       Puts spaces between arguments. Puts newline at end
                       unless statement ends with comma.
                       Print is not required when running interactively,
                       simply typing an expression will print its value,
                       unless the value is None.
    exec x [in globals [,locals]]
                    -- Executes x in namespaces provided. Defaults
                       to current namespaces. x can be a string, file
                       object or a function object.
    callable(value,... [id=value], [*args], [**kw])
                    -- Call function callable with parameters. Parameters can
                       be passed by name or be omitted if function
                       defines default values. E.g. if callable is defined as
                       "def callable(p1=1, p2=2)"
                       "callable()"       <=>  "callable(1, 2)"
                       "callable(10)"     <=>  "callable(10, 2)"
                       "callable(p2=99)"  <=>  "callable(1, 99)"
                       *args is a tuple of positional arguments.
                       **kw is a dictionary of keyword arguments.

    Assignment operators

                              Caption
    Operator                    Result                     Notes
    a = b    Basic assignment - assign object b to label a  (1)
    a += b   Roughly equivalent to a = a + b                (2)
    a -= b   Roughly equivalent to a = a - b                (2)
    a *= b   Roughly equivalent to a = a * b                (2)
    a /= b   Roughly equivalent to a = a / b                (2)
    a %= b   Roughly equivalent to a = a % b                (2)
    a **= b  Roughly equivalent to a = a ** b               (2)
    a &= b   Roughly equivalent to a = a & b                (2)
    a |= b   Roughly equivalent to a = a | b                (2)
    a ^= b   Roughly equivalent to a = a ^ b                (2)
    a >>= b  Roughly equivalent to a = a >> b               (2)
    a <<= b  Roughly equivalent to a = a << b               (2)

    Notes :
        (1) Can unpack tuples, lists, and strings.
           first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
           Tip: x,y = y,x swaps x and y.
        (2) Not exactly equivalent - a is evaluated only once. Also, where
    possible, operation performed in-place - a is modified rather than
    replaced.

    Control Flow

    if condition: suite
    [elif condition: suite]*
    [else: suite]   -- usual if/else_if/else statement
    while condition: suite
    [else: suite]
                    -- usual while statement. "else" suite is executed
                       after loop exits, unless the loop is exited with
                       "break"
    for element in sequence: suite
    [else: suite]
                    -- iterates over sequence, assigning each element to element.
                       Use built-in range function to iterate a number of times.
                       "else" suite executed at end unless loop exited
                       with "break"
    break           -- immediately exits "for" or "while" loop
    continue        -- immediately does next iteration of "for" or "while" loop
    return [result] -- Exits from function (or method) and returns result (use a tuple to
                       return more than one value). If no result given, then returns None.
    yield result    -- Freezes the execution frame of a generator and returns the result
                       to the iterator's .next() method.  Upon the next call to next(),
                       resumes execution at the frozen point with all of the local variables
                       still intact.

    Exception Statements

    assert expr[, message]
                    -- expr is evaluated. if false, raises exception AssertionError
                       with message. Inhibited if __debug__ is 0.
    try: suite1
    [except [exception [, value]: suite2]+
    [else: suite3]
                    -- statements in suite1 are executed. If an exception occurs, look
                       in "except" clauses for matching <exception>. If matches or bare
                       "except" execute suite of that clause. If no exception happens
                       suite in "else" clause is executed after suite1.
                       If exception has a value, it is put in value.
                       exception can also be tuple of exceptions, e.g.
                       "except (KeyError, NameError), val: print val"
    try: suite1
    finally: suite2
                    -- statements in suite1 are executed. If no
                       exception, execute suite2 (even if suite1 is
                       exited with a "return", "break" or "continue"
                       statement). If exception did occur, executes
                       suite2 and then immediately reraises exception.
    raise exception [,value [, traceback]]
                    -- raises exception with optional value
                       value. Arg traceback specifies a traceback object to
                       use when printing the exception's backtrace.
    raise           -- a raise statement without arguments re-raises
                       the last exception raised in the current function
An exception is either a string (object) or a class instance.
  Can create a new one simply by creating a new string:

              my_exception = 'You did something wrong'
      try:
                   if bad:
              raise my_exception, bad
      except my_exception, value:
                    print 'Oops', value

Exception classes must be derived from the predefined class: Exception, e.g.:
            class text_exception(Exception): pass
            try:
                if bad:
                    raise text_exception()
                    # This is a shorthand for the form
                    # "raise <class>, <instance>"
             except Exception:
                 print 'Oops'
                 # This will be printed because
                 # text_exception is a subclass of Exception
When an error message is printed for an unhandled exception which is a
class, the class name is printed, then a colon and a space, and
finally the instance converted to a string using the built-in function
str().
All built-in exception classes derives from StandardError, itself
derived from Exception.

Name Space Statements

[1.51: On Mac & Windows, the case of module file names must now match the case
as used
  in the import statement]
Packages (>1.5): a package is a name space which maps to a directory including
                module(s) and the special initialization module '__init__.py'
                (possibly empty). Packages/dirs can be nested. You address a
                module's symbol via '[package.[package...]module.symbol's.
import module1 [as name1] [, module2]*
                -- imports modules. Members of module must be
                   referred to by qualifying with [package.]module name:
                   "import sys; print sys.argv:"
                   "import package1.subpackage.module; package1.subpackage.module.foo()"
                   module1 renamed as name1, if supplied.
from module import name1 [as othername1] [, name2]*
                -- imports names from module module in current namespace.
                   "from sys import argv; print argv"
                   "from package1 import module; module.foo()"
                   "from package1.module import foo; foo()"
                   name1 renamed as othername1, if supplied.
from module import *
                -- imports all names in module, except those starting with "_";
                   *to be used sparsely, beware of name clashes* :
                   "from sys import *; print argv"
                   "from package.module import *; print x'
                    NB: "from package import *" only imports the symbols defined
                    in the package's __init__.py file, not those in the
                    template modules!
global name1 [, name2]*
                -- names are from global scope (usually meaning from module)
                   rather than local (usually meaning only in function).
                -- E.g. in fct without "global" statements, assuming
                   "a" is name that hasn't been used in fct or module
                   so far:
                   -Try to read from "a" -> NameError
                   -Try to write to "a" -> creates "a" local to fcn
                   -If "a" not defined in fct, but is in module, then
                       -Try to read from "a", gets value from module
                       -Try to write to "a", creates "a" local to fct
                   But note "a[0]=3" starts with search for "a",
                   will use to global "a" if no local "a".

Function Definition

def func_id ([param_list]): suite
                -- Creates a function object & binds it to name func_id.

    param_list ::= [id [, id]*]
    id ::= value | id = value | *id | **id
    [Args are passed by value.Thus only args representing a mutable object
    can be modified (are inout parameters). Use a tuple to return more than
    one value]

Example:
        def test (p1, p2 = 1+1, *rest, **keywords):
            -- Parameters with "=" have default value (v is
               evaluated when function defined).
               If list has "*id" then id is assigned a tuple of
               all remaining args passed to function (like C vararg)
               If list has "**id" then id is assigned a dictionary of
               all extra arguments passed as keywords.

Class Definition

class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
        -- Creates a class object and assigns it name <class_id>
           <suite> may contain local "defs" of class methods and
           assignments to class attributes.
Example:
       class my_class (class1, class_list[3]): ...
                  Creates a class object inheriting from both "class1" and whatever
                  class object "class_list[3]" evaluates to. Assigns new
                  class object to name "my_class".
        - First arg to class methods is always instance object, called 'self'
          by convention.
        - Special method __init__() is called when instance is created.
        - Special method __del__() called when no more reference to object.
        - Create instance by "calling" class object, possibly with arg
          (thus instance=apply(aClassObject, args...) creates an instance!)
        - In current implementation, can't subclass off built-in
          classes. But can "wrap" them, see UserDict & UserList modules,
          and see __getattr__() below.
Example:
        class c (c_parent):
           def __init__(self, name): self.name = name
           def print_name(self): print "I'm", self.name
           def call_parent(self): c_parent.print_name(self)
           instance = c('tom')
           print instance.name
           'tom'
           instance.print_name()
           "I'm tom"
        Call parent's super class by accessing parent's method
        directly and passing "self" explicitly (see "call_parent"
        in example above).
        Many other special methods available for implementing
        arithmetic operators, sequence, mapping indexing, etc.

Documentation Strings

Modules, classes and functions may be documented by placing a string literal by
itself as the first statement in the suite. The documentation can be retrieved
by getting the '__doc__' attribute from the module, class or function.
Example:
        class C:
            "A description of C"
            def __init__(self):
                "A description of the constructor"
                # etc.
Then c.__doc__ == "A description of C".
Then c.__init__.__doc__ == "A description of the constructor".

Others

lambda [param_list]: returnedExpr
                -- Creates an anonymous function. returnedExpr must be
                   an expression, not a statement (e.g., not "if xx:...",
                   "print xxx", etc.) and thus can't contain newlines.
                   Used mostly for filter(), map(), reduce() functions, and GUI callbacks..
List comprehensions
result = [expression for item1 in sequence1  [if condition1]
                        [for item2 in sequence2 ... for itemN in sequenceN]
                      ]
is equivalent to:
result = []
for item1 in sequence1:
    for item2 in sequence2:
    ...
        for itemN in sequenceN:
             if (condition1) and furthur conditions:
                  result.append(expression)



Built-In Functions

                              Built-In Functions
     Function                                 Result
__import__(name[,   Imports module within the given context (see lib ref for
globals[, locals[,  more details)
fromlist]]])
abs(x)              Return the absolute value of number x.
apply(f, args[,     Calls func/method f with arguments args and optional
keywords])          keywords.
bool(x)             Returns True when the argument x is true and False otherwise.
buffer(obj)         Creates a buffer reference to an object.
callable(x)         Returns True if x callable, else False.
chr(i)              Returns one-character string whose ASCII code isinteger i
classmethod(f)      Converts a function f, into a method with the class as the
                    first argument.  Useful for creating alternative constructors.
cmp(x,y)            Returns negative, 0, positive if x <, ==, > to y
coerce(x,y)         Returns a tuple of the two numeric arguments converted to a
                    common type.
                    Compiles string into a code object.filename is used in
                    error message, can be any string. It isusually the file
compile(string,     from which the code was read, or eg. '<string>'if not read
filename, kind)     from file.kind can be 'eval' if string is a single stmt, or
                    'single' which prints the output of expression statements
                    thatevaluate to something else than None, or be 'exec'.
complex(real[,      Builds a complex object (can also be done using J or j
image])             suffix,e.g. 1+3J)
delattr(obj, name)  deletes attribute named name of object obj <=> del obj.name
                    If no args, returns the list of names in current
dict([items])       Create a new dictionary from the specified item list.
dir([object])       localsymbol table. With a module, class or class
                    instanceobject as arg, returns list of names in its attr.
                    dict.
divmod(a,b)         Returns tuple of (a/b, a%b)
enumerate(seq)      Return an iterator giving:  (0, seq[0]), (1, seq[1]), ...
eval(s[, globals[,  Eval string s in (optional) globals, locals contexts.s must
locals]])           have no NUL's or newlines. s can also be acode object.
                    Example: x = 1; incr_x = eval('x + 1')
execfile(file[,     Executes a file without creating a new module, unlike
globals[, locals]]) import.
file()              Synonym for open().
filter(function,    Constructs a list from those elements of sequence for which
sequence)           function returns true. function takes one parameter.
float(x)            Converts a number or a string to floating point.
getattr(object,     [<default> arg added in 1.5.2]Gets attribute called name
name[, default]))   from object,e.g. getattr(x, 'f') <=> x.f). If not found,
                    raisesAttributeError or returns default if specified.
globals()           Returns a dictionary containing current global variables.
hasattr(object,     Returns true if object has attr called name.
name)
hash(object)        Returns the hash value of the object (if it has one)
help(f)             Display documentation on object f.
hex(x)              Converts a number x to a hexadecimal string.
id(object)          Returns a unique 'identity' integer for an object.
input([prompt])     Prints prompt if given. Reads input and evaluates it.
                    Converts a number or a string to a plain integer. Optional
int(x[, base])      base parameter specifies base from which to convert string
                    values.
intern(aString)     Enters aString in the table of "interned strings"
                    andreturns the string. Interned strings are 'immortals'.
isinstance(obj,     returns true if obj is an instance of class. Ifissubclass
class)              (A,B) then isinstance(x,A) => isinstance(x,B)
issubclass(class1,  returns true if class1 is derived from class2
class2)
                    Returns the length (the number of items) of an object
iter(collection)    Returns an iterator over the collection.
len(obj)            (sequence, dictionary, or instance of class implementing
                    __len__).
list(sequence)      Converts sequence into a list. If already a list,returns a
                    copy of it.
locals()            Returns a dictionary containing current local variables.
                    Converts a number or a string to a long integer. Optional
long(x[, base])     base parameter specifies base from which to convert string
                    values.
                    Applies function to every item of list and returns a listof
map(function, list, the results. If additional arguments are passed,function
...)                must take that many arguments and it is givento function on
                    each call.
max(seq)            Returns the largest item of the non-empty sequence seq.
min(seq)            Returns the smallest item of a non-empty sequence seq.
oct(x)              Converts a number to an octal string.
open(filename [,    Returns a new file object. First two args are same asthose
mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
implementation      1 for line-buffered, negative forsys-default, all else, of
dependent]])        (about) given size.
ord(c)              Returns integer ASCII value of c (a string of len 1). Works
                    with Unicode char.
object()            Create a base type.  Used as a superclass for new-style objects.
open(name           Open a file.
  [, mode
  [, buffering]])
pow(x, y [, z])     Returns x to power y [modulo z]. See also ** operator.
property()          Created a property with access controlled by functions.
range(start [,end   Returns list of ints from >= start and < end.With 1 arg,
[, step]])          list from 0..arg-1With 2 args, list from start..end-1With 3
                    args, list from start up to end by step
raw_input([prompt]) Prints prompt if given, then reads string from stdinput (no
                    trailing \n). See also input().
reduce(f, list [,   Applies the binary function f to the items oflist so as to
init])              reduce the list to a single value.If init given, it is
                    "prepended" to list.
                    Re-parses and re-initializes an already imported module.
                    Useful in interactive mode, if you want to reload amodule
reload(module)      after fixing it. If module was syntacticallycorrect but had
                    an error in initialization, mustimport it one more time
                    before calling reload().
                    Returns a string containing a printable and if possible
repr(object)        evaluable representation of an object. <=> `object`
                    (usingbackquotes). Class redefinissable (__repr__). See
                    also str()
round(x, n=0)       Returns the floating point value x rounded to n digitsafter
                    the decimal point.
setattr(object,     This is the counterpart of getattr().setattr(o, 'foobar',
name, value)        3) <=> o.foobar = 3Creates attribute if it doesn't exist!
slice([start,] stop Returns a slice object representing a range, with R/
[, step])           Oattributes: start, stop, step.
                    Returns a string containing a nicely
staticmethod()      Convert a function to method with no self or class
                    argument.  Useful for methods associated with a class that
                    do not need access to an object's internal state.
str(object)         printablerepresentation of an object. Class overridable
                    (__str__).See also repr().
super(type)         Create an unbound super object.  Used to call cooperative
                    superclass methods.
sum(sequence,       Add the values in the sequence and return the sum.
    [start])
tuple(sequence)     Creates a tuple with same elements as sequence. If already
                    a tuple, return itself (not a copy).
                    Returns a type object [see module types] representing
                    thetype of obj. Example: import typesif type(x) ==
type(obj)           types.StringType: print 'It is a string'NB: it is
                    recommanded to use the following form:if isinstance(x,
                    types.StringType): etc...
unichr(code)        code.
unicode(string[,    Creates a Unicode string from an 8-bit string, using
encoding[, error    thegiven encoding name and error treatment ('strict',
]]])                'ignore',or 'replace'}.
                    Without arguments, returns a dictionary correspondingto the
                    current local symbol table. With a module,class or class
vars([object])      instance object as argumentreturns a dictionary
                    corresponding to the object'ssymbol table. Useful with "%"
                    formatting operator.
xrange(start [, end Like range(), but doesn't actually store entire listall at
[, step]])          once. Good to use in "for" loops when there is abig range
                    and little memory.
zip(seq1[, seq2,    Returns a list of tuples where each tuple contains the nth
...])               element of each of the argument sequences.




Built-In Exceptions

Exception>
         Root class for all exceptions
    SystemExit
         On 'sys.exit()'
    StopIteration
         Signal the end from iterator.next()
    StandardError
                 Base class for all built-in exceptions; derived from Exception
    root class.
        ArithmeticError
                 Base class for OverflowError, ZeroDivisionError,
    FloatingPointError
            FloatingPointError
                       When a floating point operation fails.
            OverflowError
                            On excessively large arithmetic operation
            ZeroDivisionError
                  On division or modulo operation with 0 as 2nd arg
            AssertionError
                When an assert statement fails.
        AttributeError
                    On attribute reference or assignment failure
        EnvironmentError    [new in 1.5.2]
                On error outside Python; error arg tuple is (errno, errMsg...)
            IOError    [changed in 1.5.2]
               I/O-related operation failure
            OSError    [new in 1.5.2]
               used by the os module's os.error exception.
        EOFError
                    Immediate end-of-file hit by input() or raw_input()
        ImportError
         On failure of `import' to find module or name
        KeyboardInterrupt
         On user entry of the interrupt key (often `Control-C')
        LookupError
                base class for IndexError, KeyError
            IndexError
                 On out-of-range sequence subscript
            KeyError
                 On reference to a non-existent mapping (dict) key
        MemoryError
         On recoverable memory exhaustion
        NameError
         On failure to find a local or global (unqualified) name
        RuntimeError
         Obsolete catch-all; define a suitable error instead
          NotImplementedError   [new in 1.5.2]
                On method not implemented
        SyntaxError
         On parser encountering a syntax error
       IndentationError
           On parser encountering an indentation syntax error
       TabError
           On parser encountering an indentation syntax error
        SystemError
         On non-fatal interpreter error - bug - report it
        TypeError
         On passing inappropriate type to built-in op or func
        ValueError
         On arg error not covered by TypeError or more precise
    Warning
              UserWarning
              DeprecationWarning
              PendingDeprecationWarning
              SyntaxWarning
              RuntimeWarning
              FutureWarning



Standard methods & operators redefinition in classes

Standard methods & operators map to special '__methods__' and thus may be
 redefined (mostly in user-defined classes), e.g.:
    class x:
         def __init__(self, v): self.value = v
         def __add__(self, r): return self.value + r
    a = x(3) # sort of like calling x.__init__(a, 3)
    a + 4    # is equivalent to a.__add__(4)

Special methods for any class

(s: self, o: other)
        __init__(s, args) instance initialization (on construction)
        __del__(s)        called on object demise (refcount becomes 0)
        __repr__(s)       repr() and `...` conversions
        __str__(s)        str() and 'print' statement
        __cmp__(s, o)     Compares s to o and returns <0, 0, or >0.
                          Implements >, <, == etc...
        __hash__(s)       Compute a 32 bit hash code; hash() and dictionary ops
        __nonzero__(s)    Returns False or True for truth value testing
        __getattr__(s, name)  called when attr lookup doesn't find <name>
        __setattr__(s, name, val) called when setting an attr
                                  (inside, don't use "self.name = value"
                                   use "self.__dict__[name] = val")
        __delattr__(s, name)  called to delete attr <name>
        __call__(self, *args) called when an instance is called as function.

Operators

    See list in the operator module. Operator function names are provided with
    2 variants, with or without
    ading & trailing '__' (eg. __add__ or add).

    Numeric operations special methods
    (s: self, o: other)

        s+o       =  __add__(s,o)         s-o        =  __sub__(s,o)
        s*o       =  __mul__(s,o)         s/o        =  __div__(s,o)
        s%o       =  __mod__(s,o)         divmod(s,o) = __divmod__(s,o)
        s**o      =  __pow__(s,o)
        s&o       =  __and__(s,o)
        s^o       =  __xor__(s,o)         s|o        =  __or__(s,o)
        s<<o      =  __lshift__(s,o)      s>>o       =  __rshift__(s,o)
        nonzero(s) = __nonzero__(s) (used in boolean testing)
        -s        =  __neg__(s)           +s         =  __pos__(s)
        abs(s)    =  __abs__(s)           ~s         =  __invert__(s)  (bitwise)
        s+=o      =  __iadd__(s,o)        s-=o       =  __isub__(s,o)
        s*=o      =  __imul__(s,o)        s/=o       =  __idiv__(s,o)
        s%=o      =  __imod__(s,o)
        s**=o     =  __ipow__(s,o)
        s&=o      =  __iand__(s,o)
        s^=o      =  __ixor__(s,o)        s|=o       =  __ior__(s,o)
        s<<=o     =  __ilshift__(s,o)     s>>=o      =  __irshift__(s,o)
        Conversions
        int(s)    =  __int__(s)           long(s)    =  __long__(s)
        float(s)  =  __float__(s)         complex(s)    =  __complex__(s)
        oct(s)    =  __oct__(s)           hex(s)     =  __hex__(s)
        coerce(s,o) = __coerce__(s,o)
        Right-hand-side equivalents for all binary operators exist;
        are called when class instance is on r-h-s of operator:
        a + 3  calls __add__(a, 3)
        3 + a  calls __radd__(a, 3)

    All seqs and maps, general operations plus:
    (s: self, i: index or key)

        len(s)    = __len__(s)        length of object, >= 0.  Length 0 == false
        s[i]      = __getitem__(s,i)  Element at index/key i, origin 0

    Sequences, general methods, plus:
      s[i]=v           = __setitem__(s,i,v)
      del s[i]         = __delitem__(s,i)
      s[i:j]           = __getslice__(s,i,j)
      s[i:j]=seq       = __setslice__(s,i,j,seq)
      del s[i:j]       = __delslice__(s,i,j)   == s[i:j] = []
      seq * n          = __repeat__(seq, n)
      s1 + s2          = __concat__(s1, s2)
      i in s           = __contains__(s, i)
    Mappings, general methods, plus
      hash(s)          = __hash__(s) - hash value for dictionary references
      s[k]=v           = __setitem__(s,k,v)
      del s[k]         = __delitem__(s,k)

Special informative state attributes for some types:

    Modules:
        __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
        __name__(string, R/O): module name (also in __dict__['__name__'])
        __dict__ (dict, R/O): module's name space
        __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
                 modules statically linked to the interpreter)

    Classes:    [in bold: writable since 1.5.2]
        __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
        __module__ is the module name in which the class was defined
        __name__(string, R/W): class name (also in __dict__['__name__'])
        __bases__ (tuple, R/W): parent classes
        __dict__ (dict, R/W): attributes (class name space)

    Instances:
        __class__ (class, R/W): instance's class
        __dict__ (dict, R/W): attributes

    User-defined functions: [bold: writable since 1.5.2]
        __doc__ (string/None, R/W): doc string
        __name__(string, R/O): function name
        func_doc (R/W): same as __doc__
        func_name (R/O): same as __name__
        func_defaults (tuple/None, R/W): default args values if any
        func_code (code, R/W): code object representing the compiled function body
        func_globals (dict, R/O): ref to dictionary of func global variables
        func_dict (dict, R/W):  same as __dict__ contains the namespace supporting
            arbitrary function attributes
        func_closure (R/O): None or a tuple of cells that contain bindings
            for the function's free variables.


    User-defined Methods:
        __doc__ (string/None, R/O): doc string
        __name__(string, R/O): method name (same as im_func.__name__)
        im_class (class, R/O): class defining the method (may be a base class)
        im_self (instance/None, R/O): target instance object (None if unbound)
        im_func (function, R/O): function object

    Built-in Functions & methods:
        __doc__ (string/None, R/O): doc string
        __name__ (string, R/O): function name
        __self__ : [methods only] target object

    Codes:
        co_name (string, R/O): function name
        co_argcount (int, R/0): number of positional args
        co_nlocals (int, R/O): number of local vars (including args)
        co_varnames (tuple, R/O): names of local vars (starting with args)
        co_cellvars (tuple, R/O)) the names of local variables referenced by
            nested functions
        co_freevars (tuple, R/O)) names of free variables
        co_code (string, R/O): sequence of bytecode instructions
        co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
                                fct doc (or None)
        co_names (tuple, R/O): names used by the bytecode
        co_filename (string, R/O): filename from which the code was compiled
        co_firstlineno (int, R/O): first line number of the function
        co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
        co_stacksize (int, R/O): required stack size (including local vars)
        co_flags (int, R/O): flags for the interpreter
                           bit 2 set if fct uses "*arg" syntax
                           bit 3 set if fct uses '**keywords' syntax
    Frames:
        f_back (frame/None, R/O): previous stack frame (toward the caller)
        f_code (code, R/O): code object being executed in this frame
        f_locals (dict, R/O): local vars
        f_globals (dict, R/O): global vars
        f_builtins (dict, R/O): built-in (intrinsic) names
        f_restricted (int, R/O): flag indicating whether fct is executed in
                                 restricted mode
        f_lineno (int, R/O): current line number
        f_lasti (int, R/O): precise instruction (index into bytecode)
        f_trace (function/None, R/W): debug hook called at start of each source line
        f_exc_type (Type/None, R/W): Most recent exception type
        f_exc_value (any, R/W): Most recent exception value
        f_exc_traceback (traceback/None, R/W): Most recent exception traceback
    Tracebacks:
        tb_next (frame/None, R/O): next level in stack trace (toward the frame where
                                  the exception occurred)
        tb_frame (frame, R/O): execution frame of the current level
        tb_lineno (int, R/O): line number where the exception occurred
        tb_lasti (int, R/O): precise instruction (index into bytecode)

    Slices:
        start (any/None, R/O): lowerbound
        stop (any/None, R/O): upperbound
        step (any/None, R/O): step value

    Complex numbers:
        real (float, R/O): real part
        imag (float, R/O): imaginary part


Important Modules

                                      sys

                              Some sys variables
      Variable                                Content
argv                 The list of command line arguments passed to aPython
                     script. sys.argv[0] is the script name.
builtin_module_names A list of strings giving the names of all moduleswritten
                     in C that are linked into this interpreter.
check_interval       How often to check for thread switches or signals(measured
                     in number of virtual machine instructions)
exc_type, exc_value, Deprecated since release 1.5. Use exc_info() instead.
exc_traceback
exitfunc             User can set to a parameterless fcn. It will getcalled
                     before interpreter exits.
last_type,           Set only when an exception not handled andinterpreter
last_value,          prints an error. Used by debuggers.
last_traceback
maxint               maximum positive value for integers
modules              Dictionary of modules that have already been loaded.
path                 Search path for external modules. Can be modifiedby
                     program. sys.path[0] == dir of script executing
platform             The current platform, e.g. "sunos5", "win32"
ps1, ps2             prompts to use in interactive mode.
                     File objects used for I/O. One can redirect byassigning a
stdin, stdout,       new file object to them (or any object:.with a method
stderr               write(string) for stdout/stderr,.with a method readline()
                     for stdin)
version              string containing version info about Python interpreter.
                     (and also: copyright, dllhandle, exec_prefix, prefix)
version_info         tuple containing Python version info - (major, minor,
                     micro, level, serial).

                              Some sys functions
     Function                                 Result
exit(n)            Exits with status n. Raises SystemExit exception.(Hence can
                   be caught and ignored by program)
getrefcount(object Returns the reference count of the object. Generally one
)                  higher than you might expect, because of object arg temp
                   reference.
setcheckinterval(  Sets the interpreter's thread switching interval (in number
interval)          of virtual code instructions, default:100).
settrace(func)     Sets a trace function: called before each line ofcode is
                   exited.
setprofile(func)   Sets a profile function for performance profiling.
                   Info on exception currently being handled; this is atuple
                   (exc_type, exc_value, exc_traceback).Warning: assigning the
exc_info()         traceback return value to a local variable in a
                   function handling an exception will cause a circular
                   reference.
setdefaultencoding Change default Unicode encoding - defaults to 7-bit ASCII.
(encoding)
getrecursionlimit  Retrieve maximum recursion depth.
()
setrecursionlimit  Set maximum recursion depth. (Defaults to 1000.)
()



                                      os
"synonym" for whatever O/S-specific module is proper for current environment.
this module uses posix whenever possible.
(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
platform.py)

                               Some os variables
     Variable                                 Meaning
name                name of O/S-specific module (e.g. "posix", "nt")
path                O/S-specific module for path manipulations.
                    On Unix, os.path.split() <=> posixpath.split()
curdir              string used to represent current directory ('.')
pardir              string used to represent parent directory ('..')
sep                 string used to separate directories ('/' or '\'). Tip: use
                    os.path.join() to build portable paths.
altsep              Alternate sep
if applicable (None
otherwise)
pathsep             character used to separate search path components (as in
                    $PATH), eg. ';' for windows.
linesep             line separator as used in binary files, ie '\n' on Unix, '\
                    r\n' on Dos/Win, '\r'

                               Some os functions
     Function                                 Result
makedirs(path[,     Recursive directory creation (create required intermediary
mode=0777])         dirs); os.error if fails.
removedirs(path)    Recursive directory delete (delete intermediary empty
                    dirs); if fails.
renames(old, new)   Recursive directory or file renaming; os.error if fails.



                                     posix
don't import this module directly, import os instead !
(see also module: shutil for file copy & remove fcts)

                            posix Variables
Variable                             Meaning
environ  dictionary of environment variables, e.g.posix.environ['HOME'].
error    exception raised on POSIX-related error.
         Corresponding value is tuple of errno code and perror() string.

                             Some posix functions
   Function                                 Result
chdir(path)     Changes current directory to path.
chmod(path,     Changes the mode of path to the numeric mode
mode)
close(fd)       Closes file descriptor fd opened with posix.open.
_exit(n)        Immediate exit, with no cleanups, no SystemExit,etc. Should use
                this to exit a child process.
execv(p, args)  "Become" executable p with args args
getcwd()        Returns a string representing the current working directory
getpid()        Returns the current process id
fork()          Like C's fork(). Returns 0 to child, child pid to parent.[Not
                on Windows]
kill(pid,       Like C's kill [Not on Windows]
signal)
listdir(path)   Lists (base)names of entries in directory path, excluding '.'
                and '..'
lseek(fd, pos,  Sets current position in file fd to position pos, expressedas
how)            an offset relative to beginning of file (how=0), tocurrent
                position (how=1), or to end of file (how=2)
mkdir(path[,    Creates a directory named path with numeric mode (default 0777)
mode])
open(file,      Like C's open(). Returns file descriptor. Use file object
flags, mode)    fctsrather than this low level ones.
pipe()          Creates a pipe. Returns pair of file descriptors (r, w) [Not on
                Windows].
popen(command,  Opens a pipe to or from command. Result is a file object to
mode='r',       read to orwrite from, as indicated by mode being 'r' or 'w'.
bufSize=0)      Use it to catch acommand output ('r' mode) or to feed it ('w'
                mode).
remove(path)    See unlink.
rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
)               name already exists]
rmdir(path)     Removes the empty directory path
read(fd, n)     Reads n bytes from file descriptor fd and return as string.
                Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid,
stat(path)      st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
                are dummy on Windows]
system(command) Executes string command in a subshell. Returns exitstatus of
                subshell (usually 0 means OK).
                Returns accumulated CPU times in sec (user, system, children's
times()         user,children's sys, elapsed real time). [3 last not on
                Windows]
unlink(path)    Unlinks ("deletes") the file (not dir!) path. same as: remove
utime(path, (   Sets the access & modified time of the file to the given tuple
aTime, mTime))  of values.
wait()          Waits for child process completion. Returns tuple ofpid,
                exit_status [Not on Windows]
waitpid(pid,    Waits for process pid to complete. Returns tuple ofpid,
options)        exit_status [Not on Windows]
write(fd, str)  Writes str to file fd. Returns nb of bytes written.



                                   posixpath
Do not import this module directly, import os instead and refer to this module
as os.path. (e.g. os.path.exists(p)) !

                           Some posixpath functions
 Function                                 Result
abspath(p) Returns absolute path for path p, taking current working dir in
           account.
dirname/
basename(p directory and name parts of the path p. See also split.
)
exists(p)  True if string p is an existing path (file or directory)
expanduser Returns string that is (a copy of) p with "~" expansion done.
(p)
expandvars Returns string that is (a copy of) p with environment vars expanded.
(p)        [Windows: case significant; must use Unix: $var notation, not %var%]
getsize(   return the size in bytes of filename. raise os.error.
filename)
getmtime(  return last modification time of filename (integer nb of seconds
filename)  since epoch).
getatime(  return last access time of filename (integer nb of seconds since
filename)  epoch).
isabs(p)   True if string p is an absolute path.
isdir(p)   True if string p is a directory.
islink(p)  True if string p is a symbolic link.
ismount(p) True if string p is a mount point [true for all dirs on Windows].
join(p[,q  Joins one or more path components intelligently.
[,...]])
           Splits p into (head, tail) where tail is lastpathname component and
split(p)   <head> is everything leadingup to that. <=> (dirname(p), basename
           (p))
splitdrive Splits path p in a pair ('drive:', tail) [Windows]
(p)
splitext(p Splits into (root, ext) where last comp of root contains no periods
)          and ext is empty or startswith a period.
           Calls the function visit with arguments(arg, dirname, names) for
           each directory recursively inthe directory tree rooted at p
walk(p,    (including p itself if it's a dir)The argument dirname specifies the
visit, arg visited directory, the argumentnames lists the files in the
)          directory. The visit function maymodify names to influence the set
           of directories visited belowdirname, e.g., to avoid visiting certain
           parts of the tree.



                                    shutil
high-level file operations (copying, deleting).

                             Main shutil functions
     Function                                 Result
copy(src, dst)     Copies the contents of file src to file dst, retaining file
                   permissions.
copytree(src, dst  Recursively copies an entire directory tree rooted at src
[, symlinks])      into dst (which should not already exist). If symlinks is
                   true, links insrc are kept as such in dst.
rmtree(path[,      Deletes an entire directory tree, ignoring errors if
ignore_errors[,    ignore_errors true,or calling onerror(func, path,
onerror]])         sys.exc_info()) if supplied with

(and also: copyfile, copymode, copystat, copy2)

time

                                  Variables
Variable                               Meaning
altzone  signed offset of local DST timezone in sec west of the 0th meridian.
daylight nonzero if a DST timezone is specified

                                   Functions
  Function                                 Result
time()        return a float representing UTC time in seconds since the epoch.
gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
localtime(    (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
secs)         monday), Julian day(1-366), daylight flag(-1,0 or 1))
asctime(
timeTuple),
strftime(
format,       return a formatted string representing time.
timeTuple)
mktime(tuple) inverse of localtime(). Return a float.
strptime(     parse a formatted string representing time, return tuple as in
string[,      gmtime().
format])
sleep(secs)   Suspend execution for <secs> seconds. <secs> can be a float.

and also: clock, ctime.

                                    string

As of Python 2.0, much (though not all) of the functionality provided by the
string module have been superseded by built-in string methods - see Operations
on strings for details.

                             Some string variables
              Variable                                Meaning
digits                               The string '0123456789'
hexdigits, octdigits                 legal hexadecimal & octal digits
letters, uppercase, lowercase,       Strings containing the appropriate
whitespace                           characters
index_error                          Exception raised by index() if substr not
                                     found.

                             Some string functions
     Function                                 Result
expandtabs(s,      returns a copy of string <s> with tabs expanded.
tabSize)
find/rfind(s, sub  Return the lowest/highest index in <s> where the substring
[, start=0[, end=  <sub> is found such that <sub> is wholly contained ins
0])                [start:end]. Return -1 if <sub> not found.
ljust/rjust/center Return a copy of string <s> left/right justified/centerd in
(s, width)         afield of given width, padded with spaces. <s> is
                   nevertruncated.
lower/upper(s)     Return a string that is (a copy of) <s> in lowercase/
                   uppercase
split(s[, sep=     Return a list containing the words of the string <s>,using
whitespace[,       the string <sep> as a separator.
maxsplit=0]])
join(words[, sep=' Concatenate a list or tuple of words with
'])                interveningseparators; inverse of split.
replace(s, old,    Returns a copy of string <s> with all occurrences of
new[, maxsplit=0]  substring<old> replaced by <new>. Limits to <maxsplit>
                   firstsubstitutions if specified.
strip(s)           Return a string that is (a copy of) <s> without leadingand
                   trailing whitespace. see also lstrip, rstrip.



                                   re (sre)

Handles Unicode strings. Implemented in new module sre, re now a mere front-end
for compatibility.
Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
litteralize backslashes.


                           Regular expression syntax
   Form                                Description
.          matches any character (including newline if DOTALL flag specified)
^          matches start of the string (of every line in MULTILINE mode)
$          matches end of the string (of every line in MULTILINE mode)
*          0 or more of preceding regular expression (as many as possible)
+          1 or more of preceding regular expression (as many as possible)
?          0 or 1 occurrence of preceding regular expression
*?, +?, ?? Same as *, + and ? but matches as few characters as possible
{m,n}      matches from m to n repetitions of preceding RE
{m,n}?     idem, attempting to match as few repetitions as possible
[ ]        defines character set: e.g. '[a-zA-Z]' to match all letters(see also
           \w \S)
[^ ]       defines complemented character set: matches if char is NOT in set
           escapes special chars '*?+&$|()' and introduces special sequences
\          (see below). Due to Python string rules, write as '\\' orr'\' in the
           pattern string.
\\         matches a litteral '\'; due to Python string rules, write as '\\\\
           'in pattern string, or better using raw string: r'\\'.
|          specifies alternative: 'foo|bar' matches 'foo' or 'bar'
(...)      matches any RE inside (), and delimits a group.
(?:...)    idem but doesn't delimit a group.
           matches if ... matches next, but doesn't consume any of the string
(?=...)    e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by
           'Asimov'.
(?!...)    matches if ... doesn't match next. Negative of (?=...)
(?P<name   matches any RE inside (), and delimits a named group. (e.g. r'(?P
>...)      <id>[a-zA-Z_]\w*)' defines a group named id)
(?P=name)  matches whatever text was matched by the earlier group named name.
(?#...)    A comment; ignored.
(?letter)  letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
           (re.I, re.L, re.M, re.S, re.X) for the entire RE.

                               Special sequences
Sequence                              Description
number   matches content of the group of the same number; groups are numbered
         starting from 1
\A       matches only at the start of the string
\b       empty str at beg or end of word: '\bis\b' matches 'is', but not 'his'
\B       empty str NOT at beginning or end of word
\d       any decimal digit (<=> [0-9])
\D       any non-decimal digit char (<=> [^O-9])
\s       any whitespace char (<=> [ \t\n\r\f\v])
\S       any non-whitespace char (<=> [^ \t\n\r\f\v])
\w       any alphaNumeric char (depends on LOCALE flag)
\W       any non-alphaNumeric char (depends on LOCALE flag)
\Z       matches only at the end of the string

                         Variables
Variable                       Meaning
error    Exception when pattern string isn't a valid regexp.

                                   Functions
   Function                                 Result
               Compile a RE pattern string into a regular expression object.
               Flags (combinable by |):

               I or IGNORECASE or (?i)
                   case insensitive matching
compile(       L or LOCALE or (?L)
pattern[,          make \w, \W, \b, \B dependent on thecurrent locale
flags=0])      M or MULTILINE or (?m)
                   matches every new line and not onlystart/end of the whole
                   string
               S or DOTALL or (?s)
                   '.' matches ALL chars, including newline
               X or VERBOSE or (?x)
                   Ignores whitespace outside character sets
escape(string) return (a copy of) string with all non-alphanumerics
               backslashed.
match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
string[, flags string,return a corresponding MatchObject instance, or None if
])             no match.
search(pattern scan thru <string> for a location matching <pattern>, return
, string[,     acorresponding MatchObject instance, or None if no match.
flags])
split(pattern, split <string> by occurrences of <pattern>. If capturing () are
string[,       used inpattern, then occurrences of patterns or subpatterns are
maxsplit=0])   also returned.
findall(       return a list of non-overlapping matches in <pattern>, either a
pattern,       list ofgroups or a list of tuples if the pattern has more than 1
string)        group.
               return string obtained by replacing the (<count> first) lefmost
sub(pattern,   non-overlapping occurrences of <pattern> (a string or a RE
repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
count=0])      called with a single MatchObj arg, which must return the
               replacement string.
subn(pattern,
repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
count=0])

Regular Expression Objects


(RE objects are returned by the compile fct)

                          re object attributes
Attribute                            Descrition
flags      flags arg used when RE obj was compiled, or 0 if none provided
groupindex dictionary of {group name: group number} in pattern
pattern    pattern string from which RE obj was compiled

                               re object methods
  Method                                  Result
            If zero or more characters at the beginning of string match this
            regular expression, return a corresponding MatchObject instance.
            Return None if the string does not match the pattern; note that
            this is different from a zero-length match.
            The optional second parameter pos gives an index in the string
match(      where the search is to start; it defaults to 0. This is not
string[,    completely equivalent to slicing the string; the '' pattern
pos][,      character matches at the real beginning of the string and at
endpos])    positions just after a newline, but not necessarily at the index
            where the search is to start.
            The optional parameter endpos limits how far the string will be
            searched; it will be as if the string is endpos characters long, so
            only the characters from pos to endpos will be searched for a
            match.
            Scan through string looking for a location where this regular
search(     expression produces a match, and return a corresponding MatchObject
string[,    instance. Return None if no position in the string matches the
pos][,      pattern; note that this is different from finding a zero-length
endpos])    match at some point in the string.
            The optional pos and endpos parameters have the same meaning as for
            the match() method.
split(
string[,    Identical to the split() function, using the compiled pattern.
maxsplit=
0])
findall(    Identical to the findall() function, using the compiled pattern.
string)
sub(repl,
string[,    Identical to the sub() function, using the compiled pattern.
count=0])
subn(repl,
string[,    Identical to the subn() function, using the compiled pattern.
count=0])

Match Objects


(Match objects are returned by the match & search functions)

                            Match object attributes
Attribute                              Description
pos       value of pos passed to search or match functions; index intostring at
          which RE engine started search.
endpos    value of endpos passed to search or match functions; index intostring
          beyond which RE engine won't go.
re        RE object whose match or search fct produced this MatchObj instance
string    string passed to match() or search()

                            Match object functions
Function                                 Result
          returns one or more groups of the match. If one arg, result is a
group([g1 string;if multiple args, result is a tuple with one item per arg. If
, g2,     gi is 0,return value is entire matching string; if 1 <= gi <= 99,
...])     returnstring matching group #gi (or None if no such group); gi may
          also bea group name.
          returns a tuple of all groups of the match; groups not
groups()  participatingto the match have a value of None. Returns a string
          instead of tupleif len(tuple)=1
start(
group),   returns indices of start & end of substring matched by group (or
end(group Noneif group exists but doesn't contribute to the match)
)
span(     returns the 2-tuple (start(group), end(group)); can be (None, None)if
group)    group didn't contibute to the match.



                                     math

Variables:
pi
e
Functions (see ordinary C man pages for info):
acos(x)
asin(x)
atan(x)
atan2(x, y)
ceil(x)
cos(x)
cosh(x)
degrees(x)
exp(x)
fabs(x)
floor(x)
fmod(x, y)
frexp(x)        -- Unlike C: (float, int) = frexp(float)
ldexp(x, y)
log(x [,base])
log10(x)
modf(x)         -- Unlike C: (float, float) = modf(float)
pow(x, y)
radians(x)
sin(x)
sinh(x)
sqrt(x)
tan(x)
tanh(x)

                                    getopt

Functions:
getopt(list, optstr)    -- Similar to C. <optstr> is option
                           letters to look for. Put ':' after letter
                           if option takes arg. E.g.
    # invocation was "python test.py -c hi -a arg1 arg2"
       opts, args =  getopt.getopt(sys.argv[1:], 'ab:c:')
    # opts would be
       [('-c', 'hi'), ('-a', '')]
    # args would be
       ['arg1', 'arg2']


List of modules and packages in base distribution

(built-ins and content of python Lib directory)
(Python NT distribution, may be slightly different in other distributions)

                           Standard library modules
   Operation                                 Result
aifc             Stuff to parse AIFF-C and AIFF files.
anydbm           Generic interface to all dbm clones. (dbhash, gdbm,
                 dbm,dumbdbm)
asynchat         Support for 'chat' style protocols
asyncore         Asynchronous File I/O (in select style)
atexit           Register functions to be called at exit of Python interpreter.
audiodev         Audio support for a few platforms.
base64           Conversions to/from base64 RFC-MIME transport encoding .
BaseHTTPServer   Base class forhttp services.
Bastion          "Bastionification" utility (control access to instance vars)
bdb              A generic Python debugger base class.
binhex           Macintosh binhex compression/decompression.
bisect           List bisection algorithms.
bz2              Support for bz2 compression/decompression.
calendar         Calendar printing functions.
cgi              Wraps the WWW Forms Common Gateway Interface (CGI).
cgitb            Utility for handling CGI tracebacks.
CGIHTTPServer    CGI http services.
cmd              A generic class to build line-oriented command interpreters.
datetime         Basic date and time types.
code             Utilities needed to emulate Python's interactive interpreter
codecs           Lookup existing Unicode encodings and register new ones.
colorsys         Conversion functions between RGB and other color systems.
commands         Tools for executing UNIX commands .
compileall       Force "compilation" of all .py files in a directory.
ConfigParser     Configuration file parser (much like windows .ini files)
copy             Generic shallow and deep copying operations.
copy_reg         Helper to provide extensibility for pickle/cPickle.
csv              Read and write files with comma separated values.
dbhash           (g)dbm-compatible interface to bsdhash.hashopen.
dircache         Sorted list of files in a dir, using a cache.
[DEL:dircmp:DEL] [DEL:Defines a class to build directory diff tools on.:DEL]
difflib          Tool for creating delta between sequences.
dis              Bytecode disassembler.
distutils        Package installation system.
doctest          Tool for running and verifying tests inside doc strings.
dospath          Common operations on DOS pathnames.
dumbdbm          A dumb and slow but simple dbm clone.
[DEL:dump:DEL]   [DEL:Print python code that reconstructs a variable.:DEL]
email            Comprehensive support for internet email.
exceptions       Class based built-in exception hierarchy.
filecmp          File comparison.
fileinput        Helper class to quickly write a loop over all standard input
                 files.
[DEL:find:DEL]   [DEL:Find files directory hierarchy matching a pattern.:DEL]
fnmatch          Filename matching with shell patterns.
formatter        A test formatter.
fpformat         General floating point formatting functions.
ftplib           An FTP client class. Based on RFC 959.
gc               Perform garbacge collection, obtain GC debug stats, and tune
                 GC parameters.
getopt           Standard command line processing. See also ftp://
                 www.pauahtun.org/pub/getargspy.zip
getpass          Utilities to get a password and/or the current user name.
glob             filename globbing.
gopherlib        Gopher protocol client interface.
[DEL:grep:DEL]   [DEL:'grep' utilities.:DEL]
gzip             Read & write gzipped files.
heapq            Priority queue implemented using lists organized as heaps.
HMAC             Keyed-Hashing for Message Authentication -- RFC 2104.
htmlentitydefs   Proposed entity definitions for HTML.
htmllib          HTML parsing utilities.
HTMLParser       A parser for HTML and XHTML.
httplib          HTTP client class.
ihooks           Hooks into the "import" mechanism.
imaplib          IMAP4 client.Based on RFC 2060.
imghdr           Recognizing image files based on their first few bytes.
imputil          Privides a way of writing customised import hooks.
inspect          Tool for probing live Python objects.
keyword          List of Python keywords.
knee             A Python re-implementation of hierarchical module import.
linecache        Cache lines from files.
linuxaudiodev    Lunix /dev/audio support.
locale           Support for number formatting using the current locale
                 settings.
logging          Python logging facility.
macpath          Pathname (or related) operations for the Macintosh.
macurl2path      Mac specific module for conversion between pathnames and URLs.
mailbox          A class to handle a unix-style or mmdf-style mailbox.
mailcap          Mailcap file handling (RFC 1524).
mhlib            MH (mailbox) interface.
mimetools        Various tools used by MIME-reading or MIME-writing programs.
mimetypes        Guess the MIME type of a file.
MimeWriter       Generic MIME writer.
mimify           Mimification and unmimification of mail messages.
mmap             Interface to memory-mapped files - they behave like mutable
                 strings./font>
multifile        Class to make multi-file messages easier to handle.
mutex            Mutual exclusion -- for use with module sched.
netrc
nntplib          An NNTP client class. Based on RFC 977.
ntpath           Common operations on DOS pathnames.
nturl2path       Mac specific module for conversion between pathnames and URLs.
optparse         A comprehensive tool for processing command line options.
os               Either mac, dos or posix depending system.
[DEL:packmail:   [DEL:Create a self-unpacking shell archive.:DEL]
DEL]
pdb              A Python debugger.
pickle           Pickling (save and restore) of Python objects (a faster
                 Cimplementation exists in built-in module: cPickle).
pipes            Conversion pipeline templates.
pkgunil          Utilities for working with Python packages.
popen2           variations on pipe open.
poplib           A POP3 client class. Based on the J. Myers POP3 draft.
posixfile        Extended (posix) file operations.
posixpath        Common operations on POSIX pathnames.
pprint           Support to pretty-print lists, tuples, & dictionaries
                 recursively.
profile          Class for profiling python code.
pstats           Class for printing reports on profiled python code.
pydoc            Utility for generating documentation from source files.
pty              Pseudo terminal utilities.
pyexpat          Interface to the Expay XML parser.
py_compile       Routine to "compile" a .py file to a .pyc file.
pyclbr           Parse a Python file and retrieve classes and methods.
Queue            A multi-producer, multi-consumer queue.
quopri           Conversions to/from quoted-printable transport encoding.
rand             Don't use unless you want compatibility with C's rand().
random           Random variable generators
re               Regular Expressions.
repr             Redo repr() but with limits on most sizes.
rexec            Restricted execution facilities ("safe" exec, eval, etc).
rfc822           RFC-822 message manipulation class.
rlcompleter      Word completion for GNU readline 2.0.
robotparser      Parse robots.txt files, useful for web spiders.
sched            A generally useful event scheduler class.
sets             Module for a set datatype.
sgmllib          A parser for SGML.
shelve           Manage shelves of pickled objects.
shlex            Lexical analyzer class for simple shell-like syntaxes.
shutil           Utility functions usable in a shell-like program.
SimpleHTTPServer Simple extension to base http class
site             Append module search paths for third-party packages to
                 sys.path.
smtplib          SMTP Client class (RFC 821)
sndhdr           Several routines that help recognizing sound.
SocketServer     Generic socket server classes.
stat             Constants and functions for interpreting stat/lstat struct.
statcache        Maintain a cache of file stats.
statvfs          Constants for interpreting statvfs struct as returned by
                 os.statvfs()and os.fstatvfs() (if they exist).
string           A collection of string operations.
StringIO         File-like objects that read/write a string buffer (a fasterC
                 implementation exists in built-in module: cStringIO).
sunau            Stuff to parse Sun and NeXT audio files.
sunaudio         Interpret sun audio headers.
symbol           Non-terminal symbols of Python grammar (from "graminit.h").
tabnanny,/font>  Check Python source for ambiguous indentation.
tarfile          Facility for reading and writing to the *nix tarfile format.
telnetlib        TELNET client class. Based on RFC 854.
tempfile         Temporary file name allocation.
textwrap         Object for wrapping and filling text.
threading        Proposed new higher-level threading interfaces
threading_api    (doc of the threading module)
toaiff           Convert "arbitrary" sound files to AIFF files .
token            Tokens (from "token.h").
tokenize         Compiles a regular expression that recognizes Python tokens.
traceback        Format and print Python stack traces.
tty              Terminal utilities.
turtle           LogoMation-like turtle graphics
types            Define names for all type symbols in the std interpreter.
tzparse          Parse a timezone specification.
unicodedata      Interface to unicode properties.
urllib           Open an arbitrary URL.
urlparse         Parse URLs according to latest draft of standard.
user             Hook to allow user-specified customization code to run.
UserDict         A wrapper to allow subclassing of built-in dict class.
UserList         A wrapper to allow subclassing of built-in list class.
UserString       A wrapper to allow subclassing of built-in string class.
[DEL:util:DEL]   [DEL:some useful functions that don't fit elsewhere !!:DEL]
uu               UUencode/UUdecode.
unittest         Utilities for implementing unit testing.
wave             Stuff to parse WAVE files.
weakref          Tools for creating and managing weakly referenced objects.
webbrowser       Platform independent URL launcher.
[DEL:whatsound:  [DEL:Several routines that help recognizing sound files.:DEL]
DEL]
whichdb          Guess which db package to use to open a db file.
xdrlib           Implements (a subset of) Sun XDR (eXternal Data
                 Representation)
xmllib           A parser for XML, using the derived class as static DTD.
xml.dom          Classes for processing XML using the Document Object Model.
xml.sax          Classes for processing XML using the SAX API.
xmlrpclib        Support for remote procedure calls using XML.
zipfile          Read & write PK zipped files.
[DEL:zmod:DEL]   [DEL:Demonstration of abstruse mathematical concepts.:DEL]



* Built-ins *

            sys                 Interpreter state vars and functions
            __built-in__        Access to all built-in python identifiers
            __main__            Scope of the interpreters main program, script or stdin
            array               Obj efficiently representing arrays of basic values
            math                Math functions of C standard
            time                Time-related functions (also the newer datetime module)
            marshal             Read and write some python values in binary format
            struct              Convert between python values and C structs

* Standard *

            getopt              Parse cmd line args in sys.argv.  A la UNIX 'getopt'.
            os                  A more portable interface to OS dependent functionality
            re                  Functions useful for working with regular expressions
            string              Useful string and characters functions and exceptions
            random              Mersenne Twister pseudo-random number generator
            thread              Low-level primitives for working with process threads
            threading           idem, new recommanded interface.

* Unix/Posix *

            dbm                 Interface to Unix ndbm database library
            grp                 Interface to Unix group database
            posix               OS functionality standardized by C and POSIX standards
            posixpath           POSIX pathname functions
            pwd                 Access to the Unix password database
            select              Access to Unix select multiplex file synchronization
            socket              Access to BSD socket interface

* Tk User-interface Toolkit *

            tkinter             Main interface to Tk

* Multimedia *

            audioop             Useful operations on sound fragments
            imageop             Useful operations on images
            jpeg                Access to jpeg image compressor and decompressor
            rgbimg              Access SGI imglib image files

* Cryptographic Extensions *

            md5         Interface to RSA's MD5 message digest algorithm
            sha         Interface to the SHA message digest algorithm
            HMAC        Keyed-Hashing for Message Authentication -- RFC 2104.

* SGI IRIX * (4 & 5)

            al          SGI audio facilities
            AL          al constants
            fl          Interface to FORMS library
            FL          fl constants
            flp Functions for form designer
            fm          Access to font manager library
            gl          Access to graphics library
            GL          Constants for gl
            DEVICE      More constants for gl
            imgfile     Imglib image file interface

* Suns *

            sunaudiodev Access to sun audio interface


Workspace exploration and idiom hints

        dir(<module>)   list functions, variables in <module>
        dir()           get object keys, defaults to local name space
        if __name__ == '__main__': main()            invoke main if running as script
        map(None, lst1, lst2, ...)                   merge lists
        b = a[:]                                     create copy of seq structure
        _                       in interactive mode, is last value printed







Python Mode for Emacs

(Not revised, possibly not up to date)
Type C-c ? when in python-mode for extensive help.
INDENTATION
Primarily for entering new code:
        TAB      indent line appropriately
        LFD      insert newline, then indent
        DEL      reduce indentation, or delete single character
Primarily for reindenting existing code:
        C-c :    guess py-indent-offset from file content; change locally
        C-u C-c :        ditto, but change globally
        C-c TAB  reindent region to match its context
        C-c <    shift region left by py-indent-offset
        C-c >    shift region right by py-indent-offset
MARKING & MANIPULATING REGIONS OF CODE
C-c C-b         mark block of lines
M-C-h           mark smallest enclosing def
C-u M-C-h       mark smallest enclosing class
C-c #           comment out region of code
C-u C-c #       uncomment region of code
MOVING POINT
C-c C-p         move to statement preceding point
C-c C-n         move to statement following point
C-c C-u         move up to start of current block
M-C-a           move to start of def
C-u M-C-a       move to start of class
M-C-e           move to end of def
C-u M-C-e       move to end of class
EXECUTING PYTHON CODE
C-c C-c sends the entire buffer to the Python interpreter
C-c |   sends the current region
C-c !   starts a Python interpreter window; this will be used by
        subsequent C-c C-c or C-c | commands
C-c C-w runs PyChecker

VARIABLES
py-indent-offset        indentation increment
py-block-comment-prefix comment string used by py-comment-region
py-python-command       shell command to invoke Python interpreter
py-scroll-process-buffer        t means always scroll Python process buffer
py-temp-directory       directory used for temp files (if needed)
py-beep-if-tab-change   ring the bell if tab-width is changed


The Python Debugger

(Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE)

Accessing

import pdb      (it's a module written in Python)
        -- defines functions :
           run(statement[,globals[, locals]])
                        -- execute statement string under debugger control, with optional
                           global & local environment.
           runeval(expression[,globals[, locals]])
                        -- same as run, but evaluate expression and return value.
           runcall(function[, argument, ...])
                        -- run function object with given arg(s)
           pm()         -- run postmortem on last exception (like debugging a core file)
           post_mortem(t)
                        -- run postmortem on traceback object <t>

        -- defines class Pdb :
           use Pdb to create reusable debugger objects. Object
           preserves state (i.e. break points) between calls.

        runs until a breakpoint hit, exception, or end of program
        If exception, variable '__exception__' holds (exception,value).

Commands

h, help
        brief reminder of commands
b, break [<arg>]
        if <arg> numeric, break at line <arg> in current file
        if <arg> is function object, break on entry to fcn <arg>
        if no arg, list breakpoints
cl, clear [<arg>]
        if <arg> numeric, clear breakpoint at <arg> in current file
        if no arg, clear all breakpoints after confirmation
w, where
        print current call stack
u, up
        move up one stack frame (to top-level caller)
d, down
        move down one stack frame
s, step
        advance one line in the program, stepping into calls
n, next
        advance one line, stepping over calls
r, return
        continue execution until current function returns
        (return value is saved in variable "__return__", which
        can be printed or manipulated from debugger)
c, continue
        continue until next breakpoint
j, jump lineno
        Set the next line that will be executed
a, args
        print args to current function
rv, retval
        prints return value from last function that returned
p, print <arg>
        prints value of <arg> in current stack frame
l, list [<first> [, <last>]]
               List source code for the current file.
               Without arguments, list 11 lines around the current line
               or continue the previous listing.
               With one argument, list 11 lines starting at that line.
               With two arguments, list the given range;
               if the second argument is less than the first, it is a count.
whatis <arg>
        prints type of <arg>
!
        executes rest of line as a Python statement in the current stack frame
q quit
        immediately stop execution and leave debugger
<return>
        executes last command again
Any input debugger doesn't recognize as a command is assumed to be a
Python statement to execute in the current stack frame, the same way
the exclamation mark ("!") command does.

Example

(1394) python
Python 1.0.3 (Sep 26 1994)
Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
>>> import rm
>>> rm.run()
Traceback (innermost last):
         File "<stdin>", line 1
         File "./rm.py", line 7
           x = div(3)
         File "./rm.py", line 2
           return a / r
ZeroDivisionError: integer division or modulo
>>> import pdb
>>> pdb.pm()
> ./rm.py(2)div: return a / r
(Pdb) list
         1     def div(a):
         2  ->     return a / r
         3
         4     def run():
         5         global r
         6         r = 0
         7         x = div(3)
         8         print x
[EOF]
(Pdb) print r
0
(Pdb) q
>>> pdb.runcall(rm.run)
etc.

Quirks

Breakpoints are stored as filename, line number tuples. If a module is reloaded
after editing, any remembered breakpoints are likely to be wrong.

Always single-steps through top-most stack frame. That is, "c" acts like "n".
PK	%�\L�Zs��html/_images/logging_flow.pngnu�[���PK	%�\�����&=�html/_sources/c-api/exceptions.rst.txtnu�[���PK	%�\��~/66 {Lhtml/_sources/c-api/file.rst.txtnu�[���PK	%�\�J�+
+
!ehtml/_sources/c-api/float.rst.txtnu�[���PK	%�\��g�u	u	$}rhtml/_sources/c-api/function.rst.txtnu�[���PK	%�\X?���%F|html/_sources/c-api/gcsupport.rst.txtnu�[���PK	%�\���E��V�html/_sources/c-api/gen.rst.txtnu�[���PK	%�\@i1�+�+"=�html/_sources/c-api/import.rst.txtnu�[���PK	%�\�~V.BB!d�html/_sources/c-api/index.rst.txtnu�[���PK	%�\�T6��� ��html/_sources/c-api/init.rst.txtnu�[���PK	%�\�O����O�html/_sources/c-api/int.rst.txtnu�[���PK	%�\�?��9o9o!��html/_sources/c-api/intro.rst.txtnu�[���PK	%�\���nn 
html/_sources/c-api/iter.rst.txtnu�[���PK	%�\�ѥ$�html/_sources/c-api/iterator.rst.txtnu�[���PK	%�\��`F��  html/_sources/c-api/list.rst.txtnu�[���PK	%�\�=9�33 J1html/_sources/c-api/long.rst.txtnu�[���PK	%�\$;��::#�Phtml/_sources/c-api/mapping.rst.txtnu�[���PK	%�\�����#Z\html/_sources/c-api/marshal.rst.txtnu�[���PK	%�\&6y$-$-">lhtml/_sources/c-api/memory.rst.txtnu�[���PK	%�\9�	�33"��html/_sources/c-api/method.rst.txtnu�[���PK	%�\��J�"9�html/_sources/c-api/module.rst.txtnu�[���PK	%�\�Q9�� ��html/_sources/c-api/none.rst.txtnu�[���PK	%�\fj�ϣ.�."��html/_sources/c-api/number.rst.txtnu�[���PK	%�\o����	�	%��html/_sources/c-api/objbuffer.rst.txtnu�[���PK	%�\���SDSD"��html/_sources/c-api/object.rst.txtnu�[���PK	%�\D�<11#r2html/_sources/c-api/objimpl.rst.txtnu�[���PK	%�\���tvv'�3html/_sources/c-api/refcounting.rst.txtnu�[���PK	%�\�'
�&�?html/_sources/c-api/reflection.rst.txtnu�[���PK	%�\��`s""$8Fhtml/_sources/c-api/sequence.rst.txtnu�[���PK	%�\������hhtml/_sources/c-api/set.rst.txtnu�[���PK	%�\�3�$��!��html/_sources/c-api/slice.rst.txtnu�[���PK	%�\Qē'><><"��html/_sources/c-api/string.rst.txtnu�[���PK	%�\����v:v:&'�html/_sources/c-api/structures.rst.txtnu�[���PK	%�\$�+�RR�html/_sources/c-api/sys.rst.txtnu�[���PK	%�\Fm�hss!�html/_sources/c-api/tuple.rst.txtnu�[���PK	%�\>d5��
�
 X2html/_sources/c-api/type.rst.txtnu�[���PK	%�\�c�(xx#q=html/_sources/c-api/typeobj.rst.txtnu�[���PK	%�\pin6F�F�#<Chtml/_sources/c-api/unicode.rst.txtnu�[���PK	%�\E�����%��html/_sources/c-api/utilities.rst.txtnu�[���PK	%�\�n\w3434$�html/_sources/c-api/veryhigh.rst.txtnu�[���PK	%�\$�q9#P*html/_sources/c-api/weakref.rst.txtnu�[���PK	%�\��H���$�5html/_sources/c-api/abstract.rst.txtnu�[���PK	%�\���A��&�8html/_sources/c-api/allocation.rst.txtnu�[���PK	%�\��n�e�e�Khtml/_sources/c-api/arg.rst.txtnu�[���PK	%�\
��2 ��html/_sources/c-api/bool.rst.txtnu�[���PK	%�\�Wf�Y�Y"�html/_sources/c-api/buffer.rst.txtnu�[���PK	%�\D��T��%html/_sources/c-api/bytearray.rst.txtnu�[���PK	%�\�
�mmm#�html/_sources/c-api/capsule.rst.txtnu�[���PK	%�\mʼW�� �0html/_sources/c-api/cell.rst.txtnu�[���PK	%�\��?JJ!�8html/_sources/c-api/class.rst.txtnu�[���PK	%�\��NN#6@html/_sources/c-api/cobject.rst.txtnu�[���PK	%�\��l�cc �Ghtml/_sources/c-api/code.rst.txtnu�[���PK	%�\|-�##!�Nhtml/_sources/c-api/codec.rst.txtnu�[���PK	%�\����#�`html/_sources/c-api/complex.rst.txtnu�[���PK	%�\i��
��$@qhtml/_sources/c-api/concrete.rst.txtnu�[���PK	%�\�0���&?yhtml/_sources/c-api/conversion.rst.txtnu�[���PK	%�\I�͖

$I�html/_sources/c-api/datetime.rst.txtnu�[���PK	%�\�
��&��html/_sources/c-api/descriptor.rst.txtnu�[���PK	%�\���MM �html/_sources/c-api/dict.rst.txtnu�[���PK	%�\���ROO(��html/_sources/distributing/index.rst.txtnu�[���PK	%�\���p�p&T�html/_sources/distutils/apiref.rst.txtnu�[���PK	%�\'7�IfVfV)f_
html/_sources/distutils/builtdist.rst.txtnu�[���PK	%�\ �F`*%�
html/_sources/distutils/commandref.rst.txtnu�[���PK	%�\U'HI*��
html/_sources/distutils/configfile.rst.txtnu�[���PK	%�\$��ZZ(�
html/_sources/distutils/examples.rst.txtnu�[���PK	%�\cG���)��
html/_sources/distutils/extending.rst.txtnu�[���PK	%�\�0��%�html/_sources/distutils/index.rst.txtnu�[���PK	%�\ϓ�*r!r!,�html/_sources/distutils/introduction.rst.txtnu�[���PK	%�\ ��!�!,�(html/_sources/distutils/packageindex.rst.txtnu�[���PK	%�\���y�y+�Jhtml/_sources/distutils/setupscript.rst.txtnu�[���PK	%�\��z�0�0*��html/_sources/distutils/sourcedist.rst.txtnu�[���PK	%�\7Ru���)�html/_sources/distutils/uploading.rst.txtnu�[���PK	%�\� �V(A�html/_sources/extending/building.rst.txtnu�[���PK	%�\�w��{/{/)�html/_sources/extending/embedding.rst.txtnu�[���PK	%�\��1N����)�<html/_sources/extending/extending.rst.txtnu�[���PK	%�\�Cs4SS%�
html/_sources/extending/index.rst.txtnu�[���PK	%�\XO������(r#
html/_sources/extending/newtypes.rst.txtnu�[���PK	%�\:n	�  '�html/_sources/extending/windows.rst.txtnu�[���PK	%�\P�9s�� ,html/_sources/faq/design.rst.txtnu�[���PK	%�\{ۻ#�F�F#m�html/_sources/faq/extending.rst.txtnu�[���PK	%�\�T=�GVGV!�html/_sources/faq/general.rst.txtnu�[���PK	%�\�mi��%Whtml/_sources/faq/gui.rst.txtnu�[���PK	%�\Vv��khtml/_sources/faq/index.rst.txtnu�[���PK	%�\��}-	-	#klhtml/_sources/faq/installed.rst.txtnu�[���PK	%�\՘S�{�{�!�uhtml/_sources/faq/library.rst.txtnu�[���PK	%�\����""%��html/_sources/faq/programming.rst.txtnu�[���PK	%�\���6�6!.html/_sources/faq/windows.rst.txtnu�[���PK	%�\���\�\$2Khtml/_sources/howto/argparse.rst.txtnu�[���PK	%�\�%`$�html/_sources/howto/cporting.rst.txtnu�[���PK	%�\a0���U�U"f�html/_sources/howto/curses.rst.txtnu�[���PK	%�\�X�KIDID&�html/_sources/howto/descriptor.rst.txtnu�[���PK	%�\�N�w,w,%'bhtml/_sources/howto/doanddont.rst.txtnu�[���PK	%�\<����&�html/_sources/howto/functional.rst.txtnu�[���PK	%�\iO�{{!_Ihtml/_sources/howto/index.rst.txtnu�[���PK	%�\a��`�`�,+Lhtml/_sources/howto/logging-cookbook.rst.txtnu�[���PK	%�\X������#�7html/_sources/howto/logging.rst.txtnu�[���PK	%�\�,x@�W�W%5�html/_sources/howto/pyporting.rst.txtnu�[���PK	%�\?5����!tChtml/_sources/howto/regex.rst.txtnu�[���PK	%�\��*��O�O#}6html/_sources/howto/sockets.rst.txtnu�[���PK	%�\�X2020#��html/_sources/howto/sorting.rst.txtnu�[���PK	%�\�x'����#�html/_sources/howto/unicode.rst.txtnu�[���PK	%�\0��[�[#8html/_sources/howto/urllib2.rst.txtnu�[���PK	%�\��YjC�C�&>�html/_sources/howto/webservers.rst.txtnu�[���PK	%�\4g9��#�html/_sources/install/index.rst.txtnu�[���PK	%�\����"�"&/�html/_sources/installing/index.rst.txtnu�[���PK	%�\M�J���)H�html/_sources/library/__builtin__.rst.txtnu�[���PK	%�\�I�XX(whtml/_sources/library/__future__.rst.txtnu�[���PK	%�\B���&'html/_sources/library/__main__.rst.txtnu�[���PK	%�\��	[	[%�html/_sources/library/_winreg.rst.txtnu�[���PK	%�\��l33!�vhtml/_sources/library/abc.rst.txtnu�[���PK	%�\ny�*��$v�html/_sources/library/aepack.rst.txtnu�[���PK	%�\�#e��
�
%k�html/_sources/library/aetools.rst.txtnu�[���PK	%�\G`�Q��%��html/_sources/library/aetypes.rst.txtnu�[���PK	%�\�

��"��html/_sources/library/aifc.rst.txtnu�[���PK	%�\��T�� ��html/_sources/library/al.rst.txtnu�[���PK	%�\c�#���#��html/_sources/library/allos.rst.txtnu�[���PK	%�\�vy.$��html/_sources/library/anydbm.rst.txtnu�[���PK	%�\To����'�html/_sources/library/archiving.rst.txtnu�[���PK	%�\քv��#�#&�	html/_sources/library/argparse.rst.txtnu�[���PK	%�\�k))#.html/_sources/library/array.rst.txtnu�[���PK	%�\?��''!}Whtml/_sources/library/ast.rst.txtnu�[���PK	%�\S�`h�#�#&Mhtml/_sources/library/asynchat.rst.txtnu�[���PK	%�\�j{�2�2&��html/_sources/library/asyncore.rst.txtnu�[���PK	%�\|��FF$x�html/_sources/library/atexit.rst.txtnu�[���PK	%�\��~�(�(%�html/_sources/library/audioop.rst.txtnu�[���PK	%�\��V��%html/_sources/library/autogil.rst.txtnu�[���PK	%�\Q�{ll$Nhtml/_sources/library/base64.rst.txtnu�[���PK	%�\�Q�^�(�(,,html/_sources/library/basehttpserver.rst.txtnu�[���PK	%�\a�3
3
%Uhtml/_sources/library/bastion.rst.txtnu�[���PK	%�\��N�0�0!�_html/_sources/library/bdb.rst.txtnu�[���PK	%�\����ll&��html/_sources/library/binascii.rst.txtnu�[���PK	%�\�ؗvv$Q�html/_sources/library/binhex.rst.txtnu�[���PK	%�\�U,�''$�html/_sources/library/bisect.rst.txtnu�[���PK	%�\Je���#��html/_sources/library/bsddb.rst.txtnu�[���PK	%�\�v����!��html/_sources/library/bz2.rst.txtnu�[���PK	%�\_z��,,&Qhtml/_sources/library/calendar.rst.txtnu�[���PK	%�\�n�T>T>$�1html/_sources/library/carbon.rst.txtnu�[���PK	%�\?Ҿ��.�. aphtml/_sources/library/cd.rst.txtnu�[���PK	%�\=��EYEY!w�html/_sources/library/cgi.rst.txtnu�[���PK	%�\�6gE�
�
+
�html/_sources/library/cgihttpserver.rst.txtnu�[���PK	%�\{��::#Lhtml/_sources/library/cgitb.rst.txtnu�[���PK	%�\�;N[[#�html/_sources/library/chunk.rst.txtnu�[���PK	%�\ʼQ.��#�#html/_sources/library/cmath.rst.txtnu�[���PK	%�\��u!u!!�Ahtml/_sources/library/cmd.rst.txtnu�[���PK	%�\�r.b��"chtml/_sources/library/code.rst.txtnu�[���PK	%�\_�Zl��$�html/_sources/library/codecs.rst.txtnu�[���PK	%�\��xʾ�$��html/_sources/library/codeop.rst.txtnu�[���PK	%�\�@����)��html/_sources/library/collections.rst.txtnu�[���PK	%�\�����)�6 html/_sources/library/colorpicker.rst.txtnu�[���PK	%�\9�B<&�: html/_sources/library/colorsys.rst.txtnu�[���PK	%�\K�@w#
#
&4B html/_sources/library/commands.rst.txtnu�[���PK	%�\���>FF(�L html/_sources/library/compileall.rst.txtnu�[���PK	%�\u��X�X�&K_ html/_sources/library/compiler.rst.txtnu�[���PK	%�\$s�r�L�L*�� html/_sources/library/configparser.rst.txtnu�[���PK	%�\"G�3		'�>!html/_sources/library/constants.rst.txtnu�[���PK	%�\;?L||(YH!html/_sources/library/contextlib.rst.txtnu�[���PK	%�\�e4�G%G%$-`!html/_sources/library/cookie.rst.txtnu�[���PK	%�\�r��l�l'ȅ!html/_sources/library/cookielib.rst.txtnu�[���PK	%�\�`R�

"�!html/_sources/library/copy.rst.txtnu�[���PK	%�\��		&k"html/_sources/library/copy_reg.rst.txtnu�[���PK	%�\�w���#�	"html/_sources/library/crypt.rst.txtnu�[���PK	%�\ñ�&cc$!"html/_sources/library/crypto.rst.txtnu�[���PK	%�\�V�~�X�X!�"html/_sources/library/csv.rst.txtnu�[���PK	%�\����a�a$n"html/_sources/library/ctypes.rst.txtnu�[���PK	%�\��zV#V#*��#html/_sources/library/curses.ascii.rst.txtnu�[���PK	%�\��XR�
�
*��#html/_sources/library/curses.panel.rst.txtnu�[���PK	%�\�00�}$}$$��#html/_sources/library/curses.rst.txtnu�[���PK	%�\�`�::*�#%html/_sources/library/custominterp.rst.txtnu�[���PK	%�\���g``'&%html/_sources/library/datatypes.rst.txtnu�[���PK	%�\
�v��#�#&�)%html/_sources/library/datetime.rst.txtnu�[���PK	%�\�/�Y$�M&html/_sources/library/dbhash.rst.txtnu�[���PK	%�\�J��--!G]&html/_sources/library/dbm.rst.txtnu�[���PK	%�\�J����#�i&html/_sources/library/debug.rst.txtnu�[���PK	%�\��%�k&html/_sources/library/decimal.rst.txtnu�[���PK	%�\A\ER��)9�'html/_sources/library/development.rst.txtnu�[���PK	%�\�}wo�w�w%�'html/_sources/library/difflib.rst.txtnu�[���PK	%�\�$�&c�'html/_sources/library/dircache.rst.txtnu�[���PK	%�\:4f�Z�Z!�(html/_sources/library/dis.rst.txtnu�[���PK	%�\\�fߪ�*�^(html/_sources/library/distribution.rst.txtnu�[���PK	%�\�1��'�`(html/_sources/library/distutils.rst.txtnu�[���PK	%�\�{'e@
@
 �h(html/_sources/library/dl.rst.txtnu�[���PK	%�\5��8!!%�v(html/_sources/library/doctest.rst.txtnu�[���PK	%�\�S�2��-֗)html/_sources/library/docxmlrpcserver.rst.txtnu�[���PK	%�\8���%
�)html/_sources/library/dumbdbm.rst.txtnu�[���PK	%�\�V)v""*{�)html/_sources/library/dummy_thread.rst.txtnu�[���PK	%�\ίxe-��)html/_sources/library/dummy_threading.rst.txtnu�[���PK	%�\��/�j(j()s�)html/_sources/library/easydialogs.rst.txtnu�[���PK	%�\�t�v��,6�)html/_sources/library/email-examples.rst.txtnu�[���PK	%�\�hWg�%�%+��)html/_sources/library/email.charset.rst.txtnu�[���PK	%�\��7+H	H	,�*html/_sources/library/email.encoders.rst.txtnu�[���PK	%�\�L؈��*>*html/_sources/library/email.errors.rst.txtnu�[���PK	%�\4�]���->(*html/_sources/library/email.generator.rst.txtnu�[���PK	%�\��~kk*�@*html/_sources/library/email.header.rst.txtnu�[���PK	%�\N�`
u	u	-T^*html/_sources/library/email.iterators.rst.txtnu�[���PK	%�\�1�6�b�b+&h*html/_sources/library/email.message.rst.txtnu�[���PK	%�\Yu/v�&�&(�*html/_sources/library/email.mime.rst.txtnu�[���PK	%�\���W(W(*�*html/_sources/library/email.parser.rst.txtnu�[���PK	%�\�4���>�>#�+html/_sources/library/email.rst.txtnu�[���PK	%�\�iL�KK)
Z+html/_sources/library/email.utils.rst.txtnu�[���PK	%�\IjT��'�s+html/_sources/library/ensurepip.rst.txtnu�[���PK	%�\��Y44#��+html/_sources/library/errno.rst.txtnu�[���PK	%�\9!s�G�G(*�+html/_sources/library/exceptions.rst.txtnu�[���PK	%�\iwlX��#)�+html/_sources/library/fcntl.rst.txtnu�[���PK	%�\�^c��%=,html/_sources/library/filecmp.rst.txtnu�[���PK	%�\���#..)v,html/_sources/library/fileformats.rst.txtnu�[���PK	%�\2��%��'�,html/_sources/library/fileinput.rst.txtnu�[���PK	%�\��&&%M;,html/_sources/library/filesys.rst.txtnu�[���PK	%�\����D�D �>,html/_sources/library/fl.rst.txtnu�[���PK	%�\5�:�
�
 �,html/_sources/library/fm.rst.txtnu�[���PK	%�\�"6j  %�,html/_sources/library/fnmatch.rst.txtnu�[���PK	%�\�Y�ս3�3'V�,html/_sources/library/formatter.rst.txtnu�[���PK	%�\�EKK$j�,html/_sources/library/fpectl.rst.txtnu�[���PK	%�\@
���&	�,html/_sources/library/fpformat.rst.txtnu�[���PK	%�\^�ұ�'2�,html/_sources/library/fractions.rst.txtnu�[���PK	%�\w�O��,�,':�,html/_sources/library/framework.rst.txtnu�[���PK	%�\n�szz(E)-html/_sources/library/frameworks.rst.txtnu�[���PK	%�\��h=h=$+-html/_sources/library/ftplib.rst.txtnu�[���PK	%�\��"'"''�h-html/_sources/library/functions.rst.txtnu�[���PK	%�\�~a'L�.html/_sources/library/functools.rst.txtnu�[���PK	%�\VW���-��.html/_sources/library/future_builtins.rst.txtnu�[���PK	%�\��6#6# �.html/_sources/library/gc.rst.txtnu�[���PK	%�\��>1"x�.html/_sources/library/gdbm.rst.txtnu�[���PK	%�\���')),��.html/_sources/library/gensuitemodule.rst.txtnu�[���PK	%�\��D�$a�.html/_sources/library/getopt.rst.txtnu�[���PK	%�\�~�TT%�/html/_sources/library/getpass.rst.txtnu�[���PK	%�\���&pqpq%l/html/_sources/library/gettext.rst.txtnu�[���PK	%�\��yy 1�/html/_sources/library/gl.rst.txtnu�[���PK	%�\Jյn	n	"��/html/_sources/library/glob.rst.txtnu�[���PK	%�\4)T6��!��/html/_sources/library/grp.rst.txtnu�[���PK	%�\J�����"۷/html/_sources/library/gzip.rst.txtnu�[���PK	%�\&����%	�/html/_sources/library/hashlib.rst.txtnu�[���PK	%�\�a�́3�3#1�/html/_sources/library/heapq.rst.txtnu�[���PK	%�\
���7979"0html/_sources/library/2to3.rst.txtnu�[���PK	%�\L�6�"�U0html/_sources/library/hmac.rst.txtnu�[���PK	%�\����%�a0html/_sources/library/hotshot.rst.txtnu�[���PK	%�\
8���%�r0html/_sources/library/htmllib.rst.txtnu�[���PK	%�\�h�x-x-(�0html/_sources/library/htmlparser.rst.txtnu�[���PK	%�\���N�N�%�0html/_sources/library/httplib.rst.txtnu�[���PK	%�\<[���"�P1html/_sources/library/i18n.rst.txtnu�[���PK	%�\�\� }R1html/_sources/library/ic.rst.txtnu�[���PK	%�\�+��V�V"Zf1html/_sources/library/idle.rst.txtnu�[���PK	%�\ȴ���%R�1html/_sources/library/imageop.rst.txtnu�[���PK	%�\� �!ECEC%H�1html/_sources/library/imaplib.rst.txtnu�[���PK	%�\����
�
%�2html/_sources/library/imgfile.rst.txtnu�[���PK	%�\z��^K
K
$2html/_sources/library/imghdr.rst.txtnu�[���PK	%�\B�(�1111!�&2html/_sources/library/imp.rst.txtnu�[���PK	%�\rs�ff'%X2html/_sources/library/importlib.rst.txtnu�[���PK	%�\&v�oo%�\2html/_sources/library/imputil.rst.txtnu�[���PK	%�\g5�s��#�x2html/_sources/library/index.rst.txtnu�[���PK	%�\�B�m�m%�2html/_sources/library/inspect.rst.txtnu�[���PK	%�\o!����&4�2html/_sources/library/internet.rst.txtnu�[���PK	%�\V��
�
#@�2html/_sources/library/intro.rst.txtnu�[���PK	%�\���g�g� ��2html/_sources/library/io.rst.txtnu�[���PK	%�\�rL�vv!=�3html/_sources/library/ipc.rst.txtnu�[���PK	%�\�����'�3html/_sources/library/itertools.rst.txtnu�[���PK	%�\gv�"?)4html/_sources/library/jpeg.rst.txtnu�[���PK	%�\}��;�c�c"�84html/_sources/library/json.rst.txtnu�[���PK	%�\ϖ��ii%��4html/_sources/library/keyword.rst.txtnu�[���PK	%�\�A�F&|�4html/_sources/library/language.rst.txtnu�[���PK	%�\����__'ݡ4html/_sources/library/linecache.rst.txtnu�[���PK	%�\����a�a$��4html/_sources/library/locale.rst.txtnu�[���PK	%�\P��H{H{,v5html/_sources/library/logging.config.rst.txtnu�[���PK	%�\�O�9�m�m.�5html/_sources/library/logging.handlers.rst.txtnu�[���PK	%�\��: "�"�%q�5html/_sources/library/logging.rst.txtnu�[���PK	%�\xi��!�6html/_sources/library/mac.rst.txtnu�[���PK	%�\&�?��#P�6html/_sources/library/macos.rst.txtnu�[���PK	%�\��z||$��6html/_sources/library/macosa.rst.txtnu�[���PK	%�\���(c�6html/_sources/library/macostools.rst.txtnu�[���PK	%�\nZ���%l�6html/_sources/library/macpath.rst.txtnu�[���PK	%�\veu_!
!
%K�6html/_sources/library/mailbox.rst.txtnu�[���PK	%�\�,��[[%��7html/_sources/library/mailcap.rst.txtnu�[���PK	%�\Z�	���$q�7html/_sources/library/markup.rst.txtnu�[���PK	%�\\��-99%�8html/_sources/library/marshal.rst.txtnu�[���PK	%�\Jg��*�*"48html/_sources/library/math.rst.txtnu�[���PK	%�\���9�
�
!.B8html/_sources/library/md5.rst.txtnu�[���PK	%�\�Rہ~~#~M8html/_sources/library/mhlib.rst.txtnu�[���PK	%�\�6J��'O]8html/_sources/library/mimetools.rst.txtnu�[���PK	%�\='.�o&o&'>o8html/_sources/library/mimetypes.rst.txtnu�[���PK	%�\��r. 
 
(�8html/_sources/library/mimewriter.rst.txtnu�[���PK	%�\���
�
$|�8html/_sources/library/mimify.rst.txtnu�[���PK	%�\��	

)��8html/_sources/library/miniaeframe.rst.txtnu�[���PK	%�\��O���"�8html/_sources/library/misc.rst.txtnu�[���PK	%�\�I6-�� 6�8html/_sources/library/mm.rst.txtnu�[���PK	%�\�},5�(�("E�8html/_sources/library/mmap.rst.txtnu�[���PK	%�\^D4
4
*��8html/_sources/library/modulefinder.rst.txtnu�[���PK	%�\{�U�~~%�8html/_sources/library/modules.rst.txtnu�[���PK	%�\ZG��vJvJ$�8html/_sources/library/msilib.rst.txtnu�[���PK	%�\��>���$�B9html/_sources/library/msvcrt.rst.txtnu�[���PK	%�\_n���'T9html/_sources/library/multifile.rst.txtnu�[���PK	%�\�kk��i�i--n9html/_sources/library/multiprocessing.rst.txtnu�[���PK	%�\d+�N��#W�:html/_sources/library/mutex.rst.txtnu�[���PK	%�\�~ZI��%=�:html/_sources/library/netdata.rst.txtnu�[���PK	%�\;>��//#B�:html/_sources/library/netrc.rst.txtnu�[���PK	%�\
Pe?]
]
!��:html/_sources/library/new.rst.txtnu�[���PK	%�\_�<<<!r�:html/_sources/library/nis.rst.txtnu�[���PK	%�\����8�8%�;html/_sources/library/nntplib.rst.txtnu�[���PK	%�\R��?GG%;;html/_sources/library/numbers.rst.txtnu�[���PK	%�\<��z��%�Z;html/_sources/library/numeric.rst.txtnu�[���PK	%�\��LVLV&�];html/_sources/library/operator.rst.txtnu�[���PK	%�\�O��----&��;html/_sources/library/optparse.rst.txtnu�[���PK	%�\;�};&3&3%�<html/_sources/library/os.path.rst.txtnu�[���PK	%�\/��B�B �=html/_sources/library/os.rst.txtnu�[���PK	%�\@U.ޝC�C){X>html/_sources/library/ossaudiodev.rst.txtnu�[���PK	%�\ʙ*y�
�
&q�>html/_sources/library/othergui.rst.txtnu�[���PK	%�\N@�<<$h�>html/_sources/library/parser.rst.txtnu�[���PK	%�\��>�>!��>html/_sources/library/pdb.rst.txtnu�[���PK	%�\K�p�::)�"?html/_sources/library/persistence.rst.txtnu�[���PK	%�\i�Xh����$d&?html/_sources/library/pickle.rst.txtnu�[���PK	%�\�^����)F�?html/_sources/library/pickletools.rst.txtnu�[���PK	%�\:7�N��#l�?html/_sources/library/pipes.rst.txtnu�[���PK	%�\}�""%��?html/_sources/library/pkgutil.rst.txtnu�[���PK	%�\���R%R%&�?html/_sources/library/platform.rst.txtnu�[���PK	%�\�/�&&&�@html/_sources/library/plistlib.rst.txtnu�[���PK	%�\��Cnn$$$@html/_sources/library/popen2.rst.txtnu�[���PK	%�\�hMLL$�?@html/_sources/library/poplib.rst.txtnu�[���PK	%�\H�o	..#�X@html/_sources/library/posix.rst.txtnu�[���PK	%�\,NO�  'g@html/_sources/library/posixfile.rst.txtnu�[���PK	%�\���o#o#$~�@html/_sources/library/pprint.rst.txtnu�[���PK	%�\��~�o�o%A�@html/_sources/library/profile.rst.txtnu�[���PK	%�\���J��!�Ahtml/_sources/library/pty.rst.txtnu�[���PK	%�\��� �
�
!�Ahtml/_sources/library/pwd.rst.txtnu�[���PK	%�\��8�	�	(�)Ahtml/_sources/library/py_compile.rst.txtnu�[���PK
%�\$qR��$�3Ahtml/_sources/library/pyclbr.rst.txtnu�[���PK
%�\�J����#�@Ahtml/_sources/library/pydoc.rst.txtnu�[���PK
%�\x7��p�p%:QAhtml/_sources/library/pyexpat.rst.txtnu�[���PK
%�\b�7q$j�Ahtml/_sources/library/python.rst.txtnu�[���PK
%�\��6�zz#��Ahtml/_sources/library/queue.rst.txtnu�[���PK
%�\H�Un
n
$��Ahtml/_sources/library/quopri.rst.txtnu�[���PK
%�\�V�-44$O�Ahtml/_sources/library/random.rst.txtnu�[���PK
%�\�f!�>�>� �Bhtml/_sources/library/re.rst.txtnu�[���PK
%�\�JN))&8�Bhtml/_sources/library/readline.rst.txtnu�[���PK
%�\��\�nn"� Chtml/_sources/library/repr.rst.txtnu�[���PK
%�\�bO�{%{%&_3Chtml/_sources/library/resource.rst.txtnu�[���PK
%�\�����(0YChtml/_sources/library/restricted.rst.txtnu�[���PK
%�\���-�-#�fChtml/_sources/library/rexec.rst.txtnu�[���PK
%�\��0�6�6$��Chtml/_sources/library/rfc822.rst.txtnu�[���PK
%�\=E�	�	)��Chtml/_sources/library/rlcompleter.rst.txtnu�[���PK
%�\kYmƎ�)��Chtml/_sources/library/robotparser.rst.txtnu�[���PK
%�\��#��Chtml/_sources/library/runpy.rst.txtnu�[���PK
%�\�#�$$#L�Chtml/_sources/library/sched.rst.txtnu�[���PK
%�\!��!cc*�Dhtml/_sources/library/scrolledtext.rst.txtnu�[���PK
%�\RU�P�P$�Dhtml/_sources/library/select.rst.txtnu�[���PK
%�\�	�}:}:"�cDhtml/_sources/library/sets.rst.txtnu�[���PK
%�\��	BB!��Dhtml/_sources/library/sgi.rst.txtnu�[���PK
%�\g�Ko�)�)%�Dhtml/_sources/library/sgmllib.rst.txtnu�[���PK
%�\�M��
�
!�Dhtml/_sources/library/sha.rst.txtnu�[���PK
%�\�~��  $\�Dhtml/_sources/library/shelve.rst.txtnu�[���PK
%�\t�1,1,#/�Dhtml/_sources/library/shlex.rst.txtnu�[���PK
%�\�gz��4�4$�"Ehtml/_sources/library/shutil.rst.txtnu�[���PK
%�\t�,�)�)$�WEhtml/_sources/library/signal.rst.txtnu�[���PK
%�\qN2���.�Ehtml/_sources/library/simplehttpserver.rst.txtnu�[���PK
%�\���ǁ*�*0�Ehtml/_sources/library/simplexmlrpcserver.rst.txtnu�[���PK
%�\٣6���"��Ehtml/_sources/library/site.rst.txtnu�[���PK
%�\�4�2�	�	#�Ehtml/_sources/library/smtpd.rst.txtnu�[���PK
%�\v::::%�Ehtml/_sources/library/smtplib.rst.txtnu�[���PK
%�\����$�"Fhtml/_sources/library/sndhdr.rst.txtnu�[���PK
%�\<��G=�=�$�)Fhtml/_sources/library/socket.rst.txtnu�[���PK
%�\�=�W�W*[�Fhtml/_sources/library/socketserver.rst.txtnu�[���PK
%�\��\WW$�!Ghtml/_sources/library/someos.rst.txtnu�[���PK
%�\
���		"P$Ghtml/_sources/library/spwd.rst.txtnu�[���PK
%�\F�x�x�%�/Ghtml/_sources/library/sqlite3.rst.txtnu�[���PK
%�\v��_
+
+!x�Ghtml/_sources/library/ssl.rst.txtnu�[���PK
%�\���bb"��Hhtml/_sources/library/stat.rst.txtnu�[���PK
%�\�X.�%�Ihtml/_sources/library/statvfs.rst.txtnu�[���PK
%�\��#�,�,�&�	Ihtml/_sources/library/stdtypes.rst.txtnu�[���PK
%�\�8S�5�5�$r�Jhtml/_sources/library/string.rst.txtnu�[���PK
%�\
8QFF&��Khtml/_sources/library/stringio.rst.txtnu�[���PK
%�\�lЎ�(��Khtml/_sources/library/stringprep.rst.txtnu�[���PK
%�\�����%}�Khtml/_sources/library/strings.rst.txtnu�[���PK
%�\٦� �B�B$��Khtml/_sources/library/struct.rst.txtnu�[���PK
%�\
p�p�(�Khtml/_sources/library/subprocess.rst.txtnu�[���PK
%�\�3����!��Lhtml/_sources/library/sun.rst.txtnu�[���PK
%�\�E!��#�Lhtml/_sources/library/sunau.rst.txtnu�[���PK
%�\�:��&�Lhtml/_sources/library/sunaudio.rst.txtnu�[���PK
%�\J�$W��$D�Lhtml/_sources/library/symbol.rst.txtnu�[���PK
%�\�ɘ��&g�Lhtml/_sources/library/symtable.rst.txtnu�[���PK
%�\{�a ���!��Lhtml/_sources/library/sys.rst.txtnu�[���PK
%�\|�����'v�Mhtml/_sources/library/sysconfig.rst.txtnu�[���PK
%�\$���[[$��Mhtml/_sources/library/syslog.rst.txtnu�[���PK
%�\tB����&S�Mhtml/_sources/library/tabnanny.rst.txtnu�[���PK
%�\sS�/6n6n%x�Mhtml/_sources/library/tarfile.rst.txtnu�[���PK
%�\S�S�::'-Nhtml/_sources/library/telnetlib.rst.txtnu�[���PK
%�\-�	))&�JNhtml/_sources/library/tempfile.rst.txtnu�[���PK
%�\����%�sNhtml/_sources/library/termios.rst.txtnu�[���PK
%�\o��P�D�D"܂Nhtml/_sources/library/test.rst.txtnu�[���PK
%�\<,��h!h!&)�Nhtml/_sources/library/textwrap.rst.txtnu�[���PK
%�\үͳ��$��Nhtml/_sources/library/thread.rst.txtnu�[���PK
%�\�n}�~�~'�Ohtml/_sources/library/threading.rst.txtnu�[���PK
%�\�Wm�e�e""�Ohtml/_sources/library/time.rst.txtnu�[���PK
%�\���N-N-$�Ohtml/_sources/library/timeit.rst.txtnu�[���PK
%�\���X�X!�Phtml/_sources/library/tix.rst.txtnu�[���PK
%�\W��LL �oPhtml/_sources/library/tk.rst.txtnu�[���PK
%�\�������%LvPhtml/_sources/library/tkinter.rst.txtnu�[���PK
%�\8�1�	�	#Q�Phtml/_sources/library/token.rst.txtnu�[���PK
%�\�=����&7Qhtml/_sources/library/tokenize.rst.txtnu�[���PK
%�\��DD#OQhtml/_sources/library/trace.rst.txtnu�[���PK
%�\�
>��)�)'�3Qhtml/_sources/library/traceback.rst.txtnu�[���PK
%�\�#
C�C�!^Qhtml/_sources/library/ttk.rst.txtnu�[���PK
%�\M��T��!�>Rhtml/_sources/library/tty.rst.txtnu�[���PK
%�\h�a�a�$�BRhtml/_sources/library/turtle.rst.txtnu�[���PK
%�\�&�88#�=Shtml/_sources/library/types.rst.txtnu�[���PK
%�\�z�(��#,VShtml/_sources/library/undoc.rst.txtnu�[���PK
%�\��hh)pShtml/_sources/library/unicodedata.rst.txtnu�[���PK
%�\����DD&ֆShtml/_sources/library/unittest.rst.txtnu�[���PK
%�\}2$��"4�Thtml/_sources/library/unix.rst.txtnu�[���PK
%�\�:#�a�a$p�Thtml/_sources/library/urllib.rst.txtnu�[���PK
%�\;��3����%D/Uhtml/_sources/library/urllib2.rst.txtnu�[���PK
%�\�Vt��>�>&$�Uhtml/_sources/library/urlparse.rst.txtnu�[���PK
%�\v'�
�
"A�Uhtml/_sources/library/user.rst.txtnu�[���PK
%�\�z�J$J$&OVhtml/_sources/library/userdict.rst.txtnu�[���PK
%�\F�{�A	A	 �'Vhtml/_sources/library/uu.rst.txtnu�[���PK
%�\ux� � "�1Vhtml/_sources/library/uuid.rst.txtnu�[���PK
%�\���6gMgM&�RVhtml/_sources/library/warnings.rst.txtnu�[���PK
%�\G)D���"I�Vhtml/_sources/library/wave.rst.txtnu�[���PK
%�\�1�W~2~2%R�Vhtml/_sources/library/weakref.rst.txtnu�[���PK
%�\	�Ň&�&(%�Vhtml/_sources/library/webbrowser.rst.txtnu�[���PK
%�\3�p_��%Whtml/_sources/library/whichdb.rst.txtnu�[���PK
%�\(#Bf%�Whtml/_sources/library/windows.rst.txtnu�[���PK
%�\ԐVC��&bWhtml/_sources/library/winsound.rst.txtnu�[���PK
%�\y��mgwgw%�'Whtml/_sources/library/wsgiref.rst.txtnu�[���PK
%�\�>�[��$>�Whtml/_sources/library/xdrlib.rst.txtnu�[���PK
%�\)v���+�+-�Whtml/_sources/library/xml.dom.minidom.rst.txtnu�[���PK
%�\��##-D�Whtml/_sources/library/xml.dom.pulldom.rst.txtnu�[���PK
%�\ծ����%��Whtml/_sources/library/xml.dom.rst.txtnu�[���PK
%�\b�~�{�{�3�Xhtml/_sources/library/xml.etree.elementtree.rst.txtnu�[���PK
%�\~E�x��!�Yhtml/_sources/library/xml.rst.txtnu�[���PK
%�\Xm�o<<-3Yhtml/_sources/library/xml.sax.handler.rst.txtnu�[���PK
%�\�I��/�/,poYhtml/_sources/library/xml.sax.reader.rst.txtnu�[���PK
%�\��p<<%��Yhtml/_sources/library/xml.sax.rst.txtnu�[���PK
%�\M����
�
+>�Yhtml/_sources/library/xml.sax.utils.rst.txtnu�[���PK
%�\�w�%XX'��Yhtml/_sources/library/xmlrpclib.rst.txtnu�[���PK
%�\�U�p�I�I%�Zhtml/_sources/library/zipfile.rst.txtnu�[���PK
%�\6a��EE'jZhtml/_sources/library/zipimport.rst.txtnu�[���PK
%�\lZݦ�1�1"��Zhtml/_sources/library/zlib.rst.txtnu�[���PK
%�\[���\\.ϳZhtml/_sources/reference/compound_stmts.rst.txtnu�[���PK
%�\��J�����)K[html/_sources/reference/datamodel.rst.txtnu�[���PK
%�\��{��*�*.$�\html/_sources/reference/executionmodel.rst.txtnu�[���PK
%�\�mW&]�]�+L�\html/_sources/reference/expressions.rst.txtnu�[���PK
%�\6�� ��'�]html/_sources/reference/grammar.rst.txtnu�[���PK
%�\]lh_��%+�]html/_sources/reference/index.rst.txtnu�[���PK
%�\�)�1��,/�]html/_sources/reference/introduction.rst.txtnu�[���PK
%�\�F~`�q�q0!^html/_sources/reference/lexical_analysis.rst.txtnu�[���PK
%�\|l5�5�,v^html/_sources/reference/simple_stmts.rst.txtnu�[���PK
%�\0�pI�
�
3�_html/_sources/reference/toplevel_components.rst.txtnu�[���PK
%�\���'�(_html/_sources/tutorial/appendix.rst.txtnu�[���PK
%�\�
����'�:_html/_sources/tutorial/appetite.rst.txtnu�[���PK
%�\ߞ�l��&�L_html/_sources/tutorial/classes.rst.txtnu�[���PK
%�\�9'm�\�\*X�_html/_sources/tutorial/controlflow.rst.txtnu�[���PK
%�\��ڷ�c�c-�;`html/_sources/tutorial/datastructures.rst.txtnu�[���PK
%�\?po��;�;%�`html/_sources/tutorial/errors.rst.txtnu�[���PK
%�\�Egm!!,��`html/_sources/tutorial/floatingpoint.rst.txtnu�[���PK
%�\Kͧ�F	F	$c�`html/_sources/tutorial/index.rst.txtnu�[���PK
%�\��>�>*�ahtml/_sources/tutorial/inputoutput.rst.txtnu�[���PK
%�\A��)__*Fahtml/_sources/tutorial/interactive.rst.txtnu�[���PK
%�\�~+��*�`ahtml/_sources/tutorial/interpreter.rst.txtnu�[���PK
%�\g�J�OUOU+�wahtml/_sources/tutorial/introduction.rst.txtnu�[���PK
%�\���+W`W`&b�ahtml/_sources/tutorial/modules.rst.txtnu�[���PK
%�\�@"Ά&�&%.bhtml/_sources/tutorial/stdlib.rst.txtnu�[���PK
%�\���_�;�;&�Tbhtml/_sources/tutorial/stdlib2.rst.txtnu�[���PK
%�\�ٗ�&Őbhtml/_sources/tutorial/whatnow.rst.txtnu�[���PK
%�\��ęW�W#+�bhtml/_sources/using/cmdline.rst.txtnu�[���PK
%�\SϤ��!�bhtml/_sources/using/index.rst.txtnu�[���PK
%�\/r��aa�bhtml/_sources/using/mac.rst.txtnu�[���PK
%�\�<� �chtml/_sources/using/unix.rst.txtnu�[���PK
%�\?���3�3#�*chtml/_sources/using/windows.rst.txtnu�[���PK
%�\5nBfJ�J�"_chtml/_sources/whatsnew/2.0.rst.txtnu�[���PK
%�\��VR����"�Gdhtml/_sources/whatsnew/2.1.rst.txtnu�[���PK
%�\�Ҫ:����"��dhtml/_sources/whatsnew/2.2.rst.txtnu�[���PK
%�\���?^?^"��ehtml/_sources/whatsnew/2.3.rst.txtnu�[���PK
%�\;�]��"@#ghtml/_sources/whatsnew/2.4.rst.txtnu�[���PK
%�\(QK�,�,�"�hhtml/_sources/whatsnew/2.5.rst.txtnu�[���PK
%�\@��y��"�ihtml/_sources/whatsnew/2.6.rst.txtnu�[���PK
%�\l>�����"b�khtml/_sources/whatsnew/2.7.rst.txtnu�[���PK
%�\U����$v�mhtml/_sources/whatsnew/index.rst.txtnu�[���PK
%�\~7����h�mhtml/_sources/about.rst.txtnu�[���PK
%�\ �@���mhtml/_sources/bugs.rst.txtnu�[���PK
%�\�oL�mhtml/_sources/contents.rst.txtnu�[���PK
%�\˗���m�mhtml/_sources/copyright.rst.txtnu�[���PK
%�\�WV����mhtml/_sources/glossary.rst.txtnu�[���PK
%�\>�(L�L��7nhtml/_sources/license.rst.txtnu�[���PK
%�\<>��z�nhtml/_static/ajax-loader.gifnu�[���PK
%�\�o�Ŭ�g�nhtml/_static/basic.cssnu�[���PK
%�\`A�?��Yohtml/_static/classic.cssnu�[���PK
%�\x,���'ohtml/_static/comment-bright.pngnu�[���PK
%�\5��==johtml/_static/comment-close.pngnu�[���PK
%�\4�����ohtml/_static/comment.pngnu�[���PK
%�\��`x
x
�!ohtml/_static/copybutton.jsnu�[���PK
%�\_���,ohtml/_static/default.cssnu�[���PK
%�\JO�S$$�,ohtml/_static/doctools.jsnu�[���PK
%�\N�9�%4Qohtml/_static/documentation_options.jsnu�[���PK
%�\�'����Rohtml/_static/down-pressed.pngnu�[���PK
%�\9.�����Sohtml/_static/down.pngnu�[���PK
%�\S[�S�Tohtml/_static/file.pngnu�[���PK
%�\����:Vohtml/_static/jquery-3.2.1.jsnu�[���PK
%�\)��R�R�mshtml/_static/jquery.jsnu�[���PK
%�\���ZZV�thtml/_static/minus.pngnu�[���PK
%�\�]l�==��thtml/_static/opensearch.xmlnu�[���PK
%�\��%ZZZ~�thtml/_static/plus.pngnu�[���PK
%�\��
ͷ��thtml/_static/py.pngnu�[���PK
%�\�PlS++�thtml/_static/pygments.cssnu�[���PK
%�\����icic��thtml/_static/searchtools.jsnu�[���PK
%�\�y��pp?<uhtml/_static/sidebar.jsnu�[���PK
%�\F@���Suhtml/_static/switchers.jsnu�[���PK
%�\��`�`� �guhtml/_static/underscore-1.3.1.jsnu�[���PK
%�\��;�l/l/��uhtml/_static/underscore.jsnu�[���PK
%�\���H��T!vhtml/_static/up-pressed.pngnu�[���PK
%�\>u���u"vhtml/_static/up.pngnu�[���PK
%�\Fo,�cc�#vhtml/_static/websupport.jsnu�[���PK
%�\�NC�L!L!؆vhtml/c-api/gen.htmlnu�[���PK
%�\+�����g�vhtml/c-api/import.htmlnu�[���PK
%�\G0P�4�4?4whtml/c-api/index.htmlnu�[���PK
%�\��n-�-�iwhtml/c-api/init.htmlnu�[���PK
%�\#*9l0P0P�yhtml/c-api/int.htmlnu�[���PK
%�\��A����\yhtml/c-api/intro.htmlnu�[���PK
%�\�g}��'�'�_zhtml/c-api/iter.htmlnu�[���PK
%�\���6.6.��zhtml/c-api/iterator.htmlnu�[���PK
%�\�L>�^`^`:�zhtml/c-api/list.htmlnu�[���PK
%�\��7f�����{html/c-api/long.htmlnu�[���PK
%�\S�f�>�>��{html/c-api/mapping.htmlnu�[���PK
%�\	�c�?�?��{html/c-api/marshal.htmlnu�[���PK
%�\UV� ÀÀL|html/c-api/memory.htmlnu�[���PK
%�\ۏ�
&5&5U�|html/c-api/method.htmlnu�[���PK
%�\�	@��B�B��|html/c-api/module.htmlnu�[���PK
%�\��s�[[}html/c-api/none.htmlnu�[���PK
%�\�9�½½�2}html/c-api/number.htmlnu�[���PK
%�\?�q00��}html/c-api/objbuffer.htmlnu�[���PK
%�\���c����!~html/c-api/object.htmlnu�[���PK
%�\��
QQhtml/c-api/objimpl.htmlnu�[���PK
%�\'S�Z,2,2�'html/c-api/refcounting.htmlnu�[���PK
%�\_dz��)�)Zhtml/c-api/reflection.htmlnu�[���PK
%�\�c$D~D~�html/c-api/sequence.htmlnu�[���PK
%�\����{�{��html/c-api/set.htmlnu�[���PK
%�\^��55�~�html/c-api/slice.htmlnu�[���PK
%�\���]����<��html/c-api/string.htmlnu�[���PK
%�\-�D�����D�html/c-api/structures.htmlnu�[���PK
%�\O+��R�RKށhtml/c-api/sys.htmlnu�[���PK
%�\����S�S�1�html/c-api/tuple.htmlnu�[���PK
%�\�h���:�:���html/c-api/type.htmlnu�[���PK
%�\K�Yi�������html/c-api/typeobj.htmlnu�[���PK
%�\)�i�i�i����html/c-api/unicode.htmlnu�[���PK
%�\���ɤ�@T�html/c-api/utilities.htmlnu�[���PK
%�\<��ޭޭ-r�html/c-api/veryhigh.htmlnu�[���PK
%�\��ۄ#5#5S �html/c-api/weakref.htmlnu�[���PK
%�\�HĴ33�U�html/c-api/abstract.htmlnu�[���PK
%�\"8t_I_I8s�html/c-api/allocation.htmlnu�[���PK
%�\Q���2�2�Ἀhtml/c-api/arg.htmlnu�[���PK
%�\Tn�8)')'V��html/c-api/bool.htmlnu�[���PK
%�\y���g�g��Չhtml/c-api/buffer.htmlnu�[���PK
%�\��1�}7}7p��html/c-api/bytearray.htmlnu�[���PK
%�\��o�Q�Q6̊html/c-api/capsule.htmlnu�[���PK
%�\���+�+h�html/c-api/cell.htmlnu�[���PK
%�\
�N&�,�,fJ�html/c-api/class.htmlnu�[���PK
%�\m��2/2/Dw�html/c-api/cobject.htmlnu�[���PK
%�\����-�-���html/c-api/code.htmlnu�[���PK
%�\�R<ISIS�ԋhtml/c-api/codec.htmlnu�[���PK
%�\��9�Q�Q(�html/c-api/complex.htmlnu�[���PK
%�\�;�=�=z�html/c-api/concrete.htmlnu�[���PK
%�\&cn[n[K��html/c-api/conversion.htmlnu�[���PK
%�\�g��egeg�html/c-api/datetime.htmlnu�[���PK
%�\
kc//�{�html/c-api/descriptor.htmlnu�[���PK
%�\��ƁƁ���html/c-api/dict.htmlnu�[���PK
%�\�Q\tGkGk-�html/c-api/exceptions.htmlnu�[���PK
%�\'��^�^���html/c-api/file.htmlnu�[���PK
%�\"�:�vDvD��html/c-api/float.htmlnu�[���PK
%�\I;sy�7�7�<�html/c-api/function.htmlnu�[���PK
%�\��z�F]F]�t�html/c-api/gcsupport.htmlnu�[���PK
%�\,�~!F!FOҐhtml/distributing/index.htmlnu�[���PK
%�\)��b�b���html/distutils/apiref.htmlnu�[���PK
%�\�5�S��h
�html/distutils/builtdist.htmlnu�[���PK
%�\�Kg������html/distutils/commandref.htmlnu�[���PK
%�\i�>H>H�ɔhtml/distutils/configfile.htmlnu�[���PK
%�\�2�JfJf0�html/distutils/examples.htmlnu�[���PK
%�\9�x�7�7�x�html/distutils/extending.htmlnu�[���PK
%�\9�0([a[a���html/distutils/index.htmlnu�[���PK
%�\49�P�P [�html/distutils/introduction.htmlnu�[���PK
%�\>$�f�f �c�html/distutils/packageindex.htmlnu�[���PK
%�\�����
�
sʖhtml/distutils/setupscript.htmlnu�[���PK
%�\��]s]svؗhtml/distutils/sourcedist.htmlnu�[���PK
%�\�r��!L�html/distutils/uploading.htmlnu�[���PK
%�\j�$KNKNp`�html/extending/building.htmlnu�[���PK
%�\��D<�<���html/extending/embedding.htmlnu�[���PK
%�\�6��K�html/extending/extending.htmlnu�[���PK
%�\l?G��/�/�i�html/extending/index.htmlnu�[���PK
%�\�3D���ݙ�html/extending/newtypes.htmlnu�[���PK
%�\o�P�G�Gߩ�html/extending/windows.htmlnu�[���PK
%�\؎x��H�H��html/faq/design.htmlnu�[���PK
%�\�������:�html/faq/extending.htmlnu�[���PK
%�\�K-�-��.�html/faq/general.htmlnu�[���PK
%�\#tmBBۢhtml/faq/gui.htmlnu�[���PK
%�\EF�U��z�html/faq/index.htmlnu�[���PK
%�\`�Rh�$�$L8�html/faq/installed.htmlnu�[���PK
%�\}��}�}9]�html/faq/library.htmlnu�[���PK
%�\��h�]T]TGۤhtml/faq/programming.htmlnu�[���PK
%�\��9����/�html/faq/windows.htmlnu�[���PK
%�\�
�Z�Z�N��html/genindex-S.htmlnu�[���PK
%�\ ��r3O3O쀪html/genindex-Symbols.htmlnu�[���PK
%�\��w����iЪhtml/genindex-T.htmlnu�[���PK
%�\�6�X����R�html/genindex-U.htmlnu�[���PK
%�\ �Q�30304�html/genindex-V.htmlnu�[���PK
%�\p����Y�Y�1�html/genindex-W.htmlnu�[���PK
%�\r�~�$�$���html/genindex-X.htmlnu�[���PK
%�\�!A����html/genindex-Y.htmlnu�[���PK
%�\�)�x##�Ȭhtml/genindex-Z.htmlnu�[���PK
%�\ <��V�V�V�html/genindex-_.htmlnu�[���PK
%�\{Q-p==�}�html/genindex-all.htmlnu�[���PK
%�\�|�s��html/genindex.htmlnu�[���PK
%�\��$�QLQL��html/glossary.htmlnu�[���PK
%�\��oW#W#Ib�html/index.htmlnu�[���PK
%�\�5xՃ���߅�html/license.htmlnu�[���PK
%�\#��@�@��v�html/py-modindex.htmlnu�[���PK
%�\�R8WLL(5�html/objects.invnu�[���PK
%�\[!����~��html/searchindex.jsnu�[���PK
%�\,U7U7dQ�html/howto/argparse.htmlnu�[���PK
%�\^�`員����html/howto/cporting.htmlnu�[���PK
%�\��ͰͰ�*�html/howto/curses.htmlnu�[���PK
%�\�P��������html/howto/descriptor.htmlnu�[���PK
%�\�?Qy�y�0��html/howto/doanddont.htmlnu�[���PK
%�\�Y@_���h�html/howto/functional.htmlnu�[���PK
%�\�6C����~�html/howto/index.htmlnu�[���PK
%�\ށ�_�/�/ ��html/howto/logging-cookbook.htmlnu�[���PK
%�\��p%������html/howto/logging.htmlnu�[���PK
%�\1[��+�+��}�html/howto/pyporting.htmlnu�[���PK
%�\?�u9D9DO2�html/howto/regex.htmlnu�[���PK
%�\)��#�#��v�html/howto/sockets.htmlnu�[���PK
%�\a�kR�R�7�html/howto/sorting.htmlnu�[���PK
%�\n�~||���html/howto/unicode.htmlnu�[���PK
%�\�4��������html/howto/urllib2.htmlnu�[���PK
%�\;�����u��html/howto/webservers.htmlnu�[���PK
%�\�U��o�o���html/install/index.htmlnu�[���PK
%�\MR�PUPU�A�html/installing/index.htmlnu�[���PK
%�\��o=+=+K��html/library/__builtin__.htmlnu�[���PK
%�\b�`9`9���html/library/__future__.htmlnu�[���PK
%�\11�XX���html/library/__main__.htmlnu�[���PK
%�\ݷ&Bw�w�#�html/library/_winreg.htmlnu�[���PK
%�\b{�S�d�d��html/library/abc.htmlnu�[���PK
%�\��dyT7T7
|�html/library/aepack.htmlnu�[���PK
%�\��Y�@@���html/library/aetools.htmlnu�[���PK
%�\��wRR���html/library/aetypes.htmlnu�[���PK
%�\�֫��a�aZF�html/library/aifc.htmlnu�[���PK
%�\���]�H�H���html/library/al.htmlnu�[���PK
%�\H<�������html/library/allos.htmlnu�[���PK
%�\2x�x�F�F�{�html/library/anydbm.htmlnu�[���PK
%�\;�	^'^'���html/library/archiving.htmlnu�[���PK
%�\�������html/library/argparse.htmlnu�[���PK
%�\�v�o|o|���html/library/array.htmlnu�[���PK
%�\��2���am�html/library/ast.htmlnu�[���PK
%�\�1�؊�����html/library/asynchat.htmlnu�[���PK
%�\��>��������html/library/asyncore.htmlnu�[���PK
%�\v���HH�&�html/library/atexit.htmlnu�[���PK
%�\�s��̅̅�n�html/library/audioop.htmlnu�[���PK
%�\�M�""��html/library/autogil.htmlnu�[���PK
%�\�MKfUfUl�html/library/base64.htmlnu�[���PK
%�\�XiA�A� m�html/library/basehttpserver.htmlnu�[���PK
%�\mV�..���html/library/bastion.htmlnu�[���PK
%�\Bt����
.�html/library/bdb.htmlnu�[���PK
%�\��X��Y�Y�html/library/binascii.htmlnu�[���PK
%�\HWe�-,-,!*�html/library/binhex.htmlnu�[���PK
%�\���XZ`Z`�V�html/library/bisect.htmlnu�[���PK
%�\�_��o�o8��html/library/bsddb.htmlnu�[���PK
%�\/_�xqxq,'�html/library/bz2.htmlnu�[���PK
%�\"�?"�"��html/library/calendar.htmlnu�[���PK
%�\��]��U<�html/library/carbon.htmlnu�[���PK
%�\���QuQu��html/library/cd.htmlnu�[���PK
%�\B�r�r�P}�html/library/cgi.htmlnu�[���PK
%�\�&�6�6X�html/library/cgihttpserver.htmlnu�[���PK
%�\��f�/�/ ��html/library/cgitb.htmlnu�[���PK
%�\�D��>>N��html/library/chunk.htmlnu�[���PK
%�\�y���n�n���html/library/cmath.htmlnu�[���PK
%�\<�D'rqrq�l�html/library/cmd.htmlnu�[���PK
%�\v�[`OiOi{�html/library/code.htmlnu�[���PK
%�\�v�����H�html/library/codecs.htmlnu�[���PK
%�\��$>>J�html/library/codeop.htmlnu�[���PK
%�\l�*�@�@�T�html/library/collections.htmlnu�[���PK
%�\��rcc��html/library/colorpicker.htmlnu�[���PK
%�\�pҏ.�.h�html/library/colorsys.htmlnu�[���PK
%�\�O9?�<�<A�html/library/commands.htmlnu�[���PK
%�\�)>�H�H'!html/library/compileall.htmlnu�[���PK
%�\�0�yy(y(0jhtml/library/compiler.htmlnu�[���PK
%�\��r���html/library/configparser.htmlnu�[���PK
%�\�#�6�6�html/library/constants.htmlnu�[���PK
%�\��3�X�X��html/library/contextlib.htmlnu�[���PK
%�\���~�~�,html/library/cookie.htmlnu�[���PK
%�\(�u�c�c��html/library/cookielib.htmlnu�[���PK
%�\�P�2�2�3html/library/copy.htmlnu�[���PK
%�\�P�[c9c9�fhtml/library/copy_reg.htmlnu�[���PK
%�\��a �)�){�html/library/crypt.htmlnu�[���PK
%�\�a<�QQY�html/library/crypto.htmlnu�[���PK
%�\)��T�*�*��html/library/csv.htmlnu�[���PK
%�\��T		�	html/library/ctypes.htmlnu�[���PK
%�\�P�)a)a�
html/library/curses.ascii.htmlnu�[���PK
%�\�M�M�
html/library/curses.htmlnu�[���PK
%�\^ro��=�=�
html/library/curses.panel.htmlnu�[���PK
%�\�ZZ�Khtml/library/custominterp.htmlnu�[���PK
%�\2���_F_Fxkhtml/library/datatypes.htmlnu�[���PK
%�\HX.����"�html/library/datetime.htmlnu�[���PK
%�\�_`��A�Aj�html/library/dbhash.htmlnu�[���PK
%�\����4�4k�html/library/dbm.htmlnu�[���PK
%�\:����)�)shtml/library/debug.htmlnu�[���PK
%�\M�ukdkd�1html/library/decimal.htmlnu�[���PK
%�\����9�9=�html/library/development.htmlnu�[���PK
%�\�;�GgGgv�html/library/difflib.htmlnu�[���PK
%�\����008html/library/dircache.htmlnu�[���PK
%�\oԝ�H�H[hhtml/library/dis.htmlnu�[���PK
%�\ZHn���\�html/library/distribution.htmlnu�[���PK
%�\�P^�'�'��html/library/distutils.htmlnu�[���PK
%�\(�EE��html/library/dl.htmlnu�[���PK
%�\d�z-���<html/library/doctest.htmlnu�[���PK
%�\M :�D�D!Hhtml/library/docxmlrpcserver.htmlnu�[���PK
%�\s�u�<�<>Xhtml/library/dumbdbm.htmlnu�[���PK
%�\t�y�Q'Q'D�html/library/dummy_thread.htmlnu�[���PK
%�\>���"�"!�html/library/dummy_threading.htmlnu�[���PK
%�\�p��d�d��html/library/easydialogs.htmlnu�[���PK
%�\Xe�@�@� �a html/library/email-examples.htmlnu�[���PK
%�\K�?�r�r[!html/library/email.charset.htmlnu�[���PK
%�\U&A\/2/2 ��!html/library/email.encoders.htmlnu�[���PK
%�\1�j� F F�!html/library/email.errors.htmlnu�[���PK
%�\(eZeZ!�"html/library/email.generator.htmlnu�[���PK
%�\,��޴q�q=b"html/library/email.header.htmlnu�[���PK
%�\K|����?�"html/library/email.htmlnu�[���PK
%�\�>LRO1O1!0�#html/library/email.iterators.htmlnu�[���PK
%�\�t--��#html/library/email.message.htmlnu�[���PK
%�\�i+�{�{L�$html/library/email.mime.htmlnu�[���PK
%�\b�5F�F�?n%html/library/email.parser.htmlnu�[���PK
%�\�;I�i�i�%html/library/email.utils.htmlnu�[���PK
%�\��?��G�G�a&html/library/ensurepip.htmlnu�[���PK
%�\~��6�6�Ʃ&html/library/errno.htmlnu�[���PK
%�\�5��CG'html/library/exceptions.htmlnu�[���PK
%�\bZ�N�f�f\@(html/library/fcntl.htmlnu�[���PK
%�\L��O�]�](�(html/library/filecmp.htmlnu�[���PK
%�\l�R��%�%.)html/library/fileformats.htmlnu�[���PK
%�\~	\�i�i0+)html/library/fileinput.htmlnu�[���PK
%�\$��r*r*:�)html/library/filesys.htmlnu�[���PK
%�\����������)html/library/fl.htmlnu�[���PK
%�\T(��2�2�*html/library/fm.htmlnu�[���PK
%�\��t�?�?�*html/library/fnmatch.htmlnu�[���PK
%�\`�c������+html/library/formatter.htmlnu�[���PK
%�\�[z�A�A,�+html/library/fpectl.htmlnu�[���PK
%�\~��H�,�,c�+html/library/fpformat.htmlnu�[���PK
%�\��Y�8a8al,html/library/fractions.htmlnu�[���PK
%�\2�WF�F��r,html/library/framework.htmlnu�[���PK
%�\(���-html/library/frameworks.htmlnu�[���PK
%�\�A�	����K!-html/library/ftplib.htmlnu�[���PK
%�\᭙BH#H#<�-html/library/functions.htmlnu�[���PK
%�\�����s�s�1html/library/functools.htmlnu�[���PK
%�\q���8�8!�z1html/library/future_builtins.htmlnu�[���PK
%�\�Nݱooų1html/library/gc.htmlnu�[���PK
%�\h�j��E�E#2html/library/gdbm.htmlnu�[���PK
%�\�j��11 �h2html/library/gensuitemodule.htmlnu�[���PK
%�\��c��b�bQ�2html/library/getopt.htmlnu�[���PK
%�\�"��,�,Y�2html/library/getpass.htmlnu�[���PK
%�\��i�K�KD*3html/library/gettext.htmlnu�[���PK
%�\�-��__xv4html/library/gl.htmlnu�[���PK
%�\Ē{^8^8��4html/library/glob.htmlnu�[���PK
%�\�i!�4,4,v5html/library/grp.htmlnu�[���PK
%�\(�/`P`P�:5html/library/gzip.htmlnu�[���PK
%�\�&��{c{c��5html/library/hashlib.htmlnu�[���PK
%�\��%3J�J�Y�5html/library/heapq.htmlnu�[���PK
%�\a�&8&8�w6html/library/hmac.htmlnu�[���PK
%�\�-�K�N�NV�6html/library/hotshot.htmlnu�[���PK
%�\�蒙"l"lR�6html/library/htmllib.htmlnu�[���PK
%�\�������k7html/library/htmlparser.htmlnu�[���PK
%�\#
��8html/library/httplib.htmlnu�[���PK
%�\�V�&?'?'''9html/library/i18n.htmlnu�[���PK
%�\�����H�H�N9html/library/ic.htmlnu�[���PK
%�\�*,����Η9html/library/idle.htmlnu�[���PK
%�\�nj�>�>�<:html/library/imageop.htmlnu�[���PK
%�\@
X�����{:html/library/imaplib.htmlnu�[���PK
%�\�k�s�1�1�`;html/library/imgfile.htmlnu�[���PK
%�\����/�/Œ;html/library/imghdr.htmlnu�[���PK
%�\$�a����;html/library/imp.htmlnu�[���PK
%�\�-�O�"�"V<html/library/importlib.htmlnu�[���PK
%�\��
��,y<html/library/imputil.htmlnu�[���PK
%�\�����4�4��<html/library/index.htmlnu�[���PK
%�\�1)�����1>html/library/inspect.htmlnu�[���PK
%�\mǷpff?html/library/internet.htmlnu�[���PK
%�\�$��$�$kv?html/library/intro.htmlnu�[���PK
%�\"��%�%�;�?html/library/io.htmlnu�[���PK
%�\���G�@�@�WAhtml/library/ipc.htmlnu�[���PK
%�\g�]�������Ahtml/library/itertools.htmlnu�[���PK
%�\љc߽5�5߂Chtml/library/jpeg.htmlnu�[���PK
%�\>V�����Chtml/library/json.htmlnu�[���PK
%�\���U  ��Dhtml/library/keyword.htmlnu�[���PK
%�\3�2��-�-Q�Dhtml/library/language.htmlnu�[���PK
%�\�d�&�,�,B'Ehtml/library/linecache.htmlnu�[���PK
%�\�0&����%TEhtml/library/locale.htmlnu�[���PK
%�\˹�8�8 �DFhtml/library/logging.config.htmlnu�[���PK
%�\�F�)B9B9"�}Ghtml/library/logging.handlers.htmlnu�[���PK
%�\}�>������Hhtml/library/logging.htmlnu�[���PK
%�\y‹GP[P[}fJhtml/library/mac.htmlnu�[���PK
%�\���??�Jhtml/library/macos.htmlnu�[���PK
%�\���*77ZKhtml/library/macosa.htmlnu�[���PK
%�\�/BB�8Khtml/library/macostools.htmlnu�[���PK
%�\{FQ�� � �zKhtml/library/macpath.htmlnu�[���PK
%�\�W�pq�q���Khtml/library/mailbox.htmlnu�[���PK
%�\K��4747�8Nhtml/library/mailcap.htmlnu�[���PK
%�\_�9�M�M2pNhtml/library/markup.htmlnu�[���PK
%�\GU3�LL�Nhtml/library/marshal.htmlnu�[���PK
%�\c(eM��Y
Ohtml/library/math.htmlnu�[���PK
%�\x/;;��Ohtml/library/md5.htmlnu�[���PK
%�\�Q�;^;^��Ohtml/library/mhlib.htmlnu�[���PK
%�\�te2�R�RhPPhtml/library/mimetools.htmlnu�[���PK
%�\K�x+�w�w��Phtml/library/mimetypes.htmlnu�[���PK
%�\]~�y�>�>~Qhtml/library/mimewriter.htmlnu�[���PK
%�\����;�;�ZQhtml/library/mimify.htmlnu�[���PK
%�\�,�|5353��Qhtml/library/miniaeframe.htmlnu�[���PK
%�\�A/�DD�Qhtml/library/misc.htmlnu�[���PK
%�\Lz�>b%b%��Qhtml/library/mm.htmlnu�[���PK
%�\!�^�pxpxARhtml/library/mmap.htmlnu�[���PK
%�\1<�M�F�F��Rhtml/library/modulefinder.htmlnu�[���PK
%�\�h�Z9#9#��Rhtml/library/modules.htmlnu�[���PK
%�\��������w�Rhtml/library/msilib.htmlnu�[���PK
%�\����R�R��Shtml/library/msvcrt.htmlnu�[���PK
%�\�:b�f�f�$Thtml/library/multifile.htmlnu�[���PK
%�\��^�GSGS!ϋThtml/library/multiprocessing.htmlnu�[���PK
%�\ȫ�<s/s/g�Zhtml/library/mutex.htmlnu�[���PK
%�\\�;�G�G![html/library/netdata.htmlnu�[���PK
%�\�yM�6�65W[html/library/netrc.htmlnu�[���PK
%�\�93y3y3A�[html/library/new.htmlnu�[���PK
%�\�7���,�,��[html/library/nis.htmlnu�[���PK
%�\w��}y�y�2�[html/library/nntplib.htmlnu�[���PK
%�\�h�?�����\html/library/numbers.htmlnu�[���PK
%�\Ji�B�7�7�@]html/library/numeric.htmlnu�[���PK
%�\��x�m�my]html/library/operator.htmlnu�[���PK
%�\�Gi�����^html/library/optparse.htmlnu�[���PK
%�\O�C�C�]�bhtml/library/os.htmlnu�[���PK
%�\��>�����bfhtml/library/os.path.htmlnu�[���PK
%�\6����ghtml/library/ossaudiodev.htmlnu�[���PK
%�\�ҭ�$�$�ghtml/library/othergui.htmlnu�[���PK
%�\���>�>�#�ghtml/library/parser.htmlnu�[���PK
%�\���3˖˖��hhtml/library/pdb.htmlnu�[���PK
%�\��o�<=<=�!ihtml/library/persistence.htmlnu�[���PK
%�\�$z0t�t�B_ihtml/library/pickle.htmlnu�[���PK
%�\�1���,�,�khtml/library/pickletools.htmlnu�[���PK
%�\�Z%P�L�L9khtml/library/pipes.htmlnu�[���PK
%�\�����j�jJ�khtml/library/pkgutil.htmlnu�[���PK
%�\6]�o{o{z�khtml/library/platform.htmlnu�[���PK
%�\;3�"�G�G3mlhtml/library/plistlib.htmlnu�[���PK
%�\B_7k�k�k%�lhtml/library/popen2.htmlnu�[���PK
%�\�ar�__>!mhtml/library/poplib.htmlnu�[���PK
%�\���@�@��mhtml/library/posix.htmlnu�[���PK
%�\�� 2�S�S��mhtml/library/posixfile.htmlnu�[���PK
%�\�2c�}�}�nhtml/library/pprint.htmlnu�[���PK
%�\x�|TT��nhtml/library/profile.htmlnu�[���PK
%�\`jw�'�'I�ohtml/library/pty.htmlnu�[���PK
%�\�
gxd0d0a�ohtml/library/pwd.htmlnu�[���PK
%�\�
�ݜ.�.
	phtml/library/py_compile.htmlnu�[���PK
%�\���'�=�=�7phtml/library/pyclbr.htmlnu�[���PK
%�\�Ka�R5R5�uphtml/library/pydoc.htmlnu�[���PK
%�\6�qK�;�;��phtml/library/pyexpat.htmlnu�[���PK
%�\8Nb�6262��qhtml/library/python.htmlnu�[���PK
%�\W����h�hTrhtml/library/queue.htmlnu�[���PK
%�\&q,�1�1��rhtml/library/quopri.htmlnu�[���PK
%�\�N�r����rhtml/library/random.htmlnu�[���PK
%�\
4ΰQaQa�\shtml/library/re.htmlnu�[���PK
%�\e�_��M�uhtml/library/readline.htmlnu�[���PK
%�\�8�sUU�Pvhtml/library/repr.htmlnu�[���PK
%�\�`1~n~n��vhtml/library/resource.htmlnu�[���PK
%�\��uN0N0�whtml/library/restricted.htmlnu�[���PK
%�\{<lQv�v�XEwhtml/library/rexec.htmlnu�[���PK
%�\bg;�H�H��whtml/library/rfc822.htmlnu�[���PK
%�\���|8|8��xhtml/library/rlcompleter.htmlnu�[���PK
%�\&$[4[4n�xhtml/library/robotparser.htmlnu�[���PK
%�\8v�U�Uyhtml/library/runpy.htmlnu�[���PK
%�\=[�+�M�M]yhtml/library/sched.htmlnu�[���PK
%�\ƭ��&&�yhtml/library/scrolledtext.htmlnu�[���PK
%�\����:�:�=�yhtml/library/select.htmlnu�[���PK
%�\!XO�לל�}zhtml/library/sets.htmlnu�[���PK
%�\Ӻ6�(�(�{html/library/sgi.htmlnu�[���PK
%�\{��Ġ����C{html/library/sgmllib.htmlnu�[���PK
%�\B0�33��{html/library/sha.htmlnu�[���PK
%�\���uu�{html/library/shelve.htmlnu�[���PK
%�\�9�وو#s|html/library/shlex.htmlnu�[���PK
%�\�ĭ�����C�|html/library/shutil.htmlnu�[���PK
%�\םr����}html/library/signal.htmlnu�[���PK
%�\���OO"H3~html/library/simplehttpserver.htmlnu�[���PK
%�\]��$����$�~html/library/simplexmlrpcserver.htmlnu�[���PK
%�\TL`�iihtml/library/site.htmlnu�[���PK
%�\�u[\55\�html/library/smtpd.htmlnu�[���PK
%�\M6��ηη��html/library/smtplib.htmlnu�[���PK
%�\��*��*�*�m�html/library/sndhdr.htmlnu�[���PK
%�\��ƾ�����html/library/socket.htmlnu�[���PK
%�\!���*�*`�html/library/socketserver.htmlnu�[���PK
%�\��=uX@X@芃html/library/someos.htmlnu�[���PK
%�\�”�+�+�˃html/library/spwd.htmlnu�[���PK
%�\�	>9�I�Ii��html/library/sqlite3.htmlnu�[���PK
%�\�~���A�html/library/ssl.htmlnu�[���PK
%�\��j%�%��X�html/library/stat.htmlnu�[���PK
%�\��a�>,>,5�html/library/statvfs.htmlnu�[���PK
%�\��KS������html/library/stdtypes.htmlnu�[���PK
%�\��Y�������html/library/string.htmlnu�[���PK
%�\��	q]N]N�o�html/library/stringio.htmlnu�[���PK
%�\уAHAEAE0��html/library/stringprep.htmlnu�[���PK
%�\D��!>!>��html/library/strings.htmlnu�[���PK
%�\'��`�`�'B�html/library/struct.htmlnu�[���PK
%�\�X6o�o���html/library/subprocess.htmlnu�[���PK
%�\:l�UU���html/library/sun.htmlnu�[���PK
%�\g�ih;u;u$��html/library/sunau.htmlnu�[���PK
%�\�s�g$K$K�3�html/library/sunaudio.htmlnu�[���PK
%�\�&�����html/library/symbol.htmlnu�[���PK
%�\0i�ee(��html/library/symtable.htmlnu�[���PK
%�\�܂������html/library/sys.htmlnu�[���PK
%�\'���f�fZ��html/library/sysconfig.htmlnu�[���PK
%�\E��oMM`�html/library/syslog.htmlnu�[���PK
%�\&9�$�,�,�j�html/library/tabnanny.htmlnu�[���PK
%�\e��ۘZ�Z���html/library/tarfile.htmlnu�[���PK
%�\��E�l�lm�html/library/telnetlib.htmlnu�[���PK
%�\���|�|>_�html/library/tempfile.htmlnu�[���PK
%�\�,�C�C'ܙhtml/library/termios.htmlnu�[���PK
%�\��~����
 �html/library/test.htmlnu�[���PK
%�\W$i�u�u��html/library/textwrap.htmlnu�[���PK
%�\F٠�S�Su�html/library/thread.htmlnu�[���PK
%�\�C�RRPɛhtml/library/threading.htmlnu�[���PK
%�\E��6�6��html/library/time.htmlnu�[���PK
%�\���Q�Q���html/library/timeit.htmlnu�[���PK
%�\��`�����/��html/library/tix.htmlnu�[���PK
%�\�np�g�g
z�html/library/tk.htmlnu�[���PK
%�\�^�\I\I�html/library/tkinter.htmlnu�[���PK
%�\��ZRR�+�html/library/token.htmlnu�[���PK
%�\�{�PP	~�html/library/tokenize.htmlnu�[���PK
%�\�v�o�o�Ρhtml/library/trace.htmlnu�[���PK
%�\lŨ;ğğ?�html/library/traceback.htmlnu�[���PK
%�\�����$ߢhtml/library/ttk.htmlnu�[���PK
%�\j�&&&L��html/library/tty.htmlnu�[���PK
%�\#r�S�S����html/library/turtle.htmlnu�[���PK
%�\oZ�t�tE2�html/library/types.htmlnu�[���PK
%�\6�!h`h`��html/library/undoc.htmlnu�[���PK
%�\Ր�A�N�N��html/library/unicodedata.htmlnu�[���PK
%�\1^	�n�n�V�html/library/unittest.htmlnu�[���PK
%�\1�F��+�+2Ƭhtml/library/unix.htmlnu�[���PK
%�\DB�t�
�
O�html/library/urllib.htmlnu�[���PK
%�\�����A��html/library/urllib2.htmlnu�[���PK
%�\r�]ҩҩn��html/library/urlparse.htmlnu�[���PK
%�\n�m5�1�1�b�html/library/user.htmlnu�[���PK
%�\�P��E}E}s��html/library/userdict.htmlnu�[���PK
%�\%��".".�html/library/uu.htmlnu�[���PK
%�\?zZ7�u�uh@�html/library/uuid.htmlnu�[���PK
%�\����g��html/library/warnings.htmlnu�[���PK
%�\	.�>a>a�}�html/library/wave.htmlnu�[���PK
%�\Ӄ�~����;߲html/library/weakref.htmlnu�[���PK
%�\%�i��g�gw�html/library/webbrowser.htmlnu�[���PK
%�\=X��%%-߳html/library/whichdb.htmlnu�[���PK
%�\t�Y&Y&��html/library/windows.htmlnu�[���PK
%�\X\T�O�O3+�html/library/winsound.htmlnu�[���PK
%�\D��@Y@Yo{�html/library/wsgiref.htmlnu�[���PK
%�\�
]�����Եhtml/library/xdrlib.htmlnu�[���PK
%�\�g�U~U~:V�html/library/xml.dom.htmlnu�[���PK
%�\*=ިި!�Էhtml/library/xml.dom.minidom.htmlnu�[���PK
%�\�]�66!~�html/library/xml.dom.pulldom.htmlnu�[���PK
%�\?8x����'c��html/library/xml.etree.elementtree.htmlnu�[���PK
%�\1:WFWFvi�html/library/xml.htmlnu�[���PK
%�\6������!��html/library/xml.sax.handler.htmlnu�[���PK
%�\%{Xe�[�[�S�html/library/xml.sax.htmlnu�[���PK
%�\�
 �� 㯻html/library/xml.sax.reader.htmlnu�[���PK
%�\��P�>�>5_�html/library/xml.sax.utils.htmlnu�[���PK
%�\��UGG[��html/library/xmlrpclib.htmlnu�[���PK
%�\��-���html/library/zipfile.htmlnu�[���PK
%�\n5v\�X�XI��html/library/zipimport.htmlnu�[���PK
%�\¸C��y�y���html/library/zlib.htmlnu�[���PK
%�\q�Cs�s��s�html/library/2to3.htmlnu�[���PK
%�\�O�66"�\�html/reference/compound_stmts.htmlnu�[���PK
%�\ŝg�����
^�html/reference/datamodel.htmlnu�[���PK
%�\,�s�kkkk"N0�html/reference/executionmodel.htmlnu�[���PK
%�\��p�P�P��html/reference/expressions.htmlnu�[���PK
%�\�6P.�.���html/reference/grammar.htmlnu�[���PK
%�\-*sN@N@}}�html/reference/index.htmlnu�[���PK
%�\_ܶs?9?9 ��html/reference/introduction.htmlnu�[���PK
%�\��Y��$���html/reference/lexical_analysis.htmlnu�[���PK
%�\�aITψψ ��html/reference/simple_stmts.htmlnu�[���PK
%�\�{^��4�4'/z�html/reference/toplevel_components.htmlnu�[���PK
%�\��^B^BR��html/tutorial/appendix.htmlnu�[���PK
%�\�~X�)�)���html/tutorial/appetite.htmlnu�[���PK
%�\��Ġg�g��html/tutorial/classes.htmlnu�[���PK
%�\�.��$�$��html/tutorial/controlflow.htmlnu�[���PK
%�\�j1�\�\!'��html/tutorial/datastructures.htmlnu�[���PK
%�\�/Ѷ����html/tutorial/errors.htmlnu�[���PK
%�\H�elWlW ��html/tutorial/floatingpoint.htmlnu�[���PK
%�\C��d�d��html/tutorial/index.htmlnu�[���PK
%�\I�����ʀ�html/tutorial/inputoutput.htmlnu�[���PK
%�\��3OO�S�html/tutorial/interactive.htmlnu�[���PK
%�\��/)�H�HR��html/tutorial/interpreter.htmlnu�[���PK
%�\��}]]s��html/tutorial/introduction.htmlnu�[���PK
%�\!�q,������html/tutorial/modules.htmlnu�[���PK
%�\�������*��html/tutorial/stdlib.htmlnu�[���PK
%�\�]��+��html/tutorial/stdlib2.htmlnu�[���PK
%�\�V��'�'ul�html/tutorial/whatnow.htmlnu�[���PK
%�\�����html/using/cmdline.htmlnu�[���PK
%�\����,�,��html/using/index.htmlnu�[���PK
%�\ۙ�C�M�M��html/using/mac.htmlnu�[���PK
%�\��3C3C��html/using/unix.htmlnu�[���PK
%�\+̒�ptptUX�html/using/windows.htmlnu�[���PK
%�\%)������html/whatsnew/2.0.htmlnu�[���PK
%�\l�V�>�>���html/whatsnew/2.1.htmlnu�[���PK
%�\�p.�l(l(��html/whatsnew/2.2.htmlnu�[���PK
%�\;J�>�>��@�html/whatsnew/2.3.htmlnu�[���PK
%�\N��������html/whatsnew/2.4.htmlnu�[���PK
%�\ŎŤ���
l�html/whatsnew/2.5.htmlnu�[���PK
%�\��(�(��P�html/whatsnew/2.6.htmlnu�[���PK
%�\�^�e��html/whatsnew/2.7.htmlnu�[���PK
%�\�T8ee*��html/whatsnew/index.htmlnu�[���PK
%�\��011�M�html/about.htmlnu�[���PK
%�\6w��,�,�k�html/bugs.htmlnu�[���PK
%�\��9�����html/contents.htmlnu�[���PK
%�\�3VKë�html/copyright.htmlnu�[���PK
%�\4�����html/download.htmlnu�[���PK
%�\�y������html/genindex-A.htmlnu�[���PK
%�\w�/x������html/genindex-B.htmlnu�[���PK
%�\T��miZiZ/�html/genindex-C.htmlnu�[���PK
%�\��{�������html/genindex-D.htmlnu�[���PK
%�\�^�N N �^�html/genindex-E.htmlnu�[���PK
%�\V�:�s�s��html/genindex-F.htmlnu�[���PK
%�\]hZc{{6D�html/genindex-G.htmlnu�[���PK
%�\��V_�|�|�Rhtml/genindex-H.htmlnu�[���PK
%�\�o>�>��html/genindex-I.htmlnu�[���PK
%�\�s�{����html/genindex-J.htmlnu�[���PK
%�\-N�Z(Z(��html/genindex-K.htmlnu�[���PK
%�\�o�9�9�chtml/genindex-L.htmlnu�[���PK
%�\�	�N�����html/genindex-M.htmlnu�[���PK
%�\�Z�[s[s�hhtml/genindex-N.htmlnu�[���PK
%�\nA��������html/genindex-O.htmlnu�[���PK
%�\������phtml/genindex-P.htmlnu�[���PK
%�\�H��$�$�'html/genindex-Q.htmlnu�[���PK
%�\�ޫ
�Lhtml/genindex-R.htmlnu�[���PK
%�\�C�Iihtml/search.htmlnu�[���PK
%�\Ϸf%u
%u
]|HISTORYnu�[���PK
%�\@^KP�P���NEWSnu�[���PK
%�\~Fm�P	P	=�READMEnu�[���PK
%�\��p4�4�
Écheatsheetnu�[���PKz1(